stored i (List.mem_finRange i),fun x hx => frame x (fun i _ => by have := i.isLt; omega)⟩
+
+end CompressorRecords.ShrinkResidentsPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentInterval.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentInterval.lean
new file mode 100644
index 0000000000..c136272df5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentInterval.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.CompressorShrinkBranchResident
+import OAI.Computability.VPVNP.CompressorShrinkScoreOperands
+import OAI.Computability.VPVNP.CompressorBlockABSliceFootprint
+
+/-! # Inputs retained in table zero across the hidden and map publications
+
+Publishing six resident-directory heads changes cells in the old level header.
+Every input of the two interval calendars is nevertheless in table zero,
+from the sorted demand columns through the selected child-directory rows.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkOutput
+
+open Compression BurstRAM ShrinkBlockInputs ShrinkSliceSweep TermScores SlotLevel ShrinkSlots
+open scoped Classical Fin.CommRing
+open private columns_after before_width from OAI.Computability.VPVNP.CompressorBlockABSliceFootprint
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+variable (T : IncidenceDirectory w) (start : ℕ)
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "ids" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w
+local notation "keepEnd" => SelectedFinish.stop X term (10 : Word w)
+local notation "role" => SelectedArena.roleBase X term (10 : Word w)
+local notation "wb" => ShrinkInput.widthBase X start
+local notation "z" => ShrinkInput.plan X start
+local notation "t" => ShrinkInput.thickBank X T start
+local notation "cd" => ShrinkInput.cdBank X T start
+local notation "ab" => ShrinkInput.piecesBank X T start
+
+set_option maxHeartbeats 1400000 in
+theorem Resident.above {width : ℕ} {mem out : Memory w}
+ (h : Resident B i X sel term 10 ids T start width mem)
+ (room : ShrinkInput.termEnd X start 10 < 2^w) (selected : keepEnd ≤ 2^w)
+ (same : ∀ x, start ≤ x → out x = mem x) :
+ Resident B i X sel term 10 ids T start width out := by
+ have termLow := ScorePackets.start_le_term i X start room
+ have hwidth := before_width i X start
+ have col := columns_after i X T start room
+ have q := (z).values T (ShrinkInput.placementBank X T start) Fintype.card_pos
+ (show (z).stop < 2^w by change wb < 2^w; change wb+_+_+_+_ < 2^w at room; omega)
+ let block := (z).B*(ShrinkRankSpace.Shape.collectBank z w 4).val
+ have blockEq : block = (z).B*(z).Q := by dsimp [block]; rw [q.stride]
+ have inputFit : wb+6*((z).B*(z).Q)+2*(z).B < 2^w := by
+ change wb+6*((z).B*(z).Q)+2*(z).B+_+_ < 2^w at room; omega
+ have cd₂ : (cd 2).val = wb+block := by
+ change (wb%(2^w)+block)%(2^w) = _
+ rw [Nat.mod_eq_of_lt (show wb<2^w by omega),Nat.mod_eq_of_lt (by omega)]
+ have cd₃ : (cd 3).val = wb+2*block+block := by
+ change (wb+2*block+block)%(2^w) = _
+ exact Nat.mod_eq_of_lt (by omega)
+ have keep (p i j : ℕ) (hp : start ≤ p) : (out (p+i+j)).val = (mem (p+i+j)).val :=
+ congrArg Fin.val (same _ (by omega))
+ have rb := ShrinkInput.range_bounds X start
+ have gathered : ShrinkInput.rankBase X start ≤ (z).gathered := by
+ change ShrinkInput.rankBase X start ≤ ShrinkInput.rankBase X start+_+_+_; omega
+ have aEnd : (z).gathered+(z).B*(z).Q ≤ wb := by
+ change (z).gathered+(z).B*(z).Q ≤ (z).gathered+((2*(z).B)*(z).Q)+(z).A
+ rw [Nat.mul_assoc,two_mul]; omega
+ have absRoom : (z).gathered+(z).B*(z).Q < 2^w := by omega
+ have absLow : start ≤ (ids).val := by change start ≤ (_:ℕ)%(2^w); rw [Nat.mod_eq_of_lt absRoom]; omega
+ have hrole : start ≤ role := by unfold SelectedArena.roleBase SelectedArena.placementBase SelectedArena.origin; omega
+ have hcell : start ≤ SelectedArena.origin X term (10 : Word w)+2 := by unfold SelectedArena.origin; omega
+ refine ⟨⟨fun b j => (keep _ _ _ col.1).trans (h.demand.thickWidths b j),
+ fun b j => (keep _ _ _ (by omega : start ≤ (cd 2).val)).trans (h.demand.cdWidths b j),
+ fun b j => (keep _ _ _ col.2.1).trans (h.demand.thickStarts b j),
+ fun b j => (keep _ _ _ (by omega : start ≤ (cd 3).val)).trans (h.demand.cdStarts b j),
+ ⟨fun b j => (keep _ _ _ col.2.2.1).trans (h.demand.ab.widths b j),
+ fun b j => (keep _ _ _ col.2.2.2).trans (h.demand.ab.starts b j)⟩⟩,
+ fun j => (congrArg Fin.val (same _ (by omega))).trans (h.directory j),?_,
+ ⟨fun arc => (congrArg Fin.val (same _ (by omega))).trans (h.roles.cd arc),
+ fun arc r => (congrArg Fin.val (same _ (by omega))).trans (h.roles.packed arc r)⟩,
+ (same _ hcell).trans h.chosen,?_⟩
+ · apply terms_after B.shrink X term (10 : Word w).val _ (levelShape (b := b i) X).subdivisions sel mem out h.terms
+ intro j k _ head
+ have rowFit := (ShrinkInput.termLayout X T start 10 room).2.2.2
+ have hj : j.val ≤ ShrinkTermInputs.motifCount X := by
+ rw [← ShrinkTermRecipe.count_card X]; exact j.isLt.le
+ have le : j.val*(10 : Word w).val ≤ ShrinkTermInputs.motifCount X*10 :=
+ Nat.mul_le_mul hj (Nat.mod_le 10 (2^w))
+ have exactHead : head.val = (term).val+j.val*(10 : Word w).val := Nat.mod_eq_of_lt (by omega)
+ exact same _ (by omega)
+ · have hl : start ≤ SelectedFinish.countStart X term 10 := by
+ unfold SelectedFinish.countStart SelectedArena.endAddr; omega
+ have hc : (SelectedFinish.counts X term 10).val = SelectedFinish.countStart X term 10 := by
+ apply Nat.mod_eq_of_lt
+ have positive : 0 < ShrinkPreimages.newCount X := Nat.mul_pos Fintype.card_pos (Nat.mul_pos (Nat.two_pow_pos _) (Nat.two_pow_pos _))
+ unfold SelectedFinish.stop SelectedFinish.rowStart at selected; omega
+ have hr : (SelectedFinish.rows X term 10).val = SelectedFinish.rowStart X term 10 := by
+ apply Nat.mod_eq_of_lt
+ have positive : 0 < ShrinkPreimages.oldCount X := Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos _)
+ unfold SelectedFinish.stop at selected; omega
+ have rowLow : start ≤ (SelectedFinish.rows X term 10).val := by rw [hr]; unfold SelectedFinish.rowStart; omega
+ exact ⟨fun v => (congrArg Fin.val (same _ (by omega))).trans (h.preimages.count v),
+ fun v j => (congrArg Fin.val (same _ (by omega))).trans (h.preimages.child v j)⟩
+
+/-- Intervening publications may update the header while preserving every
+earlier field within the physical scratch table. -/
+theorem resident_of_branch_interval (selectors : Word w) (cap : ℕ) {m : Memory w}
+ (p : ShrinkBranch.Prefix X T start cap m)
+ (v : ShrinkBranch.Selected B X T start 10 selectors cap m p sel)
+ (fit : ShrinkBranch.PrefixFits B X T start 10 cap) (room : ShrinkInput.termEnd X start 10 < 2^w)
+ (selected : keepEnd ≤ 2^w) (width : ℕ) (input : Memory w)
+ (frame : ∀ x, start ≤ x → x < keepEnd → input x = v.beforeOutput x) :
+ Resident B i X sel term 10 ids T start width input := by
+ let staged : Memory w := fun x => if x < start then v.beforeOutput x else input x
+ have keep (x : ℕ) (hx : x < keepEnd) : staged x = v.beforeOutput x := by
+ by_cases early : x < start
+ · exact ite_eq_left early
+ · exact (ite_eq_right early).trans (frame x (Nat.le_of_not_gt early) hx)
+ have initial := resident_of_branch B i X sel T start 10 selectors cap p v fit width staged keep
+ exact initial.above B i X sel T start room selected (fun x hx => (ite_eq_right (Nat.not_lt.mpr hx)).symm)
+
+end CompressorRecords.ShrinkOutput
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentLayout.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentLayout.lean
new file mode 100644
index 0000000000..ddffcc219f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentLayout.lean
@@ -0,0 +1,174 @@
+import OAI.Computability.VPVNP.CompressorRecordsShrinkHistory
+import OAI.Computability.VPVNP.CompressorShrinkSelectedPlan
+
+/-!
+# Workspace for the shrinking history's two resident directories
+
+The absorbed-field records start after the chosen placement's child rows.
+The map records follow them. Each stores one owner word and one ordered
+row word per occurrence, and one counter per packed site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkResidentLayout
+
+open BurstRAM Compression Compression.PackingData PrimedStackRAM
+open PairSimulation.LocalHistory ShrinkHistoryRows
+open scoped Fin.CommRing Classical
+
+/-- Occurrences per motif in a resident scan, four for absorbed fields and six for party maps. -/
+def radix (maps : Bool) := if maps then 6 else 4
+
+/-- Number of occurrence slots reserved per packed site in the selected field or map directory,
+accounting for degree, pieces and occurrences per motif. -/
+def rowCapacity (a : ℕ) (maps : Bool) := radix maps*(2^a*pieceCount (2^a) (Shrink.colors a))
+
+/-- Dimensions and starting address for two consecutive resident directories, each with an
+owner column, per-site counts and ordered preimage rows. -/
+structure Layout where
+ /-- Number of packed output sites, each with its own count and preimage row in both
+ directories. -/
+ sites : ℕ
+ /-- Number of shrinking motifs whose field and party-map occurrences must be assigned to
+ owners. -/
+ motifs : ℕ
+ /-- Base of the hidden-field owner column, the first address of the combined resident
+ workspace. -/
+ first : ℕ
+
+namespace Layout
+
+/-- Number of occurrences in the selected directory, the motif count times four hidden fields
+or six party maps. -/
+def size (L : Layout) (maps : Bool) := L.motifs*radix maps
+
+/-- Start of the selected owner column. The hidden-field column comes first and the map column
+follows the complete hidden-field directory. -/
+def owner (L : Layout) (maps : Bool) :=
+ if maps then L.first + L.size false + L.sites + L.size false else L.first
+
+/-- Start of the per-site counts immediately following the selected occurrence-owner column. -/
+def counts (L : Layout) (maps : Bool) := L.owner maps + L.size maps
+
+/-- Start of the selected preimage rows, following one count word per packed site. -/
+def rows (L : Layout) (maps : Bool) := L.counts maps + L.sites
+
+/-- First free address following the party-map preimage rows and hence both resident
+directories. -/
+def endAddr (L : Layout) := L.rows true + L.size true
+
+/-- Six public collector operands in order, occurrence count, owner base, site count, count
+base, row capacity and row base. -/
+def params (L : Layout) (a : ℕ) (maps : Bool) (w : ℕ) : Fin 6 → Word w :=
+ ![(L.size maps : Word w),(L.owner maps : Word w),(L.sites : Word w),
+ (L.counts maps : Word w),(rowCapacity a maps : Word w),(L.rows maps : Word w)]
+
+theorem ranges (L : Layout) (maps : Bool) : L.first ≤ L.owner maps ∧
+ L.owner maps + L.size maps = L.counts maps ∧ L.counts maps+L.sites = L.rows maps ∧
+ L.rows maps+L.size maps ≤ L.endAddr := by
+ cases maps <;> dsimp [endAddr,rows,counts,owner] <;> omega
+
+end Layout
+
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+
+/-- Instantiate the resident workspace at `first` using the actual number of packed sites and
+the motif order of the shrinking state. -/
+def layout (first : ℕ) : Layout := ⟨ShrinkPreimages.newCount X,(shrinkMotifOrder X).length,first⟩
+
+theorem size_eq_rows (first : ℕ) (maps : Bool) :
+ (layout X first).size maps = (layout X first).sites * rowCapacity a maps := by
+ have h := Fintype.card_congr (ShrinkMotifOrder.stateNumber X)
+ rw [Fintype.card_fin] at h
+ change Fintype.card X.packingData.Motif * radix maps = ShrinkPreimages.newCount X * _
+ rw [h]
+ unfold rowCapacity
+ ring
+
+/-- No index is truncated when the next free address fits the word. -/
+theorem frame (first : ℕ) (maps : Bool) (fit : (layout X first).endAddr < 2^w) :
+ let L := layout X first
+ let p := L.params a maps w
+ RowRegions p ∧ (p 0).val = L.size maps ∧ (p 1).val = L.owner maps ∧
+ (p 2).val = L.sites ∧ (p 3).val = L.counts maps ∧ (p 4).val = rowCapacity a maps ∧
+ (p 5).val = L.rows maps := by
+ intro L p
+ change L.endAddr < 2^w at fit
+ obtain ⟨_,hc,hr,hend⟩ := L.ranges maps
+ have dim := size_eq_rows X first maps
+ change L.size maps = L.sites*rowCapacity a maps at dim
+ have hpos : 0 < L.sites := Nat.mul_pos Fintype.card_pos (Nat.mul_pos (Nat.two_pow_pos _) (Nat.two_pow_pos _))
+ have hcap := Nat.le_mul_of_pos_left (rowCapacity a maps) hpos
+ have ok0 : (p 0).val = L.size maps := Nat.mod_eq_of_lt (by omega)
+ have ok1 : (p 1).val = L.owner maps := Nat.mod_eq_of_lt (by omega)
+ have ok2 : (p 2).val = L.sites := Nat.mod_eq_of_lt (by omega)
+ have ok3 : (p 3).val = L.counts maps := Nat.mod_eq_of_lt (by omega)
+ have ok4 : (p 4).val = rowCapacity a maps := Nat.mod_eq_of_lt (by omega)
+ have ok5 : (p 5).val = L.rows maps := Nat.mod_eq_of_lt (by omega)
+ exact ⟨⟨by rw [ok1,ok0,ok3,hc],by rw [ok3,ok2,ok5,hr],
+ by rw [ok5,ok2,ok4,←dim]; exact hend.trans fit.le⟩,ok0,ok1,ok2,ok3,ok4,ok5⟩
+
+theorem hidden_id (m : X.packingData.Motif) (t : Fin 4) :
+ ((hiddenOrder X).entries.symm (m,t)).val = (ShrinkMotifOrder.stateNumber X m).val * 4 + t.val := by
+ change t.val + 4*(ShrinkMotifOrder.stateNumber X m).val = _
+ omega
+
+theorem map_id (m : X.packingData.Motif) (t : Fin 6) :
+ ((mapOrder X).entries.symm (m,t)).val = (ShrinkMotifOrder.stateNumber X m).val * 6 + t.val := by
+ change t.val + 6*(ShrinkMotifOrder.stateNumber X m).val = _
+ omega
+
+theorem hidden_build (first : ℕ) (fit : (layout X first).endAddr < 2^w) (side : Bool)
+ (mem : Memory w) :
+ let L := layout X first
+ let p := L.params a false w
+ let old := hiddenOrder X
+ let next := packedOrder X
+ let place := X.packingData.shrinkInternalOwner side
+ (∀ i : Word w, i p 3)).program 8 (some 0) mem
+ (List.replicate L.sites []) = some cs ∧
+ runSegment ((template collectPreimage 3).instantiate w p).program 23 (some 0) mid
+ (List.replicate (L.size false) []) = some rs ∧
+ Directory old next place p out ∧ cs.length=L.sites ∧ rs.length=L.size false ∧
+ (∀ r ∈ cs, r.probes=1 ∧ r.events.length+1=8) ∧ (∀ r ∈ rs, r.probes=4 ∧ r.events.length+1=23) ∧
+ (∀ j, OutsidePreimageWrites p j → out j = mem j) := by
+ intro L p old next place owners
+ obtain ⟨regions,ho,_,hn,_,hc,_⟩ := frame X first false fit
+ exact build old next place p regions ho hn (fun v => (hidden_count X side v).le.trans hc.symm.le) mem owners
+
+theorem map_build (first : ℕ) (fit : (layout X first).endAddr < 2^w) (side : Bool)
+ (mem : Memory w) :
+ let L := layout X first
+ let p := L.params a true w
+ let old := mapOrder X
+ let next := packedOrder X
+ let place := fun (e : X.packingData.Motif × Fin 6) => X.packingData.shrinkPartySite side e.1 e.2
+ (∀ i : Word w, i
p 3)).program 8 (some 0) mem
+ (List.replicate L.sites []) = some cs ∧
+ runSegment ((template collectPreimage 3).instantiate w p).program 23 (some 0) mid
+ (List.replicate (L.size true) []) = some rs ∧
+ Directory old next place p out ∧ cs.length=L.sites ∧ rs.length=L.size true ∧
+ (∀ r ∈ cs, r.probes=1 ∧ r.events.length+1=8) ∧ (∀ r ∈ rs, r.probes=4 ∧ r.events.length+1=23) ∧
+ (∀ j, OutsidePreimageWrites p j → out j = mem j) := by
+ intro L p old next place owners
+ obtain ⟨regions,ho,_,hn,_,hc,_⟩ := frame X first true fit
+ exact build old next place p regions ho hn (fun v => (map_count X side v).le.trans hc.symm.le) mem owners
+
+end CompressorRecords.ShrinkResidentLayout
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentOwners.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentOwners.lean
new file mode 100644
index 0000000000..762e15360d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentOwners.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner
+import OAI.Computability.VPVNP.CompressorSlotOwnerAgreement
+import OAI.Computability.VPVNP.ShrinkRoles
+
+/-!
+# Native generation of the shrinking resident owner columns
+
+A history cursor combines its motif number with either a party ordinal or an
+absorbed edge type. The worker uses the sorted absolute-CD column and the
+selected layout's A/B/D role words to write the owner at that cursor. It needs
+two memory reads and one write.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ResidentOwners
+
+open Compression Compression.ShrinkMotif BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open PhaseRecipe BlockPlanner
+open scoped Fin.CommRing
+
+/-- The six map parties or four absorbed edge types stored per motif. -/
+def arity (maps : Bool) := if maps then 6 else 4
+
+variable {w : ℕ}
+
+private def four : Word w := 2*2
+private def radix (maps : Bool) : Word w := (if maps then 3 else 2)*2
+
+private theorem four_eq : (four : Word w) = 4 := by unfold four; norm_num
+private theorem radix_eq (maps : Bool) : (radix maps : Word w) = (arity maps : Word w) := by
+ cases maps <;> norm_num [radix,arity]
+
+private def mux (flag lo hi : Word w) := lo + flag*(hi-lo)
+
+private def chooseReg (flag lo hi dst : Fin 20) : List (Op 20 4) :=
+ [.binary .sub 15 hi lo,.binary .mul 15 flag 15,.binary .add dst lo 15]
+
+/-- Registers 11, 12 and 13 carry the three bits of the within-motif tag.
+Register 8 carries the layout, register 9 is two, and register 14 is the
+resulting role offset. -/
+private def roleOps (maps : Bool) : List (Op 20 4) := if maps then
+ chooseReg 11 8 9 16 ++ chooseReg 12 11 16 14 ++
+ [.binary .mul 16 9 8,.binary .sub 17 9 8] ++ chooseReg 11 16 17 18 ++ chooseReg 13 14 18 14
+ else [.binary .mul 16 11 12] ++ chooseReg 16 8 9 14
+
+/-- Native owner-scan instructions for a hidden field or party map. Decode the occurrence, read
+its absolute CD identifier and role word, and write the packed owner. -/
+def code (maps : Bool) : List (Op 20 4) :=
+ [.stateWord 0,.constant 9 2,.binary .mul 10 9 9,
+ .constant 3 (if maps then 3 else 2),.binary .mul 3 3 9,.binary .div 1 0 3,.binary .mod 2 0 3,
+ .publicWord 8 2,
+ .binary .mod 11 2 9,.binary .div 12 2 9,.binary .mod 12 12 9,.binary .div 13 2 10] ++
+ roleOps maps ++
+ [.publicWord 4 0,.binary .add 4 4 1,.read 5 4,.binary .mul 6 10 5,.publicWord 17 1,
+ .binary .add 6 17 6,.binary .add 6 6 14,.read 7 6,.publicWord 18 3,.binary .add 18 18 0,
+ .write 18 7,.constant 19 1,.binary .add 0 0 19]
+
+/-- Register the resident owner scan as a scheduler pass that returns its advanced occurrence
+cursor. -/
+def worker (maps : Bool) : Schedule.Pass := ⟨_,_,_,template (code maps) 0⟩
+
+/-- Schedule the owner scan from zero to the occurrence count with pointers to absolute CD
+identifiers, role records and the owner output, plus the selected layout. -/
+def visit (maps : Bool) (count absoluteCD roleBase layout ownerBase : Expr) : Visit :=
+ ⟨worker maps,.lit 0,count,![absoluteCD,roleBase,layout,ownerBase]⟩
+
+/-- Compute the role-word offset within a four-word old-arc record from the selected layout and
+the local field or party-map tag. -/
+def offset (maps : Bool) (layout tag : Word w) : Word w :=
+ let lo := BinaryOp.mod.eval tag 2
+ let mid := BinaryOp.mod.eval (BinaryOp.div.eval tag 2) 2
+ let hi := BinaryOp.div.eval tag four
+ if maps then mux hi (mux mid lo (mux lo layout 2)) (mux lo (2*layout) (2-layout))
+ else mux (lo*mid) layout 2
+
+private theorem div_cast {x y : ℕ} (hx : x < 2^w) (hy : y < 2^w) :
+ BinaryOp.div.eval (x : Word w) (y : Word w) = ((x/y : ℕ) : Word w) := by
+ change Fin.ofNat _ ((x % 2^w)/(y % 2^w)) = _
+ rw [Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hy]
+ rfl
+
+private theorem remainder_cast {x y : ℕ} (hx : x < 2^w) (hy : y < 2^w) :
+ BinaryOp.mod.eval (x : Word w) (y : Word w) = ((x%y : ℕ) : Word w) := by
+ change Fin.ofNat _ ((x % 2^w)%(y % 2^w)) = _
+ rw [Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hy]
+ rfl
+
+private theorem offset_nat (maps : Bool) (layout : Word w) (t : ℕ) (hw : 6 < 2^w) (ht : t < 6) :
+ offset maps layout (t : Word w) =
+ if maps then mux ((t/4 : ℕ) : Word w)
+ (mux ((t/2%2 : ℕ) : Word w) ((t%2 : ℕ) : Word w) (mux ((t%2 : ℕ) : Word w) layout 2))
+ (mux ((t%2 : ℕ) : Word w) (2*layout) (2-layout))
+ else mux (((t%2 : ℕ) : Word w)*((t/2%2 : ℕ) : Word w)) layout 2 := by
+ unfold offset
+ rw [four_eq]
+ have h₂ : 2 < 2^w := by omega
+ have h₄ : 4 < 2^w := by omega
+ have h := ht.trans hw
+ have hd : t/2 < 2^w := (Nat.div_le_self ..).trans_lt h
+ have r₂ := remainder_cast h h₂
+ have d₂ := div_cast h h₂
+ have dr := remainder_cast hd h₂
+ have d₄ := div_cast h h₄
+ simp only [Nat.cast_ofNat] at r₂ d₂ dr d₄
+ rw [r₂,d₂,dr,d₄]
+
+/-- Bit decoding agrees with the party-role table in both layouts. -/
+theorem offset_party (layout : Bool) (t : Fin 6) (hw : 6 < 2^w) :
+ offset true (layout.toNat : Word w) (t.val : Word w) = (SlotOwners.roleOffset (partyRole layout t) : Word w) := by
+ rw [offset_nat true _ _ hw t.isLt]
+ cases layout <;> fin_cases t <;> simp [mux, partyRole, SlotOwners.roleOffset]; ring
+
+/-- Bit decoding agrees with the owner of each absorbed edge type. -/
+theorem offset_hidden (layout : Bool) (t : Fin 4) (hw : 6 < 2^w) :
+ offset false (layout.toNat : Word w) (t.val : Word w) = (SlotOwners.roleOffset (internalRole layout t) : Word w) := by
+ rw [offset_nat false _ _ hw (t.isLt.trans (by decide))]
+ cases layout <;> fin_cases t <;> simp [mux, internalRole, partyRole, supply, supplySource, SlotOwners.roleOffset]
+
+/-- Address of the occurrence's absolute CD identifier, using the quotient of its cursor by the
+number of occurrences per motif. -/
+def absoluteAddr (maps : Bool) (p : Fin 4 → Word w) (s : Word w) :=
+ p 0 + BinaryOp.div.eval s (radix maps)
+
+/-- Address of the packed-owner word in the old arc's four-word role record, using the stored
+CD identifier and the occurrence's selected role. -/
+def roleAddr (maps : Bool) (p : Fin 4 → Word w) (m : Memory w) (s : Word w) :=
+ p 1 + four*m (absoluteAddr maps p s).val + offset maps (p 2) (BinaryOp.mod.eval s (radix maps))
+
+theorem absoluteAddr_eq (maps : Bool) (p : Fin 4 → Word w) (s : Word w) :
+ absoluteAddr maps p s = p 0 + BinaryOp.div.eval s (arity maps : Word w) := by
+ rw [absoluteAddr,radix_eq]
+
+theorem roleAddr_eq (maps : Bool) (p : Fin 4 → Word w) (m : Memory w) (s : Word w) :
+ roleAddr maps p m s = p 1 + 4*m (absoluteAddr maps p s).val +
+ offset maps (p 2) (BinaryOp.mod.eval s (arity maps : Word w)) := by rw [roleAddr,four_eq,radix_eq]
+
+/-- Trace of one owner visit, reading the motif identifier and selected role word, writing that
+owner at the occurrence cursor, and returning the next cursor. -/
+def report (maps : Bool) (p : Fin 4 → Word w) (s : Word w) (m : Memory w) : Report w :=
+ let abs := absoluteAddr maps p s
+ let role := roleAddr maps p m s
+ let value := m role.val
+ ⟨List.replicate (14+(roleOps maps).length) .tick ++ [.read abs (m abs.val)] ++
+ List.replicate 4 .tick ++ [.read role value] ++ List.replicate 2 .tick ++
+ [.write (p 3+s) value] ++ List.replicate 2 .tick, some (s+1)⟩
+
+theorem length_code (maps : Bool) : (code maps).length = if maps then 39 else 29 := by cases maps <;> rfl
+
+theorem native (maps : Bool) (p : Fin 4 → Word w) (s : Word w) (m : Memory w) :
+ let M := (worker maps).table.instantiate w p
+ execute M.program (1+(code maps).length) (M.program.start s) m [] = some (report maps p s m) ∧
+ after m (report maps p s m).events = writeMemory m (p 3+s) (m (roleAddr maps p m s).val) ∧
+ countProbes (report maps p s m).events = 3 ∧ (report maps p s m).events.length = (code maps).length ∧
+ choiceBits (report maps p s m).events = [] := by
+ intro M
+ refine ⟨?_,?_,?_,?_,?_⟩
+ · change execute ((template (code maps) 0).instantiate w p).program (1+(code maps).length)
+ ⟨((template (code maps) 0).instantiate w p).entry,s,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _
+ rw [execute_template,run_eq_trace]
+ cases maps <;> rfl
+ all_goals cases maps <;> rfl
+
+end CompressorRecords.ResidentOwners
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentPackets.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentPackets.lean
new file mode 100644
index 0000000000..124892efbe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentPackets.lean
@@ -0,0 +1,235 @@
+import OAI.Computability.VPVNP.CompressorBlockIndex
+import OAI.Computability.VPVNP.CompressorScriptWindow
+import OAI.Computability.VPVNP.CompressorShrinkResidentHeaders
+import OAI.Computability.VPVNP.CompressorShrinkResidentRun
+import OAI.Computability.VPVNP.CompressorHeaderOperands
+
+/-! # The twelve resident-directory visits in the installed compressor script
+
+The old hidden and map directories each use an owner scan, a counter clear
+and a guarded append. Six single-word publishers then install their heads
+at offsets 30 through 35. The window starts after the 36 preceding visits
+of the same shrinking substep.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkResidentPackets
+
+open Compression BurstRAM BlockPlanner PhaseRecipe DescriptorSpace PrimedStackRAM SourceTransport
+open ShrinkResidentRun ShrinkResidentLayout
+open scoped Fin.CommRing
+
+/-- Expressions and degree exponent used to plan the two resident directory builds and their
+six header publications for a selected shrink. -/
+structure Plan where
+ /-- Selected-shrink input formulas supplying the site and motif counts, role-record base and
+ layout choice. -/
+ chosen : SelectedPlan.Inputs
+ /-- Expression for the first workspace address assigned to the hidden-field and party-map
+ directories. -/
+ first : Expr
+ /-- Expression for the old level header where the six completed directory heads are
+ published. -/
+ oldLevel : Expr
+ /-- Expression for the dense motif-indexed array of absolute CD identifiers read by the owner
+ scans. -/
+ absoluteCD : Expr
+ /-- Old degree exponent used to compute the preimage-row capacity for the collector's operand
+ bank. -/
+ exponent : ℕ
+
+/-- A resident-directory operation, either writing owners, clearing counts, appending preimages
+for one resident kind, or publishing one of the six heads. -/
+inductive Stage
+ | owners (maps : Bool)
+ | clear (maps : Bool)
+ | append (maps : Bool)
+ | header (i : Fin 6)
+
+/-- The three visits that build one resident directory, assigning owners, clearing site counts
+and appending occurrence identifiers in order. -/
+def scans (maps : Bool) : List Stage := [.owners maps,.clear maps,.append maps]
+
+/-- Execution order of the twelve stages, building hidden-field rows, then party-map rows, then
+publishing their six pointers. -/
+def order : List Stage := scans false ++ scans true ++ (List.finRange 6).map Stage.header
+
+/-- Translate one resident stage into its scheduled worker, cursor bounds and operand
+expressions for this plan. -/
+def Stage.visit (P : Plan) : Stage → BlockPlanner.Visit
+ | .owners maps => ResidentOwners.visit maps (ShrinkResidentsPlan.size P.chosen maps) P.absoluteCD
+ (SelectedPlan.roleBase P.chosen) (SelectedPlan.layout P.chosen) (ShrinkResidentsPlan.owner P.chosen P.first maps)
+ | .clear maps => ops SliceRAM.clearOps 0 (.lit 0) P.chosen.newSites (fun _ => ShrinkResidentsPlan.counts P.chosen P.first maps)
+ | .append maps => ops collectPreimage 3 (.lit 0) (ShrinkResidentsPlan.size P.chosen maps)
+ (ShrinkResidentsPlan.bank P.chosen P.first P.exponent maps)
+ | .header i => ShrinkResidentsPlan.headerVisit P.chosen P.first P.oldLevel i
+
+/-- The ordered block-planner visits that execute both resident directory builds and publish
+their heads using the plan's inputs. -/
+def Plan.visits (P : Plan) := ShrinkResidentsPlan.visits P.chosen P.first P.oldLevel P.absoluteCD P.exponent
+
+theorem Plan.ordered (P : Plan) : order.map (Stage.visit P) = P.visits := by
+ simp only [order,List.map_append,List.map_map,Plan.visits,ShrinkResidentsPlan.visits,
+ ShrinkResidentsPlan.publications,List.ofFn_eq_map]
+ rfl
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+
+/-- Recover the resident plan for a particular block substep from its selected inputs, old
+level, directory arena, absolute CD table and old degree exponent. -/
+def plan : Plan :=
+ let F := BlockProgram.geometry B
+ let origin := BlockProgram.arena B i.val 0
+ ⟨ShrinkBlockInputs.selectedInputs B F i origin,BlockProgram.arena B i.val 5,LevelFields.atLevel i.val,
+ ShrinkBundlePlan.absoluteCD i.val (ShrinkBlockInputs.a i) origin,ShrinkBlockInputs.a i⟩
+
+/-- The portion of this shrinking substep preceding its resident-directory window, comprising
+the first 36 visits. -/
+def prior := ShrinkBlockInputs.beforeSlices B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0)
+
+private theorem tail_exists : ∃ tail, BlockProgram.shrink B i = prior B i ++ (plan B i).visits ++ tail := by
+ unfold BlockProgram.shrink
+ simp only [List.append_assoc]
+ exact ⟨_,rfl⟩
+
+/-- Locate the twelve resident visits in the installed block script after the earlier substeps
+and this substep's prefix. -/
+def window : Window (BlockProgram.script B) (plan B i).visits where
+ before := BlockIndex.earlier B i ++ prior B i
+ after := (tail_exists B i).choose ++ BlockIndex.later B i
+ block := by
+ change BlockProgram.block B = _
+ conv_lhs => rw [BlockIndex.split_block,(tail_exists B i).choose_spec]
+ simp only [List.append_assoc]
+
+theorem window_offset : (window B i).before.length = (BlockIndex.earlier B i).length+36 := by
+ change (BlockIndex.earlier B i ++ prior B i).length = _
+ rw [List.length_append,prior,ShrinkBlockInputs.beforeSlices_length]
+
+theorem window_phase (t : ℕ) (j : Fin (plan B i).visits.length) :
+ let A := BlockProgram.script B
+ let ordinal := A.initial.length+t*A.block.length+(BlockIndex.earlier B i).length+36+j.val
+ (Schedule.Online.calendar A.plan).phase ordinal = ((window B i).index j).val ∧
+ (Schedule.Online.calendar A.plan).level ordinal = t := by
+ dsimp only
+ simpa only [Window.index,Window.position,window_offset,Fin.val_natAdd,Nat.add_assoc] using
+ (BlockProgram.script B).block_phase t ((window B i).position j)
+
+variable {w : ℕ}
+
+/-- Concrete resident workspace, header address, source pointers and layout choice used to
+instantiate the planned scans at a given word width. -/
+structure Values (w : ℕ) where
+ /-- The concrete layout of both resident directories, determining their table addresses and
+ scan sizes. -/
+ layout : ShrinkResidentLayout.Layout
+ /-- Address of the old level header receiving the six resident directory pointers. -/
+ level : ℕ
+ /-- Machine-word pointer to the dense absolute CD identifiers, one per motif. -/
+ absolute : Word w
+ /-- Machine-word pointer to the four-word role records indexed by absolute old arc. -/
+ role : Word w
+ /-- The Boolean shrink layout used to select the resident's packed role when writing owners. -/
+ side : Bool
+
+/-- Exclusive cursor bound for this stage, the occurrence count for owners and appends, the
+site count for clearing, or one for a head publication. -/
+def Stage.limit (D : Values w) : Stage → ℕ
+ | .owners maps | .append maps => D.layout.size maps
+ | .clear _ => D.layout.sites
+ | .header _ => 1
+
+/-- Private fuel allowed for one worker call of this stage, determined by its native owner,
+clear, append or publication code. -/
+def Stage.fuel : Stage → ℕ
+ | .owners maps => 1+(ResidentOwners.code maps).length
+ | .clear _ => 8
+ | .append _ => 23
+ | .header _ => 7
+
+theorem Stage.clock (j : Stage) : 0 < j.fuel ∧ j.fuel ≤ 40 := by
+ cases j with
+ | owners maps => cases maps <;> decide
+ | clear | append | header => simp [Stage.fuel]
+
+/-- Concrete public operand vector for the stage's worker, using the instantiated directory
+addresses, source pointers and selected layout. -/
+def Stage.bank (P : Plan) (D : Values w) : (j : Stage) → Fin (Stage.visit P j).worker.params → Word w
+ | .owners maps => ![D.absolute,D.role,(D.side.toNat : Word w),(D.layout.owner maps : Word w)]
+ | .clear maps => fun _ => (D.layout.counts maps : Word w)
+ | .append maps => D.layout.params P.exponent maps w
+ | .header j => ShrinkResidentsPlan.headerBank D.level D.layout w j
+
+/-- The planned operands evaluate in the current public words, state and memory to the concrete
+resident layout, header address, source pointers and selected side. -/
+structure OperandValues (P : Plan) (D : Values w) (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w) : Prop where
+ ready : ShrinkResidentsPlan.Ready P.chosen P.first pub st mem D.layout
+ oldLevel : P.oldLevel.eval pub st mem = (D.level : Word w)
+ absolute : P.absoluteCD.eval pub st mem = D.absolute
+ role : (SelectedPlan.roleBase P.chosen).eval pub st mem = D.role
+ side : (SelectedPlan.layout P.chosen).eval pub st mem = (D.side.toNat : Word w)
+
+theorem OperandValues.words {P : Plan} {D : Values w} {pub : Fin 5 → Word w} {st : Word w} {mem : Memory w}
+ (h : OperandValues P D pub st mem) (j : Stage) :
+ (j.visit P).initial.eval pub st mem = 0 ∧ (j.visit P).stop.eval pub st mem = (j.limit D : Word w) ∧
+ (fun t => ((j.visit P).params t).eval pub st mem) = j.bank P D := by
+ have size := ShrinkResidentsPlan.size_val P.chosen P.first pub st mem D.layout h.ready
+ have owner := ShrinkResidentsPlan.owner_val P.chosen P.first pub st mem D.layout h.ready
+ have counts := ShrinkResidentsPlan.counts_val P.chosen P.first pub st mem D.layout h.ready
+ cases j with
+ | owners maps =>
+ refine ⟨rfl,size maps,?_⟩
+ funext t
+ fin_cases t <;> first | exact h.absolute | exact h.role | exact h.side | exact owner maps
+ | clear maps => exact ⟨rfl,h.ready.sites,funext fun _ => counts maps⟩
+ | append maps => exact ⟨rfl,size maps,ShrinkResidentsPlan.bank_val P.chosen P.first pub st mem D.layout h.ready P.exponent maps⟩
+ | header t => exact ⟨rfl,rfl,ShrinkResidentsPlan.header_bank_eq P.chosen P.first P.oldLevel pub st mem D.level D.layout h.ready h.oldLevel t⟩
+
+/-- The only loaded expressions needed for all twelve visits. -/
+structure OperandReads (P : Plan) (data : ℕ → Prop) (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w) : Prop where
+ sites : P.chosen.newSites.ReadsFrom data pub st mem
+ motifs : P.chosen.motifs.ReadsFrom data pub st mem
+ first : P.first.ReadsFrom data pub st mem
+ role : (SelectedPlan.roleBase P.chosen).ReadsFrom data pub st mem
+ layout : (SelectedPlan.layout P.chosen).ReadsFrom data pub st mem
+ absolute : P.absoluteCD.ReadsFrom data pub st mem
+ level : P.oldLevel.ReadsFrom data pub st mem
+
+theorem OperandReads.supported {P : Plan} {data : ℕ → Prop} {pub : Fin 5 → Word w} {st : Word w} {mem : Memory w}
+ (h : OperandReads P data pub st mem) (j : Stage) : HeaderOperands.Supported data pub st mem (j.visit P) := by
+ let rd := fun x : Expr => x.ReadsFrom data pub st mem
+ have size (b) : rd (ShrinkResidentsPlan.size P.chosen b) := ⟨h.motifs,trivial⟩
+ have owner (b) : rd (ShrinkResidentsPlan.owner P.chosen P.first b) := by
+ cases b
+ · exact h.first
+ · exact ⟨⟨⟨h.first,size false⟩,h.sites⟩,size false⟩
+ have counts (b) : rd (ShrinkResidentsPlan.counts P.chosen P.first b) := ⟨owner b,size b⟩
+ have rows (b) : rd (ShrinkResidentsPlan.rows P.chosen P.first b) := ⟨counts b,h.sites⟩
+ cases j with
+ | owners b =>
+ refine ⟨trivial,size b,?_⟩
+ intro t; fin_cases t <;> first | exact h.absolute | exact h.role | exact h.layout | exact owner b
+ | clear b => exact ⟨trivial,h.sites,fun _ => counts b⟩
+ | append b =>
+ refine ⟨trivial,size b,?_⟩
+ intro t; fin_cases t <;> first | exact size b | exact owner b | exact h.sites | exact counts b | exact rows b | trivial
+ | header i =>
+ refine ⟨trivial,trivial,?_⟩
+ intro t
+ fin_cases t
+ · exact ⟨h.level,trivial⟩
+ · fin_cases i <;> first | exact owner false | exact counts false | exact rows false
+ | exact owner true | exact counts true | exact rows true
+
+end CompressorRecords.ShrinkResidentPackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentRun.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentRun.lean
new file mode 100644
index 0000000000..218f216ef9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentRun.lean
@@ -0,0 +1,263 @@
+import OAI.Computability.VPVNP.CompressorShrinkResidentDirectory
+import OAI.Computability.VPVNP.CompressorShrinkResidentsPlan
+
+/-! # Native construction of both local resident tables in chronological memory -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkResidentRun
+
+open Compression BurstRAM PrimedStackRAM PairSimulation.LocalHistory
+open ShrinkResidentLayout
+open scoped Fin.CommRing Classical
+
+variable {a g w : ℕ} (X : State a (packingLaneBits a g)) (first : ℕ)
+variable (absolute roleHead : Word w) (side : Bool)
+
+/-- The owner scan takes four words in order, the dense-to-absolute motif table base, the role
+table base, the selected side bit, and the output base for hidden or map owners. -/
+def ownerBank (maps : Bool) : Fin 4 → Word w :=
+ ![absolute,roleHead,(side.toNat : Word w),((layout X first).owner maps : Word w)]
+
+/-- The preimage collector takes six words for the chosen resident kind, giving its size and
+owner base, the packed-site count and counter base, the row capacity, and the ID row base. -/
+def outputBank (maps : Bool) := (layout X first).params a maps w
+
+/-- The resident arena and both input tables fit the address space, each input table lies
+outside the arena, and six is representable as a word. -/
+structure Areas : Prop where
+ fit : (layout X first).endAddr < 2^w
+ absoluteRoom : absolute.val+(shrinkMotifOrder X).length ≤ 2^w
+ roleRoom : roleHead.val+4*DemandRAM.absoluteCount X ≤ 2^w
+ absoluteApart : absolute.val+(shrinkMotifOrder X).length ≤ first ∨ (layout X first).endAddr ≤ absolute.val
+ roleApart : roleHead.val+4*DemandRAM.absoluteCount X ≤ first ∨ (layout X first).endAddr ≤ roleHead.val
+ tagFit : 6 < 2^w
+
+variable {X first absolute roleHead} (space : Areas X first absolute roleHead)
+
+include space in
+theorem Areas.owner (maps : Bool) : ShrinkResidentDirectory.Areas X maps (ownerBank X first absolute roleHead side maps) := by
+ let L := layout X first
+ have dims : (ShrinkResidentDirectory.oldOrder X maps).length = L.size maps := rfl
+ obtain ⟨start,cnt,rows,stop⟩ := L.ranges maps
+ have fit : L.endAddr < 2^w := space.fit
+ have word : (ownerBank X first absolute roleHead side maps 3).val = L.owner maps := Nat.mod_eq_of_lt (show L.owner maps < 2^w by omega)
+ refine ⟨space.absoluteRoom,space.roleRoom,?_,?_,?_,space.tagFit⟩
+ · rw [word,dims]; omega
+ · rw [word,dims]; exact space.absoluteApart.imp (fun h => h.trans start) (fun h => (show L.owner maps+L.size maps ≤ L.endAddr by omega).trans h)
+ · rw [word,dims]; exact space.roleApart.imp (fun h => h.trans start) (fun h => (show L.owner maps+L.size maps ≤ L.endAddr by omega).trans h)
+
+/-- Reports from the three successive scans that build a directory of hidden residents or map
+residents at the packed sites. -/
+structure Passes (w : ℕ) where
+ /-- Reports from writing the packed owner of each resident in motif-major order. -/
+ owners : List (Report w)
+ /-- Reports from setting each packed site’s resident counter to zero before collecting its
+ IDs. -/
+ clear : List (Report w)
+ /-- Reports from appending each resident’s dense ID to its owner’s row and incrementing that
+ site’s counter. -/
+ collect : List (Report w)
+
+/-- Memory after replaying the owner-column writes on the entry memory, ready for the
+counter-clear scan. -/
+def Passes.mid (p : Passes w) (m : Memory w) := after m (eventLog p.owners)
+/-- Memory after the owner scan and the counter-clear scan, where the ID collection starts. -/
+def Passes.cleared (p : Passes w) (m : Memory w) := after (p.mid m) (eventLog p.clear)
+/-- Memory after collecting the resident IDs on top of the owner and counter scans. -/
+def Passes.final (p : Passes w) (m : Memory w) := after (p.cleared m) (eventLog p.collect)
+/-- The complete directory trace in execution order, from the owner writes through counter
+clearing to ID collection. -/
+def Passes.all (p : Passes w) := p.owners++p.clear++p.collect
+
+theorem Passes.after_all (p : Passes w) (m : Memory w) : after m (eventLog p.all) = p.final m := by
+ simp only [all,final,cleared,mid,eventLog,List.flatMap_append,after,List.foldl_append]
+
+variable (X first absolute roleHead) (maps : Bool)
+
+/-- Certifies the three native scans, their ordered per-site resident directory, and
+preservation outside the resident tables. The total charge is nine per resident and two per
+packed site. -/
+structure Built (m : Memory w) (p : Passes w) : Prop where
+ owners : ShrinkResidentDirectory.Written X maps (ownerBank X first absolute roleHead side maps) side m p.owners
+ clear : runSegment ((template SliceRAM.clearOps 0).instantiate w (fun _ => outputBank X first maps 3)).program 8
+ (some 0) (p.mid m) (List.replicate (layout X first).sites []) = some p.clear
+ collect : runSegment ((template collectPreimage 3).instantiate w (outputBank X first maps)).program 23
+ (some 0) (p.cleared m) (List.replicate ((layout X first).size maps) []) = some p.collect
+ directory : ShrinkHistoryRows.Directory (ShrinkResidentDirectory.oldOrder X maps) (ShrinkHistoryRows.packedOrder X)
+ (ShrinkResidentDirectory.place X maps side) (outputBank X first maps) (p.final m)
+ frame (x : ℕ) (hx : x < (layout X first).owner maps ∨ (layout X first).rows maps+(layout X first).size maps ≤ x) :
+ p.final m x = m x
+ charge : RAMBuckets.cost Report.probes p.all = 9*(layout X first).size maps + 2*(layout X first).sites
+
+private theorem clearCost (rs : List (Report w)) (h : ∀ r ∈ rs, r.probes = 1) :
+ RAMBuckets.cost Report.probes rs = 2*rs.length := by
+ induction rs with
+ | nil => rfl
+ | cons r rs ih =>
+ rw [RAMBuckets.cost, h r (List.mem_cons_self ..), ih (fun _ hv => h _ (List.mem_cons_of_mem _ hv)), List.length_cons,Nat.mul_succ]
+ omega
+
+include space in
+/-- Starting from actual CD and role data, this deterministic three-stage
+scan gives precisely the ordered local hidden IDs or map IDs. -/
+theorem run (mem : Memory w) (dir : ShrinkResidentDirectory.Absolute X absolute mem)
+ (roles : DemandRAM.RoleColumns X side roleHead.val mem) :
+ ∃ p : Passes w, Built X first absolute roleHead side maps mem p := by
+ let L := layout X first
+ let bank := outputBank (w := w) X first maps
+ have ho : (ShrinkResidentDirectory.oldOrder X maps).length = L.size maps := rfl
+ have hn : (ShrinkHistoryRows.packedOrder X).length = L.sites := rfl
+ obtain ⟨areas,h0,h1,h2,h3,h4,h5⟩ := ShrinkResidentLayout.frame X first maps space.fit
+ change (bank 0).val=L.size maps at h0
+ change (bank 1).val=L.owner maps at h1
+ change (bank 2).val=L.sites at h2
+ change (bank 3).val=L.counts maps at h3
+ change (bank 4).val=rowCapacity a maps at h4
+ change (bank 5).val=L.rows maps at h5
+ have newFit : (ShrinkHistoryRows.packedOrder X).length ≤ 2^w := (h2 ▸ (bank 2).isLt).le
+ have allowed := space.owner side maps
+ obtain ⟨own,hw⟩ := ShrinkResidentDirectory.run X maps (ownerBank X first absolute roleHead side maps) rfl allowed newFit dir roles
+ have cap (v) : Fintype.card {x // ShrinkResidentDirectory.place X maps side x = v} ≤ (bank 4).val := by
+ exact (show Fintype.card {x // ShrinkResidentDirectory.place X maps side x = v} ≤ rowCapacity a maps from by
+ cases maps
+ · exact (ShrinkHistoryRows.hidden_count X side v).le
+ · exact (ShrinkHistoryRows.map_count X side v).le).trans h4.symm.le
+ obtain ⟨cs,rs,hc,hr,rows,clen,rlen,cwork,rwork,rf⟩ := ShrinkHistoryRows.build
+ (ShrinkResidentDirectory.oldOrder X maps) (ShrinkHistoryRows.packedOrder X)
+ (ShrinkResidentDirectory.place X maps side) bank areas h0 h2 cap (after mem (eventLog own))
+ (hw.ownerAt X maps (ownerBank X first absolute roleHead side maps) allowed bank rfl h0)
+ let pass : Passes w := ⟨own,cs,rs⟩
+ refine ⟨pass,hw,hc,hr,rows,?_,?_⟩
+ · intro x hx
+ obtain ⟨_,oc,cr,_⟩ := L.ranges maps
+ have ss := size_eq_rows X first maps
+ change L.size maps=L.sites*rowCapacity a maps at ss
+ have other : OutsidePreimageWrites bank x := by
+ change (x < (bank 3).val ∨ (bank 3).val+(bank 2).val ≤ x) ∧
+ (x < (bank 5).val ∨ (bank 5).val+(bank 2).val*(bank 4).val ≤ x)
+ rw [h3,h2,h5,h4,←ss]
+ change x < L.owner maps ∨ L.rows maps+L.size maps ≤ x at hx
+ omega
+ have wo : (ownerBank X first absolute roleHead side maps 3).val = L.owner maps := h1
+ apply (rf x other).trans (hw.frame x ?_)
+ rw [wo,ho]
+ change x < L.owner maps ∨ L.rows maps+L.size maps ≤ x at hx
+ omega
+ · change RAMBuckets.cost Report.probes ((own++cs)++rs) = _
+ have rc : RAMBuckets.cost Report.probes rs = 5*rs.length := preimagePass_cost (fun r h => (rwork r h).1)
+ rw [RAMBuckets.cost_append,RAMBuckets.cost_append,hw.charge,clearCost cs (fun r h => (cwork r h).1),rc,clen,rlen,ho,hn]
+ change 4*L.size maps+2*L.sites+5*L.size maps = 9*L.size maps+2*L.sites
+ omega
+
+/-- The entire resident workspace is disjoint from the two persistent
+input arrays. A finished stage therefore leaves their typed readbacks live
+for the next stage. -/
+theorem Built.inputs {m : Memory w} {r : Passes w} (h : Built X first absolute roleHead side maps m r)
+ (dir : ShrinkResidentDirectory.Absolute X absolute m) (roles : DemandRAM.RoleColumns X side roleHead.val m)
+ (sp : Areas X first absolute roleHead) :
+ ShrinkResidentDirectory.Absolute X absolute (r.final m) ∧
+ DemandRAM.RoleColumns X side roleHead.val (r.final m) := by
+ let L := layout X first
+ obtain ⟨before,_,_,endBound⟩ := L.ranges maps
+ have same (x : ℕ) (hx : x < first ∨ L.endAddr ≤ x) : r.final m x = m x :=
+ h.frame x (hx.imp (fun lo => lo.trans_le before) (fun hi => endBound.trans hi))
+ have absSafe {i : ℕ} (hi : i < (shrinkMotifOrder X).length) :
+ absolute.val+i < first ∨ L.endAddr ≤ absolute.val+i :=
+ sp.absoluteApart.imp (fun ha => (Nat.add_lt_add_left hi _).trans_le ha) (fun ha => ha.trans (Nat.le_add_right ..))
+ have roleSafe {i j : ℕ} (hi : i (show _ < roleHead.val+4*DemandRAM.absoluteCount X by omega).trans_le ha)
+ (fun ha => (ha.trans (Nat.le_add_right ..)).trans (Nat.le_add_right ..))
+ constructor
+ · intro i
+ have hc := Fintype.card_congr (ShrinkMotifOrder.stateNumber X)
+ rw [Fintype.card_fin] at hc
+ have hi : i.val < (shrinkMotifOrder X).length := i.isLt.trans_eq hc.symm
+ rw [same _ (absSafe hi)]
+ exact dir i
+ · constructor
+ · intro e
+ rw [same _ (roleSafe (DemandRAM.absoluteIndex X e).isLt (by decide : 3<4))]
+ exact roles.cd e
+ · intro e role
+ have small : SlotOwners.roleOffset role < 4 := by cases role <;> decide
+ rw [same _ (roleSafe (DemandRAM.absoluteIndex X e.val).isLt small)]
+ exact roles.packed e role
+
+private theorem hidden_length_le (v) : (ShrinkHistoryRows.residents (ShrinkHistoryRows.hiddenOrder X)
+ (X.packingData.shrinkInternalOwner side) v).length ≤ rowCapacity a false := by
+ let f := X.packingData.shrinkInternalOwner side
+ have changeFiber : {u // v=f u} ≃ {u // f u=v} := Equiv.subtypeEquivRight fun _ => eq_comm
+ exact (Fintype.card_congr changeFiber).le.trans (ShrinkHistoryRows.hidden_count X side v).le
+
+/-- The later map-directory calls retain both the earlier hidden counts
+and every earlier hidden ID. -/
+theorem retained_hidden {m : Memory w} {h r : Passes w}
+ (hb : Built X first absolute roleHead side false m h)
+ (rb : Built X first absolute roleHead side true (h.final m) r)
+ (fit : (layout X first).endAddr < 2^w) :
+ ShrinkHistoryRows.Directory (ShrinkHistoryRows.hiddenOrder X) (ShrinkHistoryRows.packedOrder X)
+ (X.packingData.shrinkInternalOwner side) (outputBank X first false) (r.final (h.final m)) := by
+ let L := layout X first
+ let p := outputBank (w := w) X first false
+ obtain ⟨_,_,_,hSites,hCount,hCap,hRow⟩ := ShrinkResidentLayout.frame X first false fit
+ change (p 2).val=L.sites at hSites
+ change (p 3).val=L.counts false at hCount
+ change (p 4).val=rowCapacity a false at hCap
+ change (p 5).val=L.rows false at hRow
+ have order (v) : ((ShrinkHistoryRows.packedOrder X).entries.symm v).val < L.sites :=
+ ((ShrinkHistoryRows.packedOrder X).entries.symm v).isLt
+ have next : L.owner true = L.rows false+L.size false := rfl
+ constructor
+ · intro v
+ have addr : (p 3).val+((ShrinkHistoryRows.packedOrder X).entries.symm v).val < L.owner true := by
+ rw [hCount,next]
+ have := order v
+ change L.counts false+_ < L.counts false+L.sites+L.size false
+ omega
+ rw [rb.frame _ (.inl addr)]
+ exact hb.directory.count v
+ · intro v j
+ have vv := Nat.mul_le_mul_right (rowCapacity a false) (order v)
+ rw [Nat.succ_mul] at vv
+ have hv := j.isLt.trans_le (hidden_length_le X side v)
+ have dim := size_eq_rows X first false
+ change L.size false=L.sites*rowCapacity a false at dim
+ have addr : (p 5).val+((ShrinkHistoryRows.packedOrder X).entries.symm v).val*(p 4).val+j.val < L.owner true := by
+ rw [hRow,hCap,next,dim]
+ omega
+ rw [rb.frame _ (.inl addr)]
+ exact hb.directory.idAt v j
+
+include space in
+/-- Six deterministic native visits execute on the same memory image
+as the two resident headers describe. No guessed bits are used to recover
+the resident lists. -/
+theorem both (m : Memory w) (dir : ShrinkResidentDirectory.Absolute X absolute m)
+ (roles : DemandRAM.RoleColumns X side roleHead.val m) :
+ ∃ h r : Passes w, Built X first absolute roleHead side false m h ∧
+ Built X first absolute roleHead side true (h.final m) r ∧
+ ShrinkHistoryRows.Directory (ShrinkHistoryRows.hiddenOrder X) (ShrinkHistoryRows.packedOrder X)
+ (X.packingData.shrinkInternalOwner side) (outputBank X first false) (r.final (h.final m)) ∧
+ RAMBuckets.cost Report.probes (h.all++r.all) = 90*(layout X first).motifs+4*(layout X first).sites := by
+ obtain ⟨h,hh⟩ := run X first absolute roleHead side space false m dir roles
+ obtain ⟨dir',roles'⟩ := hh.inputs X first absolute roleHead side false dir roles space
+ obtain ⟨r,hr⟩ := run X first absolute roleHead side space true (h.final m) dir' roles'
+ refine ⟨h,r,hh,hr,retained_hidden X first absolute roleHead side hh hr space.fit,?_⟩
+ rw [RAMBuckets.cost_append,hh.charge,hr.charge]
+ change 9*((layout X first).motifs*4)+2*(layout X first).sites +
+ (9*((layout X first).motifs*6)+2*(layout X first).sites) = _
+ omega
+
+end CompressorRecords.ShrinkResidentRun
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentScan.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentScan.lean
new file mode 100644
index 0000000000..eebbf2b815
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentScan.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.CompressorShrinkResidentOwners
+
+/-!
+# Executing the dense resident owner scan
+
+The role and absolute-CD input cells lie outside the fresh output column.
+A pass preserves its source cells while writing exactly one owner for each
+dense history index.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ResidentOwners
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private def Written (maps : Bool) (p : Fin 4 → Word w) (old m : Memory w) (k : ℕ) : Prop :=
+ (∀ j < k, m ((p 3).val+j) = old (roleAddr maps p old (j : Word w)).val) ∧
+ ∀ a, a < (p 3).val ∨ (p 3).val+k ≤ a → m a = old a
+
+private theorem scan_from (maps : Bool) (p : Fin 4 → Word w) (old : Memory w) (N : ℕ)
+ (fits : (p 3).val+N ≤ 2^w)
+ (inputs : ∀ i : Word w, i.val < N →
+ ((absoluteAddr maps p i).val < (p 3).val ∨ (p 3).val+N ≤ (absoluteAddr maps p i).val) ∧
+ ((roleAddr maps p old i).val < (p 3).val ∨ (p 3).val+N ≤ (roleAddr maps p old i).val))
+ {k n : ℕ} {m : Memory w} (bound : k+n ≤ N) (done : Written maps p old m k) :
+ let W := (worker maps).table.instantiate w p
+ ∃ rs, runSegment W.program (1+(code maps).length) (some (k : Word w)) m (List.replicate n []) = some rs ∧
+ Written maps p old (after m (eventLog rs)) (k+n) ∧ rs.length = n ∧
+ (∀ r ∈ rs, r.events.length = (code maps).length ∧ countProbes r.events = 3 ∧ choiceBits r.events = []) ∧
+ RAMBuckets.cost Report.probes rs = 4*n := by
+ intro W
+ induction n generalizing k m with
+ | zero => exact ⟨[],rfl,done,rfl,by simp,rfl⟩
+ | succ n ih =>
+ let i : Word w := (k : Word w)
+ have hk : k < N := by omega
+ have hi : i.val = k := Nat.mod_eq_of_lt (by omega)
+ have hr := inputs i (hi ▸ hk)
+ have keep (addr : ℕ) (ha : addr < (p 3).val ∨ (p 3).val+N ≤ addr) : m addr = old addr :=
+ done.2 addr (by omega)
+ have hrole : roleAddr maps p m i = roleAddr maps p old i := by
+ unfold roleAddr
+ rw [keep _ hr.1]
+ have hval : m (roleAddr maps p m i).val = old (roleAddr maps p old i).val := by
+ rw [hrole]; exact keep _ hr.2
+ have haddr : (p 3+i).val = (p 3).val+k := by
+ rw [Fin.val_add,hi,Nat.mod_eq_of_lt (by omega)]
+ let u := writeMemory m (p 3+i) (m (roleAddr maps p m i).val)
+ have step : Written maps p old u (k+1) := by
+ refine ⟨fun j hj ↦ ?_, fun a ha ↦ ?_⟩
+ · by_cases eq : j = k
+ · subst j; simpa only [u,writeMemory,haddr,ite_true] using hval
+ · rw [show u ((p 3).val+j) = m ((p 3).val+j) by simp [u,writeMemory,haddr,eq]]
+ exact done.1 j (by omega)
+ · have hne : a ≠ (p 3).val+k := by omega
+ simp only [u,writeMemory,haddr,ite_eq_right hne]
+ exact done.2 _ (by omega)
+ obtain ⟨rs,run,stored,len,work,cost⟩ := ih (k := k+1) (m := u) (by omega) step
+ let head := report maps p i m
+ obtain ⟨call,update,reads,ticks,choices⟩ := native maps p i m
+ have next : head.result = some ((k+1 : ℕ) : Word w) := by
+ change some ((k : Word w)+1) = _; simp
+ have combined : after m (eventLog (head::rs)) = after u (eventLog rs) := by
+ change after m (head.events++eventLog rs) = _
+ exact (List.foldl_append ..).trans (congrArg (fun s ↦ after s (eventLog rs)) update)
+ refine ⟨head::rs,?_,combined ▸ (by simpa only [Nat.add_assoc,Nat.add_comm 1 n] using stored),
+ by simp [len],?_,?_⟩
+ · rw [List.replicate_succ,runSegment]
+ rw [call]
+ change (runSegment W.program _ head.result (after m head.events) _).map _ = _
+ rw [next,update,run]; rfl
+ · intro r hr
+ rcases List.mem_cons.mp hr with rfl | hr
+ · exact ⟨ticks,reads,choices⟩
+ · exact work r hr
+ · change 1+countProbes head.events+RAMBuckets.cost Report.probes rs = _
+ rw [reads,cost]; omega
+
+/-- Exact terminal owner table, source-frame preservation and probe count on
+the real fixed instruction sequence. -/
+theorem scan_separate (maps : Bool) (p : Fin 4 → Word w) (m : Memory w) (N : ℕ)
+ (fits : (p 3).val+N ≤ 2^w)
+ (inputs : ∀ i : Word w, i.val
+ change some [] = some rs at h
+ rw [← Option.some.inj h]
+ simp [endState]
+ | succ n ih =>
+ rw [List.replicate_succ,runSegment,(native maps p start m).1] at h
+ cases eq : runSegment ((worker maps).table.instantiate w p).program (1+(code maps).length)
+ (some (start+1)) (after m (report maps p start m).events) (List.replicate n []) with
+ | none =>
+ change Option.map _ (runSegment _ _ (some (start+1)) _ _) = _ at h
+ rw [eq] at h; contradiction
+ | some ts =>
+ change Option.map _ (runSegment _ _ (some (start+1)) _ _) = _ at h
+ rw [eq] at h
+ rw [← Option.some.inj h]
+ change endState (some (start+1)) ts = _
+ simpa [Nat.cast_succ,add_assoc,add_comm,add_left_comm] using ih (start+1) _ ts eq
+
+end CompressorRecords.ResidentOwners
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentTerms.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentTerms.lean
new file mode 100644
index 0000000000..5d1fa455e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentTerms.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.CompressorShrinkOutputAllocation
+import OAI.Computability.VPVNP.CompressorRecordsSelectedFinish
+
+/-! # The selected shrinking rows in the allocated output pass
+
+The post-selection readback uses the cardinal-length motif order. The
+split worker uses the state numbering of the same ordered motifs. Their
+ten-word rows and all eight supply coordinates coincide.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkOutput
+
+open Compression Compression.PackingData Compression.ShrinkMotif MotifBlocks MotifGrid MotifConversion
+open BurstRAM ShrinkSliceSweep
+open scoped Classical
+
+variable {a b g w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+variable (B : S.Templates) (X : State a (packingLaneBits a g))
+variable (term stride selectors : Word w) (role retained : ℕ)
+
+set_option maxHeartbeats 1200000 in
+theorem resident_terms (sel : SelectedScore.Selection B X) (mem : Memory w)
+ (hs : SelectedScore.Stored B X sel (SelectedScore.headAt X (SelectedArena.scoreTables X term stride selectors)) mem) :
+ let T := splitBank (b := b) X B.shrink sel term stride.val role retained
+ Terms X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) T B.shrink X.packingWidth sel mem := by
+ intro T i
+ let m := (ShrinkMotifOrder.stateNumber X).symm i
+ let j := (SelectedScore.motifOrder X).entries.symm m
+ have hj : j.val = i.val := (ShrinkMotifOrder.entries_ordinal X m).trans (congrArg Fin.val ((ShrinkMotifOrder.stateNumber X).apply_symm_apply i))
+ have h := hs j
+ change TermRecordScan.Fields _ _ _ _ (sel ((SelectedScore.motifOrder X).entries j)).val _ _ at h
+ rw [show (SelectedScore.motifOrder X).entries j = m from (SelectedScore.motifOrder X).entries.apply_symm_apply _] at h
+ have addr : SelectedScore.headAt X (SelectedArena.scoreTables X term stride selectors) j = Fin.ofNat (2^w) (term.val+i.val*stride.val) := by
+ apply Fin.ext
+ simp only [SelectedScore.headAt, TermScores.rowBase, TermScores.word, SelectedArena.scoreTables, Fin.val_add, Fin.val_mul, Fin.val_ofNat, hj]
+ simp [Nat.add_mod, Nat.mul_mod]
+ rw [addr] at h
+ exact h
+
+end CompressorRecords.ShrinkOutput
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentsPlan.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentsPlan.lean
new file mode 100644
index 0000000000..9e84b765c6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentsPlan.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.CompressorShrinkResidentLayout
+import OAI.Computability.VPVNP.CompressorShrinkResidentOwners
+
+/-!
+# Native planner rows for the six-party resident directories
+
+Build hidden and map owner columns, clear their counters, append the dense
+ordinals, and publish the six absolute heads in level header cells 30–35.
+The chosen layout is read from the score comparison's actual output cell.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkResidentsPlan
+
+open BurstRAM BlockPlanner PhaseRecipe PrimedStackRAM ShrinkResidentLayout
+open scoped Fin.CommRing
+
+variable (I : SelectedPlan.Inputs) (first : Expr)
+
+/-- Number of dense resident IDs for the chosen kind, four per motif for hidden residents and
+six per motif for maps. -/
+def size (maps : Bool) := I.motifs.mul (.lit (radix maps))
+
+/-- Planner expression for the start of the owner column. Hidden owners start at `first`, and
+map owners start just after the hidden ID rows. -/
+def owner (maps : Bool) :=
+ if maps then ((first.add (size I false)).add I.newSites).add (size I false) else first
+
+/-- Planner address of the per-site counters, immediately after the owner column for this
+resident kind. -/
+def counts (maps : Bool) := (owner I first maps).add (size I maps)
+
+/-- Planner address of the resident ID rows, immediately after the count word for the last
+packed site. -/
+def rows (maps : Bool) := (counts I first maps).add I.newSites
+
+/-- First address after the map ID rows, which end the workspace for the two resident
+directories. -/
+def endAddr := (rows I first true).add (size I true)
+
+/-- The six operand expressions for resident collection, giving the resident count, owner base,
+site count, counter base, IDs per row, and ID row base. -/
+def bank (a : ℕ) (maps : Bool) : Fin 6 → Expr :=
+ ![size I maps,owner I first maps,I.newSites,counts I first maps,.lit (rowCapacity a maps),rows I first maps]
+
+/-- The three visits for one resident kind write each ID’s packed owner using the chosen
+layout, clear one counter per site, then append the IDs to their owners’ rows. -/
+def phases (absoluteCD : Expr) (a : ℕ) (maps : Bool) : List Visit :=
+ [ResidentOwners.visit maps (size I maps) absoluteCD (SelectedPlan.roleBase I) (SelectedPlan.layout I) (owner I first maps),
+ ops SliceRAM.clearOps 0 (.lit 0) I.newSites (fun _ => counts I first maps),
+ ops collectPreimage 3 (.lit 0) (size I maps) (bank I first a maps)]
+
+/-- The six directory bases in publication order, with owner, count, and ID row bases for
+hidden residents followed by the same three bases for maps. -/
+def heads : Fin 6 → Expr :=
+ ![owner I first false,counts I first false,rows I first false,owner I first true,counts I first true,rows I first true]
+
+/-- Six visits that write the resident directory bases to offsets 30 through 35 of the old
+level header. -/
+def publications (oldLevel : Expr) :=
+ List.ofFn fun i : Fin 6 => publish (oldLevel.add (.lit (30+i.val))) (heads I first i)
+
+/-- The complete resident schedule builds the hidden directory, builds the map directory, then
+publishes their six bases in the old level header. -/
+def visits (oldLevel absoluteCD : Expr) (a : ℕ) :=
+ phases I first absoluteCD a false ++ phases I first absoluteCD a true ++ publications I first oldLevel
+
+theorem visits_length (oldLevel absoluteCD : Expr) (a : ℕ) :
+ (visits I first oldLevel absoluteCD a).length = 12 := by simp [visits,phases,publications]
+
+section Words
+
+variable {w : ℕ} (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w) (L : Layout)
+local notation "ev" => Expr.eval pub st mem
+
+/-- Only the site count, motif count and start of the allocated arena vary
+across the linked levels. -/
+structure Ready : Prop where
+ sites : ev I.newSites = (L.sites : Word w)
+ motifs : ev I.motifs = (L.motifs : Word w)
+ arena : ev first = (L.first : Word w)
+
+variable (h : Ready I first pub st mem L)
+
+private theorem eval_add (a b : Expr) : ev (a.add b) = ev a + ev b := rfl
+private theorem eval_mul (a b : Expr) : ev (a.mul b) = ev a * ev b := rfl
+private theorem eval_lit (n : ℕ) : ev (.lit n) = (n : Word w) := rfl
+
+include h in
+theorem size_val (maps : Bool) : ev (size I maps) = (L.size maps : Word w) := by
+ simp only [size,Layout.size,eval_mul,eval_lit,h.motifs,Nat.cast_mul]
+
+include h in
+theorem owner_val (maps : Bool) : ev (owner I first maps) = (L.owner maps : Word w) := by
+ cases maps <;> simp [owner,Layout.owner,eval_add,h.arena,size_val I first pub st mem L h,h.sites,Nat.cast_add]
+
+include h in
+theorem counts_val (maps : Bool) : ev (counts I first maps) = (L.counts maps : Word w) := by
+ simp only [counts,Layout.counts,eval_add,owner_val I first pub st mem L h,size_val I first pub st mem L h,Nat.cast_add]
+
+include h in
+theorem rows_val (maps : Bool) : ev (rows I first maps) = (L.rows maps : Word w) := by
+ simp only [rows,Layout.rows,eval_add,counts_val I first pub st mem L h,h.sites,Nat.cast_add]
+
+include h in
+theorem end_val : ev (endAddr I first) = (L.endAddr : Word w) := by
+ simp only [endAddr,Layout.endAddr,eval_add,rows_val I first pub st mem L h,size_val I first pub st mem L h,Nat.cast_add]
+
+include h in
+theorem bank_val (a : ℕ) (maps : Bool) :
+ (fun i => ev (bank I first a maps i)) = L.params a maps w := by
+ funext i
+ fin_cases i <;> first | exact size_val I first pub st mem L h maps | exact owner_val I first pub st mem L h maps
+ | exact h.sites | exact counts_val I first pub st mem L h maps | rfl | exact rows_val I first pub st mem L h maps
+
+end Words
+end CompressorRecords.ShrinkResidentsPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledCharges.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledCharges.lean
new file mode 100644
index 0000000000..a567546199
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledCharges.lean
@@ -0,0 +1,177 @@
+import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables
+import OAI.Computability.VPVNP.CompressorShrinkSlotWindow
+import OAI.Computability.VPVNP.CompressorScheduledSlotRates
+import OAI.Computability.VPVNP.CompressorPublishedHeadWindows
+import OAI.Computability.VPVNP.CompressorShrinkLevelSpace
+
+/-! # Tapes and traffic of the three shrinking output windows
+
+The native AB, surviving-width, ordered-slot and canonical-copy reports all
+consume empty tapes. We count the calls of each scan and include the actual
+copy reports in the bound per incoming wire position. The same statements
+hold for the packet choices whenever the packets replay these reports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkScheduledCharges
+
+open BurstRAM Compression ShrinkBlockInputs ShrinkOutput ShrinkSliceSweep
+open SlotLevel ShrinkSlots ShrinkSlotPlan.Scheduled
+open scoped Classical Fin.CommRing
+open private motif_le packed_le from OAI.Computability.VPVNP.CompressorShrinkLevelSpace
+
+private theorem walk_tapes {J : Type*} {w : ℕ} {run : J → Memory w → List (Report w) → Prop}
+ {js : List J} {mem : Memory w} {rs : List (Report w)} (count : J → ℕ)
+ (walk : SourceWalk run js mem rs)
+ (one : ∀ j m log, run j m log → branchPaths log = List.replicate (count j) []) :
+ branchPaths rs = List.replicate ((js.map count).sum) [] := by
+ induction walk with
+ | done => rfl
+ | @next j js m head tail h _ ih =>
+ rw [branchPaths,List.map_append,← branchPaths,← branchPaths,one j m head h,ih,
+ List.map_cons,List.sum_cons,List.replicate_add]
+
+/-- Incoming positions pay for the AB and width rectangles, and for the
+ordered-slot scans and their physical transfers. All three rates depend
+only on the fixed degrees and the subdivisions of the template. -/
+def rate (a b : ℕ) :=
+ let d := 2^a
+ let q := ShrinkBundlePlan.cap a
+ let t := ShrinkBundlePlan.thickCount a
+ let u := ShrinkLevelSpace.subdivisionSum a b
+ let s : Shape := ⟨1,1,1,d,Shrink.colors a,Compression.ShrinkMotif.subdivisions d (Shrink.colors a) (2^b),2^b⟩
+ d*(2*(t+q)+16*(t*q)) + 18*(d*q)*u + ScheduledRates.slotRate s
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} {δ : ℝ} (X : State (a i) (packingLaneBits (a i) g))
+variable (ready : ShrinkMotif.Ready (2^(a i)) (Shrink.colors (a i)) (2^(b i)) δ) (sel : SelectedScore.Selection B X)
+variable (term stride abs : Word w) (start : ℕ) {I : ShrinkABSliceRecipe.Inputs}
+variable {pub : Fin 5 → Word w} {st : Word w} {ref m : Memory w} {first cap : ℕ} (width slotStart : ℕ)
+variable (dst : IncidenceDirectory w) (r : TablesRun w)
+
+local notation "sh" => levelShape (b := b i) X
+local notation "role" => SelectedArena.roleBase X term stride
+local notation "bank" => splitBank (b := b i) X B.shrink sel term (Fin.val stride) role width
+local notation "slotHead" => heads sh role slotStart
+local notation "Y" => X.shrinkNext B.shrink ready sel
+local notation "src" => directory sh slotHead w
+local notation "native" => r.remainder.slots
+local notation "raw" => r.remainder.postWidths
+local notation "copies" => CopyIncidence.reports Y src dst CopyIncidence.allColumns (after raw (eventLog (Build.Construction.all native)))
+local notation "bs" => ShrinkRankSpace.Shape.B (ShrinkInput.plan X start)
+local notation "ns" => ShrinkBundlePlan.thickCount (a i)
+local notation "nt" => ShrinkBundlePlan.cap (a i)
+local notation "nAB" => bs*(ns+nt+2*(ns*nt))
+local notation "nWidth" => motifCount X*Allocation.stride bank
+local notation "nSlot" => List.sum (List.map (Stage.limit sh) constructionOrder)
+local notation "nCopy" => 3*(Fintype.card (State.Base Y)*2^(b i))+3*(State.positions Y*2^(b i))
+local notation "allLogs" => r.reports++copies
+
+/-- Counts, costs and choice tapes for the four report lists in Parts 6–8. -/
+structure Accounted : Prop where
+ abCount : r.intersections.length = nAB
+ widthCount : r.remainder.widthRows.flatten.length = nWidth
+ slotCount : (native).all.length = nSlot
+ copyCount : (copies).length = nCopy
+ abTapes : branchPaths r.intersections = List.replicate nAB []
+ widthTapes : branchPaths r.remainder.widthRows.flatten = List.replicate nWidth []
+ slotTapes : branchPaths (native).all = List.replicate nSlot []
+ copyTapes : branchPaths copies = List.replicate nCopy []
+ abCost : RAMBuckets.cost Report.probes r.intersections ≤ bs*(2*(ns+nt)+16*(ns*nt))
+ widthCost : RAMBuckets.cost Report.probes r.remainder.widthRows.flatten = 18*nWidth
+ slotCost : RAMBuckets.cost Report.probes (native).all = slotProbes sh
+ copyCost : RAMBuckets.cost Report.probes copies = 9*(Fintype.card (State.Base Y)*2^(b i))+9*(State.positions Y*2^(b i))
+ linear : RAMBuckets.cost Report.probes allLogs ≤ X.positions*rate (a i) (b i)
+
+set_option maxHeartbeats 1400000 in
+/-- Account for the reports of a completed three-table run and the six copies
+which follow it in the ordered-slot window. -/
+theorem accounted (run : CompleteTables B i X ready sel term stride abs start I pub st ref first width slotStart cap m r) :
+ Accounted B i X ready sel term stride start width slotStart dst r := by
+ have ab := ScheduledRates.scheduledABCounts I pub st ref run.abRun
+ have abTapes := walk_tapes (fun _ ↦ bs) run.abRun (fun _ _ _ h ↦ ((runSegment_iff ..).mp h).2.2)
+ have abNumber : ((ShrinkABSliceRecipe.phases ns nt).map (fun _ ↦ bs)).sum = nAB := by
+ have eq := congrArg List.length abTapes
+ simpa only [branchPaths,List.length_map,List.length_replicate,ab.1] using eq.symm
+ rw [abNumber] at abTapes
+ have wc := run.remainder.sweep.calls
+ have widthBits : branchPaths r.remainder.widthRows.flatten = List.replicate nWidth [] := by
+ rw [← wc]
+ apply List.eq_replicate_iff.mpr
+ refine ⟨List.length_map _,?_⟩
+ intro tape ht
+ obtain ⟨rep,hr,rfl⟩ := List.mem_map.mp ht
+ obtain ⟨_,_,site⟩ := run.remainder.sweep.sites hr
+ exact site.bits
+ have slot := run.remainder.construction
+ have phases := construction_sources (ShrinkSlotCalendar.plan B i) sh slotHead (selectedLayout X B.shrink sel)
+ (bank).widthBase dst native raw slot.slots
+ have slotTapes := walk_tapes (Stage.limit sh) phases (fun _ _ _ h ↦ ((runSegment_iff ..).mp h).2.2)
+ have slotCount : (native).all.length = nSlot := by
+ simpa only [branchPaths,List.length_map,List.length_replicate] using congrArg List.length slotTapes
+ have cp := ScheduledRates.copyColumns Y src dst (after raw (eventLog (Build.Construction.all native)))
+ have copyBits : branchPaths copies = List.replicate nCopy [] := by
+ apply List.eq_replicate_iff.mpr
+ refine ⟨(List.length_map _).trans cp.2.1,?_⟩
+ intro tape ht
+ obtain ⟨rep,hr,rfl⟩ := List.mem_map.mp ht
+ exact (CopyIncidence.reports_work Y src dst CopyIncidence.allColumns _).2.2 rep hr |>.2.2
+ have widthCost : RAMBuckets.cost Report.probes r.remainder.widthRows.flatten = 18*nWidth := by
+ have c := run.remainder.probes
+ rw [Passes.reports,RAMBuckets.cost_append,← slot.probes] at c
+ exact Nat.add_right_cancel c
+ refine ⟨ab.1,wc,slotCount,cp.2.1,abTapes,widthBits,slotTapes,copyBits,ab.2.1,widthCost,
+ slot.probes,cp.2.2.1,?_⟩
+ have slotTotal := (ScheduledRates.selectedSlotProgram X B.shrink ready sel slotHead (bank).widthBase
+ dst raw native slot.slots).2.1
+ rw [Build.Construction.final_eq] at slotTotal
+ let d := 2^(a i)
+ let u := ShrinkLevelSpace.subdivisionSum (a i) (b i)
+ let abWeight := 2*(ns+nt)+16*(ns*nt)
+ have bFit : bs ≤ X.positions*d := Nat.mul_le_mul_right d (packed_le X)
+ have mFit : motifCount X ≤ X.positions*(d*nt) := motif_le X
+ have cAB := ab.2.1.trans (Nat.mul_le_mul_right abWeight bFit)
+ have cWidth : RAMBuckets.cost Report.probes r.remainder.widthRows.flatten ≤ 18*((X.positions*(d*nt))*u) :=
+ widthCost.le.trans (Nat.mul_le_mul_left 18 (Nat.mul_le_mul_right u mFit))
+ change RAMBuckets.cost Report.probes ((r.intersections++(r.remainder.widthRows.flatten++(native).all))++copies) ≤
+ X.positions*(d*abWeight+18*(d*nt)*u+ScheduledRates.slotRate sh)
+ rw [List.append_assoc,List.append_assoc,RAMBuckets.cost_append,RAMBuckets.cost_append]
+ calc
+ _ ≤ (X.positions*d)*abWeight+(18*((X.positions*(d*nt))*u)+X.positions*ScheduledRates.slotRate sh) :=
+ Nat.add_le_add cAB (Nat.add_le_add cWidth slotTotal)
+ _ = _ := by ring
+
+/-- The AB intersection probes depend on the widths. Once that observed charge
+is fixed, the remaining three scans have the following exact charge. -/
+theorem Accounted.exact_cost (h : Accounted B i X ready sel term stride start width slotStart dst r) :
+ RAMBuckets.cost Report.probes allLogs = RAMBuckets.cost Report.probes r.intersections +
+ (18*nWidth + slotProbes sh) + (9*(Fintype.card (State.Base Y)*2^(b i)) + 9*(State.positions Y*2^(b i))) := by
+ simp only [TablesRun.reports,Passes.reports,RAMBuckets.cost_append,h.widthCost,h.slotCost,h.copyCost]
+
+/-- The actual packet tapes and their source charge for the concatenation of
+all three windows. The only input about the packets is their verified native
+chronology and the equality of the four flattened report lists. -/
+theorem Accounted.packets (h : Accounted B i X ready sel term stride start width slotStart dst r)
+ {A : BlockPlanner.Script} (input : Memory w) (ps : List (SourceOnline.Packet A w))
+ (chron : SourceWalk.Chronological SourceOnline.Visit.Runs input ps)
+ (reports : ps.flatMap SourceWalk.Packet.reports = allLogs) :
+ ps.flatMap (fun p => p.stage.choices) = List.replicate (nAB+nWidth+nSlot+nCopy) [] ∧
+ RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) ≤ X.positions*rate (a i) (b i) := by
+ rw [PublishedHeads.chronological_tapes input ps chron,reports]
+ refine ⟨?_,h.linear⟩
+ have join (xs ys : List (Report w)) : branchPaths (xs++ys) = branchPaths xs++branchPaths ys := List.map_append
+ simp only [TablesRun.reports,Passes.reports,join,h.abTapes,h.widthTapes,h.slotTapes,h.copyTapes]
+ simp only [List.replicate_add,List.append_assoc]
+
+end CompressorRecords.ShrinkScheduledCharges
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledFinish.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledFinish.lean
new file mode 100644
index 0000000000..6aefed2465
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledFinish.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.CompressorShrinkScheduledOutput
+import OAI.Computability.VPVNP.CompressorShrinkScheduledTail
+
+/-! # The output graph and final history records of a scheduled shrinking step
+
+The selected geometry feeds the resident-directory builders, interval scans and
+canonical slot copies. The three final publications then run in the memory
+produced by those copies. Their endpoint is the exact last visit of the
+shrinking substep, including all static rectangle subdivisions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkScheduledFinish
+
+open BurstRAM Compression BlockPlanner DescriptorSpace SourceOnline
+open ShrinkBlockInputs ShrinkOutput
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+variable (base : Word w) (positions blocks round cap : ℕ)
+local notation "prog" => BlockProgram.script B
+local notation "space" => BlockProgram.layout B (Fin.val base) positions blocks
+local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog prog)) base
+local notation "fst" => Script.levelsPerBlock prog * round
+local notation "idx" => fst+i.val
+local notation "tab₀" => tableBase space idx (0 : Fin 6)
+local notation "oldInc" => packedIncidence space w idx (DemandRAM.oldCount X)
+local notation "P₀" => SourceOnline.Packet prog w
+local notation "ord" => ShrinkForward.first B i round
+
+/-- The four output windows occupy precisely the interval between the end
+of selected geometry and the first metadata publication. -/
+theorem output_length {m : Memory w} {a₅ a₆ a₇ a₈ : List P₀} {r : TablesRun w}
+ (out : ScheduledShrink.Output B i X sel base positions blocks round cap m a₅ a₆ a₇ a₈ r) :
+ 36 + (((a₅++a₆)++a₇)++a₈).length = ShrinkForward.visitsBefore B i 9 := by
+ let parts := BlockGroups.parts B i
+ have sizes := congrArg List.length out.indices
+ simp only [List.length_map,List.length_append] at sizes
+ have first : ShrinkForward.visitsBefore B i 5 = 36 := by
+ change ((BlockGroups.parts B i).take 5).flatten.length = 36
+ rw [show ((BlockGroups.parts B i).take 5).flatten = ShrinkBlockInputs.beforeSlices B
+ (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0) by
+ simp only [BlockGroups.parts,ShrinkBlockInputs.beforeSlices,List.take_succ_cons,
+ List.take_zero,List.flatten_cons,List.flatten_nil,List.append_nil,List.append_assoc]]
+ exact ShrinkBlockInputs.beforeSlices_length ..
+ have offset (j : ℕ) (live : j < 12) :
+ ShrinkForward.visitsBefore B i (j+1) = ShrinkForward.visitsBefore B i j +
+ (parts[j]'(by change j < 12; exact live)).length := by
+ simp only [ShrinkForward.visitsBefore,List.take_succ_eq_append_getElem
+ (show j < (BlockGroups.parts B i).length by change j<12; exact live),List.flatten_append,
+ List.flatten_cons,List.flatten_nil,List.append_nil,List.length_append,parts]
+ have h₅ : (ShrinkResidentPackets.window B i).indices.length = (parts[5]'(by change 5<12; decide)).length := List.length_ofFn
+ have h₆ : (BlockSlices.abWindow B i).indices.length = (parts[6]'(by change 6<12; decide)).length := List.length_ofFn
+ have h₇ : (SurvivingPackets.window B i).indices.length = (parts[7]'(by change 7<12; decide)).length := List.length_ofFn
+ have h₈ : (BlockGroups.shrink B i 8).indices.length = (parts[8]'(by change 8<12; decide)).length := List.length_ofFn
+ rw [h₅,h₆,h₇,h₈] at sizes
+ have e₅ := offset 5 (by decide)
+ have e₆ := offset 6 (by decide)
+ have e₇ := offset 7 (by decide)
+ have e₈ := offset 8 (by decide)
+ norm_num1 at e₅ e₆ e₇ e₈
+ simp only [List.length_append]
+ omega
+
+/-- The twenty-one final deterministic calls close the substep. -/
+theorem tail_length :
+ ShrinkForward.visitsBefore B i 9 + 21 = (BlockProgram.shrink B i).length := by
+ rw [← BlockGroups.parts_flatten]
+ rw [← List.take_append_drop 9 (BlockGroups.parts B i),List.flatten_append,List.length_append]
+ change ShrinkForward.visitsBefore B i 9 + 21 = ShrinkForward.visitsBefore B i 9 + _
+ apply congrArg (ShrinkForward.visitsBefore B i 9 + ·)
+ change 21 = 3+4+14
+ decide
+
+/-- All six output and publication lists retain their actual native executions.
+The metadata subgroup is a prefix of the three final publication groups. -/
+structure Finish (input : Memory w) (a₅ a₆ a₇ a₈ ms tail : List P₀) (r : TablesRun w) : Prop where
+ output : ScheduledShrink.Output B i X sel base positions blocks round cap input a₅ a₆ a₇ a₈ r
+ published : ShrinkScheduledTail.Result B base positions blocks round cap i X
+ (post input (((a₅++a₆)++a₇)++a₈)) ms tail
+ group : Group prog space base cap (ord+36) (directoryRows space) input ((((a₅++a₆)++a₇)++a₈)++tail)
+ length : 36 + ((((a₅++a₆)++a₇)++a₈)++tail).length = (BlockProgram.shrink B i).length
+
+theorem join {input : Memory w} {a₅ a₆ a₇ a₈ ms tail : List P₀} {r : TablesRun w}
+ (out : ScheduledShrink.Output B i X sel base positions blocks round cap input a₅ a₆ a₇ a₈ r)
+ (pubs : ShrinkScheduledTail.Result B base positions blocks round cap i X
+ (post input (((a₅++a₆)++a₇)++a₈)) ms tail) :
+ Finish B i X sel base positions blocks round cap input a₅ a₆ a₇ a₈ ms tail r := by
+ have sizes := output_length B i X sel base positions blocks round cap out
+ refine ⟨out,pubs,out.group.append ?_,?_⟩
+ · have h := pubs.group
+ change Group prog space base cap ((ord+36)+_) _ _ _
+ rw [Nat.add_assoc,sizes]; exact h
+ · rw [List.length_append,← Nat.add_assoc,sizes,pubs.length,tail_length]
+
+end CompressorRecords.ShrinkScheduledFinish
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledGeometry.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledGeometry.lean
new file mode 100644
index 0000000000..e587b77985
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledGeometry.lean
@@ -0,0 +1,174 @@
+import OAI.Computability.VPVNP.CompressorShrinkScheduledPrefix
+import OAI.Computability.VPVNP.CompressorShrinkSelectedGroup
+import OAI.Computability.VPVNP.CompressorShrinkGeometryHeadRetention
+import OAI.Computability.VPVNP.CompressorSourceGroupSplit
+import OAI.Computability.VPVNP.CompressorBlockShrinkPrefixFits
+
+/-!
+# The shrinking calendar through the selected geometry
+
+The first twenty-one visits prepare the physical selector input. One visit
+runs the prescribed selection. The following fourteen visits score its
+terms and build the selected placement, role, and child directories.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkScheduledGeometry
+
+open BurstRAM BlockPlanner DescriptorSpace Compression BlockHeaderRun SourceOnline SourceTransport
+open ShrinkSlots SlotLevel
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem below_data {A : Script} {L : Layout} {base : Word w} {cap ord total : ℕ}
+ {m : Memory w} {ps : List (Packet A w)} (run : Group A L base cap ord total m ps)
+ {x : ℕ} (hx : x < levelStart L 0) : post m ps x = m x := by
+ apply after_outside m (data := (levelStart L 0 ≤ ·)) _ (Nat.not_le_of_gt hx)
+ intro a value ha
+ change Event.write a value ∈ (ps.flatMap SourceWalk.Packet.reports).flatMap Report.events at ha
+ obtain ⟨r,hr,ev⟩ := List.mem_flatMap.mp ha
+ obtain ⟨q,hq,hr⟩ := List.mem_flatMap.mp hr
+ exact (run.checked q hq).write a value (List.mem_flatMap.mpr ⟨r,hr,ev⟩)
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps)
+variable {g w : ℕ} (X : GreedyArena.ShrinkingState (ShrinkBlockInputs.a i) g)
+variable (sel : SelectedScore.Selection B X) (tape : List Bool) (base : Word w) (positions blocks t : ℕ)
+local notation "prog" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog (BlockProgram.script B))) base
+local notation "first" => (S.steps+1)*t
+local notation "level" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape
+local notation "offset" => List.length (Script.initial prog)+t*List.length (Script.block prog)+List.length (BlockIndex.earlier B i)
+local notation "total" => directoryRows L
+local notation "H" => levelStart L 0
+local notation "Pkt" => SourceOnline.Packet prog w
+variable (old new : Fin (BlockProgram.layout B base.val positions blocks).levels) (m : Memory w)
+local notation "start" => tableBase L old (0 : Fin 6)
+local notation "T" => packedIncidence L w old (DemandRAM.oldCount X)
+local notation "initial" => finalMemory level L old new m
+local notation "headers" => BlockHeaderRun.reports level L old new m
+local notation "s" => levelShape (b := ShrinkBlockInputs.b i) X
+local notation "rawHeader" => ShrinkHeaderReads.Header i X T start L first
+local notation "headBank" => PortRefresh.TraversalHeaders.HeadBank L
+
+set_option maxHeartbeats 1800000
+
+/-- A scheduled execution of shrink geometry in 36 packets. The 21 prefix packets, selector and
+14 suffix packets reproduce the branch events and leave the required headers and head banks
+in memory before output. -/
+structure Result (fuel : ℕ) (p : ShrinkBranch.Prefix X T start fuel initial)
+ (v : ShrinkBranch.Selected B X T start (10 : Word w) (B.shrink.selectorBits : Word w) fuel initial p sel) (cap : ℕ) (pre : List Pkt) (selector : Pkt) (tail : List Pkt) : Prop where
+ prefixGroup : Group prog L base cap offset total m pre
+ prefixLength : pre.length = 21
+ prefixEmpty : ∀ q ∈ pre, ∀ bs ∈ q.stage.choices, bs = []
+ prefixReports : pre.flatMap SourceWalk.Packet.reports = headers++p.reports
+ prefixPost : post m pre = p.beforeTerm
+ selected : Group prog L base cap (offset+21) total p.beforeTerm [selector]
+ selectInput : selector.input = p.beforeTerm
+ selectStage : selector.stage = ShrinkTermOnline.globalVisit B i X T start sel fuel .select
+ selectChoices : selector.stage.choices = List.ofFn (ShrinkTermSelection.tapes B.shrink X sel w)
+ selectReports : selector.reports = v.terms
+ selectOutput : selector.output = after p.beforeTerm (eventLog v.terms)
+ suffix : Group prog L base cap (offset+22) total selector.output tail
+ suffixLength : tail.length = 14
+ suffixEmpty : ∀ q ∈ tail, ∀ bs ∈ q.stage.choices, bs = []
+ suffixTapes : tail.flatMap (fun q => q.stage.choices) = List.replicate (SelectedTailPackets.selectedCalls X) []
+ suffixEvents : eventLog (tail.flatMap SourceWalk.Packet.reports) = eventLog v.geometry.reports
+ whole : Group prog L base cap offset total m (pre++selector::tail)
+ length : (pre++selector::tail).length = 36
+ events : eventLog ((pre++selector::tail).flatMap SourceWalk.Packet.reports) =
+ eventLog ((headers++p.reports)++v.reports)
+ final : post m (pre++selector::tail) = v.beforeOutput
+ beforeHeader : rawHeader p.beforeTerm
+ beforeRows : p.beforeTerm (pt).rows.val = (total : Word w)
+ beforePitch : p.beforeTerm ((pt).directory-1).val = (levelWords L : Word w)
+ header : rawHeader v.beforeOutput
+ rows : v.beforeOutput (pt).rows.val = (total : Word w)
+ pitch : v.beforeOutput ((pt).directory-1).val = (levelWords L : Word w)
+ oldHeads : headBank old (DemandRAM.oldCount X) v.beforeOutput
+ nextHeads : headBank new (actualCount s) v.beforeOutput
+ frame : ∀ x, x < start ∨ levelStart L new ≤ x → v.beforeOutput x = initial x
+
+/-- Join the deterministic prefix, prescribed selector and deterministic
+geometry at their exact calendar ordinals and machine memories. -/
+theorem run (fuel : ℕ) (p : ShrinkBranch.Prefix X T start fuel initial)
+ (v : ShrinkBranch.Selected B X T start (10 : Word w) (B.shrink.selectorBits : Word w) fuel initial p sel) (oldAt : first+i.val=old.val) (next : old.val+1=new.val)
+ (sub : Substep level L old new (by change 6 ≤ 54; decide) m)
+ (fits : ShrinkBranch.PrefixFits B X T start (10 : Word w) fuel)
+ (oldHeads : headBank old (DemandRAM.oldCount X) m)
+ (low : ∀ c, H ≤ ((T).column c).val) (room : endAddress L < 2^w)
+ (sitesFit : X.positions ≤ positions) (within : t < blocks)
+ (rows : m (pt).rows.val = (total : Word w)) (pitch : m ((pt).directory-1).val = (levelWords L : Word w))
+ (cap : ℕ) (headerClock : ShrinkHeaderGreedyPackets.clock B i ≤ cap)
+ (denseClock : scanCap prog (ShrinkBundlePackets.maxFuel B i) ≤ cap)
+ (termClock : scanCap prog fuel ≤ cap) (geometryClock : scanCap prog 65 ≤ cap) :
+ ∃ pre selector tail, Result B f hf i X sel tape base positions blocks t old new m fuel p v cap pre selector tail := by
+ have stride : (10 : Word w).val = 10 := Nat.le_antisymm (Nat.mod_le ..) fits.wide
+ have termRoom := fits.termRoom
+ rw [stride] at termRoom
+ have heads (c : Fin 6) : m (incidenceHead L old c) = (T).column c := by
+ rw [packed_column]; exact oldHeads.incidence c
+ obtain ⟨pre,selector,gp,npre,empty,plogs,ppost,hin,stage,choices,logs,gs,spost,before⟩ :=
+ ShrinkScheduledPrefix.through_selection B f hf i X sel tape base positions blocks t old new m T
+ oldAt next sub fuel p v heads (oldHeads.tables (0 : Fin 6)) low room termRoom rows pitch within cap headerClock
+ denseClock fits.gatherClock termClock
+ have hH := (levelStart_mono L (Nat.zero_le (L).levels)).trans_lt room
+ have cells := Window.lowCells (A := prog) L base rfl rfl hH
+ have beforeRows : p.beforeTerm (pt).rows.val = (total : Word w) := by
+ exact (congrFun ppost _).symm.trans ((below_data gp cells.1).trans rows)
+ have beforePitch := before.entry.pitch
+ have geomRoom := ShrinkBranch.selected_geometry_fit B i X base.val positions blocks old sitesFit room
+ obtain ⟨tail,gt,ntail,tailEvents,tailPost,tailChoices⟩ :=
+ SelectedTailPackets.selected_group B i X T start base positions blocks t sel initial fuel cap
+ p v fits geomRoom before.raw before.fieldsBelow low beforeRows beforePitch within room geometryClock
+ have selectGroup := gs.split.2
+ rw [npre,ppost] at selectGroup
+ have selectOut : selector.output = after p.beforeTerm (eventLog v.terms) := by
+ simp only [SourceWalk.Packet.output,hin,logs]
+ have full := gs.append (by
+ rw [spost,List.length_append,List.length_singleton,npre]; exact gt)
+ have postFull : post m (pre++selector::tail) = v.beforeOutput := by
+ have joined := (post_append m (pre++[selector]) tail).trans
+ ((congrArg (fun z => post z tail) spost).trans tailPost)
+ simpa only [List.append_assoc,List.singleton_append] using joined
+ have gfull : Group prog L base cap offset total m (pre++selector::tail) := by
+ simpa only [List.append_assoc,List.singleton_append] using full
+ have keep (x : ℕ) (hx : x < start) : v.beforeOutput x = p.beforeTerm x := by
+ have ranges := ShrinkInput.range_bounds X start
+ have oldLimit := hx.trans_le (ranges.1.trans (ranges.2.1.trans (ranges.2.2.1.trans ranges.2.2.2)))
+ have stopFit : ShrinkInput.stop X start < 2^w := by unfold ShrinkInput.termEnd at termRoom; omega
+ have daddr : (ShrinkInput.demandHead (w := w) X start).val = ShrinkInput.stop X start := Nat.mod_eq_of_lt stopFit
+ exact (v.lowerFrame x oldLimit).trans (p.gatherRun.frame x (.inl (by
+ change x < (ShrinkInput.demandHead (w := w) X start).val; rwa [daddr]))).symm
+ have afterHeader := before.keep_below keep
+ have banks := ShrinkGeometryHeadBanks.beforeOutput_heads B i X sel base.val positions blocks old new
+ f hf tape next m sub p v oldHeads sitesFit room
+ have frame := ShrinkGeometryHeadBanks.beforeOutput_frame B i X sel base.val positions blocks old new
+ next p v sitesFit room
+ refine ⟨pre,selector,tail,gp,npre,empty,plogs,ppost,selectGroup,hin,stage,choices,logs,selectOut,
+ selectOut.symm ▸ gt,ntail,?_,tailChoices,tailEvents,gfull,?_,?_,postFull,before.raw,beforeRows,beforePitch,
+ afterHeader.raw,?_,afterHeader.entry.pitch,banks.1,banks.2,frame⟩
+ · intro q hq bs hb
+ have hmem : bs ∈ tail.flatMap (fun q => q.stage.choices) := List.mem_flatMap.mpr ⟨q,hq,hb⟩
+ rw [tailChoices] at hmem
+ exact (List.mem_replicate.mp hmem).2
+ · rw [List.length_append,List.length_cons,npre,ntail]
+ · simp only [List.flatMap_append,List.flatMap_cons,plogs,logs,ShrinkBranch.Selected.reports,
+ eventLog,List.append_assoc] at tailEvents ⊢
+ rw [tailEvents]
+ · rw [← postFull]; exact (below_data gfull cells.1).trans rows
+
+end CompressorRecords.ShrinkScheduledGeometry
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledOutput.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledOutput.lean
new file mode 100644
index 0000000000..21700e2268
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledOutput.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.CompressorShrinkScheduledResidents
+import OAI.Computability.VPVNP.CompressorShrinkTablesPhysical
+import OAI.Computability.VPVNP.CompressorShrinkABSliceGroup
+import OAI.Computability.VPVNP.CompressorShrinkSurvivingPackets
+import OAI.Computability.VPVNP.CompressorShrinkSlotPhysicalGroup
+import OAI.Computability.VPVNP.CompressorShrinkScheduledRetention
+
+/-! # The four post-selection groups of a physical shrinking substep
+
+On each admitted branch the hidden/map directory visits precede the AB
+intervals, the four surviving-role scans and the ordered-slot/copy visits.
+The AB and surviving packets use the actual reports of the same three-table
+construction. The final memory carries the new canonical incidence directory
+and all old-level data read by the backward traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ScheduledShrink
+
+open BurstRAM Compression ShrinkBlockInputs DescriptorSpace SourceOnline BlockPlanner ShrinkOutput
+open SlotLevel ShrinkSlots ShrinkSliceSweep
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+variable (base : Word w) (positions blocks round : ℕ)
+local notation "prog" => BlockProgram.script B
+local notation "space" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog prog)) base
+local notation "pub" => Schedule.Ports.data pt
+local notation "first₀" => Script.levelsPerBlock prog * round
+local notation "old₀" => first₀+i.val
+local notation "next₀" => old₀+1
+local notation "tab" => (fun j : Fin 6 => tableBase space old₀ j)
+local notation "st₀" => (levelStart space first₀ : Word w)
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "abs₀" => ShrinkResidentPackets.absoluteWord (w := w) X (tab 0)
+local notation "T" => packedIncidence space w old₀ (DemandRAM.oldCount X)
+local notation "sh" => levelShape (b := b i) X
+local notation "Pkt" => SourceOnline.Packet prog w
+local notation "headWords" => PortRefresh.TraversalHeaders.HeadBank space
+local notation "I" => BlockSlices.abInputs i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 1)
+local notation "part₅" => ShrinkResidentPackets.window B i
+local notation "part₆" => BlockSlices.abWindow B i
+local notation "part₇" => SurvivingPackets.window B i
+local notation "part₈" => BlockGroups.shrink B i 8
+local notation "h" => ShrinkOutput.heads sh (SelectedArena.roleBase X term (10 : Word w)) (tab 3)
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "dst" => packedIncidence space w next₀ (actualCount sh)
+
+private theorem offset_succ {j : ℕ} (hj : j+1 < 12) :
+ (BlockGroups.shrink B i ⟨j+1,hj⟩).before.length =
+ (BlockGroups.shrink B i ⟨j,by omega⟩).before.length+
+ ((BlockGroups.parts B i)[j]'(by change j < 12; omega)).length := by
+ rw [BlockGroups.shrink_offset,BlockGroups.shrink_offset]
+ simp only [List.take_succ_eq_append_getElem (show j < (BlockGroups.parts B i).length by change j < 12; omega),
+ List.flatten_append,List.flatten_cons,List.flatten_nil,List.append_nil,List.length_append,Nat.add_assoc]
+
+/-- A consecutive trace and the native reports consumed by its calendar windows. -/
+structure Output (cap : ℕ) (input : Memory w) (ps₅ ps₆ ps₇ ps₈ : List Pkt) (r : TablesRun w) : Prop where
+ residents : Residents B i X sel base positions blocks round cap input ps₅
+ tables : CompleteTables B i X (S.shrink i) sel term 10 abs₀ (tab 0) I pub st₀ (post input ps₅)
+ (tab 1) (tab 2) (tab 3) cap (post input ps₅) r
+ abReports : ps₆.flatMap SourceWalk.Packet.reports = r.intersections
+ widthReports : ps₇.flatMap SourceWalk.Packet.reports = r.remainder.widthRows.flatten
+ slotReports : ps₈.flatMap SourceWalk.Packet.reports = r.remainder.slots.all ++
+ CopyIncidence.reports Y (directory sh h w) dst CopyIncidence.allColumns
+ (after r.remainder.postWidths (eventLog r.remainder.slots.all))
+ group : Group prog space base cap ((prog).initial.length+round*(prog).block.length+(BlockIndex.earlier B i).length+36)
+ (directoryRows space) input (((ps₅++ps₆)++ps₇)++ps₈)
+ indices : (((ps₅++ps₆)++ps₇)++ps₈).map (fun p => p.stage.phase) =
+ (((part₅).indices++(part₆).indices)++(part₇).indices)++(part₈).indices
+ postWidth : post input ((ps₅++ps₆)++ps₇) = r.remainder.postWidths
+ readbacks : ScheduledReadbacks B i X sel base positions blocks round T (post input (((ps₅++ps₆)++ps₇)++ps₈))
+
+set_option maxHeartbeats 2600000 in
+theorem output (fuel cap : ℕ) {initial : Memory w} (p : ShrinkBranch.Prefix X T (tab 0) fuel initial)
+ (v : ShrinkBranch.Selected B X T (tab 0) 10 (B.shrink.selectorBits : Word w) fuel initial p sel)
+ (hp : ShrinkBranch.PrefixFits B X T (tab 0) 10 fuel)
+ (header : ShrinkHeaderReads.Header i X T (tab 0) space first₀ v.beforeOutput)
+ (oldHeads : headWords old₀ (DemandRAM.oldCount X) v.beforeOutput)
+ (nextHeads : headWords next₀ (actualCount sh) v.beforeOutput)
+ (rows : v.beforeOutput (pt).rows.val = (directoryRows space : Word w))
+ (pitch : v.beforeOutput ((pt).directory-1).val = (levelWords space : Word w))
+ (live : round < blocks) (sites : X.positions ≤ positions) (room : endAddress space < 2^w)
+ (arithmetic : TableArithmetic B i X w) (clock : scanCap prog 95 ≤ cap) :
+ ∃ ps₅ ps₆ ps₇ ps₈ r, Output B i X sel base positions blocks round cap v.beforeOutput ps₅ ps₆ ps₇ ps₈ r := by
+ have clockAt (n : ℕ) (hn : n ≤ 95) : scanCap prog n ≤ cap := by unfold scanCap at *; omega
+ have sourceCap : 95 ≤ cap := by unfold scanCap at clock; omega
+ obtain ⟨ps₅,res⟩ := residents B i X sel base positions blocks round fuel cap p v hp header oldHeads nextHeads
+ rows pitch sites room live (clockAt 40 (by decide))
+ let m := post v.beforeOutput ps₅
+ obtain ⟨r,native,abArgs⟩ := withAB_physical B i X base positions blocks round T m (S.shrink i) sel
+ live sites room arithmetic res.header res.pitch (res.oldHeads.tables (1 : Fin 6)) res.tables cap sourceCap
+ (lt_of_lt_of_le (by decide : SurvivingNative.ops.length < 95) sourceCap)
+ have entry : LevelFields.Entry space first₀ pub st₀ m := ⟨rfl,res.pitch⟩
+ obtain ⟨ps₆,logs₆,g₆,ids₆,_⟩ := BlockSlices.build_packets_of_run B i X base positions blocks round
+ m live sites room arithmetic.widthRoom res.rows res.pitch (res.header.reads B entry)
+ (res.oldHeads.tables (1 : Fin 6)) res.tables.demand m cap r.intersections abArgs native.abRun cap clock
+ have post₆ : post m ps₆ = r.postAB m := by rw [post,logs₆]; rfl
+ obtain ⟨ps₇,g₇,ids₇,logs₇,post₇⟩ := SurvivingPackets.group B i X T base positions blocks round sel
+ (S.shrink i) m m cap cap r native live sites room res.header (res.oldHeads.tables (2 : Fin 6))
+ res.rows res.pitch (clockAt _ (by decide))
+ obtain ⟨ps₈,g₈,ids₈,logs₈,incidence,_⟩ := ShrinkSlotCalendar.physical_group B i X base positions blocks round
+ T sel abs₀ I m m cap r live sites room res.rows res.pitch res.header (DemandRAM.oldCount X)
+ res.oldHeads res.nextHeads res.tables native cap (clockAt 49 (by decide))
+ have abLength : ps₆.length = ((BlockGroups.parts B i)[6]'(by change 6 < 12; decide)).length := by
+ change ps₆.length = (BlockSlices.intersections i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 1)).length
+ simpa only [List.length_map,Window.indices,List.length_ofFn] using congrArg List.length ids₆
+ have widthLength : ps₇.length = ((BlockGroups.parts B i)[7]'(by change 7 < 12; decide)).length := by
+ change ps₇.length = (BlockSlices.surviving B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 2)).length
+ simpa only [List.length_map,Window.indices,List.length_ofFn] using congrArg List.length ids₇
+ have e₆ := BlockSlices.abWindow_offset B i
+ have e₇ : (part₇).before.length = (part₆).before.length+ps₆.length := by rw [abLength]; exact offset_succ B i (j := 6) (by decide)
+ have e₈ : (part₈).before.length = (part₇).before.length+ps₇.length := by rw [widthLength]; exact offset_succ B i (j := 7) (by decide)
+ have g₅₆ := res.group.append (show Group prog space base cap
+ ((prog).initial.length+round*(prog).block.length+(BlockIndex.earlier B i).length+36+ps₅.length)
+ (directoryRows space) m ps₆ by convert g₆ using 1; rw [e₆,res.length]; omega)
+ have after₆ : post v.beforeOutput (ps₅++ps₆) = r.postAB m := (post_append ..).trans post₆
+ have g₅₆₇ := g₅₆.append (show Group prog space base cap
+ ((prog).initial.length+round*(prog).block.length+(BlockIndex.earlier B i).length+36+(ps₅++ps₆).length)
+ (directoryRows space) (post v.beforeOutput (ps₅++ps₆)) ps₇ by
+ rw [after₆]; convert g₇ using 1
+ rw [List.length_append,res.length,e₇,e₆]; omega)
+ have after₇ : post v.beforeOutput ((ps₅++ps₆)++ps₇) = r.remainder.postWidths := by
+ rw [post_append,after₆,post₇]
+ have all := g₅₆₇.append (show Group prog space base cap
+ ((prog).initial.length+round*(prog).block.length+(BlockIndex.earlier B i).length+36+((ps₅++ps₆)++ps₇).length)
+ (directoryRows space) (post v.beforeOutput ((ps₅++ps₆)++ps₇)) ps₈ by
+ rw [after₇]; convert g₈ using 1
+ rw [List.length_append,List.length_append,res.length,e₈,e₇,e₆]; omega)
+ refine ⟨ps₅,ps₆,ps₇,ps₈,r,res,native,logs₆,logs₇,logs₈,all,?_,after₇,?_⟩
+ · simp only [List.map_append,res.indices,ids₆,ids₇,ids₈]
+ · rw [post_append,after₇]
+ exact scheduled_readbacks B i X sel base positions blocks round T I m m cap r ps₈ live sites room res.tables
+ ⟨res.published,res.directories⟩ native logs₈ incidence
+
+end CompressorRecords.ScheduledShrink
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledPrefix.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledPrefix.lean
new file mode 100644
index 0000000000..33ea755104
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledPrefix.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.CompressorShrinkHeaderGreedyPackets
+import OAI.Computability.VPVNP.CompressorShrinkHeaderGreedyTapes
+import OAI.Computability.VPVNP.CompressorShrinkBundlePrepared
+import OAI.Computability.VPVNP.CompressorShrinkTermGroup
+import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch
+
+/-! # The actual shrinking calendar up to the selected term rows
+
+The same memory that receives the three header publications feeds the greedy,
+placement, bundle, and absolute-ID workers. The gather and the term selection
+then use the demand widths computed by those workers. The complete prefix
+has twenty-two visits at their concrete global ordinals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkScheduledPrefix
+
+open BurstRAM BlockPlanner DescriptorSpace Compression BlockHeaderRun SourceOnline
+open scoped Fin.CommRing
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps)
+variable {g w : ℕ} (X : GreedyArena.ShrinkingState (ShrinkBlockInputs.a i) g)
+variable (sel : SelectedScore.Selection B X) (tape : List Bool) (base : Word w)
+variable (positions blocks t : ℕ)
+local notation "scr" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B (Fin.val base) positions blocks
+local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog (BlockProgram.script B))) base
+local notation "H" => levelStart L 0
+local notation "first" => (S.steps+1)*t
+local notation "v" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape
+local notation "atStart" => List.length (Script.initial scr)+t*List.length (Script.block scr)+List.length (BlockIndex.earlier B i)
+
+variable (old new : Fin (BlockProgram.layout B (Fin.val base) positions blocks).levels) (m : Memory w) (T : IncidenceDirectory w)
+local notation "start" => tableBase L old (0 : Fin 6)
+local notation "headPost" => finalMemory v L old new m
+local notation "hdr" => ShrinkGreedyHeaderValues.Header i X T L first start (Schedule.Ports.data pt) (levelStart L first : Word w)
+local notation "Pkt" => SourceOnline.Packet scr w
+
+set_option maxHeartbeats 1200000 in
+/-- The physical reports and memory before the first gather, together with the
+published fields the term planner will read in that memory. -/
+theorem before_gather (oldAt : first+i.val=old.val) (next : old.val+1=new.val)
+ (sub : Substep v L old new (by change 6 ≤ 54; decide) m) (fuel : ℕ)
+ (p : ShrinkBranch.Prefix X T start fuel headPost)
+ (heads : ∀ c : Fin 6, m (incidenceHead L old c)=T.column c)
+ (scratch : m (tableHead L old (0 : Fin 6))=(start : Word w))
+ (low : ∀ c, H ≤ (T.column c).val)
+ (fit : endAddress L < 2^w) (room : ShrinkInput.stop X start < 2^w)
+ (rows : m (pt).rows.val=(directoryRows L : Word w))
+ (pitch : m ((pt).directory-1).val=(levelWords L : Word w))
+ (within : t < blocks) (cap : ℕ) (headClock : ShrinkHeaderGreedyPackets.clock B i ≤ cap)
+ (denseClock : scanCap scr (ShrinkBundlePackets.maxFuel B i) ≤ cap) :
+ ∃ ps : List Pkt, Group scr L base cap atStart (directoryRows L) m ps ∧ ps.length=20 ∧
+ ps.flatMap SourceWalk.Packet.reports =
+ (BlockHeaderRun.reports v L old new m ++ p.input.reports) ++ p.absolute ∧
+ post m ps = after p.input.post (eventLog p.absolute) ∧
+ hdr headPost ∧ hdr (after p.input.post (eventLog p.absolute)) ∧
+ (∀ q ∈ ps, ∀ bs ∈ q.stage.choices, bs = []) := by
+ let absMem := after p.input.post (eventLog p.absolute)
+ have hH : H < 2^w := (levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit
+ have cells := Window.lowCells (A:=scr) L base (BlockProgram.layout_arity B ..).symm rfl hH
+ have here := levelStart_mono L (Nat.zero_le old.val)
+ have entry : LevelFields.Entry L first (pt).data (levelStart L first : Word w) m := ⟨rfl,pitch⟩
+ have header : hdr headPost := ShrinkGreedyHeaderValues.post_header B i X f hf sel tape base positions blocks
+ T first old new oldAt.symm next.symm m sub fit _ _ entry (cells.2.trans_le here) heads scratch
+ have postRows := (sub.before v next (pt).rows.val (cells.1.trans_le here)).trans rows
+ obtain ⟨hs,hg,phases,hlogs,hpost⟩ := ShrinkHeaderGreedyPackets.group B f hf i X sel tape base
+ positions blocks t old new oldAt next m sub T p.input.greedy heads scratch low fit rows pitch within cap headClock
+ obtain ⟨ds,dg,labels,dlogs,dpost⟩ := ShrinkBundlePackets.group B i X T start base positions blocks t
+ p.input p.absolute p.absoluteRun room low within header postRows cap denseClock
+ have hlen : hs.length=9 := by
+ calc
+ hs.length = (ShrinkHeaderGreedyPackets.window B i).indices.length := by
+ simpa only [List.length_map] using congrArg List.length phases
+ _ = (ShrinkHeaderGreedyPackets.visits B i).length := List.length_ofFn
+ _ = 9 := ShrinkHeaderGreedyPackets.visits_length B i
+ have dlen : ds.length=11 := by
+ calc
+ ds.length = ShrinkBundlePackets.stages.length := by
+ simpa only [List.length_map,List.length_ofFn] using congrArg List.length labels
+ _ = 11 := by decide
+ rw [ShrinkBundlePackets.startOrdinal_eq] at dg
+ have together := hg.append (by rw [hpost,hlen]; exact dg)
+ have floor : start ≤ (ShrinkInput.plan X start).gathered := by
+ have pre := (ShrinkInput.range_bounds X start).1.trans (ShrinkInput.range_bounds X start).2.1
+ apply pre.trans
+ change ShrinkInput.rankBase X start ≤ ((ShrinkInput.rankBase X start + 2*(ShrinkInput.plan X start).A) +
+ 2*(ShrinkInput.plan X start).B) + (ShrinkInput.plan X start).rectangleSize
+ omega
+ have keep (x : ℕ) (hx : x < start) : absMem x = headPost x :=
+ (p.absoluteRun.frame x (.inl (hx.trans_le floor))).trans (p.input.below x hx)
+ have hempty := ShrinkHeaderGreedyPackets.empty_choices v sub p.input.greedy hg.chronological hlogs
+ have dempty (q : Pkt) (hq : q ∈ ds) (bits : List Bool) (hb : bits ∈ q.stage.choices) : bits = [] := by
+ have mem : q.stage ∈ ds.map SourceWalk.Packet.stage := List.mem_map_of_mem hq
+ rw [labels,List.mem_ofFn] at mem
+ obtain ⟨j,hj⟩ := mem
+ rw [← hj] at hb
+ exact (List.mem_replicate.mp hb).2
+ refine ⟨hs++ds,together,by rw [List.length_append,hlen,dlen],?_,?_,header,header.keep_below keep,?_⟩
+ · rw [List.flatMap_append,hlogs,dlogs]
+ simp only [ShrinkInput.Run.reports,ShrinkBundlePlan.Scheduled.preparationReports,List.append_assoc]
+ · rw [post_append,hpost,dpost]
+ · intro q hq bs hb
+ exact (List.mem_append.mp hq).elim (fun h => hempty q h bs hb) (fun h => dempty q h bs hb)
+
+set_option maxHeartbeats 1200000 in
+/-- The first twenty-one visits are deterministic. The final packet runs the
+true term worker on the memory built by the preceding gather, and its tapes
+are the ordered words of the prescribed shrinking selection. -/
+theorem through_selection (oldAt : first+i.val=old.val) (next : old.val+1=new.val)
+ (sub : Substep v L old new (by change 6 ≤ 54; decide) m) (fuel : ℕ)
+ (p : ShrinkBranch.Prefix X T start fuel headPost)
+ (chosen : ShrinkBranch.Selected B X T start (10 : Word w) (B.shrink.selectorBits : Word w)
+ fuel headPost p sel)
+ (heads : ∀ c : Fin 6, m (incidenceHead L old c)=T.column c)
+ (scratch : m (tableHead L old (0 : Fin 6))=(start : Word w)) (low : ∀ c, H ≤ (T.column c).val)
+ (fit : endAddress L < 2^w) (room : ShrinkInput.termEnd X start 10 < 2^w)
+ (rows : m (pt).rows.val=(directoryRows L : Word w)) (pitch : m ((pt).directory-1).val=(levelWords L : Word w))
+ (within : t < blocks) (cap : ℕ) (headClock : ShrinkHeaderGreedyPackets.clock B i ≤ cap)
+ (denseClock : scanCap scr (ShrinkBundlePackets.maxFuel B i) ≤ cap)
+ (gatherClock : ShrinkDemandGather.cost < fuel) (termClock : scanCap scr fuel ≤ cap) :
+ ∃ pre : List Pkt, ∃ last : Pkt,
+ Group scr L base cap atStart (directoryRows L) m pre ∧ pre.length=21 ∧
+ (∀ q ∈ pre, ∀ bs ∈ q.stage.choices, bs = []) ∧
+ pre.flatMap SourceWalk.Packet.reports = BlockHeaderRun.reports v L old new m ++ p.reports ∧
+ post m pre = p.beforeTerm ∧ last.input = p.beforeTerm ∧
+ last.stage = ShrinkTermOnline.globalVisit B i X T start sel fuel .select ∧
+ last.stage.choices = List.ofFn (ShrinkTermSelection.tapes B.shrink X sel w) ∧ last.reports=chosen.terms ∧
+ Group scr L base cap atStart (directoryRows L) m (pre++[last]) ∧
+ post m (pre++[last]) = after p.beforeTerm (eventLog chosen.terms) ∧
+ hdr p.beforeTerm := by
+ have stopFit : ShrinkInput.stop X start < 2^w := by unfold ShrinkInput.termEnd at room; omega
+ obtain ⟨ps,gp,nps,reports,post₀,hbefore,habs,empty⟩ := before_gather B f hf i X sel tape base
+ positions blocks t old new m T oldAt next sub fuel p heads scratch low fit stopFit rows pitch within cap headClock denseClock
+ let absMem := after p.input.post (eventLog p.absolute)
+ let ga := ShrinkTermOnline.packet B i X T start sel fuel .gather absMem p.gather
+ let te := ShrinkTermOnline.packet B i X T start sel fuel .select p.beforeTerm chosen.terms
+ have cert := ShrinkTermOnline.branch_group B i X T start sel fuel base positions blocks t cap headPost p chosen
+ gatherClock room hbefore.raw hbefore.fieldsBelow within termClock
+ have two : Group scr L base cap (atStart+20) (directoryRows L) absMem [ga,te] := cert.1
+ have g := Group.singleton ga rfl two.chronological.2.1 (two.checked ga (by simp))
+ (show Prepared scr L base (atStart+20) (directoryRows L) ga by simpa using two.prepared 0)
+ have before := gp.append (by rw [post₀,nps]; exact g)
+ have all := gp.append (by rw [post₀,nps]; exact two)
+ have preg : post m (ps++[ga]) = p.beforeTerm := by
+ rw [post_append,post₀]
+ simp only [post,List.flatMap_cons,List.flatMap_nil,List.append_nil,ga,ShrinkTermOnline.packet,
+ ShrinkBranch.Prefix.beforeTerm,absMem]
+ have daddr : (ShrinkInput.demandHead (w:=w) X start).val = ShrinkInput.stop X start :=
+ Nat.mod_eq_of_lt stopFit
+ have stLe := ShrinkInput.range_bounds X start
+ have keep (x : ℕ) (hx : x BlockProgram.script B
+local notation "space" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog prog)) base
+local notation "first₀" => Script.levelsPerBlock prog * round
+local notation "old₀" => first₀+i.val
+local notation "next₀" => old₀+1
+local notation "tab" => tableBase space old₀
+local notation "head₀" => levelStart space old₀
+local notation "start₀" => tableBase space old₀ (0 : Fin 6)
+local notation "term" => ShrinkInput.termHead (w := w) X start₀
+local notation "abs₀" => ShrinkResidentPackets.absoluteWord (w := w) X start₀
+local notation "T" => packedIncidence space w old₀ (DemandRAM.oldCount X)
+local notation "side₀" => SelectedFinish.chosen B X sel
+local notation "sh" => levelShape (b := b i) X
+local notation "Pkt" => SourceOnline.Packet prog w
+local notation "heads₀" => PortRefresh.TraversalHeaders.HeadBank space old₀ (DemandRAM.oldCount X)
+local notation "heads₁" => PortRefresh.TraversalHeaders.HeadBank space next₀ (actualCount sh)
+
+/-- Certifies the twelve resident visits of a selected shrink branch. Their final memory
+contains both per-site directories and their six header pointers, while preserving the data
+needed by the following slice scans. -/
+structure Residents (cap : ℕ) (mem : Memory w) (ps : List Pkt) : Prop where
+ group : Group prog space base cap ((prog).initial.length+round*(prog).block.length+(BlockIndex.earlier B i).length+36)
+ (directoryRows space) mem ps
+ indices : ps.map (fun p => p.stage.phase) = (ShrinkResidentPackets.window B i).indices
+ length : ps.length = 12
+ tapes : ps.flatMap (fun p => p.stage.choices) = List.replicate (ShrinkResidentLayout.layout X (tab (5 : Fin 6))).calls []
+ cost : RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) =
+ (ShrinkResidentLayout.layout X (tab (5 : Fin 6))).charge
+ published : ∀ j : Fin 6, post mem ps (head₀+(30+j.val)) =
+ (ShrinkResidentsPlan.headValues (ShrinkResidentLayout.layout X (tab (5 : Fin 6))) j : Word w)
+ preserved : ∀ x, ¬ ShrinkResidentPackets.Mutable (ShrinkResidentPackets.values (ShrinkResidentPackets.plan B i)
+ X (tab (5 : Fin 6)) head₀ abs₀ (ShrinkResidentPackets.roleWord X start₀) side₀) x → post mem ps x = mem x
+ directories : ∀ maps : Bool, ShrinkHistoryRows.Directory (ShrinkResidentDirectory.oldOrder X maps)
+ (ShrinkHistoryRows.packedOrder X) (ShrinkResidentDirectory.place X maps side₀)
+ (outputBank X (tab (5 : Fin 6)) maps) (post mem ps)
+ rows : post mem ps (pt).rows.val = (directoryRows space : Word w)
+ pitch : post mem ps ((pt).directory-1).val = (levelWords space : Word w)
+ header : ShrinkHeaderReads.Header i X T start₀ space first₀ (post mem ps)
+ oldHeads : heads₀ (post mem ps)
+ nextHeads : heads₁ (post mem ps)
+ tables : ShrinkOutput.Resident B i X sel term 10 abs₀ T start₀ (tab (2 : Fin 6)) (post mem ps)
+
+set_option maxHeartbeats 1600000 in
+theorem residents (fuel cap : ℕ) {initial : Memory w} (p : ShrinkBranch.Prefix X T start₀ fuel initial)
+ (v : ShrinkBranch.Selected B X T start₀ 10 (B.shrink.selectorBits : Word w) fuel initial p sel)
+ (hp : ShrinkBranch.PrefixFits B X T start₀ 10 fuel)
+ (header : ShrinkHeaderReads.Header i X T start₀ space first₀ v.beforeOutput)
+ (oldHeads : heads₀ v.beforeOutput) (nextHeads : heads₁ v.beforeOutput)
+ (rows : v.beforeOutput (pt).rows.val = (directoryRows space : Word w))
+ (pitch : v.beforeOutput ((pt).directory-1).val = (levelWords space : Word w))
+ (sites : X.positions ≤ positions) (room : endAddress space < 2^w)
+ (live : round < blocks) (clock : ShrinkResidentPackets.clock B ≤ cap) :
+ ∃ ps, Residents B i X sel base positions blocks round cap v.beforeOutput ps := by
+ have liveOld : old₀ < (space).levels := by
+ change (S.steps+1)*round+i.val < 1+(S.steps+1)*blocks
+ have bound := Nat.mul_le_mul_left (S.steps+1) live
+ rw [Nat.mul_succ] at bound; have := i.isLt; omega
+ let old : Fin (space).levels := ⟨_,liveOld⟩
+ have amount : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords space := by
+ change _ ≤ positions*(BlockProgram.allocationShape B).slots*(BlockProgram.allocationShape B).fields
+ rw [Nat.mul_assoc]; exact Nat.mul_le_mul sites (BlockProgram.field_rates B base.val positions blocks).1
+ have bounds := ShrinkLevelSpace.packed_ends S i X start₀ (tab (1 : Fin 6)) (tab (2 : Fin 6)) (tab (3 : Fin 6)) w
+ have word₀ := tableStop_lt space old (0 : Fin 6) amount room
+ have termRoom : ShrinkInput.termEnd X start₀ 10 < 2^w := bounds.2.1.trans_lt word₀
+ have selectedRoom : SelectedFinish.stop X term (10 : Word w) < 2^w := bounds.2.2.1.trans_lt word₀
+ have within₀ : SelectedFinish.stop X term (10 : Word w) ≤ start₀+tableWords space :=
+ bounds.2.2.1.trans (Nat.add_le_add_left amount _)
+ have src := resident_of_branch B i X sel T start₀ 10 (B.shrink.selectorBits : Word w) fuel p v hp
+ (tab (2 : Fin 6)) v.beforeOutput (fun _ _ => rfl)
+ obtain ⟨ps,group,ids,heads,frame,dirs,charge,len,tapes⟩ := ShrinkResidentPackets.physical_group
+ B i X base positions blocks round v.beforeOutput T side₀ header (oldHeads.tables (5 : Fin 6)) src.chosen
+ src.directory src.roles sites room rows pitch live cap clock
+ have fr := ShrinkResidentPackets.physical_frame B i X base positions blocks old sites room abs₀
+ (ShrinkResidentPackets.roleWord X start₀) side₀ v.beforeOutput (post v.beforeOutput ps) frame
+ have fields : ShrinkHeaderReads.Header i X T start₀ space first₀ (post v.beforeOutput ps) :=
+ ⟨header.room,(fr.scalar 0 (by decide)).trans header.vertices,(fr.scalar 1 (by decide)).trans header.degree,
+ (fr.scalar 2 (by decide)).trans header.lanes,(fr.scalar 3 (by decide)).trans header.residual,
+ fun c => (fr.higher (54+c.val) (by omega) (by have := c.isLt; omega)).trans (header.incidence c),(fr.tables 0).trans header.scratch⟩
+ have oldWords : heads₀ (post v.beforeOutput ps) :=
+ ⟨fun c => (fr.incidence c).trans (oldHeads.incidence c),fun c => (fr.tables c).trans (oldHeads.tables c)⟩
+ have newWords := nextHeads.keep (fun n _ => fr.next _ (Nat.le_add_right ..))
+ have retained := resident_of_branch_interval B i X sel T start₀ (B.shrink.selectorBits : Word w) fuel p v hp
+ termRoom selectedRoom.le (tab (2 : Fin 6)) (post v.beforeOutput ps)
+ (fun x low high => fr.tableZero x low (high.trans_le within₀))
+ exact ⟨ps,group,ids,len,tapes,charge,heads,frame,dirs,fr.rows.trans rows,fr.pitch.trans pitch,fields,oldWords,newWords,retained⟩
+
+end CompressorRecords.ScheduledShrink
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledRetention.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledRetention.lean
new file mode 100644
index 0000000000..4aa6c88494
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledRetention.lean
@@ -0,0 +1,218 @@
+import OAI.Computability.VPVNP.CompressorSourceGroups
+import OAI.Computability.VPVNP.CompressorShrinkOldFieldTransfer
+import OAI.Computability.VPVNP.CompressorShrinkReadbackTransfer
+import OAI.Computability.VPVNP.CompressorShrinkSlotPhysicalSpace
+import OAI.Computability.VPVNP.CompressorShrinkTablesPhysical
+import OAI.Computability.VPVNP.CompressorSlotCopiedTables
+import OAI.Computability.VPVNP.CompressorShrinkResidentFinal
+
+/-! # Readbacks after the shrinking slot packets and the canonical incidence copy
+
+The six copy workers write at the next level. The current level retains the
+old demand and selected terms in table zero, the two slice directories in
+tables one and two, the ordered endpoint table in table three and both
+resident directories in table five.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkOutput
+
+open BurstRAM BlockPlanner Compression DescriptorSpace Schedule ShrinkBlockInputs
+open ShrinkSlots SlotLevel SourceOnline
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+variable (base : Word w) (positions blocks t : ℕ)
+local notation "prog" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (arity (Script.catalog prog)) base
+local notation "blockStart" => Script.levelsPerBlock prog*t
+local notation "old" => blockStart+i.val
+local notation "nxt" => blockStart+(i.val+1)
+local notation "st" => (levelStart L blockStart : Word w)
+local notation "tab" => (fun j : Fin 6 => tableBase L old j)
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "ids" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X (tab 0)) w
+local notation "step" => (10 : Word w)
+local notation "role" => SelectedArena.roleBase X term step
+local notation "keepEnd" => SelectedFinish.stop X term step
+local notation "sh" => levelShape (b := b i) X
+local notation "h" => heads sh role (tab 3)
+local notation "side" => SelectedFinish.chosen B X sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "dst" => packedIncidence L w nxt (actualCount sh)
+local notation "hiddenBank" => ShrinkResidentLayout.layout X (tab 5)
+local notation "pub" => Ports.data pt
+local notation "P" => SourceOnline.Packet prog w
+
+/-- The six public words and both ordered lists of residents of a packed site. -/
+structure HiddenReadbacks (out : Memory w) : Prop where
+ heads : ∀ j : Fin 6, out (levelStart L old+(30+j.val)) =
+ (ShrinkResidentsPlan.headValues hiddenBank j : Word w)
+ directories : ∀ maps : Bool, ShrinkHistoryRows.Directory (ShrinkResidentDirectory.oldOrder X maps)
+ (ShrinkHistoryRows.packedOrder X) (ShrinkResidentDirectory.place X maps side)
+ (ShrinkResidentRun.outputBank X (tab 5) maps) out
+
+/-- All shrinking directories in the packet memory immediately following Part 8. -/
+structure ScheduledReadbacks (T : IncidenceDirectory w) (out : Memory w) : Prop where
+ resident : Resident B i X sel term step ids T (tab 0) (tab 2) out
+ slices : SliceReadbacks B i X sel term step (tab 1) (tab 2) out
+ ordered : Build.OrderedTables X (S.shrink i) side h out
+ hidden : HiddenReadbacks B i X sel base positions blocks t out
+ incidence : (dst).Represents Y out
+
+/-- The six copies preserve every address outside the canonical incidence columns. -/
+private theorem copy_frame (level : Fin (L).levels) (atNext : level.val = nxt) (r : TablesRun w)
+ (ps : List P) (fit : finish sh h < 2^w) (room : endAddress L < 2^w)
+ (capacity : actualCount sh ≤ slotCapacity L)
+ (logs : ps.flatMap SourceWalk.Packet.reports = r.remainder.slots.all ++
+ CopyIncidence.reports Y (directory sh h w) dst CopyIncidence.allColumns
+ (after r.remainder.postWidths (eventLog r.remainder.slots.all))) :
+ ∀ x, (x < incidenceStart L nxt ∨ incidenceStart L nxt+6*actualCount sh ≤ x) →
+ post r.remainder.postWidths ps x = r.final x := by
+ let mid := after r.remainder.postWidths (eventLog r.remainder.slots.all)
+ let copies := CopyIncidence.reports Y (directory sh h w) dst CopyIncidence.allColumns mid
+ have counts := next_counts X B.shrink (S.shrink i) sel
+ have src := CopyIncidence.shrink_column_bounds Y sh h counts.1 counts.2 fit
+ have target := CopyIncidence.packed_column_bounds Y sh L level counts.2 room capacity
+ have endRoom := packed_incidence_room L room level capacity
+ rw [atNext] at target endRoom
+ have write := ((CopyIncidence.reports_run Y (directory sh h w) dst CopyIncidence.allColumns mid).footprint
+ (fun c => (src c).2.trans fit.le) (fun c => (target c).2.trans endRoom.le)).2
+ intro x outside
+ have empty : ¬ CopyIncidence.ColumnCell Y dst x := by
+ rintro ⟨c,lo,hi⟩
+ have v : ((dst).column c).val = incidenceStart L nxt+c.val*actualCount sh ∧
+ ((dst).column c).val+CopyIncidence.rows Y c ≤ incidenceStart L nxt+6*actualCount sh := target c
+ omega
+ have keep : after mid (eventLog copies) x = r.final x :=
+ (SourceTransport.after_outside mid write empty).trans (congrFun (r.remainder.slots.final_eq r.remainder.postWidths).symm x)
+ simpa only [post,logs,mid,copies,eventLog,List.flatMap_append,after,List.foldl_append] using keep
+
+set_option maxHeartbeats 1200000 in
+/-- Every cell outside the interval tables, the ordered-slot workspace and
+the successor's six incidence columns agrees with the post-resident memory.
+This includes all old scalar publications, selected placement, low controller
+words and the entire successor header. -/
+theorem scheduled_frame (I : ShrinkABSliceRecipe.Inputs) (ref m : Memory w) (cap : ℕ)
+ (r : TablesRun w) (ps : List P) (live : t < blocks) (sites : X.positions ≤ positions)
+ (room : endAddress L < 2^w)
+ (run : CompleteTables B i X (S.shrink i) sel term step ids (tab 0) I pub st ref
+ (tab 1) (tab 2) (tab 3) cap m r)
+ (logs : ps.flatMap SourceWalk.Packet.reports = r.remainder.slots.all ++
+ CopyIncidence.reports Y (directory sh h w) dst CopyIncidence.allColumns
+ (after r.remainder.postWidths (eventLog r.remainder.slots.all))) :
+ ∀ x, (x < tab 1 ∨ finish sh h ≤ x) →
+ (x < incidenceStart L nxt ∨ incidenceStart L nxt+6*actualCount sh ≤ x) →
+ post r.remainder.postWidths ps x = m x := by
+ have nextLive : nxt < (L).levels := by
+ change (S.steps+1)*t+(i.val+1) < 1+(S.steps+1)*blocks
+ have upper := Nat.mul_le_mul_left (S.steps+1) live
+ rw [Nat.mul_succ] at upper
+ have hi := i.isLt
+ omega
+ let level : Fin (L).levels := ⟨old,by omega⟩
+ let next : Fin (L).levels := ⟨nxt,nextLive⟩
+ have space := table_space B i X base positions blocks t live sites room
+ obtain ⟨_,count,_,_⟩ := ShrinkSlotCalendar.physical_space (w := w) B i X base.val positions blocks level rfl sites room
+ have width : tab 2 ≤ widthBase X (term).val (step).val role (tab 2) :=
+ retained_room X term (step).val role (tab 2)
+ have slots : widthBase X (term).val (step).val role (tab 2) ≤ tab 3 :=
+ (width_le_slots (b := b i) X term (step).val role (tab 2)).trans space.slotAfter
+ have last : tab 3 ≤ finish sh h := by
+ unfold finish widthHead inHead outHead inverseBaseHead stopAddress shiftsHead targetsHead inverseHead rowsHead heads
+ dsimp only
+ omega
+ intro x outside copy
+ have native := copy_frame B i X sel base positions blocks t next rfl r ps space.slotRoom room count logs x copy
+ apply native.trans
+ apply (run.remainder.construction.frame x (outside.imp
+ (fun hx => hx.trans_le (((Nat.le_add_right _ _).trans space.widthAfter).trans width)) id)).trans
+ exact run.abFrame x (outside.imp id (fun hx => space.widthAfter.trans (width.trans (slots.trans (last.trans hx)))))
+
+set_option maxHeartbeats 1800000 in
+/-- A three-table run followed by its actual slot packets retains the current
+level's selected tables and its two previously published resident directories. -/
+theorem scheduled_readbacks (T : IncidenceDirectory w) (I : ShrinkABSliceRecipe.Inputs)
+ (ref m : Memory w) (cap : ℕ) (r : TablesRun w) (ps : List P)
+ (live : t < blocks) (sites : X.positions ≤ positions) (room : endAddress L < 2^w)
+ (resident : Resident B i X sel term step ids T (tab 0) (tab 2) m)
+ (hidden : HiddenReadbacks B i X sel base positions blocks t m)
+ (run : CompleteTables B i X (S.shrink i) sel term step ids (tab 0) I pub st ref
+ (tab 1) (tab 2) (tab 3) cap m r)
+ (logs : ps.flatMap SourceWalk.Packet.reports = r.remainder.slots.all ++
+ CopyIncidence.reports Y (directory sh h w) dst CopyIncidence.allColumns
+ (after r.remainder.postWidths (eventLog r.remainder.slots.all)))
+ (incidence : (dst).Represents Y (post r.remainder.postWidths ps)) :
+ ScheduledReadbacks B i X sel base positions blocks t T (post r.remainder.postWidths ps) := by
+ have nextBound : nxt < (L).levels := by
+ change (S.steps+1)*t+(i.val+1) < 1+(S.steps+1)*blocks
+ have e := Nat.mul_le_mul_left (S.steps+1) live
+ rw [Nat.mul_succ] at e
+ have hi := i.isLt
+ omega
+ let level : Fin (L).levels := ⟨old,by omega⟩
+ let next : Fin (L).levels := ⟨nxt,nextBound⟩
+ have space := table_space B i X base positions blocks t live sites room
+ obtain ⟨sp,count,_,width⟩ := ShrinkSlotCalendar.physical_space B i X base.val positions blocks level rfl sites room
+ obtain ⟨_,endTerm,endSelected,_,_,_,endSlots,_,endResidents⟩ :=
+ BlockLevelFit.shrink (w := w) B base.val positions blocks level rfl i X sites room
+ have oldNext : level.val+1 = nxt := by dsimp [level]; omega
+ have nextHead : levelStart L (level.val+1) ≤ incidenceStart L nxt :=
+ oldNext ▸ Nat.le_add_right _ _
+ have slotEnd := endSlots.next.trans nextHead
+ have hiddenEnd := endResidents.next.trans nextHead
+ have earlier (x : ℕ) (hx : x < incidenceStart L nxt) :=
+ copy_frame B i X sel base positions blocks t next rfl r ps endSlots.word room count logs x (.inl hx)
+ have oldFrame := scheduled_frame B i X sel base positions blocks t I ref m cap r ps live sites room run logs
+ have ten : 10 < 2^w := by
+ have hv : levelStart L old+66 ≤ tab 0 := by
+ change levelStart L old+66 ≤ levelStart L old+66+6*slotCapacity L+0*tableWords L
+ omega
+ have htab : tab 0 < 2^w := tableStop_lt L level (0 : Fin 6) (Nat.zero_le _) room
+ omega
+ have stepVal : (step).val=10 := Nat.mod_eq_of_lt ten
+ have termRoom : ShrinkInput.termEnd X (tab 0) (step).val < 2^w := stepVal ▸ endTerm.word
+ have slotStartBound : tab 3 ≤ incidenceStart L nxt :=
+ (Nat.le_add_right _ _).trans ((tableEnd_le_nextLevel L level (3 : Fin 6)).trans nextHead)
+ have selectedKeep (x : ℕ) (hx : x earlier x (hx.trans_le slotStartBound))
+ rw [← width] at sp
+ let native := run.remainder.construction
+ have sorted := Build.retained_tables X B.shrink (S.shrink i) sel h _ r.remainder.postWidths r.remainder.slots
+ sp native.inputRoles native.slots
+ have kept := Build.retained_after_copy X B.shrink (S.shrink i) sel h r.remainder.postWidths r.remainder.slots L
+ next room endSlots.word count sorted (.inl slotEnd)
+ refine ⟨packed,sf,?_,⟨?_,?_⟩,incidence⟩
+ · rw [post,logs]
+ exact kept
+ · intro j
+ have start : levelStart L old+66 ≤ tab 1 := by
+ change levelStart L old+66 ≤ levelStart L old+66+6*slotCapacity L+1*tableWords L
+ omega
+ have lo : levelStart L old+(30+j.val) < tab 1 := by have := j.isLt; omega
+ have before := (Nat.le_add_right (tab 1) (tableWords L)).trans ((tableEnd_le_nextLevel L level (1 : Fin 6)).trans nextHead)
+ exact (oldFrame _ (.inl lo) (.inl (lo.trans_le before))).trans (hidden.heads j)
+ · intro maps
+ apply ShrinkResidentRun.transfer X (tab 5) side maps (hidden.directories maps) endResidents.word
+ intro x lo hi
+ have slotBefore := endSlots.within.trans (tableEnd_le_tableBase L level (show (3 : Fin 6) < 5 by decide))
+ exact oldFrame x (.inr (slotBefore.trans lo)) (.inl (hi.trans_le hiddenEnd))
+
+end CompressorRecords.ShrinkOutput
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledRun.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledRun.lean
new file mode 100644
index 0000000000..2b66db7b78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledRun.lean
@@ -0,0 +1,171 @@
+import OAI.Computability.VPVNP.CompressorShrinkCurrentBranch
+import OAI.Computability.VPVNP.CompressorShrinkScheduledGeometry
+import OAI.Computability.VPVNP.CompressorShrinkScheduledFinish
+import OAI.Computability.VPVNP.CompressorShrinkOutputHeaders
+import OAI.Computability.VPVNP.CompressorShrinkOutputCharges
+
+/-! # Running every shrinking visit from the common native selection state
+
+At each reachable level the deterministic prefix leads to one fixed term
+input memory. For any admitted selection the following native packet and all
+of its deterministic continuations build and publish the actual output graph.
+The full suffix has exactly the length prescribed by this script's window.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkScheduledRun
+
+open BurstRAM Compression ShrinkBlockInputs BlockPlanner DescriptorSpace SourceOnline
+open ShrinkOutput
+open scoped Fin.CommRing
+
+private theorem post_before_marker {U : Script} {w : ℕ} (m : Memory w)
+ (ps : List (Packet U w)) (mark : Packet U w) (rest : List (Packet U w))
+ (input : post m ps = mark.input) :
+ post m (ps++mark::rest) = post mark.output rest := by
+ rw [post_append,input]
+ simp only [post,List.flatMap_cons,SourceWalk.after_append,SourceWalk.Packet.output]
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable (start positions blocks round : ℕ) (live : round < blocks)
+
+/-- The destination level of shrink step `i` in a live block round, one level past its source. -/
+def next : Fin (BlockProgram.layout B start positions blocks).levels :=
+ ⟨(S.steps+1)*round+i.val+1,by
+ change (S.steps+1)*round+i.val+1 < 1+(S.steps+1)*blocks
+ have mul := Nat.mul_le_mul_left (S.steps+1) live
+ rw [Nat.mul_succ] at mul
+ have hi := i.isLt
+ omega⟩
+
+/-- The source level of shrink step `i` in a live block round, at offset `i.val` from the
+round's first level. -/
+def old : Fin (BlockProgram.layout B start positions blocks).levels :=
+ ⟨(S.steps+1)*round+i.val,Nat.lt_of_succ_lt ((next B i start positions blocks round live).isLt)⟩
+
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+variable {g w : ℕ} (X : GreedyArena.ShrinkingState (a i) g) (base : Word w) (m : Memory w)
+variable (fuel cap : ℕ)
+local notation "src" => old B i (Fin.val base) positions blocks round live
+local notation "dst" => next B i (Fin.val base) positions blocks round live
+local notation "L" => BlockProgram.layout B (Fin.val base) positions blocks
+local notation "prog" => BlockProgram.script B
+local notation "begin₀" => ShrinkForward.first B i round
+local notation "count₀" => directoryRows L
+local notation "inc" => packedIncidence L w src (DemandRAM.oldCount X)
+local notation "origin" => tableBase L src (0 : Fin 6)
+local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog prog)) base
+local notation "Pkt" => Packet prog w
+
+/-- Every real column used by a pass lies in the descriptor data suffix. -/
+theorem column_lower (sites : X.positions ≤ positions) (room : endAddress L < 2^w) (c : Fin 6) :
+ levelStart L 0 ≤ ((inc).column c).val := by
+ have positionsEq : Fintype.card X.Base*2^(packingLaneBits (a i) g) = X.positions := by
+ simp only [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv _),Fintype.card_fin]
+ have deg : 2^(a i) ≤ slotDegree S :=
+ (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j)
+ (Finset.mem_univ i.castSucc)).trans (le_max_right ..)
+ have size : DemandRAM.oldCount X ≤ slotCapacity L := by
+ change Fintype.card X.Base*2^(packingLaneBits (a i) g)*2^(a i) ≤ positions*slotDegree S
+ rw [positionsEq]; exact Nat.mul_le_mul sites deg
+ have endFit := packed_incidence_room L room src size
+ have mul := Nat.mul_le_mul_right (DemandRAM.oldCount X) c.isLt.le
+ have address : incidenceBase L src (DemandRAM.oldCount X) c < 2^w :=
+ (Nat.add_le_add_left mul _).trans_lt endFit
+ rw [packed_column]
+ change levelStart L 0 ≤ incidenceBase L src (DemandRAM.oldCount X) c % 2^w
+ rw [Nat.mod_eq_of_lt address]
+ exact (levelStart_mono L (Nat.zero_le _)).trans ((Nat.le_add_right ..).trans (Nat.le_add_right ..))
+
+variable (common : ShrinkCurrentBranch.Common B f hf i X base.val positions blocks
+ (old B i base.val positions blocks round live) (next B i base.val positions blocks round live) m fuel)
+variable (sel : SelectedScore.Selection B X) (tape : List Bool)
+local notation "chosen" => Classical.choice (common.selected sel)
+local notation "selectedPost" => ShrinkBranch.Selected.beforeOutput chosen
+local notation "headBank" => PortRefresh.TraversalHeaders.HeadBank
+
+/-- Facts of the physical shrinking interval. Keeping their component types
+as parameters also lets the kernel check each large stage separately. -/
+structure PacketFacts (G F U N Q W M : Prop) : Prop where
+ geometry : G
+ finish : F
+ suffix : U
+ suffixLength : N
+ quiet : Q
+ whole : W
+ final : M
+
+set_option maxHeartbeats 1800000 in
+/-- Complete native packets and the physical readbacks needed by the next
+level and by the terminal traversal. -/
+abbrev Result (pre : List Pkt) (marker : Pkt) (geom p₅ p₆ p₇ p₈ ms tail : List Pkt) (r : TablesRun w) :=
+ PacketFacts
+ (ShrinkScheduledGeometry.Result B f hf i X sel tape base positions blocks round src dst m fuel
+ common.pre chosen cap pre marker geom)
+ (ShrinkScheduledFinish.Finish B i X sel base positions blocks round cap selectedPost p₅ p₆ p₇ p₈ ms tail r)
+ (Group prog L base cap (begin₀+22) count₀ marker.output (geom++((((p₅++p₆)++p₇)++p₈)++tail)))
+ (22 + (geom++((((p₅++p₆)++p₇)++p₈)++tail)).length = (BlockProgram.shrink B i).length)
+ (∀ q ∈ geom++((((p₅++p₆)++p₇)++p₈)++tail), ∀ bs ∈ q.stage.choices, bs = [])
+ (Group prog L base cap begin₀ count₀ m ((pre++marker::geom)++((((p₅++p₆)++p₇)++p₈)++tail)))
+ (post marker.output (geom++((((p₅++p₆)++p₇)++p₈)++tail)) =
+ post (post selectedPost (((p₅++p₆)++p₇)++p₈)) tail)
+
+set_option maxHeartbeats 2400000 in
+theorem run (fits : ShrinkBranch.PrefixFits B X inc origin (10 : Word w) fuel)
+ (heads : headBank L src (DemandRAM.oldCount X) m) (low : ∀ c, levelStart L 0 ≤ ((inc).column c).val)
+ (sites : X.positions ≤ positions) (room : endAddress L < 2^w)
+ (rows : m (pt).rows.val=(count₀ : Word w)) (pitch : m ((pt).directory-1).val=(levelWords L : Word w))
+ (arithmetic : TableArithmetic B i X w)
+ (headerClock : ShrinkHeaderGreedyPackets.clock B i ≤ cap)
+ (denseClock : scanCap prog (ShrinkBundlePackets.maxFuel B i) ≤ cap)
+ (termClock : scanCap prog fuel ≤ cap) (fixedClock : scanCap prog 95 ≤ cap) :
+ ∃ pre marker geom p₅ p₆ p₇ p₈ ms tail r,
+ Result B i positions blocks round live f hf X base m fuel cap common sel tape pre marker geom p₅ p₆ p₇ p₈ ms tail r := by
+ have clock (q : ℕ) (small : q ≤ 95) : scanCap prog q ≤ cap := by
+ unfold scanCap at fixedClock ⊢; omega
+ obtain ⟨pre,marker,geom,geo⟩ := ShrinkScheduledGeometry.run B f hf i X sel tape base positions blocks round
+ src dst m fuel common.pre chosen rfl rfl (common.header sel tape) fits heads low room sites live rows pitch cap
+ headerClock denseClock termClock (clock 65 (by decide))
+ obtain ⟨p₅,p₆,p₇,p₈,r,out⟩ := ScheduledShrink.output B i X sel base positions blocks round fuel cap common.pre
+ chosen fits geo.header geo.oldHeads geo.nextHeads geo.rows geo.pitch live sites room arithmetic fixedClock
+ let body := ((p₅++p₆)++p₇)++p₈
+ have h := out.tail_inputs live sites room
+ obtain ⟨ms,tail,pubs⟩ := ShrinkScheduledTail.run B base positions blocks round cap i X (post selectedPost body)
+ inc h.header sites live room h.rows h.pitch (clock 42 (by decide))
+ have done := ShrinkScheduledFinish.join B i X sel base positions blocks round cap out pubs
+ have intoMarker : post m pre = marker.input := geo.prefixPost.trans geo.selectInput.symm
+ have atBody : post marker.output geom = selectedPost :=
+ (post_before_marker m pre marker geom intoMarker).symm.trans geo.final
+ have offset : (begin₀+22)+geom.length = begin₀+36 := by rw [geo.suffixLength]
+ have suffix := geo.suffix.append (show Group prog L base cap ((begin₀+22)+geom.length) count₀
+ (post marker.output geom) (body++tail) by
+ rw [offset,atBody]; exact done.group)
+ have whole := geo.whole.append (by rw [geo.length,geo.final]; exact done.group)
+ refine ⟨pre,marker,geom,p₅,p₆,p₇,p₈,ms,tail,r,geo,done,suffix,?_,?_,whole,?_⟩
+ · rw [List.length_append,geo.suffixLength]
+ have size := done.length
+ omega
+ · intro q hq bs hb
+ rcases List.mem_append.mp hq with hq|hq
+ · exact geo.suffixEmpty q hq bs hb
+ rcases List.mem_append.mp hq with hq|hq
+ · have hbs : bs ∈ body.flatMap (fun z => z.stage.choices) := List.mem_flatMap.mpr ⟨q,hq,hb⟩
+ rw [show body.flatMap (fun z => z.stage.choices) = _ from out.tapes] at hbs
+ exact (List.mem_replicate.mp hbs).2
+ · have hbs : bs ∈ tail.flatMap (fun z => z.stage.choices) := List.mem_flatMap.mpr ⟨q,hq,hb⟩
+ rw [pubs.tapes] at hbs
+ exact (List.mem_replicate.mp hbs).2
+ · rw [post_append,atBody,post_append]
+
+end CompressorRecords.ShrinkScheduledRun
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledRunRate.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledRunRate.lean
new file mode 100644
index 0000000000..1db8d507e8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledRunRate.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.CompressorShrinkScheduledRun
+import OAI.Computability.VPVNP.CompressorShrinkOutputRate
+import OAI.Computability.VPVNP.CompressorShrinkGeometryRate
+import OAI.Computability.VPVNP.CompressorGroupCost
+
+/-! # The per-position rate of a complete scheduled shrinking pass
+
+The deterministic prefix can be supplied by the default admitted branch.
+Its packet count and its actual raw reports agree for every selection, which
+suffices for charging it together with the selected row and the chosen
+continuation. The coefficient is fixed by the compressor template and
+degree transition.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkScheduledRun
+
+open BurstRAM Compression ShrinkBlockInputs BlockPlanner DescriptorSpace SourceOnline
+open ShrinkOutput ScheduledTrace
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+local notation "prog" => BlockProgram.script B
+
+/-- The scheduled cost bound per incoming position for a complete shrink step, summing the
+prefix and geometry, output, and publication tail rates. -/
+def fixedRate :=
+ groupRate prog (ShrinkScheduledPrefix.prefixRate B i) 36 + ScheduledShrink.outputGroupRate B i + ScheduledShrink.tailGroupRate B
+
+variable (positions blocks round : ℕ) (live : round < blocks) {R : Type*} [CommRing R]
+variable (f : B.Entry → R) (hf : B.IsSolution f) {g w : ℕ} (X : GreedyArena.ShrinkingState (a i) g)
+variable (base : Word w) (m : Memory w) (fuel cap : ℕ)
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "src" => old B i base.val positions blocks round live
+local notation "dst" => next B i base.val positions blocks round live
+
+variable {common : ShrinkCurrentBranch.Common B f hf i X base.val positions blocks
+ (old B i base.val positions blocks round live) (next B i base.val positions blocks round live) m fuel}
+variable {sel : SelectedScore.Selection B X} {tape : List Bool}
+variable {pre geom p₅ p₆ p₇ p₈ ms tail : List (Packet (BlockProgram.script B) w)} {marker : Packet (BlockProgram.script B) w}
+ {tables : TablesRun w}
+local notation "level" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape
+local notation "body" => (((p₅++p₆)++p₇)++p₈)
+
+variable {B i positions blocks round live f hf X base m fuel cap}
+
+set_option maxHeartbeats 1500000 in
+theorem Result.rate_from
+ (h : Result B i positions blocks round live f hf X base m fuel cap common sel tape pre marker geom p₅ p₆ p₇ p₈ ms tail tables)
+ (shared : List (Packet prog w)) (count : shared.length=21)
+ (reports : shared.flatMap SourceWalk.Packet.reports = BlockHeaderRun.reports level L src dst m ++ common.pre.reports) :
+ groupCost prog shared + groupCost prog [marker] + groupCost prog (geom++(body++tail)) ≤ X.positions*fixedRate B i := by
+ have firstPart := h.geometry.prefix_rate shared count reports
+ have finished := h.finish
+ have rest := ScheduledShrink.Output.rate B i X sel base positions blocks round cap finished.output
+ have last := ScheduledShrink.tail_rate B i X base positions blocks round cap finished.published
+ have bound := Nat.add_le_add (Nat.add_le_add firstPart rest) last
+ rw [groupCost_split_selector prog shared marker geom] at bound
+ rw [groupCost_append prog geom (body++tail),groupCost_append prog body tail,fixedRate,Nat.mul_add,Nat.mul_add]
+ simpa only [Nat.add_assoc] using bound
+
+theorem Result.rate
+ (h : Result B i positions blocks round live f hf X base m fuel cap common sel tape pre marker geom p₅ p₆ p₇ p₈ ms tail tables) :
+ groupCost prog pre + groupCost prog [marker] + groupCost prog (geom++(body++tail)) ≤ X.positions*fixedRate B i :=
+ h.rate_from pre h.geometry.prefixLength h.geometry.prefixReports
+
+/-- The common prefix may come from a different admitted selection and
+its own execution. Only its real header and deterministic reports enter
+the charge. -/
+theorem Result.rate_shared
+ (h : Result B i positions blocks round live f hf X base m fuel cap common sel tape pre marker geom p₅ p₆ p₇ p₈ ms tail tables)
+ {other : SelectedScore.Selection B X} {word : List Bool} {shared g₀ s₅ s₆ s₇ s₈ m₀ t₀ : List (Packet prog w)}
+ {sMarker : Packet prog w} {sTables : TablesRun w}
+ (d : Result B i positions blocks round live f hf X base m fuel cap common other word shared sMarker g₀ s₅ s₆ s₇ s₈ m₀ t₀ sTables) :
+ groupCost prog shared + groupCost prog [marker] + groupCost prog (geom++(body++tail)) ≤ X.positions*fixedRate B i := by
+ apply h.rate_from shared d.geometry.prefixLength
+ have same := (ShrinkCurrentBranch.header_eq B f hf i X base.val positions blocks src dst m other word).2.trans
+ (ShrinkCurrentBranch.header_eq B f hf i X base.val positions blocks src dst m sel tape).2.symm
+ exact d.geometry.prefixReports.trans (congrArg (· ++ common.pre.reports) same)
+
+end CompressorRecords.ShrinkScheduledRun
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledTail.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledTail.lean
new file mode 100644
index 0000000000..52eb37a158
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledTail.lean
@@ -0,0 +1,187 @@
+import OAI.Computability.VPVNP.CompressorBlockHeadSequence
+import OAI.Computability.VPVNP.CompressorBlockMetadataWindows
+
+/-! # The three terminal DFS publication windows of a shrink
+
+Starting at the actual memory after the slot construction, the metadata
+writer emits its twelve old-header operands and two successor words. The
+term and data writers then fill eighteen old-header words. Each report is
+from the installed phase at its chronological ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkScheduledTail
+
+open BurstRAM DescriptorSpace BlockPlanner PhaseRecipe Schedule Compression SourceOnline SourceTransport
+open scoped Fin.CommRing
+
+variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+variable (base : Word w) (positions blocks t cap : ℕ) (i : Fin S.steps)
+local notation "prog" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (arity (Script.catalog prog)) base
+local notation "pub" => Ports.data pt
+local notation "first" => Script.levelsPerBlock prog * t
+local notation "st" => (levelStart L (first) : Word w)
+local notation "oldHead" => levelStart L (first+i.val)
+local notation "newHead" => levelStart L (first+(i.val+1))
+local notation "origin" => tableBase L (first+i.val) (0 : Fin 6)
+local notation "termVec" => BlockHeadStability.shrinkTerms B i
+local notation "headVec" => PublishedHeads.dataValues B i
+local notation "startOrdinal" => ShrinkForward.first B i t + ShrinkForward.visitsBefore B i 9
+local notation "Packet₀" => SourceOnline.Packet prog w
+local notation "metaW" => BlockGroups.shrink B i 9
+local notation "termW" => BlockGroups.shrink B i 10
+local notation "dataW" => BlockGroups.shrink B i 11
+
+variable {g : ℕ} (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) (m : Memory w)
+local notation "meta" => BlockMetadata.Published B base positions blocks t i.val BlockMetadata.Role.shrink (BlockMetadata.shrinkFields B i) m (ShrinkPreimages.oldCount X)
+
+/-- Memory after writing the term base, term stride, selected layout bit, and absolute motif
+table base to offsets 36 through 39 of the old level header. -/
+def termImage (mem : Memory w) := PublishedHeads.image pub st mem (oldHead+36) termVec
+
+/-- Memory after writing the fourteen data pointers used by the shrinking node reader to
+offsets 40 through 53 of the old level header. -/
+def dataImage (mem : Memory w) := PublishedHeads.image pub st mem (oldHead+40) headVec
+
+/-- Exact post-images of the three groups, together with their fixed online
+control positions. -/
+structure Result (metadata ps : List Packet₀) : Prop where
+ group : Group prog L base cap startOrdinal (directoryRows L) m ps
+ phases : ps.map (fun p ↦ p.stage.phase) = (metaW).indices++(termW).indices++(dataW).indices
+ baseFields : meta (metadata.flatMap SourceWalk.Packet.reports)
+ published : PublishedHeads.Pair B base positions blocks t i.val cap (post m metadata) termVec headVec termW dataW
+ image : post m ps = dataImage B base positions blocks t i (termImage B base positions blocks t i (post m metadata))
+ tapes : ps.flatMap (fun p ↦ p.stage.choices) = List.replicate 21 []
+ charge : RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) = 53
+
+private theorem header_gap : oldHead+66 ≤ newHead := by
+ have size : levelHeaderWords L = 66 := rfl
+ rw [show first+(i.val+1)=(first+i.val)+1 by omega]
+ simp only [levelStart,Nat.succ_mul,levelWords,size]
+ omega
+
+variable {B base positions blocks t cap i X m}
+
+theorem Result.outside {ms ps : List Packet₀} (r : Result B base positions blocks t cap i X m ms ps) (x : ℕ)
+ (metaOutside : x < oldHead+15 ∨ oldHead+27 ≤ x) (headOutside : x < oldHead+36 ∨ oldHead+54 ≤ x)
+ (baseOutside : x ≠ newHead+14) (roleOutside : x ≠ newHead+27) :
+ post m ps x = m x := by
+ rw [r.image]
+ have d := r.published.dataGroup.source.outside x (by unfold PublishedHeads.Outside; omega)
+ have h := r.published.termGroup.source.outside x (by unfold PublishedHeads.Outside; omega)
+ exact d.trans (h.trans (r.baseFields.outside x metaOutside baseOutside roleOutside))
+
+theorem Result.metaCell {ms ps : List Packet₀} (r : Result B base positions blocks t cap i X m ms ps) (x : ℕ)
+ (outside : x < oldHead+36 ∨ oldHead+54 ≤ x) : post m ps x = post m ms x := by
+ rw [r.image]
+ have d := r.published.dataGroup.source.outside x (by unfold PublishedHeads.Outside; omega)
+ exact d.trans (r.published.termGroup.source.outside x (by unfold PublishedHeads.Outside; omega))
+
+theorem Result.earlier {ms ps : List Packet₀} (r : Result B base positions blocks t cap i X m ms ps)
+ (x : ℕ) (hx : x < oldHead) : post m ps x = m x := by
+ have := header_gap B base positions blocks t i
+ apply r.outside <;> omega
+
+/-- Both this level's packed tables and the successor's canonical packed
+incidence region lie outside the two scalar publication blocks. -/
+theorem Result.old_data {ms ps : List Packet₀} (r : Result B base positions blocks t cap i X m ms ps)
+ (x : ℕ) (lo : oldHead+54 ≤ x) (hi : x < newHead) : post m ps x = m x := by
+ apply r.outside <;> omega
+
+theorem Result.next_data {ms ps : List Packet₀} (r : Result B base positions blocks t cap i X m ms ps)
+ (x : ℕ) (lo : newHead+28 ≤ x) : post m ps x = m x := by
+ have := header_gap B base positions blocks t i
+ apply r.outside <;> omega
+
+theorem Result.length {ms ps : List Packet₀} (r : Result B base positions blocks t cap i X m ms ps) :
+ ps.length = 21 := by
+ have h := congrArg List.length r.phases
+ simp only [Window.indices,List.length_map,List.length_append,List.length_ofFn] at h
+ change ps.length = 3+4+14 at h
+ exact h
+
+private theorem metaTapes {p : Fin 5 → Word w} {s : Word w} {ls : List BlockPlanner.Visit} {raw : Memory w}
+ {rs : List (Report w)} (walk : SourceWalk (BlockMetadata.Source p s) ls raw rs) :
+ branchPaths rs = List.replicate rs.length [] := by
+ induction walk with
+ | done => rfl
+ | @next v vs before xs ys call _ ih =>
+ obtain ⟨f,r,rfl,_,_,_,hr⟩ := call
+ have bits := (execute_iff.mp hr).2.2
+ change choiceBits r.events :: branchPaths ys = _
+ simp only [List.singleton_append,List.length_cons,List.replicate_succ,bits,ih]
+
+variable (B base positions blocks t cap i X m)
+
+/-- Run Parts 9, 10 and 11 at their fixed program ordinals from the
+post-slot memory. All capacity bounds use the real table-zero allocation. -/
+theorem run (T : IncidenceDirectory w)
+ (header : ShrinkHeaderReads.Header i X T origin L (first) m) (sites : X.positions ≤ positions)
+ (ht : t < blocks) (fit : endAddress L < 2^w) (rows : m (pt).rows.val = (directoryRows L : Word w))
+ (pitch : m (pub 1-1).val = (levelWords L : Word w)) (clock : scanCap prog 42 ≤ cap) :
+ ∃ ms ps : List Packet₀, Result B base positions blocks t cap i X m ms ps := by
+ have entry : LevelFields.Entry L (first) pub st m := ⟨rfl,pitch⟩
+ have old : (LevelFields.sites i.val).eval pub st m = (ShrinkPreimages.oldCount X : Word w) := by
+ have hv := header.reads B entry
+ change (LevelFields.vertices i.val).eval pub st m * (LevelFields.lanes i.val).eval pub st m = _
+ rw [hv.vertices,hv.lanes,← Nat.cast_mul]
+ obtain ⟨ms,mGroup,mPh,hMeta⟩ := BlockMetadata.shrink_group B base positions blocks t cap m i ht fit rows pitch clock _ old
+ let afterMeta := post m ms
+ have sep := header_gap B base positions blocks t i
+ have below (x : ℕ) (hx : x < levelStart L 0) : afterMeta x = m x := by
+ have := levelStart_mono L (show 0 ≤ first+i.val from Nat.zero_le _)
+ exact hMeta.outside x (Or.inl (by omega)) (by omega) (by omega)
+ have hold (j : ℕ) (hj : j ≤ 60) (free : j < 15 ∨ 27 ≤ j) : afterMeta (oldHead+j) = m (oldHead+j) :=
+ hMeta.outside _ (by omega) (by omega) (by omega)
+ have hdr : ShrinkHeaderReads.Header i X T origin L (first) afterMeta :=
+ ⟨header.room,(hold 0 (by decide) (by decide)).trans header.vertices,
+ (hold 1 (by decide) (by decide)).trans header.degree,(hold 2 (by decide) (by decide)).trans header.lanes,
+ (hold 3 (by decide) (by decide)).trans header.residual,fun c ↦
+ (hold (54+c.val) (by have := c.isLt; omega) (.inr (by omega))).trans (header.incidence c),
+ (hold 60 (by decide) (by decide)).trans header.scratch⟩
+ have low := Window.lowCells (A:=prog) L base rfl rfl ((levelStart_mono L (Nat.zero_le _)).trans_lt fit)
+ have small : scanCap prog 7 ≤ scanCap prog 42 := by unfold scanCap; omega
+ have ready : PublishedHeads.Ready B base positions blocks t cap afterMeta :=
+ ⟨ht,fit,(below _ low.1).trans rows,(below _ low.2).trans pitch,small.trans clock⟩
+ have pair := PublishedHeads.shrink_pair B i ready X T hdr sites
+ obtain ⟨ps,pGroup,ph,logs,bits⟩ := pair.online
+ have num : ms.length = 3 := by
+ have e := congrArg List.length mPh
+ simp only [Window.indices,List.length_map,List.length_ofFn] at e
+ exact e.trans (by rfl)
+ have ord : startOrdinal+ms.length = (prog).initial.length+t*(prog).block.length+(termW).before.length := by
+ rw [num,BlockGroups.shrink_offset]
+ unfold ShrinkForward.first ShrinkForward.visitsBefore
+ have h : ((BlockGroups.parts B i).take 10).flatten.length = ((BlockGroups.parts B i).take 9).flatten.length+3 := by
+ rw [List.take_succ_eq_append_getElem (show 9 < (BlockGroups.parts B i).length by rw [BlockGroups.parts_length]; decide)]
+ rw [List.flatten_append,List.length_append,List.flatten_cons,List.flatten_nil,List.append_nil]
+ rfl
+ change _+3 = _+(_+((BlockGroups.parts B i).take 10).flatten.length)
+ rw [h]
+ omega
+ have group := mGroup.append (ord ▸ pGroup)
+ refine ⟨ms,ms++ps,group,?_,hMeta,pair,?_,?_,?_⟩
+ · rw [List.map_append,mPh,ph]
+ exact (List.append_assoc ..).symm
+ · rw [post_append,post,logs,SourceWalk.after_append]
+ rfl
+ · have mbits := metaTapes hMeta.source
+ rw [hMeta.length] at mbits
+ rw [List.flatMap_append,PublishedHeads.chronological_tapes m ms mGroup.chronological,mbits,bits]
+ rfl
+ · rw [List.flatMap_append,RAMBuckets.cost_append,hMeta.charge,logs,PublishedHeads.pair_charge]
+
+end CompressorRecords.ShrinkScheduledTail
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScoreBounds.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreBounds.lean
new file mode 100644
index 0000000000..169c79dc90
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreBounds.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.CompressorShrinkScoreWalk
+import OAI.Computability.VPVNP.CompressorSourceOnline
+
+/-! # Memory footprints and cursor progress of the ten score stages -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ScorePackets
+
+open BurstRAM SourceTransport SourceOnline TermScores Compression
+open scoped Classical Fin.CommRing
+
+variable {w : ℕ} (T : Tables w) (n : ℕ)
+
+/-- Physical address information used by every score visit. -/
+structure Region : Prop where
+ one : 1 < 2^w
+ rows : n < 2^w
+ counters : ∀ l, T.termBase.val ≤ (counter T l).val
+ level : T.termBase.val ≤ T.levelCell.val
+ repetitions : ∀ i < n, T.termBase.val ≤ (TermScores.repetitions T (word i)).val
+ payload : ∀ j : Fin 8, ∀ i < n, T.termBase.val ≤ (TermScores.payload T (SelectedScore.axes j) (word i)).val
+
+theorem Region.selected {a g : ℕ} (X : State a (packingLaneBits a g)) (term stride selectors : Word w)
+ (wide : 10 ≤ stride.val) (fit : SelectedArena.Fits X term stride) :
+ Region (SelectedArena.scoreTables X term stride selectors) (SelectedArena.motifs X) := by
+ let L := SelectedArena.scoreTables X term stride selectors
+ let N := SelectedArena.motifs X
+ let endRows := term.val+N*stride.val
+ have room : endRows+2 < 2^w := by
+ change endRows+3+_+_ < 2^w at fit; omega
+ have base : L.scoreBase.val = endRows := by
+ change endRows % (2^w) = endRows
+ exact Nat.mod_eq_of_lt (by omega)
+ have le : N ≤ N*stride.val := Nat.le_mul_of_pos_right _ (by omega)
+ have row (i : ℕ) (hi : i < N) : i*stride.val + stride.val ≤ N*stride.val := by
+ simpa only [Nat.succ_mul] using Nat.mul_le_mul_right stride.val hi
+ have hs : L.termBase.val = term.val := rfl
+ have st : L.termStride.val = stride.val := rfl
+ have hEnd : endRows = term.val+N*stride.val := rfl
+ refine ⟨by omega,by omega,?_,?_,?_,?_⟩
+ · intro l
+ have hl : l.toNat ≤ 1 := by cases l <;> decide
+ change term.val ≤ (counter L l).val
+ rw [counter,Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,base,Nat.mod_eq_of_lt (by omega)]
+ omega
+ · change term.val ≤ (endRows+2)%(2^w)
+ rw [Nat.mod_eq_of_lt room]; omega
+ · intro i hi
+ have h := row i hi
+ change term.val ≤ (TermScores.repetitions L _).val
+ rw [repetitions_val L (by rw [hs,st]; omega),hs]; omega
+ · intro j i hi
+ have h := row i hi
+ have hc : (SelectedScore.axes (w := w) j).coordinate.val ≤ j.val := Nat.mod_le ..
+ change term.val ≤ (TermScores.payload L _ _).val
+ rw [payload_val L _ (by rw [hs,st]; have := j.isLt; omega),hs]; omega
+
+/-- Exclusive stopping cursor for a score visit. Each axis scans `n` motif rows, while clearing
+and comparison each take one call. -/
+def Stage.limit (n : ℕ) : Stage → ℕ | .axis _ => n | _ => 1
+
+private theorem worker_access (region : Region T n) (j : Fin 8) (mem : Memory w) (k : ℕ) (hk : k < n) :
+ Reads (T.termBase.val ≤ ·) (workerReport T (SelectedScore.axes j) mem (word k)).events ∧
+ Writes (T.termBase.val ≤ ·) (workerReport T (SelectedScore.axes j) mem (word k)).events := by
+ constructor
+ · intro a v ha
+ simp only [workerReport,List.mem_append,List.mem_replicate,List.mem_cons,List.not_mem_nil,
+ reduceCtorEq,Event.read.injEq,and_false,or_false,false_or] at ha
+ rcases ha with (⟨rfl,_⟩ | ⟨rfl,_⟩) | ⟨rfl,_⟩
+ exacts [region.repetitions _ hk,region.payload _ _ hk,region.counters _]
+ · intro a v ha
+ simp only [workerReport,List.mem_append,List.mem_replicate,List.mem_cons,List.not_mem_nil,
+ reduceCtorEq,Event.write.injEq,and_false,or_false,false_or] at ha
+ obtain ⟨rfl,_⟩ := ha
+ exact region.counters _
+
+open private word_succ from OAI.Computability.VPVNP.CompressorRecordTermScores
+
+private theorem axis_progress (region : Region T n) (j : Fin 8) (left k : ℕ) (endAt : k+left=n)
+ (mem : Memory w) (rs : List (Report w))
+ (run : runSegment (workerMachine T (SelectedScore.axes j)).program 27 (some (word k)) mem
+ (List.replicate left []) = some rs) :
+ Progress (word n) (word k) rs ∧ Reads (T.termBase.val ≤ ·) (eventLog rs) ∧
+ Writes (T.termBase.val ≤ ·) (eventLog rs) := by
+ induction left generalizing k mem rs with
+ | zero =>
+ have e : [] = rs := Option.some.inj run
+ subst rs
+ rw [Nat.add_zero] at endAt
+ subst k
+ exact ⟨.done le_rfl,by simp [Reads,eventLog],by simp [Writes,eventLog]⟩
+ | succ left ih =>
+ have hk : k < n := by omega
+ have active : word (w := w) k < word n := Fin.lt_def.mpr (by
+ change k%(2^w) (List.mem_append.mp hv).elim (acc.1 a v) (rd a v),
+ fun a v hv => (List.mem_append.mp hv).elim (acc.2 a v) (wr a v)⟩
+
+theorem Native.bounds (region : Region T n) (j : Stage) (mem : Memory w) (rs : List (Report w))
+ (h : Native T n j mem rs) : Progress (word (j.limit n)) 0 rs ∧
+ Reads (T.termBase.val ≤ ·) (eventLog rs) ∧ Writes (T.termBase.val ≤ ·) (eventLog rs) := by
+ have pos : (0 : Word w) < 1 := Fin.lt_def.mpr (by
+ change 0 < 1%(2^w); rw [Nat.mod_eq_of_lt region.one]; decide)
+ have h₀ : T.termBase.val ≤ T.scoreBase.val := (counter_false T) ▸ region.counters false
+ have h₁ : T.termBase.val ≤ (T.scoreBase+1).val := region.counters true
+ cases j with
+ | axis j => exact axis_progress T n region j n 0 (Nat.zero_add _) mem rs h
+ | clear =>
+ subst rs
+ refine ⟨.next pos rfl (.done le_rfl),?_,?_⟩
+ · simp [Reads,eventLog,advance,clearReport]
+ · intro a v ha
+ simp [eventLog,advance,clearReport] at ha
+ rcases ha with ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> assumption
+ | compare =>
+ subst rs
+ refine ⟨.next pos rfl (.done le_rfl),?_,?_⟩
+ · intro a v ha
+ simp [eventLog,advance,compareReport] at ha
+ rcases ha with ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> assumption
+ · intro a v ha
+ simp [eventLog,advance,compareReport] at ha
+ obtain ⟨rfl,_⟩ := ha; exact region.level
+
+private theorem Native.writes_walk {stages : List Stage} {mem : Memory w} {rs : List (Report w)}
+ (region : Region T n) (h : SourceWalk (Native T n) stages mem rs) :
+ Writes (T.termBase.val ≤ ·) (eventLog rs) := by
+ induction h with
+ | done => simp [Writes,eventLog]
+ | next head _ ih =>
+ have wr := (head.bounds T n region _ _ _).2.2
+ intro a v ha
+ rw [eventLog,List.flatMap_append] at ha
+ exact (List.mem_append.mp ha).elim (wr a v) (ih a v)
+
+/-- The actual score run leaves the old level header and every earlier
+allocation untouched. -/
+theorem score_frame (mem : Memory w) (rs : List (Report w))
+ (execute : TermScores.run T n (List.ofFn SelectedScore.axes) mem = some rs)
+ (region : Region T n) (x : ℕ) (hx : x < T.termBase.val) :
+ after mem (eventLog rs) x = mem x := by
+ obtain ⟨logs,hw,he⟩ := walk T n mem rs execute
+ rw [← he]
+ exact after_outside mem (Native.writes_walk T n region hw) (Nat.not_le_of_lt hx)
+
+end CompressorRecords.ScorePackets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScoreGroup.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreGroup.lean
new file mode 100644
index 0000000000..7cc6198cd6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreGroup.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.CompressorShrinkScoreOperands
+import OAI.Computability.VPVNP.CompressorShrinkTermOnline
+import OAI.Computability.VPVNP.CompressorPublishedHeadWindows
+
+/-! # The score packet group in the complete repeated block program
+
+At the 22nd offset of each shrinking substep the actual ten visits clear both
+accumulators, read the eight selected coordinates and publish the chosen bit.
+The reports leave the same post-memory as the verified selected score run.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ScorePackets
+
+open BurstRAM Compression BlockPlanner ShrinkBlockInputs DescriptorSpace SourceTransport PhaseRecipe Schedule
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+local notation "script₀" => BlockProgram.script B
+local notation "O" => BlockProgram.arena B i.val 0
+local notation "I" => selectedInputs B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0)
+
+/-- Locates the ten score visits in the repeated block, directly after the term-record visits
+and before placement uses the selected layout. -/
+def window : Window script₀ (visits I) where
+ before := (ShrinkTermOnline.window B i).before ++ termVisits B i O
+ after := [SelectedPlan.placement I,SelectedPlan.roles I,SelectedPlan.clearChildren I,SelectedPlan.children I (a i)] ++
+ (BlockProgram.shrink B i).drop (beforeSlices B (BlockProgram.geometry B) i O).length ++ BlockIndex.later B i
+ block := by
+ rw [(ShrinkTermOnline.window B i).block,visits_eq]
+ simp only [ShrinkTermOnline.window,ShrinkTermOnline.remaining,SelectedPlan.visits,
+ List.append_assoc,List.cons_append,List.nil_append]
+
+theorem before_length : (window B i).before.length = (BlockIndex.earlier B i).length+22 := by
+ change ((BlockIndex.earlier B i ++ ShrinkTermOnline.prior B i) ++ termVisits B i O).length = _
+ rw [List.length_append,List.length_append,ShrinkTermOnline.prior_length,termVisits_length]
+
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+variable (base : Word w) (positions blocks t : ℕ)
+local notation "W" => window B i
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (arity (Script.catalog script₀)) base
+local notation "pub" => Schedule.Ports.data pt
+local notation "first₀" => Script.levelsPerBlock script₀ * t
+local notation "st" => (levelStart L (first₀) : Word w)
+local notation "D" => Window.operandRegion script₀ L base
+local notation "H" => levelStart L 0
+local notation "head" => levelStart L (first₀+i.val)
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "table" => SelectedArena.scoreTables X term (10 : Word w) (B.shrink.selectorBits : Word w)
+local notation "N" => SelectedArena.motifs X
+local notation "Pkt" => SourceWalk.Packet (SourceOnline.Visit script₀ w) w
+
+private theorem paths {tab : TermScores.Tables w} {n : ℕ} {js : List Stage} {m : Memory w} {rs : List (Report w)}
+ (h : SourceWalk (Native tab n) js m rs) :
+ branchPaths rs = List.replicate ((js.map (Stage.limit n)).sum) [] := by
+ induction h with
+ | done => rfl
+ | @next j js m xs ys hs _ ih =>
+ have eq : branchPaths xs = List.replicate (j.limit n) [] := by
+ cases j with
+ | axis j => exact ((runSegment_iff ..).mp hs).2.2
+ | clear => subst xs; rfl
+ | compare => subst xs; rfl
+ rw [branchPaths,List.map_append,← branchPaths,← branchPaths,eq,ih,List.map_cons,List.sum_cons,List.replicate_add]
+
+set_option maxHeartbeats 1200000 in
+private theorem raw {js : List Stage} {mem : Memory w} {rs : List (Report w)}
+ (run : SourceWalk (Native table N) js mem rs)
+ (region : Region table N)
+ (room : ShrinkInput.termEnd X start 10 < 2^w) (before : head+60 < start)
+ (fit : H < 2^w) (header : ShrinkHeaderReads.Header i X T start L (first₀) mem)
+ (pitch : mem (pub 1-1).val = (levelWords L : Word w)) :
+ SourceWalk (Window.Raw (A:=script₀) L base t 27) (js.map (Stage.visit I)) mem rs := by
+ have low : H ≤ head := levelStart_mono L (Nat.zero_le _)
+ have lower := start_le_term i X start room
+ have control := Window.lowCells (A:=script₀) L base rfl rfl fit
+ induction run with
+ | done => exact .done _
+ | @next j js m xs ys hs _ ih =>
+ have entry : LevelFields.Entry L (first₀) pub st m := ⟨rfl,pitch⟩
+ have ev := term_values B i X T start pub st m (header.reads B entry) room
+ have sup := term_support B i X T start pub st m header entry D (Or.inr (.inl rfl))
+ (fun z _ => Or.inr (.inr (low.trans (Nat.le_add_right ..))))
+ have score : (SelectedPlan.scoreBase I).eval pub st m = (table).scoreBase := by
+ change (I).termBase.eval pub st m + (I).motifs.eval pub st m * (10 : Word w) = _
+ rw [ev.1,ev.2]
+ have tr : ((term).val : Word w) = term := Fin.ext (Nat.mod_eq_of_lt (term).isLt)
+ have ten : 10 < 2^w := by
+ have h := region.one
+ have h₀ := header.room; omega
+ change _ = (((term).val + N*(10 : Word w).val : ℕ) : Word w)
+ have hten : (10 : Word w).val = 10 := Nat.mod_eq_of_lt ten
+ rw [hten,Nat.cast_add,Nat.cast_mul,tr,Nat.cast_ofNat]
+ have cell : (SelectedPlan.layoutCell I).eval pub st m = (table).levelCell := by
+ change (SelectedPlan.scoreBase I).eval pub st m + 2 = _
+ rw [score]
+ change ((_ : ℕ) : Word w)+2 = ((_+2 : ℕ) : Word w)
+ rw [Nat.cast_add,Nat.cast_ofNat]
+ have values : Readback I pub st m table N := ⟨ev.2,ev.1,rfl,rfl,score,cell⟩
+ have packet := hs.run I pub st m table N L (by change H ≤ (term).val; omega) region values j xs
+ have bounds := hs.bounds table N region j m xs
+ have keep (x : ℕ) (hx : x < start) : after m (eventLog xs) x = m x :=
+ after_outside m bounds.2.2 (show ¬(term).val ≤ x by omega)
+ have gap : (pub 1-1).val < start := by
+ have h : (pub 1-1).val < H := control.2
+ omega
+ exact .next ⟨j.fuel,List.replicate (j.limit N) [],j.fuel_le,packet,supported I pub st m D j sup.2 sup.1⟩
+ (ih (header.keep_below before keep) ((keep _ gap).trans pitch))
+
+set_option maxHeartbeats 1800000 in
+/-- Install all ten score visits at the true shrinking substep, from the
+executed score run in the selected branch. The group has its exact post-memory
+and one empty choice stream per actual worker call. -/
+theorem group (cap : ℕ) (mem : Memory w) (scores : List (Report w))
+ (execute : TermScores.run table N (List.ofFn SelectedScore.axes) mem = some scores)
+ (live : t < blocks) (room : ShrinkInput.termEnd X start 10 < 2^w) (before : head+60 < start)
+ (selectedFit : SelectedArena.Fits X term (10 : Word w))
+ (header : ShrinkHeaderReads.Header i X T start L (first₀) mem)
+ (rows : mem (pt).rows.val = (directoryRows L : Word w)) (pitch : mem (pub 1-1).val = (levelWords L : Word w))
+ (clock : SourceOnline.scanCap script₀ 27 ≤ cap) :
+ ∃ ps : List Pkt, SourceOnline.Group script₀ L base cap ((script₀).initial.length+t*(script₀).block.length+
+ (BlockIndex.earlier B i).length+22) (directoryRows L) mem ps ∧
+ ps.map (fun p => p.stage.phase) = (W).indices ∧
+ eventLog (ps.flatMap SourceWalk.Packet.reports) = eventLog scores ∧
+ ps.flatMap (fun p => p.stage.choices) = List.replicate (8*N+2) [] := by
+ obtain ⟨logs,hs,events⟩ := walk table N mem scores execute
+ have low := levelStart_mono L (Nat.zero_le (first₀+i.val))
+ have hroom := header.room
+ have ten : 10 < 2^w := by omega
+ have region := Region.selected X term (10 : Word w) (B.shrink.selectorBits : Word w)
+ (show 10 ≤ (10 : Word w).val by change 10 ≤ 10%(2^w); rw [Nat.mod_eq_of_lt ten]) selectedFit
+ have hi : H < 2^w := by omega
+ have hrs := raw B i X T start base positions blocks t hs region room before hi header pitch
+ have clocks (j : Fin (script₀).size) :
+ ((script₀).plan.recipes j).2.code.length+1+2*Online.N (script₀).size (script₀).size+5 ≤ cap ∧
+ 27+3+4*(((script₀).catalog j).params+1)+2*Online.N (script₀).size (script₀).size+5 ≤ cap :=
+ SourceOnline.scanCap_clocks (p:=⟨HeaderPacket.attach script₀ j pub st mem 27 [],mem,[]⟩) 27 le_rfl clock
+ obtain ⟨ps,gp,ids,logEq⟩ := (W).group L base t rfl rfl hi cap 27 mem logs hrs rows pitch
+ (PublishedHeads.windowLive B base positions blocks t W live) (fun j _ => (clocks j).1) (fun j _ => (clocks j).2)
+ refine ⟨ps,?_,ids,(congrArg eventLog logEq).trans events,?_⟩
+ · rw [before_length,Nat.add_assoc] at gp
+ convert gp using 1; omega
+ · rw [PublishedHeads.chronological_tapes mem ps gp.chronological,logEq,paths hs]
+ congr 1
+ simp [stages,Stage.limit]; omega
+
+end CompressorRecords.ScorePackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScoreOperands.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreOperands.lean
new file mode 100644
index 0000000000..4f1a5672a2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreOperands.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.CompressorShrinkScoreVisits
+import OAI.Computability.VPVNP.CompressorShrinkABSliceOperands
+import OAI.Computability.VPVNP.CompressorShrinkHeaderReads
+import OAI.Computability.VPVNP.CompressorGreedyPlannerFootprint
+import OAI.Computability.VPVNP.CompressorShrinkInputTerms
+
+/-! # Score operands in the actual shrinking block header -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ScorePackets
+
+open BurstRAM Compression BlockPlanner ShrinkBlockInputs DescriptorSpace PhaseRecipe
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+local notation "F" => BlockProgram.geometry B
+local notation "O" => BlockProgram.arena B i.val 0
+local notation "I" => selectedInputs B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0)
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "N" => SelectedArena.motifs X
+
+theorem start_le_term (room : ShrinkInput.termEnd X start 10 < 2^w) : start ≤ (term).val := by
+ let M := ShrinkTermRecipe.M X
+ have earlier : start ≤ ShrinkInput.widthBase X start := by
+ have greedy := GreedyArena.greedyStop_eq start (Fintype.card X.Base) (a i)
+ change start ≤ (((((ShrinkInput.placementBase X start+_)+_)+_)+_)+_)+_
+ change ShrinkInput.placementBase X start = start+_+_ at greedy
+ omega
+ change ShrinkInput.widthBase X start+_+_+2*M+M*10 < 2^w at room
+ change start ≤ (ShrinkInput.widthBase X start+_+_+2*M)%(2^w)
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+
+variable (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w)
+
+set_option maxHeartbeats 1000000 in
+theorem term_values (reads : ShrinkBundlePlan.Reads X F i.val O pub st mem start T)
+ (room : ShrinkInput.termEnd X start 10 < 2^w) :
+ (I).motifs.eval pub st mem = (N : Word w) ∧ (I).termBase.eval pub st mem = term := by
+ let z := ShrinkInput.plan X start
+ let q := ShrinkRankSpace.Shape.collectBank z w
+ let W := ShrinkInput.widthBase X start
+ let ab := ShrinkWidthArena.abBase X q W
+ let M := ShrinkTermRecipe.M X
+ let R := ShrinkBundlePlan.termInputs i.val (a i) O
+ have stopEq : ShrinkInput.stop X start = W+6*M+2*z.B := rfl
+ change ShrinkInput.stop X start+2*M+M*10 < 2^w at room
+ have fit : z.stop < 2^w := by change W < _; omega
+ have hv := z.values T (ShrinkInput.placementBank X T start) Fintype.card_pos fit
+ have hd : ab+2*M = ShrinkInput.stop X start := by
+ rw [stopEq]
+ change W+2*(z.B*(q 4).val)+2*(z.B*(q 4).val)+2*z.B+2*M = _
+ rw [hv.stride]
+ change W+2*M+2*M+2*z.B+2*M = _
+ omega
+ have data := ShrinkBundlePlan.term_input X reads fit
+ refine ⟨(ShrinkTermRecipe.eval_count R X pub st mem data).trans
+ (congrArg (fun z : ℕ => (z : Word w)) (ShrinkTermRecipe.count_card X)),?_⟩
+ have value := ShrinkTermRecipe.eval_term R X pub st mem data
+ change (I).termBase.eval pub st mem = ((ab+2*M+2*M : ℕ) : Word w) at value
+ rw [hd] at value; exact value
+
+theorem term_support {L : Layout} {first : ℕ} (h : ShrinkHeaderReads.Header i X T start L first mem)
+ (entry : LevelFields.Entry L first pub st mem) (D : ℕ → Prop) (pitch : D (pub 1-1).val)
+ (cells : ∀ n ≤ 60, D (levelStart L (first+i.val)+n)) :
+ (I).motifs.ReadsFrom D pub st mem ∧ (I).termBase.ReadsFrom D pub st mem := by
+ have field (n : ℕ) (hn : n ≤ 60) : (LevelFields.scalar i.val n).ReadsFrom D pub st mem :=
+ GreedyVisit.scalar_support D L first i.val n entry pitch (cells n hn) ((Nat.add_le_add_left hn _).trans_lt h.room)
+ have base : (O).ReadsFrom D pub st mem := field 60 le_rfl
+ have inputs := BlockSlices.ab_supported i D pub st mem O O
+ (fun j => field j.val (by have := j.isLt; omega)) base base
+ have count : (I).motifs.ReadsFrom D pub st mem := ⟨inputs.rows,trivial⟩
+ exact ⟨count,⟨⟨inputs.newWidths,trivial,count⟩,trivial,count⟩⟩
+
+end CompressorRecords.ScorePackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScoreVisits.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreVisits.lean
new file mode 100644
index 0000000000..5dd12931c4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreVisits.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.CompressorShrinkScoreBounds
+import OAI.Computability.VPVNP.CompressorBlockHeaderPacket
+import OAI.Computability.VPVNP.CompressorHeaderOperands
+
+/-! # Typed planner launches for the score workers -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ScorePackets
+
+open scoped Fin.CommRing
+
+open BurstRAM TermScores SourceTransport SourceOnline DescriptorSpace PhaseRecipe
+
+variable {w : ℕ} (I : SelectedPlan.Inputs) (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w)
+
+/-- Per-call instruction budget for a score worker, seven for clearing, twenty-seven for an
+axis, and ten for comparison. -/
+def Stage.fuel : Stage → ℕ | .clear => 7 | .axis _ => 27 | .compare => 10
+
+theorem Stage.fuel_le (j : Stage) : j.fuel ≤ 27 := by cases j <;> simp [Stage.fuel]
+
+theorem supported (D : ℕ → Prop) (j : Stage) (term : I.termBase.ReadsFrom D pub st mem)
+ (motifs : I.motifs.ReadsFrom D pub st mem) :
+ HeaderOperands.Supported D pub st mem (j.visit I) := by
+ have score : (SelectedPlan.scoreBase I).ReadsFrom D pub st mem := ⟨term,motifs,trivial⟩
+ cases j with
+ | clear => exact ⟨trivial,trivial,fun _ => score⟩
+ | axis j =>
+ refine ⟨trivial,motifs,?_⟩
+ intro u; change (SelectedPlan.axisBank I j u).ReadsFrom D pub st mem
+ fin_cases u <;> first | exact term | exact score | trivial
+ | compare =>
+ refine ⟨trivial,trivial,?_⟩
+ intro u; fin_cases u
+ exacts [score,⟨score,trivial⟩]
+
+variable (T : Tables w) (n : ℕ)
+
+/-- Relates the planner operands to the native score table by matching the term base, motif
+count, term stride, selector width, score base, and layout cell. -/
+structure Readback : Prop where
+ term : I.termBase.eval pub st mem = T.termBase
+ rows : I.motifs.eval pub st mem = word n
+ stride : (I.termStride : Word w) = T.termStride
+ selectors : (I.selectorBits : Word w) = T.selectorBits
+ score : (SelectedPlan.scoreBase I).eval pub st mem = T.scoreBase
+ cell : (SelectedPlan.layoutCell I).eval pub st mem = T.levelCell
+
+theorem Native.run (D : Layout) (low : levelStart D 0 ≤ T.termBase.val) (region : Region T n)
+ (values : Readback I pub st mem T n) (j : Stage) (rs : List (Report w)) (h : Native T n j mem rs) :
+ HeaderPacket.Run D pub st (j.visit I) mem rs j.fuel (List.replicate (j.limit n) []) := by
+ have bounds := h.bounds T n region j mem rs
+ have pos : 0 < j.fuel := by cases j <;> simp [Stage.fuel]
+ have initial : (j.visit I).initial.eval pub st mem = 0 := by cases j <;> rfl
+ have stop : (j.visit I).stop.eval pub st mem = word (j.limit n) := by
+ cases j <;> first | rfl | exact values.rows
+ refine ⟨pos,?_,(initial ▸ stop ▸ bounds.1),fun a v ha => low.trans (bounds.2.1 a v ha),
+ fun a v ha => low.trans (bounds.2.2 a v ha)⟩
+ cases j with
+ | clear =>
+ subst rs
+ change runSegment (((SelectedPlan.clear I).worker.table.instantiate w
+ (fun _ => (SelectedPlan.scoreBase I).eval pub st mem)).program) 7 (some 0) mem [[]] = _
+ rw [values.score,runSegment,SelectedPlan.clear_native]; rfl
+ | compare =>
+ subst rs
+ have bank : (fun u : Fin 2 => (![SelectedPlan.scoreBase I,SelectedPlan.layoutCell I] u).eval pub st mem) = ![T.scoreBase,T.levelCell] := by
+ funext u; fin_cases u
+ exacts [values.score,values.cell]
+ change runSegment ((SelectedPlan.compareTable.instantiate w (fun u : Fin 2 => (![SelectedPlan.scoreBase I,SelectedPlan.layoutCell I] u).eval pub st mem)).program) 10 (some 0) mem [[]] = _
+ rw [bank,runSegment,SelectedPlan.compare_native]; rfl
+ | axis j =>
+ have bank : (fun u => (SelectedPlan.axisBank I j u).eval pub st mem) = params T (SelectedScore.axes j) := by
+ funext u; fin_cases u <;> first | exact values.term | exact values.stride | exact values.score | exact values.selectors | rfl
+ change runSegment (((PrimedStackRAM.template TermScores.worker 0).instantiate w
+ (fun u => (SelectedPlan.axisBank I j u).eval pub st mem)).program) 27 (some 0) mem (List.replicate n []) = _
+ rw [bank]; exact h
+
+end CompressorRecords.ScorePackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScoreWalk.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreWalk.lean
new file mode 100644
index 0000000000..7ce9474b03
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScoreWalk.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.CompressorShrinkSelectedPlan
+import OAI.Computability.VPVNP.CompressorSourceWalk
+
+/-! # The ten selected-score visits as a chronological native walk
+
+The one-shot calendar programs return cursor one. Their memory operations
+coincide with the clear and comparison operations in the score calculation.
+The eight strided scans use exactly the original reports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ScorePackets
+
+open BurstRAM BlockPlanner PhaseRecipe TermScores
+
+/-- A stage of layout scoring clears both accumulators, scans one of the eight layout-and-role
+coordinates, or compares the totals to choose a layout. -/
+inductive Stage where
+ | clear
+ | axis (j : Fin 8)
+ | compare
+
+/-- Score stages in execution order, clearing the accumulators once, scanning coordinates zero
+through seven, then comparing the two layout scores. -/
+def stages : List Stage := [.clear] ++ List.ofFn Stage.axis ++ [.compare]
+/-- The planner visit implementing a score stage on the selected plan’s term and accumulator
+tables. -/
+def Stage.visit (I : SelectedPlan.Inputs) : Stage → Visit
+ | .clear => SelectedPlan.clear I
+ | .axis j => SelectedPlan.axis I j
+ | .compare => SelectedPlan.compare I
+
+/-- The ten score visits obtained by translating the ordered score stages into planner visits
+for the supplied inputs. -/
+def visits (I : SelectedPlan.Inputs) := stages.map (Stage.visit I)
+
+theorem visits_eq (I : SelectedPlan.Inputs) :
+ visits I = [SelectedPlan.clear I] ++ List.ofFn (SelectedPlan.axis I) ++ [SelectedPlan.compare I] := by
+ simp [visits,stages,Stage.visit]
+
+theorem length : stages.length = 10 := by simp [stages]
+
+variable {w : ℕ} (T : Tables w) (n : ℕ)
+
+/-- Give a one-shot score report the calendar’s return cursor of one while retaining its event
+trace. -/
+def advance (r : Report w) : Report w := ⟨r.events,some 1⟩
+
+/-- Specifies a stage’s source reports. An axis executes its score worker once per motif with
+empty choices, while clearing and comparison each produce one report returning cursor one. -/
+def Native : Stage → Memory w → List (Report w) → Prop
+ | .clear,_,rs => rs = [advance (clearReport T)]
+ | .axis j,m,rs => runSegment (workerMachine T (SelectedScore.axes j)).program 27 (some 0) m
+ (List.replicate n []) = some rs
+ | .compare,m,rs => rs = [advance (compareReport T m)]
+
+private theorem axis_walk (js : List (Fin 8)) (mem : Memory w) (rs : List (Report w))
+ (hr : runAxes T n (js.map SelectedScore.axes) mem = some rs) :
+ SourceWalk (Native T n) (js.map Stage.axis) mem rs := by
+ induction js generalizing mem rs with
+ | nil =>
+ have e : [] = rs := Option.some.inj hr
+ subst rs
+ exact .done mem
+ | cons j js ih =>
+ simp only [List.map_cons,runAxes] at hr
+ cases hp : runSegment (workerMachine T (SelectedScore.axes j)).program 27 (some 0) mem
+ (List.replicate n []) with
+ | none => simp [hp] at hr
+ | some head =>
+ cases ht : runAxes T n (js.map SelectedScore.axes) (after mem (eventLog head)) with
+ | none => simp [hp,ht] at hr
+ | some tail =>
+ simp [hp,ht] at hr
+ subst rs
+ exact .next hp (ih _ _ ht)
+
+/-- Decompose the actual native score calculation into its ten recipe
+occurrences, retaining every event and the complete post-memory. -/
+theorem walk (mem : Memory w) (rs : List (Report w))
+ (hr : run T n (List.ofFn SelectedScore.axes) mem = some rs) :
+ ∃ logs, SourceWalk (Native T n) stages mem logs ∧ eventLog logs = eventLog rs := by
+ let c := clearReport T
+ let mc := after mem c.events
+ rw [run,execute_clear] at hr
+ change (runAxes T n (List.ofFn SelectedScore.axes) mc).bind _ = _ at hr
+ cases ha : runAxes T n (List.ofFn SelectedScore.axes) mc with
+ | none => rw [ha] at hr; cases hr
+ | some middle =>
+ let last := after mc (eventLog middle)
+ rw [ha] at hr
+ change (execute (compareMachine T).program 10 ((compareMachine T).program.start 0) last []).bind _ = _ at hr
+ rw [execute_compare] at hr
+ have e : c :: (middle ++ [compareReport T last]) = rs := Option.some.inj hr
+ subst rs
+ have ha' := axis_walk T n (List.ofFn id) mc middle (by simpa only [List.map_ofFn,Function.comp_id] using ha)
+ have hw : SourceWalk (Native T n) (List.ofFn Stage.axis) mc middle := by
+ simpa only [List.map_ofFn,Function.comp_id] using ha'
+ have hlast : SourceWalk (Native T n) [.compare] last [advance (compareReport T last)] :=
+ SourceWalk.singleton (i := Stage.compare) rfl
+ refine ⟨advance c :: (middle ++ [advance (compareReport T last)]),?_,?_⟩
+ · change SourceWalk (Native T n) (.clear :: (List.ofFn Stage.axis ++ [.compare])) mem
+ ([advance c] ++ (middle ++ [advance (compareReport T last)]))
+ exact .next (show Native T n .clear mem [advance c] from rfl) (hw.append hlast)
+ · simp [eventLog,advance]
+
+end CompressorRecords.ScorePackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedEmission.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedEmission.lean
new file mode 100644
index 0000000000..25f35cea55
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedEmission.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.CompressorShrinkCurrentResident
+
+/-! # The shrinking directory produced by the selected native term and placement passes -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace CompressorRecords.ShrinkScheduledTail
+
+open BurstRAM Compression DescriptorSpace BlockPlanner SourceOnline BlockHeaderRun
+open SelectedDirectoryHistory PairSimulation.TraversalRows
+open scoped Fin.CommRing
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} {B : S.Templates}
+variable {f : B.Entry → R} {hf : B.IsSolution f} {i : Fin S.steps} {w g : ℕ}
+variable {X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)}
+variable {sel : SelectedScore.Selection B X} {tape : List Bool}
+variable {workspace : Word w} {positions blocks t cap n : ℕ} {m : Memory w}
+local notation "scr" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B workspace.val positions blocks
+local notation "first" => Script.levelsPerBlock scr * t
+local notation "cur" => first + i.val
+local notation "head" => levelStart L cur
+local notation "nxt" => levelStart L (cur + 1)
+local notation "start" => tableBase L cur (0 : Fin 6)
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog scr)) workspace
+local notation "v" => shrinkLevel B f hf i X sel tape
+variable {ms ps : List (Packet (BlockProgram.script B) w)}
+variable (r : Result (g := g) B workspace positions blocks t cap i X m ms ps)
+
+private theorem and_rec {a b : Prop} {motive : a ∧ b → Sort*}
+ (f : ∀ x y, motive ⟨x, y⟩) (h : a ∧ b) : And.rec (motive := motive) f h = f h.1 h.2 := by
+ cases h
+ rfl
+
+/-- The actual selected placement and preimage collection supply both the
+ordered child lists and the five operands installed in the header. Between
+the collector and the tail the other kernels retain its occupied table. -/
+def Result.selectedEmission (T : IncidenceDirectory w) {selectors : Word w} {p₀ : Fin 14 → Word w}
+ {source : Memory w} {p : SelectedStage.Passes w} {q : SelectedFinish.Passes w}
+ (built : SelectedFinish.Built B X term 10 selectors p₀ sel source p q)
+ (slotRoom : SelectedFinish.stop X term 10 ≤ nxt) (nxtFit : nxt < 2 ^ w)
+ (termFit : ShrinkInput.termEnd X start 10 < 2 ^ w)
+ (keep : ∀ x, start ≤ x → x < SelectedFinish.stop X term 10 → m x = q.final (p.final source) x)
+ (header : ShrinkHeaderReads.Header i X T start L first m)
+ (pitch : m ((pt).directory - 1).val = (levelWords L : Word w))
+ (rows : m (pt).rows.val = (directoryRows L : Word w))
+ (length : m (levelStart L 0 + 29) = (n : Word w)) : Emission L cur v m (post m ps) := by
+ let finish := SelectedFinish.stop X term 10
+ have room : finish < 2 ^ w := slotRoom.trans_lt nxtFit
+ let d := selectedShrinkDirectory B f hf i X term 10 selectors
+ p₀ sel source p q tape built room.le
+ let shr := SelectedFinish.shr X term 10 p₀ source p
+ have bank : d.pub = SelectedFinish.params X term 10 shr := by
+ simp only [d, selectedShrinkDirectory, SelectedFinish.Built.selectedDirectory,
+ ShrinkPreimages.selectedDirectory]
+ simp only [and_rec]
+ rfl
+ have termLo : start ≤ (term).val := by
+ obtain ⟨a, b, c, d'⟩ := ShrinkInput.range_bounds X start
+ have bound := a.trans (b.trans (c.trans d'))
+ unfold ShrinkInput.termEnd at termFit
+ change start ≤ (ShrinkInput.stop X start + 2 * _ )%(2 ^ w)
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+ have headLo : head + 54 ≤ start := by
+ change head + 54 ≤ head + 66 + 6 * slotCapacity L + 0 * tableWords L
+ omega
+ have dirLo : start ≤ (d.pub 1).val := by
+ rw [bank]
+ change start ≤ (SelectedArena.placementWord X term 10 0).val
+ have fits : SelectedArena.Fits X term (10 : Word w) := by
+ change SelectedArena.endAddr X term 10 < 2 ^ w
+ change SelectedArena.endAddr X term 10 + ShrinkPreimages.newCount X
+ + ShrinkPreimages.oldCount X
+ < 2 ^ w at room
+ omega
+ rw [SelectedArena.column_value X term 10 fits]
+ unfold SelectedArena.placementBase SelectedArena.origin
+ omega
+ let live := d.transport (m' := m) (fun x hx =>
+ (keep x (dirLo.trans (Directory.cells_interval d hx).1) (Directory.cells_interval d hx).2).symm)
+ let widened : LevelDirectory v m nxt := {live with inputEnd := live.inputEnd.trans slotRoom}
+ exact r.emission T widened shr bank (headLo.trans dirLo) header pitch termFit rows length
+
+end CompressorRecords.ShrinkScheduledTail
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedGroup.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedGroup.lean
new file mode 100644
index 0000000000..dfcfdbaea0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedGroup.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.CompressorShrinkSelectedTailGroup
+import OAI.Computability.VPVNP.CompressorShrinkScoreGroup
+import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch
+
+/-! # Fourteen selected-geometry visits on each admitted shrinking branch -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.SelectedTailPackets
+
+open BurstRAM Compression ShrinkBlockInputs BlockPlanner DescriptorSpace Schedule SourceTransport
+open scoped Fin.CommRing Classical
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+variable (base : Word w) (positions blocks t : ℕ)
+local notation "prog" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (arity (BlockPlanner.Script.catalog (BlockProgram.script B))) base
+local notation "pub" => Schedule.Ports.data pt
+local notation "first₀" => BlockPlanner.Script.levelsPerBlock (BlockProgram.script B)*t
+local notation "H" => levelStart L 0
+local notation "head" => levelStart L (first₀+i.val)
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "p₀" => ShrinkInput.placementBank X T start
+local notation "tab" => SelectedArena.scoreTables X term (10 : Word w) (B.shrink.selectorBits : Word w)
+
+/-- Total source calls for the selected geometry, including two one-shot score calls, eight
+score calls per motif, and the four scans for placement, roles, and the child directory. -/
+def selectedCalls {a g : ℕ} (X : State a (packingLaneBits a g)) :=
+ (8*SelectedArena.motifs X+2)+(SelectedArena.positions X+(DemandRAM.oldCount X+
+ (ShrinkPreimages.newCount X+ShrinkPreimages.oldCount X)))
+
+
+private theorem preliminaryFloor {mem : Memory w} (r : ShrinkInput.Run X T start mem)
+ (lo : ℕ) (before : lo ≤ start) (inc : ∀ j, lo≤(T.column j).val) :
+ lo ≤ ShrinkHistoryTrace.inputFloor p₀ := by
+ have h := GreedyArena.bounds start (Fintype.card X.Base) (a i)
+ have room := r.greedy.room
+ have v₁ : GreedyArena.colorBase start < 2^w := by omega
+ have v₂ : GreedyArena.offsetBase start (Fintype.card X.Base) (a i) < 2^w := by omega
+ apply le_min
+ · apply le_min
+ · change lo≤GreedyArena.colorBase start%(2^w); rw [Nat.mod_eq_of_lt v₁]; exact before
+ · change lo≤GreedyArena.offsetBase start _ _%(2^w); rw [Nat.mod_eq_of_lt v₂]
+ exact before.trans (by unfold GreedyArena.offsetBase; omega)
+ · exact le_min (inc 0) (inc 2)
+
+set_option maxHeartbeats 2000000 in
+/-- The fixed ten-score and four-directory groups join at the score post-memory.
+The branch supplies all native proofs. The returned memory is the entry for
+the next resident-directory group. -/
+theorem selected_group (s : SelectedScore.Selection B X) (m : Memory w) (fuel cap : ℕ)
+ (p : ShrinkBranch.Prefix X T start fuel m)
+ (v : ShrinkBranch.Selected B X T start (10 : Word w) (B.shrink.selectorBits : Word w) fuel m p s)
+ (fits : ShrinkBranch.PrefixFits B X T start (10 : Word w) fuel) (room : SelectedFinish.stop X term 10 ≤ 2^w)
+ (header : ShrinkHeaderReads.Header i X T start L (first₀) p.beforeTerm) (before : head+60 < start)
+ (inc : ∀ j, H≤(T.column j).val) (rows : p.beforeTerm (pt).rows.val = (directoryRows L : Word w))
+ (pitch : p.beforeTerm (pub 1-1).val = (levelWords L : Word w))
+ (within : t q.stage.choices)=List.replicate (selectedCalls X) [] := by
+ intro mem ordinal
+ let r := v.geometry.placed
+ let c := v.geometry.children
+ have exec := v.postTerm.placed
+ have selected := v.postTerm.selected
+ have finish := v.postTerm.geometry
+ have ten : 10<2^w := by have := header.room; omega
+ have small : (10 : Word w).val=10 := Nat.mod_eq_of_lt ten
+ have terms := fits.termRoom
+ rw [small] at terms
+ have lo := ScorePackets.start_le_term i X start terms
+ have h0 : H≤head := levelStart_mono L (Nat.zero_le _)
+ have startLo : H≤start := by omega
+ have baseFit : H<2^w := (levelStart_mono L (Nat.zero_le _)).trans_lt fit
+ have hctrl := Window.lowCells (A:=prog) L base rfl rfl baseFit
+ have beforeTerm (j : ℕ) (hj : j choiceBits z.events)=_ from paths (n:=SelectedArena.positions X) exec.positions,
+ show r.roles.map (fun z => choiceBits z.events)=_ from paths (n:=DemandRAM.oldCount X) exec.roles,
+ show c.clear.map (fun z => choiceBits z.events)=_ from paths (n:=ShrinkPreimages.newCount X) finish.raw.clear,
+ show c.collect.map (fun z => choiceBits z.events)=_ from paths (n:=ShrinkPreimages.oldCount X) finish.raw.collect]
+ simp only [← List.replicate_add,selectedCalls]
+
+end CompressorRecords.SelectedTailPackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedOutput.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedOutput.lean
new file mode 100644
index 0000000000..3605b84046
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedOutput.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.CompressorRecordsShrinkOutputBuild
+import OAI.Computability.VPVNP.CompressorShrinkResidentTerms
+import OAI.Computability.VPVNP.CompressorShrinkOutputRetained
+import OAI.Computability.VPVNP.CompressorSurvivingSweep
+
+/-! # The fixed output workers after a selected shrinking pass
+
+The four role programs read the layout bit, dense-to-absolute motif table,
+and selected term fields from one post-selection memory. The slot passes
+consume their absolute width rectangle. Their complete trace preserves
+the preimage directory and gives the next state's six incidence columns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkOutput
+
+open Compression Compression.PackingData Compression.ShrinkMotif MotifBlocks MotifGrid
+open BurstRAM SlotLevel ShrinkSlots ShrinkSliceSweep SurvivingNative
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {a b g w : ℕ} {δ : ℝ}
+variable (B : S.Templates) (X : State a (packingLaneBits a g))
+variable (ready : Ready (2^a) (Shrink.colors a) (2^b) δ) (sel : SelectedScore.Selection B X)
+variable (term stride abs : Word w)
+
+/-- Word address of the chosen layout bit, two cells after the start of the score arena. -/
+abbrev layoutWord := Fin.ofNat (2^w) (SelectedArena.origin X term stride+2)
+
+local notation "sh" => levelShape (b := b) X
+local notation "role" => SelectedArena.roleBase X term stride
+local notation "keepEnd" => SelectedFinish.stop X term stride
+local notation "cutoff" => widthBase X term.val stride.val role keepEnd
+local notation "T" => splitBank (b := b) X B.shrink sel term stride.val role keepEnd
+local notation "side" => SelectedFinish.chosen B X sel
+local notation "sz" => selected X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) T B.shrink X.packingWidth sel
+
+local notation "bankAt" => splitBank (b := b) X B.shrink sel term stride.val role
+local notation "sizesAt" => fun floor : ℕ => selected X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex)
+ (bankAt floor) B.shrink X.packingWidth sel
+
+/-- The width-scan traces for the four surviving roles, their output memory, and the subsequent
+construction of the successor’s slot tables. -/
+structure Passes (w : ℕ) where
+ /-- Lists of native width reports grouped by surviving role, in the order of the four role
+ sweeps. -/
+ widthRows : List (List (Report w))
+ /-- The memory handed from the four role width sweeps to the slot-table construction. -/
+ postWidths : Memory w
+ /-- Construction traces that consume the role widths and build the successor’s slot and
+ incidence tables. -/
+ slots : Build.Construction w
+
+/-- The full output trace, with the role width reports flattened in sweep order and followed by
+all slot-construction reports. -/
+def Passes.reports (p : Passes w) := p.widthRows.flatten++p.slots.all
+/-- Memory obtained by replaying the slot construction from the memory produced by the width
+sweeps. -/
+def Passes.final (p : Passes w) := p.slots.final p.postWidths
+
+/-- The actual fixed controls and final readback on one selected branch. -/
+structure Complete (cap : ℕ) (mem : Memory w) (p : Passes w) (floor : ℕ := keepEnd)
+ (slotStart : ℕ := (slotHeads (b := b) X term.val stride.val role floor).role) : Prop where
+ sweep : SurvivingPass.Roles (bankAt floor) (sizesAt floor) (fun t => program (bankAt floor) t abs (layoutWord X term stride)) (fun _ => cap)
+ (fun t => SurvivingNative.Site (bankAt floor) t abs (layoutWord X term stride)) (List.finRange 4) mem p.postWidths p.widthRows
+ construction : Constructed X B.shrink ready sel term stride.val role floor mem p.postWidths p.slots slotStart
+ preimages : ShrinkPreimages.Directory X side (SelectedFinish.counts X term stride) (SelectedFinish.rows X term stride) p.final
+ directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber abs p.final
+ replay : after mem (eventLog p.reports) = p.final
+ probes : RAMBuckets.cost Report.probes p.reports = 18*(motifCount X*(bankAt floor).stride)+slotProbes sh
+ rowCounts : p.widthRows.map List.length = List.ofFn (fun t => motifCount X*(bankAt floor).subdiv t)
+
+set_option maxHeartbeats 1800000 in
+/-- Execute the same fixed controls at the width-table and slot-table heads
+chosen by the block calendar. A gap between the two tables is permitted. -/
+theorem build_at (input : Memory w) (floor slotStart : ℕ) (keepBefore : keepEnd ≤ floor)
+ (wide : 10 ≤ stride.val) (hw : FitsWords (b := b) X B.shrink term stride.val role floor)
+ (slotAfter : (bankAt floor).last ≤ slotStart) (slotRoom : finish sh (heads sh role slotStart) < 2^w)
+ (absBefore : abs.val+motifCount X ≤ keepEnd)
+ (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber abs input)
+ (terms : Terms X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) (bankAt floor) B.shrink X.packingWidth sel input)
+ (roles : DemandRAM.RoleColumns X side role input)
+ (sideWord : input (SelectedArena.origin X term stride+2) = ((side).toNat : Word w))
+ (preimages : ShrinkPreimages.Directory X side (SelectedFinish.counts X term stride) (SelectedFinish.rows X term stride) input)
+ (cap : ℕ) (fuel : SurvivingNative.ops.length < cap) :
+ ∃ result : Passes w, Complete B X ready sel term stride abs cap input result floor slotStart := by
+ let fit := fits X B.shrink sel term stride.val role floor ready wide hw.room
+ have lower := keepBefore.trans (retained_room X term stride.val role floor)
+ have upper := (width_le_slots (b := b) X term stride.val role floor).trans (slots_le_stop X term stride.val role floor)
+ have idFit := absBefore.trans (lower.trans (upper.trans hw.room.le))
+ have idLo (j : Fin (motifCount X)) : abs.val+j.val < widthBase X term.val stride.val role floor := (Nat.add_lt_add_left j.isLt _).trans_le (absBefore.trans lower)
+ have sideLo : SelectedArena.origin X term stride+2 < keepEnd := by
+ unfold SelectedFinish.stop SelectedFinish.rowStart SelectedFinish.countStart SelectedArena.endAddr
+ SelectedArena.roleBase SelectedArena.placementBase
+ omega
+ have sideEq : (layoutWord X term stride).val = SelectedArena.origin X term stride+2 :=
+ Nat.mod_eq_of_lt (sideLo.trans_le (lower.trans (upper.trans hw.room.le)))
+ have chosenWord : (input (layoutWord X term stride).val).val = (bankAt floor).layout.toNat := by
+ rw [sideEq]
+ have hsmall : (side).toNat ≤ 1 := by cases side <;> decide
+ have bitFit : (side).toNat < 2^w := hsmall.trans_lt (by have := fit.roles; omega)
+ exact (congrArg Fin.val sideWord).trans (Nat.mod_eq_of_lt bitFit)
+ have absolute := directory_for_selected B.shrink X term abs stride.val (widthBase X term.val stride.val role floor) (sh).subdivisions sel input directory
+ obtain ⟨out,rows,walk,_,_,images,values,frame,lengths,_,cost⟩ :=
+ SurvivingSweep.graph X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) X.baseIndex
+ (bitWordFinEquiv (Shrink.J a)) (bitWordFinEquiv g) (bankAt floor) B.shrink X.packingWidth sel
+ rfl fit (Nat.mod_eq_of_lt hw.selector) (supply_fit X B.shrink sel term stride.val role floor hw)
+ abs (layoutWord X term stride) idFit (fun i j => (bankAt floor).rowOutside fit i _ (.inl (idLo j)))
+ (fun i => (bankAt floor).rowOutside fit i _ (.inl (sideEq ▸ sideLo.trans_le lower))) cap fuel input absolute chosenWord terms
+ obtain ⟨slot,constructed⟩ := finish_after_sweep_at X B.shrink ready sel term stride.val role floor slotStart slotAfter slotRoom wide hw input out
+ roles images values frame
+ let result : Passes w := ⟨rows,out,slot⟩
+ refine ⟨result,⟨walk,constructed,?_,?_,?_,?_,lengths⟩⟩
+ · exact preimages_retained X term stride preimages (fun j hj => constructed.frame j (.inl (hj.trans_le lower)))
+ · intro j
+ exact (congrArg Fin.val (constructed.frame _ (.inl (idLo j)))).trans (directory j)
+ · change after input (eventLog (rows.flatten++slot.all)) = slot.final out
+ rw [show after input (eventLog (rows.flatten++slot.all)) = after (after input (eventLog rows.flatten)) (eventLog slot.all) by
+ simp only [after,eventLog,List.flatMap_append,List.foldl_append],walk.replay,slot.final_eq]
+ · exact (RAMBuckets.cost_append Report.probes rows.flatten slot.all).trans (congrArg₂ (·+·) cost constructed.probes)
+
+set_option maxHeartbeats 1800000 in
+/-- The width and ordered-slot arrays are produced from the earlier selected
+stage and the physical absolute-ID table. The layout bit remains at its
+score-comparison address through the preimage and output passes. -/
+theorem build_selected (selectors : Word w) (p₀ : Fin 14 → Word w) (mem : Memory w)
+ (p : SelectedStage.Passes w) (q : SelectedFinish.Passes w)
+ (chosen : SelectedFinish.Built B X term stride selectors p₀ sel mem p q)
+ (wide : 10 ≤ stride.val) (hw : FitsWords (b := b) X B.shrink term stride.val role keepEnd)
+ (absBefore : abs.val+motifCount X ≤ keepEnd)
+ (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber abs (q.final (p.final mem)))
+ (cap : ℕ) (fuel : SurvivingNative.ops.length < cap) :
+ ∃ result : Passes w, Complete B X ready sel term stride abs cap (q.final (p.final mem)) result :=
+ build_at B X ready sel term stride abs (q.final (p.final mem)) keepEnd
+ (slotHeads (b := b) X term.val stride.val role keepEnd).role le_rfl wide hw le_rfl hw.room absBefore directory
+ (resident_terms (b := b) B X term stride selectors role keepEnd sel _ chosen.terms)
+ chosen.roles chosen.chosenCell chosen.raw.directory cap fuel
+
+end CompressorRecords.ShrinkOutput
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedPlan.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedPlan.lean
new file mode 100644
index 0000000000..b912cd0544
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedPlan.lean
@@ -0,0 +1,274 @@
+import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner
+import OAI.Computability.VPVNP.CompressorRecordsSelectedScoreRun
+import OAI.Computability.VPVNP.CompressorRecordsSelectedArenaDemand
+import OAI.Computability.VPVNP.CompressorRecordsShrinkPreimages
+
+/-!
+# Selected layout, placement, role and child-directory visits
+
+The two scores and chosen layout bit follow the strided term array.
+Four placement columns and the absolute arc role rows follow. The
+preimage collector appends old sites in their numeric order after clearing
+a counter for each new site. The one-shot score stages return cursor one
+after writing their result to its designated cell.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SelectedPlan
+
+open BurstRAM BurstRAM.PrivateRAM Compression BlockPlanner PhaseRecipe PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Counts, term-table dimensions and placement operands used to score both shrinking layouts
+and build the chosen layout’s placement, arc-role and child tables. -/
+structure Inputs where
+ /-- Expression for the number of old sites. It sets the length of each placement column and
+ the number of calls to the preimage collector. -/
+ oldSites : Expr
+ /-- Expression for the number of packed sites after shrinking. Each packed site receives a
+ child count and one row of old-site indices. -/
+ newSites : Expr
+ /-- Expression for the number of old arc slots. The role pass visits each slot and reserves
+ four words per absolute arc. -/
+ oldSlots : Expr
+ /-- Expression for the number of motif term records scanned on each of the eight score
+ coordinates. -/
+ motifs : Expr
+ /-- Address expression for the first motif’s selected term record. The score passes read the
+ repetition and supply fields relative to this base. -/
+ termBase : Expr
+ /-- Distance in words between successive motif term records, used to locate each record and
+ the score cells following the last one. -/
+ termStride : ℕ
+ /-- Number of selector bits per repetition. Each score pass adds the repetition count times
+ this width to its coordinate’s payload width. -/
+ selectorBits : ℕ
+ /-- The fourteen operand expressions for the preliminary placement pass. The selected pass
+ reuses its dimensions and input columns, supplying the chosen layout bit and fresh output
+ addresses. -/
+ preliminary : Fin 14 → Expr
+ /-- Address expression for the old incidence directory’s actual-out column, used by the role
+ pass to find the target of each old arc. -/
+ oldActualOut : Expr
+
+variable (I : Inputs)
+
+/-- Start of the two layout-score accumulators, immediately after the strided array of motif
+term records. -/
+def scoreBase := I.termBase.add (I.motifs.mul (.lit I.termStride))
+/-- Address of the chosen-layout bit, two words past the start of the score accumulators. -/
+def layoutCell := (scoreBase I).add (.lit 2)
+/-- Load the chosen-layout bit from the cell written by the score comparison. -/
+def layout := Expr.load (layoutCell I)
+/-- Start of the selected placement columns, immediately after the two scores and their
+comparison bit. -/
+def placementBase := (scoreBase I).add (.lit 3)
+/-- Base address of column `c` in the selected placement table. In order, the columns store the
+owner, thick-site bit, assigned bundle and bundle target, with one word per old site. -/
+def placementColumn (c : Fin 4) := (placementBase I).add ((Expr.lit c.val).mul I.oldSites)
+/-- Start of the four-word demand-role records indexed by absolute old arc, following the four
+placement columns. -/
+def roleBase := (placementBase I).add ((Expr.lit 4).mul I.oldSites)
+/-- First address after the old-arc role records and base of the child-count array indexed by
+packed site. -/
+def roleEnd := (roleBase I).add ((Expr.lit 4).mul I.oldSlots)
+/-- Base of the rectangular child table, just past the count word for the last packed site. -/
+def childRows := (roleEnd I).add I.newSites
+/-- First address after the child table, which reserves one word for every old site across all
+packed-site rows. -/
+def preimageEnd := (childRows I).add I.oldSites
+
+/-- One-shot visit that zeros both layout-score accumulators before the coordinate scans and
+returns cursor one. -/
+def clear : Visit := ops TermScores.clearCode 2 (.lit 0) (.lit 1) (fun _ ↦ scoreBase I)
+
+theorem clear_native (L : TermScores.Tables w) (m : Memory w) :
+ let P := ((clear I).worker.table.instantiate w (fun _ ↦ L.scoreBase)).program
+ execute P 7 (P.start 0) m [] = some ⟨(TermScores.clearReport L).events,some 1⟩ := rfl
+
+/-- Seven operands for score coordinate `j` comprise the term base and stride, score base,
+selector width, coordinate index, layout side and relative-mass weight. -/
+noncomputable def axisBank (j : Fin 8) : Fin 7 → Expr :=
+ let e := SelectedScore.supplyOrder.entries j
+ ![I.termBase,.lit I.termStride,scoreBase I,.lit I.selectorBits,.lit j.val,.lit e.1.toNat,
+ .lit (MotifAdmission.weight ShrinkMotif.relativeMass e.2)]
+
+/-- Scan all motif term records for coordinate `j`, adding the weighted square of each supply
+width to that coordinate’s layout score. -/
+noncomputable def axis (j : Fin 8) : Visit :=
+ ops TermScores.worker 0 (.lit 0) I.motifs (axisBank I j)
+
+/-- The source comparison leaves one in register two on both outcomes. Its
+published bit is still taken from register four. -/
+def compareTable : Template 11 5 2 :=
+ { TermScores.compareTemplate with code := fun pc ↦ if pc.val = 10 then .returnState 2
+ else TermScores.compareTemplate.code pc }
+
+/-- Compare the two scores once and store one in the layout cell exactly when the second score
+is smaller. The visit returns cursor one on either outcome. -/
+def compare : Visit :=
+ ⟨⟨_,_,_,compareTable⟩,.lit 0,.lit 1,![scoreBase I,layoutCell I]⟩
+
+theorem compare_native (L : TermScores.Tables w) (m : Memory w) :
+ let M := compareTable.instantiate w ![L.scoreBase,L.levelCell]
+ execute M.program 10 (M.program.start 0) m [] = some ⟨(TermScores.compareReport L
+ m).events,some 1⟩ := by
+ let M := compareTable.instantiate w ![L.scoreBase,L.levelCell]
+ let c := (((M.program.start 0).put 1 0 L.scoreBase).put 2 1 (m L.scoreBase.val)).put 3 2 1
+ let d := (c.put 4 0 (L.scoreBase+1)).put 5 3 (m (L.scoreBase+1).val)
+ let pc := if m (L.scoreBase+1).val < m L.scoreBase.val then (6 : Fin 11) else 7
+ change (execute M.program 4 {d with pc := pc} m [] |>.map (Report.prepend .tick)
+ |>.map (Report.prepend (.read (L.scoreBase+1) (m (L.scoreBase+1).val)))
+ |>.map (Report.prepend .tick) |>.map (Report.prepend .tick)
+ |>.map (Report.prepend (.read L.scoreBase (m L.scoreBase.val))) |>.map (Report.prepend .tick))
+ = _
+ by_cases h : m (L.scoreBase+1).val < m L.scoreBase.val <;>
+ simp only [pc,h,↓reduceIte,TermScores.compareReport,TermScores.bit] <;> rfl
+
+/-- Operands for recomputing placement. Slot 5 reads the winning layout bit, slots 10 through
+13 point to the selected output columns, and the other slots come from preliminary
+placement. -/
+def placementBank : Fin 14 → Expr :=
+ ![I.preliminary 0,I.preliminary 1,I.preliminary 2,I.preliminary 3,I.preliminary 4,layout I,
+ I.preliminary 6,I.preliminary 7,I.preliminary 8,I.preliminary 9,
+ placementColumn I 0,placementColumn I 1,placementColumn I 2,placementColumn I 3]
+
+/-- Scan the old sites with the chosen layout and write the owner, thick-site bit, assigned
+bundle and bundle target for each site. -/
+def placement : Visit := ops ShrinkRAM.visit 0 (.lit 0) I.oldSites (placementBank I)
+
+/-- Operands for the absolute arc-role pass, combining the preliminary dimensions, old
+actual-out column, selected placement columns and role-table destination. -/
+def rolesBank : Fin 11 → Expr :=
+ ![I.preliminary 2,I.preliminary 0,I.preliminary 1,I.preliminary 3,.lit 0,I.oldActualOut,
+ placementColumn I 1,placementColumn I 0,placementColumn I 2,placementColumn I 3,roleBase I]
+
+/-- Visit every old arc slot and write its four-word demand-role record at the absolute arc
+index using the selected placement. -/
+def roles : Visit := ops DemandRAM.visit 0 (.lit 0) I.oldSlots (rolesBank I)
+
+/-- Zero the child counter for each packed site before the preimage collector begins appending
+old sites. -/
+def clearChildren : Visit := ops SliceRAM.clearOps 0 (.lit 0) I.newSites (fun _ ↦ roleEnd I)
+
+/-- Six operands for collecting preimages comprise the old-site count, selected owner column,
+packed-site count, child-count base, row capacity at exponent `a`, and child-row base. -/
+def childBank (a : ℕ) : Fin 6 → Expr :=
+ ![I.oldSites,placementColumn I 0,I.newSites,roleEnd I,.lit
+ (ShrinkPreimages.capacity a),childRows I]
+
+/-- Visit old sites in increasing index order, appending each index to its selected owner’s
+child row and incrementing that owner’s count. -/
+def children (a : ℕ) : Visit := ops collectPreimage 3 (.lit 0) I.oldSites (childBank I a)
+
+/-- The fourteen visits that clear the scores, scan eight supply coordinates, choose the
+layout, write placement and arc roles, then clear the child counts and collect preimages. -/
+noncomputable def visits (a : ℕ) : List Visit :=
+ [clear I] ++ List.ofFn (axis I) ++ [compare I,placement I,roles I,clearChildren I,children I a]
+
+theorem visits_length (a : ℕ) : (visits I a).length = 14 := by simp [visits]
+
+section Values
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g)) (p₀ : Fin 14 → Word w)
+ (T : IncidenceDirectory w) (term : Word w) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w)
+
+local notation "ev" => Expr.eval pub state m
+
+/-- Relates the evaluated input expressions to a shrinking state’s site, arc and motif counts,
+term base, actual-out column and preliminary operands, and requires the term stride to fit
+in a word. -/
+structure Reads : Prop where
+ sites : ev I.oldSites = ((ShrinkPreimages.oldCount X : ℕ) : Word w)
+ nextSites : ev I.newSites = ((ShrinkPreimages.newCount X : ℕ) : Word w)
+ slots : ev I.oldSlots = ((DemandRAM.oldCount X : ℕ) : Word w)
+ motifs : ev I.motifs = ((SelectedArena.motifs X : ℕ) : Word w)
+ term : ev I.termBase = term
+ strideFit : I.termStride < 2^w
+ oldOut : ev I.oldActualOut = T.actualOut
+ prior : ∀ i, ev (I.preliminary i) = p₀ i
+
+variable (read : Reads I X p₀ T term pub state m)
+
+local notation "L" => SelectedArena.scoreTables X term (I.termStride : Word w)
+ (I.selectorBits : Word w)
+
+private theorem ev_add (u v : Expr) : ev (u.add v) = ev u + ev v := rfl
+private theorem ev_mul (u v : Expr) : ev (u.mul v) = ev u * ev v := rfl
+private theorem ev_lit (u : ℕ) : ev (.lit u) = (u : Word w) := rfl
+
+include read in
+theorem score_head : ev (scoreBase I) = (SelectedArena.origin X term (I.termStride : Word w)
+ : Word w) := by
+ have ht : (term.val : Word w) = term := Fin.ext (Nat.mod_eq_of_lt term.isLt)
+ simp [scoreBase, ev_add, ev_mul, ev_lit, read.term, read.motifs, SelectedArena.origin, ht,
+ Nat.mod_eq_of_lt read.strideFit]
+
+include read in
+theorem axis_bank (j : Fin 8) :
+ (fun i ↦ ev (axisBank I j i)) = TermScores.params L (SelectedScore.axes j) := by
+ funext i
+ fin_cases i <;> first | exact read.term | exact score_head I X p₀ T term pub state m read | rfl
+
+include read in
+theorem placement_column (c : Fin 4) :
+ ev (placementColumn I c) = SelectedArena.placementWord X term (I.termStride : Word w) c := by
+ simp only [placementColumn,placementBase,ev_add,ev_mul,ev_lit,score_head I X p₀ T term pub state
+ m read,read.sites]
+ change _ = ((SelectedArena.origin X term
+ (I.termStride : Word w)+3+c.val*ShrinkPreimages.oldCount X : ℕ) : Word w)
+ push_cast
+ rfl
+
+include read in
+theorem roles_head : ev (roleBase I) = (SelectedArena.roleBase X term (I.termStride : Word w)
+ : Word w) := by
+ simp only [roleBase,placementBase,ev_add,ev_mul,ev_lit,score_head I X p₀ T term pub state m
+ read,read.sites]
+ simp [SelectedArena.roleBase, SelectedArena.placementBase, SelectedArena.positions,
+ ShrinkPreimages.oldCount]
+
+include read in
+theorem placement_bank (fit : SelectedArena.Fits X term (I.termStride : Word w)) :
+ (fun i ↦ ev (placementBank I i)) = SelectedArena.selectedWords X term (I.termStride : Word w)
+ p₀ m := by
+ have head := score_head I X p₀ T term pub state m read
+ have col := placement_column I X p₀ T term pub state m read
+ have loc : SelectedArena.origin X term (I.termStride : Word w)+2 < 2^w := by
+ change _ + 3 + 4 * _ + 4 * _ < 2^w at fit; omega
+ have bit : ev (layout I) = m (SelectedArena.origin X term (I.termStride : Word w)+2) := by
+ change m (ev (scoreBase I)+2).val = _
+ rw [head,← (Nat.cast_ofNat (R := Word w) (n :=
+ 2)),← Nat.cast_add,Fin.val_natCast,Nat.mod_eq_of_lt loc]
+ funext i
+ fin_cases i <;> first | exact read.prior _ | exact bit | exact col _
+
+include read in
+theorem roles_bank :
+ (fun i ↦ ev (rolesBank I i)) = SelectedArena.demandWords X term (I.termStride : Word w)
+ p₀ T := by
+ have col := placement_column I X p₀ T term pub state m read
+ funext i
+ fin_cases i <;> first | exact read.prior _ | exact read.oldOut | exact col _ |
+ exact roles_head I X p₀ T term pub state m read | rfl
+
+include read in
+theorem child_bank (selected : Fin 14 → Word w)
+ (owner : selected 10 = SelectedArena.placementWord X term (I.termStride : Word w) 0) :
+ (fun i ↦ ev (childBank I a i)) = ShrinkPreimages.params X selected (ev (roleEnd I)) (ev
+ (childRows I)) := by
+ funext i
+ fin_cases i <;> first | exact read.sites | exact read.nextSites |
+ exact (placement_column I X p₀ T term pub state m read 0).trans owner.symm | rfl
+
+end Values
+end CompressorRecords.SelectedPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedReadback.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedReadback.lean
new file mode 100644
index 0000000000..8d3a27cd2a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedReadback.lean
@@ -0,0 +1,53 @@
+import OAI.Computability.VPVNP.CompressorShrinkSelectedTailPackets
+import OAI.Computability.VPVNP.CompressorShrinkScoreOperands
+import OAI.Computability.VPVNP.CompressorShrinkBundleOperandSupport
+
+/-! # Selected placement and child-directory operands from the published shrinking header -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.SelectedTailPackets
+
+open BurstRAM Compression BlockPlanner ShrinkBlockInputs DescriptorSpace PhaseRecipe SourceTransport
+open scoped Fin.CommRing Classical
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+local notation "I" => selectedInputs B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0)
+local notation "p₀" => ShrinkInput.placementBank X T start
+local notation "term" => ShrinkInput.termHead (w := w) X start
+
+open private eval_sites eval_slots from OAI.Computability.VPVNP.CompressorShrinkBundlePlan
+
+theorem header_values (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w)
+ {L : Layout} {first : ℕ} (h : ShrinkHeaderReads.Header i X T start L first mem)
+ (entry : LevelFields.Entry L first pub st mem) (room : ShrinkInput.termEnd X start 10 < 2^w)
+ (width : 10<2^w) (D : ℕ → Prop) (pitch : D (pub 1-1).val)
+ (cells : ∀ n≤60, D (levelStart L (first+i.val)+n)) :
+ SelectedPlan.Reads I X p₀ T term pub st mem ∧ Footprint I D pub st mem := by
+ have rd := h.reads B entry
+ obtain ⟨count,head⟩ := ScorePackets.term_values B i X T start pub st mem rd room
+ obtain ⟨countR,headR⟩ := ScorePackets.term_support B i X T start pub st mem h entry D pitch cells
+ have newValue : (newSites i).eval pub st mem = (ShrinkPreimages.newCount X : Word w) := by
+ change (LevelFields.vertices i.val).eval pub st mem*(((2^(Shrink.J (a i)) : ℕ) : Word w)*
+ (LevelFields.residualLanes i.val).eval pub st mem) = _
+ rw [rd.vertices,rd.residual,← Nat.cast_mul,← Nat.cast_mul]
+ refine ⟨⟨eval_sites X rd,newValue,eval_slots X rd,count,head,width,rd.incidence 3,
+ congrFun (ShrinkBundlePlan.placement_bank X rd)⟩,?_⟩
+ have field (n : ℕ) (hn : n≤60) : (LevelFields.scalar i.val n).ReadsFrom D pub st mem :=
+ GreedyVisit.scalar_support D L first i.val n entry pitch (cells n hn) ((Nat.add_le_add_left hn _).trans_lt h.room)
+ have place := ShrinkBundlePackets.expr_reads B i h entry D pitch cells .positions
+ exact ⟨⟨field 0 (by decide),field 2 (by decide)⟩,⟨field 0 (by decide),trivial,field 3 (by decide)⟩,
+ ⟨⟨field 0 (by decide),field 2 (by decide)⟩,field 1 (by decide)⟩,countR,headR,field 57 (by decide),place.params⟩
+
+end CompressorRecords.SelectedTailPackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedScans.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedScans.lean
new file mode 100644
index 0000000000..b4b2f58060
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedScans.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.CompressorShrinkHistoryAccess
+import OAI.Computability.VPVNP.CompressorShrinkSlotOrdinals
+import OAI.Computability.VPVNP.CompressorSlotFillFootprint
+import OAI.Computability.VPVNP.CompressorScanProgress
+
+/-! # Progress and address bounds of selected layout and child-directory scans -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkHistoryTrace
+
+open BurstRAM Compression PrimedStackRAM SourceTransport SelectedArena
+open scoped Fin.CommRing Classical
+
+variable {w : ℕ}
+
+theorem emptyScanned {Q : Type*} (P : BurstRAM.Program w Q) (f : ℕ)
+ (advance : ∀ m i r, execute P f (P.start i) m [] = some r → r.result=some (i+1))
+ {j n N : ℕ} (size : j+n=N) (m : Memory w) (rs : List (Report w))
+ (run : runSegment P f (some (j : Word w)) m (List.replicate n [])=some rs) :
+ StageFrame.Scanned j N rs := by
+ induction n generalizing j rs m with
+ | zero =>
+ change some []=some rs at run
+ rw [← Option.some.inj run,show j=N by omega]
+ exact .done _
+ | succ n ih =>
+ rw [List.replicate_succ,runSegment] at run
+ cases head : execute P f (P.start (j : Word w)) m [] with
+ | none => rw [head] at run; contradiction
+ | some r =>
+ rw [head] at run
+ obtain ⟨tail,ht,rfl⟩ := Option.map_eq_some_iff.mp run
+ have ret := advance m (j : Word w) r head
+ rw [← Nat.cast_add_one] at ret
+ rw [ret] at ht
+ exact .next (by omega) ret (ih (by omega) _ tail ht)
+
+open private append_result from OAI.Computability.VPVNP.CompressorShrinkSlotOrdinals
+
+theorem append_scanned (p : Fin 6 → Word w) (n : ℕ) (m : Memory w) (rs : List (Report w))
+ (run : runSegment ((template collectPreimage 3).instantiate w p).program 23 (some 0) m (List.replicate n [])=some rs) :
+ StageFrame.Scanned 0 n rs :=
+ emptyScanned _ _ (append_result p) (Nat.zero_add n) m rs run
+
+theorem clear_scanned (b : Word w) (n : ℕ) (room : b.val+n ≤ 2^w) (m : Memory w) (rs : List (Report w))
+ (run : runSegment ((template SliceRAM.clearOps 0).instantiate w (fun _ => b)).program 8 (some 0) m (List.replicate n [])=some rs) :
+ StageFrame.Scanned 0 n rs ∧ Reads (fun _ => False) (eventLog rs) ∧
+ Writes (SlotFillFootprint.InColumn b.val n) (eventLog rs) := by
+ obtain ⟨hs,_,hr,hw⟩ := StageFrame.scan _ 8 0 n (fun _ _ => True)
+ (fun _ i => (SliceRAM.clearReport b i).events) (fun _ => False) (SlotFillFootprint.InColumn b.val n)
+ (fun j _ _ mem => SliceRAM.clearVisit_native b (j : Word w) mem) (fun j _ hj mem _ => by
+ have addr : (b+(j : Word w)).val=b.val+j := by
+ rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (show j<2^w by omega),Nat.mod_eq_of_lt (show b.val+j<2^w by omega)]
+ refine ⟨trivial,?_,?_⟩
+ · intro a v h; simp [SliceRAM.clearReport] at h
+ · intro a v h
+ simp [SliceRAM.clearReport] at h
+ rw [h.1,addr]; exact ⟨Nat.le_add_right ..,Nat.add_lt_add_left hj _⟩)
+ (Nat.zero_le n) m rs trivial (by simpa only [Nat.sub_zero,Nat.cast_zero] using run)
+ exact ⟨hs,hr,hw⟩
+
+end CompressorRecords.ShrinkHistoryTrace
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedSlices.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedSlices.lean
new file mode 100644
index 0000000000..5e7be1e75f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedSlices.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.CompressorShrinkSliceHeads
+import OAI.Computability.VPVNP.CompressorShrinkABSliceTable
+import OAI.Computability.VPVNP.CompressorShrinkTermPhases
+
+/-!
+# Interval tables of an admitted shrinking branch
+
+The surviving sweep reads the physical term rows emitted by the fused term
+verifier in precisely its dense bundle order. The source bits and rounded
+pieces needed for AB slicing come from the other columns of that same
+post-memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep
+
+open BurstRAM Compression MotifGrid MotifBlocks MotifConversion ShrinkMotif
+open scoped Classical
+
+variable {k : Type*} [_root_.Field k] {factor : ℝ}
+variable (F : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+
+local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex
+local notation "M" => ((Fintype.card X.Base*(2^(Shrink.J a)*2^g))*2^a)*PackingData.pieceCount (2^a) (Shrink.colors a)
+local notation "A" => Slots.oldBaseArcCount (Fintype.card X.Base) (2^(Shrink.J a)) (2^a) (Shrink.colors a) * 2^g
+
+/-- Place the width rectangle and the dense interval banks after the term
+rows. Use the exact common surviving layout selected by the energy comparison. -/
+noncomputable def selectedAllocation (s : X.ShrinkSelection F) (term : Word w) (stride widthBase : ℕ)
+ (subdiv : Fin 4 → ℕ) : Allocation w M A where
+ termBase := term.val
+ termStride := stride
+ widthBase := widthBase
+ absolute := absolute X.packingData X.shrinkNumber sites X.baseIndex (bitWordFinEquiv (Shrink.J a)) (bitWordFinEquiv g)
+ subdiv := subdiv
+ selectors := Fin.ofNat _ F.selectorBits
+ layout := X.packingData.shrinkTermLayout F X.shrinkNumber X.packingWidth s
+
+/-- The fused native verifier's fields are exactly the input image expected
+by the surviving slice-table worker, including the two headers. -/
+theorem written_terms (dense term : Word w) (stride widthBase cap : ℕ) (subdiv : Fin 4 → ℕ)
+ (s : X.ShrinkSelection F) (m : Memory w) (rs : List (Report w))
+ (h : ShrinkTermSelection.Written F X dense term stride cap s m rs) :
+ Terms X.packingData X.shrinkNumber sites (selectedAllocation F X s term stride widthBase subdiv)
+ F X.packingWidth s (after m (eventLog rs)) := by
+ intro i
+ let motif := (ShrinkMotifOrder.stateNumber X).symm i
+ have hv := h.fields motif
+ have eqn : ShrinkTermSelection.rowBase X term stride motif = Fin.ofNat (2^w) (term.val+i.val*stride) := by
+ simp only [ShrinkTermSelection.rowBase,motif,Equiv.apply_symm_apply]
+ rw [eqn] at hv
+ exact hv
+
+/-- Extra calls between term selection and slicing may update the chosen-layout
+cell and scores. Equality at the ten term words suffices for the width sweep. -/
+theorem terms_after (term : Word w) (stride widthBase : ℕ) (subdiv : Fin 4 → ℕ)
+ (s : X.ShrinkSelection F) (prior next : Memory w)
+ (ht : Terms X.packingData X.shrinkNumber sites (selectedAllocation F X s term stride widthBase subdiv)
+ F X.packingWidth s prior)
+ (frame : ∀ i : Fin M, ∀ j < 10, let base := Fin.ofNat (2^w) (term.val+i.val*stride)
+ next (base.val+j) = prior (base.val+j)) :
+ Terms X.packingData X.shrinkNumber sites (selectedAllocation F X s term stride widthBase subdiv)
+ F X.packingWidth s next := by
+ intro i
+ obtain ⟨grid,rep,payload⟩ := ht i
+ let b := Fin.ofNat (2^w) (term.val+i.val*stride)
+ have read (j : ℕ) (h : j < 10) : next (b.val+j) = prior (b.val+j) := frame i j h
+ exact ⟨(read 0 (by decide)) ▸ grid,(read 1 (by decide)) ▸ rep,
+ fun j => (show next (b.val+2+j.val) = prior (b.val+2+j.val) by
+ simpa only [Nat.add_assoc] using read (2+j.val) (by have := j.isLt; omega)) ▸ payload j⟩
+
+set_option maxHeartbeats 900000 in
+/-- Physical input to the width-sweep header's absolute-ID read in the same
+dyadic state and dense order as the fused verifier. -/
+theorem directory_for_selected (term abs : Word w) (stride widthBase : ℕ) (subdiv : Fin 4 → ℕ)
+ (s : X.ShrinkSelection F) (mem : Memory w)
+ (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber abs mem) :
+ let T := selectedAllocation F X s term stride widthBase subdiv
+ ∀ i : Fin M, (mem (abs.val+i.val)).val = (T.absolute i).val :=
+ Heads.directory_input X.slots X.baseIndex X.shrinkNumber abs mem directory
+
+end CompressorRecords.ShrinkSliceSweep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedTailGroup.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedTailGroup.lean
new file mode 100644
index 0000000000..1de159f760
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedTailGroup.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.CompressorShrinkSelectedReadback
+import OAI.Computability.VPVNP.CompressorBlockGroups
+import OAI.Computability.VPVNP.CompressorWindowPackets
+import OAI.Computability.VPVNP.CompressorSourceScanned
+
+/-! # Installing the four selected shrinking scans in the global block -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.SelectedTailPackets
+
+open BurstRAM Compression BlockPlanner DescriptorSpace Schedule SourceTransport ShrinkBlockInputs SelectedArena
+open scoped Fin.CommRing Classical
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+local notation "script₀" => BlockProgram.script B
+local notation "I" => selectedInputs B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0)
+
+/-- Locates the four placement, role, and child-directory visits immediately after the ten
+scoring visits in the repeated shrink block. -/
+def window : Window script₀ (tail I (a i)) where
+ before := (BlockGroups.shrink B i 4).before ++
+ ([SelectedPlan.clear I]++List.ofFn (SelectedPlan.axis I)++[SelectedPlan.compare I])
+ after := (BlockGroups.shrink B i 4).after
+ block := by
+ let W : Window script₀ (SelectedPlan.visits I (a i)) := BlockGroups.shrink B i 4
+ exact W.block.trans ((congrArg (fun ls => W.before ++ ls ++ W.after) (split (a:=a i) I)).trans (by simp only [List.append_assoc]; rfl))
+
+theorem window_offset : (window B i).before.length = (BlockIndex.earlier B i).length+32 := by
+ change ((BlockGroups.shrink B i 4).before++_).length=_
+ rw [List.length_append,BlockGroups.shrink_offset]
+ change (BlockIndex.earlier B i).length+
+ ((BlockHeaderPlan.substep _ _ _ ++ (GreedyLevelPlan.visits _ _ _ _ ++
+ (ShrinkBundlePlan.visits _ _ _ _ ++ (termVisits B i _ ++ [])))).length)+_ = _
+ simp only [List.length_append,BlockHeaderPlan.substep_length,GreedyLevelPlan.visits_length,
+ ShrinkBundlePlan.visits_length,termVisits_length,List.length_nil,List.length_cons,List.length_ofFn]
+
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+variable (base : Word w) (positions blocks t : ℕ)
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (arity (BlockPlanner.Script.catalog (BlockProgram.script B))) base
+local notation "pub" => Schedule.Ports.data pt
+local notation "first" => BlockPlanner.Script.levelsPerBlock (BlockProgram.script B)*t
+local notation "st" => (levelStart L (first) : Word w)
+local notation "H" => levelStart L 0
+local notation "D" => Window.operandRegion script₀ L base
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "p₀" => ShrinkInput.placementBank X T start
+local notation "W" => window B i
+local notation "low" => levelStart L (first+i.val)
+
+
+open private room_vals from OAI.Computability.VPVNP.CompressorRecordsSelectedPreimages
+
+set_option maxHeartbeats 1800000 in
+theorem group (s : SelectedScore.Selection B X) (m : Memory w) (p : SelectedStage.Passes w) (q : SelectedFinish.Passes w)
+ (exec : SelectedStage.Execution X term 10 (B.shrink.selectorBits : Word w) p₀ T m p)
+ (stored : SelectedStage.Stored B X term 10 p₀ s m p)
+ (built : SelectedFinish.Built B X term 10 (B.shrink.selectorBits : Word w) p₀ s m p q)
+ (hp : ShrinkRAM.Params p₀ (a i) (Shrink.colors (a i)) (Shrink.J (a i)) g false)
+ (old : OldInputs X term 10 p₀ T) (termRoom : ShrinkInput.termEnd X start 10 < 2^w)
+ (room : SelectedFinish.stop X term 10 ≤ 2^w)
+ (header : ShrinkHeaderReads.Header i X T start L (first) (p.afterScores m)) (before : low+60 < start)
+ (floor : H ≤ ShrinkHistoryTrace.inputFloor p₀) (outFloor : H≤T.actualOut.val)
+ (rows : p.afterScores m (pt).rows.val=(directoryRows L : Word w))
+ (pitch : p.afterScores m (pub 1-1).val=(levelWords L : Word w))
+ (within : t r.stage.phase) = (W).indices ∧ ps.flatMap SourceWalk.Packet.reports = reports p q ∧
+ SourceOnline.post (p.afterScores m) ps=q.final (p.final m) := by
+ have baseFit : H < 2^w := (levelStart_mono L (Nat.zero_le _)).trans_lt fit
+ have lowBound : H≤low := levelStart_mono L (Nat.zero_le _)
+ have hh := Window.lowCells (A:=script₀) L base rfl rfl baseFit
+ have termLow := ScorePackets.start_le_term i X start termRoom
+ have size : 10<2^w := by have := header.room; omega
+ obtain ⟨full,cval,_⟩ := room_vals X term (10 : Word w) room
+ obtain ⟨_,wp,_,wr⟩ := ShrinkHistoryTrace.selected_access B X term (10 : Word w) (B.shrink.selectorBits : Word w)
+ p₀ T s m p exec stored old hp full
+ have pl : start≤placementBase X term (10 : Word w) := termLow.trans (by
+ change (term).val ≤ (term).val + _ + 3; omega)
+ have rl : start≤roleBase X term (10 : Word w) := pl.trans (Nat.le_add_right ..)
+ have posKeep (x : ℕ) (hx : x Nat.not_le_of_lt (hx.trans_le pl) h.1)
+ have roleKeep (x : ℕ) (hx : x Nat.not_le_of_lt (hx.trans_le rl) h.1)).trans (posKeep x hx)
+ let area := SelectedFinish.areas X term 10 p₀ (p.afterScores m (origin X term 10+2)) room
+ obtain ⟨_,_,wc⟩ := ShrinkHistoryTrace.clear_scanned _ _ (area.countEnd.trans (SelectedFinish.rows X term 10).isLt.le)
+ _ _ built.raw.clear
+ have countBound : start≤(SelectedFinish.counts X term 10).val := cval.symm ▸ (rl.trans (Nat.le_add_right ..))
+ have clearKeep (x : ℕ) (hx : x Nat.not_le_of_lt (hx.trans_le countBound) h.1)).trans (roleKeep x hx)
+ have source (r : Memory w) (hr : r∈inputs m p q) :
+ SelectedPlan.Reads I X p₀ T term pub st r ∧ Footprint I D pub st r := by
+ have same (x : ℕ) (hx : x .inr (.inr (lowBound.trans (Nat.le_add_right ..))))
+ have walk := SelectedTailPackets.walk I X term p₀ T D pub st L B s m p q exec stored built hp old room
+ floor outFloor (lowBound.trans ((show low≤start by omega).trans termLow)) (fun _ h => Or.inr (Or.inr h)) source
+ have budget (j : Fin (script₀).size) :
+ ((script₀).plan.recipes j).2.code.length+1+2*Online.N (script₀).size (script₀).size+5≤cap ∧
+ 65+3+4*(((script₀).catalog j).params+1)+2*Online.N (script₀).size (script₀).size+5≤cap := by
+ let e := HeaderPacket.attach script₀ j pub st m 65 []
+ exact SourceOnline.scanCap_clocks (p:=⟨e,m,[]⟩) 65 (by rfl) clock
+ have live (j : Fin (tail I (a i)).length) : Window.ordinal (A:=script₀) t ((W).index j) (budget j).1) (fun j _ => (budget j).2)
+ rw [window_offset] at hg
+ refine ⟨ps,?_,ph,rep,?_⟩
+ · simpa only [Nat.add_assoc] using hg
+ · rw [SourceOnline.post,rep,reports,SourceWalk.after_append,SourceWalk.after_append,SourceWalk.after_append]
+ rfl
+
+end CompressorRecords.SelectedTailPackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedTailPackets.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedTailPackets.lean
new file mode 100644
index 0000000000..458350b352
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSelectedTailPackets.lean
@@ -0,0 +1,203 @@
+import OAI.Computability.VPVNP.CompressorShrinkSelectedScans
+import OAI.Computability.VPVNP.CompressorShrinkSelectedPlan
+import OAI.Computability.VPVNP.CompressorRecordsSelectedFinish
+import OAI.Computability.VPVNP.CompressorHeaderOperands
+
+/-! # The four chronological placement, role and child-directory packets -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.SelectedTailPackets
+
+open BurstRAM Compression BlockPlanner PhaseRecipe SourceTransport DescriptorSpace SelectedArena
+open ShrinkHistoryTrace
+open scoped Fin.CommRing Classical
+
+variable {a g w : ℕ} (I : SelectedPlan.Inputs) (X : State a (packingLaneBits a g))
+ (term : Word w) (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w)
+local notation "stride" => (I.termStride : Word w)
+local notation "selectors" => (I.selectorBits : Word w)
+
+/-- The four post-comparison visits write placements, write role rows, clear child counters,
+then collect children by their new site. -/
+def tail (a : ℕ) := [SelectedPlan.placement I,SelectedPlan.roles I,SelectedPlan.clearChildren I,SelectedPlan.children I a]
+
+theorem split : SelectedPlan.visits I a =
+ ([SelectedPlan.clear I]++List.ofFn (SelectedPlan.axis I)++[SelectedPlan.compare I]) ++ tail I a := by
+ simp only [SelectedPlan.visits,tail,List.append_assoc,List.cons_append,List.nil_append]
+
+/-- Requires the size, term, old outgoing-incidence, and preliminary operand expressions used
+by the four tail visits to read only addresses in `D`. -/
+structure Footprint (D : ℕ → Prop) (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) : Prop where
+ sites : I.oldSites.ReadsFrom D pub st m
+ newSites : I.newSites.ReadsFrom D pub st m
+ slots : I.oldSlots.ReadsFrom D pub st m
+ motifs : I.motifs.ReadsFrom D pub st m
+ term : I.termBase.ReadsFrom D pub st m
+ oldOut : I.oldActualOut.ReadsFrom D pub st m
+ prior : ∀ j, (I.preliminary j).ReadsFrom D pub st m
+
+variable (D : ℕ → Prop) (pub : Fin 5 → Word w) (st : Word w)
+open SelectedPlan in
+private theorem supported (m : Memory w) (h : Footprint I D pub st m)
+ (layoutAddr : D ((layoutCell I).eval pub st m).val) :
+ ∀ v ∈ tail I a, HeaderOperands.Supported D pub st m v := by
+ let safe := fun (e : Expr) => e.ReadsFrom D pub st m
+ have sc : safe (scoreBase I) := ⟨h.term,h.motifs,trivial⟩
+ have pl : safe (placementBase I) := ⟨sc,trivial⟩
+ have co (c : Fin 4) : safe (placementColumn I c) := ⟨pl,trivial,h.sites⟩
+ have ro : safe (roleBase I) := ⟨pl,trivial,h.sites⟩
+ have en : safe (roleEnd I) := ⟨ro,trivial,h.slots⟩
+ have rows : safe (childRows I) := ⟨en,h.newSites⟩
+ have la : safe (layout I) := ⟨⟨sc,trivial⟩,layoutAddr⟩
+ intro v hv
+ simp only [tail,List.mem_cons,List.not_mem_nil,or_false] at hv
+ rcases hv with rfl|rfl|rfl|rfl
+ · refine ⟨trivial,h.sites,?_⟩
+ intro j; change (placementBank I j).ReadsFrom D pub st m
+ fin_cases j <;> first | exact h.prior _ | exact la | exact co _
+ · refine ⟨trivial,h.slots,?_⟩
+ intro j; change (rolesBank I j).ReadsFrom D pub st m
+ fin_cases j <;> first | exact h.prior _ | exact h.oldOut | exact co _ | exact ro | trivial
+ · exact ⟨trivial,h.newSites,fun _ => en⟩
+ · refine ⟨trivial,h.sites,?_⟩
+ intro j; change (childBank I a j).ReadsFrom D pub st m
+ fin_cases j <;> first | exact h.sites | exact h.newSites | exact co _ | exact rows | exact en | trivial
+
+variable (L : DescriptorSpace.Layout)
+local notation "H" => levelStart L 0
+
+/-- A source run of the visit with instruction fuel at most 65, whose header operand
+expressions read only from `D` at entry. -/
+def Source (v : BlockPlanner.Visit) (m : Memory w) (rs : List (Report w)) :=
+ ∃ fuel bits, fuel≤65 ∧ HeaderPacket.Run L pub st v m rs fuel bits ∧ HeaderOperands.Supported D pub st m v
+
+private theorem packet (v : BlockPlanner.Visit) (n f : ℕ) (bank : Fin v.worker.params → Word w) (m : Memory w) (rs : List (Report w))
+ (pos : 0 (v.params j).eval pub st m)=bank)
+ (run : runSegment (v.worker.table.instantiate w bank).program f (some 0) m (List.replicate n [])=some rs)
+ (shape : StageFrame.Scanned 0 n rs) (rd : Reads (H≤·) (eventLog rs)) (wr : Writes (H≤·) (eventLog rs))
+ (supp : HeaderOperands.Supported D pub st m v) : Source D pub st L v m rs := by
+ refine ⟨f,List.replicate n [],hf,⟨pos,?_,?_,rd,wr⟩,supp⟩
+ · dsimp only; rw [args,start]; exact run
+ · rw [start,stop]; exact shape.toProgress size
+
+private theorem roleEnd_value (m : Memory w) (rd : SelectedPlan.Reads I X p₀ T term pub st m) :
+ (SelectedPlan.roleEnd I).eval pub st m = SelectedFinish.counts X term stride := by
+ change (SelectedPlan.roleBase I).eval pub st m + 4*I.oldSlots.eval pub st m = _
+ rw [SelectedPlan.roles_head I X p₀ T term pub st m rd,rd.slots,DemandRAM.count_eq X]
+ change (SelectedArena.roleBase X term stride : Word w)+4*(DemandRAM.absoluteCount X : Word w) =
+ ((SelectedArena.roleBase X term stride+4*DemandRAM.absoluteCount X : ℕ) : Word w)
+ push_cast; rfl
+
+private theorem rows_value (m : Memory w) (rd : SelectedPlan.Reads I X p₀ T term pub st m) :
+ (SelectedPlan.childRows I).eval pub st m = SelectedFinish.rows X term stride := by
+ change (SelectedPlan.roleEnd I).eval pub st m + I.newSites.eval pub st m = _
+ rw [roleEnd_value I X term p₀ T pub st m rd,rd.nextSites]
+ exact (Nat.cast_add ..).symm
+
+/-- The entry memories for the four tail visits, taken after scoring, after placement, after
+writing roles, and after clearing child counters. -/
+def inputs (m : Memory w) (p : SelectedStage.Passes w) (q : SelectedFinish.Passes w) :=
+ [p.afterScores m,p.afterPositions m,p.final m,q.middle (p.final m)]
+
+/-- The source reports from placement, role writes, child-counter clearing, and child
+collection concatenated in execution order. -/
+def reports (p : SelectedStage.Passes w) (q : SelectedFinish.Passes w) :=
+ p.positions ++ (p.roles ++ (q.clear ++ q.collect))
+
+open private room_vals from OAI.Computability.VPVNP.CompressorRecordsSelectedPreimages
+
+set_option maxHeartbeats 1200000 in
+/-- Each of the four visits uses the memory left by its predecessor,
+including the selected layout bit and the newly materialized owner column. -/
+theorem walk {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ (s : SelectedScore.Selection B X) (m : Memory w) (p : SelectedStage.Passes w) (q : SelectedFinish.Passes w)
+ (exec : SelectedStage.Execution X term stride selectors p₀ T m p)
+ (stored : SelectedStage.Stored B X term stride p₀ s m p)
+ (built : SelectedFinish.Built B X term stride selectors p₀ s m p q)
+ {side : Bool} (hp : ShrinkRAM.Params p₀ a (Shrink.colors a) (Shrink.J a) g side)
+ (old : OldInputs X term stride p₀ T) (room : SelectedFinish.stop X term stride ≤ 2^w)
+ (floor : H≤ inputFloor p₀) (oldOut : H≤T.actualOut.val) (termFloor : H≤term.val)
+ (data : ∀ x, H≤x → D x)
+ (raw : ∀ r ∈ inputs m p q, SelectedPlan.Reads I X p₀ T term pub st r ∧ Footprint I D pub st r) :
+ SourceWalk (Source D pub st L) (tail I a) (p.afterScores m) (reports p q) := by
+ obtain ⟨fit,cval,rval⟩ := room_vals X term stride room
+ let sh : Fin 14 → Word w := selectedWords X term stride p₀ (p.afterScores m)
+ let bank := SelectedFinish.params X term stride sh
+ let area := SelectedFinish.areas X term stride p₀ ((p.afterScores m) (origin X term stride+2)) room
+ have prec : ShrinkPreimages.Areas X sh (SelectedFinish.counts X term stride) (SelectedFinish.rows X term stride) := area
+ have sizes := prec.dimensions
+ have fN : ShrinkPreimages.oldCount X<2^w := sizes.1 ▸ (bank 0).isLt
+ have fV : ShrinkPreimages.newCount X<2^w := sizes.2.1 ▸ (bank 2).isLt
+ have endFit : placementBase X term stride+4*positions X+4*DemandRAM.absoluteCount X < 2^w := fit
+ have gN : DemandRAM.oldCount X < 2^w := by rw [DemandRAM.count_eq X]; omega
+ have cLo : H ≤ SelectedFinish.countStart X term stride := by
+ change H≤term.val+motifs X*(stride).val+3+4*positions X+4*DemandRAM.absoluteCount X
+ omega
+ have pLo : H ≤ placementBase X term stride := by change H≤term.val+motifs X*(stride).val+3; omega
+ have rLo : H ≤ roleBase X term stride := pLo.trans (Nat.le_add_right ..)
+ have here (r : Memory w) (hr : r ∈ inputs m p q) (v : BlockPlanner.Visit) (hv : v ∈ tail I a) :
+ HeaderOperands.Supported D pub st r v := by
+ obtain ⟨read,feet⟩ := raw r hr
+ apply supported I D pub st r feet _ v hv
+ apply data
+ change H ≤ ((SelectedPlan.scoreBase I).eval pub st r+2).val
+ rw [SelectedPlan.score_head I X p₀ T term pub st r read,← (Nat.cast_ofNat (R := Word w) (n := 2)),← Nat.cast_add,Fin.val_natCast]
+ have hf : origin X term stride+2<2^w := by change origin X term stride+3+_+_<2^w at endFit; omega
+ rw [Nat.mod_eq_of_lt hf]; change H≤term.val+motifs X*(stride).val+2; omega
+ obtain ⟨pr,pw,rr,rw'⟩ := selected_access B X term stride selectors p₀ T s m p exec stored old hp fit
+ have pl := (raw (p.afterScores m) (by simp [inputs])).1
+ have ro := (raw (p.afterPositions m) (by simp [inputs])).1
+ have cl := (raw (p.final m) (by simp [inputs])).1
+ have ap := (raw (q.middle (p.final m)) (by simp [inputs])).1
+ have posShape : StageFrame.Scanned 0 (positions X) p.positions :=
+ emptyScanned _ 65 (fun mem i r h => congrArg Report.result (Option.some.inj (h.symm.trans (ShrinkRAM.visit_native sh mem i))))
+ (Nat.zero_add _) _ _ exec.positions
+ have roleShape : StageFrame.Scanned 0 (DemandRAM.oldCount X) p.roles :=
+ emptyScanned _ 65 (fun mem i r h => congrArg Report.result (Option.some.inj (h.symm.trans (DemandRAM.visit_native _ mem i))))
+ (Nat.zero_add _) _ _ exec.roles
+ have hpos : Source D pub st L (SelectedPlan.placement I) (p.afterScores m) p.positions :=
+ packet D pub st L (SelectedPlan.placement I) (positions X) 65 sh _ _ (by decide) le_rfl fN rfl pl.sites
+ (SelectedPlan.placement_bank I X p₀ T term pub st _ pl fit) exec.positions posShape
+ (fun a v h => floor.trans (pr a v h).1) (fun a v h => pLo.trans (pw a v h).1)
+ (here _ (by simp [inputs]) _ (by simp [tail]))
+ have hrole : Source D pub st L (SelectedPlan.roles I) (p.afterPositions m) p.roles :=
+ packet D pub st L (SelectedPlan.roles I) _ 65 (demandWords X term stride p₀ T) _ _ (by decide) le_rfl gN rfl ro.slots
+ (SelectedPlan.roles_bank I X p₀ T term pub st _ ro) exec.roles roleShape
+ (fun a v h => (rr a v h).elim (fun b => oldOut.trans b.1) (fun b => pLo.trans b.1))
+ (fun a v h => rLo.trans (rw' a v h).1) (here _ (by simp [inputs]) _ (by simp [tail]))
+ obtain ⟨clearShape,cr,cw⟩ := clear_scanned _ _ (prec.countEnd.trans (SelectedFinish.rows X term stride).isLt.le)
+ _ _ built.raw.clear
+ have hclear : Source D pub st L (SelectedPlan.clearChildren I) (p.final m) q.clear :=
+ packet D pub st L (SelectedPlan.clearChildren I) _ 8 (fun _ => SelectedFinish.counts X term stride) _ _ (by decide) (by decide) fV rfl cl.nextSites
+ (funext fun _ => roleEnd_value I X term p₀ T pub st _ cl) built.raw.clear clearShape
+ (fun a v h => (cr a v h).elim) (fun a v h => (cval.symm ▸ cLo).trans (cw a v h).1)
+ (here _ (by simp [inputs]) _ (by simp [tail]))
+ have arg := SelectedPlan.child_bank I X p₀ T term pub st _ ap sh rfl
+ rw [roleEnd_value I X term p₀ T pub st _ ap,rows_value I X term p₀ T pub st _ ap] at arg
+ have own : H ≤ (bank 1).val := by
+ change H ≤ (placementWord X term stride 0).val
+ rw [column_value X term stride fit,Fin.val_zero,Nat.zero_mul,Nat.add_zero]; exact pLo
+ have cnt : H ≤ (bank 3).val := cval.symm ▸ cLo
+ have rows : H ≤ (bank 5).val := rval.symm ▸ (cLo.trans (Nat.le_add_right ..))
+ obtain ⟨ar,aw⟩ := SlotFillFootprint.append_run prec.regions built.raw.collect
+ have happ : Source D pub st L (SelectedPlan.children I a) (q.middle (p.final m)) q.collect :=
+ packet D pub st L (SelectedPlan.children I a) _ 23 bank _ _ (by decide) (by decide) fN rfl ap.sites arg built.raw.collect
+ (append_scanned _ _ _ _ built.raw.collect)
+ (fun a v h => (ar a v h).elim (fun b => own.trans b.1) (fun b => cnt.trans b.1))
+ (fun a v h => (aw a v h).elim (fun b => cnt.trans b.1) (fun b => rows.trans b.1))
+ (here _ (by simp [inputs]) _ (by simp [tail]))
+ exact .next hpos (.next hrole (.next hclear (SourceWalk.singleton happ)))
+
+end CompressorRecords.SelectedTailPackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSetupFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSetupFootprint.lean
new file mode 100644
index 0000000000..5768609c12
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSetupFootprint.lean
@@ -0,0 +1,196 @@
+import OAI.Computability.VPVNP.CompressorRecordsShrinkInput
+import OAI.Computability.VPVNP.CompressorLogAccess
+import OAI.Computability.VPVNP.CompressorSlotFillFootprint
+import OAI.Computability.VPVNP.CompressorSlotScanFootprint
+
+/-! # Addresses accessed while preparing a shrinking state's bundle lists
+
+The preliminary placement and classification read their old input columns.
+Their writes, as well as all counter clears and bounded appends, lie in the
+new shrinking arena. This permits each native segment to run with the
+scheduler control memory overlaid below the data.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkInput
+
+open BurstRAM Compression PrimedStackRAM SourceTransport
+open private offsets from OAI.Computability.VPVNP.CompressorRecordsShrinkPlacement
+open private site_lt from OAI.Computability.VPVNP.CompressorRecordsShrinkRankArena
+
+variable {w a g : ℕ}
+
+private abbrev Within (lo hi z : ℕ) := lo ≤ z ∧ z < hi
+
+private theorem address {lo hi size : ℕ} (base i : Word w) (low : lo ≤ base.val)
+ (index : i.val < size) (before : base.val+size ≤ hi) (fit : hi ≤ 2^w) :
+ Within lo hi (base+i).val := by
+ rw [Fin.val_add,Nat.mod_eq_of_lt (by omega)]
+ exact ⟨by omega,by omega⟩
+
+private theorem placement_row (p : Fin 14 → Word w) (m : Memory w) (i : Word w)
+ (rd wr : ℕ → Prop) (read : ∀ c : Fin 4, rd (ShrinkRAM.readAddr p c i))
+ (write : ∀ c : Fin 4, wr (ShrinkRAM.outAddr p c i)) :
+ Reads rd (ShrinkRAM.events p m i) ∧ Writes wr (ShrinkRAM.events p m i) := by
+ constructor <;> intro a v h
+ · simp only [ShrinkRAM.events,List.mem_append,List.mem_replicate,List.mem_cons,List.not_mem_nil,
+ reduceCtorEq,Event.read.injEq,and_false,or_false,false_or] at h
+ rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩
+ exacts [read 0,read 1,read 2,read 3]
+ · simp only [ShrinkRAM.events,List.mem_append,List.mem_replicate,List.mem_cons,List.not_mem_nil,
+ reduceCtorEq,Event.write.injEq,and_false,or_false,false_or] at h
+ rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩
+ exacts [write 0,write 1,write 2,write 3]
+
+private theorem classify_row (p : Fin 11 → Word w) (m : Memory w) (i : Word w)
+ (rd wr : ℕ → Prop) (read : ∀ c : Fin 6, rd (BundleRAM.readAddress p m i c).val)
+ (write : ∀ c : Fin 2, wr (BundleRAM.outAddr p c i)) :
+ Reads rd (BundleRAM.events p m i) ∧ Writes wr (BundleRAM.events p m i) := by
+ constructor <;> intro a v h
+ · simp only [BundleRAM.events,List.mem_append,List.mem_replicate,List.mem_cons,List.not_mem_nil,
+ reduceCtorEq,Event.read.injEq,and_false,or_false,false_or] at h
+ rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩
+ exacts [read 0,read 1,read 2,read 3,read 4,read 5]
+ · simp only [BundleRAM.events,List.mem_append,List.mem_replicate,List.mem_cons,List.not_mem_nil,
+ reduceCtorEq,Event.write.injEq,and_false,or_false,false_or] at h
+ rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩
+ exacts [write 0,write 1]
+
+namespace Run
+
+variable {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ}
+variable {m : Memory w} (r : Run X T start m)
+
+local notation "N" => Fintype.card X.Base
+local notation "S" => N*2^(packingLaneBits a g)
+local notation "A" => S*2^a
+local notation "Z" => plan X start
+local notation "sh" => placementBank X T start
+local notation "wb" => widthBase X start
+local notation "p" => ShrinkRankSpace.Shape.classifyBank (plan X start) T (placementBank X T start)
+local notation "q" => ShrinkRankSpace.Shape.collectBank (plan X start) w
+
+theorem placement_access (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) (room : stop X start < 2^w) :
+ LogAccess (Within lo (placementBase X start)) (Within (placementBase X start) (rankBase X start)) r.sites := by
+ let P := ((template ShrinkRAM.visit 0).instantiate w sh).program
+ obtain ⟨h₁,h₂,h₃,h₄⟩ := range_bounds X start
+ have init : lo ≤ start := (low 0).trans ((Nat.le_add_right ..).trans (r.greedy.old 0))
+ have fit := h₃.trans_lt (h₄.trans_lt room)
+ have bank := r.bankParams room
+ have hb := r.inputBounds
+ have bounds := GreedyArena.bounds start N a
+ have lc : lo ≤ (sh 6).val := by
+ change lo ≤ start % (2^w)
+ rw [Nat.mod_eq_of_lt (h₁.trans_lt (h₂.trans_lt fit))]; exact init
+ have lt : lo ≤ (sh 7).val := by
+ change lo ≤ GreedyArena.offsetBase start N a % (2^w)
+ have k : GreedyArena.offsetBase start N a < 2^w := by have := r.greedy.room; omega
+ rw [Nat.mod_eq_of_lt k]; exact init.trans (by unfold GreedyArena.offsetBase; omega)
+ apply SlotEventBounds.scan P 65 S (ShrinkRAM.events sh) (fun _ ↦ True) _ _
+ (ShrinkRAM.visit_native sh) _ _ _ trivial r.positions
+ intro j hj mem _
+ let i := Fin.ofNat (2^w) j
+ have hi : i.val < S := (Nat.mod_le ..).trans_lt hj
+ have off := offsets X T _ _ _ false bank i hi
+ have rd (c : Fin 4) : Within lo (placementBase X start) (ShrinkRAM.readAddr sh c i) := by
+ fin_cases c
+ · exact address _ _ lc off.1 hb.1 (h₂.trans fit.le)
+ · exact address _ _ lt off.1 hb.2.1 (h₂.trans fit.le)
+ · exact address _ _ (low 0) off.2 hb.2.2.1 (h₂.trans fit.le)
+ · exact address _ _ (low 2) off.2 hb.2.2.2 (h₂.trans fit.le)
+ have wr (c : Fin 4) : Within (placementBase X start) (rankBase X start) (ShrinkRAM.outAddr sh c i) := by
+ apply address _ i _ hi (pre_starts X T start room c) fit.le
+ rw [show (sh (c.natAdd 10)).val = placementBase X start+c.val*S from ShrinkPlacement.starts X T _ _ _ false fit c]
+ exact Nat.le_add_right ..
+ exact ⟨(placement_row sh mem i _ _ rd wr).1,(placement_row sh mem i _ _ rd wr).2,trivial⟩
+
+theorem clear_access (room : stop X start < 2^w) :
+ LogAccess (fun _ ↦ False) (Within (Z).counts (Z).ids) r.clear := by
+ have fit := (range_bounds X start).2.2.2.trans_lt room
+ have hv := (Z).values T sh Fintype.card_pos fit
+ have hb : (Z).counts+2*(Z).B ≤ 2^w := by
+ change (Z).counts+2*(Z).B+(Z).rectangleSize+(Z).rectangleSize+(Z).A < 2^w at fit
+ omega
+ exact direct_scan _ 8 4 2 (Z).counts (2*(Z).B) (fun _ ↦ (0 : Word w)) hb
+ (fun mem i ↦ SliceRAM.clearVisit_native (q 3) i mem) _ _ r.ranking.clear
+
+theorem classify_access (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) (room : stop X start < 2^w) :
+ LogAccess (Within lo (rankBase X start)) (Within (rankBase X start) (Z).counts) r.classify := by
+ let prog := ((template BundleRAM.visit 0).instantiate w p).program
+ obtain ⟨h₁,h₂,h₃,h₄⟩ := range_bounds X start
+ have fit := h₄.trans_lt room
+ have hZ := (Z).values T sh Fintype.card_pos fit
+ have hA := ((Z).scalarFits Fintype.card_pos fit).1.le
+ have lowStart : lo ≤ start := (low 3).trans ((Nat.le_add_right ..).trans (r.greedy.old 3))
+ have old (c : Fin 6) : (T.column c).val+A ≤ rankBase X start :=
+ (r.greedy.old c).trans (h₁.trans h₂)
+ have counts : (Z).counts = rankBase X start+2*A := rfl
+ have cfit : (Z).counts ≤ wb := by
+ change (Z).counts ≤ (Z).counts+2*(Z).B+(Z).rectangleSize+(Z).rectangleSize+(Z).A; omega
+ have hrank := h₃.trans fit.le
+ have hw (i : Word w) (hi : i.val < A) (c : Fin 2) : Within (rankBase X start) (Z).counts (BundleRAM.outAddr p c i) := by
+ fin_cases c
+ · apply address (p 9) i _ hi _ (cfit.trans fit.le)
+ · exact hZ.owner.ge
+ · rw [hZ.owner,counts]; change rankBase X start+A ≤ rankBase X start+2*A; omega
+ · apply address (p 10) i _ hi _ (cfit.trans fit.le)
+ · rw [hZ.key]; exact Nat.le_add_right ..
+ · rw [hZ.key,counts]; change rankBase X start+A+A ≤ rankBase X start+2*A; omega
+ let ms := after r.greedy.post (eventLog r.sites)
+ let m₀ := after ms (eventLog r.clear)
+ have incSite : T.Represents X ms := r.greedy.incidence.retain (fun c ↦ (r.greedy.old c).trans h₁) r.siteFrame
+ have inc₀ : T.Represents X m₀ := incSite.retain old (fun z hz ↦
+ SourceTransport.after_outside ms (r.clear_access room).2 (fun h ↦ by have hx := h.1; rw [counts] at hx; omega))
+ have lowPre (t : Fin 4) : lo ≤ (sh (t.natAdd 10)).val := by
+ rw [show (sh (t.natAdd 10)).val = placementBase X start+t.val*S from
+ ShrinkPlacement.starts X T _ _ _ false (h₃.trans_lt fit) t]
+ exact (lowStart.trans h₁).trans (Nat.le_add_right ..)
+ apply SlotEventBounds.scan prog (1+BundleRAM.visit.length) A (BundleRAM.events p) (T.Represents X) _ _
+ (BundleRAM.visit_native p) _ m₀ r.classify inc₀ r.ranking.ranked.classify
+ intro j hj mem inc
+ let i := Fin.ofNat (2^w) j
+ have hi : i.val < A := (Nat.mod_le ..).trans_lt hj
+ obtain ⟨hs,ht⟩ := site_lt X T sh (rankBase X start) mem inc.actual hZ hA i hi
+ have rd (c : Fin 6) : Within lo (rankBase X start) (BundleRAM.readAddress p mem i c).val := by
+ fin_cases c
+ · exact address T.actualOut i (low 3) hi (old 3) hrank
+ · exact address (sh 11) _ (lowPre 1) hs (pre_starts X T start room 1) hrank
+ · exact address (sh 11) _ (lowPre 1) ht (pre_starts X T start room 1) hrank
+ · exact address (sh 10) _ (lowPre 0) hs (pre_starts X T start room 0) hrank
+ · exact address (sh 12) _ (lowPre 2) hs (pre_starts X T start room 2) hrank
+ · exact address (sh 12) _ (lowPre 2) ht (pre_starts X T start room 2) hrank
+ obtain ⟨reads,writes⟩ := classify_row p mem i _ _ rd (hw i hi)
+ exact ⟨reads,writes,inc.retain old (fun z hz ↦ SourceTransport.after_outside mem writes (fun h ↦ hz.not_ge h.1))⟩
+
+theorem append_access (room : stop X start < 2^w) :
+ LogAccess (Within (rankBase X start) (Z).ids) (Within (Z).counts (Z).gathered) r.append := by
+ have h := range_bounds X start
+ have fit := h.2.2.2.trans_lt room
+ have hv := (Z).values T sh Fintype.card_pos fit
+ have before := (r.greedy.old 5).trans (h.1.trans h.2.1)
+ have reg := ((Z).regions T sh Fintype.card_pos before fit).1
+ have raw := SlotFillFootprint.append_run reg r.ranking.ranked.append
+ have own : (q 1).val = rankBase X start := hv.owner
+ have cend : (Z).counts+2*(Z).B = (Z).ids := rfl
+ have rend : (Z).ids+2*(Z).B*(Z).Q = (Z).gathered := rfl
+ have cstart : rankBase X start+2*A = (Z).counts := rfl
+ apply LogAccess.mono raw
+ · intro x hx
+ rcases hx with ⟨hx₁,hx₂⟩ | ⟨hx₁,hx₂⟩
+ · rw [own,hv.count] at *; change x < rankBase X start+A at hx₂; exact ⟨hx₁,by omega⟩
+ · rw [hv.counts] at hx₁ hx₂; rw [hv.buckets] at hx₂; exact ⟨by omega,by omega⟩
+ · intro x hx
+ rcases hx with ⟨hx₁,hx₂⟩ | ⟨hx₁,hx₂⟩
+ · rw [hv.counts] at hx₁ hx₂; rw [hv.buckets] at hx₂; exact ⟨hx₁,by omega⟩
+ · rw [hv.ids] at hx₁ hx₂; rw [hv.buckets,hv.stride,rend] at hx₂; exact ⟨by omega,hx₂⟩
+
+end Run
+
+end CompressorRecords.ShrinkInput
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSliceArrays.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceArrays.lean
new file mode 100644
index 0000000000..463607bafa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceArrays.lean
@@ -0,0 +1,323 @@
+import OAI.Computability.VPVNP.CompressorSliceSchedule
+import OAI.Computability.VPVNP.CompressorTermRecord
+import OAI.Computability.VPVNP.ShrinkLayout
+
+/-!
+# Width arrays for shrinking-step kernel slices
+
+The AB bundle and each surviving supply wire are repartitioned by the same
+quotient and remainder rule. Each visit reads the total from external memory
+and writes one subdivision width. A surviving supply total includes the
+selected payload and one selector field per repetition.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceArrays
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression
+open Compression.PackingData
+
+variable {w : ℕ}
+
+private abbrev div (a b : Word w) := BinaryOp.div.eval a b
+private abbrev mod (a b : Word w) := BinaryOp.mod.eval a b
+
+/-- Public data give the total address, number of pieces, and output base. -/
+def splitOps : List (Op 7 3) :=
+ [.stateWord 0, .publicWord 1 0, .read 2 1, .publicWord 3 1,
+ .binary .div 4 2 3, .binary .mod 5 2 3, .constant 6 1,
+ .binary .add 0 0 6, .binary .div 5 5 0, .binary .div 5 5 5,
+ .binary .add 4 4 5, .publicWord 1 2, .stateWord 5, .binary .add 1 1 5,
+ .write 1 4]
+
+/-- Word width assigned to piece `i` when splitting a total `b` among `q` pieces. For `i < q`,
+the first `b % q` pieces get one more than `b / q`. -/
+def splitValue (b q i : Word w) : Word w :=
+ let t := div (mod b q) (i+1)
+ div b q + div t t
+
+/-- Trace of one split visit, reading the total, writing the width at the output base plus
+piece index `i`, and returning `i + 1`. -/
+def splitReport (p : Fin 3 → Word w) (mem : Memory w) (i : Word w) : Report w :=
+ let b := mem (p 0).val
+ ⟨[.tick,.tick,.read (p 0) b,.tick,.tick,.tick,.tick,.tick,.tick,.tick,
+ .tick,.tick,.tick,.tick,.write (p 2+i) (splitValue b (p 1) i)],some (i+1)⟩
+
+theorem split_native (p : Fin 3 → Word w) (mem : Memory w) (i : Word w) :
+ let M := (template splitOps 0).instantiate w p
+ execute M.program 16 (M.program.start i) mem [] = some (splitReport p mem i) := by
+ let M := (template splitOps 0).instantiate w p
+ change execute M.program (1+splitOps.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ mem [] = _
+ rw [execute_template,run_eq_trace]
+ simp (config := {decide := true}) [splitOps,splitReport,splitValue,trace,Op.effect,BinaryOp.eval,
+ div,mod,Function.update]
+ exact ⟨rfl,rfl⟩
+
+private theorem div_val (a b : Word w) : (div a b).val = a.val / b.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt a.isLt)
+
+private theorem mod_val (a b : Word w) : (mod a b).val = a.val % b.val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt a.isLt)
+
+/-- Division of the remainder by the next cursor, followed by its nonzero
+indicator, supplies the extra bit exactly to the initial remainder-many fields. -/
+theorem splitValue_eq (b q i : Word w) (hi : i.val < q.val) :
+ (splitValue b q i).val = splitWidth b.val q.val ⟨i.val,hi⟩ := by
+ let t := div (mod b q) (i+1)
+ have hone : (1 : Word w).val = 1 := by rw [Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^w by have := q.isLt; omega)]
+ have hnext : (i+1).val = i.val+1 := by
+ rw [Fin.val_add, hone, Nat.mod_eq_of_lt (by have := q.isLt; omega)]
+ have ht : t.val = (b.val % q.val) / (i.val+1) := by rw [div_val,mod_val,hnext]
+ have hq : 0 < q.val := by omega
+ have hsum : (∑ j, splitWidth b.val q.val j) < 2^w := (sum_splitWidth _ _ hq) ▸ b.isLt
+ have hfit : splitWidth b.val q.val ⟨i.val,hi⟩ < 2^w := (Finset.single_le_sum (fun j _ => Nat.zero_le (splitWidth b.val q.val j))
+ (Finset.mem_univ (⟨i.val,hi⟩ : Fin q.val))).trans_lt hsum
+ change (div b q + div t t).val = _
+ rw [Fin.val_add,div_val,div_val]
+ apply (Nat.mod_eq_of_lt _).trans
+ · exact (show b.val / q.val + t.val / t.val = splitWidth b.val q.val ⟨i.val,hi⟩ by
+ by_cases h : i.val < b.val % q.val
+ · rw [Nat.div_self (ht ▸ Nat.div_pos h (Nat.zero_lt_succ _)), splitWidth, ite_eq_left h]
+ · rw [ht, Nat.div_eq_of_lt (show b.val % q.val < i.val+1 by omega), Nat.zero_div, Nat.add_zero, splitWidth, ite_eq_right h])
+ · by_cases h : i.val < b.val % q.val
+ · rw [Nat.div_self (ht ▸ Nat.div_pos h (Nat.zero_lt_succ _))]
+ simpa only [splitWidth,ite_eq_left h] using hfit
+ · rw [ht,Nat.div_eq_of_lt (show b.val % q.val < i.val+1 by omega),Nat.zero_div,Nat.add_zero]
+ exact (Nat.div_le_self ..).trans_lt b.isLt
+
+/-- Initial contents outside the target width row are preserved. -/
+structure SplitAt (p : Fin 3 → Word w) (initial mem : Memory w) (k : ℕ) : Prop where
+ rows : ∀ i : Fin (p 1).val, i.val < k →
+ (mem ((p 2).val+i.val)).val = splitWidth (initial (p 0).val).val (p 1).val i
+ frame : ∀ x, x < (p 2).val ∨ (p 2).val+k ≤ x → mem x = initial x
+
+/-- The piece-count word is also the stopping cursor. Every call has two probes
+and sixteen instructions, including the return. -/
+theorem split_prefix (p : Fin 3 → Word w) (mem : Memory w) (k : ℕ) (hk : k ≤ (p 1).val)
+ (fit : (p 2).val + (p 1).val ≤ 2^w)
+ (apart : (p 0).val < (p 2).val ∨ (p 2).val+(p 1).val ≤ (p 0).val) :
+ let M := (template splitOps 0).instantiate w p
+ ∃ rs, runSegment M.program 16 (some 0) mem (List.replicate k []) = some rs ∧
+ SplitAt p mem (after mem (eventLog rs)) k ∧
+ endState (some 0) rs = some (Fin.ofNat _ k) ∧ rs.length = k ∧
+ ∀ r ∈ rs, r.probes = 2 ∧ r.events.length+1 = 16 := by
+ let M := (template splitOps 0).instantiate w p
+ induction k with
+ | zero => exact ⟨[],rfl,⟨fun _ h => by omega,fun _ _ => rfl⟩,rfl,rfl,by simp⟩
+ | succ k ih =>
+ obtain ⟨rs,hr,cur,he,hl,hw⟩ := ih (by omega)
+ let i : Word w := Fin.ofNat _ k
+ have hv : i.val = k := Nat.mod_eq_of_lt (by have := (p 1).isLt; omega)
+ have hn : i+1 = Fin.ofNat _ (k+1) := by
+ apply Fin.ext
+ rw [Fin.val_add,Fin.val_one',hv,Nat.add_mod_mod]; rfl
+ have ha : (p 2+i).val = (p 2).val + k := by
+ rw [Fin.val_add,hv,Nat.mod_eq_of_lt (by omega)]
+ let m := after mem (eventLog rs)
+ let r := splitReport p m i
+ have hmem : after mem (eventLog (rs ++ [r])) =
+ writeMemory m (p 2+i) (splitValue (m (p 0).val) (p 1) i) := by
+ simp only [eventLog,List.flatMap_append,after,List.foldl_append]
+ rfl
+ have hs : m (p 0).val = mem (p 0).val := cur.frame _ (by omega)
+ refine ⟨rs ++ [r],?_,⟨?_,?_⟩,?_,by simp [hl],?_⟩
+ · rw [List.replicate_succ',PrimedSchedule.runSegment_append,hr]
+ simp only [Option.bind_some,he,runSegment,split_native,Option.map_some]
+ rfl
+ · intro j hj
+ rw [hmem]
+ by_cases h : j.val = k
+ · simp only [writeMemory,ha,h,↓reduceIte,hs]
+ rw [splitValue_eq (mem (p 0).val) (p 1) i (by omega)]
+ exact congrArg _ (Fin.ext (hv.trans h.symm))
+ · simpa only [writeMemory,ha,ite_eq_right (show (p 2).val+j.val ≠ (p 2).val+k by omega)] using
+ cur.rows j (by omega)
+ · intro x hx
+ rw [hmem,writeMemory,ha,ite_eq_right (by omega)]
+ exact cur.frame _ (by omega)
+ · rw [endState_append]; exact congrArg some hn
+ · intro t ht
+ rcases List.mem_append.mp ht with ht | ht
+ · exact hw _ ht
+ · obtain rfl := List.mem_singleton.mp ht; exact ⟨rfl,rfl⟩
+
+/-- Materialize the complete target array from the total cell. -/
+theorem split_run (p : Fin 3 → Word w) (mem : Memory w)
+ (fit : (p 2).val + (p 1).val ≤ 2^w)
+ (apart : (p 0).val < (p 2).val ∨ (p 2).val+(p 1).val ≤ (p 0).val) :
+ let M := (template splitOps 0).instantiate w p
+ ∃ rs, runSegment M.program 16 (some 0) mem (List.replicate (p 1).val []) = some rs ∧
+ SplitAt p mem (after mem (eventLog rs)) (p 1).val ∧
+ endState (some 0) rs = some (p 1) ∧ rs.length = (p 1).val ∧
+ ∀ r ∈ rs, r.probes = 2 ∧ r.events.length+1 = 16 := by
+ simpa using split_prefix p mem (p 1).val le_rfl fit apart
+
+
+open SliceSchedule
+
+/-- The native descriptor pass with its exact local cost. -/
+structure Built (o t B : Word w) (old new : List ℕ) (m : Memory w) (rs : Passes w) : Prop where
+ runs : NativePasses o t B old.length new.length m rs
+ stored : Stored B old new m (rs.result m)
+ calls : rs.all.length = 2 + 2*(old.length+new.length) + 2*(old.length*new.length)
+ probes : (rs.all.map Report.probes).sum = 2 + 5*(old.length+new.length) +
+ 6*(old.length*new.length) + 8*(copyRecords old new).length
+ instructions : (rs.all.map fun r => r.events.length+1).sum = 16 + 22*(old.length+new.length) +
+ 46*(old.length*new.length) + 28*(copyRecords old new).length
+
+theorem build_arrays (o t B : Word w) (old new : List ℕ) (m : Memory w)
+ (space : Workspace o t B old.length new.length)
+ (ho : old.sum < 2^w) (hn : new.sum < 2^w)
+ (src : ∀ i (hi : i < old.length), (m (o.val+i)).val = old[i])
+ (dst : ∀ i (hi : i < new.length), (m (t.val+i)).val = new[i]) :
+ ∃ rs, Built o t B old new m rs := by
+ obtain ⟨rs,h₁,h₂,h₃,h₄,h₅⟩ := build old new o t B m space ho hn src dst
+ exact ⟨rs,h₁,h₂,h₃,h₄,h₅⟩
+
+/-- Put the source total and piece count in the fixed split-worker slots. -/
+def splitData (total q t : Word w) : Fin 3 → Word w := ![total,q,t]
+
+/-- A complete native split scan from cursor zero to `q`, with one two-probe report per piece
+and the resulting widths in the output row at `t`. -/
+structure SplitPass (total q t : Word w) (mem : Memory w) (rs : List (Report w)) : Prop where
+ runs : let M := (template splitOps 0).instantiate w (splitData total q t)
+ runSegment M.program 16 (some 0) mem (List.replicate q.val []) = some rs
+ widths : SplitAt (splitData total q t) mem (after mem (eventLog rs)) q.val
+ result : endState (some 0) rs = some q
+ length : rs.length = q.val
+ cost : ∀ r ∈ rs, r.probes = 2 ∧ r.events.length+1 = 16
+
+/-- Repartition a physical old row. The native split and descriptor schedules
+share external memory, including the computed total and the old widths. -/
+theorem split_build (o total q t B : Word w) (old : List ℕ) (mem : Memory w)
+ (space : Workspace o t B old.length q.val) (hq : 0 < q.val)
+ (apart : total.val < t.val ∨ t.val+q.val ≤ total.val)
+ (rowsApart : o.val+old.length ≤ t.val ∨ t.val+q.val ≤ o.val)
+ (widths : ∀ i (hi : i < old.length), (mem (o.val+i)).val = old[i])
+ (sum : (mem total.val).val = old.sum) :
+ ∃ split desc, SplitPass total q t mem split ∧
+ Built o t B old (List.ofFn (splitWidth old.sum q.val)) (after mem (eventLog split)) desc := by
+ let p := splitData total q t
+ obtain ⟨rs,hr,hp,he,hl,hc⟩ := split_run p mem space.newFit apart
+ let out := after mem (eventLog rs)
+ let new := List.ofFn (splitWidth old.sum q.val)
+ have hn : new.length = q.val := List.length_ofFn
+ have hsum : new.sum = old.sum := List.sum_ofFn.trans (sum_splitWidth _ _ hq)
+ have hfit : old.sum < 2^w := sum ▸ (mem total.val).isLt
+ have src (i : ℕ) (hi : i < old.length) : (out (o.val+i)).val = old[i] := by
+ rw [show out (o.val+i) = mem (o.val+i) from hp.frame _ (show o.val+i < t.val ∨ t.val+q.val ≤ o.val+i by omega)]
+ exact widths i hi
+ have dst (i : ℕ) (hi : i < new.length) : (out (t.val+i)).val = new[i] := by
+ have hj : i < q.val := hn ▸ hi
+ have h := hp.rows (⟨i,hj⟩ : Fin q.val) hj
+ change (out (t.val+i)).val = splitWidth (mem total.val).val q.val ⟨i,hj⟩ at h
+ simpa only [new,List.getElem_ofFn,sum] using h
+ obtain ⟨desc,hd⟩ := build_arrays o t B old new out (hn ▸ space) hfit (hsum ▸ hfit) src dst
+ exact ⟨rs,desc,⟨hr,hp,he,hl,hc⟩,hd⟩
+
+/-- Read the selected supply field and repetition word, multiply by the fixed
+selector width, and store the complete width for the subsequent split pass. -/
+def supplyOps : List (Op 6 3) :=
+ [.stateWord 0,.constant 1 1,.binary .add 2 0 1,.read 2 2,.publicWord 3 1,
+ .binary .mul 2 2 3,.constant 1 2,.binary .add 3 0 1,.publicWord 4 0,
+ .binary .add 3 3 4,.read 4 3,.binary .add 4 4 2,.publicWord 5 2,.write 5 4,
+ .constant 0 0]
+
+/-- The supply worker’s three public operands in order are the term-field coordinate, selector
+width per repetition, and address for the resulting total. -/
+def supplyData (coordinate selectors total : Word w) : Fin 3 → Word w :=
+ ![coordinate,selectors,total]
+
+/-- Total width of the selected supply field, equal to its payload word plus the repetition
+count times the selector width. -/
+def supplyValue (p : Fin 3 → Word w) (base : Word w) (m : Memory w) : Word w :=
+ m (base+2+p 0).val + m (base+1).val * p 1
+
+/-- Report of the supply worker, reading the repetition count and selected payload from the
+term record, writing their combined width to the total cell, and returning zero. -/
+def supplyReport (p : Fin 3 → Word w) (base : Word w) (m : Memory w) : Report w :=
+ ⟨[.tick,.tick,.tick,.read (base+1) (m (base+1).val),.tick,.tick,.tick,.tick,.tick,.tick,
+ .read (base+2+p 0) (m (base+2+p 0).val),.tick,.tick,.write (p 2) (supplyValue p base m),.tick],some 0⟩
+
+theorem supply_native (p : Fin 3 → Word w) (base : Word w) (m : Memory w) :
+ let M := (template supplyOps 0).instantiate w p
+ execute M.program 16 (M.program.start base) m [] = some (supplyReport p base m) ∧
+ after m (supplyReport p base m).events = writeMemory m (p 2) (supplyValue p base m) ∧
+ (supplyReport p base m).probes = 3 ∧ (supplyReport p base m).events.length+1 = 16 := by
+ let M := (template supplyOps 0).instantiate w p
+ refine ⟨?_,rfl,rfl,rfl⟩
+ change execute M.program (1+supplyOps.length) ⟨M.entry,base,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template,run_eq_trace]
+ simp (config := {decide := true}) [supplyOps,supplyReport,supplyValue,trace,Op.effect,BinaryOp.eval,Function.update]
+ exact ⟨⟨rfl,rfl⟩,rfl⟩
+
+theorem supplyValue_eq (p : Fin 3 → Word w) (base : Word w) (m : Memory w)
+ {width : ℕ} (hfit : base.val+2+(p 0).val < 2^w)
+ (read : (m (base.val+2+(p 0).val)).val + (m (base.val+1)).val * (p 1).val = width)
+ (hw : width < 2^w) : (supplyValue p base m).val = width := by
+ have h1 : (base+1).val = base.val+1 := by
+ rw [Fin.val_add,Fin.val_one',Nat.mod_eq_of_lt (show 1 < 2^w by omega),Nat.mod_eq_of_lt (by omega)]
+ have h2 : (2 : Word w).val = 2 := Nat.mod_eq_of_lt (show 2 < 2^w by omega)
+ have h3 : (base+2+p 0).val = base.val+2+(p 0).val := by
+ simp only [Fin.val_add,h2,Nat.mod_add_mod,Nat.mod_eq_of_lt hfit]
+ rw [supplyValue,Fin.val_add,Fin.val_mul,h3,h1,Nat.add_mod_mod,read,Nat.mod_eq_of_lt hw]
+
+section Supply
+
+open MotifGrid MotifBlocks MotifConversion MotifSelector
+
+variable {K : Type*} [_root_.Field K] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (F : FixedBlock K a b P (realWidths p) (realWidths q) H H')
+
+/-- Given the two addressed cells of the actual term-record image, the native
+source reader, subdivision pass and interval construction produce both endpoint
+directories for this supply edge. The rest of memory can hold other motifs. -/
+theorem supply_build {n : ℕ} (supply : Fin n ≃ S) (hq : ∀ e, 0 < q e)
+ (demand : D → ℕ) (v : ↥(outerIndices F demand)) (i : Fin n)
+ (prior m : Memory w) (base row u count total t B : BurstRAM.Word w)
+ (recFit : base.val+2+n < 2^w) (cap : outerCap F demand < 2^w)
+ (rep : u.val = repetitions F demand)
+ (record : ∀ x, base.val ≤ x → x < base.val+2+n →
+ m x = TermRecord.recordMemory prior base row u supply v.val x)
+ (selectors : F.selectorBits < 2^w)
+ (wf : supplyWidths F demand v.val (supply i) < 2^w)
+ (space : Workspace total t B 1 count.val) (hc : 0 < count.val)
+ (apart : total.val < t.val ∨ t.val+count.val ≤ total.val) :
+ let pub := supplyData (Fin.ofNat _ i.val) (Fin.ofNat _ F.selectorBits) total
+ let r := supplyReport pub base m
+ let M := (template supplyOps 0).instantiate w pub
+ let width := supplyWidths F demand v.val (supply i)
+ let m₁ := after m r.events
+ execute M.program 16 (M.program.start base) m [] = some r ∧
+ (m₁ total.val).val = width ∧ r.probes = 3 ∧ r.events.length+1 = 16 ∧
+ ∃ split desc, SplitPass total count t m₁ split ∧
+ Built total t B [width] (List.ofFn (splitWidth width count.val)) (after m₁ (eventLog split)) desc := by
+ intro pub r M width m₁
+ have hi : (pub 0).val = i.val := Nat.mod_eq_of_lt (by have := i.isLt; omega)
+ have hs : (pub 1).val = F.selectorBits := Nat.mod_eq_of_lt selectors
+ have exactWidth := TermRecord.recordMemory_supply F prior base row u supply hq demand v cap recFit rep i
+ have read : (m (base.val+2+(pub 0).val)).val + (m (base.val+1)).val * (pub 1).val = width := by
+ rw [hi,hs,record _ (by omega) (by have := i.isLt; omega),record _ (by omega) (by have := i.isLt; omega)]
+ exact exactWidth
+ have hval := supplyValue_eq pub base m (hi ▸ (show base.val+2+i.val < 2^w by have := i.isLt; omega)) read wf
+ obtain ⟨hr,hm,probes,cost⟩ := supply_native pub base m
+ have ht : (m₁ total.val).val = width := by
+ change (after m (supplyReport pub base m).events total.val).val = _
+ rw [hm]; simpa only [writeMemory,show pub 2 = total from rfl,↓reduceIte] using hval
+ refine ⟨hr,ht,probes,cost,?_⟩
+ have src (j : ℕ) (hj : j < [width].length) : (m₁ (total.val+j)).val = [width][j] := by
+ obtain rfl : j = 0 := by simpa using hj
+ simpa using ht
+ simpa using split_build total total count t B [width] m₁ space hc apart (by simp; omega) src (by simpa using ht)
+
+end Supply
+
+end CompressorRecords.ShrinkSliceArrays
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSliceHeads.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceHeads.lean
new file mode 100644
index 0000000000..dab902f390
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceHeads.lean
@@ -0,0 +1,226 @@
+import OAI.Computability.VPVNP.CompressorShrinkSliceTable
+import OAI.Computability.VPVNP.CompressorShrinkMotifAbsolute
+
+/-!
+# Computing the physical ports of a shrinking supply row
+
+One fixed worker takes a dense motif-and-role cursor. It reads the absolute
+old arc identifier, the fixed subdivision count and the stored layout bit,
+then writes the seven operands of the supply, split and interval passes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep.Heads
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ShrinkSliceArrays
+open Allocation Compression
+
+variable {w n A : ℕ}
+
+/-- The eleven public words supplying table bases and strides, selector width, and the
+destination for one slice row’s seven operands. -/
+abbrev Public (w : ℕ) := Fin 11 → Word w
+
+/-- External term start and stride, absolute-ID and subdivision tables,
+selected layout cell, width start and stride, interval start and stride,
+selector width, and the destination for the seven physical operands. -/
+def params (T : Allocation w n A) (absolute subdiv layout out : Word w) : Public w :=
+ ![Fin.ofNat _ T.termBase,Fin.ofNat _ T.termStride,absolute,subdiv,layout,Fin.ofNat _ T.widthBase,
+ Fin.ofNat _ T.stride,Fin.ofNat _ T.widthEnd,Fin.ofNat _ T.recordStride,T.selectors,out]
+
+/-- Native code that decodes a motif-and-role cursor, reads the motif’s absolute ID, the role’s
+subdivision count, and the layout bit, then writes the seven slice operands and advances
+the cursor. -/
+def ops : List (Op 12 11) :=
+ [.stateWord 0,.constant 1 2,.binary .add 1 1 1,.binary .div 2 0 1,.binary .mod 3 0 1,
+ .publicWord 7 2,.binary .add 7 7 2,.read 4 7,
+ .publicWord 7 3,.binary .add 7 7 3,.read 5 7,
+ .publicWord 7 4,.read 9 7,.binary .mul 9 9 1,.binary .add 9 9 3,
+ .publicWord 7 1,.binary .mul 10 2 7,.publicWord 7 0,.binary .add 10 7 10,
+ .publicWord 7 8,.binary .mul 8 0 7,.publicWord 7 7,.binary .add 8 7 8,
+ .binary .mul 4 4 1,.binary .add 4 4 3,.publicWord 7 6,.binary .mul 4 4 7,
+ .publicWord 7 5,.binary .add 4 7 4,.publicWord 7 9,.publicWord 6 10,.constant 11 1,
+ .write 6 10,.binary .add 6 6 11,.write 6 9,.binary .add 6 6 11,.write 6 7,
+ .binary .add 6 6 11,.write 6 8,.binary .add 6 6 11,.write 6 5,.binary .add 6 6 11,
+ .write 6 4,.binary .add 6 6 11,.binary .add 8 8 11,.write 6 8,.binary .add 0 0 11]
+
+private abbrev radix : Word w := 2+2
+/-- Dense motif index obtained by dividing the row cursor by the four roles per motif. -/
+def dense (cursor : Word w) := BinaryOp.div.eval cursor radix
+/-- Role index within the motif, given by the row cursor modulo four. -/
+def role (cursor : Word w) := BinaryOp.mod.eval cursor radix
+
+/-- Compute one row’s term address, supply operands, subdivision count, width destination, and
+descriptor bank from the cursor and the three input table reads. -/
+def readRow (p : Public w) (m : Memory w) (cursor : Word w) : Row w :=
+ let i := dense cursor
+ let t := role cursor
+ let abs := m (p 2+i).val
+ let count := m (p 3+t).val
+ let side := m (p 4).val
+ let total := p 7+cursor*p 8
+ ⟨p 0+i*p 1, supplyData (side*radix+t) (p 9) total,count,p 5+(abs*radix+t)*p 6,total+1⟩
+
+/-- The row header words in storage order are the term address, supply coordinate, selector
+width, total address, piece count, width destination, and descriptor bank. -/
+def words (r : Row w) : Fin 7 → Word w :=
+ ![r.term,r.supply 0,r.supply 1,r.total,r.count,r.dst,r.bank]
+
+private def writeEvents (a : Word w) (r : Row w) : List (Event w) :=
+ [.write a r.term,.tick,.write (a+1) (r.supply 0),.tick,.write (a+1+1) (r.supply 1),
+ .tick,.write (a+1+1+1) r.total,.tick,.write (a+1+1+1+1) r.count,.tick,
+ .write (a+1+1+1+1+1) r.dst,.tick,.tick,.write (a+1+1+1+1+1+1) r.bank,.tick]
+
+/-- Trace for one head-worker call, reading the absolute ID, subdivision count, and layout,
+writing the seven header words, and returning the next row cursor. -/
+def report (p : Public w) (m : Memory w) (c : Word w) : Report w :=
+ let a := p 2+dense c
+ let b := p 3+role c
+ ⟨List.replicate 7 .tick ++ [.read a (m a.val),.tick,.tick,.read b (m b.val),.tick,.read (p 4) (m (p 4).val)] ++
+ List.replicate 19 .tick ++ writeEvents (p 10) (readRow p m c),some (c+1)⟩
+
+set_option maxRecDepth 8192 in
+set_option maxHeartbeats 1400000 in
+theorem native (p : Public w) (m : Memory w) (c : Word w) :
+ let M := (template ops 0).instantiate w p
+ execute M.program 48 (M.program.start c) m [] = some (report p m c) ∧
+ (report p m c).probes = 10 ∧ (report p m c).events.length+1 = 48 := by
+ let M := (template ops 0).instantiate w p
+ refine ⟨?_,rfl,rfl⟩
+ change execute M.program (1+ops.length) ⟨M.entry,c,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template,run_eq_trace]
+ simp (config := {decide := true}) [ops,report,readRow,writeEvents,Row.total,supplyData,dense,role,
+ radix,trace,Op.effect,BinaryOp.eval,Function.update,List.replicate_succ]
+ repeat' first | rfl | apply And.intro
+
+/-- The written header is contiguous and has no external effects elsewhere. -/
+theorem stored (p : Public w) (m : Memory w) (c : Word w) (fit : (p 10).val+7 ≤ 2^w) :
+ let out := after m (report p m c).events
+ (∀ i : Fin 7, out ((p 10).val+i.val) = words (readRow p m c) i) ∧
+ ∀ x, x < (p 10).val ∨ (p 10).val+7 ≤ x → out x = m x := by
+ let a := p 10
+ let v := readRow p m c
+ let m₀ := writeMemory m a v.term
+ let m₁ := writeMemory m₀ (a+1) (v.supply 0)
+ let m₂ := writeMemory m₁ (a+1+1) (v.supply 1)
+ let m₃ := writeMemory m₂ (a+1+1+1) v.total
+ let m₄ := writeMemory m₃ (a+1+1+1+1) v.count
+ let m₅ := writeMemory m₄ (a+1+1+1+1+1) v.dst
+ let m₆ := writeMemory m₅ (a+1+1+1+1+1+1) v.bank
+ have hpost : after m (report p m c).events = m₆ := rfl
+ have hu : (1 : Word w).val = 1 := by rw [Fin.val_one',Nat.mod_eq_of_lt (show 1 < 2^w by omega)]
+ have ha₁ : (a+1).val = a.val+1 := by rw [Fin.val_add,hu,Nat.mod_eq_of_lt (show a.val+1 < 2^w by dsimp [a]; omega)]
+ have ha₂ : (a+1+1).val = a.val+2 := by rw [Fin.val_add,ha₁,hu,Nat.mod_eq_of_lt (show a.val+1+1 < 2^w by dsimp [a]; omega)]
+ have ha₃ : (a+1+1+1).val = a.val+3 := by rw [Fin.val_add,ha₂,hu,Nat.mod_eq_of_lt (show a.val+2+1 < 2^w by dsimp [a]; omega)]
+ have ha₄ : (a+1+1+1+1).val = a.val+4 := by rw [Fin.val_add,ha₃,hu,Nat.mod_eq_of_lt (show a.val+3+1 < 2^w by dsimp [a]; omega)]
+ have ha₅ : (a+1+1+1+1+1).val = a.val+5 := by rw [Fin.val_add,ha₄,hu,Nat.mod_eq_of_lt (show a.val+4+1 < 2^w by dsimp [a]; omega)]
+ have ha₆ : (a+1+1+1+1+1+1).val = a.val+6 := by rw [Fin.val_add,ha₅,hu,Nat.mod_eq_of_lt (show a.val+5+1 < 2^w by dsimp [a]; omega)]
+ dsimp only
+ rw [hpost]
+ constructor
+ · intro i
+ change m₆ (a.val+i.val) = words v i
+ fin_cases i <;> simp [m₆,m₅,m₄,m₃,m₂,m₁,m₀,writeMemory,ha₁,ha₂,ha₃,ha₄,ha₅,ha₆,words]
+ · intro x hx
+ change x < a.val ∨ a.val+7 ≤ x at hx
+ simp only [m₆,m₅,m₄,m₃,m₂,m₁,m₀,writeMemory,ha₁,ha₂,ha₃,ha₄,ha₅,ha₆]
+ repeat' rw [ite_eq_right (by omega)]
+
+private abbrev word (n : ℕ) : Word w := Fin.ofNat _ n
+
+private theorem word_add (x y : ℕ) : word (w := w) x + word y = word (x+y) := by
+ apply Fin.ext
+ simp [word,Fin.val_add,Nat.add_mod]
+
+private theorem word_mul (x y : ℕ) : word (w := w) x * word y = word (x*y) := by
+ apply Fin.ext
+ simp [word,Fin.val_mul,Nat.mul_mod]
+
+/-- The fixed head worker addresses the same term and descriptor rows as
+the simultaneous shrinking sweep. All input answers are actual external words. -/
+theorem readRow_exact (T : Allocation w n A) (fit : T.Fits)
+ (abs sub layout out : Word w) (m : Memory w)
+ (absFit : abs.val+n ≤ 2^w) (subFit : sub.val+4 ≤ 2^w)
+ (absolute : ∀ j, (m (abs.val+j.val)).val = (T.absolute j).val)
+ (counts : ∀ t, (m (sub.val+t.val)).val = T.subdiv t)
+ (side : (m layout.val).val = T.layout.toNat) (i : Id n) :
+ let c := word (w := w) (denseKey i).val
+ readRow (params T abs sub layout out) m c = T.row i := by
+ intro c
+ let p := params T abs sub layout out
+ have hrows : n*4 ≤ T.last := by
+ have h1 : 0 < T.recordStride := by simp [recordStride]
+ have h := Nat.le_mul_of_pos_right (n*4) h1
+ exact h.trans (Nat.le_add_left ..)
+ have hc : c.val = (denseKey i).val := Nat.mod_eq_of_lt ((denseKey i).isLt.trans (hrows.trans_lt fit.room))
+ have hfour : (radix (w := w)).val = 4 := by
+ have htwo : (2 : Word w).val = 2 := Nat.mod_eq_of_lt (by have := fit.roles; omega : 2 < 2^w)
+ rw [radix,Fin.val_add,htwo,Nat.mod_eq_of_lt (by have := fit.roles; omega)]
+ have hnum : (denseKey i).val = i.1.val*4+i.2.val := by change i.2.val+4*i.1.val = _; omega
+ have hd : (dense c).val = i.1.val := by
+ change c.val / radix.val % 2^w = _
+ rw [Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt c.isLt),hfour,hc,hnum,Nat.mul_comm i.1.val,
+ Nat.mul_add_div (by decide : 0 < 4),Nat.div_eq_of_lt i.2.isLt,Nat.add_zero]
+ have ht : (role c).val = i.2.val := by
+ change c.val % radix.val % 2^w = _
+ rw [Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt c.isLt),hfour,hc,hnum,Nat.mul_add_mod_of_lt i.2.isLt]
+ have ha : (p 2+dense c).val = abs.val+i.1.val := by
+ rw [Fin.val_add,hd,show p 2 = abs from rfl,Nat.mod_eq_of_lt (by have := i.1.isLt; omega)]
+ have hs : (p 3+role c).val = sub.val+i.2.val := by
+ rw [Fin.val_add,ht,show p 3 = sub from rfl,Nat.mod_eq_of_lt (by have := i.2.isLt; omega)]
+ have toWord (x : Word w) {v : ℕ} (h : x.val = v) : x = word v := by
+ apply Fin.ext; exact h ▸ (Nat.mod_eq_of_lt x.isLt).symm
+ have hr : (radix : Word w) = word 4 := toWord _ hfour
+ have key : (T.absoluteKey i).val = (T.absolute i.1).val*4+i.2.val := by
+ change i.2.val+4*(T.absolute i.1).val = _; omega
+ change readRow p m c = _
+ simp only [readRow,ha,hs,toWord _ (absolute i.1),toWord _ (counts i.2),show p 4 = layout from rfl,
+ toWord _ side]
+ simp only [hr,toWord _ hd,toWord _ ht]
+ change Row.mk (word T.termBase+word i.1.val*word T.termStride)
+ (supplyData (word T.layout.toNat*word 4+word i.2.val) T.selectors
+ (word T.widthEnd+c*word T.recordStride)) (word (T.subdiv i.2))
+ (word T.widthBase+(word (T.absolute i.1).val*word 4+word i.2.val)*word T.stride)
+ (word T.widthEnd+c*word T.recordStride+1) = _
+ simp only [row,termStart,widthStart,recordStart,key,c,← show word (w := w) 1 = 1 from rfl,word_mul,word_add]
+
+/-- The dense directory produced by the physical classified-port scatter
+supplies the absolute index column required by the head worker. -/
+theorem directory_input {V : Type} {a g N : ℕ}
+ (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) (ord : V ≃ Fin N)
+ (cd : (orderedDyadicPacking G ord).BundleNumbering) (base : Word w) (m : Memory w)
+ (h : MotifAbsolute.Directory G ord cd base m) :
+ let P := orderedDyadicPacking G ord
+ let sites := Shrink.packedIndex (a := a) (g := g) ord
+ let ids := ShrinkSliceSweep.absolute P cd sites ord (bitWordFinEquiv (Shrink.J a)) (bitWordFinEquiv g)
+ ∀ i, (m (base.val+i.val)).val = (ids i).val := h
+
+/-- One physical row cursor prepares all worker operands from the dense
+directory, the subdivision profile and the common layout bit. -/
+theorem prepare (T : Allocation w n A) (fit : T.Fits) (abs sub layout out : Word w) (m : Memory w)
+ (absFit : abs.val+n ≤ 2^w) (subFit : sub.val+4 ≤ 2^w) (outFit : out.val+7 ≤ 2^w)
+ (absolute : ∀ j, (m (abs.val+j.val)).val = (T.absolute j).val)
+ (counts : ∀ t, (m (sub.val+t.val)).val = T.subdiv t)
+ (side : (m layout.val).val = T.layout.toNat) (i : Id n) :
+ let p := params T abs sub layout out
+ let c := Fin.ofNat (2^w) (denseKey i).val
+ let M := (template ops 0).instantiate w p
+ let r := report p m c
+ let next := after m r.events
+ execute M.program 48 (M.program.start c) m [] = some r ∧
+ (∀ j : Fin 7, next (out.val+j.val) = words (T.row i) j) ∧
+ (∀ x, x < out.val ∨ out.val+7 ≤ x → next x = m x) ∧ r.probes = 10 ∧ r.events.length+1 = 48 := by
+ intro p c M r next
+ obtain ⟨hr,hp,ht⟩ := native p m c
+ obtain ⟨hw,hframe⟩ := stored p m c outFit
+ have read := readRow_exact T fit abs sub layout out m absFit subFit absolute counts side i
+ exact ⟨hr,fun j => (hw j).trans (congrArg (fun row => words row j) read),hframe,hp,ht⟩
+
+end CompressorRecords.ShrinkSliceSweep.Heads
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSliceInterval.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceInterval.lean
new file mode 100644
index 0000000000..8f7959dd45
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceInterval.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.CompressorShrinkReadbackTransfer
+import OAI.Computability.VPVNP.CompressorSlotCoreAccess
+
+/-! # Shrinking tables survive writes to the descriptor header
+
+The AB and CD interval lookups use cells between the first slice table and
+the ordered-slot workspace. The forward and inverse slot lookups use cells
+in the workspace. The two transfers only need agreement on those ranges.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif MotifBlocks MotifGrid
+open ShrinkBlockInputs ShrinkSliceSweep SlotLevel ShrinkSlots
+open scoped Classical Fin.CommRing
+
+namespace ShrinkOutput
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {i : Fin S.steps}
+variable {g w : ℕ} {X : State (a i) (packingLaneBits (a i) g)} {sel : SelectedScore.Selection B X}
+variable {term stride : Word w} {first width slotStart : ℕ}
+
+local notation "sh" => levelShape (b := b i) X
+local notation "role" => SelectedArena.roleBase X term stride
+local notation "alloc" => splitBank (b := b i) X B.shrink sel term stride.val role width
+local notation "base" => widthBase X term.val stride.val role width
+local notation "ns" => ShrinkBundlePlan.thickCount (a i)
+local notation "nt" => ShrinkBundlePlan.cap (a i)
+
+set_option maxHeartbeats 900000 in
+/-- Slice-table readbacks require agreement only from the AB base through
+the end of the CD tables. Earlier header or resident cells may be written. -/
+theorem SliceReadbacks.transfer_interval {T : IncidenceDirectory w} {start : ℕ} {before post : Memory w} {δ : ℝ}
+ (h : SliceReadbacks B i X sel term stride first width before)
+ (ready : Ready (2^(a i)) (Shrink.colors (a i)) (2^(b i)) δ)
+ (termRoom : ShrinkInput.termEnd X start stride.val < 2^w) (fresh : ShrinkInput.stop X start ≤ first)
+ (widthAfter : first+(ShrinkInput.plan X start).B*IndexedStarts.capacity ns nt ≤ width)
+ (slotAfter : (alloc).last ≤ slotStart) (slotRoom : slotStart < 2^w) (wide : 10 ≤ stride.val)
+ (packedRoom : stop (b := b i) X term.val stride.val role width < 2^w)
+ (frame : ∀ x, first ≤ x → x < slotStart → post x = before x) :
+ SliceReadbacks B i X sel term stride first width post := by
+ have fit := fits X B.shrink sel term stride.val role width ready wide packedRoom
+ have room := (width_le_slots (b := b i) X term stride.val role width).trans slotAfter
+ have abEnd := widthAfter.trans ((retained_room X term stride.val role width).trans room)
+ have lo : first ≤ base := (Nat.le_add_right _ _).trans (widthAfter.trans (retained_room X term stride.val role width))
+ refine ⟨abFields_transfer_interval (T := T) h.abFields termRoom fresh abEnd slotRoom frame,?_,?_⟩
+ · intro j
+ apply (h.intervals j).keep
+ intro x hx
+ have low : (alloc).widthBase ≤ x := le_of_not_gt fun below => hx ((alloc).rowOutside fit j x (.inl below))
+ exact frame x (lo.trans low) (lt_of_not_ge fun beyond => hx ((alloc).rowOutside fit j x (.inr (slotAfter.trans beyond))))
+ · intro j
+ have bound := SlotWidthScan.splitOffset_lt X.packingData (sh).subdivisions X.baseIndex
+ (bitWordFinEquiv (Shrink.J (a i))) (bitWordFinEquiv g) j
+ have last : base+(absoluteCount X*4)*(∑ t,(sh).subdivisions t) ≤ slotStart := (Nat.le_add_right _ _).trans slotAfter
+ rw [frame _ (lo.trans (Nat.le_add_right _ _)) ((Nat.add_lt_add_left bound base).trans_le last)]
+ exact h.sparseWidths j
+
+end ShrinkOutput
+
+namespace ShrinkSlots.Build
+
+variable {a b g w : ℕ} {δ : ℝ} {X : State a (packingLaneBits a g)}
+variable {ready : Ready (2^a) (2*2^a+1) (2^b) δ} {side : Bool} {role slotStart : ℕ}
+
+local notation "sh" => levelShape (b := b) X
+local notation "h" => ShrinkOutput.heads sh role slotStart
+
+/-- The sorted endpoint and inverse-field tables use addresses inside the
+ordered-slot workspace. -/
+theorem OrderedTables.transfer_interval {before post : Memory w} (sorted : OrderedTables X ready side h before)
+ (frame : ∀ x, slotStart ≤ x → x < finish sh h → post x = before x) : OrderedTables X ready side h post := by
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let lanes := bitWordFinEquiv g
+ let D := SlotSchedule.slotDirectory X.packingData (sh).subdivisions X.baseIndex tags lanes side (pad := pad sh)
+ let degree := fun v ↦ (SlotSchedule.slotDirectory_degree X.packingData (sh).subdivisions X.baseIndex tags lanes
+ (State.two_le_packingColors a) side v).trans (Nat.add_sub_of_le ready.degree_budget)
+ have low : slotStart ≤ rowsHead sh h := by unfold rowsHead ShrinkOutput.heads; dsimp only; omega
+ have rect : rowsHead sh h+owners sh*(sh).newDegree ≤ inverseHead sh h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.le_add_right _ _)) _
+ have extent : inverseHead sh h+fields sh = targetsHead sh h := rfl
+ have high : targetsHead sh h ≤ finish sh h := by
+ unfold finish widthHead inHead outHead inverseBaseHead stopAddress shiftsHead; omega
+ constructor
+ · intro e
+ have hi : (SlotSchedule.sortedFields D (2^b) degree e).val < owners sh*(sh).newDegree :=
+ (SlotSchedule.sortedFields D (2^b) degree e).isLt
+ exact (frame (rowsHead sh h+(SlotSchedule.sortedFields D (2^b) degree e).val) (by omega) (by omega)).trans (sorted.bySlot e)
+ · intro e
+ have hi : (D.address e).val < fields sh := (D.address e).isLt
+ exact (frame (inverseHead sh h+(D.address e).val) (by omega) (by omega)).trans (sorted.byField e)
+
+end ShrinkSlots.Build
+end CompressorRecords
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSliceSweep.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceSweep.lean
new file mode 100644
index 0000000000..88321fbd2b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceSweep.lean
@@ -0,0 +1,404 @@
+import OAI.Computability.VPVNP.CompressorShrinkKernelSlices
+import OAI.Computability.VPVNP.CompressorShrinkMotifOrder
+
+/-!
+# Scanning the shrinking supply rows
+
+Each dense term contributes four surviving rows. The width cells use the
+absolute old CD arc number. The interval frames use the dense term number.
+The total cell immediately precedes each row's private interval workspace.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression SliceSchedule ShrinkSliceArrays
+
+variable {w : ℕ}
+
+private theorem rows_separate {i j width : ℕ} (hne : i ≠ j) :
+ i*width+width ≤ j*width ∨ j*width+width ≤ i*width := by
+ rcases lt_or_gt_of_ne hne with hi | hj
+ · exact Or.inl (Nat.succ_mul i width ▸ Nat.mul_le_mul_right width hi)
+ · exact Or.inr (Nat.succ_mul j width ▸ Nat.mul_le_mul_right width hj)
+
+/-- Per-row physical ports of the surviving slice schedule. -/
+structure Row (w : ℕ) where
+ /-- Address of the selected term record supplying the surviving width for this motif and
+ role. -/
+ term : Word w
+ /-- The supply worker receives the selected layout and role coordinate, the selector width,
+ and the address of the total. -/
+ supply : Fin 3 → Word w
+ /-- Number of subdivisions into which this surviving supply width is split. -/
+ count : Word w
+ /-- First output address for the subdivision widths of this old arc and role. -/
+ dst : Word w
+ /-- First address of the interval descriptor workspace for this dense motif and role. -/
+ bank : Word w
+
+/-- The cell where the supply worker writes the selected role's total width before subdivision. -/
+def Row.total (r : Row w) := r.supply 2
+
+/-- The address is outside the row's total cell, subdivision widths and interval descriptor
+bank. -/
+def Row.Outside (r : Row w) (x : ℕ) : Prop :=
+ x ≠ r.total.val ∧ (x < r.dst.val ∨ r.dst.val+r.count.val ≤ x) ∧
+ (x < r.bank.val ∨ stop r.bank.val 1 r.count.val ≤ x)
+
+/-- Native reports in chronological order, with every return/choice checked
+by the existing segment semantics. -/
+structure Run (r : Row w) (width : ℕ) (initial out : Memory w) (reports : List (Report w)) : Prop where
+ executed : ∃ split desc,
+ let call := supplyReport r.supply r.term initial
+ let mid := after initial call.events
+ let M := (template supplyOps 0).instantiate w r.supply
+ execute M.program 16 (M.program.start r.term) initial [] = some call ∧
+ (mid r.total.val).val = width ∧
+ SplitPass r.total r.count r.dst mid split ∧
+ Built r.total r.dst r.bank [width] (List.ofFn (splitWidth width r.count.val)) (after mid (eventLog split)) desc ∧
+ out = desc.result (after mid (eventLog split)) ∧ reports = call :: (split ++ desc.all)
+
+/-- Readout and frame information for one completed row. The terminal memory
+of its interval pass supplies the values inside that row's descriptor bank. -/
+structure Image (r : Row w) (width : ℕ) (out : Memory w) : Prop where
+ total : (out r.total.val).val = width
+ widths : ∀ j : Fin r.count.val, (out (r.dst.val+j.val)).val = splitWidth width r.count.val j
+ descriptors : ∃ before stored, Stored r.bank [width] (List.ofFn (splitWidth width r.count.val)) before stored ∧
+ ∀ x, r.bank.val ≤ x → x < stop r.bank.val 1 r.count.val → out x = stored x
+
+theorem Image.keep {r : Row w} {width : ℕ} {before out : Memory w} (h : Image r width before)
+ (frame : ∀ x, ¬ r.Outside x → out x = before x) : Image r width out := by
+ constructor
+ · rw [frame _ (fun hn => hn.1 rfl)]; exact h.total
+ · intro j
+ rw [frame _ (fun hn => by have := hn.2.1; have := j.isLt; omega)]
+ exact h.widths j
+ · obtain ⟨src,stored,hs,hv⟩ := h.descriptors
+ refine ⟨src,stored,hs,fun x hl hu => ?_⟩
+ exact (frame x (fun hn => by have := hn.2.2; omega)).trans (hv x hl hu)
+
+/-- Replaying the reports reaches the final memory used by the next row. -/
+theorem Run.replay {r : Row w} {b : ℕ} {init out : Memory w} {reports : List (Report w)}
+ (run : Run r b init out reports) : after init (eventLog reports) = out := by
+ obtain ⟨s,d,_,_,_,_,rfl,rfl⟩ := run.executed
+ simp only [Passes.all,Passes.result,Passes.tested,Passes.prepared,SliceRAM.preparationAfter,
+ eventLog,List.flatMap_cons,List.flatMap_append,after,List.foldl_append]
+
+/-- All supply-row writes preserve every cell outside that row. -/
+theorem Run.frame {r : Row w} {b : ℕ} {init out : Memory w} {reports : List (Report w)}
+ (run : Run r b init out reports) {x : ℕ} (hx : r.Outside x) : out x = init x := by
+ obtain ⟨s,d,_,_,hs,hd,rfl,_⟩ := run.executed
+ rw [hd.stored.outside _ (by simpa only [List.length_singleton,List.length_ofFn] using hx.2.2),
+ hs.widths.frame x hx.2.1,(supply_native r.supply r.term init).2.1]
+ exact ite_eq_right hx.1
+
+/-- Once the split and descriptor workspaces fit, the complete row stores
+the chosen width, the subdivisions and the interval records. -/
+theorem Run.image {r : Row w} {b : ℕ} {init out : Memory w} {reports : List (Report w)}
+ (run : Run r b init out reports) (space : Workspace r.total r.dst r.bank 1 r.count.val)
+ (apart : r.total.val < r.dst.val ∨ r.dst.val+r.count.val ≤ r.total.val) : Image r b out := by
+ obtain ⟨s,d,_,ht,hs,hd,rfl,_⟩ := run.executed
+ constructor
+ · rw [hd.stored.outside _ (by
+ simp only [List.length_singleton,List.length_ofFn]; have := space.oldApart; omega),
+ hs.widths.frame _ apart]
+ exact ht
+ · intro j
+ rw [hd.stored.outside _ (by
+ simp only [List.length_singleton,List.length_ofFn]; have := space.newApart; have := j.isLt; omega)]
+ exact (hs.widths.rows j j.isLt).trans (congrArg (fun b => splitWidth b r.count.val j) ht)
+ · exact ⟨_,_,hd.stored,fun _ _ _ => rfl⟩
+
+/-- A supply row with q subdivisions uses one source-reader call, q split
+calls and the descriptor builder. Its total calls plus probes are linear in q. -/
+theorem Run.cost {r : Row w} {b : ℕ} {init out : Memory w} {reports : List (Report w)}
+ (run : Run r b init out reports) :
+ reports.length = 5+5*r.count.val ∧ (reports.map Report.probes).sum ≤ 10+21*r.count.val ∧
+ (reports.map (fun t => t.events.length+1)).sum ≤ 54+112*r.count.val := by
+ obtain ⟨s,d,_,_,hs,hd,_,rfl⟩ := run.executed
+ let q := r.count.val
+ have hp : (s.map Report.probes).sum = 2*s.length := by
+ have he : s.map Report.probes = List.replicate s.length 2 :=
+ List.map_eq_replicate_iff.mpr (fun x hx => (hs.cost x hx).1)
+ simp [he,Nat.mul_comm]
+ have hi : (s.map (fun x => x.events.length+1)).sum = 16*s.length := by
+ have he : s.map (fun x => x.events.length+1) = List.replicate s.length 16 :=
+ List.map_eq_replicate_iff.mpr (fun x hx => (hs.cost x hx).2)
+ simp [he,Nat.mul_comm]
+ have hk := copyRecords_length_le [b] (List.ofFn (splitWidth b q))
+ have hc := (supply_native r.supply r.term init).2.2
+ simp only [List.length_singleton,List.length_ofFn,one_mul,q] at hk
+ simp only [List.length_cons,List.length_append,List.map_cons,List.sum_cons,List.map_append,List.sum_append,
+ hd.calls,hd.probes,hd.instructions,List.length_nil,List.length_ofFn,hp,hi,hs.length,hc.1,hc.2]
+ omega
+
+variable {ι : Type*}
+
+/-- In the supplied order, thread each interval builder's output memory into
+the first width read of the next row. -/
+inductive Runs (r : ι → Row w) (b : ι → ℕ) :
+ List ι → Memory w → Memory w → List (Report w) → Prop where
+ | nil (m : Memory w) : Runs r b [] m m []
+ | cons {i : ι} {is : List ι} {m next out : Memory w} {head tail : List (Report w)} :
+ Run (r i) (b i) m next head → Runs r b is next out tail → Runs r b (i::is) m out (head++tail)
+
+theorem Runs.replay {r : ι → Row w} {b : ι → ℕ} {is : List ι} {m out : Memory w}
+ {rs : List (Report w)} (h : Runs r b is m out rs) : after m (eventLog rs) = out := by
+ induction h with
+ | nil => rfl
+ | @cons _ _ m next _ head tail step _ ih =>
+ rw [show after m (eventLog (head ++ tail)) = after (after m (eventLog head)) (eventLog tail) from
+ by simp only [after,eventLog,List.flatMap_append,List.foldl_append],step.replay,ih]
+
+/-- Exact memory frame of a sequence of native rows. -/
+theorem Runs.frame {r : ι → Row w} {b : ι → ℕ} {is : List ι} {m out : Memory w}
+ {rs : List (Report w)} (h : Runs r b is m out rs) {x : ℕ}
+ (hx : ∀ i ∈ is, (r i).Outside x) : out x = m x := by
+ induction h with
+ | nil => rfl
+ | @cons i is _ _ _ _ _ step _ ih =>
+ exact (ih fun j hj => hx j (List.mem_cons_of_mem _ hj)).trans (step.frame (hx i List.mem_cons_self))
+
+theorem Runs.cost {r : ι → Row w} {b : ι → ℕ} {is : List ι} {m out : Memory w}
+ {rs : List (Report w)} (h : Runs r b is m out rs) {Q : ℕ} (hq : ∀ i ∈ is, (r i).count.val ≤ Q) :
+ rs.length ≤ is.length*(5+5*Q) ∧ (rs.map Report.probes).sum ≤ is.length*(10+21*Q) ∧
+ (rs.map (fun t => t.events.length+1)).sum ≤ is.length*(54+112*Q) := by
+ induction h with
+ | nil => simp
+ | @cons i is _ _ _ _ _ step _ ih =>
+ obtain ⟨ac,ap,ai⟩ := step.cost
+ obtain ⟨bc,bp,bi⟩ := ih fun j hj => hq j (List.mem_cons_of_mem _ hj)
+ have := hq i List.mem_cons_self
+ simp only [List.length_append,List.length_cons,List.map_append,List.sum_append]
+ rw [Nat.add_mul,Nat.add_mul,Nat.add_mul,one_mul,one_mul,one_mul]
+ omega
+
+/-- Scan actual workers with disjoint output rows. The returned images coexist
+in a single final memory and the read-only term table remains usable throughout. -/
+theorem scan {r : ι → Row w} {b : ι → ℕ} (ready : Memory w → Prop)
+ (space : ∀ i, Workspace (r i).total (r i).dst (r i).bank 1 (r i).count.val)
+ (apart : ∀ i, (r i).total.val < (r i).dst.val ∨ (r i).dst.val+(r i).count.val ≤ (r i).total.val)
+ (separate : ∀ {i j}, i ≠ j → ∀ x, ¬ (r i).Outside x → (r j).Outside x)
+ (keep : ∀ i m out, ready m → (∀ x, (r i).Outside x → out x = m x) → ready out)
+ (worker : ∀ i m, ready m → ∃ out rs, Run (r i) (b i) m out rs)
+ (is : List ι) (m : Memory w) (hready : ready m) (nodup : is.Nodup) :
+ ∃ out rs, Runs r b is m out rs ∧ ready out ∧ ∀ i ∈ is, Image (r i) (b i) out := by
+ induction is generalizing m with
+ | nil => exact ⟨m,[],.nil _,hready,by simp⟩
+ | cons i is ih =>
+ obtain ⟨next,head,run⟩ := worker i m hready
+ have nd := List.nodup_cons.mp nodup
+ obtain ⟨out,tail,done,hr,stored⟩ := ih next (keep i _ _ hready fun _ hx => run.frame hx) nd.2
+ refine ⟨out,head++tail,.cons run done,hr,fun j hj => ?_⟩
+ rcases List.mem_cons.mp hj with rfl | hj
+ · apply (run.image (space j) (apart j)).keep
+ intro x hx
+ exact done.frame fun k hk => separate (i := j) (j := k) (fun e => nd.1 (e.symm ▸ hk)) x hx
+ · exact stored j hj
+
+
+variable {n A : ℕ}
+
+/-- The dense term rectangle precedes the absolute-ID width rectangle.
+Interval records follow in dense order, leaving the term rows read-only. -/
+structure Allocation (w n A : ℕ) where
+ /-- First address of the selected term records, stored in dense motif order. -/
+ termBase : ℕ
+ /-- Reserved word count between consecutive dense term records. -/
+ termStride : ℕ
+ /-- First address of the surviving-width table indexed by absolute old arc and supply role. -/
+ widthBase : ℕ
+ /-- Injectively map a dense motif ordinal to its absolute old CD arc number for locating its
+ widths. -/
+ absolute : Fin n ↪ Fin A
+ /-- The subdivision count assigned to each of the four supply roles. -/
+ subdiv : Fin 4 → ℕ
+ /-- Selector-bit count supplied to the worker when it reads a selected term's supply
+ coordinate. -/
+ selectors : Word w
+ /-- The selected layout side used to choose the four supply coordinates from each term. -/
+ layout : Bool
+
+namespace Allocation
+
+variable (D : Allocation w n A)
+
+/-- A surviving row identified by its dense motif ordinal and one of four supply roles. -/
+abbrev Id (n : ℕ) := Fin n × Fin 4
+
+/-- Words reserved for a surviving-width row, using the sum of the four role subdivision
+counts. -/
+def stride := ∑ t, D.subdiv t
+/-- Words reserved for each dense role's total and interval workspace, five plus seven times
+the width-row stride. -/
+def recordStride := 5+7*D.stride
+/-- Exclusive end of all absolute arc/role width rows and starting address for the dense
+interval records. -/
+def widthEnd := D.widthBase+(A*4)*D.stride
+/-- Exclusive end of the full allocation, after the width table and all dense motif/role
+interval records. -/
+def last := D.widthEnd+(n*4)*D.recordStride
+
+/-- Flatten the absolute old arc number and role into a single index of the width table. -/
+def absoluteKey (i : Id n) : Fin (A*4) := finProdFinEquiv (D.absolute i.1,i.2)
+/-- Flatten the dense motif ordinal and role into a single index of the interval-record table. -/
+def denseKey (i : Id n) : Fin (n*4) := finProdFinEquiv i
+/-- Starting address of the selected term at a given dense motif ordinal. -/
+def termStart (i : Fin n) := D.termBase+i.val*D.termStride
+/-- Starting address of the surviving widths for the given motif's absolute old arc and role. -/
+def widthStart (i : Id n) := D.widthBase+(D.absoluteKey i).val*D.stride
+/-- Starting address of the total and interval workspace for a given dense motif and role. -/
+def recordStart (i : Id n) := D.widthEnd+(denseKey i).val*D.recordStride
+
+/-- Term records have room for ten fields and precede the widths, all roles have positive
+subdivisions, and the allocation and eight supply coordinates fit in words. -/
+structure Fits : Prop where
+ termStride : 10 ≤ D.termStride
+ terms : D.termBase+n*D.termStride ≤ D.widthBase
+ positive : ∀ t, 0 < D.subdiv t
+ room : D.last < 2^w
+ roles : 8 < 2^w
+
+/-- Build the physical operands for a motif/role sweep, placing its total first in the dense
+record and its interval workspace immediately afterward. -/
+def row (i : Id n) : Row w :=
+ let total := Fin.ofNat _ (D.recordStart i)
+ ⟨Fin.ofNat _ (D.termStart i.1),supplyData (Fin.ofNat _ (D.layout.toNat*4+i.2.val)) D.selectors total,
+ Fin.ofNat _ (D.subdiv i.2),Fin.ofNat _ (D.widthStart i),Fin.ofNat _ (D.recordStart i+1)⟩
+
+private theorem sub_le (i : Fin 4) : D.subdiv i ≤ D.stride :=
+ Finset.single_le_sum (fun j _ => Nat.zero_le (D.subdiv j)) (Finset.mem_univ _)
+
+private theorem width_stop (i : Id n) : D.widthStart i + D.stride ≤ D.widthEnd := by
+ have h := Nat.mul_le_mul_right D.stride (D.absoluteKey i).isLt
+ rw [Nat.succ_mul] at h
+ dsimp [widthStart,widthEnd]; omega
+
+private theorem record_stop (i : Id n) : D.recordStart i + D.recordStride ≤ D.last := by
+ have h := Nat.mul_le_mul_right D.recordStride (denseKey i).isLt
+ rw [Nat.succ_mul] at h
+ dsimp [recordStart,last]; omega
+
+theorem term_stop (h : D.Fits) (i : Fin n) : D.termStart i+10 ≤ D.widthBase := by
+ have hcap := Nat.mul_le_mul_right D.termStride i.isLt
+ rw [Nat.succ_mul] at hcap
+ have := h.termStride
+ have := h.terms
+ dsimp [termStart]; omega
+
+private theorem width_lt (h : D.Fits) (i : Id n) : D.widthStart i < 2^w := by
+ have hstop := D.width_stop i
+ have hl : D.widthEnd ≤ D.last := Nat.le_add_right ..
+ exact ((Nat.le_add_right ..).trans (hstop.trans hl)).trans_lt h.room
+
+private theorem record_fit (h : D.Fits) (i : Id n) : D.recordStart i+1 < 2^w := by
+ have := D.record_stop i
+ have := h.room
+ simp only [recordStride] at *; omega
+
+theorem row_vals (h : D.Fits) (i : Id n) :
+ let r := D.row i
+ r.term.val = D.termStart i.1 ∧ r.total.val = D.recordStart i ∧ r.bank.val = D.recordStart i+1 ∧
+ r.dst.val = D.widthStart i ∧ r.count.val = D.subdiv i.2 := by
+ have hs := D.sub_le i.2
+ have hb := D.term_stop h i.1
+ have h₁ := D.width_stop i
+ have h₂ : D.widthBase ≤ D.widthStart i := Nat.le_add_right ..
+ have h₃ : D.widthEnd ≤ D.last := Nat.le_add_right ..
+ have h₄ := D.record_fit h i
+ have h₅ := h.room
+ exact ⟨Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt h₄,
+ Nat.mod_eq_of_lt (D.width_lt h i),Nat.mod_eq_of_lt (by omega)⟩
+
+private theorem local_stop (i : Id n) : stop (D.recordStart i+1) 1 (D.subdiv i.2) ≤
+ D.recordStart i+D.recordStride := by
+ have := D.sub_le i.2
+ simp [stop,frameHead,recordStride]; omega
+
+theorem space (h : D.Fits) (i : Id n) :
+ Workspace (D.row i).total (D.row i).dst (D.row i).bank 1 (D.row i).count.val := by
+ obtain ⟨_,ht,hb,hd,hc⟩ := D.row_vals h i
+ have hs := D.sub_le i.2
+ have hw := D.width_stop i
+ have hr := D.record_stop i
+ have he : D.widthEnd ≤ D.recordStart i := Nat.le_add_right ..
+ have hf := h.room
+ have hl := D.local_stop i
+ constructor
+ · rw [hb,hc]; omega
+ · rw [ht]; omega
+ · rw [hd,hc]; omega
+ · left; rw [ht,hb]
+ · left; rw [hd,hb,hc]; omega
+
+theorem apart (h : D.Fits) (i : Id n) :
+ (D.row i).total.val < (D.row i).dst.val ∨
+ (D.row i).dst.val+(D.row i).count.val ≤ (D.row i).total.val := by
+ obtain ⟨_,ht,_,hd,hc⟩ := D.row_vals h i
+ right
+ rw [ht,hd,hc]
+ exact (Nat.add_le_add_left (D.sub_le i.2) _).trans ((D.width_stop i).trans (Nat.le_add_right ..))
+
+private theorem key_injective : Function.Injective D.absoluteKey := by
+ intro i j he
+ have h := finProdFinEquiv.injective he
+ exact Prod.ext (D.absolute.injective (Prod.mk.inj h).1) (Prod.mk.inj h).2
+
+private theorem outside_iff (h : D.Fits) (i : Id n) (x : ℕ) :
+ (D.row i).Outside x ↔ (x < D.widthStart i ∨ D.widthStart i+D.subdiv i.2 ≤ x) ∧
+ (x < D.recordStart i ∨ stop (D.recordStart i+1) 1 (D.subdiv i.2) ≤ x) := by
+ obtain ⟨_,ht,hb,hd,hc⟩ := D.row_vals h i
+ simp only [Row.Outside,ht,hb,hd,hc,stop,frameHead,one_mul]
+ omega
+
+theorem separate (h : D.Fits) {i j : Id n} (hne : i ≠ j) (x : ℕ)
+ (hi : ¬ (D.row i).Outside x) : (D.row j).Outside x := by
+ rw [D.outside_iff h i] at hi
+ rw [D.outside_iff h j]
+ have hkey : (D.absoluteKey i).val ≠ (D.absoluteKey j).val :=
+ fun e => hne (D.key_injective (Fin.ext e))
+ have hden : (denseKey i).val ≠ (denseKey j).val :=
+ fun e => hne (finProdFinEquiv.injective (Fin.ext e))
+ have hw := rows_separate (width := D.stride) hkey
+ have hr := rows_separate (width := D.recordStride) hden
+ have hwi := D.width_stop i
+ have hwj := D.width_stop j
+ have hci := D.sub_le i.2
+ have hcj := D.sub_le j.2
+ have hri := D.local_stop i
+ have hrj := D.local_stop j
+ dsimp only [widthStart,recordStart] at *
+ omega
+
+/-- The two rectangles cover every address touched by any surviving row. -/
+theorem rowOutside (h : D.Fits) (i : Id n) (x : ℕ) (hx : x < D.widthBase ∨ D.last ≤ x) :
+ (D.row i).Outside x := by
+ rw [D.outside_iff h i]
+ have hw : D.widthBase ≤ D.widthStart i := Nat.le_add_right ..
+ have hr : D.widthBase ≤ D.recordStart i := (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ have he : D.widthEnd ≤ D.last := Nat.le_add_right ..
+ have h₁ := D.width_stop i
+ have h₂ := D.sub_le i.2
+ have h₃ := D.local_stop i
+ have h₄ := D.record_stop i
+ omega
+
+theorem termOutside (h : D.Fits) (i : Id n) (j : Fin n) (x : ℕ) (hx : x < D.termStart j+10) :
+ (D.row i).Outside x := by
+ rw [D.outside_iff h i]
+ have hterm := D.term_stop h j
+ have hw : D.widthBase ≤ D.widthStart i := Nat.le_add_right ..
+ have hr : D.widthBase ≤ D.recordStart i := (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ exact ⟨Or.inl (by omega),Or.inl (by omega)⟩
+
+end Allocation
+
+end CompressorRecords.ShrinkSliceSweep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSliceTable.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceTable.lean
new file mode 100644
index 0000000000..918c23594f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSliceTable.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.CompressorShrinkSliceSweep
+
+/-!
+# Complete surviving width and slice tables of one shrinking step
+
+The dense CD order is the assigned bundle followed by the relative-key rank.
+Every role of every chosen CD term runs once. The next slot directory can
+read all surviving widths from the same final external memory by absolute
+arc number and subdivision.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData
+open ShrinkSliceArrays Allocation SliceSchedule MotifBlocks MotifGrid MotifConversion
+open MotifDemandPadding ShrinkMotif
+
+variable {w d c n N J nL : ℕ} {V H Tag L : Type}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (cd : P.BundleNumbering) (site : Site V Tag L ≃ Fin n)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+local notation "M" => (n*d)*pieceCount d c
+local notation "A" => Slots.oldBaseArcCount N J d c * nL
+local notation "order" => ShrinkMotifOrder.number P cd site
+local notation "arc" => Slots.oldArcIndex P vertices tags lanes
+
+/-- Convert a dense motif ordinal into its absolute surviving-slot source
+identifier. The native dense-to-absolute table stores this embedding. -/
+def absolute : Fin M ↪ Fin A where
+ toFun i := arc ((order).symm i).val
+ inj' := (arc).injective.comp (Subtype.val_injective.comp (order).symm.injective)
+
+variable (T : Allocation w ((n*d)*pieceCount d c) (Slots.oldBaseArcCount N J d c * nL))
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable {K : Type*} [_root_.Field K] {factor : ℝ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (old : Arc V H Tag L d c → ℕ)
+variable (choice : ∀ m : P.Motif, P.ShrinkChoice cd old F m)
+
+/-- Memory contains the chosen term fields at every dense motif record, with the motif's actual
+two demand widths. -/
+def Terms (mem : Memory w) : Prop :=
+ ∀ i : Fin M, let m := (order).symm i
+ TermRecordScan.Fields F supplyRoles demandMass_pos (P.shrinkDemandWidths cd old m)
+ (choice m).val (Fin.ofNat _ (T.termStart i)) mem
+
+/-- The surviving width of a particular dense motif and supply role for the stored term choice
+and selected layout. -/
+noncomputable def selected (i : Id M) : ℕ := P.termWidths F cd old choice ((order).symm i.1) T.layout i.2
+
+private theorem term_val (fit : T.Fits) (i : Fin M) :
+ (Fin.ofNat (2^w) (T.termStart i)).val = T.termStart i := (T.row_vals fit (i,0)).1
+
+/-- A surviving-row write preserves every admitted term in the dense directory. -/
+theorem keep_terms (fit : T.Fits) (i : Id M) (m out : Memory w)
+ (ht : Terms P cd site T F old choice m) (frame : ∀ x, (T.row i).Outside x → out x = m x) :
+ Terms P cd site T F old choice out := by
+ intro j
+ let base := Fin.ofNat (2^w) (T.termStart j)
+ have hv : base.val = T.termStart j := term_val T fit j
+ have keep (x : ℕ) (hx : x < base.val+10) : out x = m x := frame x (T.termOutside fit i j _ (hv ▸ hx))
+ obtain ⟨g,u,v⟩ := ht j
+ exact ⟨(keep base.val (by omega)) ▸ g,(keep (base.val+1) (by omega)) ▸ u,
+ fun k => (keep (base.val+2+k.val) (by have := k.isLt; omega)) ▸ v k⟩
+
+private theorem key_val (i : Id M) :
+ (T.absoluteKey i).val = (T.absolute i.1).val*4+i.2.val := by
+ change i.2.val + 4*(T.absolute i.1).val = _
+ omega
+
+private theorem row_worker (habs : T.absolute = absolute P cd site vertices tags lanes)
+ (fit : T.Fits) (selector : T.selectors.val = F.selectorBits)
+ (cap : ∀ m, outerCap F (P.shrinkDemandWidths cd old m) < 2^w)
+ (bound : ∀ i, selected P cd site T F old choice i < 2^w)
+ (i : Id M) (mem : Memory w) (ht : Terms P cd site T F old choice mem) :
+ ∃ out rs, Run (T.row i) (selected P cd site T F old choice i) mem out rs := by
+ let m := (order).symm i.1
+ let r := T.row i
+ let width := selected P cd site T F old choice i
+ obtain ⟨hterm,_,_,hd,hc⟩ := T.row_vals fit i
+ have eqw : survivingRowBase P vertices tags lanes T.widthBase T.subdiv m i.2 = T.widthStart i := by
+ simp only [survivingRowBase,widthStart,key_val,habs,absolute,stride,m]
+ rfl
+ have hhead : (Fin.ofNat (2^w) (survivingRowBase P vertices tags lanes T.widthBase T.subdiv m i.2)) = r.dst :=
+ Fin.ext (by rw [eqw,← hd]; exact Nat.mod_eq_of_lt r.dst.isLt)
+ have hsub : (Fin.ofNat (2^w) (T.subdiv i.2)) = r.count := Fin.ext (by rw [← hc]; exact Nat.mod_eq_of_lt r.count.isLt)
+ have hsel : (Fin.ofNat (2^w) F.selectorBits) = T.selectors := Fin.ext (by rw [← selector]; exact Nat.mod_eq_of_lt T.selectors.isLt)
+ have htermFit : r.term.val+2+8 < 2^w := by
+ have ht := T.term_stop fit i.1
+ have h₁ : T.widthBase ≤ T.widthEnd := Nat.le_add_right ..
+ have h₂ : T.widthEnd ≤ T.last := Nat.le_add_right ..
+ have hf := fit.room
+ rw [hterm]; omega
+ have space : Workspace r.total r.dst r.bank 1 (T.subdiv i.2) := hc ▸ (T.space fit i)
+ have sep := T.apart fit i
+ rw [hd,hc,← eqw] at sep
+ have stages := surviving_build P vertices tags lanes F cd old choice T.subdiv m T.layout i.2 mem
+ r.term r.total r.bank T.widthBase htermFit (cap m) (ht i.1)
+ (selector ▸ T.selectors.isLt) (bound i) (fit.positive i.2) (hc ▸ r.count.isLt)
+ ((eqw.trans hd.symm) ▸ r.dst.isLt) (hhead ▸ space) sep
+ dsimp only at stages
+ rw [hhead,hsub,hsel] at stages
+ obtain ⟨exec,htotal,s,ds,hs,hdsc,_⟩ := stages
+ let call := supplyReport r.supply r.term mem
+ let mid := after mem call.events
+ let post := after mid (eventLog s)
+ have eqn : List.ofFn (splitWidth width (T.subdiv i.2)) = List.ofFn (splitWidth width r.count.val) :=
+ congrArg (fun q => List.ofFn (splitWidth width q)) hc.symm
+ refine ⟨ds.result post,call :: (s++ds.all),⟨s,ds,exec,htotal,hs,?_,rfl,rfl⟩⟩
+ exact eqn ▸ hdsc
+
+/-- The linear dense order has one visit per surviving role, with the role
+type varying fastest. -/
+def schedule (n : ℕ) : List (Id n) := List.ofFn (fun i : Fin (n*4) => finProdFinEquiv.symm i)
+
+/-- Construct all the chosen width rows and both directories on each row in
+one shared memory. The count bound depends only on the fixed subdivisions. -/
+theorem graph_run (habs : T.absolute = absolute P cd site vertices tags lanes)
+ (fit : T.Fits) (selector : T.selectors.val = F.selectorBits)
+ (cap : ∀ m, outerCap F (P.shrinkDemandWidths cd old m) < 2^w)
+ (bound : ∀ i, selected P cd site T F old choice i < 2^w)
+ (mem : Memory w) (input : Terms P cd site T F old choice mem) :
+ ∃ out reports, Runs T.row (selected P cd site T F old choice) (schedule M) mem out reports ∧
+ Terms P cd site T F old choice out ∧
+ (∀ i, Image (T.row i) (selected P cd site T F old choice i) out) ∧
+ (∀ (m : P.Motif) (t : Fin 4) (j : Fin (T.subdiv t)),
+ (out (T.widthBase+((arc m.val).val*4+t.val)*T.stride+j.val)).val =
+ splitWidth (P.termWidths F cd old choice m T.layout t) (T.subdiv t) j) ∧
+ reports.length ≤ (M*4)*(5+5*T.stride) ∧
+ (reports.map Report.probes).sum ≤ (M*4)*(10+21*T.stride) ∧
+ (reports.map fun r => r.events.length+1).sum ≤ (M*4)*(54+112*T.stride) := by
+ have nd : (schedule M).Nodup := List.nodup_ofFn_ofInjective finProdFinEquiv.symm.injective
+ obtain ⟨out,rs,run,keep,all⟩ := scan (Terms P cd site T F old choice) (T.space fit) (T.apart fit)
+ (T.separate fit) (keep_terms P cd site T F old choice fit)
+ (row_worker P cd site vertices tags lanes T F old choice habs fit selector cap bound)
+ (schedule M) mem input nd
+ have images (i : Id M) := all i (List.mem_ofFn.mpr ⟨finProdFinEquiv i,finProdFinEquiv.symm_apply_apply _⟩)
+ have hsub (t : Fin 4) : T.subdiv t ≤ T.stride :=
+ Finset.single_le_sum (fun j _ => Nat.zero_le (T.subdiv j)) (Finset.mem_univ t)
+ have cost := run.cost (Q := T.stride) (fun i _ => (T.row_vals fit i).2.2.2.2 ▸ hsub i.2)
+ refine ⟨out,rs,run,keep,images,?_,by simpa only [schedule,List.length_ofFn] using cost⟩
+ intro m t j
+ let i : Id M := (order m,t)
+ obtain ⟨_,_,_,hd,hc⟩ := T.row_vals fit i
+ have hpos : j.val < (T.row i).count.val := lt_of_lt_of_eq j.isLt hc.symm
+ have hrow := (images i).widths ⟨j.val,hpos⟩
+ change (out ((T.row i).dst.val+j.val)).val =
+ splitWidth (selected P cd site T F old choice i) (T.row i).count.val ⟨j.val,hpos⟩ at hrow
+ rw [hd,widthStart,key_val,habs] at hrow
+ simpa only [i,absolute,Function.Embedding.coeFn_mk,Equiv.symm_apply_apply,selected,splitWidth,hc] using hrow
+
+end CompressorRecords.ShrinkSliceSweep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotBoundary.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotBoundary.lean
new file mode 100644
index 0000000000..fc03f1ada2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotBoundary.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotFixedOperands
+import OAI.Computability.VPVNP.CompressorWindowPrepared
+
+/-! # Control and header addresses protected during a shrinking slot window -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BurstRAM BlockPlanner DescriptorSpace Schedule
+open scoped Fin.CommRing
+
+variable {w : ℕ} (A : Script) (L : DescriptorSpace.Layout) (base : Word w)
+local notation "pt" => Workspace.ports (Schedule.arity A.catalog) base
+local notation "H" => levelStart L 0
+local notation "pitchCell" => Fin.val (Schedule.Ports.directory pt-1)
+
+/-- Numeric layout evidence for a single repeated shrinking block. The
+two headers and the selected score cell are read by the actual planners. -/
+structure Boundary (t step role slotStart slotEnd copyStart score : ℕ) : Prop where
+ arity : Schedule.arity A.catalog = L.shape.arity
+ baseValue : base.val = L.base
+ fits : H < 2^w
+ blockRoom : A.initial.length+(t+1)*A.block.length ≤ directoryRows L
+ rowsBefore : (pt).rows.val < H
+ pitchBefore : pitchCell < H
+ roleHigh : H ≤ role
+ roleBefore : role ≤ slotStart
+ oldBefore : levelStart L (A.levelsPerBlock*t+step)+66 ≤ slotStart
+ slotBefore : slotEnd ≤ levelStart L (A.levelsPerBlock*t+(step+1))
+ headerBefore : levelStart L (A.levelsPerBlock*t+(step+1))+66 ≤ copyStart
+ scoreHigh : H ≤ score
+ scoreBefore : score < slotStart
+ oldFits : levelStart L (A.levelsPerBlock*t+step)+66 ≤ 2^w
+ nextFits : levelStart L (A.levelsPerBlock*t+(step+1))+66 ≤ 2^w
+
+variable {A L base} {t step role slotStart slotEnd copyStart score : ℕ}
+variable (bound : Boundary A L base t step role slotStart slotEnd copyStart score)
+local notation "old" => levelStart L (A.levelsPerBlock*t+step)
+local notation "new" => levelStart L (A.levelsPerBlock*t+(step+1))
+local notation "roots" => RootCell pitchCell old new score
+
+include bound in
+/-- Actual slot writes and canonical copies preserve every planner root
+and the row-total cell. -/
+theorem Boundary.untouched {x count : ℕ} (live : slotStart ≤ slotEnd)
+ (written : (slotStart ≤ x ∧ x < slotEnd) ∨ (copyStart ≤ x ∧ x < copyStart+count)) :
+ ¬ (roots x ∨ x=(pt).rows.val) := by
+ have h₀ := bound.roleHigh
+ have h₁ := bound.roleBefore
+ have h₂ := bound.oldBefore
+ have h₃ := bound.slotBefore
+ have h₄ := bound.headerBefore
+ have h₅ := bound.scoreBefore
+ have hp := bound.pitchBefore
+ have hr := bound.rowsBefore
+ rintro ((p|o|n|s)|r) <;> omega
+
+end CompressorRecords.ShrinkSlotCalendar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotFixedOperands.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotFixedOperands.lean
new file mode 100644
index 0000000000..0978f8fcfa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotFixedOperands.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotOperandFootprint
+import OAI.Computability.VPVNP.CompressorShrinkSlotWindow
+
+/-!
+# Physical read addresses of the shrinking slot planners
+
+The fixed block computes its slot operands from the pitch word, the two
+level headers and the stored layout bit. The arithmetic locating that bit
+includes the two greedy directories, the ranked bundles and the motif terms.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BurstRAM Compression DescriptorSpace PhaseRecipe ShrinkSlotPlan.Scheduled
+open scoped Fin.CommRing
+
+/-- The physical inputs of the slot planners at a shrinking substep. The
+fixed level header consists of 54 scalars, six incidence pointers and six
+table pointers. -/
+def RootCell (pitch old next score x : ℕ) : Prop :=
+ x = pitch ∨ (old ≤ x ∧ x < old+66) ∨ (next ≤ x ∧ x < next+66) ∨ x = score
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+ {w : ℕ} {L : DescriptorSpace.Layout} {first : ℕ} {pub : Fin 5 → Word w} {state : Word w}
+ {m : Memory w}
+
+/-- Every external load in the inputs of the actual 22-stage program uses
+one of the two headers, the pitch word or the selected layout cell. -/
+theorem plan_roots (entry : LevelFields.Entry L first pub state m)
+ (oldFit : levelStart L (first+i.val)+66 ≤ 2^w)
+ (nextFit : levelStart L (first+(i.val+1))+66 ≤ 2^w) :
+ Roots (plan B i) (RootCell (pub 1-1).val (levelStart L (first+i.val))
+ (levelStart L (first+(i.val+1))) ((SelectedPlan.layoutCell (selected B i)).eval pub state m).val)
+ pub state m := by
+ let data := RootCell (pub 1-1).val (levelStart L (first+i.val)) (levelStart L (first+(i.val+1)))
+ ((SelectedPlan.layoutCell (selected B i)).eval pub state m).val
+ let R := Expr.ReadsFrom data pub state m
+ have pitch : R LevelFields.stride := ⟨⟨trivial,trivial⟩,Or.inl rfl⟩
+ have addr (j offset : ℕ) : R (LevelFields.address j offset) := ⟨⟨trivial,trivial,pitch⟩,trivial⟩
+ have old (offset : ℕ) (ho : offset < 66) : R (LevelFields.scalar i.val offset) := by
+ refine ⟨addr _ _,?_⟩
+ rw [LevelFields.eval_address entry,Fin.val_natCast,Nat.mod_eq_of_lt (by omega)]
+ exact Or.inr (Or.inl ⟨Nat.le_add_right ..,by omega⟩)
+ have next (offset : ℕ) (ho : offset < 66) : R (LevelFields.scalar (i.val+1) offset) := by
+ refine ⟨addr _ _,?_⟩
+ rw [LevelFields.eval_address entry,Fin.val_natCast,Nat.mod_eq_of_lt (by omega)]
+ exact Or.inr (Or.inr (Or.inl ⟨Nat.le_add_right ..,by omega⟩))
+ have vertices := old 0 (by decide)
+ have degree := old 1 (by decide)
+ have lanes := old 2 (by decide)
+ have residual := old 3 (by decide)
+ have originRead : R (origin B i) := old 60 (by decide)
+ have split : R (BlockProgram.arena B i.val 2) := old 62 (by decide)
+ have role : R (BlockProgram.arena B i.val 3) := old 63 (by decide)
+ have sites : R (LevelFields.sites i.val) := ⟨vertices,lanes⟩
+ have slots : R (LevelFields.slots i.val) := ⟨sites,degree⟩
+ have newSites : R (ShrinkBlockInputs.newSites i) := ⟨vertices,trivial,residual⟩
+ let a := ShrinkBlockInputs.a i
+ let org := origin B i
+ have offset : R (GreedyLevelPlan.offsetBase i.val a org) :=
+ ⟨⟨originRead,vertices⟩,vertices,trivial⟩
+ have shift : R (GreedyLevelPlan.shiftBase i.val a org) :=
+ ⟨⟨offset,vertices⟩,vertices,trivial⟩
+ have greedy : R (GreedyLevelPlan.greedyStop i.val a org) := ⟨⟨shift,vertices,degree⟩,trivial⟩
+ have bundles : R (ShrinkBundlePlan.bundles i.val a) := ⟨newSites,degree⟩
+ have owner : R (ShrinkBundlePlan.owner i.val a org) := ⟨greedy,trivial,sites⟩
+ have counts : R (ShrinkBundlePlan.counts i.val a org) := ⟨owner,trivial,slots⟩
+ have buckets : R (ShrinkBundlePlan.bucketCount i.val a) := ⟨trivial,bundles⟩
+ have ids : R (ShrinkBundlePlan.ids i.val a org) := ⟨counts,buckets⟩
+ have rectangle : R (ShrinkBundlePlan.rectangle i.val a) := ⟨buckets,trivial⟩
+ have sorted : R (ShrinkBundlePlan.sorted i.val a org) := ⟨⟨⟨ids,rectangle⟩,rectangle⟩,slots⟩
+ have block : R (ShrinkBundlePlan.blockSize i.val a) := ⟨bundles,trivial⟩
+ have ab : R (ShrinkBundlePlan.abStart i.val a org) :=
+ ⟨⟨⟨sorted,trivial,block⟩,trivial,block⟩,buckets⟩
+ have motifs : R (selected B i).motifs := ⟨bundles,trivial⟩
+ have term : R (selected B i).termBase := ⟨⟨ab,trivial,motifs⟩,trivial,motifs⟩
+ have score : R (SelectedPlan.scoreBase (selected B i)) := ⟨term,motifs,trivial⟩
+ have oldArc : R (plan B i).input.oldArc := ⟨⟨score,trivial⟩,trivial,sites⟩
+ have chosen : R (plan B i).layout := ⟨⟨score,trivial⟩,Or.inr (Or.inr (Or.inr rfl))⟩
+ have cyclic : R (plan B i).input.nextSite := ⟨role,trivial⟩
+ have subdiv : R (plan B i).input.subdivisions := ⟨cyclic,newSites⟩
+ refine ⟨vertices,residual,oldArc,role,subdiv,cyclic,⟨subdiv,trivial⟩,chosen,split,?_⟩
+ intro c
+ exact next (54+c.val) (by have := c.isLt; omega)
+
+end CompressorRecords.ShrinkSlotCalendar
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotFootprint.lean
new file mode 100644
index 0000000000..2ea159cb3c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotFootprint.lean
@@ -0,0 +1,178 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotScheduledRuns
+import OAI.Computability.VPVNP.CompressorLogAccess
+
+/-!
+# External accesses in the shrinking slot preparation and column copies
+
+Every preparation call has one external write and no reads. Each copy call
+reads one live source cell and writes the corresponding destination cell.
+The resulting bounds apply to every individual source segment of the
+twenty-two-visit program when the directory and output scans have their
+respective event bounds.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport
+open scoped Fin.CommRing
+open private addr_val from OAI.Computability.VPVNP.CompressorLogAccess
+
+variable {w : ℕ}
+
+namespace ShrinkSlots.Preparation
+
+open SlotLevel SlotOwners
+
+/-- All seven preparation phases access only their output cells. The stronger
+upper bound is the start of the sorted rows, immediately after the counters. -/
+theorem Reports.Native.footprint {r : Reports w} {s : Shape} {h : Heads} {layout : Bool} {m : Memory w}
+ (native : r.Native s h layout m) (roleRoom : h.role+8 ≤ h.nextSite)
+ (nextRoom : h.nextSite+sites s ≤ h.subdivisions) (subRoom : h.subdivisions+4 ≤ h.scratch)
+ (fit : rowsHead s h < 2^w) :
+ LogAccess (fun _ ↦ False) (fun x ↦ h.role ≤ x ∧ x < rowsHead s h) r.all := by
+ obtain ⟨hp,hr,hn,hc⟩ := native
+ let cnt := owners s+fields s
+ let clearHead := h.scratch+fields s
+ have endEq : rowsHead s h = clearHead+cnt := rfl
+ have low : h.scratch ≤ clearHead := Nat.le_add_right ..
+ have pub : LogAccess (fun _ ↦ False) (fun x ↦ h.role ≤ x ∧ x < rowsHead s h) (List.ofFn r.publish) := by
+ have same (i : Fin 4) := Option.some.inj ((hp i).symm.trans (publish_run h.subdivisions s.subdivisions
+ (after m (eventLog ((List.ofFn r.publish).take i.val))) i))
+ have one (i : Fin 4) : LogAccess (fun _ ↦ False) (fun x ↦ h.role ≤ x ∧ x < rowsHead s h) [r.publish i] := by
+ rw [(List.cons.inj (same i)).1]
+ change Reads _ (directEvents 3 2 _ _) ∧ Writes _ (directEvents 3 2 _ _)
+ apply direct_events
+ have ht := i.isLt
+ change h.role ≤ (h.subdivisions+i.val) % (2^w) ∧ (h.subdivisions+i.val) % (2^w) < rowsHead s h
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+ exact (((one 0).append (one 1)).append (one 2)).append (one 3)
+ have roles := direct_scan _ 26 23 1 h.role 8 (Aux.roleValue ((roleBank h layout w) 0))
+ (by omega) (Aux.role_native (roleBank h layout w)) _ _ hr
+ have cyclic := direct_scan _ 19 16 1 h.nextSite (sites s) (Aux.nextValue (cyclicBank s h w))
+ (by omega) (Aux.next_native (cyclicBank s h w)) _ _ hn
+ have clear := direct_scan _ 8 4 2 clearHead cnt (fun _ ↦ (0 : Word w)) (by omega)
+ (fun mem i ↦ SliceRAM.clearVisit_native (clearHead : Word w) i mem) _ _ hc
+ exact ((pub.append (roles.mono (fun _ hx ↦ hx) (fun _ hx ↦ by obtain ⟨_,_⟩ := hx; omega))).append
+ (cyclic.mono (fun _ hx ↦ hx) (fun _ hx ↦ by obtain ⟨_,_⟩ := hx; omega))).append
+ (clear.mono (fun _ hx ↦ hx) (fun _ hx ↦ by obtain ⟨_,_⟩ := hx; omega))
+
+end ShrinkSlots.Preparation
+
+namespace CopyIncidence
+
+open Compression
+
+/-- Natural half-open intervals of the six live columns. -/
+def ColumnCell {a l : ℕ} (Y : State a l) (T : IncidenceDirectory w) (x : ℕ) : Prop :=
+ ∃ c, (T.column c).val ≤ x ∧ x < (T.column c).val+rows Y c
+
+private def copyEvents (src dst i : Word w) (m : Memory w) : List (Event w) :=
+ [.tick,.tick,.tick,.tick,.tick,.read (src+i) (m (src+i).val),.tick,.tick,
+ .write (dst+i) (m (src+i).val),.tick,.tick]
+
+private theorem copy_events_native (src dst i : Word w) (m : Memory w) :
+ let M := (copyPass.table.instantiate w (copyPublic src dst)).program
+ execute M 12 (M.start i) m [] = some ⟨copyEvents src dst i m,some (i+1)⟩ := by
+ change execute ((template LiveAuxiliaryHeaders.copyWord 7).instantiate w (copyPublic src dst)).program
+ (1+LiveAuxiliaryHeaders.copyWord.length) ⟨_,i,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _
+ rw [execute_template,run_eq_trace]
+ simp (config := {decide := true}) [LiveAuxiliaryHeaders.copyWord,trace,Op.effect,Function.update,copyPublic,
+ copyEvents,BinaryOp.eval]
+
+private theorem column_val (base : Word w) (i : ℕ) (fit : base.val+i < 2^w) :
+ (base+(i : Word w)).val = base.val+i := by
+ have hb : (base.val : Word w) = base := Fin.ext (Nat.mod_eq_of_lt base.isLt)
+ simpa only [hb] using addr_val (w := w) base.val i fit
+
+/-- Every copied report reads the selected source column at its own ordinal
+and writes only the same ordinal in the corresponding destination column. -/
+theorem Runs.footprint {a l : ℕ} {Y : State a l} {T U : IncidenceDirectory w} {cs : List (Fin 6)}
+ {m : Memory w} {rs : List (Report w)} (run : Runs Y T U cs m rs)
+ (roomT : ∀ c, (T.column c).val+rows Y c ≤ 2^w) (roomU : ∀ c, (U.column c).val+rows Y c ≤ 2^w) :
+ LogAccess (ColumnCell Y T) (ColumnCell Y U) rs := by
+ induction run with
+ | nil => exact ⟨fun _ _ h ↦ (List.not_mem_nil h).elim,fun _ _ h ↦ (List.not_mem_nil h).elim⟩
+ | cons c hr _ ih =>
+ refine LogAccess.append ?_ ih
+ let src := T.column c
+ let dst := U.column c
+ let ev := fun m i ↦ copyEvents src dst i m
+ refine (StageFrame.scan _ 12 0 (rows Y c) (fun _ _ ↦ True) ev _ _
+ (fun _ _ _ m ↦ copy_events_native src dst _ m) ?_ (Nat.zero_le _) _ _
+ trivial (by simpa only [Nat.sub_zero,Nat.cast_zero] using hr)).2.2
+ intro j _ hj _ _
+ have addr (D : IncidenceDirectory w) (room : (D.column c).val+rows Y c ≤ 2^w) :
+ ColumnCell Y D (D.column c+(j : Word w)).val := by
+ refine ⟨c,?_⟩
+ rw [column_val _ _ (by omega)]
+ omega
+ refine ⟨trivial,?_,?_⟩
+ · intro x v hx; simp [ev,copyEvents] at hx
+ exact hx.1 ▸ addr T (roomT c)
+ · intro x v hx; simp [ev,copyEvents] at hx
+ exact hx.1 ▸ addr U (roomU c)
+
+end CopyIncidence
+
+/-- An aggregate event bound on a chronological walk also holds at each
+source stage in its own memory. -/
+theorem SourceWalk.refine_footprints {J : Type*} {src : J → Memory w → List (Report w) → Prop}
+ {stages : List J} {m : Memory w} {rs : List (Report w)} {rd wr : ℕ → Prop}
+ (walk : SourceWalk src stages m rs) (bounds : LogAccess rd wr rs) :
+ SourceWalk (fun j m rs ↦ src j m rs ∧ LogAccess rd wr rs) stages m rs := by
+ induction walk with
+ | done => exact .done _
+ | next head _ ih =>
+ simp only [LogAccess,eventLog,List.flatMap_append] at bounds
+ exact .next ⟨head,fun a v h ↦ bounds.1 a v (List.mem_append_left _ h),
+ fun a v h ↦ bounds.2 a v (List.mem_append_left _ h)⟩ (ih ⟨fun a v h ↦ bounds.1 a v (List.mem_append_right _ h),
+ fun a v h ↦ bounds.2 a v (List.mem_append_right _ h)⟩)
+
+namespace ShrinkSlotPlan.Scheduled
+
+open ShrinkSlots SlotLevel Compression
+
+/-- Combine the concrete preparation and copy accesses with the five directory
+and four output scans. Each of the twenty-two stages retains its own source
+execution and bounds on its own read and write events. -/
+theorem sources_with_footprints {a l : ℕ} (P : Plan) (s : Shape) (h : Heads) (chosen : Bool)
+ (splitHead : ℕ) (dest : IncidenceDirectory w) (Y : State a l)
+ (r : Build.Construction w) (m : Memory w) (hr : r.Native s h splitHead chosen m)
+ (lengths : ∀ c, CopyIncidence.rows Y c = (Stage.copy c).limit s)
+ (roleRoom : h.role+8 ≤ h.nextSite) (nextRoom : h.nextSite+sites s ≤ h.subdivisions)
+ (subRoom : h.subdivisions+4 ≤ h.scratch) (fit : rowsHead s h < 2^w)
+ (roomT : ∀ c, ((directory s h w).column c).val+CopyIncidence.rows Y c ≤ 2^w)
+ (roomU : ∀ c, (dest.column c).val+CopyIncidence.rows Y c ≤ 2^w)
+ (rd wr : ℕ → Prop)
+ (prepRegion : ∀ x, h.role ≤ x → x < rowsHead s h → wr x)
+ (sourcesRead : ∀ x, CopyIncidence.ColumnCell Y (directory s h w) x → rd x)
+ (destWrite : ∀ x, CopyIncidence.ColumnCell Y dest x → wr x)
+ (core : LogAccess rd wr r.passes.slots.all)
+ (out : LogAccess rd wr (r.passes.mates.all++r.passes.widths)) :
+ let built := after m (eventLog r.all)
+ let copies := CopyIncidence.reports Y (directory s h w) dest CopyIncidence.allColumns built
+ SourceWalk (fun j m rs ↦ Source P s h chosen splitHead dest j m rs ∧ LogAccess rd wr rs)
+ order m (r.all++copies) := by
+ intro built copies
+ have prep := hr.1.footprint roleRoom nextRoom subRoom fit
+ have copied := CopyIncidence.reports_run Y (directory s h w) dest CopyIncidence.allColumns built
+ have copy := copied.footprint roomT roomU
+ have pass : LogAccess rd wr r.passes.all := by
+ simpa only [Build.Passes.all,List.append_assoc] using core.append out
+ exact ((construction_sources P s h chosen splitHead dest r m hr).append
+ (copy_sources P s h chosen splitHead dest Y lengths copied)).refine_footprints
+ (((prep.mono (fun _ ↦ False.elim) (fun x hx ↦ prepRegion x hx.1 hx.2)).append pass).append
+ (copy.mono sourcesRead destWrite))
+
+end ShrinkSlotPlan.Scheduled
+
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotFrame.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotFrame.lean
new file mode 100644
index 0000000000..3fca47023f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotFrame.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.CompressorShrinkBlockInputs
+import OAI.Computability.VPVNP.CompressorShrinkOutputAllocation
+
+/-!
+# Reading the fixed shrinking block's live slot operands
+
+The cyclic successor table follows the eight role words. The four
+subdivision words follow the cyclic table. These expressions agree with the
+allocation supplied to the native preparation and ordered-slot workers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkBlockInputs
+
+open BurstRAM PhaseRecipe Compression SlotLevel ShrinkSlots
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+variable (F : DescriptorSpace.Shape) (i : Fin S.steps)
+variable {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g))
+variable (origin slotArena : Expr) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w)
+
+local notation "ev" => Expr.eval pub state m
+local notation "s" => levelShape (b := b i) X
+
+/-- Every compiled slot head agrees with the native head used on the current selected branch. -/
+theorem slotInputs_reads (role start : ℕ)
+ (bases : ev (LevelFields.vertices i.val) = (Fintype.card X.Base : Word w))
+ (lanes : ev (LevelFields.residualLanes i.val) = (2^g : ℕ))
+ (oldArc : ev (SelectedPlan.roleBase (selectedInputs B F i origin)) = (role : Word w))
+ (arena : ev slotArena = (start : Word w)) :
+ SlotLevel.Recipe.Reads (slotInputs B F i origin slotArena) pub state m (Fintype.card X.Base) (2^g)
+ (ShrinkOutput.heads s role start) := by
+ have count : ev (newSites i) = (sites s : Word w) := by
+ change ev (LevelFields.vertices i.val) * ((2^(Shrink.J (a i)) : ℕ) * ev (LevelFields.residualLanes i.val)) = _
+ rw [bases,lanes,← Nat.cast_mul,← Nat.cast_mul]; rfl
+ have cyclic : ev (slotArena.add (.lit 8)) = ((start+8 : ℕ) : Word w) := by
+ change ev slotArena+8 = _; rw [arena,Nat.cast_add]; rfl
+ have subdiv : ev ((slotArena.add (.lit 8)).add (newSites i)) = ((start+8+sites s : ℕ) : Word w) := by
+ change ev (slotArena.add (.lit 8)) + ev (newSites i) = _
+ rw [cyclic,count,← Nat.cast_add]
+ refine ⟨bases,lanes,oldArc,arena,subdiv,cyclic,?_⟩
+ change ev ((slotArena.add (.lit 8)).add (newSites i)) + 4 = ((start+8+sites s+4 : ℕ) : Word w)
+ rw [subdiv]
+ exact (Nat.cast_add (start+8+sites s) 4).symm
+
+/-- These are the two persistent addresses published for subsequent endpoint lookup. -/
+theorem endpoint_heads (role start : ℕ)
+ (read : SlotLevel.Recipe.Reads (slotInputs B F i origin slotArena) pub state m (Fintype.card X.Base) (2^g)
+ (ShrinkOutput.heads s role start)) :
+ let counts := SlotLevel.Recipe.counts (slotTemplate i) (slotInputs B F i origin slotArena)
+ ev counts.rows = (rowsHead s (ShrinkOutput.heads s role start) : Word w) ∧
+ ev counts.inverse = (inverseHead s (ShrinkOutput.heads s role start) : Word w) := by
+ intro c
+ have eq := SlotLevel.Recipe.eval_counts (slotTemplate i) (slotInputs B F i origin slotArena) read
+ exact ⟨congrArg SlotLevel.Recipe.Counts.rows eq,congrArg SlotLevel.Recipe.Counts.inverse eq⟩
+
+end CompressorRecords.ShrinkBlockInputs
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotGroupFrame.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotGroupFrame.lean
new file mode 100644
index 0000000000..5ee270fe7b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotGroupFrame.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotPacketGroup
+import OAI.Computability.VPVNP.CompressorShrinkSlotWindow
+import OAI.Computability.VPVNP.CompressorShrinkOutputAccess
+
+/-! # Memory outside the installed shrinking slot group
+
+The selected construction writes in its slot workspace, then copies six
+incidence columns to the next level. The same frame holds for the global
+packet list whenever its concatenated worker reports are those two runs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BurstRAM BlockPlanner DescriptorSpace SourceTransport Compression ShrinkSlots SlotLevel
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g))
+variable (sel : X.ShrinkSelection B.shrink) (term : Word w) (stride role retained slotStart : ℕ)
+variable (L : Layout) (level : Fin L.levels)
+local notation "sh" => levelShape (b := ShrinkBlockInputs.b i) X
+local notation "heads" => ShrinkOutput.heads sh role slotStart
+local notation "slotEnd" => finish sh heads
+local notation "count" => actualCount sh
+local notation "copyBase" => incidenceStart L level
+
+/-- Every cell outside both physical write intervals retains its value from
+the input memory of the slot group. -/
+theorem packet_group_frame_of_space {initial raw : Memory w} {r : Build.Construction w}
+ (c : ShrinkOutput.Constructed X B.shrink (S.shrink i) sel term stride role retained initial raw r slotStart)
+ (sp : Build.Space sh heads (ShrinkOutput.widthBase X term.val stride role retained) w)
+ (room : endAddress L < 2^w) (capacity : count ≤ slotCapacity L)
+ (apart : slotEnd ≤ copyBase ∨ copyBase+6*count ≤ targetsHead sh heads)
+ (ps : List (SourceOnline.Packet (BlockProgram.script B) w)) :
+ let Y := X.shrinkNext B.shrink (S.shrink i) sel
+ let copies := CopyIncidence.reports Y (directory sh heads w) (packedIncidence L w level count)
+ CopyIncidence.allColumns (after raw (eventLog r.all))
+ ps.flatMap SourceWalk.Packet.reports = r.all++copies →
+ ∀ x, (x < slotStart ∨ slotEnd ≤ x) → (x < copyBase ∨ copyBase+6*count ≤ x) →
+ SourceOnline.post raw ps x = raw x := by
+ intro Y copies reports x outsideSlot outsideCopy
+ have walk := (c.sources_of_space X B.shrink (S.shrink i) sel term stride role retained slotStart sp
+ (plan B i) L level room capacity apart).1
+ rw [SourceOnline.post,reports]
+ apply (walk.with_invariant (I := fun m ↦ m x = raw x) rfl ?_).2
+ intro j mem logs hs input
+ refine (after_outside mem hs.2.2 ?_).trans input
+ rintro (slot | copy) <;> omega
+
+/-- Specialization to the separate allocation certified by the selected width sweep. -/
+theorem packet_group_frame {initial raw : Memory w} {r : Build.Construction w}
+ (c : ShrinkOutput.Constructed X B.shrink (S.shrink i) sel term stride role retained initial raw r slotStart)
+ (hw : ShrinkOutput.FitsWords (b := ShrinkBlockInputs.b i) X B.shrink term stride role retained)
+ (gap : (ShrinkOutput.slotHeads (b := ShrinkBlockInputs.b i) X term.val stride role retained).role ≤ slotStart)
+ (endFit : slotEnd < 2^w) (room : endAddress L < 2^w) (capacity : count ≤ slotCapacity L)
+ (apart : slotEnd ≤ copyBase ∨ copyBase+6*count ≤ targetsHead sh heads)
+ (ps : List (SourceOnline.Packet (BlockProgram.script B) w)) :
+ let Y := X.shrinkNext B.shrink (S.shrink i) sel
+ let copies := CopyIncidence.reports Y (directory sh heads w) (packedIncidence L w level count)
+ CopyIncidence.allColumns (after raw (eventLog r.all))
+ ps.flatMap SourceWalk.Packet.reports = r.all++copies →
+ ∀ x, (x < slotStart ∨ slotEnd ≤ x) → (x < copyBase ∨ copyBase+6*count ≤ x) →
+ SourceOnline.post raw ps x = raw x :=
+ packet_group_frame_of_space B i X sel term stride role retained slotStart L level c
+ (hw.slot_space_at X B.shrink term stride role retained slotStart gap endFit) room capacity apart ps
+
+end CompressorRecords.ShrinkSlotCalendar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotGroupIndices.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotGroupIndices.lean
new file mode 100644
index 0000000000..88b09c721b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotGroupIndices.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotPackets
+import OAI.Computability.VPVNP.CompressorShrinkSlotWindow
+import OAI.Computability.VPVNP.CompressorBlockGroups
+import OAI.Computability.VPVNP.CompressorWindowPackets
+
+/-! # Calendar indices of the 22 selected shrinking slot passes -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BurstRAM BlockPlanner Compression ShrinkSlotPlan.Scheduled
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+local notation "W" => window B i
+local notation "groupW" => BlockGroups.shrink B i 8
+
+theorem part_eight_before : (W).before.length = (groupW).before.length := by
+ rw [BlockGroups.shrink_offset, show (8 : Fin 12).val = 8 from rfl]
+ simp only [window,List.length_append,BlockGroups.parts,ShrinkBlockInputs.beforeSlices,
+ BlockSlices.visits,space,origin,selected,List.take_succ_cons,List.take_zero,
+ List.flatten_cons,List.flatten_nil,List.length_nil,Nat.add_zero]
+ omega
+
+/-- Embedding the repeated slot workers in the full block yields precisely
+the eighth shrinking part's ordered catalog indices. -/
+theorem part_eight_indices {w : ℕ} (s : SlotLevel.Shape) (h : SlotLevel.Heads)
+ (side : Bool) (width : ℕ) (dest : IncidenceDirectory w) :
+ (List.ofFn (ShrinkSlotPackets.packetVisit (plan B i) W s h side width dest)).map
+ (fun v => v.phase) = (groupW).indices := by
+ rw [List.map_ofFn,Window.indices]
+ have len : order.length = ((BlockGroups.parts B i)[8]'(by rw [BlockGroups.parts_length]; decide)).length := by
+ change order.length = (ShrinkBlockInputs.slots B (space B) i (origin B i)
+ (BlockProgram.arena B i.val 3) (BlockProgram.arena B i.val 2)).length
+ rw [ShrinkBlockInputs.slots_length]
+ rfl
+ rw [List.ofFn_congr len]
+ congr 1
+ funext n
+ apply Fin.ext
+ change (BlockProgram.script B).initial.length+((W).before.length+n.val) =
+ (BlockProgram.script B).initial.length+((groupW).before.length+n.val)
+ rw [part_eight_before]
+
+end CompressorRecords.ShrinkSlotCalendar
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotLaunch.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotLaunch.lean
new file mode 100644
index 0000000000..2396ff6f4f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotLaunch.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotPackets
+import OAI.Computability.VPVNP.CompressorShrinkSlotOperandFootprint
+import OAI.Computability.VPVNP.CompressorWindowPrepared
+
+/-! # The runtime operand bank of a globally indexed shrinking slot visit -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlotPackets
+
+open BurstRAM BlockPlanner DescriptorSpace PhaseRecipe SourceTransport Schedule
+open SlotLevel ShrinkSlotPlan.Scheduled
+open scoped Fin.CommRing
+
+variable {A : Script} {w : ℕ} (P : Plan) (W : Window A (order.map (Stage.visit P)))
+variable {bases lanes : ℕ} {h : Heads} {chosen : Bool} {splitHead : ℕ} {dest : IncidenceDirectory w}
+variable {pub : Fin 5 → Word w} {state : Word w} {m : Memory w}
+
+/-- The live roots of a selected slot plan. The arithmetic for the 22
+different banks and limits is determined by these shared entry values. -/
+structure Values (P : Plan) (bases lanes : ℕ) (h : Heads) (chosen : Bool) (splitHead : ℕ)
+ (dest : IncidenceDirectory w) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) : Prop where
+ input : SlotLevel.Recipe.Reads P.input pub state m bases lanes h
+ layout : P.layout.eval pub state m = (chosen.toNat : Word w)
+ split : P.split.eval pub state m = (splitHead : Word w)
+ columns : ∀ c, (LevelFields.incidence P.space (P.step+1) c).eval pub state m = dest.column c
+
+theorem Values.transport {P : Plan} {data : ℕ → Prop} {m' : Memory w}
+ (v : Values P bases lanes h chosen splitHead dest pub state m)
+ (roots : Roots P data pub state m) (same : Agree data m m') :
+ Values P bases lanes h chosen splitHead dest pub state m' := by
+ have eq (e : Expr) (r : e.ReadsFrom data pub state m) : e.eval pub state m' = e.eval pub state m :=
+ (e.eval_eq_of_reads r same).symm
+ exact ⟨⟨(eq _ roots.bases).trans v.input.bases_eq,(eq _ roots.lanes).trans v.input.lanes_eq,
+ (eq _ roots.oldArc).trans v.input.oldArc_eq,(eq _ roots.role).trans v.input.role_eq,
+ (eq _ roots.subdivisions).trans v.input.subdivisions_eq,(eq _ roots.nextSite).trans v.input.nextSite_eq,
+ (eq _ roots.scratch).trans v.input.scratch_eq⟩,(eq _ roots.chosen).trans v.layout,
+ (eq _ roots.split).trans v.split,fun c ↦ (eq _ (roots.columns c)).trans (v.columns c)⟩
+
+private structure Frame (v : BlockPlanner.Visit) (data : ℕ → Prop) (pub : Fin 5 → Word w)
+ (state : Word w) (m : Memory w) (stop : Word w) (bank : Fin v.worker.params → Word w) : Prop where
+ initial : v.initial.eval pub state m = 0
+ limit : v.stop.eval pub state m = stop
+ param (i) : (v.params i).eval pub state m = bank i
+ initialReads : v.initial.ReadsFrom data pub state m
+ limitReads : v.stop.ReadsFrom data pub state m
+ paramReads (i) : (v.params i).ReadsFrom data pub state m
+
+private theorem Frame.cast {u v : BlockPlanner.Visit} (eq : u=v) {data : ℕ → Prop} {stop : Word w}
+ {bank : Fin v.worker.params → Word w} (frame : Frame v data pub state m stop bank) :
+ Frame u data pub state m stop (bank ∘ Fin.cast (congrArg (fun e : BlockPlanner.Visit ↦ e.worker.params) eq)) := by
+ subst v; exact frame
+
+private theorem local_frame (j : Stage) {data : ℕ → Prop}
+ (values : Values P bases lanes h chosen splitHead dest pub state m)
+ (roots : Roots P data pub state m) :
+ let s := P.template.shape bases lanes
+ let bank := j.bank s h chosen splitHead dest
+ Frame (j.visit P) data pub state m (j.limit s : Word w) (bank ∘ Fin.cast (j.params P)) := by
+ intro s bank
+ have words := j.words P values.input values.layout values.split values.columns (0 : Word w)
+ simp only [ShrinkSlotPlan.words,List.cons.injEq,true_and] at words
+ obtain ⟨first,limit,params⟩ := words
+ have pd := params.trans (List.ofFn_congr (j.params P).symm bank)
+ obtain ⟨ri,rs,rp⟩ := j.reads P roots
+ exact ⟨first,limit,fun i ↦ congrFun (List.ofFn_injective pd) i,ri,rs,rp⟩
+
+variable (L : DescriptorSpace.Layout) (base : Word w) (t : ℕ)
+local notation "pt" => Workspace.ports (arity A.catalog) base
+local notation "first" => (levelStart L (A.levelsPerBlock*t) : Word w)
+local notation "region" => Window.operandRegion A L base
+
+/-- The complete global recipe evaluates to this source visit's own bank.
+The global worker occurrence fixes both the return clock and the register arity. -/
+theorem evaluated (i : Fin order.length) (m : Memory w)
+ (values : Values P bases lanes h chosen splitHead dest (pt).data first m)
+ (roots : Roots P region (pt).data first m) :
+ let s := P.template.shape bases lanes
+ W.Evaluated L base (Fin.cast (List.length_map (f := Stage.visit P) (as := order)).symm i) t m (packetVisit P W s h chosen splitHead dest i) := by
+ intro s
+ let j := order[i.val]
+ have f := (local_frame P j values roots).cast (index_visit P W i)
+ exact ⟨rfl,f.initial,f.limit,f.param,f.initialReads,f.limitReads,f.paramReads⟩
+
+end CompressorRecords.ShrinkSlotPackets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotOnlineGroup.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotOnlineGroup.lean
new file mode 100644
index 0000000000..22293a6e99
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotOnlineGroup.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotBoundary
+import OAI.Computability.VPVNP.CompressorShrinkSlotLaunch
+import OAI.Computability.VPVNP.CompressorShrinkSlotPacketGroup
+import OAI.Computability.VPVNP.CompressorShrinkSlotOperandTransport
+import OAI.Computability.VPVNP.CompressorShrinkOutputAccess
+
+/-!
+# The selected shrinking slot group in the complete online script
+
+Starting with the score and header words in the source memory, each
+actual source visit preserves its planner's inputs. At that visit's
+global calendar ordinal the recipe evaluates to its native worker bank,
+including in every scheduler memory that agrees on the live data.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BurstRAM BlockPlanner DescriptorSpace PhaseRecipe SourceTransport Schedule Compression
+open ShrinkSlots SlotLevel ShrinkSlotPlan.Scheduled
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g))
+local notation "a₀" => ShrinkBlockInputs.a i
+local notation "b₀" => ShrinkBlockInputs.b i
+variable (sel : X.ShrinkSelection B.shrink)
+variable (term : Word w) (stride role retained slotStart : ℕ)
+local notation "s" => levelShape (b := b₀) X
+local notation "h" => ShrinkOutput.heads s role slotStart
+local notation "end₀" => finish s h
+local notation "width" => ShrinkOutput.widthBase X term.val stride role retained
+local notation "side" => selectedLayout X B.shrink sel
+local notation "A" => BlockProgram.script B
+local notation "P" => plan B i
+local notation "W" => window B i
+
+variable (L : DescriptorSpace.Layout) (base : Word w) (t : ℕ) (level : Fin L.levels)
+local notation "pt" => Workspace.ports (arity (Script.catalog A)) base
+local notation "first" => Script.levelsPerBlock A*t
+local notation "state" => (levelStart L first : Word w)
+local notation "pub" => Schedule.Ports.data pt
+local notation "H" => levelStart L 0
+local notation "dst" => packedIncidence L w level (actualCount s)
+local notation "copyBase" => incidenceStart L level
+local notation "pitchCell" => Fin.val (Schedule.Ports.directory pt-1)
+local notation "labels" => ShrinkSlotPackets.packetVisit P W s h side width dst
+
+set_option maxHeartbeats 1400000 in
+/-- The twenty-two global rows are checked and prepared at their exact
+ordinals. Their choices and report memories are those of the physical
+construction and its six canonical copies. -/
+theorem packet_group {initial raw : Memory w} {r : Build.Construction w}
+ (c : ShrinkOutput.Constructed X B.shrink (S.shrink i) sel term stride role retained initial raw r slotStart)
+ (sp : Build.Space s h width w) (room : endAddress L < 2^w) (capacity : actualCount s ≤ slotCapacity L)
+ (total : raw (pt).rows.val = (directoryRows L : Word w))
+ (pitch : raw pitchCell = (levelWords L : Word w))
+ (values : ShrinkSlotPackets.Values P (Fintype.card X.Base) (2^g) h side width dst pub state raw)
+ (bound : Boundary A L base t i.val role slotStart end₀ copyBase
+ ((SelectedPlan.layoutCell (selected B i)).eval pub state raw).val)
+ (cap : ℕ) (capFits : SourceOnline.scanCap A 49 ≤ cap) :
+ let Y := X.shrinkNext B.shrink (S.shrink i) sel
+ let copies := CopyIncidence.reports Y (directory s h w) dst CopyIncidence.allColumns (after raw (eventLog r.all))
+ let ordinal := (A).initial.length+t*(A).block.length+(W).before.length
+ ∃ ps : List (SourceOnline.Packet A w),
+ ps.map SourceWalk.Packet.stage = List.ofFn labels ∧ ps.flatMap SourceWalk.Packet.reports = r.all++copies ∧
+ SourceOnline.Group A L base cap ordinal (directoryRows L) raw ps ∧
+ (dst).Represents Y (SourceOnline.post raw ps) := by
+ intro Y copies ordinal
+ let score := ((SelectedPlan.layoutCell (selected B i)).eval pub state raw).val
+ let root := RootCell pitchCell (levelStart L (first+i.val)) (levelStart L (first+(i.val+1))) score
+ let stable := fun x ↦ root x ∨ x=(pt).rows.val
+ have entry : LevelFields.Entry L first pub state raw := ⟨rfl,pitch⟩
+ have roots : Roots P root pub state raw := plan_roots B i entry bound.oldFits bound.nextFits
+ have apart := bound.slotBefore.trans ((Nat.le_add_right _ 66).trans bound.headerBefore)
+ obtain ⟨walk,rep⟩ := c.sources_of_space X B.shrink (S.shrink i) sel term stride role retained slotStart sp P L level
+ room capacity (Or.inl apart)
+ have startLe : slotStart ≤ end₀ := by
+ simp only [finish,widthHead,inHead,outHead,inverseBaseHead,stopAddress,shiftsHead,targetsHead,inverseHead,
+ rowsHead,ShrinkOutput.heads]; omega
+ have live := (walk.with_invariant (I := fun mem ↦ Agree stable raw mem) (fun _ _ ↦ rfl) (by
+ intro j mem logs hs agree x hx
+ apply (agree x hx).trans
+ symm
+ apply after_outside mem hs.2.2
+ intro inside
+ exact bound.untouched startLe inside hx)).1
+ have cert (n : Fin order.length) (mem : Memory w) (logs : List (Report w))
+ (hs : Source P s h side width dst order[n.val] mem logs)
+ (access : LogAccess (fun x ↦ role≤x ∧ x Expr.ReadsFrom data pub state m
+local notation "cs" => SlotLevel.Recipe.counts P.template P.input
+local notation "os" => ShrinkSlots.Recipe.columns P.template P.input
+
+private structure CountReads (c : SlotLevel.Recipe.Counts Expr) (r : Expr → Prop) : Prop where
+ sites : r c.sites
+ pad : r c.pad
+ oldBaseArcs : r c.oldBaseArcs
+ genuineArcs : r c.genuineArcs
+ genuine : r c.genuine
+ dummy : r c.dummy
+ fields : r c.fields
+ owners : r c.owners
+ baseArcs : r c.baseArcs
+ rows : r c.rows
+ inverse : r c.inverse
+ targets : r c.targets
+ shifts : r c.shifts
+ stopAddress : r c.stopAddress
+
+private theorem count_reads (h : Roots P data pub state m) : CountReads cs R := by
+ have sites : R (cs).sites := ⟨h.bases,trivial,h.lanes⟩
+ have old : R (cs).oldBaseArcs := ⟨h.bases,trivial⟩
+ have gen : R (cs).genuineArcs := ⟨⟨trivial,old,trivial⟩,h.lanes⟩
+ have fields : R (cs).fields := ⟨⟨gen,sites,trivial⟩,trivial⟩
+ have owners : R (cs).owners := ⟨sites,trivial⟩
+ have arcs : R (cs).baseArcs := ⟨⟨h.bases,trivial⟩,trivial⟩
+ have rows : R (cs).rows := ⟨⟨h.scratch,fields⟩,owners,fields⟩
+ have inv : R (cs).inverse := ⟨rows,⟨owners,fields⟩,trivial⟩
+ have targets : R (cs).targets := ⟨inv,fields⟩
+ have shifts : R (cs).shifts := ⟨targets,arcs⟩
+ exact ⟨sites,trivial,old,gen,⟨gen,trivial⟩,⟨⟨sites,trivial⟩,trivial⟩,fields,owners,arcs,
+ rows,inv,targets,shifts,⟨shifts,arcs⟩⟩
+
+private structure ColumnReads (c : ShrinkSlots.Recipe.Columns) (r : Expr → Prop) : Prop where
+ count : r c.count
+ baseInverse : r c.baseInverse
+ actualOut : r c.actualOut
+ actualIn : r c.actualIn
+ width : r c.width
+
+private theorem column_reads (h : CountReads cs R) : ColumnReads os R := by
+ have count : R (os).count := ⟨h.sites,trivial⟩
+ have out : R (os).actualOut := ⟨h.stopAddress,h.baseArcs⟩
+ have incoming : R (os).actualIn := ⟨out,count⟩
+ exact ⟨count,h.stopAddress,out,incoming,⟨incoming,count⟩⟩
+
+private theorem core_reads (h : Roots P data pub state m) (c : CountReads cs R) (p : SlotLevel.Phase) :
+ let v := (.core p : Stage).visit P
+ R v.initial ∧ R v.stop ∧ ∀ j, R (v.params j) := by
+ intro v
+ cases p with
+ | genuineOwners =>
+ refine ⟨trivial,c.genuine,?_⟩
+ intro j; change Fin 8 at j; fin_cases j
+ exacts [h.lanes,trivial,c.oldBaseArcs,h.oldArc,h.role,h.subdivisions,c.owners,h.scratch]
+ | dummyOwners =>
+ refine ⟨trivial,c.dummy,?_⟩
+ intro j; change Fin 3 at j; fin_cases j
+ exacts [c.pad,h.nextSite,⟨h.scratch,c.genuine⟩]
+ | appendFields =>
+ refine ⟨trivial,c.fields,?_⟩
+ intro j; change Fin 6 at j; fin_cases j
+ exacts [c.fields,h.scratch,⟨c.owners,c.fields⟩,⟨h.scratch,c.fields⟩,trivial,c.rows]
+ | invertFields =>
+ refine ⟨trivial,⟨c.owners,trivial⟩,?_⟩
+ intro j; change Fin 2 at j; fin_cases j
+ exacts [c.rows,c.inverse]
+ | baseMatching =>
+ refine ⟨trivial,c.baseArcs,?_⟩
+ intro j; change Fin 6 at j; fin_cases j
+ exacts [trivial,h.lanes,c.rows,c.inverse,c.targets,c.shifts]
+
+private theorem output_reads (h : Roots P data pub state m) (c : CountReads cs R) (o : ColumnReads os R)
+ (p : ShrinkSlots.Recipe.Phase) : let v := (.output p : Stage).visit P
+ R v.initial ∧ R v.stop ∧ ∀ j, R (v.params j) := by
+ intro v
+ cases p with
+ | baseInverse =>
+ refine ⟨trivial,c.baseArcs,?_⟩
+ intro j; change Fin 2 at j; fin_cases j
+ exacts [c.targets,o.baseInverse]
+ | actualOut =>
+ refine ⟨trivial,o.count,?_⟩
+ intro j; change Fin 5 at j; fin_cases j
+ exacts [trivial,h.lanes,c.targets,c.shifts,o.actualOut]
+ | actualIn =>
+ refine ⟨trivial,o.count,?_⟩
+ intro j; change Fin 5 at j; fin_cases j
+ exacts [trivial,h.lanes,o.baseInverse,c.shifts,o.actualIn]
+ | widths =>
+ refine ⟨trivial,o.count,?_⟩
+ intro j; change Fin 8 at j; fin_cases j
+ exacts [trivial,h.lanes,trivial,c.oldBaseArcs,c.genuineArcs,c.rows,h.split,o.width]
+
+/-- Every expression in the active worker's chronological operand row reads
+only the supplied region. -/
+theorem Stage.reads (stage : Stage) (h : Roots P data pub state m) :
+ R (stage.visit P).initial ∧ R (stage.visit P).stop ∧ ∀ j, R ((stage.visit P).params j) := by
+ have c := count_reads P h
+ have o := column_reads P c
+ cases stage with
+ | subdivision i =>
+ refine ⟨trivial,trivial,?_⟩
+ intro j; change Fin 2 at j; fin_cases j
+ exacts [⟨h.subdivisions,trivial⟩,trivial]
+ | roles =>
+ refine ⟨trivial,trivial,?_⟩
+ intro j; change Fin 2 at j; fin_cases j
+ exacts [h.chosen,h.role]
+ | cyclic =>
+ refine ⟨trivial,c.sites,?_⟩
+ intro j; change Fin 3 at j; fin_cases j
+ exacts [h.lanes,trivial,h.nextSite]
+ | clear => exact ⟨trivial,⟨c.owners,c.fields⟩,fun _ ↦ ⟨h.scratch,c.fields⟩⟩
+ | core p => exact core_reads P h c p
+ | output p => exact output_reads P h c o p
+ | copy i =>
+ have num : R (columnCount P.template P.input i) := by
+ unfold columnCount; split
+ · exact c.baseArcs
+ · exact o.count
+ have src : R (sourceHeads P.template P.input i) := by
+ fin_cases i
+ exacts [c.targets,o.baseInverse,c.shifts,o.actualOut,o.actualIn,o.width]
+ refine ⟨trivial,num,?_⟩
+ intro j; change Fin 3 at j; fin_cases j
+ exacts [trivial,src,h.columns i]
+
+end CompressorRecords.ShrinkSlotPlan.Scheduled
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotOperandTransport.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotOperandTransport.lean
new file mode 100644
index 0000000000..78e93b9c8d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotOperandTransport.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotFixedOperands
+import OAI.Computability.VPVNP.CompressorWindowPrepared
+
+/-!
+# Replaying shrinking slot operands after earlier workers
+
+When memory agrees on the original roots, every load computes the same
+address. The structural footprint therefore holds in the next memory and
+may be widened to the scheduler's persistent operand region.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open BurstRAM PhaseRecipe SourceTransport
+
+variable {w : ℕ} {small data : ℕ → Prop} {pub : Fin 5 → Word w} {state : Word w} {m m' : Memory w}
+
+/-- A footprint is preserved when its input cells retain their contents,
+including for a load whose address is computed by a nested load. -/
+theorem PhaseRecipe.Expr.reads_transport (e : Expr) (reads : e.ReadsFrom small pub state m)
+ (same : Agree small m m') (widen : ∀ x, small x → data x) : e.ReadsFrom data pub state m' := by
+ induction e with
+ | lit | state | publicWord => trivial
+ | binary op a b ha hb => exact ⟨ha reads.1,hb reads.2⟩
+ | load a ha =>
+ refine ⟨ha reads.1,?_⟩
+ rw [← a.eval_eq_of_reads reads.1 same]
+ exact widen _ reads.2
+
+/-- The pitch belongs to the online operand region. Both header intervals
+lie in the data suffix, as does the chosen score cell when its address is
+at or above the first header. -/
+theorem ShrinkSlotCalendar.rootCell_operandRegion (A : BlockPlanner.Script) (L : DescriptorSpace.Layout)
+ (base : Word w) (old next score : ℕ) (scoreLow : DescriptorSpace.levelStart L 0 ≤ score) :
+ ∀ x, ShrinkSlotCalendar.RootCell ((Workspace.ports (Schedule.arity A.catalog) base).directory-1).val
+ (DescriptorSpace.levelStart L old) (DescriptorSpace.levelStart L next) score x →
+ BlockPlanner.Window.operandRegion A L base x := by
+ intro x hx
+ rcases hx with pitch | ⟨lo,_⟩ | ⟨lo,_⟩ | rfl
+ · exact Or.inr (Or.inl pitch)
+ · exact Or.inr (Or.inr ((DescriptorSpace.levelStart_mono L (Nat.zero_le old)).trans lo))
+ · exact Or.inr (Or.inr ((DescriptorSpace.levelStart_mono L (Nat.zero_le next)).trans lo))
+ · exact Or.inr (Or.inr scoreLow)
+
+namespace ShrinkSlotPlan.Scheduled
+
+theorem Roots.transport {P : Plan} (roots : Roots P small pub state m)
+ (same : Agree small m m') (widen : ∀ x, small x → data x) : Roots P data pub state m' := by
+ have keep (e : Expr) (read : e.ReadsFrom small pub state m) : e.ReadsFrom data pub state m' :=
+ e.reads_transport read same widen
+ exact ⟨keep _ roots.bases,keep _ roots.lanes,keep _ roots.oldArc,keep _ roots.role,
+ keep _ roots.subdivisions,keep _ roots.nextSite,keep _ roots.scratch,keep _ roots.chosen,
+ keep _ roots.split,fun c ↦ keep _ (roots.columns c)⟩
+
+/-- The evaluated worker bounds and bank agree between the original and
+current packet inputs on the same stage, even when the entry layouts differ elsewhere. -/
+theorem Stage.eval_transport (P : Plan) (stage : Stage) (roots : Roots P small pub state m)
+ (same : Agree small m m') :
+ let v := stage.visit P
+ v.initial.eval pub state m = v.initial.eval pub state m' ∧
+ v.stop.eval pub state m = v.stop.eval pub state m' ∧
+ ∀ j, (v.params j).eval pub state m = (v.params j).eval pub state m' := by
+ intro v
+ obtain ⟨hi,hs,hp⟩ := Stage.reads P stage roots
+ exact ⟨v.initial.eval_eq_of_reads hi same,v.stop.eval_eq_of_reads hs same,
+ fun j ↦ (v.params j).eval_eq_of_reads (hp j) same⟩
+
+end ShrinkSlotPlan.Scheduled
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotOrdinals.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotOrdinals.lean
new file mode 100644
index 0000000000..01605a055f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotOrdinals.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotScheduledRuns
+import OAI.Computability.VPVNP.CompressorRecordsOrdinalRun
+import OAI.Computability.VPVNP.CompressorSourceTransport
+import OAI.Computability.VPVNP.RAMChoicePrefix
+
+/-!
+# Guarded cursors of the shrinking slot program
+
+Each successful slot worker advances the dense ordinal by exactly one,
+including the guarded append into an owner's row. A run whose writes lie
+outside the active scheduler controls passes every dispatch guard when
+the initial row is ready and its exclusive stop fits the word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlotPlan.Scheduled
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Schedule
+open scoped Fin.CommRing
+
+variable {w d : ℕ}
+
+private theorem result_of_run {Q : Type*} {M : BurstRAM.Program w Q} {f : ℕ} {i : Word w}
+ {m : Memory w} {r : Report w} {es : List (Event w)}
+ (known : execute M f (M.start i) m [] = some ⟨es,some (i+1)⟩)
+ (run : execute M f (M.start i) m [] = some r) : r.result = some (i+1) :=
+ congrArg Report.result (Option.some.inj (run.symm.trans known))
+
+private theorem append_result (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (r : Report w) :
+ let M := (template collectPreimage 3).instantiate w p
+ execute M.program 23 (M.program.start i) m [] = some r → r.result = some (i+1) := by
+ intro M run
+ by_cases h : i < p 0 ∧ ownerAt p m i < p 2 ∧ m (countAt p (ownerAt p m i)).val < p 4
+ · exact result_of_run (collectPreimage_native p m i h.1 h.2.1 h.2.2) run
+ · change execute M.program (1+collectPreimage.length) ⟨M.entry,i,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ at run
+ rw [execute_template,run_eq_trace,collectPreimage_invalid p i _ m h] at run
+ contradiction
+
+/-- The cursor result comes from the actual instruction table. The assertion
+holds for arbitrary public words and memory whenever the reset call succeeds. -/
+theorem Stage.advance (P : Plan) (j : Stage) (data : Fin (j.visit P).worker.params → Word w)
+ (m : Memory w) (i : Word w) (r : Report w) :
+ let v := j.visit P
+ let M := (v.worker.table.instantiate w data).program
+ execute M (v.worker.pcs-1) (M.start i) m [] = some r → r.result = some (i+1) := by
+ cases j with
+ | subdivision t => exact result_of_run (BlockPlanner.publish_native
+ (P.input.subdivisions.add (.lit t.val)) (.lit (P.template.subdivisions t)) data i m).1
+ | roles => exact result_of_run (SlotOwners.Aux.role_native data m i)
+ | cyclic => exact result_of_run (SlotOwners.Aux.next_native data m i)
+ | clear =>
+ change Fin 1 → Word w at data
+ have hd : data = fun _ ↦ data 0 := funext fun x ↦ congrArg data (Subsingleton.elim x 0)
+ intro v M run
+ change execute ((template SliceRAM.clearOps 0).instantiate w data).program 8
+ (((template SliceRAM.clearOps 0).instantiate w data).program.start i) m [] = some r at run
+ rw [hd] at run
+ exact result_of_run (SliceRAM.clearVisit_native (data 0) i m) run
+ | core p =>
+ cases p with
+ | genuineOwners => exact result_of_run (SlotOwners.genuine_native data m i)
+ | dummyOwners => exact result_of_run (SlotOwners.dummy_native data m i)
+ | appendFields => exact append_result data m i r
+ | invertFields => exact result_of_run (SlotScatter.visit_native data m i)
+ | baseMatching => exact result_of_run (SlotBaseScan.native data m i)
+ | output p =>
+ cases p with
+ | baseInverse => exact result_of_run (SlotScatter.visit_native data m i)
+ | actualOut => exact result_of_run (SlotIncidencePass.native data false m i)
+ | actualIn => exact result_of_run (SlotIncidencePass.native data true m i)
+ | widths => exact result_of_run (SlotWidthScan.native data m i)
+ | copy c =>
+ obtain ⟨_,he,_⟩ := LiveAuxiliaryHeaders.copyWord_native data i m
+ exact result_of_run he
+
+/-- A guard proof may use the writes of the actual source log. The induction
+invariant keeps its remaining successful zero-tape suffix. Consequently only
+the real writes need to be disjoint from scheduler control cells. -/
+theorem Source.validTrace (P : Plan) (s : SlotLevel.Shape) (h : SlotLevel.Heads) (chosen : Bool)
+ (splitHead : ℕ) (dest : IncidenceDirectory w) (j : Stage) (m : Memory w) (rs : List (Report w))
+ (C : Catalog d) (idx : Fin d) (ports : Ports w) (worker : C idx = (j.visit P).worker) :
+ let data := j.bank s h chosen splitHead dest ∘ Fin.cast (j.params P)
+ let args := data ∘ Fin.cast (congrArg Pass.params worker)
+ let N := j.limit s
+ N < 2^w →
+ Ready C idx ports args (N : Word w) m →
+ Source P s h chosen splitHead dest j m rs →
+ SourceTransport.Writes (fun x ↦ ¬ OrdinalRun.ControlCell (C idx).params ports x) (eventLog rs) →
+ ValidTrace C idx ports args (N : Word w) 0 m rs ∧
+ OrdinalRun.Preserved (C idx).params ports m (after m (eventLog rs)) := by
+ intro data args N fit ready source outside
+ let v := j.visit P
+ let M := (v.worker.table.instantiate w data).program
+ let f := v.worker.pcs-1
+ let safe := fun x ↦ ¬ OrdinalRun.ControlCell (C idx).params ports x
+ let I := fun (k : ℕ) (mem : Memory w) ↦ ∃ tail, runSegment M f (some (k : Word w)) mem
+ (List.replicate (N-k) []) = some tail ∧ SourceTransport.Writes safe (eventLog tail)
+ have advance (k : ℕ) (hk : k < N) (mem : Memory w) (inv : I k mem) (bits : List Bool) (r : Report w)
+ (run : execute M f (M.start (k : Word w)) mem bits = some r) :
+ r.result = some ((k+1 : ℕ) : Word w) ∧ I (k+1) (after mem r.events) ∧
+ OrdinalRun.Preserved (C idx).params ports mem (after mem r.events) := by
+ obtain ⟨tail,ht,wr⟩ := inv
+ rw [show N-k = N-(k+1)+1 by omega,List.replicate_succ,runSegment] at ht
+ cases hd : execute M f (M.start (k : Word w)) mem [] with
+ | none => rw [hd] at ht; contradiction
+ | some rep =>
+ have eqn : rep = r := (execute_prefix_unique (suffix := bits) hd run).2
+ subst rep
+ rw [hd] at ht
+ obtain ⟨rest,hr,rfl⟩ := Option.map_eq_some_iff.mp ht
+ have succ := j.advance P data mem (k : Word w) r hd
+ rw [show ((k : Word w)+1) = ((k+1 : ℕ) : Word w) by simp] at succ
+ rw [succ] at hr
+ have here : SourceTransport.Writes safe r.events := fun a b ha ↦
+ wr a b (List.mem_append_left _ ha)
+ have later : SourceTransport.Writes safe (eventLog rest) := fun a b ha ↦
+ wr a b (List.mem_append_right _ ha)
+ exact ⟨succ,⟨rest,hr,later⟩,fun x hx ↦ SourceTransport.after_outside mem here (not_not_intro hx)⟩
+ have active (k : ℕ) (hk : k < N) : (k : Word w) < (N : Word w) := by
+ change k % 2^w < N % 2^w
+ rwa [Nat.mod_eq_of_lt (hk.trans fit),Nat.mod_eq_of_lt fit]
+ have run : runSegment M f (some 0) m (List.replicate N []) = some rs := source
+ have inv : I 0 m := ⟨rs,by simpa only [Nat.sub_zero,Nat.cast_zero] using run,outside⟩
+ obtain ⟨valid,_,keep⟩ := OrdinalRun.validTrace C idx ports M f args (N : Word w) (fun k ↦ (k : Word w))
+ N I active (le_refl _) advance 0 (List.replicate N []) m rs (by simp) inv ready source
+ exact ⟨valid,keep⟩
+
+end CompressorRecords.ShrinkSlotPlan.Scheduled
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPacketGroup.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPacketGroup.lean
new file mode 100644
index 0000000000..7131ea948e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPacketGroup.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.CompressorSourceGroups
+
+/-!
+# Packet groups from chronological source walks
+
+The ordinal of a source packet is its position in the window, even when
+two workers or two visits coincide. Each packet retains the source
+segment's input memory, reports and tapes. An invariant can be carried
+along the original report sequence to justify its launch operands.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open BurstRAM
+
+namespace SourceWalk
+
+variable {w : ℕ} {J : Type*} {src : J → Memory w → List (Report w) → Prop}
+variable {js : List J} {m : Memory w} {rs : List (Report w)}
+
+/-- Carry a memory invariant into the input of every source segment and
+through the complete report log. -/
+theorem with_invariant (walk : SourceWalk src js m rs) {I : Memory w → Prop} (start : I m)
+ (step : ∀ j mem logs, src j mem logs → I mem → I (after mem (eventLog logs))) :
+ SourceWalk (fun j mem logs ↦ src j mem logs ∧ I mem) js m rs ∧ I (after m (eventLog rs)) := by
+ induction walk with
+ | done => exact ⟨.done _, start⟩
+ | @next j js m xs ys head _ ih =>
+ obtain ⟨tail,finish⟩ := ih (step _ _ _ head start)
+ exact ⟨.next ⟨head,start⟩ tail, by rwa [after_append]⟩
+
+/-- An actual walk that writes only outside a region keeps the reference
+memory's operands there at every packet start, and in the final memory. -/
+theorem with_agreement (walk : SourceWalk src js m rs) (region : ℕ → Prop) (reference : Memory w)
+ (start : SourceTransport.Agree region reference m)
+ (writes : SourceTransport.Writes (fun x ↦ ¬ region x) (eventLog rs)) :
+ SourceWalk (fun j mem logs ↦ src j mem logs ∧ SourceTransport.Agree region reference mem) js m rs ∧
+ SourceTransport.Agree region reference (after m (eventLog rs)) := by
+ induction walk with
+ | done => exact ⟨.done _, start⟩
+ | @next j js m xs ys head _ ih =>
+ rw [eventLog,List.flatMap_append] at writes
+ have first : SourceTransport.Writes (fun x ↦ ¬ region x) (eventLog xs) :=
+ fun a v h ↦ writes a v (List.mem_append_left _ h)
+ have rest : SourceTransport.Writes (fun x ↦ ¬ region x) (eventLog ys) :=
+ fun a v h ↦ writes a v (List.mem_append_right _ h)
+ have next : SourceTransport.Agree region reference (after m (eventLog xs)) :=
+ fun i hi ↦ (start i hi).trans (SourceTransport.after_outside m first (not_not_intro hi)).symm
+ obtain ⟨tail,finish⟩ := ih next rest
+ exact ⟨.next ⟨head,start⟩ tail, by rwa [after_append]⟩
+
+end SourceWalk
+
+namespace SourceOnline.Group
+
+open BlockPlanner DescriptorSpace
+
+/-- Assemble a complete window from its actual runs. The certificate is
+indexed by the label occurrence, so it can use that occurrence's physical
+calendar ordinal directly. -/
+theorem of_window_walk {J : Type*} {w : ℕ} {A : Script} {L : Layout} {base : Word w} {cap ordinal total : ℕ}
+ {src : J → Memory w → List (Report w) → Prop} {stages : List J}
+ (labels : Fin stages.length → Visit A w)
+ {m : Memory w} {rs : List (Report w)} (walk : SourceWalk src stages m rs)
+ (cert : ∀ i mem logs, src stages[i.val] mem logs →
+ (labels i).Runs mem logs ∧ Checked A L cap ⟨labels i,mem,logs⟩ ∧
+ Prepared A L base (ordinal+i.val) total ⟨labels i,mem,logs⟩) :
+ ∃ ps : List (Packet A w), ps.map SourceWalk.Packet.stage = List.ofFn labels ∧
+ ps.flatMap SourceWalk.Packet.reports = rs ∧ Group A L base cap ordinal total m ps := by
+ induction walk generalizing ordinal with
+ | done =>
+ exact ⟨[],List.ofFn_zero.symm,rfl,nil⟩
+ | @next j js m xs ys head _ ih =>
+ rw [@List.ofFn_succ _ js.length labels]
+ let first : Packet A w := ⟨labels 0,m,xs⟩
+ obtain ⟨run,check,prepare⟩ := cert 0 m xs head
+ have firstGroup : Group A L base cap ordinal total m [first] :=
+ singleton first rfl run check (by simpa only [Fin.val_zero,Nat.add_zero] using prepare)
+ have later (i : Fin js.length) mem logs (hs : src js[i.val] mem logs) :
+ (labels i.succ).Runs mem logs ∧ Checked A L cap ⟨labels i.succ,mem,logs⟩ ∧
+ Prepared A L base ((ordinal+1)+i.val) total ⟨labels i.succ,mem,logs⟩ := by
+ rw [show (ordinal+1)+i.val = ordinal+i.succ.val by simp only [Fin.val_succ]; omega]
+ exact cert i.succ mem logs hs
+ obtain ⟨ps,stages,reports,group⟩ := ih (fun i ↦ labels i.succ) later
+ refine ⟨first::ps, congrArg (labels 0 :: ·) stages, congrArg (xs ++ ·) reports, firstGroup.append ?_⟩
+ simpa only [post,List.flatMap_cons,List.flatMap_nil,List.append_nil,List.length_cons,List.length_nil,first] using group
+
+end SourceOnline.Group
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPacketSpace.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPacketSpace.lean
new file mode 100644
index 0000000000..4f959bf3f2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPacketSpace.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotBoundary
+import OAI.Computability.VPVNP.CompressorShrinkSlotWindow
+import OAI.Computability.VPVNP.CompressorWindowPackets
+import OAI.Computability.VPVNP.CompressorShrinkLevelSpace
+
+/-!
+# Physical address and calendar bounds for shrinking slot packets
+
+At each repetition, the selected score and old role rows lie in table zero
+and the complete slot construction fits in table three. Its exclusive end
+precedes the next level header, whose incidence block receives the six copied
+columns. The directory has room for every visit of the repeated block.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BurstRAM BlockPlanner Compression DescriptorSpace Schedule ShrinkSlots
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+variable (base : Word w) (positions blocks t : ℕ)
+
+local notation "prog" => BlockProgram.script B
+local notation "arenaL" => BlockProgram.layout B base.val positions blocks
+
+/-- Every slot worker's actual repeated-block ordinal is strictly below
+the exclusive end of the compact physical directory. -/
+theorem ordinal_lt (live : t < blocks) (j : Fin (ShrinkSlotPlan.Scheduled.order.map
+ (ShrinkSlotPlan.Scheduled.Stage.visit (plan B i))).length) :
+ Window.ordinal (A := prog) t ((window B i).index j) < directoryRows arenaL := by
+ rw [(window B i).ordinal_index, BlockProgram.directory_rows,(prog).calendar_total]
+ have h := Nat.mul_le_mul_right (prog).block.length live
+ rw [Nat.succ_mul] at h
+ have hj := ((window B i).position j).isLt
+ omega
+
+/-- The geometry of the actual compiled allocation proves every boundary
+required to preserve the planner's roots throughout a slot window. -/
+theorem physical_boundary (live : t < blocks) (sites : X.positions ≤ positions)
+ (room : endAddress arenaL < 2^w) :
+ let old := (prog).levelsPerBlock*t+i.val
+ let next := (prog).levelsPerBlock*t+(i.val+1)
+ let start := tableBase arenaL old (0 : Fin 6)
+ let term := ShrinkInput.termHead (w := w) X start
+ let stride := (10 : Word w)
+ let role := SelectedArena.roleBase X term stride
+ let score := SelectedArena.origin X term stride+2
+ let s := levelShape (b := S.degreeExponent i.succ) X
+ let slotStart := tableBase arenaL old (3 : Fin 6)
+ let slotEnd := finish s (ShrinkOutput.heads s role slotStart)
+ Boundary prog arenaL base t i.val role slotStart slotEnd (incidenceStart arenaL next) score := by
+ intro old next start term stride role score s slotStart slotEnd
+ have nextEq : old+1 = next := by dsimp only [old,next]; omega
+ have nextLive : next < (arenaL).levels := by
+ have h := Nat.mul_le_mul_left (S.steps+1) live
+ rw [Nat.mul_succ] at h
+ have hi := i.isLt
+ change (S.steps+1)*t+(i.val+1) < 1+(S.steps+1)*blocks
+ omega
+ have arityEq : arity (prog).catalog = (arenaL).shape.arity := rfl
+ have levelFit : levelStart arenaL 0 < 2^w :=
+ (levelStart_mono arenaL (Nat.zero_le (arenaL).levels)).trans_lt room
+ obtain ⟨rows,pitch⟩ := Window.lowCells (A := prog) arenaL base arityEq rfl levelFit
+ have rowRoom : (prog).initial.length+(t+1)*(prog).block.length ≤ directoryRows arenaL := by
+ rw [BlockProgram.directory_rows,(prog).calendar_total]
+ exact Nat.add_le_add_left (Nat.mul_le_mul_right _ live) _
+ have slotPos : 0 < slotDegree S := (Nat.two_pow_pos _).trans_le (show 2^S.degreeExponent i.castSucc ≤ slotDegree S from
+ (Finset.le_sup (f := fun j : Fin (S.steps+1) ↦ 2^S.degreeExponent j) (Finset.mem_univ i.castSucc)).trans
+ (le_max_right ..))
+ have fieldBound : ShrinkLevelSpace.tableFactor S ≤ BlockProgram.fieldCount B := by
+ unfold BlockProgram.fieldCount; omega
+ have size : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords arenaL := by
+ change _ ≤ positions*slotDegree S*BlockProgram.fieldCount B
+ rw [Nat.mul_assoc]
+ exact Nat.mul_le_mul sites (fieldBound.trans (Nat.le_mul_of_pos_left _ slotPos))
+ have ends := ShrinkLevelSpace.packed_ends S i X start start start slotStart w
+ have termBound : ShrinkInput.termEnd X start 10 ≤ start+X.positions*ShrinkLevelSpace.tableFactor S := ends.2.1
+ have retainedBound : SelectedFinish.stop X term stride ≤ start+X.positions*ShrinkLevelSpace.tableFactor S := ends.2.2.1
+ have slotBound : slotEnd ≤ slotStart+X.positions*ShrinkLevelSpace.tableFactor S := ends.2.2.2.2.2.2
+ have slotBefore : slotEnd ≤ levelStart arenaL next :=
+ slotBound.trans ((Nat.add_le_add_left size _).trans (nextEq ▸ tableEnd_le_nextLevel arenaL old (3 : Fin 6)))
+ have header (n : ℕ) : incidenceStart arenaL n = levelStart arenaL n+66 := rfl
+ have headerBeforeTable (n : ℕ) (u : Fin 6) : incidenceStart arenaL n ≤ tableBase arenaL n u :=
+ (Nat.le_add_right _ _).trans (Nat.le_add_right _ _)
+ have nextRoom : incidenceStart arenaL next < 2^w :=
+ (headerBeforeTable next 0).trans_lt (((Nat.le_add_right _ _).trans
+ ((tableEnd_le_nextLevel arenaL next (0 : Fin 6)).trans (levelStart_mono arenaL nextLive))).trans_lt room)
+ have oldRoom : incidenceStart arenaL old < 2^w := by
+ rw [header]
+ have nextFits : levelStart arenaL next+66 < 2^w := (header next) ▸ nextRoom
+ have h := levelStart_mono arenaL (show old ≤ next by omega)
+ omega
+ have startToSlot : start+tableWords arenaL ≤ slotStart :=
+ tableEnd_le_tableBase arenaL old (show (0 : Fin 6) < 3 by decide)
+ have slotStartFit : slotStart < 2^w := ((Nat.le_add_right _ _).trans
+ ((tableEnd_le_nextLevel arenaL old (3 : Fin 6)).trans (levelStart_mono arenaL (by omega : old+1 ≤ (arenaL).levels)))).trans_lt room
+ have tr : ShrinkInput.termEnd X start 10 < 2^w :=
+ termBound.trans_lt (((Nat.add_le_add_left size start).trans startToSlot).trans_lt slotStartFit)
+ let N := ShrinkTermSelection.bundles X*ShrinkTermSelection.ranks (S.degreeExponent i.castSucc)
+ change ShrinkInput.stop X start+2*N+N*10 < 2^w at tr
+ have termAt : term.val = ShrinkInput.stop X start+2*N := Nat.mod_eq_of_lt (by omega)
+ obtain ⟨h₀,h₁,h₂,h₃⟩ := ShrinkInput.range_bounds X start
+ have headLow : levelStart arenaL 0 ≤ start := (levelStart_mono arenaL (Nat.zero_le old)).trans
+ ((Nat.le_add_right _ _).trans (headerBeforeTable old 0))
+ have scoreLow : levelStart arenaL 0 ≤ score := by
+ dsimp only [score,SelectedArena.origin]
+ omega
+ have scoreRole : score < role := by
+ dsimp only [score,role,SelectedArena.roleBase,SelectedArena.placementBase]; omega
+ have roleEnd : role ≤ SelectedFinish.stop X term stride := by
+ unfold SelectedFinish.stop SelectedFinish.rowStart SelectedFinish.countStart SelectedArena.endAddr; omega
+ have roleBefore : role ≤ slotStart :=
+ roleEnd.trans (retainedBound.trans ((Nat.add_le_add_left size start).trans startToSlot))
+ exact ⟨arityEq,rfl,levelFit,rowRoom,rows,pitch,scoreLow.trans scoreRole.le,roleBefore,
+ (header old) ▸ headerBeforeTable old 3,slotBefore,(header next).ge,scoreLow,scoreRole.trans_le roleBefore,
+ (header old) ▸ oldRoom.le,(header next) ▸ nextRoom.le⟩
+
+end CompressorRecords.ShrinkSlotCalendar
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPackets.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPackets.lean
new file mode 100644
index 0000000000..443324c6f1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPackets.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotOrdinals
+import OAI.Computability.VPVNP.CompressorSlotCoreAccess
+import OAI.Computability.VPVNP.CompressorScriptWindow
+import OAI.Computability.VPVNP.CompressorSourceScanned
+import OAI.Computability.VPVNP.CompressorShrinkPreparationAccess
+
+/-!
+# Checked online packets for a shrinking slot window
+
+The twenty-two source scans retain their global catalog indices, public
+banks, tapes and reports. Each report advances its cursor to the next
+ordinal and all exclusive stops fit the allocated word. The fixed worker
+instruction bound is 49 before adding the online dispatch overhead.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlotPackets
+
+open BurstRAM BlockPlanner DescriptorSpace Schedule SlotLevel ShrinkSlots ShrinkSlotPlan.Scheduled
+open scoped Fin.CommRing
+open private scanned from OAI.Computability.VPVNP.CompressorShrinkPreparationAccess
+
+variable {A : Script} (P : Plan) (W : Window A (order.map (Stage.visit P)))
+
+/-- Map a scheduled slot-stage index through its script window to the global catalog index. -/
+def index (i : Fin order.length) : Fin A.size := W.index (Fin.cast (List.length_map (Stage.visit P)).symm i)
+
+theorem index_visit (i : Fin order.length) : A.visit (index P W i) = order[i.val].visit P := by
+ simpa only [index,List.getElem_map,Fin.val_cast] using W.visit (Fin.cast (List.length_map (Stage.visit P)).symm i)
+
+theorem index_worker (i : Fin order.length) : A.catalog (index P W i) = (order[i.val].visit P).worker :=
+ congrArg BlockPlanner.Visit.worker (index_visit P W i)
+
+variable {w : ℕ} (s : SlotLevel.Shape) (h : Heads) (chosen : Bool) (splitHead : ℕ) (dest : IncidenceDirectory w)
+
+/-- The online packet for a slot worker, with its global index, physical bank, exclusive stop
+and an empty choice stream at each cursor ordinal. -/
+def packetVisit (i : Fin order.length) : SourceOnline.Visit A w :=
+ let j := order[i.val]
+ let v := j.visit P
+ SourceOnline.Visit.ofWorker (index P W i) v.worker (index_worker P W i) (v.worker.pcs-1)
+ 0 (j.limit s : Word w) (j.bank s h chosen splitHead dest ∘ Fin.cast (j.params P))
+ (List.replicate (j.limit s) [])
+
+local notation "pkt" => packetVisit P W s h chosen splitHead dest
+
+/-- The embedded catalog visit executes the original source program. -/
+theorem runs (i : Fin order.length) (m : Memory w) (rs : List (Report w)) :
+ (pkt i).Runs m rs ↔ Source P s h chosen splitHead dest order[i.val] m rs :=
+ SourceOnline.Visit.ofWorker_runs _ _ (index_worker P W i) _ _ _ _ _ _ _
+
+theorem fuel_bounds (j : Stage) : 0 < (j.visit P).worker.pcs-1 ∧ (j.visit P).worker.pcs-1 ≤ 49 := by
+ cases j with
+ | subdivision _ => exact (by decide : 0 < 7 ∧ 7 ≤ 49)
+ | roles => exact (by decide : 0 < 26 ∧ 26 ≤ 49)
+ | cyclic => exact (by decide : 0 < 19 ∧ 19 ≤ 49)
+ | clear => exact (by decide : 0 < 8 ∧ 8 ≤ 49)
+ | core p =>
+ cases p
+ exacts [(by decide : 0 < 49 ∧ 49 ≤ 49), (by decide : 0 < 20 ∧ 20 ≤ 49),
+ (by decide : 0 < 23 ∧ 23 ≤ 49), (by decide : 0 < 10 ∧ 10 ≤ 49), (by decide : 0 < 33 ∧ 33 ≤ 49)]
+ | output p =>
+ cases p
+ exacts [(by decide : 0 < 10 ∧ 10 ≤ 49), (by decide : 0 < 28 ∧ 28 ≤ 49),
+ (by decide : 0 < 28 ∧ 28 ≤ 49), (by decide : 0 < 43 ∧ 43 ≤ 49)]
+ | copy _ => exact (by decide : 0 < 12 ∧ 12 ≤ 49)
+
+/-- The allocated endpoint, counter, sorted-row and incidence arrays bound
+every stop, including the strided rectangle traversed by inversion. -/
+theorem limit_fit (sp : Build.Space s h splitHead w) (j : Stage) : j.limit s < 2^w := by
+ have fit := sp.fit
+ unfold finish widthHead inHead outHead inverseBaseHead stopAddress shiftsHead targetsHead
+ inverseHead rowsHead at fit
+ have rc := sp.roles
+ have nc := sp.next
+ have sc := sp.subdiv
+ have gc := counts_add s
+ have ownerBound := Nat.mul_le_mul_right s.newDegree (Nat.le_add_right (owners s) (fields s))
+ have siteBound : sites s ≤ owners s := by unfold owners; omega
+ cases j with
+ | core p => cases p <;> simp only [Stage.limit,SlotLevel.limit] <;> omega
+ | output p => cases p <;> simp only [Stage.limit,ShrinkSlots.Recipe.limit] <;> omega
+ | copy c => simp only [Stage.limit]; split <;> omega
+ | _ => simp only [Stage.limit]; omega
+
+theorem scanned_source (j : Stage) (m : Memory w) (rs : List (Report w))
+ (source : Source P s h chosen splitHead dest j m rs) : StageFrame.Scanned 0 (j.limit s) rs := by
+ let data := j.bank s h chosen splitHead dest ∘ Fin.cast (j.params P)
+ have shape := scanned (j.advance P data) m 0 (j.limit s) rs source
+ simpa only [Nat.zero_add] using shape
+
+/-- Check the embedded packet at a single occurrence using its original
+worker run and the lower bounds on all of its external accesses. -/
+theorem checked_source (i : Fin order.length) (L : DescriptorSpace.Layout) (cap : ℕ)
+ (sp : Build.Space s h splitHead w) (capFits : SourceOnline.scanCap A 49 ≤ cap)
+ (mem : Memory w) (logs : List (Report w))
+ (source : Source P s h chosen splitHead dest order[i.val] mem logs)
+ (access : LogAccess (levelStart L 0 ≤ ·) (levelStart L 0 ≤ ·) logs) :
+ SourceOnline.Checked A L cap ⟨pkt i,mem,logs⟩ := by
+ let j := order[i.val]
+ let p : SourceWalk.Packet (SourceOnline.Visit A w) w := ⟨pkt i,mem,logs⟩
+ have fuel : 0 < p.stage.fuel ∧ p.stage.fuel ≤ 49 := fuel_bounds P j
+ have clocks := SourceOnline.scanCap_clocks (p := p) 49 fuel.2 capFits
+ exact SourceOnline.Checked.ofScanned fuel.1 clocks.1 clocks.2 (first := 0) rfl rfl
+ (limit_fit s h splitHead sp j) (scanned_source P s h chosen splitHead dest j mem logs source)
+ access.1 access.2 (fun _ hx ↦ hx) (fun _ hx ↦ hx)
+
+/-- Embed the entire chronological slot program and check each online packet
+using its actual source access bounds above the persistent level base. -/
+theorem checked_walk (L : DescriptorSpace.Layout) (cap : ℕ) (sp : Build.Space s h splitHead w)
+ (capFits : SourceOnline.scanCap A 49 ≤ cap) (m : Memory w) (rs : List (Report w))
+ (walk : SourceWalk (fun j mem logs ↦ Source P s h chosen splitHead dest j mem logs ∧
+ LogAccess (levelStart L 0 ≤ ·) (levelStart L 0 ≤ ·) logs) order m rs) :
+ SourceWalk (fun v mem logs ↦ v.Runs mem logs ∧ SourceOnline.Checked A L cap ⟨v,mem,logs⟩)
+ (List.ofFn pkt) m rs := by
+ apply walk.mapAt pkt
+ intro i mem logs hs
+ exact ⟨(runs P W s h chosen splitHead dest i mem logs).2 hs.1,
+ checked_source P W s h chosen splitHead dest i L cap sp capFits mem logs hs.1 hs.2⟩
+
+end CompressorRecords.ShrinkSlotPackets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPhysicalGroup.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPhysicalGroup.lean
new file mode 100644
index 0000000000..99692501f8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPhysicalGroup.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotOnlineGroup
+import OAI.Computability.VPVNP.CompressorShrinkSlotGroupIndices
+import OAI.Computability.VPVNP.CompressorShrinkSlotGroupFrame
+import OAI.Computability.VPVNP.CompressorShrinkSlotPacketSpace
+import OAI.Computability.VPVNP.CompressorShrinkSlotPhysicalSpace
+import OAI.Computability.VPVNP.CompressorShrinkSlotReference
+
+/-!
+# Executing the slot group of an allocated shrinking block
+
+The preceding width reports fix the input memory for these 22 packets.
+The selected score, level headers and published column addresses determine
+each launch. The six final copies populate the next level's incidence rows.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BurstRAM BlockPlanner Compression DescriptorSpace PhaseRecipe Schedule ShrinkBlockInputs
+open ShrinkSlots SlotLevel
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (base : Word w) (positions blocks t : ℕ)
+local notation "A" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (arity (Script.catalog A)) base
+local notation "pub" => Schedule.Ports.data pt
+local notation "first" => Script.levelsPerBlock A*t
+local notation "old" => first+i.val
+local notation "next" => first+(i.val+1)
+local notation "st" => (levelStart L first : Word w)
+local notation "head" => (fun j : Fin 6 => tableBase L old j)
+local notation "term" => ShrinkInput.termHead (w := w) X (head 0)
+local notation "step" => (10 : Word w)
+local notation "role" => SelectedArena.roleBase X term step
+local notation "s" => levelShape (b := b i) X
+local notation "h" => ShrinkOutput.heads s role (head 3)
+local notation "dst" => packedIncidence L w next (actualCount s)
+local notation "W" => BlockGroups.shrink B i 8
+
+set_option maxHeartbeats 1500000 in
+/-- The selected slots and canonical copies occupy the actual eighth
+shrinking part. The reports agree with the output of the preceding
+construction, including its post-width memory. -/
+theorem physical_group (T : IncidenceDirectory w) (sel : SelectedScore.Selection B X)
+ (abs : Word w) (I : ShrinkABSliceRecipe.Inputs) (ref m : Memory w) (fuel : ℕ) (r : ShrinkOutput.TablesRun w)
+ (live : t < blocks) (sitesFit : X.positions ≤ positions) (room : endAddress L < 2^w)
+ (rows : m (pt).rows.val = (directoryRows L : Word w))
+ (pitch : m ((pt).directory-1).val = (levelWords L : Word w))
+ (header : ShrinkHeaderReads.Header i X T (head 0) L first m) (oldRows : ℕ)
+ (currentHeads : PortRefresh.TraversalHeaders.HeadBank L old oldRows m)
+ (nextHeads : PortRefresh.TraversalHeaders.HeadBank L next (actualCount s) m)
+ (resident : ShrinkOutput.Resident B i X sel term step abs T (head 0) (head 2) m)
+ (run : ShrinkOutput.CompleteTables B i X (S.shrink i) sel term step abs (head 0)
+ I pub st ref (head 1) (head 2) (head 3) fuel m r)
+ (cap : ℕ) (clock : SourceOnline.scanCap A 49 ≤ cap) :
+ let Y := X.shrinkNext B.shrink (S.shrink i) sel
+ let raw := r.remainder.postWidths
+ let native := r.remainder.slots
+ let copies := CopyIncidence.reports Y (directory s h w) dst CopyIncidence.allColumns
+ (after raw (eventLog native.all))
+ ∃ ps : List (SourceOnline.Packet A w),
+ SourceOnline.Group A L base cap ((A).initial.length+t*(A).block.length+(W).before.length)
+ (directoryRows L) raw ps ∧
+ ps.map (fun p => p.stage.phase) = (W).indices ∧
+ ps.flatMap SourceWalk.Packet.reports = native.all++copies ∧
+ (dst).Represents Y (SourceOnline.post raw ps) ∧
+ ∀ x, (x < head 3 ∨ finish s h ≤ x) →
+ (x < incidenceStart L next ∨ incidenceStart L next+6*actualCount s ≤ x) →
+ SourceOnline.post raw ps x = raw x := by
+ intro Y raw native copies
+ have currentLive : old < (L).levels := by
+ have many := Nat.mul_le_mul_left (S.steps+1) live
+ rw [Nat.mul_succ] at many
+ have hi := i.isLt
+ change (S.steps+1)*t+i.val < 1+(S.steps+1)*blocks
+ omega
+ have nextLive : next < (L).levels := by
+ have many := Nat.mul_le_mul_left (S.steps+1) live
+ rw [Nat.mul_succ] at many
+ have hi := i.isLt
+ change (S.steps+1)*t+(i.val+1) < 1+(S.steps+1)*blocks
+ omega
+ let cur : Fin (L).levels := ⟨old,currentLive⟩
+ let nxt : Fin (L).levels := ⟨next,nextLive⟩
+ have geometry : Boundary A L base t i.val role (head 3) (finish s h) (incidenceStart L next)
+ (SelectedArena.origin X term step+2) := physical_boundary B i X base positions blocks t live sitesFit room
+ obtain ⟨sp,count,_,width⟩ := physical_space B i X base.val positions blocks cur rfl sitesFit room
+ have size : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords L := by
+ change _ ≤ positions*(L).shape.slots*(L).shape.fields
+ rw [Nat.mul_assoc]
+ exact Nat.mul_le_mul sitesFit (BlockProgram.field_rates B base.val positions blocks).1
+ have bank0 : head 0 = arrayBase L old := by
+ change arrayBase L old+0*tableWords L = _
+ rw [Nat.zero_mul,Nat.add_zero]
+ have bank1 : head 1 = head 0+tableWords L := by
+ change arrayBase L old+1*tableWords L = head 0+tableWords L
+ rw [bank0,one_mul]
+ have bank2 : head 2 = head 0+2*tableWords L := by rw [bank0]; rfl
+ have bank3 : head 3 = head 0+3*tableWords L := by rw [bank0]; rfl
+ have headerLow : levelStart L old+66 ≤ head 0 := by rw [bank0]; exact Nat.le_add_right ..
+ have dataLow := (levelStart_mono L (Nat.zero_le old)).trans ((Nat.le_add_right _ 66).trans headerLow)
+ have lowPitch := geometry.pitchBefore.trans_le dataLow
+ have lowRows := geometry.rowsBefore.trans_le dataLow
+ have entry : LevelFields.Entry L first pub st m := ⟨rfl,pitch⟩
+ obtain ⟨values,low,_⟩ := values_at_slots_framed B i X T (head 0) L first pub st m sel (S.shrink i)
+ abs I ref (head 1) (head 2) (head 3) fuel r cur nxt rfl rfl oldRows rfl rfl bank0 bank1 bank2
+ bank3 size room lowPitch header entry currentHeads nextHeads resident run
+ have ends := ShrinkLevelSpace.packed_ends S i X (head 0) (head 1) (head 2) (head 3) w
+ have limit := tableStop_lt L cur (0 : Fin 6) size room
+ have postHeader := header.keep_below (by omega : levelStart L old+60 < head 0) low
+ have postPitch := (low _ lowPitch).trans pitch
+ have postEntry : LevelFields.Entry L first pub st raw := ⟨rfl,postPitch⟩
+ have score := (reference_heads B i X T (head 0) L first pub st raw postHeader postEntry
+ (ends.2.1.trans_lt limit) (ends.2.2.1.trans limit.le)).2.1
+ rw [← score] at geometry
+ change Build.Space s h (head 2) w at sp
+ change ShrinkOutput.widthBase X (term).val (step).val role (head 2) = head 2 at width
+ rw [← width] at sp values
+ obtain ⟨ps,labels,reports,group,rep⟩ := packet_group B i X sel term (step).val role (head 2)
+ (head 3) L base t nxt run.remainder.construction sp room count ((low _ lowRows).trans rows)
+ postPitch values geometry cap clock
+ rw [part_eight_before] at group
+ refine ⟨ps,group,?_,reports,rep,?_⟩
+ · have phases := congrArg (List.map (fun (v : SourceOnline.Visit A w) => v.phase)) labels
+ simpa only [List.map_map,Function.comp_def] using phases.trans (part_eight_indices B i _ _ _ _ _)
+ · apply packet_group_frame_of_space B i X sel term (step).val role (head 2) (head 3) L nxt
+ run.remainder.construction sp room count _ ps reports
+ exact .inl (geometry.slotBefore.trans ((Nat.le_add_right _ 66).trans geometry.headerBefore))
+
+end CompressorRecords.ShrinkSlotCalendar
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPhysicalSpace.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPhysicalSpace.lean
new file mode 100644
index 0000000000..64f2fe4f0a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPhysicalSpace.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.CompressorBlockLevelFit
+import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables
+import OAI.Computability.VPVNP.CompressorSlotCoreAccess
+
+/-! # Word and incidence capacity for a physical shrinking slot workspace
+
+The selected role columns occupy table zero. Table two holds the balanced
+subdivisions and their interval records. Table three holds the slot workspace.
+The available address range also bounds the lane, tag, subdivision and degree
+words used by the slot workers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BurstRAM Compression DescriptorSpace ShrinkBlockInputs ShrinkSlots SlotLevel
+open scoped Fin.CommRing
+open private packed_le absolute_eq from OAI.Computability.VPVNP.CompressorShrinkLevelSpace
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g))
+variable (base positions blocks : ℕ) {L : Layout} (level : Fin L.levels)
+local notation "tab" => BlockLevelFit.tableStart L level.val
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "step" => (10 : Word w)
+local notation "role" => SelectedArena.roleBase X term step
+local notation "sh" => levelShape (b := b i) X
+local notation "h" => ShrinkOutput.heads sh role (tab 3)
+
+theorem physical_space (physical : L = BlockProgram.layout B base positions blocks)
+ (size : X.positions ≤ positions) (fit : endAddress L < 2 ^ w) :
+ Build.Space sh h (tab 2) w ∧ actualCount sh ≤ slotCapacity L ∧
+ (ShrinkOutput.slotHeads (b := b i) X (term).val (step).val role (tab 2)).role ≤ tab 3 ∧
+ ShrinkOutput.widthBase X (term).val (step).val role (tab 2) = tab 2 := by
+ have ends := BlockLevelFit.shrink B base positions blocks level physical i X size fit
+ have zeroBefore : tab 0 + tableWords L ≤ tab 2 := by unfold BlockLevelFit.tableStart; omega
+ have twoBefore : tab 2 + tableWords L ≤ tab 3 := by unfold BlockLevelFit.tableStart; omega
+ have retained : SelectedFinish.stop X term step ≤ tab 2 := ends.2.2.1.within.trans zeroBefore
+ have widthEq := ShrinkOutput.width_at_eq i X term step (tab 2) retained
+ have gap : ShrinkOutput.slotsBase X (tab 2) sh ≤ tab 3 :=
+ ends.2.2.2.2.2.1.within.trans twoBefore
+ have slotRoom : finish sh h < 2^w := ends.2.2.2.2.2.2.1.word
+ have sumRoom : ShrinkOutput.slotsBase X (tab 2) sh < 2^w := ends.2.2.2.2.2.1.word
+ have roleBound := (ShrinkOutput.old_bounds i X term step).2.1.trans retained
+ have widthBound : tab 2 + (ShrinkOutput.absoluteCount X * 4) * (∑ t, (sh).subdivisions t) ≤
+ ShrinkOutput.slotsBase X (tab 2) sh := Nat.le_add_right ..
+ have absolutePos : 0 < ShrinkOutput.absoluteCount X := by
+ rw [absolute_eq X]
+ exact Nat.mul_pos X.positions_pos (Nat.two_pow_pos _)
+ have profile : (∑ t, (sh).subdivisions t) < 2 ^ w :=
+ (Nat.le_mul_of_pos_left _ (Nat.mul_pos absolutePos (by decide : 0 < 4))).trans_lt
+ ((Nat.le_add_left ..).trans_lt (widthBound.trans_lt sumRoom))
+ have tagPos : 0 < (sh).tags := Nat.two_pow_pos _
+ have lanePos : 0 < (sh).lanes := Nat.two_pow_pos _
+ have basePos : 0 < (sh).bases := Fintype.card_pos
+ have degPos : 0 < (sh).newDegree := Nat.two_pow_pos _
+ have sitePos : 0 < sites sh := Nat.mul_pos basePos (Nat.mul_pos tagPos lanePos)
+ have countRoom : actualCount sh < 2^w := (Nat.le_add_left ..).trans_lt slotRoom
+ have siteRoom : sites sh < 2^w := (Nat.le_mul_of_pos_right _ degPos).trans_lt countRoom
+ have tagsLanes : (sh).tags * (sh).lanes < 2^w := (Nat.le_mul_of_pos_left _ basePos).trans_lt siteRoom
+ have degreeBound : 2^(b i) ≤ slotDegree S :=
+ (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j)
+ (Finset.mem_univ i.succ)).trans (le_max_right ..)
+ refine ⟨⟨?_,widthBound.trans gap,le_rfl,le_rfl,le_rfl,slotRoom,
+ (Nat.le_mul_of_pos_left _ tagPos).trans_lt tagsLanes,
+ (Nat.le_mul_of_pos_right _ lanePos).trans_lt tagsLanes,profile,
+ (Nat.le_mul_of_pos_left _ sitePos).trans_lt countRoom⟩,?_,?_,widthEq⟩
+ · exact roleBound.trans ((Nat.le_add_right ..).trans twoBefore)
+ · have capacity : slotCapacity L = positions * slotDegree S := physical ▸ rfl
+ rw [capacity]
+ exact Nat.mul_le_mul ((packed_le X).trans size) degreeBound
+ · change ShrinkOutput.slotsBase X (ShrinkOutput.widthBase X (term).val (step).val role (tab 2)) sh ≤ _
+ rw [widthEq]; exact gap
+
+end CompressorRecords.ShrinkSlotCalendar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPlan.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPlan.lean
new file mode 100644
index 0000000000..9d63666d3f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotPlan.lean
@@ -0,0 +1,223 @@
+import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner
+import OAI.Computability.VPVNP.CompressorRecordsLevelFields
+import OAI.Computability.VPVNP.CompressorSlotOutputRecipe
+import OAI.Computability.VPVNP.CompressorSlotIncidence
+import OAI.Computability.VPVNP.CompressorSlotWidthScan
+import OAI.Computability.VPVNP.CompressorSlotOwnerAux
+import OAI.Computability.VPVNP.CompressorSlicePreparation
+
+/-!
+# The chronological shrinking slot program
+
+Four fixed writes install the subdivision counts. Two scans prepare the
+selected role and cyclic successor tables, and one clears the append counters.
+Five sorted-slot scans and four output scans fill the six incidence columns.
+Finally the program copies these columns, at their own base or lane-slot
+lengths, into the following level's canonical incidence arrays.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlotPlan
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PhaseRecipe BlockPlanner
+open scoped Fin.CommRing
+
+/-- Fixed tag, degree, color and subdivision data used to build the shrinking output slots. -/
+abbrev Template := SlotLevel.Recipe.Template
+/-- Runtime expressions for the graph dimensions and table heads needed by the shrinking slot
+recipes. -/
+abbrev Inputs := SlotLevel.Recipe.Inputs
+
+private def coreOps : (p : SlotLevel.Phase) → Expr → (Fin (SlotLevel.arity p) → Expr) → Visit
+ | .genuineOwners => ops SlotOwners.genuine 0 (.lit 0)
+ | .dummyOwners => ops SlotOwners.dummy 0 (.lit 0)
+ | .appendFields => ops collectPreimage 3 (.lit 0)
+ | .invertFields => ops SlotScatter.visit 0 (.lit 0)
+ | .baseMatching => ops SlotBaseScan.code 0 (.lit 0)
+
+private def outputOps : (p : ShrinkSlots.Recipe.Phase) → Expr → (Fin (ShrinkSlots.Recipe.arity p) → Expr) → Visit
+ | .baseInverse => ops SlotScatter.visit 0 (.lit 0)
+ | .actualOut => ops (SlotIncidencePass.visit false) 0 (.lit 0)
+ | .actualIn => ops (SlotIncidencePass.visit true) 0 (.lit 0)
+ | .widths => ops SlotWidthScan.visit 0 (.lit 0)
+
+/-- Build the visit for a slot-core phase using its phase-specific stop bound and public
+operand expressions. -/
+def core (T : Template) (I : Inputs) (p : SlotLevel.Phase) : Visit :=
+ coreOps p (SlotLevel.Recipe.stop T I p) (SlotLevel.Recipe.params T I p)
+
+/-- Build the visit for an output incidence phase, supplying the split-width head along with
+its derived operands. -/
+def output (T : Template) (I : Inputs) (split : Expr) (p : ShrinkSlots.Recipe.Phase) : Visit :=
+ outputOps p (ShrinkSlots.Recipe.stop T I p) (ShrinkSlots.Recipe.params T I split p)
+
+/-- Publish one role's fixed subdivision count in the runtime subdivision table. -/
+def subdivision (T : Template) (I : Inputs) (i : Fin 4) : Visit :=
+ publish (I.subdivisions.add (.lit i.val)) (.lit (T.subdivisions i))
+
+/-- The eight-row pass that publishes the role lookup for the selected layout side. -/
+def roles (I : Inputs) (layout : Expr) : Visit :=
+ ops SlotOwners.Aux.roleCode 0 (.lit 0) (.lit 8) ![layout,I.role]
+
+/-- The pass that fills the cyclic successor-site table from the lane and tag counts. -/
+def cyclic (T : Template) (I : Inputs) : Visit :=
+ ops SlotOwners.Aux.nextCode 0 (.lit 0) (SlotLevel.Recipe.counts T I).sites ![I.lanes,.lit T.tags,I.nextSite]
+
+/-- The unused owners have append counters too. Clear their cells and the real
+owners' cells before the uninterrupted five scans. -/
+def clear (T : Template) (I : Inputs) : Visit :=
+ let c := SlotLevel.Recipe.counts T I
+ ops SliceRAM.clearOps 0 (.lit 0) (c.owners.add c.fields) (fun _ ↦ I.scratch.add c.fields)
+
+/-- Expressions for the six constructed incidence-column heads used as sources of the final
+copy passes. -/
+def sourceHeads (T : Template) (I : Inputs) := ShrinkSlots.Recipe.columnHeads T I
+
+/-- The number of cells to copy for a column, using the base-arc count for the first three
+columns and the actual port count for the last three. -/
+def columnCount (T : Template) (I : Inputs) (c : Fin 6) :=
+ if c.val < 3 then (SlotLevel.Recipe.counts T I).baseArcs else (ShrinkSlots.Recipe.columns T I).count
+
+/-- Copy a completed incidence column from the shrinking slot arena to the canonical head
+published by the next level. -/
+def copyColumn (T : Template) (I : Inputs) (shape : DescriptorSpace.Shape) (step : ℕ) (c : Fin 6) : Visit :=
+ copy (columnCount T I c) (sourceHeads T I c) (LevelFields.incidence shape (step+1) c)
+
+/-- The list itself fixes the order of the native workers. Expression evaluation
+supplies the current heads, selected layout and split-width input at runtime. -/
+def visits (T : Template) (I : Inputs) (layout split : Expr) (shape : DescriptorSpace.Shape) (step : ℕ) :
+ List Visit :=
+ List.ofFn (subdivision T I) ++ [roles I layout, cyclic T I, clear T I,
+ core T I .genuineOwners, core T I .dummyOwners, core T I .appendFields, core T I .invertFields,
+ core T I .baseMatching, output T I split .baseInverse, output T I split .actualOut,
+ output T I split .actualIn, output T I split .widths] ++ List.ofFn (copyColumn T I shape step)
+
+@[simp] theorem visits_length (T : Template) (I : Inputs) (layout split : Expr) (shape : DescriptorSpace.Shape)
+ (step : ℕ) : (visits T I layout split shape step).length = 22 := by simp [visits]
+
+/-- Public-bank widths, in chronological order. The rectangular catalog can
+reserve eight parameter words for every shrinking slot visit. -/
+theorem operand_counts (T : Template) (I : Inputs) (layout split : Expr) (shape : DescriptorSpace.Shape)
+ (step : ℕ) :
+ ((visits T I layout split shape step).map fun v ↦ v.worker.params) =
+ [2,2,2,2,2,3,1,8,3,6,2,6,2,5,5,8,3,3,3,3,3,3] := rfl
+
+variable {w : ℕ} {pub : Fin 5 → Word w} {state : Word w} {m : Memory w}
+variable {bases lanes : ℕ} {h : SlotLevel.Heads} (T : Template) (I : Inputs)
+variable (read : SlotLevel.Recipe.Reads I pub state m bases lanes h)
+
+/-- Agreement of a worker's actual register arity, cursor bounds and operands
+with its native unpadded frame. The external catalog assigns its tag. -/
+def words (v : Visit) (tag : Word w) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) : List (Word w) :=
+ tag :: v.initial.eval pub state m :: v.stop.eval pub state m ::
+ List.ofFn (fun i ↦ (v.params i).eval pub state m)
+
+/-- The chronological script compiler uses the worker's position as its tag
+and pads the checked operand list to the largest arity in the catalog. -/
+theorem script_words (A : BlockPlanner.Script) (j : Fin A.size) :
+ (A.phase j).recipe.words pub state m =
+ words (A.visit j) (j.succ.val : Word w) pub state m ++
+ List.replicate (Schedule.arity A.catalog-(A.visit j).worker.params) 0 := by
+ let v := A.visit j
+ let phase : PhaseRecipe.Phase v.worker.params := ⟨j.succ.val,v.initial,v.stop,v.params⟩
+ have hp := SlotLevel.Recipe.pad_phase_words (Schedule.params_le_arity A.catalog j) phase pub state m
+ exact hp.trans (congrArg (fun xs ↦ xs ++ List.replicate _ 0) (PhaseRecipe.recipe_words phase pub state m))
+
+include read in
+theorem core_words (p : SlotLevel.Phase) (tag : Word w) :
+ words (core T I p) tag pub state m = SlotLevel.frame (T.shape bases lanes) h (fun _ ↦ tag) p := by
+ have hs := SlotLevel.Recipe.eval_stop T I p read
+ have hp := funext (SlotLevel.Recipe.eval_params T I p read)
+ cases p <;> exact congrArg₂ (fun u v ↦ tag :: 0 :: u :: List.ofFn v) hs hp
+
+include read in
+theorem output_words (split : Expr) {splitHead : ℕ} (hsplit : split.eval pub state m = (splitHead : Word w))
+ (p : ShrinkSlots.Recipe.Phase) (tag : Word w) :
+ words (output T I split p) tag pub state m = ShrinkSlots.Recipe.frame (T.shape bases lanes) h splitHead
+ (fun _ ↦ tag) p := by
+ have hs := ShrinkSlots.Recipe.eval_stop T I read p
+ have hp := funext (ShrinkSlots.Recipe.eval_params T I split read p hsplit)
+ cases p <;> exact congrArg₂ (fun u v ↦ tag :: 0 :: u :: List.ofFn v) hs hp
+
+include read in
+theorem subdivision_words (tag : Word w) (i : Fin 4) :
+ words (subdivision T I i) tag pub state m =
+ [tag,0,1,((h.subdivisions+i.val : ℕ) : Word w),(T.subdivisions i : Word w)] := by
+ change [tag,0,1,I.subdivisions.eval pub state m+(i.val : Word w),(T.subdivisions i : Word w)] = _
+ rw [read.subdivisions_eq,Nat.cast_add]
+
+include read in
+theorem cyclic_words (tag : Word w) :
+ words (cyclic T I) tag pub state m =
+ [tag,0,(SlotLevel.sites (T.shape bases lanes) : Word w),(lanes : Word w),(T.tags : Word w),(h.nextSite : Word w)] := by
+ have hc := SlotLevel.Recipe.eval_counts T I read
+ change tag :: 0 :: (SlotLevel.Recipe.counts T I).sites.eval pub state m :: I.lanes.eval pub state m :: (T.tags : Word w) :: I.nextSite.eval pub state m :: [] = _
+ rw [read.lanes_eq,read.nextSite_eq,show (SlotLevel.Recipe.counts T I).sites.eval pub state m =
+ (SlotLevel.sites (T.shape bases lanes) : Word w) from congrArg SlotLevel.Recipe.Counts.sites hc]
+
+include read in
+theorem role_words (layout : Expr) (chosen : Bool) (hl : layout.eval pub state m = (chosen.toNat : Word w))
+ (tag : Word w) :
+ words (roles I layout) tag pub state m = [tag,0,8,(chosen.toNat : Word w),(h.role : Word w)] := by
+ change [tag,0,8,layout.eval pub state m,I.role.eval pub state m] = _
+ rw [hl,read.role_eq]
+
+include read in
+theorem clear_words (tag : Word w) :
+ let s := T.shape bases lanes
+ words (clear T I) tag pub state m =
+ [tag,0,((SlotLevel.owners s + SlotLevel.fields s : ℕ) : Word w), ((h.scratch+SlotLevel.fields s : ℕ) : Word w)] := by
+ intro s
+ let c := SlotLevel.Recipe.counts T I
+ have hc := SlotLevel.Recipe.eval_counts T I read
+ have ho : c.owners.eval pub state m = (SlotLevel.owners s : Word w) := congrArg SlotLevel.Recipe.Counts.owners hc
+ have hf : c.fields.eval pub state m = (SlotLevel.fields s : Word w) := congrArg SlotLevel.Recipe.Counts.fields hc
+ change [tag,0,c.owners.eval pub state m + c.fields.eval pub state m,I.scratch.eval pub state m + c.fields.eval pub state m] = _
+ rw [ho,hf,read.scratch_eq,Nat.cast_add,Nat.cast_add]
+
+/-- Even with arbitrary old scratch contents, the clearing worker establishes
+the zero-counter input to the five native scans and preserves every earlier input table. -/
+theorem clear_run (s : SlotLevel.Shape) (h : SlotLevel.Heads) (mem : Memory w)
+ (fit : SlotLevel.rowsHead s h < 2^w) :
+ let start := h.scratch + SlotLevel.fields s
+ let n := SlotLevel.owners s + SlotLevel.fields s
+ let P := ((template SliceRAM.clearOps 0).instantiate w (fun _ ↦ (start : Word w))).program
+ ∃ rs, runSegment P 8 (some 0) mem (List.replicate n []) = some rs ∧
+ (∀ u : Word w, u.val < n → after mem (eventLog rs) (start+u.val) = 0) ∧
+ (∀ a, a < start ∨ SlotLevel.rowsHead s h ≤ a → after mem (eventLog rs) a = mem a) ∧
+ endState (some 0) rs = some (Fin.ofNat _ n) ∧ rs.length = n ∧
+ ∀ r ∈ rs, r.probes = 1 ∧ r.events.length+1 = 8 := by
+ intro start n P
+ have room : start+n < 2^w := fit
+ have val : (start : Word w).val = start := Nat.mod_eq_of_lt (by omega)
+ obtain ⟨rs,run,zero,frame,cursor,length,work⟩ :=
+ SliceRAM.clearPass_run (start : Word w) n (by rw [val]; omega) (by omega) mem
+ rw [val] at zero frame
+ exact ⟨rs,run,fun u hu ↦ zero _ (by omega) (by omega),fun a ha ↦ frame a ha,cursor,length,work⟩
+
+include read in
+theorem copy_words (tag : Word w) (shape : DescriptorSpace.Shape) (step : ℕ) (c : Fin 6) :
+ let s := T.shape bases lanes
+ let n := if c.val < 3 then SlotLevel.baseArcs s else ShrinkSlots.actualCount s
+ words (copyColumn T I shape step c) tag pub state m =
+ [tag,0,(n : Word w),0,(ShrinkSlots.directory s h w).column c,(LevelFields.incidence shape (step+1) c).eval pub state m] := by
+ intro s n
+ have hc := SlotLevel.Recipe.eval_counts T I read
+ have count : (columnCount T I c).eval pub state m = (n : Word w) := by
+ by_cases hbase : c.val < 3
+ · simp only [columnCount,n,hbase,↓reduceIte]
+ exact congrArg SlotLevel.Recipe.Counts.baseArcs hc
+ · simp only [columnCount,n,hbase,↓reduceIte]
+ exact (ShrinkSlots.Recipe.eval_columns T I read).count
+ change [tag,0,(columnCount T I c).eval pub state m,0,(sourceHeads T I c).eval pub state m,
+ (LevelFields.incidence shape (step+1) c).eval pub state m] = _
+ rw [count,show (sourceHeads T I c).eval pub state m = _ from ShrinkSlots.Recipe.eval_columnHeads T I read c]
+
+end CompressorRecords.ShrinkSlotPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotReference.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotReference.lean
new file mode 100644
index 0000000000..b7b0076469
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotReference.lean
@@ -0,0 +1,288 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotLaunch
+import OAI.Computability.VPVNP.CompressorShrinkSlotFrame
+import OAI.Computability.VPVNP.CompressorShrinkSlotFixedOperands
+import OAI.Computability.VPVNP.CompressorShrinkSelectedReadback
+import OAI.Computability.VPVNP.CompressorShrinkBranchResident
+import OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders
+
+/-!
+# Physical entry values of the selected slot calendar
+
+The planner reads the old level's header and its computed score bit, the two
+separate width and slot table heads, and the next level's six canonical
+incidence heads. The address of the score is inside the selected prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BurstRAM Compression DescriptorSpace PhaseRecipe ShrinkBlockInputs
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w)
+variable (start : ℕ) (L : Layout) (first : ℕ) (pub : Fin 5 → Word w) (st : Word w)
+variable (m : Memory w)
+
+local notation "ev" => Expr.eval pub st m
+local notation "old" => levelStart L (first + i.val)
+local notation "new" => levelStart L (first + (i.val + 1))
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "step" => (10 : Word w)
+local notation "score" => SelectedArena.origin X (ShrinkInput.termHead (w := w) X start) step + 2
+local notation "role" => SelectedArena.roleBase X (ShrinkInput.termHead (w := w) X start) step
+local notation "sh" => ShrinkSlots.levelShape (b := b i) X
+
+/-- The layout cell read by the online planner has its natural address in the
+input arena and strictly precedes the selected role columns. -/
+theorem reference_heads (header : ShrinkHeaderReads.Header i X T start L first m)
+ (entry : LevelFields.Entry L first pub st m) (termRoom : ShrinkInput.termEnd X start 10 < 2 ^ w)
+ (room : SelectedFinish.stop X term step ≤ 2 ^ w) :
+ ev (plan B i).input.oldArc = (role : Word w) ∧
+ (ev (SelectedPlan.layoutCell (selected B i))).val = score ∧
+ start ≤ score ∧ score < role := by
+ have width : 10 < 2 ^ w := by have := header.room; omega
+ have read := (SelectedTailPackets.header_values B i X T start pub st m header entry termRoom
+ width (fun _ => True) trivial (fun _ _ => trivial)).1
+ have roles := SelectedPlan.roles_head _ X _ T term pub st m read
+ have scored := SelectedPlan.score_head _ X _ T term pub st m read
+ have endScore := (ShrinkOutput.old_bounds i X term step).2.2
+ have hword : score < 2 ^ w := endScore.trans_le room
+ have cell : (ev (SelectedPlan.layoutCell (selected B i))).val = score := by
+ change (ev (SelectedPlan.scoreBase (selected B i)) + 2).val = _
+ rw [scored,← (Nat.cast_ofNat (R := Word w) (n := 2)),← Nat.cast_add,
+ Fin.val_natCast]
+ exact Nat.mod_eq_of_lt hword
+ have le := ScorePackets.start_le_term i X start termRoom
+ refine ⟨roles,cell,?_,?_⟩
+ · unfold SelectedArena.origin; omega
+ · unfold SelectedArena.roleBase SelectedArena.placementBase; omega
+
+/-- The shared values needed for all twenty-two native packets, in their reference
+memory. The slot and width tables have the addresses published for this level. -/
+theorem values (sel : SelectedScore.Selection B X) (width slots : ℕ) (dest : IncidenceDirectory w)
+ (header : ShrinkHeaderReads.Header i X T start L first m)
+ (entry : LevelFields.Entry L first pub st m) (termRoom : ShrinkInput.termEnd X start 10 < 2 ^ w)
+ (room : SelectedFinish.stop X term step ≤ 2 ^ w)
+ (chosen : m score = ((SelectedFinish.chosen B X sel).toNat : Word w))
+ (widthCell : m (old + 62) = (width : Word w)) (slotCell : m (old + 63) = (slots : Word w))
+ (destCells : ∀ c : Fin 6, m (new + (54 + c.val)) = dest.column c)
+ (oldRoom : old + 66 ≤ 2 ^ w) (newRoom : new + 66 ≤ 2 ^ w) :
+ ShrinkSlotPackets.Values (plan B i) (Fintype.card X.Base) (2 ^ g)
+ (ShrinkOutput.heads sh role slots) (SelectedFinish.chosen B X sel) width dest pub st m := by
+ have r := header.reads B entry
+ obtain ⟨roleAt,layoutAt,_,_⟩ :=
+ reference_heads B i X T start L first pub st m header entry termRoom room
+ have slotHead : ev (BlockProgram.arena B i.val 3) = (slots : Word w) :=
+ (LevelFields.eval_scalar entry i.val 63 (by omega)).trans slotCell
+ refine ⟨slotInputs_reads B (space B) i X (origin B i) (BlockProgram.arena B i.val 3)
+ pub st m role slots r.vertices r.residual roleAt slotHead,?_,?_,?_⟩
+ · change m (ev (SelectedPlan.layoutCell (selected B i))).val = _
+ rw [layoutAt]; exact chosen
+ · exact (LevelFields.eval_scalar entry i.val 62 (by omega)).trans widthCell
+ · intro c
+ exact (LevelFields.eval_scalar entry (i.val + 1) (54 + c.val) (by have := c.isLt; omega)).trans
+ (destCells c)
+
+/-- Both saved pointer banks determine the two arena heads and the packed
+destination columns. `HeadBank.ofNative` supplies these banks at publication. -/
+theorem values_of_headBanks (sel : SelectedScore.Selection B X)
+ (current next : Fin L.levels) (atCurrent : current.val = first + i.val)
+ (atNext : next.val = first + (i.val + 1)) (oldRows : ℕ)
+ (scalars : L.shape.scalarFields = 54) (tables : L.shape.tables = 6)
+ (fit : endAddress L < 2 ^ w)
+ (header : ShrinkHeaderReads.Header i X T start L first m)
+ (entry : LevelFields.Entry L first pub st m)
+ (termRoom : ShrinkInput.termEnd X start 10 < 2 ^ w)
+ (room : SelectedFinish.stop X term step ≤ 2 ^ w)
+ (chosen : m score = ((SelectedFinish.chosen B X sel).toNat : Word w))
+ (currentHeads : PortRefresh.TraversalHeaders.HeadBank L current oldRows m)
+ (nextHeads : PortRefresh.TraversalHeaders.HeadBank L next (ShrinkSlots.actualCount sh) m) :
+ let width := arrayBase L current + 2 * tableWords L
+ let slots := arrayBase L current + 3 * tableWords L
+ let dest := packedIncidence L w next (ShrinkSlots.actualCount sh)
+ ShrinkSlotPackets.Values (plan B i) (Fintype.card X.Base) (2 ^ g)
+ (ShrinkOutput.heads sh role slots) (SelectedFinish.chosen B X sel) width dest pub st m := by
+ intro width slots dest
+ have extent (j : Fin L.levels) : levelStart L j + 66 < 2 ^ w := by
+ apply lt_of_le_of_lt _ (level_room L fit j)
+ have h : 66 ≤ levelWords L := by unfold levelWords levelHeaderWords; omega
+ change levelsBase L + j.val * levelWords L + 66 ≤ levelsBase L + (j.val + 1) * levelWords L
+ rw [Nat.succ_mul]; omega
+ have oldFit := extent current
+ have newFit := extent next
+ rw [atCurrent] at oldFit; rw [atNext] at newFit
+ apply values B i X T start L first pub st m sel width slots dest header entry termRoom room
+ chosen _ _ _ oldFit.le newFit.le
+ · let col : Fin L.shape.tables := ⟨2,by omega⟩
+ have h := currentHeads.tables col
+ change m (levelStart L current + L.shape.scalarFields + 6 + 2) =
+ ((arrayBase L current + 2 * tableWords L : ℕ) : Word w) at h
+ simpa only [scalars,atCurrent,Nat.add_assoc,width,slots] using h
+ · let col : Fin L.shape.tables := ⟨3,by omega⟩
+ have h := currentHeads.tables col
+ change m (levelStart L current + L.shape.scalarFields + 6 + 3) =
+ ((arrayBase L current + 3 * tableWords L : ℕ) : Word w) at h
+ simpa only [scalars,atCurrent,Nat.add_assoc,width,slots] using h
+ · intro c
+ have h := nextHeads.incidence c
+ rw [show dest = packedIncidence L w next (ShrinkSlots.actualCount sh) from rfl,packed_column]
+ simpa only [incidenceHead,scalars,atNext,Nat.add_assoc] using h
+
+section Widths
+
+open ShrinkSliceSweep
+
+variable (sel : SelectedScore.Selection B X)
+variable {δ : ℝ} (ready : ShrinkMotif.Ready (2 ^ (a i)) (Shrink.colors (a i)) (2 ^ (b i)) δ)
+variable (abs : Word w)
+variable (I : ShrinkABSliceRecipe.Inputs) (ref : Memory w) (ab width slots cap : ℕ)
+variable (r : ShrinkOutput.TablesRun w)
+local notation "alloc" =>
+ ShrinkOutput.splitBank (b := b i) X B.shrink sel term (Fin.val (10 : Word w)) role width
+local notation "post" => r.remainder.postWidths
+
+/-- Exact reference-memory frame from the beginning of the AB calendar up to
+the first native slot packet. It applies to the selected bit and to both headers. -/
+theorem before_slots_frame
+ (run : ShrinkOutput.CompleteTables B i X ready sel term step abs start
+ I pub st ref ab width slots cap m r)
+ (fits : (alloc).Fits) {x : ℕ}
+ (outsideAB : x < ab ∨ ab + (ShrinkInput.plan X start).B *
+ IndexedStarts.capacity (ShrinkBundlePlan.thickCount (a i)) (ShrinkBundlePlan.cap (a i)) ≤ x)
+ (outsideSupply : x < (alloc).widthBase ∨ (alloc).last ≤ x) : post x = m x := by
+ have frame := run.remainder.sweep.frame
+ (fun t _ j => (alloc).rowOutside fits (j,t) x outsideSupply)
+ exact frame.trans (run.abFrame x outsideAB)
+
+/-- Recover the chosen bit in the precise post-width memory passed to the
+slot program, from the resident chosen readback preceding both slice passes. -/
+theorem post_width_chosen
+ (resident : ShrinkOutput.Resident B i X sel term step abs T start width m)
+ (run : ShrinkOutput.CompleteTables B i X ready sel term step abs start
+ I pub st ref ab width slots cap m r)
+ (fits : (alloc).Fits) (early : SelectedFinish.stop X term step ≤ ab)
+ (widthAfter : SelectedFinish.stop X term step ≤ width) :
+ post score = ((SelectedFinish.chosen B X sel).toNat : Word w) := by
+ have low := (ShrinkOutput.old_bounds i X term step).2.2
+ have wa : width ≤ (alloc).widthBase := ShrinkOutput.retained_room X term (step).val role width
+ exact (before_slots_frame B i X start pub st m sel ready abs I ref ab width slots cap r
+ run fits (.inl (low.trans_le early)) (.inl (low.trans_le (widthAfter.trans wa)))).trans
+ resident.chosen
+
+/-- Read the actual slot operands in the memory reached by the AB calendar and
+the four role sweeps. The bound on the number of table words is the uniform
+per-position bound from the block layout. -/
+theorem values_at_slots_framed
+ (current next : Fin L.levels) (atCurrent : current.val = first + i.val)
+ (atNext : next.val = first + (i.val + 1)) (oldRows : ℕ)
+ (scalars : L.shape.scalarFields = 54) (tables : L.shape.tables = 6)
+ (head : start = arrayBase L current) (firstTable : ab = start + tableWords L)
+ (widthTable : width = start + 2 * tableWords L)
+ (slotTable : slots = start + 3 * tableWords L)
+ (size : X.positions * ShrinkLevelSpace.tableFactor S ≤ tableWords L)
+ (fit : endAddress L < 2 ^ w) (pitch : (pub 1 - 1).val < start)
+ (header : ShrinkHeaderReads.Header i X T start L first m)
+ (entry : LevelFields.Entry L first pub st m)
+ (currentHeads : PortRefresh.TraversalHeaders.HeadBank L current oldRows m)
+ (nextHeads : PortRefresh.TraversalHeaders.HeadBank L next (ShrinkSlots.actualCount sh) m)
+ (resident : ShrinkOutput.Resident B i X sel term step abs T start width m)
+ (run : ShrinkOutput.CompleteTables B i X ready sel term step abs start
+ I pub st ref ab width slots cap m r) :
+ ShrinkSlotPackets.Values (plan B i) (Fintype.card X.Base) (2 ^ g)
+ (ShrinkOutput.heads sh role slots) (SelectedFinish.chosen B X sel) width
+ (packedIncidence L w next (ShrinkSlots.actualCount sh)) pub st post ∧
+ (∀ x < start, post x = m x) ∧ (∀ x, new ≤ x → post x = m x) := by
+ have ends := ShrinkLevelSpace.packed_ends S i X start ab width slots w
+ have nextRoom : new < 2 ^ w :=
+ (levelStart_mono L (atNext ▸ next.isLt.le)).trans_lt fit
+ have afterTable : width + tableWords L ≤ new := by
+ let col : Fin L.shape.tables := ⟨2, by omega⟩
+ have h := tableEnd_le_nextLevel L current col
+ change arrayBase L current + 2 * tableWords L + tableWords L ≤
+ levelStart L (current.val + 1) at h
+ rw [← head, ← widthTable, atCurrent, Nat.add_assoc] at h
+ exact h
+ have abBound := ends.2.2.2.2.1
+ have keep : SelectedFinish.stop X term step ≤ ab :=
+ ends.2.2.1.trans (firstTable ▸ Nat.add_le_add_left size _)
+ have tr : ShrinkInput.termEnd X start 10 < 2 ^ w :=
+ ends.2.1.trans_lt (by omega)
+ have wa := ShrinkOutput.width_at_eq i X term step width (by omega)
+ have last : (alloc).last ≤ new := by
+ change ShrinkOutput.slotsBase X
+ (ShrinkOutput.widthBase X (term).val (step).val role width) sh ≤ _
+ rw [wa]
+ exact ends.2.2.2.2.2.1.trans ((Nat.add_le_add_left size _).trans afterTable)
+ have small : 10 < 2 ^ w := by have := header.room; omega
+ have fits : (alloc).Fits :=
+ ⟨(Nat.mod_eq_of_lt small).ge, le_max_left .., ready.count_pos, last.trans_lt nextRoom,
+ by omega⟩
+ have abLast : ab + (ShrinkInput.plan X start).B *
+ IndexedStarts.capacity (ShrinkBundlePlan.thickCount (a i)) (ShrinkBundlePlan.cap (a i))
+ ≤ new := by
+ apply abBound.trans
+ omega
+ have left (x : ℕ) (hx : x < start) : post x = m x := by
+ apply before_slots_frame B i X start pub st m sel ready abs I ref ab width slots cap r run fits
+ · exact .inl (by omega)
+ · apply Or.inl
+ change x < ShrinkOutput.widthBase X (term).val (step).val role width
+ rw [wa]; omega
+ have right (x : ℕ) (hx : new ≤ x) : post x = m x :=
+ before_slots_frame B i X start pub st m sel ready abs I ref ab width slots cap r
+ run fits (.inr (abLast.trans hx)) (.inr (last.trans hx))
+ have oldSpan : levelStart L current + levelHeaderWords L ≤ start := by
+ rw [head]; exact Nat.le_add_right ..
+ have hLen : levelHeaderWords L = 66 := by simp [levelHeaderWords, scalars, tables]
+ have oldBefore : old + 60 < start := by rw [atCurrent, hLen] at oldSpan; omega
+ have postHeader := header.keep_below oldBefore left
+ have postEntry : LevelFields.Entry L first pub st post :=
+ ⟨entry.pointer, (left _ pitch).trans entry.pitch⟩
+ have postOld := currentHeads.keep (fun n hn => left _ (by omega))
+ have postNext := nextHeads.keep (fun n _ => right _ (by rw [atNext]; omega))
+ have chosen := post_width_chosen B i X T start pub st m sel ready abs I ref ab width slots cap r
+ resident run fits keep (by omega)
+ have h := values_of_headBanks B i X T start L first pub st post sel current next atCurrent
+ atNext oldRows scalars tables fit postHeader postEntry tr (by omega) chosen postOld postNext
+ refine ⟨?_, left, right⟩
+ simpa only [slotTable, widthTable, head] using h
+
+/-- The planner values at the first slot packet of the true post-width memory. -/
+theorem values_at_slots
+ (current next : Fin L.levels) (atCurrent : current.val = first + i.val)
+ (atNext : next.val = first + (i.val + 1)) (oldRows : ℕ)
+ (scalars : L.shape.scalarFields = 54) (tables : L.shape.tables = 6)
+ (head : start = arrayBase L current) (firstTable : ab = start + tableWords L)
+ (widthTable : width = start + 2 * tableWords L)
+ (slotTable : slots = start + 3 * tableWords L)
+ (size : X.positions * ShrinkLevelSpace.tableFactor S ≤ tableWords L)
+ (fit : endAddress L < 2 ^ w) (pitch : (pub 1 - 1).val < start)
+ (header : ShrinkHeaderReads.Header i X T start L first m)
+ (entry : LevelFields.Entry L first pub st m)
+ (currentHeads : PortRefresh.TraversalHeaders.HeadBank L current oldRows m)
+ (nextHeads : PortRefresh.TraversalHeaders.HeadBank L next (ShrinkSlots.actualCount sh) m)
+ (resident : ShrinkOutput.Resident B i X sel term step abs T start width m)
+ (run : ShrinkOutput.CompleteTables B i X ready sel term step abs start
+ I pub st ref ab width slots cap m r) :
+ ShrinkSlotPackets.Values (plan B i) (Fintype.card X.Base) (2 ^ g)
+ (ShrinkOutput.heads sh role slots) (SelectedFinish.chosen B X sel) width
+ (packedIncidence L w next (ShrinkSlots.actualCount sh)) pub st post :=
+ (values_at_slots_framed B i X T start L first pub st m sel ready abs I ref ab width slots cap r
+ current next atCurrent atNext oldRows scalars tables head firstTable widthTable slotTable size
+ fit pitch header entry currentHeads nextHeads resident run).1
+
+end Widths
+
+end CompressorRecords.ShrinkSlotCalendar
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotRetention.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotRetention.lean
new file mode 100644
index 0000000000..c17fa3b80f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotRetention.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.CompressorShrinkOutputAccess
+import OAI.Computability.VPVNP.CompressorShrinkLevelSpace
+import OAI.Computability.VPVNP.CompressorSlotCopiedTables
+
+/-!
+# Retaining the inverse endpoint table across canonical copies
+
+The selected allocation fits in a table of the current descriptor level.
+The canonical output is in the incidence block of the next level, after
+the end of the entire current table. Thus the final six copy passes
+preserve both endpoint lookup directions for later descriptor queries.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkOutput
+
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion Slots SlotLevel ShrinkSlots BurstRAM
+
+variable {a b g w : ℕ} {k : Type*} [_root_.Field k] {factor δ : ℝ}
+variable (X : State a (packingLaneBits a g))
+variable (F : FixedBlock k demandSource demandTarget Compression.ShrinkMotif.supply
+ (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection F)
+variable (term : Word w) (stride role retained : ℕ)
+
+local notation "s" => levelShape (b := b) X
+local notation "h" => slotHeads (b := b) X term.val stride role retained
+local notation "last" => stop (b := b) X term.val stride role retained
+local notation "side" => selectedLayout X F sel
+
+/-- The sorted lookup arrays in a separately placed slot workspace are still
+present after its canonical destination has been filled. -/
+theorem Constructed.retained_after_copy_at (slotStart : ℕ) (gap : (h).role ≤ slotStart)
+ (endFit : finish s (heads s role slotStart) < 2^w) {initial out : Memory w} {r : Build.Construction w}
+ (c : Constructed X F ready sel term stride role retained initial out r slotStart)
+ (hw : FitsWords (b := b) X F term stride role retained)
+ (L : DescriptorSpace.Layout) (level : Fin L.levels)
+ (room : DescriptorSpace.endAddress L < 2^w) (cap : actualCount s ≤ DescriptorSpace.slotCapacity L) :
+ let h₀ := heads s role slotStart
+ let Y := X.shrinkNext F ready sel
+ let U := DescriptorSpace.packedIncidence L w level (actualCount s)
+ let T := directory s h₀ w
+ let start := DescriptorSpace.incidenceStart L level
+ let m := after out (eventLog r.all)
+ let copies := CopyIncidence.reports Y T U CopyIncidence.allColumns m
+ (finish s h₀ ≤ start ∨ start+6*actualCount s ≤ rowsHead s h₀) →
+ Build.OrderedTables X ready side h₀ (after out (eventLog (r.all++copies))) := by
+ intro h₀ Y U T start m copies apart
+ exact Build.retained_after_copy X F ready sel h₀ out r L level room endFit cap
+ (c.retained_tables_at X F ready sel term stride role retained slotStart gap endFit hw) apart
+
+/-- Retention on the actual report memory at the end of all 22 stages. -/
+theorem Constructed.retained_after_copy {initial out : Memory w} {r : Build.Construction w}
+ (c : Constructed X F ready sel term stride role retained initial out r)
+ (hw : FitsWords (b := b) X F term stride role retained)
+ (L : DescriptorSpace.Layout) (level : Fin L.levels)
+ (room : DescriptorSpace.endAddress L < 2^w) (cap : actualCount s ≤ DescriptorSpace.slotCapacity L) :
+ let Y := X.shrinkNext F ready sel
+ let U := DescriptorSpace.packedIncidence L w level (actualCount s)
+ let T := directory s h w
+ let start := DescriptorSpace.incidenceStart L level
+ let m := after out (eventLog r.all)
+ let copies := CopyIncidence.reports Y T U CopyIncidence.allColumns m
+ (last ≤ start ∨ start+6*actualCount s ≤ rowsHead s h) →
+ Build.OrderedTables X ready side h (after out (eventLog (r.all++copies))) :=
+ c.retained_after_copy_at X F ready sel term stride role retained (h).role le_rfl hw.room hw L level room cap
+
+/-- The canonical following-level destination comes after every retained slot
+array when the current table uses the uniform shrinking capacity. -/
+theorem packed_before_next (S : BlockSchedule k) (i : Fin S.steps) {g w : ℕ}
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (L : DescriptorSpace.Layout) (current next : Fin L.levels) (table : Fin L.shape.tables)
+ (later : current < next) (sites : X.positions ≤ L.positions)
+ (capacity : ShrinkLevelSpace.tableFactor S ≤ L.shape.slots*L.shape.fields) :
+ let start := DescriptorSpace.tableBase L current table
+ let term := ShrinkInput.termHead (w := w) X start
+ let stride := Fin.ofNat (2^w) 10
+ let role := SelectedArena.roleBase X term stride
+ let retained := SelectedFinish.stop X term stride
+ stop (b := S.degreeExponent i.succ) X term.val stride.val role retained ≤
+ DescriptorSpace.incidenceStart L next := by
+ intro start term stride role retained
+ have slot := (ShrinkLevelSpace.packed_ends S i X start start start start w).2.2.2.1
+ have fit : X.positions*ShrinkLevelSpace.tableFactor S ≤ DescriptorSpace.tableWords L := by
+ change _ ≤ L.positions*L.shape.slots*L.shape.fields
+ rw [Nat.mul_assoc]; exact Nat.mul_le_mul sites capacity
+ exact slot.trans ((Nat.add_le_add_left fit start).trans ((DescriptorSpace.tableEnd_le_nextLevel L current table).trans
+ ((DescriptorSpace.levelStart_mono L (show current.val+1 ≤ next.val from later)).trans (Nat.le_add_right _ _))))
+
+/-- The same separation holds when the slot scratch is a separate table in
+the current level, as in the fixed block planner's slot-arena expression. -/
+theorem separate_before_next (S : BlockSchedule k) (i : Fin S.steps) {g : ℕ}
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (L : DescriptorSpace.Layout) (current next : Fin L.levels) (table : Fin L.shape.tables)
+ (role : ℕ) (later : current < next) (sites : X.positions ≤ L.positions)
+ (capacity : ShrinkLevelSpace.tableFactor S ≤ L.shape.slots*L.shape.fields) :
+ let sh := levelShape (b := S.degreeExponent i.succ) X
+ let start := DescriptorSpace.tableBase L current table
+ finish sh (heads sh role start) ≤ DescriptorSpace.incidenceStart L next := by
+ intro sh start
+ have rate : ShrinkLevelSpace.slotRate (S.degreeExponent i.castSucc) (S.degreeExponent i.succ) ≤
+ ShrinkLevelSpace.tableFactor S := by
+ apply le_trans _ (ShrinkLevelSpace.levelRate_le_tableFactor S i)
+ unfold ShrinkLevelSpace.levelRate; omega
+ have fit : X.positions*ShrinkLevelSpace.slotRate (S.degreeExponent i.castSucc) (S.degreeExponent i.succ) ≤
+ DescriptorSpace.tableWords L := by
+ change _ ≤ L.positions*L.shape.slots*L.shape.fields
+ rw [Nat.mul_assoc]; exact Nat.mul_le_mul sites (rate.trans capacity)
+ exact (ShrinkLevelSpace.slot_end (b := S.degreeExponent i.succ) X role start).trans
+ ((Nat.add_le_add_left fit start).trans ((DescriptorSpace.tableEnd_le_nextLevel L current table).trans
+ ((DescriptorSpace.levelStart_mono L (show current.val+1 ≤ next.val from later)).trans (Nat.le_add_right _ _))))
+
+end CompressorRecords.ShrinkOutput
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotScheduledRuns.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotScheduledRuns.lean
new file mode 100644
index 0000000000..e6c9d9270a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotScheduledRuns.lean
@@ -0,0 +1,214 @@
+import OAI.Computability.VPVNP.CompressorSlotBuild
+import OAI.Computability.VPVNP.CompressorShrinkSlotPlan
+import OAI.Computability.VPVNP.CompressorSourceWalk
+import OAI.Computability.VPVNP.CompressorRecordsCopyIncidence
+
+/-!
+# Source runs of the shrinking slot program
+
+The slot builder's reports follow the same sequence of workers as the
+descriptor planner. The first sixteen phases prepare and fill the physical
+directory. The last six copy it into the next level's canonical arrays.
+Each worker starts at zero in the actual memory left by the preceding phase.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlotPlan.Scheduled
+
+open BurstRAM PhaseRecipe BlockPlanner ShrinkSlots SlotLevel
+open scoped Fin.CommRing
+
+/-- The operands compiled into this occurrence of the slot plan. -/
+structure Plan where
+ /-- Fixed slot geometry and role subdivision counts for this scheduled shrinking step. -/
+ template : ShrinkSlotPlan.Template
+ /-- Expressions locating the dynamic dimensions and working tables of the slot builder. -/
+ input : Inputs
+ /-- Expression reading the layout side selected by the shrink score. -/
+ layout : Expr
+ /-- Expression locating the surviving-width table used to fill the output slot widths. -/
+ split : Expr
+ /-- Descriptor shape used to locate the next level's canonical incidence pointers. -/
+ space : DescriptorSpace.Shape
+ /-- Substep number used to locate the level receiving the six completed columns. -/
+ step : ℕ
+
+/-- A scheduled slot-builder stage for publishing subdivision data, preparing lookups, building
+the directory or copying one incidence column. -/
+inductive Stage where
+ | subdivision (i : Fin 4)
+ | roles | cyclic | clear
+ | core (p : SlotLevel.Phase)
+ | output (p : ShrinkSlots.Recipe.Phase)
+ | copy (c : Fin 6)
+ deriving DecidableEq
+
+/-- Compile a slot-builder stage into the corresponding planned worker visit and operands. -/
+def Stage.visit (P : Plan) : Stage → Visit
+ | .subdivision i => ShrinkSlotPlan.subdivision P.template P.input i
+ | .roles => ShrinkSlotPlan.roles P.input P.layout
+ | .cyclic => ShrinkSlotPlan.cyclic P.template P.input
+ | .clear => ShrinkSlotPlan.clear P.template P.input
+ | .core p => ShrinkSlotPlan.core P.template P.input p
+ | .output p => ShrinkSlotPlan.output P.template P.input P.split p
+ | .copy c => ShrinkSlotPlan.copyColumn P.template P.input P.space P.step c
+
+/-- Publish four subdivision counts, prepare the role and cyclic-site lookups, then clear the
+append counters. -/
+def preparationOrder : List Stage := List.ofFn Stage.subdivision ++ [.roles,.cyclic,.clear]
+
+/-- The five sorted-slot core phases followed by base inverse, actual outgoing, actual incoming
+and width publication. -/
+def directoryOrder : List Stage := [.core .genuineOwners,.core .dummyOwners,.core .appendFields,
+ .core .invertFields,.core .baseMatching,.output .baseInverse,.output .actualOut,.output .actualIn,.output .widths]
+
+/-- The preparation and directory phases in the order that builds all six output columns. -/
+def constructionOrder := preparationOrder ++ directoryOrder
+
+/-- The complete shrinking slot schedule, ending with the six copies into the next level's
+canonical arrays. -/
+def order := constructionOrder ++ CopyIncidence.allColumns.map Stage.copy
+
+/-- The stage enumeration uses exactly the same chronological visits as the
+native block planner, including its six per-column destinations. -/
+theorem order_visits (P : Plan) :
+ order.map (Stage.visit P) = visits P.template P.input P.layout P.split P.space P.step := rfl
+
+/-- Exclusive worker cursor for each stage, using its actual site, owner, field or
+incidence-column count. -/
+def Stage.limit (s : Shape) : Stage → ℕ
+ | .subdivision _ => 1
+ | .roles => 8
+ | .cyclic => sites s
+ | .clear => owners s+fields s
+ | .core p => SlotLevel.limit s p
+ | .output p => ShrinkSlots.Recipe.limit s p
+ | .copy c => if c.val < 3 then baseArcs s else actualCount s
+
+/-- Number of public operand words expected by the worker for this scheduled stage. -/
+abbrev Stage.arity : Stage → ℕ
+ | .subdivision _ | .roles => 2
+ | .cyclic | .copy _ => 3
+ | .clear => 1
+ | .core p => SlotLevel.arity p
+ | .output p => ShrinkSlots.Recipe.arity p
+
+theorem Stage.params (P : Plan) (j : Stage) : (j.visit P).worker.params = j.arity := by
+ cases j with
+ | core p => cases p <;> rfl
+ | output p => cases p <;> rfl
+ | _ => rfl
+
+variable {w : ℕ}
+
+/-- Instantiate the stage's physical operands from the slot shape and table heads, chosen
+layout, split widths and destination directory. -/
+def Stage.bank (s : Shape) (h : Heads) (chosen : Bool) (splitHead : ℕ) (dest : IncidenceDirectory w) :
+ (j : Stage) → Fin j.arity → Word w
+ | .subdivision i => Preparation.publishBank h.subdivisions s.subdivisions w i
+ | .roles => Preparation.roleBank h chosen w
+ | .cyclic => Preparation.cyclicBank s h w
+ | .clear => fun _ ↦ Fin.ofNat _ (h.scratch+fields s)
+ | .core p => SlotLevel.bank s h w p
+ | .output p => ShrinkSlots.Recipe.bank s h splitHead w p
+ | .copy c => CopyIncidence.copyPublic ((directory s h w).column c) (dest.column c)
+
+/-- Expression evaluation at the planner cursor supplies the exact bank and
+exclusive stop used by the physical worker. -/
+theorem Stage.words (P : Plan) (j : Stage) {pub : Fin 5 → Word w} {state : Word w} {m : Memory w}
+ {bases lanes : ℕ} {h : Heads} {chosen : Bool} {splitHead : ℕ} {dest : IncidenceDirectory w}
+ (read : SlotLevel.Recipe.Reads P.input pub state m bases lanes h)
+ (layout : P.layout.eval pub state m = (chosen.toNat : Word w))
+ (split : P.split.eval pub state m = (splitHead : Word w))
+ (columns : ∀ c, (LevelFields.incidence P.space (P.step+1) c).eval pub state m = dest.column c)
+ (tag : Word w) :
+ let s := P.template.shape bases lanes
+ ShrinkSlotPlan.words (j.visit P) tag pub state m =
+ tag :: 0 :: (j.limit s : Word w) :: List.ofFn (j.bank s h chosen splitHead dest) := by
+ intro s
+ cases j with
+ | subdivision i => exact subdivision_words P.template P.input read tag i
+ | roles => exact role_words P.input read P.layout chosen layout tag
+ | cyclic => exact cyclic_words P.template P.input read tag
+ | clear => exact clear_words P.template P.input read tag
+ | core p => exact core_words P.template P.input read p tag
+ | output p => exact output_words P.template P.input read P.split split p tag
+ | copy c =>
+ have eqn := copy_words P.template P.input read tag P.space P.step c
+ rw [columns] at eqn
+ exact eqn
+
+/-- The visit's straight-line program has one unreachable reject instruction.
+All preceding instructions, including the return, form its checked fuel bound. -/
+def Source (P : Plan) (s : Shape) (h : Heads) (chosen : Bool) (splitHead : ℕ)
+ (dest : IncidenceDirectory w) (j : Stage) (m : Memory w) (rs : List (Report w)) : Prop :=
+ let v := j.visit P
+ let bank := (j.bank s h chosen splitHead dest) ∘ Fin.cast (j.params P)
+ let M := (v.worker.table.instantiate w bank).program
+ runSegment M (v.worker.pcs-1) (some 0) m (List.replicate (j.limit s) []) = some rs
+
+variable (P : Plan) (s : Shape) (h : Heads) (chosen : Bool) (splitHead : ℕ) (dest : IncidenceDirectory w)
+local notation "src" => Source P s h chosen splitHead dest
+
+private theorem preparation_sources (r : Preparation.Reports w) (m : Memory w)
+ (hr : r.Native s h chosen m) : SourceWalk src preparationOrder m r.all := by
+ obtain ⟨hp,hr,hn,hc⟩ := hr
+ have put (i : Fin 4) : src (.subdivision i) (after m (eventLog ((List.ofFn r.publish).take i.val))) [r.publish i] :=
+ hp i
+ have p₀ : SourceWalk src [.subdivision 0] m [r.publish 0] := .singleton (put 0)
+ have pubs : SourceWalk src (List.ofFn Stage.subdivision) m (List.ofFn r.publish) :=
+ ((p₀.append (.singleton (put 1))).append (.singleton (put 2))).append (.singleton (put 3))
+ let mp := after m (eventLog (List.ofFn r.publish))
+ have rest : SourceWalk src [.roles,.cyclic,.clear] mp (r.roles++(r.cyclic++r.clear)) :=
+ .next hr (.next hn (.singleton hc))
+ simpa only [preparationOrder,Preparation.Reports.all,List.append_assoc] using pubs.append rest
+
+private theorem directory_sources (r : Build.Passes w) (m : Memory w) (hr : r.Native s h splitHead m) :
+ SourceWalk src directoryOrder m r.all := by
+ obtain ⟨⟨hg,hd,ha,hi,hb⟩,⟨hbi,ho,hinc⟩,hw⟩ := hr
+ simp only [Build.Passes.all,SlotLevel.Reports.all,MateReports.all,List.append_assoc]
+ exact .next hg (.next hd (.next ha (.next hi (.next hb (.next hbi (.next ho (.next hinc (.singleton hw))))))))
+
+/-- Extraction of the original reports of all sixteen construction phases,
+with the physical banks and fresh cursors of their compiled workers. -/
+theorem construction_sources (r : Build.Construction w) (m : Memory w) (hr : r.Native s h splitHead chosen m) :
+ SourceWalk src constructionOrder m r.all :=
+ (preparation_sources P s h chosen splitHead dest r.prepare m hr.1).append
+ (directory_sources P s h chosen splitHead dest r.passes (r.prepare.final m) hr.2)
+
+variable {a l : ℕ} (Y : Compression.State a l)
+
+/-- Copy the completed columns using their actual base or lane-slot row count. -/
+theorem copy_sources {cs : List (Fin 6)} {m : Memory w} {rs : List (Report w)}
+ (lengths : ∀ c, CopyIncidence.rows Y c = (Stage.copy c).limit s)
+ (hr : CopyIncidence.Runs Y (directory s h w) dest cs m rs) :
+ SourceWalk src (cs.map Stage.copy) m rs := by
+ induction hr with
+ | nil => exact .done _
+ | cons c hr _ ih =>
+ rw [lengths] at hr
+ exact .next hr ih
+
+/-- The twenty-two-stage source walk retains every report in construction
+and copying. The destination represents the selected next state at the end. -/
+theorem sources (r : Build.Construction w) (m : Memory w)
+ (hr : r.Native s h splitHead chosen m)
+ (lengths : ∀ c, CopyIncidence.rows Y c = (Stage.copy c).limit s)
+ (reg : CopyIncidence.Regions Y (directory s h w) dest)
+ (rep : (directory s h w).Represents Y (after m (eventLog r.all))) :
+ let built := after m (eventLog r.all)
+ let copies := CopyIncidence.reports Y (directory s h w) dest CopyIncidence.allColumns built
+ SourceWalk src order m (r.all++copies) ∧ dest.Represents Y (after built (eventLog copies)) := by
+ intro built copies
+ obtain ⟨copied,rep',_⟩ := CopyIncidence.copy_directory Y (directory s h w) dest built reg rep
+ exact ⟨(construction_sources P s h chosen splitHead dest r m hr).append
+ (copy_sources P s h chosen splitHead dest Y lengths copied),rep'⟩
+
+end CompressorRecords.ShrinkSlotPlan.Scheduled
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSlotWindow.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotWindow.lean
new file mode 100644
index 0000000000..138f81aec0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSlotWindow.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.CompressorBlockIndex
+import OAI.Computability.VPVNP.CompressorShrinkSlotScheduledRuns
+import OAI.Computability.VPVNP.CompressorScriptWindow
+
+/-! # The selected slot program's exact ordinal interval in the full block -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkSlotCalendar
+
+open BlockPlanner Compression ShrinkSlotPlan.Scheduled
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+
+/-- The fixed descriptor shape for placing this substep's slot calendar in the complete block
+program. -/
+abbrev space := BlockProgram.geometry B
+/-- Address expression for the first scratch table in this shrinking substep. -/
+abbrev origin := BlockProgram.arena B i.val 0
+/-- The selected-placement input expressions at this substep's scratch origin, including the
+source of its layout bit. -/
+abbrev selected := ShrinkBlockInputs.selectedInputs B (space B) i (origin B i)
+
+/-- The slot plan instantiated for this block, reading the selected layout and surviving widths
+and using the reserved slot arena to build the next level. -/
+def plan : Plan :=
+ ⟨ShrinkBlockInputs.slotTemplate i,
+ ShrinkBlockInputs.slotInputs B (space B) i (origin B i) (BlockProgram.arena B i.val 3),
+ SelectedPlan.layout (selected B i),BlockProgram.arena B i.val 2,space B,i.val⟩
+
+/-- The slot interval follows the resident and slice phases of this exact
+substep. The following metadata and pointer publishers are outside it. -/
+def window : Window (BlockProgram.script B) (order.map (Stage.visit (plan B i))) where
+ before := BlockIndex.earlier B i ++ ShrinkBlockInputs.beforeSlices B (space B) i (origin B i) ++
+ ShrinkResidentsPlan.visits (selected B i) (BlockProgram.arena B i.val 5) (LevelFields.atLevel i.val)
+ (ShrinkBundlePlan.absoluteCD i.val (ShrinkBlockInputs.a i) (origin B i)) (ShrinkBlockInputs.a i) ++
+ BlockSlices.visits B (space B) i (origin B i) (BlockProgram.arena B i.val 1) (BlockProgram.arena B i.val 2)
+ after := BlockMetadata.visits (space B) i.val B.recordLimit (slotDegree S) .shrink
+ (.shrink (ShrinkBlockInputs.a i) (selected B i)) ++
+ BlockProgram.termPointers i.val (selected B i).termBase (.lit (selected B i).termStride)
+ (SelectedPlan.layout (selected B i)) (ShrinkBundlePlan.absoluteCD i.val (ShrinkBlockInputs.a i) (origin B i)) ++
+ BlockDataHeads.visits B (space B) i (origin B i) (BlockProgram.arena B i.val 1)
+ (BlockProgram.arena B i.val 2) (BlockProgram.arena B i.val 3) ++ BlockIndex.later B i
+ block := by
+ change BlockProgram.block B = _
+ rw [BlockIndex.split_block B i,order_visits]
+ simp only [BlockProgram.shrink,ShrinkBlockInputs.slots,plan,space,origin,selected,List.append_assoc]
+
+end CompressorRecords.ShrinkSlotCalendar
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSourceWorker.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSourceWorker.lean
new file mode 100644
index 0000000000..e57f2a76e8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSourceWorker.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.CompressorSelectorSitePacket
+import OAI.Computability.VPVNP.CompressorShrinkPhysicalWorkerInput
+import OAI.Computability.VPVNP.CompressorShrinkTermForward
+
+/-! # Installing the actual shrinking term worker
+
+The gather establishes the physical demand rows in its post-memory. The
+next visit has the fixed shrinking motif table and the two strided address
+regions selected by that same input prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkCurrentBranch
+
+open BurstRAM Compression DescriptorSpace BlockPlanner SelectedTerms PairSimulation.LocalHistory
+open scoped Classical Fin.CommRing
+attribute [local irreducible] BlockProgram.script
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+variable (T : IncidenceDirectory w) (start fuel : ℕ) {m : Memory w} (p : ShrinkBranch.Prefix X T start fuel m)
+variable (fit : ShrinkBranch.PrefixFits B X T start (10 : Word w) fuel)
+
+local notation "o" => (PassOrigin.shrink i rfl X : PassOrigin B f hf (B.shrinkPassAt f hf i rfl X))
+local notation "I" => workerInput B f hf i X T start fuel p fit
+local notation "src" => ShrinkInput.demandHead (w := w) X start
+local notation "dst" => ShrinkInput.termHead (w := w) X start
+local notation "N" => ShrinkTermInputs.motifCount X
+local notation "script" => BlockProgram.script B
+
+private theorem start_le_dense (space : ShrinkInput.termEnd X start 10 < 2^w) : start ≤ (src).val := by
+ have earlier : start ≤ ShrinkInput.widthBase X start := by
+ have greedy := GreedyArena.greedyStop_eq start (Fintype.card X.Base) (S.degreeExponent i.castSucc)
+ change start ≤ (((((ShrinkInput.placementBase X start+_)+_)+_)+_)+_)+_
+ change ShrinkInput.placementBase X start = start+_+_ at greedy
+ omega
+ have bound : ShrinkInput.stop X start < 2^w := by unfold ShrinkInput.termEnd at space; omega
+ change start ≤ (ShrinkInput.stop X start) % 2^w
+ rw [Nat.mod_eq_of_lt bound]
+ change start ≤ ShrinkInput.widthBase X start+_+_
+ omega
+
+set_option maxHeartbeats 1000000 in
+/-- The post-gather worker, table, operand bank and instruction clock of
+the shrinking selector packet agree with its installed source worker. -/
+theorem sourceWorker (L : Layout) (selection : X.ShrinkSelection B.shrink) (rs : List (Report w))
+ (dataStart : levelStart L 0 ≤ start)
+ (width : SelectedTermWorker.fitConstant B+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) :
+ ScheduledTrace.SelectorSite.SourceWorker (I) L
+ (ShrinkTermOnline.packet B i X T start selection fuel .select p.beforeTerm rs) := by
+ have ten : (10 : Word w).val = 10 := Nat.mod_eq_of_lt (fit.wide.trans_lt (10 : Word w).isLt)
+ have space := fit.termRoom
+ rw [ten] at space
+ have bounds := ShrinkInput.termLayout X T start 10 space
+ have sep := bounds.2.2.1
+ have room := bounds.2.2.2
+ have head : levelStart L 0 ≤ (src).val := dataStart.trans (start_le_dense i X start space)
+ have dest : levelStart L 0 ≤ (dst).val := head.trans ((Nat.le_add_right ..).trans sep)
+ have fits : N < 2^w := by omega
+ have code : (script).catalog (ShrinkTermOnline.index B i .select) =
+ TermWorker.motifPass (grid o).block (grid o).demandOrder.entries (grid o).e :=
+ congrArg BlockPlanner.Visit.worker (ShrinkTermOnline.index_visit B i .select)
+ refine ⟨code,rfl,?_,?_,rfl,width,?_,?_,fun _ _ => rfl⟩
+ · exact Nat.mod_eq_of_lt fits
+ · intro j
+ rfl
+ · intro j
+ change levelStart L 0 ≤ ((src).val+j.val*2)%(2^w)
+ have hj := Nat.mul_le_mul_right 2 (show j.val ≤ N from j.isLt.le)
+ rw [Nat.mod_eq_of_lt (by omega)]
+ exact head.trans (Nat.le_add_right ..)
+ · intro j
+ change levelStart L 0 ≤ ((dst).val+j.val*10)%(2^w)
+ have hj := Nat.mul_le_mul_right 10 (show j.val ≤ N from j.isLt.le)
+ rw [Nat.mod_eq_of_lt (by omega)]
+ exact dest.trans (Nat.le_add_right ..)
+
+end CompressorRecords.ShrinkCurrentBranch
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSuccessorIndex.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSuccessorIndex.lean
new file mode 100644
index 0000000000..f0fbe913b6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSuccessorIndex.lean
@@ -0,0 +1,32 @@
+import OAI.Computability.VPVNP.PairVertexLevelSchedule
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open Compression PairSimulation.VertexLevel
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+variable {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T h X).Choices)
+local notation "passes" => executeLevels B f hf T h X z
+
+/-- Every shrinking pass has a following pass on its selected branch. -/
+theorem executeLevels_shrink_succ_lt (i : Fin (passes).length)
+ (shrink : passes[i].origin.ordinal < S.steps) : i.val + 1 < (passes).length := by
+ rw [selected_pass_ordinal B f hf T h X z i] at shrink
+ by_contra! last
+ have finalIndex : i.val + 1 = (passes).length := by have := i.isLt; omega
+ have zero : (i.val + 1) % (S.steps + 1) = 0 := by
+ rw [finalIndex, selected_pass_count B f hf T h X z, Nat.mul_mod_left]
+ rw [← Nat.mod_add_mod, Nat.mod_eq_of_lt (Nat.add_lt_add_right shrink 1)] at zero
+ omega
+
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSurvivingOperands.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSurvivingOperands.lean
new file mode 100644
index 0000000000..0ba8d725cd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSurvivingOperands.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.CompressorShrinkSelectedReadback
+import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables
+import OAI.Computability.VPVNP.CompressorShrinkBundleAbsolute
+
+/-! # Operands of the four surviving-role visits
+
+The planner computes the address of the chosen layout from the old level
+header. The native worker loads the layout at this address on each call.
+All reads made while preparing the packet lie below table zero, including
+the pointer to the width rectangle in table two.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkSurvivingOperands
+
+open BurstRAM Compression BlockPlanner PhaseRecipe DescriptorSpace ShrinkBlockInputs ShrinkSliceSweep
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (inc : IncidenceDirectory w) (start : ℕ)
+variable (sel : SelectedScore.Selection B X) (width : ℕ)
+variable (pub : Fin 5 → Word w) (st : Word w) (m : Memory w)
+local notation "F" => BlockProgram.geometry B
+local notation "origin" => BlockProgram.arena B i.val 0
+local notation "widthArena" => BlockProgram.arena B i.val 2
+local notation "chosen" => selectedInputs B F i origin
+local notation "heads" => BlockSlices.survivingHeads B F i origin widthArena
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "step" => (10 : Word w)
+local notation "score" => (SelectedArena.origin X term step + 2 : ℕ)
+local notation "bank" => ShrinkOutput.splitBank (b := b i) X B.shrink sel term
+ (Fin.val step) (SelectedArena.roleBase X term step) width
+local notation "abs" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w
+
+/-- The published scalar and table cells supply the exact stop and all eleven
+native operands for each role. The support bound allows reuse after the AB
+and surviving scans write in later tables. -/
+theorem fields {L : Layout} {first : ℕ}
+ (header : ShrinkHeaderReads.Header i X inc start L first m)
+ (entry : LevelFields.Entry L first pub st m) (termRoom : ShrinkInput.termEnd X start 10 < 2 ^ w)
+ (widthAfter : SelectedFinish.stop X term step ≤ width)
+ (widthCell : m (levelStart L (first + i.val) + 62) = (width : Word w))
+ (headerBelow : levelStart L (first + i.val) + 62 < start)
+ (pitchLo : (pub 1 - 1).val < start) (D : ℕ → Prop) (pitchD : D (pub 1 - 1).val)
+ (dataD : ∀ x, levelStart L 0 ≤ x → D x) (role : Fin 4) :
+ let v := SurvivingNative.visits (slotTemplate i).subdivisions heads role
+ (v.initial.eval pub st m = 0 ∧
+ v.stop.eval pub st m = ((ShrinkOutput.motifCount X * (bank).subdiv role : ℕ) : Word w) ∧
+ (fun j => (v.params j).eval pub st m) = SurvivingNative.params bank role abs (score : Word w)) ∧
+ HeaderOperands.Supported (fun x => D x ∧ x < start) pub st m v := by
+ intro v
+ let R := fun x => D x ∧ x < start
+ have firstLo := levelStart_mono L (Nat.zero_le (first+i.val))
+ have startFit := (ScorePackets.start_le_term i X start termRoom).trans_lt (term).isLt
+ have cell (n : ℕ) (hn : n ≤ 62) : R (levelStart L (first+i.val)+n) :=
+ ⟨dataD _ (firstLo.trans (Nat.le_add_right ..)),by omega⟩
+ have pitch : R (pub 1 - 1).val := ⟨pitchD,pitchLo⟩
+ have ten : 10 < 2 ^ w := by have := header.room; omega
+ obtain ⟨read,support⟩ := SelectedTailPackets.header_values B i X inc start pub st m header entry
+ termRoom ten R pitch (fun n hn => cell n (by omega))
+ have absolute := (ShrinkBundlePlan.head_values X (header.reads B entry)).absoluteCD
+ have widthEq := ShrinkOutput.width_at_eq i X term step width widthAfter
+ have widthValue : (widthArena).eval pub st m = (width : Word w) :=
+ (LevelFields.eval_scalar entry i.val 62 (by omega)).trans widthCell
+ have motifEq : ShrinkOutput.motifCount X = SelectedArena.motifs X := ShrinkTermRecipe.count_card X
+ have scoreValue : (SelectedPlan.layoutCell chosen).eval pub st m = (score : Word w) := by
+ change (SelectedPlan.scoreBase chosen).eval pub st m + 2 = _
+ rw [SelectedPlan.score_head chosen X _ inc term pub st m read,Nat.cast_add,Nat.cast_ofNat]
+ rfl
+ have intervalValue : (heads).intervalBase.eval pub st m = ((bank).widthEnd : Word w) := by
+ change (widthArena).eval pub st m +
+ (4*(chosen).oldSlots.eval pub st m)*(BlockSlices.subdivisionSum i : Word w) =
+ ((ShrinkOutput.widthBase X (term).val (step).val (SelectedArena.roleBase X term step) width +
+ (DemandRAM.absoluteCount X*4)*BlockSlices.subdivisionSum i : ℕ) : Word w)
+ rw [widthValue,widthEq,read.slots,DemandRAM.count_eq X]
+ push_cast
+ ring
+ constructor
+ · apply SurvivingNative.visit_fields bank heads role pub st abs (score : Word w) m
+ · exact read.motifs.trans (congrArg (fun n : ℕ => (n : Word w)) motifEq.symm)
+ · exact read.term.trans (Fin.cast_val_eq_self _).symm
+ · exact (Fin.cast_val_eq_self _).symm
+ · exact absolute
+ · exact scoreValue
+ · rfl
+ · exact widthValue.trans (congrArg (fun n : ℕ => (n : Word w)) widthEq.symm)
+ · exact intervalValue
+ · let safe := Expr.ReadsFrom R pub st m
+ have widthRead : safe widthArena :=
+ GreedyVisit.scalar_support R L first i.val 62 entry pitch (cell 62 le_rfl) (by omega)
+ have absStage := ShrinkBundlePackets.expr_reads B i header entry R pitch
+ (fun n hn => cell n (by omega)) .absolute
+ have cdStage := ShrinkBundlePackets.expr_reads B i header entry R pitch
+ (fun n hn => cell n (by omega)) .motifPrefix
+ have absRead : safe (heads).absolute := ⟨absStage.params (4 : Fin 7),cdStage.stop⟩
+ have layoutRead : safe (heads).layout := ⟨⟨support.term,support.motifs,trivial⟩,trivial⟩
+ have intervalRead : safe (heads).intervalBase := ⟨widthRead,⟨trivial,support.slots⟩,trivial⟩
+ refine ⟨trivial,⟨support.motifs,trivial⟩,?_⟩
+ intro j
+ change Fin 11 at j
+ fin_cases j
+ exacts [True.intro,True.intro,support.term,True.intro,absRead,layoutRead,True.intro,widthRead,
+ True.intro,intervalRead,True.intro]
+
+end CompressorRecords.ShrinkSurvivingOperands
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkSurvivingPackets.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkSurvivingPackets.lean
new file mode 100644
index 0000000000..59ecd7b566
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkSurvivingPackets.lean
@@ -0,0 +1,251 @@
+import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables
+import OAI.Computability.VPVNP.CompressorShrinkSlotPacketSpace
+import OAI.Computability.VPVNP.CompressorShrinkABSliceWindow
+import OAI.Computability.VPVNP.CompressorShrinkPreparationAccess
+import OAI.Computability.VPVNP.CompressorSourceScanned
+import OAI.Computability.VPVNP.CompressorShrinkSurvivingOperands
+
+/-!
+# The four surviving-width packets in a shrinking block
+
+Each role's native worker reads the chosen bit at the common score address,
+the absolute arc ID and the two term words. It writes the balanced subdivision
+width and its interval references in table two. The four chronological packets
+retain the original reports and start in the memory produced by the AB scans.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.SurvivingPackets
+
+open BurstRAM Compression PhaseRecipe BlockPlanner DescriptorSpace Schedule SourceTransport
+open ShrinkSliceSweep ShrinkBlockInputs SurvivingNative
+open scoped Fin.CommRing
+open private scanned from OAI.Computability.VPVNP.CompressorShrinkPreparationAccess
+open private useFixedFuel from OAI.Computability.VPVNP.CompressorScheduledSliceRates
+open private expr_agree from OAI.Computability.VPVNP.CompressorShrinkABSliceWindow
+
+/-- One more than the length of the native surviving-width instruction list, allowing the final
+return. -/
+abbrev workerFuel := 1+SurvivingNative.ops.length
+
+variable {w n A : ℕ} {L : Layout} {D : ℕ → Prop} {pub : Fin 5 → Word w} {st : Word w}
+
+/-- The public recipe for each role has the same operands as the physical
+allocation. All planner loads consult the reference header below table zero. -/
+def Evaluated (heads : Heads) (T : Allocation w n A) (abs layout : Word w) (cut : ℕ) (ref : Memory w)
+ (D : ℕ → Prop) (pub : Fin 5 → Word w) (st : Word w) : Prop :=
+ ∀ t, let v := SurvivingNative.visits T.subdiv heads t
+ (v.initial.eval pub st ref = 0 ∧ v.stop.eval pub st ref = ((n*T.subdiv t : ℕ) : Word w) ∧
+ (fun i ↦ (v.params i).eval pub st ref) = params T t abs layout) ∧
+ HeaderOperands.Supported (fun x ↦ D x ∧ x < cut) pub st ref v
+
+/-- The finite native traces feed the actual header-driven visits. Shortening
+the per-call clock to the worker's instruction count preserves every report. -/
+theorem raw_walk (heads : Heads) (T : Allocation w n A) (abs layout : Word w) (cut : ℕ) (ref : Memory w)
+ (fit : T.Fits) (low : levelStart L 0 ≤ cut) (writesAbove : cut ≤ T.widthBase)
+ (readsAbove : ∀ x, readRegion T abs layout x → levelStart L 0 ≤ x)
+ (values : Evaluated heads T abs layout cut ref D pub st)
+ {f : ℕ} {width : Allocation.Id n → ℕ} {js : List (Fin 4)} {mem out : Memory w} {batches : List (List (Report w))}
+ (raw : SurvivingPass.Roles T width (fun t ↦ program T t abs layout) (fun _ ↦ f)
+ (fun t ↦ Site T t abs layout) js mem out batches) (same : Agree (· < cut) ref mem) :
+ SourceWalk (fun v cur rs ↦ ∃ bits,
+ HeaderPacket.Run L pub st v cur rs workerFuel bits ∧ HeaderOperands.Supported D pub st cur v)
+ (js.map (SurvivingNative.visits T.subdiv heads)) mem batches.flatten := by
+ induction raw with
+ | nil => exact .done _
+ | @cons t ts mem out rs batches run _ ih =>
+ let v := SurvivingNative.visits T.subdiv heads t
+ let data := params T t abs layout
+ let M := program T t abs layout
+ let N := n*T.subdiv t
+ have actual : runSegment M workerFuel (some 0) mem (List.replicate N []) = some rs :=
+ useFixedFuel M (fun m i ↦ ⟨_,(SurvivingNative.native data i m).1⟩) run.executed
+ have inc (m : Memory w) (i : Word w) (r : Report w)
+ (he : execute M workerFuel (M.start i) m [] = some r) : r.result = some (i+1) :=
+ (congrArg Report.result (Option.some.inj (he.symm.trans (SurvivingNative.native data i m).1))).trans
+ (SurvivingNative.native data i m).2.1
+ have scan : StageFrame.Scanned 0 N rs := by simpa only [Nat.zero_add] using scanned inc mem 0 N rs actual
+ obtain ⟨eval,supported⟩ := values t
+ have start := expr_agree v.initial D cut mem supported.initial same
+ have stop := expr_agree v.stop D cut mem supported.stop same
+ have args (j) := expr_agree (v.params j) D cut mem (supported.params j) same
+ have eqStart := start.1.symm.trans eval.1
+ have eqStop := stop.1.symm.trans eval.2.1
+ have eqArgs : (fun j ↦ (v.params j).eval pub st mem) = data :=
+ (funext fun j ↦ (args j).1.symm).trans eval.2.2
+ obtain ⟨rd,wr⟩ := run.toSegment.footprint (fun r (h : Site T t abs layout r) ↦ ⟨h.reads,h.writes⟩)
+ have later (x : ℕ) (hx : writeRegion T t x) : cut ≤ x := by
+ obtain ⟨i,inside⟩ := hx
+ exact le_of_not_gt (fun h ↦ inside (T.rowOutside fit (i,t) x (.inl (h.trans_le writesAbove))))
+ have agree : Agree (· < cut) ref (after mem (eventLog rs)) := fun x hx ↦
+ (same x hx).trans (after_outside mem wr (fun h ↦ (later x h).not_gt hx)).symm
+ refine .next ⟨List.replicate N [],⟨Nat.zero_lt_succ _,?_,?_,fun a b ha ↦ readsAbove _ (rd a b ha),
+ fun a b ha ↦ low.trans (later _ (wr a b ha))⟩,⟨start.2,stop.2,fun j ↦ (args j).2⟩⟩ (ih agree)
+ · change runSegment (v.worker.table.instantiate w (fun j ↦ (v.params j).eval pub st mem)).program
+ workerFuel (some (v.initial.eval pub st mem)) mem (List.replicate N []) = _
+ rw [eqStart,eqArgs]
+ exact actual
+ · change SourceOnline.Progress (v.stop.eval pub st mem) (v.initial.eval pub st mem) rs
+ rw [eqStop,eqStart]; exact scan.toProgress (count_fit T fit t)
+
+section Physical
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (inc : IncidenceDirectory w)
+variable (base : Word w) (positions blocks round : ℕ)
+
+local notation "scr" => BlockProgram.script B
+local notation "geom" => BlockProgram.geometry B
+local notation "lay" => BlockProgram.layout B base.val positions blocks
+local notation "ports" => Workspace.ports (Schedule.arity (Script.catalog (BlockProgram.script B))) base
+local notation "public" => Schedule.Ports.data ports
+local notation "blockStart" => (S.steps+1)*round
+local notation "cur" => blockStart+i.val
+local notation "state" => (levelStart lay blockStart : Word w)
+local notation "cut" => tableBase lay cur (0 : Fin 6)
+local notation "ab" => tableBase lay cur (1 : Fin 6)
+local notation "width" => tableBase lay cur (2 : Fin 6)
+local notation "slots" => tableBase lay cur (3 : Fin 6)
+local notation "term" => ShrinkInput.termHead (w := w) X cut
+local notation "stride" => (10 : Word w)
+local notation "oldRole" => SelectedArena.roleBase X term stride
+local notation "layoutAddr" => ShrinkOutput.layoutWord X term stride
+local notation "ids" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X cut) w
+local notation "heads" => BlockSlices.survivingHeads B geom i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 2)
+local notation "high" => levelStart lay 0
+local notation "data" => Window.operandRegion scr lay base
+local notation "V" => BlockSlices.surviving B geom i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 2)
+
+/-- The four surviving-width visits for the supply roles, placed in the script immediately
+after the AB intersection scans. -/
+abbrev window : Window scr V := BlockGroups.shrink B i 7
+
+private theorem absolute_low (start : ℕ) (room : ShrinkInput.termEnd X start 10 < 2^w) :
+ start ≤ (ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w).val := by
+ let z := ShrinkInput.plan X start
+ obtain ⟨hg,hp,_,hw⟩ := ShrinkInput.range_bounds X start
+ have rect : z.rectangleSize = 2*(z.B*z.Q) := Nat.mul_assoc ..
+ have startRank : start ≤ z.origin := hg.trans hp
+ have lo : z.origin ≤ z.gathered := by unfold ShrinkRankSpace.Shape.gathered ShrinkRankSpace.Shape.ids ShrinkRankSpace.Shape.counts; omega
+ have stop : z.stop ≤ ShrinkInput.stop X start := hw
+ change z.gathered+z.rectangleSize+z.A ≤ _ at stop
+ rw [rect] at stop
+ unfold ShrinkInput.termEnd at room
+ change start ≤ (z.gathered+z.B*z.Q)%(2^w)
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+
+variable (sel : SelectedScore.Selection B X) {δ : ℝ} (ready : ShrinkMotif.Ready (2^(a i)) (Shrink.colors (a i)) (2^(b i)) δ)
+
+local notation "alloc" => ShrinkOutput.splitBank (b := b i) X B.shrink sel term (Fin.val stride) oldRole width
+local notation "win" => window B i
+
+set_option maxHeartbeats 1200000 in
+/-- Package the four actual surviving segments of the chosen `withAB` run.
+Their source memory starts after its AB reports and ends at the exact width
+memory consumed by the following ordered-slot construction. -/
+theorem group (ref mem : Memory w) (srcFuel onlineCap : ℕ) (r : ShrinkOutput.TablesRun w)
+ (complete : ShrinkOutput.CompleteTables B i X ready sel term stride ids cut
+ (BlockSlices.abInputs i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 1)) public state ref
+ ab width slots srcFuel mem r)
+ (live : round < blocks) (capacity : X.positions ≤ positions) (room : endAddress lay < 2^w)
+ (header : ShrinkHeaderReads.Header i X inc cut lay blockStart mem)
+ (widthHead : mem (levelStart lay cur+62) = (width : Word w))
+ (total : mem (ports).rows.val = (directoryRows lay : Word w))
+ (pitch : mem ((ports).directory-1).val = (levelWords lay : Word w))
+ (clock : SourceOnline.scanCap scr workerFuel ≤ onlineCap) :
+ ∃ ps : List (SourceOnline.Packet scr w), SourceOnline.Group scr lay base onlineCap
+ ((scr).initial.length+round*(scr).block.length+(win).before.length) (directoryRows lay) (r.postAB mem) ps ∧
+ ps.map (fun p ↦ p.stage.phase) = (win).indices ∧ ps.flatMap SourceWalk.Packet.reports = r.remainder.widthRows.flatten ∧
+ SourceOnline.post (r.postAB mem) ps = r.remainder.postWidths := by
+ have boundary := ShrinkSlotCalendar.physical_boundary B i X base positions blocks round live capacity room
+ have size : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords lay := by
+ have degree : 2^(a i) ≤ slotDegree S :=
+ (Finset.le_sup (f := fun j : Fin (S.steps+1) ↦ 2^S.degreeExponent j) (Finset.mem_univ i.castSucc)).trans
+ (le_max_right ..)
+ have hc : ShrinkLevelSpace.tableFactor S ≤ BlockProgram.fieldCount B :=
+ (le_max_left ..).trans (Nat.le_add_right ..)
+ change _ ≤ positions*slotDegree S*BlockProgram.fieldCount B
+ rw [Nat.mul_assoc]
+ exact Nat.mul_le_mul capacity (hc.trans (Nat.le_mul_of_pos_left _ ((Nat.two_pow_pos _).trans_le degree)))
+ have ends := ShrinkLevelSpace.packed_ends S i X cut ab width slots w
+ have cutToWidth := tableEnd_le_tableBase lay cur (show (0 : Fin 6) < 2 by decide)
+ have widthToSlots := tableEnd_le_tableBase lay cur (show (2 : Fin 6) < 3 by decide)
+ have startToAB := tableEnd_le_tableBase lay cur (show (0 : Fin 6) < 1 by decide)
+ have headBefore : levelStart lay cur+62 < cut := by
+ change _ < levelStart lay cur+66+6*slotCapacity lay+0*tableWords lay
+ omega
+ have hcut : high ≤ cut := (levelStart_mono lay (Nat.zero_le cur)).trans (by omega)
+ have slotRoom : slots < 2^w := by
+ have nxt : levelStart lay (cur+1)+66 ≤ 2^w := by
+ rw [Nat.add_assoc]; exact boundary.nextFits
+ have e := tableEnd_le_nextLevel lay cur (3 : Fin 6)
+ omega
+ have termFit : ShrinkInput.termEnd X cut 10 < 2^w := ends.2.1.trans_lt (by omega)
+ have early : SelectedFinish.stop X term stride ≤ width := ends.2.2.1.trans
+ ((Nat.add_le_add_left size cut).trans cutToWidth)
+ have baseEq : (alloc).widthBase = width := ShrinkOutput.width_at_eq i X term stride width early
+ have last : (alloc).last ≤ slots := by
+ change ShrinkOutput.slotsBase X (alloc).widthBase (ShrinkSlots.levelShape (b := b i) X) ≤ _
+ rw [baseEq]
+ exact ends.2.2.2.2.2.1.trans ((Nat.add_le_add_left size width).trans widthToSlots)
+ have ten : (10 : ℕ) < 2^w := by have hh := header.room; omega
+ have allocationFits : (alloc).Fits := ⟨(Nat.mod_eq_of_lt ten).ge, le_max_left .., ready.count_pos,
+ last.trans_lt slotRoom,by omega⟩
+ have entry : LevelFields.Entry lay blockStart public state mem := ⟨rfl,pitch⟩
+ have supported : Evaluated heads alloc ids layoutAddr cut mem data public state := fun t ↦
+ ShrinkSurvivingOperands.fields B i X inc cut sel width public state mem header entry termFit early widthHead
+ headBefore (boundary.pitchBefore.trans_le hcut) data (.inr (.inl rfl)) (fun _ h ↦ .inr (.inr h)) t
+ have highRead (x : ℕ) (hx : readRegion alloc ids layoutAddr x) : high ≤ x := by
+ rcases hx with rfl | ⟨lo,_⟩ | ⟨j,lo,_⟩
+ · have hv := Nat.mod_eq_of_lt (boundary.scoreBefore.trans slotRoom)
+ exact (show (layoutAddr).val = _ from hv) ▸ boundary.scoreHigh
+ · exact hcut.trans ((absolute_low i X cut termFit).trans lo)
+ · exact hcut.trans ((ScorePackets.start_le_term i X cut termFit).trans ((Nat.le_add_right ..).trans lo))
+ have agree : Agree (· < cut) mem (r.postAB mem) := fun x hx ↦ (complete.abFrame x (.inl (by omega))).symm
+ have ww := raw_walk heads alloc ids layoutAddr cut mem allocationFits hcut (by rw [baseEq]; omega)
+ highRead supported complete.remainder.sweep agree
+ have raw : SourceWalk (Window.Raw (A := scr) lay base round workerFuel) V (r.postAB mem) r.remainder.widthRows.flatten := by
+ have lift {js : List BlockPlanner.Visit} {mm : Memory w} {xs : List (Report w)}
+ (walk : SourceWalk (fun v m rs ↦ ∃ bits, HeaderPacket.Run lay public state v m rs workerFuel bits ∧
+ HeaderOperands.Supported data public state m v) js mm xs) :
+ SourceWalk (Window.Raw (A := scr) lay base round workerFuel) js mm xs := by
+ induction walk with
+ | done => exact .done _
+ | next hd _ ih => obtain ⟨bs,rn,ok⟩ := hd; exact .next ⟨workerFuel,bs,le_rfl,rn,ok⟩ ih
+ exact lift ww
+ have rowEq := (agree _ (boundary.rowsBefore.trans_le hcut)).symm.trans total
+ have pitchEq := (agree _ (boundary.pitchBefore.trans_le hcut)).symm.trans pitch
+ have ord (j : Fin (V).length) : Window.ordinal (A := scr) round ((win).index j) < directoryRows lay := by
+ rw [(win).ordinal_index]
+ have hr := boundary.blockRoom
+ rw [Nat.succ_mul] at hr
+ have hi := ((win).position j).isLt
+ omega
+ have clocks (j : Fin (scr).size) :
+ ((scr).plan.recipes j).2.code.length+1+2*Online.N (scr).size (scr).size+5 ≤ onlineCap ∧
+ workerFuel+3+4*(((scr).catalog j).params+1)+2*Online.N (scr).size (scr).size+5 ≤ onlineCap := by
+ have rc := Finset.le_sup (f := fun j : Fin (scr).size ↦ ((scr).plan.recipes j).2.code.length+1+
+ 2*Online.N (scr).size (scr).size+5) (Finset.mem_univ j)
+ have ar := params_le_arity (scr).catalog j
+ unfold SourceOnline.scanCap at clock
+ exact ⟨rc.trans ((le_max_left ..).trans clock),by omega⟩
+ obtain ⟨ps,hgroup,hids,hrs⟩ := (win).group lay base round rfl rfl boundary.fits onlineCap workerFuel
+ (r.postAB mem) r.remainder.widthRows.flatten raw rowEq pitchEq ord (fun j _ ↦ (clocks j).1) (fun j _ ↦ (clocks j).2)
+ refine ⟨ps,hgroup,hids,hrs,?_⟩
+ rw [SourceOnline.post,hrs]
+ exact complete.remainder.sweep.replay
+
+end Physical
+end CompressorRecords.SurvivingPackets
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTablesPhysical.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTablesPhysical.lean
new file mode 100644
index 0000000000..8836230756
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTablesPhysical.lean
@@ -0,0 +1,169 @@
+import OAI.Computability.VPVNP.CompressorBlockCapacity
+import OAI.Computability.VPVNP.CompressorRecordsShrinkBuild
+import OAI.Computability.VPVNP.CompressorShrinkFieldCapacity
+import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables
+import OAI.Computability.VPVNP.CompressorShrinkHeaderReads
+
+/-! # Allocated tables for the AB, surviving-width and ordered-slot passes
+
+At a live shrinking level the selected rows end in table zero. The interval
+records and widths fit in the following two tables, and the native slot passes
+end in table three. The calendar reads their starting addresses from the same
+published header as the prefix. Scalar bounds hold uniformly on the selected
+states once the input length reaches the word-capacity threshold.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkOutput
+
+open BurstRAM Compression BlockPlanner DescriptorSpace ShrinkBlockInputs Schedule
+open ShrinkSliceSweep CursorBounds Filter
+open scoped Fin.CommRing
+open private absolute_room from OAI.Computability.VPVNP.CompressorRecordsShrinkBuild
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g))
+variable (base : Word w) (positions blocks round : ℕ)
+
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "ports" => Workspace.ports (arity (Script.catalog (BlockProgram.script B))) base
+local notation "pub" => Ports.data ports
+local notation "blockStart" => (S.steps+1)*round
+local notation "cur" => blockStart+i.val
+local notation "st" => (levelStart L blockStart : Word w)
+local notation "cut" => tableBase L cur (0 : Fin 6)
+local notation "first" => tableBase L cur (1 : Fin 6)
+local notation "width" => tableBase L cur (2 : Fin 6)
+local notation "slots" => tableBase L cur (3 : Fin 6)
+local notation "term" => ShrinkInput.termHead (w := w) X cut
+local notation "step" => (10 : Word w)
+local notation "ids" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X cut) w
+local notation "role" => SelectedArena.roleBase X term step
+local notation "keepEnd" => SelectedFinish.stop X term step
+local notation "sh" => ShrinkSlots.levelShape (b := b i) X
+local notation "abInputs" => BlockSlices.abInputs i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 1)
+local notation "nt" => ShrinkBundlePlan.cap (a i)
+local notation "ns" => ShrinkBundlePlan.thickCount (a i)
+
+/-- The address bounds used by all three workers and by the preceding hidden-map frame. -/
+structure TableSpace : Prop where
+ termRoom : ShrinkInput.termEnd X cut 10 < 2^w
+ fresh : ShrinkInput.stop X cut ≤ first
+ selectedWithin : keepEnd ≤ cut+tableWords L
+ abAfter : keepEnd ≤ first
+ widthAfter : first+(ShrinkInput.plan X cut).B*IndexedStarts.capacity ns nt ≤ width
+ slotAfter : slotsBase X (widthBase X (term).val (step).val role width) sh ≤ slots
+ slotRoom : ShrinkSlots.finish sh (heads sh role slots) < 2^w
+ packedRoom : stop (b := b i) X (term).val (step).val role width < 2^w
+
+private theorem finish_mono (s : SlotLevel.Shape) (r : ℕ) {u v : ℕ} (h : u ≤ v) :
+ ShrinkSlots.finish s (heads s r u) ≤ ShrinkSlots.finish s (heads s r v) := by
+ unfold ShrinkSlots.finish ShrinkSlots.widthHead ShrinkSlots.inHead ShrinkSlots.outHead
+ ShrinkSlots.inverseBaseHead SlotLevel.stopAddress SlotLevel.shiftsHead SlotLevel.targetsHead
+ SlotLevel.inverseHead SlotLevel.rowsHead heads
+ dsimp only
+ omega
+
+set_option maxHeartbeats 1200000 in
+/-- Specialize the compiled block endpoints to the three separately allocated tables. -/
+theorem table_space (live : round < blocks) (sites : X.positions ≤ positions)
+ (room : endAddress L < 2^w) : TableSpace B i X base positions blocks round := by
+ have active : cur < (L).levels := by
+ change (S.steps+1)*round+i.val < 1+(S.steps+1)*blocks
+ have h := Nat.mul_le_mul_left (S.steps+1) live
+ rw [Nat.mul_succ] at h
+ have hi := i.isLt
+ omega
+ let level : Fin (L).levels := ⟨cur,active⟩
+ have amount : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords L := by
+ change _ ≤ positions*(L).shape.slots*(L).shape.fields
+ rw [Nat.mul_assoc]
+ exact Nat.mul_le_mul sites (BlockProgram.field_rates B base.val positions blocks).1
+ obtain ⟨h₀,h₁,h₂,_,h₄,h₅,h₆⟩ := ShrinkLevelSpace.packed_ends S i X cut first width slots w
+ have within (u : ℕ) := Nat.add_le_add_left amount u
+ have end₀ := tableStop_lt L level (0 : Fin 6) amount room
+ have end₃ := tableStop_lt L level (3 : Fin 6) amount room
+ have firstAfter := tableEnd_le_tableBase L cur (show (0 : Fin 6) < 1 by decide)
+ have secondAfter := tableEnd_le_tableBase L cur (show (1 : Fin 6) < 2 by decide)
+ have thirdAfter := tableEnd_le_tableBase L cur (show (2 : Fin 6) < 3 by decide)
+ have keep : keepEnd ≤ first := h₂.trans ((within cut).trans firstAfter)
+ have abLast : first+(ShrinkInput.plan X cut).B*IndexedStarts.capacity ns nt ≤ width := h₄.trans ((within first).trans secondAfter)
+ have exactBase := width_at_eq i X term step width (keep.trans ((Nat.le_add_right first _).trans abLast))
+ have slotStart : slotsBase X (widthBase X (term).val (step).val role width) sh ≤ slots := by
+ rw [exactBase]
+ exact h₅.trans ((within width).trans thirdAfter)
+ have slotRoom := h₆.trans_lt end₃
+ exact ⟨h₁.trans_lt end₀,h₀.trans ((within cut).trans firstAfter),h₂.trans (within cut),
+ keep,abLast,slotStart,slotRoom,(finish_mono sh role slotStart).trans_lt slotRoom⟩
+
+/-- Uniform arithmetic capacity for the surviving and AB workers. The address
+argument of `fields` is discharged by `table_space` after allocating the level. -/
+structure TableArithmetic (w : ℕ) : Prop where
+ widthRoom : nt*X.maxWireWidth < 2^w
+ fields : ∀ (rowBase : Word w) (stride roles floor : ℕ),
+ stop (b := b i) X rowBase.val stride roles floor < 2^w →
+ FitsWords (b := b i) X B.shrink rowBase stride roles floor
+
+theorem eventually_tableArithmetic (d : ℕ) (hd : 1 ≤ d) : ∀ᶠ n : ℕ in atTop,
+ ∀ (i : Fin S.steps) {g : ℕ} (X : State (a i) (packingLaneBits (a i) g)),
+ X.positions ≤ initialPositions d n → X.maxWireWidth ≤ n → TableArithmetic B i X (wordBits d n) := by
+ let q := Finset.univ.sup fun j : Fin S.steps => ShrinkBundlePlan.cap (a j)
+ filter_upwards [eventually_fitsWords B d hd,
+ CursorRAM.eventual_word_room d hd ((PolynomiallyBounded.const q).mul PolynomiallyBounded.id)] with n fields product
+ intro i g X sites wire
+ have bound : ShrinkBundlePlan.cap (a i) ≤ q := Finset.le_sup
+ (f := fun j : Fin S.steps => ShrinkBundlePlan.cap (a j)) (Finset.mem_univ i)
+ exact ⟨(Nat.mul_le_mul bound wire).trans_lt product, fields i X sites wire⟩
+
+set_option maxHeartbeats 1600000 in
+/-- The post-hidden memory drives the actual three-table workers. The AB operand
+readbacks refer to that memory and therefore also describe its source trace. -/
+theorem withAB_physical (inc : IncidenceDirectory w) (mem : Memory w) {δ : ℝ}
+ (ready : ShrinkMotif.Ready (2^(a i)) (Shrink.colors (a i)) (2^(b i)) δ)
+ (sel : SelectedScore.Selection B X) (live : round < blocks) (sites : X.positions ≤ positions)
+ (room : endAddress L < 2^w) (arithmetic : TableArithmetic B i X w)
+ (header : ShrinkHeaderReads.Header i X inc cut L blockStart mem)
+ (pitch : mem ((ports).directory-1).val = (levelWords L : Word w))
+ (abHead : mem (tableHead L cur (1 : Fin 6)) = (first : Word w))
+ (resident : Resident B i X sel term step ids inc cut width mem)
+ (cap : ℕ) (abFuel : 95 ≤ cap) (sweepFuel : SurvivingNative.ops.length < cap) :
+ ∃ r, CompleteTables B i X ready sel term step ids cut abInputs pub st mem first width slots cap mem r ∧
+ ShrinkABSliceRecipe.Describes abInputs pub st mem (ShrinkInput.thickBank X inc cut)
+ (ShrinkInput.piecesBank X inc cut) (ShrinkInput.plan X cut).B first := by
+ have h := table_space B i X base positions blocks round live sites room
+ have ten : 10 < 2^w := by have hh := header.room; omega
+ have stepVal : (step).val = 10 := Nat.mod_eq_of_lt ten
+ have tr : ShrinkInput.termEnd X cut (step).val < 2^w := stepVal ▸ h.termRoom
+ have entry : LevelFields.Entry L blockStart pub st mem := ⟨rfl,pitch⟩
+ have level := header.reads B entry
+ have headFit : tableHead L cur (1 : Fin 6) < 2^w := by
+ have below : tableHead L cur (1 : Fin 6) < cut := by
+ change levelStart L cur+54+6+1 < levelStart L cur+66+_+_; omega
+ obtain ⟨g₀,g₁,g₂,g₃⟩ := ShrinkInput.range_bounds X cut
+ have tr₀ := h.termRoom
+ unfold ShrinkInput.termEnd at tr₀
+ omega
+ let : Nontrivial (Word w) := Fin.nontrivial_iff_two_le.mpr (by omega)
+ have arena := (LevelFields.eval_table entry i.val (1 : Fin 6) headFit).trans abHead
+ have hw := arithmetic.fields term (step).val role width h.packedRoom
+ obtain ⟨r,run⟩ := withAB B i X ready sel term step ids inc cut first width slots cap mem level arena tr h.fresh
+ arithmetic.widthRoom h.abAfter h.widthAfter h.slotAfter h.slotRoom stepVal.ge hw
+ (absolute_room X cut step tr) resident abFuel sweepFuel
+ have rankFit : (ShrinkInput.plan X cut).stop < 2^w := by
+ change ShrinkInput.widthBase X cut < _
+ change ShrinkInput.widthBase X cut+_+_+_+_ < _ at tr
+ omega
+ exact ⟨r,run,BlockSlices.ab_describes i X inc cut level rankFit arena⟩
+
+end CompressorRecords.ShrinkOutput
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTailReadback.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTailReadback.lean
new file mode 100644
index 0000000000..a1f3884058
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTailReadback.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.CompressorShrinkScheduledTail
+
+/-! # All DFS header words after the terminal shrinking group
+
+The fourteen address publications preserve the preceding four term words.
+The eighteen publications together preserve the twelve metadata words and
+the two successor fields written by the first group.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkScheduledTail
+
+open BurstRAM DescriptorSpace BlockPlanner PhaseRecipe Schedule Compression SourceOnline SourceTransport
+open scoped Fin.CommRing
+
+variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+variable {base : Word w} {positions blocks t cap : ℕ} {i : Fin S.steps}
+variable {g : ℕ} {X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)} {m : Memory w}
+local notation "prog" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (arity (Script.catalog prog)) base
+local notation "pub" => Ports.data pt
+local notation "first" => Script.levelsPerBlock prog * t
+local notation "st" => (levelStart L (first) : Word w)
+local notation "here" => levelStart L (first+i.val)
+local notation "nextHead" => levelStart L (first+(i.val+1))
+
+variable {ms ps : List (Packet (BlockProgram.script B) w)}
+ (r : Result B base positions blocks t cap i X m ms ps)
+
+include r
+
+theorem Result.payload (j : Fin 12) :
+ post m ps (here+15+j.val) =
+ (BlockMetadata.fieldExprs (L).shape i.val B.recordLimit (slotDegree S) (BlockMetadata.shrinkFields B i) j).eval pub st m :=
+ (r.metaCell _ (.inl (by have := j.isLt; omega))).trans (r.baseFields.payload j)
+
+theorem Result.next_words :
+ post m ps (nextHead+14) = m (here+14) + ((B.recordLimit+2 : ℕ) : Word w)*(ShrinkPreimages.oldCount X : Word w) ∧
+ post m ps (nextHead+27) = (BlockMetadata.Role.shrink.code : Word w) := by
+ have size : levelHeaderWords L = 66 := rfl
+ have gap : here+66 ≤ nextHead := by
+ rw [show first+(i.val+1)=(first+i.val)+1 by omega]
+ simp only [levelStart,Nat.succ_mul,levelWords,size]
+ omega
+ exact ⟨(r.metaCell _ (.inr (by omega))).trans r.baseFields.successor,(r.metaCell _ (.inr (by omega))).trans r.baseFields.tag⟩
+
+theorem Result.term_word (j : Fin 4) :
+ post m ps (here+36+j.val) = (BlockHeadStability.shrinkTerms B i j).eval pub st (post m ms) := by
+ rw [r.image]
+ have keep := r.published.dataGroup.source.outside (here+36+j.val) (.inl (by have := j.isLt; omega))
+ exact keep.trans (r.published.termGroup.source.stored j)
+
+theorem Result.data_word (j : Fin 14) :
+ post m ps (here+40+j.val) = (PublishedHeads.dataValues B i j).eval pub st (termImage B base positions blocks t i (post m ms)) := by
+ rw [r.image]
+ exact r.published.dataGroup.source.stored j
+
+end CompressorRecords.ShrinkScheduledTail
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTailRetention.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTailRetention.lean
new file mode 100644
index 0000000000..6eafde5332
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTailRetention.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.CompressorShrinkScheduledTail
+import OAI.Computability.VPVNP.CompressorShrinkScheduledRetention
+import OAI.Computability.VPVNP.CompressorShrinkSliceInterval
+import OAI.Computability.VPVNP.CompressorCurrentGraph
+
+/-! # Physical shrinking readbacks after the terminal publication rows
+
+Parts nine through eleven publish the DFS metadata and all term and slice
+pointers. The six header words for the resident directories and every old
+data table retain their values. The successor incidence arrays begin after
+its header and also retain their six packed columns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkScheduledTail
+
+open BurstRAM Compression BlockPlanner DescriptorSpace Schedule ShrinkBlockInputs
+open ShrinkSlots SlotLevel SourceOnline ShrinkOutput
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+variable {w g : ℕ} {i : Fin S.steps} {X : State (a i) (packingLaneBits (a i) g)}
+variable {base : Word w} {positions blocks t cap : ℕ} {m : Memory w}
+local notation "prog" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "firstLevel" => Script.levelsPerBlock prog*t
+local notation "old" => firstLevel+i.val
+local notation "nxt" => firstLevel+(i.val+1)
+local notation "oldHead" => levelStart L old
+local notation "nextHead" => levelStart L nxt
+local notation "tab" => (fun j : Fin 6 => tableBase L old j)
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "step" => (10 : Word w)
+local notation "keepEnd" => SelectedFinish.stop X term step
+local notation "sh" => levelShape (b := b i) X
+variable {ms ps : List (SourceOnline.Packet (BlockProgram.script B) w)}
+
+private theorem table_after (j : Fin 6) : oldHead+66 ≤ tab j := by
+ change oldHead+66 ≤ oldHead+66+6*slotCapacity L+j.val*tableWords L
+ omega
+
+private theorem table_before (j : Fin 6) : tab j+tableWords L ≤ nextHead := by
+ have next : old+1=nxt := by omega
+ rw [← next]
+ exact tableEnd_le_nextLevel L old j
+
+theorem Result.table_data (tail : ShrinkScheduledTail.Result B base positions blocks t cap i X m ms ps) (j : Fin 6) (x : ℕ) (lo : tab j ≤ x) (hi : x < tab j+tableWords L) : post m ps x=m x := by
+ have floor : oldHead+66 ≤ tab j := table_after j
+ have top : tab j+tableWords L ≤ nextHead := table_before j
+ exact tail.old_data x (by omega) (hi.trans_le top)
+
+/-- The old resident head words occupy the gap between the metadata and
+the term-pointer publication ranges. -/
+theorem Result.residentHeads (tail : ShrinkScheduledTail.Result B base positions blocks t cap i X m ms ps) (j : Fin 6) : post m ps (oldHead+(30+j.val)) = m (oldHead+(30+j.val)) := by
+ have sep : oldHead+66 ≤ nextHead :=
+ (table_after (B := B) (base := base) (positions := positions) (blocks := blocks) (t := t) (i := i) 0).trans
+ ((Nat.le_add_right ..).trans (table_before 0))
+ have := j.isLt
+ apply tail.outside <;> omega
+
+private theorem levels (live : t < blocks) : old < (L).levels ∧ nxt < (L).levels := by
+ have h := Nat.mul_le_mul_left (S.steps+1) live
+ rw [Nat.mul_succ] at h
+ have hi := i.isLt
+ change (S.steps+1)*t+i.val < 1+(S.steps+1)*blocks ∧ (S.steps+1)*t+(i.val+1) < 1+(S.steps+1)*blocks
+ omega
+
+/-- The selected native placement bank still contains all four actual
+columns for every old vertex. The word-base addition is within table zero. -/
+theorem Result.placement (tail : ShrinkScheduledTail.Result B base positions blocks t cap i X m ms ps) (sel : Bool) (p₀ : Fin 14 → Word w) (bit : Word w)
+ (before : ShrinkRAM.PlacementColumns X.slots X.baseIndex (SelectedArena.shrinkWords X term step p₀ bit) sel m)
+ (live : t < blocks) (size : X.positions ≤ positions) (room : endAddress L < 2^w) :
+ ShrinkRAM.PlacementColumns X.slots X.baseIndex (SelectedArena.shrinkWords X term step p₀ bit) sel (post m ps) := by
+ let level : Fin (L).levels := ⟨old,(levels (B := B) (base := base) (positions := positions) (i := i) live).1⟩
+ have space := table_space B i X base positions blocks t live size room
+ have startLe := ScorePackets.start_le_term i X (tab 0) space.termRoom
+ have endFit := tableStop_lt L level (0 : Fin 6) le_rfl room
+ have last : keepEnd ≤ tab 0+tableWords L := space.selectedWithin
+ have within : SelectedArena.endAddr X term step ≤ keepEnd := by
+ unfold SelectedFinish.stop SelectedFinish.rowStart SelectedFinish.countStart
+ omega
+ have fit : SelectedArena.Fits X term step := within.trans_lt (last.trans_lt endFit)
+ let p := SelectedArena.shrinkWords X term step p₀ bit
+ let place := SelectedArena.placementBase X term step
+ let role := SelectedArena.roleBase X term step
+ have placeLo : tab 0 ≤ place := by
+ change tab 0 ≤ (term).val+SelectedArena.motifs X*(step).val+3
+ omega
+ have roleEnd : role ≤ keepEnd := (Nat.le_add_right ..).trans within
+ constructor
+ intro x _
+ let idx := ShrinkRAM.word w (Shrink.oldNumber X.baseIndex x)
+ have jBound : idx.val < SelectedArena.positions X := by
+ change (Shrink.oldNumber X.baseIndex x) % 2^w < _
+ rw [← Shrink.oldIndex_val]; exact (Nat.mod_le ..).trans_lt (Fin.isLt _)
+ have same (j : Fin 4) : post m ps (ShrinkRAM.outAddr p j idx) = m (ShrinkRAM.outAddr p j idx) := by
+ have head := SelectedArena.output_column X term step p₀ bit fit j
+ change (p (j.natAdd 10)).val = place+j.val*SelectedArena.positions X at head
+ have sep := Nat.mul_le_mul_right (SelectedArena.positions X) j.isLt
+ rw [Nat.succ_mul] at sep
+ have top : place+j.val*SelectedArena.positions X+idx.val < role := by
+ change place+j.val*SelectedArena.positions X+idx.val < place+4*SelectedArena.positions X
+ omega
+ have addr : ShrinkRAM.outAddr p j idx = place+j.val*SelectedArena.positions X+idx.val := by
+ rw [ShrinkRAM.outAddr,Fin.val_add,head,Nat.mod_eq_of_lt (top.trans_le (roleEnd.trans (last.trans endFit.le)))]
+ exact tail.table_data 0 _ (addr ▸ placeLo.trans ((Nat.le_add_right ..).trans (Nat.le_add_right ..)))
+ (addr ▸ top.trans_le (roleEnd.trans last))
+ change (((post m ps) (ShrinkRAM.outAddr p 0 idx)).val,((post m ps) (ShrinkRAM.outAddr p 1 idx)).val,
+ ((post m ps) (ShrinkRAM.outAddr p 2 idx)).val,((post m ps) (ShrinkRAM.outAddr p 3 idx)).val) = _
+ rw [same 0,same 1,same 2,same 3]
+ exact before.atSite x
+
+/-- Every selected and computed table used by the history reader survives
+on the actual post-memory. The word and allocation bounds are derived from
+the same fitted block as the native construction. -/
+theorem Result.readbacks (tail : ShrinkScheduledTail.Result B base positions blocks t cap i X m ms ps) (sel : SelectedScore.Selection B X) (T : IncidenceDirectory w)
+ (before : ScheduledReadbacks B i X sel base positions blocks t T m)
+ (live : t < blocks) (size : X.positions ≤ positions) (room : endAddress L < 2^w) :
+ ScheduledReadbacks B i X sel base positions blocks t T (post m ps) := by
+ obtain ⟨liveOld,liveNext⟩ := levels (B := B) (base := base) (positions := positions) (i := i) live
+ let level : Fin (L).levels := ⟨old,liveOld⟩
+ let next : Fin (L).levels := ⟨nxt,liveNext⟩
+ have space := table_space B i X base positions blocks t live size room
+ obtain ⟨_,endTerm,endSelected,_,_,_,endSlots,_,endResidents⟩ :=
+ BlockLevelFit.shrink (w := w) B base.val positions blocks level rfl i X size room
+ have lo : oldHead+66 ≤ tab 0 := table_after 0
+ have ten : 10 < 2^w := by
+ have h : tab 0 < 2^w := tableStop_lt L level (0 : Fin 6) (Nat.zero_le _) room
+ omega
+ have wide : (step).val=10 := Nat.mod_eq_of_lt ten
+ have sliced := before.slices.transfer_interval (T := T) (start := tab 0) (S.shrink i)
+ (show ShrinkInput.termEnd X (tab 0) (step).val < 2^w by rw [wide]; exact endTerm.word)
+ space.fresh space.widthAfter space.slotAfter (tableStop_lt L level (3 : Fin 6) (Nat.zero_le _) room)
+ wide.ge space.packedRoom (post := post m ps) (fun x low high => tail.old_data x
+ ((show oldHead+54 ≤ tab 1 by have h : oldHead+66 ≤ tab 1 := table_after 1; omega).trans low)
+ (high.trans_le ((Nat.le_add_right ..).trans (table_before 3))))
+ have ordered := before.ordered.transfer_interval (post := post m ps)
+ (fun x low high => tail.table_data 3 x low (high.trans_le endSlots.within))
+ refine ⟨before.resident.interval B i X sel T (tab 0) endTerm.word ten endSelected.word.le
+ (fun x low high => tail.table_data 0 x low (high.trans_le endSelected.within)),
+ sliced,ordered,⟨fun j => (tail.residentHeads j).trans (before.hidden.heads j),?_⟩,?_⟩
+ · intro maps
+ exact ShrinkResidentRun.transfer X (tab 5) (SelectedFinish.chosen B X sel) maps
+ (before.hidden.directories maps) endResidents.word
+ (fun x low high => tail.table_data 5 x low (high.trans_le endResidents.within))
+ · let Y := X.shrinkNext B.shrink (S.shrink i) sel
+ have count := (ShrinkSlotCalendar.physical_space B i X base.val positions blocks level rfl size room).2.1
+ have exactCount := (next_counts X B.shrink (S.shrink i) sel).2
+ have input := before.incidence
+ rw [← exactCount] at input ⊢
+ apply CurrentGraph.incidence_keep L next Y room (exactCount.le.trans count) input
+ intro x low _
+ apply tail.next_data
+ change nextHead+66 ≤ x at low
+ omega
+
+end CompressorRecords.ShrinkScheduledTail
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermAllocation.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermAllocation.lean
new file mode 100644
index 0000000000..e32da8dffa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermAllocation.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.CompressorShrinkTermPhases
+
+/-!
+# Allocation of the shrinking term phase
+
+Following the sorted width and field-start tables, reserve a pair of
+words per motif for the inputs and a strided row for each selected term.
+One bound on the end of this last region certifies both native segments
+and preservation of the six earlier columns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkTermSelection
+
+open BurstRAM Compression.PackingData
+
+variable {w : ℕ}
+
+theorem packed_arena (s : Fin 5 → BurstRAM.Word w) (B d c prefixHead termStride : ℕ)
+ (live : pieceCount d c ≤ (s 3).val)
+ (afterWidths : (s 4).val+2*(B*(s 3).val) ≤ prefixHead)
+ (fits : prefixHead+2*(B*(s 3).val)+2*B+4*(B*pieceCount d c)+(B*pieceCount d c)*termStride < 2^w) :
+ let Q := pieceCount d c
+ let N := B*Q
+ let t := BundlePrefixGraph.prefixPublic s B d c prefixHead false
+ let u := BundlePrefixGraph.prefixPublic s B d c prefixHead true
+ let abStart := prefixHead+2*(B*(s 3).val)+2*B
+ let p := DemandWidths.packedPublic (t 4) B Q abStart
+ let dense := Fin.ofNat (2^w) (abStart+2*N)
+ let term := Fin.ofNat (2^w) (abStart+2*N+2*N)
+ ShrinkDemandGather.Layout B Q (ShrinkTermInputs.operands u p dense) ∧
+ ShrinkDemandFrame.Before B (2^c*d/4) Q t u p dense.val ∧
+ dense.val+N*2 ≤ term.val ∧ term.val+N*termStride < 2^w := by
+ intro Q N t u abStart p dense term
+ let extent := B*(s 3).val
+ change (s 4).val+2*extent ≤ prefixHead at afterWidths
+ change abStart+4*N+N*termStride < 2^w at fits
+ have ha : abStart = prefixHead+2*extent+2*B := rfl
+ have hq : Q < 2^w := live.trans_lt (s 3).isLt
+ have h₁ : (p 0).val = Q := Nat.mod_eq_of_lt hq
+ have h₂ : (p 1).val = Q := Nat.mod_eq_of_lt hq
+ have h₃ : (p 3).val = abStart := Nat.mod_eq_of_lt (by omega)
+ have h₄ : (p 4).val = abStart+N := Nat.mod_eq_of_lt (by omega)
+ have hd : dense.val = abStart+2*N := Nat.mod_eq_of_lt (by omega)
+ have he : term.val = abStart+2*N+2*N := Nat.mod_eq_of_lt (by omega)
+ have ht₁ : (t 1).val = (s 3).val := rfl
+ have ht₂ : (t 2).val = (s 4).val := Nat.mod_eq_of_lt (s 4).isLt
+ have ht₃ : (t 3).val = prefixHead := Nat.mod_eq_of_lt (show prefixHead < 2^w by omega)
+ have hu₁ : (u 1).val = (s 3).val := rfl
+ have hu₂ : (u 2).val = (s 4).val+extent := Nat.mod_eq_of_lt (show (s 4).val+extent < 2^w by omega)
+ have hu₃ : (u 3).val = prefixHead+extent := Nat.mod_eq_of_lt (show prefixHead+extent < 2^w by omega)
+ have hthick : 2^c*d/4 ≤ Q := by change _ ≤ 3*(2^c*d)/4; omega
+ have oldFit : prefixHead+2*extent ≤ dense.val := by omega
+ have hg₁ : (p 3).val+B*(p 1).val ≤ dense.val := by rw [h₂,h₃,hd]; change abStart+N ≤ _; omega
+ have hg₂ : (u 2).val+B*(u 1).val ≤ dense.val := by rw [hu₂,hu₁]; change _ + extent ≤ _; omega
+ have hdt : dense.val+2*N ≤ term.val := by omega
+ have htf : term.val+N*termStride < 2^w := by omega
+ refine ⟨⟨h₁,h₂.ge,hu₁ ▸ live,hg₁.trans dense.isLt.le,hg₂.trans dense.isLt.le,hdt.trans term.isLt.le,
+ .inl hg₁,.inl hg₂⟩,⟨ht₁ ▸ hthick.trans live,hu₁ ▸ live,h₂.ge,?_,?_,hg₂,?_,hg₁,?_⟩,?_,htf⟩
+ · rw [ht₂,ht₁]; change _+extent ≤ _; omega
+ · rw [ht₃,ht₁]; change _+extent ≤ _; omega
+ · rw [hu₃,hu₁]; change _+extent ≤ _; omega
+ · rw [h₄,h₂,hd]; change abStart+N+N ≤ abStart+2*N; omega
+ · simpa only [Nat.mul_comm N 2] using hdt
+
+end CompressorRecords.ShrinkTermSelection
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermForward.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermForward.lean
new file mode 100644
index 0000000000..fe2e817c12
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermForward.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.CompressorShrinkTermLaunch
+import OAI.Computability.VPVNP.CompressorSourceGroups
+
+/-!
+# The certified term interval of the complete shrinking script
+
+The raw reports of the actual gather and term verifier are retained as
+two chronological packets. Both satisfy the online replay and clock
+conditions. The selector's recipe reads the same published level header
+after the gather writes its dense demand pairs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkTermOnline
+
+open BurstRAM BlockPlanner Compression DescriptorSpace Schedule ShrinkBlockInputs ShrinkInput ShrinkTermPackets
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+variable (s : X.ShrinkSelection B.shrink) (fuel : ℕ)
+local notation "A" => BlockProgram.script B
+local notation "O" => BlockProgram.arena B i.val 0
+local notation "H" => ShrinkTermSelection.bundles X
+local notation "Q" => ShrinkTermSelection.ranks (a i)
+local notation "N" => ShrinkTermInputs.motifCount X
+local notation "D" => Online.N (BlockPlanner.Script.size (BlockProgram.script B)) (BlockPlanner.Script.size (BlockProgram.script B))
+
+/-- Combine a globally indexed term visit with its actual entry memory and the reports emitted
+by its source run. -/
+def packet (j : Stage) (raw : Memory w) (rs : List (Report w)) :
+ SourceWalk.Packet (SourceOnline.Visit A w) w := ⟨globalVisit B i X T start s fuel j,raw,rs⟩
+
+/-- The gather packet followed by the selector packet, starting the selector in the memory
+produced by the gather reports. -/
+def packetList (raw : Memory w) (gs ts : List (Report w)) :=
+ [packet B i X T start s fuel .gather raw gs,packet B i X T start s fuel .select (after raw (eventLog gs)) ts]
+
+
+private theorem pair_group {U : Script} {L : DescriptorSpace.Layout} {base : Word w} {cap ordinal total : ℕ}
+ (m : Memory w) (p q : SourceOnline.Packet U w)
+ (first : p.input = m) (next : q.input = p.output)
+ (rp : p.stage.Runs p.input p.reports) (rq : q.stage.Runs q.input q.reports)
+ (hp : SourceOnline.Checked U L cap p) (hq : SourceOnline.Checked U L cap q)
+ (ep : SourceOnline.Prepared U L base ordinal total p) (eq : SourceOnline.Prepared U L base (ordinal+1) total q) :
+ SourceOnline.Group U L base cap ordinal total m [p,q] := by
+ refine ⟨⟨first,rp,next,rq,trivial⟩,fun x h => ?_,fun n => ?_⟩
+ · simp only [List.mem_cons,List.not_mem_nil,or_false] at h
+ rcases h with rfl|rfl <;> assumption
+ · change Fin 2 at n
+ fin_cases n <;> assumption
+
+set_option maxHeartbeats 1200000 in
+theorem certify (L : DescriptorSpace.Layout) (base : Word w) (iteration total cap : ℕ)
+ (before : Memory w) (gs ts : List (Report w))
+ (hg : ShrinkDemandGather.Gathered H Q (pairBank X T start) fuel before gs)
+ (ht : ShrinkTermSelection.Written B.shrink X (demandHead X start) (termHead X start)
+ 10 fuel s (after before (eventLog gs)) ts)
+ (hcap : ShrinkDemandGather.cost < fuel) (space : ShrinkInput.termEnd X start 10 < 2^w)
+ (header : ShrinkHeaderReads.Header i X T start L ((S.steps+1)*iteration) before)
+ (headerBefore : levelStart L ((S.steps+1)*iteration+i.val) + 60 < start)
+ (arityFit : arity (A).catalog = L.shape.arity) (baseFit : base.val = L.base)
+ (totalRows : total = directoryRows L) (live : ordinal B i iteration .select < total)
+ (recipeClock : ∀ j, ((A).plan.recipes (index B i j)).2.code.length+1+2*D+5 ≤ cap)
+ (dataClock : ∀ j, fuel+3+4*(((A).catalog (index B i j)).params+1)+2*D+5 ≤ cap) :
+ SourceOnline.Group A L base cap (ordinal B i iteration .gather) total before
+ (packetList B i X T start s fuel before gs ts) := by
+ let mid := after before (eventLog gs)
+ have ga := gathered_packet B i O X T start s fuel hcap space before gs hg
+ have te := selected_packet B i O X T start s fuel space mid ts ht
+ have first : levelStart L 0 ≤ levelStart L ((S.steps+1)*iteration+i.val) := levelStart_mono L (Nat.zero_le _)
+ have startData : levelStart L 0 ≤ start := by omega
+ have fits : levelStart L 0 < 2^w := first.trans_lt ((Nat.le_add_right ..).trans_lt header.room)
+ have hd : (demandHead (w := w) X start).val = ShrinkInput.stop X start :=
+ Nat.mod_eq_of_lt (by unfold termEnd at space; omega)
+ obtain ⟨h₁,h₂,h₃,h₄⟩ := range_bounds X start
+ have keep (x : ℕ) (hx : x < start) : mid x = before x :=
+ hg.frame x (.inl (show x < (demandHead (w := w) X start).val by rw [hd]; omega))
+ have header' := header.keep_below headerBefore keep
+ have succ : ordinal B i iteration .gather + 1 = ordinal B i iteration .select := by
+ unfold ordinal
+ rw [show (localIndex B i .gather).val = 0 from rfl,show (localIndex B i .select).val = 1 from rfl,Nat.add_zero]
+ have hp : 0 < fuel := (Nat.zero_le _).trans_lt hcap
+ have gp := prepared B i X T start s fuel L base iteration total .gather before gs header space arityFit baseFit fits
+ totalRows (by omega)
+ have tp := prepared B i X T start s fuel L base iteration total .select mid ts header' space arityFit baseFit fits
+ totalRows live
+ let gPacket := packet B i X T start s fuel .gather before gs
+ let tPacket := packet B i X T start s fuel .select mid ts
+ have tp' : SourceOnline.Prepared A L base (ordinal B i iteration .gather+1) total tPacket :=
+ Eq.mp (congrArg (fun n => SourceOnline.Prepared A L base n total tPacket) succ.symm) tp
+ exact pair_group before gPacket tPacket rfl rfl
+ (runs B i X T start s fuel .gather _ _ ga) (runs B i X T start s fuel .select _ _ te)
+ (checked B i X T start s fuel L cap .gather before gs ga hp space startData (recipeClock _) (dataClock _))
+ (checked B i X T start s fuel L cap .select mid ts te hp space startData (recipeClock _) (dataClock _))
+ gp tp'
+
+end CompressorRecords.ShrinkTermOnline
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermGroup.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermGroup.lean
new file mode 100644
index 0000000000..eeab049cb8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermGroup.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.CompressorShrinkTermForward
+import OAI.Computability.VPVNP.CompressorShrinkPublishedHeader
+import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch
+import OAI.Computability.VPVNP.CompressorPublishedHeadWindows
+import OAI.Computability.VPVNP.CompressorBlockGroups
+
+/-!
+# Term selection in the chronological shrinking branch
+
+The physical deterministic prefix preserves the level header through the
+absolute-ID scatter. The two following packets use the same source logs
+and selector tapes as the chosen branch, at the corresponding ordinals of
+the tight directory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkTermOnline
+
+open BurstRAM BlockPlanner Compression DescriptorSpace Schedule ShrinkBlockInputs ShrinkTermPackets
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+variable (s : X.ShrinkSelection B.shrink) (fuel : ℕ) (base : Word w) (positions blocks t : ℕ)
+local notation "A" => BlockProgram.script B
+local notation "W" => window B i
+local notation "L" => BlockProgram.layout B (Fin.val base) positions blocks
+local notation "head" => levelStart L ((S.steps+1)*t+i.val)
+local notation "Z" => ShrinkInput.plan X start
+local notation "N" => ShrinkTermInputs.motifCount X
+
+private theorem afterAbsolute {raw : Memory w} (p : ShrinkBranch.Prefix X T start fuel raw)
+ (header : ShrinkHeaderReads.Header i X T start L ((S.steps+1)*t) raw) (before : head+60 < start) :
+ ShrinkHeaderReads.Header i X T start L ((S.steps+1)*t) (after p.input.post (eventLog p.absolute)) := by
+ have hr := ShrinkInput.range_bounds X start
+ have leRank : start ≤ ShrinkInput.rankBase X start := hr.1.trans hr.2.1
+ have leGather : ShrinkInput.rankBase X start ≤ (Z).gathered := by
+ change ShrinkInput.rankBase X start ≤ ((ShrinkInput.rankBase X start+2*(Z).A)+2*(Z).B)+(Z).rectangleSize
+ omega
+ exact header.keep_below before fun x hx =>
+ (p.absoluteRun.frame _ (.inl (hx.trans_le (leRank.trans leGather)))).trans (p.input.below _ hx)
+
+theorem live (active : t < blocks) (j : Stage) : ordinal B i t j < directoryRows L := by
+ have h := PublishedHeads.windowLive B base positions blocks t W active (localIndex B i j)
+ rw [(W).ordinal_index] at h
+ have before : (W).before.length = (BlockIndex.earlier B i).length+20 := by
+ change (BlockIndex.earlier B i ++ prior B i).length = _
+ rw [List.length_append,prior_length]
+ change (A).initial.length+t*(A).block.length+((W).before.length+(localIndex B i j).val) < directoryRows L at h
+ rw [before] at h
+ unfold ordinal
+ omega
+
+theorem packet_views (m : Memory w) (gs ts : List (Report w)) :
+ let ps := packetList B i X T start s fuel m gs ts
+ ps.map (fun p => p.stage.phase) = (W).indices ∧
+ ps.flatMap SourceWalk.Packet.reports = gs++ts ∧
+ ps.flatMap (fun p => p.stage.choices) =
+ List.replicate N [] ++ List.ofFn (ShrinkTermSelection.tapes B.shrink X s w) := by
+ intro ps
+ have phase : ps.map (fun p => p.stage.phase) = [index B i .gather,index B i .select] := rfl
+ refine ⟨phase.trans ?_,?_,?_⟩
+ · change _ = List.ofFn (fun j : Fin 2 => (W).index j)
+ simp only [List.ofFn_succ,List.ofFn_zero]
+ rfl
+ · change gs++(ts++[]) = _
+ rw [List.append_nil]
+ · change List.replicate (ShrinkTermSelection.bundles X*ShrinkTermSelection.ranks (a i)) [] ++
+ (List.ofFn (ShrinkTermSelection.tapes B.shrink X s w) ++ []) = _
+ rw [List.append_nil]
+ exact congrArg (fun n => List.replicate n [] ++ List.ofFn (ShrinkTermSelection.tapes B.shrink X s w))
+ (ShrinkTermSelection.motifCount_eq X).symm
+
+/-- The common third zero-based part in the twelve-group calendar. -/
+abbrev partWindow : Window A (termVisits B i (BlockProgram.arena B i.val 0)) := BlockGroups.shrink B i 3
+
+theorem part_before : (partWindow B i).before.length = (BlockIndex.earlier B i).length+20 := by
+ rw [partWindow,BlockGroups.shrink_offset]
+ change _ + ([BlockHeaderPlan.substep (BlockProgram.geometry B) i.val (.shrink (a i) (b i)),
+ GreedyLevelPlan.visits (BlockProgram.geometry B) i.val (a i) (BlockProgram.arena B i.val 0),
+ ShrinkBundlePlan.visits (BlockProgram.geometry B) i.val (a i) (BlockProgram.arena B i.val 0)] : List _).flatten.length = _
+ simp only [List.flatten_cons,List.flatten_nil,List.length_append,List.length_nil,BlockHeaderPlan.substep_length,
+ GreedyLevelPlan.visits_length,ShrinkBundlePlan.visits_length]
+
+theorem part_indices : (W).indices = (partWindow B i).indices := by
+ unfold Window.indices
+ apply congrArg List.ofFn
+ funext j
+ apply Fin.ext
+ rw [(W).index_val,(partWindow B i).index_val,part_before]
+ change _ + (BlockIndex.earlier B i ++ prior B i).length + j.val = _
+ rw [List.length_append,prior_length]
+
+/-- The third zero-based group of the fixed shrinking substep. Its input
+memory is the actual post-memory of the ranked absolute-ID scatter. -/
+theorem branch_group (cap : ℕ) (raw : Memory w) (p : ShrinkBranch.Prefix X T start fuel raw)
+ (selected : ShrinkBranch.Selected B X T start (10 : Word w) (B.shrink.selectorBits : Word w) fuel raw p s)
+ (gatherClock : ShrinkDemandGather.cost < fuel) (space : ShrinkInput.termEnd X start 10 < 2^w)
+ (header : ShrinkHeaderReads.Header i X T start L ((S.steps+1)*t) raw)
+ (headerBefore : head+60 < start) (active : t < blocks) (clock : SourceOnline.scanCap A fuel ≤ cap) :
+ let m := after p.input.post (eventLog p.absolute)
+ let ps := packetList B i X T start s fuel m p.gather selected.terms
+ SourceOnline.Group A L base cap ((A).initial.length+t*(A).block.length+(BlockIndex.earlier B i).length+20)
+ (directoryRows L) m ps ∧ ps.map (fun q => q.stage.phase) = (partWindow B i).indices ∧
+ ps.flatMap SourceWalk.Packet.reports = p.gather++selected.terms ∧
+ ps.flatMap (fun q => q.stage.choices) =
+ List.replicate N [] ++ List.ofFn (ShrinkTermSelection.tapes B.shrink X s w) := by
+ intro m ps
+ have hhead := afterAbsolute B i X T start fuel base positions blocks t p header headerBefore
+ have ten : 10 < 2^w := by have h := header.room; omega
+ have hten : (10 : Word w).val = 10 := Nat.mod_eq_of_lt ten
+ have terms := selected.termRun
+ rw [hten] at terms
+ have clocks (j : Stage) := SourceOnline.scanCap_clocks (p := packet B i X T start s fuel j m []) fuel le_rfl clock
+ have group := certify B i X T start s fuel L base t (directoryRows L) cap m p.gather selected.terms p.gatherRun
+ terms gatherClock space hhead headerBefore rfl rfl rfl (live B i base positions blocks t active .select)
+ (fun j => (clocks j).1) (fun j => (clocks j).2)
+ have first : ordinal B i t .gather =
+ (A).initial.length+t*(A).block.length+(BlockIndex.earlier B i).length+20 := by
+ unfold ordinal; rw [show (localIndex B i .gather).val = 0 from rfl,Nat.add_zero]
+ rw [first] at group
+ have views := packet_views B i X T start s fuel m p.gather selected.terms
+ exact ⟨group,views.1.trans (part_indices B i),views.2⟩
+
+end CompressorRecords.ShrinkTermOnline
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermInputs.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermInputs.lean
new file mode 100644
index 0000000000..7cbac9fce9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermInputs.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.CompressorRecordsDemandWidths
+import OAI.Computability.VPVNP.CompressorShrinkDemandGather
+import OAI.Computability.VPVNP.CompressorShrinkMotifOrder
+import OAI.Computability.VPVNP.CompressorTermRecordScan
+
+/-!
+# Physical AB/CD demand inputs of a shrinking pass
+
+The balanced AB pieces and the original CD widths are stored in distinct
+rectangles. The paired gather visits their common bundle and rank. Its
+two output cells form the exact input to the six-party term reader.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkTermInputs
+
+open Compression Compression.PackingData BurstRAM
+
+variable {w : ℕ}
+
+/-- The two rectangle heads and strides are the ones used by the prefix and
+balanced-piece passes. The first word is the common number of CD ranks. -/
+def operands (cdRows ab : Fin 5 → BurstRAM.Word w) (dense : BurstRAM.Word w) : Fin 6 → BurstRAM.Word w :=
+ ![ab 0, ab 1, cdRows 1, ab 3, cdRows 2, dense]
+
+section Packed
+
+variable {V H T L : Type} {n d c : ℕ}
+variable [AddCommGroup H] [AddCommGroup T] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype T] [Fintype L]
+variable [DecidableEq V] [DecidableEq T] [DecidableEq L]
+variable (P : PackingData V H T L d c) (site : Site V T L ≃ Fin n) (old : Arc V H T L d c → ℕ)
+variable (cd : P.BundleNumbering)
+
+/-- The dense scan order is the CD ordinal used at both AB endpoints.
+Cell zero holds the balanced AB width and cell one the original CD width. -/
+def Pairs (dense : BurstRAM.Word w) (mem : Memory w) : Prop :=
+ ∀ m : P.Motif, let j := (ShrinkMotifOrder.number P cd site m).val
+ (mem (dense.val+2*j)).val = P.abWidth cd old m ∧ (mem (dense.val+2*j+1)).val = old m.val
+
+theorem gather (dd : P.ThickNumbering) (thick cdRows ab : Fin 5 → BurstRAM.Word w)
+ (dense : BurstRAM.Word w) (mem : Memory w)
+ (stored : DemandWidths.Stored P site old dd cd thick cdRows ab mem)
+ (layout : ShrinkDemandGather.Layout (n*d) (pieceCount d c) (operands cdRows ab dense))
+ {cap : ℕ} (hcap : ShrinkDemandGather.cost < cap) :
+ ∃ rs, ShrinkDemandGather.Gathered (n*d) (pieceCount d c) (operands cdRows ab dense) cap mem rs ∧
+ Pairs P site old cd dense (after mem (eventLog rs)) := by
+ obtain ⟨rs,h⟩ := ShrinkDemandGather.gather layout mem hcap
+ refine ⟨rs,h,fun m => ?_⟩
+ let b := P.bundle m
+ let x : P.MotifFiber b := ⟨m,rfl⟩
+ let r := cd b x
+ let j := BundleLists.portIndex site b
+ have he := (cd b).symm_apply_apply x
+ have hab := (congrArg Fin.val (h.readAB j.val j.isLt r.val r.isLt)).trans (stored.ab.widths b r)
+ have hcd := (congrArg Fin.val (h.readCD j.val j.isLt r.val r.isLt)).trans (stored.cdWidths b r)
+ change (after mem (eventLog rs) (dense.val+2*(ShrinkMotifOrder.number P cd site m).val)).val = _ ∧
+ (after mem (eventLog rs) (dense.val+2*(ShrinkMotifOrder.number P cd site m).val+1)).val = _
+ rw [ShrinkMotifOrder.number_val]
+ rw [show (cd b).symm r = x from he] at hab hcd
+ exact ⟨hab,hcd⟩
+
+end Packed
+
+/-- Read a dense array of pairs using the fixed two-coordinate order of the block. -/
+private theorem pairInputs {m : ℕ} (b : Fin m → Bool → ℕ) (dense term : BurstRAM.Word w)
+ (stride : ℕ) (wide : 10 ≤ stride) (sep : dense.val+m*2 ≤ term.val)
+ (room : term.val+m*stride < 2^w) (mem : Memory w)
+ (pairs : ∀ (j : Fin m), (mem (dense.val+2*j.val)).val = b j false ∧ (mem (dense.val+2*j.val+1)).val = b j true) :
+ TermRecordScan.Inputs finTwoEquiv (TermRecordScan.strided m 2 8 w dense.val term.val 2 stride le_rfl wide sep room) b mem := by
+ let rows := TermRecordScan.strided m 2 8 w dense.val term.val 2 stride le_rfl wide sep room
+ intro j
+ have hs : (rows.source j).val = dense.val+2*j.val := by
+ have h := Nat.mul_le_mul_right 2 j.isLt
+ rw [Nat.succ_mul] at h
+ change (dense.val+j.val*2)%(2^w) = _
+ rw [Nat.mod_eq_of_lt (by omega),Nat.mul_comm]
+ funext e
+ cases e with
+ | false =>
+ have h := DemandPreparation.demandAt_address finTwoEquiv (rows.source j) mem (rows.sourceFits j) (0 : Fin 2)
+ exact h.trans (by change (mem ((rows.source j).val+0)).val = _; rw [hs,Nat.add_zero]; exact (pairs j).1)
+ | true =>
+ have h := DemandPreparation.demandAt_address finTwoEquiv (rows.source j) mem (rows.sourceFits j) (1 : Fin 2)
+ exact h.trans (by change (mem ((rows.source j).val+1)).val = _; rw [hs]; exact (pairs j).2)
+
+section State
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g))
+open scoped Classical
+
+/-- Number of CD motifs in the input state's packing data. -/
+abbrev motifCount := Fintype.card X.packingData.Motif
+
+/-- The two shrinking demand widths for the motif at a given dense physical ordinal. -/
+noncomputable abbrev demand (j : Fin (motifCount X)) :=
+ X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth (ShrinkMotifOrder.entries X j)
+
+/-- The memory readback that identifies dense demand pairs with their actual motifs and packing
+widths in this state. -/
+noncomputable abbrev statePairs (dense : BurstRAM.Word w) (mem : Memory w) :=
+ Pairs X.packingData (Shrink.packedIndex X.baseIndex) X.packingWidth X.shrinkNumber dense mem
+
+/-- Term records have two headers and eight supply coordinates. A larger
+stride leaves the padding available to the surrounding record directory. -/
+def termRows (dense term : BurstRAM.Word w) (stride : ℕ) (wide : 10 ≤ stride)
+ (sep : dense.val+motifCount X*2 ≤ term.val) (room : term.val+motifCount X*stride < 2^w) :=
+ TermRecordScan.strided (motifCount X) 2 8 w dense.val term.val 2 stride le_rfl wide sep room
+
+set_option maxHeartbeats 1200000 in
+theorem inputs (dense term : BurstRAM.Word w) (stride : ℕ) (wide : 10 ≤ stride)
+ (sep : dense.val+motifCount X*2 ≤ term.val) (room : term.val+motifCount X*stride < 2^w)
+ (mem : Memory w) (pairs : statePairs X dense mem) :
+ TermRecordScan.Inputs finTwoEquiv (termRows X dense term stride wide sep room) (demand X) mem := by
+ apply pairInputs (demand X) dense term stride wide sep room mem
+ intro j
+ let m := ShrinkMotifOrder.entries X j
+ have he : (ShrinkMotifOrder.stateNumber X m).val = j.val :=
+ (ShrinkMotifOrder.entries_ordinal X m).symm.trans (congrArg Fin.val ((ShrinkMotifOrder.entries X).symm_apply_apply j))
+ have pair := pairs m
+ change (mem (dense.val+2*(ShrinkMotifOrder.stateNumber X m).val)).val = _ ∧
+ (mem (dense.val+2*(ShrinkMotifOrder.stateNumber X m).val+1)).val = _ at pair
+ rw [he] at pair
+ exact pair
+
+end State
+
+end CompressorRecords.ShrinkTermInputs
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermLaunch.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermLaunch.lean
new file mode 100644
index 0000000000..04a3e6b508
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermLaunch.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.CompressorShrinkTermOnline
+import OAI.Computability.VPVNP.CompressorShrinkHeaderReads
+
+/-!
+# Launching the shrinking term visits from the repeated calendar
+
+At the packet's global ordinal the live scheduler computes the first
+level of the block and uses the published scalar, incidence and scratch
+cells of its shrinking substep. Evaluating the two concrete visit recipes
+therefore launches the exact worker, start, stop and bank of the original
+source packet.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkTermOnline
+
+open BurstRAM Schedule BlockPlanner DescriptorSpace Compression ShrinkBlockInputs SourceOnline SourceTransport
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+variable (s : X.ShrinkSelection B.shrink) (fuel : ℕ)
+local notation "A" => BlockProgram.script B
+local notation "F" => BlockProgram.geometry B
+local notation "O" => BlockProgram.arena B i.val 0
+
+private theorem transfer {u v : BlockPlanner.Visit} (e : u=v) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w)
+ (bank : Fin v.worker.params → Word w) (h : (fun j => (v.params j).eval pub state m) = bank) :
+ ∀ j, (u.params j).eval pub state m = bank (j.cast (congrArg (fun z : BlockPlanner.Visit => z.worker.params) e)) := by
+ subst u
+ exact fun j => congrFun h j
+
+set_option maxHeartbeats 1200000 in
+theorem prepared (L : DescriptorSpace.Layout) (base : Word w) (iteration total : ℕ) (j : ShrinkTermPackets.Stage)
+ (raw : Memory w) (rs : List (Report w))
+ (fields : ShrinkHeaderReads.Header i X T start L ((S.steps+1)*iteration) raw)
+ (room : ShrinkInput.termEnd X start 10 < 2^w)
+ (arityFit : arity (A).catalog = L.shape.arity) (baseFit : base.val = L.base) (fit : levelStart L 0 < 2^w)
+ (totalRows : total = directoryRows L) (live : ordinal B i iteration j < total) :
+ Prepared A L base (ordinal B i iteration j) total ⟨globalVisit B i X T start s fuel j,raw,rs⟩ := by
+ intro m agree ord rows _ pitch
+ let pt := Workspace.ports (arity (A).catalog) base
+ let phase := index B i j
+ let pre := Online.calendarMemory (d := (A).size) pt m phase
+ let st := (A).recipeState base m
+ have hcal := calendar B i iteration j
+ have hlevel : (Online.calendar (A).plan).level (m pt.ordinal.val).val = iteration := by
+ rw [ord]; exact hcal.2
+ obtain ⟨entry,kept⟩ := SourceOnline.calendar_entry A L base arityFit baseFit fit m phase iteration hlevel
+ (rows.trans totalRows) pitch
+ have header : ShrinkHeaderReads.Header i X T start L ((S.steps+1)*iteration) pre :=
+ (fields.keep agree).keep kept
+ have read := ShrinkTermPackets.visit_readback B i O X T start F pt.data st pre (header.reads B entry) room j
+ refine ⟨hcal.1,SourceOnline.launch_of_evaluation A base L arityFit baseFit fit m _ ?_ ?_ ?_ ?_ ?_⟩
+ · rw [ord,← totalRows]; exact live
+ · apply Fin.lt_def.mpr; rw [ord,rows]; exact live
+ · change (((A).visit phase).initial).eval pt.data st pre = 0
+ rw [index_visit]; exact read.1
+ · change (((A).visit phase).stop).eval pt.data st pre = (ShrinkTermInputs.motifCount X : Word w)
+ rw [index_visit]; exact read.2.1
+ · exact transfer (index_visit B i j) pt.data st pre _ read.2.2
+
+end CompressorRecords.ShrinkTermOnline
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermOnline.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermOnline.lean
new file mode 100644
index 0000000000..bf58978545
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermOnline.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.CompressorBlockIndex
+import OAI.Computability.VPVNP.CompressorScriptWindow
+import OAI.Computability.VPVNP.CompressorSourceSequence
+import OAI.Computability.VPVNP.CompressorShrinkTermPacketBounds
+import OAI.Computability.VPVNP.CompressorShrinkTermVisitReadback
+
+/-!
+# The two shrinking term packets in the repeated online block
+
+The gather occupies ordinal 20 of its shrinking substep, and the fused
+term selector occupies ordinal 21. The stage occurrences retain the
+original resetting instruction programs, physical operands, bit streams
+and reports when placed into the global script.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorRecords.ShrinkTermOnline
+
+open BurstRAM BlockPlanner Compression Schedule DescriptorSpace ShrinkBlockInputs ShrinkTermPackets
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+local notation "A" => BlockProgram.script B
+local notation "F" => BlockProgram.geometry B
+local notation "O" => BlockProgram.arena B i.val 0
+
+/-- The header, greedy and bundle visits that precede term gathering within this shrinking
+substep. -/
+def prior := BlockHeaderPlan.substep F i.val (.shrink (a i) (b i)) ++
+ GreedyLevelPlan.visits F i.val (a i) O ++ ShrinkBundlePlan.visits F i.val (a i) O
+
+/-- The selected placement and later slice and slot visits following term selection in this
+shrinking substep. -/
+def remaining :=
+ let prepared := ShrinkBlockInputs.beforeSlices B F i O
+ SelectedPlan.visits (selectedInputs B F i O) (a i) ++ (BlockProgram.shrink B i).drop prepared.length
+
+theorem prior_length : (prior B i).length = 20 := by
+ simp only [prior,List.length_append,BlockHeaderPlan.substep_length,GreedyLevelPlan.visits_length,ShrinkBundlePlan.visits_length]
+
+/-- The exact two-visit interval occupied by demand gathering and term selection in the
+repeated block script. -/
+def window : BlockPlanner.Window A (termVisits B i O) where
+ before := BlockIndex.earlier B i ++ prior B i
+ after := remaining B i ++ BlockIndex.later B i
+ block := by
+ change BlockProgram.block B = _
+ rw [BlockIndex.split_block B i]
+ simp only [prior,remaining,BlockProgram.shrink,List.append_assoc,List.drop_left]
+ simp only [ShrinkBlockInputs.beforeSlices,List.append_assoc]
+
+/-- Number the gather as the first term visit and the selector as the second. -/
+def localIndex : Stage → Fin (termVisits B i O).length
+ | .gather => ⟨0,by rw [termVisits_length]; decide⟩
+ | .select => ⟨1,by rw [termVisits_length]; decide⟩
+
+/-- Map the gather or selector through its two-visit window to its global script index. -/
+def index (j : Stage) : Fin (A).size := (window B i).index (localIndex B i j)
+
+theorem index_visit (j : Stage) : (A).visit (index B i j) = ShrinkTermPackets.visit B i O j := by
+ cases j <;> exact (window B i).visit (localIndex B i _)
+
+/-- The chronological phase ordinal of a term visit at a given block repetition, after the
+initial sequence and earlier substeps. -/
+def ordinal (iteration : ℕ) (j : Stage) :=
+ (A).initial.length+iteration*(A).block.length+(BlockIndex.earlier B i).length+20+(localIndex B i j).val
+
+theorem calendar (iteration : ℕ) (j : Stage) :
+ (Online.calendar (A).plan).phase (ordinal B i iteration j) = (index B i j).val ∧
+ (Online.calendar (A).plan).level (ordinal B i iteration j) = iteration := by
+ let n := (window B i).position (localIndex B i j)
+ have offset : n.val = (BlockIndex.earlier B i).length+20+(localIndex B i j).val := by
+ change ((BlockIndex.earlier B i ++ prior B i).length+(localIndex B i j).val) = _
+ rw [List.length_append,prior_length]
+ have h := (A).block_phase iteration n
+ have e : ordinal B i iteration j = (A).initial.length+iteration*(A).block.length+n.val := by rw [offset,ordinal]; omega
+ rw [e]; exact h
+
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+variable (s : X.ShrinkSelection B.shrink) (fuel : ℕ)
+
+/-- Install the chosen term worker at its global index with the physical operand bank,
+motif-count stop and gather or selection tapes. -/
+def globalVisit (j : Stage) : SourceOnline.Visit A w :=
+ SourceOnline.Visit.ofWorker (index B i j) (ShrinkTermPackets.visit B i O j).worker
+ (congrArg BlockPlanner.Visit.worker (index_visit B i j))
+ fuel 0 (ShrinkTermInputs.motifCount X : Word w) (bank B i O X T start j) (choices (w := w) B i X s j)
+
+theorem runs (j : Stage) (mem : Memory w) (rs : List (Report w))
+ (packet : PacketRun B i O X T start s fuel j mem rs) :
+ (globalVisit B i X T start s fuel j).Runs mem rs := (SourceOnline.Visit.ofWorker_runs ..).mpr packet.run
+
+theorem checked (L : DescriptorSpace.Layout) (cap : ℕ) (j : Stage) (mem : Memory w) (rs : List (Report w))
+ (packet : PacketRun B i O X T start s fuel j mem rs)
+ (hpos : 0 < fuel) (room : ShrinkInput.termEnd X start 10 < 2^w) (dataStart : levelStart L 0 ≤ start)
+ (recipeClock : ((A).plan.recipes (index B i j)).2.code.length+1+2*Online.N (A).size (A).size+5 ≤ cap)
+ (dataClock : fuel+3+4*(((A).catalog (index B i j)).params+1)+2*Online.N (A).size (A).size+5 ≤ cap) :
+ SourceOnline.Checked A L cap ⟨globalVisit B i X T start s fuel j,mem,rs⟩ := by
+ have hn := ShrinkTermSelection.motifCount_eq X
+ have fits : ShrinkTermInputs.motifCount X < 2^w := by
+ rw [hn]; unfold ShrinkInput.termEnd at room; omega
+ obtain ⟨rd,wr⟩ := packet.arena room
+ exact ⟨hpos,recipeClock,dataClock,(packet.bounds fits).1,
+ fun a v h => dataStart.trans (rd a v h).1, fun a v h => dataStart.trans (wr a v h).1⟩
+
+end CompressorRecords.ShrinkTermOnline
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermPacketBounds.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermPacketBounds.lean
new file mode 100644
index 0000000000..1f2f7b1a5c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermPacketBounds.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.CompressorShrinkTermPackets
+import OAI.Computability.VPVNP.CompressorOrdinalProgress
+
+/-!
+# Work and data-arena bounds of the shrinking term packets
+
+Both packets can be replayed under the online calendar. Every cursor
+increment occurs before the exclusive motif stop. Their reads and
+writes stay within the current shrinking arena, and each report obeys
+the source instruction cap.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkTermPackets
+
+open BurstRAM BlockPlanner Compression ShrinkBlockInputs ShrinkInput SourceOnline SourceTransport
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {i : Fin S.steps} {origin : PhaseRecipe.Expr}
+variable {g w : ℕ} {X : State (a i) (packingLaneBits (a i) g)} {T : IncidenceDirectory w} {start cap : ℕ}
+variable {s : X.ShrinkSelection B.shrink} {j : Stage} {m : Memory w} {rs : List (Report w)}
+
+local notation "N" => ShrinkTermInputs.motifCount X
+local notation "Z" => ShrinkInput.plan X start
+local notation "q" => ShrinkRankSpace.Shape.collectBank (ShrinkInput.plan X start) w
+local notation "W" => widthBase X start
+local notation "K" => ShrinkTermSelection.bundles X*ShrinkTermSelection.ranks (a i)
+
+/-- The two source rows already have the cursor progress, private cap and
+external charge needed to construct their linked online rows. -/
+theorem PacketRun.bounds (h : PacketRun B i origin X T start s cap j m rs) (stopFits : N < 2^w) :
+ Progress (N : Word w) 0 rs ∧ (∀ r ∈ rs, r.events.length < cap) ∧
+ RAMBuckets.cost Report.probes rs ≤ N * (1+probeRate B j) := by
+ have he := Progress.ofOrdinals N 0 N stopFits (Nat.zero_add _) rs h.cursors
+ have work := localSegment_event_bound ((runSegment_iff ..).mp h.run).1
+ refine ⟨he,work,?_⟩
+ rw [packet_cost,h.count,Nat.mul_add,Nat.mul_one]
+ exact Nat.add_le_add_left h.probes N
+
+/-- A data replay needs agreement only inside the allocated shrinking
+level. In particular all locations before the level's start are excluded. -/
+theorem PacketRun.arena (h : PacketRun B i origin X T start s cap j m rs)
+ (room : termEnd X start 10 < 2^w) :
+ Reads (fun x => start ≤ x ∧ x < termEnd X start 10) (eventLog rs) ∧
+ Writes (fun x => start ≤ x ∧ x < termEnd X start 10) (eventLog rs) := by
+ have count := ShrinkTermSelection.motifCount_eq X
+ have endSpace : termEnd X start 10 = ShrinkInput.stop X start + 2*K+K*10 := rfl
+ have stopEq : ShrinkInput.stop X start = W+6*K+2*(Z).B := rfl
+ have hrank : (Z).stop < 2^w := by change W < _; omega
+ have v := (Z).values T (placementBank X T start) Fintype.card_pos hrank
+ have begin := ShrinkInput.range_bounds X start
+ have first : start ≤ W := begin.1.trans (begin.2.1.trans begin.2.2.1)
+ have dense : (demandHead (w := w) X start).val = ShrinkInput.stop X start := Nat.mod_eq_of_lt (by omega)
+ have term : (termHead (w := w) X start).val = ShrinkInput.stop X start+2*K := Nat.mod_eq_of_lt (by omega)
+ let bank := pairBank X T start
+ have ab : (bank 3).val = W+4*K+2*(Z).B := by
+ change (W+2*((Z).B*(q 4).val)+2*((Z).B*(q 4).val)+2*(Z).B)%(2^w) = _
+ rw [v.stride]
+ change (W+2*K+2*K+2*(Z).B)%(2^w) = _
+ rw [Nat.mod_eq_of_lt (by omega)]; omega
+ have cd : (bank 4).val = W+K := by
+ have word : (ShrinkRAM.word w W).val = W := Nat.mod_eq_of_lt hrank
+ change ((ShrinkRAM.word w W).val+(Z).B*(q 4).val)%(2^w) = _
+ rw [word,v.stride]; change (W+K)%(2^w) = W+K; apply Nat.mod_eq_of_lt; omega
+ have ⟨_,earlier,_,_⟩ := termLayout X T start 10 room
+ have topAB : (bank 3).val+(Z).B*(bank 1).val ≤ (demandHead (w := w) X start).val := earlier.abWidths
+ have topCD : (bank 4).val+(Z).B*(bank 2).val ≤ (demandHead (w := w) X start).val := earlier.cdWidths
+ cases j with
+ | gather =>
+ refine ⟨fun a v mem => ?_,fun a v mem => ?_⟩
+ · rcases h.reads a v mem with hab|hcd
+ · change (bank 3).val ≤ a.val ∧ a.val < (bank 3).val+(Z).B*(bank 1).val at hab
+ omega
+ · change (bank 4).val ≤ a.val ∧ a.val < (bank 4).val+(Z).B*(bank 2).val at hcd
+ omega
+ · have wr := h.writes a v mem
+ change (demandHead (w := w) X start).val ≤ a.val ∧ a.val < (demandHead (w := w) X start).val+2*K at wr
+ omega
+ | select =>
+ refine ⟨fun a v mem => ?_,fun a v mem => ?_⟩
+ · have rd := h.reads a v mem
+ change (demandHead (w := w) X start).val ≤ a.val ∧ a.val < (termHead (w := w) X start).val+N*10 at rd
+ omega
+ · have wr := h.writes a v mem
+ change (termHead (w := w) X start).val ≤ a.val ∧ a.val < (termHead (w := w) X start).val+N*10 at wr
+ omega
+
+end CompressorRecords.ShrinkTermPackets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermPackets.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermPackets.lean
new file mode 100644
index 0000000000..b6ca729403
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermPackets.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.CompressorShrinkBlockInputs
+import OAI.Computability.VPVNP.CompressorShrinkInputTerms
+import OAI.Computability.VPVNP.CompressorShrinkGatherDispatch
+import OAI.Computability.VPVNP.CompressorTermWorkerFootprint
+import OAI.Computability.VPVNP.CompressorSourceWalk
+
+/-!
+# The two term-selection packets in the shrinking block calendar
+
+The ordered packets correspond to the actual gather and selection visits
+of the block planner. Each packet records the source program, complete
+branch tapes, successor ordinals, and external read and write bounds.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkTermPackets
+
+open BurstRAM BlockPlanner Compression ShrinkBlockInputs ShrinkInput PhaseRecipe SourceTransport
+open scoped Classical Fin.CommRing
+
+/-- The two native stages of term preparation, gathering AB/CD demand widths and selecting a
+term for each motif. -/
+inductive Stage where
+ | gather | select
+ deriving DecidableEq
+
+/-- Run the demand gather before the term selector so the selector sees the completed dense
+pairs. -/
+def order : List Stage := [.gather,.select]
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) (origin : Expr)
+
+/-- The planned gather or selector visit at its position in the shrinking substep's term
+window. -/
+noncomputable def visit : Stage → Visit
+ | .gather => (termVisits B i origin)[0]'(by rw [termVisits_length]; decide)
+ | .select => (termVisits B i origin)[1]'(by rw [termVisits_length]; decide)
+
+theorem order_visits : order.map (visit B i origin) = termVisits B i origin := rfl
+
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+variable (s : X.ShrinkSelection B.shrink)
+local notation "N" => ShrinkTermInputs.motifCount X
+local notation "H" => ShrinkTermSelection.bundles X
+local notation "Q" => ShrinkTermSelection.ranks (a i)
+local notation "src" => demandHead (w := w) X start
+local notation "dst" => termHead (w := w) X start
+
+/-- The public operands of the demand gather or motif selector, using the actual pair bank or
+the dense demand and term-table heads. -/
+noncomputable def bank : (j : Stage) → Fin (visit B i origin j).worker.params → Word w
+ | .gather => pairBank X T start
+ | .select => TermWorker.motifData B.shrink finTwoEquiv SelectedScore.supplyOrder.entries w
+ (ShrinkTermSelection.addr src dst 10)
+
+/-- An empty tape per gather row, or the encoded selected term's tape per dense motif for the
+selector. -/
+noncomputable def choices : Stage → List (List Bool)
+ | .gather => List.replicate (H*Q) []
+ | .select => List.ofFn (ShrinkTermSelection.tapes B.shrink X s w)
+
+/-- Running the selected worker with its physical bank from cursor zero on the given tapes
+yields the indicated reports. -/
+noncomputable def source (cap : ℕ) (j : Stage) (mem : Memory w) (bs : List (List Bool)) (rs : List (Report w)) : Prop :=
+ let P := ((visit B i origin j).worker.table.instantiate w (bank B i origin X T start j)).program
+ runSegment P cap (some 0) mem bs = some rs
+
+/-- The allowed external read region for gathering demands or reading the dense demands and
+selected term records. -/
+def readable : Stage → ℕ → Prop
+ | .gather => ShrinkDemandGather.ReadRegion H (pairBank X T start)
+ | .select => fun x => (src).val ≤ x ∧ x < (dst).val+N*10
+
+/-- The gather's output pair region or the selector's ten-word term rows, according to the
+phase. -/
+def writable : Stage → ℕ → Prop
+ | .gather => ShrinkDemandGather.WriteRegion H Q (pairBank X T start)
+ | .select => fun x => (dst).val ≤ x ∧ x < (dst).val+N*10
+
+/-- The per-motif probe bound for a term packet, four for gathering or the term-reader bound
+for two demands and eight supplies. -/
+noncomputable def probeRate : Stage → ℕ
+ | .gather => 4
+ | .select => TermRecordScan.probesPerRow B.shrink 2 8
+
+/-- The physical gather or selection run with its tapes, cursor sequence, motif report count,
+memory footprint and probe bound. -/
+structure PacketRun (cap : ℕ) (j : Stage) (mem : Memory w) (rs : List (Report w)) : Prop where
+ run : source B i origin X T start cap j mem (choices (w := w) B i X s j) rs
+ reads : Reads (readable i X T start j) (eventLog rs)
+ writes : Writes (writable i X T start j) (eventLog rs)
+ cursors : rs.map Report.result = (List.range' 1 N).map (fun k : ℕ => some (k : Word w))
+ branches : branchPaths rs = choices (w := w) B i X s j
+ count : rs.length = N
+ probes : countProbes (eventLog rs) ≤ N * probeRate B j
+
+theorem gathered_packet (cap : ℕ) (hcap : ShrinkDemandGather.cost < cap) (room : termEnd X start 10 < 2^w)
+ (mem : Memory w) (rs : List (Report w)) (hg : ShrinkDemandGather.Gathered H Q (pairBank X T start) cap mem rs) :
+ PacketRun B i origin X T start s cap .gather mem rs := by
+ have layout := (termLayout X T start 10 room).1
+ let P := ShrinkDemandGather.program (pairBank X T start)
+ let cursor (j : ℕ) : Word w := j
+ have inc (j : ℕ) (_ : j < H*Q) (m : Memory w) (bits : List Bool) (r : Report w)
+ (h : execute P cap (P.start (cursor j)) m bits = some r) : r.result = some (cursor (j+1)) := by
+ have he := (execute_prefix_unique (suffix := bits) (ShrinkDemandGather.visit_run (pairBank X T start) (cursor j) m hcap) h).2
+ rw [← he,ShrinkDemandGather.visits_result]; simp [cursor]
+ have ord := OrdinalRun.successors P cap cursor (H*Q) inc 0 (List.replicate (H*Q) []) mem rs (by simp) hg.run
+ obtain ⟨rd,wr⟩ := ShrinkDemandGather.footprints _ layout hcap mem rs hg.run
+ exact ⟨hg.run,rd,wr,by simpa only [List.length_replicate,ShrinkTermSelection.motifCount_eq] using ord,
+ ((runSegment_iff ..).mp hg.run).2.2,hg.count.trans (ShrinkTermSelection.motifCount_eq X).symm,
+ by rw [hg.probes,ShrinkTermSelection.motifCount_eq]; change 4*(H*Q) ≤ (H*Q)*4; omega⟩
+
+set_option maxHeartbeats 1200000 in
+theorem selected_packet (cap : ℕ) (room : termEnd X start 10 < 2^w)
+ (mem : Memory w) (rs : List (Report w))
+ (h : ShrinkTermSelection.Written B.shrink X src dst 10 cap s mem rs) :
+ PacketRun B i origin X T start s cap .select mem rs := by
+ obtain ⟨_,_,sep,fit⟩ := termLayout X T start 10 room
+ let L := ShrinkTermInputs.termRows X src dst 10 le_rfl sep fit
+ let addr := ShrinkTermSelection.addr src dst 10
+ let P := ShrinkTermSelection.termProgram B.shrink src dst 10
+ let cursor (j : ℕ) : Word w := j
+ let bits := List.ofFn (ShrinkTermSelection.tapes B.shrink X s w)
+ have hw : TermWorker.Addresses L addr := TermWorker.addresses_strided (n := 8) _ _ _ _ le_rfl le_rfl sep fit
+ have inc (j : ℕ) (hj : j visit B i origin p.stage)) = termVisits B i origin ∧
+ SourceWalk.Chronological (PacketRun B i origin X T start s cap) before ps ∧
+ ShrinkTermSelection.Written B.shrink X src dst 10 cap s mid ts ∧
+ ShrinkTermSelection.oldRows X (thickBank X T start) (cdBank X T start) (piecesBank X T start) out ∧
+ ∀ x < ShrinkInput.stop X start, out x = before x := by
+ obtain ⟨gs,hg,_,full⟩ := ShrinkInput.gather_select_from X T start B.shrink before stored 10 le_rfl room fit cap
+ gatherCap termCap
+ obtain ⟨ts,ht,cols,frame⟩ := full s
+ exact ⟨gs,ts,rfl,⟨rfl,gathered_packet B i origin X T start s cap gatherCap room before gs hg,
+ rfl,selected_packet B i origin X T start s cap room _ ts ht,trivial⟩,ht,cols,frame⟩
+
+end CompressorRecords.ShrinkTermPackets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermPhases.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermPhases.lean
new file mode 100644
index 0000000000..c7837f9bf5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermPhases.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.CompressorShrinkTermSelection
+import OAI.Computability.VPVNP.CompressorShrinkDemandFrame
+
+/-!
+# The consecutive demand-gather and term-selection segments
+
+The first segment reads the balanced AB table and old CD table. Its final
+memory is the initial memory of the second segment. The second segment
+admits precisely the paper's term choices. Its final memory contains
+both the selected term rows and the original widths and starts needed
+by the shrinking kernel.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkTermSelection
+
+open Compression Compression.PackingData MotifGrid MotifBlocks ShrinkMotif BurstRAM
+open scoped Classical
+
+variable {a g w : ℕ} {k : Type*} [_root_.Field k] {factor : ℝ}
+variable (F : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (X : State a (packingLaneBits a g))
+
+/-- Number of directed packed bundles, counting each base vertex, packing tag, residual lane
+and outgoing port. -/
+abbrev bundles := Fintype.card X.Base * (2^(packingTagBits (2^a)) * 2^g) * 2^a
+/-- Number of motif ranks or balanced pieces in one shrinking bundle at input degree exponent
+`a`. -/
+abbrev ranks (a : ℕ) := pieceCount (2^a) (2*2^a+1)
+
+theorem motifCount_eq : ShrinkTermInputs.motifCount X = bundles X * ranks a :=
+ (Fintype.card_congr (ShrinkMotifOrder.stateNumber X)).trans (Fintype.card_fin _)
+
+/-- Readback of the thick and CD width rows and AB pieces in their physical per-bundle orders. -/
+noncomputable abbrev oldRows (thick cdRows ab : Fin 5 → BurstRAM.Word w) (mem : Memory w) :=
+ DemandWidths.Stored X.packingData (Shrink.packedIndex X.baseIndex) X.packingWidth
+ X.shrinkOrder X.shrinkNumber thick cdRows ab mem
+
+local notation "N" => ShrinkTermInputs.motifCount X
+
+set_option maxHeartbeats 1000000 in
+theorem gather_select (thick cdRows ab : Fin 5 → BurstRAM.Word w) (dense term : BurstRAM.Word w)
+ (stride : ℕ) (wide : 10 ≤ stride) (sep : dense.val+N*2 ≤ term.val)
+ (room : term.val+N*stride < 2^w) (ref : Memory w) (stored : oldRows X thick cdRows ab ref)
+ (layout : ShrinkDemandGather.Layout (bundles X) (ranks a) (ShrinkTermInputs.operands cdRows ab dense))
+ (earlier : ShrinkDemandFrame.Before (bundles X) (2^(2*2^a+1)*2^a/4) (ranks a) thick cdRows ab dense.val)
+ (fit : fitConstant F+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w)
+ (cap : ℕ) (gatherCap : ShrinkDemandGather.cost < cap) (termCap : TermWorker.budget F 2 8 w X.maxWireWidth ≤ cap) :
+ ∃ gs, ShrinkDemandGather.Gathered (bundles X) (ranks a) (ShrinkTermInputs.operands cdRows ab dense) cap ref gs ∧
+ let mem := after ref (eventLog gs)
+ (∀ bs : Fin N → List Bool, (runSegment (termProgram F dense term stride) cap (some 0) mem (List.ofFn bs)).isSome ↔
+ ∃! s : X.ShrinkSelection F, bs = tapes F X s w) ∧
+ ∀ s : X.ShrinkSelection F, ∃ ts, Written F X dense term stride cap s mem ts ∧
+ oldRows X thick cdRows ab (after mem (eventLog ts)) := by
+ obtain ⟨gs,hgs,hpair⟩ := ShrinkTermInputs.gather X.packingData (Shrink.packedIndex X.baseIndex) X.packingWidth
+ X.shrinkNumber X.shrinkOrder thick cdRows ab dense ref stored layout gatherCap
+ let mid := after ref (eventLog gs)
+ obtain ⟨legal,full⟩ := native F X dense term stride wide sep room mid hpair fit cap termCap
+ refine ⟨gs,hgs,legal,fun s => ?_⟩
+ obtain ⟨ts,hw⟩ := full s
+ refine ⟨ts,hw,ShrinkDemandFrame.retain stored earlier (fun x hx => ?_)⟩
+ exact (hw.frame x (.inl (by omega))).trans (hgs.frame x (.inl hx))
+
+end CompressorRecords.ShrinkTermSelection
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermRecipe.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermRecipe.lean
new file mode 100644
index 0000000000..0ab015ee48
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermRecipe.lean
@@ -0,0 +1,233 @@
+import OAI.Computability.VPVNP.CompressorTermWorkerRecipe
+import OAI.Computability.VPVNP.CompressorShrinkTermInputs
+import OAI.Computability.VPVNP.CompressorBundleKeyTable
+
+/-!
+# Online row planners for the shrinking motif gather and selection
+
+Both phases visit one row per CD occurrence. The packed AB width and offset
+rectangles precede the dense pair array, followed by the selected term rows.
+The sorted CD widths occupy the second half of the sorted-width rectangle.
+The planner obtains its shape scalars and allocation heads from level expressions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkTermRecipe
+
+open BurstRAM BurstRAM.PrivateRAM PhaseRecipe Compression Compression.PackingData MotifConversion MotifGrid MotifBlocks
+open scoped Fin.CommRing
+open private pieces_arithmetic from OAI.Computability.VPVNP.SlotDemandEnergy
+
+/-- Dynamic scalars and addresses read by the two planners. -/
+structure Inputs where
+ /-- Expression for the number of input base vertices at the selected shrinking level. -/
+ vertices : Expr
+ /-- Expression for the input degree used to count bundles and old port slots. -/
+ degree : Expr
+ /-- Expression for the number of input lanes per base vertex before shrinking. -/
+ lanes : Expr
+ /-- Expression for the residual lane count used to enumerate packed bundles. -/
+ residualLanes : Expr
+ /-- Base-address expression for the two sorted thick and CD width rectangles. -/
+ sortedWidth : Expr
+ /-- The row stride expression shared by the per-bundle sorted-width rectangles. -/
+ sortedStride : Expr
+ /-- The starting address expression for the balanced AB pieces, ahead of the dense pair and
+ term tables. -/
+ abStart : Expr
+
+variable (a stride : ℕ) (I : Inputs)
+
+/-- Number of CD motif ranks per bundle, computed from the input degree and the shrinking color
+count. -/
+def ranks (a : ℕ) := pieceCount (2^a) (Shrink.colors a)
+
+/-- The runtime bundle count obtained from base vertices, tags, residual lanes and input
+degree. -/
+def bundles := (I.vertices.mul ((Expr.lit (2^(Shrink.J a))).mul I.residualLanes)).mul I.degree
+/-- The runtime count of old directed slots over all base vertices and input lanes. -/
+def oldSlots := (I.vertices.mul I.lanes).mul I.degree
+/-- Total number of dense term visits, one for every bundle and motif rank. -/
+def count := (bundles a I).mul (.lit (ranks a))
+/-- The head of the sorted CD widths, following the entire thick-width rectangle. -/
+def cdStart := I.sortedWidth.add ((bundles a I).mul I.sortedStride)
+/-- Head of the dense two-word AB/CD demand pairs, following the AB width and offset
+rectangles. -/
+def dense := I.abStart.add ((Expr.lit 2).mul (count a I))
+/-- Head of the selected term records, immediately after all dense demand pairs. -/
+def term := (dense a I).add ((Expr.lit 2).mul (count a I))
+/-- Exclusive end of the selected term table at the supplied record stride. -/
+def stopAddress := (term a I).add ((count a I).mul (.lit stride))
+
+/-- The rank counts, sorted stride and AB, CD and dense output heads used by the paired demand
+gather. -/
+def gatherOperands : Fin 6 → Expr :=
+ ![.lit (ranks a),.lit (ranks a),I.sortedStride,I.abStart,cdStart a I,dense a I]
+
+/-- The selector's dense demand base and stride of two, followed by the selected term base and
+record stride. -/
+def termHeads : Fin 4 → Expr := ![dense a I,.lit 2,term a I,.lit stride]
+
+variable {k : Type*} [_root_.Field k] {H' : ℝ} (F : FixedBlock k ShrinkMotif.demandSource ShrinkMotif.demandTarget
+ ShrinkMotif.supply (realWidths ShrinkMotif.demandMass) (realWidths ShrinkMotif.supplyMass) (31/16) H')
+variable (supply : Fin 8 ≃ Bool × Fin 4)
+
+/-- A planner phase launching the paired demand gather from zero over the full dense motif
+count. -/
+def gatherPhase {G : ℕ} (tag : ℕ) (room : 6 ≤ G) : Phase G :=
+ Phase.ofParams room tag (.lit 0) (count a I) (gatherOperands a I)
+
+/-- A planner phase launching the fused motif term selector with the computed addresses and
+fixed supply ordering. -/
+noncomputable def termPhase {G : ℕ} (tag : ℕ) (room : (TermWorker.motifPass F finTwoEquiv 8).params ≤ G) :
+ Phase G :=
+ Phase.ofParams room tag (.lit 0) (count a I) (TermWorker.motifExprs F finTwoEquiv supply (termHeads a stride I))
+
+variable {a} {g w : ℕ} (X : State a (packingLaneBits a g))
+
+/-- Number of base vertices in the input state used by the term recipe's address formulas. -/
+abbrev N := Fintype.card X.Base
+/-- The concrete number of packed bundles in this input state for the given degree and residual
+lane exponents. -/
+abbrev B := BundleKeys.numBundles (N X) a g
+/-- The concrete number of dense motif rows, equal to the bundle count times the number of
+ranks per bundle. -/
+abbrev M := B X * ranks a
+/-- Number of original directed input ports across the base vertices and all uncompressed
+packing lanes. -/
+abbrev originalSlots := (N X * 2^(packingLaneBits a g)) * 2^a
+
+/-- The chosen physical interval indexes every motif exactly once. -/
+theorem count_card : M X = ShrinkTermInputs.motifCount X :=
+ ((Fintype.card_congr (ShrinkMotifOrder.stateNumber X)).trans (Fintype.card_fin _)).symm
+
+/-- Exact cardinality before taking any word reduction. -/
+theorem four_count : 4 * M X = 3 * originalSlots X := by
+ let h := 2^(Shrink.colors a) * 2^a / 4
+ have hq : ranks a = 3*h := (pieces_arithmetic (State.two_le_packingColors a) (Nat.two_pow_pos a)).1
+ have total := BundleKeys.bundle_rows_total (N X) a g
+ change B X*h + B X*ranks a = originalSlots X at total
+ change 4*(B X*ranks a) = _
+ rw [← total,hq]; ring
+
+theorem count_le_slots : M X ≤ originalSlots X := by have := four_count X; omega
+
+theorem count_eq_three_quarters : M X = 3*originalSlots X/4 := by have := four_count X; omega
+
+variable (pub : Fin 5 → BurstRAM.Word w) (state : BurstRAM.Word w) (mem : Memory w)
+
+/-- The input fields describe the current dyadic state and the already packed
+source rectangle. The AB width rectangle starts at the supplied allocator cursor. -/
+structure Describes (sorted : Fin 5 → BurstRAM.Word w) (abStart : ℕ) : Prop where
+ vertices : I.vertices.eval pub state mem = (N X : BurstRAM.Word w)
+ degree : I.degree.eval pub state mem = (2^a : ℕ)
+ lanes : I.lanes.eval pub state mem = (2^(packingLaneBits a g) : ℕ)
+ residual : I.residualLanes.eval pub state mem = (2^g : ℕ)
+ sortedWidth : I.sortedWidth.eval pub state mem = sorted 4
+ sortedStride : I.sortedStride.eval pub state mem = sorted 3
+ abHead : I.abStart.eval pub state mem = (abStart : BurstRAM.Word w)
+
+variable {sorted : Fin 5 → BurstRAM.Word w} {abStart : ℕ} (h : Describes I X pub state mem sorted abStart)
+local notation "ev" => Expr.eval pub state mem
+
+include h in
+theorem eval_bundles : ev (bundles a I) = (B X : BurstRAM.Word w) := by
+ simp only [bundles,Expr.mul,Expr.eval,BinaryOp.eval,h.vertices,h.degree,h.residual,← Nat.cast_mul]; rfl
+
+include h in
+theorem eval_oldSlots : ev (oldSlots I) = (originalSlots X : BurstRAM.Word w) := by
+ simp only [oldSlots,Expr.mul,Expr.eval,BinaryOp.eval,h.vertices,h.degree,h.lanes,← Nat.cast_mul]
+
+include h in
+theorem eval_count : ev (count a I) = (M X : BurstRAM.Word w) := by
+ change ev (bundles a I) * (ranks a : BurstRAM.Word w) = _
+ rw [eval_bundles I X pub state mem h,Nat.cast_mul]
+
+include h in
+theorem eval_dense : ev (dense a I) = ((abStart+2*M X : ℕ) : BurstRAM.Word w) := by
+ change ev I.abStart + 2*ev (count a I) = _
+ simp only [h.abHead,eval_count I X pub state mem h,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat]
+
+include h in
+theorem eval_term : ev (term a I) = ((abStart+2*M X+2*M X : ℕ) : BurstRAM.Word w) := by
+ change ev (dense a I) + 2*ev (count a I) = _
+ simp only [eval_dense I X pub state mem h,eval_count I X pub state mem h,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat]
+
+include h in
+theorem eval_stopAddress : ev (stopAddress a stride I) =
+ ((abStart+2*M X+2*M X+M X*stride : ℕ) : BurstRAM.Word w) := by
+ change ev (term a I) + ev (count a I)*(stride : BurstRAM.Word w) = _
+ simp only [eval_term I X pub state mem h,eval_count I X pub state mem h,Nat.cast_add,Nat.cast_mul]
+
+include h in
+theorem stop_val (fits : originalSlots X < 2^w) : (ev (count a I)).val = ShrinkTermInputs.motifCount X := by
+ rw [eval_count I X pub state mem h,Fin.val_natCast,Nat.mod_eq_of_lt ((count_le_slots X).trans_lt fits),count_card]
+
+include h in
+theorem gather_bank (prefixHead : ℕ) (total : BurstRAM.Word w) :
+ (fun i => ev (gatherOperands a I i)) = ShrinkTermInputs.operands
+ (BundlePrefixGraph.prefixPublic sorted (B X) (2^a) (Shrink.colors a) prefixHead true)
+ (DemandWidths.packedPublic total (B X) (ranks a) abStart)
+ ((abStart+2*M X : ℕ) : BurstRAM.Word w) := by
+ have cd : ev (cdStart a I) = (((sorted 4).val+B X*(sorted 3).val : ℕ) : BurstRAM.Word w) := by
+ change ev I.sortedWidth + ev (bundles a I)*ev I.sortedStride = _
+ simp [h.sortedWidth,h.sortedStride,eval_bundles I X pub state mem h]
+ funext i
+ fin_cases i <;> first | exact cd | exact eval_dense I X pub state mem h | exact h.sortedStride | exact h.abHead | rfl
+
+include h in
+theorem term_bank :
+ (fun i => ev (TermWorker.motifExprs F finTwoEquiv supply (termHeads a stride I) i)) =
+ TermWorker.motifData F finTwoEquiv supply w
+ ![((abStart+2*M X : ℕ) : BurstRAM.Word w),2,((abStart+2*M X+2*M X : ℕ) : BurstRAM.Word w),stride] := by
+ rw [TermWorker.eval_motifExprs]
+ congr 1
+ funext i
+ fin_cases i <;> first | exact eval_dense I X pub state mem h | exact eval_term I X pub state mem h | rfl
+
+/-- Read back the physical row emitted by the compiled planner. Fields above
+the worker arity contain the zero padding of the shared dispatcher frame. -/
+def Installed {K G : ℕ} (P : Phase G) (tag limit : ℕ) (bank : Fin K → BurstRAM.Word w) : Prop :=
+ let row := Controller.rowBase G pub mem
+ let out := after mem (P.recipe.report pub state mem).events
+ out row.val = (tag : BurstRAM.Word w) ∧ out (row+1).val = 0 ∧ out (row+2).val = (limit : BurstRAM.Word w) ∧
+ ∀ j : Fin G, Controller.field (row+2) out (j.val+1) = if hi : j.val < K then bank ⟨j.val,hi⟩ else 0
+
+private theorem installed {K G : ℕ} (tag limit : ℕ) (stop : Expr) (params : Fin K → Expr) (room : K ≤ G)
+ (bank : Fin K → BurstRAM.Word w) (values : (fun i => ev (params i)) = bank)
+ (counter : ev stop = (limit : BurstRAM.Word w)) (rowFits : (Controller.rowBase G pub mem).val + (G+3) ≤ 2^w) :
+ Installed pub state mem (Phase.ofParams room tag (.lit 0) stop params) tag limit bank := by
+ let phase := Phase.ofParams room tag (.lit 0) stop params
+ obtain ⟨tagged,first,last,fields⟩ := PhaseRecipe.row_fields phase pub state mem rowFits
+ refine ⟨tagged,first,last.trans counter,fun j => ?_⟩
+ rw [fields]
+ change ev (if hi : j.val < K then params ⟨j.val,hi⟩ else .lit 0) = _
+ split <;> first | exact congrFun values _ | rfl
+
+include h in
+theorem gather_compiled {G : ℕ} (tag : ℕ) (room : 6 ≤ G) (prefixHead : ℕ) (total : BurstRAM.Word w)
+ (rowFits : (Controller.rowBase G pub mem).val+(G+3) ≤ 2^w) :
+ Installed pub state mem (gatherPhase a I tag room) tag (ShrinkTermInputs.motifCount X)
+ (ShrinkTermInputs.operands
+ (BundlePrefixGraph.prefixPublic sorted (B X) (2^a) (Shrink.colors a) prefixHead true)
+ (DemandWidths.packedPublic total (B X) (ranks a) abStart) ((abStart+2*M X : ℕ) : BurstRAM.Word w)) :=
+ installed pub state mem _ _ _ _ _ _ (gather_bank I X pub state mem h prefixHead total)
+ ((eval_count I X pub state mem h).trans (congrArg (fun n : ℕ => (n : BurstRAM.Word w)) (count_card X))) rowFits
+
+include h in
+theorem term_compiled {G : ℕ} (tag : ℕ) (room : (TermWorker.motifPass F finTwoEquiv 8).params ≤ G)
+ (rowFits : (Controller.rowBase G pub mem).val+(G+3) ≤ 2^w) :
+ Installed pub state mem (termPhase a stride I F supply tag room) tag (ShrinkTermInputs.motifCount X)
+ (TermWorker.motifData F finTwoEquiv supply w
+ ![((abStart+2*M X : ℕ) : BurstRAM.Word w),2,((abStart+2*M X+2*M X : ℕ) : BurstRAM.Word w),stride]) :=
+ installed pub state mem _ _ _ _ _ _ (term_bank stride I F supply X pub state mem h)
+ ((eval_count I X pub state mem h).trans (congrArg (fun n : ℕ => (n : BurstRAM.Word w)) (count_card X))) rowFits
+
+end CompressorRecords.ShrinkTermRecipe
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermSelection.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermSelection.lean
new file mode 100644
index 0000000000..1799e30c1a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermSelection.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.CompressorShrinkTermInputs
+import OAI.Computability.VPVNP.CompressorTermWorkerScan
+import OAI.Computability.VPVNP.CompressorShrinkKernelSlices
+import OAI.Computability.VPVNP.ShrinkFieldBounds
+import OAI.Computability.VPVNP.StatePassHistory
+
+/-!
+# Shrinking choices from the physical balanced and original wire widths
+
+The gather and the fused term verifier run on successive memory states.
+Their successful streams biject with the actual six-party terms at the
+packed CD motifs. Grid, repetition and payload words remain available at
+the same dense ordinal for scoring and interval subdivision.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkTermSelection
+
+open Compression Compression.PackingData MotifGrid MotifBlocks MotifConversion ShrinkMotif BurstRAM
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {factor : ℝ}
+variable (F : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+
+local notation "N" => ShrinkTermInputs.motifCount X
+local notation "roles" => ShrinkSliceArrays.supplyRoles
+local notation "demand" => ShrinkTermInputs.demand X
+
+/-- The word-fit constant supplied by the native term-scan theorem for shrinking motifs with
+two demand coordinates. -/
+noncomputable def fitConstant :=
+ (TermWorker.scan_native F finTwoEquiv roles demandMass_pos supplyMass_pos).choose
+
+/-- Supply tapes and term rows both use the physical bundle/rank ordinal. -/
+noncomputable def tapes (s : X.ShrinkSelection F) (w : ℕ) (j : Fin N) : List Bool :=
+ TermRecordScan.tape F roles (demand j) w (s (ShrinkMotifOrder.entries X j)).val
+
+/-- Identify a term choice at each shrinking motif with the same choices in the dense physical
+scan order. -/
+noncomputable def reindex : X.ShrinkSelection F ≃ TermRecordScan.Choices F demand :=
+ Equiv.piCongrLeft' (fun m => ↥(outerIndices F (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m)))
+ (ShrinkMotifOrder.entries X).symm
+
+/-- The first header address of the actual CD occurrence's term. -/
+noncomputable def rowBase (term : BurstRAM.Word w) (stride : ℕ) (m : X.packingData.Motif) : BurstRAM.Word w :=
+ Fin.ofNat _ (term.val+(ShrinkMotifOrder.stateNumber X m).val*stride)
+
+/-- The term worker's four public words, specifying the dense demand base, two demand fields
+per motif, the term base and the term-record stride. -/
+def addr (dense term : BurstRAM.Word w) (stride : ℕ) : Fin 4 → BurstRAM.Word w :=
+ ![dense.val, 2, term.val, stride]
+
+/-- The native shrinking term verifier instantiated with the two demand roles and the dense
+demand and term addresses. -/
+noncomputable abbrev termProgram (dense term : BurstRAM.Word w) (stride : ℕ) :=
+ TermWorker.program F finTwoEquiv roles (addr dense term stride)
+
+/-- The physical term scan runs on the tapes of the given selection, stores each motif's
+selected fields, and has the stated cursor, frame, report count and resource bounds. -/
+structure Written (dense term : BurstRAM.Word w) (stride cap : ℕ) (s : X.ShrinkSelection F)
+ (before : Memory w) (rs : List (Report w)) : Prop where
+ run : runSegment (termProgram F dense term stride) cap (some 0) before (List.ofFn (tapes F X s w)) = some rs
+ fields : ∀ m, TermRecordScan.Fields F roles demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m) (s m).val
+ (rowBase X term stride m) (after before (eventLog rs))
+ frame : ∀ x, x < term.val ∨ term.val + N*stride ≤ x → after before (eventLog rs) x = before x
+ cursor : endState (some (0 : BurstRAM.Word w)) rs = some (N : BurstRAM.Word w)
+ count : rs.length = N
+ branches : branchPaths rs = List.ofFn (tapes F X s w)
+ probes : countProbes (eventLog rs) ≤ N * TermRecordScan.probesPerRow F 2 8
+ steps : (eventLog rs).length ≤ N * TermWorker.budget F 2 8 w X.maxWireWidth
+
+set_option maxHeartbeats 1600000 in
+theorem native (dense term : BurstRAM.Word w) (stride : ℕ) (wide : 10 ≤ stride)
+ (sep : dense.val+N*2 ≤ term.val) (room : term.val+N*stride < 2^w)
+ (mem : Memory w) (pairs : ShrinkTermInputs.statePairs X dense mem)
+ (fit : fitConstant F+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w)
+ (cap : ℕ) (hcap : TermWorker.budget F 2 8 w X.maxWireWidth ≤ cap) :
+ (∀ bs : Fin N → List Bool, (runSegment (termProgram F dense term stride) cap (some 0) mem (List.ofFn bs)).isSome ↔
+ ∃! s : X.ShrinkSelection F, bs = tapes F X s w) ∧
+ ∀ s : X.ShrinkSelection F, ∃ rs, Written F X dense term stride cap s mem rs := by
+ let L := ShrinkTermInputs.termRows X dense term stride wide sep room
+ have hin := ShrinkTermInputs.inputs X dense term stride wide sep room mem pairs
+ have hw (j : Fin N) (e : Bool) : demand j e ≤ X.maxWireWidth :=
+ X.packingData.shrinkDemandWidths_le (State.two_le_packingColors _) (Nat.two_pow_pos _)
+ X.shrinkNumber X.packingWidth (fun _ => X.width_le_maxWireWidth _) _ e
+ have haddr : TermWorker.Addresses L (addr dense term stride) :=
+ TermWorker.addresses_strided (n := 8) _ _ _ _ le_rfl wide sep room
+ obtain ⟨legal,chosen⟩ := (TermWorker.scan_native F finTwoEquiv roles demandMass_pos supplyMass_pos).choose_spec
+ N X.maxWireWidth w fit L (addr dense term stride) haddr demand hw mem hin cap hcap
+ constructor
+ · intro bs
+ rw [legal]
+ let P := fun v : TermRecordScan.Choices F demand =>
+ bs = fun j => TermRecordScan.tape F roles (demand j) w (v j).val
+ let E := reindex F X
+ change (∃! v, P v) ↔ ∃! s, P (E s)
+ constructor
+ · rintro ⟨v,hv,uniq⟩
+ exact ⟨E.symm v,by simpa using hv,fun s hs => E.injective (by simpa using uniq _ hs)⟩
+ · rintro ⟨s,hs,uniq⟩
+ refine ⟨E s,hs,fun v hv => ?_⟩
+ have h := uniq (E.symm v) (by simpa using hv)
+ simpa using congrArg E h
+ · intro s
+ obtain ⟨rs,hr,fields,frame,cursor,count,bs,probes,steps⟩ := chosen (reindex F X s)
+ refine ⟨rs,hr,fun m => ?_,fun x h => frame x (fun i => ?_),cursor,count,bs,probes,steps⟩
+ · let j := (ShrinkMotifOrder.entries X).symm m
+ have h := fields j
+ have eqn : ShrinkMotifOrder.entries X j = m := (ShrinkMotifOrder.entries X).apply_symm_apply m
+ have hb : L.base j = rowBase X term stride m := by
+ change Fin.ofNat _ (term.val+j.val*stride) = Fin.ofNat _ (term.val+_*stride)
+ rw [ShrinkMotifOrder.entries_ordinal]
+ rw [hb] at h
+ change TermRecordScan.Fields F roles demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth (ShrinkMotifOrder.entries X j))
+ (s (ShrinkMotifOrder.entries X j)).val _ _ at h
+ rwa [eqn] at h
+ · have endRow := Nat.mul_le_mul_right stride i.isLt
+ rw [Nat.succ_mul] at endRow
+ have hb : (L.base i).val = term.val+i.val*stride := Nat.mod_eq_of_lt (by omega)
+ change x < (L.base i).val ∨ (L.base i).val + 2+8 ≤ x
+ rw [hb]; omega
+
+end CompressorRecords.ShrinkTermSelection
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkTermVisitReadback.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkTermVisitReadback.lean
new file mode 100644
index 0000000000..afb384c16e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkTermVisitReadback.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.CompressorShrinkTermPackets
+
+/-!
+# Operand readback of the two actual shrinking term visits
+
+The planner expressions read the published shrinking level and allocator
+origin. Their evaluated operands, initial cursors and exclusive stops are
+the ones used by the chronological native packets.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkTermPackets
+
+open BurstRAM BlockPlanner Compression PhaseRecipe ShrinkBlockInputs ShrinkInput
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) (origin : Expr)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+
+local notation "Z" => plan X start
+local notation "q" => ShrinkRankSpace.Shape.collectBank (plan X start) w
+local notation "rank" => ShrinkRAM.word w (ShrinkRankSpace.Shape.ranks (plan X start))
+local notation "W" => widthBase X start
+local notation "AB" => ShrinkWidthArena.abBase X q W
+local notation "M" => ShrinkTermRecipe.M X
+local notation "N" => ShrinkTermInputs.motifCount X
+
+set_option maxHeartbeats 900000 in
+theorem visit_readback (shape : DescriptorSpace.Shape) (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+ (reads : ShrinkBundlePlan.Reads X shape i.val origin pub state mem start T)
+ (room : termEnd X start 10 < 2^w) (j : Stage) :
+ let v := visit B i origin j
+ v.initial.eval pub state mem = 0 ∧ v.stop.eval pub state mem = (N : Word w) ∧
+ (fun u => (v.params u).eval pub state mem) = bank B i origin X T start j := by
+ let I := ShrinkBundlePlan.termInputs i.val (a i) origin
+ have stopEq : ShrinkInput.stop X start = W+6*M+2*(Z).B := rfl
+ change ShrinkInput.stop X start+2*M+M*10 < 2^w at room
+ have fit : (Z).stop < 2^w := by change W < _; omega
+ have hv := (Z).values T (placementBank X T start) Fintype.card_pos fit
+ have hd : AB + 2*M = ShrinkInput.stop X start := by
+ rw [stopEq]
+ change W+2*((Z).B*(q 4).val)+2*((Z).B*(q 4).val)+2*(Z).B+2*M = _
+ rw [hv.stride]
+ change W+2*M+2*M+2*(Z).B+2*M = _
+ omega
+ have ready := ShrinkBundlePlan.term_input X reads fit
+ have hc := (ShrinkTermRecipe.eval_count I X pub state mem ready).trans
+ (congrArg (fun n : ℕ => (n : Word w)) (ShrinkTermRecipe.count_card X))
+ cases j with
+ | gather =>
+ have data := ShrinkTermRecipe.gather_bank I X pub state mem ready (ShrinkWidthArena.prefixBase X q W)
+ (thickBank X T start 4)
+ change _ = ShrinkTermInputs.operands (cdBank X T start) (piecesBank X T start) ((AB+2*M : ℕ) : Word w) at data
+ rw [hd] at data
+ exact ⟨rfl,hc,data⟩
+ | select =>
+ have data := ShrinkTermRecipe.term_bank 10 I B.shrink SelectedScore.supplyOrder.entries X pub state mem ready
+ change _ = TermWorker.motifData B.shrink finTwoEquiv SelectedScore.supplyOrder.entries w
+ ![((AB+2*M : ℕ) : Word w),2,((AB+2*M+2*M : ℕ) : Word w),10] at data
+ rw [hd] at data
+ refine ⟨rfl,hc,data.trans ?_⟩
+ change TermWorker.motifData B.shrink _ _ w _ = TermWorker.motifData B.shrink _ _ w _
+ congr 1
+ funext t
+ fin_cases t <;> first | rfl | apply Fin.ext; exact (Nat.mod_mod _ _).symm
+
+end CompressorRecords.ShrinkTermPackets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkWidthFootprints.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkWidthFootprints.lean
new file mode 100644
index 0000000000..c0db183314
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorShrinkWidthFootprints.lean
@@ -0,0 +1,179 @@
+import OAI.Computability.VPVNP.CompressorShrinkBundleAbsolute
+import OAI.Computability.VPVNP.CompressorRefreshStageFrame
+import OAI.Computability.VPVNP.CompressorSlotFillFootprint
+
+/-!
+# Probes of dense shrinking width, prefix, AB and absolute-ID workers
+
+All bounds concern the chronological source events. For both scattered
+payloads the rank and owner cells keep their original values throughout
+the scan, so indirect writes stay in the two reserved rectangles.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkWidthFootprints
+
+open BurstRAM PrimedStackRAM SourceTransport
+open SlotFillFootprint (InColumn)
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- A scan covers cursor ordinals from zero to the bound and confines all its external reads
+and writes to their respective allowed regions. -/
+abbrev Checked (N : ℕ) (rd wr : ℕ → Prop) (rs : List (Report w)) :=
+ StageFrame.Scanned 0 N rs ∧ Reads rd (eventLog rs) ∧ Writes wr (eventLog rs)
+
+private theorem add_in (base off : Word w) {n : ℕ} (fit : base.val+n ≤ 2^w) (within : off.val < n) :
+ InColumn base.val n (base+off).val := by
+ rw [Fin.val_add,Nat.mod_eq_of_lt (by omega)]
+ exact ⟨Nat.le_add_right ..,Nat.add_lt_add_left within _⟩
+
+/-- The same quotient and remainder index the sorted prefixes and AB pieces. -/
+private theorem coordinates (p : Fin 5 → Word w) {B : ℕ} (positive : 0 < (p 0).val)
+ (stride : (p 0).val ≤ (p 1).val) {i : Word w} (hi : i.val < B*(p 0).val) :
+ (BundlePrefixRAM.row p i).val < B ∧ (BundlePrefixRAM.index p i).val < B*(p 1).val := by
+ have hr : (BundlePrefixRAM.row p i).val = i.val/(p 0).val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt i.isLt)
+ have hp : (BundlePrefixRAM.pos p i).val = i.val%(p 0).val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt i.isLt)
+ have row := (Nat.div_lt_iff_lt_mul positive).mpr hi
+ have col := (Nat.mod_lt i.val positive).trans_le stride
+ have cap := Nat.mul_le_mul_right (p 1).val row
+ rw [Nat.succ_mul] at cap
+ refine ⟨hr ▸ row,?_⟩
+ rw [BundlePrefixRAM.index,Fin.val_add,Fin.val_mul,hr,hp,Nat.mod_add_mod]
+ exact (Nat.mod_le ..).trans_lt (by omega)
+
+/-- Addresses the prefix worker may read in the per-bundle width rectangle and the column of
+running bundle totals. -/
+def prefixReads (p : Fin 5 → Word w) (B x : ℕ) :=
+ InColumn (p 2).val (B*(p 1).val) x ∨ InColumn (p 4).val B x
+
+/-- Addresses the prefix worker may write in the per-bundle start-offset rectangle and the
+totals column. -/
+def prefixWrites (p : Fin 5 → Word w) (B x : ℕ) :=
+ InColumn (p 3).val (B*(p 1).val) x ∨ InColumn (p 4).val B x
+
+theorem prefix_scan (p : Fin 5 → Word w) (B : ℕ) (layout : BundlePrefixRAM.Layout p B)
+ (m : Memory w) (rs : List (Report w))
+ (run : runSegment ((template BundlePrefixRAM.visit 0).instantiate w p).program 25
+ (some 0) m (List.replicate (B*(p 0).val) []) = some rs) :
+ Checked (B*(p 0).val) (prefixReads p B) (prefixWrites p B) rs := by
+ have step (j : ℕ) (hj : j < B*(p 0).val) (mem : Memory w) :
+ Reads (prefixReads p B) (BundlePrefixRAM.events p mem (j : Word w)) ∧
+ Writes (prefixWrites p B) (BundlePrefixRAM.events p mem (j : Word w)) := by
+ obtain ⟨hr,hi⟩ := coordinates p (B := B) (i := (j : Word w)) layout.positive layout.size_le_stride ((Nat.mod_le j (2^w)).trans_lt hj)
+ have width := add_in _ _ layout.widthsFit hi
+ have offset := add_in _ _ layout.startsFit hi
+ have total := add_in _ _ layout.totalsFit hr
+ constructor <;> intro addr val he <;> simp [BundlePrefixRAM.events] at he
+ · rcases he with ⟨rfl,_⟩ | ⟨rfl,_⟩; exact .inl width; exact .inr total
+ · rcases he with ⟨rfl,_⟩ | ⟨rfl,_⟩; exact .inl offset; exact .inr total
+ obtain ⟨shape,_,rd,wr⟩ := StageFrame.scan _ 25 0 (B*(p 0).val) (fun _ _ ↦ True)
+ (BundlePrefixRAM.events p) (prefixReads p B) (prefixWrites p B)
+ (fun j _ _ mem ↦ BundlePrefixRAM.native p mem j) (fun j _ hj mem _ ↦ ⟨trivial,step j hj mem⟩)
+ (Nat.zero_le _) m rs trivial run
+ exact ⟨shape,rd,wr⟩
+
+/-- The bundle-total column from which the AB worker reads its balancing inputs. -/
+def abReads (p : Fin 5 → Word w) (B x : ℕ) := InColumn (p 2).val B x
+
+/-- Allowed write addresses for the AB worker. The two rectangles reserve a full row stride per
+bundle for piece widths and starting offsets. -/
+def abWrites (p : Fin 5 → Word w) (B x : ℕ) :=
+ ∃ t : Fin 2, InColumn (p (t.natAdd 3)).val (B*(p 1).val) x
+
+theorem ab_scan (p : Fin 5 → Word w) (B : ℕ) (layout : ABWidths.Layout p B)
+ (m : Memory w) (rs : List (Report w))
+ (run : runSegment ((template ABWidths.visit 0).instantiate w p).program 30 (some 0) m
+ (List.replicate (B*(p 0).val) []) = some rs) : Checked (B*(p 0).val) (abReads p B) (abWrites p B) rs := by
+ have step (j : ℕ) (hj : j < B*(p 0).val) (mem : Memory w) :
+ Reads (abReads p B) (ABWidths.events p mem (j : Word w)) ∧
+ Writes (abWrites p B) (ABWidths.events p mem (j : Word w)) := by
+ obtain ⟨hr,hi⟩ := coordinates p (B := B) (i := (j : Word w)) layout.positive layout.stride ((Nat.mod_le j (2^w)).trans_lt hj)
+ have total := add_in _ _ layout.totalFit hr
+ have out (t : Fin 2) := add_in _ _ (layout.outFit t) hi
+ constructor <;> intro addr val he <;> simp [ABWidths.events] at he
+ · obtain ⟨rfl,_⟩ := he; exact total
+ · rcases he with ⟨rfl,_⟩ | ⟨rfl,_⟩; exact ⟨0,out 0⟩; exact ⟨1,out 1⟩
+ obtain ⟨shape,_,rd,wr⟩ := StageFrame.scan _ 30 0 (B*(p 0).val) (fun _ _ ↦ True)
+ (ABWidths.events p) (abReads p B) (abWrites p B) (fun j _ _ mem ↦ ABWidths.native p mem j)
+ (fun j _ hj mem _ ↦ ⟨trivial,step j hj mem⟩) (Nat.zero_le _) m rs trivial run
+ exact ⟨shape,rd,wr⟩
+
+open BundleWidthScatter
+
+/-- Addresses in the owner, rank and old-width columns consulted by the width scatter. -/
+def scatterReads (p : Fin 5 → Word w) (A x : ℕ) := ∃ t : Fin 3, InColumn (p (t.castAdd 2)).val A x
+
+/-- The two consecutive sorted-width rectangles, one for thick entries and one for CD entries,
+that receive the scatter writes. -/
+def scatterWrites (p : Fin 5 → Word w) (B x : ℕ) := InColumn (p 4).val ((B+B)*(p 3).val) x
+
+private theorem scatter_scan {C : Type*} (P : BurstRAM.Program w C) (fuel : ℕ) (p : Fin 5 → Word w)
+ (A B : ℕ) (m : Memory w) (rs : List (Report w)) (log : Memory w → Word w → List (Event w))
+ (native : ∀ mem i, execute P fuel (P.start i) mem [] = some ⟨log mem i,some (i+1)⟩)
+ (probes : ∀ mem i, Reads (fun x ↦ ∃ t : Fin 3, x = (source p t i).val) (log mem i) ∧
+ Writes (fun x ↦ x = (outAddress p mem i).val) (log mem i))
+ (fit : ∀ t : Fin 3, (p (t.castAdd 2)).val+A ≤ 2^w)
+ (write : ∀ j < A, scatterWrites p B (outAddress p m (j : Word w)).val)
+ (reg : Regions p m A)
+ (run : runSegment P fuel (some 0) m (List.replicate A []) = some rs) :
+ Checked A (scatterReads p A) (scatterWrites p B) rs := by
+ let I (_ : ℕ) (mem : Memory w) := ∀ t : Fin 3, ∀ j < A,
+ mem (source p t (j : Word w)).val = m (source p t (j : Word w)).val
+ have step (j : ℕ) (hj : j intro addr val he <;> simp [BundleWidthScatter.events] at he
+ · rcases he with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> first | exact ⟨0,rfl⟩ | exact ⟨1,rfl⟩ | exact ⟨2,rfl⟩
+ · exact congrArg Fin.val he.1
+
+theorem absolute_scan (p : Fin 7 → Word w) (A B : ℕ) (m : Memory w) (rs : List (Report w))
+ (fit : ∀ t : Fin 3, ((MotifAbsolute.columns p) (t.castAdd 2)).val+A ≤ 2^w)
+ (write : ∀ j < A, scatterWrites (MotifAbsolute.columns p) B (outAddress (MotifAbsolute.columns p) m (j : Word w)).val)
+ (reg : Regions (MotifAbsolute.columns p) m A)
+ (run : runSegment ((template MotifAbsolute.visit 0).instantiate w p).program 25 (some 0) m
+ (List.replicate A []) = some rs) :
+ Checked A (scatterReads (MotifAbsolute.columns p) A) (scatterWrites (MotifAbsolute.columns p) B) rs := by
+ apply scatter_scan _ 25 _ A B m rs (MotifAbsolute.events p) (MotifAbsolute.native p) _ fit write reg run
+ intro mem i
+ constructor <;> intro addr val he <;> simp [MotifAbsolute.events] at he
+ · rcases he with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> first | exact ⟨0,rfl⟩ | exact ⟨1,rfl⟩ | exact ⟨2,rfl⟩
+ · exact congrArg Fin.val he.1
+
+end CompressorRecords.ShrinkWidthFootprints
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSliceAdjacency.lean b/lean/OAI/Computability/VPVNP/CompressorSliceAdjacency.lean
new file mode 100644
index 0000000000..11b6ac54ce
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSliceAdjacency.lean
@@ -0,0 +1,256 @@
+import OAI.Computability.VPVNP.CompressorSliceAdjacencyNative
+import OAI.Computability.VPVNP.CompressorSliceAdjacencyRows
+import OAI.Computability.VPVNP.RAMChain
+import OAI.Computability.VPVNP.RAMBuckets
+
+/-!
+# Native construction of both endpoint directories for copy slices
+
+Scan the rectangular output frames of Appendix E in row-major order. A nonempty
+frame appends its identifier to the row for its source and the row for its
+target. The stored counts delimit the meaningful portions of both directories.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SliceRAM
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {w : ℕ}
+
+/-- Source-field adjacency directory, with one row per old field and one slot per new field. -/
+def oldBank (pub : Fin 7 → Word w) : AdjBank w := ⟨pub 3, pub 4, pub 1, pub 0⟩
+/-- Target-field adjacency directory, with one row per new field and one slot per old field. -/
+def newBank (pub : Fin 7 → Word w) : AdjBank w := ⟨pub 5, pub 6, pub 0, pub 1⟩
+
+/-- Counters precede the raw frames, which precede both reference arrays.
+The inequalities allow gaps between arrays. -/
+structure AdjRegions (pub : Fin 7 → Word w) : Prop where
+ oldBeforeNewCounts : (pub 3).val + (pub 1).val ≤ (pub 5).val
+ countsBeforeFrames : (pub 5).val + (pub 0).val ≤ (pub 2).val
+ framesBeforeRefs : (pub 2).val + 3 * ((pub 1).val * (pub 0).val) ≤ (pub 4).val
+ oldBeforeNewRefs : (oldBank pub).stop ≤ (pub 6).val
+ refsFit : (newBank pub).stop ≤ 2^w
+
+private theorem oldFits {pub : Fin 7 → Word w} (a : AdjRegions pub) : (oldBank pub).Fits := by
+ have := a.oldBeforeNewCounts
+ have := a.countsBeforeFrames
+ have := a.framesBeforeRefs
+ exact ⟨by change (pub 3).val + (pub 1).val ≤ (pub 4).val; omega,
+ a.oldBeforeNewRefs.trans (pub 6).isLt.le⟩
+
+private theorem newFits {pub : Fin 7 → Word w} (a : AdjRegions pub) : (newBank pub).Fits := by
+ have := a.countsBeforeFrames
+ have := a.framesBeforeRefs
+ have ht := a.oldBeforeNewRefs
+ change (pub 4).val + (pub 1).val * (pub 0).val ≤ (pub 6).val at ht
+ exact ⟨by change (pub 5).val + (pub 0).val ≤ (pub 6).val; omega, a.refsFit⟩
+
+private theorem banks_disjoint {pub : Fin 7 → Word w} (a : AdjRegions pub) (x : ℕ)
+ (ho : (oldBank pub).Inside x) (hn : (newBank pub).Inside x) : False := by
+ have := a.oldBeforeNewCounts
+ have := a.countsBeforeFrames
+ have := a.framesBeforeRefs
+ have h := a.oldBeforeNewRefs
+ simp only [oldBank, newBank, AdjBank.Inside, AdjBank.stop] at ho hn h
+ omega
+
+/-- Both directories represent the same prefix of the scan. -/
+structure AdjAt (pub : Fin 7 → Word w) (length : ℕ → ℕ) (initial mem : Memory w) (k : ℕ) : Prop where
+ oldRows : (oldBank pub).Represents mem length (· / (pub 0).val) k
+ newRows : (newBank pub).Represents mem length (· % (pub 0).val) k
+ outside : ∀ x, ¬ (oldBank pub).Inside x → ¬ (newBank pub).Inside x → mem x = initial x
+
+/-- Every frame word retains its offsets or length throughout the adjacency pass. -/
+theorem AdjAt.frame_eq {pub : Fin 7 → Word w} (bounds : AdjRegions pub)
+ {length : ℕ → ℕ} {initial mem : Memory w} {k : ℕ} (h : AdjAt pub length initial mem k)
+ {x : ℕ} (lo : (pub 2).val ≤ x) (hi : x < (pub 2).val + 3*((pub 1).val*(pub 0).val)) :
+ mem x = initial x := by
+ have := bounds.framesBeforeRefs
+ have := bounds.countsBeforeFrames
+ have := bounds.oldBeforeNewCounts
+ have ho := bounds.oldBeforeNewRefs
+ change (pub 4).val + (pub 1).val * (pub 0).val ≤ (pub 6).val at ho
+ exact h.outside x (by simp only [oldBank, AdjBank.Inside]; omega)
+ (by simp only [newBank, AdjBank.Inside]; omega)
+
+theorem adjFrameLength_val {pub : Fin 7 → Word w} (bounds : AdjRegions pub)
+ {id : Word w} (hk : id.val < (pub 1).val * (pub 0).val) :
+ (adjFrameLength pub id).val = (pub 2).val + 3 * id.val + 2 := by
+ have hfit := bounds.framesBeforeRefs
+ have hlt := (pub 4).isLt
+ have h3 : (3 : Word w).val = 3 := by
+ change 3 % (2^w) = 3
+ exact Nat.mod_eq_of_lt (by omega)
+ have h2 : (2 : Word w).val = 2 := by
+ change 2 % (2^w) = 2
+ exact Nat.mod_eq_of_lt (by omega)
+ rw [adjFrameLength, Fin.val_add, Fin.val_add, Fin.val_mul, h3, h2,
+ Nat.mod_eq_of_lt (show 3 * id.val < 2^w by omega),
+ Nat.mod_eq_of_lt (show (pub 2).val + 3*id.val < 2^w by omega),
+ Nat.mod_eq_of_lt (by omega)]
+
+private theorem current_length {pub : Fin 7 → Word w} (bounds : AdjRegions pub)
+ {length : ℕ → ℕ} {initial mem : Memory w}
+ (frames : ∀ t, t < (pub 1).val * (pub 0).val → (initial ((pub 2).val + 3*t+2)).val = length t)
+ {id : Word w} (hk : id.val < (pub 1).val * (pub 0).val) (h : AdjAt pub length initial mem id.val) :
+ (mem (adjFrameLength pub id).val).val = length id.val := by
+ rw [adjFrameLength_val bounds hk, h.frame_eq bounds (by omega) (by omega)]
+ exact frames _ hk
+
+private theorem adjAt_step {pub : Fin 7 → Word w} (bounds : AdjRegions pub)
+ {length : ℕ → ℕ} {initial mem : Memory w}
+ (frames : ∀ t, t < (pub 1).val * (pub 0).val → (initial ((pub 2).val + 3*t+2)).val = length t)
+ {id : Word w} (hk : id.val < (pub 1).val * (pub 0).val) (h : AdjAt pub length initial mem id.val) :
+ AdjAt pub length initial (adjUpdate pub mem id) (id.val+1) := by
+ have hlen := current_length bounds frames hk h
+ have hzero : mem (adjFrameLength pub id).val = 0 ↔ length id.val = 0 := by
+ rw [← hlen]
+ exact ⟨fun he => by simp [he], fun h => Fin.ext (by simpa using h)⟩
+ by_cases hz : length id.val = 0
+ · rw [adjUpdate, ite_eq_left (hzero.mpr hz)]
+ exact ⟨fun v hv => by simpa [adjPrefix_succ, hz] using h.oldRows v hv,
+ fun v hv => by simpa [adjPrefix_succ, hz] using h.newRows v hv, h.outside⟩
+ rw [adjUpdate, ite_eq_right (mt hzero.mp hz)]
+ let i := id / pub 0
+ let j := id % pub 0
+ let O := oldBank pub
+ let N := newBank pub
+ have hn : 0 < (pub 0).val := by
+ by_contra! he
+ rw [show (pub 0).val = 0 by omega, Nat.mul_zero] at hk
+ omega
+ have hi : i < O.size := (Nat.div_lt_iff_lt_mul hn).mpr hk
+ have hj : j < N.size := Nat.mod_lt _ hn
+ have hid : id = Fin.ofNat (2^w) id.val := Fin.ext (Nat.mod_eq_of_lt id.isLt).symm
+ have ocap (k : ℕ) (hbound : k ≤ (pub 1).val * (pub 0).val) (v : Word w) :
+ (adjPrefix w length (· / (pub 0).val) v.val k).length ≤ O.cap.val :=
+ adjPrefix_old_le length hbound
+ have ncap (k : ℕ) (hbound : k ≤ (pub 1).val * (pub 0).val) (v : Word w) :
+ (adjPrefix w length (· % (pub 0).val) v.val k).length ≤ N.cap.val :=
+ adjPrefix_new_le length hbound
+ let middle := adjAppend mem (O.count i) (O.row i) id
+ obtain ⟨ho, hmo⟩ := AdjBank.append_step (oldFits bounds) h.oldRows hi rfl hid hz
+ (fun v _ => ocap _ hk v)
+ change O.Represents middle length (· / (pub 0).val) (id.val+1) at ho
+ change ∀ x, ¬ O.Inside x → middle x = mem x at hmo
+ have hnRows : N.Represents middle length (· % (pub 0).val) id.val :=
+ AdjBank.represents_congr (newFits bounds) h.newRows (fun v _ => ncap _ hk.le v)
+ (fun x hx => hmo x (fun ho => banks_disjoint bounds x ho hx))
+ obtain ⟨hn', hmn⟩ := AdjBank.append_step (newFits bounds) hnRows hj rfl hid hz
+ (fun v _ => ncap _ hk v)
+ exact ⟨AdjBank.represents_congr (oldFits bounds) ho (fun v _ => ocap _ hk v)
+ (fun x hx => hmn x (banks_disjoint bounds x hx)), hn',
+ fun x xo xn => (hmn x xn).trans ((hmo x xo).trans (h.outside x xo xn))⟩
+
+/-- Number of nonempty frames in a contiguous part of the scan. -/
+def adjNonempty (length : ℕ → ℕ) (k steps : ℕ) : ℕ :=
+ ((List.range' k steps).filter fun t => length t ≠ 0).length
+
+private theorem adjNonempty_succ (length : ℕ → ℕ) (k steps : ℕ) :
+ adjNonempty length k (steps+1) = (if length k = 0 then 0 else 1) +
+ adjNonempty length (k+1) steps := by
+ by_cases hz : length k = 0 <;> simp [adjNonempty, List.range'_succ, hz, Nat.add_comm]
+
+/-- A segment of the native program visits all consecutive identifiers starting at `k`.
+The total cost counts calls and probes, and the instruction total counts each return. -/
+theorem adjSegment_run {pub : Fin 7 → Word w} (bounds : AdjRegions pub)
+ {length : ℕ → ℕ} {initial mem : Memory w}
+ (frames : ∀ t, t < (pub 1).val * (pub 0).val → (initial ((pub 2).val + 3*t+2)).val = length t)
+ {k : ℕ} (h : AdjAt pub length initial mem k) (steps : ℕ)
+ (hb : k + steps ≤ (pub 1).val * (pub 0).val) :
+ let M := adjTemplate.instantiate w pub
+ let idx := Fin.ofNat (2^w)
+ ∃ rs, runSegment M.program 36 (some (idx k)) mem (List.replicate steps []) = some rs ∧
+ AdjAt pub length initial (after mem (eventLog rs)) (k + steps) ∧
+ endState (some (idx k)) rs = some (idx (k+steps)) ∧ rs.length = steps ∧
+ RAMBuckets.cost Report.probes rs = 2*steps + 6*adjNonempty length k steps ∧
+ (rs.map fun r => r.events.length + 1).sum = 12*steps + 24*adjNonempty length k steps := by
+ let M := adjTemplate.instantiate w pub
+ let idx := Fin.ofNat (2^w)
+ have hfit := bounds.framesBeforeRefs
+ have hspace := (pub 4).isLt
+ induction steps generalizing k mem with
+ | zero => exact ⟨[], rfl, h, rfl, rfl, by simp [RAMBuckets.cost, adjNonempty],
+ by simp [adjNonempty]⟩
+ | succ s ih =>
+ have hi : (idx k).val = k := Nat.mod_eq_of_lt (by omega)
+ have hnext : idx k + 1 = idx (k+1) := by
+ apply Fin.ext
+ rw [Fin.val_add, hi, Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^w by omega)]
+ rfl
+ let r : Report w := ⟨adjEvents pub mem (idx k), some (idx k + 1)⟩
+ have hlen := current_length bounds frames (id := idx k) (by omega) (hi ▸ h)
+ rw [hi] at hlen
+ have hzero : mem (adjFrameLength pub (idx k)).val = 0 ↔ length k = 0 := by
+ rw [← hlen]
+ exact ⟨fun he => by simp [he], fun h => Fin.ext (by simpa using h)⟩
+ have hp := adjAt_step bounds frames (id := idx k) (by omega) (hi ▸ h)
+ rw [hi] at hp
+ obtain ⟨rs, hr, hp', he, hl, hc, hw⟩ := ih hp (by omega)
+ have ha : k + (s+1) = k+1+s := by omega
+ refine ⟨r :: rs, ?_, ?_, ?_, by simp [hl], ?_, ?_⟩
+ · change runSegment M.program 36 (some (idx k)) mem (List.replicate (s+1) []) = _
+ rw [List.replicate_succ, runSegment, adjVisit_native]
+ simp only [hnext, adjEvents_after]
+ rw [hr]
+ simp only [Option.map_some, r, hnext]
+ · have hm : after mem (eventLog (r :: rs)) =
+ after (adjUpdate pub mem (idx k)) (eventLog rs) := by
+ change List.foldl update mem (r.events ++ eventLog rs) = _
+ rw [List.foldl_append]
+ change after (after mem (adjEvents pub mem (idx k))) (eventLog rs) = _
+ rw [adjEvents_after]
+ rw [hm, ha]
+ exact hp'
+ · change endState (some (idx k + 1)) rs = _
+ rw [hnext, he, ha]
+ · have hp := (adjEvents_work pub mem (idx k)).1
+ change r.probes = _ at hp
+ rw [RAMBuckets.cost, hp, hc, adjNonempty_succ]
+ by_cases hz : length k = 0 <;> simp [hzero, hz] <;> omega
+ · have hp := (adjEvents_work pub mem (idx k)).2
+ change r.events.length + 1 = _ at hp
+ rw [List.map_cons, List.sum_cons, hp, hw, adjNonempty_succ]
+ by_cases hz : length k = 0 <;> simp [hzero, hz] <;> omega
+
+/-- Splitting the reported segment cost into its call and probe totals. -/
+theorem adjCost_eq_length_add_probes (rs : List (Report w)) :
+ RAMBuckets.cost Report.probes rs = rs.length + (rs.map Report.probes).sum := by
+ induction rs with
+ | nil => rfl
+ | cons r rs ih => simp [RAMBuckets.cost, ih]; omega
+
+/-- Starting with zero counts, the scan constructs every row at both endpoints.
+Empty frames and zero-dimensional tables produce no incidences. -/
+theorem adjPass_run {pub : Fin 7 → Word w} (bounds : AdjRegions pub)
+ {length : ℕ → ℕ} {mem : Memory w}
+ (frames : ∀ t, t < (pub 1).val * (pub 0).val → (mem ((pub 2).val + 3*t+2)).val = length t)
+ (oldZero : ∀ i : Word w, i < pub 1 → mem (adjOldCount pub i).val = 0)
+ (newZero : ∀ j : Word w, j < pub 0 → mem (adjNewCount pub j).val = 0) :
+ let pairs := (pub 1).val * (pub 0).val
+ let M := adjTemplate.instantiate w pub
+ ∃ rs, runSegment M.program 36 (some 0) mem (List.replicate pairs []) = some rs ∧
+ AdjAt pub length mem (after mem (eventLog rs)) pairs ∧
+ endState (some 0) rs = some (Fin.ofNat (2^w) pairs) ∧ rs.length = pairs ∧
+ RAMBuckets.cost Report.probes rs = 2*pairs + 6*adjNonempty length 0 pairs ∧
+ (rs.map fun r => r.events.length + 1).sum = 12*pairs + 24*adjNonempty length 0 pairs := by
+ have h : AdjAt pub length mem mem 0 := by
+ constructor
+ · intro i hi
+ change (mem (adjOldCount pub i).val).val = _ ∧ _
+ simp [adjPrefix, oldZero i hi]
+ · intro j hj
+ change (mem (adjNewCount pub j).val).val = _ ∧ _
+ simp [adjPrefix, newZero j hj]
+ · exact fun _ _ _ => rfl
+ simpa using adjSegment_run bounds frames h ((pub 1).val * (pub 0).val) (by simp)
+
+end CompressorRecords.SliceRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSliceAdjacencyNative.lean b/lean/OAI/Computability/VPVNP/CompressorSliceAdjacencyNative.lean
new file mode 100644
index 0000000000..a278b357ac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSliceAdjacencyNative.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.CompressorSliceRAM
+
+/-!
+# Indexing the copy records incident to each field
+
+In the Appendix E interval scan, each candidate has a three-word output frame.
+A second scan reads the length from this frame. For a positive length it appends
+the candidate number to the adjacency lists of both fields. Rows are allocated
+with one possible reference per opposite field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SliceRAM
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {w : ℕ}
+
+/-- The seven public words are the new field count, the old field count, the output
+frame base, and the count and reference bases for the old and new fields in order. -/
+def adjFrameLength (pub : Fin 7 → Word w) (k : Word w) : Word w := pub 2 + 3 * k + 2
+
+/-- Address of the number of retained slice frames for source field `i`. -/
+def adjOldCount (pub : Fin 7 → Word w) (i : Word w) : Word w := pub 3 + i
+
+/-- First reference cell in the adjacency row for source field `i`. -/
+def adjOldRow (pub : Fin 7 → Word w) (i : Word w) : Word w := pub 4 + i * pub 0
+
+/-- Address of the number of retained slice frames for target field `j`. -/
+def adjNewCount (pub : Fin 7 → Word w) (j : Word w) : Word w := pub 5 + j
+
+/-- First reference cell in the adjacency row for target field `j`. -/
+def adjNewRow (pub : Fin 7 → Word w) (j : Word w) : Word w := pub 6 + j * pub 1
+
+/-- Write one candidate number at the current end of a row and increment its count. -/
+def adjAppend (mem : Memory w) (count row value : Word w) : Memory w :=
+ writeMemory (writeMemory mem (row + mem count.val) value) count (mem count.val + 1)
+
+/-- Append the frame ordinal to both endpoint rows exactly when its recorded length is
+positive. -/
+def adjUpdate (pub : Fin 7 → Word w) (mem : Memory w) (k : Word w) : Memory w :=
+ if mem (adjFrameLength pub k).val = 0 then mem else
+ adjAppend (adjAppend mem (adjOldCount pub (k / pub 0)) (adjOldRow pub (k / pub 0)) k)
+ (adjNewCount pub (k % pub 0)) (adjNewRow pub (k % pub 0)) k
+
+/-- One fresh call reads the frame length, handles both nonempty adjacency writes
+and returns the next candidate number. Register eight is zero at call entry. -/
+def adjTemplate : Template 36 9 7 where
+ literalWidth := 2
+ entry := 0
+ code pc := match pc.val with
+ | 0 => .stateWord 0 1
+ | 1 => .constant 1 1 2
+ | 2 => .constant 2 3 3
+ | 3 => .binary .mul 2 2 0 4
+ | 4 => .publicWord 3 2 5
+ | 5 => .binary .add 3 3 2 6
+ | 6 => .constant 2 2 7
+ | 7 => .binary .add 3 3 2 8
+ | 8 => .readExternal 4 3 9
+ | 9 => .jumpEq 4 8 34 10
+ | 10 => .publicWord 2 0 11
+ | 11 => .binary .div 3 0 2 12
+ | 12 => .binary .mod 4 0 2 13
+ | 13 => .publicWord 5 3 14
+ | 14 => .binary .add 5 5 3 15
+ | 15 => .readExternal 6 5 16
+ | 16 => .binary .mul 3 3 2 17
+ | 17 => .publicWord 7 4 18
+ | 18 => .binary .add 7 7 3 19
+ | 19 => .binary .add 7 7 6 20
+ | 20 => .writeExternal 7 0 21
+ | 21 => .binary .add 6 6 1 22
+ | 22 => .writeExternal 5 6 23
+ | 23 => .publicWord 2 1 24
+ | 24 => .publicWord 5 5 25
+ | 25 => .binary .add 5 5 4 26
+ | 26 => .readExternal 6 5 27
+ | 27 => .binary .mul 4 4 2 28
+ | 28 => .publicWord 7 6 29
+ | 29 => .binary .add 7 7 4 30
+ | 30 => .binary .add 7 7 6 31
+ | 31 => .writeExternal 7 0 32
+ | 32 => .binary .add 6 6 1 33
+ | 33 => .writeExternal 5 6 34
+ | 34 => .binary .add 0 0 1 35
+ | _ => .returnState 0
+
+private def appendEvents (mem : Memory w) (count row k : Word w) : List (Event w) :=
+ let size := mem count.val
+ [.read count size, .tick, .tick, .tick, .tick, .write (row + size) k, .tick,
+ .write count (size + 1)]
+
+/-- The target row's size is read from memory after the source row's two writes. -/
+def adjEvents (pub : Fin 7 → Word w) (mem : Memory w) (k : Word w) : List (Event w) :=
+ let a := adjFrameLength pub k
+ let length := mem a.val
+ let i := k / pub 0
+ let j := k % pub 0
+ let updated := adjAppend mem (adjOldCount pub i) (adjOldRow pub i) k
+ List.replicate 8 .tick ++ [.read a length, .tick] ++
+ (if length = 0 then [] else
+ List.replicate 5 .tick ++ appendEvents mem (adjOldCount pub i) (adjOldRow pub i) k ++
+ List.replicate 3 .tick ++ appendEvents updated (adjNewCount pub j) (adjNewRow pub j) k) ++
+ [.tick]
+
+theorem adjEvents_after (pub : Fin 7 → Word w) (mem : Memory w) (k : Word w) :
+ after mem (adjEvents pub mem k) = adjUpdate pub mem k := by
+ by_cases h : mem (adjFrameLength pub k).val = 0 <;>
+ simp only [adjEvents, adjUpdate, h, ↓reduceIte] <;> rfl
+
+theorem adjEvents_work (pub : Fin 7 → Word w) (mem : Memory w) (k : Word w) :
+ countProbes (adjEvents pub mem k) = (if mem (adjFrameLength pub k).val = 0 then 1 else 7) ∧
+ (adjEvents pub mem k).length + 1 = (if mem (adjFrameLength pub k).val = 0 then 12 else 36) := by
+ by_cases h : mem (adjFrameLength pub k).val = 0 <;>
+ simp only [adjEvents, h, ↓reduceIte] <;> exact ⟨rfl,rfl⟩
+
+open Fin.NatCast
+
+private theorem divWord (x y : Word w) : ((x.val / y.val : ℕ) : Word w) = x / y :=
+ Fin.ext (Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.div_le_self ..) x.isLt))
+
+private theorem modWord (x y : Word w) : ((x.val % y.val : ℕ) : Word w) = x % y :=
+ Fin.ext (Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.mod_le ..) x.isLt))
+
+set_option maxRecDepth 4096 in
+set_option maxHeartbeats 1200000 in
+theorem adjVisit_native (pub : Fin 7 → Word w) (mem : Memory w) (k : Word w) :
+ let M := adjTemplate.instantiate w pub
+ execute M.program 36 (M.program.start k) mem [] = some ⟨adjEvents pub mem k, some (k + 1)⟩ := by
+ dsimp only
+ by_cases h : mem (adjFrameLength pub k).val = 0 <;>
+ simp only [adjEvents, h, ↓reduceIte] <;>
+ simp only [adjFrameLength] at h <;>
+ simp (config := {decide := true}) [h, adjTemplate, Template.instantiate, Machine.program,
+ execute, Instr.resize, Instr.run, Config.put, BinaryOp.eval, Function.update,
+ adjFrameLength, adjOldCount, adjOldRow, adjNewCount, adjNewRow, adjAppend,
+ appendEvents, Report.prepend, divWord, modWord]
+
+end CompressorRecords.SliceRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSliceAdjacencyRows.lean b/lean/OAI/Computability/VPVNP/CompressorSliceAdjacencyRows.lean
new file mode 100644
index 0000000000..f24b596bcd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSliceAdjacencyRows.lean
@@ -0,0 +1,212 @@
+import OAI.Computability.VPVNP.CompressorRecordTable
+import Mathlib.Data.Finset.Card
+
+/-!
+# Endpoint rows of the copy-slice scan
+
+A bounded row records all nonempty frame identifiers at an endpoint in scan order.
+For a rectangular table the opposite coordinate injects the retained frames of
+one row into its slot range.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SliceRAM
+
+open BurstRAM
+
+variable {w : ℕ}
+
+/-- Nonempty frames incident to endpoint `v` among the first `k` frames. -/
+def adjPrefix (w : ℕ) (length owner : ℕ → ℕ) (v k : ℕ) : List (Word w) :=
+ ((List.range k).filter fun t => length t ≠ 0 ∧ owner t = v).map (Fin.ofNat (2^w))
+
+theorem adjPrefix_succ (length owner : ℕ → ℕ) (v k : ℕ) :
+ adjPrefix w length owner v (k+1) = adjPrefix w length owner v k ++
+ (if length k ≠ 0 ∧ owner k = v then [Fin.ofNat (2^w) k] else []) := by
+ by_cases h : length k ≠ 0 ∧ owner k = v <;> simp [adjPrefix, List.range_succ, h]
+
+private theorem adjPrefix_le {length owner : ℕ → ℕ} {v k cap : ℕ} (slot : ℕ → ℕ)
+ (hfit : ∀ t, t < k → owner t = v → slot t < cap)
+ (hinj : ∀ a b, owner a = v → owner b = v → slot a = slot b → a = b) :
+ (adjPrefix w length owner v k).length ≤ cap := by
+ let xs := (List.range k).filter fun t => decide (length t ≠ 0 ∧ owner t = v)
+ have hs {t : ℕ} (h : t ∈ xs.toFinset) : t < k ∧ owner t = v := by
+ have ht : t < k ∧ length t ≠ 0 ∧ owner t = v := by simpa [xs] using h
+ exact ⟨ht.1, ht.2.2⟩
+ simp only [adjPrefix, List.length_map]
+ change xs.length ≤ cap
+ rw [← List.toFinset_card_of_nodup (l := xs) (List.nodup_range.filter _), ← Finset.card_range cap]
+ exact Finset.card_le_card_of_injOn slot
+ (fun t ht => Finset.mem_range.mpr (hfit t (hs ht).1 (hs ht).2))
+ (fun a ha b hb h => hinj a b (hs ha).2 (hs hb).2 h)
+
+/-- At an old endpoint, remainders are distinct slots below the number of new endpoints. -/
+theorem adjPrefix_old_le (length : ℕ → ℕ) {m n v k : ℕ} (hk : k ≤ m*n) :
+ (adjPrefix w length (· / n) v k).length ≤ n := by
+ apply adjPrefix_le (fun t => t % n)
+ · intro t ht _
+ exact Nat.mod_lt _ (by by_contra! h; simp [show n = 0 by omega] at hk; omega)
+ · intro a b ha hb he
+ simpa only [Nat.mod_add_div] using
+ (show a % n + n * (a / n) = b % n + n * (b / n) by rw [ha, hb, he])
+
+/-- At a new endpoint, quotients are distinct slots below the number of old endpoints. -/
+theorem adjPrefix_new_le (length : ℕ → ℕ) {m n v k : ℕ} (hk : k ≤ m*n) :
+ (adjPrefix w length (· % n) v k).length ≤ m := by
+ apply adjPrefix_le (fun t => t / n)
+ · intro t ht _
+ exact (Nat.div_lt_iff_lt_mul (by by_contra! h; simp [show n = 0 by omega] at hk; omega)).mpr
+ (lt_of_lt_of_le ht hk)
+ · intro a b ha hb he
+ calc a = a % n + n * (a / n) := (Nat.mod_add_div ..).symm
+ _ = b % n + n * (b / n) := by rw [ha, hb, he]
+ _ = b := Nat.mod_add_div ..
+
+/-- The counter array followed by the fixed-capacity rows of one endpoint class. -/
+structure AdjBank (w : ℕ) where
+ /-- Base address of the per-endpoint reference counts. -/
+ countHead : Word w
+ /-- Base address of the rectangular array of frame-reference rows. -/
+ refHead : Word w
+ /-- Number of endpoints represented by this adjacency directory. -/
+ size : Word w
+ /-- Number of reference slots reserved for each endpoint. -/
+ cap : Word w
+
+namespace AdjBank
+
+/-- Address of endpoint `v`'s live reference count. -/
+def count (B : AdjBank w) (v : Word w) := B.countHead + v
+/-- Address of the first reference slot for endpoint `v`. -/
+def row (B : AdjBank w) (v : Word w) := B.refHead + v * B.cap
+/-- Exclusive natural-number end address of the reference array. -/
+def stop (B : AdjBank w) := B.refHead.val + B.size.val * B.cap.val
+
+/-- The counter and reference arrays may have an unrelated table between them. -/
+def Inside (B : AdjBank w) (x : ℕ) : Prop :=
+ (B.countHead.val ≤ x ∧ x < B.countHead.val + B.size.val) ∨
+ (B.refHead.val ≤ x ∧ x < B.stop)
+
+/-- The count array ends before the reference array and the reference array fits in the address
+space. -/
+structure Fits (B : AdjBank w) : Prop where
+ countsBeforeRows : B.countHead.val + B.size.val ≤ B.refHead.val
+ rowsFit : B.stop ≤ 2^w
+
+/-- Each endpoint row contains exactly its positive-length frame ordinals among the first `k`
+candidates, in scan order. -/
+def Represents (B : AdjBank w) (mem : Memory w) (length owner : ℕ → ℕ) (k : ℕ) : Prop :=
+ ∀ v : Word w, v < B.size → rowRepresents mem (B.count v) (B.row v) (adjPrefix w length owner v.val k)
+
+theorem count_val {B : AdjBank w} (h : B.Fits) {v : Word w} (hv : v < B.size) :
+ (B.count v).val = B.countHead.val + v.val := by
+ have := h.countsBeforeRows
+ have := B.refHead.isLt
+ change v.val < B.size.val at hv
+ rw [count, Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+
+private theorem row_bound {B : AdjBank w} {v : Word w} (hv : v < B.size) :
+ B.refHead.val + v.val * B.cap.val + B.cap.val ≤ B.stop := by
+ have h := Nat.mul_le_mul_right B.cap.val (show v.val+1 ≤ B.size.val from hv)
+ rw [Nat.succ_mul] at h
+ dsimp [stop]
+ omega
+
+theorem row_val {B : AdjBank w} (h : B.Fits) {v : Word w} (hv : v < B.size) :
+ (B.row v).val = B.refHead.val + v.val * B.cap.val := by
+ have h1 := row_bound hv
+ have h2 := h.rowsFit
+ by_cases hc : B.cap.val = 0
+ · simp [row, Fin.val_add, Fin.val_mul, hc, Nat.mod_eq_of_lt B.refHead.isLt]
+ · rw [row, Fin.val_add, Fin.val_mul, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)]
+
+/-- Cells outside the bank do not enter its row interpretation. -/
+theorem represents_congr {B : AdjBank w} (hf : B.Fits) {length owner : ℕ → ℕ} {k : ℕ}
+ {mem mem' : Memory w} (h : B.Represents mem length owner k)
+ (cap : ∀ v : Word w, v < B.size → (adjPrefix w length owner v.val k).length ≤ B.cap.val)
+ (heq : ∀ x, B.Inside x → mem' x = mem x) :
+ B.Represents mem' length owner k := by
+ intro v hv
+ have hr := h v hv
+ have hc := cap v hv
+ have h1 := hf.countsBeforeRows
+ have h2 := row_bound hv
+ have h3 := count_val hf hv
+ have h4 := row_val hf hv
+ change v.val < B.size.val at hv
+ constructor
+ · rw [heq _ (Or.inl ⟨by omega, by omega⟩)]
+ exact hr.1
+ · intro i
+ have := i.isLt
+ rw [heq _ (Or.inr ⟨by omega, by omega⟩)]
+ exact hr.2 i
+
+/-- Appending to one row preserves the other rows and every external cell. -/
+theorem append_step {B : AdjBank w} (hf : B.Fits) {length owner : ℕ → ℕ} {k : ℕ}
+ {mem : Memory w} (h : B.Represents mem length owner k) {v id : Word w}
+ (hv : v < B.size) (ho : owner k = v.val) (hid : id = Fin.ofNat (2^w) k)
+ (hne : length k ≠ 0)
+ (cap : ∀ u : Word w, u < B.size → (adjPrefix w length owner u.val (k+1)).length ≤ B.cap.val) :
+ let newMem := writeMemory (writeMemory mem (B.row v + mem (B.count v).val) id)
+ (B.count v) (mem (B.count v).val + 1)
+ B.Represents newMem length owner (k+1) ∧
+ ∀ x, ¬ B.Inside x → newMem x = mem x := by
+ dsimp only
+ have hprefix : adjPrefix w length owner v.val (k+1) = adjPrefix w length owner v.val k ++ [id] := by
+ rw [adjPrefix_succ, ite_eq_left ⟨hne, ho⟩, hid]
+ have hc := cap v hv
+ simp only [hprefix, List.length_append, List.length_singleton] at hc
+ have hr := h v hv
+ have hcap : (mem (B.count v).val).val < B.cap.val := by rw [hr.1]; omega
+ have hcount := count_val hf hv
+ have hrow := row_val hf hv
+ have hmax := row_bound hv
+ have hfit := hf.rowsFit
+ have hsep := hf.countsBeforeRows
+ have hv' := Fin.lt_def.mp hv
+ have hslot : (B.row v + mem (B.count v).val).val = (B.row v).val + (mem (B.count v).val).val := by
+ rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ constructor
+ · intro u hu
+ by_cases he : u = v
+ · subst u
+ rw [hprefix]
+ exact appendRecord_represents (cap := B.cap) hr (by omega) (by omega) (Or.inl (by omega))
+ · have huv : v.val ≠ u.val := fun eq => he (Fin.ext eq.symm)
+ have huPrefix : adjPrefix w length owner u.val (k+1) = adjPrefix w length owner u.val k := by
+ simp [adjPrefix_succ, ho, huv]
+ rw [huPrefix]
+ have huCap := cap u hu
+ rw [huPrefix] at huCap
+ have huC := count_val hf hu
+ have huR := row_val hf hu
+ have hu' := Fin.lt_def.mp hu
+ have hpre := h u hu
+ constructor
+ · simpa only [writeMemory, ite_eq_right (show (B.count u).val ≠ (B.count v).val by omega),
+ ite_eq_right (show (B.count u).val ≠ (B.row v + mem (B.count v).val).val by omega)] using hpre.1
+ · intro i
+ have hi := i.isLt
+ have apart : u.val * B.cap.val + B.cap.val ≤ v.val * B.cap.val ∨
+ v.val * B.cap.val + B.cap.val ≤ u.val * B.cap.val := by
+ rcases lt_or_gt_of_ne huv with hlt | hlt
+ · exact Or.inr (by simpa [Nat.succ_mul] using Nat.mul_le_mul_right B.cap.val (Nat.succ_le_of_lt hlt))
+ · exact Or.inl (by simpa [Nat.succ_mul] using Nat.mul_le_mul_right B.cap.val (Nat.succ_le_of_lt hlt))
+ simpa only [writeMemory, ite_eq_right (show (B.row u).val + i.val ≠ (B.count v).val by omega),
+ ite_eq_right (show (B.row u).val + i.val ≠ (B.row v + mem (B.count v).val).val by omega)] using hpre.2 i
+ · intro x hx
+ simp only [Inside, not_or, not_and_or, not_le, not_lt] at hx
+ simp only [writeMemory, ite_eq_right (show x ≠ (B.count v).val by omega),
+ ite_eq_right (show x ≠ (B.row v + mem (B.count v).val).val by omega)]
+
+end AdjBank
+
+end CompressorRecords.SliceRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSliceIndexedStarts.lean b/lean/OAI/Computability/VPVNP/CompressorSliceIndexedStarts.lean
new file mode 100644
index 0000000000..266ca15077
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSliceIndexedStarts.lean
@@ -0,0 +1,283 @@
+import OAI.Computability.VPVNP.CompressorSliceSchedule
+
+/-!
+# Interval frames from precomputed field starts
+
+The sorted shrinking-bundle tables already contain field starts. Read them
+directly during the pair scan, then index each positive frame at both ends.
+A row occupies consecutive count cells, frames and endpoint-reference cells.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.IndexedStarts
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SliceRAM SliceSchedule
+
+variable {w : ℕ}
+
+/-- Workspace size for the endpoint counts, three-word pair frames, and references at both
+endpoints. -/
+def capacity (m n : ℕ) := m+n+5*(m*n)
+
+/-- Public operands for the pair scan, including the four input columns and the base of the
+output frames. -/
+def pair (input : Fin 4 → Word w) (B : Word w) (m n : ℕ) : Fin 6 → Word w :=
+ ![Fin.ofNat _ n,input 0,input 1,input 2,input 3,Fin.ofNat _ (B.val+m+n)]
+
+/-- Public operands for indexing the pair frames in the source and target adjacency
+directories. -/
+def adj (B : Word w) (m n : ℕ) : Fin 7 → Word w :=
+ ![Fin.ofNat _ n,Fin.ofNat _ m,Fin.ofNat _ (B.val+m+n),B,
+ Fin.ofNat _ (B.val+m+n+3*(m*n)),Fin.ofNat _ (B.val+m),Fin.ofNat _ (B.val+m+n+4*(m*n))]
+
+/-- The input columns end before the workspace and its exclusive end fits in a machine word. -/
+structure Space (input : Fin 4 → Word w) (B : Word w) (m n : ℕ) : Prop where
+ fits : B.val+capacity m n < 2^w
+ reads : ∀ i : Fin 4, (input i).val+(if i.val < 2 then m else n) ≤ B.val
+
+private theorem adj_vals {input : Fin 4 → Word w} {B : Word w} {m n : ℕ}
+ (h : Space input B m n) :
+ let p := adj B m n
+ (p 0).val = n ∧ (p 1).val = m ∧ (p 2).val = B.val+m+n ∧ p 3 = B ∧
+ (p 4).val = B.val+m+n+3*(m*n) ∧ (p 5).val = B.val+m ∧ (p 6).val = B.val+m+n+4*(m*n) := by
+ have hf := h.fits
+ unfold capacity at hf
+ exact ⟨Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt (by omega),rfl,
+ Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt (by omega)⟩
+
+private theorem pair_space {input : Fin 4 → Word w} {B : Word w} {m n : ℕ}
+ (h : Space input B m n) : FrameSpace (pair input B m n) m n := by
+ have hf := h.fits
+ unfold capacity at hf
+ have hb : ((pair input B m n) 5).val = B.val+m+n := Nat.mod_eq_of_lt (by omega)
+ constructor
+ · exact Nat.mod_eq_of_lt (by omega)
+ · omega
+ · intro i; have hi := h.reads i; fin_cases i <;> exact hi.trans B.isLt.le
+ · rw [hb]; omega
+ · intro i; left
+ rw [hb]
+ have hi := h.reads i
+ fin_cases i <;> exact hi.trans (by omega)
+
+private theorem adj_space {input : Fin 4 → Word w} {B : Word w} {m n : ℕ}
+ (h : Space input B m n) : AdjRegions (adj B m n) := by
+ obtain ⟨n',m',a,b,c,d,e⟩ := adj_vals h
+ have hf := h.fits
+ dsimp [capacity] at hf
+ constructor <;> simp only [oldBank,newBank,AdjBank.stop,n',m',a,b,c,d,e,Nat.mul_comm n m] <;> omega
+
+/-- Logs of the count clearing, pair-frame construction, and endpoint indexing sweeps. -/
+structure Reports (w : ℕ) where
+ /-- Reports emitted while clearing the source and target count cells. -/
+ clear : List (Report w)
+ /-- Reports emitted while computing the copy frame for every field pair. -/
+ pairs : List (Report w)
+ /-- Reports emitted while appending positive-length frame references at both endpoints. -/
+ refs : List (Report w)
+
+/-- Memory after replaying the count-clearing sweep. -/
+def Reports.cleared (rs : Reports w) (m : Memory w) := after m (eventLog rs.clear)
+/-- Memory after the cleared workspace has been filled with the pair frames. -/
+def Reports.framed (rs : Reports w) (m : Memory w) := after (rs.cleared m) (eventLog rs.pairs)
+/-- Concatenate the clearing, frame, and reference reports in execution order. -/
+def Reports.all (rs : Reports w) := rs.clear ++ rs.pairs ++ rs.refs
+
+/-- The three native scans produce the supplied reports on empty choice tapes, each starting in
+its predecessor's memory. -/
+structure Native (input : Fin 4 → Word w) (B : Word w) (m n : ℕ)
+ (mem : Memory w) (rs : Reports w) : Prop where
+ clear : runSegment ((template clearOps 0).instantiate w (fun _ => B)).program 8 (some 0) mem
+ (List.replicate (m+n) []) = some rs.clear
+ pairs : runSegment (IndexedPair.table.instantiate w (pair input B m n)).program 38 (some 0)
+ (rs.cleared mem) (List.replicate (m*n) []) = some rs.pairs
+ refs : runSegment (adjTemplate.instantiate w (adj B m n)).program 36 (some 0)
+ (rs.framed mem) (List.replicate (m*n) []) = some rs.refs
+
+/-- All offsets and incidence lists of one completed row. Its frame fields
+occupy three words at each source-major pair index. -/
+structure Stored (B : Word w) (old new : List ℕ) (mem : Memory w) : Prop where
+ lengths : ∀ k, k < old.length*new.length →
+ (mem (B.val+old.length+new.length+3*k+2)).val = (sliceAt old new k).length
+ offsets : ∀ k, k < old.length*new.length → 0 < (sliceAt old new k).length →
+ (mem (B.val+old.length+new.length+3*k)).val = (sliceAt old new k).sourceOffset ∧
+ (mem (B.val+old.length+new.length+3*k+1)).val = (sliceAt old new k).targetOffset
+ oldRows : (oldBank (adj B old.length new.length)).Represents mem
+ (fun k => (sliceAt old new k).length) (· / new.length) (old.length*new.length)
+ newRows : (newBank (adj B old.length new.length)).Represents mem
+ (fun k => (sliceAt old new k).length) (· % new.length) (old.length*new.length)
+
+/-- All reads used by the interval record and both endpoint lists lie in the
+row's allocated bank. Thus a subsequent disjoint row preserves the entire
+stored interpretation. -/
+theorem Stored.transfer {input : Fin 4 → Word w} {B : Word w} {old new : List ℕ} {s t : Memory w}
+ (space : Space input B old.length new.length) (h : Stored B old new s)
+ (same : ∀ x, B.val ≤ x → x < B.val+capacity old.length new.length → t x = s x) :
+ Stored B old new t := by
+ let q := adj B old.length new.length
+ obtain ⟨hn,hm,hf,hc,hr,hc',hr'⟩ := adj_vals space
+ have fit := space.fits
+ dsimp [capacity] at fit
+ have fitOld : (oldBank q).Fits := by
+ constructor <;> simp only [oldBank,q,AdjBank.stop,hn,hm,hc,hr] <;> omega
+ have fitNew : (newBank q).Fits := by
+ constructor <;> simp only [newBank,q,AdjBank.stop,hn,hm,hc',hr',Nat.mul_comm new.length old.length] <;> omega
+ constructor
+ · intro k hk
+ rw [same _ (by omega) (by unfold capacity; omega)]
+ exact h.lengths k hk
+ · intro k hk hpos
+ rw [same _ (by omega) (by unfold capacity; omega),same _ (by omega) (by unfold capacity; omega)]
+ exact h.offsets k hk hpos
+ · apply AdjBank.represents_congr fitOld h.oldRows
+ · intro v _
+ change _ ≤ (adj B old.length new.length 0).val
+ rw [hn]; exact adjPrefix_old_le _ le_rfl
+ · intro x hx
+ simp only [oldBank,q,AdjBank.Inside,AdjBank.stop,hn,hm,hc,hr] at hx
+ exact same x (by omega) (by unfold capacity; omega)
+ · apply AdjBank.represents_congr fitNew h.newRows
+ · intro v _
+ change _ ≤ (adj B old.length new.length 1).val
+ rw [hm]; exact adjPrefix_new_le _ le_rfl
+ · intro x hx
+ simp only [newBank,q,AdjBank.Inside,AdjBank.stop,hn,hm,hc',hr',Nat.mul_comm new.length old.length] at hx
+ exact same x (by omega) (by unfold capacity; omega)
+
+/-- The clearing, intersection and directory passes are deterministic and
+work from arbitrary stale output rows. The two input prefixes are reused. -/
+theorem build (old new : List ℕ) (input : Fin 4 → Word w) (B : Word w) (mem : Memory w)
+ (space : Space input B old.length new.length)
+ (hs : old.sum < 2^w) (ht : new.sum < 2^w)
+ (h : Inputs (pair input B old.length new.length) old new mem) :
+ let m := old.length
+ let n := new.length
+ ∃ rs, Native input B m n mem rs ∧
+ Stored B old new (after mem (eventLog rs.all)) ∧
+ (∀ x, x < B.val ∨ B.val+capacity m n ≤ x → after mem (eventLog rs.all) x = mem x) ∧
+ rs.all.length = m+n+2*(m*n) ∧
+ (rs.all.map Report.probes).sum ≤ m+n+14*(m*n) ∧
+ (rs.all.map fun r => r.events.length+1).sum ≤ 8*(m+n)+74*(m*n) := by
+ intro m n
+ let p := pair input B m n
+ let q := adj B m n
+ let len := fun k => (sliceAt old new k).length
+ have hf := space.fits
+ change B.val+(m+n+5*(m*n)) < 2^w at hf
+ obtain ⟨hn,hm,hframe,hc,hr,hc',hr'⟩ := adj_vals space
+ change (q 0).val = n at hn
+ change (q 1).val = m at hm
+ change (q 2).val = B.val+m+n at hframe
+ change q 3 = B at hc
+ change (q 4).val = B.val+m+n+3*(m*n) at hr
+ change (q 5).val = B.val+m at hc'
+ change (q 6).val = B.val+m+n+4*(m*n) at hr'
+ obtain ⟨clear,cr,zero,cout,_,cl,cw⟩ := clearPass_run B (m+n) (by omega) (by omega) mem
+ let initial := after mem (eventLog clear)
+ have same (j : Fin 4) (i : ℕ) (hi : i < (if j.val < 2 then m else n)) :
+ initial ((input j).val+i) = mem ((input j).val+i) := by
+ have hfit := space.reads j
+ apply cout
+ left
+ change (input j).val + (if j.val < 2 then m else n) ≤ B.val at hfit
+ omega
+ have hi : Inputs p old new initial := by
+ constructor <;> intro i hi
+ · exact (congrArg Fin.val (same 0 i hi)).trans (h.oldStart i hi)
+ · exact (congrArg Fin.val (same 1 i hi)).trans (h.oldWidth i hi)
+ · exact (congrArg Fin.val (same 2 i hi)).trans (h.newStart i hi)
+ · exact (congrArg Fin.val (same 3 i hi)).trans (h.newWidth i hi)
+ have start : FramesAt p old new initial initial 0 := ⟨hi,fun _ hj => by omega,fun _ hj _ => by omega,fun _ _ => rfl⟩
+ obtain ⟨pairs,pr,fr,_,pl,pp,pi⟩ := frameSegment_run (pair_space space) hs ht start (m*n) (by simp [m,n])
+ simp only [Nat.zero_add] at fr
+ let mid := after initial (eventLog pairs)
+ change FramesAt p old new initial mid (m*n) at fr
+ have hhead : (p 5).val = B.val+m+n := Nat.mod_eq_of_lt (by omega)
+ have sq := adj_space space
+ change AdjRegions q at sq
+ have lengths (k : ℕ) (hk : k < (q 1).val*(q 0).val) : (mid ((q 2).val+3*k+2)).val = len k := by
+ rw [hframe,← hhead]
+ exact fr.lengths k (by simpa only [hm,hn] using hk)
+ have z₀ (i : Word w) (hi : i < q 1) : mid (adjOldCount q i).val = 0 := by
+ have hv : i.val < m := lt_of_lt_of_eq (Fin.lt_def.mp hi) hm
+ have eqn : (adjOldCount q i).val = B.val+i.val := by rw [adjOldCount,Fin.val_add,hc,Nat.mod_eq_of_lt (by omega)]
+ rw [eqn,fr.outside _ (Or.inl (by rw [hhead]; omega))]
+ exact zero _ (by omega) (by omega)
+ have z₁ (i : Word w) (hi : i < q 0) : mid (adjNewCount q i).val = 0 := by
+ have hv : i.val < n := lt_of_lt_of_eq (Fin.lt_def.mp hi) hn
+ have eqn : (adjNewCount q i).val = B.val+m+i.val := by rw [adjNewCount,Fin.val_add,hc',Nat.mod_eq_of_lt (by omega)]
+ rw [eqn,fr.outside _ (Or.inl (by rw [hhead]; omega))]
+ exact zero _ (by omega) (by omega)
+ obtain ⟨refs,rr,done,_,rl,rp,ri⟩ := adjPass_run sq lengths z₀ z₁
+ change runSegment (adjTemplate.instantiate w q).program 36 (some 0) mid
+ (List.replicate ((q 1).val*(q 0).val) []) = some refs at rr
+ let post := after mid (eventLog refs)
+ change AdjAt q len mid post ((q 1).val*(q 0).val) at done
+ change refs.length = (q 1).val*(q 0).val at rl
+ change RAMBuckets.cost Report.probes refs = 2*((q 1).val*(q 0).val)+6*adjNonempty len 0 ((q 1).val*(q 0).val) at rp
+ change (refs.map fun r => r.events.length+1).sum = 12*((q 1).val*(q 0).val)+24*adjNonempty len 0 ((q 1).val*(q 0).val) at ri
+ rw [hm,hn] at rr done rl rp ri
+ let rs : Reports w := ⟨clear,pairs,refs⟩
+ have replay : after mem (eventLog rs.all) = post := by
+ simp only [rs,Reports.all,post,mid,initial,after,eventLog,List.flatMap_append,List.foldl_append]
+ have live (x : ℕ) (lo : B.val+m+n ≤ x) (up : x < B.val+m+n+3*(m*n)) : post x = mid x := by
+ exact done.frame_eq sq (by simpa only [hframe] using lo) (by simpa only [hm,hn,hframe] using up)
+ refine ⟨rs,⟨cr,pr,rr⟩,?_,?_,?_,?_,?_⟩
+ · rw [replay]
+ constructor
+ · intro k hk
+ change k < m*n at hk
+ rw [live _ (by dsimp [m,n]; omega) (by dsimp [m,n] at *; omega),← hhead]
+ exact fr.lengths k hk
+ · intro k hk hl
+ change k < m*n at hk
+ change (post (B.val+m+n+3*k)).val = _ ∧ (post (B.val+m+n+3*k+1)).val = _
+ rw [live _ (by omega) (by omega),live _ (by omega) (by omega),← hhead]
+ exact fr.offsets k hk hl
+ · simpa only [hn] using done.oldRows
+ · simpa only [hn] using done.newRows
+ · intro x hx
+ rw [replay]
+ have out : ¬ (oldBank q).Inside x ∧ ¬ (newBank q).Inside x := by
+ simp only [oldBank,newBank,AdjBank.Inside,AdjBank.stop,hm,hn,hc,hc',hr,hr',Nat.mul_comm n m]
+ dsimp [capacity] at hx
+ omega
+ rw [done.outside _ out.1 out.2,fr.outside _ (by rw [hhead]; dsimp [capacity] at hx; omega)]
+ exact cout _ (by dsimp [capacity] at hx; omega)
+ · simp only [rs,Reports.all,List.length_append,cl,pl,rl]; omega
+ · have cp : (clear.map Report.probes).sum = m+n := by
+ rw [show clear.map Report.probes = List.replicate clear.length 1 from
+ List.map_eq_replicate_iff.mpr (fun x hx => (cw x hx).1)]; simp [cl]
+ have e := emitted_all old new
+ have eb := copyRecords_length_le old new
+ have ub : adjNonempty len 0 (m*n) ≤ m*n :=
+ (List.length_filter_le ..).trans (by simp)
+ rw [adjCost_eq_length_add_probes,rl] at rp
+ change emitted old new 0 (m*n) = _ at e
+ change (copyRecords old new).length ≤ m*n at eb
+ change (pairs.map Report.probes).sum = 5*(m*n)+2*emitted old new 0 (m*n) at pp
+ change (pairs.map fun r => r.events.length+1).sum = 34*(m*n)+4*emitted old new 0 (m*n) at pi
+ simp only [rs,Reports.all,List.map_append,List.sum_append,cp]
+ omega
+ · have cc : (clear.map fun x => x.events.length+1).sum = (m+n)*8 := by
+ rw [show (clear.map fun x => x.events.length+1) = List.replicate clear.length 8 from
+ List.map_eq_replicate_iff.mpr (fun x hx => (cw x hx).2)]; simp [cl]
+ have e := emitted_all old new
+ have eb := copyRecords_length_le old new
+ have ub : adjNonempty len 0 (m*n) ≤ m*n :=
+ (List.length_filter_le ..).trans (by simp)
+ change emitted old new 0 (m*n) = _ at e
+ change (copyRecords old new).length ≤ m*n at eb
+ change (pairs.map Report.probes).sum = 5*(m*n)+2*emitted old new 0 (m*n) at pp
+ change (pairs.map fun r => r.events.length+1).sum = 34*(m*n)+4*emitted old new 0 (m*n) at pi
+ simp only [rs,Reports.all,List.map_append,List.sum_append,cc]
+ omega
+
+end CompressorRecords.IndexedStarts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlicePairVisit.lean b/lean/OAI/Computability/VPVNP/CompressorSlicePairVisit.lean
new file mode 100644
index 0000000000..720791f701
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlicePairVisit.lean
@@ -0,0 +1,232 @@
+import OAI.Computability.VPVNP.CompressorSliceRAM
+
+/-!
+# Indexed RAM visits for the interval scan
+
+The persistent word enumerates the Cartesian product in source-major order.
+One call reads both fields from the external start and width arrays. It stores
+the two offsets and length of a nonempty copy in the pair's three-word slot.
+For an empty copy it writes zero in the length cell, even when the slot
+initially contains arbitrary words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SliceRAM.IndexedPair
+
+open BurstRAM BurstRAM.PrivateRAM Compression.PackingData
+
+variable {w : ℕ}
+
+/-- Public words contain the new field count, four array bases in source/target
+and start/width order, and the base of the three-word output slots. -/
+def table : Template 41 15 6 where
+ literalWidth := 2
+ entry := 17
+ code pc := match pc.val with
+ | 0 => .binary .add 4 0 1 1
+ | 1 => .binary .add 5 2 3 2
+ | 2 => .jumpLt 0 2 3 4
+ | 3 => .copy 6 2 5
+ | 4 => .copy 6 0 5
+ | 5 => .jumpLt 4 5 6 7
+ | 6 => .copy 7 4 8
+ | 7 => .copy 7 5 8
+ | 8 => .jumpLt 6 7 9 16
+ | 9 => .binary .sub 8 6 0 10
+ | 10 => .binary .sub 9 6 2 11
+ | 11 => .binary .sub 10 7 6 12
+ | 12 => .writeExternal 11 8 13
+ | 13 => .writeExternal 12 9 14
+ | 14 => .writeExternal 13 10 15
+ | 15 => .returnState 14
+ | 16 => .constant 10 0 14
+ | 17 => .stateWord 14 18
+ | 18 => .publicWord 4 0 19
+ | 19 => .binary .div 5 14 4 20
+ | 20 => .binary .mod 6 14 4 21
+ | 21 => .publicWord 7 1 22
+ | 22 => .binary .add 7 7 5 23
+ | 23 => .readExternal 0 7 24
+ | 24 => .publicWord 7 2 25
+ | 25 => .binary .add 7 7 5 26
+ | 26 => .readExternal 1 7 27
+ | 27 => .publicWord 7 3 28
+ | 28 => .binary .add 7 7 6 29
+ | 29 => .readExternal 2 7 30
+ | 30 => .publicWord 7 4 31
+ | 31 => .binary .add 7 7 6 32
+ | 32 => .readExternal 3 7 33
+ | 33 => .constant 8 3 34
+ | 34 => .binary .mul 8 8 14 35
+ | 35 => .publicWord 11 5 36
+ | 36 => .binary .add 11 11 8 37
+ | 37 => .constant 8 1 38
+ | 38 => .binary .add 12 11 8 39
+ | 39 => .binary .add 13 12 8 40
+ | _ => .binary .add 14 14 8 0
+
+/-- Source field of a pair ordinal, obtained by division by the number of target fields. -/
+def oldIndex (p : Fin 6 → Word w) (k : Word w) : Word w := BinaryOp.div.eval k (p 0)
+
+/-- Target field of a pair ordinal, obtained by reduction modulo the number of target fields. -/
+def newIndex (p : Fin 6 → Word w) (k : Word w) : Word w := BinaryOp.mod.eval k (p 0)
+
+/-- First word of the slot assigned to this ordered pair. -/
+def base (p : Fin 6 → Word w) (k : Word w) : Word w := p 5 + 3 * k
+
+theorem oldIndex_val (p : Fin 6 → Word w) (k : Word w) :
+ (oldIndex p k).val = k.val / (p 0).val :=
+ Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.div_le_self ..) k.isLt)
+
+theorem newIndex_val (p : Fin 6 → Word w) (k : Word w) :
+ (newIndex p k).val = k.val % (p 0).val :=
+ Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.mod_le ..) k.isLt)
+
+theorem base_val (p : Fin 6 → Word w) (k : Word w) (ha : (p 5).val + 3*k.val < 2^w) :
+ (base p k).val = (p 5).val + 3*k.val := by
+ have hmul : ((3 : Word w) * k).val = 3*k.val := by
+ change ((3 % (2^w)) * k.val) % (2^w) = _
+ rw [Nat.mod_mul_mod, Nat.mod_eq_of_lt (by omega)]
+ rw [base, Fin.val_add, hmul, Nat.mod_eq_of_lt ha]
+
+/-- Compute the interval copy for the selected pair using both start and width arrays in
+memory. -/
+def slice (p : Fin 6 → Word w) (k : Word w) (m : Memory w) : CopySlice :=
+ let i := oldIndex p k
+ let j := newIndex p k
+ copySlice (m (p 1 + i).val).val (m (p 2 + i).val).val
+ (m (p 3 + j).val).val (m (p 4 + j).val).val
+
+private def reads (p : Fin 6 → Word w) (k : Word w) (m : Memory w) : List (Event w) :=
+ let a := p 1 + oldIndex p k
+ let b := p 2 + oldIndex p k
+ let c := p 3 + newIndex p k
+ let d := p 4 + newIndex p k
+ [.tick, .tick, .tick, .tick, .tick, .tick, .read a (m a.val), .tick, .tick,
+ .read b (m b.val), .tick, .tick, .read c (m c.val), .tick, .tick,
+ .read d (m d.val)] ++ List.replicate 8 .tick
+
+private def stores (a : Word w) (s : CopySlice) : List (Event w) :=
+ if s.length = 0 then List.replicate 8 .tick ++ [.write (a+1+1) 0] else
+ List.replicate 10 .tick ++ [.write a (Fin.ofNat _ s.sourceOffset),
+ .write (a+1) (Fin.ofNat _ s.targetOffset), .write (a+1+1) (Fin.ofNat _ s.length)]
+
+/-- Full trace of an indexed visit, including the four array reads. -/
+def report (p : Fin 6 → Word w) (k : Word w) (m : Memory w) (s : CopySlice) : Report w :=
+ ⟨reads p k m ++ stores (base p k) s, some (k+1)⟩
+
+theorem report_result (p : Fin 6 → Word w) (k : Word w) (m : Memory w) (s : CopySlice) :
+ (report p k m s).result = some (k+1) := rfl
+
+theorem report_cost (p : Fin 6 → Word w) (k : Word w) (m : Memory w) (s : CopySlice) :
+ (report p k m s).probes = (if s.length = 0 then 5 else 7) ∧
+ (report p k m s).events.length + 1 = (if s.length = 0 then 34 else 38) := by
+ by_cases h : s.length = 0 <;> simp only [report, stores, h, ↓reduceIte] <;> exact ⟨rfl, rfl⟩
+
+theorem report_after (p : Fin 6 → Word w) (k : Word w) (m : Memory w) (s : CopySlice) :
+ let a := base p k
+ after m (report p k m s).events = if s.length = 0 then writeMemory m (a+1+1) 0 else
+ writeMemory (writeMemory (writeMemory m a (Fin.ofNat _ s.sourceOffset))
+ (a+1) (Fin.ofNat _ s.targetOffset)) (a+1+1) (Fin.ofNat _ s.length) := by
+ by_cases h : s.length = 0 <;> simp only [report, stores, h, ↓reduceIte] <;> rfl
+
+private def registers (p : Fin 6 → Word w) (k : Word w) (m : Memory w) : Fin 15 → Word w :=
+ let i := oldIndex p k
+ let j := newIndex p k
+ let a := base p k
+ ![m (p 1+i).val, m (p 2+i).val, m (p 3+j).val, m (p 4+j).val, p 0, i, j, p 4+j,
+ 1, 0, 0, a, a+1, a+1+1, k+1]
+
+set_option maxRecDepth 4096 in
+private theorem execute_reads (p : Fin 6 → Word w) (k : Word w) (m : Memory w) (fuel : ℕ) :
+ let M := table.instantiate w p
+ execute M.program (fuel + 24) (M.program.start k) m [] =
+ (execute M.program fuel ⟨0, k, registers p k m, fun _ => 0⟩ m []).map
+ (fun r => ⟨reads p k m ++ r.events, r.result⟩) := by
+ simp (config := { decide := true }) [execute, Machine.program, table, Template.instantiate,
+ Instr.run, Instr.resize, Config.put, BinaryOp.eval, Report.prepend, Function.comp_def,
+ reads, oldIndex, newIndex]
+ congr 4
+ funext i
+ fin_cases i <;> rfl
+
+private def wordStores (a s t lo hi : Word w) : List (Event w) :=
+ if lo < hi then List.replicate 10 .tick ++
+ [.write a (lo-s), .write (a+1) (lo-t), .write (a+1+1) (hi-lo)]
+ else List.replicate 8 .tick ++ [.write (a+1+1) 0]
+
+set_option maxHeartbeats 600000 in
+private theorem execute_stores (p : Fin 6 → Word w) (k : Word w) (m : Memory w)
+ (rs : Fin 15 → Word w) (h₁ : rs 12 = rs 11 + 1) (h₂ : rs 13 = rs 11 + 1 + 1) :
+ let M := table.instantiate w p
+ let lo := if rs 0 < rs 2 then rs 2 else rs 0
+ let e₁ := rs 0 + rs 1
+ let e₂ := rs 2 + rs 3
+ execute M.program 14 ⟨0, k, rs, fun _ => 0⟩ m [] =
+ some ⟨wordStores (rs 11) (rs 0) (rs 2) lo (if e₁ < e₂ then e₁ else e₂), some (rs 14)⟩ := by
+ dsimp only
+ by_cases hl : rs 0 < rs 2 <;> by_cases hh : rs 0 + rs 1 < rs 2 + rs 3 <;>
+ simp only [wordStores, hl, hh, ↓reduceIte]
+ all_goals
+ split <;> rename_i hc <;>
+ simp (config := { decide := true }) [table, Template.instantiate, Machine.program,
+ execute, Instr.resize, Instr.run, Config.put, BinaryOp.eval, Function.update,
+ hl, hh, hc, h₁, h₂, Report.prepend]
+
+private theorem stores_exact (a s ns t nt : Word w)
+ (hs : s.val + ns.val < 2^w) (ht : t.val + nt.val < 2^w) :
+ let lo := if s < t then t else s
+ let hi := if s + ns < t + nt then s + ns else t + nt
+ wordStores a s t lo hi = stores a (copySlice s.val ns.val t.val nt.val) := by
+ intro lo hi
+ have hlo : lo.val = max s.val t.val := by
+ by_cases h : s < t
+ · simp [lo, h, max_eq_right (Fin.le_iff_val_le_val.mp h.le)]
+ · simp [lo, h, max_eq_left (Fin.le_iff_val_le_val.mp (le_of_not_gt h))]
+ have hsum₁ : (s + ns).val = s.val + ns.val := Nat.mod_eq_of_lt hs
+ have hsum₂ : (t + nt).val = t.val + nt.val := Nat.mod_eq_of_lt ht
+ have hhi : hi.val = min (s.val + ns.val) (t.val + nt.val) := by
+ rw [← hsum₁, ← hsum₂]
+ by_cases h : s + ns < t + nt
+ · simp [hi, h, min_eq_left (Fin.le_iff_val_le_val.mp h.le)]
+ · simp [hi, h, min_eq_right (Fin.le_iff_val_le_val.mp (le_of_not_gt h))]
+ have hlen : (copySlice s.val ns.val t.val nt.val).length = hi.val - lo.val := by
+ simp [copySlice, hhi, hlo]
+ by_cases h : lo < hi
+ · have hsle : s ≤ lo := Fin.le_iff_val_le_val.mpr (hlo ▸ le_max_left ..)
+ have htle : t ≤ lo := Fin.le_iff_val_le_val.mpr (hlo ▸ le_max_right ..)
+ have offset (x : Word w) (hle : x ≤ lo) :
+ lo - x = Fin.ofNat _ (lo.val - x.val) := by
+ apply Fin.ext
+ rw [Fin.sub_val_of_le hle, Fin.val_ofNat, Nat.mod_eq_of_lt (by have := lo.isLt; omega)]
+ have len : hi - lo = Fin.ofNat _ (hi.val - lo.val) := by
+ apply Fin.ext
+ rw [Fin.sub_val_of_le h.le, Fin.val_ofNat, Nat.mod_eq_of_lt (by have := hi.isLt; omega)]
+ have hn : (copySlice s.val ns.val t.val nt.val).length ≠ 0 :=
+ hlen ▸ Nat.sub_ne_zero_of_lt (Fin.lt_def.mp h)
+ simp only [wordStores, stores, h, hn, ↓reduceIte, offset s hsle, offset t htle, len]
+ rw [hhi, hlo]
+ rfl
+ · simp [wordStores, stores, h, hlen, Nat.sub_eq_zero_of_le (le_of_not_gt h)]
+
+/-- A reset call computes the interval intersection and returns the next
+pair identifier. The two endpoint bounds suffice for correct word arithmetic. -/
+theorem visit_native (p : Fin 6 → Word w) (k : Word w) (m : Memory w)
+ (hs : (m (p 1 + oldIndex p k).val).val + (m (p 2 + oldIndex p k).val).val < 2^w)
+ (ht : (m (p 3 + newIndex p k).val).val + (m (p 4 + newIndex p k).val).val < 2^w) :
+ let M := table.instantiate w p
+ execute M.program 38 (M.program.start k) m [] = some (report p k m (slice p k m)) := by
+ dsimp only
+ let r := registers p k m
+ rw [execute_reads p k m 14, execute_stores p k m _ rfl rfl,
+ stores_exact (r 11) (r 0) (r 1) (r 2) (r 3) hs ht]
+ rfl
+
+end CompressorRecords.SliceRAM.IndexedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlicePrefix.lean b/lean/OAI/Computability/VPVNP/CompressorSlicePrefix.lean
new file mode 100644
index 0000000000..a6ce0f556c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlicePrefix.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.CompressorSliceRAM
+import OAI.Computability.VPVNP.RAMChain
+
+/-!
+# Native prefix scans for Appendix E
+
+A fixed table visits the external width array in increasing index order.
+Its persistent word carries the index across calls. An external cell holds the
+running total, so the next call can start with fresh private registers. Each
+visit records the start of one field and adds its width to the total.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SliceRAM
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ}
+
+/-- Public words name the width-array base, start-array base and accumulator cell.
+Register zero carries the persistent field index. -/
+def prefixOps : List (Op 7 3) :=
+ [.stateWord 0, .publicWord 1 0, .binary .add 1 1 0, .read 2 1,
+ .publicWord 3 2, .read 4 3, .publicWord 5 1, .binary .add 5 5 0,
+ .write 5 4, .binary .add 4 4 2, .write 3 4, .constant 6 1, .binary .add 0 0 6]
+
+/-- The two read answers are obtained before either of the two writes. -/
+def prefixEvents (pub : Fin 3 → Word w) (i : Word w) (mem : Memory w) : List (Event w) :=
+ let a := pub 0 + i
+ let total := mem (pub 2).val
+ let width := mem a.val
+ [.tick, .tick, .tick, .read a width, .tick, .read (pub 2) total, .tick, .tick,
+ .write (pub 1 + i) total, .tick, .write (pub 2) (total + width), .tick, .tick]
+
+/-- Replay stores the old total at the field's start and the new total in the accumulator. -/
+theorem after_prefixEvents (pub : Fin 3 → Word w) (i : Word w) (mem : Memory w) :
+ after mem (prefixEvents pub i mem) =
+ writeMemory (writeMemory mem (pub 1 + i) (mem (pub 2).val))
+ (pub 2) (mem (pub 2).val + mem (pub 0 + i).val) := rfl
+
+/-- The actual opcode table executes one field visit in fourteen instructions. -/
+theorem prefixVisit_native (pub : Fin 3 → Word w) (i : Word w) (mem : Memory w) :
+ let M := (template prefixOps 0).instantiate w pub
+ execute M.program 14 (M.program.start i) mem [] =
+ some ⟨prefixEvents pub i mem, some (i + 1)⟩ := by
+ let M := (template prefixOps 0).instantiate w pub
+ change execute M.program (1 + prefixOps.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ mem [] = _
+ rw [execute_template, run_eq_trace]
+ simp (config := { decide := true }) [prefixOps, trace, Op.effect, BinaryOp.eval,
+ Function.update, prefixEvents]
+ rfl
+
+/-- The input and output arrays fit and are disjoint. The accumulator can be
+any other word address. -/
+structure PrefixRegions (pub : Fin 3 → Word w) (n : ℕ) : Prop where
+ widthsFit : (pub 0).val + n ≤ 2^w
+ startsFit : (pub 1).val + n ≤ 2^w
+ arraysApart : (pub 0).val + n ≤ (pub 1).val ∨ (pub 1).val + n ≤ (pub 0).val
+ totalOutsideWidths : (pub 2).val < (pub 0).val ∨ (pub 0).val + n ≤ (pub 2).val
+ totalOutsideStarts : (pub 2).val < (pub 1).val ∨ (pub 1).val + n ≤ (pub 2).val
+
+/-- The first `k` start cells have been filled. Every other cell apart from the
+accumulator retains its initial contents. -/
+structure PrefixAt (pub : Fin 3 → Word w) (ws : List ℕ) (initial mem : Memory w) (k : ℕ) : Prop where
+ widths : ∀ i (hi : i < ws.length), (mem ((pub 0).val + i)).val = ws[i]
+ starts : ∀ i, i < k → (mem ((pub 1).val + i)).val = (ws.take i).sum
+ total : (mem (pub 2).val).val = (ws.take k).sum
+ outside : ∀ x, x ≠ (pub 2).val → (x < (pub 1).val ∨ (pub 1).val + k ≤ x) → mem x = initial x
+
+private theorem prefixAt_step {pub : Fin 3 → Word w} {ws : List ℕ}
+ (bounds : PrefixRegions pub ws.length) (hs : ws.sum < 2^w) {initial mem : Memory w}
+ {i : Word w} (hi : i.val < ws.length) (h : PrefixAt pub ws initial mem i.val) :
+ PrefixAt pub ws initial (after mem (prefixEvents pub i mem)) (i.val + 1) := by
+ have hwa : (pub 0 + i).val = (pub 0).val + i.val := by
+ have := bounds.widthsFit
+ exact Nat.mod_eq_of_lt (by omega)
+ have hsa : (pub 1 + i).val = (pub 1).val + i.val := by
+ have := bounds.startsFit
+ exact Nat.mod_eq_of_lt (by omega)
+ rw [after_prefixEvents]
+ constructor
+ · intro j hj
+ have := bounds.arraysApart
+ have := bounds.totalOutsideWidths
+ simpa [writeMemory, hsa, show (pub 0).val + j ≠ (pub 2).val by omega,
+ show (pub 0).val + j ≠ (pub 1).val + i.val by omega] using h.widths j hj
+ · intro j hj
+ have := bounds.totalOutsideStarts
+ have ht : (pub 1).val + j ≠ (pub 2).val := by omega
+ by_cases he : j = i.val
+ · subst j
+ simpa [writeMemory, ht, hsa] using h.total
+ · simpa [writeMemory, hsa, ht, he]
+ using h.starts j (by omega)
+ · have hsum := congrArg List.sum (List.take_append_drop (i.val + 1) ws)
+ simp only [List.sum_append] at hsum
+ have hval := h.widths i.val hi
+ simp only [writeMemory, ↓reduceIte, Fin.val_add, h.total, hwa, hval]
+ rw [← List.sum_take_succ _ _ hi, Nat.mod_eq_of_lt (by omega)]
+ · intro x hne hx
+ simpa [writeMemory, hne, hsa, show x ≠ (pub 1).val + i.val by omega]
+ using h.outside x hne (by omega)
+
+/-- An uninterrupted segment may start at any completed prefix. All probes
+read or write exactly the two cells specified for their current visit. -/
+theorem prefixSegment_run {pub : Fin 3 → Word w} {ws : List ℕ} (bounds : PrefixRegions pub ws.length)
+ (hl : ws.length < 2^w) (hs : ws.sum < 2^w) {initial mem : Memory w} {k : ℕ}
+ (h : PrefixAt pub ws initial mem k) (steps : ℕ) (hb : k + steps ≤ ws.length) :
+ let M := (template prefixOps 0).instantiate w pub
+ let idx := fun n => Fin.ofNat (2^w) n
+ ∃ rs, runSegment M.program 14 (some (idx k)) mem (List.replicate steps []) = some rs ∧
+ PrefixAt pub ws initial (after mem (eventLog rs)) (k + steps) ∧
+ endState (some (idx k)) rs = some (idx (k + steps)) ∧ rs.length = steps ∧
+ ∀ r ∈ rs, r.probes = 4 ∧ r.events.length + 1 = 14 := by
+ let idx := fun n => Fin.ofNat (2^w) n
+ let M := (template prefixOps 0).instantiate w pub
+ induction steps generalizing k mem with
+ | zero => exact ⟨[], rfl, h, rfl, rfl, by simp⟩
+ | succ steps ih =>
+ have hi : (idx k).val = k := Nat.mod_eq_of_lt (by omega)
+ have hnext : idx k + 1 = idx (k + 1) := by
+ apply Fin.ext
+ rw [Fin.val_add, hi, Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^w by omega)]
+ rfl
+ let r : Report w := ⟨prefixEvents pub (idx k) mem, some (idx k + 1)⟩
+ have hp := prefixAt_step bounds hs (i := idx k) (by omega) (hi ▸ h)
+ rw [hi] at hp
+ obtain ⟨rs,hr,hp',he,hℓ,hcost⟩ := ih hp (by omega)
+ refine ⟨r :: rs, ?_, ?_, ?_, by simp [hℓ], ?_⟩
+ · change runSegment M.program 14 (some (idx k)) mem (List.replicate (steps + 1) []) = _
+ rw [List.replicate_succ, runSegment, prefixVisit_native]
+ simp only [hnext, r]
+ rw [show runSegment M.program 14 (some (idx (k+1))) (after mem (prefixEvents pub (idx k) mem))
+ (List.replicate steps []) = some rs from hr]
+ rfl
+ · have hm : after mem (eventLog (r :: rs)) = after (after mem r.events) (eventLog rs) := by
+ change List.foldl update mem (r.events ++ eventLog rs) = _
+ rw [List.foldl_append]
+ rfl
+ rw [hm, show k + (steps + 1) = k + 1 + steps by omega]
+ exact hp'
+ · change endState (some (idx k + 1)) rs = _
+ rw [hnext, he, show k + (steps + 1) = k + 1 + steps by omega]
+ · intro t ht
+ rcases List.mem_cons.mp ht with rfl | ht
+ · exact ⟨rfl,rfl⟩
+ · exact hcost _ ht
+
+/-- Starting from a zero accumulator, the native pass computes all field
+starts, preserves the widths and returns the field count. Its final accumulator
+contains the full width sum, including when the list is empty. -/
+theorem prefixPass_run {pub : Fin 3 → Word w} {ws : List ℕ} (bounds : PrefixRegions pub ws.length)
+ (hl : ws.length < 2^w) (hs : ws.sum < 2^w) {mem : Memory w}
+ (hw : ∀ i (hi : i < ws.length), (mem ((pub 0).val + i)).val = ws[i])
+ (hz : (mem (pub 2).val).val = 0) :
+ let M := (template prefixOps 0).instantiate w pub
+ ∃ rs, runSegment M.program 14 (some 0) mem (List.replicate ws.length []) = some rs ∧
+ PrefixAt pub ws mem (after mem (eventLog rs)) ws.length ∧
+ endState (some 0) rs = some (Fin.ofNat (2^w) ws.length) ∧ rs.length = ws.length ∧
+ ∀ r ∈ rs, r.probes = 4 ∧ r.events.length + 1 = 14 := by
+ have h : PrefixAt pub ws mem mem 0 :=
+ ⟨hw, fun i hi => by omega, by simpa using hz, fun _ _ _ => rfl⟩
+ simpa using prefixSegment_run bounds hl hs h ws.length (by omega)
+
+end CompressorRecords.SliceRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlicePreparation.lean b/lean/OAI/Computability/VPVNP/CompressorSlicePreparation.lean
new file mode 100644
index 0000000000..b221317f14
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlicePreparation.lean
@@ -0,0 +1,251 @@
+import OAI.Computability.VPVNP.CompressorSlicePrefix
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+
+/-!
+# Preparing the interval-scan workspace
+
+The workspace consists, in order, of two totals, two incidence-count arrays
+and two field-start arrays. A single clearing sweep initializes both totals
+and both count arrays. Two prefix sweeps then produce the starts from the
+original external width arrays. The pair records begin immediately after this
+workspace.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SliceRAM
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ}
+
+/-- Clear the cell at the public base plus the persistent index, then advance. -/
+def clearOps : List (Op 4 1) :=
+ [.stateWord 0, .publicWord 1 0, .binary .add 1 1 0, .constant 2 0,
+ .write 1 2, .constant 3 1, .binary .add 0 0 3]
+
+/-- Native report for zeroing one workspace cell and advancing the clearing cursor. -/
+def clearReport (base i : Word w) : Report w :=
+ ⟨[.tick, .tick, .tick, .tick, .write (base + i) 0, .tick, .tick], some (i + 1)⟩
+
+theorem clearVisit_native (base i : Word w) (mem : Memory w) :
+ let M := (template clearOps 0).instantiate w (fun _ => base)
+ execute M.program 8 (M.program.start i) mem [] = some (clearReport base i) := by
+ let M := (template clearOps 0).instantiate w (fun _ => base)
+ change execute M.program (1 + clearOps.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ mem [] = _
+ rw [execute_template, run_eq_trace]
+ simp (config := { decide := true }) [clearOps, trace, Op.effect, BinaryOp.eval,
+ Function.update, clearReport]
+ rfl
+
+/-- The clearing segment starts from arbitrary memory and writes each visited
+cell once. All addresses outside its interval retain their original contents. -/
+theorem clearPass_run (base : Word w) (n : ℕ) (hfit : base.val + n ≤ 2^w)
+ (hlen : n < 2^w) (mem : Memory w) :
+ let M := (template clearOps 0).instantiate w (fun _ => base)
+ ∃ rs, runSegment M.program 8 (some 0) mem (List.replicate n []) = some rs ∧
+ (∀ x, base.val ≤ x → x < base.val + n → after mem (eventLog rs) x = 0) ∧
+ (∀ x, (x < base.val ∨ base.val + n ≤ x) → after mem (eventLog rs) x = mem x) ∧
+ endState (some 0) rs = some (Fin.ofNat (2^w) n) ∧ rs.length = n ∧
+ ∀ r ∈ rs, r.probes = 1 ∧ r.events.length + 1 = 8 := by
+ let M := (template clearOps 0).instantiate w (fun _ => base)
+ induction n with
+ | zero => exact ⟨[], rfl, fun _ _ _ => by omega, fun _ _ => rfl, rfl, rfl, by simp⟩
+ | succ n ih =>
+ let i := Fin.ofNat (2^w) n
+ have hi : i.val = n := Nat.mod_eq_of_lt (by omega)
+ have ha : (base + i).val = base.val + n := by
+ rw [Fin.val_add, hi, Nat.mod_eq_of_lt (by omega)]
+ have he : i + 1 = Fin.ofNat (2^w) (n+1) := by
+ apply Fin.ext
+ rw [Fin.val_add, hi, Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^w by omega)]
+ rfl
+ obtain ⟨rs,hr,hzero,hout,hend,hℓ,hcost⟩ := ih (by omega) (by omega)
+ let r := clearReport base i
+ have hm : after mem (eventLog (rs ++ [r])) =
+ writeMemory (after mem (eventLog rs)) (base + i) 0 := by
+ simp only [eventLog, List.flatMap_append, after, List.foldl_append]
+ rfl
+ refine ⟨rs ++ [r], ?_, ?_, ?_, ?_, by simp [hℓ], ?_⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, hr]
+ simp only [Option.bind_some, hend, runSegment, clearVisit_native, Option.map_some]
+ rfl
+ · intro x h₁ h₂
+ rw [hm]
+ by_cases hx : x = base.val + n
+ · simp [writeMemory, ha, hx]
+ · simpa [writeMemory, ha, hx] using hzero x h₁ (by omega)
+ · intro x hx
+ rw [hm]
+ simpa [writeMemory, ha, show x ≠ base.val + n by omega] using hout x (by omega)
+ · rw [endState_append]
+ change some (i + 1) = _
+ rw [he]
+ · intro t ht
+ rcases List.mem_append.mp ht with h | h
+ · exact hcost _ h
+ · obtain rfl := List.mem_singleton.mp h
+ exact ⟨rfl,rfl⟩
+
+/-- Public input widths can be supplied in any two arrays disjoint from the
+workspace. Their bounds and the first pair-record address fit the word size. -/
+structure PreparationRegions (oldBase newBase B : Word w) (m n : ℕ) : Prop where
+ oldWidthsFit : oldBase.val + m ≤ 2^w
+ newWidthsFit : newBase.val + n ≤ 2^w
+ frameBaseFits : B.val + 2 + 2*m + 2*n < 2^w
+ oldApart : oldBase.val + m ≤ B.val ∨ B.val + 2 + 2*m + 2*n ≤ oldBase.val
+ newApart : newBase.val + n ≤ B.val ∨ B.val + 2 + 2*m + 2*n ≤ newBase.val
+
+/-- Start and total cells of the source fields. -/
+def oldPrefixData (oldBase B : Word w) (m n : ℕ) : Fin 3 → Word w :=
+ ![oldBase, Fin.ofNat _ (B.val + 2 + m + n), B]
+
+/-- Start and total cells of the target fields. -/
+def newPrefixData (newBase B : Word w) (m n : ℕ) : Fin 3 → Word w :=
+ ![newBase, Fin.ofNat _ (B.val + 2 + 2*m + n), Fin.ofNat _ (B.val + 1)]
+
+/-- Exact contents and footprint of the initialized workspace. -/
+structure Prepared (oldBase newBase B : Word w) (old new : List ℕ) (initial mem : Memory w) : Prop where
+ oldWidths : ∀ i (hi : i < old.length), (mem (oldBase.val + i)).val = old[i]
+ newWidths : ∀ j (hj : j < new.length), (mem (newBase.val + j)).val = new[j]
+ oldStarts : ∀ i, i < old.length → (mem (B.val + 2 + old.length + new.length + i)).val =
+ (old.take i).sum
+ newStarts : ∀ j, j < new.length → (mem (B.val + 2 + 2*old.length + new.length + j)).val =
+ (new.take j).sum
+ oldCounts : ∀ i, i < old.length → mem (B.val + 2 + i) = 0
+ newCounts : ∀ j, j < new.length → mem (B.val + 2 + old.length + j) = 0
+ oldTotal : (mem B.val).val = old.sum
+ newTotal : (mem (B.val + 1)).val = new.sum
+ outside : ∀ x, (x < B.val ∨ B.val + 2 + 2*old.length + 2*new.length ≤ x) → mem x = initial x
+
+/-- Compose the physical memory effects of the three native segments. -/
+def preparationAfter (mem : Memory w) (clear oldRun newRun : List (Report w)) : Memory w :=
+ after (after (after mem (eventLog clear)) (eventLog oldRun)) (eventLog newRun)
+
+/-- The three actual segments with their exact transfer of memory and
+instruction and probe totals. The persistent word starts at zero in each segment. -/
+structure PreparationRuns (oldBase newBase B : Word w) (m n : ℕ) (mem : Memory w)
+ (clear oldRun newRun : List (Report w)) : Prop where
+ clearNative : runSegment ((template clearOps 0).instantiate w (fun _ => B)).program 8
+ (some 0) mem (List.replicate (2+m+n) []) = some clear
+ oldNative : runSegment ((template prefixOps 0).instantiate w (oldPrefixData oldBase B m n)).program
+ 14 (some 0) (after mem (eventLog clear)) (List.replicate m []) = some oldRun
+ newNative : runSegment ((template prefixOps 0).instantiate w (newPrefixData newBase B m n)).program
+ 14 (some 0) (after (after mem (eventLog clear)) (eventLog oldRun))
+ (List.replicate n []) = some newRun
+ clearLength : clear.length = 2+m+n
+ oldLength : oldRun.length = m
+ newLength : newRun.length = n
+ probes : ((clear ++ oldRun ++ newRun).map Report.probes).sum = 2 + 5*(m+n)
+ instructions : ((clear ++ oldRun ++ newRun).map (fun r => r.events.length + 1)).sum =
+ 16 + 22*(m+n)
+
+private theorem sum_constant_cost {α : Type*} (f : α → ℕ) (rs : List α) (v : ℕ)
+ (h : ∀ r ∈ rs, f r = v) : (rs.map f).sum = v * rs.length := by
+ induction rs with
+ | nil => simp
+ | cons r rs ih =>
+ rw [List.map_cons, List.sum_cons, h r (by simp), ih (fun t ht => h t (by simp [ht])),
+ List.length_cons, Nat.mul_succ, Nat.add_comm]
+
+/-- From the original width arrays and arbitrary workspace contents, produce
+both indexed start arrays and zero counts for all source and target fields. -/
+theorem preparation_run {oldBase newBase B : Word w} {old new : List ℕ}
+ (regions : PreparationRegions oldBase newBase B old.length new.length)
+ (hOldSum : old.sum < 2^w) (hNewSum : new.sum < 2^w) {mem : Memory w}
+ (hOldWidths : ∀ i (hi : i < old.length), (mem (oldBase.val + i)).val = old[i])
+ (hNewWidths : ∀ j (hj : j < new.length), (mem (newBase.val + j)).val = new[j]) :
+ ∃ clear oldRun newRun,
+ PreparationRuns oldBase newBase B old.length new.length mem clear oldRun newRun ∧
+ Prepared oldBase newBase B old new mem (preparationAfter mem clear oldRun newRun) := by
+ let O := oldPrefixData oldBase B old.length new.length
+ let N := newPrefixData newBase B old.length new.length
+ have hfit := regions.frameBaseFits
+ have hoa := regions.oldApart
+ have hna := regions.newApart
+ have ho₀ : (O 0).val = oldBase.val := rfl
+ have ho₁ : (O 1).val = B.val + 2 + old.length + new.length := Nat.mod_eq_of_lt (by omega)
+ have ho₂ : (O 2).val = B.val := rfl
+ have hn₀ : (N 0).val = newBase.val := rfl
+ have hn₁ : (N 1).val = B.val + 2 + 2*old.length + new.length := Nat.mod_eq_of_lt (by omega)
+ have hn₂ : (N 2).val = B.val + 1 := Nat.mod_eq_of_lt (by omega)
+ have hoReg : PrefixRegions O old.length :=
+ ⟨regions.oldWidthsFit, by omega, by omega, by omega, by omega⟩
+ have hnReg : PrefixRegions N new.length :=
+ ⟨regions.newWidthsFit, by omega, by omega, by omega, by omega⟩
+ obtain ⟨clear,hcRun,hcZero,hcOutside,_,hcLen,hcCost⟩ :=
+ clearPass_run B (2 + old.length + new.length) (by omega) (by omega) mem
+ let cleared := after mem (eventLog clear)
+ have hoW (i : ℕ) (hi : i < old.length) : (cleared ((O 0).val + i)).val = old[i] := by
+ change (after mem (eventLog clear) (oldBase.val + i)).val = _
+ rw [hcOutside _ (by omega)]
+ exact hOldWidths i hi
+ have hoZ : (cleared (O 2).val).val = 0 := by
+ change (after mem (eventLog clear) B.val).val = 0
+ rw [hcZero _ le_rfl (by omega)]
+ rfl
+ obtain ⟨oldRun,hoRun,ho,_,hoLen,hoCost⟩ :=
+ prefixPass_run hoReg (by omega) hOldSum hoW hoZ
+ let oldDone := after cleared (eventLog oldRun)
+ have hnW (j : ℕ) (hj : j < new.length) : (oldDone ((N 0).val + j)).val = new[j] := by
+ change (after cleared (eventLog oldRun) (newBase.val + j)).val = _
+ rw [ho.outside _ (by omega) (by omega)]
+ change (after mem (eventLog clear) (newBase.val + j)).val = _
+ rw [hcOutside _ (by omega)]
+ exact hNewWidths j hj
+ have hnZ : (oldDone (N 2).val).val = 0 := by
+ change (after cleared (eventLog oldRun) (N 2).val).val = 0
+ rw [ho.outside _ (by omega) (by omega)]
+ change (after mem (eventLog clear) (N 2).val).val = 0
+ rw [hcZero _ (by omega) (by omega)]
+ rfl
+ obtain ⟨newRun,hnRun,hn,_,hnLen,hnCost⟩ :=
+ prefixPass_run hnReg (by omega) hNewSum hnW hnZ
+ refine ⟨clear, oldRun, newRun, ⟨hcRun, hoRun, hnRun, hcLen, hoLen, hnLen, ?_, ?_⟩, ?_⟩
+ · simp only [List.map_append, List.sum_append]
+ rw [sum_constant_cost _ clear 1 (fun r hr => (hcCost r hr).1),
+ sum_constant_cost _ oldRun 4 (fun r hr => (hoCost r hr).1),
+ sum_constant_cost _ newRun 4 (fun r hr => (hnCost r hr).1), hcLen, hoLen, hnLen]
+ omega
+ · simp only [List.map_append, List.sum_append]
+ rw [sum_constant_cost _ clear 8 (fun r hr => (hcCost r hr).2),
+ sum_constant_cost _ oldRun 14 (fun r hr => (hoCost r hr).2),
+ sum_constant_cost _ newRun 14 (fun r hr => (hnCost r hr).2), hcLen, hoLen, hnLen]
+ omega
+ · change Prepared oldBase newBase B old new mem (after oldDone (eventLog newRun))
+ have hkeepCount (x : ℕ) (hx : B.val + 2 ≤ x)
+ (hx' : x < B.val + 2 + old.length + new.length) :
+ after oldDone (eventLog newRun) x = 0 := by
+ rw [hn.outside _ (by omega) (by omega)]
+ change after cleared (eventLog oldRun) x = 0
+ rw [ho.outside _ (by omega) (by omega)]
+ exact hcZero x (by omega) (by omega)
+ constructor
+ · intro i hi
+ rw [hn.outside _ (by omega) (by omega)]
+ exact ho.widths i hi
+ · exact hn.widths
+ · intro i hi
+ rw [hn.outside _ (by omega) (by omega)]
+ simpa only [ho₁] using ho.starts i hi
+ · simpa only [hn₁] using hn.starts
+ · intro i hi
+ exact hkeepCount _ (by omega) (by omega)
+ · intro j hj
+ exact hkeepCount _ (by omega) (by omega)
+ · rw [hn.outside _ (by omega) (by omega)]
+ simpa only [ho₂, List.take_length] using ho.total
+ · simpa only [hn₂, List.take_length] using hn.total
+ · intro x hx
+ rw [hn.outside _ (by omega) (by omega)]
+ change after cleared (eventLog oldRun) x = mem x
+ rw [ho.outside _ (by omega) (by omega)]
+ exact hcOutside x (by omega)
+
+end CompressorRecords.SliceRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSliceRAM.lean b/lean/OAI/Computability/VPVNP/CompressorSliceRAM.lean
new file mode 100644
index 0000000000..cc2a7929ec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSliceRAM.lean
@@ -0,0 +1,335 @@
+import OAI.Computability.VPVNP.CompressorRecordSlices
+import OAI.Computability.VPVNP.RAMRecords
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+
+/-!
+# Burst RAM interval intersection
+
+A fixed instruction table intersects a candidate pair of fields from Appendix E.
+The persistent word points to a frame with four input words and three output
+cells. The table reads the two starts and widths. A nonempty intersection writes
+two offsets and a length. An empty intersection returns zero after the four reads.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SliceRAM
+
+open BurstRAM BurstRAM.PrivateRAM Compression.PackingData
+
+/-- Labels 17–28 load the frame. Labels 0–16 select the larger start and
+smaller end and skip all three writes when the intersection is empty. -/
+def pairTemplate : Template 29 14 0 where
+ literalWidth := 1
+ entry := 17
+ code pc := match pc.val with
+ | 0 => .binary .add 4 0 1 1
+ | 1 => .binary .add 5 2 3 2
+ | 2 => .jumpLt 0 2 3 4
+ | 3 => .copy 6 2 5
+ | 4 => .copy 6 0 5
+ | 5 => .jumpLt 4 5 6 7
+ | 6 => .copy 7 4 8
+ | 7 => .copy 7 5 8
+ | 8 => .jumpLt 6 7 9 16
+ | 9 => .binary .sub 8 6 0 10
+ | 10 => .binary .sub 9 6 2 11
+ | 11 => .binary .sub 10 7 6 12
+ | 12 => .writeExternal 11 8 13
+ | 13 => .writeExternal 12 9 14
+ | 14 => .writeExternal 13 10 15
+ | 15 => .returnState 10
+ | 16 => .constant 10 0 15
+ | 17 => .stateWord 11 18
+ | 18 => .constant 6 1 19
+ | 19 => .readExternal 0 11 20
+ | 20 => .binary .add 12 11 6 21
+ | 21 => .readExternal 1 12 22
+ | 22 => .binary .add 13 12 6 23
+ | 23 => .readExternal 2 13 24
+ | 24 => .binary .add 11 13 6 25
+ | 25 => .readExternal 3 11 26
+ | 26 => .binary .add 11 11 6 27
+ | 27 => .binary .add 12 11 6 28
+ | _ => .binary .add 13 12 6 0
+
+variable {w : ℕ}
+
+private def lower (s t : Word w) := if s < t then t else s
+private def upper (s t : Word w) := if s < t then s else t
+
+private def written (rs : Fin 14 → Word w) (lo hi : Word w) : Report w :=
+ ⟨List.replicate 10 .tick ++
+ [.write (rs 11) (lo - rs 0), .write (rs 12) (lo - rs 2), .write (rs 13) (hi - lo)],
+ some (hi - lo)⟩
+
+private def skipped (w : ℕ) : Report w := ⟨List.replicate 8 .tick, some 0⟩
+
+private theorem execute_words (pub : Fin 0 → Word w) (state : Word w) (rs : Fin 14 → Word w)
+ (priv : Word w → Word w) (mem : Memory w) :
+ let M := pairTemplate.instantiate w pub
+ let lo := lower (rs 0) (rs 2)
+ let hi := upper (rs 0 + rs 1) (rs 2 + rs 3)
+ execute M.program 14 ⟨0, state, rs, priv⟩ mem [] =
+ some (if lo < hi then written rs lo hi else skipped w) := by
+ dsimp only
+ by_cases hl : rs 0 < rs 2 <;> by_cases hh : rs 0 + rs 1 < rs 2 + rs 3 <;>
+ simp only [lower, upper, hl, hh, ↓reduceIte]
+ all_goals
+ split <;> rename_i hc <;>
+ simp (config := { decide := true }) [pairTemplate, Template.instantiate, Machine.program,
+ execute, Instr.resize, Instr.run, Config.put, BinaryOp.eval, Function.update,
+ hl, hh, hc, written, skipped, Report.prepend]
+
+private def wordNat (n : ℕ) : Word w := Fin.ofNat _ n
+
+private theorem word_val (x : Word w) : wordNat x.val = x :=
+ Fin.ext (Nat.mod_eq_of_lt x.isLt)
+
+/-- The native events prescribed by the descriptor. Source and target offsets
+are written only when the interval contains a bit. -/
+def resultReport (rs : Fin 14 → Word w) (slice : CopySlice) : Report w :=
+ if slice.length = 0 then skipped w else
+ ⟨List.replicate 10 .tick ++
+ [.write (rs 11) (wordNat slice.sourceOffset), .write (rs 12) (wordNat slice.targetOffset),
+ .write (rs 13) (wordNat slice.length)], some (wordNat slice.length)⟩
+
+/-- From label zero, the table executes the pair test with fields already loaded. -/
+theorem execute_slice (pub : Fin 0 → Word w) (state : Word w) (rs : Fin 14 → Word w)
+ (priv : Word w → Word w) (mem : Memory w)
+ (hs : (rs 0).val + (rs 1).val < 2^w) (ht : (rs 2).val + (rs 3).val < 2^w) :
+ let M := pairTemplate.instantiate w pub
+ let slice := copySlice (rs 0).val (rs 1).val (rs 2).val (rs 3).val
+ execute M.program 14 ⟨0,state,rs,priv⟩ mem [] = some (resultReport rs slice) := by
+ dsimp only
+ rw [execute_words]
+ let lo := lower (rs 0) (rs 2)
+ let hi := upper (rs 0 + rs 1) (rs 2 + rs 3)
+ let slice := copySlice (rs 0).val (rs 1).val (rs 2).val (rs 3).val
+ have hl : lo.val = max (rs 0).val (rs 2).val := by
+ by_cases h : rs 0 < rs 2
+ · simp [lo, lower, h, max_eq_right (Fin.le_iff_val_le_val.mp h.le)]
+ · change (if rs 0 < rs 2 then rs 2 else rs 0).val = _
+ rw [ite_eq_right h, max_eq_left (Fin.le_iff_val_le_val.mp (le_of_not_gt h))]
+ have he₁ : (rs 0 + rs 1).val = (rs 0).val + (rs 1).val := by
+ rw [Fin.val_add, Nat.mod_eq_of_lt hs]
+ have he₂ : (rs 2 + rs 3).val = (rs 2).val + (rs 3).val := by
+ rw [Fin.val_add, Nat.mod_eq_of_lt ht]
+ have hu : hi.val = min ((rs 0).val + (rs 1).val) ((rs 2).val + (rs 3).val) := by
+ rw [← he₁, ← he₂]
+ by_cases h : rs 0 + rs 1 < rs 2 + rs 3
+ · simp [hi, upper, h, min_eq_left (Fin.le_iff_val_le_val.mp h.le)]
+ · simp [hi, upper, h, min_eq_right (Fin.le_iff_val_le_val.mp (le_of_not_gt h))]
+ have hlen : slice.length = hi.val - lo.val := by simp [slice, copySlice, hl, hu]
+ change some (if lo < hi then written rs lo hi else skipped w) = some (resultReport rs slice)
+ by_cases h : lo < hi
+ · have hpos : slice.length ≠ 0 := by rw [hlen]; have := Fin.lt_def.mp h; omega
+ have ho₁ : lo - rs 0 = wordNat slice.sourceOffset := by
+ have hle : rs 0 ≤ lo := Fin.le_iff_val_le_val.mpr (hl ▸ le_max_left ..)
+ rw [← word_val (lo - rs 0), Fin.sub_val_of_le hle, hl]
+ rfl
+ have ho₂ : lo - rs 2 = wordNat slice.targetOffset := by
+ have hle : rs 2 ≤ lo := Fin.le_iff_val_le_val.mpr (hl ▸ le_max_right ..)
+ rw [← word_val (lo - rs 2), Fin.sub_val_of_le hle, hl]
+ rfl
+ have hz : hi - lo = wordNat slice.length := by
+ rw [← word_val (hi-lo), Fin.sub_val_of_le h.le, hlen]
+ simp [h, resultReport, hpos, written, ho₁, ho₂, hz]
+ · have hzero : slice.length = 0 := by rw [hlen]; exact Nat.sub_eq_zero_of_le (le_of_not_gt h)
+ simp [h, resultReport, hzero]
+
+/-- Three probes and thirteen nonterminal instructions suffice for a nonempty
+copy. A disjoint pair takes eight nonterminal instructions and zero probes. -/
+theorem resultReport_cost (rs : Fin 14 → Word w) (slice : CopySlice) :
+ (resultReport rs slice).probes = (if slice.length = 0 then 0 else 3) ∧
+ (resultReport rs slice).events.length = (if slice.length = 0 then 8 else 13) := by
+ by_cases h : slice.length = 0 <;> simp only [resultReport, h, ↓reduceIte] <;> exact ⟨rfl,rfl⟩
+
+/-- Consecutive cells of a seven-word frame, with the burst machine's modular addresses. -/
+def frameAddress (base : Word w) : ℕ → Word w
+ | 0 => base
+ | i + 1 => frameAddress base i + 1
+
+/-- Every cell of a frame fitting the address space has its ordinary consecutive address. -/
+theorem frameAddress_val (base : Word w) (i : ℕ) (h : base.val + i < 2^w) :
+ (frameAddress base i).val = base.val + i := by
+ induction i with
+ | zero => simp [frameAddress]
+ | succ i ih =>
+ have h1 : (1 : Word w).val = 1 := by
+ rw [Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^w by omega)]
+ rw [frameAddress, Fin.val_add, ih (by omega), h1, Nat.mod_eq_of_lt (by omega)]
+ omega
+
+private def frameRegs (base : Word w) (mem : Memory w) : Fin 14 → Word w :=
+ ![mem base.val, mem (frameAddress base 1).val, mem (frameAddress base 2).val,
+ mem (frameAddress base 3).val, 0, 0, 1, 0, 0, 0, 0, frameAddress base 4,
+ frameAddress base 5, frameAddress base 6]
+
+private def frameEvents (base : Word w) (mem : Memory w) : List (Event w) :=
+ [.tick, .tick, .read base (mem base.val), .tick,
+ .read (frameAddress base 1) (mem (frameAddress base 1).val), .tick,
+ .read (frameAddress base 2) (mem (frameAddress base 2).val), .tick,
+ .read (frameAddress base 3) (mem (frameAddress base 3).val), .tick, .tick, .tick]
+
+private theorem execute_frame_prefix (pub : Fin 0 → Word w) (base : Word w) (mem : Memory w)
+ (fuel : ℕ) :
+ let M := pairTemplate.instantiate w pub
+ execute M.program (fuel + 12) (M.program.start base) mem [] =
+ (execute M.program fuel ⟨0, base, frameRegs base mem, fun _ => 0⟩ mem []).map
+ (fun r => ⟨frameEvents base mem ++ r.events, r.result⟩) := by
+ simp (config := { decide := true }) [execute, Machine.program, pairTemplate, Template.instantiate,
+ Instr.run, Instr.resize, Config.put, BinaryOp.eval, Report.prepend, Function.comp_def,
+ frameAddress, frameEvents]
+ congr 4
+ funext i
+ fin_cases i <;> rfl
+
+/-- The four input words of a candidate test in a caller's memory. -/
+def frameHolds (base : Word w) (mem : Memory w) (p : Field × Field) : Prop :=
+ (mem base.val).val = p.1.start ∧
+ (mem (frameAddress base 1).val).val = p.1.width ∧
+ (mem (frameAddress base 2).val).val = p.2.start ∧
+ (mem (frameAddress base 3).val).val = p.2.width
+
+/-- Exact report for the whole candidate call, including its frame reads. -/
+def frameReport (base : Word w) (mem : Memory w) (p : Field × Field) : Report w :=
+ let r := resultReport (frameRegs base mem) (copySlice p.1.start p.1.width p.2.start p.2.width)
+ ⟨frameEvents base mem ++ r.events, r.result⟩
+
+/-- Fresh-call execution for every field pair of the source-major scan. The
+two bounds on total widths suffice for all its endpoint additions. -/
+theorem execute_candidate (pub : Fin 0 → Word w) (base : Word w) (mem : Memory w)
+ {old new : List ℕ} (p : Field × Field) (hmem : frameHolds base mem p)
+ (hp : p ∈ candidates old new) (hs : old.sum < 2^w) (ht : new.sum < 2^w) :
+ let M := pairTemplate.instantiate w pub
+ execute M.program 26 (M.program.start base) mem [] = some (frameReport base mem p) := by
+ obtain ⟨ho,hn⟩ := List.mem_product.mp hp
+ have hse := (fieldsFrom_bounds ho).2.2.2
+ have hte := (fieldsFrom_bounds hn).2.2.2
+ obtain ⟨h₀,h₁,h₂,h₃⟩ := hmem
+ dsimp only
+ rw [execute_frame_prefix pub base mem 14, execute_slice]
+ · simp [frameReport, frameRegs, h₀, h₁, h₂, h₃]
+ · change (mem base.val).val + (mem (frameAddress base 1).val).val < 2^w
+ omega
+ · change (mem (frameAddress base 2).val).val + (mem (frameAddress base 3).val).val < 2^w
+ omega
+
+/-- The frame contributes four reads and twelve instructions. The final
+return costs one instruction in both cases. -/
+theorem frameReport_cost (base : Word w) (mem : Memory w) (p : Field × Field) :
+ let emitted := (intersectFields p).isSome
+ (frameReport base mem p).probes = 4 + (if emitted then 3 else 0) ∧
+ (frameReport base mem p).events.length + 1 = 21 + (if emitted then 5 else 0) := by
+ by_cases h : (copySlice p.1.start p.1.width p.2.start p.2.width).length = 0 <;>
+ simp only [intersectFields, frameReport, resultReport, h, ↓reduceIte] <;> exact ⟨rfl,rfl⟩
+
+/-- Replay gives exactly the three specified writes for a nonempty interval
+and preserves memory on the empty branch. -/
+theorem frameReport_after (base : Word w) (mem : Memory w) (p : Field × Field) :
+ let s := copySlice p.1.start p.1.width p.2.start p.2.width
+ after mem (frameReport base mem p).events = if s.length = 0 then mem else
+ writeMemory (writeMemory (writeMemory mem (frameAddress base 4) (Fin.ofNat _ s.sourceOffset))
+ (frameAddress base 5) (Fin.ofNat _ s.targetOffset)) (frameAddress base 6) (Fin.ofNat _ s.length) := by
+ dsimp only
+ by_cases h : (copySlice p.1.start p.1.width p.2.start p.2.width).length = 0 <;>
+ simp only [frameReport, resultReport, h, ↓reduceIte] <;> rfl
+
+private theorem sum_frame_cost (base : Field × Field → Word w) (mem : Field × Field → Memory w)
+ (pairs : List (Field × Field)) :
+ let reports := pairs.map fun p => frameReport (base p) (mem p) p
+ (reports.map Report.probes).sum = 4 * pairs.length + 3 * (pairs.filterMap intersectFields).length ∧
+ (reports.map (fun r => r.events.length + 1)).sum =
+ 21 * pairs.length + 5 * (pairs.filterMap intersectFields).length := by
+ induction pairs with
+ | nil => simp
+ | cons p pairs ih =>
+ obtain ⟨hprobes,hsteps⟩ := frameReport_cost (base p) (mem p) p
+ cases h : intersectFields p <;>
+ simp only [List.map_cons, List.sum_cons, List.filterMap_cons, List.length_cons, h,
+ Option.isSome_none, Option.isSome_some, Bool.false_eq_true, ↓reduceIte] at *
+ all_goals omega
+
+/-- Exact cost of all candidate-test calls. Memories can differ from one
+call to the next. Each report is native under the frame invariant of
+`execute_candidate`. The cost depends only on field and record counts. -/
+theorem scan_cost (old new : List ℕ) (base : Field × Field → Word w)
+ (mem : Field × Field → Memory w) :
+ let reports := (candidates old new).map fun p => frameReport (base p) (mem p) p
+ (reports.map Report.probes).sum = 4 * (old.length * new.length) + 3 * (copyRecords old new).length ∧
+ (reports.map (fun r => r.events.length + 1)).sum =
+ 21 * (old.length * new.length) + 5 * (copyRecords old new).length := by
+ simpa only [candidates_length, copyRecords] using sum_frame_cost base mem (candidates old new)
+
+section PrefixScan
+
+open PrimedStackRAM
+
+/-- One step of `fieldsFrom` with the width in external memory. Registers
+0 and 1 carry the index and prefix sum. Register 2 supplies the width address
+and registers 3–5 supply the index, start and width output addresses. -/
+def fieldOps : List (Op 8 0) :=
+ [.read 6 2, .write 3 0, .write 4 1, .write 5 6, .binary .add 1 1 6,
+ .constant 7 1, .binary .add 0 0 7]
+
+/-- The prefix scan reads one width, writes one indexed descriptor and
+advances both running totals. -/
+theorem fieldOps_trace (pub : Fin 0 → Word w) (state : Word w) (rs : Regs w 8) (mem : Memory w) :
+ let width := mem (rs 2).val
+ let es := [.read (rs 2) width, .write (rs 3) (rs 0), .write (rs 4) (rs 1),
+ .write (rs 5) width, .tick, .tick, .tick]
+ ∃ rs', trace pub state fieldOps rs mem = some (es, rs', after mem es) ∧
+ rs' 0 = rs 0 + 1 ∧ rs' 1 = rs 1 + width := by
+ simp (config := { decide := true }) [fieldOps, trace, Op.effect, BinaryOp.eval, Function.update,
+ after, update]
+ rfl
+
+/-- Numeric field and next prefix computed by the straight-line native code,
+under the usual index and address-width bounds. -/
+theorem fieldOps_native (pub : Fin 0 → Word w) (state : Word w) (rs : Regs w 8)
+ (priv : Word w → Word w) (mem : Memory w) (hi : (rs 0).val + 1 < 2^w)
+ (hw : (rs 1).val + (mem (rs 2).val).val < 2^w) :
+ let M := (template fieldOps 1).instantiate w pub
+ let width := mem (rs 2).val
+ ∃ es post, trace pub state fieldOps rs mem = some (es, post, after mem es) ∧
+ execute M.program 8 ⟨M.entry,state,rs,priv⟩ mem [] = some ⟨es, some (post 1)⟩ ∧
+ es = [.read (rs 2) width, .write (rs 3) (rs 0), .write (rs 4) (rs 1),
+ .write (rs 5) width, .tick, .tick, .tick] ∧
+ (post 0).val = (rs 0).val + 1 ∧ (post 1).val = (rs 1).val + width.val ∧
+ countProbes es = 4 ∧ es.length + 1 = 8 := by
+ obtain ⟨rs',h,hn,hp⟩ := fieldOps_trace pub state rs mem
+ refine ⟨_,rs',h,?_,rfl,?_,?_,rfl,rfl⟩
+ · change execute ((template fieldOps 1).instantiate w pub).program (1 + fieldOps.length)
+ _ mem [] = _
+ rw [execute_template, run_eq_trace, h]
+ simp
+ · have h1 : (1 : Word w).val = 1 := by
+ rw [Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^w by omega)]
+ rw [hn, Fin.val_add, h1, Nat.mod_eq_of_lt hi]
+ · rw [hp, Fin.val_add, Nat.mod_eq_of_lt hw]
+
+/-- The two prefix scans plus all interval tests use a width-independent
+number of word instructions and probes. This accounts for the prefix steps
+and the candidate calls with their input frames in place. -/
+theorem scan_bounds (old new : List ℕ) (base : Field × Field → Word w)
+ (mem : Field × Field → Memory w) :
+ let reports := (candidates old new).map fun p => frameReport (base p) (mem p) p
+ let fields := old.length + new.length
+ let pairs := old.length * new.length
+ 4 * fields + (reports.map Report.probes).sum ≤ 4 * fields + 7 * pairs ∧
+ 8 * fields + (reports.map fun r => r.events.length + 1).sum ≤ 8 * fields + 26 * pairs := by
+ have h := scan_cost old new base mem
+ have hsize := copyRecords_length_le old new
+ dsimp only at *
+ omega
+
+end PrefixScan
+
+end CompressorRecords.SliceRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSliceReader.lean b/lean/OAI/Computability/VPVNP/CompressorSliceReader.lean
new file mode 100644
index 0000000000..2f80cf3289
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSliceReader.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.CompressorBaseAdvice
+import OAI.Computability.VPVNP.CompressorCoordinateBudgets
+import OAI.Computability.VPVNP.CompressorEvaluatorInput
+import OAI.Computability.VPVNP.CompressorMatrixReader
+import OAI.Computability.VPVNP.CompressorReaderTypes
+import OAI.Computability.VPVNP.RankCoordinateCanonicalReader
+
+/-! # The two advised physical readers for the actual compressor algebra
+
+At every admissible prime and slice, the same two fixed programs return the
+multiplication and Frobenius coordinates. All the initial field, coefficient,
+rank and monomial advice is selected before the exponent widths and coordinate
+ordinals. A single length-indexed budget bounds both programs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace CompressorReader
+
+open RankQuery.Stack RankQuery.Stack.Coordinate RAMTape Evaluator.MatrixCallbacks
+
+/-- The bit selects the fixed Frobenius or label-multiplication control. The
+program and its ports do not depend on the input length or the field. -/
+def read (frobenius : Bool) : FiniteRoutine (ReadPort Ports) :=
+ CanonicalReader.program MacaulayRead.ordinaryReader frobenius
+
+end CompressorReader
+
+namespace Compression.BlockSchedule.Templates
+
+open LabelEvaluator SliceArithmetic RankQuery.Stack RankQuery.Stack.Coordinate
+open ConcreteResources Evaluator.MatrixCallbacks RAMTape RadicalCertificate.MonomialIndex
+
+local instance sliceReaderPrime (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+/-- Finite enumeration of the slice's ground field used in the coordinate reader construction. -/
+noncomputable local instance sliceReaderFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+/-- Classical equality decision on ground-field elements used by the slice reader. -/
+noncomputable local instance sliceReaderDecidable (p : Nat.Primes) (t d : ℕ) : DecidableEq (Ground p t d) := Classical.decEq _
+
+variable {k : Type*} [Field k] {sched : BlockSchedule k} (B : sched.Templates)
+
+set_option maxHeartbeats 1800000 in
+set_option maxRecDepth 10000 in
+set_option synthInstance.maxSize 12000 in
+/-- The deterministic coordinate readers, their common advice and their
+uniform bounds for one model. The field-coordinate map is the one used in
+the terminal test of the nondeterministic evaluator. -/
+theorem exists_sliceReaderAdvice (q c : ℕ) {sp ex : ℕ → ℕ} (signed : B.SignedCallFits q c (B.coordinateWidth q c) sp ex)
+ (n : ℕ) (hn : 2 ≤ n) (p : Nat.Primes) (hp : q ≠ 0 → p.val = q) (hz : q = 0 → p.val ≤ 2^B.compressorPrimeBits c n)
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn c)) :
+ let w := B.coordinateWidth q c n
+ let cost := B.coordinateBudget CompressorReader.Parts CompressorReader.Work CompressorReader.K q c n w (sp n) (ex n)
+ ∃ H : B.SliceReaderAdvice M (CompressorReader.read true) (CompressorReader.read false),
+ H.indexWidth = w ∧ H.degreePred+1 ≤ B.readerDegreeBudget q c n ∧ H.limbWidth ≤ B.readerLimbBudget q c n ∧
+ H.extraSpace ≤ cost.space ∧ H.peak ≤ cost.space ∧ H.queryExponent ≤ Nat.clog 2 cost.time := by
+ intro w cost
+ let t := B.compressorLabelCount c n
+ let e := SliceField.extensionDegree p.val (columnCountBound t (B.compressorDegree n))
+ let v := B.readerLimbBudget q c n
+ let plan := B.compressorReaderPlan q c n
+ let data := M.queryData (B.compressorCoeff hn c)
+ let d := planDepth plan
+ let degree := B.readerDegreeBudget q c n
+ let A := plan.live degree v w (sp n)
+ let S := plan.armSpace degree v w (sp n)
+ let T := plan.readTime degree v w (sp n) (ex n)
+ have : NeZero e := ⟨Nat.succ_ne_zero _⟩
+ obtain ⟨m, φ, _, irreducible, coord⟩ := exists_compatible_advice p.val (columnCountBound t (B.compressorDegree n))
+ have : Fact (Irreducible (modulus m)) := ⟨irreducible⟩
+ let : DecidableEq (AdjoinRoot (modulus m)) := Classical.decEq _
+ obtain ⟨planFits, degreeFits, working⟩ := B.compressorReaderCovers q c hn p M hp hz
+ have hdegree : e ≤ degree := degreeFits
+ have hw : plan.wordWidth ≤ w := (planWidth_covers plan).2
+ have fit : CanonicalFits data d w v e A S T := canonicalFits planFits le_rfl hdegree le_rfl (sp n) (ex n)
+ obtain ⟨signedS, signedT⟩ := signed n hn p.val e v hdegree le_rfl
+ have raw := B.compressorMatrixReader q c hn M φ hp hz hw hdegree le_rfl working (sp n) (ex n) signedS signedT
+ let ready := B.compressorBaseReady hn M m φ w v
+ let base := B.compressorBaseBank hn M m φ w v
+ have isReady : ready base := B.compressorBaseBank_ready hn M m φ q w v hp hz hw
+ let layout := JointScalar.Leaf.layout B.Entry B.EquationIndex B.equation c hn w p.val e v
+ have signedBank : JointScalar.Leaf.bankSize layout w (t*w) ≤ sp n :=
+ (le_max_right ..).trans ((Nat.le_add_right ..).trans signedS)
+ have room (s : Stacks CompressorReader.K) (hs : ready s) (a : CompressorReader.K) : (s a).length ≤ A :=
+ B.compressorBaseReady_length hn M m φ q w v (sp n) hdegree le_rfl signedBank s hs a
+ let actual := preparedBudget CompressorReader.Parts CompressorReader.Work CompressorReader.K
+ (SliceMinors.height data) (SliceMinors.width data) (NativeReader.order data) d w v e T A S T t
+ have covered : actual.time ≤ cost.time ∧ actual.space ≤ cost.space :=
+ B.coordinateBudget_covers CompressorReader.Parts CompressorReader.Work CompressorReader.K q c n w (sp n) (ex n)
+ data planFits hdegree le_rfl
+ let extra := SelectedAdvice.selectedExtra m data w v base
+ have extras (a : CompressorReader.Ports) : (extra a).length ≤ cost.space := by
+ have h := SelectedAdvice.extra_length (d := d) (S := S) m data base (room _ isReady) fit.rowFit fit.columnFit
+ fit.wordLive fit.arityLive fit.scalarLive working a
+ exact h.trans ((preparedBudget_advice CompressorReader.Parts CompressorReader.Work CompressorReader.K
+ (SliceMinors.height data) (SliceMinors.width data) (NativeReader.order data) d w v e T A S T t).trans covered.2)
+ let dim := M.dimensionWord fit.dimensionFit
+ have run (op : QueryData.Operation t) :
+ ReadsEntryWithin φ dim extra (CompressorReader.read (SelectedAdvice.mode op)) v (SelectedAdvice.label op)
+ (2^(Nat.clog 2 cost.time)) cost.space (fun src dest ↦ data.matrixEntry op dest src) := by
+ have h := CanonicalReader.readsEntryWithin φ data dim rfl op MacaulayRead.ordinaryReader raw room base isReady working fit
+ exact ReadsEntryWithin.mono φ dim extra (covered.1.trans (Nat.le_pow_clog (by decide) _)) covered.2 h
+ refine ⟨{
+ degreePred := Nat.log p.val (2*columnCountBound t (B.compressorDegree n))
+ coefficients := m
+ fieldMap := φ
+ primeCoordinate := coord
+ indexWidth := w
+ dimensionFits := fit.dimensionFit
+ limbWidth := v
+ widthFits := working
+ extra := extra
+ extraSpace := cost.space
+ extraFits := extras
+ peak := cost.space
+ queryExponent := Nat.clog 2 cost.time
+ frobeniusRead := run .frobenius
+ labelRead := fun j ↦ run (.label j)
+ }, rfl, hdegree, le_rfl, le_rfl, le_rfl, le_rfl⟩
+
+end Compression.BlockSchedule.Templates
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSliceSchedule.lean b/lean/OAI/Computability/VPVNP/CompressorSliceSchedule.lean
new file mode 100644
index 0000000000..9742208094
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSliceSchedule.lean
@@ -0,0 +1,635 @@
+import OAI.Computability.VPVNP.CompressorSlicePairVisit
+import OAI.Computability.VPVNP.CompressorSlicePreparation
+import OAI.Computability.VPVNP.CompressorSliceAdjacency
+import OAI.Computability.VPVNP.RAMChain
+import Mathlib.Data.List.OfFn
+
+/-!
+# Scheduling the compressor's interval records
+
+The source-major Cartesian scan uses one persistent pair number. Its quotient
+and remainder select source and target fields in their two external arrays.
+The output frame for that pair consists of three words, two offsets and a
+length. Empty intersections have length zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SliceSchedule
+
+open BurstRAM BurstRAM.PrivateRAM Compression.PackingData
+
+/-- Descriptor at a numerical array index. The default width occurs only
+outside the array and is never read by a scheduled visit. -/
+def fieldAt (ws : List ℕ) (i : ℕ) : Field :=
+ ⟨i, (ws.take i).sum, ws[i]?.getD 0⟩
+
+private theorem fields_eq_ofFn (ws : List ℕ) :
+ fieldsFrom 0 0 ws = List.ofFn (fun i : Fin ws.length => fieldAt ws i) := by
+ apply List.ext_getElem (by simp)
+ intro i hi hj
+ have h : i < ws.length := by simpa using hi
+ simp [fieldsFrom_get ws 0 0 i h, fieldAt]
+
+/-- Read the pair whose row-major index is `k`. -/
+def pairAt (old new : List ℕ) (k : ℕ) : Field × Field :=
+ (fieldAt old (k / new.length), fieldAt new (k % new.length))
+
+/-- Copy interval for the `k`th old/new field pair in source-major order. -/
+def sliceAt (old new : List ℕ) (k : ℕ) : CopySlice :=
+ let p := pairAt old new k
+ copySlice p.1.start p.1.width p.2.start p.2.width
+
+/-- The word-arithmetic index order is the order of the record builder's
+Cartesian product, including fields of width zero. -/
+theorem numbered_pairs (old new : List ℕ) :
+ List.ofFn (fun k : Fin (old.length * new.length) => pairAt old new k) = candidates old new := by
+ rw [List.ofFn_mul, candidates, fields_eq_ofFn, fields_eq_ofFn]
+ change _ = List.flatten (List.map _ (List.ofFn _))
+ rw [List.map_ofFn]
+ congr 2
+ funext i
+ dsimp only [Function.comp_apply]
+ rw [List.map_ofFn]
+ congr 1
+ funext j
+ have hn : 0 < new.length := (Nat.zero_le j.val).trans_lt j.isLt
+ have hd : (i.val * new.length + j.val) / new.length = i.val := by
+ rw [Nat.add_comm, Nat.add_mul_div_right _ _ hn, Nat.div_eq_of_lt j.isLt, Nat.zero_add]
+ simp [pairAt, hd, Nat.mod_eq_of_lt j.isLt]
+
+/-- Number of records emitted among the first `t` candidate visits,
+starting with persistent index `k`. -/
+def emitted (old new : List ℕ) (k t : ℕ) : ℕ :=
+ ((List.range' k t).map (pairAt old new)).countP (fun p => (intersectFields p).isSome)
+
+private theorem emitted_succ (old new : List ℕ) (k t : ℕ) :
+ emitted old new k (t+1) =
+ (if (sliceAt old new k).length = 0 then 0 else 1) + emitted old new (k+1) t := by
+ simp only [emitted, List.range'_succ, List.map_cons, List.countP_cons, intersectFields, sliceAt]
+ split <;> simp [Nat.add_comm, *]
+
+theorem emitted_all (old new : List ℕ) :
+ emitted old new 0 (old.length * new.length) = (copyRecords old new).length := by
+ rw [emitted, copyRecords, List.length_filterMap_eq_countP, ← numbered_pairs]
+ congr 1
+ apply List.ext_getElem (by simp)
+ intro i hi hj
+ simp
+
+/-- The four arrays read by the pair visitor contain natural width and start
+coordinates. Array heads are in words 1–4 of the visitor's public data. -/
+structure Inputs {w : ℕ} (p : Fin 6 → Word w) (old new : List ℕ) (mem : Memory w) : Prop where
+ oldStart : ∀ i, i < old.length → (mem ((p 1).val + i)).val = (old.take i).sum
+ oldWidth : ∀ i (hi : i < old.length), (mem ((p 2).val + i)).val = old[i]
+ newStart : ∀ j, j < new.length → (mem ((p 3).val + j)).val = (new.take j).sum
+ newWidth : ∀ j (hj : j < new.length), (mem ((p 4).val + j)).val = new[j]
+
+/-- All five physical arrays fit their word addresses. Only the frame array
+is written during the pair pass. Input arrays may share other data. -/
+structure FrameSpace {w : ℕ} (p : Fin 6 → Word w) (m n : ℕ) : Prop where
+ targetCount : (p 0).val = n
+ cursorFit : m * n < 2^w
+ inputsFit : ∀ t : Fin 4, (p t.succ.castSucc).val + (if t.val < 2 then m else n) ≤ 2^w
+ framesFit : (p 5).val + 3 * (m*n) ≤ 2^w
+ apart : ∀ t : Fin 4, (p t.succ.castSucc).val + (if t.val < 2 then m else n) ≤ (p 5).val ∨
+ (p 5).val + 3*(m*n) ≤ (p t.succ.castSucc).val
+
+/-- Contents of all completed frames. The length word is overwritten even
+on the empty branch so arbitrary stale output cannot be read as a record. -/
+structure FramesAt {w : ℕ} (p : Fin 6 → Word w) (old new : List ℕ)
+ (initial mem : Memory w) (k : ℕ) : Prop where
+ inputs : Inputs p old new mem
+ lengths : ∀ a, a < k → (mem ((p 5).val + 3*a + 2)).val = (sliceAt old new a).length
+ offsets : ∀ a, a < k → 0 < (sliceAt old new a).length →
+ (mem ((p 5).val + 3*a)).val = (sliceAt old new a).sourceOffset ∧
+ (mem ((p 5).val + 3*a + 1)).val = (sliceAt old new a).targetOffset
+ outside : ∀ x, x < (p 5).val ∨ (p 5).val + 3*k ≤ x → mem x = initial x
+
+variable {w : ℕ}
+
+/-- Physical writes of a frame, using the ordinary natural offsets of a
+validated array. The two empty offsets can have arbitrary prior contents. -/
+def writeFrame (m : Memory w) (a : ℕ) (s : CopySlice) : Memory w := fun x =>
+ if x = a + 2 then Fin.ofNat _ s.length else if s.length = 0 then m x
+ else if x = a then Fin.ofNat _ s.sourceOffset else if x = a + 1 then Fin.ofNat _ s.targetOffset
+ else m x
+
+private theorem frame_outside (m : Memory w) (a : ℕ) (s : CopySlice) (x : ℕ)
+ (hx : x < a ∨ a + 3 ≤ x) : writeFrame m a s x = m x := by
+ simp [writeFrame, show x ≠ a by omega, show x ≠ a+1 by omega, show x ≠ a+2 by omega]
+
+private theorem field_bounds (ws : List ℕ) (i : ℕ) (hi : i < ws.length) :
+ (fieldAt ws i).start + (fieldAt ws i).width ≤ ws.sum := by
+ have h : fieldAt ws i ∈ fieldsFrom 0 0 ws := by
+ rw [fields_eq_ofFn]
+ exact List.mem_ofFn.mpr ⟨⟨i,hi⟩,rfl⟩
+ simpa using (fieldsFrom_bounds h).2.2.2
+
+private theorem indices_lt {m n k : ℕ} (h : k < m*n) :
+ k / n < m ∧ k % n < n := by
+ have hn : 0 < n := by by_contra! hn; rw [show n = 0 by omega, Nat.mul_zero] at h; omega
+ exact ⟨(Nat.div_lt_iff_lt_mul hn).mpr h, Nat.mod_lt k hn⟩
+
+private theorem pair_bounds (old new : List ℕ) (k : ℕ) (hk : k < old.length * new.length) :
+ let p := pairAt old new k
+ p.1.start + p.1.width ≤ old.sum ∧ p.2.start + p.2.width ≤ new.sum :=
+ ⟨field_bounds _ _ (indices_lt hk).1, field_bounds _ _ (indices_lt hk).2⟩
+
+private theorem slice_fits (old new : List ℕ) (k : ℕ) (hk : k < old.length * new.length)
+ (hs : old.sum < 2^w) (ht : new.sum < 2^w) :
+ let s := sliceAt old new k
+ s.sourceOffset < 2^w ∧ s.targetOffset < 2^w ∧ s.length < 2^w := by
+ have hb := pair_bounds old new k hk
+ dsimp only [sliceAt, copySlice]
+ dsimp only at hb
+ omega
+
+private theorem frame_step {old new : List ℕ} {p : Fin 6 → Word w} {initial mem : Memory w}
+ {k : ℕ} (reg : FrameSpace p old.length new.length) (hs : old.sum < 2^w)
+ (ht : new.sum < 2^w) (hk : k < old.length * new.length) (h : FramesAt p old new initial mem k) :
+ FramesAt p old new initial (writeFrame mem ((p 5).val + 3*k) (sliceAt old new k)) (k+1) := by
+ let a := (p 5).val + 3*k
+ let s := sliceAt old new k
+ let post := writeFrame mem a s
+ have sameInput (t : Fin 4) (i : ℕ) (hi : i < (if t.val < 2 then old.length else new.length)) :
+ post ((p t.succ.castSucc).val + i) = mem ((p t.succ.castSucc).val + i) := by
+ apply frame_outside
+ have := reg.apart t
+ dsimp only [a]
+ omega
+ obtain ⟨hf₀,hf₁,hf₂⟩ := slice_fits old new k hk hs ht
+ constructor
+ · constructor
+ · intro i hi; exact (congrArg Fin.val (sameInput 0 i hi)).trans (h.inputs.oldStart i hi)
+ · intro i hi; exact (congrArg Fin.val (sameInput 1 i hi)).trans (h.inputs.oldWidth i hi)
+ · intro i hi; exact (congrArg Fin.val (sameInput 2 i hi)).trans (h.inputs.newStart i hi)
+ · intro i hi; exact (congrArg Fin.val (sameInput 3 i hi)).trans (h.inputs.newWidth i hi)
+ · intro j hj
+ rcases Nat.lt_succ_iff_lt_or_eq.mp hj with hj | rfl
+ · rw [frame_outside _ _ _ _ (Or.inl (by omega)), h.lengths j hj]
+ · simp [writeFrame, Fin.ofNat, Nat.mod_eq_of_lt hf₂]
+ · intro j hj hp
+ rcases Nat.lt_succ_iff_lt_or_eq.mp hj with hj | rfl
+ · rw [frame_outside _ _ _ _ (Or.inl (by omega)), frame_outside _ _ _ _ (Or.inl (by omega))]
+ exact h.offsets j hj hp
+ · simp [writeFrame, hp.ne', Fin.ofNat, Nat.mod_eq_of_lt hf₀, Nat.mod_eq_of_lt hf₁]
+ · intro x hx
+ rw [frame_outside _ _ _ _ (by omega), h.outside x (by omega)]
+
+open SliceRAM.IndexedPair
+
+private theorem read_inputs {p : Fin 6 → Word w} {old new : List ℕ} {mem : Memory w}
+ (reg : FrameSpace p old.length new.length) (h : Inputs p old new mem)
+ (id : Word w) (hk : id.val < old.length * new.length) :
+ let f := pairAt old new id.val
+ (mem (p 1 + oldIndex p id).val).val = f.1.start ∧
+ (mem (p 2 + oldIndex p id).val).val = f.1.width ∧
+ (mem (p 3 + newIndex p id).val).val = f.2.start ∧
+ (mem (p 4 + newIndex p id).val).val = f.2.width := by
+ obtain ⟨hi,hj⟩ := indices_lt hk
+ have hd : (oldIndex p id).val = id.val / new.length := by
+ change (id.val / (p 0).val) % (2^w) = _
+ rw [reg.targetCount, Nat.mod_eq_of_lt ((Nat.div_le_self _ _).trans_lt id.isLt)]
+ have hm : (newIndex p id).val = id.val % new.length := by
+ change (id.val % (p 0).val) % (2^w) = _
+ rw [reg.targetCount, Nat.mod_eq_of_lt ((Nat.mod_le _ _).trans_lt id.isLt)]
+ have addr (t : Fin 4) (v : Word w)
+ (hv : v.val < (if t.val < 2 then old.length else new.length)) :
+ (p t.succ.castSucc + v).val = (p t.succ.castSucc).val + v.val := by
+ have := reg.inputsFit t
+ rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ dsimp only
+ have a₀ : (p 1 + oldIndex p id).val = (p 1).val + (oldIndex p id).val := addr 0 _ (hd ▸ hi)
+ have a₁ : (p 2 + oldIndex p id).val = (p 2).val + (oldIndex p id).val := addr 1 _ (hd ▸ hi)
+ have a₂ : (p 3 + newIndex p id).val = (p 3).val + (newIndex p id).val := addr 2 _ (hm ▸ hj)
+ have a₃ : (p 4 + newIndex p id).val = (p 4).val + (newIndex p id).val := addr 3 _ (hm ▸ hj)
+ rw [a₀, a₁, a₂, a₃]
+ simp [hd, hm, pairAt, fieldAt, hi, hj, h.oldStart _ hi, h.oldWidth _ hi, h.newStart _ hj, h.newWidth _ hj]
+
+private theorem after_indexed {p : Fin 6 → Word w} {old new : List ℕ}
+ (reg : FrameSpace p old.length new.length) (mem : Memory w) (id : Word w)
+ (hk : id.val < old.length * new.length) (s : CopySlice) :
+ after mem (report p id mem s).events = writeFrame mem ((p 5).val + 3*id.val) s := by
+ let a := (p 5).val + 3*id.val
+ have hf := reg.framesFit
+ have h1 : (1 : Word w).val = 1 := by rw [Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^w by omega)]
+ have hb : (base p id).val = a := base_val p id (by omega)
+ have hb₁ : (base p id+1).val = a+1 := by
+ rw [Fin.val_add, hb, h1, Nat.mod_eq_of_lt (by dsimp [a]; omega)]
+ have hb₂ : (base p id+1+1).val = a+2 := by
+ rw [Fin.val_add, hb₁, h1, Nat.mod_eq_of_lt (by dsimp [a]; omega)]
+ rw [report_after]
+ funext x
+ by_cases hz : s.length = 0 <;> by_cases h₀ : x = a <;> by_cases h₁ : x = a + 1 <;>
+ by_cases h₂ : x = a + 2 <;>
+ simp [writeFrame, writeMemory, hb, hb₁, hb₂, ← show a = (p 5).val + 3*id.val from rfl,
+ hz, h₀, h₁, h₂]
+
+/-- A contiguous segment of actual pair calls carries the linear pair cursor
+and writes every completed frame. The scan starts from arbitrary prior contents
+of its unused output slots. -/
+theorem frameSegment_run {p : Fin 6 → Word w} {old new : List ℕ}
+ (reg : FrameSpace p old.length new.length) (hs : old.sum < 2^w) (ht : new.sum < 2^w)
+ {initial mem : Memory w} {k : ℕ} (h : FramesAt p old new initial mem k)
+ (t : ℕ) (htot : k+t ≤ old.length * new.length) :
+ let M := table.instantiate w p
+ let idx := Fin.ofNat (2^w)
+ ∃ rs, runSegment M.program 38 (some (idx k)) mem (List.replicate t []) = some rs ∧
+ FramesAt p old new initial (after mem (eventLog rs)) (k+t) ∧
+ endState (some (idx k)) rs = some (idx (k+t)) ∧ rs.length = t ∧
+ (rs.map Report.probes).sum = 5*t + 2*emitted old new k t ∧
+ (rs.map fun r => r.events.length+1).sum = 34*t + 4*emitted old new k t := by
+ let idx := Fin.ofNat (2^w)
+ let M := table.instantiate w p
+ induction t generalizing k mem with
+ | zero => exact ⟨[],rfl,by simpa [after,eventLog] using h,rfl,rfl,by simp [emitted],by simp [emitted]⟩
+ | succ t ih =>
+ have hk : k < old.length * new.length := by omega
+ have hv : (idx k).val = k := Nat.mod_eq_of_lt (hk.trans reg.cursorFit)
+ have hn : idx k + 1 = idx (k+1) := by
+ apply Fin.ext
+ rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^w by have := reg.cursorFit; omega), hv]
+ rfl
+ obtain ⟨h₀,h₁,h₂,h₃⟩ := read_inputs reg h.inputs (idx k) (by simpa only [hv] using hk)
+ rw [hv] at h₀ h₁ h₂ h₃
+ have hb := pair_bounds old new k hk
+ dsimp only at hb
+ have hs' : slice p (idx k) mem = sliceAt old new k := by
+ simp only [slice, h₀, h₁, h₂, h₃, sliceAt]
+ have hvst := visit_native p (idx k) mem (by rw [h₀,h₁]; omega) (by rw [h₂,h₃]; omega)
+ rw [hs'] at hvst
+ let r := report p (idx k) mem (sliceAt old new k)
+ have hnext := frame_step reg hs ht hk h
+ have hm := after_indexed reg mem (idx k) (by simpa only [hv] using hk) (sliceAt old new k)
+ rw [hv] at hm
+ change after mem r.events = _ at hm
+ obtain ⟨rs,hr,hf,he,hlen,hcost,hinst⟩ := ih (hm ▸ hnext) (by omega)
+ have hresult : r.result = some (idx (k+1)) := congrArg some hn
+ refine ⟨r::rs,?_,?_,?_,by simp [hlen],?_,?_⟩
+ · change runSegment M.program 38 (some (idx k)) mem (List.replicate (t+1) []) = _
+ rw [List.replicate_succ, runSegment, hvst]
+ change (runSegment M.program 38 r.result (after mem r.events) (List.replicate t [])).map _ = _
+ rw [hresult,hr]; rfl
+ · have hl : after mem (eventLog (r :: rs)) = after (after mem r.events) (eventLog rs) := by
+ change List.foldl BurstRAM.update mem (r.events ++ eventLog rs) = _
+ rw [List.foldl_append]; rfl
+ simpa only [hl, show k+(t+1)=k+1+t by omega] using hf
+ · change endState r.result rs = _
+ rw [hresult, he, show k+1+t = k+(t+1) by omega]
+ · have hc := (report_cost p (idx k) mem (sliceAt old new k)).1
+ change r.probes = _ at hc
+ simp only [List.map_cons, List.sum_cons, hcost, hc, emitted_succ]
+ split <;> omega
+ · have hc := (report_cost p (idx k) mem (sliceAt old new k)).2
+ change r.events.length + 1 = _ at hc
+ simp only [List.map_cons, List.sum_cons, hinst, hc, emitted_succ]
+ split <;> omega
+
+open SliceRAM
+
+/-- First frame after the two totals, the incidence counts and the prefix arrays. -/
+def frameHead (B m n : ℕ) := B + 2 + 2*m + 2*n
+
+/-- Last exclusive workspace address. Each pair reserves three frame cells
+and one reference slot in each of the two endpoint directories. -/
+def stop (B m n : ℕ) := frameHead B m n + 5*(m*n)
+
+/-- Address bounds and separation of the slice workspace from both input width arrays. -/
+structure Workspace (oldBase newBase B : Word w) (m n : ℕ) : Prop where
+ fits : stop B.val m n < 2^w
+ oldFit : oldBase.val + m ≤ 2^w
+ newFit : newBase.val + n ≤ 2^w
+ oldApart : oldBase.val + m ≤ B.val ∨ stop B.val m n ≤ oldBase.val
+ newApart : newBase.val + n ≤ B.val ∨ stop B.val m n ≤ newBase.val
+
+private def pairNumbers (o t B m n : ℕ) : Fin 6 → ℕ :=
+ ![n, B+2+m+n, o, B+2+2*m+n, t, frameHead B m n]
+
+/-- Pair worker public data. -/
+def pairData (oldBase newBase B : Word w) (m n : ℕ) : Fin 6 → Word w :=
+ fun i => Fin.ofNat _ (pairNumbers oldBase.val newBase.val B.val m n i)
+
+private def adjNumbers (B m n : ℕ) : Fin 7 → ℕ :=
+ let a := frameHead B m n
+ ![n, m, a, B+2, a+3*(m*n), B+2+m, a+4*(m*n)]
+
+/-- Endpoint-directory worker public data. -/
+def adjacencyData (B : Word w) (m n : ℕ) : Fin 7 → Word w :=
+ fun i => Fin.ofNat _ (adjNumbers B.val m n i)
+
+variable {o t B : Word w} {m n : ℕ}
+
+private theorem pair_val (h : Workspace o t B m n) (i : Fin 6) :
+ (pairData o t B m n i).val = pairNumbers o.val t.val B.val m n i := by
+ apply Nat.mod_eq_of_lt
+ have hfit := h.fits
+ dsimp only [stop, frameHead] at hfit
+ fin_cases i <;> dsimp [pairNumbers,frameHead] <;> first | exact o.isLt | exact t.isLt | omega
+
+private theorem adj_val (h : Workspace o t B m n) (i : Fin 7) :
+ (adjacencyData B m n i).val = adjNumbers B.val m n i := by
+ apply Nat.mod_eq_of_lt
+ have hfit := h.fits
+ dsimp only [stop,frameHead] at hfit
+ fin_cases i <;> dsimp [adjNumbers,frameHead] <;> omega
+
+private theorem prepSpace (h : Workspace o t B m n) : PreparationRegions o t B m n := by
+ obtain ⟨hf,ho,ht,hao,hat⟩ := h
+ dsimp [stop,frameHead] at *
+ exact ⟨ho,ht,by omega,by omega,by omega⟩
+
+private theorem pairSpace (h : Workspace o t B m n) : FrameSpace (pairData o t B m n) m n := by
+ have hf := h.fits
+ have hao := h.oldApart
+ have hat := h.newApart
+ dsimp only [stop,frameHead] at hf hao hat
+ constructor
+ · exact pair_val h 0
+ · omega
+ · intro i
+ rw [pair_val h]
+ fin_cases i <;> dsimp [pairNumbers] <;> first | exact h.oldFit | exact h.newFit | omega
+ · rw [pair_val h]; dsimp [pairNumbers,frameHead]; omega
+ · intro i
+ simp only [pair_val h]
+ fin_cases i <;> dsimp [pairNumbers,frameHead] <;> omega
+
+private theorem directorySpace (h : Workspace o t B m n) : AdjRegions (adjacencyData B m n) := by
+ have hf := h.fits
+ dsimp only [stop,frameHead] at hf
+ constructor <;> simp only [oldBank,newBank,AdjBank.stop,adj_val h] <;>
+ dsimp [adjNumbers,frameHead] <;> (try rw [Nat.mul_comm n m]) <;> omega
+
+private theorem prepInputs {old new : List ℕ} {initial mem : Memory w}
+ (h : Workspace o t B old.length new.length) (hp : Prepared o t B old new initial mem) :
+ Inputs (pairData o t B old.length new.length) old new mem := by
+ constructor <;> intro i hi <;> rw [pair_val h]
+ · exact hp.oldStarts i hi
+ · exact hp.oldWidths i hi
+ · exact hp.newStarts i hi
+ · exact hp.newWidths i hi
+
+private theorem nonempty_eq_emitted (old new : List ℕ) (k t : ℕ) :
+ adjNonempty (fun j => (sliceAt old new j).length) k t = emitted old new k t := by
+ rw [adjNonempty, ← List.countP_eq_length_filter, emitted, List.countP_map]
+ congr 1
+ funext j
+ dsimp only [Function.comp_apply, intersectFields, sliceAt]
+ split <;> simp [*]
+
+/-- Reports from the five rows of the local descriptor schedule. -/
+structure Passes (w : ℕ) where
+ /-- Reports for zeroing the two totals and both endpoint count arrays. -/
+ clear : List (Report w)
+ /-- Reports for computing the starts of the old fields from their widths. -/
+ oldPrefix : List (Report w)
+ /-- Reports for computing the starts of the new fields from their widths. -/
+ newPrefix : List (Report w)
+ /-- Reports from testing the field pairs and storing their interval offsets and lengths. -/
+ frames : List (Report w)
+ /-- Reports from indexing nonempty pair frames in both endpoint directories. -/
+ directories : List (Report w)
+
+/-- Memory after clearing and computing both arrays of field starts. -/
+def Passes.prepared (rs : Passes w) (mem : Memory w) :=
+ preparationAfter mem rs.clear rs.oldPrefix rs.newPrefix
+
+/-- Memory after the pair scan writes its frames into the prepared workspace. -/
+def Passes.tested (rs : Passes w) (mem : Memory w) :=
+ after (rs.prepared mem) (eventLog rs.frames)
+
+/-- Memory after both endpoint directories have been populated from the tested frames. -/
+def Passes.result (rs : Passes w) (mem : Memory w) :=
+ after (rs.tested mem) (eventLog rs.directories)
+
+/-- Reports of all five sweeps in execution order. -/
+def Passes.all (rs : Passes w) :=
+ (rs.clear ++ rs.oldPrefix ++ rs.newPrefix) ++ rs.frames ++ rs.directories
+
+/-- The five reset-cursor segments of the fixed worker schedule, in chronological order. -/
+structure NativePasses (o t B : Word w) (m n : ℕ) (mem : Memory w) (rs : Passes w) : Prop where
+ preparation : PreparationRuns o t B m n mem rs.clear rs.oldPrefix rs.newPrefix
+ pairs : runSegment (table.instantiate w (pairData o t B m n)).program 38 (some 0)
+ (rs.prepared mem) (List.replicate (m*n) []) = some rs.frames
+ adjacency : runSegment (adjTemplate.instantiate w (adjacencyData B m n)).program 36 (some 0)
+ (rs.tested mem) (List.replicate (m*n) []) = some rs.directories
+
+/-- The final table stores the three words for each nonempty pair and its
+identifier in both compact incidence lists. Each list occupies the live prefix
+of its bounded row, in the order of the candidate scan. -/
+structure Stored (B : Word w) (old new : List ℕ) (initial mem : Memory w) : Prop where
+ oldStarts : ∀ i, i < old.length →
+ (mem (B.val+2+old.length+new.length+i)).val = (old.take i).sum
+ newStarts : ∀ j, j < new.length →
+ (mem (B.val+2+2*old.length+new.length+j)).val = (new.take j).sum
+ lengths : ∀ k, k < old.length*new.length →
+ (mem (frameHead B.val old.length new.length + 3*k + 2)).val = (sliceAt old new k).length
+ offsets : ∀ k, k < old.length*new.length → 0 < (sliceAt old new k).length →
+ (mem (frameHead B.val old.length new.length + 3*k)).val = (sliceAt old new k).sourceOffset ∧
+ (mem (frameHead B.val old.length new.length + 3*k+1)).val = (sliceAt old new k).targetOffset
+ oldRows : (oldBank (adjacencyData B old.length new.length)).Represents mem
+ (fun k => (sliceAt old new k).length) (· / new.length) (old.length*new.length)
+ newRows : (newBank (adjacencyData B old.length new.length)).Represents mem
+ (fun k => (sliceAt old new k).length) (· % new.length) (old.length*new.length)
+ outside : ∀ x, x < B.val ∨ stop B.val old.length new.length ≤ x → mem x = initial x
+
+/-- Following a reference in the live portion of an endpoint row. -/
+def References (bank : AdjBank w) (mem : Memory w) (owner id : Word w) : Prop :=
+ ∃ j < (mem (bank.count owner).val).val, mem ((bank.row owner).val + j) = id
+
+private theorem references_iff {bank : AdjBank w} {mem : Memory w} {len owner : ℕ → ℕ}
+ {k : ℕ} (h : bank.Represents mem len owner k) (fit : k ≤ 2^w)
+ (v id : Word w) (hv : v < bank.size) :
+ References bank mem v id ↔ id.val < k ∧ len id.val ≠ 0 ∧ owner id.val = v.val := by
+ let row := adjPrefix w len owner v.val k
+ obtain ⟨hcount, hslots⟩ := h v hv
+ change (mem (bank.count v).val).val = row.length at hcount
+ have inRow : References bank mem v id ↔ id ∈ row := by
+ constructor
+ · rintro ⟨j,hj,he⟩
+ have hpos : j < row.length := hcount ▸ hj
+ exact List.mem_iff_getElem.mpr ⟨j,hpos,(hslots ⟨j,hpos⟩).symm.trans he⟩
+ · intro hr
+ obtain ⟨j,hj,he⟩ := List.mem_iff_getElem.mp hr
+ exact ⟨j,hcount.symm ▸ hj,(hslots ⟨j,hj⟩).trans he⟩
+ rw [inRow]
+ simp only [row, adjPrefix, List.mem_map, List.mem_filter, List.mem_range, decide_eq_true_eq]
+ constructor
+ · rintro ⟨j,⟨hj,hz,hv'⟩,he⟩
+ have hj' : j = id.val := (Nat.mod_eq_of_lt (hj.trans_le fit)).symm.trans (congrArg Fin.val he)
+ exact hj' ▸ ⟨hj,hz,hv'⟩
+ · rintro ⟨hk,hz,hv'⟩
+ exact ⟨id.val, ⟨hk,hz,hv'⟩, Fin.ext (Nat.mod_eq_of_lt id.isLt)⟩
+
+/-- A source or target's physical row contains exactly the positive-length
+frames incident to that field. Dividing the returned ID by the target count
+recovers the source, and its remainder recovers the target. -/
+theorem Stored.references {old new : List ℕ} {initial mem : Memory w}
+ (space : Workspace o t B old.length new.length) (h : Stored B old new initial mem)
+ (i j id : Word w) (hi : i.val < old.length) (hj : j.val < new.length) :
+ let d := adjacencyData B old.length new.length
+ let live := id.val < old.length*new.length ∧ (sliceAt old new id.val).length ≠ 0
+ (References (oldBank d) mem i id ↔ live ∧ id.val / new.length = i.val) ∧
+ (References (newBank d) mem j id ↔ live ∧ id.val % new.length = j.val) := by
+ let d := adjacencyData B old.length new.length
+ have hi' : i < (oldBank d).size := by
+ change i.val < (d 1).val
+ rw [adj_val space]; exact hi
+ have hj' : j < (newBank d).size := by
+ change j.val < (d 0).val
+ rw [adj_val space]; exact hj
+ have fit := (pairSpace space).cursorFit.le
+ exact ⟨(references_iff h.oldRows fit i id hi').trans and_assoc.symm,
+ (references_iff h.newRows fit j id hj').trans and_assoc.symm⟩
+
+private theorem directory_outside {p : Fin 7 → Word w} (hp : p = adjacencyData B m n)
+ (space : Workspace o t B m n) (x : ℕ) (hx : x < B.val ∨ stop B.val m n ≤ x) :
+ ¬ (oldBank p).Inside x ∧ ¬ (newBank p).Inside x := by
+ subst p
+ simp only [oldBank, newBank, AdjBank.Inside, AdjBank.stop, adj_val space]
+ dsimp [adjNumbers,frameHead]
+ dsimp [stop,frameHead] at hx
+ rw [Nat.mul_comm n m]
+ omega
+
+private theorem directory_skips_starts (space : Workspace o t B m n) (x : ℕ)
+ (hl : B.val+2+m+n ≤ x) (hu : x < frameHead B.val m n) :
+ ¬ (oldBank (adjacencyData B m n)).Inside x ∧ ¬ (newBank (adjacencyData B m n)).Inside x := by
+ simp only [oldBank,newBank,AdjBank.Inside,AdjBank.stop,adj_val space]
+ dsimp [adjNumbers,frameHead]
+ dsimp [frameHead] at hu
+ omega
+
+/-- Build the interval records and both of their endpoint directories
+directly from the two width arrays. All scratch words may initially be stale.
+The exact totals include address preparation, the intersection tests, and the
+writes that compact both endpoint lists. -/
+theorem build (old new : List ℕ) (o t B : Word w) (mem : Memory w)
+ (space : Workspace o t B old.length new.length)
+ (ho : old.sum < 2^w) (hn : new.sum < 2^w)
+ (oldWidths : ∀ i (hi : i < old.length), (mem (o.val+i)).val = old[i])
+ (newWidths : ∀ j (hj : j < new.length), (mem (t.val+j)).val = new[j]) :
+ let m := old.length
+ let n := new.length
+ let k := (copyRecords old new).length
+ ∃ rs : Passes w, NativePasses o t B m n mem rs ∧ Stored B old new mem (rs.result mem) ∧
+ rs.all.length = 2 + 2*(m+n) + 2*(m*n) ∧
+ (rs.all.map Report.probes).sum = 2 + 5*(m+n) + 6*(m*n) + 8*k ∧
+ (rs.all.map fun r => r.events.length + 1).sum = 16 + 22*(m+n) + 46*(m*n) + 28*k := by
+ let m := old.length
+ let n := new.length
+ let p := pairData o t B m n
+ let q := adjacencyData B m n
+ let a := frameHead B.val m n
+ let len := fun k => (sliceAt old new k).length
+ have hp₅ : (p 5).val = a := pair_val space 5
+ have hq₀ : (q 0).val = n := adj_val space 0
+ have hq₁ : (q 1).val = m := adj_val space 1
+ have hq₂ : (q 2).val = a := adj_val space 2
+ have hq₃ : (q 3).val = B.val+2 := adj_val space 3
+ have hq₅ : (q 5).val = B.val+2+m := adj_val space 5
+ obtain ⟨clear, oldRun, newRun, hpre, hd⟩ :=
+ preparation_run (prepSpace space) ho hn oldWidths newWidths
+ let pre := preparationAfter mem clear oldRun newRun
+ have h0 : FramesAt p old new pre pre 0 :=
+ ⟨prepInputs space hd, fun _ hj => by omega, fun _ hj => by omega, fun _ _ => rfl⟩
+ obtain ⟨ps,hps,hf,_,hplen,hpc,hpi⟩ := frameSegment_run (pairSpace space) ho hn h0 (m*n) (by simp [m,n])
+ simp only [Nat.zero_add] at hf
+ let fr := after pre (eventLog ps)
+ change FramesAt p old new pre fr (m*n) at hf
+ have lengths (k : ℕ) (hk : k < (q 1).val*(q 0).val) :
+ (fr ((q 2).val + 3*k+2)).val = len k := by
+ rw [hq₁,hq₀] at hk
+ rw [hq₂, ← hp₅]
+ exact hf.lengths k hk
+ have hfit := space.fits
+ change a + 5*(m*n) < 2^w at hfit
+ have oldZero (i : Word w) (hi : i < q 1) : fr (adjOldCount q i).val = 0 := by
+ have hv : i.val < m := hq₁ ▸ Fin.lt_def.mp hi
+ have haddr : (adjOldCount q i).val = B.val + 2 + i.val := by
+ rw [adjOldCount, Fin.val_add, hq₃, Nat.mod_eq_of_lt (by dsimp [a,frameHead] at hfit; omega)]
+ rw [haddr, hf.outside _ (Or.inl (by rw [hp₅]; dsimp [a,frameHead]; omega))]
+ exact hd.oldCounts i.val hv
+ have newZero (j : Word w) (hj : j < q 0) : fr (adjNewCount q j).val = 0 := by
+ have hv : j.val < n := hq₀ ▸ Fin.lt_def.mp hj
+ have haddr : (adjNewCount q j).val = B.val+2+m+j.val := by
+ rw [adjNewCount, Fin.val_add, hq₅, Nat.mod_eq_of_lt (by dsimp [a,frameHead] at hfit; omega)]
+ rw [haddr, hf.outside _ (Or.inl (by rw [hp₅]; dsimp [a,frameHead]; omega))]
+ exact hd.newCounts j.val hv
+ have sq := directorySpace space
+ obtain ⟨ds,hds,hdir,_,hdlen,hdc,hdi⟩ := adjPass_run sq lengths oldZero newZero
+ rw [hq₁,hq₀] at hds hdir hdlen hdc hdi
+ let post := after fr (eventLog ds)
+ change AdjAt q len fr post (m*n) at hdir
+ have preserve (x : ℕ) (hl : a ≤ x) (hu : x < a+3*(m*n)) : post x = fr x :=
+ hdir.frame_eq sq (hq₂ ▸ hl) (by rw [hq₁,hq₀,hq₂]; exact hu)
+ let rs : Passes w := ⟨clear,oldRun,newRun,ps,ds⟩
+ refine ⟨rs, ⟨hpre,hps,hds⟩, ?_, ?_, ?_, ?_⟩
+ · have sameStart (x : ℕ) (hl : B.val+2+m+n ≤ x) (hu : x < a) : post x = pre x := by
+ obtain ⟨hox,hnx⟩ := directory_skips_starts space x hl hu
+ exact (hdir.outside x hox hnx).trans (hf.outside x (Or.inl (hp₅ ▸ hu)))
+ constructor
+ · intro i hi
+ change i < m at hi
+ change (post (B.val+2+m+n+i)).val = _
+ rw [sameStart _ (by omega) (by dsimp [a,frameHead]; omega)]
+ exact hd.oldStarts i hi
+ · intro j hj
+ change j < n at hj
+ change (post (B.val+2+2*m+n+j)).val = _
+ rw [sameStart _ (by omega) (by dsimp [a,frameHead]; omega)]
+ exact hd.newStarts j hj
+ · intro k hk
+ change k < m*n at hk
+ change (post (a+3*k+2)).val = _
+ rw [preserve _ (by omega) (by omega), ← hp₅]
+ exact hf.lengths k hk
+ · intro k hk hpos
+ change k < m*n at hk
+ change (post (a+3*k)).val = _ ∧ (post (a+3*k+1)).val = _
+ rw [preserve _ (by omega) (by omega), preserve _ (by omega) (by omega), ← hp₅]
+ exact hf.offsets k hk hpos
+ · have h := hdir.oldRows
+ rw [hq₀] at h
+ exact h
+ · have h := hdir.newRows
+ rw [hq₀] at h
+ exact h
+ · intro x hx
+ obtain ⟨hox,hnx⟩ := directory_outside (p := q) rfl space x hx
+ change post x = mem x
+ change x < B.val ∨ a + 5*(m*n) ≤ x at hx
+ rw [hdir.outside x hox hnx, hf.outside x (by rw [hp₅]; dsimp [a,frameHead] at *; omega)]
+ exact hd.outside x (by dsimp [a,frameHead] at hx; omega)
+ · have hc := hpre.clearLength
+ have hh := hpre.oldLength
+ have hj := hpre.newLength
+ simp only [rs, Passes.all, List.length_append]
+ dsimp only [m,n] at *
+ omega
+ · rw [adjCost_eq_length_add_probes] at hdc
+ have hk : adjNonempty len 0 (m*n) = (copyRecords old new).length :=
+ (nonempty_eq_emitted old new 0 (m*n)).trans (emitted_all old new)
+ rw [hk] at hdc
+ rw [show emitted old new 0 (m*n) = _ from emitted_all old new] at hpc
+ change (((clear ++ oldRun ++ newRun) ++ ps ++ ds).map Report.probes).sum = _
+ rw [List.map_append, List.sum_append, List.map_append, List.sum_append, hpre.probes]
+ dsimp only [m,n] at *
+ omega
+ · have hk : adjNonempty len 0 (m*n) = (copyRecords old new).length :=
+ (nonempty_eq_emitted old new 0 (m*n)).trans (emitted_all old new)
+ rw [hk] at hdi
+ rw [show emitted old new 0 (m*n) = _ from emitted_all old new] at hpi
+ change (((clear ++ oldRun ++ newRun) ++ ps ++ ds).map fun r => r.events.length+1).sum = _
+ rw [List.map_append, List.sum_append, List.map_append, List.sum_append, hpre.instructions]
+ dsimp only [m,n] at *
+ omega
+
+end CompressorRecords.SliceSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotAddresses.lean b/lean/OAI/Computability/VPVNP/CompressorSlotAddresses.lean
new file mode 100644
index 0000000000..629f7e298c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotAddresses.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.CompressorRecordSlots
+
+/-!
+# Scanning the address space for surviving slot records
+
+The absolute arc record uses a mixed-radix word. Every address can be decoded
+locally into an old arc, a role edge, a subdivision, and an absolute lane,
+or into a dummy site and dummy number. Only thick–thick old arcs and subdivision
+numbers outside their type's range leave holes in this space.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.Slots
+
+open Compression Compression.PackingData Compression.SurvivingSlots
+
+variable {V H Tag L : Type*} {d c N J nL : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL) (pad : ℕ)
+
+/-- Identifier of a surviving arc, either a role edge and subdivision of a motif or a dummy
+slot at a packed site. -/
+abbrev ActualId := Id P.Motif subdiv ⊕ Site V Tag L × Fin pad
+
+/-- Size of the address space for surviving slot records, including unused genuine candidate
+addresses and all dummy slots. -/
+abbrev RecordCount (N J nL d c pad : ℕ) (subdiv : Fin 4 → ℕ) :=
+ keyCount N J d c subdiv * nL + (N * (J * nL)) * pad
+
+private abbrev Candidate (V H Tag L : Type*) (d c pad m : ℕ) :=
+ ((Fin 4 × ((V × Tag × Fin d × BitWord c × H) × Fin m)) × L) ⊕ Site V Tag L × Fin pad
+
+private def pairCode {A B : Type*} {a b : ℕ} (f : A ≃ Fin a) (g : B ≃ Fin b) : A × B ≃ Fin (a * b) :=
+ (f.prodCongr g).trans finProdFinEquiv
+
+private def candidateIndex : Candidate V H Tag L d c pad (∑ t, subdiv t) ≃
+ Fin (RecordCount N J nL d c pad subdiv) :=
+ let old := pairCode vertices (pairCode tags (pairCode (Equiv.refl (Fin d))
+ (pairCode (bitWordFinEquiv c) P.slotLabel)))
+ let key := pairCode (Equiv.refl (Fin 4)) (pairCode old (Equiv.refl (Fin (∑ t, subdiv t))))
+ let site := pairCode vertices (pairCode tags lanes)
+ ((pairCode key lanes).sumCongr (pairCode site (Equiv.refl (Fin pad)))).trans finSumFinEquiv
+
+private def toCandidate : ActualId P subdiv pad → Candidate V H Tag L d c pad (∑ t, subdiv t)
+ | .inr x => .inr x
+ | .inl ⟨t, m, j⟩ =>
+ let a := m.val
+ let h : subdiv t ≤ ∑ t, subdiv t :=
+ Finset.single_le_sum (fun t _ ↦ Nat.zero_le (subdiv t)) (Finset.mem_univ _)
+ .inl ((t, ((a.1.1.1, a.1.1.2.1, a.1.2, a.2), j.castLE h)), P.sourceLane m)
+
+private def fromCandidate : Candidate V H Tag L d c pad (∑ t, subdiv t) → Option (ActualId P subdiv pad)
+ | .inr x => some (.inr x)
+ | .inl ((t, ((v, tag, slot, bits, h), j)), g) =>
+ let a : Arc V H Tag L d c := (((v,tag,g),slot),bits,h)
+ if hj : j.val < subdiv t then
+ if hm : ¬ (P.thick (sourcePosition a) ∧ P.thick (sourcePosition (P.actual a))) then
+ some (.inl ⟨t, ⟨a, hm⟩, ⟨j.val, hj⟩⟩)
+ else none
+ else none
+
+private theorem from_to (e : ActualId P subdiv pad) :
+ fromCandidate P subdiv pad (toCandidate P subdiv pad e) = some e := by
+ rcases e with ⟨t,⟨⟨⟨⟨v, tag, g⟩, slot⟩, bits,h⟩, hm⟩, j⟩ | x
+ · have hg : P.sourceLane ⟨(((v,tag,g),slot),bits,h), hm⟩ = g := rfl
+ simp only [toCandidate, fromCandidate, hg, Fin.val_castLE, dite_eq_left j.isLt, dite_eq_left hm]
+ · rfl
+
+private theorem to_from {x : Candidate V H Tag L d c pad (∑ t, subdiv t)} {e : ActualId P subdiv pad}
+ (h : fromCandidate P subdiv pad x = some e) : toCandidate P subdiv pad e = x := by
+ rcases x with ⟨⟨t,⟨⟨v, tag, slot, bits,h'⟩, j⟩⟩, g⟩ | x
+ · by_cases hj : j.val < subdiv t
+ · let a : Arc V H Tag L d c := (((v, tag, g), slot), bits, h')
+ by_cases hm : ¬ (P.thick (sourcePosition a) ∧ P.thick (sourcePosition (P.actual a)))
+ · dsimp only [a] at hm
+ simp only [fromCandidate, dite_eq_left hj, dite_eq_left hm, Option.some.injEq] at h
+ rw [← h]; rfl
+ · dsimp only [a] at hm
+ simp only [fromCandidate, dite_eq_left hj, dite_eq_right hm, reduceCtorEq] at h
+ · simp only [fromCandidate, dite_eq_right hj, reduceCtorEq] at h
+ · cases h; rfl
+
+/-- Random-access decode of one numeric arc address. -/
+def decodeArc (a : Fin (RecordCount N J nL d c pad subdiv)) : Option (ActualId P subdiv pad) :=
+ fromCandidate P subdiv pad ((candidateIndex P subdiv vertices tags lanes pad).symm a)
+
+private theorem candidateIndex_actual (e : ActualId P subdiv pad) :
+ candidateIndex P subdiv vertices tags lanes pad (toCandidate P subdiv pad e) =
+ arcAddress P subdiv vertices tags lanes pad e := by
+ rcases e with ⟨t, m, j⟩ | x <;> rfl
+
+/-- Scanning numeric addresses visits every genuine or dummy arc exactly once. -/
+theorem decodeArc_eq_some (a : Fin (RecordCount N J nL d c pad subdiv)) (e : ActualId P subdiv pad) :
+ decodeArc P subdiv vertices tags lanes pad a = some e ↔ arcAddress P subdiv vertices tags lanes pad e = a := by
+ let f := candidateIndex P subdiv vertices tags lanes pad
+ rw [← candidateIndex_actual]
+ change fromCandidate P subdiv pad (f.symm a) = some e ↔ f (toCandidate P subdiv pad e) = a
+ constructor
+ · intro h; rw [to_from P subdiv pad h, f.apply_symm_apply]
+ · intro h; rw [← h, f.symm_apply_apply, from_to]
+
+/-- The high-order component of a genuine arc address is the relative key,
+and the low-order component is the absolute lane of its original CD arc. -/
+theorem address_genuine_val (i : Id P.Motif subdiv) :
+ (arcAddress P subdiv vertices tags lanes pad (.inl i)).val =
+ (lanes (P.sourceLane i.2.1)).val + nL * (relativeKey P subdiv vertices tags i).val := rfl
+
+/-- Taking the quotient of the absolute genuine record address recovers its
+relative integer key directly. -/
+theorem address_div_lane (i : Id P.Motif subdiv) :
+ (arcAddress P subdiv vertices tags lanes pad (.inl i)).val / nL =
+ (relativeKey P subdiv vertices tags i).val := by
+ rw [address_genuine_val, Nat.add_mul_div_left _ _ (by have := (lanes (P.sourceLane i.2.1)).isLt; omega),
+ Nat.div_eq_of_lt (lanes (P.sourceLane i.2.1)).isLt, Nat.zero_add]
+
+end CompressorRecords.Slots
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotBaseFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorSlotBaseFootprint.lean
new file mode 100644
index 0000000000..5577b373ea
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotBaseFootprint.lean
@@ -0,0 +1,180 @@
+import OAI.Computability.VPVNP.CompressorSlotLevelRun
+import OAI.Computability.VPVNP.CompressorRefreshStageFrame
+
+/-!
+# External addresses of the lane-zero base matching scan
+
+Each base arc uses the real outgoing row to locate the adjacent incoming
+field in the inverse table. Both lookups precede the output columns, so
+the same sorted endpoint tables remain valid on every visit. The native
+reports read within the row and inverse tables and write within the target
+and displacement columns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotLevel
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport
+open Compression Compression.PackingData Compression.SurvivingSlots Slots SlotSchedule
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The sorted endpoint rows and inverse field directory. -/
+def BaseReadRegion (s : Shape) (h : Heads) (x : ℕ) : Prop :=
+ rowsHead s h ≤ x ∧ x < targetsHead s h
+
+/-- The target and displacement columns written by the base matching scan. -/
+def BaseWriteRegion (s : Shape) (h : Heads) (x : ℕ) : Prop :=
+ targetsHead s h ≤ x ∧ x < stopAddress s h
+
+private theorem write_row (s : Shape) (h : Heads) (fit : stopAddress s h < 2^w)
+ (m : Memory w) {j : ℕ} (hj : j < baseArcs s) :
+ Writes (BaseWriteRegion s h) (SlotBaseScan.events (bank s h w .baseMatching) m (j : Word w)) := by
+ let q := bank s h w .baseMatching
+ have htgt : targetsHead s h + baseArcs s = shiftsHead s h := rfl
+ have hsh : shiftsHead s h + baseArcs s = stopAddress s h := rfl
+ have q4 : (q 4).val = targetsHead s h := Nat.mod_eq_of_lt (by omega : targetsHead s h < 2^w)
+ have q5 : (q 5).val = shiftsHead s h := Nat.mod_eq_of_lt (by omega : shiftsHead s h < 2^w)
+ have hj' : (j : Word w).val = j := Nat.mod_eq_of_lt (by omega)
+ intro a v ha
+ change Event.write a v ∈ SlotBaseScan.events q m (j : Word w) at ha
+ simp [SlotBaseScan.events] at ha
+ rcases ha with ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> unfold BaseWriteRegion
+ · rw [Fin.val_add,q4,hj',Nat.mod_eq_of_lt (by omega)]
+ omega
+ · rw [Fin.val_add,q5,hj',Nat.mod_eq_of_lt (by omega)]
+ omega
+
+/-- Lift read bounds on a single visit to its full segment. All earlier
+writes are above the two input tables. -/
+private theorem scan_regions (s : Shape) (h : Heads) (m : Memory w) (rs : List (Report w))
+ (fit : stopAddress s h < 2^w) (readable : ℕ → Prop)
+ (rd : ∀ j < baseArcs s, ∀ curr : Memory w, Agree (BaseReadRegion s h) m curr →
+ Reads readable (SlotBaseScan.events (bank s h w .baseMatching) curr (j : Word w)))
+ (run : runSegment ((template SlotBaseScan.code 0).instantiate w (bank s h w .baseMatching)).program
+ 33 (some 0) m (List.replicate (baseArcs s) []) = some rs) :
+ StageFrame.Scanned 0 (baseArcs s) rs ∧ Reads readable (eventLog rs) ∧
+ Writes (BaseWriteRegion s h) (eventLog rs) := by
+ let q := bank s h w .baseMatching
+ let P := ((template SlotBaseScan.code 0).instantiate w q).program
+ have step (j : ℕ) (_ : 0 ≤ j) (hj : j < baseArcs s) (curr : Memory w)
+ (agree : Agree (BaseReadRegion s h) m curr) :
+ Agree (BaseReadRegion s h) m (after curr (SlotBaseScan.events q curr (j : Word w))) ∧
+ Reads readable (SlotBaseScan.events q curr (j : Word w)) ∧
+ Writes (BaseWriteRegion s h) (SlotBaseScan.events q curr (j : Word w)) := by
+ have wr := write_row s h fit curr hj
+ refine ⟨fun x hx ↦ (agree x hx).trans (after_outside curr wr ?_).symm, rd j hj curr agree, wr⟩
+ exact fun hw ↦ hx.2.not_ge hw.1
+ have hs := StageFrame.scan P 33 0 (baseArcs s) (fun _ ↦ Agree (BaseReadRegion s h) m)
+ (SlotBaseScan.events q) readable (BaseWriteRegion s h) (fun j _ _ curr ↦ SlotBaseScan.native q curr _)
+ step (Nat.zero_le _) m rs (fun _ _ ↦ rfl) (by simpa using run)
+ exact ⟨hs.1, hs.2.2⟩
+
+variable {V H Tag L : Type*} {d c N J nL degree : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] [Module (ZMod 2) Tag]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- In the memory left by scatter, the sorted source row contains the field of
+the lane-zero outgoing end. Its successor is the incoming field of the same
+arc. These two fitting addresses account for every external read of the pass. -/
+theorem base_footprint (layout : Bool) (h : Heads) (hc : 2 ≤ c)
+ (hφ : P.slots.ValidTagOffsets P.tagShift P.offset) (hd : survivingDegree d c subdiv ≤ degree)
+ (hJ : 1 < J) (hlane : (lanes 0).val = 0) (hw : 2 < 2^w)
+ (hdw : degree < 2^w) (hlw : nL < 2^w) (m : Memory w) (rs : List (Report w)) :
+ let s : Shape := ⟨N,J,nL,d,c,subdiv,degree⟩
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad s)
+ let hD := fun b ↦ (slotDirectory_degree P subdiv vertices tags lanes hc layout b).trans (Nat.add_sub_of_le hd)
+ let q := bank s h w .baseMatching
+ stopAddress s h < 2^w → Tables D degree (rowsHead s h) (inverseHead s h) hD m →
+ runSegment ((template SlotBaseScan.code 0).instantiate w q).program 33
+ (some 0) m (List.replicate (baseArcs s) []) = some rs →
+ StageFrame.Scanned 0 (baseArcs s) rs ∧ Reads (BaseReadRegion s h) (eventLog rs) ∧
+ Writes (BaseWriteRegion s h) (eventLog rs) := by
+ intro s D hD q fit tab run
+ apply scan_regions s h m rs fit _ _ run
+ intro j hj curr agree
+ have rowCap : rowsHead s h + owners s * degree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right degree (Nat.le_add_right (owners s) (fields s))) _
+ have hf : inverseHead s h + fields s = targetsHead s h := rfl
+ have ht : targetsHead s h + baseArcs s = shiftsHead s h := rfl
+ have hs : shiftsHead s h + baseArcs s = stopAddress s h := rfl
+ let e := (baseIndex vertices tags (degree := degree)).symm ⟨j,hj⟩
+ have he : (baseIndex vertices tags e).val = j :=
+ congrArg Fin.val ((baseIndex vertices tags).apply_symm_apply ⟨j,hj⟩)
+ have hb := base_lookup P subdiv vertices tags lanes hc hφ layout hd hJ hlane m e
+ (by change fields s ≤ 2^w; omega) (by change owners s * degree ≤ 2^w; omega) tab
+ rw [he] at hb
+ let source := laneZeroRow degree nL j
+ have hsource : source < owners s * degree := hb.1
+ have hread : BaseReadRegion s h (rowsHead s h + source) := by
+ unfold BaseReadRegion; omega
+ have hfield : (curr (rowsHead s h + source)).val + 1 < fields s := by
+ rw [← agree _ hread]
+ exact hb.2.1
+ have q0 : (q 0).val = degree := Nat.mod_eq_of_lt hdw
+ have q1 : (q 1).val = nL := Nat.mod_eq_of_lt hlw
+ have q2 : (q 2).val = rowsHead s h := Nat.mod_eq_of_lt (by omega : rowsHead s h < 2^w)
+ have q3 : (q 3).val = inverseHead s h := Nat.mod_eq_of_lt (by omega : inverseHead s h < 2^w)
+ have ji : (j : Word w).val = j := Nat.mod_eq_of_lt (by omega)
+ have addrs := SlotBaseScan.read_addresses q curr (j : Word w) hw
+ (by rw [q0,q1,q2,ji]; change rowsHead s h + source < 2^w; omega)
+ (by dsimp only; rw [q0,q1,q2,q3,ji]; change inverseHead s h + ((curr (rowsHead s h + source)).val+1) < 2^w; omega)
+ dsimp only at addrs
+ rw [q0,q1,q2,q3,ji] at addrs
+ change (SlotBaseScan.rowAddr q (j : Word w)).val = rowsHead s h + source ∧
+ (SlotBaseScan.invAddr q curr (j : Word w)).val =
+ inverseHead s h + ((curr (rowsHead s h + source)).val+1) at addrs
+ intro a v ha
+ change Event.read a v ∈ SlotBaseScan.events q curr (j : Word w) at ha
+ simp [SlotBaseScan.events] at ha
+ rcases ha with ⟨rfl,_⟩ | ⟨rfl,_⟩
+ · rwa [addrs.1]
+ · rw [addrs.2]
+ unfold BaseReadRegion
+ omega
+
+/-- The native reports and final tables supplied by `run_selected` suffice:
+the base pass writes only above the scatter tables, so the final table
+readback also holds at entry to this pass. -/
+theorem selected_base_footprint (layout : Bool) (h : Heads) (hc : 2 ≤ c)
+ (hφ : P.slots.ValidTagOffsets P.tagShift P.offset) (hd : survivingDegree d c subdiv ≤ degree)
+ (hJ : 1 < J) (hlane : (lanes 0).val = 0) (hw : 2 < 2^w)
+ (hdw : degree < 2^w) (hlw : nL < 2^w) (mem : Memory w) (r : Reports w) :
+ let s : Shape := ⟨N,J,nL,d,c,subdiv,degree⟩
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad s)
+ let hD := fun b ↦ (slotDirectory_degree P subdiv vertices tags lanes hc layout b).trans (Nat.add_sub_of_le hd)
+ stopAddress s h < 2^w → r.Native s h mem →
+ Tables D degree (rowsHead s h) (inverseHead s h) hD (r.final mem) →
+ StageFrame.Scanned 0 (baseArcs s) r.bases ∧ Reads (BaseReadRegion s h) (eventLog r.bases) ∧
+ Writes (BaseWriteRegion s h) (eventLog r.bases) := by
+ intro s D hD fit native tab
+ let m := after (after (after (after mem (eventLog r.genuine)) (eventLog r.dummy)) (eventLog r.append))
+ (eventLog r.scatter)
+ have run := native.2.2.2.2
+ have wr := (scan_regions s h m r.bases fit (fun _ ↦ True) (fun _ _ _ _ _ _ _ ↦ trivial) run).2.2
+ have same (x : ℕ) (hx : x < targetsHead s h) : r.final mem x = m x :=
+ after_outside m wr (fun hw ↦ hx.not_ge hw.1)
+ apply base_footprint P subdiv vertices tags lanes layout h hc hφ hd hJ hlane hw hdw hlw m r.bases fit _ run
+ have rowCap : rowsHead s h + owners s * degree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right degree (Nat.le_add_right (owners s) (fields s))) _
+ have hf : inverseHead s h + fields s = targetsHead s h := rfl
+ constructor
+ · intro e
+ have he : (sortedFields D degree hD e).val < owners s * degree := (sortedFields D degree hD e).isLt
+ exact (same (rowsHead s h + (sortedFields D degree hD e).val) (by omega)).symm.trans (tab.bySlot e)
+ · intro e
+ have he : (D.address e).val < fields s := (D.address e).isLt
+ exact (same (inverseHead s h + (D.address e).val) (by omega)).symm.trans (tab.byField e)
+
+end CompressorRecords.SlotLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotBaseLookup.lean b/lean/OAI/Computability/VPVNP/CompressorSlotBaseLookup.lean
new file mode 100644
index 0000000000..44e0e17d1d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotBaseLookup.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.CompressorSlotNetwork
+
+/-!
+# Extracting the base target and lane displacement from the endpoint arrays
+
+The packed graph is a lift. At source lane zero the destination lane is the
+base arc displacement. Unpacking the destination rectangular slot therefore
+recovers both base-table words needed by the next substep, for real and dummy
+arcs alike.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotSchedule
+
+open Compression Compression.PackingData Compression.SurvivingSlots Slots BurstRAM
+
+variable {V H Tag L : Type*} {d c N J nL pad : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- The actual arc at a given source-role lane over the padded base ID. -/
+def atLane (layout : Bool) (z : PaddedId (V × Tag) (Id P.BaseMotif subdiv) pad) (g : L) :
+ ActualId P subdiv pad :=
+ match z with
+ | .inl a => .inl ((P.survivingLaneEquiv layout subdiv).symm (a,g))
+ | .inr (b,j) => .inr ((b.1,b.2,g),j)
+
+theorem baseId_atLane (layout : Bool) (z : PaddedId (V × Tag) (Id P.BaseMotif subdiv) pad) (g : L) :
+ paddedBaseId P subdiv (atLane P subdiv layout z g) = z := by
+ cases z with
+ | inl a =>
+ let e := P.survivingLaneEquiv layout subdiv
+ have hb (i : Id P.Motif subdiv) : (e i).1 = baseId P subdiv i := by cases i; rfl
+ change Sum.inl (baseId P subdiv (e.symm (a,g))) = _
+ rw [← hb, e.apply_symm_apply]
+ | inr p => rfl
+
+theorem endpoints_atLane (layout : Bool) (z : PaddedId (V × Tag) (Id P.BaseMotif subdiv) pad) (g : L) :
+ let i := atLane P subdiv layout z g
+ let src := paddedSource (endpoint (P.roleBase layout) (sourceRole layout)) z
+ let dst := paddedTarget (endpoint (P.roleBase layout) (targetRole layout)) (cycleTags tags) z
+ let shift := paddedShift (P.roleDisplacement layout (sourceRole layout) (targetRole layout)) z
+ actualEnd P subdiv tags layout false i = (src.1,src.2,g) ∧
+ actualEnd P subdiv tags layout true i = (dst.1,dst.2,g+shift) := by
+ cases z with
+ | inl a => exact P.survivingLane_endpoints layout subdiv a g
+ | inr p => exact ⟨rfl, by change (_, _, g) = (_, _, g+0); rw [add_zero]; rfl⟩
+
+/-- Numeric order of the next graph's packed bases and their outgoing slots. -/
+def baseIndex {degree : ℕ} : (V × Tag) × Fin degree ≃ Fin ((N*J)*degree) :=
+ ((((vertices.prodCongr tags).trans finProdFinEquiv).prodCongr (Equiv.refl _))).trans finProdFinEquiv
+
+private theorem divLow {n : ℕ} (x : Fin n) (h : ℕ) : (x.val+n*h)/n = h := by
+ rw [Nat.add_mul_div_left _ _ ((Nat.zero_le x.val).trans_lt x.isLt), Nat.div_eq_of_lt x.isLt, Nat.zero_add]
+
+private theorem modLow {n : ℕ} (x : Fin n) (h : ℕ) : (x.val+n*h)%n = x.val := by
+ simp [Nat.mod_eq_of_lt x.isLt]
+
+/-- Linear index of a packed base vertex, with its tag index as the low digit. -/
+def packedCode (b : V × Tag) : Fin (N*J) := finProdFinEquiv (vertices b.1, tags b.2)
+
+omit [AddCommGroup Tag] [AddCommGroup L] in
+theorem site_val (b : V × Tag) (g : L) : (siteIndex vertices tags lanes (b.1,b.2,g)).val =
+ (lanes g).val + nL*(packedCode vertices tags b).val := by
+ change (lanes g).val + nL*(tags b.2).val + (J*nL)*(vertices b.1).val =
+ (lanes g).val + nL*((tags b.2).val + J*(vertices b.1).val)
+ ring
+
+/-- Source rectangular slot at lane zero, computed from the base arc's
+numeric index by quotient and remainder. -/
+def laneZeroRow (degree laneCount i : ℕ) : ℕ := (i/degree)*laneCount*2*degree + i%degree
+
+/-- Decode a packed incoming rectangular index into the base arc and lane. -/
+def unpackBaseTarget (degree laneCount rect : ℕ) : ℕ × ℕ :=
+ let site := rect / degree / 2
+ (site/laneCount*degree + rect%degree, site%laneCount)
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] [Module (ZMod 2) Tag]
+
+/-- On each lane-zero source row, the adjacent inverse field supplies the
+actual graph's target base-arc index and displacement. -/
+theorem base_lookup {w rows inverse : ℕ} (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (layout : Bool) {degree : ℕ} (hd : survivingDegree d c subdiv ≤ degree) (hJ : 1 < J)
+ (hzero : (lanes 0).val = 0) (m : Memory w) (p : (V × Tag) × Fin degree)
+ (hfields : RecordCount N J nL d c (degree-survivingDegree d c subdiv) subdiv * 2 ≤ 2^w)
+ (hrect : (N*(J*nL)*2)*degree ≤ 2^w) :
+ let := P.slotIdentifierOrder vertices tags subdiv
+ let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := degree-survivingDegree d c subdiv)
+ let hD := fun b ↦ (slotDirectory_degree P subdiv vertices tags lanes hc layout b).trans (Nat.add_sub_of_le hd)
+ let source := laneZeroRow degree nL (baseIndex vertices tags p).val
+ let field := m (rows+source)
+ let target := m (inverse+(field.val+1))
+ Tables D degree rows inverse hD m → source < (N*(J*nL)*2)*degree ∧
+ field.val+1 < RecordCount N J nL d c (degree-survivingDegree d c subdiv) subdiv * 2 ∧
+ unpackBaseTarget degree nL target.val =
+ ((baseIndex vertices tags (I.graph.base.target p)).val, (lanes (I.graph.displacement p)).val) := by
+ intro order I D hD source field target tab
+ let z := I.outgoing.symm p
+ let i := atLane P subdiv layout z 0
+ have hz : paddedBaseId P subdiv i = z := baseId_atLane P subdiv layout z 0
+ have hsrc : I.outgoing z = p := I.outgoing.apply_symm_apply p
+ have hdst : I.incoming z = I.graph.base.target p := (I.match_eq z).symm.trans (congrArg I.graph.base.target hsrc)
+ have hshift := (I.displacement_eq z).symm.trans (congrArg I.graph.displacement hsrc)
+ have hends := endpoints_atLane P subdiv tags layout z 0
+ have hs : actualEnd P subdiv tags layout false i = (p.1.1,p.1.2,0) := by
+ have h := (I.src_eq z).symm.trans (congrArg Prod.fst hsrc)
+ exact hends.1.trans (congrArg (fun b : V×Tag ↦ (b.1,b.2,(0:L))) h)
+ let t := I.graph.base.target p
+ let g := I.graph.displacement p
+ have ht : actualEnd P subdiv tags layout true i = (t.1.1,t.1.2,g) := by
+ have h := (I.dst_eq z).symm.trans (congrArg Prod.fst hdst)
+ rw [← h]; exact hends.2.trans (congrArg (fun l : L ↦ (_,_,l)) ((zero_add _).trans hshift))
+ let q := siteIndex vertices tags lanes (t.1.1,t.1.2,g)
+ have hout : (sortedFields D degree hD (i,0)).val = source := by
+ have h := rectangular_slot P subdiv vertices tags lanes hc hφ layout hd hJ i 0
+ change (sortedFields D degree hD (i,0)).val = (I.outgoing (paddedBaseId P subdiv i)).2.val +
+ degree*(D.owner (i,0)).val at h
+ rw [hz,hsrc] at h
+ change (sortedFields D degree hD (i,0)).val = p.2.val + degree*(0+2*(siteIndex vertices tags lanes
+ (actualEnd P subdiv tags layout false i)).val) at h
+ rw [hs, site_val, hzero] at h
+ change _ = laneZeroRow degree nL (p.2.val+degree*(packedCode vertices tags p.1).val)
+ rw [h,laneZeroRow,divLow,modLow]; ring
+ have hinc : (sortedFields D degree hD (i,1)).val = t.2.val+degree*(1+2*q.val) := by
+ have h := rectangular_slot P subdiv vertices tags lanes hc hφ layout hd hJ i 1
+ change (sortedFields D degree hD (i,1)).val = (I.incoming (paddedBaseId P subdiv i)).2.val +
+ degree*(D.owner (i,1)).val at h
+ rw [hz,hdst] at h
+ change (sortedFields D degree hD (i,1)).val = t.2.val + degree*(1+2*(siteIndex vertices tags lanes
+ (actualEnd P subdiv tags layout true i)).val) at h
+ simpa only [ht] using h
+ have hf : field.val = (D.address (i,0)).val := by
+ change (m (rows+source)).val = _
+ rw [← hout, tab.bySlot, Fin.val_ofNat, Nat.mod_eq_of_lt ((D.address (i,0)).isLt.trans_le hfields)]
+ have hother : (D.address (i,0)).val+1 = (D.address (i,1)).val := by
+ change 0 + 2*(arcAddress P subdiv vertices tags lanes _ i).val + 1 =
+ 1+2*(arcAddress P subdiv vertices tags lanes _ i).val
+ omega
+ have htarget : target.val = t.2.val+degree*(1+2*q.val) := by
+ change (m (inverse+(field.val+1))).val = _
+ rw [hf, hother, tab.byField, Fin.val_ofNat, Nat.mod_eq_of_lt ((sortedFields D degree hD (i,1)).isLt.trans_le hrect), hinc]
+ have hq : q.val = (lanes g).val+nL*(packedCode vertices tags t.1).val := site_val vertices tags lanes t.1 g
+ refine ⟨hout ▸ (sortedFields D degree hD (i,0)).isLt, by rw [hf,hother]; exact (D.address (i,1)).isLt, ?_⟩
+ rw [htarget, unpackBaseTarget, divLow, modLow, show (1+2*q.val)/2=q.val from divLow (1 : Fin 2) q.val,
+ hq, divLow, modLow]
+ change ((packedCode vertices tags t.1).val * degree + t.2.val, _) =
+ (t.2.val + degree*(packedCode vertices tags t.1).val, _)
+ congr 1; ring
+
+end CompressorRecords.SlotSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotBasePass.lean b/lean/OAI/Computability/VPVNP/CompressorSlotBasePass.lean
new file mode 100644
index 0000000000..bd7a57808f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotBasePass.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Scanning two output tables of the compressed base graph
+
+The worker at cursor `i` writes the destination base arc and lane displacement
+into separate tables. Outside their completed prefixes, all input words retain
+their initial values. This lets one lift a single native call to a full scan
+with an exact calls-plus-probes count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotBasePass
+
+open BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- Execution of one call under the frame left by all preceding calls. -/
+def Visit (P : Program w C) (fuel probes ticks base₁ base₂ count : ℕ)
+ (value₁ value₂ : ℕ → Word w) (initial : Memory w) : Prop :=
+ ∀ i < count, ∀ mem : Memory w,
+ (∀ a, (a < base₁ ∨ base₁ + i ≤ a) → (a < base₂ ∨ base₂ + i ≤ a) →
+ mem a = initial a) →
+ ∃ es, execute P fuel (P.start (Fin.ofNat _ i)) mem [] =
+ some ⟨es, some (Fin.ofNat _ (i + 1))⟩ ∧
+ after mem es = writeMemory (writeMemory mem (Fin.ofNat _ (base₁ + i)) (value₁ i))
+ (Fin.ofNat _ (base₂ + i)) (value₂ i) ∧
+ countProbes es = probes ∧ es.length = ticks
+
+/-- The two completed tables, persistent state, and resource use of a scan. -/
+structure FilledRun (P : Program w C) (fuel probes ticks base₁ base₂ count : ℕ)
+ (value₁ value₂ : ℕ → Word w) (initial : Memory w) (rs : List (Report w)) : Prop where
+ executed : runSegment P fuel (some 0) initial (List.replicate count []) = some rs
+ cursor : endState (some 0) rs = some (Fin.ofNat _ count)
+ first : ∀ i < count, after initial (eventLog rs) (base₁ + i) = value₁ i
+ second : ∀ i < count, after initial (eventLog rs) (base₂ + i) = value₂ i
+ frame : ∀ a, (a < base₁ ∨ base₁ + count ≤ a) → (a < base₂ ∨ base₂ + count ≤ a) →
+ after initial (eventLog rs) a = initial a
+ length : rs.length = count
+ calls : ∀ r ∈ rs, r.probes = probes ∧ r.events.length = ticks
+ cost : RAMBuckets.cost Report.probes rs = (1 + probes) * count
+
+/-- Successive calls fill both disjoint output intervals in cursor order. -/
+theorem run (P : Program w C) (fuel probes ticks base₁ base₂ count : ℕ)
+ (value₁ value₂ : ℕ → Word w) (initial : Memory w)
+ (fit₁ : base₁ + count ≤ 2 ^ w) (fit₂ : base₂ + count ≤ 2 ^ w)
+ (disjoint : base₁ + count ≤ base₂ ∨ base₂ + count ≤ base₁)
+ (visit : Visit P fuel probes ticks base₁ base₂ count value₁ value₂ initial) :
+ ∃ rs, FilledRun P fuel probes ticks base₁ base₂ count value₁ value₂ initial rs := by
+ induction count with
+ | zero =>
+ exact ⟨[], rfl, rfl, by omega, by omega, fun _ _ _ => rfl, rfl, by simp, by simp [RAMBuckets.cost]⟩
+ | succ count ih =>
+ obtain ⟨rs, prev⟩ := ih (by omega) (by omega) (by omega)
+ (fun i hi => visit i (by omega))
+ let mem := after initial (eventLog rs)
+ obtain ⟨es, he, hw, hp, ht⟩ := visit count (Nat.lt_succ_self _) mem prev.frame
+ let r : Report w := ⟨es, some (Fin.ofNat _ (count + 1))⟩
+ have h₁ : (Fin.ofNat (2 ^ w) (base₁ + count)).val = base₁ + count :=
+ Nat.mod_eq_of_lt (by omega)
+ have h₂ : (Fin.ofNat (2 ^ w) (base₂ + count)).val = base₂ + count :=
+ Nat.mod_eq_of_lt (by omega)
+ have hm (a : ℕ) : after initial (eventLog (rs ++ [r])) a =
+ if a = base₂ + count then value₂ count
+ else if a = base₁ + count then value₁ count else mem a := by
+ simpa only [eventLog, List.flatMap_append, List.flatMap_singleton, after, List.foldl_append,
+ r, mem, writeMemory, h₁, h₂] using congrFun hw a
+ refine ⟨rs ++ [r], ?_, ?_, ?_, ?_, ?_, by simp [prev.length], ?_, ?_⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, prev.executed]
+ simp only [Option.bind_some, prev.cursor, runSegment, Option.map_some]
+ change (match execute P fuel (P.start (Fin.ofNat _ count)) mem [] with
+ | none => none | some t => some [t]).map (rs ++ ·) = some (rs ++ [r])
+ rw [he]
+ rfl
+ · rw [endState_append]
+ rfl
+ · intro i hi
+ rw [hm, ite_eq_right (by omega)]
+ by_cases eq : i = count
+ · simp [eq]
+ · rw [ite_eq_right (by omega)]
+ exact prev.first i (by omega)
+ · intro i hi
+ rw [hm]
+ by_cases eq : i = count
+ · simp [eq]
+ · rw [ite_eq_right (by omega), ite_eq_right (by omega)]
+ exact prev.second i (by omega)
+ · intro a ha hb
+ rw [hm, ite_eq_right (by omega), ite_eq_right (by omega)]
+ exact prev.frame a (by omega) (by omega)
+ · intro t h
+ rcases List.mem_append.mp h with h | h
+ · exact prev.calls t h
+ · obtain rfl := List.mem_singleton.mp h
+ exact ⟨hp, ht⟩
+ · have hprobes : r.probes = probes := hp
+ rw [RAMBuckets.cost_append, prev.cost, RAMBuckets.cost, hprobes, RAMBuckets.cost, Nat.mul_succ]
+ omega
+
+end CompressorRecords.SlotBasePass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotBaseScan.lean b/lean/OAI/Computability/VPVNP/CompressorSlotBaseScan.lean
new file mode 100644
index 0000000000..eeacbb7213
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotBaseScan.lean
@@ -0,0 +1,205 @@
+import OAI.Computability.VPVNP.CompressorSlotBasePass
+import OAI.Computability.VPVNP.CompressorSlotBaseLookup
+import OAI.Computability.VPVNP.CompressorSlotOwnerRuns
+
+/-!
+# Native scan of packed base arcs
+
+Each call starts at one packed base and outgoing slot. Two reads follow the
+lane-zero source row to its adjacent incoming field in the inverse table.
+The worker strips the incoming side and lane digits, writes the base target
+and lane displacement to separate arrays, and advances its persistent cursor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotBaseScan
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ}
+
+private abbrev divWord := @BinaryOp.eval w .div
+private abbrev modWord := @BinaryOp.eval w .mod
+
+/-- The public words, in order, are the degree, number of lanes, row-table base,
+inverse-table base, base-target output address, and displacement output address. -/
+def code : List (Op 10 6) :=
+ [.stateWord 0, .publicWord 1 0, .publicWord 2 1, .constant 3 2, .constant 4 1,
+ .binary .div 5 0 1, .binary .mod 6 0 1, .binary .mul 5 5 2, .binary .mul 5 5 3,
+ .binary .mul 5 5 1, .binary .add 5 5 6, .publicWord 6 2, .binary .add 6 6 5, .read 5 6,
+ .binary .add 5 5 4, .publicWord 6 3, .binary .add 6 6 5, .read 5 6,
+ .binary .mod 6 5 1, .binary .div 5 5 1, .binary .div 5 5 3, .binary .mod 7 5 2,
+ .binary .div 5 5 2, .binary .mul 5 5 1, .binary .add 5 5 6,
+ .publicWord 8 4, .binary .add 8 8 0, .write 8 5,
+ .publicWord 9 5, .binary .add 9 9 0, .write 9 7, .binary .add 0 0 4]
+
+/-- Row of the outgoing slot over lane zero. -/
+def srcRect (p : Fin 6 → Word w) (i : Word w) : Word w :=
+ divWord i (p 0) * p 1 * 2 * p 0 + modWord i (p 0)
+
+/-- Address of the outgoing endpoint field in the row table at lane zero for the given base
+port. -/
+def rowAddr (p : Fin 6 → Word w) (i : Word w) : Word w := p 2 + srcRect p i
+
+/-- Address in the inverse table of the incoming field paired with the source field read at
+lane zero. -/
+def invAddr (p : Fin 6 → Word w) (m : Memory w) (i : Word w) : Word w :=
+ p 3 + (m (rowAddr p i).val + 1)
+
+/-- Incoming rectangular slot of the same arc. -/
+def dstRect (p : Fin 6 → Word w) (m : Memory w) (i : Word w) : Word w :=
+ m (invAddr p m i).val
+
+/-- Recover the target site index from the incoming rectangular slot by removing the slot and
+side digits. -/
+def dstSite (p : Fin 6 → Word w) (m : Memory w) (i : Word w) : Word w :=
+ divWord (divWord (dstRect p m i) (p 0)) 2
+
+/-- Base index and incoming slot, encoded in the same radix as the source cursor. -/
+def target (p : Fin 6 → Word w) (m : Memory w) (i : Word w) : Word w :=
+ divWord (dstSite p m i) (p 1) * p 0 + modWord (dstRect p m i) (p 0)
+
+/-- Residual lane of the target reached from source lane zero, giving the base arc's lane
+displacement. -/
+def displacement (p : Fin 6 → Word w) (m : Memory w) (i : Word w) : Word w :=
+ modWord (dstSite p m i) (p 1)
+
+/-- Trace of one base-port visit, reading the row and inverse tables before writing the target
+base port and lane displacement. -/
+def events (p : Fin 6 → Word w) (m : Memory w) (i : Word w) : List (Event w) :=
+ List.replicate 13 .tick ++ [.read (rowAddr p i) (m (rowAddr p i).val)] ++
+ List.replicate 3 .tick ++ [.read (invAddr p m i) (dstRect p m i)] ++
+ List.replicate 9 .tick ++ [.write (p 4+i) (target p m i), .tick, .tick,
+ .write (p 5+i) (displacement p m i), .tick]
+
+theorem events_after (p : Fin 6 → Word w) (m : Memory w) (i : Word w) :
+ after m (events p m i) =
+ writeMemory (writeMemory m (p 4+i) (target p m i)) (p 5+i) (displacement p m i) := rfl
+
+theorem events_work (p : Fin 6 → Word w) (m : Memory w) (i : Word w) :
+ countProbes (events p m i) = 4 ∧ (events p m i).length = 32 := ⟨rfl, rfl⟩
+
+set_option maxRecDepth 8192 in
+/-- The two lookups precede both writes, so the words in the trace are computed
+from the memory at the start of the call, even if some addresses coincide. -/
+theorem native (p : Fin 6 → Word w) (m : Memory w) (i : Word w) :
+ let M := (template code 0).instantiate w p
+ execute M.program 33 (M.program.start i) m [] = some ⟨events p m i, some (i+1)⟩ := by
+ change execute ((template code 0).instantiate w p).program (1+code.length)
+ ⟨_, i, fun _ => 0, fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]
+ rfl
+
+/-- Worst-case word operations, including arbitrary shortened read streams. -/
+theorem opcode_work (p : Fin 6 → Word w) (i : Word w) (allowance : ℕ) (bits : List Bool) :
+ let M := (template code 0).instantiate w p
+ M.loggedDispatchWork 33 (M.logProgram.start i) allowance bits ≤ 198 :=
+ SlotOwners.template_opcode_work code 0 p 33 _ allowance bits
+
+private theorem word_add (base : Word w) (i : ℕ) :
+ base + Fin.ofNat _ i = Fin.ofNat _ (base.val+i) := by
+ apply Fin.ext
+ simp only [Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod]
+
+private theorem word_succ (i : ℕ) :
+ (Fin.ofNat (2^w) i : Word w) + 1 = Fin.ofNat _ (i+1) := by
+ apply Fin.ext
+ simp [Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod]
+
+/-- Each table lookup falls outside the two output regions. The inverse address
+is specified using the field returned by the original row-table read. -/
+def ReadsOutside (p : Fin 6 → Word w) (m : Memory w) (count : ℕ) : Prop :=
+ ∀ i < count, ∀ a ∈ [rowAddr p (Fin.ofNat _ i), invAddr p m (Fin.ofNat _ i)],
+ (a.val < (p 4).val ∨ (p 4).val+count ≤ a.val) ∧
+ (a.val < (p 5).val ∨ (p 5).val+count ≤ a.val)
+
+/-- Fill both base-graph tables using two reads and two writes per arc.
+The two output arrays may be placed in either order. -/
+theorem run (p : Fin 6 → Word w) (initial : Memory w) (count : ℕ)
+ (fit₁ : (p 4).val+count ≤ 2^w) (fit₂ : (p 5).val+count ≤ 2^w)
+ (disjoint : (p 4).val+count ≤ (p 5).val ∨ (p 5).val+count ≤ (p 4).val)
+ (reads : ReadsOutside p initial count) :
+ let P := ((template code 0).instantiate w p).program
+ ∃ rs, SlotBasePass.FilledRun P 33 4 32 (p 4).val (p 5).val count
+ (fun i => target p initial (Fin.ofNat _ i)) (fun i => displacement p initial (Fin.ofNat _ i))
+ initial rs := by
+ intro P
+ apply SlotBasePass.run P 33 4 32 (p 4).val (p 5).val count _ _ initial fit₁ fit₂ disjoint
+ intro i hi mem frame
+ let j : Word w := Fin.ofNat _ i
+ have eq (a : Word w) (ha : a ∈ [rowAddr p j, invAddr p initial j]) :
+ mem a.val = initial a.val := by
+ obtain ⟨h₁, h₂⟩ := reads i hi a ha
+ exact frame a.val (by omega) (by omega)
+ have row := eq (rowAddr p j) (by simp)
+ have sameInv : invAddr p mem j = invAddr p initial j := by simp only [invAddr, row]
+ have dst : dstRect p mem j = dstRect p initial j := by
+ simpa only [dstRect, sameInv] using eq (invAddr p initial j) (by simp)
+ refine ⟨events p mem j, ?_, ?_, (events_work ..).1, (events_work ..).2⟩
+ · rw [native, word_succ]
+ · rw [events_after]
+ simp only [target, displacement, dstSite, dst, j, word_add]
+
+private theorem div_val (x y : Word w) : (divWord x y).val = x.val / y.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)
+
+private theorem mod_val (x y : Word w) : (modWord x y).val = x.val % y.val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt)
+
+/-- The native mixed-radix address equals the lane-zero row when it fits. -/
+theorem srcRect_val (p : Fin 6 → Word w) (i : Word w) (hw : 2 < 2^w)
+ (fit : SlotSchedule.laneZeroRow (p 0).val (p 1).val i.val < 2^w) :
+ (srcRect p i).val = SlotSchedule.laneZeroRow (p 0).val (p 1).val i.val := by
+ have two : (2 : Word w).val = 2 := Nat.mod_eq_of_lt hw
+ simp only [srcRect, Fin.val_add, Fin.val_mul, div_val, mod_val, two,
+ Nat.mod_mul_mod, Nat.mod_add_mod]
+ exact Nat.mod_eq_of_lt fit
+
+/-- Both word addresses denote the ordinary natural-number table lookups. -/
+theorem read_addresses (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (hw : 2 < 2^w)
+ (rowFit : (p 2).val + SlotSchedule.laneZeroRow (p 0).val (p 1).val i.val < 2^w)
+ (invFit : let source := SlotSchedule.laneZeroRow (p 0).val (p 1).val i.val
+ (p 3).val + ((m ((p 2).val+source)).val+1) < 2^w) :
+ let source := SlotSchedule.laneZeroRow (p 0).val (p 1).val i.val
+ let field := m ((p 2).val+source)
+ (rowAddr p i).val = (p 2).val+source ∧ (invAddr p m i).val = (p 3).val+(field.val+1) := by
+ intro source field
+ have hr : (rowAddr p i).val = (p 2).val+source := by
+ rw [rowAddr, Fin.val_add, srcRect_val _ _ hw (by omega), Nat.mod_eq_of_lt rowFit]
+ have hi : (p 3).val + (field.val+1) < 2^w := invFit
+ have hI : (invAddr p m i).val = (p 3).val + (field.val+1) := by
+ change (p 3 + (m (rowAddr p i).val+1)).val = _
+ rw [hr]
+ change (p 3 + (field+1)).val = _
+ rw [Fin.val_add, Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (by omega : 1 < 2^w),
+ Nat.mod_eq_of_lt (by omega : field.val+1 < 2^w), Nat.mod_eq_of_lt hi]
+ exact ⟨hr, hI⟩
+
+/-- With fitting input addresses the words computed by the worker agree with
+the numerical lane-zero lookup and incoming-slot decoder. -/
+theorem outputs_eq (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (hw : 2 < 2^w)
+ (rowFit : (p 2).val + SlotSchedule.laneZeroRow (p 0).val (p 1).val i.val < 2^w)
+ (invFit : let source := SlotSchedule.laneZeroRow (p 0).val (p 1).val i.val
+ (p 3).val + ((m ((p 2).val+source)).val+1) < 2^w) :
+ let source := SlotSchedule.laneZeroRow (p 0).val (p 1).val i.val
+ let field := m ((p 2).val+source)
+ let result := SlotSchedule.unpackBaseTarget (p 0).val (p 1).val (m ((p 3).val+(field.val+1))).val
+ target p m i = Fin.ofNat _ result.1 ∧ displacement p m i = Fin.ofNat _ result.2 := by
+ intro source field result
+ have hI : (invAddr p m i).val = (p 3).val+(field.val+1) :=
+ (read_addresses p m i hw rowFit invFit).2
+ have two : (2 : Word w).val = 2 := Nat.mod_eq_of_lt hw
+ constructor <;> apply Fin.ext <;>
+ simp only [result, SlotSchedule.unpackBaseTarget, target, displacement, dstSite, dstRect, hI,
+ div_val, mod_val, two, Fin.val_mul, Fin.val_add, Fin.val_ofNat, Nat.mod_add_mod]
+ exact (Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt ((Nat.div_le_self ..).trans_lt
+ ((Nat.div_le_self ..).trans_lt (m ((p 3).val+(field.val+1))).isLt)))).symm
+
+end CompressorRecords.SlotBaseScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotBuild.lean b/lean/OAI/Computability/VPVNP/CompressorSlotBuild.lean
new file mode 100644
index 0000000000..0b357eb664
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotBuild.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.CompressorSlotBuildInputs
+import OAI.Computability.VPVNP.CompressorSlotFinish
+
+/-!
+# Complete shrinking slot and incidence construction from the selected rows
+
+The demand-role scan supplies the CD indicator and three packed role sites
+on each old arc. The term/slice scan supplies each genuine subdivision width.
+Beginning with those rows, native preparation, ordering, inversion and width
+scans construct all six incidence columns for the very next compressor state.
+The scratch and output counters may initially contain arbitrary words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots.Build
+
+open Compression Compression.State Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion Slots SlotLevel SlotOwners SlotSchedule
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+/-- Reports for a complete shrinking slot construction, from preparing the selected input
+tables to writing the next state's incidence columns. -/
+structure Construction (w : ℕ) where
+ /-- Reports for publishing subdivisions, building the role and successor tables, and clearing
+ the append counters. -/
+ prepare : Preparation.Reports w
+ /-- Reports for constructing the slot and mate directories and gathering their widths from
+ the prepared inputs. -/
+ passes : Passes w
+
+/-- All preparation and construction reports in execution order. -/
+def Construction.all {w : ℕ} (r : Construction w) := r.prepare.all++r.passes.all
+
+/-- Memory after replaying the preparation reports and then the slot, mate, and width passes. -/
+def Construction.final {w : ℕ} (r : Construction w) (m : Memory w) := r.passes.final (r.prepare.final m)
+
+/-- The memory consumed by the next level is the replay of this construction's chronological log. -/
+theorem Construction.final_eq {w : ℕ} (r : Construction w) (m : Memory w) :
+ r.final m = after m (eventLog r.all) := by
+ simp only [Construction.all, Construction.final, Preparation.Reports.final, Passes.all, Passes.final,
+ SlotLevel.Reports.all, SlotLevel.Reports.final, MateReports.all, MateReports.final, eventLog,
+ List.flatMap_append, after, List.foldl_append]
+
+/-- The preparation and construction reports are produced by their respective native workers,
+with construction starting from the prepared memory. -/
+def Construction.Native {w : ℕ} (r : Construction w) (s : Shape) (h : Heads) (splitHead : ℕ) (layout : Bool) (m : Memory w) :=
+ r.prepare.Native s h layout m ∧ r.passes.Native s h splitHead (r.prepare.final m)
+
+/-- All preparation and construction passes return their prescribed ending cursors for this
+level. -/
+def Construction.Cursors {w : ℕ} (r : Construction w) (s : Shape) := r.prepare.Cursors s ∧ r.passes.Cursors s
+
+variable {a b g w : ℕ} {δ factor : ℝ} {k : Type*} [_root_.Field k]
+variable (X : State a (packingLaneBits a g))
+variable (B : FixedBlock k demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection B)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Convert the simultaneous natural-number width readback of the selected
+slice sweep to the word representation used by the ordered incidence passes. -/
+theorem splitRows_of_values (subdiv : Fin 4 → ℕ) (base : ℕ) (mem : Memory w)
+ (width : X.packingData.Motif → Fin 4 → ℕ)
+ (values : ∀ m t (j : Fin (subdiv t)),
+ (mem (base + (((oldArcIndex X.packingData X.baseIndex (bitWordFinEquiv (packingTagBits (2^a)))
+ (bitWordFinEquiv g) m.val).val * 4 + t.val) * (∑ e, subdiv e) + j.val))).val =
+ splitWidth (width m t) (subdiv t) j) :
+ SlotWidthScan.SplitRows X.packingData subdiv X.baseIndex (bitWordFinEquiv (packingTagBits (2^a)))
+ (bitWordFinEquiv g) width base mem := by
+ intro i
+ apply Fin.ext
+ rw [Fin.val_ofNat, ← values i.2.1 i.1 i.2.2, Nat.mod_eq_of_lt (mem _).isLt]
+
+/-- Construct the complete shared incidence directory in arbitrary initial
+scratch memory. Source word bounds are the live radices of the level.
+The frame covers every earlier input and every later reserved address. -/
+theorem build (h : Heads) (splitHead : ℕ) (mem : Memory w) :
+ let s := levelShape (b := b) X
+ let layout := selectedLayout X B sel
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let lanes := bitWordFinEquiv g
+ let splits := SlotWidthScan.SplitRows X.packingData s.subdivisions X.baseIndex tags lanes (branchWidth X B sel) splitHead
+ DemandRAM.RoleColumns X layout h.oldArc mem → splits mem →
+ h.oldArc+4*DemandRAM.absoluteCount X ≤ h.role →
+ splitHead+(oldBaseArcCount s.bases s.tags s.oldDegree s.colors*s.lanes)*4*(∑ t,s.subdivisions t) ≤ h.role →
+ h.role+8 ≤ h.nextSite → h.nextSite+sites s ≤ h.subdivisions → h.subdivisions+4 ≤ h.scratch →
+ finish s h < 2^w → s.lanes < 2^w → s.tags < 2^w → (∑t,s.subdivisions t)<2^w → s.newDegree<2^w →
+ ∃ r : Construction w, r.Native s h splitHead layout mem ∧ r.Cursors s ∧
+ (directory s h w).Represents (X.shrinkNext B ready sel) (r.final mem) ∧
+ DemandRAM.RoleColumns X layout h.oldArc (r.final mem) ∧ splits (r.final mem) ∧
+ (∀ addr, addr < h.role ∨ finish s h ≤ addr → r.final mem addr=mem addr) ∧
+ RAMBuckets.cost Report.probes r.all = (24+2*sites s+2*(owners s+fields s))+
+ (6*genuineCount s+3*dummyCount s+5*fields s+3*(owners s*2^b)+8*baseArcs s+12*actualCount s) := by
+ intro s layout tags lanes splits roles split oldRoom splitRoom roleRoom nextRoom subRoom fit lw tw sw dw
+ have hr : h.scratch ≤ rowsHead s h := by unfold rowsHead; omega
+ have hs : rowsHead s h ≤ finish s h := by
+ calc
+ _ ≤ inverseHead s h := Nat.le_add_right _ _
+ _ ≤ targetsHead s h := Nat.le_add_right _ _
+ _ ≤ shiftsHead s h := Nat.le_add_right _ _
+ _ ≤ inverseBaseHead s h := Nat.le_add_right _ _
+ _ ≤ outHead s h := Nat.le_add_right _ _
+ _ ≤ inHead s h := Nat.le_add_right _ _
+ _ ≤ widthHead s h := Nat.le_add_right _ _
+ _ ≤ finish s h := Nat.le_add_right _ _
+ obtain ⟨prep,hp,cursor,gTable,dTable,zero,fp,prepCost⟩ := Preparation.run (b := b) X h layout mem roles
+ oldRoom roleRoom nextRoom subRoom (hs.trans_lt fit) lw tw sw dw
+ let mp := prep.final mem
+ have split' : splits mp := SlotWidthScan.SplitRows.congr_below _ _ _ _ _ split splitRoom (fun addr ha ↦ fp addr (Or.inl ha))
+ have oldRoom' : h.oldArc+4*(oldBaseArcCount s.bases s.tags s.oldDegree s.colors*s.lanes) ≤ h.scratch := by
+ change h.oldArc+4*DemandRAM.absoluteCount X ≤ h.scratch; omega
+ obtain ⟨result,native,cursors,rep,fr,cost⟩ := from_prepared X B ready sel h splitHead mp dw gTable dTable
+ split' oldRoom' (by omega) subRoom (nextRoom.trans (by omega)) (splitRoom.trans (by omega)) fit zero
+ let r : Construction w := ⟨prep,result⟩
+ have frame (addr : ℕ) (ha : addr < h.role ∨ finish s h ≤ addr) : r.final mem addr=mem addr :=
+ (fr addr (by change addr simp +arith
+ · intro ha
+ repeat rw [ite_eq_right (by omega)]
+
+/-- Public layout bit and destination table base for computing the endpoint roles of the four
+edge types. -/
+def roleBank (h : Heads) (l : Bool) (w : ℕ) : Fin 2 → Word w := ![word l.toNat,word h.role]
+
+/-- Public lane count, tag count, and destination base for writing the cyclic tag successor of
+every packed site. -/
+def cyclicBank (s : Shape) (h : Heads) (w : ℕ) : Fin 3 → Word w := ![word s.lanes,word s.tags,word h.nextSite]
+
+/-- Reports for the seven input preparation phases, covering four subdivision writes and three
+subsequent scans. -/
+structure Reports (w : ℕ) where
+ /-- One native write report for each of the four subdivision counts. -/
+ publish : Fin 4 → Report w
+ /-- Reports that populate the eight endpoint role entries for the chosen layout. -/
+ roles : List (Report w)
+ /-- Reports that write the site reached by advancing the tag at each packed site. -/
+ cyclic : List (Report w)
+ /-- Reports that zero the append counters for the real endpoint owners and the reserved hole
+ owners. -/
+ clear : List (Report w)
+
+/-- Preparation reports in order of execution, from the four subdivision writes through the
+counter clear. -/
+def Reports.all (r : Reports w) := List.ofFn r.publish ++ r.roles ++ r.cyclic ++ r.clear
+
+/-- Memory after applying all input preparation reports in order. -/
+def Reports.final (r : Reports w) (mem : Memory w) := after mem (eventLog r.all)
+
+/-- All public banks, per-phase fuel and reset cursors, in the planner's visit order. -/
+def Reports.Native (r : Reports w) (s : Shape) (h : Heads) (layout : Bool) (mem : Memory w) : Prop :=
+ let ps := List.ofFn r.publish
+ let m₁ := after mem (eventLog ps)
+ let m₂ := after m₁ (eventLog r.roles)
+ let m₃ := after m₂ (eventLog r.cyclic)
+ (∀ i : Fin 4,
+ let P := ((BlockPlanner.publish (.lit (h.subdivisions+i.val)) (.lit (s.subdivisions i))).worker.table.instantiate
+ w (publishBank h.subdivisions s.subdivisions w i)).program
+ runSegment P 7 (some 0) (after mem (eventLog (ps.take i.val))) [[]] = some [r.publish i]) ∧
+ runSegment ((template Aux.roleCode 0).instantiate w (roleBank h layout w)).program 26 (some 0) m₁
+ (List.replicate 8 []) = some r.roles ∧
+ runSegment ((template Aux.nextCode 0).instantiate w (cyclicBank s h w)).program 19 (some 0) m₂
+ (List.replicate (sites s) []) = some r.cyclic ∧
+ runSegment ((template SliceRAM.clearOps 0).instantiate w (fun _ ↦ word (h.scratch+fields s))).program 8
+ (some 0) m₃ (List.replicate (owners s+fields s) []) = some r.clear
+
+/-- The four publishers return cursor one, and the role, successor, and clear scans return
+their respective row counts. -/
+def Reports.Cursors (r : Reports w) (s : Shape) : Prop :=
+ (∀ i, endState (some 0) [r.publish i] = some 1) ∧
+ endState (some 0) r.roles = some 8 ∧ endState (some 0) r.cyclic = some (word (sites s)) ∧
+ endState (some 0) r.clear = some (word (owners s+fields s))
+
+/-- Calls, calls plus external probes, total dispatched instructions, and the
+per-call instruction bound for the entire seven-phase preparation program. -/
+theorem Reports.Native.resources {r : Reports w} {s : Shape} {h : Heads} {layout : Bool}
+ {mem : Memory w} (native : r.Native s h layout mem) :
+ let n := owners s+fields s
+ r.all.length = 12+sites s+n ∧
+ RAMBuckets.cost Report.probes r.all = 24+2*sites s+2*n ∧
+ (r.all.map (fun rep ↦ rep.events.length+1)).sum = 236+19*sites s+8*n ∧
+ ∀ rep ∈ r.all, rep.events.length+1 ≤ 26 := by
+ intro n
+ obtain ⟨hpub,hr,hn,hc⟩ := native
+ have same : r.publish = published h.subdivisions s.subdivisions w := by
+ funext i
+ have h := (hpub i).symm.trans (publish_run h.subdivisions s.subdivisions
+ (after mem (eventLog ((List.ofFn r.publish).take i.val))) i)
+ exact List.cons.inj (Option.some.inj h) |>.1
+ have role := PhaseCosts.fixedScanCounts (probes := 1) (ticks := 25) _
+ (Aux.role_native (roleBank h layout w)) (fun _ _ ↦ ⟨rfl,rfl⟩) hr
+ have cyclic := PhaseCosts.fixedScanCounts (probes := 1) (ticks := 18) _
+ (Aux.next_native (cyclicBank s h w)) (fun _ _ ↦ ⟨rfl,rfl⟩) hn
+ have clear := PhaseCosts.fixedScanCounts (probes := 1) (ticks := 7) _
+ (fun m i ↦ SliceRAM.clearVisit_native (word (h.scratch+fields s)) i m) (fun _ _ ↦ ⟨rfl,rfl⟩) hc
+ let ps := List.ofFn (published h.subdivisions s.subdivisions w)
+ have pl : ps.length = 4 := rfl
+ change r.all.length = _ ∧ _ ∧ _ ∧ _
+ rw [Reports.all,same]
+ change (ps++r.roles++r.cyclic++r.clear).length = _ ∧ _ ∧ _ ∧ _
+ refine ⟨?_,?_,?_,?_⟩
+ · simp only [List.length_append,pl,role.1,cyclic.1,clear.1]; rfl
+ · simp only [RAMBuckets.cost_append,role.2.1,cyclic.2.1,clear.2.1]; rfl
+ · simp only [List.map_append,List.sum_append,role.2.2.1,cyclic.2.2.1,clear.2.2.1]; rfl
+ · intro rep hx
+ simp only [List.mem_append] at hx
+ rcases hx with ((hp|hr)|hn)|hc
+ · obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hp
+ exact (by decide : 6+1 ≤ 26)
+ · rw [role.2.2.2 rep hr]
+ · rw [cyclic.2.2.2 rep hn]; decide
+ · rw [clear.2.2.2 rep hc]; decide
+
+private theorem cost_one (rs : List (Report w)) (hp : ∀ r ∈ rs, r.probes = 1) :
+ RAMBuckets.cost Report.probes rs = 2*rs.length := by
+ induction rs with
+ | nil => rfl
+ | cons r rs ih =>
+ rw [RAMBuckets.cost,hp r (by simp),ih (fun q hq ↦ hp q (by simp [hq])),List.length_cons,Nat.mul_succ]
+ omega
+
+variable {a b g : ℕ} (X : State a (packingLaneBits a g))
+
+/-- Preservation of both previously materialized slot inputs under the
+preparation program's frame, including every selected split-width cell. -/
+theorem preserve_rows (h : Heads) (layout : Bool) (splitHead : ℕ)
+ (width : X.packingData.Motif → Fin 4 → ℕ) (mem out : Memory w) :
+ let s := levelShape (b := b) X
+ let split := SlotWidthScan.SplitRows X.packingData s.subdivisions X.baseIndex
+ (bitWordFinEquiv (Shrink.J a)) (bitWordFinEquiv g) width splitHead
+ h.oldArc+4*DemandRAM.absoluteCount X ≤ h.role →
+ splitHead+DemandRAM.absoluteCount X*4*(∑ t,s.subdivisions t) ≤ h.role →
+ (∀ addr < h.role, out addr = mem addr) →
+ DemandRAM.RoleColumns X layout h.oldArc mem → split mem →
+ DemandRAM.RoleColumns X layout h.oldArc out ∧ split out := by
+ intro s split oldRoom splitRoom frame cols widths
+ refine ⟨⟨?_,?_⟩, SlotWidthScan.SplitRows.congr_below _ _ _ _ _ widths splitRoom frame⟩
+ · intro e
+ have he : (DemandRAM.absoluteIndex X e).val < DemandRAM.absoluteCount X := (DemandRAM.absoluteIndex X e).isLt
+ rw [frame _ (by omega),cols.cd]
+ · intro e u
+ have he : (DemandRAM.absoluteIndex X e.val).val < DemandRAM.absoluteCount X := (DemandRAM.absoluteIndex X e.val).isLt
+ have hu : roleOffset u < 3 := by cases u <;> decide
+ rw [frame _ (by omega),cols.packed]
+
+/-- The prepared memory supplies both owner workers and all zero append counters.
+Every external cell before the role table or beyond the counters retains its
+initial value. The older split-width rows can therefore use the same frame. -/
+theorem run (h : Heads) (layout : Bool) (mem : Memory w) :
+ let s := levelShape (b := b) X
+ let tags := bitWordFinEquiv (Shrink.J a)
+ let lanes := bitWordFinEquiv g
+ DemandRAM.RoleColumns X layout h.oldArc mem →
+ h.oldArc+4*DemandRAM.absoluteCount X ≤ h.role → h.role+8 ≤ h.nextSite →
+ h.nextSite+sites s ≤ h.subdivisions → h.subdivisions+4 ≤ h.scratch → rowsHead s h < 2^w →
+ s.lanes < 2^w → s.tags < 2^w → (∑ t,s.subdivisions t) < 2^w → s.newDegree < 2^w →
+ ∃ r : Reports w, r.Native s h layout mem ∧ r.Cursors s ∧
+ GenuineTables X.packingData s.subdivisions X.baseIndex tags lanes layout (bank s h w .genuineOwners) (r.final mem) ∧
+ DummyTables X.baseIndex tags lanes (pad s) (bank s h w .dummyOwners) (r.final mem) ∧
+ (∀ u : Word w, u.val < owners s+fields s → r.final mem (h.scratch+fields s+u.val) = 0) ∧
+ (∀ addr, addr < h.role ∨ rowsHead s h ≤ addr → r.final mem addr = mem addr) ∧
+ RAMBuckets.cost Report.probes r.all = 24+2*sites s+2*(owners s+fields s) := by
+ intro s tags lanes cols oldRoom roleRoom nextRoom subRoom fit laneFit tagFit sumFit degreeFit
+ let cnt := owners s+fields s
+ let start := h.scratch+fields s
+ have room : start+cnt < 2^w := fit
+ let p := published h.subdivisions s.subdivisions w
+ let m₁ := after mem (eventLog (List.ofFn p))
+ let rb := roleBank h layout w
+ let cb := cyclicBank s h w
+ let gb := bank s h w .genuineOwners
+ let db := bank s h w .dummyOwners
+ have oldSize : DemandRAM.absoluteCount X = oldBaseArcCount s.bases s.tags s.oldDegree s.colors * s.lanes := rfl
+ have lanePos : 0 < s.lanes := Nat.two_pow_pos _
+ have baseLe := Nat.le_mul_of_pos_right (oldBaseArcCount s.bases s.tags s.oldDegree s.colors) lanePos
+ rw [← oldSize] at baseLe
+ have scratchLe : h.scratch ≤ start := Nat.le_add_right ..
+ have roleVal : (rb 1).val = h.role := Nat.mod_eq_of_lt (by omega : h.role < 2^w)
+ have nextVal : (cb 2).val = h.nextSite := Nat.mod_eq_of_lt (by omega : h.nextSite < 2^w)
+ have subVal : (gb 5).val = h.subdivisions := Nat.mod_eq_of_lt (by omega : h.subdivisions < 2^w)
+ have oldVal : (gb 3).val = h.oldArc := Nat.mod_eq_of_lt (by omega : h.oldArc < 2^w)
+ have clrVal : (word (w := w) start).val = start := Nat.mod_eq_of_lt (by omega)
+ obtain ⟨rs,roleRun,roleData⟩ := Aux.roles_run layout rb m₁ rfl (by rw [roleVal]; omega)
+ let m₂ := after m₁ (eventLog rs)
+ have padFit : pad s < 2^w := (Nat.sub_le ..).trans_lt degreeFit
+ obtain ⟨ns,nextRun,nextData⟩ := Aux.next_run X.baseIndex tags lanes cb db m₂
+ (Nat.mod_eq_of_lt laneFit) (Nat.mod_eq_of_lt tagFit) (pad s) (Nat.mod_eq_of_lt padFit)
+ rfl (by omega) (by rw [nextVal]; change h.nextSite+sites s ≤ _; omega)
+ let m₃ := after m₂ (eventLog ns)
+ obtain ⟨cs,clearRun,clearData,clearFrame,clearCursor,clearLength,clearWork⟩ :=
+ SliceRAM.clearPass_run (word start) cnt (by rw [clrVal]; omega) (by omega) m₃
+ rw [clrVal] at clearData clearFrame
+ let r : Reports w := ⟨p,rs,ns,cs⟩
+ have final : r.final mem = after m₃ (eventLog cs) := by
+ simp only [r,Reports.final,Reports.all,eventLog,List.flatMap_append,after,List.foldl_append,m₃,m₂,m₁]
+ have roleFrame (x : ℕ) (hx : x < h.role ∨ h.role+8 ≤ x) : m₂ x = m₁ x :=
+ roleRun.frame x (roleVal ▸ hx)
+ have nextFrame (x : ℕ) (hx : x < h.nextSite ∨ h.nextSite+sites s ≤ x) : m₃ x = m₂ x :=
+ nextRun.frame x (nextVal ▸ hx)
+ have finalFrame (x : ℕ) (hx : x < h.role ∨ rowsHead s h ≤ x) : r.final mem x = mem x := by
+ change x < h.role ∨ start+cnt ≤ x at hx
+ rw [final,clearFrame x (by omega),nextFrame x (by omega),roleFrame x (by omega)]
+ exact (published_after _ _ mem (by omega) x).2 (by omega)
+ have roles : (gb 4).val = h.role := roleVal
+ have dummyHead : (db 1).val = h.nextSite := nextVal
+ refine ⟨r, ⟨fun i ↦ publish_run _ _ _ i,roleRun.executed,nextRun.executed,clearRun⟩,
+ ⟨fun _ ↦ rfl,roleRun.cursor,nextRun.cursor,clearCursor⟩, ?_, ?_, ?_, finalFrame, ?_⟩
+ · refine ⟨Nat.mod_eq_of_lt laneFit,Nat.mod_eq_of_lt sumFit,
+ Nat.mod_eq_of_lt (show oldBaseArcCount s.bases s.tags s.oldDegree s.colors < 2^w by omega),
+ Nat.mod_eq_of_lt (show owners s < 2^w by dsimp only [cnt] at room; omega),
+ by rw [oldVal,← oldSize]; omega, by rw [roles]; omega, by rw [subVal]; omega, ?_, ?_, ?_, ?_⟩
+ · intro t u
+ have idx : 2*t.val+u.val < 8 := by have := t.isLt; have := u.isLt; omega
+ rw [roles,final,clearFrame _ (by omega),nextFrame _ (by omega),← roleVal]
+ exact roleData t u
+ · intro t
+ have ht := t.isLt
+ rw [subVal,final,clearFrame _ (by omega),nextFrame _ (by omega),roleFrame _ (by omega)]
+ have cell : m₁ (h.subdivisions+t.val) = word (s.subdivisions t) :=
+ (published_after h.subdivisions s.subdivisions mem (by omega) _).1 t rfl
+ rw [cell]
+ exact Nat.mod_eq_of_lt ((Finset.single_le_sum (fun i _ ↦ Nat.zero_le (s.subdivisions i))
+ (Finset.mem_univ t)).trans_lt sumFit)
+ · intro e
+ have he : (DemandRAM.absoluteIndex X e).val < DemandRAM.absoluteCount X := (DemandRAM.absoluteIndex X e).isLt
+ rw [oldVal]
+ change (r.final mem (h.oldArc+4*(DemandRAM.absoluteIndex X e).val+3)).val = _
+ rw [finalFrame _ (.inl (by omega))]
+ exact cols.cd e
+ · intro e u
+ have he : (DemandRAM.absoluteIndex X e.val).val < DemandRAM.absoluteCount X := (DemandRAM.absoluteIndex X e.val).isLt
+ have hu : roleOffset u < 3 := by cases u <;> decide
+ rw [oldVal]
+ change (r.final mem (h.oldArc+4*(DemandRAM.absoluteIndex X e.val).val+roleOffset u)).val = _
+ rw [finalFrame _ (.inl (by omega))]
+ exact cols.packed e u
+ · refine ⟨nextData.twoFits,nextData.padCount,nextData.nextFits,?_⟩
+ intro i
+ have hi : i.val < sites s := i.isLt
+ rw [final,clearFrame _ (.inl (by rw [dummyHead]; omega))]
+ exact nextData.nextSite i
+ · intro u hu
+ rw [final]
+ exact clearData _ (by omega) (by change u.val < cnt at hu; omega)
+ · have pc : RAMBuckets.cost Report.probes (List.ofFn p) = 8 := by
+ rw [cost_one _ (by intro rep hr; obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hr; rfl),List.length_ofFn]
+ have cc := cost_one cs (fun rep hr ↦ (clearWork rep hr).1)
+ rw [clearLength] at cc
+ simp only [r,Reports.all,RAMBuckets.cost_append,pc,roleRun.cost,nextRun.cost,cc]
+ rfl
+
+end CompressorRecords.ShrinkSlots.Preparation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotCopiedTables.lean b/lean/OAI/Computability/VPVNP/CompressorSlotCopiedTables.lean
new file mode 100644
index 0000000000..bcd1d32604
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotCopiedTables.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.CompressorSlotSelectedAccess
+
+/-! # Persistence of sorted endpoint records in a distinct descriptor level
+
+The canonical incidence copies write within the six live destination columns.
+A distinct allocation retains every source and inverse endpoint record.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots.Build
+
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion Slots SlotLevel BurstRAM
+
+variable {a b g w : ℕ} {k : Type*} [_root_.Field k] {factor δ : ℝ}
+variable (X : State a (packingLaneBits a g))
+variable (F : FixedBlock k demandSource demandTarget Compression.ShrinkMotif.supply
+ (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection F)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+set_option maxHeartbeats 1000000 in
+/-- Any fitting slot workspace retains its rectangular lookup tables after the
+six native incidence copies if their destination avoids those two tables. -/
+theorem retained_after_copy (h : Heads) (out : Memory w) (r : Construction w) (L : DescriptorSpace.Layout)
+ (level : Fin L.levels) (room : DescriptorSpace.endAddress L < 2^w) :
+ let s := levelShape (b := b) X
+ let side := selectedLayout X F sel
+ let Y := X.shrinkNext F ready sel
+ let U := DescriptorSpace.packedIncidence L w level (actualCount s)
+ let T := directory s h w
+ let start := DescriptorSpace.incidenceStart L level
+ let m := after out (eventLog r.all)
+ let copies := CopyIncidence.reports Y T U CopyIncidence.allColumns m
+ finish s h < 2^w → actualCount s ≤ DescriptorSpace.slotCapacity L →
+ OrderedTables X ready side h (r.final out) →
+ (finish s h ≤ start ∨ start+6*actualCount s ≤ rowsHead s h) →
+ OrderedTables X ready side h (after out (eventLog (r.all++copies))) := by
+ intro s side Y U T start m copies fit cap sorted apart
+ have hm : m = r.final out := (r.final_eq out).symm
+ have hb := next_counts X F ready sel
+ have source := CopyIncidence.shrink_column_bounds Y s h hb.1 hb.2 fit
+ have dest := CopyIncidence.packed_column_bounds Y s L level hb.2 room cap
+ have live := DescriptorSpace.packed_incidence_room L room level cap
+ have copied := CopyIncidence.reports_run Y T U CopyIncidence.allColumns m
+ have writes := (copied.footprint (fun c ↦ (source c).2.trans fit.le)
+ (fun c ↦ (dest c).2.trans live.le)).2
+ have finish : targetsHead s h ≤ ShrinkSlots.finish s h := by
+ unfold ShrinkSlots.finish widthHead inHead outHead inverseBaseHead stopAddress shiftsHead; omega
+ have keep (x) (first : rowsHead s h ≤ x) (end_ : x < targetsHead s h) :
+ after out (eventLog (r.all++copies)) x = r.final out x := by
+ have empty : ¬ CopyIncidence.ColumnCell Y U x := by
+ rintro ⟨i,hi⟩
+ have hd : (U.column i).val=start+i.val*actualCount s ∧
+ (U.column i).val+CopyIncidence.rows Y i ≤ start+6*actualCount s := dest i
+ omega
+ have eq : after m (eventLog copies) x = r.final out x :=
+ (SourceTransport.after_outside m writes empty).trans (congrFun hm x)
+ simpa only [m,eventLog,List.flatMap_append,after,List.foldl_append] using eq
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let lanes := bitWordFinEquiv g
+ let D := SlotSchedule.slotDirectory X.packingData (s).subdivisions X.baseIndex tags lanes side (pad := pad s)
+ let degree := fun v ↦ (SlotSchedule.slotDirectory_degree X.packingData (s).subdivisions X.baseIndex tags lanes
+ (State.two_le_packingColors a) side v).trans (Nat.add_sub_of_le ready.degree_budget)
+ have rect : rowsHead s h+owners s*(s).newDegree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.le_add_right _ _)) _
+ have extent : inverseHead s h+fields s=targetsHead s h := rfl
+ constructor
+ · intro e
+ have hi : (SlotSchedule.sortedFields D (2^b) degree e).val < owners s*(s).newDegree :=
+ (SlotSchedule.sortedFields D (2^b) degree e).isLt
+ exact (keep (rowsHead s h+(SlotSchedule.sortedFields D (2^b) degree e).val) (by omega) (by omega)).trans (sorted.bySlot e)
+ · intro e
+ have hi : (D.address e).val < fields s := (D.address e).isLt
+ exact (keep (inverseHead s h+(D.address e).val) (by omega) (by omega)).trans (sorted.byField e)
+
+end CompressorRecords.ShrinkSlots.Build
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotCopyLayout.lean b/lean/OAI/Computability/VPVNP/CompressorSlotCopyLayout.lean
new file mode 100644
index 0000000000..5a31e5d97f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotCopyLayout.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.CompressorRecordsCopyIncidence
+import OAI.Computability.VPVNP.CompressorSlotOutputLayout
+
+/-!
+# Address bounds for copying the shrinking incidence directory
+
+The three base columns occupy shorter intervals than the three lane columns.
+The destination reserves one full lane column per field. A single interval
+comparison therefore suffices to schedule the six canonical copy scans.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.CopyIncidence
+
+open Compression SlotLevel ShrinkSlots BurstRAM
+
+variable {a l w : ℕ} (Y : State a l) (s : SlotLevel.Shape) (h : Heads)
+
+/-- The native copy worker scans exactly the initialized part of each output column. -/
+theorem shrink_rows (baseRows : Fintype.card Y.Base*2^a = baseArcs s)
+ (laneRows : Fintype.card Y.Base*2^l*2^a = actualCount s) (c : Fin 6) :
+ rows Y c = if c.val < 3 then baseArcs s else actualCount s := by
+ simp only [rows, State.positions, Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv l),
+ Fintype.card_fin, baseRows, laneRows]
+
+/-- Every live source cell lies between the first base target and the last outgoing width. -/
+theorem shrink_column_bounds (baseRows : Fintype.card Y.Base*2^a = baseArcs s)
+ (laneRows : Fintype.card Y.Base*2^l*2^a = actualCount s) (scratchRoom : finish s h < 2^w) (c : Fin 6) :
+ targetsHead s h ≤ ((directory s h w).column c).val ∧
+ ((directory s h w).column c).val + rows Y c ≤ finish s h := by
+ let head : Fin 6 → ℕ := ![targetsHead s h, inverseBaseHead s h, shiftsHead s h,
+ outHead s h, inHead s h, widthHead s h]
+ have b₁ : targetsHead s h + baseArcs s = shiftsHead s h := rfl
+ have b₂ : shiftsHead s h + baseArcs s = inverseBaseHead s h := rfl
+ have b₃ : inverseBaseHead s h + baseArcs s = outHead s h := rfl
+ have b₄ : outHead s h + actualCount s = inHead s h := rfl
+ have b₅ : inHead s h + actualCount s = widthHead s h := rfl
+ have b₆ : widthHead s h + actualCount s = finish s h := rfl
+ have source (c : Fin 6) : targetsHead s h ≤ head c ∧ head c + rows Y c ≤ finish s h := by
+ rw [shrink_rows Y s baseRows laneRows]
+ fin_cases c
+ · change _ ≤ targetsHead s h ∧ targetsHead s h + baseArcs s ≤ _; omega
+ · change _ ≤ inverseBaseHead s h ∧ inverseBaseHead s h + baseArcs s ≤ _; omega
+ · change _ ≤ shiftsHead s h ∧ shiftsHead s h + baseArcs s ≤ _; omega
+ · change _ ≤ outHead s h ∧ outHead s h + actualCount s ≤ _; omega
+ · change _ ≤ inHead s h ∧ inHead s h + actualCount s ≤ _; omega
+ · change _ ≤ widthHead s h ∧ widthHead s h + actualCount s ≤ _; omega
+ have he : (directory s h w).column c = Fin.ofNat _ (head c) := by fin_cases c <;> rfl
+ rw [he,Fin.val_ofNat,Nat.mod_eq_of_lt (by have := (source c).2; omega)]
+ exact source c
+
+/-- The descriptor's fixed column stride reserves all live rows of the selected state. -/
+theorem packed_column_bounds (L : DescriptorSpace.Layout) (level : Fin L.levels)
+ (laneRows : Fintype.card Y.Base*2^l*2^a = actualCount s) (levelRoom : DescriptorSpace.endAddress L < 2^w)
+ (capacity : actualCount s ≤ DescriptorSpace.slotCapacity L) (c : Fin 6) :
+ let start := DescriptorSpace.incidenceStart L level
+ let n := actualCount s
+ let U := DescriptorSpace.packedIncidence L w level n
+ (U.column c).val = start+c.val*n ∧ (U.column c).val+rows Y c ≤ start+6*n := by
+ intro start n U
+ have room : start + 6*n < 2^w := DescriptorSpace.packed_incidence_room L levelRoom level capacity
+ have destHead (c : Fin 6) : (U.column c).val = start+c.val*n := by
+ rw [show U = DescriptorSpace.packedIncidence L w level n from rfl,DescriptorSpace.packed_column]
+ have hc := Nat.mul_le_mul_right n c.isLt.le
+ exact Nat.mod_eq_of_lt (by change start+c.val*n < _; omega)
+ have counts (c : Fin 6) : rows Y c ≤ n := by
+ have nr : Y.positions*2^a = n := by
+ simpa only [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv l),Fintype.card_fin] using laneRows
+ exact (rows_le_slots Y c).trans_eq nr
+ have dest (c : Fin 6) : (U.column c).val + rows Y c ≤ start + 6*n := by
+ have hc := Nat.mul_le_mul_right n c.isLt
+ rw [Nat.succ_mul] at hc
+ rw [destHead]
+ have := counts c; omega
+ exact ⟨destHead c,dest c⟩
+
+/-- The selected shrinking directory can be copied to the next descriptor
+level whether the canonical output is below or above the scratch allocation. -/
+theorem Regions.shrink_to_level (L : DescriptorSpace.Layout) (level : Fin L.levels)
+ (baseRows : Fintype.card Y.Base*2^a = baseArcs s)
+ (laneRows : Fintype.card Y.Base*2^l*2^a = actualCount s)
+ (scratchRoom : finish s h < 2^w) (levelRoom : DescriptorSpace.endAddress L < 2^w)
+ (capacity : actualCount s ≤ DescriptorSpace.slotCapacity L)
+ (apart : finish s h ≤ DescriptorSpace.incidenceStart L level ∨
+ DescriptorSpace.incidenceStart L level + 6 * actualCount s ≤ targetsHead s h) :
+ Regions Y (directory s h w) (DescriptorSpace.packedIncidence L w level (actualCount s)) := by
+ let T := directory s h w
+ let U := DescriptorSpace.packedIncidence L w level (actualCount s)
+ let start := DescriptorSpace.incidenceStart L level
+ let n := actualCount s
+ have source := shrink_column_bounds Y s h baseRows laneRows scratchRoom
+ have packed := packed_column_bounds Y s L level laneRows levelRoom capacity
+ have destHead (c : Fin 6) : (U.column c).val = start+c.val*n := (packed c).1
+ have dest (c : Fin 6) : (U.column c).val + rows Y c ≤ start + 6*n := (packed c).2
+ have counts (c : Fin 6) : rows Y c ≤ n := by
+ rw [shrink_rows Y s baseRows laneRows]
+ split
+ · rw [← baseRows,show n = Fintype.card Y.Base*2^l*2^a from laneRows.symm]
+ exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos l))
+ · exact le_rfl
+ have room : start+6*n < 2^w := DescriptorSpace.packed_incidence_room L levelRoom level capacity
+ apply Regions.of_intervals Y T U
+ · intro c; exact (source c).2.trans scratchRoom.le
+ · intro c; exact (dest c).trans room.le
+ · intro c d
+ change finish s h ≤ start ∨ start+6*n ≤ targetsHead s h at apart
+ rcases apart with hf|hf
+ · left; rw [destHead]; exact (source c).2.trans (hf.trans (Nat.le_add_right _ _))
+ · right; exact (dest d).trans (hf.trans (source c).1)
+ · intro c d hcd
+ have before (i j : Fin 6) (lt : i < j) : (U.column i).val + rows Y i ≤ (U.column j).val := by
+ have ij := Nat.mul_le_mul_right n (show i.val+1 ≤ j.val from lt)
+ rw [Nat.succ_mul] at ij
+ rw [destHead,destHead]
+ have := counts i; omega
+ exact (lt_or_gt_of_ne hcd).imp (before c d) (before d c)
+
+end CompressorRecords.CopyIncidence
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotCoreAccess.lean b/lean/OAI/Computability/VPVNP/CompressorSlotCoreAccess.lean
new file mode 100644
index 0000000000..d8d4a7f8fe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotCoreAccess.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.CompressorSlotOwnerFootprint
+import OAI.Computability.VPVNP.CompressorSlotFillFootprint
+import OAI.Computability.VPVNP.CompressorSlotBaseFootprint
+import OAI.Computability.VPVNP.CompressorSlotRunUnique
+import OAI.Computability.VPVNP.CompressorShrinkSlotFootprint
+
+/-!
+# Access bounds of the five sorted-slot workers on the selected branch
+
+Recover the owner records, zero counters and sorted fields at their actual
+phase boundaries. This gives the addresses of every emitted probe, including
+the indirect row and inverse-field lookups.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots.Build
+
+open Compression Compression.State Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion Slots SlotLevel SlotOwners SlotSchedule
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+/-- The physical inputs used by the branch and all intermediate slot arrays. -/
+def readRegion (s : Shape) (h : Heads) (splitHead x : ℕ) :=
+ min h.oldArc splitHead ≤ x ∧ x < finish s h
+
+/-- Slot outputs including the small preparation tables. -/
+def writeRegion (s : Shape) (h : Heads) (x : ℕ) := h.role ≤ x ∧ x < finish s h
+
+/-- Bounds used to allocate and instantiate the native shrinking workers. -/
+structure Space (s : Shape) (h : Heads) (splitHead w : ℕ) : Prop where
+ old : h.oldArc + SlotOwnerFootprint.oldWords s ≤ h.role
+ split : splitHead+(oldBaseArcCount s.bases s.tags s.oldDegree s.colors*s.lanes)*4*(∑t,s.subdivisions t) ≤ h.role
+ roles : h.role+8 ≤ h.nextSite
+ next : h.nextSite+sites s ≤ h.subdivisions
+ subdiv : h.subdivisions+4 ≤ h.scratch
+ fit : finish s h < 2^w
+ lanes : s.lanes < 2^w
+ tags : s.tags < 2^w
+ profile : (∑t,s.subdivisions t) < 2^w
+ degree : s.newDegree < 2^w
+
+variable {a b g w : ℕ} {δ factor : ℝ} {k : Type*} [_root_.Field k]
+variable (X : State a (packingLaneBits a g))
+variable (B : FixedBlock k demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection B)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- The two-way rectangular slot order on this actual selected network. -/
+noncomputable abbrev OrderedTables (side : Bool) (h : Heads) (mem : Memory w) :=
+ let s := levelShape (b := b) X
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let D := slotDirectory X.packingData s.subdivisions X.baseIndex tags (bitWordFinEquiv g) side (pad := pad s)
+ let degree := fun v ↦ (slotDirectory_degree X.packingData s.subdivisions X.baseIndex tags (bitWordFinEquiv g)
+ (two_le_packingColors a) side v).trans (Nat.add_sub_of_le ready.degree_budget)
+ Tables D (2^b) (rowsHead s h) (inverseHead s h) degree mem
+
+set_option maxHeartbeats 1000000 in
+/-- All five sorted-slot phases access the allocated data, and the exact
+post-memory supplies the typed base matching for the subsequent mate scans. -/
+theorem core_access (h : Heads) (splitHead : ℕ) (mem : Memory w) (r : Construction w) :
+ let s := levelShape (b := b) X
+ let side := selectedLayout X B sel
+ Space s h splitHead w → DemandRAM.RoleColumns X side h.oldArc mem →
+ r.Native s h splitHead side mem →
+ LogAccess (readRegion s h splitHead) (writeRegion s h) r.passes.slots.all ∧
+ BaseForward (X.shrinkNext B ready sel) (targetsHead s h) (shiftsHead s h)
+ (r.passes.slots.final (r.prepare.final mem)) ∧
+ 2 < 2^w ∧ oldBaseArcCount s.bases s.tags s.oldDegree s.colors < 2^w ∧
+ OrderedTables X ready side h (r.passes.slots.final (r.prepare.final mem)) := by
+ intro s side sp roles native
+ let P := X.packingData
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let lanes := bitWordFinEquiv g
+ let D := slotDirectory P s.subdivisions X.baseIndex tags lanes side (pad := pad s)
+ let degree := fun v ↦ (slotDirectory_degree P s.subdivisions X.baseIndex tags lanes (two_le_packingColors a) side v).trans
+ (Nat.add_sub_of_le ready.degree_budget)
+ have h0 := sp.old
+ have h1 := sp.roles
+ have h2 := sp.next
+ have h3 := sp.subdiv
+ have f0 : h.scratch+fields s ≤ rowsHead s h := Nat.le_add_right _ _
+ have f1 : rowsHead s h+owners s*s.newDegree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.le_add_right _ _)) _
+ have f2 : inverseHead s h ≤ targetsHead s h := Nat.le_add_right _ _
+ have f3 : targetsHead s h ≤ stopAddress s h := (Nat.le_add_right _ _).trans (Nat.le_add_right _ _)
+ have f4 : stopAddress s h ≤ finish s h := by unfold finish widthHead inHead outHead inverseBaseHead; omega
+ have fit := sp.fit
+ have oldBound : h.oldArc + SlotOwnerFootprint.oldWords s ≤ h.scratch := by omega
+ have roleBound : h.role+8 ≤ h.scratch := by omega
+ have nextBound : h.nextSite+sites s ≤ h.scratch := by omega
+ have cap : stopAddress s h < 2^w := f4.trans_lt fit
+ have capRows : rowsHead s h < 2^w := by omega
+ obtain ⟨prep,pn,_,genuine,dummy,zero,_,_⟩ := Preparation.run (b := b) X h side mem roles h0 h1 h2 h3
+ capRows sp.lanes sp.tags sp.profile sp.degree
+ obtain rfl := pn.unique native.1
+ let mp := r.prepare.final mem
+ let rs := r.passes.slots
+ have rn : rs.Native s h mp := native.2.1
+ obtain ⟨rs',rn',_,tables,forward,_,_⟩ := next_run X B ready sel h mp sp.degree genuine dummy
+ oldBound roleBound h3 nextBound cap zero
+ obtain rfl := rn'.unique rn
+ obtain ⟨gr,dr⟩ := SlotOwnerFootprint.of_tables (degree := s.newDegree) P s.subdivisions X.baseIndex tags lanes
+ side h mp rs genuine dummy oldBound roleBound h3 nextBound cap rn
+ have input := input_of_tables (degree := s.newDegree) P s.subdivisions X.baseIndex tags lanes
+ side mp h genuine dummy oldBound roleBound h3 nextBound cap
+ obtain ⟨ar,ir⟩ := SlotFillFootprint.selected s h D input (Nat.two_pow_pos b) sp.degree degree cap zero rn
+ have hJ : 1 < 2^packingTagBits (2^a) := Nat.one_lt_two_pow (Nat.succ_pos _).ne'
+ have zeroLane : (lanes 0).val = 0 := by simpa using bitWordFinEquiv_add_val (0 : BitWord g) 0
+ obtain ⟨_,br⟩ := selected_base_footprint P s.subdivisions X.baseIndex tags lanes side h (two_le_packingColors a)
+ (orderedDyadicPacking_validTags X.slots X.baseIndex) ready.degree_budget hJ zeroLane dummy.twoFits
+ sp.degree sp.lanes mp rs cap rn tables
+ have lower := min_le_left h.oldArc splitHead
+ have sizes := counts_add s
+ let rd := readRegion s h splitHead
+ let wr := writeRegion s h
+ have g' : LogAccess rd wr rs.genuine := LogAccess.mono gr (fun x hx ↦ by
+ change SlotOwnerFootprint.interval h.oldArc (SlotOwnerFootprint.oldWords s) x ∨
+ SlotOwnerFootprint.interval h.role 8 x ∨ SlotOwnerFootprint.interval h.subdivisions 4 x at hx
+ unfold SlotOwnerFootprint.interval at hx
+ change min h.oldArc splitHead ≤ x ∧ x < finish s h; rcases hx with hx|hx|hx <;> omega)
+ (fun x hx ↦ by change h.scratch≤x ∧ x intro a v h
+ · simp only [collectEvents, List.mem_cons, List.not_mem_nil, or_false, false_or, reduceCtorEq,
+ Event.read.injEq] at h
+ rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩
+ · exact .inl oaddr
+ · exact .inr caddr
+ · simp only [collectEvents, List.mem_cons, List.not_mem_nil, or_false, false_or, reduceCtorEq,
+ Event.write.injEq] at h
+ rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩
+ · exact .inr daddr
+ · exact .inl caddr
+
+/-- Native append bounds for a successful partial or complete scan. The guards
+on each call suffice for these bounds even with arbitrary starting memory. -/
+theorem append_run {p : Fin 6 → Word w} (regions : RowRegions p) {m : Memory w} {i : Word w}
+ {steps : ℕ} {rs : List (Report w)}
+ (run : runSegment ((template collectPreimage 3).instantiate w p).program 23 (some i) m
+ (List.replicate steps []) = some rs) :
+ Reads (AppendReads p) (eventLog rs) ∧ Writes (AppendWrites p) (eventLog rs) := by
+ induction steps generalizing m i rs with
+ | zero =>
+ change some [] = some rs at run
+ cases run
+ simp [eventLog, Reads, Writes]
+ | succ steps ih =>
+ rw [List.replicate_succ, runSegment] at run
+ by_cases ok : i < p 0 ∧ ownerAt p m i < p 2 ∧ m (countAt p (ownerAt p m i)).val < p 4
+ · rw [collectPreimage_native p m i ok.1 ok.2.1 ok.2.2] at run
+ obtain ⟨tail, ht, rfl⟩ := Option.map_eq_some_iff.mp run
+ obtain ⟨tr, tw⟩ := ih ht
+ obtain ⟨hr, hw⟩ := append_visit regions m i ok.1 ok.2.1 ok.2.2
+ exact ⟨fun a v h => (List.mem_append.mp h).elim (hr a v) (tr a v),
+ fun a v h => (List.mem_append.mp h).elim (hw a v) (tw a v)⟩
+ · rw [collectPreimage_reject p m i ok] at run
+ cases run
+
+/-- Bounds for the native inverse pass with a bounded forward column. The values
+may repeat. Each write lies in the disjoint inverse interval, so all remaining
+source reads see their initial values. -/
+theorem scatter_run_bounded {n cap : ℕ} {p : Fin 2 → Word w} (regions : SlotScatter.Regions p n cap)
+ {m : Memory w} (bounded : ∀ i : Fin n, (m ((p 0).val+i.val)).val < cap)
+ {k steps : ℕ} (size : k + steps ≤ n) {rs : List (Report w)}
+ (run : runSegment ((template SlotScatter.visit 0).instantiate w p).program 10
+ (some (Fin.ofNat (2^w) k)) m (List.replicate steps []) = some rs) :
+ Reads (InColumn (p 0).val n) (eventLog rs) ∧ Writes (InColumn (p 1).val cap) (eventLog rs) := by
+ let M := (template SlotScatter.visit 0).instantiate w p
+ let I := fun (_ : ℕ) (mem : Memory w) => ∀ i : Fin n, (mem ((p 0).val+i.val)).val < cap
+ apply OrdinalRun.footprint M.program 10 (Fin.ofNat (2^w)) n I _ _ _ k (List.replicate steps [])
+ m rs (by simpa only [List.length_replicate] using size) bounded run
+ intro j hj mem hmem bits rep he
+ let idx := Fin.ofNat (2^w) j
+ let v := mem (p 0 + idx).val
+ have hs : (p 0 + idx).val = (p 0).val + j := address_val (p 0) regions.fieldsFit ⟨j,hj⟩
+ have hv : v.val < cap := by change (mem (p 0 + idx).val).val < cap; rw [hs]; exact hmem ⟨j,hj⟩
+ have hf := regions.inverseFit
+ have hd : (p 1 + v).val = (p 1).val + v.val := by rw [Fin.val_add,Nat.mod_eq_of_lt (by omega)]
+ have hr := (execute_prefix_unique (suffix := bits) (SlotScatter.visit_native p mem idx) he).2
+ subst rep
+ refine ⟨congrArg some (word_succ j), ?_, ?_, ?_⟩
+ · intro b
+ have hb := b.isLt
+ have sep := regions.disjoint
+ have neq : (p 0).val+b.val ≠ (p 1 + v).val := by rw [hd]; omega
+ change (writeMemory mem (p 1+v) idx ((p 0).val+b.val)).val < cap
+ rw [writeMemory,ite_eq_right neq]; exact hmem b
+ · intro a x h
+ simp only [SlotScatter.events,List.mem_cons,List.not_mem_nil,or_false,false_or,reduceCtorEq,Event.read.injEq] at h
+ obtain ⟨rfl,_⟩ := h
+ change InColumn _ _ (p 0 + idx).val
+ rw [InColumn,hs]; omega
+ · intro a x h
+ simp only [SlotScatter.events,List.mem_cons,List.not_mem_nil,or_false,false_or,reduceCtorEq,Event.write.injEq] at h
+ obtain ⟨rfl,_⟩ := h
+ change InColumn _ _ (p 1 + v).val
+ rw [InColumn,hd]; omega
+
+/-- Footprint of the reports returned by `SlotScatter.run`, for any occupied
+endpoint embedding. -/
+theorem scatter_run {n cap : ℕ} {p : Fin 2 → Word w} (regions : SlotScatter.Regions p n cap)
+ (field : Fin n ↪ Fin cap) {m : Memory w}
+ (stored : ∀ i : Fin n, m ((p 0).val+i.val) = Fin.ofNat _ (field i).val)
+ {rs : List (Report w)} (run : runSegment ((template SlotScatter.visit 0).instantiate w p).program 10
+ (some 0) m (List.replicate n []) = some rs) :
+ Reads (InColumn (p 0).val n) (eventLog rs) ∧ Writes (InColumn (p 1).val cap) (eventLog rs) :=
+ scatter_run_bounded regions (fun i => by rw [stored i]; exact (Nat.mod_le ..).trans_lt (field i).isLt)
+ (k := 0) (by simp) run
+
+/-- In the layout used by the slot builder, the append call's readable interval
+ends at the row base, and its writable interval begins after the owner stream. -/
+theorem appendFields {base A B deg : ℕ} (fit : base+A+(B+A)+(B+A)*deg < 2^w)
+ (hdw : deg < 2^w) {m : Memory w} {rs : List (Report w)}
+ (run : runSegment ((template collectPreimage 3).instantiate w (SlotSchedule.parameters w base A B deg)).program
+ 23 (some 0) m (List.replicate A []) = some rs) :
+ Reads (InColumn base (A+(B+A))) (eventLog rs) ∧
+ Writes (InColumn (base+A) ((B+A)+(B+A)*deg)) (eventLog rs) := by
+ let p := SlotSchedule.parameters w base A B deg
+ obtain ⟨h0,h1,h2,h3,h4,h5⟩ := parameter_values fit hdw
+ have reg : RowRegions p := ⟨by rw [h1,h0,h3], by rw [h3,h2,h5], by rw [h5,h2,h4]; omega⟩
+ obtain ⟨rd,wr⟩ := append_run reg run
+ constructor <;> intro a v ha
+ · have r := rd a v ha
+ simp only [AppendReads,InColumn,p,h1,h0,h3,h2] at r
+ unfold InColumn; omega
+ · have r := wr a v ha
+ simp only [AppendWrites,InColumn,p,h3,h2,h5,h4] at r
+ unfold InColumn; omega
+
+variable {E : Type*} [Fintype E] {A B : ℕ}
+
+/-- Bounds for scattering a rectangular endpoint table with its mathematical
+ordering. Only the forward part of the table is needed as input. -/
+theorem invertFields {deg : ℕ} (D : SlotSchedule.Directory E A B)
+ (hc : ∀ b, Fintype.card {e // D.owner e = b} = deg)
+ {p : Fin 2 → Word w} (regions : SlotScatter.Regions p (B*deg) A) {m : Memory w}
+ (bySlot : ∀ e, m ((p 0).val+(SlotSchedule.sortedFields D deg hc e).val) = Fin.ofNat _ (D.address e).val)
+ {rs : List (Report w)} (run : runSegment ((template SlotScatter.visit 0).instantiate w p).program
+ 10 (some 0) m (List.replicate (B*deg) []) = some rs) :
+ Reads (InColumn (p 0).val (B*deg)) (eventLog rs) ∧ Writes (InColumn (p 1).val A) (eventLog rs) := by
+ let order := SlotSchedule.sortedFields D deg hc
+ apply scatter_run regions (order.symm.toEmbedding.trans D.address) _ run
+ intro i
+ have he := bySlot (order.symm i)
+ change m ((p 0).val+(order (order.symm i)).val) = _ at he
+ rwa [order.apply_symm_apply] at he
+
+/-- Scattering immediately after the actual append pass uses the bounded entries
+that pass produced. Equality of the native reports identifies its physical output
+with the `PreimagesAt` postcondition from `fill_run`. -/
+theorem invertFields_after_append (D : SlotSchedule.Directory E A B) {base deg : ℕ}
+ (hdeg : 0 < deg) (hdw : deg < 2^w) (hc : ∀ b, Fintype.card {e // D.owner e = b} = deg)
+ (fit : base+A+(B+A)+(B+A)*deg+A < 2^w) {m : Memory w}
+ (owners : ∀ i : Word w, i.val < A → m (base+i.val) = D.wordOwner i)
+ (zero : ∀ u : Word w, u.val < B+A → m (base+A+u.val) = 0)
+ {fs ss : List (Report w)}
+ (fill : runSegment ((template collectPreimage 3).instantiate w (SlotSchedule.parameters w base A B deg)).program
+ 23 (some 0) m (List.replicate A []) = some fs)
+ (scatter : runSegment ((template SlotScatter.visit 0).instantiate w (SlotSchedule.scatterParameters w base A B deg)).program
+ 10 (some 0) (after m (eventLog fs)) (List.replicate (B*deg) []) = some ss) :
+ Reads (InColumn (base+A+(B+A)) (B*deg)) (eventLog ss) ∧
+ Writes (InColumn (base+A+(B+A)+(B+A)*deg) A) (eventLog ss) := by
+ obtain ⟨rs,hr,rows,_⟩ := SlotSchedule.fill_run D hdeg hdw (fun b => (hc b).le) (by omega) m owners zero
+ obtain rfl := Option.some.inj (fill.symm.trans hr)
+ let p := SlotSchedule.scatterParameters w base A B deg
+ have h0 : (p 0).val = base+A+(B+A) := Nat.mod_eq_of_lt (by omega)
+ have h1 : (p 1).val = base+A+(B+A)+(B+A)*deg := Nat.mod_eq_of_lt (by omega)
+ have hmul := Nat.mul_le_mul_right deg (Nat.le_add_right B A)
+ have reg : SlotScatter.Regions p (B*deg) A :=
+ ⟨by rw [h0]; omega, by rw [h1]; omega, Or.inl (by rw [h0,h1]; omega)⟩
+ rw [← h1,← h0]
+ apply invertFields D hc reg _ scatter
+ intro e
+ rw [h0]
+ simpa only [Equiv.symm_apply_apply] using SlotSchedule.rectangular_rows D base deg hc (by omega) hdw _ rows
+ (SlotSchedule.sortedFields D deg hc e)
+
+/-- A selected state's forward mate column is a permutation in its canonical
+base-port ordering. Its inverse pass reads and writes only those two columns. -/
+theorem baseInverse {a l : ℕ} (Y : Compression.State a l) {shift : ℕ} {m : Memory w}
+ {p : Fin 2 → Word w} (regions : SlotScatter.Regions p (Fintype.card Y.Base*2^a) (Fintype.card Y.Base*2^a))
+ (forward : ShrinkSlots.BaseForward Y (p 0).val shift m) {rs : List (Report w)}
+ (run : runSegment ((template SlotScatter.visit 0).instantiate w p).program 10
+ (some 0) m (List.replicate (Fintype.card Y.Base*2^a) []) = some rs) :
+ Reads (InColumn (p 0).val (Fintype.card Y.Base*2^a)) (eventLog rs) ∧
+ Writes (InColumn (p 1).val (Fintype.card Y.Base*2^a)) (eventLog rs) := by
+ let order := IncidenceDirectory.baseOrder Y
+ let mate := order.symm.trans (Y.slots.base.target.trans order)
+ apply scatter_run regions mate.toEmbedding _ run
+ intro i
+ have he := forward.mate (order.symm i)
+ change m ((p 0).val+(order (order.symm i)).val) = _ at he
+ rwa [order.apply_symm_apply] at he
+
+open SlotLevel
+
+/-- Read and write bounds for the append and invert phases of an actual shrinking
+level. The genuine and dummy reports determine the physical input to append,
+including all still-zero counters. The append reports then determine the actual
+source rows read by the inversion. -/
+theorem selected (s : Shape) (h : Heads) (D : SlotSchedule.Directory E (fields s) (owners s))
+ {mem : Memory w} (input : SlotSchedule.OwnerInput D (bank s h w .genuineOwners)
+ (bank s h w .dummyOwners) mem h.scratch (genuineCount s) (dummyCount s))
+ (hdeg : 0 < s.newDegree) (hdw : s.newDegree < 2^w)
+ (hc : ∀ b, Fintype.card {e // D.owner e = b} = s.newDegree)
+ (fit : stopAddress s h < 2^w)
+ (zero : ∀ u : Word w, u.val < owners s+fields s → mem (h.scratch+fields s+u.val) = 0)
+ {r : Reports w} (native : r.Native s h mem) :
+ (Reads (fun x => h.scratch ≤ x ∧ x < rowsHead s h) (eventLog r.append) ∧
+ Writes (fun x => h.scratch+fields s ≤ x ∧ x < inverseHead s h) (eventLog r.append)) ∧
+ (Reads (fun x => rowsHead s h ≤ x ∧ x < rowsHead s h+owners s*s.newDegree) (eventLog r.scatter) ∧
+ Writes (fun x => inverseHead s h ≤ x ∧ x < targetsHead s h) (eventLog r.scatter)) := by
+ obtain ⟨gr,dr,fill,scatter,_⟩ := native
+ have fit' : h.scratch+fields s+(owners s+fields s)+(owners s+fields s)*s.newDegree+fields s < 2^w := by
+ change targetsHead s h < 2^w
+ unfold stopAddress shiftsHead at fit; omega
+ obtain ⟨gs,ds,hg,hd,stored,frame,_⟩ := SlotSchedule.owner_table_run D _ _ mem input (by omega)
+ obtain rfl := Option.some.inj (gr.symm.trans hg.executed)
+ obtain rfl := Option.some.inj (dr.symm.trans hd.executed)
+ have counts (u : Word w) (hu : u.val < owners s+fields s) :
+ after (after mem (eventLog r.genuine)) (eventLog r.dummy) (h.scratch+fields s+u.val) = 0 :=
+ (frame _ (Or.inr (Nat.le_add_right _ _))).trans (zero u hu)
+ have append := appendFields (A := fields s) (B := owners s) (base := h.scratch) (deg := s.newDegree)
+ (by omega) hdw fill
+ have inverse := invertFields_after_append D hdeg hdw hc fit' stored counts fill scatter
+ simpa only [Reads,Writes,InColumn,rowsHead,inverseHead,targetsHead,Nat.add_assoc] using And.intro append inverse
+
+end CompressorRecords.SlotFillFootprint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotFinish.lean b/lean/OAI/Computability/VPVNP/CompressorSlotFinish.lean
new file mode 100644
index 0000000000..23d8646616
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotFinish.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.CompressorSlotMateColumns
+import OAI.Computability.VPVNP.CompressorSlotWidthState
+
+/-!
+# Building the selected shrinking state's incidence directory
+
+One native run produces the sorted endpoint and base tables. The following
+three scans invert and lift the base matching, and a final scan gathers the
+selected split widths. All six output columns use the exact canonical port
+numbers of the next compressor state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots.Build
+
+open Compression Compression.State Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion Slots SlotLevel SlotOwners SlotSchedule
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+/-- Reports for the nine passes that build the endpoint tables, lift the base matching, and
+gather the next state's widths. -/
+structure Passes (w : ℕ) where
+ /-- Reports for the five passes that order endpoint fields and recover the base matching and
+ displacements. -/
+ slots : Reports w
+ /-- Reports for inverting the base matching and writing the two directions of actual port
+ incidence. -/
+ mates : MateReports w
+ /-- Reports that gather the selected split widths for actual outgoing slots, including zero
+ widths for dummy slots. -/
+ widths : List (Report w)
+
+/-- All slot, mate, and width reports in the order their workers execute. -/
+def Passes.all {w : ℕ} (r : Passes w) := r.slots.all++r.mates.all++r.widths
+
+/-- Memory after applying the slot passes, the mate passes, and the final width scan. -/
+def Passes.final {w : ℕ} (r : Passes w) (m : Memory w) := after (r.mates.final (r.slots.final m)) (eventLog r.widths)
+
+/-- The three groups of reports arise from native slot, mate, and width executions on
+successive memory states. -/
+def Passes.Native {w : ℕ} (r : Passes w) (s : Shape) (h : Heads) (splitHead : ℕ) (m : Memory w) :=
+ let m₁ := r.slots.final m
+ let m₂ := r.mates.final m₁
+ r.slots.Native s h m ∧ r.mates.Native s h m₁ ∧
+ runSegment ((template SlotWidthScan.visit 0).instantiate w (widthBank s h splitHead w)).program 43 (some 0)
+ m₂ (List.replicate (actualCount s) []) = some r.widths
+
+/-- The slot and mate scans reach their prescribed stops and the width scan returns the actual
+port count. -/
+def Passes.Cursors {w : ℕ} (r : Passes w) (s : Shape) := r.slots.Cursors s ∧ r.mates.Cursors s ∧
+ endState (some 0) r.widths = some (Fin.ofNat _ (actualCount s))
+
+variable {a b g w : ℕ} {δ factor : ℝ} {k : Type*} [Field k]
+variable (X : State a (packingLaneBits a g))
+variable (B : FixedBlock k demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection B)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- All nine passes on a prepared shrinking level. The final representation
+feeds the ordinary incidence API and retains the source arrays. -/
+theorem from_prepared (h : Heads) (splitHead : ℕ) (mem : Memory w) (hdw : 2^b < 2^w) :
+ let s := levelShape (b := b) X
+ let l := selectedLayout X B sel
+ let P := X.packingData
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let lanes := bitWordFinEquiv g
+ let g₀ := bank s h w .genuineOwners
+ let d₀ := bank s h w .dummyOwners
+ let Y := X.shrinkNext B ready sel
+ GenuineTables P s.subdivisions X.baseIndex tags lanes l g₀ mem →
+ DummyTables X.baseIndex tags lanes (pad s) d₀ mem →
+ SlotWidthScan.SplitRows P s.subdivisions X.baseIndex tags lanes (branchWidth X B sel) splitHead mem →
+ h.oldArc+4*(oldBaseArcCount s.bases s.tags s.oldDegree s.colors*s.lanes) ≤ h.scratch →
+ h.role+8 ≤ h.scratch → h.subdivisions+4 ≤ h.scratch → h.nextSite+sites s ≤ h.scratch →
+ splitHead+(oldBaseArcCount s.bases s.tags s.oldDegree s.colors*s.lanes)*4*(∑t,s.subdivisions t) ≤ h.scratch →
+ finish s h < 2^w → (∀ u : Word w, u.val < owners s+fields s → mem (h.scratch+fields s+u.val)=0) →
+ ∃ r : Passes w, r.Native s h splitHead mem ∧ r.Cursors s ∧ (directory s h w).Represents Y (r.final mem) ∧
+ (∀ addr, addr < h.scratch ∨ finish s h ≤ addr → r.final mem addr=mem addr) ∧
+ RAMBuckets.cost Report.probes r.all = 6*genuineCount s+3*dummyCount s+5*fields s+
+ 3*(owners s*2^b)+8*baseArcs s+12*actualCount s := by
+ intro s l P tags lanes g₀ d₀ Y hg hp split ho hr hs hn hsplit fit zero
+ have h₀ : targetsHead s h+baseArcs s=shiftsHead s h := rfl
+ have h₁ : shiftsHead s h+baseArcs s=inverseBaseHead s h := rfl
+ have h₂ : inverseBaseHead s h+baseArcs s=outHead s h := rfl
+ have h₃ : outHead s h+actualCount s=inHead s h := rfl
+ have h₄ : inHead s h+actualCount s=widthHead s h := rfl
+ have h₅ : widthHead s h+actualCount s=finish s h := rfl
+ have hpre : h.scratch ≤ rowsHead s h := by unfold rowsHead; omega
+ have hrect : rowsHead s h+owners s*s.newDegree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.le_add_right _ _)) _
+ have htargets : inverseHead s h+fields s=targetsHead s h := rfl
+ have hstop : stopAddress s h=inverseBaseHead s h := rfl
+ obtain ⟨slot, sn, sc, tab, forward, sf, costS⟩ := next_run X B ready sel h mem hdw hg hp ho hr hs hn (by change stopAddress s h < 2^w; omega) zero
+ let m₁ := slot.final mem
+ obtain ⟨nb,na⟩ := next_counts X B ready sel
+ change Fintype.card Y.Base*2^b=baseArcs s at nb
+ change Fintype.card Y.Base*2^g*2^b=actualCount s at na
+ have hlw : 2^g < 2^w := hg.laneCount ▸ (g₀ 0).isLt
+ obtain ⟨mate,mn,mc,mates,mf,costM⟩ := writeMates Y s h m₁ forward nb na rfl rfl hdw hlw fit
+ let m₂ := mate.final m₁
+ have split' := SlotWidthScan.SplitRows.congr_below P s.subdivisions X.baseIndex tags lanes (m' := m₂)
+ split hsplit (fun addr haddr ↦ (mf addr (Or.inl (by omega))).trans (sf addr (Or.inl haddr)))
+ have oldRows (e) := tab.bySlot e
+ obtain ⟨ws,wn,wc,widths,wf,costW⟩ := width_run X B ready sel h splitHead m₂ hp.twoFits hdw hlw
+ (hg.subdivCount ▸ (g₀ 1).isLt) (hg.baseCount ▸ (g₀ 2).isLt) hsplit fit split' (fun e ↦ by
+ let D := slotDirectory P s.subdivisions X.baseIndex tags lanes l (pad := pad s)
+ have hD (v) : Fintype.card {x // D.owner x=v} = s.newDegree :=
+ (slotDirectory_degree P s.subdivisions X.baseIndex tags lanes (two_le_packingColors a) l v).trans (Nat.add_sub_of_le ready.degree_budget)
+ have he : (sortedFields D s.newDegree hD e).val < owners s*s.newDegree := (sortedFields D s.newDegree hD e).isLt
+ exact (mf (rowsHead s h+(sortedFields D s.newDegree hD e).val) (Or.inl (by omega))).trans (oldRows e))
+ let r : Passes w := ⟨slot,mate,ws⟩
+ change ∀ addr, addr < widthHead s h ∨ finish s h ≤ addr → r.final mem addr=m₂ addr at wf
+ have done : Stored s h Y (r.final mem) := by
+ constructor
+ · intro e; have he := (IncidenceDirectory.baseOrder Y e).isLt
+ exact (wf _ (Or.inl (by omega))).trans (mates.forward.mate e)
+ · intro e; have he := (IncidenceDirectory.baseOrder Y e).isLt
+ exact (wf _ (Or.inl (by omega))).trans (mates.baseIn e)
+ · intro e; have he := (IncidenceDirectory.baseOrder Y e).isLt
+ exact (wf _ (Or.inl (by omega))).trans (mates.forward.displacement e)
+ · intro e; have he := (IncidenceDirectory.actualOrder Y e).isLt
+ exact (wf _ (Or.inl (by omega))).trans (mates.actualOut e)
+ · intro e; have he := (IncidenceDirectory.actualOrder Y e).isLt
+ exact (wf _ (Or.inl (by omega))).trans (mates.actualIn e)
+ · exact widths
+ refine ⟨r,⟨sn,mn,wn⟩,⟨sc,mc,wc⟩,done.represents nb na fit,?_,?_⟩
+ · intro addr ha
+ have hsf : addr < h.scratch ∨ stopAddress s h ≤ addr := by omega
+ exact (wf addr (by omega)).trans ((mf addr (by omega)).trans (sf addr hsf))
+ · change RAMBuckets.cost Report.probes ((slot.all++mate.all)++ws) = _
+ change RAMBuckets.cost Report.probes slot.all = 6*genuineCount s+3*dummyCount s+5*fields s+3*(owners s*2^b)+5*baseArcs s at costS
+ change RAMBuckets.cost Report.probes ws = 4*actualCount s at costW
+ rw [RAMBuckets.cost_append,RAMBuckets.cost_append,costS,costM,costW]; ring
+
+end CompressorRecords.ShrinkSlots.Build
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotFrames.lean b/lean/OAI/Computability/VPVNP/CompressorSlotFrames.lean
new file mode 100644
index 0000000000..097ab75f41
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotFrames.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.CompressorRecordPreimageScan
+
+/-!
+# The persistent cursor and memory frame of the preimage pass
+
+Every successful call checks the owner and the current row length before its two
+writes. Thus a scan in one descriptor level preserves other levels' tables, even
+when the initial contents of the latter are arbitrary. The persistent cursor
+advances once per call, including in a partial scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ}
+
+private theorem collectPreimage_reject (pub : Fin 6 → Word w) (mem : Memory w) (i : Word w)
+ (bad : ¬ (i < pub 0 ∧ ownerAt pub mem i < pub 2 ∧ mem (countAt pub (ownerAt pub mem i)).val < pub 4)) :
+ let M := (template collectPreimage 3).instantiate w pub
+ execute M.program 23 (M.program.start i) mem [] = none := by
+ change execute ((template collectPreimage 3).instantiate w pub).program (1 + collectPreimage.length)
+ ⟨_, i, fun _ => 0, fun _ => 0⟩ mem [] = _
+ rw [execute_template, run_eq_trace, collectPreimage_invalid pub i _ mem bad]
+ rfl
+
+/-- The two writable intervals of the preimage pass are the count column and the
+rectangular row data. Space between these intervals is also preserved. -/
+def OutsidePreimageWrites (pub : Fin 6 → Word w) (addr : ℕ) : Prop :=
+ (addr < (pub 3).val ∨ (pub 3).val + (pub 2).val ≤ addr) ∧
+ (addr < (pub 5).val ∨ (pub 5).val + (pub 2).val * (pub 4).val ≤ addr)
+
+private theorem collectUpdate_frame {pub : Fin 6 → Word w} (regions : RowRegions pub)
+ (mem : Memory w) (i : Word w) (ho : ownerAt pub mem i < pub 2)
+ (hcap : mem (countAt pub (ownerAt pub mem i)).val < pub 4) (addr : ℕ)
+ (outside : OutsidePreimageWrites pub addr) : collectUpdate pub mem i addr = mem addr := by
+ let owner := ownerAt pub mem i
+ let length := mem (countAt pub owner).val
+ change owner.val < (pub 2).val at ho
+ change length.val < (pub 4).val at hcap
+ have hc := regions.countsBeforeRows
+ have hf := regions.rowsFit
+ have hb := (pub 5).isLt
+ have hcval : (countAt pub owner).val = (pub 3).val + owner.val := by
+ rw [countAt, Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ have hmul := Nat.mul_le_mul_right (pub 4).val (Nat.succ_le_of_lt ho)
+ rw [Nat.succ_mul] at hmul
+ have hrval : (rowAt pub owner + length).val = (pub 5).val + owner.val * (pub 4).val + length.val := by
+ rw [Fin.val_add, rowAt, Fin.val_add, Fin.val_mul, Nat.add_mod_mod,
+ Nat.mod_eq_of_lt (show (pub 5).val + owner.val * (pub 4).val < 2^w by omega),
+ Nat.mod_eq_of_lt (by omega)]
+ obtain ⟨hcount, hrow⟩ := outside
+ have ha : addr ≠ (countAt pub owner).val := by rw [hcval]; omega
+ have hd : addr ≠ (rowAt pub owner + length).val := by rw [hrval]; omega
+ change writeMemory (writeMemory mem (rowAt pub owner + length) i) (countAt pub owner) (length+1) addr = _
+ simp only [writeMemory, ite_eq_right ha, ite_eq_right hd]
+
+/-- Any successful native scan retains its exact end cursor and preserves each
+address outside the two writable intervals. This applies directly to the reports
+produced by `collectPreimages_run`. -/
+theorem collectPreimages_cursor_frame {pub : Fin 6 → Word w} (regions : RowRegions pub)
+ {mem : Memory w} {k steps : ℕ} {rs : List (Report w)}
+ (hrun : runSegment ((template collectPreimage 3).instantiate w pub).program 23
+ (some (Fin.ofNat (2^w) k)) mem (List.replicate steps []) = some rs) :
+ endState (some (Fin.ofNat (2^w) k)) rs = some (Fin.ofNat (2^w) (k+steps)) ∧
+ ∀ addr, OutsidePreimageWrites pub addr → after mem (eventLog rs) addr = mem addr := by
+ induction steps generalizing k mem rs with
+ | zero =>
+ change some [] = some rs at hrun
+ cases hrun
+ exact ⟨rfl, fun _ _ => rfl⟩
+ | succ steps ih =>
+ let i := Fin.ofNat (2^w) k
+ let owner := ownerAt pub mem i
+ let valid := i < pub 0 ∧ owner < pub 2 ∧ mem (countAt pub owner).val < pub 4
+ rw [List.replicate_succ, runSegment] at hrun
+ by_cases h : valid
+ · obtain ⟨hi, ho, hcap⟩ := h
+ rw [collectPreimage_native pub mem i hi ho hcap] at hrun
+ have hnext : i + 1 = Fin.ofNat (2^w) (k+1) := by
+ apply Fin.ext
+ simp [i, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod]
+ simp only [after_collectEvents, hnext, Option.map_eq_some_iff] at hrun
+ obtain ⟨tail, htail, rfl⟩ := hrun
+ obtain ⟨hs, hf⟩ := ih htail
+ refine ⟨?_, ?_⟩
+ · change endState (some (Fin.ofNat (2^w) (k+1))) tail = _
+ rw [hs, show k+1+steps = k+(steps+1) by omega]
+ · intro addr ha
+ change ((collectEvents pub mem i ++ eventLog tail).foldl update mem) addr = _
+ rw [List.foldl_append]
+ exact (hf addr ha).trans (collectUpdate_frame regions mem i ho hcap addr ha)
+ · rw [collectPreimage_reject pub mem i h] at hrun
+ cases hrun
+
+/-- In particular every cell in a previous or subsequent level's disjoint interval
+keeps its value through this pass. -/
+theorem collectPreimages_frame {pub : Fin 6 → Word w} (regions : RowRegions pub)
+ {mem : Memory w} {k steps : ℕ} {rs : List (Report w)}
+ (hrun : runSegment ((template collectPreimage 3).instantiate w pub).program 23
+ (some (Fin.ofNat (2^w) k)) mem (List.replicate steps []) = some rs) :
+ endState (some (Fin.ofNat (2^w) k)) rs = some (Fin.ofNat (2^w) (k+steps)) ∧
+ ∀ addr, addr < (pub 3).val ∨ (pub 5).val + (pub 2).val * (pub 4).val ≤ addr →
+ after mem (eventLog rs) addr = mem addr := by
+ obtain ⟨hs, hf⟩ := collectPreimages_cursor_frame regions hrun
+ refine ⟨hs, fun addr h => hf addr ?_⟩
+ have hc := regions.countsBeforeRows
+ unfold OutsidePreimageWrites
+ omega
+
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotIncidence.lean b/lean/OAI/Computability/VPVNP/CompressorSlotIncidence.lean
new file mode 100644
index 0000000000..ed3a3055a2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotIncidence.lean
@@ -0,0 +1,254 @@
+import OAI.Computability.VPVNP.CompressorSlotState
+import OAI.Computability.VPVNP.CompressorSlotOwnerPass
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-!
+# Expanding base incidence into the actual slot columns
+
+The forward scan reads the base mate and the source arc's displacement. The
+reverse scan first recovers the source from the inverse base permutation and
+then reads that source's displacement. In both directions the lane changes by
+one native XOR, since binary-vector translations are their own inverses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotIncidencePass
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression IncidenceDirectory SourceTransport
+
+variable {w a l : ℕ}
+
+/-- Public words are the degree, lane count, base permutation, displacement,
+and actual incidence output heads. The persistent word is the actual port. -/
+def visit (reverse : Bool) : List (Op 9 5) :=
+ [.stateWord 0, .publicWord 1 0, .publicWord 2 1,
+ .binary .div 3 0 1, .binary .mod 4 0 1, .binary .div 5 3 2,
+ .binary .mul 5 5 1, .binary .add 5 5 4, .binary .mod 3 3 2,
+ .publicWord 6 2, .binary .add 6 6 5, .read 6 6,
+ .publicWord 7 3, .binary .add 7 7 (if reverse then 6 else 5), .read 7 7,
+ .binary .bitXor 3 3 7, .binary .div 8 6 1, .binary .mul 8 8 2, .binary .add 8 8 3,
+ .binary .mul 8 8 1, .binary .mod 4 6 1, .binary .add 8 8 4,
+ .publicWord 7 4, .binary .add 7 7 0, .write 7 8, .constant 7 1, .binary .add 0 0 7]
+
+private abbrev divW := @BinaryOp.eval w .div
+private abbrev modW := @BinaryOp.eval w .mod
+
+variable (p : Fin 5 → Word w)
+
+private def base (i : Word w) :=
+ divW (divW i (p 0)) (p 1) * p 0 + modW i (p 0)
+
+private def lane (i : Word w) := modW (divW i (p 0)) (p 1)
+
+private def mate (m : Memory w) (i : Word w) := m (p 2 + base p i).val
+
+private def shiftAddr (reverse : Bool) (m : Memory w) (i : Word w) :=
+ p 3 + (if reverse then mate p m i else base p i)
+
+private def dest (reverse : Bool) (m : Memory w) (i : Word w) :=
+ let t := mate p m i
+ let sh := m (shiftAddr p reverse m i).val
+ (divW t (p 0) * p 1 + BinaryOp.bitXor.eval (lane p i) sh) * p 0 + modW t (p 0)
+
+/-- Trace of one forward or reverse incidence visit, reading a base mate and the source arc's
+displacement before writing the translated actual port. -/
+def events (reverse : Bool) (m : Memory w) (i : Word w) : List (Event w) :=
+ List.replicate 11 .tick ++ [.read (p 2 + base p i) (mate p m i), .tick, .tick,
+ .read (shiftAddr p reverse m i) (m (shiftAddr p reverse m i).val)] ++
+ List.replicate 9 .tick ++ [.write (p 4+i) (dest p reverse m i), .tick, .tick]
+
+theorem events_work (rev : Bool) (m : Memory w) (i : Word w) :
+ (events p rev m i).length = 27 ∧ countProbes (events p rev m i) = 3 := ⟨rfl,rfl⟩
+
+private theorem events_after (rev : Bool) (m : Memory w) (i : Word w) :
+ after m (events p rev m i) = writeMemory m (p 4+i) (dest p rev m i) := rfl
+
+set_option maxRecDepth 4096 in
+private theorem visit_trace (rev : Bool) (m : Memory w) (i : Word w) (rs : Regs w 9) :
+ ∃ out, trace p i (visit rev) rs m =
+ some (events p rev m i, out, after m (events p rev m i)) ∧ out 0 = i+1 := by
+ rw [events_after]
+ cases rev <;> simp (config := {decide := true}) [visit, events, dest, shiftAddr, mate, base, lane,
+ trace, Op.effect, BinaryOp.eval, divW, modW, Function.update] <;> rfl
+
+theorem native (rev : Bool) (m : Memory w) (i : Word w) :
+ let M := (template (visit rev) 0).instantiate w p
+ execute M.program 28 (M.program.start i) m [] = some ⟨events p rev m i, some (i+1)⟩ := by
+ obtain ⟨rs, ht, hv⟩ := visit_trace p rev m i (fun _ => 0)
+ let M := (template (visit rev) 0).instantiate w p
+ change execute M.program (1+(visit rev).length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [hv]
+
+private theorem unpack {x d : Word w} {hi lo : ℕ} (h : x.val = hi*d.val+lo) (hl : lo < d.val) :
+ (divW x d).val = hi ∧ (modW x d).val = lo := by
+ have hd := Nat.zero_lt_of_lt hl
+ constructor
+ · change (x.val/d.val) % _ = hi
+ rw [Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt),h,Nat.mul_comm hi,
+ Nat.mul_add_div hd,Nat.div_eq_of_lt hl,Nat.add_zero]
+ · change (x.val%d.val) % _ = lo
+ rw [Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt),h,Nat.mul_add_mod_of_lt hl]
+
+private theorem unpack_port (Y : State a l) (hd : (p 0).val = 2^a) (hl : (p 1).val = 2^l)
+ (room : Fintype.card Y.Base * 2^a ≤ 2^w) (e : (Y.Base × BitWord l) × Fin (2^a))
+ (i : Word w) (hi : i.val = (actualOrder Y e).val) :
+ (base p i).val = (baseOrder Y (e.1.1,e.2)).val ∧
+ (lane p i).val = (bitWordFinEquiv l e.1.2).val := by
+ have digits : i.val =
+ ((Y.baseIndex e.1.1).val * (p 1).val + (bitWordFinEquiv l e.1.2).val) * (p 0).val + e.2.val := by
+ rw [hi,actualOrder_val,hl,hd]
+ have hq := unpack digits (by rw [hd]; exact e.2.isLt)
+ have hv := unpack hq.1 (by rw [hl]; exact (bitWordFinEquiv l e.1.2).isLt)
+ refine ⟨?_,hv.2⟩
+ rw [base,Fin.val_add,Fin.val_mul,hv.1,hq.2,hd,Nat.mod_add_mod,← baseOrder_val Y (e.1.1,e.2)]
+ exact Nat.mod_eq_of_lt ((baseOrder Y _).isLt.trans_le room)
+
+/-- Each native visit reads a base mate and a source displacement, then writes
+the current actual port. The reverse visit uses the stored mate as its source
+index, so a range bound on that word suffices for both directions. -/
+theorem row_footprint (rev : Bool) (Y : State a l) (m : Memory w)
+ (hd : (p 0).val = 2^a) (hl : (p 1).val = 2^l)
+ (ht : (p 2).val + Fintype.card Y.Base*2^a ≤ (p 4).val)
+ (hs : (p 3).val + Fintype.card Y.Base*2^a ≤ (p 4).val)
+ (fit : (p 4).val + Fintype.card Y.Base*2^l*2^a ≤ 2^w)
+ (hm : ∀ e, (m ((p 2).val + (baseOrder Y e).val)).val < Fintype.card Y.Base * 2^a)
+ (j : ℕ) (hj : j < Fintype.card Y.Base * 2^l * 2^a) :
+ Reads (fun x ↦ ((p 2).val ≤ x ∧ x < (p 2).val + Fintype.card Y.Base * 2^a) ∨
+ ((p 3).val ≤ x ∧ x < (p 3).val + Fintype.card Y.Base * 2^a)) (events p rev m (Fin.ofNat _ j)) ∧
+ Writes (fun x ↦ (p 4).val ≤ x ∧ x < (p 4).val + Fintype.card Y.Base * 2^l * 2^a)
+ (events p rev m (Fin.ofNat _ j)) := by
+ let i := Fin.ofNat (2^w) j
+ let e := (actualOrder Y).symm ⟨j,hj⟩
+ let b := (e.1.1,e.2)
+ have hi : i.val = j := Nat.mod_eq_of_lt (by omega)
+ have he : (actualOrder Y e).val = j := congrArg Fin.val ((actualOrder Y).apply_symm_apply ⟨j,hj⟩)
+ have room := (p 4).isLt
+ have hb : (base p i).val = (baseOrder Y b).val :=
+ (unpack_port p Y hd hl (by omega) e i (hi.trans he.symm)).1
+ have b_lt := (baseOrder Y b).isLt
+ have atMate : (p 2 + base p i).val = (p 2).val + (baseOrder Y b).val := by
+ rw [Fin.val_add,hb,Nat.mod_eq_of_lt (by omega)]
+ have src_lt : (if rev then mate p m i else base p i).val < Fintype.card Y.Base * 2^a := by
+ cases rev
+ · simpa only [Bool.false_eq_true,ite_false,hb] using b_lt
+ · simpa only [ite_true,mate,atMate] using hm b
+ have atShift : (shiftAddr p rev m i).val =
+ (p 3).val + (if rev then mate p m i else base p i).val := by
+ rw [shiftAddr,Fin.val_add,Nat.mod_eq_of_lt (by omega)]
+ constructor <;> intro addr val mem
+ · change Event.read addr val ∈ events p rev m i at mem
+ simp [events] at mem
+ rcases mem with ⟨rfl,_⟩ | ⟨rfl,_⟩
+ · left; rw [atMate]; omega
+ · right; rw [atShift]; omega
+ · change Event.write addr val ∈ events p rev m i at mem
+ simp [events] at mem
+ rw [mem.1,Fin.val_add,hi,Nat.mod_eq_of_lt (by omega)]
+ omega
+
+private theorem read_row (rev : Bool) (Y : State a l) (m : Memory w)
+ (hd : (p 0).val = 2^a) (hl : (p 1).val = 2^l)
+ (ht : (p 2).val + Fintype.card Y.Base*2^a ≤ (p 4).val)
+ (hs : (p 3).val + Fintype.card Y.Base*2^a ≤ (p 4).val)
+ (fit : (p 4).val + Fintype.card Y.Base*2^l*2^a ≤ 2^w)
+ (hm : ∀ e, m ((p 2).val+(baseOrder Y e).val) =
+ Fin.ofNat _ (baseOrder Y ((if rev then Y.slots.base.target.symm else Y.slots.base.target) e)).val)
+ (hsh : ∀ e, m ((p 3).val+(baseOrder Y e).val) =
+ Fin.ofNat _ (bitWordFinEquiv l (Y.slots.displacement e)).val)
+ (e : (Y.Base × BitWord l) × Fin (2^a)) :
+ dest p rev m (Fin.ofNat _ (actualOrder Y e).val) =
+ Fin.ofNat _ (actualOrder Y ((if rev then Y.slots.actualGraph.target.symm else Y.slots.actualGraph.target) e)).val := by
+ rcases e with ⟨⟨v,g⟩,j⟩
+ let e := (v,j)
+ let t := (if rev then Y.slots.base.target.symm else Y.slots.base.target) e
+ let s := Y.slots.displacement (if rev then t else e)
+ let i := Fin.ofNat (2^w) (actualOrder Y ((v,g),j)).val
+ have hbase (f : Y.Base × Fin (2^a)) : (baseOrder Y f).val < 2^w := by
+ have := (baseOrder Y f).isLt
+ have := (p 4).isLt
+ omega
+ have hi : i.val = (actualOrder Y ((v,g),j)).val :=
+ Nat.mod_eq_of_lt (by have := (actualOrder Y ((v,g),j)).isLt; omega)
+ obtain ⟨hb,hlane⟩ := unpack_port p Y hd hl (by have := (p 4).isLt; omega) ((v,g),j) i hi
+ have hmate : mate p m i = Fin.ofNat _ (baseOrder Y t).val := by
+ rw [mate,Fin.val_add,hb,Nat.mod_eq_of_lt (by have := (baseOrder Y e).isLt; have := (p 4).isLt; omega)]
+ exact hm e
+ have htval : (mate p m i).val = (baseOrder Y t).val := by
+ rw [hmate,Fin.val_ofNat,Nat.mod_eq_of_lt (hbase t)]
+ have hsource : (if rev then mate p m i else base p i).val =
+ (baseOrder Y (if rev then t else e)).val := by cases rev <;> first | exact hb | exact htval
+ have hread : (m (shiftAddr p rev m i).val).val = (bitWordFinEquiv l s).val := by
+ rw [shiftAddr,Fin.val_add,hsource,Nat.mod_eq_of_lt (by
+ have := (baseOrder Y (if rev then t else e)).isLt; have := (p 4).isLt; omega),hsh,Fin.val_ofNat]
+ exact Nat.mod_eq_of_lt ((bitWordFinEquiv l s).isLt.trans (hl ▸ (p 1).isLt))
+ have hu := unpack (x := mate p m i) (d := p 0) (hi := (Y.baseIndex t.1).val) (lo := t.2.val)
+ (by rw [htval,baseOrder_val,hd]) (by rw [hd]; exact t.2.isLt)
+ have hnum : (actualOrder Y ((if rev then Y.slots.actualGraph.target.symm else Y.slots.actualGraph.target) ((v,g),j))).val =
+ ((Y.baseIndex t.1).val*2^l + (bitWordFinEquiv l (g+s)).val)*2^a + t.2.val := by
+ have neg (x : BitWord l) : -x = x := funext fun u ↦ CharTwo.neg_eq (x u)
+ cases rev <;> simp [e,t,s,LiftedSlots.actualGraph_target,LiftedSlots.actualGraph_target_symm,
+ actualOrder_val,sub_eq_add_neg,neg]
+ apply Fin.ext
+ change (dest p rev m i).val = _ % _
+ rw [hnum,dest,Fin.val_add,Fin.val_mul,Fin.val_add,Fin.val_mul,hu.1,hu.2,hl,hd,bitWordFinEquiv_add_val]
+ change (((_ % _ + (((lane p i).val ^^^ _) % _)) % _ * _ % _ + _) % _) = _
+ rw [hlane,hread]
+ simp only [Nat.mod_add_mod,Nat.add_mod_mod,Nat.mod_mul_mod]
+
+/-- Construct either actual incidence column over all positions, lanes and
+slots. Every call uses two reads and one write, and preserves the input arrays. -/
+theorem run (reverse : Bool) (Y : State a l) (p : Fin 5 → Word w) (m : Memory w)
+ (hd : (p 0).val = 2^a) (hl : (p 1).val = 2^l)
+ (ht : (p 2).val + Fintype.card Y.Base*2^a ≤ (p 4).val)
+ (hs : (p 3).val + Fintype.card Y.Base*2^a ≤ (p 4).val)
+ (fit : (p 4).val + Fintype.card Y.Base*2^l*2^a ≤ 2^w)
+ (hm : ∀ e, m ((p 2).val+(baseOrder Y e).val) =
+ Fin.ofNat _ (baseOrder Y ((if reverse then Y.slots.base.target.symm else Y.slots.base.target) e)).val)
+ (hsh : ∀ e, m ((p 3).val+(baseOrder Y e).val) =
+ Fin.ofNat _ (bitWordFinEquiv l (Y.slots.displacement e)).val) :
+ let n := Fintype.card Y.Base*2^l*2^a
+ let M := (template (visit reverse) 0).instantiate w p
+ ∃ rs, runSegment M.program 28 (some 0) m (List.replicate n []) = some rs ∧
+ endState (some 0) rs = some (Fin.ofNat _ n) ∧
+ (∀ e, after m (eventLog rs) ((p 4).val+(actualOrder Y e).val) =
+ Fin.ofNat _ (actualOrder Y ((if reverse then Y.slots.actualGraph.target.symm else Y.slots.actualGraph.target) e)).val) ∧
+ (∀ addr, addr < (p 4).val ∨ (p 4).val+n ≤ addr → after m (eventLog rs) addr = m addr) ∧
+ RAMBuckets.cost Report.probes rs = 4*n := by
+ intro n M
+ let order := actualOrder Y
+ let f := if reverse then Y.slots.actualGraph.target.symm else Y.slots.actualGraph.target
+ let value := fun j : ℕ ↦ Fin.ofNat (2^w) (order (f (order.symm (Fin.ofNat n j)))).val
+ obtain ⟨rs, hr, hc, hvals, hframe, _, _, hcost⟩ := SlotOwnerPass.run M.program 28 3 27 (p 4).val 0 n value m
+ (by simpa using fit) (by
+ intro j _ hj mem frame
+ have hjn : j < n := by simpa using hj
+ let u : Fin n := ⟨j,hjn⟩
+ let e := order.symm u
+ have he : (actualOrder Y e).val = j := congrArg Fin.val (order.apply_symm_apply u)
+ have hu : Fin.ofNat n j = u := Fin.ext (Nat.mod_eq_of_lt hjn)
+ have hv := read_row p reverse Y mem hd hl ht hs fit (fun z ↦ by
+ have := (baseOrder Y z).isLt; rw [frame _ (.inl (by omega))]; exact hm z) (fun z ↦ by
+ have := (baseOrder Y z).isLt; rw [frame _ (.inl (by omega))]; exact hsh z) e
+ rw [he] at hv
+ have hval : dest p reverse mem (Fin.ofNat _ j) = value j := by simpa only [value,hu] using hv
+ have hnext : Fin.ofNat (2^w) j + 1 = Fin.ofNat _ (j+1) := by
+ apply Fin.ext; simp [Fin.val_add,Nat.mod_add_mod,Nat.add_mod_mod]
+ have haddr : p 4 + Fin.ofNat _ j = Fin.ofNat _ ((p 4).val+j) := by
+ apply Fin.ext; simp [Fin.val_add,Nat.add_mod_mod]
+ exact ⟨events p reverse mem _,by rw [native,hnext],by rw [events_after,haddr,hval],
+ (events_work ..).2,(events_work ..).1⟩)
+ refine ⟨rs,hr,by simpa using hc,?_,fun addr ha ↦ hframe addr (by omega),by simpa using hcost⟩
+ intro e
+ have he := (order e).isLt
+ have hu : Fin.ofNat n (order e).val = order e := Fin.ext (Nat.mod_eq_of_lt he)
+ simpa only [value,hu,Equiv.symm_apply_apply] using hvals (order e).val (Nat.zero_le _) (by simpa only [Nat.zero_add] using he)
+
+end CompressorRecords.SlotIncidencePass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotLevel.lean b/lean/OAI/Computability/VPVNP/CompressorSlotLevel.lean
new file mode 100644
index 0000000000..aa4baf5f4e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotLevel.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.CompressorSlotPipeline
+import OAI.Computability.VPVNP.CompressorSlotOwnerDirectory
+import OAI.Computability.VPVNP.CompressorSlotBaseScan
+
+/-!
+# The shrinking level's slot directory
+
+The current level supplies the old-arc records, the chosen layout's role
+table, the fixed subdivision counts and the cyclic tag-successor table.
+From the current level counts one computes all five native pass frames.
+The last two arrays are the next graph's base-slot matching and displacement.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotLevel
+
+open Compression Compression.PackingData Compression.SurvivingSlots Slots SlotSchedule SlotOwners
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+/-- Counts at a shrinking level. The four subdivisions are chosen for the new degree. -/
+structure Shape where
+ /-- Number of old base vertices whose tags form the next level's packed base vertices. -/
+ bases : ℕ
+ /-- Number of tag values per old base vertex in the packed graph. -/
+ tags : ℕ
+ /-- Number of residual lanes over each packed base vertex. -/
+ lanes : ℕ
+ /-- Degree of the input slot graph used to enumerate the old arc records. -/
+ oldDegree : ℕ
+ /-- Number of bits in an old position's color mask. -/
+ colors : ℕ
+ /-- Number of surviving subdivisions for each of the four role edge types. -/
+ subdivisions : Fin 4 → ℕ
+ /-- Target degree of the next graph after padding with dummy slots. -/
+ newDegree : ℕ
+
+/-- Source tables selected by the current branch and the start of fresh scratch space. -/
+structure Heads where
+ /-- Start of the old arc records containing three role sites and a CD indicator for each arc. -/
+ oldArc : ℕ
+ /-- Start of the eight-entry table selecting a source and target role for each edge type. -/
+ role : ℕ
+ /-- Start of the four published subdivision counts indexed by edge type. -/
+ subdivisions : ℕ
+ /-- Start of the table of cyclic tag successors used to choose dummy target sites. -/
+ nextSite : ℕ
+ /-- First fresh word for constructing the endpoint owner, count, row, and inverse tables. -/
+ scratch : ℕ
+
+variable (s : Shape) (h : Heads)
+
+/-- Number of packed sites across all base vertices, tags, and residual lanes. -/
+def sites := s.bases*(s.tags*s.lanes)
+/-- Number of dummy slots per packed site needed to bring the surviving degree up to the new
+degree. -/
+def pad := s.newDegree-survivingDegree s.oldDegree s.colors s.subdivisions
+
+/-- Number of endpoint fields scanned in the genuine candidate range, counting both ends even
+for candidates that decode to holes. -/
+def genuineCount := (keyCount s.bases s.tags s.oldDegree s.colors s.subdivisions * s.lanes)*2
+/-- Number of endpoint fields in the dummy range, two per padding slot at every packed site. -/
+def dummyCount := (sites s * pad s)*2
+/-- Total number of absolute endpoint field addresses in the genuine candidate and dummy
+ranges. -/
+def fields := RecordCount s.bases s.tags s.lanes s.oldDegree s.colors (pad s) s.subdivisions*2
+/-- Number of real endpoint owners, with separate outgoing and incoming rows at each packed
+site. -/
+def owners := sites s*2
+/-- Number of outgoing slots over packed base vertices, before lifting the matching to residual
+lanes. -/
+def baseArcs := s.bases*s.tags*s.newDegree
+
+/-- First word of the rectangular endpoint rows, after the field owner column and all append
+counters. -/
+def rowsHead := h.scratch+fields s+(owners s+fields s)
+/-- Start of the table mapping absolute field IDs back to rectangular slots, after the reserved
+row space. -/
+def inverseHead := rowsHead s h+(owners s+fields s)*s.newDegree
+/-- Start of the base-target column, immediately after the inverse field table. -/
+def targetsHead := inverseHead s h+fields s
+/-- Start of the base arc displacement column, immediately after the base targets. -/
+def shiftsHead := targetsHead s h+baseArcs s
+/-- First free address after the base-target and displacement columns built by the five slot
+passes. -/
+def stopAddress := shiftsHead s h+baseArcs s
+
+theorem counts_add : genuineCount s+dummyCount s = fields s := by
+ dsimp [genuineCount,dummyCount,sites,fields,RecordCount]; ring
+
+/-- Pass order used by the descriptor controller. -/
+inductive Phase where
+ | genuineOwners | dummyOwners | appendFields | invertFields | baseMatching
+ deriving DecidableEq
+
+/-- Exclusive cursor stop for the selected owner, append, inverse, or base-matching scan. -/
+def limit : Phase → ℕ
+ | .genuineOwners => genuineCount s
+ | .dummyOwners => dummyCount s
+ | .appendFields => fields s
+ | .invertFields => owners s*s.newDegree
+ | .baseMatching => baseArcs s
+
+/-- Number of public parameter words required by the worker for each slot phase. -/
+abbrev arity : Phase → ℕ
+ | .genuineOwners => 8
+ | .dummyOwners => 3
+ | .appendFields | .baseMatching => 6
+ | .invertFields => 2
+
+/-- The five public banks. Each worker starts its own cursor at zero. -/
+def bank (w : ℕ) : (phase : Phase) → Fin (arity phase) → Word w
+ | .genuineOwners => (Fin.ofNat (2^w)) ∘ ![s.lanes, ∑ t, s.subdivisions t,
+ oldBaseArcCount s.bases s.tags s.oldDegree s.colors, h.oldArc, h.role, h.subdivisions, owners s, h.scratch]
+ | .dummyOwners => (Fin.ofNat (2^w)) ∘ ![pad s, h.nextSite, h.scratch+genuineCount s]
+ | .appendFields => SlotSchedule.parameters w h.scratch (fields s) (owners s) s.newDegree
+ | .invertFields => SlotSchedule.scatterParameters w h.scratch (fields s) (owners s) s.newDegree
+ | .baseMatching => (Fin.ofNat (2^w)) ∘ ![s.newDegree,s.lanes,rowsHead s h,inverseHead s h,targetsHead s h,shiftsHead s h]
+
+/-- The controller row begins with the dispatch tag, initial cursor and exclusive stop. -/
+def frame {w : ℕ} (tag : Phase → Word w) (phase : Phase) : List (Word w) :=
+ tag phase :: 0 :: Fin.ofNat _ (limit s phase) :: List.ofFn (bank s h w phase)
+
+variable {V H Tag L : Type*} {d c N J nL degree w : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- Assemble the array-scan input from the paper's actual selected role and
+original-arc words, using only the four numerical input-region bounds. -/
+theorem input_of_tables (layout : Bool) (mem : Memory w) (h : Heads) :
+ let s : Shape := ⟨N,J,nL,d,c,subdiv,degree⟩
+ let g := bank s h w .genuineOwners
+ let p := bank s h w .dummyOwners
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad s)
+ GenuineTables P subdiv vertices tags lanes layout g mem → DummyTables vertices tags lanes (pad s) p mem →
+ h.oldArc+4*(oldBaseArcCount N J d c*nL) ≤ h.scratch → h.role+8 ≤ h.scratch →
+ h.subdivisions+4 ≤ h.scratch → h.nextSite+sites s ≤ h.scratch → stopAddress s h < 2^w →
+ OwnerInput D g p mem h.scratch (genuineCount s) (dummyCount s) := by
+ intro s g p D hg hp hold hrole hsub hnext fit
+ have hstop : h.scratch+fields s ≤ stopAddress s h := by
+ unfold stopAddress shiftsHead targetsHead inverseHead rowsHead; omega
+ have hf : h.scratch+fields s < 2^w := hstop.trans_lt fit
+ have counts := counts_add s
+ have start : (g 7).val = h.scratch := Nat.mod_eq_of_lt (by omega : h.scratch < 2^w)
+ have startD : (p 2).val = h.scratch+genuineCount s := Nat.mod_eq_of_lt (by omega : h.scratch+genuineCount s < 2^w)
+ have old : (g 3).val = h.oldArc := Nat.mod_eq_of_lt (by omega : h.oldArc < 2^w)
+ have role : (g 4).val = h.role := Nat.mod_eq_of_lt (by omega : h.role < 2^w)
+ have sub : (g 5).val = h.subdivisions := Nat.mod_eq_of_lt (by omega : h.subdivisions < 2^w)
+ have next : (p 1).val = h.nextSite := Nat.mod_eq_of_lt (by omega : h.nextSite < 2^w)
+ refine ⟨counts,start,startD,?_,?_,?_,?_⟩
+ · intro i hi a ha; rw [← start]
+ exact genuineInputs_before P subdiv vertices tags lanes hg (g 7)
+ (by rw [old,start]; exact hold) (by rw [role,start]; exact hrole) (by rw [sub,start]; exact hsub) i hi a ha
+ · intro i hi; rw [← start]
+ exact dummyInput_before vertices tags lanes hp (g 7) (by rw [next,start]; exact hnext) i hi
+ · intro i hi
+ exact genuine_directory P subdiv vertices tags lanes layout g mem hg (Fin.ofNat _ i) ((Nat.mod_le ..).trans_lt hi)
+ · intro i hi
+ have hv : (Fin.ofNat (2^w) i).val = i := Nat.mod_eq_of_lt (by omega)
+ have h := dummy_directory P subdiv vertices tags lanes (pad := pad s) layout p mem hp (Fin.ofNat _ i)
+ ((Nat.mod_le ..).trans_lt hi) (by change fields s ≤ _; omega)
+ rw [hv] at h
+ exact h
+
+end CompressorRecords.SlotLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotLevelRecipe.lean b/lean/OAI/Computability/VPVNP/CompressorSlotLevelRecipe.lean
new file mode 100644
index 0000000000..e43dba327f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotLevelRecipe.lean
@@ -0,0 +1,310 @@
+import OAI.Computability.VPVNP.CompressorSlotLevel
+import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe
+import Mathlib.Data.List.OfFn
+
+/-!
+# Native row planners for the five shrinking slot passes
+
+The template fixes the degree, consumed colors, tag count and subdivisions
+for this substep. The planner reads the current base and residual lane counts,
+the heads of the selected input tables, and the start of scratch space. It
+computes each pass's exclusive stop and every address in its public bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotLevel.Recipe
+
+open BurstRAM BurstRAM.PrivateRAM PhaseRecipe
+open scoped Fin.CommRing
+open Compression Compression.PackingData Compression.SurvivingSlots Slots SlotOwners
+
+/-- Constants in a shrinking substep's fixed finite instruction template. -/
+structure Template where
+ /-- Fixed number of tags per base vertex used by this shrinking substep's planner. -/
+ tags : ℕ
+ /-- Input slot degree compiled into the planner's old arc counts. -/
+ oldDegree : ℕ
+ /-- Fixed number of old color-mask bits used to size the genuine candidate range. -/
+ colors : ℕ
+ /-- Fixed subdivision count for each role edge type, used to size the candidate range and
+ determine padding. -/
+ subdivisions : Fin 4 → ℕ
+ /-- Padded output degree compiled into the slot rows and base-matching phase. -/
+ newDegree : ℕ
+
+/-- Combine the template constants with the current base and lane counts to obtain the slot
+level shape. -/
+def Template.shape (T : Template) (bases lanes : ℕ) : Shape :=
+ ⟨bases, T.tags, lanes, T.oldDegree, T.colors, T.subdivisions, T.newDegree⟩
+
+/-- Current level counts and physical heads. The role table contains the
+eight entries materialized for the chosen layout. -/
+structure Inputs where
+ /-- Planner expression yielding the current number of base vertices. -/
+ bases : Expr
+ /-- Planner expression yielding the number of residual lanes per packed base. -/
+ lanes : Expr
+ /-- Planner expression locating the selected old arc records with their role sites and CD
+ flags. -/
+ oldArc : Expr
+ /-- Planner expression locating the chosen layout's eight endpoint role selectors. -/
+ role : Expr
+ /-- Planner expression locating the published subdivision counts for the four edge types. -/
+ subdivisions : Expr
+ /-- Planner expression locating the cyclic site successor table used by dummy slots. -/
+ nextSite : Expr
+ /-- Planner expression yielding the first fresh address for the slot directory. -/
+ scratch : Expr
+
+variable {w : ℕ}
+
+/-- The current expressions read the two shape scalars and the five array heads. -/
+structure Reads (I : Inputs) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w)
+ (bases lanes : ℕ) (h : Heads) : Prop where
+ bases_eq : I.bases.eval pub state m = (bases : Word w)
+ lanes_eq : I.lanes.eval pub state m = (lanes : Word w)
+ oldArc_eq : I.oldArc.eval pub state m = (h.oldArc : Word w)
+ role_eq : I.role.eval pub state m = (h.role : Word w)
+ subdivisions_eq : I.subdivisions.eval pub state m = (h.subdivisions : Word w)
+ nextSite_eq : I.nextSite.eval pub state m = (h.nextSite : Word w)
+ scratch_eq : I.scratch.eval pub state m = (h.scratch : Word w)
+
+/-- Derived counts and array addresses used by the native passes. -/
+structure Counts (α : Type) where
+ /-- Total number of packed sites including all residual lanes. -/
+ sites : α
+ /-- Number of dummy outgoing slots needed at each packed site to reach the target degree. -/
+ pad : α
+ /-- Number of old arc identifiers before adding the residual lane digit. -/
+ oldBaseArcs : α
+ /-- Size of the genuine candidate arc range across edge types, subdivisions, and residual
+ lanes, including holes. -/
+ genuineArcs : α
+ /-- Number of source and target fields in the genuine candidate range. -/
+ genuine : α
+ /-- Number of source and target fields in the dummy arc range. -/
+ dummy : α
+ /-- Total number of field addresses covered by the owner and append scans. -/
+ fields : α
+ /-- Count of real site-and-side owners before allocating private rows for holes. -/
+ owners : α
+ /-- Number of packed base ports for which the matching scan computes a target and
+ displacement. -/
+ baseArcs : α
+ /-- Starting address of the rectangular field rows following the append counters. -/
+ rows : α
+ /-- Starting address of the inverse table that maps each real endpoint field to its
+ rectangular slot. -/
+ inverse : α
+ /-- Starting address of the matching target column indexed by packed base port. -/
+ targets : α
+ /-- Starting address of the lane displacement column indexed by packed base port. -/
+ shifts : α
+ /-- First address after the slot directory's base displacement column. -/
+ stopAddress : α
+
+/-- Compile only the level-dependent arithmetic. Subtraction, division and
+exponentiation inside template constants take place when building the fixed program. -/
+def counts (T : Template) (I : Inputs) : Counts Expr :=
+ let sites := I.bases.mul ((.lit T.tags : Expr).mul I.lanes)
+ let oldBaseArcs := I.bases.mul (.lit (T.tags * (T.oldDegree * (2 ^ T.colors * T.oldDegree))))
+ let pad := Expr.lit (T.newDegree - survivingDegree T.oldDegree T.colors T.subdivisions)
+ let keys := (.lit 4 : Expr).mul (oldBaseArcs.mul (.lit (∑ t, T.subdivisions t)))
+ let genuineArcs := keys.mul I.lanes
+ let dummyArcs := sites.mul pad
+ let fields := (genuineArcs.add dummyArcs).mul (.lit 2)
+ let owners := sites.mul (.lit 2)
+ let baseArcs := (I.bases.mul (.lit T.tags)).mul (.lit T.newDegree)
+ let rows := (I.scratch.add fields).add (owners.add fields)
+ let inverse := rows.add ((owners.add fields).mul (.lit T.newDegree))
+ let targets := inverse.add fields
+ let shifts := targets.add baseArcs
+ ⟨sites,pad,oldBaseArcs,genuineArcs,genuineArcs.mul (.lit 2),dummyArcs.mul (.lit 2),
+ fields,owners,baseArcs,rows,inverse,targets,shifts,shifts.add baseArcs⟩
+
+/-- Apply the same conversion to every derived count and address, as when evaluating planner
+expressions or encoding natural values as words. -/
+def Counts.map {α β : Type} (f : α → β) (c : Counts α) : Counts β :=
+ ⟨f c.sites, f c.pad, f c.oldBaseArcs, f c.genuineArcs, f c.genuine, f c.dummy, f c.fields,
+ f c.owners, f c.baseArcs, f c.rows, f c.inverse, f c.targets, f c.shifts, f c.stopAddress⟩
+
+/-- Calculate the natural-number slot counts and physical table addresses from the level shape
+and input heads. -/
+def countValues (s : Shape) (h : Heads) : Counts ℕ :=
+ ⟨sites s, pad s, oldBaseArcCount s.bases s.tags s.oldDegree s.colors,
+ keyCount s.bases s.tags s.oldDegree s.colors s.subdivisions * s.lanes,
+ genuineCount s, dummyCount s, fields s, owners s, baseArcs s, rowsHead s h,
+ inverseHead s h, targetsHead s h, shiftsHead s h, stopAddress s h⟩
+
+theorem eval_counts (T : Template) (I : Inputs) {pub : Fin 5 → Word w} {state : Word w} {m : Memory w}
+ {bases lanes : ℕ} {h : Heads} (read : Reads I pub state m bases lanes h) :
+ (counts T I).map (fun e ↦ e.eval pub state m) =
+ (countValues (T.shape bases lanes) h).map (fun n : ℕ ↦ (n : Word w)) := by
+ simp only [counts, Counts.map, countValues, Expr.mul, Expr.add, Expr.eval, BinaryOp.eval,
+ read.bases_eq, read.lanes_eq, read.scratch_eq, ← Nat.cast_mul, ← Nat.cast_add]
+ rfl
+
+/-- Planner expression for the selected slot worker's exclusive cursor bound. -/
+def stop (T : Template) (I : Inputs) : SlotLevel.Phase → Expr
+ | .genuineOwners => (counts T I).genuine
+ | .dummyOwners => (counts T I).dummy
+ | .appendFields => (counts T I).fields
+ | .invertFields => (counts T I).owners.mul (.lit T.newDegree)
+ | .baseMatching => (counts T I).baseArcs
+
+/-- Public parameter expressions for the selected worker, in the order of its native parameter
+bank. -/
+def params (T : Template) (I : Inputs) : (p : SlotLevel.Phase) → Fin (arity p) → Expr
+ | .genuineOwners => ![I.lanes, .lit (∑ t, T.subdivisions t), (counts T I).oldBaseArcs,
+ I.oldArc, I.role, I.subdivisions, (counts T I).owners, I.scratch]
+ | .dummyOwners => ![(counts T I).pad, I.nextSite, I.scratch.add (counts T I).genuine]
+ | .appendFields =>
+ let c := counts T I
+ ![c.fields, I.scratch, c.owners.add c.fields, I.scratch.add c.fields, .lit T.newDegree, c.rows]
+ | .invertFields => ![(counts T I).rows, (counts T I).inverse]
+ | .baseMatching =>
+ let c := counts T I
+ ![.lit T.newDegree, I.lanes, c.rows, c.inverse, c.targets, c.shifts]
+
+/-- Form the selected worker's descriptor recipe from its tag, zero starting cursor, stop
+expression, and public parameters. -/
+def phase (tag : SlotLevel.Phase → ℕ) (T : Template) (I : Inputs) (p : SlotLevel.Phase) :
+ PhaseRecipe.Phase (arity p) := ⟨tag p, .lit 0, stop T I p, params T I p⟩
+
+variable (tag : SlotLevel.Phase → ℕ) (T : Template) (I : Inputs) (p : SlotLevel.Phase)
+variable {pub : Fin 5 → Word w} {state : Word w} {m : Memory w} {bases lanes : ℕ} {h : Heads}
+variable (read : Reads I pub state m bases lanes h)
+
+include read
+
+theorem eval_stop :
+ (stop T I p).eval pub state m = Fin.ofNat (2^w) (limit (T.shape bases lanes) p) := by
+ have hc := eval_counts T I read
+ cases p
+ case genuineOwners => exact congrArg Counts.genuine hc
+ case dummyOwners => exact congrArg Counts.dummy hc
+ case appendFields => exact congrArg Counts.fields hc
+ case invertFields =>
+ change ((counts T I).owners.eval pub state m) * (T.newDegree : Word w) = _
+ rw [show (counts T I).owners.eval pub state m = (owners (T.shape bases lanes) : Word w) from
+ congrArg Counts.owners hc, ← Nat.cast_mul]
+ rfl
+ case baseMatching => exact congrArg Counts.baseArcs hc
+
+theorem eval_params (i : Fin (arity p)) :
+ (params T I p i).eval pub state m = bank (T.shape bases lanes) h w p i := by
+ let s := T.shape bases lanes
+ have hc := eval_counts T I read
+ have c (f : Counts (Word w) → Word w) := congrArg f hc
+ have old : (counts T I).oldBaseArcs.eval pub state m = (oldBaseArcCount s.bases s.tags s.oldDegree s.colors : Word w) := c Counts.oldBaseArcs
+ have own : (counts T I).owners.eval pub state m = (owners s : Word w) := c Counts.owners
+ have pad' : (counts T I).pad.eval pub state m = (pad s : Word w) := c Counts.pad
+ have genuine : (counts T I).genuine.eval pub state m = (genuineCount s : Word w) := c Counts.genuine
+ have fields' : (counts T I).fields.eval pub state m = (fields s : Word w) := c Counts.fields
+ have rows : (counts T I).rows.eval pub state m = (rowsHead s h : Word w) := c Counts.rows
+ have inv : (counts T I).inverse.eval pub state m = (inverseHead s h : Word w) := c Counts.inverse
+ have targets : (counts T I).targets.eval pub state m = (targetsHead s h : Word w) := c Counts.targets
+ have shifts : (counts T I).shifts.eval pub state m = (shiftsHead s h : Word w) := c Counts.shifts
+ have plus {a b : Expr} {x y : ℕ} (hx : a.eval pub state m = (x : Word w))
+ (hy : b.eval pub state m = (y : Word w)) : (a.add b).eval pub state m = ((x+y : ℕ) : Word w) := by
+ change a.eval pub state m + b.eval pub state m = _
+ rw [hx, hy, Nat.cast_add]
+ cases p with
+ | genuineOwners =>
+ fin_cases i
+ exacts [read.lanes_eq, rfl, old, read.oldArc_eq, read.role_eq, read.subdivisions_eq, own, read.scratch_eq]
+ | dummyOwners =>
+ fin_cases i
+ exacts [pad', read.nextSite_eq, plus read.scratch_eq genuine]
+ | appendFields =>
+ fin_cases i
+ exacts [fields', read.scratch_eq, plus own fields', plus read.scratch_eq fields', rfl, rows]
+ | invertFields =>
+ fin_cases i
+ exacts [rows, inv]
+ | baseMatching =>
+ fin_cases i
+ exacts [rfl, read.lanes_eq, rows, inv, targets, shifts]
+
+/-- Exact words of the compiled planner at the worker's own arity. -/
+theorem recipe_words :
+ (phase tag T I p).recipe.words pub state m =
+ frame (T.shape bases lanes) h (fun q ↦ (tag q : Word w)) p := by
+ rw [PhaseRecipe.recipe_words]
+ change _ :: _ :: (stop T I p).eval pub state m :: List.ofFn (fun i ↦ (params T I p i).eval pub state m) =
+ _ :: _ :: _ :: List.ofFn _
+ rw [eval_stop T I p read, show (fun i ↦ (params T I p i).eval pub state m) =
+ bank (T.shape bases lanes) h w p from funext (eval_params T I p read)]
+ rfl
+
+/-- The cursor stop also equals the natural count when that count fits in one word. -/
+theorem stop_val (fit : limit (T.shape bases lanes) p < 2^w) :
+ ((phase tag T I p).stop.eval pub state m).val = limit (T.shape bases lanes) p := by
+ change ((stop T I p).eval pub state m).val = _
+ rw [eval_stop T I p read]
+ exact Nat.mod_eq_of_lt fit
+
+/-- Extend a slot phase recipe to the scheduler's common arity by appending zero parameter
+words. -/
+def padded (g : ℕ) (room : arity p ≤ g) : PhaseRecipe.Phase g :=
+ PhaseRecipe.Phase.ofParams room (tag p) (.lit 0) (stop T I p) (params T I p)
+
+omit read in
+private theorem ofFn_padded {α : Type} {k g : ℕ} (f : Fin k → α) (z : α) (room : k ≤ g) :
+ List.ofFn (fun i : Fin g ↦ if h : i.val < k then f ⟨i.val,h⟩ else z) =
+ List.ofFn f ++ List.replicate (g-k) z := by
+ obtain ⟨l,rfl⟩ := Nat.exists_eq_add_of_le room
+ rw [Nat.add_sub_cancel_left, ← List.ofFn_const l z, ← List.ofFn_fin_append]
+ congr 1
+ funext i
+ cases i using Fin.addCases with
+ | left j => simp [j.isLt]
+ | right j => simp
+
+omit read in
+/-- Padding a native phase only appends zero words to its parameter row. -/
+theorem pad_phase_words {k g : ℕ} (room : k ≤ g) (P : PhaseRecipe.Phase k)
+ (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) :
+ (PhaseRecipe.Phase.ofParams room P.tag P.initial P.stop P.params).recipe.words pub state m =
+ P.recipe.words pub state m ++ List.replicate (g-k) 0 := by
+ simp only [PhaseRecipe.recipe_words, PhaseRecipe.Phase.ofParams, PhaseRecipe.Phase.words, List.cons_append]
+ congr 3
+ rw [← ofFn_padded (fun i ↦ (P.params i).eval pub state m) (0 : Word w) room]
+ congr 1
+ funext i
+ by_cases hi : i.val < k <;> simp [hi, Expr.eval]
+
+/-- The enclosing catalog can use any larger row width. Extra words after the
+worker's public bank are zero and have no effect on its operands. -/
+theorem padded_words (g : ℕ) (room : arity p ≤ g) :
+ (padded tag T I p g room).recipe.words pub state m =
+ frame (T.shape bases lanes) h (fun q ↦ (tag q : Word w)) p ++
+ List.replicate (g-arity p) 0 := by
+ rw [← recipe_words tag T I p read]
+ exact pad_phase_words room (phase tag T I p) pub state m
+
+/-- Launch the finite planner and install the computed row in the live
+directory. Its reads, writes and private execution use the native compiler. -/
+theorem execute_padded (g : ℕ) (room : arity p ≤ g) (cap : ℕ)
+ (budget : (padded tag T I p g room).recipe.code.length < cap)
+ (fit : (Controller.rowBase g pub m).val + (g+3) ≤ 2^w) :
+ let R := (padded tag T I p g room).recipe
+ let M := R.acceptTable.instantiate w pub
+ let es := (R.report pub state m).events
+ execute M.program cap (M.program.start state) m [] = some ⟨es,none⟩ ∧
+ Greedy.Stores (after m es) (Controller.rowBase g pub m)
+ (frame (T.shape bases lanes) h (fun q ↦ (tag q : Word w)) p ++ List.replicate (g-arity p) 0) ∧
+ (∀ a, a < (Controller.rowBase g pub m).val ∨ (Controller.rowBase g pub m).val + (g+3) ≤ a →
+ after m es a = m a) ∧ countProbes es = R.reads+(g+3) ∧ choiceBits es = [] := by
+ have he := execute_phase (padded tag T I p g room) pub state m cap budget fit
+ rw [← PhaseRecipe.recipe_words, padded_words tag T I p read g room] at he
+ exact he
+
+end CompressorRecords.SlotLevel.Recipe
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotLevelRun.lean b/lean/OAI/Computability/VPVNP/CompressorSlotLevelRun.lean
new file mode 100644
index 0000000000..b9964c944f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotLevelRun.lean
@@ -0,0 +1,232 @@
+import OAI.Computability.VPVNP.CompressorSlotLevel
+
+/-!
+# The physical base matching produced by a shrinking level
+
+The first four passes construct the absolute endpoint tables. The fifth
+visits each base slot at lane zero and writes its matching base slot and
+its lane displacement. These are exactly the words that serve as the old
+base tables of the following compression level.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotLevel
+
+open Compression Compression.PackingData Compression.SurvivingSlots Slots SlotSchedule SlotOwners
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {V H Tag L : Type*} {d c N J nL degree w : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] [Module (ZMod 2) Tag]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- Exact readback of both base tables under their common numeric base-arc enumeration. -/
+structure BaseMatching (G : LiftedSlots (V × Tag) degree L) (target shift : ℕ) (mem : Memory w) : Prop where
+ targetAt : ∀ e, (mem (target+(baseIndex vertices tags e).val)).val = (baseIndex vertices tags (G.base.target e)).val
+ shiftAt : ∀ e, (mem (shift+(baseIndex vertices tags e).val)).val = (lanes (G.displacement e)).val
+
+/-- The fifth native pass, including the range checks for both of its data-dependent reads. -/
+theorem materialize (layout : Bool) (h : Heads) (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (hd : survivingDegree d c subdiv ≤ degree) (hJ : 1 < J) (hzero : (lanes 0).val = 0)
+ (hw : 2 < 2^w) (hdw : degree < 2^w) (hlw : nL < 2^w) (m : Memory w) :
+ let s : Shape := ⟨N,J,nL,d,c,subdiv,degree⟩
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad s)
+ let hD := fun b ↦ (slotDirectory_degree P subdiv vertices tags lanes hc layout b).trans (Nat.add_sub_of_le hd)
+ let := P.slotIdentifierOrder vertices tags subdiv
+ let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ
+ let q := bank s h w .baseMatching
+ let worker := ((template SlotBaseScan.code 0).instantiate w q).program
+ stopAddress s h < 2^w → Tables D degree (rowsHead s h) (inverseHead s h) hD m →
+ ∃ rs, runSegment worker 33 (some 0) m (List.replicate (baseArcs s) []) = some rs ∧
+ endState (some 0) rs = some (Fin.ofNat _ (baseArcs s)) ∧
+ BaseMatching vertices tags lanes I.graph (targetsHead s h) (shiftsHead s h) (after m (eventLog rs)) ∧
+ (∀ a, a < targetsHead s h ∨ stopAddress s h ≤ a → after m (eventLog rs) a = m a) ∧
+ RAMBuckets.cost Report.probes rs = 5*(baseArcs s) ∧ ∀ r ∈ rs, r.events.length=32 := by
+ intro s D hD order I q worker hfit tab
+ have hrowCap : rowsHead s h + owners s * degree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right degree (Nat.le_add_right (owners s) (fields s))) _
+ have hfld : inverseHead s h+fields s=targetsHead s h := rfl
+ have htgt : targetsHead s h+baseArcs s=shiftsHead s h := rfl
+ have hsh : shiftsHead s h+baseArcs s=stopAddress s h := rfl
+ have q0 : (q 0).val = degree := Nat.mod_eq_of_lt hdw
+ have q1 : (q 1).val = nL := Nat.mod_eq_of_lt hlw
+ have q2 : (q 2).val = rowsHead s h := Nat.mod_eq_of_lt (by omega : rowsHead s h < 2^w)
+ have q3 : (q 3).val = inverseHead s h := Nat.mod_eq_of_lt (by omega : inverseHead s h < 2^w)
+ have q4 : (q 4).val = targetsHead s h := Nat.mod_eq_of_lt (by omega : targetsHead s h < 2^w)
+ have q5 : (q 5).val = shiftsHead s h := Nat.mod_eq_of_lt (by omega : shiftsHead s h < 2^w)
+ have step (e : (V×Tag)×Fin degree) :
+ let i := Fin.ofNat (2^w) (baseIndex vertices tags e).val
+ (SlotBaseScan.rowAddr q i).val < targetsHead s h ∧ (SlotBaseScan.invAddr q m i).val < targetsHead s h ∧
+ SlotBaseScan.target q m i = Fin.ofNat _ (baseIndex vertices tags (I.graph.base.target e)).val ∧
+ SlotBaseScan.displacement q m i = Fin.ofNat _ (lanes (I.graph.displacement e)).val := by
+ intro i
+ have hE : (baseIndex vertices tags e).val < baseArcs s := (baseIndex vertices tags e).isLt
+ have hi : i.val = (baseIndex vertices tags e).val := Nat.mod_eq_of_lt (by omega)
+ let source := laneZeroRow degree nL (baseIndex vertices tags e).val
+ let field := m (rowsHead s h + source)
+ have exactRead := base_lookup P subdiv vertices tags lanes hc hφ layout hd hJ hzero m e
+ (by change fields s ≤ 2^w; omega) (by change owners s*degree ≤ 2^w; omega) tab
+ obtain ⟨hsource, hfield, htarget⟩ := exactRead
+ change source < owners s*degree at hsource
+ change field.val+1 < fields s at hfield
+ have rf : (q 2).val + laneZeroRow (q 0).val (q 1).val i.val < 2^w := by
+ rw [q2,q0,q1,hi]; change rowsHead s h+source < 2^w; omega
+ have iv : (q 3).val+((m ((q 2).val+laneZeroRow (q 0).val (q 1).val i.val)).val+1) < 2^w := by
+ rw [q3,q2,q0,q1,hi]; change inverseHead s h+(field.val+1) < 2^w; omega
+ have read := SlotBaseScan.read_addresses q m i hw rf iv
+ have out := SlotBaseScan.outputs_eq q m i hw rf iv
+ dsimp only at read out
+ rw [q0,q1,q2,q3,hi] at read out
+ change (SlotBaseScan.rowAddr q i).val = rowsHead s h+source ∧
+ (SlotBaseScan.invAddr q m i).val = inverseHead s h+(field.val+1) at read
+ rw [htarget] at out
+ exact ⟨by rw [read.1]; omega, by rw [read.2]; omega, out⟩
+ have outside : SlotBaseScan.ReadsOutside q m (baseArcs s) := by
+ intro i hi a ha
+ let e := (baseIndex vertices tags (degree := degree)).symm ⟨i,hi⟩
+ have he : (baseIndex vertices tags e).val = i := congrArg Fin.val ((baseIndex vertices tags).apply_symm_apply ⟨i,hi⟩)
+ obtain ⟨hr, hv, _⟩ := step e
+ rw [he] at hr hv
+ have ha' : a.val < targetsHead s h := by
+ simp only [List.mem_cons, List.mem_nil_iff, or_false] at ha
+ rcases ha with rfl|rfl
+ · exact hr
+ · exact hv
+ exact ⟨Or.inl (q4 ▸ ha'), Or.inl (by rw [q5]; omega)⟩
+ obtain ⟨rs, run⟩ := SlotBaseScan.run q m (baseArcs s) (by omega) (by omega) (Or.inl (by omega)) outside
+ refine ⟨rs,run.executed,run.cursor,⟨?_,?_⟩,?_,run.cost,fun r hr ↦ (run.calls r hr).2⟩
+ · intro e
+ have hj : (baseIndex vertices tags e).val < baseArcs s := (baseIndex vertices tags e).isLt
+ have he := run.first _ hj
+ rw [q4,(step e).2.2.1] at he
+ rw [he,Fin.val_ofNat, Nat.mod_eq_of_lt (by have ht : (baseIndex vertices tags (I.graph.base.target e)).val < baseArcs s := (baseIndex vertices tags (I.graph.base.target e)).isLt; omega)]
+ · intro e
+ have hj : (baseIndex vertices tags e).val < baseArcs s := (baseIndex vertices tags e).isLt
+ have he := run.second _ hj
+ rw [q5,(step e).2.2.2] at he
+ rw [he,Fin.val_ofNat,Nat.mod_eq_of_lt ((lanes (I.graph.displacement e)).isLt.trans hlw)]
+ · intro a ha
+ exact run.frame a (by rw [q4]; omega) (by rw [q5]; omega)
+
+/-- Reports of the five actual passes, in directory order. -/
+structure Reports (w : ℕ) where
+ /-- Reports assigning each genuine candidate field to its endpoint owner or its reserved hole
+ row. -/
+ genuine : List (Report w)
+ /-- Reports assigning the outgoing and incoming fields of padding arcs to their packed site
+ owners. -/
+ dummy : List (Report w)
+ /-- Reports that append each absolute field identifier to its owner's row. -/
+ append : List (Report w)
+ /-- Reports that invert the real endpoint rows to recover the rectangular slot of each field. -/
+ scatter : List (Report w)
+ /-- Reports that follow lane-zero endpoints to write the base matching and its lane
+ displacements. -/
+ bases : List (Report w)
+
+/-- The five slot-directory report lists in chronological order from the first owner scan
+through base matching. -/
+def Reports.all (r : Reports w) := r.genuine++r.dummy++r.append++r.scatter++r.bases
+
+/-- Memory after replaying all five slot-directory scans in sequence. -/
+def Reports.final (r : Reports w) (m : Memory w) :=
+ after (after (after (after (after m (eventLog r.genuine)) (eventLog r.dummy)) (eventLog r.append))
+ (eventLog r.scatter)) (eventLog r.bases)
+
+/-- The public banks and local cursor stops used by all five successive scans. -/
+def Reports.Native (r : Reports w) (s : Shape) (h : Heads) (m : Memory w) : Prop :=
+ let m₁ := after m (eventLog r.genuine)
+ let m₂ := after m₁ (eventLog r.dummy)
+ let m₃ := after m₂ (eventLog r.append)
+ let m₄ := after m₃ (eventLog r.scatter)
+ runSegment ((template SlotOwners.genuine 0).instantiate w (bank s h w .genuineOwners)).program 49
+ (some 0) m (List.replicate (genuineCount s) []) = some r.genuine ∧
+ runSegment ((template SlotOwners.dummy 0).instantiate w (bank s h w .dummyOwners)).program 20
+ (some 0) m₁ (List.replicate (dummyCount s) []) = some r.dummy ∧
+ runSegment ((template collectPreimage 3).instantiate w (bank s h w .appendFields)).program 23
+ (some 0) m₂ (List.replicate (fields s) []) = some r.append ∧
+ runSegment ((template SlotScatter.visit 0).instantiate w (bank s h w .invertFields)).program 10
+ (some 0) m₃ (List.replicate (owners s*s.newDegree) []) = some r.scatter ∧
+ runSegment ((template SlotBaseScan.code 0).instantiate w (bank s h w .baseMatching)).program 33
+ (some 0) m₄ (List.replicate (baseArcs s) []) = some r.bases
+
+/-- Exclusive stops are also the values returned by the last visits. -/
+def Reports.Cursors (r : Reports w) (s : Shape) : Prop :=
+ endState (some 0) r.genuine = some (Fin.ofNat _ (genuineCount s)) ∧
+ endState (some 0) r.dummy = some (Fin.ofNat _ (dummyCount s)) ∧
+ endState (some 0) r.append = some (Fin.ofNat _ (fields s)) ∧
+ endState (some 0) r.scatter = some (Fin.ofNat _ (owners s*s.newDegree)) ∧
+ endState (some 0) r.bases = some (Fin.ofNat _ (baseArcs s))
+
+/-- Starting from the selected records and fresh counters, construct the
+absolute endpoint arrays and the next base graph in physical RAM. No rank
+oracle or sorted input rows are required. -/
+theorem run_selected (layout : Bool) (h : Heads) (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (hd : survivingDegree d c subdiv ≤ degree) (hJ : 1 < J) (hlane : (lanes 0).val = 0)
+ (hdeg : 0 < degree) (hdw : degree < 2^w) (mem : Memory w) :
+ let s : Shape := ⟨N,J,nL,d,c,subdiv,degree⟩
+ let g := bank s h w .genuineOwners
+ let p := bank s h w .dummyOwners
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad s)
+ let hD := fun b ↦ (slotDirectory_degree P subdiv vertices tags lanes hc layout b).trans (Nat.add_sub_of_le hd)
+ let := P.slotIdentifierOrder vertices tags subdiv
+ let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ
+ GenuineTables P subdiv vertices tags lanes layout g mem → DummyTables vertices tags lanes (pad s) p mem →
+ h.oldArc+4*(oldBaseArcCount N J d c*nL) ≤ h.scratch → h.role+8 ≤ h.scratch →
+ h.subdivisions+4 ≤ h.scratch → h.nextSite+sites s ≤ h.scratch → stopAddress s h < 2^w →
+ (∀ u : Word w, u.val < owners s+fields s → mem (h.scratch+fields s+u.val)=0) →
+ ∃ r : Reports w, r.Native s h mem ∧ r.Cursors s ∧
+ Tables D degree (rowsHead s h) (inverseHead s h) hD (r.final mem) ∧
+ BaseMatching vertices tags lanes I.graph (targetsHead s h) (shiftsHead s h) (r.final mem) ∧
+ (∀ a, a < h.scratch ∨ stopAddress s h ≤ a → r.final mem a = mem a) ∧
+ RAMBuckets.cost Report.probes r.all =
+ 6*genuineCount s+3*dummyCount s+5*fields s+3*(owners s*degree)+5*baseArcs s ∧
+ ∀ rep ∈ r.all, rep.events.length ≤ 48 := by
+ intro s g p D hD order I hg hp ho hrole hsub hn hfit hzero
+ have input := input_of_tables (degree := degree) P subdiv vertices tags lanes layout mem h hg hp ho hrole hsub hn hfit
+ have hrow : rowsHead s h+owners s*degree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right degree (Nat.le_add_right (owners s) (fields s))) _
+ have hfld : inverseHead s h+fields s=targetsHead s h := rfl
+ have htgt : targetsHead s h+baseArcs s=shiftsHead s h := rfl
+ have hsh : shiftsHead s h+baseArcs s=stopAddress s h := rfl
+ have hbase : h.scratch ≤ rowsHead s h := by unfold rowsHead; omega
+ obtain ⟨gs,ds,fs,ss,hgRun,hdRun,hfRun,hsRun,tab,cg,cd,cf,cs,frame,cost,wg,wd,wf,ws⟩ :=
+ SlotSchedule.run D g p mem input hdeg hdw hD (by change targetsHead s h < 2^w; omega) hzero
+ let m₄ := after (after (after (after mem (eventLog gs)) (eventLog ds)) (eventLog fs)) (eventLog ss)
+ have ht : Tables D degree (rowsHead s h) (inverseHead s h) hD m₄ := tab
+ obtain ⟨bs, hbRun, cb, matching, frameB, costB, wb⟩ := materialize P subdiv vertices tags lanes layout h hc hφ hd hJ
+ hlane hp.twoFits hdw (hg.laneCount ▸ (g 0).isLt) m₄ hfit ht
+ change ∀ a, a < targetsHead s h ∨ stopAddress s h ≤ a → after m₄ (eventLog bs) a = m₄ a at frameB
+ let r : Reports w := ⟨gs,ds,fs,ss,bs⟩
+ refine ⟨r, ⟨hgRun,hdRun,hfRun,hsRun,hbRun⟩, ⟨cg,cd,cf,cs,cb⟩, ⟨?_,?_⟩, matching, ?_, ?_, ?_⟩
+ · intro e
+ have he : (sortedFields D degree hD e).val < owners s*degree := (sortedFields D degree hD e).isLt
+ exact (frameB _ (Or.inl (by omega))).trans (ht.bySlot e)
+ · intro e
+ have he : (D.address e).val < fields s := (D.address e).isLt
+ exact (frameB _ (Or.inl (by omega))).trans (ht.byField e)
+ · intro a ha
+ have h₁ : a < h.scratch ∨ targetsHead s h ≤ a := by omega
+ exact (frameB a (by omega)).trans (frame a h₁)
+ · change RAMBuckets.cost Report.probes ((gs++ds++fs++ss)++bs) = _
+ rw [RAMBuckets.cost_append,cost,costB]; rfl
+ · intro rep hr
+ change rep ∈ gs++ds++fs++ss++bs at hr
+ simp only [List.mem_append] at hr
+ rcases hr with (((hr|hr)|hr)|hr)|hr
+ · exact (wg rep hr).le
+ · rw [wd rep hr]; decide
+ · rw [wf rep hr]; decide
+ · rw [ws rep hr]; decide
+ · rw [wb rep hr]; decide
+
+end CompressorRecords.SlotLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotMateColumns.lean b/lean/OAI/Computability/VPVNP/CompressorSlotMateColumns.lean
new file mode 100644
index 0000000000..e4ad7c8cda
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotMateColumns.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.CompressorSlotOutputLayout
+import OAI.Computability.VPVNP.CompressorSlotIncidence
+
+/-!
+# The three remaining incidence permutations
+
+After the base-target scan, invert its permutation and expand both directions
+to all binary lanes. Each pass starts with the previous pass's physical memory.
+The base mate, inverse, displacement and two actual mate columns coexist in
+the final memory; older tables and the reserved width region are preserved.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots
+
+open SlotLevel BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression IncidenceDirectory
+
+variable {a l w : ℕ} (Y : State a l) (s : Shape) (h : Heads)
+
+/-- Memory represents the next state's forward and inverse base matching, base displacements,
+and both directions of actual port incidence in canonical port order. -/
+structure Mates (m : Memory w) : Prop where
+ forward : BaseForward Y (targetsHead s h) (shiftsHead s h) m
+ baseIn : ∀ e, m (inverseBaseHead s h+(baseOrder Y e).val) = Fin.ofNat _ (baseOrder Y (Y.slots.base.target.symm e)).val
+ actualOut : ∀ e, m (outHead s h+(actualOrder Y e).val) = Fin.ofNat _ (actualOrder Y (Y.slots.actualGraph.target e)).val
+ actualIn : ∀ e, m (inHead s h+(actualOrder Y e).val) = Fin.ofNat _ (actualOrder Y (Y.slots.actualGraph.target.symm e)).val
+
+/-- Reports for the base inverse scan followed by the two scans that lift the matching to every
+residual lane. -/
+structure MateReports (w : ℕ) where
+ /-- Reports that invert the base-target permutation, giving the source base port at each
+ incoming base port. -/
+ baseIn : List (Report w)
+ /-- Reports that expand the forward base matching and displacements into the outgoing
+ actual-port mate column. -/
+ actualOut : List (Report w)
+ /-- Reports that expand the inverse base matching and source displacements into the incoming
+ actual-port mate column. -/
+ actualIn : List (Report w)
+
+/-- Concatenate the base inverse, actual forward, and actual inverse reports in execution
+order. -/
+def MateReports.all (r : MateReports w) := r.baseIn++r.actualOut++r.actualIn
+
+/-- Memory after replaying the base inverse and the two actual mate scans in sequence. -/
+def MateReports.final (r : MateReports w) (m : Memory w) :=
+ after (after (after m (eventLog r.baseIn)) (eventLog r.actualOut)) (eventLog r.actualIn)
+
+/-- The three mate report lists arise from their native workers starting at cursor zero on
+successive memory states. -/
+def MateReports.Native (r : MateReports w) (s : Shape) (h : Heads) (m : Memory w) : Prop :=
+ let m₁ := after m (eventLog r.baseIn)
+ let m₂ := after m₁ (eventLog r.actualOut)
+ runSegment ((template SlotScatter.visit 0).instantiate w (inverseBank s h w)).program 10 (some 0) m
+ (List.replicate (baseArcs s) []) = some r.baseIn ∧
+ runSegment ((template (SlotIncidencePass.visit false) 0).instantiate w (actualBank s h false w)).program 28
+ (some 0) m₁ (List.replicate (actualCount s) []) = some r.actualOut ∧
+ runSegment ((template (SlotIncidencePass.visit true) 0).instantiate w (actualBank s h true w)).program 28
+ (some 0) m₂ (List.replicate (actualCount s) []) = some r.actualIn
+
+/-- The base inverse scan returns the base port count and both lifted mate scans return the
+actual port count. -/
+def MateReports.Cursors (r : MateReports w) (s : Shape) : Prop :=
+ endState (some 0) r.baseIn=some (Fin.ofNat _ (baseArcs s)) ∧
+ endState (some 0) r.actualOut=some (Fin.ofNat _ (actualCount s)) ∧ endState (some 0) r.actualIn=some (Fin.ofNat _ (actualCount s))
+
+/-- The three passes share and preserve the prior target and displacement
+columns. Their total cost is linear in the numbers of base and actual ports. -/
+theorem writeMates (m : Memory w) (base : BaseForward Y (targetsHead s h) (shiftsHead s h) m)
+ (hB : Fintype.card Y.Base*2^a=baseArcs s) (hA : Fintype.card Y.Base*2^l*2^a=actualCount s)
+ (hd : s.newDegree=2^a) (hl : s.lanes=2^l) (hdw : 2^a<2^w) (hlw : 2^l<2^w)
+ (hfit : finish s h < 2^w) :
+ ∃ r : MateReports w, r.Native s h m ∧ r.Cursors s ∧ Mates Y s h (r.final m) ∧
+ (∀ addr, addr < inverseBaseHead s h ∨ widthHead s h ≤ addr → r.final m addr=m addr) ∧
+ RAMBuckets.cost Report.probes r.all = 3*baseArcs s+8*actualCount s := by
+ let p := inverseBank s h w
+ let q := actualBank s h false w
+ let t := actualBank s h true w
+ have h₀ : targetsHead s h+baseArcs s=shiftsHead s h := rfl
+ have h₁ : shiftsHead s h+baseArcs s=inverseBaseHead s h := rfl
+ have h₂ : inverseBaseHead s h+baseArcs s=outHead s h := rfl
+ have h₃ : outHead s h+actualCount s=inHead s h := rfl
+ have h₄ : inHead s h+actualCount s=widthHead s h := rfl
+ have h₅ : widthHead s h+actualCount s=finish s h := rfl
+ have p0 : (p 0).val=targetsHead s h := Nat.mod_eq_of_lt (by omega : targetsHead s h < 2^w)
+ have p1 : (p 1).val=inverseBaseHead s h := Nat.mod_eq_of_lt (by omega : inverseBaseHead s h < 2^w)
+ have q0 : (q 0).val=2^a := (Nat.mod_eq_of_lt (hd ▸ hdw)).trans hd
+ have q1 : (q 1).val=2^l := (Nat.mod_eq_of_lt (hl ▸ hlw)).trans hl
+ have q2 : (q 2).val=targetsHead s h := p0
+ have q3 : (q 3).val=shiftsHead s h := Nat.mod_eq_of_lt (by omega : shiftsHead s h < 2^w)
+ have q4 : (q 4).val=outHead s h := Nat.mod_eq_of_lt (by omega : outHead s h < 2^w)
+ have t2 : (t 2).val=inverseBaseHead s h := p1
+ have t4 : (t 4).val=inHead s h := Nat.mod_eq_of_lt (by omega : inHead s h < 2^w)
+ have regions : SlotScatter.Regions p (Fintype.card Y.Base*2^a) (Fintype.card Y.Base*2^a) :=
+ ⟨by rw [p0,hB]; omega,by rw [p1,hB]; omega,Or.inl (by rw [p0,p1,hB]; omega)⟩
+ obtain ⟨bs,hbr,cb,base₁,bi,fb,costB⟩ := scatterBaseIn Y m p (shiftsHead s h) regions (p0 ▸ base)
+ (Or.inl (by rw [p1,hB]; omega))
+ let m₁ := after m (eventLog bs)
+ have base₁' : BaseForward Y (targetsHead s h) (shiftsHead s h) m₁ := p0 ▸ base₁
+ obtain ⟨os,hor,co,hout,fo,costO⟩ := SlotIncidencePass.run false Y q m₁ q0 q1
+ (by rw [q2,q4,hB]; omega) (by rw [q3,q4,hB]; omega) (by rw [q4,hA]; omega)
+ (fun e ↦ by rw [q2]; exact base₁'.mate e) (fun e ↦ by rw [q3]; exact base₁'.displacement e)
+ let m₂ := after m₁ (eventLog os)
+ have bv e : m₂ ((t 2).val+(baseOrder Y e).val) = Fin.ofNat _ (baseOrder Y (Y.slots.base.target.symm e)).val := by
+ have hi : (baseOrder Y e).val < baseArcs s := (baseOrder Y e).isLt.trans_le hB.le
+ rw [t2]
+ exact (fo (inverseBaseHead s h+(baseOrder Y e).val) (Or.inl (by rw [q4]; omega))).trans (p1 ▸ bi e)
+ have sv e : m₂ ((t 3).val+(baseOrder Y e).val) = Fin.ofNat _ (bitWordFinEquiv l (Y.slots.displacement e)).val := by
+ have hi : (baseOrder Y e).val < baseArcs s := (baseOrder Y e).isLt.trans_le hB.le
+ change m₂ ((q 3).val+_) = _
+ rw [q3]
+ exact (fo (shiftsHead s h+(baseOrder Y e).val) (Or.inl (by rw [q4]; omega))).trans (base₁'.displacement e)
+ obtain ⟨is',hir,ci,hinc,fi,costI⟩ := SlotIncidencePass.run true Y t m₂ q0 q1
+ (by rw [t2,t4,hB]; omega) (by change (q 3).val+_ ≤ _; rw [q3,t4,hB]; omega) (by rw [t4,hA]; omega) bv sv
+ let r : MateReports w := ⟨bs,os,is'⟩
+ have prev (addr : ℕ) (ha : addr < outHead s h ∨ widthHead s h ≤ addr) : r.final m addr=m₁ addr :=
+ (fi addr (by rw [t4,hA]; omega)).trans (fo addr (by rw [q4,hA]; omega))
+ have hfinal : BaseForward Y (targetsHead s h) (shiftsHead s h) (r.final m) := by
+ constructor
+ · intro e; have he := (baseOrder Y e).isLt
+ exact (prev _ (.inl (by omega))).trans (base₁'.mate e)
+ · intro e; have he := (baseOrder Y e).isLt
+ exact (prev _ (.inl (by omega))).trans (base₁'.displacement e)
+ refine ⟨r, ⟨hB ▸ hbr,hA ▸ hor,hA ▸ hir⟩, ⟨hB ▸ cb,hA ▸ co,hA ▸ ci⟩, ⟨hfinal,?_,?_,?_⟩, ?_, ?_⟩
+ · intro e; have he := (baseOrder Y e).isLt
+ exact (prev _ (.inl (by omega))).trans (p1 ▸ bi e)
+ · intro e; have he := (actualOrder Y e).isLt
+ exact (fi _ (.inl (by rw [t4]; omega))).trans (q4 ▸ hout e)
+ · intro e; exact t4 ▸ hinc e
+ · intro addr ha
+ exact (prev addr (by omega)).trans (fb addr (by rw [p1,hB]; omega))
+ · change RAMBuckets.cost Report.probes ((bs++os)++is') = _
+ rw [RAMBuckets.cost_append,RAMBuckets.cost_append,costB,costO,costI,hA,hB]; ring
+
+end CompressorRecords.ShrinkSlots
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotMateFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorSlotMateFootprint.lean
new file mode 100644
index 0000000000..3c746ccc0e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotMateFootprint.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.CompressorSlotMateColumns
+import OAI.Computability.VPVNP.CompressorSlotFillFootprint
+import OAI.Computability.VPVNP.CompressorSlotScanFootprint
+
+/-!
+# External addresses of the three mate-table passes
+
+The first pass inverts the base permutation. The other two expand that
+matching to all lanes, once in each direction. On the reverse pass the
+inverse table determines the index of the displacement read. Its entries
+remain bounded by the base-port count after the forward expansion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport
+open Compression IncidenceDirectory SlotLevel SlotFillFootprint
+
+variable {a l w : ℕ}
+
+/-- The lifted incidence pass reads the selected base-mate and displacement
+columns. It writes one cell in its output column per actual port. -/
+theorem actual_scan_footprint (p : Fin 5 → Word w) (reverse : Bool) (Y : State a l)
+ (m : Memory w) (rs : List (Report w))
+ (hd : (p 0).val = 2^a) (hl : (p 1).val = 2^l)
+ (ht : (p 2).val + Fintype.card Y.Base * 2^a ≤ (p 4).val)
+ (hs : (p 3).val + Fintype.card Y.Base * 2^a ≤ (p 4).val)
+ (fit : (p 4).val + Fintype.card Y.Base * 2^l * 2^a ≤ 2^w)
+ (bounded : ∀ e, (m ((p 2).val + (baseOrder Y e).val)).val < Fintype.card Y.Base * 2^a)
+ (run : runSegment ((template (SlotIncidencePass.visit reverse) 0).instantiate w p).program
+ 28 (some 0) m (List.replicate (Fintype.card Y.Base * 2^l * 2^a) []) = some rs) :
+ Reads (fun x ↦ InColumn (p 2).val (Fintype.card Y.Base * 2^a) x ∨
+ InColumn (p 3).val (Fintype.card Y.Base * 2^a) x) (eventLog rs) ∧
+ Writes (InColumn (p 4).val (Fintype.card Y.Base * 2^l * 2^a)) (eventLog rs) := by
+ let I (mem : Memory w) := ∀ e, (mem ((p 2).val + (baseOrder Y e).val)).val < Fintype.card Y.Base * 2^a
+ apply SlotEventBounds.scan _ 28 _ (SlotIncidencePass.events p reverse) I _ _
+ (SlotIncidencePass.native p reverse) _ m rs bounded run
+ intro j hj mem hmem
+ obtain ⟨rd,wr⟩ := SlotIncidencePass.row_footprint p reverse Y mem hd hl ht hs fit hmem j hj
+ refine ⟨rd, wr, fun e ↦ ?_⟩
+ have he := (baseOrder Y e).isLt
+ rw [after_outside mem wr (fun hx ↦ by omega)]
+ exact hmem e
+
+/-- The three chronological native scans read within the five mate columns
+and write only the inverse-base and two actual columns. The bounds include
+the data-dependent displacement reads of the reverse scan. -/
+theorem mate_footprint (Y : State a l) (s : Shape) (h : Heads) (m : Memory w) (r : MateReports w)
+ (base : BaseForward Y (targetsHead s h) (shiftsHead s h) m)
+ (hB : Fintype.card Y.Base * 2^a = baseArcs s)
+ (hA : Fintype.card Y.Base * 2^l * 2^a = actualCount s)
+ (hd : s.newDegree = 2^a) (hl : s.lanes = 2^l) (hdw : 2^a < 2^w) (hlw : 2^l < 2^w)
+ (hfit : finish s h < 2^w) (native : r.Native s h m) :
+ Reads (fun x ↦ targetsHead s h ≤ x ∧ x < widthHead s h) (eventLog r.all) ∧
+ Writes (fun x ↦ inverseBaseHead s h ≤ x ∧ x < widthHead s h) (eventLog r.all) := by
+ let p := inverseBank s h w
+ let q := actualBank s h false w
+ let t := actualBank s h true w
+ have h₀ : targetsHead s h + baseArcs s = shiftsHead s h := rfl
+ have h₁ : shiftsHead s h + baseArcs s = inverseBaseHead s h := rfl
+ have h₂ : inverseBaseHead s h + baseArcs s = outHead s h := rfl
+ have h₃ : outHead s h + actualCount s = inHead s h := rfl
+ have h₄ : inHead s h + actualCount s = widthHead s h := rfl
+ have h₅ : widthHead s h + actualCount s = finish s h := rfl
+ have p0 : (p 0).val = targetsHead s h := Nat.mod_eq_of_lt (by omega : targetsHead s h < 2^w)
+ have p1 : (p 1).val = inverseBaseHead s h := Nat.mod_eq_of_lt (by omega : inverseBaseHead s h < 2^w)
+ have q0 : (q 0).val = 2^a := (Nat.mod_eq_of_lt (hd ▸ hdw)).trans hd
+ have q1 : (q 1).val = 2^l := (Nat.mod_eq_of_lt (hl ▸ hlw)).trans hl
+ have q2 : (q 2).val = targetsHead s h := p0
+ have q3 : (q 3).val = shiftsHead s h := Nat.mod_eq_of_lt (by omega : shiftsHead s h < 2^w)
+ have q4 : (q 4).val = outHead s h := Nat.mod_eq_of_lt (by omega : outHead s h < 2^w)
+ have t2 : (t 2).val = inverseBaseHead s h := p1
+ have t3 : (t 3).val = shiftsHead s h := q3
+ have t4 : (t 4).val = inHead s h := Nat.mod_eq_of_lt (by omega : inHead s h < 2^w)
+ let m₁ := after m (eventLog r.baseIn)
+ let m₂ := after m₁ (eventLog r.actualOut)
+ obtain ⟨rb,ro,ri⟩ := native
+ rw [← hB] at rb
+ rw [← hA] at ro ri
+ have reg : SlotScatter.Regions p (Fintype.card Y.Base*2^a) (Fintype.card Y.Base*2^a) :=
+ ⟨by rw [p0,hB]; omega, by rw [p1,hB]; omega, Or.inl (by rw [p0,p1,hB]; omega)⟩
+ obtain ⟨readB,writeB⟩ := baseInverse Y reg (p0 ▸ base) rb
+ obtain ⟨bs,hbr,_,forward,inv,_⟩ := scatterBaseIn Y m p (shiftsHead s h) reg (p0 ▸ base)
+ (Or.inl (by rw [p1,hB]; omega))
+ obtain rfl := Option.some.inj (rb.symm.trans hbr)
+ have outBound (e) : (m₁ ((q 2).val + (baseOrder Y e).val)).val < Fintype.card Y.Base * 2^a := by
+ change (after m (eventLog r.baseIn) ((p 0).val + (baseOrder Y e).val)).val < _
+ rw [forward.mate e]
+ exact (Nat.mod_le ..).trans_lt (baseOrder Y (Y.slots.base.target e)).isLt
+ obtain ⟨readO,writeO⟩ := actual_scan_footprint q false Y m₁ r.actualOut q0 q1
+ (by rw [q2,q4,hB]; omega) (by rw [q3,q4,hB]; omega) (by rw [q4,hA]; omega) outBound ro
+ have inBound (e) : (m₂ ((t 2).val + (baseOrder Y e).val)).val < Fintype.card Y.Base * 2^a := by
+ have he : (baseOrder Y e).val < baseArcs s := (baseOrder Y e).isLt.trans_le hB.le
+ have away : ¬ InColumn (q 4).val (Fintype.card Y.Base * 2^l * 2^a) ((p 1).val + (baseOrder Y e).val) := by
+ rw [InColumn,q4,p1]; omega
+ change (after m₁ (eventLog r.actualOut) ((p 1).val + (baseOrder Y e).val)).val < _
+ rw [after_outside m₁ writeO away, show m₁ ((p 1).val + (baseOrder Y e).val) = _ from inv e]
+ exact (Nat.mod_le ..).trans_lt (baseOrder Y (Y.slots.base.target.symm e)).isLt
+ obtain ⟨readI,writeI⟩ := actual_scan_footprint t true Y m₂ r.actualIn q0 q1
+ (by rw [t2,t4,hB]; omega) (by rw [t3,t4,hB]; omega) (by rw [t4,hA]; omega) inBound ri
+ constructor <;> intro addr val member <;>
+ simp only [MateReports.all,eventLog,List.flatMap_append,List.mem_append] at member
+ · rcases member with (hb | ho) | hi
+ · have hr := readB addr val hb
+ rw [InColumn,p0,hB] at hr
+ omega
+ · have hr := readO addr val ho
+ simp only [InColumn,q2,q3,hB] at hr
+ omega
+ · have hr := readI addr val hi
+ simp only [InColumn,t2,t3,hB] at hr
+ omega
+ · rcases member with (hb | ho) | hi
+ · have hw := writeB addr val hb
+ rw [InColumn,p1,hB] at hw
+ omega
+ · have hw := writeO addr val ho
+ rw [InColumn,q4,hA] at hw
+ omega
+ · have hw := writeI addr val hi
+ rw [InColumn,t4,hA] at hw
+ omega
+
+end CompressorRecords.ShrinkSlots
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotNetwork.lean b/lean/OAI/Computability/VPVNP/CompressorSlotNetwork.lean
new file mode 100644
index 0000000000..e10f1f8cf4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotNetwork.lean
@@ -0,0 +1,189 @@
+import OAI.Computability.VPVNP.CompressorSlotSchedule
+import OAI.Computability.VPVNP.CompressorSlotOrder
+
+/-!
+# The selected shrinking layout in the RAM slot directory
+
+Both ends of an actual arc have adjacent field identifiers. The low bit is
+zero for the outgoing end and one for the incoming end. The real owner array
+uses the same convention on absolute sites. The native row and inverse scans
+therefore leave two direct tables from which the next substep can query its
+incoming site and slot using its outgoing site and slot.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotSchedule
+
+open Compression Compression.PackingData Compression.SurvivingSlots Slots BurstRAM
+
+variable {V H Tag L : Type*} {d c N J nL pad : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- Direct mixed-radix index of one absolute site. -/
+def siteIndex : Site V Tag L ≃ Fin (N*(J*nL)) :=
+ (vertices.prodCongr ((tags.prodCongr lanes).trans finProdFinEquiv)).trans finProdFinEquiv
+
+/-- Decode one candidate field by splitting off its side bit and using the
+actual arc-address decoder. The owners are the two role endpoints of the
+chosen layout, including the cyclic target of each padding arc. -/
+def slotDirectory (layout : Bool) : Directory (ActualId P subdiv pad × Fin 2)
+ (RecordCount N J nL d c pad subdiv * 2) ((N*(J*nL))*2) where
+ address := endpointAddress (arcAddress P subdiv vertices tags lanes pad)
+ decode := fun j ↦ let p := finProdFinEquiv.symm j
+ (decodeArc P subdiv vertices tags lanes pad p.1).map fun i ↦ (i,p.2)
+ decode_eq_some := by
+ intro j ⟨i,s⟩
+ obtain ⟨⟨a,b⟩,rfl⟩ := finProdFinEquiv.surjective j
+ simp only [Equiv.symm_apply_apply]
+ change _ ↔ finProdFinEquiv (arcAddress P subdiv vertices tags lanes pad i,s) = finProdFinEquiv (a,b)
+ simp only [Option.map_eq_some_iff, finProdFinEquiv.injective.eq_iff, Prod.mk.injEq]
+ constructor
+ · rintro ⟨x,h,rfl,rfl⟩; exact ⟨(decodeArc_eq_some _ _ _ _ _ _ _ _).mp h, rfl⟩
+ · rintro ⟨h,rfl⟩; exact ⟨i, (decodeArc_eq_some _ _ _ _ _ _ _ _).mpr h, rfl, rfl⟩
+ owner := fun ⟨i,s⟩ ↦ finProdFinEquiv (siteIndex vertices tags lanes
+ (actualEnd P subdiv tags layout (decide (s=1)) i),s)
+
+private theorem owner_iff (layout : Bool) (e : ActualId P subdiv pad × Fin 2) (s : Site V Tag L) (b : Fin 2) :
+ (slotDirectory P subdiv vertices tags lanes layout).owner e = finProdFinEquiv (siteIndex vertices tags lanes s,b) ↔
+ actualEnd P subdiv tags layout (decide (e.2=1)) e.1 = s ∧ e.2 = b := by
+ simp only [slotDirectory, EmbeddingLike.apply_eq_iff_eq, Prod.mk.injEq]
+
+private theorem field_lt (i j : ActualId P subdiv pad) (side : Fin 2) :
+ endpointAddress (arcAddress P subdiv vertices tags lanes pad) (i,side) <
+ endpointAddress (arcAddress P subdiv vertices tags lanes pad) (j,side) ↔
+ arcAddress P subdiv vertices tags lanes pad i < arcAddress P subdiv vertices tags lanes pad j := by
+ change side.val + 2 * (arcAddress _ _ _ _ _ _ i).val < side.val + 2 * (arcAddress _ _ _ _ _ _ j).val ↔ _
+ rw [Fin.lt_def]; omega
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+/-- The two side arrays have exactly the common degree at each real owner. -/
+theorem slotDirectory_degree (hc : 2 ≤ c) (layout : Bool) (b : Fin ((N*(J*nL))*2)) :
+ Fintype.card {e // (slotDirectory P subdiv vertices tags lanes layout (pad := pad)).owner e = b} =
+ survivingDegree d c subdiv + pad := by
+ obtain ⟨⟨v,side⟩,rfl⟩ := finProdFinEquiv.surjective b
+ obtain ⟨s,rfl⟩ := (siteIndex vertices tags lanes).surjective v
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad)
+ let t := finProdFinEquiv (siteIndex vertices tags lanes s,side)
+ let eqv : {e // D.owner e = t} ≃ {i // actualEnd P subdiv tags layout (decide (side=1)) i = s} := {
+ toFun e := ⟨e.val.1, by
+ obtain ⟨h, hs⟩ := (owner_iff P subdiv vertices tags lanes layout e.val s side).mp e.prop
+ simpa only [hs] using h⟩
+ invFun i := ⟨(i.val,side), (owner_iff P subdiv vertices tags lanes layout _ _ _).mpr ⟨i.prop,rfl⟩⟩
+ left_inv e := Subtype.ext (Prod.ext rfl ((owner_iff P subdiv vertices tags lanes layout e.val s side).mp e.prop).2.symm)
+ right_inv _ := rfl }
+ exact (Fintype.card_congr eqv).trans (actualEnd_card P subdiv tags hc layout (decide (side=1)) s)
+
+private theorem field_rank (layout : Bool) (i : ActualId P subdiv pad) (side : Fin 2) :
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad)
+ Fintype.card {x // D.owner x = D.owner (i,side) ∧ D.address x < D.address (i,side)} =
+ addressRank P subdiv vertices tags lanes layout (decide (side=1)) i := by
+ intro D
+ let s := actualEnd P subdiv tags layout (decide (side=1)) i
+ let eqv : {x // D.owner x = D.owner (i,side) ∧ D.address x < D.address (i,side)} ≃
+ {j // actualEnd P subdiv tags layout (decide (side=1)) j = s ∧
+ arcAddress P subdiv vertices tags lanes pad j < arcAddress P subdiv vertices tags lanes pad i} := {
+ toFun x := ⟨x.val.1, by
+ rcases x with ⟨⟨j,t⟩, hx, hlt⟩
+ obtain ⟨he, ht⟩ := (owner_iff P subdiv vertices tags lanes layout (j,t) s side).mp hx
+ change t = side at ht; subst t
+ exact ⟨he, (field_lt P subdiv vertices tags lanes j i side).mp hlt⟩⟩
+ invFun x := ⟨(x.val,side), (owner_iff P subdiv vertices tags lanes layout _ _ _).mpr ⟨x.prop.1,rfl⟩,
+ (field_lt P subdiv vertices tags lanes _ _ _).mpr x.prop.2⟩
+ left_inv x := by
+ rcases x with ⟨⟨j,t⟩, hx, hlt⟩
+ have ht : t = side := ((owner_iff P subdiv vertices tags lanes layout _ s side).mp hx).2
+ subst t; rfl
+ right_inv _ := rfl }
+ exact Fintype.card_congr eqv
+
+variable [Module (ZMod 2) Tag]
+
+/-- Every rectangular RAM index contains the regularized graph's prescribed
+slot at the specified absolute endpoint, with the orientation bit retained. -/
+theorem rectangular_slot (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (layout : Bool) {d' : ℕ} (hd : survivingDegree d c subdiv ≤ d') (hJ : 1 < J)
+ (i : ActualId P subdiv (d' - survivingDegree d c subdiv)) (side : Fin 2) :
+ let := P.slotIdentifierOrder vertices tags subdiv
+ let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := d' - survivingDegree d c subdiv)
+ let hD := fun b ↦ (slotDirectory_degree P subdiv vertices tags lanes hc layout b).trans (Nat.add_sub_of_le hd)
+ (sortedFields D d' hD (i,side)).val =
+ ((if side=1 then I.incoming else I.outgoing) (paddedBaseId P subdiv i)).2.val + d'*(D.owner (i,side)).val := by
+ intro order I D hD
+ rw [sortedFields_val]
+ congr 1
+ rw [field_rank]
+ simpa only [decide_eq_true_eq] using addressRank_eq_slot P subdiv vertices tags lanes hc hφ layout
+ (decide (side=1)) hd hJ i
+
+open BurstRAM.PrivateRAM PrimedStackRAM
+
+/-- Starting with the rectangular outgoing slot, fetch its absolute field,
+advance to the adjacent incoming field, and read the incoming rectangular slot. -/
+def oppositeLookup : List (Op 3 2) :=
+ [.stateWord 0, .publicWord 1 0, .binary .add 1 1 0, .read 2 1,
+ .constant 1 1, .binary .add 2 2 1, .publicWord 1 1, .binary .add 2 1 2, .read 2 2]
+
+theorem oppositeLookup_native {w : ℕ} (p : Fin 2 → Word w) (m : Memory w) (idx : Word w) :
+ let M := (template oppositeLookup 2).instantiate w p
+ let ptr := p 0 + idx
+ let field := m ptr.val
+ let inv := p 1 + (field + 1)
+ let target := m inv.val
+ ∃ es, execute M.program 10 (M.program.start idx) m [] = some ⟨es, some target⟩ ∧
+ after m es = m ∧ es.length = 9 ∧ countProbes es = 2 := by
+ intro M ptr field inv target
+ refine ⟨[.tick,.tick,.tick,.read ptr field,.tick,.tick,.tick,.tick,.read inv target], ?_, rfl, rfl, rfl⟩
+ change execute M.program (1 + oppositeLookup.length) ⟨_,idx,fun _ => 0, fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]; rfl
+
+omit [Module (ZMod 2) Tag] [DecidableEq V] [DecidableEq Tag] [DecidableEq L] in
+/-- The two native reads on any occupied outgoing slot return the incoming
+slot of the same arc. The numbers used here are the paper's slot numbers by
+`rectangular_slot`. Lane zero can use the destination site to read off the
+remaining-lane displacement; the other lanes use the same matching. -/
+theorem lookup_from_tables {w rows inverse : ℕ} (layout : Bool) (i : ActualId P subdiv pad)
+ {deg : ℕ} (hc : ∀ b, Fintype.card {e // (slotDirectory P subdiv vertices tags lanes layout (pad := pad)).owner e = b} = deg)
+ (m : Memory w) (tab : Tables (slotDirectory P subdiv vertices tags lanes layout) deg rows inverse hc m)
+ (p : Fin 2 → Word w) (hrow : (p 0).val = rows) (hinv : (p 1).val = inverse)
+ (hrows : rows + ((N*(J*nL))*2)*deg ≤ 2^w)
+ (hfields : inverse + RecordCount N J nL d c pad subdiv*2 ≤ 2^w) :
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad)
+ let src := Fin.ofNat (2^w) (sortedFields D deg hc (i,0)).val
+ let dst := Fin.ofNat (2^w) (sortedFields D deg hc (i,1)).val
+ let M := (template oppositeLookup 2).instantiate w p
+ ∃ es, execute M.program 10 (M.program.start src) m [] = some ⟨es, some dst⟩ ∧
+ after m es = m ∧ es.length = 9 ∧ countProbes es = 2 := by
+ intro D src dst M
+ let a := D.address (i,0)
+ let b := D.address (i,1)
+ have hab : a.val+1 = b.val := by
+ change 0 + 2 * (arcAddress P subdiv vertices tags lanes pad i).val + 1 =
+ 1 + 2 * (arcAddress P subdiv vertices tags lanes pad i).val
+ omega
+ have hs : (p 0 + src).val = rows + (sortedFields D deg hc (i,0)).val := by
+ have h := (sortedFields D deg hc (i,0)).isLt
+ rw [Fin.val_add, hrow, show src.val = _ from Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)]
+ have ha : m (p 0 + src).val = Fin.ofNat (2^w) a.val := by rw [hs]; exact tab.bySlot (i,0)
+ have hb : (p 1 + (m (p 0 + src).val + 1)).val = inverse + b.val := by
+ have fit : b.val < RecordCount N J nL d c pad subdiv * 2 := b.isLt
+ have bfit : b.val < 2^w := by omega
+ have total : inverse+b.val < 2^w := by omega
+ rw [ha, Fin.val_add, hinv, Fin.val_add, Fin.val_ofNat, Fin.val_one',
+ Nat.mod_eq_of_lt (show a.val < 2^w by omega), Nat.mod_eq_of_lt (show 1 < 2^w by omega),
+ hab, Nat.mod_eq_of_lt bfit, Nat.mod_eq_of_lt total]
+ have hr : m (p 1 + (m (p 0 + src).val + 1)).val = dst := by rw [hb]; exact tab.byField (i,1)
+ simpa only [hr] using oppositeLookup_native p m src
+
+end CompressorRecords.SlotSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOrder.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOrder.lean
new file mode 100644
index 0000000000..55f0c12f73
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOrder.lean
@@ -0,0 +1,198 @@
+import OAI.Computability.VPVNP.CompressorSlotAddresses
+
+/-!
+# Ordering actual compressor arc records at each endpoint
+
+In a single endpoint fiber the high-order relative key already distinguishes
+all genuine arcs. Hence adding the absolute lane as a low-order address digit
+preserves their order. The padding records come afterwards, in dummy-number
+order at the unique dummy source for this fiber.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.Slots
+
+open Compression Compression.PackingData Compression.SurvivingSlots
+
+variable {V H Tag L : Type*} {d c N J nL pad : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- The orientation bit selects the outgoing (false) or incoming (true) role. -/
+def endRole (layout side : Bool) : Fin 4 → PackedRole :=
+ if side then targetRole layout else sourceRole layout
+
+/-- From the source site of a dummy, recover its site at the selected end. -/
+def dummyEnd (side : Bool) : Equiv.Perm (Site V Tag L) :=
+ if side then
+ (Equiv.prodAssoc V Tag L).symm.trans
+ (((cycleTags tags).prodCongr (Equiv.refl L)).trans (Equiv.prodAssoc V Tag L))
+ else Equiv.refl _
+
+/-- The actual endpoint used as the owner of an arc record's field. -/
+def actualEnd (layout side : Bool) : ActualId P subdiv pad → Site V Tag L :=
+ Sum.elim (endpoint (P.survivingRole layout) (endRole layout side))
+ (fun x ↦ dummyEnd tags side x.1)
+
+/-- Base identifier used by the regularized slot permutation. -/
+def paddedBaseId : ActualId P subdiv pad → PaddedId (V × Tag) (Id P.BaseMotif subdiv) pad :=
+ Sum.map (baseId P subdiv) (fun x ↦ (packedBase x.1, x.2))
+
+private theorem genuine_lt_dummy (i : Id P.Motif subdiv) (x : Site V Tag L × Fin pad) :
+ arcAddress P subdiv vertices tags lanes pad (.inl i) < arcAddress P subdiv vertices tags lanes pad (.inr x) := by
+ let a := finProdFinEquiv (relativeKey P subdiv vertices tags i, lanes (P.sourceLane i.2.1))
+ let s := finProdFinEquiv (vertices x.1.1, finProdFinEquiv (tags x.1.2.1, lanes x.1.2.2))
+ change a.val < keyCount N J d c subdiv * nL + (finProdFinEquiv (s, x.2)).val
+ exact a.isLt.trans_le (Nat.le_add_right _ _)
+
+private theorem dummy_lt_dummy (s : Site V Tag L) (a b : Fin pad) :
+ arcAddress P subdiv vertices tags lanes pad (.inr (s,a)) <
+ arcAddress P subdiv vertices tags lanes pad (.inr (s,b)) ↔ a < b := by
+ let site := finProdFinEquiv (vertices s.1, finProdFinEquiv (tags s.2.1, lanes s.2.2))
+ change keyCount N J d c subdiv * nL + (a.val + pad * site.val) <
+ keyCount N J d c subdiv * nL + (b.val + pad * site.val) ↔ a.val < b.val
+ omega
+
+/-- The absolute-address comparison in one genuine endpoint fiber is exactly
+the comparison of the two relative keys used by the base slot numbering. -/
+theorem address_lt_iff_relative (layout : Bool) (pick : Fin 4 → PackedRole)
+ {i j : Id P.Motif subdiv} (h : endpoint (P.survivingRole layout) pick i =
+ endpoint (P.survivingRole layout) pick j) :
+ arcAddress P subdiv vertices tags lanes pad (.inl i) < arcAddress P subdiv vertices tags lanes pad (.inl j) ↔
+ relativeKey P subdiv vertices tags i < relativeKey P subdiv vertices tags j := by
+ let addr (x : Id P.Motif subdiv) := (arcAddress P subdiv vertices tags lanes pad (.inl x)).val
+ let key (x : Id P.Motif subdiv) := (relativeKey P subdiv vertices tags x).val
+ have quotient (x : Id P.Motif subdiv) : addr x / nL = key x :=
+ address_div_lane P subdiv vertices tags lanes pad x
+ have monotone (x y : Id P.Motif subdiv) (ha : addr x ≤ addr y) : key x ≤ key y := by
+ rw [← quotient, ← quotient]
+ exact Nat.div_le_div_right ha
+ constructor
+ · intro ha
+ refine lt_of_le_of_ne (monotone _ _ ha.le) ?_
+ intro hk
+ have hb : baseId P subdiv i = baseId P subdiv j := P.slotIdentifier_injective vertices tags subdiv hk
+ let f := incidentBaseEquiv P subdiv layout pick (endpoint (P.survivingRole layout) pick j)
+ have he : i = j := congrArg Subtype.val (f.injective
+ (show f ⟨i, h⟩ = f ⟨j, rfl⟩ from Subtype.ext hb))
+ exact (ne_of_lt ha) (congrArg (fun x ↦ arcAddress P subdiv vertices tags lanes pad (.inl x)) he)
+ · intro hk
+ exact lt_of_not_ge (fun ha ↦ (not_le_of_gt hk) (monotone _ _ ha))
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+private theorem genuineEnd_card (hc : 2 ≤ c) (layout side : Bool) (s : Site V Tag L) :
+ Fintype.card {i : Id P.Motif subdiv // endpoint (P.survivingRole layout) (endRole layout side) i = s} =
+ survivingDegree d c subdiv := by
+ cases side
+ · exact (P.survivingSlot_degree hc layout subdiv s).1
+ · exact (P.survivingSlot_degree hc layout subdiv s).2
+
+private def dummyFiberEquiv (side : Bool) (s : Site V Tag L) :
+ {x : Site V Tag L × Fin pad // dummyEnd tags side x.1 = s} ≃ Fin pad where
+ toFun x := x.1.2
+ invFun j := ⟨((dummyEnd tags side).symm s, j), (dummyEnd tags side).apply_symm_apply _⟩
+ left_inv x := Subtype.ext (Prod.ext ((dummyEnd tags side).symm_apply_eq.mpr x.2.symm) rfl)
+ right_inv _ := rfl
+
+/-- Every actual endpoint has all the surviving slots and every padding slot. -/
+theorem actualEnd_card (hc : 2 ≤ c) (layout side : Bool) (s : Site V Tag L) :
+ Fintype.card {i : ActualId P subdiv pad // actualEnd P subdiv tags layout side i = s} =
+ survivingDegree d c subdiv + pad := by
+ rw [Fintype.card_congr Equiv.subtypeSum, Fintype.card_sum]
+ exact congrArg₂ (· + ·) (genuineEnd_card P subdiv hc layout side s)
+ ((Fintype.card_congr (dummyFiberEquiv tags side (pad := pad) s)).trans (Fintype.card_fin pad))
+
+/-- A zero-based position within the endpoint row obtained by scanning the
+entire numeric address space. -/
+abbrev addressRank (layout side : Bool) (i : ActualId P subdiv pad) :=
+ Fintype.card {j : ActualId P subdiv pad //
+ actualEnd P subdiv tags layout side j = actualEnd P subdiv tags layout side i ∧
+ arcAddress P subdiv vertices tags lanes pad j < arcAddress P subdiv vertices tags lanes pad i}
+
+private theorem addressRank_genuine (layout side : Bool) (i : Id P.Motif subdiv)
+ (r : IncidentRow (endpoint (P.survivingRole layout) (endRole layout side))
+ (endpoint (P.survivingRole layout) (endRole layout side) i)) :
+ addressRank P subdiv vertices tags lanes layout side (pad := pad) (.inl i) =
+ rowRank P subdiv vertices tags i r.ids := by
+ classical
+ let A := arcAddress P subdiv vertices tags lanes pad
+ let ep := actualEnd P subdiv tags layout side (pad := pad)
+ have empty : IsEmpty {x : Site V Tag L × Fin pad //
+ ep (.inr x) = ep (.inl i) ∧ A (.inr x) < A (.inl i)} :=
+ ⟨fun x ↦ (asymm x.2.2) (genuine_lt_dummy P subdiv vertices tags lanes i x.1)⟩
+ change Fintype.card {j // ep j = ep (.inl i) ∧ A j < A (.inl i)} = _
+ rw [Fintype.card_congr Equiv.subtypeSum, Fintype.card_sum,
+ Fintype.card_eq_zero (α := {x : Site V Tag L × Fin pad //
+ ep (.inr x) = ep (.inl i) ∧ A (.inr x) < A (.inl i)}), Nat.add_zero]
+ rw [Fintype.card_subtype]
+ change _ = r.ids.countP (fun j ↦ decide (relativeKey P subdiv vertices tags j < relativeKey P subdiv vertices tags i))
+ rw [← r.nodup.card_eq_countP (P := fun j ↦ relativeKey P subdiv vertices tags j < relativeKey P subdiv vertices tags i)]
+ congr 1
+ ext j
+ simp only [Finset.mem_filter, Finset.mem_univ, true_and, List.mem_toFinset, r.complete]
+ exact and_congr_right fun h ↦ address_lt_iff_relative P subdiv vertices tags lanes layout (endRole layout side) h
+
+private theorem addressRank_dummy (hc : 2 ≤ c) (layout side : Bool) (s : Site V Tag L) (a : Fin pad) :
+ addressRank P subdiv vertices tags lanes layout side (.inr (s,a)) = survivingDegree d c subdiv + a.val := by
+ classical
+ let A := arcAddress P subdiv vertices tags lanes pad
+ let ep := actualEnd P subdiv tags layout side (pad := pad)
+ let real := Equiv.subtypeEquivRight (fun j : Id P.Motif subdiv ↦
+ show ep (.inl j) = ep (.inr (s,a)) ∧ A (.inl j) < A (.inr (s,a)) ↔ ep (.inl j) = ep (.inr (s,a)) from
+ and_iff_left (genuine_lt_dummy P subdiv vertices tags lanes j (s,a)))
+ let dummy : {x : Site V Tag L × Fin pad //
+ ep (.inr x) = ep (.inr (s,a)) ∧ A (.inr x) < A (.inr (s,a))} ≃ {b : Fin pad // b.val < a.val} := {
+ toFun x := ⟨x.1.2, by
+ have hs := (dummyEnd tags side).injective x.2.1
+ have h := x.2.2
+ rcases x with ⟨⟨s', b⟩, _⟩
+ change s' = s at hs
+ subst s'
+ exact (dummy_lt_dummy P subdiv vertices tags lanes s b a).mp h⟩
+ invFun b := ⟨(s,b), rfl, (dummy_lt_dummy P subdiv vertices tags lanes s b a).mpr b.2⟩
+ left_inv x := Subtype.ext (Prod.ext ((dummyEnd tags side).injective x.2.1).symm rfl)
+ right_inv _ := rfl }
+ change Fintype.card {j // ep j = ep (.inr (s,a)) ∧ A j < A (.inr (s,a))} = _
+ rw [Fintype.card_congr Equiv.subtypeSum, Fintype.card_sum, Fintype.card_congr real, Fintype.card_congr dummy,
+ Fintype.card_fin_lt_of_le a.isLt.le]
+ exact congrArg (· + a.val) (genuineEnd_card P subdiv hc layout side (dummyEnd tags side s))
+
+private noncomputable def allIncident {E S : Type*} [Fintype E] [DecidableEq S] (endSite : E → S) (s : S) :
+ IncidentRow endSite s := by
+ let fiber := Finset.univ.filter (fun e ↦ endSite e = s)
+ exact ⟨fiber.toList, fiber.nodup_toList, fun _ ↦ by simp [fiber]⟩
+
+variable [Module (ZMod 2) Tag]
+
+/-- Address order in either endpoint fiber agrees with the full regularized
+slot indexing, both on genuine arcs and on the dummy tail. -/
+theorem addressRank_eq_slot (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (layout side : Bool) {d' : ℕ} (hd : survivingDegree d c subdiv ≤ d') (hJ : 1 < J)
+ (i : ActualId P subdiv (d' - survivingDegree d c subdiv)) :
+ let := P.slotIdentifierOrder vertices tags subdiv
+ let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ
+ addressRank P subdiv vertices tags lanes layout side i =
+ ((if side then I.incoming else I.outgoing) (paddedBaseId P subdiv i)).2.val := by
+ intro order I
+ rcases i with i | ⟨s,a⟩
+ · let r (b : Bool) := allIncident (endpoint (P.survivingRole layout) (endRole layout b) (subdiv := subdiv))
+ (endpoint (P.survivingRole layout) (endRole layout b) i)
+ rw [addressRank_genuine P subdiv vertices tags lanes layout side i (r side)]
+ have h := actualSlot_numbers P subdiv vertices tags hc hφ layout hd hJ i (r false) (r true)
+ cases side
+ · exact h.1
+ · exact h.2
+ · rw [addressRank_dummy P subdiv vertices tags lanes hc layout side s a]
+ cases side <;> rfl
+
+end CompressorRecords.Slots
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOutputLayout.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOutputLayout.lean
new file mode 100644
index 0000000000..0cf1dcdbf4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOutputLayout.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.CompressorSlotLevel
+import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout
+
+/-!
+# The six shared columns of a shrinking output
+
+The sorted slot pass already writes the base mate and displacement. Allocate
+the base inverse, actual forward and inverse, and outgoing widths in the
+following address ranges. Their lengths are the actual numbers of base or
+lifted slots. The full six-column directory then supplies subsequent passes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots
+
+open SlotLevel BurstRAM Compression Slots
+
+variable (s : Shape) (h : Heads)
+
+/-- Number of outgoing ports in the next graph across all packed sites and residual lanes. -/
+def actualCount := sites s*s.newDegree
+/-- First address after the base displacement table, reserved for the inverse base matching. -/
+def inverseBaseHead := stopAddress s h
+/-- Start of the outgoing actual mate column, immediately after the inverse base matching. -/
+def outHead := inverseBaseHead s h+baseArcs s
+/-- Start of the incoming actual mate column, immediately after the outgoing actual mates. -/
+def inHead := outHead s h+actualCount s
+/-- Start of the outgoing actual width column, immediately after the incoming actual mates. -/
+def widthHead := inHead s h+actualCount s
+/-- First free address following the last outgoing width in the shrinking output directory. -/
+def finish := widthHead s h+actualCount s
+
+/-- Source and destination addresses for scattering the forward base matching into its inverse. -/
+def inverseBank (w : ℕ) : Fin 2 → Word w := (Fin.ofNat (2^w)) ∘ ![targetsHead s h,inverseBaseHead s h]
+
+/-- Public degree, lane count, matching, displacement, and destination parameters for lifting
+the forward or inverse base matching to actual ports. -/
+def actualBank (reverse : Bool) (w : ℕ) : Fin 5 → Word w :=
+ (Fin.ofNat (2^w)) ∘ ![s.newDegree,s.lanes,if reverse then inverseBaseHead s h else targetsHead s h,
+ shiftsHead s h,if reverse then inHead s h else outHead s h]
+
+/-- The radices, genuine range bound, and row, split-width, and output addresses used to gather
+widths in actual outgoing-port order. -/
+def widthBank (splitHead w : ℕ) : Fin 8 → Word w :=
+ (Fin.ofNat (2^w)) ∘ ![s.newDegree,s.lanes,∑t,s.subdivisions t,oldBaseArcCount s.bases s.tags s.oldDegree s.colors,
+ keyCount s.bases s.tags s.oldDegree s.colors s.subdivisions*s.lanes,rowsHead s h,splitHead,widthHead s h]
+
+/-- Assemble the six public column addresses for the next state's base mates, displacements,
+actual mates, and widths. -/
+def directory (w : ℕ) : IncidenceDirectory w :=
+ ⟨Fin.ofNat _ (targetsHead s h),Fin.ofNat _ (inverseBaseHead s h),Fin.ofNat _ (shiftsHead s h),
+ Fin.ofNat _ (outHead s h),Fin.ofNat _ (inHead s h),Fin.ofNat _ (widthHead s h)⟩
+
+/-- Natural-address readback of the six arrays in their canonical finite port orders. -/
+structure Stored {a l w : ℕ} (Y : State a l) (m : Memory w) : Prop where
+ baseOut : ∀ e, m (targetsHead s h+(IncidenceDirectory.baseOrder Y e).val) =
+ Fin.ofNat _ (IncidenceDirectory.baseOrder Y (Y.slots.base.target e)).val
+ baseIn : ∀ e, m (inverseBaseHead s h+(IncidenceDirectory.baseOrder Y e).val) =
+ Fin.ofNat _ (IncidenceDirectory.baseOrder Y (Y.slots.base.target.symm e)).val
+ shift : ∀ e, m (shiftsHead s h+(IncidenceDirectory.baseOrder Y e).val) =
+ Fin.ofNat _ (bitWordFinEquiv l (Y.slots.displacement e)).val
+ actualOut : ∀ e, m (outHead s h+(IncidenceDirectory.actualOrder Y e).val) =
+ Fin.ofNat _ (IncidenceDirectory.actualOrder Y (Y.slots.actualGraph.target e)).val
+ actualIn : ∀ e, m (inHead s h+(IncidenceDirectory.actualOrder Y e).val) =
+ Fin.ofNat _ (IncidenceDirectory.actualOrder Y (Y.slots.actualGraph.target.symm e)).val
+ width : ∀ e, m (widthHead s h+(IncidenceDirectory.actualOrder Y e).val) = Fin.ofNat _ (Y.width ((e.1.1,e.2),e.1.2))
+
+private theorem add_index {w n : ℕ} (base : ℕ) (i : Fin n) (bound : base+n ≤ 2^w) :
+ ((Fin.ofNat (2^w) base : Word w)+Fin.ofNat _ i.val).val=base+i.val := by
+ have hi := i.isLt
+ rw [Fin.val_add,Fin.val_ofNat,Fin.val_ofNat,Nat.mod_eq_of_lt (by omega : base < 2^w),
+ Nat.mod_eq_of_lt (by omega : i.val < 2^w),Nat.mod_eq_of_lt (by omega)]
+
+/-- The numeric arrays are precisely the common incidence directory expected
+by the next cursor, shrink or refresh calculation. -/
+theorem Stored.represents {s : Shape} {h : Heads} {a l w : ℕ} {Y : State a l} {m : Memory w}
+ (data : Stored s h Y m) (hb : Fintype.card Y.Base*2^a=baseArcs s)
+ (ha : Fintype.card Y.Base*2^l*2^a=actualCount s) (fit : finish s h < 2^w) :
+ (directory s h w).Represents Y m := by
+ have h₁ : targetsHead s h+baseArcs s=shiftsHead s h := rfl
+ have h₂ : shiftsHead s h+baseArcs s=inverseBaseHead s h := rfl
+ have h₃ : inverseBaseHead s h+baseArcs s=outHead s h := rfl
+ have h₄ : outHead s h+actualCount s=inHead s h := rfl
+ have h₅ : inHead s h+actualCount s=widthHead s h := rfl
+ have h₆ : widthHead s h+actualCount s=finish s h := rfl
+ constructor <;> intro e <;> simp only [IncidenceDirectory.basePort_number,IncidenceDirectory.actualPort_number,
+ directory,CursorRAM.encode] <;> rw [add_index _ _ (by omega)]
+ · exact data.baseOut e
+ · exact data.baseIn e
+ · exact data.shift e
+ · exact data.actualOut e
+ · exact data.actualIn e
+ · exact data.width e
+
+end CompressorRecords.ShrinkSlots
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOutputRecipe.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOutputRecipe.lean
new file mode 100644
index 0000000000..932e440a5c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOutputRecipe.lean
@@ -0,0 +1,232 @@
+import OAI.Computability.VPVNP.CompressorSlotLevelRecipe
+import OAI.Computability.VPVNP.CompressorSlotOutputLayout
+
+/-!
+# Planning the shrinking output columns
+
+The base inverse, two actual incidence permutations, and width column are
+allocated immediately after the sorted slot directory. Their native planner
+rows are computed from the selected level's counts and heads. Only the width
+worker also reads the head of the already materialized split-width input.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots.Recipe
+
+open SlotLevel.Recipe PhaseRecipe BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+/-- The four output passes following base matching, inverting base mates, expanding actual
+mates in each direction, and collecting outgoing widths. -/
+inductive Phase where
+ | baseInverse | actualOut | actualIn | widths
+ deriving DecidableEq
+
+/-- Number of public words required by each output worker, two for base inversion, five for
+actual incidence, and eight for widths. -/
+abbrev arity : Phase → ℕ
+ | .baseInverse => 2
+ | .actualOut | .actualIn => 5
+ | .widths => 8
+
+/-- Exclusive output scan bound, counting base ports for the inverse scan and actual ports for
+the other three passes. -/
+def limit (s : SlotLevel.Shape) : Phase → ℕ
+ | .baseInverse => SlotLevel.baseArcs s
+ | .actualOut | .actualIn | .widths => actualCount s
+
+/-- Select the native parameter bank for the requested output phase, including the split-width
+input head for the width scan. -/
+def bank (s : SlotLevel.Shape) (h : SlotLevel.Heads) (split w : ℕ) : (p : Phase) → Fin (arity p) → Word w
+ | .baseInverse => inverseBank s h w
+ | .actualOut => actualBank s h false w
+ | .actualIn => actualBank s h true w
+ | .widths => widthBank s h split w
+
+/-- Controller row containing the output worker tag, zero starting cursor, exclusive stop, and
+public parameters. -/
+def frame {w : ℕ} (s : SlotLevel.Shape) (h : SlotLevel.Heads) (split : ℕ)
+ (tag : Phase → Word w) (p : Phase) : List (Word w) :=
+ tag p :: 0 :: Fin.ofNat _ (limit s p) :: List.ofFn (bank s h split w p)
+
+/-- Native expressions for the additional addresses and the shared lane-slot count. -/
+structure Columns where
+ /-- Planner expression for the number of actual outgoing ports, the common length of the two
+ mate columns and the width column. -/
+ count : Expr
+ /-- Planner expression for the start of the inverse base-matching column following the base
+ displacement column. -/
+ baseInverse : Expr
+ /-- Planner expression for the start of the actual forward mate column. -/
+ actualOut : Expr
+ /-- Planner expression for the start of the actual inverse mate column. -/
+ actualIn : Expr
+ /-- Planner expression for the start of the actual outgoing-width column. -/
+ width : Expr
+ /-- Planner expression for the first free address after the last output column. -/
+ finish : Expr
+
+/-- Derive the output count and column boundaries from the current slot level's computed
+dimensions and stop address. -/
+def columns (T : SlotLevel.Recipe.Template) (I : Inputs) : Columns :=
+ let c := counts T I
+ let count := c.sites.mul (.lit T.newDegree)
+ let out := c.stopAddress.add c.baseArcs
+ let incoming := out.add count
+ let width := incoming.add count
+ ⟨count,c.stopAddress,out,incoming,width,width.add count⟩
+
+variable {w : ℕ} (T : SlotLevel.Recipe.Template) (I : Inputs) (split : Expr)
+variable {pub : Fin 5 → Word w} {state : Word w} {m : Memory w} {bases lanes : ℕ} {h : SlotLevel.Heads}
+variable (read : Reads I pub state m bases lanes h)
+
+/-- Evaluating the planner expressions yields the word encodings of the actual port count, the
+four output heads, and the final address. -/
+structure ColumnValues (c : Columns) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w)
+ (s : SlotLevel.Shape) (h : SlotLevel.Heads) : Prop where
+ count : c.count.eval pub state m = (actualCount s : Word w)
+ baseInverse : c.baseInverse.eval pub state m = (inverseBaseHead s h : Word w)
+ actualOut : c.actualOut.eval pub state m = (outHead s h : Word w)
+ actualIn : c.actualIn.eval pub state m = (inHead s h : Word w)
+ width : c.width.eval pub state m = (widthHead s h : Word w)
+ finish : c.finish.eval pub state m = (ShrinkSlots.finish s h : Word w)
+
+include read in
+theorem eval_columns : ColumnValues (columns T I) pub state m (T.shape bases lanes) h := by
+ let s := T.shape bases lanes
+ let c := counts T I
+ have hc := eval_counts T I read
+ have sites : c.sites.eval pub state m = (SlotLevel.sites s : Word w) := congrArg Counts.sites hc
+ have stop : c.stopAddress.eval pub state m = (inverseBaseHead s h : Word w) := congrArg Counts.stopAddress hc
+ have arcs : c.baseArcs.eval pub state m = (SlotLevel.baseArcs s : Word w) := congrArg Counts.baseArcs hc
+ have size : (columns T I).count.eval pub state m = (actualCount s : Word w) := by
+ change c.sites.eval pub state m * (T.newDegree : Word w) = _
+ rw [sites, ← Nat.cast_mul]
+ rfl
+ have plus {a b : Expr} {x y : ℕ} (hx : a.eval pub state m = (x : Word w))
+ (hy : b.eval pub state m = (y : Word w)) : (a.add b).eval pub state m = ((x+y : ℕ) : Word w) := by
+ change a.eval pub state m + b.eval pub state m = _
+ rw [hx,hy,Nat.cast_add]
+ have out : (columns T I).actualOut.eval pub state m = (outHead s h : Word w) := plus stop arcs
+ have incoming : (columns T I).actualIn.eval pub state m = (inHead s h : Word w) := plus out size
+ have width : (columns T I).width.eval pub state m = (widthHead s h : Word w) := plus incoming size
+ exact ⟨size,stop,out,incoming,width,plus width size⟩
+
+/-- All six heads in the order used by the next level's incidence header. -/
+def columnHeads : Fin 6 → Expr :=
+ let c := counts T I
+ let col := columns T I
+ ![c.targets, col.baseInverse, c.shifts, col.actualOut, col.actualIn, col.width]
+
+include read in
+theorem eval_columnHeads (j : Fin 6) :
+ (columnHeads T I j).eval pub state m = (directory (T.shape bases lanes) h w).column j := by
+ have hc := eval_counts T I read
+ have hs := eval_columns T I read
+ fin_cases j
+ exacts [congrArg Counts.targets hc, hs.baseInverse, congrArg Counts.shifts hc, hs.actualOut, hs.actualIn, hs.width]
+
+/-- Construct the cursor-stop expression for a base inverse, actual mate, or width scan. -/
+def stop : Phase → Expr
+ | .baseInverse => (counts T I).baseArcs
+ | .actualOut | .actualIn | .widths => (columns T I).count
+
+private def actualParams (reverse : Bool) : Fin 5 → Expr :=
+ let c := counts T I
+ let col := columns T I
+ ![.lit T.newDegree, I.lanes, if reverse then col.baseInverse else c.targets, c.shifts,
+ if reverse then col.actualIn else col.actualOut]
+
+/-- Construct the ordered parameter expressions for one output worker from the level inputs
+and, for widths, the split table head. -/
+def params : (p : Phase) → Fin (arity p) → Expr
+ | .baseInverse => ![(counts T I).targets, (columns T I).baseInverse]
+ | .actualOut => actualParams T I false
+ | .actualIn => actualParams T I true
+ | .widths =>
+ let c := counts T I
+ ![.lit T.newDegree, I.lanes, .lit (∑ t, T.subdivisions t), c.oldBaseArcs, c.genuineArcs,
+ c.rows, split, (columns T I).width]
+
+/-- Assemble one output worker recipe from its dispatch tag, zero starting cursor, computed
+stop, and parameter expressions. -/
+def phase (tag : Phase → ℕ) (p : Phase) : PhaseRecipe.Phase (arity p) :=
+ ⟨tag p, .lit 0, stop T I p, params T I split p⟩
+
+variable (tag : Phase → ℕ) (p : Phase)
+variable {splitHead : ℕ} (hsplit : split.eval pub state m = (splitHead : Word w))
+
+include read in
+theorem eval_stop :
+ (stop T I p).eval pub state m = Fin.ofNat (2^w) (limit (T.shape bases lanes) p) := by
+ cases p
+ case baseInverse => exact congrArg Counts.baseArcs (eval_counts T I read)
+ all_goals exact (eval_columns T I read).count
+
+include read hsplit in
+theorem eval_params (i : Fin (arity p)) :
+ (params T I split p i).eval pub state m = bank (T.shape bases lanes) h splitHead w p i := by
+ have hc := eval_counts T I read
+ have hs := eval_columns T I read
+ cases p with
+ | baseInverse =>
+ fin_cases i
+ exacts [congrArg Counts.targets hc, hs.baseInverse]
+ | actualOut =>
+ fin_cases i
+ exacts [rfl,read.lanes_eq,congrArg Counts.targets hc,congrArg Counts.shifts hc,hs.actualOut]
+ | actualIn =>
+ fin_cases i
+ exacts [rfl,read.lanes_eq,hs.baseInverse,congrArg Counts.shifts hc,hs.actualIn]
+ | widths =>
+ fin_cases i
+ exacts [rfl,read.lanes_eq,rfl,congrArg Counts.oldBaseArcs hc,congrArg Counts.genuineArcs hc,
+ congrArg Counts.rows hc,hsplit,hs.width]
+
+include read hsplit in
+theorem recipe_words :
+ (phase T I split tag p).recipe.words pub state m =
+ frame (T.shape bases lanes) h splitHead (fun q ↦ (tag q : Word w)) p := by
+ rw [PhaseRecipe.recipe_words]
+ change _ :: _ :: (stop T I p).eval pub state m :: List.ofFn (fun i ↦ (params T I split p i).eval pub state m) =
+ _ :: _ :: _ :: List.ofFn _
+ rw [eval_stop T I read p, show (fun i ↦ (params T I split p i).eval pub state m) =
+ bank (T.shape bases lanes) h splitHead w p from funext (eval_params T I split read p hsplit)]
+ rfl
+
+/-- Extend the output worker's recipe to the scheduler's common parameter count with trailing
+zero operands. -/
+def padded (g : ℕ) (room : arity p ≤ g) : PhaseRecipe.Phase g :=
+ PhaseRecipe.Phase.ofParams room (tag p) (.lit 0) (stop T I p) (params T I split p)
+
+include read hsplit in
+theorem padded_words (g : ℕ) (room : arity p ≤ g) :
+ (padded T I split tag p g room).recipe.words pub state m =
+ frame (T.shape bases lanes) h splitHead (fun q ↦ (tag q : Word w)) p ++ List.replicate (g-arity p) 0 := by
+ rw [← recipe_words T I split read tag p hsplit]
+ exact pad_phase_words room (phase T I split tag p) pub state m
+
+include read hsplit in
+theorem execute_padded (g : ℕ) (room : arity p ≤ g) (cap : ℕ)
+ (budget : (padded T I split tag p g room).recipe.code.length < cap)
+ (fit : (Controller.rowBase g pub m).val + (g+3) ≤ 2^w) :
+ let R := (padded T I split tag p g room).recipe
+ let M := R.acceptTable.instantiate w pub
+ let es := (R.report pub state m).events
+ execute M.program cap (M.program.start state) m [] = some ⟨es,none⟩ ∧
+ Greedy.Stores (after m es) (Controller.rowBase g pub m)
+ (frame (T.shape bases lanes) h splitHead (fun q ↦ (tag q : Word w)) p ++ List.replicate (g-arity p) 0) ∧
+ (∀ a, a < (Controller.rowBase g pub m).val ∨ (Controller.rowBase g pub m).val + (g+3) ≤ a →
+ after m es a = m a) ∧ countProbes es = R.reads+(g+3) ∧ choiceBits es = [] := by
+ have he := execute_phase (padded T I split tag p g room) pub state m cap budget fit
+ rw [← PhaseRecipe.recipe_words, padded_words T I split read tag p hsplit g room] at he
+ exact he
+
+end CompressorRecords.ShrinkSlots.Recipe
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOwnerAgreement.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerAgreement.lean
new file mode 100644
index 0000000000..8f9aa9072c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerAgreement.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.CompressorSlotOwnerDecode
+import OAI.Computability.VPVNP.CompressorSlotOwners
+
+/-!
+# The physical endpoint owner stream for a selected layout
+
+A dense original arc record stores the selected layout's three packed sites and
+its CD indicator. With these input records and the four subdivision counts, the
+native genuine and dummy workers compute the exact owner of every absolute
+field in the shrinking directory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotOwners
+
+open Compression Compression.PackingData Compression.SurvivingSlots Slots SlotSchedule BurstRAM
+
+variable {V H Tag L : Type*} {d c N J nL pad w : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- Column offsets of the three site words in the old arc record. -/
+def roleOffset : PackedRole → ℕ
+ | .a => 0
+ | .b => 1
+ | .d => 2
+
+private theorem role_lt (r : PackedRole) : roleOffset r < 3 := by cases r <;> decide
+
+/-- The layout parameters and physical input columns for the genuine worker.
+Every original arc has a CD indicator. Its site words are used only on CD arcs. -/
+structure GenuineTables (layout : Bool) (p : Fin 8 → Word w) (m : Memory w) : Prop where
+ laneCount : (p 0).val = nL
+ subdivCount : (p 1).val = ∑ t, subdiv t
+ baseCount : (p 2).val = oldBaseArcCount N J d c
+ realCount : (p 6).val = (N*(J*nL))*2
+ arcFits : (p 3).val + 4 * (oldBaseArcCount N J d c * nL) ≤ 2^w
+ rolesFit : (p 4).val + 8 ≤ 2^w
+ subdivFits : (p 5).val + 4 ≤ 2^w
+ role : ∀ (t : Fin 4) (s : Fin 2),
+ (m ((p 4).val + (2*t.val+s.val))).val = roleOffset (endRole layout (decide (s=1)) t)
+ count : ∀ (t : Fin 4), (m ((p 5).val+t.val)).val = subdiv t
+ cd : ∀ a : Arc V H Tag L d c,
+ (m ((p 3).val + 4*(oldArcIndex P vertices tags lanes a).val + 3)).val = if isCD P a then 1 else 0
+ packed : ∀ (a : P.Motif) (r : PackedRole),
+ (m ((p 3).val + 4*(oldArcIndex P vertices tags lanes a.val).val + roleOffset r)).val =
+ (siteIndex vertices tags lanes (P.survivingRole layout r a)).val
+
+private theorem wordOwner_at {E : Type*} {A B : ℕ} (D : Directory E A B) (j : Fin A) (u : Word w) (h : u.val = j.val) :
+ D.wordOwner u = Fin.ofNat _ (D.destination j).val := by
+ have hj : u.val < A := h ▸ j.isLt
+ simp only [Directory.wordOwner, encodedPlacement, dite_eq_left hj, Equiv.refl_symm,
+ Equiv.refl_apply]
+ rw [show (⟨u.val,hj⟩ : Fin A) = j from Fin.ext h]
+
+/-- Every genuine worker output equals the directory word at this absolute ID,
+including IDs whose subdivision is too large or whose old arc is thick–thick. -/
+theorem genuine_directory (layout : Bool) (p : Fin 8 → Word w) (m : Memory w)
+ (tables : GenuineTables P subdiv vertices tags lanes layout p m) (i : Word w)
+ (hi : i.val < (keyCount N J d c subdiv * nL)*2) :
+ genuineOwner p m i = (slotDirectory P subdiv vertices tags lanes layout (pad := pad)).wordOwner i := by
+ let a : Fin (keyCount N J d c subdiv * nL) := ⟨i.val/2, by omega⟩
+ let s : Fin 2 := ⟨i.val%2, by omega⟩
+ let field := finProdFinEquiv (a.castAdd ((N*(J*nL))*pad),s)
+ have hfield : field.val = i.val := by change i.val%2+2*(i.val/2)=i.val; omega
+ let x := genuineDigits subdiv a
+ let old := digitArc P subdiv vertices tags lanes x
+ let t := x.1.1.1
+ let j := x.1.2.val
+ let f := natDigits (p 0).val (p 1).val (p 2).val i.val
+ let id := (oldArcIndex P vertices tags lanes old).val
+ let role := endRole layout (decide (s=1)) t
+ have ht : f.edgeType = t.val := by
+ dsimp only [f,natDigits]; rw [tables.laneCount, tables.subdivCount, tables.baseCount]; rfl
+ have hj : f.subdivision = j := by
+ dsimp only [f,natDigits]; rw [tables.laneCount, tables.subdivCount]; rfl
+ have hid : f.oldArc = id := by
+ dsimp only [f,natDigits]; rw [tables.laneCount, tables.subdivCount, tables.baseCount]
+ exact (digitArc_index P subdiv vertices tags lanes x).symm
+ have hs : f.side = s.val := rfl
+ have hrole := tables.role t s
+ have hc := tables.cd old
+ have hinput : GenuineInput p m i := by
+ have hold : id < oldBaseArcCount N J d c * nL := (oldArcIndex P vertices tags lanes old).isLt
+ have htype : t.val < 4 := t.isLt
+ have hside : s.val < 2 := s.isLt
+ have hf := tables.arcFits
+ have hr := tables.rolesFit
+ have hsd := tables.subdivFits
+ refine ⟨by omega, ?_, ?_, ?_, ?_, ?_, ?_⟩
+ · rw [tables.subdivCount]; have := x.1.2.isLt; omega
+ · change (p 3).val + 4*f.oldArc + 3 < 2^w; rw [hid]; omega
+ · change (p 4).val + (2*f.edgeType+f.side) < 2^w; rw [ht,hs]; omega
+ · change (p 5).val + f.edgeType < 2^w; rw [ht]; omega
+ · change (m ((p 4).val+(2*f.edgeType+f.side))).val < 3
+ rw [ht,hs,hrole]; exact role_lt _
+ · change (m ((p 3).val + 4*f.oldArc+3)).val ≤ 1
+ rw [hid,hc]; split <;> decide
+ rw [genuineOwner_eq _ _ _ hinput, wordOwner_at _ field i hfield.symm]
+ congr 1
+ have hdest := directory_genuine_destination P subdiv vertices tags lanes layout (pad := pad) a s
+ change (natGenuineOwner p m i.val) = _; rw [hdest]
+ change (if (m ((p 3).val+4*f.oldArc+3)).val = 1 ∧ f.subdivision < (m ((p 5).val+f.edgeType)).val
+ then 2*(m ((p 3).val+4*f.oldArc + (m ((p 4).val+(2*f.edgeType+f.side))).val)).val + f.side
+ else (p 6).val+i.val) = if j < subdiv t then if h : isCD P old then
+ 2*(siteIndex vertices tags lanes (P.survivingRole layout role ⟨old,h⟩)).val+s.val
+ else (N*(J*nL))*2+field.val else (N*(J*nL))*2+field.val
+ rw [ht,hj,hid,hs,hrole,hc,tables.count,tables.realCount,hfield]
+ by_cases hv : j < subdiv t
+ · by_cases hcd : isCD P old
+ · rw [ite_eq_left hcd, ite_eq_left ⟨rfl,hv⟩, ite_eq_left hv, dite_eq_left hcd]
+ exact congrArg (fun n => 2*n+s.val) (tables.packed ⟨old,hcd⟩ role)
+ · rw [ite_eq_right hcd, ite_eq_right (fun h => Nat.zero_ne_one h.1), ite_eq_left hv, dite_eq_right hcd]
+ · rw [ite_eq_right (fun h => hv h.2), ite_eq_right hv]
+
+/-- The dummy site table stores the tag successor with the same vertex and lane. -/
+structure DummyTables (pad : ℕ) (p : Fin 3 → Word w) (m : Memory w) : Prop where
+ twoFits : 2 < 2^w
+ padCount : (p 0).val = pad
+ nextFits : (p 1).val + N*(J*nL) ≤ 2^w
+ nextSite : ∀ b : Fin (N*(J*nL)), let site := siteIndex vertices tags lanes
+ (m ((p 1).val+b.val)).val = (site (dummyEnd tags true (site.symm b))).val
+
+/-- The dummy worker uses a local cursor while its physical directory field
+has an offset equal to the whole genuine interval. -/
+theorem dummy_directory (layout : Bool) (p : Fin 3 → Word w) (m : Memory w)
+ (tables : DummyTables vertices tags lanes pad p m) (i : Word w)
+ (hi : i.val < ((N*(J*nL))*pad)*2)
+ (fit : RecordCount N J nL d c pad subdiv * 2 ≤ 2^w) :
+ dummyOwner p m i = (slotDirectory P subdiv vertices tags lanes layout (pad := pad)).wordOwner
+ (Fin.ofNat _ ((keyCount N J d c subdiv * nL)*2+i.val)) := by
+ let a : Fin ((N*(J*nL))*pad) := ⟨i.val/2, by omega⟩
+ let s : Fin 2 := ⟨i.val%2, by omega⟩
+ let field := finProdFinEquiv (a.natAdd (keyCount N J d c subdiv * nL),s)
+ let localField := finProdFinEquiv (a,s)
+ have hl : localField.val = i.val := by change i.val%2+2*(i.val/2)=i.val; omega
+ have hg : field.val = (keyCount N J d c subdiv * nL)*2+i.val := by
+ change i.val%2+2*((keyCount N J d c subdiv * nL)+i.val/2) = _; omega
+ have hb : (Fin.ofNat (2^w) ((keyCount N J d c subdiv * nL)*2+i.val)).val = field.val := by
+ rw [← hg]; exact Nat.mod_eq_of_lt (field.isLt.trans_le fit)
+ have hs : a.divNat.val = i.val/2/pad := rfl
+ have hf : (p 1).val + i.val/2/(p 0).val < 2^w := by
+ rw [tables.padCount, ← hs]; have := a.divNat.isLt; have := tables.nextFits; omega
+ rw [dummyOwner_eq _ _ _ tables.twoFits hf, wordOwner_at _ field _ hb]
+ congr 1
+ rw [directory_dummy_destination P subdiv vertices tags lanes layout a s]
+ change (2*(if i.val%2 = 0 then i.val/2/(p 0).val else (m ((p 1).val+i.val/2/(p 0).val)).val)+i.val%2) =
+ 2*(if s.val=0 then localField.val/2/pad else _) + s.val
+ rw [hl, tables.padCount, ← hs, tables.nextSite]
+
+end CompressorRecords.SlotOwners
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOwnerAux.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerAux.lean
new file mode 100644
index 0000000000..d92bb383ec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerAux.lean
@@ -0,0 +1,231 @@
+import OAI.Computability.VPVNP.CompressorSlotOwnerAgreement
+import OAI.Computability.VPVNP.CompressorSlotOwnerRuns
+
+/-!
+# Native initialization of the auxiliary endpoint owner tables
+
+One eight-cell scan writes the selected layout's A, B, and D column offsets.
+Another scan rotates the tag digit of each site, keeping its vertex and lane.
+Both tables are produced by fixed straight-line programs, using one write per
+cell and no external reads.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotOwners.Aux
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open Compression Compression.SurvivingSlots Slots SlotSchedule
+
+variable {w : ℕ}
+
+private abbrev wd (n : ℕ) : Word w := Fin.ofNat _ n
+private abbrev div := @BinaryOp.eval w .div
+private abbrev mod := @BinaryOp.eval w .mod
+private abbrev xor := @BinaryOp.eval w .bitXor
+
+private theorem val_wd {i : ℕ} (hi : i < 2^w) : (wd (w := w) i).val = i := Nat.mod_eq_of_lt hi
+
+private theorem add_wd (a b : ℕ) : wd (w := w) a + wd b = wd (a+b) :=
+ Fin.ext (Nat.add_mod a b (2^w)).symm
+
+private theorem mul_wd (a b : ℕ) : wd (w := w) a * wd b = wd (a*b) :=
+ Fin.ext (Nat.mul_mod a b (2^w)).symm
+
+private theorem wd_val (b : Word w) : wd b.val = b := Fin.ext (Nat.mod_eq_of_lt b.isLt)
+
+private theorem div_wd {a b : ℕ} (ha : a < 2^w) (hb : b < 2^w) :
+ div (wd (w := w) a) (wd b) = wd (a/b) := by
+ change Fin.ofNat _ ((wd a : Word w).val/(wd b : Word w).val) = _
+ rw [val_wd ha, val_wd hb]
+
+private theorem mod_wd {a b : ℕ} (ha : a < 2^w) (hb : b < 2^w) :
+ mod (wd (w := w) a) (wd b) = wd (a%b) := by
+ change Fin.ofNat _ ((wd a : Word w).val%(wd b : Word w).val) = _
+ rw [val_wd ha, val_wd hb]
+
+/-- The edge type has two binary digits. Its incoming end has role D precisely
+when the digits differ. Its outgoing end has role D only on the last type. -/
+def roleCode : List (Op 10 2) :=
+ [.stateWord 0, .constant 1 1, .constant 2 2, .publicWord 3 0,
+ .binary .mod 4 0 2, .binary .div 5 0 2, .binary .mod 6 5 2, .binary .div 7 5 2,
+ .binary .sub 5 2 3, .binary .bitXor 8 6 7, .binary .mul 8 8 5, .binary .add 8 3 8,
+ .binary .mul 6 6 5, .binary .add 6 3 6, .binary .sub 9 1 3, .binary .sub 6 6 9,
+ .binary .mul 6 7 6, .binary .add 6 9 6, .binary .sub 8 8 6, .binary .mul 8 4 8,
+ .binary .add 8 6 8, .publicWord 9 1, .binary .add 9 9 0, .write 9 8, .binary .add 0 0 1]
+
+private def choose (b x y : Word w) := x + b*(y-x)
+
+/-- Select the role-site offset for an edge type and endpoint side in the chosen layout, using
+the low cursor bit for the side. -/
+def roleValue (l i : Word w) : Word w :=
+ let side := mod i 2
+ let t := div i 2
+ let low := mod t 2
+ let high := div t 2
+ let dst := choose (xor low high) l 2
+ let src := choose high (1-l) (choose low l 2)
+ choose side src dst
+
+private def oneWrite (n : ℕ) (a v : Word w) : List (Event w) :=
+ List.replicate n .tick ++ [.write a v, .tick]
+
+private theorem oneWrite_after (n : ℕ) (a v : Word w) (m : Memory w) :
+ after m (oneWrite n a v) = writeMemory m a v := by
+ induction n with
+ | zero => rfl
+ | succ n ih => exact ih
+
+private theorem oneWrite_work (n : ℕ) (a v : Word w) :
+ countProbes (oneWrite n a v) = 1 ∧ (oneWrite n a v).length = n+2 := by
+ induction n with
+ | zero => exact ⟨rfl,rfl⟩
+ | succ n ih =>
+ simp only [oneWrite, List.replicate_succ, List.cons_append, countProbes, List.length_cons]
+ exact ⟨ih.1, by change (oneWrite n a v).length+1 = _; omega⟩
+
+theorem role_native (p : Fin 2 → Word w) (m : Memory w) (i : Word w) :
+ let M := (template roleCode 0).instantiate w p
+ execute M.program 26 (M.program.start i) m [] = some
+ ⟨oneWrite 23 (p 1+i) (roleValue (p 0) i), some (i+1)⟩ := by
+ let M := (template roleCode 0).instantiate w p
+ change execute M.program (1+roleCode.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]; rfl
+
+open scoped Fin.CommRing in
+/-- The program implements the selected layout's outgoing and incoming roles
+on all eight entries of the finite role table. -/
+theorem roleValue_eq (layout : Bool) (t : Fin 4) (s : Fin 2) (hw : 8 ≤ 2^w) :
+ roleValue (wd (w := w) layout.toNat) (wd (2*t.val+s.val)) =
+ wd (roleOffset (endRole layout (decide (s=1)) t)) := by
+ have h2 : 2 < 2^w := by omega
+ have hs : s.val < 2 := s.isLt
+ have ht : t.val < 4 := t.isLt
+ have hfield : 2*t.val+s.val < 2^w := by omega
+ have hlt : t.val < 2^w := by omega
+ have modField : (2*t.val+s.val)%2 = s.val := by omega
+ have divField : (2*t.val+s.val)/2 = t.val := by omega
+ change choose (mod (wd _) (wd 2)) (choose (div (div (wd _) (wd 2)) (wd 2)) _
+ (choose (mod (div (wd _) (wd 2)) (wd 2)) _ _))
+ (choose (xor (mod (div (wd _) (wd 2)) (wd 2)) (div (div (wd _) (wd 2)) (wd 2))) _ _) = _
+ rw [div_wd hfield h2, mod_wd hfield h2, modField, divField, div_wd hlt h2, mod_wd hlt h2]
+ have hx : xor (wd (w := w) (t.val%2)) (wd (t.val/2)) = wd ((t.val%2) ^^^ (t.val/2)) := by
+ change Fin.ofNat _ ((wd (t.val%2) : Word w).val ^^^ (wd (t.val/2) : Word w).val) = _
+ rw [val_wd (by omega : t.val%2 < 2^w), val_wd (by omega : t.val/2 < 2^w)]
+ rw [hx]
+ fin_cases t <;> fin_cases s <;> cases layout <;>
+ simp [endRole, sourceRole, targetRole, roleOffset, choose, wd]
+
+/-- Public fields give lane count, tag count and cyclic successor table start. -/
+def nextCode : List (Op 9 3) :=
+ [.stateWord 0, .constant 1 1, .publicWord 2 0, .publicWord 3 1,
+ .binary .mod 4 0 2, .binary .div 5 0 2, .binary .mod 6 5 3, .binary .div 7 5 3,
+ .binary .add 6 6 1, .binary .mod 6 6 3, .binary .mul 7 7 3, .binary .add 7 7 6,
+ .binary .mul 7 7 2, .binary .add 7 7 4, .publicWord 8 2, .binary .add 8 8 0,
+ .write 8 7, .binary .add 0 0 1]
+
+/-- Compute a packed site's cyclic successor by advancing its tag modulo the tag count at the
+same base vertex and residual lane. -/
+def nextValue (p : Fin 3 → Word w) (i : Word w) : Word w :=
+ let base := div i (p 0)
+ (div base (p 1)*p 1 + mod (mod base (p 1)+1) (p 1))*p 0 + mod i (p 0)
+
+theorem next_native (p : Fin 3 → Word w) (m : Memory w) (i : Word w) :
+ let M := (template nextCode 0).instantiate w p
+ execute M.program 19 (M.program.start i) m [] = some
+ ⟨oneWrite 16 (p 2+i) (nextValue p i), some (i+1)⟩ := by
+ let M := (template nextCode 0).instantiate w p
+ change execute M.program (1+nextCode.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]; rfl
+
+variable {V Tag L : Type*} {N J nL : ℕ}
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- Numeric cycle with the same original vertex and lane even when the tag wraps. -/
+theorem nextValue_eq (p : Fin 3 → Word w) (b : Fin (N*(J*nL)))
+ (hl : (p 0).val = nL) (ht : (p 1).val = J) (fit : N*(J*nL) ≤ 2^w) :
+ let site := siteIndex vertices tags lanes
+ nextValue p (wd b.val) = wd (site (dummyEnd tags true (site.symm b))).val := by
+ intro site
+ obtain ⟨⟨v,t,l⟩,rfl⟩ := site.surjective b
+ let vertex := (vertices v).val
+ let tag := (tags t).val
+ let lane := (lanes l).val
+ have hi : (site (v,t,l)).val = (vertex*J+tag)*nL+lane := by
+ change lane+nL*tag+(J*nL)*vertex = _; ring
+ have htag : tag < J := (tags t).isLt
+ have hlane : lane < nL := (lanes l).isLt
+ have hcap := (site (v,t,l)).isLt.trans_le fit
+ have hlw : nL < 2^w := hl ▸ (p 0).isLt
+ have htw : J < 2^w := ht ▸ (p 1).isLt
+ have hp0 : p 0 = wd nL := hl ▸ (wd_val (p 0)).symm
+ have hp1 : p 1 = wd J := ht ▸ (wd_val (p 1)).symm
+ have lower (b m u : ℕ) (hu : u < m) : (b*m+u)/m = b := by
+ rw [Nat.mul_comm b m, Nat.mul_add_div (by omega), Nat.div_eq_of_lt hu, Nat.add_zero]
+ have hb : vertex*J+tag < 2^w := by
+ have := (Nat.div_le_self (site (v,t,l)).val nL).trans_lt hcap
+ rwa [hi, lower _ _ _ hlane] at this
+ rw [Equiv.symm_apply_apply]
+ change nextValue p (wd (site (v,t,l)).val) = wd (site (v,tags.symm (finRotate J (tags t)),l)).val
+ have he : (site (v,tags.symm (finRotate J (tags t)),l)).val =
+ (vertex*J+(finRotate J (tags t)).val)*nL+lane := by
+ change lane+nL*(tags (tags.symm _)).val+(J*nL)*vertex = _
+ rw [tags.apply_symm_apply]; ring
+ let := (tags t).neZero
+ rw [he, finRotate_apply, Fin.val_add, Fin.val_one', Nat.add_mod_mod]
+ simp only [nextValue, hp0, hp1, hi]
+ rw [div_wd (hi ▸ hcap) hlw, mod_wd (hi ▸ hcap) hlw, lower _ _ _ hlane, Nat.mul_add_mod_of_lt hlane,
+ div_wd hb htw, mod_wd hb htw, lower _ _ _ htag, Nat.mul_add_mod_of_lt htag]
+ change (wd vertex * wd J + mod (wd tag + wd 1) (wd J))*wd nL+wd lane = _
+ rw [add_wd, mod_wd (by omega : tag+1 < 2^w) htw, mul_wd, add_wd, mul_wd, add_wd]
+
+private theorem direct_run {C : Type*} (P : Program w C) (fuel n count : ℕ) (base : Word w)
+ (value : Word w → Word w) (initial : Memory w) (fit : base.val+count ≤ 2^w)
+ (visit : ∀ (m : Memory w) (i : Word w), execute P fuel (P.start i) m [] =
+ some ⟨oneWrite n (base+i) (value i), some (i+1)⟩) :
+ ∃ rs, FilledRun P fuel 1 (n+2) count base (fun i => value (wd i)) initial rs := by
+ apply filled_run _ _ _ _ _ _ _ _ fit
+ intro i _ _ m _
+ have hnext : wd (w := w) i + 1 = wd (i+1) := add_wd i 1
+ have hadd : base + wd i = wd (base.val+i) := by
+ simpa only [wd_val] using add_wd (w := w) base.val i
+ exact ⟨_, (visit m (wd i)).trans (by rw [hnext]), (oneWrite_after ..).trans (by rw [hadd]),
+ (oneWrite_work ..).1, (oneWrite_work ..).2⟩
+
+/-- Fill the finite role table. Its final cells are the role offsets needed
+by the selected layout, with the outgoing cell first in each pair. -/
+theorem roles_run (layout : Bool) (p : Fin 2 → Word w) (initial : Memory w)
+ (hl : p 0 = wd layout.toNat) (fit : (p 1).val+8 ≤ 2^w) :
+ let P := ((template roleCode 0).instantiate w p).program
+ ∃ rs, FilledRun P 26 1 25 8 (p 1) (fun i => roleValue (p 0) (wd i)) initial rs ∧
+ ∀ (t : Fin 4) (s : Fin 2), (after initial (eventLog rs) ((p 1).val+(2*t.val+s.val))).val =
+ roleOffset (endRole layout (decide (s=1)) t) := by
+ intro P
+ obtain ⟨rs,hr⟩ := direct_run P 26 23 8 (p 1) (roleValue (p 0)) initial fit (role_native p)
+ refine ⟨rs,hr,fun t s => ?_⟩
+ have hi : 2*t.val+s.val < 8 := by have := t.isLt; have := s.isLt; omega
+ rw [hr.filled _ hi, hl, roleValue_eq _ _ _ (by omega), val_wd (by have := role_lt' (endRole layout (decide (s=1)) t); omega)]
+where
+ role_lt' (r : PackedRole) : roleOffset r < 3 := by cases r <;> decide
+
+/-- Build the entire cyclic successor table directly from the two radices.
+The result satisfies the input predicate used by the native dummy worker. -/
+theorem next_run (p q : Fin 3 → Word w) (initial : Memory w)
+ (hl : (p 0).val = nL) (ht : (p 1).val = J) (pad : ℕ) (hp : (q 0).val = pad)
+ (start : q 1 = p 2) (hw : 2 < 2^w) (fit : (p 2).val+N*(J*nL) ≤ 2^w) :
+ let P := ((template nextCode 0).instantiate w p).program
+ ∃ rs, FilledRun P 19 1 18 (N*(J*nL)) (p 2) (fun i => nextValue p (wd i)) initial rs ∧
+ DummyTables vertices tags lanes pad q (after initial (eventLog rs)) := by
+ intro P
+ obtain ⟨rs,hr⟩ := direct_run P 19 16 _ (p 2) (nextValue p) initial fit (next_native p)
+ refine ⟨rs,hr,hw,hp,start ▸ fit,fun b => ?_⟩
+ rw [start, hr.filled _ b.isLt, nextValue_eq vertices tags lanes p b hl ht (by omega)]
+ exact val_wd ((siteIndex vertices tags lanes _).isLt.trans_le (by omega))
+
+end CompressorRecords.SlotOwners.Aux
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOwnerDecode.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerDecode.lean
new file mode 100644
index 0000000000..c19ccdea01
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerDecode.lean
@@ -0,0 +1,294 @@
+import OAI.Computability.VPVNP.CompressorSlotNetwork
+
+/-!
+# Numeric decoding of shrinking endpoint owners
+
+The old CD arc, role-edge type, subdivision and absolute lane are recovered
+by quotient and remainder before any endpoint lookup. This identifies which
+entries of the two rectangular owner tables are real and which are holes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.Slots
+
+open Compression Compression.PackingData Compression.SurvivingSlots
+
+variable {V H Tag L : Type*} {d c N J nL pad : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- Cardinality of the old outgoing arc space with the remaining lane suppressed. -/
+abbrev oldBaseArcCount (N J d c : ℕ) := N * (J * (d * (2 ^ c * d)))
+
+private def digitPair {A B : Type*} {a b : ℕ} (f : A ≃ Fin a) (g : B ≃ Fin b) : A × B ≃ Fin (a*b) :=
+ (f.prodCongr g).trans finProdFinEquiv
+
+/-- Dense old arc index with the original absolute lane as the least significant digit. -/
+def oldArcIndex : Arc V H Tag L d c ≃ Fin (oldBaseArcCount N J d c * nL) :=
+ let reorder : Arc V H Tag L d c ≃ (V × Tag × Fin d × BitWord c × H) × L :=
+ ⟨fun a ↦ ((a.1.1.1, a.1.1.2.1, a.1.2, a.2), a.1.1.2.2),
+ fun ⟨⟨v, t, k, w, h⟩, g⟩ ↦ (((v,t,g),k),w,h), fun _ ↦ rfl, fun _ ↦ rfl⟩
+ reorder.trans (digitPair (digitPair vertices (digitPair tags (digitPair (Equiv.refl (Fin d))
+ (digitPair (bitWordFinEquiv c) P.slotLabel)))) lanes)
+
+/-- Mixed-radix coordinates of a genuine candidate arc, consisting of edge type, old base arc,
+subdivision, and absolute lane. -/
+abbrev GenuineDigits (N J nL d c : ℕ) (subdiv : Fin 4 → ℕ) :=
+ ((Fin 4 × Fin (oldBaseArcCount N J d c)) × Fin (∑ t, subdiv t)) × Fin nL
+
+private def genuineIndex : GenuineDigits N J nL d c subdiv ≃ Fin (keyCount N J d c subdiv * nL) :=
+ (digitPair (digitPair finProdFinEquiv (Equiv.refl (Fin (∑ t, subdiv t)))) (Equiv.refl (Fin nL))).trans
+ (finCongr (by unfold keyCount oldBaseArcCount; ac_rfl))
+
+/-- In order, the role-edge type, old base arc number, subdivision and absolute lane. -/
+def genuineDigits (a : Fin (keyCount N J d c subdiv * nL)) : GenuineDigits N J nL d c subdiv :=
+ (genuineIndex subdiv).symm a
+
+theorem genuineDigits_val (a : Fin (keyCount N J d c subdiv * nL)) :
+ let x := genuineDigits subdiv a
+ let key := a.val / nL
+ x.1.1.1.val = key / (∑ t, subdiv t) / oldBaseArcCount N J d c ∧
+ x.1.1.2.val = key / (∑ t, subdiv t) % oldBaseArcCount N J d c ∧
+ x.1.2.val = key % (∑ t, subdiv t) ∧ x.2.val = a.val % nL := ⟨rfl, rfl, rfl, rfl⟩
+
+/-- Look up the original absolute old arc at the two decoded digits. -/
+def digitArc (x : GenuineDigits N J nL d c subdiv) : Arc V H Tag L d c :=
+ (oldArcIndex P vertices tags lanes).symm (finProdFinEquiv (x.1.1.2, x.2))
+
+omit [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] in
+theorem digitArc_index (x : GenuineDigits N J nL d c subdiv) :
+ (oldArcIndex P vertices tags lanes (digitArc P subdiv vertices tags lanes x)).val =
+ x.1.1.2.val * nL + x.2.val := by
+ rw [digitArc, Equiv.apply_symm_apply]
+ change x.2.val + nL * x.1.1.2.val = _
+ ring
+
+/-- CD validity test on an original directed arc, independent of subdivision and type. -/
+abbrev isCD (a : Arc V H Tag L d c) :=
+ ¬ (P.thick (sourcePosition a) ∧ P.thick (sourcePosition (P.actual a)))
+
+private def encodeIdDigits (i : Id P.Motif subdiv) : GenuineDigits N J nL d c subdiv :=
+ let p := finProdFinEquiv.symm (oldArcIndex P vertices tags lanes i.2.1.1)
+ let bound := Finset.single_le_sum (fun t _ ↦ Nat.zero_le (subdiv t)) (Finset.mem_univ i.1)
+ (((i.1, p.1), i.2.2.castLE bound), p.2)
+
+private theorem encode_address (i : Id P.Motif subdiv) :
+ arcAddress P subdiv vertices tags lanes pad (.inl i) =
+ (genuineIndex subdiv (encodeIdDigits P subdiv vertices tags lanes i)).castAdd _ := by
+ let f := digitPair vertices (digitPair tags (digitPair (Equiv.refl (Fin d))
+ (digitPair (bitWordFinEquiv c) P.slotLabel)))
+ let a := i.2.1.val
+ let b := f (a.1.1.1, a.1.1.2.1, a.1.2, a.2)
+ let l := lanes a.1.1.2.2
+ have hp : finProdFinEquiv.symm (oldArcIndex P vertices tags lanes a) = (b,l) :=
+ finProdFinEquiv.symm_apply_apply (b,l)
+ change finProdFinEquiv.symm (oldArcIndex P vertices tags lanes i.2.1.val) = (b,l) at hp
+ apply Fin.ext
+ simp only [encodeIdDigits]
+ rw [hp]
+ change l.val + nL * (i.2.2.val + (∑ t, subdiv t) * b.val +
+ (oldBaseArcCount N J d c * (∑ t, subdiv t)) * i.1.val) =
+ l.val + nL * (i.2.2.val + (∑ t, subdiv t) * (b.val + oldBaseArcCount N J d c * i.1.val))
+ ring
+
+private def digitId (x : GenuineDigits N J nL d c subdiv) : Option (Id P.Motif subdiv) :=
+ let a := digitArc P subdiv vertices tags lanes x
+ if hj : x.1.2.val < subdiv x.1.1.1 then
+ if hm : isCD P a then some ⟨x.1.1.1, ⟨a,hm⟩, ⟨x.1.2.val,hj⟩⟩ else none
+ else none
+
+private theorem digitId_encode (i : Id P.Motif subdiv) :
+ digitId P subdiv vertices tags lanes (encodeIdDigits P subdiv vertices tags lanes i) = some i := by
+ have ha : digitArc P subdiv vertices tags lanes (encodeIdDigits P subdiv vertices tags lanes i) = i.2.1.1 := by
+ change (oldArcIndex P vertices tags lanes).symm (finProdFinEquiv (finProdFinEquiv.symm _)) = _
+ rw [Equiv.apply_symm_apply, Equiv.symm_apply_apply]
+ dsimp only [digitId]
+ rw [ha]
+ change (if hj : i.2.2.val < subdiv i.1 then if hm : isCD P i.2.1.1 then
+ some ⟨i.1, ⟨i.2.1.1,hm⟩, ⟨i.2.2.val,hj⟩⟩ else none else none) = some i
+ rw [dite_eq_left i.2.2.isLt, dite_eq_left i.2.1.prop]
+
+private theorem encode_digitId (x : GenuineDigits N J nL d c subdiv) (i : Id P.Motif subdiv)
+ (hi : digitId P subdiv vertices tags lanes x = some i) :
+ encodeIdDigits P subdiv vertices tags lanes i = x := by
+ dsimp only [digitId] at hi
+ split at hi <;> try contradiction
+ split at hi <;> try contradiction
+ obtain rfl := Option.some.inj hi
+ simp only [encodeIdDigits, digitArc, Equiv.apply_symm_apply, Equiv.symm_apply_apply]
+ rfl
+
+/-- Quotient/remainder decoding of a genuine-region candidate, including the
+two reasons for an unoccupied address. -/
+theorem decodeArc_genuine (a : Fin (keyCount N J d c subdiv * nL)) :
+ let x := genuineDigits subdiv a
+ let old := digitArc P subdiv vertices tags lanes x
+ decodeArc P subdiv vertices tags lanes pad (a.castAdd _) =
+ if hj : x.1.2.val < subdiv x.1.1.1 then
+ if hm : isCD P old then some (.inl ⟨x.1.1.1, ⟨old,hm⟩, ⟨x.1.2.val,hj⟩⟩) else none
+ else none := by
+ intro x old
+ have eqn : decodeArc P subdiv vertices tags lanes pad (a.castAdd _) =
+ (digitId P subdiv vertices tags lanes x).map Sum.inl := by
+ apply Option.ext
+ intro i
+ rw [decodeArc_eq_some, Option.map_eq_some_iff]
+ rcases i with i | p
+ · simp only [Sum.inl.injEq, exists_eq_right]
+ rw [encode_address, Fin.ext_iff]
+ change (genuineIndex subdiv (encodeIdDigits P subdiv vertices tags lanes i)).val = a.val ↔ _
+ rw [← Fin.ext_iff, ← Equiv.eq_symm_apply]
+ change encodeIdDigits P subdiv vertices tags lanes i = x ↔ _
+ exact ⟨fun h ↦ h ▸ digitId_encode P subdiv vertices tags lanes i,
+ fun h ↦ encode_digitId P subdiv vertices tags lanes x i h⟩
+ · simp only [Sum.inl_ne_inr, and_false, exists_false, iff_false]
+ intro h
+ have hn := congrArg Fin.val h
+ change keyCount N J d c subdiv * nL + _ = a.val at hn
+ have := a.isLt
+ omega
+ rw [eqn]
+ dsimp only [digitId]
+ rw [show digitArc P subdiv vertices tags lanes x = old from rfl]
+ by_cases hj : x.1.2.val < subdiv x.1.1.1
+ · rw [dite_eq_left hj, dite_eq_left hj]
+ by_cases hm : isCD P old
+ · rw [dite_eq_left hm, dite_eq_left hm]; rfl
+ · rw [dite_eq_right hm, dite_eq_right hm]; rfl
+ · rw [dite_eq_right hj, dite_eq_right hj]; rfl
+
+/-- Exactly the proper subdivisions of CD arcs have genuine endpoint owners. -/
+theorem decodeArc_genuine_isSome (a : Fin (keyCount N J d c subdiv * nL)) :
+ let x := genuineDigits subdiv a
+ (decodeArc P subdiv vertices tags lanes pad (a.castAdd _)).isSome ↔
+ x.1.2.val < subdiv x.1.1.1 ∧ isCD P (digitArc P subdiv vertices tags lanes x) := by
+ intro x
+ rw [decodeArc_genuine]
+ rw [show genuineDigits subdiv a = x from rfl]
+ by_cases hj : x.1.2.val < subdiv x.1.1.1
+ · rw [dite_eq_left hj, and_iff_right hj]
+ by_cases hm : isCD P (digitArc P subdiv vertices tags lanes x)
+ · rw [dite_eq_left hm]; simpa using hm
+ · rw [dite_eq_right hm]; simpa using hm
+ · rw [dite_eq_right hj]
+ exact iff_of_false Bool.false_ne_true (fun h ↦ hj h.1)
+
+/-- Select the endpoint owner directly from the role-edge type and its old CD arc. -/
+theorem decodeArc_genuine_end (a : Fin (keyCount N J d c subdiv * nL)) (layout side : Bool) :
+ let x := genuineDigits subdiv a
+ let old := digitArc P subdiv vertices tags lanes x
+ (decodeArc P subdiv vertices tags lanes pad (a.castAdd _)).map (actualEnd P subdiv tags layout side) =
+ if x.1.2.val < subdiv x.1.1.1 then
+ if hm : isCD P old then some (P.survivingRole layout (endRole layout side x.1.1.1) ⟨old,hm⟩) else none
+ else none := by
+ intro x old
+ rw [decodeArc_genuine]
+ rw [show genuineDigits subdiv a = x from rfl, show digitArc P subdiv vertices tags lanes x = old from rfl]
+ by_cases hj : x.1.2.val < subdiv x.1.1.1
+ · rw [dite_eq_left hj, ite_eq_left hj]
+ by_cases hm : isCD P old
+ · rw [dite_eq_left hm, dite_eq_left hm]; rfl
+ · rw [dite_eq_right hm, dite_eq_right hm]; rfl
+ · rw [dite_eq_right hj, ite_eq_right hj]; rfl
+
+/-- Read the source site and the local dummy number from the address offset
+past the genuine interval. The site number is the quotient by the padding
+degree and the dummy number is the remainder. -/
+def dummySourceSite (a : Fin ((N * (J * nL)) * pad)) : Site V Tag L :=
+ (SlotSchedule.siteIndex vertices tags lanes).symm a.divNat
+
+theorem decodeArc_dummy (a : Fin ((N * (J * nL)) * pad)) :
+ decodeArc P subdiv vertices tags lanes pad (a.natAdd (keyCount N J d c subdiv * nL)) =
+ some (.inr (dummySourceSite vertices tags lanes a, a.modNat)) := by
+ rw [decodeArc_eq_some]
+ let site := SlotSchedule.siteIndex vertices tags lanes
+ change finSumFinEquiv (.inr (finProdFinEquiv (site (site.symm a.divNat), a.modNat))) = _
+ rw [site.apply_symm_apply, ← show finProdFinEquiv.symm a = (a.divNat,a.modNat) from rfl,
+ finProdFinEquiv.apply_symm_apply, finSumFinEquiv_apply_right]
+
+/-- In the dummy interval, the selected endpoint keeps the lane and applies
+the tag cycle exactly for an incoming field. -/
+theorem decodeArc_dummy_end (a : Fin ((N * (J * nL)) * pad)) (layout side : Bool) :
+ (decodeArc P subdiv vertices tags lanes pad (a.natAdd (keyCount N J d c subdiv * nL))).map
+ (actualEnd P subdiv tags layout side) = some (dummyEnd tags side (dummySourceSite vertices tags lanes a)) := by
+ rw [decodeArc_dummy]; rfl
+
+/-- The local dummy address for any member of the trailing interval. -/
+def dummyOffset (a : Fin (RecordCount N J nL d c pad subdiv)) (h : keyCount N J d c subdiv * nL ≤ a.val) :
+ Fin ((N * (J * nL)) * pad) :=
+ ⟨a.val - keyCount N J d c subdiv * nL, by have := a.isLt; unfold RecordCount at this; omega⟩
+
+theorem dummyOffset_natAdd (a : Fin (RecordCount N J nL d c pad subdiv)) (h : keyCount N J d c subdiv * nL ≤ a.val) :
+ (dummyOffset subdiv a h).natAdd (keyCount N J d c subdiv * nL) = a := by
+ apply Fin.ext
+ change keyCount N J d c subdiv * nL + (a.val - keyCount N J d c subdiv * nL) = a.val
+ omega
+
+open SlotSchedule
+
+/-- The field's two least-significant operations split off its orientation bit. -/
+theorem endpoint_field_digits {n : ℕ} (a : Fin n) (s : Fin 2) :
+ (finProdFinEquiv (a,s)).val / 2 = a.val ∧ (finProdFinEquiv (a,s)).val % 2 = s.val :=
+ ⟨congrArg (fun z : Fin n × Fin 2 ↦ z.1.val) (finProdFinEquiv.symm_apply_apply (a,s)),
+ congrArg (fun z : Fin n × Fin 2 ↦ z.2.val) (finProdFinEquiv.symm_apply_apply (a,s))⟩
+
+/-- Numerical directory destination on the entire genuine-field interval.
+Invalid addresses occupy distinct rows past all real endpoint owners. -/
+theorem directory_genuine_destination (layout : Bool) (a : Fin (keyCount N J d c subdiv * nL)) (s : Fin 2) :
+ let field := finProdFinEquiv (a.castAdd ((N * (J * nL)) * pad), s)
+ let x := genuineDigits subdiv a
+ let old := digitArc P subdiv vertices tags lanes x
+ let hole := (N * (J * nL)) * 2 + field.val
+ ((slotDirectory P subdiv vertices tags lanes layout).destination field).val =
+ if x.1.2.val < subdiv x.1.1.1 then
+ if hm : isCD P old then 2 * (siteIndex vertices tags lanes
+ (P.survivingRole layout (endRole layout (decide (s=1)) x.1.1.1) ⟨old,hm⟩)).val + s.val
+ else hole
+ else hole := by
+ intro field x old hole
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad)
+ have hd : D.decode field = (decodeArc P subdiv vertices tags lanes pad (a.castAdd _)).map (fun i ↦ (i,s)) := by
+ simp only [D, field, slotDirectory, Equiv.symm_apply_apply]
+ change (D.destination field).val = _
+ rw [Directory.destination, hd, decodeArc_genuine]
+ rw [show genuineDigits subdiv a = x from rfl, show digitArc P subdiv vertices tags lanes x = old from rfl]
+ by_cases hj : x.1.2.val < subdiv x.1.1.1
+ · rw [dite_eq_left hj, ite_eq_left hj]
+ by_cases hm : isCD P old
+ · rw [dite_eq_left hm, dite_eq_left hm]
+ change s.val + 2 * _ = 2 * _ + s.val
+ exact Nat.add_comm _ _
+ · rw [dite_eq_right hm, dite_eq_right hm]; rfl
+ · rw [dite_eq_right hj, ite_eq_right hj]; rfl
+
+/-- Numerical destination of a dummy field in the second scan. The dummy
+source index is the local field divided by two and then by the padding degree. -/
+theorem directory_dummy_destination (layout : Bool) (a : Fin ((N * (J * nL)) * pad)) (s : Fin 2) :
+ let field := finProdFinEquiv (a.natAdd (keyCount N J d c subdiv * nL), s)
+ let localField := finProdFinEquiv (a,s)
+ let site := siteIndex vertices tags lanes
+ ((slotDirectory P subdiv vertices tags lanes layout).destination field).val =
+ 2 * (if s.val = 0 then localField.val / 2 / pad
+ else (site (dummyEnd tags true (site.symm a.divNat))).val) + s.val := by
+ intro field localField site
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad)
+ have hd : D.decode field = (decodeArc P subdiv vertices tags lanes pad (a.natAdd _)).map (fun i ↦ (i,s)) := by
+ simp only [D, field, slotDirectory, Equiv.symm_apply_apply]
+ change (D.destination field).val = _
+ rw [Directory.destination, hd, decodeArc_dummy]
+ change s.val + 2 * (site (dummyEnd tags (decide (s = 1)) (site.symm a.divNat))).val = _
+ rw [Nat.add_comm s.val, (endpoint_field_digits a s).1]
+ fin_cases s
+ · change 2 * (site (site.symm a.divNat)).val + 0 = 2 * a.divNat.val + 0
+ rw [site.apply_symm_apply]
+ · rfl
+
+end CompressorRecords.Slots
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOwnerDirectory.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerDirectory.lean
new file mode 100644
index 0000000000..b636867b1b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerDirectory.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.CompressorSlotOwnerAgreement
+import OAI.Computability.VPVNP.CompressorSlotOwnerRuns
+
+/-!
+# Physical input bounds for the shrinking slot directory
+
+The mixed-radix scan reads only the three descriptor arrays and the cyclic
+successor array. Their lengths follow from the packed graph parameters. Placing
+them below a common scratch base gives the source bounds for both owner passes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotOwners
+
+open Compression Compression.PackingData Compression.SurvivingSlots Slots BurstRAM
+
+variable {V H Tag L : Type*} {d c N J nL pad w : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- The role, old arc and subdivision arrays end below the scratch base.
+Every decoded read is therefore stable throughout the two owner scans. -/
+theorem genuineInputs_before {layout : Bool} {g : Fin 8 → Word w} {mem : Memory w}
+ (tables : GenuineTables P subdiv vertices tags lanes layout g mem) (base : Word w)
+ (oldEnd : (g 3).val + 4*(oldBaseArcCount N J d c*nL) ≤ base.val)
+ (roleEnd : (g 4).val+8 ≤ base.val) (subdivEnd : (g 5).val+4 ≤ base.val) :
+ ∀ i < (keyCount N J d c subdiv*nL)*2, ∀ a ∈ genuineInputs g mem (Fin.ofNat _ i),
+ a.val < base.val := by
+ intro i hi
+ have roles (j : ℕ) (hj : j < 8) : (mem ((g 4).val+j)).val < 3 := by
+ let t : Fin 4 := ⟨j/2, by omega⟩
+ let s : Fin 2 := ⟨j%2, by omega⟩
+ have idx : 2*t.val+s.val = j := by dsimp only [t,s]; omega
+ have h := tables.role t s
+ rw [idx] at h
+ rw [h]
+ cases endRole layout (decide (s=1)) t <;> decide
+ apply genuine_inputs_before g mem (Fin.ofNat _ i) base _ roleEnd subdivEnd roles
+ · rw [tables.baseCount, tables.subdivCount, tables.laneCount]
+ apply (Nat.mod_le i (2^w)).trans_lt
+ simpa only [keyCount, oldBaseArcCount, Nat.mul_assoc] using hi
+ · simpa only [tables.baseCount, tables.laneCount] using oldEnd
+
+omit [AddCommGroup Tag] [AddCommGroup L] in
+/-- Both sides of every dummy field read below the scratch base when the
+packed-site successor array ends there. -/
+theorem dummyInput_before {p : Fin 3 → Word w} {mem : Memory w}
+ (tables : DummyTables vertices tags lanes pad p mem) (base : Word w)
+ (nextEnd : (p 1).val + N*(J*nL) ≤ base.val) :
+ ∀ i < ((N*(J*nL))*pad)*2, (p 1+dummySource p (Fin.ofNat _ i)).val < base.val := by
+ intro i hi
+ apply dummy_input_before p (Fin.ofNat _ i) base (N*(J*nL)) nextEnd tables.twoFits
+ rw [tables.padCount]
+ exact (Nat.mod_le i (2^w)).trans_lt hi
+
+end CompressorRecords.SlotOwners
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOwnerFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerFootprint.lean
new file mode 100644
index 0000000000..45a0b89c77
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerFootprint.lean
@@ -0,0 +1,187 @@
+import OAI.Computability.VPVNP.CompressorSlotLevelRun
+import OAI.Computability.VPVNP.CompressorRecordsOrdinalFootprint
+import OAI.Computability.VPVNP.RAMChoicePrefix
+
+/-!
+# External addresses touched by the endpoint-owner scans
+
+The genuine scan reads from the old arc, selected role and subdivision
+tables, then writes the genuine prefix of the owner stream. The dummy scan
+reads the cyclic successor table and writes the trailing dummy fields. The
+bounds apply to the emitted probes of every call in the two native segments.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotOwnerFootprint
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport SlotLevel Slots
+open Compression Compression.PackingData
+
+variable {w : ℕ}
+
+/-- A half-open external array of the given length. -/
+def interval (base count addr : ℕ) : Prop := base ≤ addr ∧ addr < base+count
+
+/-- Size in words of the old arc record table, with three role sites and a CD flag per absolute
+old arc. -/
+def oldWords (s : Shape) := 4*(oldBaseArcCount s.bases s.tags s.oldDegree s.colors*s.lanes)
+
+/-- Addresses in the old arc, role, or subdivision tables that the genuine owner scan may read. -/
+def genuineRead (s : Shape) (h : Heads) (addr : ℕ) : Prop :=
+ interval h.oldArc (oldWords s) addr ∨ interval h.role 8 addr ∨ interval h.subdivisions 4 addr
+
+/-- The cyclic successor table range read by the dummy endpoint owner scan. -/
+def dummyRead (s : Shape) (h : Heads) := interval h.nextSite (sites s)
+
+/-- The leading scratch interval that receives owner words for genuine candidate fields. -/
+def genuineWrite (s : Shape) (h : Heads) := interval h.scratch (genuineCount s)
+
+/-- The trailing owner interval, immediately after the genuine fields, that receives owner
+words for dummy fields. -/
+def dummyWrite (s : Shape) (h : Heads) := interval (h.scratch+genuineCount s) (dummyCount s)
+
+private theorem genuine_event_addresses (g : Fin 8 → Word w) (m : Memory w) (i : Word w) :
+ (∀ a v, Event.read a v ∈ SlotOwners.genuineEvents g m i → a ∈ SlotOwners.genuineInputs g m i) ∧
+ (∀ a v, Event.write a v ∈ SlotOwners.genuineEvents g m i → a = g 7+i) := by
+ constructor
+ · intro a v hv
+ simp [SlotOwners.genuineEvents] at hv
+ simp only [SlotOwners.genuineInputs, List.mem_cons]
+ rcases hv with h | h | h | h <;> tauto
+ · intro a v hv
+ simp [SlotOwners.genuineEvents] at hv
+ exact hv.1
+
+private theorem dummy_event_addresses (p : Fin 3 → Word w) (m : Memory w) (i : Word w) :
+ (∀ a v, Event.read a v ∈ SlotOwners.dummyEvents p m i → a = p 1+SlotOwners.dummySource p i) ∧
+ (∀ a v, Event.write a v ∈ SlotOwners.dummyEvents p m i → a = p 2+i) := by
+ constructor <;> intro a v hv <;> simp [SlotOwners.dummyEvents] at hv <;> exact hv.1
+
+private theorem word_inc (i : ℕ) :
+ Fin.ofNat (2^w) i + 1 = Fin.ofNat _ (i+1) := by
+ apply Fin.ext
+ simp [Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod]
+
+private theorem owner_end (s : Shape) (h : Heads) : h.scratch+fields s ≤ stopAddress s h := by
+ dsimp [stopAddress, shiftsHead, targetsHead, inverseHead, rowsHead]; omega
+
+/-- For the exact native genuine run, every emitted read and write lies in its
+declared physical array. Its eight role offsets remain bounded across the scan. -/
+theorem genuine (s : Shape) (h : Heads) (initial : Memory w) (rs : List (Report w))
+ (arcEnd : h.oldArc+oldWords s ≤ h.scratch) (roleEnd : h.role+8 ≤ h.scratch)
+ (subEnd : h.subdivisions+4 ≤ h.scratch) (fit : stopAddress s h < 2^w) :
+ let g := bank s h w .genuineOwners
+ let P := ((template SlotOwners.genuine 0).instantiate w g).program
+ (g 0).val = s.lanes → (g 1).val = ∑ t, s.subdivisions t →
+ (g 2).val = oldBaseArcCount s.bases s.tags s.oldDegree s.colors →
+ (∀ j < 8, (initial (h.role+j)).val < 3) →
+ runSegment P 49 (some 0) initial (List.replicate (genuineCount s) []) = some rs →
+ Reads (genuineRead s h) (eventLog rs) ∧ Writes (genuineWrite s h) (eventLog rs) := by
+ intro g P lanes sub bases roles run
+ have room := (owner_end s h).trans_lt fit
+ have both := counts_add s
+ have g3 : (g 3).val = h.oldArc := Nat.mod_eq_of_lt (by omega : h.oldArc < 2^w)
+ have g4 : (g 4).val = h.role := Nat.mod_eq_of_lt (by omega : h.role < 2^w)
+ have g5 : (g 5).val = h.subdivisions := Nat.mod_eq_of_lt (by omega : h.subdivisions < 2^w)
+ have g7 : (g 7).val = h.scratch := Nat.mod_eq_of_lt (by omega : h.scratch < 2^w)
+ let cursor (j : ℕ) := Fin.ofNat (2^w) j
+ let inv (_ : ℕ) (m : Memory w) := ∀ j < 8, (m (h.role+j)).val < 3
+ apply OrdinalRun.footprint P 49 cursor (genuineCount s) inv _ _ _ 0 _ initial rs (by simp) roles run
+ intro j hj m hm bits rep hex
+ have eq := (execute_prefix_unique (SlotOwners.genuine_native g m (cursor j))
+ (show execute P 49 (P.start (cursor j)) m ([]++bits) = some rep from hex)).2
+ subst rep
+ have hc : (cursor j).val = j := Nat.mod_eq_of_lt (by omega)
+ have hi : (cursor j).val < 4*(g 2).val*(g 1).val*(g 0).val*2 := by
+ rw [hc, bases, sub, lanes]
+ simpa only [genuineCount, keyCount, oldBaseArcCount, Nat.mul_assoc] using hj
+ have within := SlotOwners.genuine_inputs_ranges g m (cursor j)
+ (by rw [g3,bases,lanes]; change h.oldArc+oldWords s ≤ _; omega)
+ (by rw [g4]; omega) (by rw [g5]; omega) (by simpa only [g4] using hm) hi
+ have ha : (g 7+cursor j).val = h.scratch+j := by
+ rw [Fin.val_add,g7,hc,Nat.mod_eq_of_lt (by omega)]
+ obtain ⟨rd,wr⟩ := genuine_event_addresses g m (cursor j)
+ have writes : Writes (genuineWrite s h) (SlotOwners.genuineEvents g m (cursor j)) := by
+ intro a v hv
+ change h.scratch ≤ a.val ∧ a.val < h.scratch+genuineCount s
+ rw [wr a v hv,ha]; omega
+ refine ⟨congrArg some (word_inc j), ?_, ?_, writes⟩
+ · intro k hk
+ rw [after_outside m writes (by change ¬ (h.scratch ≤ h.role+k ∧ _); omega)]
+ exact hm k hk
+ · intro a v hv
+ simpa only [g3,g4,g5,bases,lanes,genuineRead,interval,oldWords] using within a (rd a v hv)
+
+/-- Every dummy call reads its source site's cyclic successor, even when
+the selected side is the outgoing end. Its write lies in the dummy suffix. -/
+theorem dummy (s : Shape) (h : Heads) (initial : Memory w) (rs : List (Report w))
+ (nextEnd : h.nextSite+sites s ≤ h.scratch) (fit : stopAddress s h < 2^w)
+ (hw : 2 < 2^w) :
+ let p := bank s h w .dummyOwners
+ let P := ((template SlotOwners.dummy 0).instantiate w p).program
+ (p 0).val = pad s →
+ runSegment P 20 (some 0) initial (List.replicate (dummyCount s) []) = some rs →
+ Reads (dummyRead s h) (eventLog rs) ∧ Writes (dummyWrite s h) (eventLog rs) := by
+ intro p P padding run
+ have room := (owner_end s h).trans_lt fit
+ have both := counts_add s
+ have p1 : (p 1).val = h.nextSite := Nat.mod_eq_of_lt (by omega : h.nextSite < 2^w)
+ have p2 : (p 2).val = h.scratch+genuineCount s :=
+ Nat.mod_eq_of_lt (by omega : h.scratch+genuineCount s < 2^w)
+ let cursor (j : ℕ) := Fin.ofNat (2^w) j
+ apply OrdinalRun.footprint P 20 cursor (dummyCount s) (fun _ _ => True) _ _ _ 0 _
+ initial rs (by simp) trivial run
+ intro j hj m _ bits rep hex
+ have eq := (execute_prefix_unique (SlotOwners.dummy_native p m (cursor j))
+ (show execute P 20 (P.start (cursor j)) m ([]++bits) = some rep from hex)).2
+ subst rep
+ have hc : (cursor j).val = j := Nat.mod_eq_of_lt (by omega)
+ have within := SlotOwners.dummy_input_range p (cursor j) (sites s) (by rw [p1]; omega) hw
+ (by rw [hc,padding]; exact hj)
+ have ha : (p 2+cursor j).val = h.scratch+genuineCount s+j := by
+ rw [Fin.val_add,p2,hc,Nat.mod_eq_of_lt (by omega)]
+ obtain ⟨rd,wr⟩ := dummy_event_addresses p m (cursor j)
+ refine ⟨congrArg some (word_inc j), trivial, ?_, ?_⟩
+ · intro a v hv
+ rw [rd a v hv]; simpa only [p1,dummyRead,interval] using within
+ · intro a v hv
+ change _ ≤ a.val ∧ a.val < h.scratch+genuineCount s+dummyCount s
+ rw [wr a v hv,ha]; omega
+
+variable {V H Tag L : Type*} {d c N J nL degree : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- Read and write footprints of the first two reports of a selected shrinking
+level. They follow from the actual stored table representation at the level's
+initial memory and the five native segments supplied by the level run. -/
+theorem of_tables (layout : Bool) (h : Heads) (mem : Memory w) (rs : SlotLevel.Reports w) :
+ let s : Shape := ⟨N,J,nL,d,c,subdiv,degree⟩
+ SlotOwners.GenuineTables P subdiv vertices tags lanes layout (bank s h w .genuineOwners) mem →
+ SlotOwners.DummyTables vertices tags lanes (pad s) (bank s h w .dummyOwners) mem →
+ h.oldArc+oldWords s ≤ h.scratch → h.role+8 ≤ h.scratch → h.subdivisions+4 ≤ h.scratch →
+ h.nextSite+sites s ≤ h.scratch → stopAddress s h < 2^w → rs.Native s h mem →
+ (Reads (genuineRead s h) (eventLog rs.genuine) ∧ Writes (genuineWrite s h) (eventLog rs.genuine)) ∧
+ (Reads (dummyRead s h) (eventLog rs.dummy) ∧ Writes (dummyWrite s h) (eventLog rs.dummy)) := by
+ intro s hg hd ha hr hs hn fit run
+ have rg : (bank s h w .genuineOwners 4).val = h.role :=
+ Nat.mod_eq_of_lt (by have := (owner_end s h).trans_lt fit; omega : h.role < 2^w)
+ have roles (j : ℕ) (hj : j < 8) : (mem (h.role+j)).val < 3 := by
+ let t : Fin 4 := ⟨j/2, by omega⟩
+ let side : Fin 2 := ⟨j%2, by omega⟩
+ have ix : 2*t.val+side.val = j := by dsimp [t,side]; omega
+ have hslot := hg.role t side
+ rw [rg,ix] at hslot
+ rw [hslot]; cases endRole layout (decide (side=1)) t <;> decide
+ exact ⟨genuine s h mem rs.genuine ha hr hs fit hg.laneCount hg.subdivCount hg.baseCount roles run.1,
+ dummy s h _ rs.dummy hn fit hd.twoFits hd.padCount run.2.1⟩
+
+end CompressorRecords.SlotOwnerFootprint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOwnerPass.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerPass.lean
new file mode 100644
index 0000000000..915ae91a09
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerPass.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Sequential generation of the endpoint owner table
+
+The genuine-field and padding-field workers each scan a consecutive interval of
+endpoint IDs. This pass lifts a single worker's native RAM execution to the
+whole interval. The single-call proof may read any cell outside the completed
+prefix, since all those cells still contain their initial words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotOwnerPass
+
+open BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- A worker for one endpoint ID. Only the output cells of earlier calls may
+have changed when the worker starts. -/
+def Visit (P : Program w C) (fuel probes ticks base start count : ℕ)
+ (value : ℕ → Word w) (initial : Memory w) : Prop :=
+ ∀ i, start ≤ i → i < start + count → ∀ mem : Memory w,
+ (∀ a, a < base + start ∨ base + i ≤ a → mem a = initial a) →
+ ∃ es, execute P fuel (P.start (Fin.ofNat _ i)) mem [] =
+ some ⟨es, some (Fin.ofNat _ (i + 1))⟩ ∧
+ after mem es = writeMemory mem (Fin.ofNat _ (base + i)) (value i) ∧
+ countProbes es = probes ∧ es.length = ticks
+
+/-- Running the worker with successive persistent cursors fills exactly the
+specified interval of the table. Both the probe count and the instruction
+trace length per call are exact. -/
+theorem run (P : Program w C) (fuel probes ticks base start count : ℕ)
+ (value : ℕ → Word w) (initial : Memory w) (fit : base + start + count ≤ 2 ^ w)
+ (visit : Visit P fuel probes ticks base start count value initial) :
+ ∃ rs, runSegment P fuel (some (Fin.ofNat _ start)) initial (List.replicate count []) = some rs ∧
+ endState (some (Fin.ofNat _ start)) rs = some (Fin.ofNat _ (start + count)) ∧
+ (∀ i, start ≤ i → i < start + count → after initial (eventLog rs) (base + i) = value i) ∧
+ (∀ a, a < base + start ∨ base + start + count ≤ a → after initial (eventLog rs) a = initial a) ∧
+ rs.length = count ∧ (∀ r ∈ rs, r.probes = probes ∧ r.events.length = ticks) ∧
+ RAMBuckets.cost Report.probes rs = (1 + probes) * count := by
+ induction count with
+ | zero =>
+ exact ⟨[], rfl, rfl, by omega, fun _ _ => rfl, rfl, by simp, by simp [RAMBuckets.cost]⟩
+ | succ count ih =>
+ obtain ⟨rs, hr, hs, hfilled, hframe, hlen, hwork, hcost⟩ :=
+ ih (by omega) (fun i lo hi mem frame => visit i lo (by omega) mem frame)
+ let k := start + count
+ let mem := after initial (eventLog rs)
+ obtain ⟨es, he, hw, hp, ht⟩ :=
+ visit k (by dsimp [k]; omega) (by dsimp [k]; omega) mem
+ (fun a ha => hframe a (by simpa only [k, Nat.add_assoc] using ha))
+ let r : Report w := ⟨es, some (Fin.ofNat _ (k + 1))⟩
+ have haddr : (Fin.ofNat (2 ^ w) (base + k)).val = base + k :=
+ Nat.mod_eq_of_lt (by dsimp [k]; omega)
+ have hm : after initial (eventLog (rs ++ [r])) =
+ writeMemory mem (Fin.ofNat _ (base + k)) (value k) := by
+ simpa only [eventLog, List.flatMap_append, List.flatMap_singleton, after, List.foldl_append, r,
+ mem] using hw
+ have hprobes : r.probes = probes := hp
+ refine ⟨rs ++ [r], ?_, ?_, ?_, ?_, by simp [hlen], ?_, ?_⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, hr]
+ simp only [Option.bind_some, hs, runSegment, Option.map_some]
+ change (match execute P fuel (P.start (Fin.ofNat _ k)) mem [] with
+ | none => none | some t => some [t]).map (rs ++ ·) = some (rs ++ [r])
+ rw [he]
+ rfl
+ · rw [endState_append]
+ change some (Fin.ofNat _ (k + 1)) = _
+ rw [show k + 1 = start + (count + 1) by dsimp [k]; omega]
+ · intro i lo hi
+ rw [hm, writeMemory, haddr]
+ by_cases eq : i = k
+ · simp [eq]
+ · rw [ite_eq_right (fun h => eq (Nat.add_left_cancel h))]
+ exact hfilled i lo (by dsimp [k] at eq; omega)
+ · intro a ha
+ rw [hm, writeMemory, haddr, ite_eq_right (by dsimp [k]; omega)]
+ exact hframe a (by omega)
+ · intro t h
+ rcases List.mem_append.mp h with h | h
+ · exact hwork t h
+ · obtain rfl := List.mem_singleton.mp h
+ exact ⟨hp, ht⟩
+ · rw [RAMBuckets.cost_append, hcost, RAMBuckets.cost, hprobes, RAMBuckets.cost, Nat.mul_succ]
+ omega
+
+end CompressorRecords.SlotOwnerPass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOwnerRuns.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerRuns.lean
new file mode 100644
index 0000000000..913d31a709
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOwnerRuns.lean
@@ -0,0 +1,301 @@
+import OAI.Computability.VPVNP.CompressorSlotOwners
+import OAI.Computability.VPVNP.CompressorSlotOwnerPass
+import OAI.Computability.VPVNP.RAMWork
+
+/-!
+# The two native endpoint-owner scans
+
+The genuine scan reads the role, the chosen site, the CD indicator, and the
+subdivision count. The padding scan reads the cyclic successor of a site.
+Disjointness of those inputs from the output interval suffices to compute
+both scans from the original descriptor memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotOwners
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ} {C : Type*}
+
+private abbrev word (i : ℕ) : Word w := Fin.ofNat _ i
+
+/-- The four external addresses consulted by the genuine worker. The second
+read depends on the role word returned by the first. -/
+def genuineInputs (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : List (Word w) :=
+ let f := digits p i
+ let role := roleAddress p f
+ let old := oldAddress p f
+ [role, old + m role.val, old + 3, subdivAddress p f]
+
+private theorem genuine_congr (p : Fin 8 → Word w) (i : Word w) {mem ref : Memory w}
+ (reads : ∀ a ∈ genuineInputs p ref i, mem a.val = ref a.val) :
+ genuineOwner p mem i = genuineOwner p ref i := by
+ let f := digits p i
+ let role := roleAddress p f
+ let old := oldAddress p f
+ have hrole := reads role (by simp [genuineInputs, role, f])
+ have hsite := reads (old + ref role.val) (by simp [genuineInputs, old, role, f])
+ have hcd := reads (old + 3) (by simp [genuineInputs, old, f])
+ have hsub := reads (subdivAddress p f) (by simp [genuineInputs, f])
+ dsimp only [f, old, role] at hrole hsite hcd hsub
+ simp only [genuineOwner, hrole, hsite, hcd, hsub]
+
+private theorem dummy_congr (p : Fin 3 → Word w) (i : Word w) {mem ref : Memory w}
+ (read : mem (p 1 + dummySource p i).val = ref (p 1 + dummySource p i).val) :
+ dummyOwner p mem i = dummyOwner p ref i := by
+ simp only [dummyOwner, read]
+
+private theorem word_add (base : Word w) (i : ℕ) : base + word i = word (base.val+i) := by
+ apply Fin.ext
+ simp only [word, Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod]
+
+private theorem word_succ (i : ℕ) : word (w := w) i + 1 = word (i+1) := by
+ apply Fin.ext
+ simp [word, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod]
+
+/-- A complete worker scan starts at cursor zero and fills its output cells
+in address order. The frame covers arbitrary external addresses. -/
+structure FilledRun (P : Program w C) (fuel probes ticks count : ℕ)
+ (base : Word w) (value : ℕ → Word w) (initial : Memory w) (rs : List (Report w)) : Prop where
+ executed : runSegment P fuel (some 0) initial (List.replicate count []) = some rs
+ cursor : endState (some 0) rs = some (Fin.ofNat _ count)
+ filled : ∀ i < count, after initial (eventLog rs) (base.val+i) = value i
+ frame : ∀ a, a < base.val ∨ base.val+count ≤ a → after initial (eventLog rs) a = initial a
+ length : rs.length = count
+ calls : ∀ r ∈ rs, r.probes = probes ∧ r.events.length = ticks
+ cost : RAMBuckets.cost Report.probes rs = (1+probes)*count
+
+/-- Start a sequential output worker at zero and package its interval and frame. -/
+theorem filled_run (P : Program w C) (fuel probes ticks count : ℕ)
+ (base : Word w) (value : ℕ → Word w) (initial : Memory w) (fit : base.val+count ≤ 2^w)
+ (visit : SlotOwnerPass.Visit P fuel probes ticks base.val 0 count value initial) :
+ ∃ rs, FilledRun P fuel probes ticks count base value initial rs := by
+ obtain ⟨rs,hr,hs,hf,ho,hl,hc,hcost⟩ :=
+ SlotOwnerPass.run P fuel probes ticks base.val 0 count value initial (by simpa using fit) visit
+ exact ⟨rs, hr, by simpa using hs, fun i hi => hf i (Nat.zero_le i) (by simpa using hi),
+ fun a ha => ho a (by simpa using ha), hl, hc, hcost⟩
+
+/-- Read four input words and write one genuine-field owner at each cursor. -/
+theorem genuine_run (p : Fin 8 → Word w) (initial : Memory w) (count : ℕ)
+ (fit : (p 7).val+count ≤ 2^w)
+ (reads : ∀ i < count, ∀ a ∈ genuineInputs p initial (word i),
+ a.val < (p 7).val ∨ (p 7).val+count ≤ a.val) :
+ let P := ((template genuine 0).instantiate w p).program
+ ∃ rs, FilledRun P 49 5 48 count (p 7) (fun i => genuineOwner p initial (word i)) initial rs := by
+ intro P
+ apply filled_run P 49 5 48 count (p 7) _ initial fit
+ intro i _ hi mem frame
+ have lt : i < count := by simpa using hi
+ have eq := genuine_congr p (word i) (mem := mem) (ref := initial) (fun a ha => by
+ have h := reads i lt a ha
+ exact frame a.val (by omega))
+ refine ⟨genuineEvents p mem (word i), ?_, ?_, (genuine_work ..).2, (genuine_work ..).1⟩
+ · rw [genuine_native, word_succ]
+ · rw [genuine_after, eq, word_add]
+
+/-- Read one cyclic successor and write one dummy-field owner at each cursor. -/
+theorem dummy_run (p : Fin 3 → Word w) (initial : Memory w) (count : ℕ)
+ (fit : (p 2).val+count ≤ 2^w)
+ (reads : ∀ i < count, let a := p 1 + dummySource p (word i)
+ a.val < (p 2).val ∨ (p 2).val+count ≤ a.val) :
+ let P := ((template dummy 0).instantiate w p).program
+ ∃ rs, FilledRun P 20 2 19 count (p 2) (fun i => dummyOwner p initial (word i)) initial rs := by
+ intro P
+ apply filled_run P 20 2 19 count (p 2) _ initial fit
+ intro i _ hi mem frame
+ have lt : i < count := by simpa using hi
+ let a := p 1 + dummySource p (word i)
+ have h : a.val < (p 2).val ∨ (p 2).val+count ≤ a.val := reads i lt
+ have eq : mem a.val = initial a.val := frame a.val (by omega)
+ refine ⟨dummyEvents p mem (word i), ?_, ?_, (dummy_work ..).2, (dummy_work ..).1⟩
+ · rw [dummy_native, word_succ]
+ · rw [dummy_after, word_add]
+ rw [dummy_congr p (word i) eq]
+
+/-- Execute the genuine and dummy workers in sequence, resetting the cursor
+between phases. The final table gives each endpoint the owner computed from
+the original descriptor memory. The two calls-plus-probes costs add exactly. -/
+theorem owner_runs (g : Fin 8 → Word w) (d : Fin 3 → Word w) (initial : Memory w)
+ (ng nd : ℕ) (adjacent : (d 2).val = (g 7).val + ng) (fit : (d 2).val+nd ≤ 2^w)
+ (greads : ∀ i < ng, ∀ a ∈ genuineInputs g initial (word i),
+ a.val < (g 7).val ∨ (d 2).val+nd ≤ a.val)
+ (dreads : ∀ i < nd, let a := d 1 + dummySource d (word i)
+ a.val < (g 7).val ∨ (d 2).val+nd ≤ a.val) :
+ let Pg := ((template genuine 0).instantiate w g).program
+ let Pd := ((template dummy 0).instantiate w d).program
+ ∃ gr dr, let mid := after initial (eventLog gr)
+ let final := after mid (eventLog dr)
+ FilledRun Pg 49 5 48 ng (g 7) (fun i => genuineOwner g initial (word i)) initial gr ∧
+ FilledRun Pd 20 2 19 nd (d 2) (fun i => dummyOwner d initial (word i)) mid dr ∧
+ (∀ i < ng, final ((g 7).val+i) = genuineOwner g initial (word i)) ∧
+ (∀ a, a < (g 7).val ∨ (d 2).val+nd ≤ a → final a = initial a) ∧
+ RAMBuckets.cost Report.probes (gr ++ dr) = 6*ng + 3*nd := by
+ intro Pg Pd
+ obtain ⟨gr, gh⟩ := genuine_run g initial ng (by omega) (fun i hi a ha => by
+ have := greads i hi a ha
+ omega)
+ let mid := after initial (eventLog gr)
+ obtain ⟨dr, dh⟩ := dummy_run d mid nd fit (fun i hi => by
+ have h := dreads i hi
+ dsimp only at h ⊢
+ omega)
+ have same (i : ℕ) (hi : i < nd) : dummyOwner d mid (word i) = dummyOwner d initial (word i) := by
+ apply dummy_congr
+ apply gh.frame
+ have h := dreads i hi
+ dsimp only at h
+ omega
+ refine ⟨gr, dr, gh, {dh with filled := fun i hi => (dh.filled i hi).trans (same i hi)}, ?_, ?_, ?_⟩
+ · intro i hi
+ exact (dh.frame _ (.inl (by omega))).trans (gh.filled i hi)
+ · intro a ha
+ exact (dh.frame a (by omega)).trans (gh.frame a (by omega))
+ · rw [RAMBuckets.cost_append, gh.cost, dh.cost]
+
+private theorem div_value (x y : Word w) : (BinaryOp.div.eval x y).val = x.val / y.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)
+
+private theorem mod_value (x y : Word w) : (BinaryOp.mod.eval x y).val = x.val % y.val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt)
+
+/-- The four read addresses stay in the original-arc records, the eight role
+entries, and the four subdivision counts, respectively. -/
+theorem genuine_inputs_ranges (p : Fin 8 → Word w) (m : Memory w) (i : Word w)
+ (arcsFit : (p 3).val + 4 * ((p 2).val * (p 0).val) ≤ 2^w)
+ (rolesFit : (p 4).val + 8 ≤ 2^w) (subdivFit : (p 5).val + 4 ≤ 2^w)
+ (roles : ∀ j < 8, (m ((p 4).val+j)).val < 3)
+ (hi : i.val < 4*(p 2).val*(p 1).val*(p 0).val*2) :
+ ∀ a ∈ genuineInputs p m i,
+ ((p 3).val ≤ a.val ∧ a.val < (p 3).val+4*((p 2).val*(p 0).val)) ∨
+ ((p 4).val ≤ a.val ∧ a.val < (p 4).val+8) ∨
+ ((p 5).val ≤ a.val ∧ a.val < (p 5).val+4) := by
+ let f := digits p i
+ have htwo : (2 : Word w).val = 2 := Nat.mod_eq_of_lt (by omega : 2 < 2^w)
+ have oldPos : 0 < (p 2).val := by by_contra! h; simp [show (p 2).val = 0 by omega] at hi
+ have subPos : 0 < (p 1).val := by by_contra! h; simp [show (p 1).val = 0 by omega] at hi
+ have lanePos : 0 < (p 0).val := by by_contra! h; simp [show (p 0).val = 0 by omega] at hi
+ have ht : f.edgeType.val < 4 := by
+ change ((BinaryOp.div.eval _ (p 2)).val < 4)
+ simp only [div_value, htwo, Nat.div_lt_iff_lt_mul oldPos, Nat.div_lt_iff_lt_mul subPos,
+ Nat.div_lt_iff_lt_mul lanePos, Nat.div_lt_iff_lt_mul (by decide : 0 < 2)]
+ exact hi
+ have hs : f.side.val < 2 := by
+ change (BinaryOp.mod.eval i 2).val < 2
+ rw [mod_value, htwo]
+ exact Nat.mod_lt _ (by decide)
+ have hb : f.oldArc.val < (p 2).val*(p 0).val := by
+ let arc := BinaryOp.div.eval i 2
+ let b := BinaryOp.div.eval (BinaryOp.div.eval arc (p 0)) (p 1)
+ have hbase := Nat.mod_lt b.val oldPos
+ have hlane := Nat.mod_lt arc.val lanePos
+ have bound := Nat.mul_le_mul_right (p 0).val (Nat.succ_le_of_lt hbase)
+ rw [Nat.succ_mul] at bound
+ change ((BinaryOp.mod.eval b (p 2)) * p 0 + BinaryOp.mod.eval arc (p 0)).val < _
+ rw [Fin.val_add, Fin.val_mul, mod_value, mod_value, Nat.mod_add_mod]
+ exact (Nat.mod_le ..).trans_lt (by omega)
+ let r := roleAddress p f
+ let old := oldAddress p f
+ have hr : r.val = (p 4).val + (2*f.edgeType.val + f.side.val) := by
+ simp only [r, roleAddress, Fin.val_add, Fin.val_mul, htwo, Nat.mod_add_mod, Nat.add_mod_mod]
+ exact Nat.mod_eq_of_lt (by omega)
+ have hrole : (m r.val).val < 3 := by rw [hr]; exact roles _ (by omega)
+ have hold : old.val = (p 3).val + 4*f.oldArc.val := by
+ simp only [old, oldAddress, Fin.val_add, Fin.val_mul, htwo, Nat.mod_mul_mod, Nat.add_mod_mod]
+ exact Nat.mod_eq_of_lt (by omega)
+ have hc : (old + 3).val = old.val+3 := by
+ rw [Fin.val_add, show (3 : Word w).val = 3 from Nat.mod_eq_of_lt (by omega : 3 < 2^w),
+ Nat.mod_eq_of_lt (by omega)]
+ have hsite : (old + m r.val).val = old.val+(m r.val).val := by
+ rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ have hsub : (subdivAddress p f).val = (p 5).val+f.edgeType.val := by
+ rw [subdivAddress, Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ intro a ha
+ change a ∈ [r, old + m r.val, old + 3, subdivAddress p f] at ha
+ simp only [List.mem_cons, List.not_mem_nil, or_false] at ha
+ rcases ha with rfl | rfl | rfl | rfl
+ · exact Or.inr (Or.inl (by omega))
+ · exact Or.inl (by omega)
+ · exact Or.inl (by omega)
+ · exact Or.inr (Or.inr (by omega))
+
+/-- Placing the three input arrays below the output suffices for every genuine
+read. The role words are offsets in the three-site part of each four-word record. -/
+theorem genuine_inputs_before (p : Fin 8 → Word w) (m : Memory w) (i stop : Word w)
+ (arcsEnd : (p 3).val + 4 * ((p 2).val * (p 0).val) ≤ stop.val)
+ (rolesEnd : (p 4).val + 8 ≤ stop.val) (subdivEnd : (p 5).val + 4 ≤ stop.val)
+ (roles : ∀ j < 8, (m ((p 4).val+j)).val < 3)
+ (hi : i.val < 4*(p 2).val*(p 1).val*(p 0).val*2) :
+ ∀ a ∈ genuineInputs p m i, a.val < stop.val := by
+ intro a ha
+ rcases genuine_inputs_ranges p m i (arcsEnd.trans stop.isLt.le) (rolesEnd.trans stop.isLt.le)
+ (subdivEnd.trans stop.isLt.le) roles hi a ha with h | h | h <;> omega
+
+/-- Both endpoints of a dummy arc probe its original site in the cyclic successor array. -/
+theorem dummy_input_range (p : Fin 3 → Word w) (i : Word w) (sites : ℕ)
+ (fit : (p 1).val+sites ≤ 2^w) (hw : 2 < 2^w)
+ (hi : i.val < sites*(p 0).val*2) :
+ (p 1).val ≤ (p 1+dummySource p i).val ∧ (p 1+dummySource p i).val < (p 1).val+sites := by
+ have hp : 0 < (p 0).val := by by_contra! h; simp [show (p 0).val = 0 by omega] at hi
+ have hs : (dummySource p i).val < sites := by
+ change (BinaryOp.div.eval (BinaryOp.div.eval i 2) (p 0)).val < _
+ rw [div_value, div_value, show (2 : Word w).val = 2 from Nat.mod_eq_of_lt hw,
+ Nat.div_lt_iff_lt_mul hp, Nat.div_lt_iff_lt_mul (by decide : 0 < 2)]
+ exact hi
+ rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ omega
+
+/-- A cyclic-successor array of one word per site suffices for both sides of
+each dummy arc, including all copies of a padding slot. -/
+theorem dummy_input_before (p : Fin 3 → Word w) (i stop : Word w) (sites : ℕ)
+ (endOfTable : (p 1).val+sites ≤ stop.val) (hw : 2 < 2^w)
+ (hi : i.val < sites*(p 0).val*2) : (p 1+dummySource p i).val < stop.val :=
+ (dummy_input_range p i sites (endOfTable.trans stop.isLt.le) hw hi).2.trans_le endOfTable
+
+/-- Straight-line templates use registers and external memory, so an
+instruction never scans the private write log. This holds at every program
+counter, for every allowance and stream of read bits. -/
+theorem template_opcode_work {r k : ℕ} (ops : List (Op r k)) (result : Fin r)
+ (pub : Fin k → Word w) (fuel : ℕ) (l : LogConfig w (ops.length+2) r)
+ (allowance : ℕ) (bits : List Bool) :
+ ((template ops result).instantiate w pub).loggedDispatchWork fuel l allowance bits ≤ 6*fuel := by
+ let M := (template ops result).instantiate w pub
+ have noLog (c : LogConfig w (ops.length+2) r) : (M.code c.pc).actualLogWork c = 0 := by
+ simp only [M, Template.instantiate, template]
+ split
+ · cases ops[c.pc.val] <;> rfl
+ · split <;> rfl
+ change M.loggedDispatchWork fuel l allowance bits ≤ _
+ induction fuel generalizing l allowance bits with
+ | zero => rfl
+ | succ f ih =>
+ rw [Machine.loggedDispatchWork, noLog, Nat.add_zero]
+ have h := (M.code l.pc).wordWork_le
+ split
+ · omega
+ · rename_i l' a' bs' _
+ have := ih l' a' bs'
+ omega
+
+/-- A genuine-owner call dispatches at most 49 instructions. -/
+theorem genuine_opcode_work (pub : Fin 8 → Word w) (i : Word w)
+ (allowance : ℕ) (bits : List Bool) :
+ let M := (template genuine 0).instantiate w pub
+ M.loggedDispatchWork 49 (M.logProgram.start i) allowance bits ≤ 294 :=
+ template_opcode_work genuine 0 pub 49 _ allowance bits
+
+/-- A dummy-owner call dispatches at most 20 instructions. -/
+theorem dummy_opcode_work (pub : Fin 3 → Word w) (i : Word w)
+ (allowance : ℕ) (bits : List Bool) :
+ let M := (template dummy 0).instantiate w pub
+ M.loggedDispatchWork 20 (M.logProgram.start i) allowance bits ≤ 120 :=
+ template_opcode_work dummy 0 pub 20 _ allowance bits
+
+end CompressorRecords.SlotOwners
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotOwners.lean b/lean/OAI/Computability/VPVNP/CompressorSlotOwners.lean
new file mode 100644
index 0000000000..ef1544e5bc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotOwners.lean
@@ -0,0 +1,318 @@
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+import OAI.Computability.VPVNP.RAMRecords
+import Mathlib.Data.ZMod.Defs
+
+/-!
+# Computing endpoint owners in absolute field order
+
+A genuine candidate has an edge type, an original base arc, a subdivision index,
+an absolute source lane, and an endpoint side. The scan reads one selected role
+from the layout table and follows it to the packed site in the original arc
+record. Each missing candidate receives its own auxiliary owner. A separate
+scan handles the contiguous dummy fields and uses the cyclic next-site table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotOwners
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ}
+
+private abbrev divWord := @BinaryOp.eval w .div
+private abbrev modWord := @BinaryOp.eval w .mod
+
+/-- Public words are the number of lanes, sum of subdivision counts, number of old
+base arcs, starts of the old arc records, role table and subdivision table,
+number of real endpoint owners, and start of the output. -/
+def genuine : List (Op 16 8) :=
+ [.stateWord 0, .constant 1 1, .constant 2 2, .binary .mod 3 0 2,
+ .binary .div 4 0 2, .publicWord 5 0, .binary .mod 6 4 5, .binary .div 4 4 5,
+ .publicWord 7 1, .binary .mod 8 4 7, .binary .div 4 4 7, .publicWord 7 2,
+ .binary .mod 9 4 7, .binary .div 10 4 7, .binary .mul 9 9 5, .binary .add 9 9 6,
+ .binary .add 11 2 2, .binary .mul 9 11 9, .publicWord 11 3, .binary .add 9 11 9,
+ .publicWord 11 4, .binary .mul 12 2 10, .binary .add 12 12 3, .binary .add 12 11 12,
+ .read 12 12, .binary .add 12 9 12, .read 12 12,
+ .constant 13 3, .binary .add 13 9 13, .read 13 13,
+ .publicWord 14 5, .binary .add 14 14 10, .read 14 14,
+ .binary .add 8 8 1, .binary .div 14 14 8, .binary .div 14 14 14, .binary .mul 13 13 14,
+ .binary .mul 12 2 12, .binary .add 12 12 3,
+ .publicWord 15 6, .binary .add 15 15 0, .binary .sub 12 12 15,
+ .binary .mul 12 13 12, .binary .add 12 15 12, .publicWord 15 7, .binary .add 15 15 0,
+ .write 15 12, .binary .add 0 0 1]
+
+/-- The decoded side, role edge type, subdivision, and absolute old arc used to classify one
+genuine candidate field. -/
+structure Digits (α : Type) where
+ /-- Endpoint bit of the candidate field, zero for the outgoing side and one for the incoming
+ side. -/
+ side : α
+ /-- Index of the role edge type used to select the endpoint roles and subdivision limit. -/
+ edgeType : α
+ /-- Candidate subdivision index to compare with the selected edge type's subdivision count. -/
+ subdivision : α
+ /-- Absolute old arc index, with the residual lane as its least significant digit. -/
+ oldArc : α
+
+/-- The original arc keeps its lane as its least significant digit, even though
+the subdivision digit lies between the old base arc and lane in the candidate ID. -/
+def digits (p : Fin 8 → Word w) (i : Word w) : Digits (Word w) :=
+ let arc := divWord i 2
+ let key := divWord arc (p 0)
+ let typeAndBase := divWord key (p 1)
+ ⟨modWord i 2, divWord typeAndBase (p 2), modWord key (p 1),
+ modWord typeAndBase (p 2) * p 0 + modWord arc (p 0)⟩
+
+/-- Address of the role selector for the candidate's edge type and endpoint side. -/
+def roleAddress (p : Fin 8 → Word w) (f : Digits (Word w)) := p 4 + (2 * f.edgeType + f.side)
+
+/-- Start of the candidate's four-word old arc record, containing the role sites and CD flag. -/
+def oldAddress (p : Fin 8 → Word w) (f : Digits (Word w)) := p 3 + ((2+2) * f.oldArc)
+
+/-- Address of the subdivision count for the candidate's role edge type. -/
+def subdivAddress (p : Fin 8 → Word w) (f : Digits (Word w)) := p 5 + f.edgeType
+
+private def below (j n : Word w) : Word w :=
+ let q := divWord n (j+1)
+ divWord q q
+
+private def select (b x y : Word w) : Word w := x + b * (y-x)
+
+/-- Word written for a genuine candidate, including candidates that decode to holes. -/
+def genuineOwner (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : Word w :=
+ let f := digits p i
+ let a := oldAddress p f
+ let site := m (a + m (roleAddress p f).val).val
+ let cd := m (a+3).val
+ let n := m (subdivAddress p f).val
+ select (cd * below f.subdivision n) (p 6+i) (2*site+f.side)
+
+/-- Trace of one genuine candidate visit, reading its role selector, site, CD flag, and
+subdivision count before writing its owner. -/
+def genuineEvents (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : List (Event w) :=
+ let f := digits p i
+ let role := roleAddress p f
+ let a := oldAddress p f
+ let site := a + m role.val
+ let cd := a+3
+ let n := subdivAddress p f
+ List.replicate 24 .tick ++ [.read role (m role.val), .tick, .read site (m site.val),
+ .tick, .tick, .read cd (m cd.val), .tick, .tick, .read n (m n.val)] ++
+ List.replicate 13 .tick ++ [.write (p 7+i) (genuineOwner p m i), .tick]
+
+theorem genuine_after (p : Fin 8 → Word w) (m : Memory w) (i : Word w) :
+ after m (genuineEvents p m i) = writeMemory m (p 7+i) (genuineOwner p m i) := rfl
+
+theorem genuine_work (p : Fin 8 → Word w) (m : Memory w) (i : Word w) :
+ (genuineEvents p m i).length = 48 ∧ countProbes (genuineEvents p m i) = 5 := ⟨rfl,rfl⟩
+
+set_option maxRecDepth 8192 in
+set_option maxHeartbeats 1000000 in
+private theorem genuine_trace (p : Fin 8 → Word w) (m : Memory w) (i : Word w) (rs : Regs w 16) :
+ ∃ rs', trace p i genuine rs m = some (genuineEvents p m i, rs', after m (genuineEvents p m i)) ∧
+ rs' 0 = i+1 := by
+ simp (config := {decide := true}) [genuine, trace, Op.effect, Function.update, BinaryOp.eval,
+ genuineEvents, genuineOwner, roleAddress, oldAddress, subdivAddress, digits, below, select,
+ divWord, modWord]
+ repeat' apply And.intro
+ all_goals rfl
+
+/-- Four table reads and one write compute the next genuine field. -/
+theorem genuine_native (p : Fin 8 → Word w) (m : Memory w) (i : Word w) :
+ let M := (template genuine 0).instantiate w p
+ execute M.program 49 (M.program.start i) m [] = some ⟨genuineEvents p m i, some (i+1)⟩ := by
+ obtain ⟨rs, ht, hr⟩ := genuine_trace p m i (fun _ => 0)
+ let M := (template genuine 0).instantiate w p
+ change execute M.program (1 + genuine.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace, ht]; simp [hr]
+
+/-- Dummy public words are the padding degree, cyclic next-site table start, and
+start of the dummy output interval. Each dummy pass starts its cursor at zero. -/
+def dummy : List (Op 8 3) :=
+ [.stateWord 0, .constant 1 1, .constant 2 2, .binary .div 3 0 2, .binary .mod 4 0 2,
+ .publicWord 5 0, .binary .div 3 3 5, .publicWord 5 1, .binary .add 5 5 3, .read 6 5,
+ .binary .sub 6 6 3, .binary .mul 6 4 6, .binary .add 6 3 6, .binary .mul 6 2 6,
+ .binary .add 6 6 4, .publicWord 7 2, .binary .add 7 7 0, .write 7 6, .binary .add 0 0 1]
+
+/-- Recover the padding arc's source site from its field cursor by removing the side and
+dummy-slot digits. -/
+def dummySource (p : Fin 3 → Word w) (i : Word w) := divWord (divWord i 2) (p 0)
+
+/-- Encode the source site and outgoing side for a dummy source field or the cyclic successor
+and incoming side for its target field. -/
+def dummyOwner (p : Fin 3 → Word w) (m : Memory w) (i : Word w) :=
+ let s := dummySource p i
+ let side := modWord i 2
+ 2 * select side s (m (p 1+s).val) + side
+
+/-- Trace of one dummy field visit, reading the source site's cyclic successor and writing the
+selected endpoint owner. -/
+def dummyEvents (p : Fin 3 → Word w) (m : Memory w) (i : Word w) : List (Event w) :=
+ let a := p 1 + dummySource p i
+ List.replicate 9 .tick ++ [.read a (m a.val)] ++ List.replicate 7 .tick ++
+ [.write (p 2+i) (dummyOwner p m i), .tick]
+
+theorem dummy_after (p : Fin 3 → Word w) (m : Memory w) (i : Word w) :
+ after m (dummyEvents p m i) = writeMemory m (p 2+i) (dummyOwner p m i) := rfl
+
+theorem dummy_work (p : Fin 3 → Word w) (m : Memory w) (i : Word w) :
+ (dummyEvents p m i).length = 19 ∧ countProbes (dummyEvents p m i) = 2 := ⟨rfl,rfl⟩
+
+/-- One next-site read and one write compute the dummy field. -/
+theorem dummy_native (p : Fin 3 → Word w) (m : Memory w) (i : Word w) :
+ let M := (template dummy 0).instantiate w p
+ execute M.program 20 (M.program.start i) m [] = some ⟨dummyEvents p m i, some (i+1)⟩ := by
+ let M := (template dummy 0).instantiate w p
+ change execute M.program (1 + dummy.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]
+ rfl
+
+/-- Natural-number decoding in the same mixed radices as the genuine arc address. -/
+def natDigits (lanes subdivisions oldBases field : ℕ) : Digits ℕ :=
+ let arc := field / 2
+ let key := arc / lanes
+ let typeAndBase := key / subdivisions
+ ⟨field % 2, typeAndBase / oldBases, key % subdivisions,
+ (typeAndBase % oldBases) * lanes + arc % lanes⟩
+
+private theorem div_val (x y : Word w) : (divWord x y).val = x.val / y.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)
+
+private theorem mod_val (x y : Word w) : (modWord x y).val = x.val % y.val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt)
+
+private theorem two_val (hw : 2 < 2^w) : (2 : Word w).val = 2 :=
+ Nat.mod_eq_of_lt hw
+
+private theorem below_eq (j n : Word w) (hj : j.val + 1 < 2^w) :
+ below j n = if j.val < n.val then 1 else 0 := by
+ have hs : (j+1).val = j.val + 1 := by
+ rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (by omega : 1 < 2^w), Nat.mod_eq_of_lt hj]
+ apply Fin.ext
+ simp only [below, div_val, hs]
+ by_cases h : j.val < n.val
+ · rw [ite_eq_left h, Nat.div_self (Nat.div_pos h (Nat.zero_lt_succ _)),
+ Fin.val_one', Nat.mod_eq_of_lt (by omega)]
+ · rw [ite_eq_right h, Nat.div_eq_of_lt (by omega : n.val < j.val+1)]; rfl
+
+/-- Input words and lookup addresses used by one genuine field. The old record
+has three packed sites and a CD indicator. The role lookup always chooses one
+of the three site fields, even on a candidate that ultimately becomes a hole. -/
+structure GenuineInput (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : Prop where
+ twoFits : 2 < 2^w
+ subdivPositive : 0 < (p 1).val
+ oldFits : let f := natDigits (p 0).val (p 1).val (p 2).val i.val
+ (p 3).val + 4*f.oldArc + 3 < 2^w
+ roleFits : let f := natDigits (p 0).val (p 1).val (p 2).val i.val
+ (p 4).val + (2*f.edgeType + f.side) < 2^w
+ subdivFits : let f := natDigits (p 0).val (p 1).val (p 2).val i.val
+ (p 5).val + f.edgeType < 2^w
+ roleValid : let f := natDigits (p 0).val (p 1).val (p 2).val i.val
+ (m ((p 4).val + (2*f.edgeType + f.side))).val < 3
+ cdBit : let f := natDigits (p 0).val (p 1).val (p 2).val i.val
+ (m ((p 3).val + 4*f.oldArc + 3)).val ≤ 1
+
+/-- Numeric owner prior to conversion to a RAM word. The hole owner is unique
+to the absolute field and starts just beyond the real endpoint owners. -/
+def natGenuineOwner (p : Fin 8 → Word w) (m : Memory w) (i : ℕ) : ℕ :=
+ let f := natDigits (p 0).val (p 1).val (p 2).val i
+ let base := (p 3).val + 4*f.oldArc
+ let role := (m ((p 4).val + (2*f.edgeType + f.side))).val
+ if (m (base+3)).val = 1 ∧ f.subdivision < (m ((p 5).val+f.edgeType)).val
+ then 2*(m (base+role)).val + f.side
+ else (p 6).val+i
+
+open scoped Fin.CommRing in
+/-- With fitting addresses the native word implements the numerical decoder,
+including both reasons a genuine candidate can be absent. -/
+theorem genuineOwner_eq (p : Fin 8 → Word w) (m : Memory w) (i : Word w)
+ (h : GenuineInput p m i) : genuineOwner p m i = Fin.ofNat _ (natGenuineOwner p m i.val) := by
+ let f := natDigits (p 0).val (p 1).val (p 2).val i.val
+ let g := digits p i
+ let base := (p 3).val + 4*f.oldArc
+ let r := (p 4).val + (2*f.edgeType + f.side)
+ let n := (p 5).val + f.edgeType
+ have hbase : base + 3 < 2^w := h.oldFits
+ have hr : r < 2^w := h.roleFits
+ have hn : n < 2^w := h.subdivFits
+ have hrole : (m r).val < 3 := h.roleValid
+ have hbit : (m (base+3)).val ≤ 1 := h.cdBit
+ have hw := two_val h.twoFits
+ have hd : g.side.val = f.side ∧ g.edgeType.val = f.edgeType ∧
+ g.subdivision.val = f.subdivision ∧ g.oldArc.val = f.oldArc := by
+ have hOld : f.oldArc < 2^w := by dsimp only [base] at hbase; omega
+ simp only [g, digits, mod_val, div_val, hw, Fin.val_add, Fin.val_mul, Nat.mod_add_mod]
+ exact ⟨rfl, rfl, rfl, Nat.mod_eq_of_lt hOld⟩
+ obtain ⟨hs,ht,hj,ho⟩ := hd
+ have haddr : (oldAddress p g).val = base := by
+ simp only [oldAddress, Fin.val_add, Fin.val_mul, hw, ho, Nat.mod_mul_mod, Nat.add_mod_mod]
+ exact Nat.mod_eq_of_lt (by omega : base < 2^w)
+ have hraddr : (roleAddress p g).val = r := by
+ simp only [roleAddress, Fin.val_add, Fin.val_mul, hw, hs, ht, Nat.mod_add_mod, Nat.add_mod_mod]
+ exact Nat.mod_eq_of_lt hr
+ have hnaddr : (subdivAddress p g).val = n := by
+ rw [subdivAddress, Fin.val_add, ht, Nat.mod_eq_of_lt hn]
+ have hcaddr : (oldAddress p g+3).val = base+3 := by
+ have hthree : (3 : Word w).val = 3 := Nat.mod_eq_of_lt (by omega : 3 < 2^w)
+ rw [Fin.val_add, haddr, hthree, Nat.mod_eq_of_lt hbase]
+ have hsaddr : (oldAddress p g + m r).val = base + (m r).val := by
+ rw [Fin.val_add, haddr, Nat.mod_eq_of_lt (by omega)]
+ have hsub : f.subdivision < (p 1).val := Nat.mod_lt _ h.subdivPositive
+ have hjfit : g.subdivision.val + 1 < 2^w := by rw [hj]; have := (p 1).isLt; omega
+ change select (m (oldAddress p g+3).val * below g.subdivision (m (subdivAddress p g).val))
+ (p 6+i) (2*m (oldAddress p g+m (roleAddress p g).val).val+g.side) = _
+ rw [hcaddr, hnaddr, below_eq _ _ hjfit, hj, hraddr, hsaddr]
+ change _ = Fin.ofNat _ (if (m (base+3)).val = 1 ∧ f.subdivision < (m n).val
+ then 2*(m (base+(m r).val)).val+f.side else (p 6).val+i.val)
+ have hole : p 6+i = Fin.ofNat _ ((p 6).val + i.val) := rfl
+ have real : 2*m (base+(m r).val)+g.side = Fin.ofNat _ (2*(m (base+(m r).val)).val+f.side) := by
+ apply Fin.ext
+ rw [Fin.val_add, Fin.val_mul, hw, hs, Nat.mod_add_mod]; rfl
+ by_cases hc : (m (base+3)).val = 1
+ · have hc' : m (base+3) = 1 := Fin.ext (hc.trans (Nat.mod_eq_of_lt (by omega)).symm)
+ by_cases hj' : f.subdivision < (m n).val
+ · rw [ite_eq_left hj', ite_eq_left (c := (m (base+3)).val = 1 ∧ f.subdivision < (m n).val) ⟨hc,hj'⟩, hc', one_mul]
+ simpa only [select, one_mul, add_sub_cancel] using real
+ · rw [ite_eq_right hj', ite_eq_right (c := (m (base+3)).val = 1 ∧ f.subdivision < (m n).val) (fun a => hj' a.2), hc', mul_zero]
+ simpa only [select, zero_mul, add_zero] using hole
+ · have hc' : m (base+3) = 0 := Fin.ext (by change _ = 0; omega)
+ rw [ite_eq_right (c := (m (base+3)).val = 1 ∧ f.subdivision < (m n).val) (fun a => hc a.1), hc', zero_mul]
+ simpa only [select, zero_mul, add_zero] using hole
+
+/-- The dummy source is recovered by stripping the side and padding-copy
+digits. The incoming field reads the next site in the cyclic tag order. -/
+def natDummyOwner (p : Fin 3 → Word w) (m : Memory w) (i : ℕ) : ℕ :=
+ let s := i / 2 / (p 0).val
+ let side := i % 2
+ 2 * (if side = 0 then s else (m ((p 1).val+s)).val) + side
+
+open scoped Fin.CommRing in
+theorem dummyOwner_eq (p : Fin 3 → Word w) (m : Memory w) (i : Word w)
+ (hw : 2 < 2^w) (hfit : (p 1).val + i.val / 2 / (p 0).val < 2^w) :
+ dummyOwner p m i = Fin.ofNat _ (natDummyOwner p m i.val) := by
+ let s := i.val / 2 / (p 0).val
+ have htwo := two_val hw
+ have hs : (dummySource p i).val = s := by rw [dummySource, div_val, div_val, htwo]
+ have ha : (p 1+dummySource p i).val = (p 1).val+s := by rw [Fin.val_add, hs, Nat.mod_eq_of_lt hfit]
+ have hside : (modWord i 2).val = i.val % 2 := by rw [mod_val, htwo]
+ have he : i.val % 2 = 0 ∨ i.val % 2 = 1 := by omega
+ rcases he with h | h
+ · have hz : modWord i 2 = 0 := Fin.ext (hside.trans h)
+ simp only [dummyOwner, hz, select, zero_mul, add_zero, natDummyOwner, h, ite_true]
+ apply Fin.ext
+ rw [Fin.val_mul, htwo, hs]; rfl
+ · have hu : modWord i 2 = 1 := Fin.ext ((hside.trans h).trans (Nat.mod_eq_of_lt (by omega)).symm)
+ simp only [dummyOwner, hu, select, one_mul, add_sub_cancel, ha, natDummyOwner, h, Nat.one_ne_zero,
+ ite_false]
+ apply Fin.ext
+ rw [Fin.val_add, Fin.val_mul, htwo, Fin.val_one', Nat.mod_eq_of_lt (by omega : 1 < 2^w),
+ Nat.mod_add_mod]; rfl
+
+end CompressorRecords.SlotOwners
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotPhaseCosts.lean b/lean/OAI/Computability/VPVNP/CompressorSlotPhaseCosts.lean
new file mode 100644
index 0000000000..6a2a656198
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotPhaseCosts.lean
@@ -0,0 +1,856 @@
+import OAI.Computability.VPVNP.CompressorSliceSchedule
+import OAI.Computability.VPVNP.CompressorRecordsDemandRAM
+import OAI.Computability.VPVNP.CompressorSlotLevelRun
+import OAI.Computability.VPVNP.CompressorSlotOwnerAux
+import OAI.Computability.VPVNP.CompressorSlotOwnerDecode
+import OAI.Computability.VPVNP.CompressorRecordsBundleGather
+import OAI.Computability.VPVNP.CompressorRecordRefreshAllSlots
+import OAI.Computability.VPVNP.RAMFinite
+
+/-!
+# Costs of the physical slot and slice passes of Appendix E
+
+A pass is charged for every worker call and external probe, including visits to
+empty records. The site count multiplies constants determined by the degree and
+the subdivision template. Field widths affect the values stored in words, while
+the directory allocations count fields and candidate intersections.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PhaseCosts
+
+open BurstRAM Compression
+
+variable {w : ℕ}
+
+/-- The native schedule consumes one branch record per executed worker. -/
+theorem run_length {C : Type*} {P : BurstRAM.Program w C} {fuel st mem bs rs}
+ (hr : runSegment P fuel st mem bs = some rs) : rs.length = bs.length := by
+ have h := ((runSegment_iff ..).mp hr).2.2
+ simpa [branchPaths] using congrArg List.length h
+
+/-- Each report in a successful native segment obeys the segment worker cap. -/
+theorem run_cap {C : Type*} {P : BurstRAM.Program w C} {fuel st mem bs rs}
+ (hr : runSegment P fuel st mem bs = some rs) : ∀ r ∈ rs, r.events.length + 1 ≤ fuel :=
+ fun r h ↦ localSegment_event_bound ((runSegment_iff ..).mp hr).1 r h
+
+private theorem probeCount_eq_sum (rs : List (Report w)) :
+ RAMBuckets.probeCount Report.probes rs = (rs.map Report.probes).sum := by
+ induction rs with
+ | nil => rfl
+ | cons r rs ih => simp [RAMBuckets.probeCount, ih]
+
+/-- One family of concrete slice workspaces, each starting at the memory handed to it. -/
+structure SliceInput (w : ℕ) (old new : List ℕ) where
+ /-- Base address of the old field widths supplied to the slice construction. -/
+ oldBase : Word w
+ /-- Base address of the new field widths against which the slice construction intersects the
+ old fields. -/
+ newBase : Word w
+ /-- Start of the workspace used to build field boundaries, copy records, and adjacency data
+ for this slice. -/
+ scratch : Word w
+ /-- Memory presented to the slice workers, containing the specified old and new width arrays. -/
+ initial : Memory w
+ workspace : SliceSchedule.Workspace oldBase newBase scratch old.length new.length
+ oldSum : old.sum < 2^w
+ newSum : new.sum < 2^w
+ oldWidths : ∀ i (hi : i < old.length), (initial (oldBase.val+i)).val = old[i]
+ newWidths : ∀ j (hj : j < new.length), (initial (newBase.val+j)).val = new[j]
+
+/-- Native segment executions and their physical output tables. -/
+def SliceInput.produces {old new : List ℕ} (t : SliceInput w old new)
+ (r : SliceSchedule.Passes w) : Prop :=
+ SliceSchedule.NativePasses t.oldBase t.newBase t.scratch old.length new.length t.initial r ∧
+ SliceSchedule.Stored t.scratch old new t.initial (r.result t.initial)
+
+/-- End-to-end resource bounds for the five passes, together with the resulting physical
+tables. `M` and `N` bound the number of source and destination fields per invocation. -/
+def SliceCosts {ι : Type*} [Fintype ι] (old new : ι → List ℕ)
+ (input : ∀ i, SliceInput w (old i) (new i)) (M N : ℕ) : Prop :=
+ ∃ rs : ι → SliceSchedule.Passes w,
+ (∀ i, (input i).produces (rs i)) ∧
+ (∀ i, ∀ r ∈ (rs i).all, r.events.length + 1 ≤ 38) ∧
+ (∑ i, (rs i).all.length) ≤ Fintype.card ι * (2 + 2*(M+N) + 2*(M*N)) ∧
+ (∑ i, RAMBuckets.cost Report.probes (rs i).all) ≤
+ Fintype.card ι * (4 + 7*(M+N) + 16*(M*N)) ∧
+ (∑ i, ((rs i).all.map fun r ↦ r.events.length + 1).sum) ≤
+ Fintype.card ι * (16 + 22*(M+N) + 74*(M*N)) ∧
+ (∀ i, SliceSchedule.stop (input i).scratch.val (old i).length (new i).length ≤
+ (input i).scratch.val + 2 + 2*(M+N) + 5*(M*N))
+
+/-- All slice calls from actual input arrays, with costs summed across sites and a bound
+on the largest row address. Empty fields and empty intersections are charged as well. -/
+theorem sliceSites {ι : Type*} [Fintype ι] (old new : ι → List ℕ)
+ (input : ∀ i, SliceInput w (old i) (new i)) {M N : ℕ}
+ (ho : ∀ i, (old i).length ≤ M) (hn : ∀ i, (new i).length ≤ N) :
+ SliceCosts old new input M N := by
+ classical
+ have one (i : ι) := SliceSchedule.build (old i) (new i) (input i).oldBase (input i).newBase
+ (input i).scratch (input i).initial (input i).workspace (input i).oldSum (input i).newSum
+ (input i).oldWidths (input i).newWidths
+ choose rs hnative hstored hcalls hprobe hinst using one
+ have hprod (i : ι) := Nat.mul_le_mul (ho i) (hn i)
+ have hsum (i : ι) := Nat.add_le_add (ho i) (hn i)
+ have hrec (i : ι) := copyRecords_length_le (old i) (new i)
+ refine ⟨rs, fun i ↦ ⟨hnative i, hstored i⟩, ?_, ?_, ?_, ?_, ?_⟩
+ · intro i r hr
+ simp only [SliceSchedule.Passes.all, List.mem_append] at hr
+ rcases hr with (((h|h)|h)|h)|h
+ · exact (run_cap (hnative i).preparation.clearNative r h).trans (by decide)
+ · exact (run_cap (hnative i).preparation.oldNative r h).trans (by decide)
+ · exact (run_cap (hnative i).preparation.newNative r h).trans (by decide)
+ · exact run_cap (hnative i).pairs r h
+ · exact (run_cap (hnative i).adjacency r h).trans (by decide)
+ · rw [← Nat.nsmul_eq_mul, ← Finset.card_univ (α := ι), ← Finset.sum_const]
+ exact Finset.sum_le_sum fun i _ ↦ by have := hcalls i; have := hsum i; have := hprod i; omega
+ · rw [← Nat.nsmul_eq_mul, ← Finset.card_univ (α := ι), ← Finset.sum_const]
+ apply Finset.sum_le_sum
+ intro i _
+ rw [RAMBuckets.cost_eq_length_add_probes, probeCount_eq_sum, hcalls i, hprobe i]
+ have := hprod i; have := hsum i; have := hrec i; omega
+ · rw [← Nat.nsmul_eq_mul, ← Finset.card_univ (α := ι), ← Finset.sum_const]
+ apply Finset.sum_le_sum
+ intro i _
+ rw [hinst i]
+ have := hprod i; have := hsum i; have := hrec i; omega
+ · intro i
+ unfold SliceSchedule.stop SliceSchedule.frameHead
+ have := hprod i; have := hsum i; omega
+
+open Compression.PackingData in
+/-- One demand slice invocation per packed bundle, on its actual thick and motif fields. -/
+theorem demandSliceCosts {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag]
+ [AddCommGroup L] [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+ [DecidableEq V] [DecidableEq Tag] [DecidableEq L] (P : PackingData V H Tag L d c)
+ (number : P.BundleNumbering) (order : P.ThickNumbering) (width : Arc V H Tag L d c → ℕ) :
+ let old := fun b ↦ orderedWidths (order b) (fun s ↦ width s.1.1)
+ let new := fun b ↦ orderedWidths (number b) (fun t ↦ P.abWidth number width t.1)
+ ∀ input : ∀ b, SliceInput w (old b) (new b),
+ SliceCosts old new input (2^c*d/4) (pieceCount d c) := by
+ intro old new input
+ apply sliceSites <;> intro b <;> simp [old, new, orderedWidths]
+
+/-- Subdivision slice invocation for every surviving role edge in the selected template. -/
+theorem subdivisionSliceCosts {ι : Type*} [Fintype ι] (width : ι → ℕ) (subdiv : Fin 4 → ℕ)
+ (role : ι → Fin 4) :
+ let old := fun i ↦ [width i]
+ let new := fun i ↦ List.ofFn (splitWidth (width i) (subdiv (role i)))
+ ∀ input : ∀ i, SliceInput w (old i) (new i),
+ SliceCosts old new input 1 (∑ t, subdiv t) := by
+ intro old new input
+ apply sliceSites
+ · simp [old]
+ · intro i
+ simpa [new] using
+ (Finset.single_le_sum (fun t _ ↦ Nat.zero_le (subdiv t)) (Finset.mem_univ (role i)))
+
+/-- A refresh bundle concatenates its original slot widths into a single external word. -/
+theorem refreshSliceCosts {ι : Type*} [Fintype ι] {d : ℕ} (width : ι → Fin d → ℕ) :
+ let old := fun i ↦ List.ofFn (width i)
+ let new := fun i ↦ [∑ k, width i k]
+ ∀ input : ∀ i, SliceInput w (old i) (new i), SliceCosts old new input d 1 := by
+ intro old new input
+ apply sliceSites <;> intro i <;> simp [old, new]
+
+/-- From the actual chosen placement, allocate exactly one bounded row per packed site and
+run the native preimage scan. There are `2^c*d` entries in every row, for either layout. -/
+theorem placementPreimages {V H Tag L : Type} {d c A B : ℕ}
+ [AddCommGroup Tag] [AddCommGroup L] [Finite V] [Finite H] [Finite Tag] [Finite L]
+ (P : PackingData V H Tag L d c)
+ (layout : Bool) (hc : 0 < c) (old : Position V H Tag L c ≃ Fin A) (new : Site V Tag L ≃ Fin B)
+ (p : Fin 6 → Word w) (regions : RowRegions p) (hA : (p 0).val = A) (hB : (p 2).val = B)
+ (cap : (p 4).val = 2 ^ c * d) (mem : Memory w)
+ (owners : ∀ i : Word w, i < p 0 → ownerAt p mem i = encodedPlacement old new
+ (P.placement layout) i)
+ (zero : ∀ i : Word w, i < p 2 → mem (countAt p i).val = 0) :
+ let place := encodedPlacement old new (P.placement layout) (w := w)
+ let M := (PrimedStackRAM.template collectPreimage 3).instantiate w p
+ ∃ rs, runSegment M.program 23 (some 0) mem (List.replicate A []) = some rs ∧
+ PreimagesAt p place (after mem (eventLog rs)) A ∧
+ rs.length = B * (2^c*d) ∧ RAMBuckets.cost Report.probes rs = B * (5*(2^c*d)) ∧
+ (∀ r ∈ rs, r.events.length + 1 = 23) ∧
+ (p 0).val + (p 2).val + (p 2).val * (p 4).val = B * (1+2*(2^c*d)) := by
+ classical
+ let := Fintype.ofFinite V
+ let := Fintype.ofFinite H
+ let := Fintype.ofFinite Tag
+ let := Fintype.ofFinite L
+ intro place M
+ have ha : A ≤ 2^w := hA ▸ (p 0).isLt.le
+ have hb : B ≤ 2^w := hB ▸ (p 2).isLt.le
+ have hsize : A = B*(2^c*d) := by
+ have oldCard := Fintype.card_congr old
+ have newCard := Fintype.card_congr new
+ rw [Fintype.card_fin] at oldCard newCard
+ rw [← oldCard, Fintype.card_congr (Equiv.sigmaFiberEquiv (P.placement layout)).symm,
+ Fintype.card_sigma]
+ simp only [P.card_placement hc layout, Finset.sum_const, Finset.card_univ, newCard,
+ Nat.nsmul_eq_mul]
+ have legal (i : Word w) (hi : i < p 0) : place i < p 2 := by
+ let j : Fin A := ⟨i.val, hA ▸ hi⟩
+ have e : Fin.ofNat (2^w) j.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt)
+ change (encodedPlacement _ _ _ i).val < (p 2).val
+ rw [← e, encodedPlacement_eq old new _ ha hb j, hB]
+ exact (new _).isLt
+ have capacity (u : Word w) (hu : u < p 2) : (preimagePrefix place u (p 0).val).length ≤
+ (p 4).val := by
+ let j : Fin B := ⟨u.val, hB ▸ hu⟩
+ obtain ⟨s, hs⟩ := new.surjective j
+ have e : Fin.ofNat (2^w) (new s).val = u := hs ▸ Fin.ext (Nat.mod_eq_of_lt u.isLt)
+ rw [hA, ← e, encodedPlacement_rowLength old new _ ha hb s, P.card_placement hc layout, cap]
+ have start : PreimagesAt p place mem 0 :=
+ ⟨owners, fun u hu ↦ by simp [preimagePrefix, rowRepresents, zero u hu]⟩
+ obtain ⟨rs, hr, done, hlen, hwork⟩ := collectPreimages_run regions legal capacity start A
+ (by simp [hA])
+ refine ⟨rs, hr, (by simpa using done), hlen.trans hsize, ?_, fun r h ↦ by rw [(hwork r h).1], ?_⟩
+ · change RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = _
+ rw [preimagePass_cost (fun r h ↦ (hwork r h).2), hlen, hsize]
+ ring
+ · rw [hA, hB, cap, hsize]
+ ring
+
+/-- Scratch and immutable source arrays for the four ordered slot passes. The genuine
+region includes every mixed-radix candidate, including subdivision and thick-wire holes. -/
+theorem orderedSlotAllocation (N J lanes d c pad deg : ℕ) (subdiv : Fin 4 → ℕ) :
+ let sites := N*(J*lanes)
+ let keys := 4*d*(2^c*d)*(∑ t, subdiv t)
+ let A := Slots.RecordCount N J lanes d c pad subdiv * 2
+ let B := sites*2
+ A + (B+A) + (B+A)*deg + A =
+ sites * (6*(keys+pad) + 2 + (2+2*(keys+pad))*deg) ∧
+ 4*(Slots.oldBaseArcCount N J d c * lanes) + sites + 12 =
+ sites * (4*d*(2^c*d)+1) + 12 := by
+ dsimp only [Slots.RecordCount, Slots.keyCount, Slots.oldBaseArcCount]
+ constructor <;> ring
+
+private theorem instruction_total (rs : List (Report w)) (cap : ℕ)
+ (h : ∀ r ∈ rs, r.events.length + 1 = cap) :
+ (rs.map fun r ↦ r.events.length + 1).sum = rs.length * cap := by
+ induction rs with
+ | nil => simp
+ | cons r rs ih =>
+ rw [List.map_cons, List.sum_cons, h r (by simp), ih (fun q hq ↦ h q (by simp [hq])),
+ List.length_cons, Nat.succ_mul, Nat.add_comm]
+
+open scoped Classical in
+open PackingData SlotSchedule PrimedStackRAM in
+/-- Costs on the actual ordered directory. The candidate count includes holes and the
+two sides of each genuine and cyclic padding arc. The scatter visits only the real rows. -/
+theorem orderedSlotRun {V H Tag L : Type} {N J lanes d c pad base : ℕ}
+ [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+ [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] (P : PackingData V H Tag L d c)
+ (subdiv : Fin 4 → ℕ)
+ (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (laneOrder : L ≃ Fin lanes)
+ (layout : Bool) (hc : 2 ≤ c) (g : Fin 8 → Word w) (p : Fin 3 → Word w) (mem : Memory w) :
+ let sites := N*(J*lanes)
+ let deg := survivingDegree d c subdiv + pad
+ let D := slotDirectory P subdiv vertices tags laneOrder layout (pad := pad)
+ let G := (Slots.keyCount N J d c subdiv * lanes)*2
+ let H₀ := (sites*pad)*2
+ let A := Slots.RecordCount N J lanes d c pad subdiv * 2
+ let B := sites*2
+ let rows := base+A+(B+A)
+ let inverse := rows+(B+A)*deg
+ let U := 4*d*(2^c*d)*(∑ t, subdiv t)
+ ∀ (_ : OwnerInput D g p mem base G H₀), 0 < deg → deg < 2^w → inverse+A < 2^w →
+ (∀ u : Word w, u.val < B+A → mem (base+A+u.val) = 0) →
+ ∃ gs ds fs ss,
+ let m₁ := after mem (eventLog gs)
+ let m₂ := after m₁ (eventLog ds)
+ let m₃ := after m₂ (eventLog fs)
+ let all := gs ++ ds ++ fs ++ ss
+ runSegment ((template SlotOwners.genuine 0).instantiate w g).program 49 (some 0) mem
+ (List.replicate G []) = some gs ∧
+ runSegment ((template SlotOwners.dummy 0).instantiate w p).program 20 (some 0) m₁
+ (List.replicate H₀ []) = some ds ∧
+ runSegment ((template collectPreimage 3).instantiate w (parameters w base A B deg)).program
+ 23 (some 0) m₂ (List.replicate A []) = some fs ∧
+ runSegment ((template SlotScatter.visit 0).instantiate w
+ (scatterParameters w base A B deg)).program
+ 10 (some 0) m₃ (List.replicate (B*deg) []) = some ss ∧
+ Tables D deg rows inverse (slotDirectory_degree P subdiv vertices tags laneOrder hc layout)
+ (after m₃ (eventLog ss)) ∧
+ all.length = sites * (4*(U+pad)+2*deg) ∧
+ RAMBuckets.cost Report.probes all = sites * (22*U+16*pad+6*deg) ∧
+ (all.map fun r ↦ r.events.length+1).sum = sites * (144*U+86*pad+20*deg) ∧
+ ∀ r ∈ all, r.events.length+1 ≤ 49 := by
+ intro sites deg D G H₀ A B rows inverse U input hdeg hdw hfit zero
+ obtain ⟨gs,ds,fs,ss,hg,hd,hf,hs,ht,_,_,_,_,_,cost,wg,wd,wf,ws⟩ :=
+ SlotSchedule.run D g p mem input hdeg hdw
+ (slotDirectory_degree P subdiv vertices tags laneOrder hc layout) hfit zero
+ have ng : gs.length = G := (run_length hg).trans (List.length_replicate ..)
+ have nd : ds.length = H₀ := (run_length hd).trans (List.length_replicate ..)
+ have nf : fs.length = A := (run_length hf).trans (List.length_replicate ..)
+ have ns : ss.length = B*deg := (run_length hs).trans (List.length_replicate ..)
+ have hG : G = sites*(2*U) := by dsimp [G, sites, U, Slots.keyCount]; ring
+ have hH : H₀ = sites*(2*pad) := by dsimp [H₀]; ring
+ have hA : A = sites*(2*(U+pad)) := by dsimp [A,sites,U,Slots.RecordCount,Slots.keyCount]; ring
+ refine ⟨gs,ds,fs,ss,hg,hd,hf,hs,ht,?_,?_,?_,?_⟩
+ · simp only [List.length_append, ng, nd, nf, ns, hG, hH, hA, B]
+ ring
+ · change RAMBuckets.cost Report.probes _ = _ at cost
+ rw [cost]
+ change 6*G+3*H₀+5*A+3*(B*deg) = _
+ rw [hG,hH,hA]
+ dsimp [B]; ring
+ · simp only [List.map_append,List.sum_append]
+ rw [instruction_total gs 49 (fun r h ↦ by rw [wg r h]),
+ instruction_total ds 20 (fun r h ↦ by rw [wd r h]),
+ instruction_total fs 23 (fun r h ↦ by rw [wf r h]),
+ instruction_total ss 10 (fun r h ↦ by rw [ws r h]), ng, nd, nf, ns, hG, hH, hA]
+ dsimp [B]; ring
+ · intro r hr
+ simp only [List.mem_append] at hr
+ rcases hr with ((h|h)|h)|h
+ · rw [wg r h]
+ · rw [wd r h]; decide
+ · rw [wf r h]; decide
+ · rw [ws r h]; decide
+
+/-- Accumulate the event counts of each successful call, including guarded workers
+which reject invalid addresses. -/
+private theorem checked_scan {C : Type*} {P : BurstRAM.Program w C} {fuel steps probes ticks : ℕ}
+ (one : ∀ m i r, execute P fuel (P.start i) m [] = some r →
+ r.events.length = ticks ∧ r.probes = probes)
+ {s : Option (Word w)} {m : Memory w} {rs : List (Report w)}
+ (hr : runSegment P fuel s m (List.replicate steps []) = some rs) :
+ rs.length = steps ∧ RAMBuckets.cost Report.probes rs = (1+probes)*steps ∧
+ (rs.map fun r ↦ r.events.length+1).sum = (ticks+1)*steps ∧
+ ∀ r ∈ rs, r.events.length = ticks := by
+ induction steps generalizing s m rs with
+ | zero =>
+ have h : rs = [] := by simpa [runSegment] using hr.symm
+ simp [h]
+ | succ n ih =>
+ cases s with
+ | none => simp [List.replicate_succ, runSegment] at hr
+ | some s =>
+ rw [List.replicate_succ, runSegment] at hr
+ cases h : execute P fuel (P.start s) m [] with
+ | none => rw [h] at hr; contradiction
+ | some r =>
+ rw [h] at hr
+ obtain ⟨tail, htail, rfl⟩ := Option.map_eq_some_iff.mp hr
+ obtain ⟨hl, hc, hi, hh⟩ := ih htail
+ obtain ⟨ht, hp⟩ := one _ _ _ h
+ refine ⟨by simp [hl], ?_, ?_, fun rep h ↦ ?_⟩
+ · rw [RAMBuckets.cost, hp, hc, Nat.mul_succ]; omega
+ · rw [List.map_cons, List.sum_cons, ht, hi, Nat.mul_succ]; omega
+ · rcases List.mem_cons.mp h with rfl | h
+ · exact ht
+ · exact hh _ h
+
+/-- Raw report statistics of a deterministic worker with fixed per-call counts. -/
+theorem fixedScanCounts {C : Type*} {P : BurstRAM.Program w C} {fuel steps probes ticks : ℕ}
+ (ev : Memory w → Word w → List (Event w))
+ (hn : ∀ m i, execute P fuel (P.start i) m [] = some ⟨ev m i, some (i + 1)⟩)
+ (he : ∀ m i, (ev m i).length = ticks ∧ countProbes (ev m i) = probes)
+ {s : Word w} {m : Memory w} {rs : List (Report w)}
+ (hr : runSegment P fuel (some s) m (List.replicate steps []) = some rs) :
+ rs.length = steps ∧ RAMBuckets.cost Report.probes rs = (1+probes)*steps ∧
+ (rs.map fun r ↦ r.events.length+1).sum = (ticks+1)*steps ∧
+ ∀ r ∈ rs, r.events.length = ticks := by
+ apply checked_scan _ hr
+ intro mem i r h
+ rw [hn mem i] at h
+ cases h
+ exact he mem i
+
+open PrimedStackRAM in
+private theorem preimage_scan_cost {p : Fin 6 → Word w} {m : Memory w} {steps : ℕ}
+ {rs : List (Report w)}
+ (hr : runSegment ((template collectPreimage 3).instantiate w p).program 23
+ (some 0) m (List.replicate steps []) = some rs) :
+ RAMBuckets.cost Report.probes rs = 5*steps := by
+ refine (checked_scan (probes := 4) (ticks := 22) ?_ hr).2.1
+ intro mem i rep he
+ by_cases h : i < p 0 ∧ ownerAt p mem i < p 2 ∧ mem (countAt p (ownerAt p mem i)).val < p 4
+ · rw [collectPreimage_native p mem i h.1 h.2.1 h.2.2] at he
+ cases he
+ exact collectEvents_work p mem i
+ · change execute ((template collectPreimage 3).instantiate w p).program (1+collectPreimage.length)
+ ⟨_, i, fun _ ↦ 0, fun _ ↦ 0⟩ mem [] = _ at he
+ rw [execute_template, run_eq_trace, collectPreimage_invalid p i _ mem h] at he
+ cases he
+
+open PortRefresh.NewSlots in
+/-- Instructions of a refreshed incidence worker, including its return. -/
+def refreshSlotInstructions : Kind → ℕ
+ | .external => 22
+ | .expander => 46
+ | .padding => 36
+
+open PortRefresh PortRefresh.NewSlots in
+/-- Raw costs of successive physical incidence-column scans. -/
+theorem refreshWrites {d sites : ℕ} (kind : Fin d → Kind) (pub : Fin d → Public w)
+ {ks : List (Fin d)} {m : Memory w} {rs : List (Report w)}
+ (runs : AllSlots.Runs kind pub sites ks m rs) :
+ rs.length = ks.length*sites ∧
+ RAMBuckets.cost Report.probes rs = (ks.map fun k ↦ (1+probeCount (kind k))*sites).sum ∧
+ (rs.map fun r ↦ r.events.length+1).sum =
+ (ks.map fun k ↦ refreshSlotInstructions (kind k)*sites).sum ∧
+ ∀ r ∈ rs, r.events.length+1 ≤ 46 := by
+ induction runs with
+ | nil => simp
+ | cons k head tail ih =>
+ have one := fixedScanCounts (events (kind k) (pub k)) (native (kind k) (pub k))
+ (events_work (kind k) (pub k)) head
+ obtain ⟨hn,hc,hi,hcap⟩ := one
+ have cost := ih.2.1
+ refine ⟨?_, ?_, ?_, ?_⟩
+ · rw [List.length_append, hn, ih.1, List.length_cons, Nat.succ_mul]; omega
+ · rw [RAMBuckets.cost_append, hc, cost, List.map_cons, List.sum_cons]
+ cases kind k <;> rfl
+ · rw [List.map_append, List.sum_append, hi, ih.2.2.1, List.map_cons, List.sum_cons]
+ cases kind k <;> rfl
+ · intro r hr
+ rcases List.mem_append.mp hr with h | h
+ · rw [hcap _ h]
+ cases kind k <;> decide
+ · exact ih.2.2.2 _ h
+
+open PortRefresh.NewSlots Compression.DegreeRefresh in
+private theorem slot_instruction_sum {dH outDegree : ℕ} (hd : dH + 1 ≤ outDegree) (sites : ℕ) :
+ ∑ k : Fin outDegree, refreshSlotInstructions (kindOf ((refreshSlots hd).symm k))*sites =
+ (22+46*dH+36*(outDegree-(dH+1)))*sites := by
+ rw [← (refreshSlots hd).sum_comp]
+ simp only [Equiv.symm_apply_apply, Fintype.sum_sum_type, kindOf, refreshSlotInstructions,
+ Finset.sum_const, Finset.card_univ, Fintype.card_fin, Nat.nsmul_eq_mul]
+ ring
+
+open PortRefresh PortRefresh.NewSlots Compression.DegreeRefresh PrimedStackRAM in
+/-- The three external refresh passes followed by all actual incidence writebacks.
+These totals apply to the chronologically joined report lists from `external_phases` and
+`all_slots`, for any selected expander supplies and any widths. -/
+theorem refreshPhaseCounts {sites degree dH outDegree : ℕ} (hd : dH + 1 ≤ outDegree)
+ (g : Fin 4 → Word w) (b e : Fin 8 → Word w) (out : Fin outDegree → Public w)
+ (m : Memory w) (gs ds es os : List (Report w))
+ (hg : runSegment ((template RefreshGather.gather 0).instantiate w g).program 24 (some 0) m
+ (List.replicate (sites * degree) []) = some gs)
+ (hb : runSegment ((template BundleDirectory.visit 0).instantiate w b).program 28 (some 0)
+ (after m (eventLog gs)) (List.replicate sites []) = some ds)
+ (he : runSegment ((template RefreshRAM.visit 0).instantiate w e).program 33 (some 0)
+ (after (after m (eventLog gs)) (eventLog ds)) (List.replicate (sites * degree) []) = some es)
+ (ho : AllSlots.Runs (fun k ↦ kindOf ((refreshSlots hd).symm k)) out sites
+ (List.finRange outDegree) (after (after (after m (eventLog gs)) (eventLog ds))
+ (eventLog es)) os) :
+ let all := gs ++ ds ++ es ++ os
+ let pad := outDegree-(dH+1)
+ all.length = sites*(2*degree+1+outDegree) ∧
+ RAMBuckets.cost Report.probes all = sites*(12*degree + 12 + 7*dH + 4*pad) ∧
+ (all.map fun r ↦ r.events.length+1).sum = sites*(57*degree + 50 + 46*dH + 36*pad) ∧
+ ∀ r ∈ all, r.events.length+1 ≤ 46 := by
+ intro all pad
+ have rg := fixedScanCounts (RefreshGather.events g) (RefreshGather.gather_native g)
+ (RefreshGather.gather_work g) hg
+ have rd := fixedScanCounts (BundleDirectory.events b) (BundleDirectory.visit_native b)
+ (BundleDirectory.events_work b) hb
+ have re := fixedScanCounts (RefreshRAM.events e) (RefreshRAM.visit_native e)
+ (RefreshRAM.events_work e) he
+ have ro := refreshWrites _ _ ho
+ have workO : RAMBuckets.cost Report.probes os = (6+7*dH+4*pad)*sites := by
+ rw [ro.2.1, ← List.ofFn_id, List.map_ofFn, List.sum_ofFn]
+ exact slot_cost hd sites
+ have ticksO : (os.map fun r ↦ r.events.length+1).sum = (22+46*dH+36*pad)*sites := by
+ rw [ro.2.2.1, ← List.ofFn_id, List.map_ofFn, List.sum_ofFn]
+ exact slot_instruction_sum hd sites
+ refine ⟨?_, ?_, ?_, ?_⟩
+ · simp only [all, List.length_append, rg.1, rd.1, re.1, ro.1, List.length_finRange]; ring
+ · simp only [all, RAMBuckets.cost_append, rg.2.1, rd.2.1, re.2.1, workO]; ring
+ · simp only [all, List.map_append, List.sum_append, rg.2.2.1, rd.2.2.1, re.2.2.1, ticksO]; ring
+ · intro r hr
+ simp only [all, List.mem_append] at hr
+ rcases hr with ((h|h)|h)|h
+ · rw [rg.2.2.2 _ h]; decide
+ · rw [rd.2.2.2 _ h]; decide
+ · rw [re.2.2.2 _ h]; decide
+ · exact ro.2.2.2 _ h
+
+/-- The two preparation scans write the selected role offsets and the cyclic successor of
+every packed site. The four subdivision constants belong to the fixed input template. -/
+theorem slotOwnerPreparation {C D : Type*} {sites : ℕ} {p : BurstRAM.Program w C}
+ {q : BurstRAM.Program w D} {roleBase nextBase : Word w}
+ {rv nv : ℕ → Word w} {m : Memory w} {rs ns : List (Report w)}
+ (role : SlotOwners.FilledRun p 26 1 25 8 roleBase rv m rs)
+ (next : SlotOwners.FilledRun q 19 1 18 sites nextBase nv (after m (eventLog rs)) ns) :
+ (rs++ns).length = 8+sites ∧ RAMBuckets.cost Report.probes (rs++ns) = 16+2*sites ∧
+ ((rs++ns).map fun r ↦ r.events.length+1).sum = 208+19*sites ∧
+ ∀ r ∈ rs++ns, r.events.length+1 ≤ 26 := by
+ refine ⟨by rw [List.length_append, role.length, next.length],
+ by rw [RAMBuckets.cost_append, role.cost, next.cost], ?_, ?_⟩
+ · rw [List.map_append, List.sum_append,
+ instruction_total rs 26 (fun r hr ↦ by rw [(role.calls r hr).2]),
+ instruction_total ns 19 (fun r hr ↦ by rw [(next.calls r hr).2]), role.length, next.length]
+ ring
+ · intro r hr
+ rcases List.mem_append.mp hr with h | h
+ · rw [(role.calls r h).2]
+ · rw [(next.calls r h).2]; decide
+
+/-- Exact charged work of all five endpoint passes from the native segment executions
+alone. A successful guarded append checks its owner and capacity before its two writes. -/
+theorem slotLevelExactCost {s : SlotLevel.Shape} {h : SlotLevel.Heads} {m : Memory w}
+ {r : SlotLevel.Reports w} (native : r.Native s h m) :
+ RAMBuckets.cost Report.probes r.all =
+ 6*SlotLevel.genuineCount s + 3*SlotLevel.dummyCount s + 5*SlotLevel.fields s +
+ 3*(SlotLevel.owners s*s.newDegree) + 5*SlotLevel.baseArcs s := by
+ obtain ⟨rg, rd, rf, ri, rb⟩ := native
+ have g := fixedScanCounts _ (SlotOwners.genuine_native _) (SlotOwners.genuine_work _) rg
+ have d := fixedScanCounts _ (SlotOwners.dummy_native _) (SlotOwners.dummy_work _) rd
+ have f := preimage_scan_cost rf
+ let ip := SlotLevel.bank s h w .invertFields
+ have i := fixedScanCounts (probes := 2) (ticks := 9)
+ (fun mem x ↦ SlotScatter.events ip x (mem (ip 0+x).val)) (SlotScatter.visit_native ip)
+ (fun _ _ ↦ ⟨rfl,rfl⟩) ri
+ have b := fixedScanCounts _ (SlotBaseScan.native _)
+ (fun mem x ↦ (SlotBaseScan.events_work _ mem x).symm) rb
+ simp only [SlotLevel.Reports.all, RAMBuckets.cost_append, g.2.1, d.2.1, f, i.2.1, b.2.1]
+
+/-- The five selected slot passes from `SlotLevel.run_selected`, including the lane-zero
+base matching writeback. All counts and the highest allocated address are linear in the
+number of packed sites, independently of the wire widths. -/
+theorem slotLevelBounds (s : SlotLevel.Shape) (h : SlotLevel.Heads) (m : Memory w)
+ (r : SlotLevel.Reports w) (hnative : r.Native s h m) (hlanes : 1 ≤ s.lanes)
+ (hwork : RAMBuckets.cost Report.probes r.all =
+ 6 * SlotLevel.genuineCount s + 3 * SlotLevel.dummyCount s + 5 * SlotLevel.fields s +
+ 3 * (SlotLevel.owners s * s.newDegree) + 5 * SlotLevel.baseArcs s) :
+ let P := SlotLevel.sites s
+ let pad := SlotLevel.pad s
+ let U := 4*s.oldDegree*(2^s.colors*s.oldDegree)*(∑ t, s.subdivisions t)
+ r.all.length ≤ P*(4*(U+pad) + 3*s.newDegree) ∧
+ RAMBuckets.cost Report.probes r.all ≤ P*(22*U+16*pad+11*s.newDegree) ∧
+ (∀ rep ∈ r.all, rep.events.length+1 ≤ 49) ∧
+ SlotLevel.stopAddress s h ≤ h.scratch +
+ P*(6*(U+pad) + 2 + (4+2*(U+pad))*s.newDegree) := by
+ intro P pad U
+ have hn : s.bases*s.tags ≤ P := by
+ change _ ≤ s.bases*(s.tags*s.lanes)
+ rw [← Nat.mul_assoc]; exact Nat.le_mul_of_pos_right _ hlanes
+ have hg : SlotLevel.genuineCount s = P*(2*U) := by
+ dsimp [SlotLevel.genuineCount, P, SlotLevel.sites, U, Slots.keyCount]; ring
+ have hd : SlotLevel.dummyCount s = P*(2*pad) := by
+ dsimp [SlotLevel.dummyCount, P, pad]; ring
+ have hf : SlotLevel.fields s = P*(2*(U+pad)) := by
+ rw [← SlotLevel.counts_add, hg, hd]; ring
+ have ho : SlotLevel.owners s = 2*P := Nat.mul_comm ..
+ have hb : SlotLevel.baseArcs s ≤ P*s.newDegree := Nat.mul_le_mul_right _ hn
+ obtain ⟨rg,rd,rf,ri,rb⟩ := hnative
+ have lens := fun {C : Type} {p : BurstRAM.Program w C} {fuel st mem n} {rs : List (Report w)}
+ (hr : runSegment p fuel st mem (List.replicate n []) = some rs) ↦
+ (run_length hr).trans (List.length_replicate ..)
+ refine ⟨?_, ?_, ?_, ?_⟩
+ · simp only [SlotLevel.Reports.all, List.length_append, lens rg, lens rd, lens rf, lens ri,
+ lens rb,
+ hg, hd, hf, ho]
+ linarith only [hb]
+ · rw [hwork,hg,hd,hf,ho]
+ linarith only [hb]
+ · intro rep hr
+ simp only [SlotLevel.Reports.all,List.mem_append] at hr
+ rcases hr with (((hh|hh)|hh)|hh)|hh
+ · exact run_cap rg _ hh
+ · exact (run_cap rd _ hh).trans (by decide)
+ · exact (run_cap rf _ hh).trans (by decide)
+ · exact (run_cap ri _ hh).trans (by decide)
+ · exact (run_cap rb _ hh).trans (by decide)
+ · dsimp only [SlotLevel.stopAddress, SlotLevel.shiftsHead, SlotLevel.targetsHead,
+ SlotLevel.inverseHead, SlotLevel.rowsHead]
+ rw [hf, ho]; linarith only [hb]
+
+/-- Gathering one complete classified row and ranking each of its actual pivots. The result
+includes each rank call's input memory, returned rank, and write to its physical destination.
+For a thick row use `2^c*d/4` pivots. For a motif row use `pieceCount d c`. -/
+theorem gatheredRankCosts {row arcs widthBase : ℕ} (g : Fin 3 → Word w) (m : Memory w)
+ (gs : List (Report w)) (hg : BundleGather.Gathered g row arcs widthBase m gs)
+ (pub : Fin row → Fin 2 → Word w) (mem : Fin row → Memory w)
+ (pivot rank : Fin row → Word w) (h : ∀ i, BundleRank.RankWrite row (pub i) (mem i)
+ (pivot i) (rank i)) :
+ ∃ log : Fin row → List (Event w),
+ (∀ i, Slots.rankExecution row (pub i) (pivot i) (mem i) (log i) (rank i) ∧
+ after (mem i) (log i) = writeMemory (mem i) (pub i 1) (rank i)) ∧
+ gs.length + row = 2*row ∧
+ RAMBuckets.cost Report.probes gs + ∑ i, (1+countProbes (log i)) = row*(row+6) ∧
+ (gs.map fun r ↦ r.events.length+1).sum + ∑ i, ((log i).length+1) = row*(6*row+19) ∧
+ ∀ i, (log i).length+1 = 6*row+6 := by
+ classical
+ choose log hex hwrite hp ht using h
+ refine ⟨log, fun i ↦ ⟨hex i,hwrite i⟩, by rw [hg.run.length]; omega, ?_, ?_, ht⟩
+ · simp only [hg.run.cost, hp, Finset.sum_const, Finset.card_univ, Fintype.card_fin,
+ Nat.nsmul_eq_mul]
+ ring
+ · rw [instruction_total gs 13 (fun r h ↦ by rw [(hg.run.calls r h).2]), hg.run.length]
+ simp only [ht, Finset.sum_const, Finset.card_univ, Fintype.card_fin, Nat.nsmul_eq_mul]
+ ring
+
+/-- The concrete input and gather trace for one row of thick-wire or motif keys. The rank
+entry points use the physical source, destination, pivot and input memory of each call. -/
+structure RankInput (w row : ℕ) where
+ /-- Public heads of the ID row, absolute key column, and output key row used by the gather
+ worker. -/
+ gatherBank : Fin 3 → Word w
+ /-- Number of absolute old arc widths covered by the gather's preservation guarantee. -/
+ arcCount : ℕ
+ /-- Start of the old arc width column retained during key gathering. -/
+ widthBase : ℕ
+ /-- Memory containing the collected arc IDs and their keys at the start of the gather scan. -/
+ initial : Memory w
+ /-- Reports of the native calls that materialize one row of keys from its absolute arc IDs. -/
+ gatherLog : List (Report w)
+ gathered : BundleGather.Gathered gatherBank row arcCount widthBase initial gatherLog
+ /-- Key-row base and rank destination supplied to each pivot's ranking call. -/
+ rankBank : Fin row → Fin 2 → Word w
+ /-- External memory supplied at the entry to each pivot's ranking call. -/
+ memory : Fin row → Memory w
+ /-- Comparison key supplied to the ranking worker for each row entry. -/
+ pivot : Fin row → Word w
+ /-- Rank word to be written for each pivot, counting the row keys strictly below it. -/
+ rank : Fin row → Word w
+ checked : ∀ i, BundleRank.RankWrite row (rankBank i) (memory i) (pivot i) (rank i)
+
+/-- Actual gather and rank traffic for this row. -/
+def RankInput.traffic {n : ℕ} (job : RankInput w n) (log : Fin n → List (Event w)) : ℕ :=
+ RAMBuckets.cost Report.probes job.gatherLog + ∑ i, (1+countProbes (log i))
+
+/-- Each proposed event log executes the corresponding rank call, leaves the specified rank at
+its destination, and has the exact instruction count. -/
+def RankInput.realizes {n : ℕ} (job : RankInput w n) (log : Fin n → List (Event w)) : Prop :=
+ ∀ i, Slots.rankExecution n (job.rankBank i) (job.pivot i) (job.memory i) (log i) (job.rank i) ∧
+ after (job.memory i) (log i) = writeMemory (job.memory i) (job.rankBank i 1) (job.rank i) ∧
+ (log i).length+1 = 6*n+6
+
+theorem RankInput.gather_instruction_count {n : ℕ} (job : RankInput w n) (r : Report w)
+ (hr : r ∈ job.gatherLog) : r.events.length+1 = 13 := by rw [(job.gathered.run.calls r hr).2]
+
+private theorem RankInput.logs {n : ℕ} (job : RankInput w n) :
+ ∃ log, job.realizes log ∧ job.traffic log = n*(n+6) := by
+ obtain ⟨log, h, _, hc, _, ticks⟩ := gatheredRankCosts job.gatherBank job.initial
+ job.gatherLog job.gathered
+ job.rankBank job.memory job.pivot job.rank job.checked
+ exact ⟨log, fun i ↦ ⟨(h i).1,(h i).2,ticks i⟩, hc⟩
+
+/-- One packed shrinking stage's native local row traffic. There is one thick and one
+motif key row per outgoing port, one demand slice pass per bundle, and one subdivision
+slice pass per role edge of each actual motif. -/
+theorem shrinkLocalTraffic {V H Tag L : Type} {d c : ℕ}
+ [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+ [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] [DecidableEq V] [DecidableEq Tag]
+ [DecidableEq L]
+ (P : PackingData V H Tag L d c) (hc : 2 ≤ c)
+ (number : P.BundleNumbering) (order : P.ThickNumbering) (width : Arc V H Tag L d c → ℕ)
+ (subdiv : Fin 4 → ℕ) (roleWidth : Fin 4 × P.Motif → ℕ)
+ (thickJob : Site V Tag L × Fin d → RankInput w (2 ^ c * d / 4))
+ (motifJob : Site V Tag L × Fin d → RankInput w (PackingData.pieceCount d c)) :
+ let H₀ := 2^c*d/4
+ let Q := PackingData.pieceCount d c
+ let S := ∑ t, subdiv t
+ let old := fun b ↦ orderedWidths (order b) (fun s ↦ width s.1.1)
+ let new := fun b ↦ orderedWidths (number b) (fun t ↦ P.abWidth number width t.1)
+ let divided := fun (i : Fin 4 × P.Motif) ↦ List.ofFn (splitWidth (roleWidth i) (subdiv i.1))
+ ∀ (input : ∀ b, SliceInput w (old b) (new b))
+ (split : ∀ i, SliceInput w [roleWidth i] (divided i)),
+ ∃ (thickLog : Site V Tag L × Fin d → Fin H₀ → List (Event w))
+ (motifLog : Site V Tag L × Fin d → Fin Q → List (Event w))
+ (demand : Site V Tag L × Fin d → SliceSchedule.Passes w)
+ (roles : Fin 4 × P.Motif → SliceSchedule.Passes w),
+ (∀ b, (thickJob b).realizes (thickLog b) ∧ (motifJob b).realizes (motifLog b)) ∧
+ (∀ b, (input b).produces (demand b) ∧ ∀ r ∈ (demand b).all, r.events.length+1 ≤ 38) ∧
+ (∀ i, (split i).produces (roles i) ∧ ∀ r ∈ (roles i).all, r.events.length+1 ≤ 38) ∧
+ (∑ b, (thickJob b).traffic (thickLog b)) + (∑ b, (motifJob b).traffic (motifLog b)) +
+ (∑ b, RAMBuckets.cost Report.probes (demand b).all) +
+ (∑ i, RAMBuckets.cost Report.probes (roles i).all) ≤
+ Fintype.card (Site V Tag L) * (d*(H₀*(H₀+6) + Q*(Q+6) + 4 + 7*(H₀+Q) + 16*(H₀*Q) +
+ 4*Q*(4+7*(1+S)+16*S))) := by
+ classical
+ intro H₀ Q S old new divided input split
+ choose tl ht ct using fun b ↦ (thickJob b).logs
+ choose ml hm cm using fun b ↦ (motifJob b).logs
+ obtain ⟨ds, hs, hdCap, _, cs, _⟩ := demandSliceCosts P number order width input
+ obtain ⟨rs, hr, hrCap, _, cr, _⟩ := subdivisionSliceCosts roleWidth subdiv Prod.fst split
+ have countM : Fintype.card P.Motif = Fintype.card (Site V Tag L) * d * Q := by
+ rw [Fintype.card_congr (Equiv.sigmaFiberEquiv P.bundle).symm, Fintype.card_sigma]
+ simp only [P.card_motifs_bundle hc, Finset.sum_const, Finset.card_univ, Fintype.card_prod,
+ Fintype.card_fin, Nat.nsmul_eq_mul, Q, PackingData.pieceCount]
+ refine ⟨tl,ml,ds,rs,fun b ↦ ⟨ht b,hm b⟩,fun b ↦ ⟨hs b,hdCap b⟩,fun i ↦ ⟨hr i,hrCap i⟩,?_⟩
+ simp only [ct,cm,Finset.sum_const, Finset.card_univ, Fintype.card_prod, Fintype.card_fin,
+ Nat.nsmul_eq_mul]
+ simp only [Fintype.card_prod,Fintype.card_fin,countM] at cs cr
+ dsimp only [H₀,Q,S] at cs cr ⊢
+ linarith only [cs, cr]
+
+/-- A concrete input memory and the resulting reports for a reset-cursor scan. -/
+structure NativeScan {C : Type*} (P : BurstRAM.Program w C) (fuel calls : ℕ) where
+ /-- External memory at the start of this worker's deterministic scan from cursor zero. -/
+ initial : Memory w
+ /-- Reports returned by executing the specified number of scan calls, each with an empty
+ choice stream. -/
+ reports : List (Report w)
+ executed : runSegment P fuel (some 0) initial (List.replicate calls []) = some reports
+
+open PrimedStackRAM in
+/-- The placement, preimage, classification, role-record and auxiliary-table scans feeding
+the selected slot workers. Each trace starts from the memory at its actual entry point. -/
+structure ShrinkScans (w : ℕ) (s : SlotLevel.Shape) where
+ /-- Public parameters for computing placement owners, thickness flags, assigned ports, and
+ targets at old positions. -/
+ placementBank : Fin 14 → Word w
+ /-- Public parameters for appending old positions to the child rows of their packed owners. -/
+ preimageBank : Fin 6 → Word w
+ /-- Public parameters for classifying old ports by bundle and computing their sorting keys. -/
+ classifierBank : Fin 11 → Word w
+ /-- Public parameters for collecting absolute old port IDs into thick-wire and motif bucket
+ rows. -/
+ bundleBank : Fin 6 → Word w
+ /-- Public radices and table addresses for writing three role sites and a CD flag for each
+ old arc. -/
+ demandBank : Fin 11 → Word w
+ /-- Layout selector and destination head for publishing the eight endpoint role offsets. -/
+ roleBank : Fin 2 → Word w
+ /-- Lane and tag counts and destination head for the cyclic site successor scan. -/
+ successorBank : Fin 3 → Word w
+ /-- Native scan computing a shrinking placement record for each old position. -/
+ placement : NativeScan ((template ShrinkRAM.visit 0).instantiate w placementBank).program
+ 65 (SlotLevel.sites s*(2^s.colors*s.oldDegree))
+ /-- Native scan appending each old position to the preimage row of its packed owner. -/
+ preimages : NativeScan ((template collectPreimage 3).instantiate w preimageBank).program
+ 23 (SlotLevel.sites s*(2^s.colors*s.oldDegree))
+ /-- Native scan assigning each old outgoing port a bundle bucket and a sorting key. -/
+ classifier : NativeScan ((template BundleRAM.visit 0).instantiate w classifierBank).program
+ (1+BundleRAM.visit.length) (SlotLevel.sites s*(2^s.colors*s.oldDegree)*s.oldDegree)
+ /-- Native scan collecting the classified old port IDs into the corresponding bundle rows. -/
+ bundles : NativeScan ((template collectPreimage 3).instantiate w bundleBank).program
+ 23 (SlotLevel.sites s*(2^s.colors*s.oldDegree)*s.oldDegree)
+ /-- Native scan visiting old outgoing ports and writing each role-site and CD record at its
+ absolute old arc ID. -/
+ demandRoles : NativeScan ((template DemandRAM.visit 0).instantiate w demandBank).program
+ 65 (SlotLevel.sites s*(2^s.colors*s.oldDegree)*s.oldDegree)
+ /-- The eight native calls that publish one role selector for each edge type and side. -/
+ roleOffsets : NativeScan ((template SlotOwners.Aux.roleCode 0).instantiate w
+ roleBank).program 26 8
+ /-- Native scan computing a cyclic tag successor for each packed site. -/
+ successors : NativeScan ((template SlotOwners.Aux.nextCode 0).instantiate w successorBank).program
+ 19 (SlotLevel.sites s)
+
+/-- Concatenate the reports of the seven preparation scans in order for the shrinking phase's
+traffic calculation. -/
+def ShrinkScans.reports {s : SlotLevel.Shape} (r : ShrinkScans w s) : List (Report w) :=
+ r.placement.reports ++ r.preimages.reports ++ r.classifier.reports ++ r.bundles.reports ++
+ r.demandRoles.reports ++ r.roleOffsets.reports ++ r.successors.reports
+
+/-- Combine the physical scans with the row work bounded by `shrinkLocalTraffic`. The
+coefficient involves only the incoming and outgoing degrees, the color count, the
+subdivision template, and the local row coefficient. -/
+theorem shrinkDescriptorTraffic (s : SlotLevel.Shape) (h : SlotLevel.Heads) (m : Memory w)
+ (r : SlotLevel.Reports w) (hnative : r.Native s h m) (hlanes : 1 ≤ s.lanes)
+ (hnonempty : 0 < SlotLevel.sites s) (prep : ShrinkScans w s)
+ (hwork : RAMBuckets.cost Report.probes r.all =
+ 6 * SlotLevel.genuineCount s + 3 * SlotLevel.dummyCount s + 5 * SlotLevel.fields s +
+ 3 * (SlotLevel.owners s * s.newDegree) + 5 * SlotLevel.baseArcs s)
+ {rowWork rowFactor : ℕ} (hrows : rowWork ≤ SlotLevel.sites s * rowFactor) :
+ let P := SlotLevel.sites s
+ let K := 2^s.colors*s.oldDegree
+ let U := 4*s.oldDegree*K*(∑ t, s.subdivisions t)
+ let all := prep.reports ++ r.all
+ RAMBuckets.cost Report.probes all + rowWork ≤ P *
+ (14*K + 25*K*s.oldDegree + 18 + 22*U + 16*SlotLevel.pad s + 11*s.newDegree + rowFactor) ∧
+ ∀ rep ∈ all, rep.events.length+1 ≤ 66 := by
+ intro P K U all
+ have p := fixedScanCounts _ (ShrinkRAM.visit_native prep.placementBank)
+ (ShrinkRAM.visit_work prep.placementBank) prep.placement.executed
+ have pre := preimage_scan_cost prep.preimages.executed
+ have c := fixedScanCounts _ (BundleRAM.visit_native prep.classifierBank)
+ (BundleRAM.events_work prep.classifierBank) prep.classifier.executed
+ have b := preimage_scan_cost prep.bundles.executed
+ have d := fixedScanCounts _ (DemandRAM.visit_native prep.demandBank)
+ (DemandRAM.visit_work prep.demandBank) prep.demandRoles.executed
+ have role := fixedScanCounts (probes := 1) (ticks := 25) _
+ (SlotOwners.Aux.role_native prep.roleBank)
+ (fun _ _ ↦ ⟨rfl,rfl⟩) prep.roleOffsets.executed
+ have suc := fixedScanCounts (probes := 1) (ticks := 18) _
+ (SlotOwners.Aux.next_native prep.successorBank)
+ (fun _ _ ↦ ⟨rfl,rfl⟩) prep.successors.executed
+ obtain ⟨_, hs, hcap, _⟩ := slotLevelBounds s h m r hnative hlanes hwork
+ constructor
+ · simp only [all,ShrinkScans.reports,RAMBuckets.cost_append,p.2.1,pre,c.2.1,b,d.2.1,role.2.1,
+ suc.2.1]
+ dsimp only [P,K,U]
+ linarith only [hrows, hs, hnonempty]
+ · intro rep hm
+ simp only [all,ShrinkScans.reports,List.mem_append] at hm
+ rcases hm with ((((((hh|hh)|hh)|hh)|hh)|hh)|hh)|hh
+ · exact (run_cap prep.placement.executed _ hh).trans (by decide)
+ · exact (run_cap prep.preimages.executed _ hh).trans (by decide)
+ · exact (run_cap prep.classifier.executed _ hh).trans (by decide)
+ · exact (run_cap prep.bundles.executed _ hh).trans (by decide)
+ · exact (run_cap prep.demandRoles.executed _ hh).trans (by decide)
+ · exact (run_cap prep.roleOffsets.executed _ hh).trans (by decide)
+ · exact (run_cap prep.successors.executed _ hh).trans (by decide)
+ · exact (hcap _ hh).trans (by decide)
+
+/-- Coefficient for all row, slot, and slice passes counted above at one selected shrink.
+It uses only the degrees, colors, and four subdivision lengths. -/
+def shrinkTrafficFactor (s : SlotLevel.Shape) : ℕ :=
+ let d := s.oldDegree
+ let K := 2^s.colors*d
+ let H := K/4
+ let Q := PackingData.pieceCount d s.colors
+ let S := ∑ t, s.subdivisions t
+ let U := 4*d*K*S
+ 14*K + 25*K*d + 18 + 22*U + 16*SlotLevel.pad s + 11*s.newDegree +
+ d*(H*(H+6) + Q*(Q+6) + 4 + 7*(H+Q) + 16*(H*Q) + 4*Q*(4+7*(1+S)+16*S))
+
+/-- Total traffic for the native selected slot directory and all its checked bundle rows
+and slice inputs. The numerical premises on the directory are returned by
+`SlotLevel.run_selected`. The number of row invocations is proved from the selected
+packing data. -/
+theorem selectedShrinkTraffic {V H Tag L : Type}
+ [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+ [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] [DecidableEq V] [DecidableEq Tag]
+ [DecidableEq L]
+ (s : SlotLevel.Shape) (h : SlotLevel.Heads) (m : Memory w) (r : SlotLevel.Reports w)
+ (hnative : r.Native s h m) (prep : ShrinkScans w s) (hlanes : 1 ≤ s.lanes)
+ (hnonempty : 0 < SlotLevel.sites s)
+ (hwork : RAMBuckets.cost Report.probes r.all =
+ 6 * SlotLevel.genuineCount s + 3 * SlotLevel.dummyCount s + 5 * SlotLevel.fields s +
+ 3 * (SlotLevel.owners s * s.newDegree) + 5 * SlotLevel.baseArcs s)
+ (P : PackingData V H Tag L s.oldDegree s.colors) (hc : 2 ≤ s.colors)
+ (sites : Site V Tag L ≃ Fin (SlotLevel.sites s)) (number : P.BundleNumbering)
+ (order : P.ThickNumbering) (width : Arc V H Tag L s.oldDegree s.colors → ℕ)
+ (roleWidth : Fin 4 × P.Motif → ℕ)
+ (thickJob : Site V Tag L × Fin s.oldDegree → RankInput w (2 ^ s.colors * s.oldDegree / 4))
+ (motifJob : Site V Tag L × Fin s.oldDegree → RankInput w
+ (PackingData.pieceCount s.oldDegree s.colors)) :
+ let old := fun b ↦ orderedWidths (order b) (fun x ↦ width x.1.1)
+ let new := fun b ↦ orderedWidths (number b) (fun x ↦ P.abWidth number width x.1)
+ let divided := fun (i : Fin 4 × P.Motif) ↦ List.ofFn (splitWidth (roleWidth i)
+ (s.subdivisions i.1))
+ ∀ (input : ∀ b, SliceInput w (old b) (new b)) (split : ∀ i, SliceInput w [roleWidth i]
+ (divided i)),
+ ∃ (tl : Site V Tag L × Fin s.oldDegree → Fin (2^s.colors*s.oldDegree/4) → List (Event w))
+ (ml : Site V Tag L × Fin s.oldDegree → Fin (PackingData.pieceCount s.oldDegree
+ s.colors) → List (Event w))
+ (ds : Site V Tag L × Fin s.oldDegree → SliceSchedule.Passes w) (rs : Fin 4 × P.Motif →
+ SliceSchedule.Passes w),
+ (∀ b, (thickJob b).realizes (tl b) ∧ (motifJob b).realizes (ml b)) ∧
+ (∀ b, (input b).produces (ds b)) ∧ (∀ i, (split i).produces (rs i)) ∧
+ RAMBuckets.cost Report.probes (prep.reports++r.all) +
+ ((∑ b, (thickJob b).traffic (tl b)) + (∑ b, (motifJob b).traffic (ml b)) +
+ (∑ b, RAMBuckets.cost Report.probes (ds b).all) + (∑ i, RAMBuckets.cost Report.probes
+ (rs i).all)) ≤
+ SlotLevel.sites s * shrinkTrafficFactor s := by
+ intro old new divided input split
+ obtain ⟨tl,ml,ds,rs,hrank,hd,hs,hlocal⟩ :=
+ shrinkLocalTraffic P hc number order width s.subdivisions roleWidth thickJob motifJob input
+ split
+ rw [Fintype.card_congr sites, Fintype.card_fin] at hlocal
+ exact ⟨tl,ml,ds,rs,hrank,fun b ↦ (hd b).1,fun i ↦ (hs i).1,
+ (shrinkDescriptorTraffic s h m r hnative hlanes hnonempty prep hwork hlocal).1⟩
+
+end CompressorRecords.PhaseCosts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotPipeline.lean b/lean/OAI/Computability/VPVNP/CompressorSlotPipeline.lean
new file mode 100644
index 0000000000..3ffe5f132e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotPipeline.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.CompressorSlotNetwork
+import OAI.Computability.VPVNP.CompressorSlotOwnerRuns
+import OAI.Computability.VPVNP.CompressorSlotFrames
+
+/-!
+# The four physical passes that construct the next slot matching
+
+Generate the genuine and dummy owner fields in two contiguous portions of
+one directory. Feed that directory to the bounded append pass, then invert
+the real incidence rows. Each pass reads the actual post-memory of its
+predecessor. All four cursor ranges and both address bounds are explicit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotSchedule
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SlotOwners
+
+variable {E : Type*} [Fintype E] {A B w : ℕ} (D : Directory E A B)
+
+/-- The selected input records determine the two portions of the owner array.
+All four genuine inputs and the cyclic successor table precede the scratch
+space allocated at `base`. -/
+structure OwnerInput (g : Fin 8 → Word w) (p : Fin 3 → Word w) (mem : Memory w)
+ (base genuineCount dummyCount : ℕ) : Prop where
+ total : genuineCount+dummyCount=A
+ startGenuine : (g 7).val=base
+ startDummy : (p 2).val=base+genuineCount
+ genuineSources : ∀ i < genuineCount, ∀ a ∈ genuineInputs g mem (Fin.ofNat _ i), a.val < base
+ dummySource : ∀ i < dummyCount, (p 1 + SlotOwners.dummySource p (Fin.ofNat _ i)).val < base
+ genuineValue : ∀ i < genuineCount, genuineOwner g mem (Fin.ofNat _ i) = D.wordOwner (Fin.ofNat _ i)
+ dummyValue : ∀ i < dummyCount, dummyOwner p mem (Fin.ofNat _ i) = D.wordOwner (Fin.ofNat _ (genuineCount+i))
+
+omit [Fintype E] in
+/-- The genuine and dummy worker scans produce the complete selected owner table
+and preserve every address outside that contiguous table. The execution reports
+also give the two end cursors and exact cost for the enclosing schedule. -/
+theorem owner_table_run {base ng nd : ℕ} (g : Fin 8 → Word w) (p : Fin 3 → Word w)
+ (mem : Memory w) (input : OwnerInput D g p mem base ng nd) (fit : base+A ≤ 2^w) :
+ ∃ gs ds,
+ let mid := after mem (eventLog gs)
+ let final := after mid (eventLog ds)
+ FilledRun ((template genuine 0).instantiate w g).program 49 5 48 ng (g 7)
+ (fun i => genuineOwner g mem (Fin.ofNat _ i)) mem gs ∧
+ FilledRun ((template dummy 0).instantiate w p).program 20 2 19 nd (p 2)
+ (fun i => dummyOwner p mem (Fin.ofNat _ i)) mid ds ∧
+ (∀ i : Word w, i.val < A → final (base+i.val) = D.wordOwner i) ∧
+ (∀ addr, addr < base ∨ base+A ≤ addr → final addr = mem addr) ∧
+ RAMBuckets.cost Report.probes (gs++ds) = 6*ng+3*nd := by
+ obtain ⟨total, hgbase, hdbase, hgsrc, hdsrc, hgval, hdval⟩ := input
+ obtain ⟨gs, ds, hg, hdm, hG, hFrame, hGenCost⟩ := owner_runs g p mem ng nd
+ (by omega) (by omega) (fun i hi a ha ↦ Or.inl (hgbase ▸ hgsrc i hi a ha))
+ (fun i hi ↦ Or.inl (hgbase ▸ hdsrc i hi))
+ let m₂ := after (after mem (eventLog gs)) (eventLog ds)
+ have init (i : Word w) (hi : i.val < A) : m₂ (base+i.val) = D.wordOwner i := by
+ have he : Fin.ofNat (2^w) i.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt)
+ by_cases h : i.val < ng
+ · have h₁ := hG i.val h
+ rw [hgbase] at h₁
+ exact h₁.trans ((hgval i.val h).trans (congrArg D.wordOwner he))
+ · let k := i.val-ng
+ have hk : k < nd := by dsimp [k]; omega
+ have hj : ng+k = i.val := Nat.add_sub_of_le (by omega)
+ have h₂ := hdm.filled k hk
+ rw [hdbase, Nat.add_assoc, hj] at h₂
+ exact h₂.trans (by simpa only [hj,he] using hdval k hk)
+ have genFrame (a : ℕ) (ha : a < base ∨ base+A ≤ a) : m₂ a = mem a :=
+ hFrame a (by omega)
+ exact ⟨gs,ds,hg,hdm,init,genFrame,hGenCost⟩
+
+/-- Full native scan on the selected role, subdivision and successor records.
+The final tables are usable by the two-read endpoint query. Their allocation
+and all auxiliary singleton rows leave addresses outside the scratch region
+unchanged. -/
+theorem run {base deg genuineCount dummyCount : ℕ} (g : Fin 8 → Word w) (p : Fin 3 → Word w)
+ (mem : Memory w) (input : OwnerInput D g p mem base genuineCount dummyCount)
+ (hdeg : 0 < deg) (hdw : deg < 2^w) (hc : ∀ b, Fintype.card {e // D.owner e = b} = deg)
+ (hfit : base+A+(B+A)+(B+A)*deg+A < 2^w) (hzero : ∀ u : Word w, u.val < B+A → mem (base+A+u.val) = 0) :
+ let ownerM := ((template genuine 0).instantiate w g).program
+ let dummyM := ((template dummy 0).instantiate w p).program
+ let fill := parameters w base A B deg
+ let scatter := scatterParameters w base A B deg
+ let fillM := ((template collectPreimage 3).instantiate w fill).program
+ let scatterM := ((template SlotScatter.visit 0).instantiate w scatter).program
+ let rows := base+A+(B+A)
+ let inverse := rows+(B+A)*deg
+ ∃ gs ds fs ss,
+ let m₁ := after mem (eventLog gs)
+ let m₂ := after m₁ (eventLog ds)
+ let m₃ := after m₂ (eventLog fs)
+ let m₄ := after m₃ (eventLog ss)
+ runSegment ownerM 49 (some 0) mem (List.replicate genuineCount []) = some gs ∧
+ runSegment dummyM 20 (some 0) m₁ (List.replicate dummyCount []) = some ds ∧
+ runSegment fillM 23 (some 0) m₂ (List.replicate A []) = some fs ∧
+ runSegment scatterM 10 (some 0) m₃ (List.replicate (B*deg) []) = some ss ∧
+ Tables D deg rows inverse hc m₄ ∧
+ endState (some 0) gs = some (Fin.ofNat _ genuineCount) ∧
+ endState (some 0) ds = some (Fin.ofNat _ dummyCount) ∧
+ endState (some 0) fs = some (Fin.ofNat _ A) ∧ endState (some 0) ss = some (Fin.ofNat _ (B*deg)) ∧
+ (∀ a, a < base ∨ inverse+A ≤ a → m₄ a = mem a) ∧
+ RAMBuckets.cost Report.probes (gs++ds++fs++ss) = 6*genuineCount+3*dummyCount+5*A+3*(B*deg) ∧
+ (∀ r ∈ gs, r.events.length=48) ∧ (∀ r ∈ ds, r.events.length=19) ∧
+ (∀ r ∈ fs, r.events.length=22) ∧ ∀ r ∈ ss, r.events.length=9 := by
+ intro ownerM dummyM fill scatter fillM scatterM rows inverse
+ obtain ⟨gs,ds,hg,hdm,init,genFrame,hGenCost⟩ := owner_table_run D g p mem input (by omega)
+ let m₂ := after (after mem (eventLog gs)) (eventLog ds)
+ have zero (u : Word w) (hu : u.val < B+A) : m₂ (base+A+u.val) = 0 :=
+ (genFrame _ (.inr (Nat.le_add_right _ _))).trans (hzero _ hu)
+ obtain ⟨fs, ss, hr, hs, ht, hfc, hsc, hsFrame, _, _, cost, hfwork, hswork⟩ :=
+ build_tables D hdeg hdw hc hfit m₂ init zero
+ refine ⟨gs,ds,fs,ss,hg.executed,hdm.executed,hr,hs,ht,hg.cursor,hdm.cursor,hfc,hsc,?_,?_,
+ fun r h ↦ (hg.calls r h).2,fun r h ↦ (hdm.calls r h).2,hfwork,hswork⟩
+ · intro a ha
+ exact (hsFrame a (by omega)).trans (genFrame a (by omega))
+ · rw [RAMBuckets.cost_append,RAMBuckets.cost_append,hGenCost]; omega
+
+end CompressorRecords.SlotSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotPostAccess.lean b/lean/OAI/Computability/VPVNP/CompressorSlotPostAccess.lean
new file mode 100644
index 0000000000..63b628aad0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotPostAccess.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.CompressorSlotCoreAccess
+import OAI.Computability.VPVNP.CompressorSlotMateFootprint
+import OAI.Computability.VPVNP.CompressorSlotWidthFootprint
+
+/-! # Retained endpoint identifiers after all shrinking output scans
+
+The native mate and width passes write beyond the rectangular row and inverse
+field arrays. Both lookup directions remain available to the selector after
+the completed incidence directory has been produced.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots.Build
+
+open Compression Compression.State Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion Slots SlotLevel ShrinkSlots BurstRAM
+
+variable {a b g w : ℕ} {δ factor : ℝ} {k : Type*} [_root_.Field k]
+variable (X : State a (packingLaneBits a g))
+variable (B : FixedBlock k demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection B)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+set_option maxHeartbeats 1000000 in
+theorem post_access (h : Heads) (splitHead : ℕ) (m : Memory w) (r : Construction w) :
+ let s := levelShape (b := b) X
+ let side := selectedLayout X B sel
+ Space s h splitHead w → DemandRAM.RoleColumns X side h.oldArc m → r.Native s h splitHead side m →
+ LogAccess (readRegion s h splitHead) (writeRegion s h) r.passes.slots.all ∧
+ LogAccess (readRegion s h splitHead) (writeRegion s h) (r.passes.mates.all++r.passes.widths) ∧
+ OrderedTables X ready side h (r.final m) := by
+ intro s side sp roles native
+ let Y := X.shrinkNext B ready sel
+ obtain ⟨core,forward,twoFits,oldFits,tables⟩ := Build.core_access X B ready sel h splitHead m r sp roles native
+ have counts := next_counts X B ready sel
+ change Fintype.card Y.Base*2^b=baseArcs s ∧ Fintype.card Y.Base*2^g*2^b=actualCount s at counts
+ let m₁ := r.passes.slots.final (r.prepare.final m)
+ let m₂ := r.passes.mates.final m₁
+ have mate := mate_footprint Y s h m₁ r.passes.mates forward counts.1 counts.2 rfl rfl
+ sp.degree sp.lanes sp.fit native.2.2.1
+ have h0 := sp.old
+ have h1 := sp.roles
+ have h2 := sp.next
+ have h3 := sp.subdiv
+ have h4 := sp.split
+ have hs : h.scratch ≤ rowsHead s h := by unfold rowsHead; omega
+ have hr : rowsHead s h ≤ targetsHead s h := by unfold targetsHead inverseHead; omega
+ have ht : targetsHead s h ≤ inverseBaseHead s h := by unfold inverseBaseHead stopAddress shiftsHead; omega
+ have hb : inverseBaseHead s h ≤ widthHead s h := by unfold widthHead inHead outHead; omega
+ have hw : widthHead s h ≤ finish s h := Nat.le_add_right _ _
+ have ws := SlotWidthScan.run_footprint s h splitHead m₂ r.passes.widths twoFits sp.degree sp.lanes sp.profile
+ oldFits (h4.trans (by omega)) (by omega) sp.fit native.2.2.2
+ let rd := readRegion s h splitHead
+ let wr := writeRegion s h
+ have lower := min_le_left h.oldArc splitHead
+ have other := min_le_right h.oldArc splitHead
+ have mate' : LogAccess rd wr r.passes.mates.all := LogAccess.mono mate
+ (fun x hx ↦ by change min h.oldArc splitHead ≤ x ∧ x < finish s h; omega)
+ (fun x hx ↦ by change h.role ≤ x ∧ x < finish s h; omega)
+ have width' : LogAccess rd wr r.passes.widths := LogAccess.mono ws
+ (fun x hx ↦ by change min h.oldArc splitHead ≤ x ∧ x < finish s h; omega)
+ (fun x hx ↦ by change h.role ≤ x ∧ x < finish s h; omega)
+ have keep (x : ℕ) (hx : x < targetsHead s h) : r.final m x = m₁ x := by
+ have cm : m₂ = after m₁ (eventLog r.passes.mates.all) := by
+ simp only [m₂,MateReports.final,MateReports.all,eventLog,List.flatMap_append,after,List.foldl_append]
+ have hw := SourceTransport.after_outside m₂ ws.2 (show ¬ (widthHead s h ≤ x ∧ x < finish s h) by omega)
+ have hm := SourceTransport.after_outside m₁ mate.2 (show ¬ (inverseBaseHead s h ≤ x ∧ x < widthHead s h) by omega)
+ change after m₂ (eventLog r.passes.widths) x = m₁ x
+ exact hw.trans (by rw [cm]; exact hm)
+ have rect : rowsHead s h+owners s*s.newDegree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.le_add_right _ _)) _
+ have extent : inverseHead s h+fields s=targetsHead s h := rfl
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let lanes := bitWordFinEquiv g
+ let D := SlotSchedule.slotDirectory X.packingData s.subdivisions X.baseIndex tags lanes side (pad := pad s)
+ let hD := fun v ↦ (SlotSchedule.slotDirectory_degree X.packingData s.subdivisions X.baseIndex tags lanes
+ (two_le_packingColors a) side v).trans (Nat.add_sub_of_le ready.degree_budget)
+ refine ⟨core,mate'.append width',⟨?_,?_⟩⟩
+ · intro e
+ apply (keep _ ?_).trans (tables.bySlot e)
+ change rowsHead s h+(SlotSchedule.sortedFields D (2^b) hD e).val < targetsHead s h
+ have index : (SlotSchedule.sortedFields D (2^b) hD e).val < owners s*s.newDegree :=
+ (SlotSchedule.sortedFields D (2^b) hD e).isLt
+ omega
+ · intro e
+ apply (keep _ ?_).trans (tables.byField e)
+ change inverseHead s h+(D.address e).val < targetsHead s h
+ have hi : (D.address e).val < fields s := (D.address e).isLt
+ omega
+
+/-- The canonical sorted-field and inverse-field arrays after all sixteen construction phases. -/
+theorem retained_tables (h : Heads) (splitHead : ℕ) (m : Memory w) (r : Construction w) :
+ let s := levelShape (b := b) X
+ let side := selectedLayout X B sel
+ Space s h splitHead w → DemandRAM.RoleColumns X side h.oldArc m → r.Native s h splitHead side m →
+ OrderedTables X ready side h (r.final m) := by
+ intro s side sp roles native
+ exact (post_access X B ready sel h splitHead m r sp roles native).2.2
+
+end CompressorRecords.ShrinkSlots.Build
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotRankRAM.lean b/lean/OAI/Computability/VPVNP/CompressorSlotRankRAM.lean
new file mode 100644
index 0000000000..ab0f324273
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotRankRAM.lean
@@ -0,0 +1,223 @@
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+import OAI.Computability.VPVNP.RAMWork
+
+/-!
+# Native RAM ranks for ordered incidence slots
+
+The input row lists the incident slot keys in the order in which the descriptor
+builder found them. The burst call counts keys strictly below its persistent
+input and writes the count to the endpoint's slot field. It reads each key once.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotRankRAM
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ}
+
+/-- Register 0 is the moving read address, 1 the pivot, 2 the unit,
+3 the running count and 4 a temporary word. -/
+private def visit : List (Op 5 2) :=
+ [.read 4 0, .binary .add 4 4 2, .binary .div 4 1 4, .binary .div 4 4 4,
+ .binary .add 3 3 4, .binary .add 0 0 2]
+
+private def scan : ℕ → List (Op 5 2)
+ | 0 => []
+ | n + 1 => visit ++ scan n
+
+/-- Public words 0 and 1 are the row address and destination address.
+The rank accumulator starts at zero on entry to the burst call. -/
+def rankCode (n : ℕ) : List (Op 5 2) :=
+ [.publicWord 0 0, .stateWord 1, .constant 2 1] ++ scan n ++
+ [.publicWord 4 1, .write 4 3]
+
+theorem rankCode_length (n : ℕ) : (rankCode n).length = 6 * n + 5 := by
+ have h : (scan n).length = 6 * n := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [scan, visit, ih]; omega
+ simp [rankCode, h]
+
+/-- Unsigned division by the key's successor, followed by a nonzero test,
+implements strict order on word values. -/
+private theorem quotient_indicator (pivot key : Word w) (hkey : key.val + 1 < 2 ^ w) :
+ let q := BinaryOp.div.eval pivot (key + 1)
+ BinaryOp.div.eval q q = if key < pivot then 1 else 0 := by
+ dsimp only
+ have h1 : (1 : Word w).val = 1 := by rw [Fin.val_one', Nat.mod_eq_of_lt (by omega)]
+ have hs : (key + 1).val = key.val + 1 := by
+ rw [Fin.val_add, h1, Nat.mod_eq_of_lt hkey]
+ have hq : (BinaryOp.div.eval pivot (key + 1)).val = pivot.val / (key.val + 1) := by
+ change (pivot.val / (key + 1).val) % (2 ^ w) = _
+ rw [hs, Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt pivot.isLt)]
+ change Fin.ofNat _ ((BinaryOp.div.eval pivot (key + 1)).val /
+ (BinaryOp.div.eval pivot (key + 1)).val) = _
+ rw [hq]
+ by_cases h : key < pivot
+ · rw [ite_eq_left h, Nat.div_self (Nat.div_pos (Fin.lt_def.mp h) (Nat.zero_lt_succ _))]
+ rfl
+ · rw [ite_eq_right h, Nat.div_eq_of_lt (Nat.lt_succ_of_le (le_of_not_gt (show ¬key.val < pivot.val from h)))]
+ rfl
+
+private def holds (mem : Memory w) (ptr : Word w) : List (Word w) → Prop
+ | [] => True
+ | key :: ks => mem ptr.val = key ∧ holds mem (ptr + 1) ks
+
+private theorem holds_of_getElem (mem : Memory w) (ptr : Word w) (row : List (Word w))
+ (hmem : ∀ i : Fin row.length, mem (ptr.val + i.val) = row[i.val])
+ (haddr : ptr.val + row.length ≤ 2 ^ w) : holds mem ptr row := by
+ induction row generalizing ptr with
+ | nil => trivial
+ | cons key ks ih =>
+ simp only [List.length_cons] at haddr
+ have hle : (ptr + 1).val ≤ ptr.val + 1 := by
+ rw [Fin.val_add, Fin.val_one']
+ exact (Nat.mod_le _ _).trans (Nat.add_le_add_left (Nat.mod_le _ _) _)
+ refine ⟨hmem ⟨0, by simp⟩, ih _ (fun i => ?_) (by omega)⟩
+ have hi := i.isLt
+ have hnext : (ptr + 1).val = ptr.val + 1 := by
+ rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^w by omega),
+ Nat.mod_eq_of_lt (by omega)]
+ simpa [hnext, Nat.add_assoc, Nat.add_comm 1 i.val] using hmem i.succ
+
+private def scanEvents (ptr : Word w) : List (Word w) → List (Event w)
+ | [] => []
+ | key :: ks => .read ptr key :: .tick :: .tick :: .tick :: .tick :: .tick ::
+ scanEvents (ptr + 1) ks
+
+private theorem scanEvents_spec (ptr : Word w) (row : List (Word w)) (mem : Memory w)
+ (es : List (Event w)) :
+ countProbes (scanEvents ptr row ++ es) = row.length + countProbes es ∧
+ (scanEvents ptr row ++ es).length = 6 * row.length + es.length ∧
+ after mem (scanEvents ptr row ++ es) = after mem es := by
+ induction row generalizing ptr with
+ | nil => simp [scanEvents]
+ | cons key ks ih =>
+ obtain ⟨hc, hl, hm⟩ := ih (ptr + 1)
+ refine ⟨?_, ?_, hm⟩
+ · change 1 + countProbes (scanEvents (ptr + 1) ks ++ es) = ks.length + 1 + _
+ omega
+ · change (scanEvents (ptr + 1) ks ++ es).length + 6 = 6 * (ks.length + 1) + es.length
+ omega
+
+private theorem visit_trace (pub : Fin 2 → Word w) (pivot key : Word w) (mem : Memory w)
+ (rs : Regs w 5) (hp : rs 1 = pivot) (hu : rs 2 = 1) (hm : mem (rs 0).val = key)
+ (hk : key.val + 1 < 2 ^ w) :
+ ∃ mid, trace pub pivot visit rs mem =
+ some ([.read (rs 0) key, .tick, .tick, .tick, .tick, .tick], mid, mem) ∧
+ mid 0 = rs 0 + 1 ∧ mid 1 = pivot ∧ mid 2 = 1 ∧
+ mid 3 = rs 3 + (if key < pivot then 1 else 0) := by
+ have hf := quotient_indicator pivot key hk
+ simp (config := { decide := true }) [visit, trace, Op.effect, BinaryOp.eval, Function.update,
+ hm, hp, hu] at hf ⊢
+ exact hf ▸ rfl
+
+private theorem scan_trace (pub : Fin 2 → Word w) (pivot : Word w) (mem : Memory w)
+ (row : List (Word w)) (rs : Regs w 5) (hp : rs 1 = pivot) (hu : rs 2 = 1)
+ (hm : holds mem (rs 0) row) (hk : ∀ key ∈ row, key.val + 1 < 2 ^ w)
+ (hsize : (rs 3).val + row.length < 2 ^ w) :
+ ∃ out, trace pub pivot (scan row.length) rs mem =
+ some (scanEvents (rs 0) row, out, mem) ∧
+ (out 3).val = (rs 3).val + (row.filter fun key => decide (key < pivot)).length := by
+ induction row generalizing rs with
+ | nil => exact ⟨rs, rfl, rfl⟩
+ | cons key ks ih =>
+ obtain ⟨hhead, htail⟩ := hm
+ have hkey := hk key (List.mem_cons_self ..)
+ obtain ⟨mid, hmid, hptr, hpiv, hone, hrank⟩ := visit_trace pub pivot key mem rs hp hu hhead hkey
+ simp only [List.length_cons] at hsize
+ have hv : (mid 3).val = (rs 3).val + (if key < pivot then 1 else 0) := by
+ rw [hrank, Fin.val_add]
+ split_ifs <;> simp only [Fin.val_one', Fin.val_zero, Nat.add_zero]
+ · rw [Nat.mod_eq_of_lt (show 1 < 2^w by omega), Nat.mod_eq_of_lt (by omega)]
+ · rw [Nat.mod_eq_of_lt (rs 3).isLt]
+ obtain ⟨out, htrace, hvout⟩ := ih mid hpiv hone (hptr ▸ htail)
+ (fun k h => hk k (List.mem_cons_of_mem _ h)) (by rw [hv]; split <;> omega)
+ refine ⟨out, ?_, ?_⟩
+ · simp [scan, trace_append, hmid, htrace, hptr, scanEvents]
+ · rw [hvout, hv]
+ by_cases h : key < pivot <;> simp [h]
+ omega
+
+/-- The call starts with a fresh private workspace, reads the entire row in
+descriptor order, writes the strict rank to the requested field, and returns it.
+The destination may coincide with a source cell since the write follows all reads. -/
+theorem rank_native (pub : Fin 2 → Word w) (pivot : Word w) (mem : Memory w)
+ (row : List (Word w))
+ (hmem : ∀ i : Fin row.length, mem ((pub 0).val + i.val) = row[i.val])
+ (haddr : (pub 0).val + row.length ≤ 2 ^ w) (hsize : row.length < 2 ^ w)
+ (hkeys : ∀ key ∈ row, key.val + 1 < 2 ^ w) :
+ let rank := (row.filter fun key => decide (key < pivot)).length
+ let M := (template (rankCode row.length) 3).instantiate w pub
+ ∃ es, execute M.program (6 * row.length + 6) (M.program.start pivot) mem [] =
+ some ⟨es, some (Fin.ofNat _ rank)⟩ ∧
+ after mem es = writeMemory mem (pub 1) (Fin.ofNat _ rank) ∧
+ countProbes es = row.length + 1 ∧ es.length + 1 = 6 * row.length + 6 := by
+ dsimp only
+ let rank := (row.filter fun key => decide (key < pivot)).length
+ let init : Regs w 5 := Function.update (Function.update
+ (Function.update (fun _ => 0) (0 : Fin 5) (pub 0)) 1 pivot) 2 1
+ have hi : trace pub pivot [.publicWord 0 0, .stateWord 1, .constant 2 1]
+ (fun _ : Fin 5 => 0) mem = some ([.tick, .tick, .tick], init, mem) := rfl
+ obtain ⟨out, htrace, hv⟩ := scan_trace pub pivot mem row init (by simp [init]) (by simp [init])
+ (by simpa [init] using holds_of_getElem mem (pub 0) row hmem haddr) hkeys (by simpa [init] using hsize)
+ have hrank : out 3 = Fin.ofNat _ rank := by
+ apply Fin.ext
+ change (out 3).val = rank % (2^w)
+ rw [Nat.mod_eq_of_lt ((List.length_filter_le ..).trans_lt hsize)]
+ simpa [init, rank] using hv
+ let tail : List (Event w) := [.tick, .write (pub 1) (Fin.ofNat _ rank)]
+ have ht : trace pub pivot [.publicWord 4 1, .write 4 3] out mem =
+ some (tail, Function.update out 4 (pub 1), writeMemory mem (pub 1) (Fin.ofNat _ rank)) := by
+ simp [trace, Op.effect, tail, hrank]
+ have he := scanEvents_spec (pub 0) row mem tail
+ obtain ⟨hc, hl, hm⟩ := he
+ refine ⟨.tick :: .tick :: .tick :: (scanEvents (pub 0) row ++ tail), ?_, hm, hc, ?_⟩
+ · rw [show 6 * row.length + 6 = 1 + (rankCode row.length).length by rw [rankCode_length]; omega]
+ change execute ((template (rankCode row.length) 3).instantiate w pub).program _
+ ⟨_, pivot, fun _ => 0, fun _ => 0⟩ mem [] = _
+ rw [execute_template, run_eq_trace, rankCode, trace_append, trace_append, hi]
+ simp [htrace, ht, hrank, init, rank]
+ · change (scanEvents (pub 0) row ++ tail).length + 4 = _
+ change (scanEvents (pub 0) row ++ tail).length = 6 * row.length + 2 at hl
+ omega
+
+/-- The table uses only registers and external probes. In the metered opcode
+interpreter each dispatch costs at most six elementary word operations, including
+when a supplied read stream stops early. -/
+theorem rank_opcode_work (pub : Fin 2 → Word w) (pivot : Word w) (n allowance : ℕ)
+ (bits : List Bool) :
+ let M := (template (rankCode n) 3).instantiate w pub
+ M.loggedDispatchWork (6 * n + 6) (M.logProgram.start pivot) allowance bits ≤ 36 * n + 36 := by
+ let M := (template (rankCode n) 3).instantiate w pub
+ have noLog (l : LogConfig w ((rankCode n).length + 2) 5) :
+ (M.code l.pc).actualLogWork l = 0 := by
+ simp only [M, Template.instantiate, template]
+ split
+ · cases (rankCode n)[l.pc.val] <;> rfl
+ · split <;> rfl
+ have bound (fuel : ℕ) (l : LogConfig w ((rankCode n).length + 2) 5) (a : ℕ) (bs : List Bool) :
+ M.loggedDispatchWork fuel l a bs ≤ 6 * fuel := by
+ induction fuel generalizing l a bs with
+ | zero => rfl
+ | succ f ih =>
+ rw [Machine.loggedDispatchWork, noLog, Nat.add_zero]
+ have h := (M.code l.pc).wordWork_le
+ split
+ · omega
+ · rename_i l' a' bs' _
+ have := ih l' a' bs'
+ omega
+ have h := bound (6 * n + 6) (M.logProgram.start pivot) allowance bits
+ change M.loggedDispatchWork (6 * n + 6) (M.logProgram.start pivot) allowance bits ≤ 36 * n + 36
+ omega
+
+end CompressorRecords.SlotRankRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotRunUnique.lean b/lean/OAI/Computability/VPVNP/CompressorSlotRunUnique.lean
new file mode 100644
index 0000000000..c6b46e25b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotRunUnique.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.CompressorSlotBuild
+
+/-!
+# Uniqueness of reports from the deterministic slot workers
+
+The slot program has empty choice tapes after its layout has been selected.
+Its operand banks and initial memory determine the reports of every phase.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open BurstRAM SlotLevel
+
+variable {w : ℕ} {s : Shape} {h : Heads} {m : Memory w}
+
+theorem ShrinkSlots.Preparation.Reports.Native.unique {layout : Bool} {r t : ShrinkSlots.Preparation.Reports w}
+ (hr : r.Native s h layout m) (ht : t.Native s h layout m) : r = t := by
+ have fixed {r : ShrinkSlots.Preparation.Reports w} (run : r.Native s h layout m) :
+ r.publish = ShrinkSlots.Preparation.published h.subdivisions s.subdivisions w := by
+ funext i
+ have hp := ShrinkSlots.Preparation.publish_run h.subdivisions s.subdivisions
+ (after m (eventLog ((List.ofFn r.publish).take i.val))) i
+ exact (List.cons.inj (Option.some.inj ((run.1 i).symm.trans hp))).1
+ have eq := (fixed hr).trans (fixed ht).symm
+ rcases r with ⟨p,r,c,z⟩
+ rcases t with ⟨q,r',c',z'⟩
+ change p=q at eq; subst q
+ rcases hr with ⟨_,hr,hc,hz⟩
+ rcases ht with ⟨_,hr',hc',hz'⟩
+ have e : r=r' := Option.some.inj (hr.symm.trans hr'); subst r'
+ have e : c=c' := Option.some.inj (hc.symm.trans hc'); subst c'
+ have e : z=z' := Option.some.inj (hz.symm.trans hz'); subst z'
+ rfl
+
+theorem SlotLevel.Reports.Native.unique {r t : SlotLevel.Reports w}
+ (hr : r.Native s h m) (ht : t.Native s h m) : r=t := by
+ rcases r with ⟨g,d,a,i,b⟩
+ rcases t with ⟨g',d',a',i',b'⟩
+ obtain ⟨hg,hd,ha,hi,hb⟩ := hr
+ obtain ⟨hg',hd',ha',hi',hb'⟩ := ht
+ have e : g=g' := Option.some.inj (hg.symm.trans hg'); subst g'
+ have e : d=d' := Option.some.inj (hd.symm.trans hd'); subst d'
+ have e : a=a' := Option.some.inj (ha.symm.trans ha'); subst a'
+ have e : i=i' := Option.some.inj (hi.symm.trans hi'); subst i'
+ have e : b=b' := Option.some.inj (hb.symm.trans hb'); subst b'
+ rfl
+
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotScanFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorSlotScanFootprint.lean
new file mode 100644
index 0000000000..5411080e94
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotScanFootprint.lean
@@ -0,0 +1,44 @@
+import OAI.Computability.VPVNP.CompressorRecordsOrdinalFootprint
+import OAI.Computability.VPVNP.RAMChoicePrefix
+
+/-!
+# External events of a dense native slot scan
+
+Each successful call advances the cursor by one. A memory invariant can
+retain initialized input columns while the scan fills its output.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotEventBounds
+
+open BurstRAM SourceTransport
+
+variable {w : ℕ}
+
+/-- Lift the address bounds of one empty-tape call to the entire ordinal scan. -/
+theorem scan {Q : Type*} (P : Program w Q) (fuel n : ℕ)
+ (events : Memory w → Word w → List (Event w)) (I : Memory w → Prop) (read write : ℕ → Prop)
+ (native : ∀ m i, execute P fuel (P.start i) m [] = some ⟨events m i,some (i+1)⟩)
+ (step : ∀ j < n, ∀ m, I m → let es := events m (Fin.ofNat (2^w) j)
+ Reads read es ∧ Writes write es ∧ I (after m es))
+ (m : Memory w) (rs : List (Report w)) (init : I m)
+ (run : runSegment P fuel (some 0) m (List.replicate n []) = some rs) :
+ Reads read (eventLog rs) ∧ Writes write (eventLog rs) := by
+ apply OrdinalRun.footprint P fuel (Fin.ofNat (2^w)) n (fun _ ↦ I) read write _ 0 _ m rs (by simp) init run
+ intro j hj m hm bits rep executed
+ let i := Fin.ofNat (2^w) j
+ have equal := (execute_prefix_unique (native m i)
+ (show execute P fuel (P.start i) m ([]++bits) = some rep from executed)).2
+ subst rep
+ obtain ⟨rd,wr,inv⟩ := step j hj m hm
+ refine ⟨congrArg some ?_,inv,rd,wr⟩
+ apply Fin.ext; simp [i,Fin.val_add,Nat.mod_add_mod,Nat.add_mod_mod]
+
+end CompressorRecords.SlotEventBounds
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotScatter.lean b/lean/OAI/Computability/VPVNP/CompressorSlotScatter.lean
new file mode 100644
index 0000000000..30818078d4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotScatter.lean
@@ -0,0 +1,161 @@
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+import OAI.Computability.VPVNP.RAMChain
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Inverting a rectangular endpoint table in external RAM
+
+The input is indexed by ordered incidence and gives the absolute endpoint field of
+that incidence. One burst call reads this field and stores the incidence index at
+that field in the inverse table. An injective input can leave holes in the inverse
+table. The pass preserves every hole as well as all memory outside the table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotScatter
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w n capacity : ℕ}
+
+/-- Public words give the base of the field table and the base of the inverse table.
+Register 0 is the incidence index and becomes the next call's persistent cursor. -/
+def visit : List (Op 4 2) :=
+ [.stateWord 0, .publicWord 1 0, .binary .add 1 1 0, .read 2 1,
+ .publicWord 3 1, .binary .add 3 3 2, .write 3 0, .constant 1 1, .binary .add 0 0 1]
+
+/-- The read and the write in program order, including the intervening arithmetic. -/
+def events (pub : Fin 2 → Word w) (i field : Word w) : List (Event w) :=
+ [.tick, .tick, .tick, .read (pub 0 + i) field, .tick, .tick, .write (pub 1 + field) i,
+ .tick, .tick]
+
+theorem visit_native (pub : Fin 2 → Word w) (mem : Memory w) (i : Word w) :
+ let M := (template visit 0).instantiate w pub
+ execute M.program 10 (M.program.start i) mem [] =
+ some ⟨events pub i (mem (pub 0 + i).val), some (i + 1)⟩ := by
+ change execute ((template visit 0).instantiate w pub).program (1 + visit.length)
+ ⟨_, i, fun _ => 0, fun _ => 0⟩ mem [] = _
+ rw [execute_template, run_eq_trace]
+ rfl
+
+/-- Both address intervals fit in a word and are disjoint. Either order is allowed. -/
+structure Regions (pub : Fin 2 → Word w) (n capacity : ℕ) : Prop where
+ fieldsFit : (pub 0).val + n ≤ 2 ^ w
+ inverseFit : (pub 1).val + capacity ≤ 2 ^ w
+ disjoint : (pub 0).val + n ≤ (pub 1).val ∨ (pub 1).val + capacity ≤ (pub 0).val
+
+private theorem address_val (base : Word w) {limit : ℕ} (fit : base.val + limit ≤ 2^w)
+ (i : Fin limit) : (base + Fin.ofNat (2^w) i.val).val = base.val + i.val := by
+ have hi := i.isLt
+ rw [Fin.val_add, Fin.val_ofNat, Nat.mod_eq_of_lt (show i.val < 2^w by omega), Nat.mod_eq_of_lt (by omega)]
+
+private theorem word_succ (k : ℕ) : Fin.ofNat (2^w) k + 1 = Fin.ofNat (2^w) (k+1) := by
+ apply Fin.ext
+ simp [Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod]
+
+/-- At cursor `k` precisely the fields of incidences below `k` have been written. -/
+private structure Prefix (base : ℕ) (field : Fin n ↪ Fin capacity)
+ (initial mem : Memory w) (k : ℕ) : Prop where
+ inverse : ∀ i : Fin n, i.val < k → mem (base + (field i).val) = Fin.ofNat _ i.val
+ frame : ∀ addr, (∀ i : Fin n, i.val < k → addr ≠ base + (field i).val) → mem addr = initial addr
+
+private theorem prefix_step {pub : Fin 2 → Word w} (regions : Regions pub n capacity)
+ (field : Fin n ↪ Fin capacity) {initial mem : Memory w} (i : Fin n)
+ (stored : ∀ j : Fin n, initial ((pub 0).val + j.val) = Fin.ofNat _ (field j).val)
+ (prior : Prefix (pub 1).val field initial mem i.val) :
+ let idx := Fin.ofNat (2^w) i.val
+ let v := Fin.ofNat (2^w) (field i).val
+ mem (pub 0 + idx).val = v ∧
+ Prefix (pub 1).val field initial (after mem (events pub idx v)) (i.val+1) := by
+ intro idx v
+ have ha := address_val (pub 0) regions.fieldsFit i
+ have hd : (pub 1 + v).val = (pub 1).val + (field i).val :=
+ address_val (pub 1) regions.inverseFit (field i)
+ have hm : after mem (events pub idx v) = writeMemory mem (pub 1 + v) idx := rfl
+ refine ⟨?_, ?_⟩
+ · rw [ha, prior.frame, stored]
+ intro j _
+ have hi := i.isLt
+ have hj := (field j).isLt
+ rcases regions.disjoint with h | h <;> omega
+ · rw [hm]
+ constructor
+ · intro j hj
+ by_cases he : j = i
+ · subst j; rw [writeMemory, hd, ite_eq_left rfl]
+ · have hne : (field j).val ≠ (field i).val := fun h => he (field.injective (Fin.ext h))
+ have hv : j.val ≠ i.val := fun h => he (Fin.ext h)
+ simpa only [writeMemory, hd, Nat.add_left_cancel_iff, ite_eq_right hne] using prior.inverse j (by omega)
+ · intro addr h
+ have hhead := h i (Nat.lt_succ_self _)
+ simpa only [writeMemory, hd, ite_eq_right hhead] using prior.frame addr (fun j hj => h j (by omega))
+
+private theorem run_from {pub : Fin 2 → Word w} (regions : Regions pub n capacity)
+ (field : Fin n ↪ Fin capacity) {initial : Memory w}
+ (stored : ∀ i : Fin n, initial ((pub 0).val + i.val) = Fin.ofNat _ (field i).val)
+ (k steps : ℕ) (mem : Memory w) (prior : Prefix (pub 1).val field initial mem k)
+ (bound : k + steps ≤ n) :
+ let M := (template visit 0).instantiate w pub
+ let state := some (Fin.ofNat (2^w) k)
+ ∃ rs, runSegment M.program 10 state mem (List.replicate steps []) = some rs ∧
+ endState state rs = some (Fin.ofNat _ (k+steps)) ∧
+ Prefix (pub 1).val field initial (after mem (eventLog rs)) (k+steps) ∧
+ rs.length = steps ∧ (∀ r ∈ rs, r.events.length = 9 ∧ r.probes = 2) ∧
+ RAMBuckets.cost Report.probes rs = 3 * steps := by
+ induction steps generalizing k mem with
+ | zero => exact ⟨[], rfl, rfl, prior, rfl, by simp, rfl⟩
+ | succ steps ih =>
+ let i : Fin n := ⟨k, by omega⟩
+ let idx := Fin.ofNat (2^w) k
+ let v := Fin.ofNat (2^w) (field i).val
+ let es := events pub idx v
+ let r : Report w := ⟨es, some (idx+1)⟩
+ obtain ⟨hread, hnext⟩ := prefix_step regions field i stored prior
+ obtain ⟨rs, hrun, hstate, hmem, hlen, hwork, hcost⟩ :=
+ ih (k+1) (after mem es) hnext (by omega)
+ have hstart : idx + 1 = Fin.ofNat _ (k+1) := word_succ k
+ have harr : k + 1 + steps = k + (steps + 1) := by omega
+ refine ⟨r :: rs, ?_, ?_, ?_, by simp [hlen], ?_, ?_⟩
+ · rw [List.replicate_succ, runSegment, visit_native, hread]
+ simpa only [hstart, Option.map_some, idx, v, r, es] using
+ congrArg (Option.map (r :: ·)) hrun
+ · change endState (some (idx+1)) rs = _
+ rwa [hstart, ← harr]
+ · change Prefix _ field initial ((es ++ eventLog rs).foldl update mem) _
+ rw [List.foldl_append, ← harr]
+ exact hmem
+ · intro t ht
+ rcases List.mem_cons.mp ht with rfl | h
+ · exact ⟨rfl, rfl⟩
+ · exact hwork t h
+ · rw [RAMBuckets.cost, show r.probes = 2 from rfl, hcost, Nat.mul_succ]
+ omega
+
+/-- The complete scatter pass constructs the inverse at every occupied endpoint
+field, returns the end cursor, and preserves all other cells. It spends exactly
+three calls-plus-probes units per incidence, with ten instructions of fuel per call. -/
+theorem run {pub : Fin 2 → Word w} (regions : Regions pub n capacity)
+ (field : Fin n ↪ Fin capacity) (mem : Memory w)
+ (stored : ∀ i : Fin n, mem ((pub 0).val + i.val) = Fin.ofNat _ (field i).val) :
+ let M := (template visit 0).instantiate w pub
+ ∃ rs, runSegment M.program 10 (some 0) mem (List.replicate n []) = some rs ∧
+ endState (some 0) rs = some (Fin.ofNat (2^w) n) ∧
+ (∀ i : Fin n, after mem (eventLog rs) ((pub 1).val + (field i).val) = Fin.ofNat _ i.val) ∧
+ (∀ addr, (∀ i : Fin n, addr ≠ (pub 1).val + (field i).val) →
+ after mem (eventLog rs) addr = mem addr) ∧
+ rs.length = n ∧ (∀ r ∈ rs, r.events.length = 9 ∧ r.probes = 2) ∧
+ RAMBuckets.cost Report.probes rs = 3 * n := by
+ have h0 : Prefix (pub 1).val field mem mem 0 := ⟨by simp, fun _ _ => rfl⟩
+ obtain ⟨rs, hrun, hstate, hmem, hlen, hwork, hcost⟩ := run_from regions field stored 0 n mem h0 (by simp)
+ rw [Nat.zero_add] at hstate hmem
+ exact ⟨rs, hrun, hstate, fun i => hmem.inverse i i.isLt,
+ fun addr h => hmem.frame addr (fun i _ => h i), hlen, hwork, hcost⟩
+
+end CompressorRecords.SlotScatter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotSchedule.lean b/lean/OAI/Computability/VPVNP/CompressorSlotSchedule.lean
new file mode 100644
index 0000000000..9a9398041f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotSchedule.lean
@@ -0,0 +1,333 @@
+import OAI.Computability.VPVNP.CompressorSlotAddresses
+import OAI.Computability.VPVNP.CompressorRecordPlacement
+import OAI.Computability.VPVNP.CompressorSlotScatter
+import OAI.Computability.VPVNP.CompressorSlotFrames
+
+/-!
+# Filling the local slot arrays in address order
+
+A scan over absolute endpoint fields visits each genuine arc in relative-key
+order, followed by the padding arcs. Nonexistent mixed-radix IDs are each
+sent to a separate unused row, so the scan requires no preliminary compacting
+pass. Each real row then contains the absolute field addresses in slot order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotSchedule
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+/-- Numeric endpoint field space and the selected owners for the current layout. -/
+structure Directory (E : Type*) (A B : ℕ) where
+ /-- Inject each genuine or dummy endpoint field into its absolute address in the candidate
+ range. -/
+ address : E ↪ Fin A
+ /-- Decode an absolute candidate address to its endpoint field when occupied, returning none
+ for a hole. -/
+ decode : Fin A → Option E
+ decode_eq_some : ∀ i e, decode i = some e ↔ address e = i
+ /-- Real owner row to which an endpoint field is assigned under the chosen layout. -/
+ owner : E → Fin B
+
+variable {E : Type*} {A B w : ℕ} (D : Directory E A B)
+
+/-- Allocate an auxiliary row for each unoccupied address. Its count is at most one. -/
+def Directory.destination (a : Fin A) : Fin (B + A) :=
+ finSumFinEquiv ((D.decode a).elim (.inr a) (fun e ↦ .inl (D.owner e)))
+
+private theorem Directory.real (e : E) : D.destination (D.address e) = (D.owner e).castAdd A := by
+ rw [Directory.destination, (D.decode_eq_some _ _).mpr rfl]
+ rfl
+
+private theorem Directory.real_iff (a : Fin A) (b : Fin B) :
+ D.destination a = b.castAdd A ↔ ∃ e, D.address e = a ∧ D.owner e = b := by
+ change finSumFinEquiv _ = finSumFinEquiv (.inl b) ↔ _
+ rw [finSumFinEquiv.injective.eq_iff]
+ cases h : D.decode a with
+ | none =>
+ constructor
+ · simp
+ · rintro ⟨e, he, _⟩; simpa [h] using (D.decode_eq_some a e).mpr he
+ | some e =>
+ constructor
+ · intro he; exact ⟨e, (D.decode_eq_some a e).mp h, Sum.inl.inj he⟩
+ · rintro ⟨x, hx, hx'⟩
+ obtain rfl := Option.some.inj (h.symm.trans ((D.decode_eq_some a x).mpr hx))
+ exact congrArg Sum.inl hx'
+
+private theorem Directory.hole_eq (a h : Fin A) (ha : D.destination a = h.natAdd B) : a = h := by
+ change finSumFinEquiv _ = finSumFinEquiv (.inr h) at ha
+ have he := finSumFinEquiv.injective ha
+ cases hd : D.decode a <;> simp [hd] at he
+ exact he
+
+/-- End-site index stored in the owner array for each candidate absolute field. -/
+def Directory.wordOwner (D : Directory E A B) : Word w → Word w :=
+ encodedPlacement (Equiv.refl (Fin A)) (Equiv.refl (Fin (B+A))) D.destination
+
+private theorem owner_eq (hA : A ≤ 2 ^ w) (hB : B+A ≤ 2^w) (i : Fin A) :
+ (D.wordOwner (Fin.ofNat (2^w) i.val)).val = (D.destination i).val :=
+ encodedPlacement_eq _ _ _ hA hB i
+
+/-- Among the fields scanned before cursor `k`, the real entries of row `b`
+are exactly the identified endpoints in that row with address below `k`. -/
+theorem real_prefix_length [Fintype E] (hA : A ≤ 2^w) (hB : B+A ≤ 2^w) (b : Fin B)
+ (k : ℕ) (hk : k ≤ A) :
+ (preimagePrefix D.wordOwner (Fin.ofNat (2^w) b.val) k).length =
+ Fintype.card {e // D.owner e = b ∧ (D.address e).val < k} := by
+ rw [preimagePrefix_card]
+ let I := {i : Fin k // D.wordOwner (Fin.ofNat (2^w) i.val) = Fin.ofNat (2^w) b.val}
+ let J := {e // D.owner e = b ∧ (D.address e).val < k}
+ have iffOwner (i : Fin k) : D.wordOwner (Fin.ofNat (2^w) i.val) = Fin.ofNat (2^w) b.val ↔
+ D.destination (i.castLE hk) = b.castAdd A := by
+ have hn := owner_eq D hA hB (i.castLE hk)
+ change (D.wordOwner (Fin.ofNat (2^w) i.val)).val = _ at hn
+ rw [Fin.ext_iff, Fin.ext_iff, hn]
+ change _ = b.val % (2^w) ↔ _ = b.val
+ rw [Nat.mod_eq_of_lt (b.isLt.trans_le (by omega))]
+ let f (e : J) : I := ⟨⟨(D.address e.val).val, e.prop.2⟩, (iffOwner _).mpr
+ (by simpa [e.prop.1] using D.real e.val)⟩
+ refine (Fintype.card_congr (Equiv.ofBijective f ⟨?_, ?_⟩)).symm
+ · intro x y he; exact Subtype.ext (D.address.injective (Fin.ext (congrArg (fun i : I ↦ i.val.val) he)))
+ · intro i
+ obtain ⟨e, ha, ho⟩ := (D.real_iff _ b).mp ((iffOwner i.val).mp i.prop)
+ have ha' : (D.address e).val = i.val.val := congrArg Fin.val ha
+ exact ⟨⟨e, ho, ha' ▸ i.val.isLt⟩, Subtype.ext (Fin.ext ha')⟩
+
+private theorem capacity [Fintype E] {deg : ℕ} (hdeg : 0 < deg)
+ (hcount : ∀ b, Fintype.card {e // D.owner e = b} ≤ deg) (hA : A ≤ 2^w) (hB : B+A ≤ 2^w)
+ (u : Word w) (hu : u.val < B+A) : (preimagePrefix D.wordOwner u A).length ≤ deg := by
+ let b : Fin (B+A) := ⟨u.val, hu⟩
+ have he : Fin.ofNat (2^w) b.val = u := Fin.ext (Nat.mod_eq_of_lt u.isLt)
+ have hlen := encodedPlacement_rowLength (Equiv.refl (Fin A)) (Equiv.refl (Fin (B+A))) D.destination hA hB b
+ change (preimagePrefix D.wordOwner (Fin.ofNat (2^w) b.val) A).length = _ at hlen
+ rw [← he, hlen]
+ obtain ⟨v | a, hb⟩ := (@finSumFinEquiv B A).surjective b
+ · rw [← hb]
+ have bij : {e // D.owner e = v} ≃ {i // D.destination i = v.castAdd A} :=
+ Equiv.ofBijective (fun e ↦ ⟨D.address e.val, (D.real e.val).trans (congrArg (Fin.castAdd A) e.prop)⟩)
+ ⟨fun _ _ h ↦ Subtype.ext (D.address.injective (congrArg Subtype.val h)),
+ fun i ↦ by
+ obtain ⟨e, ha, ho⟩ := (D.real_iff i.val v).mp i.prop
+ exact ⟨⟨e,ho⟩, Subtype.ext ha⟩⟩
+ exact (Fintype.card_congr bij).symm.le.trans (hcount v)
+ · rw [← hb]
+ apply le_trans _ hdeg
+ apply Fintype.card_le_one_iff_subsingleton.mpr
+ exact ⟨fun x y ↦ Subtype.ext ((D.hole_eq x.val a x.prop).trans (D.hole_eq y.val a y.prop).symm)⟩
+
+/-- The count and bounded row arrays lie immediately after the owner stream. -/
+def parameters (w base A B deg : ℕ) : Fin 6 → Word w :=
+ ![Fin.ofNat _ A, Fin.ofNat _ base, Fin.ofNat _ (B+A), Fin.ofNat _ (base+A),
+ Fin.ofNat _ deg, Fin.ofNat _ (base+A+(B+A))]
+
+private theorem parameter_values {base deg : ℕ} (hfit : base+A+(B+A)+(B+A)*deg < 2^w)
+ (hdeg : deg < 2^w) :
+ let p := parameters w base A B deg
+ (p 0).val = A ∧ (p 1).val = base ∧ (p 2).val = B+A ∧ (p 3).val = base+A ∧
+ (p 4).val = deg ∧ (p 5).val = base+A+(B+A) := by
+ dsimp [parameters, Fin.ofNat]
+ repeat' apply And.intro
+ all_goals apply Nat.mod_eq_of_lt; omega
+
+/-- A complete sequence of native append calls fills all rows. Empty row
+counters are the only initialization needed beyond the selected owner stream. -/
+theorem fill_run [Fintype E] {base deg : ℕ} (hdeg : 0 < deg) (hdw : deg < 2^w)
+ (hcount : ∀ b, Fintype.card {e // D.owner e = b} ≤ deg)
+ (hfit : base+A+(B+A)+(B+A)*deg < 2^w) (mem : Memory w)
+ (howners : ∀ i : Word w, i.val < A → mem (base + i.val) = D.wordOwner i)
+ (hzero : ∀ u : Word w, u.val < B+A → mem (base+A+u.val) = 0) :
+ let p := parameters w base A B deg
+ let M := (template collectPreimage 3).instantiate w p
+ ∃ rs, runSegment M.program 23 (some 0) mem (List.replicate A []) = some rs ∧
+ PreimagesAt p D.wordOwner (after mem (eventLog rs)) A ∧ rs.length = A ∧
+ RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = 5 * A ∧
+ ∀ r ∈ rs, r.events.length = 22 := by
+ intro p M
+ obtain ⟨h0,h1,h2,h3,h4,h5⟩ := parameter_values (A := A) (B := B) hfit hdw
+ change (p 0).val = A at h0
+ change (p 1).val = base at h1
+ change (p 2).val = B+A at h2
+ change (p 3).val = base+A at h3
+ change (p 4).val = deg at h4
+ change (p 5).val = base+A+(B+A) at h5
+ have reg : RowRegions p := ⟨by rw [h1,h0,h3], by rw [h3,h2,h5], by rw [h5,h2,h4]; omega⟩
+ have start : PreimagesAt p D.wordOwner mem 0 := by
+ constructor
+ · intro i hi
+ change i.val < (p 0).val at hi
+ rw [h0] at hi
+ simpa [ownerAt, Fin.val_add, h1, Nat.mod_eq_of_lt (by omega : base + i.val < 2^w)] using howners i hi
+ · intro u hu
+ change u.val < (p 2).val at hu
+ rw [h2] at hu
+ simp [rowRepresents, countAt, Fin.val_add, h3, Nat.mod_eq_of_lt (by omega : base+A+u.val < 2^w),
+ hzero u hu, preimagePrefix]
+ have legal (i : Word w) (hi : i < p 0) : D.wordOwner i < p 2 := by
+ change i.val < (p 0).val at hi
+ let j : Fin A := ⟨i.val, h0 ▸ hi⟩
+ have he : Fin.ofNat (2^w) j.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt)
+ change (D.wordOwner i).val < (p 2).val
+ rw [← he, owner_eq D (by omega) (by omega) j, h2]; exact (D.destination j).isLt
+ have cap (v : Word w) (hv : v < p 2) : (preimagePrefix D.wordOwner v (p 0).val).length ≤ (p 4).val := by
+ rw [h0,h4]; exact capacity D hdeg hcount (by omega) (by omega) v (h2 ▸ hv)
+ obtain ⟨rs, hr, ha, hl, hw⟩ := collectPreimages_run reg legal cap start A (by rw [h0]; omega)
+ exact ⟨rs, hr, by simpa only [Nat.zero_add] using ha, hl, (preimagePass_cost (fun q hq ↦ (hw q hq).2)).trans (by rw [hl]),
+ fun q hq ↦ (hw q hq).1⟩
+
+/-- The entry indexed by the number of earlier incident fields is exactly
+this field. This read uses a single directly addressed cell in the filled array. -/
+theorem stored_at_rank [Fintype E] (p : Fin 6 → Word w) (mem : Memory w)
+ (hA : A ≤ 2^w) (hB : (p 2).val = B+A) (h : PreimagesAt p D.wordOwner mem A) (e : E) :
+ let owner := Fin.ofNat (2^w) (D.owner e).val
+ let rank := Fintype.card {x // D.owner x = D.owner e ∧ D.address x < D.address e}
+ mem ((rowAt p owner).val + rank) = Fin.ofNat (2^w) (D.address e).val := by
+ intro owner rank
+ have hsum : B+A < 2^w := hB ▸ (p 2).isLt
+ have ho : owner.val = (D.owner e).val := Nat.mod_eq_of_lt ((D.owner e).isLt.trans_le (by omega))
+ have hb : owner < p 2 := by change owner.val < (p 2).val; rw [ho,hB]; have := (D.owner e).isLt; omega
+ let j := (D.address e).val
+ let id := Fin.ofNat (2^w) j
+ have howner : D.wordOwner id = owner := Fin.ext (by rw [owner_eq D hA hsum.le (D.address e), D.real, ho]; rfl)
+ have hlen : (preimagePrefix D.wordOwner owner j).length = rank :=
+ real_prefix_length D hA hsum.le (D.owner e) j (D.address e).isLt.le
+ have hstep : preimagePrefix D.wordOwner owner (j+1) = preimagePrefix D.wordOwner owner j ++ [id] := by
+ simp only [preimagePrefix, List.range_succ, List.map_append, List.map_singleton, List.filter_append,
+ List.filter_cons, List.filter_nil, beq_iff_eq]
+ rw [ite_eq_left howner]
+ obtain ⟨n, hn⟩ := Nat.exists_eq_add_of_le (show j+1 ≤ A from (D.address e).isLt)
+ have pref : preimagePrefix D.wordOwner owner (j+1) <+: preimagePrefix D.wordOwner owner A := by
+ conv_rhs => arg 3; rw [hn]
+ conv_rhs => rw [preimagePrefix, List.range_add, List.map_append, List.filter_append]
+ exact List.prefix_append _ _
+ rw [hstep] at pref
+ have hi : rank < (preimagePrefix D.wordOwner owner j ++ [id]).length := by simp [hlen]
+ have hg := pref.getElem hi
+ rw [List.getElem_append_right hlen.le] at hg
+ simp only [hlen, Nat.sub_self, List.getElem_cons_zero] at hg
+ exact (h.rows owner hb).2 ⟨rank, hi.trans_le pref.length_le⟩ |>.trans hg.symm
+
+/-- Number fields first by their row owner and then by increasing numeric
+field address within the row. Every real row has the fixed degree `deg`. -/
+noncomputable def sortedFields [Fintype E] (deg : ℕ) (hc : ∀ b, Fintype.card {e // D.owner e = b} = deg) :
+ E ≃ Fin (B * deg) :=
+ let := LinearOrder.lift' D.address D.address.injective
+ ((Equiv.sigmaFiberEquiv D.owner).symm.trans (Equiv.sigmaEquivProdOfEquiv fun b ↦
+ (Fintype.orderIsoFinOfCardEq {e // D.owner e = b} (hc b)).symm.toEquiv)).trans finProdFinEquiv
+
+/-- The contiguous real rows have this concrete rectangular address order. -/
+theorem sortedFields_val [Fintype E] (deg : ℕ) (hc : ∀ b, Fintype.card {e // D.owner e = b} = deg) (e : E) :
+ (sortedFields D deg hc e).val =
+ Fintype.card {x // D.owner x = D.owner e ∧ D.address x < D.address e} + deg * (D.owner e).val := by
+ let := LinearOrder.lift' D.address D.address.injective
+ let F := {x // D.owner x = D.owner e}
+ let label := (Fintype.orderIsoFinOfCardEq F (hc (D.owner e))).symm
+ let a : F := ⟨e,rfl⟩
+ let ordered := label.toEquiv.subtypeEquiv (p := fun x : F ↦ x < a)
+ (q := fun j : Fin deg ↦ j.val < (label a).val) (fun x ↦ by change x < a ↔ label x < label a; simp)
+ let members : {x : F // x < a} ≃ {x // D.owner x = D.owner e ∧ D.address x < D.address e} :=
+ ⟨fun x ↦ ⟨x.1.1, x.1.2, x.2⟩, fun x ↦ ⟨⟨x.1, x.2.1⟩, x.2.2⟩, fun _ ↦ rfl, fun _ ↦ rfl⟩
+ change (label a).val + _ = _
+ congr 1
+ rw [← Fintype.card_fin_lt_of_le (label a).isLt.le, ← Fintype.card_congr ordered, Fintype.card_congr members]
+
+/-- Every cell of the real rectangular array holds its designated absolute
+endpoint field. The spare rows for holes follow the entire real array. -/
+theorem rectangular_rows [Fintype E] (base deg : ℕ) (hc : ∀ b, Fintype.card {e // D.owner e = b} = deg)
+ (hfit : base+A+(B+A)+(B+A)*deg < 2^w) (hdw : deg < 2^w) (m : Memory w)
+ (h : PreimagesAt (parameters w base A B deg) D.wordOwner m A) (j : Fin (B*deg)) :
+ m (base+A+(B+A) + j.val) = Fin.ofNat _ (D.address ((sortedFields D deg hc).symm j)).val := by
+ let p := parameters w base A B deg
+ obtain ⟨_,_,h2,_,h4,h5⟩ := parameter_values (A := A) (B := B) hfit hdw
+ obtain ⟨e, rfl⟩ := (sortedFields D deg hc).surjective j
+ rw [Equiv.symm_apply_apply]
+ let u := Fin.ofNat (2^w) (D.owner e).val
+ have hu : u.val = (D.owner e).val := Nat.mod_eq_of_lt ((D.owner e).isLt.trans_le (by omega))
+ have hl := Nat.mul_le_mul_right deg ((D.owner e).isLt.le.trans (Nat.le_add_right B A))
+ have hrow : (rowAt p u).val = base+A+(B+A) + (D.owner e).val * deg := by
+ rw [rowAt, Fin.val_add, Fin.val_mul, hu, show (p 4).val = deg from h4,
+ show (p 5).val = _ from h5, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)]
+ have hs := stored_at_rank D p m (by omega) h2 h e
+ change m ((rowAt p u).val + _) = _ at hs
+ rw [hrow] at hs
+ rw [sortedFields_val, Nat.mul_comm deg, Nat.add_comm (Fintype.card _), ← Nat.add_assoc]
+ exact hs
+
+/-- Direct row lookup and its inverse, after both native array passes. -/
+structure Tables [Fintype E] (deg rows inverse : ℕ) (hc : ∀ b, Fintype.card {e // D.owner e = b} = deg)
+ (m : Memory w) : Prop where
+ bySlot : ∀ e, m (rows + (sortedFields D deg hc e).val) = Fin.ofNat _ (D.address e).val
+ byField : ∀ e, m (inverse + (D.address e).val) = Fin.ofNat _ (sortedFields D deg hc e).val
+
+/-- Allocate the inverse immediately after all bounded rows. -/
+def scatterParameters (w base A B deg : ℕ) : Fin 2 → Word w :=
+ let rows := base+A+(B+A)
+ ![Fin.ofNat _ rows, Fin.ofNat _ (rows+(B+A)*deg)]
+
+/-- First fill the rectangular rows, then invert only the real rows. The
+scatter pass starts with the physical post-memory of the population pass.
+The two final tables agree on every occupied field. -/
+theorem build_tables [Fintype E] {base deg : ℕ} (hdeg : 0 < deg) (hdw : deg < 2^w)
+ (hc : ∀ b, Fintype.card {e // D.owner e = b} = deg)
+ (hfit : base+A+(B+A)+(B+A)*deg+A < 2^w) (mem : Memory w)
+ (howners : ∀ i : Word w, i.val < A → mem (base + i.val) = D.wordOwner i)
+ (hzero : ∀ u : Word w, u.val < B+A → mem (base+A+u.val) = 0) :
+ let p := parameters w base A B deg
+ let q := scatterParameters w base A B deg
+ let M := (template collectPreimage 3).instantiate w p
+ let S := (template SlotScatter.visit 0).instantiate w q
+ let rows := base+A+(B+A)
+ let inverse := rows+(B+A)*deg
+ ∃ rs ss, runSegment M.program 23 (some 0) mem (List.replicate A []) = some rs ∧
+ runSegment S.program 10 (some 0) (after mem (eventLog rs)) (List.replicate (B*deg) []) = some ss ∧
+ Tables D deg rows inverse hc (after (after mem (eventLog rs)) (eventLog ss)) ∧
+ endState (some 0) rs = some (Fin.ofNat (2^w) A) ∧ endState (some 0) ss = some (Fin.ofNat _ (B*deg)) ∧
+ (∀ a, a < base+A ∨ inverse+A ≤ a → after (after mem (eventLog rs)) (eventLog ss) a = mem a) ∧
+ rs.length = A ∧ ss.length = B*deg ∧
+ RAMBuckets.cost Report.probes rs + RAMBuckets.cost Report.probes ss = 5*A + 3*(B*deg) ∧
+ (∀ r ∈ rs, r.events.length = 22) ∧ ∀ r ∈ ss, r.events.length = 9 := by
+ intro p q M S rows inverse
+ obtain ⟨rs, hrun, hrows, hlen, hcost, hwork⟩ := fill_run D hdeg hdw (fun b ↦ (hc b).le)
+ (base := base) (by omega) mem howners hzero
+ let m := after mem (eventLog rs)
+ let f := (sortedFields D deg hc).symm.toEmbedding.trans D.address
+ have hr : (q 0).val = rows := Nat.mod_eq_of_lt (by omega)
+ have hi : (q 1).val = inverse := Nat.mod_eq_of_lt (by omega)
+ have hrect : rows+B*deg ≤ inverse := Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.le_add_right B A)) rows
+ have reg : SlotScatter.Regions q (B*deg) A := by
+ refine ⟨?_, ?_, Or.inl ?_⟩
+ · rw [hr]; exact hrect.trans (hi ▸ (q 1).isLt.le)
+ · rw [hi]; exact hfit.le
+ · rw [hr,hi]; exact hrect
+ have stored (j : Fin (B*deg)) : m ((q 0).val + j.val) = Fin.ofNat _ (f j).val := by
+ rw [hr]
+ exact rectangular_rows D base deg hc (by omega) hdw m hrows j
+ obtain ⟨ss, hscatter, hcursor, hbyField, hframe, hlen', hwork', hcost'⟩ := SlotScatter.run reg f m stored
+ obtain ⟨h0,h1,h2,h3,h4,h5⟩ := parameter_values (A := A) (B := B) (base := base) (deg := deg)
+ (by omega : base+A+(B+A)+(B+A)*deg < 2^w) hdw
+ have rowReg : RowRegions p := ⟨by rw [h1,h0,h3], by rw [h3,h2,h5], by rw [h5,h2,h4]; omega⟩
+ obtain ⟨hfillCursor, hfillFrame⟩ := collectPreimages_frame (k := 0) rowReg hrun
+ change endState (some 0) rs = some (Fin.ofNat (2^w) (0+A)) at hfillCursor
+ refine ⟨rs, ss, hrun, hscatter, ⟨?_, ?_⟩, by simpa only [Nat.zero_add] using hfillCursor, hcursor, ?_, hlen, hlen', by rw [hcost', ← hcost]; rfl, hwork,
+ fun r hr ↦ (hwork' r hr).1⟩
+ · intro e
+ let j := sortedFields D deg hc e
+ have hj : f j = D.address e := congrArg D.address ((sortedFields D deg hc).symm_apply_apply e)
+ have hpres := hframe (rows+j.val) (fun x ↦ by rw [hi]; have := j.isLt; omega)
+ exact hpres.trans (by simpa only [hr,hj] using stored j)
+ · intro e
+ let j := sortedFields D deg hc e
+ have hj : f j = D.address e := congrArg D.address ((sortedFields D deg hc).symm_apply_apply e)
+ simpa only [hi,hj] using hbyField j
+ · intro a ha
+ have hs := hframe a (fun j ↦ by rw [hi]; have := (f j).isLt; omega)
+ exact hs.trans (hfillFrame a (by rw [h3,h5,h2,h4]; omega))
+
+end CompressorRecords.SlotSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotSelectedAccess.lean b/lean/OAI/Computability/VPVNP/CompressorSlotSelectedAccess.lean
new file mode 100644
index 0000000000..e7c66a8325
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotSelectedAccess.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.CompressorSlotPostAccess
+import OAI.Computability.VPVNP.CompressorSlotCopyLayout
+
+/-!
+# Eventwise memory bounds for the full selected shrinking slot program
+
+The 22-stage source walk records each chronological worker execution together
+with every actual external address it read or wrote. The final six scans copy
+the resulting graph into the canonical descriptor directory of the next level.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlotPlan.Scheduled
+
+open Compression Compression.State Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion Slots SlotLevel ShrinkSlots BurstRAM
+
+variable {a b g w : ℕ} {δ factor : ℝ} {k : Type*} [_root_.Field k]
+variable (X : State a (packingLaneBits a g))
+variable (B : FixedBlock k demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection B)
+
+/-- An address writable by the selected slot schedule, either in its construction workspace or
+in the six-column packed incidence destination. -/
+def writeData (s : SlotLevel.Shape) (h : Heads) (start x : ℕ) :=
+ Build.writeRegion s h x ∨ start ≤ x ∧ x < start+6*actualCount s
+
+set_option maxHeartbeats 1000000 in
+/-- A fully bounded source execution of all 22 planner rows, with the exact
+selected state's incidence directory in the destination after the last copy. -/
+theorem selected_sources (P : Plan) (h : Heads) (splitHead : ℕ) (m : Memory w)
+ (r : Build.Construction w) (L : DescriptorSpace.Layout) (level : Fin L.levels) :
+ let s := levelShape (b := b) X
+ let side := selectedLayout X B sel
+ let Y := X.shrinkNext B ready sel
+ let T := directory s h w
+ let U := DescriptorSpace.packedIncidence L w level (actualCount s)
+ let start := DescriptorSpace.incidenceStart L level
+ let built := after m (eventLog r.all)
+ let copies := CopyIncidence.reports Y T U CopyIncidence.allColumns built
+ Build.Space s h splitHead w → DemandRAM.RoleColumns X side h.oldArc m →
+ r.Native s h splitHead side m → T.Represents Y (r.final m) →
+ DescriptorSpace.endAddress L < 2^w → actualCount s ≤ DescriptorSpace.slotCapacity L →
+ (finish s h ≤ start ∨ start+6*actualCount s ≤ targetsHead s h) →
+ SourceWalk (fun j mem rs ↦ Source P s h side splitHead U j mem rs ∧
+ LogAccess (Build.readRegion s h splitHead) (writeData s h start) rs) order m (r.all++copies) ∧
+ U.Represents Y (after m (eventLog (r.all++copies))) := by
+ intro s side Y T U start built copies sp roles native rep room capacity apart
+ obtain ⟨core,out,_⟩ := Build.post_access X B ready sel h splitHead m r sp roles native
+ have counts := next_counts X B ready sel
+ change Fintype.card Y.Base*2^b=baseArcs s ∧ Fintype.card Y.Base*2^g*2^b=actualCount s at counts
+ have h0 := sp.old
+ have h1 := sp.roles
+ have h2 := sp.next
+ have h3 := sp.subdiv
+ have hs : h.scratch ≤ rowsHead s h := by unfold rowsHead; omega
+ have hr : rowsHead s h ≤ targetsHead s h := by unfold targetsHead inverseHead; omega
+ have ht : targetsHead s h ≤ finish s h := by
+ unfold finish widthHead inHead outHead inverseBaseHead stopAddress shiftsHead; omega
+ let rd := Build.readRegion s h splitHead
+ let wr := writeData s h start
+ have lower := min_le_left h.oldArc splitHead
+ have core' : LogAccess rd wr r.passes.slots.all := LogAccess.mono core (fun _ ↦ id) (fun _ ↦ Or.inl)
+ have out' : LogAccess rd wr (r.passes.mates.all++r.passes.widths) := LogAccess.mono out (fun _ ↦ id) (fun _ ↦ Or.inl)
+ have srcBound := CopyIncidence.shrink_column_bounds Y s h counts.1 counts.2 sp.fit
+ have dstBound := CopyIncidence.packed_column_bounds Y s L level counts.2 room capacity
+ have endFit : start+6*actualCount s < 2^w := DescriptorSpace.packed_incidence_room L room level capacity
+ have lengths (c : Fin 6) : CopyIncidence.rows Y c = (Stage.copy c).limit s :=
+ CopyIncidence.shrink_rows Y s counts.1 counts.2 c
+ have pre : ∀ x, h.role ≤ x → x < rowsHead s h → wr x := fun x hx hy ↦
+ Or.inl (by change h.role ≤ x ∧ x < finish s h; omega)
+ have src (x) (cell : CopyIncidence.ColumnCell Y T x) : rd x := by
+ obtain ⟨c,hc⟩ := cell
+ change (T.column c).val ≤ x ∧ x < (T.column c).val + CopyIncidence.rows Y c at hc
+ have hs : targetsHead s h ≤ (T.column c).val ∧ (T.column c).val + CopyIncidence.rows Y c ≤ finish s h := srcBound c
+ change min h.oldArc splitHead ≤ x ∧ x < finish s h; omega
+ have dst (x) (cell : CopyIncidence.ColumnCell Y U x) : wr x := by
+ obtain ⟨c,hc⟩ := cell
+ have hd : (U.column c).val=start+c.val*actualCount s ∧
+ (U.column c).val+CopyIncidence.rows Y c ≤ start+6*actualCount s := dstBound c
+ exact Or.inr (by omega)
+ have regs := CopyIncidence.Regions.shrink_to_level Y s h L level counts.1 counts.2 sp.fit room capacity apart
+ have repBuilt : T.Represents Y built := by simpa only [built, ← r.final_eq m] using rep
+ have copied := (CopyIncidence.copy_directory Y T U built regs repBuilt).2.1
+ refine ⟨sources_with_footprints P s h side splitHead U Y r m native lengths h1 h2 h3
+ ((by omega : rowsHead s h ≤ finish s h).trans_lt sp.fit) (fun c ↦ (srcBound c).2.trans sp.fit.le)
+ (fun c ↦ (dstBound c).2.trans endFit.le) rd wr pre src dst core' out',?_⟩
+ simpa only [eventLog,List.flatMap_append,after,List.foldl_append,built,copies] using copied
+
+end CompressorRecords.ShrinkSlotPlan.Scheduled
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotState.lean b/lean/OAI/Computability/VPVNP/CompressorSlotState.lean
new file mode 100644
index 0000000000..82fdd712c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotState.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.CompressorSlotLevelRun
+import OAI.Computability.VPVNP.ShrinkStatePass
+import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout
+import OAI.Computability.VPVNP.BitSlotXor
+
+/-!
+# Passing the sorted shrinking graph to the next compressor state
+
+The graph used by `State.shrinkNext` uses the same current base index, binary
+tag index, subdivisions and common layout as the native slot builder. Its
+base-arc numbers are exactly the ordinary port numbers in the shared
+incidence directory. A scatter of the forward base table constructs the
+inverse at the same numerical indices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots
+
+open Compression Compression.State Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion Slots SlotLevel SlotOwners SlotSchedule
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {a b g w : ℕ} {δ factor : ℝ} {k : Type*} [Field k]
+variable (X : State a (packingLaneBits a g))
+variable (B : FixedBlock k demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection B)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Slot directory dimensions for this shrink, using the current base vertices and residual
+lanes and the subdivisions chosen for the outgoing degree. -/
+noncomputable abbrev levelShape : Shape :=
+ ⟨Fintype.card X.Base,2^(packingTagBits (2^a)),2^g,2^a,2*2^a+1,subdivisions (2^a) (2*2^a+1) (2^b),2^b⟩
+
+/-- The layout with lower group energy for the selected term's widths, choosing the false
+layout on a tie. -/
+noncomputable abbrev selectedLayout :=
+ chosenLayout (equalArcMass (Position X.Base (BitWord a) (BitWord (packingTagBits (2^a))) (BitWord g) (2*2^a+1)) (2^a))
+ (fun e ↦ (relativeMass e : ℝ)) (X.packingData.termWidths B X.shrinkNumber X.packingWidth sel)
+
+/-- Base columns shared by the following level in the canonical port order. -/
+structure BaseForward {a l : ℕ} (Y : State a l) (target shift : ℕ) (mem : Memory w) : Prop where
+ mate : ∀ e, mem (target+(IncidenceDirectory.baseOrder Y e).val) = Fin.ofNat _ (IncidenceDirectory.baseOrder Y (Y.slots.base.target e)).val
+ displacement : ∀ e, mem (shift+(IncidenceDirectory.baseOrder Y e).val) = Fin.ofNat _ (bitWordFinEquiv l (Y.slots.displacement e)).val
+
+/-- The kernel's actual branch and the native builder have identical topology. -/
+theorem next_baseMatching (targets shifts : ℕ) (m : Memory w) :
+ let l := selectedLayout X B sel
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let I := X.shrinkStateIndex ready l
+ BaseMatching X.baseIndex tags (bitWordFinEquiv g) I.graph targets shifts m →
+ BaseForward (X.shrinkNext B ready sel) targets shifts m := by
+ intro l tags I h
+ let Y := X.shrinkNext B ready sel
+ have idx (e : Y.Base × Fin (2^b)) : (IncidenceDirectory.baseOrder Y e).val =
+ (SlotSchedule.baseIndex X.baseIndex tags e).val := rfl
+ constructor
+ · intro e
+ rw [idx,idx]
+ exact Fin.ext ((h.targetAt e).trans (Nat.mod_eq_of_lt ((h.targetAt e) ▸ (m _).isLt)).symm)
+ · intro e
+ rw [idx]
+ exact Fin.ext ((h.shiftAt e).trans (Nat.mod_eq_of_lt ((h.shiftAt e) ▸ (m _).isLt)).symm)
+
+/-- Native slot construction directly on the same selected state as the
+compression kernel, using the canonical next-level port addresses. -/
+theorem next_run (h : Heads) (mem : Memory w) (hdw : 2^b < 2^w) :
+ let s := levelShape (b := b) X
+ let l := selectedLayout X B sel
+ let p := X.packingData
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let lanes := bitWordFinEquiv g
+ let g₀ := bank s h w .genuineOwners
+ let d₀ := bank s h w .dummyOwners
+ let D := slotDirectory p s.subdivisions X.baseIndex tags lanes l (pad := pad s)
+ let hD := fun owner ↦ (slotDirectory_degree p s.subdivisions X.baseIndex tags lanes (two_le_packingColors a) l owner).trans
+ (Nat.add_sub_of_le ready.degree_budget)
+ GenuineTables p s.subdivisions X.baseIndex tags lanes l g₀ mem →
+ DummyTables X.baseIndex tags lanes (pad s) d₀ mem →
+ h.oldArc+4*(oldBaseArcCount s.bases s.tags s.oldDegree s.colors*s.lanes) ≤ h.scratch →
+ h.role+8 ≤ h.scratch → h.subdivisions+4 ≤ h.scratch → h.nextSite+sites s ≤ h.scratch → stopAddress s h < 2^w →
+ (∀ u : Word w, u.val < owners s+fields s → mem (h.scratch+fields s+u.val)=0) →
+ ∃ r : Reports w, r.Native s h mem ∧ r.Cursors s ∧
+ Tables D (2^b) (rowsHead s h) (inverseHead s h) hD (r.final mem) ∧
+ BaseForward (X.shrinkNext B ready sel) (targetsHead s h) (shiftsHead s h) (r.final mem) ∧
+ (∀ addr, addr < h.scratch ∨ stopAddress s h ≤ addr → r.final mem addr = mem addr) ∧
+ RAMBuckets.cost Report.probes r.all =
+ 6*genuineCount s+3*dummyCount s+5*fields s+3*(owners s*2^b)+5*baseArcs s := by
+ intro s l p tags lanes g₀ d₀ D hD hg hp ho hr hs hn fit hz
+ have hJ : 1 < 2^packingTagBits (2^a) := Nat.one_lt_two_pow (Nat.succ_pos _).ne'
+ have hlane : (lanes 0).val = 0 := by simpa using bitWordFinEquiv_add_val (0 : BitWord g) 0
+ obtain ⟨r,hNative,hCursors,tab,hBase,hFrame,hCost,_⟩ := SlotLevel.run_selected p s.subdivisions X.baseIndex tags lanes l h
+ (two_le_packingColors a) (orderedDyadicPacking_validTags X.slots X.baseIndex) ready.degree_budget hJ hlane
+ (Nat.two_pow_pos b) hdw mem hg hp ho hr hs hn fit hz
+ exact ⟨r,hNative,hCursors,tab,next_baseMatching X B ready sel _ _ _ hBase,hFrame,hCost⟩
+
+/-- Inverting the canonical base-mate permutation needs one two-probe
+scatter per base port. Forward and shift columns survive in separate arrays. -/
+theorem scatterBaseIn {a l : ℕ} (Y : State a l) (m : Memory w) (p : Fin 2 → Word w) (shift : ℕ)
+ (regions : SlotScatter.Regions p (Fintype.card Y.Base * 2^a) (Fintype.card Y.Base * 2^a))
+ (forward : BaseForward Y (p 0).val shift m)
+ (hshift : shift+(Fintype.card Y.Base * 2^a) ≤ (p 1).val ∨ (p 1).val+(Fintype.card Y.Base * 2^a) ≤ shift) :
+ let n := Fintype.card Y.Base * 2^a
+ let worker := ((template SlotScatter.visit 0).instantiate w p).program
+ ∃ rs, runSegment worker 10 (some 0) m (List.replicate n []) = some rs ∧
+ endState (some 0) rs = some (Fin.ofNat _ n) ∧
+ BaseForward Y (p 0).val shift (after m (eventLog rs)) ∧
+ (∀ e, after m (eventLog rs) ((p 1).val+(IncidenceDirectory.baseOrder Y e).val) =
+ Fin.ofNat _ (IncidenceDirectory.baseOrder Y (Y.slots.base.target.symm e)).val) ∧
+ (∀ addr, addr < (p 1).val ∨ (p 1).val+n ≤ addr → after m (eventLog rs) addr = m addr) ∧
+ RAMBuckets.cost Report.probes rs = 3*n := by
+ intro n worker
+ let o := IncidenceDirectory.baseOrder Y
+ let t := o.symm.trans (Y.slots.base.target.trans o)
+ have stored (i : Fin n) : m ((p 0).val+i.val) = Fin.ofNat _ (t i).val := by
+ have h := forward.mate (o.symm i)
+ change m ((p 0).val+(o (o.symm i)).val) = _ at h
+ rwa [o.apply_symm_apply] at h
+ obtain ⟨rs,hr,hc,hvals,hframe,_,_,hcost⟩ := SlotScatter.run regions t.toEmbedding m stored
+ refine ⟨rs,hr,hc,⟨?_,?_⟩,?_,?_,hcost⟩
+ · intro e
+ rw [hframe,forward.mate]
+ intro i; have he := (o e).isLt; have ht := (t i).isLt; have := regions.disjoint; change _+ (o e).val ≠ _+(t i).val; omega
+ · intro e
+ rw [hframe,forward.displacement]
+ intro i; have he := (o e).isLt; have ht := (t i).isLt; change _+(o e).val ≠ _+(t i).val; omega
+ · intro e
+ have hx : t (o (Y.slots.base.target.symm e)) = o e := by simp [t]
+ simpa only [Equiv.coe_toEmbedding,hx] using hvals (o (Y.slots.base.target.symm e))
+ · intro addr ha
+ exact hframe addr (fun i ↦ by have hi := (t i).isLt; change addr ≠ _+(t i).val; omega)
+
+end CompressorRecords.ShrinkSlots
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotWidth.lean b/lean/OAI/Computability/VPVNP/CompressorSlotWidth.lean
new file mode 100644
index 0000000000..6e87ded13a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotWidth.lean
@@ -0,0 +1,217 @@
+import OAI.Computability.VPVNP.CompressorSlotWidthScan
+import OAI.Computability.VPVNP.CompressorSlotBaseLookup
+import OAI.Computability.VPVNP.ShrinkPayload
+
+/-!
+# Width lookup on the sorted shrinking output
+
+The split array is indexed by original old arc (including its lane), role-edge
+type, and local subdivision. The canonical outgoing array is indexed by the new
+site and its local slot. The two lookups refer to the same selected motif.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotWidthScan
+
+open Compression Compression.PackingData Compression.SurvivingSlots Slots SlotSchedule BurstRAM PrimedStackRAM
+
+variable {V H Tag L : Type} {d c N J nL degree pad w : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+/-- The chosen widths in the contiguous old-arc/type/subdivision rows. -/
+def SplitRows (oldWidth : P.Motif → Fin 4 → ℕ) (base : ℕ) (m : Memory w) : Prop :=
+ ∀ i : Id P.Motif subdiv,
+ m (base + (((oldArcIndex P vertices tags lanes i.2.1.val).val*4+i.1.val)*(∑ t,subdiv t)+i.2.2.val)) =
+ Fin.ofNat _ (splitWidth (oldWidth i.2.1 i.1) (subdiv i.1) i.2.2)
+
+theorem splitOffset_lt (i : Id P.Motif subdiv) :
+ ((oldArcIndex P vertices tags lanes i.2.1.val).val*4+i.1.val)*(∑t,subdiv t)+i.2.2.val <
+ (oldBaseArcCount N J d c*nL)*4*(∑t,subdiv t) := by
+ let n := (oldArcIndex P vertices tags lanes i.2.1.val).val
+ have ho := Nat.mul_le_mul_right 4 (Nat.succ_le_of_lt (oldArcIndex P vertices tags lanes i.2.1.val).isLt)
+ rw [Nat.succ_mul] at ho
+ have ht : n*4+i.1.val+1 ≤ (oldBaseArcCount N J d c*nL)*4 := by have := i.1.isLt; omega
+ have hu := Nat.mul_le_mul_right (∑t,subdiv t) ht
+ rw [Nat.succ_mul] at hu
+ have hj : i.2.2.val < ∑t,subdiv t := i.2.2.isLt.trans_le
+ (Finset.single_le_sum (fun t _ ↦ Nat.zero_le (subdiv t)) (Finset.mem_univ i.1))
+ change (n*4+i.1.val)*(∑t,subdiv t)+i.2.2.val < _; omega
+
+theorem SplitRows.congr_below {oldWidth : P.Motif → Fin 4 → ℕ} {base stop : ℕ} {m m' : Memory w}
+ (split : SplitRows P subdiv vertices tags lanes oldWidth base m)
+ (room : base+(oldBaseArcCount N J d c*nL)*4*(∑t,subdiv t) ≤ stop) (frame : ∀ a < stop, m' a=m a) :
+ SplitRows P subdiv vertices tags lanes oldWidth base m' := by
+ intro i
+ rw [frame _ (by have := splitOffset_lt P subdiv vertices tags lanes i; omega)]
+ exact split i
+
+private theorem divLow {n : ℕ} (x : Fin n) (h : ℕ) : (x.val+n*h)/n=h := by
+ rw [Nat.add_mul_div_left _ _ (Nat.zero_lt_of_lt x.isLt),Nat.div_eq_of_lt x.isLt,Nat.zero_add]
+private theorem modLow {n : ℕ} (x : Fin n) (h : ℕ) : (x.val+n*h)%n=x.val := by simp [Nat.mod_eq_of_lt x.isLt]
+
+/-- Reading the digits of a genuine absolute ID produces its exact split-row offset. -/
+theorem splitNumber_genuine (i : Id P.Motif subdiv) :
+ splitNumber nL (∑ t,subdiv t) (oldBaseArcCount N J d c)
+ (arcAddress P subdiv vertices tags lanes pad (.inl i)).val =
+ ((oldArcIndex P vertices tags lanes i.2.1.val).val*4+i.1.val)*(∑ t,subdiv t)+i.2.2.val := by
+ let old := P.baseMotifIndex vertices tags (P.baseMotif i.2.1)
+ let g := lanes (P.sourceLane i.2.1)
+ let j := i.2.2.castLE (Finset.single_le_sum (fun t _ ↦ Nat.zero_le (subdiv t)) (Finset.mem_univ i.1))
+ have hk : (relativeKey P subdiv vertices tags i).val = j.val + (∑ t,subdiv t)*(old.val+(oldBaseArcCount N J d c)*i.1.val) := by
+ change j.val+(∑ t,subdiv t)*old.val+(oldBaseArcCount N J d c*(∑ t,subdiv t))*i.1.val=_
+ ring
+ have ha : (arcAddress P subdiv vertices tags lanes pad (.inl i)).val = g.val + nL*(relativeKey P subdiv vertices tags i).val := rfl
+ have hold : (oldArcIndex P vertices tags lanes i.2.1.val).val = g.val+nL*old.val := rfl
+ rw [splitNumber,ha,divLow,modLow,hk,divLow,modLow,divLow,modLow,hold]
+ change _ = ( _ * 4 + i.1.val)*(∑ t,subdiv t)+j.val
+ ring
+
+/-- Ordinary new outgoing slot number: site first, local slot second. -/
+def portIndex : ((V × Tag) × L) × Fin degree ≃ Fin ((N*(J*nL))*degree) :=
+ ((((Equiv.prodAssoc V Tag L).trans (siteIndex vertices tags lanes)).prodCongr (Equiv.refl _))).trans finProdFinEquiv
+
+private theorem width_atLane (layout : Bool) (oldWidth : P.Motif → Fin 4 → ℕ)
+ (outgoing : PaddedId (V×Tag) (Id P.BaseMotif subdiv) pad ≃ (V×Tag)×Fin degree)
+ (z : PaddedId (V×Tag) (Id P.BaseMotif subdiv) pad) (g : L) :
+ P.shrinkSlotWidth layout subdiv oldWidth outgoing (outgoing z,g) =
+ Sum.elim (fun i : Id P.Motif subdiv ↦ splitWidth (oldWidth i.2.1 i.1) (subdiv i.1) i.2.2)
+ (fun _ ↦ 0) (atLane P subdiv layout z g) := by
+ cases z with
+ | inr p => exact P.shrinkSlotWidth_padding layout subdiv oldWidth outgoing p g
+ | inl z =>
+ let e := P.survivingLaneEquiv layout subdiv
+ have h := P.shrinkSlotWidth_genuine layout subdiv oldWidth outgoing (e.symm (z,g))
+ rw [P.shrinkArcEquiv_genuine] at h
+ change P.shrinkSlotWidth layout subdiv oldWidth outgoing
+ ((outgoing (.inl (e (e.symm (z,g))).1)),(e (e.symm (z,g))).2) = _ at h
+ rwa [e.apply_symm_apply] at h
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] [Module (ZMod 2) Tag]
+
+/-- One actual outgoing slot: both read addresses are inside their allocated
+input regions and the written word is the width used in the semantic shrinking step. -/
+theorem readback (layout : Bool) (oldWidth : P.Motif → Fin 4 → ℕ)
+ (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (hd : survivingDegree d c subdiv ≤ degree) (hJ : 1 < J) (p : Fin 8 → Word w) (m : Memory w)
+ (hdg : (p 0).val=degree) (hl : (p 1).val=nL) (hs : (p 2).val=∑ t,subdiv t)
+ (hb : (p 3).val=oldBaseArcCount N J d c) (hg : (p 4).val=keyCount N J d c subdiv*nL)
+ (hw : 2 < 2^w) (hrow : (p 5).val+((N*(J*nL))*2)*degree ≤ (p 7).val)
+ (hsplit : (p 6).val+(oldBaseArcCount N J d c*nL)*4*(∑t,subdiv t) ≤ (p 7).val)
+ (hs0 : (p 6).val < (p 7).val) (e : ((V×Tag)×L)×Fin degree) (split : SplitRows P subdiv vertices tags lanes oldWidth (p 6).val m) :
+ let pad := degree-survivingDegree d c subdiv
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad)
+ let hD := fun b ↦ (slotDirectory_degree P subdiv vertices tags lanes hc layout b).trans (Nat.add_sub_of_le hd)
+ let := P.slotIdentifierOrder vertices tags subdiv
+ let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ
+ let cursor := Fin.ofNat (2^w) (portIndex vertices tags lanes e).val
+ (∀ x, m ((p 5).val+(sortedFields D degree hD x).val) = Fin.ofNat _ (D.address x).val) →
+ RecordCount N J nL d c pad subdiv*2 ≤ 2^w →
+ (row p cursor).val < (p 7).val ∧ (splitAddr p m cursor).val < (p 7).val ∧
+ width p m cursor = Fin.ofNat _ (P.shrinkSlotWidth layout subdiv oldWidth I.outgoing ((e.1.1,e.2),e.1.2)) := by
+ intro pad D hD order I cursor tab fits
+ let p₀ := (e.1.1,e.2)
+ let z := I.outgoing.symm p₀
+ let i := atLane P subdiv layout z e.1.2
+ have hz : paddedBaseId P subdiv i = z := baseId_atLane P subdiv layout z e.1.2
+ have hsrc : I.outgoing z = p₀ := I.outgoing.apply_symm_apply p₀
+ have hend := (endpoints_atLane P subdiv tags layout z e.1.2).1
+ have hpos : actualEnd P subdiv tags layout false i = (e.1.1.1,e.1.1.2,e.1.2) :=
+ hend.trans (congrArg (fun b : V×Tag ↦ (b.1,b.2,e.1.2)) ((I.src_eq z).symm.trans (congrArg Prod.fst hsrc)))
+ let owner := siteIndex vertices tags lanes (e.1.1.1,e.1.1.2,e.1.2)
+ have hcursorBound : (portIndex vertices tags lanes e).val < ((N*(J*nL))*2)*degree :=
+ (portIndex vertices tags lanes e).isLt.trans_le (Nat.mul_le_mul_right degree (by omega))
+ have hv : cursor.val = (portIndex vertices tags lanes e).val := Nat.mod_eq_of_lt (by have := (p 7).isLt; omega)
+ have hrect : rowNumber (p 0).val cursor.val = (sortedFields D degree hD (i,0)).val := by
+ have h := rectangular_slot P subdiv vertices tags lanes hc hφ layout hd hJ i 0
+ change (sortedFields D degree hD (i,0)).val = (I.outgoing (paddedBaseId P subdiv i)).2.val+degree*(D.owner (i,0)).val at h
+ rw [hz,hsrc] at h
+ change (sortedFields D degree hD (i,0)).val = e.2.val+degree*(0+2*(siteIndex vertices tags lanes (actualEnd P subdiv tags layout false i)).val) at h
+ rw [h,hpos,hv,hdg]
+ change rowNumber degree (e.2.val+degree*owner.val) = e.2.val+degree*(0+2*owner.val)
+ rw [rowNumber,divLow,modLow]; ring
+ have hlt : (p 5).val+rowNumber (p 0).val cursor.val < (p 7).val := by
+ rw [hrect]; have hi : (sortedFields D degree hD (i,0)).val < ((N*(J*nL))*2)*degree := (sortedFields D degree hD (i,0)).isLt; omega
+ have hfa : (m ((p 5).val+rowNumber (p 0).val cursor.val)).val/2 = (arcAddress P subdiv vertices tags lanes pad i).val := by
+ rw [hrect,tab,Fin.val_ofNat,Nat.mod_eq_of_lt ((D.address (i,0)).isLt.trans_le fits)]
+ exact divLow (0 : Fin 2) (arcAddress P subdiv vertices tags lanes pad i).val
+ have hwidth := width_atLane P subdiv layout oldWidth I.outgoing z e.1.2
+ rw [hsrc] at hwidth
+ change P.shrinkSlotWidth layout subdiv oldWidth I.outgoing ((e.1.1,e.2),e.1.2) = Sum.elim _ _ i at hwidth
+ have hwval := width_eq p m cursor hw (hlt.trans (p 7).isLt)
+ dsimp only at hwval
+ rw [hfa,hl,hs,hb,hg] at hwval
+ refine ⟨(row_val p cursor hw (hlt.trans (p 7).isLt)).trans_lt hlt,?_⟩
+ cases he : i with
+ | inr x =>
+ have ge : ¬ (arcAddress P subdiv vertices tags lanes pad (.inr x)).val < keyCount N J d c subdiv*nL := by
+ change ¬ keyCount N J d c subdiv*nL + _ < _; omega
+ rw [he] at hwval hwidth
+ obtain ⟨haddr,hvalue⟩ := hwval (fun bad ↦ (ge bad).elim)
+ exact ⟨by simpa only [ite_eq_right ge,haddr] using hs0, by rw [hwidth]; exact hvalue.trans (ite_eq_right ge)⟩
+ | inl j =>
+ have real : (arcAddress P subdiv vertices tags lanes pad (.inl j)).val < keyCount N J d c subdiv*nL :=
+ (finProdFinEquiv (relativeKey P subdiv vertices tags j,lanes (P.sourceLane j.2.1))).isLt
+ rw [he] at hwval hwidth
+ rw [splitNumber_genuine] at hwval
+ let old := oldArcIndex P vertices tags lanes j.2.1.val
+ let idx := (old.val*4+j.1.val)*(∑ t,subdiv t)+j.2.2.val
+ have ho := Nat.mul_le_mul_right 4 (Nat.succ_le_of_lt old.isLt)
+ rw [Nat.succ_mul] at ho
+ have ht : old.val*4+j.1.val+1 ≤ (oldBaseArcCount N J d c*nL)*4 := by have := j.1.isLt; omega
+ have hu := Nat.mul_le_mul_right (∑t,subdiv t) ht
+ rw [Nat.succ_mul] at hu
+ have hj : j.2.2.val < ∑t,subdiv t := j.2.2.isLt.trans_le
+ (Finset.single_le_sum (fun t _ ↦ Nat.zero_le (subdiv t)) (Finset.mem_univ j.1))
+ have hi : (p 6).val+idx < (p 7).val := by dsimp only [idx]; omega
+ obtain ⟨haddr,hvalue⟩ := hwval (fun _ ↦ hi.trans (p 7).isLt)
+ rw [ite_eq_left real] at haddr hvalue
+ exact ⟨haddr.trans_lt hi, hvalue.trans (by rw [hwidth]; exact split j)⟩
+
+/-- Every canonical outgoing width is written once, including all zero-width
+slots and the dummy tail. -/
+theorem write_all (layout : Bool) (oldWidth : P.Motif → Fin 4 → ℕ)
+ (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (hd : survivingDegree d c subdiv ≤ degree) (hJ : 1 < J) (p : Fin 8 → Word w) (m : Memory w)
+ (hdg : (p 0).val=degree) (hl : (p 1).val=nL) (hs : (p 2).val=∑ t,subdiv t)
+ (hb : (p 3).val=oldBaseArcCount N J d c) (hg : (p 4).val=keyCount N J d c subdiv*nL)
+ (hw : 2 < 2^w) (hrow : (p 5).val+((N*(J*nL))*2)*degree ≤ (p 7).val)
+ (hsplit : (p 6).val+(oldBaseArcCount N J d c*nL)*4*(∑t,subdiv t) ≤ (p 7).val)
+ (hs0 : (p 6).val < (p 7).val) (split : SplitRows P subdiv vertices tags lanes oldWidth (p 6).val m)
+ (room : (p 7).val+(N*(J*nL))*degree ≤ 2^w) :
+ let pad := degree-survivingDegree d c subdiv
+ let D := slotDirectory P subdiv vertices tags lanes layout (pad := pad)
+ let hD := fun b ↦ (slotDirectory_degree P subdiv vertices tags lanes hc layout b).trans (Nat.add_sub_of_le hd)
+ let := P.slotIdentifierOrder vertices tags subdiv
+ let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ
+ let M := (template visit 0).instantiate w p
+ let n := (N*(J*nL))*degree
+ (∀ x, m ((p 5).val+(sortedFields D degree hD x).val) = Fin.ofNat _ (D.address x).val) →
+ RecordCount N J nL d c pad subdiv*2 ≤ 2^w →
+ ∃ rs, runSegment M.program 43 (some 0) m (List.replicate n []) = some rs ∧
+ endState (some 0) rs = some (Fin.ofNat _ n) ∧
+ (∀ e, after m (eventLog rs) ((p 7).val+(portIndex vertices tags lanes e).val) =
+ Fin.ofNat _ (P.shrinkSlotWidth layout subdiv oldWidth I.outgoing ((e.1.1,e.2),e.1.2))) ∧
+ (∀ addr, addr < (p 7).val ∨ (p 7).val+n ≤ addr → after m (eventLog rs) addr=m addr) ∧
+ RAMBuckets.cost Report.probes rs = 4*n := by
+ intro pad D hD order I M n tab hspace
+ have step e := readback P subdiv vertices tags lanes layout oldWidth hc hφ hd hJ p m hdg hl hs hb hg
+ hw hrow hsplit hs0 e split tab hspace
+ let ord := portIndex vertices tags lanes (degree := degree)
+ obtain ⟨rs,hr,cursor,written,frame,cost⟩ := run p m n room (fun j hj ↦ by
+ let e := ord.symm ⟨j,hj⟩
+ have hi : (portIndex vertices tags lanes e).val = j := congrArg Fin.val (ord.apply_symm_apply ⟨j,hj⟩)
+ obtain ⟨a,b,_⟩ := step e
+ rw [hi] at a b; exact ⟨a,b⟩)
+ exact ⟨rs,hr,cursor,fun e ↦ (written _ (ord e).isLt).trans (step e).2.2,frame,cost⟩
+
+end CompressorRecords.SlotWidthScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotWidthFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorSlotWidthFootprint.lean
new file mode 100644
index 0000000000..755f55435e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotWidthFootprint.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.CompressorSlotWidthState
+import OAI.Computability.VPVNP.CompressorSlotScanFootprint
+
+/-!
+# External addresses of the shrinking width scan
+
+The mask on the sparse width lookup bounds its offset even on arbitrary
+initial row words. A dummy reads the first input word. A genuine identifier
+decodes to a cell in the old-arc, edge-type and subdivision rectangle.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotWidthScan
+
+open Slots SlotLevel ShrinkSlots BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport
+
+private theorem splitNumber_lt {lanes sub old a : ℕ} (bound : a < (4*(old*sub))*lanes) :
+ splitNumber lanes sub old a < old*lanes*4*sub := by
+ have hl : 0 < lanes := Nat.pos_of_ne_zero (by rintro rfl; simp at bound)
+ have hs : 0 < sub := Nat.pos_of_ne_zero (by rintro rfl; simp at bound)
+ have ho : 0 < old := Nat.pos_of_ne_zero (by rintro rfl; simp at bound)
+ let key := a/lanes
+ let pair := key/sub
+ have ht : pair/old < 4 := by
+ change a/lanes/sub/old < 4
+ rw [Nat.div_lt_iff_lt_mul ho,Nat.div_lt_iff_lt_mul hs,Nat.div_lt_iff_lt_mul hl]
+ simpa only [Nat.mul_assoc] using bound
+ have hm := Nat.mul_le_mul_right lanes (Nat.succ_le_of_lt (Nat.mod_lt pair ho))
+ rw [Nat.succ_mul] at hm
+ have hx : pair%old*lanes+a%lanes < old*lanes := by have := Nat.mod_lt a hl; omega
+ have hy := Nat.mul_le_mul_right 4 (Nat.succ_le_of_lt hx)
+ rw [Nat.succ_mul] at hy
+ have hz : (pair%old*lanes+a%lanes)*4+pair/old < old*lanes*4 := by omega
+ have hu := Nat.mul_le_mul_right sub (Nat.succ_le_of_lt hz)
+ rw [Nat.succ_mul] at hu
+ change ((pair%old*lanes+a%lanes)*4+pair/old)*sub+key%sub < _
+ have := Nat.mod_lt key hs; omega
+
+private theorem rowNumber_lt {n d j : ℕ} (hj : j < n*d) : rowNumber d j < n*2*d := by
+ have hd : 0 < d := Nat.pos_of_ne_zero (by rintro rfl; simp at hj)
+ have hq : j/d < n := (Nat.div_lt_iff_lt_mul hd).mpr hj
+ have h := Nat.mul_le_mul_right d (show j/d*2+1 ≤ n*2 by omega)
+ rw [Nat.succ_mul] at h
+ have := Nat.mod_lt j hd
+ unfold rowNumber; omega
+
+/-- All reads lie in the initialized endpoint-row and split-width workspace.
+The only writes are the canonical outgoing widths. -/
+theorem run_footprint {w : ℕ} (s : SlotLevel.Shape) (h : Heads) (splitHead : ℕ) (m : Memory w)
+ (rs : List (Report w)) (twoFits : 2 < 2^w) (degreeFits : s.newDegree < 2^w)
+ (lanesFit : s.lanes < 2^w) (subFit : (∑ t, s.subdivisions t) < 2^w)
+ (oldFit : oldBaseArcCount s.bases s.tags s.oldDegree s.colors < 2^w)
+ (input : splitHead+(oldBaseArcCount s.bases s.tags s.oldDegree s.colors*s.lanes)*4*(∑ t,s.subdivisions t)
+ ≤ h.scratch) (first : splitHead < widthHead s h) (fit : finish s h < 2^w) :
+ let p := widthBank s h splitHead w
+ let P := ((template visit 0).instantiate w p).program
+ runSegment P 43 (some 0) m (List.replicate (actualCount s) []) = some rs →
+ Reads (fun a ↦ min splitHead (rowsHead s h) ≤ a ∧ a < widthHead s h) (eventLog rs) ∧
+ Writes (fun a ↦ widthHead s h ≤ a ∧ a < finish s h) (eventLog rs) := by
+ intro p P run
+ let old := oldBaseArcCount s.bases s.tags s.oldDegree s.colors
+ let sub := ∑ t, s.subdivisions t
+ have fend : h.scratch+fields s ≤ rowsHead s h := Nat.le_add_right _ _
+ have rend : rowsHead s h+owners s*s.newDegree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.le_add_right _ _)) _
+ have iend : inverseHead s h ≤ widthHead s h := by
+ dsimp only [widthHead,inHead,outHead,inverseBaseHead,stopAddress,shiftsHead,targetsHead]; omega
+ have endWidth : widthHead s h+actualCount s=finish s h := rfl
+ have sizes := counts_add s
+ have p0 : (p 0).val = s.newDegree := Nat.mod_eq_of_lt degreeFits
+ have p1 : (p 1).val = s.lanes := Nat.mod_eq_of_lt lanesFit
+ have p2 : (p 2).val = sub := Nat.mod_eq_of_lt subFit
+ have p3 : (p 3).val = old := Nat.mod_eq_of_lt oldFit
+ have p4 : (p 4).val = (4*(old*sub))*s.lanes := by
+ change ((4*(old*sub))*s.lanes)%(2^w) = _
+ change ((4*(old*sub))*s.lanes)*2+dummyCount s=fields s at sizes
+ exact Nat.mod_eq_of_lt (by omega)
+ have p5 : (p 5).val = rowsHead s h := Nat.mod_eq_of_lt (by omega : rowsHead s h < 2^w)
+ have p6 : (p 6).val = splitHead := Nat.mod_eq_of_lt (by omega : splitHead < 2^w)
+ have p7 : (p 7).val = widthHead s h := Nat.mod_eq_of_lt (by omega : widthHead s h < 2^w)
+ apply SlotEventBounds.scan P 43 (actualCount s) (events p) (fun _ ↦ True) _ _ (native p) _ m rs trivial run
+ intro j hj mem _
+ let i := Fin.ofNat (2^w) j
+ have hi : i.val = j := Nat.mod_eq_of_lt (by omega)
+ have rr : rowNumber (p 0).val i.val < owners s*s.newDegree := by
+ rw [p0,hi]; exact rowNumber_lt hj
+ have hf : (p 5).val+rowNumber (p 0).val i.val < widthHead s h := by rw [p5]; omega
+ have ra := row_val p i twoFits (hf.trans (by omega))
+ have sa := width_eq p mem i twoFits (hf.trans (by omega))
+ let a := (mem ((p 5).val+rowNumber (p 0).val i.val)).val/2
+ have sf (hg : a < (p 4).val) :
+ (p 6).val+splitNumber (p 1).val (p 2).val (p 3).val a < widthHead s h := by
+ rw [p4] at hg
+ have hidx := splitNumber_lt hg
+ rw [p1,p2,p3,p6]
+ change splitHead+old*s.lanes*4*sub ≤ h.scratch at input
+ omega
+ have haddr := (sa (fun hg ↦ (sf hg).trans (by omega))).1
+ change (splitAddr p mem i).val = if a < (p 4).val then
+ (p 6).val+splitNumber (p 1).val (p 2).val (p 3).val a else (p 6).val at haddr
+ have lower := min_le_left splitHead (rowsHead s h)
+ have lower' := min_le_right splitHead (rowsHead s h)
+ have readRow : min splitHead (rowsHead s h) ≤ (row p i).val ∧ (row p i).val < widthHead s h := by
+ rw [ra,p5]; rw [p5] at hf; omega
+ have readSplit : min splitHead (rowsHead s h) ≤ (splitAddr p mem i).val ∧
+ (splitAddr p mem i).val < widthHead s h := by
+ by_cases hg : a < (p 4).val
+ · rw [haddr,ite_eq_left hg,p6]; have hc := sf hg; rw [p6] at hc; omega
+ · rw [haddr,ite_eq_right hg,p6]; exact ⟨lower,first⟩
+ refine ⟨?_,?_,trivial⟩
+ · intro x v he
+ simp only [events,List.mem_append,List.mem_cons,List.mem_nil_iff,List.mem_replicate,
+ Event.read.injEq,reduceCtorEq,and_false,or_false,false_or] at he
+ rcases he with h|h <;> rw [h.1] <;> first | exact readRow | exact readSplit
+ · intro x v he
+ simp [events] at he
+ change x = p 7+i ∧ _ at he
+ rw [he.1,Fin.val_add,p7,hi,Nat.mod_eq_of_lt (by omega)]
+ omega
+
+end CompressorRecords.SlotWidthScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotWidthScan.lean b/lean/OAI/Computability/VPVNP/CompressorSlotWidthScan.lean
new file mode 100644
index 0000000000..2f16ac0519
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotWidthScan.lean
@@ -0,0 +1,197 @@
+import OAI.Computability.VPVNP.CompressorSlotOwnerPass
+import OAI.Computability.VPVNP.CompressorSlotOwnerDecode
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+
+/-!
+# Materializing widths in canonical outgoing-port order
+
+Look up an outgoing slot's absolute field in the sorted incidence row. Its
+numeric arc identifier identifies the old arc, role edge and subdivision.
+Read the corresponding split-width cell. A dummy uses a masked zero offset
+and writes zero independently of the value read there.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SlotWidthScan
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ}
+private abbrev divW := @BinaryOp.eval w .div
+private abbrev modW := @BinaryOp.eval w .mod
+
+/-- Public words give the degree, lane count, total subdivisions, old-base arc
+count, genuine address-space size and the row, split-width and output heads. -/
+def visit : List (Op 12 8) :=
+ [.stateWord 0, .constant 1 1, .constant 2 2, .publicWord 3 0,
+ .binary .div 4 0 3, .binary .mul 4 4 2, .binary .mul 4 4 3, .binary .mod 5 0 3,
+ .binary .add 4 4 5, .publicWord 5 5, .binary .add 4 5 4, .read 4 4, .binary .div 4 4 2,
+ .publicWord 5 4, .binary .add 6 4 1, .binary .div 5 5 6, .binary .div 5 5 5,
+ .publicWord 6 1, .publicWord 7 2, .publicWord 8 3,
+ .binary .mod 9 4 6, .binary .div 4 4 6, .binary .mod 10 4 7, .binary .div 4 4 7,
+ .binary .mod 11 4 8, .binary .div 4 4 8, .binary .mul 11 11 6, .binary .add 11 11 9,
+ .binary .add 9 2 2, .binary .mul 11 11 9, .binary .add 11 11 4,
+ .binary .mul 11 11 7, .binary .add 11 11 10, .binary .mul 11 5 11,
+ .publicWord 4 6, .binary .add 11 4 11, .read 11 11, .binary .mul 11 5 11,
+ .publicWord 4 7, .binary .add 4 4 0, .write 4 11, .binary .add 0 0 1]
+
+/-- Address of the source endpoint field for an actual outgoing port in the rectangular row
+table. -/
+def row (p : Fin 8 → Word w) (i : Word w) := p 5 + (divW i (p 0)*2*(p 0)+modW i (p 0))
+
+/-- Absolute arc ID recovered from the source field in the row table by dropping its endpoint
+bit. -/
+def arc (p : Fin 8 → Word w) (m : Memory w) (i : Word w) := divW (m (row p i).val) 2
+
+private def keep (p : Fin 8 → Word w) (a : Word w) : Word w :=
+ let q := divW (p 4) (a+1)
+ divW q q
+
+/-- Reindex a genuine candidate arc as a split-width table offset ordered by absolute old arc,
+edge type, and subdivision. -/
+def offset (p : Fin 8 → Word w) (a : Word w) :=
+ let key := divW a (p 1)
+ let pair := divW key (p 2)
+ let old := modW pair (p 3)*p 1 + modW a (p 1)
+ (old*(2+2)+divW pair (p 3))*p 2 + modW key (p 2)
+
+/-- Address of the selected split-width entry for a genuine arc, or the split table base for a
+dummy arc. -/
+def splitAddr (p : Fin 8 → Word w) (m : Memory w) (i : Word w) :=
+ let a := arc p m i
+ p 6 + keep p a * offset p a
+
+/-- Width written for the actual outgoing port, taking the selected split width for a genuine
+arc and zero for a dummy. -/
+def width (p : Fin 8 → Word w) (m : Memory w) (i : Word w) := keep p (arc p m i) * m (splitAddr p m i).val
+
+/-- Trace of one width visit, reading the source field and split-width table before writing the
+outgoing port's width. -/
+def events (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : List (Event w) :=
+ List.replicate 11 .tick ++ [.read (row p i) (m (row p i).val)] ++ List.replicate 24 .tick ++
+ [.read (splitAddr p m i) (m (splitAddr p m i).val)] ++ List.replicate 3 .tick ++ [.write (p 7+i) (width p m i),.tick]
+
+theorem events_after (p : Fin 8 → Word w) (m : Memory w) (i : Word w) :
+ after m (events p m i) = writeMemory m (p 7+i) (width p m i) := rfl
+
+theorem events_work (p : Fin 8 → Word w) (m : Memory w) (i : Word w) :
+ (events p m i).length = 42 ∧ countProbes (events p m i) = 3 := ⟨rfl,rfl⟩
+
+set_option maxRecDepth 8192 in
+set_option maxHeartbeats 1000000 in
+private theorem visit_trace (p : Fin 8 → Word w) (m : Memory w) (i : Word w) (regs : Regs w 12) :
+ ∃ rs, trace p i visit regs m = some (events p m i, rs, after m (events p m i)) ∧ rs 0=i+1 := by
+ rw [events_after]
+ simp (config := {decide := true}) [visit,trace,Op.effect,Function.update,events,splitAddr,width,
+ offset,keep,arc,row,divW,modW,BinaryOp.eval]
+ repeat' apply And.intro
+ all_goals rfl
+
+theorem native (p : Fin 8 → Word w) (m : Memory w) (i : Word w) :
+ let M := (template visit 0).instantiate w p
+ execute M.program 43 (M.program.start i) m [] = some ⟨events p m i, some (i+1)⟩ := by
+ obtain ⟨rs, ht, hv⟩ := visit_trace p m i (fun _ => 0)
+ let M := (template visit 0).instantiate w p
+ change execute M.program (1+visit.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template,run_eq_trace,ht]; simp [hv]
+
+private theorem div_val (x y : Word w) : (divW x y).val = x.val / y.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)
+private theorem mod_val (x y : Word w) : (modW x y).val = x.val % y.val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt)
+
+private theorem keep_eq (p : Fin 8 → Word w) (a : Word w) (fit : a.val+1 < 2^w) :
+ keep p a = if a.val < (p 4).val then 1 else 0 := by
+ have h1 : (1 : Word w).val=1 := by rw [Fin.val_one',Nat.mod_eq_of_lt (by omega)]
+ have hs : (a+1).val=a.val+1 := by rw [Fin.val_add,h1,Nat.mod_eq_of_lt fit]
+ change Fin.ofNat _ ((divW (p 4) (a+1)).val/(divW (p 4) (a+1)).val) = _
+ rw [div_val,hs]
+ by_cases h : a.val < (p 4).val
+ · rw [ite_eq_left h,Nat.div_self (Nat.div_pos h (Nat.zero_lt_succ _))]; rfl
+ · rw [ite_eq_right h,Nat.div_eq_of_lt (by omega : (p 4).val < a.val+1)]; rfl
+
+/-- Natural offset of the outgoing field in the rectangular rows, accounting for both endpoint
+sides at every site. -/
+def rowNumber (d i : ℕ) := i/d*2*d+i%d
+
+/-- Natural split-table offset obtained by rearranging the genuine arc's digits into old arc,
+edge type, and subdivision order. -/
+def splitNumber (l sub old a : ℕ) :=
+ let key := a/l
+ let pair := key/sub
+ ((pair%old*l+a%l)*4+pair/old)*sub + key%sub
+
+theorem row_val (p : Fin 8 → Word w) (i : Word w) (hw : 2 < 2^w)
+ (hr : (p 5).val+rowNumber (p 0).val i.val < 2^w) :
+ (row p i).val = (p 5).val+rowNumber (p 0).val i.val := by
+ have htwo : (2 : Word w).val=2 := Nat.mod_eq_of_lt hw
+ simp only [row,Fin.val_add,Fin.val_mul,div_val,mod_val,htwo,Nat.mod_mul_mod,Nat.mod_add_mod,Nat.add_mod_mod]
+ exact Nat.mod_eq_of_lt hr
+
+/-- A genuine field reads its old arc's split-width word. A dummy reads a
+safe fixed address and supplies zero irrespective of that word. -/
+theorem width_eq (p : Fin 8 → Word w) (m : Memory w) (i : Word w) (hw : 2 < 2^w)
+ (hr : (p 5).val+rowNumber (p 0).val i.val < 2^w) :
+ let a := (m ((p 5).val+rowNumber (p 0).val i.val)).val/2
+ let idx := splitNumber (p 1).val (p 2).val (p 3).val a
+ (a < (p 4).val → (p 6).val+idx < 2^w) →
+ (splitAddr p m i).val = (if a < (p 4).val then (p 6).val+idx else (p 6).val) ∧
+ width p m i = if a < (p 4).val then m ((p 6).val+idx) else 0 := by
+ intro a idx hf
+ have htwo : (2 : Word w).val = 2 := Nat.mod_eq_of_lt hw
+ have ha : (arc p m i).val = a := by rw [arc,div_val,htwo,row_val p i hw hr]
+ have hab : a+1 < 2^w := by
+ dsimp only [a]
+ have := (m ((p 5).val+rowNumber (p 0).val i.val)).isLt
+ omega
+ have hk := keep_eq p (arc p m i) (ha ▸ hab)
+ rw [ha] at hk
+ by_cases h : a < (p 4).val
+ · rw [ite_eq_left h] at hk
+ have off : (offset p (arc p m i)).val = idx := by
+ simp only [offset, Fin.val_add,Fin.val_mul,div_val,mod_val,htwo,Nat.mod_mul_mod,Nat.mul_mod_mod,
+ Nat.mod_add_mod,ha]
+ exact Nat.mod_eq_of_lt (by have := hf h; omega : idx < 2^w)
+ have hs : (splitAddr p m i).val = (p 6).val+idx := by
+ rw [splitAddr,hk,one_mul,Fin.val_add,off,Nat.mod_eq_of_lt (hf h)]
+ simp [width,hk,hs,h]
+ · rw [ite_eq_right h] at hk
+ simp [splitAddr,width,hk,h]
+
+/-- Full canonical outgoing-width pass, with read-only input regions below
+the output head. Each record costs one call, two reads and one write. -/
+theorem run (p : Fin 8 → Word w) (m : Memory w) (n : ℕ) (fit : (p 7).val+n ≤ 2^w)
+ (hreads : ∀ j < n, let i := Fin.ofNat (2^w) j
+ (row p i).val < (p 7).val ∧ (splitAddr p m i).val < (p 7).val) :
+ let M := (template visit 0).instantiate w p
+ ∃ rs, runSegment M.program 43 (some 0) m (List.replicate n []) = some rs ∧
+ endState (some 0) rs = some (Fin.ofNat _ n) ∧
+ (∀ j < n, after m (eventLog rs) ((p 7).val+j) = width p m (Fin.ofNat _ j)) ∧
+ (∀ a, a < (p 7).val ∨ (p 7).val+n ≤ a → after m (eventLog rs) a=m a) ∧
+ RAMBuckets.cost Report.probes rs = 4*n := by
+ intro M
+ obtain ⟨rs, hr,hc,hf,hframe,_,_,hcost⟩ := SlotOwnerPass.run M.program 43 3 42 (p 7).val 0 n
+ (fun i ↦ width p m (Fin.ofNat _ i)) m (by simpa using fit) (by
+ intro j _ hj mem frame
+ let i := Fin.ofNat (2^w) j
+ obtain ⟨hrow,hsplit⟩ := hreads j (by simpa using hj)
+ have hR : mem (row p i).val = m (row p i).val := frame _ (.inl (by omega))
+ have ha : arc p mem i = arc p m i := congrArg (fun x ↦ divW x 2) hR
+ have hs : splitAddr p mem i = splitAddr p m i := by unfold splitAddr; rw [ha]
+ have value : width p mem i = width p m i := by
+ have hv := frame (splitAddr p m i).val (.inl (by omega))
+ simp only [width,ha,hs,hv]
+ have hnext : i+1 = Fin.ofNat _ (j+1) := by apply Fin.ext; simp [i,Fin.val_add,Nat.mod_add_mod,Nat.add_mod_mod]
+ have haddr : p 7+i = Fin.ofNat _ ((p 7).val+j) := by apply Fin.ext; simp [i,Fin.val_add,Nat.add_mod_mod]
+ exact ⟨events p mem i, by rw [native,hnext], by rw [events_after,haddr,value], (events_work ..).2,(events_work ..).1⟩)
+ exact ⟨rs,hr,by simpa using hc,fun j hj ↦ hf j (Nat.zero_le j) (by simpa using hj),
+ fun a ha ↦ hframe a (by omega),by simpa using hcost⟩
+
+end CompressorRecords.SlotWidthScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSlotWidthState.lean b/lean/OAI/Computability/VPVNP/CompressorSlotWidthState.lean
new file mode 100644
index 0000000000..67b7333391
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSlotWidthState.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.CompressorSlotWidth
+import OAI.Computability.VPVNP.CompressorSlotOutputLayout
+import OAI.Computability.VPVNP.CompressorSlotState
+
+/-!
+# The selected shrinking state's canonical width column
+
+The graph and slot order read by the width writer are those used in the
+selected compression branch. The old-arc-indexed split words are mapped to
+the outgoing ports of the next state in its stored base order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSlots
+
+open Compression Compression.State Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion Slots SlotLevel SlotOwners SlotSchedule
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {a b g w : ℕ} {δ factor : ℝ} {k : Type*} [Field k]
+variable (X : State a (packingLaneBits a g))
+variable (B : FixedBlock k demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection B)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Width of the specified motif role edge in the selected term and layout before division into
+surviving slots. -/
+noncomputable abbrev branchWidth (m : X.packingData.Motif) (t : Fin 4) :=
+ X.packingData.termWidths B X.shrinkNumber X.packingWidth sel m (selectedLayout X B sel) t
+
+/-- The shared port lengths agree with the branch's own base and lane cardinals. -/
+theorem next_counts :
+ let s := levelShape (b := b) X
+ let Y := X.shrinkNext B ready sel
+ Fintype.card Y.Base*2^b=baseArcs s ∧ Fintype.card Y.Base*2^g*2^b=actualCount s := by
+ intro s Y
+ change Fintype.card (X.Base×BitWord (packingTagBits (2^a))) * 2^b = _ ∧
+ Fintype.card (X.Base×BitWord (packingTagBits (2^a))) * 2^g * 2^b = _
+ rw [Fintype.card_prod]
+ have card := (Fintype.card_congr (bitWordFinEquiv (packingTagBits (2^a)))).trans (Fintype.card_fin _)
+ rw [card]
+ exact ⟨rfl,by change _ = (Fintype.card X.Base * (2^packingTagBits (2^a)*2^g))*2^b; ring⟩
+
+/-- Re-association of base, tag and remaining lane in the two mixed-radix
+implementations produces the same canonical port number. -/
+theorem portIndex_next (e : ((X.shrinkNext B ready sel).Base × BitWord g) × Fin (2^b)) :
+ (SlotWidthScan.portIndex X.baseIndex (bitWordFinEquiv (packingTagBits (2^a))) (bitWordFinEquiv g) e).val =
+ (IncidenceDirectory.actualOrder (X.shrinkNext B ready sel) e).val := by
+ let v := (X.baseIndex e.1.1.1).val
+ let t := (bitWordFinEquiv (packingTagBits (2^a)) e.1.1.2).val
+ let l := (bitWordFinEquiv g e.1.2).val
+ let J := 2^packingTagBits (2^a)
+ change e.2.val+2^b*(l+2^g*t+(J*2^g)*v) = e.2.val+2^b*(l+2^g*(t+J*v))
+ ring
+
+/-- Actual native width scan in state coordinates. Its input split rows can
+be the simultaneously established rows of `ShrinkSliceSweep.graph_run`. -/
+theorem width_run (h : Heads) (splitHead : ℕ) (m : Memory w) :
+ let s := levelShape (b := b) X
+ let l := selectedLayout X B sel
+ let P := X.packingData
+ let tags := bitWordFinEquiv (packingTagBits (2^a))
+ let lanes := bitWordFinEquiv g
+ let D := slotDirectory P s.subdivisions X.baseIndex tags lanes l (pad := pad s)
+ let hD := fun v ↦ (slotDirectory_degree P s.subdivisions X.baseIndex tags lanes (two_le_packingColors a) l v).trans
+ (Nat.add_sub_of_le ready.degree_budget)
+ let p := widthBank s h splitHead w
+ let M := (template SlotWidthScan.visit 0).instantiate w p
+ let Y := X.shrinkNext B ready sel
+ 2 < 2^w → 2^b < 2^w → 2^g < 2^w → (∑t,s.subdivisions t) < 2^w →
+ oldBaseArcCount s.bases s.tags s.oldDegree s.colors < 2^w →
+ splitHead+(oldBaseArcCount s.bases s.tags s.oldDegree s.colors*s.lanes)*4*(∑ t,s.subdivisions t) ≤ h.scratch →
+ finish s h < 2^w → SlotWidthScan.SplitRows P s.subdivisions X.baseIndex tags lanes (branchWidth X B sel) splitHead m →
+ (∀ x, m (rowsHead s h+(sortedFields D (2^b) hD x).val) = Fin.ofNat _ (D.address x).val) →
+ ∃ rs, runSegment M.program 43 (some 0) m (List.replicate (actualCount s) []) = some rs ∧
+ endState (some 0) rs = some (Fin.ofNat _ (actualCount s)) ∧
+ (∀ e, after m (eventLog rs) (widthHead s h+(IncidenceDirectory.actualOrder Y e).val) =
+ Fin.ofNat _ (Y.width ((e.1.1,e.2),e.1.2))) ∧
+ (∀ addr, addr < widthHead s h ∨ finish s h ≤ addr → after m (eventLog rs) addr=m addr) ∧
+ RAMBuckets.cost Report.probes rs = 4*actualCount s := by
+ intro s l P tags lanes D hD p M Y hw hdw hlw hsw hbw room fit split rows
+ have hrow : rowsHead s h+owners s*s.newDegree ≤ inverseHead s h :=
+ Nat.add_le_add_left (Nat.mul_le_mul_right s.newDegree (Nat.le_add_right (owners s) (fields s))) _
+ have hheads : h.scratch ≤ rowsHead s h ∧ inverseHead s h+fields s ≤ widthHead s h ∧ widthHead s h+actualCount s=finish s h := by
+ refine ⟨(Nat.le_add_right h.scratch (fields s)).trans (Nat.le_add_right _ _), ?_, rfl⟩
+ change targetsHead s h ≤ widthHead s h
+ calc
+ targetsHead s h ≤ shiftsHead s h := Nat.le_add_right _ _
+ _ ≤ inverseBaseHead s h := Nat.le_add_right _ _
+ _ ≤ outHead s h := Nat.le_add_right _ _
+ _ ≤ inHead s h := Nat.le_add_right _ _
+ _ ≤ widthHead s h := Nat.le_add_right _ _
+ have hgen : keyCount s.bases s.tags s.oldDegree s.colors s.subdivisions*s.lanes ≤ fields s := by
+ unfold fields RecordCount; omega
+ have hP0 : (p 0).val=2^b := Nat.mod_eq_of_lt hdw
+ have hP1 : (p 1).val=2^g := Nat.mod_eq_of_lt hlw
+ have hP2 : (p 2).val=∑t,s.subdivisions t := Nat.mod_eq_of_lt hsw
+ have hP3 : (p 3).val=oldBaseArcCount s.bases s.tags s.oldDegree s.colors := Nat.mod_eq_of_lt hbw
+ have hP4 : (p 4).val=keyCount s.bases s.tags s.oldDegree s.colors s.subdivisions*s.lanes :=
+ Nat.mod_eq_of_lt (by omega : keyCount s.bases s.tags s.oldDegree s.colors s.subdivisions*s.lanes < 2^w)
+ have hP5 : (p 5).val=rowsHead s h := Nat.mod_eq_of_lt (by omega : rowsHead s h < 2^w)
+ have hP6 : (p 6).val=splitHead := Nat.mod_eq_of_lt (by omega : splitHead < 2^w)
+ have hP7 : (p 7).val=widthHead s h := Nat.mod_eq_of_lt (by omega : widthHead s h < 2^w)
+ have hpos : 0 < actualCount s := by
+ rw [← (next_counts X B ready sel).2]; positivity
+ have hbase : h.scratch < widthHead s h := by
+ simp only [widthHead,inHead,outHead,inverseBaseHead,stopAddress,shiftsHead,targetsHead,inverseHead,rowsHead]; omega
+ obtain ⟨rs,hr,hc,output,frame,cost⟩ := SlotWidthScan.write_all P s.subdivisions X.baseIndex tags lanes l
+ (branchWidth X B sel) (two_le_packingColors a) (orderedDyadicPacking_validTags X.slots X.baseIndex)
+ ready.degree_budget (Nat.one_lt_two_pow (Nat.succ_pos _).ne') p m hP0 hP1 hP2 hP3 hP4 hw
+ (by rw [hP5,hP7]; change rowsHead s h+owners s*s.newDegree ≤ widthHead s h; omega)
+ (by rw [hP6,hP7]; exact room.trans hbase.le) (by rw [hP6,hP7]; omega) (hP6 ▸ split)
+ (by rw [hP7]; change widthHead s h+actualCount s ≤ 2^w; omega)
+ (fun x ↦ hP5 ▸ rows x) (by change fields s ≤ 2^w; omega)
+ refine ⟨rs,hr,hc,?_,?_,cost⟩
+ · intro e
+ have he := output e
+ rw [hP7,portIndex_next X B ready sel] at he
+ exact he
+ · intro addr ha; exact frame addr (by rw [hP7]; change addr < widthHead s h ∨ widthHead s h+actualCount s ≤ addr; omega)
+
+end CompressorRecords.ShrinkSlots
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceBankFrame.lean b/lean/OAI/Computability/VPVNP/CompressorSourceBankFrame.lean
new file mode 100644
index 0000000000..01100cb28d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceBankFrame.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.CompressorScriptSnapshot
+import OAI.Computability.VPVNP.CompressorOnlinePeel
+import OAI.Computability.VPVNP.CompressorSourceWalk
+import OAI.Computability.VPVNP.CompressorRecordsOnlineWorkspace
+
+/-! # The physical pointer bank across all calls of a descriptor row
+
+The calendar tag, ordinal, active frame, recipe row and data workspace lie
+above the six external pointer cells. Each original data call is charged its
+own writes. Each scheduler call has its concrete memory effect. Consequently
+the framing reads on every intervening call see the same pointers, and words
+preceding the workspace, including the virtual header span, survive the row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceBankFrame
+open BurstRAM DescriptorSpace BlockPlanner Schedule SourceTransport
+open scoped Fin.CommRing
+open private field_addresses from OAI.Computability.VPVNP.CompressorScriptSnapshot
+open private workerRows_after from OAI.Computability.VPVNP.CompressorRecordsOnline
+
+variable {w : ℕ}
+
+/-- Preservation at every call boundary, including intermediate worker calls. -/
+def Stable (lo : ℕ) : Memory w → List (Report w) → Prop
+ | _, [] => True
+ | m, r::rs => (∀ x < lo, after m r.events x = m x) ∧ Stable lo (after m r.events) rs
+
+namespace Stable
+
+theorem append {lo : ℕ} {m : Memory w} {rs ts : List (Report w)} (h : Stable lo m rs)
+ (ht : Stable lo (after m (eventLog rs)) ts) : Stable lo m (rs++ts) := by
+ induction rs generalizing m with
+ | nil => exact ht
+ | cons r rs ih =>
+ exact ⟨h.1,ih h.2 (by simpa only [eventLog,List.flatMap_cons,after,List.foldl_append] using ht)⟩
+
+theorem take_eq {lo : ℕ} {m : Memory w} {rs : List (Report w)} (h : Stable lo m rs)
+ (n x : ℕ) (hx : x < lo) : after m (eventLog (rs.take n)) x = m x := by
+ induction rs generalizing n m with
+ | nil => simp only [List.take_nil]; rfl
+ | cons r rs ih =>
+ cases n with
+ | zero => rfl
+ | succ n =>
+ simp only [List.take_succ_cons,eventLog,List.flatMap_cons,after,List.foldl_append]
+ exact (ih h.2 n).trans (h.1 x hx)
+
+theorem installed {g : ℕ} {base : Word w} {m : Memory w} {rs : List (Report w)}
+ (stable : Stable (base.val+6) m rs) (bank : Workspace.Installed g base m) (n : ℕ) :
+ Workspace.Installed g base (after m (eventLog (rs.take n))) := by
+ apply bank.preserve
+ intro i
+ apply stable.take_eq
+ rw [Fin.val_add,Fin.val_natCast]
+ exact (Nat.mod_le ..).trans_lt (Nat.add_lt_add_left ((Nat.mod_le ..).trans_lt i.isLt) _)
+
+theorem banks {g : ℕ} {base : Word w} {m : Memory w} {rs : List (Report w)}
+ (stable : Stable (base.val+6) m rs) (bank : Workspace.Installed g base m) : OnlineWorkspace.Banks g base m rs := by
+ induction rs generalizing m with
+ | nil => trivial
+ | cons r rs ih =>
+ exact ⟨bank,ih stable.2 (by simpa [eventLog] using stable.installed bank 1)⟩
+
+end Stable
+
+variable (A : Script) (L : Layout) (base : Word w)
+local notation "g" => arity A.catalog
+local notation "pt" => Workspace.ports (arity A.catalog) base
+local notation "H" => levelStart L 0
+local notation "lo" => base.val+6
+
+private theorem worker_stable (i : Fin A.size) (pub : Fin (A.catalog i).params → Word w)
+ (bound st : Word w) (m : Memory w) (rs : List (Report w)) (fits : lo ≤ H)
+ (valid : ValidTrace A.catalog i pt pub bound st m rs) (writes : Writes (H ≤ ·) (eventLog rs)) :
+ Stable lo m (Online.workerRows A.catalog A.size pt i m rs) := by
+ induction rs generalizing st m with
+ | nil => trivial
+ | cons r rs ih =>
+ obtain ⟨_,_,next,ret,tail⟩ := valid
+ have he := (Online.active_effect (C := A.catalog) (initial := A.initial.length) (phases := A.block.length)
+ pt i m r ret).2.1
+ change (∀ x < lo, after m (Online.activeReport A.catalog A.size pt i m r).events x = m x) ∧ _
+ rw [he]
+ refine ⟨fun x hx => after_outside m (fun a v h => writes a v (List.mem_append_left _ h)) (not_le_of_gt (hx.trans_le fits)),?_⟩
+ exact ih next _ tail (fun a v h => writes a v (List.mem_append_right _ h))
+
+/-- The three deterministic control calls retain all six physical pointers,
+including in a selector row with no admitted terms. -/
+theorem preparation_stable (hg : g = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w)
+ (m : Memory w) (j : Fin A.size) (room : (m (pt).ordinal.val).val < directoryRows L) :
+ Stable lo m (Online.preparation A.plan pt m j) := by
+ have top : H = L.base+(11+g)+directoryRows L*(g+3) := by
+ rw [hg]
+ simp only [levelStart,levelsBase,directoryBase,plannerTag,frameBase,Nat.zero_mul,Nat.add_zero]
+ omega
+ have fitDir : base.val+(11+g) < 2^w := by omega
+ obtain ⟨tagAddr,ordAddr,_,dirAddr,frameAddr⟩ := field_addresses g base fitDir
+ let pre := Online.calendarMemory (d := A.size) pt m j
+ let state := LevelCalendar.header (Online.calendar A.plan) (pt).data m
+ let R := (A.phase j).recipe
+ have preOrd : pre (pt).ordinal.val = m (pt).ordinal.val := ite_eq_right (by omega)
+ have offset : (pt).directory.val+(pre (pt).ordinal.val).val*(g+3) < H := by
+ rw [preOrd,top,dirAddr,hb]
+ exact Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_right room (by omega)) _
+ have rowVal := Directory.rowBase_val A.catalog pt pre (offset.trans fit)
+ have bound := OnlineFootprint.row_bound A L base hg hb fit pre (preOrd ▸ room)
+ have lower (x : ℕ) (hx : x < lo) : x < (Controller.rowBase g (pt).data pre).val := by
+ change x < (Directory.rowBase A.catalog pt pre).val
+ rw [rowVal,dirAddr]
+ omega
+ have hc := (Online.calendar_effect A.plan pt m j).2.1
+ have hr := (Online.recipe_effect A.plan pt j state pre).2.1
+ have hl := (Online.launch_effect (C := A.catalog) (initial := A.initial.length) (phases := A.block.length) pt (Online.rowInput A.plan pt m j)).2.1
+ change Stable lo m [Online.calendarReport A.plan pt m j, Online.recipeReport A.plan pt j state pre,
+ Online.launchReport A.catalog A.size pt (Online.rowInput A.plan pt m j)]
+ rw [Stable,hc]
+ refine ⟨fun x hx => ite_eq_right (by omega),?_⟩
+ change Stable lo pre (Online.recipeReport A.plan pt j state pre :: _)
+ rw [Stable,hr]
+ constructor
+ · intro x hx
+ have preserved := RowRecipe.row_outside R (pt).data state pre
+ (by rw [PhaseRecipe.recipe_address]; exact bound.trans fit.le) x
+ (.inl (by rw [PhaseRecipe.recipe_address]; exact lower x hx))
+ rw [RowRecipe.after_row] at preserved
+ exact (ite_eq_right (by omega : x ≠ (pt).tag.val)).trans preserved
+ · change Stable lo (Online.rowInput A.plan pt m j) (Online.launchReport A.catalog A.size pt _ :: _)
+ rw [Stable,hl]
+ constructor
+ · intro x hx
+ exact Controller.after_row_outside g (pt).data (Online.rowInput A.plan pt m j) x (by change x ≠ (pt).ordinal.val; omega)
+ (by change x ≠ (pt).tag.val; omega)
+ (fun i => by change x ≠ ((pt).activeFrame+(i.val : Word w)).val; rw [frameAddr]; omega)
+ · trivial
+
+/-- Preparation, data and closing calls all preserve the low cells. The only
+source footprint premise concerns the genuine data worker's own writes. -/
+theorem row_stable (hg : g = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w)
+ (m : Memory w) (j : Fin A.size) (row : Directory.Row A.size w)
+ (room : (m (pt).ordinal.val).val < directoryRows L)
+ (input : row.input = Online.rowInput A.plan pt m j) (valid : row.Valid A.catalog pt)
+ (writes : Writes (H ≤ ·) (eventLog row.reports)) :
+ Stable lo m (Online.rowLog A.plan pt m j row) := by
+ have ready := preparation_stable A L base hg hb fit m j room
+ have hp := (Online.preparation_effect A.plan pt 0 m j).2
+ have top : H = L.base+(11+g)+directoryRows L*(g+3) := by
+ rw [hg]
+ simp only [levelStart,levelsBase,directoryBase,plannerTag,frameBase,Nat.zero_mul,Nat.add_zero]
+ omega
+ have lowTag := (field_addresses g base (by omega)).1
+ have hworker := worker_stable A L base row.worker _ _ _ _ _ (by omega) valid.frame writes
+ have workerEnd := workerRows_after (initial := A.initial.length) (phases := A.block.length) pt row.worker _ _ _ _ _ valid.frame
+ have last := (Online.stop_effect (C := A.catalog) (initial := A.initial.length) (phases := A.block.length)
+ pt row.worker (row.endMemory A.catalog pt)).2.1
+ rw [Online.rowLog,List.append_assoc]
+ apply ready.append
+ rw [hp,← input]
+ apply hworker.append
+ rw [workerEnd]
+ change Stable lo (row.endMemory A.catalog pt) [Online.stopReport A.catalog A.size pt row.worker _]
+ rw [Stable,last]
+ exact ⟨fun x hx => ite_eq_right (by omega),trivial⟩
+
+end CompressorRecords.SourceBankFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceCalendarEntry.lean b/lean/OAI/Computability/VPVNP/CompressorSourceCalendarEntry.lean
new file mode 100644
index 0000000000..bccec9da74
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceCalendarEntry.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.CompressorSourceSequence
+import OAI.Computability.VPVNP.CompressorRecordsLevelFields
+
+/-!
+# The level header seen by a repeated online recipe
+
+At a live calendar ordinal the row counter and pitch identify the first
+level of the current block. Writing the recipe tag preserves that pitch
+and all source data in the level arena.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceOnline
+
+open BurstRAM BlockPlanner Schedule DescriptorSpace SourceTransport
+open scoped Fin.CommRing
+open private field_addresses from OAI.Computability.VPVNP.CompressorScriptSnapshot
+
+variable {w : ℕ} (A : Script) (L : Layout) (base : Word w)
+local notation "g" => arity A.catalog
+local notation "pt" => Workspace.ports (arity A.catalog) base
+local notation "H" => levelStart L 0
+
+theorem calendar_entry (arityFit : g = L.shape.arity) (baseFit : base.val = L.base) (fit : H < 2^w)
+ (m : Memory w) (j : Fin A.size) (block : ℕ)
+ (level : (Online.calendar A.plan).level (m (pt).ordinal.val).val = block)
+ (total : (m (pt).rows.val).val = directoryRows L)
+ (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) :
+ let pre := Online.calendarMemory (d := A.size) pt m j
+ LevelFields.Entry L (A.levelsPerBlock*block) (pt).data (A.recipeState base m) pre ∧ Agree (H ≤ ·) m pre := by
+ intro pre
+ have top : H = base.val+(11+g)+directoryRows L*(g+3) := by
+ simp only [levelStart,levelsBase,directoryBase,plannerTag,frameBase,Nat.zero_mul,Nat.add_zero,baseFit,arityFit]
+ omega
+ have dirRoom : base.val+(11+g) < 2^w := by omega
+ obtain ⟨tagAt,_,_,dirAt,_⟩ := field_addresses g base dirRoom
+ have dir : (pt).data 1 = (directoryBase L : Word w) := by
+ apply Fin.ext
+ change (pt).directory.val = (directoryBase L)%(2^w)
+ have head : directoryBase L = base.val+(11+g) := by unfold directoryBase plannerTag frameBase; omega
+ rw [dirAt,head,Nat.mod_eq_of_lt dirRoom]
+ have rows : m ((pt).data 3).val = (directoryRows L : Word w) := by
+ apply Fin.ext
+ rw [Fin.val_natCast,← total,Nat.mod_eq_of_lt (m (pt).rows.val).isLt]; rfl
+ have original := LevelFields.eval_calendar_entry (Online.calendar A.plan) (pt).data m L dir
+ (show (Online.calendar A.plan).rowPitch = L.shape.arity+3 from congrArg (·+3) arityFit) rows pitch
+ have first : (Online.calendar A.plan).levelsPerBlock * (Online.calendar A.plan).level (m ((pt).data 2).val).val =
+ A.levelsPerBlock*block := congrArg (A.levelsPerBlock*·) level
+ rw [first] at original
+ have gapVal : ((pt).directory-1).val = base.val+(10+g) := by
+ have one : (1 : Word w).val = 1 := by
+ change 1 % (2^w) = 1
+ exact Nat.mod_eq_of_lt (show 1 < 2^w by omega)
+ have le : (1 : Word w) ≤ (pt).directory := Fin.le_def.mpr (by rw [one,dirAt]; omega)
+ rw [Fin.sub_val_of_le le,dirAt,one]; omega
+ have tagNe : ((pt).directory-1).val ≠ (pt).tag.val := by omega
+ refine ⟨⟨original.pointer,?_⟩,fun x hx => ?_⟩
+ · change writeMemory m (pt).tag _ ((pt).directory-1).val = _
+ rw [writeMemory,ite_eq_right tagNe]; exact pitch
+ · change m x = writeMemory m (pt).tag _ x
+ rw [writeMemory,ite_eq_right (by omega : x ≠ (pt).tag.val)]
+
+end CompressorRecords.SourceOnline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceGroupSplit.lean b/lean/OAI/Computability/VPVNP/CompressorSourceGroupSplit.lean
new file mode 100644
index 0000000000..32f2112bc0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceGroupSplit.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.CompressorSourceGroups
+
+/-! # Splitting a chronological group at a selected source row
+
+The tail starts in the actual memory returned by the preceding packets,
+and the native row ordinal advances by their number. In particular the
+packet following a selector sees the selector's own output memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceOnline.Group
+
+open BurstRAM BlockPlanner DescriptorSpace
+
+variable {w : ℕ} {A : Script} {L : Layout} {base : Word w} {cap ordinal total : ℕ}
+variable {m : Memory w} {xs ys : List (Packet A w)}
+
+private theorem chronological_split (h : SourceWalk.Chronological Visit.Runs m (xs++ys)) :
+ SourceWalk.Chronological Visit.Runs m xs ∧ SourceWalk.Chronological Visit.Runs (post m xs) ys := by
+ induction xs generalizing m with
+ | nil => exact ⟨trivial,h⟩
+ | cons p ps ih =>
+ obtain ⟨head,tail⟩ := ih h.2.2
+ refine ⟨⟨h.1,h.2.1,head⟩,?_⟩
+ have same : post m (p::ps) = post p.output ps := by
+ rw [← h.1]
+ simp only [post,List.flatMap_cons,SourceWalk.Packet.output,SourceWalk.after_append]
+ exact same.symm ▸ tail
+
+/-- Split without choosing new executions or resetting the ordinal. -/
+theorem split (h : Group A L base cap ordinal total m (xs++ys)) :
+ Group A L base cap ordinal total m xs ∧
+ Group A L base cap (ordinal+xs.length) total (post m xs) ys := by
+ obtain ⟨first,second⟩ := chronological_split h.chronological
+ constructor
+ · refine ⟨first,fun p hp => h.checked p (List.mem_append_left _ hp),?_⟩
+ intro i
+ have bound : i.val < (xs++ys).length := by simp; omega
+ have hv := h.prepared ⟨i.val,bound⟩
+ simpa only [List.getElem_append_left i.isLt] using hv
+ · refine ⟨second,fun p hp => h.checked p (List.mem_append_right _ hp),?_⟩
+ intro i
+ have bound : xs.length+i.val < (xs++ys).length := by simpa only [List.length_append] using Nat.add_lt_add_left i.isLt xs.length
+ have hv := h.prepared ⟨xs.length+i.val,bound⟩
+ simpa only [List.getElem_append_right (Nat.le_add_right ..),Nat.add_sub_cancel_left,← Nat.add_assoc] using hv
+
+/-- The selector is the next executed packet after the prefix. Its own
+output memory is the source of the suffix, including when either side is empty. -/
+theorem split_at_selector {sel : Packet A w} (h : Group A L base cap ordinal total m (xs++sel::ys)) :
+ Group A L base cap ordinal total m xs ∧
+ Group A L base cap (ordinal+xs.length) total (post m xs) [sel] ∧
+ sel.input = post m xs ∧
+ Group A L base cap (ordinal+xs.length+1) total sel.output ys := by
+ obtain ⟨before,rest⟩ := h.split
+ obtain ⟨selected,suffix⟩ := (split (xs := [sel]) (ys := ys) rest)
+ have input : sel.input = post m xs := selected.chronological.1
+ have returned : post (post m xs) [sel] = sel.output := by
+ rw [← input]
+ simp only [post,List.flatMap_cons,List.flatMap_nil,List.append_nil,SourceWalk.Packet.output]
+ exact ⟨before,selected,input,returned ▸ suffix⟩
+
+end CompressorRecords.SourceOnline.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceGroups.lean b/lean/OAI/Computability/VPVNP/CompressorSourceGroups.lean
new file mode 100644
index 0000000000..467f351658
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceGroups.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.CompressorSourceSequence
+import OAI.Computability.VPVNP.CompressorScriptWindow
+
+/-!
+# Joining contiguous groups of online descriptor packets
+
+Each group retains the actual execution on the raw memory, the event footprint and
+clock bounds, and the recipe evaluation at the packet's live ordinal. Groups are
+joined at the exact post-memory of their predecessors, shifting the ordinal by the
+number of preceding visits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceOnline
+
+open BurstRAM BlockPlanner DescriptorSpace
+
+variable {w : ℕ}
+
+/-- One online script visit together with its source memory and native worker reports. -/
+abbrev Packet (A : Script) (w : ℕ) := SourceWalk.Packet (Visit A w) w
+
+/-- Memory after replaying the reports from a list of online visit packets in order. -/
+def post {A : Script} (m : Memory w) (ps : List (Packet A w)) := after m (eventLog (ps.flatMap SourceWalk.Packet.reports))
+
+/-- Chronological packets whose runs satisfy the clock and memory bounds and whose recipes
+match successive live ordinals. -/
+structure Group (A : Script) (L : Layout) (base : Word w) (cap ordinal total : ℕ)
+ (raw : Memory w) (ps : List (Packet A w)) : Prop where
+ chronological : SourceWalk.Chronological Visit.Runs raw ps
+ checked : ∀ p ∈ ps, Checked A L cap p
+ prepared : ∀ i : Fin ps.length, Prepared A L base (ordinal+i.val) total ps[i.val]
+
+private theorem chronological_append {A : Script} {ps qs : List (Packet A w)} {m : Memory w}
+ (hp : SourceWalk.Chronological Visit.Runs m ps)
+ (hq : SourceWalk.Chronological Visit.Runs (post m ps) qs) :
+ SourceWalk.Chronological Visit.Runs m (ps++qs) := by
+ induction ps generalizing m with
+ | nil => exact hq
+ | cons p ps ih =>
+ refine ⟨hp.1,hp.2.1,ih hp.2.2 ?_⟩
+ have he : post m (p::ps) = post p.output ps := by
+ rw [← hp.1]
+ simp only [post,List.flatMap_cons,SourceWalk.Packet.output,SourceWalk.after_append]
+ rwa [← he]
+
+theorem post_append {A : Script} (m : Memory w) (ps qs : List (Packet A w)) :
+ post m (ps++qs) = post (post m ps) qs := by
+ simp only [post,List.flatMap_append,SourceWalk.after_append]
+
+namespace Group
+
+variable {A : Script} {L : Layout} {base : Word w} {cap ordinal total : ℕ}
+variable {m : Memory w} {ps qs : List (Packet A w)}
+
+theorem nil : Group A L base cap ordinal total m [] :=
+ ⟨trivial,by simp,fun i => Fin.elim0 i⟩
+
+theorem singleton (p : Packet A w) (hin : p.input=m) (run : p.stage.Runs p.input p.reports)
+ (checked : Checked A L cap p) (prepared : Prepared A L base ordinal total p) :
+ Group A L base cap ordinal total m [p] := by
+ refine ⟨⟨hin,run,trivial⟩,by simpa using checked,?_⟩
+ intro i
+ fin_cases i
+ simpa using prepared
+
+theorem append (first : Group A L base cap ordinal total m ps)
+ (second : Group A L base cap (ordinal+ps.length) total (post m ps) qs) :
+ Group A L base cap ordinal total m (ps++qs) := by
+ refine ⟨chronological_append first.chronological second.chronological,?_,?_⟩
+ · intro p hp
+ rcases List.mem_append.mp hp with h | h
+ · exact first.checked p h
+ · exact second.checked p h
+ · intro i
+ by_cases hi : i.val < ps.length
+ · rw [List.getElem_append_left hi]
+ exact first.prepared ⟨i.val,hi⟩
+ · have hj : i.val-ps.length < qs.length := by have := i.isLt; simp only [List.length_append] at this; omega
+ have hordinal : ordinal+i.val = (ordinal+ps.length)+(i.val-ps.length) := by omega
+ rw [List.getElem_append_right (by omega),hordinal]
+ exact second.prepared ⟨_,hj⟩
+
+end Group
+end CompressorRecords.SourceOnline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceLaunch.lean b/lean/OAI/Computability/VPVNP/CompressorSourceLaunch.lean
new file mode 100644
index 0000000000..d215e754c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceLaunch.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.CompressorSourceOnline
+import OAI.Computability.VPVNP.CompressorScriptSnapshot
+
+/-! # The physical launch certificate for the current script phase -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceOnline
+
+open BurstRAM Schedule BlockPlanner DescriptorSpace
+
+variable {w : ℕ} (A : Script) (base : Word w)
+local notation "g₀" => arity A.catalog
+local notation "P₀" => Workspace.ports g₀ base
+
+/-- Actual stage operands depend on the current memory. Choice strings and
+the worker's private clock are supplied by the source scan. -/
+def evaluated (m : Memory w) (j : Fin A.size) (fuel : ℕ) (bits : List (List Bool)) : Visit A w :=
+ ⟨j,fuel,A.operand base m j (A.visit j).initial,A.operand base m j (A.visit j).stop,
+ fun i => A.operand base m j ((A.visit j).params i),bits⟩
+
+theorem evaluated_launch (L : Layout) (hg : g₀=L.shape.arity) (hb : base.val=L.base) (fit : levelStart L 0 < 2^w)
+ (m : Memory w) (j : Fin A.size) (fuel : ℕ) (bits : List (List Bool))
+ (room : (m (P₀).ordinal.val).val < directoryRows L) (active : m (P₀).ordinal.val < m (P₀).rows.val) :
+ (evaluated A base m j fuel bits).Launch P₀ m := by
+ obtain ⟨ord,rows,tag,start,stop,params,ready,next,same⟩ := A.snapshot L base hg hb fit m j room active
+ exact ⟨tag,ord,rows,start,stop,params,ready,next,same⟩
+
+/-- Public field evaluation is all that a typed source stage needs to supply
+to identify its computed runtime launch. -/
+theorem launch_of_evaluation (L : Layout) (hg : g₀=L.shape.arity) (hb : base.val=L.base) (fit : levelStart L 0 < 2^w)
+ (m : Memory w) (v : Visit A w) (room : (m (P₀).ordinal.val).val < directoryRows L)
+ (active : m (P₀).ordinal.val < m (P₀).rows.val)
+ (st : A.operand base m v.phase (A.visit v.phase).initial = v.start)
+ (stop : A.operand base m v.phase (A.visit v.phase).stop = v.stop)
+ (args : ∀ i, A.operand base m v.phase ((A.visit v.phase).params i) = v.params i) : v.Launch P₀ m := by
+ have eq : evaluated A base m v.phase v.fuel v.choices = v := by
+ cases v
+ simp_all [evaluated]
+ exact funext args
+ exact eq ▸ evaluated_launch A base L hg hb fit m v.phase v.fuel v.choices room active
+
+/-- A valid row at a script visit has the worker tag selected by that visit.
+This equality is recovered from the prepared memory even when the source scan
+is empty. -/
+theorem worker_eq_phase (L : Layout) (hg : g₀=L.shape.arity) (hb : base.val=L.base) (fit : levelStart L 0 < 2^w)
+ (m : Memory w) {cap : ℕ} (s : Online.Run.Step A.size A.size w)
+ (valid : s.Valid A.plan P₀ cap m) (room : (m (P₀).ordinal.val).val < directoryRows L)
+ (tags : A.size+1 ≤ 2^w) : s.row.worker=s.phase := by
+ have ready : Ready A.catalog s.row.worker P₀ (Directory.words A.catalog P₀ s.row.worker s.row.input)
+ (Directory.bound A.catalog P₀ s.row.input) (s.row.dataMemory A.catalog P₀) := by
+ have h := valid.source.frame
+ cases hlist : s.row.reports <;> rw [hlist] at h <;> exact h.1
+ have a := ready.1
+ change (Directory.prepared A.catalog P₀ s.row.input) (P₀).tag.val = _ at a
+ rw [valid.input] at a
+ have b := (evaluated_launch A base L hg hb fit m s.phase s.row.fuel s.row.choices room valid.active).ready.1
+ have eq : LiveStageLink.tagWord w s.row.worker.succ = LiveStageLink.tagWord w s.phase.succ := a.symm.trans b
+ have val := congrArg Fin.val eq
+ change (s.row.worker.val+1)%2^w = (s.phase.val+1)%2^w at val
+ have hw : s.row.worker.val+1 < 2^w := s.row.worker.succ.isLt.trans_le tags
+ have hj : s.phase.val+1 < 2^w := s.phase.succ.isLt.trans_le tags
+ rw [Nat.mod_eq_of_lt hw,Nat.mod_eq_of_lt hj] at val
+ exact Fin.ext (by omega)
+
+end CompressorRecords.SourceOnline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceObservableFrame.lean b/lean/OAI/Computability/VPVNP/CompressorSourceObservableFrame.lean
new file mode 100644
index 0000000000..f5fa33208b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceObservableFrame.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.CompressorSourceWalk
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-!
+# Recovering a write footprint from native replay and an external frame
+
+Once a native schedule reads only its data region, the same reports execute
+on every memory agreeing there. A write to an outside cell would force its
+final value independently of its initial value. Thus a frame theorem valid
+for all such initial memories excludes even temporary writes to the cell.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceTransport
+
+open BurstRAM
+
+variable {w : ℕ} {J : Type*} {src : J → Memory w → List (Report w) → Prop}
+variable {data : ℕ → Prop}
+
+private theorem write_forces {a v : Word w} (es : List (Event w)) (hit : Event.write a v ∈ es)
+ (m m' : Memory w) : after m es a.val = after m' es a.val := by
+ have point {q q' : Memory w} (h : q a.val = q' a.val) (tail : List (Event w)) :
+ after q tail a.val = after q' tail a.val := by
+ induction tail generalizing q q' with
+ | nil => exact h
+ | cons e es ih =>
+ apply ih
+ cases e <;> simp only [update,writeMemory]
+ all_goals first | exact h | split <;> first | rfl | exact h
+ induction es generalizing m m' with
+ | nil => simp at hit
+ | cons e es ih =>
+ rcases List.mem_cons.mp hit with he|rest
+ · subst e
+ exact point (q := update m (.write a v)) (q' := update m' (.write a v)) (by simp [update,writeMemory]) es
+ · exact ih rest (update m e) (update m' e)
+
+/-- If the same log preserves every value in the complement, a native
+instruction cannot have written there at any point of that log. -/
+theorem writes_of_replay [Nontrivial (Word w)] (m : Memory w) (es : List (Event w))
+ (frame : ∀ m' : Memory w, Agree data m m' → ∀ x, ¬ data x → after m' es x = m' x) :
+ Writes data es := by
+ intro a v hit
+ by_contra ha
+ obtain ⟨u,hu⟩ := exists_ne (m a.val)
+ let m' := writeMemory m a u
+ have agree : Agree data m m' := fun x hx => by
+ change m x = if x = a.val then u else m x
+ have hn : x ≠ a.val := fun he => ha (he ▸ hx)
+ simp [hn]
+ have orig := frame m (fun _ _ => rfl) a.val ha
+ have alt := frame m' agree a.val ha
+ have forced := write_forces es hit m' m
+ rw [alt,orig] at forced
+ exact hu (by simpa [m',writeMemory] using forced)
+
+theorem walk_deterministic (det : ∀ j m a b, src j m a → src j m b → a = b)
+ {js : List J} {m : Memory w} {as bs : List (Report w)}
+ (h : SourceWalk src js m as) (g : SourceWalk src js m bs) : as = bs := by
+ induction h generalizing bs with
+ | done => cases g; rfl
+ | @next j js m a b ha hb ih =>
+ cases g with
+ | @next _ _ _ a' b' ha' hb' =>
+ obtain rfl := det j m a a' ha ha'
+ exact congrArg (a++·) (ih hb')
+
+/-- A heterogeneous list of actual source calls replays under agreement on
+all the addresses read by its complete event log. -/
+theorem replay_walk
+ (transport : ∀ j m m' rs, Agree data m m' → Reads data (eventLog rs) → src j m rs → src j m' rs)
+ {js : List J} {m m' : Memory w} {rs : List (Report w)}
+ (h : SourceWalk src js m rs) (agree : Agree data m m') (rd : Reads data (eventLog rs)) :
+ SourceWalk src js m' rs := by
+ induction h generalizing m' with
+ | done => exact .done _
+ | @next j js m a b ha hb ih =>
+ simp only [eventLog,List.flatMap_append] at rd
+ exact .next (transport j m m' a agree (fun x v hx => rd x v (List.mem_append_left _ hx)) ha)
+ (ih (agree.after _) (fun x v hx => rd x v (List.mem_append_right _ hx)))
+
+end CompressorRecords.SourceTransport
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceOnline.lean b/lean/OAI/Computability/VPVNP/CompressorSourceOnline.lean
new file mode 100644
index 0000000000..6dbd56cd57
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceOnline.lean
@@ -0,0 +1,189 @@
+import OAI.Computability.VPVNP.CompressorSourceWalk
+import OAI.Computability.VPVNP.CompressorOnlineFootprint
+import OAI.Computability.VPVNP.CompressorRecordsOnlineRun
+import OAI.Computability.VPVNP.CompressorRecordsOrdinalRun
+
+/-!
+# Lifting a physical source scan into the online block program
+
+A visit identifies an occurrence of an actual finite worker, its operand
+bank, initial and final cursors, and the complete branch tape. The launch
+certificate reads those operands from the online recipe. The source trace
+then replays on the prepared RAM. The scheduler's ordinal advances once
+and the shared data for the next worker agrees with the raw source memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceOnline
+
+open BurstRAM Schedule BlockPlanner SourceTransport DescriptorSpace
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Values supplied to one occurrence of the script's actual worker. -/
+structure Visit (A : Script) (w : ℕ) where
+ /-- Catalog occurrence identifying the worker used by this visit. -/
+ phase : Fin A.size
+ /-- Private instruction cap for each worker call in this visit. -/
+ fuel : ℕ
+ /-- Initial persistent cursor passed to the worker. -/
+ start : Word w
+ /-- Cursor value marking the end of the scheduled visit. -/
+ stop : Word w
+ /-- Public operand words for the selected catalog worker. -/
+ params : Fin (A.catalog phase).params → Word w
+ /-- Sequence of branch tapes, one per call of this worker. -/
+ choices : List (List Bool)
+
+namespace Visit
+
+variable {A : Script} (v : Visit A w)
+
+/-- Running the selected worker with the visit's operands, cursor, fuel, and tapes yields
+exactly the supplied reports. -/
+def Runs (m : Memory w) (rs : List (Report w)) : Prop :=
+ runSegment ((A.catalog v.phase).table.instantiate w v.params).program v.fuel (some v.start) m v.choices = some rs
+
+/-- Directory row for replaying this visit, using the recipe input computed from the given
+ports and memory. -/
+def row (ports : Ports w) (m : Memory w) (rs : List (Report w)) : Directory.Row A.size w :=
+ ⟨Online.rowInput A.plan ports m v.phase,v.phase,v.fuel,v.choices,rs⟩
+
+/-- The live memory values after the calendar, recipe and launcher calls. -/
+structure Launch (ports : Ports w) (m : Memory w) : Prop where
+ tag : (Online.rowInput A.plan ports m v.phase) ports.tag.val = 0
+ ordinal : (Online.rowInput A.plan ports m v.phase) ports.ordinal.val = m ports.ordinal.val
+ rows : (Online.rowInput A.plan ports m v.phase) ports.rows.val = m ports.rows.val
+ start : Directory.start A.catalog ports (Online.rowInput A.plan ports m v.phase) = v.start
+ stop : Directory.bound A.catalog ports (Online.rowInput A.plan ports m v.phase) = v.stop
+ params : Directory.words A.catalog ports v.phase (Online.rowInput A.plan ports m v.phase) = v.params
+ ready : Ready A.catalog v.phase ports v.params v.stop
+ (Directory.prepared A.catalog ports (Online.rowInput A.plan ports m v.phase))
+ nextOrdinal : ((Directory.prepared A.catalog ports (Online.rowInput A.plan ports m v.phase)) ports.ordinal.val).val =
+ (m ports.ordinal.val).val + 1
+ sameRows : (Directory.prepared A.catalog ports (Online.rowInput A.plan ports m v.phase)) ports.rows.val =
+ m ports.rows.val
+
+end Visit
+
+/-- Cursor guard facts, independent of the control memory inserted by the
+dispatcher. Some scanners advance by a record stride or start at a nonzero
+cursor. -/
+inductive Progress (stop : Word w) : Word w → List (Report w) → Prop where
+ | done {cursor} (closed : stop ≤ cursor) : Progress stop cursor []
+ | next {cursor next r rs} (active : cursor < stop) (returns : r.result = some next)
+ (rest : Progress stop next rs) : Progress stop cursor (r::rs)
+
+theorem Progress.ofValid {d : ℕ} {C : Catalog d} {i : Fin d} {ports : Ports w} {pub : Fin (C i).params → Word w}
+ {stop cursor : Word w} {m : Memory w} {rs : List (Report w)} (h : ValidTrace C i ports pub stop cursor m rs) :
+ Progress stop cursor rs := by
+ induction rs generalizing cursor m with
+ | nil => exact .done h.2
+ | cons r rs ih =>
+ obtain ⟨_,live,next,ret,tail⟩ := h
+ exact .next live ret (ih tail)
+
+theorem Progress.guarded {d : ℕ} {C : Catalog d} {i : Fin d} {ports : Ports w}
+ {pub : Fin (C i).params → Word w} {stop cursor : Word w} {m : Memory w} {rs : List (Report w)}
+ {data : ℕ → Prop} (h : Progress stop cursor rs) (ready : Ready C i ports pub stop m)
+ (writes : Writes data (eventLog rs)) (apart : ∀ x, OrdinalRun.ControlCell (C i).params ports x → ¬ data x) :
+ ValidTrace C i ports pub stop cursor m rs := by
+ induction h generalizing m with
+ | done closed => exact ⟨ready,closed⟩
+ | @next cursor next r rs active ret _ ih =>
+ have wh : Writes data r.events := fun a v hv ↦ writes a v (List.mem_append_left _ hv)
+ have wt : Writes data (eventLog rs) := fun a v hv ↦ writes a v (List.mem_append_right _ hv)
+ have stable : OrdinalRun.Preserved (C i).params ports m (after m r.events) :=
+ fun x hx ↦ after_outside m wh (apart x hx)
+ exact ⟨ready,active,next,ret,ih (OrdinalRun.ready_of_preserved C i ports ready stable) wt⟩
+
+variable (A : Script) (L : Layout) (base : Word w)
+local notation "ports" => Workspace.ports (arity A.catalog) base
+local notation "H" => levelStart L 0
+local notation "D" => Online.N A.size A.size
+
+open private port_bounds from OAI.Computability.VPVNP.CompressorOnlineFootprint
+
+private theorem control_below (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w)
+ (i : Fin A.size) (x : ℕ) (hx : OrdinalRun.ControlCell (A.catalog i).params ports x) : x < H := by
+ obtain ⟨_,ho,ht,hfr⟩ := port_bounds A L base hg hb fit
+ have hpre : L.base + 9 ≤ H := by
+ change _ ≤ levelsBase L + 0*levelWords L
+ simp only [Nat.zero_mul,Nat.add_zero,levelsBase,directoryBase,plannerTag,frameBase]
+ omega
+ rcases hx with rfl|rfl|rfl|⟨j,rfl⟩
+ · omega
+ · omega
+ · change (base+8).val < _
+ rw [Fin.val_add,hb]
+ exact (Nat.mod_le _ _).trans_lt (by have hv : (8 : Word w).val ≤ 8 := Nat.mod_le _ _; omega)
+ · let j' : Fin (arity A.catalog+1) := j.castLE (Nat.succ_le_succ (params_le_arity _ _))
+ exact hfr j'
+
+/-- Replay one genuine source packet into the live script, producing the
+actual online step and the data and ordinal needed by the next packet. -/
+theorem packet (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w)
+ (v : Visit A w) (raw m : Memory w) (rs : List (Report w)) (cap : ℕ)
+ (agree : Agree (H ≤ ·) raw m) (phase : (Online.calendar A.plan).phase (m (ports).ordinal.val).val = v.phase.val)
+ (active : m (ports).ordinal.val < m (ports).rows.val) (room : (m (ports).ordinal.val).val < directoryRows L)
+ (launch : v.Launch ports m) (fuel : 0 < v.fuel)
+ (recipeClock : (A.plan.recipes v.phase).2.code.length+1+2*D+5 ≤ cap)
+ (dataClock : v.fuel+3+4*((A.catalog v.phase).params+1)+2*D+5 ≤ cap)
+ (run : v.Runs raw rs) (progress : Progress v.stop v.start rs)
+ (read : Reads (H ≤ ·) (eventLog rs)) (write : Writes (H ≤ ·) (eventLog rs)) :
+ let r := v.row ports m rs
+ let post := Online.post A.catalog A.size ports r
+ Online.Run.Step.Valid A.plan ports cap m ⟨v.phase,r⟩ ∧
+ Agree (H ≤ ·) (after raw (eventLog rs)) post ∧
+ (post (ports).ordinal.val).val = (m (ports).ordinal.val).val+1 ∧
+ post (ports).rows.val = m (ports).rows.val := by
+ intro r post
+ have run' : runSegment ((A.catalog r.worker).table.instantiate w (Directory.words A.catalog ports r.worker r.input)).program
+ r.fuel (some (Directory.start A.catalog ports r.input)) raw r.choices = some r.reports := by
+ change runSegment ((A.catalog v.phase).table.instantiate w
+ (Directory.words A.catalog ports v.phase (Online.rowInput A.plan ports m v.phase))).program v.fuel
+ (some (Directory.start A.catalog ports (Online.rowInput A.plan ports m v.phase))) raw v.choices = some rs
+ rw [launch.params,launch.start]; exact run
+ obtain ⟨on,same⟩ := OnlineFootprint.replay A L base hg hb fit raw m v.phase r room rfl agree read run'
+ have apart := fun x h ↦ not_le_of_gt (control_below A L base hg hb fit v.phase x h)
+ have trace := progress.guarded launch.ready write apart
+ have valid : r.Valid A.catalog ports := by
+ refine ⟨launch.tag,?_,fuel,on,?_⟩
+ · change (Online.rowInput A.plan ports m v.phase) (ports).ordinal.val < (Online.rowInput A.plan ports m v.phase) (ports).rows.val
+ rw [launch.ordinal,launch.rows]; exact active
+ · change ValidTrace A.catalog v.phase ports (Directory.words A.catalog ports v.phase (Online.rowInput A.plan ports m v.phase))
+ (Directory.bound A.catalog ports (Online.rowInput A.plan ports m v.phase))
+ (Directory.start A.catalog ports (Online.rowInput A.plan ports m v.phase)) _ rs
+ rw [launch.params,launch.stop,launch.start]; exact trace
+ have hout (x : ℕ) (hx : OrdinalRun.ControlCell (A.catalog v.phase).params ports x) :
+ r.endMemory A.catalog ports x = r.dataMemory A.catalog ports x :=
+ after_outside _ write (apart x hx)
+ obtain ⟨_,ho,ht,_⟩ := port_bounds A L base hg hb fit
+ have hOrd : (ports).ordinal.val ≠ (ports).tag.val := by omega
+ have hRows : (ports).rows.val ≠ (ports).tag.val := by
+ change (base+8).val ≠ (base+6).val
+ have hpre : L.base+9 ≤ H := by
+ simp only [levelStart,levelsBase,Nat.zero_mul,Nat.add_zero,directoryBase,plannerTag,frameBase]; omega
+ have hs : L.base+8 < 2^w := (by omega : L.base+8 < H).trans fit
+ change (base.val+(8 : Word w).val)%2^w ≠ (base.val+(6 : Word w).val)%2^w
+ change (base.val+(8 % 2^w))%2^w ≠ (base.val+(6 % 2^w))%2^w
+ rw [hb,Nat.mod_eq_of_lt (by omega : 8<2^w),Nat.mod_eq_of_lt (by omega : 6<2^w),
+ Nat.mod_eq_of_lt hs,Nat.mod_eq_of_lt (by omega)]
+ omega
+ refine ⟨⟨phase,active,rfl,valid,recipeClock,dataClock⟩,same,?_,?_⟩
+ · change (writeMemory _ _ _ (ports).ordinal.val).val = _
+ rw [writeMemory,ite_eq_right hOrd,hout _ (Or.inr (Or.inl rfl))]
+ exact launch.nextOrdinal
+ · change writeMemory _ _ _ (ports).rows.val = _
+ rw [writeMemory,ite_eq_right hRows,hout _ (Or.inr (Or.inr (Or.inl rfl)))]
+ exact launch.sameRows
+
+end CompressorRecords.SourceOnline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourcePitch.lean b/lean/OAI/Computability/VPVNP/CompressorSourcePitch.lean
new file mode 100644
index 0000000000..c3cb75354c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourcePitch.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.CompressorSourceLaunch
+
+/-! # Preservation of the online calendar's level stride -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceOnline
+
+open BurstRAM DescriptorSpace BlockPlanner Schedule SourceTransport
+open scoped Fin.CommRing
+open private field_addresses from OAI.Computability.VPVNP.CompressorScriptSnapshot
+
+variable {w : ℕ} (A : Script) (L : Layout) (base : Word w)
+local notation "g" => arity A.catalog
+local notation "pt" => Workspace.ports (arity A.catalog) base
+local notation "H" => levelStart L 0
+
+/-- The pitch word is strictly above the complete active frame and below
+every directory row. A source packet writing in the data suffix also leaves
+it untouched. All five parts of the actual packet preserve its value. -/
+theorem pitch_packet (hg : g = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w)
+ (v : Visit A w) (m : Memory w) (rs : List (Report w))
+ (room : (m (pt).ordinal.val).val < directoryRows L) (writes : Writes (H ≤ ·) (eventLog rs)) :
+ (Online.post A.catalog A.size pt (v.row pt m rs)) ((pt).directory-1).val = m ((pt).directory-1).val := by
+ let gap := ((pt).directory-1).val
+ have top : H = L.base+(11+g)+directoryRows L*(g+3) := by
+ rw [hg]
+ simp only [levelStart,levelsBase,directoryBase,plannerTag,frameBase,Nat.zero_mul,Nat.add_zero]
+ omega
+ have dirRoom : base.val+(11+g) < 2^w := by omega
+ obtain ⟨tagAddr,ordAddr,_,dirAddr,frameAddr⟩ := field_addresses g base dirRoom
+ have gapVal : gap = base.val+(10+g) := by
+ have one : (1 : Word w).val = 1 := by
+ change 1 % 2^w = 1
+ exact Nat.mod_eq_of_lt (by omega)
+ have lo : (1 : Word w) ≤ (pt).directory := Fin.le_def.mpr (by rw [one,dirAddr]; omega)
+ rw [show gap = ((pt).directory-1).val from rfl, Fin.sub_val_of_le lo,dirAddr,one]
+ omega
+ have tagNe : gap ≠ (pt).tag.val := by omega
+ have ordNe : gap ≠ (pt).ordinal.val := by omega
+ have frameNe (i : Fin (g+1)) : gap ≠ ((pt).activeFrame+(i.val : Word w)).val := by
+ have := frameAddr i
+ have := i.isLt
+ omega
+ let j := v.phase
+ let pre := Online.calendarMemory (d := A.size) pt m j
+ have preGap : pre gap = m gap := ite_eq_right tagNe
+ have preOrd : pre (pt).ordinal.val = m (pt).ordinal.val := ite_eq_right (by omega)
+ have offset : (pt).directory.val+(pre (pt).ordinal.val).val*(g+3) < H := by
+ rw [preOrd,top,dirAddr,hb]
+ exact Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_right room (by omega)) _
+ have rowVal := Directory.rowBase_val A.catalog pt pre (offset.trans fit)
+ have before : gap < (Controller.rowBase g (pt).data pre).val := by
+ change gap < (Directory.rowBase A.catalog pt pre).val
+ rw [rowVal,dirAddr,gapVal]
+ omega
+ let s := LevelCalendar.header (Online.calendar A.plan) (pt).data m
+ let R := (A.phase j).recipe
+ have bound := OnlineFootprint.row_bound A L base hg hb fit pre (preOrd ▸ room)
+ have preserved := RowRecipe.row_outside R (pt).data s pre
+ (by rw [PhaseRecipe.recipe_address]; exact bound.trans fit.le) gap
+ (.inl (by rw [PhaseRecipe.recipe_address]; exact before))
+ rw [RowRecipe.after_row] at preserved
+ have input : Online.rowInput A.plan pt m j gap = m gap := by
+ change writeMemory (Greedy.writeRow pre (R.address (pt).data s pre) (R.words (pt).data s pre)) (pt).tag 0 gap = _
+ rw [writeMemory,ite_eq_right tagNe,preserved,preGap]
+ have prep : Directory.prepared A.catalog pt (Online.rowInput A.plan pt m j) gap = m gap :=
+ (Controller.after_row_outside g (pt).data _ gap ordNe tagNe frameNe).trans input
+ have source := after_outside (Directory.prepared A.catalog pt (Online.rowInput A.plan pt m j))
+ writes (i := gap) (by omega)
+ change writeMemory (after (Directory.prepared A.catalog pt (Online.rowInput A.plan pt m j)) (eventLog rs))
+ (pt).tag _ gap = m gap
+ rw [writeMemory,ite_eq_right tagNe,source,prep]
+
+end CompressorRecords.SourceOnline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceScanned.lean b/lean/OAI/Computability/VPVNP/CompressorSourceScanned.lean
new file mode 100644
index 0000000000..8d0e85b6b0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceScanned.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.CompressorScanProgress
+import OAI.Computability.VPVNP.CompressorSourceSequence
+
+/-!
+# Using ordinal scan certificates in online source packets
+
+An ordinal trace gives the scheduler's strict cursor test until the exclusive
+stop and its closed test at the stop. Each source scan's access intervals are
+included in the persistent level region. A single instruction cap can account
+for every finite recipe and the frame overhead of every worker in the script.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open BurstRAM SourceTransport BlockPlanner DescriptorSpace Schedule
+open scoped Fin.CommRing
+
+namespace SourceOnline
+
+variable {w : ℕ} {A : Script} {L : Layout} {cap first N : ℕ}
+variable {p : SourceWalk.Packet (SourceOnline.Visit A w) w}
+local notation "dispatch" => Online.N A.size A.size
+
+/-- Convert an actual stage's raw ordinal and address evidence to the packet
+checked by the online source sequence. The controller prefix is below the
+level base, so the read and write inclusions are sufficient for replay. -/
+theorem Checked.ofScanned {readable writable : ℕ → Prop}
+ (positiveFuel : 0 < p.stage.fuel)
+ (recipeClock : (A.plan.recipes p.stage.phase).2.code.length+1+2*dispatch+5 ≤ cap)
+ (dataClock : p.stage.fuel+3+4*((A.catalog p.stage.phase).params+1)+2*dispatch+5 ≤ cap)
+ (start : p.stage.start = (first : Word w)) (stop : p.stage.stop = (N : Word w))
+ (fit : N < 2^w) (shape : StageFrame.Scanned first N p.reports)
+ (rd : Reads readable (eventLog p.reports)) (wr : Writes writable (eventLog p.reports))
+ (readAt : ∀ x, readable x → levelStart L 0 ≤ x) (writeAt : ∀ x, writable x → levelStart L 0 ≤ x) :
+ Checked A L cap p := by
+ refine ⟨positiveFuel,recipeClock,dataClock,?_,fun a v h ↦ readAt _ (rd a v h),
+ fun a v h ↦ writeAt _ (wr a v h)⟩
+ rw [stop,start]
+ exact shape.toProgress fit
+
+/-- The planner part is fixed with the program text. Only the bound for the
+native worker calls may depend on the live word width. -/
+def scanCap (A : Script) (maxFuel : ℕ) : ℕ :=
+ max (Finset.univ.sup fun i ↦ (A.plan.recipes i).2.code.length+1+2*Online.N A.size A.size+5)
+ (maxFuel+3+4*(Schedule.arity A.catalog+1)+2*Online.N A.size A.size+5)
+
+/-- Uniform overhead for a fixed compiled script. -/
+theorem scanCap_le (A : Script) (maxFuel : ℕ) : scanCap A maxFuel ≤ maxFuel+scanCap A 0 := by
+ unfold scanCap
+ omega
+
+theorem scanCap_clocks (maxFuel : ℕ) (hp : p.stage.fuel ≤ maxFuel) (hc : scanCap A maxFuel ≤ cap) :
+ (A.plan.recipes p.stage.phase).2.code.length+1+2*dispatch+5 ≤ cap ∧
+ p.stage.fuel+3+4*((A.catalog p.stage.phase).params+1)+2*dispatch+5 ≤ cap := by
+ have hr := Finset.le_sup (f := fun i ↦ (A.plan.recipes i).2.code.length+1+2*dispatch+5)
+ (Finset.mem_univ p.stage.phase)
+ have ar := params_le_arity A.catalog p.stage.phase
+ exact ⟨hr.trans ((le_max_left _ _).trans hc),
+ (show p.stage.fuel+3+4*((A.catalog p.stage.phase).params+1)+2*dispatch+5 ≤
+ maxFuel+3+4*(Schedule.arity A.catalog+1)+2*dispatch+5 by omega).trans ((le_max_right _ _).trans hc)⟩
+
+/-- Apply the native worker to its own packet inputs and tape. The result
+is a checked packet and the worker's exact terminal memory invariant. -/
+theorem Checked.ofScanRun (maxFuel : ℕ) (positive : 0 < p.stage.fuel)
+ (fuel : p.stage.fuel ≤ maxFuel) (capFits : scanCap A maxFuel ≤ cap)
+ (start : p.stage.start = (first : Word w)) (stop : p.stage.stop = (N : Word w))
+ (tapes : p.stage.choices = List.replicate (N-first) []) (first_le : first ≤ N) (fit : N < 2^w)
+ (I : ℕ → Memory w → Prop) (events : Memory w → Word w → List (Event w))
+ (readable writable : ℕ → Prop)
+ (readAt : ∀ x, readable x → levelStart L 0 ≤ x) (writeAt : ∀ x, writable x → levelStart L 0 ≤ x)
+ (native : let M := ((A.catalog p.stage.phase).table.instantiate w p.stage.params).program
+ ∀ j, first ≤ j → j < N → ∀ m, execute M p.stage.fuel (M.start (j : Word w)) m [] =
+ some ⟨events m (j : Word w),some ((j : Word w)+1)⟩)
+ (step : ∀ j, first ≤ j → j < N → ∀ m, I j m → I (j+1) (after m (events m (j : Word w))) ∧
+ Reads readable (events m (j : Word w)) ∧ Writes writable (events m (j : Word w)))
+ (initial : I first p.input) (run : p.stage.Runs p.input p.reports) :
+ Checked A L cap p ∧ I N p.output := by
+ obtain ⟨rc,dc⟩ := scanCap_clocks maxFuel fuel capFits
+ rw [Visit.Runs,start,tapes] at run
+ obtain ⟨shape,final,rd,wr⟩ := StageFrame.scan _ p.stage.fuel first N I events readable writable
+ native step first_le p.input p.reports initial run
+ exact ⟨Checked.ofScanned positive rc dc start stop fit shape rd wr readAt writeAt,final⟩
+
+end SourceOnline
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceSequence.lean b/lean/OAI/Computability/VPVNP/CompressorSourceSequence.lean
new file mode 100644
index 0000000000..98a7b7407d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceSequence.lean
@@ -0,0 +1,169 @@
+import OAI.Computability.VPVNP.CompressorSourcePitch
+import OAI.Computability.VPVNP.CompressorSourceBankFrame
+import OAI.Computability.VPVNP.CompressorOnlineBranchCut
+
+/-!
+# Executing a complete chronological sequence of native descriptor visits
+
+The input is the sequence of original source packets and its memory
+invariants. Each row recipe is evaluated at its own calendar ordinal in
+any live memory that agrees with that packet's input data. The construction
+threads the *actual* post-memory of the dispatcher through all packets,
+preserving source reports and branch choices, and terminates at exhaustion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceOnline
+
+open BurstRAM BlockPlanner DescriptorSpace Schedule SourceTransport
+open scoped Fin.CommRing
+
+variable {w : ℕ} (A : Script) (L : Layout) (base : Word w)
+local notation "pt" => Workspace.ports (arity A.catalog) base
+local notation "H" => levelStart L 0
+local notation "D" => Online.N A.size A.size
+local notation "strideCell" => Fin.val (Schedule.Ports.directory pt - 1)
+local notation "tag" => LiveStageLink.tagWord w (Online.calendarIndex A.size A.size)
+local notation "Pkt" => SourceWalk.Packet (Visit A w) w
+
+/-- Facts obtained by inspecting the actual source program for this packet. -/
+structure Checked (cap : ℕ) (p : Pkt) : Prop where
+ positiveFuel : 0 < p.stage.fuel
+ recipeClock : (A.plan.recipes p.stage.phase).2.code.length+1+2*D+5 ≤ cap
+ dataClock : p.stage.fuel+3+4*((A.catalog p.stage.phase).params+1)+2*D+5 ≤ cap
+ progress : Progress p.stage.stop p.stage.start p.reports
+ read : Reads (H ≤ ·) (eventLog p.reports)
+ write : Writes (H ≤ ·) (eventLog p.reports)
+
+/-- Physical recipe evaluation at the packet's true offset. -/
+def Prepared (ordinal total : ℕ) (p : Pkt) : Prop :=
+ ∀ m : Memory w, Agree (H ≤ ·) p.input m → (m (pt).ordinal.val).val = ordinal →
+ (m (pt).rows.val).val = total → m (pt).tag.val = tag → m strideCell = (levelWords L : Word w) →
+ (Online.calendar A.plan).phase ordinal = p.stage.phase.val ∧ p.stage.Launch pt m
+
+private theorem fold_append (m : Memory w) (r s : List (Report w)) :
+ after m (eventLog (r++s)) = after (after m (eventLog r)) (eventLog s) :=
+ SourceWalk.after_append m r s
+
+/-- A semantic source-packet sequence determines valid steps of the concrete
+online program, with precisely the same worker reports and worker tapes. -/
+theorem interval_stable (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w)
+ (cap ordinal total : ℕ) (m raw : Memory w) (ps : List Pkt)
+ (chron : SourceWalk.Chronological Visit.Runs raw ps)
+ (checks : ∀ p ∈ ps, Checked A L cap p)
+ (prepare : ∀ i : Fin ps.length, Prepared A L base (ordinal+i.val) total ps[i.val])
+ (count : ordinal+ps.length ≤ total) (room : total ≤ directoryRows L)
+ (agree : Agree (H ≤ ·) raw m) (ho : (m (pt).ordinal.val).val=ordinal) (ht : (m (pt).rows.val).val=total)
+ (hTag : m (pt).tag.val = tag) (pitch : m strideCell = (levelWords L : Word w)) :
+ ∃ steps : List (Online.Run.Step A.size A.size w),
+ Online.Run.Interval A.plan pt cap m steps ∧
+ steps.map Online.Run.Step.phase = ps.map (fun p ↦ p.stage.phase) ∧
+ steps.map (fun s ↦ s.row.reports) = ps.map SourceWalk.Packet.reports ∧
+ steps.map (fun s ↦ s.row.choices) = ps.map (fun p ↦ p.stage.choices) ∧
+ Agree (H ≤ ·) (after raw (eventLog (ps.flatMap SourceWalk.Packet.reports)))
+ (Online.Run.finalMemory (C := A.catalog) pt m steps) ∧
+ ((Online.Run.finalMemory (C := A.catalog) pt m steps) (pt).ordinal.val).val = ordinal+ps.length ∧
+ (Online.Run.finalMemory (C := A.catalog) pt m steps) (pt).rows.val = m (pt).rows.val ∧
+ (Online.Run.finalMemory (C := A.catalog) pt m steps) strideCell = m strideCell ∧
+ SourceBankFrame.Stable (base.val+6) m (Online.Run.intervalLog A.plan pt m steps) := by
+ induction ps generalizing raw m ordinal with
+ | nil =>
+ exact ⟨[],trivial,rfl,rfl,rfl,agree,by simpa only [Online.Run.finalMemory,List.length_nil,Nat.add_zero] using ho,rfl,rfl,trivial⟩
+ | cons p ps ih =>
+ obtain ⟨rfl,run,rest⟩ := chron
+ have lead : Prepared A L base ordinal total p := by simpa using prepare (0 : Fin (p::ps).length)
+ have active : m (pt).ordinal.val < m (pt).rows.val := by
+ apply Fin.lt_def.mpr; simp only [List.length_cons] at count; omega
+ obtain ⟨phase,launch⟩ := lead m agree ho ht hTag pitch
+ let r := p.stage.row pt m p.reports
+ let s : Online.Run.Step A.size A.size w := ⟨p.stage.phase,r⟩
+ let post := Online.post A.catalog A.size pt r
+ have ck := checks p List.mem_cons_self
+ obtain ⟨hv,ha,ho',ht'⟩ := packet A L base hg hb fit p.stage p.input m p.reports cap agree
+ (ho ▸ phase) active ((Fin.lt_def.mp active).trans_le (ht.le.trans room)) launch ck.positiveFuel
+ ck.recipeClock ck.dataClock run ck.progress ck.read ck.write
+ have prepTail (i : Fin ps.length) : Prepared A L base ((ordinal+1)+i.val) total ps[i.val] := by
+ simpa only [Fin.val_succ,List.getElem_cons_succ,Nat.add_assoc,Nat.add_comm 1 i.val] using prepare i.succ
+ have postTag : post (pt).tag.val = tag := by simp [post,Online.post,writeMemory]
+ have stride : post strideCell = m strideCell :=
+ pitch_packet A L base hg hb fit p.stage m p.reports ((Fin.lt_def.mp active).trans_le (ht.le.trans room)) ck.write
+ obtain ⟨ss,hss,hp,hr,hc,hm,hl,htail,hstride,hstable⟩ := ih (ordinal := ordinal+1) (raw := p.output) (m := post) rest
+ (fun q hq ↦ checks q (List.mem_cons_of_mem _ hq)) prepTail (by simp only [List.length_cons] at count; omega)
+ ha (ho'.trans (congrArg (·+1) ho)) ((congrArg Fin.val ht').trans ht) postTag (stride.trans pitch)
+ refine ⟨s::ss,⟨hv,hss⟩,?_,?_,?_,?_,?_,?_,?_,?_⟩
+ · exact congrArg (p.stage.phase :: ·) hp
+ · exact congrArg (p.reports :: ·) hr
+ · exact congrArg (p.stage.choices :: ·) hc
+ · simpa only [List.flatMap_cons,fold_append,Online.Run.finalMemory,SourceWalk.Packet.output,s,post] using hm
+ · simpa only [Online.Run.finalMemory,List.length_cons,s,post,Nat.add_assoc,Nat.add_comm 1 ps.length] using hl
+ · exact htail.trans ht'
+ · exact hstride.trans stride
+ · apply (SourceBankFrame.row_stable A L base hg hb fit m p.stage.phase r
+ ((Fin.lt_def.mp active).trans_le (ht.le.trans room)) hv.input hv.source ck.write).append
+ rw [(Online.row_effect A.plan pt m p.stage.phase r hv.input hv.source 0).1]
+ exact hstable
+
+/-- A semantic source-packet sequence determines valid steps of the concrete
+online program, with precisely the same worker reports and worker tapes. -/
+theorem interval (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w)
+ (cap ordinal total : ℕ) (m raw : Memory w) (ps : List Pkt)
+ (chron : SourceWalk.Chronological Visit.Runs raw ps)
+ (checks : ∀ p ∈ ps, Checked A L cap p)
+ (prepare : ∀ i : Fin ps.length, Prepared A L base (ordinal+i.val) total ps[i.val])
+ (count : ordinal+ps.length ≤ total) (room : total ≤ directoryRows L)
+ (agree : Agree (H ≤ ·) raw m) (ho : (m (pt).ordinal.val).val=ordinal) (ht : (m (pt).rows.val).val=total)
+ (hTag : m (pt).tag.val = tag) (pitch : m strideCell = (levelWords L : Word w)) :
+ ∃ steps : List (Online.Run.Step A.size A.size w),
+ Online.Run.Interval A.plan pt cap m steps ∧
+ steps.map Online.Run.Step.phase = ps.map (fun p ↦ p.stage.phase) ∧
+ steps.map (fun s ↦ s.row.reports) = ps.map SourceWalk.Packet.reports ∧
+ steps.map (fun s ↦ s.row.choices) = ps.map (fun p ↦ p.stage.choices) ∧
+ Agree (H ≤ ·) (after raw (eventLog (ps.flatMap SourceWalk.Packet.reports)))
+ (Online.Run.finalMemory (C := A.catalog) pt m steps) ∧
+ ((Online.Run.finalMemory (C := A.catalog) pt m steps) (pt).ordinal.val).val = ordinal+ps.length ∧
+ (Online.Run.finalMemory (C := A.catalog) pt m steps) (pt).rows.val = m (pt).rows.val ∧
+ (Online.Run.finalMemory (C := A.catalog) pt m steps) strideCell = m strideCell := by
+ obtain ⟨steps,valid,phase,reports,bits,memory,ord,rows,stride,_⟩ :=
+ interval_stable A L base hg hb fit cap ordinal total m raw ps chron checks prepare count room agree ho ht hTag pitch
+ exact ⟨steps,valid,phase,reports,bits,memory,ord,rows,stride⟩
+
+private theorem valid_at_end {d w i r cap : ℕ} {C : Catalog d} {plan : Online.Config C i r} {ports : Ports w}
+ {m : Memory w} (steps : List (Online.Run.Step d (i+r) w)) (hs : Online.Run.Interval plan ports cap m steps)
+ (endRows : let z := Online.Run.finalMemory (C := C) ports m steps
+ z ports.rows.val ≤ z ports.ordinal.val) : Online.Run.Valid plan ports cap m steps := by
+ induction steps generalizing m with
+ | nil => exact endRows
+ | cons s rest ih => exact ⟨hs.1,ih hs.2 endRows⟩
+
+/-- A semantic source-packet sequence determines valid steps of the concrete
+online program, with precisely the same worker reports and worker tapes. -/
+theorem sequence (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w)
+ (cap ordinal total : ℕ) (m raw : Memory w) (ps : List Pkt)
+ (chron : SourceWalk.Chronological Visit.Runs raw ps)
+ (checks : ∀ p ∈ ps, Checked A L cap p)
+ (prepare : ∀ i : Fin ps.length, Prepared A L base (ordinal+i.val) total ps[i.val])
+ (count : ordinal+ps.length = total) (room : total ≤ directoryRows L)
+ (agree : Agree (H ≤ ·) raw m) (ho : (m (pt).ordinal.val).val=ordinal) (ht : (m (pt).rows.val).val=total)
+ (hTag : m (pt).tag.val = tag) (pitch : m strideCell = (levelWords L : Word w)) :
+ ∃ steps : List (Online.Run.Step A.size A.size w),
+ Online.Run.Valid A.plan pt cap m steps ∧
+ steps.map Online.Run.Step.phase = ps.map (fun p ↦ p.stage.phase) ∧
+ steps.map (fun s ↦ s.row.reports) = ps.map SourceWalk.Packet.reports ∧
+ steps.map (fun s ↦ s.row.choices) = ps.map (fun p ↦ p.stage.choices) ∧
+ Agree (H ≤ ·) (after raw (eventLog (ps.flatMap SourceWalk.Packet.reports)))
+ (Online.Run.finalMemory (C := A.catalog) pt m steps) := by
+ obtain ⟨steps,valid,phase,reports,choices,mem,ordinalEnd,rowsEnd,_⟩ := interval A L base hg hb fit cap ordinal total m raw ps
+ chron checks prepare count.le room agree ho ht hTag pitch
+ refine ⟨steps,valid_at_end steps valid ?_,phase,reports,choices,mem⟩
+ apply Fin.le_def.mpr
+ rw [rowsEnd,ht,ordinalEnd,count]
+
+
+end CompressorRecords.SourceOnline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceTransport.lean b/lean/OAI/Computability/VPVNP/CompressorSourceTransport.lean
new file mode 100644
index 0000000000..3084383087
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceTransport.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.RAMChain
+
+/-!
+# Transporting native source runs across scheduler writes
+
+The online calendar changes its control cells between calls. If the
+original reports read only data cells, the same worker produces exactly
+the same reports in any memory agreeing on those cells. Every prefix of
+the run preserves the data agreement. A separate write condition preserves
+the scheduler's control cells throughout the source scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceTransport
+
+open BurstRAM
+variable {w : ℕ}
+
+/-- The two memories return the same word at every address satisfying the data predicate. -/
+def Agree (data : ℕ → Prop) (m m' : Memory w) : Prop := ∀ i, data i → m i = m' i
+
+/-- Every read recorded in the event list addresses a cell satisfying the data predicate. -/
+def Reads (data : ℕ → Prop) (es : List (Event w)) : Prop :=
+ ∀ a v, Event.read a v ∈ es → data a.val
+
+/-- Every write recorded in the event list addresses a cell satisfying the data predicate. -/
+def Writes (data : ℕ → Prop) (es : List (Event w)) : Prop :=
+ ∀ a v, Event.write a v ∈ es → data a.val
+
+theorem Agree.update {data : ℕ → Prop} {m m' : Memory w} (h : Agree data m m') (e : Event w) :
+ Agree data (update m e) (update m' e) := by
+ intro i hi
+ cases e <;> simp only [BurstRAM.update,writeMemory]
+ all_goals first | exact h i hi | split <;> first | rfl | exact h i hi
+
+theorem Agree.after {data : ℕ → Prop} {m m' : Memory w} (h : Agree data m m') (es : List (Event w)) :
+ Agree data (after m es) (after m' es) := by
+ induction es generalizing m m' with
+ | nil => exact h
+ | cons e es ih => exact ih (h.update e)
+
+theorem Reads.tail {data : ℕ → Prop} {e : Event w} {es : List (Event w)} (h : Reads data (e::es)) :
+ Reads data es := fun a v hv ↦ h a v (List.mem_cons_of_mem e hv)
+
+theorem Writes.tail {data : ℕ → Prop} {e : Event w} {es : List (Event w)} (h : Writes data (e::es)) :
+ Writes data es := fun a v hv ↦ h a v (List.mem_cons_of_mem e hv)
+
+theorem correct {data : ℕ → Prop} {m m' : Memory w} {es : List (Event w)}
+ (agree : Agree data m m') (reads : Reads data es) (ok : Correct m es) : Correct m' es := by
+ induction es generalizing m m' with
+ | nil => trivial
+ | cons e es ih =>
+ have tail := reads.tail
+ cases e with
+ | read a v => exact ⟨ok.1.trans (agree _ (reads a v (List.mem_cons_self))), ih agree tail ok.2⟩
+ | tick => exact ih (agree.update .tick) tail ok
+ | choice b => exact ih (agree.update (.choice b)) tail ok
+ | write a v => exact ih (agree.update (.write a v)) tail ok
+
+/-- The sequence of native calls is identical under any changes to addresses
+outside its read region. Private state resets and branch choices are included. -/
+theorem segment {C : Type*} {P : Program w C} {fuel s m m' bs rs} {data : ℕ → Prop}
+ (run : runSegment P fuel s m bs = some rs) (agree : Agree data m m') (reads : Reads data (eventLog rs)) :
+ runSegment P fuel s m' bs = some rs ∧ Agree data (after m (eventLog rs)) (after m' (eventLog rs)) := by
+ obtain ⟨calls,ok,choices⟩ := (runSegment_iff ..).mp run
+ exact ⟨(runSegment_iff ..).mpr ⟨calls,correct agree reads ok,choices⟩,agree.after _⟩
+
+/-- No call in the native segment changes a cell outside the permitted writes. -/
+theorem after_outside {data : ℕ → Prop} (m : Memory w) {es : List (Event w)}
+ (writes : Writes data es) {i : ℕ} (hi : ¬ data i) : after m es i = m i := by
+ induction es generalizing m with
+ | nil => rfl
+ | cons e es ih =>
+ change after (update m e) es i = m i
+ rw [ih _ writes.tail]
+ cases e with
+ | tick | choice | read => rfl
+ | write a v =>
+ have hne : i ≠ a.val := fun h ↦ hi (h ▸ writes a v List.mem_cons_self)
+ exact ite_eq_right hne
+
+/-- Inserting a prefix of online control writes leaves the original source
+run executable and all of its data cells identical in the resulting memory. -/
+theorem after_control {C : Type*} {P : Program w C} {fuel s m bs rs} (control : List (Event w))
+ {data : ℕ → Prop} (run : runSegment P fuel s m bs = some rs)
+ (outside : Writes (fun i ↦ ¬ data i) control) (reads : Reads data (eventLog rs)) :
+ runSegment P fuel s (after m control) bs = some rs ∧
+ Agree data (after m (eventLog rs)) (after (after m control) (eventLog rs)) :=
+ segment run (fun _ hi ↦ (after_outside m outside (not_not_intro hi)).symm) reads
+
+end CompressorRecords.SourceTransport
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceWalk.lean b/lean/OAI/Computability/VPVNP/CompressorSourceWalk.lean
new file mode 100644
index 0000000000..1b2c824923
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceWalk.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.RAMChain
+
+/-!
+# Chronological source kernels in external memory
+
+The native descriptor recipe consists of heterogeneous kernels, with
+each segment starting from the data memory produced by the preceding one.
+Packets retain the source ordinal, actual input memory and report list
+when the online dispatcher inserts its control calls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+open BurstRAM
+
+/-- A sequence of heterogeneous native source kernels operating on one shared
+memory. The join keeps their actual reports, including empty phase segments. -/
+inductive SourceWalk {w : ℕ} {J : Type*} (source : J → Memory w → List (Report w) → Prop) :
+ List J → Memory w → List (Report w) → Prop where
+ | done (m) : SourceWalk source [] m []
+ | next {j js m rs ts} (head : source j m rs) (tail : SourceWalk source js (after m (eventLog rs)) ts) :
+ SourceWalk source (j::js) m (rs++ts)
+
+theorem SourceWalk.after_append {w : ℕ} (m : Memory w) (xs ys : List (Report w)) :
+ after m (eventLog (xs++ys)) = after (after m (eventLog xs)) (eventLog ys) := by
+ simp only [eventLog,List.flatMap_append,after,List.foldl_append]
+
+theorem SourceWalk.append {w : ℕ} {J : Type*} {source : J → Memory w → List (Report w) → Prop}
+ {is js : List J} {m : Memory w} {rs ts : List (Report w)}
+ (h : SourceWalk source is m rs) (h' : SourceWalk source js (after m (eventLog rs)) ts) :
+ SourceWalk source (is++js) m (rs++ts) := by
+ induction h with
+ | done => exact h'
+ | @next j is m xs ys hx _ ih =>
+ rw [after_append] at h'
+ simpa only [List.cons_append,List.append_assoc] using SourceWalk.next hx (ih h')
+
+theorem SourceWalk.singleton {w : ℕ} {J : Type*} {source : J → Memory w → List (Report w) → Prop}
+ {i : J} {m : Memory w} {rs : List (Report w)} (h : source i m rs) :
+ SourceWalk source [i] m rs := by simpa using SourceWalk.next h (SourceWalk.done _)
+
+namespace SourceWalk
+
+/-- A source stage together with its entry memory and sequence of native reports. -/
+structure Packet (J : Type*) (w : ℕ) where
+ /-- Source stage executed to produce this packet. -/
+ stage : J
+ /-- Memory supplied to the source stage before its first call. -/
+ input : Memory w
+ /-- Reports returned by the stage in execution order. -/
+ reports : List (Report w)
+
+/-- Memory obtained by replaying the packet's reports on its entry memory. -/
+def Packet.output {w : ℕ} {J : Type*} (p : Packet J w) := after p.input (eventLog p.reports)
+
+/-- Each packet runs its named stage on the preceding packet's output, beginning with the
+supplied memory. -/
+def Chronological {w : ℕ} {J : Type*} (source : J → Memory w → List (Report w) → Prop) :
+ Memory w → List (Packet J w) → Prop
+ | _, [] => True
+ | m, p::ps => p.input = m ∧ source p.stage p.input p.reports ∧ Chronological source p.output ps
+
+theorem packets {w : ℕ} {J : Type*} {source : J → Memory w → List (Report w) → Prop}
+ {js : List J} {m : Memory w} {rs : List (Report w)} (h : SourceWalk source js m rs) :
+ ∃ ps : List (Packet J w), ps.map Packet.stage = js ∧ ps.flatMap Packet.reports = rs ∧ Chronological source m ps := by
+ induction h with
+ | done => exact ⟨[],rfl,rfl,trivial⟩
+ | @next j js m xs ys hx _ ih =>
+ obtain ⟨ps,hjs,hrs,hchron⟩ := ih
+ refine ⟨⟨j,m,xs⟩::ps,?_,?_,rfl,hx,hchron⟩
+ · simp only [List.map_cons,hjs]
+ · simp only [List.flatMap_cons,hrs]
+
+theorem report_count {w : ℕ} {J : Type*} {source : J → Memory w → List (Report w) → Prop}
+ {js : List J} {m : Memory w} {rs : List (Report w)} (h : SourceWalk source js m rs) (count : J → ℕ)
+ (hc : ∀ j m rs, source j m rs → rs.length = count j) : rs.length = (js.map count).sum := by
+ induction h with
+ | done => rfl
+ | next h _ ih => rw [List.length_append,List.map_cons,List.sum_cons,hc _ _ _ h,ih]
+
+end SourceWalk
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceWalkJoin.lean b/lean/OAI/Computability/VPVNP/CompressorSourceWalkJoin.lean
new file mode 100644
index 0000000000..1b41fbe215
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceWalkJoin.lean
@@ -0,0 +1,53 @@
+import OAI.Computability.VPVNP.CompressorSourceWalk
+import OAI.Computability.VPVNP.CompressorRefreshStageFrame
+
+/-!
+# Combining a native source walk with its per-stage certificates
+
+When both walks contain a prescribed number of reports for each stage, their
+boundaries coincide. Thus both properties hold at the same input memories.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open BurstRAM
+
+theorem StageFrame.Scanned.calls {w first stop : ℕ} {rs : List (Report w)}
+ (h : StageFrame.Scanned first stop rs) : rs.length + first = stop := by
+ induction h with
+ | done => simp
+ | next _ _ _ ih => rw [List.length_cons]; omega
+
+namespace SourceWalk
+
+variable {w : ℕ} {J : Type*} {src extra : J → Memory w → List (Report w) → Prop}
+
+private theorem split_cons {i : J} {is : List J} {m : Memory w} {rs : List (Report w)}
+ (walk : SourceWalk src (i::is) m rs) :
+ ∃ xs ys, src i m xs ∧ SourceWalk src is (after m (eventLog xs)) ys ∧ rs = xs++ys := by
+ cases walk with
+ | next head tail => exact ⟨_,_,head,tail,rfl⟩
+
+theorem and_of_counts (count : J → ℕ)
+ (sourceCount : ∀ j m rs, src j m rs → rs.length = count j)
+ (extraCount : ∀ j m rs, extra j m rs → rs.length = count j)
+ {is : List J} {m : Memory w} {rs : List (Report w)}
+ (source : SourceWalk src is m rs) (other : SourceWalk extra is m rs) :
+ SourceWalk (fun j m rs ↦ src j m rs ∧ extra j m rs) is m rs := by
+ induction source with
+ | done => exact .done _
+ | @next i is m xs ys h tail ih =>
+ obtain ⟨xs',ys',h',rest,eqn⟩ := split_cons other
+ obtain ⟨rfl,rfl⟩ := List.append_inj eqn ((sourceCount i m xs h).trans (extraCount i m xs' h').symm)
+ exact .next ⟨h,h'⟩ (ih rest)
+
+end SourceWalk
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSourceZip.lean b/lean/OAI/Computability/VPVNP/CompressorSourceZip.lean
new file mode 100644
index 0000000000..eae8850829
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSourceZip.lean
@@ -0,0 +1,67 @@
+import OAI.Computability.VPVNP.CompressorSourceWalk
+import OAI.Computability.VPVNP.CompressorRefreshStageFrame
+
+/-!
+# Joining chronological source evidence
+
+Fixed stage lengths identify the same report boundaries in two walks. This lets
+a physical source execution carry independently verified cursor and memory facts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+open BurstRAM
+open scoped Fin.CommRing
+
+/-- Two proofs about the same chronological sequence can be joined once their
+per-stage report counts agree. Empty stages and nonzero entry cursors are allowed. -/
+theorem SourceWalk.zip {w : ℕ} {J : Type*} {p q : J → Memory w → List (Report w) → Prop}
+ {js : List J} {m : Memory w} {rs ts : List (Report w)} (one : SourceWalk p js m rs)
+ (two : SourceWalk q js m ts) (same : rs=ts)
+ (lengths : ∀ j m xs ys, p j m xs → q j m ys → xs.length = ys.length) :
+ SourceWalk (fun j m xs ↦ p j m xs ∧ q j m xs) js m rs := by
+ induction one generalizing ts with
+ | done => exact .done _
+ | next head _ ih =>
+ cases two with
+ | next other tail =>
+ obtain ⟨rfl,rfl⟩ := List.append_inj same (lengths _ _ _ _ head other)
+ exact .next ⟨head,other⟩ (ih tail rfl)
+
+theorem StageFrame.Scanned.length {w j N : ℕ} {rs : List (Report w)} (s : Scanned j N rs) :
+ rs.length = N-j := by
+ induction s with
+ | done => simp
+ | next live _ _ ih => rw [List.length_cons,ih]; omega
+
+/-- Successful calls in an arbitrary tape advance the concrete ordinal by one. -/
+theorem StageFrame.scanned_tapes {w : ℕ} {Q : Type*} (P : BurstRAM.Program w Q) (fuel N : ℕ)
+ (inc : ∀ j < N, ∀ mem bs rep, execute P fuel (P.start (j : Word w)) mem bs = some rep →
+ rep.result = some ((j+1 : ℕ) : Word w)) (j : ℕ) (m : Memory w) (bs : List (List Bool))
+ (rs : List (Report w)) (size : j+bs.length = N)
+ (run : runSegment P fuel (some (j : Word w)) m bs = some rs) : Scanned j N rs := by
+ induction bs generalizing j m rs with
+ | nil =>
+ have e : j=N := by simpa using size
+ change some []=some rs at run
+ cases Option.some.inj run
+ exact e ▸ .done _
+ | cons b bs ih =>
+ have live : j simp [runSegment,h] at run
+ | some rep =>
+ have ret := inc j live m b rep h
+ rw [runSegment,h] at run
+ simp only [ret,Option.map_eq_some_iff] at run
+ obtain ⟨tail,ht,rfl⟩ := run
+ exact .next live ret (ih (j+1) _ _ (by simp only [List.length_cons] at size; omega) ht)
+
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingArithmetic.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingArithmetic.lean
new file mode 100644
index 0000000000..ccd9de76d6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingArithmetic.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.CompressorSurvivingNative
+import OAI.Computability.VPVNP.CompressorSurvivingCells
+
+/-!
+# Integer readback of the surviving subdivision instruction table
+
+The native masks are division by the same word, yielding zero or one.
+They compute both minima needed by a balanced subdivision, even when
+the selected supply width is zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+open BurstRAM BurstRAM.PrivateRAM SliceSchedule
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private abbrev wd (a : ℕ) : Word w := (a : Word w)
+
+private theorem div_cast {x y : ℕ} (hx : x < 2^w) (hy : y < 2^w) :
+ BinaryOp.div.eval (wd (w := w) x) (wd y) = wd (x/y) := by
+ simp only [BinaryOp.eval,wd,Fin.val_natCast,Nat.mod_eq_of_lt hx,Nat.mod_eq_of_lt hy]; rfl
+
+private theorem remainder_cast {x y : ℕ} (hx : x < 2^w) (hy : y < 2^w) :
+ BinaryOp.mod.eval (wd (w := w) x) (wd y) = wd (x%y) := by
+ simp only [BinaryOp.eval,wd,Fin.val_natCast,Nat.mod_eq_of_lt hx,Nat.mod_eq_of_lt hy]; rfl
+
+private theorem flag_cast {x : ℕ} (hx : x < 2^w) :
+ BinaryOp.div.eval (wd (w := w) x) (wd x) = if x=0 then 0 else 1 := by
+ rw [div_cast hx hx]
+ split_ifs with h
+ · subst x; rfl
+ · rw [Nat.div_self (Nat.pos_of_ne_zero h)]; rfl
+
+private theorem piece_pos {b q j : ℕ} (hj : j < q) :
+ 0 < b/q+(if j < b%q then 1 else 0) ↔ j < min b q := by
+ by_cases small : b < q
+ · simp only [Nat.div_eq_of_lt small,Nat.mod_eq_of_lt small,min_eq_left small.le,Nat.zero_add]
+ split_ifs <;> omega
+ · have h := Nat.div_pos (Nat.le_of_not_gt small) (Nat.zero_lt_of_lt hj)
+ rw [min_eq_right (Nat.le_of_not_gt small)]; omega
+
+theorem values_exact (r : Row w) (b j : ℕ) (hb : b < 2^w) (hj : j < r.count.val) :
+ let d := Data.mk (wd j) r.count (wd b) r.total r.dst
+ ∀ f, d.values f = wd (SurvivingCells.value b r.count.val j f) := by
+ dsimp only
+ let q := r.count.val
+ let a := b/q
+ let rem := b%q
+ let u := if j < rem then 1 else 0
+ let k := if b < q then 0 else 1
+ let d := Data.mk (wd j) r.count (wd b) r.total r.dst
+ have qfit : q < 2^w := r.count.isLt
+ have qpos : 0 < q := Nat.zero_lt_of_lt hj
+ have eqQ : r.count = wd q := (Fin.natCast_eq_mk ..).symm
+ have small : rem < 2^w := (Nat.mod_lt b qpos).trans qfit
+ have fitA : a < 2^w := (Nat.div_le_self ..).trans_lt hb
+ have d₁ : BinaryOp.div.eval (wd b) r.count = wd a := eqQ ▸ div_cast hb qfit
+ have d₂ : BinaryOp.mod.eval (wd b) r.count = wd rem := eqQ ▸ remainder_cast hb qfit
+ have add : wd (w := w) j + 1 = wd (j+1) := by simp [wd]
+ have quot : BinaryOp.div.eval (wd rem) (wd (w := w) j+1) = wd (rem/(j+1)) := by
+ rw [add]; exact div_cast small (Nat.succ_le_of_lt hj |>.trans_lt qfit)
+ have mask : BinaryOp.div.eval (wd (w := w) (rem/(j+1))) (wd (rem/(j+1))) = wd u := by
+ rw [flag_cast ((Nat.div_le_self ..).trans_lt small)]
+ by_cases h : j < rem
+ · have hpos := Nat.div_pos (Nat.succ_le_of_lt h) (Nat.succ_pos j)
+ simp [u,h,hpos.ne',wd]
+ · have hz := Nat.div_eq_of_lt (show rem < j+1 by omega)
+ simp [u,h,hz,wd]
+ have maskA : BinaryOp.div.eval (wd (w := w) a) (wd a) = wd k := by
+ rw [flag_cast fitA]
+ by_cases h : b < q
+ · simp [a,k,h,Nat.div_eq_of_lt h,wd]
+ · have hp := Nat.div_pos (Nat.le_of_not_gt h) qpos
+ simp [a,k,h,hp.ne',wd]
+ have piece : d.piece = wd (a+u) := by
+ change BinaryOp.div.eval (wd b) r.count +
+ BinaryOp.div.eval (BinaryOp.div.eval (BinaryOp.mod.eval (wd b) r.count) (wd j+1))
+ (BinaryOp.div.eval (BinaryOp.mod.eval (wd b) r.count) (wd j+1)) = _
+ rw [d₁,d₂,quot,mask]; simp only [wd,Nat.cast_add]
+ have offset : d.offset = wd (j*a + min j rem) := by
+ change wd j * BinaryOp.div.eval (wd b) r.count +
+ (BinaryOp.mod.eval (wd b) r.count+(wd j-BinaryOp.mod.eval (wd b) r.count)*
+ BinaryOp.div.eval (BinaryOp.div.eval (BinaryOp.mod.eval (wd b) r.count) (wd j+1))
+ (BinaryOp.div.eval (BinaryOp.mod.eval (wd b) r.count) (wd j+1))) = _
+ rw [d₁,d₂,quot,mask]
+ by_cases h : j < rem <;> simp [u,h,wd,min_eq_left_of_lt,show ¬ j < rem → rem ≤ j by omega]
+ have live : d.live = wd (min b q) := by
+ change wd b + (r.count-wd b)*BinaryOp.div.eval (BinaryOp.div.eval (wd b) r.count)
+ (BinaryOp.div.eval (wd b) r.count) = _
+ rw [d₁,maskA,eqQ]
+ by_cases h : b < q <;> simp [k,h,wd,min_eq_left_of_lt,show ¬ b < q → q ≤ b by omega]
+ have fitPiece : a+u < 2^w := SurvivingCells.value_fit hb qfit hj (1 : Fin 13)
+ have indicator : BinaryOp.div.eval d.piece d.piece = wd (if j < min b q then 1 else 0) := by
+ rw [piece,flag_cast fitPiece]
+ have pos : 0 < a+u ↔ j < min b q := piece_pos hj
+ by_cases hz : a+u=0
+ · have hn : ¬ j < min b q := fun h => (Nat.ne_of_gt (pos.mpr h)) hz
+ simp [hz,hn,wd]
+ · have hp := pos.mp (Nat.pos_of_ne_zero hz)
+ rw [ite_eq_right hz,ite_eq_left hp]; rfl
+ intro f
+ change d.values f = wd (SurvivingCells.value b q j f)
+ fin_cases f <;> first | exact piece | exact live | exact indicator | exact offset | rfl
+
+theorem addresses_exact (r : Row w) (b j : ℕ) (hbank : r.bank = r.total+1) :
+ let d := Data.mk (wd j) r.count (wd b) r.total r.dst
+ ∀ f, d.addresses f = wd (SurvivingCells.address r j f) := by
+ intro d f
+ have bank : r.total+1 = (r.bank.val : Word w) := hbank.symm.trans (by simp)
+ fin_cases f <;> simp [d,Data.addresses,SurvivingCells.address,frameHead,wd,bank] <;> ring
+
+end CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingCells.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingCells.lean
new file mode 100644
index 0000000000..68f64eae36
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingCells.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.CompressorShrinkSliceSweep
+
+/-!
+# Cells written for each subdivision of a surviving wire
+
+Every piece writes its own width, offset, interval frame and references. The
+source width and source directory header are shared across all pieces. These
+repeated writes agree, even when the source width is zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep.SurvivingCells
+
+open BurstRAM SliceSchedule Compression
+
+variable {w b q j k : ℕ} {r : Row w}
+
+/-- The thirteen write destinations for piece `j` in a surviving row. -/
+def address (r : Row w) (j : ℕ) : Fin 13 → ℕ :=
+ let B := r.bank.val
+ let q := r.count.val
+ let a := frameHead B 1 q
+ ![r.total.val, r.dst.val+j, B, B+1, B+2, B+3+j, B+3+q, B+4+q+j,
+ a+3*j, a+3*j+1, a+3*j+2, a+3*q+j, a+4*q+j]
+
+/-- The balanced width, prefix, and adjacency data written by piece `j`. -/
+def value (b q j : ℕ) : Fin 13 → ℕ :=
+ let width := b/q + (if j < b%q then 1 else 0)
+ let start := j*(b/q) + min j (b%q)
+ ![b, width, b, b, min b q, if j < min b q then 1 else 0, 0, start,
+ start, 0, width, j, j]
+
+theorem value_fit (hb : b < 2^w) (hq : q < 2^w) (hj : j < q) (f : Fin 13) :
+ value b q j f < 2^w := by
+ have hwidth := Finset.single_le_sum (f := splitWidth b q) (fun _ _ ↦ Nat.zero_le _)
+ (Finset.mem_univ (⟨j,hj⟩ : Fin q))
+ rw [sum_splitWidth b q (Nat.zero_lt_of_lt hj)] at hwidth
+ have hpiece : b/q + (if j < b%q then 1 else 0) ≤ b := by
+ by_cases h : j < b%q <;> simpa [splitWidth, h] using hwidth
+ have hstart : j*(b/q) + min j (b%q) ≤ b := by
+ have := Nat.mul_le_mul_right (b/q) hj.le
+ have := Nat.div_add_mod b q
+ omega
+ fin_cases f <;> dsimp [value] <;> first | omega | split <;> omega
+
+theorem address_fit (space : Workspace r.total r.dst r.bank 1 r.count.val)
+ (hj : j < r.count.val) (f : Fin 13) : address r j f < 2^w := by
+ have := r.total.isLt
+ have := space.newFit
+ have := space.fits
+ simp only [stop, frameHead, one_mul] at this
+ fin_cases f <;> dsimp [address, frameHead] <;> omega
+
+theorem inside (hj : j < r.count.val) (f : Fin 13) : ¬ r.Outside (address r j f) := by
+ fin_cases f <;> dsimp [address, Row.Outside, frameHead, stop] <;> omega
+
+set_option maxHeartbeats 2500000 in
+/-- Disjoint header columns and endpoint arrays determine the field number
+uniquely. The three interleaved frame columns differ modulo three. -/
+private theorem same_field (space : Workspace r.total r.dst r.bank 1 r.count.val)
+ (apart : r.total.val < r.dst.val ∨ r.dst.val+r.count.val ≤ r.total.val)
+ (hj : j < r.count.val) (hk : k < r.count.val) {f g : Fin 13}
+ (e : address r j f = address r k g) : f = g := by
+ have ht := space.oldApart
+ have hd := space.newApart
+ simp only [stop, frameHead, one_mul] at ht hd
+ fin_cases f <;> fin_cases g <;> first
+ | rfl
+ | dsimp [address, frameHead] at e
+ omega
+
+theorem address_injective (space : Workspace r.total r.dst r.bank 1 r.count.val)
+ (apart : r.total.val < r.dst.val ∨ r.dst.val+r.count.val ≤ r.total.val)
+ (hj : j < r.count.val) : Function.Injective (address r j) := by
+ intro f g e
+ exact same_field space apart hj hj e
+
+/-- Two writes in the same row can only collide within the same column.
+For a piece-specific column the address then determines the piece, and for a
+shared header column the value depends only on the row. -/
+theorem same_value (space : Workspace r.total r.dst r.bank 1 r.count.val)
+ (apart : r.total.val < r.dst.val ∨ r.dst.val+r.count.val ≤ r.total.val)
+ (hj : j < r.count.val) (hk : k < r.count.val) {f g : Fin 13}
+ (e : address r j f = address r k g) :
+ value b r.count.val j f = value b r.count.val k g := by
+ have he := same_field space apart hj hk e
+ subst g
+ fin_cases f <;> dsimp [address, value] at e ⊢ <;> first
+ | rfl
+ | rw [show j = k by omega]
+
+end CompressorRecords.ShrinkSliceSweep.SurvivingCells
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingEvents.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingEvents.lean
new file mode 100644
index 0000000000..8ec0e53b12
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingEvents.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.CompressorSurvivingNative
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-!
+# External footprint of one surviving subdivision call
+
+The call reads its four input words before issuing the thirteen stores.
+This identifies the physical addresses protected against scheduler writes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+open BurstRAM RowRecipe
+variable {w : ℕ}
+
+private def rd (m : Memory w) (a : Word w) : Event w := .read a (m a.val)
+
+private def inputLog (a : Fin 4 → Word w) (m : Memory w) : List (Event w) :=
+ List.replicate 10 .tick ++ [rd m (a 0),.tick,rd m (a 1)] ++ List.replicate 5 .tick ++
+ [rd m (a 2)] ++ List.replicate 4 .tick ++ [rd m (a 3)] ++ List.replicate 56 .tick
+
+set_option maxRecDepth 8192 in
+private theorem events (p : Public w) (st : Word w) (m : Memory w) :
+ (report p st m).events = inputLog (readAddresses p st m) m ++ ScatterCall.storeLog (stores (read p st m)) := rfl
+
+private def readCell : Event w → Option (Word w)
+ | .read a _ => some a
+ | _ => none
+
+private def writeCell : Event w → Option (Word w)
+ | .write a _ => some a
+ | _ => none
+
+private theorem readInputs (a : Fin 4 → Word w) (m : Memory w) :
+ (inputLog a m).filterMap readCell = List.ofFn a := rfl
+
+private theorem noWrites (a : Fin 4 → Word w) (m : Memory w) :
+ (inputLog a m).filterMap writeCell = [] := rfl
+
+private theorem storeCells (xs : List (Word w × Word w)) :
+ (ScatterCall.storeLog xs).filterMap readCell = [] ∧
+ (ScatterCall.storeLog xs).filterMap writeCell = xs.map Prod.fst := by
+ induction xs with
+ | nil => exact ⟨rfl,rfl⟩
+ | cons x xs ih =>
+ simpa only [ScatterCall.storeLog,List.map_cons,List.filterMap_cons,readCell,writeCell] using
+ And.intro ih.1 (congrArg (x.1 :: ·) ih.2)
+
+theorem footprint (p : Public w) (st : Word w) (m : Memory w) :
+ SourceTransport.Reads (fun x => ∃ f, (readAddresses p st m f).val = x) (report p st m).events ∧
+ SourceTransport.Writes (fun x => ∃ f, ((read p st m).addresses f).val = x) (report p st m).events := by
+ constructor <;> intro a v hv
+ · have h : a ∈ (report p st m).events.filterMap readCell := List.mem_filterMap.mpr ⟨_,hv,rfl⟩
+ rw [events,List.filterMap_append,readInputs,(storeCells _).1,List.append_nil] at h
+ obtain ⟨f,hf⟩ := List.mem_ofFn.mp h
+ exact ⟨f,congrArg Fin.val hf⟩
+ · have h : a ∈ (report p st m).events.filterMap writeCell := List.mem_filterMap.mpr ⟨_,hv,rfl⟩
+ rw [events,List.filterMap_append,noWrites,(storeCells _).2,List.nil_append] at h
+ simp only [stores,List.map_ofFn,List.mem_ofFn,Function.comp_apply] at h
+ obtain ⟨f,hf⟩ := h
+ exact ⟨f,congrArg Fin.val hf⟩
+
+end CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingGeometry.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingGeometry.lean
new file mode 100644
index 0000000000..20d8ea9889
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingGeometry.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.CompressorSurvivingNative
+
+/-!
+# Address decoding for a surviving-subdivision visit
+
+The quotient and remainder of the call's ordinal locate the dense motif and
+its subdivision. The motif's absolute arc identifier addresses the width
+table, while its dense number addresses the interval frame.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+open BurstRAM BurstRAM.PrivateRAM Allocation
+open scoped Fin.CommRing
+
+variable {w n A : ℕ}
+
+/-- The three inputs needed by the surviving-row visits at one level. -/
+structure Inputs (T : Allocation w n A) (abs layout : Word w) (width : Id n → ℕ)
+ (mem : Memory w) : Prop where
+ absolute : ∀ i : Fin n, (mem (abs.val+i.val)).val = (T.absolute i).val
+ side : (mem layout.val).val = T.layout.toNat
+ width : ∀ (i : Fin n) (t : Fin 4),
+ (mem (T.termStart i+1)*T.selectors + mem (T.termStart i+2+(T.layout.toNat*4+t.val))).val = width (i,t)
+
+theorem Inputs.keep {T : Allocation w n A} {abs layout : Word w} {width : Id n → ℕ}
+ {mem out : Memory w} (h : Inputs T abs layout width mem) (fit : T.Fits) (visited : Id n)
+ (habs : ∀ i : Fin n, (T.row visited).Outside (abs.val+i.val))
+ (hlayout : (T.row visited).Outside layout.val)
+ (frame : ∀ x, (T.row visited).Outside x → out x = mem x) : Inputs T abs layout width out := by
+ constructor
+ · intro i
+ rw [frame _ (habs i)]; exact h.absolute i
+ · rw [frame _ hlayout]; exact h.side
+ · intro i t
+ have side : T.layout.toNat ≤ 1 := by cases T.layout <;> decide
+ rw [frame _ (T.termOutside fit visited i _ (by omega)),
+ frame _ (T.termOutside fit visited i _ (by have := t.isLt; omega))]
+ exact h.width i t
+
+/-- The ordinal at the end of a role's rectangular scan fits the state word. -/
+theorem count_fit (T : Allocation w n A) (fit : T.Fits) (t : Fin 4) :
+ n*T.subdiv t < 2^w := by
+ have hs : T.subdiv t ≤ T.stride :=
+ Finset.single_le_sum (fun j _ => Nat.zero_le (T.subdiv j)) (Finset.mem_univ t)
+ have hr : T.stride ≤ T.recordStride := by dsimp [recordStride]; omega
+ have hn : n ≤ n*4 := by omega
+ calc
+ n*T.subdiv t ≤ (n*4)*T.recordStride := Nat.mul_le_mul hn (hs.trans hr)
+ _ ≤ T.last := Nat.le_add_left ..
+ _ < _ := fit.room
+
+variable (T : Allocation w n A) (fit : T.Fits) (abs layout : Word w)
+ (width : Id n → ℕ) (mem : Memory w) (absFit : abs.val+n ≤ 2^w)
+ (inputs : Inputs T abs layout width mem) (i : Fin n) (t : Fin 4) (j : Fin (T.subdiv t))
+
+include fit absFit inputs
+
+private theorem geometry :
+ read (params T t abs layout) (↑(i.val*T.subdiv t+j.val)) mem =
+ ⟨↑j.val,(T.row (i,t)).count,↑(width (i,t)),(T.row (i,t)).total,(T.row (i,t)).dst⟩ ∧
+ (fun f => (readAddresses (params T t abs layout) (↑(i.val*T.subdiv t+j.val)) mem f).val) =
+ ![abs.val+i.val,layout.val,T.termStart i+1,T.termStart i+2+(T.layout.toNat*4+t.val)] := by
+ let q := T.subdiv t
+ let p := params T t abs layout
+ let c : Word w := ↑(i.val*q+j.val)
+ let ix := BinaryOp.div.eval c (p 0)
+ let rank := BinaryOp.mod.eval c (p 0)
+ let term := p 2 + ix * p 3
+ let four : Word w := 2+2
+ have qpos := fit.positive t
+ have fitRows := count_fit T fit t
+ have hbound : i.val*q+j.val < n*q := calc
+ _ < i.val*q+q := Nat.add_lt_add_left j.isLt _
+ _ = (i.val+1)*q := (Nat.succ_mul ..).symm
+ _ ≤ _ := Nat.mul_le_mul_right q i.isLt
+ have cc : c.val = i.val*q+j.val := Nat.mod_eq_of_lt (hbound.trans fitRows)
+ have qc : (p 0).val = q := (T.row_vals fit (i,t)).2.2.2.2
+ have ixv : ix.val = i.val := by
+ change (c.val / (p 0).val) % 2^w = _
+ rw [Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt c.isLt),cc,qc,
+ Nat.mul_comm i.val,Nat.mul_add_div qpos,Nat.div_eq_of_lt j.isLt,Nat.add_zero]
+ have rankv : rank.val = j.val := by
+ change (c.val % (p 0).val) % 2^w = _
+ rw [Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt c.isLt),cc,qc,
+ Nat.mul_add_mod_of_lt j.isLt]
+ have ofVal (x : Word w) {v : ℕ} (hx : x.val = v) : x = ↑v := hx ▸ (Fin.cast_val_eq_self x).symm
+ have ixe := ofVal ix ixv
+ have rke := ofVal rank rankv
+ have fourEq : four = ↑(4 : ℕ) := by norm_num [four]
+ have termEq : term = ↑(T.termStart i) := by
+ change (↑T.termBase : Word w) + ix * ↑T.termStride = _
+ simp only [ixe,termStart,Nat.cast_add,Nat.cast_mul]
+ have absRead : (p 4 + ix).val = abs.val+i.val := by
+ rw [Fin.val_add,ixv,show p 4 = abs from rfl,Nat.mod_eq_of_lt (by have := i.isLt; omega)]
+ have absEq := ofVal _ (inputs.absolute i)
+ have layoutEq := ofVal _ inputs.side
+ have roleEq : mem (p 5).val*four + p 1 = ↑(T.layout.toNat*4+t.val) := by
+ rw [show p 5 = layout from rfl,layoutEq,fourEq]
+ simp only [Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat]
+ rfl
+ have termFit : T.termStart i + 10 ≤ 2^w := by
+ have hle : T.widthBase ≤ T.widthEnd := Nat.le_add_right ..
+ have hle' : T.widthEnd ≤ T.last := Nat.le_add_right ..
+ exact (T.term_stop fit i).trans (hle.trans (hle'.trans fit.room.le))
+ have rep : (term+1).val = T.termStart i+1 := by
+ rw [termEq,← Nat.cast_add_one,Fin.val_natCast,Nat.mod_eq_of_lt (by omega)]
+ have payload : (term+2+(mem (p 5).val*four+p 1)).val = T.termStart i+2+(T.layout.toNat*4+t.val) := by
+ have hs : T.layout.toNat ≤ 1 := by cases T.layout <;> decide
+ have eq : term+2+(mem (p 5).val*four+p 1) = ↑(T.termStart i+2+(T.layout.toNat*4+t.val)) := by
+ simp only [roleEq,termEq,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat]
+ rw [eq,Fin.val_natCast,Nat.mod_eq_of_lt (by have := t.isLt; omega)]
+ have absKey : (T.absoluteKey (i,t)).val = (T.absolute i).val*4+t.val := by
+ change t.val+4*(T.absolute i).val = _; omega
+ have denseKey : (Allocation.denseKey (i,t)).val = i.val*4+t.val := by
+ change t.val+4*i.val = _; omega
+ constructor
+ · change Data.mk rank (p 0) (mem (term+1).val*(p 6) + mem (term+2+(mem (p 5).val*four+p 1)).val)
+ (p 9+(ix*four+p 1)*p 10) (p 7+(mem (p 4+ix).val*four+p 1)*p 8) = _
+ rw [rke,rep,payload,show p 6 = T.selectors from rfl,ofVal _ (inputs.width i t),absRead,absEq,ixe,fourEq]
+ congr 1
+ · change (↑T.widthEnd : Word w) + (↑i.val*↑(4 : ℕ)+↑t.val)*↑T.recordStride = ↑(T.recordStart (i,t))
+ simp only [recordStart,denseKey,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat]
+ · change (↑T.widthBase : Word w) + (↑(T.absolute i).val*↑(4 : ℕ)+↑t.val)*↑T.stride = ↑(T.widthStart (i,t))
+ simp only [widthStart,absKey,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat]
+ · funext f
+ fin_cases f
+ · exact absRead
+ · rfl
+ · exact rep
+ · exact payload
+
+/-- Decoding one native call gives the chosen width and the two physical row
+heads used in the interval representation. -/
+theorem read_geometry :
+ read (params T t abs layout) (↑(i.val*T.subdiv t+j.val)) mem =
+ ⟨↑j.val,(T.row (i,t)).count,↑(width (i,t)),(T.row (i,t)).total,(T.row (i,t)).dst⟩ :=
+ (geometry T fit abs layout width mem absFit inputs i t j).1
+
+/-- The reads use the absolute-directory, layout, repetition and payload
+addresses of the selected dense motif. -/
+theorem read_addresses :
+ (fun f => (readAddresses (params T t abs layout) (↑(i.val*T.subdiv t+j.val)) mem f).val) =
+ ![abs.val+i.val,layout.val,T.termStart i+1,T.termStart i+2+(T.layout.toNat*4+t.val)] :=
+ (geometry T fit abs layout width mem absFit inputs i t j).2
+
+end CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingImage.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingImage.lean
new file mode 100644
index 0000000000..247e570000
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingImage.lean
@@ -0,0 +1,220 @@
+import OAI.Computability.VPVNP.CompressorSurvivingCells
+
+/-!
+# Closed form for the descriptor of a surviving wire
+
+A source field of width `b` meets every target subdivision in the entire
+target. Its live reference list is the initial segment of length `min b q`.
+Each live target has exactly one reference, its own index.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep
+
+open BurstRAM SliceRAM SliceSchedule ShrinkSliceArrays Compression
+
+variable {w : ℕ}
+
+/-- Direct numerical readout of a surviving row with one old field. -/
+structure SurvivingWords (r : Row w) (b : ℕ) (mem : Memory w) : Prop where
+ total : (mem r.total.val).val = b
+ widths : ∀ j : Fin r.count.val, (mem (r.dst.val+j.val)).val = splitWidth b r.count.val j
+ oldStart : (mem (r.bank.val+3+r.count.val)).val = 0
+ newStarts : ∀ j : Fin r.count.val, (mem (r.bank.val+4+r.count.val+j.val)).val =
+ j.val*(b/r.count.val) + min j.val (b%r.count.val)
+ frames : ∀ j : Fin r.count.val,
+ let a := frameHead r.bank.val 1 r.count.val + 3*j.val
+ (mem a).val = j.val*(b/r.count.val) + min j.val (b%r.count.val) ∧
+ (mem (a+1)).val = 0 ∧ (mem (a+2)).val = splitWidth b r.count.val j
+ oldCount : (mem (r.bank.val+2)).val = min b r.count.val
+ newCounts : ∀ j : Fin r.count.val, (mem (r.bank.val+3+j.val)).val =
+ if j.val < min b r.count.val then 1 else 0
+ oldRefs : ∀ j : Fin r.count.val,
+ (mem (frameHead r.bank.val 1 r.count.val+3*r.count.val+j.val)).val = j.val
+ newRefs : ∀ j : Fin r.count.val,
+ (mem (frameHead r.bank.val 1 r.count.val+4*r.count.val+j.val)).val = j.val
+
+private theorem start_eq (b q j : ℕ) (hj : j ≤ q) :
+ ((List.ofFn (splitWidth b q)).take j).sum = j*(b/q)+min j (b%q) := by
+ induction j with
+ | zero => simp
+ | succ j ih =>
+ have hlt : j < q := hj
+ have hi : j < (List.ofFn (splitWidth b q)).length := by simpa
+ rw [List.sum_take_succ _ _ hi,ih hlt.le,List.getElem_ofFn,Nat.succ_mul]
+ simp only [splitWidth]
+ split <;> omega
+
+private theorem live_iff (b q : ℕ) (j : Fin q) :
+ splitWidth b q j ≠ 0 ↔ j.val < min b q := by
+ by_cases hb : b < q
+ · simp [splitWidth,Nat.div_eq_of_lt hb,Nat.mod_eq_of_lt hb,Nat.min_eq_left hb.le]
+ · have hpos : 0 < b/q := Nat.div_pos_iff.mpr ⟨Nat.zero_lt_of_lt j.isLt,by omega⟩
+ simp [splitWidth,Nat.min_eq_right (by omega : q ≤ b),j.isLt]
+ split <;> omega
+
+private def frameLength (b q : ℕ) (k : ℕ) :=
+ (sliceAt [b] (List.ofFn (splitWidth b q)) k).length
+
+private theorem frame_live {b q j : ℕ} (hj : j < q) :
+ frameLength b q j ≠ 0 ↔ j < min b q := by
+ rw [frameLength,surviving_sliceAt b q (Nat.zero_lt_of_lt hj) ⟨j,hj⟩]
+ exact live_iff b q ⟨j,hj⟩
+
+private theorem sourcePrefix (b q t : ℕ) (ht : t ≤ q) :
+ adjPrefix w (frameLength b q) (· / q) 0 t =
+ (List.range (min b t)).map (Fin.ofNat (2^w)) := by
+ induction t with
+ | zero => simp [adjPrefix]
+ | succ t ih =>
+ have hlt : t < q := ht
+ have live : frameLength b q t ≠ 0 ∧ t / q = 0 ↔ t < b := by
+ rw [frame_live hlt,Nat.div_eq_of_lt hlt]; omega
+ rw [adjPrefix_succ,ih hlt.le,if_congr live rfl rfl]
+ by_cases hl : t < b
+ · rw [Nat.min_eq_right hl.le,Nat.min_eq_right hl,List.range_succ,List.map_append]
+ simp [hl]
+ · have hb : b ≤ t := by omega
+ simp [hl,Nat.min_eq_left hb,Nat.min_eq_left (Nat.le_succ_of_le hb)]
+
+private theorem targetPrefix (b q v t : ℕ) (ht : t ≤ q) :
+ adjPrefix w (frameLength b q) (· % q) v t =
+ if v < min b t then [Fin.ofNat (2^w) v] else [] := by
+ induction t with
+ | zero => simp [adjPrefix]
+ | succ t ih =>
+ have hlt : t < q := ht
+ rw [adjPrefix_succ,ih hlt.le,Nat.mod_eq_of_lt hlt]
+ by_cases hv : t = v
+ · subst v
+ have next : ¬ t < min b t := by omega
+ simp only [next,ite_false,List.nil_append,frame_live hlt,and_true]
+ apply if_congr _ rfl rfl
+ omega
+ · simp only [hv,and_false,ite_false,List.append_nil]
+ apply if_congr _ rfl rfl
+ omega
+
+/-- The closed-form numerical fields are a complete stored interval schedule,
+including the incidence ordering required by the endpoint readers. -/
+theorem SurvivingWords.image {r : Row w} {b : ℕ} {mem : Memory w} (h : SurvivingWords r b mem)
+ (positive : 0 < r.count.val) (fits : stop r.bank.val 1 r.count.val < 2^w) : Image r b mem := by
+ let q := r.count.val
+ let B := r.bank.val
+ let a := frameHead B 1 q
+ let ws := List.ofFn (splitWidth b q)
+ have nq : ws.length = q := List.length_ofFn
+ have bound : a+5*q < 2^w := by simpa only [stop,one_mul,a,B,q] using fits
+ have ha : a = B+4+2*q := by simp [a,frameHead]
+ have sub (j : ℕ) (hj : j < q) := surviving_sliceAt b q positive ⟨j,hj⟩
+ refine ⟨h.total,h.widths,mem,mem,?_,fun _ _ _ => rfl⟩
+ change Stored r.bank [b] ws mem mem
+ constructor
+ · intro i hi
+ simp only [List.length_singleton] at hi ⊢
+ have hz : i = 0 := by omega
+ subst i
+ simpa [nq] using h.oldStart
+ · intro j hj
+ rw [nq] at hj
+ simpa [nq,start_eq b q j hj.le,ws] using h.newStarts ⟨j,hj⟩
+ · intro j hj
+ simp only [List.length_singleton,nq,one_mul] at hj ⊢
+ rw [sub j hj]
+ exact (h.frames ⟨j,hj⟩).2.2
+ · intro j hj _
+ simp only [List.length_singleton,nq,one_mul] at hj ⊢
+ rw [sub j hj,start_eq b q j hj.le]
+ exact ⟨(h.frames ⟨j,hj⟩).1,(h.frames ⟨j,hj⟩).2.1⟩
+ · simp only [List.length_singleton,nq,one_mul]
+ let bank := oldBank (adjacencyData r.bank 1 q)
+ change bank.Represents mem (frameLength b q) (· / q) q
+ intro v hv
+ have size : bank.size.val = 1 := Nat.mod_eq_of_lt (by omega : 1 < 2^w)
+ have hz : v.val = 0 := by have := Fin.lt_def.mp hv; omega
+ have count : (bank.count v).val = B+2 := by
+ change ((B+2) % 2^w + v.val) % 2^w = _
+ rw [hz,Nat.add_zero,Nat.mod_mod,Nat.mod_eq_of_lt (by omega)]
+ have row : (bank.row v).val = a+3*q := by
+ have hr : bank.refHead.val = a+3*q := by
+ change (a+3*(1*q)) % 2^w = _
+ rw [one_mul,Nat.mod_eq_of_lt (by omega)]
+ simp [AdjBank.row,Fin.val_add,Fin.val_mul,hz,hr,Nat.mod_eq_of_lt (by omega : a+3*q < 2^w)]
+ rw [hz,sourcePrefix b q q le_rfl]
+ constructor
+ · rw [count,List.length_map,List.length_range]
+ exact h.oldCount
+ · intro i
+ have hi : i.val < min b q := by simpa only [List.length_map,List.length_range] using i.isLt
+ rw [row,List.getElem_map,List.getElem_range]
+ apply Fin.ext
+ exact (h.oldRefs ⟨i.val,by omega⟩).trans (Nat.mod_eq_of_lt (by omega)).symm
+ · simp only [List.length_singleton,nq,one_mul]
+ let bank := newBank (adjacencyData r.bank 1 q)
+ change bank.Represents mem (frameLength b q) (· % q) q
+ intro v hv
+ have size : bank.size.val = q := Nat.mod_eq_of_lt (by omega : q < 2^w)
+ have cap : bank.cap.val = 1 := Nat.mod_eq_of_lt (by omega : 1 < 2^w)
+ have hlt : v.val < q := size ▸ Fin.lt_def.mp hv
+ have count : (bank.count v).val = B+3+v.val := by
+ change ((B+2+1) % 2^w + v.val) % 2^w = _
+ rw [Nat.mod_add_mod,Nat.mod_eq_of_lt (by omega)]
+ have row : (bank.row v).val = a+4*q+v.val := by
+ have hr : bank.refHead.val = a+4*q := by
+ change (a+4*(1*q)) % 2^w = _
+ rw [one_mul,Nat.mod_eq_of_lt (by omega)]
+ rw [AdjBank.row,Fin.val_add,Fin.val_mul,cap,hr,Nat.mul_one,Nat.add_mod_mod,Nat.mod_eq_of_lt (by omega)]
+ rw [targetPrefix b q v.val q le_rfl]
+ have hc := h.newCounts ⟨v.val,hlt⟩
+ by_cases hlive : v.val < min b q
+ · rw [ite_eq_left hlive] at hc ⊢
+ constructor
+ · rw [count]; exact hc
+ · intro i
+ have hz : i.val = 0 := by have hi : i.val < 1 := i.isLt; omega
+ simp only [row,hz,Nat.add_zero,List.getElem_cons_zero]
+ apply Fin.ext
+ exact (h.newRefs ⟨v.val,hlt⟩).trans (Nat.mod_eq_of_lt v.isLt).symm
+ · rw [ite_eq_right hlive] at hc ⊢
+ exact ⟨count ▸ hc,fun i => Fin.elim0 i⟩
+ · exact fun _ _ => rfl
+
+namespace SurvivingCells
+
+/-- Reading the thirteen worker cells at every target yields the physical
+interval table. One target suffices to read the source's shared cells. -/
+theorem words_of_fields {r : Row w} {b : ℕ} {mem : Memory w}
+ (h : ∀ j : Fin r.count.val, ∀ f, (mem (address r j.val f)).val = value b r.count.val j.val f)
+ (hq : 0 < r.count.val) : SurvivingWords r b mem := by
+ let first : Fin r.count.val := ⟨0,hq⟩
+ have piece (j : Fin r.count.val) : b/r.count.val + (if j.val < b%r.count.val then 1 else 0) =
+ splitWidth b r.count.val j := by
+ unfold splitWidth
+ split <;> simp [*]
+ constructor
+ · exact h first 0
+ · intro j
+ exact (h j 1).trans (piece j)
+ · exact h first 6
+ · intro j
+ exact h j 7
+ · intro j
+ exact ⟨h j 8,h j 9,(h j 10).trans (piece j)⟩
+ · exact h first 4
+ · intro j
+ exact h j 5
+ · intro j
+ exact h j 11
+ · intro j
+ exact h j 12
+
+end SurvivingCells
+
+end CompressorRecords.ShrinkSliceSweep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingNative.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingNative.lean
new file mode 100644
index 0000000000..5dc2826814
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingNative.lean
@@ -0,0 +1,235 @@
+import OAI.Computability.VPVNP.CompressorScatterCall
+import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner
+import OAI.Computability.VPVNP.CompressorShrinkSliceSweep
+
+/-!
+# A fixed native surviving-slice visit for one subdivision
+
+Each of the four role passes has a constant public bank. Its ordinal gives
+the dense motif number and subdivision index. Four reads obtain the absolute
+arc number, the common layout, the repetition word and the selected payload.
+The call writes the balanced width and both endpoint directories directly.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM RowRecipe PhaseRecipe
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The eleven public operand words shared by the visits for a surviving role. -/
+abbrev Public (w : ℕ) := Fin 11 → Word w
+
+/-- The fixed role and subdivision count accompany the level's array heads. -/
+def params {n A : ℕ} (T : Allocation w n A) (t : Fin 4) (abs layout : Word w) : Public w :=
+ ![T.subdiv t,t.val,T.termBase,T.termStride,abs,layout,T.selectors,T.widthBase,T.stride,T.widthEnd,T.recordStride]
+
+private abbrev div (x y : Word w) := BinaryOp.div.eval x y
+private abbrev mod (x y : Word w) := BinaryOp.mod.eval x y
+private abbrev flag (x : Word w) := div x x
+
+/-- All dynamic fields of a single call, in machine-word arithmetic. -/
+structure Data (w : ℕ) where
+ /-- Zero-based index of the subdivision visited within the motif and role. -/
+ rank : Word w
+ /-- Number of subdivisions into which the role's width is split. -/
+ count : Word w
+ /-- Full role width obtained by adding the selected payload to the repetition contribution. -/
+ width : Word w
+ /-- Address of the total-width cell at the start of the motif and role's interval record. -/
+ total : Word w
+ /-- Base of the output width row for this absolute arc and role. -/
+ dst : Word w
+
+/-- Decode the motif and subdivision from the cursor and read the arc ID, layout, repetition
+count, and payload to form the visit's data. -/
+def read (p : Public w) (st : Word w) (m : Memory w) : Data w :=
+ let i := div st (p 0)
+ let j := mod st (p 0)
+ let four : Word w := 2+2
+ let term := p 2+i*p 3
+ let id := m (p 4+i).val
+ let layout := m (p 5).val
+ let u := m (term+1).val
+ let payload := m (term+2+(layout*four+p 1)).val
+ ⟨j,p 0,u*p 6+payload,p 9+(i*four+p 1)*p 10,p 7+(id*four+p 1)*p 8⟩
+
+/-- Absolute ID, common layout, repetition word and selected payload word,
+in the order in which the instruction table reads them. -/
+def readAddresses (p : Public w) (st : Word w) (m : Memory w) : Fin 4 → Word w :=
+ let i := div st (p 0)
+ let term := p 2+i*p 3
+ ![p 4+i,p 5,term+1,term+2+(m (p 5).val*(2+2)+p 1)]
+
+/-- Width assigned to this subdivision, including one extra unit for the first subdivisions
+that share the remainder. -/
+def Data.piece (d : Data w) := div d.width d.count + flag (div (mod d.width d.count) (d.rank+1))
+
+/-- Starting offset of this subdivision in the balanced split of the role's width. -/
+def Data.offset (d : Data w) :=
+ let rem := mod d.width d.count
+ let pick := flag (div rem (d.rank+1))
+ d.rank * div d.width d.count + (rem + (d.rank-rem)*pick)
+
+/-- Number of positive-width subdivisions in the balanced split. -/
+def Data.live (d : Data w) := d.width + (d.count-d.width)*flag (div d.width d.count)
+
+/-- The thirteen destination cells for the total, piece width, interval metadata, copy frame,
+and endpoint references. -/
+def Data.addresses (d : Data w) : Fin 13 → Word w :=
+ let B := d.total+1
+ let two : Word w := 2
+ let four := two+two
+ let frame := B+four+(d.count+d.count)
+ let pair := frame+3*d.rank
+ ![d.total,d.dst+d.rank,B,B+1,B+two,B+3+d.rank,B+3+d.count,B+four+d.count+d.rank,
+ pair,pair+1,pair+two,frame+3*d.count+d.rank,frame+four*d.count+d.rank]
+
+/-- The thirteen field values to store, ordered to match the visit's destination addresses. -/
+def Data.values (d : Data w) : Fin 13 → Word w :=
+ ![d.width,d.piece,d.width,d.width,d.live,flag d.piece,0,d.offset,d.offset,0,d.piece,d.rank,d.rank]
+
+/-- A list of register assignments for the worker with 64 private registers and eleven public
+operands. -/
+abbrev Lines := List (Assign 64 11)
+
+private def readLines : Lines :=
+ [⟨0,.state⟩,⟨1,.publicWord 0⟩,⟨2,.binary .div 0 1⟩,⟨3,.binary .mod 0 1⟩,
+ ⟨4,.literal 1⟩,⟨5,.literal 2⟩,⟨6,.binary .add 5 5⟩,⟨7,.publicWord 1⟩,
+ ⟨8,.publicWord 4⟩,⟨8,.binary .add 8 2⟩,⟨8,.read 8⟩,
+ ⟨9,.publicWord 5⟩,⟨9,.read 9⟩,
+ ⟨10,.publicWord 3⟩,⟨10,.binary .mul 2 10⟩,⟨11,.publicWord 2⟩,⟨10,.binary .add 11 10⟩,
+ ⟨11,.binary .add 10 4⟩,⟨11,.read 11⟩,
+ ⟨12,.binary .mul 9 6⟩,⟨12,.binary .add 12 7⟩,⟨13,.binary .add 10 5⟩,
+ ⟨13,.binary .add 13 12⟩,⟨13,.read 13⟩,⟨14,.publicWord 6⟩,
+ ⟨14,.binary .mul 11 14⟩,⟨14,.binary .add 14 13⟩,
+ ⟨15,.binary .mul 8 6⟩,⟨15,.binary .add 15 7⟩,⟨16,.publicWord 8⟩,
+ ⟨15,.binary .mul 15 16⟩,⟨16,.publicWord 7⟩,⟨15,.binary .add 16 15⟩,
+ ⟨16,.binary .mul 2 6⟩,⟨16,.binary .add 16 7⟩,⟨17,.publicWord 10⟩,
+ ⟨16,.binary .mul 16 17⟩,⟨17,.publicWord 9⟩,⟨16,.binary .add 17 16⟩]
+
+private def valueLines : Lines :=
+ [⟨17,.binary .div 14 1⟩,⟨18,.binary .mod 14 1⟩,⟨19,.binary .add 3 4⟩,
+ ⟨19,.binary .div 18 19⟩,⟨19,.binary .div 19 19⟩,⟨20,.binary .add 17 19⟩,
+ ⟨21,.binary .sub 3 18⟩,⟨21,.binary .mul 21 19⟩,⟨21,.binary .add 18 21⟩,
+ ⟨22,.binary .mul 3 17⟩,⟨22,.binary .add 22 21⟩,
+ ⟨23,.binary .div 17 17⟩,⟨24,.binary .sub 1 14⟩,⟨24,.binary .mul 24 23⟩,
+ ⟨24,.binary .add 14 24⟩,⟨25,.binary .div 20 20⟩,⟨26,.literal 0⟩,⟨27,.literal 3⟩]
+
+private def addressLines : Lines :=
+ [⟨29,.binary .add 16 4⟩,⟨30,.binary .add 15 3⟩,⟨31,.binary .add 29 4⟩,
+ ⟨32,.binary .add 29 5⟩,⟨33,.binary .add 29 27⟩,⟨34,.binary .add 33 3⟩,
+ ⟨35,.binary .add 33 1⟩,⟨36,.binary .add 29 6⟩,⟨37,.binary .add 36 1⟩,⟨37,.binary .add 37 3⟩,
+ ⟨38,.binary .add 1 1⟩,⟨38,.binary .add 36 38⟩,⟨39,.binary .mul 27 3⟩,
+ ⟨39,.binary .add 38 39⟩,⟨40,.binary .add 39 4⟩,⟨41,.binary .add 39 5⟩,
+ ⟨42,.binary .mul 27 1⟩,⟨42,.binary .add 38 42⟩,⟨42,.binary .add 42 3⟩,
+ ⟨43,.binary .mul 6 1⟩,⟨43,.binary .add 38 43⟩,⟨43,.binary .add 43 3⟩,⟨44,.binary .add 0 4⟩]
+
+/-- Assignments that read the term, compute the balanced piece, and form the addresses of its
+output fields. -/
+def lines : Lines := readLines ++ valueLines ++ addressLines
+
+/-- Registers containing the destination addresses of the thirteen scatter writes. -/
+def destinations : Fin 13 → Fin 64 := ![16,30,29,31,32,34,35,37,39,40,41,42,43]
+/-- Registers containing the values for the thirteen scatter writes. -/
+def sources : Fin 13 → Fin 64 := ![14,20,14,14,24,25,26,22,22,26,20,3,3]
+/-- Ordered address-register and value-register pairs consumed by the scatter worker. -/
+def writes := List.ofFn fun f : Fin 13 => (destinations f,sources f)
+/-- Native instruction sequence that evaluates the assignments and performs all thirteen
+writes. -/
+def ops := ScatterCall.ops lines writes
+/-- Schedulable surviving-piece worker returning the next subdivision cursor from register 44. -/
+def pass : Schedule.Pass := ⟨_,_,_,template ops 44⟩
+/-- Event report and return word for a surviving-piece call at the supplied cursor and memory. -/
+abbrev report (p : Public w) (st : Word w) (m : Memory w) := ScatterCall.report lines writes 44 p st m
+
+set_option maxRecDepth 8192 in
+set_option maxHeartbeats 2200000 in
+theorem registers (p : Public w) (st : Word w) (m : Memory w) :
+ let rs := (evaluate p st m lines (fun _ => 0)).2
+ let d := read p st m
+ (∀ f, rs (destinations f) = d.addresses f ∧ rs (sources f) = d.values f) ∧ rs 44 = st+1 := by
+ constructor
+ · intro f; fin_cases f <;> exact ⟨rfl,rfl⟩
+ · rfl
+
+/-- Ordered address and value pairs describing the surviving-piece call's effect on memory. -/
+def stores (d : Data w) := List.ofFn fun f : Fin 13 => (d.addresses f,d.values f)
+
+set_option maxRecDepth 8192 in
+set_option maxHeartbeats 1200000 in
+theorem native (p : Public w) (st : Word w) (m : Memory w) :
+ let T := (pass.table.instantiate w p).program
+ let rep := report p st m
+ execute T (1+ops.length) (T.start st) m [] = some rep ∧ rep.result = some (st+1) ∧
+ after m rep.events = ScatterCall.applyStores m (stores (read p st m)) ∧
+ rep.probes = 17 ∧ rep.events.length = ops.length ∧ choiceBits rep.events = [] := by
+ obtain ⟨fields,ret⟩ := registers p st m
+ obtain ⟨steps,probes,bits⟩ := ScatterCall.cost lines writes 44 p st m
+ refine ⟨ScatterCall.native lines writes 44 p st m,congrArg some ret,?_,probes.trans (by decide),?_,bits⟩
+ · rw [ScatterCall.effect]
+ unfold stores ScatterCall.stores writes
+ rw [List.map_ofFn]
+ exact congrArg (ScatterCall.applyStores m) (congrArg List.ofFn (funext fun f => Prod.ext (fields f).1 (fields f).2))
+ · exact steps.trans (by simp [ops,ScatterCall.ops])
+
+/-- Planner heads for four passes, with one runtime ordinal per live piece. -/
+structure Heads where
+ /-- Recipe expression for the number of dense motifs scanned at this level. -/
+ motifs : Expr
+ /-- Recipe expression for the base address of the selected motif records. -/
+ terms : Expr
+ /-- Recipe expression for the spacing in words between successive selected motif records. -/
+ termStride : Expr
+ /-- Recipe expression for the base of the table mapping dense motif numbers to absolute arc
+ IDs. -/
+ absolute : Expr
+ /-- Recipe expression for the address of the common layout word used to select payload
+ columns. -/
+ layout : Expr
+ /-- Recipe expression for the selector width contributed by each repetition. -/
+ selectors : Expr
+ /-- Recipe expression for the base of the output width rows indexed by absolute arc and role. -/
+ widthBase : Expr
+ /-- Recipe expression for the start of the interval records indexed by dense motif and role. -/
+ intervalBase : Expr
+
+/-- Schedule one role's surviving-piece pass with one call per motif and subdivision. -/
+def visits (subdiv : Fin 4 → ℕ) (H : Heads) (t : Fin 4) : BlockPlanner.Visit :=
+ let stride := ∑ r, subdiv r
+ ⟨pass,.lit 0,H.motifs.mul (.lit (subdiv t)),
+ ![.lit (subdiv t),.lit t.val,H.terms,H.termStride,H.absolute,H.layout,H.selectors,H.widthBase,
+ .lit stride,H.intervalBase,.lit (5+7*stride)]⟩
+
+/-- List the four surviving-piece visits in role order. -/
+def phases (subdiv : Fin 4 → ℕ) (H : Heads) := List.ofFn (visits subdiv H)
+
+/-- Evaluate the four fixed visits against the allocation's actual heads.
+Only the phase stop depends on the number of dense motifs. -/
+theorem visit_fields {n A : ℕ} (T : Allocation w n A) (H : Heads) (t : Fin 4)
+ (pub : Fin 5 → Word w) (st abs layout : Word w) (m : Memory w)
+ (hm : H.motifs.eval pub st m = (n : Word w)) (ht : H.terms.eval pub st m = (T.termBase : Word w))
+ (hs : H.termStride.eval pub st m = (T.termStride : Word w)) (ha : H.absolute.eval pub st m = abs)
+ (hl : H.layout.eval pub st m = layout) (hsel : H.selectors.eval pub st m = T.selectors)
+ (hw : H.widthBase.eval pub st m = (T.widthBase : Word w))
+ (hb : H.intervalBase.eval pub st m = (T.widthEnd : Word w)) :
+ let v := visits T.subdiv H t
+ v.initial.eval pub st m = 0 ∧ v.stop.eval pub st m = ((n*T.subdiv t : ℕ) : Word w) ∧
+ (fun i => (v.params i).eval pub st m) = params T t abs layout := by
+ refine ⟨rfl,?_,?_⟩
+ · change H.motifs.eval pub st m * (T.subdiv t : Word w) = _
+ rw [hm,Nat.cast_mul]
+ · funext i
+ change Fin 11 at i
+ fin_cases i <;> first | exact ht | exact hs | exact ha | exact hl | exact hsel | exact hw | exact hb | rfl
+
+end CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingPass.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingPass.lean
new file mode 100644
index 0000000000..fd6926627a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingPass.lean
@@ -0,0 +1,339 @@
+import OAI.Computability.VPVNP.CompressorSurvivingImage
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+import OAI.Computability.VPVNP.CompressorRecordsOrdinalFootprint
+
+/-!
+# Native scans of surviving wire subdivisions
+
+Each role has a rectangular pass indexed by the dense motif and the subdivision.
+A call writes the cells of one subdivision, including shared fields of its row.
+Shared cells receive the same value on every write. The terminal memory therefore
+contains every slice of every motif, even for widths smaller than the number of
+subdivisions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep.SurvivingPass
+
+open BurstRAM Allocation
+
+variable {w : ℕ} {C : Type*}
+
+/-- A scan starts at ordinal zero, returns the ordinal after the last call,
+and satisfies the stated per-call bounds and memory access conditions. -/
+structure Segment (P : Program w C) (fuel count : ℕ) (site : Report w → Prop)
+ (initial : Memory w) (rs : List (Report w)) : Prop where
+ executed : runSegment P fuel (some 0) initial (List.replicate count []) = some rs
+ cursor : endState (some 0) rs = some (Fin.ofNat _ count)
+ length : rs.length = count
+ advance : ∀ j (hj : j < rs.length), rs[j].result = some (Fin.ofNat _ (j+1))
+ sites : ∀ r ∈ rs, site r
+
+private theorem fill {N : ℕ} (P : Program w C) (fuel : ℕ) (site : Report w → Prop)
+ (address value : Fin N → Fin 13 → ℕ) (ready : Memory w → Prop)
+ (consistent : ∀ i j f g, address i f = address j g → value i f = value j g)
+ (keep : ∀ i m out, ready m → (∀ x, (∀ f, x ≠ address i f) → out x = m x) → ready out)
+ (one : ∀ (i : Fin N) m, ready m → ∃ es,
+ let r : Report w := ⟨es,some (Fin.ofNat _ (i.val+1))⟩
+ execute P fuel (P.start (Fin.ofNat _ i.val)) m [] = some r ∧ site r ∧
+ (∀ f, (after m es (address i f)).val = value i f) ∧
+ ∀ x, (∀ f, x ≠ address i f) → after m es x = m x)
+ (initial : Memory w) (start : ready initial) (k : ℕ) (hk : k ≤ N) :
+ ∃ rs, Segment P fuel k site initial rs ∧ ready (after initial (eventLog rs)) ∧
+ (∀ (i : Fin N), i.val < k → ∀ f, (after initial (eventLog rs) (address i f)).val = value i f) ∧
+ ∀ x, (∀ (i : Fin N), i.val < k → ∀ f, x ≠ address i f) → after initial (eventLog rs) x = initial x := by
+ classical
+ induction k with
+ | zero => exact ⟨[],⟨rfl,rfl,rfl,by simp,by simp⟩,start,by simp,fun _ _ => rfl⟩
+ | succ k ih =>
+ obtain ⟨rs,run,input,previous,unchanged⟩ := ih (by omega)
+ let i : Fin N := ⟨k,hk⟩
+ let m := after initial (eventLog rs)
+ obtain ⟨es,exec,legal,fields,frame⟩ := one i m input
+ let r : Report w := ⟨es,some (Fin.ofNat _ (k+1))⟩
+ have hm : after initial (eventLog (rs++[r])) = after m es := by
+ simp only [eventLog,List.flatMap_append,List.flatMap_singleton,after,List.foldl_append,m,r]
+ refine ⟨rs++[r],⟨?_,?_,by simp [run.length],?_,?_⟩,hm ▸ keep i m _ input frame,?_,?_⟩
+ · rw [List.replicate_succ',PrimedSchedule.runSegment_append,run.executed]
+ simp only [Option.bind_some,run.cursor,runSegment,Option.map_some]
+ change (match execute P fuel (P.start (Fin.ofNat _ k)) m [] with
+ | none => none | some a => some [a]).map (rs ++ ·) = some (rs ++ [r])
+ rw [exec]; rfl
+ · rw [endState_append]; rfl
+ · intro j hj
+ by_cases h : j < rs.length
+ · rw [List.getElem_append_left h]; exact run.advance j h
+ · rw [List.getElem_append_right (by omega)]
+ have e : j = k := by simp only [List.length_append,List.length_singleton,run.length] at hj; rw [run.length] at h; omega
+ subst j; simp [run.length,r]
+ · intro s hs
+ rcases List.mem_append.mp hs with hs | hs
+ · exact run.sites _ hs
+ · exact (List.mem_singleton.mp hs) ▸ legal
+ · intro j hj f
+ rw [hm]
+ by_cases hit : ∃ g, address j f = address i g
+ · obtain ⟨g,he⟩ := hit
+ rw [he,fields,consistent j i f g he]
+ · have hji : j ≠ i := fun he => hit ⟨f,he ▸ rfl⟩
+ have hlt : j.val < k := by have hv : j.val ≠ k := fun e => hji (Fin.ext e); omega
+ rw [frame _ (fun g he => hit ⟨g,he⟩)]
+ exact previous j hlt f
+ · intro x hx
+ rw [hm,frame x (hx i (Nat.lt_succ_self _))]
+ exact unchanged x (fun j hj => hx j (by omega))
+
+/-- A segment's read and write regions are the union of the regions used by
+its individual calls. -/
+theorem Segment.footprint {P : Program w C} {fuel N site m rs} (h : Segment P fuel N site m rs)
+ {readable writable : ℕ → Prop}
+ (region : ∀ r, site r → SourceTransport.Reads readable r.events ∧ SourceTransport.Writes writable r.events) :
+ SourceTransport.Reads readable (eventLog rs) ∧ SourceTransport.Writes writable (eventLog rs) := by
+ constructor <;> intro a v hv <;> obtain ⟨r,hr,he⟩ := List.mem_flatMap.mp hv
+ · exact (region r (h.sites r hr)).1 a v he
+ · exact (region r (h.sites r hr)).2 a v he
+
+/-- The four role passes can use the ordinary guarded dispatcher. Its bound
+is exclusive, and the final cursor equals that bound. -/
+theorem Segment.validTrace {P : Program w C} {fuel N site m rs} (h : Segment P fuel N site m rs)
+ {d : ℕ} (catalog : Schedule.Catalog d) (worker : Fin d) (ports : Schedule.Ports w)
+ (pub : Fin (catalog worker).params → Word w) (fit : N < 2^w)
+ (keep : ∀ r, site r → ∀ mem, OrdinalRun.Preserved (catalog worker).params ports mem (after mem r.events))
+ (active : Schedule.Ready catalog worker ports pub (Fin.ofNat _ N) m) :
+ Schedule.ValidTrace catalog worker ports pub (Fin.ofNat _ N) 0 m rs ∧
+ OrdinalRun.Preserved (catalog worker).params ports m (after m (eventLog rs)) := by
+ let cursor := Fin.ofNat (2^w)
+ have loop (j : ℕ) (mem : Memory w) (tail : List (Report w)) (len : j+tail.length=N)
+ (sites : ∀ r ∈ tail, site r) (inc : ∀ k (hk : k < tail.length), tail[k].result = some (cursor (j+k+1)))
+ (ready : Schedule.Ready catalog worker ports pub (cursor N) mem) :
+ Schedule.ValidTrace catalog worker ports pub (cursor N) (cursor j) mem tail ∧
+ OrdinalRun.Preserved (catalog worker).params ports mem (after mem (eventLog tail)) := by
+ induction tail generalizing j mem with
+ | nil =>
+ have ej : j = N := by simpa only [List.length_nil,Nat.add_zero] using len
+ exact ⟨⟨ready,ej ▸ le_rfl⟩,fun _ _ => rfl⟩
+ | cons r tail ih =>
+ have hj : j < N := by simp only [List.length_cons] at len; omega
+ have guard : cursor j < cursor N := by
+ change j % 2^w < N % 2^w
+ rwa [Nat.mod_eq_of_lt (hj.trans fit),Nat.mod_eq_of_lt fit]
+ have frame := keep r (sites r List.mem_cons_self) mem
+ have next := OrdinalRun.ready_of_preserved catalog worker ports ready frame
+ obtain ⟨rest,last⟩ := ih (j+1) _ (by simp only [List.length_cons] at len; omega)
+ (fun s hs => sites s (List.mem_cons_of_mem r hs)) (fun k hk => by
+ have succ := inc (k+1) (by simpa using hk)
+ change tail[k].result = some (cursor (j+(k+1)+1)) at succ
+ exact (show j+(k+1)+1 = (j+1)+k+1 by omega) ▸ succ) next
+ have first : r.result = some (cursor (j+1)) := by exact inc 0 (by simp)
+ refine ⟨⟨ready,guard,_,first,rest⟩,fun x hx => ?_⟩
+ change after mem (r.events ++ eventLog tail) x = mem x
+ rw [show after mem (r.events ++ eventLog tail) = after (after mem r.events) (eventLog tail) from List.foldl_append]
+ exact (last x hx).trans (frame x hx)
+ exact loop 0 m rs (by simpa using h.length) h.sites (by simpa only [Nat.zero_add] using h.advance) active
+
+variable {n A : ℕ}
+
+/-- All native calls of one fixed role, and all output rows in their shared
+terminal memory. -/
+structure RoleRun (T : Allocation w n A) (width : Id n → ℕ) (t : Fin 4)
+ (P : Program w C) (fuel : ℕ) (site : Report w → Prop) (initial : Memory w) (rs : List (Report w)) : Prop
+ extends Segment P fuel (n*T.subdiv t) site initial rs where
+ images : ∀ i, Image (T.row (i,t)) (width (i,t)) (after initial (eventLog rs))
+ frame : ∀ x, (∀ i, (T.row (i,t)).Outside x) → after initial (eventLog rs) x = initial x
+
+variable {E : Fin 4 → Type*}
+
+/-- Successive role programs start at zero, with the memory actually produced
+by all earlier programs. Each list in `batches` is one role's native segment. -/
+inductive Roles (T : Allocation w n A) (width : Id n → ℕ) (P : ∀ t, Program w (E t))
+ (fuel : Fin 4 → ℕ) (site : Fin 4 → Report w → Prop) :
+ List (Fin 4) → Memory w → Memory w → List (List (Report w)) → Prop where
+ | nil (m : Memory w) : Roles T width P fuel site [] m m []
+ | cons {t ts m out rs batches} : RoleRun T width t (P t) (fuel t) (site t) m rs →
+ Roles T width P fuel site ts (after m (eventLog rs)) out batches →
+ Roles T width P fuel site (t::ts) m out (rs::batches)
+
+variable {T : Allocation w n A} {width : Id n → ℕ} {P : ∀ t, Program w (E t)}
+variable {fuel : Fin 4 → ℕ} {site : Fin 4 → Report w → Prop} {ts : List (Fin 4)}
+variable {m out : Memory w} {batches : List (List (Report w))}
+
+theorem Roles.replay (h : Roles T width P fuel site ts m out batches) : after m (eventLog batches.flatten) = out := by
+ induction h with
+ | nil => rfl
+ | cons head _ ih =>
+ simp only [List.flatten_cons,eventLog,List.flatMap_append,after,List.foldl_append] at ih ⊢
+ exact ih
+
+theorem Roles.frame (h : Roles T width P fuel site ts m out batches) {x : ℕ}
+ (outside : ∀ t ∈ ts, ∀ i, (T.row (i,t)).Outside x) : out x = m x := by
+ induction h with
+ | nil => rfl
+ | cons head _ ih =>
+ exact (ih fun _ ht => outside _ (List.mem_cons_of_mem _ ht)).trans (head.frame x (outside _ List.mem_cons_self))
+
+theorem Roles.lengths (h : Roles T width P fuel site ts m out batches) :
+ batches.map List.length = ts.map (fun t => n*T.subdiv t) := by
+ induction h with
+ | nil => rfl
+ | cons head _ ih => simp only [List.map_cons,head.length,ih]
+
+/-- Recover an individual native role segment at its actual starting memory.
+The preceding batches are replayed in chronological order. -/
+theorem Roles.get (h : Roles T width P fuel site ts m out batches) (j : ℕ) (hj : j < ts.length) :
+ ∃ rs, batches[j]? = some rs ∧ RoleRun T width ts[j] (P ts[j]) (fuel ts[j]) (site ts[j])
+ (after m (eventLog (batches.take j).flatten)) rs := by
+ induction h generalizing j with
+ | nil => simp at hj
+ | @cons t ts m out rs tail head _ ih =>
+ cases j with
+ | zero => exact ⟨rs,rfl,head⟩
+ | succ j =>
+ have lt : j < ts.length := by simpa using hj
+ obtain ⟨last,hindex,hrun⟩ := ih j lt
+ refine ⟨last,hindex,?_⟩
+ change RoleRun T width ts[j] (P ts[j]) (fuel ts[j]) (site ts[j])
+ (after m (eventLog (rs ++ (tail.take j).flatten))) last
+ simpa only [eventLog,List.flatMap_append,after,List.foldl_append] using hrun
+
+theorem Roles.roleAt (h : Roles T width P fuel site (List.finRange 4) m out batches) (t : Fin 4) :
+ ∃ rs, batches[t.val]? = some rs ∧ RoleRun T width t (P t) (fuel t) (site t)
+ (after m (eventLog (batches.take t.val).flatten)) rs := by
+ have lt : t.val < (List.finRange 4).length := by simp
+ obtain ⟨rs,entry,hrun⟩ := h.get t.val lt
+ have atRole : (List.finRange 4)[t.val] = t := by simp
+ exact ⟨rs,entry,Eq.mp (congrArg (fun i => RoleRun T width i (P i) (fuel i) (site i)
+ (after m (eventLog (batches.take t.val).flatten)) rs) atRole) hrun⟩
+
+theorem Roles.sites (h : Roles T width P fuel site ts m out batches) {r : Report w}
+ (hr : r ∈ batches.flatten) : ∃ t ∈ ts, site t r := by
+ induction h with
+ | nil => simp at hr
+ | @cons t ts m out rs tail head _ ih =>
+ rcases List.mem_append.mp (show r ∈ rs ++ tail.flatten from hr) with hh | ht
+ · exact ⟨t,List.mem_cons_self,head.sites r hh⟩
+ · obtain ⟨v,hv,hsite⟩ := ih ht
+ exact ⟨v,List.mem_cons_of_mem t hv,hsite⟩
+
+theorem Roles.calls (h : Roles T width P fuel site (List.finRange 4) m out batches) :
+ batches.flatten.length = n*T.stride := by
+ rw [List.length_flatten,h.lengths,← List.ofFn_eq_map,List.sum_ofFn,Allocation.stride,Finset.mul_sum]
+
+/-- The four role stages leave the complete endpoint tables of every motif
+simultaneously readable. Their per-role traces have exactly `n * subdiv t` calls. -/
+theorem four (fit : T.Fits) (ready : Memory w → Prop)
+ (worker : ∀ t mem, ready mem → ∃ rs, RoleRun T width t (P t) (fuel t) (site t) mem rs ∧
+ ready (after mem (eventLog rs))) (initial : Memory w) (input : ready initial) :
+ ∃ out batches, Roles T width P fuel site (List.finRange 4) initial out batches ∧
+ ready out ∧ (∀ i, Image (T.row i) (width i) out) ∧
+ (∀ x, (∀ i, (T.row i).Outside x) → out x = initial x) ∧
+ batches.map List.length = List.ofFn (fun t => n*T.subdiv t) := by
+ have scan (ts : List (Fin 4)) (nd : ts.Nodup) (m : Memory w) (hm : ready m) :
+ ∃ out batches, Roles T width P fuel site ts m out batches ∧ ready out ∧
+ ∀ t ∈ ts, ∀ i, Image (T.row (i,t)) (width (i,t)) out := by
+ induction ts generalizing m with
+ | nil => exact ⟨m,[],.nil m,hm,by simp⟩
+ | cons t ts ih =>
+ obtain ⟨rs,head,next⟩ := worker t m hm
+ obtain ⟨missing,unique⟩ := List.nodup_cons.mp nd
+ obtain ⟨out,tail,run,last,rows⟩ := ih unique _ next
+ refine ⟨out,rs::tail,.cons head run,last,fun s hs i => ?_⟩
+ rcases List.mem_cons.mp hs with rfl | hs
+ · apply (head.images i).keep
+ intro x hx
+ apply run.frame
+ intro v hv j
+ apply T.separate fit (i := (i,s)) (j := (j,v)) _ x hx
+ intro eqn
+ have eqRole : s = v := congrArg Prod.snd eqn
+ exact missing (eqRole.symm ▸ hv)
+ · exact rows s hs i
+ obtain ⟨out,bs,done,hr,rows⟩ := scan (List.finRange 4) (List.nodup_finRange _) initial input
+ exact ⟨out,bs,done,hr,fun i => rows i.2 (List.mem_finRange i.2) i.1,
+ fun x hx => done.frame (fun t _ i => hx (i,t)),by simpa only [List.ofFn_eq_map] using done.lengths⟩
+
+/-- Local specification of the native program at a dense motif and subdivision.
+The single ordinal is computed from these two indices without external advice. -/
+def One (T : Allocation w n A) (width : Id n → ℕ) (ready : Memory w → Prop) (t : Fin 4)
+ (P : Program w C) (fuel : ℕ) (site : Report w → Prop) : Prop :=
+ ∀ (i : Fin n) (j : Fin (T.subdiv t)) (m : Memory w), ready m → ∃ es,
+ let k := i.val*T.subdiv t+j.val
+ let r : Report w := ⟨es,some (Fin.ofNat _ (k+1))⟩
+ execute P fuel (P.start (Fin.ofNat _ k)) m [] = some r ∧ site r ∧
+ (∀ f, (after m es (SurvivingCells.address (T.row (i,t)) j.val f)).val =
+ SurvivingCells.value (width (i,t)) (T.subdiv t) j.val f) ∧
+ ∀ x, (∀ f, x ≠ SurvivingCells.address (T.row (i,t)) j.val f) → after m es x = m x
+
+/-- Run all subdivisions of a single role. Equal-address writes agree, whether
+shared by two subdivisions or made at the last unfilled position. -/
+theorem role {Q : Program w C} {cap : ℕ} {ok : Report w → Prop}
+ (fit : T.Fits) (ready : Memory w → Prop) (t : Fin 4)
+ (keep : ∀ i m out, ready m → (∀ x, (T.row i).Outside x → out x = m x) → ready out)
+ (worker : One T width ready t Q cap ok) (initial : Memory w) (input : ready initial) :
+ ∃ rs, RoleRun T width t Q cap ok initial rs ∧ ready (after initial (eventLog rs)) := by
+ let pieces := T.subdiv t
+ let decode : Fin (n*pieces) ≃ Fin n × Fin pieces := finProdFinEquiv.symm
+ let row (k : Fin (n*pieces)) := ((decode k).1,t)
+ let piece (k : Fin (n*pieces)) := (decode k).2.val
+ let addr k := SurvivingCells.address (T.row (row k)) (piece k)
+ let val k := SurvivingCells.value (width (row k)) pieces (piece k)
+ have count (i : Fin n) : (T.row (i,t)).count.val = pieces := (T.row_vals fit (i,t)).2.2.2.2
+ have bound (k : Fin (n*pieces)) : piece k < (T.row (row k)).count.val := by
+ rw [show (T.row (row k)).count.val = pieces from count _]; exact (decode k).2.isLt
+ have inside (k : Fin (n*pieces)) (f : Fin 13) : ¬ (T.row (row k)).Outside (addr k f) :=
+ SurvivingCells.inside (bound k) f
+ have consistent (i j : Fin (n*pieces)) (f g : Fin 13) (e : addr i f = addr j g) : val i f = val j g := by
+ by_cases same : row i = row j
+ · change SurvivingCells.address (T.row (row i)) (piece i) f = SurvivingCells.address (T.row (row j)) (piece j) g at e
+ change SurvivingCells.value (width (row i)) pieces (piece i) f = SurvivingCells.value (width (row j)) pieces (piece j) g
+ rw [same] at e ⊢
+ rw [← count (decode j).1]
+ exact SurvivingCells.same_value (T.space fit (row j)) (T.apart fit (row j)) (same ▸ bound i) (bound j) e
+ · have outside := T.separate fit same (addr i f) (inside i f)
+ exact False.elim (inside j g (e ▸ outside))
+ have retain (k : Fin (n*pieces)) (m out : Memory w) (hm : ready m)
+ (frame : ∀ x, (∀ f, x ≠ addr k f) → out x = m x) : ready out :=
+ keep (row k) m out hm (fun x hx => frame x (fun f he => inside k f (he ▸ hx)))
+ have calls (k : Fin (n*pieces)) (m : Memory w) (hm : ready m) := worker (decode k).1 (decode k).2 m hm
+ have ordinal (k : Fin (n*pieces)) : (decode k).1.val*T.subdiv t+(decode k).2.val = k.val := by
+ have e := congrArg Fin.val (finProdFinEquiv.apply_symm_apply k)
+ change (decode k).2.val+pieces*(decode k).1.val = k.val at e
+ change (decode k).1.val*pieces+(decode k).2.val = k.val
+ rw [← e]; ac_rfl
+ obtain ⟨rs,run,next,fields,frame⟩ := fill Q cap ok addr val ready consistent retain
+ (fun k m hm => by simpa only [ordinal k] using calls k m hm) initial input (n*pieces) le_rfl
+ refine ⟨rs,⟨run,?_,?_⟩,next⟩
+ · intro i
+ have positive : 0 < (T.row (i,t)).count.val := (count i).symm ▸ fit.positive t
+ apply SurvivingWords.image _ positive (T.space fit (i,t)).fits
+ apply SurvivingCells.words_of_fields _ positive
+ intro j f
+ let part : Fin pieces := ⟨j.val,(count i) ▸ j.isLt⟩
+ let k := decode.symm (i,part)
+ have he : (after initial (eventLog rs) (SurvivingCells.address (T.row (i,t)) j.val f)).val =
+ SurvivingCells.value (width (i,t)) pieces j.val f := by
+ simpa only [addr,val,row,piece,k,Equiv.apply_symm_apply,part] using fields k k.isLt f
+ exact he.trans (congrArg (fun q => SurvivingCells.value (width (i,t)) q j.val f) (count i).symm)
+ · intro x outside
+ exact frame x (fun k _ f he => inside k f (he ▸ outside (decode k).1))
+
+/-- Execute all four rectangular passes in role order. The frames of earlier
+roles and the read-only directory survive, and every resulting interval image
+has the chosen width. -/
+theorem full (fit : T.Fits) (ready : Memory w → Prop)
+ (keep : ∀ i m out, ready m → (∀ x, (T.row i).Outside x → out x = m x) → ready out)
+ (workers : ∀ t, One T width ready t (P t) (fuel t) (site t))
+ (initial : Memory w) (input : ready initial) :
+ ∃ out batches, Roles T width P fuel site (List.finRange 4) initial out batches ∧
+ ready out ∧ (∀ i, Image (T.row i) (width i) out) ∧
+ (∀ x, (∀ i, (T.row i).Outside x) → out x = initial x) ∧
+ batches.map List.length = List.ofFn (fun t => n*T.subdiv t) :=
+ four fit ready (fun t m hm => role fit ready t keep (workers t) m hm) initial input
+
+end CompressorRecords.ShrinkSliceSweep.SurvivingPass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingReadback.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingReadback.lean
new file mode 100644
index 0000000000..8aef5dfd21
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingReadback.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.CompressorShrinkSliceTable
+
+/-!
+# Reading a surviving width from its admitted term
+
+The selected layout chooses one of two groups of four payload cells. The width
+of its role is that cell plus one selector field per repetition, computed from
+the repetition header of the same dense motif row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep
+
+open BurstRAM Compression Compression.PackingData ShrinkSliceArrays
+open MotifBlocks MotifGrid MotifConversion ShrinkMotif
+
+variable {w d c n N J nL : ℕ} {V H Tag L : Type}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (P : PackingData V H Tag L d c) (cd : P.BundleNumbering) (site : Site V Tag L ≃ Fin n)
+local notation "M" => (n*d)*pieceCount d c
+variable (T : Allocation w ((n*d)*pieceCount d c) (Slots.oldBaseArcCount N J d c*nL))
+variable {K : Type*} [_root_.Field K] {factor : ℝ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (old : Arc V H Tag L d c → ℕ) (choice : ∀ m : P.Motif, P.ShrinkChoice cd old F m)
+
+/-- Reading the repetition and payload as naturals gives the selected role's
+width, including all selector bits. -/
+theorem selected_width_readback (fit : T.Fits) (selectors : T.selectors.val = F.selectorBits)
+ {mem : Memory w} (terms : Terms P cd site T F old choice mem) (i : Fin M) (t : Fin 4) :
+ (mem (T.termStart i+1)).val*T.selectors.val +
+ (mem (T.termStart i+2+T.layout.toNat*4+t.val)).val = selected P cd site T F old choice (i,t) := by
+ let motif := (ShrinkMotifOrder.number P cd site).symm i
+ let j := supplyRoles.symm (T.layout,t)
+ obtain ⟨_,rep,payload⟩ := terms i
+ have base : (Fin.ofNat (2^w) (T.termStart i)).val = T.termStart i := (T.row_vals fit (i,t)).1
+ have hj := payload j
+ rw [base] at rep hj
+ rw [supplyRoles_index, ← Nat.add_assoc] at hj
+ change (mem (T.termStart i+2+T.layout.toNat*4+t.val)).val =
+ (choice motif).val (supplyRoles (supplyRoles.symm (T.layout,t))) at hj
+ rw [Equiv.apply_symm_apply] at hj
+ rw [rep,selectors,hj,Nat.add_comm]
+ rfl
+
+/-- The machine's word multiply and add agree with the exact selected width
+whenever that output fits in a word. -/
+theorem selected_width_word (fit : T.Fits) (selectors : T.selectors.val = F.selectorBits)
+ {mem : Memory w} (terms : Terms P cd site T F old choice mem) (i : Fin M) (t : Fin 4)
+ (bound : selected P cd site T F old choice (i,t) < 2^w) :
+ (mem (T.termStart i+1)*T.selectors + mem (T.termStart i+2+T.layout.toNat*4+t.val)).val =
+ selected P cd site T F old choice (i,t) := by
+ rw [Fin.val_add,Fin.val_mul,Nat.mod_add_mod,
+ selected_width_readback P cd site T F old choice fit selectors terms i t,Nat.mod_eq_of_lt bound]
+
+end CompressorRecords.ShrinkSliceSweep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingSweep.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingSweep.lean
new file mode 100644
index 0000000000..c100bceb30
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingSweep.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.CompressorSurvivingPass
+import OAI.Computability.VPVNP.CompressorSurvivingVisit
+import OAI.Computability.VPVNP.CompressorSurvivingReadback
+
+/-!
+# Chosen surviving intervals in one native shrinking step
+
+The role programs read the same dense motif table but publish split widths
+by absolute source arc. Their outputs also provide both endpoint directories
+for every surviving role. The native reports retain the physical input and
+output addresses for use by the online dispatcher.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep.SurvivingSweep
+
+open BurstRAM Compression Compression.PackingData Allocation SurvivingNative
+open ShrinkSliceArrays SliceSchedule MotifBlocks MotifGrid MotifConversion MotifDemandPadding ShrinkMotif
+
+variable {w : ℕ}
+
+/-- One stage of the native sweep satisfies the guarded calendar and can
+be replayed across scheduler writes outside its input region. -/
+theorem guarded {n A d : ℕ} {T : Allocation w n A} (fit : T.Fits) {width : Id n → ℕ} {t : Fin 4}
+ {abs layout : Word w} {cap : ℕ} {initial : Memory w} {rs : List (Report w)}
+ (run : SurvivingPass.RoleRun T width t (program T t abs layout) cap (SurvivingNative.Site T t abs layout) initial rs)
+ (catalog : Schedule.Catalog d) (worker : Fin d) (ports : Schedule.Ports w) (pub : Fin (catalog worker).params → Word w)
+ (apart : ∀ x, OrdinalRun.ControlCell (catalog worker).params ports x → ¬ writeRegion T t x)
+ (active : Schedule.Ready catalog worker ports pub (Fin.ofNat _ (n*T.subdiv t)) initial) :
+ Schedule.ValidTrace catalog worker ports pub (Fin.ofNat _ (n*T.subdiv t)) 0 initial rs ∧
+ OrdinalRun.Preserved (catalog worker).params ports initial (after initial (eventLog rs)) ∧
+ SourceTransport.Reads (readRegion T abs layout) (eventLog rs) ∧
+ SourceTransport.Writes (writeRegion T t) (eventLog rs) := by
+ obtain ⟨valid,frame⟩ := run.toSegment.validTrace catalog worker ports pub (count_fit T fit t)
+ (fun r h m x hx => SourceTransport.after_outside m h.writes (apart x hx)) active
+ exact ⟨valid,frame,run.toSegment.footprint (fun r h => ⟨h.reads,h.writes⟩)⟩
+
+private theorem cost {rs : List (Report w)} (all : ∀ r ∈ rs, r.probes = 17) :
+ RAMBuckets.cost Report.probes rs = 18*rs.length := by
+ induction rs with
+ | nil => rfl
+ | cons r rs ih =>
+ rw [RAMBuckets.cost,all r List.mem_cons_self,ih (fun s hs => all s (List.mem_cons_of_mem r hs)),
+ List.length_cons,Nat.mul_succ]; omega
+
+variable {d c n N J nL : ℕ} {V H Tag L : Type}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (cd : P.BundleNumbering) (site : Compression.Site V Tag L ≃ Fin n)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+
+local notation "M" => (n*d)*pieceCount d c
+local notation "A" => Slots.oldBaseArcCount N J d c * nL
+local notation "order" => ShrinkMotifOrder.number P cd site
+local notation "arc" => Slots.oldArcIndex P vertices tags lanes
+
+variable (T : Allocation w ((n*d)*pieceCount d c) (Slots.oldBaseArcCount N J d c * nL))
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable {K : Type*} [_root_.Field K] {factor : ℝ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (old : Arc V H Tag L d c → ℕ) (choice : ∀ m : P.Motif, P.ShrinkChoice cd old F m)
+local notation "chosen" => selected P cd site T F old choice
+
+/-- Decode the next incidence pass's absolute-arc width addresses in the
+same memory as the dense interval records. -/
+theorem sparse_widths (habs : T.absolute = absolute P cd site vertices tags lanes) (fit : T.Fits)
+ (out : Memory w) (images : ∀ i, Image (T.row i) (chosen i) out)
+ (m : P.Motif) (t : Fin 4) (j : Fin (T.subdiv t)) :
+ (out (T.widthBase+((arc m.val).val*4+t.val)*T.stride+j.val)).val =
+ splitWidth (P.termWidths F cd old choice m T.layout t) (T.subdiv t) j := by
+ let i : Id M := (order m,t)
+ obtain ⟨_,_,_,hd,hc⟩ := T.row_vals fit i
+ have key : (T.absoluteKey i).val = (T.absolute i.1).val*4+i.2.val := by
+ change i.2.val+4*(T.absolute i.1).val = _; omega
+ have hpos : j.val < (T.row i).count.val := lt_of_lt_of_eq j.isLt hc.symm
+ have read := (images i).widths ⟨j.val,hpos⟩
+ rw [hd,widthStart,key,habs] at read
+ simpa only [i,absolute,Function.Embedding.coeFn_mk,Equiv.symm_apply_apply,selected,splitWidth,hc] using read
+
+/-- Native execution of the four fixed role visits, including the absolute
+width rectangle used by the slot compiler. Every call performs four reads
+and thirteen writes. With its call charge the total cost is exactly eighteen
+times the number of motif subdivisions. -/
+theorem graph (habs : T.absolute = absolute P cd site vertices tags lanes)
+ (fit : T.Fits) (selectors : T.selectors.val = F.selectorBits) (bound : ∀ i, chosen i < 2^w)
+ (abs layout : Word w) (absFit : abs.val+M ≤ 2^w)
+ (absOutside : ∀ i (j : Fin M), (T.row i).Outside (abs.val+j.val))
+ (layoutOutside : ∀ i, (T.row i).Outside layout.val)
+ (cap : ℕ) (fuel : ops.length < cap) (initial : Memory w)
+ (directory : ∀ j, (initial (abs.val+j.val)).val = (T.absolute j).val)
+ (side : (initial layout.val).val = T.layout.toNat) (terms : Terms P cd site T F old choice initial) :
+ ∃ out batches,
+ SurvivingPass.Roles T chosen (fun t => program T t abs layout) (fun _ => cap)
+ (fun t => SurvivingNative.Site T t abs layout) (List.finRange 4) initial out batches ∧
+ Inputs T abs layout chosen out ∧ Terms P cd site T F old choice out ∧
+ (∀ i, Image (T.row i) (chosen i) out) ∧
+ (∀ (m : P.Motif) (t : Fin 4) (j : Fin (T.subdiv t)),
+ (out (T.widthBase+((arc m.val).val*4+t.val)*T.stride+j.val)).val =
+ splitWidth (P.termWidths F cd old choice m T.layout t) (T.subdiv t) j) ∧
+ (∀ x, x < T.widthBase ∨ T.last ≤ x → out x = initial x) ∧
+ batches.map List.length = List.ofFn (fun t => M*T.subdiv t) ∧
+ batches.flatten.length = M*T.stride ∧ RAMBuckets.cost Report.probes batches.flatten = 18*(M*T.stride) := by
+ have inputs : Inputs T abs layout chosen initial := by
+ refine ⟨directory,side,fun i t => ?_⟩
+ simpa only [Nat.add_assoc] using selected_width_word P cd site T F old choice fit selectors terms i t (bound (i,t))
+ let ready (m : Memory w) := Inputs T abs layout chosen m ∧ Terms P cd site T F old choice m
+ have keep (i : Id M) (m out : Memory w) (hm : ready m)
+ (frame : ∀ x, (T.row i).Outside x → out x = m x) : ready out :=
+ ⟨hm.1.keep fit i (absOutside i) (layoutOutside i) frame,
+ keep_terms P cd site T F old choice fit i m out hm.2 frame⟩
+ obtain ⟨out,batches,runs,next,images,frame,lengths⟩ := SurvivingPass.full fit ready keep
+ (fun t i j m hm => one T fit abs layout absFit chosen t cap fuel i j m hm.1) initial ⟨inputs,terms⟩
+ have stable (x : ℕ) (hx : x < T.widthBase ∨ T.last ≤ x) := frame x (fun i => T.rowOutside fit i x hx)
+ have work := cost (rs := batches.flatten) (fun r hr => by
+ obtain ⟨t,_,s⟩ := runs.sites hr
+ exact s.probes)
+ rw [runs.calls] at work
+ exact ⟨out,batches,runs,next.1,next.2,images,
+ sparse_widths P cd site vertices tags lanes T F old choice habs fit out images,
+ stable,lengths,runs.calls,work⟩
+
+end CompressorRecords.ShrinkSliceSweep.SurvivingSweep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorSurvivingVisit.lean b/lean/OAI/Computability/VPVNP/CompressorSurvivingVisit.lean
new file mode 100644
index 0000000000..153eb5ba45
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorSurvivingVisit.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.CompressorSurvivingArithmetic
+import OAI.Computability.VPVNP.CompressorSurvivingGeometry
+import OAI.Computability.VPVNP.CompressorSurvivingEvents
+import OAI.Computability.VPVNP.CompressorSurvivingPass
+import OAI.Computability.VPVNP.LiveHeaderProtectedCore
+
+/-!
+# A physical surviving subdivision call
+
+The same table reads the four physical inputs on every ordinal. Its thirteen
+stores write the width, the interval fields and the two compact references at
+their exact addresses. All other external words retain their previous values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+open BurstRAM Allocation
+open scoped Fin.CommRing
+variable {w n A : ℕ}
+
+/-- Instantiate the surviving-piece table with the selected role and the allocation's actual
+array heads. -/
+abbrev program (T : Allocation w n A) (t : Fin 4) (abs layout : Word w) :=
+ (pass.table.instantiate w (params T t abs layout)).program
+
+/-- Addresses of the common layout word, the absolute-ID table, and the ten fields of each
+motif term. -/
+def readRegion (T : Allocation w n A) (abs layout : Word w) (x : ℕ) : Prop :=
+ x = layout.val ∨ (abs.val ≤ x ∧ x < abs.val+n) ∨ ∃ i : Fin n, T.termStart i ≤ x ∧ x < T.termStart i+10
+
+/-- Union of the writable row regions for this role over the dense motifs. -/
+def writeRegion (T : Allocation w n A) (t : Fin 4) (x : ℕ) := ∃ i : Fin n, ¬(T.row (i,t)).Outside x
+
+/-- Per-call report specification with seventeen probes, fixed instruction count, empty branch
+tape, and read and write regions. -/
+structure Site (T : Allocation w n A) (t : Fin 4) (abs layout : Word w) (r : Report w) : Prop where
+ probes : r.probes = 17
+ length : r.events.length = ops.length
+ bits : choiceBits r.events = []
+ reads : SourceTransport.Reads (readRegion T abs layout) r.events
+ writes : SourceTransport.Writes (writeRegion T t) r.events
+
+theorem one (T : Allocation w n A) (fit : T.Fits) (abs layout : Word w) (absFit : abs.val+n ≤ 2^w)
+ (width : Id n → ℕ) (t : Fin 4) (cap : ℕ) (hc : ops.length < cap) :
+ SurvivingPass.One T width (Inputs T abs layout width) t (program T t abs layout) cap (Site T t abs layout) := by
+ intro i j m input
+ let k := i.val*T.subdiv t + j.val
+ let st : Word w := Fin.ofNat _ k
+ let p := params T t abs layout
+ let out := report p st m
+ let d := read p st m
+ let r := T.row (i,t)
+ let b := width (i,t)
+ let f := SurvivingCells.address r j.val
+ let v := SurvivingCells.value b (T.subdiv t) j.val
+ have ge := read_geometry T fit abs layout width m absFit input i t j
+ change d = ⟨(j.val : Word w),r.count,(b : Word w),r.total,r.dst⟩ at ge
+ obtain ⟨_,htotal,hbank,_,hcount⟩ := T.row_vals fit (i,t)
+ change r.count.val = T.subdiv t at hcount
+ have bank : r.bank = r.total+1 := by
+ change (Fin.ofNat (2^w) (T.recordStart (i,t)+1)) = (Fin.ofNat (2^w) (T.recordStart (i,t))) + 1
+ exact Nat.cast_add_one _
+ have hpos : j.val < r.count.val := by rw [hcount]; exact j.isLt
+ have hb : b < 2^w := by
+ change width (i,t) < 2^w
+ rw [← input.width i t]; exact Fin.isLt _
+ have addr (e : Fin 13) : (d.addresses e).val = f e := by
+ rw [ge,addresses_exact r b j.val bank,Fin.val_natCast]
+ exact Nat.mod_eq_of_lt (SurvivingCells.address_fit (T.space fit (i,t)) hpos e)
+ have val (e : Fin 13) : (d.values e).val = v e := by
+ rw [ge,values_exact r b j.val hb hpos,Fin.val_natCast,hcount]
+ exact Nat.mod_eq_of_lt (SurvivingCells.value_fit hb (hcount ▸ r.count.isLt) j.isLt e)
+ obtain ⟨he,ret,afterCall,probes,len,bits⟩ := native p st m
+ change execute (program T t abs layout) (1+ops.length) ((program T t abs layout).start st) m [] = some out at he
+ have inc : out.result = some (Fin.ofNat (2^w) (k+1)) := ret.trans (congrArg some (Nat.cast_add_one k).symm)
+ have reportEq : out = ⟨out.events,some (Fin.ofNat _ (k+1))⟩ := congrArg (Report.mk out.events) inc
+ refine ⟨out.events,?_,?_,?_,?_⟩
+ · rw [← reportEq]
+ have run := execute_extend he (cap-(1+ops.length))
+ rwa [show 1+ops.length+(cap-(1+ops.length)) = cap by omega] at run
+ · change Site T t abs layout ⟨out.events,some (Fin.ofNat _ (k+1))⟩
+ rw [← reportEq]
+ obtain ⟨hr,hw⟩ := footprint p st m
+ refine ⟨probes,len,bits,fun a z h => ?_,fun a z h => ?_⟩
+ · obtain ⟨e,readEq⟩ := hr a z h
+ have hread := congrFun (read_addresses T fit abs layout width m absFit input i t j) e
+ change (readAddresses p st m e).val = _ at hread
+ rw [← readEq,hread]
+ have side : T.layout.toNat ≤ 1 := by cases T.layout <;> decide
+ have hrole := t.isLt
+ have hi := i.isLt
+ fin_cases e
+ · exact Or.inr (Or.inl ⟨by simp,by simp [hi]⟩)
+ · exact Or.inl rfl
+ · exact Or.inr (Or.inr ⟨i,by simp,by simp⟩)
+ · refine Or.inr (Or.inr ⟨i,?_,?_⟩)
+ · change T.termStart i ≤ T.termStart i+2+(T.layout.toNat*4+t.val); omega
+ · change T.termStart i+2+(T.layout.toNat*4+t.val) < T.termStart i+10; omega
+ · obtain ⟨e,ea⟩ := hw a z h
+ exact ⟨i,ea ▸ addr e ▸ SurvivingCells.inside hpos e⟩
+ · intro e
+ change (after m out.events (f e)).val = _
+ rw [afterCall]
+ let xs := stores d
+ have live : ∃ av ∈ xs, av.1.val = f e :=
+ ⟨(d.addresses e,d.values e),(by unfold xs stores; exact List.mem_ofFn.mpr ⟨e,rfl⟩),addr e⟩
+ have agree (av) (hav : av ∈ xs) (hh : av.1.val = f e) : av.2 = d.values e := by
+ obtain ⟨g,rfl⟩ := List.mem_ofFn.mp hav
+ have eq : f g = f e := (addr g).symm.trans hh
+ exact congrArg d.values (SurvivingCells.address_injective (T.space fit _) (T.apart fit _) hpos eq)
+ change (ScatterCall.applyStores m xs (f e)).val = _
+ rw [ScatterCall.stored xs m live agree]
+ exact val e
+ · intro x hx
+ rw [afterCall]
+ apply ScatterCall.outside
+ intro av hav
+ obtain ⟨e,rfl⟩ := List.mem_ofFn.mp hav
+ exact (addr e ▸ (hx e).symm)
+
+end CompressorRecords.ShrinkSliceSweep.SurvivingNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermRecord.lean b/lean/OAI/Computability/VPVNP/CompressorTermRecord.lean
new file mode 100644
index 0000000000..d845800b70
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermRecord.lean
@@ -0,0 +1,312 @@
+import OAI.Computability.VPVNP.CompressorChoiceGridStage
+import OAI.Computability.VPVNP.CompressorPayloadCall
+
+/-!
+# Constructing a motif term descriptor in external memory
+
+A local demand record supplies the widths. A sequence of fixed native calls
+writes the selected rounded-grid row and repetition count, followed by one
+word per admitted supply coordinate. Every transition carries just the
+previous return word and the post-call memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TermRecord
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open MotifGrid MotifBlocks MotifConversion MotifSelector
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- A returned row number or repetition word is stored in its descriptor cell.
+The second public word is the cursor passed to the next native call. -/
+def saveFlow : Flow 3 2 :=
+ .seq (.line (.stateWord 0)) <|
+ .seq (.line (.publicWord 1 0)) <|
+ .seq (.line (.write 1 0)) (.line (.publicWord 2 1))
+
+/-- Run the native store that saves the incoming value at `target` and returns `next` for the
+following call. -/
+def save (target next value : BurstRAM.Word w) (mem : Memory w) : Option (Report w) :=
+ let prog := (saveFlow.template (some 2)).instantiate w ![target,next]
+ execute prog.program 5 (prog.program.start value) mem []
+
+/-- Exact four-event report of the single-cell save, including the return word for the next
+call. -/
+def saved (target next value : BurstRAM.Word w) : Report w :=
+ ⟨[.tick,.tick,.write target value,.tick],some next⟩
+
+theorem save_native (target next value : BurstRAM.Word w) (mem : Memory w) :
+ save target next value mem = some (saved target next value) ∧
+ after mem (saved target next value).events = writeMemory mem target value := by
+ let pub : Fin 2 → BurstRAM.Word w := ![target,next]
+ let rs : Regs w 3 := fun _ => 0
+ let a := Function.update rs 0 value
+ let b := Function.update a 1 target
+ let out := Function.update b 2 next
+ let mem' := writeMemory mem target value
+ have ha : Flow.Exec pub value (.line (.stateWord 0)) rs mem [.tick] a mem := .line rfl
+ have hb : Flow.Exec pub value (.line (.publicWord 1 0)) a mem [.tick] b mem := .line rfl
+ have hc : Flow.Exec pub value (.line (.write 1 0)) b mem [.write target value] b mem' := by
+ apply Flow.Exec.line
+ simp (config := {decide := true}) [Op.effect,b,a,Function.update,mem']
+ have hd : Flow.Exec pub value (.line (.publicWord 2 1)) b mem' [.tick] out mem' := .line rfl
+ exact ⟨DemandPreparation.execute_return saveFlow pub 2 value mem mem' (saved target next value).events out
+ (.seq ha (.seq hb (.seq hc hd))) rfl 4 le_rfl,rfl⟩
+
+variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+
+/-- Read the actual demands, select and store the grid row, read the same
+demand words for the repetition count, then store it next to the row. -/
+noncomputable def headers {d : ℕ} (order : Fin d ≃ D) (src base : BurstRAM.Word w)
+ (mem : Memory w) (prepFuel : ℕ) : Option (List (Report w)) := do
+ let rows := DemandGridRAM.fixedRows B
+ let grid := DemandGridRAM.machine order p rows w
+ let g ← execute grid.program (6*d+(11*d+4)*B.grid.demands.toList.length+8)
+ (grid.program.start src) mem []
+ let row ← g.result
+ let m₁ := after mem g.events
+ let sr ← save base src row m₁
+ let src' ← sr.result
+ let m₂ := after m₁ sr.events
+ let reps := DemandPreparation.repetitionMachine order p B.scale w
+ let r ← execute reps.program prepFuel (reps.program.start src') m₂ []
+ let u ← r.result
+ let su ← save (base+1) (base+2) u (after m₂ r.events)
+ return [g,sr,r,su]
+
+/-- Generated descriptor headers use adjacent external words. -/
+def withHeaders (mem : Memory w) (base row u : BurstRAM.Word w) : Memory w :=
+ writeMemory (writeMemory mem base row) (base+1) u
+
+private theorem demands_write {d : ℕ} {X : Type*} (order : Fin d ≃ X) (src base row : BurstRAM.Word w)
+ (mem : Memory w) (hsrc : src.val+d ≤ 2^w) (hsep : src.val+d ≤ base.val ∨ base.val < src.val) :
+ DemandPreparation.demandAt order src (writeMemory mem base row) =
+ DemandPreparation.demandAt order src mem := by
+ funext e
+ obtain ⟨i,rfl⟩ := order.surjective e
+ rw [DemandPreparation.demandAt_address _ _ _ hsrc, DemandPreparation.demandAt_address _ _ _ hsrc]
+ have hne : src.val+i.val ≠ base.val := by have := i.isLt; omega
+ simp [writeMemory,hne]
+
+theorem headers_native {d : ℕ} (order : Fin d ≃ D) (hp : ∀ i, 0 < p i) :
+ ∃ K : ℕ, ∀ M w, K+4*Nat.clog 2 (M+1) ≤ w → ∀ (src base : BurstRAM.Word w) (mem : Memory w),
+ src.val+d ≤ 2^w → (src.val+d ≤ base.val ∨ base.val < src.val) →
+ (∀ i, DemandPreparation.demandAt order src mem i ≤ M) →
+ let demand := DemandPreparation.demandAt order src mem
+ let fuel := 6*d + 7*((∑ i, MotifAdmission.weight p i).size + 2*Nat.clog 2 (M+1)) + 10
+ ∃ (row u : BurstRAM.Word w) (gs rs : List (Event w)),
+ B.grid.demands.toList[row.val]? = some (demandGrid B hp demand).val ∧ u.val = repetitions B demand ∧
+ headers B order src base mem fuel =
+ some [⟨gs,some row⟩, saved base src row, ⟨rs,some u⟩, saved (base+1) (base+2) u] ∧
+ after mem gs = mem ∧ after (writeMemory mem base row) rs = writeMemory mem base row ∧
+ choiceBits gs = [] ∧ choiceBits rs = [] ∧ countProbes gs ≤ d+B.grid.demands.toList.length*d ∧
+ countProbes rs = d ∧ gs.length < 6*d+(11*d+4)*B.grid.demands.toList.length+8 ∧ rs.length < fuel := by
+ let table := B.grid.demands.toList
+ let rows := DemandGridRAM.fixedRows B
+ obtain ⟨kg,hg⟩ := DemandGridRAM.native order p rows
+ obtain ⟨kr,hr⟩ := DemandPreparation.repetition_native order p B.scale B.scale_pos
+ obtain ⟨ku,hu⟩ := MotifChoiceRAM.native_word_fit p q B.scale B.scale_pos B.radius
+ let K := max table.length.size (max ku (max kg kr))
+ refine ⟨K,fun M w hW src base mem hsrc hsep hD => ?_⟩
+ have hmax₁ := le_max_left table.length.size (max ku (max kg kr))
+ have hmax₂ := le_max_right table.length.size (max ku (max kg kr))
+ have hmax₃ := le_max_left ku (max kg kr)
+ have hmax₄ := le_max_right ku (max kg kr)
+ have hmax₅ := le_max_left kg kr
+ have hmax₆ := le_max_right kg kr
+ dsimp [K] at hW
+ let b := DemandPreparation.demandAt order src mem
+ let idx := GridRAM.firstRow p b rows
+ let row : BurstRAM.Word w := Fin.ofNat _ idx
+ let u : BurstRAM.Word w := Fin.ofNat _ (repetitions B b)
+ let m₂ := writeMemory mem base row
+ obtain ⟨gs,hgr,hgb,hgp,hgm,hgl⟩ := hg M w (by omega) src mem hD
+ have hi : idx < 2^w := (List.findIdx_le_length (xs := List.ofFn rows) (p := _)).trans_lt
+ (by rw [List.length_ofFn]; exact Nat.size_le.mp (show table.length.size ≤ w by omega))
+ have hz := GridRAM.firstRow_getElem? p b rows
+ rw [show List.ofFn rows = table from DemandGridRAM.fixedRows_list B,selectGrid_eq B hp b] at hz
+ have he : DemandPreparation.demandAt order src m₂ = b := demands_write order src base row mem hsrc hsep
+ obtain ⟨rs,hrr,hrb,hrp,hrm,hrl⟩ := hr M w (by omega) src m₂ (he ▸ hD)
+ have uf := (hu M b hD).1
+ have huv : u.val = repetitions B b := Nat.mod_eq_of_lt
+ (uf.trans_le (Nat.pow_le_pow_right (by decide) (by omega)))
+ refine ⟨row,u,gs,rs,?_,huv,?_,hgm,hrm,hgb,hrb,hgp,hrp,hgl,by omega⟩
+ · rw [show row.val = idx from Nat.mod_eq_of_lt hi]
+ exact hz
+ · dsimp only [rows] at hgr
+ rw [he] at hrr
+ let fuel := 6*d + 7*((∑ i, MotifAdmission.weight p i).size + 2*Nat.clog 2 (M+1)) + 10
+ change execute _ fuel _ m₂ [] = some ⟨rs,some u⟩ at hrr
+ change headers B order src base mem fuel = _
+ unfold headers
+ simp only [hgr, bind, Option.bind_some, hgm]
+ change ((save base src row mem).bind _) = _
+ rw [(save_native base src row mem).1]
+ simp only [Option.bind_some, saved]
+ change ((execute _ fuel _ m₂ []).bind _) = _
+ rw [hrr]
+ simp only [Option.bind_some]
+ change ((save (base+1) (base+2) u (after m₂ rs)).bind _) = _
+ rw [hrm,(save_native (base+1) (base+2) u m₂).1]
+ rfl
+
+
+/-- Execute the five descriptor calls and keep their reports in order. The
+payload call reads its own repetition word from the preceding record cell. -/
+noncomputable def run {d n : ℕ} (order : Fin d ≃ D) (supply : Fin n ≃ S) (src base : BurstRAM.Word w)
+ (mem : Memory w) (prepFuel : ℕ) (bits : List Bool) : Option (List (Report w)) := do
+ let hs ← headers B order src base mem prepFuel
+ let payload ← endState (some src) hs
+ let m := after mem (eventLog hs)
+ let prog := PayloadWrite.storedMachine B supply w
+ let choice ← execute prog.program (PayloadWrite.storedFuel B n w) (prog.program.start payload) m bits
+ return hs ++ [choice]
+
+private def headerReports (src base row u : BurstRAM.Word w) (gs rs : List (Event w)) : List (Report w) :=
+ [⟨gs,some row⟩,saved base src row,⟨rs,some u⟩,saved (base+1) (base+2) u]
+
+private theorem after_append (m : Memory w) (es fs : List (Event w)) :
+ after m (es ++ fs) = after (after m es) fs := List.foldl_append
+
+private theorem headerMemory (src base row u : BurstRAM.Word w) (gs rs : List (Event w))
+ (mem : Memory w) (hg : after mem gs = mem)
+ (hr : after (writeMemory mem base row) rs = writeMemory mem base row) :
+ after mem (eventLog (headerReports src base row u gs rs)) = withHeaders mem base row u := by
+ simp only [headerReports,eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil]
+ rw [after_append, hg, after_append]
+ change after (writeMemory mem base row) (rs ++ _) = _
+ rw [after_append, hr]; rfl
+
+/-- The descriptor memory image contains precisely the two headers and the
+selected integer vector. All other external addresses retain their input. -/
+def recordMemory {n : ℕ} (mem : Memory w) (base row u : BurstRAM.Word w) (supply : Fin n ≃ S)
+ (v : S → ℕ) : Memory w :=
+ PayloadWrite.overlay (withHeaders mem base row u) (base+2).val (List.ofFn fun i => (v (supply i) : BurstRAM.Word w))
+
+
+omit [Fintype S] in
+/-- Read the physical fields of a term record. The layout is the rounded-grid
+index, the repetition count, and then the outer supply coordinates in order. -/
+theorem recordMemory_fields {n : ℕ} (mem : Memory w) (base row u : BurstRAM.Word w)
+ (supply : Fin n ≃ S) (v : S → ℕ) (hfit : base.val + 2 + n < 2^w) :
+ let m := recordMemory mem base row u supply v
+ m base.val = row ∧ m (base.val+1) = u ∧
+ (∀ i, m (base.val+2+i.val) = (v (supply i) : BurstRAM.Word w)) ∧
+ ∀ j, j < base.val ∨ base.val+2+n ≤ j → m j = mem j := by
+ let vec := fun i => (v (supply i) : BurstRAM.Word w)
+ let m := withHeaders mem base row u
+ have htwo : 2 < 2^w := by omega
+ have hone : 1 < 2^w := by omega
+ have one : (base+1).val = base.val+1 := by
+ rw [Fin.val_add, show (1 : BurstRAM.Word w).val = 1 from Nat.mod_eq_of_lt hone, Nat.mod_eq_of_lt (by omega)]
+ have two : (base+2).val = base.val+2 := by
+ rw [Fin.val_add, show (2 : BurstRAM.Word w).val = 2 from Nat.mod_eq_of_lt htwo, Nat.mod_eq_of_lt (by omega)]
+ dsimp only [recordMemory]
+ rw [two]
+ refine ⟨?_,?_,PayloadWrite.overlay_slot m (base.val+2) vec,?_⟩
+ · rw [PayloadWrite.overlay_outside m (base.val+2) vec base.val (Or.inl (by omega))]
+ simp [m,withHeaders,writeMemory,one]
+ · rw [PayloadWrite.overlay_outside m (base.val+2) vec (base.val+1) (Or.inl (by omega))]
+ simp [m,withHeaders,writeMemory,one]
+ · intro j hj
+ rw [PayloadWrite.overlay_outside m (base.val+2) vec j (by omega)]
+ simp [m,withHeaders,writeMemory,one,show j ≠ base.val by omega,show j ≠ base.val+1 by omega]
+
+/-- The stored words read back as the original natural widths in every
+admitted block. This is the integer readout needed by the supply-width pass. -/
+theorem recordMemory_supply {n : ℕ} (mem : Memory w) (base row u : BurstRAM.Word w)
+ (supply : Fin n ≃ S) (hq : ∀ i, 0 < q i) (demand : D → ℕ) (v : ↥(outerIndices B demand))
+ (hw : outerCap B demand < 2^w) (hfit : base.val+2+n < 2^w) (hu : u.val = repetitions B demand) :
+ let m := recordMemory mem base row u supply v.val
+ ∀ i, (m (base.val+2+i.val)).val + (m (base.val+1)).val * B.selectorBits =
+ supplyWidths B demand v.val (supply i) := by
+ dsimp only
+ intro i
+ obtain ⟨_,hrep,hv,_⟩ := recordMemory_fields mem base row u supply v.val hfit
+ rw [hv i,hrep,hu,Fin.val_natCast]
+ apply congrArg (· + repetitions B demand * B.selectorBits)
+ exact Nat.mod_eq_of_lt ((MotifAdmission.payload_le_cap q hq _ _ _ _
+ ((mem_outerIndices_iff B hq _ _).mp v.property) _).trans_lt hw)
+
+/-- The native term phase produces exactly one external-memory descriptor for
+each stream admitted by the motif. The two headers, every payload word, all
+five reports and the probe allowance are accounted for on each admitted path. -/
+theorem run_spec {d n : ℕ} (order : Fin d ≃ D) (supply : Fin n ≃ S)
+ (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
+ ∃ K : ℕ, ∀ M w, K+4*Nat.clog 2 (M+1) ≤ w → ∀ (src base : BurstRAM.Word w) (mem : Memory w),
+ src.val+d ≤ 2^w → base.val+2+n < 2^w →
+ (src.val+d ≤ base.val ∨ base.val+2+n ≤ src.val) →
+ (∀ i, DemandPreparation.demandAt order src mem i ≤ M) →
+ let demand := DemandPreparation.demandAt order src mem
+ let fuel := 6*d + 7*((∑ i, MotifAdmission.weight p i).size + 2*Nat.clog 2 (M+1)) + 10
+ ∃ (hw : outerCap B demand < 2^w) (row u : BurstRAM.Word w),
+ B.grid.demands.toList[row.val]? = some (demandGrid B hp demand).val ∧ u.val = repetitions B demand ∧
+ (∀ bits, (run B order supply src base mem fuel bits).isSome ↔
+ ∃ v, (outerReader B supply hq demand w hw).read bits = some (v, [])) ∧
+ ∀ v, ∃ reports, run B order supply src base mem fuel ((outerReader B supply hq demand w hw).encode v) =
+ some reports ∧ reports.length = 5 ∧ after mem (eventLog reports) = recordMemory mem base row u supply v.val ∧
+ branchPaths reports = [[],[],[],[],(outerReader B supply hq demand w hw).encode v] ∧
+ countProbes (eventLog reports) ≤ d+B.grid.demands.toList.length*d+d+n+3 ∧
+ (eventLog reports).length ≤ 6*d+(11*d+4)*B.grid.demands.toList.length+8 +
+ fuel + 8 + PayloadWrite.storedFuel B n w := by
+ obtain ⟨kh,hh⟩ := headers_native B order hp
+ obtain ⟨kv,hv⟩ := PayloadWrite.stored_outer_paths B supply hq
+ refine ⟨max kh kv,fun M w hW src base mem hsrc hbase hsep hD => ?_⟩
+ have hk₁ := le_max_left kh kv
+ have hk₂ := le_max_right kh kv
+ let demand := DemandPreparation.demandAt order src mem
+ let fuel := 6*d + 7*((∑ i, MotifAdmission.weight p i).size + 2*Nat.clog 2 (M+1)) + 10
+ obtain ⟨row,u,gs,rs,hrow,hu,header,hgm,hrm,hgb,hrb,hgp,hrp,hgl,hrl⟩ :=
+ hh M w (by omega) src base mem hsrc (by omega) hD
+ let hs := headerReports src base row u gs rs
+ let dst := base+2
+ let m := withHeaders mem base row u
+ change headers B order src base mem fuel = some hs at header
+ have hm : after mem (eventLog hs) = m := headerMemory src base row u gs rs mem hgm hrm
+ have hd : dst.val = base.val+2 := by
+ have two : 2 < 2^w := by omega
+ change (base+2).val = _
+ rw [Fin.val_add, show (2 : BurstRAM.Word w).val = 2 from Nat.mod_eq_of_lt two, Nat.mod_eq_of_lt (by omega)]
+ have hsub : dst-1 = base+1 := by dsimp [dst]; ring
+ have hread : (m (dst-1).val).val = repetitions B demand := by simp [hsub,m,withHeaders,writeMemory,hu,demand]
+ obtain ⟨hw,har,paths⟩ := hv M demand hD w (by omega) dst m (by omega) hread
+ let prog := PayloadWrite.storedMachine B supply w
+ let read (bits : List Bool) := execute prog.program (PayloadWrite.storedFuel B n w) (prog.program.start dst) m bits
+ have reduce (bits : List Bool) : run B order supply src base mem fuel bits = (read bits).map (hs ++ [·]) := by
+ simp only [run, header, bind, Option.bind_some, show endState (some src) hs = some dst from rfl, hm, pure]
+ change ((read bits).bind fun r => some (hs ++ [r])) = _
+ cases read bits <;> rfl
+ refine ⟨hw,row,u,hrow,hu,fun bits => ?_,fun v => ?_⟩
+ · change (run B order supply src base mem fuel bits).isSome ↔ _
+ rw [reduce,Option.isSome_map]
+ exact har bits
+ · obtain ⟨es,he,hmem,hp,hes,hb⟩ := paths v
+ change read _ = some ⟨es,none⟩ at he
+ refine ⟨hs ++ [⟨es,none⟩],?_,rfl,?_,?_,?_,?_⟩
+ · change run B order supply src base mem fuel _ = _
+ rw [reduce, he]; rfl
+ · rw [show eventLog (hs ++ [⟨es,none⟩]) = eventLog hs ++ es by simp [eventLog],
+ after_append, hm]
+ exact hmem
+ · simp [hs,headerReports,branchPaths,saved,choiceBits,hgb,hrb,hb,demand]
+ · simp [hs,headerReports,eventLog,DemandPreparation.probes_append,saved,countProbes,hrp,hp]
+ simp only [Finset.length_toList] at hgp
+ omega
+ · change (eventLog (hs ++ [⟨es,none⟩])).length ≤ 6*d+(11*d+4)*B.grid.demands.toList.length+8 + fuel + 8 + _
+ simp [hs,headerReports,eventLog,saved]
+ simp only [Finset.length_toList] at hgl
+ change rs.length < fuel at hrl
+ omega
+
+end CompressorRecords.TermRecord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermRecordScan.lean b/lean/OAI/Computability/VPVNP/CompressorTermRecordScan.lean
new file mode 100644
index 0000000000..8f9b407717
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermRecordScan.lean
@@ -0,0 +1,354 @@
+import OAI.Computability.VPVNP.CompressorTermRecord
+
+/-!
+# Ordered native term-record scans for a compressor pass
+
+Each motif has a contiguous input demand row and a disjoint output descriptor.
+The scan threads the post-call memory into the next motif. Every legal outer
+choice is therefore counted once and all emitted rows are still available to
+the later score and slice scans.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TermRecordScan
+
+open BurstRAM MotifGrid MotifBlocks MotifConversion MotifSelector
+
+variable {m d n w : ℕ}
+
+/-- The rows may have arbitrary identifiers. Demand words are read-only and
+term rows have two headers followed by the supply coordinates. -/
+structure Layout (m d n w : ℕ) where
+ /-- First address of the contiguous input demand widths for each motif. -/
+ source : Fin m → BurstRAM.Word w
+ /-- First address of the disjoint output term descriptor for each motif. -/
+ base : Fin m → BurstRAM.Word w
+ sourceFits : ∀ i, (source i).val + d ≤ 2^w
+ termFits : ∀ i, (base i).val + 2 + n < 2^w
+ separate : ∀ i j, (source j).val + d ≤ (base i).val ∨ (base i).val + 2+n ≤ (source j).val
+ different : ∀ i j, i ≠ j →
+ (base j).val + 2+n ≤ (base i).val ∨ (base i).val + 2+n ≤ (base j).val
+
+/-- The address lies outside the grid index, repetition count, and payload columns of motif
+`i`'s descriptor. -/
+def Layout.Outside (L : Layout m d n w) (i : Fin m) (x : ℕ) : Prop :=
+ x < (L.base i).val ∨ (L.base i).val + 2+n ≤ x
+
+/-- A dense or strided directory of demand rows followed by disjoint
+descriptor rows is a concrete instance of the scan's address layout. -/
+def strided (m d n w src dst srcStride termStride : ℕ)
+ (hd : d ≤ srcStride) (hn : 2+n ≤ termStride)
+ (hsep : src + m*srcStride ≤ dst) (hfit : dst + m*termStride < 2^w) :
+ Layout m d n w := by
+ let source (i : Fin m) : BurstRAM.Word w := Fin.ofNat _ (src+i.val*srcStride)
+ let base (i : Fin m) : BurstRAM.Word w := Fin.ofNat _ (dst+i.val*termStride)
+ have sup (i : Fin m) : src+i.val*srcStride + d ≤ dst := by
+ have h := Nat.mul_le_mul_right srcStride (Nat.succ_le_of_lt i.isLt)
+ rw [Nat.succ_mul] at h
+ omega
+ have endFits (i : Fin m) : dst+i.val*termStride + 2+n < 2^w := by
+ have h := Nat.mul_le_mul_right termStride (Nat.succ_le_of_lt i.isLt)
+ rw [Nat.succ_mul] at h
+ omega
+ have hs (i : Fin m) : (source i).val = src+i.val*srcStride :=
+ Nat.mod_eq_of_lt (by have := sup i; omega)
+ have hb (i : Fin m) : (base i).val = dst+i.val*termStride :=
+ Nat.mod_eq_of_lt (by have := endFits i; omega)
+ refine ⟨source,base,fun i => ?_,fun i => ?_,fun i j => Or.inl ?_,fun i j hne => ?_⟩
+ · rw [hs]; exact (sup i).trans (by omega)
+ · rw [hb]; exact endFits i
+ · rw [hs,hb]; exact (sup j).trans (Nat.le_add_right ..)
+ · rw [hb,hb]
+ have step (i j : Fin m) (h : i.val < j.val) : i.val*termStride + 2+n ≤ j.val*termStride := by
+ have h' := Nat.mul_le_mul_right termStride (Nat.succ_le_of_lt h)
+ rw [Nat.succ_mul] at h'
+ omega
+ rcases lt_or_gt_of_ne (Fin.val_ne_of_ne hne) with h | h
+ · right; have := step i j h; omega
+ · left; have := step j i h; omega
+
+variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+variable (order : Fin d ≃ D) (supply : Fin n ≃ S) (L : Layout m d n w)
+
+/-- Expected demand vectors of a pass, read from the given memory. -/
+def Inputs (demand : Fin m → D → ℕ) (mem : Memory w) : Prop :=
+ ∀ i, DemandPreparation.demandAt order (L.source i) mem = demand i
+
+/-- Exact row contents for an individual motif. -/
+def Fields (hp : ∀ i, 0 < p i) (demand : D → ℕ) (v : S → ℕ) (base : BurstRAM.Word w) (mem : Memory w) : Prop :=
+ B.grid.demands.toList[(mem base.val).val]? = some (demandGrid B hp demand).val ∧
+ (mem (base.val+1)).val = repetitions B demand ∧
+ ∀ j, (mem (base.val+2+j.val)).val = v (supply j)
+
+/-- Canonical branch bits for an individual descriptor. -/
+def tape (demand : D → ℕ) (w : ℕ) (v : S → ℕ) : List Bool :=
+ (List.ofFn fun i => PrimedCounter.digits (coordinateBits B demand w) (v (supply i))).flatten
+
+theorem tape_eq (demand : D → ℕ) (hq : ∀ i, 0 < q i) (v : ↥(outerIndices B demand))
+ (hw : outerCap B demand < 2^w) : (outerReader B supply hq demand w hw).encode v = tape B supply demand w v.val := by
+ have he := (ChoiceReader.read_iff (outerReader B supply hq demand w hw) _ v []).mpr (List.append_nil _).symm
+ simpa [tape] using (read_outer_iff B supply hq demand w hw _ [] v).mp he
+
+/-- Instruction cap for computing the repetition count from `d` demand widths bounded by `M`. -/
+def prepFuel (d M : ℕ) := 6*d+7*((∑ i, MotifAdmission.weight p i).size+2*Nat.clog 2 (M+1))+10
+
+/-- One uniform event budget and one probe budget apply to every motif in the pass. -/
+noncomputable def eventsPerRow (d n w M : ℕ) := 6*d+(11*d+4)*B.grid.demands.toList.length+8 +
+ prepFuel (p := p) d M+8+PayloadWrite.storedFuel B n w
+
+/-- Probe bound for constructing one term record, including grid search, repetition
+preparation, and payload stores. -/
+noncomputable def probesPerRow (d n : ℕ) := d+B.grid.demands.toList.length*d+d+n+3
+
+/-- Execute the five reset calls at each visited motif, threading the physical
+external memory and preserving every report in order. -/
+noncomputable def walk (fuel : ℕ) (tapes : Fin m → List Bool) : List (Fin m) → Memory w → Option (List (Report w))
+ | [], _ => some []
+ | i :: is, mem => do
+ let head ← TermRecord.run B order supply (L.source i) (L.base i) mem fuel (tapes i)
+ let tail ← walk fuel tapes is (after mem (eventLog head))
+ return head ++ tail
+
+private structure Visit (hp : ∀ i, 0 < p i) (demand : D → ℕ) (i : Fin m) (v : S → ℕ)
+ (M : ℕ) (initial : Memory w) (rs : List (Report w)) : Prop where
+ fields : Fields B supply hp demand v (L.base i) (after initial (eventLog rs))
+ frame : ∀ x, L.Outside i x → after initial (eventLog rs) x = initial x
+ length : rs.length = 5
+ bits : branchPaths rs = [[],[],[],[],tape B supply demand w v]
+ probes : countProbes (eventLog rs) ≤ probesPerRow B d n
+ steps : (eventLog rs).length ≤ eventsPerRow B d n w M
+
+private def Ready (hp : ∀ i, 0 < p i) (demand : Fin m → D → ℕ) (M : ℕ) : Prop :=
+ ∀ (mem : Memory w), Inputs order L demand mem → ∀ i,
+ let call := TermRecord.run B order supply (L.source i) (L.base i) mem (prepFuel (p := p) d M)
+ (∀ bs, (call bs).isSome ↔ ∃ v : ↥(outerIndices B (demand i)), bs = tape B supply (demand i) w v.val) ∧
+ ∀ v : ↥(outerIndices B (demand i)), ∃ rs, call (tape B supply (demand i) w v.val) = some rs ∧
+ Visit B supply L hp (demand i) i v.val M mem rs
+
+private theorem ready (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
+ ∃ K : ℕ, ∀ m M w, K+4*Nat.clog 2 (M+1) ≤ w → ∀ (L : Layout m d n w) (demand : Fin m → D → ℕ),
+ (∀ i e, demand i e ≤ M) → Ready B order supply L hp demand M := by
+ obtain ⟨K,hK⟩ := TermRecord.run_spec B order supply hp hq
+ refine ⟨K,fun m M w hW L demand hD mem hmem i => ?_⟩
+ have hd := hmem i
+ have all := hK M w hW (L.source i) (L.base i) mem (L.sourceFits i) (L.termFits i) (L.separate i i) (hd ▸ hD i)
+ dsimp only at all
+ rw [hd] at all
+ obtain ⟨hw,row,u,hr,hu,hs,complete⟩ := all
+ dsimp only
+ constructor
+ · intro bits
+ unfold prepFuel
+ rw [hs]
+ exact exists_congr fun v => by rw [ChoiceReader.read_iff, List.append_nil, tape_eq B supply _ hq v hw]
+ · intro v
+ obtain ⟨rs,he,hlen,hm,hbs,hps,hst⟩ := complete v
+ rw [tape_eq B supply _ hq v hw] at he hbs
+ obtain ⟨hrow,hrp,hv,hframe⟩ := TermRecord.recordMemory_fields mem (L.base i) row u supply v.val (L.termFits i)
+ refine ⟨rs,he,⟨?_,fun x hx => hm ▸ hframe x hx,hlen,hbs,hps,hst⟩⟩
+ unfold Fields
+ rw [hm,hrow,hrp]
+ refine ⟨hr,hu,fun j => ?_⟩
+ rw [hv, Fin.val_natCast]
+ exact Nat.mod_eq_of_lt ((MotifAdmission.payload_le_cap q hq _ _ _ _
+ ((mem_outerIndices_iff B hq _ _).mp v.property) _).trans_lt hw)
+
+omit [Fintype D] in
+theorem inputs_after {demand : Fin m → D → ℕ} {mem next : Memory w} (h : Inputs order L demand mem)
+ (i : Fin m) (hf : ∀ x, L.Outside i x → next x = mem x) : Inputs order L demand next := by
+ intro j
+ rw [← h j]
+ funext e
+ obtain ⟨a,rfl⟩ := order.surjective e
+ rw [DemandPreparation.demandAt_address _ _ _ (L.sourceFits j), DemandPreparation.demandAt_address _ _ _ (L.sourceFits j),hf]
+ rcases L.separate i j with hl | hr
+ · left; have := a.isLt; omega
+ · right; omega
+
+private theorem otherFields {demand : D → ℕ} {hp : ∀ i, 0 < p i} {v : S → ℕ} {i : Fin m}
+ {mem next : Memory w} (h : Fields B supply hp demand v (L.base i) mem)
+ (hf : ∀ x, ¬ L.Outside i x → next x = mem x) : Fields B supply hp demand v (L.base i) next := by
+ obtain ⟨hg,hr,hv⟩ := h
+ have inside (j : ℕ) (hj : j < 2+n) : ¬ L.Outside i ((L.base i).val+j) := by unfold Layout.Outside; omega
+ constructor
+ · rwa [hf _ (by simpa using inside 0 (by omega))]
+ · constructor
+ · rwa [hf _ (inside 1 (by omega))]
+ · intro j
+ rw [hf _ (by simpa [Nat.add_assoc] using inside (2+j.val) (by have := j.isLt; omega))]
+ exact hv j
+
+
+/-- Supply-index assignments for all motifs in the pass, with independently
+admitted sets defined by each actual demand row. -/
+noncomputable abbrev Choices (demand : Fin m → D → ℕ) := ∀ i, ↥(outerIndices B (demand i))
+
+private structure Result (hp : ∀ i, 0 < p i) (demand : Fin m → D → ℕ) (v : Choices B demand)
+ (ids : List (Fin m)) (M : ℕ) (initial : Memory w) (rs : List (Report w)) : Prop where
+ fields : ∀ i ∈ ids, Fields B supply hp (demand i) (v i).val (L.base i) (after initial (eventLog rs))
+ frame : ∀ x, (∀ i ∈ ids, L.Outside i x) → after initial (eventLog rs) x = initial x
+ length : rs.length = ids.length*5
+ bits : branchPaths rs = ids.flatMap (fun i => [[],[],[],[],tape B supply (demand i) w (v i).val])
+ probes : countProbes (eventLog rs) ≤ ids.length * probesPerRow B d n
+ steps : (eventLog rs).length ≤ ids.length * eventsPerRow B d n w M
+
+private theorem walk_selected {hp : ∀ i, 0 < p i} {demand : Fin m → D → ℕ} {M : ℕ}
+ (hready : Ready B order supply L hp demand M) (v : Choices B demand) (ids : List (Fin m))
+ (hnd : ids.Nodup) (mem : Memory w) (hin : Inputs order L demand mem) :
+ ∃ rs, walk B order supply L (prepFuel (p := p) d M) (fun i => tape B supply (demand i) w (v i).val)
+ ids mem = some rs ∧ Result B supply L hp demand v ids M mem rs := by
+ induction ids generalizing mem with
+ | nil => exact ⟨[],rfl,⟨by simp,fun _ _ => rfl,rfl,rfl,by simp [eventLog,countProbes],by simp [eventLog]⟩⟩
+ | cons i ids ih =>
+ obtain ⟨hi,hnd'⟩ := List.nodup_cons.mp hnd
+ obtain ⟨head,hhead,hh⟩ := (hready mem hin i).2 (v i)
+ let mid := after mem (eventLog head)
+ obtain ⟨tail,htail,ht⟩ := ih hnd' mid (inputs_after order L hin i hh.frame)
+ let final := after mid (eventLog tail)
+ have he : after mem (eventLog (head ++ tail)) = final := by simp [eventLog,after,final,mid]
+ dsimp only [mid] at htail
+ refine ⟨head++tail,by simp [walk,hhead,htail],⟨?_,?_,?_,?_,?_,?_⟩⟩
+ · intro j hj
+ rw [he]
+ rcases List.mem_cons.mp hj with hij | h
+ · subst j
+ apply otherFields B supply L hh.fields
+ intro x hx
+ apply ht.frame x
+ intro j hj
+ have hne : i ≠ j := fun h => hi (h ▸ hj)
+ have hsep := L.different i j hne
+ unfold Layout.Outside at *
+ omega
+ · exact ht.fields j h
+ · intro x hx
+ rw [he]
+ exact (ht.frame x (fun j hj => hx j (List.mem_cons_of_mem _ hj))).trans (hh.frame x (hx i (by simp)))
+ · simp only [List.length_append,List.length_cons,hh.length,ht.length,Nat.succ_mul]; omega
+ · rw [show branchPaths (head ++ tail) = branchPaths head ++ branchPaths tail from List.map_append,hh.bits,ht.bits,List.flatMap_cons]
+ · rw [show eventLog (head++tail) = eventLog head ++ eventLog tail from List.flatMap_append,DemandPreparation.probes_append]
+ simpa only [List.length_cons,Nat.succ_mul,Nat.add_comm] using Nat.add_le_add hh.probes ht.probes
+ · rw [show eventLog (head++tail) = eventLog head ++ eventLog tail from List.flatMap_append,List.length_append]
+ simpa only [List.length_cons,Nat.succ_mul,Nat.add_comm] using Nat.add_le_add hh.steps ht.steps
+
+private theorem walk_sound {hp : ∀ i, 0 < p i} {demand : Fin m → D → ℕ} {M : ℕ}
+ (hready : Ready B order supply L hp demand M) (tapes : Fin m → List Bool) (ids : List (Fin m))
+ (mem : Memory w) (hin : Inputs order L demand mem) (rs : List (Report w))
+ (hr : walk B order supply L (prepFuel (p := p) d M) tapes ids mem = some rs) :
+ ∀ i ∈ ids, ∃ v : ↥(outerIndices B (demand i)), tapes i = tape B supply (demand i) w v.val := by
+ induction ids generalizing mem rs with
+ | nil => simp
+ | cons i ids ih =>
+ cases hh : TermRecord.run B order supply (L.source i) (L.base i) mem (prepFuel (p := p) d M) (tapes i) with
+ | none => simp [walk,hh] at hr
+ | some head =>
+ let mid := after mem (eventLog head)
+ cases ht : walk B order supply L (prepFuel (p := p) d M) tapes ids mid with
+ | none => simp [walk,hh,mid,ht] at hr
+ | some tail =>
+ obtain ⟨v,hv⟩ := ((hready mem hin i).1 (tapes i)).mp (by rw [hh]; rfl)
+ obtain ⟨head',hh',hfield⟩ := (hready mem hin i).2 v
+ rw [← hv,hh] at hh'
+ cases Option.some.inj hh'
+ intro j hj
+ rcases List.mem_cons.mp hj with rfl | hj
+ · exact ⟨v,hv⟩
+ · exact ih mid (inputs_after order L hin i hfield.frame) tail ht j hj
+
+private theorem tape_inj {hp : ∀ i, 0 < p i} {demand : Fin m → D → ℕ} {M : ℕ}
+ (hready : Ready B order supply L hp demand M) (mem : Memory w) (hin : Inputs order L demand mem)
+ (i : Fin m) {v v' : ↥(outerIndices B (demand i))}
+ (h : tape B supply (demand i) w v.val = tape B supply (demand i) w v'.val) : v = v' := by
+ obtain ⟨rs,hr,hv⟩ := (hready mem hin i).2 v
+ obtain ⟨rs',hr',hv'⟩ := (hready mem hin i).2 v'
+ rw [h,hr'] at hr
+ cases Option.some.inj hr
+ apply Subtype.ext
+ funext e
+ obtain ⟨j,rfl⟩ := supply.surjective e
+ exact ((hv.fields.2.2 j).symm.trans (hv'.fields.2.2 j))
+
+/-- The full pass has exactly the admissible term choices as successful
+streams. Every output row survives to the end of the pass, and outside all
+term rows the external memory is preserved. -/
+theorem run_spec (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
+ ∃ K : ℕ, ∀ m M w, K+4*Nat.clog 2 (M+1) ≤ w → ∀ (L : Layout m d n w) (demand : Fin m → D → ℕ),
+ (∀ i e, demand i e ≤ M) → ∀ (mem : Memory w), Inputs order L demand mem →
+ let fuel := prepFuel (p := p) d M
+ let run := fun tapes => walk B order supply L fuel tapes (List.finRange m) mem
+ (∀ tapes, (run tapes).isSome ↔ ∃! v : Choices B demand,
+ tapes = fun i => tape B supply (demand i) w (v i).val) ∧
+ ∀ v : Choices B demand, ∃ rs, run (fun i => tape B supply (demand i) w (v i).val) = some rs ∧
+ (∀ i, Fields B supply hp (demand i) (v i).val (L.base i) (after mem (eventLog rs))) ∧
+ (∀ x, (∀ i, L.Outside i x) → after mem (eventLog rs) x = mem x) ∧
+ rs.length = m*5 ∧ branchPaths rs = (List.finRange m).flatMap
+ (fun i => [[],[],[],[],tape B supply (demand i) w (v i).val]) ∧
+ countProbes (eventLog rs) ≤ m*probesPerRow B d n ∧ (eventLog rs).length ≤ m*eventsPerRow B d n w M := by
+ obtain ⟨K,hK⟩ := ready B order supply hp hq
+ refine ⟨K,fun m M w hW L demand hD mem hin => ?_⟩
+ have hR := hK m M w hW L demand hD
+ have full v := walk_selected B order supply L hR v (List.finRange m) (List.nodup_finRange _) mem hin
+ dsimp only
+ constructor
+ · intro tapes
+ constructor
+ · intro h
+ obtain ⟨rs,hr⟩ := Option.isSome_iff_exists.mp h
+ have witness (i : Fin m) := walk_sound B order supply L hR tapes (List.finRange m) mem hin rs hr i (by simp)
+ choose v hv using witness
+ refine ⟨v,funext hv,fun z hz => ?_⟩
+ funext i
+ exact tape_inj B order supply L hR mem hin i ((congrFun hz i).symm.trans (hv i))
+ · rintro ⟨v,rfl,_⟩
+ obtain ⟨rs,hr,_⟩ := full v
+ exact Option.isSome_iff_exists.mpr ⟨rs,hr⟩
+ · intro v
+ obtain ⟨rs,hr,hs⟩ := full v
+ exact ⟨rs,hr,fun i => hs.fields i (by simp),fun x h => hs.frame x (fun i _ => h i),
+ by simpa using hs.length,hs.bits,by simpa using hs.probes,by simpa using hs.steps⟩
+
+private theorem one_site_bound (i : Fin m) (M : ℕ) (mem : Memory w) (bits : List Bool)
+ {rs : List (Report w)} (h : TermRecord.run B order supply (L.source i) (L.base i) mem
+ (prepFuel (p := p) d M) bits = some rs) : ∀ r ∈ rs, r.events.length ≤ eventsPerRow B d n w M := by
+ simp only [TermRecord.run,TermRecord.headers,bind,Option.bind_eq_some_iff] at h
+ obtain ⟨hs,⟨g,hg,row,_,sr,hsr,src',_,rep,hrep,u,_,su,hsu,hlist⟩,cursor,_,pay,hpay,hlast⟩ := h
+ change some [g,sr,rep,su] = some hs at hlist
+ cases Option.some.inj hlist
+ change some ([g,sr,rep,su] ++ [pay]) = some rs at hlast
+ cases Option.some.inj hlast
+ rw [(TermRecord.save_native ..).1] at hsr hsu
+ cases Option.some.inj hsr
+ cases Option.some.inj hsu
+ have gsteps := (execute_spec hg).1.length_lt
+ have rsteps := (execute_spec hrep).1.length_lt
+ have psteps := (execute_spec hpay).1.length_lt
+ simp only [List.cons_append,List.nil_append,List.forall_mem_cons,List.not_mem_nil,IsEmpty.forall_iff]
+ unfold eventsPerRow
+ change _ ∧ 4 ≤ _ ∧ _ ∧ 4 ≤ _ ∧ _
+ repeat' constructor <;> try omega
+ simp
+
+/-- Each individual report obeys the same local instruction cap, even in
+a pass with an arbitrarily large number of motifs. -/
+theorem walk_site_bound (M : ℕ) (tapes : Fin m → List Bool) (ids : List (Fin m)) (mem : Memory w)
+ {rs : List (Report w)} (h : walk B order supply L (prepFuel (p := p) d M) tapes ids mem = some rs) :
+ ∀ r ∈ rs, r.events.length ≤ eventsPerRow B d n w M := by
+ induction ids generalizing mem rs with
+ | nil => change some [] = some rs at h; cases Option.some.inj h; simp
+ | cons i ids ih =>
+ simp only [walk,bind,Option.bind_eq_some_iff] at h
+ obtain ⟨head,hh,tail,ht,hall⟩ := h
+ change some (head ++ tail) = some rs at hall
+ cases Option.some.inj hall
+ simpa only [List.forall_mem_append] using And.intro (one_site_bound B order supply L i M mem (tapes i) hh) (ih _ ht)
+
+end CompressorRecords.TermRecordScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermRowStart.lean b/lean/OAI/Computability/VPVNP/CompressorTermRowStart.lean
new file mode 100644
index 0000000000..72af9f079f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermRowStart.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.CompressorTermWorkerDispatch
+import OAI.Computability.VPVNP.CompressorSourceLaunch
+import OAI.Computability.VPVNP.CompressorOnlineRowInverse
+
+/-! # The physical row invariant at a compressor term selector
+
+The fixed term table reads a demand row and writes its selected supply
+coordinates. For any successful choice tape it preserves all demand
+inputs, writes outside the scheduler frame, returns the next ordinal,
+and satisfies the row-specific clock. The script recipe supplies its
+actual bank from the current RAM.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TermWorker
+
+open BurstRAM TermRecordScan MotifGrid MotifBlocks MotifConversion MotifSelector Schedule OrdinalRun
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+variable {d n : ℕ} (order : Fin d ≃ D) (supply : Fin n ≃ S) (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i)
+
+private theorem call_catalog {W : Schedule.Pass} (eq : W = motifPass B order n) {w : ℕ}
+ (addr : Fin 4 → BurstRAM.Word w) (f : ℕ) (s : BurstRAM.Word w) (mem : Memory w) (bs : List Bool) :
+ let G := (W.table.instantiate w (fun i => motifData B order supply w addr (i.cast (congrArg Schedule.Pass.params eq)))).program
+ execute G f (G.start s) mem bs = execute (program B order supply addr) f ((program B order supply addr).start s) mem bs := by
+ subst W
+ rfl
+
+/-- Genuine local inverse for any catalog occurrence of the fixed term
+worker, using its actual call-frame and event bound. -/
+theorem workerStep {workers m M w cap fuel : ℕ} (C : Catalog workers) (j : Fin workers)
+ (ports : Schedule.Ports w) (passEq : C j = motifPass B order n)
+ (layout : Layout m d n w) (addr : Fin 4 → BurstRAM.Word w) (haddr : Addresses layout addr)
+ (demand : Fin m → D → ℕ) (hD : ∀ i x, demand i x ≤ M)
+ (width : frameFit B order supply hp hq + 4*Nat.clog 2 (M+1) ≤ w)
+ (clock : budget B d n w M ≤ fuel) (hcap : fuel ≤ cap) (hstop : m < 2^w)
+ (apart : ∀ i x, ControlCell (C j).params ports x → layout.Outside i x) :
+ Online.WorkerStep ports j (catalogWords B order supply C j addr passEq) (m : BurstRAM.Word w) cap fuel
+ (fun _ mem => Inputs order layout demand mem) := by
+ intro st mem bs rep frame inv active source
+ have hi : st.val < m := by
+ change st.val < m % (2^w) at active
+ rwa [Nat.mod_eq_of_lt hstop] at active
+ let i : Fin m := ⟨st.val,hi⟩
+ have stEq : (i.val : BurstRAM.Word w)=st := Fin.ext (Nat.mod_eq_of_lt st.isLt)
+ have capBound := clock.trans hcap
+ have concrete : execute (program B order supply addr) cap ((program B order supply addr).start st) mem bs = some rep :=
+ (call_catalog B order supply passEq addr cap st mem bs).symm.trans source
+ rw [← stEq] at concrete
+ obtain ⟨next,inv',keep,_,short⟩ := (call_frame B order supply hp hq).choose_spec m M w width
+ layout addr haddr demand hD cap capBound mem inv i bs rep concrete
+ exact ⟨short.trans_le clock,_,next,ready_of_preserved C j ports frame (fun x hx => keep x (apart i x hx)),inv'⟩
+
+open DescriptorSpace BlockPlanner SourceOnline SourceTransport
+open private control_below from OAI.Computability.VPVNP.CompressorSourceOnline
+
+/-- Construct the actual scheduler boundary certificate needed to invert a
+term-selection row. The readable and writable term arenas begin after the
+workspace directory. Only the public operand and width equations specific
+to the physical motif remain at a use site. -/
+noncomputable def rowStart {m M w cap fuel : ℕ} (A : Script) (outer : DescriptorSpace.Layout)
+ (base : BurstRAM.Word w) (hg : arity A.catalog=outer.shape.arity) (hb : base.val=outer.base)
+ (fit : levelStart outer 0 < 2^w) (mem : Memory w) (j : Fin A.size)
+ (passEq : A.catalog j = motifPass B order n)
+ (layout : TermRecordScan.Layout m d n w) (addr : Fin 4 → BurstRAM.Word w) (haddr : Addresses layout addr)
+ (demand : Fin m → D → ℕ) (hD : ∀ i x, demand i x ≤ M)
+ (width : frameFit B order supply hp hq+4*Nat.clog 2 (M+1) ≤ w)
+ (clock : budget B d n w M ≤ fuel) (hstop : m < 2^w)
+ (readable : ∀ i, levelStart outer 0 ≤ (layout.source i).val)
+ (writable : ∀ i, levelStart outer 0 ≤ (layout.base i).val)
+ (inputs : Inputs order layout demand mem)
+ (stop : A.operand base mem j (A.visit j).stop = (m : BurstRAM.Word w))
+ (args : ∀ i, A.operand base mem j ((A.visit j).params i) = catalogWords B order supply A.catalog j addr passEq i)
+ (phase : (Online.calendar A.plan).phase (mem (Workspace.ports (arity A.catalog) base).ordinal.val).val = j.val)
+ (room : (mem (Workspace.ports (arity A.catalog) base).ordinal.val).val < directoryRows outer)
+ (active : mem (Workspace.ports (arity A.catalog) base).ordinal.val < mem (Workspace.ports (arity A.catalog) base).rows.val)
+ (recipeCap : (A.plan.recipes j).2.code.length+1+2*(Online.N A.size A.size)+5 ≤ cap)
+ (dataCap : fuel+3+4*((A.catalog j).params+1)+2*(Online.N A.size A.size)+5 ≤ cap) :
+ Online.Run.RowStart A.plan (Workspace.ports (arity A.catalog) base) cap mem := by
+ let ports := Workspace.ports (arity A.catalog) base
+ let entry := Online.rowInput A.plan ports mem j
+ let fresh := Directory.prepared A.catalog ports entry
+ have launch := evaluated_launch A base outer hg hb fit mem j fuel [] room active
+ have stored : Directory.words A.catalog ports j entry = catalogWords B order supply A.catalog j addr passEq :=
+ launch.params.trans (funext args)
+ have endWord : Directory.bound A.catalog ports entry = (m : BurstRAM.Word w) := launch.stop.trans stop
+ have agree := OnlineFootprint.prepared A outer base hg hb fit mem j room
+ have freshInput : Inputs order layout demand fresh := by
+ intro i
+ funext x
+ obtain ⟨l,rfl⟩ := order.surjective x
+ rw [DemandPreparation.demandAt_address order _ _ (layout.sourceFits i)]
+ have hr := congrFun (inputs i) (order l)
+ rw [DemandPreparation.demandAt_address order _ _ (layout.sourceFits i)] at hr
+ exact (congrArg Fin.val (agree _ ((readable i).trans (Nat.le_add_right ..)))).symm.trans hr
+ refine ⟨j,j,fuel,fun _ mem => Inputs order layout demand mem,phase,?_,?_,recipeCap,dataCap,?_,freshInput,?_⟩
+ · change entry ports.ordinal.val < entry ports.rows.val
+ rw [show entry ports.ordinal.val = mem ports.ordinal.val from launch.ordinal,
+ show entry ports.rows.val = mem ports.rows.val from launch.rows]
+ exact active
+ · have hpos : 0 < budget B d n w M := by unfold budget; omega
+ exact hpos.trans_le clock
+ · change Ready A.catalog j ports (Directory.words A.catalog ports j entry) (Directory.bound A.catalog ports entry) fresh
+ rw [stored,endWord]
+ have hr : Ready A.catalog j ports (fun i => A.operand base mem j ((A.visit j).params i))
+ (A.operand base mem j (A.visit j).stop) fresh := launch.ready
+ exact ⟨hr.1,hr.2.1.trans stop,funext fun i => (congrFun hr.2.2 i).trans (args i)⟩
+ · change Online.WorkerStep ports j (Directory.words A.catalog ports j entry) (Directory.bound A.catalog ports entry) cap fuel _
+ rw [stored,endWord]
+ exact workerStep B order supply hp hq A.catalog j ports passEq layout addr haddr demand hD width clock
+ (by omega) hstop (fun i x hx => Or.inl ((control_below A outer base hg hb fit j x hx).trans_le (writable i)))
+
+end CompressorRecords.TermWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermWorker.lean b/lean/OAI/Computability/VPVNP/CompressorTermWorker.lean
new file mode 100644
index 0000000000..adff3b895f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermWorker.lean
@@ -0,0 +1,251 @@
+import OAI.Computability.VPVNP.CompressorFlowRebase
+import OAI.Computability.VPVNP.CompressorTermRecord
+import OAI.Computability.VPVNP.PrimedCounterCallPaths
+import OAI.Computability.VPVNP.RAMChoicePrefix
+import OAI.Computability.VPVNP.CompressorRecordsSchedule
+
+/-!
+# A fixed native worker for a strided motif scan
+
+One call starts at the current motif ordinal. Its address prelude multiplies
+the ordinal by each of the two strides. The grid search, repetition routine
+and payload writer have disjoint reset register banks. Between them two native
+stores save the grid and repetition results in the row just computed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TermWorker
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter
+open scoped Fin.CommRing
+
+variable {w n g r k : ℕ}
+
+/-- Total private register count for the address prelude, grid search, repetition routine, and
+payload writer. -/
+abbrev Registers (n : ℕ) := 7 + (8 + (8 + (6+n)))
+/-- Total public operand count for the address, grid, repetition, and payload banks. -/
+abbrev Ports (g r k : ℕ) := 4 + (g + (r+k))
+
+/-- Embed the address prelude's seven registers at the start of the fused worker's register
+bank. -/
+def headReg (n : ℕ) := Fin.castAddEmb (8+(8+(6+n))) (n := 7)
+/-- Embed the grid search's eight registers immediately after the address prelude's registers. -/
+def gridReg (n : ℕ) := (Fin.castAddEmb (8+(6+n)) (n := 8)).trans (Fin.natAddEmb 7)
+/-- Embed the repetition routine's eight registers after the grid search's register bank. -/
+def repReg (n : ℕ) := ((Fin.castAddEmb (6+n) (n := 8)).trans (Fin.natAddEmb 8)).trans (Fin.natAddEmb 7)
+/-- Embed the payload writer's registers in the final block of the fused worker's register
+bank. -/
+def payloadReg (n : ℕ) := ((Fin.natAddEmb 8 (m := 6+n)).trans (Fin.natAddEmb 8)).trans (Fin.natAddEmb 7)
+
+/-- Index the two base addresses and two strides in the worker's public operand bank. -/
+def addrPort : Fin 4 → Fin (Ports g r k) := Fin.castAdd _
+/-- Index the grid-search operands immediately after the four address operands. -/
+def gridPort : Fin g → Fin (Ports g r k) := Fin.natAdd 4 ∘ Fin.castAdd _
+/-- Index the repetition routine's operands after the address and grid operands. -/
+def repPort : Fin r → Fin (Ports g r k) := Fin.natAdd 4 ∘ Fin.natAdd g ∘ Fin.castAdd k
+/-- Index the payload writer's operands in the final block of public words. -/
+def payloadPort : Fin k → Fin (Ports g r k) := Fin.natAdd 4 ∘ Fin.natAdd g ∘ Fin.natAdd r
+
+/-- Assemble the four public operand banks in the order used by the fused term worker. -/
+def words (addr : Fin 4 → Word w) (grid : Fin g → Word w) (reps : Fin r → Word w) (payload : Fin k → Word w) :
+ Fin (Ports g r k) → Word w := Fin.append addr (Fin.append grid (Fin.append reps payload))
+
+private theorem addr_words (a : Fin 4 → Word w) (x : Fin g → Word w) (y : Fin r → Word w) (z : Fin k → Word w) :
+ words a x y z ∘ addrPort = a := by funext i; simp [words,addrPort]
+private theorem grid_words (a : Fin 4 → Word w) (x : Fin g → Word w) (y : Fin r → Word w) (z : Fin k → Word w) :
+ words a x y z ∘ gridPort = x := by funext i; simp [words,gridPort]
+private theorem rep_words (a : Fin 4 → Word w) (x : Fin g → Word w) (y : Fin r → Word w) (z : Fin k → Word w) :
+ words a x y z ∘ repPort = y := by funext i; simp [words,repPort]
+private theorem payload_words (a : Fin 4 → Word w) (x : Fin g → Word w) (y : Fin r → Word w) (z : Fin k → Word w) :
+ words a x y z ∘ payloadPort = z := by funext i; simp [words,payloadPort]
+
+/-- Address of motif `j`'s input demand row computed from the input base and stride. -/
+def source (addr : Fin 4 → Word w) (j : Word w) := j * addr 1 + addr 0
+/-- Address of motif `j`'s output term record computed from the output base and stride. -/
+def base (addr : Fin 4 → Word w) (j : Word w) := j * addr 3 + addr 2
+
+/-- Compute the demand and term addresses, output field addresses, and next motif ordinal from
+the persistent cursor. -/
+def prelude : Flow 7 4 :=
+ .seq (.line (.stateWord 0)) <|
+ .seq (.line (.publicWord 1 1)) <|
+ .seq (.line (.binary .mul 1 0 1)) <|
+ .seq (.line (.publicWord 6 0)) <|
+ .seq (.line (.binary .add 1 1 6)) <|
+ .seq (.line (.publicWord 2 3)) <|
+ .seq (.line (.binary .mul 2 0 2)) <|
+ .seq (.line (.publicWord 6 2)) <|
+ .seq (.line (.binary .add 2 2 6)) <|
+ .seq (.line (.constant 6 1)) <|
+ .seq (.line (.binary .add 3 2 6)) <|
+ .seq (.line (.binary .add 4 3 6)) (.line (.binary .add 5 0 6))
+
+private theorem prelude_exec (a : Fin 4 → Word w) (j : Word w) (m : Memory w) :
+ ∃ out, Flow.Exec a j prelude (fun _ => 0) m (List.replicate 13 .tick) out m ∧
+ out 1 = source a j ∧ out 2 = base a j ∧ out 3 = base a j + 1 ∧
+ out 4 = base a j + 2 ∧ out 5 = j+1 := by
+ let dst := base a j
+ let out : Regs w 7 := ![j,source a j,dst,dst+1,dst+2,j+1,1]
+ refine ⟨out,?_,rfl,rfl,rfl,rfl,rfl⟩
+ unfold prelude
+ repeat' apply Flow.Exec.seq (.line rfl)
+ apply Flow.Exec.line
+ simp (config := {decide := true}) [Op.effect,BinaryOp.eval,Function.update,source,base,out,dst]
+ funext i
+ fin_cases i <;> simp (config := {decide := true}) [Function.update]
+ ring
+
+/-- Assemble the fixed stages and choose their private register locations. -/
+def headerCode (n : ℕ) (grid : Flow 8 g) (reps : Flow 8 r) (k : ℕ) : Flow (Registers n) (Ports g r k) :=
+ .seq (renameFlow (headReg n) addrPort prelude) <|
+ .seq (Rebased.code (gridReg n) gridPort (headReg n 1) grid) <|
+ .seq (.line (.write (headReg n 2) (gridReg n 1))) <|
+ .seq (Rebased.code (repReg n) repPort (headReg n 1) reps)
+ (.line (.write (headReg n 3) (repReg n 2)))
+
+/-- Combine the strided address prelude, grid and repetition stores, and payload writer in one
+worker. -/
+def code (grid : Flow 8 g) (reps : Flow 8 r) (payload : Flow (6+n) k) : Flow (Registers n) (Ports g r k) :=
+ .seq (headerCode n grid reps k) (Rebased.code (payloadReg n) payloadPort (headReg n 4) payload)
+
+/-- Schedule the fused worker with the successor motif ordinal as its return word. -/
+def pass (grid : Flow 8 g) (reps : Flow 8 r) (payload : Flow (6+n) k) : Schedule.Pass :=
+ ⟨_,_,_,(code grid reps payload).template (some (headReg n 5))⟩
+
+private theorem head_left {j : Fin 7} {i : Fin 8} : gridReg n i ≠ headReg n j := by
+ intro h; have := congrArg Fin.val h; change 7+i.val = j.val at this; omega
+
+private theorem grid_left {i j : Fin 8} : repReg n i ≠ gridReg n j := by
+ intro h; have := congrArg Fin.val h; change 7+(8+i.val) = 7+j.val at this; omega
+
+private theorem head_rep {i : Fin 8} {j : Fin 7} : repReg n i ≠ headReg n j := by
+ intro h; have := congrArg Fin.val h; change 7+(8+i.val) = j.val at this; omega
+
+private theorem payload_head {i : Fin (6+n)} {j : Fin 7} : payloadReg n i ≠ headReg n j := by
+ intro h; have := congrArg Fin.val h; change 7+(8+(8+i.val)) = j.val at this; omega
+
+private theorem payload_grid {i : Fin (6+n)} {j : Fin 8} : payloadReg n i ≠ gridReg n j := by
+ intro h; have := congrArg Fin.val h; change 7+(8+(8+i.val)) = 7+j.val at this; omega
+
+private theorem payload_rep {i : Fin (6+n)} {j : Fin 8} : payloadReg n i ≠ repReg n j := by
+ intro h; have := congrArg Fin.val h; change 7+(8+(8+i.val)) = 7+(8+j.val) at this; omega
+
+private theorem outRange {a b : Type*} {f : a → b} {y : b} (h : ∀ i, f i ≠ y) :
+ y ∉ Set.range f := fun ⟨i,hi⟩ => h i hi
+
+/-- The only external writes beyond the payload are the row index and the
+repetition header. The thirteen address operations consume private ticks. -/
+def headerLog (dst row u : Word w) (gs rs : List (Event w)) :=
+ List.replicate 13 .tick ++ gs ++ [.write dst row] ++ rs ++ [.write (dst+1) u]
+
+private theorem prepared {grid : Flow 8 g} {reps : Flow 8 r} (n : ℕ)
+ (a : Fin 4 → Word w) (x : Fin g → Word w) (y : Fin r → Word w) (z : Fin k → Word w)
+ (j : Word w) (m mg mr : Memory w) (gs rs : List (Event w))
+ (G R : Regs w 8)
+ (hg : Flow.Exec x (source a j) grid (fun _ => 0) m gs G mg)
+ (hr : Flow.Exec y (source a j) reps (fun _ => 0) (writeMemory mg (base a j) (G 1)) rs R mr) :
+ ∃ out, Flow.Exec (words a x y z) j (headerCode n grid reps k) (fun _ => 0) m
+ (headerLog (base a j) (G 1) (R 2) gs rs) out (writeMemory mr (base a j+1) (R 2)) ∧
+ out ∘ payloadReg n = (fun _ => 0) ∧ out (headReg n 4) = base a j+2 ∧ out (headReg n 5) = j+1 := by
+ let pub := words a x y z
+ obtain ⟨h,hpre,hs,hd,hd1,hd2,hn⟩ := prelude_exec a j m
+ obtain ⟨h',hinit,hH,oH⟩ := liftExec (headReg n) addrPort pub ((addr_words a x y z) ▸ hpre)
+ (fun _ => 0) rfl
+ have hHi i : h' (headReg n i) = h i := congrFun hH i
+ have h0 i : h' (gridReg n i) = 0 := oH _ (outRange fun _ => head_left.symm)
+ obtain ⟨g',hgrid,hG,oG⟩ := Rebased.liftExec (state := j) (gridReg n) gridPort (headReg n 1)
+ (outRange fun _ => head_left) pub ((grid_words a x y z) ▸ hg) h' (funext h0) ((hHi 1).trans hs)
+ have gHead i : g' (headReg n i) = h i := (oG _ (outRange fun _ => head_left)).trans (hHi i)
+ have g₁ : g' (gridReg n 1) = G 1 := congrFun hG 1
+ have store₁ : Flow.Exec pub j (.line (.write (headReg n 2) (gridReg n 1))) g' mg
+ [.write (base a j) (G 1)] g' (writeMemory mg (base a j) (G 1)) := by
+ apply Flow.Exec.line; simp only [Op.effect,gHead,hd,g₁]
+ have g0 i : g' (repReg n i) = 0 :=
+ (oG _ (outRange fun _ => grid_left.symm)).trans (oH _ (outRange fun _ => head_rep.symm))
+ obtain ⟨r',hreps,hR,oR⟩ := Rebased.liftExec (state := j) (repReg n) repPort (headReg n 1)
+ (outRange fun _ => head_rep) pub ((rep_words a x y z) ▸ hr) g' (funext g0) ((gHead 1).trans hs)
+ have rHead i : r' (headReg n i) = h i := (oR _ (outRange fun _ => head_rep)).trans (gHead i)
+ have r₂ : r' (repReg n 2) = R 2 := congrFun hR 2
+ have store₂ : Flow.Exec pub j (.line (.write (headReg n 3) (repReg n 2))) r' mr
+ [.write (base a j+1) (R 2)] r' (writeMemory mr (base a j+1) (R 2)) := by
+ apply Flow.Exec.line; simp only [Op.effect,rHead,hd1,r₂]
+ have r0 i : r' (payloadReg n i) = 0 := (oR _ (outRange fun _ => payload_rep.symm)).trans
+ ((oG _ (outRange fun _ => payload_grid.symm)).trans (oH _ (outRange fun _ => payload_head.symm)))
+ refine ⟨r',?_,funext r0,(rHead 4).trans hd2,(rHead 5).trans hn⟩
+ simpa only [headerCode,headerLog,List.append_assoc] using
+ (Flow.Exec.seq hinit (.seq hgrid (.seq store₁ (.seq hreps store₂))))
+
+private theorem fixedPrefix {R K : ℕ} {pub : Fin K → Word w} {st : Word w} {a : Flow R K}
+ {start m es rs m' fs out last}
+ (he : Flow.Exec pub st a start m es rs m') (bits : choiceBits es = [])
+ (other : Flow.Exec pub st a start m fs out last) : fs = es ∧ out = rs ∧ last = m' := by
+ have reports (res : Option (Fin R)) :
+ (⟨es,res.map rs⟩ : Report w) = ⟨fs,res.map out⟩ := by
+ have one := (Flow.template_execute_iff a res pub st (fun _ => 0) start m (es.length+1) []
+ ⟨es,res.map rs⟩).mpr ⟨rs,m',he,rfl,Nat.lt_succ_self _,bits⟩
+ have two := (Flow.template_execute_iff a res pub st (fun _ => 0) start m (fs.length+1) (choiceBits fs)
+ ⟨fs,res.map out⟩).mpr ⟨out,last,other,rfl,Nat.lt_succ_self _,rfl⟩
+ exact (execute_prefix_unique (suffix := choiceBits fs) one two).2
+ have logs := (congrArg Report.events (reports none)).symm
+ refine ⟨logs,funext fun i => Option.some.inj (congrArg Report.result (reports (some i))).symm,?_⟩
+ exact (Call.exec_memory other).symm.trans ((congrArg (after m) logs).trans (Call.exec_memory he))
+
+/-- After the empty-choice prefix, the payload is executed on reset ordinary
+registers with its computed base. Conversely every execution restricts to
+one payload derivation with exactly its tape and memory effect. -/
+theorem execute_iff {grid : Flow 8 g} {reps : Flow 8 r} (payload : Flow (6+n) k)
+ (a : Fin 4 → Word w) (x : Fin g → Word w) (y : Fin r → Word w) (z : Fin k → Word w)
+ (j : Word w) (m mg mr : Memory w) (gs rs : List (Event w)) (G R : Regs w 8)
+ (hg : Flow.Exec x (source a j) grid (fun _ => 0) m gs G mg) (hgb : choiceBits gs = [])
+ (hr : Flow.Exec y (source a j) reps (fun _ => 0) (writeMemory mg (base a j) (G 1)) rs R mr)
+ (hrb : choiceBits rs = []) (cap : ℕ) (bs : List Bool) (rep : Report w) :
+ let dst := base a j
+ let pre := headerLog dst (G 1) (R 2) gs rs
+ let mid := writeMemory mr (dst+1) (R 2)
+ let T := ((pass grid reps payload).table.instantiate w (words a x y z)).program
+ execute T cap (T.start j) m bs = some rep ↔
+ ∃ vs V mv, Flow.Exec z (dst+2) payload (fun _ => 0) mid vs V mv ∧
+ rep = ⟨pre++vs,some (j+1)⟩ ∧ pre.length+vs.length < cap ∧ choiceBits vs = bs := by
+ dsimp only
+ let pub := words a x y z
+ let dst := base a j
+ let pre := headerLog dst (G 1) (R 2) gs rs
+ let mid := writeMemory mr (dst+1) (R 2)
+ obtain ⟨prep,he,hzero,harg,hnext⟩ := prepared n a x y z j m mg mr gs rs G R hg hr
+ have hn : choiceBits pre = [] := by simp [pre,headerLog,Flow.choiceBits_append,hgb,hrb,choiceBits,List.replicate_succ]
+ change choiceBits (headerLog (base a j) (G 1) (R 2) gs rs) = [] at hn
+ have core := Flow.template_execute_iff (code grid reps payload) (some (headReg n 5)) pub j (fun _ => 0)
+ (fun _ => 0) m cap bs rep
+ apply core.trans
+ constructor
+ · rintro ⟨out,last,run,result,size,tape⟩
+ obtain ⟨fs,q,mq,vs,hfirst,hvs,hlog⟩ : ∃ fs q mq vs, Flow.Exec pub j (headerCode n grid reps k) (fun _ => 0) m fs q mq ∧
+ Flow.Exec pub j (Rebased.code (payloadReg n) payloadPort (headReg n 4) payload) q mq vs out last ∧
+ rep.events = fs++vs := by
+ generalize h : rep.events = es at run
+ cases run with | seq h₁ h₂ => exact ⟨_,_,_,_,h₁,h₂,rfl⟩
+ obtain ⟨rfl,rfl,rfl⟩ := fixedPrefix he hn hfirst
+ obtain ⟨pay,away⟩ := Rebased.restrictExec (payloadReg n) payloadPort (headReg n 4)
+ (outRange fun _ => payload_head) pub payload hvs
+ rw [payload_words a x y z,harg,hzero] at pay
+ refine ⟨vs,_,_,pay,?_,?_,?_⟩
+ · cases rep with | mk es res =>
+ simp only [Report.mk.injEq]; exact ⟨hlog,result.trans (congrArg some ((away _ (outRange fun _ => payload_head)).trans hnext))⟩
+ · simpa only [hlog,List.length_append] using size
+ · simpa only [hlog,Flow.choiceBits_append,hn,List.nil_append] using tape
+ · rintro ⟨vs,V,mv,pay,rfl,size,tape⟩
+ obtain ⟨out,body,_,away⟩ := Rebased.liftExec (state := j) (payloadReg n) payloadPort (headReg n 4)
+ (outRange fun _ => payload_head) pub ((payload_words a x y z) ▸ pay) prep hzero harg
+ refine ⟨out,mv,.seq he body,congrArg some ((away _ (outRange fun _ => payload_head)).trans hnext).symm,?_,?_⟩
+ · simpa only [List.length_append] using size
+ · simpa only [Flow.choiceBits_append,hn,List.nil_append] using tape
+
+end CompressorRecords.TermWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermWorkerDispatch.lean b/lean/OAI/Computability/VPVNP/CompressorTermWorkerDispatch.lean
new file mode 100644
index 0000000000..80798d993c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermWorkerDispatch.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.CompressorTermWorkerScan
+import OAI.Computability.VPVNP.CompressorRecordsOrdinalRun
+import OAI.Computability.VPVNP.CompressorRecordsOnline
+
+/-!
+# Fused term scans in the guarded descriptor dispatcher
+
+The term writes stay in a single strided row at each reset. A dispatch frame
+outside those rows therefore remains ready through the exclusive motif count.
+The closing guard transfers to the level calendar.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TermWorker
+
+open BurstRAM TermRecordScan MotifGrid MotifBlocks MotifConversion MotifSelector Schedule OrdinalRun
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+variable {d n : ℕ} (order : Fin d ≃ D) (supply : Fin n ≃ S) (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i)
+
+/-- Fixed word-width allowance used to prove that a successful call writes only its selected
+term row. -/
+noncomputable def frameFit : ℕ := (call_frame B order supply hp hq).choose
+
+variable {m w workers M fuel : ℕ} (C : Catalog workers) (worker : Fin workers) (ports : Schedule.Ports w)
+ (pub : Fin (C worker).params → BurstRAM.Word w) (L : Layout m d n w) (addr : Fin 4 → BurstRAM.Word w)
+ (haddr : Addresses L addr) (demand : Fin m → D → ℕ) (hD : ∀ i e, demand i e ≤ M)
+ (hW : frameFit B order supply hp hq + 4*Nat.clog 2 (M+1) ≤ w)
+ (hcap : budget B d n w M ≤ fuel) (hstop : m < 2^w)
+ (apart : ∀ i x, ControlCell (C worker).params ports x → L.Outside i x)
+ (mem : Memory w) (hin : Inputs order L demand mem)
+ (ready : Schedule.Ready C worker ports pub (m : BurstRAM.Word w) mem)
+ (bits : List (List Bool)) (rs : List (Report w)) (size : bits.length = m)
+ (run : runSegment (program B order supply addr) fuel (some 0) mem bits = some rs)
+
+include haddr hD hW hcap hstop apart hin ready size run in
+theorem valid_trace :
+ ValidTrace C worker ports pub (m : BurstRAM.Word w) 0 mem rs ∧
+ Inputs order L demand (after mem (eventLog rs)) ∧
+ Preserved (C worker).params ports mem (after mem (eventLog rs)) := by
+ have step := (call_frame B order supply hp hq).choose_spec m M w hW L addr haddr demand hD fuel hcap
+ let cursor (j : ℕ) : BurstRAM.Word w := j
+ have active (j : ℕ) (hj : j < m) : cursor j < cursor m := by
+ change j%(2^w) < m%(2^w)
+ simpa only [Nat.mod_eq_of_lt (hj.trans hstop),Nat.mod_eq_of_lt hstop] using hj
+ apply OrdinalRun.validTrace C worker ports (program B order supply addr) fuel pub (cursor m) cursor m
+ (fun _ x => Inputs order L demand x) active le_rfl _ 0 bits mem rs (by omega) hin ready run
+ intro j hj x inv bs rep he
+ let i : Fin m := ⟨j,hj⟩
+ obtain ⟨inc,next,frame,_,_⟩ := step x inv i bs rep he
+ exact ⟨inc,next,fun u hu => frame u (apart i u hu)⟩
+
+/-- Public operands of a catalog slot whose instruction table is the fixed
+motif worker. The cast accounts for the slot's dependent arity. -/
+noncomputable def catalogWords (passEq : C worker = motifPass B order n) : Fin (C worker).params → BurstRAM.Word w :=
+ fun i => motifData B order supply w addr (i.cast (congrArg Schedule.Pass.params passEq))
+
+private theorem run_catalog {W : Schedule.Pass} (eq : W = motifPass B order n) (f : ℕ)
+ (mem : Memory w) (bs : List (List Bool)) :
+ runSegment (W.table.instantiate w (fun i => motifData B order supply w addr (i.cast (congrArg Schedule.Pass.params eq)))).program
+ f (some 0) mem bs = runSegment (program B order supply addr) f (some 0) mem bs := by
+ subst W
+ rfl
+
+variable {initial phases cap : ℕ} (plan : Online.Config C initial phases) (passEq : C worker = motifPass B order n)
+
+include haddr hD hW hcap hstop apart hin size run in
+/-- Execute the whole term pass under the online tag reader, including the
+closing transfer and arbitrary subsequent calendar calls. -/
+theorem online_segment (prepared : Schedule.Ready C worker ports (catalogWords B order supply C worker addr passEq)
+ (m : BurstRAM.Word w) mem) (tagFit : Online.N workers (initial+phases) ≤ 2^w)
+ (clock : fuel+3+4*((C worker).params+1)+2*Online.N workers (initial+phases)+5 ≤ cap)
+ (tail : List (List Bool)) :
+ let T := Online.program plan ports
+ let finalMem := after mem (eventLog rs)
+ runSegment T cap (some 0) mem (bits ++ [] :: tail) =
+ (runSegment T cap (some 0) (writeMemory finalMem ports.tag
+ (LiveStageLink.tagWord w (Online.calendarIndex workers (initial+phases)))) tail).map
+ (fun more => Online.workerRows C (initial+phases) ports worker mem rs ++
+ Online.stopReport C (initial+phases) ports worker finalMem :: more) := by
+ have valid := valid_trace B order supply hp hq C worker ports _ L addr haddr demand hD hW hcap hstop apart
+ mem hin prepared bits rs size run
+ have original := (run_catalog B order supply addr passEq fuel mem bits).trans run
+ have positive : 0 < fuel := by unfold budget at hcap; omega
+ exact Online.worker_segment plan ports worker _ (m : BurstRAM.Word w) 0 mem bits rs fuel cap positive
+ tagFit clock original valid.1 tail
+
+end CompressorRecords.TermWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermWorkerFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorTermWorkerFootprint.lean
new file mode 100644
index 0000000000..05fd2f8f14
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermWorkerFootprint.lean
@@ -0,0 +1,214 @@
+import OAI.Computability.VPVNP.CompressorTermWorkerScan
+import OAI.Computability.VPVNP.CompressorDemandFootprint
+import OAI.Computability.VPVNP.CompressorPayloadFootprint
+import OAI.Computability.VPVNP.CompressorRecordsOrdinalFootprint
+
+/-!
+# External addresses accessed by a native term-worker pass
+
+The two demand scans use the current input row. The payload reader probes the
+repetition count just stored in the second descriptor header. All stores land
+in the current descriptor. These event-level bounds let the same choices run
+after a change to the scheduler's control memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TermWorker.Footprint
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter SourceTransport
+open MotifGrid MotifBlocks MotifConversion MotifSelector TermRecordScan
+open scoped Fin.CommRing
+open private addr_words grid_words rep_words payload_words prelude_exec fixedPrefix head_left head_rep
+ payload_head outRange from OAI.Computability.VPVNP.CompressorTermWorker
+open private gridCode gridWords payloadCode payloadWords from OAI.Computability.VPVNP.CompressorTermWorkerRun
+
+variable {w d n g r k : ℕ}
+
+private abbrev Bounds (rd wr : ℕ → Prop) (es : List (Event w)) := Reads rd es ∧ Writes wr es
+
+private theorem append {rd wr : ℕ → Prop} {es fs : List (Event w)} (h : Bounds rd wr es)
+ (h' : Bounds rd wr fs) : Bounds rd wr (es ++ fs) :=
+ ⟨fun a v hv => (List.mem_append.mp hv).elim (h.1 a v) (h'.1 a v),
+ fun a v hv => (List.mem_append.mp hv).elim (h.2 a v) (h'.2 a v)⟩
+
+private theorem store {rd wr : ℕ → Prop} {a v : BurstRAM.Word w} (ha : wr a.val) :
+ Bounds rd wr [.write a v] := by
+ constructor <;> intro x y hx <;> simp only [List.mem_singleton,reduceCtorEq,Event.write.injEq] at hx
+ obtain ⟨rfl,rfl⟩ := hx
+ exact ha
+
+private theorem header {G : Flow 8 g} {R : Flow 8 r} (n : ℕ) (addr : Fin 4 → BurstRAM.Word w)
+ (x : Fin g → BurstRAM.Word w) (y : Fin r → BurstRAM.Word w) (z : Fin k → BurstRAM.Word w)
+ (j : BurstRAM.Word w) {m es out last} {rd wr : ℕ → Prop}
+ (grid : ∀ {rs mem gs reg post}, Flow.Exec x (source addr j) G rs mem gs reg post → Bounds rd wr gs)
+ (reps : ∀ {rs mem fs reg post}, Flow.Exec y (source addr j) R rs mem fs reg post → Bounds rd wr fs)
+ (first : wr (base addr j).val) (second : wr (base addr j+1).val)
+ (run : Flow.Exec (words addr x y z) j (headerCode n G R k) (fun _ => 0) m es out last) :
+ Bounds rd wr es ∧ out (headReg n 4) = base addr j+2 ∧ out (headReg n 5) = j+1 := by
+ cases run with | seq pre rest =>
+ cases rest with | seq search rest =>
+ cases rest with | seq save rest =>
+ cases rest with | seq repeatRow saveCount =>
+ let pub := words addr x y z
+ obtain ⟨h,hpre,hs,hd,h1,h2,hn⟩ := prelude_exec addr j m
+ have hp := (PrimedCounter.restrictExec (headReg n) addrPort pub prelude pre).1
+ rw [show pub ∘ addrPort = addr from addr_words ..] at hp
+ obtain ⟨e,bank,_⟩ := fixedPrefix hpre (by simp [choiceBits,List.replicate_succ]) hp
+ have H i := congrFun bank i
+ simp only [Function.comp_apply] at H
+ have ga (i : Fin 7) : headReg n i ∉ Set.range (gridReg n) := outRange fun _ => head_left
+ have ra (i : Fin 7) : headReg n i ∉ Set.range (repReg n) := outRange fun _ => head_rep
+ obtain ⟨hg,ag⟩ := Rebased.restrictExec (gridReg n) gridPort (headReg n 1) (ga 1) pub G search
+ have gH i := (ag _ (ga i)).trans (H i)
+ rw [show pub ∘ gridPort = x from grid_words ..,(H 1).trans hs] at hg
+ cases save with | line he =>
+ simp only [Op.effect,Option.some.injEq,Prod.mk.injEq] at he
+ obtain ⟨rfl,rfl,rfl⟩ := he
+ obtain ⟨hr,ar⟩ := Rebased.restrictExec (repReg n) repPort (headReg n 1) (ra 1) pub R repeatRow
+ have rH i := (ar _ (ra i)).trans (gH i)
+ rw [show pub ∘ repPort = y from rep_words ..,(gH 1).trans hs] at hr
+ cases saveCount with | line he =>
+ simp only [Op.effect,Option.some.injEq,Prod.mk.injEq] at he
+ obtain ⟨rfl,rfl,rfl⟩ := he
+ refine ⟨append ?_ (append (grid hg) (append (store ?_) (append (reps hr) (store ?_)))),
+ (rH 4).trans h2,(rH 5).trans hn⟩
+ · rw [e]
+ exact FlowFootprint.bounds_of_noProbes _ _ (by rfl)
+ · rwa [(gH 2).trans hd]
+ · rwa [(rH 3).trans h1]
+
+variable {K : Type*} [Field K] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock K a b P (realWidths p) (realWidths q) H H')
+variable (order : Fin d ≃ D) (supply : Fin n ≃ S)
+
+private theorem flow (addr : Fin 4 → BurstRAM.Word w) (j : BurstRAM.Word w) {mem es out last}
+ (hsrc : (source addr j).val+d ≤ 2^w) (hdst : (base addr j).val+2+n < 2^w)
+ (run : Flow.Exec (motifData B order supply w addr) j
+ (code (gridCode B order) (DemandPreparation.repetitionCall d) (payloadCode B n))
+ (fun _ => 0) mem es out last) :
+ out (headReg n 5) = j+1 ∧
+ Bounds (fun i => ((source addr j).val ≤ i ∧ i < (source addr j).val+d) ∨ i = (base addr j).val+1)
+ (fun i => (base addr j).val ≤ i ∧ i < (base addr j).val+2+n) es := by
+ let src := source addr j
+ let dst := base addr j
+ let rd := fun i => (src.val ≤ i ∧ i < src.val+d) ∨ i = dst.val+1
+ let wr := fun i => dst.val ≤ i ∧ i < dst.val+2+n
+ have dfit : dst.val+2+n < 2^w := hdst
+ have addOne : (dst+1).val = dst.val+1 := by
+ have one : 1 < 2^w := by omega
+ rw [Fin.val_add,show (1 : BurstRAM.Word w).val = 1 from Nat.mod_eq_of_lt one,Nat.mod_eq_of_lt (by omega)]
+ have addTwo : (dst+2).val = dst.val+2 := by
+ have two : 2 < 2^w := by omega
+ rw [Fin.val_add,show (2 : BurstRAM.Word w).val = 2 from Nat.mod_eq_of_lt two,Nat.mod_eq_of_lt (by omega)]
+ have narrow {fs : List (Event w)} (h : DemandFootprint.Footprint src d fs) : Bounds rd wr fs := by
+ obtain ⟨r,w⟩ := h.interval hsrc
+ exact ⟨fun a v hv => Or.inl (r a v hv),fun a v hv => (w a v hv).elim⟩
+ cases run with | seq head payload =>
+ obtain ⟨hh,arg,next⟩ := header n addr (gridWords B order w) (DemandPreparation.publicWords order p B.scale w)
+ (payloadWords B supply w) j (rd := rd) (wr := wr)
+ (fun hg => narrow (DemandFootprint.gridCode order p (DemandGridRAM.fixedRows B) _ src hg))
+ (fun hr => narrow (DemandFootprint.repetition _ src hr))
+ (show wr dst.val by dsimp [wr]; omega) (show wr (dst+1).val by dsimp [wr]; rw [addOne]; omega) head
+ have away (i : Fin 7) : headReg n i ∉ Set.range (payloadReg n) := outRange fun _ => payload_head
+ let pub := words addr (gridWords B order w) (DemandPreparation.publicWords order p B.scale w)
+ (payloadWords B supply w)
+ obtain ⟨hp,unmoved⟩ := Rebased.restrictExec (payloadReg n) payloadPort (headReg n 4) (away 4) pub
+ (payloadCode B n) payload
+ rw [show pub ∘ payloadPort = payloadWords B supply w from payload_words ..,arg] at hp
+ obtain ⟨read,write⟩ := PayloadFootprint.storedCall _ (dst+2) (by rw [addTwo]; exact dfit.le) hp
+ refine ⟨(unmoved _ (away 5)).trans next,append hh ⟨?_,?_⟩⟩
+ · intro a v hv
+ exact Or.inr ((read a v hv).trans ((congrArg Fin.val (show dst+2-1 = dst+1 by ring)).trans addOne))
+ · intro a v hv
+ obtain ⟨lo,hi⟩ := write a v hv
+ rw [addTwo] at lo hi
+ exact ⟨by omega,hi⟩
+
+/-- At any successful call, even with an arbitrary tape and fuel, the worker
+advances one ordinal. It reads its own demand row and repetition header and
+writes exclusively in the term row. -/
+theorem call (addr : Fin 4 → BurstRAM.Word w) (j : BurstRAM.Word w) (mem : Memory w)
+ (cap : ℕ) (bits : List Bool) (rep : Report w) (hsrc : (source addr j).val+d ≤ 2^w)
+ (hdst : (base addr j).val+2+n < 2^w)
+ (run : execute (program B order supply addr) cap ((program B order supply addr).start j) mem bits = some rep) :
+ rep.result = some (j+1) ∧
+ Reads (fun i => ((source addr j).val ≤ i ∧ i < (source addr j).val+d) ∨ i = (base addr j).val+1) rep.events ∧
+ Writes (fun i => (base addr j).val ≤ i ∧ i < (base addr j).val+2+n) rep.events := by
+ obtain ⟨_,_,he,result,_,_⟩ := (Flow.template_execute_iff
+ (code (gridCode B order) (DemandPreparation.repetitionCall d) (payloadCode B n)) (some (headReg n 5))
+ (motifData B order supply w addr) j (fun _ => 0) (fun _ => 0) mem cap bits rep).mp run
+ obtain ⟨inc,fp⟩ := flow B order supply addr j hsrc hdst he
+ exact ⟨result.trans (congrArg some inc),fp⟩
+
+variable {m : ℕ}
+
+/-- The footprints of any contiguous segment are contained in the union of
+its rows. The predicates can be widened to fit the scheduler's memory layout. -/
+theorem segment (L : Layout m d n w) (addr : Fin 4 → BurstRAM.Word w) (ha : Addresses L addr)
+ (rd wr : ℕ → Prop)
+ (demand : ∀ i x, (L.source i).val ≤ x → x < (L.source i).val+d → rd x)
+ (header : ∀ i, rd ((L.base i).val+1))
+ (term : ∀ i x, (L.base i).val ≤ x → x < (L.base i).val+2+n → wr x)
+ (start cap : ℕ) (mem : Memory w) (bs : List (List Bool)) (rs : List (Report w))
+ (size : start+bs.length ≤ m)
+ (run : runSegment (program B order supply addr) cap (some (start : BurstRAM.Word w)) mem bs = some rs) :
+ Reads rd (eventLog rs) ∧ Writes wr (eventLog rs) := by
+ apply OrdinalRun.footprint (program B order supply addr) cap (fun j => (j : BurstRAM.Word w)) m
+ (fun _ _ => True) rd wr _ start bs mem rs size trivial run
+ intro j hj mem _ bits rep he
+ let i : Fin m := ⟨j,hj⟩
+ obtain ⟨hs,ht⟩ := ha i
+ have fitS := hs.symm ▸ L.sourceFits i
+ have fitT := ht.symm ▸ L.termFits i
+ obtain ⟨inc,reads,writes⟩ := call B order supply addr (i.val : BurstRAM.Word w) mem cap bits rep fitS fitT he
+ rw [hs,ht] at reads
+ rw [ht] at writes
+ refine ⟨by simpa [i,Nat.cast_add] using inc,trivial,fun a v hv => ?_,fun a v hv => ?_⟩
+ · rcases reads a v hv with ⟨lo,hi⟩ | eq
+ · exact demand i _ lo hi
+ · exact eq ▸ header i
+ · obtain ⟨lo,hi⟩ := writes a v hv
+ exact term i _ lo hi
+
+/-- With the paper's strided layout, every successful segment reads between
+the first demand cell and the end of the descriptor arena. Its writes are
+confined to that arena, including for a partial pass starting at a later row. -/
+theorem strided_segment (src dst srcStride termStride : ℕ) (hd : d ≤ srcStride) (hn : 2+n ≤ termStride)
+ (sep : src+m*srcStride ≤ dst) (fit : dst+m*termStride < 2^w)
+ (start cap : ℕ) (mem : Memory w) (bs : List (List Bool)) (rs : List (Report w))
+ (size : start+bs.length ≤ m)
+ (run : runSegment (program B order supply ![src,srcStride,dst,termStride]) cap
+ (some (start : BurstRAM.Word w)) mem bs = some rs) :
+ Reads (fun x => src ≤ x ∧ x < dst+m*termStride) (eventLog rs) ∧
+ Writes (fun x => dst ≤ x ∧ x < dst+m*termStride) (eventLog rs) := by
+ let L := strided m d n w src dst srcStride termStride hd hn sep fit
+ have stops (i : Fin m) (stride : ℕ) : i.val*stride+stride ≤ m*stride := by
+ simpa only [Nat.succ_mul] using Nat.mul_le_mul_right stride (Nat.succ_le_of_lt i.isLt)
+ have s (i : Fin m) : (L.source i).val = src+i.val*srcStride := by
+ exact Nat.mod_eq_of_lt (by have := stops i srcStride; omega)
+ have t (i : Fin m) : (L.base i).val = dst+i.val*termStride := by
+ exact Nat.mod_eq_of_lt (by have := stops i termStride; omega)
+ apply segment B order supply L _ (addresses_strided src dst srcStride termStride hd hn sep fit)
+ _ _ _ _ _ start cap mem bs rs size run
+ · intro i x lo hi
+ rw [s] at lo hi
+ have := stops i srcStride
+ exact ⟨by omega,by omega⟩
+ · intro i
+ rw [t]
+ have := stops i termStride
+ exact ⟨by omega,by omega⟩
+ · intro i x lo hi
+ rw [t] at lo hi
+ have := stops i termStride
+ exact ⟨by omega,by omega⟩
+
+end CompressorRecords.TermWorker.Footprint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermWorkerFuel.lean b/lean/OAI/Computability/VPVNP/CompressorTermWorkerFuel.lean
new file mode 100644
index 0000000000..3272fc6393
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermWorkerFuel.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.CompressorPayloadCall
+import OAI.Computability.VPVNP.PrimedCounterKernel
+import OAI.Computability.VPVNP.LiveEvaluatorRAM
+
+/-!
+# Execution time of the stored motif choice
+
+A successful stored payload call fits the published fuel bound from any register
+file, memory and public input. The word reader runs its loop once per bit.
+The remaining instructions are straight-line code apart from the dispatch on
+zero repetitions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PayloadWrite
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open MotifChoiceRAM LiveEvaluatorRAM
+
+variable {n w : ℕ}
+
+private theorem guess_exec_length {r k : ℕ} (reg : Fin 3 ↪ Fin r)
+ {pub : Fin k → Word w} {st rs m es out mem}
+ (h : Flow.Exec pub st (PrimedCounter.GuessWord.flow reg) rs m es out mem) :
+ es.length ≤ 4*w+4 := by
+ let o : Output w r := ⟨es, out, mem, []⟩
+ have hg := (guess_kernel_exec (w := w) (k := k) reg (bits := choiceBits es) (o := o)).mpr
+ ⟨h, (List.append_nil _).symm⟩
+ exact (guess_refine reg).bounded hg
+
+private theorem coordinate_exec_length (i : Fin n) {pub : Fin n → Word w} {st rs m es out mem}
+ (h : Flow.Exec pub st (coordinate i) rs m es out mem) : es.length ≤ 4*w+10 := by
+ cases h with
+ | seq guess compute =>
+ have hg := guess_exec_length _ guess
+ have hc := length_le_of_loopFree compute rfl
+ change _ ≤ 6 at hc
+ rw [List.length_append]
+ omega
+
+private theorem scan_exec_length (is : List (Fin n)) {pub : Fin n → Word w} {st rs m es out mem}
+ (h : Flow.Exec pub st (scan is) rs m es out mem) : es.length ≤ is.length*(4*w+10)+1 := by
+ induction is generalizing rs m es with
+ | nil =>
+ change Flow.Exec _ _ (.line _) _ _ _ _ _ at h
+ cases h
+ simp
+ | cons i is ih =>
+ cases h with
+ | seq coord rest =>
+ have hc := coordinate_exec_length i coord
+ have hr := ih rest
+ rw [List.length_append, List.length_cons, Nat.succ_mul]
+ omega
+
+private theorem prepareBounds_loopFree (d factor denominator : ℕ) :
+ loopFree (prepareBounds d factor denominator) = true := by
+ have digits {r k : ℕ} (dst src : Fin r) (bs : List Bool) :
+ loopFree (scaleDigits (k := k) dst src bs) = true := by
+ induction bs with
+ | nil => rfl
+ | cons b bs ih => cases b <;> simp [scaleDigits, loopFree, ih]
+ simp [prepareBounds, scaleFixed, loopFree, digits]
+
+private theorem unitSlots_loopFree {n : ℕ} (is : List (Fin n)) :
+ loopFree (unitSlots is) = true := by
+ induction is with
+ | nil => rfl
+ | cons i is ih => simp [unitSlots, loopFree, ih]
+
+private theorem unitSlots_length {n : ℕ} (is : List (Fin n)) :
+ (unitSlots is).length = is.length + 1 := by
+ induction is with
+ | nil => rfl
+ | cons i is ih => simp [unitSlots, Flow.length, ih]; omega
+
+private theorem writePayload_loopFree (n : ℕ) : loopFree (writePayload n) = true := by
+ have slots (is : List (Fin n)) : loopFree (writeSlots is) = true := by
+ induction is with
+ | nil => rfl
+ | cons i is ih => simp [writeSlots, loopFree, ih]
+ simp [writePayload, loopFree, slots]
+
+private theorem writePayload_length (n : ℕ) : (writePayload n).length = 2*n+3 := by
+ have slots (is : List (Fin n)) : (writeSlots is).length = 2*is.length+1 := by
+ induction is with
+ | nil => rfl
+ | cons i is ih => simp [writeSlots, Flow.length, ih]; omega
+ simp [writePayload, Flow.length, slots]; omega
+
+private theorem choosePayload_exec_length {pub : Fin n → Word w} {st rs m es out mem}
+ (h : Flow.Exec pub st (choosePayload n) rs m es out mem) : es.length ≤ n*(4*w+10)+2 := by
+ cases h with
+ | ifEqYes _ unit =>
+ have hu := length_le_of_loopFree unit (unitSlots_loopFree _)
+ rw [unitSlots_length, List.length_finRange] at hu
+ have hn := Nat.le_mul_of_pos_right n (show 0 < 4*w+10 by omega)
+ rw [List.length_cons]
+ omega
+ | ifEqNo _ scan =>
+ have hs := scan_exec_length _ scan
+ rw [List.length_finRange] at hs
+ rw [List.length_cons]
+ omega
+
+open MotifGrid MotifBlocks MotifConversion MotifSelector
+
+variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+
+/-- Every finite execution of the stored choice fits the standalone call's fuel,
+including the fuel unit needed at its accept continuation. -/
+theorem storedCall_exec_length_lt (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+ {pub : Fin n → BurstRAM.Word w} {base rs m es out mem}
+ (run : Flow.Exec pub base (storedCall n (B.scale*B.radius.num.natAbs) (MotifAdmission.denominator q))
+ rs m es out mem) : es.length < storedFuel B n w := by
+ cases run with
+ | seq setup store =>
+ cases setup with
+ | seq load prep =>
+ cases store with
+ | seq choose write =>
+ have hl := length_le_of_loopFree load rfl
+ change _ ≤ 4 at hl
+ have hp := length_le_of_loopFree prep (prepareBounds_loopFree ..)
+ have hc := choosePayload_exec_length choose
+ have hw := length_le_of_loopFree write (writePayload_loopFree _)
+ rw [writePayload_length] at hw
+ simp only [List.length_append]
+ change _ < (4+(prepareBounds n (B.scale*B.radius.num.natAbs) (MotifAdmission.denominator q)).length) +
+ (n*(4*w+10)+3+(2*n+3))
+ omega
+
+end CompressorRecords.PayloadWrite
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermWorkerRecipe.lean b/lean/OAI/Computability/VPVNP/CompressorTermWorkerRecipe.lean
new file mode 100644
index 0000000000..ed0f6f8027
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermWorkerRecipe.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.CompressorTermWorkerRun
+import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe
+
+/-!
+# Fixed planner operands for the motif worker
+
+The four physical address formulas are supplied by the level planner. Every
+remaining operand is the reduction of a fixed natural coefficient. The word
+reader determines the width by doubling a one-bit mask until it vanishes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TermWorker
+
+open BurstRAM PhaseRecipe MotifGrid MotifBlocks MotifConversion MotifSelector
+
+variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+variable {d n t w : ℕ}
+
+private def demandLiterals (order : Fin d ≃ D) (p : D → ℚ) (scale : ℕ) : Fin (d+1) → Expr :=
+ Fin.lastCases (.lit (scale^2 * MotifAdmission.denominator p))
+ (fun i => .lit (MotifAdmission.weight p (order i)))
+
+private def gridLiterals (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ)
+ (x : Fin (t*d*3)) : Expr :=
+ let (ji,f) := finProdFinEquiv.symm x
+ let (j,i) := finProdFinEquiv.symm ji
+ let u := rows j (order i)
+ .lit (if f = 0 then i.val else if f = 1 then u.den^2 * MotifAdmission.denominator p else u.num.natAbs^2)
+
+private theorem evalDemand (order : Fin d ≃ D) (p : D → ℚ) (scale : ℕ) (pub : Fin 5 → BurstRAM.Word w)
+ (state : BurstRAM.Word w) (m : Memory w) (i : Fin (d+1)) :
+ (demandLiterals order p scale i).eval pub state m = DemandPreparation.publicWords order p scale w i := by
+ cases i using Fin.lastCases <;> simp [demandLiterals,DemandPreparation.publicWords,Expr.eval]
+
+private theorem evalGrid (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ)
+ (pub : Fin 5 → BurstRAM.Word w) (state : BurstRAM.Word w) (m : Memory w) (i : Fin (t*d*3)) :
+ (gridLiterals order p rows i).eval pub state m = GridRAM.coefficients order p rows i := by
+ unfold gridLiterals GridRAM.coefficients
+ dsimp only [Expr.eval]
+ split <;> first | rfl | (split <;> rfl)
+
+/-- Planner formulas in exactly the worker's public-operand order. -/
+noncomputable def motifExprs (order : Fin d ≃ D) (supply : Fin n ≃ S) (head : Fin 4 → Expr) :
+ Fin (motifPass B order n).params → Expr :=
+ Fin.append head <| Fin.append
+ (Fin.append (demandLiterals order p 1) (gridLiterals order p (DemandGridRAM.fixedRows B))) <|
+ Fin.append (demandLiterals order p B.scale)
+ (fun i => .lit (MotifAdmission.weight q (supply i) * B.radius.den^2))
+
+theorem eval_motifExprs (order : Fin d ≃ D) (supply : Fin n ≃ S) (head : Fin 4 → Expr)
+ (pub : Fin 5 → BurstRAM.Word w) (state : BurstRAM.Word w) (m : Memory w) :
+ (fun i => (motifExprs B order supply head i).eval pub state m) =
+ motifData B order supply w (fun j => (head j).eval pub state m) := by
+ funext i
+ change ((Fin.append head (Fin.append (Fin.append (demandLiterals order p 1)
+ (gridLiterals order p (DemandGridRAM.fixedRows B))) (Fin.append (demandLiterals order p B.scale)
+ (fun i => Expr.lit (MotifAdmission.weight q (supply i) * B.radius.den^2))))) i).eval pub state m =
+ (Fin.append (fun j => (head j).eval pub state m)
+ (Fin.append (Fin.append (DemandPreparation.publicWords order p 1 w)
+ (GridRAM.coefficients order p (DemandGridRAM.fixedRows B)))
+ (Fin.append (DemandPreparation.publicWords order p B.scale w)
+ (fun j => Fin.ofNat (2^w) (MotifAdmission.weight q (supply j) * B.radius.den^2))))) i
+ cases i using Fin.addCases with
+ | left i => simp
+ | right i =>
+ simp only [Fin.append_right]
+ cases i using Fin.addCases with
+ | left i =>
+ simp only [Fin.append_left]
+ cases i using Fin.addCases <;> simp [evalDemand,evalGrid]
+ | right i =>
+ simp only [Fin.append_right]
+ cases i using Fin.addCases <;> simp [evalDemand,Expr.eval]
+
+end CompressorRecords.TermWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermWorkerRun.lean b/lean/OAI/Computability/VPVNP/CompressorTermWorkerRun.lean
new file mode 100644
index 0000000000..17b8da44b7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermWorkerRun.lean
@@ -0,0 +1,227 @@
+import OAI.Computability.VPVNP.CompressorTermWorker
+import OAI.Computability.VPVNP.CompressorTermWorkerFuel
+
+/-!
+# Native execution of a complete term-descriptor visit
+
+The strided worker uses one fixed pass table for all motif ordinals.
+Its only nondeterministic instructions read the selected outer vector.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TermWorker
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter
+open MotifGrid MotifBlocks MotifConversion MotifSelector
+open scoped Fin.CommRing
+
+variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+variable {d n w : ℕ}
+
+private noncomputable abbrev gridCode (order : Fin d ≃ D) := DemandGridRAM.code order (DemandGridRAM.fixedRows B)
+private noncomputable abbrev gridWords (order : Fin d ≃ D) (w : ℕ) :=
+ (DemandGridRAM.machine order p (DemandGridRAM.fixedRows B) w).publicData
+
+private abbrev payloadCode (n : ℕ) :=
+ PayloadWrite.storedCall n (B.scale*B.radius.num.natAbs) (MotifAdmission.denominator q)
+private abbrev payloadWords (supply : Fin n ≃ S) (w : ℕ) := (PayloadWrite.storedMachine B supply w).publicData
+
+private theorem components (order : Fin d ≃ D) (src dst row u : BurstRAM.Word w) (mem : Memory w)
+ (fuel : ℕ) (gs rs : List (Event w))
+ (h : TermRecord.headers B order src dst mem fuel = some
+ [⟨gs,some row⟩,TermRecord.saved dst src row,⟨rs,some u⟩,TermRecord.saved (dst+1) (dst+2) u])
+ (hgm : after mem gs = mem)
+ (hrm : after (writeMemory mem dst row) rs = writeMemory mem dst row) :
+ ∃ G R, Flow.Exec (gridWords B order w) src (gridCode B order) (fun _ => 0) mem gs G mem ∧
+ G 1 = row ∧ Flow.Exec (DemandPreparation.publicWords order p B.scale w) src
+ (DemandPreparation.repetitionCall d) (fun _ => 0) (writeMemory mem dst row) rs R (writeMemory mem dst row) ∧
+ R 2 = u := by
+ let grid := DemandGridRAM.machine order p (DemandGridRAM.fixedRows B) w
+ let gf := 6*d+(11*d+4)*B.grid.demands.toList.length+8
+ let reps := DemandPreparation.repetitionMachine order p B.scale w
+ unfold TermRecord.headers at h
+ change (execute grid.program gf (grid.program.start src) mem []).bind _ = _ at h
+ cases hg : execute grid.program gf (grid.program.start src) mem [] with
+ | none => simp [hg] at h
+ | some gr =>
+ cases gr with | mk ge grow =>
+ cases grow with
+ | none => simp [hg,bind] at h
+ | some v =>
+ rw [hg] at h
+ simp only [Option.bind_some,bind] at h
+ rw [(TermRecord.save_native dst src v _).1] at h
+ simp only [Option.bind_some,TermRecord.saved] at h
+ let mid := writeMemory (after mem ge) dst v
+ change (execute reps.program fuel (reps.program.start src) mid []).bind _ = _ at h
+ cases hr : execute reps.program fuel (reps.program.start src) mid [] with
+ | none => simp [hr] at h
+ | some rr =>
+ cases rr with | mk re ru =>
+ cases ru with
+ | none => simp [hr] at h
+ | some u' =>
+ rw [hr] at h
+ simp only [Option.bind_some] at h
+ rw [(TermRecord.save_native (dst+1) (dst+2) u' _).1] at h
+ simp only [Option.bind_some,pure,Option.some.injEq,List.cons.injEq,Report.mk.injEq] at h
+ obtain ⟨⟨rfl,hv⟩,_,⟨rfl,hu⟩,_⟩ := h
+ cases hv
+ cases hu
+ dsimp only [mid] at hr
+ rw [hgm] at hr
+ obtain ⟨G,mG,eG,gval,_,_⟩ := (Flow.template_execute_iff (gridCode B order) (some 1) (gridWords B order w)
+ src (fun _ => 0) (fun _ => 0) mem gf [] ⟨ge,some row⟩).mp hg
+ obtain ⟨R,mR,eR,rval,_,_⟩ := (Flow.template_execute_iff (DemandPreparation.repetitionCall d) (some 2)
+ (DemandPreparation.publicWords order p B.scale w) src (fun _ => 0) (fun _ => 0)
+ (writeMemory mem dst row) fuel [] ⟨re,some u⟩).mp hr
+ rw [← Call.exec_memory eG,hgm] at eG
+ rw [← Call.exec_memory eR,hrm] at eR
+ exact ⟨G,R,eG,(Option.some.inj gval).symm,eR,(Option.some.inj rval).symm⟩
+
+/-- The same finite instruction table handles every row at every machine width. -/
+noncomputable def motifPass (order : Fin d ≃ D) (n : ℕ) : Schedule.Pass :=
+ pass (gridCode B order) (DemandPreparation.repetitionCall d) (payloadCode B n)
+
+/-- Assemble the address operands and grid, repetition, and payload constants for the selected
+motif template. -/
+noncomputable def motifData (order : Fin d ≃ D) (supply : Fin n ≃ S) (w : ℕ)
+ (addr : Fin 4 → BurstRAM.Word w) : Fin (motifPass B order n).params → BurstRAM.Word w :=
+ words addr (gridWords B order w) (DemandPreparation.publicWords order p B.scale w) (payloadWords B supply w)
+
+/-- Instruction allowance for one fused term call at the given word width and maximum demand
+width. -/
+noncomputable def budget (d n w M : ℕ) :=
+ 15 + (6*d+(11*d+4)*B.grid.demands.toList.length+8) +
+ (6*d+7*((∑ i, MotifAdmission.weight p i).size+2*Nat.clog 2 (M+1))+10) + PayloadWrite.storedFuel B n w
+
+/-- For a fixed motif, the instruction cap grows linearly with machine word width. -/
+theorem budget_linear (d n : ℕ) : ∃ A : ℕ, ∀ w M, M < 2^w →
+ budget B d n w M ≤ A + (4*n+14)*w := by
+ let c := B.grid.demands.toList.length
+ let weights := (∑ i, MotifAdmission.weight p i).size
+ refine ⟨15 + 6*d+(11*d+4)*c+8 + 6*d+7*weights+10 + n*12 +
+ 2*(B.scale*B.radius.num.natAbs).size + 4*(MotifAdmission.denominator q).size + 20,fun w M fit => ?_⟩
+ have hlog : Nat.clog 2 (M+1) ≤ w := Nat.clog_le_of_le_pow fit
+ have hp := PayloadWrite.storedFuel_le B n w
+ unfold budget
+ simp only [c,weights,Nat.mul_add,Nat.add_mul,Nat.mul_assoc] at *
+ rw [show n*(4*w) = 4*(n*w) by ring] at hp
+ omega
+
+/-- Row arithmetic in a strided scan agrees with the natural addresses reduced to words. -/
+theorem strided_addresses (w src dst srcStride dstStride i : ℕ) :
+ let addr : Fin 4 → BurstRAM.Word w := ![src,srcStride,dst,dstStride]
+ source addr (i : BurstRAM.Word w) = Fin.ofNat _ (src+i*srcStride) ∧
+ base addr (i : BurstRAM.Word w) = Fin.ofNat _ (dst+i*dstStride) := by
+ dsimp only
+ change ((i : BurstRAM.Word w) * srcStride + src) = ((src+i*srcStride : ℕ) : BurstRAM.Word w) ∧
+ ((i : BurstRAM.Word w) * dstStride + dst) = ((dst+i*dstStride : ℕ) : BurstRAM.Word w)
+ simp [Nat.cast_add,Nat.cast_mul,add_comm]
+
+/-- Every admitted tape returns the successor ordinal and the complete term
+record. Conversely, at every sufficient cap, successful native calls consume
+exactly the canonical outer-choice tapes. -/
+theorem native (order : Fin d ≃ D) (supply : Fin n ≃ S)
+ (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
+ ∃ K : ℕ, ∀ M w, K+4*Nat.clog 2 (M+1) ≤ w → ∀ (addr : Fin 4 → BurstRAM.Word w)
+ (j : BurstRAM.Word w) (mem : Memory w),
+ let src := source addr j
+ let dst := base addr j
+ let demand := DemandPreparation.demandAt order src mem
+ src.val+d ≤ 2^w → dst.val+2+n < 2^w → (src.val+d ≤ dst.val ∨ dst.val+2+n ≤ src.val) →
+ (∀ e, demand e ≤ M) →
+ let T := ((motifPass B order n).table.instantiate w (motifData B order supply w addr)).program
+ ∃ (hw : outerCap B demand < 2^w) (row u : BurstRAM.Word w),
+ B.grid.demands.toList[row.val]? = some (demandGrid B hp demand).val ∧ u.val = repetitions B demand ∧
+ ∀ cap, budget B d n w M ≤ cap →
+ (∀ bs, (execute T cap (T.start j) mem bs).isSome ↔
+ ∃ v, (outerReader B supply hq demand w hw).read bs = some (v,[])) ∧
+ ∀ v, ∃ es, execute T cap (T.start j) mem ((outerReader B supply hq demand w hw).encode v) =
+ some ⟨es,some (j+1)⟩ ∧ after mem es = TermRecord.recordMemory mem dst row u supply v.val ∧
+ choiceBits es = (outerReader B supply hq demand w hw).encode v ∧
+ countProbes es ≤ d+B.grid.demands.toList.length*d+d+n+3 ∧ es.length < budget B d n w M := by
+ obtain ⟨kh,headers⟩ := TermRecord.headers_native B order hp
+ obtain ⟨kv,payload⟩ := PayloadWrite.stored_outer_paths B supply hq
+ refine ⟨max kh kv,fun M w hW addr j mem hsrc hdst hsep hD => ?_⟩
+ have hk := le_max_left kh kv
+ have hk' := le_max_right kh kv
+ let src := source addr j
+ let dst := base addr j
+ let demand := DemandPreparation.demandAt order src mem
+ let gf := 6*d+(11*d+4)*B.grid.demands.toList.length+8
+ let rf := 6*d+7*((∑ i, MotifAdmission.weight p i).size+2*Nat.clog 2 (M+1))+10
+ obtain ⟨row,u,gs,rs,hrow,hu,hh,hgm,hrm,hgb,hrb,hgp,hrp,hgl,hrl⟩ :=
+ headers M w (by omega) src dst mem hsrc (by dsimp only [src,dst] at *; omega) hD
+ obtain ⟨G,R,hG,G₁,hR,R₂⟩ := components B order src dst row u mem rf gs rs hh hgm hrm
+ let middle := TermRecord.withHeaders mem dst row u
+ have payloadAddr : (dst+2).val = dst.val+2 := by
+ have hfit : dst.val+2+n < 2^w := hdst
+ have two : 2 < 2^w := by omega
+ rw [Fin.val_add,show (2 : BurstRAM.Word w).val = 2 from Nat.mod_eq_of_lt two,Nat.mod_eq_of_lt (by omega)]
+ have hread : (middle (dst+2-1).val).val = repetitions B demand := by
+ rw [show dst+2-1 = dst+1 by ring]
+ simp [middle,TermRecord.withHeaders,writeMemory,hu,demand]
+ obtain ⟨hw,hs,paths⟩ := payload M demand hD w (by omega) (dst+2) middle
+ (by rw [payloadAddr]; change dst.val+2+n < 2^w at hdst; omega) hread
+ let pre := headerLog dst row u gs rs
+ let T := ((motifPass B order n).table.instantiate w (motifData B order supply w addr)).program
+ have hdr (cap bs rep) : execute T cap (T.start j) mem bs = some rep ↔
+ ∃ vs V mv, Flow.Exec (payloadWords B supply w) (dst+2) (payloadCode B n) (fun _ => 0) middle vs V mv ∧
+ rep = ⟨pre++vs,some (j+1)⟩ ∧ pre.length+vs.length < cap ∧ choiceBits vs = bs := by
+ have hr' := hR
+ rw [← G₁] at hr'
+ have he := execute_iff (payloadCode B n) addr (gridWords B order w) (DemandPreparation.publicWords order p B.scale w)
+ (payloadWords B supply w) j mem mem (writeMemory mem dst (G 1)) gs rs G R hG hgb hr' hrb cap bs rep
+ dsimp only at he
+ rw [G₁,R₂] at he
+ exact he
+ let pf := PayloadWrite.storedFuel B n w
+ let Q := (PayloadWrite.storedMachine B supply w).program
+ have part (bs : List Bool) (r : Report w) : execute Q pf (Q.start (dst+2)) middle bs = some r ↔
+ ∃ V mv, Flow.Exec (payloadWords B supply w) (dst+2) (payloadCode B n) (fun _ => 0) middle r.events V mv ∧
+ r.result = none ∧ r.events.length < pf ∧ choiceBits r.events = bs :=
+ Flow.template_execute_iff (payloadCode B n) none (payloadWords B supply w) (dst+2) (fun _ => 0) (fun _ => 0)
+ middle pf bs r
+ have len : pre.length = 15+gs.length+rs.length := by simp [pre,headerLog]; omega
+ have enough (vs : List (Event w)) (hlt : vs.length < pf) : pre.length+vs.length < budget B d n w M := by
+ rw [len]
+ change gs.length < gf at hgl
+ change rs.length < rf at hrl
+ change _ < 15+gf+rf+pf
+ omega
+ refine ⟨hw,row,u,hrow,hu,fun cap hcap => ⟨fun bs => ?_,fun v => ?_⟩⟩
+ · rw [← hs bs,Option.isSome_iff_exists,Option.isSome_iff_exists]
+ constructor
+ · rintro ⟨r,he⟩
+ obtain ⟨vs,V,mv,hv,_,_,hb⟩ := (hdr cap bs r).mp he
+ exact ⟨⟨vs,none⟩,(part bs _).mpr ⟨V,mv,hv,rfl,PayloadWrite.storedCall_exec_length_lt B hv,hb⟩⟩
+ · rintro ⟨r,he⟩
+ obtain ⟨V,mv,hv,_,hlt,hb⟩ := (part bs r).mp he
+ exact ⟨_,(hdr cap bs _).mpr ⟨r.events,V,mv,hv,rfl,(enough _ hlt).trans_le hcap,hb⟩⟩
+ · obtain ⟨vs,run,hm,hp',hv,hb⟩ := paths v
+ obtain ⟨V,mv,he,_,_,_⟩ := (part _ _).mp run
+ have fits := enough vs hv
+ refine ⟨pre++vs,(hdr _ _ _).mpr ⟨vs,V,mv,he,rfl,fits.trans_le hcap,hb⟩,?_,?_,?_,?_⟩
+ · have first : after mem pre = middle := by
+ simp only [pre,headerLog,after,List.foldl_append]
+ change after (writeMemory (after (writeMemory (after mem gs) dst row) rs) (dst+1) u) [] = _
+ rw [hgm,hrm]; rfl
+ rw [show after mem (pre++vs) = after (after mem pre) vs from List.foldl_append,first]; exact hm
+ · simp [pre,headerLog,Flow.choiceBits_append,hgb,hrb,hb,choiceBits,List.replicate_succ]
+ rfl
+ · simp [pre,headerLog,DemandPreparation.probes_append,hrp,hp',countProbes,List.replicate_succ]
+ simp only [Finset.length_toList] at hgp
+ omega
+ · rwa [List.length_append]
+
+end CompressorRecords.TermWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTermWorkerScan.lean b/lean/OAI/Computability/VPVNP/CompressorTermWorkerScan.lean
new file mode 100644
index 0000000000..ba50175f39
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTermWorkerScan.lean
@@ -0,0 +1,302 @@
+import OAI.Computability.VPVNP.CompressorTermWorkerRun
+import OAI.Computability.VPVNP.CompressorTermRecordScan
+
+/-!
+# A complete motif pass of the fixed native program
+
+The native RAM starts at ordinal zero and returns the successor on every
+admitted row. Its execution on a list of row tapes has the same final memory
+as the five-call descriptor scan. Disjoint term rows preserve all demand
+inputs as well as the descriptors already written.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TermWorker
+
+open BurstRAM PrimedInputRAM TermRecordScan MotifGrid MotifBlocks MotifConversion MotifSelector
+open scoped Fin.CommRing
+
+variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+variable {m d n w : ℕ} (order : Fin d ≃ D) (supply : Fin n ≃ S)
+
+/-- Public address operands describe every ordinal in the supplied layout. -/
+def Addresses (L : Layout m d n w) (addr : Fin 4 → BurstRAM.Word w) : Prop :=
+ ∀ i, source addr (i.val : BurstRAM.Word w) = L.source i ∧ base addr (i.val : BurstRAM.Word w) = L.base i
+
+theorem addresses_strided (src dst srcStride termStride : ℕ) (hd : d ≤ srcStride) (hn : 2+n ≤ termStride)
+ (hsep : src+m*srcStride ≤ dst) (hfit : dst+m*termStride < 2^w) :
+ Addresses (strided m d n w src dst srcStride termStride hd hn hsep hfit)
+ ![src,srcStride,dst,termStride] := fun i => strided_addresses w src dst srcStride termStride i.val
+
+private theorem row_unique {α : Type*} {xs : List α} (nodup : xs.Nodup) {i j : ℕ} {x : α}
+ (hi : xs[i]? = some x) (hj : xs[j]? = some x) : i = j := by
+ obtain ⟨hi,ei⟩ := List.getElem?_eq_some_iff.mp hi
+ obtain ⟨hj,ej⟩ := List.getElem?_eq_some_iff.mp hj
+ exact nodup.getElem_inj_iff.mp (ei.trans ej.symm)
+
+/-- Native strided motif program instantiated with the grid, column orders, and four address
+operands. -/
+noncomputable abbrev program (addr : Fin 4 → BurstRAM.Word w) :=
+ ((motifPass B order n).table.instantiate w (motifData B order supply w addr)).program
+
+private structure RowEffect (L : Layout m d n w) (demand : Fin m → D → ℕ) (M : ℕ) (i : Fin m)
+ (initial : Memory w) (fresh : Report w) (old : List (Report w)) : Prop where
+ cursor : fresh.result = some ((i.val+1 : ℕ) : BurstRAM.Word w)
+ memory : after initial fresh.events = after initial (eventLog old)
+ inputs : Inputs order L demand (after initial fresh.events)
+ frame : ∀ x, L.Outside i x → after initial fresh.events x = initial x
+ probes : fresh.probes ≤ probesPerRow B d n
+ steps : fresh.events.length < budget B d n w M
+
+private def Ready (L : Layout m d n w) (addr : Fin 4 → BurstRAM.Word w) (demand : Fin m → D → ℕ) (M cap : ℕ) :=
+ ∀ mem, Inputs order L demand mem → ∀ (i : Fin m) (bits : List Bool),
+ let T := program B order supply addr
+ Option.Rel (RowEffect B order L demand M i mem)
+ (execute T cap (T.start (i.val : BurstRAM.Word w)) mem bits)
+ (TermRecord.run B order supply (L.source i) (L.base i) mem (prepFuel (p := p) d M) bits)
+
+private theorem row_ready (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
+ ∃ K : ℕ, ∀ m M w, K+4*Nat.clog 2 (M+1) ≤ w → ∀ (L : Layout m d n w) addr,
+ Addresses L addr → ∀ (demand : Fin m → D → ℕ), (∀ i e, demand i e ≤ M) →
+ ∀ cap, budget B d n w M ≤ cap → Ready B order supply L addr demand M cap := by
+ obtain ⟨kn,native⟩ := native B order supply hp hq
+ obtain ⟨ko,original⟩ := TermRecord.run_spec B order supply hp hq
+ refine ⟨max kn ko,fun m M w hW L addr haddr demand hD cap hcap mem hin i bits => ?_⟩
+ let j : BurstRAM.Word w := i.val
+ have hkn := le_max_left kn ko
+ have hko := le_max_right kn ko
+ have hn := native M w (by omega) addr j mem
+ dsimp only at hn
+ rw [(haddr i).1,(haddr i).2] at hn
+ obtain ⟨hw,row,u,hrow,hu,hf⟩ := hn (L.sourceFits i) (L.termFits i) (L.separate i i) ((hin i) ▸ hD i)
+ obtain ⟨hw',row',u',hrow',hu',ha,complete⟩ :=
+ original M w (by omega) (L.source i) (L.base i) mem (L.sourceFits i) (L.termFits i)
+ (L.separate i i) ((hin i) ▸ hD i)
+ obtain ⟨hnative,selected⟩ := hf cap hcap
+ have hroweq : row = row' := Fin.ext (row_unique (Finset.nodup_toList _) hrow hrow')
+ have hueq : u = u' := Fin.ext (hu.trans hu'.symm)
+ subst row' u'
+ let T := program B order supply addr
+ let old := TermRecord.run B order supply (L.source i) (L.base i) mem (prepFuel (p := p) d M)
+ change Option.Rel _ (execute T cap (T.start j) mem bits) (old bits)
+ cases hs : execute T cap (T.start j) mem bits with
+ | none =>
+ have ho : old bits = none := by
+ apply Option.not_isSome_iff_eq_none.mp
+ intro hsome
+ have h := (hnative bits).mpr ((ha bits).mp hsome)
+ change (execute T cap (T.start j) mem bits).isSome at h
+ simp [hs] at h
+ rw [ho]; exact .none
+ | some fresh =>
+ obtain ⟨v,read⟩ := (hnative bits).mp (by change (execute T cap (T.start j) mem bits).isSome; simp [hs])
+ have hbs : bits = (outerReader B supply hq _ w hw).encode v := by
+ simpa only [List.append_nil] using (ChoiceReader.read_iff ..).mp read
+ obtain ⟨es,he,hm,_,hprobe,hlen⟩ := selected v
+ rw [← hbs] at he
+ change execute T cap (T.start j) mem bits = some _ at he
+ rw [hs] at he
+ cases Option.some.inj he
+ obtain ⟨rs,ho,_,hmem,_,_,_⟩ := complete v
+ rw [← hbs] at ho
+ change old bits = some rs at ho
+ rw [ho]
+ have frame : ∀ x, L.Outside i x → after mem es x = mem x := by
+ intro x hx
+ rw [hm]
+ exact (TermRecord.recordMemory_fields mem (L.base i) row u supply v.val (L.termFits i)).2.2.2 x hx
+ exact .some ⟨by simp [j],hm.trans hmem.symm,inputs_after order L hin i frame,frame,hprobe,hlen⟩
+
+/-- Any successful call at a valid row ordinal returns its successor and
+preserves every demand input and every cell outside that row's descriptor.
+This includes the dispatch frame when it is allocated outside the term rows. -/
+theorem call_frame (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
+ ∃ K : ℕ, ∀ m M w, K+4*Nat.clog 2 (M+1) ≤ w → ∀ (L : Layout m d n w) addr,
+ Addresses L addr → ∀ (demand : Fin m → D → ℕ), (∀ i e, demand i e ≤ M) →
+ ∀ cap, budget B d n w M ≤ cap → ∀ mem, Inputs order L demand mem →
+ ∀ (i : Fin m) (bits : List Bool) (rep : Report w),
+ let T := program B order supply addr
+ execute T cap (T.start (i.val : BurstRAM.Word w)) mem bits = some rep →
+ rep.result = some ((i.val+1 : ℕ) : BurstRAM.Word w) ∧ Inputs order L demand (after mem rep.events) ∧
+ (∀ x, L.Outside i x → after mem rep.events x = mem x) ∧ rep.probes ≤ probesPerRow B d n ∧
+ rep.events.length < budget B d n w M := by
+ obtain ⟨K,hw⟩ := row_ready B order supply hp hq
+ refine ⟨K,fun m M w hW L addr ha demand hD cap hc mem hin i bs r hr => ?_⟩
+ have he := hw m M w hW L addr ha demand hD cap hc mem hin i bs
+ dsimp only at he
+ rw [hr] at he
+ cases ho : TermRecord.run B order supply (L.source i) (L.base i) mem (prepFuel (p := p) d M) bs with
+ | none => rw [ho] at he; cases he
+ | some old =>
+ rw [ho] at he
+ cases he with | some h => exact ⟨h.cursor,h.inputs,h.frame,h.probes,h.steps⟩
+
+private structure PassEffect (start M : ℕ) (ids : List (Fin m)) (initial : Memory w)
+ (fresh old : List (Report w)) : Prop where
+ memory : after initial (eventLog fresh) = after initial (eventLog old)
+ cursor : endState (some (start : BurstRAM.Word w)) fresh = some ((start+ids.length : ℕ) : BurstRAM.Word w)
+ length : fresh.length = ids.length
+ probes : countProbes (eventLog fresh) ≤ ids.length * probesPerRow B d n
+ steps : (eventLog fresh).length ≤ ids.length * budget B d n w M
+ sites : ∀ r ∈ fresh, r.events.length < budget B d n w M
+
+private theorem paired {L : Layout m d n w} {addr : Fin 4 → BurstRAM.Word w} {demand : Fin m → D → ℕ}
+ {M cap : ℕ} (ready : Ready B order supply L addr demand M cap) (tapes : Fin m → List Bool)
+ (ids : List (Fin m)) (start : ℕ) (sorted : ids.map Fin.val = List.range' start ids.length)
+ (mem : Memory w) (hin : Inputs order L demand mem) :
+ Option.Rel (PassEffect (d := d) (n := n) B start M ids mem)
+ (runSegment (program B order supply addr) cap (some (start : BurstRAM.Word w)) mem (ids.map tapes))
+ (walk B order supply L (prepFuel (p := p) d M) tapes ids mem) := by
+ induction ids generalizing start mem with
+ | nil =>
+ exact .some ⟨rfl,rfl,rfl,by simp [eventLog,countProbes],by simp [eventLog],by simp⟩
+ | cons i ids ih =>
+ simp only [List.map_cons,List.length_cons,List.range'_succ,List.cons.injEq] at sorted
+ obtain ⟨rfl,htail⟩ := sorted
+ let T := program B order supply addr
+ let old := TermRecord.run B order supply (L.source i) (L.base i) mem (prepFuel (p := p) d M) (tapes i)
+ let fresh := execute T cap (T.start (i.val : BurstRAM.Word w)) mem (tapes i)
+ have both : Option.Rel _ fresh old := ready mem hin i (tapes i)
+ cases hf : fresh with
+ | none =>
+ cases ho : old with
+ | none =>
+ change Option.Rel _ (match fresh with | none => none | some _ => _) (old.bind _)
+ rw [hf,ho]; exact .none
+ | some o => rw [hf,ho] at both; cases both
+ | some f =>
+ cases ho : old with
+ | none => rw [hf,ho] at both; cases both
+ | some o =>
+ rw [hf,ho] at both
+ cases both with | some effect =>
+ let next := after mem f.events
+ have tails := ih (i.val+1) htail next effect.inputs
+ simp only [List.map_cons,runSegment,walk,bind]
+ change Option.Rel _ (match fresh with | none => none | some f => _) (old.bind _)
+ rw [hf,ho]
+ simp only [Option.bind_some,effect.cursor,← effect.memory]
+ cases ht : runSegment T cap (some ((i.val+1 : ℕ) : BurstRAM.Word w)) next (ids.map tapes) with
+ | none =>
+ cases hto : walk B order supply L (prepFuel (p := p) d M) tapes ids next with
+ | none => exact .none
+ | some _ => rw [ht,hto] at tails; cases tails
+ | some fs =>
+ cases hto : walk B order supply L (prepFuel (p := p) d M) tapes ids next with
+ | none => rw [ht,hto] at tails; cases tails
+ | some os =>
+ rw [ht,hto] at tails
+ cases tails with | some effects =>
+ refine .some ⟨?_,?_,?_,?_,?_,?_⟩
+ · change after mem (f.events++eventLog fs) = after mem (eventLog (o++os))
+ rw [show after mem (f.events++eventLog fs) = after next (eventLog fs) from List.foldl_append]
+ rw [effects.memory,show eventLog (o++os) = eventLog o ++ eventLog os from List.flatMap_append,
+ show after mem (eventLog o ++ eventLog os) = after (after mem (eventLog o)) (eventLog os) from List.foldl_append,
+ ← effect.memory]
+ · change endState f.result fs = _
+ rw [effect.cursor,effects.cursor]
+ simp [Nat.add_assoc,Nat.add_comm 1]
+ · simp [effects.length]
+ · change countProbes (f.events++eventLog fs) ≤ (ids.length+1)*probesPerRow B d n
+ rw [DemandPreparation.probes_append,Nat.succ_mul]
+ have h := effect.probes
+ change countProbes f.events ≤ _ at h
+ exact (Nat.add_le_add h effects.probes).trans_eq (Nat.add_comm ..)
+ · change (f.events++eventLog fs).length ≤ (ids.length+1)*budget B d n w M
+ rw [List.length_append,Nat.succ_mul]
+ exact (Nat.add_le_add effect.steps.le effects.steps).trans_eq (Nat.add_comm ..)
+ · intro r hr
+ rcases List.mem_cons.mp hr with rfl | h
+ · exact effect.steps
+ · exact effects.sites r h
+
+private theorem ordinal_order (m : ℕ) : (List.finRange m).map Fin.val = List.range' 0 (List.finRange m).length := by
+ apply List.ext_getElem
+ · simp
+ · intro i hi hj
+ simp
+
+private theorem isSome_iff_of_rel {X Y : Type*} {r : X → Y → Prop} {x : Option X} {y : Option Y}
+ (h : Option.Rel r x y) : x.isSome ↔ y.isSome := by cases h <;> rfl
+
+/-- One fixed native table traverses the complete layout. Each vector family
+determines one successful tape tuple, and all stored row headers and supply
+fields survive in the final memory. -/
+theorem scan_native (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
+ ∃ K : ℕ, ∀ m M w, K+4*Nat.clog 2 (M+1) ≤ w → ∀ (L : Layout m d n w) addr,
+ Addresses L addr → ∀ (demand : Fin m → D → ℕ), (∀ i e, demand i e ≤ M) →
+ ∀ (mem : Memory w), Inputs order L demand mem → ∀ cap, budget B d n w M ≤ cap →
+ let T := program B order supply addr
+ let run := fun tapes : Fin m → List Bool => runSegment T cap (some 0) mem (List.ofFn tapes)
+ (∀ tapes, (run tapes).isSome ↔ ∃! v : Choices B demand,
+ tapes = fun i => tape B supply (demand i) w (v i).val) ∧
+ ∀ v : Choices B demand, ∃ rs, run (fun i => tape B supply (demand i) w (v i).val) = some rs ∧
+ (∀ i, Fields B supply hp (demand i) (v i).val (L.base i) (after mem (eventLog rs))) ∧
+ (∀ x, (∀ i, L.Outside i x) → after mem (eventLog rs) x = mem x) ∧
+ endState (some (0 : BurstRAM.Word w)) rs = some (m : BurstRAM.Word w) ∧
+ rs.length = m ∧ branchPaths rs = List.ofFn (fun i => tape B supply (demand i) w (v i).val) ∧
+ countProbes (eventLog rs) ≤ m*probesPerRow B d n ∧ (eventLog rs).length ≤ m*budget B d n w M := by
+ obtain ⟨kw,workers⟩ := row_ready B order supply hp hq
+ obtain ⟨kr,records⟩ := TermRecordScan.run_spec B order supply hp hq
+ refine ⟨max kw kr,fun m M w hW L addr addrs demand hD mem hin cap hcap => ?_⟩
+ have hkw := le_max_left kw kr
+ have hkr := le_max_right kw kr
+ have ready := workers m M w (by omega) L addr addrs demand hD cap hcap
+ obtain ⟨legal,full⟩ := records m M w (by omega) L demand hD mem hin
+ let ids := List.finRange m
+ let run := fun tapes : Fin m → List Bool => runSegment (program B order supply addr) cap (some 0) mem (List.ofFn tapes)
+ have sync (tapes : Fin m → List Bool) :
+ Option.Rel (PassEffect (d := d) (n := n) B 0 M ids mem) (run tapes)
+ (walk B order supply L (prepFuel (p := p) d M) tapes ids mem) := by
+ simpa only [run,ids,List.ofFn_eq_map,Nat.cast_zero] using paired B order supply ready tapes ids 0 (ordinal_order m) mem hin
+ refine ⟨fun tapes => (isSome_iff_of_rel (sync tapes)).trans (legal tapes),fun v => ?_⟩
+ let bs := fun i => tape B supply (demand i) w (v i).val
+ obtain ⟨old,ho,fields,frame,_⟩ := full v
+ change walk B order supply L (prepFuel (p := p) d M) bs ids mem = some old at ho
+ have he := sync bs
+ rw [ho] at he
+ cases hf : run bs with
+ | none => rw [hf] at he; cases he
+ | some fresh =>
+ rw [hf] at he
+ cases he with | some effect =>
+ have branches := ((runSegment_iff ..).mp hf).2.2
+ refine ⟨fresh,hf,?_,?_,?_,?_,branches,?_,?_⟩
+ · rw [effect.memory]; exact fields
+ · rw [effect.memory]; exact frame
+ · simpa only [ids,List.length_finRange,Nat.zero_add,Nat.cast_zero] using effect.cursor
+ · simpa only [ids,List.length_finRange] using effect.length
+ · simpa only [ids,List.length_finRange] using effect.probes
+ · simpa only [ids,List.length_finRange] using effect.steps
+
+/-- The local resource bound applies to each reset call even when the full
+segment runs with a larger instruction cap. -/
+theorem scan_site_bound (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
+ ∃ K : ℕ, ∀ m M w, K+4*Nat.clog 2 (M+1) ≤ w → ∀ (L : Layout m d n w) addr,
+ Addresses L addr → ∀ (demand : Fin m → D → ℕ), (∀ i e, demand i e ≤ M) →
+ ∀ (mem : Memory w), Inputs order L demand mem → ∀ cap, budget B d n w M ≤ cap →
+ ∀ (tapes : Fin m → List Bool) (rs : List (Report w)),
+ runSegment (program B order supply addr) cap (some 0) mem (List.ofFn tapes) = some rs →
+ ∀ r ∈ rs, r.events.length < budget B d n w M := by
+ obtain ⟨K,hw⟩ := row_ready B order supply hp hq
+ refine ⟨K,fun m M w hW L addr haddr demand hD mem hin cap hcap tapes rs hr => ?_⟩
+ let ids := List.finRange m
+ have sync := paired B order supply (hw m M w hW L addr haddr demand hD cap hcap) tapes ids 0
+ (ordinal_order m) mem hin
+ have he : runSegment (program B order supply addr) cap (some ((0 : ℕ) : BurstRAM.Word w)) mem (ids.map tapes)
+ = some rs := by simpa only [ids,Nat.cast_zero,← List.ofFn_eq_map] using hr
+ rw [he] at sync
+ cases ho : walk B order supply L (prepFuel (p := p) d M) tapes ids mem with
+ | none => rw [ho] at sync; cases sync
+ | some os => rw [ho] at sync; cases sync with | some h => exact h.sites
+
+end CompressorRecords.TermWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTimelineDepth.lean b/lean/OAI/Computability/VPVNP/CompressorTimelineDepth.lean
new file mode 100644
index 0000000000..b84826a16e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTimelineDepth.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.CompressorPassTimeline
+
+/-! # The stored level number of each chronological block visit
+
+A pass advances the stored history by one level, while its calendar ordinal
+advances by its number of physical rows. The current history length agrees
+with the block number and shrinking or refresh index at every pass.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PassTimeline
+
+variable {steps : ℕ}
+
+/-- History level of a pass, counting all previous blocks and the preceding passes in the
+current block. -/
+def Located.depth (loc : Located steps) : ℕ :=
+ loc.block*(steps+1) + match loc.pass with | .shrink i => i.val | .refresh => steps
+
+/-- Every pass in the list has its position plus `first` as its stored history depth. -/
+def Numbered (first : ℕ) (xs : List (Located steps)) : Prop :=
+ ∀ i : Fin xs.length, xs[i.val].depth = first+i.val
+
+theorem Numbered.head {s : Located steps} {ss : List (Located steps)} {first : ℕ}
+ (h : Numbered first (s::ss)) : s.depth = first := by simpa using h 0
+
+theorem Numbered.tail {s : Located steps} {ss : List (Located steps)} {first : ℕ}
+ (h : Numbered first (s::ss)) : Numbered (first+1) ss := by
+ intro i
+ have eq := h i.succ
+ simp only [Fin.val_succ,List.getElem_cons_succ] at eq
+ rw [eq]
+ omega
+
+theorem Numbered.append {xs ys : List (Located steps)} {first : ℕ}
+ (hx : Numbered first xs) (hy : Numbered (first+xs.length) ys) : Numbered first (xs++ys) := by
+ intro i
+ by_cases lt : i.val < xs.length
+ · rw [List.getElem_append_left lt]
+ exact hx ⟨i.val,lt⟩
+ · have hi : i.val-xs.length < ys.length := by have := i.isLt; simp only [List.length_append] at this; omega
+ rw [List.getElem_append_right (Nat.le_of_not_lt lt),hy ⟨_,hi⟩]
+ change first+xs.length+(i.val-xs.length) = first+i.val
+ omega
+
+@[simp] theorem oneBlock_length (steps t : ℕ) : (oneBlock steps t).length = steps+1 := by simp [oneBlock]
+
+theorem oneBlock_numbered (steps t : ℕ) : Numbered (t*(steps+1)) (oneBlock steps t) := by
+ intro i
+ have hi : i.val < steps+1 := i.isLt.trans_le (oneBlock_length steps t).le
+ by_cases lt : i.val < steps
+ · have hl : i.val < ((List.finRange steps).map (fun j => Located.mk t (Pass.shrink j))).length := by simpa using lt
+ simp only [oneBlock,List.getElem_append_left hl,List.getElem_map,List.getElem_finRange,Located.depth,Fin.val_cast]
+ · have eq : i.val = steps := by omega
+ simp [oneBlock,eq,List.getElem_append_right,Located.depth]
+
+@[simp] theorem timeline_length (steps T : ℕ) : (timeline steps T).length = T*(steps+1) := by
+ induction T with
+ | zero => simp [timeline]
+ | succ t ih =>
+ simp only [timeline,List.range_succ,List.flatMap_append,List.flatMap_singleton,List.length_append,oneBlock_length]
+ change (timeline steps t).length+_ = _
+ rw [ih,Nat.succ_mul]
+
+theorem timeline_numbered (steps T : ℕ) : Numbered 0 (timeline steps T) := by
+ induction T with
+ | zero => intro i; exact i.elim0
+ | succ t ih =>
+ simp only [timeline,List.range_succ,List.flatMap_append,List.flatMap_singleton]
+ apply ih.append
+ simpa only [Nat.zero_add,timeline_length] using oneBlock_numbered steps t
+
+theorem block_lt_of_mem {T : ℕ} {loc : Located steps} (h : loc ∈ timeline steps T) : loc.block < T := by
+ obtain ⟨t,ht,hl⟩ := List.mem_flatMap.mp h
+ have eq : loc.block = t := by
+ rcases List.mem_append.mp hl with left|right
+ · obtain ⟨i,_,rfl⟩ := List.mem_map.mp left
+ rfl
+ · exact congrArg Located.block (List.mem_singleton.mp right)
+ exact eq ▸ List.mem_range.mp ht
+
+end CompressorRecords.PassTimeline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTransferredStartup.lean b/lean/OAI/Computability/VPVNP/CompressorTransferredStartup.lean
new file mode 100644
index 0000000000..da089dfe2a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTransferredStartup.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.CompressorCursorFrameTransfers
+import OAI.Computability.VPVNP.CompressorCalendarArenaTransfers
+
+/-!
+# All eight startup reports of the compressed pair
+
+Every report uses the memory left by the previous report and its linker tag
+write. The state passed to the online stage carries its controller bank, the
+persistent cursor operands and the natural history-arena bounds.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TransferredStartup
+
+open BurstRAM CursorBounds DescriptorSpace OnlineCursorStartup
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The two successive groups of startup reports that prepare the cursor frame and initialize
+the calendar. -/
+structure Trace (w : ℕ) where
+ /-- First four reports, which prepare and copy the cursor operands into the active frame. -/
+ frame : CursorFrameTransfers.Trace w
+ /-- Last four reports, which compute the stride, install the arena and bank, and arm the
+ calendar. -/
+ calendar : CalendarArenaTransfers.Trace w
+
+/-- All eight native startup reports indexed in execution order. -/
+def Trace.source (t : Trace w) : Fin 8 → Report w :=
+ ![t.frame.row, t.frame.raw, t.frame.loaded, t.frame.copied,
+ t.calendar.stride, t.calendar.arena, t.calendar.bank, t.calendar.arm]
+
+/-- The nine boundary memories before, between, and after the eight startup calls, including
+linker tag writes. -/
+def Trace.entry (t : Trace w) (tag : Word w) (m : Memory w) : Fin 9 → Memory w :=
+ let prepared := t.frame.post tag m
+ ![m,t.frame.postRow tag m,t.frame.postRaw tag m,t.frame.postLoad tag m,prepared,
+ t.calendar.postStride tag prepared,t.calendar.postArena tag prepared,
+ t.calendar.postBank tag prepared,t.calendar.post tag prepared]
+
+theorem Trace.transfer (t : Trace w) (tag : Word w) (m : Memory w) (i : Fin 8) :
+ t.entry tag m i.succ = writeMemory (after (t.entry tag m i.castSucc) (t.source i).events)
+ tag ((i.val+1 : ℕ) : Word w) := by fin_cases i <;> rfl
+
+/-- Construct the startup reports, beginning the calendar initialization in the memory produced
+by the frame transfers. -/
+noncomputable def trace (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes steps : ℕ)
+ (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) : Trace w :=
+ let front := CursorFrameTransfers.trace D L B n a lanes pub tag m
+ ⟨front, CalendarArenaTransfers.trace D d L steps pub tag (front.post tag m)⟩
+
+theorem source_closed (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes steps : ℕ)
+ (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) (i : Fin 8) :
+ ((trace D d L B n a lanes steps pub tag m).source i).result = none := by
+ fin_cases i <;> rfl
+
+/-- Both groups of native startup calls run, with calendar initialization using the
+post-transfer cursor memory. -/
+structure Runs (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes steps : ℕ)
+ (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) : Prop where
+ frame : CursorFrameTransfers.Runs D L B n a lanes pub tag m
+ calendar : CalendarArenaTransfers.Runs D d L B n a lanes steps pub tag
+ ((CursorFrameTransfers.trace D L B n a lanes pub tag m).post tag m)
+
+/-- The pair performs the eight source calls with the actual intervening
+transfer writes. A lower tag address and a fitting descriptor allocation
+suffice independently of the contents of the incoming memory. -/
+theorem run (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes steps : ℕ)
+ (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) (input : Input D L B n pub)
+ (hw : w = wordBits B n) (hB : 1 ≤ B) (lower : tag.val < L.base)
+ (hL : roundedDown D.p D.q n*lanes ≤ virtualBits B n)
+ (arity : 7 ≤ L.shape.arity) (scalars : 30 ≤ L.shape.scalarFields)
+ (positions : initialPositions B n = L.positions) (levels : L.levels = 1+roundedDown D.p D.q n*(steps+1))
+ (capacity : CursorRAM.ParametersInit.Capacity B n a (roundedDown D.p D.q n*lanes)
+ (directoryBase L) 1 (incidenceStart L 0) (levelStart L 0+6)) :
+ Runs D d L B n a lanes steps pub tag m := by
+ have front := CursorFrameTransfers.run D L B n a lanes pub tag m input hw hB hL arity
+ ((by decide : 14 ≤ 30).trans scalars) capacity lower
+ have cols : incidenceStart L 0 < 2^w := hw ▸ capacity.public_lt 6
+ have headFit : levelStart L 0+29 < 2^w := by unfold incidenceStart levelHeaderWords at cols; omega
+ exact ⟨front, CalendarArenaTransfers.run D d L B n a lanes steps pub tag _ input lower hL positions
+ levels headFit front.count front.active front.saved⟩
+
+/-- The exact native post-memory, including the tag transfer to stage eight.
+The first header retains the natural arena base, level count and input length. -/
+theorem Runs.output {D d L B n a lanes steps pub tag m}
+ (h : Runs (w := w) D d L B n a lanes steps pub tag m) (hn : n < 2^w)
+ (hl : 0 < L.levels) (hs : 30 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) :
+ let t := trace D d L B n a lanes steps pub tag m
+ let out := t.entry tag m (Fin.last 8)
+ let head := levelStart L 0
+ OnlineWorkspace.Ready d L.shape.arity (pub 2) (CalendarRows.rows D n) (levelWords L) out ∧
+ Frame.data (DescriptorParameters.saved L w) out = DescriptorParameters.outputs L B n a (roundedDown D.p D.q n*lanes) w ∧
+ (out (head+14)).val = endAddress L ∧ (out (head+28)).val = L.levels ∧ (out (head+29)).val = n ∧
+ out tag.val = 8 := by
+ intro t out head
+ let middle := (CursorFrameTransfers.trace D L B n a lanes pub tag m).post tag m
+ obtain ⟨base,count,len,_⟩ := HistoryArenaBase.stored L n middle hn hl hs fit
+ have level (j : ℕ) : out (head+j) = HistoryArenaBase.install L n middle (head+j) :=
+ h.calendar.levelWords_after _ (Nat.le_add_right ..)
+ exact ⟨h.calendar.ready,h.calendar.saved,(congrArg Fin.val (level 14)).trans base,
+ (congrArg Fin.val (level 28)).trans count,(congrArg Fin.val (level 29)).trans len,h.calendar.tagged⟩
+
+/-- One length threshold covers the complete physical startup, for every
+incoming memory and every linker tag preceding the polynomially bounded
+workspace. Only the eight compiler constants and the live dimensions enter
+the source instruction tables. -/
+theorem eventually_run (D : CalendarRows.Spec) (d : ℕ) (F : Shape) (B a lanes steps : ℕ)
+ (hB : 1 ≤ B) (hq : 0 < D.q) (hph : 0 < D.phaseRows)
+ (hθ : (D.p : ℝ)/D.q ≤ 1) (hlanes : lanes ≤ B)
+ (arity : 7 ≤ F.arity) (scalars : 30 ≤ F.scalarFields) {base : ℕ → ℕ} (hb : PolynomiallyBounded base) :
+ ∀ᶠ n : ℕ in Filter.atTop, ∀ (pub : Fin 11 → Word (wordBits B n)) (tag : Word (wordBits B n)),
+ (pub 2).val = base n → (pub 6).val = n → (pub 7).val = addressBits B n → tag.val < base n →
+ ∀ m, Runs D d (LevelFields.tightDirectory (cursorLayout F B steps ((D.p : ℝ)/D.q) (base n) n)
+ (CalendarRows.rows D n)) B n a lanes steps pub tag m := by
+ filter_upwards [OnlineCursorStartup.eventually_input D B hB hq hph,
+ DescriptorParameters.eventually_tight_capacity D F B a lanes hB hθ hlanes hb] with n input cap
+ intro pub tag base_eq length_eq addr_eq lower m
+ let P := cursorLayout F B steps ((D.p : ℝ)/D.q) (base n) n
+ let L := LevelFields.tightDirectory P (CalendarRows.rows D n)
+ have levels : L.levels = 1+roundedDown D.p D.q n*(steps+1) := by
+ change 1+(steps+1)*Compression.blockCount ((D.p : ℝ)/D.q) n = _
+ rw [roundedDown_eq, Nat.mul_comm]
+ obtain ⟨hL,hcap⟩ := cap P.positions P.levels
+ exact run D d L B n a lanes steps pub tag m (input P pub base_eq length_eq addr_eq) rfl hB lower
+ hL arity scalars rfl levels hcap
+
+end CompressorRecords.TransferredStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorTransferredStartupFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorTransferredStartupFootprint.lean
new file mode 100644
index 0000000000..6a525d4496
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorTransferredStartupFootprint.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.CompressorTransferredStartup
+
+/-!
+# Protected low memory across the eight native startup calls
+
+Each source report preserves every cell below the descriptor workspace. The
+linker writes its tag after each report, so every other low cell retains its
+initial value at all nine entries. These statements use the reports of the
+linked machines on the actual intermediate memories.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.TransferredStartup
+
+open BurstRAM DescriptorSpace
+open scoped Fin.CommRing
+
+variable {w d B n a lanes steps : ℕ} {D : CalendarRows.Spec} {L : Layout}
+variable {pub : Fin 11 → Word w} {tag : Word w} {m : Memory w}
+
+/-- The native source of every transfer keeps the protected low memory. -/
+theorem Runs.source_below (h : Runs D d L B n a lanes steps pub tag m) (i : Fin 8)
+ (x : ℕ) (hx : x < L.base) :
+ let t := trace D d L B n a lanes steps pub tag m
+ after (t.entry tag m i.castSucc) (t.source i).events x = t.entry tag m i.castSucc x := by
+ obtain ⟨h₀,h₁,h₂,h₃⟩ := h.frame.source_below x hx
+ obtain ⟨h₄,h₅,h₆,h₇⟩ := h.calendar.source_below x hx
+ fin_cases i
+ · exact h₀
+ · exact h₁
+ · exact h₂
+ · exact h₃
+ · exact h₄
+ · exact h₅
+ · exact h₆
+ · exact h₇
+
+/-- Every prefix, including the last transfer to the online worker, preserves
+all low cells outside the pair tag. -/
+theorem Runs.entry_below (h : Runs D d L B n a lanes steps pub tag m) (i : Fin 9)
+ (x : ℕ) (hx : x < L.base) (ht : x ≠ tag.val) :
+ (trace D d L B n a lanes steps pub tag m).entry tag m i x = m x := by
+ let t := trace D d L B n a lanes steps pub tag m
+ change t.entry tag m i x = m x
+ induction i using Fin.induction with
+ | zero => rfl
+ | succ i ih =>
+ rw [t.transfer,writeMemory,ite_eq_right ht]
+ exact (h.source_below i x hx).trans ih
+
+/-- The post-memory of any of the eight source reports also agrees with the
+original input on every protected address. -/
+theorem Runs.after_source_below (h : Runs D d L B n a lanes steps pub tag m) (i : Fin 8)
+ (x : ℕ) (hx : x < L.base) (ht : x ≠ tag.val) :
+ let t := trace D d L B n a lanes steps pub tag m
+ after (t.entry tag m i.castSucc) (t.source i).events x = m x :=
+ (h.source_below i x hx).trans (h.entry_below i.castSucc x hx ht)
+
+end CompressorRecords.TransferredStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorUniformEvaluator.lean b/lean/OAI/Computability/VPVNP/CompressorUniformEvaluator.lean
new file mode 100644
index 0000000000..063922ce5d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorUniformEvaluator.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.CompressorEvaluatorInput
+
+/-!
+# Uniform compilation of the joint label evaluator
+
+The scalar-query implementation provides its two fixed tables and a polynomial
+length envelope for their physical inputs. This theorem composes that interface
+with algebraic descent, the canonical monomial basis, nondeterministic
+evaluation and the literal two-tape compiler. Its exponent and threshold are
+chosen before the input length, prime, solution, exponent width or processor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.BlockSchedule.Templates
+
+open MvPolynomial LabelEvaluator RAMTape Evaluator.MatrixCallbacks EvaluatorProgramRawInput
+open Evaluator.BinaryMachine LiveEvaluatorEncoding
+
+local instance uniformEvaluatorPrime (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+/-- Finite enumeration of the ground field used by the uniform joint evaluator. -/
+noncomputable local instance uniformEvaluatorFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+/-- Classical equality decision for the ground-field coefficients used by the uniform
+evaluator. -/
+noncomputable local instance uniformEvaluatorDecidableEq (p : Nat.Primes) (t d : ℕ) : DecidableEq (Ground p t d) := Classical.decEq _
+/-- Algebra structure on the ambient field induced by the slice-field embedding. -/
+noncomputable local instance uniformEvaluatorAmbientAlgebra (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) :=
+ (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+ {P : Type} [DecidableEq P] [Fintype P]
+ (ps : List (Evaluator.WeightedStep.Port P)) (hps : ps.Nodup) (hall : ∀ x, x ∈ ps)
+ (frob label : FiniteRoutine (ReadPort P)) (q c : ℕ) [CharP k q]
+
+local notation "ports" => Fintype.card (MachinePort (Evaluator.WeightedStep.Port P))
+
+include hps hall in
+/-- The uniform fixed-code evaluator conclusion, with its physical reader
+interface left explicit for assembly of the deterministic Cramer routines. -/
+theorem uniform_evaluator_of_coordinate_readers (a : ℕ → ℕ) (ha : PolynomiallyBounded a) (N : ℕ)
+ (prepare : ∀ n ≥ N, ∀ (hn : 2 ≤ n) (p : Nat.Primes),
+ (q ≠ 0 → p.val = q) → (q = 0 → p.val ≤ 2^B.compressorPrimeBits c n) →
+ ∀ M : Model p (B.compressorDegree n) (B.compressorEquations hn c),
+ ∃ H : B.SliceReaderAdvice M frob label, H.envelope ps ≤ a n) :
+ let E := Evaluator.MatrixCallbacks.program ps frob label
+ ∃ C N' : ℕ, ∀ n ≥ N', ∀ hn : 2 ≤ n,
+ (∃ x : Fin (B.compressorLabelCount c n) → k,
+ ∀ i, eval₂ (Int.castRingHom k) x (B.compressorEquations hn c i) = 0) →
+ ∃ p : Nat.Primes, (q ≠ 0 → p.val = q) ∧ (q = 0 → p.val ≤ 2^B.compressorPrimeBits c n) ∧
+ ∃ M : Model p (B.compressorDegree n) (B.compressorEquations hn c),
+ ∃ adviceBits : List Bool, adviceBits.length ≤ n^C ∧
+ Finite M.algebra ∧ IsReduced M.algebra ∧ M.functional 1 = 1 ∧
+ (∀ i, eval₂ (Int.castRingHom M.algebra) M.labels (B.compressorEquations hn c i) = 0) ∧
+ ∀ Z (es : Fin (B.compressorLabelCount c n) → BurstRAM.Word Z),
+ let raw := adviceBits ++ runtime es
+ UniversalMachine.AllHalt E (2^(n^C)*(Z+1)^4) (UniversalMachine.initial E raw) ∧
+ (∀ ticks ≥ 2^(n^C)*(Z+1)^4,
+ (UniversalMachine.paths E ticks (UniversalMachine.initial E raw) : ZMod p.val) =
+ M.functional (∏ i, M.labels i ^ (es i).val)) ∧
+ (∀ choices, let disp := choiceDisplacement E (UniversalMachine.initial E raw) choices
+ RAMTape.StackCompiler.HeadBox (2240*(ports+1)*(n^C+Z+1)^4) disp.1 disp.2) ∧
+ ∀ time (bits : Fin time → Bool) (i : Fin (time+1)),
+ StateFits (2240*(ports+1)*(n^C+Z+1)^4)
+ (EvaluatorTail.history E time (UniversalMachine.initial E raw) bits i) := by
+ intro E
+ obtain ⟨C,N₀,hC⟩ := exists_uniform_clock ha
+ refine ⟨C,max N N₀,fun n hn htwo hx ↦ ?_⟩
+ obtain ⟨x, hx⟩ := hx
+ obtain ⟨p,hp,hz,⟨M⟩⟩ := B.exists_compressorModel_of_solution q htwo x hx
+ obtain ⟨H,hH⟩ := prepare n ((le_max_left ..).trans hn) htwo p hp hz M
+ let D := B.compressorCanonical htwo c M
+ let M' := M.withCanonicalPresentation D
+ have ha' : 6*a n+23 ≤ n^C := by
+ have he := hC n ((le_max_right ..).trans hn) 0
+ simp only [Nat.zero_add, one_pow, Nat.mul_one] at he
+ exact (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp he
+ have env : H.envelope ps ≤ n^C := by omega
+ refine ⟨p,hp,hz,M',H.binary ps,(H.binary_le ps).trans env,
+ M'.finite_algebra,M'.reduced,M'.functional_one,M'.solution,fun Z es ↦ ?_⟩
+ let ticks := 2^(n^C)*(Z+1)^4
+ have clock : 2^(6*H.envelope ps+23)*(Z+1)^4 ≤ ticks :=
+ Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (by omega))
+ have result := H.resources_and_value ps hps hall es ticks clock
+ have hsize : 2240*(ports+1)*(H.envelope ps+Z+1)^4 ≤ 2240*(ports+1)*(n^C+Z+1)^4 :=
+ Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) _)
+ refine ⟨result.1, fun t ht ↦ (H.evaluate ps hps hall es t (clock.trans ht)).1, fun choices ↦ ?_,
+ fun time bits i ↦ LiveEvaluatorRadius.fits_mono hsize _ (result.2.2.2 time bits i)⟩
+ have small := result.2.2.1 choices
+ exact small.mono hsize
+
+omit [CharP k q] in
+/-- Per-component size bounds on concrete initialized readers yield the common
+length envelope needed for uniform compilation, even if the advised prime and
+slice vary across lengths. -/
+theorem exists_reader_envelope (iw e lw s peak exp : ℕ → ℕ)
+ (hiw : PolynomiallyBounded iw) (he : PolynomiallyBounded e) (hlw : PolynomiallyBounded lw)
+ (hs : PolynomiallyBounded s) (hpeak : PolynomiallyBounded peak) (hexp : PolynomiallyBounded exp)
+ (N : ℕ)
+ (ready : ∀ n ≥ N, ∀ (hn : 2 ≤ n) (p : Nat.Primes),
+ (q ≠ 0 → p.val = q) → (q = 0 → p.val ≤ 2^B.compressorPrimeBits c n) →
+ ∀ M : Model p (B.compressorDegree n) (B.compressorEquations hn c),
+ ∃ H : B.SliceReaderAdvice M frob label,
+ H.indexWidth ≤ iw n ∧ H.degreePred+1 ≤ e n ∧ H.limbWidth ≤ lw n ∧
+ H.extraSpace ≤ s n ∧ H.peak ≤ peak n ∧ H.queryExponent ≤ exp n) :
+ ∃ a : ℕ → ℕ, PolynomiallyBounded a ∧ ∀ n ≥ N, ∀ (hn : 2 ≤ n) (p : Nat.Primes),
+ (q ≠ 0 → p.val = q) → (q = 0 → p.val ≤ 2^B.compressorPrimeBits c n) →
+ ∀ M : Model p (B.compressorDegree n) (B.compressorEquations hn c),
+ ∃ H : B.SliceReaderAdvice M frob label, H.envelope ps ≤ a n := by
+ let a (n : ℕ) := lengthEnvelope (B.compressorLabelCount c n) (B.fieldWordBound q c n) ps.length
+ (ports) (iw n) (e n) (lw n) (s n) (peak n) (exp n)
+ refine ⟨a, lengthEnvelope_polynomial _ _ (B.compressorLabelCount_polynomial c)
+ (B.fieldWordBound_polynomial q c) hiw he hlw hs hpeak hexp, ?_⟩
+ intro n hn htwo p hp hz M
+ obtain ⟨H, h₁, h₂, h₃, h₄, h₅, h₆⟩ := ready n hn htwo p hp hz M
+ exact ⟨H, lengthEnvelope_mono le_rfl (B.field_parameters_le q c n p hp hz).1 h₁ h₂ h₃ h₄ h₅ h₆⟩
+
+end Compression.BlockSchedule.Templates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorWindowPackets.lean b/lean/OAI/Computability/VPVNP/CompressorWindowPackets.lean
new file mode 100644
index 0000000000..00eba21ec7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorWindowPackets.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.CompressorWindowPrepared
+import OAI.Computability.VPVNP.CompressorHeaderOperands
+import OAI.Computability.VPVNP.CompressorSourceGroups
+
+/-! # Checked chronological packets of an installed block window
+
+Each stage runs with its own actual input memory. Source writes lie above
+the controller words, so the row count and pitch stay valid throughout the
+window. The native online launcher reads the same operands at the stage's
+actual repeated-block ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.BlockPlanner.Window
+
+open BurstRAM Schedule DescriptorSpace PhaseRecipe SourceTransport
+open scoped Fin.CommRing
+
+variable {w : ℕ} {A : Script} {visits : List BlockPlanner.Visit} (W : Window A visits)
+variable (L : Layout) (base : Word w) (t : ℕ)
+local notation "pt" => Workspace.ports (arity A.catalog) base
+local notation "pub" => Schedule.Ports.data pt
+local notation "st" => (levelStart L (A.levelsPerBlock*t) : Word w)
+local notation "D" => operandRegion A L base
+local notation "H" => levelStart L 0
+local notation "gap" => Fin.val (Schedule.Ports.directory pt - 1)
+local notation "Pkt" => SourceWalk.Packet (SourceOnline.Visit A w) w
+
+/-- A visit has a run within the instruction bound and its operand expressions read only the
+specified data region. -/
+def Raw (bound : ℕ) (v : BlockPlanner.Visit) (m : Memory w) (rs : List (Report w)) :=
+ ∃ fuel bits, fuel ≤ bound ∧ HeaderPacket.Run L pub st v m rs fuel bits ∧ HeaderOperands.Supported D pub st m v
+
+/-- Script indices of the window's visits, listed in occurrence order. -/
+def indices := List.ofFn W.index
+
+theorem indices_map : (indices W).map A.visit = visits := by
+ rw [indices,List.map_ofFn,show A.visit ∘ W.index = visits.get from funext W.visit]
+ exact List.ofFn_get _
+
+/-- Absolute calendar ordinal of a phase in block repetition `t`, including the initialization
+prefix. -/
+def ordinal (phase : Fin A.size) := A.initial.length+t*A.block.length+(phase.val-A.initial.length)
+
+theorem ordinal_index (j : Fin visits.length) : ordinal (A:=A) t (W.index j) =
+ A.initial.length+t*A.block.length+(W.position j).val := by
+ simp only [ordinal,index,Fin.val_natAdd,Nat.add_sub_cancel_left]
+
+private theorem attached (hg : arity A.catalog = L.shape.arity) (hb : base.val=L.base) (fit : H < 2^w)
+ (j : Fin visits.length) (fuel : ℕ) (bits : List (List Bool)) (raw : Memory w) (rs : List (Report w))
+ (rows : raw (pt).rows.val = (directoryRows L : Word w)) (stride : raw gap = (levelWords L : Word w))
+ (live : ordinal (A:=A) t (W.index j) < directoryRows L)
+ (supp : HeaderOperands.Supported D pub st raw (A.visit (W.index j))) :
+ let p : Pkt := ⟨HeaderPacket.attach A (W.index j) pub st raw fuel bits,raw,rs⟩
+ SourceOnline.Prepared A L base (ordinal (A:=A) t p.stage.phase) (directoryRows L) p := by
+ intro p
+ rw [show p.stage.phase = W.index j from rfl,W.ordinal_index]
+ apply W.prepared L base hg hb fit j t p raw (fun _ _ => rfl) rows stride ((W.ordinal_index t j) ▸ live)
+ exact ⟨rfl,rfl,rfl,fun _ => rfl,supp.initial,supp.stop,supp.params⟩
+
+open private field_addresses from OAI.Computability.VPVNP.CompressorScriptSnapshot
+
+theorem lowCells (hg : arity A.catalog = L.shape.arity) (hb : base.val=L.base) (fit : H < 2^w) :
+ (pt).rows.val < H ∧ gap < H := by
+ have bound : base.val+(11+arity A.catalog) ≤ H := by
+ rw [hb,hg]
+ simp only [levelStart,levelsBase,directoryBase,plannerTag,frameBase,Nat.zero_mul,Nat.add_zero]
+ omega
+ obtain ⟨_,_,rows,dir,_⟩ := field_addresses _ base (bound.trans_lt fit)
+ refine ⟨by rw [rows]; omega,?_⟩
+ rw [Fin.val_sub_one_of_ne_zero]
+ · rw [dir]; omega
+ · intro h
+ have v := congrArg Fin.val h
+ change (pt).directory.val=0 at v
+ rw [dir] at v; omega
+
+/-- Attach native reports to the global catalog, preserving their exact
+chronology and proving the launch condition in every matching live memory. -/
+theorem packets (hg : arity A.catalog = L.shape.arity) (hb : base.val=L.base) (fit : H < 2^w)
+ (cap bound : ℕ) (m : Memory w) (rs : List (Report w))
+ (walk : SourceWalk (Raw (A:=A) L base t bound) visits m rs)
+ (rows : m (pt).rows.val = (directoryRows L : Word w)) (stride : m gap = (levelWords L : Word w))
+ (live : ∀ j : Fin visits.length, ordinal (A:=A) t (W.index j) < directoryRows L)
+ (rc : ∀ j ∈ W.indices, (A.plan.recipes j).2.code.length+1+2*Online.N A.size A.size+5 ≤ cap)
+ (dc : ∀ j ∈ W.indices, bound+3+4*((A.catalog j).params+1)+2*Online.N A.size A.size+5 ≤ cap) :
+ ∃ ps : List Pkt, SourceWalk.Chronological SourceOnline.Visit.Runs m ps ∧
+ ps.map (fun p => p.stage.phase)=W.indices ∧ ps.flatMap SourceWalk.Packet.reports=rs ∧
+ ∀ p ∈ ps, SourceOnline.Checked A L cap p ∧
+ SourceOnline.Prepared A L base (ordinal (A:=A) t p.stage.phase) (directoryRows L) p := by
+ have bounds := lowCells (A:=A) L base hg hb fit
+ have loop (js : List (Fin A.size)) (inside : ∀ j ∈ js, j ∈ W.indices) (mem : Memory w) (logs : List (Report w))
+ (raw : SourceWalk (Raw (A:=A) L base t bound) (js.map A.visit) mem logs)
+ (nr : mem (pt).rows.val=(directoryRows L : Word w)) (np : mem gap=(levelWords L : Word w)) :
+ ∃ ps : List Pkt, SourceWalk.Chronological SourceOnline.Visit.Runs mem ps ∧
+ ps.map (fun p => p.stage.phase)=js ∧ ps.flatMap SourceWalk.Packet.reports=logs ∧
+ ∀ p ∈ ps, SourceOnline.Checked A L cap p ∧
+ SourceOnline.Prepared A L base (ordinal (A:=A) t p.stage.phase) (directoryRows L) p := by
+ induction js generalizing mem logs with
+ | nil => cases raw; exact ⟨[],trivial,rfl,rfl,by simp⟩
+ | cons j js ih =>
+ cases raw with
+ | @next _ _ _ head tail current rest =>
+ obtain ⟨fuel,bits,hfuel,run,supp⟩ := current
+ have hj := inside j List.mem_cons_self
+ obtain ⟨k,hk⟩ := List.mem_ofFn.mp hj
+ let p : Pkt := ⟨HeaderPacket.attach A j pub st mem fuel bits,mem,head⟩
+ have next (x : ℕ) (hx : x < H) : p.output x = mem x := after_outside _ run.write (Nat.not_le_of_lt hx)
+ obtain ⟨ps,hchron,hphase,hreports,hall⟩ := ih (fun j h => inside j (List.mem_cons_of_mem _ h))
+ p.output tail rest ((next _ bounds.1).trans nr) ((next _ bounds.2).trans np)
+ refine ⟨p::ps,⟨rfl,HeaderPacket.attach_runs A j rfl run,hchron⟩,congrArg (j::·) hphase,
+ congrArg (head++·) hreports,?_⟩
+ intro q hq
+ rcases List.mem_cons.mp hq with rfl|hq
+ · refine ⟨HeaderPacket.attach_checked A j rfl run cap (rc j hj) (by have := dc j hj; omega),?_⟩
+ subst j
+ exact attached W L base t hg hb fit k fuel bits mem head nr np (live k) supp
+ · exact hall q hq
+ exact loop W.indices (fun _ h => h) m rs ((W.indices_map).symm ▸ walk) rows stride
+
+/-- Package the proved launches at consecutive ordinals for appending this
+window to preceding and succeeding source groups. -/
+theorem group (hg : arity A.catalog = L.shape.arity) (hb : base.val=L.base) (fit : H < 2^w)
+ (cap bound : ℕ) (m : Memory w) (rs : List (Report w))
+ (walk : SourceWalk (Raw (A:=A) L base t bound) visits m rs)
+ (rows : m (pt).rows.val = (directoryRows L : Word w)) (stride : m gap = (levelWords L : Word w))
+ (live : ∀ j : Fin visits.length, ordinal (A:=A) t (W.index j) < directoryRows L)
+ (rc : ∀ j ∈ W.indices, (A.plan.recipes j).2.code.length+1+2*Online.N A.size A.size+5 ≤ cap)
+ (dc : ∀ j ∈ W.indices, bound+3+4*((A.catalog j).params+1)+2*Online.N A.size A.size+5 ≤ cap) :
+ ∃ ps : List Pkt, SourceOnline.Group A L base cap (A.initial.length+t*A.block.length+W.before.length)
+ (directoryRows L) m ps ∧ ps.map (fun p => p.stage.phase)=W.indices ∧
+ ps.flatMap SourceWalk.Packet.reports=rs := by
+ obtain ⟨ps,chron,labels,reports,checked⟩ := W.packets L base t hg hb fit cap bound m rs walk rows stride live rc dc
+ refine ⟨ps,⟨chron,fun p hp => (checked p hp).1,?_⟩,labels,reports⟩
+ intro j
+ have len : ps.length=visits.length := by simpa only [indices,List.length_map,List.length_ofFn] using congrArg List.length labels
+ let i : Fin visits.length := j.cast len
+ have phase : ps[j.val].stage.phase=W.index i := by
+ have h := List.getElem_of_eq (i:=j.val) labels (by simpa only [List.length_map] using j.isLt)
+ simp only [indices,List.getElem_map,List.getElem_ofFn] at h
+ exact h.trans (congrArg W.index (Fin.ext rfl))
+ have eqn : ordinal (A:=A) t ps[j.val].stage.phase = A.initial.length+t*A.block.length+W.before.length+j.val := by
+ rw [phase,W.ordinal_index]
+ simp only [Window.position,i,Fin.val_cast,Nat.add_assoc]
+ exact eqn ▸ (checked _ (List.getElem_mem ..)).2
+
+end CompressorRecords.BlockPlanner.Window
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorWindowPrepared.lean b/lean/OAI/Computability/VPVNP/CompressorWindowPrepared.lean
new file mode 100644
index 0000000000..175b7d9763
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorWindowPrepared.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.CompressorScriptWindow
+import OAI.Computability.VPVNP.CompressorSourceLaunch
+import OAI.Computability.VPVNP.CompressorSourceSequence
+import OAI.Computability.VPVNP.CompressorFormulaFootprint
+
+/-!
+# Preparing script-window packets from their source operands
+
+During online planning the recipe sees the same persistent data and
+level stride as the physical source computation. Its block-header state
+is determined by the actual calendar ordinal. Structural read footprints
+therefore suffice to replay each operand formula and to obtain the typed
+worker launch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open BurstRAM Schedule BlockPlanner DescriptorSpace SourceTransport PhaseRecipe
+open scoped Fin.CommRing
+
+theorem PhaseRecipe.Expr.eval_eq_of_reads {w : ℕ} {data : ℕ → Prop} {pub : Fin 5 → Word w} {s : Word w}
+ {m m' : Memory w} (e : Expr) (reads : e.ReadsFrom data pub s m) (h : Agree data m m') :
+ e.eval pub s m = e.eval pub s m' := by
+ induction e with
+ | lit | publicWord | state => rfl
+ | load a ih =>
+ change m (a.eval pub s m).val = m' (a.eval pub s m').val
+ exact (h _ reads.2).trans (congrArg (fun i : Word w ↦ m' i.val) (ih reads.1))
+ | binary op a b ih₁ ih₂ => exact congrArg₂ op.eval (ih₁ reads.1) (ih₂ reads.2)
+
+namespace BlockPlanner.Window
+
+variable {w : ℕ} {A : Script} {visits : List BlockPlanner.Visit} (W : Window A visits)
+variable (L : Layout) (base : Word w)
+local notation "pt" => Workspace.ports (arity A.catalog) base
+local notation "H" => levelStart L 0
+local notation "gap" => Fin.val (Schedule.Ports.directory pt - 1)
+
+/-- The recipe may read the immutable pitch and row total in addition to
+the data suffix. The tag, active frame and current row are excluded. -/
+def operandRegion (A : Script) (L : Layout) (base : Word w) (x : ℕ) :=
+ x = (Workspace.ports (arity A.catalog) base).rows.val ∨ x = ((Workspace.ports (arity A.catalog) base).directory - 1).val ∨ levelStart L 0 ≤ x
+
+open private port_bounds from OAI.Computability.VPVNP.CompressorOnlineFootprint
+open private field_addresses from OAI.Computability.VPVNP.CompressorScriptSnapshot
+
+private theorem calendar_agree (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base)
+ (fit : H < 2^w) (ref m : Memory w) (j : Fin A.size) (suffix : Agree (H ≤ ·) ref m)
+ (rows : ref (pt).rows.val = m (pt).rows.val) (pitch : ref gap = m gap) :
+ Agree (operandRegion A L base) ref (Online.calendarMemory (d := A.size) pt m j) := by
+ obtain ⟨hdir,_,ht,_⟩ := port_bounds A L base hg hb fit
+ have hd : directoryBase L ≤ H := by
+ change directoryBase L ≤ levelsBase L + 0*levelWords L
+ dsimp only [levelsBase]; omega
+ have hf : base.val + (11 + arity A.catalog) < 2^w := by
+ rw [hb,hg]; exact (by dsimp only [directoryBase,plannerTag,frameBase] at hd; omega)
+ have hv := field_addresses (arity A.catalog) base hf
+ have gapval : gap = directoryBase L - 1 := by
+ rw [Fin.val_sub_one_of_ne_zero]
+ · rw [hdir]
+ · intro h
+ have h₀ : directoryBase L = 0 := hdir.symm.trans (h ▸ rfl)
+ simp [directoryBase,plannerTag,frameBase] at h₀
+ intro x hx
+ rcases hx with rfl | rfl | h
+ · have hne : (pt).rows.val ≠ (pt).tag.val := by rw [hv.2.2.1,hv.1]; omega
+ simpa only [Online.calendarMemory,writeMemory,ite_eq_right hne] using rows
+ · have hne : gap ≠ (pt).tag.val := by rw [gapval,ht]; dsimp only [directoryBase,plannerTag,frameBase]; omega
+ simpa only [Online.calendarMemory,writeMemory,ite_eq_right hne] using pitch
+ · have hne : x ≠ (pt).tag.val := by
+ rw [ht]; dsimp only [directoryBase,plannerTag,frameBase] at hd; omega
+ simpa only [Online.calendarMemory,writeMemory,ite_eq_right hne] using suffix x h
+
+/-- Source operand evidence. The state here is the first level of the
+specified block, rather than the header of the local substep. -/
+structure Evaluated (i : Fin visits.length) (t : ℕ) (ref : Memory w) (v : SourceOnline.Visit A w) : Prop where
+ index : v.phase = W.index i
+ start : (A.visit v.phase).initial.eval (pt).data (levelStart L (A.levelsPerBlock*t) : Word w) ref = v.start
+ stop : (A.visit v.phase).stop.eval (pt).data (levelStart L (A.levelsPerBlock*t) : Word w) ref = v.stop
+ params : ∀ j, ((A.visit v.phase).params j).eval (pt).data (levelStart L (A.levelsPerBlock*t) : Word w) ref = v.params j
+ startReads : (A.visit v.phase).initial.ReadsFrom (operandRegion A L base) (pt).data
+ (levelStart L (A.levelsPerBlock*t) : Word w) ref
+ stopReads : (A.visit v.phase).stop.ReadsFrom (operandRegion A L base) (pt).data
+ (levelStart L (A.levelsPerBlock*t) : Word w) ref
+ paramReads : ∀ j, ((A.visit v.phase).params j).ReadsFrom (operandRegion A L base) (pt).data
+ (levelStart L (A.levelsPerBlock*t) : Word w) ref
+
+/-- The same packet is launched in every scheduler memory satisfying the
+actual ordinal, row count, pitch and persistent-data invariants. -/
+theorem prepared (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w)
+ (i : Fin visits.length) (t : ℕ) (p : SourceWalk.Packet (SourceOnline.Visit A w) w)
+ (ref : Memory w) (raw : Agree (H ≤ ·) ref p.input)
+ (total : ref (pt).rows.val = (directoryRows L : Word w)) (pitch : ref gap = (levelWords L : Word w))
+ (live : A.initial.length+t*A.block.length+(W.position i).val < directoryRows L)
+ (ev : Evaluated W L base i t ref p.stage) :
+ SourceOnline.Prepared A L base (A.initial.length+t*A.block.length+(W.position i).val) (directoryRows L) p := by
+ intro m suffix ord rows _ stride
+ have active : m (pt).ordinal.val < m (pt).rows.val := Fin.lt_def.mpr (ord ▸ rows ▸ live)
+ have room := ord ▸ live
+ have count : m (pt).rows.val = (directoryRows L : Word w) := by
+ apply Fin.ext; rw [Fin.val_natCast,← rows,Nat.mod_eq_of_lt (m _).isLt]
+ have phase := A.block_phase t (W.position i)
+ have pc : p.stage.phase = (W.position i).natAdd A.initial.length := ev.index
+ refine ⟨phase.1.trans (congrArg Fin.val pc.symm),?_⟩
+ have hdir := (port_bounds A L base hg hb fit).1
+ have dir : (pt).data 1 = (directoryBase L : Word w) := by
+ change (pt).directory = _; apply Fin.ext; rw [Fin.val_natCast,← hdir,Nat.mod_eq_of_lt (pt).directory.isLt]
+ have entry := LevelFields.eval_calendar_entry (Online.calendar A.plan) (pt).data m L dir
+ (show (Online.calendar A.plan).rowPitch = L.shape.arity+3 from congrArg (·+3) hg) count stride
+ have state : A.recipeState base m = (levelStart L (A.levelsPerBlock*t) : Word w) := by
+ change LevelCalendar.header (Online.calendar A.plan) (pt).data m = _
+ have ptr := entry.pointer
+ change LevelCalendar.header (Online.calendar A.plan) (pt).data m =
+ (levelStart L (A.levelsPerBlock*(Online.calendar A.plan).level (m (pt).ordinal.val).val) : Word w) at ptr
+ rwa [ord,phase.2] at ptr
+ have ag := calendar_agree L base hg hb fit ref m p.stage.phase
+ (fun x h ↦ (raw x h).trans (suffix x h)) (total.trans count.symm) (pitch.trans stride.symm)
+ have same (e : Expr) (r : e.ReadsFrom (operandRegion A L base) (pt).data (levelStart L (A.levelsPerBlock*t)) ref) :
+ A.operand base m p.stage.phase e = e.eval (pt).data (levelStart L (A.levelsPerBlock*t)) ref := by
+ unfold Script.operand
+ rw [state]; exact (e.eval_eq_of_reads r ag).symm
+ apply SourceOnline.launch_of_evaluation A base L hg hb fit m p.stage room active
+ · exact (same _ ev.startReads).trans ev.start
+ · exact (same _ ev.stopReads).trans ev.stop
+ · intro j; exact (same _ (ev.paramReads j)).trans (ev.params j)
+
+end BlockPlanner.Window
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorWorkspaceBranchCut.lean b/lean/OAI/Computability/VPVNP/CompressorWorkspaceBranchCut.lean
new file mode 100644
index 0000000000..2fff7b7dd8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorWorkspaceBranchCut.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.CompressorOnlineBranchCut
+import OAI.Computability.VPVNP.CompressorSourceBankFrame
+
+/-! # Native branch cuts through the six-word online workspace frame
+
+The framing prologue reads the installed pointer bank at each call. The
+inverse below uses the actual choice stream up to the worker's closing
+guard. Each successful active call preserves the pointer bank before the
+next prologue reads it. The remaining calls can use arbitrary choice bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.OnlineWorkspace
+
+open BurstRAM Schedule BranchSegments
+
+variable {w d initial phases : ℕ} {C : Catalog d} (plan : Online.Config C initial phases)
+variable (pub : Fin 11 → Word w)
+local notation "pt" => ports (C := C) pub
+local notation "q" => initial+phases
+local notation "inner" => Online.program plan pt
+local notation "outer" => program plan pub
+local notation "installed" => Workspace.Installed (arity C) (pub 2)
+
+variable {cap : ℕ} {st : Option (Word w)} {m : Memory w}
+
+/-- Lift a verified sequence of calls with its full report log. -/
+def framedSegment (s : Segment inner cap st m) (bank : Banks (arity C) (pub 2) m s.logs) :
+ Segment outer (cap+24) st m :=
+ ⟨s.bits, framed (pub 2) m s.logs, run_framed plan pub cap st m s.bits s.logs s.run bank⟩
+
+@[simp] theorem framedSegment_state (s : Segment inner cap st m) (bank : Banks (arity C) (pub 2) m s.logs) :
+ (framedSegment plan pub s bank).state = s.state := (framed_effect _ _ _ _).1
+
+@[simp] theorem framedSegment_memory (s : Segment inner cap st m) (bank : Banks (arity C) (pub 2) m s.logs) :
+ (framedSegment plan pub s bank).memory = s.memory := (framed_effect _ _ _ st).2.1
+
+/-- A successful source call from a reachable active cursor preserves the
+six pointers that the next physical call reads. -/
+def WorkerBanks (i : Fin d) (data : Fin (C i).params → Word w) (bound : Word w)
+ (cap : ℕ) (inv : Word w → Memory w → Prop) : Prop :=
+ let P := ((C i).table.instantiate w data).program
+ ∀ cursor mem bs rep, inv cursor mem → cursor < bound → installed mem →
+ execute P cap (P.start cursor) mem bs = some rep → installed (after mem rep.events)
+
+/-- A successful prefix either ends inside the worker with every visited
+call preserving the low addresses, or contains an entire valid term row. -/
+theorem workerPrefixCases (i : Fin d) (data : Fin (C i).params → Word w)
+ (bound : Word w) (cap f : ℕ) (inv : Word w → Memory w → Prop)
+ (step : Online.WorkerStep pt i data bound cap f inv) (bankStep : WorkerBanks pub i data bound cap inv)
+ (lo : ℕ) (keep : let P := ((C i).table.instantiate w data).program
+ ∀ st mem bs rep, inv st mem → st < bound → execute P cap (P.start st) mem bs = some rep →
+ ∀ x < lo, after mem rep.events x = mem x)
+ (fits : Online.N d q ≤ 2^w) (cursor : Word w) (mem : Memory w)
+ (ready : Schedule.Ready C i pt data bound mem) (hinv : inv cursor mem) (bank : installed mem)
+ (bits : List (List Bool)) (logs : List (Report w))
+ (run : runSegment outer (cap+24) (some cursor) mem bits = some logs) :
+ let P := ((C i).table.instantiate w data).program
+ (SourceBankFrame.Stable lo mem logs ∧ (endState (some cursor) logs).isSome) ∨
+ ∃ dataBits tail raw, bits = dataBits ++ [] :: tail ∧
+ runSegment P f (some cursor) mem dataBits = some raw ∧ ValidTrace C i pt data bound cursor mem raw := by
+ intro P
+ induction bits generalizing cursor mem logs with
+ | nil =>
+ change some [] = some logs at run
+ obtain rfl := Option.some.inj run
+ exact Or.inl ⟨trivial,rfl⟩
+ | cons b bs ih =>
+ rw [runSegment, execute_dispatch plan pub cursor mem b _ bank, Nat.add_sub_cancel] at run
+ cases first : execute inner cap ((inner).start cursor) mem b with
+ | none => simp [first] at run
+ | some actual =>
+ simp only [first,Option.map_some,Option.map_eq_some_iff] at run
+ obtain ⟨rest,suffix,rfl⟩ := run
+ obtain ⟨_,_,_,hm,hs⟩ := Workspace.report_effect (pub 2) mem actual
+ rw [hm,hs] at suffix
+ by_cases live : cursor < bound
+ · have guard : cursor < stopWord (pt).activeFrame mem := ready.2.1.symm ▸ live
+ obtain ⟨_,rep,source,he⟩ := (Online.worker_active_iff plan pt i cursor mem b ready.1 fits guard cap actual).mp first
+ rw [ready.2.2] at source
+ obtain ⟨small,next,returned,ready',inv'⟩ := step cursor mem b rep ready hinv live source
+ have bank' := bankStep cursor mem b rep hinv live bank source
+ have eqn : actual = Online.activeReport C q pt i mem rep := he
+ obtain ⟨res,memory,_⟩ := Online.active_effect (initial := initial) (phases := phases) (C := C) pt i mem rep returned
+ rw [eqn,res,memory] at suffix
+ rcases ih next (after mem rep.events) ready' inv' bank' rest suffix with ⟨stable,cont⟩ | ⟨db,tail,raw,hbits,hraw,hvalid⟩
+ · left
+ rw [SourceBankFrame.Stable,endState,hm,hs,eqn,res,memory]
+ exact ⟨⟨keep cursor mem b rep hinv live source,stable⟩,cont⟩
+ · right
+ refine ⟨b::db,tail,rep::raw,congrArg (List.cons b) hbits,?_,⟨ready,live,next,returned,hvalid⟩⟩
+ have short : execute P f (P.start cursor) mem b = some rep := execute_at_cap source small
+ simp only [runSegment,short,returned,hraw,Option.map_some]
+ · have closed : stopWord (pt).activeFrame mem ≤ cursor := ready.2.1.symm ▸ Nat.le_of_not_gt live
+ obtain ⟨_,rfl,_⟩ := (Online.worker_stop_iff plan pt i cursor mem b ready.1 fits closed cap actual).mp first
+ exact Or.inr ⟨[],bs,[],rfl,rfl,ready,Nat.le_of_not_gt live⟩
+
+variable {state : Word w} {I : Type*}
+
+/-- Invert the three forced descriptor calls and the physical term worker on
+an arbitrary accepting tape, up to the return to the level calendar. -/
+def selectorCut (bounds : Online.Run.ControlBounds plan cap (w := w))
+ (htag : m (pt).tag.val = LiveStageLink.tagWord w (Online.calendarIndex d q))
+ (entry : Online.Run.RowStart plan pt cap m) (active : m (pt).ordinal.val < m (pt).rows.val)
+ (prepBanks : Banks (arity C) (pub 2) m (Online.preparation plan pt m entry.phase))
+ (preparedBank : installed (Directory.prepared C pt (Online.rowInput plan pt m entry.phase)))
+ (workerBank : let x := Online.rowInput plan pt m entry.phase
+ WorkerBanks pub entry.worker (Directory.words C pt entry.worker x) (Directory.bound C pt x) cap entry.invariant)
+ (rows : I → Online.Run.Step d q w) (valid : ∀ i, (rows i).Valid plan pt cap m)
+ (rowBanks : ∀ i, Banks (arity C) (pub 2) m (Online.rowLog plan pt m (rows i).phase (rows i).row))
+ (decode : ∀ s : Online.Run.Step d q w, s.Valid plan pt cap m → s.phase = entry.phase →
+ s.row.worker = entry.worker → s.row.fuel = entry.fuel → ∃ i, s.row.choices = (rows i).row.choices)
+ (count : ℕ) (lengths : ∀ i, (rows i).row.choices.length = count)
+ (unique : Function.Injective fun i => (rows i).row.choices) :
+ Cut outer (cap+24) (some state) m I where
+ part i := framedSegment plan pub (Online.Run.oneRow plan pt bounds htag (rows i) (valid i)) (rowBanks i)
+ separate := (Online.Run.selectorCut plan pt bounds htag entry active rows valid decode count lengths unique
+ (state := state)).separate
+ cover bits logs run halt := by
+ let x := Online.rowInput plan pt m entry.phase
+ have prep : runSegment inner cap (some state) m (List.replicate 3 []) = some (Online.preparation plan pt m entry.phase) := by
+ change runSegment _ _ _ _ ([] :: [] :: [] :: []) = _
+ rw [Online.prepare_segment plan pt state m entry.phase htag bounds.tags active entry.calendarPhase entry.liveRow
+ bounds.calendar entry.recipeCap bounds.launch []]
+ simp [runSegment]
+ have hp := run_framed plan pub cap (some state) m _ _ prep prepBanks
+ obtain ⟨tail,reps,hbits,rfl,suffix⟩ := LiveProgram.split_empty_segment hp run halt
+ obtain ⟨st,mem⟩ := Online.preparation_effect plan pt state m entry.phase
+ obtain ⟨st',mem',_⟩ := framed_effect (pub 2) m (Online.preparation plan pt m entry.phase) (some state)
+ rw [st',mem',st,mem] at suffix
+ rw [endState_append,st',st] at halt
+ have hw := workerPrefixCases plan pub entry.worker _ _ cap entry.fuel entry.invariant entry.dataStep workerBank
+ 0 (fun _ _ _ _ _ _ _ _ hx => (Nat.not_lt_zero _ hx).elim) bounds.tags _ _ entry.ready entry.initialInv
+ preparedBank tail reps suffix
+ obtain ⟨db,rest,raw,hb,hr,hv⟩ := hw.resolve_left (fun h => by simpa [halt] using h.2)
+ let s : Online.Run.Step d q w := ⟨entry.phase, ⟨x, entry.worker, entry.fuel, db, raw⟩⟩
+ have valid' : s.Valid plan pt cap m := ⟨entry.calendarPhase,active,rfl,
+ ⟨by simp [s,x,Online.rowInput,writeMemory],entry.liveRow,entry.positiveFuel,hr,hv⟩,entry.recipeCap,entry.dataCap⟩
+ obtain ⟨i, selected⟩ := decode s valid' rfl rfl rfl
+ change db = (rows i).row.choices at selected
+ exact ⟨i,rest,by simpa [Online.rowChoices,framedSegment,Online.Run.oneRow,hb,selected] using hbits⟩
+
+end CompressorRecords.OnlineWorkspace
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorWorkspaceCore.lean b/lean/OAI/Computability/VPVNP/CompressorWorkspaceCore.lean
new file mode 100644
index 0000000000..df944265d7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorWorkspaceCore.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.CompressorWorkspaceIntervals
+import OAI.Computability.VPVNP.RAMFinite
+
+/-! # Source reports of actual framed descriptor intervals
+
+The six pointer reads are charged once per source call. The core clock can
+be smaller than the clock of the framed table. Along concatenation the second
+interval sees exactly the memory and cursor returned by the first. This
+retains the actual core runs for charging work across repeated block visits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.OnlineWorkspace
+open BurstRAM BlockPlanner Schedule BranchSegments
+
+variable {w clock cap : ℕ} {A : Script} {pub : Fin 11 → Word w}
+local notation "pt" => ports (C := A.catalog) pub
+local notation "inner" => Online.program A.plan pt
+local notation "outer" => program A.plan pub
+
+theorem framed_append (base : Word w) (m : Memory w) (rs ts : List (Report w)) :
+ framed base m (rs++ts) = framed base m rs ++ framed base (after m (eventLog rs)) ts := by
+ induction rs generalizing m with
+ | nil => rfl
+ | cons r rs ih =>
+ simp only [List.cons_append,framed,ih,eventLog,List.flatMap_cons,after,List.foldl_append]
+
+/-- A selected physical interval retains the inner machine's true reports
+and native execution on its own private clock. -/
+structure Core (A : Script) (pub : Fin 11 → Word w) {st : Option (Word w)} {m : Memory w} (s : Segment (program A.plan pub) clock st m) (cap : ℕ) where
+ /-- Reports produced by the inner online program on the segment's branch tapes and private
+ clock. -/
+ logs : List (Report w)
+ run : runSegment (Online.program A.plan (ports (C := A.catalog) pub)) cap st m s.bits = some logs
+ frame : s.logs = framed (pub 2) m logs
+
+namespace Core
+
+variable {st : Option (Word w)} {m : Memory w} {s : Segment (program A.plan pub) clock st m} (source : Core A pub s cap)
+
+theorem state : endState st source.logs = s.state := by
+ rw [Segment.state,source.frame,(framed_effect (pub 2) m source.logs st).1]
+
+theorem memory : after m (eventLog source.logs) = s.memory := by
+ rw [Segment.memory,source.frame,(framed_effect (pub 2) m source.logs st).2.1]
+
+/-- Join consecutive core runs by passing the first segment's returned state and memory to the
+second. -/
+def append {t : Segment outer clock s.state s.memory} (next : Core A pub t cap) : Core A pub (s.append t) cap where
+ logs := source.logs ++ next.logs
+ run := by
+ change runSegment _ _ _ _ (s.bits++t.bits) = _
+ rw [PrimedSchedule.runSegment_append,source.run,Option.bind_some,source.state,source.memory,next.run]
+ rfl
+ frame := by
+ change s.logs++t.logs = _
+ rw [framed_append,source.memory,← next.frame,← source.frame]
+
+@[simp] theorem cost_append {t : Segment outer clock s.state s.memory} (next : Core A pub t cap) :
+ RAMBuckets.cost Report.probes (source.append next).logs =
+ RAMBuckets.cost Report.probes source.logs + RAMBuckets.cost Report.probes next.logs :=
+ RAMBuckets.cost_append ..
+
+/-- The chosen core clock bounds every actual source report, even when the
+enclosing table gives the worker a larger clock. -/
+theorem ticks (r : Report w) (hr : r ∈ source.logs) : r.events.length < cap :=
+ localSegment_event_bound ((runSegment_iff ..).mp source.run).1 r hr
+
+end Core
+
+/-- Recover the inner reports and execution of a segment framed using the installed pointer
+bank. -/
+def framedSegmentCore {st : Option (Word w)} {m : Memory w}
+ (s : Segment inner cap st m) (bank : Banks (arity A.catalog) (pub 2) m s.logs) :
+ Core A pub (framedSegment A.plan pub s bank) cap := ⟨s.logs,s.run,rfl⟩
+
+variable {m : Memory w}
+
+/-- The exact core reports of the closing physical call. -/
+def terminalCore {small : ℕ} (bounds : Online.Run.ControlBounds A.plan cap (w := w))
+ (smallBounds : Online.Run.ControlBounds A.plan small (w := w))
+ (htag : m (pt).tag.val = LiveStageLink.tagWord w (Online.calendarIndex A.size A.size))
+ (bank : Workspace.Installed (arity A.catalog) (pub 2) m) (stop : m (pt).rows.val ≤ m (pt).ordinal.val) :
+ Core A pub (terminalSegment A pub bounds htag bank stop) small where
+ logs := [Online.linked pt (Online.calendarIndex A.size A.size) (LevelCalendar.closedReport (pt).data m)]
+ run := by
+ change runSegment inner small (some 0) m [[]] = _
+ rw [runSegment,Online.calendar_stop A.plan pt 0 m htag smallBounds.tags stop (by have := smallBounds.calendar; omega)]
+ rfl
+ frame := rfl
+
+theorem terminal_cost {small : ℕ} (bounds : Online.Run.ControlBounds A.plan cap (w := w))
+ (smallBounds : Online.Run.ControlBounds A.plan small (w := w))
+ (htag : m (pt).tag.val = LiveStageLink.tagWord w (Online.calendarIndex A.size A.size))
+ (bank : Workspace.Installed (arity A.catalog) (pub 2) m) (stop : m (pt).rows.val ≤ m (pt).ordinal.val) :
+ RAMBuckets.cost Report.probes (terminalCore (A := A) (pub := pub) bounds smallBounds htag bank stop).logs = 4 := by
+ have hp := (Online.terminal_effect (d := A.size) (initial := A.initial.length) (phases := A.block.length) pt m).2.2.1
+ change 1+_+0=4
+ rw [hp]
+
+end CompressorRecords.OnlineWorkspace
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CompressorWorkspaceIntervals.lean b/lean/OAI/Computability/VPVNP/CompressorWorkspaceIntervals.lean
new file mode 100644
index 0000000000..c1b29e2b20
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CompressorWorkspaceIntervals.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.CompressorSourceSequence
+import OAI.Computability.VPVNP.CompressorWorkspaceBranchCut
+import OAI.Computability.VPVNP.LiveStagePaths
+
+/-! # Framed descriptor intervals and the terminal calendar call -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open BurstRAM Schedule BranchSegments BlockPlanner DescriptorSpace
+open scoped Fin.CommRing
+
+variable {w cap : ℕ}
+
+theorem SourceBankFrame.Stable.framed {lo : ℕ} {m : Memory w} {rs : List (Report w)}
+ (base : Word w) (h : SourceBankFrame.Stable lo m rs) :
+ SourceBankFrame.Stable lo m (OnlineWorkspace.framed base m rs) := by
+ induction rs generalizing m with
+ | nil => trivial
+ | cons r rs ih =>
+ rw [OnlineWorkspace.framed,SourceBankFrame.Stable,(Workspace.report_effect base m r).2.2.2.1]
+ exact ⟨h.1,ih h.2⟩
+
+private theorem returning_reports {Q : Type*} {P : BurstRAM.Program w Q} {st : Option (Word w)}
+ {m : Memory w} {bs : List (List Bool)} {rs : List (Report w)}
+ (run : runSegment P cap st m bs = some rs) (cont : endState st rs ≠ none) :
+ ∀ r ∈ rs, r.result ≠ none ∧ r.events.length < cap := by
+ induction bs generalizing st m rs with
+ | nil => change some [] = some rs at run; obtain rfl := Option.some.inj run; simp
+ | cons b bs ih =>
+ cases st with
+ | none => contradiction
+ | some st =>
+ cases hr : execute P cap (P.start st) m b with
+ | none => simp [runSegment,hr] at run
+ | some r =>
+ simp only [runSegment,hr,Option.map_eq_some_iff] at run
+ obtain ⟨tail,rest,rfl⟩ := run
+ rw [List.forall_mem_cons]
+ refine ⟨⟨?_,(execute_spec hr).1.length_lt⟩,ih rest cont⟩
+ intro halted
+ rw [halted] at rest
+ cases bs with
+ | nil => change some [] = some tail at rest; obtain rfl := Option.some.inj rest; exact cont halted
+ | cons => contradiction
+
+/-- Every report of a returning segment fits the enclosing link: the link
+adds transfer instructions only to the component's accepting report. -/
+theorem BranchSegments.Segment.link_room {Q : Type*} {P : BurstRAM.Program w Q} {st : Option (Word w)}
+ {m : Memory w} (s : Segment P cap st m) (cont : s.state ≠ none)
+ {d : ℕ} (next : Fin d → Option (Fin d)) (addr : Word w) (stage : Fin d) :
+ ∀ r ∈ s.logs, LiveStageLink.room next addr stage cap r := by
+ intro r hr
+ have ⟨ret,hlen⟩ := returning_reports s.run cont r hr
+ cases eqn : r.result with
+ | none => exact (ret eqn).elim
+ | some st => simpa only [LiveStageLink.room,LiveStageLink.exitReport,eqn] using hlen
+
+namespace OnlineWorkspace
+
+variable (A : Script) (pub : Fin 11 → Word w)
+local notation "pt" => Workspace.ports (arity A.catalog) (pub 2)
+local notation "prog" => program A.plan pub
+variable {m : Memory w} (bounds : Online.Run.ControlBounds A.plan cap (w := w))
+variable (htag : m (Workspace.ports (arity A.catalog) (pub 2)).tag.val =
+ LiveStageLink.tagWord w (Online.calendarIndex A.size A.size)) (steps : List (Online.Run.Step A.size A.size w))
+variable (valid : Online.Run.Interval A.plan (Workspace.ports (arity A.catalog) (pub 2)) cap m steps)
+variable (stable : SourceBankFrame.Stable ((pub 2).val+6) m (Online.Run.intervalLog A.plan (Workspace.ports (arity A.catalog) (pub 2)) m steps))
+variable (bank : Workspace.Installed (arity A.catalog) (pub 2) m)
+
+/-- Run the chronological interval obtained from the actual source packets by
+`SourceOnline.interval_stable`, reading the six stable pointers on every call. -/
+def intervalSegment : Segment prog (cap+24) (some 0) m :=
+ framedSegment A.plan pub (Online.Run.intervalSegment A.plan pt bounds htag steps valid) (stable.banks bank)
+
+@[simp] theorem intervalSegment_state :
+ (intervalSegment A pub bounds htag steps valid stable bank).state = some 0 := by
+ exact (framedSegment_state A.plan pub (Online.Run.intervalSegment A.plan pt bounds htag steps valid)
+ (stable.banks bank)).trans (Online.Run.interval_state_zero A.plan pt bounds htag steps valid)
+
+@[simp] theorem intervalSegment_memory :
+ (intervalSegment A pub bounds htag steps valid stable bank).memory = Online.Run.finalMemory (C := A.catalog) pt m steps := by
+ exact (framedSegment_memory A.plan pub (Online.Run.intervalSegment A.plan pt bounds htag steps valid)
+ (stable.banks bank)).trans (Online.Run.interval_memory A.plan pt bounds htag steps valid)
+
+theorem intervalSegment_stable :
+ SourceBankFrame.Stable ((pub 2).val+6) m (intervalSegment A pub bounds htag steps valid stable bank).logs :=
+ stable.framed _
+
+theorem intervalSegment_bank :
+ Workspace.Installed (arity A.catalog) (pub 2) (intervalSegment A pub bounds htag steps valid stable bank).memory := by
+ let s := intervalSegment A pub bounds htag steps valid stable bank
+ have h := (intervalSegment_stable A pub bounds htag steps valid stable bank).installed bank s.logs.length
+ rw [List.take_length] at h
+ exact h
+
+theorem intervalSegment_quiet (quiet : ∀ s ∈ steps, s.row.choices = List.replicate s.row.choices.length []) :
+ let segment := intervalSegment A pub bounds htag steps valid stable bank
+ segment.bits = List.replicate segment.bits.length [] := Online.Run.quietInterval steps quiet
+
+/-- The one final framed calendar call executes its empty tape and halts. -/
+def terminalSegment (stop : m (pt).rows.val ≤ m (pt).ordinal.val) : Segment prog (cap+24) (some 0) m where
+ bits := [[]]
+ logs := [Workspace.report (pub 2) m (Online.linked pt (Online.calendarIndex A.size A.size)
+ (LevelCalendar.closedReport (pt).data m))]
+ run := by
+ have hc := Online.calendar_stop A.plan pt 0 m htag bounds.tags stop (by have := bounds.calendar; omega : _ ≤ cap)
+ rw [runSegment,execute_dispatch A.plan pub 0 m [] _ bank,Nat.add_sub_cancel,hc]
+ rfl
+
+@[simp] theorem terminalSegment_state (stop : m (pt).rows.val ≤ m (pt).ordinal.val) :
+ (terminalSegment A pub bounds htag bank stop).state = none :=
+ (Online.terminal_effect (d := A.size) (initial := A.initial.length) (phases := A.block.length) pt m).1
+
+@[simp] theorem terminalSegment_memory (stop : m (pt).rows.val ≤ m (pt).ordinal.val) :
+ (terminalSegment A pub bounds htag bank stop).memory = m := by
+ simp only [Segment.memory,terminalSegment,eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil]
+ rw [(Workspace.report_effect _ _ _).2.2.2.1]
+ exact (Online.terminal_effect (d := A.size) (initial := A.initial.length) (phases := A.block.length) pt m).2.1
+
+theorem terminalSegment_stable (stop : m (pt).rows.val ≤ m (pt).ordinal.val) (lo : ℕ) :
+ SourceBankFrame.Stable lo m (terminalSegment A pub bounds htag bank stop).logs := by
+ let r := Online.linked pt (Online.calendarIndex A.size A.size) (LevelCalendar.closedReport (pt).data m)
+ change (∀ x < lo, after m (Workspace.report (pub 2) m r).events x = m x) ∧ True
+ rw [(Workspace.report_effect _ _ _).2.2.2.1]
+ have hm := (Online.terminal_effect (d := A.size) (initial := A.initial.length) (phases := A.block.length) pt m).2.1
+ exact ⟨fun x _ => congrFun hm x,trivial⟩
+
+/-- The terminal calendar call fits with all three outer transfer instructions. -/
+theorem terminalSegment_room (stop : m (pt).rows.val ≤ m (pt).ordinal.val)
+ {d : ℕ} (next : Fin d → Option (Fin d)) (addr : Word w) (stage : Fin d) :
+ ∀ r ∈ (terminalSegment A pub bounds htag bank stop).logs, LiveStageLink.room next addr stage (cap+24) r := by
+ let src := Online.linked pt (Online.calendarIndex A.size A.size) (LevelCalendar.closedReport (pt).data m)
+ let r := Workspace.report (pub 2) m src
+ intro rep hr
+ obtain rfl : rep = r := List.mem_singleton.mp hr
+ have small := Online.calendar_stop A.plan pt 0 m htag bounds.tags stop (cap := cap-3)
+ (by have := bounds.calendar; omega)
+ have length : src.events.length < cap-3 := (execute_spec small).1.length_lt
+ have framedLen : r.events.length = 24+src.events.length := (Workspace.report_effect _ _ _).1
+ have halted : r.result = none :=
+ (Workspace.report_effect _ _ _).2.2.2.2.trans
+ (Online.terminal_effect (d := A.size) (initial := A.initial.length) (phases := A.block.length) pt m).1
+ cases ht : next stage <;>
+ simp only [LiveStageLink.room,LiveStageLink.exitReport,halted,ht,LiveStageLink.transferEvents,List.length_append,
+ List.length_cons,List.length_nil,framedLen] <;> omega
+
+end OnlineWorkspace
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ConfigurationClosure.lean b/lean/OAI/Computability/VPVNP/ConfigurationClosure.lean
new file mode 100644
index 0000000000..4cfcea33b8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ConfigurationClosure.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.SpectralRelabel
+import OAI.Computability.VPVNP.SubpartyNormalization
+import OAI.Computability.VPVNP.SpectralRealizable
+import OAI.Computability.VPVNP.ConfigurationLimits
+import Mathlib.Logic.Equiv.Set
+
+/-! # Closure of finite wire configurations under coordinatewise limits
+
+Any assignment of the finite label set to ambient parties factors through a
+surjection onto a numbered set of used parties. Their numbering may vary, but
+there are only finitely many possible numbers and maps. Separating the used
+parties from their complement allows the spectrum to be normalized on them.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+open Filter Set
+open scoped Topology
+
+private abbrev PartyPattern (ι : Type*) [Fintype ι] :=
+ (n : Fin (Fintype.card ι + 1)) × {f : ι → Fin n.val // Function.Surjective f}
+
+private theorem exists_party_pattern {ι J : Type*} [Fintype ι] (f : ι → J) :
+ ∃ p : PartyPattern ι, ∃ e : (Fin p.1.val ⊕ ((Set.range f)ᶜ : Set J)) ≃ J,
+ ∀ i, e (.inl (p.2.1 i)) = f i := by
+ classical
+ let used := Set.range f
+ let : Fintype used := Fintype.ofFinite used
+ let e := Fintype.equivFin used
+ let g := e ∘ Set.rangeFactorization f
+ have hg : Function.Surjective g := e.surjective.comp Set.rangeFactorization_surjective
+ have hcard : Fintype.card used ≤ Fintype.card ι :=
+ Fintype.card_le_of_surjective (Set.rangeFactorization f) Set.rangeFactorization_surjective
+ refine ⟨⟨⟨Fintype.card used, by omega⟩, g, hg⟩,
+ (Equiv.sumCongr e.symm (Equiv.refl _)).trans (Equiv.Set.sumCompl used), ?_⟩
+ intro i
+ simp [g, used]
+
+variable {k : Type*} [Field k] {ι : Type*} [Fintype ι]
+
+private theorem normalize_realization {d : ι → ι → ℝ} (w : WireRealization k d)
+ {a b : ι} (hab : d a b ≠ 0) :
+ ∃ p : PartyPattern ι, SpectralPoint.Realizes k p.2.1 (fun i ↦ d i.1 i.2) := by
+ classical
+ obtain ⟨p, e, he⟩ := exists_party_pattern w.label
+ have : Nonempty (Fin p.1.val) := ⟨p.2.1 a⟩
+ let : Fintype ((range w.label)ᶜ : Set w.Parties) := Fintype.ofFinite _
+ let H := w.spectrum.relabel e
+ have hwire (i j : ι) : H.wireDistance (.inl (p.2.1 i)) (.inl (p.2.1 j)) =
+ w.spectrum.wireDistance (w.label i) (w.label j) := by
+ rw [show H = w.spectrum.relabel e from rfl, w.spectrum.wireDistance_relabel, he, he]
+ have hpos : 0 < H.subpartyExponent := by
+ have hw : 0 < w.spectrum.wireDistance (w.label a) (w.label b) := by
+ refine lt_of_le_of_ne (w.spectrum.wireDistance_nonneg _ _) ?_
+ intro hz
+ exact hab (by rw [w.distances, ← hz, mul_zero])
+ rw [← hwire] at hw
+ exact hw.trans_le (H.wireDistance_le_subpartyExponent _ _)
+ refine ⟨p, H.subpartyNormalization hpos, w.scale * H.subpartyExponent,
+ mul_pos w.scale_pos hpos, ?_⟩
+ rintro ⟨i, j⟩
+ dsimp only
+ rw [H.subpartyNormalization_wireDistance hpos, hwire, w.distances]
+ field_simp [hpos.ne']
+
+omit [Fintype ι] in
+/-- Lemma 2.3. A coordinatewise limit of realizable wire configurations on a
+fixed finite label set is realizable at a common positive scale. -/
+theorem RealizableUpToScale.limit [Finite ι] {d : ι → ι → ℝ} (seq : ℕ → ι → ι → ℝ)
+ (hseq : ∀ m, RealizableUpToScale k (seq m))
+ (hlim : ∀ i j, Tendsto (fun m ↦ seq m i j) atTop (𝓝 (d i j))) : RealizableUpToScale k d := by
+ classical
+ let := Fintype.ofFinite ι
+ by_cases hzero : ∀ i j, d i j = 0
+ · obtain ⟨w⟩ := hseq 0
+ let center : w.Parties := Classical.ofNonempty
+ exact ⟨{
+ Parties := w.Parties
+ spectrum := w.spectrum
+ label := fun _ ↦ center
+ scale := 1
+ scale_pos := zero_lt_one
+ distances := fun i j ↦ by rw [hzero, w.spectrum.wireDistance_self, mul_zero] }⟩
+ obtain ⟨a, ha⟩ := not_forall.mp hzero
+ obtain ⟨b, hab⟩ := not_forall.mp ha
+ have : Nonempty ι := ⟨a⟩
+ have hd : (fun i : ι × ι ↦ d i.1 i.2) ≠ 0 := fun h ↦ hab (congrFun h (a, b))
+ have hpatterns : ∃ᶠ m in atTop, ∃ p : PartyPattern ι,
+ SpectralPoint.Realizes k p.2.1 (fun i ↦ seq m i.1 i.2) := by
+ apply ((hlim a b).eventually_ne hab).frequently.mono
+ intro m hm
+ obtain ⟨w⟩ := hseq m
+ exact normalize_realization w hm
+ obtain ⟨p, G, t, ht, heq⟩ := SpectralPoint.realizes_limit_of_finite_patterns
+ (fun p : PartyPattern ι ↦ Fin p.1.val) (fun p ↦ p.2.1) (fun p ↦ p.2.2)
+ hd (fun m i ↦ seq m i.1 i.2) hpatterns (fun i ↦ hlim i.1 i.2)
+ have : Nonempty (Fin p.1.val) := ⟨p.2.1 a⟩
+ have : Nontrivial (Fin p.1.val) := G.nontrivial_parties
+ exact ⟨{
+ Parties := Fin p.1.val
+ spectrum := G
+ label := p.2.1
+ scale := t
+ scale_pos := ht
+ distances := fun i j ↦ (heq (i, j)).symm }⟩
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ConfigurationCompletion.lean b/lean/OAI/Computability/VPVNP/ConfigurationCompletion.lean
new file mode 100644
index 0000000000..d9431f872f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ConfigurationCompletion.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.ConfigurationClosure
+import OAI.Computability.VPVNP.GrassmannCompactness
+import Mathlib.Topology.MetricSpace.Completion
+
+/-!
+# Realizable configurations in completions and limits of rescaled arrays
+
+In Corollary 2.5 and Lemma 4.1 of *VP and VNP differ over every field*,
+realizability of finite configurations passes to the metric completion.
+Corollary 5.2 uses the same closedness to turn failure to realize the
+distances of a cube into uniform exclusion over a class of metric spaces.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor.RealizableUpToScale
+
+open Filter Set
+open scoped Topology
+
+variable {k : Type*} [Field k] {ι : Type*} [Fintype ι]
+
+/-- The coordinatewise closed set of realizable distance matrices on a
+fixed finite label set. -/
+theorem isClosed : IsClosed {d : ι → ι → ℝ | RealizableUpToScale k d} :=
+ IsSeqClosed.isClosed fun x _ hx hlim ↦ RealizableUpToScale.limit x hx
+ fun i j ↦ tendsto_pi_nhds.mp (tendsto_pi_nhds.mp hlim i) j
+
+/-- Realizability of every finite configuration passes from a pseudometric
+space to its metric completion. -/
+theorem completion {X : Type*} [PseudoMetricSpace X]
+ (hX : ∀ y : ι → X, RealizableUpToScale k (fun i j ↦ dist (y i) (y j)))
+ (z : ι → UniformSpace.Completion X) :
+ RealizableUpToScale k (fun i j ↦ dist (z i) (z j)) := by
+ let D (w : ι → UniformSpace.Completion X) := fun i j ↦ dist (w i) (w j)
+ have hc : Continuous D := continuous_pi fun i ↦ continuous_pi fun j ↦
+ (continuous_apply i).dist (continuous_apply j)
+ let embed (y : ι → X) : ι → UniformSpace.Completion X := fun i ↦ ↑(y i)
+ have hdense : DenseRange embed :=
+ DenseRange.piMap (fun _ : ι ↦ UniformSpace.Completion.denseRange_coe (α := X))
+ refine hdense.induction_on (p := fun w ↦ RealizableUpToScale k (D w)) z
+ (isClosed.preimage hc) ?_
+ intro y
+ simpa only [D, embed, UniformSpace.Completion.dist_eq] using hX y
+
+/-- A class of spaces whose finite configurations are realizable uniformly
+excludes any distance matrix which fails realizability, allowing arbitrary
+positive rescalings of the marked configurations. -/
+theorem notMem_closure_markedDistances {κ : Type*} (X : κ → Type*)
+ [∀ j, PseudoMetricSpace (X j)]
+ (hX : ∀ (j : κ) (y : ι → X j), RealizableUpToScale k (fun a b ↦ dist (y a) (y b)))
+ {d : ι → ι → ℝ} (hd : ¬ RealizableUpToScale k d) :
+ d ∉ closure (VPVNP.Grassmann.markedDistances X ι) := by
+ intro hm
+ apply hd
+ refine closure_minimal (t := {D : ι → ι → ℝ | RealizableUpToScale k D}) ?_ isClosed hm
+ rintro _ ⟨j, scale, hscale, y, rfl⟩
+ exact (hX j y).smul hscale
+
+end WireTensor.RealizableUpToScale
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ConfigurationLimits.lean b/lean/OAI/Computability/VPVNP/ConfigurationLimits.lean
new file mode 100644
index 0000000000..b45322b807
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ConfigurationLimits.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.SpanningStar
+import OAI.Computability.VPVNP.SpectrumCompactness
+import Mathlib.Analysis.SpecialFunctions.Log.Base
+import Mathlib.Topology.Instances.Real.Lemmas
+import Mathlib.Topology.Order.Lattice
+import Mathlib.Topology.Order.LiminfLimsup
+
+/-! # Limits of scaled finite spectral configurations
+
+The compactness step in Lemma 2.3 uses a positive lower bound on the diameter
+of a normalized configuration. For a fixed set of `k ≥ 2` used parties, the
+spanning-tree estimate supplies the lower bound `1 / (k - 1)`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+open Filter Set
+open scoped Topology
+
+/-- A nonzero coordinatewise limit of scaled configurations is realized by a
+point of the same compact spectrum at a positive scale. The coordinates can
+be the ordered pairs of a finite label set. -/
+theorem exists_scaled_configuration_limit {ι K : Type*} [Fintype ι] [Nonempty ι]
+ [TopologicalSpace K] {spectrum : Set K} (hcompact : IsCompact spectrum)
+ (wire : K → ι → ℝ) (hwire : ∀ i, Continuous (fun k ↦ wire k i))
+ {x : ℕ → K} {r : ℕ → ℝ} (hx : ∀ m, x m ∈ spectrum) (hr : ∀ m, 0 ≤ r m)
+ {δ : ℝ} (hδ : 0 < δ)
+ (hnorm : ∀ m, δ ≤ Finset.univ.sup' Finset.univ_nonempty (wire (x m)))
+ {v : ι → ℝ} (hv : v ≠ 0)
+ (hlim : ∀ i, Tendsto (fun m ↦ r m * wire (x m) i) atTop (𝓝 (v i))) :
+ ∃ k ∈ spectrum, ∃ t : ℝ, 0 < t ∧ ∀ i, t * wire k i = v i := by
+ classical
+ let diameter (y : ι → ℝ) : ℝ := Finset.univ.sup' Finset.univ_nonempty y
+ have hdiam : Tendsto (fun m ↦ diameter (fun i ↦ r m * wire (x m) i)) atTop
+ (𝓝 (diameter v)) :=
+ Tendsto.finset_sup'_nhds_apply Finset.univ_nonempty fun i _ ↦ hlim i
+ obtain ⟨U, hU⟩ := hdiam.bddAbove_range
+ have hscale (m : ℕ) : r m ∈ Icc 0 (U / δ) := by
+ obtain ⟨i, hi, hiδ⟩ := (Finset.le_sup'_iff Finset.univ_nonempty).mp (hnorm m)
+ refine ⟨hr m, (le_div_iff₀ hδ).2 ?_⟩
+ calc
+ r m * δ ≤ r m * wire (x m) i := mul_le_mul_of_nonneg_left hiδ (hr m)
+ _ ≤ diameter (fun j ↦ r m * wire (x m) j) := Finset.le_sup' (fun j ↦ r m * wire (x m) j) hi
+ _ ≤ U := hU ⟨m, rfl⟩
+ let realize (p : K × ℝ) : ι → ℝ := fun i ↦ p.2 * wire p.1 i
+ have hrealize : Continuous realize := continuous_pi fun i ↦
+ continuous_snd.mul ((hwire i).comp continuous_fst)
+ have hclosed : IsClosed (realize '' (spectrum ×ˢ Icc 0 (U / δ))) :=
+ ((hcompact.prod isCompact_Icc).image hrealize).isClosed
+ have hmem := hclosed.mem_of_tendsto (tendsto_pi_nhds.mpr hlim) <|
+ Eventually.of_forall fun m ↦ ⟨(x m, r m), ⟨hx m, hscale m⟩, rfl⟩
+ obtain ⟨⟨k, t⟩, ⟨hk, ht⟩, heq⟩ := hmem
+ refine ⟨k, hk, t, lt_of_le_of_ne ht.1 ?_, fun i ↦ congrFun heq i⟩
+ rintro rfl
+ apply hv
+ funext i
+ simpa [realize] using congrFun heq.symm i
+
+end Spectral
+
+namespace WireTensor.SpectralPoint
+
+open Filter Set
+open scoped NNReal Topology
+
+universe u v
+
+variable {k : Type u} [Field k] {J : Type v} [Fintype J] [Nonempty J]
+variable {ι : Type*} [Fintype ι] [Nonempty ι]
+
+/-- A nonzero coordinatewise limit of normalized configurations on fixed
+parties is realized on the same parties. Labels may repeat. -/
+theorem exists_wire_configuration_limit (label : ι → J) (F : ℕ → SpectralPoint k J)
+ {r : ℕ → ℝ} (hr : ∀ m, 0 ≤ r m) {δ : ℝ} (hδ : 0 < δ)
+ (hnorm : ∀ m, δ ≤ Finset.univ.sup' Finset.univ_nonempty
+ (fun i : ι × ι ↦ (F m).wireDistance (label i.1) (label i.2)))
+ {d : ι × ι → ℝ} (hd : d ≠ 0)
+ (hlim : ∀ i : ι × ι, Tendsto (fun m ↦ r m * (F m).wireDistance (label i.1) (label i.2))
+ atTop (𝓝 (d i))) :
+ ∃ G : SpectralPoint k J, ∃ t : ℝ, 0 < t ∧ ∀ i : ι × ι,
+ t * G.wireDistance (label i.1) (label i.2) = d i := by
+ let extended (g : Tensor.{u,v,0} k J → ℝ≥0) (i : ι × ι) :=
+ Real.logb 2 (max 1 (g (wire (label i.1) (label i.2) (Fin 2)) : ℝ))
+ have hcontinuous (i : ι × ι) : Continuous (extended · i) := by
+ let W := wire (k := k) (label i.1) (label i.2) (Fin 2)
+ have hW : Continuous (fun g : Tensor.{u,v,0} k J → ℝ≥0 ↦ (g W : ℝ)) :=
+ NNReal.continuous_coe.comp (continuous_apply W)
+ exact (continuous_const.max hW).logb
+ fun _ ↦ (zero_lt_one.trans_le (le_max_left 1 _)).ne'
+ have hdist (G : SpectralPoint k J) (i : ι × ι) :
+ extended G.value i = G.wireDistance (label i.1) (label i.2) := by
+ change Real.logb 2 (max 1 (G.wireDimension (label i.1) (label i.2) 2)) = _
+ rw [max_eq_right (G.one_le_wireDimension _ _ (by decide))]
+ rfl
+ obtain ⟨_, ⟨G, rfl⟩, t, ht, hGt⟩ := VPVNP.Spectral.exists_scaled_configuration_limit
+ (isCompact_range_value (k := k) (J := J)) extended hcontinuous
+ (x := fun m ↦ (F m).value) (fun m ↦ mem_range_self (F m)) hr hδ
+ (by simpa only [hdist] using hnorm) hd (by simpa only [hdist] using hlim)
+ exact ⟨G, t, ht, by simpa only [hdist] using hGt⟩
+
+/-- A matrix of labeled wire distances realized at one spectral point and one
+positive common scale. -/
+def Realizes (k : Type u) [Field k] {J : Type v} [Fintype J] {ι : Type*}
+ (label : ι → J) (d : ι × ι → ℝ) : Prop :=
+ ∃ G : SpectralPoint k J, ∃ t : ℝ, 0 < t ∧ ∀ i : ι × ι,
+ t * G.wireDistance (label i.1) (label i.2) = d i
+
+omit [Fintype ι] in
+/-- After normalization on the used parties, there are finitely many label
+patterns. One pattern occurs along an infinite subsequence, so its spectrum
+realizes the nonzero limiting configuration. -/
+theorem realizes_limit_of_finite_patterns [Finite ι] {P : Type*} [Finite P] (parties : P → Type v)
+ [∀ p, Fintype (parties p)] (labels : ∀ p, ι → parties p)
+ (hcover : ∀ p, Function.Surjective (labels p)) {d : ι × ι → ℝ} (hd : d ≠ 0)
+ (seq : ℕ → ι × ι → ℝ) (hseq : ∃ᶠ m in atTop, ∃ p, Realizes k (labels p) (seq m))
+ (hlim : ∀ i, Tendsto (fun m ↦ seq m i) atTop (𝓝 (d i))) :
+ ∃ p, Realizes k (labels p) d := by
+ classical
+ let := Fintype.ofFinite ι
+ obtain ⟨p, hp⟩ := frequently_exists.mp hseq
+ obtain ⟨φ, hφ, hreal⟩ := extraction_of_frequently_atTop hp
+ choose G r hr heq using hreal
+ have : Nonempty (parties p) := ⟨labels p Classical.ofNonempty⟩
+ have hsub (i : ι × ι) : Tendsto
+ (fun m ↦ r m * (G m).wireDistance (labels p i.1) (labels p i.2)) atTop (𝓝 (d i)) :=
+ ((hlim i).comp hφ.tendsto_atTop).congr fun m ↦ (heq m i).symm
+ have hcard := Fintype.one_lt_card_iff_nontrivial.mpr (G 0).nontrivial_parties
+ have hden : 0 < (Fintype.card (parties p) : ℝ) - 1 := sub_pos.mpr (by exact_mod_cast hcard)
+ exact ⟨p, exists_wire_configuration_limit (labels p) G (fun m ↦ (hr m).le)
+ (one_div_pos.mpr hden) (fun m ↦ (G m).inv_card_sub_one_le_wire_diameter _ (hcover p) hcard)
+ hd hsub⟩
+
+omit [Nonempty J] [Fintype ι] [Nonempty ι] in
+/-- Repeating one party realizes the zero configuration at unit scale. -/
+theorem zero_wire_configuration (G : SpectralPoint k J) (a : J) :
+ ∃ label : ι → J, ∀ i : ι × ι, G.wireDistance (label i.1) (label i.2) = 0 :=
+ ⟨fun _ ↦ a, fun _ ↦ G.wireDistance_self a⟩
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ContractionClass.lean b/lean/OAI/Computability/VPVNP/ContractionClass.lean
new file mode 100644
index 0000000000..117d1fee36
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ContractionClass.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.ContractionValue
+import OAI.Computability.VPVNP.StarEmbedding
+import OAI.Computability.VPVNP.TensorRestrictionSpectrum
+
+/-!
+# Center contractions on restriction classes
+
+The supremal contraction value descends to the extended-party restriction
+classes. Its additivity evaluates the copy multiplicities on both sides of
+the comparison in Theorem 2.4. Multiplication by an embedded old tensor
+can also be evaluated, even with an arbitrary covector on the other factor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+open scoped NNReal
+
+namespace WireTensor.SpectralPoint
+
+open RestrictionClass
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nonempty J] (F : SpectralPoint k J)
+
+/-- Real-valued supremal contraction on classes, preserving finite direct sums. -/
+noncomputable def contractionClassValue : RestrictionClass k (Option J) →+ ℝ where
+ toFun := Quotient.lift (fun T ↦ (F.contractionValue T : ℝ)) (fun _ _ h ↦
+ congrArg (fun r : ℝ≥0 ↦ (r : ℝ)) (le_antisymm (F.contractionValue_mono h.2)
+ (F.contractionValue_mono h.1)))
+ map_zero' := by
+ change (F.contractionValue (diagonal (Fin 0)) : ℝ) = 0
+ rw [F.contractionValue_zero]
+ · rfl
+ · funext x
+ exact Fin.elim0 (x none)
+ map_add' x y := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ obtain ⟨U, rfl⟩ := ofTensor_surjective y
+ change (F.contractionValue (directSum T U) : ℝ) = F.contractionValue T + F.contractionValue U
+ rw [F.contractionValue_directSum, NNReal.coe_add]
+
+@[simp] theorem contractionClassValue_ofTensor (T : Tensor.{u,v,0} k (Option J)) :
+ F.contractionClassValue (ofTensor T) = (F.contractionValue T : ℝ) := rfl
+
+theorem contractionClassValue_monotone : Monotone F.contractionClassValue := by
+ intro x y h
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ obtain ⟨U, rfl⟩ := ofTensor_surjective y
+ exact NNReal.coe_le_coe.mpr (F.contractionValue_mono ((ofTensor_le_iff T U).mp h))
+
+@[simp] theorem contractionClassValue_one : F.contractionClassValue 1 = 1 := by
+ change (F.contractionValue unit : ℝ) = 1
+ rw [F.contractionValue_unit, NNReal.coe_one]
+
+theorem contractionClassValue_nonneg (x : RestrictionClass k (Option J)) :
+ 0 ≤ F.contractionClassValue x := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ exact NNReal.coe_nonneg _
+
+theorem one_le_contractionClassValue {x : RestrictionClass k (Option J)} (hx : x ≠ 0) :
+ 1 ≤ F.contractionClassValue x := by
+ rw [← F.contractionClassValue_one]
+ exact F.contractionClassValue_monotone (orderBounds.one_le hx)
+
+/-- A natural-number copy factor gives that many times the single value. -/
+@[simp] theorem contractionClassValue_copies (n : ℕ) (x : RestrictionClass k (Option J)) :
+ F.contractionClassValue ((n : RestrictionClass k (Option J)) * x) = n * F.contractionClassValue x := by
+ rw [← nsmul_eq_mul, map_nsmul, nsmul_eq_mul]
+
+/-- Evaluating a class with an embedded old factor leaves only the
+contraction value of the remaining extended-party class. -/
+theorem contractionClassValue_old_product (x : RestrictionClass k J) (y : RestrictionClass k (Option J)) :
+ F.contractionClassValue (embedOldClass x * y) = ofSpectralPoint F x * F.contractionClassValue y := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ obtain ⟨U, rfl⟩ := ofTensor_surjective y
+ rw [embedOldClass_ofTensor, ← ofTensor_tensorProduct, contractionClassValue_ofTensor,
+ F.contractionValue_old_product, NNReal.coe_mul, contractionClassValue_ofTensor, ofSpectralPoint_ofTensor]
+
+/-- A center leg of dimension one preserves the old spectral point on classes. -/
+@[simp] theorem contractionClassValue_embedOldClass (x : RestrictionClass k J) :
+ F.contractionClassValue (embedOldClass x) = ofSpectralPoint F x := by
+ simpa only [mul_one, F.contractionClassValue_one] using F.contractionClassValue_old_product x 1
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ContractionValue.lean b/lean/OAI/Computability/VPVNP/ContractionValue.lean
new file mode 100644
index 0000000000..74676a00d6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ContractionValue.lean
@@ -0,0 +1,148 @@
+import OAI.Computability.VPVNP.StarContraction
+import OAI.Computability.VPVNP.WireSpectrum
+import Mathlib.Order.ConditionallyCompleteLattice.Group
+
+/-!
+# Supremum of spectral values of center contractions
+
+In the proof of Theorem 2.4 of *VP and VNP differ over every field*, the
+center contraction may use any covector, including on products of several
+wires. Its supremal spectral value is monotone under local restrictions.
+Direct sums separate into independent blocks, and an embedded old factor
+can be evaluated separately.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+open scoped NNReal
+
+namespace WireTensor.SpectralPoint
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] (F : SpectralPoint k J)
+
+/-- Supremum over all covectors on the center, before acting at the old parties. -/
+noncomputable def contractionValue (T : Tensor.{u,v,0} k (Option J)) : ℝ≥0 :=
+ ⨆ ξ, F.value (contractCenter T ξ)
+
+/-- A common bound for all contractions depends only on the dimensions at the old parties. -/
+theorem contractionValues_bddAbove [Nonempty J] (T : Tensor.{u,v,0} k (Option J)) :
+ BddAbove (Set.range (fun ξ ↦ F.value (contractCenter T ξ))) := by
+ refine ⟨((∏ j : J, Fintype.card (T.Basis (some j)) : ℕ) : ℝ≥0), ?_⟩
+ rintro _ ⟨ξ, rfl⟩
+ exact F.value_le_basis_product (contractCenter T ξ)
+
+variable [Nonempty J]
+
+theorem value_le_contractionValue (T : Tensor.{u,v,0} k (Option J)) (ξ : T.Basis none → k) :
+ F.value (contractCenter T ξ) ≤ F.contractionValue T :=
+ le_ciSup (F.contractionValues_bddAbove T) ξ
+
+theorem contractionValue_le_basis_product (T : Tensor.{u,v,0} k (Option J)) :
+ F.contractionValue T ≤ (∏ j : J, Fintype.card (T.Basis (some j)) : ℕ) :=
+ ciSup_le fun ξ ↦ F.value_le_basis_product (contractCenter T ξ)
+
+/-- The real least upper bound used in the root-limit estimates. -/
+theorem isLUB_contractionValue (T : Tensor.{u,v,0} k (Option J)) :
+ IsLUB (Set.range (fun ξ ↦ (F.value (contractCenter T ξ) : ℝ))) (F.contractionValue T : ℝ) := by
+ rw [contractionValue, NNReal.coe_iSup]
+ apply isLUB_ciSup
+ refine ⟨(F.contractionValue T : ℝ), ?_⟩
+ rintro _ ⟨ξ, rfl⟩
+ exact NNReal.coe_le_coe.mpr (F.value_le_contractionValue T ξ)
+
+/-- A restriction can only decrease the supremal contraction value. -/
+theorem contractionValue_mono {Y X : Tensor.{u,v,0} k (Option J)} (h : Restricts Y X) :
+ F.contractionValue X ≤ F.contractionValue Y := by
+ apply ciSup_le
+ intro ξ
+ obtain ⟨η, hη⟩ := contractCenter_restricts h ξ
+ exact (F.monotone hη).trans (F.value_le_contractionValue Y η)
+
+omit [Nonempty J] in
+/-- Each contraction of a zero array is zero. -/
+theorem contractionValue_zero (T : Tensor.{u,v,0} k (Option J)) (hT : T.coeff = 0) :
+ F.contractionValue T = 0 := by
+ apply le_antisymm _ bot_le
+ apply ciSup_le
+ intro ξ
+ apply (F.value_zero _ ?_).le
+ funext x
+ simp [contractCenter, hT]
+
+/-- Contracting the unit by the all-ones covector attains the dimensional upper bound. -/
+theorem contractionValue_unit : F.contractionValue unit = 1 := by
+ apply le_antisymm
+ · refine (F.contractionValue_le_basis_product _).trans_eq ?_
+ change ((∏ _ : J, Fintype.card PUnit.{1} : ℕ) : ℝ≥0) = 1
+ simp
+ · have hu : contractCenter (unit.{u,v,0} (k := k) (J := Option J)) (fun _ ↦ 1) = unit := by
+ unfold contractCenter unit
+ congr 1
+ funext x
+ simp
+ rw [← F.value_unit, ← hu]
+ exact F.value_le_contractionValue _ _
+
+/-- A nonzero extended tensor has a center contraction of supremal value at least one. -/
+theorem one_le_contractionValue (T : Tensor.{u,v,0} k (Option J)) (hT : T.coeff ≠ 0) :
+ 1 ≤ F.contractionValue T := by
+ rw [← F.contractionValue_unit]
+ exact F.contractionValue_mono (restricts_unit_of_ne_zero T hT)
+
+/-- The two blocks of the center admit independent covectors, so the
+supremum of contractions is additive on direct sums. -/
+theorem contractionValue_directSum (T U : Tensor.{u,v,0} k (Option J)) :
+ F.contractionValue (directSum T U) = F.contractionValue T + F.contractionValue U := by
+ apply le_antisymm
+ · apply ciSup_le
+ intro ξ
+ rw [contractCenter_directSum, F.value_directSum]
+ exact add_le_add (F.value_le_contractionValue T _) (F.value_le_contractionValue U _)
+ · apply NNReal.coe_le_coe.mp
+ simp only [NNReal.coe_add, contractionValue, NNReal.coe_iSup]
+ apply ciSup_add_ciSup_le
+ intro ξ η
+ have h := F.value_le_contractionValue (directSum T U) (Sum.elim ξ η)
+ rw [contractCenter_directSum T U (Sum.elim ξ η), F.value_directSum] at h
+ change F.value (contractCenter T ξ) + F.value (contractCenter U η) ≤ F.contractionValue _ at h
+ simpa only [contractionValue, NNReal.coe_iSup, NNReal.coe_add] using (NNReal.coe_le_coe.mpr h)
+
+omit [Nonempty J] in
+/-- A spectral extension dominates every old contraction of an extended tensor. -/
+theorem contractionValue_le_extension (H : SpectralPoint k (Option J))
+ (hH : ∀ T, H.value (embedOld T) = F.value T) (U : Tensor.{u,v,0} k (Option J)) :
+ F.contractionValue U ≤ H.value U := by
+ apply ciSup_le
+ intro ξ
+ rw [← hH]
+ exact H.monotone (restricts_embedOld_contractCenter U ξ)
+
+/-- The unit center leg on an embedded old tensor can be contracted with coefficient one. -/
+theorem contractionValue_embedOld (T : Tensor.{u,v,0} k J) :
+ F.contractionValue (embedOld T) = F.value T := by
+ apply le_antisymm
+ · exact ciSup_le fun ξ ↦ F.monotone (restricts_contractCenter_embedOld T ξ)
+ · have h := F.value_le_contractionValue (embedOld T) (fun _ ↦ 1)
+ rwa [contractCenter_embedOld_one] at h
+
+/-- Embedded old tensors multiply the contraction value by their spectral value. -/
+theorem contractionValue_old_product (T : Tensor.{u,v,0} k J) (U : Tensor.{u,v,0} k (Option J)) :
+ F.contractionValue (tensorProduct (embedOld T) U) = F.value T * F.contractionValue U := by
+ apply le_antisymm
+ · apply ciSup_le
+ intro ξ
+ rw [contractCenter_old_product, F.value_tensorProduct]
+ exact mul_le_mul_right (F.value_le_contractionValue U _) _
+ · apply NNReal.mul_iSup_le
+ intro η
+ have h := F.value_le_contractionValue (tensorProduct (embedOld T) U) (fun z ↦ η z.2)
+ rwa [contractCenter_old_product, F.value_tensorProduct] at h
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CoordinateQueries.lean b/lean/OAI/Computability/VPVNP/CoordinateQueries.lean
new file mode 100644
index 0000000000..4012ead9c7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CoordinateQueries.lean
@@ -0,0 +1,279 @@
+import OAI.Computability.VPVNP.DeterminantQueries
+
+/-!
+# Greedy row and column coordinate queries
+
+Appendix D.2 of *VP and VNP differ over every field* selects rows using ranks
+of prefixes of the original matrix. For an independent list of rows it
+selects independent columns by the same test on the transpose. A coordinate
+of a target in their span then uses two ordinary determinant queries.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+open Polynomial
+
+/-- Ordinary determinant recovered at the top pencil degree, with its sign. -/
+def squareDetQuery {K : Type*} [CommRing K] {r : ℕ} (A : Matrix (Fin r) (Fin r) K) : K :=
+ (-1) ^ r * determinantQuery (fun i j z => if z = 0 then A i j else 0) r 0
+
+theorem squareDetQuery_eq {K : Type*} [Field K] {r : ℕ} (A : Matrix (Fin r) (Fin r) K) :
+ squareDetQuery A = A.det := by
+ let M := A.map C
+ have he (i j : Fin r) (z : ℕ) : (if z = 0 then A i j else 0) = (M i j).coeff z := by
+ simp [M, coeff_C]
+ have htop : M.charpolyRev.coeff r = M.charpoly.coeff 0 := by
+ rw [← M.reverse_charpoly, coeff_reverse, M.charpoly_natDegree_eq_dim, Fintype.card_fin]
+ simp
+ rw [squareDetQuery, determinantQuery_eq M _ he, htop]
+ have hs := M.det_eq_sign_charpoly_coeff
+ rw [Fintype.card_fin, ← show C ((-1 : K) ^ r) = (-1 : K[X]) ^ r from by simp] at hs
+ have h := congrArg (fun p : K[X] => p.coeff 0) hs
+ rw [coeff_C_mul] at h
+ change (C.mapMatrix A).det.coeff 0 = _ at h
+ rw [← C.map_det, coeff_C_zero] at h
+ exact h.symm
+
+variable {K : Type*} [Field K] {n m r : ℕ}
+
+/-- The first `s` rows, retaining every column. -/
+def prefixRows (A : Matrix (Fin n) (Fin m) K) (s : ℕ) (hs : s ≤ n) :
+ Matrix (Fin s) (Fin m) K := A.submatrix (Fin.castLE hs) id
+
+theorem rank_prefixRows (A : Matrix (Fin n) (Fin m) K) (s : ℕ) (hs : s ≤ n) :
+ (prefixRows A s hs).rank = ((greedyIndices K A.row).filter (fun i => i.val < s)).card := by
+ let S := (greedyIndices K A.row).filter (fun i => i.val < s)
+ have hS : (S : Set (Fin n)) = (greedyIndices K A.row : Set (Fin n)) ∩ {i | i.val < s} := by
+ ext i
+ simp [S]
+ have h := greedyIndices_prefix K A.row s
+ rw [← hS] at h
+ have hrows : (prefixRows A s hs).row = A.row ∘ Fin.castLE hs := rfl
+ rw [Matrix.rank_eq_finrank_span_row, hrows, Set.range_comp, Fin.range_castLE, ← h.2,
+ Set.image_eq_range, finrank_span_eq_card h.1]
+ simp [S]
+
+/-- The next row is retained exactly at the indices where the prefix rank increases. -/
+theorem mem_greedyIndices_iff_prefixRank_lt (A : Matrix (Fin n) (Fin m) K) (i : Fin n) :
+ i ∈ greedyIndices K A.row ↔
+ (prefixRows A i.val i.isLt.le).rank < (prefixRows A (i.val + 1) i.isLt).rank := by
+ rw [rank_prefixRows, rank_prefixRows]
+ let S := greedyIndices K A.row
+ have hsplit : S.filter (fun j => j.val < i.val + 1) =
+ if i ∈ S then insert i (S.filter (fun j => j.val < i.val))
+ else S.filter (fun j => j.val < i.val) := by
+ ext j
+ by_cases hi : i ∈ S <;> simp only [hi, ite_true, ite_false, Finset.mem_filter, Finset.mem_insert]
+ · by_cases he : j = i
+ · subst j; simp [hi]
+ · have hval : j.val ≠ i.val := Fin.val_injective.ne he
+ simp [he]; omega
+ · apply and_congr_right
+ intro hj
+ have hval : j.val ≠ i.val := fun he => hi (Fin.ext he ▸ hj)
+ omega
+ change i ∈ S ↔ (S.filter _).card < (S.filter _).card
+ rw [hsplit]
+ by_cases hi : i ∈ S <;> simp [hi]
+
+private theorem ordered_prefix_counts {n r : ℕ} (S : Finset (Fin n)) (hcard : S.card = r)
+ (k : Fin r) :
+ (S.filter (· < S.orderEmbOfFin hcard k)).card = k.val ∧
+ (S.filter (· ≤ S.orderEmbOfFin hcard k)).card = k.val + 1 := by
+ let e := S.orderEmbOfFin hcard
+ have hlt : S.filter (· < e k) = (Finset.Iio k).map e.toEmbedding := by
+ conv_lhs => rhs; rw [← S.map_orderEmbOfFin_univ hcard]
+ rw [Finset.filter_map]
+ congr 1
+ ext i
+ rw [Finset.mem_filter]
+ change (i ∈ Finset.univ ∧ e i < e k) ↔ _
+ simp
+ have hle : S.filter (· ≤ e k) = (Finset.Iic k).map e.toEmbedding := by
+ conv_lhs => rhs; rw [← S.map_orderEmbOfFin_univ hcard]
+ rw [Finset.filter_map]
+ congr 1
+ ext i
+ rw [Finset.mem_filter]
+ change (i ∈ Finset.univ ∧ e i ≤ e k) ↔ _
+ simp
+ change (S.filter (· < e k)).card = _ ∧ (S.filter (· ≤ e k)).card = _
+ simp [hlt, hle]
+
+/-- Retrieve the zero-based `k`-th selected index by scanning prefixes
+until the number of selected items first exceeds `k`. -/
+def firstPrefixAbove {n : ℕ} (prefixRank : (s : ℕ) → s ≤ n → ℕ) (k : ℕ)
+ (hex : ∃ i : Fin n, k < prefixRank (i.val + 1) i.isLt) : Fin n :=
+ Fin.find (fun i => k < prefixRank (i.val + 1) i.isLt) hex
+
+theorem prefix_above_exists {n r : ℕ} (S : Finset (Fin n)) (hcard : S.card = r)
+ (prefixRank : (s : ℕ) → s ≤ n → ℕ)
+ (hrank : ∀ s hs, prefixRank s hs = (S.filter (fun i => i.val < s)).card) (k : Fin r) :
+ ∃ i : Fin n, k.val < prefixRank (i.val + 1) i.isLt := by
+ let j := S.orderEmbOfFin hcard k
+ refine ⟨j, ?_⟩
+ rw [hrank]
+ simp only [Nat.lt_succ_iff]
+ change k.val < (S.filter (· ≤ j)).card
+ rw [(ordered_prefix_counts S hcard k).2]
+ omega
+
+theorem firstPrefixAbove_eq {n r : ℕ} (S : Finset (Fin n)) (hcard : S.card = r)
+ (prefixRank : (s : ℕ) → s ≤ n → ℕ)
+ (hrank : ∀ s hs, prefixRank s hs = (S.filter (fun i => i.val < s)).card) (k : Fin r) :
+ firstPrefixAbove prefixRank k.val (prefix_above_exists S hcard prefixRank hrank k) =
+ S.orderEmbOfFin hcard k := by
+ apply (Fin.find_eq_iff _).mpr
+ obtain ⟨hlt, hle⟩ := ordered_prefix_counts S hcard k
+ constructor
+ · rw [hrank]
+ simp only [Nat.lt_succ_iff]
+ change k.val < (S.filter (· ≤ S.orderEmbOfFin hcard k)).card
+ omega
+ · intro i hi
+ rw [hrank, not_lt, ← hlt]
+ apply Finset.card_le_card
+ intro j hj
+ obtain ⟨hjS, hji⟩ := Finset.mem_filter.mp hj
+ exact Finset.mem_filter.mpr ⟨hjS, lt_of_le_of_lt (Nat.le_of_lt_succ hji) hi⟩
+
+
+/-- Query one coordinate in a row basis from an oracle for square determinants.
+Both input matrices are given entrywise, from the selected columns. -/
+def rowCoordinateQuery (detQuery : Matrix (Fin r) (Fin r) K → K)
+ (B : Matrix (Fin r) (Fin m) K) (cols : Fin r → Fin m) (target : Fin m → K) (i : Fin r) : K :=
+ let A := B.submatrix id cols
+ detQuery (A.updateRow i (target ∘ cols)) / detQuery A
+
+/-- Replacing row `i` by the restricted target multiplies the determinant by
+the `i`-th coefficient in every representation of that target. -/
+theorem rowCoordinateQuery_eq (detQuery : Matrix (Fin r) (Fin r) K → K)
+ (hdet : ∀ A, detQuery A = A.det) (B : Matrix (Fin r) (Fin m) K)
+ (cols : Fin r → Fin m) (hnonsing : (B.submatrix id cols).det ≠ 0)
+ (target : Fin m → K) (c : Fin r → K) (hc : ∑ k, c k • B k = target) (i : Fin r) :
+ rowCoordinateQuery detQuery B cols target i = c i := by
+ let A := B.submatrix id cols
+ have hrestrict : target ∘ cols = ∑ k, c k • A k := by
+ funext j
+ rw [← hc, Function.comp_apply, Finset.sum_apply, Finset.sum_apply]
+ rfl
+ change detQuery (A.updateRow i (target ∘ cols)) / detQuery A = c i
+ rw [hdet, hdet, hrestrict, Matrix.det_updateRow_sum, smul_eq_mul, mul_div_cancel_right₀ _ hnonsing]
+
+/-- When the target lies in the span, querying the coordinates reconstructs
+the target on all columns of the original rectangular matrix. -/
+theorem rowCoordinateQuery_reconstruct (detQuery : Matrix (Fin r) (Fin r) K → K)
+ (hdet : ∀ A, detQuery A = A.det) (B : Matrix (Fin r) (Fin m) K)
+ (cols : Fin r → Fin m) (hnonsing : (B.submatrix id cols).det ≠ 0)
+ (target : Fin m → K) (hspan : target ∈ Submodule.span K (Set.range B)) :
+ ∑ i, rowCoordinateQuery detQuery B cols target i • B i = target := by
+ obtain ⟨c, hc⟩ := (Submodule.mem_span_range_iff_exists_fun K).mp hspan
+ simpa only [rowCoordinateQuery_eq detQuery hdet B cols hnonsing target c hc] using hc
+
+section GreedyQueries
+
+variable [DecidableEq K]
+
+theorem greedyRows_card (A : Matrix (Fin n) (Fin m) K) :
+ (greedyIndices K A.row).card = rankQuery A := by
+ rw [rankQuery_eq]
+ have h := rank_prefixRows A n le_rfl
+ have hA : prefixRows A n le_rfl = A := rfl
+ rw [hA] at h
+ simpa using h.symm
+
+private theorem prefixRankQuery_count (A : Matrix (Fin n) (Fin m) K) (s : ℕ) (hs : s ≤ n) :
+ rankQuery (prefixRows A s hs) = ((greedyIndices K A.row).filter (fun i => i.val < s)).card := by
+ rw [rankQuery_eq, rank_prefixRows]
+
+/-- The indexed row of the greedy basis. Every rank query during the scan
+uses an initial block of the supplied matrix. -/
+def greedyRowIndex (A : Matrix (Fin n) (Fin m) K) (k : Fin (rankQuery A)) : Fin n :=
+ firstPrefixAbove (fun s hs => rankQuery (prefixRows A s hs)) k.val
+ (prefix_above_exists _ (greedyRows_card A) _ (prefixRankQuery_count A) k)
+
+theorem greedyRowIndex_eq (A : Matrix (Fin n) (Fin m) K) (k : Fin (rankQuery A)) :
+ greedyRowIndex A k = (greedyIndices K A.row).orderEmbOfFin (greedyRows_card A) k :=
+ firstPrefixAbove_eq _ (greedyRows_card A) _ (prefixRankQuery_count A) k
+
+theorem greedyRowIndex_independent (A : Matrix (Fin n) (Fin m) K) :
+ LinearIndependent K (A.row ∘ greedyRowIndex A) := by
+ have h := greedyIndices_linearIndepOn K A.row
+ let e := (greedyIndices K A.row).orderIsoOfFin (greedyRows_card A)
+ have h' := (linearIndependent_equiv (R := K)
+ (f := fun i : greedyIndices K A.row => A.row i.val) e.toEquiv).mpr h
+ change LinearIndependent K
+ (fun i => A.row ((greedyIndices K A.row).orderIsoOfFin (greedyRows_card A) i).val) at h'
+ simpa only [Function.comp_def, greedyRowIndex_eq, Finset.coe_orderIsoOfFin_apply] using h'
+
+theorem greedyRowIndex_span (A : Matrix (Fin n) (Fin m) K) :
+ Submodule.span K (Set.range (A.row ∘ greedyRowIndex A)) =
+ Submodule.span K (Set.range A.row) := by
+ have hindices : greedyRowIndex A = (greedyIndices K A.row).orderEmbOfFin (greedyRows_card A) :=
+ funext (greedyRowIndex_eq A)
+ rw [hindices, Set.range_comp, Finset.range_orderEmbOfFin]
+ simpa using greedyIndices_span_prefix K A.row n
+
+/-- The independent columns of an assembled full-row-rank matrix, queried
+by their ordinal among the selected columns. -/
+def coordinateColumns (B : Matrix (Fin r) (Fin m) K) (hB : B.rank = r) : Fin r → Fin m :=
+ fun i => greedyRowIndex B.transpose (Fin.cast (by rw [rankQuery_eq, Matrix.rank_transpose, hB]) i)
+
+theorem coordinateColumns_nonsingular (B : Matrix (Fin r) (Fin m) K) (hB : B.rank = r) :
+ (B.submatrix id (coordinateColumns B hB)).det ≠ 0 := by
+ have hdim : r = rankQuery B.transpose := by rw [rankQuery_eq, Matrix.rank_transpose, hB]
+ let e := finCongr hdim
+ have h := greedyRowIndex_independent B.transpose
+ have h' := (linearIndependent_equiv (R := K)
+ (f := B.transpose.row ∘ greedyRowIndex B.transpose) e).mpr h
+ have hc : LinearIndependent K (B.submatrix id (coordinateColumns B hB)).col := h'
+ exact ((Matrix.isUnit_iff_isUnit_det _).mp (Matrix.linearIndependent_cols_iff_isUnit.mp hc)).ne_zero
+
+/-- Coordinate of the target row in an independent row list, using only
+entrywise prefix rank queries and two scalar determinant queries. -/
+def coordinateQuery (B : Matrix (Fin r) (Fin m) K) (hB : B.rank = r)
+ (target : Fin m → K) (i : Fin r) : K :=
+ rowCoordinateQuery squareDetQuery B (coordinateColumns B hB) target i
+
+theorem coordinateQuery_eq (B : Matrix (Fin r) (Fin m) K) (hB : B.rank = r)
+ (target : Fin m → K) (c : Fin r → K) (hc : ∑ k, c k • B k = target) (i : Fin r) :
+ coordinateQuery B hB target i = c i :=
+ rowCoordinateQuery_eq _ squareDetQuery_eq _ _ (coordinateColumns_nonsingular B hB) _ c hc i
+
+theorem coordinateQuery_reconstruct (B : Matrix (Fin r) (Fin m) K) (hB : B.rank = r)
+ (target : Fin m → K) (hspan : target ∈ Submodule.span K (Set.range B)) :
+ ∑ i, coordinateQuery B hB target i • B i = target :=
+ rowCoordinateQuery_reconstruct _ squareDetQuery_eq _ _ (coordinateColumns_nonsingular B hB) _ hspan
+
+/-- The rectangular matrix of the selected rows, still presented by an entry
+function so querying its entries only requests their indices in the original matrix. -/
+def greedyRowBasis (A : Matrix (Fin n) (Fin m) K) : Matrix (Fin (rankQuery A)) (Fin m) K :=
+ A.submatrix (greedyRowIndex A) id
+
+theorem greedyRowBasis_fullRank (A : Matrix (Fin n) (Fin m) K) :
+ (greedyRowBasis A).rank = rankQuery A := by
+ have h : LinearIndependent K (greedyRowBasis A).row := greedyRowIndex_independent A
+ simpa using h.rank_matrix
+
+/-- Coordinate of a target in the greedy row basis of an arbitrary matrix. -/
+def greedyCoordinateQuery (A : Matrix (Fin n) (Fin m) K) (target : Fin m → K)
+ (i : Fin (rankQuery A)) : K :=
+ coordinateQuery (greedyRowBasis A) (greedyRowBasis_fullRank A) target i
+
+theorem greedyCoordinateQuery_reconstruct (A : Matrix (Fin n) (Fin m) K)
+ (target : Fin m → K) (hspan : target ∈ Submodule.span K (Set.range A.row)) :
+ ∑ i, greedyCoordinateQuery A target i • A (greedyRowIndex A i) = target := by
+ rw [← greedyRowIndex_span A] at hspan
+ exact coordinateQuery_reconstruct (greedyRowBasis A) (greedyRowBasis_fullRank A) target hspan
+
+end GreedyQueries
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CountedLabelReadback.lean b/lean/OAI/Computability/VPVNP/CountedLabelReadback.lean
new file mode 100644
index 0000000000..d494bb2b43
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CountedLabelReadback.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.FixedLabelReadback
+import OAI.Computability.VPVNP.ParseOracleRun
+
+/-!
+# The two counted scalar queries of Section 8.1
+
+The joint reader uses the same fixed counting machine with two choices of
+Boolean circuit advice. One circuit counts the incidence words for a parse
+histogram, and one counts the zero-padded witnesses of the universal machine.
+A grammar exponent too large for the degree of the queried polynomial
+returns zero before invoking the counter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointLabelSystem
+
+open MvPolynomial PrimedStackRAM RadicalCertificate.MonomialIndex UniversalCountStack
+open RAMTape
+
+/-- The binary output in the count stack of the fixed enumerator. -/
+noncomputable def countBits {u w g : ℕ} (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) g)
+ (x : Fin u → Bool) : List Bool :=
+ digits (w + 1) (∑ bits, (c.eval (Sum.elim x bits)).toNat)
+
+theorem countBits_runs {u w g : ℕ} (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) g)
+ (x : Fin u → Bool) :
+ ∃ t ≤ 2 ^ w * perChoice c, SpaceRun countCircuit.standalone (stackLimit c) t
+ (some countCircuit.entry) (bank (scalarInputs c x) (digits w 0) (digits (w + 1) 0) [] []) none
+ (bank (scalarInputs c x) (digits w 0) (countBits c x) [] []) := countCircuit_runs c x
+
+/-- The constant coefficient is read from the clocked path-count query. -/
+noncomputable def pathScalar {n : ℕ} (x : Fin n → Bool) : ℕ :=
+ TapeWord.value (countBits (VerifierMachine.verifierCircuit n) x)
+
+theorem pathScalar_eq {n : ℕ} (x : Fin n → Bool) : pathScalar x = acceptingCount x := by
+ unfold pathScalar countBits
+ simp only [VerifierMachine.verifierCircuit_eval]
+ have h := acceptingCount_eq_sum_witnesses (R := ℕ) x
+ simp only [Nat.cast_id] at h
+ have hs : (∑ bits, (verifiesInput x bits).toNat) = acceptingCount x := by
+ rw [h]
+ exact Finset.sum_congr rfl fun bits _ => by cases verifiesInput x bits <;> rfl
+ rw [hs, count_digits_value]
+
+/-- The production-counter callback uses `2n` bits per queried exponent.
+Larger exponents cannot occur in a degree-`2n-1` parse monomial. -/
+noncomputable def parseScalar {n : ℕ} (hn : 2 ≤ n) (c : ℕ) (x : Fin n → Bool)
+ (z : Fin (FixedRows.productionCount n c) → ℕ) : ℤ :=
+ if ∀ j, z j < 2 ^ (2*n) then
+ let checker := ParseOracle.checker (⟨n - 1, by omega⟩ : Fin n)
+ (⟨0, pow_pos (by omega) _⟩ : Fin (n ^ (c + 5))) (labelIndex n n _) (2*n)
+ TapeWord.value (countBits checker (ParseOracle.query x z (2*n)))
+ else 0
+
+theorem parseScalar_eq {n : ℕ} (hn : 2 ≤ n) (c : ℕ) (x : Fin n → Bool)
+ (e : Production n c →₀ ℕ) :
+ parseScalar hn c x (fun i => e ((labelIndex n n _).symm i)) =
+ (labelQuery (⟨n - 1, by omega⟩ : Fin n) (⟨0, pow_pos (by omega) _⟩ : Fin (n ^ (c+5))) x).coeff e := by
+ let d : Fin n := ⟨n-1, by omega⟩
+ let h : Fin (n^(c+5)) := ⟨0, pow_pos (by omega) _⟩
+ let f := labelIndex n n (n^(c+5))
+ let z := fun i => e (f.symm i)
+ by_cases hz : ∀ i, z i < 2^(2*n)
+ · rw [parseScalar, ite_eq_left hz]
+ change (TapeWord.value (digits (ParseOracle.Flags n n _ + 1)
+ (∑ bits, ((ParseOracle.checker d h f (2*n)).eval (Sum.elim (ParseOracle.query x z (2*n)) bits)).toNat)) : ℤ) = _
+ rw [ParseOracle.count_checker d h f x z (fun l => hz (f l)) e (fun l => by simp [z])]
+ exact ParseOracle.coefficient_query_value d h x e
+ · rw [parseScalar, ite_eq_right hz]
+ by_contra he
+ apply hz
+ intro i
+ have hm := monomial_le_degreeOf (f.symm i) (mem_support_iff.mpr (Ne.symm he))
+ have hD := (degreeOf_le_totalDegree (labelQuery d h x) (f.symm i)).trans (labelQuery_isHomogeneous d h x).totalDegree_le
+ exact (hm.trans (hD.trans (show 2*d.val+1 ≤ 2*n by dsimp [d]; omega))).trans_lt Nat.lt_two_pow_self
+
+namespace FixedRows
+
+variable (V I : Type*) [Fintype V] [Fintype I] (F : I → MvPolynomial V ℤ) {n : ℕ}
+
+/-- Integer coefficient lookup with both counted callbacks instantiated by
+the outputs of the fixed circuit enumerator. -/
+noncomputable def countedCoeff (hn : 2 ≤ n) (c : ℕ) :
+ Fin (2^n + Fintype.card I) → (Fin (labelTotal V n c) → ℕ) → ℤ :=
+ readAdvice (orderAdvice V n c) (fixedTable V I F ∘ (Fintype.equivFin _).symm)
+ (parseScalar hn c) pathScalar
+
+theorem countedCoeff_eq (hn : 2 ≤ n) (c : ℕ) (i : Fin (2^n + Fintype.card I))
+ (a : Fin (labelTotal V n c) → ℕ) :
+ countedCoeff V I F hn c i a = (unionEquations (grammarEquation hn c) F (rowIndex I n i)).coeff
+ (exponentVector a) :=
+ (readAdvice_eq_getCoeff V I F n c _ _ i a).trans (getCoeff_eq V I F n c hn
+ (parseScalar hn c) (parseScalar_eq hn c) pathScalar pathScalar_eq i a)
+
+end FixedRows
+end JointLabelSystem
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CouplingAmplification.lean b/lean/OAI/Computability/VPVNP/CouplingAmplification.lean
new file mode 100644
index 0000000000..11afc72bd6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CouplingAmplification.lean
@@ -0,0 +1,202 @@
+import OAI.Computability.VPVNP.ExteriorLevelRates
+import OAI.Computability.VPVNP.SpectralGeometry
+
+/-!
+# Amplification of the endpoint-coupling estimate
+
+Appendix A.3 of *VP and VNP differ over every field* bounds a wire value by a
+binary tree of exterior decompositions. The finite exterior level estimate
+controls each child's table with no asymptotic error. After summing the leaves,
+the wire dimension tends to infinity at fixed depth, and then the depth tends
+to infinity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open Filter
+open scoped Topology
+
+namespace SpectralGeometry
+
+/-- Exterior level used for a split with wire length `t` and current endpoint exponents `N`. -/
+noncomputable def couplingLevel (q : ℕ) (t : ℝ) (N : EndpointTable) : ℕ :=
+ ExteriorLevelRates.level q ((q : ℝ) ^ (gapMidpoint N / t))
+
+/-- At the chosen level both normalized crossing factors obey their target bounds for
+each finite wire dimension `q ≥ 2`. -/
+theorem couplingLevel_bounds {q : ℕ} (hq : 2 ≤ q) {t : ℝ} (ht : 0 < t)
+ {N : EndpointTable} (hgap : ∀ j, |columnGap N j| ≤ t) :
+ let b := couplingLevel q t N
+ 1 ≤ b ∧ b < q ∧
+ ((q.choose (b + 1) : ℝ) / q.choose b) ^ t ≤ (q : ℝ) ^ gapMidpoint N ∧
+ ((q.choose (b - 1) : ℝ) / q.choose b) ^ t ≤ (q : ℝ) ^ (-gapMidpoint N) := by
+ have hq₁ : (1 : ℝ) ≤ q := by exact_mod_cast (show 1 ≤ q by omega)
+ have hq₀ := zero_le_one.trans hq₁
+ have hmid : -t ≤ gapMidpoint N ∧ gapMidpoint N ≤ t := by
+ obtain ⟨h₀, h₁⟩ := abs_le.mp (hgap false)
+ obtain ⟨h₂, h₃⟩ := abs_le.mp (hgap true)
+ unfold gapMidpoint
+ constructor <;> linarith
+ have hlo := Real.rpow_le_rpow_of_exponent_le hq₁
+ ((le_div_iff₀ ht).2 (by simpa only [neg_one_mul] using hmid.1) :
+ (-1 : ℝ) ≤ gapMidpoint N / t)
+ have hhi := Real.rpow_le_rpow_of_exponent_le hq₁
+ ((div_le_iff₀ ht).2 (by simpa only [one_mul] using hmid.2) : gapMidpoint N / t ≤ 1)
+ rw [Real.rpow_neg hq₀, Real.rpow_one, ← one_div] at hlo
+ rw [Real.rpow_one] at hhi
+ obtain ⟨hb, hbq, hu, hd⟩ := ExteriorLevelRates.level_bounds hq hlo hhi
+ refine ⟨hb, hbq, ?_, ?_⟩
+ · have h := Real.rpow_le_rpow (by positivity) hu.2 ht.le
+ rwa [← Real.rpow_mul hq₀, div_mul_cancel₀ _ ht.ne'] at h
+ · rw [← Real.rpow_neg hq₀] at hd
+ have h := Real.rpow_le_rpow (by positivity) hd.2 ht.le
+ rwa [← Real.rpow_mul hq₀, neg_mul, div_mul_cancel₀ _ ht.ne'] at h
+
+/-- The normalized endpoint bounds at both children of an Appendix A.3 split. -/
+theorem split_endpoint_bounds {q : ℕ} (hq : 2 ≤ q) {t : ℝ} (ht : 0 < t)
+ {N F : EndpointTable} (hgap : ∀ j, |columnGap N j| ≤ t)
+ (hF₀ : ∀ i j, 0 ≤ F i j) (hF : ∀ i j, F i j ≤ (q : ℝ) ^ N i j)
+ {G : Bool → EndpointTable} (hG : ∀ branch i j, G branch i j ≤ F i j)
+ (hplus : ∀ j, G true false j ≤
+ ((q.choose (couplingLevel q t N + 1) : ℝ) / q.choose (couplingLevel q t N)) ^ t * F true j)
+ (hminus : ∀ j, G false true j ≤
+ ((q.choose (couplingLevel q t N - 1) : ℝ) / q.choose (couplingLevel q t N)) ^ t * F false j)
+ (branch i j : Bool) : G branch i j ≤ (q : ℝ) ^ splitTable N branch i j := by
+ have hq₁ : (1 : ℝ) ≤ q := by exact_mod_cast (show 1 ≤ q by omega)
+ have hq₀ := zero_lt_one.trans_le hq₁
+ have hm : Monotone (fun r : ℝ ↦ (q : ℝ) ^ r) :=
+ fun _ _ h ↦ Real.rpow_le_rpow_of_exponent_le hq₁ h
+ obtain ⟨_, _, hup, hdown⟩ := couplingLevel_bounds hq ht hgap
+ have hsame := (hG branch i j).trans (hF i j)
+ cases branch <;> cases i
+ · exact hsame
+ · change G false true j ≤ (q : ℝ) ^ min (N true j) (N false j - gapMidpoint N)
+ rw [hm.map_min]
+ refine le_min hsame ?_
+ rw [sub_eq_add_neg, Real.rpow_add hq₀, mul_comm]
+ exact (hminus j).trans (mul_le_mul hdown (hF false j) (hF₀ false j) (by positivity))
+ · change G true false j ≤ (q : ℝ) ^ min (N false j) (N true j + gapMidpoint N)
+ rw [hm.map_min]
+ refine le_min hsame ?_
+ rw [Real.rpow_add hq₀, mul_comm]
+ exact (hplus j).trans (mul_le_mul hup (hF true j) (hF₀ true j) (by positivity))
+ · exact hsame
+
+/-- The cost table at an appended child agrees with one more split of the current table. -/
+theorem leafTable_append_child (M : EndpointTable) (p : List Bool) (b : Bool) :
+ leafTable M (p ++ [b]) = splitTable (leafTable M p) b := by
+ induction p generalizing M with
+ | nil => rfl
+ | cons c p ih => exact ih (splitTable M c)
+
+/-- Propagating normalized endpoint estimates from the root to any path of the given depth. -/
+theorem endpoint_tree_bounds {q : ℕ} (hq : 2 ≤ q) {t : ℝ} (ht : 0 < t) (a : ℕ)
+ (M : EndpointTable) (hgap : ∀ j, |columnGap M j| ≤ t) (F : List Bool → EndpointTable)
+ (hF₀ : ∀ p i j, 0 ≤ F p i j) (hroot : ∀ i j, F [] i j ≤ (q : ℝ) ^ M i j)
+ (hsame : ∀ p : List Bool, p.length < a → ∀ b i j, F (p ++ [b]) i j ≤ F p i j)
+ (hplus : ∀ p : List Bool, p.length < a → ∀ j,
+ let b := couplingLevel q t (leafTable M p)
+ F (p ++ [true]) false j ≤ ((q.choose (b + 1) : ℝ) / q.choose b) ^ t * F p true j)
+ (hminus : ∀ p : List Bool, p.length < a → ∀ j,
+ let b := couplingLevel q t (leafTable M p)
+ F (p ++ [false]) true j ≤ ((q.choose (b - 1) : ℝ) / q.choose b) ^ t * F p false j) :
+ ∀ p : List Bool, p.length ≤ a → ∀ i j, F p i j ≤ (q : ℝ) ^ leafTable M p i j := by
+ intro p
+ induction p using List.reverseRecOn with
+ | nil => exact fun _ ↦ hroot
+ | append_singleton p b ih =>
+ intro hp i j
+ have hp' : p.length < a := by simpa using hp
+ rw [leafTable_append_child]
+ exact split_endpoint_bounds hq ht (leafTable_columnGap_mem M p hgap) (hF₀ p) (ih hp'.le)
+ (G := fun b ↦ F (p ++ [b])) (hsame p hp') (hplus p hp') (hminus p hp') b i j
+
+/-- The independent endpoint estimate (A.4) passes to normalized values because
+its exponents sum to one. Applies to any coupling with these marginals. -/
+theorem normalized_endpoint_product_bound {u v q D W : ℝ} (ρ : EndpointCoupling u v)
+ {F N : EndpointTable} (hq : 0 < q) (hD : 0 < D) (hF₀ : ∀ i j, 0 ≤ F i j)
+ (hW : W ≤ ∏ i, ∏ j, (F i j) ^ ρ.mass i j) (hF : ∀ i j, F i j / D ≤ q ^ N i j) :
+ W / D ≤ q ^ ρ.cost N := by
+ have hmass : (∑ i, ∑ j, ρ.mass i j) = 1 := by
+ simp only [Fintype.sum_bool]
+ linarith only [ρ.row₀, ρ.row₁]
+ have hcost : (∑ i, ∑ j, N i j * ρ.mass i j) = ρ.cost N := by
+ simp only [Fintype.sum_bool, EndpointCoupling.cost]; ring
+ have hprod (x : ℝ) (hx : 0 < x) (p : EndpointTable) :
+ (∏ i, ∏ j, x ^ p i j) = x ^ (∑ i, ∑ j, p i j) := by
+ simp_rw [Real.rpow_sum_of_pos hx]
+ calc W / D ≤ (∏ i, ∏ j, (F i j) ^ ρ.mass i j) / D := div_le_div_of_nonneg_right hW hD.le
+ _ = ∏ i, ∏ j, (F i j / D) ^ ρ.mass i j := by
+ simp_rw [Real.div_rpow (hF₀ _ _) hD.le, Finset.prod_div_distrib]
+ rw [hprod D hD, hmass, Real.rpow_one]
+ _ ≤ ∏ i, ∏ j, (q ^ N i j) ^ ρ.mass i j := by
+ apply Finset.prod_le_prod₀
+ · exact fun i _ ↦ Finset.prod_nonneg fun j _ ↦
+ Real.rpow_nonneg (div_nonneg (hF₀ i j) hD.le) _
+ · intro i _
+ apply Finset.prod_le_prod₀
+ · exact fun j _ ↦ Real.rpow_nonneg (div_nonneg (hF₀ i j) hD.le) _
+ · exact fun j _ ↦ Real.rpow_le_rpow (div_nonneg (hF₀ i j) hD.le) (hF i j) (ρ.nonneg i j)
+ _ = q ^ ρ.cost N := by
+ simp_rw [← Real.rpow_mul hq.le]
+ rw [hprod q hq, hcost]
+
+/-- A depth-`a` tree with subadditive parent values and uniformly bounded leaf values. -/
+private theorem binary_tree_bound (a : ℕ) (E : List Bool → ℝ) (B : ℝ)
+ (hsplit : ∀ p : List Bool, p.length < a → E p ≤ E (p ++ [true]) + E (p ++ [false]))
+ (hleaf : ∀ p : List Bool, p.length = a → E p ≤ B) : E [] ≤ (2 : ℝ) ^ a * B := by
+ have descend (r : ℕ) (p : List Bool) (h : p.length + r = a) : E p ≤ (2 : ℝ) ^ r * B := by
+ induction r generalizing p with
+ | zero => simpa only [pow_zero, one_mul] using hleaf p (by omega)
+ | succ r ih =>
+ have hchild (b : Bool) : E (p ++ [b]) ≤ (2 : ℝ) ^ r * B :=
+ ih _ (by simp only [List.length_append, List.length_singleton]; omega)
+ calc E p ≤ E (p ++ [true]) + E (p ++ [false]) := hsplit p (by omega)
+ _ ≤ (2 : ℝ) ^ r * B + 2 ^ r * B := add_le_add (hchild true) (hchild false)
+ _ = (2 : ℝ) ^ (r + 1) * B := by rw [pow_succ]; ring
+ exact descend a [] (by simp)
+
+/-- The root is at most `2 ^ a` times the common coupling bound for the leaves. -/
+theorem coupling_tree_bound {u v t q : ℝ} (ρ π : EndpointCoupling u v) (M : EndpointTable)
+ (hgap : ∀ j, |columnGap M j| ≤ t) (hq : 1 ≤ q) (a : ℕ) (E : List Bool → ℝ)
+ (hsplit : ∀ p : List Bool, p.length < a → E p ≤ E (p ++ [true]) + E (p ++ [false]))
+ (hleaf : ∀ p : List Bool, p.length = a → E p ≤ q ^ ρ.cost (leafTable M p)) :
+ E [] ≤ (2 : ℝ) ^ a * q ^ (π.cost M + 2 * t * (1 / 2) ^ a) := by
+ apply binary_tree_bound a E _ hsplit
+ intro p hp
+ apply (hleaf p hp).trans (Real.rpow_le_rpow_of_exponent_le hq ?_)
+ simpa only [hp] using coupling_leaf_bound ρ π M hgap p
+
+/-- A fixed dyadic prefactor vanishes from the exponential rate as the power tends to infinity.
+The remaining error tends to zero as the precision index increases. -/
+theorem le_of_dyadic_amplification {d cost t : ℝ}
+ (h : ∀ a n : ℕ, 1 ≤ n → ((2 : ℝ) ^ n) ^ d ≤
+ (2 : ℝ) ^ a * ((2 : ℝ) ^ n) ^ (cost + 2 * t * (1 / 2) ^ a)) :
+ d ≤ cost := by
+ let rate (a : ℕ) := cost + 2 * t * (1 / 2 : ℝ) ^ a
+ have hfixed (a : ℕ) : d ≤ rate a := by
+ have hlim : Tendsto (fun n : ℕ ↦ (a : ℝ) / n + rate a) atTop (𝓝 (rate a)) := by
+ simpa using (tendsto_const_div_atTop_nhds_zero_nat (a : ℝ)).add_const (rate a)
+ apply ge_of_tendsto hlim
+ filter_upwards [eventually_ge_atTop 1] with n hn
+ have hn_pos : (0 : ℝ) < n := by exact_mod_cast (show 0 < n from hn)
+ have hpow : ((2 : ℝ) ^ n) ^ d ≤ (2 : ℝ) ^ a * ((2 : ℝ) ^ n) ^ rate a := h a n hn
+ rw [← Real.rpow_natCast_mul (by norm_num : (0 : ℝ) ≤ 2),
+ ← Real.rpow_natCast_mul (by norm_num : (0 : ℝ) ≤ 2), ← Real.rpow_natCast 2 a,
+ ← Real.rpow_add (by norm_num : (0 : ℝ) < 2), Real.rpow_le_rpow_left_iff (by norm_num)] at hpow
+ apply (mul_le_mul_iff_right₀ hn_pos).mp
+ rw [mul_add, mul_comm _ (_ / _), div_mul_cancel₀ _ hn_pos.ne']
+ exact hpow
+ have hlim : Tendsto rate atTop (𝓝 cost) := by
+ have hhalf := tendsto_pow_atTop_nhds_zero_of_lt_one
+ (by norm_num : (0 : ℝ) ≤ 1 / 2) (by norm_num : (1 / 2 : ℝ) < 1)
+ simpa [rate] using (hhalf.const_mul (2 * t)).const_add cost
+ exact ge_of_tendsto' hlim hfixed
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CrossingCard.lean b/lean/OAI/Computability/VPVNP/CrossingCard.lean
new file mode 100644
index 0000000000..e20ea5b505
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CrossingCard.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.ShiftedPairing
+import OAI.Computability.VPVNP.StateCount
+import Lemmata.FockCircuits.FiniteIdentity
+
+/-!
+# Dimensions of the two wires in the shifted crossing
+
+The operator indices in Appendix B range over nonvacuum occupation states.
+The sigma type used for the integral pairing separates these states by their
+positive particle number. Counting that type removes exactly the vacuum.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+private abbrev OccupationsBelow (H : ℕ) :=
+ {s : Occupation H // doubledEnergy s ≤ (H : ℤ)}
+
+private def emptyOccupation (H : ℕ) : OccupationsBelow H :=
+ ⟨∅, by simp [doubledEnergy]⟩
+
+private def nonvacuumEquiv (H : ℕ) :
+ {s : OccupationsBelow H // s ≠ emptyOccupation H} ≃ BoundedState H where
+ toFun s := ⟨s.val.val.map Fin.valEmbedding, by
+ have hn : s.val.val ≠ ∅ := fun hz => s.prop (Subtype.ext hz)
+ exact (Finset.nonempty_iff_ne_empty.mpr hn).map, by
+ change Lemmata.FockCircuits.doubledEnergy _ ≤ H
+ exact_mod_cast (doubledEnergy_map_val s.val.val).le.trans s.val.prop⟩
+ invFun s := by
+ have hbound (i : ℕ) (hi : i ∈ s.val) : i < H := by
+ have := Finset.single_le_sum (f := fun j : ℕ => 2*j+1) (fun _ _ => Nat.zero_le _) hi
+ have := s.prop.2
+ omega
+ refine ⟨⟨s.val.attachFin hbound, ?_⟩, ?_⟩
+ · rw [← doubledEnergy_map_val, Finset.map_valEmbedding_attachFin]
+ exact_mod_cast s.prop.2
+ · intro he
+ have hc := congrArg (fun p : OccupationsBelow H => p.val.card) he
+ simp [emptyOccupation] at hc
+ exact s.prop.1.ne_empty hc
+ left_inv s := by
+ apply Subtype.ext
+ apply Subtype.ext
+ apply Finset.map_injective Fin.valEmbedding
+ exact Finset.map_valEmbedding_attachFin _
+ right_inv s := Subtype.ext (Finset.map_valEmbedding_attachFin _)
+
+/-- The positive particle-number sectors together index exactly the cutoff count
+minus the unique empty occupation state. This includes the zero-energy cutoff. -/
+theorem crossingState_card (H : ℕ) :
+ Fintype.card (Σ m : Fin H, EnergySector H (m.val + 1) H) = cutoffCount H - 1 := by
+ classical
+ have h := Fintype.card_congr ((Equiv.optionCongr
+ ((boundedStateEquivSectors H).symm.trans (nonvacuumEquiv H).symm)).trans
+ (Equiv.optionSubtypeNe (emptyOccupation H)))
+ rw [Fintype.card_option, occupationCount_eq H H le_rfl] at h
+ omega
+
+open Lemmata.FockCircuits.FiniteIdentity (Index)
+
+private abbrev indexEnergy {N : ℕ} (p : Index N) : ℤ :=
+ Lemmata.FockCircuits.doubledEnergy p.val
+
+private theorem modeCutoff_card (N : ℕ) (B : ℤ) :
+ Fintype.card (Cutoff (indexEnergy (N := N)) B) =
+ Fintype.card (Cutoff (doubledEnergy (N := N)) B) := by
+ symm
+ let toIndex (s : Cutoff (doubledEnergy (N := N)) B) : Cutoff (indexEnergy (N := N)) B :=
+ ⟨⟨s.1.map Fin.valEmbedding, Finset.mem_powerset.mpr (by
+ intro i hi
+ obtain ⟨j, _, rfl⟩ := Finset.mem_map.mp hi
+ exact Finset.mem_range.mpr j.isLt)⟩, (doubledEnergy_map_val s.1).le.trans s.2⟩
+ apply Fintype.card_of_bijective (f := toIndex)
+ constructor
+ · intro s t h
+ exact Subtype.ext <| Finset.map_injective Fin.valEmbedding <| congrArg (fun p => p.val.val) h
+ · intro p
+ have h (i : ℕ) (hi : i ∈ p.val.val) : i < N :=
+ Finset.mem_range.mp (Finset.mem_powerset.mp p.val.property hi)
+ refine ⟨⟨p.val.val.attachFin h, ?_⟩, Subtype.ext <| Subtype.ext ?_⟩
+ · rw [← doubledEnergy_map_val, Finset.map_valEmbedding_attachFin]
+ exact p.property
+ · exact Finset.map_valEmbedding_attachFin h
+
+/-- Upper bound for the number of finite-mode matrix indices below an integer cutoff. -/
+theorem modeCutoff_card_le (N : ℕ) (B : ℤ) :
+ Fintype.card (Cutoff (fun p : Index N => (Lemmata.FockCircuits.doubledEnergy p.1 : ℤ)) B) ≤
+ cutoffCount B.toNat := by
+ rw [modeCutoff_card]
+ by_cases h : 0 ≤ B
+ · simpa only [Int.toNat_of_nonneg h] using occupationCount_le N B.toNat
+ · rw [occupationCount_of_neg N (lt_of_not_ge h)]
+ exact Nat.zero_le _
+
+/-- A finite-mode matrix with at least `E` modes realizes every state at energy at most `E`. -/
+theorem modeCutoff_card_eq (N E : ℕ) (h : E ≤ N) :
+ Fintype.card (Cutoff (fun p : Index N => (Lemmata.FockCircuits.doubledEnergy p.1 : ℤ)) E) =
+ cutoffCount E :=
+ (modeCutoff_card N E).trans (occupationCount_eq N E h)
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CrossingPlacement.lean b/lean/OAI/Computability/VPVNP/CrossingPlacement.lean
new file mode 100644
index 0000000000..69a446997f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CrossingPlacement.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.ShiftedCrossing
+import OAI.Computability.VPVNP.WireTensor
+
+/-!
+# Placing the two crossing wires at tensor parties
+
+The four roles in Lemma 3.2 are the positive and negative endpoints of the two
+wires. An arbitrary map from roles to parties may put several endpoints at one
+party. Its local basis retains a coordinate for each role at that party.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open VPVNP.WireTensor
+open scoped BigOperators
+
+/-- The two copies of `Bool` label the two wires. On either wire, `false` is
+the positive endpoint and `true` is the negative endpoint. -/
+abbrev Terminal := Bool ⊕ Bool
+
+/-- Basis label carried by each terminal. -/
+abbrev terminalBasis (x y : ℕ) : Terminal → Type
+ | .inl _ => Fin x
+ | .inr _ => Fin y
+
+instance (x y : ℕ) (r : Terminal) : Fintype (terminalBasis x y r) := by
+ cases r <;> exact inferInstanceAs (Fintype (Fin _))
+
+variable {x y plus minus : ℕ} {J k : Type*}
+
+/-- The first ordinary summand uses the cut pairing equal endpoint signs. -/
+def plusArray (k : Type*) [Ring k] (f : IntegralCrossing x y plus minus) :
+ WireTensor.Array k (terminalBasis x y) := fun z =>
+ ∑ a, (f.leftPlus a (z (.inl false)) (z (.inr false)) : k) *
+ (f.rightPlus a (z (.inl true)) (z (.inr true)) : k)
+
+/-- The second ordinary summand pairs opposite endpoint signs. -/
+def minusArray (k : Type*) [Ring k] (f : IntegralCrossing x y plus minus) :
+ WireTensor.Array k (terminalBasis x y) := fun z =>
+ ∑ a, (f.leftMinus a (z (.inl false)) (z (.inr true)) : k) *
+ (f.rightMinus a (z (.inl true)) (z (.inr false)) : k)
+
+/-- The chosen integral crossing factors sum to the product of the two
+Kronecker deltas in any coefficient ring. -/
+theorem plusArray_add_minusArray [Ring k] (f : IntegralCrossing x y plus minus)
+ (z : (r : Terminal) → terminalBasis x y r) :
+ plusArray k f z + minusArray k f z =
+ (if (z (.inl false) : Fin x) = z (.inl true) then 1 else 0) *
+ (if (z (.inr false) : Fin y) = z (.inr true) then 1 else 0) := by
+ simpa only [plusArray, minusArray, map_add, map_mul, map_sum, apply_ite (Int.castRingHom k),
+ map_one, map_zero, Int.coe_castRingHom] using congrArg (Int.castRingHom k)
+ (f.identity (z (.inl false)) (z (.inl true)) (z (.inr false)) (z (.inr true)))
+
+variable [Fintype J] [CommRing k]
+
+/-- Product of the two identity wires at the designated parties. -/
+noncomputable def terminalWires (p : Terminal → J) (x y : ℕ) : Tensor k J :=
+ tensorProduct (wire (p (.inl false)) (p (.inl true)) (Fin x))
+ (wire (p (.inr false)) (p (.inr true)) (Fin y))
+
+private def terminalEquiv (p : Terminal → J) (x y : ℕ) (j : J) :
+ (terminalWires (k := k) p x y).Basis j ≃
+ ((r : Terminal) → j = p r → terminalBasis x y r) where
+ toFun w
+ | .inl false => w.1.1
+ | .inl true => w.1.2
+ | .inr false => w.2.1
+ | .inr true => w.2.2
+ invFun z := ((z (.inl false), z (.inl true)), z (.inr false), z (.inr true))
+ left_inv _ := rfl
+ right_inv z := by funext r; rcases r with (_ | _) | (_ | _) <;> rfl
+
+/-- The direct sum of the two placed ordinary summands locally restricts to
+the two-wire tensor. This covers arbitrary coincidences among all terminals. -/
+theorem placed_crossing_restricts (p : Terminal → J) (f : IntegralCrossing x y plus minus) :
+ Restricts (directSum (placedTensor p (terminalBasis x y) (plusArray k f))
+ (placedTensor p (terminalBasis x y) (minusArray k f))) (terminalWires p x y) := by
+ let P := placedTensor p (terminalBasis x y) (plusArray k f)
+ let M := placedTensor p (terminalBasis x y) (minusArray k f)
+ apply (directSum_restricts_add P.coeff M.coeff).trans
+ apply (restricts_of_reindex (fun j => terminalEquiv p x y j) _).1
+ intro z
+ let coords : (r : Terminal) → terminalBasis x y r :=
+ fun r => terminalEquiv p x y (p r) (z (p r)) r rfl
+ change (terminalWires p x y).coeff z = plusArray k f coords + minusArray k f coords
+ rw [plusArray_add_minusArray]
+ have hxPlus : coords (.inl false) = (z (p (.inl false))).1.1 rfl := rfl
+ have hxMinus : coords (.inl true) = (z (p (.inl true))).1.2 rfl := rfl
+ have hyPlus : coords (.inr false) = (z (p (.inr false))).2.1 rfl := rfl
+ have hyMinus : coords (.inr true) = (z (p (.inr true))).2.2 rfl := rfl
+ simp only [terminalWires, tensorProduct, wire, hxPlus, hxMinus, hyPlus, hyMinus]
+ split_ifs <;> simp_all
+
+/-- Side of the two-center cut. The second cut reverses the ends of the Y wire. -/
+def cutSide (flipY : Bool) : Terminal → Bool
+ | .inl b => b
+ | .inr b => b.xor flipY
+
+/-- The four terminal wires to their respective centers and the wire carrying
+the factorization index between the two centers. -/
+noncomputable def crossingNetwork (p : Terminal → J) (center : Bool → J)
+ (flipY : Bool) (x y rank : ℕ) : Tensor k J :=
+ wireNetwork (cutSource p center) (cutTarget (cutSide flipY) center)
+ (cutBasis (terminalBasis x y) (Fin rank))
+
+/-- Realize the two shifted factors at independently placed pairs of centers.
+A local restriction of the direct sum of the two wire networks gives the two
+original identity wires at the four terminals. -/
+theorem crossingNetworks_restricts (p : Terminal → J) (centerPlus centerMinus : Bool → J)
+ (f : IntegralCrossing x y plus minus) :
+ Restricts (directSum (crossingNetwork p centerPlus false x y plus)
+ (crossingNetwork p centerMinus true x y minus)) (terminalWires (k := k) p x y) := by
+ apply Restricts.trans _ (placed_crossing_restricts p f)
+ apply directSum_restricts
+ · exact cutFactorization_restricts p (cutSide false) centerPlus (terminalBasis x y) (Fin plus)
+ (fun z a => (f.leftPlus a (z (.inl false) rfl) (z (.inr false) rfl) : k))
+ (fun z a => (f.rightPlus a (z (.inl true) rfl) (z (.inr true) rfl) : k))
+ · exact cutFactorization_restricts p (cutSide true) centerMinus (terminalBasis x y) (Fin minus)
+ (fun z a => (f.leftMinus a (z (.inl false) rfl) (z (.inr true) rfl) : k))
+ (fun z a => (f.rightMinus a (z (.inl true) rfl) (z (.inr false) rfl) : k))
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CrossingSpectralBound.lean b/lean/OAI/Computability/VPVNP/CrossingSpectralBound.lean
new file mode 100644
index 0000000000..f80898968a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CrossingSpectralBound.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.CrossingPlacement
+import OAI.Computability.VPVNP.WireSpectrum
+
+/-!
+# Spectral bounds for the two shifted crossing cuts
+
+Section 3.2 of *VP and VNP differ over every field* places four terminals and
+two pairs of auxiliary centers at a single spectral point. The two cuts have
+independent ranks. This file derives the numerical inequality in the wire
+distances from the integral factors and local restrictions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open VPVNP.WireTensor
+open scoped NNReal
+
+variable {k J : Type*} [Field k] [Fintype J] (F : SpectralPoint k J)
+variable {x y plus minus : ℕ}
+
+/-- The sum of the spectral values of the two cut networks bounds the value
+of the original wires, including when some of the wire dimensions vanish. -/
+theorem crossing_value_le (p : Terminal → J) (cp cm : Bool → J)
+ (f : IntegralCrossing x y plus minus) :
+ F.value (terminalWires p x y) ≤ F.value (crossingNetwork p cp false x y plus) +
+ F.value (crossingNetwork p cm true x y minus) :=
+ (F.monotone (crossingNetworks_restricts p cp cm f)).trans_eq (F.value_directSum _ _)
+
+private theorem card_fin_instance (n : ℕ) (inst : Fintype (Fin n)) :
+ @Fintype.card (Fin n) inst = n := by
+ exact (@Fintype.card_congr _ _ inst (Fin.fintype n) (Equiv.refl _)).trans (Fintype.card_fin n)
+
+/-- The four terminal wires and one rank wire give the cost of either cut.
+Reversing the second wire exchanges its assignments to the two centers. -/
+theorem crossingNetwork_value (p : Terminal → J) (c : Bool → J) (flipY : Bool) {rank : ℕ}
+ (hx : 0 < x) (hy : 0 < y) (hr : 0 < rank) :
+ (F.value (crossingNetwork p c flipY x y rank) : ℝ) =
+ (x : ℝ) ^ (F.wireDistance (p (.inl false)) (c false) +
+ F.wireDistance (p (.inl true)) (c true)) *
+ (y : ℝ) ^ (F.wireDistance (p (.inr flipY)) (c false) +
+ F.wireDistance (p (.inr (!flipY))) (c true)) *
+ (rank : ℝ) ^ F.wireDistance (c false) (c true) := by
+ have hx' : 0 < (x : ℝ) := Nat.cast_pos.mpr hx
+ have hy' : 0 < (y : ℝ) := Nat.cast_pos.mpr hy
+ let dims : Option Terminal → ℕ
+ | none => rank
+ | some (.inl _) => x
+ | some (.inr _) => y
+ have hcard (e : Option Terminal) :
+ Fintype.card (cutBasis (terminalBasis x y) (Fin rank) e) = dims e := by
+ rcases e with _ | (b | b) <;> exact card_fin_instance _ _
+ unfold crossingNetwork
+ rw [F.value_wireNetwork_eq_prod_rpow]
+ · simp only [hcard, Fintype.prod_option, Fintype.prod_sum_type, Fintype.prod_bool]
+ cases flipY <;>
+ simp only [dims, cutSource, cutTarget, cutSide, Bool.xor_false, Bool.xor_true,
+ Bool.not_true, Bool.not_false, Real.rpow_add hx', Real.rpow_add hy'] <;> ring
+ · intro e
+ rw [hcard]
+ rcases e with _ | (b | b)
+ · exact hr
+ · exact hx
+ · exact hy
+
+/-- The spectral inequality used in the proof of norm rigidity. Both pairs
+of centers and all four terminals may occupy arbitrary, even coincident,
+parties at the same spectral point. The cut ranks need not agree. -/
+theorem crossing_spectral_inequality (p : Terminal → J) (cp cm : Bool → J)
+ (hx : 0 < x) (hy : 0 < y) (hp : 0 < plus) (hm : 0 < minus)
+ (f : IntegralCrossing x y plus minus) :
+ (x : ℝ) ^ F.wireDistance (p (.inl false)) (p (.inl true)) *
+ (y : ℝ) ^ F.wireDistance (p (.inr false)) (p (.inr true)) ≤
+ (x : ℝ) ^ (F.wireDistance (p (.inl false)) (cp false) +
+ F.wireDistance (p (.inl true)) (cp true)) *
+ (y : ℝ) ^ (F.wireDistance (p (.inr false)) (cp false) +
+ F.wireDistance (p (.inr true)) (cp true)) *
+ (plus : ℝ) ^ F.wireDistance (cp false) (cp true) +
+ (x : ℝ) ^ (F.wireDistance (p (.inl false)) (cm false) +
+ F.wireDistance (p (.inl true)) (cm true)) *
+ (y : ℝ) ^ (F.wireDistance (p (.inr true)) (cm false) +
+ F.wireDistance (p (.inr false)) (cm true)) *
+ (minus : ℝ) ^ F.wireDistance (cm false) (cm true) := by
+ have h := NNReal.coe_le_coe.mpr (crossing_value_le F p cp cm f)
+ simpa only [terminalWires, F.value_tensorProduct, NNReal.coe_mul, NNReal.coe_add,
+ F.value_wire_eq_rpow _ _ hx, F.value_wire_eq_rpow _ _ hy,
+ crossingNetwork_value F p cp false hx hy hp, crossingNetwork_value F p cm true hx hy hm,
+ Bool.not_true, Bool.not_false] using h
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CubeExclusion.lean b/lean/OAI/Computability/VPVNP/CubeExclusion.lean
new file mode 100644
index 0000000000..f56f970043
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CubeExclusion.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.GrassmannCompactness
+import Mathlib.Data.Finset.SymmDiff
+import Mathlib.Topology.MetricSpace.Pseudo.Constructions
+
+/-!
+# Enlarging a class of targets by the real line
+
+In Section 5.1 of *VP and VNP differ over every field*, uniform exclusion
+passes to every larger cube by restriction to a face. In dimension at least
+two the real line can then be included among the targets. Every triple on
+the real line satisfies a closed polynomial identity on its distances, while
+three corners of a Euclidean square violate that identity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Set
+open scoped symmDiff
+
+universe u
+
+variable {κ : Type*} (X : κ → Type u) [∀ k, PseudoMetricSpace (X k)]
+
+/-- Euclidean distances between the corners of the unit cube. -/
+noncomputable def cubeDistances (ℓ : ℕ) (A B : Finset (Fin ℓ)) : ℝ :=
+ √((A ∆ B).card : ℝ)
+
+theorem cube_exclusion_mono {ℓ L : ℕ} (h : ℓ ≤ L)
+ (hQ : cubeDistances ℓ ∉ closure (markedDistances X (Finset (Fin ℓ)))) :
+ cubeDistances L ∉ closure (markedDistances X (Finset (Fin L))) := by
+ let e := Fin.castLEEmb h
+ let f := fun (D : Finset (Fin L) → Finset (Fin L) → ℝ) (A B : Finset (Fin ℓ)) =>
+ D (A.map e) (B.map e)
+ have hf : MapsTo f (markedDistances X _) (markedDistances X _) := by
+ rintro _ ⟨k, s, hs, x, rfl⟩
+ exact ⟨k, s, hs, fun A => x (A.map e), rfl⟩
+ have hc : Continuous f := by dsimp [f]; fun_prop
+ have heq : f (cubeDistances L) = cubeDistances ℓ := by
+ ext A B
+ have hdiff : (A ∆ B).map e = A.map e ∆ B.map e := by
+ simp only [Finset.symmDiff_def, Finset.map_union, Finset.map_sdiff]
+ simp only [f, cubeDistances, ← hdiff, Finset.card_map]
+ exact fun hmem => hQ (heq ▸ hf.closure hc hmem)
+
+/-- Add the real line at the extra index `none`. -/
+def withRealLine (X : κ → Type u) : Option κ → Type u
+ | none => ULift.{u} ℝ
+ | some k => X k
+
+instance (k : Option κ) : PseudoMetricSpace (withRealLine X k) := by
+ cases k <;> unfold withRealLine <;> infer_instance
+
+instance [∀ k, CompleteSpace (X k)] (k : Option κ) : CompleteSpace (withRealLine X k) := by
+ cases k <;> unfold withRealLine <;> infer_instance
+
+instance [∀ k, Nonempty (X k)] (k : Option κ) : Nonempty (withRealLine X k) := by
+ cases k <;> unfold withRealLine <;> infer_instance
+
+theorem withRealLine_hasCATZeroSegments (hcat : ∀ k, SpectralGeometry.HasCATZeroSegments (X k)) :
+ ∀ k, SpectralGeometry.HasCATZeroSegments (withRealLine X k) := by
+ intro k
+ cases k with
+ | some k => exact hcat k
+ | none =>
+ intro x y t _ _
+ refine ⟨ULift.up ((1 - t) * x.down + t * y.down), fun z => ?_⟩
+ change dist z.down ((1 - t) * x.down + t * y.down) ^ 2 ≤
+ (1 - t) * dist z.down x.down ^ 2 + t * dist z.down y.down ^ 2 -
+ t * (1 - t) * dist x.down y.down ^ 2
+ simp only [Real.dist_eq, sq_abs]
+ exact le_of_eq (by ring)
+
+/-- On the line a triple has zero squared area. This is a closed condition
+on ordinary distances, including after any choice of scale. -/
+private theorem line_triple_closure {J : Type*} {D : J → J → ℝ}
+ (hD : D ∈ closure (markedDistances (fun _ : Unit => ℝ) J)) (a b c : J) :
+ (D a c ^ 2 - D a b ^ 2 - D b c ^ 2) ^ 2 = 4 * D a b ^ 2 * D b c ^ 2 := by
+ let S : Set (J → J → ℝ) := {A | (A a c ^ 2 - A a b ^ 2 - A b c ^ 2) ^ 2 =
+ 4 * A a b ^ 2 * A b c ^ 2}
+ have hclosed : IsClosed S := isClosed_eq (by fun_prop) (by fun_prop)
+ apply closure_minimal (t := S) _ hclosed hD
+ rintro _ ⟨_, s, _, x, rfl⟩
+ simp only [S, mem_ofPred_eq, Real.dist_eq, mul_pow, sq_abs]
+ ring
+
+/-- The Euclidean square has a right triangle of side lengths `1`, `1`, `√2`. -/
+theorem realLine_cube_exclusion {ℓ : ℕ} (hℓ : 2 ≤ ℓ) :
+ cubeDistances ℓ ∉ closure (markedDistances (fun _ : Unit => ℝ) (Finset (Fin ℓ))) := by
+ apply cube_exclusion_mono (fun _ : Unit => ℝ) hℓ
+ intro hD
+ have h := line_triple_closure hD {0} ∅ {1}
+ have h2 : (({0} : Finset (Fin 2)) ∆ {1}).card = 2 := by decide
+ have h1 : (({0} : Finset (Fin 2)) ∆ ∅).card = 1 := by decide
+ have h1' : ((∅ : Finset (Fin 2)) ∆ {1}).card = 1 := by decide
+ simp only [cubeDistances, Real.sq_sqrt (Nat.cast_nonneg _), h1, h1', h2] at h
+ norm_num at h
+
+/-- Marked arrays for the enlarged class are the union of the two classes
+of arrays, so uniform exclusion in dimension at least two is preserved. -/
+theorem withRealLine_cube_exclusion {ℓ : ℕ} (hℓ : 2 ≤ ℓ)
+ (hQ : cubeDistances ℓ ∉ closure (markedDistances X (Finset (Fin ℓ)))) :
+ cubeDistances ℓ ∉ closure (markedDistances (withRealLine X) (Finset (Fin ℓ))) := by
+ have hs : markedDistances (withRealLine X) (Finset (Fin ℓ)) ⊆
+ markedDistances X _ ∪ markedDistances (fun _ : Unit => ℝ) _ := by
+ rintro _ ⟨k, s, hs, x, rfl⟩
+ cases k with
+ | none => exact Or.inr ⟨(), s, hs, fun A => (x A).down, rfl⟩
+ | some k => exact Or.inl ⟨k, s, hs, x, rfl⟩
+ intro hmem
+ have h := closure_mono hs hmem
+ rw [closure_union] at h
+ exact h.elim hQ (realLine_cube_exclusion hℓ)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CubeFilling.lean b/lean/OAI/Computability/VPVNP/CubeFilling.lean
new file mode 100644
index 0000000000..346a69ae74
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CubeFilling.lean
@@ -0,0 +1,275 @@
+import OAI.Computability.VPVNP.FlatRectangle
+import Mathlib.Analysis.Real.Sqrt
+import Mathlib.Topology.UnitInterval
+import Mathlib.Data.Fin.Tuple.Basic
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Data.Finset.SymmDiff
+
+/-!
+# Filling a Euclidean cube from its corners
+
+The spectral wire argument uses the rigidity of flat quadrilaterals to fill an isometric
+copy of the cube from its vertex configuration. We recursively interpolate
+the two opposite faces. The induction keeps track of an entire family of
+parallel faces, so that the diagonal distances needed for each application
+of rectangle rigidity are known as well.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+open scoped unitInterval symmDiff
+
+variable {X : Type*} [MetricSpace X]
+
+/-- Squared Euclidean distance between two points in the unit cube. -/
+def cubeSquaredDistance {n : ℕ} (x y : Fin n → I) : ℝ :=
+ ∑ i, ((x i : ℝ) - y i) ^ 2
+
+private def bitCoordinate (b : Bool) : I := if b then 1 else 0
+
+private def bitCoordinates {n : ℕ} (u : Fin n → Bool) : Fin n → I :=
+ fun i ↦ bitCoordinate (u i)
+
+private def interpolateBits {V : Type*} (segment : V → V → I → V) :
+ (n : ℕ) → ((Fin n → Bool) → V) → (Fin n → I) → V
+ | 0, f, _ => f Fin.elim0
+ | n + 1, f, x => segment
+ (interpolateBits segment n (fun v ↦ f (Fin.cons false v)) (Fin.tail x))
+ (interpolateBits segment n (fun v ↦ f (Fin.cons true v)) (Fin.tail x)) (x 0)
+
+private noncomputable abbrev fillBits (h : HasCATZeroSegments X) :=
+ interpolateBits (catPoint h)
+
+private lemma fillBits_corners (h : HasCATZeroSegments X) (n : ℕ)
+ (f : (Fin n → Bool) → X) (v : Fin n → Bool) :
+ fillBits h n f (bitCoordinates v) = f v := by
+ induction n with
+ | zero => exact congrArg f (Subsingleton.elim _ _)
+ | succ n ih =>
+ obtain ⟨b, u, rfl⟩ := Fin.exists_cons v
+ have ht : Fin.tail (bitCoordinates (Fin.cons b u)) = bitCoordinates u := by
+ funext i
+ simp [Fin.tail, bitCoordinates]
+ dsimp only [fillBits] at ih
+ rw [fillBits, interpolateBits, ht, ih, ih]
+ cases b <;> simp [bitCoordinates, bitCoordinate, catPoint_zero, catPoint_one]
+
+private theorem fillBits_sq (h : HasCATZeroSegments X) (K : ℝ) (n : ℕ)
+ {J : Type*} (f : J → (Fin n → Bool) → X) (W : J → J → ℝ)
+ (hzero : ∀ i, W i i = 0)
+ (hf : ∀ i j u v, dist (f i u) (f j v) ^ 2 =
+ W i j + K * cubeSquaredDistance (bitCoordinates u) (bitCoordinates v)) :
+ ∀ i j x y, dist (fillBits h n (f i) x) (fillBits h n (f j) y) ^ 2 =
+ W i j + K * cubeSquaredDistance x y := by
+ induction n generalizing J with
+ | zero =>
+ intro i j x y
+ simpa [fillBits, interpolateBits, cubeSquaredDistance] using hf i j Fin.elim0 Fin.elim0
+ | succ n ih =>
+ let g (p : J × Bool) (u : Fin n → Bool) := f p.1 (Fin.cons p.2 u)
+ let U (p q : J × Bool) := W p.1 q.1 + K *
+ ((bitCoordinate p.2 : ℝ) - bitCoordinate q.2) ^ 2
+ have hU (p : J × Bool) : U p p = 0 := by simp [U, hzero]
+ have hg (p q : J × Bool) (u v : Fin n → Bool) :
+ dist (g p u) (g q v) ^ 2 =
+ U p q + K * cubeSquaredDistance (bitCoordinates u) (bitCoordinates v) := by
+ dsimp only [g]
+ rw [hf]
+ simp only [U, cubeSquaredDistance, Fin.sum_univ_succ, bitCoordinates, Fin.cons_zero,
+ Fin.cons_succ]
+ ring
+ have hind := ih g U hU hg
+ intro i j x y
+ let a := fillBits h n (g (i, false)) (Fin.tail x)
+ let b := fillBits h n (g (i, true)) (Fin.tail x)
+ let d := fillBits h n (g (j, false)) (Fin.tail y)
+ let c := fillBits h n (g (j, true)) (Fin.tail y)
+ let T := W i j + K * cubeSquaredDistance (Fin.tail x) (Fin.tail y)
+ have hab : dist a b ^ 2 = K := by
+ simpa [a, b, U, hzero, bitCoordinate, cubeSquaredDistance] using
+ hind (i, false) (i, true) (Fin.tail x) (Fin.tail x)
+ have hdc : dist d c ^ 2 = K := by
+ simpa [d, c, U, hzero, bitCoordinate, cubeSquaredDistance] using
+ hind (j, false) (j, true) (Fin.tail y) (Fin.tail y)
+ have had : dist a d ^ 2 = T := by
+ simpa [a, d, U, T] using hind (i, false) (j, false) (Fin.tail x) (Fin.tail y)
+ have hbc : dist b c ^ 2 = T := by
+ simpa [b, c, U, T] using hind (i, true) (j, true) (Fin.tail x) (Fin.tail y)
+ have hac : dist a c ^ 2 = K + T := by
+ simpa [a, c, U, T, bitCoordinate, add_left_comm, add_assoc, add_comm] using
+ hind (i, false) (j, true) (Fin.tail x) (Fin.tail y)
+ have hbd : dist b d ^ 2 = K + T := by
+ simpa [b, d, U, T, bitCoordinate, add_left_comm, add_assoc, add_comm] using
+ hind (i, true) (j, false) (Fin.tail x) (Fin.tail y)
+ change dist (catPoint h a b (x 0)) (catPoint h d c (y 0)) ^ 2 = _
+ rw [rectangle_interpolate h hab hdc had hbc hac hbd]
+ simp only [T, cubeSquaredDistance, Fin.sum_univ_succ, Fin.tail]
+ ring
+
+private def cornerSet {n : ℕ} (u : Fin n → Bool) : Finset (Fin n) :=
+ Finset.univ.filter fun i ↦ u i = true
+
+private lemma cornerSet_distance {n : ℕ} (u v : Fin n → Bool) :
+ cubeSquaredDistance (bitCoordinates u) (bitCoordinates v) =
+ ((cornerSet u ∆ cornerSet v).card : ℝ) := by
+ calc
+ _ = ∑ i : Fin n, if i ∈ cornerSet u ∆ cornerSet v then (1 : ℝ) else 0 := by
+ apply Finset.sum_congr rfl
+ intro i _
+ cases hu : u i <;> cases hv : v i <;>
+ simp [bitCoordinates, bitCoordinate, cornerSet, Finset.mem_symmDiff, hu, hv]
+ _ = _ := by simp
+
+/-- The corner with ones in the indicated coordinate positions. -/
+def cubeCorner {n : ℕ} (A : Finset (Fin n)) (i : Fin n) : I :=
+ if i ∈ A then 1 else 0
+
+/-- The filling by successive CAT(0) segment interpolations, starting on
+opposite faces and ending at the first coordinate. -/
+noncomputable def fillCube (h : HasCATZeroSegments X) {n : ℕ} (f : Finset (Fin n) → X) :
+ (Fin n → I) → X := fillBits h n (f ∘ cornerSet)
+
+/-- A finite prescription for extending a set of marked parties by fractional
+points. The tree depends only on the labels and fractions, so the same
+prescription can be used in each subsequent metric realization. -/
+inductive InterpolationTree (V : Type*) where
+ | vertex (label : V)
+ | segment (left right : InterpolationTree V) (fraction : I)
+
+/-- Evaluate a finite prescription in a CAT(0) space. -/
+noncomputable def InterpolationTree.eval {V : Type*} (h : HasCATZeroSegments X)
+ (f : V → X) : InterpolationTree V → X
+ | .vertex v => f v
+ | .segment left right t => catPoint h (left.eval h f) (right.eval h f) t
+
+private abbrev treeFromBits {V : Type*} (n : ℕ) (labels : (Fin n → Bool) → V) (x : Fin n → I) :=
+ interpolateBits InterpolationTree.segment n (InterpolationTree.vertex ∘ labels) x
+
+private theorem eval_treeFromBits {V : Type*} (h : HasCATZeroSegments X) (f : V → X)
+ (n : ℕ) (labels : (Fin n → Bool) → V) (x : Fin n → I) :
+ (treeFromBits n labels x).eval h f = fillBits h n (f ∘ labels) x := by
+ induction n with
+ | zero => rfl
+ | succ n ih =>
+ change catPoint h ((treeFromBits n (fun v ↦ labels (Fin.cons false v)) (Fin.tail x)).eval h f)
+ ((treeFromBits n (fun v ↦ labels (Fin.cons true v)) (Fin.tail x)).eval h f) (x 0) = _
+ rw [ih, ih]
+ rfl
+
+/-- Interpolation instructions for a specified point of the cube, using only
+the original corner labels. -/
+def cubeInterpolation {n : ℕ} (x : Fin n → I) : InterpolationTree (Finset (Fin n)) :=
+ treeFromBits n cornerSet x
+
+theorem cubeInterpolation_eval (h : HasCATZeroSegments X) {n : ℕ}
+ (f : Finset (Fin n) → X) (x : Fin n → I) :
+ (cubeInterpolation x).eval h f = fillCube h f x :=
+ eval_treeFromBits h f n cornerSet x
+
+theorem fillCube_corner (h : HasCATZeroSegments X) {n : ℕ} (f : Finset (Fin n) → X)
+ (A : Finset (Fin n)) : fillCube h f (cubeCorner A) = f A := by
+ let u : Fin n → Bool := fun i ↦ decide (i ∈ A)
+ have hc : bitCoordinates u = cubeCorner A := by
+ funext i
+ simp [bitCoordinates, bitCoordinate, cubeCorner, u]
+ have hs : cornerSet u = A := by ext i; simp [cornerSet, u]
+ rw [fillCube, ← hc, fillBits_corners, Function.comp_apply, hs]
+
+/-- If the corner squared distances are scaled Hamming distances, the full
+cube has Euclidean squared distances with the same scale. -/
+theorem fillCube_dist_sq (h : HasCATZeroSegments X) {n : ℕ} {scale : ℝ}
+ (f : Finset (Fin n) → X)
+ (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card)
+ (x y : Fin n → I) :
+ dist (fillCube h f x) (fillCube h f y) ^ 2 = scale ^ 2 * cubeSquaredDistance x y := by
+ have hg (_ _ : Unit) (u v : Fin n → Bool) :
+ dist ((f ∘ cornerSet) u) ((f ∘ cornerSet) v) ^ 2 =
+ 0 + scale ^ 2 * cubeSquaredDistance (bitCoordinates u) (bitCoordinates v) := by
+ simp [cornerSet_distance, hf]
+ simpa [fillCube] using fillBits_sq h (scale ^ 2) n (fun _ : Unit ↦ f ∘ cornerSet)
+ (fun _ _ ↦ 0) (fun _ ↦ rfl) hg () () x y
+
+/-- Straight line segments in the filled cube coincide with the corresponding
+CAT(0) segments. In particular its image is geodesically convex. -/
+theorem fillCube_segment (h : HasCATZeroSegments X) {n : ℕ} {scale : ℝ}
+ (f : Finset (Fin n) → X)
+ (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card)
+ (x y : Fin n → I) (t : I) :
+ fillCube h f (fun i ↦ Set.Icc.convexComb (x i) (y i) t) =
+ catPoint h (fillCube h f x) (fillCube h f y) t := by
+ let z : Fin n → I := fun i ↦ Set.Icc.convexComb (x i) (y i) t
+ have hx : cubeSquaredDistance z x = (t : ℝ) ^ 2 * cubeSquaredDistance x y := by
+ rw [cubeSquaredDistance, cubeSquaredDistance, Finset.mul_sum]
+ apply Finset.sum_congr rfl
+ intro i _
+ simp only [z, Set.Icc.coe_convexComb]
+ ring
+ have hy : cubeSquaredDistance z y = (1 - (t : ℝ)) ^ 2 * cubeSquaredDistance x y := by
+ rw [cubeSquaredDistance, cubeSquaredDistance, Finset.mul_sum]
+ apply Finset.sum_congr rfl
+ intro i _
+ simp only [z, Set.Icc.coe_convexComb]
+ ring
+ have hb := catPoint_bound h (fillCube h f x) (fillCube h f y) t (fillCube h f z)
+ rw [fillCube_dist_sq h f hf z x, fillCube_dist_sq h f hf z y,
+ fillCube_dist_sq h f hf x y, hx, hy] at hb
+ apply dist_eq_zero.mp
+ change dist (fillCube h f z) _ = 0
+ nlinarith only [hb]
+
+/-- The filled cube is compact. -/
+theorem isCompact_range_fillCube (h : HasCATZeroSegments X) {n : ℕ} {scale : ℝ}
+ (f : Finset (Fin n) → X)
+ (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card) :
+ IsCompact (Set.range (fillCube h f)) := by
+ apply isCompact_range
+ rw [continuous_iff_continuous_dist]
+ have he (u : (Fin n → I) × (Fin n → I)) :
+ dist (fillCube h f u.1) (fillCube h f u.2) =
+ Real.sqrt (scale ^ 2 * cubeSquaredDistance u.1 u.2) := by
+ rw [← fillCube_dist_sq h f hf, Real.sqrt_sq dist_nonneg]
+ simp_rw [he, cubeSquaredDistance]
+ fun_prop
+
+open Filter Topology in
+/-- For any ambient point, a closest point in the cube satisfies the
+CAT(0) projection inequality against every other point in the cube. -/
+theorem fillCube_nearest (h : HasCATZeroSegments X) {n : ℕ} {scale : ℝ}
+ (f : Finset (Fin n) → X)
+ (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card) (p : X) :
+ ∃ x : Fin n → I, ∀ y : Fin n → I, dist p (fillCube h f x) ^ 2 +
+ dist (fillCube h f x) (fillCube h f y) ^ 2 ≤ dist p (fillCube h f y) ^ 2 := by
+ obtain ⟨q, ⟨x, rfl⟩, hmin⟩ := (isCompact_range_fillCube h f hf).exists_isMinOn
+ (Set.range_nonempty _) (continuous_const.dist continuous_id).continuousOn
+ refine ⟨x, fun y ↦ ?_⟩
+ let q := fillCube h f x
+ let v := fillCube h f y
+ have bound (r : ℝ) (hr : 0 < r) (hr' : r ≤ 1) :
+ dist p q ^ 2 + (1 - r) * dist q v ^ 2 ≤ dist p v ^ 2 := by
+ let t : I := ⟨r, hr.le, hr'⟩
+ have hz : catPoint h q v t ∈ Set.range (fillCube h f) :=
+ ⟨_, fillCube_segment h f hf x y t⟩
+ have hqz : dist p q ≤ dist p (catPoint h q v t) := hmin hz
+ have hsq := pow_le_pow_left₀ dist_nonneg hqz 2
+ have hb := catPoint_bound h q v t p
+ change dist p (catPoint h q v t) ^ 2 ≤ (1 - r) * dist p q ^ 2 +
+ r * dist p v ^ 2 - r * (1 - r) * dist q v ^ 2 at hb
+ apply (mul_le_mul_iff_right₀ hr).mp
+ nlinarith only [hsq, hb]
+ have he : ∀ᶠ r in 𝓝[>] (0 : ℝ),
+ dist p q ^ 2 + (1 - r) * dist q v ^ 2 ≤ dist p v ^ 2 := by
+ filter_upwards [self_mem_nhdsWithin, nhdsWithin_le_nhds (gt_mem_nhds zero_lt_one)]
+ with r hr hr' using bound r hr hr'.le
+ have hc : Continuous (fun r : ℝ ↦ dist p q ^ 2 + (1 - r) * dist q v ^ 2) := by fun_prop
+ have hlim := le_of_tendsto hc.continuousWithinAt.tendsto he
+ simpa [q, v] using hlim
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CubeStar.lean b/lean/OAI/Computability/VPVNP/CubeStar.lean
new file mode 100644
index 0000000000..a718749657
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CubeStar.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.CubeFilling
+import OAI.Computability.VPVNP.SpectralGeometry
+
+/-!
+# The star estimate for cube corners in a CAT(0) space
+
+Section 4.3 of *VP and VNP differ over every field* compares the total distance
+from an ambient center to the basis vertices with the wire lengths of a
+balanced cut. The nearest point in the filled cube reduces the lower bound to
+the Euclidean star estimate, and the cut centroids also belong to that cube.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+open scoped unitInterval symmDiff
+
+noncomputable section
+
+/-- The Euclidean vector with the coordinates of a point in the unit cube. -/
+def cubeVector {n : ℕ} (x : Fin n → I) : EuclideanSpace ℝ (Fin n) :=
+ WithLp.toLp 2 fun i ↦ (x i : ℝ)
+
+theorem cubeVector_corner_singleton {n : ℕ} (i : Fin n) :
+ cubeVector (cubeCorner {i}) = EuclideanSpace.single i (1 : ℝ) := by
+ ext j
+ by_cases hj : j = i <;> simp [cubeVector, cubeCorner, EuclideanSpace.single, hj]
+
+variable {X : Type*} [MetricSpace X] {n : ℕ} {scale : ℝ}
+
+/-- The filling scales Euclidean distances by the same factor as its corners. -/
+theorem fillCube_dist (h : HasCATZeroSegments X) (f : Finset (Fin n) → X)
+ (hs : 0 ≤ scale) (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card)
+ (x y : Fin n → I) :
+ dist (fillCube h f x) (fillCube h f y) = scale * dist (cubeVector x) (cubeVector y) := by
+ apply (sq_eq_sq₀ dist_nonneg (mul_nonneg hs dist_nonneg)).mp
+ rw [fillCube_dist_sq h f hf, mul_pow, PiLp.dist_sq_eq_of_L2]
+ simp only [cubeVector, cubeSquaredDistance, PiLp.toLp_apply, Real.dist_eq, sq_abs]
+
+/-- The star estimate (4.4) in the ambient metric. Its center may lie anywhere
+in the CAT(0) space containing the cube. -/
+theorem cube_star_lower (h : HasCATZeroSegments X) (f : Finset (Fin n) → X)
+ (hs : 0 ≤ scale) (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card)
+ (p : X) :
+ scale * starLength n ≤ ∑ i : Fin n, dist p (f {i}) := by
+ obtain ⟨x, hx⟩ := fillCube_nearest h f hf p
+ have hterm (i : Fin n) :
+ scale * dist (EuclideanSpace.single i (1 : ℝ)) (cubeVector x) ≤ dist p (f {i}) := by
+ have hi := hx (cubeCorner {i})
+ rw [fillCube_dist h f hs hf, cubeVector_corner_singleton, fillCube_corner,
+ dist_comm (cubeVector x)] at hi
+ apply (sq_le_sq₀ (mul_nonneg hs dist_nonneg) dist_nonneg).mp
+ linarith only [hi, sq_nonneg (dist p (fillCube h f x))]
+ calc
+ scale * starLength n = scale * ∑ i : Fin n,
+ dist (EuclideanSpace.single i (1 : ℝ)) (basisCentroid n) := by
+ rw [basisCentroid_star_length, starLength]
+ _ ≤ scale * ∑ i : Fin n, dist (EuclideanSpace.single i (1 : ℝ)) (cubeVector x) :=
+ mul_le_mul_of_nonneg_left (basisCentroid_minimizes (cubeVector x)) hs
+ _ ≤ _ := by
+ rw [Finset.mul_sum]
+ exact Finset.sum_le_sum fun i _ ↦ hterm i
+
+/-- Unit-cube coordinates of the centroid of the basis vertices in a side of the cut. -/
+def cubeCentroidCoordinates (S : Finset (Fin n)) (i : Fin n) : I :=
+ ⟨if i ∈ S then (S.card : ℝ)⁻¹ else 0, by
+ by_cases hi : i ∈ S
+ · have hc : 1 ≤ (S.card : ℝ) := by exact_mod_cast Finset.card_pos.mpr ⟨i, hi⟩
+ simp only [hi, ↓reduceIte, Set.mem_Icc]
+ exact ⟨by positivity, inv_le_one_of_one_le₀ hc⟩
+ · simp [hi]⟩
+
+private theorem cubeVector_centroid (S : Finset (Fin n)) :
+ cubeVector (cubeCentroidCoordinates S) = subsetCentroid S := rfl
+
+/-- The side centroid realized in the CAT(0) target by filling the marked cube. -/
+def filledSubsetCentroid (h : HasCATZeroSegments X)
+ (f : Finset (Fin n) → X) (S : Finset (Fin n)) : X :=
+ fillCube h f (cubeCentroidCoordinates S)
+
+/-- The distance from an individual basis terminal to a side centroid. -/
+theorem basis_dist_filledSubsetCentroid (h : HasCATZeroSegments X)
+ (f : Finset (Fin n) → X) (hs : 0 ≤ scale)
+ (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card)
+ (S : Finset (Fin n)) (i : Fin n) :
+ dist (f {i}) (filledSubsetCentroid h f S) =
+ scale * dist (EuclideanSpace.single i (1 : ℝ)) (subsetCentroid S) := by
+ rw [← fillCube_corner h f {i}, filledSubsetCentroid, fillCube_dist h f hs hf,
+ cubeVector_corner_singleton, cubeVector_centroid]
+
+/-- Total distance of one side's terminal wires in a scaled CAT(0) cube. -/
+theorem filledSubsetCentroid_star_length (h : HasCATZeroSegments X)
+ (f : Finset (Fin n) → X) (hs : 0 ≤ scale)
+ (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card)
+ (S : Finset (Fin n)) :
+ ∑ i ∈ S, dist (f {i}) (filledSubsetCentroid h f S) =
+ scale * √((S.card : ℝ) * ((S.card : ℝ) - 1)) := by
+ simp only [basis_dist_filledSubsetCentroid h f hs hf, ← Finset.mul_sum,
+ subsetCentroid_star_length]
+
+/-- Distance between the centroids of disjoint sides of a scaled CAT(0) cube. -/
+theorem disjoint_filledSubsetCentroids_dist (h : HasCATZeroSegments X)
+ (f : Finset (Fin n) → X) (hs : 0 ≤ scale)
+ (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card)
+ {S T : Finset (Fin n)} (hST : Disjoint S T) :
+ dist (filledSubsetCentroid h f S) (filledSubsetCentroid h f T) =
+ scale * √((S.card : ℝ)⁻¹ + (T.card : ℝ)⁻¹) := by
+ rw [filledSubsetCentroid, filledSubsetCentroid, fillCube_dist h f hs hf,
+ cubeVector_centroid, cubeVector_centroid, disjoint_subsetCentroids_dist hST]
+
+/-- In a positively scaled cube of dimension at least `18 * C²`, a balanced
+two-centroid layout costs strictly less than a star with any ambient center. -/
+theorem filled_balancedLayout_strict (h : HasCATZeroSegments X) {C : ℝ}
+ (f : Finset (Fin n) → X) (hs : 0 < scale)
+ (hf : ∀ A B, dist (f A) (f B) ^ 2 = scale ^ 2 * (A ∆ B).card)
+ (hC : 1 ≤ C) (hdim : 18 * C ^ 2 ≤ n)
+ (S : Finset (Fin n)) (hlo : n ≤ 3 * S.card) (hhi : 3 * S.card ≤ 2 * n) (p : X) :
+ (∑ i ∈ S, dist (f {i}) (filledSubsetCentroid h f S)) +
+ (∑ i ∈ Sᶜ, dist (f {i}) (filledSubsetCentroid h f Sᶜ)) +
+ C * dist (filledSubsetCentroid h f S) (filledSubsetCentroid h f Sᶜ) <
+ ∑ i : Fin n, dist p (f {i}) := by
+ have he := balancedLayout_strict hC hdim S hlo hhi (basisCentroid n)
+ rw [subsetCentroid_star_length, subsetCentroid_star_length,
+ disjoint_subsetCentroids_dist disjoint_compl_right, basisCentroid_star_length] at he
+ apply lt_of_lt_of_le _ (cube_star_lower h f hs.le hf p)
+ rw [filledSubsetCentroid_star_length h f hs.le hf,
+ filledSubsetCentroid_star_length h f hs.le hf,
+ disjoint_filledSubsetCentroids_dist h f hs.le hf disjoint_compl_right]
+ rw [mul_left_comm C scale, ← mul_add, ← mul_add]
+ exact mul_lt_mul_of_pos_left he hs
+
+end
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorBounds.lean b/lean/OAI/Computability/VPVNP/CursorBounds.lean
new file mode 100644
index 0000000000..9866ef6abd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorBounds.lean
@@ -0,0 +1,228 @@
+import OAI.Computability.VPVNP.CursorRouting
+import OAI.Computability.VPVNP.RAMParameters
+
+/-!
+# Size of the routed network before compression
+
+In §§11–12 of *VP and VNP differ over every field*, the virtual group uses the least
+power-of-two site count that accommodates the pair parser's budget. One circuit of
+cursor positions routes each message, with separate fields for each mask. These exact
+choices give the position and maximum-width bounds needed in equation (12.1).
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorBounds
+
+open VPVNP.Compression
+
+/-- The live processor address length in Section 9.1. -/
+abbrev addressBits := BurstRAM.addressWidth
+
+/-- Live processors indexed by their binary addresses. -/
+def processorCount (B n : ℕ) : ℕ := 2 ^ addressBits B n
+
+/-- The least binary virtual address length giving enough bucket slots. -/
+def virtualBits (B n : ℕ) : ℕ := BurstRAM.virtualSiteExponent (addressBits B n) n
+
+theorem virtualBits_le_iff (B n d : ℕ) : virtualBits B n ≤ d ↔
+ processorCount B n * n * Nat.clog 2 n ≤ 2 ^ d * virtualBucket n := by
+ simpa only [virtualBits, processorCount, virtualBucket, BurstRAM.roundedUp_eq, Nat.cast_one,
+ Nat.cast_ofNat] using BurstRAM.virtualSiteExponent_le_iff (addressBits B n) n d
+
+/-- Rounding the virtual processor count to a power of two costs at most a factor of two. -/
+theorem virtualCount_bound (B n : ℕ) (hn : 2 ≤ n) :
+ ((2 ^ virtualBits B n : ℕ) : ℝ) ≤
+ 2 * (processorCount B n : ℝ) * (n : ℝ) ^ (3 / 4 : ℝ) * (Nat.clog 2 n : ℝ) := by
+ have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast (show 1 ≤ n by omega)
+ have hnpos := zero_lt_one.trans_le hn'
+ cases hD : virtualBits B n with
+ | zero =>
+ have hP : 1 ≤ processorCount B n := Nat.one_le_pow _ _ Nat.zero_lt_two
+ have hc := Nat.clog_pos Nat.one_lt_two (show 1 < n by omega)
+ have hP' : (1 : ℝ) ≤ processorCount B n := by exact_mod_cast hP
+ have hc' : (1 : ℝ) ≤ Nat.clog 2 n := by exact_mod_cast hc
+ have hn34 := Real.one_le_rpow hn' (by norm_num : (0 : ℝ) ≤ 3 / 4)
+ simp only [pow_zero, Nat.cast_one]
+ calc
+ 1 ≤ 2 * (1 : ℝ) * 1 * 1 := by norm_num
+ _ ≤ _ := by gcongr
+ | succ d =>
+ have hlt : 2 ^ d * virtualBucket n < processorCount B n * n * Nat.clog 2 n := by
+ apply lt_of_not_ge
+ intro h
+ have hd := (virtualBits_le_iff B n d).mpr h
+ omega
+ have hlt' : ((2 ^ d : ℕ) : ℝ) * virtualBucket n <
+ (processorCount B n : ℝ) * n * Nat.clog 2 n := by exact_mod_cast hlt
+ have hfrac : (n : ℝ) ^ (3 / 4 : ℝ) * (n : ℝ) ^ (1 / 4 : ℝ) = n := by
+ rw [← Real.rpow_add hnpos]
+ norm_num
+ apply le_of_mul_le_mul_right _ (Real.rpow_pos_of_pos hnpos (1 / 4))
+ calc
+ ((2 ^ (d + 1) : ℕ) : ℝ) * (n : ℝ) ^ (1 / 4 : ℝ)
+ ≤ 2 * (((2 ^ d : ℕ) : ℝ) * virtualBucket n) := by
+ rw [pow_succ, Nat.cast_mul, Nat.cast_ofNat, mul_comm _ (2 : ℝ), mul_assoc]
+ gcongr
+ exact (virtualBucket_bounds (by omega : 1 ≤ n)).1
+ _ ≤ 2 * ((processorCount B n : ℝ) * n * Nat.clog 2 n) := by gcongr
+ _ = 2 * (processorCount B n : ℝ) * (n : ℝ) ^ (3 / 4 : ℝ) * (Nat.clog 2 n : ℝ) *
+ (n : ℝ) ^ (1 / 4 : ℝ) := by
+ conv_lhs => rw [← hfrac]
+ ring
+
+
+/-- The rounded binary logarithm and the paper's real-log convention agree at all lengths. -/
+theorem addressBits_eq_ceil (B n : ℕ) :
+ addressBits B n = B * ⌈Real.logb 2 n⌉₊ := by
+ rw [addressBits, BurstRAM.addressWidth, ← Real.natCeil_logb_natCast 2 n]
+ rfl
+
+/-- At most two extra logarithmic terms in the virtual processor address length:
+one for the word length `n`, one for its rounded binary logarithm. -/
+theorem virtualBits_le (B n : ℕ) : virtualBits B n ≤ (B + 2) * Nat.clog 2 n := by
+ let c := Nat.clog 2 n
+ have hn : n ≤ 2 ^ c := Nat.le_pow_clog Nat.one_lt_two _
+ have hc : c ≤ 2 ^ c := Nat.lt_two_pow_self.le
+ unfold virtualBits BurstRAM.virtualSiteExponent
+ apply (Nat.sub_le _ _).trans
+ apply Nat.clog_le_of_le_pow
+ calc
+ processorCount B n * n * c ≤ 2 ^ (B * c) * 2 ^ c * 2 ^ c :=
+ Nat.mul_le_mul (Nat.mul_le_mul_left (2 ^ (B * c)) hn) hc
+ _ = 2 ^ ((B + 2) * c) := by rw [← pow_add, ← pow_add]; ring_nf
+
+/-- At large lengths the virtual group retains at least the live number of address
+bits. Thus reserving a fixed number of fresh lane bits per compressor block is possible. -/
+theorem addressBits_le_virtualBits (B n : ℕ) (hn : 3 ≤ n) :
+ addressBits B n ≤ virtualBits B n := by
+ have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast (show 1 ≤ n by omega)
+ have hcap := (virtualBits_le_iff B n (virtualBits B n)).mp le_rfl
+ have hc : 2 ≤ Nat.clog 2 n :=
+ (Nat.lt_clog_iff_pow_lt Nat.one_lt_two).mpr (show 2 ^ 1 < n by omega)
+ have hpow : (n : ℝ) ^ (1 / 4 : ℝ) ≤ n := by
+ simpa using Real.rpow_le_rpow_of_exponent_le hn' (by norm_num : (1 / 4 : ℝ) ≤ 1)
+ have hK : virtualBucket n ≤ 2 * n := by
+ exact_mod_cast (virtualBucket_bounds (by omega : 1 ≤ n)).2.trans
+ (mul_le_mul_of_nonneg_left hpow (by norm_num : (0 : ℝ) ≤ 2))
+ have hKN : virtualBucket n ≤ n * Nat.clog 2 n := by
+ calc
+ _ ≤ 2 * n := hK
+ _ = n * 2 := Nat.mul_comm _ _
+ _ ≤ _ := Nat.mul_le_mul_left _ hc
+ have hsize : processorCount B n * virtualBucket n ≤ 2 ^ virtualBits B n * virtualBucket n :=
+ (Nat.mul_le_mul_left (processorCount B n) hKN).trans (by simpa [mul_assoc] using hcap)
+ apply (Nat.pow_le_pow_iff_right Nat.one_lt_two).mp
+ exact Nat.le_of_mul_le_mul_right hsize (Nat.two_pow_pos _)
+
+theorem laneBudget (B lanes n : ℕ) (hB : lanes ≤ B) {θ : ℝ} (hθ : θ ≤ 1) (hn : 3 ≤ n) :
+ lanes * blockCount θ n ≤ virtualBits B n := by
+ have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast (show 1 ≤ n by omega)
+ have hlog : 0 ≤ Real.logb 2 (n : ℝ) := Real.logb_nonneg (by norm_num) hn'
+ have ht : blockCount θ n ≤ Nat.clog 2 n := by
+ rw [blockCount, ← Real.natCeil_logb_natCast 2 n]
+ exact (Nat.floor_le_floor (mul_le_of_le_one_left hlog hθ)).trans (Nat.floor_le_ceil _)
+ exact (Nat.mul_le_mul hB ht).trans (addressBits_le_virtualBits B n hn)
+
+/-- The virtual word length is inherited from the live RAM. -/
+def wordBits (B n : ℕ) : ℕ := (addressBits B n + 10) ^ 4
+
+/-- Count the actual processor-cursor positions in the graph of §12. -/
+noncomputable def initialPositions (B n : ℕ) : ℕ :=
+ 2 ^ virtualBits B n * virtualBits B n
+
+/-- Width of one directed cursor arc, reserving a disjoint payload for each mask system. -/
+noncomputable def initialWidth (B n : ℕ) : ℕ :=
+ ∑ s : CursorRouting.RAMSystem (virtualBits B n),
+ CursorRouting.ramFieldBits (virtualBucket n) (wordBits B n) s
+
+theorem initialPositions_card (B n : ℕ) : initialPositions B n =
+ Fintype.card (CursorRouting.Site (virtualBits B n) × Fin (virtualBits B n)) :=
+ (CursorRouting.cursorPositions_card _).symm
+
+private theorem arcWidth_le (D H w : ℕ) (hH : 1 ≤ H) :
+ (∑ s : CursorRouting.RAMSystem D, CursorRouting.ramFieldBits H w s) ≤
+ 28 * H * (D + 1) ^ 2 * w := by
+ have hD : D ≤ (D + 1) ^ 2 := by nlinarith
+ have hL : RAMLayout.layerCount D ≤ (D + 1) ^ 2 := by
+ rw [RAMLayout.layerCount, Nat.choose_two_right]
+ apply (Nat.div_le_self _ _).trans
+ rw [pow_two]
+ gcongr
+ omega
+ rw [CursorRouting.ramArcWidth, RAMLayout.blockBits]
+ calc
+ _ ≤ (D + 1) ^ 2 * (8 * (H * w)) + (D + 1) ^ 2 * (4 * H * 5 * w) := by
+ gcongr
+ exact Nat.le_mul_of_pos_left _ hH
+ _ = _ := by ring
+
+/-- Pointwise initial-position bound with explicit logarithmic factors. -/
+theorem initialPositions_bound (B n : ℕ) (hn : 2 ≤ n) :
+ (initialPositions B n : ℝ) ≤
+ (2 * ((B : ℝ) + 2)) * (processorCount B n : ℝ) *
+ (n : ℝ) ^ (3 / 4 : ℝ) * ((n.log2 : ℝ) + 1) ^ 2 := by
+ let c := Nat.clog 2 n
+ have hD : (virtualBits B n : ℝ) ≤ ((B : ℝ) + 2) * c := by
+ exact_mod_cast virtualBits_le B n
+ have hL : (c : ℝ) ≤ (n.log2 : ℝ) + 1 := by exact_mod_cast BurstRAM.clog_le_log2_succ n
+ have hR := virtualCount_bound B n hn
+ rw [initialPositions, Nat.cast_mul]
+ calc
+ _ ≤ (2 * (processorCount B n : ℝ) * (n : ℝ) ^ (3 / 4 : ℝ) * c) *
+ (((B : ℝ) + 2) * c) := mul_le_mul hR hD (by positivity) (by positivity)
+ _ ≤ (2 * (processorCount B n : ℝ) * (n : ℝ) ^ (3 / 4 : ℝ) * ((n.log2 : ℝ) + 1)) *
+ (((B : ℝ) + 2) * ((n.log2 : ℝ) + 1)) := by gcongr
+ _ = _ := by ring
+
+/-- Pointwise initial arc-width bound with explicit logarithmic factors. -/
+theorem initialWidth_bound (B n : ℕ) (hn : 2 ≤ n) :
+ (initialWidth B n : ℝ) ≤
+ (56 * ((B : ℝ) + 3) ^ 2 * ((B : ℝ) + 10) ^ 4) *
+ (n : ℝ) ^ (1 / 4 : ℝ) * ((n.log2 : ℝ) + 1) ^ 6 := by
+ let L := n.log2 + 1
+ have hD : virtualBits B n + 1 ≤ (B + 3) * L := by
+ have h := (virtualBits_le B n).trans (Nat.mul_le_mul_left _ (BurstRAM.clog_le_log2_succ n))
+ dsimp [L]
+ nlinarith
+ have hw : wordBits B n ≤ ((B + 10) * L) ^ 4 := by
+ unfold wordBits addressBits BurstRAM.addressWidth
+ apply Nat.pow_le_pow_left
+ have h := Nat.mul_le_mul_left B (BurstRAM.clog_le_log2_succ n)
+ dsimp [L]
+ nlinarith
+ have hK : 1 ≤ virtualBucket n := Nat.two_pow_pos _
+ have hwidth : initialWidth B n ≤ 28 * virtualBucket n * ((B + 3) * L) ^ 2 *
+ ((B + 10) * L) ^ 4 := by
+ apply (arcWidth_le _ _ _ hK).trans
+ gcongr
+ have hwidth' : (initialWidth B n : ℝ) ≤ 28 * (virtualBucket n : ℝ) *
+ (((B : ℝ) + 3) * ((n.log2 : ℝ) + 1)) ^ 2 *
+ (((B : ℝ) + 10) * ((n.log2 : ℝ) + 1)) ^ 4 := by exact_mod_cast hwidth
+ calc
+ _ ≤ _ := hwidth'
+ _ ≤ 28 * (2 * (n : ℝ) ^ (1 / 4 : ℝ)) *
+ (((B : ℝ) + 3) * ((n.log2 : ℝ) + 1)) ^ 2 *
+ (((B : ℝ) + 10) * ((n.log2 : ℝ) + 1)) ^ 4 := by
+ gcongr
+ exact (virtualBucket_bounds (by omega : 1 ≤ n)).2
+ _ = _ := by ring
+
+open Filter in
+/-- The two pre-compression estimates of §12 hold simultaneously for fixed `B`. -/
+theorem initialBounds (B : ℕ) :
+ ∃ A W : ℝ, ∃ s t : ℕ, ∀ᶠ n : ℕ in atTop,
+ (initialPositions B n : ℝ) ≤ A * (processorCount B n : ℝ) *
+ (n : ℝ) ^ (3 / 4 : ℝ) * ((n.log2 : ℝ) + 1) ^ s ∧
+ (initialWidth B n : ℝ) ≤ W * (n : ℝ) ^ (1 / 4 : ℝ) * ((n.log2 : ℝ) + 1) ^ t := by
+ refine ⟨2 * ((B : ℝ) + 2), 56 * ((B : ℝ) + 3) ^ 2 * ((B : ℝ) + 10) ^ 4,
+ 2, 6, eventually_atTop.mpr ⟨2, fun n hn => ?_⟩⟩
+ exact ⟨initialPositions_bound B n hn, initialWidth_bound B n hn⟩
+
+end CursorBounds
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorBranchBudget.lean b/lean/OAI/Computability/VPVNP/CursorBranchBudget.lean
new file mode 100644
index 0000000000..e367975080
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorBranchBudget.lean
@@ -0,0 +1,202 @@
+import OAI.Computability.VPVNP.IteratedCompression
+import OAI.Computability.VPVNP.CursorState
+import OAI.Computability.VPVNP.CursorCompressionBudget
+
+/-!
+# Budgets of a selected compressed cursor network
+
+Section 12 bounds the shared bits, local records and total number of
+history occurrences on each branch. Here the input carries the real
+sorting and successor fields of the virtual RAM. The threshold precedes
+the lane labeling, coefficient assignment and compressor branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open Compression CursorBounds CursorRouting Filter
+
+variable {k : Type*} [Field k] {S : BlockSchedule k}
+
+/-- Place the virtual RAM at the cursor-zero positions and reserve the
+successor and sorting message fields on both physical routing arcs. -/
+noncomputable def pairInput (S : BlockSchedule k) {b n base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n) :
+ State (S.degreeExponent 0) lanes :=
+ cursorState labels hD (Nat.add_sub_of_le S.degree_bounds.1)
+ (ramFieldBits (virtualBucket n) (wordBits b n) : RAMSystem (virtualBits b n) → ℕ)
+
+theorem pairInput_positions (S : BlockSchedule k) {b n base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n) :
+ (pairInput S labels hD).positions = initialPositions b n :=
+ cursorState_positions _ _ _ _
+
+theorem pairInput_maxWireWidth (S : BlockSchedule k) {b n base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n) :
+ (pairInput S labels hD).maxWireWidth ≤ initialWidth b n := by
+ apply Finset.sup_le
+ intro e _
+ let bits := (ramFieldBits (virtualBucket n) (wordBits b n) : RAMSystem (virtualBits b n) → ℕ)
+ change paddedWidth bits ((stateEdges labels (Nat.add_sub_of_le S.degree_bounds.1)).symm
+ ((e.1.1,e.2),e.1.2)) ≤ initialWidth b n
+ cases (stateEdges labels (Nat.add_sub_of_le S.degree_bounds.1)).symm ((e.1.1,e.2),e.1.2) with
+ | inl => exact le_rfl
+ | inr => exact Nat.zero_le _
+
+theorem pairInput_sqrtEnergy (S : BlockSchedule k) {b n base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n) :
+ Real.sqrt (pairInput S labels hD).energy ≤
+ (initialPositions b n : ℝ) * S.baseDegree * initialWidth b n := by
+ have hpad : 2 + (2 ^ S.degreeExponent 0 - 2) = S.baseDegree := Nat.add_sub_of_le S.degree_bounds.1
+ unfold pairInput initialWidth initialPositions
+ simpa only [hpad] using
+ (cursorState_sqrtEnergy_le labels hD (Nat.add_sub_of_le S.degree_bounds.1)
+ (ramFieldBits (virtualBucket n) (wordBits b n) : RAMSystem (virtualBits b n) → ℕ))
+
+private theorem eventually_widthEnvelope (b d : ℕ) (A : ℝ) (hA : 0 ≤ A)
+ {θ : ℝ} (hθ : 0 < θ) :
+ ∀ᶠ n : ℕ in atTop,
+ ((initialPositions b n : ℝ) * d * initialWidth b n + A * initialPositions b n) /
+ 2 ^ blockCount θ n ≤ (processorCount b n : ℝ) * (n : ℝ) ^ (1 - θ/2) := by
+ let p := 2 * ((b : ℝ) + 2)
+ let w := 56 * ((b : ℝ) + 3)^2 * ((b : ℝ) + 10)^4
+ have h₁ := eventually_absorb_polylog (2 * p * d * w) 8 (show 1 - θ < 1 - θ/2 by linarith)
+ (show (0 : ℝ) < 1/2 by norm_num)
+ have h₂ := eventually_absorb_polylog (2 * A * p) 2 (show 3/4 - θ < 1 - θ/2 by linarith)
+ (show (0 : ℝ) < 1/2 by norm_num)
+ filter_upwards [h₁, h₂, eventually_ge_atTop 2] with n h₁ h₂ hn
+ have hp := initialPositions_bound b n hn
+ have hw := initialWidth_bound b n hn
+ have hi := inv_two_pow_blockCount θ (show 1 ≤ n by omega)
+ have hnpos : 0 < (n : ℝ) := by exact_mod_cast (show 0 < n by omega)
+ let L := (n.log2 : ℝ) + 1
+ let R := (processorCount b n : ℝ)
+ calc
+ _ ≤ ((p * R * (n : ℝ) ^ (3/4 : ℝ) * L^2) * d * (w * (n : ℝ) ^ (1/4 : ℝ) * L^6) +
+ A * (p * R * (n : ℝ) ^ (3/4 : ℝ) * L^2)) * (2 * (n : ℝ) ^ (-θ)) := by
+ rw [div_eq_mul_one_div]
+ gcongr
+ _ = R * ((2 * p * d * w) * (n : ℝ)^(1-θ) * L^8 + (2*A*p)*(n : ℝ)^(3/4-θ)*L^2) := by
+ rw [show (1-θ) = (3/4+1/4)+(-θ) by ring, Real.rpow_add hnpos, Real.rpow_add hnpos,
+ sub_eq_add_neg, Real.rpow_add hnpos]
+ ring
+ _ ≤ R * ((1/2)*(n : ℝ)^(1-θ/2) + (1/2)*(n : ℝ)^(1-θ/2)) := by gcongr
+ _ = _ := by dsimp [R]; ring
+
+/-- The fixed growth constant determines rational parameters as in Section 9.1. -/
+structure PairExponents (C₂ : ℕ) where
+ /-- Positive rational exponent governing the number of compression blocks, chosen to control
+ growth under iteration. -/
+ θ : ℚ
+ /-- Positive rational slack exponent chosen smaller than one tenth of the compression
+ exponent `θ`. -/
+ δ : ℚ
+ theta_pos : 0 < θ
+ theta_lt : θ < 1/100
+ delta_pos : 0 < δ
+ delta_lt : δ < θ/10
+ growth : (θ : ℝ) * Real.logb 2 C₂ ≤ 1/100
+
+/-- Choose the two exponents for the compressed pair using only the fixed block's growth
+constant. -/
+noncomputable def pairExponents (B : S.Templates) : PairExponents B.growthConstant := by
+ have hc : 1 ≤ (B.growthConstant : ℝ) := by
+ exact_mod_cast (show 1 ≤ B.growthConstant by linarith [B.growthConstant_ge_two])
+ apply Classical.choice
+ obtain ⟨θ, δ, ht, ht', hd, hd', hg⟩ := exists_compression_exponents _ hc
+ exact ⟨⟨θ, δ, ht, ht', hd, hd', hg⟩⟩
+
+/-- Count local map, field and child occurrences over all final positions
+using the actual placement fibers on a selected branch. -/
+noncomputable def totalOccurrences {A : Type*} {N Y : NetworkKernel.Network}
+ (chain : NetworkKernel.TermChain A N Y) : ℕ :=
+ ∑ v : Y.Site, chain.occurrences (fun _ => 1) v
+
+/-- Section 12 on the actual cursor graph and selected terms. The last
+strict inequality bounds the sum over all final sites if each of their
+recorded map occurrences contributes its allowed degree. -/
+theorem eventually_pairBranchBounds (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) :
+ ∀ᶠ n : ℕ in atTop,
+ 1 < virtualBits b n ∧ blockCount (u.θ : ℝ) n * S.laneBits ≤ virtualBits b n ∧
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ ∀ z : E.Choices,
+ let Y := E.finalState z
+ let chain := E.termChain (B.records f hf T hT X) z
+ let fieldLimit := B.growthConstant ^ T * (X.maxWireWidth + 1)
+ Y.positions ≤ initialPositions b n ∧
+ (Y.totalWidth : ℝ) ≤ processorCount b n * (n : ℝ) ^ (1-u.θ/2 : ℝ) ∧
+ (∀ v, (chain.occurrences (fun _ => 1) v : ℝ) ≤ (n : ℝ) ^ (1/100 : ℝ)) ∧
+ chain.AllRecordsLe fieldLimit ∧ Y.maxWireWidth ≤ fieldLimit ∧
+ (fieldLimit : ℝ) ≤ (n : ℝ) ^ (3/10 : ℝ) ∧
+ (totalOccurrences chain : ℝ) ≤ initialPositions b n * (n : ℝ) ^ (1/100 : ℝ) ∧
+ Y.positions * B.growthConstant ^ T * fieldLimit < 2 ^ (2 * addressBits b n) := by
+ have hθ : 0 < (u.θ : ℝ) := by exact_mod_cast u.theta_pos
+ have hθ' : (u.θ : ℝ) < 1/100 := by simpa using (Rat.cast_lt (K := ℝ)).mpr u.theta_lt
+ have hC : 1 ≤ (B.growthConstant : ℝ) := by
+ exact_mod_cast (show 1 ≤ B.growthConstant by linarith [B.growthConstant_ge_two])
+ have hr := cursorResource_bounds b S.laneBits hθ.le (by linarith) hC u.growth
+ (A := 1) (by norm_num) hb
+ have hw := eventually_widthEnvelope b S.baseDegree B.widthAllowance (Real.sqrt_nonneg _) hθ
+ filter_upwards [hr, hw, eventually_ge_atTop 3] with n hr hw hn
+ have hB : 5 ≤ b := (le_max_right _ _).trans hb
+ have hclog := Nat.clog_pos (by decide : 1 < 2) (show 1 < n by omega)
+ have hbits := addressBits_le_virtualBits b n hn
+ have hD : 1 < virtualBits b n := by
+ change b * Nat.clog 2 n ≤ virtualBits b n at hbits
+ exact (show 1 < b * Nat.clog 2 n by nlinarith).trans_le hbits
+ refine ⟨hD, by simpa only [Nat.mul_comm] using hr.1, ?_⟩
+ intro base lanes labels hD hT A _ f hf X T E z Y chain L
+ have h := B.branch_bounds f hf T hT X z
+ change X.positions = S.positionFactor^T * Y.positions ∧ _ at h
+ have hp := pairInput_positions S labels hD
+ change X.positions = initialPositions b n at hp
+ have hfactor : 0 < S.positionFactor ^ T := pow_pos (by linarith [S.positionFactor_gt_two]) _
+ have hy : Y.positions ≤ initialPositions b n := hp ▸ h.1 ▸ Nat.le_mul_of_pos_left _ hfactor
+ have hwin := pairInput_maxWireWidth S labels hD
+ have hg := history_pow_blockCount_le hC hθ.le (show 1 ≤ n by omega) u.growth
+ change (B.growthConstant : ℝ)^T ≤ (n : ℝ)^(1/100 : ℝ) at hg
+ have hsize : (L : ℝ) ≤ (n : ℝ) ^ (3/10 : ℝ) := by
+ change ((B.growthConstant^T * (X.maxWireWidth+1) : ℕ) : ℝ) ≤ _
+ push_cast
+ have hwin' : (X.maxWireWidth : ℝ) + 1 ≤ (initialWidth b n : ℝ) + 1 := by
+ exact_mod_cast Nat.succ_le_succ hwin
+ exact (mul_le_mul_of_nonneg_left hwin' (pow_nonneg (Nat.cast_nonneg _) _)).trans
+ (by simpa only [one_mul] using hr.2.1)
+ have hs : totalOccurrences chain ≤ Y.positions * B.growthConstant^T := by
+ calc _ ≤ ∑ _v : Y.network.Site, B.growthConstant^T := Finset.sum_le_sum fun v _ => h.2.2.2.1 v
+ _ = _ := by rw [Finset.sum_const, Finset.card_univ, nsmul_eq_mul]; rfl
+ have hcast : ((Y.positions * B.growthConstant^T : ℕ) : ℝ) ≤
+ (initialPositions b n : ℝ) * (n : ℝ)^(1/100 : ℝ) := by
+ push_cast
+ gcongr
+ have hs' : (totalOccurrences chain : ℝ) ≤ ((Y.positions * B.growthConstant^T : ℕ) : ℝ) := by
+ exact_mod_cast hs
+ refine ⟨hy, h.2.1.trans (h.2.2.1.trans (?_ : _ ≤ _)), fun v => ?_, h.2.2.2.2.1,
+ h.2.2.2.2.2, hsize, hs'.trans hcast, ?_⟩
+ · apply le_trans _ hw
+ rw [hp]
+ gcongr
+ exact pairInput_sqrtEnergy S labels hD
+ · have hv : (chain.occurrences (fun _ => 1) v : ℝ) ≤ (B.growthConstant : ℝ)^T := by
+ exact_mod_cast h.2.2.2.1 v
+ exact hv.trans hg
+ · have hdeg := hsize.trans (Real.rpow_le_rpow_of_exponent_le
+ (show 1 ≤ (n : ℝ) by exact_mod_cast (show 1 ≤ n by omega)) (by norm_num : (3/10 : ℝ) ≤ 2/5))
+ have hh := (mul_le_mul hcast hdeg (by positivity) (by positivity)).trans_lt hr.2.2
+ rw [processorCount, Nat.cast_pow, Nat.cast_ofNat, ← pow_mul, mul_comm (addressBits b n) 2] at hh
+ exact_mod_cast hh
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorBranchCommunication.lean b/lean/OAI/Computability/VPVNP/CursorBranchCommunication.lean
new file mode 100644
index 0000000000..3d83d949c2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorBranchCommunication.lean
@@ -0,0 +1,177 @@
+import OAI.Computability.VPVNP.CursorBranchBudget
+
+/-!
+# External accesses for the compressed pair
+
+The site burst follows its placement history and reads both of its
+incidences. Summing these reads charges each final arc exactly twice,
+including when its endpoints coincide. The global allowance accounts
+separately for the descriptor scans, the writes of shared bits and
+the final vertex visits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open Filter Compression CursorBounds
+
+variable {k : Type*} [Field k] {S : BlockSchedule k}
+
+/-- Total number of incident payload bits at one site, summing all incoming and outgoing
+half-wire widths. -/
+def incidentBits {a g : ℕ} (X : State a g) (v : X.network.Site) : ℕ :=
+ ∑ dir : Bool, ∑ j, X.halfWidth v dir j
+
+theorem incidentBits_le {a g : ℕ} (X : State a g) (v : X.network.Site) :
+ incidentBits X v ≤ (2 * 2^a) * X.maxWireWidth := by
+ calc _ ≤ ∑ _dir : Bool, ∑ _j : Fin (2^a), X.maxWireWidth :=
+ Finset.sum_le_sum fun dir _ => Finset.sum_le_sum fun j _ => X.halfWidth_le_max v dir j
+ _ = _ := by simp [Nat.mul_assoc]
+
+/-- The two endpoint reads at all vertices together have cost twice
+the total actual width. -/
+theorem sum_incidentBits {a g : ℕ} (X : State a g) :
+ ∑ v, incidentBits X v = 2 * X.totalWidth := by
+ let e : X.network.Site × Fin (2^a) ≃ (X.Base × Fin (2^a)) × BitWord g :=
+ ⟨fun x => ((x.1.1,x.2),x.1.2), fun x => ((x.1.1,x.2),x.1.2), fun _ => rfl, fun _ => rfl⟩
+ have ho : ∑ v, ∑ j, X.halfWidth v false j = X.totalWidth := by
+ rw [← Fintype.sum_prod_type']
+ exact Fintype.sum_equiv e _ _ fun _ => rfl
+ have hi : ∑ v, ∑ j, X.halfWidth v true j = X.totalWidth := by
+ rw [← Fintype.sum_prod_type']
+ exact Fintype.sum_equiv (e.trans X.slots.actualTarget.symm) _ _ fun _ => rfl
+ simp only [incidentBits, Fintype.sum_bool, Finset.sum_add_distrib, ho, hi, two_mul]
+
+/-- The per-site external charge, allowing a fixed number of probes per
+incident bit, and a fixed polylogarithmic cost per history occurrence. -/
+noncomputable def siteAccesses {A : Type*} {N : NetworkKernel.Network} {a g : ℕ}
+ (Y : State a g) (chain : NetworkKernel.TermChain A N Y.network)
+ (C logPower n : ℕ) (v : Y.network.Site) : ℕ :=
+ C * (1 + incidentBits Y v + chain.occurrences (fun _ => 1) v * (n.log2+1)^logPower)
+
+/-- Descriptor scans use old positions, final guesses use actual wire
+widths, and each final-site charge uses that site's own incidences. -/
+noncomputable def branchAccesses {A : Type*} {a g a' g' : ℕ} (X : State a g)
+ (Y : State a' g') (chain : NetworkKernel.TermChain A X.network Y.network) (C logPower n : ℕ) :
+ ℕ :=
+ C * (X.positions * (n.log2+1)^logPower + Y.totalWidth) +
+ ∑ v, siteAccesses Y chain C logPower n v
+
+theorem branchAccesses_eq {A : Type*} {a g a' g' : ℕ} (X : State a g)
+ (Y : State a' g') (chain : NetworkKernel.TermChain A X.network Y.network) (C logPower n : ℕ) :
+ branchAccesses X Y chain C logPower n =
+ C * (X.positions * (n.log2+1)^logPower + 3 * Y.totalWidth + Y.positions +
+ totalOccurrences chain * (n.log2+1)^logPower) := by
+ unfold branchAccesses siteAccesses totalOccurrences
+ rw [← Finset.mul_sum]
+ simp only [Finset.sum_add_distrib, ← Finset.sum_mul, sum_incidentBits, Finset.sum_const,
+ Finset.card_univ, nsmul_eq_mul, mul_one]
+ change C * (X.positions * _ + Y.totalWidth) + C * (Y.positions + 2 * Y.totalWidth + _) = _
+ ring
+
+/-- The threshold precedes every choice of branch. The total charge
+fits any positive fraction of the live group, while each site's burst
+is bounded by the square root of the input length. -/
+theorem eventually_pairAccesses (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) (C logPower : ℕ) {ε : ℝ} (hε : 0 < ε) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ ∀ z : E.Choices,
+ let Y := E.finalState z
+ let chain := E.termChain (B.records f hf T hT X) z
+ (branchAccesses X Y chain C logPower n : ℝ) <
+ ε * (processorCount b n : ℝ) * liveBucket u.δ n ∧
+ (∀ v, (siteAccesses Y chain C logPower n v : ℝ) ≤ (n : ℝ)^(1/2 : ℝ)) ∧
+ (n : ℝ)^(1/2 : ℝ) ≤ liveBucket u.δ n := by
+ let θ := (u.θ : ℝ)
+ let δ := (u.δ : ℝ)
+ have ht : θ < 1/100 := by simpa [θ] using (Rat.cast_lt (K := ℝ)).mpr u.theta_lt
+ have ht0 : 0 < θ := Rat.cast_pos.mpr u.theta_pos
+ have hd : δ < θ/10 := by simpa [θ,δ] using (Rat.cast_lt (K := ℝ)).mpr u.delta_lt
+ let p := 2 * ((b : ℝ) + 2)
+ have h₁ := eventually_absorb_polylog (3 * C * p) (2 + logPower)
+ (show 3/4 + 1/100 < 1 - δ by linarith) (half_pos (half_pos hε))
+ have h₂ := eventually_absorb_polylog (3 * (C : ℝ)) 0
+ (show 1 - θ/2 < 1 - δ by linarith) (half_pos (half_pos hε))
+ let d := (2 * S.baseDegree + 2 : ℕ)
+ have hburst := eventually_burst_le (δ := δ) (by linarith) ((C : ℝ) * d) logPower
+ filter_upwards [eventually_pairBranchBounds B u b hb, h₁, h₂, hburst, eventually_ge_atTop 2]
+ with n hbranch h₁ h₂ hburst hn
+ intro base lanes labels hD hT A _ f hf X T E z Y chain
+ have h := hbranch.2.2 labels hD hT A f hf z
+ let P := (initialPositions b n : ℝ)
+ let R := (processorCount b n : ℝ)
+ let L := ((n.log2 : ℝ) + 1)^logPower
+ let g := (n : ℝ)^(1/100 : ℝ)
+ let F := (Y.totalWidth : ℝ)
+ have hpos : 0 < (n : ℝ) := by exact_mod_cast (show 0 < n by omega)
+ have hn1 : 1 ≤ (n : ℝ) := by exact_mod_cast (show 1 ≤ n by omega)
+ have hg : 1 ≤ g := Real.one_le_rpow hn1 (by norm_num)
+ have hL : 1 ≤ L := one_le_pow₀ (by linarith [Nat.cast_nonneg (α := ℝ) n.log2])
+ have hP : 0 ≤ P := Nat.cast_nonneg _
+ have hR : 0 < R := Nat.cast_pos.mpr (Nat.two_pow_pos _)
+ have hw : (Y.maxWireWidth : ℝ) ≤ (n : ℝ)^(3/10 : ℝ) :=
+ (Nat.cast_le.mpr h.2.2.2.2.1).trans h.2.2.2.2.2.1
+ have hF : F ≤ R*(n : ℝ)^(1-θ/2) := h.2.1
+ have hv : (Y.positions : ℝ) ≤ P := Nat.cast_le.mpr h.1
+ have ho : (totalOccurrences chain : ℝ) ≤ P*g := h.2.2.2.2.2.2.1
+ have hp := pairInput_positions S labels hD
+ have hPg : P ≤ P*g := le_mul_of_one_le_right hP hg
+ have hPgL : P ≤ P*g*L := hPg.trans (le_mul_of_one_le_right (by positivity) hL)
+ refine ⟨?_, ?_, hburst.2⟩
+ · rw [branchAccesses_eq]
+ push_cast
+ change (C : ℝ) * ((X.positions : ℝ)*L + 3*F + (Y.positions : ℝ) +
+ (totalOccurrences chain : ℝ)*L) < ε*R*liveBucket δ n
+ change X.positions = initialPositions b n at hp
+ rw [hp]
+ have hp' : P ≤ p*R*(n : ℝ)^(3/4 : ℝ)*((n.log2 : ℝ)+1)^2 := initialPositions_bound b n hn
+ have hc : 0 ≤ (C : ℝ) := Nat.cast_nonneg _
+ have hsub : P*L + 3*F + (Y.positions : ℝ) + (totalOccurrences chain : ℝ)*L ≤
+ 3*P*g*L + 3*(R*(n : ℝ)^(1-θ/2)) := by
+ linarith only [mul_le_mul_of_nonneg_right hPg (zero_le_one.trans hL),
+ mul_le_mul_of_nonneg_right ho (zero_le_one.trans hL), hv.trans hPgL, hF]
+ calc _ ≤ C*(3*P*g*L + 3*(R*(n : ℝ)^(1-θ/2))) := mul_le_mul_of_nonneg_left hsub hc
+ _ ≤ C*(3*(p*R*(n : ℝ)^(3/4 : ℝ)*((n.log2 : ℝ)+1)^2)*g*L +
+ 3*(R*(n : ℝ)^(1-θ/2))) := by gcongr
+ _ = R*((3*C*p)*(n : ℝ)^(3/4+1/100 : ℝ)*((n.log2 : ℝ)+1)^(2+logPower) +
+ (3*C)*(n : ℝ)^(1-θ/2)) := by rw [Real.rpow_add hpos, pow_add]; dsimp [g,L]; ring
+ _ ≤ R*((ε/2/2)*(n : ℝ)^(1-δ)+(ε/2/2)*(n : ℝ)^(1-δ)) := by
+ apply mul_le_mul_of_nonneg_left _ hR.le
+ exact add_le_add h₁ (by simpa only [pow_zero, mul_one] using h₂)
+ _ < ε * R * (n : ℝ)^(1-δ) := by
+ nlinarith only [mul_pos (mul_pos hε hR) (Real.rpow_pos_of_pos hpos (1-δ))]
+ _ ≤ _ := by gcongr; exact (liveBucket_bounds (by linarith : δ ≤ 1) (by omega)).1
+ · intro v
+ have hinc : (incidentBits Y v : ℝ) ≤ (2*S.baseDegree : ℕ) * (n : ℝ)^(3/10 : ℝ) := by
+ have hi : (incidentBits Y v : ℝ) ≤ ((2*S.baseDegree : ℕ) : ℝ) * (Y.maxWireWidth : ℝ) := by
+ exact_mod_cast incidentBits_le Y v
+ exact hi.trans (mul_le_mul_of_nonneg_left hw (Nat.cast_nonneg _))
+ have hvis : (chain.occurrences (fun _ => 1) v : ℝ) ≤ g := h.2.2.1 v
+ have hL' : 1 ≤ g*L := one_le_mul_of_one_le_of_one_le hg hL
+ unfold siteAccesses
+ push_cast
+ apply le_trans _ hburst.1
+ change (C : ℝ) * (1 + (incidentBits Y v : ℝ) + _*L) ≤
+ ((C : ℝ)*d) * ((n : ℝ)^(3/10 : ℝ)+g*L)
+ rw [mul_assoc]
+ apply mul_le_mul_of_nonneg_left _ (Nat.cast_nonneg _)
+ dsimp only [d]
+ push_cast at hinc ⊢
+ nlinarith only [hinc, mul_le_mul_of_nonneg_right hvis (zero_le_one.trans hL), hL',
+ Real.rpow_nonneg (Nat.cast_nonneg (α := ℝ) n) (3/10),
+ mul_nonneg (Nat.cast_nonneg (α := ℝ) S.baseDegree) (zero_le_one.trans hL')]
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorCoefficientContraction.lean b/lean/OAI/Computability/VPVNP/CursorCoefficientContraction.lean
new file mode 100644
index 0000000000..e9acccf4b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorCoefficientContraction.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.CursorIncidentExtension
+import OAI.Computability.VPVNP.RAMSiteInput
+import OAI.Computability.VPVNP.PairedFamily
+
+/-!
+# Universal coefficients at routed processor sites
+
+A routed site evaluates its input at the selected mask fields. The exact
+coefficient identity on sender arrays therefore applies even to a local
+argument of a contraction before route ties have been imposed globally.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open BurstRAM PrivateRAM RAMLayout CursorRouting NetworkKernel
+
+variable {n d e w pc regs pubs : ℕ} (D : UniversalMachine.Program)
+ (fit : ProcessorInput.Fits D n d (2^e) w)
+ (M : Machine w pc regs pubs) (fuel : ℕ) (initial : Word w)
+ (hdr : Site d → ProcessorInput.Header) (hw : 4 ≤ w) (hc : 2^d*2^e < 2^w)
+
+/-- Word header at a routed site. The initialization addresses beyond the
+network have their usual zero default. -/
+def headerAt (i : ℕ) : Word w :=
+ if hi : i < 2^d then ProcessorInput.headerWord hw (hdr ⟨i,hi⟩) else 0
+
+theorem headerAt_site (v : Site d) : headerAt hdr hw v.val = ProcessorInput.headerWord hw (hdr v) := by
+ simp [headerAt,v.isLt]
+
+/-- Encode a routed site's processor header and incident RAM payloads as the Boolean input to
+its local processor. -/
+def cursorInput (v : Site d) (out inc : RAMPayload d (2^e) w) : Fin n → Bool :=
+ ProcessorInput.encode D n v (hdr v) (decodeIncident v out inc) fit
+
+variable (processor : ∀ (v : Site d) (a : SendArrays d (2^e) w),
+ acceptingCount (ProcessorInput.encode D n v (hdr v) (RAMLayout.incidentBits a v) fit) =
+ Nat.card (M.IncidentPaths fuel initial (ProcessorInput.headerWord hw (hdr v))
+ (by omega) hc v (RAMLayout.incidentBits a v)))
+
+include processor
+theorem cursorInput_count (v : Site d) (out inc : RAMPayload d (2^e) w) :
+ acceptingCount (cursorInput D fit hdr v out inc) =
+ Nat.card (validatorPaths M fuel initial (headerAt hdr hw) (by omega) hc v out inc) := by
+ have h := processor v (localExtension v out inc)
+ rw [localExtension_incident] at h
+ simpa only [cursorInput, validatorPaths, headerAt_site] using h
+
+theorem cursorInput_coeff (v : Site d) (out inc : RAMPayload d (2^e) w) :
+ (P n).coeff (pairedExponent (cursorInput D fit hdr v out inc)) =
+ (Nat.card (validatorPaths M fuel initial (headerAt hdr hw) (by omega) hc v out inc) : ℤ) := by
+ rw [coeff_P, cursorInput_count D fit M fuel initial hdr hw hc processor]
+
+variable [NeZero d]
+
+open scoped Classical in
+/-- The integer contraction of the uncompressed cursor network evaluates
+the exact natural coefficients of the universal paired polynomial. -/
+theorem cursorInput_contract :
+ contract (validatorNetwork d e w)
+ (factors systemMask (fun v out inc => if ActiveSends v out then
+ acceptingCount (cursorInput D fit hdr v out inc) else 0)) =
+ Nat.card (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2^d) (headerAt hdr hw))
+ (withinCaps (2^d) (2^e))) := by
+ rw [contract_ram]
+ rw [← validatorPaths_sum M fuel initial (headerAt hdr hw) (by omega : 2 ≤ w) hc]
+ apply Finset.sum_congr rfl
+ intro a _
+ apply Finset.prod_congr rfl
+ intro v _
+ exact cursorInput_count D fit M fuel initial hdr hw hc processor v _ _
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorCompressionBudget.lean b/lean/OAI/Computability/VPVNP/CursorCompressionBudget.lean
new file mode 100644
index 0000000000..e06499a028
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorCompressionBudget.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.CompressionBudget
+import OAI.Computability.VPVNP.CursorBounds
+
+/-!
+# Communication of the routed cursor network after compression
+
+This specialization uses the actual numbers of sites, cursor positions, and
+reserved routing bits in Sections 11 and 12. Its remaining inputs concern
+an admitted compressor path and the external operations performed on it.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+open Filter Asymptotics CursorBounds
+
+/-- Equations (12.1) and the external budget of Proposition 13.1 for the prescribed
+cursor network. Its position and width bounds are supplied by the routing construction. -/
+theorem cursorPairSimulation_budget (B k : ℕ) {θ δ d c κ C : ℝ}
+ (hθ : 0 < θ) (hθ' : θ < 1 / 100) (hδ : δ < θ / 10)
+ (hd : 0 ≤ d) (hc : 0 ≤ c) (hκ : 2 < κ) (hC : 0 ≤ C)
+ {Wire : ℕ → Type*} [∀ n, Fintype (Wire n)] (width : ∀ n, Wire n → ℕ)
+ (mass : ∀ n, Wire n → ℝ) (hmass : ∀ᶠ n in atTop, ∀ e, 0 < mass n e)
+ (hnorm : ∀ᶠ n in atTop, ∑ e, mass n e = 1)
+ {L : ℕ → ℕ → ℝ} {work : ℕ → ℕ} (hinit : ∀ᶠ n in atTop,
+ 0 ≤ L n 0 ∧ Real.sqrt (L n 0) ≤ d * initialPositions B n * initialWidth B n)
+ (hstep : ∀ᶠ n in atTop, ∀ i < blockCount θ n, L n (i + 1) ≤ L n i / 4 +
+ c * ((initialPositions B n : ℝ) / κ ^ i) ^ 2)
+ (hfinal : ∀ᶠ n in atTop, ∑ e, (width n e : ℝ) ^ 2 / mass n e ≤ L n (blockCount θ n))
+ (hwork : ∀ᶠ n in atTop, (work n : ℝ) ≤ C * (initialPositions B n *
+ (n : ℝ) ^ (1 / 100 : ℝ) * (n.log2 + 1 : ℝ) ^ k + ↑(∑ e, width n e))) :
+ (∀ᶠ n in atTop, (∑ e, (width n e : ℝ)) ≤ processorCount B n * (n : ℝ) ^ (1 - θ / 2)) ∧
+ (fun n => (work n : ℝ)) =o[atTop] (fun n => (processorCount B n : ℝ) * liveBucket δ n) :=
+ pairSimulation_budget width mass hmass hnorm hθ hθ' hδ hd hc hκ (by positivity) hC
+ ((eventually_ge_atTop 2).mono fun n => initialPositions_bound B n)
+ ((eventually_ge_atTop 2).mono fun n => initialWidth_bound B n) hinit hstep hfinal hwork
+
+/-- Fixing the address exponent after the number of lanes per block provides
+the lanes, the local field bound, and enough counter bits at the same lengths. -/
+theorem cursorResource_bounds (B lanes : ℕ) {θ C₂ A : ℝ} (hθ : 0 ≤ θ) (hθ' : θ ≤ 1)
+ (hC : 1 ≤ C₂) (hexp : θ * Real.logb 2 C₂ ≤ 1 / 100) (hA : 0 ≤ A)
+ (hB : max lanes 5 ≤ B) : ∀ᶠ n : ℕ in atTop,
+ lanes * blockCount θ n ≤ virtualBits B n ∧
+ A * C₂ ^ blockCount θ n * (initialWidth B n + 1 : ℝ) ≤ (n : ℝ) ^ (3 / 10 : ℝ) ∧
+ (initialPositions B n : ℝ) * (n : ℝ) ^ (1 / 100 : ℝ) * (n : ℝ) ^ (2 / 5 : ℝ) <
+ (processorCount B n : ℝ) ^ 2 := by
+ have hlen := eventually_fieldGrowth_le (B := 56 * ((B : ℝ) + 3) ^ 2 * ((B : ℝ) + 10) ^ 4)
+ hθ hC hexp hA 6
+ have hcounter := eventually_counter_lt (2 * ((B : ℝ) + 2)) 2
+ filter_upwards [eventually_ge_atTop 3, hlen, hcounter] with n hn hlen hcounter
+ have hn' : 2 ≤ n := by omega
+ exact ⟨by simpa [Nat.mul_comm] using laneBudget B lanes n (le_trans (le_max_left _ _) hB) hθ' hn,
+ (hlen _ (initialWidth_bound B n hn')).1,
+ hcounter _ _ (pow_five_le_processorCount n (le_trans (le_max_right _ _) hB))
+ (initialPositions_bound B n hn')⟩
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorDescriptorUnits.lean b/lean/OAI/Computability/VPVNP/CursorDescriptorUnits.lean
new file mode 100644
index 0000000000..515bcc8500
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorDescriptorUnits.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.CursorBranchBudget
+import OAI.Computability.VPVNP.PairSimulationSelectorBounds
+
+/-!
+# Number of descriptor visits on the selected cursor branch
+
+The units of the descriptor scans count the old sites, old slots and encoded
+outer-term bits along the actual compressor execution. The number of blocks
+and the binary length of every intermediate field are logarithmic in the
+input length. Both logarithms enter the visit bound in Appendix E.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open Filter Compression CursorBounds PairSimulation.LocalHistory
+
+variable {k : Type*} [Field k] {S : BlockSchedule k}
+
+/-- The actual number of old site visits, old slot visits, and selector bits
+on a branch of the chosen iterated compressor. -/
+noncomputable def descriptorUnits (B : S.Templates) {A : Type*} [CommRing A] (f : B.Entry → A)
+ (hf : B.IsSolution f) {lanes : ℕ} (T : ℕ) (h : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T h X).Choices) : ℕ :=
+ scanUnits (B.execute f hf T h X) _
+ (repeatReaders (blockReaders B f hf) _ T lanes (Nat.add_sub_of_le h).symm X) z
+
+/-- Uniform constant multiplying the quadratic logarithmic visit bound. -/
+noncomputable def descriptorUnitConstant (B : S.Templates) : ℕ :=
+ (S.steps + 1) * scanConstant B * (scanConstant B + 1)
+
+/-- The threshold precedes all lane labelings, scalar specializations, and
+outer term choices. Both site and slot scans count the old level's order. -/
+theorem eventually_descriptorUnits (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) : ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ ∀ z : (B.execute f hf T hT X).Choices,
+ descriptorUnits B f hf T hT X z ≤
+ descriptorUnitConstant B * initialPositions b n * (n.log2 + 1) ^ 2 := by
+ filter_upwards [eventually_pairBranchBounds B u b hb, eventually_ge_atTop 2] with n hbranch hn
+ intro base lanes labels hD hT A _ f hf X T z
+ let L := n.log2 + 1
+ let K := scanConstant B
+ let width := B.growthConstant ^ T * (X.maxWireWidth + 1)
+ have hwidth := (hbranch.2.2 labels hD hT A f hf z).2.2.2.2.2.1
+ change (width : ℝ) ≤ (n : ℝ) ^ (3/10 : ℝ) at hwidth
+ have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast (show 1 ≤ n by omega)
+ have hw : width ≤ n := by
+ have h : (width : ℝ) ≤ n := hwidth.trans (by
+ simpa using (Real.rpow_le_rpow_of_exponent_le hn₁ (by norm_num : (3/10:ℝ) ≤ 1)))
+ exact_mod_cast h
+ have hbits : Nat.clog 2 (width + 1) ≤ L := by
+ apply (Nat.clog_le_iff_le_pow Nat.one_lt_two).mpr
+ have hp : n < 2 ^ L := Nat.lt_log2_self
+ omega
+ have htθ : (u.θ : ℝ) ≤ 1 := by
+ have := (Rat.cast_lt (K := ℝ)).mpr u.theta_lt
+ norm_num at this
+ linarith
+ have hTlog : T ≤ L := by
+ apply le_trans _ (BurstRAM.clog_le_log2_succ n)
+ rw [show T = blockCount (u.θ : ℝ) n from rfl, blockCount, ← Real.natCeil_logb_natCast 2 n]
+ exact (Nat.floor_le_floor (mul_le_of_le_one_left (Real.logb_nonneg (by norm_num) hn₁) htθ)).trans
+ (Nat.floor_le_ceil _)
+ have hp := pairInput_positions S labels hD
+ change X.positions = initialPositions b n at hp
+ have hbound := execute_scanUnits B f hf T hT X z
+ change descriptorUnits B f hf T hT X z ≤ ((S.steps+1)*T) * (X.positions*K*(K+Nat.clog 2 (width+1))) at hbound
+ have hK : K + Nat.clog 2 (width + 1) ≤ (K + 1) * L := by
+ rw [Nat.add_mul, Nat.one_mul]
+ exact Nat.add_le_add (Nat.le_mul_of_pos_right K (Nat.succ_pos _)) hbits
+ apply hbound.trans
+ calc
+ _ ≤ ((S.steps + 1) * L) * (X.positions * K * ((K + 1) * L)) :=
+ Nat.mul_le_mul (Nat.mul_le_mul_left _ hTlog) (Nat.mul_le_mul_left _ hK)
+ _ = _ := by rw [hp]; dsimp [descriptorUnitConstant, K, L]; ring
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorDescriptorWords.lean b/lean/OAI/Computability/VPVNP/CursorDescriptorWords.lean
new file mode 100644
index 0000000000..2fb4828cc4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorDescriptorWords.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.CompressorSelectedTerms
+import OAI.Computability.VPVNP.CompressorRecordsCursorCapacity
+import OAI.Computability.VPVNP.CompressorRecordScores
+
+/-!
+# Descriptor arithmetic in the live cursor word format
+
+The chosen field length envelope controls the input to every motif scan.
+The two layout scores fit after multiplying the old slot count by the
+squared supply width and the fixed denominator-cleared weights. The word
+width also gives a uniform polylogarithmic budget for one motif visit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords
+
+open Compression CursorNetwork CursorBounds Filter PairSimulation.LocalHistory
+open scoped Classical
+
+private theorem fieldLimit_le_length {n M : ℕ} (hn : 1 ≤ n) (h : (M : ℝ) ≤ (n : ℝ) ^ (3/10 : ℝ)) :
+ M ≤ n := by
+ have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast hn
+ have hp : (n : ℝ) ^ (3/10 : ℝ) ≤ n := by
+ simpa using Real.rpow_le_rpow_of_exponent_le hn₁ (by norm_num : (3/10 : ℝ) ≤ 1)
+ exact_mod_cast h.trans hp
+
+/-- Binary instruction budget per motif visit, including the full payload word scan. -/
+theorem word_plus_clog_le (b n M : ℕ) (hM : M ≤ n) :
+ wordBits b n + Nat.clog 2 (M+1) + 1 ≤ ((b+10)^4+2)*(n.log2+1)^4 := by
+ let L := n.log2+1
+ have hb : wordBits b n ≤ ((b+10)*L)^4 := by
+ unfold wordBits addressBits BurstRAM.addressWidth
+ apply Nat.pow_le_pow_left
+ have h := Nat.mul_le_mul_left b (BurstRAM.clog_le_log2_succ n)
+ dsimp [L]; nlinarith only [h,Nat.zero_le n.log2]
+ have hlog : Nat.clog 2 (M+1) ≤ L := (Nat.clog_le_iff_le_pow Nat.one_lt_two).mpr
+ ((Nat.succ_le_succ hM).trans Nat.lt_log2_self)
+ have hl : 1 ≤ L := Nat.succ_pos _
+ have hl4 : L ≤ L^4 := by simpa using (Nat.pow_le_pow_right hl (by decide : 1 ≤ 4))
+ have h := Nat.add_le_add (Nat.add_le_add hb (hlog.trans hl4)) (hl.trans hl4)
+ apply h.trans_eq
+ dsimp only [L]; ring
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+/-- One threshold suffices for every selected substep. The last inequality
+holds for any fixed coefficient multiplying the squared intermediate width
+and the count of motifs. In particular the cleared-energy counters never wrap. -/
+theorem eventually_descriptorWords (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) (K : ℕ) : ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ ∀ z : (B.execute f hf T hT X).Choices, ∀ v ∈ executeLevels B f hf T hT X z,
+ SelectedTerms.fitConstant B + 4*Nat.clog 2 (v.input.maxWireWidth+1) ≤ wordBits b n ∧
+ wordBits b n + Nat.clog 2 (v.input.maxWireWidth+1) + 1 ≤ ((b+10)^4+2)*(n.log2+1)^4 ∧
+ K * v.origin.motifCount * (v.input.maxWireWidth+1)^2 < 2^wordBits b n := by
+ have hb' := (le_max_right S.laneBits 5).trans hb
+ let cost n := K * (initialPositions b n * slotDegree S) * (n+1)^2
+ have hcost : PolynomiallyBounded cost := ((PolynomiallyBounded.const K).mul
+ ((CursorRAM.bounded_positions b).mul (PolynomiallyBounded.const (slotDegree S)))).mul (PolynomiallyBounded.succ.pow 2)
+ filter_upwards [eventually_pairBranchBounds B u b hb, eventually_ge_atTop 1,
+ DemandPreparation.eventually_live_word_fits b (by omega) (SelectedTerms.fitConstant B) 4 1 1,
+ CursorRAM.eventual_word_room b (by omega) hcost] with n branch hn fit room
+ intro base lanes labels hD hT A _ f hf X T z v hv
+ obtain ⟨hp,hw⟩ := executeLevels_limits B f hf T hT X z v hv
+ have hwidth := fieldLimit_le_length hn (branch.2.2 labels hD hT A f hf z).2.2.2.2.2.1
+ have hm := hw.trans hwidth
+ have hx := pairInput_positions S labels hD
+ have hmots := v.origin.motifCount_le.trans (Nat.mul_le_mul (hp.trans hx.le) v.oldDegree_le)
+ exact ⟨fit _ (by simpa using hm),word_plus_clog_le _ _ _ hm,
+ (Nat.mul_le_mul (Nat.mul_le_mul_left K hmots) (Nat.pow_le_pow_left (Nat.succ_le_succ hm) 2)).trans_lt room⟩
+
+/-- The bound consumed by the two native score counters at a genuine
+shrinking pass, with payload-plus-selector supply widths on every role. -/
+theorem shrink_layoutScore_le (B : S.Templates) {a g : ℕ} (X : State a (packingLaneBits a g))
+ (c : ∀ m, X.packingData.ShrinkChoice X.shrinkNumber X.packingWidth B.shrink m) (l : Bool) :
+ layoutScore ShrinkMotif.relativeMass
+ (fun m l t ↦ X.packingData.shrinkSupplyWidths X.shrinkNumber X.packingWidth B.shrink m (c m) (l,t)) l ≤
+ ((∑ t, MotifAdmission.weight ShrinkMotif.relativeMass t) * (ShrinkMotif.fieldFactor B.shrink)^2) *
+ (shrinkMotifOrder X).length * (X.maxWireWidth+1)^2 := by
+ have hs := layoutScore_le ShrinkMotif.relativeMass
+ (fun m l t ↦ X.packingData.shrinkSupplyWidths X.shrinkNumber X.packingWidth B.shrink m (c m) (l,t))
+ (ShrinkMotif.fieldFactor B.shrink*(X.maxWireWidth+1))
+ (fun m l t ↦ ((X.packingData.shrinkTerm_bounds (State.two_le_packingColors _) (Nat.two_pow_pos _)
+ X.shrinkNumber X.packingWidth (fun e ↦ X.width_le_maxWireWidth _) B.shrink m (c m)).2 (l,t)).2) l
+ exact hs.trans_eq (by change _ = _ * Fintype.card X.packingData.Motif * _; ring)
+
+end CompressorRecords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorFieldOffsets.lean b/lean/OAI/Computability/VPVNP/CursorFieldOffsets.lean
new file mode 100644
index 0000000000..453002e634
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorFieldOffsets.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.CursorRouting
+import OAI.Computability.VPVNP.RAMSortAddressBounds
+
+/-!
+# Contiguous field offsets on a cursor arc
+
+The arc reserves one eight-word field for each successor mask class, followed
+by one sorting block for each layer in phase order. The two choices of arc at
+each cursor use the same layout. Its inverse recovers the system and in-field
+index of every bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorRouting
+
+open RAMLayout RAMSort
+
+variable {D H w : ℕ}
+
+/-- Length of the bit vector on either outgoing arc. -/
+def ramPayloadWidth (D H w : ℕ) : ℕ :=
+ D * (8 * w) + layerCount D * blockBits H w
+
+theorem ramPayloadWidth_eq_sum (D H w : ℕ) :
+ ramPayloadWidth D H w = ∑ s : RAMSystem D, ramFieldBits H w s :=
+ (ramArcWidth D H w).symm
+
+/-- Number all bits in the arc payload, allowing empty fields and zero width. -/
+def ramFieldOffset (D H w : ℕ) :
+ ((s : RAMSystem D) × Fin (ramFieldBits H w s)) ≃ Fin (ramPayloadWidth D H w) :=
+ let succ := (Equiv.sigmaEquivProd (Fin D) (Fin (8 * w))).trans finProdFinEquiv
+ let sort := (Equiv.sigmaEquivProd (Layer D) (Fin (blockBits H w))).trans
+ (((layerEquiv D).prodCongr (Equiv.refl _)).trans finProdFinEquiv)
+ (Equiv.sumSigmaDistrib (fun s : RAMSystem D => Fin (ramFieldBits H w s))).trans
+ ((succ.sumCongr sort).trans finSumFinEquiv)
+
+@[simp] theorem ramFieldOffset_successor (k : Fin D) (j : Fin (8 * w)) :
+ (ramFieldOffset D H w ⟨.inl k, j⟩).val = k.val * (8 * w) + j.val := by
+ change j.val + 8 * w * k.val = _
+ ring
+
+@[simp] theorem ramFieldOffset_sort (l : Layer D) (j : Fin (blockBits H w)) :
+ (ramFieldOffset D H w ⟨.inr l, j⟩).val =
+ D * (8 * w) + l.ordinal.val * blockBits H w + j.val := by
+ change D * (8 * w) + (j.val + blockBits H w * l.ordinal.val) = _
+ ring
+
+/-- Flatten the separate field functions to a single vector of arc bits. -/
+def ramPayloadEquiv (D H w : ℕ) :
+ ((s : RAMSystem D) → Fin (ramFieldBits H w s) → Bool) ≃ (Fin (ramPayloadWidth D H w) → Bool) :=
+ (Equiv.piCurry (fun (s : RAMSystem D) (_ : Fin (ramFieldBits H w s)) => Bool)).symm.trans
+ ((ramFieldOffset D H w).arrowCongr (Equiv.refl Bool))
+
+@[simp] theorem ramPayloadEquiv_offset
+ (payload : (s : RAMSystem D) → Fin (ramFieldBits H w s) → Bool)
+ (s : RAMSystem D) (j : Fin (ramFieldBits H w s)) :
+ ramPayloadEquiv D H w payload (ramFieldOffset D H w ⟨s, j⟩) = payload s j := by
+ change Sigma.uncurry payload ((ramFieldOffset D H w).symm (ramFieldOffset D H w ⟨s, j⟩)) = _
+ rw [Equiv.symm_apply_apply]
+ rfl
+
+/-- Straight-line word arithmetic for a bit address. The sorting case computes
+the triangular prefix from the phase and step counters. -/
+def ramFieldAddress (D H w : ℕ) (s : RAMSystem D) (j : Fin (ramFieldBits H w s)) : IndexExpr :=
+ let successorBits := IndexExpr.mul (.arg 8) (.arg w)
+ match s with
+ | .inl k => .add (.mul (.arg k.val) successorBits) (.arg j.val)
+ | .inr l =>
+ let phase := IndexExpr.arg l.phase
+ let ordinal := IndexExpr.add (.div (.mul phase (.add phase (.arg 1))) (.arg 2)) (.arg l.step)
+ let block := IndexExpr.mul (.mul (.mul (.arg 4) (.arg H)) (.arg 5)) (.arg w)
+ .add (.add (.mul (.arg D) successorBits) (.mul ordinal block)) (.arg j.val)
+
+theorem ramFieldAddress_eval (s : RAMSystem D) (j : Fin (ramFieldBits H w s)) :
+ (ramFieldAddress D H w s j).eval = (ramFieldOffset D H w ⟨s, j⟩).val := by
+ cases s with
+ | inl k => exact (ramFieldOffset_successor (H := H) k j).symm
+ | inr l =>
+ rw [ramFieldOffset_sort (H := H) (w := w) l j]
+ simp only [ramFieldAddress, IndexExpr.eval, Layer.ordinal, layerCount,
+ Nat.choose_two_right, Nat.add_sub_cancel, blockBits]
+ rw [Nat.mul_comm l.phase (l.phase + 1)]
+
+/-- The address calculation uses at most thirteen arithmetic instructions
+regardless of the number of successor classes or sorting layers. -/
+theorem ramFieldAddress_work (s : RAMSystem D) (j : Fin (ramFieldBits H w s)) :
+ (ramFieldAddress D H w s j).work ≤ 13 := by
+ cases s <;> simp [ramFieldAddress, IndexExpr.work]
+
+/-- Every temporary register fits below or at the total payload width. This
+includes the product in the triangular prefix before division by two. -/
+theorem ramFieldAddress_peak_le (s : RAMSystem D) (j : Fin (ramFieldBits H w s)) :
+ (ramFieldAddress D H w s j).peak ≤ ramPayloadWidth D H w := by
+ have haddr := (ramFieldOffset D H w ⟨s, j⟩).isLt
+ cases s with
+ | inl k =>
+ have hj : j.val < 8 * w := j.isLt
+ have hk := k.isLt
+ have hwidth := Nat.le_mul_of_pos_left (8 * w) (show 0 < D by omega)
+ have hD := Nat.le_mul_of_pos_right D (show 0 < 8 * w by omega)
+ rw [ramFieldOffset_successor (H := H) k j] at haddr
+ simp only [ramFieldAddress, IndexExpr.peak, IndexExpr.eval, max_le_iff]
+ unfold ramPayloadWidth at *
+ repeat' constructor <;> omega
+ | inr l =>
+ have hj : j.val < blockBits H w := j.isLt
+ have hpos : 0 < 4 * H * 5 * w := hj.trans_le' (Nat.zero_le _)
+ have hw : 0 < w := Nat.pos_of_mul_pos_left hpos
+ have hH : 0 < H := by
+ by_contra!
+ simp_all
+ have h20 := Nat.le_mul_of_pos_right (4 * H * 5) hw
+ have hmin : 2 ≤ blockBits H w := by unfold blockBits; omega
+ have hord : l.phase * (l.phase + 1) / 2 + l.step < layerCount D := by
+ simpa [Layer.ordinal, layerCount, Nat.choose_two_right, Nat.mul_comm l.phase] using
+ l.ordinal.isLt
+ have hp := l.phase_lt
+ have hsucc := Nat.le_mul_of_pos_left (8 * w) (show 0 < D by omega)
+ have hD := Nat.le_mul_of_pos_right D (show 0 < 8 * w by omega)
+ have hblock := Nat.le_mul_of_pos_left (blockBits H w) (show 0 < layerCount D by omega)
+ have hlayers := Nat.mul_le_mul_left (layerCount D) hmin
+ rw [ramFieldOffset_sort (H := H) (w := w) l j] at haddr
+ simp only [Layer.ordinal, layerCount, Nat.choose_two_right, Nat.add_sub_cancel,
+ Nat.mul_comm (l.phase + 1) l.phase] at haddr
+ change D * (8 * w) + (l.phase * (l.phase + 1) / 2 + l.step) * blockBits H w + j.val <
+ ramPayloadWidth D H w at haddr
+ simp only [ramFieldAddress, IndexExpr.peak, IndexExpr.eval, max_le_iff]
+ unfold ramPayloadWidth at *
+ unfold blockBits at *
+ repeat' constructor <;> omega
+
+/-- With a register large enough to hold the payload length, modular word
+evaluation gives the exact bit address. -/
+theorem ramFieldAddress_evalWord {bits : ℕ} (h : ramPayloadWidth D H w < 2 ^ bits)
+ (s : RAMSystem D) (j : Fin (ramFieldBits H w s)) :
+ ((ramFieldAddress D H w s j).evalWord bits).val = (ramFieldOffset D H w ⟨s, j⟩).val :=
+ ((ramFieldAddress D H w s j).evalWord_eq ((ramFieldAddress_peak_le s j).trans_lt h)).trans
+ (ramFieldAddress_eval s j)
+
+end CursorRouting
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorIncidentExtension.lean b/lean/OAI/Computability/VPVNP/CursorIncidentExtension.lean
new file mode 100644
index 0000000000..3d758b2ed8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorIncidentExtension.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.CursorValidatorContraction
+
+/-!
+# Extending arbitrary local cursor fields to physical RAM sends
+
+At a single cursor-zero site its two endpoints of each cross-site sorting
+layer are distinct. Its successor predecessor and successor sender are also
+distinct, with a zero clamp at each missing endpoint. Consequently every
+local payload vector decoded at cursor zero can be supplied to the compiled
+RAM processor by a genuine assignment of its physical shared bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting RAMLayout BurstRAM
+
+variable {D H w : ℕ}
+
+/-- A sender array realizing the selected site's local fields. Other sites
+can take arbitrary values beyond the two relevant endpoints of each layer. -/
+def localExtension (v : Site D) (outgoing incoming : RAMPayload D H w) : SendArrays D H w :=
+ (fun u j =>
+ if h : u.val = v.val then
+ outgoing (.inl (successorClass (x := v.val) (by have := u.isLt; omega))) j
+ else
+ incoming (.inl (successorClass (x := u.val) (by have := u.isLt; omega))) j,
+ fun l u j => if u = v then outgoing (.inr l) j else incoming (.inr l) j)
+
+theorem localExtension_incident (v : Site D) (outgoing incoming : RAMPayload D H w) :
+ incidentBits (localExtension v outgoing incoming) v = decodeIncident v outgoing incoming := by
+ let a := localExtension v outgoing incoming
+ funext i
+ obtain ⟨slot,rfl⟩ := (offset D H w).surjective i
+ change incidentBits a v (offset D H w slot) = _
+ rw [incidentBits_offset]
+ simp only [decodeIncident, Function.comp_apply, Equiv.symm_apply_apply]
+ rcases slot with ⟨dir,j⟩ | ⟨l,dir,j⟩ <;> fin_cases dir
+ · by_cases hv : v.val+1 < 2^D
+ · let u : Fin (2^D-1) := ⟨v.val,by omega⟩
+ have h := incident_send a (.inl (u,j))
+ change (incidentEquiv D H w a).val (v, .inl (0,j)) = a.1 u j at h
+ refine h.trans ?_
+ simp [decodeSlot,a,localExtension,u,hv]
+ · have hend : v.val+1 = 2^D := by have := v.isLt; omega
+ rw [incident_clamp a _ (peer_send_end v hend j)]
+ simp [decodeSlot,hv]
+ · by_cases hv : 0 < v.val
+ · refine (incident_receive_successor a v hv j).trans ?_
+ simp [decodeSlot,hv,a,localExtension,show v.val-1 ≠ v.val by omega]
+ · have hz : v.val = 0 := by omega
+ rw [incident_clamp a _ (peer_receive_start v hz j)]
+ simp [decodeSlot,hv]
+ · refine (incident_send a (.inr (l,v,j))).trans ?_
+ simp [decodeSlot,localExtension,a]
+ · refine (incident_receive_sort a l v j).trans ?_
+ simp [decodeSlot,localExtension,a,l.partner_ne v]
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorInitialCheck.lean b/lean/OAI/Computability/VPVNP/CursorInitialCheck.lean
new file mode 100644
index 0000000000..07273e22c7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorInitialCheck.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.CursorRouteChecker
+import OAI.Computability.VPVNP.CursorFieldOffsets
+
+/-!
+# Executing an initial cursor vertex
+
+The checker receives four contiguous bit vectors, the two outgoing and the
+two incoming fields of its own vertex. It executes the local route tests
+and runs the private site validator only at cursor zero. Its accepted bit
+strings are exactly the initial choices used in the monomial path sum.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting RAMLayout BurstRAM BurstRAM.PrivateRAM
+
+variable {D H w p r k e : ℕ} [NeZero D]
+
+/-- Four contiguous vectors of arc bits, addressed within one vertex. -/
+abbrev Buffers (D H w : ℕ) := LocalPort → Fin (ramPayloadWidth D H w) → Bool
+
+/-- Read one routing operand at its precomputed field offset. -/
+def readBuffer (buf : Buffers D H w) (a : LocalAddress D H w) : Bool :=
+ buf a.port (ramFieldOffset D H w ⟨a.system, a.bit⟩)
+
+/-- Serialize the four independent half-wire vectors supplied at a vertex. -/
+def halfBuffers (v : Position D) (z : (network D (ramFieldBits H w : RAMSystem D → ℕ)).Half v) :
+ Buffers D H w
+ | .outgoing side => ramPayloadEquiv D H w (out v z side)
+ | .incoming side => ramPayloadEquiv D H w (inc v z side)
+
+theorem readBuffer_halfBuffers (v : Position D)
+ (z : (network D (ramFieldBits H w : RAMSystem D → ℕ)).Half v) :
+ readBuffer (halfBuffers v z) = readHalf v z := by
+ funext a
+ rcases a with ⟨port,s,j⟩
+ cases port <;> simp [readBuffer, halfBuffers, readHalf]
+
+/-- Decode the validator input by addressing the selected arc at each
+successor or sorting slot. -/
+def incidentBuffer (v : Position D) (buf : Buffers D H w) : Fin (width D H w) → Bool :=
+ decodeIncident v.2
+ (fun s j ↦ readBuffer buf ⟨.outgoing ((systemMask s).val.testBit v.1.val), s, j⟩)
+ (fun s j ↦ readBuffer buf
+ ⟨.incoming ((systemMask s).val.testBit ((finRotate D).symm v.1).val), s, j⟩)
+
+theorem incidentBuffer_halfBuffers (v : Position D)
+ (z : (network D (ramFieldBits H w : RAMSystem D → ℕ)).Half v) :
+ incidentBuffer v (halfBuffers v z) =
+ decodeIncident v.2 (sent systemMask v z) (received systemMask v z) := by
+ unfold incidentBuffer
+ rw [readBuffer_halfBuffers]
+ rfl
+
+/-- Boolean acceptance on independently supplied half-wire indices. A valid
+transit vertex consumes no private bits. -/
+def initialAccept (M : Machine w p r k) (fuel : ℕ) (initial header : Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) (v : Position D)
+ (buf : Buffers D (2 ^ e) w) (choices : List Bool) : Bool :=
+ routeAccept (2 ^ e) w v (readBuffer buf) &&
+ (if v.1 = 0 then
+ (M.validateIncident fuel initial header hw hc v.2 (incidentBuffer v buf) choices).1.isSome
+ else choices.isEmpty)
+
+private def rejectEquiv {f : List Bool → Bool} (h : ∀ bs, f bs = false) :
+ {bs // f bs = true} ≃ Empty where
+ toFun b := False.elim (by have := b.prop; simp [h] at this)
+ invFun := Empty.elim
+ left_inv b := False.elim (by have := b.prop; simp [h] at this)
+ right_inv e := e.elim
+
+private def transitEquiv {f : List Bool → Bool} (h : ∀ bs, f bs = true ↔ bs = []) :
+ {bs // f bs = true} ≃ Unit where
+ toFun _ := ()
+ invFun _ := ⟨[], (h []).mpr rfl⟩
+ left_inv b := Subtype.ext ((h _).mp b.prop).symm
+ right_inv _ := rfl
+
+/-- Acceptance on the serialized local buffers preserves the original
+private path itself. It gives the singleton empty string at a valid transit
+vertex and no strings at vertices failing a route or clamp check. -/
+noncomputable def initialAcceptEquiv (M : Machine w p r k) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w)
+ (v : Position D) (z : (validatorNetwork D e w).Half v) :
+ {bs // initialAccept M fuel initial (header v.2) hw hc v (halfBuffers v z) bs = true} ≃
+ initialChoices M fuel initial header hw hc v z := by
+ classical
+ let passed := routeAccept (2 ^ e) w v (readBuffer (halfBuffers v z))
+ have ok : passed = true ↔ Checks systemMask v z ∧
+ (v.1 = 0 → ActiveSends v.2 (sent systemMask v z)) := by
+ rw [show passed = routeAccept (2 ^ e) w v (readHalf v z) by
+ simp [passed, readBuffer_halfBuffers]]
+ exact routeAccept_readHalf v z
+ unfold initialChoices
+ split_ifs with hcheck hzero hactive
+ · apply Equiv.subtypeEquivRight
+ intro bs
+ have hp := ok.mpr ⟨hcheck, fun _ ↦ hactive⟩
+ unfold passed at hp
+ simp only [initialAccept, hp, Bool.true_and, hzero, ↓reduceIte, incidentBuffer_halfBuffers]
+ · apply rejectEquiv
+ have hp : passed = false := Bool.eq_false_iff.mpr fun h ↦ hactive ((ok.mp h).2 hzero)
+ intro bs
+ unfold passed at hp
+ simp only [initialAccept, hp, Bool.false_and]
+ · apply transitEquiv
+ have hp := ok.mpr ⟨hcheck, fun h ↦ (hzero h).elim⟩
+ intro bs
+ unfold passed at hp
+ simp [initialAccept, hp, hzero]
+ · apply rejectEquiv
+ have hp : passed = false := Bool.eq_false_iff.mpr fun h ↦ hcheck (ok.mp h).1
+ intro bs
+ unfold passed at hp
+ simp only [initialAccept, hp, Bool.false_and]
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorLanes.lean b/lean/OAI/Computability/VPVNP/CursorLanes.lean
new file mode 100644
index 0000000000..eb2bc00b62
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorLanes.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.CursorPadding
+import OAI.Computability.VPVNP.SlotPacking
+
+/-!
+# Designating lane coordinates on the cursor graph
+
+Number the bits of the site address in increasing order of significance. Any
+partition of these coordinates supplies a base part and a binary vector of
+lanes in the sense of Section 7. At a fixed cursor and slot, the displacement
+in both parts is independent of the address. This also applies to the
+zero-width parallel copies of the no-flip arc.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting
+open Compression (BitWord SlotGraph LiftedSlots)
+
+variable {D b l d : ℕ}
+
+/-- Little-endian binary coordinates in the additive vector group. -/
+def addressWord (D : ℕ) : Site D ≃ BitWord D := finFunctionFinEquiv.symm
+
+theorem addressWord_bit (x : Site D) (i : Fin D) :
+ finTwoEquiv (addressWord D x i) = x.val.testBit i.val := by
+ rw [Nat.testBit_eq_decide_div_mod_eq]
+ change (finFunctionFinEquiv.symm x i == 1) = decide (x.val / 2 ^ i.val % 2 = 1)
+ rw [Bool.eq_iff_iff, decide_eq_true_iff, beq_iff_eq, Fin.ext_iff,
+ finFunctionFinEquiv_symm_apply_val]
+ rfl
+
+/-- The displacement of a stay or flip slot in binary address coordinates. -/
+def stepShift (j : Fin D) (side : Bool) : BitWord D :=
+ fun i ↦ if side = true ∧ j = i then 1 else 0
+
+private theorem bit_add (a b : ZMod 2) :
+ finTwoEquiv (a+b) = (finTwoEquiv a ^^ finTwoEquiv b) := by
+ fin_cases a <;> fin_cases b <;> decide
+
+theorem addressWord_step (j : Fin D) (side : Bool) (x : Site D) :
+ addressWord D (stepSite j side x) = addressWord D x + stepShift j side := by
+ funext i
+ apply finTwoEquiv.injective
+ change finTwoEquiv (addressWord D (stepSite j side x) i) =
+ finTwoEquiv (addressWord D x i + stepShift j side i)
+ rw [bit_add, addressWord_bit, addressWord_bit]
+ cases side with
+ | false => simp [stepShift, finTwoEquiv]
+ | true =>
+ rw [stepSite_true_val, Nat.testBit_xor, Nat.testBit_two_pow]
+ by_cases h : j = i
+ · simp [h, stepShift, finTwoEquiv]
+ · have hn : j.val ≠ i.val := fun e ↦ h (Fin.ext e)
+ simp [h, hn, stepShift, finTwoEquiv]
+
+/-- Reorder address coordinates into the chosen base and lane blocks. -/
+def addressPartition (labels : Fin D ≃ Fin b ⊕ Fin l) : BitWord D ≃+ BitWord b × BitWord l where
+ toEquiv := (labels.arrowCongr (Equiv.refl (ZMod 2))).trans (Equiv.sumArrowEquivProdArrow _ _ _)
+ map_add' _ _ := rfl
+
+/-- Change coordinates on positions, retaining the cursor in the base. -/
+def lanePositions (labels : Fin D ≃ Fin b ⊕ Fin l) :
+ (Fin D × Site D) ≃ (Fin D × BitWord b) × BitWord l :=
+ ((Equiv.refl _).prodCongr ((addressWord D).trans (addressPartition labels).toEquiv)).trans
+ (Equiv.prodAssoc _ _ _).symm
+
+private def baseTarget (labels : Fin D ≃ Fin b ⊕ Fin l) (flip : Fin d → Bool) :
+ Equiv.Perm ((Fin D × BitWord b) × Fin d) where
+ toFun p := ((finRotate D p.1.1,
+ p.1.2 + (addressPartition labels (stepShift p.1.1 (flip p.2))).1),p.2)
+ invFun q :=
+ let j := (finRotate D).symm q.1.1
+ ((j, q.1.2 - (addressPartition labels (stepShift j (flip q.2))).1),q.2)
+ left_inv _ := by simp only [Equiv.symm_apply_apply, add_sub_cancel_right]
+ right_inv _ := by simp only [Equiv.apply_symm_apply, sub_add_cancel]
+
+/-- A Section 7 lifted slot graph using any designated set of address bits as
+lanes. Its arc displacements depend only on cursor and slot. -/
+def laneGraph (labels : Fin D ≃ Fin b ⊕ Fin l) (flip : Fin d → Bool) (hD : 1 < D) :
+ LiftedSlots (Fin D × BitWord b) d (BitWord l) where
+ base.target := baseTarget labels flip
+ base.ends_ne p he := by
+ have : NeZero D := ⟨by omega⟩
+ have hj : finRotate D p.1.1 = p.1.1 := congrArg Prod.fst he
+ rw [finRotate_apply] at hj
+ have hz : (1 : Fin D) = 0 := add_left_cancel (a := p.1.1) (by simpa using hj)
+ have := congrArg Fin.val hz
+ simp [Nat.mod_eq_of_lt hD] at this
+ displacement p := (addressPartition labels (stepShift p.1.1 (flip p.2))).2
+
+/-- The actual slot matching of the lifted network is the original cursor
+advance and address step, transported by the position bijection. -/
+theorem laneGraph_target (labels : Fin D ≃ Fin b ⊕ Fin l) (flip : Fin d → Bool) (hD : 1 < D)
+ (j : Fin D) (x : Site D) (i : Fin d) :
+ (laneGraph labels flip hD).actualGraph.target (lanePositions labels (j,x),i) =
+ (lanePositions labels (finRotate D j, stepSite j (flip i) x),i) := by
+ change (((finRotate D j, (addressPartition labels (addressWord D x)).1 +
+ (addressPartition labels (stepShift j (flip i))).1),
+ (addressPartition labels (addressWord D x)).2 +
+ (addressPartition labels (stepShift j (flip i))).2),i) =
+ (((finRotate D j, (addressPartition labels (addressWord D (stepSite j (flip i) x))).1),
+ (addressPartition labels (addressWord D (stepSite j (flip i) x))).2),i)
+ rw [addressWord_step, map_add]
+ rfl
+
+/-- The Section 7 matching is exactly the regularized cursor matching under
+the position bijection, including all zero-width parallel slots. -/
+theorem paddedLaneGraph_target {p : ℕ} (labels : Fin D ≃ Fin b ⊕ Fin l) (hD : 1 < D)
+ (v : Position D) (i : Fin (2 + p)) :
+ (laneGraph labels slotSide hD).actualGraph.target (lanePositions labels v, i) =
+ ((lanePositions labels).prodCongr (Equiv.refl _)) ((paddedSlotGraph D p hD).target (v,i)) :=
+ laneGraph_target labels slotSide hD v.1 v.2 i
+
+/-- Each padded tensor-network edge is realized by the lifted slot matching
+between its own two positions. -/
+theorem paddedLaneGraph_edge {S : Type} [Fintype S] {p : ℕ} (labels : Fin D ≃ Fin b ⊕ Fin l)
+ (hD : 1 < D) (bits : S → ℕ) (e : PaddedArc D p) :
+ (laneGraph labels slotSide hD).actualGraph.target
+ (lanePositions labels ((paddedNetwork D p bits).src e), (paddedEdgeEquiv D p e).2) =
+ (lanePositions labels ((paddedNetwork D p bits).dst e), (paddedEdgeEquiv D p e).2) := by
+ rw [paddedEdge_source, paddedLaneGraph_target]
+ rw [show ((paddedEdgeEquiv D p e).1, (paddedEdgeEquiv D p e).2) = paddedEdgeEquiv D p e from rfl,
+ paddedEdge_target hD bits]
+ rfl
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorNetwork.lean b/lean/OAI/Computability/VPVNP/CursorNetwork.lean
new file mode 100644
index 0000000000..e6a1e8cfbb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorNetwork.lean
@@ -0,0 +1,271 @@
+import OAI.Computability.VPVNP.CursorRouting
+import OAI.Computability.VPVNP.NetworkKernel
+import Mathlib.Logic.Equiv.Fin.Rotate
+
+/-!
+# Local vertex factors of the cursor network
+
+Section 12 gives each mask system a field on each of the two outgoing arcs.
+At a nonzero cursor its local factor tests the routing equalities. At cursor
+zero it also evaluates the site's validator on the selected outgoing and
+returning fields. These factors accept arbitrary independent half-wire
+indices, as required by the substitutions in (12.2).
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting NetworkKernel
+
+/-- A cursor position, consisting of the current mask-bit index and the site occupied at that
+index. -/
+abbrev Position (D : ℕ) := Fin D × Site D
+/-- A directed cursor arc indexed by the current bit position, sending site, and decision to
+flip that bit. -/
+abbrev Arc (D : ℕ) := Fin D × Site D × Bool
+/-- One Boolean word of the prescribed width for each system sharing a cursor arc. -/
+abbrev Payload {S : Type} (bits : S → ℕ) := (s : S) → Fin (bits s) → Bool
+
+variable {D : ℕ} {S : Type} [Fintype S] [NeZero D]
+
+/-- The head of an arc after advancing the cursor and applying its bit choice. -/
+def head (e : Arc D) : Position D := (finRotate D e.1, stepSite e.1 e.2.2 e.2.1)
+
+omit [NeZero D] in
+private theorem step_involutive (j : Fin D) (side : Bool) (x : Site D) :
+ stepSite j side (stepSite j side x) = x := by
+ cases side with
+ | false => rfl
+ | true => exact Fin.ext (by simp [stepSite_true_val])
+
+open scoped Classical in
+/-- The two arcs at a position are indexed by their sender and choice. -/
+noncomputable def network (D : ℕ) (bits : S → ℕ) : Network where
+ Site := Position D
+ Edge := Arc D
+ src e := (e.1, e.2.1)
+ dst := head
+ Payload _ := Payload bits
+ siteFintype := inferInstance
+ edgeFintype := inferInstance
+ payloadFintype _ := inferInstance
+
+/-- Source of the unique incoming arc with the prescribed choice. -/
+def incomingArc (v : Position D) (side : Bool) : Arc D :=
+ let prev := (finRotate D).symm v.1
+ (prev, stepSite prev side v.2, side)
+
+@[simp] theorem head_incomingArc (v : Position D) (side : Bool) :
+ head (incomingArc v side) = v := by simp [head, incomingArc, step_involutive]
+
+@[simp] theorem incomingArc_head (e : Arc D) :
+ incomingArc (head e) e.2.2 = e := by simp [head, incomingArc, step_involutive]
+
+variable {bits : S → ℕ}
+
+/-- A site's half-wire arguments can be read using local outgoing and incoming
+slot numbers, without consulting any other site's arguments. -/
+def out (v : Position D) (z : (network D bits).Half v) (side : Bool) : Payload bits :=
+ z.1 (v.1, v.2, side) rfl
+
+/-- Incoming payload at a cursor position from the arc with the specified flip decision. -/
+def inc (v : Position D) (z : (network D bits).Half v) (side : Bool) : Payload bits :=
+ z.2 (incomingArc v side) (head_incomingArc v side).symm
+
+/-- Assemble each system's sent payload from the outgoing arc selected by its current mask bit. -/
+def sent (mask : S → Site D) (v : Position D) (z : (network D bits).Half v) : Payload bits :=
+ fun s ↦ out v z ((mask s).val.testBit v.1.val) s
+
+/-- Assemble each system's received payload from the incoming arc selected by its mask bit at
+the preceding cursor position. -/
+def received (mask : S → Site D) (v : Position D) (z : (network D bits).Half v) : Payload bits :=
+ fun s ↦ inc v z ((mask s).val.testBit ((finRotate D).symm v.1).val) s
+
+/-- Clamp every unused outgoing field, and at each nonzero cursor tie the
+selected incoming and outgoing fields bitwise. -/
+def Checks (mask : S → Site D) (v : Position D) (z : (network D bits).Half v) : Prop :=
+ (∀ s side, side ≠ (mask s).val.testBit v.1.val → out v z side s = fun _ ↦ false) ∧
+ (v.1 ≠ 0 → sent mask v z = received mask v z)
+
+variable {k : Type*} [CommSemiring k]
+
+open scoped Classical in
+/-- The uncompressed tensor factors, one per position. The validator takes
+the selected send vector followed by the selected receive vector. -/
+noncomputable def factors (mask : S → Site D)
+ (validator : Site D → Payload bits → Payload bits → k) : Factors k (network D bits) :=
+ fun v z ↦ if Checks mask v z then
+ if v.1 = 0 then validator v.2 (sent mask v z) (received mask v z) else 1
+ else 0
+
+private noncomputable abbrev shared (z : Arc D → Payload bits) (v : Position D) :=
+ WireTensor.edgeAssignment (network D bits).src (network D bits).dst z v
+
+private abbrev field (z : Arc D → Payload bits) (s : S) : ArcFields D (Fin (bits s) → Bool) :=
+ fun j x b ↦ z (j, x, b) s
+
+/-- The last cursor is the incoming cursor of every site validator. -/
+private theorem rotate_of_step {i j : Fin D} (h : j.val = i.val + 1) : finRotate D i = j := by
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (NeZero.ne D)
+ apply Fin.ext
+ have hn : i ≠ Fin.last n := by
+ rintro rfl
+ have := j.isLt
+ simp only [Fin.val_last] at h
+ omega
+ exact (coe_finRotate_of_ne_last hn).trans h.symm
+
+private theorem rotate_of_last {i : Fin D} (h : i.val + 1 = D) : finRotate D i = 0 := by
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (NeZero.ne D)
+ have hi : i = Fin.last n := Fin.ext (by simp only [Fin.val_last]; omega)
+ exact hi ▸ finRotate_last
+
+private theorem prev_zero : ((finRotate D).symm 0).val + 1 = D := by
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (NeZero.ne D)
+ have he : (finRotate (n+1)).symm 0 = Fin.last n :=
+ (finRotate (n+1)).symm_apply_eq.mpr finRotate_last.symm
+ rw [he, Fin.val_last]
+
+private theorem received_head (mask : S → Site D) (z : Arc D → Payload bits)
+ (j : Fin D) (x : Site D) (s : S) :
+ let b := (mask s).val.testBit j.val
+ received mask (head (j,x,b)) (shared z _) s = z (j,x,b) s := by
+ dsimp only
+ simp only [received, head, Equiv.symm_apply_apply]
+ change z (incomingArc (head (j, x, (mask s).val.testBit j.val)) _) s = _
+ rw [incomingArc_head]
+
+private noncomputable abbrev sends (mask : S → Site D) (z : Arc D → Payload bits) (x : Site D) :=
+ sent mask (0,x) (shared z _)
+
+private noncomputable abbrev receives (mask : S → Site D) (z : Arc D → Payload bits) (x : Site D) :=
+ received mask (0,x) (shared z _)
+
+private theorem ties_of_checks (mask : S → Site D) (z : Arc D → Payload bits)
+ (h : ∀ v, Checks mask v (shared z v)) (s : S) :
+ LocalTies (fun _ ↦ false) (mask s) (fun x ↦ sends mask z x s)
+ (fun x ↦ receives mask z x s) (field z s) := by
+ constructor
+ · exact fun j x b hb ↦ (h (j,x)).1 s b hb
+ · intro x; rfl
+ · intro j l hj x
+ let b := (mask s).val.testBit j.val
+ let v := head (j,x,b)
+ have hv : v.1 = l := rotate_of_step hj
+ have hn : v.1 ≠ 0 := by rw [hv]; intro he; rw [he, Fin.val_zero] at hj; omega
+ have he := congrFun ((h v).2 hn) s
+ rw [received_head] at he
+ change z (finRotate D j, stepSite j b x, (mask s).val.testBit (finRotate D j).val) s = _ at he
+ change finRotate D j = l at hv
+ rw [hv] at he
+ exact he
+ · intro j hj x
+ have he := received_head mask z j x s
+ change receives mask z _ s = _
+ have hv : head (j,x,(mask s).val.testBit j.val) =
+ (0,stepSite j ((mask s).val.testBit j.val) x) := Prod.ext (rotate_of_last hj) rfl
+ dsimp only at he
+ rw [hv] at he
+ exact he
+
+private theorem prev_succ {j : Fin D} (h : j ≠ 0) :
+ j.val = ((finRotate D).symm j).val + 1 := by
+ rw [coe_finRotate_symm_of_ne_zero h]
+ have := Fin.val_ne_zero_iff.mpr h
+ omega
+
+private theorem checks_of_ties (mask : S → Site D) (z : Arc D → Payload bits)
+ (a b : Site D → Payload bits)
+ (h : ∀ s, LocalTies (fun _ ↦ false) (mask s) (fun x ↦ a x s) (fun x ↦ b x s)
+ (field z s)) (v : Position D) : Checks mask v (shared z v) := by
+ refine ⟨fun s side hs ↦ (h s).clamp v.1 v.2 side hs, ?_⟩
+ intro hn
+ funext s
+ let j := (finRotate D).symm v.1
+ let side := (mask s).val.testBit j.val
+ let x := stepSite j side v.2
+ have he := (h s).transit j v.1 (prev_succ hn) x
+ change field z s v.1 v.2 ((mask s).val.testBit v.1.val) = field z s j x side
+ simpa only [x, side, step_involutive] using he
+
+/-- Returns at cursor zero pull the corresponding send back through the full
+xor permutation for each individual mask. -/
+def returned (mask : S → Site D) (a : Site D → Payload bits) (x : Site D) : Payload bits :=
+ fun s ↦ a ((routePos (mask s) D).symm x) s
+
+private def fieldEquiv (D : ℕ) (bits : S → ℕ) :
+ (Arc D → Payload bits) ≃ ((s : S) → ArcFields D (Fin (bits s) → Bool)) where
+ toFun := field
+ invFun f e s := f s e.1 e.2.1 e.2.2
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+set_option maxHeartbeats 1200000 in
+-- Reindexing the dependent system and half-wire products elaborates their finite instances.
+/-- Contracting the actual two-arc graph gives one term per source setting.
+All intermediate equalities and clamps are evaluated on their own half-wires. -/
+theorem contract_eq (mask : S → Site D)
+ (validator : Site D → Payload bits → Payload bits → k) :
+ open scoped Classical in
+ contract (network D bits) (factors mask validator) =
+ ∑ a : Site D → Payload bits, ∏ x, validator x (a x) (returned mask a x) := by
+ classical
+ let wt (a : Site D → Payload bits) := ∏ x, validator x (a x) (returned mask a x)
+ let send (a : Site D → Payload bits) := fun s x ↦ a x s
+ let recv (a : Site D → Payload bits) := fun s x ↦ returned mask a x s
+ have hinj : Function.Injective send := by
+ intro a b h
+ funext x s
+ exact congrFun (congrFun h s) x
+ have hmatch (a : Site D → Payload bits) (s : S) (x : Site D) :
+ recv a s (routePos (mask s) D x) = send a s x := by simp [recv, returned, send]
+ rw [← routed_contraction_eq (fun _ _ ↦ false) mask send recv hinj hmatch wt, contract_edgeSum]
+ unfold routedContraction
+ let N := network D bits
+ let inst : Fintype (Arc D → Payload bits) :=
+ @Pi.instFintype N.Edge N.Payload (fun x y ↦ Classical.propDecidable (x = y))
+ N.edgeFintype N.payloadFintype
+ refine Fintype.sum_equiv (M := k) (fieldEquiv D bits) _ _ fun z ↦ ?_
+ let T (a : Site D → Payload bits) := ∀ s, LocalTies (fun _ ↦ false) (mask s)
+ (send a s) (recv a s) (field z s)
+ change (∏ v : Position D, factors mask validator v (shared z v)) =
+ @dite k (∃ a, T a) (Classical.propDecidable _) (fun h ↦ wt h.choose) (fun _ ↦ 0)
+ simp only [factors, Fintype.prod_ite_zero]
+ by_cases h : ∃ a, T a
+ · let a := h.choose
+ have ha : T a := h.choose_spec
+ rw [ite_eq_left (checks_of_ties mask z a (returned mask a) ha), dite_eq_left h,
+ Fintype.prod_prod_type]
+ change (∏ j : Fin D, ∏ x : Site D, if j = 0 then _ else 1) = wt a
+ simp_rw [← Finset.ite_prod_one]
+ rw [Fintype.prod_ite_eq']
+ apply Finset.prod_congr rfl
+ intro x _
+ have hs : sends mask z x = a x := funext fun s ↦ (ha s).start x
+ have hr : receives mask z x = returned mask a x := by
+ funext s
+ let j := (finRotate D).symm 0
+ have hj : j.val + 1 = D := prev_zero
+ let b := (mask s).val.testBit j.val
+ have he := (ha s).arrival j hj (stepSite j b x)
+ change field z s j (stepSite j b x) b = recv a s x
+ simpa only [b, step_involutive] using he.symm
+ exact congrArg₂ (validator x) hs hr
+ · rw [dite_eq_right h, ite_eq_right]
+ intro hc
+ let a := sends mask z
+ have ht := ties_of_checks mask z hc
+ have hr (s : S) (x : Site D) : receives mask z x s = recv a s x := by
+ have he := (ht s).receive_at ((routePos (mask s) D).symm x)
+ simpa [a, recv, returned] using he
+ apply h
+ exact ⟨a, fun s ↦ (funext (hr s)) ▸ ht s⟩
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorPadding.lean b/lean/OAI/Computability/VPVNP/CursorPadding.lean
new file mode 100644
index 0000000000..02f4ede8c8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorPadding.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.CursorNetwork
+import OAI.Computability.VPVNP.SlotGraph
+
+/-!
+# Zero-width parallel slots of the cursor network
+
+Section 12 pads the two original arcs to the compressor's prescribed degree
+by making extra copies of the no-flip arc. Each copy carries a singleton
+alphabet. Distinct copies retain distinct slot numbers at both endpoints.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting NetworkKernel
+
+/-- Original cursor arcs together with the padding slots indexed by a position and a local
+padding ordinal. -/
+abbrev PaddedArc (D p : ℕ) := Arc D ⊕ (Position D × Fin p)
+
+variable {S : Type} [Fintype S] {D p : ℕ}
+
+open scoped Classical in
+/-- Add one zero-width copy of the no-flip arc for each extra slot. -/
+noncomputable def paddedNetwork (D p : ℕ) (bits : S → ℕ) : Network where
+ Site := Position D
+ Edge := PaddedArc D p
+ src := Sum.elim (network D bits).src Prod.fst
+ dst := Sum.elim head (fun e ↦ head (e.1.1, e.1.2, false))
+ Payload := Sum.elim (fun _ ↦ Payload bits) (fun _ ↦ Unit)
+ siteFintype := inferInstance
+ edgeFintype := inferInstance
+ payloadFintype e := by
+ cases e with
+ | inl _ => exact inferInstanceAs (Fintype (Payload bits))
+ | inr _ => exact inferInstanceAs (Fintype Unit)
+
+variable {bits : S → ℕ}
+
+/-- The incident fields on the genuine arcs of a padded position. -/
+def unpadHalf (p : ℕ) (v : Position D) (z : (paddedNetwork D p bits).Half v) :
+ (network D bits).Half v :=
+ (fun e h ↦ z.1 (.inl e) h, fun e h ↦ z.2 (.inl e) h)
+
+/-- Evaluate each original tensor on the two genuine incoming and outgoing slots. -/
+def paddedFactors {k : Type*} (p : ℕ) (F : Factors k (network D bits)) :
+ Factors k (paddedNetwork D p bits) :=
+ fun v z ↦ F v (unpadHalf p v z)
+
+/-- Deleting the singleton fields is a bijection on shared-edge assignments. -/
+def unpadFields (p : ℕ) :
+ ((e : (paddedNetwork D p bits).Edge) → (paddedNetwork D p bits).Payload e) ≃
+ ((e : (network D bits).Edge) → (network D bits).Payload e) where
+ toFun z e := z (.inl e)
+ invFun z
+ | .inl e => z e
+ | .inr _ => ()
+ left_inv z := by funext e; cases e <;> rfl
+ right_inv _ := rfl
+
+open scoped Classical in
+/-- Padding preserves the contraction for arbitrary factors on the original network. -/
+theorem contract_padded {k : Type*} [CommSemiring k] (p : ℕ) (F : Factors k (network D bits)) :
+ contract (paddedNetwork D p bits) (paddedFactors p F) = contract (network D bits) F := by
+ rw [contract_edgeSum, contract_edgeSum]
+ exact Fintype.sum_equiv (unpadFields p) _ _ fun _ ↦ rfl
+
+/-- The first two slot numbers are the stay and flip arcs; padding follows them. -/
+def paddingSlots (p : ℕ) : Bool ⊕ Fin p ≃ Fin (2 + p) :=
+ (finTwoEquiv.symm.sumCongr (Equiv.refl _)).trans finSumFinEquiv
+
+/-- Only the original flip arc changes the current address bit. -/
+def slotSide {p : ℕ} (i : Fin (2 + p)) : Bool :=
+ ((paddingSlots p).symm i).elim id (fun _ ↦ false)
+
+@[simp] theorem slotSide_real (p : ℕ) (b : Bool) :
+ slotSide (paddingSlots p (.inl b)) = b := by simp [slotSide]
+
+@[simp] theorem slotSide_pad (u : Fin p) :
+ slotSide (paddingSlots p (.inr u)) = false := by simp [slotSide]
+
+/-- Number each physical edge by its source position and outgoing slot. -/
+def paddedEdgeEquiv (D p : ℕ) : PaddedArc D p ≃ Position D × Fin (2 + p) where
+ toFun
+ | .inl (j, x, b) => ((j, x), paddingSlots p (.inl b))
+ | .inr (v, i) => (v, paddingSlots p (.inr i))
+ invFun vi := match (paddingSlots p).symm vi.2 with
+ | .inl b => .inl (vi.1.1, vi.1.2, b)
+ | .inr i => .inr (vi.1, i)
+ left_inv e := by rcases e with ⟨j,x,b⟩ | ⟨v,i⟩ <;> simp
+ right_inv vi := by
+ rcases vi with ⟨⟨j,x⟩, i⟩
+ obtain ⟨b | i, rfl⟩ := (paddingSlots p).surjective i <;> simp
+
+private theorem rotate_ne_self (hD : 1 < D) (j : Fin D) : finRotate D j ≠ j := by
+ have : NeZero D := ⟨by omega⟩
+ rw [finRotate_apply]
+ intro h
+ have hz : (1 : Fin D) = 0 := add_left_cancel (a := j) (show j + 1 = j + 0 by simpa using h)
+ have := congrArg Fin.val hz
+ simp [Nat.mod_eq_of_lt hD] at this
+
+/-- The slot permutation advances the cursor and preserves the slot number.
+Thus incoming copies and outgoing copies are independently numbered at every site. -/
+def paddedSlotGraph (D p : ℕ) (hD : 1 < D) : Compression.SlotGraph (Position D) (2 + p) where
+ target :=
+ { toFun := fun vi ↦ (head (vi.1.1, vi.1.2, slotSide vi.2), vi.2)
+ invFun := fun vi ↦
+ let e := incomingArc vi.1 (slotSide vi.2)
+ ((e.1, e.2.1), vi.2)
+ left_inv := by
+ rintro ⟨⟨j,x⟩,i⟩
+ have : NeZero D := ⟨by omega⟩
+ have he := incomingArc_head (j,x,slotSide i)
+ exact congrArg (fun e : Arc D ↦ ((e.1,e.2.1), i)) he
+ right_inv := by
+ rintro ⟨v,i⟩
+ have : NeZero D := ⟨by omega⟩
+ exact congrArg (fun u : Position D ↦ (u,i)) (head_incomingArc v (slotSide i)) }
+ ends_ne := fun vi he ↦ rotate_ne_self hD vi.1.1 (congrArg Prod.fst he)
+
+@[simp] theorem paddedSlotGraph_target (hD : 1 < D) (v : Position D) (i : Fin (2 + p)) :
+ (paddedSlotGraph D p hD).target (v, i) = (head (v.1, v.2, slotSide i), i) := rfl
+
+/-- The source endpoint of a numbered edge is its outgoing position. -/
+theorem paddedEdge_source (bits : S → ℕ) (e : PaddedArc D p) :
+ (paddedNetwork D p bits).src e = (paddedEdgeEquiv D p e).1 := by
+ rcases e with ⟨j,x,b⟩ | ⟨v,i⟩ <;> rfl
+
+/-- The target permutation gives the incoming position of every edge, retaining
+the slot number even for parallel copies. -/
+theorem paddedEdge_target (hD : 1 < D) (bits : S → ℕ) (e : PaddedArc D p) :
+ (paddedSlotGraph D p hD).target (paddedEdgeEquiv D p e) =
+ ((paddedNetwork D p bits).dst e, (paddedEdgeEquiv D p e).2) := by
+ rcases e with ⟨j,x,b⟩ | ⟨v,i⟩ <;> simp [paddedEdgeEquiv, paddedNetwork]
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorPaddingWidths.lean b/lean/OAI/Computability/VPVNP/CursorPaddingWidths.lean
new file mode 100644
index 0000000000..352bb2b10d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorPaddingWidths.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.CursorPadding
+import OAI.Computability.VPVNP.CursorBounds
+import OAI.Computability.VPVNP.SlotDemandKernel
+import OAI.Computability.VPVNP.CompressionBudget
+
+/-!
+# Bit widths and initial energy of the padded cursor network
+
+A genuine cursor wire concatenates the message systems in their slot order.
+Its zero-width copies contribute a unique empty word. Under the compressor's
+equal mass per arc the initial energy therefore satisfies the bound in §12.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting RAMLayout
+
+variable {S : Type} [Fintype S] {D p m : ℕ}
+
+/-- Width of an actual edge, with the parallel copies carrying zero bits. -/
+def paddedWidth (bits : S → ℕ) : PaddedArc D p → ℕ := Sum.elim (fun _ ↦ ∑ s, bits s) (fun _ ↦ 0)
+
+/-- Concatenate the system fields in the supplied order. On a padded edge
+the singleton symbol is equivalent to the empty bit word. -/
+def paddedPayloadEquiv (order : S ≃ Fin m) (bits : S → ℕ) (e : PaddedArc D p) :
+ (paddedNetwork D p bits).Payload e ≃ (Fin (paddedWidth bits e) → Bool) := by
+ cases e with
+ | inl _ =>
+ exact (Equiv.piCurry (fun s (_ : Fin (bits s)) ↦ Bool)).symm.trans
+ ((Compression.PackingData.orderedBits order bits).arrowCongr (Equiv.refl Bool))
+ | inr _ => exact Equiv.ofUnique Unit (Fin 0 → Bool)
+
+/-- The successor-mask classes precede the sorting layers, in layer ordinal order. -/
+def ramSystemOrder (D : ℕ) : RAMSystem D ≃ Fin (D + layerCount D) :=
+ ((Equiv.refl (Fin D)).sumCongr (layerEquiv D)).trans finSumFinEquiv
+
+/-- The regular graph has exactly one edge for every outgoing slot at every
+processor-cursor position. -/
+theorem paddedEdge_card (D p : ℕ) : Fintype.card (PaddedArc D p) = (2 ^ D * D) * (2 + p) := by
+ rw [Fintype.card_congr (paddedEdgeEquiv D p)]
+ simp [Position, Site, Nat.mul_comm D]
+
+/-- Upper bound on the initial square-root energy with the actual padding
+and the uniform mass on the resulting edges. -/
+theorem padded_sqrtEnergy_le (D p : ℕ) (bits : S → ℕ) :
+ Real.sqrt (∑ e : PaddedArc D p, (paddedWidth bits e : ℝ) ^ 2 /
+ (1 / (((2 ^ D * D : ℕ) : ℝ) * (2 + p : ℕ)))) ≤
+ ((2 ^ D * D : ℕ) : ℝ) * (2 + p : ℕ) * (∑ s, bits s : ℕ) :=
+ Compression.regularWire_sqrtEnergy_le (paddedWidth bits) (paddedEdge_card D p) (fun e ↦ by
+ cases e with
+ | inl _ => exact le_rfl
+ | inr _ => exact Nat.zero_le _)
+
+/-- Specialization to the RAM routing layout of §12, using its position count
+and the total bit width of all successor and sorting message systems. -/
+theorem cursorRAM_sqrtEnergy_le (B n p : ℕ) :
+ let D := CursorBounds.virtualBits B n
+ let bits : RAMSystem D → ℕ :=
+ ramFieldBits (Compression.virtualBucket n) (CursorBounds.wordBits B n)
+ Real.sqrt (∑ e : PaddedArc D p, (paddedWidth bits e : ℝ) ^ 2 /
+ (1 / ((CursorBounds.initialPositions B n : ℝ) * (2 + p : ℕ)))) ≤
+ (CursorBounds.initialPositions B n : ℝ) * (2 + p : ℕ) * (CursorBounds.initialWidth B n : ℝ) :=
+ padded_sqrtEnergy_le _ p _
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorRAMFields.lean b/lean/OAI/Computability/VPVNP/CursorRAMFields.lean
new file mode 100644
index 0000000000..8e67e1300f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorRAMFields.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.CursorNetwork
+
+/-!
+# Reindexing cursor fields by physical RAM sends
+
+Each internal successor boundary has exactly one active mask. After clamping
+all other successor fields to zero, the independent source settings in the
+cursor contraction are in bijection with the original RAM send arrays.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting RAMLayout NetworkKernel
+
+variable {D H w : ℕ}
+
+/-- A site can send a nonzero successor field only in the class of its own
+nonwrapping successor. Every sorting-system send is active. -/
+def ActiveSends (x : Site D) (out : Payload (ramFieldBits H w : RAMSystem D → ℕ)) : Prop :=
+ ∀ k : Fin D, ¬ (x.val + 1 < 2 ^ D ∧ x.val ^^^ (x.val + 1) = (systemMask (.inl k)).val) →
+ out (.inl k) = fun _ ↦ false
+
+theorem activeSends_ramSend (a : SendArrays D H w) (x : Site D) :
+ ActiveSends x (fun s ↦ ramSend a s x) :=
+ fun k h ↦ funext (ramSend_successor_unused a k x h)
+
+/-- Restrict a site's expanded payload to the physical successor and sorting sends. -/
+private def physicalSends (out : Site D → Payload (ramFieldBits H w : RAMSystem D → ℕ)) :
+ SendArrays D H w :=
+ (fun u ↦ out ⟨u.val, by have := u.isLt; omega⟩
+ (.inl (successorClass (x := u.val) (by have := u.isLt; omega))),
+ fun l x ↦ out x (.inr l))
+
+private theorem ramSend_physicalSends {out : Site D → Payload (ramFieldBits H w : RAMSystem D → ℕ)}
+ (h : ∀ x, ActiveSends x (out x)) (x : Site D) (s : RAMSystem D) :
+ ramSend (physicalSends out) s x = out x s := by
+ cases s with
+ | inl k =>
+ funext j
+ by_cases hs : x.val + 1 < 2 ^ D ∧ x.val ^^^ (x.val + 1) = (systemMask (.inl k)).val
+ · have hk : successorClass hs.1 = k := (successorClass_eq_iff hs.1 k).mpr hs.2
+ simp only [ramSend, dite_eq_left hs, physicalSends]
+ exact congrArg (fun l : Fin D ↦ out x (.inl l) j) hk
+ · exact (ramSend_successor_unused (physicalSends out) k x hs j).trans
+ (congrFun (h x k hs) j).symm
+ | inr l => rfl
+
+/-- Exactly the expanded source assignments satisfying the local clamps
+survive, once for each setting of the physical send arrays. -/
+def activeSendsEquiv (D H w : ℕ) : SendArrays D H w ≃
+ {out : Site D → Payload (ramFieldBits H w : RAMSystem D → ℕ) //
+ ∀ x, ActiveSends x (out x)} where
+ toFun a := ⟨fun x s ↦ ramSend a s x, activeSends_ramSend a⟩
+ invFun out := physicalSends out.val
+ left_inv a := by
+ apply ramSend_injective
+ funext s x
+ exact ramSend_physicalSends (activeSends_ramSend a) x s
+ right_inv out := Subtype.ext (funext fun x ↦ funext fun s ↦ ramSend_physicalSends out.prop x s)
+
+variable {k : Type*} [CommSemiring k] [NeZero D]
+
+open scoped Classical in
+/-- For any local validator the cursor contraction with inactive sends clamped
+is exactly the RAM contraction indexed by the original send arrays. -/
+theorem contract_ram
+ (validator : Site D → Payload (ramFieldBits H w : RAMSystem D → ℕ) →
+ Payload (ramFieldBits H w : RAMSystem D → ℕ) → k) :
+ contract (network D (ramFieldBits H w : RAMSystem D → ℕ))
+ (factors systemMask (fun x out inc ↦ if ActiveSends x out then validator x out inc else 0)) =
+ ∑ a : SendArrays D H w, ∏ x : Site D,
+ validator x (fun s ↦ ramSend a s x) (fun s ↦ ramReceive a s x) := by
+ rw [contract_eq]
+ simp_rw [Fintype.prod_ite_zero]
+ let good (a : Site D → Payload (ramFieldBits H w : RAMSystem D → ℕ)) := ∀ x, ActiveSends x (a x)
+ let wt (a : Site D → Payload (ramFieldBits H w : RAMSystem D → ℕ)) :=
+ ∏ x, validator x (a x) (returned systemMask a x)
+ trans ∑ a ∈ Finset.univ.filter good, wt a
+ · rw [Finset.sum_filter]
+ refine Finset.sum_congr ?_ fun a _ ↦ ?_
+ · ext a
+ simp
+ · exact ite_congr rfl (fun _ ↦ rfl) (fun _ ↦ rfl)
+ · rw [Finset.sum_subtype (p := good) _ (fun _ ↦ by simp) wt]
+ exact (Fintype.sum_equiv (activeSendsEquiv D H w) _ (fun a ↦ wt a.val) fun _ ↦ rfl).symm
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorRouteChecker.lean b/lean/OAI/Computability/VPVNP/CursorRouteChecker.lean
new file mode 100644
index 0000000000..2e42660d3a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorRouteChecker.lean
@@ -0,0 +1,207 @@
+import OAI.Computability.VPVNP.CursorValidatorContraction
+import Mathlib.Data.List.FinRange
+
+/-!
+# Reading the routing constraints at one cursor vertex
+
+At most two bit tests per field bit check all the routing constraints of
+Section 12. Each test uses the vertex's own outgoing and incoming ports.
+A transit comparison probes two bits. A zero check probes one. The program
+retains the inactive-successor zero checks at cursor zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting RAMLayout
+
+variable {D H w : ℕ}
+
+/-- The four incident arc slots of a cursor vertex. -/
+inductive LocalPort
+ | outgoing (flip : Bool)
+ | incoming (flip : Bool)
+
+/-- A bit address consists of a local port, a mask-system field, and a bit
+within that field. -/
+structure LocalAddress (D H w : ℕ) where
+ /-- Incoming or outgoing arc slot at which the routing checker reads the bit. -/
+ port : LocalPort
+ /-- Mask system identifying the RAM field to be read from that port. -/
+ system : RAMSystem D
+ /-- Bit position within the field of the selected RAM system. -/
+ bit : Fin (ramFieldBits H w system)
+
+/-- Primitive routing comparisons, with explicit operands. -/
+inductive BitTest (D H w : ℕ)
+ | skip
+ | clear (a : LocalAddress D H w)
+ | same (a b : LocalAddress D H w)
+
+/-- Evaluate a routing test by skipping it, testing a bit for zero, or comparing two addressed
+bits. -/
+def BitTest.run (read : LocalAddress D H w → Bool) : BitTest D H w → Bool
+ | .skip => true
+ | .clear a => !read a
+ | .same a b => read a == read b
+
+/-- Exact number of bit probes needed for one test. -/
+def BitTest.probes : BitTest D H w → ℕ
+ | .skip => 0
+ | .clear _ => 1
+ | .same _ _ => 2
+
+/-- The sort fields are enumerated by their triangular layer ordinals. -/
+def systemList (D : ℕ) : List (RAMSystem D) :=
+ (List.finRange D).map Sum.inl ++ (List.finRange (layerCount D)).map (Sum.inr ∘ layerAt D)
+
+private theorem mem_systemList (s : RAMSystem D) : s ∈ systemList D := by
+ rcases s with k | l
+ · simp [systemList]
+ · apply List.mem_append_right
+ exact List.mem_map.mpr ⟨l.ordinal, List.mem_finRange _,
+ congrArg Sum.inr ((layerEquiv D).symm_apply_apply l)⟩
+
+/-- The second test at a given bit. -/
+def payloadTest [NeZero D] (v : Position D) (s : RAMSystem D)
+ (j : Fin (ramFieldBits H w s)) : BitTest D H w :=
+ let used := (systemMask s).val.testBit v.1.val
+ let q := LocalAddress.mk (.outgoing used) s j
+ if v.1 = 0 then
+ match s with
+ | .inl k =>
+ if v.2.val + 1 < 2 ^ D ∧ v.2.val ^^^ (v.2.val + 1) = (systemMask (.inl k)).val then .skip
+ else .clear q
+ | .inr _ => .skip
+ else .same q ⟨.incoming ((systemMask s).val.testBit ((finRotate D).symm v.1).val), s, j⟩
+
+/-- First zero the unused outgoing field. Then check the site's transit or
+inactive-successor constraint at this bit. -/
+def bitTests [NeZero D] (v : Position D) (s : RAMSystem D) (j : Fin (ramFieldBits H w s)) :
+ List (BitTest D H w) :=
+ [.clear ⟨.outgoing (!(systemMask s).val.testBit v.1.val), s, j⟩, payloadTest v s j]
+
+/-- All the local bit tests in contiguous mask-system and bit order. -/
+def routeTests [NeZero D] (H w : ℕ) (v : Position D) : List (BitTest D H w) :=
+ (systemList D).flatMap (fun s ↦ (List.finRange (ramFieldBits H w s)).flatMap (bitTests v s))
+
+/-- Run the Boolean checker using a reader for the four local ports. -/
+def routeAccept [NeZero D] (H w : ℕ) (v : Position D) (read : LocalAddress D H w → Bool) : Bool :=
+ (routeTests H w v).all (BitTest.run read)
+
+/-- A reader for independently supplied half-wire indices at a position. -/
+def readHalf [NeZero D] (v : Position D)
+ (z : (network D (ramFieldBits H w : RAMSystem D → ℕ)).Half v)
+ (a : LocalAddress D H w) : Bool :=
+ match a.port with
+ | .outgoing b => out v z b a.system a.bit
+ | .incoming b => inc v z b a.system a.bit
+
+private theorem routeAccept_iff [NeZero D] (v : Position D) (read : LocalAddress D H w → Bool) :
+ routeAccept H w v read = true ↔
+ ∀ s j, read ⟨.outgoing (!(systemMask s).val.testBit v.1.val), s, j⟩ = false ∧
+ (payloadTest v s j).run read = true := by
+ simp only [routeAccept, routeTests, List.all_eq_true, List.mem_flatMap, forall_exists_index,
+ and_imp, List.mem_finRange, true_implies, bitTests, List.mem_cons, List.not_mem_nil, or_false]
+ constructor
+ · intro h s j
+ exact ⟨by simpa [BitTest.run] using h _ s (mem_systemList s) j (Or.inl rfl),
+ h _ s (mem_systemList s) j (Or.inr rfl)⟩
+ · rintro h _ s _ j (rfl | rfl)
+ · simpa [BitTest.run] using (h s j).1
+ · exact (h s j).2
+
+/-- On all half-wire inputs the local bit program checks precisely the route
+conditions and, at cursor zero, the inactive successor fields. -/
+theorem routeAccept_readHalf [NeZero D] (v : Position D)
+ (z : (network D (ramFieldBits H w : RAMSystem D → ℕ)).Half v) :
+ routeAccept H w v (readHalf v z) = true ↔
+ Checks systemMask v z ∧ (v.1 = 0 → ActiveSends v.2 (sent systemMask v z)) := by
+ rw [routeAccept_iff]
+ constructor
+ · intro h
+ refine ⟨⟨?_, ?_⟩, ?_⟩
+ · intro s side hs
+ have he : side = !(systemMask s).val.testBit v.1.val := by
+ cases side <;> cases hb : (systemMask s).val.testBit v.1.val <;> simp_all
+ subst side
+ exact funext fun j ↦ (h s j).1
+ · intro hz
+ funext s j
+ simpa [payloadTest, hz, BitTest.run, readHalf, sent, received] using (h s j).2
+ · intro hz k hinactive
+ funext j
+ simpa [payloadTest, hz, hinactive, BitTest.run, readHalf, sent] using (h (.inl k) j).2
+ · rintro ⟨⟨hclamp, htransit⟩, hactive⟩ s j
+ refine ⟨?_, ?_⟩
+ · exact congrFun (hclamp s _ (Bool.not_ne_self _)) j
+ · by_cases hz : v.1 = 0
+ · rcases s with k | l
+ · by_cases h : v.2.val + 1 < 2 ^ D ∧ v.2.val ^^^ (v.2.val + 1) = (systemMask (.inl k)).val
+ · simp [payloadTest, hz, h, BitTest.run]
+ · simpa [payloadTest, hz, h, BitTest.run, readHalf, sent] using
+ congrFun (hactive hz k h) j
+ · simp [payloadTest, hz, BitTest.run]
+ · simpa [payloadTest, hz, BitTest.run, readHalf, sent, received] using
+ congrFun (congrFun (htransit hz) s) j
+
+
+private theorem sum_widths_systemList (D H w : ℕ) :
+ ((systemList D).map (ramFieldBits H w)).sum =
+ D * (8 * w) + layerCount D * blockBits H w := by
+ simp [systemList, List.map_map, Function.comp_def, ramFieldBits]
+
+/-- Two instructions per payload bit are enough, even for independently
+supplied half-wire assignments that fail one of the comparisons. -/
+theorem routeTests_length [NeZero D] (v : Position D) :
+ (routeTests H w v).length = 2 * (D * (8 * w) + layerCount D * blockBits H w) := by
+ have hj (s : RAMSystem D) (js : List (Fin (ramFieldBits H w s))) :
+ (js.flatMap (bitTests v s)).length = 2 * js.length := by
+ induction js with
+ | nil => rfl
+ | cons j js ih => simp [bitTests, ih, Nat.mul_add]
+ have hs (ss : List (RAMSystem D)) :
+ (ss.flatMap (fun s ↦ (List.finRange (ramFieldBits H w s)).flatMap (bitTests v s))).length =
+ 2 * (ss.map (ramFieldBits H w)).sum := by
+ induction ss with
+ | nil => rfl
+ | cons s ss ih => simp [hj, ih, Nat.mul_add]
+ exact (hs (systemList D)).trans (congrArg (2 * ·) (sum_widths_systemList D H w))
+
+private theorem probes_le_two (t : BitTest D H w) : t.probes ≤ 2 := by
+ cases t <;> simp [BitTest.probes]
+
+/-- Worst-case probes of the test list. Its first instruction per bit is
+always a single zero read. Its second instruction reads at most two bits. -/
+theorem routeTests_probes_le [NeZero D] (v : Position D) :
+ ((routeTests H w v).map BitTest.probes).sum ≤
+ 3 * (D * (8 * w) + layerCount D * blockBits H w) := by
+ have hj (s : RAMSystem D) (js : List (Fin (ramFieldBits H w s))) :
+ (((js.flatMap (bitTests v s)).map BitTest.probes).sum) ≤ 3 * js.length := by
+ induction js with
+ | nil => rfl
+ | cons j js ih =>
+ simp only [List.flatMap_cons, List.map_append, List.sum_append, bitTests, List.map_cons,
+ List.map_nil, List.sum_cons, List.sum_nil, Nat.add_zero, List.length_cons]
+ change 1 + (payloadTest v s j).probes + _ ≤ _
+ have := probes_le_two (payloadTest v s j)
+ omega
+ have hs (ss : List (RAMSystem D)) :
+ ((ss.flatMap (fun s ↦ (List.finRange (ramFieldBits H w s)).flatMap (bitTests v s))).map
+ BitTest.probes).sum ≤ 3 * (ss.map (ramFieldBits H w)).sum := by
+ induction ss with
+ | nil => rfl
+ | cons s ss ih =>
+ simp only [List.flatMap_cons, List.map_append, List.sum_append, List.map_cons,
+ List.sum_cons, Nat.mul_add]
+ exact Nat.add_le_add (by simpa using hj s (List.finRange (ramFieldBits H w s))) ih
+ exact (hs (systemList D)).trans_eq (congrArg (3 * ·) (sum_widths_systemList D H w))
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorRouting.lean b/lean/OAI/Computability/VPVNP/CursorRouting.lean
new file mode 100644
index 0000000000..668c7cb9c1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorRouting.lean
@@ -0,0 +1,497 @@
+import OAI.Computability.VPVNP.RAMPathCount
+import Mathlib.Data.LawfulXor.Equiv
+
+/-!
+# Routing the transcript fields on the cursor graph
+
+In §12 of *VP and VNP differ over every field*, each site address traverses the cursor cycle
+once per message system. It flips the current bit exactly when the system's mask specifies
+that bit. At intermediate cursors every field comes from a unique sender. Unused arcs are
+clamped, used arcs carry equal payloads at consecutive positions, and the returning arc
+supplies the receiving validator. These local checks preserve the contraction exactly.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorRouting
+
+/-- A binary word of width `D` used to address a site. -/
+abbrev Site (D : ℕ) := Fin (2 ^ D)
+
+variable {D : ℕ}
+
+private def lowMask (mask : Site D) (k : ℕ) : Site D :=
+ ⟨mask.val % 2 ^ k, lt_of_le_of_lt (Nat.mod_le _ _) mask.isLt⟩
+
+private def bitMask (j : Fin D) : Site D :=
+ ⟨2 ^ j.val, Nat.pow_lt_pow_right (by decide) j.isLt⟩
+
+/-- Location at cursor `k` under the route that flips the bits set in `mask`. -/
+def routePos (mask : Site D) (k : ℕ) : Equiv.Perm (Site D) :=
+ Equiv.xor (lowMask mask k)
+
+theorem routePos_val (mask : Site D) (k : ℕ) (x : Site D) :
+ (routePos mask k x).val = x.val ^^^ (mask.val % 2 ^ k) := by
+ rw [routePos, Equiv.xor_apply, Fin.xor_comm, Fin.xor_val,
+ Nat.mod_eq_of_lt (Nat.xor_lt_two_pow x.isLt (lowMask mask k).isLt)]
+ rfl
+
+@[simp] theorem routePos_zero (mask : Site D) (x : Site D) : routePos mask 0 x = x := by
+ apply Fin.ext
+ simp [routePos_val, Nat.mod_one]
+
+theorem routePos_full_val (mask x : Site D) : (routePos mask D x).val = x.val ^^^ mask.val := by
+ rw [routePos_val, Nat.mod_eq_of_lt mask.isLt]
+
+theorem routePos_symm_full_val (mask x : Site D) :
+ ((routePos mask D).symm x).val = x.val ^^^ mask.val :=
+ routePos_full_val mask x
+
+/-- One arc of the cursor graph, either staying at `x` or flipping bit `j`. -/
+def stepSite (j : Fin D) (flip : Bool) (x : Site D) : Site D :=
+ if flip then x ^^^ bitMask j else x
+
+@[simp] theorem stepSite_false (j : Fin D) (x : Site D) : stepSite j false x = x := rfl
+
+theorem stepSite_true_val (j : Fin D) (x : Site D) :
+ (stepSite j true x).val = x.val ^^^ 2 ^ j.val := by
+ change (x ^^^ bitMask j).val = _
+ rw [Fin.xor_val, Nat.mod_eq_of_lt (Nat.xor_lt_two_pow x.isLt (bitMask j).isLt)]
+ rfl
+
+private theorem lowMask_succ_val (mask : Site D) (j : Fin D) :
+ mask.val % 2 ^ (j.val + 1) =
+ (mask.val % 2 ^ j.val) ^^^ (if mask.val.testBit j.val then 2 ^ j.val else 0) := by
+ apply Nat.eq_of_testBit_eq
+ intro i
+ rcases lt_trichotomy i j.val with h | h | h
+ · have hne := Ne.symm h.ne
+ cases mask.val.testBit j.val <;> simp [h, Nat.lt_succ_of_lt h, hne]
+ · subst i
+ cases hb : mask.val.testBit j.val <;> simp [hb]
+ · have hn : ¬ i < j.val + 1 := by omega
+ have hn' : ¬ i < j.val := by omega
+ cases mask.val.testBit j.val <;> simp [hn, hn', h.ne]
+
+theorem routePos_step (mask : Site D) (j : Fin D) (x : Site D) :
+ routePos mask (j.val + 1) x = stepSite j (mask.val.testBit j.val) (routePos mask j.val x) := by
+ apply Fin.ext
+ rw [routePos_val, lowMask_succ_val, ← Nat.xor_assoc]
+ cases h : mask.val.testBit j.val with
+ | false => simp [routePos_val]
+ | true =>
+ simp only [ite_true, stepSite_true_val, routePos_val]
+
+/-- Incrementing a binary address changes exactly its trailing ones and the zero preceding them. -/
+theorem successor_mask_eq {D x : ℕ} (hx : x + 1 < 2 ^ D) :
+ ∃ k : Fin D, x ^^^ (x + 1) = 2 ^ (k.val + 1) - 1 := by
+ induction D generalizing x with
+ | zero => simp at hx
+ | succ D ih =>
+ let y := x / 2
+ rcases Nat.mod_two_eq_zero_or_one x with heven | hodd
+ · have hx₀ : x = Nat.bit false y := by simp only [Nat.bit_false, y]; omega
+ have hx₁ : x + 1 = Nat.bit true y := by rw [hx₀, Nat.bit_false, Nat.bit_true]
+ exact ⟨0, by rw [hx₁, hx₀, Nat.xor_bit, Nat.xor_self]; rfl⟩
+ · have hx₀ : x = Nat.bit true y := by simp only [Nat.bit_true, y]; omega
+ have hx₁ : x + 1 = Nat.bit false (y + 1) := by
+ simp only [hx₀, Nat.bit_true, Nat.bit_false]
+ omega
+ have hy : y + 1 < 2 ^ D := by
+ simp only [hx₁, Nat.bit_false, Nat.pow_succ] at hx
+ omega
+ obtain ⟨k, hk⟩ := ih hy
+ refine ⟨k.succ, ?_⟩
+ rw [hx₁, hx₀, Nat.xor_bit, hk]
+ change 2 * (2 ^ (k.val + 1) - 1) + 1 = 2 ^ ((k.val + 1) + 1) - 1
+ rw [Nat.pow_succ _ (k.val + 1)]
+ have := Nat.two_pow_pos (k.val + 1)
+ omega
+
+/-- The masks of all nonwrapping successor messages in a graph with `D` address bits. -/
+def successorMasks (D : ℕ) : Finset ℕ :=
+ (Finset.range (2 ^ D - 1)).image fun x => x ^^^ (x + 1)
+
+/-- Section 12's partition of successor messages uses at most one mask per address bit. -/
+theorem card_successorMasks_le (D : ℕ) : (successorMasks D).card ≤ D := by
+ let possible := (Finset.range D).image fun k => 2 ^ (k + 1) - 1
+ have hsub : successorMasks D ⊆ possible := by
+ intro m hm
+ obtain ⟨x, hx, rfl⟩ := Finset.mem_image.mp hm
+ have hx' := Finset.mem_range.mp hx
+ obtain ⟨k, hk⟩ := successor_mask_eq (D := D) (x := x) (by omega)
+ exact Finset.mem_image.mpr ⟨k.val, Finset.mem_range.mpr k.isLt, hk.symm⟩
+ exact (Finset.card_le_card hsub).trans (Finset.card_image_le.trans (Finset.card_range D).le)
+
+variable {D : ℕ} [NeZero D] {B : Type*}
+
+/-- Fields on the two outgoing arc choices of every processor and cursor. Each
+communication system gets its own instance of these fields. -/
+abbrev ArcFields (D : ℕ) (B : Type*) := Fin D → Site D → Bool → B
+
+/-- Both outgoing arcs advance the cursor cyclically. The flip arc additionally
+changes the current cursor bit of the processor. -/
+def arcTarget (x : Site D) (j : Fin D) (flip : Bool) : Site D × Fin D :=
+ (stepSite j flip x, Fin.ofNat D (j.val + 1))
+
+/-- The pointwise equalities checked at the routing vertices. Unselected arc choices
+are clamped to `blank`. A message can itself be blank when its sender is inactive. -/
+structure LocalTies (blank : B) (mask : Site D) (send receive : Site D → B)
+ (fields : ArcFields D B) : Prop where
+ clamp : ∀ j x side, side ≠ mask.val.testBit j.val → fields j x side = blank
+ start : ∀ x, fields 0 x (mask.val.testBit 0) = send x
+ transit : ∀ (j k : Fin D), k.val = j.val + 1 → ∀ x,
+ fields k (stepSite j (mask.val.testBit j.val) x) (mask.val.testBit k.val) =
+ fields j x (mask.val.testBit j.val)
+ arrival : ∀ j : Fin D, j.val + 1 = D → ∀ x,
+ receive (stepSite j (mask.val.testBit j.val) x) = fields j x (mask.val.testBit j.val)
+
+/-- Pull each used field back along the prefix permutation to its unique sender. -/
+def routedFields (blank : B) (mask : Site D) (send : Site D → B) : ArcFields D B :=
+ fun j x side => if side = mask.val.testBit j.val then send ((routePos mask j.val).symm x)
+ else blank
+
+omit [NeZero D] in
+private theorem routedFields_at (blank : B) (mask : Site D) (send : Site D → B)
+ (j : Fin D) (x : Site D) :
+ routedFields blank mask send j (routePos mask j.val x) (mask.val.testBit j.val) = send x := by
+ simp [routedFields]
+
+theorem routedFields_localTies (blank : B) (mask : Site D) (send receive : Site D → B)
+ (h : ∀ x, receive (routePos mask D x) = send x) :
+ LocalTies blank mask send receive (routedFields blank mask send) := by
+ constructor
+ · intro j x side hs
+ simp [routedFields, hs]
+ · intro x
+ simpa [routePos_zero] using routedFields_at blank mask send (0 : Fin D) x
+ · intro j k hstep y
+ obtain ⟨x, rfl⟩ := (routePos mask j.val).surjective y
+ rw [← routePos_step, ← hstep, routedFields_at, routedFields_at]
+ · intro j hj y
+ obtain ⟨x, rfl⟩ := (routePos mask j.val).surjective y
+ rw [← routePos_step, hj, h, routedFields_at]
+
+/-- Following the local equalities from the sender determines each used field. -/
+theorem LocalTies.field_at {blank : B} {mask : Site D} {send receive : Site D → B}
+ {fields : ArcFields D B} (h : LocalTies blank mask send receive fields)
+ (j : Fin D) (x : Site D) :
+ fields j (routePos mask j.val x) (mask.val.testBit j.val) = send x := by
+ obtain ⟨k, hk⟩ := j
+ induction k with
+ | zero =>
+ rw [routePos_zero]
+ exact h.start x
+ | succ k ih =>
+ let i : Fin D := ⟨k, by omega⟩
+ let j : Fin D := ⟨k + 1, hk⟩
+ change fields j (routePos mask (i.val + 1) x) (mask.val.testBit j.val) = send x
+ rw [routePos_step, h.transit i j rfl]
+ exact ih i.isLt
+
+theorem LocalTies.receive_at {blank : B} {mask : Site D} {send receive : Site D → B}
+ {fields : ArcFields D B} (h : LocalTies blank mask send receive fields) (x : Site D) :
+ receive (routePos mask D x) = send x := by
+ have hd : 0 < D := Nat.pos_of_ne_zero (NeZero.ne D)
+ let j : Fin D := ⟨D - 1, by omega⟩
+ have hj : j.val + 1 = D := by dsimp [j]; omega
+ calc
+ receive (routePos mask D x) =
+ receive (stepSite j (mask.val.testBit j.val) (routePos mask j.val x)) := by
+ rw [← routePos_step, hj]
+ _ = fields j (routePos mask j.val x) (mask.val.testBit j.val) := h.arrival j hj _
+ _ = send x := h.field_at j x
+
+theorem LocalTies.fields_eq {blank : B} {mask : Site D} {send receive : Site D → B}
+ {fields : ArcFields D B} (h : LocalTies blank mask send receive fields) :
+ fields = routedFields blank mask send := by
+ funext j y side
+ obtain ⟨x, rfl⟩ := (routePos mask j.val).surjective y
+ by_cases hs : side = mask.val.testBit j.val
+ · subst side
+ rw [h.field_at, routedFields_at]
+ · rw [h.clamp _ _ _ hs]
+ simp [routedFields, hs]
+
+/-- Prescribed sends and receives extend uniquely exactly when their endpoints match. -/
+theorem existsUnique_fields_iff (blank : B) (mask : Site D) (send receive : Site D → B) :
+ (∃! f : ArcFields D B, LocalTies blank mask send receive f) ↔
+ ∀ x, receive (routePos mask D x) = send x := by
+ constructor
+ · rintro ⟨_, h, _⟩
+ exact h.receive_at
+ · intro h
+ exact ⟨_, routedFields_localTies blank mask send receive h, fun _ hg => hg.fields_eq⟩
+
+/-- After assigning a separate routed field to each mask system, summing over all
+route bits and checking their ties leaves the original contraction unchanged. -/
+theorem contraction_eq {A S R : Type*} [Fintype A] [Fintype S] [AddCommMonoid R]
+ {P : S → Type*} [∀ s, Fintype (P s)] (blank : ∀ s, P s) (mask : S → Site D)
+ (send receive : A → ∀ s, Site D → P s)
+ (hcompat : ∀ a s x, receive a s (routePos (mask s) D x) = send a s x) (weight : A → R) :
+ open scoped Classical in
+ ∑ a : A, ∑ f : (s : S) → ArcFields D (P s),
+ (if ∀ s, LocalTies (blank s) (mask s) (send a s) (receive a s) (f s) then weight a else 0) =
+ ∑ a : A, weight a := by
+ classical
+ refine Finset.sum_congr rfl fun a _ => ?_
+ let f : (s : S) → ArcFields D (P s) := fun s => routedFields (blank s) (mask s) (send a s)
+ have hf (s : S) : LocalTies (blank s) (mask s) (send a s) (receive a s) (f s) :=
+ routedFields_localTies _ _ _ _ (hcompat a s)
+ rw [Finset.sum_eq_single f, ite_eq_left hf]
+ · intro g _ hne
+ apply ite_eq_right
+ intro hg
+ exact hne (funext fun s => (hg s).fields_eq)
+ · simp
+
+/-- Sum over the routed fields, giving zero to a setting that fails to carry
+any consistent source assignment. -/
+noncomputable def routedContraction {A S R : Type*} [Fintype S] [AddCommMonoid R]
+ {P : S → Type*} [∀ s, Fintype (P s)] (blank : ∀ s, P s) (mask : S → Site D)
+ (send receive : A → ∀ s, Site D → P s) (weight : A → R) : R := by
+ classical
+ exact ∑ f : (s : S) → ArcFields D (P s),
+ if h : ∃ a, ∀ s, LocalTies (blank s) (mask s) (send a s) (receive a s) (f s)
+ then weight h.choose else 0
+
+/-- When the send fields recover the old assignment, the contraction can be indexed
+solely by routed arc fields. The clamps and ties discard all invalid settings. -/
+theorem routed_contraction_eq {A S R : Type*} [Fintype A] [Fintype S] [AddCommMonoid R]
+ {P : S → Type*} [∀ s, Fintype (P s)] (blank : ∀ s, P s) (mask : S → Site D)
+ (send receive : A → ∀ s, Site D → P s) (hinj : Function.Injective send)
+ (hcompat : ∀ a s x, receive a s (routePos (mask s) D x) = send a s x) (weight : A → R) :
+ routedContraction blank mask send receive weight = ∑ a : A, weight a := by
+ classical
+ unfold routedContraction
+ rw [← contraction_eq blank mask send receive hcompat weight, Finset.sum_comm]
+ refine Finset.sum_congr rfl fun f _ => ?_
+ by_cases h : ∃ a, ∀ s, LocalTies (blank s) (mask s) (send a s) (receive a s) (f s)
+ · rw [dite_eq_left h, Finset.sum_eq_single h.choose, ite_eq_left h.choose_spec]
+ · intro b _ hb
+ apply ite_eq_right
+ intro hties
+ exact hb (hinj (funext fun s => funext fun x =>
+ ((hties s).start x).symm.trans ((h.choose_spec s).start x)))
+ · simp
+ · rw [dite_eq_right h]
+ symm
+ exact Finset.sum_eq_zero fun a _ => ite_eq_right (fun ha => h ⟨a, ha⟩)
+
+end CursorRouting
+
+namespace CursorRouting
+
+variable {D H w : ℕ}
+
+/-- A successor mask class, or a cross-site layer of the sorting network. -/
+abbrev RAMSystem (D : ℕ) := Fin D ⊕ RAMLayout.Layer D
+
+/-- Every system uses its own field on both choices of arc at each cursor. -/
+def ramFieldBits (H w : ℕ) : RAMSystem D → ℕ
+ | .inl _ => 8 * w
+ | .inr _ => RAMLayout.blockBits H w
+
+/-- Exact number of processor-cursor positions before compression. -/
+theorem cursorPositions_card (D : ℕ) : Fintype.card (Site D × Fin D) = 2 ^ D * D := by
+ simp [Site]
+
+/-- Width of one of the two cursor arcs when both reserve a field for every system. -/
+theorem ramArcWidth (D H w : ℕ) : ∑ s : RAMSystem D, ramFieldBits H w s =
+ D * (8 * w) + RAMLayout.layerCount D * RAMLayout.blockBits H w := by
+ have hcard : Fintype.card (RAMLayout.Layer D) = RAMLayout.layerCount D := by
+ simpa using Fintype.card_congr (RAMLayout.layerEquiv D)
+ rw [Fintype.sum_sum_type]
+ simp [ramFieldBits, hcard]
+
+/-- A successor class flips a low-bit prefix. A sorting layer flips one site bit. -/
+def systemMask : RAMSystem D → Site D
+ | .inl k => ⟨2 ^ (k.val + 1) - 1, by
+ have := Nat.pow_le_pow_right (by decide : 0 < 2) k.isLt
+ have := Nat.two_pow_pos (k.val + 1)
+ omega⟩
+ | .inr s => ⟨2 ^ s.siteBit, Nat.pow_lt_pow_right (by decide) s.siteBit_lt⟩
+
+private theorem log_successorMask {x : ℕ} {k : Fin D}
+ (h : x ^^^ (x + 1) = 2 ^ (k.val + 1) - 1) :
+ ((x ^^^ (x + 1)) + 1).log2 - 1 = k.val := by
+ have hp := Nat.two_pow_pos (k.val + 1)
+ rw [h, Nat.sub_add_cancel hp, Nat.log2_two_pow]
+ omega
+
+/-- The unique mask class of a nonwrapping successor edge, computed from its sender. -/
+def successorClass {x : ℕ} (h : x + 1 < 2 ^ D) : Fin D :=
+ ⟨((x ^^^ (x + 1)) + 1).log2 - 1, by
+ obtain ⟨k, hk⟩ := successor_mask_eq h
+ exact (log_successorMask hk) ▸ k.isLt⟩
+
+theorem successorClass_eq_iff {x : ℕ} (h : x + 1 < 2 ^ D) (k : Fin D) :
+ successorClass h = k ↔ x ^^^ (x + 1) = (systemMask (.inl k)).val := by
+ constructor
+ · obtain ⟨i, hi⟩ := successor_mask_eq h
+ intro hk
+ have hi' : successorClass h = i := Fin.ext (log_successorMask hi)
+ exact hk ▸ hi' ▸ hi
+ · exact fun hk ↦ Fin.ext (log_successorMask hk)
+
+/-- At an active successor source the route uses the corresponding physical
+send. At the last site and in other classes its source is the all-zero field. -/
+def ramSend (a : RAMLayout.SendArrays D H w) :
+ (s : RAMSystem D) → Site D → Fin (ramFieldBits H w s) → Bool
+ | .inl k, x, j =>
+ if h : x.val + 1 < 2 ^ D ∧ x.val ^^^ (x.val + 1) = (systemMask (.inl k)).val
+ then a.1 ⟨x.val, by omega⟩ j else false
+ | .inr s, x, j => a.2 s x j
+
+/-- An arrival reads the source identified by the inverse cursor permutation. -/
+def ramReceive (a : RAMLayout.SendArrays D H w) (s : RAMSystem D) (y : Site D) :
+ Fin (ramFieldBits H w s) → Bool := ramSend a s ((routePos (systemMask s) D).symm y)
+
+@[simp] theorem ramReceive_at (a : RAMLayout.SendArrays D H w) (s : RAMSystem D) (x : Site D) :
+ ramReceive a s (routePos (systemMask s) D x) = ramSend a s x := by simp [ramReceive]
+
+theorem ramSend_sort (a : RAMLayout.SendArrays D H w) (s : RAMLayout.Layer D) (x : Site D)
+ (j : Fin (RAMLayout.blockBits H w)) :
+ ramSend a (.inr s) x j = (RAMLayout.incidentEquiv D H w a).val (x, .inr (s, 0, j)) :=
+ (RAMLayout.incident_send a (.inr (s, x, j))).symm
+
+theorem ramReceive_sort (a : RAMLayout.SendArrays D H w) (s : RAMLayout.Layer D) (y : Site D)
+ (j : Fin (RAMLayout.blockBits H w)) :
+ ramReceive a (.inr s) y j = (RAMLayout.incidentEquiv D H w a).val (y, .inr (s, 1, j)) := by
+ have hp : (routePos (systemMask (.inr s)) D).symm y = s.partner y :=
+ Fin.ext (routePos_symm_full_val _ _)
+ rw [ramReceive, hp, RAMLayout.incident_receive_sort]
+ rfl
+
+theorem ramSend_successor (a : RAMLayout.SendArrays D H w) (x : Site D)
+ (hx : x.val + 1 < 2 ^ D) (j : Fin (8 * w)) :
+ ramSend a (.inl (successorClass hx)) x j =
+ (RAMLayout.incidentEquiv D H w a).val (x, .inl (0, j)) := by
+ have hm := (successorClass_eq_iff hx _).mp rfl
+ simp only [ramSend, dite_eq_left (And.intro hx hm)]
+ exact (RAMLayout.incident_send a (.inl (⟨x.val, by omega⟩, j))).symm
+
+theorem ramSend_successor_unused (a : RAMLayout.SendArrays D H w) (k : Fin D) (x : Site D)
+ (h : ¬ (x.val + 1 < 2 ^ D ∧ x.val ^^^ (x.val + 1) = (systemMask (.inl k)).val))
+ (j : Fin (8 * w)) : ramSend a (.inl k) x j = false := by simp [ramSend, h]
+
+theorem ramReceive_successor (a : RAMLayout.SendArrays D H w) (y : Site D) (hy : 0 < y.val)
+ (j : Fin (8 * w)) :
+ ramReceive a (.inl (successorClass (x := y.val - 1) (D := D) (by have := y.isLt; omega))) y j =
+ (RAMLayout.incidentEquiv D H w a).val (y, .inl (1, j)) := by
+ have hx : y.val - 1 + 1 < 2 ^ D := by have := y.isLt; omega
+ let k := successorClass hx
+ have hm : (y.val - 1) ^^^ y.val = (systemMask (.inl k)).val := by
+ simpa [Nat.sub_add_cancel hy] using (successorClass_eq_iff hx k).mp rfl
+ let x : Site D := ⟨y.val - 1, by have := y.isLt; omega⟩
+ have he : routePos (systemMask (.inl k)) D x = y := by
+ apply Fin.ext
+ rw [routePos_full_val, ← hm]
+ exact Nat.xor_xor_cancel_left _ _
+ change ramReceive a (.inl k) y j = _
+ rw [← he, ramReceive_at, he, RAMLayout.incident_receive_successor a y hy]
+ simp [ramSend, x, Nat.sub_add_cancel hy, hm, y.isLt]
+
+theorem ramReceive_successor_unused (a : RAMLayout.SendArrays D H w) (k : Fin D) (y : Site D)
+ (h : ¬ (0 < y.val ∧ (y.val - 1) ^^^ y.val = (systemMask (.inl k)).val))
+ (j : Fin (8 * w)) : ramReceive a (.inl k) y j = false := by
+ let m := systemMask (.inl k)
+ let x := (routePos m D).symm y
+ apply ramSend_successor_unused
+ intro ⟨_, hm⟩
+ have he : y.val = x.val ^^^ m.val := by
+ rw [← routePos_full_val]
+ exact (congrArg Fin.val ((routePos m D).apply_symm_apply y)).symm
+ have hv : y.val = x.val + 1 := by
+ rw [he, ← hm, Nat.xor_xor_cancel_left]
+ apply h
+ rw [hv]
+ exact ⟨Nat.succ_pos _, by simpa using hm⟩
+
+/-- Restricting the source arrays to all routed systems preserves every physical send. -/
+theorem ramSend_injective :
+ Function.Injective (fun a : RAMLayout.SendArrays D H w ↦ ramSend a) := by
+ intro a b hab
+ apply Prod.ext
+ · funext u j
+ have h : u.val + 1 < 2 ^ D := by have := u.isLt; omega
+ let k := successorClass h
+ let x : Site D := ⟨u.val, by omega⟩
+ have hm := (successorClass_eq_iff h k).mp rfl
+ have he := congrFun (congrFun (congrFun hab (.inl k)) x) j
+ simpa [ramSend, x, h, hm] using he
+ · funext s x j
+ exact congrFun (congrFun (congrFun hab (.inr s)) x) j
+
+/-- Route-bit assignment, with separate payload bits for each system on every
+cursor arc. These are the shared variables in the expanded contraction. -/
+abbrev RAMFields (D H w : ℕ) :=
+ (s : RAMSystem D) → ArcFields D (Fin (ramFieldBits H w s) → Bool)
+
+/-- Recover each physical send directly from its outgoing field at cursor zero.
+At a successor boundary only its own mask class is consulted. -/
+def readSends [NeZero D] (f : RAMFields D H w) : RAMLayout.SendArrays D H w :=
+ (fun u j =>
+ let s : RAMSystem D := .inl (successorClass (x := u.val) (by have := u.isLt; omega))
+ f s 0 ⟨u.val, by have := u.isLt; omega⟩ ((systemMask s).val.testBit 0) j,
+ fun l x j => f (.inr l) 0 x ((systemMask (.inr l)).val.testBit 0) j)
+
+theorem readSends_eq [NeZero D] (a : RAMLayout.SendArrays D H w) (f : RAMFields D H w)
+ (h : ∀ s, LocalTies (fun _ => false) (systemMask s) (ramSend a s) (ramReceive a s) (f s)) :
+ readSends f = a := by
+ apply Prod.ext
+ · funext u j
+ have hx : u.val + 1 < 2 ^ D := by have := u.isLt; omega
+ let k := successorClass hx
+ let x : Site D := ⟨u.val, by have := u.isLt; omega⟩
+ change f (.inl k) 0 x ((systemMask (.inl k)).val.testBit 0) j = a.1 u j
+ rw [(h (.inl k)).start x]
+ simp [ramSend, x, hx, (successorClass_eq_iff hx k).mp rfl]
+ · funext l x j
+ exact congrFun ((h (.inr l)).start x) j
+
+/-- A routed field assignment can be checked using the directly addressed sends
+read at cursor zero. No search over a compatible original assignment is required. -/
+theorem carries_iff_readSends [NeZero D] (f : RAMFields D H w) :
+ (∃ a, ∀ s, LocalTies (fun _ => false) (systemMask s) (ramSend a s) (ramReceive a s) (f s)) ↔
+ ∀ s, LocalTies (fun _ => false) (systemMask s) (ramSend (readSends f) s)
+ (ramReceive (readSends f) s) (f s) := by
+ constructor
+ · rintro ⟨a, ha⟩
+ rw [readSends_eq a f ha]
+ exact ha
+ · exact fun h => ⟨readSends f, h⟩
+
+/-- Unweighted contraction on the cursor graph, summing over its actual bit fields. -/
+noncomputable def ramContraction [NeZero D] {R : Type*} [AddCommMonoid R]
+ (weight : RAMLayout.SendArrays D H w → R) : R :=
+ routedContraction (P := fun s : RAMSystem D => Fin (ramFieldBits H w s) → Bool)
+ (fun _ _ => false) systemMask ramSend ramReceive weight
+
+theorem ramContraction_eq [NeZero D] {R : Type*} [AddCommMonoid R]
+ (weight : RAMLayout.SendArrays D H w → R) :
+ ramContraction weight = ∑ a, weight a := by
+ unfold ramContraction
+ exact routed_contraction_eq _ _ _ _ ramSend_injective ramReceive_at weight
+
+open BurstRAM RAMMemory RAMLayout in
+/-- Applied to the local validators, the routed tensor network still counts precisely
+the capped accepting RAM paths, including all their private branches. -/
+theorem ramContraction_pathCount {C : Type*} {e : ℕ} [NeZero D]
+ (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) :
+ ramContraction (fun a : SendArrays D (2 ^ e) w => ∏ v : Site D,
+ Nat.card (SitePaths P fuel initial header hw hc ((sendArraysEquiv D (2 ^ e) w).symm a) v)) =
+ Nat.card (ActualPaths P fuel initial (initialMemory (2 ^ D) header)
+ (withinCaps (2 ^ D) (2 ^ e))) := by
+ rw [ramContraction_eq, parsimoniousRAMTranscripts P fuel initial header hw hc]
+ exact (sendArraysEquiv D (2 ^ e) w).symm.sum_comp
+ (fun bits => ∏ v : Site D, Nat.card (SitePaths P fuel initial header hw hc bits v))
+
+end CursorRouting
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorState.lean b/lean/OAI/Computability/VPVNP/CursorState.lean
new file mode 100644
index 0000000000..f390d3cce9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorState.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.CursorLanes
+import OAI.Computability.VPVNP.CursorPaddingWidths
+import OAI.Computability.VPVNP.CompressionState
+import OAI.Computability.VPVNP.NetworkHalfIso
+
+/-!
+# The initial state of the compressor
+
+Reindex the physical padded cursor network as the dyadic-degree state of
+Section 7. The site map selects the designated address bits as lanes. The
+edge map preserves the original parallel-arc index. The payload bijection
+concatenates the fields reserved for the individual mask systems.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting NetworkKernel
+open Compression (BitWord State)
+
+variable {D b l a p m : ℕ} {S : Type} [Fintype S]
+variable (labels : Fin D ≃ Fin b ⊕ Fin l) (hD : 1 < D) (hd : 2 + p = 2 ^ a)
+
+/-- Padded physical arc IDs in the compressor's site-first numbering. -/
+def stateEdges : PaddedArc D p ≃ ((Fin D × BitWord b) × BitWord l) × Fin (2 ^ a) :=
+ (paddedEdgeEquiv D p).trans ((lanePositions labels).prodCongr (finCongr hd))
+
+/-- Actual width on one outgoing slot at one source lane, as indexed by a state. -/
+def stateWidth (bits : S → ℕ) (e : ((Fin D × BitWord b) × Fin (2 ^ a)) × BitWord l) : ℕ :=
+ paddedWidth bits ((stateEdges labels hd).symm ((e.1.1,e.2),e.1.2))
+
+/-- The Section 12 state with degree and designated lane count as indices. -/
+noncomputable def cursorState (bits : S → ℕ) : State a l where
+ Base := Fin D × BitWord b
+ baseFintype := inferInstance
+ baseNonempty := ⟨⟨⟨0, by omega⟩,0⟩⟩
+ baseIndex := State.productIndex (Equiv.refl (Fin D)) (Compression.bitWordFinEquiv b)
+ slots := laneGraph labels (slotSide ∘ (finCongr hd).symm) hD
+ width := stateWidth labels hd bits
+
+/-- Match the tensor network of the original cursor validators with the
+input network of a typed compressor execution. -/
+noncomputable def cursorStateIso (order : S ≃ Fin m) (bits : S → ℕ) :
+ (paddedNetwork D p bits).Iso (cursorState labels hD hd bits).network where
+ site := lanePositions labels
+ edge := stateEdges labels hd
+ src e := congrArg (lanePositions labels) (paddedEdge_source bits e)
+ dst e := by
+ let v := (paddedEdgeEquiv D p e).1
+ let i := (paddedEdgeEquiv D p e).2
+ have h := laneGraph_target labels (slotSide ∘ (finCongr hd).symm) hD v.1 v.2 (finCongr hd i)
+ have ht := congrArg Prod.fst (paddedEdge_target hD bits e)
+ change head (v.1, v.2, slotSide i) = (paddedNetwork D p bits).dst e at ht
+ have h' := congrArg Prod.fst h
+ simp only [Function.comp_apply, Equiv.symm_apply_apply] at h'
+ exact (congrArg (lanePositions labels) ht.symm).trans h'.symm
+ payload e := by
+ let z := stateEdges labels hd e
+ change (paddedNetwork D p bits).Payload e ≃
+ (Fin (stateWidth labels hd bits ((z.1.1,z.2),z.1.2)) → Bool)
+ have hw : stateWidth labels hd bits ((z.1.1,z.2),z.1.2) = paddedWidth bits e := by
+ change paddedWidth bits ((stateEdges labels hd).symm (stateEdges labels hd e)) = _
+ exact congrArg (paddedWidth bits) ((stateEdges labels hd).symm_apply_apply e)
+ exact (paddedPayloadEquiv order bits e).trans ((finCongr hw.symm).arrowCongr (Equiv.refl _))
+
+/-- The state position count still includes every processor and every cursor. -/
+theorem cursorState_positions (bits : S → ℕ) :
+ (cursorState labels hD hd bits).positions = 2 ^ D * D := by
+ change Fintype.card ((Fin D × BitWord b) × BitWord l) = _
+ rw [← Fintype.card_congr (lanePositions labels)]
+ simp [Site, Nat.mul_comm D]
+
+/-- The energy charged to the initial state is the energy of the actual
+physical fields and all of its zero-width padding. -/
+theorem cursorState_energy (bits : S → ℕ) :
+ (cursorState labels hD hd bits).energy =
+ ∑ e : PaddedArc D p, (paddedWidth bits e : ℝ) ^ 2 /
+ (1 / (((2 ^ D * D : ℕ) : ℝ) * (2 + p : ℕ))) := by
+ let coords : (((Fin D × BitWord b) × BitWord l) × Fin (2^a)) ≃
+ ((Fin D × BitWord b) × Fin (2^a)) × BitWord l :=
+ ⟨fun e ↦ ((e.1.1,e.2),e.1.2), fun e ↦ ((e.1.1,e.2),e.1.2), fun _ ↦ rfl, fun _ ↦ rfl⟩
+ unfold State.energy
+ rw [cursorState_positions, hd]
+ symm
+ apply Fintype.sum_equiv ((stateEdges labels hd).trans coords)
+ intro e
+ change _ = (paddedWidth bits ((stateEdges labels hd).symm ((stateEdges labels hd) e)) : ℝ) ^ 2 / _
+ rw [Equiv.symm_apply_apply]
+
+/-- Initial square-root energy at the state's normalized arc mass. -/
+theorem cursorState_sqrtEnergy_le (bits : S → ℕ) :
+ Real.sqrt (cursorState labels hD hd bits).energy ≤
+ ((2 ^ D * D : ℕ) : ℝ) * (2 + p : ℕ) * (∑ s, bits s : ℕ) := by
+ rw [cursorState_energy]
+ exact padded_sqrtEnergy_le D p bits
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorStateCount.lean b/lean/OAI/Computability/VPVNP/CursorStateCount.lean
new file mode 100644
index 0000000000..1059de707b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorStateCount.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.CursorValidatorContraction
+import OAI.Computability.VPVNP.CursorState
+import OAI.Computability.VPVNP.NetworkFactorIso
+
+/-!
+# Expanded RAM path counts in compressor coordinates
+
+In (12.2) the compressor starts with the regular cursor network, represented
+as base vertices and lanes. Relabelling its original local choices preserves
+each accepting path of each validator, including when later substitutions
+give it half-wire arguments that disagree across an original edge.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting NetworkKernel BurstRAM BurstRAM.PrivateRAM
+
+variable {D b l a padding w p r k e : ℕ} [NeZero D]
+
+/-- Equation (12.2) for a finite history on the dyadic-degree compressor
+state. The original local choices are the validator's individual private
+strings and the empty transit choices, transported through the site, edge
+and bit-alphabet bijections. -/
+noncomputable def expandedRAMStateCount {A : Type*} [CommRing A] {Label : Type} [Fintype Label]
+ {κ : Label → A} (M : Machine w p r k) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w)
+ (labels : Fin D ≃ Fin b ⊕ Fin l) (hD : 1 < D) (hd : 2 + padding = 2 ^ a)
+ (T : History A (cursorState labels hD hd (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ)).network)
+ (K : T.KernelWitnesses κ) :
+ MonomialWitness κ (Nat.card (ActualPaths M.program fuel initial
+ (RAMMemory.initialMemory (2 ^ D) header)
+ (withinCaps (2 ^ D) (2 ^ e))) : A) :=
+ let bits := (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ)
+ let I := cursorStateIso labels hD hd (ramSystemOrder D) bits
+ let P : Factors Type (paddedNetwork D padding bits) := fun v z ↦
+ initialChoices M fuel initial header hw hc v (unpadHalf padding v z)
+ let fin : ∀ v z, Fintype (P v z) := fun v z ↦
+ initialChoicesFintype M fuel initial header hw hc v (unpadHalf padding v z)
+ let counts := fun v z ↦ @Fintype.card _ (initialChoicesFintype M fuel initial header hw hc v z)
+ let count_eq := (I.contract_pushChoiceCount P fin).trans
+ ((contract_padded padding counts).trans (initialChoices_contract M fuel initial header hw hc))
+ (@History.expandedCount A _ Label _ κ _ T K (I.pushFactors P)
+ (I.pushChoiceFintype P fin)).changeValue
+ (congrArg (fun n : ℕ ↦ (n : A)) count_eq)
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CursorValidatorContraction.lean b/lean/OAI/Computability/VPVNP/CursorValidatorContraction.lean
new file mode 100644
index 0000000000..2878af3052
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CursorValidatorContraction.lean
@@ -0,0 +1,182 @@
+import OAI.Computability.VPVNP.CursorRAMFields
+import OAI.Computability.VPVNP.CursorPadding
+import OAI.Computability.VPVNP.IncidentPathFiniteness
+import OAI.Computability.VPVNP.NetworkMonomials
+
+/-!
+# Local path counts at cursor zero
+
+In Section 12 of *VP and VNP differ over every field* the selected outgoing and
+returning fields at cursor zero supply the incident bits of the local RAM
+validator. Successor fields use their unique active mask class, and a missing
+successor at either endpoint supplies zero. Sorting layers have a field in
+each direction. We identify this local decoder with the physical bit layout.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorRouting RAMLayout BurstRAM BurstRAM.PrivateRAM
+
+variable {D H w : ℕ}
+
+/-- All mask-system fields on one selected side of a cursor site. -/
+abbrev RAMPayload (D H w : ℕ) := (s : RAMSystem D) → Fin (ramFieldBits H w s) → Bool
+
+/-- Decode one incident slot using only the two sets of fields delivered to
+this site's validator. -/
+def decodeSlot (v : Site D) (outgoing incoming : RAMPayload D H w) : Slot D H w → Bool
+ | .inl (dir, j) =>
+ if dir = 0 then
+ if h : v.val + 1 < 2 ^ D then outgoing (.inl (successorClass h)) j else false
+ else
+ if h : 0 < v.val then
+ incoming (.inl (successorClass (x := v.val - 1) (by have := v.isLt; omega))) j
+ else false
+ | .inr (s, dir, j) => if dir = 0 then outgoing (.inr s) j else incoming (.inr s) j
+
+/-- Serialize the decoded slots in the order expected by the RAM validator. -/
+def decodeIncident (v : Site D) (outgoing incoming : RAMPayload D H w) :
+ Fin (width D H w) → Bool :=
+ decodeSlot v outgoing incoming ∘ (offset D H w).symm
+
+/-- For a routed assignment, the local decoder reads exactly the bit vector
+at the corresponding site of the original transcript. -/
+theorem decodeIncident_ram (a : SendArrays D H w) (v : Site D) :
+ decodeIncident v (fun s ↦ ramSend a s v) (fun s ↦ ramReceive a s v) =
+ RAMLayout.incidentBits a v := by
+ funext i
+ obtain ⟨p, rfl⟩ := (offset D H w).surjective i
+ simp only [decodeIncident, Function.comp_apply, Equiv.symm_apply_apply, incidentBits_offset]
+ rcases p with ⟨dir, j⟩ | ⟨s, dir, j⟩ <;> fin_cases dir
+ · by_cases h : v.val + 1 < 2 ^ D
+ · simpa [decodeSlot, h] using ramSend_successor a v h j
+ · have hend : v.val + 1 = 2 ^ D := by have := v.isLt; omega
+ simpa [decodeSlot, h] using
+ (incident_clamp a (v, .inl (0, j)) (peer_send_end v hend j)).symm
+ · by_cases h : 0 < v.val
+ · simpa [decodeSlot, h] using ramReceive_successor a v h j
+ · have hstart : v.val = 0 := by omega
+ simpa [decodeSlot, h] using
+ (incident_clamp a (v, .inl (1, j)) (peer_receive_start v hstart j)).symm
+ · simpa [decodeSlot] using ramSend_sort a s v j
+ · simpa [decodeSlot] using ramReceive_sort a s v j
+
+variable {p r k e : ℕ}
+
+/-- The genuine accepting private strings for the supplied local cursor bits. -/
+abbrev validatorPaths (M : Machine w p r k) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) (v : Site D)
+ (outgoing incoming : RAMPayload D (2 ^ e) w) :=
+ M.IncidentPaths fuel initial (header v) hw hc v (decodeIncident v outgoing incoming)
+
+/-- Summing the zero-cursor local counts against the physical sender arrays
+gives the capped path count, with every private choice retaining its own
+multiplicity. -/
+theorem validatorPaths_sum [NeZero D] (M : Machine w p r k) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) :
+ (∑ a : SendArrays D (2 ^ e) w, ∏ v : Site D, Nat.card
+ (validatorPaths M fuel initial header hw hc v (fun s ↦ ramSend a s v)
+ (fun s ↦ ramReceive a s v))) =
+ Nat.card (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2 ^ D) header)
+ (withinCaps (2 ^ D) (2 ^ e))) := by
+ rw [← ramContraction_pathCount M.program fuel initial header hw hc, ramContraction_eq]
+ apply Finset.sum_congr rfl
+ intro a _
+ apply Finset.prod_congr rfl
+ intro v _
+ simp only [validatorPaths, decodeIncident_ram]
+ have he : BurstRAM.incidentBits ((sendArraysEquiv D (2 ^ e) w).symm a) v =
+ RAMLayout.incidentBits a v := by
+ simp [BurstRAM.incidentBits]
+ exact he ▸ Nat.card_congr (M.incidentPathEquiv fuel initial header hw hc
+ ((sendArraysEquiv D (2 ^ e) w).symm a) v)
+
+open NetworkKernel
+
+variable [NeZero D]
+
+/-- The initial network of Section 12 has a bit field for every RAM mask
+system on each of the two arcs leaving each cursor position. -/
+noncomputable abbrev validatorNetwork (D e w : ℕ) :=
+ network D (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ)
+
+open scoped Classical in
+/-- A valid transit vertex contributes its unique empty choice. At cursor
+zero the local choices are the private binary paths of the site validator. -/
+noncomputable def initialChoices (M : Machine w p r k) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w)
+ (v : Position D) (z : (validatorNetwork D e w).Half v) : Type :=
+ if Checks systemMask v z then
+ if v.1 = 0 then
+ if ActiveSends v.2 (sent systemMask v z) then
+ validatorPaths M fuel initial header hw hc v.2
+ (sent systemMask v z) (received systemMask v z)
+ else Empty
+ else Unit
+ else Empty
+
+instance (M : Machine w p r k) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) (v : Position D)
+ (z : (validatorNetwork D e w).Half v) :
+ Finite (initialChoices M fuel initial header hw hc v z) := by
+ unfold initialChoices
+ split_ifs <;> infer_instance
+
+noncomputable instance initialChoicesFintype (M : Machine w p r k) (fuel : ℕ)
+ (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) (v : Position D)
+ (z : (validatorNetwork D e w).Half v) :
+ Fintype (initialChoices M fuel initial header hw hc v z) := Fintype.ofFinite _
+
+open scoped Classical in
+/-- The actual finite cursor network contracts to the capped RAM path count.
+The local factor is defined for every half-wire input, even those that never
+occur in a globally tied assignment. -/
+theorem initialChoices_contract (M : Machine w p r k) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) :
+ contract (validatorNetwork D e w)
+ (fun v z ↦ @Fintype.card _ (initialChoicesFintype M fuel initial header hw hc v z)) =
+ Nat.card (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2 ^ D) header)
+ (withinCaps (2 ^ D) (2 ^ e))) := by
+ let val := fun v out inc ↦ Nat.card (validatorPaths M fuel initial header hw hc v out inc)
+ have hf : (fun v z ↦ Fintype.card (initialChoices M fuel initial header hw hc v z)) =
+ factors systemMask (fun v out inc ↦ if ActiveSends v out then val v out inc else 0) := by
+ funext v z
+ rw [← Nat.card_eq_fintype_card]
+ unfold initialChoices factors
+ split_ifs <;> simp_all [val]
+ exact (congrArg (contract (validatorNetwork D e w)) hf).trans
+ ((contract_ram val).trans (validatorPaths_sum M fuel initial header hw hc))
+
+/-- Equation (12.2) for the paper's cursor graph, including any required
+parallel zero-width slots. Given an exact finite compression history, the sum
+of the monomials on its expanded paths equals the capped machine count. -/
+noncomputable def expandedRAMCount {A : Type*} [CommRing A] {Label : Type} [Fintype Label]
+ {κ : Label → A} (M : Machine w p r k) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) (padding : ℕ)
+ (T : History A (paddedNetwork D padding (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ)))
+ (K : T.KernelWitnesses κ) :
+ MonomialWitness κ (Nat.card (ActualPaths M.program fuel initial
+ (RAMMemory.initialMemory (2 ^ D) header)
+ (withinCaps (2 ^ D) (2 ^ e))) : A) :=
+ let P := initialChoices M fuel initial header hw hc
+ let counts := fun v z ↦ @Fintype.card _ (initialChoicesFintype M fuel initial header hw hc v z)
+ let count_eq := (contract_padded padding counts).trans
+ (initialChoices_contract M fuel initial header hw hc)
+ let fin : ∀ (v : Position D)
+ (z : (paddedNetwork D padding (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ)).Half v),
+ Fintype (P v (unpadHalf padding v z)) :=
+ fun v z ↦ initialChoicesFintype M fuel initial header hw hc v (unpadHalf padding v z)
+ (@History.expandedCount A _ Label _ κ _ T K
+ (fun v z ↦ P v (unpadHalf padding v z)) fin).changeValue
+ (congrArg (fun n : ℕ ↦ (n : A)) count_eq)
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CutSchedule.lean b/lean/OAI/Computability/VPVNP/CutSchedule.lean
new file mode 100644
index 0000000000..f39cba60cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CutSchedule.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.RAMSerialization
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+import Mathlib.Data.Nat.Log
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# The cut widths in the paired chain
+
+The primary paper uses a chain of length `2^H`. Equation (9.1) allocates
+`(H − ⌊log₂ i⌋) Δ` bits to the interior cut numbered `i`. On the first half
+this is exactly the width of the doubled primed cut plus one block. On the
+tail there is one block. The field layouts below keep the mode at the first
+position and the zero padding at the end.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CutSchedule
+
+/-- Number of bits on a cut, with both missing endpoint cuts clamped. -/
+def width (H Δ i : ℕ) : ℕ :=
+ if 0 < i ∧ i < 2 ^ H then (H - Nat.log 2 i) * Δ else 0
+
+@[simp] theorem width_zero (H Δ : ℕ) : width H Δ 0 = 0 := by simp [width]
+
+@[simp] theorem width_end (H Δ : ℕ) : width H Δ (2 ^ H) = 0 := by simp [width]
+
+/-- On every nonempty cut in the tail, including the middle cut, the width is one block. -/
+theorem width_tail (h Δ i : ℕ) (hi : 2 ^ h ≤ i) (hlt : i < 2 ^ (h + 1)) :
+ width (h + 1) Δ i = Δ := by
+ have hi' : 0 < i := (Nat.two_pow_pos h).trans_le hi
+ rw [width, ite_eq_left ⟨hi', hlt⟩, Nat.log_eq_of_pow_le_of_lt_pow hi hlt]
+ simp
+
+/-- Doubling the primed cut number saves exactly one block, even at the
+middle cut where the doubled primed cut is the empty endpoint. -/
+theorem width_double (h Δ i : ℕ) (hi : 0 < i) (hle : i ≤ 2 ^ h) :
+ width (h + 1) Δ i = width (h + 1) Δ (2 * i) + Δ := by
+ have hh : 0 < 2 ^ h := Nat.two_pow_pos h
+ have hi' : i < 2 ^ (h + 1) := by rw [pow_succ]; omega
+ by_cases he : i = 2 ^ h
+ · subst i
+ rw [width_tail _ _ _ le_rfl hi', ← pow_succ', width_end, Nat.zero_add]
+ · have h2i : 2 * i < 2 ^ (h + 1) := by rw [pow_succ]; omega
+ have hlog := Nat.log_lt_of_lt_pow (Nat.ne_of_gt hi) hi'
+ rw [width, width, ite_eq_left ⟨hi, hi'⟩, ite_eq_left ⟨by omega, h2i⟩, Nat.mul_comm 2 i,
+ Nat.log_mul_base (by decide) (Nat.ne_of_gt hi)]
+ rw [show h + 1 - Nat.log 2 i = (h + 1 - (Nat.log 2 i + 1)) + 1 by omega, Nat.succ_mul]
+
+/-- A width-`w` Boolean word indexed by the integers from zero to `w - 1`. -/
+abbrev Bits (w : ℕ) := Fin w → Bool
+
+/-- Split a cut into its contiguous left and right fields. -/
+def splitBits (a b : ℕ) : Bits (a + b) ≃ Bits a × Bits b :=
+ (finSumFinEquiv.symm.arrowCongr (Equiv.refl Bool)).trans
+ (Equiv.sumArrowEquivProdArrow (Fin a) (Fin b) Bool)
+
+private def castBits {a b : ℕ} (h : a = b) : Bits a ≃ Bits b :=
+ (finCongr h).arrowCongr (Equiv.refl Bool)
+
+private def modeBits : Bits 1 ≃ Bool := Equiv.funUnique _ _
+
+/-- The first-half layout in Section 14.1 in the order mode, exterior primed
+bits, exponents, padding. Exponents use the RAM's fixed-width binary encoding.
+A zero width gives the unique empty bit string. -/
+def firstHalfLayout (h Δ i t Z : ℕ) (hi : 0 < i) (hle : i ≤ 2 ^ h) (hfit : 1 + t * Z ≤ Δ) :
+ Bits (width (h + 1) Δ i) ≃
+ Bool × Bits (width (h + 1) Δ (2 * i)) × (Fin t → BurstRAM.Word Z) × Bits (Δ - (1 + t * Z)) :=
+ let old := width (h + 1) Δ (2 * i)
+ let pad := Δ - (1 + t * Z)
+ let size : width (h + 1) Δ i = 1 + (old + (t * Z + pad)) := by
+ rw [width_double h Δ i hi hle]
+ dsimp [old, pad]
+ omega
+ let splitPayload := (splitBits (t * Z) pad).trans
+ ((RAMSerialization.arrayBits t Z).symm.prodCongr (Equiv.refl _))
+ let splitExterior := (splitBits old _).trans ((Equiv.refl _).prodCongr splitPayload)
+ (castBits size).trans ((splitBits 1 _).trans (modeBits.prodCongr splitExterior))
+
+/-- Tail cuts store one mode, the evaluator configuration, and trailing padding. -/
+def tailLayout (h Δ i c : ℕ) (hi : 2 ^ h ≤ i) (hlt : i < 2 ^ (h + 1)) (hfit : 1 + c ≤ Δ) :
+ Bits (width (h + 1) Δ i) ≃ Bool × Bits c × Bits (Δ - (1 + c)) :=
+ let size : width (h + 1) Δ i = 1 + (c + (Δ - (1 + c))) := by rw [width_tail _ _ _ hi hlt]; omega
+ (castBits size).trans ((splitBits 1 _).trans (modeBits.prodCongr (splitBits c _)))
+
+/-- Exterior bits and the accumulated label exponents uniquely fix each
+first-half cut string once the mode and canonical zero padding are imposed. -/
+theorem firstHalf_unique (h Δ i t Z : ℕ) (hi : 0 < i) (hle : i ≤ 2 ^ h) (hfit : 1 + t * Z ≤ Δ)
+ (mode : Bool) (exterior : Bits (width (h + 1) Δ (2 * i))) (exponents : Fin t → BurstRAM.Word Z) :
+ ∃! bits, firstHalfLayout h Δ i t Z hi hle hfit bits =
+ (mode, exterior, exponents, fun _ => false) :=
+ (firstHalfLayout h Δ i t Z hi hle hfit).bijective.existsUnique _
+
+/-- The configuration and mode determine exactly one canonically padded
+tail cut, also when no padding is needed. -/
+theorem tail_unique (h Δ i c : ℕ) (hi : 2 ^ h ≤ i) (hlt : i < 2 ^ (h + 1)) (hfit : 1 + c ≤ Δ)
+ (mode : Bool) (config : Bits c) :
+ ∃! bits, tailLayout h Δ i c hi hlt hfit bits = (mode, config, fun _ => false) :=
+ (tailLayout h Δ i c hi hlt hfit).bijective.existsUnique _
+
+/-- Every prefix sum of local `2r`-bit increments fits in the paper's `Z = 2H`
+bits when `2r < H`, as verified in Section 14.1. -/
+theorem accumulated_lt (H r k : ℕ) (inc : ℕ → ℕ) (hk : k ≤ 2 ^ H) (hr : 2 * r < H)
+ (hinc : ∀ i < k, inc i < 2 ^ (2 * r)) :
+ ∑ i ∈ Finset.range k, inc i < 2 ^ (2 * H) := by
+ calc
+ _ ≤ ∑ _i ∈ Finset.range k, 2 ^ (2 * r) :=
+ Finset.sum_le_sum (fun i hi => (hinc i (Finset.mem_range.mp hi)).le)
+ _ = k * 2 ^ (2 * r) := by simp
+ _ ≤ 2 ^ H * 2 ^ (2 * r) := Nat.mul_le_mul_right _ hk
+ _ = 2 ^ (H + 2 * r) := (pow_add ..).symm
+ _ < 2 ^ (2 * H) := Nat.pow_lt_pow_right (by decide) (by omega)
+
+end CutSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CycleCriterion.lean b/lean/OAI/Computability/VPVNP/CycleCriterion.lean
new file mode 100644
index 0000000000..01a04a2b82
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CycleCriterion.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.Hamiltonian
+import Mathlib.Dynamics.PeriodicPts.Defs
+
+/-!
+# Recognizing a spanning cycle by its first return
+
+A walk from one root can check a Boolean adjacency matrix one row at a time.
+If it first returns to the root after exactly as many steps as there are vertices,
+the visited rows comprise the whole matrix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open Function
+
+/-- The scanned successor is the only true entry of the row. -/
+def RowValid {m : ℕ} (x : Fin m × Fin m → Bool) (i : Fin m) : Prop :=
+ ∀ j, x (i, j) = decide (rowSuccessor x i = j)
+
+/-- A row-by-row walk accepts exactly the adjacency matrices of spanning cycles.
+It rejects a missing or ambiguous outgoing edge on any visited row, as well as
+a return to the root before the final step. -/
+theorem mem_spanningCycleEdges_iff_firstReturn {m : ℕ} (root : Fin m)
+ (x : Fin m × Fin m → Bool) :
+ x ∈ (spanningCycles m).image permutationEdges ↔
+ (∀ k : Fin m, RowValid x ((rowSuccessor x)^[k.val] root)) ∧
+ (∀ k : ℕ, 0 < k → k < m → (rowSuccessor x)^[k] root ≠ root) ∧
+ (rowSuccessor x)^[m] root = root := by
+ classical
+ have hm := Nat.zero_lt_of_lt root.isLt
+ constructor
+ · intro hx
+ obtain ⟨π, hπ, rfl⟩ := Finset.mem_image.mp hx
+ have hcyc : π.IsCycleOn (Finset.univ : Finset (Fin m)) := by
+ simpa [spanningCycles, hm] using hπ
+ simp only [RowValid, rowSuccessor_permutationEdges]
+ refine ⟨fun _ _ => rfl, ?_, ?_⟩
+ · intro k hk hkm heq
+ have hdvd : m ∣ k := by
+ simpa using (hcyc.pow_apply_eq (Finset.mem_univ root)).1 heq
+ exact hkm.not_ge (Nat.le_of_dvd hk hdvd)
+ · simpa [Equiv.Perm.coe_pow] using hcyc.pow_card_apply (Finset.mem_univ root)
+ · rintro ⟨hrow, hfirst, hreturn⟩
+ let f := rowSuccessor x
+ have hp : IsPeriodicPt f m root := hreturn
+ have hmin : minimalPeriod f root = m := by
+ apply (hp.minimalPeriod_le hm).antisymm
+ exact le_of_not_gt fun h =>
+ hfirst _ (hp.minimalPeriod_pos hm) h (iterate_minimalPeriod (f := f) (x := root))
+ let visit (k : Fin m) := f^[k.val] root
+ have hinj : Injective visit := by
+ intro i j h
+ apply Fin.ext
+ exact (iterate_eq_iterate_iff_of_lt_minimalPeriod
+ (hmin.symm ▸ i.isLt) (hmin.symm ▸ j.isLt)).mp h
+ have hreach : Surjective visit := Finite.injective_iff_surjective.mp hinj
+ apply (acceptsCycleMatrix_iff root x).mp
+ rw [acceptsCycleMatrix, decide_eq_true_eq]
+ refine ⟨?_, ?_, hreach⟩
+ · intro i
+ obtain ⟨k, rfl⟩ := hreach i
+ exact hrow k
+ · intro j
+ obtain ⟨k, rfl⟩ := hreach j
+ exact periodicPts_subset_range (mk_mem_periodicPts hm (hp.apply_iterate k.val))
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CycleQuery.lean b/lean/OAI/Computability/VPVNP/CycleQuery.lean
new file mode 100644
index 0000000000..a1f6464980
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CycleQuery.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.CycleCriterion
+import OAI.Computability.VPVNP.CycleQueryRow
+
+/-!
+# Exact query budget for the Hamiltonian matrix check
+
+Starting from the distinguished root, the finite-control program scans one row
+per vertex in the putative cycle. A successful traversal uses exactly one read
+per column of each of its `m` rows.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+variable {m : ℕ} (root : Fin m) (x : Fin m × Fin m → Bool)
+
+/-- The row and first-return checks that are still pending at the start of row `t`. -/
+private def passesFrom (t : ℕ) : Prop :=
+ (∀ k : ℕ, t ≤ k → k < m → RowValid x ((rowSuccessor x)^[k] root)) ∧
+ (∀ k : ℕ, t < k → k < m → (rowSuccessor x)^[k] root ≠ root) ∧
+ (rowSuccessor x)^[m] root = root
+
+private theorem passesFrom_succ {t : ℕ} (ht : t + 1 < m) :
+ passesFrom root x t ↔ RowValid x ((rowSuccessor x)^[t] root) ∧
+ (rowSuccessor x)^[t + 1] root ≠ root ∧ passesFrom root x (t + 1) := by
+ constructor
+ · rintro ⟨rows, before, finish⟩
+ exact ⟨rows t le_rfl (by omega), before _ (by omega) ht,
+ fun k hk hkm => rows k (by omega) hkm, fun k hk hkm => before k (by omega) hkm, finish⟩
+ · rintro ⟨row, next, rows, before, finish⟩
+ refine ⟨fun k hk hkm => ?_, fun k hk hkm => ?_, finish⟩
+ · by_cases h : k = t
+ · simpa [h] using row
+ · exact rows k (by omega) hkm
+ · by_cases h : k = t + 1
+ · simpa [h] using next
+ · exact before k (by omega) hkm
+
+private theorem passesFrom_last {t : ℕ} (ht : t + 1 = m) :
+ passesFrom root x t ↔ RowValid x ((rowSuccessor x)^[t] root) ∧
+ (rowSuccessor x)^[t + 1] root = root := by
+ constructor
+ · rintro ⟨rows, _, finish⟩
+ exact ⟨rows _ le_rfl (by omega), ht.symm ▸ finish⟩
+ · rintro ⟨row, finish⟩
+ refine ⟨fun k hk hkm => ?_, fun k hk hkm => ?_, ht ▸ finish⟩
+ · have h : k = t := by omega
+ simpa [h] using row
+ · omega
+
+private theorem cycleQuery_eval_from (t : Fin m) :
+ (cycleQuery root).eval (x ∘ finProdFinEquiv.symm) ((m - t.val) * m)
+ (.inr (t, (rowSuccessor x)^[t.val] root, ⟨0, root.pos⟩, none)) = true ↔
+ passesFrom root x t.val := by
+ have ht := t.isLt
+ have hfuel : (m - t.val) * m = (m - (t.val + 1)) * m + m := by
+ rw [← Nat.succ_mul, show (m - (t.val + 1)).succ = m - t.val by omega]
+ rw [hfuel, cycleQuery_eval_row]
+ have hvisit : rowSuccessor x ((rowSuccessor x)^[t.val] root) =
+ (rowSuccessor x)^[t.val + 1] root := (Function.iterate_succ_apply' ..).symm
+ by_cases row : RowValid x ((rowSuccessor x)^[t.val] root)
+ · have rowBits := row
+ unfold RowValid at rowBits
+ rw [ite_eq_left rowBits, hvisit]
+ by_cases h : t.val + 1 < m
+ · rw [passesFrom_succ root x h, and_iff_right row]
+ simp only [afterRow, dite_eq_left h]
+ by_cases early : (rowSuccessor x)^[t.val + 1] root = root
+ · simp [early]
+ · rw [ite_eq_right early, and_iff_right early]
+ exact cycleQuery_eval_from ⟨_, h⟩
+ · rw [passesFrom_last root x (by omega), and_iff_right row]
+ simp only [afterRow, dite_eq_right h, cycleQuery_eval_halt, beq_iff_eq]
+ · have rowBits := row
+ unfold RowValid at rowBits
+ rw [ite_eq_right rowBits]
+ exact ⟨fun h => by contradiction, fun hp => (row (hp.1 _ le_rfl t.isLt)).elim⟩
+termination_by m - t.val
+decreasing_by omega
+
+
+/-- The matrix query program decides the directed spanning-cycle predicate with
+a budget of exactly `m * m` payload queries. -/
+theorem cycleQuery_eval_iff (root : Fin m) (x : Fin m × Fin m → Bool) :
+ (cycleQuery root).eval (x ∘ finProdFinEquiv.symm) (m * m) (cycleQuery root).start = true ↔
+ x ∈ (spanningCycles m).image permutationEdges := by
+ rw [mem_spanningCycleEdges_iff_firstReturn]
+ have start := cycleQuery_eval_from root x ⟨0, root.pos⟩
+ simp only [Nat.sub_zero, Function.iterate_zero, id_eq] at start
+ rw [show (cycleQuery root).start = .inr (⟨0, root.pos⟩, root, ⟨0, root.pos⟩, none) by rfl, start]
+ unfold passesFrom
+ refine and_congr_left fun _ => ⟨fun rows k => rows k.val (Nat.zero_le _) k.isLt, ?_⟩
+ exact fun rows k _ hk => rows ⟨k, hk⟩
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/CycleQueryRow.lean b/lean/OAI/Computability/VPVNP/CycleQueryRow.lean
new file mode 100644
index 0000000000..b491ca581c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/CycleQueryRow.lean
@@ -0,0 +1,179 @@
+import OAI.Computability.VPVNP.Hamiltonian
+import OAI.Computability.VPVNP.QueryProgram
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# Reading a directed Hamiltonian cycle row by row
+
+A running control stores the number of completed rows, the current vertex, the column
+to inspect, and the unique edge found so far in the row. Each transition reads one
+payload bit. A second edge in a row or an empty row immediately gives a rejection.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+/-- A halted result or a row count, vertex, column, and previously found successor. -/
+abbrev CycleState (m : ℕ) := Bool ⊕ (Fin m × Fin m × Fin m × Option (Fin m))
+
+/-- Continue the traversal at the unique edge's target. The first return must occur
+after exactly `m` rows. -/
+def afterRow {m : ℕ} (root t w : Fin m) : CycleState m :=
+ if h : t.val + 1 < m then
+ if w = root then .inl false else .inr (⟨t.val + 1, h⟩, w, ⟨0, root.pos⟩, none)
+ else .inl (w == root)
+
+private def readEdge {m : ℕ} (root t v j : Fin m) (acc : Option (Fin m)) (bit : Bool) :
+ CycleState m :=
+ if bit = true ∧ acc ≠ none then .inl false else
+ let found := if bit then some j else acc
+ if h : j.val + 1 < m then .inr (t, v, ⟨j.val + 1, h⟩, found)
+ else match found with
+ | some w => afterRow root t w
+ | none => .inl false
+
+/-- A fixed finite control for an `m × m` binary adjacency matrix in row-major order. -/
+def cycleQuery {m : ℕ} (root : Fin m) : QueryProgram (m * m) (CycleState m) where
+ start := .inr (⟨0, root.pos⟩, root, ⟨0, root.pos⟩, none)
+ step
+ | .inl b => .halt b
+ | .inr (t, v, j, acc) =>
+ .read (finProdFinEquiv (v, j)) (readEdge root t v j acc false) (readEdge root t v j acc true)
+
+@[simp] theorem cycleQuery_eval_halt {m : ℕ} (root : Fin m) (bits : Fin (m * m) → Bool)
+ (fuel : ℕ) (b : Bool) : (cycleQuery root).eval bits fuel (.inl b) = b := by
+ cases fuel <;> rfl
+
+private theorem cycleQuery_eval_read {m : ℕ} (root : Fin m) (x : Fin m × Fin m → Bool)
+ (fuel : ℕ) (t v j : Fin m) (acc : Option (Fin m)) :
+ (cycleQuery root).eval (x ∘ finProdFinEquiv.symm) (fuel + 1) (.inr (t, v, j, acc)) =
+ (cycleQuery root).eval (x ∘ finProdFinEquiv.symm) fuel (readEdge root t v j acc (x (v, j))) := by
+ simp only [QueryProgram.eval, cycleQuery, Function.comp_apply, Equiv.symm_apply_apply]
+ cases h : x (v, j) <;> rfl
+
+private theorem rowSuccessor_eq_of_single {m : ℕ} (x : Fin m × Fin m → Bool) (v w : Fin m)
+ (h : ∀ k, x (v, k) = true ↔ w = k) : rowSuccessor x v = w := by
+ unfold rowSuccessor
+ cases hfind : (List.finRange m).find? (fun k => x (v, k)) with
+ | none =>
+ have hmiss := List.find?_eq_none.mp hfind w (List.mem_finRange _)
+ simp [(h w).2 rfl] at hmiss
+ | some k =>
+ have hk := List.find?_some hfind
+ exact ((h k).1 hk).symm
+
+private theorem row_eq_decide_of_single {m : ℕ} (x : Fin m × Fin m → Bool) (v w : Fin m)
+ (h : ∀ k, x (v, k) = true ↔ w = k) : ∀ k, x (v, k) = decide (rowSuccessor x v = k) := by
+ intro k
+ rw [rowSuccessor_eq_of_single x v w h]
+ exact Bool.eq_iff_iff.mpr (by simpa using h k)
+
+private def RowPrefix {m : ℕ} (b : Fin m → Bool) (n : ℕ) (a : Option (Fin m)) : Prop :=
+ (∀ k : Fin m, k.val < n → (b k = true ↔ a = some k)) ∧
+ (∀ k : Fin m, a = some k → k.val < n)
+
+private theorem rowPrefix_zero {m : ℕ} (b : Fin m → Bool) : RowPrefix b 0 none := by
+ simp [RowPrefix]
+
+private theorem rowPrefix_step {m : ℕ} {b : Fin m → Bool} (j : Fin m) {a : Option (Fin m)}
+ (ha : RowPrefix b j.val a) (hok : b j = true → a = none) :
+ RowPrefix b (j.val + 1) (if b j then some j else a) := by
+ obtain ⟨hbits, hbound⟩ := ha
+ cases h : b j with
+ | false =>
+ simp only [Bool.false_eq_true, ite_false]
+ refine ⟨fun k hk => ?_, fun k hak => Nat.lt_succ_of_lt (hbound k hak)⟩
+ rcases Nat.lt_succ_iff_lt_or_eq.mp hk with hk | hk
+ · exact hbits k hk
+ · have heq : k = j := Fin.ext hk
+ subst k
+ have hne : a ≠ some j := fun hj => Nat.lt_irrefl _ (hbound j hj)
+ simp [h, hne]
+ | true =>
+ have ha := hok h
+ subst a
+ simp only [ite_true]
+ constructor
+ · intro k hk
+ rcases Nat.lt_succ_iff_lt_or_eq.mp hk with hk | hk
+ · have hne : j ≠ k := by
+ rintro rfl
+ exact Nat.lt_irrefl _ hk
+ simpa [hne] using hbits k hk
+ · have heq : k = j := Fin.ext hk
+ subst k
+ simp [h]
+ · rintro k hk
+ obtain rfl := Option.some.inj hk
+ exact Nat.lt_succ_self _
+
+private theorem scanRow {m : ℕ} (root : Fin m) (x : Fin m × Fin m → Bool)
+ (f : ℕ) (t v j : Fin m) (acc : Option (Fin m))
+ (ha : RowPrefix (fun k => x (v, k)) j.val acc) :
+ (cycleQuery root).eval (x ∘ finProdFinEquiv.symm) (f + (m - j.val))
+ (.inr (t, v, j, acc)) =
+ if (∀ k, x (v, k) = decide (rowSuccessor x v = k)) then
+ (cycleQuery root).eval (x ∘ finProdFinEquiv.symm) f (afterRow root t (rowSuccessor x v))
+ else false := by
+ have htime : f + (m - j.val) = (f + (m - (j.val + 1))) + 1 := by omega
+ rw [htime, cycleQuery_eval_read]
+ by_cases hbad : x (v, j) = true ∧ acc ≠ none
+ · obtain ⟨hb, hne⟩ := hbad
+ cases acc with
+ | none => exact False.elim (hne rfl)
+ | some w =>
+ have hw : w.val < j.val := ha.2 w rfl
+ have hxw : x (v, w) = true := (ha.1 w hw).mpr rfl
+ have invalid : ¬ ∀ k, x (v, k) = decide (rowSuccessor x v = k) := by
+ intro valid
+ have e₁ := (valid w).symm.trans hxw
+ have e₂ := (valid j).symm.trans hb
+ have eq := (of_decide_eq_true e₁).symm.trans (of_decide_eq_true e₂)
+ exact (ne_of_lt hw) (congrArg Fin.val eq)
+ simp [readEdge, hb, invalid]
+ · have hok : x (v, j) = true → acc = none := by
+ intro hj
+ by_contra h
+ exact hbad ⟨hj, h⟩
+ have hn := rowPrefix_step j ha hok
+ simp only [readEdge, ite_eq_right hbad]
+ by_cases hnext : j.val + 1 < m
+ · rw [dite_eq_left hnext]
+ exact scanRow root x f t v ⟨j.val + 1, hnext⟩ _ hn
+ · rw [dite_eq_right hnext]
+ have hdone : m - (j.val + 1) = 0 := by omega
+ simp only [hdone, Nat.add_zero]
+ generalize hfound : (if x (v, j) then some j else acc) = found at hn ⊢
+ cases found with
+ | none =>
+ have invalid : ¬ ∀ k, x (v, k) = decide (rowSuccessor x v = k) := by
+ intro valid
+ let k := rowSuccessor x v
+ have hxk : x (v, k) = true := by simpa [k] using valid k
+ have hkm := k.isLt
+ have := (hn.1 k (by omega)).mp hxk
+ contradiction
+ simp [invalid]
+ | some w =>
+ have single (k : Fin m) : x (v, k) = true ↔ w = k := by
+ have hkm := k.isLt
+ simpa using hn.1 k (by omega)
+ have hw : rowSuccessor x v = w := rowSuccessor_eq_of_single x v w single
+ have valid := row_eq_decide_of_single x v w single
+ simp [valid, hw]
+termination_by m - j.val
+
+/-- With the remaining clock increased by one row, the scan either rejects the row or
+continues with its unique successor and exactly the original remaining clock. -/
+theorem cycleQuery_eval_row {m : ℕ} (root : Fin m) (x : Fin m × Fin m → Bool)
+ (f : ℕ) (t v : Fin m) :
+ (cycleQuery root).eval (x ∘ finProdFinEquiv.symm) (f + m) (.inr (t, v, ⟨0, v.pos⟩, none)) =
+ if (∀ k, x (v, k) = decide (rowSuccessor x v = k)) then
+ (cycleQuery root).eval (x ∘ finProdFinEquiv.symm) f (afterRow root t (rowSuccessor x v))
+ else false := by
+ exact scanRow root x f t v ⟨0, v.pos⟩ none (rowPrefix_zero _)
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefresh.lean b/lean/OAI/Computability/VPVNP/DegreeRefresh.lean
new file mode 100644
index 0000000000..8f81e3a2f9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefresh.lean
@@ -0,0 +1,178 @@
+import OAI.Computability.VPVNP.Compression
+import OAI.Computability.VPVNP.RegularArcGraph
+import OAI.Computability.VPVNP.GraphRounding
+
+/-!
+# Energy of the degree-restoring step
+
+Section 7.3 of *VP and VNP differ over every field* concatenates all the old
+wires over one base arc and replaces the segment ties in each block of ports
+by a term of a fixed expander motif. There are two internal ties per ordered
+pair of distinct ports. The external widths cost at most `d₀ L`; across all
+blocks the internal demands cost at most `2 L`. The comparison constant
+`2 γ d₀ / dH` for the metric motif is independent of the order of the block.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.DegreeRefresh
+
+open SpectralGeometry
+
+variable {B : Type*} [Fintype B] {D dH : ℕ}
+
+/-- The two copies distinguish the incoming and outgoing ties between ports. -/
+abbrev Tie (D : ℕ) := Bool × {q : Fin D × Fin D // q.1 ≠ q.2}
+
+/-- Old wires indexed in source-port order, before their concatenation. -/
+abbrev Widths (B : Type*) (D : ℕ) := (B × Fin D) → Fin D → ℕ
+
+/-- The width found at a destination block, incoming slot and destination port. -/
+def incoming (target : Equiv.Perm (B × Fin D)) (lane : B × Fin D → Equiv.Perm (Fin D))
+ (w : Widths B D) (e : B × Fin D) (j : Fin D) : ℕ :=
+ w (target.symm e) ((lane (target.symm e)).symm j)
+
+/-- In either direction the first port carries the old half-wire; the second
+is the designated slot at which its segment of the external wire is read. -/
+def tieWidth (target : Equiv.Perm (B × Fin D)) (lane : B × Fin D → Equiv.Perm (Fin D))
+ (w : Widths B D) (z : B) (t : Tie D) : ℕ :=
+ if t.1 then w (z,t.2.val.2) t.2.val.1 else incoming target lane w (z,t.2.val.2) t.2.val.1
+
+/-- Squared-width energy of the old network. -/
+noncomputable def oldEnergy (p : ℝ) (w : Widths B D) : ℝ :=
+ ∑ e, ∑ i, (w e i : ℝ) ^ 2 / p
+
+/-- Squared-width energy of the concatenated external payloads. -/
+noncomputable def externalEnergy (p' : ℝ) (w : Widths B D) : ℝ :=
+ ∑ e, ((∑ i, w e i : ℕ) : ℝ) ^ 2 / p'
+
+/-- The energy of the two sets of nonlocal segment ties in a block. -/
+noncomputable def demandEnergy (p : ℝ) (target : Equiv.Perm (B × Fin D))
+ (lane : B × Fin D → Equiv.Perm (Fin D)) (w : Widths B D) (z : B) : ℝ :=
+ ∑ t : Tie D, (tieWidth target lane w z t : ℝ) ^ 2 / p
+
+/-- Reindexing the old energy at its incoming half-wires counts every width once. -/
+theorem oldEnergy_incoming (target : Equiv.Perm (B × Fin D))
+ (lane : B × Fin D → Equiv.Perm (Fin D)) (w : Widths B D) (p : ℝ) :
+ oldEnergy p (incoming target lane w) = oldEnergy p w := by
+ unfold oldEnergy incoming
+ calc
+ _ = ∑ e, ∑ j, (w (target.symm e) j : ℝ) ^ 2 / p :=
+ Finset.sum_congr rfl fun e _ ↦ (lane (target.symm e)).symm.sum_comp _
+ _ = _ := target.symm.sum_comp (fun e ↦ ∑ i, (w e i : ℝ) ^ 2 / p)
+
+private theorem offDiagonal_le (f : Fin D × Fin D → ℝ) (hf : ∀ u, 0 ≤ f u) :
+ (∑ u : {q : Fin D × Fin D // q.1 ≠ q.2}, f u.val) ≤ ∑ q, f q := by
+ have h := Fintype.sum_subtype_add_sum_subtype (fun q : Fin D × Fin D ↦ q.1 ≠ q.2) f
+ exact (le_add_of_nonneg_right (Finset.sum_nonneg fun u _ ↦ hf u.val)).trans_eq h
+
+/-- All internal ties together cost at most the old energy counted twice. Ties
+at the same port are local and may be omitted even if their widths are positive. -/
+theorem demandEnergy_sum_le (target : Equiv.Perm (B × Fin D))
+ (lane : B × Fin D → Equiv.Perm (Fin D)) (w : Widths B D) {p : ℝ} (hp : 0 ≤ p) :
+ (∑ z, demandEnergy p target lane w z) ≤ 2 * oldEnergy p w := by
+ let total (z : B) (b : Widths B D) := ∑ j, ∑ i, (b (z,j) i : ℝ) ^ 2 / p
+ have hlocal (z : B) : demandEnergy p target lane w z ≤
+ total z w + total z (incoming target lane w) := by
+ have haux (b : Widths B D) : (∑ u : {q : Fin D × Fin D // q.1 ≠ q.2},
+ (b (z,u.val.2) u.val.1 : ℝ) ^ 2 / p) ≤ total z b := by
+ refine (offDiagonal_le (fun q ↦ (b (z,q.2) q.1 : ℝ) ^ 2 / p)
+ (fun _ ↦ div_nonneg (sq_nonneg _) hp)).trans_eq ?_
+ rw [Fintype.sum_prod_type, Finset.sum_comm]
+ simpa [demandEnergy, Fintype.sum_prod_type, Fintype.sum_bool, tieWidth] using
+ add_le_add (haux w) (haux (incoming target lane w))
+ have h := Finset.sum_le_sum (s := Finset.univ) fun z _ ↦ hlocal z
+ have htotal (b : Widths B D) : ∑ z, total z b = oldEnergy p b := by
+ rw [oldEnergy, Fintype.sum_prod_type]
+ rw [Finset.sum_add_distrib, htotal, htotal, oldEnergy_incoming, ← two_mul] at h
+ exact h
+
+/-- Cauchy–Schwarz bounds the external energy after concatenating the `D`
+segments of each bundle, using `D p = d₀ p'`. -/
+theorem externalEnergy_le (w : Widths B D) {p p' d₀ : ℝ}
+ (hp : 0 < p) (hp' : 0 < p') (hmass : (D : ℝ) * p = d₀ * p') :
+ externalEnergy p' w ≤ d₀ * oldEnergy p w := by
+ unfold externalEnergy oldEnergy
+ rw [Finset.mul_sum]
+ apply Finset.sum_le_sum
+ intro e _
+ have h := Finset.sum_mul_sq_le_sq_mul_sq Finset.univ (fun _ : Fin D ↦ (1 : ℝ)) (fun i ↦ (w e i : ℝ))
+ simp only [one_mul, one_pow, Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul,
+ mul_one] at h
+ rw [Nat.cast_sum]
+ apply (div_le_iff₀ hp').mpr
+ calc
+ _ ≤ (D : ℝ) * ∑ i, (w e i : ℝ) ^ 2 := h
+ _ = _ := by
+ simp only [div_eq_mul_inv, ← Finset.sum_mul]
+ field_simp [hp.ne']
+ linarith only [congrArg (fun z : ℝ ↦ z * ∑ i, (w e i : ℝ) ^ 2) hmass]
+
+private theorem offDiagonal_dist_eq {X : Type*} [PseudoMetricSpace X] (x : Fin D → X) :
+ (∑ u : {q : Fin D × Fin D // q.1 ≠ q.2}, dist (x u.val.1) (x u.val.2) ^ 2) =
+ ∑ u, ∑ v, dist (x u) (x v) ^ 2 := by
+ let f (q : Fin D × Fin D) := dist (x q.1) (x q.2) ^ 2
+ have hz : (∑ u : {q : Fin D × Fin D // ¬q.1 ≠ q.2}, f u.val) = 0 := by
+ apply Finset.sum_eq_zero
+ intro u _
+ simp [f, not_not.mp u.property]
+ have h := Fintype.sum_subtype_add_sum_subtype (fun q : Fin D × Fin D ↦ q.1 ≠ q.2) f
+ rw [hz, add_zero, Fintype.sum_prod_type] at h
+ exact h
+
+/-- The metric hypothesis of the expander motif in Section 7.3, with the actual
+directed arcs as supply and two copies of the off-diagonal as demand. -/
+theorem metric_comparison {X : Type*} [PseudoMetricSpace X]
+ (G : RegularArcGraph (Fin D) dH) {p p' d₀ γ : ℝ}
+ (hD : 0 < D) (hp : 0 ≤ p) (hmass : (D : ℝ) * p = d₀ * p')
+ (hbound : HasPoincareBound X (normalizeArcs G.multiplicity dH) γ) (x : Fin D → X) :
+ (∑ t : Tie D, p * dist (x t.2.val.1) (x t.2.val.2) ^ 2) ≤
+ (2 * γ * d₀ / dH) * ∑ e : Fin D × Fin dH, p' * dist (x e.1) (x (G.reverse e).1) ^ 2 := by
+ have hwalk : walkEnergy (normalizeArcs G.multiplicity dH) x =
+ (∑ e : Fin D × Fin dH, dist (x e.1) (x (G.reverse e).1) ^ 2) / dH := by
+ rw [G.sum_cost (fun a b ↦ dist (x a) (x b) ^ 2)]
+ simp only [walkEnergy, normalizeArcs, div_eq_mul_inv, Finset.sum_mul]
+ apply Finset.sum_congr rfl
+ intro u _
+ apply Finset.sum_congr rfl
+ intro v _
+ rw [dist_comm (x v) (x u)]
+ ring
+ have hD' : 0 < (D : ℝ) := Nat.cast_pos.mpr hD
+ have hb := hbound x
+ rw [Fintype.card_fin, hwalk] at hb
+ have h := mul_le_mul_of_nonneg_left ((div_le_iff₀ hD').mp hb) (mul_nonneg (by norm_num : (0 : ℝ) ≤ 2) hp)
+ rw [Fintype.sum_prod_type, Fintype.sum_bool]
+ simp only [← Finset.mul_sum, offDiagonal_dist_eq]
+ refine le_trans (le_of_eq (by ring)) (h.trans_eq ?_)
+ calc
+ _ = (2 * γ / (dH : ℝ)) * ((D : ℝ) * p) * ∑ e : Fin D × Fin dH, dist (x e.1) (x (G.reverse e).1) ^ 2 := by ring
+ _ = _ := by rw [hmass]; ring
+
+/-- Summing the termwise energy inequality of Theorem 6.1 over all blocks
+gives Equation (7.3). The additive term is exactly `C · P²` when the motif's
+scaled additive constant is `C` and `P = #blocks · D`. -/
+theorem refresh_energy_le (target : Equiv.Perm (B × Fin D))
+ (lane : B × Fin D → Equiv.Perm (Fin D)) (w : Widths B D) (supply : B → ℝ)
+ {p p' d₀ H' C : ℝ} (hp : 0 < p) (hp' : 0 < p') (hH : 0 ≤ H')
+ (hmass : (D : ℝ) * p = d₀ * p') (hold : 1 / p = (Fintype.card B : ℝ) * D * D)
+ (hterm : ∀ z, supply z ≤ H' * demandEnergy p target lane w z + C / p) :
+ externalEnergy p' w + ∑ z, supply z ≤
+ (d₀ + 2 * H') * oldEnergy p w + C * ((Fintype.card B : ℝ) * D) ^ 2 := by
+ have hs := Finset.sum_le_sum (s := Finset.univ) fun z _ ↦ hterm z
+ simp only [Finset.sum_add_distrib, ← Finset.mul_sum, Finset.sum_const, Finset.card_univ,
+ nsmul_eq_mul] at hs
+ have hinc := mul_le_mul_of_nonneg_left (demandEnergy_sum_le target lane w hp.le) hH
+ have hconst : (Fintype.card B : ℝ) * (C / p) = C * ((Fintype.card B : ℝ) * D) ^ 2 := by
+ rw [show C / p = C * (1 / p) by ring, hold]
+ ring
+ rw [hconst] at hs
+ linarith only [externalEnergy_le w hp hp' hmass, hs, hinc]
+
+end Compression.DegreeRefresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshActualStep.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshActualStep.lean
new file mode 100644
index 0000000000..fe53e49227
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshActualStep.lean
@@ -0,0 +1,186 @@
+import OAI.Computability.VPVNP.DegreeRefreshStep
+import OAI.Computability.VPVNP.DegreeRefreshPayloads
+import OAI.Computability.VPVNP.DegreeRefreshPorts
+import OAI.Computability.VPVNP.NetworkIso
+
+/-!
+# The degree refresh on the actual lifted slots
+
+The blockwise contraction uses source-port order within each bundle. The
+isomorphisms below restore the original and refreshed slot coordinates,
+including their lane translations, without identifying parallel arcs. The
+actual widths are those charged to equation (7.3).
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped Classical
+
+namespace Compression.Refresh
+
+open NetworkKernel
+
+variable {V H L : Type} {D dH d₀ : ℕ}
+
+/-- The word network on a lifted graph. Its edges are actual outgoing slots,
+and widths are indexed by a base arc and source lane. -/
+noncomputable def actualWireGraph {U K : Type} [Fintype U] [Fintype K] [AddCommGroup K]
+ {d : ℕ} (G : LiftedSlots U d K) (w : (U × Fin d) × K → ℕ) : Network where
+ Site := U × K
+ siteFintype := inferInstance
+ Edge := (U × K) × Fin d
+ edgeFintype := inferInstance
+ src := Prod.fst
+ dst e := (G.actualGraph.target e).1
+ Payload e := Word (w ((e.1.1,e.2),e.1.2))
+ payloadFintype _ := inferInstance
+
+/-- Old positions in bundle coordinates have their original port as the
+last component, separate from the remaining lane. -/
+def originalSites (port : H ≃ Fin D) : (V × L) × Fin D ≃ V × (H × L) where
+ toFun p := (p.1.1,port.symm p.2,p.1.2)
+ invFun p := ((p.1,p.2.2),port p.2.1)
+ left_inv _ := by simp
+ right_inv _ := by simp
+
+/-- Restore the outgoing slot number and the source lane of an individual
+old segment. -/
+def originalEdges (port : H ≃ Fin D) : Arc (V × L) D ≃ (V × (H × L)) × Fin D where
+ toFun p := (originalSites port (source p),p.1.2)
+ invFun p := (((p.1.1,p.1.2.2),p.2),port p.1.2.1)
+ left_inv _ := by simp [originalSites, source]
+ right_inv _ := by simp [originalSites, source]
+
+/-- The regrouped old width is exactly the field carried by the original
+arc in its original lane. -/
+abbrev groupedWidths (port : H ≃ Fin D) (w : (V × Fin D) × (H × L) → ℕ) :
+ Arc (V × L) D → ℕ := Function.uncurry (DegreeRefresh.bundleWidths port w)
+
+variable [Fintype V] [Fintype H] [Fintype L] [AddCommGroup H] [AddCommGroup L]
+ (G : LiftedSlots V D (H × L)) (port : H ≃ Fin D) (w : (V × Fin D) × (H × L) → ℕ)
+
+/-- Reindex the old wire tensor by its actual directed slots. Both endpoint
+maps and the full alphabet on every arc are preserved. -/
+noncomputable def originalIso :
+ Network.Iso (oldWireGraph (oldPortMatching G port) (groupedWidths port w))
+ (actualWireGraph G w) where
+ site := originalSites port
+ edge := originalEdges port
+ src _ := rfl
+ dst := by
+ rintro ⟨⟨⟨v,l⟩,i⟩,j⟩
+ change originalSites port (source (oldPortMatching G port (((v,l),i),j))) = _
+ rw [oldPortMatching_apply]
+ simp [originalSites, source, actualWireGraph, originalEdges]
+ rfl
+ payload _ := Equiv.refl _
+
+/-- Promote the port to part of the new base vertex while retaining the
+remaining lane. -/
+def promotedSites : (V × L) × Fin D ≃ (V × Fin D) × L where
+ toFun p := ((p.1.1,p.2),p.1.2)
+ invFun p := ((p.1.1,p.2),p.1.2)
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+private def outputClasses :
+ OutputEdge (V × L) (Fin D × Fin dH) D (d₀ - (dH + 1)) ≃
+ ((V × L) × Fin D) × RefreshSlot dH d₀ where
+ toFun
+ | .inl p => (p,.inl 0)
+ | .inr (.inl (s,j,h)) => ((s,j),.inr (.inl h))
+ | .inr (.inr (p,h)) => (p,.inr (.inr h))
+ invFun
+ | (p,.inl _) => .inl p
+ | ((s,j),.inr (.inl h)) => .inr (.inl (s,j,h))
+ | (p,.inr (.inr h)) => .inr (.inr (p,h))
+ left_inv e := by rcases e with p | ⟨s,j,h⟩ | ⟨p,h⟩ <;> rfl
+ right_inv p := by
+ rcases p with ⟨p,h | h | h⟩
+ · cases Subsingleton.elim h 0
+ rfl
+ · rfl
+ · rfl
+
+/-- All copies of the grouped external, expander and cyclic padding arcs
+biject with the numbered outgoing slots of the refreshed graph. -/
+def promotedEdges (hd : dH + 1 ≤ d₀) :
+ OutputEdge (V × L) (Fin D × Fin dH) D (d₀ - (dH + 1)) ≃ ActualArc V L D d₀ :=
+ outputClasses.trans (arcCoordinates hd).symm
+
+variable (P : SlotGraph (Fin D) dH) (hD : 1 < D) (hd : dH + 1 ≤ d₀)
+
+/-- The grouped output is isomorphic to the actual lifted graph with the
+widths charged in (7.3). The selected motif may use any alphabet with the
+specified word encoding at each expander slot. -/
+noncomputable def promotedIso (A : (V × L) → Fin D × Fin dH → Type)
+ [∀ s e, Fintype (A s e)] (internal : (V × L) → Fin D × Fin dH → ℕ)
+ (encode : ∀ s e, A s e ≃ Word (internal s e)) :
+ Network.Iso
+ (refreshOutput (bundleTarget G) (groupedWidths port w) Prod.fst (fun e ↦ (P.target e).1)
+ A (d₀ - (dH + 1)))
+ (actualWireGraph (degreeRefresh G P hD hd) (DegreeRefresh.actualWidths hd port w internal)) where
+ site := promotedSites
+ edge := promotedEdges hd
+ src e := by rcases e with p | ⟨s,j,k⟩ | ⟨p,k⟩ <;> rfl
+ dst := by
+ rintro (⟨⟨v,l⟩,j⟩ | ⟨⟨v,l⟩,j,k⟩ | ⟨⟨⟨v,l⟩,j⟩,k⟩)
+ · exact congrArg Prod.fst (degreeRefresh_external G P hD hd (v,j) l).symm
+ · exact congrArg Prod.fst (degreeRefresh_internal G P hD hd v j l k).symm
+ · exact congrArg Prod.fst (degreeRefresh_padding G P hD hd v j l k).symm
+ payload := by
+ rintro (p | ⟨s,j,k⟩ | ⟨p,k⟩)
+ · change Word (∑ j, groupedWidths port w (p,j)) ≃
+ Word (DegreeRefresh.newWidths hd (DegreeRefresh.bundleWidths port w) internal p
+ (refreshSlots hd (.inl 0)))
+ simpa [DegreeRefresh.newWidths] using Equiv.refl (Word (∑ j, groupedWidths port w (p,j)))
+ · change A s (j,k) ≃ Word (DegreeRefresh.newWidths hd (DegreeRefresh.bundleWidths port w)
+ internal (s,j) (refreshSlots hd (.inr (.inl k))))
+ simpa [DegreeRefresh.newWidths] using encode s (j,k)
+ · change Word 0 ≃ Word (DegreeRefresh.newWidths hd (DegreeRefresh.bundleWidths port w)
+ internal p (refreshSlots hd (.inr (.inr k))))
+ simpa [DegreeRefresh.newWidths] using Equiv.refl (Word 0)
+
+open WireTensor
+
+variable {R : Type*} [CommSemiring R] {I : (V × L) → Type} [∀ s, Fintype (I s)]
+ (A : (s : V × L) → I s → Fin D × Fin dH → Type) [∀ s i e, Fintype (A s i e)]
+ (internal : (s : V × L) → I s → Fin D × Fin dH → ℕ)
+ (encode : ∀ s i e, A s i e ≃ Word (internal s i e))
+ (M : ∀ s (i : I s) j, (internalDemand R (oldPortMatching G port) (groupedWidths port w) s).Basis j →
+ (blockSupply (R := R) Prod.fst (fun e ↦ (P.target e).1) A s i).Basis j → R)
+ (h : ∀ s, (internalDemand R (oldPortMatching G port) (groupedWidths port w) s).coeff =
+ ∑ i, applyLocal (M s i) (blockSupply (R := R) Prod.fst (fun e ↦ (P.target e).1) A s i).coeff)
+
+/-- The exact degree-refresh step on actual slot coordinates, with one
+motif choice per block and the selected word widths on the refreshed graph. -/
+noncomputable def actualRefreshStep : Step R (actualWireGraph G w) :=
+ let step := refreshStep (bundleTarget G) (groupedWidths port w) Prod.fst
+ (fun e ↦ (P.target e).1) (d₀ - (dH + 1)) (oldPortMatching G port)
+ (oldPortMatching_bundle G port) A M h
+ step.reindex (originalIso G port w)
+ (out := fun c ↦ actualWireGraph (degreeRefresh G P hD hd)
+ (DegreeRefresh.actualWidths hd port w (fun s ↦ internal s (c s))))
+ (fun c ↦ promotedIso G port w P hD hd (fun s ↦ A s (c s)) (fun s ↦ internal s (c s))
+ (fun s ↦ encode s (c s)))
+
+/-- In each branch the output network uses the stated refreshed slot graph
+and its corresponding actual widths. -/
+theorem actualRefreshStep_output (c : (s : V × L) → I s) :
+ ((actualRefreshStep G port w P hD hd A internal encode M h).term c).output =
+ actualWireGraph (degreeRefresh G P hD hd)
+ (DegreeRefresh.actualWidths hd port w (fun s ↦ internal s (c s))) := rfl
+
+/-- Each original vertex factor stays whole at the same physical position
+after promoting its port to a base label. -/
+theorem actualRefreshStep_place (c : (s : V × L) → I s) (x : V × (H × L)) :
+ ((actualRefreshStep G port w P hD hd A internal encode M h).term c).place x =
+ refreshPositions port x := rfl
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshConversion.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshConversion.lean
new file mode 100644
index 0000000000..1efeeb06e4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshConversion.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.DegreeRefreshActualStep
+import OAI.Computability.VPVNP.DegreeRefreshPorts
+import OAI.Computability.VPVNP.DegreeRefreshSupply
+import OAI.Computability.VPVNP.ExpanderSlots
+import OAI.Computability.VPVNP.MotifConversion
+
+/-!
+# Exact degree refresh from a spectral expander
+
+The expander and the field determine the finite equations of the port
+motif before any old graph or widths are specified. Any solution of these
+equations over a commutative ring gives the exact degree refresh (7.1).
+Each block chooses an admitted payload profile from Theorem 6.1. Its
+internal slots carry the profile widths together with the selector bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.Refresh
+
+open MotifGrid MotifBlocks MotifConversion SpectralGeometry NetworkKernel WireTensor DegreeRefresh
+
+variable {k : Type*} [Field k] {D dH d₀ : ℕ} {γ K K' : ℝ}
+
+/-- A single finite system of integer equations has a solution over the
+field of the spectral port bound. The system is independent of the old
+network and its widths. -/
+theorem exists_expander_parameters (G : RegularArcGraph (Fin D) dH) (hdH : 0 < dH)
+ (hD : 2 ≤ D) (hd₀ : 0 < d₀) (hP : SpectralPortBound k G γ) :
+ let P := expanderSupply G hdH (hP.connected_and_pos hD).1
+ let K := 2 * γ * d₀ / dH
+ ∃ F : FixedBlock k tieSource tieTarget P (realWidths tieMass) (realWidths (expanderMass d₀)) K (K + 1),
+ ∃ κ : (parameterData F).Entry → k, (parameterData F).IsSolution κ := by
+ obtain ⟨F⟩ := exists_expander_block G hdH hD hd₀ hP
+ exact ⟨F, exists_solution F⟩
+
+variable {V E L : Type} [Fintype V] [Fintype E] [Fintype L] [AddCommGroup E] [AddCommGroup L]
+ (G : LiftedSlots V D (E × L)) (port : E ≃ Fin D) (w : (V × Fin D) × (E × L) → ℕ)
+
+/-- The widths of the two copies of nonlocal segment ties read in each block. -/
+abbrev blockDemandWidths := internalWidth (oldPortMatching G port) (groupedWidths port w)
+
+omit [Fintype V] [Fintype E] [Fintype L] in
+theorem blockDemandWidths_eq : blockDemandWidths G port w =
+ tieWidth (bundleTarget G) (bundlePort G port) (bundleWidths port w) := by
+ funext s e
+ exact internalWidth_eq_tieWidth G port _ s e
+
+variable (P : RegularArcGraph (Fin D) dH) (hdH : 0 < dH)
+ (hconn : (arcSupportGraph P.multiplicity).Connected)
+ (F : FixedBlock k tieSource tieTarget (expanderSupply P hdH hconn)
+ (realWidths tieMass) (realWidths (expanderMass d₀)) K K')
+
+/-- Independent admitted payload profiles in the blocks of a network. -/
+noncomputable abbrev BlockChoices :=
+ (s : V × L) → ↥(outerIndices F (blockDemandWidths G port w s))
+
+/-- Every internal edge carries its admitted payload and one selector per
+base-identity repetition. -/
+noncomputable abbrev blockSupplyWidths (c : BlockChoices G port w P hdH hconn F) :=
+ fun s ↦ supplyWidths F (blockDemandWidths G port w s) (c s).val
+
+variable {R : Type*} [CommRing R] (κ : (parameterData F).Entry → R)
+ (hκ : (parameterData F).IsSolution κ) (hD : 1 < D) (hd : dH + 1 ≤ d₀)
+
+/-- Evaluate the fixed equations' local maps on the old graph and use the
+actual slots of the refreshed graph for the resulting kernel. -/
+noncomputable def expanderRefreshStep : Step R (actualWireGraph G w) := by
+ let : Nonempty (Fin D) := ⟨⟨0, by omega⟩⟩
+ let b := blockDemandWidths G port w
+ let I (s : V × L) := ↥(outerIndices F (b s))
+ let u (s : V × L) (i : I s) := supplyWidths F (b s) i.val
+ let A (s : V × L) (i : I s) (e : Fin D × Fin dH) := Fin (2 ^ u s i e)
+ have hp (i : Tie D) : 0 < tieMass i := zero_lt_one
+ have hq (e : Fin D × Fin dH) : 0 < expanderMass d₀ e := by
+ unfold expanderMass
+ exact div_pos (Nat.cast_pos.mpr (by omega)) (Nat.cast_pos.mpr (by omega))
+ let M (s : V × L) (i : I s) (j : Fin D) :=
+ fun x y ↦ evalEntry κ (entry F hp (b s) i.val j x y)
+ apply actualRefreshStep G port w P.toSlotGraph hD hd A u (fun s i e ↦ (wordIndex (u s i e)).symm) M
+ intro s
+ exact (identity F κ hκ hp hq (b s)).trans (Finset.sum_coe_sort _ _).symm
+
+/-- The branches of the spectral refresh use the arc widths of the admitted
+motif terms, in the regular graph's specified slot numbering. -/
+theorem expanderRefreshStep_output (c : BlockChoices G port w P hdH hconn F) :
+ ((expanderRefreshStep G port w P hdH hconn F κ hκ hD hd).term c).output =
+ actualWireGraph (degreeRefresh G P.toSlotGraph hD hd)
+ (actualWidths hd port w (blockSupplyWidths G port w P hdH hconn F c)) := rfl
+
+/-- The old vertex factor stays at its physical position in every branch. -/
+theorem expanderRefreshStep_place (c : BlockChoices G port w P hdH hconn F) (x : V × (E × L)) :
+ ((expanderRefreshStep G port w P hdH hconn F κ hκ hD hd).term c).place x =
+ refreshPositions port x := rfl
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshCosts.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshCosts.lean
new file mode 100644
index 0000000000..1f0221986f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshCosts.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.DegreeRefreshConversion
+import OAI.Computability.VPVNP.DegreeRefreshWidths
+
+/-!
+# Cost of each admitted expander-motif term
+
+Apply the fixed block of Theorem 6.1 with unit mass on each internal tie
+and mass `D / d₀` on each expander arc. A payload is admitted by its weighted
+norm. Its wire carries both that payload and the common list of selectors.
+The same padded widths are used in the actual slots for the energy bound and
+the maximum-width bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.DegreeRefresh
+
+open MotifBlocks MotifGrid MotifConversion
+
+variable {D dH d₀ : ℕ} {k : Type*} [Field k]
+variable {P : MotifSelector.Supply (Fin D) (Fin D × Fin dH)} {H H' : ℝ}
+
+/-- Fixed motif block converting refresh tie wires into the specified supply on the port graph. -/
+abbrev RefreshBlock (k : Type*) [Field k] (P : MotifSelector.Supply (Fin D) (Fin D × Fin dH))
+ (d₀ : ℕ) (H H' : ℝ) :=
+ FixedBlock k Refresh.tieSource Refresh.tieTarget P (realWidths Refresh.tieMass)
+ (realWidths (Refresh.expanderMass d₀)) H H'
+
+variable (F : RefreshBlock k P d₀ H H')
+
+/-- Convert the executable admission condition on the outer payload into the
+normalized termwise energy inequality needed in the refresh. -/
+theorem termWidths_energy (hD : 0 < D) (hd₀ : 0 < d₀) (b : Tie D → ℕ)
+ (v : Fin D × Fin dH → ℕ) (hadmit : v ∈ outerIndices F b) :
+ (∑ e, (supplyWidths F b v e : ℝ) ^ 2 / ((D : ℝ) / d₀)) ≤
+ H' * (∑ t, (b t : ℝ) ^ 2) + F.energyConstant := by
+ have hp (t : Tie D) : 0 < Refresh.tieMass t := zero_lt_one
+ have hq (e : Fin D × Fin dH) : 0 < Refresh.expanderMass d₀ e :=
+ div_pos (Nat.cast_pos.mpr hD) (Nat.cast_pos.mpr hd₀)
+ have h := energy_le F hp hq b v hadmit
+ rw [norm_sq (realWidths (Refresh.expanderMass d₀)) _ (fun e ↦ Rat.cast_pos.mpr (hq e)),
+ norm_sq (realWidths Refresh.tieMass) _ (fun t ↦ Rat.cast_pos.mpr (hp t))] at h
+ simpa only [realWidths, Refresh.tieMass, Refresh.expanderMass, Rat.cast_one, div_one,
+ Rat.cast_div, Rat.cast_natCast] using h
+
+/-- A surviving motif entry uses one scalar parameter per block repetition.
+This number is bounded linearly in the maximum old width for a fixed port count. -/
+theorem term_repetitions_le (b : Tie D → ℕ) {W : ℕ} (hw : ∀ t, b t ≤ W) :
+ repetitions F b ≤ Fintype.card (Tie D) * W := by
+ rw [repetitions_eq F (fun _ ↦ zero_lt_one)]
+ unfold FixedBlock.repetitions MotifWidths.copies
+ rw [Nat.ceil_le, div_le_iff₀ (Nat.cast_pos.mpr F.scale_pos)]
+ have hN : widthNorm (realWidths Refresh.tieMass) (fun t ↦ (b t : ℝ)) ≤
+ (Fintype.card (Tie D) : ℝ) * W := by
+ unfold widthNorm
+ apply Real.sqrt_le_iff.mpr
+ refine ⟨by positivity, ?_⟩
+ simp only [realWidths, Refresh.tieMass, Rat.cast_one, div_one, mul_pow]
+ have hs := Finset.sum_le_sum (s := Finset.univ) fun t _ ↦
+ pow_le_pow_left₀ (Nat.cast_nonneg (α := ℝ) (b t)) (Nat.cast_le.mpr (hw t)) 2
+ simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul] at hs
+ exact hs.trans (mul_le_mul_of_nonneg_right
+ (by exact_mod_cast Nat.le_pow (by decide : 0 < 2) : (Fintype.card (Tie D) : ℝ) ≤ _)
+ (sq_nonneg _))
+ rw [Nat.cast_mul]
+ exact hN.trans (le_mul_of_one_le_right (by positivity) (by exact_mod_cast F.scale_pos))
+
+variable {V E L : Type*} [Fintype V] [Fintype E] [Fintype L]
+ [AddCommGroup E] [AddCommGroup L]
+
+/-- Equation (7.3) for each admitted collection of expander payloads,
+with the selector bits included on every internal supply arc. -/
+theorem admitted_actual_energy [Nonempty V] [Nonempty L] (G : LiftedSlots V D (E × L))
+ (port : E ≃ Fin D) (hd : dH + 1 ≤ d₀) (hD : 0 < D) (hH' : 0 ≤ H')
+ (w : (V × Fin D) × (E × L) → ℕ) (v : V × L → Fin D × Fin dH → ℕ)
+ (hadmit : ∀ z, v z ∈ outerIndices F
+ (tieWidth (bundleTarget G) (bundlePort G port) (bundleWidths port w) z)) :
+ let n := (Fintype.card (V × (E × L)) : ℝ)
+ let b := tieWidth (bundleTarget G) (bundlePort G port) (bundleWidths port w)
+ let s := fun z ↦ supplyWidths F (b z) (v z)
+ (∑ a, (actualWidths hd port w s a : ℝ) ^ 2 / (1 / (n * d₀))) ≤
+ (d₀ + 2 * H') * (∑ a, (w a : ℝ) ^ 2 / (1 / (n * D))) + F.energyConstant * n ^ 2 := by
+ exact actualWidths_energy_le G port hd hD w _ hH' fun z ↦
+ termWidths_energy F hD (by omega) _ _ (hadmit z)
+
+omit [Fintype V] [Fintype E] [Fintype L] in
+/-- For every admitted collection of block choices the same bound on field
+lengths works at all the actual slots, independently of the old graph and lanes. -/
+theorem admitted_actual_width (G : LiftedSlots V D (E × L)) (port : E ≃ Fin D)
+ (hd : dH + 1 ≤ d₀) (hD : 0 < D) (hH' : 0 ≤ H')
+ (w : (V × Fin D) × (E × L) → ℕ) (v : V × L → Fin D × Fin dH → ℕ)
+ (hadmit : ∀ z, v z ∈ outerIndices F
+ (tieWidth (bundleTarget G) (bundlePort G port) (bundleWidths port w) z)) {W : ℕ} (hw : ∀ a, w a ≤ W) (a : ((V × Fin D) × Fin d₀) × L) :
+ let b := tieWidth (bundleTarget G) (bundlePort G port) (bundleWidths port w)
+ let s := fun z ↦ supplyWidths F (b z) (v z)
+ (actualWidths hd port w s a : ℝ) ≤
+ max (D : ℝ) (Real.sqrt (((D : ℝ) / d₀) *
+ (H' * Fintype.card (Tie D) + max 0 F.energyConstant))) * (W + 1) := by
+ apply newWidths_max_le hd hD (bundleTarget G) (bundlePort G port) _ _ hH' (le_max_left _ _)
+ (fun z ↦ (termWidths_energy F hD (by omega) _ _ (hadmit z)).trans
+ (add_le_add_right (le_max_right 0 F.energyConstant) _))
+ exact fun _ _ ↦ hw _
+
+end Compression.DegreeRefresh
+
+namespace Compression.Refresh
+
+open DegreeRefresh SpectralGeometry
+
+variable {k : Type*} [Field k] {D dH d₀ : ℕ} {K K' : ℝ}
+variable {V E L : Type} [Fintype V] [Fintype E] [Fintype L] [AddCommGroup E] [AddCommGroup L]
+ (G : LiftedSlots V D (E × L)) (port : E ≃ Fin D) (w : (V × Fin D) × (E × L) → ℕ)
+ (P : RegularArcGraph (Fin D) dH) (hdH : 0 < dH) (hconn : (arcSupportGraph P.multiplicity).Connected)
+ (F : RefreshBlock k (expanderSupply P hdH hconn) d₀ K K') (hD : 1 < D) (hd : dH + 1 ≤ d₀)
+
+include hD
+
+/-- Equation (7.3) for every branch of `expanderRefreshStep`. In the block
+chosen by `exists_expander_parameters`, the coefficient `K'` equals
+`2 * γ * d₀ / dH + 1`, so the leading coefficient is uniform over port counts. -/
+theorem expander_branch_energy_le [Nonempty V] [Nonempty L] (hK' : 0 ≤ K')
+ (c : BlockChoices G port w P hdH hconn F) :
+ let n := (Fintype.card (V × (E × L)) : ℝ)
+ (∑ a, (actualWidths hd port w (blockSupplyWidths G port w P hdH hconn F c) a : ℝ) ^ 2 /
+ (1 / (n * d₀))) ≤
+ (d₀ + 2 * K') * (∑ a, (w a : ℝ) ^ 2 / (1 / (n * D))) + F.energyConstant * n ^ 2 := by
+ have ha (z : V × L) := (c z).property
+ simp only [blockDemandWidths_eq] at ha
+ have he : blockSupplyWidths G port w P hdH hconn F c = fun z ↦ MotifConversion.supplyWidths F
+ (tieWidth (bundleTarget G) (bundlePort G port) (bundleWidths port w) z) (c z).val := by
+ funext z
+ exact congrArg (fun b ↦ MotifConversion.supplyWidths F b (c z).val)
+ (congrFun (blockDemandWidths_eq G port w) z)
+ rw [he]
+ exact
+ admitted_actual_energy F G port hd (by omega) hK' w (fun z ↦ (c z).val) ha
+
+omit [Fintype V] [Fintype E] [Fintype L] in
+/-- All external, internal and padding widths in an admitted branch of
+`expanderRefreshStep` obey the same linear bound in the largest old field. -/
+theorem expander_branch_width_le (hK' : 0 ≤ K') (c : BlockChoices G port w P hdH hconn F)
+ {W : ℕ} (hw : ∀ a, w a ≤ W) (a : ((V × Fin D) × Fin d₀) × L) :
+ (actualWidths hd port w (blockSupplyWidths G port w P hdH hconn F c) a : ℝ) ≤
+ max (D : ℝ) (Real.sqrt (((D : ℝ) / d₀) *
+ (K' * Fintype.card (Tie D) + max 0 F.energyConstant))) * (W + 1) := by
+ have ha (z : V × L) := (c z).property
+ simp only [blockDemandWidths_eq] at ha
+ have he : blockSupplyWidths G port w P hdH hconn F c = fun z ↦ MotifConversion.supplyWidths F
+ (tieWidth (bundleTarget G) (bundlePort G port) (bundleWidths port w) z) (c z).val := by
+ funext z
+ exact congrArg (fun b ↦ MotifConversion.supplyWidths F b (c z).val)
+ (congrFun (blockDemandWidths_eq G port w) z)
+ rw [he]
+ exact
+ admitted_actual_width F G port hd (by omega) hK' w (fun z ↦ (c z).val) ha hw a
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshEntries.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshEntries.lean
new file mode 100644
index 0000000000..6fedfe7495
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshEntries.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.DegreeRefreshCosts
+import OAI.Computability.VPVNP.MotifEntryWitness
+
+/-!
+# Scalar entries in an actual degree-refresh branch
+
+After the old and new incident indices have been fixed, the port first
+tests its two diagonal ties. Passing these tests leaves the single
+parameter list of the selected motif entry. The description uses only
+the wire indices, and its polynomial can be evaluated at any solution
+of the fixed equations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped Classical
+
+namespace Compression.Refresh
+
+open MotifGrid MotifBlocks MotifConversion SpectralGeometry NetworkKernel WireTensor DegreeRefresh
+
+variable {k : Type*} [Field k] {D dH d₀ : ℕ} {K K' : ℝ}
+ {V E L : Type} [Fintype V] [Fintype E] [Fintype L] [AddCommGroup E] [AddCommGroup L]
+ (G : LiftedSlots V D (E × L)) (port : E ≃ Fin D) (w : (V × Fin D) × (E × L) → ℕ)
+ (P : RegularArcGraph (Fin D) dH) (hdH : 0 < dH) (hconn : (arcSupportGraph P.multiplicity).Connected)
+ (F : FixedBlock k tieSource tieTarget (expanderSupply P hdH hconn)
+ (realWidths tieMass) (realWidths (expanderMass d₀)) K K')
+ (hD : 1 < D) (hd : dH + 1 ≤ d₀) (c : BlockChoices G port w P hdH hconn F)
+
+/-- The output network and its half-wires depend only on the branch's selected widths. -/
+noncomputable abbrev expanderBranchGraph :=
+ actualWireGraph (degreeRefresh G P.toSlotGraph hD hd)
+ (actualWidths hd port w (blockSupplyWidths G port w P hdH hconn F c))
+
+omit [Fintype V] [Fintype E] [Fintype L] [AddCommGroup E] [AddCommGroup L] in
+private theorem promoted_original (p : (V × L) × Fin D) :
+ promotedSites p = refreshPositions port (originalSites port p) := by
+ simp [promotedSites, originalSites, refreshPositions]
+
+/-- The common scalar indices for one local kernel, after checking the two
+diagonal segment equalities. The site is given in block and port coordinates. -/
+noncomputable def refreshEntryIndices (p : (V × L) × Fin D)
+ (a : Placed (refreshPositions port) (actualWireGraph G w).Half (promotedSites p))
+ (z : (expanderBranchGraph G port w P hdH hconn F hD hd c).Half (promotedSites p)) :
+ Option (Fin (repetitions F (blockDemandWidths G port w p.1)) → (parameterData F).Entry) := by
+ let t := oldPortMatching G port
+ let widths := groupedWidths port w
+ let dst := bundleTarget G
+ let n := blockSupplyWidths G port w P hdH hconn F c
+ let A := fun s e ↦ Fin (2 ^ n s e)
+ let old := originalIso G port w
+ let new := promotedIso G port w P.toSlotGraph hD hd A n (fun s e ↦ (wordIndex (n s e)).symm)
+ let x := old.pullHalf p (a (originalSites port p) (promoted_original port p))
+ let u := new.pullHalf p z
+ let seg := incidentPortSegments t dst (oldPortMatching_bundle G port) widths p
+ (u.1 (.inl p) rfl) (u.2 (.inl (dst.symm p)) (dst.apply_symm_apply p).symm)
+ let y := supplyHalf (R := ℤ) dst widths Prod.fst (fun e ↦ (P.reverse e).1) A (d₀ - (dH + 1)) p u
+ exact if x.1 ((p.1,p.2),p.2) rfl = seg.1 p.2 ∧
+ seg.2 p.2 = incomingHalf (R := ℤ) t widths p.1 p.2 p.2 x then
+ entry F (fun _ ↦ zero_lt_one) (blockDemandWidths G port w p.1) (c p.1).val p.2
+ (portInput (R := ℤ) t widths p.1 p.2 x seg) y
+ else none
+
+private theorem eval_checked {Label A : Type*} [CommRing A] {m : ℕ}
+ (κ : Label → A) (indices : Option (Fin m → Label)) (a b : Prop) [Decidable a] [Decidable b] :
+ (if a then 1 else 0) * (if b then 1 else 0) * evalEntry κ indices =
+ evalEntry κ (if a ∧ b then indices else none) := by
+ by_cases ha : a <;> by_cases hb : b <;> simp [ha, hb, evalEntry]
+
+/-- Reading the common indices and multiplying the selected scalars gives
+the actual kernel coefficient over any ring satisfying the equations. -/
+theorem refreshEntryIndices_spec (p : (V × L) × Fin D)
+ (a : Placed (refreshPositions port) (actualWireGraph G w).Half (promotedSites p))
+ (z : (expanderBranchGraph G port w P hdH hconn F hD hd c).Half (promotedSites p))
+ {R : Type*} [CommRing R] (κ : (parameterData F).Entry → R) (hκ : (parameterData F).IsSolution κ) :
+ ((expanderRefreshStep G port w P hdH hconn F κ hκ hD hd).term c).kernel (promotedSites p) a z =
+ evalEntry κ (refreshEntryIndices G port w P hdH hconn F hD hd c p a z) := by
+ simp only [expanderRefreshStep, actualRefreshStep, Step.reindex, Term.reindex, promotedIso,
+ refreshStep, refreshTerm, refreshFactor, portDiagonal,
+ segmentTest, refreshEntryIndices]
+ erw [Equiv.piCongrLeft_apply_apply]
+ rw [eval_checked]
+ congr 1
+ apply ite_congr <;> intros <;> rfl
+
+/-- The integral entry polynomial is either zero or a monomial of coefficient
+one and degree at most the number of copies used by this block. -/
+theorem refreshEntryIndices_monomial (p : (V × L) × Fin D)
+ (a : Placed (refreshPositions port) (actualWireGraph G w).Half (promotedSites p))
+ (z : (expanderBranchGraph G port w P hdH hconn F hD hd c).Half (promotedSites p)) :
+ let poly := evalEntry (MvPolynomial.X (R := ℤ)) (refreshEntryIndices G port w P hdH hconn F hD hd c p a z)
+ (poly = 0 ∨ ∃ f, poly = MvPolynomial.monomial f 1) ∧
+ poly.totalDegree ≤ repetitions F (blockDemandWidths G port w p.1) := by
+ cases h : refreshEntryIndices G port w P hdH hconn F hD hd c p a z with
+ | none => simp [evalEntry]
+ | some i => exact ⟨Or.inr ⟨_, MotifParameters.prod_entries_eq_monomial i⟩,
+ MotifParameters.prod_entries_degree_le i⟩
+
+/-- A kernel entry witness at an actual port. A failed list has no witnesses,
+and a successful list gives one witness independently of the scalar values. -/
+noncomputable def expanderKernelWitness {R : Type*} [CommRing R]
+ [Fintype (parameterData F).Entry] (κ : (parameterData F).Entry → R)
+ (hκ : (parameterData F).IsSolution κ) (v : (V × Fin D) × L)
+ (a : Placed (refreshPositions port) (actualWireGraph G w).Half v)
+ (z : (expanderBranchGraph G port w P hdH hconn F hD hd c).Half v) :
+ MonomialWitness κ (((expanderRefreshStep G port w P hdH hconn F κ hκ hD hd).term c).kernel v a z) :=
+ let p := promotedSites.symm v
+ (entryWitness κ (refreshEntryIndices G port w P hdH hconn F hD hd c p a z)).changeValue
+ (refreshEntryIndices_spec G port w P hdH hconn F hD hd c p a z κ hκ).symm
+
+/-- For every surviving witness the total multiplicity is bounded linearly
+in the maximum old width, uniformly over all networks of this fixed degree. -/
+theorem expanderKernelWitness_exponents {R : Type*} [CommRing R]
+ [Fintype (parameterData F).Entry] (κ : (parameterData F).Entry → R)
+ (hκ : (parameterData F).IsSolution κ) (v : (V × Fin D) × L)
+ (a : Placed (refreshPositions port) (actualWireGraph G w).Half v)
+ (z : (expanderBranchGraph G port w P hdH hconn F hD hd c).Half v)
+ (b : (expanderKernelWitness G port w P hdH hconn F hD hd c κ hκ v a z).Choice)
+ {W : ℕ} (hw : ∀ e, w e ≤ W) :
+ (∑ l, (expanderKernelWitness G port w P hdH hconn F hD hd c κ hκ v a z).exponents b l) ≤
+ Fintype.card (Tie D) * W := by
+ let p := promotedSites.symm v
+ refine (entryWitness_totalExponent κ
+ (refreshEntryIndices G port w P hdH hconn F hD hd c p a z) b).le.trans ?_
+ apply term_repetitions_le F
+ intro e
+ unfold blockDemandWidths internalWidth
+ split_ifs <;> exact hw _
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshExpansion.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshExpansion.lean
new file mode 100644
index 0000000000..7f9cf93f5a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshExpansion.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.DegreeRefreshMotif
+
+/-!
+# Expanding all degree-refresh motifs
+
+Each block independently chooses a term of its internal motif identity. For
+that choice, the product of block contractions is a sum over one shared
+payload per internal supply edge. The outer external wire assignment remains
+common to both of its incident blocks. This gives the portwise product and
+the branch-dependent sums in equation (7.1) for the degree refresh.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped Classical
+
+namespace Compression.Refresh
+
+open WireTensor
+
+variable {B R S : Type*} {d : ℕ} [Fintype B] [Fintype S] [CommSemiring R]
+variable {I : B → Type*} [∀ s, Fintype (I s)]
+variable (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ) (a b : S → Fin d)
+variable (A : (s : B) → I s → S → Type*) [∀ s i e, Fintype (A s i e)]
+
+/-- The local supply network in the selected term of one block. -/
+noncomputable abbrev blockSupply (s : B) (i : I s) :=
+ wireNetwork (k := R) a b (A s i)
+
+variable (M : ∀ s (i : I s) j, (internalDemand R t w s).Basis j →
+ (blockSupply (R := R) a b A s i).Basis j → R)
+
+/-- The matrix entry at one port multiplies its two local diagonal tests by
+the entry of the block motif map. Only the incident half-wires are read. -/
+noncomputable def refreshFactor (s : B) (i : I s) (j : Fin d)
+ (x : (oldNetwork R t w).Basis (s,j)) (z : PortSegments t w s j)
+ (y : (blockSupply (R := R) a b A s i).Basis j) : R :=
+ portDiagonal t w s j x z * M s i j (portInput t w s j x z) y
+
+/-- The external-bundle identity and the ordinary local identities in all
+blocks give the edge-indexed expansion with independent choices in each block. -/
+theorem refresh_edge_expansion
+ (h : ∀ s, (internalDemand R t w s).coeff =
+ ∑ i, applyLocal (M s i) (blockSupply (R := R) a b A s i).coeff)
+ (x : (v : B × Fin d) → (oldNetwork R t w).Basis v) :
+ (oldNetwork R t w).coeff x =
+ ∑ c : (s : B) → I s, ∑ z : External w, ∑ y : (s : B) → (e : S) → A s (c s) e,
+ ∏ s, ∏ j, refreshFactor t w a b A M s (c s) j (x (s,j)) (portSegments t w z s j)
+ (edgeAssignment a b (y s) j) := by
+ let term (z : External w) (s : B) (i : I s) (y : (e : S) → A s i e) :=
+ ∏ j, refreshFactor t w a b A M s i j (x (s,j)) (portSegments t w z s j)
+ (edgeAssignment a b y j)
+ have localSum (z : External w) (s : B) :
+ blockTies t w x z s = ∑ i, ∑ y, term z s i y := by
+ rw [blockTies_factor, h, Finset.sum_apply, Finset.mul_sum]
+ apply Finset.sum_congr rfl
+ intro i _
+ rw [applyLocal_wireNetwork a b (A s i) (M s i), Finset.mul_sum]
+ apply Finset.sum_congr rfl
+ intro y _
+ exact (Finset.prod_mul_distrib).symm
+ rw [external_contraction]
+ simp_rw [localSum]
+ simp_rw [Fintype.prod_sum]
+ exact Finset.sum_comm
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshIncidence.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshIncidence.lean
new file mode 100644
index 0000000000..79a5cd61a8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshIncidence.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.DegreeRefreshMotif
+
+/-!
+# Reading the incident external wires of a bundle matching
+
+When an arc matching sends whole bundles to whole bundles, the incoming
+segments at a port all come from one external wire. Their offsets are still
+determined by their order within the original source bundle.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.Refresh
+
+variable {B : Type*} {d : ℕ}
+
+private def readBundleSegment (w : Arc B d → ℕ) (a : Arc B d) {b : B × Fin d}
+ (hab : a.1 = b) (word : Word (∑ j, w (b,j))) : Word (w a) := by
+ subst b
+ exact fun k ↦ word (finSigmaFinEquiv (n := fun j ↦ w (a.1,j)) ⟨a.2,k⟩)
+
+private theorem readBundleSegment_external (w : Arc B d → ℕ) (z : External w)
+ (a : Arc B d) {b : B × Fin d} (hab : a.1 = b) :
+ readBundleSegment w a hab (z b) = segment w z a := by
+ subst b
+ rfl
+
+/-- Read all segments at a port using just the two external half-wires there.
+The inverse matching recovers each incoming segment's source-port index. -/
+def incidentPortSegments (t : Equiv.Perm (Arc B d)) (target : Equiv.Perm (B × Fin d))
+ (h : ∀ a : Arc B d, (t a).1 = target a.1) (w : Arc B d → ℕ) (p : B × Fin d)
+ (outWord : Word (∑ j, w (p,j))) (inWord : Word (∑ j, w (target.symm p,j))) :
+ PortSegments t w p.1 p.2 :=
+ (fun j ↦ readBundleSegment w (p,j) rfl outWord, fun j ↦
+ readBundleSegment w (t.symm (p,j)) (by
+ apply target.injective
+ rw [← h, t.apply_symm_apply, target.apply_symm_apply]) inWord)
+
+/-- On a global assignment of external words the local reader agrees with
+direct extraction from each arc's original bundle. -/
+@[simp] theorem incidentPortSegments_external (t : Equiv.Perm (Arc B d))
+ (target : Equiv.Perm (B × Fin d)) (h : ∀ a : Arc B d, (t a).1 = target a.1)
+ (w : Arc B d → ℕ) (p : B × Fin d) (z : External w) :
+ incidentPortSegments t target h w p (z p) (z (target.symm p)) =
+ portSegments t w z p.1 p.2 := by
+ apply Prod.ext
+ · rfl
+ · funext j
+ exact readBundleSegment_external w z _ _
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshKernel.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshKernel.lean
new file mode 100644
index 0000000000..59e608b534
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshKernel.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.DegreeRefreshTopology
+import OAI.Computability.VPVNP.WireTensor
+import Mathlib.Algebra.BigOperators.Fin
+
+/-!
+# Exact external-wire contraction in the degree refresh
+
+Section 7.3 of *VP and VNP differ over every field* consumes one port index
+per lane and concatenates all port payloads on each old base arc in source
+port order. At each block, outgoing and incoming half-wires are tied to their
+segments of the appropriate external wires. Summing the external payloads
+restores the old network coefficient for every assignment of its half-wires.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped Classical
+
+namespace Compression.Refresh
+
+/-- A block and slot index the external bundle. The final coordinate gives an old source port. -/
+abbrev Arc (B : Type*) (d : ℕ) := (B × Fin d) × Fin d
+
+/-- A payload of a given bit width. -/
+abbrev Word (width : ℕ) := Fin width → Bool
+
+variable {B H L V : Type*} {d : ℕ}
+
+/-- Reindex the old matching by its block, slot and source port. -/
+def oldPortMatching [AddCommGroup H] [AddCommGroup L] (G : LiftedSlots V d (H × L))
+ (label : H ≃ Fin d) : Equiv.Perm (Arc (V × L) d) :=
+ (bundleCoordinates label).symm.trans (G.actualTarget.trans (bundleCoordinates label))
+
+@[simp] theorem oldPortMatching_apply [AddCommGroup H] [AddCommGroup L]
+ (G : LiftedSlots V d (H × L)) (label : H ≃ Fin d) (s : (V × L) × Fin d) (j : Fin d) :
+ oldPortMatching G label (s,j) = (bundleTarget G s, bundlePort G label s j) :=
+ actualTarget_bundleCoordinates G label s j
+
+/-- Each old slot endpoint belongs to its block at the indicated port. -/
+def source (a : Arc B d) : B × Fin d := (a.1.1,a.2)
+
+/-- External strings are concatenated in order of the old source ports. -/
+abbrev External (w : Arc B d → ℕ) := (s : B × Fin d) → Word (∑ j : Fin d, w (s,j))
+
+/-- Extract one old payload from the concatenated external string. -/
+def segment (w : Arc B d → ℕ) (z : External w) (a : Arc B d) : Word (w a) :=
+ fun i ↦ z a.1 (finSigmaFinEquiv (n := fun j ↦ w (a.1,j)) ⟨a.2,i⟩)
+
+/-- The bit offset of a segment is the sum of the preceding source-port widths. -/
+theorem segment_offset (w : Arc B d → ℕ) (s : B × Fin d) (j : Fin d) (i : Fin (w (s,j))) :
+ (finSigmaFinEquiv (n := fun k ↦ w (s,k)) ⟨j,i⟩ : ℕ) =
+ (∑ k : Fin j, w (s, Fin.castLE j.isLt.le k)) + i := finSigmaFinEquiv_apply _
+
+/-- Ordered concatenation and segment extraction are mutually inverse, including
+for bundles containing zero-width fields. -/
+def segmentsEquiv (w : Arc B d → ℕ) : External w ≃ ((a : Arc B d) → Word (w a)) where
+ toFun := segment w
+ invFun x s i :=
+ let p := (finSigmaFinEquiv (n := fun j ↦ w (s,j))).symm i
+ x (s,p.1) p.2
+ left_inv z := by
+ funext s i
+ simp [segment]
+ right_inv x := by
+ funext a i
+ rcases a with ⟨s,j⟩
+ exact congrArg (fun p : (k : Fin d) × Fin (w (s,k)) ↦ x (s,p.1) p.2)
+ ((finSigmaFinEquiv (n := fun k ↦ w (s,k))).symm_apply_apply ⟨j,i⟩)
+
+variable (R : Type*) [CommSemiring R]
+
+/-- A segment tie has coefficient one exactly when its two words agree. -/
+noncomputable def segmentTest {α : Type*} (a b : α) : R :=
+ by classical exact if a = b then 1 else 0
+
+variable [Fintype B]
+
+/-- The unexpanded wire tensor on the individual old ports. -/
+noncomputable def oldNetwork (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ) :=
+ VPVNP.WireTensor.wireNetwork (k := R) source (fun a ↦ source (t a)) (fun a ↦ Word (w a))
+
+variable {R}
+
+/-- The source half-wire is tied to the matching segment at the outgoing slot's port. -/
+noncomputable def outgoingTest (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ)
+ (x : (v : B × Fin d) → (oldNetwork R t w).Basis v) (z : External w) (a : Arc B d) : R :=
+ segmentTest R ((x (source a)).1 a rfl) (segment w z a)
+
+/-- At an incoming slot, the external segment uses the order of its original source.
+Inverting the old slot permutation recovers both its source port and its width. -/
+noncomputable def incomingTest (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ)
+ (x : (v : B × Fin d) → (oldNetwork R t w).Basis v) (z : External w) (q : Arc B d) : R :=
+ let a := t.symm q
+ segmentTest R (segment w z a) ((x (source (t a))).2 a rfl)
+
+/-- All segment ties in a block. For a slot equal to the old port its tie is local. -/
+noncomputable def blockTies (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ)
+ (x : (v : B × Fin d) → (oldNetwork R t w).Basis v) (z : External w) (s : B) : R :=
+ ∏ i : Fin d, ∏ j : Fin d, outgoingTest t w x z ((s,i),j) * incomingTest t w x z ((s,i),j)
+
+private theorem prod_blockTies (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ)
+ (x : (v : B × Fin d) → (oldNetwork R t w).Basis v) (z : External w) :
+ ∏ s, blockTies t w x z s =
+ (∏ a : Arc B d, outgoingTest t w x z a) * (∏ a : Arc B d, incomingTest t w x z (t a)) := by
+ rw [Equiv.prod_comp t (incomingTest t w x z), ← Finset.prod_mul_distrib]
+ simp only [Fintype.prod_prod_type, blockTies]
+
+/-- Before the internal demand networks are converted, summing the external
+bundle assignments gives the old wire equality tensor entrywise. -/
+theorem external_contraction (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ)
+ (x : (v : B × Fin d) → (oldNetwork R t w).Basis v) :
+ (oldNetwork R t w).coeff x = ∑ z : External w, ∏ s, blockTies t w x z s := by
+ classical
+ let u (a : Arc B d) := (x (source a)).1 a rfl
+ let v (a : Arc B d) := (x (source (t a))).2 a rfl
+ let F (y : (a : Arc B d) → Word (w a)) :=
+ (∏ a, segmentTest R (u a) (y a)) * (∏ a, segmentTest R (y a) (v a))
+ have hprod (z : External w) : (∏ s, blockTies t w x z s) = F (segmentsEquiv w z) := by
+ rw [prod_blockTies]
+ change _ * _ = (∏ a, outgoingTest t w x z a) * ∏ a, segmentTest R (segment w z a) (v a)
+ congr 1
+ exact Finset.prod_congr rfl fun a _ ↦
+ congrArg (fun q ↦ segmentTest R (segment w z q) (v q)) (t.symm_apply_apply a)
+ simp_rw [hprod]
+ rw [(segmentsEquiv w).sum_comp F]
+ have htest (a b : (e : Arc B d) → Word (w e)) :
+ (∏ e, segmentTest R (a e) (b e)) = segmentTest R a b := by
+ by_cases hab : a = b
+ · subst b; simp [segmentTest]
+ · obtain ⟨e, he⟩ := Function.ne_iff.mp hab
+ rw [Finset.prod_eq_zero (Finset.mem_univ e) (by simp [segmentTest, he])]
+ simp [segmentTest, hab]
+ have hentry : (oldNetwork R t w).coeff x = ∏ a, segmentTest R (u a) (v a) := by
+ apply Finset.prod_congr rfl
+ intro a _
+ simp [segmentTest, u, v]
+ rw [hentry, htest]
+ simp only [F, htest]
+ simp [segmentTest]
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshMotif.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshMotif.lean
new file mode 100644
index 0000000000..01ed7a5bc9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshMotif.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.DegreeRefresh
+import OAI.Computability.VPVNP.DegreeRefreshKernel
+
+/-!
+# The internal demand tensor of a degree refresh
+
+In Section 7.3 of *VP and VNP differ over every field*, the nonlocal segment
+ties in one block form two copies of the directed complete graph on the
+ports, with its loops removed. The omitted ties are diagonal checks performed
+locally. The remaining ties are evaluated on the binary wire basis used in
+Theorem 6.1. An ordinary sum identity for this motif thus substitutes directly
+into the external-wire contraction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped Classical
+
+namespace Compression.Refresh
+
+open WireTensor DegreeRefresh
+
+variable {B R : Type*} {d : ℕ}
+
+/-- Each demand edge starts at the port bearing the old half-wire. -/
+def tieSource (e : Tie d) : Fin d := e.2.val.1
+
+/-- Its other endpoint is the slot port bearing the external segment. -/
+def tieTarget (e : Tie d) : Fin d := e.2.val.2
+
+/-- The old arc supplying this segment is recovered by inverting the port
+permutation when the tie belongs to an incoming slot. -/
+def internalWidth (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ) (s : B) (e : Tie d) : ℕ :=
+ if e.1 then w ((s,tieTarget e),tieSource e) else w (t.symm ((s,tieTarget e),tieSource e))
+
+/-- The equality tensor of the two off-diagonal copies, in the basis
+`Fin (2 ^ width)` of the fixed-motif theorem. -/
+noncomputable def internalDemand (R : Type*) [CommSemiring R] (t : Equiv.Perm (Arc B d))
+ (w : Arc B d → ℕ) (s : B) :=
+ wireNetwork (k := R) tieSource tieTarget (fun e ↦ Fin (2 ^ internalWidth t w s e))
+
+/-- Segment lists for the two external half-wires incident to a port, in
+source-port order for the outgoing list and destination-port order for the incoming one. -/
+abbrev PortSegments (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ) (s : B) (i : Fin d) :=
+ ((j : Fin d) → Word (w ((s,i),j))) × ((j : Fin d) → Word (w (t.symm ((s,i),j))))
+
+/-- Read the two incident external wires in the prescribed segment order. -/
+def portSegments (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ) (z : External w)
+ (s : B) (i : Fin d) : PortSegments t w s i :=
+ (fun j ↦ segment w z ((s,i),j), fun j ↦ segment w z (t.symm ((s,i),j)))
+
+/-- Encode a port's Boolean payload as the binary index of its motif wire. -/
+def wordIndex (n : ℕ) : Word n ≃ Fin (2 ^ n) :=
+ ((Equiv.refl _).arrowCongr finTwoEquiv.symm).trans finFunctionFinEquiv
+
+variable [CommSemiring R] [Fintype B]
+
+/-- Read an incoming half-wire directly from its destination port. -/
+def incomingHalf (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ) (s : B) (i j : Fin d)
+ (x : (oldNetwork R t w).Basis (s,i)) : Word (w (t.symm ((s,j),i))) :=
+ x.2 (t.symm ((s,j),i)) (congrArg source (t.apply_symm_apply ((s,j),i))).symm
+
+/-- The argument of a motif map at a single port. Its first coordinates read
+the old incident wires, and its second coordinates read external segments. -/
+noncomputable def portInput (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ) (s : B) (i : Fin d)
+ (x : (oldNetwork R t w).Basis (s,i)) (z : PortSegments t w s i) :
+ (internalDemand R t w s).Basis i := by
+ refine ⟨?_, ?_⟩
+ · rintro ⟨b,⟨⟨p,j⟩,hpj⟩⟩ h
+ change i = p at h
+ subst p
+ cases b
+ · exact wordIndex _ (incomingHalf t w s i j x)
+ · exact wordIndex _ (x.1 ((s,j),i) rfl)
+ · rintro ⟨b,⟨⟨p,j⟩,hpj⟩⟩ h
+ change i = j at h
+ subst j
+ cases b
+ · exact wordIndex _ (z.2 p)
+ · exact wordIndex _ (z.1 p)
+
+/-- Both diagonal ties are tested inside their common port. -/
+noncomputable def portDiagonal (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ) (s : B)
+ (i : Fin d) (x : (oldNetwork R t w).Basis (s,i)) (z : PortSegments t w s i) : R :=
+ segmentTest R (x.1 ((s,i),i) rfl) (z.1 i) *
+ segmentTest R (z.2 i) (incomingHalf t w s i i x)
+
+private theorem incomingTest_at (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ)
+ (x : (v : B × Fin d) → (oldNetwork R t w).Basis v) (z : External w)
+ (s : B) (p j : Fin d) :
+ incomingTest t w x z ((s,j),p) =
+ segmentTest R ((portSegments t w z s j).2 p) (incomingHalf t w s p j (x (s,p))) := by
+ have hx (a : Arc B d) (v : B × Fin d) (hv : v = source (t a)) :
+ (x (source (t a))).2 a rfl = (x v).2 a hv := by subst v; rfl
+ exact congrArg (segmentTest R (segment w z (t.symm ((s,j),p))))
+ (hx _ _ (congrArg source (t.apply_symm_apply ((s,j),p))).symm)
+
+private def diagEquiv (d : ℕ) :
+ Fin d ≃ {q : Fin d × Fin d // ¬q.1 ≠ q.2} where
+ toFun i := ⟨(i,i), by simp⟩
+ invFun q := q.val.1
+ left_inv _ := rfl
+ right_inv q := Subtype.ext (Prod.ext rfl (not_not.mp q.property))
+
+private theorem splitPortProduct (f : Fin d → Fin d → R) :
+ (∏ j, ∏ p, f p j) =
+ (∏ i, f i i) * ∏ q : {q : Fin d × Fin d // q.1 ≠ q.2}, f q.val.1 q.val.2 := by
+ let F (q : Fin d × Fin d) := f q.1 q.2
+ calc
+ _ = ∏ q, F q := by rw [Fintype.prod_prod_type, Finset.prod_comm]
+ _ = _ := by
+ rw [← Fintype.prod_subtype_mul_prod_subtype (fun q : Fin d × Fin d ↦ q.1 ≠ q.2) F, mul_comm]
+ exact congrArg (· * _) ((diagEquiv d).prod_comp (fun q ↦ F q.val)).symm
+
+private theorem testIndex {n : ℕ} (u v : Word n) :
+ segmentTest R u v = segmentTest R (wordIndex n u) (wordIndex n v) := by
+ simp [segmentTest]
+
+private theorem testIndexRev {n : ℕ} (u v : Word n) :
+ segmentTest R v u = segmentTest R (wordIndex n u) (wordIndex n v) := by
+ simp [segmentTest, eq_comm]
+
+/-- Entrywise decomposition into all local checks and the nonlocal binary
+demand tensor, with each old half-wire and external segment read at its port. -/
+theorem blockTies_factor (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ)
+ (x : (v : B × Fin d) → (oldNetwork R t w).Basis v) (z : External w) (s : B) :
+ blockTies t w x z s =
+ (∏ i, portDiagonal t w s i (x (s,i)) (portSegments t w z s i)) *
+ (internalDemand R t w s).coeff
+ (fun i ↦ portInput t w s i (x (s,i)) (portSegments t w z s i)) := by
+ let out (p j : Fin d) := outgoingTest t w x z ((s,j),p)
+ let inc (p j : Fin d) := incomingTest t w x z ((s,j),p)
+ change (∏ j, ∏ p, out p j * inc p j) = _
+ rw [splitPortProduct (fun p j ↦ out p j * inc p j)]
+ congr 1
+ · exact Finset.prod_congr rfl fun i _ ↦ congrArg (_ * ·) (incomingTest_at t w x z s i i)
+ · change _ = ∏ e : Tie d, _
+ rw [Fintype.prod_prod_type, Fintype.prod_bool, ← Finset.prod_mul_distrib]
+ apply Finset.prod_congr rfl
+ rintro ⟨⟨p,j⟩,hne⟩ _
+ dsimp only [out, inc, portInput, tieSource, tieTarget, portSegments, internalDemand]
+ rw [incomingTest_at]
+ exact congrArg₂ (· * ·)
+ (testIndex (R := R) ((x (s,p)).1 ((s,j),p) rfl) (segment w z ((s,j),p)))
+ (testIndexRev (R := R) (incomingHalf t w s p j (x (s,p))) (segment w z (t.symm ((s,j),p))))
+
+/-- Replacing the nonlocal ties with an ordinary sum of supply maps.
+Each diagonal check is absorbed into the matrix at its own port. -/
+theorem blockTies_expansion {I : Type*} [Fintype I] (t : Equiv.Perm (Arc B d))
+ (w : Arc B d → ℕ) (s : B) (Y : I → Tensor R (Fin d))
+ (M : ∀ a i, (internalDemand R t w s).Basis i → (Y a).Basis i → R)
+ (h : (internalDemand R t w s).coeff = ∑ a, applyLocal (M a) (Y a).coeff)
+ (x : (v : B × Fin d) → (oldNetwork R t w).Basis v) (z : External w) :
+ blockTies t w x z s = ∑ a, ∑ y : (i : Fin d) → (Y a).Basis i,
+ (∏ i, portDiagonal t w s i (x (s,i)) (portSegments t w z s i) *
+ M a i (portInput t w s i (x (s,i)) (portSegments t w z s i)) (y i)) *
+ (Y a).coeff y := by
+ rw [blockTies_factor, h, Finset.sum_apply, Finset.mul_sum]
+ apply Finset.sum_congr rfl
+ intro a _
+ rw [applyLocal, Finset.mul_sum]
+ simp only [Finset.prod_mul_distrib, mul_assoc]
+ congr 1
+ exact Finset.ext fun i ↦ by simp
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshPass.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshPass.lean
new file mode 100644
index 0000000000..627277efd1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshPass.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.CompressionState
+import OAI.Computability.VPVNP.DegreeRefreshCosts
+import OAI.Computability.VPVNP.LaneReindex
+
+/-!
+# Degree refresh on dyadic compression states
+
+A degree-`2^a` state spends `a` of its binary lane coordinates on the ports
+of the expander. The next state has degree `2^a₀` and the remaining `g`
+lane coordinates. Its positions, energy and largest width are related to
+the old state by the estimates of Section 7.3 on each admitted branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.Refresh
+
+open NetworkKernel SpectralGeometry DegreeRefresh MotifConversion
+
+variable {a g a₀ dH : ℕ} {k : Type*} [Field k] {K K' : ℝ}
+variable (X : State a (a + g))
+
+/-- Split the consumed port coordinates from the remaining lanes of the state. -/
+abbrev splitSlots := relane X.slots (splitBitWord a g)
+
+/-- The original widths after the identical split of lane coordinates. -/
+abbrev splitWidths := relaneWidths (splitBitWord a g) X.width
+
+variable (P : RegularArcGraph (Fin (2 ^ a)) dH) (hdH : 0 < dH)
+ (hconn : (arcSupportGraph P.multiplicity).Connected)
+ (F : RefreshBlock k (expanderSupply P hdH hconn) (2 ^ a₀) K K')
+ (hD : 1 < 2 ^ a) (hd : dH + 1 ≤ 2 ^ a₀)
+
+/-- Choices of local terms for the dyadic degree refresh, using the split slots and widths of
+the current state. -/
+abbrev DyadicRefreshChoice := BlockChoices (splitSlots X) (bitWordFinEquiv a) (splitWidths X) P hdH hconn F
+
+/-- The degree-restored state uses the port as part of its new base label. -/
+noncomputable def dyadicRefreshNext (c : DyadicRefreshChoice X P hdH hconn F) : State a₀ g where
+ Base := X.Base × Fin (2 ^ a)
+ baseFintype := inferInstance
+ baseNonempty := inferInstance
+ baseIndex := State.productIndex X.baseIndex (Equiv.refl (Fin (2 ^ a)))
+ slots := degreeRefresh (splitSlots X) P.toSlotGraph hD hd
+ width := actualWidths hd (bitWordFinEquiv a) (splitWidths X)
+ (blockSupplyWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) P hdH hconn F c)
+
+variable {R : Type*} [CommRing R] (κ : (parameterData F).Entry → R) (hκ : (parameterData F).IsSolution κ)
+
+/-- The exact kernel over an arbitrary solution of the fixed parameter equations,
+with every output of the kernel paired with its compression state. -/
+noncomputable def dyadicRefreshPass : StatePass R X a₀ g where
+ step := (expanderRefreshStep (splitSlots X) (bitWordFinEquiv a) (splitWidths X)
+ P hdH hconn F κ hκ hD hd).reindexInput (relaneIso X.slots (splitBitWord a g) X.width)
+ next := dyadicRefreshNext X P hdH hconn F hD hd
+ output_eq _ := rfl
+
+/-- Each old position stays at its own physical port. -/
+theorem dyadicRefreshPass_place (c : DyadicRefreshChoice X P hdH hconn F)
+ (x : X.Base × BitWord (a + g)) :
+ (((dyadicRefreshPass X P hdH hconn F hD hd κ hκ).step.term c).place x) =
+ refreshPositions (bitWordFinEquiv a) (x.1,splitBitWord a g x.2) := rfl
+
+/-- The degree refresh preserves the exact number of positions on every branch. -/
+theorem dyadicRefreshNext_positions (c : DyadicRefreshChoice X P hdH hconn F) :
+ (dyadicRefreshNext X P hdH hconn F hD hd c).positions = X.positions := by
+ change Fintype.card ((X.Base × Fin (2 ^ a)) × BitWord g) = Fintype.card (X.Base × BitWord (a+g))
+ let e := ((Equiv.refl X.Base).prodCongr (splitBitWord a g).toEquiv).trans
+ (refreshPositions (bitWordFinEquiv a))
+ exact (Fintype.card_congr e).symm
+
+/-- Equation (7.3) with the energy and position count of the compression
+state. The leading factor is `2^a₀ + 2 K'`, independent of the old degree
+when the block is chosen by `exists_expander_parameters`. -/
+theorem dyadicRefreshNext_energy (hK' : 0 ≤ K') (c : DyadicRefreshChoice X P hdH hconn F) :
+ (dyadicRefreshNext X P hdH hconn F hD hd c).energy ≤
+ ((2 ^ a₀ : ℕ) + 2 * K') * X.energy + F.energyConstant * X.positions ^ 2 := by
+ have h := expander_branch_energy_le (splitSlots X) (bitWordFinEquiv a) (splitWidths X)
+ P hdH hconn F hD hd hK' c
+ dsimp only at h
+ have hc : Fintype.card (X.Base × (BitWord a × BitWord g)) = X.positions :=
+ relane_card_sites (V := X.Base) (splitBitWord a g)
+ rw [hc, relane_sum_widths (splitBitWord a g) X.width
+ (fun n ↦ (n : ℝ) ^ 2 / (1 / ((X.positions : ℝ) * (2 ^ a : ℕ))))] at h
+ rw [State.energy, dyadicRefreshNext_positions]
+ exact h
+
+/-- The field bound of the degree refresh, stated on the full output state. -/
+theorem dyadicRefreshNext_width (hK' : 0 ≤ K') (c : DyadicRefreshChoice X P hdH hconn F)
+ {W : ℕ} (hW : ∀ e, X.width e ≤ W) (e : ((X.Base × Fin (2 ^ a)) × Fin (2 ^ a₀)) × BitWord g) :
+ ((dyadicRefreshNext X P hdH hconn F hD hd c).width e : ℝ) ≤
+ max ((2 ^ a : ℕ) : ℝ) (Real.sqrt ((((2 ^ a : ℕ) : ℝ) / (2 ^ a₀ : ℕ)) *
+ (K' * Fintype.card (Tie (2 ^ a)) + max 0 F.energyConstant))) * (W + 1) :=
+ expander_branch_width_le (splitSlots X) (bitWordFinEquiv a) (splitWidths X)
+ P hdH hconn F hD hd hK' c (fun _ ↦ hW _) e
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshPayloads.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshPayloads.lean
new file mode 100644
index 0000000000..1b53b86cfd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshPayloads.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.DegreeRefreshWidths
+import Mathlib.Data.Fintype.BigOperators
+
+/-!
+# Shared payloads of the refreshed graph
+
+The summation over the actual arcs in (7.1) is equivalent to choosing the
+external strings and a separate internal expander assignment in each block.
+Every padding arc carries the unique string of length zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped Classical
+
+namespace Compression.Refresh
+
+variable {V L : Type*} {D dH d₀ : ℕ}
+
+/-- A refreshed outgoing arc consists of a base port, a remaining lane, and
+one of the new degree-`d₀` slots. -/
+abbrev ActualArc (V L : Type*) (D d₀ : ℕ) := ((V × Fin D) × L) × Fin d₀
+
+/-- Read the block, its port, and the class of the numbered slot. -/
+def arcCoordinates (hd : dH + 1 ≤ d₀) :
+ ActualArc V L D d₀ ≃ ((V × L) × Fin D) × RefreshSlot dH d₀ where
+ toFun a := (((a.1.1.1,a.1.2),a.1.1.2), (refreshSlots hd).symm a.2)
+ invFun q := (((q.1.1.1,q.1.2),q.1.1.2), refreshSlots hd q.2)
+ left_inv _ := by simp
+ right_inv _ := by simp
+
+variable (ext : (V × L) × Fin D → ℕ) (internal : V × L → Fin D × Fin dH → ℕ)
+
+private def classWidth (a : ((V × L) × Fin D) × RefreshSlot dH d₀) : ℕ :=
+ match a.2 with
+ | .inl _ => ext a.1
+ | .inr (.inl h) => internal a.1.1 (a.1.2,h)
+ | .inr (.inr _) => 0
+
+/-- Width on the actual outgoing arc index of `degreeRefresh`. -/
+def actualWidth (hd : dH + 1 ≤ d₀) (ext : (V × L) × Fin D → ℕ)
+ (internal : V × L → Fin D × Fin dH → ℕ) (a : ActualArc V L D d₀) : ℕ :=
+ classWidth ext internal (arcCoordinates hd a)
+
+private def classPayloads :
+ ((a : ((V × L) × Fin D) × RefreshSlot dH d₀) → Fin (classWidth ext internal a) → Bool) ≃
+ ((b : (V × L) × Fin D) → Fin (ext b) → Bool) ×
+ ((s : V × L) → (e : Fin D × Fin dH) → Fin (internal s e) → Bool) where
+ toFun f := (fun b => f (b,.inl 0), fun s e => f ((s,e.1),.inr (.inl e.2)))
+ invFun p a := match a with
+ | (b, .inl _) => p.1 b
+ | ((s,j), .inr (.inl h)) => p.2 s (j,h)
+ | (_, .inr (.inr _)) => Fin.elim0
+ left_inv f := by
+ funext a
+ rcases a with ⟨b, k | k | k⟩
+ · cases Subsingleton.elim k 0
+ rfl
+ · rfl
+ · funext i
+ exact Fin.elim0 i
+ right_inv _ := rfl
+
+/-- Shared actual-arc payloads are exactly one external assignment and one
+internal assignment per block. Empty padding payloads add no summation index. -/
+def payloadsEquiv (hd : dH + 1 ≤ d₀) (ext : (V × L) × Fin D → ℕ)
+ (internal : V × L → Fin D × Fin dH → ℕ) :
+ ((a : ActualArc V L D d₀) → Fin (actualWidth hd ext internal a) → Bool) ≃
+ ((b : (V × L) × Fin D) → Fin (ext b) → Bool) ×
+ ((s : V × L) → (e : Fin D × Fin dH) → Fin (internal s e) → Bool) :=
+ (Equiv.piCongrLeft (fun a => Fin (classWidth ext internal a) → Bool) (arcCoordinates hd)).trans
+ (classPayloads ext internal)
+
+/-- This actual-arc width specializes to the width charged in (7.3). -/
+theorem actualWidth_eq_newWidths (hd : dH + 1 ≤ d₀) (w : DegreeRefresh.Widths (V × L) D)
+ (a : ActualArc V L D d₀) :
+ actualWidth hd (fun b => ∑ j, w b j) internal a =
+ DegreeRefresh.newWidths hd w internal ((a.1.1.1,a.1.2),a.1.1.2) a.2 := rfl
+
+@[simp] theorem actualWidth_external (hd : dH + 1 ≤ d₀) (b : (V × L) × Fin D) :
+ actualWidth hd ext internal (((b.1.1,b.2),b.1.2),refreshSlots hd (.inl 0)) = ext b := by
+ simp [actualWidth, arcCoordinates, classWidth]
+
+@[simp] theorem actualWidth_internal (hd : dH + 1 ≤ d₀) (s : V × L) (e : Fin D × Fin dH) :
+ actualWidth hd ext internal (((s.1,e.1),s.2),refreshSlots hd (.inr (.inl e.2))) =
+ internal s e := by
+ simp [actualWidth, arcCoordinates, classWidth]
+
+/-- Read the external component at its numbered actual slot. -/
+theorem payloadsEquiv_external (hd : dH + 1 ≤ d₀)
+ (f : (a : ActualArc V L D d₀) → Fin (actualWidth hd ext internal a) → Bool)
+ (b : (V × L) × Fin D) :
+ (payloadsEquiv hd ext internal f).1 b =
+ cast (congrArg (fun n => Fin n → Bool) (actualWidth_external ext internal hd b))
+ (f (((b.1.1,b.2),b.1.2),refreshSlots hd (.inl 0))) :=
+ Equiv.piCongrLeft_apply_eq_cast (P := fun a => Fin (classWidth ext internal a) → Bool)
+ (e := arcCoordinates hd) f (b,.inl 0)
+
+/-- Read a block's internal component at its numbered expander slot. -/
+theorem payloadsEquiv_internal (hd : dH + 1 ≤ d₀)
+ (f : (a : ActualArc V L D d₀) → Fin (actualWidth hd ext internal a) → Bool)
+ (s : V × L) (e : Fin D × Fin dH) :
+ (payloadsEquiv hd ext internal f).2 s e =
+ cast (congrArg (fun n => Fin n → Bool) (actualWidth_internal ext internal hd s e))
+ (f (((s.1,e.1),s.2),refreshSlots hd (.inr (.inl e.2)))) :=
+ Equiv.piCongrLeft_apply_eq_cast (P := fun a => Fin (classWidth ext internal a) → Bool)
+ (e := arcCoordinates hd) f ((s,e.1),.inr (.inl e.2))
+
+/-- The equality of finite sums used to replace the separate external and
+internal choices by the single shared arc assignment of (7.1). -/
+theorem sum_payloads [Fintype V] [Fintype L] (hd : dH + 1 ≤ d₀) {A : Type*} [AddCommMonoid A]
+ (f : ((b : (V × L) × Fin D) → Fin (ext b) → Bool) →
+ ((s : V × L) → (e : Fin D × Fin dH) → Fin (internal s e) → Bool) → A) :
+ (∑ a, f ((payloadsEquiv hd ext internal a).1) ((payloadsEquiv hd ext internal a).2)) =
+ ∑ x, ∑ y, f x y := by
+ classical
+ rw [← Fintype.sum_prod_type']
+ exact (payloadsEquiv hd ext internal).sum_comp (fun p => f p.1 p.2)
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshPorts.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshPorts.lean
new file mode 100644
index 0000000000..6bf9260924
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshPorts.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.DegreeRefreshIncidence
+import OAI.Computability.VPVNP.DegreeRefreshWidths
+
+/-!
+# Incident external words in the degree refresh
+
+In Section 7.3 of *VP and VNP differ over every field*, each destination slot
+receives all its segments in one external word, ordered by the original source
+ports. This gives a local evaluator of the two segment lists at every port and
+identifies the widths used by its internal tensor with the widths in the energy
+estimate.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.Refresh
+
+variable {H L V : Type*} {d : ℕ} [AddCommGroup H] [AddCommGroup L]
+ (G : LiftedSlots V d (H × L)) (port : H ≃ Fin d)
+
+/-- The destination slot determines the incoming bundle. Invert its port
+translation to recover the segment's position in the source ordering. -/
+theorem oldPortMatching_symm_apply (b : (V × L) × Fin d) (j : Fin d) :
+ (oldPortMatching G port).symm (b,j) =
+ ((bundleTarget G).symm b, (bundlePort G port ((bundleTarget G).symm b)).symm j) := by
+ apply (oldPortMatching G port).injective
+ simp only [oldPortMatching_apply, Equiv.apply_symm_apply]
+
+/-- Every old port in the same external word reaches the same block and slot. -/
+theorem oldPortMatching_bundle (a : Arc (V × L) d) :
+ (oldPortMatching G port a).1 = bundleTarget G a.1 := rfl
+
+/-- At an actual port the segment lists in the old tensor can be read from the
+two incident external words, using the same local reader as the kernel step. -/
+theorem portSegments_eq_incident (w : Arc (V × L) d → ℕ) (z : External w)
+ (b : (V × L) × Fin d) :
+ portSegments (oldPortMatching G port) w z b.1 b.2 =
+ incidentPortSegments (oldPortMatching G port) (bundleTarget G) (oldPortMatching_bundle G port)
+ w b (z b) (z ((bundleTarget G).symm b)) :=
+ (incidentPortSegments_external _ _ _ _ _ _).symm
+
+variable {dH d₀ : ℕ} (P : SlotGraph (Fin d) dH) (hD : 1 < d) (hd : dH + 1 ≤ d₀)
+
+open DegreeRefresh in
+omit [AddCommGroup H] in
+/-- The actual refreshed matching sends the outgoing external word at a port
+to the unique incoming external slot in the translated block. -/
+theorem actualTarget_external_bundle (b : (V × L) × Fin d) :
+ (degreeRefresh G P hD hd).actualTarget
+ (refreshedCoordinates.symm (b, refreshSlots hd (.inl 0))) =
+ refreshedCoordinates.symm (bundleTarget G b, refreshSlots hd (.inl 0)) := by
+ rcases b with ⟨⟨v,g⟩,i⟩
+ exact congrArg (fun t : ((V × Fin d) × L) × Fin d₀ ↦ ((t.1.1,t.2),t.1.2))
+ (degreeRefresh_external G P hD hd (v,i) g)
+
+open DegreeRefresh in
+omit [AddCommGroup H] in
+/-- The incoming word used by the local evaluator belongs to the actual arc
+ending at the port's external slot. -/
+theorem actualTarget_symm_external_bundle (b : (V × L) × Fin d) :
+ (degreeRefresh G P hD hd).actualTarget.symm
+ (refreshedCoordinates.symm (b, refreshSlots hd (.inl 0))) =
+ refreshedCoordinates.symm ((bundleTarget G).symm b, refreshSlots hd (.inl 0)) := by
+ apply (degreeRefresh G P hD hd).actualTarget.injective
+ rw [Equiv.apply_symm_apply, actualTarget_external_bundle, Equiv.apply_symm_apply]
+
+open DegreeRefresh in
+omit [AddCommGroup H] [AddCommGroup L] in
+/-- The external arc's actual width is the sum of the widths in its word. -/
+theorem actualWidth_external_bundle (w : (V × Fin d) × (H × L) → ℕ)
+ (u : (V × L) → Fin d × Fin dH → ℕ) (b : (V × L) × Fin d) :
+ actualWidths hd port w u (refreshedCoordinates.symm (b, refreshSlots hd (.inl 0))) =
+ ∑ j, bundleWidths port w b j := by
+ simp [actualWidths, newWidths]
+
+/-- For the actual matching, every internal tensor factor has the bit width
+charged to the corresponding tie by the energy inequality. -/
+theorem internalWidth_eq_tieWidth (w : Arc (V × L) d → ℕ) (s : V × L) (e : DegreeRefresh.Tie d) :
+ internalWidth (oldPortMatching G port) w s e =
+ DegreeRefresh.tieWidth (bundleTarget G) (bundlePort G port) (fun b j ↦ w (b,j)) s e := by
+ simp only [internalWidth, DegreeRefresh.tieWidth, DegreeRefresh.incoming, tieTarget, tieSource,
+ oldPortMatching_symm_apply]
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshStep.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshStep.lean
new file mode 100644
index 0000000000..b4cedeb42b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshStep.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.DegreeRefreshExpansion
+import OAI.Computability.VPVNP.DegreeRefreshIncidence
+import OAI.Computability.VPVNP.NetworkKernel
+
+/-!
+# The degree refresh as a placed wire-kernel step
+
+In Section 7.3, each old position becomes a port of its block. Its vertex
+factor stays whole at that port. The local map reads the outgoing external
+word, the incoming word in source-segment order, and the selected supply
+half-wires. All padding wires have their unique zero-bit payload.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped Classical
+
+namespace Compression.Refresh
+
+open WireTensor NetworkKernel
+
+variable {B S : Type} {d : ℕ} [Fintype B] [Fintype S]
+
+/-- The old wire network in block, slot, and old source-port coordinates. -/
+noncomputable def oldWireGraph (t : Equiv.Perm (Arc B d)) (w : Arc B d → ℕ) : Network where
+ Site := B × Fin d
+ siteFintype := inferInstance
+ Edge := Arc B d
+ edgeFintype := inferInstance
+ src := source
+ dst e := source (t e)
+ Payload e := Word (w e)
+ payloadFintype _ := inferInstance
+
+/-- External slots, one copy of the supply edges per block, and cyclic padding slots. -/
+abbrev OutputEdge (B S : Type) (d pad : ℕ) :=
+ (B × Fin d) ⊕ ((B × S) ⊕ ((B × Fin d) × Fin pad))
+
+private def outputPayload (w : Arc B d → ℕ) (A : B → S → Type) (pad : ℕ) :
+ OutputEdge B S d pad → Type
+ | .inl p => Word (∑ j, w (p,j))
+ | .inr (.inl (s,e)) => A s e
+ | .inr (.inr _) => Word 0
+
+/-- The selected output has one external slot per port. Each copy of the
+supply graph lies within one block, as do all cyclic padding arcs. -/
+noncomputable def refreshOutput (target : Equiv.Perm (B × Fin d)) (w : Arc B d → ℕ)
+ (a b : S → Fin d) (A : B → S → Type) [∀ s e, Fintype (A s e)] (pad : ℕ) : Network where
+ Site := B × Fin d
+ siteFintype := inferInstance
+ Edge := OutputEdge B S d pad
+ edgeFintype := inferInstance
+ src
+ | .inl p => p
+ | .inr (.inl (s,e)) => (s,a e)
+ | .inr (.inr (p,_)) => p
+ dst
+ | .inl p => target p
+ | .inr (.inl (s,e)) => (s,b e)
+ | .inr (.inr ((s,i),_)) => (s,finRotate d i)
+ Payload := outputPayload w A pad
+ payloadFintype
+ | .inl _ => inferInstanceAs (Fintype (Word _))
+ | .inr (.inl (s,e)) => inferInstanceAs (Fintype (A s e))
+ | .inr (.inr _) => inferInstanceAs (Fintype (Word 0))
+
+variable (target : Equiv.Perm (B × Fin d)) (w : Arc B d → ℕ) (a b : S → Fin d)
+ (A : B → S → Type) [∀ s e, Fintype (A s e)] (pad : ℕ)
+
+/-- Concatenated external words and internal assignments together specify
+one assignment to the output wires, with every padding slot uniquely filled. -/
+def outputAssignments :
+ External w × ((s : B) → (e : S) → A s e) ≃
+ ((e : (refreshOutput target w a b A pad).Edge) →
+ (refreshOutput target w a b A pad).Payload e) where
+ toFun zy
+ | .inl p => zy.1 p
+ | .inr (.inl (s,e)) => zy.2 s e
+ | .inr (.inr _) => Fin.elim0
+ invFun q := (fun p ↦ q (.inl p), fun s e ↦ q (.inr (.inl (s,e))))
+ left_inv _ := rfl
+ right_inv q := by
+ funext e
+ rcases e with p | ⟨s,e⟩ | p
+ · rfl
+ · rfl
+ · exact Subsingleton.elim (α := Word 0) _ _
+
+variable {R : Type*} [CommSemiring R]
+
+/-- The two half-wire lists of the supply motif are read from the internal
+arcs of this block, retaining their independent source and target values. -/
+def supplyHalf (p : B × Fin d) (u : (refreshOutput target w a b A pad).Half p) :
+ (wireNetwork (k := R) a b (A p.1)).Basis p.2 :=
+ (fun e h ↦ u.1 (.inr (.inl (p.1,e))) (Prod.ext rfl h),
+ fun e h ↦ u.2 (.inr (.inl (p.1,e))) (Prod.ext rfl h))
+
+variable {I : B → Type} [∀ s, Fintype (I s)]
+
+/-- The port-local term of (7.1) for one joint selection of the block motif maps. -/
+noncomputable def refreshTerm (t : Equiv.Perm (Arc B d)) (target : Equiv.Perm (B × Fin d))
+ (ht : ∀ e : Arc B d, (t e).1 = target e.1) (w : Arc B d → ℕ) (a b : S → Fin d)
+ (A : (s : B) → I s → S → Type) [∀ s i e, Fintype (A s i e)]
+ (M : ∀ s (i : I s) j, (internalDemand R t w s).Basis j →
+ (blockSupply (R := R) a b A s i).Basis j → R)
+ (pad : ℕ) (c : (s : B) → I s) : Term R (oldWireGraph t w) where
+ output := refreshOutput target w a b (fun s ↦ A s (c s)) pad
+ place := id
+ kernel p x u :=
+ let z := incidentPortSegments t target ht w p (u.1 (.inl p) rfl)
+ (u.2 (.inl (target.symm p)) (target.apply_symm_apply p).symm)
+ refreshFactor t w a b A M p.1 (c p.1) p.2 (x p rfl) z
+ (supplyHalf target w a b (fun s ↦ A s (c s)) pad p u)
+
+variable (t : Equiv.Perm (Arc B d)) (ht : ∀ e : Arc B d, (t e).1 = target e.1)
+ (labels : (s : B) → I s → S → Type) [∀ s i e, Fintype (labels s i e)]
+ (M : ∀ s (i : I s) j, (internalDemand R t w s).Basis j →
+ (blockSupply (R := R) a b labels s i).Basis j → R)
+
+omit [∀ s, Fintype (I s)] in
+/-- For a selected term the shared output-edge sum equals the sum over the
+external strings and the independent internal assignments in every block. -/
+theorem refreshTerm_value (c : (s : B) → I s) (x : ∀ p, (oldWireGraph t w).Half p) :
+ (refreshTerm t target ht w a b labels M pad c).value x =
+ ∑ z : External w, ∑ y : (s : B) → (e : S) → labels s (c s) e,
+ ∏ s, ∏ j, refreshFactor t w a b labels M s (c s) j (x (s,j))
+ (portSegments t w z s j) (edgeAssignment a b (y s) j) := by
+ let term := refreshTerm t target ht w a b labels M pad c
+ let f (u : (e : term.output.Edge) → term.output.Payload e) :=
+ ∏ p, term.kernel p (fun q _ ↦ x q) (edgeAssignment term.output.src term.output.dst u p)
+ rw [Term.value_eq_edgeSum]
+ change (∑ u, f u) = _
+ let split := outputAssignments target w a b (fun s ↦ labels s (c s)) pad
+ refine (split.sum_comp f).symm.trans ?_
+ refine (Fintype.sum_prod_type (fun u ↦ f (split u))).trans ?_
+ apply Finset.sum_congr rfl
+ intro z _
+ apply Finset.sum_congr rfl
+ intro y _
+ change (∏ p : B × Fin d, _) = _
+ rw [Fintype.prod_prod_type]
+ apply Finset.prod_congr rfl
+ intro s _
+ apply Finset.prod_congr rfl
+ intro j _
+ change refreshFactor t w a b labels M s (c s) j (x (s,j))
+ (incidentPortSegments t target ht w (s,j) (z (s,j)) (z (target.symm (s,j))))
+ (edgeAssignment a b (y s) j) = _
+ rw [incidentPortSegments_external]
+
+/-- An ordinary motif identity in each block produces the degree-refresh
+step of (7.1), with identity placement in the grouped port coordinates. -/
+noncomputable def refreshStep
+ (h : ∀ s, (internalDemand R t w s).coeff =
+ ∑ i, applyLocal (M s i) (blockSupply (R := R) a b labels s i).coeff) :
+ Step R (oldWireGraph t w) where
+ Choice := (s : B) → I s
+ choiceFintype := inferInstance
+ term := refreshTerm t target ht w a b labels M pad
+ exact_eq x := by
+ simp only [refreshTerm_value]
+ exact refresh_edge_expansion t w a b labels M h x
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshSupply.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshSupply.lean
new file mode 100644
index 0000000000..3d9eaabffb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshSupply.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.DegreeRefreshMotif
+import OAI.Computability.VPVNP.FlatteningWires
+import OAI.Computability.VPVNP.GraphConnectivity
+import OAI.Computability.VPVNP.MotifBlocks
+
+/-!
+# The expander supply motif of a degree refresh
+
+Section 7.3 of *VP and VNP differ over every field* divides both arc masses
+by the old arc mass. The two copies of the ordered port pairs then have
+unit mass, and every directed expander arc has mass `D / d₀`. The Poincaré
+bound for the spectral wire pseudometrics supplies the comparison required
+by Theorem 6.1. The flattening spectral point also detects connectivity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.Refresh
+
+open SpectralGeometry WireTensor MotifGrid DegreeRefresh
+
+variable {k : Type*} [Field k] {D dH d₀ : ℕ} {γ : ℝ}
+
+/-- The common Poincaré bound for every labeling of the ports in every
+spectral wire pseudometric on the port set. -/
+def SpectralPortBound (k : Type*) [Field k] (G : RegularArcGraph (Fin D) dH) (γ : ℝ) : Prop :=
+ ∀ F : SpectralPoint k (Fin D), letI := F.wirePseudoMetric
+ HasPoincareBound (Fin D) (normalizeArcs G.multiplicity dH) γ
+
+/-- The same Poincaré hypothesis implies connectivity and positivity of the
+bound. The one-party flattening gives two ports at distance one. -/
+theorem SpectralPortBound.connected_and_pos {G : RegularArcGraph (Fin D) dH}
+ (hP : SpectralPortBound k G γ) (hD : 2 ≤ D) :
+ (arcSupportGraph G.multiplicity).Connected ∧ 0 < γ := by
+ let : Nontrivial (Fin D) := Fin.nontrivial_iff_two_le.mpr hD
+ obtain ⟨a, b, hab⟩ := exists_pair_ne (Fin D)
+ let F := flatteningPoint (k := k) a
+ let := F.wirePseudoMetric
+ have hsep : 0 < dist a b := by
+ change 0 < (flatteningPoint (k := k) a).wireDistance a b
+ simp [flatteningPoint_wireDistance, hab]
+ let P := normalizeArcs G.multiplicity dH
+ have hn (i j : Fin D) : 0 ≤ P i j := by unfold P normalizeArcs; positivity
+ have hs (i j : Fin D) : P i j = P j i := by
+ simp only [P, normalizeArcs, G.multiplicity_symmetric i j]
+ constructor
+ · refine ⟨fun i j ↦ (arcSupportGraph_reachable_iff G.multiplicity G.multiplicity_symmetric i j).mpr ?_⟩
+ apply Relation.ReflTransGen.mono _ i j (reachable_of_poincare a b hsep P hn hs (hP F) i j)
+ intro u v h
+ exact Nat.pos_of_ne_zero (fun hz ↦ by simp [P, normalizeArcs, hz] at h)
+ · have hsquares : 0 < ∑ u, ∑ v, dist u v ^ 2 := Finset.sum_pos'
+ (fun _ _ ↦ Finset.sum_nonneg fun _ _ ↦ sq_nonneg _)
+ ⟨a, Finset.mem_univ _, Finset.sum_pos' (fun _ _ ↦ sq_nonneg _)
+ ⟨b, Finset.mem_univ _, sq_pos_of_pos hsep⟩⟩
+ have hwalk : 0 ≤ walkEnergy P id := Finset.sum_nonneg fun i _ ↦
+ Finset.sum_nonneg fun j _ ↦ mul_nonneg (hn i j) (sq_nonneg _)
+ have hprod : 0 < γ * walkEnergy P id :=
+ (div_pos hsquares (Nat.cast_pos.mpr (Fintype.card_pos (α := Fin D)))).trans_le (hP F id)
+ exact pos_of_mul_pos_left hprod hwalk
+
+/-- Use every directed arc as one supply edge. Its source's first outgoing
+slot is the local selector anchor. -/
+def expanderSupply (G : RegularArcGraph (Fin D) dH) (hdH : 0 < dH)
+ (hconn : (arcSupportGraph G.multiplicity).Connected) :
+ MotifSelector.Supply (Fin D) (Fin D × Fin dH) where
+ src := Prod.fst
+ dst e := (G.reverse e).1
+ anchor i := (i, ⟨0, hdH⟩)
+ anchor_incident _ := Or.inl rfl
+ connected u v := by
+ have hpath := (arcSupportGraph_reachable_iff G.multiplicity G.multiplicity_symmetric u v).mp
+ (hconn.preconnected u v)
+ apply Relation.ReflTransGen.mono _ u v hpath
+ intro i j hij
+ obtain ⟨h, hh⟩ := (G.multiplicity_pos_iff i j).mp hij
+ exact ⟨(i,h), Or.inl ⟨rfl, hh⟩⟩
+
+/-- Each segment tie has unit mass after dividing out the old arc mass. -/
+def tieMass (_ : Tie D) : ℚ := 1
+
+/-- Each expander arc has mass equal to the ratio of the old degree to the new degree. -/
+def expanderMass (d₀ : ℕ) (_ : Fin D × Fin dH) : ℚ := (D : ℚ) / d₀
+
+/-- The common port bound gives the fixed-motif comparison with the paper's
+constant `2 γ d₀ / dH`, independent of the order `D`. -/
+theorem expander_distanceEnergy (G : RegularArcGraph (Fin D) dH) (hdH : 0 < dH)
+ (hconn : (arcSupportGraph G.multiplicity).Connected) (hD : 0 < D) (hd₀ : 0 < d₀)
+ (hP : SpectralPortBound k G γ) (F : SpectralPoint k (Fin D)) :
+ distanceEnergy (realWidths tieMass) (fun t ↦ F.wireDistance (tieSource t) (tieTarget t)) ≤
+ (2 * γ * d₀ / dH) * distanceEnergy (realWidths (expanderMass d₀))
+ (fun e ↦ F.wireDistance ((expanderSupply G hdH hconn).src e) ((expanderSupply G hdH hconn).dst e)) := by
+ have h := @metric_comparison D dH (Fin D) F.wirePseudoMetric G 1 ((D : ℝ) / d₀) d₀ γ hD zero_le_one
+ (by field_simp [Nat.cast_ne_zero.mpr hd₀.ne']) (hP F) id
+ simp only [distanceEnergy, realWidths, tieMass, expanderMass, Rat.cast_one, Rat.cast_div,
+ Rat.cast_natCast]
+ exact h
+
+/-- Fix a single block of exact base identities and a uniform width-energy
+error, with the slack `H' = H + 1` used at the degree refresh. -/
+theorem exists_expander_block (G : RegularArcGraph (Fin D) dH) (hdH : 0 < dH)
+ (hD : 2 ≤ D) (hd₀ : 0 < d₀) (hP : SpectralPortBound k G γ) :
+ let P := expanderSupply G hdH (hP.connected_and_pos hD).1
+ let H := 2 * γ * d₀ / dH
+ Nonempty (MotifBlocks.FixedBlock k tieSource tieTarget P
+ (realWidths tieMass) (realWidths (expanderMass d₀)) H (H + 1)) := by
+ intro P H
+ let : Nontrivial (Fin D) := Fin.nontrivial_iff_two_le.mpr hD
+ obtain ⟨hconn, hγ⟩ := hP.connected_and_pos hD
+ have hD' : 0 < D := by omega
+ apply MotifBlocks.exists_fixed_block tieSource tieTarget P _ _
+ · simp [realWidths, tieMass]
+ · intro e
+ simp only [realWidths, expanderMass, Rat.cast_div, Rat.cast_natCast]
+ positivity
+ · dsimp [H]
+ positivity
+ · linarith
+ · exact expander_distanceEnergy G hdH hconn hD' hd₀ hP
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshTopology.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshTopology.lean
new file mode 100644
index 0000000000..388d1c0d9a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshTopology.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.SlotGraph
+import Mathlib.Algebra.Group.Units.Equiv
+import Mathlib.Algebra.Group.Prod
+import Mathlib.Logic.Equiv.Fin.Rotate
+import Mathlib.Algebra.Group.Fin.Basic
+
+/-!
+# The regular topology after a degree refresh
+
+Section 7.3 of *VP and VNP differ over every field* promotes the port
+coordinate to a base label. Each port has a single external arc, one
+internal arc per expander slot, and cyclic padding arcs. The external arc
+retains the old shift of the remaining lane. Internal and padding arcs
+stay within a block.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+variable {V H L : Type*} {D dH d₀ : ℕ}
+
+/-- Relabeling the port component of the old lane leaves a bijection of positions. -/
+def refreshPositions (port : H ≃ Fin D) : V × (H × L) ≃ (V × Fin D) × L :=
+ ((Equiv.refl V).prodCongr (port.prodCongr (Equiv.refl L))).trans (Equiv.prodAssoc _ _ _).symm
+
+@[simp] theorem refreshPositions_apply (port : H ≃ Fin D) (v : V) (j : H) (g : L) :
+ refreshPositions port (v,j,g) = ((v,port j),g) := rfl
+
+/-- Group old outgoing slots by their source block and slot, keeping the old
+port as the last index within each bundle. The same indexing applies to
+incoming slots. -/
+def bundleCoordinates (port : H ≃ Fin D) :
+ ((V × Fin D) × (H × L)) ≃ ((V × L) × Fin D) × Fin D where
+ toFun p := (((p.1.1, p.2.2), p.1.2), port p.2.1)
+ invFun p := ((p.1.1.1, p.1.2), (port.symm p.2, p.1.1.2))
+ left_inv _ := by simp
+ right_inv _ := by simp
+
+/-- A source block and slot determine the destination block and incoming slot. -/
+def bundleTarget [AddCommGroup L] (G : LiftedSlots V D (H × L)) :
+ Equiv.Perm ((V × L) × Fin D) :=
+ (LiftedSlots.mk G.base (fun p => (G.displacement p).2)).actualGraph.target
+
+@[simp] theorem bundleTarget_apply [AddCommGroup L] (G : LiftedSlots V D (H × L))
+ (x : V) (g : L) (i : Fin D) :
+ bundleTarget G ((x,g),i) =
+ (((G.base.target (x,i)).1, g + (G.displacement (x,i)).2), (G.base.target (x,i)).2) := rfl
+
+/-- The port component of the displacement bijects each source bundle's
+ordered segments with the old ports at the destination. -/
+def bundlePort [AddCommGroup H] (G : LiftedSlots V D (H × L)) (port : H ≃ Fin D)
+ (b : (V × L) × Fin D) : Equiv.Perm (Fin D) :=
+ port.symm.trans ((Equiv.addRight (G.displacement (b.1.1,b.2)).1).trans port)
+
+@[simp] theorem bundlePort_apply [AddCommGroup H] (G : LiftedSlots V D (H × L))
+ (port : H ≃ Fin D) (b : (V × L) × Fin D) (j : Fin D) :
+ bundlePort G port b j = port (port.symm j + (G.displacement (b.1.1,b.2)).1) := rfl
+
+/-- Express the original matching in bundle coordinates. The destination
+block and slot are independent of the source segment, which is relabeled by
+the port translation of the old arc. -/
+theorem actualTarget_bundleCoordinates [AddCommGroup H] [AddCommGroup L]
+ (G : LiftedSlots V D (H × L)) (port : H ≃ Fin D) (b : (V × L) × Fin D) (j : Fin D) :
+ bundleCoordinates port (G.actualTarget ((bundleCoordinates port).symm (b,j))) =
+ (bundleTarget G b, bundlePort G port b j) := rfl
+
+/-- A slot is external, internal, or a copy of the cyclic padding arc. -/
+abbrev RefreshSlot (dH d₀ : ℕ) := Fin 1 ⊕ (Fin dH ⊕ Fin (d₀ - (dH + 1)))
+
+/-- Number the three classes of slots in their stated order. -/
+def refreshSlots (hd : dH + 1 ≤ d₀) : RefreshSlot dH d₀ ≃ Fin d₀ :=
+ ((Equiv.refl (Fin 1)).sumCongr finSumFinEquiv).trans
+ (finSumFinEquiv.trans (finCongr (by omega)))
+
+private def refreshTarget (G : SlotGraph V D) (P : SlotGraph (Fin D) dH) :
+ Equiv.Perm ((V × Fin D) × RefreshSlot dH d₀) where
+ toFun
+ | (p, .inl k) => (G.target p, .inl k)
+ | ((v,j), .inr (.inl k)) => ((v,(P.target (j,k)).1), .inr (.inl (P.target (j,k)).2))
+ | ((v,j), .inr (.inr k)) => ((v,finRotate D j), .inr (.inr k))
+ invFun
+ | (p, .inl k) => (G.target.symm p, .inl k)
+ | ((v,j), .inr (.inl k)) =>
+ ((v,(P.target.symm (j,k)).1), .inr (.inl (P.target.symm (j,k)).2))
+ | ((v,j), .inr (.inr k)) => ((v,(finRotate D).symm j), .inr (.inr k))
+ left_inv p := by
+ rcases p with ⟨⟨v,j⟩, k | k | k⟩ <;> simp [-finRotate_apply, -finRotate_symm_apply]
+ right_inv p := by
+ rcases p with ⟨⟨v,j⟩, k | k | k⟩ <;> simp [-finRotate_apply, -finRotate_symm_apply]
+
+private theorem rotate_ne_self (hD : 1 < D) (j : Fin D) : finRotate D j ≠ j := by
+ have : NeZero D := ⟨by omega⟩
+ rw [finRotate_apply]
+ intro h
+ have hz : (1 : Fin D) = 0 := add_left_cancel (a := j) (show j + 1 = j + 0 by simpa using h)
+ have := congrArg Fin.val hz
+ simp [Nat.mod_eq_of_lt hD] at this
+
+/-- The new base slot graph has degree exactly `d₀` in both directions
+and each arc joins distinct base vertices. -/
+def refreshBase (G : SlotGraph V D) (P : SlotGraph (Fin D) dH) (hD : 1 < D)
+ (hd : dH + 1 ≤ d₀) : SlotGraph (V × Fin D) d₀ where
+ target :=
+ let e := (Equiv.refl (V × Fin D)).prodCongr (refreshSlots hd)
+ e.symm.trans ((refreshTarget G P).trans e)
+ ends_ne := by
+ rintro ⟨⟨v,j⟩, i⟩
+ obtain ⟨k | k | k, rfl⟩ := (refreshSlots hd).surjective i
+ · simpa [refreshTarget] using fun he : G.target (v,j) = (v,j) =>
+ G.ends_ne (v,j) (congrArg Prod.fst he)
+ · simpa [refreshTarget] using P.ends_ne (j,k)
+ · simpa [refreshTarget] using rotate_ne_self hD j
+
+/-- The sole external wire preserves the old shift on the remaining lane.
+All internal wires and cyclic padding wires have zero displacement. -/
+def degreeRefresh [Zero L] (G : LiftedSlots V D (H × L)) (P : SlotGraph (Fin D) dH)
+ (hD : 1 < D) (hd : dH + 1 ≤ d₀) : LiftedSlots (V × Fin D) d₀ L where
+ base := refreshBase G.base P hD hd
+ displacement := fun p => match (refreshSlots hd).symm p.2 with
+ | .inl _ => (G.displacement p.1).2
+ | .inr _ => 0
+
+variable [AddCommGroup L] (G : LiftedSlots V D (H × L)) (P : SlotGraph (Fin D) dH)
+ (hD : 1 < D) (hd : dH + 1 ≤ d₀)
+
+-- Apply the three slot-specific simp rules before the generic `LiftedSlots.actualGraph_target`.
+/-- The old outgoing slot is the source port of the bundled external wire;
+the old incoming slot is its destination port. -/
+@[simp high] theorem degreeRefresh_external (p : V × Fin D) (g : L) :
+ (degreeRefresh G P hD hd).actualGraph.target ((p,g), refreshSlots hd (.inl 0)) =
+ ((G.base.target p, g + (G.displacement p).2), refreshSlots hd (.inl 0)) := by
+ simp [LiftedSlots.actualGraph_target, degreeRefresh, refreshBase, refreshTarget]
+
+/-- Expander slots connect ports of the same block with the expander's
+specified outgoing and incoming slot numbers. -/
+@[simp high] theorem degreeRefresh_internal (v : V) (j : Fin D) (g : L) (k : Fin dH) :
+ (degreeRefresh G P hD hd).actualGraph.target
+ (((v,j),g), refreshSlots hd (.inr (.inl k))) =
+ (((v,(P.target (j,k)).1),g), refreshSlots hd (.inr (.inl (P.target (j,k)).2))) := by
+ simp [LiftedSlots.actualGraph_target, degreeRefresh, refreshBase, refreshTarget]
+
+/-- Each padding slot is a separate copy of the edge to the cyclic successor. -/
+@[simp high] theorem degreeRefresh_padding (v : V) (j : Fin D) (g : L) (k : Fin (d₀ - (dH + 1))) :
+ (degreeRefresh G P hD hd).actualGraph.target
+ (((v,j),g), refreshSlots hd (.inr (.inr k))) =
+ (((v,finRotate D j),g), refreshSlots hd (.inr (.inr k))) := by
+ simp [LiftedSlots.actualGraph_target, degreeRefresh, refreshBase, refreshTarget]
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DegreeRefreshWidths.lean b/lean/OAI/Computability/VPVNP/DegreeRefreshWidths.lean
new file mode 100644
index 0000000000..6e548c00a9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DegreeRefreshWidths.lean
@@ -0,0 +1,203 @@
+import OAI.Computability.VPVNP.DegreeRefresh
+import OAI.Computability.VPVNP.DegreeRefreshTopology
+
+/-!
+# Widths on the refreshed slots
+
+Each port has one concatenated external field, one field per internal expander
+arc, and zero bits on every padding arc. This module charges the resulting
+actual slots in the paper's normalization and derives the bound (7.3) from
+the internal motif's bound with masses divided by the old arc mass.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.DegreeRefresh
+
+variable {B : Type*} [Fintype B] {D dH d₀ : ℕ}
+
+/-- Widths of the external, internal and padding slots, respectively. -/
+def newWidths (hd : dH + 1 ≤ d₀) (w : Widths B D) (s : B → Fin D × Fin dH → ℕ)
+ (u : B × Fin D) (k : Fin d₀) : ℕ :=
+ match (refreshSlots hd).symm k with
+ | .inl _ => ∑ j, w u j
+ | .inr (.inl h) => s u.1 (u.2,h)
+ | .inr (.inr _) => 0
+
+/-- Energy of the expander slots in a single block. -/
+noncomputable def internalEnergy (p' : ℝ) (s : Fin D × Fin dH → ℕ) : ℝ :=
+ ∑ e, (s e : ℝ) ^ 2 / p'
+
+theorem newWidths_energy (hd : dH + 1 ≤ d₀) (w : Widths B D) (s : B → Fin D × Fin dH → ℕ)
+ (p' : ℝ) :
+ (∑ u, ∑ k, (newWidths hd w s u k : ℝ) ^ 2 / p') =
+ externalEnergy p' w + ∑ z, internalEnergy p' (s z) := by
+ have localEnergy (u : B × Fin D) :
+ (∑ k, (newWidths hd w s u k : ℝ) ^ 2 / p') =
+ ((∑ j, w u j : ℕ) : ℝ) ^ 2 / p' + ∑ h, (s u.1 (u.2,h) : ℝ) ^ 2 / p' := by
+ rw [← (refreshSlots hd).sum_comp (fun k ↦ (newWidths hd w s u k : ℝ) ^ 2 / p')]
+ simp [Fintype.sum_sum_type, newWidths]
+ simp only [localEnergy, Finset.sum_add_distrib, internalEnergy, externalEnergy, Fintype.sum_prod_type]
+
+omit [Fintype B] in
+/-- The internal motif inequality uses demand mass one and supply mass
+`D / d₀`. Multiplying by the reciprocal old arc mass restores the actual
+energies used in the network. -/
+theorem internalEnergy_of_motif (target : Equiv.Perm (B × Fin D))
+ (lane : B × Fin D → Equiv.Perm (Fin D)) (w : Widths B D) (s : Fin D × Fin dH → ℕ) (z : B)
+ {H' C p p' : ℝ} (hp : 0 < p) (hd₀ : 0 < d₀)
+ (hmass : (D : ℝ) * p = d₀ * p')
+ (hterm : (∑ e, (s e : ℝ) ^ 2 / ((D : ℝ) / d₀)) ≤
+ H' * (∑ t : Tie D, (tieWidth target lane w z t : ℝ) ^ 2) + C) :
+ internalEnergy p' s ≤ H' * demandEnergy p target lane w z + C / p := by
+ have hd₀' : 0 < (d₀ : ℝ) := Nat.cast_pos.mpr hd₀
+ have heq : (D : ℝ) / d₀ * p = p' := by
+ rw [div_mul_eq_mul_div, div_eq_iff hd₀'.ne', mul_comm p']
+ exact hmass
+ have h := div_le_div_of_nonneg_right hterm hp.le
+ simp only [div_eq_mul_inv, Finset.sum_mul, add_mul, mul_assoc] at h
+ simp only [internalEnergy, demandEnergy, div_eq_mul_inv, Finset.mul_sum]
+ have hscale : (↑D * (↑d₀ : ℝ)⁻¹)⁻¹ * p⁻¹ = p'⁻¹ := by
+ rw [← mul_inv, ← heq, div_eq_mul_inv]
+ simpa only [hscale, Finset.mul_sum, mul_assoc] using h
+
+/-- The network estimate (7.3) for the actual refreshed widths, including
+the zero-width padding slots. `B` indexes blocks of `D` ports. The leading
+coefficient is independent of `D` whenever the chosen motif coefficient is. -/
+theorem newWidths_energy_le [Nonempty B] (hd : dH + 1 ≤ d₀) (hD : 0 < D)
+ (target : Equiv.Perm (B × Fin D)) (lane : B × Fin D → Equiv.Perm (Fin D))
+ (w : Widths B D) (s : B → Fin D × Fin dH → ℕ) {H' C : ℝ} (hH : 0 ≤ H')
+ (hterm : ∀ z, (∑ e, (s z e : ℝ) ^ 2 / ((D : ℝ) / d₀)) ≤
+ H' * (∑ t : Tie D, (tieWidth target lane w z t : ℝ) ^ 2) + C) :
+ let P := (Fintype.card B : ℝ) * D
+ (∑ u, ∑ k, (newWidths hd w s u k : ℝ) ^ 2 / (1 / (P * d₀))) ≤
+ (d₀ + 2 * H') * oldEnergy (1 / (P * D)) w + C * P ^ 2 := by
+ let P := (Fintype.card B : ℝ) * D
+ let p := 1 / (P * D)
+ let p' := 1 / (P * d₀)
+ have hd₀ : 0 < d₀ := by omega
+ have hD' : 0 < (D : ℝ) := Nat.cast_pos.mpr hD
+ have hd₀' : 0 < (d₀ : ℝ) := Nat.cast_pos.mpr hd₀
+ have hB : 0 < (Fintype.card B : ℝ) := Nat.cast_pos.mpr Fintype.card_pos
+ have hP : 0 < P := mul_pos hB hD'
+ have hp : 0 < p := by dsimp [p]; positivity
+ have hp' : 0 < p' := by dsimp [p']; positivity
+ have hm : (D : ℝ) * p = d₀ * p' := by dsimp [p,p']; field_simp
+ have ho : 1 / p = (Fintype.card B : ℝ) * D * D := by simp [p,P]
+ dsimp only
+ rw [newWidths_energy]
+ exact refresh_energy_le target lane w (fun z ↦ internalEnergy p' (s z)) hp hp' hH hm ho
+ (fun z ↦ internalEnergy_of_motif target lane w _ z hp hd₀ hm (hterm z))
+
+omit [Fintype B] in
+/-- For fixed degrees and motif coefficients, every new slot has width
+bounded by a constant times one plus the maximum old width. The same bound
+applies to the concatenated fields read by the external segment ties. -/
+theorem newWidths_max_le (hd : dH + 1 ≤ d₀) (hD : 0 < D)
+ (target : Equiv.Perm (B × Fin D)) (lane : B × Fin D → Equiv.Perm (Fin D))
+ (w : Widths B D) (s : B → Fin D × Fin dH → ℕ) {H' C : ℝ} (hH : 0 ≤ H') (hC : 0 ≤ C)
+ (hterm : ∀ z, (∑ e, (s z e : ℝ) ^ 2 / ((D : ℝ) / d₀)) ≤
+ H' * (∑ t : Tie D, (tieWidth target lane w z t : ℝ) ^ 2) + C)
+ {W : ℕ} (hw : ∀ e i, w e i ≤ W) (u : B × Fin D) (k : Fin d₀) :
+ (newWidths hd w s u k : ℝ) ≤
+ max (D : ℝ) (Real.sqrt (((D : ℝ) / d₀) * (H' * Fintype.card (Tie D) + C))) * (W + 1) := by
+ let q := (D : ℝ) / d₀
+ have hq : 0 < q := div_pos (Nat.cast_pos.mpr hD) (Nat.cast_pos.mpr (by omega))
+ let A := q * (H' * Fintype.card (Tie D) + C)
+ have hA : 0 ≤ A := mul_nonneg hq.le (add_nonneg (mul_nonneg hH (Nat.cast_nonneg _)) hC)
+ have hW : 0 ≤ (W : ℝ) + 1 := by positivity
+ obtain ⟨i | h | j,rfl⟩ := (refreshSlots hd).surjective k
+ · simp only [newWidths, Equiv.symm_apply_apply, Nat.cast_sum]
+ have hx : (∑ j : Fin D, (w u j : ℝ)) ≤ ∑ _ : Fin D, ((W : ℝ) + 1) :=
+ Finset.sum_le_sum fun j _ ↦ (Nat.cast_le.mpr (hw u j)).trans (le_add_of_nonneg_right zero_le_one)
+ simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] at hx
+ exact hx.trans (mul_le_mul_of_nonneg_right (le_max_left _ _) hW)
+ · simp only [newWidths, Equiv.symm_apply_apply]
+ have ht (t : Tie D) : tieWidth target lane w u.1 t ≤ W := by
+ unfold tieWidth incoming
+ split_ifs <;> exact hw _ _
+ have htSum : (∑ t : Tie D, (tieWidth target lane w u.1 t : ℝ) ^ 2) ≤
+ (Fintype.card (Tie D) : ℝ) * ((W : ℝ) + 1) ^ 2 := by
+ have hsum := Finset.sum_le_sum (s := Finset.univ) fun t _ ↦
+ pow_le_pow_left₀ (Nat.cast_nonneg (α := ℝ) (tieWidth target lane w u.1 t))
+ ((Nat.cast_le.mpr (ht t)).trans (le_add_of_nonneg_right zero_le_one)) 2
+ simpa only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul] using hsum
+ have hsum := Finset.single_le_sum (s := Finset.univ) (fun (i : Fin D × Fin dH) _ ↦
+ div_nonneg (sq_nonneg (s u.1 i : ℝ)) hq.le) (Finset.mem_univ (u.2,h))
+ have hsmall := (div_le_iff₀ hq).mp (hsum.trans (hterm u.1))
+ have hC' := le_mul_of_one_le_right hC (one_le_pow₀ (by linarith only [Nat.cast_nonneg (α := ℝ) W]
+ : 1 ≤ (W : ℝ) + 1) (n := 2))
+ have hscale := mul_le_mul_of_nonneg_right
+ (add_le_add (mul_le_mul_of_nonneg_left htSum hH) hC') hq.le
+ have hs : (s u.1 (u.2,h) : ℝ) ≤ √A * (W + 1) := by
+ apply (sq_le_sq₀ (Nat.cast_nonneg _) (mul_nonneg (Real.sqrt_nonneg _) hW)).mp
+ rw [mul_pow, Real.sq_sqrt hA]
+ exact hsmall.trans (hscale.trans_eq (by unfold A; ring))
+ exact hs.trans (mul_le_mul_of_nonneg_right (le_max_right _ _) hW)
+ · simp only [newWidths, Equiv.symm_apply_apply, Nat.cast_zero]
+ exact mul_nonneg ((Nat.cast_nonneg D).trans (le_max_left _ _)) hW
+
+section ActualSlots
+
+variable {V H L : Type*}
+
+/-- Present the actual old width profile in the source order of each bundle. -/
+def bundleWidths (port : H ≃ Fin D) (w : (V × Fin D) × (H × L) → ℕ) : Widths (V × L) D :=
+ fun b j ↦ w ((bundleCoordinates port).symm (b,j))
+
+/-- Group actual refreshed slots by their block and port, followed by their
+outgoing slot number. -/
+def refreshedCoordinates : (((V × Fin D) × Fin d₀) × L) ≃ (((V × L) × Fin D) × Fin d₀) where
+ toFun p := (((p.1.1.1,p.2),p.1.1.2),p.1.2)
+ invFun p := (((p.1.1.1,p.1.2),p.2),p.1.1.2)
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+/-- The profile assigned to the actual slots of the new lifted topology. -/
+def actualWidths (hd : dH + 1 ≤ d₀) (port : H ≃ Fin D) (w : (V × Fin D) × (H × L) → ℕ)
+ (s : (V × L) → Fin D × Fin dH → ℕ) (a : ((V × Fin D) × Fin d₀) × L) : ℕ :=
+ newWidths hd (bundleWidths port w) s (refreshedCoordinates a).1 (refreshedCoordinates a).2
+
+variable [Fintype V] [Fintype H] [Fintype L]
+
+private theorem bundleWidths_energy (port : H ≃ Fin D) (w : (V × Fin D) × (H × L) → ℕ) (p : ℝ) :
+ oldEnergy p (bundleWidths port w) = ∑ a, (w a : ℝ) ^ 2 / p := by
+ unfold oldEnergy
+ rw [← Fintype.sum_prod_type']
+ exact (bundleCoordinates port).symm.sum_comp (fun a ↦ (w a : ℝ) ^ 2 / p)
+
+/-- Equation (7.3) in the original and refreshed actual-arc coordinates. The
+two half-wire ties use the old graph's residual-lane shift and its port shift,
+so all widths may vary with the lane. -/
+theorem actualWidths_energy_le [Nonempty V] [Nonempty L] [AddCommGroup H] [AddCommGroup L]
+ (G : LiftedSlots V D (H × L)) (port : H ≃ Fin D) (hd : dH + 1 ≤ d₀) (hD : 0 < D)
+ (w : (V × Fin D) × (H × L) → ℕ) (s : (V × L) → Fin D × Fin dH → ℕ)
+ {H' C : ℝ} (hH : 0 ≤ H')
+ (hterm : ∀ z, (∑ e, (s z e : ℝ) ^ 2 / ((D : ℝ) / d₀)) ≤
+ H' * (∑ t : Tie D, (tieWidth (bundleTarget G) (bundlePort G port) (bundleWidths port w) z t : ℝ) ^ 2) + C) :
+ let P := (Fintype.card (V × (H × L)) : ℝ)
+ (∑ a, (actualWidths hd port w s a : ℝ) ^ 2 / (1 / (P * d₀))) ≤
+ (d₀ + 2 * H') * (∑ a, (w a : ℝ) ^ 2 / (1 / (P * D))) + C * P ^ 2 := by
+ have hcard : Fintype.card (V × (H × L)) = Fintype.card (V × L) * D := by
+ rw [Fintype.card_prod, Fintype.card_prod, Fintype.card_congr port, Fintype.card_fin, Fintype.card_prod]
+ ring
+ dsimp only
+ rw [hcard, Nat.cast_mul]
+ have hh := newWidths_energy_le hd hD (bundleTarget G) (bundlePort G port) (bundleWidths port w) s hH hterm
+ dsimp only at hh
+ rw [bundleWidths_energy] at hh
+ apply le_trans (le_of_eq ?_) hh
+ rw [← Fintype.sum_prod_type']
+ exact refreshedCoordinates.sum_comp (fun u ↦
+ (newWidths hd (bundleWidths port w) s u.1 u.2 : ℝ) ^ 2 /
+ (1 / ((Fintype.card (V × L) : ℝ) * D * d₀)))
+
+end ActualSlots
+
+end Compression.DegreeRefresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DeterminantQueries.lean b/lean/OAI/Computability/VPVNP/DeterminantQueries.lean
new file mode 100644
index 0000000000..431c1c9e32
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DeterminantQueries.lean
@@ -0,0 +1,174 @@
+import OAI.Computability.VPVNP.DeterminantQueryBounds
+import OAI.Computability.VPVNP.RankQuery
+
+/-!
+# Computing matrix rank by querying a weighted determinant
+
+The Appendix D.2 rank algorithm scans bidegrees in the reverse characteristic
+polynomial of the weighted Gram matrix. A fixed degree in a Gram entry reads
+at most two scalar entries of the original matrix. The Schur coefficient query
+then evaluates the entire determinant at a single bidegree. The proofs cover
+empty matrices, rank zero, and characteristic two.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+section WeightedGramQuery
+
+open Polynomial
+
+variable {K : Type*} [CommRing K] {n m : ℕ}
+
+/-- A tagged Gram entry has at most one contributing column in each degree. -/
+def weightedGramEntryCoeff (M : Matrix (Fin n) (Fin m) K) (i j : Fin n) (z : ℕ) : K :=
+ if h : i.val + 2 ≤ z ∧ z - i.val - 2 < m then
+ let k : Fin m := ⟨z - i.val - 2, h.2⟩
+ M i k * M j k
+ else 0
+
+theorem weightedGramEntryCoeff_eq (M : Matrix (Fin n) (Fin m) K) (i j : Fin n) (z : ℕ) :
+ weightedGramEntryCoeff M i j z = ((weightedGram M) i j).coeff z := by
+ have hentry : (weightedGram M) i j = ∑ k : Fin m,
+ C (M i k * M j k) * X ^ (i.val + k.val + 2) := by
+ rw [weightedGram, Matrix.mul_apply]
+ apply Finset.sum_congr rfl
+ intro k _
+ simp only [weightDiagonal, Matrix.mul_diagonal, Matrix.diagonal_mul, Matrix.map_apply,
+ Matrix.transpose_apply, map_mul]
+ rw [show i.val + k.val + 2 = (i.val + 1) + (k.val + 1) by omega, pow_add X (i.val + 1) (k.val + 1)]
+ ac_rfl
+ rw [hentry, finsetSum_coeff]
+ simp_rw [coeff_C_mul_X_pow]
+ unfold weightedGramEntryCoeff
+ split_ifs with h
+ · let k : Fin m := ⟨z - i.val - 2, h.2⟩
+ rw [Finset.sum_eq_single k]
+ · rw [ite_eq_left (by dsimp [k]; omega)]
+ · intro l _ hl
+ rw [ite_eq_right]
+ intro heq
+ apply hl
+ apply Fin.ext
+ dsimp [k]
+ omega
+ · simp
+ · symm
+ apply Finset.sum_eq_zero
+ intro k _
+ rw [ite_eq_right]
+ have := k.isLt
+ omega
+
+/-- Scan a consecutive interval and return its maximum score, or zero if empty. -/
+def streamMaximum (n : ℕ) (f : Fin n → ℕ) : ℕ :=
+ Fin.foldl n (fun best i => max best (f i)) 0
+
+theorem streamMaximum_le_iff (n b : ℕ) (f : Fin n → ℕ) :
+ streamMaximum n f ≤ b ↔ ∀ i, f i ≤ b := by
+ induction n with
+ | zero => simp [streamMaximum]
+ | succ n ih =>
+ rw [streamMaximum, Fin.foldl_succ_last]
+ change max (streamMaximum n fun i => f i.castSucc) (f (Fin.last n)) ≤ b ↔ _
+ rw [max_le_iff, ih]
+ exact ⟨fun h i => Fin.lastCases h.2 (fun i => h.1 i) i,
+ fun h => ⟨fun i => h i.castSucc, h (Fin.last n)⟩⟩
+
+theorem le_streamMaximum {n : ℕ} (f : Fin n → ℕ) (i : Fin n) :
+ f i ≤ streamMaximum n f :=
+ (streamMaximum_le_iff n _ f).mp le_rfl i
+
+theorem indexWeight_le {q n : ℕ} (I : Set.powersetCard (Fin n) q) :
+ indexWeight I ≤ q * n := by
+ rw [indexWeight_eq_sum]
+ calc
+ _ ≤ ∑ _i : Fin q, n := Finset.sum_le_sum fun i _ =>
+ Nat.succ_le_of_lt (Set.powersetCard.ofFinEmbEquiv.symm I i).isLt
+ _ = q * n := by simp
+
+/-- The inner degree at outer degree `u` is at most `u(n+m)`. -/
+theorem rankPolynomial_coeff_natDegree_le {K : Type*} [CommRing K] {n m : ℕ}
+ (M : Matrix (Fin n) (Fin m) K) (u : ℕ) :
+ ((rankPolynomial M).coeff u).natDegree ≤ u * (n + m) := by
+ classical
+ apply natDegree_le_iff_coeff_eq_zero.mpr
+ intro z hz
+ have sign : (-1 : K[X]) ^ u = C ((-1 : K) ^ u) := by simp
+ rw [rankPolynomial_coeff, sign, coeff_C_mul, finsetSum_coeff]
+ apply mul_eq_zero_of_right
+ apply Finset.sum_eq_zero
+ intro i _
+ rw [finsetSum_coeff]
+ apply Finset.sum_eq_zero
+ intro j _
+ rw [← map_pow, mul_comm, coeff_C_mul_X_pow, ite_eq_right]
+ have hi := indexWeight_le i
+ have hj := indexWeight_le j
+ rw [Nat.mul_add] at hz
+ omega
+
+/-- Recover rank by scanning scalar bidegree queries. The scans include both
+endpoints and keep only the current indices and maximum degree. -/
+def scanRank {K : Type*} [Zero K] [DecidableEq K] (n m : ℕ) (q : ℕ → ℕ → K) : ℕ :=
+ streamMaximum (n + 1) fun u => streamMaximum ((n + m) * n + 1) fun z =>
+ if q u.val z.val = 0 then 0 else u.val
+
+theorem scanRank_correct {K : Type*} [Field K] [DecidableEq K] {n m : ℕ}
+ (M : Matrix (Fin n) (Fin m) K) (q : ℕ → ℕ → K)
+ (hq : ∀ u z, q u z = ((rankPolynomial M).coeff u).coeff z) :
+ scanRank n m q = M.rank := by
+ let score (u : Fin (n + 1)) (z : Fin ((n + m) * n + 1)) :=
+ if q u.val z.val = 0 then 0 else u.val
+ change (streamMaximum (n + 1) fun u => streamMaximum ((n + m) * n + 1) (score u)) = M.rank
+ apply le_antisymm
+ · apply (streamMaximum_le_iff ..).mpr
+ intro u
+ apply (streamMaximum_le_iff ..).mpr
+ intro z
+ dsimp [score]
+ split_ifs with hzero
+ · exact Nat.zero_le _
+ · rw [← rankPolynomial_natDegree M]
+ apply le_natDegree_of_ne_zero
+ intro hu
+ exact hzero (by rw [hq, hu, coeff_zero])
+ · by_cases hpoly : rankPolynomial M = 0
+ · simp [← rankPolynomial_natDegree M, hpoly]
+ have htop : (rankPolynomial M).coeff M.rank ≠ 0 := by
+ rw [← rankPolynomial_natDegree M, coeff_natDegree, leadingCoeff_ne_zero]
+ exact hpoly
+ let u : Fin (n + 1) := ⟨M.rank, Nat.lt_succ_of_le M.rank_le_height⟩
+ have bound : ((rankPolynomial M).coeff M.rank).natDegree ≤ (n + m) * n := calc
+ _ ≤ M.rank * (n + m) := rankPolynomial_coeff_natDegree_le M M.rank
+ _ ≤ n * (n + m) := Nat.mul_le_mul_right _ M.rank_le_height
+ _ = _ := Nat.mul_comm _ _
+ let z : Fin ((n + m) * n + 1) :=
+ ⟨((rankPolynomial M).coeff M.rank).natDegree, Nat.lt_succ_of_le bound⟩
+ have hscalar : q u.val z.val ≠ 0 := by
+ rw [hq]
+ change ((rankPolynomial M).coeff M.rank).coeff ((rankPolynomial M).coeff M.rank).natDegree ≠ 0
+ rwa [coeff_natDegree, leadingCoeff_ne_zero]
+ calc
+ M.rank = score u z := by simp [score, hscalar, u]
+ _ ≤ streamMaximum _ (score u) := le_streamMaximum _ z
+ _ ≤ streamMaximum _ _ := le_streamMaximum (fun i => streamMaximum _ (score i)) u
+
+/-- Rank computed by querying scalar coefficients of the weighted Gram determinant. -/
+def rankQuery [DecidableEq K] (M : Matrix (Fin n) (Fin m) K) : ℕ :=
+ scanRank n m (determinantQuery (weightedGramEntryCoeff M))
+
+end WeightedGramQuery
+
+theorem rankQuery_eq {K : Type*} [Field K] [DecidableEq K] {n m : ℕ} (M : Matrix (Fin n) (Fin m) K) :
+ rankQuery M = M.rank :=
+ scanRank_correct M _ (determinantQuery_eq (weightedGram M) _ (weightedGramEntryCoeff_eq M))
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DeterminantQueryBounds.lean b/lean/OAI/Computability/VPVNP/DeterminantQueryBounds.lean
new file mode 100644
index 0000000000..45b9a1db27
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DeterminantQueryBounds.lean
@@ -0,0 +1,281 @@
+import OAI.Computability.VPVNP.SchurCoefficientQueries
+import Mathlib.Tactic.Ring
+
+/-!
+# Recomputation bounds for the determinant query
+
+The call counts model the two nested recursions of Appendix D.2, including
+every repeated request for a coefficient. A rank scan on a rectangular matrix
+with dimensions bounded by `2^p` makes `2^O(p²)` scalar-query visits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+/-- Number of calls (including the root) made when every branch of a power
+entry query on an `n × n` matrix is recomputed. Each degree split at each
+intermediate index calls both children. -/
+def powerQueryVisits (n h z : ℕ) : ℕ :=
+ if h ≤ 1 then 1
+ else 1 + n * ∑ d ∈ Finset.antidiagonal z,
+ (powerQueryVisits n (h / 2) d.1 + powerQueryVisits n (h - h / 2) d.2)
+termination_by Nat.clog 2 h
+decreasing_by
+ · exact (powerQuery_halves (by omega)).1
+ · exact (powerQuery_halves (by omega)).2
+
+/-- Full recomputation of a matrix-power coefficient makes at most
+`(1 + 2n(z+1))^⌈log₂ h⌉` calls. -/
+theorem powerQueryVisits_le (n h z : ℕ) :
+ powerQueryVisits n h z ≤ (1 + 2 * n * (z + 1)) ^ Nat.clog 2 h := by
+ let B := 1 + 2 * n * (z + 1)
+ have aux (depth : ℕ) : ∀ t q, Nat.clog 2 t ≤ depth → q ≤ z →
+ powerQueryVisits n t q ≤ B ^ depth := by
+ induction depth with
+ | zero =>
+ intro t q ht _
+ have hsmall := (Nat.clog_le_iff_le_pow (b := 2) (by decide)).mp ht
+ have ht' : t ≤ 1 := by simpa using hsmall
+ simp [powerQueryVisits, ht']
+ | succ depth ih =>
+ intro t q ht hq
+ by_cases hsmall : t ≤ 1
+ · rw [powerQueryVisits, ite_eq_left hsmall]
+ exact Nat.one_le_pow _ _ (by dsimp [B]; omega)
+ have hhalves := powerQuery_halves (Nat.lt_of_not_ge hsmall)
+ have hsum : (∑ d ∈ Finset.antidiagonal q,
+ (powerQueryVisits n (t / 2) d.1 + powerQueryVisits n (t - t / 2) d.2)) ≤
+ (z + 1) * (B ^ depth + B ^ depth) := by
+ calc
+ _ ≤ ∑ _d ∈ Finset.antidiagonal q, (B ^ depth + B ^ depth) := by
+ refine Finset.sum_le_sum fun d hd => ?_
+ have hd' : d.1 + d.2 = q := Finset.mem_antidiagonal.mp hd
+ exact Nat.add_le_add (ih _ _ (by omega) (by omega)) (ih _ _ (by omega) (by omega))
+ _ = (q + 1) * (B ^ depth + B ^ depth) := by simp [Finset.Nat.card_antidiagonal]
+ _ ≤ _ := Nat.mul_le_mul_right _ (by omega)
+ have hpos : 1 ≤ B ^ depth := Nat.one_le_pow _ _ (by dsimp [B]; omega)
+ rw [powerQueryVisits, ite_eq_right hsmall, pow_succ]
+ calc
+ 1 + _ ≤ B ^ depth + n * ((z + 1) * (B ^ depth + B ^ depth)) :=
+ Nat.add_le_add hpos (Nat.mul_le_mul_left _ hsum)
+ _ = B ^ depth * B := by dsimp [B]; ring
+ exact aux _ h z le_rfl le_rfl
+
+/-- For indices of at most exponential magnitude, the full tree of repeated
+power coefficient queries has singly exponential size. -/
+theorem powerQueryVisits_le_exp (n h z p : ℕ)
+ (hn : n ≤ 2 ^ p) (hh : h ≤ 2 ^ p) (hz : z ≤ 2 ^ p) :
+ powerQueryVisits n h z ≤ 2 ^ ((2 * p + 3) * p) := by
+ have hdepth : Nat.clog 2 h ≤ p := Nat.clog_le_of_le_pow hh
+ have hpos : 1 ≤ 2 ^ p := Nat.one_le_pow _ _ (by decide)
+ have hz' : z + 1 ≤ 2 * 2 ^ p := by omega
+ have hbase : 1 + 2 * n * (z + 1) ≤ 2 ^ (2 * p + 3) := calc
+ _ ≤ 1 + 2 * 2 ^ p * (2 * 2 ^ p) :=
+ Nat.add_le_add_left (Nat.mul_le_mul (Nat.mul_le_mul_left _ hn) hz') _
+ _ ≤ 8 * (2 ^ p * 2 ^ p) := by
+ have hp := Nat.mul_le_mul hpos hpos
+ ring_nf at hp ⊢
+ omega
+ _ = 2 ^ (2 * p + 3) := by rw [two_mul p, pow_add, pow_add]; ring
+ calc
+ powerQueryVisits n h z ≤ _ := powerQueryVisits_le n h z
+ _ ≤ (2 ^ (2 * p + 3)) ^ Nat.clog 2 h := Nat.pow_le_pow_left hbase _
+ _ ≤ (2 ^ (2 * p + 3)) ^ p := Nat.pow_le_pow_right (Nat.pow_pos (by decide)) hdepth
+ _ = _ := (pow_mul _ _ _).symm
+
+/-- Count calls in the same balanced recursion as the bivariate coefficient query.
+An empty leaf costs one visit. A nonempty leaf incurs its supplied cost, which
+can include the recursion used to evaluate the factor. -/
+def balancedBivariateVisits (leafCost : ℕ → ℕ → ℕ → ℕ) (depth first count u z : ℕ) : ℕ :=
+ balancedProduct (fun _ : ℕ × ℕ => 1)
+ (fun left right p => 1 + streamAntiSum p.1 fun a₁ a₂ => streamAntiSum p.2 fun b₁ b₂ =>
+ left (a₁, b₁) + right (a₂, b₂))
+ (fun i p => leafCost i p.1 p.2) depth first count (u, z)
+
+/-- Count all recursive calls, including empty and padded leaves. No restriction
+on the starting index or the number of factors is needed for the bound. -/
+theorem balancedBivariateVisits_le (leafCost : ℕ → ℕ → ℕ → ℕ) (depth first count u z L : ℕ)
+ (hL : 1 ≤ L) (hleaf : ∀ i a b, a ≤ u → b ≤ z → leafCost i a b ≤ L) :
+ balancedBivariateVisits leafCost depth first count u z ≤
+ L * (1 + 2 * (u + 1) * (z + 1)) ^ depth := by
+ let B := 1 + 2 * (u + 1) * (z + 1)
+ have aux (d : ℕ) : ∀ i c a b, a ≤ u → b ≤ z →
+ balancedBivariateVisits leafCost d i c a b ≤ L * B ^ d := by
+ induction d with
+ | zero =>
+ intro i c a b ha hb
+ by_cases hc : c = 0 <;>
+ simp [balancedBivariateVisits, balancedProduct, hc, hL, hleaf i a b ha hb]
+ | succ d ih =>
+ intro i c a b ha hb
+ let W := L * B ^ d
+ have hpos : 1 ≤ W := by
+ exact Nat.mul_le_mul hL (Nat.one_le_pow _ _ (by dsimp [B]; omega))
+ change 1 + (streamAntiSum a fun a₁ a₂ => streamAntiSum b fun b₁ b₂ =>
+ balancedBivariateVisits leafCost d i (c / 2) a₁ b₁ +
+ balancedBivariateVisits leafCost d (i + c / 2) (c - c / 2) a₂ b₂) ≤ _
+ simp_rw [streamAntiSum_eq]
+ calc
+ 1 + _ ≤ W + ∑ _e ∈ Finset.antidiagonal a, ∑ _f ∈ Finset.antidiagonal b, (W + W) := by
+ refine Nat.add_le_add hpos (Finset.sum_le_sum fun e he => Finset.sum_le_sum fun f hf => ?_)
+ have hea := Finset.mem_antidiagonal.mp he
+ have hfb := Finset.mem_antidiagonal.mp hf
+ exact Nat.add_le_add (ih _ _ _ _ (by omega) (by omega))
+ (ih _ _ _ _ (by omega) (by omega))
+ _ = W + (a + 1) * ((b + 1) * (W + W)) := by simp [Finset.Nat.card_antidiagonal]
+ _ ≤ W + (u + 1) * ((z + 1) * (W + W)) :=
+ Nat.add_le_add_left (Nat.mul_le_mul (by omega) (Nat.mul_le_mul_right _ (by omega))) _
+ _ = L * B ^ (d + 1) := by dsimp [W]; rw [pow_succ]; dsimp [B]; ring
+ exact aux depth first count u z le_rfl le_rfl
+
+/-- With a unit cost per terminal coefficient query this counts the product
+recursion alone. -/
+theorem balancedBivariateVisits_unit_le (depth first count u z : ℕ) :
+ balancedBivariateVisits (fun _ _ _ => 1) depth first count u z ≤
+ (1 + 2 * (u + 1) * (z + 1)) ^ depth := by
+ simpa using balancedBivariateVisits_le (fun _ _ _ => 1) depth first count u z 1
+ le_rfl (fun _ _ _ _ _ => le_rfl)
+
+/-- Exponential bounds on the degree ranges and on a leaf query compose with
+the balanced recursion to give a singly exponential recomputation bound. -/
+theorem balancedBivariateVisits_le_exp (leafCost : ℕ → ℕ → ℕ → ℕ)
+ (depth first count u z p l : ℕ) (hd : depth ≤ p) (hu : u ≤ 2 ^ p) (hz : z ≤ 2 ^ p)
+ (hleaf : ∀ i a b, a ≤ u → b ≤ z → leafCost i a b ≤ 2 ^ l) :
+ balancedBivariateVisits leafCost depth first count u z ≤ 2 ^ (l + (2 * p + 4) * p) := by
+ have hp : 1 ≤ 2 ^ p := Nat.one_le_pow _ _ (by decide)
+ have hbase : 1 + 2 * (u + 1) * (z + 1) ≤ 2 ^ (2 * p + 4) := calc
+ _ ≤ 1 + 2 * (2 * 2 ^ p) * (2 * 2 ^ p) :=
+ Nat.add_le_add_left (Nat.mul_le_mul (Nat.mul_le_mul_left _ (by omega)) (by omega)) _
+ _ ≤ 16 * (2 ^ p * 2 ^ p) := by
+ have hp' := Nat.mul_le_mul hp hp
+ ring_nf at hp' ⊢
+ omega
+ _ = 2 ^ (2 * p + 4) := by rw [two_mul p, pow_add, pow_add]; ring
+ apply (balancedBivariateVisits_le leafCost depth first count u z _ (Nat.one_le_pow _ _ (by decide))
+ hleaf).trans
+ rw [pow_add, pow_mul]
+ apply Nat.mul_le_mul_left
+ exact (Nat.pow_le_pow_left hbase _).trans (Nat.pow_le_pow_right (Nat.pow_pos (by decide)) hd)
+
+/-- Number of scalar coefficient queries in one Schur factor, including the
+factor query itself. A matrix-power base case counts as one visit. At each
+higher bidegree, every degree split reads the last entry once and each inner
+split reads the first entry and evaluates one trailing matrix power. -/
+def headFactorVisits (n u z : ℕ) : ℕ :=
+ match u with
+ | 0 => 1
+ | 1 => 2
+ | h + 2 => 1 + n * n * streamAntiSum z fun d₁ _ =>
+ 1 + streamAntiSum d₁ fun _ e₂ => 1 + powerQueryVisits n h e₂
+
+private theorem streamAntiSum_le (q W : ℕ) (f : ℕ → ℕ → ℕ)
+ (hf : ∀ i j, i + j = q → f i j ≤ W) : streamAntiSum q f ≤ (q + 1) * W := by
+ rw [streamAntiSum_eq]
+ calc
+ _ ≤ ∑ _e ∈ Finset.antidiagonal q, W :=
+ Finset.sum_le_sum fun e he => hf _ _ (Finset.mem_antidiagonal.mp he)
+ _ = _ := by simp [Finset.Nat.card_antidiagonal]
+
+/-- Bounding the two matrix indices and both streamed degree splits, together
+with all calls of the power-entry recursion, gives a singly exponential bound. -/
+theorem headFactorVisits_le_exp (n u z p : ℕ) (hn : n ≤ 2 ^ p) (hu : u ≤ 2 ^ p)
+ (hz : z ≤ 2 ^ p) : headFactorVisits n u z ≤ 2 ^ (4 * p + 5 + (2 * p + 3) * p) := by
+ let N := 2 ^ p
+ let E := 2 ^ ((2 * p + 3) * p)
+ have hN : 1 ≤ N := Nat.one_le_pow _ _ (by decide)
+ have hE : 1 ≤ E := Nat.one_le_pow _ _ (by decide)
+ have hresult : 2 ^ (4 * p + 5 + (2 * p + 3) * p) = 32 * N ^ 4 * E := by
+ rw [pow_add, pow_add, mul_comm 4 p, pow_mul]
+ dsimp [N, E]
+ ring
+ rw [hresult]
+ have hNE : 1 ≤ N * E := Nat.mul_le_mul hN hE
+ have hN4E : 1 ≤ N ^ 4 * E := Nat.mul_le_mul (Nat.one_le_pow _ _ hN) hE
+ rcases u with _ | _ | h
+ · simp only [headFactorVisits]; rw [mul_assoc]; omega
+ · simp only [headFactorVisits]; rw [mul_assoc]; omega
+ have hsplit (d : ℕ) (hd : d ≤ z) :
+ streamAntiSum d (fun _ e₂ => 1 + powerQueryVisits n h e₂) ≤ 4 * (N * E) := by
+ calc
+ _ ≤ (d + 1) * (2 * E) := streamAntiSum_le _ _ _ fun i j hij => by
+ have ht := powerQueryVisits_le_exp n h j p hn (by omega) (by omega)
+ change powerQueryVisits n h j ≤ E at ht
+ omega
+ _ ≤ (2 * N) * (2 * E) := Nat.mul_le_mul_right _ (by change z ≤ N at hz; omega)
+ _ = _ := by ring
+ have houter : streamAntiSum z (fun d _ => 1 +
+ streamAntiSum d (fun _ e₂ => 1 + powerQueryVisits n h e₂)) ≤ 16 * N ^ 2 * E := by
+ calc
+ _ ≤ (z + 1) * (8 * (N * E)) := streamAntiSum_le _ _ _ fun i j hij => by
+ have ht := hsplit i (by omega)
+ omega
+ _ ≤ (2 * N) * (8 * (N * E)) := Nat.mul_le_mul_right _ (by change z ≤ N at hz; omega)
+ _ = _ := by ring
+ change 1 + n * n * _ ≤ _
+ calc
+ _ ≤ 1 + N * N * (16 * N ^ 2 * E) :=
+ Nat.add_le_add_left (Nat.mul_le_mul (Nat.mul_le_mul hn hn) houter) _
+ _ = 1 + 16 * (N ^ 4 * E) := by ring
+ _ ≤ 32 * N ^ 4 * E := by rw [mul_assoc]; omega
+
+/-- Calls made by one determinant coefficient query. Its leaves use the
+corresponding trailing matrix size, and all identity leaves cost one visit. -/
+def determinantQueryVisits (n u z : ℕ) : ℕ :=
+ balancedBivariateVisits
+ (fun i a b => if i < n then headFactorVisits (n - i - 1) a b else 1)
+ (Nat.clog 2 n) 0 n u z
+
+/-- The complete coefficient query, including both the product recursion and
+the Schur-factor power recursions, makes at most exponentially many visits
+when the dimension and both degrees have at most `p + 1` bits. -/
+theorem determinantQueryVisits_le_exp (n u z p : ℕ)
+ (hn : n ≤ 2 ^ p) (hu : u ≤ 2 ^ p) (hz : z ≤ 2 ^ p) :
+ determinantQueryVisits n u z ≤ 2 ^ (4 * p + 5 + (2 * p + 3) * p + (2 * p + 4) * p) := by
+ apply balancedBivariateVisits_le_exp _ _ _ _ _ _ _ _ (Nat.clog_le_of_le_pow hn) hu hz
+ intro i a b ha hb
+ split_ifs
+ · exact headFactorVisits_le_exp _ _ _ p (by omega) (ha.trans hu) (hb.trans hz)
+ · exact Nat.one_le_pow _ _ (by decide)
+
+/-- Total scalar-query visits over the complete rectangular scan used by
+`rankQuery`, with full recomputation at every bidegree. -/
+def rankQueryVisits (n m : ℕ) : ℕ :=
+ ∑ u : Fin (n + 1), ∑ z : Fin ((n + m) * n + 1), determinantQueryVisits n u.val z.val
+
+/-- The complete rank scan is singly exponential when both dimensions have
+at most `p + 1` bits. Its inner degree needs at most `2*p+2` bits. -/
+theorem rankQueryVisits_le_exp (n m p : ℕ) (hn : n ≤ 2 ^ p) (hm : m ≤ 2 ^ p) :
+ let s := 2 * p + 1
+ rankQueryVisits n m ≤ 2 ^ (p + 1 + (s + 1) +
+ (4 * s + 5 + (2 * s + 3) * s + (2 * s + 4) * s)) := by
+ let s := 2 * p + 1
+ let c := 4 * s + 5 + (2 * s + 3) * s + (2 * s + 4) * s
+ have hdim : n ≤ 2 ^ s := hn.trans (Nat.pow_le_pow_right (by decide) (by dsimp [s]; omega))
+ have hdegree : (n + m) * n ≤ 2 ^ s := calc
+ _ ≤ (2 ^ p + 2 ^ p) * 2 ^ p := Nat.mul_le_mul (Nat.add_le_add hn hm) hn
+ _ = _ := by dsimp [s]; rw [two_mul p, pow_add, pow_add]; ring
+ have hterms (u : Fin (n + 1)) (z : Fin ((n + m) * n + 1)) :
+ determinantQueryVisits n u.val z.val ≤ 2 ^ c :=
+ determinantQueryVisits_le_exp n _ _ s hdim ((Nat.lt_succ_iff.mp u.isLt).trans hdim)
+ ((Nat.lt_succ_iff.mp z.isLt).trans hdegree)
+ have hsucc (k t : ℕ) (h : k ≤ 2 ^ t) : k + 1 ≤ 2 ^ (t + 1) := by
+ rw [pow_succ]
+ have ht : 1 ≤ 2 ^ t := Nat.one_le_pow _ _ (by decide)
+ omega
+ change _ ≤ 2 ^ (p + 1 + (s + 1) + c)
+ calc
+ rankQueryVisits n m ≤ ∑ _u : Fin (n + 1), ∑ _z : Fin ((n + m) * n + 1), 2 ^ c :=
+ Finset.sum_le_sum fun u _ => Finset.sum_le_sum fun z _ => hterms u z
+ _ = (n + 1) * (((n + m) * n + 1) * 2 ^ c) := by simp
+ _ ≤ 2 ^ (p + 1) * (2 ^ (s + 1) * 2 ^ c) :=
+ Nat.mul_le_mul (hsucc _ _ hn) (Nat.mul_le_mul_right _ (hsucc _ _ hdegree))
+ _ = _ := by simp only [pow_add, mul_assoc]
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Diagonal.lean b/lean/OAI/Computability/VPVNP/Diagonal.lean
new file mode 100644
index 0000000000..0f6690dd35
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Diagonal.lean
@@ -0,0 +1,187 @@
+import Mathlib.Algebra.Algebra.Basic
+import Mathlib.Algebra.BigOperators.Ring.Finset
+import Mathlib.Algebra.Module.LinearMap.Basic
+import Mathlib.Data.Fintype.BigOperators
+
+/-!
+# The paired-chain contraction in Proposition 9.1
+
+`Cut` indexes all assignments to the exterior cuts of the primed pairs.
+`Path ξ i μ` indexes the successful local paths for pair `i` at exterior
+assignment `ξ` and nominated production histogram `μ`. The weights below
+are the values of the corresponding label monomials in the coefficient algebra.
+
+The algebraic argument uses linearity only after multiplying the weights of
+all the pairs. The local simulation, equality with the original contraction,
+and realization by the live program are explicit hypotheses of the criterion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Diagonal
+
+open scoped BigOperators
+
+variable {Cut Pair Hist A k : Type*}
+variable [Fintype Cut] [Fintype Pair] [DecidableEq Pair] [Fintype Hist]
+variable {Path : Cut → Pair → Hist → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+variable [Field k] [CommRing A] [Algebra k A]
+
+/-- Sum of the tail contributions over cuts, nominations, and local paths. -/
+def evaluationMode
+ (Φ : A →ₗ[k] k) (label : Hist → A)
+ (gadget : ∀ ξ i μ, Path ξ i μ → A) : k :=
+ ∑ ξ, ∑ h : Pair → Hist, ∑ q : (i : Pair) → Path ξ i (h i),
+ Φ (∏ i, label (h i) * gadget ξ i (h i) (q i))
+
+/-- Equation (9.5) evaluated in the coefficient algebra, using the
+production coefficients in (9.4). -/
+def primedContraction (label : Hist → A) (coeff : Cut → Pair → Hist → ℕ) : A :=
+ ∑ ξ, ∏ i, ∑ μ, label μ * (coeff ξ i μ : A)
+
+/-- Equation (9.2), with an assignment to the shared bits split into the
+exterior cuts `ξ` and the internal bits `s i` of each pair. The sites in
+pair `i` contribute the product of their integer path counts. -/
+def originalContraction
+ {Internal : Pair → Type*} [∀ i, Fintype (Internal i)] {Site : Type*} [Fintype Site]
+ (paths : Cut → (i : Pair) → Internal i → Site → ℕ) : ℕ :=
+ ∑ ξ, ∑ s : (i : Pair) → Internal i, ∏ i, ∏ v, paths ξ i (s i) v
+
+/-- Replacing the site counts using (8.1) and expanding each pair by
+(9.4) preserves the original contraction, as in (9.3) and (9.5). -/
+theorem primedContraction_eq_original
+ {Internal : Pair → Type*} [∀ i, Fintype (Internal i)] {Site : Type*} [Fintype Site]
+ (paths : Cut → (i : Pair) → Internal i → Site → ℕ)
+ (grammar : Cut → (i : Pair) → Internal i → Site → A)
+ (label : Hist → A) (coeff : Cut → Pair → Hist → ℕ)
+ (hsite : ∀ ξ i s v, grammar ξ i s v = (paths ξ i s v : A))
+ (hexpand : ∀ ξ i, (∑ μ, label μ * (coeff ξ i μ : A)) =
+ ∑ s, ∏ v, grammar ξ i s v) :
+ primedContraction label coeff = (originalContraction paths : A) := by
+ unfold primedContraction originalContraction
+ simp_rw [hexpand, hsite, Fintype.prod_sum]
+ push_cast
+ rfl
+
+/-- The weighted path identities for individual pairs determine the entire
+evaluation-mode sum, even when the tail functional is not multiplicative. -/
+theorem evaluationMode_eq
+ (Φ : A →ₗ[k] k) (label : Hist → A) (coeff : Cut → Pair → Hist → ℕ)
+ (gadget : ∀ ξ i μ, Path ξ i μ → A)
+ (hsim : ∀ ξ i μ, ∑ q, gadget ξ i μ q = (coeff ξ i μ : A)) :
+ evaluationMode Φ label gadget = Φ (primedContraction label coeff) := by
+ unfold evaluationMode primedContraction
+ simp only [← map_sum]
+ congr 1
+ apply Finset.sum_congr rfl
+ intro ξ _
+ rw [Fintype.prod_sum]
+ apply Finset.sum_congr rfl
+ intro h _
+ rw [← Fintype.prod_sum (fun i q => label (h i) * gadget ξ i (h i) q)]
+ simp_rw [← Finset.mul_sum, hsim]
+
+/-- The value of a label monomial with the given vector of exponents. -/
+def labelMonomial {Label : Type*} [Fintype Label] (values : Label → A)
+ (exponents : Label → ℕ) : A :=
+ ∏ j, values j ^ exponents j
+
+omit [DecidableEq Pair] in
+/-- Adding the exponents along the chain produces the same element of the
+coefficient algebra as multiplying the local label monomials. -/
+theorem labelMonomial_accumulate {Label : Type*} [Fintype Label] (values : Label → A)
+ (exponents : Pair → Label → ℕ) :
+ labelMonomial values (fun j => ∑ i, exponents i j) =
+ ∏ i, labelMonomial values (exponents i) := by
+ unfold labelMonomial
+ simp_rw [← Finset.prod_pow_eq_pow_sum]
+ rw [Finset.prod_comm]
+
+/-- Apply the evaluator to the accumulated exponents exactly once at the tail
+of the chain. Its scalar contributions then sum to the evaluation-mode count. -/
+theorem evaluationMode_accumulated
+ {Production Gadget : Type*} [Fintype Production] [Fintype Gadget]
+ (Φ : A →ₗ[k] k) (productionValues : Production → A) (κ : Gadget → A)
+ (μ : Hist → Production → ℕ) (ν : ∀ ξ i h, Path ξ i h → Gadget → ℕ) :
+ (∑ ξ, ∑ h : Pair → Hist, ∑ q : (i : Pair) → Path ξ i (h i),
+ Φ (labelMonomial productionValues (fun j => ∑ i, μ (h i) j) *
+ labelMonomial κ (fun j => ∑ i, ν ξ i (h i) (q i) j))) =
+ evaluationMode Φ (fun h => labelMonomial productionValues (μ h))
+ (fun ξ i h q => labelMonomial κ (ν ξ i h q)) := by
+ unfold evaluationMode
+ apply Finset.sum_congr rfl
+ intro ξ _
+ apply Finset.sum_congr rfl
+ intro h _
+ apply Finset.sum_congr rfl
+ intro q _
+ rw [labelMonomial_accumulate productionValues (fun i => μ (h i)),
+ labelMonomial_accumulate κ (fun i => ν ξ i (h i) (q i)), Finset.prod_mul_distrib]
+
+/-- Algebraic contradiction of Proposition 9.1. The count `Y` is the
+original integer path count. The primed contraction represents that count
+in `A`, while the live program counts one unit path plus evaluation mode
+in `k`. Taking `k = ZMod p` gives the paper's contradiction modulo `p`. -/
+theorem pairedChainCriterion
+ (Y : ℕ) (Φ : A →ₗ[k] k) (hunit : Φ 1 = 1)
+ (label : Hist → A) (coeff : Cut → Pair → Hist → ℕ)
+ (gadget : ∀ ξ i μ, Path ξ i μ → A)
+ (hsim : ∀ ξ i μ, ∑ q, gadget ξ i μ q = (coeff ξ i μ : A))
+ (hprimed : primedContraction label coeff = (Y : A))
+ (hlive : (Y : k) = 1 + evaluationMode Φ label gadget) : False := by
+ have hscalar : Φ (Y : A) = (Y : k) := by
+ calc
+ Φ (Y : A) = Φ (Y • (1 : A)) := by rw [nsmul_one]
+ _ = Y • (1 : k) := by rw [map_nsmul, hunit]
+ _ = (Y : k) := nsmul_one Y
+ rw [evaluationMode_eq Φ label coeff gadget hsim, hprimed, hscalar] at hlive
+ exact one_ne_zero (add_right_cancel (hlive.symm.trans (zero_add (Y : k)).symm))
+
+/-- The configurations counted by the original chain. For fixed cut bits and
+internal bits, each site chooses one of its accepting paths independently. -/
+abbrev OriginalPaths
+ {Internal : Pair → Type*} {Site : Type*}
+ (paths : Cut → (i : Pair) → Internal i → Site → ℕ) :=
+ (ξ : Cut) × (s : (i : Pair) → Internal i) × ((i : Pair) → (v : Site) → Fin (paths ξ i (s i) v))
+
+/-- The paths produced by the two live modes. In evaluation mode the tail
+has a separate contribution for each sequence of branch choices. -/
+abbrev LiveModes
+ (tail : ∀ ξ (h : Pair → Hist), ((i : Pair) → Path ξ i (h i)) → ℕ) :=
+ Unit ⊕ ((ξ : Cut) × (h : Pair → Hist) × (q : (i : Pair) → Path ξ i (h i)) × Fin (tail ξ h q))
+
+/-- Proposition 9.1 in terms of the asserted path bijection, sitewise
+coefficient equations, local weighted simulations, and tail path counts.
+Canonical cut fields and padding in the live program ensure that its
+evaluation mode has exactly the path multiplicities in `LiveModes`. -/
+theorem noPairedChainSimulation
+ {Internal : Pair → Type*} [∀ i, Fintype (Internal i)] {Site : Type*} [Fintype Site]
+ (paths : Cut → (i : Pair) → Internal i → Site → ℕ)
+ (grammar : Cut → (i : Pair) → Internal i → Site → A)
+ (Φ : A →ₗ[k] k) (hunit : Φ 1 = 1)
+ (label : Hist → A) (coeff : Cut → Pair → Hist → ℕ)
+ (gadget : ∀ ξ i μ, Path ξ i μ → A)
+ (tail : ∀ ξ (h : Pair → Hist), ((i : Pair) → Path ξ i (h i)) → ℕ)
+ (hsite : ∀ ξ i s v, grammar ξ i s v = (paths ξ i s v : A))
+ (hexpand : ∀ ξ i, (∑ μ, label μ * (coeff ξ i μ : A)) =
+ ∑ s, ∏ v, grammar ξ i s v)
+ (hsim : ∀ ξ i μ, ∑ q, gadget ξ i μ q = (coeff ξ i μ : A))
+ (heval : ∀ ξ h q, (tail ξ h q : k) = Φ (∏ i, label (h i) * gadget ξ i (h i) (q i))) :
+ IsEmpty (OriginalPaths paths ≃ LiveModes tail) := by
+ classical
+ constructor
+ intro e
+ apply pairedChainCriterion (originalContraction paths) Φ hunit label coeff gadget hsim
+ (primedContraction_eq_original paths grammar label coeff hsite hexpand)
+ have hcount : originalContraction paths = 1 + ∑ ξ, ∑ h, ∑ q, tail ξ h q := by
+ simpa [OriginalPaths, LiveModes, originalContraction] using Fintype.card_congr e
+ rw [hcount]
+ simp [evaluationMode, heval]
+
+end Diagonal
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/DiagonalClock.lean b/lean/OAI/Computability/VPVNP/DiagonalClock.lean
new file mode 100644
index 0000000000..dbaaa5fbaa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/DiagonalClock.lean
@@ -0,0 +1,111 @@
+import OAI.Computability.VPVNP.PolynomialBounds
+import OAI.Computability.VPVNP.LiveEvaluatorTail
+import OAI.Computability.VPVNP.RAMParameters
+import OAI.Computability.VPVNP.RAMClock
+
+/-! # Choosing the length and field widths of the diagonal chain
+
+Section 9.1 fixes the chain height using the evaluator's running time before
+choosing the processor-address multiplier. The exponent width itself depends
+on the height. The evaluator's polynomial factor in that width is absorbed
+in the tail clock without increasing the exponent of its exponential factor.
+The cut-width exponent is also chosen before the processor multiplier, since
+its quartic word width is eventually at most the input length for each fixed
+multiplier.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace DiagonalClock
+
+open Filter BurstRAM LiveEvaluatorEncoding
+
+private theorem power_bound {f : ℕ → ℕ} (hf : PolynomiallyBounded f) :
+ ∃ c : ℕ, 1 ≤ c ∧ ∀ᶠ n : ℕ in atTop, f n ≤ n^c := by
+ obtain ⟨A,d,N,h⟩ := hf
+ refine ⟨d+1, by omega, ?_⟩
+ filter_upwards [eventually_ge_atTop A, eventually_ge_atTop N] with n ha hn
+ rw [pow_succ, Nat.mul_comm]
+ exact (h n hn).trans (Nat.mul_le_mul_right _ ha)
+
+/-- On exponent inputs of width `Z=2 n^a`, the singly exponential evaluator
+fits in the `2^(n^a-1)` tail groups. The polynomial degree in `Z` may be
+arbitrary, and the choice of `a` depends only on the exponent envelope. -/
+theorem tail_clock {P : ℕ → ℕ} (hp : PolynomiallyBounded P) : ∃ a : ℕ, 2 ≤ a ∧ ∀ k : ℕ,
+ ∀ᶠ n : ℕ in atTop, 2^(P n) * (2*n^a+1)^k ≤ 2^(n^a-1) := by
+ obtain ⟨c,hc,hP⟩ := power_bound hp
+ let a := c+2
+ refine ⟨a, by dsimp [a]; omega, fun k => ?_⟩
+ filter_upwards [hP, eventually_ge_atTop (max 3 ((a+2)*k+2))] with n hn hn'
+ have hn3 := (le_max_left ..).trans hn'
+ have hm := (le_max_right ..).trans hn'
+ have hpos : 0 < n^a := Nat.pow_pos (by omega)
+ have hsmall : 2*n^a+1 ≤ n^(a+2) := by
+ rw [pow_add n a 2]
+ have hnn : 3 ≤ n^2 := by rw [pow_two]; nlinarith
+ exact (by omega : 2*n^a+1 ≤ n^a*3).trans (Nat.mul_le_mul_left _ hnn)
+ have hpw : n^((a+2)*k) ≤ 2^(n*((a+2)*k)) := by
+ rw [pow_mul 2 n ((a+2)*k)]
+ exact Nat.pow_le_pow_left Nat.lt_two_pow_self.le _
+ have he : n^c + n*((a+2)*k) < n^a := by
+ have hcn : n ≤ n^c := by simpa using Nat.pow_le_pow_right (by omega : 0 < n) hc
+ have hterm : n*((a+2)*k) ≤ n^c*((a+2)*k) := Nat.mul_le_mul_right _ hcn
+ have hn2 : 1 + (a+2)*k < n^2 := by rw [pow_two]; nlinarith
+ change n^c + n*((a+2)*k) < n^(c+2)
+ rw [pow_add n c 2]
+ calc
+ _ ≤ n^c * (1 + (a+2)*k) := by rw [Nat.mul_add, Nat.mul_one]; omega
+ _ < n^c * n^2 := Nat.mul_lt_mul_of_pos_left hn2 (Nat.pow_pos (by omega))
+ calc
+ _ ≤ 2^(n^c) * (n^(a+2))^k := Nat.mul_le_mul
+ (Nat.pow_le_pow_right (by decide) hn) (Nat.pow_le_pow_left hsmall _)
+ _ ≤ 2^(n^c) * 2^(n*((a+2)*k)) := Nat.mul_le_mul_left _ (by rw [← pow_mul]; exact hpw)
+ _ = 2^(n^c + n*((a+2)*k)) := (pow_add ..).symm
+ _ ≤ 2^(n^a-1) := Nat.pow_le_pow_right (by decide) (by omega)
+
+/-- The order of choices of `a,d₁,d₂,B` for the evaluator. A polynomial tape
+radius at every fixed polynomial exponent width suffices, independently of
+its exponentially larger clock. -/
+theorem parameters {P advice labels : ℕ → ℕ} (radius : ℕ → ℕ → ℕ)
+ (hp : PolynomiallyBounded P) (ha : PolynomiallyBounded advice)
+ (ht : PolynomiallyBounded labels)
+ (hr : ∀ a, PolynomiallyBounded fun n => radius n (2*n^a)) (E : UniversalMachine.Program) :
+ ∃ a d₁ d₂ : ℕ, 2 ≤ a ∧ ∀ k B : ℕ, 1 ≤ B → ∀ᶠ n : ℕ in atTop,
+ let Z := 2*n^a
+ let w := (addressWidth B n + 10)^4
+ 2^(P n) * (Z+1)^k ≤ 2^(n^a-1) ∧ advice n ≤ n^d₁ ∧
+ 1 + labels n * Z ≤ n^d₂ ∧ LiveEvaluatorTail.Layout E.extra (radius n Z) w (n^d₂) := by
+ obtain ⟨a,ha2,hclock⟩ := tail_clock hp
+ obtain ⟨d₁,_,had⟩ := power_bound ha
+ let space := hr a
+ have hf : PolynomiallyBounded (fun n => fieldWords (radius n (2*n^a))) :=
+ (((PolynomiallyBounded.const 1).add (((PolynomiallyBounded.const 2).mul space).add (.const 1))).add
+ (((PolynomiallyBounded.const 2).mul space).add (.const 1)))
+ have hz := (PolynomiallyBounded.const 2).mul (PolynomiallyBounded.id.pow a)
+ obtain ⟨d₂,_,hΔ⟩ := power_bound (((PolynomiallyBounded.const 1).add (ht.mul hz)).add
+ ((PolynomiallyBounded.const 1).add (hf.mul PolynomiallyBounded.id)))
+ refine ⟨a,d₁,d₂,ha2,fun k B hB => ?_⟩
+ filter_upwards [hclock k, had, hΔ, eventually_word_stage_le B 0,
+ eventually_ge_atTop (2^(E.extra+2))] with n time adviceFits cutFits word hn
+ have hr' : addressWidth B n ≤ B*(n.log2+1) := Nat.mul_le_mul_left _ (clog_le_log2_succ n)
+ have hw := (word _ 0 hr' (by simp)).1
+ dsimp only at cutFits ⊢
+ refine ⟨time, adviceFits, by omega, ?_⟩
+ constructor
+ · have hg : 2 ≤ addressWidth B n + 10 := by omega
+ exact (by decide : 2 ≤ 2^4).trans (Nat.pow_le_pow_left hg _)
+ · have he : E.extra+2 ≤ n.log2 := (Nat.le_log2 (by have := Nat.two_pow_pos (E.extra+2); omega)).mpr hn
+ have h₀ := log2_le_addressWidth hB n
+ have h₁ : addressWidth B n + 10 ≤ (addressWidth B n + 10)^4 := by
+ simpa using Nat.pow_le_pow_right (by omega : 0 < addressWidth B n + 10) (by decide : 1 ≤ 4)
+ exact (he.trans (h₀.trans ((by omega : addressWidth B n ≤ addressWidth B n + 10).trans h₁))).trans Nat.lt_two_pow_self.le
+ · have := Nat.mul_le_mul_left (fieldWords (radius n (2*n^a))) hw
+ omega
+
+end DiagonalClock
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EffectiveNullstellensatz.lean b/lean/OAI/Computability/VPVNP/EffectiveNullstellensatz.lean
new file mode 100644
index 0000000000..3ccac725c1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EffectiveNullstellensatz.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.GraphCertificateExtraction
+import OAI.Computability.VPVNP.LinearNormalization
+import OAI.Computability.VPVNP.MacaulayRelations
+import OAI.Computability.VPVNP.MonicGraphRelation
+import OAI.Computability.VPVNP.PerronBounds
+import OAI.Computability.VPVNP.PerronRelation
+
+/-! # The effective weak Nullstellensatz bound for the evaluator
+
+Section 8.2 uses the multiplier bound `(2D)^(4(n+2))` over algebraically
+closed fields. We prove it using the graph of the equation values, a linear
+Noether normalization, and a bounded Perron relation. Integral closedness
+makes the minimal relation monic, and taking its top parameter coefficient
+gives a bounded certificate. This also supplies the effective hypothesis
+in the Macaulay row test of Appendix D.1.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+open MvPolynomial
+
+/-- Every inconsistent degree-`D` system in `n` variables has a certificate of the
+explicit degree used in the paper. The equation count and the characteristic are arbitrary. -/
+theorem effective_weakCertificateBound (E I : Type*) [Field E] [IsAlgClosed E] [Fintype I]
+ {n D : ℕ} (hD : 3 ≤ D) :
+ WeakCertificateBound E I n D ((2 * D) ^ (4 * (n + 2))) := by
+ classical
+ intro F hF hno
+ obtain ⟨Q, hQ, hinj, hint⟩ := LinearNormalization.exists_linear_normalization
+ (graphGenerator F) (graphGenerator_adjoin F hno)
+ let T : MvPolynomial (Fin (n+1)) E := X 0
+ let g : Fin ((n+1)+1) → MvPolynomial (Fin (n+1)) E := Fin.cons T Q
+ have hd (j : Fin ((n+1)+1)) : (g j).totalDegree ≤ D+1 :=
+ Fin.cases (by simp [g, T]) (fun i => graphGenerator_span_degree F hF (hQ i)) j
+ obtain ⟨W, hW, hWdeg, hWzero⟩ := perron_relation g hd
+ obtain ⟨U, hmonic, hzero, _, hdeg⟩ := monic_relation_of_relation Q T hinj (hint T) W hW hWzero
+ obtain ⟨A, hA, hcert⟩ := graph_monic_certificate F hF Q hQ U (hdeg.trans hWdeg) hmonic hzero
+ refine ⟨A, fun i => (hA i).trans ?_, hcert⟩
+ apply le_trans _ (perronSimplexBound_le_paper_envelope hD)
+ let B := perronSimplexBound (n + 1) (D + 1)
+ change (D + 1) * B ≤ 2 * (D + 1) * (B + 1)^2
+ exact Nat.mul_le_mul (by omega) (by nlinarith only [Nat.zero_le (B*B)])
+
+/-- The actual effective bound in the evaluator's row-space test for radical membership.
+The tested polynomial and the matrix may be defined over a smaller base field. -/
+theorem row_test_effective {K E I : Type*} [Field K] [Field E] [Algebra K E] [IsAlgClosed E]
+ [Fintype I] {n d R₀ P : ℕ} (hd : 3 ≤ d) (F : I → MvPolynomial (Fin n) K)
+ (f : MvPolynomial (Fin n) K) (hF : ∀ i, (F i).totalDegree ≤ d) (hf : f.totalDegree ≤ R₀)
+ (hP : (2 * max d (R₀+1)) ^ (4 * (n+3)) ≤ P) (hpos : P ≠ 0) :
+ let H := (2 * max d (R₀+1)) ^ (4 * (n+3))
+ (∀ x : Fin n → E, (∀ i, aeval x (F i) = 0) → aeval x f = 0) ↔
+ coefficientRow (H + P * R₀ + d) (f ^ P) ∈ Submodule.span K
+ (Set.range (macaulayMatrix F (H + P * R₀) (H + P * R₀ + d)).row) :=
+ row_test_of_weakCertificateBound F f hP hpos hF hf
+ (effective_weakCertificateBound E (Option I) (hd.trans (le_max_left ..)))
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Evaluator.lean b/lean/OAI/Computability/VPVNP/Evaluator.lean
new file mode 100644
index 0000000000..2393c8ec17
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Evaluator.lean
@@ -0,0 +1,250 @@
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Algebra.BigOperators.Group.Finset.Sigma
+import Mathlib.Data.ZMod.Basic
+import Mathlib.FieldTheory.Finite.Basic
+import Mathlib.LinearAlgebra.Matrix.ToLin
+
+/-!
+# Counting a monomial in a finite algebra
+
+The evaluator of Section 8.2 processes base-`Q` digits most significant first
+using the linear maps for Frobenius and multiplication by a label. Once a
+basis of the coefficient algebra containing `1` is given, an index path
+through their matrices contributes a product of entries in the slice field.
+The final prime-field coordinate of this product determines the number of
+accepting branches.
+
+`finiteAlgebra_pathCount` proves equation (8.2) for these branches, and
+`digitProgram_length_le` bounds the number of linear steps. The construction
+of a slice and the algorithms for querying individual matrix entries are
+separate parts of Theorem 8.1 and Appendix D.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator
+
+section Digits
+
+variable (K : Type*) [Field K] [Fintype K]
+variable {A : Type*} [CommRing A] [Algebra K A] {t : ℕ}
+
+/-- The linear steps for one digit position. The `i`th digit is `d i`. -/
+def digitSteps (X : Fin t → A) (d : Fin t → ℕ) : List (A →ₗ[K] A) :=
+ (FiniteField.frobeniusAlgHom K A).toLinearMap ::
+ (List.finRange t).flatMap (fun i => List.replicate (d i) (LinearMap.mulLeft K (X i)))
+
+/-- The linear program for the low `width` base-`#K` digits of every exponent.
+The recursive call on the quotients processes the more significant digits first. -/
+def digitProgram (X : Fin t → A) : ℕ → (Fin t → ℕ) → List (A →ₗ[K] A)
+ | 0, _ => []
+ | width + 1, e =>
+ digitProgram X width (fun i => e i / Fintype.card K) ++
+ digitSteps K X (fun i => e i % Fintype.card K)
+
+omit [Fintype K] in
+private lemma apply_repeated_label (x v : A) (d : ℕ) :
+ (List.replicate d (LinearMap.mulLeft K x)).foldl (fun a M => M a) v = v * x ^ d := by
+ induction d generalizing v with
+ | zero => simp
+ | succ d ih =>
+ rw [List.replicate_succ, List.foldl_cons, ih, pow_succ]
+ change x * v * x ^ d = v * (x ^ d * x)
+ ac_rfl
+
+omit [Fintype K] in
+private lemma apply_label_digits (X : Fin t → A) (d : Fin t → ℕ) (s : List (Fin t)) (v : A) :
+ (s.flatMap fun i => List.replicate (d i) (LinearMap.mulLeft K (X i))).foldl
+ (fun a M => M a) v = v * (s.map fun i => X i ^ d i).prod := by
+ induction s generalizing v with
+ | nil => simp
+ | cons i s ih =>
+ rw [List.flatMap_cons, List.foldl_append, apply_repeated_label, ih]
+ simp [mul_assoc]
+
+/-- A single digit raises the previous accumulator to the field cardinality and
+then multiplies by the label monomial of this digit. -/
+theorem digitSteps_eval (X : Fin t → A) (d : Fin t → ℕ) (v : A) :
+ (digitSteps K X d).foldl (fun a M => M a) v =
+ v ^ Fintype.card K * ∏ i, X i ^ d i := by
+ rw [digitSteps, List.foldl_cons, apply_label_digits, Fin.prod_univ_def]
+ rfl
+
+private lemma digitProgram_eval_of_lt (X : Fin t → A) (width : ℕ) (e : Fin t → ℕ)
+ (h : ∀ i, e i < Fintype.card K ^ width) :
+ (digitProgram K X width e).foldl (fun a M => M a) 1 = ∏ i, X i ^ e i := by
+ induction width generalizing e with
+ | zero =>
+ have he : ∀ i, e i = 0 := fun i => Nat.lt_one_iff.mp (by simpa using h i)
+ simp [digitProgram, he]
+ | succ width ih =>
+ have hdiv (i : Fin t) : e i / Fintype.card K < Fintype.card K ^ width :=
+ (Nat.div_lt_iff_lt_mul Fintype.card_pos).mpr (by simpa [pow_succ] using h i)
+ rw [digitProgram, List.foldl_append, ih _ hdiv, digitSteps_eval,
+ ← Finset.prod_pow, ← Finset.prod_mul_distrib]
+ apply Finset.prod_congr rfl
+ intro i _
+ rw [← pow_mul, ← pow_add, Nat.mul_comm (e i / Fintype.card K), Nat.div_add_mod]
+
+/-- For exponents given by `width` input bits, `width` base-`#K` digits suffice.
+Starting the linear program at the unit returns the entire label monomial. -/
+theorem digitProgram_eval (X : Fin t → A) (width : ℕ) (e : Fin t → ℕ)
+ (h : ∀ i, e i < 2 ^ width) :
+ (digitProgram K X width e).foldl (fun a M => M a) 1 = ∏ i, X i ^ e i :=
+ digitProgram_eval_of_lt K X width e fun i =>
+ (h i).trans_le (Nat.pow_le_pow_left (Fintype.one_lt_card (α := K)) width)
+
+/-- Number of linear steps, including the Frobenius step, for one digit. -/
+theorem digitSteps_length (X : Fin t → A) (d : Fin t → ℕ) :
+ (digitSteps K X d).length = 1 + ∑ i, d i := by
+ simp [digitSteps, List.length_flatMap, Fin.sum_univ_def, Nat.add_comm]
+
+/-- The linear program executes at most one Frobenius and `t * (#K - 1)` label
+multiplications per input bit. -/
+theorem digitProgram_length_le (X : Fin t → A) (width : ℕ) (e : Fin t → ℕ) :
+ (digitProgram K X width e).length ≤ width * (1 + t * (Fintype.card K - 1)) := by
+ induction width generalizing e with
+ | zero => simp [digitProgram]
+ | succ width ih =>
+ have h (i : Fin t) : e i % Fintype.card K ≤ Fintype.card K - 1 := by
+ have := Nat.mod_lt (e i) (Fintype.card_pos (α := K))
+ omega
+ have hsum : ∑ i, e i % Fintype.card K ≤ t * (Fintype.card K - 1) := by
+ simpa using Finset.sum_le_sum (s := Finset.univ) (fun i _ => h i)
+ rw [digitProgram, List.length_append, digitSteps_length, Nat.succ_mul]
+ exact Nat.add_le_add (ih _) (Nat.add_le_add_left hsum 1)
+
+end Digits
+
+section Paths
+
+/-- One index guess for each matrix factor, with a unique path when there are no factors. -/
+def IndexPath (ι : Type*) : ℕ → Type _
+ | 0 => PUnit
+ | n + 1 => ι × IndexPath ι n
+
+instance {ι : Type*} [Fintype ι] (n : ℕ) : Fintype (IndexPath ι n) := by
+ induction n with
+ | zero => exact inferInstanceAs (Fintype PUnit)
+ | succ n ih =>
+ letI : Fintype (IndexPath ι n) := ih
+ exact inferInstanceAs (Fintype (ι × IndexPath ι n))
+
+variable {ι k : Type*} [Fintype ι] [DecidableEq ι]
+
+/-- Product of entries along an index path. Ending at a different index contributes zero. -/
+def pathWeight [Semiring k] :
+ (ms : List (Matrix ι ι k)) → ι → ι → IndexPath ι ms.length → k
+ | [], start, finish, _ => if start = finish then 1 else 0
+ | m :: ms, start, finish, ⟨j, π⟩ => m start j * pathWeight ms j finish π
+
+theorem sum_pathWeight [Semiring k] (ms : List (Matrix ι ι k)) (start finish : ι) :
+ ∑ π, pathWeight ms start finish π = ms.prod start finish := by
+ induction ms generalizing start with
+ | nil =>
+ change (∑ _ : PUnit, if start = finish then (1 : k) else 0) = (1 : Matrix ι ι k) start finish
+ simp [Matrix.one_apply]
+ | cons m ms ih =>
+ change (∑ π : ι × IndexPath ι ms.length, m start π.1 * pathWeight ms π.1 finish π.2) =
+ (m * ms.prod) start finish
+ simp_rw [Fintype.sum_prod_type, ← Finset.mul_sum, ih, Matrix.mul_apply]
+
+variable {p : ℕ} [Fact p.Prime] [Field k] [Algebra (ZMod p) k]
+
+/-- Distinguish all index paths and all admissible final choices, including paths of equal weight. -/
+abbrev AcceptingBranches (coord : k →ₗ[ZMod p] ZMod p) (ms : List (Matrix ι ι k))
+ (start finish : ι) :=
+ (π : IndexPath ι ms.length) × Fin (coord (pathWeight ms start finish π)).val
+
+/-- The integer path count, reduced modulo the prime, equals the prime-field coordinate of the
+matrix product entry. The coordinate is applied once to the product of entries on each path. -/
+theorem card_acceptingBranches_cast (coord : k →ₗ[ZMod p] ZMod p)
+ (ms : List (Matrix ι ι k)) (start finish : ι) :
+ (Fintype.card (AcceptingBranches coord ms start finish) : ZMod p) =
+ coord (ms.prod start finish) := by
+ rw [← sum_pathWeight ms start finish, map_sum]
+ simp [AcceptingBranches, Fintype.card_sigma, Nat.cast_sum]
+ rfl
+
+end Paths
+
+section Basis
+
+variable {I K A : Type*} [Field K] [CommRing A] [Algebra K A]
+variable [Fintype I] [DecidableEq I]
+
+/-- At a step from index `i` to `j`, read row `j`, column `i` of the
+matrix of the linear map. Transposing puts these entries in path order. -/
+noncomputable def transitionMatrices (b : Module.Basis I K A)
+ (steps : List (A →ₗ[K] A)) : List (Matrix I I K) :=
+ steps.map (fun f => (LinearMap.toMatrixAlgEquiv b f).transpose)
+
+private theorem transition_product (b : Module.Basis I K A) (steps : List (A →ₗ[K] A)) :
+ (transitionMatrices b steps).prod.transpose =
+ LinearMap.toMatrixAlgEquiv b steps.reverse.prod := by
+ induction steps with
+ | nil => simp [transitionMatrices]
+ | cons f fs ih =>
+ simp only [transitionMatrices, List.map_cons, List.prod_cons, Matrix.transpose_mul,
+ Matrix.transpose_transpose, List.reverse_cons, List.prod_append, List.prod_nil, mul_one,
+ map_mul]
+ rw [← ih]
+ rfl
+
+private theorem reverse_prod_apply (steps : List (A →ₗ[K] A)) (a : A) :
+ steps.reverse.prod a = steps.foldl (fun v f => f v) a := by
+ induction steps generalizing a with
+ | nil => rfl
+ | cons f fs ih =>
+ simp only [List.reverse_cons, List.prod_append, List.prod_singleton, List.foldl_cons,
+ Module.End.mul_apply]
+ exact ih (f a)
+
+/-- The matrix product entry from the basis element `1` to itself gives its
+coordinate after the chronological sequence of linear maps. -/
+theorem transitionMatrices_unit_entry (b : Module.Basis I K A) (u : I) (hunit : b u = 1)
+ (steps : List (A →ₗ[K] A)) :
+ (transitionMatrices b steps).prod u u = b.coord u (steps.foldl (fun v f => f v) 1) := by
+ have h := congrArg (fun M : Matrix I I K => M u u) (transition_product b steps)
+ simpa only [Matrix.transpose_apply, LinearMap.toMatrixAlgEquiv_apply, hunit, reverse_prod_apply,
+ Module.Basis.coord_apply] using h
+
+variable {p : ℕ} [Fact p.Prime]
+variable [Algebra (ZMod p) K] [Algebra (ZMod p) A] [IsScalarTower (ZMod p) K A]
+
+/-- The first coordinate over the slice field, followed by a prime-field
+coordinate. This is the functional of Theorem 8.1. -/
+noncomputable def primeFunctional (b : Module.Basis I K A) (u : I) (coord : K →ₗ[ZMod p] ZMod p) :
+ A →ₗ[ZMod p] ZMod p :=
+ coord.comp ((b.coord u).restrictScalars (ZMod p))
+
+omit [Fintype I] [DecidableEq I] in
+theorem primeFunctional_one (b : Module.Basis I K A) (u : I) (hunit : b u = 1)
+ (coord : K →ₗ[ZMod p] ZMod p) (hcoord : coord 1 = 1) :
+ primeFunctional b u coord 1 = 1 := by
+ simp [primeFunctional, ← hunit, Module.Basis.coord_apply, hcoord]
+
+end Basis
+
+/-- Equation (8.2). For every vector of exponents fitting in `width` bits,
+the integer number of accepting branches reduces to the prime-field
+functional of the entire monomial. -/
+theorem finiteAlgebra_pathCount {p : ℕ} [Fact p.Prime] {K A I : Type*}
+ [Field K] [Fintype K] [CommRing A] [Algebra K A]
+ [Algebra (ZMod p) K] [Algebra (ZMod p) A] [IsScalarTower (ZMod p) K A]
+ [Fintype I] [DecidableEq I] (b : Module.Basis I K A) (u : I) (hunit : b u = 1)
+ (coord : K →ₗ[ZMod p] ZMod p) {t : ℕ} (X : Fin t → A) (width : ℕ) (e : Fin t → ℕ)
+ (hwidth : ∀ i, e i < 2 ^ width) :
+ (Fintype.card (AcceptingBranches coord (transitionMatrices b (digitProgram K X width e)) u u) :
+ ZMod p) = primeFunctional b u coord (∏ i, X i ^ e i) := by
+ rw [card_acceptingBranches_cast, transitionMatrices_unit_entry b u hunit,
+ digitProgram_eval _ _ _ _ hwidth]
+ rfl
+
+end Evaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorAdviceBounds.lean b/lean/OAI/Computability/VPVNP/EvaluatorAdviceBounds.lean
new file mode 100644
index 0000000000..b37370eecc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorAdviceBounds.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.EvaluatorAdviceSerialization
+import OAI.Computability.VPVNP.PerronBounds
+
+/-!
+# Size of the advice and indices of the finite slice evaluator
+
+The parameters are those of the actual coordinate slice in `LabelEvaluator`.
+Its ground field has order greater than twice the Macaulay column bound, and
+the geometric point count is bounded by the `t`th power of twice that bound.
+Both logarithms are polynomial in the input length.
+
+The advice stores the prime in an agreed width, one field element's worth
+of coefficients for the defining polynomial, one selection bit per
+coordinate, and one field element per coordinate. All these bounds hold
+uniformly over the selected prime once its width is fixed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LabelEvaluator
+
+local instance (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+
+variable {t d : ℕ → ℕ}
+
+theorem columnCountBound_clog (ht : PolynomiallyBounded t)
+ (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n)) :
+ PolynomiallyBounded fun n => Nat.clog 2 (columnCountBound (t n) (d n)) :=
+ PolynomiallyBounded.clog_pow (PolynomiallyBounded.clog_add
+ (PolynomiallyBounded.clog_add (RadicalCertificate.polynomiallyBounded_clog_paperBound ht hd) hd)
+ ((PolynomiallyBounded.const 1).clog)) ht
+
+theorem pointCountBound_clog (ht : PolynomiallyBounded t)
+ (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n)) :
+ PolynomiallyBounded fun n => Nat.clog 2 (pointCountBound (t n) (d n)) :=
+ PolynomiallyBounded.clog_pow (PolynomiallyBounded.clog_mul
+ ((PolynomiallyBounded.const 2).clog) (columnCountBound_clog ht hd)) ht
+
+/-- Uniform width of indices in the monomial list scanned by the evaluator. -/
+theorem listingBound_clog (ht : PolynomiallyBounded t)
+ (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n)) :
+ PolynomiallyBounded fun n => Nat.clog 2 ((pointCountBound (t n) (d n) + 1) ^ t n) :=
+ PolynomiallyBounded.clog_pow (PolynomiallyBounded.clog_add (pointCountBound_clog ht hd)
+ ((PolynomiallyBounded.const 1).clog)) ht
+
+/-- This is the extension degree and width used by every coefficient block. -/
+abbrev elementWidth (p : Nat.Primes) (t d : ℕ) :=
+ SliceField.extensionDegree p.val (columnCountBound t d) * Nat.clog 2 p.val
+
+theorem ground_card_eq (p : Nat.Primes) (t d : ℕ) :
+ Nat.card (Ground p t d) = p.val ^ SliceField.extensionDegree p.val (columnCountBound t d) :=
+ SliceField.field_card ..
+
+theorem ground_card_clog_le (p : Nat.Primes) (t d w : ℕ) (hp : p.val ≤ 2 ^ w) :
+ Nat.clog 2 (Nat.card (Ground p t d)) ≤ 1 + Nat.clog 2 (columnCountBound t d) + w := by
+ apply Nat.clog_le_of_le_pow
+ have hpos : 0 < columnCountBound t d := Nat.pow_pos (Nat.succ_pos _)
+ calc
+ Nat.card (Ground p t d) ≤ 2 * columnCountBound t d * p.val := SliceField.field_card_le _ hpos
+ _ ≤ 2 * 2 ^ Nat.clog 2 (columnCountBound t d) * 2 ^ w :=
+ Nat.mul_le_mul (Nat.mul_le_mul_left _ (Nat.le_pow_clog (by decide) _)) hp
+ _ = _ := by simp only [pow_add, pow_one]
+
+theorem elementWidth_le (p : Nat.Primes) (t d w : ℕ) (hp : p.val ≤ 2 ^ w) :
+ elementWidth p t d ≤ 2 * (1 + Nat.clog 2 (columnCountBound t d) + w) :=
+ (SliceField.advice_length_le _ _).trans (Nat.mul_le_mul_left _
+ ((Nat.log_le_clog _ _).trans (ground_card_clog_le p t d w hp)))
+
+theorem extensionDegree_le_width (p : Nat.Primes) (t d : ℕ) :
+ SliceField.extensionDegree p.val (columnCountBound t d) ≤ elementWidth p t d :=
+ Nat.le_mul_of_pos_right _ (Nat.clog_pos (by decide) p.prop.one_lt)
+
+/-- In characteristic zero the prime-width exponent from the integer minor
+is polynomially bounded even when the coefficient bit lengths are themselves
+singly exponential. An extra bit represents the prime in the equality case. -/
+theorem primeHeaderWidth_polynomiallyBounded {b : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n))
+ (hb : PolynomiallyBounded fun n => Nat.clog 2 (b n)) :
+ PolynomiallyBounded fun n =>
+ let a := Nat.clog 2 (multiplierDegree (t n) (d n) + d n + 1) * t n
+ (2 * (a + Nat.clog 2 (a + b n + 2)) + 1) + 1 :=
+ (RadicalCertificate.polynomiallyBounded_good_prime_bits ht
+ (RadicalCertificate.polynomiallyBounded_clog_paperBound ht hd) hd hb).add (.const 1)
+
+/-- Numerical upper bound independent of the prime, for the four fields
+(prime header, monic polynomial, pin mask, and pin values). -/
+def adviceLengthBound (w t d : ℕ) :=
+ let v := 2 * (1 + Nat.clog 2 (columnCountBound t d) + w)
+ w + v + t + t * v
+
+theorem adviceLength_le (p : Nat.Primes) (w t d : ℕ) (hp : p.val ≤ 2 ^ w) :
+ w + elementWidth p t d + t + t * elementWidth p t d ≤ adviceLengthBound w t d := by
+ have h := elementWidth_le p t d w hp
+ exact Nat.add_le_add (Nat.add_le_add_right (Nat.add_le_add_left h w) t) (Nat.mul_le_mul_left _ h)
+
+theorem adviceLengthBound_polynomiallyBounded {w : ℕ → ℕ} (hw : PolynomiallyBounded w)
+ (ht : PolynomiallyBounded t) (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n)) :
+ PolynomiallyBounded fun n => adviceLengthBound (w n) (t n) (d n) := by
+ have hv := (PolynomiallyBounded.const 2).mul
+ (((PolynomiallyBounded.const 1).add (columnCountBound_clog ht hd)).add hw)
+ exact ((hw.add hv).add ht).add (ht.mul hv)
+
+/-- A single padding exponent works for all admissible primes at every
+sufficiently large length. In particular it is independent of the evaluator
+exponents, pin choices, and later processor prefix. -/
+theorem exists_advice_padding {w : ℕ → ℕ} (hw : PolynomiallyBounded w)
+ (ht : PolynomiallyBounded t) (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n)) :
+ ∃ d₁ N : ℕ, ∀ n ≥ N, ∀ p : Nat.Primes, p.val < 2 ^ w n →
+ w n + elementWidth p (t n) (d n) + t n + t n * elementWidth p (t n) (d n) ≤ n ^ d₁ := by
+ obtain ⟨A, b, N, h⟩ := adviceLengthBound_polynomiallyBounded hw ht hd
+ refine ⟨b + 1, max A N, fun n hn p hp => ?_⟩
+ exact (adviceLength_le p _ _ _ hp.le).trans <| (h n ((le_max_right ..).trans hn)).trans <| by
+ rw [pow_succ, Nat.mul_comm]
+ exact Nat.mul_le_mul_left _ ((le_max_left ..).trans hn)
+
+/-- Padding the actual chosen advice preserves its decoded prime, pin data,
+and field presentation. The length is fixed before selecting a prime or model. -/
+theorem exists_padded_model_advice {w : ℕ → ℕ} (hw : PolynomiallyBounded w)
+ (ht : PolynomiallyBounded t) (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n)) :
+ ∃ d₁ N : ℕ, ∀ n ≥ N, ∀ (p : Nat.Primes) (_ : p.val < 2 ^ w n)
+ {ι : Type*} {F : ι → MvPolynomial (Fin (t n)) ℤ} (model : Model p (d n) F),
+ ∃ tape : List Bool, tape.length = n ^ d₁ ∧
+ ∃ a : EvaluatorAdviceSerialization.Fields p.val
+ (EvaluatorAdviceSerialization.degree p.val (t n) (d n)) (t n),
+ EvaluatorAdviceSerialization.parse (w n) (t n) (d n) tape = some ⟨p, a⟩ ∧
+ ∃ φ : AdjoinRoot (SliceArithmetic.modulus a.coefficients) ≃ₐ[ZMod p.val] Ground p (t n) (d n),
+ Irreducible (SliceArithmetic.modulus a.coefficients) ∧
+ (∀ i, a.pins i = decide (i ∈ model.pins)) ∧
+ (∀ i, φ (SliceArithmetic.value (SliceArithmetic.modulus a.coefficients) (a.values i)) = model.values i) := by
+ obtain ⟨d₁, N, hN⟩ := exists_advice_padding hw ht hd
+ refine ⟨d₁, N, fun n hn p hp ι F model => ?_⟩
+ obtain ⟨bits, hl, a, hparse, φ, hf, hs, hv, _⟩ := EvaluatorAdviceSerialization.exists_model_advice model hp
+ have hle : bits.length ≤ n ^ d₁ := hl ▸ hN n hn p hp
+ let pad := List.replicate (n ^ d₁ - bits.length) false
+ exact ⟨bits ++ pad, by simp [pad, Nat.add_sub_of_le hle], a, hparse pad, φ, hf, hs, hv⟩
+
+end LabelEvaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorAdviceSerialization.lean b/lean/OAI/Computability/VPVNP/EvaluatorAdviceSerialization.lean
new file mode 100644
index 0000000000..adbf5a1042
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorAdviceSerialization.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.LabelEvaluator
+import OAI.Computability.VPVNP.SliceArithmeticAdvice
+
+/-!
+# Binary advice for the finite-algebra evaluator
+
+The tape begins with a fixed-width prime header. Once the prime is known, the
+extension degree is determined by the system's variable and degree bounds.
+The following fields contain the low coefficients of the monic modulus, one
+pin bit per variable, and one field element per variable. The pin values use
+the same power basis as the evaluator's final coordinate query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorAdviceSerialization
+
+open SliceArithmetic LabelEvaluator
+
+/-- The extension degree chosen for characteristic p and the column-count bound on the slice
+system in t variables of degree at most d. -/
+abbrev degree (p t d : ℕ) := SliceField.extensionDegree p (columnCountBound t d)
+/-- Bit width of one power-basis coefficient vector. Each of its e residues occupies the
+ceiling of the base-two logarithm of p in bits. -/
+abbrev vectorBits (p e : ℕ) := e * Nat.clog 2 p
+
+/-- The length of the advice prefix consisting of the prime header, modulus coefficients, pin
+mask and t value vectors. -/
+def length (w p e t : ℕ) := w + vectorBits p e + t + t * vectorBits p e
+
+/-- The modulus coefficients, pin mask and specialized field elements in the advice for a slice
+over characteristic p. -/
+structure Fields (p e t : ℕ) where
+ /-- The e lower coefficients of the monic modulus defining the advised power-basis field
+ representation. -/
+ coefficients : SliceArithmetic.Vector p e
+ /-- One bit per system variable identifying the coordinates fixed by the slice. -/
+ pins : Fin t → Bool
+ /-- The advised power-basis value for each variable, including each coordinate marked by the
+ pin mask. -/
+ values : Fin t → SliceArithmetic.Vector p e
+
+/-- Serialize all `t` values consecutively, including those at unpinned coordinates. -/
+private def valueBits {p e t : ℕ} (a : Fields p e t) (i : Fin (t * vectorBits p e)) : Bool :=
+ let ij := finProdFinEquiv.symm i
+ SliceArithmetic.encode (a.values ij.1) ij.2
+
+/-- Write the fixed-width prime, the lower modulus coefficients, the pin mask and all
+coordinate values consecutively on the binary advice tape. -/
+def encode {w p e t : ℕ} (hp : p < 2 ^ w) (a : Fields p e t) : List Bool :=
+ List.ofFn (RAMSerialization.wordBits w ⟨p, hp⟩) ++ List.ofFn (SliceArithmetic.encode a.coefficients) ++
+ List.ofFn a.pins ++ List.ofFn (valueBits a)
+
+@[simp] theorem length_encode {w p e t : ℕ} (hp : p < 2 ^ w) (a : Fields p e t) :
+ (encode hp a).length = length w p e t := by simp [encode, length, vectorBits, Nat.add_assoc]
+
+/-- Read consecutive bits at an absolute address, with zero outside the tape. -/
+def readBits (tape : List Bool) (start count : ℕ) (i : Fin count) : Bool :=
+ tape[start + i.val]?.getD false
+
+private theorem readBits_at (pre tail : List Bool) {k : ℕ} (bits : Fin k → Bool) :
+ readBits (pre ++ (List.ofFn bits ++ tail)) pre.length k = bits := by
+ funext i
+ rw [readBits, List.getElem?_append_right (by omega), Nat.add_sub_cancel_left,
+ List.getElem?_append_left (by simp), List.getElem?_eq_getElem (by simp)]
+ simp
+
+/-- Decode the prime header as a natural number from the first w bits of the advice tape,
+padding missing bits with zero. -/
+def readPrime (w : ℕ) (tape : List Bool) : ℕ :=
+ ((RAMSerialization.wordBits w).symm (readBits tape 0 w)).val
+
+/-- After the prime header is decoded, all remaining offsets are fixed. -/
+def readFields (w p e t : ℕ) [NeZero p] (tape : List Bool) : Fields p e t where
+ coefficients := ofBits (readBits tape w (vectorBits p e))
+ pins := readBits tape (w + vectorBits p e) t
+ values i := ofBits fun j =>
+ readBits tape (w + vectorBits p e + t) (t * vectorBits p e) (finProdFinEquiv (i, j))
+
+@[simp] theorem readPrime_encode {w p e t : ℕ} (hp : p < 2 ^ w) (a : Fields p e t) (tail : List Bool) :
+ readPrime w (encode hp a ++ tail) = p := by
+ let bits := RAMSerialization.wordBits w (⟨p, hp⟩ : BurstRAM.Word w)
+ have h := readBits_at [] (List.ofFn (SliceArithmetic.encode a.coefficients) ++
+ List.ofFn a.pins ++ List.ofFn (valueBits a) ++ tail) bits
+ have h' : readBits (encode hp a ++ tail) 0 w = bits := by
+ simpa only [encode, bits, List.nil_append, List.length_nil, List.append_assoc] using h
+ simp [readPrime, h', bits]
+
+@[simp] theorem readFields_encode {w p e t : ℕ} [NeZero p] (hp : p < 2 ^ w) (a : Fields p e t)
+ (tail : List Bool) : readFields w p e t (encode hp a ++ tail) = a := by
+ let header := List.ofFn (RAMSerialization.wordBits w (⟨p, hp⟩ : BurstRAM.Word w))
+ let coeff := List.ofFn (SliceArithmetic.encode a.coefficients)
+ let mask := List.ofFn a.pins
+ have hc : readBits (encode hp a ++ tail) w (vectorBits p e) = SliceArithmetic.encode a.coefficients := by
+ simpa only [encode, header, mask, List.length_ofFn, List.append_assoc] using
+ readBits_at header (mask ++ List.ofFn (valueBits a) ++ tail) (SliceArithmetic.encode a.coefficients)
+ have hm : readBits (encode hp a ++ tail) (w + vectorBits p e) t = a.pins := by
+ simpa only [encode, header, coeff, List.length_append, List.length_ofFn, List.append_assoc] using
+ readBits_at (header ++ coeff) (List.ofFn (valueBits a) ++ tail) a.pins
+ have hv : readBits (encode hp a ++ tail) (w + vectorBits p e + t) (t * vectorBits p e) = valueBits a := by
+ simpa only [encode, header, coeff, mask, List.length_append, List.length_ofFn, List.append_assoc, Nat.add_assoc] using
+ readBits_at ((header ++ coeff) ++ mask) tail (valueBits a)
+ simp [readFields, hc, hm, hv, valueBits]
+
+private def parseAtPrime (w t d p : ℕ) (tape : List Bool) :
+ Option ((q : Nat.Primes) × Fields q.val (degree q.val t d) t) :=
+ if h : p.Prime then
+ haveI : NeZero p := ⟨h.ne_zero⟩
+ if length w p (degree p t d) t ≤ tape.length then
+ some ⟨⟨p, h⟩, readFields w p (degree p t d) t tape⟩
+ else none
+ else none
+
+/-- Parse a prime from the tape and use the degree selected in Section 8.2.
+The tape may have trailing padding. A composite header or short tape fails. -/
+def parse (w t d : ℕ) (tape : List Bool) : Option ((p : Nat.Primes) × Fields p.val (degree p.val t d) t) :=
+ parseAtPrime w t d (readPrime w tape) tape
+
+local instance (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+/-- A finite enumeration of the slice ground field for representing the advised pin values. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+
+theorem parse_encode {w t d : ℕ} (p : Nat.Primes) (hp : p.val < 2 ^ w)
+ (a : Fields p.val (degree p.val t d) t) (tail : List Bool) :
+ parse w t d (encode hp a ++ tail) = some ⟨p, a⟩ := by
+ rw [parse, readPrime_encode]
+ simp [parseAtPrime, p.prop]
+ rfl
+
+/-- All advised pin values have coefficient vectors in the same quotient
+presentation that realizes the evaluator's prime-field coordinate. -/
+theorem exists_model_advice {t d w : ℕ} {p : Nat.Primes} {ι : Type*}
+ {F : ι → MvPolynomial (Fin t) ℤ} (M : Model p d F) (hp : p.val < 2 ^ w) :
+ ∃ tape : List Bool, tape.length = length w p.val (degree p.val t d) t ∧
+ ∃ a : Fields p.val (degree p.val t d) t,
+ (∀ tail, parse w t d (tape ++ tail) = some ⟨p, a⟩) ∧
+ ∃ φ : AdjoinRoot (modulus a.coefficients) ≃ₐ[ZMod p.val] Ground p t d,
+ Irreducible (modulus a.coefficients) ∧
+ (∀ i, a.pins i = decide (i ∈ M.pins)) ∧
+ (∀ i, φ (value (modulus a.coefficients) (a.values i)) = M.values i) ∧
+ ∀ v : SliceArithmetic.Vector p.val (degree p.val t d),
+ SliceEvaluator.primeCoordinate p.val (Ground p t d)
+ (φ (value (modulus a.coefficients) v)) = ((v ⟨0, Nat.succ_pos _⟩).val : ZMod p.val) := by
+ obtain ⟨c, φ, _, hirr, hcoord⟩ := exists_compatible_advice p.val (columnCountBound t d)
+ have hsurj : Function.Surjective (φ ∘ value (e := degree p.val t d) (modulus c)) := by
+ refine ((Nat.bijective_iff_injective_and_card _).mpr ⟨φ.injective.comp
+ (value_injective (modulus_monic c) (modulus_natDegree c)), ?_⟩).2
+ rw [SliceField.field_card]
+ simp [SliceArithmetic.Vector]
+ choose values hv using fun i => hsurj (M.values i)
+ let a : Fields p.val (degree p.val t d) t := ⟨c, fun i => decide (i ∈ M.pins), values⟩
+ exact ⟨encode hp a, length_encode hp a, a, parse_encode p hp a, φ, hirr, fun _ => rfl, hv, hcoord⟩
+
+end EvaluatorAdviceSerialization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorBinaryMachine.lean b/lean/OAI/Computability/VPVNP/EvaluatorBinaryMachine.lean
new file mode 100644
index 0000000000..689c7cb646
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorBinaryMachine.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.EvaluatorProgramMonomial
+import OAI.Computability.VPVNP.EvaluatorScheduleCount
+import OAI.Computability.VPVNP.RAMTapeSpaceNamed
+
+/-!
+# Binary machine for matrix-index evaluation
+
+The input reader, radix converter, digit scheduler and terminal residue test
+are linked in finite control. Only the two matrix callbacks vary when the
+program is constructed. The tape table itself is independent of the advice
+and the exponent width. Its two callbacks implement the scalar coordinate
+queries and multiplication in the advised field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.BinaryMachine
+
+open RAMTape EvaluatorDigitFetch EvaluatorProgramMonomial EvaluatorProgramRawInput
+ EvaluatorMonomialSchedule EvaluatorRoutine EvaluatorScheduleEffects
+
+variable {P : Type} [DecidableEq P]
+
+/-- The binary evaluator's stack ports. The extra port holds the raw input, and the remaining
+ports belong to the input converter and scheduler. -/
+abbrev MachinePort (P : Type) := Option (EvaluatorProgramInput.Port P)
+
+/-- Embed the three terminal registers into the scheduler's work bank. -/
+def outputPorts (out : Output.Port → P) (k : Output.Port) : MachinePort P :=
+ some (.sched (.work (out k)))
+
+/-- Run the raw binary monomial program, then test its final endpoint and
+branch directly on the low limb of the accumulated product. -/
+def evaluator (ps : List P) (out : Output.Port → P) (frobenius multiply : FiniteRoutine (Port P)) :
+ FiniteRoutine (MachinePort P) :=
+ (rawMachine ps frobenius multiply).followedBy
+ ((FiniteRoutine.ofRoutine Output.routine).onPorts (outputPorts out))
+
+/-- The literal table of a fixed evaluator. Every input starts on its designated
+raw input tape. -/
+noncomputable def program [Fintype P] (ps : List P) (out : Output.Port → P)
+ (frobenius multiply : FiniteRoutine (Port P)) : UniversalMachine.Program :=
+ let r := (evaluator ps out frobenius multiply).body
+ StackCompiler.labeledProgram none (r.close false) (some r.entry)
+
+/-- A bound for every stack path transfers the integer count to the fixed
+literal table. The overhead is quadratic in the bit-stack time and input size. -/
+theorem program_paths_eq [Fintype P] (ps : List P) (out : Output.Port → P)
+ (f m : FiniteRoutine (Port P)) (raw : List Bool) (T ticks : ℕ)
+ (stops : let r := (evaluator ps out f m).body
+ StopsWithin (r.close false) T (some r.entry) (StackCompiler.labeledInput none raw))
+ (hclock : T * (6 * (raw.length + (Fintype.card (MachinePort P) + 1) + T) + 4) ≤ ticks) :
+ let E := program ps out f m
+ let r := (evaluator ps out f m).body
+ UniversalMachine.paths E ticks (UniversalMachine.initial E raw) =
+ stackPaths (r.close false) T (some r.entry) (StackCompiler.labeledInput none raw) :=
+ StackCompiler.input_count_labeled none _ _ _ T ticks stops hclock
+
+/-- A reachable bank size bound limits each literal tape head throughout
+the evaluator computation, independently of the number of transitions. -/
+theorem program_head_space [Fintype P] (ps : List P) (out : Output.Port → P)
+ (f m : FiniteRoutine (Port P)) (raw : List Bool) {M : ℕ}
+ (bounded : let r := (evaluator ps out f m).body
+ ∀ ⦃q s⦄, StackCompiler.Reach (r.close false) (some r.entry) (StackCompiler.labeledInput none raw) q s →
+ Fintype.card (MachinePort P)+1 + ∑ k, (s k).length ≤ M) (bits : List Bool) :
+ let E := program ps out f m
+ let d := choiceDisplacement E (UniversalMachine.initial E raw) bits
+ StackCompiler.HeadBox (7*M+4) d.1 d.2 :=
+ StackCompiler.input_space_labeled none _ _ _ bounded bits
+
+variable {n p t Z v w : ℕ} [Fact p.Prime] {K A : Type}
+ [Field K] [Fintype K] [Algebra (ZMod p) K] [CommRing A] [Algebra K A]
+ [Algebra (ZMod p) A] [IsScalarTower (ZMod p) K A]
+
+variable (b : Module.Basis (Fin n) K A) (u : Fin n) (coord : K →ₗ[ZMod p] ZMod p)
+ (X : Fin t → A) (e : Fin t → BurstRAM.Word Z) (d : List Bool)
+ (payload : Fin n × K → Stacks P) (out : Output.Port → P)
+ (frobenius multiply : FiniteRoutine (Port P)) (BF BM : ℕ) (ps : List P)
+
+local notation "data" => EvaluatorRadixRows.packedTable d.length (TapeWord.value d) (List.ofFn e)
+local notation "next" => nextIndex b X
+local notation "tape" => advice ps t d (payload (u,1)) ++ runtime e
+
+/-- The actual stack-path count modulo the advised prime, given the two
+matrix-step specifications. Output data are the binary current ordinal,
+unary working limb width, and the packed field product beginning with its
+prime-field coordinate. -/
+theorem stackCount_mod (hp : ps.Nodup) (hall : ∀ a, a ∈ ps)
+ (hout : Function.Injective out) (hunit : b u = 1) (hu : u.val = 0) (hdim : n ≤ 2 ^ v)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ w)
+ (hd : TapeWord.value d = Fintype.card K)
+ (hdata : ∀ s : Fin n × K, ∃ tail, (payload s) ∘ out =
+ Output.bank (BurstRAM.wordBits (Fin.castLE hdim s.1 : BurstRAM.Word v)) (List.replicate w true)
+ (BurstRAM.wordBits (SliceArithmetic.Word.limb w (⟨(coord s.2).val, ZMod.val_lt _⟩ : Fin p)) ++ tail))
+ (R : ℕ) (hR : ∀ s, readTicks ps e d (payload s) ≤ R)
+ (hf : ∀ (j : Fin Z) left, Realizes frobenius.body
+ (fun x => bank data t Z d.length 0 j 0 left (payload x))
+ (fun x => bank data t Z d.length 0 j 0 left (payload x)) BF (stepEffect next none))
+ (hm : LabelCallback e d.length (TapeWord.value d) BM payload next multiply)
+ (fuel : ℕ) (ht : 3*w+3+v + (R + (EvaluatorProgramInput.convertTicks t Z d.length +
+ budget t Z d.length (TapeWord.value d) BF BM)) ≤ fuel) :
+ let r := (evaluator ps out frobenius multiply).body
+ (stackPaths (r.close false) fuel (some r.entry) (StackCompiler.labeledInput none tape) : ZMod p) =
+ primeFunctional b u coord (∏ i, X i ^ (e i).val) := by
+ have hq : 2 ≤ TapeWord.value d := hd ▸ Fintype.one_lt_card (α := K)
+ have hrun := raw_realizes e d payload next frobenius multiply BF BM ps hp hall R hR hq hf hm
+ let result := (FiniteRoutine.ofRoutine Output.routine).onPorts (outputPorts out)
+ let post (s : Fin n × K) := InputBank.frame [] (EvaluatorProgramInput.extend Z d
+ (bank data t Z d.length 0 0 0 0 (payload s)))
+ let c (n : ℕ) (_ : Stacks (MachinePort P)) := if n = 0 then 0 else false.toNat
+ have hpost (s : Fin n × K) (k : ℕ) (hk : 3*w+3+v ≤ k) :
+ result.body.count c k (post s) = finishWeight u coord s := by
+ have hpo : Function.Injective (outputPorts out) := fun _ _ h ↦
+ hout (Port.work.inj (EvaluatorProgramInput.Port.sched.inj (Option.some_inj.mp h)))
+ rw [show result = _ from rfl, FiniteRoutine.count_onPorts _ _ hpo]
+ obtain ⟨tail, htail⟩ := hdata s
+ change Output.routine.count _ _ (payload s ∘ out) = _
+ rw [htail, show k = k - (3*w+3+v) + (3*w+3) + v by omega,
+ Output.count_output_limb hw]
+ have hz : (s.1.val = 0) ↔ s.1 = u := by rw [← hu, Fin.val_inj]
+ simp only [Fin.val_castLE, hz, finishWeight]
+ have hcount := hrun (3*w+3+v) fuel ht (u,1) (finishWeight u coord)
+ (result.body.count c) hpost
+ change (stackPaths _ fuel _ _ : ZMod p) = _
+ rw [Routine.stackPaths_close]
+ change ((evaluator ps out frobenius multiply).body.count c fuel _ : ZMod p) = _
+ have heq : StackCompiler.labeledInput (none : MachinePort P) tape = InputBank.frame tape (fun _ ↦ []) := by
+ funext k
+ cases k <;> rfl
+ rw [heq]
+ have hseq := Routine.count_followedBy (rawMachine ps frobenius multiply).body result.body c fuel
+ (InputBank.frame tape (fun _ ↦ []))
+ have hnat := hseq.trans hcount
+ rw [hd] at hnat
+ exact (congrArg (fun z : ℕ ↦ (z : ZMod p)) hnat).trans (schedulerEffect_mod b u coord hunit X e)
+
+end Evaluator.BinaryMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorBinarySafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorBinarySafety.lean
new file mode 100644
index 0000000000..a69c810d80
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorBinarySafety.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.EvaluatorBinaryMachine
+import OAI.Computability.VPVNP.EvaluatorProgramInputBounds
+import OAI.Computability.VPVNP.RAMTapeRoutineTotalPorts
+
+/-!
+# Stopping time and space for the complete binary evaluator
+
+The raw input reader, radix converter, matrix callbacks and final residue
+comparison execute as one finite stack routine. Both bounds cover rejected
+paths as well as accepted paths. The terminal clock charges only the endpoint
+and low-limb scans and adds no term involving the earlier running time to
+the space estimate.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Routine
+
+variable {K Q : Type*} [DecidableEq K]
+
+/-- The same execution certifies every weaker pointwise storage condition. -/
+theorem SafeFrom.weaken_space {r : Routine K Q} {safe safe' : Stacks K → Prop} {cont t q s}
+ (h : r.SafeFrom safe cont t q s) (le : ∀ u, safe u → safe' u) : r.SafeFrom safe' cont t q s := by
+ induction t generalizing q s with
+ | zero => cases q <;> exact h
+ | succ t ih =>
+ cases q with
+ | none => exact h
+ | some q =>
+ rw [SafeFrom] at h ⊢
+ refine ⟨le s h.1, ?_⟩
+ have next := h.2
+ cases op : r.code q <;> rw [op] at next <;> first | exact ih next | exact ⟨ih next.1, ih next.2⟩ | trivial
+
+end RAMTape.Routine
+
+namespace Evaluator.BinaryMachine
+
+open RAMTape EvaluatorRoutineSafety EvaluatorDigitFetch EvaluatorChronologicalLoop EvaluatorRadixRows
+ EvaluatorMonomialSchedule EvaluatorProgramRawInput EvaluatorProgramMonomial
+
+variable {P S : Type} [DecidableEq P] {t Z : ℕ}
+
+/-- Time spent after the final matrix step. -/
+def terminalTicks (v w : ℕ) := 3*w+3+v
+
+/-- Instruction bound for the raw input reader, radix conversion, matrix schedule and final
+endpoint and residue test together. -/
+def fullTicks (t Z ℓ q A BF BM v w : ℕ) :=
+ terminalTicks v w + (readerBudget t Z A + (EvaluatorProgramInput.convertTicks t Z ℓ + budget t Z ℓ q BF BM))
+
+/-- Stack bound for all branches of the binary evaluator, including the storage used in its
+final endpoint and residue scan. -/
+def fullSpace (t Z ℓ workspace A v w : ℕ) := rawSpace t Z ℓ workspace A + terminalTicks v w
+
+/-- The terminal scan preserves the separation between the singly exponential
+input-length factor and the polynomial exponent-width factor of Theorem 8.1. -/
+theorem fullTicks_le_exp_poly (t Z ℓ q A BF BM v w a k : ℕ)
+ (ha : A ≤ 2^a) (ht : t ≤ 2^a) (hℓ : ℓ ≤ 2^a) (hq : q ≤ 2^a)
+ (hM : BM ≤ 2^a*(Z+1)^k) (hF : BF ≤ 2^a*(Z+1)^k) (hv : v ≤ 2^a) (hw : w ≤ 2^a) :
+ fullTicks t Z ℓ q A BF BM v w ≤ 2^(3*a+9)*(Z+1)^(k+2) := by
+ have bound := parser_budget_le_exp_poly t Z ℓ q A BF BM a k ha ht hℓ hq hM hF
+ have pos : 1 ≤ 2^a := Nat.two_pow_pos _
+ have grow : 2^a ≤ 2^(3*a) := Nat.pow_le_pow_right (by decide) (by omega)
+ have term : terminalTicks v w ≤ 2^(3*a+8) := by rw [pow_add]; unfold terminalTicks; norm_num; omega
+ have hterm : terminalTicks v w ≤ 2^(3*a+8)*(Z+1)^(k+2) := term.trans (Nat.le_mul_of_pos_right (2^(3*a+8)) (Nat.pow_pos (n := k+2) (Nat.succ_pos Z)))
+ apply (Nat.add_le_add hterm bound).trans_eq
+ rw [show 3*a+9 = (3*a+8)+1 by omega, pow_succ 2 (3*a+8)]
+ ring
+
+/-- The space bound on the full machine is quartic in the numerical widths,
+the label count, advice size and the space occupied by its callbacks. -/
+theorem fullSpace_le_power (t Z ℓ workspace A v w : ℕ) :
+ fullSpace t Z ℓ workspace A v w ≤ 157*(t+Z+ℓ+workspace+A+v+w+1)^4 := by
+ let N := t+Z+ℓ+workspace+A+v+w+1
+ have base := rawSpace_le_power t Z ℓ workspace A
+ have hmono : (t+Z+ℓ+workspace+A+1)^4 ≤ N^4 := Nat.pow_le_pow_left (by dsimp [N]; omega) _
+ have hpow : N ≤ N^4 := by
+ have hn : 1 ≤ N := by dsimp [N]; omega
+ simpa only [pow_one] using Nat.pow_le_pow_right hn (by decide : 1 ≤ 4)
+ have hterm : terminalTicks v w ≤ 7*N := by dsimp [terminalTicks, N]; omega
+ change rawSpace t Z ℓ workspace A + terminalTicks v w ≤ 157*N^4
+ omega
+
+private theorem output_safe (out : Output.Port → P) (ho : Function.Injective out) (s : Stacks (MachinePort P))
+ (v w rawCap fuel : ℕ) (hs : stackFits rawCap s) (hidx : (s (outputPorts out .index)).length = v)
+ (hwidth : (s (outputPorts out .width)).length = w) (hf : terminalTicks v w ≤ fuel) :
+ ((FiniteRoutine.ofRoutine Output.routine).onPorts (outputPorts out)).body.Safe
+ (stackFits (rawCap+terminalTicks v w)) (fun _ _ => False) fuel s := by
+ let terminal := (FiniteRoutine.ofRoutine Output.routine).onPorts (outputPorts out)
+ have inj : Function.Injective (outputPorts out) := fun _ _ h => ho (Port.work.inj
+ (EvaluatorProgramInput.Port.sched.inj (Option.some.inj h)))
+ have stop (cont : ℕ → Stacks (MachinePort P) → Prop) :
+ terminal.body.AllStops cont (terminalTicks v w) s := by
+ rw [show terminal = _ from rfl, FiniteRoutine.allStops_onPorts _ _ inj]
+ let data := s ∘ outputPorts out
+ have he : data = Output.bank (data .index) (data .width) (data .product) := by
+ funext i; cases i <;> rfl
+ have h := Output.allStops_output (data .index) (data .width) (data .product)
+ (fun t a => cont t (installStacks (outputPorts out) s a))
+ rw [← he, show (data .index).length = v from hidx, show (data .width).length = w from hwidth] at h
+ exact h
+ have result := safe_of_allStops (r := terminal.body) (safe := stackFits (rawCap+terminalTicks v w))
+ (fun _ _ => False) (fuel-terminalTicks v w) (stop (fun _ _ => False)) (fun u h k =>
+ (h k).trans (Nat.add_le_add_right (hs k) _))
+ simpa only [Nat.sub_add_cancel hf] using result
+
+variable (e : Fin t → BurstRAM.Word Z) (d : List Bool) (payload : S → Stacks P)
+ (workspace : ℕ) (hp : ∀ x p, (payload x p).length ≤ workspace)
+ (frobenius multiply : FiniteRoutine (Port P)) (BF BM : ℕ)
+
+local notation "data" => packedTable d.length (TapeWord.value d) (List.ofFn e)
+local notation "post" => fun x => EvaluatorProgramInput.extend Z d (bank data t Z d.length 0 0 0 0 (payload x))
+local notation "nativeTicks" => EvaluatorProgramInput.convertTicks t Z d.length + budget t Z d.length (TapeWord.value d) BF BM
+
+include hp in
+/-- All binary branches of the complete evaluator halt by the full clock.
+Every reachable stack on that same program satisfies the polynomial height bound. -/
+theorem full_space_clock (ps : List P) (hn : ps.Nodup) (hall : ∀ p, p ∈ ps) (A : ℕ)
+ (ha : ∀ x, (advice ps t d (payload x)).length ≤ A)
+ (native : Bounded (nativeMachine frobenius multiply).body (stackFits (nativeSpace t Z d.length workspace))
+ (EvaluatorProgramInput.initial e d ∘ payload) post nativeTicks)
+ (out : Output.Port → P) (ho : Function.Injective out) (v w : ℕ)
+ (hidx : ∀ x, (payload x (out .index)).length = v)
+ (hwidth : ∀ x, (payload x (out .width)).length = w) (outcome : Bool) (x : S) :
+ let r := (evaluator ps out frobenius multiply).body
+ let raw := advice ps t d (payload x) ++ runtime e
+ let start := StackCompiler.labeledInput (none : MachinePort P) raw
+ StopsWithin (r.close outcome) (fullTicks t Z d.length (TapeWord.value d) A BF BM v w) (some r.entry) start ∧
+ ∀ ⦃q s⦄, StackCompiler.Reach (r.close outcome) (some r.entry) start q s →
+ stackFits (fullSpace t Z d.length workspace A v w) s := by
+ let raw := rawMachine ps frobenius multiply
+ let terminal := (FiniteRoutine.ofRoutine Output.routine).onPorts (outputPorts out)
+ let tape := advice ps t d (payload x) ++ runtime e
+ let start : Stacks (MachinePort P) := InputBank.frame tape (fun _ => [])
+ let limit := rawSpace t Z d.length workspace A
+ let T := fullTicks t Z d.length (TapeWord.value d) A BF BM v w
+ have endHeight (y : S) : stackFits limit (InputBank.frame [] ((post) y)) := by
+ have hs : stackFits (nativeSpace t Z d.length workspace) ((post) y) := by
+ apply extend_fits e d workspace
+ intro k
+ have h := bank_length data t Z d.length workspace payload hp (i := 0) (j := 0)
+ (left := 0) (cols := 0) (by omega) (by omega) y k
+ exact h.trans (by unfold schedulerSpace; omega)
+ intro k
+ cases k with
+ | none => exact Nat.zero_le _
+ | some k => exact (hs k).trans (Nat.le_add_left ..)
+ have rawBound := raw_bounded_of_native e d payload workspace frobenius multiply BF BM ps hn hall A ha native
+ have combined : (raw.body.followedBy terminal.body).Safe (stackFits (limit+terminalTicks v w))
+ (fun _ _ => False) T start := by
+ rw [Routine.safe_followedBy]
+ have h := rawBound (terminalTicks v w) T le_rfl x
+ (terminal.body.Safe (stackFits (limit+terminalTicks v w)) (fun _ _ => False))
+ (fun y k hk => output_safe out ho _ v w limit k (endHeight y) (hidx y) (hwidth y) hk)
+ exact h.weaken_space (fun s hs k => (hs k).trans (Nat.le_add_right ..))
+ have he : StackCompiler.labeledInput (none : MachinePort P) tape = start := by
+ funext k; cases k <;> rfl
+ dsimp only
+ change StopsWithin _ T _ (StackCompiler.labeledInput none tape) ∧
+ ∀ ⦃q s⦄, StackCompiler.Reach _ _ (StackCompiler.labeledInput none tape) q s → _
+ rw [he]
+ exact ⟨combined.stopsWithin outcome (fun _ _ h => h.elim), fun _ _ path =>
+ combined.reach outcome (fun _ _ h => h.elim) path⟩
+
+end Evaluator.BinaryMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorCallbackMountSafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorCallbackMountSafety.lean
new file mode 100644
index 0000000000..19db150bd5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorCallbackMountSafety.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.EvaluatorCallbackSafety
+import OAI.Computability.VPVNP.EvaluatorWeightedSafety
+
+/-! # Mounting the streamed readers in the digit scheduler
+
+Each scalar read operates on the unary label and the weighted payload. The
+digit table, exponent counters and repeat stack retain their contents during
+that read. Their lengths enter only the space bound for the enclosing machine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.MatrixCallbacks
+
+open RAMTape SliceArithmetic EvaluatorRoutineSafety EvaluatorChronologicalLoop
+open EvaluatorDigitFetch (bank)
+open EvaluatorMonomialSchedule
+
+variable {P : Type} [DecidableEq P] {p e w v : ℕ} [Fact p.Prime]
+ {K : Type} [Field K] [Algebra (ZMod p) K] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (dim : BurstRAM.Word v) (extra : Stacks P)
+
+local notation "payloadBank" => (fun i next q a ↦ WeightedStep.bank φ w dim i next q a extra)
+local notation "work" => (EvaluatorDigitFetch.Port.work (P := WeightedStep.Port P))
+
+private theorem fixedFrame_bounded (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (read : FiniteRoutine (ReadPort P)) (label time peak cap : ℕ) (hpeak : peak ≤ cap)
+ (matrix : Matrix (Fin dim.val) (Fin dim.val) K)
+ (hr : ReadsEntryWithin φ dim extra read w label time peak matrix)
+ (frame : Stacks (WeightedStep.Port P) → Stacks (Host P))
+ (hwork : ∀ s k, frame s (.work k) = s k)
+ (hlabel : ∀ s, frame s (.addr .labelIndex) = List.replicate label true)
+ (hrest : ∀ x y k, (∀ j, work j ≠ k) → frame x k = frame y k)
+ (hroom : ∀ (i : Fin dim.val) (next q : List Bool), next.length ≤ v → q.length ≤ e*w →
+ ∀ (a : K) k, (frame (payloadBank i next q a) k).length + WeightedStep.localTicks v e w ≤ cap) :
+ Bounded (machine read).body (stackFits cap) (frame ∘ payload φ dim extra w)
+ (frame ∘ payload φ dim extra w) (WeightedStep.ticks v e w time) := by
+ let ambient := frame (fun _ ↦ [])
+ have hwp : Function.Injective work := fun _ _ h ↦ EvaluatorDigitFetch.Port.work.inj h
+ have hi (s) : installStacks work ambient s = frame s :=
+ installStacks_frame hwp (hwork s) (hrest s _)
+ have h := WeightedStep.callback_bounded φ work hwp ambient extra dim he hw (read.onPorts mount)
+ matrix cap time (by simpa only [hi] using hroom) (by
+ intro s j
+ let word := BurstRAM.wordBits (Fin.castLE dim.isLt.le j : BurstRAM.Word v)
+ let pre := payloadBank s.1 word [] s.2
+ let post := payloadBank s.1 word (WeightedStep.bits φ w (matrix s.1 j)) s.2
+ have hm : Function.Injective (mount (P := P)) := by
+ intro a b hh; rcases a with (⟨⟩ | a) <;> rcases b with (⟨⟩ | b) <;> cases hh <;> rfl
+ have get (b : Stacks (WeightedStep.Port P)) (k : ReadPort P) :
+ frame b (mount k) = queryBank (List.replicate label true) b k := by
+ cases k with
+ | inl => exact hlabel b
+ | inr k => exact hwork b k
+ obtain ⟨d, hd, run⟩ := hr s j
+ have mounted := FiniteRoutine.BoundedRun.onPorts (a := read) hm (frame pre) (run.mono_cap hpeak) (fun k _ ↦
+ (Nat.le_add_right _ _).trans (hroom s.1 word [] (by simp [word]) (by simp) s.2 k))
+ have first := installStacks_frame hm (get pre) (base := frame pre) (fun _ _ ↦ rfl)
+ have last := installStacks_frame hm (get post) (base := frame pre) (fun k hk ↦
+ hrest post pre k (fun j ↦ hk (.inr j)))
+ rw [first, last] at mounted
+ exact ⟨d, hd, by simpa only [hi] using mounted⟩)
+ simpa only [hi, Function.comp_def, payload, machine] using h
+
+variable {t Z : ℕ} (es : Fin t → BurstRAM.Word Z) (d : List Bool)
+ (extraSpace : ℕ) (hextra : ∀ k, (extra k).length ≤ extraSpace)
+
+local notation "footprint" => WeightedStep.bankSpace v e w extraSpace
+local notation "reserve" => WeightedStep.localTicks v e w
+local notation "tableBits" => EvaluatorRadixRows.packedTable d.length (TapeWord.value d) (List.ofFn es)
+local notation "pay" => payload φ dim extra w
+
+/-- Callback capacity available on all digit columns. -/
+def workspace (v e w extraSpace peak : ℕ) :=
+ WeightedStep.bankSpace v e w extraSpace + WeightedStep.localTicks v e w + peak
+
+include hextra in
+omit [DecidableEq P] in
+theorem payload_length (peak : ℕ) (s : Fin dim.val × K) :
+ stackFits (workspace v e w extraSpace peak) (pay s) := by
+ intro k
+ exact (WeightedStep.bank_length φ extra dim extraSpace hextra s.1 [] [] (by simp) (by simp) s.2 k).trans
+ (by unfold workspace; omega)
+
+include hextra in
+omit [DecidableEq P] in
+private theorem frame_room (i j labels cols : ℕ) (hi : i+labels ≤ t) (hj : j+cols ≤ Z) (peak : ℕ)
+ (idx : Fin dim.val) (next q : List Bool) (hn : next.length ≤ v) (hq : q.length ≤ e*w) (a : K)
+ (k : Host P) :
+ (bank tableBits t Z d.length i j labels cols (payloadBank idx next q a) k).length + reserve ≤
+ schedulerSpace (tableBits).length t Z d.length (workspace v e w extraSpace peak) := by
+ have hb := WeightedStep.bank_length φ extra dim extraSpace hextra idx next q hn hq a
+ have hs := bank_length tableBits t Z d.length footprint (fun _ : Unit ↦ payloadBank idx next q a)
+ (fun _ ↦ hb) hi hj () k
+ unfold schedulerSpace bankSpace workspace
+ unfold bankSpace at hs
+ dsimp only at hs ⊢
+ omega
+
+include hextra in
+/-- All paths of a Frobenius callback at a reachable column. -/
+theorem frobenius_bounded (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (read : FiniteRoutine (ReadPort P)) (time peak : ℕ)
+ (matrix : Matrix (Fin dim.val) (Fin dim.val) K)
+ (hr : ReadsEntryWithin φ dim extra read w 0 time peak matrix)
+ (j : Fin Z) (cols : ℕ) (hj : j.val+cols < Z) :
+ Bounded (machine read).body
+ (stackFits (schedulerSpace (tableBits).length t Z d.length (workspace v e w extraSpace peak)))
+ (fun x ↦ bank tableBits t Z d.length 0 j 0 cols (pay x))
+ (fun x ↦ bank tableBits t Z d.length 0 j 0 cols (pay x)) (WeightedStep.ticks v e w time) := by
+ apply fixedFrame_bounded φ dim extra he hw read 0 time peak _ _ matrix hr
+ (bank tableBits t Z d.length 0 j 0 cols) (fun _ _ ↦ rfl) (fun _ ↦ rfl)
+ · intro x y k hk; cases k <;> first | rfl | exact (hk _ rfl).elim
+ · exact frame_room φ dim extra es d extraSpace hextra 0 j 0 cols (by omega) hj.le peak
+ · unfold schedulerSpace bankSpace workspace; omega
+
+include hextra in
+/-- All paths of a multiplication callback, including early rejection by the
+basis-index chooser. The temporary digit holds exactly one field-cardinality
+word when the repeated callback is entered. -/
+theorem label_bounded (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (read : FiniteRoutine (ReadPort P)) (time peak : ℕ)
+ (matrix : Fin t → Matrix (Fin dim.val) (Fin dim.val) K)
+ (hr : ∀ i, ReadsEntryWithin φ dim extra read w i.val time peak (matrix i))
+ (i : Fin t) (j : Fin Z) (labels cols : ℕ) (hi : i.val+labels < t) (hj : j.val+cols < Z)
+ (digit : List Bool) (hsize : digit.length = d.length) :
+ let frame (s : Stacks (WeightedStep.Port P)) := EvaluatorDigitRepeat.frame
+ EvaluatorDigitFetch.Port.digit EvaluatorDigitFetch.Port.borrow
+ (bank tableBits t Z d.length i j labels cols s) digit []
+ Bounded (machine read).body
+ (stackFits (schedulerSpace (tableBits).length t Z d.length (workspace v e w extraSpace peak)))
+ (frame ∘ pay) (frame ∘ pay) (WeightedStep.ticks v e w time) := by
+ intro frame
+ apply fixedFrame_bounded φ dim extra he hw read i.val time peak _ _ (matrix i) (hr i) frame
+ (fun _ _ ↦ rfl) (fun _ ↦ rfl)
+ · intro x y k hk; cases k <;> first | rfl | exact (hk _ rfl).elim
+ · intro idx next q hn hq a k
+ have hh := frame_room φ dim extra es d extraSpace hextra i j labels cols hi.le hj.le peak idx next q hn hq a k
+ cases k with
+ | digit | borrow => simp [frame, EvaluatorDigitRepeat.frame, hsize, schedulerSpace, bankSpace, workspace]; omega
+ | _ => exact hh
+ · unfold schedulerSpace bankSpace workspace; omega
+
+end Evaluator.MatrixCallbacks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorCallbackSafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorCallbackSafety.lean
new file mode 100644
index 0000000000..ee84b83343
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorCallbackSafety.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.EvaluatorReadInterface
+import OAI.Computability.VPVNP.RoutineSpace
+import OAI.Computability.VPVNP.SpaceRunMonotone
+
+/-!
+# Storage specification of the coordinate-entry readers
+
+The streamed determinant queries may take exponentially many ticks. Their
+workspace bound records the peak height of each stack independently.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.MatrixCallbacks
+
+open RAMTape SliceArithmetic
+
+variable {P : Type} [DecidableEq P] {p e w v : ℕ} [Fact p.Prime]
+ {K : Type} [Field K] [Algebra (ZMod p) K] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (dim : BurstRAM.Word v) (extra : Stacks P)
+
+/-- Correct coordinate readback, with a peak bound on every stack throughout
+the deterministic call. Row and column use the scheduler's path orientation. -/
+def ReadsEntryWithin (read : FiniteRoutine (ReadPort P)) (w label time peak : ℕ)
+ (matrix : Matrix (Fin dim.val) (Fin dim.val) K) : Prop :=
+ ∀ (s : Fin dim.val × K) (j : Fin dim.val), ∃ d ≤ time, read.BoundedRun peak d
+ (queryBank (List.replicate label true) (WeightedStep.bank φ w dim s.1
+ (BurstRAM.wordBits (Fin.castLE dim.isLt.le j : BurstRAM.Word v)) [] s.2 extra))
+ (queryBank (List.replicate label true) (WeightedStep.bank φ w dim s.1
+ (BurstRAM.wordBits (Fin.castLE dim.isLt.le j : BurstRAM.Word v))
+ (WeightedStep.bits φ w (matrix s.1 j)) s.2 extra))
+
+/-- The same exact run supplies the count computation's readback law. -/
+theorem ReadsEntryWithin.readsEntry {read : FiniteRoutine (ReadPort P)} {label time peak : ℕ}
+ {matrix : Matrix (Fin dim.val) (Fin dim.val) K}
+ (h : ReadsEntryWithin φ dim extra read w label time peak matrix) :
+ ReadsEntry φ dim extra read w label time matrix := by
+ intro s j
+ obtain ⟨d, hd, hr⟩ := h s j
+ exact ⟨d, hd, hr.runs⟩
+
+theorem ReadsEntryWithin.mono {read : FiniteRoutine (ReadPort P)} {label time peak time' peak' : ℕ}
+ {matrix : Matrix (Fin dim.val) (Fin dim.val) K} (ht : time ≤ time') (hp : peak ≤ peak')
+ (h : ReadsEntryWithin φ dim extra read w label time peak matrix) :
+ ReadsEntryWithin φ dim extra read w label time' peak' matrix := by
+ intro s j
+ obtain ⟨d, hd, run⟩ := h s j
+ exact ⟨d, hd.trans ht, run.mono_cap hp⟩
+
+end Evaluator.MatrixCallbacks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorCanonicalLiteral.lean b/lean/OAI/Computability/VPVNP/EvaluatorCanonicalLiteral.lean
new file mode 100644
index 0000000000..a9a88c6b4e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorCanonicalLiteral.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.EvaluatorLiteralResources
+import OAI.Computability.VPVNP.LabelEvaluatorCanonical
+import OAI.Computability.VPVNP.EvaluatorAdviceBounds
+
+/-!
+# The literal evaluator for the canonical finite slice
+
+The basis and the unit ordinal used by the tape program are the dense
+ordinals furnished by the monomial prefix-rank queries. The physical matrix
+reader receives the source ordinal before the destination ordinal. The
+algebraic query returns the coefficient in the opposite order.
+
+The point-count bound gives an index word width fixed independently of the
+choice of pin values, the prime and the binary exponents.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LabelEvaluator
+
+open MvPolynomial FiniteSlice RAMTape Evaluator SliceArithmetic
+open Evaluator.MatrixCallbacks EvaluatorProgramRawInput Evaluator.BinaryMachine
+open RadicalCertificate.MonomialIndex
+
+local instance (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+/-- The finite enumeration of the slice ground field used to express canonical evaluator
+coordinates and bound the number of point ordinals. -/
+noncomputable local instance canonicalGroundFintype (p : Nat.Primes) (t d : ℕ) :
+ Fintype (Ground p t d) := Fintype.ofFinite _
+/-- Decidable equality on the finite slice ground field used by the canonical
+coordinate-algebra construction. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : DecidableEq (Ground p t d) := Classical.decEq _
+/-- The algebra structure on the ambient field induced by the chosen embedding of the finite
+slice ground field. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) :=
+ (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra
+
+variable {p : Nat.Primes} {t d m : ℕ} {ι : Type*} {F : ι → MvPolynomial (Fin t) ℤ}
+variable (M : Model p d F) {read : Fin m → (Fin t → ℕ) → ℤ}
+variable (D : (M.queryData read).Canonical (E := Ambient p) (sliceIdeal p d F M.pins M.values))
+
+include D in
+/-- The number of dense ordinals is bounded by the paper's geometric
+point count for the chosen slice. -/
+theorem Model.canonical_dimension_le : (M.queryData read).dimension ≤ pointCountBound t d := by
+ let I := sliceIdeal p d F M.pins M.values
+ let V := zeroLocus (Ambient p) I
+ let : Fintype V := M.finite.fintype
+ have hr := (coordinateAlgebra_finite_finrank (E := Ambient p) I).2
+ have he : Module.finrank (Ground p t d) (CoordinateAlgebra (Ground p t d) V) = (M.queryData read).dimension := by
+ simpa using Module.finrank_eq_card_basis D.denseBasis
+ rw [he, ← Nat.card_eq_fintype_card] at hr
+ exact hr.trans M.pointCount_le
+
+/-- An extra bit lets the register store the dimension itself, including at a power of two. -/
+def ordinalWidth (t d : ℕ) := Nat.clog 2 (pointCountBound t d) + 1
+
+include D in
+theorem Model.canonical_dimension_fits : (M.queryData read).dimension < 2^(ordinalWidth t d) := by
+ have h := (M.canonical_dimension_le D).trans (Nat.le_pow_clog (by decide : 1 < 2) _)
+ have hpos : 0 < 2^(Nat.clog 2 (pointCountBound t d)) := Nat.two_pow_pos _
+ rw [ordinalWidth, pow_succ]
+ omega
+
+theorem ordinalWidth_polynomiallyBounded {t d : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n)) :
+ PolynomiallyBounded (fun n => ordinalWidth (t n) (d n)) :=
+ (pointCountBound_clog ht hd).add (.const 1)
+
+variable {P : Type} [DecidableEq P] [Fintype P] {g v w Z : ℕ} {c : SliceArithmetic.Vector p.val (g+1)}
+
+variable (hdim : (M.queryData read).dimension < 2^v)
+/-- The dimension of the canonical coordinate-algebra presentation encoded in a v-bit word for
+the evaluator. -/
+noncomputable abbrev Model.dimensionWord : BurstRAM.Word v := ⟨(M.queryData read).dimension, hdim⟩
+local notation "dimWord" => M.dimensionWord hdim
+local notation "unitOrd" => D.ordinal.symm D.presentation.unitIndex
+local notation "ground" => Ground p t d
+local notation "ports" => MachinePort (WeightedStep.Port P)
+
+/-- Instantiate equation (8.2) and the uniform head bound on the canonical
+Macaulay presentation. Both assertions concern the same literal two-tape
+program and the same raw input. -/
+theorem Model.canonical_literal_evaluator
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p.val] ground)
+ (hcoord : ∀ y, SliceEvaluator.primeCoordinate p.val ground (φ (value (modulus c) y)) =
+ ((y (0 : Fin (g+1))).val : ZMod p.val))
+ (ps : List (WeightedStep.Port P)) (hps : ps.Nodup) (hall : ∀ i, i ∈ ps)
+ (frob label : FiniteRoutine (ReadPort P)) (extra : Stacks P) (extraSpace : ℕ)
+ (hextra : ∀ i, (extra i).length ≤ extraSpace) (hw : Word.workingWidth p.val ≤ w)
+ (divisor : List Bool) (hd : TapeWord.value divisor = Fintype.card ground)
+ (FT LT peak : ℕ)
+ (hf : ReadsEntryWithin φ dimWord extra frob w 0 FT peak
+ (fun src dest => (M.queryData read).matrixEntry .frobenius dest src))
+ (hl : ∀ j : Fin t, ReadsEntryWithin φ dimWord extra label w j.val LT peak
+ (fun src dest => (M.queryData read).matrixEntry (.label j) dest src))
+ (es : Fin t → BurstRAM.Word Z) (ticks : ℕ)
+ (hclock : let raw := advice ps t divisor (payload φ dimWord extra w (unitOrd,1)) ++ runtime es
+ let adv := adviceCap ps.length t divisor.length (WeightedStep.bankSpace v (g+1) w extraSpace)
+ tapeTicks raw.length (Fintype.card ports) (fullTicks t Z divisor.length (TapeWord.value divisor)
+ adv (WeightedStep.ticks v (g+1) w FT) (WeightedStep.ticks v (g+1) w LT) v w) ≤ ticks) :
+ let E := MatrixCallbacks.program ps frob label
+ let raw := advice ps t divisor (payload φ dimWord extra w (unitOrd,1)) ++ runtime es
+ let adv := adviceCap ps.length t divisor.length (WeightedStep.bankSpace v (g+1) w extraSpace)
+ (UniversalMachine.paths E ticks (UniversalMachine.initial E raw) : ZMod p.val) =
+ (M.withCanonicalPresentation D).functional (∏ j, M.labels j ^ (es j).val) ∧
+ ∀ bits, let dis := choiceDisplacement E (UniversalMachine.initial E raw) bits
+ StackCompiler.HeadBox (headRadius (Fintype.card ports)
+ (fullSpace t Z divisor.length (workspace v (g+1) w extraSpace peak) adv v w)) dis.1 dis.2 := by
+ have hf' : ReadsEntryWithin φ dimWord extra frob w 0 FT peak
+ ((LinearMap.toMatrixAlgEquiv D.denseBasis) (FiniteField.frobeniusAlgHom ground M.algebra).toLinearMap).transpose := by
+ have h := D.frobenius_transition (show (M.queryData read).fieldOrder = Fintype.card ground from rfl)
+ exact (show _ = _ from funext fun i => funext (h i)) ▸ hf
+ have hl' (j : Fin t) : ReadsEntryWithin φ dimWord extra label w j.val LT peak
+ ((LinearMap.toMatrixAlgEquiv D.denseBasis) (LinearMap.mulLeft ground (M.labels j))).transpose := by
+ have h := D.label_transition j
+ exact (show _ = _ from funext fun i => funext (h i)) ▸ hl j
+ obtain ⟨h,space⟩ := literal_from_bounded_readers ps frob label φ dimWord extra extraSpace hextra
+ unitOrd D.denseBasis M.labels es divisor hps hall hw hd FT LT peak hf' hl' D.denseBasis_unit D.unit_ordinal
+ hcoord ticks hclock
+ exact ⟨h.trans (D.functional_apply _).symm, space⟩
+
+end LabelEvaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorCellSafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorCellSafety.lean
new file mode 100644
index 0000000000..f357052be7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorCellSafety.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.EvaluatorDigitAction
+import OAI.Computability.VPVNP.EvaluatorDigitSafety
+import OAI.Computability.VPVNP.EvaluatorRoutineSafety
+
+/-!
+# Time and peak storage for one complete label action
+
+A deterministic lookup uses a polynomial number of temporary bits. Once the
+lookup returns, its temporary stacks are empty and only one digit's worth of
+counter storage is live. The subsequent countdown can invoke exponentially
+many callbacks without accumulating any of their work space.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorCellSafety
+
+open RAMTape EvaluatorDigitFetch EvaluatorDigitRepeat EvaluatorDigitCallbacks
+open EvaluatorDigitSafety EvaluatorRadixRows EvaluatorDigitAction EvaluatorRoutineSafety
+
+variable {P S : Type} [DecidableEq P] (body : FiniteRoutine (Port P))
+ (safe : Stacks (Port P) → Prop) (payload : S → Stacks P)
+ {t Z : ℕ} (e : Fin t → BurstRAM.Word Z) (ℓ Q B : ℕ) (hq : 0 < Q) (hfit : Q ≤ 2^ℓ)
+ (i : Fin t) (j : Fin Z) (labelsLeft colsLeft : ℕ)
+
+local notation "pre" => bank (packedTable ℓ Q (List.ofFn e)) t Z ℓ i.val j.val labelsLeft colsLeft ∘ payload
+local notation "fetchBound" => (19*(t*Z)+13*(t*Z*ℓ)+4)
+
+include hq hfit in
+/-- All normal returns preserve the scheduler bank outside the evaluator
+payload. Both successful and rejecting paths obey the cell clock. -/
+theorem cell_bounded
+ (room : ∀ x s, (∀ k, (s k).length ≤ (pre x k).length+fetchBound) → safe s)
+ (frames : ∀ x (xs ys : List Bool), xs.length+ys.length ≤ ℓ →
+ safe (frame .digit .borrow (pre x) xs ys))
+ (callback : ∀ (bits : List Bool), bits.length = ℓ →
+ Bounded body.body safe (fun x => frame .digit .borrow (pre x) bits [])
+ (fun x => frame .digit .borrow (pre x) bits []) B) :
+ Bounded (cellRoutine body).body safe pre pre (cellBudget t Z ℓ Q B) := by
+ let d := (e i).val / Q^(Z-1-j.val) % Q
+ let bits := PrimedCounter.digits ℓ d
+ let loaded (x : S) := frame .digit .borrow (pre x) bits []
+ have hw : bits.length = ℓ := by simp [bits, PrimedCounter.digits]
+ have hd : d < Q := Nat.mod_lt _ hq
+ have hv : TapeWord.value bits = d := by
+ simp [bits, PrimedCounter.digits, TapeWord.value_wordBits, Nat.mod_eq_of_lt (hd.trans_le hfit)]
+ have fetchSafe : Bounded fetch.body safe pre loaded fetchBound := by
+ apply Bounded.of_runs_with_room (g := id) _ room
+ intro x
+ exact ⟨_, fetchTicks_le_cells i.isLt j.isLt ℓ, fetch_cell_runs payload e ℓ Q i j labelsLeft colsLeft x⟩
+ have loopSafe : Bounded (repeatRoutine .digit .borrow body.body) safe loaded pre (repeatBudget ℓ B d) := by
+ intro extra fuel hf x c hc
+ apply repeat_safe Port.digit .borrow (by intro h; cases h) body.body safe c pre ℓ B frames _
+ d bits hw hv x extra fuel hf
+ · intro y n hn
+ rw [Function.comp_apply, frame_digit]
+ have hempty : Function.update (pre y) Port.digit [] = pre y := Function.update_eq_self ..
+ exact hempty.symm ▸ hc y n hn
+ · intro y counter hl rest n enough cont finish
+ exact callback counter hl rest n enough y cont finish
+ apply (fetchSafe.followedBy loopSafe).mono
+ exact Nat.add_le_add_left (Nat.mul_le_mul_right (4*ℓ+B+3) hd) fetchBound
+
+end EvaluatorCellSafety
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorChronologicalLoop.lean b/lean/OAI/Computability/VPVNP/EvaluatorChronologicalLoop.lean
new file mode 100644
index 0000000000..da8f6a5a88
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorChronologicalLoop.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.EvaluatorDigitFetch
+import OAI.Computability.VPVNP.EvaluatorTallySemantics
+
+/-! # Chronological traversal of the evaluator digit table
+
+For every digit column the finite control invokes the Frobenius routine,
+initializes a label counter and scans the labels in order. Both counters live
+on stacks, so the same control works at every width and every label count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorChronologicalLoop
+
+open RAMTape EvaluatorRoutine EvaluatorDigitFetch EvaluatorTallyLoop
+
+variable {P : Type} [DecidableEq P]
+
+/-- One column starts with Frobenius, then enumerates the label digits. -/
+def column (frobenius cell : FiniteRoutine (Port P)) : FiniteRoutine (Port P) :=
+ (frobenius.followedBy (EvaluatorDigitAddress.copyCount .labels .labelsLeft .copyTmp)).followedBy
+ (.ofRoutine (tallyLoop .labelsLeft (.addr .labelIndex) cell.body))
+
+/-- The entry consumes one remaining-column mark per column. -/
+def traverse (frobenius cell : FiniteRoutine (Port P)) : FiniteRoutine (Port P) :=
+ .ofRoutine (tallyLoop .colsLeft (.addr .columnIndex) (column frobenius cell).body)
+
+variable {S : Type*} (data : List Bool) (t Z ℓ : ℕ) (payload : S → Stacks P)
+
+theorem labelBank (j colsLeft : ℕ) :
+ TallyBank (Port.labelsLeft : Port P) (.addr .labelIndex)
+ (fun i rem x => bank data t Z ℓ i j rem colsLeft (payload x)) := by
+ constructor
+ · intros; rfl
+ · intros; rfl
+ · intro i r x; funext p; cases p <;> rfl
+ · intro i r x; funext p; cases p with
+ | addr k => cases k <;> rfl
+ | _ => rfl
+ · intro i x; funext p; cases p with
+ | addr k => cases k <;> rfl
+ | _ => rfl
+
+theorem columnBank :
+ TallyBank (Port.colsLeft : Port P) (.addr .columnIndex)
+ (fun j rem x => bank data t Z ℓ 0 j 0 rem (payload x)) := by
+ constructor
+ · intros; rfl
+ · intros; rfl
+ · intro i r x; funext p; cases p <;> rfl
+ · intro i r x; funext p; cases p with
+ | addr k => cases k <;> rfl
+ | _ => rfl
+ · intro i x; funext p; cases p with
+ | addr k => cases k <;> rfl
+ | _ => rfl
+
+/-- The elementary control allowance for one complete column. -/
+def columnBudget (t BF BC : ℕ) := BF + (5*t+2) + (t*(BC+2)+t+2)
+
+/-- The elementary control allowance for the entire digit schedule. -/
+def traverseBudget (t Z BF BC : ℕ) := Z*(columnBudget t BF BC+2)+Z+2
+
+/-- Correctness of the column scan for callbacks with the indicated state effects. -/
+theorem column_realizes (frobenius cell : FiniteRoutine (Port P)) (j colsLeft BF BC : ℕ)
+ (stepF : (S → ℕ) → S → ℕ) (stepC : ℕ → (S → ℕ) → S → ℕ)
+ (hF : Realizes frobenius.body
+ (fun x => bank data t Z ℓ 0 j 0 colsLeft (payload x))
+ (fun x => bank data t Z ℓ 0 j 0 colsLeft (payload x)) BF stepF)
+ (hC : ∀ i rem, i+rem < t → Realizes cell.body
+ (fun x => bank data t Z ℓ i j rem colsLeft (payload x))
+ (fun x => bank data t Z ℓ i j rem colsLeft (payload x)) BC (stepC i)) :
+ Realizes (column frobenius cell).body
+ (fun x => bank data t Z ℓ 0 j 0 colsLeft (payload x))
+ (fun x => bank data t Z ℓ 0 j 0 colsLeft (payload x)) (columnBudget t BF BC)
+ (fun f => stepF ((List.range t).foldr stepC f)) := by
+ have hcopy : Realizes (EvaluatorDigitAddress.copyCount Port.labels Port.labelsLeft Port.copyTmp).body
+ (fun x => bank data t Z ℓ 0 j 0 colsLeft (payload x))
+ (fun x => bank data t Z ℓ 0 j t colsLeft (payload x)) (5*t+2) (fun f x => f x) := by
+ apply Realizes.of_runs
+ intro x
+ refine ⟨_, le_rfl, ?_⟩
+ let s := bank data t Z ℓ 0 j 0 colsLeft (payload x)
+ have hc := EvaluatorDigitAddress.copyCount_runs Port.labels Port.labelsLeft Port.copyTmp
+ (by intro h; cases h) (by intro h; cases h) (by intro h; cases h) s t 0 rfl rfl rfl
+ have he : Function.update s Port.labelsLeft (List.replicate (0+t) true) =
+ bank data t Z ℓ 0 j t colsLeft (payload x) := by
+ funext p; cases p <;> simp [s, bank]
+ exact he ▸ hc
+ have hloop := loop_realizes Port.labelsLeft (.addr .labelIndex) cell.body _
+ (labelBank data t Z ℓ payload j colsLeft) BC stepC 0 t (by simpa using hC)
+ simpa only [column, FiniteRoutine.followedBy, FiniteRoutine.ofRoutine,
+ columnBudget, Nat.zero_add, List.range_eq_range'] using (hF.followedBy hcopy).followedBy hloop
+
+/-- The complete scan first composes labels within a column, then composes
+the columns chronologically. Both per-call bounds are independent of the indices. -/
+theorem traverse_realizes (frobenius cell : FiniteRoutine (Port P)) (BF BC : ℕ)
+ (stepF : (S → ℕ) → S → ℕ) (stepC : ℕ → ℕ → (S → ℕ) → S → ℕ)
+ (hF : ∀ j left, j+left < Z → Realizes frobenius.body
+ (fun x => bank data t Z ℓ 0 j 0 left (payload x))
+ (fun x => bank data t Z ℓ 0 j 0 left (payload x)) BF stepF)
+ (hC : ∀ j left, j+left < Z → ∀ i rem, i+rem < t → Realizes cell.body
+ (fun x => bank data t Z ℓ i j rem left (payload x))
+ (fun x => bank data t Z ℓ i j rem left (payload x)) BC (stepC j i)) :
+ Realizes (traverse frobenius cell).body
+ (fun x => bank data t Z ℓ 0 0 0 Z (payload x))
+ (fun x => bank data t Z ℓ 0 0 0 0 (payload x)) (traverseBudget t Z BF BC)
+ (fun f => (List.range Z).foldr
+ (fun j g => stepF ((List.range t).foldr (stepC j) g)) f) := by
+ have hloop := loop_realizes Port.colsLeft (.addr .columnIndex) (column frobenius cell).body _
+ (columnBank data t Z ℓ payload) (columnBudget t BF BC)
+ (fun j g => stepF ((List.range t).foldr (stepC j) g)) 0 Z (by
+ intro j left h
+ exact column_realizes data t Z ℓ payload frobenius cell j left BF BC stepF (stepC j)
+ (hF _ _ (by omega)) (hC _ _ (by omega)))
+ simpa only [traverse, FiniteRoutine.ofRoutine, traverseBudget, Nat.zero_add,
+ List.range_eq_range'] using hloop
+
+end EvaluatorChronologicalLoop
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorChronologicalSafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorChronologicalSafety.lean
new file mode 100644
index 0000000000..6848437097
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorChronologicalSafety.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.EvaluatorChronologicalLoop
+import OAI.Computability.VPVNP.EvaluatorTallySafety
+import OAI.Computability.VPVNP.EvaluatorDigitRepeat
+
+/-! # Storage and stopping bounds for both evaluator cursors
+
+The table, index tallies, and callback registers account for the storage
+between calls. Address lookup and initialization use polynomial scratch
+space. The binary digit can trigger many callbacks without increasing the
+cursor storage between them.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorChronologicalLoop
+
+open RAMTape EvaluatorDigitFetch EvaluatorTallyLoop EvaluatorRoutineSafety
+
+variable {P S : Type} [DecidableEq P]
+
+/-- Maximum length of a single stack between callbacks. -/
+def bankSpace (tableBits t Z ℓ payloadSpace : ℕ) :=
+ payloadSpace + tableBits + t + Z + ℓ
+
+/-- A polynomial allowance for addressing, fetching, and both cursor loops. -/
+def schedulerSpace (tableBits t Z ℓ payloadSpace : ℕ) :=
+ bankSpace tableBits t Z ℓ payloadSpace + (19*(t*Z) + 13*(t*Z*ℓ) + 4) + (5*t+2) + ℓ
+
+variable (data : List Bool) (t Z ℓ space : ℕ) (payload : S → Stacks P)
+variable (hp : ∀ x p, (payload x p).length ≤ space)
+
+include hp
+
+omit [DecidableEq P] in
+theorem bank_length {i j left cols : ℕ} (hi : i+left ≤ t) (hj : j+cols ≤ Z)
+ (x : S) (p : Port P) :
+ (bank data t Z ℓ i j left cols (payload x) p).length ≤ bankSpace data.length t Z ℓ space := by
+ cases p with
+ | addr k =>
+ cases k <;> simp only [bank, EvaluatorDigitAddress.ready, Tally.encode,
+ EvaluatorDigitAddress.registers, List.length_replicate, bankSpace] <;> omega
+ | work p =>
+ exact (hp x p).trans (by unfold bankSpace; omega)
+ | _ => simp [bank, bankSpace] <;> omega
+
+local notation "cap" => schedulerSpace data.length t Z ℓ space
+/-- The storage condition that every named evaluator stack has length at most the given limit. -/
+abbrev stackFits {K : Type} (limit : ℕ) (s : Stacks K) : Prop := ∀ p, (s p).length ≤ limit
+
+local notation "fits" => stackFits cap
+
+/-- The unary copy that starts a column and the subsequent label scan respect
+the same space bound as the supplied matrix callbacks. -/
+theorem column_bounded (frobenius cell : FiniteRoutine (Port P)) (j cols BF BC : ℕ)
+ (hj : j+cols ≤ Z)
+ (hF : Bounded frobenius.body fits
+ (fun x => bank data t Z ℓ 0 j 0 cols (payload x))
+ (fun x => bank data t Z ℓ 0 j 0 cols (payload x)) BF)
+ (hC : ∀ i left, i+left < t → Bounded cell.body fits
+ (fun x => bank data t Z ℓ i j left cols (payload x))
+ (fun x => bank data t Z ℓ i j left cols (payload x)) BC) :
+ Bounded (column frobenius cell).body fits
+ (fun x => bank data t Z ℓ 0 j 0 cols (payload x))
+ (fun x => bank data t Z ℓ 0 j 0 cols (payload x)) (columnBudget t BF BC) := by
+ have hcopy : Bounded (EvaluatorDigitAddress.copyCount Port.labels Port.labelsLeft Port.copyTmp).body fits
+ (fun x => bank data t Z ℓ 0 j 0 cols (payload x))
+ (fun x => bank data t Z ℓ 0 j t cols (payload x)) (5*t+2) := by
+ apply Bounded.of_runs_with_room (g := id)
+ · intro x
+ let s := bank data t Z ℓ 0 j 0 cols (payload x)
+ have hc := EvaluatorDigitAddress.copyCount_runs Port.labels Port.labelsLeft Port.copyTmp
+ (by intro h; cases h) (by intro h; cases h) (by intro h; cases h) s t 0 rfl rfl rfl
+ have he : Function.update s Port.labelsLeft (List.replicate (0+t) true) =
+ bank data t Z ℓ 0 j t cols (payload x) := by funext p; cases p <;> simp [s, bank]
+ exact ⟨_, le_rfl, he ▸ hc⟩
+ · intro x u hu p
+ have hh := bank_length data t Z ℓ space payload hp (i := 0) (left := 0) (by omega) hj x p
+ have h := hu p
+ unfold schedulerSpace
+ omega
+ have hloop := loop_bounded Port.labelsLeft (.addr .labelIndex) cell.body _
+ (labelBank data t Z ℓ payload j cols) fits BC 0 t (by
+ intro i left hi x p
+ have h := bank_length data t Z ℓ space payload hp (by omega : i+left ≤ t) hj x p
+ exact h.trans (by unfold schedulerSpace; omega)) (by simpa using hC)
+ simpa only [column, FiniteRoutine.followedBy, FiniteRoutine.ofRoutine, columnBudget, Nat.zero_add] using
+ (hF.followedBy hcopy).followedBy hloop
+
+/-- Every branch of the complete nested traversal respects the clock and peak
+storage, including branches that reject within a matrix query. -/
+theorem traverse_bounded (frobenius cell : FiniteRoutine (Port P)) (BF BC : ℕ)
+ (hF : ∀ j cols, j+cols < Z → Bounded frobenius.body fits
+ (fun x => bank data t Z ℓ 0 j 0 cols (payload x))
+ (fun x => bank data t Z ℓ 0 j 0 cols (payload x)) BF)
+ (hC : ∀ j cols, j+cols < Z → ∀ i left, i+left < t → Bounded cell.body fits
+ (fun x => bank data t Z ℓ i j left cols (payload x))
+ (fun x => bank data t Z ℓ i j left cols (payload x)) BC) :
+ Bounded (traverse frobenius cell).body fits
+ (fun x => bank data t Z ℓ 0 0 0 Z (payload x))
+ (fun x => bank data t Z ℓ 0 0 0 0 (payload x)) (traverseBudget t Z BF BC) := by
+ have hloop := loop_bounded Port.colsLeft (.addr .columnIndex) (column frobenius cell).body _
+ (columnBank data t Z ℓ payload) fits (columnBudget t BF BC) 0 Z (by
+ intro j cols hj x p
+ have h := bank_length data t Z ℓ space payload hp (i := 0) (left := 0) (by omega)
+ (by omega : j+cols ≤ Z) x p
+ exact h.trans (by unfold schedulerSpace; omega)) (by
+ intro j cols hj
+ exact column_bounded data t Z ℓ space payload hp frobenius cell j cols BF BC (by omega)
+ (hF _ _ (by omega)) (hC _ _ (by omega)))
+ simpa only [traverse, FiniteRoutine.ofRoutine, traverseBudget, Nat.zero_add] using hloop
+
+end EvaluatorChronologicalLoop
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorCoordinateMachine.lean b/lean/OAI/Computability/VPVNP/EvaluatorCoordinateMachine.lean
new file mode 100644
index 0000000000..6c098cb057
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorCoordinateMachine.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.EvaluatorReadInterface
+
+/-!
+# The binary evaluator from its two deterministic coordinate readers
+
+The entire stack machine, including binary input decoding and terminal
+branching, has fixed control as soon as its two entry readers are fixed.
+The two coordinate-query contracts concern only the stored row and column
+and the field element returned. The exponent width occurs only in the input,
+radix conversion and digit traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.MatrixCallbacks
+
+open RAMTape SliceArithmetic EvaluatorProgramRawInput
+
+variable {P : Type} [DecidableEq P] (ps : List (WeightedStep.Port P))
+ (frobenius label : FiniteRoutine (ReadPort P))
+
+/-- A single literal two-tape evaluator table built from the fixed entry
+readers, independently of the ground field or exponent width at a given input. -/
+noncomputable def program [Fintype P] : UniversalMachine.Program :=
+ BinaryMachine.program ps outputPort (machine frobenius) (machine label)
+
+variable {p d v w t Z : ℕ} [Fact p.Prime] {K A : Type} [Field K] [Fintype K]
+ [Algebra (ZMod p) K] [CommRing A] [Algebra K A] [Algebra (ZMod p) A]
+ [IsScalarTower (ZMod p) K A] {c : Vector p (d+1)}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (dim : BurstRAM.Word v)
+ (extra : Stacks P) (u : Fin dim.val) (basis : Module.Basis (Fin dim.val) K A)
+ (X : Fin t → A) (es : Fin t → BurstRAM.Word Z) (divisor : List Bool)
+
+local notation "pay" => payload φ dim extra w
+local notation "T" f => WeightedStep.ticks v (d+1) w f
+
+/-- Equation (8.2) for the actual bit-stack machine, assuming just correctness
+and running times for the two deterministic coordinate-entry readers on the
+advised matrix data. The scalar update and nondeterministic control are the
+concrete programs of the preceding modules. -/
+theorem count_from_readers (hp : ps.Nodup) (hall : ∀ a, a ∈ ps) (hunit : basis u = 1)
+ (hu : u.val = 0) (hw : Word.workingWidth p ≤ w)
+ (hcoord : ∀ y, SliceEvaluator.primeCoordinate p K (φ (value (modulus c) y)) =
+ ((y (0 : Fin (d+1))).val : ZMod p))
+ (hd : TapeWord.value divisor = Fintype.card K)
+ (R F L : ℕ) (hr : ∀ s, readTicks ps es divisor (pay s) ≤ R)
+ (hf : ReadsEntry φ dim extra frobenius w 0 F
+ ((LinearMap.toMatrixAlgEquiv basis) (FiniteField.frobeniusAlgHom K A).toLinearMap).transpose)
+ (hl : ∀ i : Fin t, ReadsEntry φ dim extra label w i.val L
+ ((LinearMap.toMatrixAlgEquiv basis) (LinearMap.mulLeft K (X i))).transpose)
+ (fuel : ℕ) (ht : 3*w+3+v + (R + (EvaluatorProgramInput.convertTicks t Z divisor.length +
+ EvaluatorMonomialSchedule.budget t Z divisor.length (TapeWord.value divisor) (T F) (T L))) ≤ fuel) :
+ let r := (BinaryMachine.evaluator ps outputPort (machine frobenius) (machine label)).body
+ let raw := advice ps t divisor (pay (u,1)) ++ runtime es
+ (stackPaths (r.close false) fuel (some r.entry) (StackCompiler.labeledInput none raw) : ZMod p) =
+ primeFunctional basis u (SliceEvaluator.primeCoordinate p K) (∏ i, X i ^ (es i).val) := by
+ exact BinaryMachine.stackCount_mod basis u (SliceEvaluator.primeCoordinate p K) X es divisor pay
+ outputPort (machine frobenius) (machine label) (T F) (T L) ps hp hall outputPort_injective hunit hu
+ dim.isLt.le hw hd (fun s ↦ output_data dim extra φ hcoord hw s.1 s.2) R hr
+ (frobenius_realizes φ dim extra basis X es divisor (by omega) hw frobenius F hf)
+ (label_callback φ dim extra basis X es divisor (by omega) hw label L hl) fuel ht
+
+end Evaluator.MatrixCallbacks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorDigitAction.lean b/lean/OAI/Computability/VPVNP/EvaluatorDigitAction.lean
new file mode 100644
index 0000000000..161e7da0f1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorDigitAction.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.EvaluatorDigitFetch
+import OAI.Computability.VPVNP.EvaluatorDigitCallbacks
+import OAI.Computability.VPVNP.EvaluatorRadixRows
+import OAI.Computability.VPVNP.EvaluatorRoutine
+
+/-!
+# Executing one label at one radix position
+
+The cell control reads its binary counter from the packed table. At the
+most-significant-first position `j` of exponent `eᵢ`, it executes the
+label callback precisely `⌊eᵢ / Q^(Z-1-j)⌋ mod Q` times on every successful
+path. The returned scheduler bank is ready for the next label.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorDigitAction
+
+open RAMTape EvaluatorDigitFetch EvaluatorDigitRepeat EvaluatorDigitCallbacks
+open EvaluatorRadixRows EvaluatorRoutine
+
+variable {P S I : Type}
+
+/-- Both the lookup control and the decrement loop are fixed across all
+rows, columns, field cardinalities, and input widths. -/
+def cellRoutine (body : FiniteRoutine (Port P)) : FiniteRoutine (Port P) :=
+ fetch.followedBy (.ofRoutine (repeatRoutine .digit .borrow body.body))
+
+/-- A per-label clock independent of the two cursor positions. -/
+def cellBudget (t Z ℓ Q B : ℕ) :=
+ 19*(t*Z) + 13*(t*Z*ℓ) + 4 + Q*(4*ℓ+B+3)
+
+theorem frame_digit [DecidableEq P] (data : List Bool)
+ (t Z ℓ i j labelsLeft colsLeft : ℕ) (p : Stacks P) (bits : List Bool) :
+ frame Port.digit .borrow (bank data t Z ℓ i j labelsLeft colsLeft p) bits [] =
+ Function.update (bank data t Z ℓ i j labelsLeft colsLeft p) Port.digit bits := by
+ funext k
+ cases k <;> rfl
+
+variable [DecidableEq P] [Fintype I] (body : FiniteRoutine (Port P))
+ (payload : S → Stacks P) (next : S → I → S) {t Z : ℕ} (e : Fin t → BurstRAM.Word Z)
+ (ℓ Q B : ℕ) (hq : 0 < Q) (hfit : Q ≤ 2 ^ ℓ) (i : Fin t) (j : Fin Z)
+ (labelsLeft colsLeft : ℕ)
+
+local notation "data" => packedTable ℓ Q (List.ofFn e)
+local notation "pre" => bank data t Z ℓ i.val j.val labelsLeft colsLeft ∘ payload
+local notation "digitValue" => Fin.val (e i) / Q^(Z-1-j.val) % Q
+
+/-- At any legal pair of cursor positions the deterministic lookup
+prepares the exact radix digit for the countdown. -/
+theorem fetch_cell_runs (x : S) :
+ fetch.Runs (fetchTicks i.val Z j.val ℓ) (pre x)
+ (frame .digit .borrow (pre x) (PrimedCounter.digits ℓ digitValue) []) := by
+ have hi : i.val < (List.ofFn e).length := by simp
+ have fits : (i.val*Z+j.val)*ℓ+ℓ ≤ (data).length := by
+ simpa [Nat.mul_assoc] using EvaluatorDigitAddress.cell_fits i.isLt j.isLt ℓ
+ have cell : (((data).drop ((i.val*Z+j.val)*ℓ)).take ℓ) = PrimedCounter.digits ℓ digitValue := by
+ simpa using packedTable_cell ℓ Q (List.ofFn e) [] i.val j.val hi j.isLt
+ have h := fetch_runs data t Z ℓ i.val j.val labelsLeft colsLeft (payload x) fits
+ rw [cell, ← frame_digit] at h
+ exact h
+
+include hq hfit in
+/-- A callback preserves the scheduler registers on every normal return. Its
+integer count can include any finite number of distinct outcomes, including
+outcomes that share a successor state. -/
+theorem cellRoutine_realizes
+ (callback : ∀ x bits fuel, (bits : List Bool).length = ℓ → B ≤ fuel →
+ ∃ delay : I → ℕ, (∀ a, delay a ≤ B) ∧ ∀ c,
+ body.body.count c fuel (frame .digit .borrow (pre x) bits []) =
+ ∑ a, c (fuel-delay a) (frame .digit .borrow (pre (next x a)) bits [])) :
+ Realizes (cellRoutine body).body pre pre (cellBudget t Z ℓ Q B)
+ (fun f x => ∑ z : Fin digitValue → I, f ((List.ofFn z).foldl next x)) := by
+ let d := digitValue
+ let bits := PrimedCounter.digits ℓ d
+ let loaded (x : S) := frame .digit .borrow (pre x) bits []
+ have hw : bits.length = ℓ := by simp [bits, PrimedCounter.digits]
+ have hd : d < Q := Nat.mod_lt _ hq
+ have hv : TapeWord.value bits = d := by
+ simp [bits, PrimedCounter.digits, TapeWord.value_wordBits, Nat.mod_eq_of_lt (hd.trans_le hfit)]
+ let fetchBound := 19*(t*Z)+13*(t*Z*ℓ)+4
+ have prefixRun : Realizes fetch.body pre loaded fetchBound (fun f x => f x) := by
+ apply Realizes.of_runs (g := id)
+ intro x
+ exact ⟨fetchTicks i.val Z j.val ℓ, fetchTicks_le_cells i.isLt j.isLt ℓ,
+ fetch_cell_runs payload e ℓ Q i j labelsLeft colsLeft x⟩
+ have loop : Realizes (repeatRoutine .digit .borrow body.body) loaded pre (repeatBudget ℓ B d)
+ (fun f x => ∑ z : Fin d → I, f ((List.ofFn z).foldl next x)) := by
+ apply Realizes.of_delay (next := fun x z => (List.ofFn z).foldl next x)
+ intro x fuel hf
+ obtain ⟨delay, hdelay, he⟩ := repeat_count_of_bound Port.digit .borrow (by intro h; cases h) body.body
+ pre next ℓ B callback d bits hw hv x fuel hf
+ refine ⟨delay, hdelay, fun c => ?_⟩
+ rw [he c]
+ apply Finset.sum_congr rfl
+ intro z _
+ have empty (y : S) : frame .digit .borrow (pre y) [] [] = pre y := by
+ rw [Function.comp_apply, frame_digit]
+ exact Function.update_eq_self ..
+ rw [empty]
+ apply (prefixRun.followedBy loop).mono
+ exact Nat.add_le_add_left (Nat.mul_le_mul_right (4*ℓ+B+3) hd) fetchBound
+
+end EvaluatorDigitAction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorDigitAddress.lean b/lean/OAI/Computability/VPVNP/EvaluatorDigitAddress.lean
new file mode 100644
index 0000000000..6c74b3036a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorDigitAddress.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.TallyConstants
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-!
+# Computing an address in the packed radix table
+
+Each of the label rows holds `Z` digits, each of width `ℓ`. Fixed stack code
+forms the row-major bit address from unary indices and copies the digit width
+for the destructive lookup. The indices and dimensions survive every call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorDigitAddress
+
+open RAMTape RAMTape.Tally
+
+/-- Unary registers for the label and column ordinals, row and digit widths, computed address
+and scratch used to locate a radix digit. -/
+inductive Port where
+ | labelIndex | rounds | columnIndex | width | offset | cellWidth | ordinal | outer | tmp
+ deriving DecidableEq
+
+instance : Fintype Port :=
+ ⟨{.labelIndex, .rounds, .columnIndex, .width, .offset, .cellWidth, .ordinal, .outer, .tmp},
+ by intro k; cases k <;> decide⟩
+
+/-- The physical calculation first forms the cell ordinal, then scales it by
+the bit width. All temporary registers are cleared before returning. -/
+def addressProgram : Program Port :=
+ (Program.mul .labelIndex .rounds .ordinal .outer .tmp (by decide)).seq <|
+ (Program.copy .columnIndex .ordinal .tmp (by decide) (by decide) (by decide)).seq <|
+ (Program.mul .ordinal .width .offset .outer .tmp (by decide)).seq <|
+ (Program.copy .width .cellWidth .tmp (by decide) (by decide) (by decide)).seq <|
+ Program.clear .ordinal
+
+/-- The fixed stack routine that computes the starting bit address of a row-major digit cell
+and prepares its width for lookup. -/
+def addressRoutine : FiniteRoutine Port := .ofRoutine addressProgram.code
+
+/-- Register contents for label i and column j in a row with Z cells of width ℓ, including the
+offset and cell-width tallies. -/
+def registers (i Z j ℓ o w : ℕ) : State Port
+ | .labelIndex => i
+ | .rounds => Z
+ | .columnIndex => j
+ | .width => ℓ
+ | .offset => o
+ | .cellWidth => w
+ | _ => 0
+
+/-- Initial unary registers for one cell. -/
+def ready (i Z j ℓ : ℕ) := encode (registers i Z j ℓ 0 0)
+
+/-- Address and width for the packed lookup, alongside the preserved inputs. -/
+def result (i Z j ℓ : ℕ) := encode (registers i Z j ℓ ((i*Z+j)*ℓ) ℓ)
+
+/-- Number of stack instructions used to compute the bit address and copy the cell width for
+digit (i,j). -/
+def addressTicks (i Z j ℓ : ℕ) := i*(5*Z+6) + 5*j + (i*Z+j)*(5*ℓ+8) + 5*ℓ + 9
+
+theorem addressRoutine_runs (i Z j ℓ : ℕ) :
+ addressRoutine.Runs (addressTicks i Z j ℓ) (ready i Z j ℓ) (result i Z j ℓ) := by
+ let s := registers i Z j ℓ 0 0
+ have hr : addressProgram.ready s := by
+ simp (config := { decide := true }) [addressProgram, s, registers]
+ have he : addressProgram.eval s = registers i Z j ℓ ((i*Z+j)*ℓ) ℓ := by
+ funext k
+ cases k <;> simp (config := { decide := true }) [addressProgram, s, registers]
+ have ht : addressProgram.work s = addressTicks i Z j ℓ := by
+ simp (config := { decide := true }) [addressProgram, s, registers, addressTicks]
+ ring
+ have h := addressProgram.spec s hr
+ rw [he, ht] at h
+ exact h
+
+/-- The address calculation can be called while the packed table, digit
+accumulator, and evaluator state occupy arbitrary other stacks. -/
+theorem addressRoutine_runs_framed {K : Type} [DecidableEq K] {p : Port → K}
+ (hp : Function.Injective p) {s : Stacks K} {i Z j ℓ : ℕ}
+ (hs : ∀ k, s (p k) = ready i Z j ℓ k) :
+ (addressRoutine.onPorts p).Runs (addressTicks i Z j ℓ) s
+ (Function.update (Function.update s (p .offset) (List.replicate ((i*Z+j)*ℓ) true))
+ (p .cellWidth) (List.replicate ℓ true)) := by
+ apply addressRoutine.runs_onPorts_framed hp (addressRoutine_runs i Z j ℓ) hs
+ · intro k
+ cases k <;> simp (config := { decide := true })
+ [hp.eq_iff, hs, ready, result, encode, registers]
+ · intro k hk
+ simp [Function.update_of_ne (hk .cellWidth).symm, Function.update_of_ne (hk .offset).symm]
+
+private theorem ordinal_succ_le {i t j Z : ℕ} (hi : i < t) (hj : j < Z) :
+ i*Z+j+1 ≤ t*Z := by
+ calc
+ i*Z+j+1 ≤ i*Z+Z := by omega
+ _ = (i+1)*Z := (Nat.succ_mul i Z).symm
+ _ ≤ t*Z := Nat.mul_le_mul_right _ hi
+
+/-- A legal cell occupies an interval contained in the packed table. -/
+theorem cell_fits {i t j Z : ℕ} (hi : i < t) (hj : j < Z) (ℓ : ℕ) :
+ (i*Z+j)*ℓ+ℓ ≤ t*Z*ℓ := by
+ simpa only [Nat.succ_mul] using Nat.mul_le_mul_right ℓ (ordinal_succ_le hi hj)
+
+/-- Every cell address can be prepared in time linear in the size of the
+table and its number of cells. This form also applies to width zero. -/
+theorem addressTicks_le_cells {i t j Z : ℕ} (hi : i < t) (hj : j < Z) (ℓ : ℕ) :
+ addressTicks i Z j ℓ ≤ 19*(t*Z) + 5*(t*Z*ℓ) := by
+ have ho := ordinal_succ_le hi hj
+ have hf := cell_fits hi hj ℓ
+ have hrow : i ≤ i*Z := by simpa using Nat.mul_le_mul_left i (show 1 ≤ Z by omega)
+ rw [addressTicks, show i*(5*Z+6) + 5*j + (i*Z+j)*(5*ℓ+8) + 5*ℓ + 9 =
+ 13*(i*Z+j) + 6*i + 5*((i*Z+j)*ℓ+ℓ) + 9 by ring]
+ omega
+
+/-- At positive digit width the uniform cell-address clock is at most
+twenty-four times the bit length of the table. -/
+theorem addressTicks_le {i t j Z ℓ : ℕ} (hi : i < t) (hj : j < Z) (hℓ : 0 < ℓ) :
+ addressTicks i Z j ℓ ≤ 24*(t*Z*ℓ) := by
+ have h := addressTicks_le_cells hi hj ℓ
+ have hc : t*Z ≤ t*Z*ℓ := by simpa using Nat.mul_le_mul_left (t*Z) hℓ
+ omega
+
+private inductive CopyPort where
+ | src | dst | tmp
+ deriving DecidableEq
+
+private def copyPorts {K : Type} (src dst tmp : K) : CopyPort → K
+ | .src => src
+ | .dst => dst
+ | .tmp => tmp
+
+private def smallCopy : FiniteRoutine CopyPort :=
+ .ofRoutine (Program.copy .src .dst .tmp (by decide) (by decide) (by decide)).code
+
+/-- Initialize a loop counter by adding a preserved unary count. -/
+def copyCount {K : Type} (src dst tmp : K) : FiniteRoutine K :=
+ smallCopy.onPorts (copyPorts src dst tmp)
+
+theorem copyCount_runs {K : Type} [DecidableEq K] (src dst tmp : K)
+ (hsd : src ≠ dst) (hst : src ≠ tmp) (hdt : dst ≠ tmp)
+ (s : Stacks K) (n m : ℕ) (hs : s src = List.replicate n true)
+ (hd : s dst = List.replicate m true) (ht : s tmp = []) :
+ (copyCount src dst tmp).Runs (5*n+2) s
+ (Function.update s dst (List.replicate (m+n) true)) := by
+ let p := copyPorts src dst tmp
+ let v : State CopyPort := fun k => match k with
+ | .src => n | .dst => m | .tmp => 0
+ have hp : Function.Injective p := by
+ intro a b hab
+ cases a <;> cases b <;> simp_all [p, copyPorts]
+ have h := copyAdd_runs CopyPort.src .dst .tmp (by decide) (by decide) (by decide) v rfl
+ apply smallCopy.runs_onPorts_framed hp h
+ · intro k
+ cases k <;> assumption
+ · intro k
+ cases k <;> simp (config := { decide := true })
+ [p, copyPorts, v, encode, hsd, hdt.symm, hs, ht]
+ · intro k hk
+ exact Function.update_of_ne (hk .dst).symm ..
+
+end EvaluatorDigitAddress
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorDigitCallbacks.lean b/lean/OAI/Computability/VPVNP/EvaluatorDigitCallbacks.lean
new file mode 100644
index 0000000000..19de9ee853
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorDigitCallbacks.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.EvaluatorDigitRepeat
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+
+/-!
+# Iterating a branching evaluator callback by a binary digit
+
+Each positive counter value dispatches one copy of the same callback. Its
+different outcomes can take different times and change the evaluator state.
+The counter stays at the decremented value for all of these outcomes. At
+zero the loop clears the counter and invokes the caller once per sequence
+of callback outcomes, with the actual remaining fuel for that sequence.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorDigitCallbacks
+
+open RAMTape TapeWord EvaluatorDigitRepeat
+
+theorem split_positive (bits : List Bool) (h : 0 < value bits) :
+ ∃ l tail, bits = List.replicate l false ++ true :: tail := by
+ induction bits with
+ | nil => exact (Nat.not_lt_zero _ h).elim
+ | cons b bits ih =>
+ cases b
+ · have hp : 0 < value bits := by simp [value] at h; omega
+ obtain ⟨l, tail, rfl⟩ := ih hp
+ exact ⟨l + 1, tail, by rw [List.replicate_succ, List.cons_append]⟩
+ · exact ⟨0, bits, rfl⟩
+
+private theorem sum_traces_succ {I : Type*} [Fintype I] {d : ℕ}
+ (f : (Fin (d + 1) → I) → ℕ) : ∑ z, f z = ∑ i, ∑ tail, f (Fin.cons i tail) := by
+ rw [← (Fin.consEquiv (fun _ : Fin (d + 1) => I)).sum_comp f, Fintype.sum_prod_type]
+ rfl
+
+/-- A per-trace upper bound. It covers the empty-counter pass at the end,
+one scan and restoration per positive counter, and every callback. -/
+def repeatBudget (w B d : ℕ) := (d + 1) * (4 * w + B + 3)
+
+/-- The output on trace `z` is obtained by folding the callback transition
+over exactly `d` outcomes. The single family of actual delays works for
+every continuation, including continuations that inspect the fuel. -/
+theorem repeat_count_of_bound {K Q S I : Type*} [DecidableEq K] [Fintype I]
+ (src tmp : K) (hne : src ≠ tmp) (body : Routine K Q)
+ (bank : S → Stacks K) (next : S → I → S) (w B : ℕ)
+ (callback : ∀ x bits fuel, (bits : List Bool).length = w → B ≤ fuel →
+ ∃ delay : I → ℕ, (∀ i, delay i ≤ B) ∧ ∀ c,
+ body.count c fuel (frame src tmp (bank x) bits []) =
+ ∑ i, c (fuel - delay i) (frame src tmp (bank (next x i)) bits []))
+ (d : ℕ) (bits : List Bool) (hw : bits.length = w) (hd : value bits = d)
+ (x : S) (fuel : ℕ) (hf : repeatBudget w B d ≤ fuel) :
+ ∃ delay : (Fin d → I) → ℕ, (∀ z, delay z ≤ repeatBudget w B d) ∧ ∀ c,
+ (repeatRoutine src tmp body).count c fuel (frame src tmp (bank x) bits []) =
+ ∑ z, c (fuel - delay z) (frame src tmp (bank ((List.ofFn z).foldl next x)) [] []) := by
+ classical
+ induction d generalizing bits x fuel with
+ | zero =>
+ have hz : bits = List.replicate w false := eq_of_length_value (by simpa using hw) (by simpa using hd)
+ subst bits
+ have h₀ : 3 * w + 2 ≤ repeatBudget w B 0 := by simp [repeatBudget]; omega
+ refine ⟨fun _ => 3 * w + 2, fun _ => h₀, fun c => ?_⟩
+ rw [← Nat.sub_add_cancel (h₀.trans hf)]
+ have h := count_zero src tmp hne body c (bank x) w (fuel - (3 * w + 2))
+ simpa only [Nat.sub_add_cancel (h₀.trans hf), List.ofFn_zero, List.foldl_nil, Fintype.sum_unique]
+ using h
+ | succ d ih =>
+ obtain ⟨l, tail, rfl⟩ := split_positive bits (by omega)
+ let smaller := List.replicate l true ++ false :: tail
+ let scan := 4 * l + 3
+ let rest := fuel - scan
+ have hs : smaller.length = w := by simpa [smaller] using hw
+ have hv : value smaller = d := by
+ have := value_decrement l tail
+ dsimp [smaller]; omega
+ have hl : l ≤ w := by simp at hw; omega
+ have hb : repeatBudget w B (d + 1) = repeatBudget w B d + (4 * w + B + 3) :=
+ Nat.succ_mul ..
+ have hsum : repeatBudget w B d + scan + B ≤ fuel := by
+ rw [hb] at hf
+ dsimp [scan]; omega
+ obtain ⟨cost, hcost, hbody⟩ := callback x smaller rest hs (by dsimp [rest]; omega)
+ have follow (i : I) := ih smaller hs hv (next x i) (rest - cost i)
+ (by have := hcost i; dsimp [rest]; omega)
+ choose later hlater hloop using follow
+ let delay (z : Fin (d + 1) → I) := scan + cost (z 0) + later (z 0) (Fin.tail z)
+ refine ⟨delay, fun z => ?_, fun c => ?_⟩
+ · have := hlater (z 0) (Fin.tail z)
+ have := hcost (z 0)
+ dsimp only [delay, scan]; rw [hb]; omega
+ · have hscan := count_positive src tmp hne body c (bank x) l rest tail
+ rw [show rest + (4 * l + 3) = fuel by dsimp [rest, scan]; omega] at hscan
+ rw [hscan, hbody, sum_traces_succ]
+ apply Finset.sum_congr rfl
+ intro i _
+ rw [hloop i c]
+ apply Finset.sum_congr rfl
+ intro z _
+ simp only [delay, Fin.cons_zero, Fin.tail_cons, List.ofFn_succ, Fin.cons_succ,
+ List.foldl_cons, rest, Nat.sub_sub, Nat.add_assoc]
+
+end EvaluatorDigitCallbacks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorDigitFetch.lean b/lean/OAI/Computability/VPVNP/EvaluatorDigitFetch.lean
new file mode 100644
index 0000000000..fc4470c9d0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorDigitFetch.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.EvaluatorDigitAddress
+import OAI.Computability.VPVNP.EvaluatorDigitLookup
+
+/-!
+# Fetching a packed digit during the column and label loops
+
+The scheduler stores both forward indices on tally stacks. Each fetch computes
+the bit address, reads the selected cell, and restores the table. Only the
+digit stack changes across the whole call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorDigitFetch
+
+open RAMTape
+
+/-- The scheduler owns the address counters, packed table, and digit scratch
+stacks. The callback's own registers occupy the `work` ports. -/
+inductive Port (P : Type) where
+ | addr (k : EvaluatorDigitAddress.Port)
+ | table | saved | rev | digit | borrow | labels | labelsLeft | colsLeft | copyTmp
+ | work (p : P)
+ deriving DecidableEq, Fintype
+
+variable {P : Type}
+
+/-- Between matrix queries all lookup and decrement scratch is empty. -/
+def bank (data : List Bool) (t Z ℓ i j labelsLeft colsLeft : ℕ) (payload : Stacks P) :
+ Stacks (Port P)
+ | .addr k => EvaluatorDigitAddress.ready i Z j ℓ k
+ | .table => data
+ | .labels => List.replicate t true
+ | .labelsLeft => List.replicate labelsLeft true
+ | .colsLeft => List.replicate colsLeft true
+ | .work p => payload p
+ | _ => []
+
+private def lookupPort : EvaluatorDigitLookup.Port → Port P
+ | .src => .table
+ | .offset => .addr .offset
+ | .width => .addr .cellWidth
+ | .saved => .saved
+ | .revDigit => .rev
+ | .digit => .digit
+
+private theorem lookupPort_injective : Function.Injective (lookupPort (P := P)) := by
+ intro x y h
+ cases x <;> cases y <;> simp_all [lookupPort]
+
+/-- Compute the row-major bit address and read one digit without consuming
+the packed table or any of the scheduler's loop indices. -/
+def fetch : FiniteRoutine (Port P) :=
+ (EvaluatorDigitAddress.addressRoutine.onPorts .addr).followedBy
+ (EvaluatorDigitLookup.lookupRoutine.onPorts lookupPort)
+
+/-- Instruction count for computing a packed digit's bit address and then reading that cell
+while restoring the table. -/
+def fetchTicks (i Z j ℓ : ℕ) := EvaluatorDigitAddress.addressTicks i Z j ℓ +
+ EvaluatorDigitLookup.lookupTicks ((i*Z+j)*ℓ) ℓ
+
+theorem fetch_runs [DecidableEq P] (data : List Bool) (t Z ℓ i j labelsLeft colsLeft : ℕ)
+ (payload : Stacks P) (fits : (i*Z+j)*ℓ+ℓ ≤ data.length) :
+ fetch.Runs (fetchTicks i Z j ℓ) (bank data t Z ℓ i j labelsLeft colsLeft payload)
+ (Function.update (bank data t Z ℓ i j labelsLeft colsLeft payload) .digit
+ ((data.drop ((i*Z+j)*ℓ)).take ℓ)) := by
+ let s := bank data t Z ℓ i j labelsLeft colsLeft payload
+ let offset := (i*Z+j)*ℓ
+ let mid := Function.update (Function.update s (.addr .offset) (List.replicate offset true))
+ (.addr .cellWidth) (List.replicate ℓ true)
+ let out := Function.update s Port.digit ((data.drop offset).take ℓ)
+ have h₁ : (EvaluatorDigitAddress.addressRoutine.onPorts Port.addr).Runs
+ (EvaluatorDigitAddress.addressTicks i Z j ℓ) s mid :=
+ EvaluatorDigitAddress.addressRoutine_runs_framed (p := Port.addr) (fun _ _ h => Port.addr.inj h) (fun _ => rfl)
+ have h₂ : (EvaluatorDigitLookup.lookupRoutine.onPorts lookupPort).Runs
+ (EvaluatorDigitLookup.lookupTicks offset ℓ) mid out := by
+ apply EvaluatorDigitLookup.lookupRoutine.runs_onPorts_framed lookupPort_injective
+ (EvaluatorDigitLookup.lookupRoutine_runs_at data [] offset ℓ fits)
+ · intro k
+ cases k <;> rfl
+ · intro k
+ cases k with
+ | digit => simp only [out, lookupPort, Function.update_self, List.append_nil]; rfl
+ | src | offset | width | saved | revDigit => rfl
+ · intro k hk
+ change Function.update s Port.digit _ k = Function.update (Function.update s (.addr .offset) _)
+ (.addr .cellWidth) _ k
+ have hd : k ≠ .digit := (hk .digit).symm
+ have hw : k ≠ .addr .cellWidth := (hk .width).symm
+ have ho : k ≠ .addr .offset := (hk .offset).symm
+ rw [Function.update_of_ne hd, Function.update_of_ne hw, Function.update_of_ne ho]
+ exact h₁.followedBy h₂
+
+/-- A uniform fetch bound works across the full pair of loops. -/
+theorem fetchTicks_le_cells {i t j Z : ℕ} (hi : i < t) (hj : j < Z) (ℓ : ℕ) :
+ fetchTicks i Z j ℓ ≤ 19*(t*Z) + 13*(t*Z*ℓ) + 4 := by
+ have h := EvaluatorDigitAddress.addressTicks_le_cells hi hj ℓ
+ have h' := EvaluatorDigitAddress.cell_fits hi hj ℓ
+ unfold fetchTicks EvaluatorDigitLookup.lookupTicks
+ omega
+
+theorem fetchTicks_le {i t j Z ℓ : ℕ} (hi : i < t) (hj : j < Z) (hℓ : 0 < ℓ) :
+ fetchTicks i Z j ℓ ≤ 32*(t*Z*ℓ) + 4 := by
+ have h := fetchTicks_le_cells hi hj ℓ
+ have hc : t*Z ≤ t*Z*ℓ := by simpa using Nat.mul_le_mul_left (t*Z) hℓ
+ omega
+
+/-- Every intermediate stack of a fetch grows by at most a linear function
+of the table dimensions, even with arbitrary callback registers in the bank. -/
+theorem fetch_space [DecidableEq P] (data : List Bool) (t Z ℓ i j labelsLeft colsLeft : ℕ)
+ (payload : Stacks P) (hi : i < t) (hj : j < Z) (fits : (i*Z+j)*ℓ+ℓ ≤ data.length)
+ {n : ℕ} {q : Option (fetch (P := P)).State} {u : Stacks (Port P)}
+ (run : StackRuns fetch.body.standalone n (some fetch.body.entry)
+ (bank data t Z ℓ i j labelsLeft colsLeft payload) q u) (k : Port P) :
+ (u k).length ≤ (bank data t Z ℓ i j labelsLeft colsLeft payload k).length +
+ (19*(t*Z) + 13*(t*Z*ℓ) + 4) := by
+ have hdone := fetch_runs data t Z ℓ i j labelsLeft colsLeft payload fits
+ have hn := EvaluatorRadixDivision.ticks_le_at_return hdone (by rfl) run
+ exact (EvaluatorRadixDivision.run_length run k).trans
+ (Nat.add_le_add_left (hn.trans (fetchTicks_le_cells hi hj ℓ)) _)
+
+end EvaluatorDigitFetch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorDigitLookup.lean b/lean/OAI/Computability/VPVNP/EvaluatorDigitLookup.lean
new file mode 100644
index 0000000000..9e00cca9e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorDigitLookup.lean
@@ -0,0 +1,202 @@
+import OAI.Computability.VPVNP.EvaluatorRadixSpace
+import Mathlib.Data.List.TakeDrop
+
+/-!
+# Selecting a digit from a packed bit stack
+
+The offset and width are unary. Two loops move the skipped and selected bits
+onto a saved stack. The second loop also copies the selected bits. Reversing
+the two temporary stacks restores the input and emits the digit in its
+original bit order. The same finite control works for every table size.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorDigitLookup
+
+open RAMTape EvaluatorRadixDivision
+
+/-- The source table, skip and width counters, and temporary and output stacks for extracting
+one digit. -/
+inductive Port where
+ | src | offset | width | saved | revDigit | digit
+ deriving DecidableEq
+
+instance : Fintype Port :=
+ ⟨{.src, .offset, .width, .saved, .revDigit, .digit}, by intro k; cases k <;> decide⟩
+
+private def bank (data : List Bool) (offset width : ℕ) (saved revDigit out : List Bool) :
+ Stacks Port
+ | .src => data
+ | .offset => List.replicate offset true
+ | .width => List.replicate width true
+ | .saved => saved
+ | .revDigit => revDigit
+ | .digit => out
+
+/-- Initial lookup bank holding the table, unary offset and width, and incoming output stack,
+with both reversal stacks empty. -/
+def ready (data : List Bool) (offset width : ℕ) (out : List Bool) : Stacks Port :=
+ bank data offset width [] [] out
+
+private def skipBit : FiniteRoutine Port :=
+ .ofRoutine (Routine.popCase .src (Routine.halt false) (Routine.push .saved false)
+ (Routine.push .saved true))
+
+private def copyBit : FiniteRoutine Port :=
+ let pushBoth (b : Bool) := (Routine.push Port.saved b).followedBy (Routine.push .revDigit b)
+ .ofRoutine (Routine.popCase .src (Routine.halt false) (pushBoth false) (pushBoth true))
+
+private def consumeMarks (counter : Port) (body : FiniteRoutine Port) : FiniteRoutine Port :=
+ .ofRoutine (Routine.popLoop counter (fun _ => true) (Routine.halt false) body.body)
+
+/-- Select a bit interval, restore the table, and prepend the selected interval
+to the digit stack. Malformed inputs that exhaust the source are rejected. -/
+def lookupRoutine : FiniteRoutine Port :=
+ (((consumeMarks .offset skipBit).followedBy (consumeMarks .width copyBit)).followedBy
+ (reverseOnto .saved .src)).followedBy (reverseOnto .revDigit .digit)
+
+/-- Instruction count for skipping the offset, extracting width bits, restoring the table and
+prepending the digit to the output stack. -/
+def lookupTicks (offset width : ℕ) := 5 * offset + 8 * width + 4
+
+private theorem skipBit_runs (b : Bool) (xs : List Bool) (i w : ℕ) (s r out : List Bool) :
+ skipBit.Runs 2 (bank (b :: xs) i w s r out) (bank xs i w (b :: s) r out) := by
+ let a := bank xs i w s r out
+ have ha : Function.update (bank (b :: xs) i w s r out) .src xs = a := by
+ funext k; cases k <;> rfl
+ have hb : Function.update a .saved (b :: a .saved) = bank xs i w (b :: s) r out := by
+ funext k; cases k <;> rfl
+ have push := Routine.runs_push .saved b a
+ rw [hb] at push
+ cases b
+ · apply Routine.runs_popCase_false Port.src _ _ _ (s := bank (false :: xs) i w s r out) rfl
+ rwa [ha]
+ · apply Routine.runs_popCase_true Port.src _ _ _ (s := bank (true :: xs) i w s r out) rfl
+ rwa [ha]
+
+private theorem copyBit_runs (b : Bool) (xs : List Bool) (i w : ℕ) (s r out : List Bool) :
+ copyBit.Runs 3 (bank (b :: xs) i w s r out) (bank xs i w (b :: s) (b :: r) out) := by
+ let a := bank xs i w s r out
+ let v := bank xs i w (b :: s) r out
+ have ha : Function.update (bank (b :: xs) i w s r out) .src xs = a := by
+ funext k; cases k <;> rfl
+ have hv : Function.update a .saved (b :: a .saved) = v := by
+ funext k; cases k <;> rfl
+ have ho : Function.update v .revDigit (b :: v .revDigit) = bank xs i w (b :: s) (b :: r) out := by
+ funext k; cases k <;> rfl
+ have h₁ := Routine.runs_push .saved b a
+ have h₂ := Routine.runs_push .revDigit b v
+ rw [hv] at h₁
+ rw [ho] at h₂
+ have push := h₁.followedBy h₂
+ cases b
+ · apply Routine.runs_popCase_false Port.src _ _ _ (s := bank (false :: xs) i w s r out) rfl
+ rwa [ha]
+ · apply Routine.runs_popCase_true Port.src _ _ _ (s := bank (true :: xs) i w s r out) rfl
+ rwa [ha]
+
+private theorem skip_runs (pre tail : List Bool) (w : ℕ) (s r out : List Bool) :
+ (consumeMarks .offset skipBit).Runs (3 * pre.length + 1)
+ (bank (pre ++ tail) pre.length w s r out)
+ (bank tail 0 w (pre.reverse ++ s) r out) := by
+ induction pre generalizing s with
+ | nil =>
+ exact Routine.Runs.popLoop_empty Port.offset (fun _ => true) (Routine.halt false)
+ skipBit.body (s := bank tail 0 w s r out) rfl
+ | cons b pre ih =>
+ let a := bank (b :: pre ++ tail) pre.length w s r out
+ have ha : Function.update (bank ((b :: pre) ++ tail) (b :: pre).length w s r out)
+ Port.offset (List.replicate pre.length true) = a := by
+ funext k; cases k <;> rfl
+ have h := Routine.Runs.popLoop_true_continue Port.offset (fun _ => true) (Routine.halt false)
+ skipBit.body (s := bank ((b :: pre) ++ tail) (b :: pre).length w s r out)
+ (List.replicate_succ ..) rfl (by rw [ha]; exact skipBit_runs ..) (ih (b :: s))
+ simpa only [consumeMarks, FiniteRoutine.Runs, FiniteRoutine.ofRoutine, List.length_cons,
+ Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append, show ∀ n : ℕ, n + 3 + 1 = 1 + 2 + (n + 1) by omega] using h
+
+private theorem copy_runs (cell tail : List Bool) (s r out : List Bool) :
+ (consumeMarks .width copyBit).Runs (4 * cell.length + 1)
+ (bank (cell ++ tail) 0 cell.length s r out)
+ (bank tail 0 0 (cell.reverse ++ s) (cell.reverse ++ r) out) := by
+ induction cell generalizing s r with
+ | nil =>
+ exact Routine.Runs.popLoop_empty Port.width (fun _ => true) (Routine.halt false)
+ copyBit.body (s := bank tail 0 0 s r out) rfl
+ | cons b cell ih =>
+ let a := bank (b :: cell ++ tail) 0 cell.length s r out
+ have ha : Function.update (bank ((b :: cell) ++ tail) 0 (b :: cell).length s r out)
+ Port.width (List.replicate cell.length true) = a := by
+ funext k; cases k <;> rfl
+ have h := Routine.Runs.popLoop_true_continue Port.width (fun _ => true) (Routine.halt false)
+ copyBit.body (s := bank ((b :: cell) ++ tail) 0 (b :: cell).length s r out)
+ (List.replicate_succ ..) rfl (by rw [ha]; exact copyBit_runs ..) (ih (b :: s) (b :: r))
+ simpa only [consumeMarks, FiniteRoutine.Runs, FiniteRoutine.ofRoutine, List.length_cons,
+ Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append, show ∀ n : ℕ, n + 4 + 1 = 1 + 3 + (n + 1) by omega] using h
+
+/-- The returned table agrees bit-for-bit with the input. The two counters
+and the two temporary stacks are empty after every successful lookup. -/
+theorem lookupRoutine_runs (pre cell post out : List Bool) :
+ lookupRoutine.Runs (lookupTicks pre.length cell.length)
+ (ready (pre ++ cell ++ post) pre.length cell.length out)
+ (ready (pre ++ cell ++ post) 0 0 (cell ++ out)) := by
+ let a := bank (cell ++ post) 0 cell.length pre.reverse [] out
+ let b := bank post 0 0 (cell.reverse ++ pre.reverse) cell.reverse out
+ let c := bank (pre ++ cell ++ post) 0 0 [] cell.reverse out
+ have h₁ : (consumeMarks .offset skipBit).Runs (3 * pre.length + 1)
+ (ready (pre ++ cell ++ post) pre.length cell.length out) a := by
+ simpa only [ready, List.append_assoc, List.append_nil, a] using
+ skip_runs pre (cell ++ post) cell.length [] [] out
+ have h₂ : (consumeMarks .width copyBit).Runs (4 * cell.length + 1) a b := by
+ simpa only [a, b, List.append_nil] using copy_runs cell post pre.reverse [] out
+ have h₃ := reverseOnto_runs (src := Port.saved) (dst := .src) (by decide) b c rfl
+ (show pre ++ cell ++ post = (cell.reverse ++ pre.reverse).reverse ++ post by simp)
+ (by intro k hk hk'; cases k <;> first | rfl | exact (hk rfl).elim | exact (hk' rfl).elim)
+ have h₄ := reverseOnto_runs (src := Port.revDigit) (dst := .digit) (by decide) c
+ (ready (pre ++ cell ++ post) 0 0 (cell ++ out)) rfl
+ (show cell ++ out = cell.reverse.reverse ++ out by simp)
+ (by intro k hk hk'; cases k <;> first | rfl | exact (hk rfl).elim | exact (hk' rfl).elim)
+ have h := ((h₁.followedBy h₂).followedBy h₃).followedBy h₄
+ have ht : lookupTicks pre.length cell.length = 3 * pre.length + 1 + (4 * cell.length + 1) +
+ (2 * (b .saved).length + 1) + (2 * (c .revDigit).length + 1) := by
+ simp only [lookupTicks, b, c, bank, List.length_append, List.length_reverse]; omega
+ rw [ht]
+ exact h
+
+theorem lookupRoutine_runs_at (data out : List Bool) (offset width : ℕ)
+ (fits : offset + width ≤ data.length) :
+ lookupRoutine.Runs (lookupTicks offset width) (ready data offset width out)
+ (ready data 0 0 ((data.drop offset).take width ++ out)) := by
+ have ho : offset ≤ data.length := by omega
+ simpa only [List.length_take, min_eq_left ho, List.length_drop,
+ min_eq_left (show width ≤ data.length - offset by omega), List.append_assoc,
+ List.take_append_drop] using
+ lookupRoutine_runs (data.take offset) ((data.drop offset).take width)
+ ((data.drop offset).drop width) out
+
+/-- A linear peak storage bound for all six stacks at every intermediate point. -/
+theorem lookupRoutine_space (data out : List Bool) (offset width : ℕ) (fits : offset + width ≤ data.length)
+ {n : ℕ} {q : Option lookupRoutine.State} {u : Stacks Port}
+ (run : StackRuns lookupRoutine.body.standalone n (some lookupRoutine.body.entry)
+ (ready data offset width out) q u) :
+ ∑ k, (u k).length ≤ 6 * (data.length + out.length + lookupTicks offset width) := by
+ have hn := ticks_le_at_return (lookupRoutine_runs_at data out offset width fits) (by rfl) run
+ have h (k : Port) : (u k).length ≤ data.length + out.length + lookupTicks offset width := by
+ have h₁ := run_length run k
+ have h₂ : (ready data offset width out k).length ≤ data.length + out.length := by
+ cases k <;> simp [ready, bank] <;> omega
+ omega
+ calc
+ ∑ k, (u k).length ≤ ∑ _ : Port, (data.length + out.length + lookupTicks offset width) :=
+ Finset.sum_le_sum (fun k _ => h k)
+ _ = _ := by simp [show Fintype.card Port = 6 by decide]
+
+end EvaluatorDigitLookup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorDigitRepeat.lean b/lean/OAI/Computability/VPVNP/EvaluatorDigitRepeat.lean
new file mode 100644
index 0000000000..f5558e56a6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorDigitRepeat.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.RAMTapeWord
+import OAI.Computability.VPVNP.StructuredStacks
+import Mathlib.Tactic.DeriveFintype
+
+/-! # Repetition by a binary field digit
+
+The evaluator multiplies by one label as many times as specified by its
+current base-`Q` digit. Its finite control decrements a little-endian bit
+stack, using a second stack to save the trailing zeros. A positive digit
+decreases by one before calling the matrix-step routine. The two digit
+stacks together occupy at most the width of the digit throughout the scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorDigitRepeat
+
+open RAMTape
+
+/-- Finite control for decrementing a binary digit, restoring the digit stack and invoking the
+scheduled callback once per decrement. -/
+inductive State (Q : Type*) where
+ | scan | mark | clearHigh | restore | restoreBit | discard | call (q : Q)
+ deriving DecidableEq, Fintype
+
+variable {K Q : Type*} [DecidableEq K]
+
+/-- The callback returns to the scan for the next unit of the digit. -/
+def repeatRoutine (src tmp : K) (body : Routine K Q) : Routine K (State Q) where
+ entry := .scan
+ code
+ | .scan => .pop src (fun b => match b with
+ | none => some .discard | some false => some .mark | some true => some .clearHigh)
+ | .mark => .push tmp true (some .scan)
+ | .clearHigh => .push src false (some .restore)
+ | .restore => .pop tmp (fun b => if b.isSome then some .restoreBit else some (.call body.entry))
+ | .restoreBit => .push src true (some .restore)
+ | .discard => .pop tmp (fun b => if b.isSome then some .discard else none)
+ | .call q => body.install State.call (some .scan) q
+
+/-- Assign both digit stacks while carrying all other registers through. -/
+def frame (src tmp : K) (base : Stacks K) (xs ys : List Bool) : Stacks K :=
+ Function.update (Function.update base src xs) tmp ys
+
+variable (src tmp : K) (hne : src ≠ tmp) (body : Routine K Q)
+variable (c : ℕ → Stacks K → ℕ) (base : Stacks K)
+
+include hne in
+private theorem source_frame (xs ys : List Bool) : frame src tmp base xs ys src = xs := by
+ simp [frame, hne]
+
+include hne in
+private theorem update_source (xs ys zs : List Bool) :
+ Function.update (frame src tmp base xs ys) src zs = frame src tmp base zs ys := by
+ funext k
+ by_cases hk : k = src <;> by_cases hj : k = tmp <;> simp_all [frame]
+
+private theorem update_tmp (xs ys zs : List Bool) :
+ Function.update (frame src tmp base xs ys) tmp zs = frame src tmp base xs zs := by
+ simp [frame]
+
+private theorem scratch_frame (xs ys : List Bool) : frame src tmp base xs ys tmp = ys := by
+ simp [frame]
+
+include hne in
+private theorem scan_false (n : ℕ) (xs ys : List Bool) :
+ (repeatRoutine src tmp body).countFrom c (n+2) (some .scan) (frame src tmp base (false::xs) ys) =
+ (repeatRoutine src tmp body).countFrom c n (some .scan) (frame src tmp base xs (true::ys)) := by
+ simp [Routine.countFrom, repeatRoutine, source_frame src tmp hne, scratch_frame,
+ update_source src tmp hne, update_tmp]
+
+include hne in
+private theorem scan_true (n : ℕ) (xs ys : List Bool) :
+ (repeatRoutine src tmp body).countFrom c (n+2) (some .scan) (frame src tmp base (true::xs) ys) =
+ (repeatRoutine src tmp body).countFrom c n (some .restore) (frame src tmp base (false::xs) ys) := by
+ simp [Routine.countFrom, repeatRoutine, source_frame src tmp hne, update_source src tmp hne]
+
+include hne in
+private theorem scan_nil (n : ℕ) (ys : List Bool) :
+ (repeatRoutine src tmp body).countFrom c (n+1) (some .scan) (frame src tmp base [] ys) =
+ (repeatRoutine src tmp body).countFrom c n (some .discard) (frame src tmp base [] ys) := by
+ simp [Routine.countFrom, repeatRoutine, source_frame src tmp hne, update_source src tmp hne]
+
+include hne in
+private theorem restore_bit (n : ℕ) (xs ys : List Bool) :
+ (repeatRoutine src tmp body).countFrom c (n+2) (some .restore) (frame src tmp base xs (true::ys)) =
+ (repeatRoutine src tmp body).countFrom c n (some .restore) (frame src tmp base (true::xs) ys) := by
+ simp [Routine.countFrom, repeatRoutine, scratch_frame, update_tmp, source_frame src tmp hne,
+ update_source src tmp hne]
+
+include hne in
+private theorem scan_zeros (l n : ℕ) (xs ys : List Bool) :
+ (repeatRoutine src tmp body).countFrom c (n + 2*l) (some .scan)
+ (frame src tmp base (List.replicate l false ++ xs) ys) =
+ (repeatRoutine src tmp body).countFrom c n (some .scan)
+ (frame src tmp base xs (List.replicate l true ++ ys)) := by
+ induction l generalizing ys with
+ | zero => simp
+ | succ l ih =>
+ rw [show n + 2*(l+1) = n+2*l+2 by omega, List.replicate_succ, List.cons_append,
+ scan_false src tmp hne body c, ih, List.replicate_succ', List.append_assoc]
+ rfl
+
+include hne in
+private theorem restore_ones (l n : ℕ) (xs : List Bool) :
+ (repeatRoutine src tmp body).countFrom c (n + 2*l + 1) (some .restore)
+ (frame src tmp base xs (List.replicate l true)) =
+ (repeatRoutine src tmp body).countFrom c n (some (.call body.entry))
+ (frame src tmp base (List.replicate l true ++ xs) []) := by
+ induction l generalizing xs with
+ | zero => simp [Routine.countFrom, repeatRoutine, scratch_frame, update_tmp]
+ | succ l ih =>
+ rw [show n+2*(l+1)+1 = n+2*l+1+2 by omega]
+ nth_rw 1 [List.replicate_succ]
+ rw [restore_bit src tmp hne body c, ih, List.replicate_succ', List.append_assoc]
+ rfl
+
+private theorem discard_one (n : ℕ) (ys : List Bool) :
+ (repeatRoutine src tmp body).countFrom c (n+1) (some .discard)
+ (frame src tmp base [] (true::ys)) =
+ (repeatRoutine src tmp body).countFrom c n (some .discard) (frame src tmp base [] ys) := by
+ simp [Routine.countFrom, repeatRoutine, scratch_frame, update_tmp]
+
+private theorem discard_ones (l n : ℕ) :
+ (repeatRoutine src tmp body).countFrom c (n+l+1) (some .discard)
+ (frame src tmp base [] (List.replicate l true)) = c n (frame src tmp base [] []) := by
+ induction l with
+ | zero => simp [Routine.countFrom, repeatRoutine, scratch_frame, update_tmp]
+ | succ l ih => rw [show n+(l+1)+1 = n+l+1+1 by omega, List.replicate_succ, discard_one, ih]
+
+include hne in
+/-- On a zero digit the control returns directly to the continuation. -/
+theorem count_zero (w fuel : ℕ) :
+ (repeatRoutine src tmp body).count c (fuel + (3*w+2))
+ (frame src tmp base (List.replicate w false) []) = c fuel (frame src tmp base [] []) := by
+ change (repeatRoutine src tmp body).countFrom c _ (some .scan) _ = _
+ rw [show fuel+(3*w+2) = (fuel+w+1+1)+2*w by omega]
+ have h := scan_zeros src tmp hne body c base w (fuel+w+1+1) [] []
+ simp only [List.append_nil] at h
+ rw [h]
+ rw [scan_nil src tmp hne body c]
+ exact discard_ones src tmp body c base w fuel
+
+include hne in
+/-- A positive digit with `l` trailing zeros costs `4*l+3` control instructions
+before entering the callback on the decremented digit. This equality retains
+every nondeterministic branch of the callback. -/
+theorem count_positive (l fuel : ℕ) (xs : List Bool) :
+ (repeatRoutine src tmp body).count c (fuel + (4*l+3))
+ (frame src tmp base (List.replicate l false ++ true :: xs) []) =
+ body.count ((repeatRoutine src tmp body).count c) fuel
+ (frame src tmp base (List.replicate l true ++ false :: xs) []) := by
+ change (repeatRoutine src tmp body).countFrom c _ (some .scan) _ = _
+ rw [show fuel+(4*l+3) = (fuel+2*l+1+1+1)+2*l by omega,
+ scan_zeros src tmp hne body c base l (fuel+2*l+1+1+1), List.append_nil]
+ rw [scan_true src tmp hne body c, restore_ones src tmp hne body c base l fuel]
+ exact Routine.countFrom_install (repeatRoutine src tmp body) body State.call (some .scan)
+ (fun _ => rfl) c fuel (some body.entry) _
+
+/-- The positive branch implements subtraction of one, at the same bit width. -/
+theorem value_decrement (l : ℕ) (xs : List Bool) :
+ TapeWord.value (List.replicate l true ++ false :: xs) + 1 =
+ TapeWord.value (List.replicate l false ++ true :: xs) := by
+ induction l with
+ | zero => simp [TapeWord.value, Nat.add_comm]
+ | succ l ih =>
+ simp only [List.replicate_succ, List.cons_append, TapeWord.value, Bool.toNat_true, Bool.toNat_false]
+ omega
+
+end EvaluatorDigitRepeat
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorDigitSafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorDigitSafety.lean
new file mode 100644
index 0000000000..f2d6ec854b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorDigitSafety.lean
@@ -0,0 +1,230 @@
+import OAI.Computability.VPVNP.StructuredStackSafe
+import OAI.Computability.VPVNP.EvaluatorDigitCallbacks
+import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+
+/-!
+# Clock and storage along every branch of a digit countdown
+
+A decremented digit can cause many nondeterministic matrix queries. Across
+these queries the two counter stacks hold at most the original width, even
+on a path that eventually rejects. The callback must itself supply a clock
+and storage guarantee for every branch, and preserve the counters whenever
+it returns normally.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorDigitSafety
+
+open RAMTape TapeWord EvaluatorDigitRepeat EvaluatorDigitCallbacks
+
+variable {K Q S : Type*} [DecidableEq K]
+variable (src tmp : K) (hne : src ≠ tmp) (body : Routine K Q)
+variable (safe : Stacks K → Prop) (cont : ℕ → Stacks K → Prop)
+variable (base : Stacks K) (w : ℕ)
+
+include hne in
+private theorem read_src (xs ys : List Bool) : frame src tmp base xs ys src = xs := by
+ simp [frame, hne]
+
+include hne in
+private theorem set_src (xs ys zs : List Bool) :
+ Function.update (frame src tmp base xs ys) src zs = frame src tmp base zs ys := by
+ simp [frame, Function.update_comm hne.symm]
+
+private theorem set_tmp (xs ys zs : List Bool) :
+ Function.update (frame src tmp base xs ys) tmp zs = frame src tmp base xs zs := by simp [frame]
+
+private theorem read_tmp (xs ys : List Bool) : frame src tmp base xs ys tmp = ys := by simp [frame]
+
+variable (hold : ∀ xs ys : List Bool, xs.length + ys.length ≤ w → safe (frame src tmp base xs ys))
+
+local notation "ok" => Routine.SafeFrom (repeatRoutine src tmp body) safe cont
+local notation "st" => frame src tmp base
+
+include hne hold in
+private theorem scanFalse (n : ℕ) (xs ys : List Bool) (h : xs.length+ys.length+1 ≤ w) :
+ ok (n+2) (some .scan) (st (false :: xs) ys) ↔ ok n (some .scan) (st xs (true :: ys)) := by
+ have ha := hold (false :: xs) ys (by simp; omega)
+ have hb := hold xs ys (by omega)
+ simp [Routine.SafeFrom, repeatRoutine, read_src src tmp hne, read_tmp, set_src src tmp hne, set_tmp, ha, hb]
+
+include hne hold in
+private theorem scanTrue (n : ℕ) (xs ys : List Bool) (h : xs.length+ys.length+1 ≤ w) :
+ ok (n+2) (some .scan) (st (true :: xs) ys) ↔ ok n (some .restore) (st (false :: xs) ys) := by
+ have ha := hold (true :: xs) ys (by simp; omega)
+ have hb := hold xs ys (by omega)
+ simp [Routine.SafeFrom, repeatRoutine, read_src src tmp hne, set_src src tmp hne, ha, hb]
+
+include hne hold in
+private theorem scanNil (n : ℕ) (ys : List Bool) (h : ys.length ≤ w) :
+ ok (n+1) (some .scan) (st [] ys) ↔ ok n (some .discard) (st [] ys) := by
+ have ha := hold [] ys (by simpa using h)
+ simp [Routine.SafeFrom, repeatRoutine, read_src src tmp hne, set_src src tmp hne, ha]
+
+include hne hold in
+private theorem restoreBit (n : ℕ) (xs ys : List Bool) (h : xs.length+ys.length+1 ≤ w) :
+ ok (n+2) (some .restore) (st xs (true :: ys)) ↔ ok n (some .restore) (st (true :: xs) ys) := by
+ have ha := hold xs (true :: ys) (by simp; omega)
+ have hb := hold xs ys (by omega)
+ simp [Routine.SafeFrom, repeatRoutine, read_tmp, set_tmp, read_src src tmp hne, set_src src tmp hne, ha, hb]
+
+include hne hold in
+private theorem scanZeros (l n : ℕ) (xs ys : List Bool) (h : l+xs.length+ys.length ≤ w) :
+ ok (n+2*l) (some .scan) (st (List.replicate l false ++ xs) ys) ↔
+ ok n (some .scan) (st xs (List.replicate l true ++ ys)) := by
+ induction l generalizing ys with
+ | zero => simp
+ | succ l ih =>
+ rw [show n+2*(l+1) = n+2*l+2 by omega, List.replicate_succ, List.cons_append,
+ scanFalse src tmp hne body safe cont base w hold _ _ _ (by simp; omega),
+ ih (true::ys) (by simp; omega), List.replicate_succ', List.append_assoc]
+ rfl
+
+include hne hold in
+private theorem restoreOnes (l n : ℕ) (xs : List Bool) (h : xs.length+l ≤ w) :
+ ok (n+2*l+1) (some .restore) (st xs (List.replicate l true)) ↔
+ ok n (some (.call body.entry)) (st (List.replicate l true ++ xs) []) := by
+ induction l generalizing xs with
+ | zero =>
+ have ha := hold xs [] (by simpa using h)
+ simp [Routine.SafeFrom, repeatRoutine, read_tmp, set_tmp, ha]
+ | succ l ih =>
+ rw [show n+2*(l+1)+1 = n+2*l+1+2 by omega]
+ nth_rw 1 [List.replicate_succ]
+ rw [restoreBit src tmp hne body safe cont base w hold _ _ _ (by simp; omega),
+ ih (true::xs) (by simp; omega), List.replicate_succ', List.append_assoc]
+ rfl
+
+include hold in
+private theorem discardOnes (l n : ℕ) (h : l ≤ w) :
+ ok (n+l+1) (some .discard) (st [] (List.replicate l true)) ↔ cont n (st [] []) := by
+ induction l with
+ | zero =>
+ have ha := hold [] [] (by simp)
+ simp [Routine.SafeFrom, repeatRoutine, read_tmp, set_tmp, ha]
+ | succ l ih =>
+ have ha := hold [] (true::List.replicate l true) (by simpa using h)
+ rw [show n+(l+1)+1 = n+l+1+1 by omega, List.replicate_succ]
+ simpa only [Routine.SafeFrom, repeatRoutine, read_tmp, List.head?_cons, List.tail_cons, Option.isSome_some,
+ ↓reduceIte, set_tmp, ha, true_and] using ih (by omega)
+
+include hne hold in
+private theorem safeZero (fuel : ℕ) :
+ (repeatRoutine src tmp body).Safe safe cont (fuel+(3*w+2)) (st (List.replicate w false) []) ↔
+ cont fuel (st [] []) := by
+ change ok _ (some .scan) _ ↔ _
+ rw [show fuel+(3*w+2) = (fuel+w+1+1)+2*w by omega]
+ have h := scanZeros src tmp hne body safe cont base w hold w (fuel+w+1+1) [] [] (by simp)
+ simp only [List.append_nil] at h
+ rw [h, scanNil src tmp hne body safe cont base w hold _ _ (by simp)]
+ exact discardOnes src tmp body safe cont base w hold w fuel le_rfl
+
+include hne hold in
+private theorem safePositive (l fuel : ℕ) (xs : List Bool) (hw : l+1+xs.length ≤ w) :
+ (repeatRoutine src tmp body).Safe safe cont (fuel+(4*l+3)) (st (List.replicate l false ++ true::xs) []) ↔
+ body.Safe safe ((repeatRoutine src tmp body).Safe safe cont) fuel
+ (st (List.replicate l true ++ false::xs) []) := by
+ change ok _ (some .scan) _ ↔ _
+ rw [show fuel+(4*l+3) = (fuel+2*l+1+1+1)+2*l by omega,
+ scanZeros src tmp hne body safe cont base w hold _ _ _ _ (by simp; omega), List.append_nil,
+ scanTrue src tmp hne body safe cont base w hold _ _ _ (by simp; omega),
+ restoreOnes src tmp hne body safe cont base w hold _ _ _ (by simp; omega)]
+ exact Routine.safeFrom_install (repeatRoutine src tmp body) body State.call (some .scan)
+ (fun _ => rfl) safe cont fuel (some body.entry) _
+
+include hne in
+/-- A safety condition checked at every callback instruction and at every
+countdown instruction holds throughout the full repetition. All normal
+returns present empty counter stacks and reserve at least `extra` more
+instructions. Abnormally terminating branches satisfy the same time and
+storage checks up to their halt. -/
+theorem repeat_safe (bank : S → Stacks K) (w B : ℕ)
+ (frames : ∀ x (xs ys : List Bool), xs.length+ys.length ≤ w → safe (frame src tmp (bank x) xs ys))
+ (callback : ∀ (x : S) (bits : List Bool), bits.length = w →
+ ∀ (extra fuel : ℕ), extra+B ≤ fuel → ∀ c,
+ (∀ y n, extra ≤ n → c n (frame src tmp (bank y) bits [])) →
+ body.Safe safe c fuel (frame src tmp (bank x) bits []))
+ (d : ℕ) (bits : List Bool) (hw : bits.length = w) (hd : value bits = d)
+ (x : S) (extra fuel : ℕ) (hf : extra+repeatBudget w B d ≤ fuel)
+ (finish : ∀ y n, extra ≤ n → cont n (frame src tmp (bank y) [] [])) :
+ (repeatRoutine src tmp body).Safe safe cont fuel (frame src tmp (bank x) bits []) := by
+ induction d generalizing bits x fuel with
+ | zero =>
+ have hz : bits = List.replicate w false := eq_of_length_value (by simpa using hw) (by simpa using hd)
+ subst bits
+ have h₀ : 3*w+2 ≤ repeatBudget w B 0 := by simp [repeatBudget]; omega
+ rw [← Nat.sub_add_cancel (show 3*w+2 ≤ fuel by omega),
+ safeZero src tmp hne body safe cont (bank x) w (frames x)]
+ exact finish _ _ (by omega)
+ | succ d ih =>
+ obtain ⟨l, tail, rfl⟩ := EvaluatorDigitCallbacks.split_positive bits (by omega)
+ let smaller := List.replicate l true ++ false :: tail
+ have hs : smaller.length = w := by simpa [smaller] using hw
+ have hv : value smaller = d := by have := value_decrement l tail; dsimp [smaller]; omega
+ have hw' : l+1+tail.length ≤ w := by simp at hw; omega
+ have hb : repeatBudget w B (d+1) = repeatBudget w B d + (4*w+B+3) := Nat.succ_mul ..
+ rw [hb] at hf
+ have enough : extra+repeatBudget w B d+B ≤ fuel-(4*l+3) := by omega
+ rw [← Nat.sub_add_cancel (show 4*l+3 ≤ fuel by omega), safePositive src tmp hne body safe cont (bank x)
+ w (frames x) _ _ _ hw']
+ apply callback x smaller hs (extra+repeatBudget w B d) _ enough
+ intro y n hn
+ exact ih smaller hs hv y n hn
+
+section Storage
+
+variable [Fintype K]
+
+private theorem update_length (s : Stacks K) (p : K) (bs : List Bool) :
+ ∑ k, (Function.update s p bs k).length ≤ (∑ k, (s k).length) + bs.length := by
+ calc
+ _ ≤ ∑ k, ((s k).length + if k = p then bs.length else 0) := Finset.sum_le_sum (fun k _ => by
+ by_cases hp : k = p <;> simp [hp])
+ _ = _ := by simp [Finset.sum_add_distrib]
+
+/-- The countdown's local storage allowance is the width of one digit. -/
+theorem frame_length_le (base : Stacks K) (src tmp : K) (xs ys : List Bool) :
+ ∑ k, (frame src tmp base xs ys k).length ≤ (∑ k, (base k).length) + xs.length + ys.length :=
+ (update_length _ _ _).trans (Nat.add_le_add_right (update_length _ _ _) _)
+
+include hne in
+/-- On the closed binary-choice machine, all branches halt within the clock
+and every reachable configuration fits the peak bound. The final instruction
+closes a normal return with the selected halt outcome. -/
+theorem repeat_space_clock (bank : S → Stacks K) (w B A callbackSpace : ℕ)
+ (base_bound : ∀ x, ∑ k, (bank x k).length ≤ A)
+ (callback : ∀ (x : S) (bits : List Bool), bits.length = w →
+ ∀ (extra fuel : ℕ), extra+B ≤ fuel → ∀ c,
+ (∀ y n, extra ≤ n → c n (frame src tmp (bank y) bits [])) →
+ body.Safe (fun s => ∑ k, (s k).length ≤ max (A+w) callbackSpace)
+ c fuel (frame src tmp (bank x) bits []))
+ (bits : List Bool) (hw : bits.length = w) (x : S) (outcome : Bool) :
+ let r := repeatRoutine src tmp body
+ let input := frame src tmp (bank x) bits []
+ StopsWithin (r.close outcome) (1+repeatBudget w B (value bits)) (some r.entry) input ∧
+ ∀ ⦃q s⦄, StackCompiler.Reach (r.close outcome) (some r.entry) input q s →
+ ∑ k, (s k).length ≤ max (A+w) callbackSpace := by
+ let limit (s : Stacks K) := ∑ k, (s k).length ≤ max (A+w) callbackSpace
+ have fits (y : S) (xs ys : List Bool) (hh : xs.length+ys.length ≤ w) :
+ limit (frame src tmp (bank y) xs ys) := by
+ have h := frame_length_le (bank y) src tmp xs ys
+ have h' := base_bound y
+ dsimp [limit]
+ exact (show ∑ k, (frame src tmp (bank y) xs ys k).length ≤ A+w by omega).trans (le_max_left ..)
+ have h := repeat_safe src tmp hne body limit (fun n s => 0 ⟨hn, fits y [] [] (by simp)⟩)
+ exact ⟨h.stopsWithin outcome (fun _ _ hc => hc.1),
+ fun _ _ path => h.reach outcome (fun _ _ hc => hc.2) path⟩
+
+end Storage
+
+end EvaluatorDigitSafety
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorDigitSchedule.lean b/lean/OAI/Computability/VPVNP/EvaluatorDigitSchedule.lean
new file mode 100644
index 0000000000..72d6f05060
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorDigitSchedule.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.Evaluator
+import OAI.Computability.VPVNP.EvaluatorDigitRepeat
+import Mathlib.Data.List.FinRange
+
+/-! # The compact digit schedule of the finite-algebra evaluator
+
+After radix conversion, each column contains one base-`Q` digit for every
+label. Processing the columns most significant first produces the same list of
+linear maps as the paper's monomial program. Each column starts with a
+Frobenius step, then repeats label multiplication according to the binary
+counter on that label.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorDigitSchedule
+
+variable {t : ℕ}
+
+/-- The two types of matrix queries made by the monomial evaluator. -/
+inductive Action (t : ℕ) where
+ | frobenius
+ | label (i : Fin t)
+ deriving DecidableEq, Fintype
+
+/-- Actions emitted by the digit counters at one position. -/
+def emit (d : Fin t → ℕ) : List (Action t) :=
+ .frobenius :: (List.finRange t).flatMap fun i => List.replicate (d i) (.label i)
+
+/-- A compact schedule of digit columns, before expanding any multiplicities. -/
+def columns (Q : ℕ) : ℕ → (Fin t → ℕ) → List (Fin t → ℕ)
+ | 0, _ => []
+ | w+1, e => columns Q w (fun i => e i / Q) ++ [fun i => e i % Q]
+
+theorem columns_length (Q w : ℕ) (e : Fin t → ℕ) : (columns Q w e).length = w := by
+ induction w generalizing e <;> simp [columns, *]
+
+/-- The radix conversion may also compute each column by its position,
+using one fixed order for the input labels. -/
+theorem columns_eq (Q w : ℕ) (e : Fin t → ℕ) :
+ columns Q w e = (List.range w).reverse.map (fun j i => e i / Q^j % Q) := by
+ induction w generalizing e with
+ | zero => rfl
+ | succ w ih =>
+ rw [columns, ih]
+ have h := List.range_succ_eq_map (n := w)
+ rw [h, List.reverse_cons, List.map_append]
+ simp only [List.map_cons, List.map_nil, pow_zero, Nat.div_one, ← List.map_reverse, List.map_map]
+ congr 1
+ apply List.map_congr_left
+ intro j _
+ funext i
+ simp [Nat.div_div_eq_div_mul, pow_succ, Nat.mul_comm]
+
+/-- Every digit lies below the cardinality of the base field. -/
+theorem columns_digit_lt {Q : ℕ} (hQ : 0 < Q) (w : ℕ) (e : Fin t → ℕ)
+ {d : Fin t → ℕ} (hd : d ∈ columns Q w e) (i : Fin t) : d i < Q := by
+ rw [columns_eq] at hd
+ obtain ⟨_, _, rfl⟩ := List.mem_map.mp hd
+ exact Nat.mod_lt _ hQ
+
+variable (K : Type*) [Field K] [Fintype K] {A : Type*} [CommRing A] [Algebra K A]
+
+/-- Interpret the streamed query identifier as a linear operator. -/
+def actionMap (X : Fin t → A) : Action t → A →ₗ[K] A
+ | .frobenius => (FiniteField.frobeniusAlgHom K A).toLinearMap
+ | .label i => LinearMap.mulLeft K (X i)
+
+theorem map_emit (X : Fin t → A) (d : Fin t → ℕ) :
+ (emit d).map (actionMap K X) = Evaluator.digitSteps K X d := by
+ simp [emit, actionMap, Evaluator.digitSteps, List.map_flatMap]
+
+/-- A column-by-column streaming traversal produces the precise chronological
+sequence of Frobenius and multiplication queries in equation (8.2). -/
+theorem actions_eq_digitProgram (X : Fin t → A) (w : ℕ) (e : Fin t → ℕ) :
+ ((columns (Fintype.card K) w e).flatMap emit).map (actionMap K X) =
+ Evaluator.digitProgram K X w e := by
+ induction w generalizing e with
+ | zero => rfl
+ | succ w ih =>
+ simp only [columns, List.flatMap_append, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil, List.map_append, ih, map_emit, Evaluator.digitProgram]
+
+/-- A compact schedule uses `w*t` digits, and executes at most one Frobenius
+and `t*(Q-1)` label multiplications per column. -/
+theorem action_count_le (w : ℕ) (e : Fin t → ℕ) :
+ ((columns (Fintype.card K) w e).flatMap emit).length ≤ w * (1+t*(Fintype.card K-1)) := by
+ let X : Fin t → K := fun _ => 0
+ simpa only [← actions_eq_digitProgram K X w e, List.length_map] using
+ Evaluator.digitProgram_length_le K X w e
+
+end EvaluatorDigitSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorIndexChoice.lean b/lean/OAI/Computability/VPVNP/EvaluatorIndexChoice.lean
new file mode 100644
index 0000000000..d5d27502cb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorIndexChoice.lean
@@ -0,0 +1,253 @@
+import OAI.Computability.VPVNP.StructuredStackTotal
+import OAI.Computability.VPVNP.RAMTapeWord
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# A binary machine choice below an input bound
+
+The evaluator guesses a basis index after each linear step. It also makes a
+final choice below the prime-field residue. This finite-control routine consumes
+the little-endian bits of the bound and guesses one bit for each. Comparing
+successive, more significant bits requires only one bit of state. A successful
+choice writes the guessed bits in big-endian order onto the output stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.IndexChoice
+
+open RAMTape
+
+/-- Finite control for a bounded binary guess. It retains the comparison with the bound as it
+reads and writes successive bits. -/
+inductive Phase where
+ | read (less : Bool)
+ | guess (less boundBit : Bool)
+ | write (less guessBit : Bool)
+ | finish (less : Bool)
+ deriving DecidableEq, Fintype
+
+private def nextLess (less guessBit boundBit : Bool) : Bool :=
+ if guessBit = boundBit then less else boundBit
+
+/-- Each bit takes a pop, a two-way choice and a push. A final pop and
+comparison either return to the continuation or halt in rejection. -/
+def guessBelow {K : Type*} (bound dest : K) : Routine K Phase where
+ entry := .read false
+ code
+ | .read less => .pop bound fun b ↦ some (b.elim (.finish less) (.guess less))
+ | .guess less b => .choose (some (.write (nextLess less false b) false))
+ (some (.write (nextLess less true b) true))
+ | .write less b => .push dest b (some (.read less))
+ | .finish true => .goto none
+ | .finish false => .halt false
+
+private def below (less : Bool) (guess bound : List Bool) : Prop :=
+ TapeWord.value guess < TapeWord.value bound ∨
+ (TapeWord.value guess = TapeWord.value bound ∧ less = true)
+
+private instance (less : Bool) (guess bound : List Bool) : Decidable (below less guess bound) :=
+ inferInstanceAs (Decidable (_ ∨ _))
+
+private theorem below_cons (less a b : Bool) (x y : List Bool) :
+ below less (a :: x) (b :: y) ↔ below (nextLess less a b) x y := by
+ cases less <;> cases a <;> cases b <;> simp [below, nextLess, TapeWord.value] <;> omega
+
+variable {K : Type*} [DecidableEq K] (bound dest : K) (hne : bound ≠ dest)
+
+/-- Replace the exhausted bound by the empty stack and prepend the guessed
+bits, high bit first, to the destination. -/
+def written (s : Stacks K) (bits : List Bool) : Stacks K :=
+ Function.update (Function.update s bound []) dest (bits.reverse ++ s dest)
+
+include hne in
+private theorem written_step (s : Stacks K) (tail bits : List Bool) (b : Bool) :
+ written bound dest (Function.update (Function.update s bound tail) dest (b :: s dest)) bits =
+ written bound dest s (b :: bits) := by
+ funext k
+ by_cases hd : k = dest
+ · subst k
+ simp [written, List.append_assoc]
+ · by_cases hb : k = bound
+ · subst k
+ simp [written, Function.update_of_ne hne]
+ · simp [written, Function.update_of_ne, hd, hb]
+
+include hne in
+private theorem count_read (fuel : ℕ) (c : ℕ → Stacks K → ℕ) (less : Bool)
+ (bs : List Bool) (s : Stacks K) (hs : s bound = bs) :
+ (guessBelow bound dest).countFrom c (fuel + (3 * bs.length + 2)) (some (.read less)) s =
+ ∑ f : Fin bs.length → Bool,
+ if below less (List.ofFn f) bs then c fuel (written bound dest s (List.ofFn f)) else 0 := by
+ induction bs generalizing less s with
+ | nil =>
+ have hup : Function.update s bound [] = s := by rw [← hs, Function.update_eq_self]
+ cases less <;> simp [Routine.countFrom, guessBelow, hs, below, written, TapeWord.value, hup]
+ | cons b bs ih =>
+ let s' := Function.update s bound bs
+ let out (a : Bool) := Function.update s' dest (a :: s dest)
+ have hsrc (a) : out a bound = bs := by simp [out, s', Function.update_of_ne hne]
+ have step (r : ℕ) :
+ (guessBelow bound dest).countFrom c (r+3) (some (.read less)) s =
+ (guessBelow bound dest).countFrom c r (some (.read (nextLess less false b))) (out false) +
+ (guessBelow bound dest).countFrom c r (some (.read (nextLess less true b))) (out true) := by
+ simp only [Routine.countFrom, guessBelow, hs, List.head?_cons, List.tail_cons, Option.elim_some]
+ simp only [out, s', Function.update_of_ne hne.symm]
+ rw [show fuel + (3 * (b :: bs).length + 2) = (fuel + (3 * bs.length + 2)) + 3 by
+ simp only [List.length_cons]; omega, step, ih _ (out false) (hsrc false),
+ ih _ (out true) (hsrc true)]
+ let test (f : Fin (bs.length + 1) → Bool) :=
+ if below less (List.ofFn f) (b :: bs) then c fuel (written bound dest s (List.ofFn f)) else 0
+ change _ = ∑ f, test f
+ rw [← (Fin.consEquiv (fun _ : Fin (bs.length + 1) ↦ Bool)).sum_comp test,
+ Fintype.sum_prod_type, Fintype.sum_bool, add_comm]
+ simp only [Fin.consEquiv_apply, test, List.ofFn_succ, Fin.cons_zero, Fin.cons_succ, below_cons,
+ out, s', written_step bound dest hne]
+
+include hne in
+/-- The continuation runs once per legal binary representation, at exactly
+the same remaining fuel on all successful branches. -/
+theorem count_guessBelow (c : ℕ → Stacks K → ℕ) (fuel : ℕ) (s : Stacks K) :
+ (guessBelow bound dest).count c (fuel + (3 * (s bound).length + 2)) s =
+ ∑ f : Fin (s bound).length → Bool,
+ if TapeWord.value (List.ofFn f) < TapeWord.value (s bound) then
+ c fuel (written bound dest s (List.ofFn f)) else 0 := by
+ simpa only [Routine.count, guessBelow, below, Bool.false_eq_true, and_false, or_false] using
+ count_read bound dest hne fuel c false (s bound) s rfl
+
+include hne in
+/-- With a bound encoded as one word, the integer count is the sum over the
+legal index type. There are no duplicate representations or modulo aliases. -/
+theorem count_guessBelow_fin {w : ℕ} (n : BurstRAM.Word w) (s : Stacks K)
+ (hs : s bound = BurstRAM.wordBits n) (c : ℕ → Stacks K → ℕ) (fuel : ℕ) :
+ (guessBelow bound dest).count c (fuel + (3*w + 2)) s =
+ ∑ i : Fin n.val, c fuel (written bound dest s
+ (BurstRAM.wordBits (Fin.castLE n.isLt.le i : BurstRAM.Word w))) := by
+ classical
+ let g (bs : List Bool) := if TapeWord.value bs < TapeWord.value (s bound) then
+ c fuel (written bound dest s bs) else 0
+ have hl : (s bound).length = w := hs ▸ BurstRAM.length_wordBits n
+ have hr : ∀ m l : ℕ, m = l → (∑ x : Fin m → Bool, g (List.ofFn x)) =
+ ∑ x : Fin l → Bool, g (List.ofFn x) := fun m _ h ↦ h ▸ rfl
+ conv_lhs => rw [← hl, count_guessBelow bound dest hne]
+ change (∑ x : Fin (s bound).length → Bool, g (List.ofFn x)) = _
+ rw [hr _ _ hl, ← (RAMSerialization.wordBits w).sum_comp (fun x ↦ g (List.ofFn x))]
+ dsimp only [g]
+ rw [hs, TapeWord.value_wordBits]
+ change (∑ i : BurstRAM.Word w, if TapeWord.value (BurstRAM.wordBits i) < n.val then
+ c fuel (written bound dest s (BurstRAM.wordBits i)) else 0) = _
+ rw [show (∑ i : BurstRAM.Word w, if TapeWord.value (BurstRAM.wordBits i) < n.val then
+ c fuel (written bound dest s (BurstRAM.wordBits i)) else 0) =
+ ∑ i : {i : BurstRAM.Word w // i.val < n.val}, c fuel (written bound dest s (BurstRAM.wordBits i.val)) by
+ simp only [TapeWord.value_wordBits, ← Finset.sum_filter]
+ exact Finset.sum_subtype _ (by simp) _]
+ let e : Fin n.val ≃ {i : BurstRAM.Word w // i.val < n.val} :=
+ { toFun := fun i ↦ ⟨Fin.castLE n.isLt.le i, i.isLt⟩
+ invFun := fun i ↦ ⟨i.val.val, i.property⟩
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ exact (e.sum_comp (fun i ↦ c fuel (written bound dest s (BurstRAM.wordBits i.val)))).symm
+
+include hne in
+/-- Returning with one successful leaf per legal final guess realizes the
+representative of the prime-field residue as an integer path count. -/
+theorem count_final_residue {w : ℕ} (n : BurstRAM.Word w) (s : Stacks K)
+ (hs : s bound = BurstRAM.wordBits n) (fuel : ℕ) :
+ (guessBelow bound dest).count (fun _ _ ↦ 1) (fuel + (3*w + 2)) s = n.val := by
+ rw [count_guessBelow_fin bound dest hne n s hs]
+ simp
+
+include hne in
+private theorem allStops_read (c : ℕ → Stacks K → Prop) (fuel : ℕ) (less : Bool)
+ (bs : List Bool) (s : Stacks K) (hs : s bound = bs)
+ (hc : ∀ xs : List Bool, xs.length = bs.length → below less xs bs →
+ c fuel (written bound dest s xs)) :
+ (guessBelow bound dest).AllStopsFrom c (fuel+(3*bs.length+2)) (some (.read less)) s := by
+ induction bs generalizing less s with
+ | nil =>
+ have hup : Function.update s bound [] = s := by rw [← hs, Function.update_eq_self]
+ cases less with
+ | false => simp [Routine.AllStopsFrom, guessBelow, hs]
+ | true =>
+ have hv := hc [] rfl (by simp [below])
+ simpa [Routine.AllStopsFrom, guessBelow, hs, written, hup] using hv
+ | cons b bs ih =>
+ let rest := Function.update s bound bs
+ let out (a : Bool) := Function.update rest dest (a :: s dest)
+ have hsrc (a) : out a bound = bs := by simp [out, rest, Function.update_of_ne hne]
+ have recur (a : Bool) := ih (nextLess less a b) (out a) (hsrc a) (by
+ intro xs hx hv
+ simpa only [out, rest, written_step bound dest hne] using
+ hc (a :: xs) (by simp [hx]) ((below_cons ..).mpr hv))
+ rw [show fuel+(3*(b::bs).length+2) = (fuel+(3*bs.length+2))+3 by simp; omega]
+ have step (r : ℕ) :
+ (guessBelow bound dest).AllStopsFrom c (r+3) (some (.read less)) s ↔
+ (guessBelow bound dest).AllStopsFrom c r (some (.read (nextLess less false b))) (out false) ∧
+ (guessBelow bound dest).AllStopsFrom c r (some (.read (nextLess less true b))) (out true) := by
+ simp only [Routine.AllStopsFrom, guessBelow, hs, List.head?_cons, List.tail_cons, Option.elim_some,
+ out, rest, Function.update_of_ne hne.symm]
+ exact (step _).mpr ⟨recur false, recur true⟩
+
+include hne in
+/-- Every nonrejecting branch returns a legal ordinal with the same residual
+clock, while every illegal choice has already halted. -/
+theorem allStops_guessBelow {w : ℕ} (n : BurstRAM.Word w) (s : Stacks K)
+ (hs : s bound = BurstRAM.wordBits n) (c : ℕ → Stacks K → Prop) (fuel : ℕ)
+ (hc : ∀ i : Fin n.val, c fuel (written bound dest s
+ (BurstRAM.wordBits (Fin.castLE n.isLt.le i : BurstRAM.Word w)))) :
+ (guessBelow bound dest).AllStops c (fuel+(3*w+2)) s := by
+ have h := allStops_read bound dest hne c fuel false (BurstRAM.wordBits n) s hs (by
+ intro xs hx hv
+ rw [BurstRAM.length_wordBits] at hx
+ have hh : TapeWord.value xs < n.val := by simpa [below, TapeWord.value_wordBits] using hv
+ let i : Fin n.val := ⟨TapeWord.value xs, hh⟩
+ have same : BurstRAM.wordBits (Fin.castLE n.isLt.le i : BurstRAM.Word w) = xs :=
+ TapeWord.eq_of_length_value (by simp [hx]) (by simp [i, TapeWord.value_wordBits])
+ simpa only [same] using hc i)
+ simpa only [Routine.AllStops, guessBelow, BurstRAM.length_wordBits] using h
+
+include hne in
+private theorem stops_read (b : Bool) (bs : List Bool) (s : Stacks K)
+ (hs : s bound = bs) (less : Bool) :
+ StopsWithin ((guessBelow bound dest).close b) (3*bs.length+3) (some (.read less)) s := by
+ induction bs generalizing s less with
+ | nil => cases less <;> simp [StopsWithin, guessBelow, Routine.close, hs]
+ | cons d ds ih =>
+ let rest := Function.update s bound ds
+ let out (a : Bool) := Function.update rest dest (a :: rest dest)
+ have hsrc (a) : out a bound = ds := by simp [out, rest, Function.update_of_ne hne]
+ have step (t : ℕ) : StopsWithin ((guessBelow bound dest).close b) (t+3) (some (.read less)) s ↔
+ StopsWithin ((guessBelow bound dest).close b) t (some (.read (nextLess less false d))) (out false) ∧
+ StopsWithin ((guessBelow bound dest).close b) t (some (.read (nextLess less true d))) (out true) := by
+ simp only [StopsWithin, Routine.close, guessBelow, hs, List.head?_cons, List.tail_cons,
+ Option.elim_some, out, rest]
+ rw [show 3*(d::ds).length+3 = (3*ds.length+3)+3 by simp; omega, step]
+ exact ⟨ih _ (hsrc false) _, ih _ (hsrc true) _⟩
+
+include hne in
+/-- Even illegal index guesses halt within the same linear instruction clock. -/
+theorem guessBelow_stops (b : Bool) (s : Stacks K) :
+ StopsWithin ((guessBelow bound dest).close b) (3*(s bound).length+3)
+ (some (guessBelow bound dest).entry) s :=
+ stops_read bound dest hne b (s bound) s rfl false
+
+include hne in
+/-- Close the returning routine as an accepting machine: its actual binary
+branch tree has exactly the specified number of accepting leaves. -/
+theorem final_residue_paths {w : ℕ} (n : BurstRAM.Word w) (s : Stacks K)
+ (hs : s bound = BurstRAM.wordBits n) :
+ stackPaths ((guessBelow bound dest).close true) (3*w+3)
+ (some (guessBelow bound dest).entry) s = n.val := by
+ rw [Routine.stackPaths_close]
+ change (guessBelow bound dest).count _ _ s = _
+ rw [show 3*w+3 = 1+(3*w+2) by omega,
+ count_guessBelow_fin bound dest hne n s hs]
+ simp
+
+end Evaluator.IndexChoice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorIndexRegisters.lean b/lean/OAI/Computability/VPVNP/EvaluatorIndexRegisters.lean
new file mode 100644
index 0000000000..8a2b9c3036
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorIndexRegisters.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.EvaluatorMatrixStep
+import OAI.Computability.VPVNP.EvaluatorSafetyTransfer
+import OAI.Computability.VPVNP.EvaluatorRadixDivision
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-!
+# The basis index registers of the evaluator
+
+Each step preserves the advised dimension and the old ordinal while it
+generates the new ordinal in the little-endian format used by the query
+routines. Once the entry has been used, committing the new ordinal clears
+the scratch stacks and prepares the registers for another step.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.IndexRegisters
+
+open RAMTape EvaluatorRadixDivision SliceArithmetic
+
+/-- Stacks for the basis dimension, current ordinal, bounded guess and the scratch used to
+commit the next ordinal. -/
+inductive Port where
+ | dimension | current | bound | reversed | next | scratch
+ deriving DecidableEq
+
+instance : Fintype Port :=
+ ⟨{.dimension, .current, .bound, .reversed, .next, .scratch}, fun k ↦ by cases k <;> simp⟩
+
+/-- The two index words available during an entry query. At a step boundary
+the next index is empty. -/
+def bank (dimension current next : List Bool) : Stacks Port
+ | .dimension => dimension | .current => current | .next => next | _ => []
+
+private def prepared (dim cur : List Bool) := Function.update (bank dim cur []) .bound dim
+
+private def prepare : FiniteRoutine Port := SuccessorFields.prependCopy .dimension .bound .scratch
+
+/-- Guess once below the dimension and restore the chosen word to the
+same bit order as the old index. -/
+def select : FiniteRoutine Port :=
+ .ofRoutine (matrixStep .bound .reversed prepare.body (reverseOnto .reversed .next).body)
+
+private theorem prepare_runs (dim cur : List Bool) :
+ prepare.Runs (5*dim.length+2) (bank dim cur []) (prepared dim cur) := by
+ simpa only [prepare, prepared, bank, List.append_nil] using
+ SuccessorFields.prependCopy_runs Port.dimension .bound .scratch (by decide) (by decide)
+ (by decide) (bank dim cur []) rfl
+
+private theorem selected_runs (dim cur bits : List Bool) :
+ (reverseOnto .reversed .next).Runs (2*bits.length+1)
+ (IndexChoice.written .bound .reversed (prepared dim cur) bits) (bank dim cur bits) := by
+ let chosen := IndexChoice.written Port.bound .reversed (prepared dim cur) bits
+ have hlen : (chosen .reversed).length = bits.length := by simp [chosen, IndexChoice.written, prepared, bank]
+ rw [← hlen]
+ apply reverseOnto_runs (by decide : Port.reversed ≠ .next) _ _ rfl
+ · simp [chosen, IndexChoice.written, prepared, bank]
+ · intro k hrev hn
+ cases k <;> first | contradiction | rfl
+
+theorem select_count {v : ℕ} (n : BurstRAM.Word v) (cur : List Bool)
+ (c : ℕ → Stacks Port → ℕ) (fuel : ℕ) :
+ select.body.count c (fuel+(10*v+5)) (bank (BurstRAM.wordBits n) cur []) =
+ ∑ j : Fin n.val, c fuel (bank (BurstRAM.wordBits n) cur
+ (BurstRAM.wordBits (Fin.castLE n.isLt.le j : BurstRAM.Word v))) := by
+ let dim := BurstRAM.wordBits n
+ let bits (j : Fin n.val) := BurstRAM.wordBits (Fin.castLE n.isLt.le j : BurstRAM.Word v)
+ have hp := prepare_runs dim cur
+ simp only [dim, BurstRAM.length_wordBits] at hp
+ let chosen (j : Fin n.val) := IndexChoice.written .bound .reversed (prepared dim cur) (bits j)
+ have hr (j : Fin n.val) :
+ (reverseOnto .reversed .next).Runs (2*v+1) (chosen j) (bank dim cur (bits j)) := by
+ simpa only [bits, BurstRAM.length_wordBits] using selected_runs dim cur (bits j)
+ have hc := matrixStep_count Port.bound .reversed prepare.body (reverseOnto .reversed .next).body
+ (by decide) n hp rfl (fun j ↦ bank dim cur (bits j)) (fun _ ↦ 2*v+1) hr c
+ (fuel+(2*v+1)) (fun _ ↦ by omega)
+ rw [show fuel+(2*v+1)+(3*v+2)+(5*v+2) = fuel+(10*v+5) by omega] at hc
+ simp only [Nat.add_sub_cancel] at hc
+ exact hc
+
+/-- The selection code preserves a polynomial storage bound on both branches
+of every choice. All returning branches supply an in-range ordinal. -/
+theorem select_safe {v : ℕ} (n : BurstRAM.Word v) (cur : List Bool)
+ (safe : Stacks Port → Prop) (cont : ℕ → Stacks Port → Prop) (reserve : ℕ)
+ (hroom : ∀ s, (∀ k, (s k).length ≤ (bank (BurstRAM.wordBits n) cur [] k).length + (10*v+5)) → safe s)
+ (hc : ∀ j : Fin n.val, cont reserve (bank (BurstRAM.wordBits n) cur
+ (BurstRAM.wordBits (Fin.castLE n.isLt.le j : BurstRAM.Word v)))) :
+ select.body.Safe safe cont (reserve+(10*v+5)) (bank (BurstRAM.wordBits n) cur []) := by
+ apply EvaluatorRoutineSafety.safe_of_allStops cont reserve _ hroom
+ let dim := BurstRAM.wordBits n
+ let c (left : ℕ) := cont (reserve+left)
+ let post := (reverseOnto Port.reversed .next).body
+ change ((prepare.body.followedBy (IndexChoice.guessBelow Port.bound .reversed)).followedBy post).AllStops
+ c (10*v+5) (bank dim cur [])
+ rw [Routine.allStops_followedBy, Routine.allStops_followedBy]
+ have hp := prepare_runs dim cur
+ simp only [dim, BurstRAM.length_wordBits] at hp
+ rw [show 10*v+5 = (2*v+1+(3*v+2))+(5*v+2) by omega, hp.allStops_iff]
+ apply IndexChoice.allStops_guessBelow Port.bound Port.reversed (by decide) n _ rfl (post.AllStops c) (2*v+1)
+ intro j
+ let bits := BurstRAM.wordBits (Fin.castLE n.isLt.le j : BurstRAM.Word v)
+ have hh := selected_runs dim cur bits
+ simp only [bits, BurstRAM.length_wordBits] at hh
+ have h := (hh.allStops_iff c 0).mpr (hc j)
+ simpa only [Nat.zero_add] using h
+
+/-- Replace the old ordinal by the new one after the matrix entry query. -/
+def commit : FiniteRoutine Port :=
+ ((CallClear.clear .current).followedBy (reverseOnto .next .reversed)).followedBy
+ (reverseOnto .reversed .current)
+
+theorem commit_runs (dim cur next : List Bool) :
+ commit.Runs (cur.length + 4*next.length + 3) (bank dim cur next) (bank dim next []) := by
+ let mid := bank dim [] next
+ let rev := Function.update (bank dim [] []) .reversed next.reverse
+ have clear : (CallClear.clear .current).Runs (cur.length+1) (bank dim cur next) mid := by
+ have hc := CallClear.clear_runs Port.current (bank dim cur next)
+ have h : Function.update (bank dim cur next) .current [] = mid := by
+ funext p
+ cases p <;> rfl
+ rwa [h] at hc
+ have first : (reverseOnto .next .reversed).Runs (2*next.length+1) mid rev := by
+ apply reverseOnto_runs (by decide : Port.next ≠ .reversed) mid rev rfl
+ · simp [mid, rev, bank]
+ · intro k hn hr
+ cases k <;> first | contradiction | rfl
+ have last : (reverseOnto .reversed .current).Runs (2*next.length+1) rev (bank dim next []) := by
+ have hlen : (rev .reversed).length = next.length := by simp [rev]
+ rw [← hlen]
+ apply reverseOnto_runs (by decide : Port.reversed ≠ .current) _ _ rfl
+ · simp [rev, bank]
+ · intro k hrev hc
+ cases k <;> first | contradiction | rfl
+ have run := (clear.followedBy first).followedBy last
+ rwa [show cur.length+1+(2*next.length+1)+(2*next.length+1) = cur.length+4*next.length+3 by omega] at run
+
+end Evaluator.IndexRegisters
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorInputBank.lean b/lean/OAI/Computability/VPVNP/EvaluatorInputBank.lean
new file mode 100644
index 0000000000..bd2e330b03
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorInputBank.lean
@@ -0,0 +1,199 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.EvaluatorMatrixStep
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Loading evaluator advice and exponents from a binary input
+
+Each fixed port receives a separate field. A zero tag ends the field and a one
+tag precedes a payload bit. Sending payloads in reverse order puts the original
+lists on their stacks with one push per bit. The parser's finite control is
+fixed by the ordered port names, independently of field lengths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.InputBank
+
+open RAMTape
+
+private def tagged : List Bool → List Bool
+ | [] => [false]
+ | b :: bs => true :: b :: tagged bs
+
+/-- A self-delimiting raw input field. -/
+def fieldBits (bs : List Bool) : List Bool := tagged bs.reverse
+
+private theorem length_tagged (bs : List Bool) : (tagged bs).length = 2*bs.length+1 := by
+ induction bs <;> simp [tagged, *]
+ omega
+
+theorem length_fieldBits (bs : List Bool) : (fieldBits bs).length = 2*bs.length+1 := by
+ simp [fieldBits, length_tagged]
+
+private theorem tagged_pair (xs : List Bool) (i : Fin xs.length) :
+ (tagged xs)[2*i.val]'(by rw [length_tagged]; omega) = true ∧
+ (tagged xs)[2*i.val+1]'(by rw [length_tagged]; omega) = xs[i.val] := by
+ induction xs with
+ | nil => exact i.elim0
+ | cons b bs ih =>
+ cases i using Fin.cases with
+ | zero => exact ⟨rfl, rfl⟩
+ | succ j =>
+ simp only [Fin.val_succ, Nat.mul_succ, tagged, List.getElem_cons_succ]
+ exact ih j
+
+private theorem tagged_end (xs : List Bool) :
+ (tagged xs)[2*xs.length]'(by rw [length_tagged]; omega) = false := by
+ induction xs with
+ | nil => rfl
+ | cons b bs ih =>
+ simpa only [List.length_cons, Nat.mul_succ, tagged, List.getElem_cons_succ] using ih
+
+theorem fieldBits_tag (xs : List Bool) (i : Fin xs.length) :
+ (fieldBits xs)[2*i.val]'(by rw [length_fieldBits]; omega) = true :=
+ (tagged_pair xs.reverse ⟨i.val, by simp⟩).1
+
+theorem fieldBits_payload (xs : List Bool) (i : Fin xs.length) :
+ (fieldBits xs)[2*i.val+1]'(by rw [length_fieldBits]; omega) = xs.reverse[i.val]'(by simp) :=
+ (tagged_pair xs.reverse ⟨i.val, by simp⟩).2
+
+theorem fieldBits_end (xs : List Bool) :
+ (fieldBits xs)[2*xs.length]'(by rw [length_fieldBits]; omega) = false := by
+ simpa only [fieldBits, List.length_reverse] using tagged_end xs.reverse
+
+/-- Finite control for reading tagged input fields and pushing each payload bit onto its named
+stack. -/
+inductive Phase where
+ | tag | bit | push (b : Bool) | reject
+ deriving DecidableEq, Fintype
+
+/-- Port `none` contains the raw input. All output ports have the form
+`some k`, so reading a field never overwrites an unread input bit. -/
+def readField {K : Type} (k : K) : Routine (Option K) Phase where
+ entry := .tag
+ code
+ | .tag => .pop none fun b ↦ match b with
+ | none => some .reject | some false => none | some true => some .bit
+ | .bit => .pop none fun b ↦ some (b.elim .reject .push)
+ | .push b => .push (some k) b (some .tag)
+ | .reject => .halt false
+
+/-- Place the raw stream on the input stack and a bank on the output stacks. -/
+def frame {K : Type} (raw : List Bool) (bank : Stacks K) : Stacks (Option K)
+ | none => raw
+ | some k => bank k
+
+variable {K : Type} [DecidableEq K]
+
+private theorem put_raw (raw raw' : List Bool) (bank : Stacks K) :
+ Function.update (frame raw bank) none raw' = frame raw' bank := by
+ funext k
+ cases k <;> simp [frame]
+
+private theorem put_port (raw bs : List Bool) (bank : Stacks K) (k : K) :
+ Function.update (frame raw bank) (some k) bs = frame raw (Function.update bank k bs) := by
+ funext j
+ cases j with
+ | none => simp [frame]
+ | some i => by_cases h : i = k <;> simp [frame, h]
+
+private theorem read_tagged (k : K) (bits tail : List Bool) (bank : Stacks K) :
+ (readField k).Runs (3*bits.length+1) (frame (tagged bits ++ tail) bank)
+ (frame tail (Function.update bank k (bits.reverse ++ bank k))) := by
+ induction bits generalizing bank with
+ | nil =>
+ simp only [List.length_nil, Nat.mul_zero, Nat.zero_add, List.reverse_nil, List.nil_append,
+ Function.update_eq_self]
+ apply StackRuns.cons (StackStep.pop (code := (readField k).standalone) rfl)
+ simp only [frame, tagged, List.cons_append, List.nil_append, List.head?_cons, List.tail_cons, put_raw]
+ exact .nil ..
+ | cons b bits ih =>
+ rw [show 3*(b::bits).length+1 = ((3*bits.length+1)+1)+1+1 by simp; omega]
+ apply StackRuns.cons (StackStep.pop (code := (readField k).standalone) rfl)
+ simp only [tagged, List.cons_append, frame, List.head?_cons, List.tail_cons, put_raw]
+ apply StackRuns.cons (StackStep.pop (code := (readField k).standalone) rfl)
+ simp only [frame, List.head?_cons, List.tail_cons, put_raw, Option.elim_some]
+ apply StackRuns.cons (StackStep.push (code := (readField k).standalone) rfl)
+ have h := ih (Function.update bank k (b::bank k))
+ simp only [Function.update_self, Function.update_idem] at h
+ simp only [frame, put_port, List.reverse_cons, List.append_assoc, List.singleton_append]
+ exact h
+
+/-- Reading one field consumes its terminator and leaves the next field at
+the top of the input. It uses three instructions per bit and one for the tag. -/
+theorem readField_runs (k : K) (bs tail : List Bool) (bank : Stacks K) :
+ (readField k).Runs (3*bs.length+1) (frame (fieldBits bs ++ tail) bank)
+ (frame tail (Function.update bank k (bs ++ bank k))) := by
+ simpa [fieldBits] using read_tagged k bs.reverse tail bank
+
+/-- The ordered fields are fixed when the input parser is compiled. -/
+def reader : List K → FiniteRoutine (Option K)
+ | [] => .ret
+ | k :: ks => (FiniteRoutine.ofRoutine (readField k)).followedBy (reader ks)
+
+/-- Raw binary serialization of the selected ports, in their specified order. -/
+def rawInput (ks : List K) (data : Stacks K) : List Bool :=
+ ks.flatMap (fun k ↦ fieldBits (data k))
+
+private def load (data : Stacks K) : List K → Stacks K → Stacks K
+ | [], bank => bank
+ | k :: ks, bank => load data ks (Function.update bank k (data k ++ bank k))
+
+private theorem reader_runs (ks : List K) (data bank : Stacks K) (tail : List Bool) :
+ (reader ks).Runs ((ks.map (fun k ↦ 3*(data k).length+1)).sum+1)
+ (frame (rawInput ks data ++ tail) bank) (frame tail (load data ks bank)) := by
+ induction ks generalizing bank with
+ | nil => exact Routine.runs_ret _
+ | cons k ks ih =>
+ have h := FiniteRoutine.Runs.followedBy (a := .ofRoutine (readField k))
+ (readField_runs k (data k) (rawInput ks data ++ tail) bank) (ih _)
+ simpa only [reader, rawInput, load, List.map_cons, List.sum_cons, List.flatMap_cons,
+ List.append_assoc, Nat.add_assoc] using h
+
+private theorem load_apply (ks : List K) (data bank : Stacks K) (hks : ks.Nodup) (k : K) :
+ load data ks bank k = if k ∈ ks then data k ++ bank k else bank k := by
+ induction ks generalizing bank with
+ | nil => simp [load]
+ | cons j ks ih =>
+ rw [load, ih _ hks.of_cons]
+ by_cases he : k = j
+ · subst k
+ simp [hks.notMem]
+ · simp [he]
+
+/-- From the raw input alone, restore the complete named evaluator bank.
+Advice fields and runtime exponent fields have independent data and lengths. -/
+theorem load_input_runs (ks : List K) (hks : ks.Nodup) (hall : ∀ k, k ∈ ks) (data : Stacks K) :
+ (reader ks).Runs ((ks.map (fun k ↦ 3*(data k).length+1)).sum+1)
+ (frame (rawInput ks data) (fun _ ↦ [])) (frame [] data) := by
+ have h : load data ks (fun _ ↦ []) = data := by
+ funext k
+ simp only [load_apply ks data _ hks k, hall k, ite_true, List.append_nil]
+ simpa only [List.append_nil, h] using reader_runs ks data (fun _ ↦ []) []
+
+/-- Initially empty scratch stacks need no fields in the raw stream. -/
+theorem load_selected_runs (ks : List K) (hks : ks.Nodup) (data : Stacks K)
+ (outside : ∀ k, k ∉ ks → data k = []) :
+ (reader ks).Runs ((ks.map (fun k ↦ 3*(data k).length+1)).sum+1)
+ (frame (rawInput ks data) (fun _ ↦ [])) (frame [] data) := by
+ have h : load data ks (fun _ ↦ []) = data := by
+ funext k
+ rw [load_apply ks data _ hks k]
+ by_cases hk : k ∈ ks <;> simp [hk, outside]
+ simpa only [List.append_nil, h] using reader_runs ks data (fun _ ↦ []) []
+
+omit [DecidableEq K] in
+/-- Encoding the advice block and the exponent block separately concatenates
+their raw streams; changing an exponent does not change any advice field. -/
+theorem rawInput_append (advice exponents : List K) (data : Stacks K) :
+ rawInput (advice ++ exponents) data = rawInput advice data ++ rawInput exponents data :=
+ List.flatMap_append ..
+
+end Evaluator.InputBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorLiteralResources.lean b/lean/OAI/Computability/VPVNP/EvaluatorLiteralResources.lean
new file mode 100644
index 0000000000..6e69bd301c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorLiteralResources.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.EvaluatorCoordinateMachine
+import OAI.Computability.VPVNP.EvaluatorNativeResources
+import OAI.Computability.VPVNP.EvaluatorPhysicalBounds
+
+/-!
+# Counts, time and space of the literal evaluator from streamed coordinate queries
+
+The program table is fixed by its two coordinate readers. Its correctness and
+resources hold simultaneously for all binary exponent arrays. The same bounded
+query executions justify both the field-valued path count and all-path storage.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.MatrixCallbacks
+
+open RAMTape SliceArithmetic EvaluatorChronologicalLoop EvaluatorProgramRawInput
+ EvaluatorProgramMonomial BinaryMachine
+
+variable {P : Type} [DecidableEq P] (ps : List (WeightedStep.Port P))
+ (frobenius label : FiniteRoutine (ReadPort P))
+
+variable {p d v w t Z : ℕ} [Fact p.Prime] {K A : Type} [Field K] [Fintype K]
+ [Algebra (ZMod p) K] [CommRing A] [Algebra K A] [Algebra (ZMod p) A]
+ [IsScalarTower (ZMod p) K A] {c : Vector p (d+1)}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (dim : BurstRAM.Word v)
+ (extra : Stacks P) (extraSpace : ℕ) (hextra : ∀ k, (extra k).length ≤ extraSpace)
+ (u : Fin dim.val) (basis : Module.Basis (Fin dim.val) K A)
+ (X : Fin t → A) (es : Fin t → BurstRAM.Word Z) (divisor : List Bool)
+
+local notation "pay" => payload φ dim extra w
+local notation "Amax" => adviceCap ps.length t divisor.length (WeightedStep.bankSpace v (d+1) w extraSpace)
+local notation "Qsize" => TapeWord.value divisor
+local notation "cost" => WeightedStep.ticks v (d+1) w
+local notation "room" => workspace v (d+1) w extraSpace
+local notation "raw" => advice ps t divisor (pay (u,1)) ++ runtime es
+local notation "bankPorts" => MachinePort (WeightedStep.Port P)
+local notation "stack" => FiniteRoutine.body (evaluator ps outputPort (machine frobenius) (machine label))
+
+variable (hp : ps.Nodup) (hall : ∀ a, a ∈ ps) (hw : Word.workingWidth p ≤ w)
+ (hd : TapeWord.value divisor = Fintype.card K) (F L peak : ℕ)
+ (hf : ReadsEntryWithin φ dim extra frobenius w 0 F peak
+ ((LinearMap.toMatrixAlgEquiv basis) (FiniteField.frobeniusAlgHom K A).toLinearMap).transpose)
+ (hl : ∀ i : Fin t, ReadsEntryWithin φ dim extra label w i.val L peak
+ ((LinearMap.toMatrixAlgEquiv basis) (LinearMap.mulLeft K (X i))).transpose)
+
+include hp hall hextra hw in
+omit [Fintype K] [Algebra (ZMod p) A] [IsScalarTower (ZMod p) K A] in
+/-- The all-path resource proof uses only the two deterministic read contracts
+and positivity of the radix. It applies to any two matrices in the field. -/
+theorem stack_from_bounded_matrices (hq : 2 ≤ TapeWord.value divisor)
+ (MF : Matrix (Fin dim.val) (Fin dim.val) K) (ML : Fin t → Matrix (Fin dim.val) (Fin dim.val) K)
+ (hF : ReadsEntryWithin φ dim extra frobenius w 0 F peak MF)
+ (hL : ∀ j, ReadsEntryWithin φ dim extra label w j.val L peak (ML j)) :
+ StopsWithin ((stack).close false) (fullTicks t Z divisor.length Qsize Amax (cost F) (cost L) v w)
+ (some (stack).entry) (StackCompiler.labeledInput none (raw)) ∧
+ ∀ ⦃q s⦄, StackCompiler.Reach ((stack).close false) (some (stack).entry)
+ (StackCompiler.labeledInput none (raw)) q s →
+ stackFits (fullSpace t Z divisor.length (room peak) Amax v w) s := by
+ have native := native_from_readers φ dim extra es divisor extraSpace hextra (by omega) hw hq
+ frobenius label F L peak _ _ hF hL
+ exact full_space_clock es divisor pay (room peak) (payload_length φ dim extra extraSpace hextra peak)
+ (machine frobenius) (machine label) (cost F) (cost L) ps hp hall Amax
+ (advice_le φ dim extra divisor extraSpace hextra ps) native outputPort outputPort_injective v w
+ (fun s ↦ BurstRAM.length_wordBits (Fin.castLE dim.isLt.le s.1 : BurstRAM.Word v))
+ (fun _ ↦ List.length_replicate ..) false (u,1)
+
+include hp hall hextra hw hd hf hl in
+omit [Algebra (ZMod p) A] [IsScalarTower (ZMod p) K A] in
+/-- All paths of the linked bit-stack routine meet their clock and the same
+height bound, even when a guessed ordinal is rejected. -/
+theorem stack_from_bounded_readers :
+ StopsWithin ((stack).close false) (fullTicks t Z divisor.length Qsize Amax (cost F) (cost L) v w)
+ (some (stack).entry) (StackCompiler.labeledInput none (raw)) ∧
+ ∀ ⦃q s⦄, StackCompiler.Reach ((stack).close false) (some (stack).entry)
+ (StackCompiler.labeledInput none (raw)) q s →
+ stackFits (fullSpace t Z divisor.length (room peak) Amax v w) s := by
+ have hq : 2 ≤ Qsize := hd ▸ Fintype.one_lt_card (α := K)
+ exact stack_from_bounded_matrices ps frobenius label φ dim extra extraSpace hextra u es divisor
+ hp hall hw F L peak hq _ _ hf hl
+
+include hp hall hextra hw hd hf hl in
+/-- Equation (8.2) and the two literal head bounds for the same fixed binary
+table. The clock may be enlarged arbitrarily without changing the path count. -/
+theorem literal_from_bounded_readers [Fintype P] (hunit : basis u = 1) (hu : u.val = 0)
+ (hcoord : ∀ y, SliceEvaluator.primeCoordinate p K (φ (value (modulus c) y)) =
+ ((y (0 : Fin (d+1))).val : ZMod p))
+ (ticks : ℕ) (hticks : tapeTicks (raw).length (Fintype.card bankPorts)
+ (fullTicks t Z divisor.length Qsize Amax (cost F) (cost L) v w) ≤ ticks) :
+ let E := MatrixCallbacks.program ps frobenius label
+ (UniversalMachine.paths E ticks (UniversalMachine.initial E (raw)) : ZMod p) =
+ primeFunctional basis u (SliceEvaluator.primeCoordinate p K) (∏ i, X i ^ (es i).val) ∧
+ ∀ bits, let dis := choiceDisplacement E (UniversalMachine.initial E (raw)) bits
+ StackCompiler.HeadBox (headRadius (Fintype.card bankPorts)
+ (fullSpace t Z divisor.length (room peak) Amax v w)) dis.1 dis.2 := by
+ have h := stack_from_bounded_readers ps frobenius label φ dim extra extraSpace hextra u basis X es
+ divisor hp hall hw hd F L peak hf hl
+ let T := fullTicks t Z divisor.length Qsize Amax (cost F) (cost L) v w
+ refine ⟨?_, fun bits ↦ ?_⟩
+ · have hcount := count_from_readers ps frobenius label φ dim extra u basis X es divisor hp hall
+ hunit hu hw hcoord hd (readerBudget t Z Amax) F L (fun s ↦ by
+ apply (readTicks_le ps es divisor (pay s)).trans
+ rw [runtime_length]
+ have ha := advice_le (w := w) (t := t) φ dim extra divisor extraSpace hextra ps s
+ exact Nat.add_le_add_right (Nat.mul_le_mul_left 2 (Nat.add_le_add_right ha _)) 1)
+ (ReadsEntryWithin.readsEntry φ dim extra hf) (fun i ↦ ReadsEntryWithin.readsEntry φ dim extra (hl i)) T le_rfl
+ have hphys := program_paths_eq ps outputPort (machine frobenius) (machine label) (raw) T ticks h.1 hticks
+ exact (congrArg (fun n : ℕ ↦ (n : ZMod p)) hphys).trans hcount
+ · apply program_head_space ps outputPort (machine frobenius) (machine label) (raw) _ bits
+ dsimp only
+ intro q s path
+ have hh := Finset.sum_le_sum (s := Finset.univ) (fun k _ ↦ h.2 path k)
+ simpa only [packedCap, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, Nat.cast_id] using Nat.add_le_add_left hh (Fintype.card bankPorts+1)
+
+end Evaluator.MatrixCallbacks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorMatrixCallbacks.lean b/lean/OAI/Computability/VPVNP/EvaluatorMatrixCallbacks.lean
new file mode 100644
index 0000000000..82351ee033
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorMatrixCallbacks.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.EvaluatorWeightedStep
+import OAI.Computability.VPVNP.EvaluatorBinaryMachine
+
+/-!
+# Mounting the coordinate query in the monomial scheduler
+
+A query sees the unary label number on one port and the weighted-step payload
+on all other ports. The Frobenius and label entry readers use the same numeric
+row and column representation. The remaining digit scheduler counters are
+framed around the callbacks, so their sizes do not enter the query clock.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.MatrixCallbacks
+
+open RAMTape SliceArithmetic WeightedStep
+open EvaluatorDigitFetch (bank)
+
+variable {P : Type} [DecidableEq P]
+
+/-- The query's label-index port together with the weighted-step ports for matrix indices,
+field arithmetic and callback data. -/
+abbrev ReadPort (P : Type) := Unit ⊕ WeightedStep.Port P
+/-- The surrounding digit-fetch bank with a weighted matrix-step register bank mounted as its
+work payload. -/
+abbrev Host (P : Type) := EvaluatorDigitFetch.Port (WeightedStep.Port P)
+
+/-- Only the label index of the outer schedule is shared with its entry reader. -/
+def mount : ReadPort P → Host P
+ | .inl _ => .addr .labelIndex
+ | .inr k => .work k
+
+omit [DecidableEq P] in
+private theorem mount_injective : Function.Injective (mount (P := P)) := by
+ intro a b h
+ rcases a with (⟨⟩ | a) <;> rcases b with (⟨⟩ | b) <;> cases h <;> rfl
+
+/-- The read ABI, with the label ordinal in unary. -/
+def queryBank (label : List Bool) (s : Stacks (WeightedStep.Port P)) : Stacks (ReadPort P) :=
+ Sum.elim (fun _ ↦ label) s
+
+/-- Fixed outer callback for either the Frobenius or the label multiplication
+query. The differing query controls are installed in the same ports. -/
+def machine (read : FiniteRoutine (ReadPort P)) : FiniteRoutine (Host P) :=
+ WeightedStep.callback EvaluatorDigitFetch.Port.work (read.onPorts mount)
+
+variable {p e w v : ℕ} [Fact p.Prime] {K : Type} [Field K] [Algebra (ZMod p) K]
+ {c : Vector p e} (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K)
+ (dim : BurstRAM.Word v) (extra : Stacks P)
+
+local notation "wb" j => BurstRAM.wordBits (Fin.castLE dim.isLt.le j : BurstRAM.Word v)
+local notation "base" => (fun i n q a ↦ WeightedStep.bank φ w dim i n q a extra)
+
+private theorem query_frame (read : FiniteRoutine (ReadPort P)) (ambient : Stacks (Host P))
+ {s s' : Stacks (WeightedStep.Port P)} {d : ℕ}
+ (h : read.Runs d (queryBank (ambient (.addr .labelIndex)) s)
+ (queryBank (ambient (.addr .labelIndex)) s')) :
+ (read.onPorts mount).Runs d (installStacks EvaluatorDigitFetch.Port.work ambient s)
+ (installStacks EvaluatorDigitFetch.Port.work ambient s') := by
+ have hw : Function.Injective (EvaluatorDigitFetch.Port.work (P := WeightedStep.Port P)) :=
+ fun _ _ h ↦ EvaluatorDigitFetch.Port.work.inj h
+ have hlookup (b : Stacks (WeightedStep.Port P)) (k : ReadPort P) :
+ installStacks EvaluatorDigitFetch.Port.work ambient b (mount k) =
+ queryBank (ambient (.addr .labelIndex)) b k := by
+ cases k with
+ | inl => exact installStacks_outside _ _ (fun _ h ↦ by cases h)
+ | inr => exact installStacks_at hw ..
+ apply read.runs_onPorts_framed mount_injective h (hlookup _) (hlookup _)
+ intro k hk
+ have hn (a : WeightedStep.Port P) : EvaluatorDigitFetch.Port.work a ≠ k := hk (.inr a)
+ rw [installStacks_outside _ _ hn, installStacks_outside _ _ hn]
+
+/-- From an actual deterministic entry reader, the complete callback
+satisfies the bounded-delay law of the digit scheduler, with its label counter
+and other outer registers preserved. -/
+theorem count_callback (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (read : FiniteRoutine (ReadPort P)) (ambient : Stacks (Host P))
+ (matrix : Matrix (Fin dim.val) (Fin dim.val) K) (i : Fin dim.val) (a : K)
+ (queryTicks : ℕ)
+ (query : ∀ j : Fin dim.val, ∃ time ≤ queryTicks, read.Runs time
+ (queryBank (ambient (.addr .labelIndex)) (base i (wb j) [] a))
+ (queryBank (ambient (.addr .labelIndex)) (base i (wb j) (bits φ w (matrix i j)) a)))
+ (fuel : ℕ) (hfuel : WeightedStep.ticks v e w queryTicks ≤ fuel) :
+ ∃ delay : Fin dim.val → ℕ, (∀ j, delay j ≤ WeightedStep.ticks v e w queryTicks) ∧
+ ∀ cont, (machine read).body.count cont fuel
+ (installStacks EvaluatorDigitFetch.Port.work ambient (base i [] [] a)) =
+ ∑ j, cont (fuel-delay j)
+ (installStacks EvaluatorDigitFetch.Port.work ambient (base j [] [] (a*matrix i j))) := by
+ apply WeightedStep.callback_count φ EvaluatorDigitFetch.Port.work
+ (fun _ _ h ↦ EvaluatorDigitFetch.Port.work.inj h) ambient extra dim he hw (read.onPorts mount)
+ matrix i a queryTicks _ fuel hfuel
+ intro j
+ obtain ⟨time, ht, hrun⟩ := query j
+ exact ⟨time, ht, query_frame read ambient hrun⟩
+
+/-- Identify the fixed ports from which the final routine reads. -/
+def outputPort : Output.Port → WeightedStep.Port P
+ | .index => .indices .current
+ | .width => .width
+ | .product => .arithmetic (.inr .acc)
+
+omit [DecidableEq P] in
+theorem outputPort_injective : Function.Injective (outputPort (P := P)) := by
+ intro x y h
+ cases x <;> cases y <;> cases h <;> rfl
+
+omit [DecidableEq P] in
+/-- On the compatible polynomial-basis advice, the real arithmetic bank meets
+the terminal reader's exact low-limb and endpoint-index specifications. -/
+theorem output_data [Fintype K] {d : ℕ} {c' : Vector p (d+1)}
+ (φ' : AdjoinRoot (modulus c') ≃ₐ[ZMod p] K)
+ (hc : ∀ x, SliceEvaluator.primeCoordinate p K (φ' (value (modulus c') x)) =
+ ((x (0 : Fin (d+1))).val : ZMod p))
+ (hw : Word.workingWidth p ≤ w) (i : Fin dim.val) (a : K) :
+ ∃ tail, WeightedStep.bank φ' w dim i [] [] a extra ∘ outputPort =
+ Output.bank (wb i) (List.replicate w true) (BurstRAM.wordBits
+ (Word.limb w (⟨(SliceEvaluator.primeCoordinate p K a).val, ZMod.val_lt _⟩ : Fin p)) ++ tail) := by
+ obtain ⟨low, tail, hl, hv⟩ := packed_primeCoordinate φ' hc hw a
+ have he : low = Word.limb w (⟨(SliceEvaluator.primeCoordinate p K a).val, ZMod.val_lt _⟩ : Fin p) :=
+ Fin.ext (by rw [Word.limb_val hw]; exact hv)
+ refine ⟨tail, funext fun k ↦ ?_⟩
+ cases k with
+ | index | width => rfl
+ | product => exact he ▸ hl
+
+end Evaluator.MatrixCallbacks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorMatrixStep.lean b/lean/OAI/Computability/VPVNP/EvaluatorMatrixStep.lean
new file mode 100644
index 0000000000..079a2434c6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorMatrixStep.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.EvaluatorIndexChoice
+import OAI.Computability.VPVNP.Evaluator
+import OAI.Computability.VPVNP.StructuredStackCount
+
+/-!
+# Streaming one matrix-index path of the finite algebra evaluator
+
+A linear step chooses its next basis index once, reads that single matrix
+entry, and multiplies the running weight. The routines before and after the
+choice are deterministic. The count formula allows their costs to depend on
+the index and passes the exact remaining fuel to the next matrix step.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator
+
+open RAMTape
+
+variable {K P Q : Type*} [DecidableEq K] (bound dest : K)
+ (prepare : Routine K P) (advance : Routine K Q)
+
+/-- The first routine prepares the basis dimension. After the binary choice,
+the second routine queries the chosen entry and updates both the current index
+and the field product, keeping only the data for the next step. -/
+def matrixStep : Routine K ((P ⊕ IndexChoice.Phase) ⊕ Q) :=
+ (prepare.followedBy (IndexChoice.guessBelow bound dest)).followedBy advance
+
+/-- Count a machine step, with arbitrary subsequent computation. The per-index
+postprocessing times need only admit a common bound. -/
+theorem matrixStep_count {w : ℕ} (hne : bound ≠ dest) (n : BurstRAM.Word w)
+ {s ready : Stacks K} {prepTime : ℕ} (hp : prepare.Runs prepTime s ready)
+ (hb : ready bound = BurstRAM.wordBits n) (next : Fin n.val → Stacks K)
+ (ticks : Fin n.val → ℕ) (ha : ∀ i, advance.Runs (ticks i)
+ (IndexChoice.written bound dest ready (BurstRAM.wordBits (Fin.castLE n.isLt.le i))) (next i))
+ (c : ℕ → Stacks K → ℕ) (fuel : ℕ) (ht : ∀ i, ticks i ≤ fuel) :
+ (matrixStep bound dest prepare advance).count c (fuel + (3*w + 2) + prepTime) s =
+ ∑ i, c (fuel - ticks i) (next i) := by
+ rw [matrixStep, Routine.count_followedBy, Routine.count_followedBy, hp.count_eq,
+ IndexChoice.count_guessBelow_fin bound dest hne n ready hb]
+ apply Finset.sum_congr rfl
+ intro i _
+ have h := (ha i).count_eq c (fuel - ticks i)
+ rwa [Nat.sub_add_cancel (ht i)] at h
+
+/-- A common step budget allows every branch to be charged its own actual
+query time. The delays are independent of the choice of continuation. -/
+theorem matrixStep_count_of_bound {w : ℕ} (hne : bound ≠ dest) (n : BurstRAM.Word w)
+ {s ready : Stacks K} {prepTime : ℕ} (hp : prepare.Runs prepTime s ready)
+ (hb : ready bound = BurstRAM.wordBits n) (next : Fin n.val → Stacks K)
+ {stepBound : ℕ} (ha : ∀ i, ∃ t, prepTime + (3*w + 2) + t ≤ stepBound ∧
+ advance.Runs t (IndexChoice.written bound dest ready
+ (BurstRAM.wordBits (Fin.castLE n.isLt.le i))) (next i))
+ (hprep : prepTime + (3*w + 2) ≤ stepBound) (fuel : ℕ) (hfuel : stepBound ≤ fuel) :
+ ∃ delay : Fin n.val → ℕ, (∀ i, delay i ≤ stepBound) ∧ ∀ c,
+ (matrixStep bound dest prepare advance).count c fuel s =
+ ∑ i, c (fuel - delay i) (next i) := by
+ choose ticks htime hrun using ha
+ let first := prepTime + (3*w + 2)
+ refine ⟨fun i ↦ first + ticks i, htime, fun c ↦ ?_⟩
+ have hn : fuel - first + (3*w+2) + prepTime = fuel := by dsimp [first]; omega
+ have hh := matrixStep_count bound dest prepare advance hne n hp hb next ticks hrun c (fuel - first)
+ (fun i ↦ by have := htime i; dsimp [first]; omega)
+ simpa only [hn, Nat.sub_sub] using hh
+
+/-- Convert the running field product to its prime-field residue. A failed
+endpoint test sets the bound to zero. A successful endpoint test uses the
+residue word as the bound and each legal choice accepts immediately. -/
+def residueBranches (finalize : Routine K P) : Routine K ((P ⊕ IndexChoice.Phase) ⊕ Unit) :=
+ (finalize.followedBy (IndexChoice.guessBelow bound dest)).followedBy (Routine.halt true)
+
+/-- For the terminating routine the ordinary integer leaf count equals the
+encoded residue, at every clock that covers its two routines and final halt. -/
+theorem residueBranches_count (finalize : Routine K P) {w : ℕ} (hne : bound ≠ dest)
+ (n : BurstRAM.Word w) {s ready : Stacks K} {t : ℕ} (hp : finalize.Runs t s ready)
+ (hb : ready bound = BurstRAM.wordBits n) (c : ℕ → Stacks K → ℕ) (fuel : ℕ) :
+ (residueBranches bound dest finalize).count c (fuel+1 + (3*w+2) + t) s = n.val := by
+ rw [residueBranches, Routine.count_followedBy, Routine.count_followedBy, hp.count_eq,
+ IndexChoice.count_guessBelow_fin bound dest hne n ready hb]
+ simp [Routine.count, Routine.countFrom, Routine.halt]
+
+end Evaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorMonomialSafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorMonomialSafety.lean
new file mode 100644
index 0000000000..990e19ecde
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorMonomialSafety.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.EvaluatorMonomialSchedule
+import OAI.Computability.VPVNP.EvaluatorChronologicalSafety
+import OAI.Computability.VPVNP.EvaluatorCellSafety
+
+/-! # The exponent scheduler's all-branch time and space bounds
+
+The largest intermediate digit counter has the bit width of the field
+cardinality, regardless of how many times the label callback is invoked.
+The fixed control therefore preserves a polynomial storage cap even on
+branches that reject inside a matrix-entry query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorMonomialSchedule
+
+open RAMTape EvaluatorChronologicalLoop EvaluatorDigitFetch EvaluatorCellSafety
+ EvaluatorDigitAction EvaluatorRadixRows EvaluatorRoutineSafety
+
+variable {P S : Type} [DecidableEq P] {t Z : ℕ} (e : Fin t → BurstRAM.Word Z)
+ (ℓ Q BF BM space : ℕ) (payload : S → Stacks P)
+ (hp : ∀ x p, (payload x p).length ≤ space)
+ (frobenius multiply : FiniteRoutine (Port P))
+
+local notation "data" => packedTable ℓ Q (List.ofFn e)
+local notation "cap" => schedulerSpace (List.length data) t Z ℓ space
+local notation "fits" => stackFits cap
+
+include hp in
+/-- For callbacks with the indicated all-path contracts, the complete
+monomial traversal uses the same clock as its count computation and keeps
+every stack within the polynomial scheduler allowance. -/
+theorem machine_bounded (hq : 0 < Q) (hfit : Q ≤ 2^ℓ)
+ (hf : ∀ (j : Fin Z) left, j.val + left < Z → Bounded frobenius.body fits
+ (fun x => bank data t Z ℓ 0 j 0 left (payload x))
+ (fun x => bank data t Z ℓ 0 j 0 left (payload x)) BF)
+ (hm : ∀ (i : Fin t) (j : Fin Z) labels cols, i.val + labels < t → j.val + cols < Z →
+ ∀ bits : List Bool, bits.length = ℓ →
+ let pre (x : S) := EvaluatorDigitRepeat.frame Port.digit Port.borrow
+ (bank data t Z ℓ i j labels cols (payload x)) bits []
+ Bounded multiply.body fits pre pre BM) :
+ Bounded (machine frobenius multiply).body fits
+ (fun x => bank data t Z ℓ 0 0 0 Z (payload x)) (fun x => bank data t Z ℓ 0 0 0 0 (payload x))
+ (budget t Z ℓ Q BF BM) := by
+ apply traverse_bounded data t Z ℓ space payload hp frobenius (cellRoutine multiply) BF (cellBudget t Z ℓ Q BM)
+ · intro j left hj
+ exact hf ⟨j, by omega⟩ left hj
+ · intro j cols hj i labels hi
+ let i' : Fin t := ⟨i, by omega⟩
+ let j' : Fin Z := ⟨j, by omega⟩
+ apply cell_bounded multiply fits payload e ℓ Q BM hq hfit i' j' labels cols _ _ (hm i' j' labels cols hi hj)
+ · intro x s hs k
+ have h₀ := bank_length data t Z ℓ space payload hp hi.le hj.le x k
+ have h₁ := hs k
+ change (s k).length ≤ (bank data t Z ℓ i j labels cols (payload x) k).length + _ at h₁
+ unfold schedulerSpace
+ omega
+ · intro x xs ys hlen k
+ have h₀ := bank_length data t Z ℓ space payload hp hi.le hj.le x k
+ by_cases hd : k = .digit
+ · subst k
+ simp only [EvaluatorDigitRepeat.frame, Function.update_self,
+ Function.update_of_ne (show (Port.digit : Port P) ≠ .borrow by intro h; cases h)]
+ unfold schedulerSpace
+ omega
+ · by_cases hb : k = .borrow
+ · subst k
+ simp only [EvaluatorDigitRepeat.frame, Function.update_self]
+ unfold schedulerSpace
+ omega
+ · simp only [EvaluatorDigitRepeat.frame, Function.update_of_ne hb, Function.update_of_ne hd]
+ exact h₀.trans (by unfold schedulerSpace; omega)
+
+/-- The bounded contract implies a physical stopping statement and the peak
+bound on all reachable stack states, even if an intermediate branch rejects. -/
+theorem machine_space_clock (outcome : Bool) (x : S)
+ (hpost : ∀ y, fits (bank data t Z ℓ 0 0 0 0 (payload y)))
+ (h : Bounded (machine frobenius multiply).body fits
+ (fun y => bank data t Z ℓ 0 0 0 Z (payload y)) (fun y => bank data t Z ℓ 0 0 0 0 (payload y))
+ (budget t Z ℓ Q BF BM)) :
+ let r := (machine frobenius multiply).body
+ let start := bank data t Z ℓ 0 0 0 Z (payload x)
+ StopsWithin (r.close outcome) (1+budget t Z ℓ Q BF BM) (some r.entry) start ∧
+ ∀ ⦃q s⦄, StackCompiler.Reach (r.close outcome) (some r.entry) start q s → fits s := by
+ have hs := h 1 (1+budget t Z ℓ Q BF BM) le_rfl x (fun n s => 0 ⟨hn, hpost y⟩)
+ exact ⟨hs.stopsWithin outcome (fun _ _ hh => hh.1), fun _ _ hr => hs.reach outcome (fun _ _ hh => hh.2) hr⟩
+
+end EvaluatorMonomialSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorMonomialSchedule.lean b/lean/OAI/Computability/VPVNP/EvaluatorMonomialSchedule.lean
new file mode 100644
index 0000000000..cb8965f593
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorMonomialSchedule.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.EvaluatorChronologicalLoop
+import OAI.Computability.VPVNP.EvaluatorDigitAction
+import OAI.Computability.VPVNP.EvaluatorScheduleEffects
+
+/-! # A fixed stack control for the monomial query schedule
+
+The only two callbacks in this control are matrix-entry steps. Every other
+instruction, from addressing the compact binary digit to advancing the row or
+column, is the same at every exponent width. The continuation effect equals
+the ordered sequence of index choices in the paper's digit program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorMonomialSchedule
+
+open RAMTape EvaluatorDigitFetch EvaluatorRoutine EvaluatorChronologicalLoop
+ EvaluatorDigitAction EvaluatorScheduleEffects EvaluatorRadixRows
+
+variable {P S I : Type} [DecidableEq P] [Fintype I]
+
+/-- Finite scheduler code parametrized solely by its two matrix-step subroutines. -/
+def machine (frobenius multiply : FiniteRoutine (Port P)) : FiniteRoutine (Port P) :=
+ traverse frobenius (cellRoutine multiply)
+
+/-- This instruction budget permits both matrix steps to use variable time
+on different index paths. -/
+def budget (t Z ℓ Q BF BM : ℕ) := traverseBudget t Z BF (cellBudget t Z ℓ Q BM)
+
+variable {t Z : ℕ} (e : Fin t → BurstRAM.Word Z) (ℓ Q BF BM : ℕ) (payload : S → Stacks P)
+ (next : Option ℕ → S → I → S) (frobenius multiply : FiniteRoutine (Port P))
+
+local notation "data" => packedTable ℓ Q (List.ofFn e)
+
+/-- The label step preserves its current binary counter while updating the
+payload by the matrix-index choice. -/
+def LabelCallback : Prop :=
+ ∀ (i : Fin t) (j : Fin Z) labelsLeft colsLeft (x : S) (bits : List Bool) fuel,
+ bits.length = ℓ → BM ≤ fuel → ∃ delay : I → ℕ, (∀ a, delay a ≤ BM) ∧ ∀ c,
+ let input (s : S) := EvaluatorDigitRepeat.frame Port.digit Port.borrow
+ (bank data t Z ℓ i.val j.val labelsLeft colsLeft (payload s)) bits []
+ multiply.body.count c fuel (input x) = ∑ a, c (fuel-delay a) (input (next (some i.val) x a))
+
+/-- With the two matrix-step semantics, the stack program realizes the
+chronological action sum at every clock covering its explicit bound. -/
+theorem machine_realizes (hq : 0 < Q) (hfit : Q ≤ 2^ℓ)
+ (hf : ∀ (j : Fin Z) colsLeft, Realizes frobenius.body
+ (fun x => bank data t Z ℓ 0 j 0 colsLeft (payload x))
+ (fun x => bank data t Z ℓ 0 j 0 colsLeft (payload x)) BF (stepEffect next none))
+ (hm : LabelCallback e ℓ Q BM payload next multiply) :
+ Realizes (machine frobenius multiply).body
+ (fun x => bank data t Z ℓ 0 0 0 Z (payload x))
+ (fun x => bank data t Z ℓ 0 0 0 0 (payload x))
+ (budget t Z ℓ Q BF BM) (schedulerEffect next e Q) := by
+ apply traverse_realizes data t Z ℓ payload frobenius (cellRoutine multiply) BF
+ (cellBudget t Z ℓ Q BM) (stepEffect next none) (cellEffect next e Q)
+ · intro j left hj
+ exact hf ⟨j, by omega⟩ left
+ · intro j cols hj i labels hi
+ let j' : Fin Z := ⟨j, by omega⟩
+ let i' : Fin t := ⟨i, by omega⟩
+ have h := cellRoutine_realizes multiply payload (next (some i)) e ℓ Q BM hq hfit
+ i' j' labels cols (hm i' j' labels cols)
+ change Realizes _ _ _ _ (repeatEffect next (some i) (digitAt Q e i'.val j'.val))
+ rw [digitAt_fin]
+ exact h
+
+end EvaluatorMonomialSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorNativeResources.lean b/lean/OAI/Computability/VPVNP/EvaluatorNativeResources.lean
new file mode 100644
index 0000000000..0b53290ada
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorNativeResources.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.EvaluatorCallbackMountSafety
+import OAI.Computability.VPVNP.EvaluatorProgramInputBounds
+
+/-! # Resource bounds for the native finite-algebra evaluator
+
+The streaming coordinate routines supply independent time and peak bounds.
+The arithmetic, digit loops and radix converter run with fixed control. The
+bounds below apply to all their paths for every input exponent width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.MatrixCallbacks
+
+open RAMTape SliceArithmetic EvaluatorRoutineSafety EvaluatorChronologicalLoop
+ EvaluatorProgramMonomial EvaluatorProgramRawInput
+open EvaluatorDigitFetch (bank)
+open EvaluatorMonomialSchedule (budget)
+
+variable {P : Type} [DecidableEq P] {p e w v t Z : ℕ} [Fact p.Prime]
+ {K : Type} [Field K] [Algebra (ZMod p) K] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (dim : BurstRAM.Word v) (extra : Stacks P)
+ (es : Fin t → BurstRAM.Word Z) (d : List Bool) (extraSpace : ℕ) (hextra : ∀ k, (extra k).length ≤ extraSpace)
+
+local notation "pay" => payload φ dim extra w
+local notation "tableBits" => EvaluatorRadixRows.packedTable d.length (TapeWord.value d) (List.ofFn es)
+local notation "space" => workspace v e w extraSpace
+local notation "ticks" => WeightedStep.ticks v e w
+
+include hextra in
+/-- The reachable-path and stopping contract for the entire converter and
+scheduler, from the two concrete streamed-entry contracts. -/
+theorem native_from_readers (he : 0 < e) (hw : Word.workingWidth p ≤ w) (hq : 2 ≤ TapeWord.value d)
+ (frobenius label : FiniteRoutine (ReadPort P)) (F L peak : ℕ)
+ (MF : Matrix (Fin dim.val) (Fin dim.val) K) (ML : Fin t → Matrix (Fin dim.val) (Fin dim.val) K)
+ (hf : ReadsEntryWithin φ dim extra frobenius w 0 F peak MF)
+ (hl : ∀ i : Fin t, ReadsEntryWithin φ dim extra label w i.val L peak (ML i)) :
+ Bounded (nativeMachine (machine frobenius) (machine label)).body
+ (stackFits (nativeSpace t Z d.length (space peak))) (EvaluatorProgramInput.initial es d ∘ pay)
+ (fun x ↦ EvaluatorProgramInput.extend Z d (bank tableBits t Z d.length 0 0 0 0 (pay x)))
+ (EvaluatorProgramInput.convertTicks t Z d.length + budget t Z d.length (TapeWord.value d) (ticks F) (ticks L)) :=
+ native_bounded es d pay (space peak) (payload_length φ dim extra extraSpace hextra peak)
+ (machine frobenius) (machine label) (ticks F) (ticks L) hq
+ (frobenius_bounded φ dim extra es d extraSpace hextra he hw frobenius F peak MF hf)
+ (label_bounded φ dim extra es d extraSpace hextra he hw label L peak ML hl)
+
+/-- A uniform bit bound for the actual advice fields over every possible
+path endpoint. The bound is independent of the exponent array. -/
+def adviceCap (fields t divisorBits payloadSpace : ℕ) := 4*t+4*divisorBits+4 + fields*(2*payloadSpace+1)
+
+include hextra in
+omit [DecidableEq P] in
+theorem advice_le (ps : List (WeightedStep.Port P)) (s : Fin dim.val × K) :
+ (advice ps t d (pay s)).length ≤ adviceCap ps.length t d.length (WeightedStep.bankSpace v e w extraSpace) := by
+ have hlen := WeightedStep.bank_length (w := w) φ extra dim extraSpace hextra s.1 [] [] (by simp) (by simp) s.2
+ rw [advice_length]
+ unfold adviceCap
+ apply Nat.add_le_add_left
+ induction ps with
+ | nil => simp
+ | cons k ks ih =>
+ simp only [List.map_cons, List.sum_cons, List.length_cons]
+ conv_rhs => rw [Nat.succ_mul]
+ have hk := hlen k
+ change (pay s k).length ≤ _ at hk
+ omega
+
+/-- The deterministic preparation and field multiplication add a polynomial
+term to each matrix query's clock. -/
+theorem localTicks_polynomial {v e w : ℕ → ℕ} (hv : PolynomiallyBounded v)
+ (he : PolynomiallyBounded e) (hw : PolynomiallyBounded w) :
+ PolynomiallyBounded fun n ↦ WeightedStep.localTicks (v n) (e n) (w n) := by
+ have hmul := (((PolynomiallyBounded.const 2000).mul ((he.add (.const 1)).pow 2)).mul
+ ((hw.add (.const 1)).pow 2)).of_le (fun n ↦ MultiplyCall.callCap_le (e n) (w n))
+ exact (((((PolynomiallyBounded.const 10).mul hv).add (.const 5)).add hmul).add
+ (((PolynomiallyBounded.const 5).mul hv).add (.const 3)))
+
+theorem workspace_polynomial {v e w h peak : ℕ → ℕ} (hv : PolynomiallyBounded v)
+ (he : PolynomiallyBounded e) (hw : PolynomiallyBounded w)
+ (hh : PolynomiallyBounded h) (hp : PolynomiallyBounded peak) :
+ PolynomiallyBounded fun n ↦ workspace (v n) (e n) (w n) (h n) (peak n) :=
+ ((((((hv.add he).add hw).add (he.mul hw)).add hh).add (localTicks_polynomial hv he hw)).add hp)
+
+theorem adviceCap_polynomial (fields : ℕ) {t ℓ footprint : ℕ → ℕ}
+ (ht : PolynomiallyBounded t) (hd : PolynomiallyBounded ℓ) (hf : PolynomiallyBounded footprint) :
+ PolynomiallyBounded fun n ↦ adviceCap fields (t n) (ℓ n) (footprint n) :=
+ ((((PolynomiallyBounded.const 4).mul ht).add ((PolynomiallyBounded.const 4).mul hd)).add (.const 4)).add
+ ((PolynomiallyBounded.const fields).mul (((PolynomiallyBounded.const 2).mul hf).add (.const 1)))
+
+end Evaluator.MatrixCallbacks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorOutput.lean b/lean/OAI/Computability/VPVNP/EvaluatorOutput.lean
new file mode 100644
index 0000000000..4811030a65
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorOutput.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.EvaluatorIndexChoice
+import OAI.Computability.VPVNP.EvaluatorSafetyTransfer
+import OAI.Computability.VPVNP.SliceArithmeticWord
+
+/-!
+# Reading the unit coordinate and branching on the final residue
+
+The basis list of Lemma 8.2 starts at the unit, with ordinal zero. A path
+ending elsewhere rejects. At ordinal zero the machine reads only the first
+limb of the accumulated field product. The width stack supplies the number
+of bits to read, so higher polynomial-basis coefficients never enter the
+residue comparison.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.Output
+
+open RAMTape
+
+/-- The basis ordinal, limb-width tally and accumulated field product read by the terminal
+residue test. -/
+inductive Port where
+ | index | width | product
+ deriving DecidableEq
+
+instance : Fintype Port := ⟨{.index, .width, .product}, fun j ↦ by cases j <;> simp⟩
+
+/-- Control for testing the unit ordinal and comparing successive guessed bits with the low
+limb of the accumulated product. -/
+inductive Phase where
+ | endpoint
+ | width (less : Bool)
+ | limb (less : Bool)
+ | choose (less bit : Bool)
+ | halt (accept : Bool)
+ deriving DecidableEq, Fintype
+
+private def compareBit (less x y : Bool) : Bool := if x = y then less else y
+
+/-- The bound comparison runs from low to high bits. On exhaustion the two
+possible branch targets already encode the comparison of the whole word. -/
+def routine : Routine Port Phase where
+ entry := .endpoint
+ code
+ | .endpoint => .pop .index fun b ↦ some (match b with
+ | none => .width false | some false => .endpoint | some true => .halt false)
+ | .width less => .pop .width fun b ↦ some (if b.isSome then .limb less else .halt less)
+ | .limb less => .pop .product fun b ↦ some (b.elim (.halt false) (.choose less))
+ | .choose less b => .choose (some (.width (compareBit less false b)))
+ (some (.width (compareBit less true b)))
+ | .halt accept => .halt accept
+
+/-- The named stacks used by the terminal reader. All other stacks of the
+whole evaluator can be framed around this routine. -/
+def bank (idx width product : List Bool) : Stacks Port
+ | .index => idx | .width => width | .product => product
+
+private theorem update_idx (idx ws prod idx' : List Bool) :
+ Function.update (bank idx ws prod) .index idx' = bank idx' ws prod := by funext k; cases k <;> rfl
+
+private theorem update_width (idx ws prod ws' : List Bool) :
+ Function.update (bank idx ws prod) .width ws' = bank idx ws' prod := by funext k; cases k <;> rfl
+
+private theorem update_prod (idx ws prod prod' : List Bool) :
+ Function.update (bank idx ws prod) .product prod' = bank idx ws prod' := by funext k; cases k <;> rfl
+
+private theorem count_width (bits tail idx : List Bool) (fuel : ℕ) (less : Bool)
+ (c : ℕ → Stacks Port → ℕ) :
+ routine.countFrom c (fuel+(3*bits.length+2)) (some (.width less))
+ (bank idx (List.replicate bits.length true) (bits ++ tail)) =
+ TapeWord.value bits + less.toNat := by
+ induction bits generalizing less with
+ | nil => simp [Routine.countFrom, routine, bank, TapeWord.value]
+ | cons b bits ih =>
+ have step (r : ℕ) :
+ routine.countFrom c (r+3) (some (.width less))
+ (bank idx (true::List.replicate bits.length true) (b::bits ++ tail)) =
+ routine.countFrom c r (some (.width (compareBit less false b)))
+ (bank idx (List.replicate bits.length true) (bits ++ tail)) +
+ routine.countFrom c r (some (.width (compareBit less true b)))
+ (bank idx (List.replicate bits.length true) (bits ++ tail)) := by
+ simp only [Routine.countFrom, routine, bank, List.head?_cons, List.tail_cons, List.cons_append,
+ Option.isSome_some, ite_true, update_width, Option.elim_some, update_prod]
+ rw [show fuel+(3*(b::bits).length+2) = (fuel+(3*bits.length+2))+3 by simp; omega,
+ List.length_cons, List.replicate_succ, step, ih, ih]
+ cases less <;> cases b <;> simp [compareBit, TapeWord.value] <;> omega
+
+/-- With a correct endpoint the continuation is never entered: every accepted
+guess halts directly. The result is the ordinary natural value of the low limb. -/
+theorem count_output (idx bits tail : List Bool) (fuel : ℕ) (c : ℕ → Stacks Port → ℕ) :
+ routine.count c (fuel + (3*bits.length+3) + idx.length)
+ (bank idx (List.replicate bits.length true) (bits ++ tail)) =
+ if TapeWord.value idx = 0 then TapeWord.value bits else 0 := by
+ induction idx with
+ | nil =>
+ rw [show fuel + (3*bits.length+3) + [].length = (fuel+(3*bits.length+2))+1 by simp; omega]
+ change routine.countFrom c _ (some .endpoint) _ = _
+ rw [Routine.countFrom]
+ simp only [routine, bank, List.head?_nil, List.tail_nil, update_idx, TapeWord.value, ite_true]
+ exact (count_width bits tail [] fuel false c).trans (by simp)
+ | cons b idx ih =>
+ rw [List.length_cons, Nat.add_succ]
+ change routine.countFrom c _ (some .endpoint) _ = _
+ rw [Routine.countFrom]
+ cases b with
+ | false => simpa only [routine, bank, List.head?_cons, List.tail_cons, update_idx, TapeWord.value,
+ Bool.toNat_false, zero_add, Nat.mul_eq_zero, OfNat.ofNat_ne_zero, false_or] using ih
+ | true =>
+ rw [show fuel + (3*bits.length+3) + idx.length = (fuel + (3*bits.length+2) + idx.length)+1 by omega]
+ simp [routine, bank, Routine.countFrom, TapeWord.value]
+
+/-- Applied to the field representation, the terminal machine counts the
+low prime-field coefficient if and only if the final ordinal is zero. -/
+theorem count_output_limb {p w v : ℕ} [NeZero p] (hw : SliceArithmetic.Word.workingWidth p ≤ w)
+ (i : BurstRAM.Word v) (r : Fin p) (tail : List Bool) (fuel : ℕ) (c : ℕ → Stacks Port → ℕ) :
+ routine.count c (fuel + (3*w+3) + v)
+ (bank (BurstRAM.wordBits i) (List.replicate w true)
+ (BurstRAM.wordBits (SliceArithmetic.Word.limb w r) ++ tail)) =
+ if i.val = 0 then r.val else 0 := by
+ simpa only [BurstRAM.length_wordBits, TapeWord.value_wordBits, SliceArithmetic.Word.limb_val hw] using
+ count_output (BurstRAM.wordBits i) (BurstRAM.wordBits (SliceArithmetic.Word.limb w r)) tail fuel c
+
+private theorem allStops_width (ws prod idx : List Bool) (less : Bool) (cont : ℕ → Stacks Port → Prop) :
+ routine.AllStopsFrom cont (3*ws.length+2) (some (.width less)) (bank idx ws prod) := by
+ induction ws generalizing less prod with
+ | nil => simp [Routine.AllStopsFrom, routine, bank]
+ | cons w ws ih =>
+ rw [show 3*(w::ws).length+2 = (3*ws.length+2)+3 by simp; omega]
+ cases prod with
+ | nil =>
+ have reject (n : ℕ) : routine.AllStopsFrom cont (n+3) (some (.width less)) (bank idx (w::ws) []) := by
+ simp [Routine.AllStopsFrom, routine, bank]
+ exact reject _
+ | cons b prod =>
+ have step (n : ℕ) : routine.AllStopsFrom cont (n+3) (some (.width less)) (bank idx (w::ws) (b::prod)) ↔
+ routine.AllStopsFrom cont n (some (.width (compareBit less false b))) (bank idx ws prod) ∧
+ routine.AllStopsFrom cont n (some (.width (compareBit less true b))) (bank idx ws prod) := by
+ simp only [Routine.AllStopsFrom, routine, bank, List.head?_cons, List.tail_cons,
+ Option.isSome_some, ite_true, update_width, Option.elim_some, update_prod]
+ exact (step _).mpr ⟨ih _ _, ih _ _⟩
+
+/-- Every terminal branch halts within its linear clock. The endpoint and low
+limb tests only consume their inputs, including on a rejecting branch. -/
+theorem allStops_output (idx ws prod : List Bool) (cont : ℕ → Stacks Port → Prop) :
+ routine.AllStops cont (3*ws.length+3+idx.length) (bank idx ws prod) := by
+ induction idx with
+ | nil =>
+ rw [show 3*ws.length+3+[].length = (3*ws.length+2)+1 by simp]
+ change routine.AllStopsFrom cont _ (some .endpoint) _
+ rw [Routine.AllStopsFrom]
+ simp only [routine, bank, List.head?_nil, List.tail_nil, update_idx]
+ exact allStops_width ws prod [] false cont
+ | cons b idx ih =>
+ rw [List.length_cons, Nat.add_succ]
+ change routine.AllStopsFrom cont _ (some .endpoint) _
+ rw [Routine.AllStopsFrom]
+ cases b with
+ | false => simpa only [routine, bank, List.head?_cons, List.tail_cons, update_idx] using ih
+ | true =>
+ rw [show 3*ws.length+3+idx.length = (3*ws.length+2+idx.length)+1 by omega]
+ simp [Routine.AllStopsFrom, routine, bank]
+
+end Evaluator.Output
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorPhysicalBounds.lean b/lean/OAI/Computability/VPVNP/EvaluatorPhysicalBounds.lean
new file mode 100644
index 0000000000..c8cf7cab8d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorPhysicalBounds.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.EvaluatorBinarySafety
+import OAI.Computability.VPVNP.EvaluatorProgramInputBounds
+
+/-!
+# Literal tape clock and storage envelope of the evaluator
+
+Compilation of the fixed stack bank costs quadratic time. Its simulated input
+length is linear in the exponent width. The resulting exponent of the width
+is a fixed four, independent of the advised matrices and their query times.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.BinaryMachine
+
+open EvaluatorProgramMonomial EvaluatorProgramRawInput
+
+/-- Physical clock sufficient for all stack instructions on the named bank. -/
+def tapeTicks (rawLength ports stackTicks : ℕ) :=
+ stackTicks*(6*(rawLength+(ports+1)+stackTicks)+4)
+
+/-- A per-stack height bounds the packed bank, including its delimiter cells. -/
+def packedCap (ports height : ℕ) := ports+1 + ports*height
+
+/-- Two heads may move to either side of their initial position. -/
+def headRadius (ports height : ℕ) := 7*packedCap ports height+4
+
+/-- Uniform in the exponent width. All other parameters, including the two
+coordinate-call clocks, admit the indicated singly exponential bound. -/
+theorem tapeTicks_le_exp_poly (t Z ℓ Q A BF BM v w ports raw a : ℕ)
+ (ha : A ≤ 2^a) (ht : t ≤ 2^a) (hℓ : ℓ ≤ 2^a) (hQ : Q ≤ 2^a)
+ (hf : BF ≤ 2^a) (hm : BM ≤ 2^a) (hend : terminalTicks v w ≤ 2^a)
+ (hp : ports+1 ≤ 2^a) (hr : raw ≤ A+(2*(t*Z)+6*Z+4)) :
+ tapeTicks raw ports (fullTicks t Z ℓ Q A BF BM v w) ≤ 2^(6*a+23)*(Z+1)^4 := by
+ let R := 2^(3*a+9)*(Z+1)^2
+ let T := fullTicks t Z ℓ Q A BF BM v w
+ have hR : 0 < R := Nat.mul_pos (Nat.two_pow_pos _) (Nat.pow_pos (Nat.succ_pos _))
+ have hz : 1 ≤ (Z+1)^2 := Nat.pow_pos (Nat.succ_pos _)
+ have he : 2^a ≤ 2^(3*a+8)*(Z+1)^2 :=
+ (Nat.pow_le_pow_right (by decide) (by omega : a ≤ 3*a+8)).trans (Nat.le_mul_of_pos_right _ hz)
+ have htick : T ≤ R := fullTicks_le_exp_poly t Z ℓ Q A BF BM v w a 0 ha ht hℓ hQ
+ (by simpa using hm) (by simpa using hf) (by unfold terminalTicks at hend; omega)
+ (by unfold terminalTicks at hend; omega)
+ have hE : 1 ≤ 2^a := Nat.two_pow_pos _
+ have hEZ : Z ≤ 2^a*Z := by simpa using Nat.mul_le_mul_right Z hE
+ have hTZ := Nat.mul_le_mul_right Z ht
+ have hr' : raw ≤ 13*2^a*(Z+1) := by rw [Nat.mul_succ, Nat.mul_assoc]; omega
+ have hr₁ : 13*2^a ≤ 2^(3*a+9) := calc
+ _ ≤ 512*2^(3*a) := Nat.mul_le_mul (by decide) (Nat.pow_le_pow_right (by decide) (by omega))
+ _ = _ := by rw [pow_add, Nat.mul_comm]; rfl
+ have hraw : raw ≤ R := hr'.trans (Nat.mul_le_mul hr₁ (by nlinarith))
+ have hports : ports+1 ≤ R := hp.trans (he.trans (Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (by omega))))
+ have hmacro : 6*(raw+(ports+1)+T)+4 ≤ 32*R := by omega
+ calc
+ tapeTicks raw ports T ≤ R*(32*R) := Nat.mul_le_mul htick hmacro
+ _ = 2^(6*a+23)*(Z+1)^4 := by
+ unfold R
+ rw [show 6*a+23 = ((3*a+9)+(3*a+9))+5 by omega, pow_add, pow_add]
+ ring
+
+/-- Uniform polynomial storage, including the head window of the literal
+machine. All coordinate reader storage is accounted for in workspace. -/
+theorem headRadius_le (t Z ℓ space A v w ports : ℕ) :
+ headRadius ports (fullSpace t Z ℓ space A v w) ≤
+ 1110*(ports+1)*(t+Z+ℓ+space+A+v+w+1)^4 := by
+ let n := t+Z+ℓ+space+A+v+w+1
+ have hn : 1 ≤ n := by dsimp [n]; omega
+ have hheight := fullSpace_le_power t Z ℓ space A v w
+ change fullSpace t Z ℓ space A v w ≤ 157*n^4 at hheight
+ have hp := Nat.mul_le_mul_left ports hheight
+ have hnpos := Nat.pow_pos hn (n := 4)
+ unfold headRadius packedCap
+ change 7*(ports+1+ports*fullSpace t Z ℓ space A v w)+4 ≤ 1110*(ports+1)*n^4
+ have hnports := Nat.le_mul_of_pos_right ports hnpos
+ nlinarith
+
+end Evaluator.BinaryMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorProgramInput.lean b/lean/OAI/Computability/VPVNP/EvaluatorProgramInput.lean
new file mode 100644
index 0000000000..e4a34ea965
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorProgramInput.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.EvaluatorDigitFetch
+import OAI.Computability.VPVNP.EvaluatorRadixRows
+import OAI.Computability.VPVNP.EvaluatorRoutine
+import OAI.Computability.VPVNP.EvaluatorRoutineFrame
+
+/-!
+# Native input conversion and the finite-algebra evaluator
+
+The row converter receives the binary exponent array in its native ascending,
+little-endian order. Its digit output is the scheduler's table stack. This
+allows traversal to start directly at column zero while preserving the
+divisor, the unary width, and the callback's state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorProgramInput
+
+open RAMTape EvaluatorRoutine
+
+/-- The packed binary input and its size counters, the division registers and the digit
+scheduler's ports. -/
+inductive Port (P : Type) where
+ | input | width | rowCount | rounds
+ | word (k : TapeWord.DivisionStack.Port)
+ | sched (k : EvaluatorDigitFetch.Port P)
+ deriving DecidableEq, Fintype
+
+variable {P : Type}
+
+/-- The radix converter writes its output directly onto the scheduler table. -/
+def radixPort : EvaluatorRadixRows.Port → Port P
+ | .input => .input
+ | .width => .width
+ | .rowCount => .rowCount
+ | .radix .rounds => .rounds
+ | .radix (.word k) => .word k
+ | .radix .digits => .sched .table
+
+private theorem radixPort_injective : Function.Injective (radixPort (P := P)) := by
+ let back : Port P → EvaluatorRadixRows.Port
+ | .input => .input
+ | .width => .width
+ | .rowCount => .rowCount
+ | .rounds => .radix .rounds
+ | .word k => .radix (.word k)
+ | .sched _ => .radix .digits
+ apply Function.LeftInverse.injective (f := radixPort) (g := back)
+ intro k
+ cases k with
+ | radix k => cases k <;> rfl
+ | _ => rfl
+
+/-- Framing a scheduler bank retains the original divisor and row width.
+All private conversion scratch is empty. -/
+def extend (Z : ℕ) (d : List Bool) (s : Stacks (EvaluatorDigitFetch.Port P)) : Stacks (Port P)
+ | .width => List.replicate Z true
+ | .word .divisor => d
+ | .sched k => s k
+ | _ => []
+
+variable {t Z : ℕ}
+
+/-- Place the binary exponent vector and dimensions on the input stacks. The
+callback payload can contain its advice and its initial arithmetic registers. -/
+def initial (e : Fin t → BurstRAM.Word Z) (d : List Bool) (payload : Stacks P) : Stacks (Port P)
+ | .rowCount => List.replicate t true
+ | .word .original => List.ofFn (RAMSerialization.arrayBits t Z e)
+ | k => extend Z d (EvaluatorDigitFetch.bank [] t Z d.length 0 0 0 Z payload) k
+
+/-- The conversion code is independent of both runtime dimensions and the divisor. -/
+def convert : FiniteRoutine (Port P) := EvaluatorRadixRows.nativeRows.onPorts radixPort
+
+/-- Instruction count for moving the binary exponent array to the converter and running its
+radix-row routine. -/
+def convertTicks (t Z ℓ : ℕ) := 2*(t*Z) + 1 + EvaluatorRadixRows.rowsTicks t Z ℓ
+
+/-- The packed table and the initial loop counters reach the scheduler together. -/
+theorem convert_runs [DecidableEq P] (e : Fin t → BurstRAM.Word Z) (d : List Bool)
+ (payload : Stacks P) (hq : 2 ≤ TapeWord.value d) :
+ convert.Runs (convertTicks t Z d.length) (initial e d payload)
+ (extend Z d (EvaluatorDigitFetch.bank
+ (EvaluatorRadixRows.packedTable d.length (TapeWord.value d) (List.ofFn e))
+ t Z d.length 0 0 0 Z payload)) := by
+ apply EvaluatorRadixRows.nativeRows.runs_onPorts_framed radixPort_injective
+ (EvaluatorRadixRows.native_array_runs e [] d [] hq)
+ · intro k
+ cases k with
+ | radix k => cases k with
+ | word k => cases k <;> rfl
+ | rounds | digits => rfl
+ | _ => rfl
+ · intro k
+ cases k with
+ | radix k => cases k with
+ | word k => cases k <;> rfl
+ | rounds => rfl
+ | digits => simp only [List.append_nil]; rfl
+ | _ => rfl
+ · intro k hk
+ cases k with
+ | sched k => cases k with
+ | table => exact (hk (.radix .digits) rfl).elim
+ | _ => rfl
+ | word k => exact (hk (.radix (.word k)) rfl).elim
+ | rowCount => exact (hk .rowCount rfl).elim
+ | _ => rfl
+
+/-- Run a scheduler from the native exponent input. The state space of the
+linked routine depends only on the fixed converter and scheduler programs. -/
+def run (scheduler : FiniteRoutine (EvaluatorDigitFetch.Port P)) : FiniteRoutine (Port P) :=
+ convert.followedBy (scheduler.onPorts .sched)
+
+private theorem realizes_sched [DecidableEq P] {S T : Type*}
+ (scheduler : FiniteRoutine (EvaluatorDigitFetch.Port P))
+ (Z : ℕ) (d : List Bool) {pre : S → Stacks (EvaluatorDigitFetch.Port P)}
+ {post : T → Stacks (EvaluatorDigitFetch.Port P)} {B : ℕ}
+ {effect : (T → ℕ) → S → ℕ} (h : Realizes scheduler.body pre post B effect) :
+ Realizes (scheduler.onPorts Port.sched).body (extend Z d ∘ pre) (extend Z d ∘ post) B effect := by
+ intro extra fuel hf x f c hc
+ have hp : Function.Injective (Port.sched (P := P)) := fun _ _ h => Port.sched.inj h
+ rw [scheduler.count_onPorts _ hp]
+ apply h extra fuel hf x f
+ intro y n hn
+ have he : installStacks Port.sched ((extend Z d ∘ pre) x) (post y) = (extend Z d ∘ post) y := by
+ apply installStacks_frame (small := post y) (target := (extend Z d ∘ post) y) hp (fun _ => rfl)
+ intro k hk
+ cases k with
+ | sched k => exact (hk k rfl).elim
+ | word k => cases k <;> rfl
+ | _ => rfl
+ rw [he]
+ exact hc y n hn
+
+/-- Any proved scheduler semantics now applies to the ascending binary input
+array, with the exact verified radix conversion time added to the clock. -/
+theorem run_realizes [DecidableEq P] {S T : Type*}
+ (scheduler : FiniteRoutine (EvaluatorDigitFetch.Port P)) (e : Fin t → BurstRAM.Word Z)
+ (d : List Bool) (hq : 2 ≤ TapeWord.value d) (payload : S → Stacks P)
+ {post : T → Stacks (EvaluatorDigitFetch.Port P)} {B : ℕ} {effect : (T → ℕ) → S → ℕ}
+ (h : Realizes scheduler.body
+ (fun x => EvaluatorDigitFetch.bank
+ (EvaluatorRadixRows.packedTable d.length (TapeWord.value d) (List.ofFn e))
+ t Z d.length 0 0 0 Z (payload x)) post B effect) :
+ Realizes (run scheduler).body (initial e d ∘ payload) (extend Z d ∘ post)
+ (convertTicks t Z d.length + B) effect := by
+ let pre (x : S) := EvaluatorDigitFetch.bank
+ (EvaluatorRadixRows.packedTable d.length (TapeWord.value d) (List.ofFn e))
+ t Z d.length 0 0 0 Z (payload x)
+ have prefixRun : Realizes convert.body (initial e d ∘ payload) (extend Z d ∘ pre)
+ (convertTicks t Z d.length) (fun f x => f x) := by
+ apply Realizes.of_runs (g := id)
+ intro x
+ exact ⟨_, le_rfl, convert_runs e d (payload x) hq⟩
+ exact prefixRun.followedBy (realizes_sched scheduler Z d h)
+
+end EvaluatorProgramInput
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorProgramInputBounds.lean b/lean/OAI/Computability/VPVNP/EvaluatorProgramInputBounds.lean
new file mode 100644
index 0000000000..5fb82da068
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorProgramInputBounds.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.EvaluatorProgramRawSafety
+import OAI.Computability.VPVNP.EvaluatorScheduleBudget
+import OAI.Computability.VPVNP.PolynomialBounds
+
+/-!
+# Advice and clock bounds for the evaluator with its input parser
+
+A fixed list of polynomial-length callback registers gives polynomial advice
+for the whole program. The parser reads a runtime stream linear in the number
+of exponent bits. Its cost fits the same exponential-in-length,
+polynomial-in-exponent-width clock as conversion and traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorProgramRawInput
+
+open RAMTape
+
+variable {P : Type}
+
+theorem advice_polynomiallyBounded (ps : List P) (t : ℕ → ℕ) (d : ℕ → List Bool)
+ (payload : ℕ → Stacks P) (ht : PolynomiallyBounded t)
+ (hd : PolynomiallyBounded fun n => (d n).length)
+ (hp : ∀ p, PolynomiallyBounded fun n => (payload n p).length) :
+ PolynomiallyBounded fun n => (advice ps (t n) (d n) (payload n)).length := by
+ have fieldsBound (ks : List P) :
+ PolynomiallyBounded fun n => (ks.map fun p => 2*(payload n p).length+1).sum := by
+ induction ks with
+ | nil => exact .const 0
+ | cons p ks ih =>
+ simpa only [List.map_cons, List.sum_cons] using
+ ((((PolynomiallyBounded.const 2).mul (hp p)).add (.const 1)).add ih)
+ simpa only [advice_length] using
+ ((((PolynomiallyBounded.const 4).mul ht).add ((PolynomiallyBounded.const 4).mul hd)).add
+ (.const 4)).add (fieldsBound ps)
+
+/-- Add the parser clock to the full machine allowance. The exponent-array
+width changes only the polynomial factor, and the bound is uniform over
+binary inputs of that width and the index path. -/
+theorem parser_budget_le_exp_poly (t Z ℓ Q A BF BM a k : ℕ)
+ (ha : A ≤ 2^a) (ht : t ≤ 2^a) (hℓ : ℓ ≤ 2^a) (hQ : Q ≤ 2^a)
+ (hM : BM ≤ 2^a*(Z+1)^k) (hF : BF ≤ 2^a*(Z+1)^k) :
+ EvaluatorProgramMonomial.readerBudget t Z A + (EvaluatorProgramInput.convertTicks t Z ℓ +
+ EvaluatorMonomialSchedule.budget t Z ℓ Q BF BM) ≤ 2^(3*a+8)*(Z+1)^(k+2) := by
+ have hs := EvaluatorScheduleBudget.scheduleBudget_le_exp_poly t Z ℓ Q BM BF a k ht hℓ hQ hM hF
+ change EvaluatorProgramInput.convertTicks t Z ℓ + EvaluatorMonomialSchedule.budget t Z ℓ Q BF BM ≤ _ at hs
+ let E := 2^a
+ have hE : 1 ≤ E := Nat.two_pow_pos a
+ have htz : t*Z ≤ E*Z := Nat.mul_le_mul_right _ ht
+ have hz : Z ≤ E*Z := by simpa only [Nat.one_mul] using Nat.mul_le_mul_right Z hE
+ have hr' : EvaluatorProgramMonomial.readerBudget t Z A ≤ 20*E*(Z+1) := by
+ change A ≤ E at ha
+ unfold EvaluatorProgramMonomial.readerBudget EvaluatorProgramMonomial.inputLengthBound
+ rw [Nat.mul_succ, Nat.mul_assoc]
+ omega
+ have hcoef : 20*E ≤ 2^(3*a+7) := by
+ calc
+ 20*E ≤ 128*2^(3*a) := Nat.mul_le_mul (by decide) (Nat.pow_le_pow_right (by decide) (by omega))
+ _ = _ := by rw [pow_add, Nat.mul_comm]; rfl
+ have hpow : Z+1 ≤ (Z+1)^(k+2) := by
+ simpa only [pow_one] using Nat.pow_le_pow_right (Nat.succ_pos Z) (show 1 ≤ k+2 by omega)
+ have hread := hr'.trans (Nat.mul_le_mul hcoef hpow)
+ rw [show 3*a+8 = (3*a+7)+1 by omega, pow_succ]
+ calc
+ _ ≤ 2^(3*a+7)*(Z+1)^(k+2) + 2^(3*a+7)*(Z+1)^(k+2) := Nat.add_le_add hread hs
+ _ = _ := by ring
+
+/-- The exact reader cost on a given input is bounded by the same clock. -/
+theorem parser_schedule_le_exp_poly {t Z a k BF BM : ℕ} (ps : List P)
+ (e : Fin t → BurstRAM.Word Z) (d : List Bool) (payload : Stacks P)
+ (ha : (advice ps t d payload).length ≤ 2^a)
+ (ht : t ≤ 2^a) (hℓ : d.length ≤ 2^a) (hQ : TapeWord.value d ≤ 2^a)
+ (hM : BM ≤ 2^a*(Z+1)^k) (hF : BF ≤ 2^a*(Z+1)^k) :
+ readTicks ps e d payload + (EvaluatorProgramInput.convertTicks t Z d.length +
+ EvaluatorMonomialSchedule.budget t Z d.length (TapeWord.value d) BF BM) ≤
+ 2^(3*a+8)*(Z+1)^(k+2) := by
+ have hr := readTicks_le ps e d payload
+ rw [runtime_length] at hr
+ exact (Nat.add_le_add_right hr _).trans (parser_budget_le_exp_poly _ _ _ _ _ _ _ _ _ ha ht hℓ hQ hM hF)
+
+end EvaluatorProgramRawInput
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorProgramMonomial.lean b/lean/OAI/Computability/VPVNP/EvaluatorProgramMonomial.lean
new file mode 100644
index 0000000000..6bcafce060
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorProgramMonomial.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.EvaluatorMonomialSchedule
+import OAI.Computability.VPVNP.EvaluatorProgramRawInput
+
+/-!
+# The monomial scheduler on binary advice and exponents
+
+Loading the self-delimiting fields, converting the native binary exponents
+to radix digits, and traversing those digits are fixed controls. This links
+their semantics to the chronological matrix-choice effect on the input
+exponents. The callback specifications concern the two matrix steps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorProgramMonomial
+
+open RAMTape EvaluatorRoutine EvaluatorDigitFetch EvaluatorScheduleEffects
+ EvaluatorMonomialSchedule EvaluatorRadixRows EvaluatorProgramRawInput
+
+variable {P S I : Type} [DecidableEq P] [Fintype I] {t Z : ℕ}
+
+/-- The radix converter followed by the monomial scheduler with the supplied Frobenius and
+label-multiplication callbacks. -/
+def nativeMachine (frobenius multiply : FiniteRoutine (Port P)) :=
+ EvaluatorProgramInput.run (machine frobenius multiply)
+
+/-- The complete monomial routine that loads the tagged raw input before executing the
+converter and the two scheduled callbacks. -/
+def rawMachine (ps : List P) (frobenius multiply : FiniteRoutine (Port P)) :=
+ withReader ps (nativeMachine frobenius multiply)
+
+variable (e : Fin t → BurstRAM.Word Z) (d : List Bool) (payload : S → Stacks P)
+ (next : Option ℕ → S → I → S) (frobenius multiply : FiniteRoutine (Port P))
+ (BF BM : ℕ)
+
+local notation "data" => packedTable d.length (TapeWord.value d) (List.ofFn e)
+local notation "post" => fun x => EvaluatorProgramInput.extend Z d
+ (bank data t Z d.length 0 0 0 0 (payload x))
+local notation "ticks" => EvaluatorProgramInput.convertTicks t Z d.length +
+ budget t Z d.length (TapeWord.value d) BF BM
+
+/-- The native little-endian exponent array reaches the chronological
+Frobenius and label action sum. Its exact conversion time precedes the
+scheduler's per-path budget. -/
+theorem native_realizes (hq : 2 ≤ TapeWord.value d)
+ (hf : ∀ (j : Fin Z) left, Realizes frobenius.body
+ (fun x => bank data t Z d.length 0 j 0 left (payload x))
+ (fun x => bank data t Z d.length 0 j 0 left (payload x)) BF (stepEffect next none))
+ (hm : LabelCallback e d.length (TapeWord.value d) BM payload next multiply) :
+ Realizes (nativeMachine frobenius multiply).body (EvaluatorProgramInput.initial e d ∘ payload)
+ post ticks (schedulerEffect next e (TapeWord.value d)) :=
+ EvaluatorProgramInput.run_realizes _ e d hq payload
+ (machine_realizes e d.length (TapeWord.value d) BF BM payload next frobenius multiply
+ (by omega) (TapeWord.value_lt d).le hf hm)
+
+/-- The whole parser, radix converter, and scheduler start with just the
+single advice-and-exponent stream on the input stack. -/
+theorem raw_realizes (ps : List P) (hp : ps.Nodup) (hall : ∀ p, p ∈ ps)
+ (R : ℕ) (hR : ∀ x, readTicks ps e d (payload x) ≤ R) (hq : 2 ≤ TapeWord.value d)
+ (hf : ∀ (j : Fin Z) left, Realizes frobenius.body
+ (fun x => bank data t Z d.length 0 j 0 left (payload x))
+ (fun x => bank data t Z d.length 0 j 0 left (payload x)) BF (stepEffect next none))
+ (hm : LabelCallback e d.length (TapeWord.value d) BM payload next multiply) :
+ Realizes (rawMachine ps frobenius multiply).body
+ (fun x => Evaluator.InputBank.frame (advice ps t d (payload x) ++ runtime e) (fun _ => []))
+ (Evaluator.InputBank.frame [] ∘ (post)) (R + (ticks)) (schedulerEffect next e (TapeWord.value d)) :=
+ withReader_realizes ps hp hall e d payload _ hR
+ (native_realizes e d payload next frobenius multiply BF BM hq hf hm)
+
+end EvaluatorProgramMonomial
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorProgramRawInput.lean b/lean/OAI/Computability/VPVNP/EvaluatorProgramRawInput.lean
new file mode 100644
index 0000000000..3e1edc3b8a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorProgramRawInput.lean
@@ -0,0 +1,166 @@
+import OAI.Computability.VPVNP.EvaluatorProgramInput
+import OAI.Computability.VPVNP.EvaluatorInputBank
+
+/-!
+# Advice and exponent fields on a single binary input
+
+The parser loads four header fields and the callback payload from the advice
+prefix. The suffix carries the runtime exponent vector and three copies of
+its unary width for the converter and the two scheduler counters. Scratch
+ports start empty without consuming any input.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorProgramRawInput
+
+open RAMTape EvaluatorRoutine EvaluatorProgramInput Evaluator.InputBank
+
+variable {P : Type}
+
+private def header : List (Port P) :=
+ [.rowCount, .word .divisor, .sched (.addr .width), .sched .labels]
+
+private def runtimePorts : List (Port P) :=
+ [.width, .word .original, .sched (.addr .rounds), .sched .colsLeft]
+
+private def workPort (p : P) : Port P := .sched (.work p)
+
+/-- The parser's ordered ports depend only on the fixed callback register list. -/
+def fields (ps : List P) := (header ++ ps.map workPort) ++ runtimePorts
+
+private theorem fields_nodup {ps : List P} (hp : ps.Nodup) : (fields ps).Nodup := by
+ have hinj : Function.Injective (workPort (P := P)) := fun _ _ h =>
+ EvaluatorDigitFetch.Port.work.inj (Port.sched.inj h)
+ rw [fields, List.nodup_append', List.nodup_append']
+ refine ⟨⟨by simp [header], hp.map hinj, ?_⟩, by simp [runtimePorts], ?_⟩
+ · intro k hk h
+ obtain ⟨p, _, rfl⟩ := List.mem_map.mp h
+ simp [header, workPort] at hk
+ · intro k hk h
+ rcases List.mem_append.mp hk with ha | hw
+ · simp [header] at ha
+ rcases ha with rfl | rfl | rfl | rfl <;> simp [runtimePorts] at h
+ · obtain ⟨p, _, rfl⟩ := List.mem_map.mp hw
+ simp [runtimePorts, workPort] at h
+
+/-- Advice contains the fixed binary divisor, the dimensions which depend
+on the label system, and the specified callback registers. -/
+def advice (ps : List P) (t : ℕ) (d : List Bool) (payload : Stacks P) : List Bool :=
+ fieldBits (List.replicate t true) ++ fieldBits d ++ fieldBits (List.replicate d.length true) ++
+ fieldBits (List.replicate t true) ++ ps.flatMap (fun k => fieldBits (payload k))
+
+/-- The runtime input depends only on the width and the native exponent array. -/
+def runtime {t Z : ℕ} (e : Fin t → BurstRAM.Word Z) : List Bool :=
+ fieldBits (List.replicate Z true) ++ fieldBits (List.ofFn (RAMSerialization.arrayBits t Z e)) ++
+ fieldBits (List.replicate Z true) ++ fieldBits (List.replicate Z true)
+
+theorem runtime_length {t Z : ℕ} (e : Fin t → BurstRAM.Word Z) :
+ (runtime e).length = 2*(t*Z)+6*Z+4 := by
+ simp only [runtime, List.length_append, length_fieldBits, List.length_replicate, List.length_ofFn]
+ omega
+
+theorem advice_length (ps : List P) (t : ℕ) (d : List Bool) (payload : Stacks P) :
+ (advice ps t d payload).length =
+ 4*t + 4*d.length + 4 + (ps.map fun k => 2*(payload k).length+1).sum := by
+ simp only [advice, List.length_append, List.length_replicate, length_fieldBits,
+ List.length_flatMap]
+ omega
+
+/-- The advice bytes are independent of both the exponent values and their width. -/
+theorem rawInput_eq {t Z : ℕ} (ps : List P) (e : Fin t → BurstRAM.Word Z) (d : List Bool)
+ (payload : Stacks P) :
+ rawInput (fields ps) (initial e d payload) = advice ps t d payload ++ runtime e := by
+ simp only [fields, rawInput, List.flatMap_append, header, runtimePorts,
+ List.flatMap_cons, List.flatMap_nil, List.flatMap_map, advice, runtime, List.append_assoc,
+ List.append_nil]
+ rfl
+
+private theorem outside_empty {t Z : ℕ} (ps : List P) (hall : ∀ p, p ∈ ps)
+ (e : Fin t → BurstRAM.Word Z) (d : List Bool) (payload : Stacks P) (k : Port P)
+ (hk : k ∉ fields ps) : initial e d payload k = [] := by
+ cases k with
+ | sched k =>
+ cases k with
+ | addr k =>
+ cases k <;> first | rfl | simp [fields, header, runtimePorts] at hk
+ | work p => exact (hk (List.mem_append_left _ (List.mem_append_right _
+ (List.mem_map.mpr ⟨p, hall p, rfl⟩)))).elim
+ | _ => first | rfl | simp [fields, header, runtimePorts] at hk
+ | word k => cases k <;> first | rfl | simp [fields, header, runtimePorts] at hk
+ | _ => first | rfl | simp [fields, header, runtimePorts] at hk
+
+/-- The clock for loading the self-delimiting input fields, charging three instructions per
+payload bit and one for each field terminator. -/
+def readTicks {t Z : ℕ} (ps : List P) (e : Fin t → BurstRAM.Word Z) (d : List Bool)
+ (payload : Stacks P) :=
+ ((fields ps).map (fun k => 3*(initial e d payload k).length+1)).sum + 1
+
+/-- Each encoded data bit and field terminator costs at most two parser steps. -/
+theorem readTicks_le {t Z : ℕ} (ps : List P) (e : Fin t → BurstRAM.Word Z) (d : List Bool)
+ (payload : Stacks P) :
+ readTicks ps e d payload ≤ 2*((advice ps t d payload).length + (runtime e).length) + 1 := by
+ let s := initial e d payload
+ have bound (ks : List (Port P)) :
+ (ks.map (fun k => 3*(s k).length+1)).sum ≤ 2*(rawInput ks s).length := by
+ induction ks with
+ | nil => simp [rawInput]
+ | cons k ks ih =>
+ simp only [rawInput, List.flatMap_cons, List.length_append, length_fieldBits,
+ List.map_cons, List.sum_cons]
+ change _ ≤ 2*(rawInput ks s).length at ih
+ simp only [rawInput] at ih
+ omega
+ have h := bound (fields ps)
+ dsimp only [s] at h
+ rw [rawInput_eq, List.length_append] at h
+ exact Nat.add_le_add_right h 1
+
+theorem reader_runs [DecidableEq P] {t Z : ℕ} (ps : List P) (hp : ps.Nodup)
+ (hall : ∀ p, p ∈ ps) (e : Fin t → BurstRAM.Word Z) (d : List Bool) (payload : Stacks P) :
+ (reader (fields ps)).Runs (readTicks ps e d payload)
+ (frame (advice ps t d payload ++ runtime e) (fun _ => [])) (frame [] (initial e d payload)) := by
+ simpa only [readTicks, rawInput_eq] using load_selected_runs (fields ps) (fields_nodup hp)
+ (initial e d payload) (outside_empty ps hall e d payload)
+
+/-- Load the advice and exponents before calling the fixed physical machine. -/
+def withReader (ps : List P) (r : FiniteRoutine (Port P)) : FiniteRoutine (Option (Port P)) :=
+ (reader (fields ps)).followedBy (r.onPorts some)
+
+theorem withReader_realizes [DecidableEq P] {t Z : ℕ} {S T : Type*}
+ (ps : List P) (hp : ps.Nodup) (hall : ∀ p, p ∈ ps) (e : Fin t → BurstRAM.Word Z)
+ (d : List Bool) (payload : S → Stacks P) (r : FiniteRoutine (Port P))
+ {post : T → Stacks (Port P)} {B R : ℕ} {effect : (T → ℕ) → S → ℕ}
+ (hR : ∀ x, readTicks ps e d (payload x) ≤ R)
+ (h : Realizes r.body (initial e d ∘ payload) post B effect) :
+ Realizes (withReader ps r).body
+ (fun x => frame (advice ps t d (payload x) ++ runtime e) (fun _ => []))
+ (frame [] ∘ post) (R+B) effect := by
+ have hpref : Realizes (reader (fields ps)).body
+ (fun x => frame (advice ps t d (payload x) ++ runtime e) (fun _ => []))
+ (fun x => frame [] (initial e d (payload x))) R (fun f x => f x) := by
+ apply Realizes.of_runs (g := id)
+ intro x
+ exact ⟨_, hR x, reader_runs ps hp hall e d (payload x)⟩
+ apply hpref.followedBy
+ intro extra fuel hf x f c hc
+ rw [r.count_onPorts some (Option.some_injective _)]
+ apply h extra fuel hf x f
+ intro y n hn
+ have he : installStacks some (frame [] (initial e d (payload x))) (post y) = frame [] (post y) := by
+ apply installStacks_frame (small := post y) (target := frame [] (post y))
+ (Option.some_injective _) (fun _ => rfl)
+ intro k hk
+ cases k with
+ | none => rfl
+ | some k => exact (hk k rfl).elim
+ rw [he]
+ exact hc y n hn
+
+end EvaluatorProgramRawInput
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorProgramRawSafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorProgramRawSafety.lean
new file mode 100644
index 0000000000..1bfd0390a8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorProgramRawSafety.lean
@@ -0,0 +1,261 @@
+import OAI.Computability.VPVNP.EvaluatorProgramMonomial
+import OAI.Computability.VPVNP.EvaluatorMonomialSafety
+
+/-!
+# All-branch resources from the raw input to the monomial result
+
+The parser and native converter have polynomial deterministic clocks. The
+digit traversal may run for exponentially many steps while respecting its
+polynomial stack bound. Each framed callback retains its safety certificate
+on both successors of every binary choice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorRoutineSafety
+
+open RAMTape
+
+variable {K L : Type} [DecidableEq K] [DecidableEq L]
+
+private theorem safeFrom_framed (r : FiniteRoutine K) (p : K → L)
+ (frame : Stacks K → Stacks L) (read : ∀ s k, frame s (p k) = s k)
+ (write : ∀ s k bits, Function.update (frame s) (p k) bits = frame (Function.update s k bits))
+ (small : Stacks K → Prop) (large : Stacks L → Prop) (hs : ∀ s, small s → large (frame s))
+ (cont : ℕ → Stacks L → Prop) (n : ℕ) (q : Option r.State) (s : Stacks K)
+ (h : r.body.SafeFrom small (fun left u => cont left (frame u)) n q s) :
+ (r.onPorts p).body.SafeFrom large cont n q (frame s) := by
+ induction n generalizing q s with
+ | zero => cases q <;> exact h
+ | succ n ih =>
+ cases q with
+ | none => exact h
+ | some q =>
+ simp only [Routine.SafeFrom] at h ⊢
+ refine ⟨hs s h.1, ?_⟩
+ have hcode : (r.onPorts p).body.code q = (r.body.code q).rename p id := rfl
+ rw [hcode]
+ have hh := h.2
+ cases he : r.body.code q <;> rw [he] at hh <;>
+ simp only [StackOp.rename, id_eq, Function.comp_apply, read, write] at *
+ all_goals first | exact ih _ _ hh | exact ⟨ih _ _ hh.1, ih _ _ hh.2⟩
+
+/-- Preserve the stopping and peak-space contract under an embedding of
+stack banks which commutes with every physical read and write. -/
+theorem Bounded.onPorts_frame {S T : Type*} (r : FiniteRoutine K) (p : K → L)
+ (frame : Stacks K → Stacks L) (read : ∀ s k, frame s (p k) = s k)
+ (write : ∀ s k bits, Function.update (frame s) (p k) bits = frame (Function.update s k bits))
+ {small : Stacks K → Prop} {large : Stacks L → Prop} (hs : ∀ s, small s → large (frame s))
+ {pre : S → Stacks K} {post : T → Stacks K} {B : ℕ} (h : Bounded r.body small pre post B) :
+ Bounded (r.onPorts p).body large (frame ∘ pre) (frame ∘ post) B := by
+ intro extra fuel hf x cont hc
+ exact safeFrom_framed r p frame read write small large hs cont fuel (some r.body.entry) (pre x)
+ (h extra fuel hf x _ hc)
+
+end EvaluatorRoutineSafety
+
+namespace EvaluatorProgramMonomial
+
+open RAMTape EvaluatorRoutineSafety EvaluatorDigitFetch EvaluatorMonomialSchedule
+ EvaluatorChronologicalLoop EvaluatorRadixRows EvaluatorProgramRawInput
+
+variable {P S : Type} [DecidableEq P] {t Z : ℕ}
+
+/-- Input sizes and converter clock are polynomial in the exponent width,
+label count, divisor bit width and callback storage. -/
+def nativeSpace (t Z ℓ space : ℕ) :=
+ (t*Z+t+Z+ℓ+space) + EvaluatorProgramInput.convertTicks t Z ℓ + schedulerSpace (t*(Z*ℓ)) t Z ℓ space
+
+/-- Upper bound on the encoded input length from the advice size, number of labels and binary
+exponent width. -/
+def inputLengthBound (t Z A : ℕ) := A + (2*(t*Z)+6*Z+4)
+
+/-- Time allowance for parsing the tagged raw input, bounded by twice its length bound plus one
+instruction. -/
+def readerBudget (t Z A : ℕ) := 2*inputLengthBound t Z A + 1
+
+/-- Stack-space bound covering the raw input, parser workspace and the subsequent converted
+monomial execution. -/
+def rawSpace (t Z ℓ space A : ℕ) :=
+ inputLengthBound t Z A + readerBudget t Z A + nativeSpace t Z ℓ space
+
+/-- The closed physical storage bound is a degree-four polynomial in the
+label count, exponent width, divisor width, callback space, and advice size. -/
+theorem rawSpace_le_power (t Z ℓ space A : ℕ) :
+ rawSpace t Z ℓ space A ≤ 150*(t+Z+ℓ+space+A+1)^4 := by
+ let M := t+Z+ℓ+space+A+1
+ have hM : 1 ≤ M := by dsimp [M]; omega
+ have hmono : rawSpace t Z ℓ space A ≤ rawSpace M M M M M := by
+ unfold rawSpace nativeSpace readerBudget inputLengthBound EvaluatorProgramInput.convertTicks
+ rowsTicks rowTicks EvaluatorRadixDivision.radixTicks EvaluatorRadixDivision.digitTicks
+ schedulerSpace bankSpace
+ gcongr <;> dsimp [M] <;> omega
+ have expand : rawSpace M M M M M = 10*M^4 + 33*M^3 + 45*M^2 + 40*M + 21 := by
+ unfold rawSpace nativeSpace readerBudget inputLengthBound EvaluatorProgramInput.convertTicks
+ rowsTicks rowTicks EvaluatorRadixDivision.radixTicks EvaluatorRadixDivision.digitTicks
+ schedulerSpace bankSpace
+ ring
+ have h₀ := Nat.pow_pos hM (n := 4)
+ have h₁ : M ≤ M^4 := by simpa only [pow_one] using Nat.pow_le_pow_right hM (by decide : 1 ≤ 4)
+ have h₂ := Nat.pow_le_pow_right hM (by decide : 2 ≤ 4)
+ have h₃ := Nat.pow_le_pow_right hM (by decide : 3 ≤ 4)
+ change _ ≤ 150*M^4
+ rw [expand] at hmono
+ omega
+
+variable (e : Fin t → BurstRAM.Word Z) (d : List Bool) (payload : S → Stacks P)
+ (space : ℕ) (hp : ∀ x p, (payload x p).length ≤ space)
+ (frobenius multiply : FiniteRoutine (Port P)) (BF BM : ℕ)
+
+local notation "data" => packedTable d.length (TapeWord.value d) (List.ofFn e)
+local notation "sFits" => stackFits (schedulerSpace (List.length data) t Z d.length space)
+local notation "post" => fun x => EvaluatorProgramInput.extend Z d (bank data t Z d.length 0 0 0 0 (payload x))
+local notation "ticks" => EvaluatorProgramInput.convertTicks t Z d.length + budget t Z d.length (TapeWord.value d) BF BM
+
+omit [DecidableEq P] in
+theorem extend_fits (s : Stacks (Port P)) (hs : sFits s) :
+ stackFits (nativeSpace t Z d.length space) (EvaluatorProgramInput.extend Z d s) := by
+ intro k
+ cases k with
+ | sched k =>
+ have h := hs k
+ simp only [packedTable_length, List.length_ofFn] at h
+ exact h.trans (Nat.le_add_left ..)
+ | word k => cases k <;> simp [EvaluatorProgramInput.extend, nativeSpace]; omega
+ | _ => simp [EvaluatorProgramInput.extend, nativeSpace] <;> omega
+
+private theorem extend_update (s : Stacks (Port P)) (k : Port P) (bits : List Bool) :
+ Function.update (EvaluatorProgramInput.extend Z d s) (.sched k) bits =
+ EvaluatorProgramInput.extend Z d (Function.update s k bits) := by
+ funext j
+ cases j with
+ | sched a => by_cases ha : a = k <;> simp [EvaluatorProgramInput.extend, ha]
+ | word a => cases a <;> rfl
+ | _ => rfl
+
+include hp in
+omit [DecidableEq P] in
+private theorem initial_length (x : S) (k : EvaluatorProgramInput.Port P) :
+ (EvaluatorProgramInput.initial e d (payload x) k).length ≤ t*Z+t+Z+d.length+space := by
+ cases k with
+ | sched k =>
+ have h := bank_length [] t Z d.length space payload hp (i := 0) (left := 0) (by omega)
+ (j := 0) (cols := Z) (by omega) x k
+ simp only [bankSpace, List.length_nil] at h
+ exact h.trans (by omega)
+ | word k => cases k <;> simp [EvaluatorProgramInput.initial, EvaluatorProgramInput.extend] <;> omega
+ | _ => simp [EvaluatorProgramInput.initial, EvaluatorProgramInput.extend] <;> omega
+
+include hp in
+/-- All paths of the native converter and the physical scheduler satisfy
+the resource bound, including paths that reject inside a callback. -/
+theorem native_bounded (hq : 2 ≤ TapeWord.value d)
+ (hf : ∀ (j : Fin Z) left, j.val + left < Z → Bounded frobenius.body sFits
+ (fun x => bank data t Z d.length 0 j 0 left (payload x))
+ (fun x => bank data t Z d.length 0 j 0 left (payload x)) BF)
+ (hm : ∀ (i : Fin t) (j : Fin Z) labels cols, i.val + labels < t → j.val + cols < Z →
+ ∀ bits : List Bool, bits.length = d.length →
+ let pre (x : S) := EvaluatorDigitRepeat.frame Port.digit Port.borrow
+ (bank data t Z d.length i j labels cols (payload x)) bits []
+ Bounded multiply.body sFits pre pre BM) :
+ Bounded (nativeMachine frobenius multiply).body (stackFits (nativeSpace t Z d.length space))
+ (EvaluatorProgramInput.initial e d ∘ payload) post ticks := by
+ let pre (x : S) := bank data t Z d.length 0 0 0 Z (payload x)
+ have h₁ : Bounded EvaluatorProgramInput.convert.body (stackFits (nativeSpace t Z d.length space))
+ (EvaluatorProgramInput.initial e d ∘ payload) (EvaluatorProgramInput.extend Z d ∘ pre)
+ (EvaluatorProgramInput.convertTicks t Z d.length) := by
+ apply Bounded.of_runs_with_room (g := id)
+ · intro x
+ exact ⟨_, le_rfl, EvaluatorProgramInput.convert_runs e d (payload x) hq⟩
+ · intro x u hu k
+ have h := initial_length e d payload space hp x k
+ have hh := hu k
+ simp only [Function.comp_apply] at hh
+ unfold nativeSpace
+ omega
+ have hs := machine_bounded e d.length (TapeWord.value d) BF BM space payload hp
+ frobenius multiply (by omega) (TapeWord.value_lt d).le hf hm
+ have h₂ := Bounded.onPorts_frame (machine frobenius multiply) EvaluatorProgramInput.Port.sched
+ (EvaluatorProgramInput.extend Z d) (fun _ _ => rfl) (extend_update d) (extend_fits e d space) hs
+ exact h₁.followedBy h₂
+
+private theorem frame_update (s : Stacks (EvaluatorProgramInput.Port P)) (k : EvaluatorProgramInput.Port P)
+ (bits : List Bool) :
+ Function.update (Evaluator.InputBank.frame [] s) (some k) bits =
+ Evaluator.InputBank.frame [] (Function.update s k bits) := by
+ funext j
+ cases j with
+ | none => rfl
+ | some a => by_cases ha : a = k <;> simp [Evaluator.InputBank.frame, ha]
+
+/-- Load the raw stream with its deterministic polynomial-space parser, then
+preserve the resource certificate of the entire native machine. -/
+theorem raw_bounded_of_native (ps : List P) (hn : ps.Nodup) (hall : ∀ p, p ∈ ps) (A : ℕ)
+ (ha : ∀ x, (advice ps t d (payload x)).length ≤ A)
+ (h : Bounded (nativeMachine frobenius multiply).body (stackFits (nativeSpace t Z d.length space))
+ (EvaluatorProgramInput.initial e d ∘ payload) post ticks) :
+ Bounded (rawMachine ps frobenius multiply).body (stackFits (rawSpace t Z d.length space A))
+ (fun x => Evaluator.InputBank.frame (advice ps t d (payload x) ++ runtime e) (fun _ => []))
+ (Evaluator.InputBank.frame [] ∘ (post)) (readerBudget t Z A + (ticks)) := by
+ have h₁ : Bounded (Evaluator.InputBank.reader (fields ps)).body (stackFits (rawSpace t Z d.length space A))
+ (fun x => Evaluator.InputBank.frame (advice ps t d (payload x) ++ runtime e) (fun _ => []))
+ (fun x => Evaluator.InputBank.frame [] (EvaluatorProgramInput.initial e d (payload x)))
+ (readerBudget t Z A) := by
+ apply Bounded.of_runs_with_room (g := id)
+ · intro x
+ refine ⟨_, ?_, reader_runs ps hn hall e d (payload x)⟩
+ have hr := readTicks_le ps e d (payload x)
+ rw [runtime_length] at hr
+ have hax := ha x
+ unfold readerBudget inputLengthBound
+ omega
+ · intro x u hu k
+ have hlen : (advice ps t d (payload x) ++ runtime e).length ≤ inputLengthBound t Z A := by
+ simp only [inputLengthBound, List.length_append, runtime_length]
+ exact Nat.add_le_add_right (ha x) _
+ have hh := hu k
+ cases k <;> simp only [Evaluator.InputBank.frame, List.length_nil] at hh
+ all_goals unfold rawSpace; omega
+ apply h₁.followedBy
+ apply Bounded.onPorts_frame (nativeMachine frobenius multiply) some (Evaluator.InputBank.frame [])
+ (fun _ _ => rfl) frame_update _ h
+ intro s hs k
+ cases k with
+ | none => exact Nat.zero_le _
+ | some k => exact (hs k).trans (Nat.le_add_left ..)
+
+include hp in
+/-- A physical stopping clock and a polynomial bound on every reachable
+stack in the machine starting on the sole raw input tape. -/
+theorem raw_space_clock (ps : List P) (hn : ps.Nodup) (hall : ∀ p, p ∈ ps) (A : ℕ)
+ (ha : ∀ x, (advice ps t d (payload x)).length ≤ A)
+ (h : Bounded (nativeMachine frobenius multiply).body (stackFits (nativeSpace t Z d.length space))
+ (EvaluatorProgramInput.initial e d ∘ payload) post ticks) (outcome : Bool) (x : S) :
+ let r := (rawMachine ps frobenius multiply).body
+ let start := Evaluator.InputBank.frame (advice ps t d (payload x) ++ runtime e) (fun _ => [])
+ StopsWithin (r.close outcome) (1+(readerBudget t Z A + (ticks))) (some r.entry) start ∧
+ ∀ ⦃q s⦄, StackCompiler.Reach (r.close outcome) (some r.entry) start q s →
+ stackFits (rawSpace t Z d.length space A) s := by
+ have hh := raw_bounded_of_native e d payload space frobenius multiply BF BM ps hn hall A ha h
+ have hpost (y : S) : stackFits (nativeSpace t Z d.length space) ((post) y) := by
+ apply extend_fits e d space
+ intro k
+ have hs := bank_length data t Z d.length space payload hp (i := 0) (left := 0) (by omega)
+ (j := 0) (cols := 0) (by omega) y k
+ exact hs.trans (by unfold schedulerSpace; omega)
+ have endSafe := hh 1 _ le_rfl x (fun n s => 0 < n ∧ stackFits (rawSpace t Z d.length space A) s) (by
+ intro y n hn
+ refine ⟨hn, fun k => ?_⟩
+ cases k with
+ | none => exact Nat.zero_le _
+ | some k => exact (hpost y k).trans (Nat.le_add_left ..))
+ exact ⟨endSafe.stopsWithin outcome (fun _ _ h => h.1), fun _ _ path =>
+ endSafe.reach outcome (fun _ _ h => h.2) path⟩
+
+end EvaluatorProgramMonomial
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorRadixDivision.lean b/lean/OAI/Computability/VPVNP/EvaluatorRadixDivision.lean
new file mode 100644
index 0000000000..e5b215bcb8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorRadixDivision.lean
@@ -0,0 +1,272 @@
+import OAI.Computability.VPVNP.PrimedCounterBits
+import OAI.Computability.VPVNP.RAMTapeDivision
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.StructuredStackLoop
+
+/-!
+# Binary-to-radix conversion for the streamed evaluator
+
+The input exponent is a most-significant-bit-first binary stack. A fixed
+restoring division table handles a divisor of any positive value, independently
+of the dividend width. One division round returns the quotient in the original
+input format and prepends a divisor-width little-endian remainder to the digit
+stack. The loop count is supplied on a unary stack. Hence the output starts
+with the most significant requested digit, including leading zero digits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorRadixDivision
+
+open RAMTape TapeWord
+
+/-- The restoring-division registers, the unary count of remaining divisions and the stack of
+accumulated radix digits. -/
+inductive Port where
+ | word (k : DivisionStack.Port)
+ | rounds
+ | digits
+ deriving DecidableEq, Fintype
+
+/-- The control consumes the source in head order, pushing onto the destination. -/
+def reverseOnto {K : Type} (src dst : K) : FiniteRoutine K :=
+ .ofRoutine (Routine.popLoop src (fun _ => true) (Routine.push dst false) (Routine.push dst true))
+
+theorem reverseOnto_runs {K : Type} [DecidableEq K] {src dst : K} (hne : src ≠ dst)
+ (s u : Stacks K) (hs : u src = []) (hd : u dst = (s src).reverse ++ s dst)
+ (hframe : ∀ k, k ≠ src → k ≠ dst → u k = s k) :
+ (reverseOnto src dst).Runs (2 * (s src).length + 1) s u := by
+ generalize hx : s src = xs at *
+ induction xs generalizing s with
+ | nil =>
+ have hu : u = s := by
+ funext k
+ by_cases h : k = src
+ · subst k; exact hs.trans hx.symm
+ by_cases h' : k = dst
+ · subst k; simpa using hd
+ exact hframe k h h'
+ rw [hu]
+ exact Routine.Runs.popLoop_empty src (fun _ => true) (Routine.push dst false) (Routine.push dst true) hx
+ | cons b xs ih =>
+ let a := Function.update s src xs
+ let v := Function.update a dst (b :: s dst)
+ have va : v src = xs := by simp [v, a, hne]
+ have ad : a dst = s dst := Function.update_of_ne hne.symm ..
+ have hpush : (Routine.push dst b).Runs 1 a v := by
+ simpa only [v, ad] using Routine.runs_push dst b a
+ have hrest : (reverseOnto src dst).Runs (2 * xs.length + 1) v u := by
+ apply ih v
+ all_goals first
+ | exact va
+ | simpa [v, List.reverse_cons, List.append_assoc] using hd
+ | exact fun k hk hk' => by simpa [v, a, hk, hk'] using hframe k hk hk'
+
+ have run := Routine.Runs.popLoop_continue src (fun _ => true) (Routine.push dst false)
+ (Routine.push dst true) hx rfl (by cases b <;> exact hpush) hrest
+ rw [show 2 * (b :: xs).length + 1 = 1 + 1 + (2 * xs.length + 1) by
+ simp only [List.length_cons]; omega]
+ exact run
+
+/-- The machine's integer inputs and scratch are precisely the division word
+ports. The counter and the growing digit string belong to the caller's loop. -/
+def bank (rounds : ℕ) (w : DivisionStack.Data) (acc : List Bool) : Stacks Port
+ | .word k => w.stacks k
+ | .rounds => List.replicate rounds true
+ | .digits => acc
+
+/-- The bank at a division-round boundary, containing the reversed dividend, divisor,
+remaining-round tally and accumulated digits. -/
+def ready (rounds : ℕ) (x d acc : List Bool) : Stacks Port :=
+ bank rounds ⟨[], x.reverse, d, [], [], [], [], []⟩ acc
+
+private def divRoutine : FiniteRoutine Port :=
+ .ofStackCode DivisionStack.code Port.word .reverseInput (· == .done)
+
+/-- One radix-conversion round. Divide the dividend, install the quotient for the next round
+and prepend the remainder bits to the digit stack. -/
+def digitRoutine : FiniteRoutine Port :=
+ let input := reverseOnto (.word .feed) (.word .input)
+ let quot := reverseOnto (.word .quotient) (.word .feed)
+ let save := reverseOnto (.word .remainder) (.word .original)
+ let emit := reverseOnto (.word .original) .digits
+ (((input.followedBy divRoutine).followedBy quot).followedBy save).followedBy emit
+
+/-- Positive-divisor division accepts arbitrary, possibly unequal widths. -/
+theorem divide_spec (x d : List Bool) (h : 0 < value d) :
+ let t := divideWords x d
+ t.1.length = x.length ∧ t.2.length = d.length ∧
+ value t.1 = value x / value d ∧ value t.2 = value x % value d := by
+ have hd := (anyBit_iff d).mpr h
+ obtain ⟨h₁, h₂, hlt, he⟩ := dividePass_spec d x h
+ simp only [divideWords, hd, ↓reduceIte]
+ refine ⟨h₁, h₂, ?_, ?_⟩
+ · rw [← he, Nat.mul_add_div h, Nat.div_eq_of_lt hlt, Nat.add_zero]
+ · rw [← he, Nat.mul_add_mod, Nat.mod_eq_of_lt hlt]
+
+/-- One complete divide-and-emit pass, measured in elementary bit instructions. -/
+def digitTicks (z w : ℕ) := z * (10*w+10) + 9*w + 8
+
+private theorem framed_divide (rounds : ℕ) (x d acc : List Bool) :
+ let out := divideWords x d
+ divRoutine.Runs (DivisionStack.ticks x d) (bank rounds ⟨x,[],d,[],[],[],[],[]⟩ acc)
+ (bank rounds ⟨[],[],d,out.2,out.1,[],[],[]⟩ acc) := by
+ have hh (q : DivisionStack.State) (h : (q == DivisionStack.State.done) = true) :
+ (DivisionStack.code q).returns = true := by
+ have : q = DivisionStack.State.done := by simpa using h
+ subst q; rfl
+ apply FiniteRoutine.runs_ofStackCode_framed (normal := (· == DivisionStack.State.done))
+ (ports := Port.word) (fun _ _ => Port.word.inj) (by decide) (by decide) hh (DivisionStack.divideRun x d)
+ · intro k; rfl
+ · intro k; rfl
+ · intro k hk
+ cases k with
+ | word j => exact (hk j rfl).elim
+ | rounds | digits => rfl
+
+local macro "frame_cases" : tactic =>
+ `(tactic| (intro k hk hk'; cases k with
+ | word j => cases j <;> first | rfl | exact (hk rfl).elim | exact (hk' rfl).elim
+ | rounds | digits => first | rfl | exact (hk rfl).elim | exact (hk' rfl).elim))
+
+theorem digitRoutine_runs (rounds : ℕ) (x d acc : List Bool) (hd : 0 < value d) :
+ let out := divideWords x d
+ digitRoutine.Runs (digitTicks x.length d.length) (ready rounds x d acc)
+ (ready rounds out.1 d (out.2 ++ acc)) := by
+ let out := divideWords x d
+ let a := bank rounds ⟨x,[],d,[],[],[],[],[]⟩ acc
+ let b := bank rounds ⟨[],[],d,out.2,out.1,[],[],[]⟩ acc
+ let c := bank rounds ⟨[],out.1.reverse,d,out.2,[],[],[],[]⟩ acc
+ let e := bank rounds ⟨[],out.1.reverse,d,[],[],[],out.2.reverse,[]⟩ acc
+ have h₁ := reverseOnto_runs (src := Port.word .feed) (dst := .word .input) (by decide)
+ (ready rounds x d acc) a rfl
+ (show x = x.reverse.reverse ++ [] by simp) (by frame_cases)
+ have h₂ : divRoutine.Runs (DivisionStack.ticks x d) a b := framed_divide rounds x d acc
+ have h₃ := reverseOnto_runs (src := Port.word .quotient) (dst := .word .feed) (by decide)
+ b c rfl (show out.1.reverse = out.1.reverse ++ [] by simp) (by frame_cases)
+ have h₄ := reverseOnto_runs (src := Port.word .remainder) (dst := .word .original) (by decide)
+ c e rfl (show out.2.reverse = out.2.reverse ++ [] by simp) (by frame_cases)
+ have h₅ := reverseOnto_runs (src := Port.word .original) (dst := .digits) (by decide)
+ e (ready rounds out.1 d (out.2 ++ acc)) rfl
+ (show out.2 ++ acc = out.2.reverse.reverse ++ acc by simp) (by frame_cases)
+ obtain ⟨hq, hr, _, _⟩ := divide_spec x d hd
+ have ht := (((h₁.followedBy h₂).followedBy h₃).followedBy h₄).followedBy h₅
+ have hc : digitTicks x.length d.length =
+ 2 * x.reverse.length + 1 + DivisionStack.ticks x d + (2*out.1.length+1) +
+ (2*out.2.length+1) + (2*out.2.reverse.length+1) := by
+ simp only [digitTicks, DivisionStack.ticks, (anyBit_iff d).mpr hd, ↓reduceIte, out,
+ List.length_reverse, hq, hr]
+ ring
+ dsimp only
+ rw [hc]
+ exact ht
+
+/-- A fixed number of base-`Q` digits, ordered from the most to the least
+significant, as in the Frobenius evaluator. -/
+def radixDigits (Q : ℕ) : ℕ → ℕ → List ℕ
+ | 0, _ => []
+ | k + 1, e => radixDigits Q k (e / Q) ++ [e % Q]
+
+/-- The digit in place `j` is the residue of the quotient by `Q ^ j`. The
+stack exposes the highest place first. -/
+theorem radixDigits_eq (Q rounds e : ℕ) :
+ radixDigits Q rounds e =
+ (List.range rounds).reverse.map (fun j => e / Q^j % Q) := by
+ induction rounds generalizing e with
+ | zero => rfl
+ | succ k ih =>
+ simp [radixDigits, ih, List.range_succ_eq_map, List.map_reverse, List.map_map,
+ Function.comp_def, Nat.div_div_eq_div_mul, pow_succ']
+
+/-- Fixed-width little-endian encoding of each digit, concatenated without
+separators. A reader knows the field width from the divisor. -/
+def encodedDigits (w Q rounds e : ℕ) :=
+ (radixDigits Q rounds e).flatMap (PrimedCounter.digits w)
+
+@[simp] theorem encodedDigits_length (w Q rounds e : ℕ) :
+ (encodedDigits w Q rounds e).length = rounds * w := by
+ induction rounds generalizing e with
+ | zero => simp [encodedDigits, radixDigits]
+ | succ k ih =>
+ simp only [encodedDigits, radixDigits, List.flatMap_append, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil, List.length_append, PrimedCounter.digits, BurstRAM.length_wordBits]
+ rw [← encodedDigits, ih, Nat.succ_mul]
+
+theorem digit_lt {Q : ℕ} (hq : 0 < Q) (rounds e : ℕ) {a : ℕ} (ha : a ∈ radixDigits Q rounds e) :
+ a < Q := by
+ induction rounds generalizing e with
+ | zero => simp [radixDigits] at ha
+ | succ k ih =>
+ simp only [radixDigits, List.mem_append, List.mem_singleton] at ha
+ exact ha.elim (ih _) (fun he => he ▸ Nat.mod_lt _ hq)
+
+private theorem bits_value (x : List Bool) :
+ PrimedCounter.digits x.length (value x) = x := by
+ apply eq_of_length_value
+ · simp [PrimedCounter.digits]
+ · simp only [PrimedCounter.digits, value_wordBits, Fin.ofNat, Nat.mod_eq_of_lt (value_lt x)]
+
+/-- Positive counter marks launch a divide-and-emit pass. Empty input to
+the loop returns immediately. -/
+def radixRoutine : FiniteRoutine Port :=
+ .ofRoutine (Routine.popLoop .rounds (fun _ => true) (Routine.halt false) digitRoutine.body)
+
+/-- Instruction count for the specified number of restoring-division rounds on a z-bit dividend
+with a w-bit divisor. -/
+def radixTicks (rounds z w : ℕ) := rounds * (digitTicks z w + 1) + 1
+
+private theorem pop_round (rounds : ℕ) (x d acc : List Bool) :
+ Function.update (ready (rounds + 1) x d acc) Port.rounds (List.replicate rounds true) =
+ ready rounds x d acc := by
+ funext k
+ cases k <;> rfl
+
+/-- Exact normal return of the fixed finite routine. It preserves the divisor,
+retains the high quotient after the requested rounds, and emits exactly one
+fixed-width binary block per round. -/
+theorem radixRoutine_runs (rounds : ℕ) (x d acc : List Bool) (hd : 0 < value d) :
+ radixRoutine.Runs (radixTicks rounds x.length d.length) (ready rounds x d acc)
+ (ready 0 (PrimedCounter.digits x.length (value x / value d ^ rounds)) d
+ (encodedDigits d.length (value d) rounds (value x) ++ acc)) := by
+ induction rounds generalizing x acc with
+ | zero =>
+ simp only [pow_zero, Nat.div_one, bits_value]
+ simpa [radixRoutine, FiniteRoutine.Runs, FiniteRoutine.ofRoutine, radixTicks, encodedDigits, radixDigits] using
+ (Routine.Runs.popLoop_empty Port.rounds (fun _ => true) (Routine.halt false) digitRoutine.body
+ (s := ready 0 x d acc) rfl)
+ | succ k ih =>
+ let t := divideWords x d
+ obtain ⟨hq, hr, hvq, hvr⟩ := divide_spec x d hd
+ have hdigit : t.2 = PrimedCounter.digits d.length (value x % value d) := by
+ simpa only [t, hr, hvr] using (bits_value t.2).symm
+ have hb := digitRoutine_runs k x d acc hd
+ have h := Routine.Runs.popLoop_true_continue Port.rounds (fun _ => true)
+ (Routine.halt false) digitRoutine.body
+ (s := ready (k+1) x d acc) (mid := ready k t.1 d (t.2 ++ acc))
+ (show ready (k+1) x d acc .rounds = true :: List.replicate k true from List.replicate_succ ..)
+ rfl (by rw [pop_round]; exact hb) (ih t.1 (t.2 ++ acc))
+ have hcost : radixTicks (k+1) x.length d.length =
+ 1 + digitTicks x.length d.length + radixTicks k t.1.length d.length := by
+ simp only [radixTicks, t, hq, Nat.succ_mul]
+ omega
+ rw [hcost]
+ simpa only [radixRoutine, FiniteRoutine.Runs, FiniteRoutine.ofRoutine, encodedDigits, radixDigits,
+ List.flatMap_append, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil, List.append_assoc, hdigit, t, hq, hvq, Nat.div_div_eq_div_mul, pow_succ'] using h
+
+/-- A full input bit width of base-`Q` rounds suffices whenever `Q ≥ 2`.
+Every such run leaves a zero quotient and all the digits of the exponent. -/
+theorem full_radixRoutine_runs (x d acc : List Bool) (hq : 2 ≤ value d) :
+ radixRoutine.Runs (radixTicks x.length x.length d.length) (ready x.length x d acc)
+ (ready 0 (PrimedCounter.digits x.length 0) d
+ (encodedDigits d.length (value d) x.length (value x) ++ acc)) := by
+ have hfit := (value_lt x).trans_le (Nat.pow_le_pow_left hq x.length)
+ simpa only [Nat.div_eq_of_lt hfit] using radixRoutine_runs x.length x d acc (by omega)
+
+end EvaluatorRadixDivision
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorRadixRows.lean b/lean/OAI/Computability/VPVNP/EvaluatorRadixRows.lean
new file mode 100644
index 0000000000..8d8a3d45cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorRadixRows.lean
@@ -0,0 +1,357 @@
+import OAI.Computability.VPVNP.EvaluatorRadixSpace
+import OAI.Computability.VPVNP.RAMTapeSuccessorFields
+
+/-!
+# Packed radix-digit rows for all label exponents
+
+The machine reads one fixed-width binary exponent per row, in descending
+label order. Each field is most-significant-bit-first. It prepends the radix
+digits of each exponent to the output. Thus the finished table is ordered by
+increasing label, with the most significant digit first in each row.
+
+A unary width counter is spent during extraction to build the radix round
+counter. The quotient produced by the division has the original width, so
+clearing its bits restores the width counter for the next exponent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorRadixRows
+
+open RAMTape TapeWord
+open EvaluatorRadixDivision (encodedDigits radixRoutine radixTicks reverseOnto reverseOnto_runs)
+
+/-- The packed exponent input, unary row and width counters and the radix-conversion register
+bank. -/
+inductive Port where
+ | input | width | rowCount | radix (k : EvaluatorRadixDivision.Port)
+ deriving DecidableEq, Fintype
+
+private abbrev staged : Port := .radix (.word .input)
+private abbrev feedPort : Port := .radix (.word .feed)
+private abbrev roundPort : Port := .radix .rounds
+
+private def frame (rows width rounds : ℕ) (raw stage feed d acc : List Bool) : Stacks Port
+ | .input => raw
+ | .width => List.replicate width true
+ | .rowCount => List.replicate rows true
+ | .radix k => EvaluatorRadixDivision.bank rounds ⟨stage,feed,d,[],[],[],[],[]⟩ acc k
+
+/-- The ready state between rows has no pending quotient or rounds. -/
+def ready (rows width : ℕ) (raw d acc : List Bool) : Stacks Port :=
+ frame rows width 0 raw [] [] d acc
+
+private def stageBit (b : Bool) :=
+ (Routine.push staged b).followedBy (Routine.push roundPort true)
+
+private def readBit :=
+ Routine.popCase Port.input (Routine.halt false) (stageBit false) (stageBit true)
+
+private def extract :=
+ Routine.popLoop Port.width (fun _ => true) (Routine.halt false) readBit
+
+private def restoreWidth :=
+ Routine.popLoop feedPort (fun _ => true) (Routine.push .width true) (Routine.push .width true)
+
+local macro "by_ports" : tactic => `(tactic|
+ (funext j; cases j with
+ | input | width | rowCount => first | rfl | exact (List.replicate_succ ..).symm
+ | radix k => cases k with
+ | rounds | digits => first | rfl | exact (List.replicate_succ ..).symm
+ | word i => cases i <;> rfl))
+
+private theorem readBit_runs (rows width n : ℕ) (b : Bool) (raw stage d acc : List Bool) :
+ readBit.Runs 3 (frame rows width n (b :: raw) stage [] d acc)
+ (frame rows width (n+1) raw (b :: stage) [] d acc) := by
+ let a := frame rows width n raw stage [] d acc
+ let u := frame rows width n raw (b :: stage) [] d acc
+ let v := frame rows width (n+1) raw (b :: stage) [] d acc
+ have h₁ : Function.update a staged (b :: a staged) = u := by by_ports
+ have h₂ : Function.update u roundPort (true :: u roundPort) = v := by by_ports
+ have p := (Routine.runs_push staged b a).followedBy (h₁.symm ▸ Routine.runs_push roundPort true u)
+ rw [h₁, h₂] at p
+ have hin : Function.update (frame rows width n (b :: raw) stage [] d acc) Port.input raw = a := by by_ports
+ cases b with
+ | false => exact Routine.runs_popCase_false _ _ _ _ rfl (by rw [hin]; exact p)
+ | true => exact Routine.runs_popCase_true _ _ _ _ rfl (by rw [hin]; exact p)
+
+private theorem extract_runs (rows n : ℕ) (xs suffix stage d acc : List Bool) :
+ extract.Runs (4*xs.length+1) (frame rows xs.length n (xs ++ suffix) stage [] d acc)
+ (frame rows 0 (n+xs.length) suffix (xs.reverse ++ stage) [] d acc) := by
+ induction xs generalizing n stage with
+ | nil =>
+ exact Routine.Runs.popLoop_empty .width (fun _ => true) (Routine.halt false) readBit
+ (s := frame rows 0 n suffix stage [] d acc) rfl
+ | cons b xs ih =>
+ let s := frame rows (xs.length+1) n (b :: (xs ++ suffix)) stage [] d acc
+ let a := frame rows xs.length n (b :: (xs ++ suffix)) stage [] d acc
+ let u := frame rows xs.length (n+1) (xs ++ suffix) (b :: stage) [] d acc
+ have ha : Function.update s .width (List.replicate xs.length true) = a := by by_ports
+ have h := Routine.Runs.popLoop_true_continue Port.width (fun _ => true) (Routine.halt false) readBit
+ (s := s) (mid := u) (show s .width = true :: List.replicate xs.length true from List.replicate_succ ..)
+ rfl (by rw [ha]; exact readBit_runs rows xs.length n b (xs ++ suffix) stage d acc) (ih (n+1) (b::stage))
+ rw [show 4*(b::xs).length+1 = 1+3+(4*xs.length+1) by simp only [List.length_cons]; omega]
+ simpa only [s, extract, List.length_cons, List.cons_append, List.reverse_cons, List.append_assoc,
+ List.singleton_append, List.nil_append, Nat.add_left_comm, Nat.add_comm, Nat.add_assoc] using h
+
+private theorem restoreWidth_runs (rows width : ℕ) (raw feed d acc : List Bool) :
+ restoreWidth.Runs (2*feed.length+1) (frame rows width 0 raw [] feed d acc)
+ (ready rows (width + feed.length) raw d acc) := by
+ induction feed generalizing width with
+ | nil =>
+ exact Routine.Runs.popLoop_empty feedPort (fun _ => true) (Routine.push .width true)
+ (Routine.push .width true) rfl
+ | cons b xs ih =>
+ let s := frame rows width 0 raw [] (b::xs) d acc
+ let a := frame rows width 0 raw [] xs d acc
+ let u := frame rows (width+1) 0 raw [] xs d acc
+ have ha : Function.update s feedPort xs = a := by by_ports
+ have hu : Function.update a .width (true :: a .width) = u := by by_ports
+ have h := Routine.Runs.popLoop_continue feedPort (fun _ => true) (Routine.push .width true)
+ (Routine.push .width true) (s := s) (mid := u) (show s feedPort = b :: xs from rfl) rfl
+ (by rw [ha]; cases b <;> exact hu ▸ Routine.runs_push Port.width true a) (ih (width+1))
+ rw [show 2*(b::xs).length+1 = 1+1+(2*xs.length+1) by simp only [List.length_cons]; omega]
+ simpa only [s, restoreWidth, List.length_cons, Nat.add_left_comm, Nat.add_comm, Nat.add_assoc] using h
+
+private def rowRoutine : FiniteRoutine Port :=
+ (((FiniteRoutine.ofRoutine extract).followedBy (reverseOnto staged feedPort)).followedBy
+ (radixRoutine.onPorts Port.radix)).followedBy (FiniteRoutine.ofRoutine restoreWidth)
+
+/-- Instruction count for extracting one z-bit exponent and converting its z requested radix
+digits using a w-bit divisor. -/
+def rowTicks (z w : ℕ) := 8*z + 3 + radixTicks z z w
+
+private theorem rowRoutine_runs (rows : ℕ) (x suffix d acc : List Bool) (hq : 2 ≤ value d) :
+ rowRoutine.Runs (rowTicks x.length d.length) (ready rows x.length (x.reverse ++ suffix) d acc)
+ (ready rows x.length suffix d (encodedDigits d.length (value d) x.length (value x) ++ acc)) := by
+ let a := frame rows 0 x.length suffix x [] d acc
+ let b := frame rows 0 x.length suffix [] x.reverse d acc
+ let q := PrimedCounter.digits x.length 0
+ let acc' := encodedDigits d.length (value d) x.length (value x) ++ acc
+ let u := frame rows 0 0 suffix [] q.reverse d acc'
+ have h₁ : (FiniteRoutine.ofRoutine extract).Runs (4*x.length+1)
+ (ready rows x.length (x.reverse ++ suffix) d acc) a := by
+ simpa only [FiniteRoutine.ofRoutine, FiniteRoutine.Runs, ready, a, List.reverse_reverse, List.length_reverse, List.append_nil, Nat.zero_add] using
+ extract_runs rows 0 x.reverse suffix [] d acc
+ have h₂ := reverseOnto_runs (src := staged) (dst := feedPort) (by decide) a b rfl
+ (show x.reverse = x.reverse ++ [] by simp) (by
+ intro k hk hk'; cases k with
+ | input | width | rowCount => rfl
+ | radix k => cases k with
+ | rounds | digits => rfl
+ | word i => cases i <;> first | rfl | exact (hk rfl).elim | exact (hk' rfl).elim)
+ have h₃ : (radixRoutine.onPorts Port.radix).Runs (radixTicks x.length x.length d.length) b u := by
+ apply FiniteRoutine.runs_onPorts_framed radixRoutine (fun _ _ => Port.radix.inj)
+ (EvaluatorRadixDivision.full_radixRoutine_runs x d acc hq)
+ · intro k; rfl
+ · intro k; rfl
+ · intro k hk
+ cases k with
+ | radix i => exact (hk i rfl).elim
+ | input | width | rowCount => rfl
+ have h₄ : (FiniteRoutine.ofRoutine restoreWidth).Runs (2*x.length+1) u
+ (ready rows x.length suffix d acc') := by
+ simpa only [FiniteRoutine.ofRoutine, FiniteRoutine.Runs, u, q, PrimedCounter.digits, List.length_reverse, BurstRAM.length_wordBits, Nat.zero_add] using
+ restoreWidth_runs rows 0 suffix q.reverse d acc'
+ have hcost : rowTicks x.length d.length =
+ (4*x.length+1)+(2*x.length+1)+radixTicks x.length x.length d.length+(2*x.length+1) := by
+ unfold rowTicks; omega
+ rw [hcost]
+ exact ((h₁.followedBy h₂).followedBy h₃).followedBy h₄
+
+/-- The loop consumes one unary mark per binary exponent field. -/
+def radixRows : FiniteRoutine Port :=
+ .ofRoutine (Routine.popLoop .rowCount (fun _ => true) (Routine.halt false) rowRoutine.body)
+
+/-- Instruction count for converting the specified number of exponent rows, including the
+row-counter updates and final exit. -/
+def rowsTicks (rows z w : ℕ) := rows * (rowTicks z w + 1) + 1
+
+/-- Source rows are supplied by descending label and highest binary bit first. -/
+def packedInput {z : ℕ} (rows : List (BurstRAM.Word z)) : List Bool :=
+ rows.reverse.flatMap fun x => (BurstRAM.wordBits x).reverse
+
+/-- Destination rows are ordered by ascending label, then descending radix
+place. Within each digit the bits are little-endian. -/
+def packedTable {z : ℕ} (w Q : ℕ) (rows : List (BurstRAM.Word z)) : List Bool :=
+ rows.flatMap fun x => encodedDigits w Q z x.val
+
+private theorem loop_runs {z : ℕ} (xs : List (BurstRAM.Word z)) (suffix d acc : List Bool) (hq : 2 ≤ value d) :
+ radixRows.Runs (rowsTicks xs.length z d.length)
+ (ready xs.length z ((xs.flatMap fun x => (BurstRAM.wordBits x).reverse) ++ suffix) d acc)
+ (ready 0 z suffix d (packedTable d.length (value d) xs.reverse ++ acc)) := by
+ induction xs generalizing acc with
+ | nil =>
+ simpa [rowsTicks, packedTable, radixRows, FiniteRoutine.Runs, FiniteRoutine.ofRoutine] using
+ (Routine.Runs.popLoop_empty Port.rowCount (fun _ => true) (Routine.halt false) rowRoutine.body
+ (s := ready 0 z suffix d acc) rfl)
+ | cons x xs ih =>
+ let tail := (xs.flatMap fun y => (BurstRAM.wordBits y).reverse) ++ suffix
+ let s := ready (xs.length+1) z ((BurstRAM.wordBits x).reverse ++ tail) d acc
+ let a := ready xs.length z ((BurstRAM.wordBits x).reverse ++ tail) d acc
+ let next := encodedDigits d.length (value d) z x.val ++ acc
+ let u := ready xs.length z tail d next
+ have ha : Function.update s Port.rowCount (List.replicate xs.length true) = a := by by_ports
+ have hb : rowRoutine.Runs (rowTicks z d.length) a u := by
+ simpa only [a, u, next, BurstRAM.length_wordBits, value_wordBits] using
+ rowRoutine_runs xs.length (BurstRAM.wordBits x) tail d acc hq
+ have h := Routine.Runs.popLoop_true_continue Port.rowCount (fun _ => true) (Routine.halt false) rowRoutine.body
+ (s := s) (mid := u)
+ (show s .rowCount = true :: List.replicate xs.length true from List.replicate_succ ..)
+ rfl (by rw [ha]; exact hb) (ih next)
+ have ht : rowsTicks (x::xs).length z d.length = 1+rowTicks z d.length+rowsTicks xs.length z d.length := by
+ simp only [rowsTicks, List.length_cons, Nat.succ_mul]
+ omega
+ rw [ht]
+ simpa only [s, next, tail, radixRows, FiniteRoutine.ofRoutine, FiniteRoutine.Runs,
+ List.length_cons, List.flatMap_cons, List.reverse_cons, packedTable, List.flatMap_append, List.flatMap_nil,
+ List.append_nil, List.append_assoc] using h
+
+/-- All rows of the exponent table are converted by the same finite code.
+The input suffix, the original divisor and the width counter are preserved.
+All intermediate stacks are empty on return. -/
+theorem radixRows_runs {z : ℕ} (rows : List (BurstRAM.Word z)) (suffix d acc : List Bool) (hq : 2 ≤ value d) :
+ radixRows.Runs (rowsTicks rows.length z d.length) (ready rows.length z (packedInput rows ++ suffix) d acc)
+ (ready 0 z suffix d (packedTable d.length (value d) rows ++ acc)) := by
+ simpa only [packedInput, List.length_reverse, List.reverse_reverse] using loop_runs rows.reverse suffix d acc hq
+
+@[simp] theorem packedTable_length {z : ℕ} (w Q : ℕ) (rows : List (BurstRAM.Word z)) :
+ (packedTable w Q rows).length = rows.length * (z*w) := by
+ induction rows with
+ | nil => simp [packedTable]
+ | cons x xs ih =>
+ simp only [packedTable, List.flatMap_cons, List.length_append, EvaluatorRadixDivision.encodedDigits_length,
+ List.length_cons, Nat.succ_mul]
+ rw [← packedTable, ih, Nat.add_comm]
+
+private theorem drop_field {A : Type*} (f : A → List Bool) (w : ℕ) (hw : ∀ a, (f a).length = w)
+ (xs : List A) (tail : List Bool) (i : ℕ) (hi : i < xs.length) :
+ ((xs.flatMap f ++ tail).drop (i*w)) =
+ f xs[i] ++ ((xs.drop (i+1)).flatMap f ++ tail) := by
+ induction xs generalizing i with
+ | nil => simp at hi
+ | cons a xs ih =>
+ cases i with
+ | zero => simp
+ | succ i =>
+ simp only [List.flatMap_cons, List.append_assoc, Nat.succ_mul, List.getElem_cons_succ]
+ rw [show i*w+w = (f a).length + i*w by rw [hw, Nat.add_comm], List.drop_length_add_append]
+ exact ih i (by simpa using hi)
+
+private theorem encodedDigits_cell (w Q z e : ℕ) (suffix : List Bool) (j : ℕ) (hj : j < z) :
+ (((encodedDigits w Q z e ++ suffix).drop (j*w)).take w) =
+ PrimedCounter.digits w (e / Q ^ (z-1-j) % Q) := by
+ let fields := EvaluatorRadixDivision.radixDigits Q z e
+ have hlen : fields.length = z := by simp [fields, EvaluatorRadixDivision.radixDigits_eq]
+ have hi : j < fields.length := hlen.symm ▸ hj
+ have hbits (n : ℕ) : (PrimedCounter.digits w n).length = w := by simp [PrimedCounter.digits]
+ have hval : fields[j] = e / Q ^ (z-1-j) % Q := by
+ simp [fields, EvaluatorRadixDivision.radixDigits_eq, List.getElem_reverse]
+ change (((fields.flatMap (PrimedCounter.digits w) ++ suffix).drop (j*w)).take w) = _
+ rw [drop_field _ w hbits fields suffix j hi, List.take_append_of_le_length (hbits fields[j]).ge,
+ List.take_of_length_le (hbits fields[j]).le, hval]
+
+/-- Lookup at row `i`, column `j` returns the encoded digit for power
+`z - 1 - j`. The suffix can carry any data already on the table stack. -/
+theorem packedTable_cell {z : ℕ} (w Q : ℕ) (rows : List (BurstRAM.Word z)) (suffix : List Bool)
+ (i j : ℕ) (hi : i < rows.length) (hj : j < z) :
+ (((packedTable w Q rows ++ suffix).drop ((i*z+j)*w)).take w) =
+ PrimedCounter.digits w (rows[i].val / Q ^ (z-1-j) % Q) := by
+ let f (a : BurstRAM.Word z) := encodedDigits w Q z a.val
+ have hlen (a : BurstRAM.Word z) : (f a).length = z*w := EvaluatorRadixDivision.encodedDigits_length ..
+ have h := drop_field f (z*w) hlen rows suffix i hi
+ change (((rows.flatMap f ++ suffix).drop ((i*z+j)*w)).take w) = _
+ rw [Nat.add_mul, Nat.mul_assoc, ← List.drop_drop, h]
+ exact encodedDigits_cell w Q z rows[i].val _ j hj
+
+@[simp] theorem packedInput_length {z : ℕ} (rows : List (BurstRAM.Word z)) :
+ (packedInput rows).length = rows.length*z := by
+ simp [packedInput, List.length_flatMap]
+
+/-- Reversing the RAM's ascending, little-endian binary word stream puts
+both the rows and their bits into the input order of the conversion loop. -/
+theorem packedInput_eq_reverse {z : ℕ} (rows : List (BurstRAM.Word z)) :
+ packedInput rows = (rows.flatMap BurstRAM.wordBits).reverse := by
+ induction rows with
+ | nil => rfl
+ | cons x xs ih =>
+ simpa only [packedInput, List.reverse_cons, List.flatMap_append, List.flatMap_cons,
+ List.flatMap_nil, List.append_nil, List.reverse_append] using
+ congrArg (· ++ (BurstRAM.wordBits x).reverse) ih
+
+/-- Entry point when the RAM's binary exponents are already on a separate
+stack in increasing label order. The saved-candidate stack of the division
+kernel is available to receive this stream before the first divide. -/
+def nativeRows : FiniteRoutine Port :=
+ (reverseOnto (.radix (.word .original)) .input).followedBy radixRows
+
+theorem nativeRows_runs {z : ℕ} (rows : List (BurstRAM.Word z)) (suffix d acc : List Bool) (hq : 2 ≤ value d) :
+ nativeRows.Runs (2*(rows.length*z)+1+rowsTicks rows.length z d.length)
+ (Function.update (ready rows.length z suffix d acc) (.radix (.word .original))
+ (rows.flatMap BurstRAM.wordBits))
+ (ready 0 z suffix d (packedTable d.length (value d) rows ++ acc)) := by
+ let src : Port := .radix (.word .original)
+ let s := Function.update (ready rows.length z suffix d acc) src (rows.flatMap BurstRAM.wordBits)
+ let u := ready rows.length z (packedInput rows ++ suffix) d acc
+ have h₁ := reverseOnto_runs (src := src) (dst := Port.input) (by decide) s u rfl
+ (show packedInput rows ++ suffix = (rows.flatMap BurstRAM.wordBits).reverse ++ suffix by
+ rw [packedInput_eq_reverse]) (by
+ intro k hk hk'
+ cases k with
+ | input => exact (hk' rfl).elim
+ | rowCount | width => rfl
+ | radix p => cases p with
+ | rounds | digits => rfl
+ | word j => cases j <;> first | rfl | exact (hk rfl).elim)
+ have ht : (s src).length = rows.length*z := by
+ simpa only [s, Function.update_self, packedInput_eq_reverse, List.length_reverse] using packedInput_length rows
+ rw [ht] at h₁
+ exact h₁.followedBy (radixRows_runs rows suffix d acc hq)
+
+/-- Conversion directly from the serialized exponent array on a cut, using
+the same word-array equivalence as the RAM transcript. -/
+theorem native_array_runs {k z : ℕ} (e : Fin k → BurstRAM.Word z) (suffix d acc : List Bool)
+ (hq : 2 ≤ value d) :
+ nativeRows.Runs (2*(k*z)+1+rowsTicks k z d.length)
+ (Function.update (ready k z suffix d acc) (.radix (.word .original))
+ (List.ofFn (RAMSerialization.arrayBits k z e)))
+ (ready 0 z suffix d (packedTable d.length (value d) (List.ofFn e) ++ acc)) := by
+ have he := SuccessorFields.raw_eq_flatten_words (RAMSerialization.arrayBits k z e)
+ simp only [Equiv.symm_apply_apply] at he
+ simpa only [List.length_ofFn, he, List.flatMap_def, List.map_ofFn, Function.comp_def] using
+ nativeRows_runs (List.ofFn e) suffix d acc hq
+
+/-- Peak total bit storage during the whole table conversion is polynomial in
+the number of labels and the two binary widths. The input suffix and any
+previously accumulated digits are included in the bound. -/
+theorem radixRows_space {z : ℕ} (rows : List (BurstRAM.Word z)) (suffix d acc : List Bool) (hq : 2 ≤ value d)
+ {n : ℕ} {q : Option radixRows.State} {u : Stacks Port}
+ (run : StackRuns radixRows.body.standalone n (some radixRows.body.entry)
+ (ready rows.length z (packedInput rows ++ suffix) d acc) q u) :
+ ∑ k, (u k).length ≤ 13 * (rows.length + z + rows.length*z + suffix.length + d.length + acc.length +
+ rowsTicks rows.length z d.length) := by
+ have hn := EvaluatorRadixDivision.ticks_le_at_return (radixRows_runs rows suffix d acc hq) (by rfl) run
+ have bound (k : Port) :
+ (u k).length ≤ rows.length + z + rows.length*z + suffix.length + d.length + acc.length +
+ rowsTicks rows.length z d.length := by
+ have h := EvaluatorRadixDivision.run_length run k
+ have hi : (ready rows.length z (packedInput rows ++ suffix) d acc k).length ≤
+ rows.length + z + rows.length*z + suffix.length + d.length + acc.length := by
+ cases k with
+ | input | width | rowCount => simp +arith [ready, frame]
+ | radix p => cases p with
+ | rounds | digits => simp [ready, frame, EvaluatorRadixDivision.bank]
+ | word j => cases j <;> simp +arith [ready, frame, EvaluatorRadixDivision.bank, DivisionStack.Data.stacks]
+ omega
+ calc
+ ∑ k, (u k).length ≤ ∑ _ : Port, (rows.length + z + rows.length*z + suffix.length + d.length + acc.length +
+ rowsTicks rows.length z d.length) := Finset.sum_le_sum (fun k _ => bound k)
+ _ = _ := by simp [show Fintype.card Port = 13 by decide]
+
+end EvaluatorRadixRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorRadixSpace.lean b/lean/OAI/Computability/VPVNP/EvaluatorRadixSpace.lean
new file mode 100644
index 0000000000..520749a5f4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorRadixSpace.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.EvaluatorRadixDivision
+
+/-!
+# Peak storage of the radix conversion
+
+The exponent, divisor and requested number of rounds are all encoded on
+stacks. Every instruction uses at most one additional bit. The exact
+polynomial clock therefore gives a polynomial storage bound at every
+intermediate point, including storage of the compact output digits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorRadixDivision
+
+open RAMTape TapeWord
+
+section Runs
+
+variable {K Q : Type*} [DecidableEq K] {code : StackCode K Q}
+
+private theorem step_unique {q r r' : Q} {s u u' : Stacks K} (h : StackStep code q s r u)
+ (h' : StackStep code q s r' u') : r = r' ∧ u = u' := by
+ cases h <;> cases h' <;> simp_all
+
+theorem ticks_le_at_return {q r v : Q} {s out u : Stacks K} {m n : ℕ}
+ (done : StackRuns code m q s r out) (halt : (code r).returns = true)
+ (prefixRun : StackRuns code n q s v u) : n ≤ m := by
+ induction done generalizing n with
+ | nil =>
+ cases prefixRun with
+ | nil => exact le_rfl
+ | cons h _ => cases h <;> simp_all
+ | cons h _ ih =>
+ cases prefixRun with
+ | nil => exact Nat.zero_le _
+ | cons h' tail =>
+ obtain ⟨rfl, rfl⟩ := step_unique h h'
+ exact Nat.succ_le_succ (ih halt tail)
+
+private theorem step_length {q r : Q} {s u : Stacks K} (run : StackStep code q s r u) (k : K) :
+ (u k).length ≤ (s k).length + 1 := by
+ cases run with
+ | goto => omega
+ | push _ =>
+ rename_i i b h
+ by_cases hi : k = i <;> simp [Function.update, hi]
+ | pop _ =>
+ rename_i i f h
+ by_cases hi : k = i <;> simp [Function.update, hi]
+ omega
+
+theorem run_length {q r : Q} {s u : Stacks K} {n : ℕ} (run : StackRuns code n q s r u)
+ (k : K) : (u k).length ≤ (s k).length + n := by
+ induction run with
+ | nil => simp
+ | cons h _ ih =>
+ have hs := step_length h k
+ omega
+
+end Runs
+
+/-- The bound holds for every intermediate configuration reached by the
+routine. It depends on the divisor only through the length of its input
+encoding. There are ten physical bit stacks. -/
+theorem radixRoutine_space (rounds : ℕ) (x d acc : List Bool) (hd : 0 < value d)
+ {n : ℕ} {q : Option radixRoutine.State} {u : Stacks Port}
+ (run : StackRuns radixRoutine.body.standalone n (some radixRoutine.body.entry)
+ (ready rounds x d acc) q u) :
+ ∑ k, (u k).length ≤
+ 10 * (rounds + x.length + d.length + acc.length + radixTicks rounds x.length d.length) := by
+ have hn := ticks_le_at_return (radixRoutine_runs rounds x d acc hd) (by rfl) run
+ have bound (k : Port) :
+ (u k).length ≤ rounds + x.length + d.length + acc.length + radixTicks rounds x.length d.length := by
+ have hs := run_length run k
+ have hi : (ready rounds x d acc k).length ≤ rounds + x.length + d.length + acc.length := by
+ cases k with
+ | rounds | digits => simp [ready, bank] <;> omega
+ | word j => cases j <;> simp [ready, bank, DivisionStack.Data.stacks] <;> omega
+ omega
+ calc
+ ∑ k, (u k).length ≤ ∑ _ : Port, (rounds + x.length + d.length + acc.length + radixTicks rounds x.length d.length) :=
+ Finset.sum_le_sum (fun k _ => bound k)
+ _ = _ := by simp [show Fintype.card Port = 10 by decide]
+
+end EvaluatorRadixDivision
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorReadInterface.lean b/lean/OAI/Computability/VPVNP/EvaluatorReadInterface.lean
new file mode 100644
index 0000000000..b5acbd19e2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorReadInterface.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.EvaluatorMatrixCallbacks
+
+/-!
+# Coordinate-reader interface for the binary evaluator
+
+The deterministic entry query takes the previous and chosen basis ordinals
+in canonical binary registers. Its output is a packed element in the advised
+field basis. This interface isolates the indexed Macaulay and Cramer computation
+from the nondeterministic choices, finite-field multiplication and digit loops.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.MatrixCallbacks
+
+open RAMTape SliceArithmetic EvaluatorRoutine EvaluatorDigitFetch EvaluatorMonomialSchedule
+open EvaluatorScheduleEffects
+
+variable {P : Type} [DecidableEq P] {p e w v : ℕ} [Fact p.Prime]
+ {K : Type} [Field K] [Algebra (ZMod p) K] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (dim : BurstRAM.Word v) (extra : Stacks P)
+
+/-- Encoded current ordinal and scalar, between two successive linear steps. -/
+noncomputable def payload (w : ℕ) (s : Fin dim.val × K) : Stacks (WeightedStep.Port P) :=
+ WeightedStep.bank φ w dim s.1 [] [] s.2 extra
+
+/-- Deterministic finite-control entry query with a common time bound. It
+restores the ordinal registers, the advised field and the caller's private
+workspace. Its only output is the requested matrix entry. -/
+def ReadsEntry (read : FiniteRoutine (ReadPort P)) (w label time : ℕ)
+ (matrix : Matrix (Fin dim.val) (Fin dim.val) K) : Prop :=
+ ∀ (s : Fin dim.val × K) (j : Fin dim.val), ∃ d ≤ time, read.Runs d
+ (queryBank (List.replicate label true) (WeightedStep.bank φ w dim s.1
+ (BurstRAM.wordBits (Fin.castLE dim.isLt.le j : BurstRAM.Word v)) [] s.2 extra))
+ (queryBank (List.replicate label true) (WeightedStep.bank φ w dim s.1
+ (BurstRAM.wordBits (Fin.castLE dim.isLt.le j : BurstRAM.Word v))
+ (WeightedStep.bits φ w (matrix s.1 j)) s.2 extra))
+
+private theorem count_fixed_frame (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (read : FiniteRoutine (ReadPort P)) (label time : ℕ)
+ (matrix : Matrix (Fin dim.val) (Fin dim.val) K)
+ (hr : ReadsEntry φ dim extra read w label time matrix)
+ (frame : Stacks (WeightedStep.Port P) → Stacks (Host P))
+ (hwork : ∀ s k, frame s (.work k) = s k)
+ (hlabel : ∀ s, frame s (.addr .labelIndex) = List.replicate label true)
+ (hrest : ∀ x y k, (∀ j, EvaluatorDigitFetch.Port.work j ≠ k) → frame x k = frame y k)
+ (s : Fin dim.val × K) (fuel : ℕ) (hfuel : WeightedStep.ticks v e w time ≤ fuel) :
+ ∃ delay : Fin dim.val → ℕ, (∀ j, delay j ≤ WeightedStep.ticks v e w time) ∧ ∀ cont,
+ (machine read).body.count cont fuel (frame (payload φ dim extra w s)) =
+ ∑ j, cont (fuel-delay j) (frame (payload φ dim extra w (j, s.2 * matrix s.1 j))) := by
+ let ambient := frame (payload φ dim extra w s)
+ have hi (x) : installStacks EvaluatorDigitFetch.Port.work ambient x = frame x :=
+ installStacks_frame (fun _ _ h ↦ EvaluatorDigitFetch.Port.work.inj h) (hwork x) (hrest x _)
+ obtain ⟨d, hd, hc⟩ := count_callback φ dim extra he hw read ambient matrix s.1 s.2 time
+ (fun j ↦ by dsimp only [ambient]; rw [hlabel]; exact hr s j) fuel hfuel
+ exact ⟨d, hd, fun cont ↦ by simpa only [hi, payload] using hc cont⟩
+
+variable {A : Type} [CommRing A] [Algebra K A] [Fintype K] {t Z : ℕ}
+ (b : Module.Basis (Fin dim.val) K A) (X : Fin t → A) (es : Fin t → BurstRAM.Word Z) (d : List Bool)
+
+local notation "data" => EvaluatorRadixRows.packedTable d.length (TapeWord.value d) (List.ofFn es)
+local notation "next" => nextIndex b X
+local notation "pay" => payload φ dim extra w
+local notation "M" => LinearMap.toMatrixAlgEquiv b
+
+/-- Installing a Frobenius entry query gives the counted Frobenius callback
+on every column, with the column and digit scheduler registers preserved. -/
+theorem frobenius_realizes (he : 0 < e) (hw : Word.workingWidth p ≤ w) (read : FiniteRoutine (ReadPort P))
+ (time : ℕ) (hr : ReadsEntry φ dim extra read w 0 time
+ (M (FiniteField.frobeniusAlgHom K A).toLinearMap).transpose) (j : Fin Z) (left : ℕ) :
+ Realizes (machine read).body (fun x ↦ bank data t Z d.length 0 j 0 left (pay x))
+ (fun x ↦ bank data t Z d.length 0 j 0 left (pay x)) (WeightedStep.ticks v e w time)
+ (stepEffect next none) := by
+ apply Realizes.of_delay
+ intro x fuel hf
+ apply count_fixed_frame φ dim extra he hw read 0 time _ hr
+ (bank data t Z d.length 0 j 0 left) (fun _ _ ↦ rfl) (fun _ ↦ rfl) _ x fuel hf
+ intro x y k hk
+ cases k <;> first | rfl | exact (hk _ rfl).elim
+
+/-- Installing the formal-coordinate multiplication query gives the label
+callback on all live label ordinals, including repeated visits in a digit. -/
+theorem label_callback (he : 0 < e) (hw : Word.workingWidth p ≤ w) (read : FiniteRoutine (ReadPort P))
+ (time : ℕ) (hr : ∀ i : Fin t, ReadsEntry φ dim extra read w i.val time
+ (M (LinearMap.mulLeft K (X i))).transpose) :
+ LabelCallback es d.length (TapeWord.value d) (WeightedStep.ticks v e w time) pay next (machine read) := by
+ intro i j labels cols x bits fuel _hf enough
+ let frame (s : Stacks (WeightedStep.Port P)) := EvaluatorDigitRepeat.frame
+ EvaluatorDigitFetch.Port.digit EvaluatorDigitFetch.Port.borrow (bank data t Z d.length i j labels cols s) bits []
+ have h := count_fixed_frame φ dim extra he hw read i.val time _ (hr i) frame
+ (fun _ _ ↦ rfl) (fun _ ↦ rfl) (fun x y k hk ↦ by
+ cases k <;> first | rfl | exact (hk _ rfl).elim) x fuel enough
+ simpa only [nextIndex, indexTransition, dite_eq_left i.isLt, Matrix.transpose_apply, frame] using h
+
+end Evaluator.MatrixCallbacks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorRepeatedEffect.lean b/lean/OAI/Computability/VPVNP/EvaluatorRepeatedEffect.lean
new file mode 100644
index 0000000000..f77c66e659
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorRepeatedEffect.lean
@@ -0,0 +1,42 @@
+import Mathlib.Data.Fintype.BigOperators
+import Mathlib.Data.List.OfFn
+
+/-! # Summing the traces of repeated evaluator transitions -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorScheduleEffects
+
+variable {S I : Type*} [Fintype I]
+
+/-- Sum the continuation over the choices of one linear step. -/
+def stepEffect (next : Option ℕ → S → I → S) (a : Option ℕ) (f : S → ℕ) (s : S) : ℕ :=
+ ∑ o : I, f (next a s o)
+
+/-- Sum over the choice traces of all repetitions of the same linear step. -/
+def repeatEffect (next : Option ℕ → S → I → S) (a : Option ℕ) (d : ℕ) (f : S → ℕ) (s : S) : ℕ :=
+ ∑ z : Fin d → I, f ((List.ofFn z).foldl (next a) s)
+
+/-- Folding the step effects in chronological order counts each trace once. -/
+theorem repeatEffect_eq_foldr (next : Option ℕ → S → I → S) (a : Option ℕ) (d : ℕ)
+ (f : S → ℕ) (s : S) :
+ repeatEffect next a d f s = (List.replicate d a).foldr (stepEffect next) f s := by
+ induction d generalizing s with
+ | zero => simp [repeatEffect]
+ | succ d ih =>
+ let wt (z : Fin (d+1) → I) := f ((List.ofFn z).foldl (next a) s)
+ change (∑ z, wt z) = _
+ rw [← (Fin.consEquiv (fun _ : Fin (d+1) => I)).sum_comp wt, Fintype.sum_prod_type,
+ List.replicate_succ, List.foldr_cons]
+ apply Finset.sum_congr rfl
+ intro o _
+ simpa only [wt, repeatEffect, Fin.consEquiv_apply, List.ofFn_succ, Fin.cons_zero, Fin.cons_succ,
+ List.foldl_cons] using ih (next a s o)
+
+end EvaluatorScheduleEffects
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorRoutine.lean b/lean/OAI/Computability/VPVNP/EvaluatorRoutine.lean
new file mode 100644
index 0000000000..c3d5a381a4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorRoutine.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.EvaluatorMatrixStep
+
+/-! # Composition of time-bounded evaluator routines
+
+A routine realizes a transition when any continuation with a reserved amount
+of fuel returns the prescribed count on the resulting states. This permits
+different branches to use different numbers of instructions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorRoutine
+
+open RAMTape
+
+variable {K Q R S T U I : Type*} [DecidableEq K]
+
+/-- The caller reserves `extra` instructions after the routine's per-path
+bound `B`. Its count on each encoded output determines the whole transition. -/
+def Realizes (r : Routine K Q) (pre : S → Stacks K) (post : T → Stacks K)
+ (B : ℕ) (effect : (T → ℕ) → S → ℕ) : Prop :=
+ ∀ (extra fuel : ℕ), extra + B ≤ fuel → ∀ (x : S) (f : T → ℕ) (c : ℕ → Stacks K → ℕ),
+ (∀ y k, extra ≤ k → c k (post y) = f y) → r.count c fuel (pre x) = effect f x
+
+variable {r : Routine K Q} {r' : Routine K R} {pre : S → Stacks K} {mid : T → Stacks K}
+ {post : U → Stacks K} {B B' : ℕ} {e : (T → ℕ) → S → ℕ} {e' : (U → ℕ) → T → ℕ}
+
+theorem Realizes.mono (h : Realizes r pre mid B e) (hB : B ≤ B') :
+ Realizes r pre mid B' e :=
+ fun extra fuel hf => h extra fuel ((Nat.add_le_add_left hB _).trans hf)
+
+theorem Realizes.followedBy (ha : Realizes r pre mid B e) (hb : Realizes r' mid post B' e') :
+ Realizes (r.followedBy r') pre post (B+B') (fun f x => e (e' f) x) := by
+ intro extra fuel hf x f c hc
+ rw [Routine.count_followedBy]
+ apply ha (extra+B') fuel (by omega)
+ intro y left hl
+ exact hb extra left hl y f c hc
+
+/-- A deterministic prefix spends its actual cost and preserves one branch. -/
+theorem Realizes.of_runs {g : S → T} (h : ∀ x, ∃ d ≤ B, r.Runs d (pre x) (mid (g x))) :
+ Realizes r pre mid B (fun f x => f (g x)) := by
+ intro extra fuel hf x f c hc
+ obtain ⟨d, hd, hr⟩ := h x
+ have he := hr.count_eq c (fuel-d)
+ rw [Nat.sub_add_cancel (by omega)] at he
+ exact he.trans (hc _ _ (by omega))
+
+/-- Bounded delays on a finite family of outcomes establish a transition
+whose multiplicity is their ordinary sum. -/
+theorem Realizes.of_delay [Fintype I] {next : S → I → T}
+ (h : ∀ x fuel, B ≤ fuel → ∃ d : I → ℕ, (∀ i, d i ≤ B) ∧ ∀ c,
+ r.count c fuel (pre x) = ∑ i, c (fuel-d i) (mid (next x i))) :
+ Realizes r pre mid B (fun f x => ∑ i, f (next x i)) := by
+ intro extra fuel hf x f c hc
+ obtain ⟨d, hd, he⟩ := h x fuel (by omega)
+ rw [he]
+ exact Finset.sum_congr rfl fun i _ => hc _ _ (by have := hd i; omega)
+
+end EvaluatorRoutine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorRoutineFrame.lean b/lean/OAI/Computability/VPVNP/EvaluatorRoutineFrame.lean
new file mode 100644
index 0000000000..9e2ec2b6f4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorRoutineFrame.lean
@@ -0,0 +1,46 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-! # Framing nondeterministic evaluator callbacks
+
+Renaming a returning routine into a larger bank of stacks leaves every other
+stack available to the scheduler. Each binary choice retains its two slots,
+and the continuation receives the residual fuel on that particular path.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.FiniteRoutine
+
+variable {K L : Type} [DecidableEq K] [DecidableEq L]
+
+/-- Exact continuation semantics on a disjoint set of named ports. -/
+theorem countFrom_onPorts (r : FiniteRoutine K) (ports : K → L) (hp : Function.Injective ports)
+ (base : Stacks L) (c : ℕ → Stacks L → ℕ) (n : ℕ) (q : Option r.State) (s : Stacks K) :
+ (r.onPorts ports).body.countFrom c n q (installStacks ports base s) =
+ r.body.countFrom (fun fuel out => c fuel (installStacks ports base out)) n q s := by
+ induction n generalizing q s with
+ | zero => cases q <;> rfl
+ | succ n ih =>
+ cases q with
+ | none => rfl
+ | some q =>
+ simp only [Routine.countFrom]
+ have hcode : (r.onPorts ports).body.code q = (r.body.code q).rename ports id := rfl
+ rw [hcode]
+ cases r.body.code q <;> simp [installStacks_at hp, installStacks_update hp, ih]
+
+/-- The entry point of a framed routine can be invoked from an arbitrary caller state. -/
+theorem count_onPorts (r : FiniteRoutine K) (ports : K → L) (hp : Function.Injective ports)
+ (base : Stacks L) (c : ℕ → Stacks L → ℕ) (n : ℕ) :
+ (r.onPorts ports).body.count c n base =
+ r.body.count (fun fuel out => c fuel (installStacks ports base out)) n (base ∘ ports) := by
+ have h := countFrom_onPorts r ports hp base c n (some r.body.entry) (base ∘ ports)
+ rwa [installStacks_eq hp base (base ∘ ports) (fun _ => rfl)] at h
+
+end RAMTape.FiniteRoutine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorRoutineSafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorRoutineSafety.lean
new file mode 100644
index 0000000000..43a43fd4a8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorRoutineSafety.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.StructuredStackSafe
+import OAI.Computability.VPVNP.EvaluatorRadixSpace
+
+/-! # Time and space contracts for evaluator routines
+
+A caller may reserve a continuation after a subroutine's clock bound. Every
+branch either halts inside the subroutine or returns with an encoded output
+and the reserved clock. The space predicate holds at every active instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorRoutineSafety
+
+open RAMTape
+
+variable {K Q R S T U : Type*} [DecidableEq K]
+
+/-- A routine contract that maintains the stack safety predicate at active instructions and
+preserves the caller's reserved fuel upon a normal return. -/
+def Bounded (r : Routine K Q) (safe : Stacks K → Prop)
+ (pre : S → Stacks K) (post : T → Stacks K) (B : ℕ) : Prop :=
+ ∀ (extra fuel : ℕ), extra+B ≤ fuel → ∀ (x : S) (cont : ℕ → Stacks K → Prop),
+ (∀ y k, extra ≤ k → cont k (post y)) → r.Safe safe cont fuel (pre x)
+
+variable {r : Routine K Q} {r' : Routine K R} {safe : Stacks K → Prop}
+ {pre : S → Stacks K} {mid : T → Stacks K} {post : U → Stacks K} {B B' : ℕ}
+
+theorem Bounded.mono (h : Bounded r safe pre mid B) (hB : B ≤ B') :
+ Bounded r safe pre mid B' :=
+ fun extra fuel hf => h extra fuel ((Nat.add_le_add_left hB _).trans hf)
+
+theorem Bounded.followedBy (ha : Bounded r safe pre mid B) (hb : Bounded r' safe mid post B') :
+ Bounded (r.followedBy r') safe pre post (B+B') := by
+ intro extra fuel hf x c hc
+ rw [Routine.safe_followedBy]
+ apply ha (extra+B') fuel (by omega)
+ intro y left hl
+ exact hb extra left hl y c hc
+
+private theorem safe_of_run {r : Routine K Q} {n : ℕ} {q : Option Q} {s out : Stacks K}
+ (h : StackRuns r.standalone n q s none out) (fuel : ℕ) (cont : ℕ → Stacks K → Prop)
+ (hcont : cont fuel out) (prefixSafe : ∀ a (v : Q) u,
+ StackRuns r.standalone a q s (some v) u → safe u) :
+ r.SafeFrom safe cont (fuel+n) q s := by
+ generalize hv : (none : Option Q) = target at h
+ induction h with
+ | nil =>
+ rw [← hv]
+ simpa using hcont
+ | @cons q₀ s₀ q₁ s₁ q₂ s₂ n hs tail ih =>
+ have later := ih hcont (fun a v u hrun => prefixSafe (a+1) v u (.cons hs hrun)) hv
+ cases q₀ with
+ | none => cases hs <;> contradiction
+ | some q =>
+ have now := prefixSafe 0 q s₀ (.nil ..)
+ cases hs with
+ | push h | pop h | goto h =>
+ change r.code q = _ at h
+ simp only [Routine.SafeFrom, h]
+ exact ⟨now, later⟩
+
+/-- A deterministic prefix satisfies the all-branch contract when every
+intermediate active state satisfies the storage invariant. -/
+theorem Bounded.of_runs {g : S → T} (h : ∀ x, ∃ d ≤ B, r.Runs d (pre x) (mid (g x)))
+ (hspace : ∀ x n (q : Q) s, StackRuns r.standalone n (some r.entry) (pre x) (some q) s → safe s) :
+ Bounded r safe pre mid B := by
+ intro extra fuel hf x cont hc
+ obtain ⟨d, hd, hr⟩ := h x
+ have hh := safe_of_run hr (fuel-d) cont (hc _ _ (by omega)) (hspace x)
+ simpa only [Nat.sub_add_cancel (show d ≤ fuel by omega)] using hh
+
+/-- An explicit polynomial clock on a deterministic call also bounds the
+increase in the length of each stack along every prefix. -/
+theorem Bounded.of_runs_with_room {g : S → T}
+ (h : ∀ x, ∃ d ≤ B, r.Runs d (pre x) (mid (g x)))
+ (hroom : ∀ x s, (∀ k, (s k).length ≤ (pre x k).length+B) → safe s) :
+ Bounded r safe pre mid B := by
+ apply Bounded.of_runs h
+ intro x n q s prefixRun
+ obtain ⟨d, hd, hr⟩ := h x
+ have hn := EvaluatorRadixDivision.ticks_le_at_return hr (by rfl) prefixRun
+ exact hroom x s fun k => (EvaluatorRadixDivision.run_length prefixRun k).trans
+ (Nat.add_le_add_left (hn.trans hd) _)
+
+end EvaluatorRoutineSafety
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorSafetyTransfer.lean b/lean/OAI/Computability/VPVNP/EvaluatorSafetyTransfer.lean
new file mode 100644
index 0000000000..3fb8048179
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorSafetyTransfer.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.EvaluatorRoutineSafety
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-!
+# Storage bounds for short branches and streamed queries
+
+A short nondeterministic routine can increase a stack by at most its instruction
+count. A deterministic long-running subroutine instead supplies the independent
+peak bound along its actual run.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorRoutineSafety
+
+open RAMTape UniversalCountStack
+
+variable {K Q : Type*} [DecidableEq K] {r : Routine K Q}
+
+/-- Add a reserved continuation clock and a peak bound to a short all-path
+execution. Only the routine's own instruction count is charged to its storage. -/
+theorem safe_of_allStops {safe : Stacks K → Prop} (cont : ℕ → Stacks K → Prop)
+ {n : ℕ} (reserve : ℕ) {q : Option Q} {s : Stacks K}
+ (h : r.AllStopsFrom (fun left out ↦ cont (reserve+left) out) n q s)
+ (hroom : ∀ u, (∀ k, (u k).length ≤ (s k).length+n) → safe u) :
+ r.SafeFrom safe cont (reserve+n) q s := by
+ induction n generalizing q s with
+ | zero =>
+ cases q with
+ | none => simpa only [Routine.safeFrom_none, Routine.allStopsFrom_none, Nat.add_zero] using h
+ | some q => exact False.elim h
+ | succ n ih =>
+ cases q with
+ | none => simpa only [Routine.safeFrom_none, Routine.allStopsFrom_none] using h
+ | some q =>
+ rw [Nat.add_succ, Routine.SafeFrom]
+ refine ⟨hroom s (by intro k; omega), ?_⟩
+ rw [Routine.AllStopsFrom] at h
+ cases he : r.code q <;> rw [he] at h
+ case push k b next =>
+ apply ih h
+ intro u hu
+ apply hroom u
+ intro j
+ by_cases hj : j = k <;> simpa [hj] using (show _ ≤ _ from
+ (hu j).trans (by simp [hj] <;> omega))
+ case pop k next =>
+ apply ih h
+ intro u hu
+ apply hroom u
+ intro j
+ by_cases hj : j = k <;> simpa [hj] using (show _ ≤ _ from
+ (hu j).trans (by simp [hj] <;> omega))
+ case goto =>
+ exact ih h fun u hu ↦ hroom u fun k ↦ by have := hu k; omega
+ case choose =>
+ exact ⟨ih h.1 fun u hu ↦ hroom u fun k ↦ by have := hu k; omega,
+ ih h.2 fun u hu ↦ hroom u fun k ↦ by have := hu k; omega⟩
+ case halt => trivial
+
+private theorem safe_of_space_run {cap n q s out} {cont : ℕ → Stacks K → Prop}
+ (run : SpaceRun r.standalone cap n q s none out) (extra : ℕ) (hc : cont extra out) :
+ r.SafeFrom (fun u ↦ ∀ k, (u k).length ≤ cap) cont (extra+n) q s := by
+ generalize eq : (none : Option Q) = t at run
+ induction run with
+ | nil => rw [← eq]; simpa using hc
+ | @cons q _ q' _ _ _ _ hs st _ ih =>
+ cases q with
+ | none => cases st <;> contradiction
+ | some q =>
+ cases st with
+ | push h | pop h | goto h =>
+ change r.code q = _ at h
+ rw [Nat.add_succ, Routine.SafeFrom, h]
+ exact ⟨hs, ih hc eq⟩
+
+/-- A deterministic, space-bounded coordinate query satisfies the scheduler's
+all-path contract even when the query time is exponential. -/
+theorem Bounded.of_space_runs {S T : Type*} {pre : S → Stacks K} {post : T → Stacks K}
+ {g : S → T} {B cap : ℕ} (run : ∀ x, ∃ n ≤ B,
+ SpaceRun r.standalone cap n (some r.entry) (pre x) none (post (g x))) :
+ Bounded r (fun u ↦ ∀ k, (u k).length ≤ cap) pre post B := by
+ intro reserve fuel hf x cont hc
+ obtain ⟨n, hn, hr⟩ := run x
+ have h := safe_of_space_run hr (fuel-n) (hc _ _ (by omega))
+ rwa [Nat.sub_add_cancel (by omega)] at h
+
+end EvaluatorRoutineSafety
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorScheduleBudget.lean b/lean/OAI/Computability/VPVNP/EvaluatorScheduleBudget.lean
new file mode 100644
index 0000000000..9e1264d505
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorScheduleBudget.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.EvaluatorChronologicalLoop
+import OAI.Computability.VPVNP.EvaluatorDigitAction
+
+/-!
+# Time allowance for native radix conversion and the chronological scheduler
+
+The clock includes the initial reversal of the RAM's exponent array, the
+restoring divisions that prepare all digit rows, and the two nested tally
+loops. For fixed field, label count and callback allowances it is quadratic
+in the input exponent width. Polynomial growth of the callback allowances in
+that width is also permitted.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorScheduleBudget
+
+open EvaluatorRadixRows EvaluatorRadixDivision EvaluatorDigitAction EvaluatorChronologicalLoop
+
+/-- Exact deterministic preparation time followed by the scheduler's reserved
+clock. The two callback allowances cover one label and one Frobenius query. -/
+def scheduleBudget (t Z ℓ Q B BF : ℕ) :=
+ 2*(t*Z)+1+rowsTicks t Z ℓ + traverseBudget t Z BF (cellBudget t Z ℓ Q B)
+
+private def quadratic (t ℓ : ℕ) := t*(10*ℓ+10) + t^2*(19+13*ℓ)
+private def linear (t ℓ Q : ℕ) := t*(9*ℓ+31) + 7 + t*Q*(4*ℓ+3)
+private def constant (t : ℕ) := 5*t+4
+
+private theorem expand (t Z ℓ Q B BF : ℕ) :
+ scheduleBudget t Z ℓ Q B BF = quadratic t ℓ * Z^2 +
+ (linear t ℓ Q + t*Q*B + BF) * Z + constant t := by
+ unfold scheduleBudget rowsTicks rowTicks radixTicks digitTicks traverseBudget columnBudget
+ cellBudget quadratic linear constant
+ ring
+
+/-- A polynomial multiplier independent of the exponent width. -/
+def coefficient (t ℓ Q B BF : ℕ) :=
+ t*(10*ℓ+10) + t^2*(19+13*ℓ) + (t*(9*ℓ+31) + 7 + t*Q*(4*ℓ+3) + t*Q*B + BF) + (5*t+4)
+
+/-- Uniform in the exponent words and the chosen sequence of matrix indices. -/
+theorem scheduleBudget_le (t Z ℓ Q B BF : ℕ) :
+ scheduleBudget t Z ℓ Q B BF ≤ coefficient t ℓ Q B BF * (Z+1)^2 := by
+ have h₂ : Z^2 ≤ (Z+1)^2 := Nat.pow_le_pow_left (Nat.le_succ _) _
+ have h₁ : Z ≤ (Z+1)^2 := by rw [pow_two]; nlinarith
+ have h₀ : 1 ≤ (Z+1)^2 := Nat.pow_pos (Nat.succ_pos Z)
+ rw [expand]
+ calc
+ _ ≤ quadratic t ℓ * (Z+1)^2 + (linear t ℓ Q + t*Q*B + BF) * (Z+1)^2 +
+ constant t * (Z+1)^2 :=
+ Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ h₂) (Nat.mul_le_mul_left _ h₁))
+ (by simpa using Nat.mul_le_mul_left (constant t) h₀)
+ _ = _ := by simp only [coefficient, quadratic, linear, constant]; ring
+
+private theorem coefficient_le {t ℓ Q B BF E D : ℕ} (hE : 1 ≤ E) (hD : 1 ≤ D)
+ (ht : t ≤ E) (hℓ : ℓ ≤ E) (hQ : Q ≤ E) (hB : B ≤ E*D) (hF : BF ≤ E*D) :
+ coefficient t ℓ Q B BF ≤ 128*E^3*D := by
+ have hmono : coefficient t ℓ Q B BF ≤ coefficient E E E (E*D) (E*D) := by
+ unfold coefficient; gcongr
+ have hscale : coefficient E E E (E*D) (E*D) ≤ coefficient E E E E E * D := by
+ let fixed := quadratic E E + linear E E E + constant E
+ calc
+ _ = fixed + (E^3+E)*D := by dsimp [fixed, quadratic, linear, constant, coefficient]; ring
+ _ ≤ fixed*D + (E^3+E)*D := Nat.add_le_add_right (by simpa using Nat.mul_le_mul_left fixed hD) _
+ _ = coefficient E E E E E * D := by dsimp [fixed, quadratic, linear, constant, coefficient]; ring
+ have h₁ : E ≤ E^2 := by simpa [pow_two] using Nat.mul_le_mul_left E hE
+ have h₂ : E^2 ≤ E^3 := by simpa only [pow_succ E 2, Nat.mul_one] using Nat.mul_le_mul_left (E^2) hE
+ have hbase : coefficient E E E E E ≤ 128*E^3 := by
+ rw [show coefficient E E E E E = 18*E^3+41*E^2+47*E+11 by unfold coefficient; ring]
+ omega
+ exact hmono.trans (hscale.trans (Nat.mul_le_mul_right D hbase))
+
+/-- When all fixed parameters are at most `2^a` and callbacks take at most
+`2^a * (Z+1)^k`, the coefficient stays singly exponential in `a` and the
+degree in `Z` grows by at most two. The same `a` and `k` may be used across
+any collection of fields, dimensions or advice parameters with those bounds. -/
+theorem scheduleBudget_le_exp_poly (t Z ℓ Q B BF a k : ℕ)
+ (ht : t ≤ 2^a) (hℓ : ℓ ≤ 2^a) (hQ : Q ≤ 2^a)
+ (hB : B ≤ 2^a*(Z+1)^k) (hF : BF ≤ 2^a*(Z+1)^k) :
+ scheduleBudget t Z ℓ Q B BF ≤ 2^(3*a+7)*(Z+1)^(k+2) := by
+ have hc := coefficient_le (Nat.pow_pos (by decide)) (Nat.pow_pos (Nat.succ_pos Z)) ht hℓ hQ hB hF
+ calc
+ _ ≤ (128*(2^a)^3*(Z+1)^k)*(Z+1)^2 :=
+ (scheduleBudget_le ..).trans (Nat.mul_le_mul_right _ hc)
+ _ = _ := by rw [Nat.mul_comm 3 a, pow_add, pow_mul, pow_add]; ring
+
+end EvaluatorScheduleBudget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorScheduleCount.lean b/lean/OAI/Computability/VPVNP/EvaluatorScheduleCount.lean
new file mode 100644
index 0000000000..b6062fb441
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorScheduleCount.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.EvaluatorScheduleEffects
+import OAI.Computability.VPVNP.EvaluatorOutput
+
+/-!
+# The residue of the scheduler's actual index choices
+
+The continuation of the nested digit loops stores the current basis ordinal
+and the accumulated scalar. At termination its ordinary integer multiplicity
+is the constant-coordinate residue at the unit ordinal and zero elsewhere.
+Expanding the continuation over the chronological actions gives exactly the
+matrix-index paths of the finite algebra.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator
+
+open EvaluatorScheduleEffects EvaluatorDigitSchedule
+
+variable {I K A : Type*} [Fintype I] [DecidableEq I] [Field K] [Fintype K]
+ [CommRing A] [Algebra K A] {p : ℕ} [Fact p.Prime] [Algebra (ZMod p) K]
+ [Algebra (ZMod p) A] [IsScalarTower (ZMod p) K A] {t Z : ℕ}
+ (b : Module.Basis I K A) (unit : I) (coord : K →ₗ[ZMod p] ZMod p)
+
+/-- The endpoint test used by the terminal field reader. -/
+def finishWeight (s : I × K) : ℕ := if s.1 = unit then (coord s.2).val else 0
+
+/-- A transition multiplies the old accumulator by row `j`, column `s.1`
+of the current linear map. The index `j` is the next binary guess. -/
+noncomputable def indexTransition (M : A →ₗ[K] A) (s : I × K) (j : I) : I × K :=
+ (j, s.2 * (LinearMap.toMatrixAlgEquiv b M) j s.1)
+
+/-- The ordinal of a label is read from the scheduler's current unary counter.
+All live ordinal values are in range. -/
+noncomputable def nextIndex (X : Fin t → A) (op : Option ℕ) : I × K → I → I × K :=
+ indexTransition b (match op with
+ | none => (FiniteField.frobeniusAlgHom K A).toLinearMap
+ | some i => if hi : i < t then LinearMap.mulLeft K (X ⟨i,hi⟩) else 0)
+
+omit [Fintype K] in
+private theorem foldr_count (ms : List (Matrix I I K)) (s : I × K) :
+ ms.foldr (fun m f (q : I × K) ↦ ∑ j, f (j, q.2 * m q.1 j)) (finishWeight unit coord) s =
+ ∑ path : IndexPath.{_,0} I ms.length, (coord (s.2 * pathWeight ms s.1 unit path)).val := by
+ induction ms generalizing s with
+ | nil =>
+ change finishWeight unit coord s =
+ ∑ _ : PUnit, (coord (s.2 * (if s.1 = unit then 1 else 0))).val
+ by_cases he : s.1 = unit <;> simp [finishWeight, he]
+ | cons m ms ih =>
+ simp only [List.foldr_cons, ih]
+ change _ = ∑ path : I × IndexPath.{_,0} I ms.length,
+ (coord (s.2 * (m s.1 path.1 * pathWeight ms path.1 unit path.2))).val
+ rw [Fintype.sum_prod_type]
+ simp only [mul_assoc]
+
+omit [Algebra (ZMod p) A] [IsScalarTower (ZMod p) K A] in
+/-- The ordinary count of the nested digit loops is the number of accepting
+index paths with their final residue multiplicities. -/
+theorem schedulerEffect_eq_card (X : Fin t → A) (e : Fin t → BurstRAM.Word Z) :
+ schedulerEffect (nextIndex b X) e (Fintype.card K) (finishWeight unit coord) (unit,1) =
+ Fintype.card (AcceptingBranches.{_,_,0} coord
+ (transitionMatrices b (digitProgram K X Z (fun i ↦ (e i).val))) unit unit) := by
+ rw [schedulerEffect_eq_digitProgram K X (nextIndex b X)
+ (fun m f q ↦ ∑ j, f (indexTransition b m q j)) (by
+ intro op
+ funext f q
+ cases op <;> simp [stepEffect, actionCode, nextIndex, actionMap])]
+ let ms := digitProgram K X Z (fun i ↦ (e i).val)
+ have h := foldr_count unit coord (transitionMatrices b ms) (unit, 1)
+ unfold AcceptingBranches
+ rw [Fintype.card_sigma]
+ simp only [Fintype.card_fin]
+ simpa only [transitionMatrices, List.foldr_map, indexTransition, Matrix.transpose_apply,
+ one_mul, ms] using h
+
+/-- Equation (8.2) for the physical scheduler's ordinary path-count effect. -/
+theorem schedulerEffect_mod (hunit : b unit = 1) (X : Fin t → A) (e : Fin t → BurstRAM.Word Z) :
+ (schedulerEffect (nextIndex b X) e (Fintype.card K) (finishWeight unit coord) (unit,1) : ZMod p) =
+ primeFunctional b unit coord (∏ i, X i ^ (e i).val) := by
+ rw [schedulerEffect_eq_card]
+ exact finiteAlgebra_pathCount b unit hunit coord X Z _ (fun i ↦ (e i).isLt)
+
+end Evaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorScheduleEffects.lean b/lean/OAI/Computability/VPVNP/EvaluatorScheduleEffects.lean
new file mode 100644
index 0000000000..7da3e86080
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorScheduleEffects.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.EvaluatorStreamCount
+import OAI.Computability.VPVNP.EvaluatorRadixRows
+import OAI.Computability.VPVNP.EvaluatorRepeatedEffect
+
+/-!
+# Counting the matrix steps of the nested digit loops
+
+The machine loops over increasing column and label indices. Its table
+starts with the most significant base digit, so column `j` selects power
+`Z - 1 - j`. In each column the machine first chooses an index for a
+Frobenius step, then chooses one index per repetition of each label. The
+finite sums of these branches are exactly the chronological continuation
+effects of the digit program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorScheduleEffects
+
+open EvaluatorDigitSchedule
+variable {S I : Type*} [Fintype I] {t Z : ℕ}
+
+/-- Value at the machine's row and column indices. The stack supplies a
+natural row number, so this definition also covers an out-of-range row. -/
+def digitAt (Q : ℕ) (e : Fin t → BurstRAM.Word Z) (i j : ℕ) : ℕ :=
+ if h : i < t then (e ⟨i,h⟩).val / Q^(Z-1-j) % Q else 0
+
+@[simp] theorem digitAt_fin (Q : ℕ) (e : Fin t → BurstRAM.Word Z) (i : Fin t) (j : ℕ) :
+ digitAt Q e i.val j = (e i).val / Q^(Z-1-j) % Q := by simp [digitAt, i.isLt]
+
+/-- The unary offset selected by the machine yields the exact multiplicity
+for its binary repetition routine. -/
+theorem digitAt_table (w Q : ℕ) (e : Fin t → BurstRAM.Word Z) (i : Fin t) (j : Fin Z)
+ (suffix : List Bool) :
+ (((EvaluatorRadixRows.packedTable w Q (List.ofFn e) ++ suffix).drop ((i.val*Z+j.val)*w)).take w) =
+ PrimedCounter.digits w (digitAt Q e i.val j.val) := by
+ have hi : i.val < (List.ofFn e).length := by rw [List.length_ofFn]; exact i.isLt
+ rw [EvaluatorRadixRows.packedTable_cell (z := Z) w Q (List.ofFn e) suffix i.val j.val hi j.isLt,
+ List.getElem_ofFn, digitAt_fin]
+
+/-- Summation over every index trace emitted by one binary repetition count. -/
+def cellEffect (next : Option ℕ → S → I → S) (e : Fin t → BurstRAM.Word Z)
+ (Q j i : ℕ) : (S → ℕ) → S → ℕ :=
+ repeatEffect next (some i) (digitAt Q e i j)
+
+/-- One column begins with Frobenius, followed by the repeated label steps
+in order of increasing label number. -/
+def columnEffect (next : Option ℕ → S → I → S) (e : Fin t → BurstRAM.Word Z)
+ (Q j : ℕ) (f : S → ℕ) : S → ℕ :=
+ stepEffect next none ((List.range t).foldr (cellEffect next e Q j) f)
+
+/-- Continuation effect of the entire nested machine schedule. -/
+def schedulerEffect (next : Option ℕ → S → I → S) (e : Fin t → BurstRAM.Word Z)
+ (Q : ℕ) (f : S → ℕ) : S → ℕ :=
+ (List.range Z).foldr (columnEffect next e Q) f
+
+/-- Physical action number used by the matrix query callback. -/
+def actionCode : Action t → Option ℕ
+ | .frobenius => none
+ | .label i => some i.val
+
+theorem columns_eq_digits (Q : ℕ) (e : Fin t → BurstRAM.Word Z) :
+ columns Q Z (fun i => (e i).val) =
+ (List.range Z).map (fun j i => digitAt Q e i.val j) := by
+ rw [columns_eq]
+ apply List.ext_getElem (by simp)
+ intro j _ _
+ funext i
+ simp [List.getElem_reverse]
+
+private theorem label_range (t : ℕ) : (List.finRange t).map Fin.val = List.range t := by
+ apply List.ext_getElem (by simp)
+ intros; simp
+
+/-- The fixed loop for a column has the same multiplicities and ordering as
+the Frobenius and label actions of `emit`. -/
+theorem columnEffect_eq_emit (next : Option ℕ → S → I → S) (e : Fin t → BurstRAM.Word Z)
+ (Q j : ℕ) (f : S → ℕ) :
+ columnEffect next e Q j f =
+ ((emit (fun i : Fin t => digitAt Q e i.val j)).map actionCode).foldr (stepEffect next) f := by
+ rw [columnEffect, ← label_range t, List.foldr_map]
+ simp only [emit, List.map_cons, actionCode, List.map_flatMap, List.map_replicate,
+ List.foldr_cons, List.foldr_flatMap]
+ apply congrArg (stepEffect next none)
+ apply congrArg (fun g => (List.finRange t).foldr g f)
+ funext i g s
+ exact repeatEffect_eq_foldr next (some i.val) (digitAt Q e i.val j) g s
+
+/-- All branch choices of the nested range loops have exactly the same
+effect as the chronological action list, for any index update and continuation. -/
+theorem schedulerEffect_eq_actions (next : Option ℕ → S → I → S) (e : Fin t → BurstRAM.Word Z)
+ (Q : ℕ) (f : S → ℕ) :
+ schedulerEffect next e Q f =
+ (((columns Q Z (fun i => (e i).val)).flatMap emit).map actionCode).foldr (stepEffect next) f := by
+ rw [schedulerEffect, columns_eq_digits, List.flatMap_map, List.map_flatMap, List.foldr_flatMap]
+ apply congrArg (fun g => (List.range Z).foldr g f)
+ funext j g
+ exact columnEffect_eq_emit next e Q j g
+
+/-- Interpret the physical scheduler's continuation in the counted action
+program of `EvaluatorStreamCount`. The interpretation may include fuel and
+stack encoding, so the action count may charge a different delay on each
+chosen index. -/
+theorem schedulerEffect_eq_actionCount {P : Type*} (next : Option ℕ → S → I → S)
+ (step : Action t → Evaluator.Continuation P → Evaluator.Continuation P)
+ (pull : Evaluator.Continuation P → S → ℕ)
+ (h : ∀ a c, stepEffect next (actionCode a) (pull c) = pull (step a c))
+ (e : Fin t → BurstRAM.Word Z) (Q : ℕ) (finish : Evaluator.Continuation P) :
+ schedulerEffect next e Q (pull finish) =
+ pull (Evaluator.actionCount step finish ((columns Q Z (fun i => (e i).val)).flatMap emit)) := by
+ rw [schedulerEffect_eq_actions]
+ generalize (columns Q Z (fun i => (e i).val)).flatMap emit = ops
+ induction ops with
+ | nil => rfl
+ | cons a ops ih => simp only [List.map_cons, List.foldr_cons, Evaluator.actionCount, ih, h]
+
+/-- An implementation of the linear-map effect on all valid action codes
+therefore realizes the concrete linear-map list of the algebra evaluator. -/
+theorem schedulerEffect_eq_digitProgram (K : Type*) [Field K] [Fintype K]
+ {A : Type*} [CommRing A] [Algebra K A] (X : Fin t → A)
+ (next : Option ℕ → S → I → S) (effect : (A →ₗ[K] A) → (S → ℕ) → S → ℕ)
+ (h : ∀ a : Action t, stepEffect next (actionCode a) = effect (actionMap K X a))
+ (e : Fin t → BurstRAM.Word Z) (f : S → ℕ) :
+ schedulerEffect next e (Fintype.card K) f =
+ (Evaluator.digitProgram K X Z (fun i => (e i).val)).foldr effect f := by
+ rw [schedulerEffect_eq_actions, ← actions_eq_digitProgram K X, List.foldr_map, List.foldr_map]
+ simp only [h]
+
+end EvaluatorScheduleEffects
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorStreamCount.lean b/lean/OAI/Computability/VPVNP/EvaluatorStreamCount.lean
new file mode 100644
index 0000000000..6d9141d01c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorStreamCount.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.EvaluatorMatrixStep
+import OAI.Computability.VPVNP.EvaluatorDigitSchedule
+
+/-!
+# Counting a streamed sequence of linear steps
+
+After an index guess, the evaluator retains only that index and its running
+product. Different branches may take different times to query their matrix
+entries. A common bound per step suffices for the modular count: after every
+permitted choice the remaining clock still covers the remaining steps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator
+
+open RAMTape
+
+variable {P : Type*} {Op : Type*}
+
+/-- The continuation count as a function of the remaining instruction budget and the current
+evaluator stack bank. -/
+abbrev Continuation (P : Type*) := ℕ → Stacks P → ℕ
+
+/-- Continuation semantics of the chronological actions, independently of the
+finite control that emits the schedule. -/
+def actionCount (step : Op → Continuation P → Continuation P) (finish : Continuation P) :
+ List Op → Continuation P
+ | [] => finish
+ | op :: ops => step op (actionCount step finish ops)
+
+variable {p n : ℕ} [Fact p.Prime] {K : Type*} [Field K] [Algebra (ZMod p) K]
+ (matrix : Op → Matrix (Fin n) (Fin n) K) (coord : K →ₗ[ZMod p] ZMod p)
+ (unit : Fin n) (bank : Fin n → K → Stacks P)
+ (step : Op → Continuation P → Continuation P) (finish : Continuation P)
+ (stepBound finishBound : ℕ)
+ (hstep : ∀ op i a fuel, stepBound ≤ fuel → ∃ delay : Fin n → ℕ,
+ (∀ j, delay j ≤ stepBound) ∧ ∀ c,
+ step op c fuel (bank i a) =
+ ∑ j, c (fuel - delay j) (bank j (a * matrix op i j)))
+ (hfinish : ∀ i a fuel, finishBound ≤ fuel →
+ (finish fuel (bank i a) : ZMod p) = coord (if i = unit then a else 0))
+
+include hstep hfinish in
+/-- After all streamed queries, reducing the integer count modulo the prime
+gives the first coordinate of the accumulated weighted matrix product. -/
+theorem actionCount_mod (ops : List Op) (i : Fin n) (a : K) (fuel : ℕ)
+ (ht : ops.length * stepBound + finishBound ≤ fuel) :
+ (actionCount step finish ops fuel (bank i a) : ZMod p) =
+ coord (a * (ops.map matrix).prod i unit) := by
+ induction ops generalizing fuel i a with
+ | nil =>
+ have he := hfinish i a fuel (by simpa using ht)
+ by_cases hi : i = unit <;> simpa [actionCount, Matrix.one_apply, hi] using he
+ | cons op ops ih =>
+ have ht' : ops.length * stepBound + stepBound + finishBound ≤ fuel := by
+ simpa only [List.length_cons, Nat.succ_mul] using ht
+ obtain ⟨delay, hd, he⟩ := hstep op i a fuel (by omega)
+ simp only [actionCount, he, Nat.cast_sum, List.map_cons, List.prod_cons, Matrix.mul_apply]
+ rw [Finset.mul_sum, map_sum]
+ apply Finset.sum_congr rfl
+ intro j _
+ have h := ih j (a * matrix op i j) (fuel - delay j) (by have := hd j; omega)
+ simpa only [mul_assoc] using h
+
+/-- Apply the chronological count identity to the actual Frobenius and label
+matrices in their monomial basis. The functional is applied after all digits. -/
+theorem monomial_actionCount_mod [Fintype K] {A : Type*} [CommRing A] [Algebra K A]
+ [Algebra (ZMod p) A] [IsScalarTower (ZMod p) K A] {t : ℕ}
+ (X : Fin t → A) (b : Module.Basis (Fin n) K A) (hb : b unit = 1)
+ (programStep : EvaluatorDigitSchedule.Action t → Continuation P → Continuation P)
+ (hs : ∀ op i a fuel, stepBound ≤ fuel → ∃ delay : Fin n → ℕ,
+ (∀ j, delay j ≤ stepBound) ∧ ∀ c, programStep op c fuel (bank i a) =
+ ∑ j, c (fuel - delay j) (bank j (a *
+ (LinearMap.toMatrixAlgEquiv b (EvaluatorDigitSchedule.actionMap K X op)) j i)))
+ (width : ℕ) (e : Fin t → ℕ) (he : ∀ i, e i < 2 ^ width) (fuel : ℕ)
+ (hclock : width * (1 + t * (Fintype.card K - 1)) * stepBound + finishBound ≤ fuel)
+ (finalCount : ∀ i a fuel, finishBound ≤ fuel →
+ (finish fuel (bank i a) : ZMod p) = coord (if i = unit then a else 0)) :
+ (actionCount programStep finish
+ ((EvaluatorDigitSchedule.columns (Fintype.card K) width e).flatMap EvaluatorDigitSchedule.emit)
+ fuel (bank unit 1) : ZMod p) = primeFunctional b unit coord (∏ i, X i ^ e i) := by
+ let ops := (EvaluatorDigitSchedule.columns (Fintype.card K) width e).flatMap EvaluatorDigitSchedule.emit
+ let m (op : EvaluatorDigitSchedule.Action t) :=
+ (LinearMap.toMatrixAlgEquiv b (EvaluatorDigitSchedule.actionMap K X op)).transpose
+ have ht : ops.length * stepBound + finishBound ≤ fuel :=
+ (Nat.add_le_add_right (Nat.mul_le_mul_right _ (EvaluatorDigitSchedule.action_count_le K width e)) _).trans hclock
+ have h := actionCount_mod m coord unit bank programStep finish stepBound finishBound hs finalCount ops unit 1 fuel ht
+ have hmaps : ops.map m = transitionMatrices b (digitProgram K X width e) := by
+ rw [transitionMatrices, ← EvaluatorDigitSchedule.actions_eq_digitProgram K X, List.map_map]
+ rfl
+ rw [hmaps, one_mul, transitionMatrices_unit_entry b unit hb, digitProgram_eval K X width e he] at h
+ exact h
+
+end Evaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorTail.lean b/lean/OAI/Computability/VPVNP/EvaluatorTail.lean
new file mode 100644
index 0000000000..0b1958d6ec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorTail.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.ChoiceWitness
+import OAI.Computability.VPVNP.CutSchedule
+import Mathlib.SetTheory.Cardinal.Finite
+
+/-!
+# One evaluator transition per tail group
+
+In Section 14.1 each live tail group executes one transition, preserving the
+two choices of a branching transition even if their successor configurations
+are equal. An accepting halt is serialized by one canonical configuration.
+For any fixed clocked machine, the sequence of matching cut configurations
+is uniquely determined by the branch choices, and the successful sequences
+count exactly its accepting paths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorTail
+
+open UniversalMachine
+
+/-- Accepted computations propagate a single canonical halted state down the tail. -/
+inductive State (extra : ℕ) where
+ | accepted
+ | rejected
+ | running (c : Config extra)
+
+/-- Forget the tape contents on a halt. -/
+def canonical {extra : ℕ} (c : Config extra) : State extra :=
+ if c.state.val = 1 then .accepted else if c.state.val = 0 then .rejected else .running c
+
+@[simp] theorem canonical_accepted_iff {extra : ℕ} (c : Config extra) :
+ canonical c = .accepted ↔ c.state.val = 1 := by
+ unfold canonical
+ split_ifs <;> simp_all
+
+/-- A padded choice zero propagates an accepting halt exactly once.
+Invalid choices, including a one at an accepting halt, enter rejection. -/
+def step (p : Program) (s : State p.extra) (bit : Bool) : State p.extra :=
+ match s with
+ | .accepted => if bit then .rejected else .accepted
+ | .rejected => .rejected
+ | .running c => canonical (choiceStep p c bit)
+
+theorem step_canonical (p : Program) (c : Config p.extra) (bit : Bool) :
+ step p (canonical c) bit = canonical (choiceStep p c bit) := by
+ by_cases ha : c.state.val = 1
+ · cases bit <;> simp [canonical, ha, step, choiceStep, reject]
+ · by_cases hr : c.state.val = 0
+ · simp [canonical, hr, step, choiceStep]
+ · simp [canonical, ha, hr, step]
+
+/-- The initial configuration and one output configuration per tail group. -/
+def history (p : Program) : (t : ℕ) → Config p.extra → (Fin t → Bool) → Fin (t + 1) → State p.extra
+ | 0, c, _ => fun _ => canonical c
+ | t + 1, c, w => Fin.cons (canonical c) (history p t (choiceStep p c (w 0)) (Fin.tail w))
+
+@[simp] theorem history_zero (p : Program) (t : ℕ) (c : Config p.extra) (w : Fin t → Bool) :
+ history p t c w 0 = canonical c := by cases t <;> rfl
+
+theorem history_step (p : Program) (t : ℕ) (c : Config p.extra) (w : Fin t → Bool) (i : Fin t) :
+ history p t c w i.succ = step p (history p t c w i.castSucc) (w i) := by
+ induction t generalizing c with
+ | zero => exact Fin.elim0 i
+ | succ t ih =>
+ refine Fin.cases ?_ (fun j => ?_) i
+ · simpa [history, Fin.cons_zero, Fin.cons_succ] using (step_canonical p c (w 0)).symm
+ · simpa [history, Fin.tail] using ih (choiceStep p c (w 0)) (Fin.tail w) j
+
+theorem history_last (p : Program) (t : ℕ) (c : Config p.extra) (w : Fin t → Bool) :
+ history p t c w (Fin.last t) = .accepted ↔ acceptsChoices p t c w := by
+ induction t generalizing c with
+ | zero => simp [history, acceptsChoices]
+ | succ t ih =>
+ rw [history, Fin.cons_last, acceptsChoices_succ]
+ exact ih (choiceStep p c (w 0)) (Fin.tail w)
+
+/-- Local tail checks fix every cut configuration, starting from the advised
+initial configuration and executing one step per group. -/
+theorem eq_history (p : Program) (t : ℕ) (c : Config p.extra) (w : Fin t → Bool)
+ (s : Fin (t + 1) → State p.extra) (hinit : s 0 = canonical c)
+ (hstep : ∀ i, s i.succ = step p (s i.castSucc) (w i)) :
+ s = history p t c w := by
+ funext i
+ induction i using Fin.induction with
+ | zero => exact hinit.trans (history_zero ..).symm
+ | succ j ih => rw [hstep, ih, history_step]
+
+/-- Accepted tail choices and their matching configurations, including the
+initial and final boundary values. -/
+abbrev Traces (p : Program) (t : ℕ) (c : Config p.extra) :=
+ (w : Fin t → Bool) × {s : Fin (t + 1) → State p.extra //
+ s 0 = canonical c ∧ (∀ i, s i.succ = step p (s i.castSucc) (w i)) ∧ s (Fin.last t) = .accepted}
+
+/-- Bijection used by the last `L/2` groups of Section 14.1. It includes an
+initially accepting evaluator and every early halt. -/
+def tracesEquiv (p : Program) (t : ℕ) (c : Config p.extra) :
+ {w : Fin t → Bool // acceptsChoices p t c w} ≃ Traces p t c where
+ toFun w := ⟨w.val, history p t c w.val, history_zero .., history_step p t c w.val,
+ (history_last ..).mpr w.property⟩
+ invFun s := ⟨s.1, (history_last ..).mp ((eq_history p t c s.1 s.2.val s.2.property.1
+ s.2.property.2.1) ▸ s.2.property.2.2)⟩
+ left_inv _ := rfl
+ right_inv s := by
+ rcases s with ⟨w, cuts, hi, hs, ha⟩
+ have he := eq_history p t c w cuts hi hs
+ subst cuts
+ rfl
+
+/-- The integer count of valid local tail transcripts equals the machine's
+clocked accepting path count. -/
+theorem card_traces (p : Program) (t : ℕ) (c : Config p.extra) :
+ Nat.card (Traces p t c) = paths p t c := by
+ rw [← Nat.card_congr (tracesEquiv p t c), Nat.card_eq_fintype_card,
+ Fintype.card_subtype, paths_eq_card_choices]
+
+/-- For a fixed encoding of the reached configuration, checking the tail
+layout and zero padding leaves exactly one possible cut string. -/
+theorem encoded_cut_unique (p : Program) (h Δ i csize : ℕ) (hi : 2 ^ h < i)
+ (hlt : i < 2 ^ (h + 1)) (hfit : 1 + csize ≤ Δ) (encode : State p.extra → CutSchedule.Bits csize)
+ (c : Config p.extra) (w : Fin (2 ^ h) → Bool) :
+ ∃! bits, CutSchedule.tailLayout h Δ i csize hi.le hlt hfit bits =
+ (true, encode (history p (2 ^ h) c w ⟨i - 2 ^ h, by rw [pow_succ] at hlt; omega⟩),
+ fun _ => false) :=
+ CutSchedule.tail_unique ..
+
+end EvaluatorTail
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorTallyLoop.lean b/lean/OAI/Computability/VPVNP/EvaluatorTallyLoop.lean
new file mode 100644
index 0000000000..193c002576
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorTallyLoop.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.StructuredStacks
+import Mathlib.Data.Fintype.Sum
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Enumerating the labels in an evaluator column
+
+The remaining labels are counted in unary. The body sees the index of the
+current label, starting at zero. Each normal return increments the index
+before the next iteration. At the end of the column the loop clears the
+index for reuse on the next column.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorTallyLoop
+
+open RAMTape
+
+/-- Control states for the unary label loop, including the callback, index advancement, final
+index clearing and rejection. -/
+inductive State (Q : Type*) where
+ | scan | call (q : Q) | advance | clearIndex | reject
+ deriving Fintype
+
+variable {K Q : Type*}
+
+/-- A zero bit in the unary count rejects. The body is invoked once per mark. -/
+def tallyLoop (remain index : K) (body : Routine K Q) : Routine K (State Q) where
+ entry := .scan
+ code
+ | .scan => .pop remain fun b => some <| match b with
+ | none => .clearIndex
+ | some false => .reject
+ | some true => .call body.entry
+ | .call q => body.install State.call (some .advance) q
+ | .advance => .push index true (some .scan)
+ | .clearIndex => .pop index fun b => b.map fun _ => .clearIndex
+ | .reject => .halt false
+
+variable [DecidableEq K] (remain index : K) (body : Routine K Q) (c : ℕ → Stacks K → ℕ)
+
+private theorem advance_count :
+ (fun n s => (tallyLoop remain index body).countFrom c n (some .advance) s) =
+ (Routine.push index true).count ((tallyLoop remain index body).count c) := by
+ funext n s
+ cases n <;> simp only [Routine.count, Routine.countFrom, Routine.push, tallyLoop, Routine.countFrom_none]
+
+/-- Reading one mark costs one instruction. Each path through the body spends
+one further instruction to push the index mark if it returns normally. -/
+theorem loop_count_succ (s : Stacks K) (tail : List Bool) (hs : s remain = true :: tail) (fuel : ℕ) :
+ (tallyLoop remain index body).count c (fuel+1) s =
+ body.count ((Routine.push index true).count ((tallyLoop remain index body).count c)) fuel
+ (Function.update s remain tail) := by
+ have h := Routine.countFrom_install (tallyLoop remain index body) body State.call (some .advance)
+ (fun _ => rfl) c fuel (some body.entry) (Function.update s remain tail)
+ rw [advance_count] at h
+ simpa only [Routine.count, Routine.countFrom, tallyLoop, hs, List.head?_cons, List.tail_cons,
+ Option.elim_some, Function.comp_apply] using h
+
+private theorem clear_count (s : Stacks K) (xs : List Bool) (hs : s index = xs) (fuel : ℕ) :
+ (tallyLoop remain index body).countFrom c (fuel+xs.length+1) (some .clearIndex) s =
+ c fuel (Function.update s index []) := by
+ induction xs generalizing s with
+ | nil => simp [Routine.countFrom, tallyLoop, hs]
+ | cons b xs ih =>
+ simp only [Routine.countFrom, tallyLoop, hs, List.head?_cons, List.tail_cons, Option.map_some]
+ have h := ih (Function.update s index xs) (Function.update_self ..)
+ simpa only [tallyLoop, List.length_cons, Nat.add_assoc, Function.update_idem] using h
+
+/-- The empty test, one pop per used index mark, and the last empty index
+test return to the caller, preserving every stack other than the index. -/
+theorem loop_count_zero (s : Stacks K) (hs : s remain = []) (fuel : ℕ) :
+ (tallyLoop remain index body).count c (fuel+(s index).length+2) s =
+ c fuel (Function.update s index []) := by
+ have hu : Function.update s remain [] = s := hs ▸ Function.update_eq_self remain s
+ simpa only [Routine.count, Routine.countFrom, tallyLoop, hs, List.head?_nil, List.tail_nil, hu] using
+ clear_count remain index body c s (s index) rfl fuel
+
+end EvaluatorTallyLoop
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorTallySafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorTallySafety.lean
new file mode 100644
index 0000000000..dddd61921d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorTallySafety.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.EvaluatorTallySemantics
+import OAI.Computability.VPVNP.EvaluatorRoutineSafety
+
+/-! # All-branch clock and storage bounds for unary evaluator scans
+
+The two counters move one mark per iteration, then the used index is
+discarded. Only the callback needs a separate bound on its internal banks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorTallyLoop
+
+open RAMTape EvaluatorRoutineSafety
+
+variable {K Q S : Type*} [DecidableEq K]
+variable (remain index : K) (body : Routine K Q) (bank : ℕ → ℕ → S → Stacks K)
+ (hb : TallyBank remain index bank) (safe : Stacks K → Prop)
+
+include hb
+
+private theorem clear_safe (i fuel : ℕ) (x : S) (c : ℕ → Stacks K → Prop)
+ (hbanks : ∀ j ≤ i, safe (bank j 0 x)) (hc : c fuel (bank 0 0 x)) :
+ (tallyLoop remain index body).SafeFrom safe c (fuel+i+1) (some .clearIndex) (bank i 0 x) := by
+ induction i with
+ | zero =>
+ rw [Routine.SafeFrom]
+ exact ⟨hbanks _ le_rfl, by simpa [tallyLoop, hb.indexAt, hb.clearIndex] using hc⟩
+ | succ i ih =>
+ rw [Routine.SafeFrom]
+ refine ⟨hbanks _ le_rfl, ?_⟩
+ have hu : Function.update (bank (i+1) 0 x) index (List.replicate i true) = bank i 0 x := by
+ rw [← hb.pushIndex, Function.update_idem, ← hb.indexAt i 0 x, Function.update_eq_self]
+ have h := ih (fun j hj => hbanks j (by omega))
+ simpa only [tallyLoop, hb.indexAt, List.replicate_succ, List.head?_cons, List.tail_cons,
+ Option.map_some, hu, Nat.add_assoc] using h
+
+private theorem scan_safe (i r fuel : ℕ) (x : S) (c : ℕ → Stacks K → Prop)
+ (hbank : safe (bank i (r+1) x))
+ (h : body.Safe safe (fun t s => (tallyLoop remain index body).SafeFrom safe c t (some .advance) s)
+ fuel (bank i r x)) :
+ (tallyLoop remain index body).Safe safe c (fuel+1) (bank i (r+1) x) := by
+ have installed := (Routine.safeFrom_install (tallyLoop remain index body) body State.call (some .advance)
+ (fun _ => rfl) safe c fuel (some body.entry) (bank i r x)).mpr h
+ rw [Routine.Safe, Routine.SafeFrom]
+ refine ⟨hbank, ?_⟩
+ simpa only [tallyLoop, hb.remainAt, List.replicate_succ, List.head?_cons, List.tail_cons,
+ hb.popRemain, Option.elim_some, Function.comp_apply] using installed
+
+/-- The tally scan meets the same clock bound on all paths, including
+rejecting ones, and preserves the given storage bound at every instruction. -/
+theorem loop_bounded (B i r : ℕ)
+ (hbanks : ∀ j left, j+left ≤ i+r → ∀ x, safe (bank j left x))
+ (hbody : ∀ j left, j+left < i+r → Bounded body safe (bank j left) (bank j left) B) :
+ Bounded (tallyLoop remain index body) safe (bank i r) (bank 0 0) (r*(B+2)+(i+r)+2) := by
+ induction r generalizing i with
+ | zero =>
+ intro extra fuel hf x c hc
+ let free := fuel-(i+2)
+ have hh := clear_safe remain index body bank hb safe i free x c
+ (fun j hj => hbanks j 0 (by omega) x) (hc x free (by dsimp [free]; simp at hf; omega))
+ have he : fuel = (free+i+1)+1 := by dsimp [free]; simp at hf; omega
+ rw [he, Routine.Safe, Routine.SafeFrom]
+ refine ⟨hbanks i 0 le_rfl x, ?_⟩
+ have hu : Function.update (bank i 0 x) remain [] = bank i 0 x := by
+ have hempty : bank i 0 x remain = [] := hb.remainAt i 0 x
+ rw [← hempty, Function.update_eq_self]
+ simpa only [tallyLoop, hb.remainAt, List.replicate_zero, List.head?_nil, List.tail_nil, hu] using hh
+ | succ r ih =>
+ have later := ih (i+1) (fun j left hj => hbanks j left (by omega))
+ (fun j left hj => hbody j left (by omega))
+ intro extra fuel hf x c hc
+ obtain ⟨fuel, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : fuel ≠ 0)
+ apply scan_safe remain index body bank hb safe _ _ _ x c (hbanks i _ le_rfl x)
+ let rest := r*(B+2)+(i+1+r)+2
+ apply hbody i r (by omega) (extra+rest+1) fuel (by
+ dsimp [rest]
+ simp only [Nat.succ_mul] at hf
+ omega)
+ intro y k hk
+ obtain ⟨k, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : k ≠ 0)
+ rw [Routine.SafeFrom]
+ refine ⟨hbanks i r (by omega) y, ?_⟩
+ simpa only [Routine.Safe, tallyLoop, hb.pushIndex] using
+ later extra k (by dsimp [rest] at hk; omega) y c hc
+
+end EvaluatorTallyLoop
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorTallySemantics.lean b/lean/OAI/Computability/VPVNP/EvaluatorTallySemantics.lean
new file mode 100644
index 0000000000..d3b693ea25
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorTallySemantics.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.EvaluatorTallyLoop
+import OAI.Computability.VPVNP.EvaluatorRoutine
+import OAI.Computability.VPVNP.EvaluatorDigitRepeat
+import OAI.Computability.VPVNP.StructuredStackRuns
+
+/-! # Chronological semantics of a unary evaluator scan
+
+Each iteration may branch. The remaining clock covers the index increment
+and every later iteration on each branch. The final cleanup removes the
+index accumulated throughout the scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace EvaluatorTallyLoop
+
+open RAMTape EvaluatorRoutine
+
+variable {K Q S : Type*} [DecidableEq K]
+
+/-- The two physical stack counters represent the current index and the
+number of callbacks still to be invoked. -/
+structure TallyBank (remain index : K) (bank : ℕ → ℕ → S → Stacks K) : Prop where
+ remainAt : ∀ i r x, bank i r x remain = List.replicate r true
+ indexAt : ∀ i r x, bank i r x index = List.replicate i true
+ popRemain : ∀ i r x, Function.update (bank i (r+1) x) remain (List.replicate r true) = bank i r x
+ pushIndex : ∀ i r x, Function.update (bank i r x) index (true :: bank i r x index) = bank (i+1) r x
+ clearIndex : ∀ i x, Function.update (bank i 0 x) index [] = bank 0 0 x
+
+/-- The usual framed bank supplies these equations for any payload bank. -/
+theorem TallyBank.of_frame (remain index : K) (hne : remain ≠ index) (base : S → Stacks K) :
+ TallyBank remain index (fun i r x =>
+ EvaluatorDigitRepeat.frame remain index (base x) (List.replicate r true) (List.replicate i true)) := by
+ constructor
+ · intro i r x
+ simp [EvaluatorDigitRepeat.frame, hne]
+ · intro i r x
+ simp [EvaluatorDigitRepeat.frame]
+ · intro i r x
+ simp [EvaluatorDigitRepeat.frame, Function.update_comm hne.symm]
+ · intro i r x
+ simp [EvaluatorDigitRepeat.frame, List.replicate_succ]
+ · intro i x
+ simp [EvaluatorDigitRepeat.frame]
+
+/-- Starting with index `i` and `r` remaining marks composes the successive
+callback effects in increasing index order. Each callback has its own paths
+and may use fewer than `B` instructions on any of them. -/
+theorem loop_realizes (remain index : K) (body : Routine K Q) (bank : ℕ → ℕ → S → Stacks K)
+ (hb : TallyBank remain index bank) (B : ℕ) (op : ℕ → (S → ℕ) → S → ℕ) (i r : ℕ)
+ (hbody : ∀ j left, j + left < i + r → Realizes body (bank j left) (bank j left) B (op j)) :
+ Realizes (tallyLoop remain index body) (bank i r) (bank 0 0)
+ (r*(B+2)+(i+r)+2) (fun f => (List.range' i r).foldr op f) := by
+ induction r generalizing i with
+ | zero =>
+ intro extra fuel hf x f c hc
+ have hs := hb.remainAt i 0 x
+ have hlen : (bank i 0 x index).length = i := by rw [hb.indexAt, List.length_replicate]
+ have h := loop_count_zero remain index body c (bank i 0 x) hs (fuel-(i+2))
+ rw [hlen, hb.clearIndex, show fuel-(i+2)+i+2 = fuel by simp at hf; omega] at h
+ exact h.trans (hc x _ (by simp at hf; omega))
+ | succ r ih =>
+ have hnext := ih (i+1) (fun j left hj => hbody j left (by omega))
+ intro extra fuel hf x f c hc
+ obtain ⟨fuel, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : fuel ≠ 0)
+ have hs : bank i (r+1) x remain = true :: List.replicate r true := by
+ rw [hb.remainAt, List.replicate_succ]
+ rw [loop_count_succ remain index body c _ _ hs, hb.popRemain, List.range'_succ]
+ simp only [List.foldr_cons]
+ let rest := r*(B+2)+(i+1+r)+2
+ apply hbody i r (by omega) (extra+rest+1) fuel (by
+ dsimp [rest]
+ simp only [Nat.succ_mul] at hf
+ omega)
+ intro y k hk
+ obtain ⟨k, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : k ≠ 0)
+ have hpush := (Routine.runs_push index true (bank i r y)).count_eq ((tallyLoop remain index body).count c) k
+ rw [hb.pushIndex] at hpush
+ exact hpush.trans (hnext extra k (by dsimp [rest] at hk; omega) y f c hc)
+
+end EvaluatorTallyLoop
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorUniformBounds.lean b/lean/OAI/Computability/VPVNP/EvaluatorUniformBounds.lean
new file mode 100644
index 0000000000..eab4486cf4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorUniformBounds.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.EvaluatorLiteralResources
+
+/-!
+# Length-uniform bounds for the fixed evaluator table
+
+All query, advice and scalar parameters can be bounded before the exponent
+width is chosen. A single length envelope then bounds the physical clock,
+advice length and tape window for every width, including widths selected by
+the later diagonal construction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.MatrixCallbacks
+
+open BinaryMachine SliceArithmetic EvaluatorProgramRawInput
+
+/-- One numeric bound for the width-independent parameters at a length.
+The entry query time is specified by its binary exponent. -/
+def lengthEnvelope (t ℓ fields ports v e w extraSpace peak queryExponent : ℕ) :=
+ let A := adviceCap fields t ℓ (WeightedStep.bankSpace v e w extraSpace)
+ A + workspace v e w extraSpace peak + t + ℓ + ports + terminalTicks v w + queryExponent + 2
+
+/-- Width and storage bounds may be chosen uniformly over all fields and
+slice models at a given length. -/
+theorem lengthEnvelope_mono {t t' ℓ ℓ' fields ports v v' e e' w w' h h' peak peak' q q' : ℕ}
+ (ht : t ≤ t') (hl : ℓ ≤ ℓ') (hv : v ≤ v') (he : e ≤ e') (hw : w ≤ w')
+ (hh : h ≤ h') (hp : peak ≤ peak') (hq : q ≤ q') :
+ lengthEnvelope t ℓ fields ports v e w h peak q ≤ lengthEnvelope t' ℓ' fields ports v' e' w' h' peak' q' := by
+ unfold lengthEnvelope adviceCap workspace WeightedStep.bankSpace WeightedStep.localTicks
+ MultiplyCall.callCap HornerControl.digitCap terminalTicks
+ dsimp only
+ gcongr
+
+theorem lengthEnvelope_polynomial (fields ports : ℕ) {t ℓ v e w h peak queryExponent : ℕ → ℕ}
+ (ht : PolynomiallyBounded t) (hℓ : PolynomiallyBounded ℓ) (hv : PolynomiallyBounded v)
+ (he : PolynomiallyBounded e) (hw : PolynomiallyBounded w) (hh : PolynomiallyBounded h)
+ (hp : PolynomiallyBounded peak) (hq : PolynomiallyBounded queryExponent) :
+ PolynomiallyBounded fun n ↦ lengthEnvelope (t n) (ℓ n) fields ports (v n) (e n) (w n) (h n) (peak n)
+ (queryExponent n) := by
+ have hb : PolynomiallyBounded fun n ↦ WeightedStep.bankSpace (v n) (e n) (w n) (h n) :=
+ (((hv.add he).add hw).add (he.mul hw)).add hh
+ have ha := adviceCap_polynomial fields ht hℓ hb
+ have hs := workspace_polynomial hv he hw hh hp
+ have hend : PolynomiallyBounded fun n ↦ terminalTicks (v n) (w n) :=
+ ((((PolynomiallyBounded.const 3).mul hw).add (.const 3)).add hv)
+ exact (((((((ha.add hs).add ht).add hℓ).add (.const ports)).add hend).add hq).add (.const 2))
+
+theorem uniform_tape_clock (t Z ℓ fields ports v e w h peak queryExponent Q F L rawLength : ℕ)
+ (hQ : Q ≤ 2^ℓ) (hF : F ≤ 2^queryExponent) (hL : L ≤ 2^queryExponent)
+ (hraw : rawLength ≤ adviceCap fields t ℓ (WeightedStep.bankSpace v e w h)+(2*(t*Z)+6*Z+4)) :
+ let A := adviceCap fields t ℓ (WeightedStep.bankSpace v e w h)
+ let a := lengthEnvelope t ℓ fields ports v e w h peak queryExponent
+ tapeTicks rawLength ports (fullTicks t Z ℓ Q A (WeightedStep.ticks v e w F)
+ (WeightedStep.ticks v e w L) v w) ≤ 2^(6*a+23)*(Z+1)^4 := by
+ intro A a
+ have h₀ : a ≤ 2^a := Nat.lt_two_pow_self.le
+ have hsum : WeightedStep.localTicks v e w + queryExponent + 1 ≤ a := by
+ dsimp [a, lengthEnvelope, workspace]; omega
+ have hcall (time : ℕ) (htime : time ≤ 2^queryExponent) : WeightedStep.ticks v e w time ≤ 2^a := by
+ let m := WeightedStep.localTicks v e w + queryExponent
+ have hm₁ : WeightedStep.localTicks v e w ≤ 2^m := (Nat.le_add_right ..).trans Nat.lt_two_pow_self.le
+ have hm₂ : time ≤ 2^m := htime.trans (Nat.pow_le_pow_right (by decide) (Nat.le_add_left ..))
+ have hb : WeightedStep.ticks v e w time = WeightedStep.localTicks v e w + time := by
+ unfold WeightedStep.ticks WeightedStep.localTicks; omega
+ calc
+ WeightedStep.ticks v e w time ≤ 2^m+2^m := hb ▸ Nat.add_le_add hm₁ hm₂
+ _ = 2^(m+1) := by rw [pow_succ]; omega
+ _ ≤ 2^a := Nat.pow_le_pow_right (by decide) hsum
+ apply tapeTicks_le_exp_poly t Z ℓ Q A _ _ v w ports rawLength a
+ · exact (by dsimp [a,A,lengthEnvelope]; omega : A ≤ a).trans h₀
+ · exact (by dsimp [a,lengthEnvelope]; omega : t ≤ a).trans h₀
+ · exact (by dsimp [a,lengthEnvelope]; omega : ℓ ≤ a).trans h₀
+ · exact hQ.trans (Nat.pow_le_pow_right (by decide) (by dsimp [a,lengthEnvelope]; omega))
+ · exact hcall F hF
+ · exact hcall L hL
+ · exact (by dsimp [a,lengthEnvelope]; omega : terminalTicks v w ≤ a).trans h₀
+ · exact (by dsimp [a,lengthEnvelope]; omega : ports+1 ≤ a).trans h₀
+ · exact hraw
+
+/-- Bound the two physical tapes including the original raw input and both
+possible directions of head movement. -/
+theorem uniform_window (t Z ℓ fields ports v e w h peak queryExponent rawLength : ℕ)
+ (hr : rawLength ≤ adviceCap fields t ℓ (WeightedStep.bankSpace v e w h)+(2*(t*Z)+6*Z+4)) :
+ let A := adviceCap fields t ℓ (WeightedStep.bankSpace v e w h)
+ let a := lengthEnvelope t ℓ fields ports v e w h peak queryExponent
+ let radius := headRadius ports (fullSpace t Z ℓ (workspace v e w h peak) A v w)
+ rawLength + radius + radius ≤ 2240*(ports+1)*(a+Z+1)^4 := by
+ intro A a radius
+ let n := a+Z+1
+ have hn : 1 ≤ n := by dsimp [n]; omega
+ have hparam : t+Z+ℓ+workspace v e w h peak+A+v+w+1 ≤ n := by
+ dsimp [a,A,n,lengthEnvelope,terminalTicks]; omega
+ have hRad : radius ≤ 1110*(ports+1)*n^4 :=
+ (headRadius_le ..).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hparam _))
+ have hs : t*Z ≤ n^2 := by rw [sq]; exact Nat.mul_le_mul (by omega) (by omega)
+ have h₂ : n^2 ≤ n^4 := Nat.pow_le_pow_right hn (by decide)
+ have h₁ : n ≤ n^4 := by simpa only [pow_one] using Nat.pow_le_pow_right hn (by decide : 1 ≤ 4)
+ have hA : A ≤ n := by omega
+ change rawLength ≤ A+(2*(t*Z)+6*Z+4) at hr
+ have hraw : rawLength ≤ 13*n^4 := by dsimp [n] at *; omega
+ have hpos : n^4 ≤ (ports+1)*n^4 := by simpa only [Nat.succ_mul] using (Nat.le_add_left (n^4) (ports*n^4))
+ change rawLength+radius+radius ≤ 2240*(ports+1)*n^4
+ rw [Nat.mul_assoc] at hRad ⊢
+ omega
+
+/-- Extract a single exponent and threshold from a length envelope before
+choosing the width. The polynomial degree in the width is fixed. -/
+theorem exists_uniform_clock {a : ℕ → ℕ} (ha : PolynomiallyBounded a) :
+ ∃ c N : ℕ, ∀ n ≥ N, ∀ Z : ℕ, 2^(6*a n+23)*(Z+1)^4 ≤ 2^(n^c)*(Z+1)^4 := by
+ obtain ⟨m,d,N,hm⟩ := (((PolynomiallyBounded.const 6).mul ha).add (.const 23))
+ refine ⟨d+1,max m N,fun n hn Z ↦ Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) ?_)⟩
+ calc
+ 6*a n+23 ≤ m*n^d := hm n ((le_max_right ..).trans hn)
+ _ ≤ n*n^d := Nat.mul_le_mul_right _ ((le_max_left ..).trans hn)
+ _ = n^(d+1) := by rw [pow_succ, Nat.mul_comm]
+
+end Evaluator.MatrixCallbacks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorWeightedSafety.lean b/lean/OAI/Computability/VPVNP/EvaluatorWeightedSafety.lean
new file mode 100644
index 0000000000..461456e4cf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorWeightedSafety.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.EvaluatorWeightedStep
+import OAI.Computability.VPVNP.EvaluatorProgramRawSafety
+import OAI.Computability.VPVNP.SpaceRunMonotone
+
+/-!
+# Independent time and space bounds for a weighted matrix step
+
+The index choice, field multiplication and ordinal commit use short clocks.
+The entry query supplies its own space-bounded execution. Consequently the
+query's potentially exponential running time never enters the stack capacity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.WeightedStep
+
+open RAMTape SliceArithmetic EvaluatorRoutineSafety
+open EvaluatorChronologicalLoop (stackFits)
+
+variable {P Q : Type} [DecidableEq Q] {p e w v : ℕ} [Fact p.Prime]
+ {K : Type} [Field K] [Algebra (ZMod p) K] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K)
+ (ports : Port P → Q) (hp : Function.Injective ports) (ambient : Stacks Q)
+ (extra : Stacks P) (dim : BurstRAM.Word v)
+
+local notation "word" j => BurstRAM.wordBits (Fin.castLE dim.isLt.le j : BurstRAM.Word v)
+local notation "frame" => installStacks ports ambient
+local notation "bankAt" => (fun (i : Fin dim.val) (j q : List Bool) (a : K) ↦ frame (bank φ w dim i j q a extra))
+
+/-- At call boundaries the largest field stream occupies one working word
+per extension coefficient. -/
+def bankSpace (v e w extraSpace : ℕ) := v + e + w + e*w + extraSpace
+
+omit [DecidableEq Q] in
+theorem bank_length (extraSpace : ℕ) (hextra : ∀ k, (extra k).length ≤ extraSpace)
+ (i : Fin dim.val) (next query : List Bool) (hn : next.length ≤ v) (hq : query.length ≤ e*w) (a : K) :
+ stackFits (bankSpace v e w extraSpace) (bank φ w dim i next query a extra) := by
+ intro k
+ cases k with
+ | indices k => cases k <;> simp [bank, IndexRegisters.bank, bankSpace] <;> omega
+ | arithmetic k =>
+ rcases k with k | k
+ · exact Nat.zero_le _
+ · cases k <;> simp [bank, MultiplyCall.clean, MultiplyCall.external, bits, bankSpace] <;> omega
+ | width => simp [bank, bankSpace]; omega
+ | aux k => exact (hextra k).trans (by unfold bankSpace; omega)
+
+/-- Space reserved for the short subroutines. -/
+def localTicks (v e w : ℕ) := (10*v+5) + MultiplyCall.callCap e w + (5*v+3)
+
+include hp in
+private theorem select_bounded (cap : ℕ) (s : Fin dim.val × K)
+ (hroom : ∀ k, (bankAt s.1 [] [] s.2 k).length + (10*v+5) ≤ cap) :
+ Bounded (IndexRegisters.select.onPorts (ports ∘ Port.indices)).body (stackFits cap)
+ (fun _ : Unit ↦ bankAt s.1 [] [] s.2) (fun j : Fin dim.val ↦ bankAt s.1 (word j) [] s.2) (10*v+5) := by
+ let m := ports ∘ Port.indices
+ have hm : Function.Injective m := hp.comp (fun _ _ h ↦ Port.indices.inj h)
+ let base := bankAt s.1 [] [] s.2
+ let localBank (next : List Bool) := IndexRegisters.bank (BurstRAM.wordBits dim) (word s.1) next
+ have eq (next : List Bool) : installStacks m base (localBank next) = bankAt s.1 next [] s.2 := by
+ apply installStacks_frame hm
+ · intro k; exact installStacks_at hp ..
+ · intro k hk
+ by_cases h : ∃ t, ports t = k
+ · obtain ⟨t, rfl⟩ := h
+ dsimp only [base]
+ rw [installStacks_at hp, installStacks_at hp]
+ cases t with
+ | indices x => exact (hk x rfl).elim
+ | arithmetic | width | aux => rfl
+ · exact (installStacks_outside _ _ (not_exists.mp h)).trans
+ (installStacks_outside _ _ (not_exists.mp h)).symm
+ have h : Bounded IndexRegisters.select.body (stackFits cap) (fun _ : Unit ↦ localBank [])
+ (fun j : Fin dim.val ↦ localBank (word j)) (10*v+5) := by
+ intro reserve fuel hf _ cont hc
+ have hr := IndexRegisters.select_safe dim (word s.1) (stackFits cap) cont (fuel-(10*v+5))
+ (fun u hu k ↦ (hu k).trans (by
+ have hh := hroom (m k)
+ simp only [m, Function.comp_apply, installStacks_at hp] at hh
+ exact hh)) (fun j ↦ hc j _ (by omega))
+ rwa [Nat.sub_add_cancel (by omega)] at hr
+ have lift := Bounded.onPorts_frame IndexRegisters.select m (installStacks m base)
+ (fun _ _ ↦ installStacks_at hm ..) (installStacks_update hm base)
+ (large := stackFits cap) (fun u hu k ↦ by
+ by_cases hh : ∃ a, m a = k
+ · obtain ⟨a, rfl⟩ := hh; rw [installStacks_at hm]; exact hu a
+ · rw [installStacks_outside _ _ (not_exists.mp hh)]
+ exact (Nat.le_add_right _ _).trans (hroom k)) h
+ intro reserve fuel hf x cont hc
+ have hsafe := lift reserve fuel hf x cont (fun j k hk ↦ by
+ rw [Function.comp_apply, eq]
+ exact hc j k hk)
+ rwa [Function.comp_apply, eq] at hsafe
+
+include hp in
+/-- From a space-bounded scalar reader, the whole callback returns a legal
+weighted payload on every nonrejecting branch within its stated clock. -/
+theorem callback_bounded (he : 0 < e) (hw : Word.workingWidth p ≤ w) (read : FiniteRoutine Q)
+ (matrix : Matrix (Fin dim.val) (Fin dim.val) K) (cap queryTicks : ℕ)
+ (hroom : ∀ (i : Fin dim.val) (next query : List Bool), next.length ≤ v → query.length ≤ e*w →
+ ∀ (a : K) k, (bankAt i next query a k).length + localTicks v e w ≤ cap)
+ (hread : ∀ (s : Fin dim.val × K) (j : Fin dim.val), ∃ d ≤ queryTicks,
+ read.BoundedRun cap d (bankAt s.1 (word j) [] s.2)
+ (bankAt s.1 (word j) (bits φ w (matrix s.1 j)) s.2)) :
+ Bounded (callback ports read).body (stackFits cap)
+ (fun s : Fin dim.val × K ↦ bankAt s.1 [] [] s.2)
+ (fun s : Fin dim.val × K ↦ bankAt s.1 [] [] s.2) (ticks v e w queryTicks) := by
+ let chosen (x : (Fin dim.val × K) × Fin dim.val) := bankAt x.1.1 (word x.2) [] x.1.2
+ let entry (x : (Fin dim.val × K) × Fin dim.val) := bankAt x.1.1 (word x.2) (bits φ w (matrix x.1.1 x.2)) x.1.2
+ let product (x : (Fin dim.val × K) × Fin dim.val) := bankAt x.1.1 (word x.2) [] (x.1.2*matrix x.1.1 x.2)
+ have select : Bounded (IndexRegisters.select.onPorts (ports ∘ Port.indices)).body (stackFits cap)
+ (fun s : Fin dim.val × K ↦ bankAt s.1 [] [] s.2) chosen (10*v+5) := by
+ intro reserve fuel hf s cont hc
+ exact select_bounded φ ports hp ambient extra dim cap s (fun k ↦ by
+ have hh := hroom s.1 [] [] (by simp) (by simp) s.2 k
+ unfold localTicks at hh; omega) reserve fuel hf () cont (fun j ↦ hc (s,j))
+ have query : Bounded read.body (stackFits cap) chosen entry queryTicks :=
+ Bounded.of_space_runs (g := id) (fun x ↦ hread x.1 x.2)
+ have mul : Bounded (MultiplyCall.machine.onPorts (ports ∘ Port.arithmetic)).body (stackFits cap)
+ entry product (MultiplyCall.callCap e w) := by
+ apply Bounded.of_runs_with_room (g := id)
+ · intro x; exact multiply_framed φ ports hp ambient extra dim he hw x.1.1 x.2 x.1.2 _
+ · intro x u hu k
+ have hh := hroom x.1.1 (word x.2) (bits φ w (matrix x.1.1 x.2)) (by simp) (by simp [bits]) x.1.2 k
+ have h := hu k; dsimp only [entry] at h; dsimp only at hh; unfold localTicks at hh; omega
+ have commit : Bounded (IndexRegisters.commit.onPorts (ports ∘ Port.indices)).body (stackFits cap)
+ product (fun s : Fin dim.val × K ↦ bankAt s.1 [] [] s.2) (5*v+3) := by
+ apply Bounded.of_runs_with_room (g := fun x ↦ (x.2, x.1.2*matrix x.1.1 x.2))
+ · intro x; exact ⟨_, le_rfl, commit_framed φ ports hp ambient extra dim x.1.1 x.2 _⟩
+ · intro x u hu k
+ have hh := hroom x.1.1 (word x.2) [] (by simp) (by simp) (x.1.2*matrix x.1.1 x.2) k
+ have h := hu k; dsimp only [product] at h; dsimp only at hh; unfold localTicks at hh; omega
+ exact ((select.followedBy query).followedBy mul).followedBy commit
+
+end Evaluator.WeightedStep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EvaluatorWeightedStep.lean b/lean/OAI/Computability/VPVNP/EvaluatorWeightedStep.lean
new file mode 100644
index 0000000000..c0769bdd78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EvaluatorWeightedStep.lean
@@ -0,0 +1,183 @@
+import OAI.Computability.VPVNP.EvaluatorIndexRegisters
+import OAI.Computability.VPVNP.EvaluatorRoutineFrame
+import OAI.Computability.VPVNP.SliceArithmeticEncoding
+import OAI.Computability.VPVNP.SliceArithmeticMultiplyCall
+
+/-!
+# The weighted matrix-step callback
+
+After a legal next index has been chosen, the deterministic query writes its
+field entry onto the multiplication input. The actual Horner bit-stack code
+multiplies that entry by the running field product and clears its workspace.
+Committing the ordinal leaves exactly the payload expected by the next call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Evaluator.WeightedStep
+
+open RAMTape SliceArithmetic
+open SliceArithmeticRound (packed)
+
+/-- The basis-index registers, field multiplication registers, limb-width tally and auxiliary
+ports of a weighted matrix step. -/
+inductive Port (P : Type) where
+ | indices (i : IndexRegisters.Port)
+ | arithmetic (i : MultiplyCall.Port)
+ | width
+ | aux (i : P)
+ deriving DecidableEq, Fintype
+
+variable {P : Type} {p e v w : ℕ} [Fact p.Prime]
+ {K : Type} [Field K] [Algebra (ZMod p) K] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K)
+
+/-- Physical coefficient representation used by the entry-query and
+multiplication routines. -/
+noncomputable def bits (w : ℕ) (x : K) := packed w (List.ofFn (scalarEncoding φ x))
+
+/-- Call boundary, with an optional pending ordinal and a possibly occupied
+query result port. The unary width register serves the terminal residue test. -/
+noncomputable def bank (w : ℕ) (dim : BurstRAM.Word v) (i : Fin dim.val) (next query : List Bool)
+ (acc : K) (extra : Stacks P) : Stacks (Port P)
+ | .indices k => IndexRegisters.bank (BurstRAM.wordBits dim)
+ (BurstRAM.wordBits (Fin.castLE dim.isLt.le i : BurstRAM.Word v)) next k
+ | .arithmetic k => MultiplyCall.clean (MultiplyCall.external p e w
+ (packed w (List.ofFn c)) query (bits φ w acc)) k
+ | .width => List.replicate w true
+ | .aux k => extra k
+
+/-- The query may use additional disjoint ports of the enclosing caller.
+The selection, field multiplication and commit instructions are fixed. -/
+def callback {Q : Type} (ports : Port P → Q) (read : FiniteRoutine Q) : FiniteRoutine Q :=
+ (((IndexRegisters.select.onPorts (ports ∘ Port.indices)).followedBy read).followedBy
+ (MultiplyCall.machine.onPorts (ports ∘ Port.arithmetic))).followedBy
+ (IndexRegisters.commit.onPorts (ports ∘ Port.indices))
+
+variable {Q : Type} [DecidableEq Q] (ports : Port P → Q) (hports : Function.Injective ports)
+ (ambient : Stacks Q) (extra : Stacks P) (dim : BurstRAM.Word v)
+
+local notation "frame" => installStacks ports ambient
+local notation "word" j => BurstRAM.wordBits (Fin.castLE dim.isLt.le j : BurstRAM.Word v)
+
+include hports in
+private theorem select_framed (i : Fin dim.val) (a : K) (cont : ℕ → Stacks Q → ℕ) (fuel : ℕ) :
+ (IndexRegisters.select.onPorts (ports ∘ Port.indices)).body.count cont (fuel+(10*v+5))
+ (frame (bank φ w dim i [] [] a extra)) =
+ ∑ j : Fin dim.val, cont fuel (frame (bank φ w dim i (word j) [] a extra)) := by
+ have hp : Function.Injective (ports ∘ Port.indices) :=
+ hports.comp (fun _ _ h ↦ Port.indices.inj h)
+ rw [FiniteRoutine.count_onPorts _ _ hp]
+ have hs : frame (bank φ w dim i [] [] a extra) ∘ (ports ∘ Port.indices) =
+ IndexRegisters.bank (BurstRAM.wordBits dim) (word i) [] := by
+ funext k
+ exact installStacks_at hports ..
+ rw [hs, IndexRegisters.select_count]
+ apply Finset.sum_congr rfl
+ intro j _
+ apply congrArg (cont fuel)
+ apply installStacks_frame hp
+ · intro k
+ exact installStacks_at hports ..
+ · intro k hk
+ by_cases h : ∃ t, ports t = k
+ · obtain ⟨t, rfl⟩ := h
+ rw [installStacks_at hports, installStacks_at hports]
+ cases t with
+ | indices x => exact (hk x rfl).elim
+ | arithmetic | width | aux => rfl
+ · rw [installStacks_outside _ _ (not_exists.mp h), installStacks_outside _ _ (not_exists.mp h)]
+
+include hports in
+theorem multiply_framed (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (i j : Fin dim.val) (a m : K) : ∃ time ≤ MultiplyCall.callCap e w,
+ (MultiplyCall.machine.onPorts (ports ∘ Port.arithmetic)).Runs time
+ (frame (bank φ w dim i (word j) (bits φ w m) a extra))
+ (frame (bank φ w dim i (word j) [] (a*m) extra)) := by
+ have hp := hports.comp (fun _ _ h ↦ Port.arithmetic.inj h)
+ obtain ⟨time, htime, h⟩ := MultiplyCall.machine_runs he hw c (scalarEncoding φ m) (scalarEncoding φ a)
+ rw [mul_scalarEncoding φ, mul_comm m a] at h
+ refine ⟨time, htime, MultiplyCall.machine.runs_onPorts_framed (ports := ports ∘ Port.arithmetic) hp h
+ (fun _ ↦ installStacks_at hports ..) (fun _ ↦ installStacks_at hports ..) ?_⟩
+ intro k hk
+ by_cases h : ∃ t, ports t = k
+ · obtain ⟨t, rfl⟩ := h
+ rw [installStacks_at hports, installStacks_at hports]
+ cases t with
+ | arithmetic x => exact (hk x rfl).elim
+ | indices | width | aux => rfl
+ · rw [installStacks_outside _ _ (not_exists.mp h), installStacks_outside _ _ (not_exists.mp h)]
+
+include hports in
+theorem commit_framed (i j : Fin dim.val) (a : K) :
+ (IndexRegisters.commit.onPorts (ports ∘ Port.indices)).Runs (5*v+3)
+ (frame (bank φ w dim i (word j) [] a extra)) (frame (bank φ w dim j [] [] a extra)) := by
+ have h := IndexRegisters.commit_runs (BurstRAM.wordBits dim) (word i) (word j)
+ simp only [BurstRAM.length_wordBits] at h
+ rw [show v+4*v+3 = 5*v+3 by omega] at h
+ apply IndexRegisters.commit.runs_onPorts_framed (ports := ports ∘ Port.indices)
+ (hports.comp (fun _ _ h ↦ Port.indices.inj h)) h (fun _ ↦ installStacks_at hports ..)
+ (fun _ ↦ installStacks_at hports ..)
+ intro k hk
+ by_cases h : ∃ t, ports t = k
+ · obtain ⟨t, rfl⟩ := h
+ rw [installStacks_at hports, installStacks_at hports]
+ cases t with
+ | indices x => exact (hk x rfl).elim
+ | arithmetic | width | aux => rfl
+ · rw [installStacks_outside _ _ (not_exists.mp h), installStacks_outside _ _ (not_exists.mp h)]
+
+/-- Per-step bound, with the advised coordinate query as its only
+singly-exponential operation. This bound does not involve the exponent width. -/
+def ticks (v e w queryTicks : ℕ) := (10*v+5) + queryTicks + MultiplyCall.callCap e w + (5*v+3)
+
+include hports in
+/-- Each distinct next ordinal is presented to the scalar query exactly once.
+The branch leaves the product of the chosen entry and the previous accumulator
+in the canonical representation, with a bounded index-dependent delay. -/
+theorem callback_count (he : 0 < e) (hw : Word.workingWidth p ≤ w) (read : FiniteRoutine Q)
+ (matrix : Matrix (Fin dim.val) (Fin dim.val) K) (i : Fin dim.val) (a : K)
+ (queryTicks : ℕ) (query : ∀ j : Fin dim.val, ∃ d ≤ queryTicks, read.Runs d
+ (frame (bank φ w dim i (word j) [] a extra))
+ (frame (bank φ w dim i (word j) (bits φ w (matrix i j)) a extra)))
+ (fuel : ℕ) (hfuel : ticks v e w queryTicks ≤ fuel) :
+ ∃ delay : Fin dim.val → ℕ, (∀ j, delay j ≤ ticks v e w queryTicks) ∧
+ ∀ cont, (callback ports read).body.count cont fuel (frame (bank φ w dim i [] [] a extra)) =
+ ∑ j, cont (fuel-delay j) (frame (bank φ w dim j [] [] (a*matrix i j) extra)) := by
+ choose q hq qr using query
+ choose m hm mr using fun j ↦ multiply_framed φ ports hports ambient extra dim he hw i j a (matrix i j)
+ let delay (j : Fin dim.val) := (10*v+5) + q j + m j + (5*v+3)
+ have hdelay (j : Fin dim.val) : delay j ≤ ticks v e w queryTicks := by
+ dsimp [delay, ticks]
+ have := hq j
+ have := hm j
+ omega
+ refine ⟨delay, hdelay, fun cont ↦ ?_⟩
+ have enough : 10*v+5 ≤ fuel := by unfold ticks at hfuel; omega
+ rw [show fuel = fuel - (10*v+5) + (10*v+5) by omega, callback]
+ simp only [FiniteRoutine.followedBy, FiniteRoutine.ofRoutine, Routine.count_followedBy]
+ rw [select_framed φ ports hports ambient extra dim]
+ apply Finset.sum_congr rfl
+ intro j _
+ have hd := (hdelay j).trans hfuel
+ dsimp only [delay] at hd ⊢
+ have h₁ := (qr j).count_eq ((MultiplyCall.machine.onPorts (ports ∘ Port.arithmetic)).body.count
+ ((IndexRegisters.commit.onPorts (ports ∘ Port.indices)).body.count cont)) (fuel-(10*v+5)-q j)
+ rw [Nat.sub_add_cancel (by omega)] at h₁
+ have h₂ := (mr j).count_eq ((IndexRegisters.commit.onPorts (ports ∘ Port.indices)).body.count cont)
+ (fuel-(10*v+5)-q j-m j)
+ rw [Nat.sub_add_cancel (by omega)] at h₂
+ have h₃ := (commit_framed (w := w) φ ports hports ambient extra dim i j (a*matrix i j)).count_eq cont
+ (fuel-(10*v+5)-q j-m j-(5*v+3))
+ rw [Nat.sub_add_cancel (by omega)] at h₃
+ simp only [Nat.sub_sub] at h₁ h₂ h₃
+ rw [Nat.sub_add_cancel enough]
+ exact (h₁.trans h₂).trans h₃
+
+end Evaluator.WeightedStep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/EventualBounds.lean b/lean/OAI/Computability/VPVNP/EventualBounds.lean
new file mode 100644
index 0000000000..03d07ea7fa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/EventualBounds.lean
@@ -0,0 +1,79 @@
+import Mathlib.Analysis.SpecialFunctions.Pow.NthRootLemmas
+import Mathlib.Order.Monotone.Basic
+
+/-!
+# Transfer of eventual circuit-size bounds under polynomial projections
+
+Section 15.1 of *VP and VNP differ over every field* uses two properties of a
+complete family: its order-`j` polynomial projects from its order-`j+1`
+polynomial for `j ≥ 2`, and the hard family projects from orders at most
+`A * n ^ b`. Both projections preserve upper bounds on the number of binary
+gates. The result below transfers the eventual lower bounds to every order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+/-- The all-sufficiently-large-length lower bound for each positive exponent. -/
+def EventuallySuperpolynomial (size : ℕ → ℕ) : Prop :=
+ ∀ C : ℕ, 1 ≤ C → ∃ N : ℕ, ∀ n ≥ N, n ^ C < size n
+
+/-- Section 15.1. For every order `m` above a fixed threshold, the floor root
+of `m / A` supplies a length `n` whose projected order is at most `m` and whose
+lower bound already exceeds `m ^ C`. The projection indices may have gaps. -/
+theorem eventualBound_of_polynomialProjection
+ {hard complete q : ℕ → ℕ} {A b n₀ : ℕ} (hA : 0 < A) (hb : 0 < b)
+ (hhard : EventuallySuperpolynomial hard)
+ (hproj : ∀ n ≥ n₀, 2 ≤ q n ∧ q n ≤ A * n ^ b ∧ hard n ≤ complete (q n))
+ (hstep : ∀ j ≥ 2, complete j ≤ complete (j + 1)) (C : ℕ) :
+ ∃ M : ℕ, ∀ m ≥ M, m ^ C < complete m := by
+ obtain ⟨N, hN⟩ := hhard (b * C + 1) (Nat.le_add_left 1 _)
+ let K := A * 2 ^ b
+ let threshold := max (max N n₀) (max 1 (K ^ C))
+ refine ⟨A * threshold ^ b, ?_⟩
+ intro m hm
+ let n := Nat.nthRoot b (m / A)
+ have hn : threshold ≤ n := (Nat.le_nthRoot_iff hb.ne').mpr <|
+ (Nat.le_div_iff_mul_le hA).mpr (by simpa [Nat.mul_comm] using hm)
+ have hnN : N ≤ n := le_trans ((le_max_left ..).trans (le_max_left ..)) hn
+ have hn₀ : n₀ ≤ n := le_trans ((le_max_right ..).trans (le_max_left ..)) hn
+ have hn1 : 1 ≤ n := le_trans ((le_max_left ..).trans (le_max_right ..)) hn
+ have hK : K ^ C ≤ n := le_trans ((le_max_right ..).trans (le_max_right ..)) hn
+ obtain ⟨hq₂, hq, hred⟩ := hproj n hn₀
+ have hqm : q n ≤ m := hq.trans <| by
+ rw [Nat.mul_comm]
+ exact (Nat.le_div_iff_mul_le hA).mp (Nat.pow_nthRoot_le (.inl hb.ne'))
+ have hmupper : m ≤ K * n ^ b := calc
+ m ≤ (n + 1) ^ b * A := ((Nat.div_lt_iff_lt_mul hA).mp
+ (Nat.lt_pow_nthRoot_add_one hb.ne' (m / A))).le
+ _ ≤ (2 * n) ^ b * A := Nat.mul_le_mul_right A (Nat.pow_le_pow_left (by omega) b)
+ _ = K * n ^ b := by simp [K, mul_pow, Nat.mul_comm, Nat.mul_left_comm]
+ calc
+ m ^ C ≤ (K * n ^ b) ^ C := Nat.pow_le_pow_left hmupper C
+ _ = n ^ (b * C) * K ^ C := by rw [mul_pow, pow_mul, Nat.mul_comm]
+ _ ≤ n ^ (b * C + 1) := by rw [pow_succ]; exact Nat.mul_le_mul_left _ hK
+ _ < hard n := hN n hnN
+ _ ≤ complete (q n) := hred
+ _ ≤ complete m := monotoneOn_nat_Ici_of_le_succ hstep hq₂ (hq₂.trans hqm) hqm
+
+/-- An eventual lower bound for each exponent excludes every polynomial size
+bound, including bounds with a multiplicative constant and a length cutoff. -/
+theorem EventuallySuperpolynomial.not_polynomially_bounded {size : ℕ → ℕ}
+ (hsize : EventuallySuperpolynomial size) :
+ ¬ ∃ A d N : ℕ, ∀ n ≥ N, size n ≤ A * n ^ d := by
+ rintro ⟨A, d, N, hupper⟩
+ obtain ⟨M, hlower⟩ := hsize (d + 1) (Nat.le_add_left 1 d)
+ let n := max A (max M N)
+ have hA : A ≤ n := le_max_left ..
+ have hM : M ≤ n := (le_max_left ..).trans (le_max_right ..)
+ have hN : N ≤ n := (le_max_right ..).trans (le_max_right ..)
+ apply (hlower n hM).not_ge
+ calc
+ size n ≤ A * n ^ d := hupper n hN
+ _ ≤ n * n ^ d := Nat.mul_le_mul_right _ hA
+ _ = n ^ (d + 1) := by rw [pow_succ, Nat.mul_comm]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExactOneClauses.lean b/lean/OAI/Computability/VPVNP/ExactOneClauses.lean
new file mode 100644
index 0000000000..93834762e1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExactOneClauses.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.HardnessCNF
+import Mathlib.Data.Fintype.EquivFin
+import Mathlib.Data.Fintype.Sigma
+import Mathlib.Data.Fintype.Prod
+import Mathlib.Data.Fintype.Sum
+
+/-!
+# Exact-one clauses for a CNF verifier
+
+Each clause selects one literal occurrence. Its selector requires that occurrence
+to be true and all earlier occurrences to be false. Each implication uses one
+filler bit in an exact-one triple. Pairs outside the triangular part of the table
+receive a singleton constraint fixing their filler to false.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ExactOne
+
+open HardnessCNF
+variable {k : ℕ}
+
+/-- An exact-one constraint counts literal occurrences, including repetitions. -/
+def Holds (φ : CNF k) (x : Fin k → Bool) : Prop :=
+ ∀ c ∈ φ, c.countP (fun l => x l.1 == l.2) = 1
+
+/-- A literal occurrence identified by its clause and its position within that clause. -/
+abbrev Occ (φ : CNF k) := Σ c : Fin φ.length, Fin (φ[c].length)
+
+/-- An ordered pair of literal occurrences in the same clause, including pairs with equal
+positions. -/
+abbrev PairOcc (φ : CNF k) := Σ c : Fin φ.length, Fin (φ[c].length) × Fin (φ[c].length)
+
+/-- Variables of the exact-one encoding, partitioned into original data bits, occurrence
+selectors, and pair fillers. -/
+abbrev Slot (φ : CNF k) := Fin k ⊕ (Occ φ ⊕ PairOcc φ)
+
+/-- Total number of Boolean variables in the exact-one encoding of the formula. -/
+def width (φ : CNF k) := Fintype.card (Slot φ)
+
+/-- Number the three kinds of exact-one variables by finite ordinals. -/
+noncomputable def index (φ : CNF k) : Slot φ ≃ Fin (width φ) := Fintype.equivFin _
+
+/-- Variable index in the exact-one encoding that carries the original Boolean variable `v`. -/
+noncomputable def data (φ : CNF k) (v : Fin k) : Fin (width φ) := index φ (.inl v)
+
+/-- Variable index marking occurrence `i` as the selected literal in clause `c`. -/
+noncomputable def selector (φ : CNF k) (c : Fin φ.length) (i : Fin (φ[c].length)) :
+ Fin (width φ) := index φ (.inr (.inl ⟨c,i⟩))
+
+/-- Variable index for the filler attached to ordered positions `i,j` in clause `c`. -/
+noncomputable def filler (φ : CNF k) (c : Fin φ.length) (i j : Fin (φ[c].length)) :
+ Fin (width φ) := index φ (.inr (.inr ⟨c,i,j⟩))
+
+/-- Recover the original assignment from an assignment to the enlarged exact-one variable set. -/
+noncomputable def original (φ : CNF k) (x : Fin (width φ) → Bool) : Fin k → Bool :=
+ x ∘ data φ
+
+/-- Bit required by selector `i` when testing occurrence `j ≤ i`. -/
+def needed (φ : CNF k) (y : Fin k → Bool) (c : Fin φ.length) (i j : Fin (φ[c].length)) :
+ Bool :=
+ let l := φ[c][j]
+ if j = i then y l.1 == l.2 else !(y l.1 == l.2)
+
+/-- Clause of positive occurrence selectors requiring exactly one selected position in the
+original clause. -/
+noncomputable def selectorClause (φ : CNF k) (c : Fin φ.length) : List (Literal (width φ)) :=
+ (List.finRange (φ[c].length)).map fun i => (selector φ c i, true)
+
+/-- Exact-one constraint comparing a candidate selector at `i` with occurrence `j`, with a
+filler bit making the choice canonical. -/
+noncomputable def pairClause (φ : CNF k) (c : Fin φ.length) (i j : Fin (φ[c].length)) :
+ List (Literal (width φ)) :=
+ let l := φ[c][j]
+ if j ≤ i then [(selector φ c i, true), (data φ l.1, if j = i then !l.2 else l.2),
+ (filler φ c i j, true)]
+ else [(filler φ c i j, false)]
+
+/-- The selector clause and all ordered-pair constraints for one clause of the original
+formula. -/
+noncomputable def rows (φ : CNF k) (c : Fin φ.length) : CNF (width φ) :=
+ selectorClause φ c :: (List.finRange (φ[c].length)).flatMap fun i =>
+ (List.finRange (φ[c].length)).map (pairClause φ c i)
+
+/-- Polynomial-size exact-one CNF with original, selector and filler variables. -/
+noncomputable def augment (φ : CNF k) : CNF (width φ) :=
+ (List.finRange φ.length).flatMap (rows φ)
+
+/-- Exactly one occurrence selector in clause `c` is true under assignment `x`. -/
+noncomputable def selectedOnce (φ : CNF k) (x : Fin (width φ) → Bool) (c : Fin φ.length) : Prop :=
+ (List.finRange (φ[c].length)).countP (fun i => x (selector φ c i)) = 1
+
+private def exactlyOne {n : ℕ} (x : Fin n → Bool) (c : List (Literal n)) : Prop :=
+ c.countP (fun l => x l.1 == l.2) = 1
+
+private theorem exactlyOne_selector (φ : CNF k) (x : Fin (width φ) → Bool)
+ (c : Fin φ.length) : exactlyOne x (selectorClause φ c) ↔ selectedOnce φ x c := by
+ simp [exactlyOne, selectorClause, selectedOnce, List.countP_map, Function.comp_def]
+
+private theorem triple (a b f : Bool) :
+ ((if f then 1 else 0) + (if !b then 1 else 0) + (if a then 1 else 0) = 1) ↔
+ (a = true → b = true) ∧ f = (b && !a) := by
+ cases a <;> cases b <;> cases f <;> decide
+
+private theorem exactlyOne_pair (φ : CNF k) (x : Fin (width φ) → Bool)
+ (c : Fin φ.length) (i j : Fin (φ[c].length)) :
+ exactlyOne x (pairClause φ c i j) ↔
+ if j ≤ i then
+ (x (selector φ c i) = true → needed φ (original φ x) c i j = true) ∧
+ x (filler φ c i j) = (needed φ (original φ x) c i j && !(x (selector φ c i)))
+ else x (filler φ c i j) = false := by
+ by_cases hji : j ≤ i
+ · have complement :
+ (x (data φ (φ[c][j]).1) == (if j = i then !(φ[c][j]).2 else (φ[c][j]).2)) =
+ !(needed φ (original φ x) c i j) := by
+ unfold needed original
+ simp only [Function.comp_apply]
+ split <;> cases h : x (data φ (φ[c][j]).1) <;> cases hp : (φ[c][j]).2 <;> rfl
+ simp only [exactlyOne, pairClause, ite_eq_left hji, List.countP_cons, List.countP_nil,
+ Nat.zero_add, complement, beq_iff_eq]
+ exact triple _ _ _
+ · cases hx : x (filler φ c i j) <;> simp [exactlyOne, pairClause, hji, hx]
+
+/-- Exact-one satisfaction determines one selector per clause, forces the tested
+literal or its negation when that selector is true, and determines every filler bit. -/
+theorem holds_augment_iff (φ : CNF k) (x : Fin (width φ) → Bool) :
+ Holds (augment φ) x ↔ (∀ c, selectedOnce φ x c) ∧ ∀ c i j,
+ if j ≤ i then
+ (x (selector φ c i) = true → needed φ (original φ x) c i j = true) ∧
+ x (filler φ c i j) = (needed φ (original φ x) c i j && !(x (selector φ c i)))
+ else x (filler φ c i j) = false := by
+ change (∀ row ∈ augment φ, exactlyOne x row) ↔ _
+ have hh : (∀ row ∈ augment φ, exactlyOne x row) ↔
+ ∀ c, exactlyOne x (selectorClause φ c) ∧ ∀ i j, exactlyOne x (pairClause φ c i j) := by
+ simp only [augment, rows, List.mem_flatMap, List.mem_finRange, true_and, List.mem_cons,
+ List.mem_map, forall_exists_index, or_imp, forall_and]
+ aesop
+ rw [hh]
+ simp only [exactlyOne_selector, exactlyOne_pair, forall_and]
+
+end ExactOne
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExactOneFamily.lean b/lean/OAI/Computability/VPVNP/ExactOneFamily.lean
new file mode 100644
index 0000000000..901b1f2e12
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExactOneFamily.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.CNFNormalization
+import OAI.Computability.VPVNP.ExactOnePadding
+import OAI.Computability.VPVNP.Hardness
+
+/-!
+# Polynomial-size exact-one presentations of VNP families
+
+The weighted CNF for a VNP summand can be replaced by exact-one clauses
+without changing its generating polynomial. Clause normalization bounds the
+number of clause vertices used by the graph reductions. A fixed false bit
+gives every instance at least one variable.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ExactOne
+
+open HardnessCNF MvPolynomial
+
+variable {F : Type*} [Field F] {V : ℕ → Type} [∀ n, Fintype (V n)]
+
+/-- The Boolean variables carry only projection labels. Variable count,
+clause count and literal-occurrence count are all polynomially bounded. -/
+theorem exists_family_of_isVNP (p : Family F V) (hp : IsVNP p) :
+ ∃ (k : ℕ → ℕ) (φ : ∀ n, CNF (k n)) (w : ∀ n, Projection F (Fin (k n)) (V n)),
+ (∀ n, 0 < k n) ∧ PolynomiallyBounded k ∧
+ PolynomiallyBounded (fun n => (φ n).length) ∧
+ PolynomiallyBounded (fun n => literalCount (φ n)) ∧
+ ∀ n, weightedExactOne (φ n) (fun i => (w n i).elim X C) = p n := by
+ obtain ⟨k, φ, w, hk, hl, hφ⟩ := Hardness.exists_weightedCNF_of_isVNP p hp
+ let ψ := fun n => normalizeClauses (φ n)
+ obtain ⟨hL, hlen⟩ := normalizeClauses_polynomial_bounds φ hl
+ obtain ⟨hwidth, hocc⟩ := polynomial_bounds ψ hk hL
+ refine ⟨fun n => width (ψ n) + 1, fun n => pad (augment (ψ n)),
+ fun n => padProjection (augmentProjection (ψ n) (w n)), fun _ => Nat.succ_pos _,
+ hwidth.add (.const 1), ?_, ?_, ?_⟩
+ · have hrows := (hlen.add (hL.pow 2)).of_le (fun n => length_augment_le (ψ n))
+ simpa only [length_pad] using hrows.add (.const 1)
+ · simpa only [literalCount_pad] using hocc.add (.const 1)
+ · intro n
+ rw [weightedExactOne_padProjection]
+ simp_rw [augmentProjection_eval, weightedExactOne_augment, ψ, weightedCNF_normalizeClauses]
+ exact hφ n
+
+end ExactOne
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExactOneFirst.lean b/lean/OAI/Computability/VPVNP/ExactOneFirst.lean
new file mode 100644
index 0000000000..de57220aa6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExactOneFirst.lean
@@ -0,0 +1,60 @@
+import Mathlib.Data.Finset.Max
+import Mathlib.Data.Fintype.Basic
+import Mathlib.Data.List.FinRange
+
+/-!
+# Selecting the first satisfied literal
+
+Each literal occurrence is indexed by its position. In a satisfied clause, the
+first match is unique even when the same literal occurs at several positions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ExactOne
+
+variable {m : ℕ}
+
+/-- A true bit with no earlier true bit. -/
+def firstMatch (f : Fin m → Bool) (i : Fin m) : Bool :=
+ decide (f i = true ∧ ∀ j < i, f j = false)
+
+theorem firstMatch_iff (f : Fin m → Bool) (i : Fin m) :
+ firstMatch f i = true ↔ f i = true ∧ ∀ j < i, f j = false := by
+ simp [firstMatch]
+
+theorem firstMatch_unique (f : Fin m → Bool) {i j : Fin m}
+ (hi : firstMatch f i = true) (hj : firstMatch f j = true) : i = j := by
+ rw [firstMatch_iff] at hi hj
+ rcases lt_trichotomy i j with h | h | h
+ · exact False.elim (by simpa [hi.1] using hj.2 i h)
+ · exact h
+ · exact False.elim (by simpa [hj.1] using hi.2 j h)
+
+theorem existsUnique_firstMatch (f : Fin m → Bool) (hf : ∃ i, f i = true) :
+ ∃! i, firstMatch f i = true := by
+ let s := Finset.univ.filter (fun i => f i = true)
+ have hs : s.Nonempty := by simpa [s, Finset.Nonempty] using hf
+ let i := s.min' hs
+ have hi : firstMatch f i = true := by
+ rw [firstMatch_iff]
+ refine ⟨by simpa [s] using s.min'_mem hs, fun j hj => ?_⟩
+ cases h : f j with
+ | false => rfl
+ | true => exact (not_le_of_gt hj (s.min'_le j (by simp [s, h]))).elim
+ exact ⟨i, hi, fun j hj => firstMatch_unique f hj hi⟩
+
+theorem countP_finRange_eq_one (f : Fin m → Bool) :
+ (List.finRange m).countP f = 1 ↔ ∃! i, f i = true := by
+ have h := (List.nodup_finRange m).card_eq_countP (P := fun i => f i = true)
+ simp only [Bool.decide_eq_true] at h
+ rw [← h, Finset.card_eq_one_iff_existsUnique]
+ simp
+
+end ExactOne
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExactOneOccurrences.lean b/lean/OAI/Computability/VPVNP/ExactOneOccurrences.lean
new file mode 100644
index 0000000000..f6a5f1d1f8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExactOneOccurrences.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.ExactOneFirst
+import OAI.Computability.VPVNP.ExactOneSize
+
+/-!
+# Flattening exact-one literal occurrences for the graph reductions
+
+The graph for Hamiltonian cycles and the graph for cycle covers have one indexed
+occurrence per literal position. Each occurrence retains its variable, clause,
+and polarity. Multiple occurrences of the same literal stay distinct.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ExactOne
+
+open HardnessCNF
+
+variable {k : ℕ}
+
+theorem card_occ (φ : CNF k) : Fintype.card (Occ φ) = literalCount φ := by
+ simp only [Occ, Fintype.card_sigma, Fintype.card_fin, sum_lengths]
+
+/-- The graph may number occurrences by any bijection. -/
+noncomputable def occurrenceIndex (φ : CNF k) : Fin (literalCount φ) ≃ Occ φ :=
+ (Fintype.equivFinOfCardEq (card_occ φ)).symm
+
+/-- The variable, clause and satisfying bit of occurrence `j`. -/
+noncomputable def occurrences (φ : CNF k) (j : Fin (literalCount φ)) :
+ Fin k × Fin φ.length × Bool :=
+ let z := occurrenceIndex φ j
+ let lit := φ[z.1][z.2]
+ (lit.1, z.1, lit.2)
+
+private theorem countP_eq_one_iff_position {A : Type*} (c : List A) (f : A → Bool) :
+ c.countP f = 1 ↔ ∃! j : Fin c.length, f c[j] = true := by
+ have hc : (List.finRange c.length).map (fun i : Fin c.length => c[i]) = c := by
+ rw [← List.ofFn_eq_map]
+ exact List.ofFn_getElem
+ have h := countP_finRange_eq_one (fun i : Fin c.length => f c[i])
+ have eqCount := congrArg (List.countP f) hc
+ rw [List.countP_map] at eqCount
+ rw [← eqCount]
+ exact h
+
+private theorem existsUnique_occ_iff (φ : CNF k) (x : Fin k → Bool) (a : Fin φ.length) :
+ (∃! z : Occ φ, z.1 = a ∧ x (φ[z.1][z.2]).1 = (φ[z.1][z.2]).2) ↔
+ ∃! i : Fin φ[a].length, x (φ[a][i]).1 = (φ[a][i]).2 := by
+ constructor
+ · rintro ⟨⟨c, i⟩, ⟨rfl, hi⟩, hu⟩
+ refine ⟨i, hi, fun j hj => ?_⟩
+ exact eq_of_heq (Sigma.mk.inj_iff.mp (hu ⟨c, j⟩ ⟨rfl, hj⟩)).2
+ · rintro ⟨i, hi, hu⟩
+ refine ⟨⟨a, i⟩, ⟨rfl, hi⟩, ?_⟩
+ rintro ⟨c, j⟩ ⟨rfl, hj⟩
+ exact congrArg (Sigma.mk c) (hu j hj)
+
+/-- Exact-one satisfaction is equivalent to one true numbered occurrence in each clause. -/
+theorem holds_iff_unique_occurrence (φ : CNF k) (x : Fin k → Bool) :
+ Holds φ x ↔ ∀ a : Fin φ.length, ∃! j : Fin (literalCount φ),
+ (occurrences φ j).2.1 = a ∧ x (occurrences φ j).1 = (occurrences φ j).2.2 := by
+ simp only [Holds, List.forall_mem_iff_get]
+ apply forall_congr'
+ intro a
+ rw [countP_eq_one_iff_position]
+ simp only [beq_iff_eq]
+ exact (existsUnique_occ_iff φ x a).symm.trans
+ (occurrenceIndex φ).existsUnique_congr_right.symm
+
+/-- Any family member containing an empty clause has zero satisfying assignments. -/
+theorem not_holds_of_nil_mem {φ : CNF k} (h : [] ∈ φ) (x : Fin k → Bool) : ¬ Holds φ x := by
+ intro hx
+ simpa using hx [] h
+
+/-- Without empty clauses the graph's number of clause vertices is at most the literal count. -/
+theorem length_le_literalCount_of_nil_notMem {φ : CNF k} (h : [] ∉ φ) :
+ φ.length ≤ literalCount φ := by
+ rw [← sum_lengths]
+ have hpos (c : Fin φ.length) : 1 ≤ φ[c].length := by
+ have hc : φ[c] ≠ [] := fun he => h (he ▸ List.getElem_mem _)
+ exact List.length_pos_iff.mpr hc
+ simpa using Finset.sum_le_sum (s := Finset.univ) (fun c _ => hpos c)
+
+end ExactOne
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExactOnePadding.lean b/lean/OAI/Computability/VPVNP/ExactOnePadding.lean
new file mode 100644
index 0000000000..c23b216fab
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExactOnePadding.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.ExactOneWeights
+
+/-!
+# A dummy variable for exact-one instances
+
+The Hamiltonian graph needs at least one variable track. Adding a final variable
+and a singleton negative clause gives each old assignment a unique extension
+with the same weight, including when the original instance has no variables.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ExactOne
+
+open HardnessCNF MvPolynomial
+open scoped Classical
+
+variable {k : ℕ} {R τ : Type*}
+
+/-- Embed the old variables as the initial coordinates and force the final one to false. -/
+def pad (φ : CNF k) : CNF (k + 1) :=
+ [(Fin.last k, false)] :: φ.map (List.map fun l => (l.1.castSucc, l.2))
+
+/-- The forced coordinate carries the unit label. -/
+def padProjection [One R] (w : Projection R (Fin k) τ) : Projection R (Fin (k + 1)) τ :=
+ Fin.snoc (α := fun _ => τ ⊕ R) w (.inr 1)
+
+@[simp] theorem length_pad (φ : CNF k) : (pad φ).length = φ.length + 1 := by simp [pad]
+
+@[simp] theorem literalCount_pad (φ : CNF k) : literalCount (pad φ) = literalCount φ + 1 := by
+ simp [pad, literalCount, List.map_map, Function.comp_def, Nat.add_comm]
+
+/-- The old coordinates retain all the old constraints. -/
+theorem holds_pad_iff (φ : CNF k) (x : Fin (k + 1) → Bool) :
+ Holds (pad φ) x ↔ x (Fin.last k) = false ∧ Holds φ (fun i => x i.castSucc) := by
+ cases hx : x (Fin.last k) <;>
+ simp [Holds, pad, List.countP_map, Function.comp_def, hx]
+
+/-- The added variable has weight one in every satisfying product because it is forced false. -/
+theorem weightedExactOne_pad [CommSemiring R] (φ : CNF k) (w : Fin (k + 1) → R) :
+ weightedExactOne (pad φ) w = weightedExactOne φ (fun i => w i.castSucc) := by
+ let e := Fin.snocEquiv (n := k) (fun _ => Bool)
+ unfold weightedExactOne
+ rw [← e.sum_comp (fun x => if Holds (pad φ) x then ∏ i, if x i then w i else 1 else 0),
+ Fintype.sum_prod_type, Fintype.sum_bool]
+ simp only [holds_pad_iff, e, Fin.snocEquiv_apply, Fin.snoc_last, Fin.snoc_castSucc,
+ Bool.true_eq_false, false_and, ite_false, Finset.sum_const_zero, zero_add, true_and]
+ apply Finset.sum_congr rfl
+ intro x _
+ by_cases hx : Holds φ x
+ · simp [hx, Fin.prod_univ_castSucc, Fin.snoc_last, Fin.snoc_castSucc]
+ · simp [hx]
+
+/-- Variable-or-constant labels of the original exact-one polynomial lift to the padded graph. -/
+theorem weightedExactOne_padProjection [CommSemiring R] (φ : CNF k) (w : Projection R (Fin k) τ) :
+ weightedExactOne (pad φ) (fun i => (padProjection w i).elim X C) =
+ weightedExactOne φ (fun i => (w i).elim X C) := by
+ simp [weightedExactOne_pad, padProjection]
+
+end ExactOne
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExactOneSize.lean b/lean/OAI/Computability/VPVNP/ExactOneSize.lean
new file mode 100644
index 0000000000..00ca167a98
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExactOneSize.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.ExactOneClauses
+import OAI.Computability.VPVNP.PolynomialBounds
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Data.Fintype.BigOperators
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+
+/-!
+# Size of the exact-one verifier
+
+A clause with `m` occurrences has `m` selector bits and `m²` filler bits.
+The selector clause has `m` literals, and each of its `m²` pair clauses has at
+most three literals. Summing over the original clauses gives quadratic bounds
+in the total number of literal occurrences, even in the presence of empty clauses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ExactOne
+
+open HardnessCNF
+
+variable {k : ℕ}
+
+/-- Sum of the clause lengths in their indexed presentation. -/
+theorem sum_lengths (φ : CNF k) : (∑ c : Fin φ.length, φ[c].length) = literalCount φ := by
+ rw [← Fin.sum_ofFn]
+ exact congrArg List.sum (List.ofFn_getElem_eq_map φ List.length)
+
+private theorem sum_squares_le (φ : CNF k) :
+ (∑ c : Fin φ.length, φ[c].length ^ 2) ≤ literalCount φ ^ 2 := by
+ calc
+ _ ≤ ∑ c : Fin φ.length, φ[c].length * literalCount φ := by
+ apply Finset.sum_le_sum
+ intro c hc
+ rw [pow_two, ← sum_lengths]
+ exact Nat.mul_le_mul_left _ (Finset.single_le_sum (fun i _ => Nat.zero_le (φ[i].length)) hc)
+ _ = _ := by rw [← Finset.sum_mul, sum_lengths, pow_two]
+
+/-- The selectors and fillers use at most `L + L²` new variables. -/
+theorem width_le (φ : CNF k) : width φ ≤ k + literalCount φ + literalCount φ ^ 2 := by
+ simp only [width, Slot, Occ, PairOcc, Fintype.card_sum, Fintype.card_sigma, Fintype.card_fin,
+ Fintype.card_prod, ← pow_two, sum_lengths, Nat.add_assoc]
+ exact Nat.add_le_add_left (Nat.add_le_add_left (sum_squares_le φ) _) _
+
+private theorem rows_length (φ : CNF k) (c : Fin φ.length) :
+ (rows φ c).length = 1 + φ[c].length ^ 2 := by
+ simp [rows, List.length_flatMap, pow_two, Nat.add_comm]
+
+/-- One selector clause is retained per original clause, including empty ones. -/
+theorem length_augment_le (φ : CNF k) : (augment φ).length ≤ φ.length + literalCount φ ^ 2 := by
+ rw [augment, List.length_flatMap, ← Fin.sum_univ_def]
+ simp only [rows_length, Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ,
+ Fintype.card_fin, smul_eq_mul, mul_one]
+ exact Nat.add_le_add_left (sum_squares_le φ) _
+
+private theorem literalCount_flatMap {A : Type*} (xs : List A) (f : A → CNF k) :
+ literalCount (xs.flatMap f) = (xs.map fun a => literalCount (f a)).sum := by
+ induction xs with
+ | nil => rfl
+ | cons a xs ih => simpa [literalCount] using ih
+
+private theorem pairClause_length_le (φ : CNF k) (c : Fin φ.length) (i j : Fin (φ[c].length)) :
+ (pairClause φ c i j).length ≤ 3 := by
+ by_cases h : j ≤ i <;> simp [pairClause, h]
+
+private theorem literalCount_rows_le (φ : CNF k) (c : Fin φ.length) :
+ literalCount (rows φ c) ≤ φ[c].length + 3 * φ[c].length ^ 2 := by
+ change (selectorClause φ c).length + literalCount _ ≤ _
+ simp only [selectorClause, List.length_map, List.length_finRange, literalCount_flatMap,
+ ← Fin.sum_univ_def]
+ apply Nat.add_le_add_left
+ have h (i : Fin (φ[c].length)) : literalCount ((List.finRange _).map (pairClause φ c i)) ≤
+ φ[c].length * 3 := by
+ simp only [literalCount, List.map_map, ← Fin.sum_univ_def]
+ simpa using Finset.sum_le_sum (s := Finset.univ) (fun j _ => pairClause_length_le φ c i j)
+ simpa [pow_two, Nat.mul_left_comm, Nat.mul_assoc, Nat.mul_comm] using
+ Finset.sum_le_sum (s := Finset.univ) (fun i _ => h i)
+
+/-- A bound depending only on literal occurrences, even with arbitrarily many empty clauses. -/
+theorem literalCount_augment_le (φ : CNF k) :
+ literalCount (augment φ) ≤ literalCount φ + 3 * literalCount φ ^ 2 := by
+ rw [augment, literalCount_flatMap, ← Fin.sum_univ_def]
+ calc
+ _ ≤ ∑ c : Fin φ.length, (φ[c].length + 3 * φ[c].length ^ 2) :=
+ Finset.sum_le_sum (fun c _ => literalCount_rows_le φ c)
+ _ ≤ _ := by
+ rw [Finset.sum_add_distrib, sum_lengths, ← Finset.mul_sum]
+ exact Nat.add_le_add_left (Nat.mul_le_mul_left _ (sum_squares_le φ)) _
+
+/-- Polynomially bounded families of CNF verifiers retain polynomial width and literal count. -/
+theorem polynomial_bounds {k : ℕ → ℕ} (φ : ∀ n, CNF (k n))
+ (hk : PolynomiallyBounded k) (hL : PolynomiallyBounded fun n => literalCount (φ n)) :
+ PolynomiallyBounded (fun n => width (φ n)) ∧
+ PolynomiallyBounded (fun n => literalCount (augment (φ n))) :=
+ ⟨((hk.add hL).add (hL.pow 2)).of_le (fun n => width_le (φ n)),
+ (hL.add ((PolynomiallyBounded.const 3).mul (hL.pow 2))).of_le
+ (fun n => literalCount_augment_le (φ n))⟩
+
+end ExactOne
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExactOneSolutions.lean b/lean/OAI/Computability/VPVNP/ExactOneSolutions.lean
new file mode 100644
index 0000000000..c50a77c99b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExactOneSolutions.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.ExactOneFirst
+import OAI.Computability.VPVNP.ExactOneClauses
+
+/-!
+# The parsimonious conversion from CNF to exact-one constraints
+
+For a satisfying assignment, the selector in each clause marks its first
+satisfied literal. This fixes the filler of every implication. Conversely an
+assignment meeting the exact-one constraints must use these same selectors
+and fillers. Restricting to the input bits therefore gives a bijection.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ExactOne
+
+open HardnessCNF
+
+variable {k : ℕ}
+
+private def hit (φ : CNF k) (y : Fin k → Bool) (c : Fin φ.length) (i : Fin (φ[c].length)) :
+ Bool := y (φ[c][i]).1 == (φ[c][i]).2
+
+private theorem satisfies_iff_hits (φ : CNF k) (y : Fin k → Bool) :
+ Satisfies φ y ↔ ∀ c : Fin φ.length, ∃ i, hit φ y c i = true := by
+ simp only [Satisfies, List.forall_mem_iff_get, List.exists_mem_iff_get, hit, beq_iff_eq]
+ rfl
+
+private theorem firstMatch_iff_needed (φ : CNF k) (y : Fin k → Bool) (c : Fin φ.length)
+ (i : Fin (φ[c].length)) :
+ firstMatch (hit φ y c) i = true ↔ ∀ j ≤ i, needed φ y c i j = true := by
+ rw [firstMatch_iff]
+ constructor
+ · rintro ⟨hi, hprefix⟩ j hj
+ rcases eq_or_lt_of_le hj with rfl | hlt
+ · simpa [needed, hit] using hi
+ · have h := hprefix j hlt
+ simpa [needed, hit, hlt.ne] using h
+ · intro h
+ refine ⟨by simpa [needed, hit] using h i le_rfl, fun j hj => ?_⟩
+ simpa [needed, hit, hj.ne] using h j hj.le
+
+/-- The unique extension of a satisfying assignment sets the first-match selectors
+and the complementary filler in each active implication. -/
+private noncomputable def encode (φ : CNF k) (y : Fin k → Bool) : Fin (width φ) → Bool :=
+ fun v => ((index φ).symm v).elim y (Sum.elim
+ (fun ⟨c, i⟩ => firstMatch (hit φ y c) i)
+ (fun ⟨c, i, j⟩ => if j ≤ i then needed φ y c i j && !(firstMatch (hit φ y c) i) else false))
+
+@[simp] private theorem encode_data (φ : CNF k) (y : Fin k → Bool) (v : Fin k) :
+ encode φ y (data φ v) = y v := by simp [encode, data]
+
+@[simp] private theorem original_encode (φ : CNF k) (y : Fin k → Bool) :
+ original φ (encode φ y) = y := by funext i; exact encode_data _ _ i
+
+@[simp] private theorem encode_selector (φ : CNF k) (y : Fin k → Bool) (c : Fin φ.length)
+ (i : Fin (φ[c].length)) : encode φ y (selector φ c i) = firstMatch (hit φ y c) i := by
+ simp [encode, selector]
+
+@[simp] private theorem encode_filler (φ : CNF k) (y : Fin k → Bool) (c : Fin φ.length)
+ (i j : Fin (φ[c].length)) :
+ encode φ y (filler φ c i j) =
+ if j ≤ i then needed φ y c i j && !(firstMatch (hit φ y c) i) else false := by
+ simp [encode, filler]
+
+private theorem holds_encode (φ : CNF k) (y : Fin k → Bool) (hy : Satisfies φ y) :
+ Holds (augment φ) (encode φ y) := by
+ apply (holds_augment_iff φ _).2
+ refine ⟨fun c => ?_, fun c i j => ?_⟩
+ · simp only [selectedOnce, encode_selector, countP_finRange_eq_one]
+ exact existsUnique_firstMatch _ ((satisfies_iff_hits φ y).1 hy c)
+ · simp only [original_encode, encode_selector, encode_filler]
+ by_cases hji : j ≤ i
+ · simp only [hji, ite_true, and_true]
+ exact fun hs => (firstMatch_iff_needed φ y c i).1 hs j hji
+ · simp [hji]
+
+private theorem selector_is_first (φ : CNF k) (x : Fin (width φ) → Bool)
+ (hx : Holds (augment φ) x) (c : Fin φ.length) (i : Fin (φ[c].length)) :
+ x (selector φ c i) = firstMatch (hit φ (original φ x) c) i := by
+ obtain ⟨honce, hpairs⟩ := (holds_augment_iff φ x).1 hx
+ have hfirst (a : Fin (φ[c].length)) (ha : x (selector φ c a) = true) :
+ firstMatch (hit φ (original φ x) c) a = true := by
+ apply (firstMatch_iff_needed _ _ _ _).2
+ intro j hj
+ have hp := hpairs c a j
+ simp only [hj, ite_true] at hp
+ exact hp.1 ha
+ apply Bool.eq_iff_iff.mpr
+ refine ⟨hfirst i, fun hi => ?_⟩
+ obtain ⟨a, ha, _⟩ := (countP_finRange_eq_one _).1 (honce c)
+ exact firstMatch_unique _ (hfirst a ha) hi ▸ ha
+
+private theorem satisfies_original (φ : CNF k) (x : Fin (width φ) → Bool)
+ (hx : Holds (augment φ) x) : Satisfies φ (original φ x) := by
+ apply (satisfies_iff_hits _ _).2
+ intro c
+ obtain ⟨i, hi, _⟩ :=
+ (countP_finRange_eq_one _).1 (((holds_augment_iff φ x).1 hx).1 c)
+ rw [selector_is_first _ _ hx] at hi
+ exact ⟨i, ((firstMatch_iff _ _).1 hi).1⟩
+
+private theorem encode_original (φ : CNF k) (x : Fin (width φ) → Bool)
+ (hx : Holds (augment φ) x) : encode φ (original φ x) = x := by
+ funext v
+ obtain ⟨s, rfl⟩ := (index φ).surjective v
+ rcases s with v | ⟨c, i⟩ | ⟨c, i, j⟩
+ · exact encode_data φ (original φ x) v
+ · exact (encode_selector φ (original φ x) c i).trans (selector_is_first φ x hx c i).symm
+ · change encode φ (original φ x) (filler φ c i j) = x (filler φ c i j)
+ rw [encode_filler, ← selector_is_first φ x hx]
+ have hf := ((holds_augment_iff φ x).1 hx).2 c i j
+ by_cases hji : j ≤ i
+ · simp only [hji, ite_true] at hf ⊢
+ exact hf.2.symm
+ · simp only [hji, ite_false] at hf ⊢
+ exact hf.symm
+
+/-- Each satisfying input has exactly one extension to the exact-one formula. -/
+noncomputable def solutionsEquiv (φ : CNF k) :
+ {x : Fin (width φ) → Bool // Holds (augment φ) x} ≃
+ {y : Fin k → Bool // Satisfies φ y} where
+ toFun x := ⟨original φ x.val, satisfies_original _ _ x.property⟩
+ invFun y := ⟨encode φ y.val, holds_encode _ _ y.property⟩
+ left_inv x := Subtype.ext (encode_original _ _ x.property)
+ right_inv y := Subtype.ext (original_encode φ y.val)
+
+@[simp] theorem solutionsEquiv_apply (φ : CNF k) (x) :
+ (solutionsEquiv φ x).val = original φ x.val := rfl
+
+end ExactOne
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExactOneWeights.lean b/lean/OAI/Computability/VPVNP/ExactOneWeights.lean
new file mode 100644
index 0000000000..d90110e0bd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExactOneWeights.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.ExactOneSolutions
+import OAI.Computability.VPVNP.HardnessWeights
+
+/-!
+# Weighted exact-one reduction
+
+The original variables retain their weights. Every selector and filler has
+weight one, so the unique extension of an assignment preserves its contribution
+over any commutative semiring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ExactOne
+
+open HardnessCNF MvPolynomial
+open scoped Classical
+
+variable {k : ℕ} {R : Type*}
+
+/-- Weighted generating function of assignments meeting each clause exactly once. -/
+noncomputable def weightedExactOne [CommSemiring R] (φ : CNF k) (w : Fin k → R) : R :=
+ ∑ x, if Holds φ x then ∏ i, if x i then w i else 1 else 0
+
+/-- A selector or filler receives the supplied neutral label. -/
+private noncomputable def extendLabels {A : Type*} (φ : CNF k) (w : Fin k → A) (neutral : A)
+ (i : Fin (width φ)) : A :=
+ ((index φ).symm i).elim w (fun _ => neutral)
+
+/-- Extend the weights to all Boolean variables of the exact-one instance. -/
+noncomputable def augmentWeight [One R] (φ : CNF k) (w : Fin k → R) : Fin (width φ) → R :=
+ extendLabels φ w 1
+
+/-- The extension also preserves variable-or-constant projection labels. -/
+noncomputable def augmentProjection {τ : Type*} [One R] (φ : CNF k)
+ (w : Projection R (Fin k) τ) : Projection R (Fin (width φ)) τ :=
+ extendLabels φ w (.inr 1)
+
+theorem augmentProjection_eval {τ : Type*} [CommSemiring R] (φ : CNF k)
+ (w : Projection R (Fin k) τ) (i : Fin (width φ)) :
+ (augmentProjection φ w i).elim X C = augmentWeight φ (fun j => (w j).elim X C) i := by
+ obtain ⟨s, rfl⟩ := (index φ).surjective i
+ cases s <;> simp [augmentProjection, augmentWeight, extendLabels]
+
+private theorem product_augmentWeight [CommSemiring R] (φ : CNF k)
+ (w : Fin k → R) (x : Fin (width φ) → Bool) :
+ (∏ i, if x i then augmentWeight φ w i else 1) =
+ ∏ j, if original φ x j then w j else 1 := by
+ rw [← (index φ).prod_comp (fun i => if x i then augmentWeight φ w i else 1),
+ Fintype.prod_sum_type]
+ simp [augmentWeight, extendLabels, original, data]
+ rfl
+
+theorem weightedExactOne_eq_sum [CommSemiring R] (φ : CNF k) (w : Fin k → R) :
+ weightedExactOne φ w =
+ ∑ x : {x : Fin k → Bool // Holds φ x}, ∏ i, if x.val i then w i else 1 := by
+ rw [weightedExactOne, ← Finset.sum_filter]
+ exact Finset.sum_subtype _ (by simp) _
+
+/-- The exact-one reduction preserves the entire generating polynomial. -/
+theorem weightedExactOne_augment [CommSemiring R] (φ : CNF k) (w : Fin k → R) :
+ weightedExactOne (augment φ) (augmentWeight φ w) = weightedCNF φ w := by
+ have hcnf : weightedCNF φ w =
+ ∑ y : {y : Fin k → Bool // Satisfies φ y}, ∏ j, if y.val j then w j else 1 := by
+ rw [weightedCNF, ← Finset.sum_filter]
+ exact Finset.sum_subtype _ (by simp) _
+ rw [weightedExactOne_eq_sum, hcnf]
+ rw [← (solutionsEquiv φ).sum_comp (fun y => ∏ j, if y.val j then w j else 1)]
+ exact Finset.sum_congr rfl fun x _ => product_augmentWeight φ w x.val
+
+end ExactOne
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExactTensorPowerLayout.lean b/lean/OAI/Computability/VPVNP/ExactTensorPowerLayout.lean
new file mode 100644
index 0000000000..aaa7b15e96
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExactTensorPowerLayout.lean
@@ -0,0 +1,40 @@
+import OAI.Computability.VPVNP.SharpTensorLayout
+import OAI.Computability.VPVNP.TensorPowerSharpProjection
+
+/-!
+# Tensor-power obstruction at the original exponent
+
+The weighted incidence machine encodes the tensor form with length
+`A * (h + 1)^4 * (2^b)^h`. Inserting this actual projection into the balanced
+layout estimate recovers the central exponent `C` of Theorem 4.2.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial WireTensor TensorPowerCNF
+
+variable {k : Type*} [Field k] {I : Type} [Fintype I] [DecidableEq I]
+ {P : Type*} [Fintype P] [Nonempty P]
+
+/-- An actual spectral witness above every balanced layout rules out arbitrarily
+large small-circuit lengths of the universal counting polynomial. -/
+theorem not_small_universal_of_exact_tensorPower_layout (F : SpectralPoint k P)
+ (place : I → P) (centers : Finset I → Bool → P) {b C : ℕ} (hb : 0 < b) (hC : 0 < C)
+ (hI : 3 ≤ Fintype.card I) (A : (I → Fin (2^b)) → k) (hnz : A ≠ 0)
+ {scale threshold : ℝ} (hs : 0 < scale)
+ (hlower : threshold <
+ Real.logb 2 (F.value (placedTensor place (fun _ ↦ Fin (2^b)) A)) / (scale * b))
+ (hcost : ∀ S : Finset I, Fintype.card I ≤ 3*S.card → 3*S.card ≤ 2*Fintype.card I →
+ (C : ℝ) * F.wireDistance (centers S false) (centers S true) +
+ ∑ i, F.wireDistance (place i) (centers S (cutSide S i)) ≤ scale * threshold) :
+ ¬ ∀ N, ∃ n ≥ N, circuitSize (map (Int.castRingHom k) (VPVNP.P n)) ≤ n^C := by
+ apply not_small_universal_of_sharp_tensor_layout F place centers hb hC hI A hnz hs hlower hcost
+ intro T
+ obtain ⟨M, hM, hproj⟩ := TensorPowerCNF.sharp_projection T
+ exact ⟨M, 4, hM, hproj⟩
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExpandedMonomialDegree.lean b/lean/OAI/Computability/VPVNP/ExpandedMonomialDegree.lean
new file mode 100644
index 0000000000..e959de8a65
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExpandedMonomialDegree.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.CompressionDegreeCoverage
+
+/-!
+# Degrees of paths in an expanded network contraction
+
+The exponent of a complete path is the sum of its local map exponents. At a
+placement node the previous factors are visited once in their placement fiber.
+This associates each expanded path to a branch of the term history and bounds
+its total degree using the map records of that same branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace NetworkKernel
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A}
+variable {N : Network}
+
+/-- Pushing a vertex factor adds the degrees of the kernel and of its children. -/
+theorem Term.pushWitness_degree_le (t : Term A N) (F : Factors A N)
+ (W : ∀ u z, MonomialWitness κ (F u z)) (K : ∀ v a z, MonomialWitness κ (t.kernel v a z))
+ (rec : t.output.Site → SiteRecords) (previous : N.Site → ℕ) (B : ℕ)
+ (hW : ∀ u z c, (∑ l, (W u z).exponents c l) ≤ previous u * B)
+ (hK : ∀ v a z c, (∑ l, (K v a z).exponents c l) ≤ ∑ j, (rec v).degree j)
+ (hB : ∀ v j, (rec v).degree j ≤ B) (v : t.output.Site) (z : t.output.Half v)
+ (c : (t.pushWitness F W K v z).Choice) :
+ (∑ l, (t.pushWitness F W K v z).exponents c l) ≤ t.pushHistorySize rec previous v * B := by
+ classical
+ obtain ⟨⟨a, children, own⟩, rfl⟩ := (t.pushChoice F W K v z).symm.surjective c
+ simp only [Term.pushChoice_exponents, Finset.sum_add_distrib]
+ rw [Finset.sum_comm]
+ have hc : Fintype.card (rec v).Map ≤ (rec v).count := by unfold SiteRecords.count; omega
+ have hk : (∑ j, (rec v).degree j) ≤ (rec v).count * B := calc
+ _ ≤ ∑ _ : (rec v).Map, B := Finset.sum_le_sum fun j _ => hB v j
+ _ ≤ _ := by simpa using Nat.mul_le_mul_right B hc
+ rw [Term.pushHistorySize, Nat.add_mul, Finset.sum_mul, Nat.add_comm]
+ exact Nat.add_le_add ((hK v a z own).trans hk) (Finset.sum_le_sum fun u _ => hW _ _ _)
+
+namespace History
+
+/-- Each expanded choice selects a single term chain. Its records suffice to
+bound the exponents for any valid input occurrence bound and map degree cap. -/
+def DegreeBound {Z : Type} {Y : Z → Network} (H : History A N) (K : H.KernelWitnesses κ)
+ (chains : ∀ z, TermChain A N (Y z)) : Prop :=
+ ∀ (F : Factors A N) (W : ∀ u z, MonomialWitness κ (F u z))
+ (c : (H.expandedWitness K F W).Choice), ∃ z : Z, ∀ (previous : N.Site → ℕ) (B : ℕ),
+ (∀ u x w, (∑ l, (W u x).exponents w l) ≤ previous u * B) →
+ (chains z).AllRecordsLe B →
+ (∑ l, (H.expandedWitness K F W).exponents c l) ≤ ∑ v, (chains z).occurrences previous v * B
+
+theorem DegreeBound.stop (K : (History.stop (k := A) (N := N)).KernelWitnesses κ) :
+ DegreeBound .stop K (fun _ : Unit => TermChain.done N) := by
+ intro F W c
+ obtain ⟨⟨a, choices⟩, rfl⟩ := (History.stopChoice K F W).symm.surjective c
+ refine ⟨(), fun previous B hW _ => ?_⟩
+ simp only [History.stopChoice_exponents, TermChain.occurrences]
+ rw [Finset.sum_comm]
+ exact Finset.sum_le_sum fun v _ => hW _ _ _
+
+theorem DegreeBound.branch (s : Step A N) (tail : ∀ i, History A (s.term i).output)
+ (K : (History.branch s tail).KernelWitnesses κ)
+ (rec : ∀ i, (s.term i).output.Site → SiteRecords)
+ {Z : s.Choice → Type} {Y : ∀ i, Z i → Network}
+ (chains : ∀ i z, TermChain A (s.term i).output (Y i z))
+ (hK : ∀ i v a z c, (∑ l, (K.1 i v a z).exponents c l) ≤ ∑ j, (rec i v).degree j)
+ (hTail : ∀ i, DegreeBound (tail i) (K.2 i) (chains i)) :
+ DegreeBound (History.branch s tail) K (fun (z : (i : s.Choice) × Z i) =>
+ TermChain.more (s.term z.1) (rec z.1) (chains z.1 z.2)) := by
+ intro F W c
+ obtain ⟨⟨i, rest⟩, rfl⟩ := (History.branchChoice s tail K F W).symm.surjective c
+ obtain ⟨z, hz⟩ := hTail i _ _ rest
+ refine ⟨⟨i, z⟩, fun previous B hW hB => ?_⟩
+ simp only [History.branchChoice_exponents, TermChain.occurrences]
+ exact hz _ B
+ ((s.term i).pushWitness_degree_le F W (K.1 i) (rec i) previous B hW (hK i) hB.2.1) hB.2.2
+
+open private transportWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+
+/-- Identify a pass output with the network of the next state, transporting
+the history, witnesses, and selected term chains together. -/
+theorem DegreeBound.castInput {N' : Network} (e : N = N') {Z : Type} {Y : Z → Network}
+ (H : History A N) (K : H.KernelWitnesses κ) (chains : ∀ z, TermChain A N (Y z))
+ (h : DegreeBound H K chains) :
+ DegreeBound (e ▸ H) (transportWitnesses e H K) (fun z => e ▸ chains z) := by
+ cases e
+ exact h
+
+/-- Local RAM paths have exponent zero before any kernels are pushed. -/
+theorem DegreeBound.expandedCount {Z : Type} {Y : Z → Network} (H : History A N)
+ (K : H.KernelWitnesses κ) (chains : ∀ z, TermChain A N (Y z))
+ (h : DegreeBound H K chains) (P : ∀ u, N.Half u → Type) [∀ u x, Fintype (P u x)]
+ (c : (H.expandedCount K P).Choice) : ∃ z : Z, ∀ B, (chains z).AllRecordsLe B →
+ (∑ l, (H.expandedCount K P).exponents c l) ≤
+ ∑ v, (chains z).occurrences (fun _ => 1) v * B := by
+ obtain ⟨z, hz⟩ := h _ (fun u x => MonomialWitness.paths κ (P u x)) c
+ exact ⟨z, fun B hB => hz _ B (fun _ _ _ => by simp [MonomialWitness.paths]) hB⟩
+
+end History
+end NetworkKernel
+
+namespace Compression.StateExecution
+
+open NetworkKernel
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {κ : L → R}
+variable {a g b n : ℕ} {X : State a g}
+
+/-- Lift per-site degree coverage to each complete monomial of a state execution. -/
+theorem history_degreeBound (E : StateExecution R b n X) (K : E.MapWitnesses κ)
+ (rec : E.Records) (hc : E.DegreeCovered K rec) :
+ E.history.DegreeBound (E.historyWitnesses K) (E.termChain rec) := by
+ induction E with
+ | done X => exact History.DegreeBound.stop _
+ | more p tail ih =>
+ apply History.DegreeBound.branch p.step (fun i => (p.output_eq i).symm ▸ (tail i).history)
+ ((more p tail).historyWitnesses K) rec.1
+ (Z := fun i => (tail i).Choices) (Y := fun i z => ((tail i).finalState z).network)
+ (fun i z => (p.output_eq i).symm ▸ (tail i).termChain (rec.2 i) z) hc.1
+ exact fun i => (ih i (K.2 i) (rec.2 i) (hc.2 i)).castInput (p.output_eq i).symm _ _ _
+
+end Compression.StateExecution
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExpanderOrders.lean b/lean/OAI/Computability/VPVNP/ExpanderOrders.lean
new file mode 100644
index 0000000000..2f9af929b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExpanderOrders.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.CloudIteration
+
+/-!
+# Arbitrarily large dyadic graph orders
+
+Section 5.3 of *VP and VNP differ over every field* iterates a fixed port graph
+and then removes loops by doubling. A real line in the target class forces
+each resulting multigraph to be connected.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {T : Type*} (Y : T → Type*) [∀ a, PseudoMetricSpace (Y a)]
+ [∀ a, CompleteSpace (Y a)] [∀ a, Nonempty (Y a)]
+
+/-- A port graph of dyadic order and degree yields connected, loopless
+multigraphs of unbounded dyadic order, with one degree and one Poincaré
+bound for all orders and targets. -/
+theorem exists_expander_orders {s e n : ℕ} (hs : 0 < s) (hn : 0 < n)
+ (H : Matrix (Fin (2 ^ s)) (Fin (2 ^ s)) ℕ) (hHs : ∀ i j, H i j = H j i)
+ (hHr : ∀ i, ∑ j, H i j = 2 ^ e) {β : ℝ} (hβ : 1 ≤ β)
+ (ht : 1776 * β ≤ 2 * (n : ℝ))
+ (hdiv : (2 * n) * (2 * (2 * 2 ^ e)) ^ (2 * n) ∣ 2 ^ s)
+ (hcat : ∀ a, HasCATZeroSegments (Y a))
+ (hH : ∀ a, HasPoincareBound (Y a) (normalizeArcs H (2 ^ e)) β)
+ (realTarget : T) (embed : ℝ → Y realTarget)
+ (h_embed : ∀ a b, dist (embed a) (embed b) = dist a b) (minimum : ℕ) :
+ ∃ o : ℕ, minimum ≤ 2 ^ o ∧
+ ∃ G : Matrix (Fin (2 ^ o)) (Fin (2 ^ o)) ℕ, (∀ i j, G i j = G j i) ∧
+ (∀ i, G i i = 0) ∧ (∀ i, ∑ j, G i j = 2 ^ (e + 2)) ∧
+ (∀ i j, Relation.ReflTransGen (fun a b ↦ 0 < G a b) i j) ∧
+ ∀ a, HasPoincareBound (Y a) (normalizeArcs G (2 ^ (e + 2))) (6 + 12 * (444 * β)) := by
+ have order : 2 * (2 ^ s) ^ minimum = 2 ^ (s * minimum + 1) := by
+ rw [pow_succ, pow_mul, Nat.mul_comm]
+ have degree : 4 * 2 ^ e = 2 ^ (e + 2) := by
+ rw [pow_add, Nat.mul_comm, show (2 : ℕ) ^ 2 = 4 by decide]
+ have hmin : minimum ≤ 2 ^ (s * minimum + 1) := by
+ apply minimum.lt_two_pow_self.le.trans
+ apply Nat.pow_le_pow_right (by decide)
+ have := Nat.mul_le_mul_right minimum (show 1 ≤ s from hs)
+ omega
+ have doubled := exists_looplessCloudGraph Y (by positivity) (by positivity) hn
+ H hHs hHr hβ ht hdiv hcat hH minimum
+ rw [order, degree] at doubled
+ obtain ⟨G, hsymm, hregular, hloop, hbound⟩ := doubled
+ refine ⟨s * minimum + 1, hmin, G, hsymm, hloop, hregular, ?_, hbound⟩
+ let P := normalizeArcs G (2 ^ (e + 2))
+ have hsep : 0 < dist (embed 0) (embed 1) := by rw [h_embed]; norm_num [Real.dist_eq]
+ have nonnegP (i j) : 0 ≤ P i j := by unfold P normalizeArcs; positivity
+ have symmP (i j) : P i j = P j i := by simp only [P, normalizeArcs, hsymm i j]
+ intro i j
+ apply Relation.ReflTransGen.mono _ i j <|
+ reachable_of_poincare (embed 0) (embed 1) hsep P nonnegP symmP (hbound realTarget) i j
+ intro a b hab
+ have hpos : (0 : ℝ) < G a b := (div_pos_iff_of_pos_right (by positivity)).mp hab
+ exact_mod_cast hpos
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExpanderSlots.lean b/lean/OAI/Computability/VPVNP/ExpanderSlots.lean
new file mode 100644
index 0000000000..89802c4b55
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExpanderSlots.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.RegularArcGraph
+import OAI.Computability.VPVNP.SlotGraph
+
+/-!
+# Numbering the arcs of a regular expander
+
+The graph supplied by Theorem 5.1 has paired arcs. The wire construction
+uses one outgoing and one incoming slot for each arc. At the destination
+we use the outgoing number of its reverse as the incoming slot number.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {V : Type*} {d : ℕ}
+
+/-- Use paired arcs as the outgoing and incoming slots of a directed graph. -/
+def RegularArcGraph.toSlotGraph (G : RegularArcGraph V d) : Compression.SlotGraph V d :=
+ ⟨G.reverse, G.ends_ne⟩
+
+/-- A loop-free symmetric multiplicity matrix with constant degree admits a
+slot numbering with exactly its specified arc counts. -/
+theorem exists_expanderSlots [Fintype V] [DecidableEq V] (M : V → V → ℕ)
+ (hsym : ∀ u v, M u v = M v u) (hrow : ∀ u, ∑ v, M u v = d) (hdiag : ∀ u, M u u = 0) :
+ ∃ H : Compression.SlotGraph V d, ∀ u v,
+ (Finset.univ.filter (fun h : Fin d ↦ (H.target (u, h)).1 = v)).card = M u v := by
+ obtain ⟨G, hG⟩ := exists_regularArcGraph M hsym hrow hdiag
+ exact ⟨G.toSlotGraph, hG⟩
+
+end SpectralGeometry
+
+namespace Compression.SlotGraph
+
+/-- Group a sum over the outgoing slots of a vertex by destination. This
+also applies when the cost depends on the source, by fixing the source. -/
+theorem sum_outgoing {V A : Type*} [Fintype V] [DecidableEq V] [AddCommMonoid A] {d : ℕ}
+ (H : SlotGraph V d) (M : V → V → ℕ)
+ (hcount : ∀ u v, (Finset.univ.filter (fun h : Fin d ↦ (H.target (u, h)).1 = v)).card = M u v)
+ (u : V) (cost : V → A) :
+ ∑ h : Fin d, cost (H.target (u, h)).1 = ∑ v, M u v • cost v := by
+ simpa only [Finset.sum_const, hcount] using
+ (Finset.sum_fiberwise' Finset.univ (fun h : Fin d ↦ (H.target (u, h)).1) cost).symm
+
+end Compression.SlotGraph
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Expanders.lean b/lean/OAI/Computability/VPVNP/Expanders.lean
new file mode 100644
index 0000000000..148f62c768
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Expanders.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.ExpanderOrders
+import OAI.Computability.VPVNP.SparseGrassmannFamily
+import OAI.Computability.VPVNP.GrassmannInequality
+import OAI.Computability.VPVNP.WalkDenominators
+
+/-!
+# Expanders from uniform exclusion of a Euclidean cube
+
+Theorem 5.1 of *VP and VNP differ over every field*. The strict Grassmann
+inequality supplies a sparse family with growth exponent below the plane
+dimension. Choose the iteration count first, then the starting size, so the
+resulting port graph admits both smoothing and an integral port matching.
+Cloud replacement and the loopless double give fixed degree and Poincaré
+bound at arbitrarily large power-of-two orders.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+universe u
+
+variable {κ : Type*} (Y : κ → Type u) [∀ i, PseudoMetricSpace (Y i)]
+
+open Grassmann
+
+private theorem choosePortGraph {ℓ : ℕ} (hℓ : 2 ≤ ℓ) (hcat : ∀ k, HasCATZeroSegments (Y k))
+ (hexclude : cubeDistances ℓ ∉ closure (markedDistances Y (Finset (Fin ℓ)))) :
+ ∃ (s e n : ℕ) (β : ℝ) (H : Matrix (Fin (2 ^ s)) (Fin (2 ^ s)) ℕ),
+ 0 < s ∧ 0 < n ∧ 1 ≤ β ∧ 1776 * β ≤ 2 * (n : ℝ) ∧
+ (2 * n) * (2 * (2 * 2 ^ e)) ^ (2 * n) ∣ 2 ^ s ∧
+ (∀ i j, H i j = H j i) ∧ (∀ i, ∑ j, H i j = 2 ^ e) ∧
+ ∀ a, HasPoincareBound (Y a) (normalizeArcs H (2 ^ e)) β := by
+ let r := ℓ
+ have hr : 0 < r := by dsimp [r]; omega
+ have hm : ℓ < 2 ^ r := Nat.lt_two_pow_self
+ obtain ⟨η, hη, hgap⟩ := strict_grassmann_bound Y hm hcat hexclude
+ obtain ⟨α, C', hα, hsmall, _, hgraphs⟩ := exists_sparse_rounded_family Y (by omega : 1 < 2 ^ r)
+ (sub_lt_self _ hη) hgap
+ push_cast at hsmall
+ obtain ⟨j, k, hk, hfour, hβ⟩ := exists_walk_smoothing_scale r hr hα.le hsmall C'
+ obtain ⟨k, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hk.ne'
+ obtain ⟨Cj, _, hCj⟩ := hgraphs j
+ obtain ⟨d, _, hd₂, hdvd⟩ := exists_walk_port_order (k+1) Cj 2
+ have hd : 0 < d := by by_contra! h; simp [Nat.eq_zero_of_le_zero h] at hd₂
+ let s := d * ((2 ^ r) ^ j)
+ have hs : 0 < s := Nat.mul_pos hd (pow_pos (pow_pos (by decide) _) _)
+ have hsize : ((2 ^ d) ^ ((2 ^ r) ^ j) : ℕ) = 2 ^ s := (pow_mul _ _ _).symm
+ have h := hCj d hd
+ rw [hsize] at h
+ obtain ⟨e, he, H, hsym, hrow, hH⟩ := h
+ have hdiv := hdvd (e+1) (by rw [pow_succ']; nlinarith only [he])
+ rw [← hfour, hsize, pow_succ' 2 e, pow_succ' 2 k] at hdiv
+ let β := max 1 (2 * C' * α ^ j)
+ refine ⟨s, e, 2 ^ k, β, H, hs, by positivity, le_max_left _ _, ?_, hdiv, hsym, hrow, ?_⟩
+ · simpa only [Nat.cast_pow, Nat.cast_ofNat, pow_succ'] using hβ
+ · intro a x
+ apply (hH a x).trans
+ apply mul_le_mul_of_nonneg_right (le_max_right _ _)
+ exact Finset.sum_nonneg fun i _ ↦ Finset.sum_nonneg fun j _ ↦
+ mul_nonneg (show 0 ≤ normalizeArcs H (2 ^ e) i j by unfold normalizeArcs; positivity)
+ (sq_nonneg _)
+
+/-- Theorem 5.1. The vertex sets are `Fin (2 ^ o)` and the integral arc
+multiplicities describe connected loopless symmetric `2 ^ e`-regular
+multigraphs. The degree and the Poincaré constant precede the order bound
+and work for every space in the original class. -/
+theorem expanders_of_cube_exclusion [∀ a, CompleteSpace (Y a)] {ℓ : ℕ}
+ (hcat : ∀ a, HasCATZeroSegments (Y a))
+ (hexclude : cubeDistances ℓ ∉ closure (markedDistances Y (Finset (Fin ℓ)))) :
+ ∃ (e : ℕ) (γ : ℝ), 0 < γ ∧ ∀ minimum : ℕ, ∃ o : ℕ, minimum ≤ 2 ^ o ∧
+ ∃ G : Matrix (Fin (2 ^ o)) (Fin (2 ^ o)) ℕ, (∀ i j, G i j = G j i) ∧
+ (∀ i, G i i = 0) ∧ (∀ i, ∑ j, G i j = 2 ^ e) ∧
+ (∀ i j, Relation.ReflTransGen (fun a b ↦ 0 < G a b) i j) ∧
+ ∀ a, HasPoincareBound (Y a) (normalizeArcs G (2 ^ e)) γ := by
+ let I := {a : κ // Nonempty (Y a)}
+ let X : I → Type u := fun i ↦ Y i.val
+ let (i : I) : Nonempty (X i) := i.property
+ have hx : cubeDistances ℓ ∉ closure (markedDistances X (Finset (Fin ℓ))) := by
+ intro h
+ apply hexclude
+ refine closure_mono ?_ h
+ rintro _ ⟨a, s, hs, x, rfl⟩
+ exact ⟨a.val, s, hs, x, rfl⟩
+ let L := max 2 ℓ
+ have hL : 2 ≤ L := le_max_left _ _
+ have hex := withRealLine_cube_exclusion X hL (cube_exclusion_mono X (le_max_right _ _) hx)
+ have hcat' := withRealLine_hasCATZeroSegments X (fun a ↦ hcat a.val)
+ obtain ⟨s, e, n, β, H, hs, hn, hβ, ht, hdiv, hsym, hrow, hH⟩ :=
+ choosePortGraph (withRealLine X) hL hcat' hex
+ refine ⟨e+2, 6 + 12 * (444 * β), by linarith only [hβ], fun minimum ↦ ?_⟩
+ obtain ⟨o, ho, G, hsym', hloop, hrow', hconn, hbound⟩ :=
+ exists_expander_orders (withRealLine X) hs hn H hsym hrow hβ ht hdiv hcat' hH none
+ (fun a ↦ ULift.up a) (fun _ _ ↦ rfl) minimum
+ refine ⟨o, ho, G, hsym', hloop, hrow', hconn, fun a x ↦ ?_⟩
+ have ha : Nonempty (Y a) := ⟨x ⟨0, pow_pos (by decide) _⟩⟩
+ exact hbound (some ⟨a, ha⟩) x
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExponentTrace.lean b/lean/OAI/Computability/VPVNP/ExponentTrace.lean
new file mode 100644
index 0000000000..1288826589
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExponentTrace.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.CutSchedule
+
+/-!
+# Accumulating the nominated production and gadget exponents
+
+At each live first-half cut, the program checks the primed exterior bits
+and the new cumulative exponents against the preceding cut. Section 14.1
+requires that a fixed sequence of pair paths determine exactly one sequence
+of cut strings, with zero initial exponents and zero padding. Here `inc`
+combines both kinds of label counters in the order used by the evaluator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ExponentTrace
+
+open CutSchedule
+
+/-- Fixed-width RAM word used to store a cumulative label exponent. -/
+abbrev Word := BurstRAM.Word
+
+variable {Label : Type*} {p : ℕ}
+
+private def extended (inc : Fin p → Label → ℕ) (i : ℕ) (a : Label) : ℕ :=
+ if h : i < p then inc ⟨i, h⟩ a else 0
+
+/-- Sum of the per-pair increments before a given cut. -/
+def partialSum (inc : Fin p → Label → ℕ) (j : Fin (p + 1)) (a : Label) : ℕ :=
+ ∑ i ∈ Finset.range j.val, extended inc i a
+
+@[simp] theorem prefix_zero (inc : Fin p → Label → ℕ) (a : Label) : partialSum inc 0 a = 0 := by
+ simp [partialSum]
+
+theorem prefix_step (inc : Fin p → Label → ℕ) (j : Fin p) (a : Label) :
+ partialSum inc j.succ a = partialSum inc j.castSucc a + inc j a := by
+ simp [partialSum, Finset.sum_range_succ, extended, j.isLt]
+
+theorem prefix_last (inc : Fin p → Label → ℕ) (a : Label) :
+ partialSum inc (Fin.last p) a = ∑ i, inc i a := by
+ rw [partialSum, Fin.val_last, ← Fin.sum_univ_eq_sum_range]
+ simp [extended]
+
+/-- A complete sequence of first-half cuts has one binary word for every
+nonempty cut numbered `i+1` with `i < 2^h`. -/
+abbrev LiveBits (h Δ : ℕ) := (i : Fin (2 ^ h)) → Bits (width (h + 1) Δ (i.val + 1))
+
+/-- Primed exterior cuts, including the two empty endpoint strings. -/
+abbrev Exterior (h Δ : ℕ) :=
+ (j : Fin (2 ^ h + 1)) → Bits (width (h + 1) Δ (2 * j.val))
+
+variable {h Δ t Z : ℕ} (hfit : 1 + t * Z ≤ Δ)
+
+private def fields (i : Fin (2 ^ h)) :=
+ firstHalfLayout h Δ (i.val + 1) t Z (Nat.succ_pos _) i.isLt hfit
+
+/-- Decode the running counters; before the first group all counters are zero. -/
+def counters (live : LiveBits h Δ) : Fin (2 ^ h + 1) → Fin t → Word Z :=
+ Fin.cons (fun _ => 0) (fun i => (fields hfit i (live i)).2.2.1)
+
+/-- The local checks performed by each live pair group. The equality of
+natural numbers enforces rejection on overflow. -/
+def Valid (ξ : Exterior h Δ) (inc : Fin (2 ^ h) → Fin t → ℕ) (live : LiveBits h Δ) : Prop :=
+ (∀ i, fields hfit i (live i) =
+ (true, ξ i.succ, counters hfit live i.succ, fun _ => false)) ∧
+ ∀ i a, (counters hfit live i.succ a).val = (counters hfit live i.castSucc a).val + inc i a
+
+theorem counters_eq_prefix (ξ : Exterior h Δ) (inc : Fin (2 ^ h) → Fin t → ℕ) (live : LiveBits h Δ)
+ (hv : Valid hfit ξ inc live) (j : Fin (2 ^ h + 1)) (a : Fin t) :
+ (counters hfit live j a).val = partialSum inc j a := by
+ induction j using Fin.induction with
+ | zero => simp [counters]
+ | succ i ih => rw [hv.2, ih, prefix_step]
+
+/-- For any fixed exterior choices and local pair paths whose prefix sums fit,
+the local checks admit exactly one binary first-half cut assignment. -/
+theorem existsUnique_live (ξ : Exterior h Δ) (inc : Fin (2 ^ h) → Fin t → ℕ)
+ (hbound : ∀ (i : Fin (2 ^ h)) a, partialSum inc i.succ a < 2 ^ Z) : ∃! live, Valid hfit ξ inc live := by
+ let data (i : Fin (2 ^ h)) (a : Fin t) : Word Z := ⟨partialSum inc i.succ a, hbound i a⟩
+ let live (i : Fin (2 ^ h)) := (fields hfit i).symm (true, ξ i.succ, data i, fun _ => false)
+ have hf (i : Fin (2 ^ h)) : fields hfit i (live i) = (true, ξ i.succ, data i, fun _ => false) :=
+ (fields hfit i).apply_symm_apply _
+ have hcount (j : Fin (2 ^ h + 1)) (a : Fin t) : (counters hfit live j a).val = partialSum inc j a := by
+ refine Fin.cases (by simp [counters]) (fun i => ?_) j
+ simp [counters, hf, data]
+ have hv : Valid hfit ξ inc live := by
+ refine ⟨fun i => ?_, fun i a => ?_⟩
+ · simp [counters, hf]
+ · rw [hcount, hcount, prefix_step]
+ refine ⟨live, hv, fun other ho => funext fun i => (fields hfit i).injective ?_⟩
+ rw [ho.1, hf]
+ congr 3
+ funext a
+ exact Fin.ext (counters_eq_prefix hfit ξ inc other ho i.succ a)
+
+/-- Instantiation with the paper's `Z = 2H` exponent width, where `H=h+1`.
+Every pair contributes less than `2^(2r)` to each label, even if later
+cancellation gives zero after evaluating the term's gadget labels. -/
+theorem firstHalf_no_overflow (h r : ℕ) (hr : 2 * r < h + 1)
+ (inc : Fin (2 ^ h) → Label → ℕ) (hinc : ∀ i a, inc i a < 2 ^ (2 * r))
+ (j : Fin (2 ^ h + 1)) (a : Label) : partialSum inc j a < 2 ^ (2 * (h + 1)) := by
+ have hj : j.val ≤ 2 ^ h := Nat.lt_succ_iff.mp j.isLt
+ apply accumulated_lt _ r _ (fun i => extended inc i a) (hj.trans (by rw [pow_succ]; omega)) hr
+ intro i hi
+ simp [extended, Nat.lt_of_lt_of_le hi hj, hinc]
+
+/-- At the middle cut the exponent vector passed to the evaluator is the
+sum of the increments for every primed pair. -/
+theorem middle_counters (ξ : Exterior h Δ) (inc : Fin (2 ^ h) → Fin t → ℕ) (live : LiveBits h Δ)
+ (hv : Valid hfit ξ inc live) (a : Fin t) :
+ (counters hfit live (Fin.last (2 ^ h)) a).val = ∑ i, inc i a :=
+ (counters_eq_prefix hfit ξ inc live hv _ a).trans (prefix_last inc a)
+
+end ExponentTrace
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExtensionAmplification.lean b/lean/OAI/Computability/VPVNP/ExtensionAmplification.lean
new file mode 100644
index 0000000000..59a1e6d7b8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExtensionAmplification.lean
@@ -0,0 +1,149 @@
+import Mathlib.Algebra.Order.Archimedean.Real.Basic
+import Mathlib.Algebra.Order.BigOperators.Ring.Finset
+import Mathlib.Data.Fintype.Prod
+import Mathlib.Tactic
+
+/-!
+# Finite amplification for exact spectral extension
+
+In Theorem 2.4 of *VP and VNP differ over every field*, a uniform multiplicative
+discrepancy on a finite list of generators is amplified by doubling or removing
+one exponent of a balanced product. Positive integer coefficients make the
+resulting variants dominate the balanced product at every competing spectral
+point, while their total target value is less than half its scaled target.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+/-- Either double or remove one exponent of the balanced product. -/
+def amplificationExponent {ι : Type*} [DecidableEq ι] (e : ℕ) (j : ι × Bool) (i : ι) : ℕ :=
+ if i = j.1 then (if j.2 then 2 * e else 0) else e
+
+private noncomputable def variantFactor {ι : Type*} (e : ℕ) (j : ι × Bool) (f : ι → ℝ) : ℝ :=
+ if j.2 then f j.1 ^ e else (f j.1 ^ e)⁻¹
+
+private theorem variantFactor_pos {ι : Type*} (e : ℕ) (j : ι × Bool)
+ (f : ι → ℝ) (hf : ∀ i, 0 < f i) : 0 < variantFactor e j f := by
+ dsimp [variantFactor]
+ split
+ · exact pow_pos (hf _) _
+ · exact inv_pos.mpr (pow_pos (hf _) _)
+
+private theorem variantProduct {ι : Type*} [Fintype ι] [DecidableEq ι] (e : ℕ) (j : ι × Bool)
+ (f : ι → ℝ) (hf : ∀ i, 0 < f i) :
+ (∏ i, f i ^ amplificationExponent e j i) = (∏ i, f i ^ e) * variantFactor e j f := by
+ calc
+ _ = ∏ i, f i ^ e * (if i = j.1 then variantFactor e j f else 1) := by
+ apply Finset.prod_congr rfl
+ intro i _
+ by_cases hi : i = j.1
+ · subst i
+ cases hj : j.2 <;> simp [amplificationExponent, variantFactor, hj, two_mul, pow_add,
+ (hf j.1).ne']
+ · simp [amplificationExponent, hi]
+ _ = _ := by
+ rw [Finset.prod_mul_distrib]
+ simp
+
+private theorem variantFactor_gap {ι : Type*} (f v : ι → ℝ)
+ (hf : ∀ i, 0 < f i)
+ (δ : ℝ) (hδ : 0 < δ) (e : ℕ) (B : ℝ) (he : B < (1 + δ) ^ e)
+ (i : ι) (hi : 1 + δ ≤ v i / f i ∨ 1 + δ ≤ f i / v i) :
+ ∃ j : ι × Bool, B * variantFactor e j f < variantFactor e j v := by
+ rcases hi with hi | hi
+ · refine ⟨(i, true), ?_⟩
+ have h := he.trans_le (pow_le_pow_left₀ (by linarith : 0 ≤ 1 + δ) hi e)
+ rw [div_pow] at h
+ exact (lt_div_iff₀ (pow_pos (hf i) e)).mp h
+ · refine ⟨(i, false), ?_⟩
+ have h := he.trans_le (pow_le_pow_left₀ (by linarith : 0 ≤ 1 + δ) hi e)
+ rw [div_pow] at h
+ change B * (f i ^ e)⁻¹ < (v i ^ e)⁻¹
+ rw [← div_eq_mul_inv, div_lt_iff₀ (pow_pos (hf i) e), inv_mul_eq_div]
+ exact h
+
+/-- Integer amplification multiplicities with a common scale for finitely many positive weights. -/
+theorem amplificationWeights {J : Type*} [Fintype J] (a : J → ℝ) (ha : ∀ j, 0 < a j)
+ (t : ℝ) (ht : 0 < t) :
+ ∃ L : ℕ, ∃ c : J → ℕ, 0 < L ∧ (∀ j, 0 < c j) ∧
+ ∀ j, (L : ℝ) * t < (c j : ℝ) * a j ∧ (c j : ℝ) * a j < (L : ℝ) * (2 * t) := by
+ classical
+ obtain ⟨L, hL⟩ := exists_nat_gt ((∑ j, a j) / t)
+ have hsum : 0 ≤ ∑ j, a j := Finset.sum_nonneg fun j _ => (ha j).le
+ have hLpos : 0 < (L : ℝ) := (div_nonneg hsum ht.le).trans_lt hL
+ have hscale : ∑ j, a j < (L : ℝ) * t := (div_lt_iff₀ ht).mp hL
+ refine ⟨L, fun j => ⌊(L : ℝ) * t / a j⌋₊ + 1, by exact_mod_cast hLpos,
+ fun j => Nat.succ_pos _, fun j => ?_⟩
+ push_cast
+ have hj : a j < (L : ℝ) * t :=
+ (Finset.single_le_sum (fun k _ => (ha k).le) (Finset.mem_univ j)).trans_lt hscale
+ constructor
+ · exact (div_lt_iff₀ (ha j)).mp (Nat.lt_floor_add_one _)
+ · have hfloor := Nat.floor_le (div_nonneg (mul_nonneg hLpos.le ht.le) (ha j).le)
+ have hprod := (le_div_iff₀ (ha j)).mp hfloor
+ linarith
+
+/-- A single balanced monomial and positive integer multiples of its variants
+separate the target profile from every profile with a uniform multiplicative gap. -/
+theorem finiteProfileAmplification {ι H : Type*} [Fintype ι] [Nonempty ι] [DecidableEq ι]
+ (f : ι → ℝ) (v : H → ι → ℝ) (hf : ∀ i, 0 < f i) (hv : ∀ h i, 0 < v h i)
+ (δ : ℝ) (hδ : 0 < δ)
+ (hgap : ∀ h, ∃ i, 1 + δ ≤ v h i / f i ∨ 1 + δ ≤ f i / v h i) :
+ ∃ e L : ℕ, ∃ c : ι × Bool → ℕ, 0 < e ∧ 0 < L ∧ (∀ j, 0 < c j) ∧
+ (∀ h, ∃ j, (L : ℝ) * (∏ i, v h i ^ e) <
+ (c j : ℝ) * (∏ i, v h i ^ amplificationExponent e j i)) ∧
+ (∑ j, (c j : ℝ) * (∏ i, f i ^ amplificationExponent e j i)) <
+ (L : ℝ) * (∏ i, f i ^ e) / 2 := by
+ let B : ℝ := 8 * Fintype.card ι
+ have hcard : 0 < Fintype.card ι := Fintype.card_pos
+ have hs : (1 : ℝ) ≤ Fintype.card ι := by exact_mod_cast hcard
+ have hB : 1 ≤ B := by dsimp [B]; linarith
+ have hBpos : 0 < B := by linarith
+ obtain ⟨e, he⟩ := pow_unbounded_of_one_lt B (by linarith : 1 < 1 + δ)
+ have hep : 0 < e := Nat.pos_of_ne_zero fun h => by
+ subst e
+ exact (not_lt_of_ge hB) (by simpa using he)
+ obtain ⟨L, c, hL, hc, hscale⟩ := amplificationWeights (fun j : ι × Bool => variantFactor e j f)
+ (fun j => variantFactor_pos e j f hf) B⁻¹ (inv_pos.mpr hBpos)
+ refine ⟨e, L, c, hep, hL, hc, ?_, ?_⟩
+ · intro h
+ obtain ⟨i, hi⟩ := hgap h
+ obtain ⟨j, hj⟩ := variantFactor_gap f (v h) hf δ hδ e B he i hi
+ refine ⟨j, ?_⟩
+ have hcj : (0 : ℝ) < c j := by exact_mod_cast hc j
+ have hfactor : (L : ℝ) < (c j : ℝ) * variantFactor e j (v h) :=
+ calc
+ (L : ℝ) = ((L : ℝ) * B⁻¹) * B := by simp [hBpos.ne']
+ _ < ((c j : ℝ) * variantFactor e j f) * B := mul_lt_mul_of_pos_right (hscale j).1 hBpos
+ _ = (c j : ℝ) * (B * variantFactor e j f) := by ring
+ _ < _ := mul_lt_mul_of_pos_left hj hcj
+ rw [variantProduct e j (v h) (hv h), mul_left_comm (c j : ℝ)]
+ simpa only [mul_comm (L : ℝ)] using
+ mul_lt_mul_of_pos_left hfactor (Finset.prod_pos fun i _ => pow_pos (hv h i) e)
+ · have hsum : (∑ j, (c j : ℝ) * variantFactor e j f) < (L : ℝ) / 2 := calc
+ _ < ∑ _j : ι × Bool, (L : ℝ) * (2 * B⁻¹) :=
+ Finset.sum_lt_sum_of_nonempty Finset.univ_nonempty fun j _ => (hscale j).2
+ _ = (L : ℝ) / 2 := by
+ simp [Fintype.card_prod, B, nsmul_eq_mul]
+ field_simp
+ norm_num
+ calc
+ _ = (∑ j, (c j : ℝ) * variantFactor e j f) * (∏ i, f i ^ e) := by
+ rw [Finset.sum_mul]
+ apply Finset.sum_congr rfl
+ intro j _
+ rw [variantProduct e j f hf]
+ ring
+ _ < ((L : ℝ) / 2) * (∏ i, f i ^ e) :=
+ mul_lt_mul_of_pos_right hsum (Finset.prod_pos fun i _ => pow_pos (hf i) e)
+ _ = _ := by ring
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExteriorLevelRates.lean b/lean/OAI/Computability/VPVNP/ExteriorLevelRates.lean
new file mode 100644
index 0000000000..65f9696b7c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExteriorLevelRates.lean
@@ -0,0 +1,192 @@
+import Mathlib.Analysis.SpecialFunctions.Log.Base
+import Mathlib.Analysis.SpecialFunctions.Pow.Continuity
+import Mathlib.Analysis.SpecificLimits.Basic
+import Mathlib.Data.Nat.Choose.Basic
+import Mathlib.Tactic.Linarith
+import Mathlib.Tactic.Positivity
+import Mathlib.Tactic.Ring
+
+/-!
+# Adjacent exterior dimensions
+
+Appendix A, equation (A.2), of *VP and VNP differ over every field* chooses
+three adjacent exterior powers of a `Q`-dimensional space. Rounding the real
+level `(Q + 1) / (1 + x)` approximates the target adjacent-dimension ratios
+`x` and `1 / x` within a factor of four, including the extreme levels.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open Filter
+open scoped Topology
+
+namespace ExteriorLevelRates
+
+theorem choose_up_mul (Q b : ℕ) :
+ Q.choose (b + 1) * (b + 1) = (Q - b) * Q.choose b := by
+ simpa only [Nat.mul_comm (Q.choose b)] using Nat.choose_succ_right_eq Q b
+
+theorem choose_down_mul {Q b : ℕ} (hb : 0 < b) (hQ : b ≤ Q) :
+ Q.choose (b - 1) * (Q - b + 1) = b * Q.choose b := by
+ obtain ⟨a, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hb.ne'
+ simpa only [Nat.add_one_sub_one, show Q - (a + 1) + 1 = Q - a by omega,
+ Nat.mul_comm (a + 1)] using (Nat.choose_succ_right_eq Q a).symm
+
+/-- The exact upward dimension ratio in (A.2). -/
+theorem choose_up_ratio {Q b : ℕ} (hQ : b ≤ Q) :
+ (Q.choose (b + 1) : ℝ) / Q.choose b = ((Q - b : ℕ) : ℝ) / (b + 1) := by
+ have h : (0 : ℝ) < Q.choose b := by exact_mod_cast Nat.choose_pos hQ
+ apply (div_eq_div_iff h.ne' (by positivity)).2
+ exact_mod_cast choose_up_mul Q b
+
+/-- The exact downward dimension ratio in (A.2). -/
+theorem choose_down_ratio {Q b : ℕ} (hb : 0 < b) (hQ : b ≤ Q) :
+ (Q.choose (b - 1) : ℝ) / Q.choose b = (b : ℝ) / (((Q - b : ℕ) : ℝ) + 1) := by
+ have h : (0 : ℝ) < Q.choose b := by exact_mod_cast Nat.choose_pos hQ
+ apply (div_eq_div_iff h.ne' (by positivity)).2
+ exact_mod_cast choose_down_mul hb hQ
+
+/-- The rounded level, capped to leave room for one more generator. -/
+noncomputable def level (Q : ℕ) (x : ℝ) : ℕ :=
+ min ⌊((Q : ℝ) + 1) / (1 + x)⌋₊ (Q - 1)
+
+private theorem ratio_bounds {a b y z : ℝ} (ha : 1 ≤ a) (hb : 1 ≤ b)
+ (hy : b ≤ y) (hy' : y ≤ b + 1) (hz : a ≤ z) (hz' : z ≤ a + 1) :
+ z / y / 4 ≤ a / (b + 1) ∧ a / (b + 1) ≤ z / y := by
+ constructor
+ · calc
+ z / y / 4 = (z / 2) / (2 * y) := by ring
+ _ ≤ a / (b + 1) := div_le_div₀ (by linarith) (by linarith) (by linarith) (by linarith)
+ · exact div_le_div₀ (by linarith) hz (by linarith) hy'
+
+/-- Both adjacent binomial ratios attain their target to within a factor of four. -/
+theorem level_bounds {Q : ℕ} {x : ℝ} (hQ : 2 ≤ Q) (hlo : 1 / Q ≤ x) (hhi : x ≤ Q) :
+ let b := level Q x
+ let up := (Q.choose (b + 1) : ℝ) / Q.choose b
+ let down := (Q.choose (b - 1) : ℝ) / Q.choose b
+ 1 ≤ b ∧ b < Q ∧ (x / 4 ≤ up ∧ up ≤ x) ∧ (x⁻¹ / 4 ≤ down ∧ down ≤ x⁻¹) := by
+ let b := level Q x
+ let y : ℝ := (Q + 1) / (1 + x)
+ let z : ℝ := Q + 1 - y
+ have hQr : (2 : ℝ) ≤ Q := by exact_mod_cast hQ
+ have hx : 0 < x := lt_of_lt_of_le (by positivity) hlo
+ have hden : 0 < 1 + x := by linarith
+ have hy : 1 ≤ y := (le_div_iff₀ hden).2 (by linarith)
+ have hyQ : y ≤ Q := by
+ have := (div_le_iff₀ (show 0 < (Q : ℝ) by linarith)).1 hlo
+ exact (div_le_iff₀ hden).2 (by nlinarith)
+ have hb : 1 ≤ b := le_min ((Nat.one_le_floor_iff y).2 hy) (by omega)
+ have hbQ : b < Q := lt_of_le_of_lt (min_le_right _ _) (by omega)
+ have hby : (b : ℝ) ≤ y := by
+ exact (Nat.cast_le.mpr (min_le_left _ _)).trans (Nat.floor_le (by linarith))
+ have hyb : y ≤ b + 1 := by
+ by_cases h : ⌊y⌋₊ ≤ Q - 1
+ · change y ≤ (min ⌊y⌋₊ (Q - 1) : ℕ) + (1 : ℝ)
+ rw [min_eq_left h]
+ exact (Nat.lt_floor_add_one y).le
+ · change y ≤ (min ⌊y⌋₊ (Q - 1) : ℕ) + (1 : ℝ)
+ rw [min_eq_right (by omega), Nat.cast_sub (by omega : 1 ≤ Q), Nat.cast_one]
+ linarith
+ have ha : (1 : ℝ) ≤ (Q - b : ℕ) := by exact_mod_cast (show 1 ≤ Q - b by omega)
+ have hb' : (1 : ℝ) ≤ b := by exact_mod_cast hb
+ have haz : ((Q - b : ℕ) : ℝ) ≤ z := by
+ rw [Nat.cast_sub hbQ.le]; dsimp [z]; linarith
+ have hza : z ≤ ((Q - b : ℕ) : ℝ) + 1 := by
+ rw [Nat.cast_sub hbQ.le]; dsimp [z]; linarith
+ have hxy : z / y = x := by
+ apply (div_eq_iff (by linarith : y ≠ 0)).2
+ have h : y * (1 + x) = Q + 1 := div_mul_cancel₀ _ hden.ne'
+ dsimp [z]; nlinarith
+ have hinv : y / z = x⁻¹ := by rw [← hxy, inv_div]
+ refine ⟨hb, hbQ, ?_, ?_⟩
+ · rw [choose_up_ratio hbQ.le, ← hxy]
+ exact ratio_bounds ha hb' hby hyb haz hza
+ · rw [choose_down_ratio hb hbQ.le, ← hinv]
+ exact ratio_bounds hb' ha haz hza hby hyb
+
+/-- The exterior level at tensor power `n` for a marked index of dimension `q`. -/
+noncomputable def powerLevel (q : ℕ) (s : ℝ) (n : ℕ) : ℕ :=
+ level (q ^ n) ((q : ℝ) ^ (s * n))
+
+private theorem log_bounds {q v r : ℝ} (hq : 1 < q) (h : q ^ v / 4 ≤ r ∧ r ≤ q ^ v) :
+ v - Real.logb q 4 ≤ Real.logb q r ∧ Real.logb q r ≤ v := by
+ have hq' : 0 < q := by linarith
+ have hp := Real.rpow_pos_of_pos hq' v
+ have hlow := Real.logb_le_logb_of_le hq (by positivity) h.1
+ have hhigh := Real.logb_le_logb_of_le hq (lt_of_lt_of_le (by positivity) h.1) h.2
+ rw [Real.logb_div hp.ne' (by norm_num), Real.logb_rpow hq' hq.ne'] at hlow
+ rw [Real.logb_rpow hq' hq.ne'] at hhigh
+ exact ⟨hlow, hhigh⟩
+
+/-- The error in each *unnormalized* logarithm is at most `logb q 4` for every positive `n`. -/
+theorem powerLevel_log_bounds {q n : ℕ} {s : ℝ} (hq : 2 ≤ q) (hn : 1 ≤ n)
+ (hs₀ : -1 ≤ s) (hs₁ : s ≤ 1) :
+ let Q := q ^ n
+ let b := powerLevel q s n
+ let up := Real.logb q ((Q.choose (b + 1) : ℝ) / Q.choose b)
+ let down := Real.logb q ((Q.choose (b - 1) : ℝ) / Q.choose b)
+ 1 ≤ b ∧ b < Q ∧
+ (s * n - Real.logb q 4 ≤ up ∧ up ≤ s * n) ∧
+ ((-s) * n - Real.logb q 4 ≤ down ∧ down ≤ (-s) * n) := by
+ have hQ : 2 ≤ q ^ n := hq.trans (by simpa using Nat.pow_le_pow_right (by omega : 0 < q) hn)
+ have hq' : (1 : ℝ) < q := by exact_mod_cast (show 1 < q from hq)
+ have hq₀ : 0 < (q : ℝ) := by linarith
+ have hn' : (0 : ℝ) ≤ n := Nat.cast_nonneg n
+ have hlo := Real.rpow_le_rpow_of_exponent_le hq'.le (by nlinarith : -(n : ℝ) ≤ s * n)
+ have hhi := Real.rpow_le_rpow_of_exponent_le hq'.le (by nlinarith : s * n ≤ (n : ℝ))
+ rw [Real.rpow_neg hq₀.le, Real.rpow_natCast, ← Nat.cast_pow, ← one_div] at hlo
+ rw [Real.rpow_natCast, ← Nat.cast_pow] at hhi
+ obtain ⟨hb, hbQ, hup, hdown⟩ := level_bounds hQ hlo hhi
+ refine ⟨hb, hbQ, log_bounds hq' hup, log_bounds hq' ?_⟩
+ rwa [neg_mul, Real.rpow_neg hq₀.le]
+
+private theorem tendsto_normalized_log {u : ℕ → ℝ} {s C : ℝ}
+ (hu : ∀ n : ℕ, 1 ≤ n → s * n - C ≤ u n ∧ u n ≤ s * n) :
+ Tendsto (fun n : ℕ ↦ u n / n) atTop (𝓝 s) := by
+ have hl : Tendsto (fun n : ℕ ↦ s - C / n) atTop (𝓝 s) := by
+ simpa only [sub_zero] using (tendsto_const_div_atTop_nhds_zero_nat C).const_sub s
+ apply tendsto_of_tendsto_of_tendsto_of_le_of_le' hl (tendsto_const_nhds (x := s))
+ · filter_upwards [eventually_ge_atTop 1] with n hn
+ have hn' : (0 : ℝ) < n := by exact_mod_cast (show 0 < n from hn)
+ rw [le_div_iff₀ hn', sub_mul, div_mul_cancel₀ _ hn'.ne']
+ exact (hu n hn).1
+ · filter_upwards [eventually_ge_atTop 1] with n hn
+ exact (div_le_iff₀ (by exact_mod_cast (show 0 < n from hn))).2 (hu n hn).2
+
+/-- Equation (A.2) along `Q = q ^ n`, simultaneously for the two adjacent dimensions. -/
+theorem exists_level_rates {q : ℕ} {s : ℝ} (hq : 2 ≤ q) (hs₀ : -1 ≤ s) (hs₁ : s ≤ 1) :
+ ∃ b : ℕ → ℕ, (∀ n, 1 ≤ n → 1 ≤ b n ∧ b n < q ^ n) ∧
+ Tendsto (fun n ↦ Real.logb q (((q ^ n).choose (b n + 1) : ℝ) / (q ^ n).choose (b n)) / n)
+ atTop (𝓝 s) ∧
+ Tendsto (fun n ↦ Real.logb q (((q ^ n).choose (b n - 1) : ℝ) / (q ^ n).choose (b n)) / n)
+ atTop (𝓝 (-s)) := by
+ refine ⟨powerLevel q s, fun n hn ↦ ?_, ?_, ?_⟩
+ · have h := powerLevel_log_bounds hq hn hs₀ hs₁
+ exact ⟨h.1, h.2.1⟩
+ · exact tendsto_normalized_log fun n hn ↦ (powerLevel_log_bounds hq hn hs₀ hs₁).2.2.1
+ · exact tendsto_normalized_log fun n hn ↦ (powerLevel_log_bounds hq hn hs₀ hs₁).2.2.2
+
+/-- The three exterior dimensions used in (A.2) are all positive. -/
+theorem choose_adjacent_pos {Q b : ℕ} (hb : 1 ≤ b) (hbQ : b < Q) :
+ 0 < Q.choose b ∧ 0 < Q.choose (b + 1) ∧ 0 < Q.choose (b - 1) :=
+ ⟨Nat.choose_pos hbQ.le, Nat.choose_pos hbQ, Nat.choose_pos (by omega)⟩
+
+/-- Exponentiating a normalized base-`q` logarithmic rate gives the limit of nth roots. -/
+theorem tendsto_nthRoot_of_logb_rate {q : ℕ} (hq : 2 ≤ q) {x : ℕ → ℝ} {s : ℝ}
+ (hpos : ∀ᶠ n in atTop, 0 < x n)
+ (hrate : Tendsto (fun n : ℕ ↦ Real.logb q (x n) / n) atTop (𝓝 s)) :
+ Tendsto (fun n : ℕ ↦ (x n) ^ (n : ℝ)⁻¹) atTop (𝓝 ((q : ℝ) ^ s)) := by
+ have hq_one : (1 : ℝ) < q := by exact_mod_cast (show 1 < q from hq)
+ have hq_pos := zero_lt_one.trans hq_one
+ apply ((Real.continuousAt_const_rpow hq_pos.ne').tendsto.comp hrate).congr'
+ filter_upwards [hpos] with n hn
+ change (q : ℝ) ^ (Real.logb q (x n) / n) = (x n) ^ (n : ℝ)⁻¹
+ rw [div_eq_mul_inv, Real.rpow_mul hq_pos.le, Real.rpow_logb hq_pos hq_one.ne' hn]
+
+end ExteriorLevelRates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ExteriorLevels.lean b/lean/OAI/Computability/VPVNP/ExteriorLevels.lean
new file mode 100644
index 0000000000..48b5de43e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ExteriorLevels.lean
@@ -0,0 +1,155 @@
+import Lemmata.FockCircuits.BasisAction
+import Mathlib.Data.Fintype.Powerset
+import Mathlib.Data.Fin.Embedding
+
+/-!
+# Finite exterior levels for wire relocation
+
+The two summands in Appendix A.2 factor through the neighboring exterior
+levels. The restricted creation and contraction matrices retain the integral
+anticommutation identity in their ordered subset bases.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor.ExteriorLevels
+
+open Lemmata.FockCircuits
+
+/-- The coordinate indices for the degree-`b` exterior power on `Q` generators. -/
+def Level (Q b : ℕ) := {s : Finset (Fin Q) // s.card = b}
+
+instance (Q b : ℕ) : DecidableEq (Level Q b) :=
+ inferInstanceAs (DecidableEq {s : Finset (Fin Q) // s.card = b})
+
+instance (Q b : ℕ) : Fintype (Level Q b) :=
+ inferInstanceAs (Fintype {s : Finset (Fin Q) // s.card = b})
+
+@[simp] theorem card_level (Q b : ℕ) : Fintype.card (Level Q b) = Q.choose b := by
+ calc
+ Fintype.card (Level Q b) = Fintype.card {s : Finset (Fin Q) // s.card = b} :=
+ Fintype.card_congr (Equiv.refl _)
+ _ = Q.choose b := by
+ simpa only [Fintype.card_fin] using Fintype.card_finset_len (α := Fin Q) b
+
+/-- Realize bounded generator indices as natural-number indices. -/
+def indexSet {Q b : ℕ} (s : Level Q b) : Finset ℕ := s.val.map Fin.valEmbedding
+
+@[simp] theorem card_indexSet {Q b : ℕ} (s : Level Q b) : (indexSet s).card = b :=
+ (Finset.card_map _).trans s.property
+
+@[simp] theorem mem_indexSet {Q b : ℕ} (s : Level Q b) (i : Fin Q) :
+ i.val ∈ indexSet s ↔ i ∈ s.val :=
+ Finset.mem_map' _
+
+theorem lt_of_mem_indexSet {Q b i : ℕ} (s : Level Q b) (hi : i ∈ indexSet s) : i < Q := by
+ obtain ⟨j, _, rfl⟩ := Finset.mem_map.mp hi
+ exact j.isLt
+
+theorem indexSet_injective {Q b : ℕ} : Function.Injective (@indexSet Q b) := by
+ intro s t h
+ exact Subtype.ext (Finset.map_injective Fin.valEmbedding h)
+
+variable (R : Type*) [CommRing R]
+
+/-- Rectangular matrix of an exterior operator between two finite levels. -/
+noncomputable def entry {Q a b : ℕ} (f : Fock R →ₗ[R] Fock R)
+ (β : Level Q b) (α : Level Q a) : R :=
+ (Fock.basis R).repr (f (Fock.basis R (indexSet α))) (indexSet β)
+
+private theorem level_expansion {Q b : ℕ} (x : Fock R)
+ (hx : x = 0 ∨ ∃ (γ : Level Q b) (c : R), x = c • Fock.basis R (indexSet γ)) :
+ ∑ γ : Level Q b, (Fock.basis R).repr x (indexSet γ) • Fock.basis R (indexSet γ) = x := by
+ classical
+ rcases hx with rfl | ⟨δ, c, rfl⟩
+ · simp
+ · rw [Finset.sum_eq_single δ]
+ · simp
+ · intro γ _ hγ
+ simp [Ne.symm (indexSet_injective.ne hγ)]
+ · simp
+
+private theorem create_level {Q b : ℕ} (i : Fin Q) (α : Level Q b) :
+ Fock.create R i (Fock.basis R (indexSet α)) = 0 ∨
+ ∃ (γ : Level Q (b+1)) (c : R),
+ Fock.create R i (Fock.basis R (indexSet α)) = c • Fock.basis R (indexSet γ) := by
+ classical
+ by_cases hi : i ∈ α.val
+ · exact Or.inl (Fock.create_basis_of_mem R ((mem_indexSet α i).2 hi))
+ · obtain ⟨ε, hε⟩ := Fock.create_basis_of_not_mem R (i := i.val) ((mem_indexSet α i).not.mpr hi)
+ let γ : Level Q (b+1) := ⟨insert i α.val, by rw [Finset.card_insert_of_notMem hi, α.property]⟩
+ have hγ : indexSet γ = insert i.val (indexSet α) := Finset.map_insert Fin.valEmbedding _ _
+ exact Or.inr ⟨γ, (ε.val : R), by rw [hγ, hε, Units.smul_def, Int.cast_smul_eq_zsmul]⟩
+
+private theorem contract_level {Q b : ℕ} (i : Fin Q) (α : Level Q b) :
+ Fock.contract R i (Fock.basis R (indexSet α)) = 0 ∨
+ ∃ (γ : Level Q (b-1)) (c : R),
+ Fock.contract R i (Fock.basis R (indexSet α)) = c • Fock.basis R (indexSet γ) := by
+ classical
+ by_cases hi : i ∈ α.val
+ · obtain ⟨ε, hε⟩ := Fock.contract_basis_of_mem R ((mem_indexSet α i).2 hi)
+ let γ : Level Q (b-1) := ⟨α.val.erase i, by rw [Finset.card_erase_of_mem hi, α.property]⟩
+ have hγ : indexSet γ = (indexSet α).erase i.val := by
+ exact Finset.map_erase Fin.valEmbedding α.val i
+ exact Or.inr ⟨γ, (ε.val : R), by rw [hγ, hε, Units.smul_def, Int.cast_smul_eq_zsmul]⟩
+ · exact Or.inl (Fock.contract_basis_of_not_mem R ((mem_indexSet α i).not.mpr hi))
+
+private theorem entry_comp {Q a b c : ℕ} (f g : Fock R →ₗ[R] Fock R)
+ (β : Level Q c) (α : Level Q a)
+ (hg : g (Fock.basis R (indexSet α)) = 0 ∨
+ ∃ (γ : Level Q b) (r : R), g (Fock.basis R (indexSet α)) = r • Fock.basis R (indexSet γ)) :
+ ∑ γ : Level Q b, entry R f β γ * entry R g γ α =
+ entry R (f.comp g) β α := by
+ let ev := ((Fock.basis R).coord (indexSet β)).comp f
+ have hx := congrArg ev (level_expansion R _ hg)
+ simp only [map_sum, map_smul, smul_eq_mul] at hx
+ simpa only [entry, ev, LinearMap.comp_apply, Module.Basis.coord_apply, mul_comm] using hx
+
+/-- Equation (A.1) in the bounded subset basis. The two intermediate sums
+have `Q.choose (b+1)` and `Q.choose (b-1)` terms, respectively. -/
+theorem matrix_car {Q b : ℕ} (i j : Fin Q) (β α : Level Q b) :
+ (∑ γ : Level Q (b+1), entry R (Fock.contract R j) β γ * entry R (Fock.create R i) γ α) +
+ (∑ γ : Level Q (b-1), entry R (Fock.create R i) β γ * entry R (Fock.contract R j) γ α) =
+ if i = j ∧ β = α then 1 else 0 := by
+ classical
+ rw [entry_comp R _ _ _ _ (create_level R i α), entry_comp R _ _ _ _ (contract_level R j α)]
+ have h := congrArg ((Fock.basis R).coord (indexSet β))
+ (Fock.contract_create_add_create_contract R j i (Fock.basis R (indexSet α)))
+ simp only [map_add, Module.Basis.coord_apply] at h
+ unfold entry
+ rw [LinearMap.comp_apply, LinearMap.comp_apply, h]
+ by_cases hij : i = j
+ · subst j
+ simp [Finsupp.single_apply, indexSet_injective.eq_iff, eq_comm]
+ · simp [Ne.symm (Fin.val_injective.ne hij), hij]
+
+/-- A single pair of integer matrix families gives (A.1) after base change
+to any commutative ring, including fields of characteristic two. -/
+theorem int_matrix_car {Q b : ℕ} (i j : Fin Q) (β α : Level Q b) :
+ (∑ γ : Level Q (b+1), (entry ℤ (Fock.contract ℤ j) β γ : R) *
+ (entry ℤ (Fock.create ℤ i) γ α : R)) +
+ (∑ γ : Level Q (b-1), (entry ℤ (Fock.create ℤ i) β γ : R) *
+ (entry ℤ (Fock.contract ℤ j) γ α : R)) =
+ if i = j ∧ β = α then 1 else 0 := by
+ have h := congrArg (Int.castRingHom R) (matrix_car ℤ i j β α)
+ simpa only [map_add, map_sum, map_mul, apply_ite, map_one, map_zero, Int.coe_castRingHom] using h
+
+/-- Contracting the old marked index against the two orders in (A.1) gives
+the original coefficient at the new index times the identity wire. -/
+theorem matrix_car_apply {Q b : ℕ} (T : Fin Q → R) (i : Fin Q) (β α : Level Q b) :
+ (∑ j, T j * ∑ γ : Level Q (b+1),
+ entry R (Fock.contract R j) β γ * entry R (Fock.create R i) γ α) +
+ (∑ j, T j * ∑ γ : Level Q (b-1),
+ entry R (Fock.create R i) β γ * entry R (Fock.contract R j) γ α) =
+ if β = α then T i else 0 := by
+ rw [← Finset.sum_add_distrib]
+ simp_rw [← mul_add, matrix_car]
+ by_cases h : β = α <;> simp [h]
+
+end WireTensor.ExteriorLevels
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FamilyResult.lean b/lean/OAI/Computability/VPVNP/FamilyResult.lean
new file mode 100644
index 0000000000..3cd99bf8e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FamilyResult.lean
@@ -0,0 +1,29 @@
+import OAI.Computability.VPVNP.Hardness
+
+/-! # The explicit complete family in Theorem 1.1 -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+/-- The algebraic and completeness assertions about the paper's integer family.
+The circuit-size lower bound is a separate assertion of Theorem 1.1. -/
+theorem explicit_complete_family (F : Type*) [Field F] :
+ (∀ n : ℕ,
+ Fintype.card (Fin n × Bool) = 2 * n ∧
+ (MvPolynomial.map (Int.castRingHom F) (P n)).IsHomogeneous n ∧
+ (MvPolynomial.map (Int.castRingHom F) (P n)).totalDegree = n ∧
+ ∀ z : Fin n × Bool, (MvPolynomial.map (Int.castRingHom F) (P n)).degreeOf z ≤ 1) ∧
+ IsVNP (σ := fun n => Fin n × Bool) (fun n => MvPolynomial.map (Int.castRingHom F) (P n)) ∧
+ ∀ (V : ℕ → Type) [∀ n, Fintype (V n)] (f : Family F V),
+ IsVNP f → PProjects f (fun n => MvPolynomial.map (Int.castRingHom F) (P n)) := by
+ refine ⟨fun n => ⟨by simp [Nat.mul_comm], ?_, totalDegree_map_P n, ?_⟩, P_vnpComplete F⟩
+ · rw [map_P]
+ exact pairedPolynomial_isHomogeneous _
+ · intro v
+ rw [map_P]
+ exact pairedPolynomial_multilinear _ v
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FiniteAlgebraEvaluator.lean b/lean/OAI/Computability/VPVNP/FiniteAlgebraEvaluator.lean
new file mode 100644
index 0000000000..d5665abeb8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FiniteAlgebraEvaluator.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.CompressorReaderEnvelope
+
+/-!
+# Theorem 8.1 of “VP and VNP differ over every field”
+
+The fixed two-tape table reads the initialized Macaulay and Cramer workspaces
+from its polynomial-length advice. At each satisfiable length the same
+advised algebra and functional apply to every exponent width. All literal
+branches halt by the uniform clock, including the rejecting index guesses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorReader
+
+open Evaluator
+
+/-- Fixed order of the work and advice fields in the evaluator's binary prefix. -/
+noncomputable def fields : List (WeightedStep.Port Ports) := Finset.univ.toList
+
+theorem fields_nodup : fields.Nodup := Finset.nodup_toList _
+set_option maxRecDepth 5000 in
+theorem mem_fields (k : WeightedStep.Port Ports) : k ∈ fields := by
+ change k ∈ (Finset.univ : Finset (WeightedStep.Port Ports)).toList
+ exact Finset.mem_toList.mpr (Finset.mem_univ k)
+
+/-- The same literal machine table serves every input length and exponent
+width, in positive characteristic and in characteristic zero. -/
+noncomputable def program : UniversalMachine.Program := MatrixCallbacks.program fields (read true) (read false)
+
+end CompressorReader
+
+namespace Compression.BlockSchedule.Templates
+
+open MvPolynomial LabelEvaluator RAMTape Evaluator.MatrixCallbacks EvaluatorProgramRawInput
+open Evaluator.BinaryMachine LiveEvaluatorEncoding
+
+local instance finiteEvaluatorPrime (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+/-- Finite enumeration of the slice ground field for the finite-algebra evaluator. -/
+noncomputable local instance finiteEvaluatorGround (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) :=
+ Fintype.ofFinite _
+/-- Algebra structure on the ambient algebraic closure induced by embedding the slice ground
+field. -/
+noncomputable local instance finiteEvaluatorAmbient (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) :=
+ (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+
+local notation "ports" => Fintype.card (MachinePort (Evaluator.WeightedStep.Port CompressorReader.Ports))
+
+/-- The advised finite reduced algebra and its computation at one length.
+The radius bounds all visited head positions and the full encoded tape state. -/
+def HasFiniteAlgebraEvaluation (q c power n : ℕ) (hn : 2 ≤ n) : Prop :=
+ ∃ p : Nat.Primes, (q ≠ 0 → p.val = q) ∧ (q = 0 → p.val ≤ 2^B.compressorPrimeBits c n) ∧
+ ∃ M : Model p (B.compressorDegree n) (B.compressorEquations hn c),
+ ∃ adviceBits : List Bool, adviceBits.length ≤ n^power ∧
+ Finite M.algebra ∧ IsReduced M.algebra ∧ M.functional 1 = 1 ∧
+ (∀ i, eval₂ (Int.castRingHom M.algebra) M.labels (B.compressorEquations hn c i) = 0) ∧
+ ∀ Z (es : Fin (B.compressorLabelCount c n) → BurstRAM.Word Z),
+ let E := CompressorReader.program
+ let raw := adviceBits ++ runtime es
+ UniversalMachine.AllHalt E (2^(n^power)*(Z+1)^4) (UniversalMachine.initial E raw) ∧
+ (∀ ticks ≥ 2^(n^power)*(Z+1)^4,
+ (UniversalMachine.paths E ticks (UniversalMachine.initial E raw) : ZMod p.val) =
+ M.functional (∏ i, M.labels i ^ (es i).val)) ∧
+ (∀ choices, let disp := choiceDisplacement E (UniversalMachine.initial E raw) choices
+ StackCompiler.HeadBox (2240*(ports+1)*(n^power+Z+1)^4) disp.1 disp.2) ∧
+ ∀ time (bits : Fin time → Bool) (i : Fin (time+1)),
+ StateFits (2240*(ports+1)*(n^power+Z+1)^4)
+ (EvaluatorTail.history E time (UniversalMachine.initial E raw) bits i)
+
+/-- The finite reduced algebra, its solution, the advised prime and the fixed
+binary evaluator at every sufficiently large satisfiable length. -/
+theorem finite_algebra_evaluator (q c : ℕ) [CharP k q] :
+ ∃ C N : ℕ, ∀ n ≥ N, ∀ hn : 2 ≤ n,
+ (∃ x : Fin (B.compressorLabelCount c n) → k,
+ ∀ i, eval₂ (Int.castRingHom k) x (B.compressorEquations hn c i) = 0) →
+ B.HasFiniteAlgebraEvaluation q c C n hn := by
+ obtain ⟨a,ha,prepare⟩ := B.exists_compressor_reader_envelope CompressorReader.fields q c
+ exact B.uniform_evaluator_of_coordinate_readers CompressorReader.fields CompressorReader.fields_nodup
+ CompressorReader.mem_fields (CompressorReader.read true) (CompressorReader.read false) q c a ha 0
+ (fun n _ ↦ prepare n)
+
+/-- The same fixed evaluator and length exponents at every exceptional small
+circuit in the fixed characteristic. The polynomial is computed exactly and
+its circuit may contain arbitrary field constants. -/
+theorem finite_algebra_evaluator_of_small_circuits (q c : ℕ) [CharP k q] (hc : 1 ≤ c) :
+ ∃ power N : ℕ, ∀ n ≥ N, ∀ hn : 2 ≤ n,
+ circuitSize (map (Int.castRingHom k) (P n)) ≤ n^c →
+ B.HasFiniteAlgebraEvaluation q c power n hn := by
+ obtain ⟨power,N,h⟩ := B.finite_algebra_evaluator q c
+ refine ⟨power,N,fun n hN hn hs ↦ ?_⟩
+ obtain ⟨s,hs,circuit,hpoly⟩ := circuitSize_le_iff.mp hs
+ exact h n hN hn (B.exists_compressorSolution_of_circuit hn hc hs circuit hpoly)
+
+end Compression.BlockSchedule.Templates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FiniteSlice.lean b/lean/OAI/Computability/VPVNP/FiniteSlice.lean
new file mode 100644
index 0000000000..c421e34011
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FiniteSlice.lean
@@ -0,0 +1,175 @@
+import Mathlib.FieldTheory.Finite.Basic
+import Mathlib.LinearAlgebra.Dimension.DivisionRing
+import Mathlib.LinearAlgebra.LinearIndependent.Lemmas
+import Mathlib.RingTheory.Nullstellensatz
+
+/-!
+# The reduced algebra of a finite geometric slice
+
+Section 8.2 of *VP and VNP differ over every field* takes the quotient of a polynomial
+ring over a finite field by the ideal vanishing at all geometric points of a finite slice.
+Evaluation embeds this reduced coordinate algebra in the functions on the slice. The
+points can be defined over an extension field. Frobenius permutes the points and forces
+the coefficients of every minimal linear dependence to descend to the base field.
+This bounds the base-field dimension by the number of geometric points.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FiniteSlice
+
+open Polynomial MvPolynomial
+
+/-- A coordinate fixed by the cardinality Frobenius of the ground field descends to that field. -/
+theorem exists_algebraMap_eq_of_frobenius_fixed (K : Type*) {E : Type*}
+ [Field K] [Fintype K] [Field E] [Algebra K E] {x : E}
+ (hx : FiniteField.frobeniusAlgHom K E x = x) : ∃ c : K, algebraMap K E c = x := by
+ have hq : 1 < Fintype.card K := Fintype.one_lt_card
+ have hs : (Polynomial.X ^ Fintype.card K - Polynomial.X : K[X]).Splits := by
+ rw [splits_iff_card_roots, FiniteField.roots_X_pow_card_sub_X,
+ ← Finset.card_def, Finset.card_univ, FiniteField.X_pow_card_sub_X_natDegree_eq K hq]
+ apply hs.mem_range_of_isRoot (FiniteField.X_pow_card_sub_X_ne_zero K hq)
+ simpa [IsRoot.def, sub_eq_zero] using hx
+
+/-- A finite family of functions equivariant for a permutation of the arguments and
+a field endomorphism is linearly independent over the extension whenever it is
+linearly independent over the fixed field. -/
+theorem linearIndependent_of_fixedField
+ {K E α : Type*} [Field K] [Field E] [Algebra K E]
+ (σ : E →ₐ[K] E) (hfixed : ∀ x, σ x = x → ∃ c : K, algebraMap K E c = x)
+ (e : Equiv.Perm α) {n : ℕ} (f : Fin n → α → E)
+ (hf : ∀ i a, f i (e a) = σ (f i a)) (hK : LinearIndependent K f) :
+ LinearIndependent E f := by
+ classical
+ induction n with
+ | zero => exact linearIndependent_empty_type
+ | succ n ih =>
+ obtain ⟨hinit, hlast⟩ := linearIndependent_finSucc'.mp hK
+ have hE : LinearIndependent E (Fin.init f) :=
+ ih (Fin.init f) (fun i a ↦ hf i.castSucc a) hinit
+ refine linearIndependent_finSucc'.mpr ⟨hE, fun hspan ↦ hlast ?_⟩
+ obtain ⟨c, hc⟩ := (Submodule.mem_span_range_iff_exists_fun E).mp hspan
+ have hpoint (a : α) : ∑ i, c i * f i.castSucc a = f (Fin.last n) a := by
+ simpa [Finset.sum_apply, Fin.init, Pi.smul_apply, smul_eq_mul] using congrFun hc a
+ have hconj : ∑ i, σ (c i) • Fin.init f i = f (Fin.last n) := by
+ funext a
+ obtain ⟨b, rfl⟩ := e.surjective a
+ simpa [Finset.sum_apply, Fin.init, Pi.smul_apply, smul_eq_mul, hf, map_sum, map_mul]
+ using congrArg σ (hpoint b)
+ have hcfix (i : Fin n) : σ (c i) = c i := hE.eq_coords_of_eq (hconj.trans hc.symm) i
+ choose d hd using fun i ↦ hfixed (c i) (hcfix i)
+ apply (Submodule.mem_span_range_iff_exists_fun K).mpr
+ refine ⟨d, ?_⟩
+ simpa only [← hd, algebraMap_smul] using hc
+
+/-- A finite coordinate model preserving independence after extending scalars bounds
+the dimension over the original field. -/
+theorem finite_and_finrank_le_of_independence
+ {K E R α : Type*} [Field K] [Field E] [Algebra K E]
+ [AddCommGroup R] [Module K R] [Fintype α]
+ (inj : R →ₗ[K] (α → E))
+ (h : ∀ (n : ℕ) (f : Fin n → R), LinearIndependent K f →
+ LinearIndependent E (fun i => inj (f i))) :
+ Module.Finite K R ∧ Module.finrank K R ≤ Fintype.card α := by
+ classical
+ have hRank : Module.rank K R ≤ Fintype.card α := by
+ apply rank_le
+ intro s hs
+ let e := (Finset.equivFinOfCardEq (s := s) rfl).symm
+ have hi := h s.card (fun i => (e i : R)) ((linearIndependent_equiv e).mpr hs)
+ simpa only [Fintype.card_fin, Module.finrank_pi] using hi.fintype_card_le_finrank
+ exact ⟨Module.rank_lt_aleph0_iff.mp (hRank.trans_lt Cardinal.natCast_lt_aleph0),
+ Module.finrank_le_of_rank_le hRank⟩
+
+variable {K E ι : Type*} [Field K] [Field E] [Algebra K E]
+
+/-- The reduced coordinate algebra over the base field of a set of extension-field points. -/
+abbrev CoordinateAlgebra (K : Type*) [Field K] [Algebra K E] (V : Set (ι → E)) :=
+ MvPolynomial ι K ⧸ vanishingIdeal K V
+
+/-- The images of the polynomial variables in the slice algebra. -/
+noncomputable def coordinateLabel (V : Set (ι → E)) (i : ι) : CoordinateAlgebra K V :=
+ Ideal.Quotient.mk _ (MvPolynomial.X i)
+
+theorem aeval_coordinateLabel (V : Set (ι → E)) :
+ MvPolynomial.aeval (coordinateLabel (K := K) V) = Ideal.Quotient.mkₐ K (vanishingIdeal K V) := by
+ ext i
+ rw [MvPolynomial.aeval_X]
+ rfl
+
+theorem adjoin_coordinateLabel (V : Set (ι → E)) :
+ Algebra.adjoin K (Set.range (coordinateLabel (K := K) V)) = ⊤ := by
+ rw [Algebra.adjoin_range_eq_range_aeval, aeval_coordinateLabel, AlgHom.range_eq_top]
+ exact Ideal.Quotient.mk_surjective
+
+/-- Evaluation of classes of base-field polynomials at all points of the slice. -/
+noncomputable def sliceEvaluation (V : Set (ι → E)) :
+ CoordinateAlgebra K V →ₐ[K] (V → E) :=
+ Ideal.Quotient.liftₐ (vanishingIdeal K V) (AlgHom.pi fun x : V => aeval x.val)
+ fun _ hp => funext fun x => hp x.val x.property
+
+@[simp] theorem sliceEvaluation_mk (V : Set (ι → E)) (p : MvPolynomial ι K) (x : V) :
+ sliceEvaluation V (Ideal.Quotient.mk _ p) x = aeval x.val p := rfl
+
+theorem sliceEvaluation_injective (V : Set (ι → E)) :
+ Function.Injective (sliceEvaluation (K := K) V) := by
+ intro a b hab
+ obtain ⟨p, rfl⟩ := Ideal.Quotient.mk_surjective (I := vanishingIdeal K V) a
+ obtain ⟨q, rfl⟩ := Ideal.Quotient.mk_surjective (I := vanishingIdeal K V) b
+ apply Ideal.Quotient.eq.mpr
+ intro x hx
+ rw [map_sub, sub_eq_zero]
+ exact congrFun hab ⟨x, hx⟩
+
+theorem coordinateAlgebra_isReduced (V : Set (ι → E)) :
+ IsReduced (CoordinateAlgebra K V) :=
+ isReduced_of_injective (sliceEvaluation V) (sliceEvaluation_injective V)
+
+theorem coordinateAlgebra_nontrivial (V : Set (ι → E)) [Nonempty V] :
+ Nontrivial (CoordinateAlgebra K V) :=
+ (sliceEvaluation (K := K) V).toRingHom.domain_nontrivial
+
+/-- Every original label equation holds in the reduced coordinate algebra. -/
+theorem equation_eq_zero (I : Ideal (MvPolynomial ι K)) (p : MvPolynomial ι K) (hp : p ∈ I) :
+ Ideal.Quotient.mk (vanishingIdeal K (zeroLocus E I)) p = 0 :=
+ Ideal.Quotient.eq_zero_iff_mem.mpr (le_vanishingIdeal_zeroLocus I hp)
+
+private def mapPoint (I : Ideal (MvPolynomial ι K)) (σ : E →ₐ[K] E) (x : zeroLocus E I) :
+ zeroLocus E I :=
+ ⟨fun i => σ (x.val i), fun p hp => by
+ rw [← comp_aeval_apply, x.property p hp, map_zero]⟩
+
+/-- A field endomorphism fixing the coefficient field permutes the points of a finite slice. -/
+noncomputable def pointPerm (I : Ideal (MvPolynomial ι K)) [Finite (zeroLocus E I)]
+ (σ : E →ₐ[K] E) : Equiv.Perm (zeroLocus E I) :=
+ Equiv.ofBijective (mapPoint I σ) <| Finite.injective_iff_bijective.mp fun _ _ h =>
+ Subtype.ext <| funext fun i => σ.injective (congrFun (congrArg Subtype.val h) i)
+
+theorem sliceEvaluation_equivariant (I : Ideal (MvPolynomial ι K)) [Finite (zeroLocus E I)]
+ (σ : E →ₐ[K] E) (a : CoordinateAlgebra K (zeroLocus E I)) (x : zeroLocus E I) :
+ sliceEvaluation _ a (pointPerm I σ x) = σ (sliceEvaluation _ a x) := by
+ obtain ⟨p, rfl⟩ := Ideal.Quotient.mk_surjective (I := vanishingIdeal K _) a
+ exact (comp_aeval_apply x.val σ p).symm
+
+/-- Dimension bound for a finite slice defined by base-field equations.
+The extension `E` may be the algebraic closure of `K`. -/
+theorem coordinateAlgebra_finite_finrank [Fintype K] (I : Ideal (MvPolynomial ι K))
+ [Fintype (zeroLocus E I)] :
+ Module.Finite K (CoordinateAlgebra K (zeroLocus E I)) ∧
+ Module.finrank K (CoordinateAlgebra K (zeroLocus E I)) ≤ Fintype.card (zeroLocus E I) := by
+ let eval := sliceEvaluation (K := K) (zeroLocus E I)
+ let σ := FiniteField.frobeniusAlgHom K E
+ apply finite_and_finrank_le_of_independence eval.toLinearMap
+ intro n f hf
+ apply linearIndependent_of_fixedField σ (fun _ h => exists_algebraMap_eq_of_frobenius_fixed K h)
+ (pointPerm I σ) _ (fun i x => sliceEvaluation_equivariant I σ (f i) x)
+ exact hf.map' eval.toLinearMap
+ (LinearMap.ker_eq_bot_of_injective (sliceEvaluation_injective _))
+
+end FiniteSlice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedCompressedPairDiagonal.lean b/lean/OAI/Computability/VPVNP/FixedCompressedPairDiagonal.lean
new file mode 100644
index 0000000000..c41196ca78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedCompressedPairDiagonal.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.FixedNativeRealization
+import OAI.Computability.VPVNP.FixedProgramRoutes
+
+/-!
+# Reducing the final native compiler obligation to the compressed pair
+
+The actual evaluator tail handles the second half of the diagonal chain.
+A sufficiently large address multiplier makes its physical frames and
+per-call budgets fit. Thus only the compressed first-half pair computation
+enters the compiler premise below.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal
+
+open Compression LiveProgram CursorNetwork Filter
+universe u
+
+namespace Program
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (T : S.Templates)
+
+/-- For arbitrarily large address multipliers, one fixed pair table realizes all sufficiently large input lengths. -/
+def PairCompiler (C : ℕ) : Prop :=
+ let u := pairExponents T
+ ∀ (c : Constants) (hc : c.circuitExponent = C) (hm : c.motifLabels = Fintype.card T.Entry),
+ 2 ≤ c.chainPower → ∀ N : ℕ, ∃ b ≥ N, ∃ (hb : 1 ≤ b) (O : PairTable),
+ let D := ofPaperConstants c CompressorReader.program O b hb (liveRatio u)
+ ∀ᶠ n : ℕ in atTop, D.PairRuns T u C hc hm n
+
+theorem nativeCompiler_of_pair (C : ℕ) (pairs : PairCompiler T C) : NativeCompiler T C := by
+ let u := pairExponents T
+ intro c hc hm ha N
+ obtain ⟨b₀,tail⟩ := eventually_native_of_pairRuns T u C c CompressorReader.program hc hm
+ obtain ⟨b,hb,hpos,O,hpair⟩ := pairs c hc hm ha (max N b₀)
+ have stages := tail b ((le_max_right ..).trans hb) hpos O
+ refine ⟨b,(le_max_left ..).trans hb,hpos,O,?_⟩
+ filter_upwards [stages,hpair] with n route run
+ exact route run
+
+end Program
+
+theorem uniform_of_pair_compilers
+ (build : ∀ (C : ℕ), 1 ≤ C → ∀ (q : ℕ) (K : Type) [Field K] [IsAlgClosed K] [Countable K] [CharP K q],
+ ∀ (S : BlockSchedule K) (T : S.Templates), (∃ κ : T.Entry → K, T.IsSolution κ) →
+ Program.PairCompiler T C) : UniformPBound.{u} := by
+ apply uniform_of_native_compilers
+ intro C hC q K _ _ _ _ S T hT
+ exact Program.nativeCompiler_of_pair T C (build C hC q K S T hT)
+
+end FixedProgramDiagonal
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedCompressionModels.lean b/lean/OAI/Computability/VPVNP/FixedCompressionModels.lean
new file mode 100644
index 0000000000..b917247efa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedCompressionModels.lean
@@ -0,0 +1,42 @@
+import OAI.Computability.VPVNP.IteratedCompression
+import OAI.Computability.VPVNP.CompressorEvaluatorAdvice
+
+/-!
+# One compressor and its specializations at small-circuit lengths
+
+Sections 8 and 9 use the same compression schedule and the same integer
+parameter equations at every length of the contradiction. Only the grammar
+assignment and the finite algebra realizing both assignments are selected
+at an individual small-circuit length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+open MvPolynomial LabelEvaluator
+
+/-- The fixed field solution and both templates precede the universal
+quantifier over small-circuit lengths. At each such length one finite
+algebra realizes the grammar and both kinds of wire maps together. The
+prime in positive characteristic is the original characteristic. -/
+theorem fixed_models_of_small_circuits (k : Type*) [Field k] (q : ℕ) [CharP k q]
+ {C : ℕ} (hC : 1 ≤ C)
+ (hsmall : ∀ N, ∃ n ≥ N, circuitSize (map (Int.castRingHom k) (P n)) ≤ n ^ C) :
+ ∃ (S : BlockSchedule k) (B : S.Templates),
+ (∃ κ : B.Entry → k, B.IsSolution κ) ∧
+ ∀ n (hn : 2 ≤ n), circuitSize (map (Int.castRingHom k) (P n)) ≤ n ^ C →
+ ∃ p : Nat.Primes, (q ≠ 0 → p.val = q) ∧ (q = 0 → p.val ≤ 2 ^ B.compressorPrimeBits C n) ∧
+ Nonempty (Model p (B.compressorDegree n) (B.compressorEquations hn C)) := by
+ obtain ⟨S, B, κ, hκ⟩ := fixed_templates_of_small_circuits k hC hsmall
+ refine ⟨S, B, ⟨κ, hκ⟩, fun n hn hsize => ?_⟩
+ obtain ⟨s, hs, circ, hcirc⟩ := circuitSize_le_iff.mp hsize
+ exact B.exists_compressorEvaluator q hn hC hs circ hcirc
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedLabelReadback.lean b/lean/OAI/Computability/VPVNP/FixedLabelReadback.lean
new file mode 100644
index 0000000000..43964fdf9b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedLabelReadback.lean
@@ -0,0 +1,285 @@
+import OAI.Computability.VPVNP.JointLabelSystem
+import OAI.Computability.VPVNP.GradedMonomialIndex
+import OAI.Computability.VPVNP.PrimedStackRAMLayout
+import OAI.Computability.VPVNP.RAMSerialization
+
+/-!
+# Reading a scalar from the joint integer label system
+
+Equation addresses first enumerate input words by their binary digits, then
+the fixed motif rows. The exponent vector is read in the arithmetic production
+order used by the primed parser. A permutation encoded in polynomially many
+advice bits reconciles this order with the finite coordinates of the joint
+system. For a motif row it suffices to scan the fixed sparse coefficient table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointLabelSystem.FixedRows
+
+open MvPolynomial PrimedStackRAM RadicalCertificate.MonomialIndex
+
+variable (V I : Type*) [Fintype V] [Fintype I] (F : I → MvPolynomial V ℤ) (n c : ℕ)
+
+/-- Number of formal labels, including all grammar productions and the compressor labels. -/
+abbrev labelTotal := Fintype.card (Production n c ⊕ V)
+/-- Number of terminal and binary production labels for a grammar with n input positions, n
+degree indices and n^(c+5) nonterminal states. -/
+abbrev productionCount := labelCount n n (n ^ (c + 5))
+
+/-- The row address is an input word or a fixed motif equation. -/
+noncomputable def rowIndex :
+ Fin (2 ^ n + Fintype.card I) ≃ (Fin n → Bool) ⊕ I :=
+ finSumFinEquiv.symm.trans ((RAMSerialization.wordBits n).sumCongr (Fintype.equivFin _).symm)
+
+/-- The production block uses the dense triangular split index and the three
+row-major state indices of the primed parser. The motif block follows it. -/
+noncomputable def labelOrder : Fin (productionCount n c + Fintype.card V) ≃ Fin (labelTotal V n c) :=
+ finSumFinEquiv.symm.trans
+ (((labelIndex n n (n ^ (c + 5))).symm.sumCongr (Fintype.equivFin V).symm).trans
+ (Fintype.equivFin _))
+
+theorem labelOrder_left (j : Production n c) :
+ labelOrder V n c ((labelIndex n n _ j).castAdd (Fintype.card V)) =
+ leftIndex (Production n c) V j := by
+ simp [labelOrder, leftIndex]
+
+theorem labelOrder_right (j : V) :
+ labelOrder V n c ((Fintype.equivFin _ j).natAdd (productionCount n c)) =
+ rightIndex (Production n c) V j := by
+ simp [labelOrder, rightIndex]
+
+theorem labelOrder_length : productionCount n c + Fintype.card V = labelTotal V n c := by
+ simpa only [Fintype.card_fin] using Fintype.card_congr (labelOrder V n c)
+
+/-- Bits occupied by the table of label ordinals, with a fixed-width word for each grammar or
+compressor label. -/
+abbrev orderBits :=
+ (productionCount n c + Fintype.card V) * Nat.clog 2 (labelTotal V n c)
+
+/-- The advice contains one fixed-width formal coordinate per dense label. -/
+noncomputable def orderAdvice : Fin (orderBits V n c) → Bool :=
+ RAMSerialization.arrayBits _ _ fun j =>
+ ⟨(labelOrder V n c j).val, (labelOrder V n c j).isLt.trans_le (Nat.le_pow_clog (by decide) _)⟩
+
+theorem orderAdvice_lookup (j : Fin (productionCount n c + Fintype.card V)) :
+ ((RAMSerialization.arrayBits _ _).symm (orderAdvice V n c) j).val = (labelOrder V n c j).val := by
+ simp [orderAdvice]
+
+theorem labelTotal_polynomiallyBounded : PolynomiallyBounded (fun n => labelTotal V n c) := by
+ have hw := PolynomiallyBounded.id.pow (c + 5)
+ refine (((hw.mul (PolynomiallyBounded.id.mul (.const 2))).add
+ ((PolynomiallyBounded.id.pow 2).mul (hw.pow 3))).add (.const (Fintype.card V))).of_le fun n => ?_
+ rw [labelTotal, Fintype.card_sum]
+ apply Nat.add_le_add_right
+ simpa only [Fintype.card_fin, Fintype.card_prod, Fintype.card_bool] using
+ card_grammarLabel_le (Fin n × Bool) (Fin (n ^ (c + 5))) n
+
+theorem orderBits_polynomiallyBounded : PolynomiallyBounded (fun n => orderBits V n c) := by
+ have h := labelTotal_polynomiallyBounded V c
+ refine (h.mul h).of_le fun n => ?_
+ rw [orderBits, labelOrder_length]
+ apply Nat.mul_le_mul_left
+ exact Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le
+
+/-- A renaming by a coordinate block preserves the coefficient if the
+complementary block has only zero exponents. -/
+theorem coeff_of_rename_blocks {V W T R : Type*} [Fintype W] [CommSemiring R]
+ (f : V ↪ T) (g : W → T) (hd : ∀ v w, f v ≠ g w) (hc : ∀ k, k ∈ Set.range f ∨ k ∈ Set.range g)
+ (p : MvPolynomial V R) (e : T →₀ ℕ) :
+ (rename f p).coeff e =
+ if ∀ j, e (g j) = 0 then p.coeff (e.comapDomain f f.injective.injOn) else 0 := by
+ classical
+ have hs : ↑e.support ⊆ Set.range f ↔ ∀ j, e (g j) = 0 := by
+ constructor
+ · intro h j
+ by_contra hn
+ obtain ⟨v, hv⟩ := h (Finsupp.mem_support_iff.mpr hn)
+ exact hd v j hv
+ · intro h k hk
+ obtain hmem | ⟨w, rfl⟩ := hc k
+ · exact hmem
+ · exact False.elim ((Finsupp.mem_support_iff.mp hk) (h w))
+ split_ifs with h
+ · exact (congrArg (fun u => (rename f p).coeff u) (Finsupp.embDomain_comapDomain (hs.mpr h)).symm).trans
+ (coeff_rename_embDomain ..)
+ · apply coeff_rename_eq_zero
+ intro a ha
+ exact False.elim (h (hs.mp (by
+ rw [← ha, ← Finsupp.embDomain_eq_mapDomain f]
+ exact (Finsupp.mem_range_embDomain_iff ..).mp ⟨a, rfl⟩)))
+
+theorem index_disjoint {V W : Type*} [Fintype V] [Fintype W] (v : V) (w : W) :
+ leftIndex V W v ≠ rightIndex V W w :=
+ fun h => Sum.inl_ne_inr ((Fintype.equivFin (V ⊕ W)).injective h)
+
+theorem index_cover {V W : Type*} [Fintype V] [Fintype W] (k : Fin (Fintype.card (V ⊕ W))) :
+ k ∈ Set.range (leftIndex V W) ∨ k ∈ Set.range (rightIndex V W) := by
+ obtain ⟨(v | w), rfl⟩ := (Fintype.equivFin (V ⊕ W)).surjective k
+ · exact Or.inl ⟨v, rfl⟩
+ · exact Or.inr ⟨w, rfl⟩
+
+/-- A fixed sparse table gives the motif coefficient by exponent comparison.
+The size of this table depends only on the chosen motif data. -/
+noncomputable def fixedTable (o : I) :
+ List ((Fin (Fintype.card V) → ℕ) × ℤ) := by
+ classical
+ let p := F o
+ exact p.support.toList.map fun a => (fun i => a ((Fintype.equivFin V).symm i), p.coeff a)
+
+/-- Recover the integer coefficient of an exponent vector by summing all matching sparse table
+rows. -/
+def tableLookup {m : ℕ} (table : List ((Fin m → ℕ) × ℤ)) (a : Fin m → ℕ) : ℤ :=
+ table.foldl (fun z row => if row.1 = a then z + row.2 else z) 0
+
+private theorem tableLookup_eq_sum {m : ℕ} (table : List ((Fin m → ℕ) × ℤ)) (a : Fin m → ℕ) :
+ tableLookup table a = (table.map (fun row => if row.1 = a then row.2 else 0)).sum := by
+ let f (row : (Fin m → ℕ) × ℤ) := if row.1 = a then row.2 else 0
+ have h (l : List ((Fin m → ℕ) × ℤ)) (z : ℤ) :
+ l.foldl (fun z row => if row.1 = a then z + row.2 else z) z = z + (l.map f).sum := by
+ induction l generalizing z with
+ | nil => simp
+ | cons b l ih =>
+ simp only [List.foldl_cons, ih, List.map_cons, List.sum_cons, f]
+ split_ifs <;> simp [add_assoc]
+ exact (h table 0).trans (zero_add _)
+
+omit [Fintype I] in
+theorem tableLookup_fixedTable (o : I) (a : V →₀ ℕ) :
+ tableLookup (fixedTable V I F o) (fun i => a ((Fintype.equivFin V).symm i)) =
+ (F o).coeff a := by
+ classical
+ have he (b : V →₀ ℕ) : (fun i => b ((Fintype.equivFin V).symm i)) =
+ (fun i => a ((Fintype.equivFin V).symm i)) ↔ b = a := by
+ refine ⟨fun h => Finsupp.ext fun v => ?_, fun h => h ▸ rfl⟩
+ simpa using congrFun h (Fintype.equivFin V v)
+ rw [tableLookup_eq_sum]
+ simp only [fixedTable, List.map_map, Function.comp_def, he, Finset.sum_map_toList]
+ by_cases ha : a ∈ (F o).support
+ · simp [ha]
+ · simp [ha, notMem_support_iff.mp ha]
+
+/-- Combine the two counted predicates and the fixed motif table. The `parse`
+argument receives the input word and its exponent vector in dense production
+order. The clocked path count is requested only for the constant coefficient. -/
+def readDense {Output : Type*} {n g m : ℕ} (parse : (Fin n → Bool) → (Fin g → ℕ) → ℤ)
+ (paths : (Fin n → Bool) → ℕ) (table : Output → List ((Fin m → ℕ) × ℤ))
+ (row : (Fin n → Bool) ⊕ Output) (e : Fin (g + m) → ℕ) : ℤ :=
+ let l := fun j : Fin g => e (j.castAdd m)
+ let r := fun j : Fin m => e (j.natAdd g)
+ match row with
+ | .inl x => if ∀ j, r j = 0 then parse x l - (if ∀ j, l j = 0 then paths x else 0 : ℕ) else 0
+ | .inr o => if ∀ j, l j = 0 then tableLookup (table o) r else 0
+
+omit [Fintype I] in
+/-- At every equation and monomial, the block reader returns the exact signed
+integer coefficient. The two scalar callbacks can be replaced independently
+by any implementations returning the parse and canonical path counts. -/
+theorem readDense_correct (hn : 2 ≤ n)
+ (parse : (Fin n → Bool) → (Fin (productionCount n c) → ℕ) → ℤ)
+ (hparse : ∀ (x : Fin n → Bool) (b : Production n c →₀ ℕ),
+ parse x (fun i => b ((labelIndex n n _).symm i)) =
+ (labelQuery (⟨n - 1, by omega⟩ : Fin n) (⟨0, pow_pos (by omega) _⟩ : Fin (n ^ (c + 5))) x).coeff b)
+ (paths : (Fin n → Bool) → ℕ) (hpaths : ∀ x, paths x = acceptingCount x)
+ (row : (Fin n → Bool) ⊕ I) (e : Fin (labelTotal V n c) →₀ ℕ) :
+ readDense parse paths (fixedTable V I F) row (e ∘ labelOrder V n c) =
+ (unionEquations (grammarEquation hn c) F row).coeff e := by
+ classical
+ let l := leftIndex (Production n c) V
+ let r := rightIndex (Production n c) V
+ let le := e.comapDomain l l.injective.injOn
+ let re := e.comapDomain r r.injective.injOn
+ let f := labelIndex n n (n ^ (c + 5))
+ let g := Fintype.equivFin V
+ have hl (j : Fin (productionCount n c)) :
+ e (labelOrder V n c (j.castAdd (Fintype.card V))) = le (f.symm j) := by
+ obtain ⟨a, rfl⟩ := f.surjective j
+ change e (labelOrder V n c ((labelIndex n n _ a).castAdd _)) = e (l (f.symm (f a)))
+ rw [labelOrder_left, f.symm_apply_apply]
+ have hr (j : Fin (Fintype.card V)) :
+ e (labelOrder V n c (j.natAdd (productionCount n c))) = re (g.symm j) := by
+ obtain ⟨a, rfl⟩ := g.surjective j
+ change e (labelOrder V n c ((Fintype.equivFin _ a).natAdd _)) = e (r (g.symm (g a)))
+ rw [labelOrder_right, g.symm_apply_apply]
+ have hlz : (∀ j, le (f.symm j) = 0) ↔ ∀ v, e (l v) = 0 := by
+ change (∀ j, le (f.symm j) = 0) ↔ ∀ v, le v = 0
+ constructor
+ · intro h v
+ simpa using h (f v)
+ · exact fun h j => h (f.symm j)
+ have hrz : (∀ j, re (g.symm j) = 0) ↔ ∀ w, e (r w) = 0 := by
+ change (∀ j, re (g.symm j) = 0) ↔ ∀ w, re w = 0
+ constructor
+ · intro h w
+ simpa using h (g w)
+ · exact fun h j => h (g.symm j)
+ have he0 : (0 : Production n c →₀ ℕ) = le ↔ ∀ v, e (l v) = 0 := by
+ constructor
+ · intro h v
+ change le v = 0
+ rw [← h, Finsupp.zero_apply]
+ · intro h
+ exact Finsupp.ext fun v => (h v).symm
+ cases row with
+ | inl x =>
+ change readDense _ _ _ (.inl x) _ = (rename l (grammarEquation hn c x)).coeff e
+ rw [coeff_of_rename_blocks l r index_disjoint index_cover]
+ simp only [readDense, Function.comp_apply, hl, hr, hlz, hrz, grammarEquation, coeff_sub,
+ coeff_C, he0, hpaths, hparse, Nat.cast_ite, Nat.cast_zero, le, f]
+ | inr o =>
+ change readDense _ _ _ (.inr o) _ = (rename r (F o)).coeff e
+ rw [coeff_of_rename_blocks r l (fun w v => (index_disjoint v w).symm)
+ (fun k => (index_cover k).symm)]
+ simp only [readDense, Function.comp_apply, hl, hr, hlz, tableLookup_fixedTable, g, re]
+
+/-- The scalar accessor on the `Fin` equation addresses and plain exponent
+arrays used by the indexed Macaulay matrix. -/
+noncomputable def getCoeff
+ (parse : (Fin n → Bool) → (Fin (productionCount n c) → ℕ) → ℤ)
+ (paths : (Fin n → Bool) → ℕ) (i : Fin (2 ^ n + Fintype.card I))
+ (a : Fin (labelTotal V n c) → ℕ) : ℤ :=
+ readDense parse paths (fixedTable V I F) (rowIndex I n i) (a ∘ labelOrder V n c)
+
+theorem getCoeff_eq (hn : 2 ≤ n)
+ (parse : (Fin n → Bool) → (Fin (productionCount n c) → ℕ) → ℤ)
+ (hparse : ∀ (x : Fin n → Bool) (b : Production n c →₀ ℕ),
+ parse x (fun i => b ((labelIndex n n _).symm i)) =
+ (labelQuery (⟨n - 1, by omega⟩ : Fin n) (⟨0, pow_pos (by omega) _⟩ : Fin (n ^ (c + 5))) x).coeff b)
+ (paths : (Fin n → Bool) → ℕ) (hpaths : ∀ x, paths x = acceptingCount x)
+ (i : Fin (2 ^ n + Fintype.card I)) (a : Fin (labelTotal V n c) → ℕ) :
+ getCoeff V I F n c parse paths i a = (unionEquations (grammarEquation hn c) F (rowIndex I n i)).coeff (exponentVector a) :=
+ readDense_correct V I F n c hn parse hparse paths hpaths (rowIndex I n i) (exponentVector a)
+
+/-- Decode an address by binary arithmetic and fetch each exponent using the
+fixed-width order advice. Unused motif coefficients are read as zero by the
+sparse table. The entire reader apart from its supplied tables and callbacks
+is uniform in the four dimensions. -/
+def readAdvice {n g m t q : ℕ} (advice : Fin ((g + m) * Nat.clog 2 t) → Bool)
+ (table : Fin q → List ((Fin m → ℕ) × ℤ))
+ (parse : (Fin n → Bool) → (Fin g → ℕ) → ℤ) (paths : (Fin n → Bool) → ℕ)
+ (i : Fin (2 ^ n + q)) (a : Fin t → ℕ) : ℤ :=
+ let words := (RAMSerialization.arrayBits (g + m) (Nat.clog 2 t)).symm advice
+ let dense (j : Fin (g + m)) := if h : (words j).val < t then a ⟨(words j).val, h⟩ else 0
+ let row := (finSumFinEquiv.symm i).map (RAMSerialization.wordBits n) id
+ readDense parse paths table row dense
+
+/-- The fixed motif table and the polynomial-size index advice suffice to
+implement the indexed joint coefficient accessor. -/
+theorem readAdvice_eq_getCoeff
+ (parse : (Fin n → Bool) → (Fin (productionCount n c) → ℕ) → ℤ)
+ (paths : (Fin n → Bool) → ℕ) (i : Fin (2 ^ n + Fintype.card I))
+ (a : Fin (labelTotal V n c) → ℕ) :
+ readAdvice (orderAdvice V n c) (fixedTable V I F ∘ (Fintype.equivFin _).symm) parse paths i a =
+ getCoeff V I F n c parse paths i a := by
+ simp only [readAdvice, orderAdvice_lookup, dite_true, Fin.is_lt, Fin.eta]
+ obtain ⟨(b | o), rfl⟩ := (finSumFinEquiv (m := 2 ^ n) (n := Fintype.card I)).surjective i
+ · simp [getCoeff, rowIndex, readDense]
+ · simp [getCoeff, rowIndex, readDense]
+
+end JointLabelSystem.FixedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedModelDiagonal.lean b/lean/OAI/Computability/VPVNP/FixedModelDiagonal.lean
new file mode 100644
index 0000000000..cecd4a2701
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedModelDiagonal.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.PairedEvaluatorContradiction
+import OAI.Computability.VPVNP.LivePhysicalContractionRealized
+
+/-!
+# The per-length diagonal for a fixed joint model
+
+The physical first-half counter vector stores production counts in parser order and
+compressor counts after them. The midpoint advice reorders this vector into the label
+coordinates of the joint equations. The same order is used in the evaluator's initial
+configuration, its modular path count, and the weighted primed contraction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.BlockSchedule.Templates
+
+open JointLabelSystem LabelEvaluator CutSchedule ExponentTrace UniversalMachine
+open LiveEvaluatorEncoding ChainAssignments BurstRAM BurstRAM.PrivateRAM
+open scoped Classical
+
+local instance diagonalPrimeFact (p : Nat.Primes) : Fact p.val.Prime := ⟨p.property⟩
+/-- Enumerate the finite ground field in the local certificate. -/
+noncomputable local instance diagonalGroundFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+/-- Use the slice embedding to give the ambient field its ground-field algebra structure. -/
+noncomputable local instance diagonalGroundAlgebra (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) :=
+ (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra
+/-- Decide equality of production labels in the physical counter order. -/
+noncomputable local instance diagonalProductionDecEq (n c : ℕ) : DecidableEq (Production n c) := Classical.decEq _
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+
+/-- Number of counters in the first-half live cut, in physical parser order. -/
+noncomputable abbrev denseCount (n c : ℕ) := FixedRows.productionCount n c + Fintype.card B.Entry
+
+/-- The midpoint scatter turns a physical counter vector into an evaluator input. -/
+noncomputable def formalExponents {n c : ℕ} (xs : Fin (B.denseCount n c) → ℕ) :
+ Fin (B.compressorLabelCount c n) → ℕ := xs ∘ (FixedRows.labelOrder B.Entry n c).symm
+
+private theorem denseExponent_lt {n c r : ℕ} (μ : PairNomination n c r) (ν : B.Entry → ℕ)
+ (hν : ∀ v, ν v < 2^(2*r)) (j : Fin (B.denseCount n c)) :
+ B.denseExponent (fun v => (μ v).val) ν j < 2^(2*r) := by
+ obtain ⟨(a | a), rfl⟩ := finSumFinEquiv.surjective j
+ · simp [denseExponent]
+ · simpa [denseExponent] using hν ((Fintype.equivFin B.Entry).symm a)
+
+/-- Every prefix of the `2^h` pairs fits in `Z` bits, including the last prefix. -/
+private theorem prefix_lt {t h r Z : ℕ} (hZ : h+2*r ≤ Z) (inc : Fin (2^h) → Fin t → ℕ)
+ (hb : ∀ i a, inc i a < 2^(2*r)) (i : Fin (2^h)) (a : Fin t) :
+ partialSum inc i.succ a < 2^Z := by
+ have hpre : partialSum inc i.succ a ≤ partialSum inc (Fin.last (2^h)) a := by
+ unfold partialSum
+ exact Finset.sum_le_sum_of_subset (Finset.range_mono (Nat.succ_le_of_lt i.isLt))
+ rw [prefix_last] at hpre
+ calc
+ _ ≤ ∑ j, inc j a := hpre
+ _ < ∑ _ : Fin (2^h), 2^(2*r) :=
+ Finset.sum_lt_sum_of_nonempty Finset.univ_nonempty (fun j _ => hb j a)
+ _ = 2^(h+2*r) := by simp [pow_add]
+ _ ≤ 2^Z := Nat.pow_le_pow_right (by decide) hZ
+
+private theorem formalExponents_sum {I : Type*} [Fintype I] {n c : ℕ}
+ (μ : I → Production n c → ℕ) (ν : I → B.Entry → ℕ) :
+ B.formalExponents (fun j => ∑ i, B.denseExponent (μ i) (ν i) j) =
+ fun j => ∑ i, joinAssignment (μ i) (ν i) j := by
+ funext j
+ apply Finset.sum_congr rfl
+ intro i _
+ rw [← B.denseExponent_labelOrder, Equiv.apply_symm_apply]
+
+/-- The length-specific compiler data used in Proposition 9.1 and §14.3. `program` and `E`
+are explicit parameters so an eventual construction can fix both tables before choosing `n`.
+The processor realization is supplied separately to `false_of_processor`. -/
+structure LocalCertificate {n c : ℕ} (hn : 2 ≤ n) {p : Nat.Primes}
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn c))
+ (h Δ a r e w Z radius : ℕ) (program : UniversalMachine.Program)
+ (hf : ProcessorInput.Fits program n r (2^e) w) (E : UniversalMachine.Program)
+ {pc regs pubs : ℕ} (D : Machine w pc regs pubs) (fuel : ℕ) (start : BurstRAM.Word w) where
+ hw : 4 ≤ w
+ hc : 2^r * 2^e < 2^w
+ hR : 4*n ≤ 2^r
+ hZ : h+2*r ≤ Z
+ /-- The common advice bits distributed to all groups of the chain. -/
+ advice : Bits a
+ fit : 1 + B.denseCount n c * Z ≤ Δ
+ layout : LiveEvaluatorTail.Layout E.extra radius w Δ
+ /-- Finite paths for the given exterior, pair index and nominated production multiplicities. -/
+ Path : Exterior h Δ → Fin (2^h) → PairNomination n c r → Type
+ [pathFintype : ∀ ξ i μ, Fintype (Path ξ i μ)]
+ /-- Multiplicity of each compressor label on the selected pair path. -/
+ ν : ∀ ξ i μ, Path ξ i μ → B.Entry → ℕ
+ hν : ∀ ξ i μ q v, ν ξ i μ q v < 2^(2*r)
+ hpair : ∀ ξ i μ, (∑ q : Path ξ i μ, ∏ v, (B.compressorValues hn M v) ^ ν ξ i μ q v) =
+ (GrammarDiagonal.multiplicity (⟨n-1, by omega⟩ : Fin n) (⟨0, pow_pos (by omega) _⟩ : Fin (n^(c+5)))
+ (PairedChain.siteInput program hf advice ξ i) μ : M.algebra)
+ /-- Initial scalar evaluator configuration for an exponent vector in formal label order. -/
+ initial : (Fin (B.compressorLabelCount c n) → ℕ) → Config E.extra
+ /-- Bounded encoding of the midpoint configuration for counters in physical order. -/
+ init : (Fin (B.denseCount n c) → ℕ) → Code E.extra radius
+ hi : ∀ xs, (init xs).toState = EvaluatorTail.canonical (initial (B.formalExponents xs))
+ histories : ∀ xs, LiveEvaluatorTail.HistoriesFit E radius (2^h) (initial xs)
+ htail : ∀ xs, (∀ j, xs j < 2^Z) → (paths E (2^h) (initial xs) : ZMod p.val) =
+ (M.presentation.branchCount p.val Z xs : ZMod p.val)
+ group : ∀ (cuts : AllCuts h Δ) (j : Fin (2^(h+1))),
+ Nat.card (ActualPaths D.program fuel start (RAMMemory.initialMemory (2^r)
+ (liveHeader (d := r) hw advice cuts j)) (withinCaps (2^r) (2^e))) =
+ specifiedGroupCount fit (fun ξ i μ q => B.denseExponent (fun v => (μ v).val) (ν ξ i μ q))
+ E layout init cuts j
+
+attribute [instance] LocalCertificate.pathFintype
+
+variable {B} {n c : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn c)}
+ {h Δ a r e w Z radius pc regs pubs : ℕ} {program E : UniversalMachine.Program}
+ {hf : ProcessorInput.Fits program n r (2^e) w} {D : Machine w pc regs pubs}
+ {fuel : ℕ} {start : BurstRAM.Word w}
+
+/-- The physical single-site equality and the certificate's single-group equality yield the
+integer two-mode count. Reducing that count in the finite algebra gives the contradiction. -/
+theorem LocalCertificate.false_of_processor
+ (C : B.LocalCertificate hn M h Δ a r e w Z radius program hf E D fuel start)
+ (processor : ∀ (v : Fin (2^r)) (hdr : ProcessorInput.Header) (sends : RAMLayout.SendArrays r (2^e) w),
+ acceptingCount (ProcessorInput.encode program n v hdr (RAMLayout.incidentBits sends v) hf) =
+ Nat.card (D.IncidentPaths fuel start (ProcessorInput.headerWord C.hw hdr) ((by decide : 2 ≤ 4).trans C.hw) C.hc v
+ (RAMLayout.incidentBits sends v))) : False := by
+ let inc := fun ξ i μ (q : C.Path ξ i μ) => B.denseExponent (fun v => (μ v).val) (C.ν ξ i μ q)
+ have bound (ξ : Exterior h Δ) (μ : Fin (2^h) → PairNomination n c r)
+ (q : (i : Fin (2^h)) → C.Path ξ i (μ i)) (i : Fin (2^h)) (j : Fin (B.denseCount n c)) :
+ partialSum (fun v => inc ξ v (μ v) (q v)) i.succ j < 2^Z :=
+ prefix_lt C.hZ _ (fun v b => B.denseExponent_lt (μ v) (C.ν ξ v (μ v) (q v))
+ (C.hν ξ v (μ v) (q v)) b) i j
+ have live := physical_two_modes_realized C.fit inc E C.layout C.init program hf C.advice D fuel start
+ C.hw C.hc processor C.group bound (fun xs => C.initial (B.formalExponents xs)) C.hi
+ (fun xs => C.histories (B.formalExponents xs))
+ apply B.pairedEvaluatorContradiction hn M program hf C.advice C.hR C.hZ C.ν C.hν C.hpair E C.initial C.htail
+ simpa only [inc, formalExponents_sum] using live
+
+end Compression.BlockSchedule.Templates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedNativeProgram.lean b/lean/OAI/Computability/VPVNP/FixedNativeProgram.lean
new file mode 100644
index 0000000000..c1aa5e53e0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedNativeProgram.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.FixedModelDiagonal
+import OAI.Computability.VPVNP.LiveProgram
+import OAI.Computability.VPVNP.LiveTranscriptCoefficients
+
+/-!
+# Choosing the exceptional length after the literal program
+
+The same pair table, evaluator, public operand formulas, and layout powers
+serve every candidate length. The actual compiled coefficient machine then
+has one common eventual threshold. At a candidate small-circuit length the
+integer equations supply the prime and a finite algebra. Only at that point
+are the advice, weighted paths and evaluator configurations selected.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal
+
+
+open Compression BurstRAM LiveProgram RAMTape LabelEvaluator Filter MvPolynomial
+
+/-- The finite tables and exponents chosen before the exceptional length. -/
+structure Program where
+ /-- Powers and label counts used by the live program at every input length. -/
+ constants : Constants
+ /-- Scalar evaluator installed in the second half of the diagonal chain. -/
+ evaluator : UniversalMachine.Program
+ /-- Finite instruction table for a pair in the first half of the chain. -/
+ pair : PairTable
+ /-- Multiplier of the binary address width at input length n. -/
+ addressFactor : ℕ
+ address_pos : 1 ≤ addressFactor
+ /-- Numerator of the rational exponent used to compute the live bucket size. -/
+ numerator : ℕ
+ /-- Denominator of the rational exponent used to compute the live bucket size. -/
+ denominator : ℕ
+ bucket_lt : numerator < denominator
+ /-- Initial persistent word supplied to the live RAM program. -/
+ initialLiteral : ℕ
+
+namespace Program
+
+variable (D : Program)
+
+theorem denominator_pos : 0 < D.denominator := Nat.zero_lt_of_lt D.bucket_lt
+
+/-- The linked RAM instruction table with the chosen evaluator and pair code. -/
+abbrev native := LiveProgram.program D.constants D.evaluator D.pair
+/-- Public operand expressions passed to the linked RAM table. -/
+abbrev operands := LiveProgram.operand D.constants D.evaluator D.pair
+
+/-- The fixed universal-machine program obtained by compiling the live RAM table and its operand expressions. -/
+@[irreducible] noncomputable def literal : UniversalMachine.Program := SiteProcessorPorts.machine D.native D.operands
+ D.addressFactor D.numerator D.denominator 10000 D.initialLiteral D.denominator_pos
+
+theorem literal_eq : D.literal = SiteProcessorPorts.machine D.native D.operands
+ D.addressFactor D.numerator D.denominator 10000 D.initialLiteral D.denominator_pos := by unfold literal; rfl
+
+/-- Address width, bucket size and word width of the live program at the given input length. -/
+def geometry (n : ℕ) : Geometry :=
+ ⟨n, addressWidth D.addressFactor n, 2^(roundedUp D.numerator D.denominator n), CursorBounds.wordBits D.addressFactor n⟩
+
+/-- Instantiate the linked RAM table with public words computed from the compiled program prefix. -/
+noncomputable def liveMachine (n : ℕ) :=
+ D.native.instantiate (D.geometry n).w (fun i => Pieces.word (D.geometry n) (CounterPublic.actualPrefix D.literal) (D.operands i))
+
+/-- Every public operand expression fits the available word width at this length. -/
+def OperandFits (n : ℕ) : Prop :=
+ ∀ j, (InputOperandStartup.Expr D.operands j).Fits (D.geometry n) (2^(D.geometry n).w)
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (B : S.Templates)
+
+/-- Local realization for one chosen joint model. Its fields consist of
+individual pair weights, individual tail counts and native one-group path
+counts. The actual shared processor coefficient is proved separately. -/
+noncomputable abbrev Certificate {n C : ℕ} (hn : 2 ≤ n) {p : Nat.Primes}
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn C))
+ (fit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w) :=
+ B.LocalCertificate hn M (n^D.constants.chainPower-1) (n^D.constants.deltaPower) (n^D.constants.advicePower)
+ (D.geometry n).d (roundedUp D.numerator D.denominator n) (D.geometry n).w (2*n^D.constants.chainPower)
+ (n^D.constants.radiusPower) D.literal fit D.evaluator (D.liveMachine n) (n^10000)
+ (Fin.ofNat (2^(D.geometry n).w) D.initialLiteral)
+
+/-- At sufficiently large lengths the fixed tables meet the local model
+obligations for the primes furnished by the arithmetic specialization. -/
+def Realizes (q C : ℕ) : Prop :=
+ ∀ᶠ n : ℕ in atTop, D.OperandFits n ∧
+ ∀ (hn : 2 ≤ n) (p : Nat.Primes),
+ (q ≠ 0 → p.val = q) → (q = 0 → p.val ≤ 2^B.compressorPrimeBits C n) →
+ Nonempty (Model p (B.compressorDegree n) (B.compressorEquations hn C)) →
+ ∀ fit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w,
+ ∃ M : Model p (B.compressorDegree n) (B.compressorEquations hn C), Nonempty (D.Certificate B hn M fit)
+
+end Program
+
+end FixedProgramDiagonal
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedNativeRealization.lean b/lean/OAI/Computability/VPVNP/FixedNativeRealization.lean
new file mode 100644
index 0000000000..f8e747f659
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedNativeRealization.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.FixedProgramSelection
+import OAI.Computability.VPVNP.FixedProgramRealization
+import OAI.Computability.VPVNP.FixedProgramDiagonal
+
+/-!
+# Specializing the diagonal to the fixed scalar reader and the native pair table
+
+All scalar readers, advice powers and site clocks are those of the concrete
+program. The compiler premise below concerns only executions on prepared
+pair and tail groups. Its table and address multiplier are selected before
+the eventual length. It does not prescribe the integer count of a whole
+chain.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal
+
+open Compression BurstRAM LiveProgram CursorNetwork Filter
+universe u
+
+namespace Program
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (T : S.Templates)
+
+/-- The address multiplier may be increased for the native compressed pair
+implementation, after the scalar clock and advice powers have been fixed. -/
+def NativeCompiler (C : ℕ) : Prop :=
+ let u := pairExponents T
+ ∀ c : Constants, c.circuitExponent = C → c.motifLabels = Fintype.card T.Entry →
+ 2 ≤ c.chainPower → ∀ N : ℕ, ∃ b ≥ N, ∃ (hb : 1 ≤ b) (O : PairTable),
+ let D := ofPaperConstants c CompressorReader.program O b hb (liveRatio u)
+ ∀ᶠ n : ℕ in atTop, D.NativeContinuations T u C n
+
+theorem program_of_native (q C : ℕ) (native : NativeCompiler T C) :
+ ∃ D : Program, D.Realizes T q C := by
+ let u := pairExponents T
+ obtain ⟨env,c,hC,hm,ha,b₀,hb₀,prepared⟩ := select_scalar T q C
+ let cap := max (max (c.chainPower+1) (c.chainPower+c.deltaPower)) (max c.advicePower (grammarCapacityPower C)) + 2
+ let N := max b₀ (max (max S.laneBits 5) cap)
+ obtain ⟨b,hb,hpos,O,runs⟩ := native c hC hm ha N
+ let D := ofPaperConstants c CompressorReader.program O b hpos (liveRatio u)
+ have atB : b₀ ≤ b := (le_max_left ..).trans hb
+ have lanes : max S.laneBits 5 ≤ b := (le_max_left ..).trans ((le_max_right ..).trans hb)
+ have virtual : cap ≤ b := (le_max_right ..).trans ((le_max_right ..).trans hb)
+ have data := prepared b atB O
+ refine ⟨D,?_⟩
+ apply D.realizes_of_continuations T u q C evaluatorPorts env hC hm rfl rfl rfl lanes virtual
+ · filter_upwards [data] with n h
+ obtain ⟨_,h⟩ := h
+ exact h
+ · exact runs
+
+end Program
+
+/-- The only remaining compiler inputs are prepared single-group execution
+proofs for the fixed native implementation. The scalar evaluator, processor
+coefficient, weighted algebraic contradiction, and common field threshold
+all follow from the compiled development. -/
+theorem uniform_of_native_compilers
+ (build : ∀ (C : ℕ), 1 ≤ C → ∀ (q : ℕ) (K : Type) [Field K] [IsAlgClosed K] [Countable K] [CharP K q],
+ ∀ (S : BlockSchedule K) (T : S.Templates), (∃ κ : T.Entry → K, T.IsSolution κ) →
+ Program.NativeCompiler T C) : UniformPBound.{u} := by
+ apply uniform_bound_of_local_programs
+ intro C hC q K _ _ _ _ S T hT
+ exact Program.program_of_native T q C (build C hC q K S T hT)
+
+end FixedProgramDiagonal
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedPaperActualRows.lean b/lean/OAI/Computability/VPVNP/FixedPaperActualRows.lean
new file mode 100644
index 0000000000..bcef60f104
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedPaperActualRows.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.FixedPaperTerminalBounds
+import OAI.Computability.VPVNP.LiveVirtualPairQuietFrame
+import OAI.Computability.VPVNP.PairVertexPaperRatedSelection
+import OAI.Computability.VPVNP.PairVirtualPaperRoleBoundary
+
+/-! # The chosen physical terminal rows of each nominated pair
+
+The three deterministic stages retain the low RAM words on each successful
+prefix. The shared-bit stage selects the actual arc payload. The roles of the
+visited terminal vertices are verified on that same memory, including its
+retained shrinking and refresh records and the virtual coefficient header.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds BurstRAM LiveProgram LiveProgram.CompressedPair Filter
+open LabelEvaluator CompressorRecords ScheduledTrace PairStages PairStages.Group PairStages.Group.CompressedPaths
+open PairSimulation LocalCount
+open scoped Fin.CommRing
+set_option quotPrecheck false
+attribute [local irreducible] BlockProgram.script BlockProgram.layout CursorNetwork.cursorState
+ CompressedPair.stages CompressedPair.regs CompressedPair.components TerminalProgram.workers
+ CursorBounds.wordBits BurstRAM.addressWidth Nat.clog CursorBounds.virtualBits
+ VertexImage.segments VertexImage.template VertexGeometry.segment ShrinkVertexImage.shrinkSegment
+ RefreshVertex.refreshSegment PrimedCounter.renameFlow PrimedInputRAM.Flow.length
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (u : PairExponents B.growthConstant)
+ (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry) (E : UniversalMachine.Program)
+ (addr : ℕ) (positive : 1 ≤ addr)
+local notation "D" => paperProgram B u c labels E addr positive
+local notation "names" => entryOrdinal B c labels
+local notation "scanRate" => VertexImage.RatedRoles.scan B names
+
+set_option maxHeartbeats 1200000 in
+/-- At all sufficiently large lengths the installed terminal table realizes every
+selected compressor vertex within its per-site cost, for every model and nomination. -/
+theorem eventually_paperRatedRows (raw : ℕ) (enough : max S.laneBits 5 ≤ addr) :
+ ∀ᶠ n : ℕ in atTop, PaperRatedRows B u c labels E addr positive raw scanRate n := by
+ have preludeBounds := eventually_paperDescriptorQuiet (D) B u c.circuitExponent enough rfl rfl c labels
+ have replay := eventually_paperDescriptorQuietFrame (D) B u c.circuitExponent enough rfl rfl c labels
+ have site := eventually_rated_at_boundary (D) B u enough rfl rfl labels names
+ have role := eventually_paperRoleBoundary (D) B u labels enough rfl rfl
+ filter_upwards [preludeBounds,replay,site,role,eventually_startup_inputs c positive (liveCapacity_polynomial u),
+ eventually_ge_atTop 128] with n choose frames rated hooks inputs large
+ intro hn p M data V inst G W P cut I A base rate Y z
+ let ht := (D).tagsFit n
+ let hc := dispatchClock hn
+ let m := I.branch.copy.memory ()
+ let ξ := VirtualPairs.exterior data W P rfl labels cut I
+ let i := VirtualPairs.modelIndex data W P rfl labels cut I
+ obtain ⟨q,ready⟩ := choose hn V ht hc M rate m Y z
+ obtain ⟨ws,_,_,before⟩ := inputs G.lit
+ have low : (PairTag.address (publicWords G)).val < (publicWords G 2).val+6 :=
+ before.trans_le (Nat.le_add_right _ _)
+ refine ⟨q,ready,?_,(frames hn V ht hc M rate m Y z).2 q⟩
+ have roleAt := hooks hn V ht hc data W P cut I A rate Y z
+ let oracle (online calendar reference memory : Memory ((D).geometry n).w) :=
+ rated hn V ht hc data.advice ξ i I.μ M.algebra (B.compressorValues hn M)
+ (B.compressorValues_solution hn M) A.leafSites z
+ (virtualBits addr n-reservedLanes B u n) (reservedLanes B u n) (initialWidth addr n) n
+ 1 scanRate online calendar reference memory
+ have good := Y.ratedSelection A z rfl rfl q ready large ws low oracle roleAt
+ unfold VirtualPairs.PaperDescriptor.RatedTerminalRows at good
+ have space : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w := ws.symm.trans_lt (publicWords G 2).isLt
+ have old := (tag_before_workspace G.constants G.g).trans space
+ change Auxiliary.counterBase G + (Auxiliary.histLength G + G.constants.motifLabels) < 2^G.w at old
+ have counterWord : (Auxiliary.terminalOperands G 4).val = Auxiliary.counterBase G :=
+ Nat.mod_eq_of_lt (show Auxiliary.counterBase G < 2^G.w by omega)
+ have grammarWord : (Auxiliary.terminalOperands G 5).val = Auxiliary.histLength G :=
+ Nat.mod_eq_of_lt (show Auxiliary.histLength G < 2^G.w by omega)
+ rw [counterWord,grammarWord] at good
+ unfold RatedAt
+ simp only [TerminalLink.QuietPrefix.reindexWorkers,
+ paperSegments,shrinkRole,refreshRole,TerminalProgram.nativeSegments,TerminalProgram.installedSegments,
+ G,paperProgram,ofPaperConstants,Auxiliary.terminalOperands,publicWords] at good ⊢
+ exact good
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedPaperDescriptorPasses.lean b/lean/OAI/Computability/VPVNP/FixedPaperDescriptorPasses.lean
new file mode 100644
index 0000000000..8a08487932
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedPaperDescriptorPasses.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.CompressorNativeLocatedRuns
+import OAI.Computability.VPVNP.LiveCompressedPairDescriptorRoom
+import OAI.Computability.VPVNP.FixedPaperPairRuns
+
+/-! # The descriptor passes of the fixed paper program
+
+The public workspace is the address evaluated by the paper program's
+layout. Both physical pass compilers run at the common small clock inside
+the same eleven-operand table. Their common length threshold applies before
+the exceptional field model, its label solution and its virtual pair.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+open Compression CursorNetwork CursorBounds BurstRAM LiveProgram LiveProgram.CompressedPair Filter
+open CompressorRecords ScheduledTrace DescriptorSpace LabelEvaluator PairSimulation.LocalHistory
+open PairSimulation.TraversalRoles PairSimulation.TraversalRows PairStages PairStages.Group PairStages.Group.CompressedPaths LocalCount
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (u : PairExponents B.growthConstant)
+variable (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry)
+variable (E : UniversalMachine.Program) (addr : ℕ) (positive : 1 ≤ addr) (C : ℕ)
+attribute [local irreducible] BlockProgram.script BlockProgram.layout BlockClock.small
+local notation "D" => paperProgram B u c labels E addr positive
+
+/-- The fixed paper program executes each selected pass at the public address supplied by the group. -/
+theorem eventually_paperPasses :
+ ∀ᶠ n : ℕ in atTop, PaperPasses B u c labels E addr positive C (descriptorRate B) n := by
+ filter_upwards [eventually_locatedRuns.{0,0} B addr positive, eventually_descriptor_room B u c labels E addr positive,
+ eventually_clocks B addr positive] with n run room clocks
+ intro hn V p M
+ let G := (D).executionGroup n ((D).tagsFit n) (dispatchClock hn)
+ let pub : Fin 11 → Word (wordBits addr n) := publicWords G
+ let base := (LiveProgram.Layout.pairWorkspace c).eval ((D).geometry n)
+ let blocks := blockCount (u.θ : ℝ) n
+ let pos := initialPositions addr n
+ let L := BlockProgram.layout B base pos blocks
+ let f := B.compressorValues hn M
+ let hf := B.compressorValues_solution hn M
+ let cap := sourceCap pub (fuel G)
+ let initial := PairSimulation.TraversalRoles.TaggedLayer.mk (leafLayer (siteOrder V.scanState)) .cursor
+ let frame : Fin 8 → Word (wordBits addr n) := cursorFrame L (S.degreeExponent 0) (virtualBits addr n-reservedLanes B u n)
+ (reservedLanes B u n) (initialWidth addr n)
+ obtain ⟨hw,space,ctrl⟩ := room ((D).tagsFit n) (dispatchClock hn)
+ change (pub 2).val = base at hw
+ have hclk := (clocks.2.2 G pub rfl).1
+ have native : LocatedRuns (CompiledResident.resident B f hf (pub 2) pos blocks n initial frame)
+ pub (levelWords (BlockProgram.layout B (pub 2).val pos blocks))
+ (directoryRows (BlockProgram.layout B (pub 2).val pos blocks)) cap (BlockClock.small B addr n)
+ (nativePassRate (BlockProgram.script B) (descriptorRate B) * pos) blocks pos n :=
+ run f hf pub blocks cap initial frame space (by exact (Nat.le_add_right _ 3).trans hclk)
+ (ctrl _ le_rfl)
+ have address : (base : Word (wordBits addr n)) = pub 2 := by
+ apply Fin.ext
+ rw [Fin.val_natCast,← hw]
+ exact Nat.mod_eq_of_lt (pub 2).isLt
+ change LocatedRuns (V.nativeResident f hf base (CompiledResident.payload (w := wordBits addr n) B f hf
+ (base : Word (wordBits addr n)) pos blocks n)) pub (levelWords L) (directoryRows L) cap (BlockClock.small B addr n)
+ (nativePassRate (BlockProgram.script B) (descriptorRate B)*pos) blocks pos n
+ rw [address]
+ change LocatedRuns (DetailedResident.resident B f hf initial L (endAddress L) n frame
+ (CompiledResident.payload B f hf (pub 2) pos blocks n)) pub (levelWords L) (directoryRows L) _ _ _ _ _ _
+ simpa only [CompiledResident.resident,hw,L] using @native
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedPaperPairCompiler.lean b/lean/OAI/Computability/VPVNP/FixedPaperPairCompiler.lean
new file mode 100644
index 0000000000..63f2f5115c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedPaperPairCompiler.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.FixedPaperDescriptorPasses
+import OAI.Computability.VPVNP.FixedPaperActualRows
+
+/-! # The complete fixed native compressed-pair compiler
+
+The template, parameter numbering, descriptor script, local vertex program,
+and address multiplier are fixed before the exceptional length. Every
+sufficiently large length then supports all finite models and all nominated
+groups of this single physical program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+open Compression CursorNetwork LiveProgram CompressedPair CompressorRecords.ScheduledTrace
+open PairSimulation
+
+/-- One fixed pair table and address multiplier work for all sufficiently large
+lengths and all finite-algebra models used by the diagonal argument. -/
+theorem paperPairCompiler {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (C : ℕ) :
+ PairCompiler B C := by
+ intro c hC labels _ N
+ subst C
+ let u := pairExponents B
+ let addr := max N (max S.laneBits 5)
+ have enough : max S.laneBits 5 ≤ addr := le_max_right ..
+ have positive : 1 ≤ addr := (by decide : 1 ≤ 5).trans ((le_max_right ..).trans enough)
+ let E := CompressorReader.program
+ let raw := descriptorRate B
+ let scan := VertexImage.RatedRoles.scan B (entryOrdinal B c labels)
+ refine ⟨addr,le_max_left ..,positive,paperTable B u c labels,?_⟩
+ apply eventually_pairRuns_of_nativeStages B u c labels E addr positive c.circuitExponent rfl raw enough
+ · exact eventually_paperPasses B u c labels E addr positive c.circuitExponent
+ · apply eventually_paperTerminals_of_rated B u c labels E addr positive raw scan enough
+ exact eventually_paperRatedRows B u c labels E addr positive raw enough
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedPaperPairRuns.lean b/lean/OAI/Computability/VPVNP/FixedPaperPairRuns.lean
new file mode 100644
index 0000000000..7e72fd3b3c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedPaperPairRuns.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.LiveVirtualPairPaperTerminal
+import OAI.Computability.VPVNP.LiveVirtualPairScanSelection
+import OAI.Computability.VPVNP.LiveCompressedPairDescriptorRoom
+import OAI.Computability.VPVNP.CompressorNativePassRates
+import OAI.Computability.VPVNP.FixedCompressedPairDiagonal
+
+/-! # Choosing the finite compressed-pair program before the exceptional length
+
+The fixed table computes the same descriptor and terminal paths used by the
+algebraic expansion. The length threshold precedes the field model, its scalar
+advice and every valid nominated group. All ring-specific work at that length
+uses a single finite model and its actual evaluated template parameters.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds BurstRAM LiveProgram LiveProgram.CompressedPair Filter
+open LabelEvaluator CompressorRecords ScheduledTrace DescriptorSpace
+open PairStages PairStages.Group PairStages.Group.CompressedPaths LocalCount
+open scoped Fin.CommRing
+
+set_option quotPrecheck false
+attribute [local irreducible] BlockProgram.script BlockProgram.layout CursorNetwork.cursorState
+ CompressedPair.stages CompressedPair.regs CompressedPair.components PairSimulation.TerminalProgram.workers
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (u : PairExponents B.growthConstant)
+ (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry) (E : UniversalMachine.Program)
+ (addr : ℕ) (positive : 1 ≤ addr) (C : ℕ) (hC : c.circuitExponent = C)
+
+local notation "D" => paperProgram B u c labels E addr positive
+local notation "script" => BlockProgram.script B
+
+/-- At the specified length, the real selected shrinking and refresh workers
+run in their actual native calendar windows. -/
+abbrev PaperPasses (raw n : ℕ) : Prop :=
+ ∀ (hn : 2 ≤ n) (V : (D).VirtualPairs B u hn C) (p : Nat.Primes)
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn C)),
+ let G := (D).executionGroup n ((D).tagsFit n) (dispatchClock hn)
+ let pub := publicWords G
+ let base := (LiveProgram.Layout.pairWorkspace c).eval ((D).geometry n)
+ let T := blockCount (u.θ : ℝ) n
+ let P := initialPositions addr n
+ let L := BlockProgram.layout B base P T
+ let f := B.compressorValues hn M
+ let ok := B.compressorValues_solution hn M
+ let data := CompiledResident.payload (w := wordBits addr n) B f ok base P T n
+ LocatedRuns (V.nativeResident f ok base data) pub (levelWords L : Word (wordBits addr n))
+ (directoryRows L) (sourceCap pub (fuel G)) (BlockClock.small B addr n) (nativePassRate script raw * P) T P n
+
+/-- For the same descriptor execution and canonical finite payload parser,
+the terminal stages act on the actual memory entering this nominated pair. -/
+abbrev PaperTerminals (raw n : ℕ) : Prop :=
+ ∀ (hn : 2 ≤ n) (p : Nat.Primes) (M : Model p (B.compressorDegree n) (B.compressorEquations hn C))
+ (data : (D).ScalarData B hn M) (V : (D).VirtualPairs B u hn C) [NeZero (virtualBits ((D).addressFactor) n)],
+ let G := (D).executionGroup n ((D).tagsFit n) (dispatchClock hn)
+ ∀ (W : Conditions G (2^G.g.d) G.g.H) (P : PairStageConditions G (2^G.g.d) G.g.H)
+ (cut : 1+B.denseCount n C*(D).counterWidth n ≤ n^c.deltaPower)
+ (I : VirtualPairs.PhysicalInput data W P hC labels cut)
+ (A : CanonicalScan data V (VirtualPairs.exterior data W P hC labels cut I)
+ (VirtualPairs.modelIndex data W P hC labels cut I) (physicalNomination hC I.μ)),
+ let base := (LiveProgram.Layout.pairWorkspace c).eval ((D).geometry n)
+ let rate := nativePassRate script raw * initialPositions addr n
+ ∀ Y : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M) c labels base
+ (fuel G) rate (publicWords G) (I.branch.copy.memory ()),
+ Nonempty (V.PaperTerminal data W P hC labels cut I A rate Y)
+
+set_option maxHeartbeats 1200000 in
+/-- Compile the per-pass and per-vertex physical source proofs into the
+complete group-path specification at the fixed program's actual prefix. -/
+theorem eventually_pairRuns_of_nativeStages (raw : ℕ) (enough : max S.laneBits 5 ≤ addr)
+ (passes : ∀ᶠ n : ℕ in atTop, PaperPasses B u c labels E addr positive C raw n)
+ (terminal : ∀ᶠ n : ℕ in atTop, PaperTerminals B u c labels E addr positive C hC raw n) :
+ ∀ᶠ n : ℕ in atTop, (D).PairRuns B u C hC labels n := by
+ obtain ⟨hd,initial⟩ := eventually_paperStartup.{0} B u c labels E addr positive ((le_max_left ..).trans enough)
+ filter_upwards [passes,terminal,initial,eventually_canonicalScan (D) B u C enough,
+ eventually_scan_prefix (D) B u C enough,eventually_descriptor_room B u c labels E addr positive]
+ with n perPass perTerminal starts scan sizes room
+ intro hn p M data fit V W P cut
+ let : NeZero (virtualBits ((D).addressFactor) n) := ⟨(Nat.zero_lt_one.trans V.dimension).ne'⟩
+ apply V.compressedCalls_of_nativeRuns data fit W P hC labels cut
+ intro I
+ let G := (D).executionGroup n ((D).tagsFit n) (dispatchClock hn)
+ let ws := (LiveProgram.Layout.pairWorkspace c).eval ((D).geometry n)
+ let rate := nativePassRate script raw * initialPositions addr n
+ obtain ⟨workspace,setup,start⟩ := starts ((D).tagsFit n) (dispatchClock hn) (I.branch.copy.memory ()) I.pairStartTag
+ obtain ⟨A⟩ := scan hn V p M data (VirtualPairs.exterior data W P hC labels cut I)
+ (VirtualPairs.modelIndex data W P hC labels cut I) (physicalNomination hC I.μ)
+ obtain ⟨_,_,controls⟩ := room ((D).tagsFit n) (dispatchClock hn)
+ let f := B.compressorValues hn M
+ let ok := B.compressorValues_solution hn M
+ obtain ⟨Y⟩ := V.paperDescriptor_of_runs f ok c labels ws (fuel G) rate (publicWords G) (I.branch.copy.memory ())
+ hd (start f ok) (controls _ le_rfl) (sizes hn V M.algebra f ok) (perPass hn V p M)
+ obtain ⟨Q⟩ := perTerminal hn p M data V W P cut I A Y
+ exact ⟨V.nativeRunsOfPaperTerminal data fit W P hC labels cut I A rate Y rfl workspace setup Q⟩
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedPaperRatedTerminal.lean b/lean/OAI/Computability/VPVNP/FixedPaperRatedTerminal.lean
new file mode 100644
index 0000000000..4f99dcc289
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedPaperRatedTerminal.lean
@@ -0,0 +1,209 @@
+import OAI.Computability.VPVNP.FixedPaperPairRuns
+import OAI.Computability.VPVNP.LiveVirtualPairQuietPrelude
+import OAI.Computability.VPVNP.LiveVirtualPairVertexCounters
+import OAI.Computability.VPVNP.LiveRatedVertexDeposits
+import OAI.Computability.VPVNP.LiveRatedTerminalFrames
+import OAI.Computability.VPVNP.LiveVirtualPairBranchCharge
+import OAI.Computability.VPVNP.LiveTerminalWorkerTransport
+import OAI.Computability.VPVNP.LiveRatedArcMemory
+import OAI.Computability.VPVNP.LiveRatedRowCharges
+
+/-! # Assembling the actual selected sites into the fixed terminal program
+
+The shared-bit readback, the chronological low-word frame, and the rated
+local vertex executions all use one quiet prefix. Transport to the packed
+runtime directory preserves the reports and final memory. The two DFS
+pointer functions here are the ones used by the physical placement trees.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds BurstRAM LiveProgram LiveProgram.CompressedPair LocalCount
+open LabelEvaluator CompressorRecords ScheduledTrace DescriptorSpace
+open PairStages PairStages.Group PairStages.Group.CompressedPaths SourceTransport
+open PairSimulation LocalHistory NetworkKernel TraversalRows TerminalLink
+open scoped Fin.CommRing
+
+set_option quotPrecheck false
+set_option maxHeartbeats 1400000
+/-- Transfer the complete reached-state predicate across the inner table's
+final lookup. This also transfers the native configuration type indexed by
+the register and program-counter counts of that row. -/
+private theorem finalRowFrame {d initial phases w : ℕ} {C : Schedule.Catalog d}
+ (boot : Bootstrap) (plan : Schedule.Online.Config C initial phases)
+ (shape : DescriptorSpace.Shape) (limit : ℕ) (parts : VertexImage.Part → VertexImage.Segment)
+ (ports : Fin 11 → Word w) (clock : ℕ) (mem : Memory w) (a : ℕ) :
+ PreservesCell (TerminalLink.program (TerminalProgram.workers shape limit parts) ports)
+ clock 0 mem a →
+ PreservesCell (original boot plan (TerminalProgram.table shape limit parts) ports
+ CompressedPair.Stage.terminal) clock 0 mem a := fun h => @h
+
+attribute [local irreducible] BlockProgram.script BlockProgram.layout CursorNetwork.cursorState
+ CompressedPair.stages CompressedPair.regs CompressedPair.components TerminalProgram.workers paperTable
+ BlockSchedule.Templates.execute CursorBounds.virtualBits CursorBounds.wordBits
+ VertexImage.template VertexImage.segments PhysicalScanData.physical stateScanPhase
+ PhaseRecipe.Expr.slots DescriptorHeads.publisher BlockProgram.geometry BlockProgram.allocationShape
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (u : PairExponents B.growthConstant) (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry)
+ (prog : UniversalMachine.Program) (addr : ℕ) (positive : 1 ≤ addr)
+local notation "D" => paperProgram B u c labels prog addr positive
+variable {n : ℕ} {hn : 2 ≤ n} {ht : 21 ≤ 2^((paperProgram B u c labels prog addr positive).geometry n).w} {hc : 44 ≤ n^10000}
+ {p : Nat.Primes} {M : Model p (B.compressorDegree n) (B.compressorEquations hn c.circuitExponent)}
+ (data : (paperProgram B u c labels prog addr positive).ScalarData B hn M) (V : (paperProgram B u c labels prog addr positive).VirtualPairs B u hn c.circuitExponent)
+ [NeZero (virtualBits ((paperProgram B u c labels prog addr positive).addressFactor) n)]
+local notation "G" => (paperProgram B u c labels prog addr positive).executionGroup n ht hc
+variable (W : Conditions ((paperProgram B u c labels prog addr positive).executionGroup n ht hc) (2^((paperProgram B u c labels prog addr positive).geometry n).d) ((paperProgram B u c labels prog addr positive).geometry n).H)
+ (P : PairStageConditions ((paperProgram B u c labels prog addr positive).executionGroup n ht hc) (2^((paperProgram B u c labels prog addr positive).geometry n).d) ((paperProgram B u c labels prog addr positive).geometry n).H)
+ (cut : 1+B.denseCount n c.circuitExponent*(paperProgram B u c labels prog addr positive).counterWidth n ≤ n^c.deltaPower)
+ (I : VirtualPairs.PhysicalInput data W P rfl labels cut)
+variable (A : CanonicalScan data V (VirtualPairs.exterior data W P rfl labels cut I)
+ (VirtualPairs.modelIndex data W P rfl labels cut I) (physicalNomination rfl I.μ))
+
+local notation "script" => BlockProgram.script B
+local notation "f" => B.compressorValues hn M
+local notation "ok" => B.compressorValues_solution hn M
+local notation "sel" => V.selection (M := M)
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "ws" => PublicExpr.eval ((D).geometry n) (Layout.pairWorkspace c)
+local notation "positions" => initialPositions addr n
+local notation "L" => BlockProgram.layout B ws positions T
+local notation "rowBase" => endAddress L
+local notation "wire" z => rowBase + words B.recordLimit (selectedLayers B f ok T le_rfl V.scanState z)
+local notation "ports" => publicWords (G)
+local notation "clk" => fuel (G)
+local notation "cap" => CompressedPair.clockAt ports clk CompressedPair.Stage.terminal
+local notation "names" => entryOrdinal B c labels
+local notation "parts" => paperSegments B u c labels
+local notation "bank" => TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit parts
+local notation "packed" => TerminalProgram.workers (L).shape B.recordLimit parts
+local notation "counter" => Auxiliary.counterBase (G)
+local notation "grammar" => Auxiliary.histLength (G)
+local notation "input" => I.branch.copy.memory ()
+local notation "boot" => paperBootstrap B u
+
+variable (raw scanRate link : ℕ)
+local notation "rate" => nativePassRate script raw * positions
+local notation "site" => VertexReportBudget.coefficient S.baseDegree (Fintype.card B.Entry) 6 scanRate 0 0
+local notation "bootCost" => TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit+1
+
+variable (Y : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M) c labels
+ ((Layout.pairWorkspace c).eval ((paperProgram B u c labels prog addr positive).geometry n)) (fuel ((paperProgram B u c labels prog addr positive).executionGroup n ht hc))
+ (nativePassRate (BlockProgram.script B) raw * initialPositions addr n)
+ (publicWords ((paperProgram B u c labels prog addr positive).executionGroup n ht hc)) (I.branch.copy.memory ()))
+
+/-- The site constructor consumes the actual post-scan memory at the true
+compressed source clock. -/
+abbrev RatedAt (z : (sel).Choices) (q : QuietPrefix bank ports cap (onlinePost (Y.paths z)))
+ (ready : Y.QuietData z q) : Prop :=
+ RatedSelection A z names rowBase counter grammar cap ports q (wire z) q.traversalRows.val.memory
+ ready.layout ready.clock ready.headerFit ready.below (fun _ _ => rfl) 1 scanRate
+
+/-- Each mathematical branch has a physical quiet prefix with its complete
+per-report footprint and the certified native ordinal executions on it. -/
+abbrev RatedBranchesAt : Prop :=
+ ∀ z : (sel).Choices, ∃ q : QuietPrefix bank ports cap (onlinePost (Y.paths z)),
+ ∃ ready : Y.QuietData z q, RatedAt B u c labels prog addr positive data V W P cut I A raw scanRate Y z q ready ∧
+ ∀ a < (ports 2).val, ReplayFrame a (onlinePost (Y.paths z)) q.reportList
+
+local notation "ptr" z => chainPointers B.recordLimit (selectedChain (V := V) (M := M) z)
+ (branchOrders (sel) (B.records f ok T le_rfl V.scanState) z)
+ (TraversalRows.address B.recordLimit rowBase (siteOrder V.scanState).length)
+local notation "leaf" => sitePointers B.recordLimit rowBase (siteOrder V.scanState)
+
+set_option maxHeartbeats 350000 in
+/-- The rated rows on the real selected memory produce all fields of the
+paper terminal certificate, including the linked total and per-call caps. -/
+theorem paperTerminalOfRated_exists
+ (setup : TransferredStartup.Runs (bootstrapRows boot (script).initial.length (script).block.length) (script).size
+ (startupLayout boot (script).initial.length (script).block.length addr n ws) addr n
+ (S.degreeExponent 0) S.laneBits S.steps ports (PairTag.address ports) input)
+ (workspace : ws < 2^((D).geometry n).w)
+ (rows : RatedBranchesAt B u c labels prog addr positive data V W P cut I A raw scanRate Y)
+ (h : BranchClocks.{0} B u addr boot (script).initial.length (script).block.length raw site 1 link n)
+ (large : 2048 ≤ n) (degree : S.baseDegree ≤ n) (labelsFit : Fintype.card B.Entry ≤ n)
+ (width : ∀ z : (sel).Choices, ((sel).finalState z).maxWireWidth ≤ n)
+ (depth : ∀ (z : (sel).Choices) v, (selectedChain (V := V) (M := M) z).occurrences (fun _ => 1) v ≤ n)
+ (prefixCosts : ∀ (z : (sel).Choices) (t : FiveTrace packed ports cap (onlinePost (Y.paths z))),
+ Nonempty (PreludeCosts V.scanState ((sel).finalState z) ports t S.steps B.recordLimit T bootCost)) :
+ Nonempty (V.PaperTerminal data W P rfl labels cut I A rate Y) := by
+ classical
+ constructor
+ let q z := (rows z).choose
+ let ready z := (rows z).choose_spec.choose
+ let R z := (rows z).choose_spec.choose_spec.1
+ have replay z := (rows z).choose_spec.choose_spec.2
+ have bankEq : bank = packed := (TerminalLayout.packed_workers B ws positions T parts).symm
+ have numeric := terminal_protected_addresses (G) (ports 2).val workspace le_rfl
+ have counterEnd z : counter+grammar+c.motifLabels ≤ (header ports).val :=
+ numeric.1.2.le.trans ((numeric.1.1.trans_le (ready z).low).le.trans
+ ((Nat.le_add_right (wire z) _).trans (ready z).below))
+ let rawBranch z := (R z).branch A z names rowBase counter grammar cap ports (q z) (wire z)
+ (q z).traversalRows.val.memory (ready z).layout (ready z).clock (ready z).headerFit (ready z).below
+ (fun _ _ => rfl) (counterEnd z)
+ let branches z := (rawBranch z).reindexWorkers bankEq
+ refine ⟨branches,(fun z => ptr z),leaf,?_,?_,?_,?_⟩
+ · intro z
+ apply finalRowFrame boot (script).plan (L).shape B.recordLimit parts ports cap (onlinePost (Y.paths z))
+ intro st now tape out reached run
+ exact (R z).branch_frames A z names rowBase counter grammar cap ports (q z) (wire z)
+ (q z).traversalRows.val.memory (ready z).layout (ready z).clock (ready z).headerFit (ready z).below
+ (fun _ _ => rfl) (counterEnd z) bankEq (ready z).low (replay z) _ numeric.1.1 (.inr numeric.1.2.le) reached run
+ · intro z a ha
+ apply finalRowFrame boot (script).plan (L).shape B.recordLimit parts ports cap (onlinePost (Y.paths z))
+ intro st now tape out reached run
+ obtain ⟨low,outside⟩ := numeric.2 a ha
+ exact (R z).branch_frames A z names rowBase counter grammar cap ports (q z) (wire z)
+ (q z).traversalRows.val.memory (ready z).layout (ready z).clock (ready z).headerFit (ready z).below
+ (fun _ _ => rfl) (counterEnd z) bankEq (ready z).low (replay z) a low (.inl outside) reached run
+ · intro z x j
+ apply (R z).deposits_reindex A z names rowBase counter grammar cap ports (q z) (wire z)
+ (q z).traversalRows.val.memory (ready z).layout (ready z).clock (ready z).headerFit (ready z).below
+ (fun _ _ => rfl) (counterEnd z) bankEq x (ptr z) leaf input _ j
+ intro j'
+ let bitPath := (rawBranch z).bitPaths x.arcs
+ have tape := (R z).bitPath_tapes A z names rowBase counter grammar cap ports (q z) (wire z)
+ (q z).traversalRows.val.memory (ready z).layout (ready z).clock (ready z).headerFit (ready z).below
+ (fun _ _ => rfl) (counterEnd z) x.arcs
+ rw [(R z).sourceMem_eq A z names rowBase counter grammar cap ports (q z) (wire z)
+ (q z).traversalRows.val.memory (ready z).layout (ready z).clock (ready z).headerFit (ready z).below
+ (fun _ _ => rfl) (counterEnd z) x.arcs]
+ exact Y.vertex_counter_initial data V W P rfl labels cut I rate z setup workspace
+ ((ready z).entry _ bitPath tape).1 j'
+ · intro z x
+ exact Y.branchCharge (arc := A.arc) (sites := A.sites) V branches h rfl rfl z x (by decide)
+ (prefixCosts z ((branches z).chosenTrace x))
+ ((R z).chosenRows_packed A z names rowBase counter grammar cap ports (q z) (wire z)
+ (q z).traversalRows.val.memory (ready z).layout (ready z).clock (ready z).headerFit (ready z).below
+ (fun _ _ => rfl) (counterEnd z) bankEq large degree labelsFit (width z) (depth z) x)
+
+/-- Choose a checked terminal certificate on this descriptor. The existence
+theorem supplies the native rows, frames, counter readback and clock bounds. -/
+noncomputable def paperTerminalOfRated
+ (setup : TransferredStartup.Runs (bootstrapRows boot (script).initial.length (script).block.length) (script).size
+ (startupLayout boot (script).initial.length (script).block.length addr n ws) addr n
+ (S.degreeExponent 0) S.laneBits S.steps ports (PairTag.address ports) input)
+ (workspace : ws < 2^((D).geometry n).w)
+ (rows : RatedBranchesAt B u c labels prog addr positive data V W P cut I A raw scanRate Y)
+ (h : BranchClocks.{0} B u addr boot (script).initial.length (script).block.length raw site 1 link n)
+ (large : 2048 ≤ n) (degree : S.baseDegree ≤ n) (labelsFit : Fintype.card B.Entry ≤ n)
+ (width : ∀ z : (sel).Choices, ((sel).finalState z).maxWireWidth ≤ n)
+ (depth : ∀ (z : (sel).Choices) v, (selectedChain (V := V) (M := M) z).occurrences (fun _ => 1) v ≤ n)
+ (prefixCosts : ∀ (z : (sel).Choices) (t : FiveTrace packed ports cap (onlinePost (Y.paths z))),
+ Nonempty (PreludeCosts V.scanState ((sel).finalState z) ports t S.steps B.recordLimit T bootCost)) :
+ V.PaperTerminal data W P rfl labels cut I A rate Y :=
+ Classical.choice (paperTerminalOfRated_exists B u c labels prog addr positive data V W P cut I A
+ raw scanRate link Y setup workspace rows h large degree labelsFit width depth prefixCosts)
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedPaperTerminalBounds.lean b/lean/OAI/Computability/VPVNP/FixedPaperTerminalBounds.lean
new file mode 100644
index 0000000000..6827b4ecf1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedPaperTerminalBounds.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.FixedPaperRatedTerminal
+import OAI.Computability.VPVNP.PairVertexOrdinalLiveCosts
+
+/-! # Uniformly closing the costs of the physical terminal
+
+The fixed vertex scan rate and raw pass charge are chosen before the input
+length. The prelude and all accepting vertex reports then fit the physical
+group clock and bucket for every nominated pair and every finite model.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds BurstRAM LiveProgram LiveProgram.CompressedPair Filter
+open LabelEvaluator CompressorRecords ScheduledTrace PairStages PairStages.Group PairStages.Group.CompressedPaths
+open PairSimulation LocalCount
+open scoped Fin.CommRing
+set_option quotPrecheck false
+attribute [local irreducible] BlockProgram.script BlockProgram.layout CursorNetwork.cursorState
+ CompressedPair.stages CompressedPair.regs CompressedPair.components TerminalProgram.workers
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (u : PairExponents B.growthConstant)
+ (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry) (E : UniversalMachine.Program)
+ (addr : ℕ) (positive : 1 ≤ addr)
+local notation "D" => paperProgram B u c labels E addr positive
+local notation "script" => BlockProgram.script B
+
+/-- The true native role calls, chosen shared-bit data and chronological
+prefix readbacks at one length. The scalar ring and advice are the ones
+supplied by the joint finite model for this nominated pair. -/
+abbrev PaperRatedRows (raw scanRate n : ℕ) : Prop :=
+ ∀ (hn : 2 ≤ n) (p : Nat.Primes) (M : Model p (B.compressorDegree n) (B.compressorEquations hn c.circuitExponent))
+ (data : (D).ScalarData B hn M) (V : (D).VirtualPairs B u hn c.circuitExponent) [NeZero (virtualBits ((D).addressFactor) n)],
+ let G := (D).executionGroup n ((D).tagsFit n) (dispatchClock hn)
+ ∀ (W : Conditions G (2^G.g.d) G.g.H) (P : PairStageConditions G (2^G.g.d) G.g.H)
+ (cut : 1+B.denseCount n c.circuitExponent*(D).counterWidth n ≤ n^c.deltaPower)
+ (I : VirtualPairs.PhysicalInput data W P rfl labels cut)
+ (A : CanonicalScan data V (VirtualPairs.exterior data W P rfl labels cut I)
+ (VirtualPairs.modelIndex data W P rfl labels cut I) (physicalNomination rfl I.μ)),
+ let base := (LiveProgram.Layout.pairWorkspace c).eval ((D).geometry n)
+ let rate := nativePassRate script raw * initialPositions addr n
+ ∀ Y : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M) c labels base
+ (fuel G) rate (publicWords G) (I.branch.copy.memory ()),
+ RatedBranchesAt B u c labels E addr positive data V W P cut I A raw scanRate Y
+
+set_option maxHeartbeats 1200000 in
+theorem eventually_paperTerminals_of_rated (raw scanRate : ℕ) (enough : max S.laneBits 5 ≤ addr)
+ (rows : ∀ᶠ n : ℕ in atTop, PaperRatedRows B u c labels E addr positive raw scanRate n) :
+ ∀ᶠ n : ℕ in atTop, PaperTerminals B u c labels E addr positive c.circuitExponent rfl raw n := by
+ obtain ⟨hd,start⟩ := eventually_paperStartup.{0} B u c labels E addr positive ((le_max_left ..).trans enough)
+ let site := VertexReportBudget.coefficient S.baseDegree (Fintype.card B.Entry) 6 scanRate 0 0
+ have clocks := eventually_branchClocks.{0,0} B u addr enough (paperBootstrap B u) (script).initial.length
+ (script).block.length raw site 1 0
+ have preludeBounds := eventually_paperDescriptorPrelude (D) B u c.circuitExponent enough rfl rfl c labels
+ have geometry := VertexImage.eventually_ordinal_geometry B u c (liveRatio u).num (liveRatio u).den addr
+ (slotDegree S) enough
+ filter_upwards [rows,start,clocks,preludeBounds,geometry] with n installed startup caps prelude geo
+ intro hn p M data V inst G W P cut I A base rate Y
+ have entered := startup ((D).tagsFit n) (dispatchClock hn) (I.branch.copy.memory ()) I.pairStartTag
+ have actual : ∀ z : (V.selection (M := M)).Choices, let chain := selectedChain (V := V) (M := M) z
+ let out := (V.selection (M := M)).finalState z
+ out.maxWireWidth ≤ n ∧ ∀ v, chain.occurrences (fun _ => 1) v ≤ n := by
+ have h := geo.2.2.2.2 (laneLabels _ _ V.lanes) V.dimension le_rfl M.algebra
+ (B.compressorValues hn M) (B.compressorValues_solution hn M)
+ unfold selectedChain VirtualPairs.selection
+ rw [V.scanState_pairInput]
+ exact h
+ refine ⟨paperTerminalOfRated B u c labels E addr positive data V W P cut I A raw scanRate 0 Y
+ entered.2.1 entered.1 (installed hn p M data V W P cut I A Y) caps geo.1 geo.2.1 geo.2.2.1
+ (fun z => (actual z).1) (fun z => (actual z).2) ?_⟩
+ exact prelude hn V ((D).tagsFit n) (dispatchClock hn) M rate (I.branch.copy.memory ()) Y
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramDiagonal.lean b/lean/OAI/Computability/VPVNP/FixedProgramDiagonal.lean
new file mode 100644
index 0000000000..f229ddc7cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramDiagonal.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.FixedCompressionModels
+import OAI.Computability.VPVNP.FixedNativeProgram
+import OAI.Computability.VPVNP.SeparationConsequences
+
+/-!
+# Choosing the exceptional length after the literal program
+
+The same pair table, evaluator, public operand formulas, and layout powers
+serve every candidate length. The actual compiled coefficient machine then
+has one common eventual threshold. At a candidate small-circuit length the
+integer equations supply the prime and a finite algebra. Only at that point
+are the advice, weighted paths and evaluator configurations selected.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal
+
+universe u
+set_option maxHeartbeats 2000000
+
+open Compression BurstRAM LiveProgram RAMTape LabelEvaluator Filter MvPolynomial
+
+namespace Program
+
+variable (D : Program) {K : Type*} [Field K] {S : BlockSchedule K} (B : S.Templates)
+
+theorem contradiction (q C : ℕ) (localRuns : D.Realizes B q C)
+ (hsmall : ∀ N, ∃ n ≥ N, circuitSize (map (Int.castRingHom K) (P n)) ≤ n^C)
+ (models : ∀ n (hn : 2 ≤ n), circuitSize (map (Int.castRingHom K) (P n)) ≤ n^C →
+ ∃ p : Nat.Primes, (q ≠ 0 → p.val = q) ∧ (q = 0 → p.val ≤ 2^B.compressorPrimeBits C n) ∧
+ Nonempty (Model p (B.compressorDegree n) (B.compressorEquations hn C))) : False := by
+ have localAt := (eventually_atTop.1 localRuns)
+ obtain ⟨N₁, hN₁⟩ := localAt
+ obtain ⟨N₂, hN₂⟩ := eventually_atTop.1 (LiveTranscript.eventually_coefficients D.native D.operands
+ D.addressFactor D.numerator D.denominator D.initialLiteral D.address_pos D.denominator_pos D.bucket_lt)
+ obtain ⟨n, hn, small⟩ := hsmall (max 2 (max N₁ N₂))
+ have hn₂ : 2 ≤ n := (le_max_left ..).trans hn
+ have hn₁ : N₁ ≤ n := (le_max_left ..).trans ((le_max_right ..).trans hn)
+ have hn' : N₂ ≤ n := (le_max_right ..).trans ((le_max_right ..).trans hn)
+ obtain ⟨hg,cert⟩ := hN₁ n hn₁
+ have atGeometry := hN₂ n hn'
+ rw [← D.literal_eq] at atGeometry
+ change D.OperandFits n → LiveTranscript.Coefficients D.literal (D.liveMachine n)
+ n (D.geometry n).d (roundedUp D.numerator D.denominator n) (n^10000)
+ (Fin.ofNat (2^(D.geometry n).w) D.initialLiteral) at atGeometry
+ have sites : LiveTranscript.Coefficients D.literal (D.liveMachine n)
+ n (D.geometry n).d (roundedUp D.numerator D.denominator n) (n^10000)
+ (Fin.ofNat (2^(D.geometry n).w) D.initialLiteral) := by exact (by assumption : D.OperandFits n → _) (by assumption)
+ obtain ⟨p,hp,hsize,hM⟩ := models n hn₂ small
+ obtain ⟨_,⟨L⟩⟩ := cert hn₂ p hp hsize hM sites.fits
+ exact L.false_of_processor sites.count
+
+end Program
+
+/-- This implication discharges the field quantifiers, the arithmetic
+specialization and the physical processor. Its input is the fixed compiler's
+eventual local realization on the two compressor templates. -/
+theorem uniform_bound_of_local_programs
+ (compile : ∀ (C : ℕ), 1 ≤ C → ∀ (q : ℕ) (K : Type) [Field K] [IsAlgClosed K] [Countable K] [CharP K q],
+ ∀ (S : BlockSchedule K) (B : S.Templates), (∃ κ : B.Entry → K, B.IsSolution κ) →
+ ∃ D : Program, D.Realizes B q C) : UniformPBound.{u} := by
+ apply uniform_P_bound_of_diagonal_contradiction
+ intro C hC q K _ _ _ _ small
+ obtain ⟨S,B,solution,models⟩ := fixed_models_of_small_circuits K q hC small
+ obtain ⟨D,localRuns⟩ := compile C hC q K S B solution
+ exact D.contradiction B q C localRuns small models
+
+end FixedProgramDiagonal
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramModelData.lean b/lean/OAI/Computability/VPVNP/FixedProgramModelData.lean
new file mode 100644
index 0000000000..28534ee54b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramModelData.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.FixedNativeProgram
+import OAI.Computability.VPVNP.LiveProgramAdviceCapacity
+import OAI.Computability.VPVNP.EvaluatorProgramRawInput
+import OAI.Computability.VPVNP.RAMTapePhysicalHalting
+
+/-!
+# The shared advice and paths of the fixed diagonal program
+
+The program distributes one advice string across the groups. It contains
+the raw evaluator advice followed, after padding, by the permutation from
+dense physical labels to the joint formal label order. Every midpoint
+configuration starts on that very raw advice and the same truncated exponent
+words. The weighted pair paths and the native single-group counts must
+refer to this common distribution.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression BurstRAM LiveProgram LabelEvaluator CutSchedule ExponentTrace JointLabelSystem
+open LiveEvaluatorEncoding UniversalMachine
+
+local instance (p : Nat.Primes) : Fact p.val.Prime := ⟨p.property⟩
+/-- Enumerate the finite ground field of the selected slice. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+/-- View the ambient field as an algebra over the ground field through the slice embedding. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) :=
+ (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra
+
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ {n C : ℕ} (hn : 2 ≤ n) {p : Nat.Primes}
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn C))
+
+/-- Height `h` for which each half of the diagonal chain has `2^h` groups. -/
+def chainHeight (n : ℕ) := n^D.constants.chainPower-1
+/-- Bit width reserved for each accumulated label exponent. -/
+def counterWidth (n : ℕ) := 2*n^D.constants.chainPower
+
+/-- Formal label index at a physical counter position, encoded as an advice word. -/
+noncomputable def orderWord (n C : ℕ) (i : Fin (B.denseCount n C)) :
+ BurstRAM.Word (Nat.clog 2 (B.compressorLabelCount C n)) :=
+ let j := FixedRows.labelOrder B.Entry n C i
+ ⟨j.val,j.isLt.trans_le (Nat.le_pow_clog (by decide) _)⟩
+
+/-- Pack the raw evaluator advice and the physical-to-formal label permutation into the shared tape. -/
+noncomputable def distributedAdvice (n C : ℕ) (raw : List Bool) : Bits (n^D.constants.advicePower) :=
+ Advice.adviceTape (D.geometry n).w (n^D.constants.prefixPower) (n^D.constants.advicePower)
+ raw (orderWord B n C)
+
+/-- Encode each exponent modulo the word size used by the evaluator. -/
+def exponentWords (n : ℕ) {t : ℕ} (xs : Fin t → ℕ) : Fin t → BurstRAM.Word (D.counterWidth n) :=
+ fun j => Fin.ofNat _ (xs j)
+
+/-- Start the evaluator on its raw advice followed by the serialized exponent vector. -/
+def initial (n : ℕ) {t : ℕ} (raw : List Bool) (xs : Fin t → ℕ) :=
+ UniversalMachine.initial D.evaluator (raw ++ EvaluatorProgramRawInput.runtime (D.exponentWords n xs))
+
+/-- The scalar program at this model has exactly the raw input assembled
+by the midpoint stages. The range statement covers all branch histories,
+so it also covers the initial configuration in the absence of an accepting path. -/
+structure ScalarData where
+ /-- Raw binary reader advice for this finite model. -/
+ raw : List Bool
+ rawLength : raw.length ≤ n^D.constants.prefixPower
+ adviceSpace : (D.geometry n).w+n^D.constants.prefixPower+B.denseCount n C*Nat.clog 2 (B.compressorLabelCount C n)
+ ≤ n^D.constants.advicePower
+ halt : ∀ xs : Fin (B.compressorLabelCount C n) → ℕ,
+ AllHalt D.evaluator (2^(D.chainHeight n)) (D.initial n raw xs)
+ space : ∀ (xs : Fin (B.compressorLabelCount C n) → ℕ) (time : ℕ) (bs : Fin time → Bool) (i : Fin (time+1)),
+ StateFits (n^D.constants.radiusPower) (EvaluatorTail.history D.evaluator time (D.initial n raw xs) bs i)
+ value : ∀ xs : Fin (B.compressorLabelCount C n) → ℕ, (∀ i, xs i < 2^(D.counterWidth n)) →
+ (paths D.evaluator (2^(D.chainHeight n)) (D.initial n raw xs) : ZMod p.val) =
+ (M.presentation.branchCount p.val (D.counterWidth n) xs : ZMod p.val)
+
+variable {D B hn M} (data : D.ScalarData B hn M)
+
+/-- Shared chain advice obtained by packing the scalar reader advice and label order. -/
+noncomputable def ScalarData.advice := D.distributedAdvice B n C data.raw
+
+/-- Encode the midpoint evaluator configuration after reindexing the physical counters. -/
+noncomputable def ScalarData.init (xs : Fin (B.denseCount n C) → ℕ) :=
+ LiveEvaluatorTail.initialCode (n^D.constants.radiusPower)
+ (D.initial n data.raw (B.formalExponents xs))
+
+theorem ScalarData.init_state (xs : Fin (B.denseCount n C) → ℕ) :
+ (data.init xs).toState = EvaluatorTail.canonical (D.initial n data.raw (B.formalExponents xs)) :=
+ LiveEvaluatorTail.initialCode_toState _ (data.space (B.formalExponents xs) 0 Fin.elim0 0)
+
+theorem ScalarData.histories (xs : Fin (B.compressorLabelCount C n) → ℕ) :
+ LiveEvaluatorTail.HistoriesFit D.evaluator (n^D.constants.radiusPower) (2^(D.chainHeight n))
+ (D.initial n data.raw xs) :=
+ fun bs _ i => data.space xs _ bs i
+
+variable (fit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+
+set_option maxHeartbeats 800000 in
+/-- Finite weighted paths for each pair whose sum recovers its nominated grammar multiplicity. -/
+structure PairData where
+ /-- Path choices for this exterior, pair index and production nomination. -/
+ Path : Exterior (D.chainHeight n) (n^D.constants.deltaPower) → Fin (2^(D.chainHeight n)) →
+ Compression.BlockSchedule.Templates.PairNomination n C (D.geometry n).d → Type
+ [pathFintype : ∀ ξ i μ, Fintype (Path ξ i μ)]
+ /-- Compressor label exponents contributed by one pair path. -/
+ ν : ∀ ξ i μ, Path ξ i μ → B.Entry → ℕ
+ bounded : ∀ ξ i μ q v, ν ξ i μ q v < 2^(2*(D.geometry n).d)
+ weight : ∀ ξ i μ, (∑ q : Path ξ i μ, ∏ v, (B.compressorValues hn M v)^ν ξ i μ q v) =
+ (GrammarDiagonal.multiplicity (⟨n-1,by omega⟩ : Fin n) (⟨0,pow_pos (by omega) _⟩ : Fin (n^(C+5)))
+ (PairedChain.siteInput (h := D.chainHeight n) (Δ := n^D.constants.deltaPower) (n := n)
+ (r := (D.geometry n).d) (bucket := (D.geometry n).H) (w := (D.geometry n).w) D.literal fit data.advice ξ i) μ : M.algebra)
+
+attribute [instance] PairData.pathFintype
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramOperandFits.lean b/lean/OAI/Computability/VPVNP/FixedProgramOperandFits.lean
new file mode 100644
index 0000000000..4769652870
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramOperandFits.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.FixedNativeProgram
+import OAI.Computability.VPVNP.PaperPairParameters
+import OAI.Computability.VPVNP.LiveProgramWordFit
+
+/-!
+# A common word-capacity threshold for the literal program
+
+The operand vector is fixed before choosing the input length. Identifying
+the rational bucket exponents identifies the whole live geometry, so the
+verified intermediate word bounds apply directly to this literal program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression LiveProgram CursorNetwork Filter RAMTape
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant)
+
+theorem paperGeometry_eq (hnumerator : D.numerator = (liveRatio u).num)
+ (hdenominator : D.denominator = (liveRatio u).den) (n : ℕ) :
+ D.geometry n = paperGeometry D.addressFactor (liveCapacity u) n := by
+ unfold geometry paperGeometry liveCapacity
+ rw [hnumerator,hdenominator]
+
+private theorem transport {k w : ℕ} (args : Fin k → InputOperand) {actual paper : Geometry}
+ (geom : actual = paper) (width : paper.w = w)
+ (fits : ∀ j, (InputOperandMachine.geometryOnly args j).Fits paper (2^w)) :
+ ∀ j, (InputOperandStartup.Expr args j).Fits actual (2^actual.w) := by
+ subst actual
+ subst w
+ exact fits
+
+attribute [local irreducible] Pieces.count rows LiveProgram.operand InputOperandMachine.geometryOnly PublicExpr.Fits
+
+theorem eventually_operandFits (hnumerator : D.numerator = (liveRatio u).num)
+ (hdenominator : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, D.OperandFits n := by
+ apply (eventually_operand_geometry_fits D.constants D.evaluator D.pair D.address_pos
+ (liveCapacity_polynomial u)).mono
+ intro n fits
+ exact transport D.operands (paperGeometry_eq D B u hnumerator hdenominator n) rfl fits
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramParameters.lean b/lean/OAI/Computability/VPVNP/FixedProgramParameters.lean
new file mode 100644
index 0000000000..2f8746a859
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramParameters.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.FixedProgramTailOrder
+import OAI.Computability.VPVNP.LiveLocalCountConditions
+
+/-!
+# Choosing the finite program's powers from a reader bound
+
+Choose the evaluator clock, advice, radius and cut powers before choosing
+the address multiplier. Enlarging that multiplier for the virtual pair
+layout preserves these bounds. The same rational bucket ratio is used by
+the compression simulation and the live site processor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression BurstRAM LiveProgram CursorNetwork CursorBounds
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (T : S.Templates)
+
+/-- Assemble the fixed program from the selected powers, scalar evaluator, pair table and bucket exponent. -/
+def ofPaperConstants (c : Constants) (E : UniversalMachine.Program) (O : PairTable)
+ (factor : ℕ) (hfactor : 1 ≤ factor) {z : ℝ} (ratio : Ratio z) : FixedProgramDiagonal.Program :=
+ ⟨c,E,O,factor,hfactor,ratio.num,ratio.den,ratio.less,0⟩
+
+/-- Clock, advice, counter and layout bounds used to realize the fixed program at a given length. -/
+structure Numerics (D : FixedProgramDiagonal.Program) (C : ℕ) (env : ℕ → ℕ) (ports n : ℕ) : Prop where
+ time : 2^(6*env n+23)*(D.counterWidth n+1)^4 ≤ 2^(D.chainHeight n)
+ space : 2240*(ports+1)*(env n+D.counterWidth n+1)^4 ≤ n^D.constants.radiusPower
+ raw : env n ≤ n^D.constants.prefixPower
+ advice : (D.geometry n).w + n^D.constants.prefixPower + T.denseCount n C*Nat.clog 2 (T.compressorLabelCount C n)
+ ≤ n^D.constants.advicePower
+ counters : 1 + T.denseCount n C*D.counterWidth n ≤ n^D.constants.deltaPower
+ layout : LiveEvaluatorTail.Layout D.evaluator.extra (n^D.constants.radiusPower) (D.geometry n).w
+ (n^D.constants.deltaPower)
+ hw : 4 ≤ (D.geometry n).w
+ hc : 2^(D.geometry n).d * (D.geometry n).H < 2^(D.geometry n).w
+ hR : 4*n ≤ 2^(D.geometry n).d
+ hZ : D.chainHeight n + 2*(D.geometry n).d ≤ D.counterWidth n
+ group : ∀ G : PairStages.Group, G.constants = D.constants → G.g = D.geometry n → G.evaluator = D.evaluator →
+ n^10000 ≤ G.clock → LocalCount.Conditions G (2^(D.geometry n).d) (D.geometry n).H
+
+set_option maxHeartbeats 1200000 in
+theorem select (C : ℕ) (u : PairExponents T.growthConstant) (E : UniversalMachine.Program)
+ (env : ℕ → ℕ) (henv : PolynomiallyBounded env) (ports : ℕ) :
+ ∃ c : Constants, c.circuitExponent = C ∧ c.motifLabels = Fintype.card T.Entry ∧
+ 2 ≤ c.chainPower ∧ ∃ N : ℕ, 1 ≤ N ∧ ∀ b ≥ N, ∀ O : PairTable,
+ ∀ᶠ n : ℕ in Filter.atTop, ∃ hb : 1 ≤ b,
+ Numerics T (ofPaperConstants c E O b hb (liveRatio u)) C env ports n := by
+ let P := fun n => 6*env n+23
+ let radius := fun n Z => 2240*(ports+1)*(env n+Z+1)^4
+ have hP : PolynomiallyBounded P := ((PolynomiallyBounded.const 6).mul henv).add (.const 23)
+ have hr (a : ℕ) : PolynomiallyBounded (fun n => radius n (2*n^a)) :=
+ (PolynomiallyBounded.const (2240*(ports+1))).mul
+ (((henv.add ((PolynomiallyBounded.const 2).mul (PolynomiallyBounded.id.pow a))).add (.const 1)).pow 4)
+ obtain ⟨a,da,d₁,d₂,r,b₀,ha,hb₀,H⟩ := LocalCount.eventually_paper_conditions u C (Fintype.card T.Entry)
+ radius hP henv hr E
+ let c : Constants := ⟨C,a,d₁,d₂,r,da,Fintype.card T.Entry⟩
+ let N := max b₀ (max S.laneBits 5)
+ refine ⟨c,rfl,rfl,ha,N,hb₀.trans (le_max_left ..),?_⟩
+ intro b hb O
+ have hb' : 1 ≤ b := hb₀.trans ((le_max_left ..).trans hb)
+ let D := ofPaperConstants c E O b hb' (liveRatio u)
+ filter_upwards [H 4 b ((le_max_left ..).trans hb),
+ eventually_numeric T u b a ((le_max_right ..).trans hb) (by omega)] with n H numeric
+ obtain ⟨time,space,raw,adv,cut,layout,groups⟩ := H
+ obtain ⟨hw,hc,hR,hZ,_,_⟩ := numeric
+ have labels : c.labels.eval (paperGeometry b (liveCapacity u) n) = T.denseCount n C :=
+ physicalLabelCount_eq D T rfl rfl
+ have card : T.denseCount n C = T.compressorLabelCount C n := JointLabelSystem.FixedRows.labelOrder_length T.Entry n C
+ rw [labels] at adv
+ have adv' : (D.geometry n).w + n^da + T.denseCount n C * Nat.clog 2 (T.compressorLabelCount C n) ≤ n^d₁ := by
+ rw [← card]
+ exact adv
+ rw [labels] at cut
+ exact ⟨hb',time,space,raw,adv',cut,layout,hw,hc,hR,hZ,groups⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramReaderData.lean b/lean/OAI/Computability/VPVNP/FixedProgramReaderData.lean
new file mode 100644
index 0000000000..8fa71c78a7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramReaderData.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.FixedProgramModelData
+import OAI.Computability.VPVNP.CompressorEvaluatorInput
+
+/-!
+# Tail obligations supplied by the literal scalar evaluator
+
+The choice of a monomial basis is part of the length-specific advice.
+Re-present the slice model in the order used by the two deterministic
+matrix readers. The same raw binary advice then works for every vector
+of exponents, with exact monomials on the required range.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression LabelEvaluator RAMTape Evaluator MatrixCallbacks LiveEvaluatorEncoding
+open BurstRAM LiveProgram
+
+local instance (p : Nat.Primes) : Fact p.val.Prime := ⟨p.property⟩
+/-- Enumerate the finite ground field of the selected slice. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+/-- View the ambient field as an algebra over the ground field through the slice embedding. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) :=
+ (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ {n C : ℕ} (hn : 2 ≤ n) {p : Nat.Primes}
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn C))
+ {P : Type} [DecidableEq P] [Fintype P] (ps : List (WeightedStep.Port P))
+ (hps : ps.Nodup) (hall : ∀ i, i ∈ ps) (frob label : FiniteRoutine (ReadPort P))
+
+/-- Present the selected slice in the canonical coordinates used by the scalar evaluator. -/
+noncomputable abbrev canonicalModel := M.withCanonicalPresentation (B.compressorCanonical hn C M)
+
+/-- Turn the encoded matrix readers and their resource bounds into scalar data for the canonical model. -/
+noncomputable def scalarDataOfReader (H : B.SliceReaderAdvice M frob label)
+ (hE : D.evaluator = MatrixCallbacks.program ps frob label)
+ (hraw : H.envelope ps ≤ n^D.constants.prefixPower)
+ (hadvice : (D.geometry n).w+n^D.constants.prefixPower+B.denseCount n C*Nat.clog 2 (B.compressorLabelCount C n)
+ ≤ n^D.constants.advicePower)
+ (hclock : 2^(6*H.envelope ps+23)*(D.counterWidth n+1)^4 ≤ 2^(D.chainHeight n))
+ (hspace : 2240*(Fintype.card (BinaryMachine.MachinePort (WeightedStep.Port P))+1)*(H.envelope ps+D.counterWidth n+1)^4
+ ≤ n^D.constants.radiusPower) :
+ D.ScalarData B hn (canonicalModel B hn M) := by
+ let data := H.binary ps
+ have run (xs : Fin (B.compressorLabelCount C n) → ℕ) :=
+ H.resources_and_value ps hps hall (D.exponentWords n xs) (2^(D.chainHeight n)) hclock
+ refine ⟨data, (H.binary_le ps).trans hraw, hadvice, ?_, ?_, ?_⟩
+ · intro xs
+ unfold initial
+ rw [hE]
+ exact (run xs).1
+ · intro xs time bs i
+ apply LiveEvaluatorRadius.fits_mono hspace
+ unfold initial
+ rw [hE]
+ exact (run xs).2.2.2 time bs i
+ · intro xs bound
+ rw [(canonicalModel B hn M).branchCount_mod _ xs bound]
+ have val (j) : (D.exponentWords n xs j).val = xs j := Nat.mod_eq_of_lt (bound j)
+ unfold initial
+ rw [hE]
+ have hv := (run xs).2.1
+ simp only [val] at hv
+ exact hv
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramRealization.lean b/lean/OAI/Computability/VPVNP/FixedProgramRealization.lean
new file mode 100644
index 0000000000..da06f0582d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramRealization.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.LiveCertificateAssembly
+import OAI.Computability.VPVNP.FixedProgramReaderData
+import OAI.Computability.VPVNP.FixedProgramParameters
+import OAI.Computability.VPVNP.FixedProgramOperandFits
+
+/-!
+# Realization at all admissible exceptional lengths
+
+Once a literal program and its powers have been chosen, take a common
+length threshold for its operand loader, its auxiliary coefficient counters,
+and its two native continuations. A prime and a model may now be given at
+that length. Use the canonical presentation computed by the reader to fill
+the scalar certificate. The same advice, field values and virtual paths are
+used on both halves of the chain.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression LiveProgram CursorNetwork LabelEvaluator Filter
+open RAMTape LiveProgram.LocalCount JointLabelSystem
+
+attribute [local irreducible] Pieces.count rows LiveProgram.operand InputOperandMachine.geometryOnly
+ PublicExpr.Fits OperandFits
+
+set_option maxHeartbeats 400000
+set_option exponentiation.threshold 10000
+
+/-- Classical equality on the bounded production labels used to assemble the native
+realization. -/
+noncomputable local instance realizationProductionDecidable (n C : ℕ) : DecidableEq (Production n C) := Classical.decEq _
+
+universe v
+variable {K : Type v} [Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant)
+
+theorem tagsFit (n : ℕ) : 21 ≤ 2^(D.geometry n).w := by
+ have w : 5 ≤ (D.geometry n).w := by
+ change 5 ≤ (CursorBounds.addressBits D.addressFactor n+10)^4
+ exact (by decide : 5 ≤ 10^4).trans (Nat.pow_le_pow_left (Nat.le_add_left ..) _)
+ exact (by decide : 21 ≤ 2^5).trans (Nat.pow_le_pow_right (by decide) w)
+
+theorem dispatchClock {n : ℕ} (hn : 2 ≤ n) : 44 ≤ n^10000 :=
+ (by decide : 44 ≤ 2^6).trans ((Nat.pow_le_pow_left hn 6).trans
+ (Nat.pow_le_pow_right (by omega : 0 < n) (by decide : 6 ≤ 10000)))
+
+/-- Native statements only on prepared groups at this one length. All
+objects come from the public virtual layout and the same scalar data. -/
+def NativeContinuations (C n : ℕ) : Prop :=
+ ∀ (hn : 2 ≤ n) (p : Nat.Primes) (M : Model p (B.compressorDegree n) (B.compressorEquations hn C))
+ (data : D.ScalarData B hn M)
+ (fit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ (V : D.VirtualPairs B u hn C)
+ (W : Conditions (D.executionGroup n (D.tagsFit n) (dispatchClock hn)) (2^(D.geometry n).d) (D.geometry n).H)
+ (cut : 1+B.denseCount n C*D.counterWidth n ≤ n^D.constants.deltaPower)
+ (image : LiveEvaluatorTail.Layout D.evaluator.extra (n^D.constants.radiusPower)
+ (D.geometry n).w (n^D.constants.deltaPower)),
+ pairObligation W heights deltas adviceSizes data.advice cut (increments data fit V) ∧
+ tailObligation W deltas adviceSizes data.advice cut image data.init
+
+/-- The readers and native continuations of a single fixed program supply
+the local certificates uniformly in length, prime and input model. -/
+theorem realizes_of_continuations (q C ports : ℕ) (env : ℕ → ℕ)
+ (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (zero : D.initialLiteral = 0) (hnumerator : D.numerator = (liveRatio u).num)
+ (hdenominator : D.denominator = (liveRatio u).den)
+ (hb : max S.laneBits 5 ≤ D.addressFactor)
+ (hB : max (max (D.constants.chainPower+1) (D.constants.chainPower+D.constants.deltaPower))
+ (max D.constants.advicePower (grammarCapacityPower C)) + 2 ≤ D.addressFactor)
+ (selected : ∀ᶠ n : ℕ in atTop, Numerics B D C env ports n ∧
+ ∀ (hn : 2 ≤ n) (p : Nat.Primes), (q ≠ 0 → p.val=q) →
+ (q=0 → p.val ≤ 2^B.compressorPrimeBits C n) →
+ ∀ M : Model p (B.compressorDegree n) (B.compressorEquations hn C),
+ Nonempty (D.ScalarData B hn (canonicalModel B hn M)))
+ (native : ∀ᶠ n : ℕ in atTop, D.NativeContinuations B u C n) : D.Realizes B q C := by
+ unfold Realizes
+ filter_upwards [D.eventually_operandFits B u hnumerator hdenominator,
+ D.eventually_virtualPairs B u C hnumerator hdenominator hb hB,selected,native] with n ops virtual selection routes
+ obtain ⟨sizes,scalar⟩ := selection
+ refine ⟨ops,?_⟩
+ intro hn p positive zeroChar M₀ fit
+ obtain ⟨M⟩ := M₀
+ obtain ⟨data⟩ := scalar hn p positive zeroChar M
+ obtain ⟨V⟩ := virtual hn
+ let G := D.executionGroup n (D.tagsFit n) (dispatchClock hn)
+ have W := sizes.group G rfl rfl rfl le_rfl
+ obtain ⟨pair,tail⟩ := routes hn p (canonicalModel B hn M) data fit V W sizes.counters sizes.layout
+ exact ⟨canonicalModel B hn M,⟨assembleLocalCertificate data fit V W hC hg sizes.counters sizes.layout
+ zero sizes.hc sizes.hR sizes.hZ pair tail⟩⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramRoutes.lean b/lean/OAI/Computability/VPVNP/FixedProgramRoutes.lean
new file mode 100644
index 0000000000..c586544547
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramRoutes.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.FixedProgramRealization
+import OAI.Computability.VPVNP.LiveVirtualPairContinuation
+import OAI.Computability.VPVNP.FixedProgramTailContinuation
+import OAI.Computability.VPVNP.FixedProgramTailCaps
+
+/-!
+# The two native routes of the fixed program
+
+The initialized tail, the remaining transitions and the non-evaluation
+routes are determined by the program itself. The pair's compressed run is
+entered only after the header, nomination and sparse-copy stages have
+actually been executed. At every sufficiently large length their resource
+bounds and the tail resource bounds hold for the same address multiplier.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression LiveProgram CursorNetwork LabelEvaluator Filter
+open LiveProgram.LocalCount LiveProgram.EvaluatorRoutes
+
+universe v
+variable {K : Type v} [Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant) (C : ℕ)
+ (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+
+/-- The native compressed pair table produces the concrete finite path and
+counter readback on each prepared input, within the actual live caps. -/
+def PairRuns (n : ℕ) : Prop :=
+ ∀ (hn : 2 ≤ n) (p : Nat.Primes) (M : Model p (B.compressorDegree n) (B.compressorEquations hn C))
+ (data : D.ScalarData B hn M)
+ (fit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ (V : D.VirtualPairs B u hn C)
+ (W : Conditions (D.executionGroup n (D.tagsFit n) (dispatchClock hn)) (2^(D.geometry n).d) (D.geometry n).H)
+ (P : PairStageConditions (D.executionGroup n (D.tagsFit n) (dispatchClock hn)) (2^(D.geometry n).d) (D.geometry n).H)
+ (cut : 1+B.denseCount n C*D.counterWidth n ≤ n^D.constants.deltaPower),
+ V.compressedCalls data fit W P hC hg cut
+
+/-- At any larger address multiplier, realizing the compressed table at
+one length implies both complete native continuation counts at that length.
+The threshold precedes the choice of the field model and its raw advice. -/
+theorem eventually_native_of_pairRuns (c : Constants) (E : UniversalMachine.Program)
+ (hc : c.circuitExponent = C) (hm : c.motifLabels = Fintype.card B.Entry) :
+ ∃ b₀ : ℕ, ∀ b ≥ b₀, ∀ (hb : 1 ≤ b) (O : PairTable),
+ let D := ofPaperConstants c E O b hb (liveRatio u)
+ ∀ᶠ n : ℕ in atTop, D.PairRuns B u C hc hm n → D.NativeContinuations B u C n := by
+ obtain ⟨b₁,h₁⟩ := eventually_pairStageConditions u c
+ obtain ⟨b₂,h₂⟩ := eventually_tailFits u c E
+ refine ⟨max b₁ b₂,?_⟩
+ intro b hbig hb O D
+ filter_upwards [h₁ b ((le_max_left ..).trans hbig),h₂ b ((le_max_right ..).trans hbig)] with n stages tails
+ intro runs hn p M data fit V W cut image
+ let G := D.executionGroup n (D.tagsFit n) (dispatchClock hn)
+ have geom : G.g = paperGeometry b (liveCapacity u) n := rfl
+ have P := stages G rfl geom le_rfl
+ have room : data.raw.length ≤ G.constants.prefixCapacity.eval G.g := by
+ rw [Constants.prefixCapacity,PublicExpr.eval_natPow]
+ exact data.rawLength
+ have F := tails G geom rfl rfl le_rfl data.raw.length room
+ exact ⟨V.pairObligation data fit W P hc hm cut (runs hn p M data fit V W P cut),
+ fixedTailObligation data W hc hm cut image F.fits F.geometry F.call F.ordinaryBudget F.initialBudget⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramSelection.lean b/lean/OAI/Computability/VPVNP/FixedProgramSelection.lean
new file mode 100644
index 0000000000..300e5ec008
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramSelection.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.FixedProgramParameters
+import OAI.Computability.VPVNP.FixedProgramReaderData
+import OAI.Computability.VPVNP.FiniteAlgebraEvaluator
+
+/-!
+# The actual scalar evaluator and the fixed live-program parameters
+
+The matrix readers are fixed controls on a fixed finite port type. Their
+per-model resource envelope determines the chain and advice powers. Only
+after choosing these powers is the address multiplier increased for the
+pair simulation, and only after that are a prime and a finite slice chosen.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+set_option maxRecDepth 10000
+
+open Compression BurstRAM LiveProgram LabelEvaluator RAMTape CursorNetwork
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (T : S.Templates)
+
+/-- Number of machine ports in the weighted scalar evaluator with the compressor readers installed. -/
+noncomputable def evaluatorPorts :=
+ Fintype.card (Evaluator.BinaryMachine.MachinePort (Evaluator.WeightedStep.Port CompressorReader.Ports))
+
+/-- Once the arithmetic bounds are known, every admissible slice has
+canonical scalar advice and a literal evaluator satisfying all the tail
+obligations on that very slice. -/
+theorem selection_of_readers (q C : ℕ) {P : Type} [DecidableEq P] [Fintype P]
+ (ps : List (Evaluator.WeightedStep.Port P)) (hps : ps.Nodup) (hall : ∀ j, j ∈ ps)
+ (frob label : FiniteRoutine (Evaluator.MatrixCallbacks.ReadPort P)) (E : UniversalMachine.Program)
+ (hE : E = Evaluator.MatrixCallbacks.program ps frob label) (qenv : ℕ → ℕ) (henv : PolynomiallyBounded qenv)
+ (readers : ∀ n, ∀ (hn : 2 ≤ n) (p : Nat.Primes), (q ≠ 0 → p.val = q) →
+ (q = 0 → p.val ≤ 2^T.compressorPrimeBits C n) → ∀ M : Model p (T.compressorDegree n) (T.compressorEquations hn C),
+ ∃ H : T.SliceReaderAdvice M frob label, H.envelope ps ≤ qenv n) :
+ let u := pairExponents T
+ let ports := Fintype.card (Evaluator.BinaryMachine.MachinePort (Evaluator.WeightedStep.Port P))
+ ∃ c : Constants, c.circuitExponent = C ∧ c.motifLabels = Fintype.card T.Entry ∧
+ 2 ≤ c.chainPower ∧ ∃ b₀ : ℕ, 1 ≤ b₀ ∧ ∀ b ≥ b₀, ∀ O : PairTable,
+ ∀ᶠ n : ℕ in Filter.atTop, ∃ hb : 1 ≤ b,
+ let D := ofPaperConstants c E O b hb (liveRatio u)
+ Numerics T D C qenv ports n ∧
+ ∀ (hn : 2 ≤ n) (p : Nat.Primes), (q ≠ 0 → p.val = q) → (q = 0 → p.val ≤ 2^T.compressorPrimeBits C n) →
+ ∀ M : Model p (T.compressorDegree n) (T.compressorEquations hn C),
+ Nonempty (D.ScalarData T hn (canonicalModel T hn M)) := by
+ intro u ports
+ obtain ⟨c,hC,hm,ha,b₀,hb₀,geometry⟩ := select T C u E qenv henv ports
+ refine ⟨c,hC,hm,ha,b₀,hb₀,?_⟩
+ intro b hb O
+ filter_upwards [geometry b hb O] with n h
+ obtain ⟨hpos,G⟩ := h
+ let D := ofPaperConstants c E O b hpos (liveRatio u)
+ refine ⟨hpos,G,?_⟩
+ intro hn p hp hbits M
+ obtain ⟨H,hH⟩ := readers n hn p hp hbits M
+ have hclock := (Nat.mul_le_mul_right ((D.counterWidth n+1)^4)
+ (Nat.pow_le_pow_right (by decide : 0 < 2) (show 6*H.envelope ps+23 ≤ 6*qenv n+23 by omega))).trans G.time
+ have hspace := (Nat.mul_le_mul_left (2240*(ports+1))
+ (Nat.pow_le_pow_left (show H.envelope ps+D.counterWidth n+1 ≤ qenv n+D.counterWidth n+1 by omega) 4)).trans G.space
+ exact ⟨scalarDataOfReader D T hn M ps hps hall frob label H hE (hH.trans G.raw) G.advice hclock hspace⟩
+
+theorem select_scalar (q C : ℕ) :
+ let u := pairExponents T
+ ∃ (env : ℕ → ℕ) (c : Constants), c.circuitExponent = C ∧ c.motifLabels = Fintype.card T.Entry ∧
+ 2 ≤ c.chainPower ∧ ∃ b₀ : ℕ, 1 ≤ b₀ ∧ ∀ b ≥ b₀, ∀ O : PairTable,
+ ∀ᶠ n : ℕ in Filter.atTop, ∃ hb : 1 ≤ b,
+ let D := ofPaperConstants c CompressorReader.program O b hb (liveRatio u)
+ Numerics T D C env evaluatorPorts n ∧
+ ∀ (hn : 2 ≤ n) (p : Nat.Primes), (q ≠ 0 → p.val = q) → (q = 0 → p.val ≤ 2^T.compressorPrimeBits C n) →
+ ∀ M : Model p (T.compressorDegree n) (T.compressorEquations hn C),
+ Nonempty (D.ScalarData T hn (canonicalModel T hn M)) := by
+ intro u
+ obtain ⟨env,henv,readers⟩ := T.exists_compressor_reader_envelope CompressorReader.fields q C
+ refine ⟨env,?_⟩
+ exact selection_of_readers T q C CompressorReader.fields CompressorReader.fields_nodup
+ CompressorReader.mem_fields (CompressorReader.read true) (CompressorReader.read false)
+ CompressorReader.program rfl env henv readers
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramTailCaps.lean b/lean/OAI/Computability/VPVNP/FixedProgramTailCaps.lean
new file mode 100644
index 0000000000..b755908f9e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramTailCaps.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.LiveFirstTailBudget
+import OAI.Computability.VPVNP.LiveLayoutWordFit
+
+/-!
+# Simultaneous size bounds for every group of the fixed evaluator
+
+The address exponent is chosen after the evaluator and the label geometry.
+For every larger fixed exponent, one eventual length threshold works for all
+advice prefixes in the allocated region and for both endpoint routes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM PairStages CursorBounds CursorNetwork Filter LiveEvaluatorTailCost
+open OutsideTailStages OutsideTailCount
+
+/-- The evaluator tail fits the word geometry, the per-call probe allowance, and the total
+budgets for its initial and ordinary groups. -/
+structure TailFits (G : Group) (raw : ℕ) : Prop where
+ fits : limit G < 2^G.w
+ geometry : GeometryFit G (radius G)
+ call : callBound G.w ≤ G.g.H
+ ordinaryBudget : LiveHeaderSchedule.costBound (Header.sizes G.constants G.g)+4+2*routeCost G.w (radius G)+transitionCost (radius G) ≤ 2^G.g.d*G.g.H
+ initialBudget : FirstTailBudget.cost G raw ≤ 2^G.g.d*G.g.H
+
+private theorem ordinary_group_cost (u : Parameters) :
+ 2*routeCost u.wordWidth u.radius+transitionCost u.radius ≤ groupBound u false false false := by
+ have hwords : LiveEvaluatorEncoding.fieldWords u.radius = u.configWords := by
+ unfold LiveEvaluatorEncoding.fieldWords Parameters.configWords; omega
+ have hroute : routeCost u.wordWidth u.radius = 4+(u.wordWidth+4)*u.configWords := by
+ rw [routeCost,hwords,Nat.mul_comm]
+ have htrans : transitionCost u.radius = u.transitionCost+u.configWords := by
+ unfold transitionCost Parameters.transitionCost Parameters.configWords LiveEvaluatorRAM.Schedule.calls; omega
+ rw [hroute,htrans,← groupBudget]
+ simp only [firstBudget,lastBudget,Bool.false_eq_true,ite_false]
+ omega
+
+private theorem ordinary_cost_le (G : Group) (raw : ℕ) :
+ LiveHeaderSchedule.costBound (Header.sizes G.constants G.g)+4+2*routeCost G.w (radius G)+transitionCost (radius G) ≤
+ OutsideBudget.actualBound G.constants G.g raw false false false := by
+ have h := ordinary_group_cost (params G raw)
+ change 2*routeCost G.w (radius G)+transitionCost (radius G) ≤ groupBound (params G raw) false false false at h
+ change _ ≤ LiveHeaderSchedule.costBound (Header.sizes G.constants G.g)+8+4*(G.constants.labels.eval G.g+1)+100+
+ 16*(OutsideBudget.auxWords (Header.sizes G.constants G.g) (G.constants.labels.eval G.g)+1)+
+ 7*(G.constants.labels.eval G.g*G.constants.Z.eval G.g+1)+groupBound (params G raw) false false false
+ omega
+
+set_option maxHeartbeats 800000 in
+/-- The threshold in the input length is uniform in the route, advice and
+model. The clock may be any common group clock above the live n^10000 cap. -/
+theorem eventually_tailFits {C : ℕ} (u : PairExponents C) (c : Constants) (E : UniversalMachine.Program) :
+ ∃ b₀, ∀ b ≥ b₀, ∀ᶠ n : ℕ in atTop, ∀ G : Group,
+ G.g = paperGeometry b (liveCapacity u) n → G.constants = c → G.evaluator = E → n^10000 ≤ G.clock →
+ ∀ raw, raw ≤ G.constants.prefixCapacity.eval G.g → TailFits G raw := by
+ obtain ⟨b₀,bounds⟩ := OutsideTraces.eventually_all_caps u c E
+ refine ⟨max 1 b₀, fun b hb => ?_⟩
+ have hb₁ : 1 ≤ b := (le_max_left ..).trans hb
+ have hshadow := ((Layout.shadow_sitePowers c).fits hb₁ (liveCapacity_polynomial u)).2
+ let e := PublicExpr.lit (9*E.extra+2)
+ have hs : e.SitePowers := trivial
+ have hrows := (hs.fits hb₁ (liveCapacity_polynomial u)).2
+ filter_upwards [bounds b ((le_max_right ..).trans hb),hshadow,hrows] with n bound shadow row
+ intro G hg hc hE hclock raw hraw
+ have fits : limit G < 2^G.w := by
+ change (Layout.shadow G.constants).eval G.g < 2^G.g.w
+ rw [hc,hg]; exact shadow.1
+ have table : 9*G.evaluator.extra+2 < 2^G.w := by
+ change 9*G.evaluator.extra+2 < 2^G.g.w
+ rw [hE,hg]; exact row.1
+ have hw : 2 ≤ G.w := by
+ by_contra! h
+ have small := Nat.pow_le_pow_right (n := 2) (by decide) (by omega : G.w ≤ 1)
+ have large := G.tagFit
+ rw [pow_one] at small; omega
+ obtain ⟨first, per, work⟩ := bound G hg hc hE raw true false false hraw
+ have later := (bound G hg hc hE raw false false false hraw).1
+ have clockFit : instructionBound G ≤ G.clock := (le_max_right ..).trans ((le_max_right ..).trans (work.trans hclock))
+ have gather : 8*G.w+67 ≤ G.clock := (le_max_left ..).trans ((le_max_right ..).trans clockFit)
+ have terminal : LiveEvaluatorRAM.Schedule.callFuel G.evaluator+47 ≤ G.clock :=
+ (le_max_right ..).trans ((le_max_right ..).trans clockFit)
+ have tick : LiveEvaluatorRAM.Schedule.callFuel G.evaluator ≤ G.clockAt Stage.transition := by
+ have len : (LiveStageLink.dispatchEvents G.addr Stage.transition).length = 44 := rfl
+ unfold Group.clockAt; rw [len]; omega
+ have positive : 0 < G.g.H := (by decide : 0 < 26).trans_le ((le_max_left ..).trans per)
+ have headroom : processorCount b n ≤ 2^G.g.d*G.g.H := by rw [hg] at positive ⊢; exact Nat.le_mul_of_pos_right _ positive
+ exact ⟨fits,geometryFit G fits hw (by omega) (by omega) gather tick,(le_max_right ..).trans per,
+ (ordinary_cost_le G raw).trans (later.le.trans headroom),
+ (FirstTailBudget.cost_le_actualBound G raw).trans (first.le.trans headroom)⟩
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramTailContinuation.lean b/lean/OAI/Computability/VPVNP/FixedProgramTailContinuation.lean
new file mode 100644
index 0000000000..d4bca81d32
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramTailContinuation.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.FixedProgramTailInitialization
+import OAI.Computability.VPVNP.LiveTailContinuation
+
+/-!
+# The fixed diagonal program realizes its model's evaluator half
+
+This identifies the physical table's continuation with the certificate's
+initial-code function, using the actual model advice, row permutation and
+integer counter widths. The program geometry fixes the remaining dimensions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression LiveProgram LiveEvaluatorEncoding LabelEvaluator JointLabelSystem
+open EvaluatorRoutes LocalCount
+open OutsideTailStages OutsideTailCount
+open scoped Fin.CommRing
+
+private theorem transportTail {G : PairStages.Group} {S H t t' z z' M M' Δ a : ℕ}
+ (W : Conditions G S H) (hd : Δ = (profile G).delta) (ha : a = (profile G).advice)
+ (ht : t = t') (hz : z = z') (hM : M = M')
+ (actualAdvice : CutSchedule.Bits (profile G).advice) (modelAdvice : CutSchedule.Bits a)
+ (advice : HEq actualAdvice modelAdvice)
+ (actualFit : 1+t*z ≤ (profile G).delta) (modelFit : 1+t'*z' ≤ Δ)
+ (actualLayout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w (profile G).delta)
+ (modelLayout : LiveEvaluatorTail.Layout G.evaluator.extra M' G.w Δ)
+ (actualInit : (Fin t → ℕ) → Code G.evaluator.extra M) (modelInit : (Fin t' → ℕ) → Code G.evaluator.extra M')
+ (initial : HEq actualInit modelInit) (result : TailContinuation W actualAdvice actualFit actualLayout actualInit) :
+ tailObligation W hd ha modelAdvice modelFit modelLayout modelInit := by
+ subst Δ; subst a; subst t'; subst z'; subst M'
+ rw [eq_of_heq advice, eq_of_heq initial] at result
+ exact result
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} {D : Program} {B : S.Templates} {n C : ℕ}
+variable {hn : 2 ≤ n} {p : Nat.Primes} {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+variable (data : D.ScalarData B hn M) {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+local notation "G" => D.executionGroup n ht hf
+
+set_option maxHeartbeats 800000 in
+/-- Native realization used by `assembleLocalCertificate`. The model
+provides the raw input, its exact ordering, and the occupied initial tape
+interval. Only the numerical caps on the common table enter separately. -/
+theorem fixedTailObligation
+ (W : Conditions G (2^(D.geometry n).d) (D.geometry n).H)
+ (hC : D.constants.circuitExponent = C) (hm : D.constants.motifLabels = Fintype.card B.Entry)
+ (fit : 1+B.denseCount n C*D.counterWidth n ≤ n^D.constants.deltaPower)
+ (layout : LiveEvaluatorTail.Layout D.evaluator.extra (n^D.constants.radiusPower) (D.geometry n).w (n^D.constants.deltaPower))
+ (fits : limit G < 2^(D.geometry n).w) (geom : GeometryFit G (radius G)) (call : callBound (D.geometry n).w ≤ (D.geometry n).H)
+ (ordinaryBudget : LiveHeaderSchedule.costBound (sizes G)+4+2*routeCost (D.geometry n).w (radius G)+transitionCost (radius G) ≤
+ 2^(D.geometry n).d*(D.geometry n).H)
+ (initialBudget : LiveHeaderSchedule.costBound (sizes G)+4+8+packWork (params G data.raw.length)+inputWork (params G data.raw.length)+
+ routeCost (D.geometry n).w (radius G)+transitionCost (radius G) ≤ 2^(D.geometry n).d*(D.geometry n).H) :
+ tailObligation W deltas adviceSizes data.advice fit layout data.init := by
+ have count : FirstTailHeader.labelCount G = B.denseCount n C := physicalLabelCount_eq D B hC hm
+ have formalCount := count.trans (FixedRows.labelOrder_length B.Entry n C)
+ have width : FirstTailHeader.exponentWidth G = D.counterWidth n := physicalCounterWidth_eq D
+ have rad : radius G = n^D.constants.radiusPower := physicalRadius_eq D
+ have delta : n^D.constants.deltaPower = (sizes G).delta := deltas
+ have adviceSize : n^D.constants.advicePower = (sizes G).advice := adviceSizes
+ have prefixCap : D.constants.prefixCapacity.eval (D.geometry n) = n^D.constants.prefixPower := by
+ rw [Constants.prefixCapacity, PublicExpr.eval_natPow]; rfl
+ let order := nativeLabelOrder D B count
+ let values := nativeOrdinalWords D B count
+ have cut : 1+FirstTailHeader.labelCount G*FirstTailHeader.exponentWidth G ≤ (sizes G).delta := by rwa [count,width,← delta]
+ have image : LiveEvaluatorTail.Layout D.evaluator.extra (radius G) (D.geometry n).w (sizes G).delta := by rwa [rad,← delta]
+ have cap : (D.geometry n).w+D.constants.prefixCapacity.eval (D.geometry n)+FirstTailHeader.labelCount G*Nat.clog 2 (FirstTailHeader.labelCount G)
+ ≤ (sizes G).advice := by
+ rw [prefixCap, ← adviceSize, show Nat.clog 2 (FirstTailHeader.labelCount G) = Nat.clog 2 (B.compressorLabelCount C n) from
+ congrArg (Nat.clog 2) formalCount, count]; exact data.adviceSpace
+ have room : D.evaluator.extra ≠ 0 → data.raw.length+(2*(FirstTailHeader.labelCount G*FirstTailHeader.exponentWidth G)+
+ 6*FirstTailHeader.exponentWidth G+4) ≤ radius G+1 := by
+ rw [formalCount,width,rad]; exact data.initialRoom D B
+ let adv := Advice.adviceTape (D.geometry n).w (D.constants.prefixCapacity.eval (D.geometry n)) (sizes G).advice data.raw values
+ have tape : HEq adv data.advice := by
+ dsimp only [adv]
+ rw [prefixCap,← adviceSize]
+ exact heq_of_eq (nativeAdvice_eq D B count data.raw)
+ have actual := tailContinuation G W fits geom cut image data.raw order values (fun _ => rfl) cap
+ (prefixCap ▸ data.rawLength) room call ordinaryBudget initialBudget
+ exact transportTail W delta adviceSize count width rad adv data.advice tape cut fit image layout _ data.init
+ (midpointInitial_heq D B count data (ht := ht) (hf := hf)) actual
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramTailInitialization.lean b/lean/OAI/Computability/VPVNP/FixedProgramTailInitialization.lean
new file mode 100644
index 0000000000..904b80ad75
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramTailInitialization.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.FixedProgramTailOrder
+import OAI.Computability.VPVNP.LiveCertificateAssembly
+import OAI.Computability.VPVNP.LiveFirstTailPhysicalCount
+
+/-!
+# The fixed diagonal program's native initialization function
+
+The scalar evaluator and the physical midpoint store each exponent in the
+same finite word width. Their complete initialization functions agree on
+arbitrary natural inputs, including inputs reduced modulo that width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression LiveProgram LiveEvaluatorEncoding JointLabelSystem
+open scoped Fin.CommRing
+
+open private runtime_congr from OAI.Computability.VPVNP.FixedProgramTailOrder
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (D : Program) (B : S.Templates)
+variable {n C : ℕ} (denseCount : physicalLabelCount D (n := n) = B.denseCount n C)
+
+/-- Both ordinal maps select the same input coordinate, even when the
+natural number supplied there requires reduction to the exponent width. -/
+theorem nativeRuntimeNat_eq (xs : Fin (physicalLabelCount D (n := n)) → ℕ) :
+ EvaluatorProgramRawInput.runtime (fun a =>
+ Fin.ofNat (2^(physicalCounterWidth D (n := n))) (xs ((nativeLabelOrder D B denseCount).symm a))) =
+ EvaluatorProgramRawInput.runtime (D.exponentWords n (B.formalExponents (xs ∘ (finCongr denseCount).symm))) := by
+ let ht := denseCount.trans (FixedRows.labelOrder_length B.Entry n C)
+ apply runtime_congr ht (physicalCounterWidth_eq D)
+ intro j
+ let a := (nativeLabelOrder D B denseCount).symm j
+ change xs a % (2^(physicalCounterWidth D (n := n))) = xs a % (2^D.counterWidth n)
+ rw [physicalCounterWidth_eq]
+
+private theorem function_heq {a b r s extra : ℕ} (count : a=b) (radius : r=s)
+ (f : (Fin a → ℕ) → Code extra r) (g : (Fin b → ℕ) → Code extra s)
+ (point : ∀ xs, HEq (f xs) (g (xs ∘ (finCongr count).symm))) : HEq f g := by
+ subst b
+ subst s
+ exact heq_of_eq (funext fun xs => eq_of_heq (point xs))
+
+variable {hn : 2 ≤ n} {p : Nat.Primes}
+variable {model : LabelEvaluator.Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+variable (data : D.ScalarData B hn model)
+
+/-- The initializer of the physical tail continuation is the initializer
+of the scalar model, with only the two equal index sizes transported. -/
+theorem midpointInitial_heq {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000} :
+ HEq (EvaluatorRoutes.midpointInitial (D.executionGroup n ht hf) data.raw (nativeLabelOrder D B denseCount))
+ data.init := by
+ apply function_heq denseCount (physicalRadius_eq D (n := n))
+ intro xs
+ unfold EvaluatorRoutes.midpointInitial ScalarData.init initial
+ change HEq (LiveEvaluatorTail.initialCode (D.constants.radius.eval (D.geometry n))
+ (UniversalMachine.initial D.evaluator (data.raw ++ EvaluatorProgramRawInput.runtime
+ (fun a => Fin.ofNat (2^(physicalCounterWidth D (n := n))) (xs ((nativeLabelOrder D B denseCount).symm a)))))) _
+ rw [nativeRuntimeNat_eq,physicalRadius_eq]
+ rfl
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FixedProgramTailOrder.lean b/lean/OAI/Computability/VPVNP/FixedProgramTailOrder.lean
new file mode 100644
index 0000000000..3f2416d773
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FixedProgramTailOrder.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.FixedProgramModelData
+
+/-!
+# The model's label order on the native evaluator input
+
+The first half stores productions first and motif variables second. The model's
+advice specifies their positions in the joint label order. The native ordinal
+words and the reindexed runtime exponent field are exactly the words of the
+fixed diagonal program, including the length-dependent width of each counter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression LiveProgram LiveEvaluatorEncoding JointLabelSystem
+open scoped Fin.CommRing
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (D : Program) (B : S.Templates)
+variable {n C : ℕ}
+
+/-- Number of dense exponent coordinates in the physical group at this input length. -/
+abbrev physicalLabelCount := D.constants.labels.eval (D.geometry n)
+/-- Number of bits allocated to each exponent counter in the physical group. -/
+abbrev physicalCounterWidth := D.constants.Z.eval (D.geometry n)
+
+theorem physicalLabelCount_eq (exponent : D.constants.circuitExponent = C)
+ (motifs : D.constants.motifLabels = Fintype.card B.Entry) :
+ physicalLabelCount D (n := n) = B.denseCount n C := by
+ change D.constants.grammarLabels.eval (D.geometry n) + D.constants.motifLabels = _
+ rw [D.constants.grammarLabels_eq, exponent, motifs]; rfl
+
+theorem physicalCounterWidth_eq : physicalCounterWidth D (n := n) = D.counterWidth n := by
+ simp only [physicalCounterWidth,Constants.Z,Constants.height,eval_mul,PublicExpr.eval_natPow]
+ rfl
+
+theorem physicalRadius_eq : D.constants.radius.eval (D.geometry n) = n^D.constants.radiusPower := by
+ rw [Constants.radius, PublicExpr.eval_natPow]; rfl
+
+variable (denseCount : physicalLabelCount D (n := n) = B.denseCount n C)
+
+/-- The native scatter has a single index type, whereas the model names
+both the dense and the formal label count. Their equality transports only
+the bounds of the indices. The permutation itself is the model's one. -/
+noncomputable def nativeLabelOrder : Fin (physicalLabelCount D (n := n)) ≃ Fin (physicalLabelCount D (n := n)) :=
+ (finCongr denseCount).trans ((FixedRows.labelOrder B.Entry n C).trans
+ (finCongr (denseCount.trans (FixedRows.labelOrder_length B.Entry n C))).symm)
+
+/-- Encode the evaluator ordinal of each physical label as a binary word in the advice
+permutation. -/
+noncomputable def nativeOrdinalWords (i : Fin (physicalLabelCount D (n := n))) :
+ Word (Nat.clog 2 (physicalLabelCount D (n := n))) :=
+ ⟨(nativeLabelOrder D B denseCount i).val,
+ (nativeLabelOrder D B denseCount i).isLt.trans_le (Nat.le_pow_clog (by decide) _)⟩
+
+theorem nativeOrdinal_value (i : Fin (physicalLabelCount D (n := n))) :
+ (nativeOrdinalWords D B denseCount i).val = (orderWord B n C (i.cast denseCount)).val := rfl
+
+private theorem tape_congr {a b za zb : ℕ} (ht : a=b) (hz : za=zb)
+ (x : Fin a → Word za) (y : Fin b → Word zb) (he : ∀ j, (x j).val = (y (j.cast ht)).val)
+ (w cap len : ℕ) (raw : List Bool) : Advice.adviceTape w cap len raw x = Advice.adviceTape w cap len raw y := by
+ subst b; subst zb
+ have eq : x=y := funext fun j => Fin.ext (he j)
+ rw [eq]
+
+/-- The literal native advice tape is the diagonal program's distributed advice. -/
+theorem nativeAdvice_eq (raw : List Bool) :
+ Advice.adviceTape (D.geometry n).w (n^D.constants.prefixPower) (n^D.constants.advicePower)
+ raw (nativeOrdinalWords D B denseCount) = D.distributedAdvice B n C raw :=
+ tape_congr denseCount (congrArg (Nat.clog 2) (denseCount.trans (FixedRows.labelOrder_length B.Entry n C)))
+ _ _ (nativeOrdinal_value D B denseCount) _ _ _ _
+
+private theorem runtime_congr {a b za zb : ℕ} (ht : a=b) (hz : za=zb)
+ (x : Fin a → Word za) (y : Fin b → Word zb) (he : ∀ j, (x j).val = (y (j.cast ht)).val) :
+ EvaluatorProgramRawInput.runtime x = EvaluatorProgramRawInput.runtime y := by
+ subst b; subst zb
+ have eq : x=y := funext fun j => Fin.ext (he j)
+ rw [eq]
+
+/-- Reading the reindexed exponent field produces the same complete binary
+input as `Program.initial` on the model's dense counter values. -/
+theorem nativeRuntime_eq (dense : Fin (physicalLabelCount D (n := n)) → Word (physicalCounterWidth D (n := n))) :
+ EvaluatorProgramRawInput.runtime (dense ∘ (nativeLabelOrder D B denseCount).symm) =
+ EvaluatorProgramRawInput.runtime (D.exponentWords n (B.formalExponents
+ (fun j => (dense ((finCongr denseCount).symm j)).val))) := by
+ let hf := denseCount.trans (FixedRows.labelOrder_length B.Entry n C)
+ apply runtime_congr hf (physicalCounterWidth_eq D)
+ intro j
+ let i := (nativeLabelOrder D B denseCount).symm j
+ change (dense i).val = (dense i).val % (2 ^ D.counterWidth n)
+ apply (Nat.mod_eq_of_lt _).symm
+ exact (physicalCounterWidth_eq D (n := n)) ▸ (dense i).isLt
+
+variable {hn : 2 ≤ n} {p : Nat.Primes} {model : LabelEvaluator.Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+variable (data : D.ScalarData B hn model)
+
+/-- Exact initial state used by the contraction after the middle exponent cut. -/
+theorem nativeInitialCode_eq (dense : Fin (physicalLabelCount D (n := n)) → Word (physicalCounterWidth D (n := n))) :
+ LiveEvaluatorTail.initialCode (n^D.constants.radiusPower) (UniversalMachine.initial D.evaluator
+ (data.raw ++ EvaluatorProgramRawInput.runtime (dense ∘ (nativeLabelOrder D B denseCount).symm))) =
+ data.init (fun j => (dense ((finCongr denseCount).symm j)).val) := by
+ rw [nativeRuntime_eq]; rfl
+
+/-- A nonempty evaluator has a nonblank tape cell for each input bit. Its
+bounded initial configuration therefore fits the whole input in the right
+half of the physical window. -/
+theorem inputLength_of_fits (p : UniversalMachine.Program) (raw : List Bool) (R : ℕ)
+ (running : p.extra ≠ 0) (fit : StateFits R (EvaluatorTail.canonical (UniversalMachine.initial p raw))) :
+ raw.length ≤ R+1 := by
+ have state : (UniversalMachine.initial p raw).state.val = 2 := by simp [UniversalMachine.initial, running]
+ rw [EvaluatorTail.canonical, state, ite_eq_right (by decide), ite_eq_right (by decide)] at fit
+ have tape := fit.2.1
+ by_contra! h
+ have b := tape ((R+1 : ℕ) : ℤ) (.inr (by omega))
+ change (Turing.Tape.mk' _ _).nth ((R+1 : ℕ) : ℤ) = 0 at b
+ rw [Turing.Tape.mk'_nth_nat, Turing.ListBlank.nth_mk, List.getI_eq_getElem?_getD,
+ List.getElem?_map,List.getElem?_eq_getElem h] at b
+ cases hbit : raw[R+1] <;> simp [hbit] at b
+
+/-- Derive midpoint input space from the verified physical evaluator histories. -/
+theorem ScalarData.initialRoom (running : D.evaluator.extra ≠ 0) :
+ data.raw.length + (2*(B.compressorLabelCount C n*D.counterWidth n)+6*D.counterWidth n+4) ≤
+ n^D.constants.radiusPower+1 := by
+ let e := D.exponentWords n (fun _ : Fin (B.compressorLabelCount C n) => 0)
+ have space := data.space (fun _ => 0) 0 Fin.elim0 0
+ rw [EvaluatorTail.history_zero] at space
+ have bound := inputLength_of_fits D.evaluator (data.raw ++ EvaluatorProgramRawInput.runtime e)
+ _ running space
+ simpa only [List.length_append,EvaluatorProgramRawInput.runtime_length] using bound
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FlatRectangle.lean b/lean/OAI/Computability/VPVNP/FlatRectangle.lean
new file mode 100644
index 0000000000..448608e2d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FlatRectangle.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.CATZeroEquality
+import OAI.Computability.VPVNP.FlatTriangleVariation
+import OAI.Computability.VPVNP.GrassmannGeometry
+
+/-!
+# Interpolating the sides of a flat rectangle
+
+A four-point configuration with the distances of a Euclidean rectangle
+extends across each pair of parallel sides with exactly the Euclidean
+cross distances. The proof uses the midpoint inequality on a saturated
+diagonal and the first variation of squared distance to exchange the two
+sides of a flat triangle. This gives the rectangle-filling step in
+Sections 4.2 and 5.4 directly from the squared CAT(0) segment inequality.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {X : Type*} [MetricSpace X]
+
+private theorem comparison_lower {a b c z : X} (h : HasCATZeroSegments X) {s : ℝ}
+ (hs : 0 ≤ s) (haz : dist a z = s * dist a b) (hbz : dist b z = (1 - s) * dist a b)
+ (hflat : ∀ t : Set.Icc (0 : ℝ) 1, dist b (catPoint h a c t) ^ 2 =
+ (1 - t.val) * dist b a ^ 2 + t.val * dist b c ^ 2 - t.val * (1 - t.val) * dist a c ^ 2) :
+ (1 - s) * dist c a ^ 2 + s * dist c b ^ 2 - s * (1 - s) * dist a b ^ 2 ≤ dist c z ^ 2 := by
+ rcases eq_or_lt_of_le hs with rfl | hs
+ · have : a = z := dist_eq_zero.mp (by simpa using haz)
+ simp [this]
+ rcases eq_or_lt_of_le (dist_nonneg (x := a) (y := b)) with hL | hL
+ · have hab := dist_eq_zero.mp hL.symm
+ have haz' := dist_eq_zero.mp (by simpa [hL.symm] using haz)
+ subst b
+ subst z
+ simp
+ linarith
+ let L := dist a b
+ let H := dist a c ^ 2
+ let k := dist b c ^ 2 - L ^ 2 - H
+ let k' := dist z c ^ 2 - (s * L) ^ 2 - H
+ have hv : s * k ≤ k' := flatTriangle_firstVariation (L := L) (H2 := H) hL hs (by
+ intro t ht ht'
+ let u : Set.Icc (0 : ℝ) 1 := ⟨t, ht.le, ht'⟩
+ let p := catPoint h a c u
+ refine ⟨dist b p, dist z p, dist_nonneg, dist_nonneg, ?_, ?_, ?_⟩
+ · have he := hflat u
+ rw [dist_comm b a] at he
+ dsimp only [L, k, H, p, u] at *
+ linarith only [he]
+ · have he := catPoint_bound h a c u z
+ rw [dist_comm z a, haz] at he
+ dsimp only [L, k', H, p, u] at *
+ linarith only [he]
+ · simpa only [hbz, L] using dist_triangle b z p)
+ rw [dist_comm c z, dist_comm c b, dist_comm c a]
+ dsimp only [k, k', L, H] at hv
+ linarith only [hv]
+
+private theorem diagonal_flat (h : HasCATZeroSegments X) (a b c d : X)
+ (heq : dist a c ^ 2 + dist b d ^ 2 =
+ dist a b ^ 2 + dist b c ^ 2 + dist c d ^ 2 + dist d a ^ 2)
+ (t : Set.Icc (0 : ℝ) 1) :
+ dist b (catPoint h a c t) ^ 2 =
+ (1 - t.val) * dist b a ^ 2 + t.val * dist b c ^ 2 - t.val * (1 - t.val) * dist a c ^ 2 := by
+ let u : Set.Icc (0 : ℝ) 1 := ⟨1 / 2, by norm_num, by norm_num⟩
+ let p := catPoint h a c u
+ have hb := catPoint_bound h a c u b
+ have hd := catPoint_bound h a c u d
+ have htri : dist b d ^ 2 ≤ (dist b p + dist d p) ^ 2 := by
+ apply (sq_le_sq₀ dist_nonneg (add_nonneg dist_nonneg dist_nonneg)).mpr
+ simpa only [dist_comm p d] using dist_triangle b p d
+ have hmid : dist b p ^ 2 = (1 - u.val) * dist b a ^ 2 + u.val * dist b c ^ 2 -
+ u.val * (1 - u.val) * dist a c ^ 2 := by
+ rw [dist_comm c d, dist_comm a b] at heq
+ dsimp only [p, u] at *
+ nlinarith only [heq, hb, hd, htri, sq_nonneg (dist b (catPoint h a c u) - dist d (catPoint h a c u))]
+ exact catPoint_bound_eq_of_interior h a c b u (by norm_num [u]) (by norm_num [u]) hmid t
+
+private theorem rectangle_vertex (h : HasCATZeroSegments X) {a b d c : X} {L W : ℝ}
+ (hab : dist a b ^ 2 = L) (hdc : dist d c ^ 2 = L)
+ (had : dist a d ^ 2 = W) (hbc : dist b c ^ 2 = W)
+ (hac : dist a c ^ 2 = L + W) (hbd : dist b d ^ 2 = L + W)
+ (s : Set.Icc (0 : ℝ) 1) :
+ dist c (catPoint h a b s) ^ 2 = L * (1 - s.val) ^ 2 + W ∧
+ dist d (catPoint h a b s) ^ 2 = L * s.val ^ 2 + W := by
+ have hab' : dist b a ^ 2 = L := (congrArg (· ^ 2) (dist_comm b a)).trans hab
+ have hdc' : dist c d ^ 2 = L := (congrArg (· ^ 2) (dist_comm c d)).trans hdc
+ have had' : dist d a ^ 2 = W := (congrArg (· ^ 2) (dist_comm d a)).trans had
+ have hbc' : dist c b ^ 2 = W := (congrArg (· ^ 2) (dist_comm c b)).trans hbc
+ have hac' : dist c a ^ 2 = L + W := (congrArg (· ^ 2) (dist_comm c a)).trans hac
+ have hbd' : dist d b ^ 2 = L + W := (congrArg (· ^ 2) (dist_comm d b)).trans hbd
+ have hL := dist_left_catPoint h a b s
+ have hR := dist_right_catPoint h a b s
+ have hlow₁ := comparison_lower h s.property.1 hL hR
+ (diagonal_flat h a b c d (by linarith only [hab, hbc, hdc', had', hac, hbd]))
+ have hlow₂ := comparison_lower (a := b) (b := a) (s := 1 - s.val) h (sub_nonneg.mpr s.property.2)
+ (by simpa only [dist_comm b a] using hR)
+ (by simpa only [sub_sub_cancel, dist_comm b a] using hL)
+ (diagonal_flat h b a d c (by linarith only [hab', had, hdc, hbc', hbd, hac]))
+ have hup₁ := catPoint_bound h a b s c
+ have hup₂ := catPoint_bound h a b s d
+ rw [hac', hbc', hab] at hlow₁ hup₁
+ rw [hbd', had', hab'] at hlow₂
+ rw [had', hbd', hab] at hup₂
+ constructor <;> linarith only [hlow₁, hlow₂, hup₁, hup₂]
+
+/-- Euclidean cross distances on the two interpolated parallel sides of a
+rectangle, including rectangles of zero width or length. -/
+theorem rectangle_interpolate (h : HasCATZeroSegments X) {a b d c : X} {L W : ℝ}
+ (hab : dist a b ^ 2 = L) (hdc : dist d c ^ 2 = L)
+ (had : dist a d ^ 2 = W) (hbc : dist b c ^ 2 = W)
+ (hac : dist a c ^ 2 = L + W) (hbd : dist b d ^ 2 = L + W)
+ (s t : Set.Icc (0 : ℝ) 1) :
+ dist (catPoint h a b s) (catPoint h d c t) ^ 2 = L * (s.val - t.val) ^ 2 + W := by
+ let e := catPoint h a b s
+ let f := catPoint h d c s
+ have had' : dist d a ^ 2 = W := (congrArg (· ^ 2) (dist_comm d a)).trans had
+ have hbc' : dist c b ^ 2 = W := (congrArg (· ^ 2) (dist_comm c b)).trans hbc
+ have hac' : dist c a ^ 2 = L + W := (congrArg (· ^ 2) (dist_comm c a)).trans hac
+ have hbd' : dist d b ^ 2 = L + W := (congrArg (· ^ 2) (dist_comm d b)).trans hbd
+ have rev (u : Set.Icc (0 : ℝ) 1) := rectangle_vertex h hdc hab had' hbc' hbd' hac' u
+ rcases eq_or_lt_of_le s.property.1 with hs | hs
+ · have heq : s = 0 := Subtype.ext hs.symm
+ rw [heq, catPoint_zero]
+ simpa using (rev t).2
+ rcases eq_or_lt_of_le s.property.2 with hs' | hs'
+ · have heq : s = 1 := Subtype.ext hs'
+ rw [heq, catPoint_one]
+ simpa using (rev t).1
+ obtain ⟨hc, hd⟩ := rectangle_vertex h hab hdc had hbc hac hbd s
+ change dist c e ^ 2 = _ at hc
+ change dist d e ^ 2 = _ at hd
+ rw [dist_comm c e] at hc
+ rw [dist_comm d e] at hd
+ have hf : dist a f ^ 2 = L * s.val ^ 2 + W := (rev s).2
+ have he' : dist a e ^ 2 = s.val ^ 2 * L := by
+ rw [dist_left_catPoint, mul_pow, hab]
+ have hf' : dist f d ^ 2 = s.val ^ 2 * L := by
+ rw [dist_comm f d, dist_left_catPoint, mul_pow, hdc]
+ have hquad := quadrilateral_sq h a e f d
+ rw [hf, hd, he', hf', had'] at hquad
+ have hup := catPoint_bound h d c s e
+ change dist e f ^ 2 ≤ _ at hup
+ rw [hc, hd, hdc] at hup
+ have heq : dist e f ^ 2 = W := by linarith only [hquad, hup]
+ have hmid : dist e f ^ 2 = (1 - s.val) * dist e d ^ 2 + s.val * dist e c ^ 2 -
+ s.val * (1 - s.val) * dist d c ^ 2 := by rw [heq, hc, hd, hdc]; ring
+ have ht := catPoint_bound_eq_of_interior h d c e s hs hs' hmid t
+ rw [hd, hc, hdc] at ht
+ change dist e (catPoint h d c t) ^ 2 = _
+ linarith only [ht]
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FlatTriangleVariation.lean b/lean/OAI/Computability/VPVNP/FlatTriangleVariation.lean
new file mode 100644
index 0000000000..a268a6a729
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FlatTriangleVariation.lean
@@ -0,0 +1,64 @@
+import Mathlib.Topology.Instances.Real.Lemmas
+import Mathlib.Tactic.FunProp
+import Mathlib.Tactic.Linarith
+import Mathlib.Tactic.Positivity
+
+/-!
+# First variation in a flat triangle
+
+To compare the first variations of two squared distances, use the triangle
+inequality at positive parameters and then pass to the right-hand limit at zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+open Filter Topology
+
+/-- For two distances initially equal to `L` and `s * L`, the triangle
+inequality with third side `(1 - s) * L` orders their normalized first
+variations. The two witnesses may be chosen separately for every parameter. -/
+theorem flatTriangle_firstVariation {L s k k' H2 : ℝ} (hL : 0 < L) (hs : 0 < s)
+ (h : ∀ t : ℝ, 0 < t → t ≤ 1 → ∃ x y : ℝ, 0 ≤ x ∧ 0 ≤ y ∧
+ x ^ 2 = L ^ 2 + t * k + t ^ 2 * H2 ∧
+ y ^ 2 ≤ (s * L) ^ 2 + t * k' + t ^ 2 * H2 ∧ x ≤ (1 - s) * L + y) :
+ s * k ≤ k' := by
+ let d := 2 * (s * L)
+ have hd : 0 < d := by dsimp [d]; positivity
+ let v := fun t : ℝ ↦ k' + t * H2
+ have bound (t : ℝ) (ht : 0 < t) (ht' : t ≤ 1) :
+ d ^ 2 * (k + t * H2) ≤ 2 * d * L * v t + t * (v t) ^ 2 := by
+ obtain ⟨x, y, hx, _, hxSq, hySq, hxy⟩ := h t ht ht'
+ have hy : d * y ≤ d * (s * L) + t * v t := by
+ dsimp [d, v]
+ nlinarith only [hySq, sq_nonneg (y - s * L)]
+ have hx' : d * x ≤ d * L + t * v t := by
+ have hxy' := mul_le_mul_of_nonneg_left hxy hd.le
+ linarith only [hy, show d * x ≤ d * L - d * (s * L) + d * y by
+ convert hxy' using 1; ring]
+ have hsq := pow_le_pow_left₀ (mul_nonneg hd.le hx) hx' 2
+ rw [mul_pow, hxSq] at hsq
+ apply le_of_mul_le_mul_left _ ht
+ nlinarith only [hsq]
+ have he : ∀ᶠ t in 𝓝[>] (0 : ℝ),
+ d ^ 2 * (k + t * H2) ≤ 2 * d * L * v t + t * (v t) ^ 2 := by
+ filter_upwards [self_mem_nhdsWithin, nhdsWithin_le_nhds (gt_mem_nhds zero_lt_one)]
+ with t ht ht'
+ exact bound t ht ht'.le
+ have hc₁ : Continuous (fun t : ℝ ↦ d ^ 2 * (k + t * H2)) := by fun_prop
+ have hc₂ : Continuous (fun t : ℝ ↦ 2 * d * L * v t + t * (v t) ^ 2) := by dsimp [v]; fun_prop
+ have hzero := le_of_tendsto_of_tendsto hc₁.continuousWithinAt.tendsto
+ hc₂.continuousWithinAt.tendsto he
+ simp only [zero_mul, add_zero, v] at hzero
+ apply le_of_mul_le_mul_left (a := 2 * d * L) _ (by positivity)
+ dsimp [d] at hzero ⊢
+ nlinarith only [hzero]
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FlatteningBlockRank.lean b/lean/OAI/Computability/VPVNP/FlatteningBlockRank.lean
new file mode 100644
index 0000000000..bd111cbf42
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FlatteningBlockRank.lean
@@ -0,0 +1,50 @@
+import Mathlib.LinearAlgebra.Matrix.Rank
+import Mathlib.LinearAlgebra.Dimension.Constructions
+
+/-!
+# Rank of a block diagonal flattening
+
+The linear map of a block diagonal matrix acts independently on the two
+coordinate blocks, so its range is isomorphic to the product of their ranges.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+/-- Ranks add under direct sums of rectangular matrices over any field. -/
+theorem rank_fromBlocks_zero {k m n i j : Type*} [Field k]
+ [Fintype n] [Fintype j] (A : Matrix m n k) (B : Matrix i j k) :
+ (Matrix.fromBlocks A 0 0 B).rank = A.rank + B.rank := by
+ let f := (Matrix.fromBlocks A 0 0 B).mulVecLin
+ let g := A.mulVecLin.prodMap B.mulVecLin
+ let e := LinearEquiv.sumArrowLequivProdArrow m i k k
+ let d := LinearEquiv.sumArrowLequivProdArrow n j k k
+ have h : e.toLinearMap.comp f = g.comp d.toLinearMap := by
+ apply LinearMap.ext
+ intro x
+ apply Prod.ext
+ · funext y
+ change ((Matrix.fromBlocks A 0 0 B).mulVec x) (.inl y) = _
+ simp [Matrix.fromBlocks_mulVec, g, d]
+ rfl
+ · funext y
+ change ((Matrix.fromBlocks A 0 0 B).mulVec x) (.inr y) = _
+ simp [Matrix.fromBlocks_mulVec, g, d]
+ rfl
+ have he : f.range.map e.toLinearMap = g.range := by
+ rw [← LinearMap.range_comp, h, d.range_comp]
+ calc
+ _ = Module.finrank k g.range := (e.ofSubmodules f.range g.range he).finrank_eq
+ _ = Module.finrank k (A.mulVecLin.range × B.mulVecLin.range) := by
+ rw [show g.range = A.mulVecLin.range.prod B.mulVecLin.range from LinearMap.range_prodMap _ _]
+ exact (Submodule.prodEquiv _ _).finrank_eq
+ _ = _ := Module.finrank_prod
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FlatteningKronecker.lean b/lean/OAI/Computability/VPVNP/FlatteningKronecker.lean
new file mode 100644
index 0000000000..4f3607629d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FlatteningKronecker.lean
@@ -0,0 +1,38 @@
+import Mathlib.LinearAlgebra.Matrix.Rank
+import Mathlib.LinearAlgebra.TensorProduct.Matrix
+import Mathlib.LinearAlgebra.Dimension.Constructions
+import Mathlib.RingTheory.Flat.Basic
+
+/-!
+# Rank of a product flattening
+
+The Kronecker product acts as the tensor product of the associated linear maps.
+Its range identifies with the tensor product of the two ranges.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+/-- Ranks multiply under Kronecker products of rectangular matrices over any field. -/
+theorem rank_kronecker {k m n i j : Type*} [Field k]
+ [Fintype m] [Fintype n] [Fintype i] [Fintype j] (A : Matrix m n k) (B : Matrix i j k) :
+ (Matrix.kronecker A B).rank = A.rank * B.rank := by
+ classical
+ let bm := Pi.basisFun k m
+ let bn := Pi.basisFun k n
+ let bi := Pi.basisFun k i
+ let bj := Pi.basisFun k j
+ rw [Matrix.rank_eq_finrank_range_toLin _ (bm.tensorProduct bi) (bn.tensorProduct bj),
+ Matrix.kronecker, Matrix.toLin_kronecker, Matrix.rank_eq_finrank_range_toLin A bm bn,
+ Matrix.rank_eq_finrank_range_toLin B bi bj, TensorProduct.range_map,
+ ← TensorProduct.range_mapIncl, LinearMap.finrank_range_of_inj, Module.finrank_tensorProduct]
+ exact Module.Flat.tensorProduct_mapIncl_injective_of_right _ _
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FlatteningWires.lean b/lean/OAI/Computability/VPVNP/FlatteningWires.lean
new file mode 100644
index 0000000000..67a038c648
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FlatteningWires.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.TensorFlatteningPoint
+
+/-!
+# Identity wires across a flattening cut
+
+Flattening at one party gives the cut-rank examples of Section 2. A crossing wire
+contains a full identity minor. A wire among the other parties contributes one row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v w
+
+namespace WireTensor
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J]
+
+section CutRanks
+
+variable [DecidableEq J]
+
+/-- The cut through one endpoint of a wire has an identity minor of its full dimension. -/
+theorem flattening_rank_wire_endpoint {a b : J} (hab : a ≠ b) (I : Type w) [Fintype I] :
+ (flattening a (wire (k := k) a b I)).rank = Fintype.card I := by
+ classical
+ let T := wire (k := k) a b I
+ let row (i : I) : T.Basis a := (fun _ ↦ i, fun _ ↦ i)
+ let col (i : I) : OtherBasis a T.Basis := fun _ ↦ (fun _ ↦ i, fun _ ↦ i)
+ let e : T.Basis a ≃ I :=
+ { toFun := fun x ↦ x.1 rfl
+ invFun := row
+ left_inv := fun x ↦ by
+ apply Prod.ext
+ · funext h
+ rfl
+ · funext h
+ exact (hab h).elim
+ right_inv := fun _ ↦ rfl }
+ have hm : (flattening a T).submatrix row col = 1 := by
+ ext i j
+ have hb := joinBasis_other a (row i) (col j) ⟨b, Ne.symm hab⟩
+ change (if (joinBasis a (row i) (col j) a).1 rfl = (joinBasis a (row i) (col j) b).2 rfl
+ then (1 : k) else 0) = _
+ rw [joinBasis_self, hb]
+ simp [row, col, Matrix.one_apply]
+ apply le_antisymm
+ · exact (Matrix.rank_le_card_height (flattening a T)).trans_eq (Fintype.card_congr e)
+ · simpa [hm] using Matrix.rank_submatrix_le (flattening a T) row col
+
+/-- If the cut party meets neither endpoint, a wire of positive dimension has
+one row and contains a nonzero entry. -/
+theorem flattening_rank_wire_away {a b c : J} (hca : c ≠ a) (hcb : c ≠ b)
+ (I : Type w) [Fintype I] [Nonempty I] :
+ (flattening c (wire (k := k) a b I)).rank = 1 := by
+ classical
+ let T := wire (k := k) a b I
+ let i : I := Classical.choice ‹Nonempty I›
+ let row (_ : Fin 1) : T.Basis c := (fun _ ↦ i, fun _ ↦ i)
+ let col (_ : Fin 1) : OtherBasis c T.Basis := fun _ ↦ (fun _ ↦ i, fun _ ↦ i)
+ let hu : Unique (T.Basis c) :=
+ { default := row 0
+ uniq := fun x ↦ by
+ apply Prod.ext
+ · funext h
+ exact (hca h).elim
+ · funext h
+ exact (hcb h).elim }
+ have hm : (flattening c T).submatrix row col = 1 := by
+ ext x y
+ have ha := joinBasis_other c (row x) (col y) ⟨a, Ne.symm hca⟩
+ have hb := joinBasis_other c (row x) (col y) ⟨b, Ne.symm hcb⟩
+ change (if (joinBasis c (row x) (col y) a).1 rfl = (joinBasis c (row x) (col y) b).2 rfl
+ then (1 : k) else 0) = _
+ rw [ha, hb]
+ simp [col, Matrix.one_apply, Subsingleton.elim x y]
+ apply le_antisymm
+ · simpa using Matrix.rank_le_card_height (flattening c T)
+ · simpa [hm] using Matrix.rank_submatrix_le (flattening c T) row col
+
+/-- A positive-dimensional identity wire has its full rank across the cut
+and rank one when both endpoints lie on the same side. -/
+theorem flattening_rank_wire (a b c : J) (I : Type w) [Fintype I] [Nonempty I] :
+ (flattening c (wire (k := k) a b I)).rank =
+ if (c = a ∧ c ≠ b) ∨ (c ≠ a ∧ c = b) then Fintype.card I else 1 := by
+ classical
+ by_cases hca : c = a
+ · subst c
+ by_cases hab : a = b
+ · subst b
+ simp only [ne_self_iff_false, and_false, false_and, or_self, ite_false]
+ let e : Fin 1 ↪ I := ⟨fun _ ↦ Classical.choice ‹Nonempty I›, fun _ _ _ ↦ Subsingleton.elim _ _⟩
+ have hl := flattening_rank_mono a ((wire_restricts_of_embedding (k := k) a a e).trans
+ (wire_one a a).2)
+ have hu := flattening_rank_mono a (unit_restricts_loop (k := k) a I)
+ rw [flattening_unit_rank] at hl hu
+ exact le_antisymm hu hl
+ · simpa [hab] using flattening_rank_wire_endpoint (k := k) hab I
+ · by_cases hcb : c = b
+ · subst c
+ have hs := wire_swap (k := k) a b I
+ have he := le_antisymm (flattening_rank_mono b hs.2) (flattening_rank_mono b hs.1)
+ simpa [hca] using he.trans (flattening_rank_wire_endpoint hca I)
+ · simpa [hca, hcb] using flattening_rank_wire_away (k := k) hca hcb I
+
+end CutRanks
+
+open scoped Classical
+
+/-- Binary wires give exactly the cut distance at the flattening spectral point. -/
+theorem flatteningPoint_wireDistance [Nontrivial J] (c a b : J) :
+ (flatteningPoint (k := k) c).wireDistance a b =
+ if (c = a ∧ c ≠ b) ∨ (c ≠ a ∧ c = b) then 1 else 0 := by
+ classical
+ change Real.log ((flatteningPoint (k := k) c).value (wire a b (Fin 2)) : ℝ) / Real.log 2 = _
+ rw [coe_flatteningPoint_value, flattening_rank_wire]
+ split_ifs
+ · simp [Real.log_pos (show (1 : ℝ) < 2 by norm_num) |>.ne']
+ · simp
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FormalSchur.lean b/lean/OAI/Computability/VPVNP/FormalSchur.lean
new file mode 100644
index 0000000000..4072ebd135
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FormalSchur.lean
@@ -0,0 +1,201 @@
+import Mathlib.Data.Fin.Tuple.Basic
+import Mathlib.LinearAlgebra.Matrix.Charpoly.Coeff
+import Mathlib.RingTheory.PowerSeries.Basic
+import Mathlib.Tactic.Ring
+
+/-!
+# Formal Schur factors of the reverse characteristic polynomial
+
+Appendix D.2 of *VP and VNP differ over every field* factors `det (1 - uM)`
+over formal power series by successively deleting the first row and column.
+The geometric inverse of a trailing matrix pencil has the powers of that
+matrix as its coefficients.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+open scoped BigOperators Matrix
+
+variable {R ι : Type*} [CommRing R] [Fintype ι] [DecidableEq ι]
+
+/-- The power-series matrix pencil whose inverse encodes all matrix powers. -/
+noncomputable def formalPencil (M : Matrix ι ι R) : Matrix ι ι (PowerSeries R) :=
+ 1 - (PowerSeries.X : PowerSeries R) • M.map PowerSeries.C
+
+/-- The entrywise series of powers of the matrix. -/
+noncomputable def formalResolvent (M : Matrix ι ι R) : Matrix ι ι (PowerSeries R) :=
+ Matrix.of (fun i j => PowerSeries.mk (fun h => (M ^ h) i j))
+
+@[simp] theorem coeff_formalResolvent (M : Matrix ι ι R) (h : ℕ) (i j : ι) :
+ PowerSeries.coeff h (formalResolvent M i j) = (M ^ h) i j :=
+ PowerSeries.coeff_mk h (fun k => (M ^ k) i j)
+
+theorem formalResolvent_mul_formalPencil (M : Matrix ι ι R) :
+ formalResolvent M * formalPencil M = 1 := by
+ rw [formalPencil, mul_sub, mul_one, Matrix.mul_smul]
+ apply Matrix.ext
+ intro i j
+ apply PowerSeries.ext
+ intro h
+ simp only [Matrix.sub_apply, Matrix.smul_apply, smul_eq_mul, map_sub, coeff_formalResolvent]
+ cases h with
+ | zero =>
+ rw [PowerSeries.coeff_zero_X_mul, sub_zero, pow_zero, Matrix.one_apply, Matrix.one_apply]
+ split_ifs <;> simp [PowerSeries.coeff_one]
+ | succ h =>
+ rw [PowerSeries.coeff_succ_X_mul, pow_succ, Matrix.mul_apply, Matrix.mul_apply, map_sum]
+ simp only [Matrix.map_apply, PowerSeries.coeff_mul_C, coeff_formalResolvent, sub_self]
+ rw [Matrix.one_apply]
+ split_ifs <;> simp [PowerSeries.coeff_one]
+
+theorem formalPencil_mul_formalResolvent (M : Matrix ι ι R) :
+ formalPencil M * formalResolvent M = 1 :=
+ mul_eq_one_comm.mp (formalResolvent_mul_formalPencil M)
+
+/-- Invertibility witness for the formal matrix pencil, with its formal resolvent as the
+inverse. -/
+@[instance_reducible] noncomputable def pencilInvertible (M : Matrix ι ι R) :
+ Invertible (formalPencil M) where
+ invOf := formalResolvent M
+ invOf_mul_self := formalResolvent_mul_formalPencil M
+ mul_invOf_self := formalPencil_mul_formalResolvent M
+
+/-- Every coefficient of the inverse pencil is an entry of a finite matrix power. -/
+theorem coeff_formalPencil_inv (M : Matrix ι ι R) (h : ℕ) (i j : ι) :
+ PowerSeries.coeff h ((formalPencil M)⁻¹ i j) = (M ^ h) i j := by
+ rw [Matrix.inv_eq_left_inv (formalResolvent_mul_formalPencil M), coeff_formalResolvent]
+
+variable {n : ℕ}
+
+/-- The Schur complement obtained by deleting the first row and column. -/
+noncomputable def headFactor (M : Matrix (Fin (n + 1)) (Fin (n + 1)) R) : PowerSeries R :=
+ 1 - PowerSeries.X * PowerSeries.C (M 0 0) - PowerSeries.X ^ 2 *
+ ∑ i : Fin n, ∑ j : Fin n, PowerSeries.C (M 0 i.succ) *
+ formalResolvent (M.submatrix Fin.succ Fin.succ) i j * PowerSeries.C (M j.succ 0)
+
+theorem det_formalPencil_succ (M : Matrix (Fin (n + 1)) (Fin (n + 1)) R) :
+ (formalPencil M).det = headFactor M * (formalPencil (M.submatrix Fin.succ Fin.succ)).det := by
+ classical
+ let _ := pencilInvertible (M.submatrix Fin.succ Fin.succ)
+ have hinv : ⅟(formalPencil (M.submatrix Fin.succ Fin.succ)) =
+ formalResolvent (M.submatrix Fin.succ Fin.succ) := rfl
+ let e : Unit ⊕ Fin n ≃ Fin (n + 1) :=
+ (Equiv.sumComm _ _).trans ((Equiv.optionEquivSumPUnit _).symm.trans (finSuccEquiv n).symm)
+ let a : Matrix Unit Unit (PowerSeries R) :=
+ Matrix.of fun _ _ => 1 - PowerSeries.X * PowerSeries.C (M 0 0)
+ let b : Matrix Unit (Fin n) (PowerSeries R) :=
+ Matrix.of fun _ j => -(PowerSeries.X * PowerSeries.C (M 0 j.succ))
+ let c : Matrix (Fin n) Unit (PowerSeries R) :=
+ Matrix.of fun i _ => -(PowerSeries.X * PowerSeries.C (M i.succ 0))
+ have hblock : (formalPencil M).submatrix e e =
+ Matrix.fromBlocks a b c (formalPencil (M.submatrix Fin.succ Fin.succ)) := by
+ ext i j
+ cases i <;> cases j <;>
+ simp [e, a, b, c, formalPencil, Matrix.one_apply, smul_eq_mul, Ne.symm (Fin.succ_ne_zero _)]
+ rw [← Matrix.det_submatrix_equiv_self e (formalPencil M), hblock, Matrix.det_fromBlocks₂₂,
+ hinv, Matrix.det_unique (a - b * formalResolvent (M.submatrix Fin.succ Fin.succ) * c), mul_comm]
+ congr 1
+ simp only [Matrix.sub_apply, Matrix.mul_apply, a, b, c, Matrix.of_apply, headFactor]
+ congr 1
+ simp_rw [Finset.sum_mul, Finset.mul_sum]
+ rw [Finset.sum_comm]
+ apply Finset.sum_congr rfl
+ intro i hi
+ apply Finset.sum_congr rfl
+ intro j hj
+ ring
+
+section TrailingIndices
+
+variable {R A : Type*}
+
+/-- Evaluate a local rule on each trailing submatrix by repeatedly dropping the first index. -/
+private def peelFactors (f : ∀ {n : ℕ}, Matrix (Fin (n + 1)) (Fin (n + 1)) R → A) :
+ ∀ {n : ℕ}, Matrix (Fin n) (Fin n) R → Fin n → A
+ | 0, _ => Fin.elim0
+ | _ + 1, M => Fin.cons (f M) (peelFactors f (M.submatrix Fin.succ Fin.succ))
+
+/-- Place the indices of the trailing principal submatrix in the full matrix. -/
+def suffixIndex {n : ℕ} (i : Fin n) (j : Fin ((n - i.val - 1) + 1)) : Fin n :=
+ ⟨j.val + i.val, by have := j.isLt; have := i.isLt; omega⟩
+
+private theorem peelFactors_eq_of_size
+ (f : ∀ {n : ℕ}, Matrix (Fin (n + 1)) (Fin (n + 1)) R → A)
+ {n m : ℕ} (M : Matrix (Fin n) (Fin n) R) (i : Fin n) (h : i.val + (m + 1) = n) :
+ peelFactors f M i = f (M.submatrix
+ (fun j : Fin (m + 1) => ⟨j.val + i.val, by have := j.isLt; omega⟩)
+ (fun j : Fin (m + 1) => ⟨j.val + i.val, by have := j.isLt; omega⟩)) := by
+ induction n with
+ | zero => exact Fin.elim0 i
+ | succ n ih =>
+ cases i using Fin.cases with
+ | zero =>
+ simp only [Fin.val_zero, Nat.zero_add, Nat.add_right_cancel_iff] at h
+ subst m
+ change f M = f _
+ congr 1
+ | succ i =>
+ have h' : i.val + (m + 1) = n := by simp only [Fin.val_succ] at h; omega
+ change peelFactors f (M.submatrix Fin.succ Fin.succ) i = _
+ rw [ih (M.submatrix Fin.succ Fin.succ) i h']
+ congr 1
+
+private theorem peelFactors_apply
+ (f : ∀ {n : ℕ}, Matrix (Fin (n + 1)) (Fin (n + 1)) R → A)
+ {n : ℕ} (M : Matrix (Fin n) (Fin n) R) (i : Fin n) :
+ peelFactors f M i = f (M.submatrix (suffixIndex i) (suffixIndex i)) :=
+ peelFactors_eq_of_size f M i (by have := i.isLt; omega)
+
+end TrailingIndices
+
+theorem coe_charpolyRev (M : Matrix ι ι R) :
+ (M.charpolyRev : PowerSeries R) = (formalPencil M).det := by
+ change Polynomial.coeToPowerSeries.ringHom (M.charpolyRev) = _
+ rw [Matrix.charpolyRev, RingHom.map_det]
+ congr 1
+ apply Matrix.ext
+ intro i j
+ change Polynomial.coeToPowerSeries.ringHom
+ ((1 - (Polynomial.X : Polynomial R) • M.map Polynomial.C) i j) = _
+ rw [Matrix.sub_apply, map_sub, Matrix.smul_apply, smul_eq_mul, map_mul]
+ simp [formalPencil, Matrix.one_apply, smul_eq_mul]
+
+/-- The degree-zero and degree-one terms of a Schur factor come from the diagonal.
+Each higher coefficient queries exactly one power of the trailing matrix. -/
+theorem coeff_headFactor (M : Matrix (Fin (n + 1)) (Fin (n + 1)) R) (u : ℕ) :
+ PowerSeries.coeff u (headFactor M) = match u with
+ | 0 => 1
+ | 1 => -M 0 0
+ | h + 2 => -(∑ i : Fin n, ∑ j : Fin n, M 0 i.succ *
+ (M.submatrix Fin.succ Fin.succ ^ h) i j * M j.succ 0) := by
+ rcases u with _ | _ | h
+ · simp [headFactor]
+ · simp [headFactor, PowerSeries.coeff_X_pow_mul', PowerSeries.coeff_X]
+ · change PowerSeries.coeff (h + 2) _ = _
+ simp [headFactor, PowerSeries.coeff_X]
+
+private theorem det_eq_peelProduct (M : Matrix (Fin n) (Fin n) R) :
+ (formalPencil M).det = ∏ i, peelFactors (fun {_} => headFactor) M i := by
+ induction n with
+ | zero => simp
+ | succ n ih =>
+ rw [det_formalPencil_succ, ih, Fin.prod_univ_succ]
+ rfl
+
+/-- Every factor of the reverse characteristic polynomial is obtained by a direct
+index shift to the trailing principal submatrix beginning at the given row. -/
+theorem charpolyRev_eq_schurProduct (M : Matrix (Fin n) (Fin n) R) :
+ (M.charpolyRev : PowerSeries R) =
+ ∏ i : Fin n, headFactor (M.submatrix (suffixIndex i) (suffixIndex i)) := by
+ rw [coe_charpolyRev, det_eq_peelProduct]
+ simp only [peelFactors_apply]
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/FractionalGeodesic.lean b/lean/OAI/Computability/VPVNP/FractionalGeodesic.lean
new file mode 100644
index 0000000000..3682b50d1b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/FractionalGeodesic.lean
@@ -0,0 +1,88 @@
+import Mathlib.Topology.UnitInterval
+import Mathlib.Topology.MetricSpace.Lipschitz
+import Mathlib.Tactic.Linarith
+
+/-! # Geodesics from unique fractional points
+
+In Corollary 2.5 of *VP and VNP differ over every field*, fractional points are
+characterized by their distances to the two endpoints. Uniqueness for every pair of
+endpoints makes these fractional points a constant-speed geodesic.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {X : Type*} [MetricSpace X]
+
+/-- Unique fractional points determine a constant-speed segment between each pair. -/
+theorem exists_constantSpeedSegment
+ (h : ∀ (a b : X) (t : unitInterval), ∃! z,
+ dist a z = (t : ℝ) * dist a b ∧ dist z b = (1 - (t : ℝ)) * dist a b)
+ (a b : X) : ∃ g : unitInterval → X, g 0 = a ∧ g 1 = b ∧
+ ∀ s t, dist (g s) (g t) = |(s : ℝ) - t| * dist a b := by
+ choose g hg using fun t => (h a b t).exists
+ have ordered (s t : unitInterval) (hst : (s : ℝ) ≤ t) :
+ dist (g s) (g t) = ((t : ℝ) - s) * dist a b := by
+ rcases lt_or_eq_of_le hst with hlt | heq
+ · have ht : (t : ℝ) ≠ 0 := ne_of_gt (lt_of_le_of_lt s.property.1 hlt)
+ let u : unitInterval := ⟨(s : ℝ) / t, unitInterval.div_mem s.property.1 t.property.1 hst⟩
+ obtain ⟨z, hl, hr⟩ := (h a (g t) u).exists
+ have hzleft : dist a z = (s : ℝ) * dist a b := by
+ rw [hl, (hg t).1]
+ change (s : ℝ) / t * ((t : ℝ) * _) = _
+ field_simp
+ have hzstep : dist z (g t) = ((t : ℝ) - s) * dist a b := by
+ rw [hr, (hg t).1]
+ change (1 - (s : ℝ) / t) * ((t : ℝ) * _) = _
+ field_simp
+ have hzright : dist z b = (1 - (s : ℝ)) * dist a b := by
+ have upper := dist_triangle z (g t) b
+ rw [hzstep, (hg t).2] at upper
+ have lower := dist_triangle a z b
+ rw [hzleft] at lower
+ linarith only [upper, lower]
+ rwa [(h a b s).unique ⟨hzleft, hzright⟩ (hg s)] at hzstep
+ · have : s = t := Subtype.ext heq
+ subst t
+ simp
+ refine ⟨g, ?_, ?_, fun s t => ?_⟩
+ · exact (eq_of_dist_eq_zero (by simpa using (hg 0).1)).symm
+ · exact eq_of_dist_eq_zero (by simpa using (hg 1).2)
+ · rcases le_total (s : ℝ) (t : ℝ) with hst | hts
+ · rw [ordered s t hst, abs_sub_comm, abs_of_nonneg (sub_nonneg.mpr hst)]
+ · rw [dist_comm, ordered t s hts, abs_of_nonneg (sub_nonneg.mpr hts)]
+
+/-- Any two constant-speed segments with these endpoints agree at every parameter. -/
+theorem existsUnique_constantSpeedSegment
+ (h : ∀ (a b : X) (t : unitInterval), ∃! z,
+ dist a z = (t : ℝ) * dist a b ∧ dist z b = (1 - (t : ℝ)) * dist a b)
+ (a b : X) : ∃! g : unitInterval → X, g 0 = a ∧ g 1 = b ∧
+ ∀ s t, dist (g s) (g t) = |(s : ℝ) - t| * dist a b := by
+ have atFraction (g : unitInterval → X) (hg₀ : g 0 = a) (hg₁ : g 1 = b)
+ (hg : ∀ s t, dist (g s) (g t) = |(s : ℝ) - t| * dist a b) (t : unitInterval) :
+ dist a (g t) = (t : ℝ) * dist a b ∧ dist (g t) b = (1 - (t : ℝ)) * dist a b := by
+ constructor
+ · simpa [hg₀, abs_of_nonneg t.property.1] using hg 0 t
+ · simpa [hg₁, abs_sub_comm (t : ℝ) 1, abs_of_nonneg (sub_nonneg.mpr t.property.2)]
+ using hg t 1
+ obtain ⟨g, hg₀, hg₁, hg⟩ := exists_constantSpeedSegment h a b
+ refine ⟨g, ⟨hg₀, hg₁, hg⟩, fun f ⟨hf₀, hf₁, hf⟩ => ?_⟩
+ exact funext fun t => (h a b t).unique (atFraction f hf₀ hf₁ hf t) (atFraction g hg₀ hg₁ hg t)
+
+/-- A constant-speed segment is Lipschitz, hence continuous. -/
+theorem continuous_of_constantSpeed (a b : X) {g : unitInterval → X}
+ (h : ∀ s t, dist (g s) (g t) = |(s : ℝ) - t| * dist a b) : Continuous g := by
+ apply (LipschitzWith.continuous (K := nndist a b))
+ apply LipschitzWith.of_dist_le_mul
+ intro s t
+ change dist (g s) (g t) ≤ dist a b * dist (s : ℝ) (t : ℝ)
+ rw [h, Real.dist_eq, mul_comm]
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GadgetPorts.lean b/lean/OAI/Computability/VPVNP/GadgetPorts.lean
new file mode 100644
index 0000000000..3ae4240246
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GadgetPorts.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.HamiltonianGadget
+
+/-! # Port neighborhoods of the exact-one Hamiltonian-cycle graph -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HCGadget
+
+variable {k h c : ℕ} {occ : Fin h → Fin k × Fin c × Bool}
+
+private theorem prevPort_buffer {i i' : Fin k} {j : Fin h} {b : Bool}
+ (t : Fin (h + 1)) (he : prevPort (c := c) i' t = .port i j b) :
+ .buffer i' t = portBuffer (c := c) i j b := by
+ induction t using Fin.cases with
+ | zero => simp at he
+ | succ t => simp only [prevPort_succ, Vertex.port.injEq] at he; rcases he with ⟨rfl,rfl,rfl⟩; rfl
+
+private theorem nextPort_buffer {i i' : Fin k} {j : Fin h} {b : Bool}
+ (t : Fin (h + 1)) (he : nextPort (c := c) i' t = .port i j b) :
+ .buffer i' t = portBuffer (c := c) i j b := by
+ induction t using Fin.lastCases with
+ | last => simp at he
+ | cast t => simp only [nextPort_castSucc, Vertex.port.injEq] at he; rcases he with ⟨rfl,rfl,rfl⟩; rfl
+
+theorem Allowed.from_port {i : Fin k} {j : Fin h} {b : Bool} {v : Vertex k h c}
+ (edge : Allowed occ (.port i j b) v) :
+ v = portBuffer i j b ∨ (v = .port i j (!b) ∧ ((occ j).1 ≠ i ∨ (occ j).2.2 = b)) ∨
+ (v = .clause (occ j).2.1 ∧ (occ j).1 = i ∧ b = !(occ j).2.2) := by
+ generalize hs : Vertex.port i j b = u at edge
+ cases edge with
+ | prevBuffer i' t => exact Or.inl (prevPort_buffer t hs.symm)
+ | nextBuffer i' t => exact Or.inl (nextPort_buffer t hs.symm)
+ | cross i' j' b' hcross => cases hs; exact Or.inr (Or.inl ⟨rfl, hcross⟩)
+ | enterClause j' => cases hs; simp
+ | _ => cases hs
+
+theorem Allowed.to_port {i : Fin k} {j : Fin h} {b : Bool} {u : Vertex k h c}
+ (edge : Allowed occ u (.port i j b)) :
+ u = portBuffer i j b ∨ (u = .port i j (!b) ∧ ((occ j).1 ≠ i ∨ (occ j).2.2 = !b)) ∨
+ (u = .clause (occ j).2.1 ∧ (occ j).1 = i ∧ b = (occ j).2.2) := by
+ generalize hs : Vertex.port i j b = v at edge
+ cases edge with
+ | bufferPrev i' t => exact Or.inl (prevPort_buffer t hs.symm)
+ | bufferNext i' t => exact Or.inl (nextPort_buffer t hs.symm)
+ | cross i' j' b' hcross => cases hs; exact Or.inr (Or.inl (by simpa using hcross))
+ | exitClause j' => cases hs; simp
+ | _ => cases hs
+
+/-- The buffer next to an endpoint, indexed by its side of the track. -/
+def endpointBuffer (i : Fin k) (b : Bool) : Vertex k h c :=
+ .buffer i (if b then Fin.last h else 0)
+
+private theorem prevEndpoint_buffer {i i' : Fin k} {b : Bool}
+ (t : Fin (h + 1)) (he : prevPort (c := c) i' t = .endpoint i b) :
+ .buffer i' t = endpointBuffer (c := c) i b := by
+ induction t using Fin.cases with
+ | zero => simp only [prevPort_zero, Vertex.endpoint.injEq] at he; rcases he with ⟨rfl,rfl⟩; rfl
+ | succ t => simp at he
+
+private theorem nextEndpoint_buffer {i i' : Fin k} {b : Bool}
+ (t : Fin (h + 1)) (he : nextPort (c := c) i' t = .endpoint i b) :
+ .buffer i' t = endpointBuffer (c := c) i b := by
+ induction t using Fin.lastCases with
+ | last => simp only [nextPort_last, Vertex.endpoint.injEq] at he; rcases he with ⟨rfl,rfl⟩; rfl
+ | cast t => simp at he
+
+theorem Allowed.from_endpoint {i : Fin k} {b : Bool} {v : Vertex k h c}
+ (edge : Allowed occ (.endpoint i b) v) :
+ v = endpointBuffer i b ∨ v = .sep (finRotate k i) := by
+ generalize hs : Vertex.endpoint i b = u at edge
+ cases edge with
+ | prevBuffer i' t => exact Or.inl (prevEndpoint_buffer t hs.symm)
+ | nextBuffer i' t => exact Or.inl (nextEndpoint_buffer t hs.symm)
+ | exitTrack i' b' => cases hs; exact Or.inr rfl
+ | _ => cases hs
+
+theorem Allowed.to_endpoint {i : Fin k} {b : Bool} {u : Vertex k h c}
+ (edge : Allowed occ u (.endpoint i b)) : u = endpointBuffer i b ∨ u = .sep i := by
+ generalize hs : Vertex.endpoint i b = v at edge
+ cases edge with
+ | bufferPrev i' t => exact Or.inl (prevEndpoint_buffer t hs.symm)
+ | bufferNext i' t => exact Or.inl (nextEndpoint_buffer t hs.symm)
+ | enterTrack i' b' => cases hs; exact Or.inr rfl
+ | _ => cases hs
+
+/-- The left and right neighbor of a buffer are distinct, including an empty track. -/
+theorem prev_next_ne (i : Fin k) (t : Fin (h + 1)) :
+ prevPort (c := c) i t ≠ nextPort i t := by
+ suffices disjoint : ∀ l r : Fin (h + 1), prevPort (c := c) i l ≠ nextPort i r from disjoint t t
+ intro l r
+ induction l using Fin.cases <;> induction r using Fin.lastCases <;> simp
+
+/-- A spanning permutation cannot contain a 2-cycle: a track has at least four vertices. -/
+theorem no_two_cycle (π : Equiv.Perm (Vertex k h c)) (cycle : π.IsCycleOn Set.univ)
+ (i : Fin k) (v : Vertex k h c) : π (π v) ≠ v := by
+ intro hv
+ have hcy : π.IsCycleOn (Finset.univ : Finset (Vertex k h c)) := by simpa using cycle
+ have hdiv := (hcy.pow_apply_eq (Finset.mem_univ v) (n := 2)).mp
+ (by simpa [pow_two] using hv)
+ rw [Finset.card_univ, card_vertex] at hdiv
+ have hle := Nat.le_of_dvd (by decide : 0 < 2) hdiv
+ have hi : 0 < k := Nat.zero_lt_of_lt i.isLt
+ have hmul := Nat.le_mul_of_pos_left (3*h+4) hi
+ omega
+
+/-- A tour passes through each degree-two buffer from one side to the other. -/
+theorem buffer_directions (π : Equiv.Perm (Vertex k h c)) (cycle : π.IsCycleOn Set.univ)
+ (allowed : ∀ v, Allowed occ v (π v)) (i : Fin k) (t : Fin (h + 1)) :
+ (π (.buffer i t) = nextPort i t ∧ π (prevPort i t) = .buffer i t) ∨
+ (π (.buffer i t) = prevPort i t ∧ π (nextPort i t) = .buffer i t) := by
+ obtain ⟨v, hv⟩ := π.surjective (.buffer i t)
+ have he := allowed v
+ rw [hv] at he
+ have hin := allowed_to_buffer_iff.mp he
+ have hout := allowed_from_buffer_iff.mp (allowed (.buffer i t))
+ have hne := no_two_cycle π cycle i v
+ rw [hv] at hne
+ rcases hin with rfl | rfl
+ · exact Or.inl ⟨hout.resolve_left hne, hv⟩
+ · exact Or.inr ⟨hout.resolve_right hne, hv⟩
+
+end HCGadget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GeneratorProducts.lean b/lean/OAI/Computability/VPVNP/GeneratorProducts.lean
new file mode 100644
index 0000000000..1b53242313
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GeneratorProducts.lean
@@ -0,0 +1,88 @@
+import Mathlib.Data.Finsupp.Basic
+import Mathlib.Data.Fintype.BigOperators
+
+/-!
+# Products of old and added generators in the exact extension proof
+
+The monomials in Theorem 2.4 have arbitrarily many embedded old factors
+and either one star generator or two split wires. Multiplicativity folds
+all the old factors into one embedded product. The common-exponent
+monomial retains both required wires with equal multiplicities.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+variable {A B ι E : Type*} [CommMonoid A] [CommMonoid B]
+
+/-- Separate the finite product into its old factors and its added factors.
+The two groups can have different, individually prescribed exponents. -/
+theorem fold_generatorProduct (φ : A →* B) (old : ι → A) (extra : E → B)
+ (s : Finset (ι ⊕ E)) (p : ι ⊕ E → ℕ) :
+ ∏ i ∈ s, (Sum.elim (φ ∘ old) extra i) ^ p i =
+ φ (∏ j ∈ s.toLeft, old j ^ p (.inl j)) * ∏ j ∈ s.toRight, extra j ^ p (.inr j) := by
+ rw [Finset.prod_sum_eq_prod_toLeft_mul_prod_toRight]
+ simp only [Sum.elim_inl, Function.comp_apply, Sum.elim_inr, map_prod, map_pow]
+
+/-- A monomial of finite support contains every extra generator to its
+prescribed power. Exponents outside its support contribute units. -/
+theorem fold_generatorMonomial [Fintype E] (φ : A →* B) (old : ι → A) (extra : E → B)
+ (d : (ι ⊕ E) →₀ ℕ) :
+ d.prod (fun i n ↦ (Sum.elim (φ ∘ old) extra i) ^ n) =
+ φ (∏ j ∈ d.support.toLeft, old j ^ d (.inl j)) * ∏ j, extra j ^ d (.inr j) := by
+ classical
+ rw [Finsupp.prod, fold_generatorProduct]
+ congr 1
+ apply Finset.prod_subset (Finset.subset_univ _)
+ intro j _ hj
+ have h : d (.inr j) = 0 := Finsupp.notMem_support_iff.mp (fun h ↦ hj (Finset.mem_toRight.mpr h))
+ simp [h]
+
+/-- If all extra generators are required, each appears exactly `e` times
+in the reference monomial. -/
+theorem fold_generatorBalanced [Fintype E] (φ : A →* B) (old : ι → A) (extra : E → B)
+ (s : Finset (ι ⊕ E)) (e : ℕ) (hs : ∀ j, Sum.inr j ∈ s) :
+ ∏ i ∈ s, (Sum.elim (φ ∘ old) extra i) ^ e =
+ φ (∏ j ∈ s.toLeft, old j ^ e) * ∏ j, extra j ^ e := by
+ have hall : s.toRight = Finset.univ :=
+ Finset.eq_univ_of_forall (fun j ↦ Finset.mem_toRight.mpr (hs j))
+ simpa only [hall] using fold_generatorProduct φ old extra s (fun _ ↦ e)
+
+/-- One star generator in an arbitrary monomial. -/
+theorem fold_starMonomial (φ : A →* B) (old : ι → A) (S : B) (d : (ι ⊕ Unit) →₀ ℕ) :
+ d.prod (fun i n ↦ (Sum.elim (φ ∘ old) (fun _ ↦ S) i) ^ n) =
+ φ (∏ j ∈ d.support.toLeft, old j ^ d (.inl j)) * S ^ d (.inr ()) := by
+ simpa only [Fintype.prod_unique] using fold_generatorMonomial φ old (fun _ ↦ S) d
+
+/-- One required star generator in the reference monomial. -/
+theorem fold_starBalanced (φ : A →* B) (old : ι → A) (S : B)
+ (s : Finset (ι ⊕ Unit)) (e : ℕ) (hs : Sum.inr () ∈ s) :
+ ∏ i ∈ s, (Sum.elim (φ ∘ old) (fun _ ↦ S) i) ^ e =
+ φ (∏ j ∈ s.toLeft, old j ^ e) * S ^ e := by
+ simpa only [Fintype.prod_unique] using
+ fold_generatorBalanced φ old (fun _ ↦ S) s e (fun _ ↦ hs)
+
+/-- The two split-wire multiplicities in an arbitrary monomial. -/
+theorem fold_splitMonomial (φ : A →* B) (old : ι → A) (wire : Bool → B)
+ (d : (ι ⊕ Bool) →₀ ℕ) :
+ d.prod (fun i n ↦ (Sum.elim (φ ∘ old) wire i) ^ n) =
+ φ (∏ j ∈ d.support.toLeft, old j ^ d (.inl j)) *
+ (wire false ^ d (.inr false) * wire true ^ d (.inr true)) := by
+ rw [fold_generatorMonomial, Fintype.prod_bool, mul_comm (wire true ^ _)]
+
+/-- The two required split wires occur with equal multiplicity in the
+reference monomial, so its center can contract to the full identity. -/
+theorem fold_splitBalanced (φ : A →* B) (old : ι → A) (wire : Bool → B)
+ (s : Finset (ι ⊕ Bool)) (e : ℕ) (hs : ∀ j : Bool, Sum.inr j ∈ s) :
+ ∏ i ∈ s, (Sum.elim (φ ∘ old) wire i) ^ e =
+ φ (∏ j ∈ s.toLeft, old j ^ e) * (wire false ^ e * wire true ^ e) := by
+ rw [fold_generatorBalanced φ old wire s e hs, Fintype.prod_bool, mul_comm (wire true ^ _)]
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GeodesicExtension.lean b/lean/OAI/Computability/VPVNP/GeodesicExtension.lean
new file mode 100644
index 0000000000..80c3fd269d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GeodesicExtension.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.ConfigurationCompletion
+import OAI.Computability.VPVNP.FractionalGeodesic
+import OAI.Computability.VPVNP.MetricMidpoints
+import OAI.Computability.VPVNP.RealizedTransport
+import OAI.Computability.VPVNP.SpectralMidpointTower
+import OAI.Computability.VPVNP.WireCompletion
+import OAI.Computability.VPVNP.WireCoupling
+
+/-!
+# The geodesic completion of a spectral wire pseudometric
+
+Corollary 2.5 of *VP and VNP differ over every field* first forms the union
+of successive midpoint extensions, then takes its metric completion.
+The transport inequality guarantees that midpoints of Cauchy endpoint
+sequences converge. Closure of finite configurations preserves spectral
+realizability in the completion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open WireTensor
+
+/-- Fractional points in a space with spectral transport form a unique
+constant-speed geodesic between any two endpoints. -/
+theorem existsUnique_segment {X : Type*} [MetricSpace X] (hf : HasFractions X)
+ (ht : FractionTransport X) (a b : X) :
+ ∃! g : unitInterval → X, g 0 = a ∧ g 1 = b ∧
+ ∀ s t, dist (g s) (g t) = |(s : ℝ) - t| * dist a b := by
+ apply SpectralGeometry.existsUnique_constantSpeedSegment _ a b
+ intro x y t
+ obtain ⟨z, hz⟩ := hf x y t t.property.1 t.property.2
+ exact ⟨z, hz, fun _ hw ↦ atFraction_unique ht t.property.1 t.property.2 hw hz⟩
+
+/-- Any distance-preserving map of a pseudometric space into a metric space
+induces an isometric embedding of the quotient identifying points at distance
+zero. -/
+theorem exists_separationQuotient_isometry {A X : Type*} [PseudoMetricSpace A] [MetricSpace X]
+ (e : A → X) (he : ∀ a b, dist (e a) (e b) = dist a b) :
+ ∃ f : SeparationQuotient A → X, Isometry f ∧ ∀ a, f (.mk a) = e a := by
+ let f := SeparationQuotient.lift e (fun x y h ↦ dist_eq_zero.mp ((he x y).trans h.dist_eq_zero))
+ refine ⟨f, Isometry.of_dist_eq ?_, fun _ ↦ rfl⟩
+ intro x y
+ obtain ⟨a, rfl⟩ := SeparationQuotient.surjective_mk x
+ obtain ⟨b, rfl⟩ := SeparationQuotient.surjective_mk y
+ exact he a b
+
+/-- The completion step of Corollary 2.5, using six-point spectral transport
+for Lemma 2.2. The isometric map sends exactly the pairs at wire distance
+zero to the same point. -/
+theorem exists_geodesic_completion_of_wire_transport {k : Type*} [Field k]
+ {J : Type} [Fintype J] [Nontrivial J] (F : SpectralPoint k J)
+ (hwire : ∀ (K : Type) [Fintype K] [Nontrivial K] (G : SpectralPoint k K),
+ @FractionTransport K G.wirePseudoMetric) :
+ ∃ (X : Type) (_ : MetricSpace X) (_ : CompleteSpace X) (e : J → X),
+ (∀ a b, dist (e a) (e b) = F.wireDistance a b) ∧
+ RealizableConfigurations k X ∧ HasFractions X ∧ FractionTransport X ∧
+ ∀ a b : X, ∃! g : unitInterval → X, g 0 = a ∧ g 1 = b ∧
+ ∀ s t, dist (g s) (g t) = |(s : ℝ) - t| * dist a b := by
+ obtain ⟨M, hJ, hR, hm⟩ := F.exists_midpoint_tower
+ let : PseudoMetricSpace (J ⊕ ℕ) := M
+ let X := UniformSpace.Completion (J ⊕ ℕ)
+ have hX : RealizableConfigurations k X := fun n p ↦ RealizableUpToScale.completion (hR n) p
+ have hT : FractionTransport X := fractionTransport_of_realizable hwire hX
+ have hmid := midpoints_of_dense_isometry ((↑) : J ⊕ ℕ → X)
+ UniformSpace.Completion.coe_isometry UniformSpace.Completion.denseRange_coe hm
+ (fractionTransport_of_realizable hwire hR)
+ have hf : HasFractions X := by
+ intro x y t ht ht'
+ apply SpectralGeometry.exists_fractionalPoint_of_midpoints _ x y ht ht'
+ intro a b
+ obtain ⟨z, hl, hr⟩ := hmid a b
+ exact ⟨z, by linarith only [hl], by linarith only [hr]⟩
+ exact ⟨X, inferInstance, inferInstance, fun a ↦ ((Sum.inl a : J ⊕ ℕ) : X),
+ fun a b ↦ (UniformSpace.Completion.dist_eq _ _).trans (hJ a b),
+ hX, hf, hT, existsUnique_segment hf hT⟩
+
+/-- Corollary 2.5. Every finite spectral wire pseudometric embeds, after
+identifying zero distances, into a complete geodesic space whose finite
+configurations are realizable up to scale. Equation (2.2) holds throughout
+the extension and the geodesic between each pair is unique. -/
+theorem exists_geodesic_completion {k : Type*} [Field k]
+ {J : Type} [Fintype J] [Nontrivial J] (F : SpectralPoint k J) :
+ ∃ (X : Type) (_ : MetricSpace X) (_ : CompleteSpace X) (e : J → X),
+ (∀ a b, dist (e a) (e b) = F.wireDistance a b) ∧
+ RealizableConfigurations k X ∧ HasFractions X ∧ FractionTransport X ∧
+ ∀ a b : X, ∃! g : unitInterval → X, g 0 = a ∧ g 1 = b ∧
+ ∀ s t, dist (g s) (g t) = |(s : ℝ) - t| * dist a b :=
+ exists_geodesic_completion_of_wire_transport F (fun _ _ _ G ↦ G.fractionTransport)
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GradedComponents.lean b/lean/OAI/Computability/VPVNP/GradedComponents.lean
new file mode 100644
index 0000000000..c36e093fd1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GradedComponents.lean
@@ -0,0 +1,63 @@
+import Mathlib.RingTheory.MvPolynomial.Homogeneous
+import Mathlib.Algebra.BigOperators.NatAntidiagonal
+
+/-! # Homogeneous components of the circuit grammar
+
+In the grammar of Section 8.1 the degree-one states are arbitrary linear forms, and a
+multiplication gate of degree `d` convolves the component lists of its input gates.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+variable {σ R : Type*} [CommSemiring R]
+
+attribute [local instance] MvPolynomial.gradedAlgebra
+
+/-- The degree-`d` component of a product uses precisely the degree splits `i + j = d`. -/
+theorem homogeneousComponent_mul (d : ℕ) (p q : MvPolynomial σ R) :
+ homogeneousComponent d (p * q) = ∑ ij ∈ Finset.antidiagonal d,
+ homogeneousComponent ij.1 p * homogeneousComponent ij.2 q := by
+ classical
+ let A := homogeneousSubmodule σ R
+ have component (p : MvPolynomial σ R) (i : ℕ) :
+ (DirectSum.decompose A p i : MvPolynomial σ R) = homogeneousComponent i p :=
+ decomposition.decompose'_apply p i
+ simp_rw [← component]
+ rw [DirectSum.decompose_mul, DirectSum.coe_mul_apply]
+ apply Finset.sum_subset
+ · intro ij hij
+ exact Finset.mem_antidiagonal.mpr (Finset.mem_filter.mp hij).2
+ · intro ij hsum hout
+ have h : ij.1 ∉ (DirectSum.decompose A p).support ∨
+ ij.2 ∉ (DirectSum.decompose A q).support := by
+ by_contra! hin
+ exact hout (Finset.mem_filter.mpr ⟨Finset.mem_product.mpr hin,
+ Finset.mem_antidiagonal.mp hsum⟩)
+ rcases h with h | h <;> simp [DFinsupp.notMem_support_iff.mp h]
+
+/-- The linear component is the linear combination of the individual variables with
+coefficients given by their degree-one monomials. -/
+theorem homogeneousComponent_one_eq_sum [Fintype σ] (p : MvPolynomial σ R) :
+ homogeneousComponent 1 p = ∑ x, C (p.coeff (Finsupp.single x 1)) * X x := by
+ classical
+ ext1 m
+ rw [coeff_homogeneousComponent, coeff_sum]
+ by_cases h : m.degree = 1
+ · have hc : (Finsupp.toMultiset m).card = 1 := by rw [Finsupp.card_toMultiset]; exact h
+ obtain ⟨x, hx⟩ := Multiset.card_eq_one.mp hc
+ have hm : m = Finsupp.single x 1 := by
+ simpa using congrArg Multiset.toFinsupp hx
+ subst m
+ simp [coeff_X, Finsupp.single_left_inj one_ne_zero]
+ · have hx (x : σ) : Finsupp.single x 1 ≠ m := by
+ rintro rfl
+ exact h (Finsupp.degree_single _ _)
+ simp [h, coeff_X, hx]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GradedMonomialIndex.lean b/lean/OAI/Computability/VPVNP/GradedMonomialIndex.lean
new file mode 100644
index 0000000000..a027272413
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GradedMonomialIndex.lean
@@ -0,0 +1,234 @@
+import OAI.Computability.VPVNP.MacaulayRows
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Data.Nat.Count
+
+/-!
+# Streaming indices for bounded monomials
+
+Appendix D orders monomials by total degree and then lexicographically. The
+outer radix digit stores the degree, and the remaining digits store the
+exponents, with variable zero in the most significant position. Removing the
+codes with an inconsistent degree gives a dense indexing. Both directions use
+counter loops, so neither needs a list of the monomials.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex
+
+/-- Count admissible codes strictly below the bound. -/
+def countCodes (p : ℕ → Bool) (n : ℕ) : ℕ :=
+ Fin.foldl n (fun count i => if p i then count + 1 else count) 0
+
+theorem countCodes_eq (p : ℕ → Bool) (n : ℕ) :
+ countCodes p n = Nat.count (fun i => p i = true) n := by
+ induction n with
+ | zero => simp [countCodes]
+ | succ n ih =>
+ rw [countCodes, Fin.foldl_succ_last, Nat.count_succ, ← ih]
+ cases hp : p n <;> simp [countCodes, hp, Fin.last]
+
+/-- Scan an interval until the zero-based ordinal of a valid code is reached.
+The loop keeps only the current code, remaining interval and remaining ordinal. -/
+def selectCode (p : ℕ → Bool) : ℕ → ℕ → ℕ → ℕ
+ | first, 0, _ => first
+ | first, len + 1, k =>
+ if p first then
+ if k = 0 then first else selectCode p (first + 1) len (k - 1)
+ else selectCode p (first + 1) len k
+termination_by _ len _ => len
+
+theorem selectCode_spec (p : ℕ → Bool) (first len k : ℕ)
+ (hk : countCodes p first + k < countCodes p (first + len)) :
+ let c := selectCode p first len k
+ first ≤ c ∧ c < first + len ∧ p c = true ∧ countCodes p c = countCodes p first + k := by
+ induction len generalizing first k with
+ | zero => simp at hk
+ | succ len ih =>
+ have hstep : countCodes p (first + 1) = countCodes p first + if p first then 1 else 0 := by
+ rw [countCodes_eq, countCodes_eq, Nat.count_succ]
+ have hend : first + (len + 1) = first + 1 + len := by omega
+ by_cases hp : p first = true
+ · by_cases hz : k = 0
+ · subst k
+ simp [selectCode, hp]
+ · have h := ih (first + 1) (k - 1) (by rw [hstep, ite_eq_left hp, ← hend]; omega)
+ simp only [selectCode, ite_eq_left hp, ite_eq_right hz, hend]
+ rw [hstep, ite_eq_left hp] at h
+ exact ⟨by omega, h.2.1, h.2.2.1, by omega⟩
+ · have h := ih (first + 1) k (by simpa [hstep, hp, ← hend] using hk)
+ simp only [selectCode, ite_eq_right hp, hend]
+ rw [hstep, ite_eq_right hp, Nat.add_zero] at h
+ exact ⟨by omega, h.2⟩
+
+private def test {n : ℕ} (p : Fin n → Bool) (i : ℕ) : Bool :=
+ if h : i < n then p ⟨i,h⟩ else false
+
+/-- Dense numbering of the selected indices of a finite interval. -/
+def denseCount {n : ℕ} (p : Fin n → Bool) : ℕ := countCodes (test p) n
+
+private theorem selected_spec {n : ℕ} (p : Fin n → Bool) (k : Fin (denseCount p)) :
+ let c := selectCode (test p) 0 n k
+ c < n ∧ test p c = true ∧ countCodes (test p) c = k.val := by
+ have h := selectCode_spec (test p) 0 n k (by simpa [countCodes_eq, denseCount] using k.isLt)
+ simpa only [Nat.zero_add, countCodes_eq, Nat.count_zero] using h.2
+
+/-- The ordinal of each selected code and the inverse ordinal query.
+Both use scans of the same interval. -/
+def denseEquiv {n : ℕ} (p : Fin n → Bool) :
+ Fin (denseCount p) ≃ {i : Fin n // p i = true} where
+ toFun k := by
+ let c := selectCode (test p) 0 n k
+ have hc := selected_spec p k
+ exact ⟨⟨c, hc.1⟩, by simpa [test, hc.1] using hc.2.1⟩
+ invFun i := ⟨countCodes (test p) i.val.val, by
+ rw [denseCount, countCodes_eq, countCodes_eq]
+ exact Nat.count_strict_mono (by simpa [test, i.val.isLt] using i.prop) i.val.isLt⟩
+ left_inv k := Fin.ext (selected_spec p k).2.2
+ right_inv i := by
+ apply Subtype.ext
+ apply Fin.ext
+ let k : Fin (denseCount p) := ⟨countCodes (test p) i.val.val, by
+ rw [denseCount, countCodes_eq, countCodes_eq]
+ exact Nat.count_strict_mono (by simpa [test, i.val.isLt] using i.prop) i.val.isLt⟩
+ have h := selected_spec p k
+ change selectCode (test p) 0 n k = i.val.val
+ apply Nat.count_injective (p := fun j => test p j = true) h.2.1 (by simpa [test, i.val.isLt] using i.prop)
+ simpa only [countCodes_eq, k] using h.2.2
+
+/-- Unfiltered addresses consist of one degree digit and `t` exponent digits. -/
+def rawSize (t D : ℕ) := (D + 1) * (D + 1) ^ t
+
+private def split {t D : ℕ} (c : Fin (rawSize t D)) :
+ Fin (D + 1) × Fin ((D + 1) ^ t) := finProdFinEquiv.symm c
+
+/-- Read a single exponent by radix division and remainder. -/
+def digit {t D : ℕ} (c : Fin (rawSize t D)) (i : Fin t) : ℕ :=
+ (finFunctionFinEquiv.symm (split c).2 i.rev).val
+
+/-- Test that the exponent digits of a raw monomial index sum to its recorded total degree. -/
+def admissible {t D : ℕ} (c : Fin (rawSize t D)) : Bool :=
+ decide ((∑ i, digit c i) = (split c).1.val)
+
+/-- Number of monomials through degree `D`, obtained without a monomial table. -/
+def size (t D : ℕ) := denseCount (@admissible t D)
+
+/-- Build the formal exponent vector for a tuple in the finite label alphabet. -/
+def exponentVector {t : ℕ} (f : Fin t → ℕ) : Fin t →₀ ℕ where
+ toFun := f
+ support := Finset.univ.filter fun i => f i ≠ 0
+ mem_support_toFun := by simp
+
+private def degree {t D : ℕ} (a : BoundedMonomial t D) : Fin (D + 1) :=
+ ⟨a.val.sum (fun _ e => e), Nat.lt_succ_of_le a.prop⟩
+
+/-- Graded-lex key of a bounded monomial, before removing unused codes. -/
+def rawCode {t D : ℕ} (a : BoundedMonomial t D) : Fin (rawSize t D) :=
+ finProdFinEquiv (degree a, finFunctionFinEquiv (fun i => a.encode i.rev))
+
+private theorem split_rawCode {t D : ℕ} (a : BoundedMonomial t D) :
+ split (rawCode a) = (degree a, finFunctionFinEquiv (fun i => a.encode i.rev)) :=
+ finProdFinEquiv.symm_apply_apply _
+
+@[simp] theorem digit_rawCode {t D : ℕ} (a : BoundedMonomial t D) (i : Fin t) :
+ digit (rawCode a) i = a.val i := by
+ simp [digit, split_rawCode, BoundedMonomial.encode]
+
+theorem admissible_rawCode {t D : ℕ} (a : BoundedMonomial t D) :
+ admissible (rawCode a) = true := by
+ simp [admissible, split_rawCode, degree, Finsupp.sum_fintype]
+
+private def decodeRaw {t D : ℕ} (c : {c : Fin (rawSize t D) // admissible c = true}) :
+ BoundedMonomial t D := by
+ refine ⟨exponentVector (digit c.val), ?_⟩
+ have h : (∑ i, digit c.val i) = (split c.val).1.val := of_decide_eq_true c.prop
+ rw [Finsupp.sum_fintype _ _ (fun _ => rfl)]
+ exact h.le.trans (Nat.le_of_lt_succ (split c.val).1.isLt)
+
+private def validEquiv (t D : ℕ) :
+ {c : Fin (rawSize t D) // admissible c = true} ≃ BoundedMonomial t D where
+ toFun := decodeRaw
+ invFun a := ⟨rawCode a, admissible_rawCode a⟩
+ right_inv a := Subtype.ext (Finsupp.ext (digit_rawCode a))
+ left_inv c := by
+ apply Subtype.ext
+ apply finProdFinEquiv.symm.injective
+ change split (rawCode (decodeRaw c)) = split c.val
+ rw [split_rawCode]
+ apply Prod.ext
+ · apply Fin.ext
+ change (exponentVector (digit c.val)).sum (fun _ e => e) = _
+ rw [Finsupp.sum_fintype _ _ (fun _ => rfl)]
+ exact of_decide_eq_true c.prop
+ · apply finFunctionFinEquiv.symm.injective
+ rw [Equiv.symm_apply_apply]
+ funext i
+ apply Fin.ext
+ change digit c.val i.rev = _
+ simp [digit]
+
+/-- Computable dense graded-lex enumeration of all bounded monomials. -/
+def enumeration (t D : ℕ) : Fin (size t D) ≃ BoundedMonomial t D :=
+ (denseEquiv (@admissible t D)).trans (validEquiv t D)
+
+/-- Read the exponent vector at a dense ordinal, without constructing a support set. -/
+def indexedDigits {t D : ℕ} (k : Fin (size t D)) : Fin t → ℕ :=
+ let c := (denseEquiv (@admissible t D) k).val
+ digit c
+
+theorem indexedDigits_eq {t D : ℕ} (k : Fin (size t D)) (i : Fin t) :
+ indexedDigits k i = (enumeration t D k).val i := rfl
+
+/-- The outer radix digit stores the total degree. -/
+theorem degree_eq_outer {t D : ℕ} (a : BoundedMonomial t D) :
+ (rawCode a).val / (D + 1) ^ t = a.val.sum (fun _ e => e) :=
+ congrArg (fun x : Fin (D+1) × Fin ((D+1)^t) => x.1.val) (split_rawCode a)
+
+/-- Dense ordinals have strictly increasing graded radix keys. -/
+theorem enumeration_strictMono (t D : ℕ) : StrictMono (rawCode ∘ enumeration t D) := by
+ intro i j hij
+ have hi := selected_spec (@admissible t D) i
+ have hj := selected_spec (@admissible t D) j
+ have hlt : countCodes (test (@admissible t D)) (selectCode (test (@admissible t D)) 0 (rawSize t D) i) <
+ countCodes (test (@admissible t D)) (selectCode (test (@admissible t D)) 0 (rawSize t D) j) := by
+ rw [hi.2.2, hj.2.2]; exact hij
+ simp only [countCodes_eq] at hlt
+ have h := Nat.lt_of_count_lt_count hlt
+ have key (k : Fin (size t D)) :
+ (rawCode (enumeration t D k)).val = selectCode (test (@admissible t D)) 0 (rawSize t D) k := by
+ exact congrArg (fun c : {c : Fin (rawSize t D) // admissible c = true} => c.val.val)
+ ((validEquiv t D).symm_apply_apply (denseEquiv _ k))
+ change (rawCode (enumeration t D i)).val < (rawCode (enumeration t D j)).val
+ simpa only [key] using h
+
+/-- The constant monomial gives dense ordinal zero, including when there are
+no variables or when the degree bound is zero. -/
+def constant (t D : ℕ) : BoundedMonomial t D := ⟨0, by simp⟩
+
+theorem constant_ordinal (t D : ℕ) : ((enumeration t D).symm (constant t D)).val = 0 := by
+ have hcode : (rawCode (constant t D)).val = 0 := by
+ simp [rawCode, constant, degree, BoundedMonomial.encode]
+ change countCodes _ (rawCode (constant t D)).val = 0
+ simp [hcode, countCodes_eq]
+
+theorem size_pos (t D : ℕ) : 0 < size t D := ((enumeration t D).symm (constant t D)).pos
+
+theorem enumeration_first (t D : ℕ) :
+ enumeration t D ⟨0, size_pos t D⟩ = constant t D :=
+ (enumeration t D).eq_symm_apply.mp (Fin.ext (constant_ordinal t D).symm)
+
+theorem size_eq_card (t D : ℕ) : size t D = Fintype.card (BoundedMonomial t D) := by
+ simpa using Fintype.card_congr (enumeration t D)
+
+theorem rawSize_le_pow {t D b : ℕ} (h : D + 1 ≤ 2 ^ b) :
+ rawSize t D ≤ 2 ^ (b * (t + 1)) := by
+ rw [pow_mul, pow_succ']
+ exact Nat.mul_le_mul h (Nat.pow_le_pow_left h t)
+
+end RadicalCertificate.MonomialIndex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrammarAssignment.lean b/lean/OAI/Computability/VPVNP/GrammarAssignment.lean
new file mode 100644
index 0000000000..a300f4ea4f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrammarAssignment.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.CircuitGrammar
+import OAI.Computability.VPVNP.GrammarLabels
+
+/-!
+# The coefficient equations at a small-circuit length
+
+At a length where the universal polynomial has a circuit of the stipulated size, the
+positive-degree grammar of Section 8.1 admits one assignment of all labels satisfying
+every paired coefficient equation simultaneously. The width and start slot below are
+those of the paper. The start slot numbered one there is zero in Lean.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+/-- The width from Section 8.1 accommodates all variables, gates and the designated output. -/
+theorem parseSlots_le (n C s : ℕ) (hn : 2 ≤ n) (hC : 1 ≤ C) (hs : s ≤ n ^ C) :
+ Fintype.card (Fin n × Bool) + s + 1 ≤ n ^ (C + 5) := by
+ simp only [Fintype.card_prod, Fintype.card_fin, Fintype.card_bool, pow_add]
+ have hnC : n ≤ n ^ C := Nat.le_self_pow (by omega) n
+ have h5 : 4 ≤ n ^ 5 := le_trans (by decide : 4 ≤ 2 ^ 5) (Nat.pow_le_pow_left hn 5)
+ have := Nat.mul_le_mul_left (n ^ C) h5
+ omega
+
+/-- A small circuit for the universal polynomial gives an assignment in its own
+coefficient ring whose output entries are exactly the machine path counts. -/
+theorem exists_pathCount_parseGrammar {R : Type*} [CommRing R] {n C s : ℕ}
+ (hn : 2 ≤ n) (hC : 1 ≤ C) (hs : s ≤ n ^ C)
+ (c : Circuit R (Fin n × Bool) s)
+ (hc : c.polynomial = map (Int.castRingHom R) (P n)) :
+ ∃ G : ParseGrammar R (Fin n × Bool) (Fin (n ^ (C + 5))) n,
+ ∀ x : Fin n → Bool,
+ (G.eval ⟨n - 1, by omega⟩ ⟨0, pow_pos (by omega) _⟩).coeff (pairedExponent x) =
+ (acceptingCount x : R) := by
+ obtain ⟨G, hG⟩ := c.exists_parseGrammar_fin n (n ^ (C + 5)) (parseSlots_le n C s hn hC hs)
+ refine ⟨G, fun x ↦ ?_⟩
+ have hout := hG ⟨n - 1, by omega⟩
+ have hdeg : n - 1 + 1 = n := by omega
+ rw [hout, hdeg, hc, map_P, homogeneousComponent_eq_self (pairedPolynomial_isHomogeneous _),
+ coeff_pairedPolynomial]
+
+/-- Equation (8.1): one assignment to the universal integer parameter polynomials
+works for all queried words. The assignment is obtained from the actual circuit. -/
+theorem pathCount_labelEquations {R : Type*} [CommRing R] {n C s : ℕ}
+ (hn : 2 ≤ n) (hC : 1 ≤ C) (hs : s ≤ n ^ C)
+ (c : Circuit R (Fin n × Bool) s)
+ (hc : c.polynomial = map (Int.castRingHom R) (P n)) :
+ ∃ labels : GrammarLabel (Fin n × Bool) (Fin (n ^ (C + 5))) n → R,
+ ∀ x : Fin n → Bool,
+ eval₂Hom (Int.castRingHom R) labels
+ (labelQuery ⟨n - 1, by omega⟩ ⟨0, pow_pos (by omega) _⟩ x) = (acceptingCount x : R) := by
+ obtain ⟨G, hG⟩ := exists_pathCount_parseGrammar hn hC hs c hc
+ exact ⟨G.labelValue, fun x ↦ (G.specialize_labelQuery _ _ x).trans (hG x)⟩
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrammarCoefficientBounds.lean b/lean/OAI/Computability/VPVNP/GrammarCoefficientBounds.lean
new file mode 100644
index 0000000000..14bf376d5a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrammarCoefficientBounds.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.GrammarSize
+import OAI.Computability.VPVNP.ParseHistogram
+
+/-!
+# Bounds for the coefficients of the label equations
+
+The coefficient of a label monomial in the integer query `Bₓ` counts ordered
+parses with that exact histogram whose terminals match the input word. The number
+of such trees bounds every coefficient uniformly over subsequent choices of scalars.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial ParseGrammar
+open scoped Classical
+
+variable {H : Type*} [Fintype H] {n m : ℕ}
+
+/-- The integer label coefficient counts matching trees, once per ordered parse. -/
+theorem coeff_labelQuery_eq_card (d : Fin n) (h : H) (x : Fin m → Bool)
+ (e : GrammarLabel (Fin m × Bool) H n →₀ ℕ) :
+ (labelQuery d h x).coeff e =
+ ((Finset.univ.filter fun p : OrderedParse (Fin m × Bool) H d.val ↦
+ (p.leaves : Multiset (Fin m × Bool)) = (List.ofFn (fun i ↦ (i, x i)) : Multiset _) ∧
+ histogram d h p = e).card : ℤ) := by
+ classical
+ rw [labelQuery, pairedExponent,
+ coeff_eval_query_multiset (universalGrammar (Fin m × Bool) H n) d h (fun i ↦ (i, x i)),
+ coeff_sum, ← Finset.sum_boole]
+ refine Finset.sum_congr rfl fun p _ ↦ ?_
+ rw [universalGrammar_weight_eq_histogram]
+ split_ifs <;> simp_all [coeff_monomial]
+
+/-- Every queried coefficient is nonnegative and at most the total count of ordered
+parses. In particular its bit length is bounded independently of field constants. -/
+theorem coeff_labelQuery_bounds (d : Fin n) (h : H) (x : Fin m → Bool)
+ (e : GrammarLabel (Fin m × Bool) H n →₀ ℕ) :
+ 0 ≤ (labelQuery d h x).coeff e ∧
+ (labelQuery d h x).coeff e ≤
+ (4 ^ d.val * Fintype.card H ^ (2 * d.val) * Fintype.card (Fin m × Bool) ^ (d.val + 1) : ℕ) := by
+ rw [coeff_labelQuery_eq_card]
+ constructor
+ · positivity
+ · exact_mod_cast (Finset.card_filter_le _ _).trans
+ (Finset.card_univ.le.trans (card_orderedParse_le (Fin m × Bool) H d.val))
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrammarDiagonal.lean b/lean/OAI/Computability/VPVNP/GrammarDiagonal.lean
new file mode 100644
index 0000000000..3b27793864
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrammarDiagonal.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.Diagonal
+import OAI.Computability.VPVNP.PairCoefficient
+import OAI.Computability.VPVNP.UniversalMachine
+
+/-!
+# The diagonal criterion for the explicit grammar and machine
+
+In Proposition 9.1 the live sites run the clocked machine defining the
+integer family. For each primed pair we use its actual universal grammar
+label queries and count all joint parse choices with the nominated histogram.
+The first-half gadget paths and the tail evaluator still have to realize
+their specified path multiplicities within the program's budget.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace GrammarDiagonal
+
+open MvPolynomial
+open scoped Classical
+
+variable {Cut Pair Site H A k : Type*} {Internal : Pair → Type*} {n m w : ℕ}
+variable [Fintype Cut] [Fintype Pair] [DecidableEq Pair] [Fintype Site] [Fintype H]
+variable [∀ i, Fintype (Internal i)] [Field k] [CommRing A] [Algebra k A]
+
+/-- A nomination gives one fixed-width counter for every production label.
+All possible counter settings are included. -/
+abbrev Nomination (m n w : ℕ) (H : Type*) :=
+ GrammarLabel (Fin m × Bool) H n → Fin (2 ^ w)
+
+/-- The integer coefficient of the nominated histogram, counted by the pair
+parser for the fixed incident exterior bits. -/
+noncomputable def multiplicity {Bits : Type*} [Fintype Bits] (d : Fin n) (h : H)
+ (x : Bits → Site → Fin m → Bool)
+ (μ : Nomination m n w H) : ℕ :=
+ Fintype.card {c : PairCoefficient.Choices H d x //
+ ∀ a, PairCoefficient.jointHistogram d h x c a = (μ a).val}
+
+variable {Path : Cut → Pair → Nomination m n w H → Type*}
+variable [∀ ξ i μ, Fintype (Path ξ i μ)] [DecidableEq (GrammarLabel (Fin m × Bool) H n)]
+
+/-- The two-mode simulation cannot coexist with the grammar label equations.
+This is the finite algebraic part of Proposition 9.1 with the paper's site
+counts, complete nomination ranges, and exact pair histogram multiplicities. -/
+theorem noGrammarSimulation
+ (d : Fin n) (h : H) (x : Cut → (i : Pair) → Internal i → Site → Fin m → Bool)
+ (value : GrammarLabel (Fin m × Bool) H n → A)
+ (heq : ∀ input, eval₂Hom (Int.castRingHom A) value (labelQuery d h input) = (acceptingCount input : A))
+ (hfit : Fintype.card Site * (2 * d.val + 1) < 2 ^ w)
+ (Φ : A →ₗ[k] k) (hunit : Φ 1 = 1)
+ (gadget : ∀ ξ i μ, Path ξ i μ → A)
+ (hsim : ∀ ξ i μ, ∑ q, gadget ξ i μ q = (multiplicity d h (x ξ i) μ : A))
+ (tail : ∀ ξ (hs : Pair → Nomination m n w H), ((i : Pair) → Path ξ i (hs i)) → ℕ)
+ (heval : ∀ ξ hs q, (tail ξ hs q : k) =
+ Φ (∏ i, (∏ a, value a ^ (hs i a).val) * gadget ξ i (hs i) (q i))) :
+ IsEmpty (Diagonal.OriginalPaths (fun ξ i s v => acceptingCount (x ξ i s v)) ≃
+ Diagonal.LiveModes tail) := by
+ refine Diagonal.noPairedChainSimulation (Path := Path) (Internal := Internal)
+ (fun ξ i s v => acceptingCount (x ξ i s v)) (fun ξ i s v =>
+ eval₂Hom (Int.castRingHom A) value (labelQuery d h (x ξ i s v))) Φ hunit
+ (fun μ => ∏ a, value a ^ (μ a).val) (fun ξ i μ => multiplicity d h (x ξ i) μ)
+ gadget tail (fun ξ i s v => heq (x ξ i s v)) ?_ hsim heval
+ intro ξ i
+ simpa only [multiplicity, PairCoefficient.jointPolynomial, map_sum, map_prod] using
+ (PairCoefficient.evaluate_by_nominations d h (x ξ i) value w hfit).symm
+
+end GrammarDiagonal
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrammarLabels.lean b/lean/OAI/Computability/VPVNP/GrammarLabels.lean
new file mode 100644
index 0000000000..f4e13aeeec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrammarLabels.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.ParseGrammar
+import OAI.Computability.VPVNP.PairedFamily
+
+/-!
+# Integer polynomials in the grammar labels
+
+In §8.1 of *VP and VNP differ over every field*, the label equations (8.1) use
+one indeterminate per terminal or ordered binary production. Here `labelQuery`
+is the polynomial `Bₓ` read at a specified state. Every parse with `a` leaves
+contributes exactly `2a - 1` label factors.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial ParseGrammar
+
+/-- A terminal production is indexed by its state and variable. A binary production
+records the parent layer and state, the split, and the two ordered child states. -/
+abbrev GrammarLabel (V H : Type*) (n : ℕ) := (H × V) ⊕ (Σ d : Fin n, H × Fin d.val × H × H)
+
+/-- The state table over the integer polynomial ring with distinct indeterminate labels. -/
+noncomputable def universalGrammar (V H : Type*) (n : ℕ) :
+ ParseGrammar (MvPolynomial (GrammarLabel V H n) ℤ) V H n where
+ terminal h v := X (.inl (h, v))
+ binary d h b i j := X (.inr ⟨d, h, b, i, j⟩)
+
+variable {V H R : Type*} {n m : ℕ}
+
+/-- The scalar assigned to each production label by a given grammar. -/
+def ParseGrammar.labelValue (G : ParseGrammar R V H n) : GrammarLabel V H n → R
+ | .inl (h, v) => G.terminal h v
+ | .inr ⟨d, h, b, i, j⟩ => G.binary d h b i j
+
+/-- Specialize the universal integer labels to the entries of `G`. -/
+noncomputable def ParseGrammar.specializeLabels [CommRing R] (G : ParseGrammar R V H n) :
+ MvPolynomial (GrammarLabel V H n) ℤ →+* R := eval₂Hom (Int.castRingHom R) G.labelValue
+
+variable [Fintype V] [Fintype H]
+
+/-- Count all scalar labels, keeping the split index of each layer explicit. -/
+theorem card_grammarLabel (n : ℕ) : Fintype.card (GrammarLabel V H n) =
+ Fintype.card H * Fintype.card V + (∑ d : Fin n, d.val) * Fintype.card H ^ 3 := by
+ simp only [GrammarLabel, Fintype.card_sum, Fintype.card_sigma, Fintype.card_prod,
+ Fintype.card_fin, Finset.sum_mul]
+ congr 1
+ exact Finset.sum_congr rfl fun d _ ↦ by ring
+
+/-- Substituting the scalar labels commutes with evaluation at each state. -/
+theorem ParseGrammar.specialize_universalGrammar [CommRing R] (G : ParseGrammar R V H n)
+ (d : Fin n) (h : H) :
+ MvPolynomial.map G.specializeLabels ((universalGrammar V H n).eval d h) = G.eval d h := by
+ symm
+ apply G.eval_eq_of_recurrence
+ (fun d h ↦ MvPolynomial.map G.specializeLabels ((universalGrammar V H n).eval d h))
+ · intro d h hd
+ rw [eval_terminal _ hd]
+ simp [universalGrammar, specializeLabels, labelValue]
+ · intro d h hd
+ rw [eval_binary _ hd]
+ simp [universalGrammar, specializeLabels, labelValue]
+
+/-- Specialization of every formal coefficient of the universal grammar. -/
+theorem ParseGrammar.specialize_coefficient [CommRing R] (G : ParseGrammar R V H n)
+ (d : Fin n) (h : H) (e : V →₀ ℕ) :
+ G.specializeLabels (((universalGrammar V H n).eval d h).coeff e) = (G.eval d h).coeff e := by
+ rw [← coeff_map, G.specialize_universalGrammar]
+
+/-- The integer coefficient query `Bₓ` of (8.1). At the start state the layer has
+value `m - 1`, and the queried polynomial has degree `m` in the paired variables. -/
+noncomputable def labelQuery (d : Fin n) (h : H) (x : Fin m → Bool) :
+ MvPolynomial (GrammarLabel (Fin m × Bool) H n) ℤ :=
+ ((universalGrammar (Fin m × Bool) H n).eval d h).coeff (pairedExponent x)
+
+theorem ParseGrammar.specialize_labelQuery [CommRing R] (G : ParseGrammar R (Fin m × Bool) H n)
+ (d : Fin n) (h : H) (x : Fin m → Bool) :
+ G.specializeLabels (labelQuery d h x) = (G.eval d h).coeff (pairedExponent x) :=
+ G.specialize_coefficient d h (pairedExponent x)
+
+omit [Fintype V] [Fintype H] in
+/-- Each tree uses one label per terminal leaf and one per binary internal vertex. -/
+theorem universalGrammar_weight_isHomogeneous (d : Fin n) (h : H) (p : OrderedParse V H d.val) :
+ ((universalGrammar V H n).weight d h p).IsHomogeneous (2 * d.val + 1) := by
+ induction d using (measure (fun d : Fin n ↦ d.val)).wf.induction generalizing h with
+ | h d ih =>
+ obtain ⟨k, hk⟩ := d
+ cases k with
+ | zero =>
+ cases p with
+ | leaf v =>
+ rw [weight_leaf]
+ exact isHomogeneous_X ℤ (.inl (h, v) : GrammarLabel V H n)
+ | succ k =>
+ cases p with
+ | node b i j l r =>
+ let d : Fin n := ⟨k + 1, hk⟩
+ rw [weight_node]
+ have hl := ih (leftDegree d b) (leftDegree_lt d b) i l
+ have hr := ih (rightDegree d b) (rightDegree_lt d b) j r
+ have hb := isHomogeneous_X ℤ (.inr ⟨d, h, b, i, j⟩ : GrammarLabel V H n)
+ convert (hb.mul hl).mul hr using 1
+ · rfl
+ · have := split_degrees d b
+ change 2 * d.val + 1 = _
+ omega
+
+/-- Reading any coefficient in the input variables leaves a homogeneous polynomial
+in the production labels. -/
+theorem universalGrammar_coeff_isHomogeneous (d : Fin n) (h : H) (e : V →₀ ℕ) :
+ (((universalGrammar V H n).eval d h).coeff e).IsHomogeneous (2 * d.val + 1) := by
+ rw [eval_eq_sum, coeff_sum]
+ refine IsHomogeneous.sum _ _ _ fun p _ ↦ ?_
+ rw [coeff_C_mul]
+ let P : MvPolynomial V ℤ := (p.leaves.map X).prod
+ have hcoeff : ((p.leaves.map (X (R := MvPolynomial (GrammarLabel V H n) ℤ))).prod).coeff e =
+ C (P.coeff e) := by
+ rw [← coeff_map]
+ simp only [P, map_list_prod, List.map_map, Function.comp_def, MvPolynomial.map_X]
+ rw [hcoeff]
+ simpa using (universalGrammar_weight_isHomogeneous d h p).mul
+ (isHomogeneous_C (GrammarLabel V H n) (P.coeff e))
+
+theorem labelQuery_isHomogeneous (d : Fin n) (h : H) (x : Fin m → Bool) :
+ (labelQuery d h x).IsHomogeneous (2 * d.val + 1) :=
+ universalGrammar_coeff_isHomogeneous d h (pairedExponent x)
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrammarSize.lean b/lean/OAI/Computability/VPVNP/GrammarSize.lean
new file mode 100644
index 0000000000..b336e16559
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrammarSize.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.GrammarLabels
+import Mathlib.Combinatorics.Enumerative.Catalan.Basic
+
+/-! # Size bounds for the ordered circuit grammar
+
+A tree at layer `d` has `d` binary productions and `d + 1` terminals. There
+are Catalan many ordered shapes, two state choices at each binary production,
+and one variable choice at each terminal. The labels are shared among all parses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open ParseGrammar
+
+variable (V H : Type*) [Fintype V] [Fintype H]
+
+/-- Number of ordered parses with fixed root state. -/
+theorem card_orderedParse (d : ℕ) : Fintype.card (OrderedParse V H d) =
+ catalan d * Fintype.card H ^ (2 * d) * Fintype.card V ^ (d + 1) := by
+ induction d using Nat.strong_induction_on with
+ | h d ih =>
+ cases d with
+ | zero => simpa using Fintype.card_congr (OrderedParse.leafEquiv (V := V) (H := H))
+ | succ d =>
+ rw [Fintype.card_congr (OrderedParse.nodeEquiv (V := V) (H := H) d),
+ Fintype.card_sigma, catalan_succ, Finset.sum_mul, Finset.sum_mul]
+ apply Finset.sum_congr rfl
+ intro b _
+ have hsplit : b.val ≤ d := Nat.le_of_lt_succ b.isLt
+ simp only [Fintype.card_prod, ih b.val b.isLt, ih (d - b.val) (by omega)]
+ have hs : 2 * (d + 1) = 2 * b.val + 2 * (d - b.val) + 1 + 1 := by omega
+ have hv : d + 1 + 1 = (b.val + 1) + (d - b.val + 1) := by omega
+ simp only [hs, hv, pow_add, pow_one]
+ ring
+
+/-- The shape count at layer `d` is at most `4 ^ d`. -/
+theorem catalan_le_four_pow (d : ℕ) : catalan d ≤ 4 ^ d := by
+ rw [catalan_eq_centralBinom_div]
+ exact (Nat.div_le_self _ _).trans (Nat.centralBinom_le_four_pow d)
+
+/-- A bound on the number of parses prior to imposing a coefficient query. -/
+theorem card_orderedParse_le (d : ℕ) : Fintype.card (OrderedParse V H d) ≤
+ 4 ^ d * Fintype.card H ^ (2 * d) * Fintype.card V ^ (d + 1) := by
+ rw [card_orderedParse]
+ exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (catalan_le_four_pow d))
+
+/-- The grammar has polynomially many scalar labels in the variable count, the
+state count and the degree cutoff. -/
+theorem card_grammarLabel_le (n : ℕ) : Fintype.card (GrammarLabel V H n) ≤
+ Fintype.card H * Fintype.card V + n ^ 2 * Fintype.card H ^ 3 := by
+ rw [card_grammarLabel]
+ apply Nat.add_le_add_left
+ apply Nat.mul_le_mul_right
+ calc
+ (∑ d : Fin n, d.val) ≤ ∑ _ : Fin n, n := Finset.sum_le_sum fun d _ => d.isLt.le
+ _ = n ^ 2 := by simp [pow_two]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GraphCertificateExtraction.lean b/lean/OAI/Computability/VPVNP/GraphCertificateExtraction.lean
new file mode 100644
index 0000000000..9abb92611f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GraphCertificateExtraction.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.NullstellensatzGraph
+import Mathlib.Algebra.MvPolynomial.Equiv
+import Mathlib.Algebra.MvPolynomial.NoZeroDivisors
+
+/-! # Bounded certificates from a monic graph relation
+
+Replace the normalized graph coordinates by their linear parts. The difference
+between the two substitutions is an explicit combination of the equations.
+Its multipliers grow in degree by at most the maximum substitution degree for
+each variable in a monomial. Taking the leading power of the graph parameter
+then produces a certificate for one.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+open MvPolynomial
+
+variable {E I V W : Type*} [Field E] [Fintype I]
+
+private theorem bounded_substitution_difference
+ (F : I → MvPolynomial W E) (a b : V → MvPolynomial W E) (D : ℕ)
+ (ha : ∀ v, (a v).totalDegree ≤ D) (hb : ∀ v, (b v).totalDegree ≤ D)
+ (c : V → I → MvPolynomial W E) (hc : ∀ v i, (c v i).totalDegree ≤ D)
+ (hdiff : ∀ v, ∑ i, c v i * F i = a v - b v) (p : MvPolynomial V E) :
+ ∃ A : I → MvPolynomial W E, (∀ i, (A i).totalDegree ≤ D * p.totalDegree) ∧
+ ∑ i, A i * F i = aeval a p - aeval b p := by
+ classical
+ let property (q : MvPolynomial V E) :=
+ (aeval a q).totalDegree ≤ D * q.totalDegree ∧
+ ∃ A : I → MvPolynomial W E, (∀ i, (A i).totalDegree ≤ D * q.totalDegree) ∧
+ ∑ i, A i * F i = aeval a q - aeval b q
+ have mono : ∀ s r, property (monomial s r) := by
+ apply induction_on_monomial
+ · intro r
+ exact ⟨by simp, fun _ => 0, by simp, by simp⟩
+ · intro q v hq
+ by_cases hz : q = 0
+ · subst q
+ exact ⟨by simp, fun _ => 0, by simp, by simp⟩
+ obtain ⟨hdeg, A, hA, hAsum⟩ := hq
+ have htotal : (q * X v).totalDegree = q.totalDegree + 1 := by
+ rw [totalDegree_mul_of_isDomain hz (X_ne_zero v), totalDegree_X]
+ simp only [property, map_mul, aeval_X, htotal, Nat.mul_add, Nat.mul_one]
+ refine ⟨(totalDegree_mul _ _).trans (Nat.add_le_add hdeg (ha v)), ?_⟩
+ refine ⟨fun i => aeval a q * c v i + A i * b v, fun i => ?_, ?_⟩
+ · exact (totalDegree_add ..).trans (max_le
+ ((totalDegree_mul ..).trans (Nat.add_le_add hdeg (hc v i)))
+ ((totalDegree_mul ..).trans (Nat.add_le_add (hA i) (hb v))))
+ · simp only [add_mul, Finset.sum_add_distrib]
+ calc
+ _ = aeval a q * (∑ i, c v i * F i) + (∑ i, A i * F i) * b v := by
+ rw [Finset.mul_sum, Finset.sum_mul]
+ congr 1 <;> apply Finset.sum_congr rfl <;> intros <;> ring
+ _ = _ := by rw [hdiff, hAsum]; ring
+ choose A hA heq using fun s => (mono s (p.coeff s)).2
+ refine ⟨fun i => ∑ s ∈ p.support, A s i, fun i => totalDegree_finsetSum_le fun s hs => ?_, ?_⟩
+ · apply (hA s i).trans
+ exact Nat.mul_le_mul_left _ ((totalDegree_monomial_le s _).trans (le_totalDegree hs))
+ · simp only [Finset.sum_mul]
+ rw [Finset.sum_comm]
+ simp_rw [heq, Finset.sum_sub_distrib, ← map_sum, ← p.as_sum]
+
+private theorem separate_parameter {n : ℕ} (p : MvPolynomial (Fin n) E) :
+ finSuccEquiv E n (rename Fin.succ p) = Polynomial.C p := by
+ induction p using MvPolynomial.induction_on with
+ | C x => simp [finSuccEquiv_apply]
+ | add p q hp hq => simp [hp,hq]
+ | mul_X p i hp => simp [hp, finSuccEquiv_X_succ]
+
+/-- Replacing the normalized coordinates by polynomials independent of the
+parameter amounts to mapping the coefficients of the univariate relation. -/
+private theorem specialize_parameter {n m : ℕ} (L : Fin m → MvPolynomial (Fin n) E)
+ (U : MvPolynomial (Fin (m+1)) E) :
+ finSuccEquiv E n (aeval (Fin.cons (X 0) (fun j => rename Fin.succ (L j))) U) =
+ Polynomial.map (aeval L).toRingHom (finSuccEquiv E m U) := by
+ induction U using MvPolynomial.induction_on with
+ | C r => simp [finSuccEquiv_apply]
+ | add p q hp hq => simp [hp,hq]
+ | mul_X p i hp =>
+ simp only [map_mul, aeval_X, Polynomial.map_mul, hp]
+ congr 1
+ refine Fin.cases ?_ (fun j => ?_) i
+ · simp [finSuccEquiv_X_zero]
+ · simp [finSuccEquiv_X_succ, separate_parameter]
+
+/-- Extract the bounded certificate for an inconsistent system from a monic
+relation on a linear Noether normalization of its graph. -/
+theorem graph_monic_certificate {n m H D : ℕ} (F : I → MvPolynomial (Fin n) E)
+ (hF : ∀ i, (F i).totalDegree ≤ D)
+ (Q : Fin m → MvPolynomial (Fin (n+1)) E)
+ (hQ : ∀ j, Q j ∈ Submodule.span E (Set.range (graphGenerator F)))
+ (U : MvPolynomial (Fin (m+1)) E) (hU : U.totalDegree ≤ H)
+ (hmonic : (finSuccEquiv E m U).Monic)
+ (hzero : aeval (Fin.cons (X 0) Q) U = 0) :
+ ∃ A : I → MvPolynomial (Fin n) E, (∀ i, (A i).totalDegree ≤ (D+1)*H) ∧
+ ∑ i, A i * F i = 1 := by
+ classical
+ choose l c hl using fun j => graphGenerator_span_decompose F (hQ j)
+ let L (j : Fin m) : MvPolynomial (Fin n) E := ∑ i, C (l j i) * X i
+ have hlift (j) : rename Fin.succ (L j) = ∑ i, C (l j i) * X i.succ := by simp [L]
+ let a : Fin (m+1) → MvPolynomial (Fin (n+1)) E := Fin.cons (X 0) (fun j => rename Fin.succ (L j))
+ let b : Fin (m+1) → MvPolynomial (Fin (n+1)) E := Fin.cons (X 0) Q
+ let diff : Fin (m+1) → I → MvPolynomial (Fin (n+1)) E :=
+ Fin.cons (fun _ => 0) (fun j i => -(X 0 * C (c j i)))
+ have ha (i) : (a i).totalDegree ≤ D+1 := by
+ refine Fin.cases (by simp [a]) (fun j => ?_) i
+ simp only [a, Fin.cons_succ, hlift]
+ apply totalDegree_finsetSum_le
+ intro u _
+ simpa using (totalDegree_mul (C (l j u) : MvPolynomial (Fin (n+1)) E) (X u.succ)).trans
+ (by simp)
+ have hb (i) : (b i).totalDegree ≤ D+1 := by
+ exact Fin.cases (by simp [b]) (fun j => graphGenerator_span_degree F hF (hQ j)) i
+ have hdiff (i) : ∑ v, diff i v * rename Fin.succ (F v) = a i - b i := by
+ refine Fin.cases (by simp [a,b,diff]) (fun j => ?_) i
+ simp only [diff, a, b, Fin.cons_succ, hl, hlift, neg_mul, Finset.sum_neg_distrib]
+ rw [Finset.mul_sum]
+ simp only [mul_assoc]
+ abel
+ have hd (i j) : (diff i j).totalDegree ≤ D+1 := by
+ refine Fin.cases (by simp [diff]) (fun u => ?_) i
+ simp only [diff, Fin.cons_succ, totalDegree_neg]
+ exact (totalDegree_mul ..).trans (by simp)
+ obtain ⟨M, hM, he⟩ := bounded_substitution_difference (fun i => rename Fin.succ (F i))
+ a b (D+1) ha hb diff hd hdiff U
+ have hz : aeval b U = 0 := hzero
+ rw [hz, sub_zero] at he
+ let d := (finSuccEquiv E m U).natDegree
+ refine ⟨fun i => (finSuccEquiv E n (M i)).coeff d, fun i => ?_, ?_⟩
+ · by_cases hc : (finSuccEquiv E n (M i)).coeff d = 0
+ · simp [hc]
+ · have := totalDegree_coeff_finSuccEquiv_add_le (M i) d hc
+ change ((finSuccEquiv E n (M i)).coeff d).totalDegree ≤ _
+ exact ((Nat.le_add_right _ d).trans this).trans ((hM i).trans (Nat.mul_le_mul_left _ hU))
+ · have ht := congrArg (fun p => (finSuccEquiv E n p).coeff d) he
+ change _ = (finSuccEquiv E n (aeval (Fin.cons (X 0) (fun j => rename Fin.succ (L j))) U)).coeff d at ht
+ rw [specialize_parameter, Polynomial.coeff_map, hmonic.coeff_natDegree, map_one] at ht
+ simpa only [map_sum, map_mul, separate_parameter, Polynomial.finsetSum_coeff,
+ Polynomial.coeff_mul_C] using ht
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GraphConnectivity.lean b/lean/OAI/Computability/VPVNP/GraphConnectivity.lean
new file mode 100644
index 0000000000..8cd8d733c3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GraphConnectivity.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.LayerWalk
+import OAI.Computability.VPVNP.RegularArcGraph
+import OAI.Computability.VPVNP.GraphRounding
+import Mathlib.Combinatorics.SimpleGraph.Connectivity.Connected
+
+/-!
+# Connected support of the regular arc multigraph
+
+In the last paragraph of Section 5.3 of *VP and VNP differ over every field*,
+the Poincaré inequality for the real line forces connectivity. The multigraph
+is specified by its arc multiplicities. Removing loops and identifying
+parallel edges leaves the following simple graph, with the same reachability.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {V : Type*}
+
+/-- The underlying simple graph of an arc multiplicity matrix. -/
+def arcSupportGraph (M : Matrix V V ℕ) : SimpleGraph V :=
+ SimpleGraph.fromRel (fun u v ↦ 0 < M u v)
+
+/-- For symmetric multiplicities an edge is present precisely when its
+distinct endpoints are joined by an arc. -/
+theorem arcSupportGraph_adj (M : Matrix V V ℕ) (hs : ∀ u v, M u v = M v u) (u v : V) :
+ (arcSupportGraph M).Adj u v ↔ u ≠ v ∧ 0 < M u v := by
+ simp only [arcSupportGraph, SimpleGraph.fromRel_adj, ← hs u v, or_self]
+
+/-- Reachability is unchanged when loops are removed and parallel arcs are
+identified. -/
+theorem arcSupportGraph_reachable_iff (M : Matrix V V ℕ) (hs : ∀ u v, M u v = M v u)
+ (u v : V) : (arcSupportGraph M).Reachable u v ↔
+ Relation.ReflTransGen (fun i j ↦ 0 < M i j) u v := by
+ rw [SimpleGraph.reachable_iff_reflTransGen]
+ constructor
+ · intro path
+ exact Relation.ReflTransGen.mono (fun i j h ↦ ((arcSupportGraph_adj M hs i j).mp h).2) u v path
+ · intro path
+ induction path with
+ | refl => exact .refl
+ | @tail i j _ hstep ih =>
+ by_cases hij : i = j
+ · exact hij ▸ ih
+ · exact ih.tail ((arcSupportGraph_adj M hs i j).2 ⟨hij, hstep⟩)
+
+/-- Every two vertices of a symmetric arc multigraph with a real Poincaré
+bound are joined by a walk in its underlying simple graph. -/
+theorem arcSupportGraph_reachable [Fintype V] (M : Matrix V V ℕ) (hs : ∀ u v, M u v = M v u)
+ {h : ℕ} {γ : ℝ} (hP : HasPoincareBound ℝ (normalizeArcs M h) γ) (u v : V) :
+ (arcSupportGraph M).Reachable u v := by
+ apply (arcSupportGraph_reachable_iff M hs u v).mpr
+ have hpath := reachable_of_poincare (0 : ℝ) 1 (by norm_num [Real.dist_eq]) _
+ (fun i j ↦ by unfold normalizeArcs; positivity)
+ (fun i j ↦ by simp only [normalizeArcs, hs i j]) hP u v
+ refine Relation.ReflTransGen.mono (fun i j hstep ↦ Nat.pos_of_ne_zero ?_) u v hpath
+ intro hz
+ simp [normalizeArcs, hz] at hstep
+
+/-- On a nonempty vertex set the real-valued inequality certifies
+connectivity in the graph-theoretic sense. -/
+theorem arcSupportGraph_connected [Fintype V] [Nonempty V] (M : Matrix V V ℕ)
+ (hs : ∀ u v, M u v = M v u) {h : ℕ} {γ : ℝ}
+ (hP : HasPoincareBound ℝ (normalizeArcs M h) γ) :
+ (arcSupportGraph M).Connected :=
+ ⟨arcSupportGraph_reachable M hs hP⟩
+
+
+/-- The matrix Poincaré inequality, expressed with the paper's averages over
+ordered vertex pairs and directed arcs. Parallel edges occur once per port. -/
+theorem RegularArcGraph.poincare_on_arcs [Fintype V] [DecidableEq V] {b : ℕ}
+ (G : RegularArcGraph V b) {X : Type*} [PseudoMetricSpace X] {γ : ℝ}
+ (hP : HasPoincareBound X (normalizeArcs G.multiplicity b) γ) (x : V → X) :
+ (∑ u, ∑ v, dist (x u) (x v) ^ 2) / (Fintype.card V : ℝ) ^ 2 ≤
+ γ * ((∑ p : V × Fin b, dist (x p.1) (x (G.reverse p).1) ^ 2) /
+ ((Fintype.card V : ℝ) * b)) := by
+ rw [G.sum_cost (fun u v ↦ dist (x u) (x v) ^ 2)]
+ have h := div_le_div_of_nonneg_right (hP x) (Nat.cast_nonneg (Fintype.card V) (α := ℝ))
+ rw [div_div, ← pow_two] at h
+ refine h.trans_eq ?_
+ unfold walkEnergy normalizeArcs
+ simp_rw [div_mul_eq_mul_div, ← Finset.sum_div]
+ rw [mul_div_assoc, div_div, mul_comm (b : ℝ)]
+ congr 4
+ funext u
+ exact Finset.sum_congr rfl fun v _ ↦ by rw [dist_comm]
+
+/-- Lift a symmetric loop-free regular arc matrix to a connected undirected
+multigraph without changing any transition multiplicity. -/
+theorem exists_connected_regularArcGraph [Fintype V] [Nonempty V] [DecidableEq V]
+ (M : Matrix V V ℕ) (hs : ∀ u v, M u v = M v u) {b : ℕ} (hr : ∀ u, ∑ v, M u v = b)
+ (hd : ∀ u, M u u = 0) (hreach : ∀ u v, Relation.ReflTransGen (fun i j ↦ 0 < M i j) u v) :
+ ∃ G : RegularArcGraph V b, G.multiplicity = M ∧ (arcSupportGraph G.multiplicity).Connected := by
+ obtain ⟨G, hG⟩ := exists_regularArcGraph M hs hr hd
+ have heq : G.multiplicity = M := funext fun u ↦ funext (hG u)
+ refine ⟨G, heq, heq ▸ ?_⟩
+ exact ⟨fun u v ↦ (arcSupportGraph_reachable_iff M hs u v).mpr (hreach u v)⟩
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GraphRounding.lean b/lean/OAI/Computability/VPVNP/GraphRounding.lean
new file mode 100644
index 0000000000..1fa1a5e871
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GraphRounding.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.WalkEnergy
+import Mathlib.Algebra.Order.Floor.Semiring
+import Mathlib.Data.Nat.Log
+
+/-!
+# Rounding a symmetric stochastic matrix to a regular multigraph
+
+At the end of Section 5.2 of *VP and VNP differ over every field*, arc
+multiplicities are rounded up from half the desired degree times each
+transition probability. The missing arcs are loops. The normalized walk
+of the resulting multigraph preserves at least half of every edge energy.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {ι : Type*} [Fintype ι]
+
+/-- Entries charged one unit of possible rounding error in a row. -/
+noncomputable def rowSupport (P : Matrix ι ι ℝ) (i : ι) : Finset ι :=
+ Finset.univ.filter fun j ↦ P i j ≠ 0
+
+/-- The integral arc multiplicities before loops are added. -/
+noncomputable def ceilingArcs (P : Matrix ι ι ℝ) (h : ℕ) : Matrix ι ι ℕ :=
+ fun i j ↦ ⌈(h : ℝ) / 2 * P i j⌉₊
+
+/-- The loss from rounding up is at most the number of nonzero entries. -/
+theorem ceilingArcs_row_le (P : Matrix ι ι ℝ) (h : ℕ) (i : ι)
+ (hn : ∀ j, 0 ≤ P i j) (hrow : ∑ j, P i j = 1) :
+ ((∑ j, ceilingArcs P h i j : ℕ) : ℝ) ≤ (h : ℝ) / 2 + (rowSupport P i).card := by
+ classical
+ have term (j : ι) : (ceilingArcs P h i j : ℝ) ≤
+ (h : ℝ) / 2 * P i j + (if P i j ≠ 0 then 1 else 0) := by
+ by_cases hz : P i j = 0
+ · simp [ceilingArcs, hz]
+ · rw [ite_eq_left hz]
+ exact (Nat.ceil_lt_add_one (mul_nonneg (by positivity : (0 : ℝ) ≤ h / 2) (hn j))).le
+ have hcard : (∑ j, if P i j ≠ 0 then (1 : ℝ) else 0) = (rowSupport P i).card := by
+ simp [rowSupport, Finset.sum_ite]
+ rw [Nat.cast_sum]
+ calc
+ _ ≤ ∑ j, ((h : ℝ) / 2 * P i j + if P i j ≠ 0 then 1 else 0) :=
+ Finset.sum_le_sum fun j _ ↦ term j
+ _ = _ := by rw [Finset.sum_add_distrib, ← Finset.mul_sum, hrow, mul_one, hcard]
+
+variable [DecidableEq ι]
+
+/-- Padded arc multiplicities. A loop counts as one outgoing arc. -/
+noncomputable def roundedArcs (P : Matrix ι ι ℝ) (h : ℕ) : Matrix ι ι ℕ :=
+ fun i j ↦ ceilingArcs P h i j + if i = j then h - ∑ k, ceilingArcs P h i k else 0
+
+/-- Rounding and adding loops preserve symmetry. -/
+theorem roundedArcs_symm (P : Matrix ι ι ℝ) (h : ℕ)
+ (hs : ∀ i j, P i j = P j i) (i j : ι) : roundedArcs P h i j = roundedArcs P h j i := by
+ by_cases heq : i = j
+ · subst j
+ rfl
+ · simp [roundedArcs, ceilingArcs, heq, Ne.symm heq, hs i j]
+
+/-- Every row has total degree exactly `h` when its support has size at most `h / 2`. -/
+theorem roundedArcs_row_sum (P : Matrix ι ι ℝ) (h : ℕ) (i : ι)
+ (hn : ∀ j, 0 ≤ P i j) (hrow : ∑ j, P i j = 1)
+ (hsupp : 2 * (rowSupport P i).card ≤ h) : ∑ j, roundedArcs P h i j = h := by
+ have hcap : ∑ j, ceilingArcs P h i j ≤ h := by
+ have hcast : 2 * ((rowSupport P i).card : ℝ) ≤ h := by exact_mod_cast hsupp
+ have hb := ceilingArcs_row_le P h i hn hrow
+ exact Nat.cast_le.mp (by linarith only [hb, hcast] :
+ ((∑ j, ceilingArcs P h i j : ℕ) : ℝ) ≤ h)
+ simpa [roundedArcs, Finset.sum_add_distrib] using Nat.add_sub_of_le hcap
+
+/-- The transition matrix associated to a regular graph's integral arc counts. -/
+noncomputable def normalizeArcs (M : Matrix ι ι ℕ) (h : ℕ) : Matrix ι ι ℝ :=
+ fun i j ↦ (M i j : ℝ) / h
+
+omit [DecidableEq ι] in
+/-- Uniformly choosing one of the `h` outgoing arcs gives a stochastic row. -/
+theorem normalizeArcs_row_sum (M : Matrix ι ι ℕ) {h : ℕ} (hh : 0 < h)
+ (i : ι) (hrow : ∑ j, M i j = h) : ∑ j, normalizeArcs M h i j = 1 := by
+ simp [normalizeArcs, div_eq_mul_inv, ← Finset.sum_mul, ← Nat.cast_sum, hrow, hh.ne']
+
+/-- Entrywise lower bound on the normalized rounded transition matrix. -/
+theorem roundedArcs_entry_ge (P : Matrix ι ι ℝ) {h : ℕ} (hh : 0 < h) (i j : ι) :
+ P i j / 2 ≤ normalizeArcs (roundedArcs P h) h i j := by
+ have hle : ceilingArcs P h i j ≤ roundedArcs P h i j := Nat.le_add_right _ _
+ apply (le_div_iff₀ (Nat.cast_pos.mpr hh : (0 : ℝ) < h)).mpr
+ calc
+ _ = (h : ℝ) / 2 * P i j := by ring
+ _ ≤ (ceilingArcs P h i j : ℝ) := Nat.le_ceil _
+ _ ≤ _ := by exact_mod_cast hle
+
+omit [DecidableEq ι] in
+/-- Entrywise domination of half of the original walk preserves half of every edge energy. -/
+theorem walkEnergy_le_twice_of_half_le {X : Type*} [PseudoMetricSpace X]
+ {P Q : Matrix ι ι ℝ} (hhalf : ∀ i j, P i j / 2 ≤ Q i j) (x : ι → X) :
+ walkEnergy P x ≤ 2 * walkEnergy Q x := by
+ unfold walkEnergy
+ simp_rw [Finset.mul_sum]
+ exact Finset.sum_le_sum fun i _ ↦ Finset.sum_le_sum fun j _ ↦ by
+ rw [← mul_assoc]
+ apply mul_le_mul_of_nonneg_right _ (sq_nonneg _)
+ linarith only [hhalf i j]
+
+omit [DecidableEq ι] in
+/-- The entrywise energy comparison gives a factor of two in the Poincaré bound. -/
+theorem hasPoincareBound_of_half_le {X : Type*} [PseudoMetricSpace X]
+ {P Q : Matrix ι ι ℝ} (hhalf : ∀ i j, P i j / 2 ≤ Q i j) {γ : ℝ} (hγ : 0 ≤ γ)
+ (hbound : HasPoincareBound X P γ) : HasPoincareBound X Q (2 * γ) := by
+ intro x
+ calc
+ _ ≤ γ * walkEnergy P x := hbound x
+ _ ≤ γ * (2 * walkEnergy Q x) :=
+ mul_le_mul_of_nonneg_left (walkEnergy_le_twice_of_half_le hhalf x) hγ
+ _ = _ := by ring
+
+/-- Rounding a walk with Poincaré bound `γ` costs at most a factor of two. -/
+theorem roundedArcs_hasPoincareBound {X : Type*} [PseudoMetricSpace X]
+ (P : Matrix ι ι ℝ) {h : ℕ} (hh : 0 < h) {γ : ℝ} (hγ : 0 ≤ γ)
+ (hbound : HasPoincareBound X P γ) :
+ HasPoincareBound X (normalizeArcs (roundedArcs P h) h) (2 * γ) :=
+ hasPoincareBound_of_half_le (roundedArcs_entry_ge P hh) hγ hbound
+
+/-- Simultaneous realization for every metric target of a sparse symmetric stochastic matrix.
+The regular degree is a power of two between twice and four times the support bound. -/
+theorem exists_regular_rounding (P : Matrix ι ι ℝ) {k : ℕ} (hk : 0 < k)
+ (hn : ∀ i j, 0 ≤ P i j) (hrow : ∀ i, ∑ j, P i j = 1)
+ (hs : ∀ i j, P i j = P j i) (hkrow : ∀ i, (rowSupport P i).card ≤ k) :
+ ∃ e : ℕ, 2 * k ≤ 2 ^ e ∧ 2 ^ e ≤ 4 * k ∧
+ ∃ M : Matrix ι ι ℕ, (∀ i j, M i j = M j i) ∧ (∀ i, ∑ j, M i j = 2 ^ e) ∧
+ (∀ i j, P i j / 2 ≤ normalizeArcs M (2 ^ e) i j) := by
+ let e := Nat.log 2 k + 2
+ have hl := Nat.lt_pow_succ_log_self (b := 2) (by decide) k
+ have hu := Nat.pow_log_le_self 2 hk.ne'
+ have hlow : 2 * k ≤ 2 ^ e := by dsimp [e]; rw [pow_add]; rw [pow_succ] at hl; omega
+ have hupp : 2 ^ e ≤ 4 * k := by dsimp [e]; rw [pow_add]; omega
+ refine ⟨e, hlow, hupp, roundedArcs P (2 ^ e), roundedArcs_symm P _ hs, ?_, ?_⟩
+ · exact fun i ↦ roundedArcs_row_sum P _ i (hn i) (hrow i)
+ ((Nat.mul_le_mul_left 2 (hkrow i)).trans hlow)
+ · exact roundedArcs_entry_ge P (by positivity)
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannAdjacentFrame.lean b/lean/OAI/Computability/VPVNP/GrassmannAdjacentFrame.lean
new file mode 100644
index 0000000000..e9998fb294
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannAdjacentFrame.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.GrassmannIndependent
+import Mathlib.LinearAlgebra.LinearIndependent.Lemmas
+
+/-!
+# A shared frame for adjacent binary Grassmannian planes
+
+Two planes at distance one have bases with all but their last columns in
+common. The tuple consisting of the common columns and both last columns is
+independent. This gives coordinates for the adjacent-pair sampling in §5.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Module Submodule Set
+
+/-- A common basis for the intersection and one additional column from each
+of an ordered pair of adjacent planes. -/
+theorem exists_adjacent_frame {n : ℕ} (p : Pair (n + 1) 1) :
+ ∃ (b : Fin n → Space (n + 1)) (u v : Space (n + 1)),
+ LinearIndependent (ZMod 2) (Fin.snoc (Fin.snoc b u) v : Fin (n + 2) → _) ∧
+ LinearIndependent (ZMod 2) (Fin.snoc b u : Fin (n + 1) → _) ∧
+ LinearIndependent (ZMod 2) (Fin.snoc b v : Fin (n + 1) → _) ∧
+ span (ZMod 2) (range (Fin.snoc b u : Fin (n + 1) → _)) = p.val.1.val ∧
+ span (ZMod 2) (range (Fin.snoc b v : Fin (n + 1) → _)) = p.val.2.val := by
+ let U := p.val.1.val
+ let V := p.val.2.val
+ let I := U ⊓ V
+ have hU : finrank (ZMod 2) U = n + 1 := p.val.1.property
+ have hV : finrank (ZMod 2) V = n + 1 := p.val.2.property
+ have hS : finrank (ZMod 2) (U ⊔ V : Submodule _ _) = n + 2 := p.property
+ have hI : finrank (ZMod 2) I = n := by
+ have hd := U.finrank_sup_add_finrank_inf_eq V
+ rw [hS, hU, hV] at hd
+ change finrank (ZMod 2) (U ⊓ V : Submodule _ _) = n
+ omega
+ have outside (W : Submodule (ZMod 2) (Space (n + 1))) (hW : finrank (ZMod 2) W = n + 1) :
+ ∃ x ∈ W, x ∉ I := by
+ apply Set.not_subset_iff_exists_mem_notMem.mp
+ intro h
+ have := Submodule.finrank_mono (show W ≤ I from h)
+ omega
+ obtain ⟨u, hu, huI⟩ := outside U hU
+ obtain ⟨v, hv, hvI⟩ := outside V hV
+ let basis := finBasisOfFinrankEq (ZMod 2) I hI
+ let b := I.subtype ∘ basis
+ have hb : LinearIndependent (ZMod 2) b := basis.linearIndependent.map' I.subtype I.ker_subtype
+ have hspan : span (ZMod 2) (range b) = I := by
+ rw [show range b = I.subtype '' range basis from Set.range_comp ..,
+ Submodule.span_image, basis.span_eq, Submodule.map_subtype_top]
+ have hu' := hb.finSnoc (hspan ▸ huI)
+ have hv' := hb.finSnoc (hspan ▸ hvI)
+ have span_eq (W : Submodule (ZMod 2) (Space (n + 1))) (hIW : I ≤ W)
+ (hW : finrank (ZMod 2) W = n + 1) (x : Space (n + 1)) (hx : x ∈ W)
+ (hbx : LinearIndependent (ZMod 2) (Fin.snoc b x : Fin (n + 1) → _)) :
+ span (ZMod 2) (range (Fin.snoc b x : Fin (n + 1) → _)) = W := by
+ apply Submodule.eq_of_le_of_finrank_eq
+ · rw [Fin.range_snoc, span_le]
+ exact Set.insert_subset hx ((span_le.mp (hspan ▸ hIW)))
+ · rw [finrank_span_eq_card hbx, Fintype.card_fin, hW]
+ have hsu := span_eq U inf_le_left hU u hu hu'
+ have hsv := span_eq V inf_le_right hV v hv hv'
+ refine ⟨b, u, v, hu'.finSnoc ?_, hu', hv', hsu, hsv⟩
+ rw [hsu]
+ exact fun h => hvI ⟨h, hv⟩
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannCompactness.lean b/lean/OAI/Computability/VPVNP/GrassmannCompactness.lean
new file mode 100644
index 0000000000..c5b4269113
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannCompactness.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.GrassmannFourPoint
+import OAI.Computability.VPVNP.GrassmannMeanBounds
+import Mathlib.Analysis.Real.Sqrt
+import Mathlib.Topology.Order.Compact
+
+/-!
+# Uniformity of the strict Grassmann inequality
+
+The last paragraph of Lemma 5.3 in *VP and VNP differ over every field*
+passes from rigidity of an extremal marked configuration to a strict uniform
+bound. The relevant topology is the product topology on real arrays. Restricting
+to a specified set of marks and taking square roots are continuous, so a cube
+in a limiting squared-distance array violates uniform cube exclusion for the
+original distances.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Set
+
+variable {κ V J : Type*} (X : κ → Type*) [∀ k, PseudoMetricSpace (X k)]
+
+/-- The rescaled marked distances whose closure defines uniform exclusion. -/
+def markedDistances (V : Type*) : Set (V → V → ℝ) :=
+ {D | ∃ (k : κ) (s : ℝ), 0 < s ∧ ∃ x : V → X k, D = fun i j => s * dist (x i) (x j)}
+
+/-- Rescaled squared distances. The parameter is the square of the distance scale. -/
+def markedSquares (V : Type*) : Set (V → V → ℝ) :=
+ {D | ∃ (k : κ) (s : ℝ), 0 < s ∧ ∃ x : V → X k, D = fun i j => s * dist (x i) (x j) ^ 2}
+
+theorem smul_mem_markedSquares {D : V → V → ℝ} (hD : D ∈ markedSquares X V)
+ {t : ℝ} (ht : 0 < t) : t • D ∈ markedSquares X V := by
+ obtain ⟨k, s, hs, x, rfl⟩ := hD
+ refine ⟨k, t * s, mul_pos ht hs, x, ?_⟩
+ ext i j
+ exact (mul_assoc _ _ _).symm
+
+/-- Restricting a limiting squared-distance array to marked vertices yields
+an ordinary distance array in the closure for those marks. -/
+theorem restrict_sqrt_mem_closure_markedDistances {D : V → V → ℝ}
+ (hD : D ∈ closure (markedSquares X V)) (e : J → V) :
+ (fun i j => Real.sqrt (D (e i) (e j))) ∈ closure (markedDistances X J) := by
+ let f := fun (A : V → V → ℝ) (i j : J) => Real.sqrt (A (e i) (e j))
+ have hf : MapsTo f (markedSquares X V) (markedDistances X J) := by
+ rintro _ ⟨k, s, hs, x, rfl⟩
+ refine ⟨k, Real.sqrt s, Real.sqrt_pos.mpr hs, x ∘ e, ?_⟩
+ ext i j
+ simp [f, Real.sqrt_mul hs.le, Real.sqrt_sq dist_nonneg]
+ have hc : Continuous f := by dsimp [f]; fun_prop
+ exact hf.closure hc hD
+
+/-- Uniform exclusion prevents a prescribed ordinary distance array from
+appearing on any set of marks in a limiting squared-distance array. -/
+theorem excluded_of_mem_closure_markedSquares {Q : J → J → ℝ}
+ (hQ : Q ∉ closure (markedDistances X J)) {D : V → V → ℝ}
+ (hD : D ∈ closure (markedSquares X V)) :
+ ¬ ∃ e : J → V, ∀ i j, Real.sqrt (D (e i) (e j)) = Q i j := by
+ rintro ⟨e, he⟩
+ exact hQ ((funext fun i => funext (he i)) ▸ restrict_sqrt_mem_closure_markedDistances X hD e)
+
+/-- On bounded normalizations of marked squared distances, a strict bound at
+every point of the closure yields a common positive improvement. The case of
+zero normalizing energy is handled by the non-strict homogeneous bound. -/
+theorem uniform_gap_of_normalized_strict
+ (adj comp : (V → V → ℝ) → ℝ) (m K : ℝ) (ha : Continuous adj) (hc : Continuous comp)
+ (ha_scale : ∀ (s : ℝ) D, adj (s • D) = s * adj D)
+ (hc_scale : ∀ (s : ℝ) D, comp (s • D) = s * comp D)
+ (ha_nonneg : ∀ D ∈ markedSquares X V, 0 ≤ adj D)
+ (hzero : ∀ D ∈ markedSquares X V, adj D = 0 → comp D ≤ 0)
+ (hbounded : ∀ D ∈ markedSquares X V, adj D = 1 → ∀ i j, D i j ≤ K)
+ (hstrict : ∀ D ∈ closure (markedSquares X V), adj D = 1 → comp D < m) :
+ ∃ η > 0, ∀ D ∈ markedSquares X V, comp D ≤ (m - η) * adj D := by
+ let S := markedSquares X V ∩ {D | adj D = 1}
+ let box : Set (V → V → ℝ) := Icc 0 (fun _ _ => K)
+ have hbox : IsCompact box := isCompact_Icc
+ have hsub : S ⊆ box := by
+ rintro D ⟨hD, hA⟩
+ refine ⟨?_, hbounded D hD hA⟩
+ obtain ⟨k, s, hs, x, rfl⟩ := hD
+ exact fun i j => mul_nonneg hs.le (sq_nonneg _)
+ have hcompact : IsCompact (closure S) :=
+ hbox.of_isClosed_subset isClosed_closure (closure_minimal hsub hbox.isClosed)
+ have hadj : closure S ⊆ {D | adj D = 1} :=
+ closure_minimal inter_subset_right (isClosed_eq ha continuous_const)
+ have hsrc : closure S ⊆ closure (markedSquares X V) := closure_mono inter_subset_left
+ have hlt (D) (hD : D ∈ closure S) : comp D < m := hstrict D (hsrc hD) (hadj hD)
+ obtain ⟨c, hcm, hbound⟩ : ∃ c : ℝ, c < m ∧ ∀ D ∈ closure S, comp D ≤ c :=
+ hcompact.exists_forall_le' (α := ℝᵒᵈ) hc.continuousOn hlt
+ refine ⟨m - c, sub_pos.mpr hcm, ?_⟩
+ intro D hD
+ rw [sub_sub_cancel]
+ rcases (ha_nonneg D hD).eq_or_lt with h | h
+ · rw [← h, mul_zero]
+ exact hzero D hD h.symm
+ · let t := (adj D)⁻¹
+ have ht : 0 < t := inv_pos.mpr h
+ have hnorm : adj (t • D) = 1 := by rw [ha_scale]; exact inv_mul_cancel₀ h.ne'
+ have hnormS : t • D ∈ S := ⟨smul_mem_markedSquares X hD ht, hnorm⟩
+ have hcomp := hbound _ (subset_closure hnormS)
+ rw [hc_scale] at hcomp
+ calc
+ comp D = (t * comp D) * adj D := by dsimp [t]; field_simp
+ _ ≤ c * adj D := mul_le_mul_of_nonneg_right hcomp h.le
+
+/-- Every limiting marked array retains the four-point inequality and its
+opposite-side equality case, even when the target spaces vary. -/
+theorem quadBounds_of_mem_closure_markedSquares
+ (hcat : ∀ k, SpectralGeometry.HasCATZeroSegments (X k)) {D : V → V → ℝ}
+ (hD : D ∈ closure (markedSquares X V)) : QuadBounds D := by
+ apply quadBounds_of_mem_catZeroArrays
+ apply closure_minimal (t := catZeroArrays V) _ (isClosed_catZeroArrays V) hD
+ rintro _ ⟨k, s, hs, x, rfl⟩
+ exact scaledDistSq_mem_catZeroArrays (hcat k) x hs.le
+
+/-- The compactness implication in Lemma 5.3 for the actual binary Grassmannian.
+The inputs from the Grassmann combinatorics are the non-strict bounds on the
+pair means and rigidity at equality. Uniform exclusion concerns the ordinary
+distance array of the cube, while rigidity yields its squared distances. -/
+theorem strict_grassmann_bound_of_rigidity (m : ℕ) (Q : J → J → ℝ)
+ (hcat : ∀ k, SpectralGeometry.HasCATZeroSegments (X k))
+ (hexclude : (fun i j => Real.sqrt (Q i j)) ∉ closure (markedDistances X J))
+ (hB : ∀ D : Plane m → Plane m → ℝ, QuadBounds D →
+ ∀ r ≤ m, mean D r ≤ (r : ℝ) * mean D 1)
+ (hrigid : ∀ D : Plane m → Plane m → ℝ, QuadBounds D →
+ mean D 1 = 1 → mean D m = (m : ℝ) → ∃ e : J → Plane m, ∀ i j, D (e i) (e j) = Q i j) :
+ ∃ η > 0, ∀ (k : κ) (x : Plane m → X k),
+ mean (fun i j => dist (x i) (x j) ^ 2) m ≤
+ ((m : ℝ) - η) * mean (fun i j => dist (x i) (x j) ^ 2) 1 := by
+ obtain ⟨K, hK⟩ := exists_coordinate_bound m
+ have hquad {D : Plane m → Plane m → ℝ} (hD : D ∈ markedSquares X (Plane m)) :=
+ quadBounds_of_mem_closure_markedSquares X hcat (subset_closure hD)
+ have hstrict (D : Plane m → Plane m → ℝ) (hD : D ∈ closure (markedSquares X (Plane m)))
+ (h1 : mean D 1 = 1) : mean D m < (m : ℝ) := by
+ have hq := quadBounds_of_mem_closure_markedSquares X hcat hD
+ have hm : mean D m ≤ (m : ℝ) := by simpa [h1] using hB D hq m le_rfl
+ refine lt_of_le_of_ne hm (fun he => ?_)
+ obtain ⟨e, he'⟩ := hrigid D hq h1 he
+ exact excluded_of_mem_closure_markedSquares X hexclude hD
+ ⟨e, fun i j => congrArg Real.sqrt (he' i j)⟩
+ obtain ⟨η, hη, hgap⟩ := uniform_gap_of_normalized_strict X
+ (fun D => mean D 1) (fun D => mean D m) m K (continuous_mean m 1) (continuous_mean m m)
+ (fun s D => mean_smul D 1 s) (fun s D => mean_smul D m s)
+ (fun _ hD => mean_nonneg (hquad hD).nonneg 1)
+ (fun D hD hz => by simpa [hz] using hB D (hquad hD) m le_rfl)
+ (fun D hD h1 => hK D (hquad hD).nonneg fun r hr => by simpa [h1] using hB D (hquad hD) r hr)
+ hstrict
+ refine ⟨η, hη, fun k x => hgap _ ⟨k, 1, one_pos, x, ?_⟩⟩
+ simp
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannCompletion.lean b/lean/OAI/Computability/VPVNP/GrassmannCompletion.lean
new file mode 100644
index 0000000000..e38a44deb3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannCompletion.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.IndependentCompletion
+import OAI.Computability.VPVNP.GrassmannTypes
+import Mathlib.Algebra.Field.ZMod
+import Mathlib.Algebra.CharP.Two
+
+/-!
+# Common completions of adjacent column frames
+
+In the equality case of Lemma 5.3 of *VP and VNP differ over every field*,
+one original column of a frame is replaced by a vector outside the span.
+Putting the difference between the two columns into the completion preserves
+the completed span of either block. Over the binary field this difference is
+the sum used in Section 5.1.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Set Submodule
+
+variable {K V ι κ : Type*} [Field K] [AddCommGroup V] [Module K V]
+
+/-- If the difference of two choices of a column already belongs to the
+completion space, every completed block span is independent of the choice. -/
+theorem completed_span_update [DecidableEq ι] {v : ι → V} (i : ι) (z : V)
+ {S : Submodule K V} (h : z - v i ∈ S) (T : Set ι) :
+ S ⊔ span K (v '' T) = S ⊔ span K ((Function.update v i z) '' T) := by
+ apply le_antisymm <;> refine sup_le le_sup_left (span_le.mpr ?_)
+ · rintro _ ⟨j, hj, rfl⟩
+ have hmem : Function.update v i z j ∈ S ⊔ span K ((Function.update v i z) '' T) :=
+ Submodule.mem_sup_right (subset_span ⟨j, hj, rfl⟩)
+ by_cases hij : j = i
+ · subst j
+ rw [Function.update_self] at hmem
+ simpa using sub_mem hmem (Submodule.mem_sup_left h)
+ · simpa [Function.update_of_ne hij] using hmem
+ · rintro _ ⟨j, hj, rfl⟩
+ have hmem : v j ∈ S ⊔ span K (v '' T) := Submodule.mem_sup_right (subset_span ⟨j, hj, rfl⟩)
+ by_cases hij : j = i
+ · subst j
+ simpa using add_mem (Submodule.mem_sup_left h) hmem
+ · simpa [Function.update_of_ne hij] using hmem
+
+/-- Adding a completion column to an original column is an invertible
+elementary operation on the completed frame. -/
+theorem independent_completed_update [DecidableEq ι] {v : ι → V} {w : κ → V}
+ (i : ι) (j : κ) (z : V) (hj : w j = z - v i)
+ (h : LinearIndependent K (Sum.elim v w)) :
+ LinearIndependent K (Sum.elim (Function.update v i z) w) := by
+ classical
+ let c : ι ⊕ κ → K := fun a ↦ if a = Sum.inl i then 1 else 0
+ have hc : c (Sum.inr j) = 0 := by simp [c]
+ have h' := (linearIndependent_add_smul_iff (v := Sum.elim v w) hc).2 h
+ convert h' using 1
+ funext a
+ rcases a with a | b
+ · by_cases ha : a = i
+ · subst a
+ simp [c, hj, add_sub_cancel]
+ · simp [c, ha]
+ · simp [c]
+
+private def completionIndices (ι : Type*) (k : ℕ) : ι ⊕ Fin (k + 1) ≃ Option ι ⊕ Fin k where
+ toFun := Sum.elim (Sum.inl ∘ some) (Fin.cases (Sum.inl none) Sum.inr)
+ invFun := Sum.elim (fun o ↦ o.elim (Sum.inr 0) Sum.inl) (Sum.inr ∘ Fin.succ)
+ left_inv := by
+ rintro (a | j)
+ · rfl
+ · refine Fin.cases ?_ (fun j ↦ ?_) j <;> rfl
+ right_inv := by
+ rintro ((_ | a) | j) <;> rfl
+
+private theorem independent_cons_completion {v : ι → V} {k : ℕ} {w : Fin k → V} {x : V}
+ (h : LinearIndependent K (Sum.elim (fun o ↦ Option.casesOn' o x v) w)) :
+ LinearIndependent K (Sum.elim v (Fin.cons x w)) := by
+ have h' := h.comp (completionIndices ι k) (completionIndices ι k).injective
+ convert h' using 1
+ funext a
+ rcases a with a | j
+ · rfl
+ · refine Fin.cases ?_ (fun j ↦ ?_) j <;> rfl
+
+
+/-- A common independent completion of the old and new frames containing
+their column difference. The final equality holds for every block of columns,
+including the whole tuple. -/
+theorem adjacent_commonCompletion [DecidableEq ι] [Fintype ι] [FiniteDimensional K V]
+ {v : ι → V} (hv : LinearIndependent K v) (i : ι) (z : V)
+ (hz : z ∉ span K (range v)) {k : ℕ} (hk : 0 < k)
+ (hd : Fintype.card ι + k ≤ Module.finrank K V) :
+ ∃ w : Fin k → V, w ⟨0, hk⟩ = z - v i ∧
+ LinearIndependent K (Sum.elim v w) ∧
+ LinearIndependent K (Sum.elim (Function.update v i z) w) ∧
+ ∀ T : Set ι, span K (range w) ⊔ span K (v '' T) =
+ span K (range w) ⊔ span K ((Function.update v i z) '' T) := by
+ cases k with
+ | zero => omega
+ | succ k =>
+ have hdiff : z - v i ∉ span K (range v) := by
+ intro h
+ exact hz (by simpa using add_mem h (subset_span (mem_range_self i)))
+ obtain ⟨tail, htail⟩ := exists_independent_completion (hv.option hdiff) (k := k)
+ (by simpa [Nat.add_assoc, Nat.add_comm 1 k] using hd)
+ let w : Fin (k + 1) → V := Fin.cons (z - v i) tail
+ have h : LinearIndependent K (Sum.elim v w) := independent_cons_completion htail
+ have hw : w 0 = z - v i := rfl
+ refine ⟨w, hw, h, independent_completed_update i 0 z hw h, ?_⟩
+ exact completed_span_update i z (subset_span ⟨0, hw⟩)
+
+/-- For the two original blocks of Section 5.1 over the binary field, the
+common completion has exactly `m - r` columns and contains `v i + z`.
+It preserves each of the two completed planes. -/
+theorem binary_pair_commonCompletion {m r : ℕ} (hr : r < m)
+ {v : Fin r ⊕ Fin r → Space m}
+ (hv : LinearIndependent (ZMod 2) v) (i : Fin r ⊕ Fin r) (z : Space m)
+ (hz : z ∉ span (ZMod 2) (range v)) :
+ ∃ w : Fin (m - r) → Space m, w ⟨0, by omega⟩ = v i + z ∧
+ LinearIndependent (ZMod 2) (Sum.elim v w) ∧
+ LinearIndependent (ZMod 2) (Sum.elim (Function.update v i z) w) ∧
+ (span (ZMod 2) (range w) ⊔ span (ZMod 2) (range (v ∘ Sum.inl)) =
+ span (ZMod 2) (range w) ⊔ span (ZMod 2) (range (Function.update v i z ∘ Sum.inl))) ∧
+ (span (ZMod 2) (range w) ⊔ span (ZMod 2) (range (v ∘ Sum.inr)) =
+ span (ZMod 2) (range w) ⊔ span (ZMod 2) (range (Function.update v i z ∘ Sum.inr))) := by
+ obtain ⟨w, hw, h₁, h₂, hspan⟩ := adjacent_commonCompletion (K := ZMod 2) (v := v) hv i z hz
+ (k := m - r) (by omega) (by
+ simp only [Fintype.card_sum, Fintype.card_fin, Module.finrank_pi]
+ omega)
+ refine ⟨w, ?_, h₁, h₂, ?_, ?_⟩
+ · rw [hw]
+ ext j
+ exact (CharTwo.sub_eq_add _ _).trans (add_comm _ _)
+ · simpa only [← range_comp] using hspan (range Sum.inl)
+ · simpa only [← range_comp] using hspan (range Sum.inr)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannEnergy.lean b/lean/OAI/Computability/VPVNP/GrassmannEnergy.lean
new file mode 100644
index 0000000000..d0b5e8230d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannEnergy.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.GrassmannSeeds
+import OAI.Computability.VPVNP.OrbitAverage
+import OAI.Computability.VPVNP.SubspaceOrbits
+import OAI.Computability.VPVNP.GrassmannGeometry
+
+/-!
+# Averaging the quadrilateral inequality on the binary Grassmannian
+
+The quantities in Lemma 5.3 are uniform means over ordered pairs of a fixed
+sum dimension. Transitivity identifies these means with averages of a single
+quadrilateral translated by the general linear group. In the saturated case
+each translate has zero quadrilateral deficit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+private theorem plane_finrank {m : ℕ} (a : Plane m) : Module.finrank (ZMod 2) a.val = m :=
+ a.property
+
+private theorem pair_finrank {m r : ℕ} (p : Pair m r) :
+ Module.finrank (ZMod 2) (p.val.1.val ⊔ p.val.2.val : Submodule (ZMod 2) (Space m)) = m + r :=
+ p.property
+
+instance (m r : ℕ) : MulAction.IsPretransitive (GL m) (Pair m r) where
+ exists_smul_eq p q := by
+ obtain ⟨g, hg, hg'⟩ := exists_pair_linearEquiv (K := ZMod 2) (V := Space m) p.val.1.val p.val.2.val
+ q.val.1.val q.val.2.val (by rw [plane_finrank, plane_finrank])
+ (by rw [plane_finrank, plane_finrank]) (by rw [pair_finrank p, pair_finrank q])
+ exact ⟨g, Subtype.ext (Prod.ext (Subtype.ext hg) (Subtype.ext hg'))⟩
+
+variable {m r s : ℕ}
+
+/-- Any seed pair of a given type gives the uniform pair mean under random
+linear changes of coordinates. -/
+theorem average_translate (D : Plane m → Plane m → ℝ) {a b : Plane m} (h : HasType r a b) :
+ (∑ g : GL m, D (g • a) (g • b)) / Fintype.card (GL m) = mean D r :=
+ orbitAverage_eq_uniformAverage (GL m) (S := Pair m r) (⟨(a,b), h⟩ : Pair m r)
+ (fun p => D p.val.1 p.val.2)
+
+private theorem sum_translate (D : Plane m → Plane m → ℝ) {a b : Plane m} (h : HasType r a b) :
+ (∑ g : GL m, D (g • a) (g • b)) = mean D r * Fintype.card (GL m) :=
+ (div_eq_iff (Nat.cast_ne_zero.mpr Fintype.card_ne_zero)).mp (average_translate D h)
+
+/-- The difference between the side and diagonal sums of a quadrilateral. -/
+def deficit (D : Plane m → Plane m → ℝ) (a b c d : Plane m) : ℝ :=
+ D a b + D b c + D c d + D d a - (D a c + D b d)
+
+/-- Squared CAT(0) distance arrays, and limits of those arrays, obey this inequality. -/
+def QuadrilateralBound (D : Plane m → Plane m → ℝ) : Prop :=
+ ∀ a b c d, D a c + D b d ≤ D a b + D b c + D c d + D d a
+
+private theorem IsSquare.sum_deficit {a b c d : Plane m} (sq : IsSquare r s a b c d)
+ (D : Plane m → Plane m → ℝ) :
+ (∑ g : GL m, deficit D (g • a) (g • b) (g • c) (g • d)) =
+ 2 * (mean D r + mean D s - mean D (r + s)) * Fintype.card (GL m) := by
+ simp only [deficit, Finset.sum_sub_distrib, Finset.sum_add_distrib,
+ sum_translate D sq.ab, sum_translate D sq.bc, sum_translate D sq.cd, sum_translate D sq.da,
+ sum_translate D sq.ac, sum_translate D sq.bd]
+ ring
+
+theorem IsSquare.mean_add_le {a b c d : Plane m} (sq : IsSquare r s a b c d)
+ {D : Plane m → Plane m → ℝ} (h : QuadrilateralBound D) :
+ mean D (r + s) ≤ mean D r + mean D s := by
+ have htotal : 0 ≤ ∑ g : GL m, deficit D (g • a) (g • b) (g • c) (g • d) :=
+ Finset.sum_nonneg (fun _ _ => sub_nonneg.mpr (h _ _ _ _))
+ rw [sq.sum_deficit D] at htotal
+ have hcard : (0 : ℝ) < Fintype.card (GL m) := Nat.cast_pos.mpr Fintype.card_pos
+ have := nonneg_of_mul_nonneg_left htotal hcard
+ linarith
+
+/-- When the pair means saturate subadditivity, each such quadrilateral
+saturates the inequality pointwise. -/
+theorem IsSquare.eq_of_mean_eq_add {a b c d : Plane m} (sq : IsSquare r s a b c d)
+ {D : Plane m → Plane m → ℝ} (h : QuadrilateralBound D)
+ (heq : mean D (r + s) = mean D r + mean D s) :
+ D a c + D b d = D a b + D b c + D c d + D d a := by
+ have htotal := sq.sum_deficit D
+ rw [heq, sub_self, mul_zero, zero_mul] at htotal
+ have hzero := (Finset.sum_eq_zero_iff_of_nonneg (fun g _ =>
+ show 0 ≤ deficit D (g • a) (g • b) (g • c) (g • d) from sub_nonneg.mpr (h _ _ _ _))).mp htotal
+ simpa [deficit, sub_eq_zero, eq_comm] using hzero (1 : GL m) (Finset.mem_univ _)
+
+/-- Type zero consists of the diagonal of the Grassmannian. -/
+theorem HasType.eq_of_zero {a b : Plane m} (h : HasType 0 a b) : a = b := by
+ have h' : Module.finrank (ZMod 2) (a.val ⊔ b.val : Submodule (ZMod 2) (Space m)) = m := h
+ have ha : a.val = a.val ⊔ b.val :=
+ Submodule.eq_of_le_of_finrank_eq le_sup_left (by rw [plane_finrank, h'])
+ have hb : b.val = a.val ⊔ b.val :=
+ Submodule.eq_of_le_of_finrank_eq le_sup_right (by rw [plane_finrank, h'])
+ exact Subtype.ext (ha.trans hb.symm)
+
+theorem mean_zero {D : Plane m → Plane m → ℝ} (h : ∀ a, D a a = 0) : mean D 0 = 0 := by
+ have hz (p : Pair m 0) : D p.val.1 p.val.2 = 0 := p.property.eq_of_zero ▸ h _
+ simp [mean, hz]
+
+/-- Grassmannian pair means are subadditive up to the maximum type. -/
+theorem mean_add_le {D : Plane m → Plane m → ℝ} (h : QuadrilateralBound D) (hrs : r + s ≤ m) :
+ mean D (r + s) ≤ mean D r + mean D s := by
+ obtain ⟨a, b, c, d, hab, hbc, hcd, hda, hac, hbd⟩ := exists_square hrs
+ exact IsSquare.mean_add_le (⟨hab, hbc, hcd, hda, hac, hbd⟩ : IsSquare r s a b c d) h
+
+theorem mean_le_mul_one {D : Plane m → Plane m → ℝ} (h : QuadrilateralBound D)
+ (hzero : ∀ a, D a a = 0) (hr : r ≤ m) : mean D r ≤ r * mean D 1 := by
+ induction r with
+ | zero => simp [mean_zero hzero]
+ | succ k ih =>
+ have ha := mean_add_le h hr
+ rw [Nat.cast_succ, add_mul, one_mul]
+ exact ha.trans (add_le_add_left (ih (by omega)) _)
+
+/-- Saturation between adjacent and complementary pairs forces saturation at
+every intermediate type. -/
+theorem mean_eq_mul_one {D : Plane m → Plane m → ℝ} (h : QuadrilateralBound D)
+ (hzero : ∀ a, D a a = 0) (hfull : mean D m = m * mean D 1) (hr : r ≤ m) :
+ mean D r = r * mean D 1 := by
+ apply le_antisymm (mean_le_mul_one h hzero hr)
+ have hsplit := mean_add_le h (Nat.le_of_eq (Nat.add_sub_of_le hr))
+ rw [Nat.add_sub_of_le hr, hfull] at hsplit
+ have htail := mean_le_mul_one h hzero (Nat.sub_le m r)
+ rw [Nat.cast_sub hr, sub_mul] at htail
+ linarith
+
+/-- Section 5.1's `Bᵣ` for a map of the Grassmannian into a metric space. -/
+noncomputable def energy {X : Type*} [PseudoMetricSpace X] (f : Plane m → X) (r : ℕ) : ℝ :=
+ mean (fun a b => dist (f a) (f b) ^ 2) r
+
+theorem energy_add_le {X : Type*} [PseudoMetricSpace X] (h : SpectralGeometry.HasCATZeroSegments X)
+ (f : Plane m → X) (hrs : r + s ≤ m) : energy f (r + s) ≤ energy f r + energy f s :=
+ mean_add_le (fun a b c d => SpectralGeometry.quadrilateral_sq h (f a) (f b) (f c) (f d)) hrs
+
+theorem energy_le_mul_one {X : Type*} [PseudoMetricSpace X]
+ (h : SpectralGeometry.HasCATZeroSegments X) (f : Plane m → X) (hr : r ≤ m) :
+ energy f r ≤ r * energy f 1 :=
+ mean_le_mul_one (fun a b c d => SpectralGeometry.quadrilateral_sq h (f a) (f b) (f c) (f d))
+ (by simp) hr
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannFourPoint.lean b/lean/OAI/Computability/VPVNP/GrassmannFourPoint.lean
new file mode 100644
index 0000000000..873672f618
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannFourPoint.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.Barycenter
+import Mathlib.Analysis.Real.Sqrt
+
+/-!
+# Four-point inequalities for Grassmannian distance arrays
+
+The proof of Lemma 5.3 uses the squared quadrilateral inequality and its
+equality case even for limits of scaled configurations in different CAT(0)
+spaces. The midpoint comparison yields a closed system of inequalities on
+the array alone. A nonnegative square in the quadrilateral deficit gives the
+equality case directly for every array in this closed set.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open VPVNP.SpectralGeometry
+
+variable {V : Type*}
+
+/-- The squared-distance upper bound from the midpoint of `ac` to `b`. -/
+noncomputable def midpointUpper (D : V → V → ℝ) (a b c : V) : ℝ :=
+ (D a b + D b c) / 2 - D a c / 4
+
+/-- Closed four-point conditions inherited from CAT(0) squared distances. -/
+def catZeroArrays (V : Type*) : Set (V → V → ℝ) :=
+ {D | (∀ a b, 0 ≤ D a b) ∧ (∀ a b, D a b = D b a) ∧ (∀ a, D a a = 0) ∧
+ (∀ a b c, 0 ≤ midpointUpper D a b c) ∧
+ (∀ a b c d, √(D b d) ≤ √(midpointUpper D a b c) + √(midpointUpper D a d c))}
+
+theorem isClosed_catZeroArrays (V : Type*) : IsClosed (catZeroArrays V) := by
+ simp only [catZeroArrays, Set.ofPred_and, Set.ofPred_forall]
+ refine IsClosed.inter ?_ (IsClosed.inter ?_ (IsClosed.inter ?_ (IsClosed.inter ?_ ?_)))
+ · exact isClosed_iInter fun a => isClosed_iInter fun b => isClosed_le continuous_const
+ ((continuous_apply b).comp (continuous_apply a))
+ · exact isClosed_iInter fun a => isClosed_iInter fun b =>
+ isClosed_eq ((continuous_apply b).comp (continuous_apply a))
+ ((continuous_apply a).comp (continuous_apply b))
+ · exact isClosed_iInter fun a =>
+ isClosed_eq ((continuous_apply a).comp (continuous_apply a)) continuous_const
+ · refine isClosed_iInter fun a => isClosed_iInter fun b => isClosed_iInter fun c =>
+ isClosed_le continuous_const ?_
+ unfold midpointUpper
+ fun_prop
+ · refine isClosed_iInter fun a => isClosed_iInter fun b => isClosed_iInter fun c =>
+ isClosed_iInter fun d => isClosed_le ?_ ?_
+ · fun_prop
+ · unfold midpointUpper
+ fun_prop
+
+/-- Scaling squared distances by any nonnegative factor preserves the closed
+four-point conditions. Only the midpoint case of the segment inequality is needed. -/
+theorem scaledDistSq_mem_catZeroArrays {X : Type*} [PseudoMetricSpace X]
+ (h : HasCATZeroSegments X) (x : V → X) {s : ℝ} (hs : 0 ≤ s) :
+ (fun i j => s * dist (x i) (x j) ^ 2) ∈ catZeroArrays V := by
+ let D (i j : V) := s * dist (x i) (x j) ^ 2
+ have hmid (a c : V) : ∃ w : X, ∀ b : V,
+ (√s * dist (x b) w) ^ 2 ≤ midpointUpper D a b c := by
+ obtain ⟨w, hw⟩ := h (x a) (x c) (1 / 2) (by norm_num) (by norm_num)
+ refine ⟨w, fun b => ?_⟩
+ have hb := hw (x b)
+ rw [dist_comm (x b) (x a)] at hb
+ rw [mul_pow, Real.sq_sqrt hs]
+ unfold midpointUpper D
+ linarith only [mul_le_mul_of_nonneg_left hb hs]
+ refine ⟨fun i j => mul_nonneg hs (sq_nonneg _), fun i j => ?_, fun i => by simp, ?_, ?_⟩
+ · dsimp
+ rw [dist_comm]
+ · intro a b c
+ obtain ⟨w, hw⟩ := hmid a c
+ exact (sq_nonneg _).trans (hw b)
+ · intro a b c d
+ obtain ⟨w, hw⟩ := hmid a c
+ rw [Real.sqrt_mul hs, Real.sqrt_sq dist_nonneg]
+ calc
+ √s * dist (x b) (x d) ≤ √s * (dist (x b) w + dist (x d) w) := by
+ rw [dist_comm (x d) w]
+ exact mul_le_mul_of_nonneg_left (dist_triangle _ _ _) (Real.sqrt_nonneg _)
+ _ = √s * dist (x b) w + √s * dist (x d) w := mul_add _ _ _
+ _ ≤ _ := add_le_add (Real.le_sqrt_of_sq_le (hw b)) (Real.le_sqrt_of_sq_le (hw d))
+
+/-- The four-point properties used by the averaging and rigidity arguments
+on the binary Grassmannian. At equality both pairs of opposite sides agree. -/
+structure QuadBounds (D : V → V → ℝ) : Prop where
+ nonneg : ∀ a b, 0 ≤ D a b
+ symm : ∀ a b, D a b = D b a
+ diag : ∀ a, D a a = 0
+ quad : ∀ a b c d, D a c + D b d ≤ D a b + D b c + D c d + D d a
+ opposite : ∀ a b c d, D a c + D b d = D a b + D b c + D c d + D d a →
+ D a b = D c d ∧ D b c = D d a
+
+theorem quadBounds_of_mem_catZeroArrays {D : V → V → ℝ} (h : D ∈ catZeroArrays V) :
+ QuadBounds D := by
+ obtain ⟨hn, hs, hd, hm, ht⟩ := h
+ have hdefect (a b c d : V) :
+ D a c + D b d + (√(midpointUpper D a b c) - √(midpointUpper D a d c)) ^ 2 ≤
+ D a b + D b c + D c d + D d a := by
+ have hsq := (sq_le_sq₀ (Real.sqrt_nonneg _)
+ (add_nonneg (Real.sqrt_nonneg _) (Real.sqrt_nonneg _))).mpr (ht a b c d)
+ rw [Real.sq_sqrt (hn b d)] at hsq
+ have hbound : D b d + (√(midpointUpper D a b c) - √(midpointUpper D a d c)) ^ 2 ≤
+ 2 * midpointUpper D a b c + 2 * midpointUpper D a d c := by
+ nlinarith only [hsq, Real.sq_sqrt (hm a b c), Real.sq_sqrt (hm a d c)]
+ unfold midpointUpper at *
+ linarith only [hbound, hs d c, hs a d]
+ have hsum (a b c d : V)
+ (he : D a c + D b d = D a b + D b c + D c d + D d a) :
+ D a b + D b c = D c d + D d a := by
+ have hz : (√(midpointUpper D a b c) - √(midpointUpper D a d c)) ^ 2 = 0 :=
+ le_antisymm (by linarith only [he, hdefect a b c d]) (sq_nonneg _)
+ have heq : √(midpointUpper D a b c) = √(midpointUpper D a d c) :=
+ sub_eq_zero.mp (sq_eq_zero_iff.mp hz)
+ have heq' := (Real.sqrt_inj (hm a b c) (hm a d c)).mp heq
+ unfold midpointUpper at heq'
+ linarith only [heq', hs d c, hs a d]
+ refine ⟨hn, hs, hd, fun a b c d => ?_, fun a b c d he => ?_⟩
+ · linarith only [hdefect a b c d, sq_nonneg (√(midpointUpper D a b c) -
+ √(midpointUpper D a d c))]
+ · have h₁ := hsum a b c d he
+ have h₂ := hsum b c d a (by linarith only [he, hs c a])
+ constructor <;> linarith only [h₁, h₂]
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannFrameDimensions.lean b/lean/OAI/Computability/VPVNP/GrassmannFrameDimensions.lean
new file mode 100644
index 0000000000..d4eef86d3c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannFrameDimensions.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.GrassmannFrameValue
+import OAI.Computability.VPVNP.GrassmannTypes
+
+/-!
+# Dimensions of completed frame blocks
+
+In the frame description of the binary Grassmannian, the two planes share
+all completion columns. Their sum contains exactly the completion and both
+original blocks. Independence counts the dimensions of all three spans.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Set Submodule
+
+variable {K V ι κ α : Type*} [Field K] [AddCommGroup V] [Module K V]
+
+omit [AddCommGroup V] in
+private theorem range_sumElim (v : ι → V) (w : κ → V) :
+ range (Sum.elim v w) = range v ∪ range w := by
+ simpa only [Set.image_univ, Set.preimage_univ] using Set.image_sumElim Set.univ v w
+
+/-- Selecting columns by an injective map gives their count plus the
+number of common completion columns as the dimension of the completed block. -/
+theorem finrank_completedBlock_range [Fintype α] [Fintype κ] (v : ι → V) (w : κ → V)
+ (f : α → ι) (hf : Function.Injective f)
+ (h : LinearIndependent K (Sum.elim v w)) :
+ Module.finrank K (completedBlock (K := K) v w (range f)) = Fintype.card α + Fintype.card κ := by
+ have hi : LinearIndependent K (Sum.elim (v ∘ f) w) := by
+ have hcomp := h.comp (Sum.map f (id : κ → κ)) (hf.sumMap Function.injective_id)
+ convert hcomp using 1
+ funext j
+ cases j <;> rfl
+ rw [completedBlock, ← range_comp, sup_comm, ← span_union, ← range_sumElim,
+ finrank_span_eq_card hi, Fintype.card_sum]
+
+variable {r s m : ℕ}
+
+/-- Dimension of the completed first block of an independent frame. -/
+theorem finrank_leftBlock (v : Fin (r + r) → V) (w : Fin s → V)
+ (h : LinearIndependent K (Sum.elim v w)) :
+ Module.finrank K (completedBlock (K := K) v w (leftIndices r)) = r + s := by
+ unfold leftIndices
+ simpa only [Fintype.card_fin] using finrank_completedBlock_range v w (Fin.castAdd r)
+ (Fin.castAdd_injective _ _) h
+
+/-- Dimension of the completed second block of an independent frame. -/
+theorem finrank_rightBlock (v : Fin (r + r) → V) (w : Fin s → V)
+ (h : LinearIndependent K (Sum.elim v w)) :
+ Module.finrank K (completedBlock (K := K) v w (rightIndices r)) = r + s := by
+ unfold rightIndices
+ simpa only [Fintype.card_fin] using finrank_completedBlock_range v w (Fin.natAdd r)
+ (Fin.natAdd_injective _ _) h
+
+private theorem frameIndices_union (r : ℕ) : leftIndices r ∪ rightIndices r = univ := by
+ apply Set.eq_univ_of_forall
+ exact Fin.addCases (fun i ↦ Or.inl (mem_range_self i)) (fun i ↦ Or.inr (mem_range_self i))
+
+/-- The sum of the two completed blocks spans the full frame. -/
+theorem sup_frameBlocks (v : Fin (r + r) → V) (w : Fin s → V) :
+ (completedBlock v w (leftIndices r) : Submodule K V) ⊔ completedBlock v w (rightIndices r) =
+ span K (range (Sum.elim v w)) := by
+ rw [completedBlock, completedBlock, sup_sup_sup_comm, sup_idem, ← span_union,
+ ← Set.image_union, frameIndices_union, Set.image_univ, range_sumElim, span_union, sup_comm]
+
+/-- Dimension of the sum of the two blocks, with their common completion
+counted once. -/
+theorem finrank_sup_frameBlocks (v : Fin (r + r) → V) (w : Fin s → V)
+ (h : LinearIndependent K (Sum.elim v w)) :
+ Module.finrank K (completedBlock v w (leftIndices r) ⊔ completedBlock v w (rightIndices r) :
+ Submodule K V) = (r + r) + s := by
+ rw [sup_frameBlocks, finrank_span_eq_card h, Fintype.card_sum, Fintype.card_fin, Fintype.card_fin]
+
+/-- The middle-dimensional plane spanned by the first block and the completion. -/
+def leftPlane (v : Fin (r + r) → Space m) (w : Fin s → Space m) (hm : s + r = m)
+ (h : LinearIndependent (ZMod 2) (Sum.elim v w)) : Plane m :=
+ ⟨completedBlock (K := ZMod 2) v w (leftIndices r), (finrank_leftBlock v w h).trans ((Nat.add_comm r s).trans hm)⟩
+
+/-- The middle-dimensional plane spanned by the second block and the completion. -/
+def rightPlane (v : Fin (r + r) → Space m) (w : Fin s → Space m) (hm : s + r = m)
+ (h : LinearIndependent (ZMod 2) (Sum.elim v w)) : Plane m :=
+ ⟨completedBlock (K := ZMod 2) v w (rightIndices r), (finrank_rightBlock v w h).trans ((Nat.add_comm r s).trans hm)⟩
+
+/-- The two planes of a completed independent frame have Grassmann type `r`. -/
+theorem hasType_framePlanes (v : Fin (r + r) → Space m) (w : Fin s → Space m) (hm : s + r = m)
+ (h : LinearIndependent (ZMod 2) (Sum.elim v w)) :
+ HasType r (leftPlane v w hm h) (rightPlane v w hm h) :=
+ (finrank_sup_frameBlocks v w h).trans (show (r + r) + s = m + r by omega)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannFrameRigidity.lean b/lean/OAI/Computability/VPVNP/GrassmannFrameRigidity.lean
new file mode 100644
index 0000000000..3b1442206f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannFrameRigidity.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.GrassmannCompletion
+import OAI.Computability.VPVNP.GrassmannFrames
+import OAI.Computability.VPVNP.GrassmannFrameValue
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# Independence of the original columns and their completion
+
+The equality case of Lemma 5.3 first makes an observable on two completed
+block spans independent of the choice of completion. Moving an original column
+then preserves the observable as well: a common completion containing the
+difference of the two columns gives identical completed block spans.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Set Function Relation GrassmannFrames
+
+variable {K V Y : Type*} [Field K] [AddCommGroup V] [Module K V]
+
+private theorem independent_append {n s : ℕ} {v : Fin n → V} {w : Fin s → V} :
+ LinearIndependent K (Sum.elim v w) ↔ LinearIndependent K (Fin.append v w) :=
+ linearIndependent_equiv' finSumFinEquiv Fin.append_comp_sumElim
+
+private theorem completion_invariant {n s : ℕ} (hd : n + s < Module.finrank K V)
+ (E : (Fin n → V) → (Fin s → V) → Y)
+ (move : ∀ (v : Fin n → V) (w : Fin s → V) (i : Fin s) (x : V),
+ LinearIndependent K (Sum.elim v (Fin.snoc w x)) → E v w = E v (update w i x))
+ (v : Fin n → V) (w w' : Fin s → V)
+ (h : LinearIndependent K (Sum.elim v w)) (h' : LinearIndependent K (Sum.elim v w')) :
+ E v w = E v w' := by
+ let observable (p : Fin (n + s) → V) := E (p ∘ Fin.castAdd s) (p ∘ Fin.natAdd n)
+ have eval (a : Fin n → V) (b : Fin s → V) : observable (Fin.append a b) = E a b := by
+ simp [observable, Function.comp_def]
+ rw [← eval v w, ← eval v w']
+ apply GrassmannFrames.invariant (f := observable) _ hd
+ (independent_append.mp h) (independent_append.mp h')
+ · intro i hi
+ cases i using Fin.addCases with
+ | left i => simp
+ | right i => simp at hi
+ · intro p q step
+ obtain ⟨j, x, hj, hx, rfl⟩ := step
+ cases j using Fin.addCases with
+ | left j => exact (Nat.not_le_of_lt j.isLt hj).elim
+ | right j =>
+ let a := p ∘ Fin.castAdd s
+ let b := p ∘ Fin.natAdd n
+ have hab : Fin.append a b = p := Fin.append_castAdd_natAdd
+ have hind : LinearIndependent K (Sum.elim a (Fin.snoc b x)) := by
+ rw [independent_append, Fin.append_snoc, hab]
+ exact hx
+ have heq : update p (Fin.natAdd n j) x = Fin.append a (update b j x) := by
+ funext i
+ cases i using Fin.addCases with
+ | left i =>
+ have hne : Fin.castAdd s i ≠ Fin.natAdd n j := by
+ intro h
+ have := congrArg Fin.val h
+ simp only [Fin.val_castAdd, Fin.val_natAdd] at this
+ omega
+ simp [a, hne]
+ | right i =>
+ by_cases hji : i = j
+ · subst i
+ simp
+ · have hne : Fin.natAdd n i ≠ Fin.natAdd n j := by simpa using hji
+ simp [b, hne, hji]
+ rw [heq, eval]
+ exact move a b j x hind
+
+/-- If replacing a completion column outside the total span preserves the
+observable, its value is the same on all pairs of completed blocks of the
+given sizes. This holds over every field, including the binary one. -/
+theorem completed_blocks_rigid [FiniteDimensional K V] {n s : ℕ} (hs : 0 < s)
+ (hd : n + s < Module.finrank K V) (A B : Set (Fin n))
+ (D : Submodule K V → Submodule K V → Y)
+ (move : ∀ (v : Fin n → V) (w : Fin s → V) (i : Fin s) (x : V),
+ LinearIndependent K (Sum.elim v (Fin.snoc w x)) →
+ D (completedBlock v w A) (completedBlock v w B) =
+ D (completedBlock v (update w i x) A) (completedBlock v (update w i x) B))
+ {v v' : Fin n → V} {w w' : Fin s → V}
+ (h : LinearIndependent K (Sum.elim v w)) (h' : LinearIndependent K (Sum.elim v' w')) :
+ D (completedBlock v w A) (completedBlock v w B) =
+ D (completedBlock v' w' A) (completedBlock v' w' B) := by
+ let E (u : Fin n → V) (t : Fin s → V) := D (completedBlock u t A) (completedBlock u t B)
+ have same := completion_invariant hd E move
+ have chain {u u' : Fin n → V} (path : ReflTransGen (OutsideStep K 0) u u') :
+ ∀ {t t' : Fin s → V}, LinearIndependent K (Sum.elim u t) →
+ LinearIndependent K (Sum.elim u' t') → E u t = E u' t' := by
+ induction path with
+ | refl => exact fun {t t'} ht ht' => same u t t' ht ht'
+ | @tail b c path step ih =>
+ intro t t' ht ht'
+ rcases step with ⟨i, z, _, hz, rfl⟩
+ obtain ⟨u₁, _, hu₁, hu₂, span_eq⟩ :=
+ adjacent_commonCompletion (linearIndependent_finSnoc.mp hz).1 i z
+ (linearIndependent_finSnoc.mp hz).2 hs (by simpa using hd.le)
+ have hval : E b u₁ = E (update b i z) u₁ := congrArg₂ D (span_eq A) (span_eq B)
+ exact (ih ht hu₁).trans (hval.trans (same _ u₁ t' hu₂ ht'))
+ apply chain (connected_of_prefix (k := 0) (Nat.zero_le n) (by omega)
+ (h.comp Sum.inl Sum.inl_injective) (h'.comp Sum.inl Sum.inl_injective) (by simp))
+ · exact h
+ · exact h'
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannFrameValue.lean b/lean/OAI/Computability/VPVNP/GrassmannFrameValue.lean
new file mode 100644
index 0000000000..fb4c6a857d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannFrameValue.lean
@@ -0,0 +1,43 @@
+import Mathlib.LinearAlgebra.Dimension.Constructions
+import Mathlib.Data.Fin.Tuple.Basic
+
+/-!
+# Completed blocks of a Grassmannian frame
+
+The fixed columns in Lemma 5.3 come in two ordered blocks of equal size.
+Adjoining a common completion produces the two planes in the ordered pair.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Set Submodule
+
+variable {K V ι κ : Type*} [Field K] [AddCommGroup V] [Module K V]
+
+/-- The span of a chosen block together with all completion columns. -/
+def completedBlock {K : Type*} [Field K] [Module K V]
+ (v : ι → V) (w : κ → V) (T : Set ι) : Submodule K V :=
+ span K (range w) ⊔ span K (v '' T)
+
+/-- First block of an ordered pair of independent `r`-column tuples. -/
+def leftIndices (r : ℕ) : Set (Fin (r + r)) := range (Fin.castAdd r : Fin r → Fin (r + r))
+
+/-- Second block of an ordered pair of independent `r`-column tuples. -/
+def rightIndices (r : ℕ) : Set (Fin (r + r)) := range (Fin.natAdd r : Fin r → Fin (r + r))
+
+/-- Applying a linear automorphism to the whole frame takes its completed
+block to the image of the original completed block. -/
+theorem completedBlock_map (v : ι → V) (w : κ → V) (T : Set ι) (e : V ≃ₗ[K] V) :
+ (completedBlock v w T).map e.toLinearMap = completedBlock (e ∘ v) (e ∘ w) T := by
+ simp only [completedBlock, Submodule.map_sup, Submodule.map_span,
+ LinearEquiv.coe_coe, Set.range_comp, Set.image_comp]
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannFrames.lean b/lean/OAI/Computability/VPVNP/GrassmannFrames.lean
new file mode 100644
index 0000000000..83e6fb691b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannFrames.lean
@@ -0,0 +1,163 @@
+import Mathlib.LinearAlgebra.Dimension.Constructions
+import Mathlib.LinearAlgebra.LinearIndependent.Lemmas
+import Mathlib.Logic.Relation
+
+/-!
+# Column moves for Grassmannian rigidity
+
+In the equality case of Lemma 5.3 of *VP and VNP differ over every field*,
+a column may be replaced by any vector outside the span of the entire tuple.
+We show that these moves connect all ordered independent tuples with a fixed
+initial segment when there is at least one unused ambient dimension.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace GrassmannFrames
+
+open Function Set Relation
+
+variable {K V : Type*} [Field K] [AddCommGroup V] [Module K V]
+
+/-- A free column is replaced by a vector outside the current span. Independence
+of the extended tuple records both the original independence and the span condition. -/
+def OutsideStep (K : Type*) [Field K] [Module K V] (k : ℕ) {n : ℕ}
+ (v w : Fin n → V) : Prop :=
+ ∃ (i : Fin n) (x : V), k ≤ i.val ∧
+ LinearIndependent K (Fin.snoc v x : Fin (n + 1) → V) ∧ w = update v i x
+
+private theorem exchange_last {n : ℕ} {v : Fin n → V} {x : V} (i : Fin n)
+ (h : LinearIndependent K (Fin.snoc v x : Fin (n + 1) → V)) :
+ LinearIndependent K (Fin.snoc (update v i x) (v i) : Fin (n + 1) → V) := by
+ let e := Equiv.swap i.castSucc (Fin.last n)
+ have he : (Fin.snoc (update v i x) (v i) : Fin (n + 1) → V) = Fin.snoc v x ∘ e := by
+ funext j
+ cases j using Fin.lastCases with
+ | last => simp [e]
+ | cast j =>
+ by_cases hji : j = i
+ · subst j
+ simp [e]
+ · have h₁ : j.castSucc ≠ i.castSucc := by simpa using hji
+ have h₂ : j.castSucc ≠ Fin.last n := Fin.castSucc_ne_last j
+ simp [e, Equiv.swap_apply_of_ne_of_ne h₁ h₂, hji]
+ rw [he]
+ exact h.comp e e.injective
+
+theorem OutsideStep.symm {k n : ℕ} {v w : Fin n → V} (h : OutsideStep K k v w) :
+ OutsideStep K k w v := by
+ rcases h with ⟨i, x, hi, hx, rfl⟩
+ exact ⟨i, v i, hi, exchange_last i hx, by simp⟩
+
+theorem OutsideStep.source_independent {k n : ℕ} {v w : Fin n → V} (h : OutsideStep K k v w) :
+ LinearIndependent K v := by
+ rcases h with ⟨_, _, _, hx, _⟩
+ exact (linearIndependent_finSnoc.mp hx).1
+
+private theorem span_ne_top {n : ℕ} (h : n < Module.finrank K V) (v : Fin n → V) :
+ Submodule.span K (range v) ≠ ⊤ := by
+ intro heq
+ have := finrank_le_of_span_eq_top heq
+ simp only [Fintype.card_fin] at this
+ omega
+
+/-- Two partial tuples of length less than the dimension admit a common new
+column outside both spans, including over the binary field. -/
+theorem exists_outside_both {n : ℕ} (h : n < Module.finrank K V) (v w : Fin n → V) :
+ ∃ x, x ∉ Submodule.span K (range v) ∧ x ∉ Submodule.span K (range w) := by
+ by_contra! hem
+ have hs : ((⊤ : Submodule K V) : Set V) ⊆
+ (Submodule.span K (range v) : Set V) ∪ Submodule.span K (range w) := by
+ intro x _
+ by_cases hx : x ∈ Submodule.span K (range v)
+ · exact Or.inl hx
+ · exact Or.inr (hem x hx)
+ rcases AddSubgroupClass.subset_union.mp hs with hv | hw
+ · exact span_ne_top h v (top_le_iff.mp hv)
+ · exact span_ne_top h w (top_le_iff.mp hw)
+
+private theorem connect_last {n k : ℕ} (hk : k ≤ n) (hd : n + 1 < Module.finrank K V)
+ {v : Fin n → V} {a b : V}
+ (ha : LinearIndependent K (Fin.snoc v a : Fin (n + 1) → V))
+ (hb : LinearIndependent K (Fin.snoc v b : Fin (n + 1) → V)) :
+ ReflTransGen (OutsideStep K k) (Fin.snoc v a) (Fin.snoc v b) := by
+ obtain ⟨c, hc₁, hc₂⟩ := exists_outside_both hd (Fin.snoc v a) (Fin.snoc v b)
+ have hac : OutsideStep K k (Fin.snoc v a) (Fin.snoc v c) :=
+ ⟨Fin.last n, c, hk, ha.finSnoc hc₁, (Fin.update_snoc_last ..).symm⟩
+ have hbc : OutsideStep K k (Fin.snoc v b) (Fin.snoc v c) :=
+ ⟨Fin.last n, c, hk, hb.finSnoc hc₂, (Fin.update_snoc_last ..).symm⟩
+ exact (ReflTransGen.single hac).tail hbc.symm
+
+private theorem lift_step {n k : ℕ} (hk : k ≤ n) (hd : n + 1 < Module.finrank K V)
+ {v w : Fin n → V} (step : OutsideStep K k v w) {a b : V}
+ (ha : LinearIndependent K (Fin.snoc v a : Fin (n + 1) → V))
+ (hb : LinearIndependent K (Fin.snoc w b : Fin (n + 1) → V)) :
+ ReflTransGen (OutsideStep K k) (Fin.snoc v a) (Fin.snoc w b) := by
+ rcases step with ⟨i, x, hi, hx, rfl⟩
+ obtain ⟨c, hc, _⟩ := exists_outside_both hd (Fin.snoc v x) (Fin.snoc v x)
+ have hxc := hx.finSnoc hc
+ have hcx : LinearIndependent K (Fin.snoc (Fin.snoc v c) x : Fin (n + 2) → V) := by
+ simpa only [Fin.update_snoc_last, Fin.snoc_last] using exchange_last (Fin.last n) hxc
+ have mid : OutsideStep K k (Fin.snoc v c) (Fin.snoc (update v i x) c) :=
+ ⟨i.castSucc, x, hi, hcx, Fin.snoc_update ..⟩
+ exact ((connect_last hk hd ha mid.source_independent).tail mid).trans
+ (connect_last hk hd mid.symm.source_independent hb)
+
+private theorem lift_path {n k : ℕ} (hk : k ≤ n) (hd : n + 1 < Module.finrank K V)
+ {v w : Fin n → V} (path : ReflTransGen (OutsideStep K k) v w) {a b : V}
+ (ha : LinearIndependent K (Fin.snoc v a : Fin (n + 1) → V))
+ (hb : LinearIndependent K (Fin.snoc w b : Fin (n + 1) → V)) :
+ ReflTransGen (OutsideStep K k) (Fin.snoc v a) (Fin.snoc w b) := by
+ induction path generalizing b with
+ | refl => exact connect_last hk hd ha hb
+ | @tail u w _ step ih =>
+ obtain ⟨c, hc, _⟩ := exists_outside_both (Nat.lt_trans (Nat.lt_succ_self n) hd) u u
+ have hu := step.source_independent.finSnoc hc
+ exact (ih hu).trans (lift_step hk hd step hu hb)
+
+/-- All independent tuples with a prescribed initial segment are connected by
+moves that leave this segment fixed and insert a column outside the current span. -/
+theorem connected {k n : ℕ} (hd : k + n < Module.finrank K V) {v w : Fin (k + n) → V}
+ (hv : LinearIndependent K v) (hw : LinearIndependent K w)
+ (hfixed : ∀ i, i.val < k → v i = w i) : ReflTransGen (OutsideStep K k) v w := by
+ induction n with
+ | zero =>
+ have : v = w := funext fun i => hfixed i i.isLt
+ rw [this]
+ | succ n ih =>
+ have hv' := (linearIndependent_finSucc'.mp hv).1
+ have hw' := (linearIndependent_finSucc'.mp hw).1
+ have path := ih (by omega) hv' hw' (fun i hi => hfixed i.castSucc hi)
+ have ha := (Fin.snoc_init_self v).symm ▸ hv
+ have hb := (Fin.snoc_init_self w).symm ▸ hw
+ have hp := lift_path (Nat.le_add_right k n) hd path ha hb
+ exact (Fin.snoc_init_self v) ▸ (Fin.snoc_init_self w) ▸ hp
+
+/-- A length-indexed version of connectivity for a prescribed prefix. -/
+theorem connected_of_prefix {k l : ℕ} (hk : k ≤ l) (hd : l < Module.finrank K V)
+ {v w : Fin l → V} (hv : LinearIndependent K v) (hw : LinearIndependent K w)
+ (hfixed : ∀ i, i.val < k → v i = w i) : ReflTransGen (OutsideStep K k) v w := by
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_add_of_le hk
+ exact connected hd hv hw hfixed
+
+/-- Any quantity preserved by outside-column replacements is constant on the
+independent completions of a fixed tuple. -/
+theorem invariant {Y : Type*} {k n : ℕ} {f : (Fin (k + n) → V) → Y}
+ (hstep : ∀ {v w}, OutsideStep K k v w → f v = f w)
+ (hd : k + n < Module.finrank K V) {v w : Fin (k + n) → V}
+ (hv : LinearIndependent K v) (hw : LinearIndependent K w)
+ (hfixed : ∀ i, i.val < k → v i = w i) : f v = f w := by
+ have along : ∀ {u t : Fin (k + n) → V}, ReflTransGen (OutsideStep K k) u t → f u = f t := by
+ intro u t path
+ induction path with
+ | refl => rfl
+ | tail _ step ih => exact ih.trans (hstep step)
+ exact along (connected hd hv hw hfixed)
+
+end GrassmannFrames
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannGeometry.lean b/lean/OAI/Computability/VPVNP/GrassmannGeometry.lean
new file mode 100644
index 0000000000..caa03ea874
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannGeometry.lean
@@ -0,0 +1,44 @@
+import OAI.Computability.VPVNP.GrassmannFourPoint
+
+/-!
+# CAT(0) quadrilaterals
+
+The proof of Lemma 5.3 of *VP and VNP differ over every field* averages
+the squared quadrilateral inequality over subspace rectangles. At equality
+both pairs of opposite sides have equal lengths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {X : Type*} [PseudoMetricSpace X]
+
+private theorem distance_quadBounds (h : HasCATZeroSegments X) :
+ Grassmann.QuadBounds (fun a b : X => dist a b ^ 2) := by
+ have hbound := Grassmann.quadBounds_of_mem_catZeroArrays
+ (Grassmann.scaledDistSq_mem_catZeroArrays h (id : X → X) zero_le_one)
+ simpa only [id_eq, one_mul] using hbound
+
+/-- The squared quadrilateral inequality (4.3), with cyclic vertices `a,b,c,d`. -/
+theorem quadrilateral_sq (h : HasCATZeroSegments X) (a b c d : X) :
+ dist a c ^ 2 + dist b d ^ 2 ≤
+ dist a b ^ 2 + dist b c ^ 2 + dist c d ^ 2 + dist d a ^ 2 :=
+ (distance_quadBounds h).quad a b c d
+
+/-- Equality of the squared diagonals and sides forces equality of opposite
+side lengths, as used in the Grassmannian rigidity argument. -/
+theorem quadrilateral_eq_opposite (h : HasCATZeroSegments X) (a b c d : X)
+ (heq : dist a c ^ 2 + dist b d ^ 2 =
+ dist a b ^ 2 + dist b c ^ 2 + dist c d ^ 2 + dist d a ^ 2) :
+ dist a b = dist c d ∧ dist b c = dist d a := by
+ obtain ⟨hab, hbc⟩ := (distance_quadBounds h).opposite a b c d heq
+ exact ⟨(sq_eq_sq₀ dist_nonneg dist_nonneg).mp hab, (sq_eq_sq₀ dist_nonneg dist_nonneg).mp hbc⟩
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannIndependent.lean b/lean/OAI/Computability/VPVNP/GrassmannIndependent.lean
new file mode 100644
index 0000000000..77cea6d55e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannIndependent.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.GrassmannTypes
+import Mathlib.Algebra.Field.ZMod
+import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas
+
+/-!
+# Independent readings on complementary planes
+
+A linear map on the ambient binary vector space is uniquely determined by
+its values on chosen bases of two complementary middle-dimensional subspaces.
+Consequently a uniform linear map gives two independent uniform tuples there.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+variable {m : ℕ}
+
+theorem HasType.isCompl {U V : Plane m} (h : HasType m U V) : IsCompl U.val V.val := by
+ change Module.finrank (ZMod 2) (U.val ⊔ V.val : Submodule _ _) = m + m at h
+ apply IsCompl.of_eq
+ · apply Submodule.finrank_eq_zero.mp
+ have hd := Submodule.finrank_sup_add_finrank_inf_eq U.val V.val
+ rw [h, U.property, V.property] at hd
+ omega
+ · apply Submodule.eq_top_of_finrank_eq
+ simpa only [Space, Module.finrank_pi, Fintype.card_fin, two_mul] using h
+
+/-- The fixed ordered basis used to read the restriction of a linear map. -/
+noncomputable def planeBasis (U : Plane m) : Module.Basis (Fin m) (ZMod 2) U.val :=
+ Module.finBasisOfFinrankEq (ZMod 2) U.val U.property
+
+variable (E : Type*) [AddCommGroup E] [Module (ZMod 2) E]
+
+/-- Values on the fixed ordered basis of a plane. -/
+noncomputable def readPlane (U : Plane m) (f : Space m →ₗ[ZMod 2] E) : Fin m → E :=
+ fun i => f (planeBasis U i)
+
+/-- Reading both members of a complementary pair is a bijection. -/
+noncomputable def readComplementEquiv {U V : Plane m} (h : HasType m U V) :
+ (Space m →ₗ[ZMod 2] E) ≃ (Fin m → E) × (Fin m → E) :=
+ (LinearMap.ofIsComplProdEquiv h.isCompl).symm.toEquiv.trans
+ (((planeBasis U).constr (ZMod 2)).symm.toEquiv.prodCongr
+ ((planeBasis V).constr (ZMod 2)).symm.toEquiv)
+
+@[simp] theorem readComplementEquiv_apply {U V : Plane m} (h : HasType m U V)
+ (f : Space m →ₗ[ZMod 2] E) :
+ readComplementEquiv E h f = (readPlane E U f, readPlane E V f) := rfl
+
+noncomputable instance [Finite E] : Fintype (Space m →ₗ[ZMod 2] E) :=
+ @Fintype.ofFinite _ (Finite.of_injective (fun f : Space m →ₗ[ZMod 2] E => (f : Space m → E))
+ DFunLike.coe_injective)
+
+/-- The sum over the sampled linear map is a sum over two independent tuples. -/
+theorem sum_read_complement [Fintype E] {U V : Plane m} (h : HasType m U V)
+ {A : Type*} [AddCommMonoid A] (d : (Fin m → E) → (Fin m → E) → A) :
+ (∑ f : Space m →ₗ[ZMod 2] E, d (readPlane E U f) (readPlane E V f)) =
+ ∑ x : Fin m → E, ∑ y : Fin m → E, d x y := by
+ classical
+ rw [← Fintype.sum_prod_type']
+ exact (readComplementEquiv E h).sum_comp (fun z => d z.1 z.2)
+
+/-- Averaging a two-point observable on complementary planes gives the product law. -/
+theorem average_read_complement [Fintype E] {U V : Plane m} (h : HasType m U V)
+ (d : (Fin m → E) → (Fin m → E) → ℝ) :
+ (∑ f : Space m →ₗ[ZMod 2] E, d (readPlane E U f) (readPlane E V f)) /
+ Fintype.card (Space m →ₗ[ZMod 2] E) =
+ (∑ x : Fin m → E, ∑ y : Fin m → E, d x y) / (Fintype.card (Fin m → E) : ℝ) ^ 2 := by
+ rw [sum_read_complement E h, Fintype.card_congr (readComplementEquiv E h),
+ Fintype.card_prod, Nat.cast_mul, sq]
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannInequality.lean b/lean/OAI/Computability/VPVNP/GrassmannInequality.lean
new file mode 100644
index 0000000000..a0d313e79a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannInequality.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.CubeExclusion
+import OAI.Computability.VPVNP.GrassmannEnergy
+import OAI.Computability.VPVNP.GrassmannPlaneRigidity
+import OAI.Computability.VPVNP.GrassmannPresentation
+
+/-!
+# The strict Grassmann inequality
+
+Lemma 5.3 of *VP and VNP differ over every field* gives a strict, uniform
+improvement over the bound by the Grassmann plane dimension `m` when all
+target spaces exclude a Euclidean cube of some dimension less than `m`.
+The proof here identifies the extremal distances on all pairs of type
+`r < m`, exhibits the cube on the coordinate planes, and uses compactness
+of normalized finite distance arrays to obtain the uniform gap.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open scoped symmDiff
+
+variable {m r : ℕ}
+
+private theorem equal_on_type {D : Plane m → Plane m → ℝ} (hr : r < m)
+ (opp : ∀ a b c d, IsSquare r 1 a b c d → D a b = D d c)
+ {a b a' b' : Plane m} (hab : HasType r a b) (hab' : HasType r a' b') :
+ D a b = D a' b' := by
+ obtain ⟨v, w, hind, hl, hu⟩ := hab.exists_frame hr.le
+ obtain ⟨v', w', hind', hl', hu'⟩ := hab'.exists_frame hr.le
+ let hm := Nat.sub_add_cancel hr.le
+ rw [show a = leftPlane v w hm hind from Subtype.ext hl,
+ show b = rightPlane v w hm hind from Subtype.ext hu,
+ show a' = leftPlane v' w' hm hind' from Subtype.ext hl',
+ show b' = rightPlane v' w' hm hind' from Subtype.ext hu']
+ exact frame_planes_rigid hr hm D opp hind hind'
+
+/-- At a saturated normalized array every ordered pair of type `r < m`
+has squared distance exactly `r`. -/
+theorem value_eq_type_of_saturated {D : Plane m → Plane m → ℝ} (hq : QuadBounds D)
+ (h1 : mean D 1 = 1) (hm : mean D m = (m : ℝ)) (hr : r < m)
+ {a b : Plane m} (hab : HasType r a b) : D a b = (r : ℝ) := by
+ have hs (k : ℕ) (hk : k ≤ m) : mean D k = (k : ℝ) := by
+ simpa only [h1, mul_one] using mean_eq_mul_one hq.quad hq.diag
+ (by simpa only [h1, mul_one] using hm) hk
+ have hopp (a b c d : Plane m) (sq : IsSquare r 1 a b c d) : D a b = D d c := by
+ have he := sq.eq_of_mean_eq_add hq.quad (by
+ rw [hs (r+1) hr, hs r hr.le, h1, Nat.cast_add, Nat.cast_one])
+ exact (hq.opposite a b c d he).1.trans (hq.symm c d)
+ have hc (p : Pair m r) : D p.val.1 p.val.2 = D a b :=
+ equal_on_type hr hopp p.property hab
+ let : Nonempty (Pair m r) := ⟨⟨(a,b), hab⟩⟩
+ have hmean : mean D r = D a b := by
+ simp only [mean, hc, Finset.sum_const, Finset.card_univ, nsmul_eq_mul]
+ exact mul_div_cancel_left₀ _ (Nat.cast_ne_zero.mpr Fintype.card_ne_zero)
+ exact hmean.symm.trans (hs r hr.le)
+
+/-- The equality case of Lemma 5.3 gives the marked Euclidean cube, with
+Hamming distance as its squared distance. -/
+theorem cube_of_saturated {ℓ : ℕ} (hℓ : ℓ < m) {D : Plane m → Plane m → ℝ}
+ (hq : QuadBounds D) (h1 : mean D 1 = 1) (hm : mean D m = (m : ℝ)) :
+ ∃ e : Finset (Fin ℓ) → Plane m, ∀ i j, D (e i) (e j) = ((i ∆ j).card : ℝ) := by
+ obtain ⟨e, he⟩ := exists_cube_face hℓ.le
+ refine ⟨e, fun i j => value_eq_type_of_saturated hq h1 hm ?_ (he i j)⟩
+ exact lt_of_le_of_lt (by simpa using Finset.card_le_univ (i ∆ j)) hℓ
+
+/-- Lemma 5.3. The improvement over the factor `m` is uniform in both the
+target space and the configuration of its Grassmannian points. -/
+theorem strict_grassmann_bound {κ : Type*} (X : κ → Type*) [∀ k, PseudoMetricSpace (X k)]
+ {ℓ m : ℕ} (hℓ : ℓ < m) (hcat : ∀ k, SpectralGeometry.HasCATZeroSegments (X k))
+ (hexclude : cubeDistances ℓ ∉ closure (markedDistances X (Finset (Fin ℓ)))) :
+ ∃ η > 0, ∀ (k : κ) (x : Plane m → X k), energy x m ≤ ((m : ℝ) - η) * energy x 1 :=
+ strict_grassmann_bound_of_rigidity X m (fun i j : Finset (Fin ℓ) => ((i ∆ j).card : ℝ))
+ hcat hexclude (fun _ hq _ hr => mean_le_mul_one hq.quad hq.diag hr)
+ (fun _ hq h1 hm => cube_of_saturated hℓ hq h1 hm)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannMeanBounds.lean b/lean/OAI/Computability/VPVNP/GrassmannMeanBounds.lean
new file mode 100644
index 0000000000..154ab86301
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannMeanBounds.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.GrassmannTypes
+import Mathlib.Topology.Instances.Real.Lemmas
+import Mathlib.Topology.Algebra.GroupWithZero
+import Mathlib.LinearAlgebra.Dimension.Constructions
+
+/-!
+# Bounds for normalized Grassmann distance arrays
+
+The means over ordered pairs of fixed type are continuous linear averages.
+Nonnegative arrays satisfying the typewise mean bounds of Section 5 have
+uniformly bounded entries. This gives a common compact box for the normalized
+arrays, even when the target CAT(0) space varies.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+theorem continuous_mean (m r : ℕ) : Continuous (fun D : Plane m → Plane m → ℝ => mean D r) := by
+ unfold mean
+ apply Continuous.div_const
+ exact continuous_finsetSum Finset.univ fun p _ =>
+ (continuous_apply p.val.2).comp (continuous_apply p.val.1)
+
+theorem mean_smul {m : ℕ} (D : Plane m → Plane m → ℝ) (r : ℕ) (s : ℝ) :
+ mean (fun a b => s * D a b) r = s * mean D r := by
+ simp only [mean, ← Finset.mul_sum, mul_div_assoc]
+
+theorem mean_nonneg {m : ℕ} {D : Plane m → Plane m → ℝ}
+ (hD : ∀ a b, 0 ≤ D a b) (r : ℕ) : 0 ≤ mean D r := by
+ exact div_nonneg (Finset.sum_nonneg fun p _ => hD p.val.1 p.val.2) (Nat.cast_nonneg _)
+
+/-- Every ordered pair has type between zero and the plane dimension. -/
+theorem exists_type_le {m : ℕ} (a b : Plane m) : ∃ r ≤ m, HasType r a b := by
+ let U := a.val ⊔ b.val
+ have hlo : m ≤ Module.finrank (ZMod 2) U := by
+ exact a.property.ge.trans (Submodule.finrank_mono le_sup_left)
+ have hhi : Module.finrank (ZMod 2) U ≤ 2 * m := by
+ simpa only [Space, Module.finrank_pi, Fintype.card_fin] using U.finrank_le
+ refine ⟨Module.finrank (ZMod 2) U - m, by omega, ?_⟩
+ change Module.finrank (ZMod 2) U = m + (Module.finrank (ZMod 2) U - m)
+ omega
+
+theorem exists_coordinate_bound (m : ℕ) :
+ ∃ K : ℝ, ∀ D : Plane m → Plane m → ℝ, (∀ a b, 0 ≤ D a b) →
+ (∀ r ≤ m, mean D r ≤ r) → ∀ a b, D a b ≤ K := by
+ refine ⟨(m : ℝ) * (Fintype.card (Plane m) : ℝ) ^ 2, ?_⟩
+ intro D hD hmean a b
+ obtain ⟨r, hr, ht⟩ := exists_type_le a b
+ let p : Pair m r := ⟨(a, b), ht⟩
+ let : Nonempty (Pair m r) := ⟨p⟩
+ have hpos : 0 < (Fintype.card (Pair m r) : ℝ) := by exact_mod_cast Fintype.card_pos
+ have hcard : Fintype.card (Pair m r) ≤ Fintype.card (Plane m) ^ 2 := by
+ simpa only [Fintype.card_prod, pow_two] using
+ Fintype.card_le_of_injective (fun x : Pair m r => x.val) Subtype.val_injective
+ calc
+ D a b ≤ ∑ t : Pair m r, D t.val.1 t.val.2 :=
+ Finset.single_le_sum (fun (t : Pair m r) _ => hD t.val.1 t.val.2) (Finset.mem_univ p)
+ _ ≤ (r : ℝ) * Fintype.card (Pair m r) := (div_le_iff₀ hpos).mp (hmean r hr)
+ _ ≤ _ := mul_le_mul (by exact_mod_cast hr) (by exact_mod_cast hcard) hpos.le (Nat.cast_nonneg _)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannMoveSquare.lean b/lean/OAI/Computability/VPVNP/GrassmannMoveSquare.lean
new file mode 100644
index 0000000000..c4c61e3ae6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannMoveSquare.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.CompletionReplacement
+import OAI.Computability.VPVNP.GrassmannFrameDimensions
+
+/-!
+# The quadrilateral of a completion-column move
+
+In the equality argument of Lemma 5.3, replace one column of the common
+completion by a vector outside the entire frame. The two original planes
+and the two new planes form a square of types `r` and one. The sums across
+the move use both the old and the new column, so their dimensions can be
+read off from the extended independent frame.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Set Submodule Function
+
+private theorem sup_completedBlock_replacement {K V ι : Type*} [Field K] [AddCommGroup V]
+ [Module K V] {s : ℕ} (v : ι → V) (w : Fin s → V) (i : Fin s) (x : V) (S T : Set ι) :
+ completedBlock (K := K) v w S ⊔ completedBlock v (update w i x) T =
+ completedBlock v (Fin.snoc w x) S ⊔ completedBlock v (Fin.snoc w x) T := by
+ unfold completedBlock
+ rw [sup_sup_sup_comm, span_completion_sup_replacement, ← sup_sup_distrib_left]
+
+/-- The old left, old right, new right, and new left completed blocks have
+dimension `m`. In this cyclic order they form an `(r, 1)` square. -/
+theorem completion_move_square {m r s : ℕ} {v : Fin (r + r) → Space m}
+ {w : Fin s → Space m} {x : Space m} (hm : s + r = m) (i : Fin s)
+ (h : LinearIndependent (ZMod 2) (Sum.elim v (Fin.snoc w x))) :
+ ∃ a b c d : Plane m,
+ a.val = completedBlock v w (leftIndices r) ∧
+ b.val = completedBlock v w (rightIndices r) ∧
+ c.val = completedBlock v (update w i x) (rightIndices r) ∧
+ d.val = completedBlock v (update w i x) (leftIndices r) ∧ IsSquare r 1 a b c d := by
+ have ho := independent_completion_init h
+ have hn := independent_completion_replacement i h
+ refine ⟨leftPlane v w hm ho, rightPlane v w hm ho, rightPlane v _ hm hn,
+ leftPlane v _ hm hn, rfl, rfl, rfl, rfl, ?_⟩
+ let dim (U : Submodule (ZMod 2) (Space m)) := Module.finrank (ZMod 2) U
+ let L {k : ℕ} (t : Fin k → Space m) := completedBlock (K := ZMod 2) v t (leftIndices r)
+ let R {k : ℕ} (t : Fin k → Space m) := completedBlock (K := ZMod 2) v t (rightIndices r)
+ constructor
+ · exact hasType_framePlanes v w hm ho
+ · change dim (R w ⊔ R (update w i x)) = _
+ rw [sup_completedBlock_replacement, sup_idem]
+ exact (finrank_rightBlock v _ h).trans (by omega)
+ · change dim (R (update w i x) ⊔ L (update w i x)) = _
+ rw [sup_comm]
+ exact (finrank_sup_frameBlocks v _ hn).trans (by omega)
+ · change dim (L (update w i x) ⊔ L w) = _
+ rw [sup_comm, sup_completedBlock_replacement, sup_idem]
+ exact (finrank_leftBlock v _ h).trans (by omega)
+ · change dim (L w ⊔ R (update w i x)) = _
+ rw [sup_completedBlock_replacement]
+ exact (finrank_sup_frameBlocks v _ h).trans (by omega)
+ · change dim (R w ⊔ L (update w i x)) = _
+ rw [sup_completedBlock_replacement, sup_comm]
+ exact (finrank_sup_frameBlocks v _ h).trans (by omega)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannPlaneRigidity.lean b/lean/OAI/Computability/VPVNP/GrassmannPlaneRigidity.lean
new file mode 100644
index 0000000000..860f7efb30
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannPlaneRigidity.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.GrassmannFrameRigidity
+import OAI.Computability.VPVNP.GrassmannFrameDimensions
+import OAI.Computability.VPVNP.GrassmannMoveSquare
+
+/-!
+# Equality rigidity for two completed block spans
+
+Opposite-side equality on every Grassmann square of type `(r, 1)` determines
+the value of a pair observable on every ordered pair presented by a frame
+of two independent blocks of size `r` with a common completion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Function
+
+/-- Opposite sides of type `r` in equality squares force the same value for
+all ordered frame presentations of type `r < m`. -/
+theorem frame_planes_rigid {m r s : ℕ} (hr : r < m) (hm : s + r = m)
+ (D : Plane m → Plane m → ℝ)
+ (opp : ∀ a b c d, IsSquare r 1 a b c d → D a b = D d c)
+ {v v' : Fin (r + r) → Space m} {w w' : Fin s → Space m}
+ (h : LinearIndependent (ZMod 2) (Sum.elim v w))
+ (h' : LinearIndependent (ZMod 2) (Sum.elim v' w')) :
+ D (leftPlane v w hm h) (rightPlane v w hm h) =
+ D (leftPlane v' w' hm h') (rightPlane v' w' hm h') := by
+ classical
+ let E (U V : Submodule (ZMod 2) (Space m)) :=
+ if hU : Module.finrank (ZMod 2) U = m then
+ if hV : Module.finrank (ZMod 2) V = m then D ⟨U, hU⟩ ⟨V, hV⟩ else 0
+ else 0
+ have eval (a b : Plane m) : E a.val b.val = D a b := by
+ simp only [E, dite_eq_left a.property, dite_eq_left b.property]
+ rfl
+ rw [← eval, ← eval (leftPlane v' w' hm h') (rightPlane v' w' hm h')]
+ apply completed_blocks_rigid (K := ZMod 2) (A := leftIndices r) (B := rightIndices r)
+ (by omega) (by simp only [Module.finrank_pi, Fintype.card_fin]; omega) E _ h h'
+ intro u t i x hi
+ obtain ⟨a, b, c, d, ha, hb, hc, hd, sq⟩ := completion_move_square hm i hi
+ rw [← ha, ← hb, ← hc, ← hd, eval, eval]
+ exact opp a b c d sq
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannPresentation.lean b/lean/OAI/Computability/VPVNP/GrassmannPresentation.lean
new file mode 100644
index 0000000000..25c9d01770
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannPresentation.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.GrassmannFrameDimensions
+import OAI.Computability.VPVNP.IndependentCompletion
+import OAI.Computability.VPVNP.SubspaceOrbits
+
+/-!
+# A frame presentation for any Grassmannian pair
+
+Two planes of type `r` have a presentation by two independent `r`-column
+blocks and a shared completion of `m-r` columns. We transport one independent
+frame by an ambient linear automorphism carrying its two planes to the given
+pair.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+/-- Every ordered pair of type `r` admits the independent column presentation
+used in the opposite-side rigidity proof of Lemma 5.3. -/
+theorem HasType.exists_frame {m r : ℕ} {a b : Plane m} (hab : HasType r a b) (hr : r ≤ m) :
+ ∃ (v : Fin (r + r) → Space m) (w : Fin (m - r) → Space m),
+ LinearIndependent (ZMod 2) (Sum.elim v w) ∧
+ a.val = completedBlock v w (leftIndices r) ∧
+ b.val = completedBlock v w (rightIndices r) := by
+ have hdim : Module.finrank (ZMod 2) (Space m) = 2*m := by simp [Space]
+ obtain ⟨v, hv⟩ := exists_linearIndependent_of_le_finrank
+ (show r + r ≤ Module.finrank (ZMod 2) (Space m) by omega)
+ obtain ⟨w, hw⟩ := exists_independent_completion hv (k := m - r) (by simp; omega)
+ have hm : (m - r) + r = m := Nat.sub_add_cancel hr
+ let l := leftPlane v w hm hw
+ let u := rightPlane v w hm hw
+ have htype : HasType r l u := hasType_framePlanes v w hm hw
+ obtain ⟨g, gl, gu⟩ := exists_pair_linearEquiv (K := ZMod 2) (V := Space m) l.val u.val
+ a.val b.val (l.property.trans a.property.symm) (u.property.trans b.property.symm)
+ (htype.trans hab.symm)
+ have hind : LinearIndependent (ZMod 2) (g.toLinearMap ∘ Sum.elim v w) :=
+ (g.toLinearMap.linearIndependent_iff g.ker).mpr hw
+ have hf : g.toLinearMap ∘ Sum.elim v w = Sum.elim (g ∘ v) (g ∘ w) := by
+ funext i
+ cases i <;> rfl
+ refine ⟨g ∘ v, g ∘ w, hf ▸ hind, ?_, ?_⟩
+ · exact gl.symm.trans (completedBlock_map v w (leftIndices r) g)
+ · exact gu.symm.trans (completedBlock_map v w (rightIndices r) g)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannSampling.lean b/lean/OAI/Computability/VPVNP/GrassmannSampling.lean
new file mode 100644
index 0000000000..179b4b034e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannSampling.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.GrassmannIndependent
+import OAI.Computability.VPVNP.GrassmannAdjacentFrame
+import OAI.Computability.VPVNP.UniformLinearSampling
+
+/-!
+# Conditional sampling on adjacent Grassmannian planes
+
+Section 5.2 of *VP and VNP differ over every field* samples a linear map
+on the whole ambient space. On adjacent planes, the joint law of its basis
+readings consists of one shared tuple on the intersection and two independent
+values on the extension columns. Changes of basis express both endpoints in
+the fixed vertex coordinates.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+variable {n : ℕ} (E : Type*) [AddCommGroup E] [Module (ZMod 2) E]
+
+private def appendCoordinate :
+ ((Fin n → E) × E) ≃ (Fin (n + 1) → E) :=
+ (Equiv.prodComm _ _).trans (Fin.snocEquiv (fun _ ↦ E))
+
+private noncomputable def readInFixedBasis (U : Plane (n + 1)) (b : Fin n → Space (n + 1))
+ (a : Space (n + 1)) (hi : LinearIndependent (ZMod 2) (Fin.snoc b a : Fin (n+1) → _))
+ (hs : Submodule.span (ZMod 2) (Set.range (Fin.snoc b a : Fin (n+1) → _)) = U.val) :
+ ((Fin n → E) × E) ≃ (Fin (n+1) → E) :=
+ let b' := (Module.Basis.span hi).map (LinearEquiv.ofEq _ _ hs)
+ ((appendCoordinate E).trans (b'.constr (ZMod 2)).toEquiv).trans
+ ((planeBasis U).constr (ZMod 2)).symm.toEquiv
+
+private theorem readInFixedBasis_apply (U : Plane (n + 1)) (b : Fin n → Space (n+1))
+ (a : Space (n+1)) (hi : LinearIndependent (ZMod 2) (Fin.snoc b a : Fin (n+1) → _))
+ (hs : Submodule.span (ZMod 2) (Set.range (Fin.snoc b a : Fin (n+1) → _)) = U.val)
+ (f : Space (n + 1) →ₗ[ZMod 2] E) :
+ readInFixedBasis E U b a hi hs (fun i ↦ f (b i), f a) = readPlane E U f := by
+ let b' := (Module.Basis.span hi).map (LinearEquiv.ofEq _ _ hs)
+ have he : b'.constr (ZMod 2) (appendCoordinate E (fun i ↦ f (b i), f a)) =
+ f.comp U.val.subtype := by
+ apply b'.ext
+ intro j
+ rw [Module.Basis.constr_basis]
+ change (Fin.snoc (fun i ↦ f (b i)) (f a) : Fin (n+1) → E) j = f ((b' j : U.val) : Space (n+1))
+ have hbj : ((b' j : U.val) : Space (n+1)) = (Fin.snoc b a : Fin (n+1) → Space (n+1)) j := by
+ simp [b', Module.Basis.map_apply]
+ rw [hbj]
+ cases j using Fin.lastCases <;> simp
+ change ((planeBasis U).constr (ZMod 2)).symm (b'.constr (ZMod 2) _) = _
+ rw [he]
+ rfl
+
+private def appendTwoCoordinates :
+ (((Fin n → E) × E) × E) ≃ (Fin (n + 2) → E) :=
+ ((appendCoordinate E).prodCongr (Equiv.refl E)).trans (appendCoordinate E)
+
+private theorem appendTwoCoordinates_eval (b : Fin n → Space (n+1)) (a c : Space (n+1))
+ (f : Space (n+1) →ₗ[ZMod 2] E) :
+ appendTwoCoordinates E ((fun i ↦ f (b i), f a), f c) =
+ fun j ↦ f ((Fin.snoc (Fin.snoc b a) c : Fin (n+2) → Space (n+1)) j) := by
+ funext j
+ change (Fin.snoc (Fin.snoc (fun i ↦ f (b i)) (f a)) (f c) : Fin (n+2) → E) j =
+ f ((Fin.snoc (Fin.snoc b a) c : Fin (n+2) → Space (n+1)) j)
+ cases j using Fin.lastCases with
+ | last => simp
+ | cast j => cases j using Fin.lastCases <;> simp
+
+/-- For any observable of the two endpoints, the mean over all linear maps is
+exactly the mean over the two extensions of the common restriction. Both
+endpoint charts are independent of the observable. -/
+theorem exists_adjacent_charts [Fintype E] (p : Pair (n+1) 1) :
+ ∃ l r : ((Fin n → E) × E) ≃ (Fin (n+1) → E), ∀ g : (Fin (n+1) → E) → (Fin (n+1) → E) → ℝ,
+ (∑ f : Space (n+1) →ₗ[ZMod 2] E, g (readPlane E p.val.1 f) (readPlane E p.val.2 f)) /
+ Fintype.card (Space (n+1) →ₗ[ZMod 2] E) =
+ ((∑ i, ∑ a, ∑ c, g (l (i,a)) (r (i,c))) / Fintype.card E) / Fintype.card (Fin (n+1) → E) := by
+ obtain ⟨b, u, v, hw, hu, hv, hsu, hsv⟩ := exists_adjacent_frame p
+ let l := readInFixedBasis E p.val.1 b u hu hsu
+ let r := readInFixedBasis E p.val.2 b v hv hsv
+ refine ⟨l, r, ?_⟩
+ intro g
+ let d (z : ((Fin n → E) × E) × E) := g (l z.1) (r (z.1.1, z.2))
+ let e := appendTwoCoordinates (n := n) E
+ let w := (Fin.snoc (Fin.snoc b u) v : Fin (n+2) → Space (n+1))
+ have hread (f : Space (n+1) →ₗ[ZMod 2] E) :
+ d (e.symm (fun j ↦ f (w j))) = g (readPlane E p.val.1 f) (readPlane E p.val.2 f) := by
+ have he : e.symm (fun j ↦ f (w j)) = ((fun i ↦ f (b i), f u), f v) :=
+ e.symm_apply_eq.mpr (appendTwoCoordinates_eval E b u v f).symm
+ simp only [he, d, l, r, readInFixedBasis_apply]
+ have hs : (∑ y : Fin (n+2) → E, d (e.symm y)) = ∑ i, ∑ a, ∑ c, g (l (i,a)) (r (i,c)) := by
+ rw [← e.sum_comp (fun y ↦ d (e.symm y))]
+ simp only [Equiv.symm_apply_apply, Fintype.sum_prod_type, d]
+ have hcard : (Fintype.card (Fin (n+2) → E) : ℝ) =
+ Fintype.card E * (Fintype.card (Fin (n+1) → E) : ℝ) := by
+ have hc := Fintype.card_congr (appendCoordinate (n := n+1) E).symm
+ rw [Fintype.card_prod, Nat.mul_comm] at hc
+ exact_mod_cast hc
+ have h := SpectralGeometry.uniformAverage_frame_eval w hw (fun y ↦ d (e.symm y))
+ simp only [hread, hs, hcard] at h
+ simpa only [div_div] using h
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannSeeds.lean b/lean/OAI/Computability/VPVNP/GrassmannSeeds.lean
new file mode 100644
index 0000000000..49c1ba7381
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannSeeds.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.GrassmannTypes
+import Mathlib.LinearAlgebra.Dimension.Constructions
+import Mathlib.Data.Finset.SymmDiff
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# Coordinate configurations in the binary Grassmannian
+
+Pair the coordinates in the ambient space and choose one from each pair. The
+sum dimension of two resulting planes is the common plane dimension plus the
+Hamming distance between the choices. Flipping two disjoint blocks of pairs
+gives the quadrilateral used in the averaging argument of Lemma 5.3.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open scoped symmDiff
+
+variable {m : ℕ}
+
+private def selectedRow (A : Finset (Fin m)) (i : Fin m) : Fin 2 :=
+ if i ∈ A then 1 else 0
+
+private def rowEmbedding (A : Finset (Fin m)) : Fin m ↪ Fin 2 × Fin m :=
+ ⟨fun i ↦ (selectedRow A i, i), fun _ _ h ↦ congrArg Prod.snd h⟩
+
+private def rows (A : Finset (Fin m)) : Finset (Fin 2 × Fin m) :=
+ Finset.univ.map (rowEmbedding A)
+
+private lemma mem_rows (A : Finset (Fin m)) (j : Fin 2) (i : Fin m) :
+ (j, i) ∈ rows A ↔ selectedRow A i = j := by
+ rw [rows, Finset.mem_map]
+ constructor
+ · rintro ⟨k, _, hk⟩
+ obtain ⟨hj, rfl⟩ := Prod.mk.inj hk
+ exact hj
+ · rintro rfl
+ exact ⟨i, Finset.mem_univ _, rfl⟩
+
+private lemma rows_sdiff (A B : Finset (Fin m)) :
+ rows A \ rows B = (A ∆ B).map (rowEmbedding A) := by
+ ext ⟨j, i⟩
+ simp only [Finset.mem_sdiff, mem_rows, Finset.mem_map, rowEmbedding,
+ Function.Embedding.coeFn_mk, Prod.mk.injEq,
+ Finset.mem_symmDiff, selectedRow]
+ by_cases ha : i ∈ A <;> by_cases hb : i ∈ B <;> simp [ha, hb] <;> rintro rfl <;> decide
+
+private def chosenCoordinates (A : Finset (Fin m)) : Finset (Fin (2 * m)) :=
+ (rows A).map finProdFinEquiv.toEmbedding
+
+/-- The coordinate plane spanned by row one in each marked pair and row zero
+in every other pair. -/
+noncomputable def cubePlane (A : Finset (Fin m)) : Plane m :=
+ ⟨Pi.spanSubset (ZMod 2) (chosenCoordinates A), by
+ rw [Pi.dim_spanSubset, Set.ncard_coe_finset]
+ simp [chosenCoordinates, rows]⟩
+
+/-- In the coordinate cube the Grassmann pair type counts exactly the pairs of
+coordinates on which the two choices differ. -/
+theorem hasType_cubePlane (A B : Finset (Fin m)) :
+ HasType (A ∆ B).card (cubePlane A) (cubePlane B) := by
+ change Module.finrank (ZMod 2) (Pi.spanSubset (ZMod 2) (chosenCoordinates A) ⊔
+ Pi.spanSubset (ZMod 2) (chosenCoordinates B) : Submodule (ZMod 2) (Space m)) = _
+ have hsup : Pi.spanSubset (ZMod 2) (chosenCoordinates A) ⊔
+ Pi.spanSubset (ZMod 2) (chosenCoordinates B) =
+ Pi.spanSubset (ZMod 2) (↑(chosenCoordinates A ∪ chosenCoordinates B) : Set (Fin (2 * m))) := by
+ simp [Pi.spanSubset, Set.image_union, Submodule.span_union]
+ rw [hsup, Pi.dim_spanSubset, Set.ncard_coe_finset]
+ rw [chosenCoordinates, chosenCoordinates, ← Finset.map_union, Finset.card_map,
+ ← Finset.card_sdiff_add_card, rows_sdiff]
+ simp [rows, Nat.add_comm]
+
+/-- The face on the first `ℓ` coordinate pairs. For `ℓ < m` its pair types
+are all strictly below `m`, as required in the equality argument of Lemma 5.3. -/
+theorem exists_cube_face {ℓ : ℕ} (h : ℓ ≤ m) :
+ ∃ face : Finset (Fin ℓ) → Plane m,
+ ∀ A B, HasType (A ∆ B).card (face A) (face B) := by
+ let e := Fin.castLEEmb h
+ refine ⟨fun A ↦ cubePlane (A.map e), fun A B ↦ ?_⟩
+ have hd : (A ∆ B).map e = (A.map e) ∆ (B.map e) := by
+ simp only [Finset.symmDiff_def, Finset.map_union, Finset.map_sdiff]
+ simpa only [← hd, Finset.card_map] using hasType_cubePlane (A.map e) (B.map e)
+
+/-- Seed quadrilaterals for the Grassmannian averaging argument. Their
+opposite sides have types `r` and `s`, and both diagonals have type `r + s`. -/
+theorem exists_square {m r s : ℕ} (h : r + s ≤ m) :
+ ∃ a b c d : Plane m,
+ HasType r a b ∧ HasType s b c ∧ HasType r c d ∧ HasType s d a ∧
+ HasType (r + s) a c ∧ HasType (r + s) b d := by
+ obtain ⟨R, _, hR⟩ := Finset.exists_subset_card_eq
+ (s := (Finset.univ : Finset (Fin m))) (n := r) (by simp; omega)
+ obtain ⟨S, hSR, hS⟩ := Finset.exists_subset_card_eq
+ (s := Rᶜ) (n := s) (by rw [Finset.card_compl, Fintype.card_fin, hR]; omega)
+ have hdis : Disjoint R S := Finset.disjoint_left.mpr fun i hi his ↦
+ Finset.mem_compl.mp (hSR his) hi
+ have hRS : (R ∆ S).card = r + s := by
+ rw [Finset.symmDiff_eq_union hdis, Finset.card_union_of_disjoint hdis, hR, hS]
+ refine ⟨cubePlane ∅, cubePlane R, cubePlane (R ∆ S), cubePlane S, ?_, ?_, ?_, ?_, ?_, ?_⟩
+ · simpa only [← Finset.bot_eq_empty, bot_symmDiff, hR] using hasType_cubePlane ∅ R
+ · simpa only [symmDiff_symmDiff_cancel_left, hS] using hasType_cubePlane R (R ∆ S)
+ · simpa only [symmDiff_symmDiff_cancel_right, hR] using hasType_cubePlane (R ∆ S) S
+ · simpa only [← Finset.bot_eq_empty, symmDiff_bot, hS] using hasType_cubePlane S ∅
+ · simpa only [← Finset.bot_eq_empty, bot_symmDiff, hRS] using hasType_cubePlane ∅ (R ∆ S)
+ · simpa only [hRS] using hasType_cubePlane R S
+
+/-- Every distance type up to the plane dimension occurs. -/
+theorem exists_pair {m r : ℕ} (h : r ≤ m) :
+ ∃ a b : Plane m, HasType r a b := by
+ obtain ⟨a, b, _, _, hab, _⟩ := exists_square (s := 0) (by simpa using h)
+ exact ⟨a, b, hab⟩
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannTypes.lean b/lean/OAI/Computability/VPVNP/GrassmannTypes.lean
new file mode 100644
index 0000000000..46dc243a9c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannTypes.lean
@@ -0,0 +1,88 @@
+import Mathlib.LinearAlgebra.FiniteDimensional.Basic
+import Mathlib.Algebra.Field.ZMod
+import Mathlib.Basic.Real.Basic
+
+/-!
+# The binary Grassmannian and its distance classes
+
+Section 5.1 uses the action of linear automorphisms on the ordered pairs of
+middle-dimensional subspaces of a binary vector space. The type of a pair
+is its sum dimension minus the common dimension of the subspaces.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+/-- The ambient binary vector space of dimension twice the plane dimension. -/
+abbrev Space (m : ℕ) := Fin (2 * m) → ZMod 2
+
+/-- Middle-dimensional subspaces of the ambient space. -/
+def Plane (m : ℕ) := {U : Submodule (ZMod 2) (Space m) // Module.finrank (ZMod 2) U = m}
+
+/-- The paper's type of an ordered pair, determined by its sum dimension. -/
+def HasType {m : ℕ} (r : ℕ) (a b : Plane m) : Prop :=
+ Module.finrank (ZMod 2) (a.val ⊔ b.val : Submodule (ZMod 2) (Space m)) = m + r
+
+/-- All ordered pairs of type `r`. -/
+def Pair (m r : ℕ) := {p : Plane m × Plane m // HasType r p.1 p.2}
+
+/-- Linear automorphisms of the ambient binary space. -/
+abbrev GL (m : ℕ) := Space m ≃ₗ[ZMod 2] Space m
+
+instance (m : ℕ) : Finite (Plane m) :=
+ Finite.of_injective (fun a : Plane m => (a.val : Set (Space m)))
+ (fun _ _ h => Subtype.ext (SetLike.coe_injective h))
+
+instance (m r : ℕ) : Finite (Pair m r) :=
+ Finite.of_injective _ (Subtype.val_injective (p := fun p : Plane m × Plane m =>
+ HasType r p.1 p.2))
+
+noncomputable instance (m : ℕ) : Fintype (Plane m) := Fintype.ofFinite _
+noncomputable instance (m r : ℕ) : Fintype (Pair m r) := Fintype.ofFinite _
+
+noncomputable instance (m : ℕ) : Fintype (GL m) :=
+ @Fintype.ofFinite _ (Finite.of_injective (fun e : GL m => (e : Space m → Space m))
+ DFunLike.coe_injective)
+
+instance (m : ℕ) : MulAction (GL m) (Plane m) where
+ smul e a := ⟨a.val.map e.toLinearMap, (e.finrank_map_eq a.val).trans a.property⟩
+ one_smul a := Subtype.ext (Submodule.map_id _)
+ mul_smul g h a := by
+ apply Subtype.ext
+ exact (Submodule.map_comp _ _ _)
+
+theorem smul_plane_val {m : ℕ} (g : GL m) (a : Plane m) :
+ (g • a).val = a.val.map g.toLinearMap := rfl
+
+theorem HasType.smul {m r : ℕ} {a b : Plane m} (h : HasType r a b) (g : GL m) :
+ HasType r (g • a) (g • b) := by
+ unfold HasType
+ rw [smul_plane_val, smul_plane_val, ← Submodule.map_sup, g.finrank_map_eq]
+ exact h
+
+instance (m r : ℕ) : MulAction (GL m) (Pair m r) where
+ smul g p := ⟨(g • p.val.1, g • p.val.2), p.property.smul g⟩
+ one_smul p := Subtype.ext (Prod.ext (one_smul _ p.val.1) (one_smul _ p.val.2))
+ mul_smul g h p := Subtype.ext (Prod.ext (mul_smul g h p.val.1) (mul_smul g h p.val.2))
+
+/-- The four side types and two diagonal types of a Grassmann quadrilateral. -/
+structure IsSquare {m : ℕ} (r s : ℕ) (a b c d : Plane m) : Prop where
+ ab : HasType r a b
+ bc : HasType s b c
+ cd : HasType r c d
+ da : HasType s d a
+ ac : HasType (r + s) a c
+ bd : HasType (r + s) b d
+
+/-- The uniform mean of an array over all ordered pairs of type `r`. -/
+noncomputable def mean {m : ℕ} (D : Plane m → Plane m → ℝ) (r : ℕ) : ℝ :=
+ (∑ p : Pair m r, D p.val.1 p.val.2) / Fintype.card (Pair m r)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GrassmannWalkTransfer.lean b/lean/OAI/Computability/VPVNP/GrassmannWalkTransfer.lean
new file mode 100644
index 0000000000..b133bf7d48
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GrassmannWalkTransfer.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.GrassmannTypes
+import OAI.Computability.VPVNP.SparseGrassmann
+
+/-!
+# Passing the strict Grassmann inequality to a sparse walk
+
+Average the strict Grassmann inequality over the random linear map. The two
+marginal laws needed here are independence on complementary planes and
+independence within matching fibers on adjacent planes. All averages are
+finite sums. The vertex factor in the conclusion agrees with the walk energy
+normalization in Section 5.2.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open SpectralGeometry
+
+variable {Ω I E S X : Type*} [Fintype Ω] [Fintype I] [Fintype E] [Fintype S]
+
+/-- Uniform expectation over a finite sample space. -/
+noncomputable def expectation {T : Type*} [Fintype T] (f : T → ℝ) : ℝ :=
+ (∑ t, f t) / Fintype.card T
+
+private theorem expectation_swap {T : Type*} [Fintype T] (f : S → T → ℝ) :
+ expectation (fun s ↦ expectation (f s)) = expectation (fun t ↦ expectation (fun s ↦ f s t)) := by
+ unfold expectation
+ simp only [div_eq_mul_inv, ← Finset.sum_mul]
+ rw [Finset.sum_comm]
+ ring
+
+private theorem expectation_const {T : Type*} [Fintype T] [Nonempty T] (v : ℝ) :
+ expectation (fun _ : T ↦ v) = v := by
+ simp [expectation, Fintype.card_ne_zero]
+
+private theorem expectation_div {T : Type*} [Fintype T] (f : T → ℝ) (c : ℝ) :
+ expectation (fun t ↦ f t / c) = expectation f / c := by
+ unfold expectation
+ simp only [div_eq_mul_inv, ← Finset.sum_mul]
+ ring
+
+/-- The two finite marginal distributions of the linear-map sampling experiment.
+Each equation quantifies over all observables, independently of the metric target. -/
+structure PairSamplingLaws {m : ℕ} (sample : S → Plane m → Ω)
+ (l r : Pair m 1 → I × E ≃ Ω) : Prop where
+ complementary : ∀ (p : Pair m m) (g : Ω → Ω → ℝ),
+ expectation (fun s ↦ g (sample s p.val.1) (sample s p.val.2)) =
+ (∑ u, ∑ v, g u v) / (Fintype.card Ω : ℝ) ^ 2
+ adjacent : ∀ (p : Pair m 1) (g : Ω → Ω → ℝ),
+ expectation (fun s ↦ g (sample s p.val.1) (sample s p.val.2)) =
+ ((∑ i, ∑ a, ∑ b, g (l p (i,a)) (r p (i,b))) / Fintype.card E) / Fintype.card Ω
+
+variable [PseudoMetricSpace X] {m : ℕ}
+
+/-- Average a Grassmann inequality over the sample space and use the pair
+laws to identify its left side with the uniform all-pairs energy. -/
+theorem PairSamplingLaws.transfer [Nonempty Ω] [Nonempty (Pair m m)]
+ {sample : S → Plane m → Ω} {l r : Pair m 1 → I × E ≃ Ω}
+ (hs : PairSamplingLaws sample l r) {c : ℝ}
+ (hgrass : ∀ f : Plane m → X,
+ mean (fun a b ↦ dist (f a) (f b) ^ 2) m ≤ c * mean (fun a b ↦ dist (f a) (f b) ^ 2) 1)
+ (x : Ω → X) :
+ (∑ u, ∑ v, dist (x u) (x v) ^ 2) / Fintype.card Ω ≤
+ c * ((∑ p, adjacentEnergy (l p) (r p) x) / Fintype.card (Pair m 1)) := by
+ let g (u v : Ω) := dist (x u) (x v) ^ 2
+ let pairFn (d : ℕ) (s : S) (p : Pair m d) := g (sample s p.val.1) (sample s p.val.2)
+ have point (s : S) : expectation (pairFn m s) ≤ c * expectation (pairFn 1 s) :=
+ hgrass (fun U ↦ x (sample s U))
+ have averaged : expectation (fun s ↦ expectation (pairFn m s)) ≤
+ c * expectation (fun s ↦ expectation (pairFn 1 s)) := by
+ have h := div_le_div_of_nonneg_right (Finset.sum_le_sum (s := Finset.univ) fun s _ ↦ point s)
+ (Nat.cast_nonneg (α := ℝ) (Fintype.card S))
+ simpa only [expectation, ← Finset.mul_sum, mul_div_assoc] using h
+ rw [expectation_swap (pairFn m), expectation_swap (pairFn 1)] at averaged
+ have hm (p : Pair m m) : expectation (fun s ↦ pairFn m s p) = (∑ u, ∑ v, g u v) /
+ (Fintype.card Ω : ℝ) ^ 2 := hs.complementary p g
+ have h₁ (p : Pair m 1) : expectation (fun s ↦ pairFn 1 s p) =
+ adjacentEnergy (l p) (r p) x / Fintype.card Ω := hs.adjacent p g
+ simp only [hm, expectation_const, h₁, expectation_div] at averaged
+ have ho : 0 < (Fintype.card Ω : ℝ) := Nat.cast_pos.mpr Fintype.card_pos
+ have h := mul_le_mul_of_nonneg_right averaged ho.le
+ have hcancel (y : ℝ) : y / (Fintype.card Ω : ℝ) ^ 2 * Fintype.card Ω =
+ y / Fintype.card Ω := by field_simp
+ rw [hcancel, mul_assoc, div_mul_cancel₀ _ ho.ne'] at h
+ exact h
+
+/-- Given the marginal laws of the random linear map, the actual fiber and
+permutation mixture has the recursive Poincaré coefficient of Section 5.2. -/
+theorem PairSamplingLaws.sparseBound [Nonempty Ω] [Nonempty E]
+ [Nonempty (Pair m 1)] [Nonempty (Pair m m)]
+ {sample : S → Plane m → Ω} {l r : Pair m 1 → I × E ≃ Ω}
+ (hs : PairSamplingLaws sample l r) (P : Matrix E E ℝ) {ε γ c : ℝ}
+ (hε : 0 < ε) (hγ : 0 ≤ γ) (hc : 0 ≤ c) (hP : HasPoincareBound X P γ)
+ (hgrass : ∀ f : Plane m → X,
+ mean (fun a b ↦ dist (f a) (f b) ^ 2) m ≤ c * mean (fun a b ↦ dist (f a) (f b) ^ 2) 1) :
+ HasPoincareBound X (sparseWalk l r P ((1 + ε) * γ) (1 + 1 / ε))
+ (c * ((1 + ε) * γ + (1 + 1 / ε))) :=
+ sparseWalk_hasPoincareBound l r P hε hγ hc hP (hs.transfer hgrass)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GreedyBasis.lean b/lean/OAI/Computability/VPVNP/GreedyBasis.lean
new file mode 100644
index 0000000000..73da81a082
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GreedyBasis.lean
@@ -0,0 +1,193 @@
+import Mathlib.Data.Set.PowersetCard
+import Mathlib.LinearAlgebra.Dimension.Constructions
+import Mathlib.LinearAlgebra.LinearIndependent.Lemmas
+import Mathlib.Order.Interval.Finset.Fin
+import Mathlib.RingTheory.Finiteness.Basic
+
+/-!
+# The isolated minimum-weight basis in the rank query
+
+Appendix D.2 of *VP and VNP differ over every field* assigns a row or column
+its one-based index as a weight. Keeping exactly the vectors that increase the
+span on a left-to-right scan gives the unique minimum-weight basis. The proof
+uses prefix ranks and applies over every field, also when the rank is zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+open scoped BigOperators
+
+private theorem prefix_weight_balance {n : ℕ} (s : Finset (Fin n)) :
+ (∑ i ∈ s, (i.val + 1)) + (∑ j : Fin n, (s.filter (· ≤ j)).card) =
+ s.card * (n + 1) := by
+ classical
+ have hcount (i : Fin n) : (∑ j : Fin n, if i ≤ j then 1 else 0) = n - i.val := by
+ rw [← Finset.card_filter]
+ have h : Finset.univ.filter (fun j : Fin n => i ≤ j) = Finset.Ici i := by ext; simp
+ rw [h, Fin.card_Ici]
+ simp_rw [Finset.card_filter]
+ rw [Finset.sum_comm (s := Finset.univ) (t := s)]
+ simp_rw [hcount]
+ rw [← Finset.sum_add_distrib]
+ calc
+ _ = ∑ _i ∈ s, (n + 1) := Finset.sum_congr rfl fun i _ => by have := i.isLt; omega
+ _ = _ := by simp
+
+private theorem eq_of_prefix_counts {n : ℕ} {s t : Finset (Fin n)}
+ (h : ∀ j : Fin n, (s.filter (· ≤ j)).card = (t.filter (· ≤ j)).card) :
+ s = t := by
+ classical
+ ext j
+ induction j using WellFoundedLT.induction with
+ | ind j ih =>
+ have hlt : s.filter (· < j) = t.filter (· < j) := by
+ ext i
+ by_cases hi : i < j
+ · simp [hi, ih i hi]
+ · simp [hi]
+ have count (u : Finset (Fin n)) :
+ (u.filter (· ≤ j)).card = (u.filter (· < j)).card + if j ∈ u then 1 else 0 := by
+ by_cases hj : j ∈ u
+ · have hu : u.filter (· ≤ j) = insert j (u.filter (· < j)) := by
+ ext i
+ simp only [Finset.mem_filter, Finset.mem_insert]
+ grind
+ simp [hu, hj]
+ · have hu : u.filter (· ≤ j) = u.filter (· < j) := by
+ ext i
+ simp only [Finset.mem_filter]
+ grind
+ simp [hu, hj]
+ have he := h j
+ rw [count s, count t, hlt] at he
+ by_cases hs : j ∈ s <;> by_cases ht : j ∈ t <;> simp_all
+
+/-- At fixed cardinality, domination of every prefix count strictly lowers the sum of
+one-based indices unless the two sets coincide. -/
+theorem weight_lt_of_prefix_dominance {n r : ℕ} {S T : Set.powersetCard (Fin n) r}
+ (hdom : ∀ j : Fin n, (T.val.filter (· ≤ j)).card ≤ (S.val.filter (· ≤ j)).card)
+ (hne : S ≠ T) : (∑ i ∈ S.val, (i.val + 1)) < ∑ i ∈ T.val, (i.val + 1) := by
+ classical
+ have hstrict : ∃ j : Fin n, (T.val.filter (· ≤ j)).card < (S.val.filter (· ≤ j)).card := by
+ by_contra! he
+ exact hne (Subtype.ext (eq_of_prefix_counts (fun j => (he j).antisymm (hdom j))))
+ obtain ⟨j, hj⟩ := hstrict
+ have hsum : (∑ i : Fin n, (T.val.filter (· ≤ i)).card) <
+ ∑ i : Fin n, (S.val.filter (· ≤ i)).card :=
+ Finset.sum_lt_sum (fun i _ => hdom i) ⟨j, Finset.mem_univ _, hj⟩
+ have hs := prefix_weight_balance S.val
+ have ht := prefix_weight_balance T.val
+ have hcard : S.val.card = T.val.card := S.property.trans T.property.symm
+ rw [hcard] at hs
+ omega
+
+variable (K : Type*) [Field K] {V : Type*} [AddCommGroup V] [Module K V]
+variable {n : ℕ} (v : Fin n → V)
+
+/-- Retain a row exactly when it increases the span of its predecessors. -/
+noncomputable def greedyIndices : Finset (Fin n) := by
+ classical
+ exact Finset.univ.filter (fun i => v i ∉ Submodule.span K (v '' Set.Iio i))
+
+@[simp] theorem mem_greedyIndices (i : Fin n) :
+ i ∈ greedyIndices K v ↔ v i ∉ Submodule.span K (v '' Set.Iio i) := by
+ classical
+ simp [greedyIndices]
+
+/-- On each prefix the retained rows form an independent spanning family. -/
+theorem greedyIndices_prefix (k : ℕ) :
+ LinearIndepOn K v ((greedyIndices K v : Set (Fin n)) ∩ {i | i.val < k}) ∧
+ Submodule.span K (v '' ((greedyIndices K v : Set (Fin n)) ∩ {i | i.val < k})) =
+ Submodule.span K (v '' {i | i.val < k}) := by
+ classical
+ induction k with
+ | zero => simp [linearIndepOn_empty]
+ | succ k ih =>
+ by_cases hk : k < n
+ · let j : Fin n := ⟨k, hk⟩
+ have hnext : {i : Fin n | i.val < k + 1} = insert j {i | i.val < k} := by
+ ext i
+ change i.val < k + 1 ↔ i = j ∨ i.val < k
+ simp only [Fin.ext_iff, j]
+ omega
+ have hprev : Set.Iio j = {i : Fin n | i.val < k} := rfl
+ rw [hnext, Set.image_insert_eq]
+ by_cases hj : j ∈ (greedyIndices K v : Set (Fin n))
+ · have hnew := (mem_greedyIndices K v j).mp hj
+ rw [hprev] at hnew
+ rw [Set.inter_insert_of_mem hj, Set.image_insert_eq]
+ constructor
+ · apply (linearIndepOn_insert ?_).mpr
+ · exact ⟨ih.1, ih.2 ▸ hnew⟩
+ · exact fun h => lt_irrefl k h.2
+ · rw [Submodule.span_insert, Submodule.span_insert, ih.2]
+ · have hdep : v j ∈ Submodule.span K (v '' {i : Fin n | i.val < k}) := by
+ by_contra hn
+ exact hj ((mem_greedyIndices K v j).mpr (hprev ▸ hn))
+ rw [Set.inter_insert_of_notMem hj, Submodule.span_insert_eq_span hdep]
+ exact ih
+ · have hsame : {i : Fin n | i.val < k + 1} = {i | i.val < k} := by
+ ext i
+ have hi := i.isLt
+ change i.val < k + 1 ↔ i.val < k
+ omega
+ rwa [hsame]
+
+theorem greedyIndices_span_prefix (k : ℕ) :
+ Submodule.span K (v '' ((greedyIndices K v : Set (Fin n)) ∩ {i | i.val < k})) =
+ Submodule.span K (v '' {i | i.val < k}) :=
+ (greedyIndices_prefix K v k).2
+
+theorem greedyIndices_linearIndepOn :
+ LinearIndepOn K v (greedyIndices K v : Set (Fin n)) := by
+ simpa using (greedyIndices_prefix K v n).1
+
+private theorem card_eq_finrank_image (v : Fin n → V) {S : Finset (Fin n)}
+ (hind : LinearIndepOn K v (S : Set (Fin n))) :
+ S.card = Module.finrank K (Submodule.span K (v '' (S : Set (Fin n)))) := by
+ rw [Set.image_eq_range, finrank_span_eq_card hind]
+ simp
+
+private theorem card_prefix_le (v : Fin n → V) {S T : Finset (Fin n)}
+ (hS : LinearIndepOn K v (S : Set (Fin n))) (hT : LinearIndepOn K v (T : Set (Fin n)))
+ (hspan : ∀ k : ℕ, Submodule.span K (v '' ((S : Set (Fin n)) ∩ {i | i.val < k})) =
+ Submodule.span K (v '' {i : Fin n | i.val < k})) (j : Fin n) :
+ (T.filter (· ≤ j)).card ≤ (S.filter (· ≤ j)).card := by
+ let early := {i : Fin n | i.val < j.val + 1}
+ have hp (B : Finset (Fin n)) : ((B.filter (· ≤ j) : Finset (Fin n)) : Set (Fin n)) =
+ (B : Set (Fin n)) ∩ early := by
+ ext i
+ simp only [Finset.mem_coe, Finset.mem_filter, Set.mem_inter_iff, early, Set.mem_ofPred_eq]
+ exact and_congr_right' (Nat.lt_succ_iff.symm : i.val ≤ j.val ↔ i.val < j.val + 1)
+ rw [card_eq_finrank_image K v (hT.mono (Finset.filter_subset _ _)),
+ card_eq_finrank_image K v (hS.mono (Finset.filter_subset _ _)), hp, hp, hspan]
+ let := Module.Finite.span_of_finite K ((Set.toFinite early).image v)
+ exact Submodule.finrank_mono (Submodule.span_mono (Set.image_mono Set.inter_subset_right))
+
+/-- Among all independent rank-sized subsets, the first basis selected in index order is
+uniquely of smallest total weight. Its indices span the entire family. -/
+theorem exists_isolatedBasis {r : ℕ}
+ (hr : r = Module.finrank K (Submodule.span K (Set.range v))) :
+ ∃ S : Set.powersetCard (Fin n) r,
+ LinearIndepOn K v (S : Set (Fin n)) ∧
+ Submodule.span K (v '' (S : Set (Fin n))) = Submodule.span K (Set.range v) ∧
+ ∀ T : Set.powersetCard (Fin n) r, LinearIndepOn K v (T : Set (Fin n)) → S ≠ T →
+ (∑ i ∈ S.val, (i.val + 1)) < ∑ i ∈ T.val, (i.val + 1) := by
+ have hspan : Submodule.span K (v '' (greedyIndices K v : Set (Fin n))) =
+ Submodule.span K (Set.range v) := by simpa using greedyIndices_span_prefix K v n
+ have hind := greedyIndices_linearIndepOn K v
+ have hcard : (greedyIndices K v).card = r := by rw [card_eq_finrank_image K v hind, hspan, hr]
+ let S : Set.powersetCard (Fin n) r := Set.powersetCard.ofCard hcard
+ refine ⟨S, hind, hspan, ?_⟩
+ intro T hT hne
+ exact weight_lt_of_prefix_dominance (card_prefix_le K v hind hT (greedyIndices_span_prefix K v)) hne
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GreedySuffixIndex.lean b/lean/OAI/Computability/VPVNP/GreedySuffixIndex.lean
new file mode 100644
index 0000000000..8da6fdee7f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GreedySuffixIndex.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.MacaulayCoordinates
+
+/-!
+# Querying basis ordinals after a prescribed row prefix
+
+Appendix D keeps the independent monomial rows following the equation rows.
+Their dense indices are the ordinals of the greedy rows of the full matrix
+offset by the rank of the equation prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+variable {K : Type*} [Field K] [DecidableEq K] {n m w : ℕ}
+
+theorem prefix_rankQuery_mono (A : Matrix (Fin n) (Fin m) K) {s u : ℕ} (hs : s ≤ n)
+ (hu : u ≤ n) (hsu : s ≤ u) :
+ rankQuery (prefixRows A s hs) ≤ rankQuery (prefixRows A u hu) := by
+ simp only [rankQuery_eq, rank_prefixRows]
+ apply Finset.card_le_card
+ intro i hi
+ obtain ⟨hi, hval⟩ := Finset.mem_filter.mp hi
+ exact Finset.mem_filter.mpr ⟨hi, hval.trans_le hsu⟩
+
+theorem greedyRowIndex_lt_iff (A : Matrix (Fin n) (Fin m) K)
+ (k : Fin (rankQuery A)) (s : ℕ) (hs : s ≤ n) :
+ (greedyRowIndex A k).val < s ↔ k.val < rankQuery (prefixRows A s hs) := by
+ cases s with
+ | zero => simp [rankQuery_eq, rank_prefixRows]
+ | succ s =>
+ let g := greedyRowIndex A k
+ have htest : k.val < rankQuery (prefixRows A (g.val + 1) g.isLt) := by
+ unfold g greedyRowIndex firstPrefixAbove
+ apply Fin.find_spec (p := fun i : Fin n => k.val < rankQuery (prefixRows A (i.val+1) i.isLt))
+ constructor
+ · intro hg
+ exact htest.trans_le (prefix_rankQuery_mono A g.isLt hs (Nat.succ_le_of_lt hg))
+ · intro hk
+ let j : Fin n := ⟨s, hs⟩
+ have hle : g ≤ j := by
+ unfold g greedyRowIndex firstPrefixAbove
+ apply Fin.find_le_of_pos
+ exact hk
+ exact Nat.lt_succ_of_le hle
+
+omit [Field K] [DecidableEq K] in
+private theorem prefix_append_eq (W : Matrix (Fin w) (Fin m) K)
+ (M : Matrix (Fin n) (Fin m) K) : prefixRows (appendRows W M) w (Nat.le_add_right _ _) = W := by
+ funext i j
+ change appendRows W M (i.castAdd n) j = W i j
+ rw [appendRows_left]
+
+/-- Number of independent monomial rows after reducing modulo the preceding rows. -/
+def suffixDimension (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K) : ℕ :=
+ rankQuery (appendRows W M) - rankQuery W
+
+private def offsetOrdinal (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K)
+ (k : Fin (suffixDimension W M)) : Fin (rankQuery (appendRows W M)) :=
+ ⟨rankQuery W + k.val, by have := k.isLt; unfold suffixDimension at this; omega⟩
+
+/-- Read the original index of a selected monomial by its ordinal among the
+independent monomial rows. The prefix rank scan always uses the original rows. -/
+def suffixBasisIndex (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K)
+ (k : Fin (suffixDimension W M)) : Fin n :=
+ let g := greedyRowIndex (appendRows W M) (offsetOrdinal W M k)
+ ⟨g.val - w, by
+ have hg := (greedyRowIndex_lt_iff (appendRows W M) (offsetOrdinal W M k) w
+ (Nat.le_add_right _ _))
+ rw [prefix_append_eq] at hg
+ have ho : rankQuery W ≤ (offsetOrdinal W M k).val := Nat.le_add_right _ _
+ have hge : w ≤ g.val := le_of_not_gt (fun h => (Nat.not_lt_of_ge ho) (hg.mp h))
+ have := g.isLt
+ omega⟩
+
+private theorem suffixBasisIndex_natAdd (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K)
+ (k : Fin (suffixDimension W M)) :
+ (suffixBasisIndex W M k).natAdd w = greedyRowIndex (appendRows W M) (offsetOrdinal W M k) := by
+ apply Fin.ext
+ let g := greedyRowIndex (appendRows W M) (offsetOrdinal W M k)
+ change w + (g.val - w) = g.val
+ have h := greedyRowIndex_lt_iff (appendRows W M) (offsetOrdinal W M k) w (Nat.le_add_right _ _)
+ rw [prefix_append_eq] at h
+ have ho : rankQuery W ≤ (offsetOrdinal W M k).val := Nat.le_add_right _ _
+ have hge : w ≤ g.val := le_of_not_gt (fun hg => (Nat.not_lt_of_ge ho) (h.mp hg))
+ omega
+
+theorem suffixBasisIndex_strictMono (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K) :
+ StrictMono (suffixBasisIndex W M) := by
+ intro i j hij
+ have ho : offsetOrdinal W M i < offsetOrdinal W M j := Nat.add_lt_add_left hij _
+ let A := appendRows W M
+ have h := ((greedyIndices K A.row).orderEmbOfFin (greedyRows_card A)).strictMono ho
+ rw [← greedyRowIndex_eq, ← greedyRowIndex_eq, ← suffixBasisIndex_natAdd, ← suffixBasisIndex_natAdd] at h
+ exact Nat.lt_of_add_lt_add_left h
+
+theorem suffixBasisIndex_injective (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K) :
+ Function.Injective (suffixBasisIndex W M) :=
+ (suffixBasisIndex_strictMono W M).injective
+
+theorem mem_range_suffixBasisIndex (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K)
+ (j : Fin n) :
+ j ∈ Set.range (suffixBasisIndex W M) ↔ j.natAdd w ∈ greedyIndices K (appendRows W M).row := by
+ let A := appendRows W M
+ constructor
+ · rintro ⟨k, rfl⟩
+ rw [suffixBasisIndex_natAdd, greedyRowIndex_eq]
+ exact Finset.orderEmbOfFin_mem ..
+ · intro hj
+ let S := greedyIndices K A.row
+ have he : j.natAdd w ∈ Set.range (greedyRowIndex A) := by
+ have hf : greedyRowIndex A = S.orderEmbOfFin (greedyRows_card A) := funext (greedyRowIndex_eq A)
+ rw [hf, Finset.range_orderEmbOfFin]
+ exact hj
+ obtain ⟨k, hk⟩ := he
+ have hw := greedyRowIndex_lt_iff A k w (Nat.le_add_right _ _)
+ rw [hk, prefix_append_eq] at hw
+ have hge : rankQuery W ≤ k.val := le_of_not_gt (fun h => by
+ have := hw.mpr h
+ change w + j.val < w at this
+ omega)
+ let u : Fin (suffixDimension W M) := ⟨k.val - rankQuery W, by
+ have hlt := k.isLt
+ change k.val < rankQuery (appendRows W M) at hlt
+ unfold suffixDimension; omega⟩
+ have hu : offsetOrdinal W M u = k := Fin.ext (by change _ + (k.val - _) = k.val; omega)
+ refine ⟨u, ?_⟩
+ have h := suffixBasisIndex_natAdd W M u
+ rw [hu, hk] at h
+ exact Fin.natAdd_injective _ _ h
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GroupContraction.lean b/lean/OAI/Computability/VPVNP/GroupContraction.lean
new file mode 100644
index 0000000000..b5f4cfa6e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GroupContraction.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.ChainAssignments
+import OAI.Computability.VPVNP.RAMValidatorPaths
+
+/-! # Replacing live groups by native RAM computations
+
+Each cut choice fixes a group's header memory. The sum over its communication
+bits is then exactly the number of accepting RAM paths. The site-prefix
+compiler supplies the local path-count identity; the regrouping works even
+when a particular choice of incident messages is malformed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ChainAssignments
+
+open BurstRAM BurstRAM.PrivateRAM RAMLayout
+open scoped Classical
+
+variable {n a h Δ d e w pc regs pubs : ℕ}
+
+/-- External memory at a live group is initialized with its actual four-bit
+headers. Addresses beyond the group receive the RAM's zero default. -/
+def liveHeader (hw : 4 ≤ w) (advice : CutSchedule.Bits a) (cuts : AllCuts h Δ)
+ (j : Fin (2^(h+1))) (addr : ℕ) : Word w :=
+ if hv : addr < 2^d then ProcessorInput.headerWord hw (physicalHeader advice cuts j ⟨addr,hv⟩)
+ else 0
+
+/-- The full contraction with the site computations for each group replaced
+by one computation of its RAM program, with the same address and cut data. -/
+theorem original_eq_group_counts (p : UniversalMachine.Program)
+ (hf : ProcessorInput.Fits p n d (2^e) w) (advice : CutSchedule.Bits a)
+ (M : Machine w pc regs pubs) (fuel : ℕ) (initial : Word w)
+ (hw : 4 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (processor : ∀ (v : Fin (2^d)) (hdr : ProcessorInput.Header) inc,
+ acceptingCount (ProcessorInput.encode p n v hdr inc hf) =
+ Nat.card (M.IncidentPaths fuel initial (ProcessorInput.headerWord hw hdr)
+ (by omega) hc v inc)) :
+ PairedChain.original (h := h) (Δ := Δ) p hf advice =
+ ∑ cuts : AllCuts h Δ, ∏ j : Fin (2^(h+1)), Nat.card
+ (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2^d)
+ (liveHeader (d := d) hw advice cuts j)) (withinCaps (2^d) (2^e))) := by
+ rw [← unpaired_eq_original, unpaired, Fintype.sum_prod_type]
+ apply Finset.sum_congr rfl
+ intro cuts _
+ simp_rw [M.parsimoniousIncidentPaths fuel initial _ (by omega : 2 ≤ w) hc]
+ rw [Fintype.prod_sum]
+ apply Finset.sum_congr rfl
+ intro bits _
+ apply Finset.prod_congr rfl
+ intro j _
+ apply Finset.prod_congr rfl
+ intro v _
+ unfold physicalInput
+ rw [processor]
+ have hinc : BurstRAM.incidentBits (bits j) v =
+ (fun u => (assignmentEquiv d (2^e) w (bits j)).val (v,(offset d (2^e) w).symm u)) := by
+ funext u
+ change (((assignmentEquiv d (2^e) w) ((sendArraysEquiv d (2^e) w).symm ((sendArraysEquiv d (2^e) w) (bits j)))).val _ = _)
+ rw [Equiv.symm_apply_apply]
+ simp [hinc, liveHeader, v.isLt]
+
+end ChainAssignments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/GroupIncidentContraction.lean b/lean/OAI/Computability/VPVNP/GroupIncidentContraction.lean
new file mode 100644
index 0000000000..7b63145fd6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/GroupIncidentContraction.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.GroupContraction
+
+/-!
+# Summing the compiled processor over the live groups' actual shared bits
+
+At each site the original polynomial contraction uses the bit vector
+obtained from one sender assignment. This identity only needs the
+coefficient formula on those vectors, including the clamps at the two ends.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ChainAssignments
+
+open BurstRAM PrivateRAM RAMLayout
+
+variable {n a h Δ d e w pc regs pubs : ℕ}
+
+theorem original_eq_incident_counts (p : UniversalMachine.Program)
+ (hf : ProcessorInput.Fits p n d (2^e) w) (advice : CutSchedule.Bits a)
+ (M : Machine w pc regs pubs) (fuel : ℕ) (initial : Word w)
+ (hw : 4 ≤ w) (hc : 2^d*2^e < 2^w)
+ (processor : ∀ (v : Fin (2^d)) (hdr : ProcessorInput.Header) (sends : SendArrays d (2^e) w),
+ acceptingCount (ProcessorInput.encode p n v hdr (RAMLayout.incidentBits sends v) hf) =
+ Nat.card (M.IncidentPaths fuel initial (ProcessorInput.headerWord hw hdr)
+ (by omega) hc v (RAMLayout.incidentBits sends v))) :
+ PairedChain.original (h := h) (Δ := Δ) p hf advice =
+ ∑ cuts : AllCuts h Δ, ∏ j : Fin (2^(h+1)), Nat.card
+ (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2^d)
+ (liveHeader (d := d) hw advice cuts j)) (withinCaps (2^d) (2^e))) := by
+ rw [← unpaired_eq_original, unpaired, Fintype.sum_prod_type]
+ apply Finset.sum_congr rfl
+ intro cuts _
+ simp_rw [M.parsimoniousIncidentPaths fuel initial _ (by omega : 2 ≤ w) hc]
+ rw [Fintype.prod_sum]
+ apply Finset.sum_congr rfl
+ intro bits _
+ apply Finset.prod_congr rfl
+ intro j _
+ apply Finset.prod_congr rfl
+ intro v _
+ let sends := sendArraysEquiv d (2^e) w (bits j)
+ have inc : RAMLayout.incidentBits sends v =
+ (fun u => (assignmentEquiv d (2^e) w (bits j)).val (v,(offset d (2^e) w).symm u)) := by
+ unfold RAMLayout.incidentBits incidentEquiv sends
+ simp
+ have eqn := processor v (physicalHeader advice cuts j v) sends
+ rw [inc] at eqn
+ unfold physicalInput
+ rw [eqn]
+ have hinc : BurstRAM.incidentBits (bits j) v =
+ (fun u => (assignmentEquiv d (2^e) w (bits j)).val (v,(offset d (2^e) w).symm u)) := by
+ simpa only [BurstRAM.incidentBits] using inc
+ simp [hinc, liveHeader, v.isLt]
+
+end ChainAssignments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HCForward.lean b/lean/OAI/Computability/VPVNP/HCForward.lean
new file mode 100644
index 0000000000..d5002cc402
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HCForward.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.HamiltonianGadget
+import Mathlib.GroupTheory.Perm.Cycle.Basic
+
+/-!
+# Directed traversal determined by an exact-one assignment
+
+The bit of each variable orients its entire track. At a satisfied occurrence
+the traversal visits the clause vertex, then continues at the other port of
+the same slot. The unique satisfied occurrence determines the outgoing arc
+from each clause.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HCGadget
+
+open Equiv
+
+variable {k h c : ℕ}
+variable (occ : Fin h → Fin k × Fin c × Bool) (x : Fin k → Bool)
+
+/-- Occurrences are distinct slots, including repeated literals within a clause. -/
+def Exact : Prop :=
+ ∀ a : Fin c, ∃! j : Fin h, (occ j).2.1 = a ∧ x (occ j).1 = (occ j).2.2
+
+variable (hx : Exact occ x)
+
+/-- The unique satisfied occurrence at the clause. -/
+noncomputable def chosen (a : Fin c) : Fin h := (hx a).exists.choose
+
+theorem chosen_spec (a : Fin c) :
+ (occ (chosen occ x hx a)).2.1 = a ∧
+ x (occ (chosen occ x hx a)).1 = (occ (chosen occ x hx a)).2.2 :=
+ (hx a).exists.choose_spec
+
+theorem chosen_eq {a : Fin c} {j : Fin h}
+ (hj : (occ j).2.1 = a ∧ x (occ j).1 = (occ j).2.2) : chosen occ x hx a = j :=
+ (hx a).unique (chosen_spec occ x hx a) hj
+
+/-- The next vertex along the cycle specified by the assignment. -/
+noncomputable def nextVertex : Vertex k h c → Vertex k h c
+ | .sep i => .endpoint i (!x i)
+ | .endpoint i b => if b = x i then .sep (finRotate k i)
+ else .buffer i (if b then Fin.last h else 0)
+ | .buffer i j => if x i then nextPort i j else prevPort i j
+ | .port i j b => if b = x i then portBuffer i j b
+ else if (occ j).1 = i ∧ (occ j).2.2 = x i then .clause (occ j).2.1
+ else .port i j (x i)
+ | .clause a =>
+ let j := chosen occ x hx a
+ .port (occ j).1 j (occ j).2.2
+
+theorem nextVertex_prevPort {i : Fin k} (hi : x i = true) (j : Fin (h + 1)) :
+ nextVertex occ x hx (prevPort i j) = .buffer i j := by
+ cases j using Fin.cases <;> simp [nextVertex, hi, portBuffer]
+
+theorem nextVertex_nextPort {i : Fin k} (hi : x i = false) (j : Fin (h + 1)) :
+ nextVertex occ x hx (nextPort i j) = .buffer i j := by
+ cases j using Fin.lastCases <;> simp [nextVertex, hi, portBuffer]
+
+theorem nextVertex_ingress (i : Fin k) (j : Fin h) :
+ nextVertex occ x hx (.port i j (!x i)) =
+ if (occ j).1 = i ∧ (occ j).2.2 = x i then .clause (occ j).2.1 else .port i j (x i) := by
+ cases hi : x i <;> simp [nextVertex, hi]
+
+theorem nextVertex_clause_of_active {i : Fin k} {j : Fin h}
+ (ha : (occ j).1 = i ∧ (occ j).2.2 = x i) :
+ nextVertex occ x hx (.clause (occ j).2.1) = .port i j (x i) := by
+ have hc := chosen_eq occ x hx (a := (occ j).2.1) (j := j) ⟨rfl, by rw [ha.1, ha.2]⟩
+ simp [nextVertex, hc, ha.1, ha.2]
+
+theorem nextVertex_surjective : Function.Surjective (nextVertex occ x hx) := by
+ intro v
+ cases v with
+ | sep i =>
+ let q := (finRotate k).symm i
+ exact ⟨.endpoint q (x q), by simp only [nextVertex, ite_true, q, Equiv.apply_symm_apply]⟩
+ | endpoint i b =>
+ cases hb : b <;> cases hi : x i
+ · exact ⟨.buffer i 0, by simp [nextVertex, hi]⟩
+ · exact ⟨.sep i, by simp [nextVertex, hi]⟩
+ · exact ⟨.sep i, by simp [nextVertex, hi]⟩
+ · exact ⟨.buffer i (Fin.last h), by simp [nextVertex, hi]⟩
+ | buffer i j =>
+ cases hi : x i with
+ | false => exact ⟨nextPort i j, nextVertex_nextPort occ x hx hi j⟩
+ | true => exact ⟨prevPort i j, nextVertex_prevPort occ x hx hi j⟩
+ | port i j b =>
+ by_cases hb : b = x i
+ · subst b
+ by_cases ha : (occ j).1 = i ∧ (occ j).2.2 = x i
+ · exact ⟨.clause (occ j).2.1, nextVertex_clause_of_active occ x hx ha⟩
+ · exact ⟨.port i j (!x i), by rw [nextVertex_ingress, ite_eq_right ha]⟩
+ · cases b <;> cases hi : x i <;> simp [hi] at hb
+ · exact ⟨.buffer i j.castSucc, by simp [nextVertex, hi]⟩
+ · exact ⟨.buffer i j.succ, by simp [nextVertex, hi]⟩
+ | clause a =>
+ let j := chosen occ x hx a
+ obtain ⟨hc, hp⟩ := chosen_spec occ x hx a
+ refine ⟨.port (occ j).1 j (!x (occ j).1), ?_⟩
+ rw [nextVertex_ingress, ite_eq_left ⟨rfl, hp.symm⟩, hc]
+
+/-- The traversal uses every vertex once as a successor. -/
+noncomputable def cycleOfAssignment : Perm (Vertex k h c) :=
+ Equiv.ofBijective (nextVertex occ x hx)
+ ⟨Finite.injective_iff_surjective.mpr (nextVertex_surjective occ x hx),
+ nextVertex_surjective occ x hx⟩
+
+@[simp] theorem cycleOfAssignment_apply (v : Vertex k h c) :
+ cycleOfAssignment occ x hx v = nextVertex occ x hx v := rfl
+
+theorem nextVertex_allowed (v : Vertex k h c) :
+ Allowed occ v (nextVertex occ x hx v) := by
+ cases v with
+ | sep i => exact .enterTrack _ _
+ | endpoint i b =>
+ by_cases hb : b = x i
+ · simpa [nextVertex, hb] using Allowed.exitTrack (occ := occ) i b
+ · cases b
+ · simpa [nextVertex, hb] using Allowed.prevBuffer (occ := occ) i (0 : Fin (h + 1))
+ · simpa [nextVertex, hb] using Allowed.nextBuffer (occ := occ) i (Fin.last h)
+ | buffer i j =>
+ cases hi : x i
+ · simpa [nextVertex, hi] using Allowed.bufferPrev (occ := occ) i j
+ · simpa [nextVertex, hi] using Allowed.bufferNext (occ := occ) i j
+ | port i j b =>
+ by_cases hb : b = x i
+ · rw [nextVertex, ite_eq_left hb]
+ cases b
+ · simpa [portBuffer] using Allowed.nextBuffer (occ := occ) i j.castSucc
+ · simpa [portBuffer] using Allowed.prevBuffer (occ := occ) i j.succ
+ · have hn : (!b) = x i := by cases b <;> cases hi : x i <;> simp [hi] at *
+ by_cases ha : (occ j).1 = i ∧ (occ j).2.2 = x i
+ · have hs : (!(occ j).2.2) = b := by rw [ha.2, ← hn]; simp
+ rw [nextVertex, ite_eq_right hb, ite_eq_left ha]
+ have he := Allowed.enterClause (occ := occ) j
+ rw [ha.1, hs] at he
+ exact he
+ · have inactive : (occ j).1 ≠ i ∨ (occ j).2.2 = b := by
+ by_cases he : (occ j).1 = i
+ · right
+ have hs : (occ j).2.2 ≠ x i := fun H => ha ⟨he, H⟩
+ cases b <;> cases hp : (occ j).2.2 <;> cases hi : x i <;> simp [hi, hp] at *
+ · exact Or.inl he
+ simpa [nextVertex, hb, ha, hn] using Allowed.cross (occ := occ) i j b inactive
+ | clause a =>
+ have he := Allowed.exitClause (occ := occ) (chosen occ x hx a)
+ rw [(chosen_spec occ x hx a).1] at he
+ exact he
+
+end HCGadget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HCForwardSpanning.lean b/lean/OAI/Computability/VPVNP/HCForwardSpanning.lean
new file mode 100644
index 0000000000..a38fbc97af
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HCForwardSpanning.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.HCForward
+import OAI.Computability.VPVNP.HCGadgetSpanning
+
+/-! The assignment traversal connects all track and clause vertices in one directed cycle. -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HCGadget
+
+open Equiv.Perm
+
+variable {k h c : ℕ} (occ : Fin h → Fin k × Fin c × Bool) (x : Fin k → Bool) (hx : Exact occ x)
+
+private theorem same_of_step {a b : Vertex k h c} (e : nextVertex occ x hx a = b) :
+ (cycleOfAssignment occ x hx).SameCycle a b := by
+ change cycleOfAssignment occ x hx a = b at e
+ rw [← e]
+ exact (SameCycle.refl _ _).apply_right
+
+theorem cycleOfAssignment_buffers (i : Fin k) (j : Fin (h+1)) :
+ (cycleOfAssignment occ x hx).SameCycle (prevPort i j) (.buffer i j) ∧
+ (cycleOfAssignment occ x hx).SameCycle (.buffer i j) (nextPort i j) := by
+ cases hi : x i with
+ | false =>
+ refine ⟨(same_of_step occ x hx ?_).symm,
+ (same_of_step occ x hx (nextVertex_nextPort occ x hx hi j)).symm⟩
+ simp [nextVertex, hi]
+ | true =>
+ refine ⟨same_of_step occ x hx (nextVertex_prevPort occ x hx hi j), same_of_step occ x hx ?_⟩
+ simp [nextVertex, hi]
+
+theorem cycleOfAssignment_slots (i : Fin k) (j : Fin h) :
+ (cycleOfAssignment occ x hx).SameCycle (.port i j false) (.port i j true) := by
+ have cross : (cycleOfAssignment occ x hx).SameCycle (.port i j (!x i)) (.port i j (x i)) := by
+ by_cases ha : (occ j).1 = i ∧ (occ j).2.2 = x i
+ · have hin : nextVertex occ x hx (.port i j (!x i)) = .clause (occ j).2.1 := by
+ rw [nextVertex_ingress, ite_eq_left ha]
+ exact (same_of_step occ x hx hin).trans (same_of_step occ x hx (nextVertex_clause_of_active occ x hx ha))
+ · exact same_of_step occ x hx (by rw [nextVertex_ingress, ite_eq_right ha])
+ cases hi : x i
+ · simpa [hi] using cross.symm
+ · simpa [hi] using cross
+
+theorem cycleOfAssignment_enter (i : Fin k) :
+ ∃ b, (cycleOfAssignment occ x hx).SameCycle (.sep i) (.endpoint i b) :=
+ ⟨!x i, same_of_step occ x hx rfl⟩
+
+theorem cycleOfAssignment_exit (i : Fin k) :
+ ∃ b, (cycleOfAssignment occ x hx).SameCycle (.endpoint i b) (.sep (finRotate k i)) :=
+ ⟨x i, same_of_step occ x hx (by simp [nextVertex])⟩
+
+theorem cycleOfAssignment_clauses (a : Fin c) :
+ ∃ i j b, (cycleOfAssignment occ x hx).SameCycle (.port i j b) (.clause a) := by
+ let j := chosen occ x hx a
+ have hc := chosen_spec occ x hx a
+ refine ⟨(occ j).1, j, !x (occ j).1, same_of_step occ x hx ?_⟩
+ rw [nextVertex_ingress, ite_eq_left ⟨rfl, hc.2.symm⟩, hc.1]
+
+/-- Every exact-one assignment yields a spanning directed cycle using allowed arcs. -/
+theorem cycleOfAssignment_spanning (hk : 0 < k) :
+ (cycleOfAssignment occ x hx).IsCycleOn Set.univ :=
+ isCycleOn_of_track_connections _ hk (cycleOfAssignment_buffers occ x hx)
+ (cycleOfAssignment_slots occ x hx) (cycleOfAssignment_enter occ x hx)
+ (cycleOfAssignment_exit occ x hx) (cycleOfAssignment_clauses occ x hx)
+
+end HCGadget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HCGadgetSpanning.lean b/lean/OAI/Computability/VPVNP/HCGadgetSpanning.lean
new file mode 100644
index 0000000000..9549e308eb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HCGadgetSpanning.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.HamiltonianGadget
+
+/-!
+# Connectivity of the directed Hamiltonian-cycle gadget
+
+If each pair of ports and each buffer belongs to the same permutation cycle as its
+neighbors, the whole variable track lies in one cycle. The separators join the tracks
+in cyclic order, and a single incident port suffices to attach each clause.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HCGadget
+
+open Equiv.Perm
+
+variable {k h c : ℕ}
+
+/-- The local connectivity conditions for variable tracks, separators and clause
+vertices suffice to make the permutation a Hamiltonian cycle. -/
+theorem isCycleOn_of_track_connections (π : Equiv.Perm (Vertex k h c)) (hk : 0 < k)
+ (buffers : ∀ i j, π.SameCycle (prevPort i j) (.buffer i j) ∧
+ π.SameCycle (.buffer i j) (nextPort i j))
+ (pairs : ∀ i j, π.SameCycle (.port i j false) (.port i j true))
+ (entries : ∀ i, ∃ b, π.SameCycle (.sep i) (.endpoint i b))
+ (exits : ∀ i, ∃ b, π.SameCycle (.endpoint i b) (.sep (finRotate k i)))
+ (clauses : ∀ a, ∃ i j b, π.SameCycle (.port i j b) (.clause a)) :
+ π.IsCycleOn Set.univ := by
+ obtain ⟨k, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hk.ne'
+ have toBuffer (i : Fin (k + 1)) (j : Fin (h + 1)) :
+ π.SameCycle (.endpoint i false) (.buffer i j) := by
+ induction j using Fin.induction with
+ | zero => simpa using (buffers i 0).1
+ | succ j ih =>
+ have left : π.SameCycle (.buffer i j.castSucc) (.port i j false) := by
+ simpa using (buffers i j.castSucc).2
+ have right : π.SameCycle (.port i j true) (.buffer i j.succ) := by
+ simpa using (buffers i j.succ).1
+ exact ((ih.trans left).trans (pairs i j)).trans right
+ have toEndpoint (i : Fin (k + 1)) (b : Bool) :
+ π.SameCycle (.endpoint i false) (.endpoint i b) := by
+ cases b with
+ | false => exact SameCycle.rfl
+ | true => simpa using (toBuffer i (Fin.last h)).trans (buffers i (Fin.last h)).2
+ have fromSep (i : Fin (k + 1)) : π.SameCycle (.sep i) (.endpoint i false) := by
+ obtain ⟨b, hb⟩ := entries i
+ exact hb.trans (toEndpoint i b).symm
+ have toSep (i : Fin (k + 1)) : π.SameCycle (.sep 0) (.sep i) := by
+ induction i using Fin.induction with
+ | zero => exact SameCycle.rfl
+ | succ i ih =>
+ obtain ⟨b, hb⟩ := exits i.castSucc
+ have rot : finRotate (k + 1) i.castSucc = i.succ := finRotate_of_lt i.isLt
+ rw [rot] at hb
+ exact ((ih.trans (fromSep i.castSucc)).trans (toEndpoint i.castSucc b)).trans hb
+ have track (i : Fin (k + 1)) : π.SameCycle (.sep 0) (.endpoint i false) :=
+ (toSep i).trans (fromSep i)
+ have port (i : Fin (k + 1)) (j : Fin h) (b : Bool) : π.SameCycle (.sep 0) (.port i j b) := by
+ have left : π.SameCycle (.buffer i j.castSucc) (.port i j false) := by
+ simpa using (buffers i j.castSucc).2
+ have first := ((track i).trans (toBuffer i j.castSucc)).trans left
+ cases b with
+ | false => exact first
+ | true => exact first.trans (pairs i j)
+ have all (v : Vertex (k + 1) h c) : π.SameCycle (.sep 0) v := by
+ cases v with
+ | sep i => exact toSep i
+ | endpoint i b => exact (track i).trans (toEndpoint i b)
+ | buffer i j => exact (track i).trans (toBuffer i j)
+ | port i j b => exact port i j b
+ | clause a =>
+ obtain ⟨i, j, b, hab⟩ := clauses a
+ exact (port i j b).trans hab
+ exact ⟨π.bijective.bijOn_univ, fun x _ y _ => (all x).symm.trans (all y)⟩
+
+end HCGadget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HCReadback.lean b/lean/OAI/Computability/VPVNP/HCReadback.lean
new file mode 100644
index 0000000000..c23f39fdc0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HCReadback.lean
@@ -0,0 +1,233 @@
+import OAI.Computability.VPVNP.GadgetPorts
+import OAI.Computability.VPVNP.HCForward
+
+/-!
+# Reading an assignment from a spanning cycle of the exact-one graph
+
+At a buffer, the predecessor and successor must lie on opposite sides. Two
+consecutive buffers must point in the same direction: otherwise both intervening
+ports would have to send edges to the same clause vertex, or both would need
+incoming edges from it. Thus a single bit determines the direction of each track.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HCGadget
+
+open Equiv
+
+variable {k h c : ℕ} {occ : Fin h → Fin k × Fin c × Bool} {π : Perm (Vertex k h c)}
+
+private theorem cannot_return (cyc : π.IsCycleOn Set.univ) (i : Fin k) {u v : Vertex k h c}
+ (go : π u = v) : π v ≠ u := by
+ simpa only [go] using no_two_cycle π cyc i u
+
+private theorem allowed_predecessor (edge : ∀ v, Allowed occ v (π v)) (v : Vertex k h c) :
+ Allowed occ (π.symm v) v := by simpa using edge (π.symm v)
+
+private theorem no_two_incoming_buffers (cyc : π.IsCycleOn Set.univ)
+ (edge : ∀ v, Allowed occ v (π v)) (i : Fin k) (j : Fin h)
+ (arrive : ∀ b, π (portBuffer i j b) = .port i j b) : False := by
+ have out (b : Bool) : π (.port i j b) = .clause (occ j).2.1 := by
+ rcases (edge (.port i j b)).from_port with hb | ⟨hc, _⟩ | ⟨hcl, _⟩
+ · exact (cannot_return cyc i (arrive b) hb).elim
+ · have he := π.injective (hc.trans (arrive (!b)).symm)
+ simp [portBuffer] at he
+ · exact hcl
+ have he := π.injective ((out false).trans (out true).symm)
+ simp at he
+
+private theorem no_two_outgoing_buffers (cyc : π.IsCycleOn Set.univ)
+ (edge : ∀ v, Allowed occ v (π v)) (i : Fin k) (j : Fin h)
+ (depart : ∀ b, π (.port i j b) = portBuffer i j b) : False := by
+ have src (b : Bool) : π.symm (.port i j b) = .clause (occ j).2.1 := by
+ rcases (allowed_predecessor edge (.port i j b)).to_port with hb | ⟨hc, _⟩ | ⟨hcl, _⟩
+ · have hback := (π.symm_apply_eq.mp hb).symm
+ exact (cannot_return cyc i (depart b) hback).elim
+ · have he := (π.symm_apply_eq.mp hc).trans (depart (!b))
+ simp [portBuffer] at he
+ · exact hcl
+ have he := π.symm.injective ((src false).trans (src true).symm)
+ simp at he
+
+/-- The two edges of a cycle incident to a buffer have the direction indicated
+by the variable bit. -/
+private def trackDirection (π : Perm (Vertex k h c)) (i : Fin k) (j : Fin (h + 1))
+ (bit : Bool) : Prop :=
+ if bit then π (.buffer i j) = nextPort i j ∧ π (prevPort i j) = .buffer i j
+ else π (.buffer i j) = prevPort i j ∧ π (nextPort i j) = .buffer i j
+
+private theorem trackDirection_step (cyc : π.IsCycleOn Set.univ)
+ (edge : ∀ v, Allowed occ v (π v)) (i : Fin k) (j : Fin h) (bit : Bool)
+ (here : trackDirection π i j.castSucc bit)
+ (options : trackDirection π i j.succ true ∨ trackDirection π i j.succ false) :
+ trackDirection π i j.succ bit := by
+ cases bit with
+ | false =>
+ rcases options with right | left
+ · have dep : ∀ b, π (.port i j b) = portBuffer i j b := by
+ intro b
+ cases b
+ · simpa [portBuffer] using (show _ ∧ _ from here).2
+ · simpa [portBuffer] using (show _ ∧ _ from right).2
+ exact (no_two_outgoing_buffers cyc edge i j dep).elim
+ · exact left
+ | true =>
+ rcases options with right | left
+ · exact right
+ · have arr : ∀ b, π (portBuffer i j b) = .port i j b := by
+ intro b
+ cases b
+ · simpa [portBuffer] using (show _ ∧ _ from here).1
+ · simpa [portBuffer] using (show _ ∧ _ from left).1
+ exact (no_two_incoming_buffers cyc edge i j arr).elim
+
+private theorem trackDirections (cyc : π.IsCycleOn Set.univ)
+ (edge : ∀ v, Allowed occ v (π v)) :
+ ∃ x : Fin k → Bool, ∀ i t, trackDirection π i t (x i) := by
+ classical
+ have options (i : Fin k) (t : Fin (h + 1)) :
+ trackDirection π i t true ∨ trackDirection π i t false :=
+ buffer_directions π cyc edge i t
+ let x (i : Fin k) := decide (trackDirection π i 0 true)
+ refine ⟨x, fun i t => ?_⟩
+ induction t using Fin.induction with
+ | zero =>
+ by_cases hi : trackDirection π i 0 true
+ · simp [x, hi]
+ · simpa [x, hi] using (options i 0).resolve_left hi
+ | succ j ih =>
+ exact trackDirection_step cyc edge i j (x i) ih (options i j.succ)
+
+private theorem aligned_port_buffers {x : Fin k → Bool}
+ (align : ∀ i t, trackDirection π i t (x i)) (i : Fin k) (j : Fin h) :
+ π (portBuffer i j (!x i)) = .port i j (!x i) ∧
+ π (.port i j (x i)) = portBuffer i j (x i) := by
+ have left := align i j.castSucc
+ have right := align i j.succ
+ cases hx : x i <;> simp [trackDirection, hx] at left right <;> simp [portBuffer, left, right]
+
+private theorem aligned_endpoint_buffers {x : Fin k → Bool}
+ (align : ∀ i t, trackDirection π i t (x i)) (i : Fin k) :
+ π (endpointBuffer i (x i)) = .endpoint i (x i) ∧
+ π (.endpoint i (!x i)) = endpointBuffer i (!x i) := by
+ have left := align i 0
+ have right := align i (Fin.last h)
+ cases hx : x i <;> simp [trackDirection, hx] at left right <;> simp [endpointBuffer, left, right]
+
+private theorem aligned_ingress {x : Fin k → Bool} (cyc : π.IsCycleOn Set.univ)
+ (edge : ∀ v, Allowed occ v (π v)) (align : ∀ i t, trackDirection π i t (x i))
+ (i : Fin k) (j : Fin h) :
+ π (.port i j (!x i)) =
+ if (occ j).1 = i ∧ (occ j).2.2 = x i then .clause (occ j).2.1 else .port i j (x i) := by
+ rcases (edge (.port i j (!x i))).from_port with hb | ⟨direct, hinactive⟩ | ⟨detour, hi, hb⟩
+ · exact (cannot_return cyc i (aligned_port_buffers align i j).1 hb).elim
+ · have h : ¬ ((occ j).1 = i ∧ (occ j).2.2 = x i) := by
+ rintro ⟨hi, hb⟩
+ rcases hinactive with hn | hn
+ · exact hn hi
+ · simp [hb] at hn
+ simpa [h] using direct
+ · have h : (occ j).1 = i ∧ (occ j).2.2 = x i := ⟨hi, by simpa using (congrArg Bool.not hb).symm⟩
+ simpa [h] using detour
+
+private theorem aligned_detour_exit {x : Fin k → Bool} (cyc : π.IsCycleOn Set.univ)
+ (edge : ∀ v, Allowed occ v (π v)) (align : ∀ i t, trackDirection π i t (x i))
+ (i : Fin k) (j : Fin h) (active : (occ j).1 = i ∧ (occ j).2.2 = x i) :
+ π (.clause (occ j).2.1) = .port i j (x i) := by
+ rcases (allowed_predecessor edge (.port i j (x i))).to_port with hb | ⟨cross, _⟩ | ⟨detour, _⟩
+ · exact (cannot_return cyc i (aligned_port_buffers align i j).2
+ (π.symm_apply_eq.mp hb).symm).elim
+ · have depart := aligned_ingress cyc edge align i j
+ rw [ite_eq_left active] at depart
+ have he := (π.symm_apply_eq.mp cross).trans depart
+ cases he
+ · exact (π.symm_apply_eq.mp detour).symm
+
+private theorem aligned_track_end {x : Fin k → Bool} (cyc : π.IsCycleOn Set.univ)
+ (edge : ∀ v, Allowed occ v (π v)) (align : ∀ i t, trackDirection π i t (x i))
+ (i : Fin k) :
+ π (.sep i) = .endpoint i (!x i) ∧ π (.endpoint i (x i)) = .sep (finRotate k i) := by
+ obtain ⟨arrive, depart⟩ := aligned_endpoint_buffers align i
+ constructor
+ · rcases (allowed_predecessor edge (.endpoint i (!x i))).to_endpoint with hb | hs
+ · exact (cannot_return cyc i depart (π.symm_apply_eq.mp hb).symm).elim
+ · exact (π.symm_apply_eq.mp hs).symm
+ · exact (edge (.endpoint i (x i))).from_endpoint.resolve_left (cannot_return cyc i arrive)
+
+private theorem aligned_exact {x : Fin k → Bool} (cyc : π.IsCycleOn Set.univ)
+ (edge : ∀ v, Allowed occ v (π v)) (align : ∀ i t, trackDirection π i t (x i)) :
+ Exact occ x := by
+ intro a
+ obtain ⟨j, hcl, hpred⟩ := allowed_to_clause_iff.mp (allowed_predecessor edge (.clause a))
+ have toClause := (π.symm_apply_eq.mp hpred).symm
+ have active : x (occ j).1 = (occ j).2.2 := by
+ by_contra h
+ have he : (!(occ j).2.2) = x (occ j).1 := by
+ cases ha : (occ j).2.2 <;> cases hx : x (occ j).1 <;> simp_all
+ rw [he, (aligned_port_buffers align (occ j).1 j).2] at toClause
+ cases toClause
+ refine ⟨j, ⟨hcl, active⟩, ?_⟩
+ rintro s ⟨hs, hv⟩
+ have from_s := aligned_ingress cyc edge align (occ s).1 s
+ rw [ite_eq_left ⟨rfl, hv.symm⟩, hs] at from_s
+ have he := π.injective (from_s.trans toClause.symm)
+ exact (Vertex.port.inj he).2.1
+
+private theorem read_aligned_cycle {x : Fin k → Bool} (cyc : π.IsCycleOn Set.univ)
+ (edge : ∀ v, Allowed occ v (π v)) (align : ∀ i t, trackDirection π i t (x i))
+ (exactly : Exact occ x) (v : Vertex k h c) : π v = nextVertex occ x exactly v := by
+ cases v with
+ | sep i => exact (aligned_track_end cyc edge align i).1
+ | endpoint i b =>
+ by_cases hb : b = x i
+ · subst b
+ simpa [nextVertex] using (aligned_track_end cyc edge align i).2
+ · have he : b = !(x i) := by cases b <;> cases hx : x i <;> simp_all
+ rw [nextVertex, ite_eq_right hb, he]
+ exact (aligned_endpoint_buffers align i).2
+ | buffer i j =>
+ have atBuffer := align i j
+ cases hi : x i <;> simp [trackDirection, hi] at atBuffer <;> simp [nextVertex, hi, atBuffer]
+ | port i j b =>
+ by_cases hb : b = x i
+ · subst b
+ simpa [nextVertex] using (aligned_port_buffers align i j).2
+ · have he : b = !(x i) := by cases b <;> cases hx : x i <;> simp_all
+ rw [he, nextVertex_ingress]
+ exact aligned_ingress cyc edge align i j
+ | clause a =>
+ let j := chosen occ x exactly a
+ obtain ⟨hcl, hv⟩ := chosen_spec occ x exactly a
+ have he := aligned_detour_exit cyc edge align (occ j).1 j ⟨rfl, hv.symm⟩
+ change π (.clause a) = .port (occ j).1 j (occ j).2.2
+ simpa only [j, hcl, hv] using he
+
+/-- Every allowed spanning cycle is precisely the traversal constructed from
+an assignment satisfying every exact-one constraint. -/
+theorem exists_exact_assignment (cyc : π.IsCycleOn Set.univ) (edge : ∀ v, Allowed occ v (π v)) :
+ ∃ (x : Fin k → Bool) (hx : Exact occ x), π = cycleOfAssignment occ x hx := by
+ obtain ⟨x, align⟩ := trackDirections cyc edge
+ let hx := aligned_exact cyc edge align
+ exact ⟨x, hx, Equiv.ext (read_aligned_cycle cyc edge align hx)⟩
+
+/-- The outgoing arc at each separator recovers its track bit, so distinct
+satisfying assignments give distinct tours. -/
+theorem cycleOfAssignment_injective (occ : Fin h → Fin k × Fin c × Bool) :
+ Function.Injective (fun x : {x : Fin k → Bool // Exact occ x} =>
+ cycleOfAssignment occ x.val x.property) := by
+ intro x y he
+ apply Subtype.ext
+ funext i
+ have e := Equiv.congr_fun he (.sep i)
+ have hb := (Vertex.endpoint.inj (show Vertex.endpoint (h := h) (c := c) i (!(x.val i)) =
+ .endpoint i (!(y.val i)) from e)).2
+ simpa using congrArg Bool.not hb
+
+end HCGadget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HCWeighted.lean b/lean/OAI/Computability/VPVNP/HCWeighted.lean
new file mode 100644
index 0000000000..5150ffc33e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HCWeighted.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.HCForwardSpanning
+import OAI.Computability.VPVNP.HCReadback
+import OAI.Computability.VPVNP.HamiltonianRelabel
+import OAI.Computability.VPVNP.ExactOneOccurrences
+import OAI.Computability.VPVNP.ExactOneWeights
+
+/-!
+# Exact-one generating polynomials as Hamiltonian-cycle projections
+
+Each satisfying assignment yields one allowed spanning cycle. Its entry arcs
+record the selected variable weights. Summing the weights of these cycles
+therefore gives the weighted exact-one polynomial over any commutative ring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HCGadget
+
+open MvPolynomial Equiv
+open scoped Classical
+
+variable {R τ : Type*} [CommSemiring R] {k h c : ℕ}
+variable (occ : Fin h → Fin k × Fin c × Bool)
+
+/-- The entering arc records a true bit by its variable or scalar weight. All
+other allowed arcs carry one. -/
+def arcWeight (w : Projection R (Fin k) τ) : Vertex k h c → Vertex k h c → τ ⊕ R
+ | .sep i, .endpoint _ false => w i
+ | _, _ => .inr 1
+
+theorem product_cycleOfAssignment (w : Projection R (Fin k) τ) (x : Fin k → Bool)
+ (hx : Exact occ x) :
+ (∏ v, (arcWeight w v (cycleOfAssignment occ x hx v)).elim X C) =
+ ∏ i, if x i then (w i).elim X C else 1 := by
+ classical
+ let S : Finset (Vertex k h c) := Finset.univ.image Vertex.sep
+ have toS : (∏ v, (arcWeight w v (cycleOfAssignment occ x hx v)).elim X C) =
+ ∏ v ∈ S, (arcWeight w v (cycleOfAssignment occ x hx v)).elim X C := by
+ symm
+ apply Finset.prod_subset (Finset.subset_univ _)
+ intro v _ hv
+ cases v with
+ | sep i => exact False.elim (hv (Finset.mem_image.mpr ⟨i, Finset.mem_univ _, rfl⟩))
+ | endpoint | buffer | port | clause => simp [arcWeight]
+ rw [toS, show S = _ from rfl, Finset.prod_image]
+ · apply Finset.prod_congr rfl
+ intro i _
+ cases hi : x i <;> simp [nextVertex, hi, arcWeight]
+ · exact fun _ _ _ _ he => Vertex.sep.inj he
+
+/-- Spanning cycles in the exact-one gadget that follow an allowed directed edge at every
+vertex. -/
+abbrev Admissible (occ : Fin h → Fin k × Fin c × Bool) :=
+ {π : Perm (Vertex k h c) // π.IsCycleOn Set.univ ∧ ∀ v, Allowed occ v (π v)}
+
+/-- Turn an exact satisfying assignment into its directed spanning cycle through the variable
+tracks and clause vertices. -/
+noncomputable def toCycle (hk : 0 < k) (x : {x : Fin k → Bool // Exact occ x}) : Admissible occ :=
+ ⟨cycleOfAssignment occ x x.2, cycleOfAssignment_spanning occ x x.2 hk, nextVertex_allowed occ x x.2⟩
+
+/-- The weight-preserving encoding of exact-one assignments as allowed Hamiltonian tours. -/
+noncomputable def assignmentsEquiv (hk : 0 < k) :
+ {x : Fin k → Bool // Exact occ x} ≃ Admissible occ :=
+ Equiv.ofBijective (toCycle occ hk) ⟨
+ fun _ _ e => cycleOfAssignment_injective occ (congrArg Subtype.val e),
+ fun π => by
+ obtain ⟨x, hx, he⟩ := exists_exact_assignment π.2.1 π.2.2
+ exact ⟨⟨x, hx⟩, Subtype.ext he.symm⟩⟩
+
+section
+
+variable {S : Type*} [CommRing S]
+
+theorem weightedProjectionSlots (hk : 0 < k) (w : Projection S (Fin k) τ) :
+ ∃ ψ : Projection S (Fin (k * (3 * h + 4) + c) × Fin (k * (3 * h + 4) + c)) τ,
+ ψ.hom (hamiltonianCyclePolynomial S (k * (3 * h + 4) + c)) =
+ ∑ x : {x : Fin k → Bool // Exact occ x}, ∏ i, if x.val i then (w i).elim X C else 1 := by
+ classical
+ let e := (Fintype.equivFinOfCardEq (card_vertex k h c)).symm
+ have hm : 0 < k * (3 * h + 4) + c := Nat.add_pos_left (Nat.mul_pos hk (by omega)) _
+ obtain ⟨ψ, he⟩ := hamiltonian_projection_on_allowed e hm (Allowed occ) (arcWeight w)
+ refine ⟨ψ, he.trans ?_⟩
+ symm
+ let aweight (x : {x : Fin k → Bool // Exact occ x}) :=
+ ∏ i, if x.val i then (w i).elim X C else 1
+ let cweight (π : Admissible occ) := ∏ v, (arcWeight w v (π.val v)).elim X C
+ refine @Fintype.sum_equiv _ _ _ ?_ ?_ _ (assignmentsEquiv occ hk) aweight cweight ?_
+ intro x
+ exact (product_cycleOfAssignment occ w x.val x.2).symm
+
+/-- Projection from a Hamiltonian polynomial of explicit order for any positive-width
+exact-one formula, allowing repeated literals and empty clauses. -/
+theorem weighted_projection (φ : HardnessCNF.CNF k) (hk : 0 < k) (w : Projection S (Fin k) τ) :
+ ∃ ψ : Projection S (Fin (k * (3 * HardnessCNF.literalCount φ + 4) + φ.length) ×
+ Fin (k * (3 * HardnessCNF.literalCount φ + 4) + φ.length)) τ,
+ ψ.hom (hamiltonianCyclePolynomial S (k * (3 * HardnessCNF.literalCount φ + 4) + φ.length)) =
+ ExactOne.weightedExactOne φ (fun i => (w i).elim X C) := by
+ obtain ⟨ψ, he⟩ := weightedProjectionSlots (ExactOne.occurrences φ) hk w
+ refine ⟨ψ, he.trans ?_⟩
+ rw [ExactOne.weightedExactOne_eq_sum]
+ let e : {x : Fin k → Bool // Exact (ExactOne.occurrences φ) x} ≃
+ {x : Fin k → Bool // ExactOne.Holds φ x} := Equiv.subtypeEquivRight (fun x => (ExactOne.holds_iff_unique_occurrence φ x).symm)
+ let wt (x : Fin k → Bool) : MvPolynomial τ S := ∏ i, if x i then (w i).elim X C else 1
+ exact Fintype.sum_equiv e (fun x => wt x.val) (fun x => wt x.val) fun _ => rfl
+
+end
+
+end HCGadget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Hamiltonian.lean b/lean/OAI/Computability/VPVNP/Hamiltonian.lean
new file mode 100644
index 0000000000..445f473682
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Hamiltonian.lean
@@ -0,0 +1,126 @@
+import Mathlib.Algebra.MvPolynomial.Basic
+import Mathlib.Data.Fintype.BigOperators
+import Mathlib.GroupTheory.Perm.Cycle.Basic
+
+/-!
+# Directed Hamiltonian cycles as binary matrices
+
+Section 1.1 of *VP and VNP differ over every field* projects the pair of
+variables encoding an edge bit to `(1, X e)`. This gives one monomial for
+each accepted adjacency matrix. The identity below identifies their sum,
+as a formal polynomial, with the sum indexed by single-cycle permutations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+/-- The edge polynomial obtained by retaining exactly the variables at true bits. -/
+noncomputable def booleanPolynomial {E R : Type*} [Fintype E] [DecidableEq E] [CommSemiring R]
+ (u : (E → Bool) → R) : MvPolynomial E R :=
+ ∑ x, C (u x) * ∏ e, if x e then X e else 1
+
+/-- The adjacency matrix of the directed edges from each vertex to its image. -/
+def permutationEdges {m : ℕ} (π : Equiv.Perm (Fin m)) (e : Fin m × Fin m) : Bool :=
+ decide (π e.1 = e.2)
+
+theorem permutationEdges_injective {m : ℕ} :
+ Function.Injective (permutationEdges (m := m)) := by
+ intro π τ h
+ apply Equiv.ext
+ intro i
+ have hi : τ i = π i := by simpa [permutationEdges] using congrFun h (i, π i)
+ exact hi.symm
+
+/-- Single directed cycles on all vertices. A loop is a cycle of order one. -/
+noncomputable def spanningCycles (m : ℕ) : Finset (Equiv.Perm (Fin m)) := by
+ classical
+ exact Finset.univ.filter (fun π => 0 < m ∧ π.IsCycleOn Set.univ)
+
+/-- Scan a row for its first edge. The diagonal default is used for an empty row. -/
+def rowSuccessor {m : ℕ} (x : Fin m × Fin m → Bool) (i : Fin m) : Fin m :=
+ ((List.finRange m).find? (fun j => x (i, j))).getD i
+
+theorem rowSuccessor_permutationEdges {m : ℕ} (π : Equiv.Perm (Fin m)) :
+ rowSuccessor (permutationEdges π) = π := by
+ funext i
+ unfold rowSuccessor
+ cases h : (List.finRange m).find? (fun j => permutationEdges π (i, j)) with
+ | none =>
+ have hn := List.find?_eq_none.mp h (π i) (List.mem_finRange _)
+ simp [permutationEdges] at hn
+ | some j =>
+ have hj := List.find?_some h
+ simpa [permutationEdges, eq_comm] using hj
+
+/-- Each row is the graph of its scanned successor,
+every column is hit, and all vertices occur in the first `m` steps starting from `root`.
+Every quantifier in this Boolean test ranges over the vertices. -/
+def acceptsCycleMatrix {m : ℕ} (root : Fin m) (x : Fin m × Fin m → Bool) : Bool :=
+ decide ((∀ i j, x (i, j) = decide (rowSuccessor x i = j)) ∧
+ (∀ j, ∃ i, rowSuccessor x i = j) ∧
+ (∀ j, ∃ k : Fin m, (rowSuccessor x)^[k.val] root = j))
+
+theorem acceptsCycleMatrix_iff {m : ℕ} (root : Fin m) (x : Fin m × Fin m → Bool) :
+ acceptsCycleMatrix root x = true ↔ x ∈ (spanningCycles m).image permutationEdges := by
+ classical
+ rw [acceptsCycleMatrix, decide_eq_true_eq]
+ have hm : 0 < m := Nat.zero_lt_of_lt root.isLt
+ constructor
+ · rintro ⟨hrow, hsurj, hreach⟩
+ let π : Equiv.Perm (Fin m) := Equiv.ofBijective (rowSuccessor x)
+ ⟨Finite.injective_iff_surjective.mpr hsurj, hsurj⟩
+ have orbit (i : Fin m) : π.SameCycle root i := by
+ obtain ⟨k, hk⟩ := hreach i
+ refine ⟨(k.val : ℤ), ?_⟩
+ rw [zpow_natCast]
+ change (rowSuccessor x)^[k.val] root = i
+ exact hk
+ have hπ : π.IsCycleOn Set.univ :=
+ ⟨π.bijective.bijOn_univ, fun i _ j _ => (orbit i).symm.trans (orbit j)⟩
+ refine Finset.mem_image.mpr ⟨π, by simpa [spanningCycles, hm] using hπ, ?_⟩
+ funext ⟨i, j⟩
+ exact (hrow i j).symm
+ · rintro hx
+ obtain ⟨π, hπ, rfl⟩ := Finset.mem_image.mp hx
+ rw [rowSuccessor_permutationEdges]
+ refine ⟨fun _ _ => rfl, π.surjective, ?_⟩
+ intro j
+ have hcyc : π.IsCycleOn (Finset.univ : Finset (Fin m)) := by
+ simpa [spanningCycles, hm] using hπ
+ obtain ⟨n, hn, heq⟩ := hcyc.exists_pow_eq (Finset.mem_univ root) (Finset.mem_univ j)
+ exact ⟨⟨n, by simpa using hn⟩, by simpa only [Equiv.Perm.coe_pow] using heq⟩
+
+/-- The zero-one coefficient for a deterministic Hamiltonian-cycle predicate. -/
+noncomputable def cycleIndicator (R : Type*) [CommSemiring R] (m : ℕ)
+ (x : Fin m × Fin m → Bool) : R := by
+ classical
+ exact if x ∈ (spanningCycles m).image permutationEdges then 1 else 0
+
+theorem cycleIndicator_eq_check (R : Type*) [CommSemiring R] {m : ℕ}
+ (root : Fin m) (x : Fin m × Fin m → Bool) :
+ cycleIndicator R m x = if acceptsCycleMatrix root x then 1 else 0 := by
+ classical
+ simp only [cycleIndicator, acceptsCycleMatrix_iff]
+
+/-- The directed Hamiltonian-cycle polynomial in matrix indeterminates. -/
+noncomputable def hamiltonianCyclePolynomial (R : Type*) [CommSemiring R] (m : ℕ) :
+ MvPolynomial (Fin m × Fin m) R :=
+ ∑ π ∈ spanningCycles m, ∏ i, X (i, π i)
+
+theorem booleanPolynomial_cycleIndicator (R : Type*) [CommSemiring R] (m : ℕ) :
+ booleanPolynomial (cycleIndicator R m) = hamiltonianCyclePolynomial R m := by
+ classical
+ unfold booleanPolynomial cycleIndicator hamiltonianCyclePolynomial
+ simp only [apply_ite C, map_one, map_zero, ite_mul, one_mul, zero_mul]
+ rw [Fintype.sum_ite_mem, Finset.sum_image permutationEdges_injective.injOn]
+ apply Finset.sum_congr rfl
+ intro π _
+ rw [Fintype.prod_prod_type]
+ simp [permutationEdges]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HamiltonianGadget.lean b/lean/OAI/Computability/VPVNP/HamiltonianGadget.lean
new file mode 100644
index 0000000000..c8b58def2b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HamiltonianGadget.lean
@@ -0,0 +1,176 @@
+import Mathlib.GroupTheory.Perm.Fin
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Directed Hamiltonian-cycle graph for exact-one clauses
+
+Each variable has a track with endpoints, one pair of ports per occurrence slot, and a
+buffer between successive pairs. At the slot belonging to a literal, the directed
+crossing for the literal's true value passes through its clause vertex. The opposite
+crossing uses the edge between the ports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HCGadget
+
+/-- The Hamiltonian reduction has a track for each variable, ports for literal occurrences,
+separators between tracks, and one vertex per clause. -/
+inductive Vertex (k h c : ℕ) where
+ | sep (i : Fin k)
+ | endpoint (i : Fin k) (side : Bool)
+ | buffer (i : Fin k) (j : Fin (h + 1))
+ | port (i : Fin k) (j : Fin h) (side : Bool)
+ | clause (a : Fin c)
+ deriving DecidableEq, Fintype
+
+variable {k h c : ℕ}
+
+/-- Left neighbor of a buffer in the linear order on its track. -/
+def prevPort (i : Fin k) (j : Fin (h + 1)) : Vertex k h c :=
+ Fin.cases (.endpoint i false) (fun s => .port i s true) j
+
+/-- Right neighbor of a buffer in the linear order on its track. -/
+def nextPort (i : Fin k) (j : Fin (h + 1)) : Vertex k h c :=
+ Fin.lastCases (.endpoint i true) (fun s => .port i s false) j
+
+/-- Each port has exactly one adjacent buffer along its track. -/
+def portBuffer (i : Fin k) (j : Fin h) (b : Bool) : Vertex k h c :=
+ .buffer i (if b then j.succ else j.castSucc)
+
+@[simp] theorem prevPort_zero (i : Fin k) : prevPort (h := h) (c := c) i 0 = .endpoint i false := rfl
+
+@[simp] theorem prevPort_succ (i : Fin k) (j : Fin h) :
+ prevPort (c := c) i j.succ = .port i j true := by simp [prevPort]
+
+@[simp] theorem nextPort_last (i : Fin k) :
+ nextPort (c := c) i (Fin.last h) = .endpoint i true := by simp [nextPort]
+
+@[simp] theorem nextPort_castSucc (i : Fin k) (j : Fin h) :
+ nextPort (c := c) i j.castSucc = .port i j false := by simp [nextPort]
+
+/-- Allowed directed edges. The occurrence data give the variable, clause and
+satisfying variable value of each slot. -/
+inductive Allowed (occ : Fin h → Fin k × Fin c × Bool) : Vertex k h c → Vertex k h c → Prop
+ | bufferPrev (i : Fin k) (j : Fin (h + 1)) : Allowed occ (.buffer i j) (prevPort i j)
+ | prevBuffer (i : Fin k) (j : Fin (h + 1)) : Allowed occ (prevPort i j) (.buffer i j)
+ | bufferNext (i : Fin k) (j : Fin (h + 1)) : Allowed occ (.buffer i j) (nextPort i j)
+ | nextBuffer (i : Fin k) (j : Fin (h + 1)) : Allowed occ (nextPort i j) (.buffer i j)
+ | enterTrack (i : Fin k) (b : Bool) : Allowed occ (.sep i) (.endpoint i b)
+ | exitTrack (i : Fin k) (b : Bool) : Allowed occ (.endpoint i b) (.sep (finRotate k i))
+ | cross (i : Fin k) (j : Fin h) (b : Bool) (inactive : (occ j).1 ≠ i ∨ (occ j).2.2 = b) :
+ Allowed occ (.port i j b) (.port i j (!b))
+ | enterClause (j : Fin h) : Allowed occ (.port (occ j).1 j (!(occ j).2.2)) (.clause (occ j).2.1)
+ | exitClause (j : Fin h) : Allowed occ (.clause (occ j).2.1) (.port (occ j).1 j (occ j).2.2)
+
+/-- The graph uses polynomially many vertices, including for empty occurrence lists. -/
+theorem card_vertex (k h c : ℕ) : Fintype.card (Vertex k h c) = k * (3 * h + 4) + c := by
+ rw [← Fintype.card_congr (proxy_equiv% (Vertex k h c))]
+ simp
+ ring
+
+
+variable {occ : Fin h → Fin k × Fin c × Bool}
+variable {i : Fin k} {j : Fin (h + 1)} {a : Fin c} {v : Vertex k h c}
+
+private def isPortOrEndpoint : Vertex k h c → Bool
+ | .port .. | .endpoint .. => true
+ | _ => false
+
+private theorem prevPort_kind (i : Fin k) (j : Fin (h + 1)) :
+ isPortOrEndpoint (prevPort (c := c) i j) = true := by
+ cases j using Fin.cases <;> simp [isPortOrEndpoint]
+
+private theorem nextPort_kind (i : Fin k) (j : Fin (h + 1)) :
+ isPortOrEndpoint (nextPort (c := c) i j) = true := by
+ cases j using Fin.lastCases <;> simp [isPortOrEndpoint]
+
+private theorem ne_prevPort_of_kind_false (u : Vertex k h c) (i : Fin k)
+ (j : Fin (h + 1)) (hu : isPortOrEndpoint u = false) : u ≠ prevPort i j := by
+ intro e
+ have he := congrArg isPortOrEndpoint e
+ simp only [hu, prevPort_kind] at he
+ contradiction
+
+private theorem ne_nextPort_of_kind_false (u : Vertex k h c) (i : Fin k)
+ (j : Fin (h + 1)) (hu : isPortOrEndpoint u = false) : u ≠ nextPort i j := by
+ intro e
+ have he := congrArg isPortOrEndpoint e
+ simp only [hu, nextPort_kind] at he
+ contradiction
+
+theorem allowed_from_buffer_iff :
+ Allowed occ (.buffer i j) v ↔ v = prevPort i j ∨ v = nextPort i j := by
+ constructor
+ · intro e
+ generalize hv : Vertex.buffer i j = u at e
+ cases e <;> (try simp_all) <;>
+ first | exact (ne_prevPort_of_kind_false _ _ _ rfl hv).elim
+ | exact (ne_nextPort_of_kind_false _ _ _ rfl hv).elim
+ · rintro (rfl | rfl)
+ · exact .bufferPrev i j
+ · exact .bufferNext i j
+
+theorem allowed_to_buffer_iff :
+ Allowed occ v (.buffer i j) ↔ v = prevPort i j ∨ v = nextPort i j := by
+ constructor
+ · intro e
+ generalize hv : Vertex.buffer i j = u at e
+ cases e <;> (try simp_all) <;>
+ first | exact (ne_prevPort_of_kind_false _ _ _ rfl hv).elim
+ | exact (ne_nextPort_of_kind_false _ _ _ rfl hv).elim
+ · rintro (rfl | rfl)
+ · exact .prevBuffer i j
+ · exact .nextBuffer i j
+
+theorem allowed_from_sep_iff :
+ Allowed occ (.sep i) v ↔ ∃ b, v = .endpoint i b := by
+ constructor
+ · intro e
+ generalize hv : Vertex.sep i = u at e
+ cases e <;> (try simp_all) <;>
+ first | exact (ne_prevPort_of_kind_false _ _ _ rfl hv).elim
+ | exact (ne_nextPort_of_kind_false _ _ _ rfl hv).elim
+ · rintro ⟨b, rfl⟩
+ exact .enterTrack i b
+
+theorem allowed_to_sep_iff :
+ Allowed occ v (.sep i) ↔ ∃ b, v = .endpoint ((finRotate k).symm i) b := by
+ constructor
+ · intro e
+ generalize hv : Vertex.sep i = u at e
+ cases e <;> (try simp_all [-finRotate_apply, -finRotate_symm_apply]) <;>
+ first | exact (ne_prevPort_of_kind_false _ _ _ rfl hv).elim
+ | exact (ne_nextPort_of_kind_false _ _ _ rfl hv).elim
+ · rintro ⟨b, rfl⟩
+ simpa only [Equiv.apply_symm_apply] using Allowed.exitTrack (occ := occ) ((finRotate k).symm i) b
+
+theorem allowed_from_clause_iff :
+ Allowed occ (.clause a) v ↔ ∃ j, (occ j).2.1 = a ∧ v = .port (occ j).1 j (occ j).2.2 := by
+ constructor
+ · intro e
+ generalize hv : Vertex.clause a = u at e
+ cases e <;> (try simp_all) <;>
+ first | exact (ne_prevPort_of_kind_false _ _ _ rfl hv).elim
+ | exact (ne_nextPort_of_kind_false _ _ _ rfl hv).elim
+ · rintro ⟨j, rfl, rfl⟩
+ exact .exitClause j
+
+theorem allowed_to_clause_iff :
+ Allowed occ v (.clause a) ↔ ∃ j, (occ j).2.1 = a ∧ v = .port (occ j).1 j (!(occ j).2.2) := by
+ constructor
+ · intro e
+ generalize hv : Vertex.clause a = u at e
+ cases e <;> (try simp_all) <;>
+ first | exact (ne_prevPort_of_kind_false _ _ _ rfl hv).elim
+ | exact (ne_nextPort_of_kind_false _ _ _ rfl hv).elim
+ · rintro ⟨j, rfl, rfl⟩
+ exact .enterClause j
+
+end HCGadget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HamiltonianHardness.lean b/lean/OAI/Computability/VPVNP/HamiltonianHardness.lean
new file mode 100644
index 0000000000..5616f1f12c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HamiltonianHardness.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.HCWeighted
+import OAI.Computability.VPVNP.ExactOneFamily
+import OAI.Computability.VPVNP.HamiltonianMembership
+import OAI.Computability.VPVNP.CompletePolynomials
+import OAI.Computability.VPVNP.CompleteFieldDescent
+
+/-!
+# Hamiltonian-cycle completeness and the transfer in Corollary 1.2
+
+The exact-one presentation of an arbitrary VNP family projects from a directed
+Hamiltonian-cycle polynomial of polynomially bounded order. For the paper's
+integer family this is the projection in the direction used in §15.1.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+variable {F : Type*} [Field F] {V : ℕ → Type} [∀ n, Fintype (V n)]
+
+/-- The directed Hamiltonian-cycle polynomial is hard under literal p-projections in all
+characteristics. The graph construction uses the Boolean variables, clauses and occurrences
+of the weighted exact-one presentation. -/
+theorem pProjects_hamiltonian_of_isVNP (p : Family F V) (hp : IsVNP p) :
+ PProjects p (hamiltonianCyclePolynomial F) := by
+ obtain ⟨k, φ, w, hk, hwidth, hclauses, hlits, he⟩ := ExactOne.exists_family_of_isVNP p hp
+ refine ⟨fun n => k n * (3 * HardnessCNF.literalCount (φ n) + 4) + (φ n).length,
+ (hwidth.mul (((PolynomiallyBounded.const 3).mul hlits).add (.const 4))).add hclauses, ?_⟩
+ intro n
+ obtain ⟨ψ, hψ⟩ := HCGadget.weighted_projection (φ n) (hk n) (w n)
+ exact ⟨ψ, hψ.trans (he n)⟩
+
+theorem hamiltonian_vnpComplete (F : Type*) [Field F] : VNPComplete (hamiltonianCyclePolynomial F) :=
+ ⟨hamiltonian_isVNP F, fun _ _ p hp => pProjects_hamiltonian_of_isVNP p hp⟩
+
+/-- The explicit integer family projects from directed Hamiltonian cycles, over every field. -/
+theorem P_pProjects_hamiltonian (F : Type*) [Field F] :
+ PProjects (fun n => map (Int.castRingHom F) (P n)) (hamiltonianCyclePolynomial F) :=
+ pProjects_hamiltonian_of_isVNP _ (P_isVNP F)
+
+/-- The directed Hamiltonian-cycle assertion of Corollary 1.2 follows from the eventual
+lower bound for `P` over one algebraically closed field of the specified characteristic. -/
+theorem hamiltonian_uniform_of_P {K : Type*} [Field K] [IsAlgClosed K]
+ (q : ℕ) [CharP K q]
+ (h : EventuallySuperpolynomial fun n => circuitSize (map (Int.castRingHom K) (P n)))
+ (C : ℕ) :
+ ∃ N, ∀ m ≥ N, ∀ (F : Type*) [Field F] [CharP F q],
+ m ^ C < circuitSize (hamiltonianCyclePolynomial F m) := by
+ obtain ⟨N, hN⟩ := hamiltonian_bound_of_pProjects (P_pProjects_hamiltonian K) h C
+ exact ⟨N, hamiltonianCyclePolynomial_uniform_bound (K := K) q C N hN⟩
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HamiltonianMembership.lean b/lean/OAI/Computability/VPVNP/HamiltonianMembership.lean
new file mode 100644
index 0000000000..3c3e9790e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HamiltonianMembership.lean
@@ -0,0 +1,19 @@
+import OAI.Computability.VPVNP.VerifierFamily
+import OAI.Computability.VPVNP.HamiltonianProjection
+import OAI.Computability.VPVNP.ProjectionClosure
+
+/-! # VNP membership of the directed Hamiltonian cycle family -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+theorem hamiltonian_isVNP (F : Type*) [Field F] :
+ IsVNP (σ := fun n => Fin n × Fin n) (hamiltonianCyclePolynomial F) := by
+ apply (P_isVNP F).of_pProjects (hamiltonian_PProjects F)
+ simpa only [Fintype.card_prod, Fintype.card_fin] using
+ PolynomiallyBounded.id.mul PolynomiallyBounded.id
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HamiltonianPadding.lean b/lean/OAI/Computability/VPVNP/HamiltonianPadding.lean
new file mode 100644
index 0000000000..44bfc6c4c7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HamiltonianPadding.lean
@@ -0,0 +1,203 @@
+import OAI.Computability.VPVNP.Circuits
+import OAI.Computability.VPVNP.Hamiltonian
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Algebra.BigOperators.GroupWithZero.Finset
+import Mathlib.GroupTheory.Perm.Fin
+
+/-!
+# Subdividing a forced arc of a directed Hamiltonian cycle
+
+Section 15.1 of *VP and VNP differ over every field* pads the directed
+Hamiltonian-cycle polynomial by one vertex. Number the new vertex by zero
+and embed the old vertices by `Fin.succ`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open Equiv Equiv.Perm MvPolynomial
+
+/-- Insert vertex zero immediately after the old vertex `a` in its cycle. -/
+def subdivideCycle {m : ℕ} (a : Fin m) (π : Perm (Fin m)) : Perm (Fin (m + 1)) :=
+ decomposeFin.symm ((π a).succ, π)
+
+@[simp] theorem subdivideCycle_zero {m : ℕ} (a : Fin m) (π : Perm (Fin m)) :
+ subdivideCycle a π 0 = (π a).succ := by simp [subdivideCycle]
+
+@[simp] theorem subdivideCycle_at {m : ℕ} (a : Fin m) (π : Perm (Fin m)) :
+ subdivideCycle a π a.succ = 0 := by simp [subdivideCycle]
+
+@[simp] theorem subdivideCycle_away {m : ℕ} (a : Fin m) (π : Perm (Fin m))
+ {i : Fin m} (hi : i ≠ a) : subdivideCycle a π i.succ = (π i).succ := by
+ simp [subdivideCycle, swap_apply_of_ne_of_ne, hi]
+
+theorem subdivideCycle_injective {m : ℕ} (a : Fin m) : Function.Injective (subdivideCycle a) := by
+ intro π τ h
+ exact congrArg Prod.snd (decomposeFin.symm.injective h)
+
+theorem range_subdivideCycle {m : ℕ} (a : Fin m) (σ : Perm (Fin (m + 1))) :
+ (∃ π, subdivideCycle a π = σ) ↔ σ a.succ = 0 := by
+ constructor
+ · rintro ⟨π, rfl⟩
+ exact subdivideCycle_at _ _
+ · obtain ⟨⟨p, π⟩, rfl⟩ := decomposeFin.symm.surjective σ
+ intro h
+ rw [decomposeFin_symm_apply_succ] at h
+ have heq : (π a).succ = p := (swap 0 p).injective (by simpa using h)
+ exact ⟨π, by simp [subdivideCycle, heq]⟩
+
+/-- A map that sends each step in a finite permutation orbit to two vertices
+of the same target orbit sends the whole orbit into that target orbit. -/
+private theorem map_sameCycle {α β : Type*} [Finite α] (f : Perm α) (g : Perm β)
+ (map : α → β) (step : ∀ i, g.SameCycle (map i) (map (f i)))
+ {x y : α} (h : f.SameCycle x y) : g.SameCycle (map x) (map y) := by
+ obtain ⟨k, hk, rfl⟩ := h.exists_pow_eq'
+ clear hk h
+ induction k with
+ | zero => exact SameCycle.rfl
+ | succ k ih =>
+ rw [pow_succ', mul_apply]
+ exact ih.trans (step _)
+
+theorem subdivideCycle_isCycleOn_iff {m : ℕ} (a : Fin m) (π : Perm (Fin m)) :
+ (subdivideCycle a π).IsCycleOn Set.univ ↔ π.IsCycleOn Set.univ := by
+ let σ := subdivideCycle a π
+ let contract : Fin (m + 1) → Fin m := Fin.cases a id
+ have hzero : contract 0 = a := rfl
+ have hsucc (i : Fin m) : contract i.succ = i := rfl
+ have hσ0 : σ 0 = (π a).succ := subdivideCycle_zero a π
+ have hσa : σ a.succ = 0 := subdivideCycle_at a π
+ have hσaway {i : Fin m} (h : i ≠ a) : σ i.succ = (π i).succ := subdivideCycle_away a π h
+ constructor
+ · intro h
+ refine ⟨π.bijective.bijOn_univ, fun x _ y _ => ?_⟩
+ have step (i : Fin (m + 1)) : π.SameCycle (contract i) (contract (σ i)) := by
+ refine Fin.cases ?_ (fun j => ?_) i
+ · rw [hσ0, hzero, hsucc]
+ exact SameCycle.rfl.apply_right
+ · by_cases hj : j = a
+ · subst j
+ rw [hσa, hsucc, hzero]
+ · rw [hσaway hj, hsucc, hsucc]
+ exact SameCycle.rfl.apply_right
+ exact map_sameCycle σ π contract step (h.2 (Set.mem_univ x.succ) (Set.mem_univ y.succ))
+ · intro h
+ have step (i : Fin m) : σ.SameCycle i.succ (π i).succ := by
+ by_cases hi : i = a
+ · subst i
+ rw [← hσ0, ← hσa]
+ exact SameCycle.rfl.apply_right.apply_right
+ · rw [← hσaway hi]
+ exact SameCycle.rfl.apply_right
+ have same (i j : Fin m) : σ.SameCycle i.succ j.succ :=
+ map_sameCycle π σ Fin.succ step (h.2 (Set.mem_univ i) (Set.mem_univ j))
+ have all (i : Fin (m + 1)) : σ.SameCycle a.succ i := by
+ refine Fin.cases ?_ (same a) i
+ rw [← hσa]
+ exact SameCycle.rfl.apply_right
+ exact ⟨σ.bijective.bijOn_univ, fun x _ y _ => (all x).symm.trans (all y)⟩
+
+/-- The forced arc from the old root to the new vertex has weight one.
+The new outgoing arcs carry the old root's variables except for the
+arc back to the root, which is forbidden. -/
+def cyclePaddingProjection {m : ℕ} (R : Type*) [CommSemiring R] (a : Fin m)
+ : Projection R (Fin (m + 1) × Fin (m + 1)) (Fin m × Fin m) := fun edge =>
+ Fin.cases
+ (Fin.cases (.inr 0) (fun j => if j = a then .inr 0 else .inl (a, j)))
+ (fun i => Fin.cases (if i = a then .inr 1 else .inr 0)
+ (fun j => if i = a then .inr 0 else .inl (i, j)))
+ edge.1 edge.2
+
+private theorem subdivideCycle_weight {R : Type*} [CommSemiring R] {m : ℕ} (hm : 2 ≤ m)
+ (a : Fin m) (π : Equiv.Perm (Fin m)) (hπ : π.IsCycleOn Set.univ) :
+ (∏ i, Sum.elim X C (cyclePaddingProjection R a (i, subdivideCycle a π i))) =
+ ∏ i, X (i, π i) := by
+ classical
+ let : Nontrivial (Fin m) := Fin.nontrivial_iff_two_le.mpr hm
+ have hne : π a ≠ a := hπ.apply_ne Set.nontrivial_univ (Set.mem_univ a)
+ rw [Fin.prod_univ_succ]
+ simp only [subdivideCycle_zero, cyclePaddingProjection, Fin.cases_zero, Fin.cases_succ,
+ ite_eq_right hne, Sum.elim_inl]
+ rw [← Finset.mul_prod_erase Finset.univ (fun i : Fin m => (X (i, π i) :
+ MvPolynomial (Fin m × Fin m) R)) (Finset.mem_univ a)]
+ congr 1
+ rw [← Finset.mul_prod_erase Finset.univ _ (Finset.mem_univ a)]
+ simp only [subdivideCycle_at, Fin.cases_zero, ite_true, Sum.elim_inr, map_one, one_mul]
+ apply Finset.prod_congr rfl
+ intro i hi
+ have hia := (Finset.mem_erase.mp hi).1
+ simp [subdivideCycle_away a π hia, hia]
+
+/-- Contracting the forced arc projects the polynomial of order `m + 1`
+to the polynomial of order `m` over any coefficient semiring. -/
+theorem hamiltonianCyclePolynomial_pad {R : Type*} [CommSemiring R] {m : ℕ} (hm : 2 ≤ m)
+ (a : Fin m) :
+ eval₂Hom C (fun e => Sum.elim X C (cyclePaddingProjection R a e))
+ (hamiltonianCyclePolynomial R (m + 1)) = hamiltonianCyclePolynomial R m := by
+ classical
+ simp only [hamiltonianCyclePolynomial, map_sum, map_prod, eval₂Hom_X']
+ have hmpos : 0 < m := by omega
+ have subset : (spanningCycles m).image (subdivideCycle a) ⊆ spanningCycles (m + 1) := by
+ intro σ hσ
+ obtain ⟨π, hπ, rfl⟩ := Finset.mem_image.mp hσ
+ simpa [spanningCycles, subdivideCycle_isCycleOn_iff, hmpos] using hπ
+ rw [← Finset.sum_subset subset, Finset.sum_image (subdivideCycle_injective a).injOn]
+ · apply Finset.sum_congr rfl
+ intro π hπ
+ exact subdivideCycle_weight hm a π (by simpa [spanningCycles, hmpos] using hπ)
+ · intro σ hσ hmiss
+ apply Finset.prod_eq_zero (Finset.mem_univ a.succ)
+ have hne : σ a.succ ≠ 0 := by
+ intro hforced
+ obtain ⟨π, rfl⟩ := (range_subdivideCycle a σ).2 hforced
+ apply hmiss
+ exact Finset.mem_image.mpr ⟨π, by
+ simpa [spanningCycles, subdivideCycle_isCycleOn_iff, hmpos] using hσ, rfl⟩
+ obtain ⟨j, hj⟩ := Fin.exists_succ_eq_of_ne_zero hne
+ simp [← hj, cyclePaddingProjection]
+
+
+/-- Contraction gives an exact circuit at the smaller order with the same number
+of binary gates. -/
+theorem Circuit.contract_hamiltonian {R : Type*} [CommRing R] {m k : ℕ} (hm : 2 ≤ m)
+ (a : Fin m) (c : Circuit R (Fin (m + 1) × Fin (m + 1)) k)
+ (hc : c.polynomial = hamiltonianCyclePolynomial R (m + 1)) :
+ (c.subst (cyclePaddingProjection R a) id).polynomial = hamiltonianCyclePolynomial R m := by
+ rw [Circuit.project_polynomial, hc]
+ exact hamiltonianCyclePolynomial_pad hm a
+
+private theorem spanningCycles_two : spanningCycles 2 = {swap 0 1} := by
+ classical
+ ext π
+ simp only [spanningCycles, Finset.mem_filter, Finset.mem_univ, true_and, Finset.mem_singleton,
+ Nat.zero_lt_succ]
+ constructor
+ · intro h
+ ext i
+ have hi := h.apply_ne Set.nontrivial_univ (Set.mem_univ i)
+ have hv : π i = 0 ∨ π i = 1 := by omega
+ rcases hv with hv | hv <;> fin_cases i <;> simp_all
+ · rintro rfl
+ have h := (isCycle_swap (show (0 : Fin 2) ≠ 1 by decide)).isCycleOn
+ convert h using 1
+ ext i
+ fin_cases i <;> simp
+
+/-- The directed cycle on two vertices consists of its two opposite arcs. -/
+theorem hamiltonianCyclePolynomial_two (R : Type*) [CommSemiring R] :
+ hamiltonianCyclePolynomial R 2 = X (0, 1) * X (1, 0) := by
+ simp [hamiltonianCyclePolynomial, spanningCycles_two, Fin.prod_univ_two]
+
+/-- Keep the first arc and set the other factors to one, as in Section 1.1. -/
+def cycleEdgeProjection (R : Type*) [CommRing R] {E : Type*} (e : E) :
+ Projection R (Fin 2 × Fin 2) E := fun ij => if ij = (0, 1) then .inl e else .inr 1
+
+theorem cycleEdgeProjection_hamiltonian {R : Type*} [CommRing R] {E : Type*} (e : E) :
+ (cycleEdgeProjection R e).hom (hamiltonianCyclePolynomial R 2) = X e := by
+ rw [hamiltonianCyclePolynomial_two, map_mul]
+ simp [Projection.hom, cycleEdgeProjection]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HamiltonianProjection.lean b/lean/OAI/Computability/VPVNP/HamiltonianProjection.lean
new file mode 100644
index 0000000000..43de06c77b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HamiltonianProjection.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.Classes
+import OAI.Computability.VPVNP.Pinning
+import OAI.Computability.VPVNP.CycleQuery
+import OAI.Computability.VPVNP.QueryPrefix
+import Mathlib.Tactic.Ring
+import Mathlib.Tactic.Linarith
+
+/-!
+# Projecting the universal integer family onto directed Hamiltonian cycles
+
+For each matrix order, a deterministic finite query program traverses the
+directed cycle, checking one full row at a time. Compiling this program with
+a budget of `m * m` queries gives a literal machine table. Pinning its prefix
+in equation (1.1) leaves exactly the cycle monomials. This construction uses
+an order-dependent prefix whose bit length is polynomially bounded.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u
+
+private theorem cycleIndex_bound (A m : ℕ) :
+ A * ((m * m + 1) * (2 + m * (m * (m * (m + 1)))) * (m * m + 1) + 1) ^ 2 + m * m ≤
+ (16 * A + 1) * (m + 1) ^ 16 := by
+ let z := m + 1
+ have h₂ : m * m + 1 ≤ z ^ 2 := by dsimp [z]; nlinarith
+ have h₄ : 2 + m * (m * (m * (m + 1))) ≤ 3 * z ^ 4 := by
+ dsimp [z]; ring_nf; omega
+ have h₈ : (m * m + 1) * (2 + m * (m * (m * (m + 1)))) * (m * m + 1) + 1 ≤
+ 4 * z ^ 8 := by
+ have h₁ : 1 ≤ z ^ 8 := Nat.one_le_pow _ _ (by dsimp [z]; omega)
+ calc _ ≤ z ^ 2 * (3 * z ^ 4) * z ^ 2 + z ^ 8 :=
+ Nat.add_le_add (Nat.mul_le_mul (Nat.mul_le_mul h₂ h₄) h₂) h₁
+ _ = _ := by ring
+ have h₁₆ : m * m ≤ z ^ 16 := (Nat.le_add_right _ 1).trans <| h₂.trans <|
+ Nat.pow_le_pow_right (by dsimp [z]; omega) (by decide)
+ calc
+ _ ≤ A * (4 * z ^ 8) ^ 2 + z ^ 16 :=
+ Nat.add_le_add (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left h₈ _)) h₁₆
+ _ = _ := by
+ rw [mul_pow, ← pow_mul, Nat.add_mul, one_mul, ← mul_assoc, Nat.mul_comm A]
+ rfl
+
+private theorem P_zero : P 0 = 0 := by
+ have malformed (x : Fin 0 → Bool) : acceptingCount x = 0 := by
+ apply acceptingCount_of_malformed
+ simp only [List.ofFn_zero]
+ rfl
+ simp [P, pairedPolynomial, malformed]
+
+private theorem hamiltonianCyclePolynomial_zero (S : Type*) [CommSemiring S] :
+ hamiltonianCyclePolynomial S 0 = 0 := by
+ classical
+ simp [hamiltonianCyclePolynomial, spanningCycles]
+
+/-- A single polynomially bounded choice of source orders works over all commutative rings. -/
+theorem hamiltonian_projection_orders :
+ ∃ r : ℕ → ℕ, (∀ m, r m ≤ 16001 * (m + 1) ^ 16) ∧
+ ∀ m (R : Type u) [CommRing R], ∃ φ : Projection R (Fin (r m) × Bool) (Fin m × Fin m),
+ φ.hom (MvPolynomial.map (Int.castRingHom R) (P (r m))) = hamiltonianCyclePolynomial R m := by
+ classical
+ have atOrder (m : ℕ) : ∃ n : ℕ, n ≤ 16001 * (m + 1) ^ 16 ∧
+ ∀ (R : Type u) [CommRing R], ∃ φ : Projection R (Fin n × Bool) (Fin m × Fin m),
+ φ.hom (MvPolynomial.map (Int.castRingHom R) (P n)) = hamiltonianCyclePolynomial R m := by
+ by_cases hz : m = 0
+ · subst m
+ refine ⟨0, Nat.zero_le _, ?_⟩
+ intro R _
+ exact ⟨fun i => Fin.elim0 i.1, by simp [P_zero, hamiltonianCyclePolynomial_zero]⟩
+ let root : Fin m := ⟨0, Nat.pos_of_ne_zero hz⟩
+ obtain ⟨l, bits, hlen, hcount⟩ := QueryMachine.exists_prefix (cycleQuery root) (m * m)
+ refine ⟨l + m * m, ?_, ?_⟩
+ · have hcard : Fintype.card (CycleState m) = 2 + m * (m * (m * (m + 1))) := by
+ simp [CycleState]
+ rw [hcard] at hlen
+ exact (Nat.add_le_add_right hlen _).trans (cycleIndex_bound 1000 m)
+ · intro R _
+ refine ⟨pinVariables bits finProdFinEquiv.symm, P_pin_hamiltonian bits m ?_ R⟩
+ intro x
+ rw [hcount, cycleIndicator]
+ by_cases h : x ∈ (spanningCycles m).image permutationEdges
+ · simp [h, (cycleQuery_eval_iff root x).mpr h]
+ · have hn := mt (cycleQuery_eval_iff root x).mp h
+ simp [h, Bool.eq_false_iff.mpr hn]
+ choose r hr hφ using atOrder
+ exact ⟨r, hr, hφ⟩
+
+/-- Directed Hamiltonian cycles are p-projections of the integer family over each field. -/
+theorem hamiltonian_PProjects (F : Type u) [Field F] :
+ PProjects (hamiltonianCyclePolynomial F)
+ (fun n => MvPolynomial.map (Int.castRingHom F) (P n)) := by
+ obtain ⟨r, hr, hφ⟩ := hamiltonian_projection_orders.{u}
+ refine ⟨r, ⟨16001 * 2 ^ 16, 16, 1, ?_⟩, fun m => hφ m F⟩
+ intro m hm
+ calc
+ r m ≤ 16001 * (m + 1) ^ 16 := hr m
+ _ ≤ 16001 * (2 * m) ^ 16 := by gcongr; omega
+ _ = _ := by rw [mul_pow, mul_assoc]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HamiltonianRelabel.lean b/lean/OAI/Computability/VPVNP/HamiltonianRelabel.lean
new file mode 100644
index 0000000000..56d179b9d3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HamiltonianRelabel.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.Hamiltonian
+import OAI.Computability.VPVNP.Circuits
+
+/-!
+# Weighted directed Hamiltonian cycles on a finite vertex type
+
+Relabel the vertices by matrix indices, substitute zero on forbidden arcs, and
+put the indicated variable or scalar on each allowed arc. In the resulting
+formal polynomial only the permitted spanning permutations contribute.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+open scoped Classical
+
+private theorem cycle_relabel {α β : Type*} (e : α ≃ β) {π : Equiv.Perm α}
+ (h : π.IsCycleOn Set.univ) : (e.permCongr π).IsCycleOn Set.univ := by
+ refine ⟨(e.permCongr π).bijective.bijOn_univ, fun x _ y _ => ?_⟩
+ obtain ⟨i, hi⟩ := h.2 (Set.mem_univ (e.symm x)) (Set.mem_univ (e.symm y))
+ refine ⟨i, ?_⟩
+ change (e.permCongrHom π ^ i) x = y
+ rw [← map_zpow]
+ simp only [Equiv.permCongrHom_coe, Equiv.permCongr_apply, hi, Equiv.apply_symm_apply]
+
+/-- The projected matrix has the given arc label on allowed arcs and zero elsewhere. -/
+theorem hamiltonian_projection_on_allowed {V R τ : Type*} [Fintype V] [CommRing R] {m : ℕ}
+ (e : Fin m ≃ V) (hm : 0 < m) (ok : V → V → Prop) (w : V → V → τ ⊕ R) :
+ ∃ ψ : Projection R (Fin m × Fin m) τ, ψ.hom (hamiltonianCyclePolynomial R m) =
+ ∑ π : {π : Equiv.Perm V // π.IsCycleOn Set.univ ∧ ∀ i, ok i (π i)},
+ ∏ i, (w i (π.val i)).elim X C := by
+ classical
+ let ψ : Projection R (Fin m × Fin m) τ := fun (i,j) =>
+ if ok (e i) (e j) then w (e i) (e j) else .inr 0
+ let good (π : Equiv.Perm V) := π.IsCycleOn Set.univ ∧ ∀ i, ok i (π i)
+ let weight (π : Equiv.Perm V) := ∏ i, (w i (π i)).elim (X (R := R)) C
+ refine ⟨ψ, ?_⟩
+ change ψ.hom (hamiltonianCyclePolynomial R m) = ∑ π : {π // good π}, weight π.val
+ rw [← Finset.sum_subtype (Finset.univ.filter good) (by simp) weight, Finset.sum_filter,
+ ← e.permCongr.sum_comp (fun π => if good π then weight π else 0)]
+ simp only [hamiltonianCyclePolynomial, spanningCycles, map_sum, Finset.sum_filter,
+ hm, true_and]
+ apply Finset.sum_congr rfl
+ intro π _
+ have hc : (e.permCongr π).IsCycleOn Set.univ ↔ π.IsCycleOn Set.univ := by
+ constructor
+ · intro hc
+ have hr := cycle_relabel e.symm hc
+ change (e.permCongr.symm (e.permCongr π)).IsCycleOn Set.univ at hr
+ rw [Equiv.symm_apply_apply] at hr
+ exact hr
+ · exact cycle_relabel e
+ by_cases hcycle : π.IsCycleOn Set.univ
+ · simp only [hcycle, ite_true, good, hc, true_and, map_prod]
+ by_cases hok : ∀ i, ok i (e.permCongr π i)
+ · rw [ite_eq_left hok]
+ dsimp only [weight]
+ rw [← e.prod_comp (fun i => (w i (e.permCongr π i)).elim X C)]
+ apply Finset.prod_congr rfl
+ intro i _
+ have hi : ok (e i) (e (π i)) := by simpa using hok (e i)
+ simp [Projection.hom, ψ, hi]
+ · rw [ite_eq_right hok]
+ obtain ⟨v, hv⟩ := not_forall.mp hok
+ apply Finset.prod_eq_zero (Finset.mem_univ (e.symm v))
+ have hi : ¬ok v (e (π (e.symm v))) := hv
+ simp [Projection.hom, ψ, hi]
+ · simp [hcycle, good, hc]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Hardness.lean b/lean/OAI/Computability/VPVNP/Hardness.lean
new file mode 100644
index 0000000000..dccad8ca9c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Hardness.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.HardnessCircuitRepresentation
+import OAI.Computability.VPVNP.HardnessWitness
+import OAI.Computability.VPVNP.VerifierFamily
+
+/-!
+# VNP-completeness of the integer family
+
+A VNP summand has a polynomial-size ordered-parse CNF presentation. Copying each selected
+production flag separates its scalar and variable labels. Witness variables become free Boolean
+bits constrained by their selected occurrences. This leaves only variable and scalar projection
+weights. The universal coefficient machine can check the resulting CNF by querying its payload.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Hardness
+
+open MvPolynomial HardnessCNF
+
+variable {F : Type*} [Field F] {V : ℕ → Type} [∀ n, Fintype (V n)]
+
+/-- Every VNP family has a CNF presentation with polynomially many bits and literals.
+Each selected bit contributes a single variable or a single scalar. -/
+theorem exists_weightedCNF_of_isVNP (p : Family F V) (hp : IsVNP p) :
+ ∃ (k : ℕ → ℕ) (φ : ∀ n, CNF (k n)) (weights : ∀ n, Projection F (Fin (k n)) (V n)),
+ PolynomiallyBounded k ∧ PolynomiallyBounded (fun n => literalCount (φ n)) ∧
+ ∀ n, weightedCNF (φ n) (fun i => (weights n i).elim X C) = p n := by
+ obtain ⟨W, inst, g, hW, hg, he⟩ := hp.2
+ let : ∀ n, Fintype (W n) := inst
+ obtain ⟨m, hk, hlit, hm⟩ := exists_markedCNF_of_isVP g hg
+ refine ⟨fun n => HardnessWitness.width (m n).width (W n),
+ fun n => HardnessWitness.augment (m n).clauses (m n).label,
+ fun n => HardnessWitness.augmentedWeight (m n).scalar (m n).label, ?_, ?_, ?_⟩
+ · exact hk.add (hk.add hW)
+ · exact (hlit.add ((PolynomiallyBounded.const 6).mul hk)).of_le
+ fun n => HardnessWitness.literalCount_augment_le (m n).clauses (m n).label
+ · intro n
+ rw [he n, ← hm n]
+ exact (HardnessWitness.sum_witnessValue_weightedCNF (m n).clauses (m n).scalar (m n).label).symm
+
+/-- Each VNP family is a p-projection of the explicit universal integer family
+after casting coefficients to the same field. -/
+theorem pProjects_P_of_isVNP (p : Family F V) (hp : IsVNP p) :
+ PProjects p (fun n => map (Int.castRingHom F) (P n)) := by
+ obtain ⟨k, φ, weights, hk, hlit, he⟩ := exists_weightedCNF_of_isVNP p hp
+ rw [← funext he]
+ exact weightedCNF_PProjects φ weights hk hlit
+
+end Hardness
+
+section
+
+/-- The VNP-completeness assertion of Theorem 1.1 for every field, with arbitrary field
+constants and variable-or-constant projections of formal polynomials. -/
+theorem P_vnpComplete (F : Type*) [Field F] :
+ VNPComplete (σ := fun n => Fin n × Bool) (fun n => MvPolynomial.map (Int.castRingHom F) (P n)) :=
+ ⟨P_isVNP F, fun _ _ p hp => Hardness.pProjects_P_of_isVNP p hp⟩
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessAlternatives.lean b/lean/OAI/Computability/VPVNP/HardnessAlternatives.lean
new file mode 100644
index 0000000000..c2ea311367
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessAlternatives.lean
@@ -0,0 +1,324 @@
+import OAI.Computability.VPVNP.HardnessWeights
+import Mathlib.Data.Fintype.EquivFin
+import Mathlib.Data.Fintype.BigOperators
+import Mathlib.Algebra.BigOperators.Group.Finset.Sigma
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+
+/-!
+# Choosing among weighted CNFs
+
+Each alternative has a selector bit and a private block of data bits. The selector
+bits are one-hot. The chosen formula is enforced, while every unchosen block is
+filled with zeros. Consequently an accepted local assignment extends uniquely
+to an accepted global assignment, even for zero-variable formulas.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HardnessAlternatives
+
+open HardnessCNF
+open scoped Classical
+
+variable {I : Type*} [Fintype I] {k : I → ℕ}
+
+/-- Boolean variables of the disjoint-alternatives formula. Each alternative gets a selector
+and its own block of local variables. -/
+abbrev Slot (k : I → ℕ) := I ⊕ (Σ i, Fin (k i))
+
+/-- The total number of selectors and local variables in the alternatives formula. -/
+def width (k : I → ℕ) := Fintype.card (Slot k)
+
+/-- A bijection from the tagged selector and local-variable slots onto the finite set of CNF
+variable indices. -/
+noncomputable def index (k : I → ℕ) : Slot k ≃ Fin (width k) := Fintype.equivFin _
+
+theorem width_le {K : ℕ} (h : ∀ i, k i ≤ K) :
+ width k ≤ Fintype.card I * (1 + K) := by
+ simp only [width, Fintype.card_sum, Fintype.card_sigma, Fintype.card_fin, Nat.mul_add,
+ Nat.mul_one]
+ apply Nat.add_le_add_left
+ simpa using Finset.sum_le_sum (s := Finset.univ) (fun i _ => h i)
+
+private noncomputable def flag (k : I → ℕ) (i : I) := index k (.inl i)
+private noncomputable def bit (k : I → ℕ) (i : I) (j : Fin (k i)) := index k (.inr ⟨i,j⟩)
+
+private noncomputable def allIndices (I : Type*) [Fintype I] : List I :=
+ (Finset.univ : Finset I).toList
+
+@[simp] private theorem mem_allIndices (i : I) : i ∈ allIndices I := by simp [allIndices]
+
+@[simp] private theorem length_allIndices : (allIndices I).length = Fintype.card I := by
+ simp [allIndices]
+
+private noncomputable def exclusive (k : I → ℕ) (i : I) : CNF (width k) :=
+ (allIndices I).map fun j => [(flag k i, false), (flag k j, decide (i = j))]
+
+private noncomputable def inactive (k : I → ℕ) (i : I) : CNF (width k) :=
+ (List.finRange (k i)).map fun j => [(flag k i, true), (bit k i j, false)]
+
+private noncomputable def guarded (φ : ∀ i, CNF (k i)) (i : I) : CNF (width k) :=
+ if [] ∈ φ i then [[(flag k i, false)]] else
+ (φ i).map fun c => (flag k i, false) :: c.map fun l => (bit k i l.1, l.2)
+
+/-- Select exactly one formula, enforcing its clauses and zeroing all inactive variables. -/
+noncomputable def formula (φ : ∀ i, CNF (k i)) : CNF (width k) :=
+ ((allIndices I).map fun i => (flag k i, true)) ::
+ (allIndices I).flatMap fun i => exclusive k i ++ inactive k i ++ guarded φ i
+
+private def Hits {n : ℕ} (x : Fin n → Bool) (c : List (Literal n)) : Prop :=
+ ∃ l ∈ c, x l.1 = l.2
+
+private theorem sat_map {A : Type*} {n : ℕ} (xs : List A) (f : A → List (Literal n))
+ (x : Fin n → Bool) : Satisfies (xs.map f) x ↔ ∀ i ∈ xs, Hits x (f i) := by
+ simp [Satisfies, Hits]
+
+private theorem sat_append {n : ℕ} (φ ψ : CNF n) (x : Fin n → Bool) :
+ Satisfies (φ ++ ψ) x ↔ Satisfies φ x ∧ Satisfies ψ x := by
+ simp [Satisfies, or_imp, forall_and]
+
+private theorem sat_exclusive (i : I) (x : Fin (width k) → Bool) :
+ Satisfies (exclusive k i) x ↔ ∀ j, x (flag k i) = true → x (flag k j) = true → i = j := by
+ rw [exclusive, sat_map]
+ simp only [mem_allIndices, forall_const, Hits, List.mem_cons, List.not_mem_nil, or_false,
+ exists_eq_or_imp]
+ constructor
+ · intro h j hi hj
+ simpa [hi, hj] using h j
+ · intro h j
+ cases hi : x (flag k i) <;> cases hj : x (flag k j) <;> by_cases e : i = j <;>
+ simp_all
+ exact e (h j hj)
+
+private theorem sat_inactive (i : I) (x : Fin (width k) → Bool) :
+ Satisfies (inactive k i) x ↔ ∀ j, x (flag k i) = false → x (bit k i j) = false := by
+ rw [inactive, sat_map]
+ cases h : x (flag k i) <;> simp [Hits, h]
+
+private theorem sat_guarded (φ : ∀ i, CNF (k i)) (i : I) (x : Fin (width k) → Bool) :
+ Satisfies (guarded φ i) x ↔ x (flag k i) = true → Satisfies (φ i) (fun j => x (bit k i j)) := by
+ by_cases he : [] ∈ φ i
+ · have hn : ¬ Satisfies (φ i) (fun j => x (bit k i j)) := by
+ intro h
+ simpa using h [] he
+ rw [guarded, ite_eq_left he]
+ simp only [hn, imp_false]
+ simp [Satisfies]
+ · rw [guarded, ite_eq_right he, sat_map]
+ have hit (c : List (Literal (k i))) :
+ Hits x ((flag k i, false) :: c.map (fun l => (bit k i l.1, l.2))) ↔
+ x (flag k i) = false ∨ Hits (fun j => x (bit k i j)) c := by
+ simp only [Hits, List.mem_cons, exists_eq_or_imp, List.mem_map]
+ aesop
+ constructor
+ · intro h hs c hc
+ exact ((hit c).1 (h c hc)).resolve_left (by simp [hs])
+ · intro h c hc
+ apply (hit c).2
+ cases hs : x (flag k i) with
+ | false => exact Or.inl rfl
+ | true => exact Or.inr (h hs c hc)
+
+private theorem sat_formula (φ : ∀ i, CNF (k i)) (x : Fin (width k) → Bool) :
+ Satisfies (formula φ) x ↔ (∃ i, x (flag k i) = true) ∧ ∀ i,
+ (∀ j, x (flag k i) = true → x (flag k j) = true → i = j) ∧
+ (∀ j, x (flag k i) = false → x (bit k i j) = false) ∧
+ (x (flag k i) = true → Satisfies (φ i) (fun j => x (bit k i j))) := by
+ have cons {n : ℕ} (c : List (Literal n)) (ψ : CNF n) (y : Fin n → Bool) :
+ Satisfies (c :: ψ) y ↔ Hits y c ∧ Satisfies ψ y := by
+ simp [Hits, Satisfies]
+ have flat {n : ℕ} (l : List I) (f : I → CNF n) (y : Fin n → Bool) :
+ Satisfies (l.flatMap f) y ↔ ∀ a ∈ l, Satisfies (f a) y := by
+ simp [Satisfies]
+ aesop
+ rw [formula, cons, flat]
+ simp [Hits, sat_append, sat_guarded, sat_exclusive, sat_inactive]
+
+private noncomputable def encode (i : I) (y : Fin (k i) → Bool) : Fin (width k) → Bool :=
+ fun z => ((index k).symm z).elim (fun j => decide (j = i))
+ (fun s => Function.update (fun j (_ : Fin (k j)) => false) i y s.1 s.2)
+
+@[simp] private theorem encode_flag (i j : I) (y : Fin (k i) → Bool) :
+ encode i y (flag k j) = decide (j = i) := by simp [encode, flag]
+
+@[simp] private theorem encode_bit_self (i : I) (y : Fin (k i) → Bool) (z : Fin (k i)) :
+ encode i y (bit k i z) = y z := by simp [encode, bit]
+
+private theorem encode_bit_other {i j : I} (hne : j ≠ i) (y : Fin (k i) → Bool) (z : Fin (k j)) :
+ encode i y (bit k j z) = false := by simp [encode, bit, hne]
+
+private theorem sat_encode (φ : ∀ i, CNF (k i)) (i : I) (y : Fin (k i) → Bool) :
+ Satisfies (formula φ) (encode i y) ↔ Satisfies (φ i) y := by
+ rw [sat_formula]
+ constructor
+ · rintro ⟨_, h⟩
+ simpa using (h i).2.2 (by simp)
+ · intro h
+ refine ⟨⟨i, by simp⟩, fun j => ⟨?_, ?_, ?_⟩⟩
+ · simp +contextual
+ · intro z hj
+ exact encode_bit_other (by simpa using hj) _ _
+ · intro hj
+ have : j = i := by simpa using hj
+ subst j
+ simpa using h
+
+private noncomputable def solutions (φ : ∀ i, CNF (k i)) :
+ (Σ i, {y : Fin (k i) → Bool // Satisfies (φ i) y}) ≃
+ {x : Fin (width k) → Bool // Satisfies (formula φ) x} := by
+ let f : (Σ i, {y : Fin (k i) → Bool // Satisfies (φ i) y}) →
+ {x : Fin (width k) → Bool // Satisfies (formula φ) x} :=
+ fun ⟨i,y⟩ => ⟨encode i y.val, (sat_encode φ i y.val).2 y.property⟩
+ apply Equiv.ofBijective f
+ constructor
+ · rintro ⟨i,y⟩ ⟨j,z⟩ he
+ have h : encode i y.val = encode j z.val := congrArg Subtype.val he
+ have hij : i = j := by simpa using congrFun h (flag k i)
+ subst j
+ congr 1
+ apply Subtype.ext
+ funext u
+ simpa using congrFun h (bit k i u)
+ · rintro ⟨x,hx⟩
+ obtain ⟨⟨i,hi⟩, hr⟩ := (sat_formula φ x).1 hx
+ let y (z : Fin (k i)) := x (bit k i z)
+ refine ⟨⟨i, y, (hr i).2.2 hi⟩, Subtype.ext ?_⟩
+ change encode i y = x
+ funext z
+ obtain ⟨s,rfl⟩ := (index k).surjective z
+ cases s with
+ | inl j =>
+ change encode i y (flag k j) = x (flag k j)
+ by_cases e : j = i
+ · subst j; simp [hi]
+ · have hj : x (flag k j) = false := by
+ cases h : x (flag k j)
+ · rfl
+ · exact (e ((hr j).1 i h hi)).elim
+ simp [hj, e]
+ | inr s =>
+ obtain ⟨j,u⟩ := s
+ change encode i y (bit k j u) = x (bit k j u)
+ by_cases e : j = i
+ · subst j; simp [y]
+ · rw [encode_bit_other e]
+ symm
+ apply (hr j).2.1 u
+ cases h : x (flag k j)
+ · rfl
+ · exact (e ((hr j).1 i h hi)).elim
+
+/-- Label each selector and each data slot. The labels can be weights or any
+parameters from which the weights will be built. -/
+noncomputable def weight {A : Type*} (k : I → ℕ) (a : I → A) (w : ∀ i, Fin (k i) → A)
+ (z : Fin (width k)) : A := ((index k).symm z).elim a (fun s => w s.1 s.2)
+
+@[simp] theorem weight_selector {A : Type*} (k : I → ℕ) (a : I → A) (w : ∀ i, Fin (k i) → A)
+ (i : I) : weight k a w (index k (.inl i)) = a i := by simp [weight]
+
+@[simp] theorem weight_data {A : Type*} (k : I → ℕ) (a : I → A) (w : ∀ i, Fin (k i) → A)
+ (i : I) (j : Fin (k i)) : weight k a w (index k (.inr ⟨i,j⟩)) = w i j := by simp [weight]
+
+variable {R : Type*} [CommSemiring R]
+
+private theorem prod_encode (a : I → R) (w : ∀ i, Fin (k i) → R) (i : I) (y : Fin (k i) → Bool) :
+ (∏ z, if encode i y z then weight k a w z else 1) =
+ a i * ∏ j, if y j then w i j else 1 := by
+ rw [← (index k).prod_comp (fun z => if encode i y z then weight k a w z else 1),
+ Fintype.prod_sum_type, Fintype.prod_sigma]
+ have sel (j : I) : encode i y (index k (.inl j)) = decide (j = i) := encode_flag i j y
+ simp only [sel, decide_eq_true_eq, weight_selector, weight_data, Finset.prod_ite_eq',
+ Finset.mem_univ, ite_true]
+ congr 1
+ rw [Finset.prod_eq_single i]
+ · have self (j : Fin (k i)) : encode i y (index k (.inr ⟨i,j⟩)) = y j :=
+ encode_bit_self i y j
+ simp [self]
+ · intro j _ hj
+ have other (z : Fin (k j)) : encode i y (index k (.inr ⟨j,z⟩)) = false :=
+ encode_bit_other hj y z
+ simp [other]
+ · simp
+
+private theorem weightedCNF_eq_sum_subtype {n : ℕ} (φ : CNF n) (w : Fin n → R) :
+ weightedCNF φ w = ∑ x : {x : Fin n → Bool // Satisfies φ x},
+ ∏ j, if x.val j then w j else 1 := by
+ rw [weightedCNF, ← Finset.sum_filter]
+ exact Finset.sum_subtype _ (by simp) _
+
+/-- The polynomial of the selector formula is the sum of the individual polynomials,
+each multiplied by the weight of its selected branch. -/
+theorem weighted_formula (φ : ∀ i, CNF (k i)) (a : I → R) (w : ∀ i, Fin (k i) → R) :
+ weightedCNF (formula φ) (weight k a w) = ∑ i, a i * weightedCNF (φ i) (w i) := by
+ simp only [weightedCNF_eq_sum_subtype, Finset.mul_sum]
+ rw [← (solutions φ).sum_comp (fun x => ∏ j, if x.val j then weight k a w j else 1),
+ Fintype.sum_sigma]
+ apply Finset.sum_congr rfl
+ intro i _
+ exact Finset.sum_congr rfl fun x _ => prod_encode a w i x.val
+
+private theorem literalCount_append {n : ℕ} (a b : CNF n) :
+ literalCount (a ++ b) = literalCount a + literalCount b := by simp [literalCount]
+
+private theorem literalCount_flatMap_le {n : ℕ} {A : Type*} (xs : List A) (f : A → CNF n)
+ (M : ℕ) (h : ∀ i, literalCount (f i) ≤ M) :
+ literalCount (xs.flatMap f) ≤ xs.length * M := by
+ induction xs with
+ | nil => simp [literalCount]
+ | cons a xs ih =>
+ simpa [literalCount_append, Nat.succ_mul, Nat.add_comm] using Nat.add_le_add (h a) ih
+
+private theorem literalCount_guarded_le (φ : ∀ i, CNF (k i)) (i : I) :
+ literalCount (guarded φ i) ≤ 1 + 2 * literalCount (φ i) := by
+ by_cases he : [] ∈ φ i
+ · simp [guarded, he, literalCount]
+ · rw [guarded, ite_eq_right he]
+ generalize hv : φ i = cs at *
+ clear hv
+ induction cs with
+ | nil => simp [literalCount]
+ | cons c cs ih =>
+ have hn : c ≠ [] := by aesop
+ have hp : 0 < c.length := List.length_pos_iff.mpr hn
+ have htail := ih (by aesop)
+ simp only [List.map_cons, literalCount, List.sum_cons, List.length_map, List.length_cons]
+ simp only [literalCount] at htail
+ omega
+
+private theorem literalCount_map_const {A : Type*} {n : ℕ} (xs : List A) (f : A → List (Literal n))
+ (v : ℕ) (hv : ∀ a, (f a).length = v) :
+ literalCount (xs.map f) = xs.length * v := by
+ induction xs with
+ | nil => simp [literalCount]
+ | cons x xs ih => simpa [literalCount, hv, Nat.succ_mul, Nat.add_comm] using ih
+
+/-- A uniform bound in the number of alternatives, the largest block width,
+and the largest literal count. Empty clauses are detected before guarding. -/
+theorem literalCount_formula_le (φ : ∀ i, CNF (k i)) {K L : ℕ}
+ (hk : ∀ i, k i ≤ K) (hl : ∀ i, literalCount (φ i) ≤ L) :
+ literalCount (formula φ) ≤ Fintype.card I +
+ Fintype.card I * (2 * Fintype.card I + 2 * K + 1 + 2 * L) := by
+ rw [formula]
+ change ((allIndices I).map fun i => (flag k i, true)).length + literalCount _ ≤ _
+ simp only [List.length_map, length_allIndices]
+ apply Nat.add_le_add_left
+ refine (literalCount_flatMap_le (allIndices I) _
+ (2 * Fintype.card I + 2 * K + 1 + 2 * L) ?_).trans_eq (by simp)
+ intro i
+ have he : literalCount (exclusive k i) = Fintype.card I * 2 := by
+ rw [exclusive, literalCount_map_const (v := 2) (hv := fun _ => rfl), length_allIndices]
+ have ha : literalCount (inactive k i) = k i * 2 := by
+ rw [inactive, literalCount_map_const (v := 2) (hv := fun _ => rfl), List.length_finRange]
+ simp only [literalCount_append, he, ha]
+ have := literalCount_guarded_le φ i
+ have := hk i
+ have := hl i
+ omega
+
+end HardnessAlternatives
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessCNF.lean b/lean/OAI/Computability/VPVNP/HardnessCNF.lean
new file mode 100644
index 0000000000..d83f4ce24a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessCNF.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.QueryProgram
+import Mathlib.Data.Fintype.Card
+
+/-!
+# Compiling a CNF test into a finite query program
+
+The payload assigns one bit to each Boolean variable. Each occurrence of a literal
+becomes one read state. A matching literal skips the rest of its clause, and an
+exhausted clause goes directly to the rejecting halt.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HardnessCNF
+
+/-- The bit must equal the indicated polarity for this literal to hold. -/
+abbrev Literal (k : ℕ) := Fin k × Bool
+
+/-- A list of clauses over `k` Boolean variables. Each clause is a disjunction of signed
+literals. -/
+abbrev CNF (k : ℕ) := List (List (Literal k))
+
+/-- Number of literal occurrences, counting repetitions within or across clauses. -/
+def literalCount {k : ℕ} (φ : CNF k) : ℕ := (φ.map List.length).sum
+
+/-- An assignment satisfies the formula when every clause contains a literal whose required bit
+matches the assignment. -/
+def Satisfies {k : ℕ} (φ : CNF k) (x : Fin k → Bool) : Prop :=
+ ∀ clause ∈ φ, ∃ l ∈ clause, x l.1 = l.2
+
+variable {k n : ℕ}
+
+/-- The compiler reserves two halting states, then adds one state per literal. -/
+def stateCount : CNF k → ℕ
+ | [] => 2
+ | clause :: φ => stateCount φ + clause.length
+
+/-- The query evaluator has one control state per literal occurrence, in addition to its two
+terminal states. -/
+abbrev State (φ : CNF k) := Fin (stateCount φ)
+
+theorem card_state (φ : CNF k) : Fintype.card (State φ) = 2 + literalCount φ := by
+ rw [Fintype.card_fin]
+ induction φ with
+ | nil => rfl
+ | cons c φ ih => simp [stateCount, literalCount] at ih ⊢; omega
+
+/-- During assembly of a clause, the first matching literal jumps to `pass`
+(the start of the remaining clauses), and exhaustion jumps to `reject`. -/
+private structure Block (k n : ℕ) extends QueryProgram k (Fin n) where
+ pass : Fin n
+ reject : Fin n
+
+private def liftStep : QueryStep k (Fin n) → QueryStep k (Fin (n + 1))
+ | .halt b => .halt b
+ | .read i lo hi => .read i lo.succ hi.succ
+
+private def push (l : Literal k) (b : Block k n) : Block k (n + 1) where
+ start := 0
+ pass := b.pass.succ
+ reject := b.reject.succ
+ step := Fin.cases
+ (.read l.1 (if l.2 then b.start.succ else b.pass.succ)
+ (if l.2 then b.pass.succ else b.start.succ))
+ (fun q => liftStep (b.step q))
+
+/-- Existing states keep their behavior when a new literal is prepended. -/
+private theorem eval_push_succ (l : Literal k) (b : Block k n) (x : Fin k → Bool)
+ (f : ℕ) (q : Fin n) :
+ (push l b).eval x f q.succ = b.eval x f q := by
+ induction f generalizing q with
+ | zero => cases h : b.step q <;> simp [QueryProgram.eval, push, h, liftStep]
+ | succ f ih =>
+ cases h : b.step q with
+ | halt v => simp [QueryProgram.eval, push, h, liftStep]
+ | read i lo hi =>
+ cases hv : x i <;> simpa [QueryProgram.eval, push, h, liftStep, hv] using
+ ih (if x i then hi else lo)
+
+private def compileClause (b : Block k n) : (c : List (Literal k)) → Block k (n + c.length)
+ | [] => { b with start := b.reject, pass := b.start }
+ | l :: c => push l (compileClause b c)
+
+private def compile : (φ : CNF k) → Block k (stateCount φ)
+ | [] => (⟨⟨1, fun q => .halt (q == 1)⟩, 1, 0⟩ : Block k 2)
+ | c :: φ => compileClause (compile φ) c
+
+/-- A query program deciding whether the payload satisfies a CNF. -/
+def query (φ : CNF k) : QueryProgram k (State φ) := (compile φ).toQueryProgram
+
+private structure Correct (b : Block k n) (x : Fin k → Bool) (budget : ℕ)
+ (pass start : Bool) : Prop where
+ reject_ok : ∀ f, budget ≤ f → b.eval x f b.reject = false
+ pass_ok : ∀ f, budget ≤ f → b.eval x f b.pass = pass
+ start_ok : ∀ f, budget ≤ f → b.eval x f b.start = start
+
+private theorem correct_push {b : Block k n} {x : Fin k → Bool} {budget : ℕ}
+ {pass start : Bool} (h : Correct b x budget pass start) (l : Literal k) :
+ Correct (push l b) x (budget + 1) pass (if x l.1 = l.2 then pass else start) := by
+ constructor
+ · intro f hf
+ exact (eval_push_succ l b x f b.reject).trans (h.reject_ok f (by omega))
+ · intro f hf
+ exact (eval_push_succ l b x f b.pass).trans (h.pass_ok f (by omega))
+ · intro f hf
+ obtain ⟨f, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : f ≠ 0)
+ change (push l b).eval x (f + 1) 0 = _
+ rw [QueryProgram.eval]
+ have hp := (eval_push_succ l b x f b.pass).trans (h.pass_ok f (by omega))
+ have hs := (eval_push_succ l b x f b.start).trans (h.start_ok f (by omega))
+ cases h₁ : x l.1 <;> cases h₂ : l.2 <;> simp [push, h₁, h₂] at hp hs ⊢ <;> assumption
+
+private def clauseValue (x : Fin k → Bool) (c : List (Literal k)) : Bool :=
+ c.any (fun l => x l.1 == l.2)
+
+private theorem eval_step_congr {Q : Type*} (p p' : QueryProgram k Q)
+ (h : p.step = p'.step) (x : Fin k → Bool) (f : ℕ) (q : Q) :
+ p.eval x f q = p'.eval x f q := by
+ induction f generalizing q with
+ | zero => simp only [QueryProgram.eval, h]
+ | succ f ih =>
+ simp only [QueryProgram.eval, h]
+ cases p'.step q with
+ | halt v => rfl
+ | read i lo hi => exact ih _
+
+private theorem correct_clause {b : Block k n} {x : Fin k → Bool} {budget : ℕ}
+ {oldPass next : Bool} (h : Correct b x budget oldPass next) (c : List (Literal k)) :
+ Correct (compileClause b c) x (budget + c.length) next (clauseValue x c && next) := by
+ induction c with
+ | nil =>
+ have he (f : ℕ) (q : Fin n) :=
+ eval_step_congr (compileClause b []).toQueryProgram b.toQueryProgram rfl x f q
+ exact ⟨fun f hf => (he f b.reject).trans (h.reject_ok f hf),
+ fun f hf => (he f b.start).trans (h.start_ok f hf),
+ fun f hf => (he f b.reject).trans (h.reject_ok f hf)⟩
+ | cons l c ih =>
+ have h' := correct_push ih l
+ change Correct (push l (compileClause b c)) x (budget + c.length + 1) next _
+ convert h' using 1
+ cases hb : x l.1 <;> cases hl : l.2 <;> simp [clauseValue, hb, hl]
+
+private theorem correct_compile (φ : CNF k) (x : Fin k → Bool) :
+ ∃ pass, Correct (compile φ) x (literalCount φ) pass (φ.all (clauseValue x)) := by
+ induction φ with
+ | nil =>
+ refine ⟨true, ?_⟩
+ constructor <;> intro f _ <;> cases f <;> rfl
+ | cons c φ ih =>
+ obtain ⟨pass, h⟩ := ih
+ refine ⟨φ.all (clauseValue x), ?_⟩
+ have hc := correct_clause h c
+ simpa [compile, stateCount, literalCount, Nat.add_comm] using hc
+
+/-- At most one query per literal is sufficient, including for formulas with
+empty clauses and the empty conjunction. -/
+theorem query_eval_iff (φ : CNF k) (x : Fin k → Bool) {fuel : ℕ}
+ (hf : literalCount φ ≤ fuel) :
+ (query φ).eval x fuel (query φ).start = true ↔ Satisfies φ x := by
+ obtain ⟨_, h⟩ := correct_compile φ x
+ rw [show (query φ).eval x fuel (query φ).start = φ.all (clauseValue x) from h.start_ok _ hf]
+ simp [List.all_eq_true, clauseValue, Satisfies]
+
+end HardnessCNF
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessCircuitRepresentation.lean b/lean/OAI/Computability/VPVNP/HardnessCircuitRepresentation.lean
new file mode 100644
index 0000000000..1302173f83
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessCircuitRepresentation.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.HardnessModel
+import OAI.Computability.VPVNP.HardnessDegrees
+import OAI.Computability.VPVNP.ParseEventWeightedCNF
+
+/-!
+# A weighted CNF representation for every VP family
+
+The positive homogeneous components of a polynomial computed by a circuit are
+generated by the graded parse table. A satisfying incidence assignment chooses
+exactly one ordered parse. Its selected coordinates carry the rule scalars and
+the terminal variable labels. A selector joins these formulas and the constant
+term into one CNF of polynomial width and literal count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Hardness
+
+open MvPolynomial ParseGrammar HardnessCNF
+open scoped Classical
+
+variable {F V : Type*} [Field F] [Fintype V]
+
+/-- Number of Boolean occurrence coordinates for one homogeneous parse. -/
+private noncomputable def eventWidth (p : MvPolynomial V F) : ℕ :=
+ Fintype.card (EventCode V (Circuit.GrammarSlots V (circuitSize p)) p.totalDegree)
+
+/-- The absent degree selects the scalar term, with a single empty assignment. -/
+private noncomputable def layer (p : MvPolynomial V F) :
+ Option (Fin p.totalDegree) → MarkedCNF F V
+ | none => MarkedCNF.unit F V
+ | some d =>
+ let e := EventCode.enumerate V (Circuit.GrammarSlots V (circuitSize p)) p.totalDegree
+ ⟨eventWidth p, incidenceCNF e 0 d.val none, fun i => (grammarFor p).eventScalar (e i),
+ fun i => (e i).leafVariable?⟩
+
+private theorem value_layer_some (p : MvPolynomial V F) (d : Fin p.totalDegree) :
+ (layer p (some d)).value = (grammarFor p).eval d none :=
+ ((grammarFor p).eval_eq_weightedCNF d none).symm
+
+private theorem width_layer_le (p : MvPolynomial V F) (d : Option (Fin p.totalDegree)) :
+ (layer p d).width ≤ eventWidth p := by
+ cases d
+ · exact Nat.zero_le _
+ · rfl
+
+private theorem literalCount_layer_le (p : MvPolynomial V F) (d : Option (Fin p.totalDegree)) :
+ literalCount (layer p d).clauses ≤ eventWidth p + eventWidth p * (5 * eventWidth p + 4) := by
+ cases d with
+ | none => exact Nat.zero_le _
+ | some d => exact literalCount_incidenceCNF_le _ _ _ _
+
+/-- A single formula encodes every homogeneous component and the scalar term. -/
+private noncomputable def circuitModel (p : MvPolynomial V F) : MarkedCNF F V :=
+ MarkedCNF.linearCombination (fun d : Option (Fin p.totalDegree) => d.elim p.constantCoeff (fun _ => 1))
+ (layer p)
+
+private theorem value_circuitModel (p : MvPolynomial V F) : (circuitModel p).value = p := by
+ rw [circuitModel, MarkedCNF.value_linearCombination, Fintype.sum_option]
+ simp only [Option.elim_none, Option.elim_some, map_one, one_mul, value_layer_some,
+ show layer p none = MarkedCNF.unit F V from rfl, MarkedCNF.value_unit, mul_one]
+ exact (polynomial_eq_constant_add_grammar p).symm
+
+/-- Polynomially bounded circuit size, formal degree and variable count suffice
+for a single scalar-and-variable-labelled CNF at each family length. -/
+theorem exists_markedCNF_of_isVP {V : ℕ → Type} [∀ n, Fintype (V n)]
+ (g : Family F V) (hg : IsVP g) :
+ ∃ m : ∀ n, MarkedCNF F (V n),
+ PolynomiallyBounded (fun n => (m n).width) ∧
+ PolynomiallyBounded (fun n => literalCount (m n).clauses) ∧
+ ∀ n, (m n).value = g n := by
+ obtain ⟨hd, hs⟩ := grammar_bounds_of_isVP hg
+ have hk : PolynomiallyBounded fun n => eventWidth (g n) := by
+ simp only [eventWidth, EventCode.card]
+ exact ((hd.mul hd).mul hs).mul (hg.1.1.add ((hd.mul hs).mul hs))
+ have hl := hk.add (hk.mul (((PolynomiallyBounded.const 5).mul hk).add (.const 4)))
+ have hc : PolynomiallyBounded fun n => Fintype.card (Option (Fin (g n).totalDegree)) := by
+ simpa using hd.add (.const 1)
+ refine ⟨fun n => circuitModel (g n), ?_, ?_, fun n => value_circuitModel _⟩
+ · exact (hc.mul ((PolynomiallyBounded.const 1).add hk)).of_le
+ fun n => HardnessAlternatives.width_le (width_layer_le (g n))
+ · have hbody := (((PolynomiallyBounded.const 2).mul hc).add
+ ((PolynomiallyBounded.const 2).mul hk)).add (.const 1)
+ exact (hc.add (hc.mul (hbody.add ((PolynomiallyBounded.const 2).mul hl)))).of_le fun n =>
+ HardnessAlternatives.literalCount_formula_le (fun i => (layer (g n) i).clauses)
+ (width_layer_le (g n)) (literalCount_layer_le (g n))
+
+end Hardness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessDegrees.lean b/lean/OAI/Computability/VPVNP/HardnessDegrees.lean
new file mode 100644
index 0000000000..e340becbd6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessDegrees.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.CircuitGrammar
+import OAI.Computability.VPVNP.PolynomialBounds
+
+/-!
+# Assembling the homogeneous parse layers
+
+The graded grammar of §8.1 represents the positive-degree pieces of a circuit.
+Its scalar output at degree zero must also be retained when expanding a general
+VNP witness summand. The number of grammar states uses the variables and the
+binary gates of the exact circuit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Hardness
+
+open MvPolynomial
+open scoped Classical
+
+variable {V : Type*} {F : Type*} [Field F]
+
+/-- The constant term plus all positive homogeneous components recover the formal polynomial. -/
+theorem eq_constant_add_positive_components (p : MvPolynomial V F) :
+ p = C p.constantCoeff +
+ ∑ d : Fin p.totalDegree, homogeneousComponent (d.val + 1) p := by
+ rw [Fin.sum_univ_eq_sum_range (fun i => homogeneousComponent (i + 1) p), add_comm]
+ simpa only [Finset.sum_range_succ', homogeneousComponent_zero, constantCoeff_eq]
+ using (sum_homogeneousComponent p).symm
+
+variable [Fintype V]
+
+/-- Choose a single table of labels from an exact circuit of minimum size. -/
+noncomputable def grammarFor (p : MvPolynomial V F) :
+ ParseGrammar F V (Circuit.GrammarSlots V (circuitSize p)) p.totalDegree :=
+ ((circuitSize_spec p).choose.exists_parseGrammar p.totalDegree).choose
+
+theorem eval_grammarFor (p : MvPolynomial V F) (d : Fin p.totalDegree) :
+ (grammarFor p).eval d none = homogeneousComponent (d.val + 1) p := by
+ rw [grammarFor, ((circuitSize_spec p).choose.exists_parseGrammar p.totalDegree).choose_spec d,
+ (circuitSize_spec p).choose_spec]
+
+theorem polynomial_eq_constant_add_grammar (p : MvPolynomial V F) :
+ p = C p.constantCoeff + ∑ d : Fin p.totalDegree, (grammarFor p).eval d none := by
+ simp only [eval_grammarFor]
+ exact eq_constant_add_positive_components p
+
+variable {X W : Type} [Fintype X] [Fintype W]
+
+/-- Under witness specialization, a leaf either contributes a visible variable or
+the field constant zero or one selected by the witness bit. -/
+noncomputable def leafValue (y : W → Bool) : X ⊕ W → MvPolynomial X F :=
+ Sum.elim MvPolynomial.X (fun i => C (if y i then 1 else 0))
+
+/-- The exact specialization at any witness, as a sum of scalar-weighted ordered parses. -/
+theorem witnessValue_eq_constant_add_parses (p : MvPolynomial (X ⊕ W) F) (y : W → Bool) :
+ witnessValue y p = C p.constantCoeff + ∑ d : Fin p.totalDegree,
+ ∑ t : ParseGrammar.OrderedParse (X ⊕ W) (Circuit.GrammarSlots (X ⊕ W) (circuitSize p)) d.val,
+ C ((grammarFor p).weight d none t) * (t.leaves.map (leafValue y)).prod := by
+ conv_lhs => rw [polynomial_eq_constant_add_grammar p]
+ rw [map_add, map_sum]
+ simp only [witnessValue, eval₂Hom_C]
+ apply congrArg (_ + ·)
+ apply Finset.sum_congr rfl
+ intro d _
+ exact (grammarFor p).eval₂_eq_sum C (leafValue y) d none
+
+/-- A VP summand supplies polynomial bounds on both the number of positive layers
+and the number of states, even when the intermediate circuit degrees are much larger. -/
+theorem grammar_bounds_of_isVP {σ : ℕ → Type} [∀ n, Fintype (σ n)]
+ {p : Family F σ} (hp : IsVP p) :
+ PolynomiallyBounded (fun n => (p n).totalDegree) ∧
+ PolynomiallyBounded (fun n => Fintype.card (Circuit.GrammarSlots (σ n) (circuitSize (p n)))) := by
+ refine ⟨hp.1.2, ?_⟩
+ simp only [Circuit.card_grammarSlots]
+ exact (hp.1.1.add hp.2).add (.const 1)
+
+end Hardness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessModel.lean b/lean/OAI/Computability/VPVNP/HardnessModel.lean
new file mode 100644
index 0000000000..930f12f5ff
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessModel.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.HardnessWeights
+import OAI.Computability.VPVNP.HardnessAlternatives
+
+/-!
+# Boolean formulas with scalar and variable labels
+
+Each selected bit contributes a scalar and, optionally, a single formal
+variable. The accepted assignments of the formula index a sum of monomials.
+Selector bits implement finite scalar linear combinations of these sums.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Hardness
+
+open MvPolynomial HardnessCNF
+open scoped Classical
+
+/-- A Boolean formula whose true variables contribute a scalar and, optionally, a polynomial
+variable to the weight of an assignment. -/
+structure MarkedCNF (F V : Type*) where
+ /-- Number of Boolean variables in the marked formula. -/
+ width : ℕ
+ /-- The clauses selecting the assignments whose weights enter the polynomial. -/
+ clauses : CNF width
+ /-- Coefficient factor contributed when a given Boolean variable is true. -/
+ scalar : Fin width → F
+ /-- Optional polynomial variable contributed when a given Boolean variable is true. -/
+ label : Fin width → Option V
+
+namespace MarkedCNF
+
+variable {F V : Type*} [CommSemiring F]
+
+/-- The formal polynomial specified by the selected scalar and variable labels. -/
+noncomputable def value (m : MarkedCNF F V) : MvPolynomial V F :=
+ weightedCNF m.clauses (fun i => C (m.scalar i) * (m.label i).elim 1 X)
+
+/-- The empty CNF with no Boolean variables has a single assignment of weight one. -/
+def unit (F V : Type*) : MarkedCNF F V := ⟨0, [], Fin.elim0, Fin.elim0⟩
+
+@[simp] theorem value_unit : (unit F V).value = 1 := by
+ have hs (x : Fin 0 → Bool) : Satisfies [] x := fun _ h => nomatch h
+ have hp (x : Fin 0 → Bool) :
+ (∏ i : Fin 0, if x i then C (i.elim0 : F) * (i.elim0 : Option V).elim 1 X else 1) = 1 :=
+ Finset.prod_eq_one fun i _ => i.elim0
+ change weightedCNF ([] : CNF 0)
+ (fun i => C (i.elim0 : F) * (i.elim0 : Option V).elim 1 X) = 1
+ simp only [weightedCNF, hs, ite_true, hp]
+ simp
+
+variable {I : Type*} [Fintype I]
+
+/-- The selector for a summand carries that summand's scalar. All data bits
+retain the scalar and optional variable of the corresponding private block. -/
+noncomputable def linearCombination (a : I → F) (m : I → MarkedCNF F V) :
+ MarkedCNF F V where
+ width := HardnessAlternatives.width (fun i => (m i).width)
+ clauses := HardnessAlternatives.formula (fun i => (m i).clauses)
+ scalar := HardnessAlternatives.weight _ a (fun i => (m i).scalar)
+ label := HardnessAlternatives.weight _ (fun _ => none) (fun i => (m i).label)
+
+theorem value_linearCombination (a : I → F) (m : I → MarkedCNF F V) :
+ (linearCombination a m).value = ∑ i, C (a i) * (m i).value := by
+ let k := fun i => (m i).width
+ have hweight (j : Fin (HardnessAlternatives.width k)) :
+ C ((linearCombination a m).scalar j) *
+ ((linearCombination a m).label j).elim 1 X =
+ HardnessAlternatives.weight k (fun i => C (a i))
+ (fun i j => C ((m i).scalar j) * ((m i).label j).elim 1 X) j := by
+ obtain ⟨s, rfl⟩ := (HardnessAlternatives.index k).surjective j
+ rcases s with i | ⟨i, j⟩ <;> simp [linearCombination, k]
+ change weightedCNF (HardnessAlternatives.formula fun i => (m i).clauses)
+ (fun j => C ((linearCombination a m).scalar j) *
+ ((linearCombination a m).label j).elim 1 X) = _
+ rw [funext hweight]
+ exact HardnessAlternatives.weighted_formula (fun i => (m i).clauses) (fun i => C (a i))
+ (fun i j => C ((m i).scalar j) * ((m i).label j).elim 1 X)
+
+end MarkedCNF
+end Hardness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessQuery.lean b/lean/OAI/Computability/VPVNP/HardnessQuery.lean
new file mode 100644
index 0000000000..1ba1b5917f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessQuery.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.QueryPrefix
+import OAI.Computability.VPVNP.Pinning
+import OAI.Computability.VPVNP.PolynomialBounds
+import OAI.Computability.VPVNP.ProjectionComposition
+
+/-!
+# Weighted Boolean predicates as projections of the universal family
+
+A finite query program reads the bits of a proposed assignment. Each selected
+bit contributes its assigned weight, which may be a scalar or a formal variable.
+Pinning the literal program prefix and projecting the payload gives the sum of
+those products over the accepted assignments, in every characteristic.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+variable {R τ : Type*} [CommRing R] {k : ℕ}
+
+/-- The formal generating polynomial of a Boolean predicate with variable or scalar weights. -/
+noncomputable def weightedPredicate (accept : (Fin k → Bool) → Bool)
+ (weight : Projection R (Fin k) τ) : MvPolynomial τ R :=
+ ∑ x, if accept x then ∏ i, if x i then (weight i).elim X C else 1 else 0
+
+theorem weightedPredicate_eq_projection (accept : (Fin k → Bool) → Bool)
+ (weight : Projection R (Fin k) τ) :
+ weight.hom (booleanPolynomial fun x => ((accept x).toNat : R)) =
+ weightedPredicate accept weight := by
+ classical
+ simp only [Projection.hom, booleanPolynomial, weightedPredicate, map_sum, map_mul,
+ map_prod, eval₂Hom_C, apply_ite, eval₂Hom_X', map_one]
+ apply Finset.sum_congr rfl
+ intro x _
+ cases h : accept x <;> simp
+
+/-- For a single weighted query program the source length is bounded explicitly
+in its state count, query budget, and payload length. -/
+theorem weightedQuery_projection {Q : Type*} [Fintype Q] (q : QueryProgram k Q)
+ (fuel : ℕ) (weight : Projection R (Fin k) τ) :
+ ∃ n, n ≤ 1000 * ((fuel + 1) * Fintype.card Q * (k + 1) + 1) ^ 2 + k ∧
+ ∃ φ : Projection R (Fin n × Bool) τ,
+ φ.hom (MvPolynomial.map (Int.castRingHom R) (P n)) =
+ weightedPredicate (fun x => q.eval x fuel q.start) weight := by
+ obtain ⟨l, bits, hsize, hcount⟩ := QueryMachine.exists_prefix q fuel
+ let pin := pinVariables (R := R) bits (Equiv.refl (Fin k))
+ have hp : pin.hom (MvPolynomial.map (Int.castRingHom R) (P (l + k))) =
+ booleanPolynomial (fun x => ((q.eval x fuel q.start).toNat : R)) := by
+ rw [map_P]
+ apply pairedPolynomial_pin
+ intro x
+ exact congrArg (fun b : ℕ => (b : R)) (hcount x)
+ refine ⟨l + k, Nat.add_le_add_right hsize k, weight.comp pin, ?_⟩
+ rw [Projection.hom_comp, RingHom.comp_apply, hp, weightedPredicate_eq_projection]
+
+/-- A polynomial-size family of query predicates gives one p-projection, including
+all the finite initial lengths. Weights may be chosen independently at each length. -/
+theorem weightedQuery_PProjects {F : Type*} [Field F] {τ : ℕ → Type}
+ {k fuel : ℕ → ℕ} {Q : ℕ → Type} [∀ n, Fintype (Q n)]
+ (q : ∀ n, QueryProgram (k n) (Q n)) (weights : ∀ n, Projection F (Fin (k n)) (τ n))
+ (hk : PolynomiallyBounded k) (hf : PolynomiallyBounded fuel)
+ (hq : PolynomiallyBounded fun n => Fintype.card (Q n)) :
+ PProjects (fun n => weightedPredicate (fun x => (q n).eval x (fuel n) (q n).start) (weights n))
+ (fun n => MvPolynomial.map (Int.castRingHom F) (P n)) := by
+ choose r hr φ hφ using fun n => weightedQuery_projection (q n) (fuel n) (weights n)
+ refine ⟨r, ?_, fun n => ⟨φ n, hφ n⟩⟩
+ have hcontrols := ((hf.add (.const 1)).mul hq).mul (hk.add (.const 1))
+ exact (((PolynomiallyBounded.const 1000).mul ((hcontrols.add (.const 1)).pow 2)).add hk).of_le hr
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessWeights.lean b/lean/OAI/Computability/VPVNP/HardnessWeights.lean
new file mode 100644
index 0000000000..0ce8d6a110
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessWeights.lean
@@ -0,0 +1,49 @@
+import OAI.Computability.VPVNP.HardnessCNF
+import OAI.Computability.VPVNP.HardnessQuery
+
+/-!
+# Generating polynomials of satisfying assignments
+
+Weights may live in any commutative semiring. When each weight is a variable or
+a scalar, the literal CNF test realizes this polynomial by a projection of the
+universal integer family. Its source index is polynomial when the number of
+Boolean variables and the total number of literals are polynomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HardnessCNF
+
+open MvPolynomial
+open scoped Classical
+
+/-- Sum of assignment weights over the satisfying assignments of a CNF. -/
+noncomputable def weightedCNF {R : Type*} [CommSemiring R] {k : ℕ}
+ (φ : CNF k) (weight : Fin k → R) : R :=
+ ∑ x, if Satisfies φ x then ∏ i, if x i then weight i else 1 else 0
+
+theorem weightedCNF_eq_query {R τ : Type*} [CommRing R] {k : ℕ}
+ (φ : CNF k) (weight : Projection R (Fin k) τ) :
+ weightedCNF φ (fun i => (weight i).elim X C) =
+ weightedPredicate (fun x => (query φ).eval x (literalCount φ) (query φ).start) weight := by
+ unfold weightedPredicate weightedCNF
+ apply Finset.sum_congr rfl
+ intro x _
+ simp only [query_eval_iff φ x le_rfl]
+
+theorem weightedCNF_PProjects {F : Type*} [Field F] {τ : ℕ → Type} {k : ℕ → ℕ}
+ (φ : ∀ n, CNF (k n)) (weights : ∀ n, Projection F (Fin (k n)) (τ n))
+ (hk : PolynomiallyBounded k) (hsize : PolynomiallyBounded fun n => literalCount (φ n)) :
+ PProjects (fun n => weightedCNF (φ n) (fun i => (weights n i).elim X C))
+ (fun n => MvPolynomial.map (Int.castRingHom F) (P n)) := by
+ simp_rw [weightedCNF_eq_query]
+ apply weightedQuery_PProjects (hk := hk) (hf := hsize)
+ simpa only [card_state] using (PolynomiallyBounded.const 2).add hsize
+
+end HardnessCNF
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessWitness.lean b/lean/OAI/Computability/VPVNP/HardnessWitness.lean
new file mode 100644
index 0000000000..66f4d1c0b9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessWitness.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.HardnessWeights
+import OAI.Computability.VPVNP.HardnessWitnessCNF
+import OAI.Computability.VPVNP.HardnessWitnessMonomial
+
+/-!
+# Eliminating Boolean witness substitutions in a weighted CNF
+
+A selected flag can carry both a scalar and a variable. Its duplicate in the
+augmented formula accounts for the variable while the original carries the scalar.
+For a witness variable the added implication excludes precisely the assignments
+where that variable specializes to zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HardnessWitness
+
+open HardnessCNF
+open scoped Classical
+variable {k : ℕ} {F : Type*} {X W : Type} [Field F] [Fintype W]
+
+/-- Projection weights on the three blocks of bits. An original flag carries
+its scalar, its duplicate carries its formal variable, and the witness is unweighted. -/
+noncomputable def augmentedWeight (a : Fin k → F) (tag : Fin k → Option (X ⊕ W)) :
+ Projection F (Fin (width k W)) X := fun j =>
+ Sum.elim (fun i => .inr (a i))
+ (Sum.elim (fun i => variableWeight (F := F) (tag i)) (fun _ => .inr 1))
+ ((slots k W).symm j)
+
+/-- Reindex a payload assignment by its witness, flags, and copies of the flags. -/
+private noncomputable def assignments (k : ℕ) (W : Type) [Fintype W] :
+ ((W → Bool) × (Fin k → Bool) × (Fin k → Bool)) ≃ (Fin (width k W) → Bool) where
+ toFun s j := Sum.elim s.2.1 (Sum.elim s.2.2 s.1) ((slots k W).symm j)
+ invFun z := (fun w => z (slots k W (.inr (.inr w))), fun i => z (slots k W (.inl i)),
+ fun i => z (slots k W (.inr (.inl i))))
+ left_inv s := by ext <;> simp
+ right_inv z := by
+ funext j
+ obtain ⟨u, rfl⟩ := (slots k W).surjective j
+ rcases u with i | i | w <;> simp
+
+private theorem satisfies_assignment (φ : CNF k) (tag : Fin k → Option (X ⊕ W))
+ (y : W → Bool) (x z : Fin k → Bool) :
+ Satisfies (augment φ tag) (assignments k W (y, x, z)) ↔
+ Satisfies φ x ∧ z = x ∧ Compatible tag x y := by
+ rw [satisfies_augment]
+ simp only [assignments, Equiv.coe_fn_mk, Equiv.symm_apply_apply, Sum.elim_inl, Sum.elim_inr]
+ rw [funext_iff]
+
+private theorem prod_assignment (a : Fin k → F) (tag : Fin k → Option (X ⊕ W))
+ (y : W → Bool) (x z : Fin k → Bool) :
+ (∏ i, if assignments k W (y, x, z) i then
+ (augmentedWeight a tag i).elim MvPolynomial.X MvPolynomial.C else 1) =
+ (∏ i, if x i then MvPolynomial.C (a i) else 1) *
+ (∏ i, if z i then (variableWeight (F := F) (tag i)).elim MvPolynomial.X MvPolynomial.C else 1) := by
+ classical
+ rw [← (slots k W).prod_comp (fun i => if assignments k W (y, x, z) i then
+ (augmentedWeight a tag i).elim MvPolynomial.X MvPolynomial.C else 1)]
+ have hw : (∏ w : W, if y w then (1 : MvPolynomial X F) else 1) = 1 :=
+ Finset.prod_eq_one fun w _ => by cases y w <;> rfl
+ simp [Fintype.prod_sum_type, assignments, augmentedWeight]
+ erw [hw, mul_one]
+ rfl
+
+/-- After summing the Boolean witnesses, a product with one scalar and one
+optional variable per selected flag has a CNF presentation with projection weights. -/
+theorem sum_witnessValue_weightedCNF (φ : CNF k) (a : Fin k → F) (tag : Fin k → Option (X ⊕ W)) :
+ ∑ y : W → Bool, witnessValue y (weightedCNF φ (fun i => monomial (a i) (tag i))) =
+ weightedCNF (augment φ tag) (fun i => (augmentedWeight a tag i).elim MvPolynomial.X MvPolynomial.C) := by
+ classical
+ unfold weightedCNF
+ simp only [map_sum, apply_ite, map_zero]
+ rw [← (assignments k W).sum_comp (fun b => if Satisfies (augment φ tag) b then
+ ∏ i, if b i then (augmentedWeight a tag i).elim MvPolynomial.X MvPolynomial.C else 1 else 0)]
+ simp only [Fintype.sum_prod_type, satisfies_assignment, prod_assignment]
+ apply Finset.sum_congr rfl
+ intro y _
+ apply Finset.sum_congr rfl
+ intro x _
+ rw [Finset.sum_eq_single x]
+ · by_cases hs : Satisfies φ x
+ · simp only [hs, ite_true, eq_self, true_and, Compatible]
+ refine (witnessValue_prod_monomial a tag x y).trans ?_
+ congr 1
+ · simp [hs]
+ · intro z _ hz
+ simp [hz]
+ · simp
+
+end HardnessWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessWitnessCNF.lean b/lean/OAI/Computability/VPVNP/HardnessWitnessCNF.lean
new file mode 100644
index 0000000000..44e776b3bd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessWitnessCNF.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.HardnessCNF
+import Mathlib.Data.Fintype.EquivFin
+import Mathlib.Data.Fintype.Sum
+
+/-! # Copying selection flags and testing witness bits
+
+The augmented formula contains the original selection flags, a second copy of
+each flag and one bit per witness variable. Each selected event labelled by a
+witness variable forces the corresponding witness bit to be true.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HardnessWitness
+
+open HardnessCNF
+
+/-- The augmented formula has the original `k` flags, their `k` copies, and one Boolean
+variable for each witness coordinate. -/
+def width (k : ℕ) (W : Type*) [Fintype W] := k + (k + Fintype.card W)
+
+/-- The three disjoint blocks of Boolean slots. -/
+noncomputable def slots (k : ℕ) (W : Type*) [Fintype W] :
+ (Fin k ⊕ (Fin k ⊕ W)) ≃ Fin (width k W) :=
+ Fintype.equivFinOfCardEq (by simp [width])
+
+variable {k : ℕ} {X W : Type*} [Fintype W]
+
+private def relabel {k m : ℕ} (f : Fin k → Fin m) (φ : CNF k) : CNF m :=
+ φ.map fun c => c.map fun p => (f p.1, p.2)
+
+private noncomputable def flagClauses (i : Fin k) (tag : Option (X ⊕ W)) : CNF (width k W) :=
+ let a := slots k W (.inl i)
+ let b := slots k W (.inr (.inl i))
+ [[(a, false), (b, true)], [(b, false), (a, true)]] ++
+ match tag with
+ | some (.inr w) => [[(a, false), (slots k W (.inr (.inr w)), true)]]
+ | _ => []
+
+/-- Lift all original clauses, constrain the copied flags, and add witness implications. -/
+noncomputable def augment (φ : CNF k) (tag : Fin k → Option (X ⊕ W)) : CNF (width k W) :=
+ relabel (fun i => slots k W (.inl i)) φ ++
+ (List.finRange k).flatMap (fun i => flagClauses i (tag i))
+
+/-- Each selected flag with a witness label has a true bit for its label. -/
+def Compatible (tag : Fin k → Option (X ⊕ W)) (x : Fin k → Bool) (y : W → Bool) : Prop :=
+ ∀ i w, x i = true → tag i = some (.inr w) → y w = true
+
+private theorem satisfies_relabel {k m : ℕ} (f : Fin k → Fin m) (φ : CNF k) (z : Fin m → Bool) :
+ Satisfies (relabel f φ) z ↔ Satisfies φ (fun i => z (f i)) := by
+ simp [Satisfies, relabel]
+
+private theorem satisfies_flagClauses (i : Fin k) (tag : Option (X ⊕ W))
+ (z : Fin (width k W) → Bool) : Satisfies (flagClauses i tag) z ↔
+ z (slots k W (.inr (.inl i))) = z (slots k W (.inl i)) ∧
+ (∀ w, z (slots k W (.inl i)) = true → tag = some (.inr w) →
+ z (slots k W (.inr (.inr w))) = true) := by
+ rcases tag with _ | v | w <;>
+ cases hx : z (slots k W (.inl i)) <;> cases hb : z (slots k W (.inr (.inl i))) <;>
+ simp only [flagClauses, List.cons_append, List.nil_append, Satisfies, List.forall_mem_cons] <;>
+ simp [hx, hb]
+
+/-- Satisfiability of the augmented formula separates into the original clauses,
+equality of every copy with its flag, and the witness implications. -/
+theorem satisfies_augment (φ : CNF k) (tag : Fin k → Option (X ⊕ W))
+ (z : Fin (width k W) → Bool) :
+ Satisfies (augment φ tag) z ↔
+ Satisfies φ (fun i => z (slots k W (.inl i))) ∧
+ (∀ i, z (slots k W (.inr (.inl i))) = z (slots k W (.inl i))) ∧
+ Compatible tag (fun i => z (slots k W (.inl i))) (fun w => z (slots k W (.inr (.inr w)))) := by
+ have split : Satisfies (augment φ tag) z ↔
+ Satisfies (relabel (fun i => slots k W (.inl i)) φ) z ∧
+ ∀ i, Satisfies (flagClauses i (tag i)) z := by
+ simp only [augment, Satisfies, List.mem_append, List.mem_flatMap, List.mem_finRange,
+ true_and]
+ aesop
+ rw [split, satisfies_relabel]
+ simp only [satisfies_flagClauses, forall_and, Compatible]
+
+private theorem literalCount_relabel {m : ℕ} (f : Fin k → Fin m) (φ : CNF k) :
+ literalCount (relabel f φ) = literalCount φ := by
+ simp [relabel, literalCount, List.map_map, Function.comp_def]
+
+private theorem literalCount_flagClauses_le (i : Fin k) (t : Option (X ⊕ W)) :
+ literalCount (flagClauses i t) ≤ 6 := by
+ cases t with
+ | none => simp [flagClauses, literalCount]
+ | some e => cases e <;> simp [flagClauses, literalCount]
+
+private theorem literalCount_flags_le (is : List (Fin k)) (tag : Fin k → Option (X ⊕ W)) :
+ literalCount (is.flatMap (fun i => flagClauses i (tag i))) ≤ 6 * is.length := by
+ induction is with
+ | nil => simp [literalCount]
+ | cons i is ih =>
+ have h := Nat.add_le_add (literalCount_flagClauses_le i (tag i)) ih
+ simpa [literalCount, Nat.mul_succ, Nat.add_comm] using h
+
+/-- Each original flag contributes at most six literals to the augmented CNF. -/
+theorem literalCount_augment_le (φ : CNF k) (tag : Fin k → Option (X ⊕ W)) :
+ literalCount (augment φ tag) ≤ literalCount φ + 6 * k := by
+ have hadd (a b : CNF (width k W)) : literalCount (a ++ b) = literalCount a + literalCount b := by
+ simp [literalCount]
+ rw [augment, hadd, literalCount_relabel]
+ exact Nat.add_le_add_left (by simpa using literalCount_flags_le (List.finRange k) tag) _
+
+end HardnessWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/HardnessWitnessMonomial.lean b/lean/OAI/Computability/VPVNP/HardnessWitnessMonomial.lean
new file mode 100644
index 0000000000..c30c17bfda
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/HardnessWitnessMonomial.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.Classes
+
+/-! # Specializing the selected monomials at a Boolean witness
+
+A selected scalar may be labelled by one output variable or one witness variable.
+After specialization, a selected witness label contributes zero if its bit is false
+and one if it is true. The output-variable labels survive as formal variables.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HardnessWitness
+
+open scoped Classical
+open MvPolynomial
+
+/-- A scalar, optionally multiplied by one labelled variable. -/
+noncomputable def monomial {F V : Type*} [Field F] (a : F) (t : Option V) :
+ MvPolynomial V F := C a * t.elim 1 X
+
+/-- The formal variable retained by a compatible label, or the constant one. -/
+def variableWeight {F X W : Type*} [Field F] : Option (X ⊕ W) → X ⊕ F
+ | some (.inl v) => .inl v
+ | some (.inr _) | none => .inr 1
+
+private theorem witnessValue_monomial {F : Type*} [Field F] {X W : Type}
+ (a : F) (t : Option (X ⊕ W)) (y : W → Bool)
+ (h : ∀ w, t = some (.inr w) → y w = true) :
+ witnessValue y (monomial a t) = C a * (variableWeight (F := F) t).elim MvPolynomial.X C := by
+ rcases t with _ | (v | w) <;> simp_all [monomial, witnessValue, variableWeight]
+
+/-- A false selected witness variable annihilates the product. Otherwise the
+product factors into the selected scalars and the selected output variables. -/
+theorem witnessValue_prod_monomial {F : Type*} [Field F] {X W : Type} {k : ℕ}
+ (a : Fin k → F) (tag : Fin k → Option (X ⊕ W)) (x : Fin k → Bool) (y : W → Bool) :
+ witnessValue y (∏ i, if x i then monomial (a i) (tag i) else 1) =
+ if (∀ i w, x i = true → tag i = some (.inr w) → y w = true) then
+ (∏ i, if x i then C (a i) else 1) *
+ (∏ i, if x i then (variableWeight (F := F) (tag i)).elim MvPolynomial.X C else 1)
+ else 0 := by
+ rw [map_prod]
+ split_ifs with compatible
+ · rw [← Finset.prod_mul_distrib]
+ apply Finset.prod_congr rfl
+ intro i _
+ cases hi : x i with
+ | false => simp
+ | true => simpa [hi] using witnessValue_monomial (a i) (tag i) y (fun w => compatible i w hi)
+ · push Not at compatible
+ obtain ⟨i, w, hi, ht, hw⟩ := compatible
+ apply Finset.prod_eq_zero (Finset.mem_univ i)
+ simp [hi, ht, hw, monomial, witnessValue]
+
+end HardnessWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IncidenceColumn.lean b/lean/OAI/Computability/VPVNP/IncidenceColumn.lean
new file mode 100644
index 0000000000..4c4f1ffccd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IncidenceColumn.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.IncidenceControl
+
+/-!
+# Reading a column of the exact-one incidence matrix
+
+On a pass for row `r`, the column parser increases its capped tally precisely when
+the column is selected and its incidence bit for row `r` is set. The scan consumes
+one tick per encoded bit and leaves the head at the following tag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace IncidenceMachine
+
+open UniversalMachine TableCompiler QueryTape
+
+/-- The count after reading the first `j` row bits of one column. -/
+private def partialCount {m : ℕ} (c : Column m) (r : Fin m) (n j : ℕ) : ℕ :=
+ if r.val < j then n + (c.1 && c.2 r).toNat else n
+
+private theorem readBit {m : ℕ} (c : Column m) (r j : Fin m) (n : ℕ) :
+ (if j = r ∧ c.1 = true ∧ (if c.2 j then (2 : Symbol) else 1) = 2 then
+ tally ((tally (partialCount c r n j.val)).val + 1)
+ else tally (partialCount c r n j.val)) = tally (partialCount c r n (j.val + 1)) := by
+ by_cases hj : j = r
+ · subst j
+ cases hs : c.1 <;> cases hb : c.2 r <;> simp [partialCount, hs, hb, tally_succ]
+ · have hne : j.val ≠ r.val := fun h => hj (Fin.ext h)
+ have hlt : r.val < j.val + 1 ↔ r.val < j.val := by omega
+ simp [partialCount, hj, hlt]
+
+private theorem bitHead {m : ℕ} (input : Word) (base : ℕ) (c : Column m)
+ (h : ReadsLeft input base (columnBits c)) (j : Fin m) :
+ (atPosition input (base + (m - j.val))).head = if c.2 j then 2 else 1 := by
+ have hi : j.val + 2 < (columnBits c).length := by simp [columnBits]
+ have hj := h (j.val + 2) hi
+ simp [columnBits] at hj
+ simpa [show base + (m + 1 + 1) - (j.val + 2) = base + (m - j.val) by omega] using hj
+
+/-- Starting at row bit `j`, read the rest of the column and return to the tag state. -/
+private theorem scanColumnBits {m : ℕ} (input : Word) (base : ℕ) (c : Column m)
+ (r j : Fin m) (n fuel : ℕ) (h : ReadsLeft input base (columnBits c)) :
+ countAt m input (base + (m - j.val))
+ (.bit r j c.1 (tally (partialCount c r n j.val))) ((m - j.val) + fuel) =
+ countAt m input base (.tag r (tally (n + (c.1 && c.2 r).toNat))) fuel := by
+ let rem := m - (j.val + 1)
+ have hpos : base + (m - j.val) = (base + rem) + 1 := by dsimp [rem]; omega
+ have htime : (m - j.val) + fuel = (rem + fuel) + 1 := by dsimp [rem]; omega
+ have hs := bitHead input base c h j
+ rw [hpos] at hs
+ rw [hpos, htime]
+ by_cases hj : j.val + 1 < m
+ · let next : Fin m := ⟨j.val + 1, hj⟩
+ refine (countAt_left (next := .bit r next c.1 (tally (partialCount c r n next.val))) ?_).trans
+ (scanColumnBits input base c r next n fuel h)
+ rw [hs]
+ simp only [command, hj, dite_true, readBit, next]
+ · have hm : j.val + 1 = m := by omega
+ have hz : rem = 0 := by simp [rem, hm]
+ simp only [hz, Nat.add_zero, Nat.zero_add] at hs ⊢
+ apply countAt_left
+ rw [hs]
+ simp only [command, hj, dite_false, readBit]
+ simp [hm, partialCount]
+termination_by m - j.val
+decreasing_by omega
+
+/-- Reading a column adds its selected incidence bit to the capped row count. -/
+theorem runColumn {m : ℕ} (input : Word) (base : ℕ) (c : Column m) (r : Fin m)
+ (n fuel : ℕ) (h : ReadsLeft input base (columnBits c)) :
+ countAt m input (base + (columnBits c).length) (.tag r (tally n))
+ ((columnBits c).length + fuel) =
+ countAt m input base (.tag r (tally (n + (c.1 && c.2 r).toNat))) fuel := by
+ have hlen : (columnBits c).length = m + 1 + 1 := by simp [columnBits]
+ have htag := h 0 (by rw [hlen]; omega)
+ have hflag := h 1 (by rw [hlen]; omega)
+ have ht : (atPosition input (base + m + 1 + 1)).head = 2 := by
+ simpa [columnBits, Nat.add_assoc] using htag
+ have hf : (atPosition input (base + m + 1)).head = if c.1 then 2 else 1 := by
+ cases hc : c.1 <;> simpa [columnBits, Nat.add_assoc, hc] using hflag
+ let first : Fin m := ⟨0, Nat.zero_lt_of_lt r.isLt⟩
+ rw [hlen, show base + (m + 1 + 1) = base + m + 1 + 1 by omega,
+ show m + 1 + 1 + fuel = ((m + fuel) + 1) + 1 by omega]
+ refine (countAt_left (next := .flag r (tally n)) ?_).trans ?_
+ · simp [command, ht]
+ refine (countAt_left (next := .bit r first c.1 (tally n)) ?_).trans ?_
+ · rw [hf]
+ cases hc : c.1 <;> simp [command, first]
+ simpa [first, partialCount] using scanColumnBits input base c r first n fuel h
+
+end IncidenceMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IncidenceControl.lean b/lean/OAI/Computability/VPVNP/IncidenceControl.lean
new file mode 100644
index 0000000000..0fe1363763
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IncidenceControl.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.QueryTape
+import OAI.Computability.VPVNP.TableCompiler
+import Mathlib.Data.Fintype.Sigma
+import Mathlib.Data.Fintype.Sum
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Read-only control for an exact-one incidence matrix
+
+Each column on the input tape carries a tag, its selection bit, and one incidence bit per
+row. The control checks one row on each pass from the right end of the tape. A three-valued
+counter distinguishes zero, one, and at least two selected columns incident with the row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace IncidenceMachine
+
+open UniversalMachine TableCompiler QueryTape
+
+/-- One incidence column, consisting of a selection bit and an incidence bit for each of the
+`m` rows. -/
+abbrev Column (m : ℕ) := Bool × (Fin m → Bool)
+
+/-- Bits of one column in the order read by the leftward scan. -/
+def columnBits {m : ℕ} (c : Column m) : Word := true :: c.1 :: List.ofFn c.2
+
+/-- Control states for searching for a row and reading each column's tag, selection bit, and
+incidence bits, with a count saturated at two. -/
+inductive State (m : ℕ) where
+ | search (row : Fin (m + 1))
+ | tag (row : Fin m) (seen : Fin 3)
+ | flag (row : Fin m) (seen : Fin 3)
+ | bit (row colRow : Fin m) (selected : Bool) (seen : Fin 3)
+ deriving DecidableEq, Fintype
+
+/-- Begin the incidence check by searching for row zero. -/
+def start (m : ℕ) : State m := .search 0
+
+/-- Saturating count of selected incidences. -/
+def tally (n : ℕ) : Fin 3 := ⟨min n 2, by omega⟩
+
+theorem tally_succ (n : ℕ) : tally ((tally n).val + 1) = tally (n + 1) := by
+ apply Fin.ext
+ dsimp [tally]
+ omega
+
+theorem tally_eq_one_iff (n : ℕ) : tally n = 1 ↔ n = 1 := by
+ rw [Fin.ext_iff]
+ change min n 2 = 1 ↔ n = 1
+ omega
+
+/-- Literal instructions, with directions 0 (stay), 1 (left), and 2 (right). -/
+def command (m : ℕ) (q : State m) (a : Symbol) : Step (State m) :=
+ match q with
+ | .search row =>
+ if h : row.val < m then
+ if a = 0 then .move (.tag ⟨row.val, h⟩ (tally 0)) 1 else .move (.search row) 2
+ else .halt true
+ | .tag r seen =>
+ if a = 2 then .move (.flag r seen) 1
+ else if a = 1 ∧ seen = 1 then .move (.search r.succ) 0 else .halt false
+ | .flag r seen =>
+ .move (.bit r ⟨0, Nat.zero_lt_of_lt r.isLt⟩ (decide (a = 2)) seen) 1
+ | .bit r j selected seen =>
+ let nextSeen := if j = r ∧ selected = true ∧ a = 2 then tally (seen.val + 1) else seen
+ if hj : j.val + 1 < m then .move (.bit r ⟨j.val + 1, hj⟩ selected nextSeen) 1
+ else .move (.tag r nextSeen) 1
+
+/-- Compile the read-only exact-one incidence checker for `m` rows into a universal-machine
+program. -/
+noncomputable def machine (m : ℕ) : Program := compile (start m) (command m)
+
+/-- Number of accepting paths within the fuel bound when the input head is at `pos` and the
+checker is in state `q`. -/
+noncomputable def countAt (m : ℕ) (input : Word) (pos : ℕ) (q : State m) (fuel : ℕ) : ℕ :=
+ paths (machine m) fuel (running (start m) q (atPosition input pos) (Turing.Tape.mk₁ []))
+
+theorem countAt_step (m : ℕ) (input : Word) (pos : ℕ) (q : State m) (fuel : ℕ) :
+ countAt m input pos q (fuel + 1) =
+ match command m q (atPosition input pos).head with
+ | .halt b => if b then 1 else 0
+ | .move next dir => paths (machine m) fuel
+ (running (start m) next (moveTape (atPosition input pos) dir) (Turing.Tape.mk₁ [])) := by
+ have h := paths_running_succ (start m) (command m) q (atPosition input pos) (Turing.Tape.mk₁ []) fuel
+ cases hc : command m q (atPosition input pos).head <;> simp only [hc] at h <;> exact h
+
+theorem countAt_left {m : ℕ} {input : Word} {pos : ℕ} {q next : State m} {fuel : ℕ}
+ (h : command m q (atPosition input (pos + 1)).head = .move next 1) :
+ countAt m input (pos + 1) q (fuel + 1) = countAt m input pos next fuel := by
+ rw [countAt_step, h]
+ change paths (machine m) fuel (running (start m) next ((atPosition input (pos + 1)).move .left) _) = _
+ rw [move_left_atPosition_succ]
+ rfl
+
+/-- The head sees these bits in order as it moves left, finishing at position `base`. -/
+def ReadsLeft (input : Word) (base : ℕ) (bits : Word) : Prop :=
+ ∀ (i : ℕ) (hi : i < bits.length),
+ (atPosition input (base + bits.length - i)).head = if bits[i] then 2 else 1
+
+end IncidenceMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IncidencePasses.lean b/lean/OAI/Computability/VPVNP/IncidencePasses.lean
new file mode 100644
index 0000000000..cb732d838d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IncidencePasses.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.IncidenceControl
+import OAI.Computability.VPVNP.ProgramLength
+import Mathlib.Data.Fintype.Prod
+import Mathlib.Tactic.Ring
+
+/-! # Iterating the incidence matrix passes
+
+Between two row checks the head scans to the blank at the right end of the
+input. A final pass halts with acceptance precisely when every row check
+succeeded. The running-time bound includes all scans across the padded prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace IncidenceMachine
+
+open UniversalMachine TableCompiler QueryTape
+open scoped Classical
+
+theorem card_state (m : ℕ) : Fintype.card (State m) = (m + 1) + m * 3 + m * 3 + m * m * 6 := by
+ let e : State m ≃ Fin (m+1) ⊕ (Fin m × Fin 3) ⊕ (Fin m × Fin 3) ⊕
+ (Fin m × Fin m × Bool × Fin 3) :=
+ { toFun := fun q => match q with
+ | .search r => .inl r
+ | .tag r z => .inr (.inl (r,z))
+ | .flag r z => .inr (.inr (.inl (r,z)))
+ | .bit r i s z => .inr (.inr (.inr (r,i,s,z)))
+ invFun := fun q => match q with
+ | .inl r => .search r
+ | .inr (.inl (r,z)) => .tag r z
+ | .inr (.inr (.inl (r,z))) => .flag r z
+ | .inr (.inr (.inr (r,i,s,z))) => .bit r i s z
+ left_inv := fun q => by cases q <;> rfl
+ right_inv := fun q => by rcases q with _ | (_ | (_ | _)) <;> rfl }
+ rw [Fintype.card_congr e]
+ simp only [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, Fintype.card_bool]
+ ring
+
+theorem programLength_le (m : ℕ) :
+ (programPrefix (machine m)).length ≤ 1000000 * (m+1)^4 := by
+ have hp := programPrefix_length_le (machine m)
+ have hc : (machine m).extra = Fintype.card (State m) := rfl
+ rw [hc, card_state] at hp
+ have hsmall : (m+1)+m*3+m*3+m*m*6+1 ≤ 20*(m+1)^2 := by
+ nlinarith [Nat.zero_le (m*m)]
+ calc
+ _ ≤ 1000 * (20*(m+1)^2)^2 := hp.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hsmall 2))
+ _ = 400000 * (m+1)^4 := by ring
+ _ ≤ _ := Nat.mul_le_mul_right _ (by decide)
+
+private theorem scanRight {m : ℕ} (input : Word) (r : Fin (m+1)) (hr : r.val < m)
+ (pos d f : ℕ) (hend : pos + d = input.length) :
+ countAt m input pos (.search r) (d + f) = countAt m input input.length (.search r) f := by
+ induction d generalizing pos with
+ | zero => simpa using congrArg (fun j => countAt m input j (.search r) f) hend
+ | succ d ih =>
+ have hpos : pos < input.length := by omega
+ have hb : (atPosition input pos).head ≠ 0 := by
+ rw [head_atPosition_of_lt _ _ hpos]
+ split <;> decide
+ rw [Nat.succ_add, countAt_step, show command m (.search r) (atPosition input pos).head =
+ .move (.search r) 2 by simp [command, hr, hb]]
+ change paths (machine m) (d+f) (running _ _ ((atPosition input pos).move .right) _) = _
+ rw [move_right_atPosition]
+ exact ih (pos+1) (by omega)
+
+/-- If the leftward pass decides row `r`, successive passes decide their conjunction. -/
+theorem check_rows {m : ℕ} (pre scan : Word) (hs : 0 < scan.length) (hit : Fin m → Prop)
+ (hrow : ∀ r f, countAt m (pre ++ scan.reverse) (pre.length + scan.length - 1)
+ (.tag r (tally 0)) (scan.length + f) =
+ if hit r then countAt m (pre ++ scan.reverse) pre.length (.search r.succ) f else 0)
+ (ticks : ℕ) (ht : m * ((pre ++ scan.reverse).length + scan.length + 1) + 1 ≤ ticks) :
+ paths (machine m) ticks (initial (machine m) (pre ++ scan.reverse)) =
+ (decide (∀ r, hit r)).toNat := by
+ let input := pre ++ scan.reverse
+ have hlen : input.length = pre.length + scan.length := by simp [input]
+ have hpass (d : ℕ) (r : Fin (m+1)) (hr : r.val + d = m) (pos f : ℕ) (hpos : pos ≤ input.length)
+ (hf : d * (input.length + scan.length + 1) + 1 ≤ f) :
+ countAt m input pos (.search r) f = (decide (∀ i : Fin m, r.val ≤ i.val → hit i)).toNat := by
+ induction d generalizing r pos f with
+ | zero =>
+ obtain ⟨f, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : f ≠ 0)
+ have hfull (i : Fin m) : ¬ r.val ≤ i.val := by have := i.isLt; omega
+ rw [countAt_step]
+ simp [command, show ¬ r.val < m by omega, hfull]
+ | succ d ih =>
+ have hr' : r.val < m := by omega
+ let i : Fin m := ⟨r.val, hr'⟩
+ let dist := input.length - pos
+ let rest := f - (dist + 1 + scan.length)
+ rw [Nat.succ_mul] at hf
+ have hrest : d * (input.length + scan.length + 1) + 1 ≤ rest := by dsimp [rest, dist]; omega
+ have htime : f = dist + ((scan.length + rest) + 1) := by dsimp [rest, dist]; omega
+ rw [htime, scanRight input r hr' _ dist _ (by dsimp [dist]; omega)]
+ have hdepart : countAt m input input.length (.search r) (scan.length + rest + 1) =
+ countAt m input (pre.length + scan.length - 1) (.tag i (tally 0)) (scan.length + rest) := by
+ let edge := pre.length + scan.length - 1
+ have he : edge + 1 = input.length := by dsimp [edge]; omega
+ have hb : (atPosition input (edge+1)).head = 0 := he ▸ head_atPosition_length input
+ rw [← he]
+ exact countAt_left (by simp [command, hb, hr', i])
+ rw [hdepart, hrow i rest]
+ have hc : (∀ t : Fin m, r.val ≤ t.val → hit t) ↔ hit i ∧
+ ∀ t : Fin m, i.succ.val ≤ t.val → hit t := by
+ constructor
+ · intro hall
+ exact ⟨hall i le_rfl, fun t ht => hall t (by change r.val + 1 ≤ t.val at ht; omega)⟩
+ · rintro ⟨hi, hnext⟩ t ht
+ by_cases he : t.val = i.val
+ · exact Fin.ext he ▸ hi
+ · exact hnext t (by change r.val + 1 ≤ t.val; change t.val ≠ r.val at he; omega)
+ by_cases hh : hit i
+ · rw [ite_eq_left hh, ih i.succ (by change (r.val+1) + d = m; omega) _ _
+ (by omega) hrest]
+ simp [hc, hh]
+ · simp [hh, hc]
+ rw [machine, initial_eq_running]
+ exact (hpass m 0 (by simp) 0 ticks (Nat.zero_le _) ht).trans (by simp)
+
+end IncidenceMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IncidenceProjection.lean b/lean/OAI/Computability/VPVNP/IncidenceProjection.lean
new file mode 100644
index 0000000000..69fa1ddacb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IncidenceProjection.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.IncidencePasses
+import OAI.Computability.VPVNP.IncidenceRecords
+import OAI.Computability.VPVNP.IncidenceReindex
+
+/-! # Exact-one weighted projections at prescribed lengths
+
+Serialize each column once, interleaving its free selection bit with fixed
+incidence data. The read-only control checks every row on this same input.
+The unary program table depends only on the number of rows, while the data
+occupy exactly `k * (m + 2) + 1` bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace IncidenceMachine
+
+open UniversalMachine InterleavedPinning
+open scoped Classical
+
+private theorem correct (padded : Word) {m k : ℕ} (M : Fin m → Fin k → Bool)
+ (x : Fin k → Bool) (ticks : ℕ)
+ (ht : m * ((padded ++ (rowBits (records M x)).reverse).length +
+ (rowBits (records M x)).length + 1) + 1 ≤ ticks) :
+ paths (machine m) ticks (initial (machine m) (padded ++ (rowBits (records M x)).reverse)) =
+ (exactOne M x).toNat := by
+ have hs : 0 < (rowBits (records M x)).length := by rw [length_rowBits_records]; omega
+ have h := check_rows padded (rowBits (records M x)) hs (fun r => rowHits r (records M x) = 1)
+ (fun r f => by
+ by_cases hr : rowHits r (records M x) = 1 <;>
+ simpa [hr] using runRow padded [] (records M x) r f) ticks ht
+ by_cases he : ∀ r, ∃! i, x i = true ∧ M r i = true <;>
+ simpa [hits_records, exactOne, he] using h
+
+/-- For fixed row count, the required source length is linear in the number of columns. -/
+theorem weighted_projection {R V : Type*} [CommRing R] {m k : ℕ}
+ (M : Fin m → Fin k → Bool) (w : Projection R (Fin k) V) (n : ℕ)
+ (hn : 1000000 * (m + 1)^4 + k * (m + 2) + 1 ≤ n) :
+ ∃ φ : Projection R (Fin n × Bool) V,
+ φ.hom (MvPolynomial.map (Int.castRingHom R) (P n)) = weightedPredicate (exactOne M) w := by
+ let pre := programPrefix (machine m)
+ let pad := List.replicate (n - (pre.length + k*(m+2)+1)) false
+ let padded := pre ++ pad
+ let layout := recordLayout padded (fun i => List.ofFn (fun r => M r i))
+ have hp : pre.length ≤ 1000000 * (m+1)^4 := programLength_le m
+ have hlen : layout.length = n := by
+ rw [show layout.length = _ from length_recordLayout padded M]
+ simp only [padded, pad, List.length_append, List.length_replicate]
+ omega
+ have hpre : m+2 ≤ padded.length := by
+ have hc : (machine m).extra = Fintype.card (State m) := rfl
+ have hs : m+1 ≤ (machine m).extra := by rw [hc, card_state]; omega
+ exact (queryPrefix_lower hs).trans (by simp [padded, pre])
+ rw [← hlen]
+ apply InterleavedPinning.weighted_projection layout.get (recordLayout_unique padded _) (exactOne M) w
+ intro x
+ have hf : List.ofFn (fill layout.get x) = padded ++ (rowBits (records M x)).reverse :=
+ fill_records padded M x
+ have hd : decode (padded ++ (rowBits (records M x)).reverse) = some (machine m) := by
+ simp [padded, pre, List.append_assoc, decode_programPrefix]
+ have hwhole : (padded ++ (rowBits (records M x)).reverse).length = layout.length := by
+ simpa only [List.length_ofFn] using (congrArg List.length hf).symm
+ have htime : m * ((padded ++ (rowBits (records M x)).reverse).length +
+ (rowBits (records M x)).length + 1) + 1 ≤ layout.length ^ clockExponent := by
+ rw [hwhole]
+ apply querySteps_le_clock (ℓ := padded.length) _ hpre
+ rw [← hwhole]
+ simp
+ simp only [acceptingCount, hf, hd]
+ exact correct padded M x _ htime
+
+end IncidenceMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IncidenceRecords.lean b/lean/OAI/Computability/VPVNP/IncidenceRecords.lean
new file mode 100644
index 0000000000..88afd3fab3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IncidenceRecords.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.IncidenceScan
+import OAI.Computability.VPVNP.InterleavedPinning
+
+/-! # Physical encoding of a selected set of columns
+
+The row test in the read-only machine counts selected columns incident with the
+row. Each column occupies the same number of cells in the pinned input layout.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace IncidenceMachine
+
+open InterleavedPinning
+
+variable {m k : ℕ}
+
+/-- Column records in the order visited by the machine. -/
+def records (M : Fin m → Fin k → Bool) (x : Fin k → Bool) : List (Column m) :=
+ (List.finRange k).map (fun i => (x i, fun r => M r i))
+
+theorem hits_records (M : Fin m → Fin k → Bool) (x : Fin k → Bool) (r : Fin m) :
+ rowHits r (records M x) = 1 ↔ ∃! i, x i = true ∧ M r i = true := by
+ let hit (i : Fin k) := x i && M r i
+ have hc := (List.nodup_finRange k).card_eq_countP (P := fun i => hit i = true)
+ simp only [Bool.decide_eq_true] at hc
+ simp only [rowHits, records, List.countP_map]
+ change (List.finRange k).countP hit = 1 ↔ _
+ rw [← hc, Finset.card_eq_one_iff_existsUnique]
+ simp [hit]
+
+theorem length_rowBits_records (M : Fin m → Fin k → Bool) (x : Fin k → Bool) :
+ (rowBits (records M x)).length = k * (m + 2) + 1 := by
+ have h (cs : List (Column m)) : (cs.flatMap columnBits).length = cs.length * (m + 2) := by
+ induction cs with
+ | nil => simp
+ | cons c cs ih => simp [columnBits, ih, Nat.add_mul]; omega
+ simp [rowBits, h, records]
+
+/-- Filling the prescribed incidence bits gives the machine's actual input. -/
+theorem fill_records (padded : List Bool) (M : Fin m → Fin k → Bool) (x : Fin k → Bool) :
+ List.ofFn (fill (recordLayout padded (fun i => List.ofFn (fun r => M r i))).get x) =
+ padded ++ (rowBits (records M x)).reverse := by
+ rw [recordLayout_fill]
+ simp [rowBits, records, List.flatMap_map, columnBits]
+
+theorem length_recordLayout (padded : List Bool) (M : Fin m → Fin k → Bool) :
+ (recordLayout padded (fun i => List.ofFn (fun r => M r i))).length =
+ padded.length + k * (m + 2) + 1 := by
+ have h := congrArg List.length (fill_records padded M (fun _ => false))
+ simpa [length_rowBits_records, Nat.add_assoc] using h
+
+end IncidenceMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IncidenceReindex.lean b/lean/OAI/Computability/VPVNP/IncidenceReindex.lean
new file mode 100644
index 0000000000..5efa3211dc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IncidenceReindex.lean
@@ -0,0 +1,48 @@
+import OAI.Computability.VPVNP.HardnessQuery
+
+/-! # Reindexing weighted exact-one incidence tables
+
+A table may label its rows and columns by arbitrary finite types. Enumerating
+both types by finite ordinals preserves both the unique-column test and every
+selected variable or scalar factor in the polynomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace IncidenceMachine
+
+open MvPolynomial
+open scoped Classical
+
+/-- Boolean test that each row is incident with exactly one of the selected columns. -/
+noncomputable def exactOne {U V : Type*} (M : U → V → Bool) (x : V → Bool) : Bool :=
+ decide (∀ r, ∃! i, x i = true ∧ M r i = true)
+
+theorem weighted_exactOne_reindex {U V τ R : Type*} [Fintype U] [Fintype V] [CommRing R]
+ {m k : ℕ} (rows : Fin m ≃ U) (cols : Fin k ≃ V)
+ (M : U → V → Bool) (w : V → τ ⊕ R) :
+ weightedPredicate (exactOne (fun r i => M (rows r) (cols i))) (w ∘ cols) =
+ ∑ x : V → Bool, if ∀ r, ∃! i, x i = true ∧ M r i = true then
+ ∏ i, if x i then (w i).elim X C else 1 else 0 := by
+ let e : (V → Bool) ≃ (Fin k → Bool) := cols.symm.arrowCongr (Equiv.refl Bool)
+ rw [weightedPredicate, ← e.sum_comp]
+ apply Finset.sum_congr rfl
+ intro x _
+ change (if exactOne (fun r i => M (rows r) (cols i)) (fun i => x (cols i)) then
+ ∏ i, if x (cols i) then (w (cols i)).elim X C else 1 else 0) = _
+ have hp (r : U) : (∃! i : Fin k, x (cols i) = true ∧ M r (cols i) = true) ↔
+ ∃! j : V, x j = true ∧ M r j = true :=
+ cols.existsUnique_congr_right (q := fun j => x j = true ∧ M r j = true)
+ have hr : (∀ r : Fin m, ∃! j : V, x j = true ∧ M (rows r) j = true) ↔
+ ∀ r : U, ∃! j : V, x j = true ∧ M r j = true :=
+ rows.forall_congr_right (q := fun r => ∃! j : V, x j = true ∧ M r j = true)
+ simp only [exactOne, decide_eq_true_eq, hp, hr,
+ cols.prod_comp (fun i => if x i then (w i).elim X C else 1)]
+
+end IncidenceMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IncidenceScan.lean b/lean/OAI/Computability/VPVNP/IncidenceScan.lean
new file mode 100644
index 0000000000..32cd34a82e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IncidenceScan.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.IncidenceColumn
+
+/-!
+# One pass of the incidence-matrix machine
+
+A row scan reads the tagged column records from right to left and finishes on the zero
+end marker. Exactly one selected incidence advances the search to the next row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace IncidenceMachine
+
+open UniversalMachine TableCompiler QueryTape
+
+variable {m : ℕ}
+
+/-- A zero after the column tags terminates each scan. -/
+def rowBits (cs : List (Column m)) : Word := cs.flatMap columnBits ++ [false]
+
+/-- Count the selected columns incident with the specified row. -/
+def rowHits (r : Fin m) (cs : List (Column m)) : ℕ :=
+ cs.countP (fun c => c.1 && c.2 r)
+
+private theorem readsLeft_split {input a b : Word} {base : ℕ}
+ (h : ReadsLeft input base (a ++ b)) :
+ ReadsLeft input (base + b.length) a ∧ ReadsLeft input base b := by
+ constructor
+ · intro i hi
+ have hs := h i (by simp; omega)
+ simpa only [List.getElem_append_left hi, List.length_append,
+ show base + (a.length + b.length) = base + b.length + a.length by omega] using hs
+ · intro i hi
+ have hs := h (a.length + i) (by simp [hi])
+ rw [List.getElem_append_right (by omega)] at hs
+ simpa only [List.length_append, Nat.add_sub_cancel_left,
+ show base + (a.length + b.length) - (a.length + i) = base + b.length - i by omega] using hs
+
+private theorem readsLeft_reverse (pre bits post : Word) :
+ ReadsLeft (pre ++ false :: bits.reverse ++ post) pre.length bits := by
+ intro i hi
+ let pos := pre.length + bits.length - i
+ have hleft : pos < (pre ++ false :: bits.reverse).length := by simp [pos]; omega
+ rw [head_atPosition_of_lt _ _ (by simp [pos] at *; omega),
+ List.getElem_append_left hleft, List.getElem_append_right (by dsimp [pos] at *; omega)]
+ have hoff : pre.length + bits.length - i - pre.length = (bits.length - 1 - i) + 1 := by omega
+ simp only [pos, hoff, List.getElem_cons_succ, List.getElem_reverse,
+ show bits.length - 1 - (bits.length - 1 - i) = i by omega]
+
+private theorem endMarker (pre bits post : Word) :
+ (atPosition (pre ++ false :: bits.reverse ++ post) pre.length).head = 1 := by
+ have hlt : pre.length < (pre ++ false :: bits.reverse).length := by simp
+ rw [head_atPosition_of_lt _ _ (by simp),
+ List.getElem_append_left hlt, List.getElem_append_right (Nat.le_refl _)]
+ simp
+
+private theorem runColumns (input : Word) (base : ℕ) (r : Fin m) (cs : List (Column m))
+ (n fuel : ℕ) (h : ReadsLeft input base (cs.flatMap columnBits)) :
+ countAt m input (base + (cs.flatMap columnBits).length) (.tag r (tally n))
+ ((cs.flatMap columnBits).length + fuel) =
+ countAt m input base (.tag r (tally (n + rowHits r cs))) fuel := by
+ induction cs generalizing n with
+ | nil => simp [rowHits]
+ | cons c cs ih =>
+ rw [List.flatMap_cons] at h ⊢
+ obtain ⟨hcol, hrest⟩ := readsLeft_split h
+ rw [List.length_append, show base + ((columnBits c).length + (cs.flatMap columnBits).length) =
+ (base + (cs.flatMap columnBits).length) + (columnBits c).length by omega, Nat.add_assoc (columnBits c).length (cs.flatMap columnBits).length fuel]
+ rw [runColumn input _ c r n _ hcol, ih _ hrest]
+ congr 3
+ simp only [rowHits, List.countP_cons]
+ cases c.1 && c.2 r <;> simp
+ omega
+
+/-- One row consumes one transition per serialized bit, including the terminating zero. -/
+theorem runRow (pre post : Word) (cs : List (Column m)) (r : Fin m) (fuel : ℕ) :
+ let input := pre ++ (rowBits cs).reverse ++ post
+ countAt m input (pre.length + (rowBits cs).length - 1) (.tag r (tally 0))
+ ((rowBits cs).length + fuel) =
+ if rowHits r cs = 1 then countAt m input pre.length (.search r.succ) fuel else 0 := by
+ dsimp only
+ simp only [rowBits, List.reverse_append, List.reverse_singleton, List.cons_append, List.nil_append,
+ List.length_append, List.length_singleton]
+ let bits := cs.flatMap columnBits
+ have h := runColumns (pre ++ false :: bits.reverse ++ post) pre.length r cs 0 (fuel + 1)
+ (readsLeft_reverse pre bits post)
+ simp only [Nat.zero_add] at h
+ rw [show pre.length + ((cs.flatMap columnBits).length + 1) - 1 =
+ pre.length + (cs.flatMap columnBits).length by omega,
+ show (cs.flatMap columnBits).length + 1 + fuel =
+ (cs.flatMap columnBits).length + (fuel + 1) by omega, h, countAt_step]
+ rw [endMarker pre bits post]
+ by_cases hhit : rowHits r cs = 1
+ · simp [command, hhit, tally, countAt, moveTape, bits]
+ · simp [command, hhit, tally_eq_one_iff]
+
+end IncidenceMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IncidentPathFiniteness.lean b/lean/OAI/Computability/VPVNP/IncidentPathFiniteness.lean
new file mode 100644
index 0000000000..11c55bb287
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IncidentPathFiniteness.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.RAMValidatorPaths
+
+/-!
+# Finiteness of the private path count for arbitrary incident bits
+
+An accepted binary string is recovered from the reports of the bounded site
+simulation. This remains true when the incident bits are supplied independently
+of the assignments on the other sites.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM
+
+open BurstRAM RAMLayout RAMSort
+
+variable {w p r k d e : ℕ}
+
+/-- The accepting site reports fit the bucket and fuel bounds, and their
+guess bits recover the entire private branch string. -/
+theorem Machine.validateIncident_boundedReports (M : Machine w p r k) (fuel : ℕ)
+ (initial header : Word w) (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (v : Fin (2 ^ d))
+ (inc : Fin (width d (2 ^ e) w) → Bool) {bs : List Bool} {rs : List (Report w)}
+ (h : (M.validateIncident fuel initial header hw hc v inc bs).1 = some rs) :
+ (rs.length ≤ 2 * 2 ^ e ∧ ∀ r ∈ rs, r.events.length < fuel) ∧
+ bs = rs.flatMap (fun r => guessBits r.events) := by
+ let raw := readIncident inc
+ let edges := (scanSuccessors hw hc initial v raw).1
+ let bucket := M.runBucket fuel (2 ^ d) (2 ^ e) v.val edges.input edges.output bs
+ change (if edges.valid then _ else (none, _)).1 = some rs at h
+ split at h
+ · dsimp only at h
+ cases hb : bucket.1 with
+ | none =>
+ rw [show (M.runBucket fuel (2 ^ d) (2 ^ e) v.val edges.input edges.output bs).1 =
+ none from hb] at h
+ cases h
+ | some ts =>
+ rw [show (M.runBucket fuel (2 ^ d) (2 ^ e) v.val edges.input edges.output bs).1 =
+ some ts from hb] at h
+ change (if (checkSiteMemory (e := e) hw v header raw edges ts).1 then some ts else none) =
+ some rs at h
+ split at h
+ · cases h
+ obtain ⟨hs, hbits⟩ := (M.runBucket_iff (Nat.two_pow_pos e)).mp hb
+ exact ⟨boundedReports_of_localSegment hs.1.calls
+ (hs.1.cost_lt (Nat.two_pow_pos e)).le, hbits⟩
+ · cases h
+ · cases h
+
+/-- The actual accepting branch strings on a fixed local input form a finite
+set, including inputs with inconsistent or malformed messages. -/
+instance Machine.finiteIncidentPaths (M : Machine w p r k) (fuel : ℕ)
+ (initial header : Word w) (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (v : Fin (2 ^ d))
+ (inc : Fin (width d (2 ^ e) w) → Bool) :
+ Finite (M.IncidentPaths fuel initial header hw hc v inc) := by
+ let output (b : M.IncidentPaths fuel initial header hw hc v inc) :=
+ (M.validateIncident fuel initial header hw hc v inc b.val).1.get b.property
+ have spec (b) := M.validateIncident_boundedReports fuel initial header hw hc v inc
+ (rs := output b) (Option.some_get b.property).symm
+ let encode (b) : BoundedReports w fuel (2 * 2 ^ e) := ⟨output b, (spec b).1⟩
+ apply Finite.of_injective encode
+ intro b c h
+ exact Subtype.ext ((spec b).2.trans ((congrArg
+ (fun t : BoundedReports w fuel (2 * 2 ^ e) =>
+ t.val.flatMap (fun r => guessBits r.events)) h).trans
+ (spec c).2.symm))
+
+end BurstRAM.PrivateRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IndependentCompletion.lean b/lean/OAI/Computability/VPVNP/IndependentCompletion.lean
new file mode 100644
index 0000000000..2895059a84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IndependentCompletion.lean
@@ -0,0 +1,33 @@
+import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas
+
+/-! # Extending a partial frame by a prescribed number of vectors -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+/-- An independent tuple can be extended by any number of vectors up to its codimension. -/
+theorem exists_independent_completion {K V ι : Type*} [Field K] [AddCommGroup V]
+ [Module K V] [FiniteDimensional K V] [Fintype ι] {v : ι → V}
+ (hv : LinearIndependent K v) {k : ℕ} (hk : Fintype.card ι + k ≤ Module.finrank K V) :
+ ∃ w : Fin k → V, LinearIndependent K (Sum.elim v w) := by
+ let W := Submodule.span K (Set.range v)
+ let f : ι → W := fun i ↦ ⟨v i, Submodule.subset_span ⟨i, rfl⟩⟩
+ have hf : LinearIndependent K f := .of_comp W.subtype hv
+ have hdim : Module.finrank K W = Fintype.card ι := finrank_span_eq_card hv
+ have hq : k ≤ Module.finrank K (V ⧸ W) := by
+ have := W.finrank_quotient_add_finrank
+ omega
+ obtain ⟨q, hq'⟩ := exists_linearIndependent_of_le_finrank hq
+ choose w hw using fun i ↦ W.mkQ_surjective (q i)
+ refine ⟨w, hf.sumElim_of_quotient w ?_⟩
+ have he : Submodule.Quotient.mk (p := W) ∘ w = q := funext hw
+ exact he.symm ▸ hq'
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/InterleavedPinning.lean b/lean/OAI/Computability/VPVNP/InterleavedPinning.lean
new file mode 100644
index 0000000000..8a95d4af8a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/InterleavedPinning.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.HardnessQuery
+import Mathlib.Data.List.FinRange
+
+/-!
+# Projections with interleaved fixed and free input bits
+
+A deterministic input format may place prescribed bits among the bits that
+carry weights. Fixing the prescribed coordinates retains exactly the paired
+monomials indexed by fillings of the free coordinates.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace InterleavedPinning
+
+open MvPolynomial
+
+variable {n k : ℕ} {R V : Type*} [CommRing R]
+
+/-- Fill the free positions of an input, preserving its prescribed bits. -/
+def fill (layout : Fin n → Bool ⊕ Fin k) (x : Fin k → Bool) (i : Fin n) : Bool :=
+ (layout i).elim id x
+
+private def pin (layout : Fin n → Bool ⊕ Fin k) (weight : Projection R (Fin k) V) :
+ Projection R (Fin n × Bool) V := fun (i, v) =>
+ match layout i with
+ | .inl b => .inr (if v = b then 1 else 0)
+ | .inr j => if v then weight j else .inr 1
+
+/-- The source index is fixed in advance. Only accepting counts on the specified
+fillings enter the weighted predicate. -/
+theorem weighted_projection (layout : Fin n → Bool ⊕ Fin k)
+ (hu : ∀ j, ∃! i, layout i = .inr j)
+ (p : (Fin k → Bool) → Bool) (weight : Projection R (Fin k) V)
+ (hcount : ∀ x, acceptingCount (fill layout x) = (p x).toNat) :
+ ∃ φ : Projection R (Fin n × Bool) V,
+ φ.hom (MvPolynomial.map (Int.castRingHom R) (P n)) = weightedPredicate p weight := by
+ classical
+ choose slot hs huniq using hu
+ have slot_inj : Function.Injective slot := by
+ intro a b hab
+ exact Sum.inr.inj ((hs a).symm.trans ((congrArg layout hab).trans (hs b)))
+ have fill_inj : Function.Injective (fill layout) := by
+ intro x y he
+ funext j
+ simpa [fill, hs] using congrFun he (slot j)
+ let factor (w : Fin n → Bool) (i : Fin n) : MvPolynomial V R :=
+ (pin layout weight (i, w i)).elim X C
+ have hprod (x : Fin k → Bool) : (∏ i, factor (fill layout x) i) =
+ ∏ j, if x j then (weight j).elim X C else 1 := by
+ rw [← Finset.prod_subset (Finset.subset_univ (Finset.univ.image slot)),
+ Finset.prod_image slot_inj.injOn]
+ · apply Finset.prod_congr rfl
+ intro j _
+ cases hj : x j <;> simp [factor, pin, fill, hs, hj]
+ · intro i _ hi
+ cases hl : layout i with
+ | inl b => simp [factor, pin, fill, hl]
+ | inr j => exact (hi (Finset.mem_image.mpr ⟨j, Finset.mem_univ _, (huniq j i hl).symm⟩)).elim
+ have hzero (w : Fin n → Bool) (hw : w ∉ Finset.univ.image (fill layout)) :
+ (∏ i, factor w i) = 0 := by
+ have hbad : ∃ i b, layout i = .inl b ∧ w i ≠ b := by
+ by_contra! h
+ apply hw
+ refine Finset.mem_image.mpr ⟨w ∘ slot, Finset.mem_univ _, ?_⟩
+ funext i
+ cases hl : layout i with
+ | inl b => simp [fill, hl, h i b hl]
+ | inr j => simp [fill, huniq j i hl, hs]
+ obtain ⟨i, b, hl, hne⟩ := hbad
+ exact Finset.prod_eq_zero (Finset.mem_univ i) (by simp [factor, pin, hl, hne])
+ refine ⟨pin layout weight, ?_⟩
+ rw [map_P]
+ simp only [Projection.hom, pairedPolynomial, map_sum, map_mul, eval₂Hom_C, map_prod,
+ eval₂Hom_X']
+ change (∑ w, C (acceptingCount w : R) * ∏ i, factor w i) = _
+ rw [← Finset.sum_subset (Finset.subset_univ (Finset.univ.image (fill layout))),
+ Finset.sum_image fill_inj.injOn, weightedPredicate]
+ · apply Finset.sum_congr rfl
+ intro x _
+ rw [hprod, hcount]
+ cases hp : p x <;> simp
+ · intro w _ hw
+ simp [hzero w hw]
+
+/-- A column record has a marker, one free bit, and its list of prescribed flags.
+The machine scans these records from the right end of the physical input. -/
+def recordLayout (padded : List Bool) (flags : Fin k → List Bool) : List (Bool ⊕ Fin k) :=
+ padded.map Sum.inl ++
+ ((List.finRange k).flatMap (fun i => Sum.inl true :: Sum.inr i :: (flags i).map Sum.inl) ++
+ [Sum.inl false]).reverse
+
+/-- The physical input obtained by filling all column records. -/
+theorem recordLayout_fill (padded : List Bool) (flags : Fin k → List Bool) (x : Fin k → Bool) :
+ List.ofFn (fill (recordLayout padded flags).get x) =
+ padded ++ ((List.finRange k).flatMap (fun i => true :: x i :: flags i) ++ [false]).reverse := by
+ have hmap : List.ofFn (fill (recordLayout padded flags).get x) =
+ (recordLayout padded flags).map (Sum.elim id x) := by
+ change List.ofFn (Sum.elim id x ∘ (recordLayout padded flags).get) = _
+ rw [← List.map_ofFn, List.ofFn_get]
+ rw [hmap]
+ simp [recordLayout, List.map_flatMap, List.map_reverse, List.map_map, Function.comp_def]
+
+private theorem unique_get_of_count_one {α : Type*} [DecidableEq α] (a : α) (l : List α)
+ (hc : l.count a = 1) : ∃! i, l.get i = a := by
+ induction l with
+ | nil => simp at hc
+ | cons b tail ih =>
+ by_cases hb : b = a
+ · subst b
+ have hnot : a ∉ tail := by
+ simpa [List.count_cons_self, List.count_eq_zero] using hc
+ refine ⟨0, rfl, fun i => ?_⟩
+ refine Fin.cases (fun _ => rfl) (fun j h => ?_) i
+ exact (hnot (h ▸ tail.get_mem j)).elim
+ · have hc' : tail.count a = 1 := by simpa [List.count_cons, hb] using hc
+ obtain ⟨j, hj, hjuniq⟩ := ih hc'
+ refine ⟨j.succ, hj, fun i => ?_⟩
+ refine Fin.cases (fun h => (hb h).elim) (fun t h => ?_) i
+ exact congrArg Fin.succ (hjuniq t h)
+
+/-- Each free variable occurs exactly once even after reversal and padding. -/
+theorem recordLayout_unique (padded : List Bool) (flags : Fin k → List Bool) :
+ ∀ j, ∃! i, (recordLayout padded flags).get i = .inr j := by
+ intro j
+ let : BEq (Bool ⊕ Fin k) := instBEqOfDecidableEq
+ apply unique_get_of_count_one
+ have hpinned (bits : List Bool) : (bits.map Sum.inl).count (Sum.inr j) = 0 := by
+ apply List.count_eq_zero.mpr
+ simp
+ have hrecords (indices : List (Fin k)) :
+ (indices.flatMap (fun i => Sum.inl true :: Sum.inr i :: (flags i).map Sum.inl)).count
+ (.inr j) = indices.count j := by
+ induction indices with
+ | nil => simp
+ | cons i tail ih => simp [List.count_cons, beq_iff_eq, hpinned, ih]
+ simp [recordLayout, hpinned, hrecords]
+
+end InterleavedPinning
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/IteratedCompression.lean b/lean/OAI/Computability/VPVNP/IteratedCompression.lean
new file mode 100644
index 0000000000..c68695167e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/IteratedCompression.lean
@@ -0,0 +1,153 @@
+import OAI.Computability.VPVNP.ShrinkProcedureHistory
+import OAI.Computability.VPVNP.RefreshProcedureRecords
+import OAI.Computability.VPVNP.CompressionBlockHistory
+import OAI.Computability.VPVNP.CompressionPowerHistory
+
+/-!
+# Iterated compression with a fixed system of wire identities
+
+Theorem 7.1 of *VP and VNP differ over every field*. The expansion here uses
+the packed six-party substeps and the port refresh on the actual lifted
+slots. Its finite templates, degree schedule, number of lane coordinates
+per block, energy allowance, and per-vertex history bound are fixed before
+choosing a network or the number of blocks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+namespace BlockSchedule.Templates
+
+open MotifConversion
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+
+/-- Execute the fixed shrinking degrees followed by the expander refresh. -/
+noncomputable def procedure : Procedure R (S.degreeExponent 0) (S.degreeExponent 0)
+ S.laneBits S.positionFactor
+ (refreshMultiplier S.baseDegree (2 ^ S.expanderExponent) S.poincare *
+ shrinkMultiplier ^ S.steps) :=
+ S.assembleBlock (B.shrinkProcedure f hf) (B.refreshProcedure f hf)
+
+/-- The additive energy error is the same in every ring realizing the templates. -/
+theorem procedure_error_eq {R' : Type*} [CommRing R'] (f' : B.Entry → R') (hf' : B.IsSolution f') :
+ (B.procedure f hf).error = (B.procedure f' hf').error :=
+ S.assembleBlock_error_congr (B.shrinkProcedure f hf) (B.shrinkProcedure f' hf')
+ (B.refreshProcedure f hf) (B.refreshProcedure f' hf')
+ (fun i => (B.shrinkProcedure_error f hf i).trans (B.shrinkProcedure_error f' hf' i).symm)
+ ((B.refreshProcedure_error f hf).trans (B.refreshProcedure_error f' hf').symm)
+
+/-- Fixed coefficient of the initial position count in the shared-width bound. -/
+noncomputable def widthAllowance : ℝ :=
+ Real.sqrt (B.procedure B.exists_solution.choose B.exists_solution.choose_spec).potentialWeight
+
+/-- Uniform bound on each substep's records at a single vertex. -/
+noncomputable def recordLimit : ℕ :=
+ max 1 (max (Finset.univ.sup fun i : Fin S.steps =>
+ State.shrinkHistoryFactor B.shrink (S.degreeExponent i.castSucc) (S.degreeExponent i.succ))
+ B.refreshRecordConstant)
+
+/-- The paper's `C₂`, enlarged to at least two. -/
+noncomputable def growthConstant : ℕ := max 2 (B.recordLimit ^ (S.steps + 1))
+
+theorem growthConstant_ge_two : 2 ≤ B.growthConstant := le_max_left _ _
+
+/-- Local records are those of the constructed wire identities at each chosen site. -/
+noncomputable def recordBounds : (B.procedure f hf).RecordBounds B.recordLimit (S.steps + 1) :=
+ (S.assembleBlockRecords _ _ (B.shrinkProcedureRecords f hf) (B.refreshProcedureRecords f hf)).mono
+ (le_max_right 1 _) le_rfl
+
+/-- `T` complete blocks on an input with any sufficient number of lane coordinates. -/
+noncomputable def execute {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n)
+ (X : State (S.degreeExponent 0) n) :
+ StateExecution R (S.degreeExponent 0) (n - T * S.laneBits) X :=
+ (B.procedure f hf).repeatWithLanes T n h X
+
+/-- The complete history of actual records on every branch of `execute`. -/
+noncomputable def records {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n)
+ (X : State (S.degreeExponent 0) n) :
+ (B.execute f hf T h X).Records :=
+ Procedure.repeatRecords (B.recordBounds f hf) _ T n (Nat.add_sub_of_le h).symm X
+
+/-- Every branch restores the base degree, satisfies the shared-width saving
+(7.4), and keeps all intermediate fields, individual map-entry degrees and
+recursive vertex expansions within the stated exponential-in-block bounds. -/
+theorem branch_bounds {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n)
+ (X : State (S.degreeExponent 0) n) (z : (B.execute f hf T h X).Choices) :
+ let E := B.execute f hf T h X
+ let Y := E.finalState z
+ let chain := E.termChain (B.records f hf T h X) z
+ X.positions = S.positionFactor ^ T * Y.positions ∧
+ (Y.totalWidth : ℝ) ≤ Real.sqrt Y.energy ∧
+ Real.sqrt Y.energy ≤ (Real.sqrt X.energy + B.widthAllowance * X.positions) / (2 : ℝ)^T ∧
+ (∀ v, chain.occurrences (fun _ => 1) v ≤ B.growthConstant ^ T) ∧
+ chain.AllRecordsLe (B.growthConstant ^ T * (X.maxWireWidth + 1)) ∧
+ Y.maxWireWidth ≤ B.growthConstant ^ T * (X.maxWireWidth + 1) := by
+ have hc := (B.procedure f hf).repeatWithLanes_bounds S.positionFactor_gt_two S.quarter T n h X z
+ obtain ⟨hpos, hwidth, henergy⟩ := hc
+ have heq : Real.sqrt (B.procedure f hf).potentialWeight = B.widthAllowance := by
+ unfold widthAllowance Procedure.potentialWeight
+ rw [B.procedure_error_eq f hf B.exists_solution.choose B.exists_solution.choose_spec]
+ rw [heq] at henergy
+ exact ⟨hpos, hwidth, henergy, Procedure.repeatWithLanes_history_bounds (B.recordBounds f hf)
+ (le_max_left 1 _) T n h X z⟩
+
+/-- The exact identity behind the estimates holds against any original
+vertex factors, including those carrying fixed external indices. -/
+theorem execute_contract {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n)
+ (X : State (S.degreeExponent 0) n) (F : NetworkKernel.Factors R X.network) :
+ let H := (B.execute f hf T h X).history
+ NetworkKernel.contract X.network F = ∑ p : H.Path, H.weight F p :=
+ (B.execute f hf T h X).history.contract_eq_sum_paths F
+
+end BlockSchedule.Templates
+
+open SpectralGeometry
+
+/-- Theorem 7.1. The degree schedule and integral templates are chosen once,
+before specializing the coefficient ring or selecting the input. Their
+quantitative conclusions for every term are `Templates.branch_bounds`, and
+their exact contraction identity is `Templates.execute_contract`. -/
+theorem exists_iterated_compression {k : Type*} [Field k] (h : HasWireExpanders k) :
+ ∃ (S : BlockSchedule k) (B : S.Templates),
+ 0 < S.laneBits ∧ 2 ≤ B.growthConstant ∧
+ (∃ κ : B.Entry → k, B.IsSolution κ) ∧
+ ∀ (R : Type*) [CommRing R] (κ : B.Entry → R) (hκ : B.IsSolution κ)
+ (n T : ℕ) (hn : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n),
+ let E := B.execute κ hκ T hn X
+ (∀ z : E.Choices,
+ let Y := E.finalState z
+ let chain := E.termChain (B.records κ hκ T hn X) z
+ X.positions = S.positionFactor ^ T * Y.positions ∧
+ (Y.totalWidth : ℝ) ≤ Real.sqrt Y.energy ∧
+ Real.sqrt Y.energy ≤ (Real.sqrt X.energy + B.widthAllowance * X.positions) / (2 : ℝ)^T ∧
+ (∀ v, chain.occurrences (fun _ => 1) v ≤ B.growthConstant ^ T) ∧
+ chain.AllRecordsLe (B.growthConstant ^ T * (X.maxWireWidth + 1)) ∧
+ Y.maxWireWidth ≤ B.growthConstant ^ T * (X.maxWireWidth + 1)) ∧
+ ∀ F : NetworkKernel.Factors R X.network,
+ NetworkKernel.contract X.network F = ∑ p : E.history.Path, E.history.weight F p := by
+ obtain ⟨S⟩ := exists_blockSchedule h
+ obtain ⟨B⟩ := S.exists_templates
+ exact ⟨S, B, S.laneBits_pos, B.growthConstant_ge_two, B.exists_solution,
+ fun _ _ κ hκ _ T hn X => ⟨B.branch_bounds κ hκ T hn X, B.execute_contract κ hκ T hn X⟩⟩
+
+/-- The small-circuit contradiction fixes both templates and a joint field
+assignment before the simulation is instantiated at any particular length.
+Every sufficient input length and block count can then use the same
+`Templates.execute`, `Templates.branch_bounds` and `Templates.execute_contract`. -/
+theorem fixed_templates_of_small_circuits (k : Type*) [Field k] {C : ℕ} (hC : 1 ≤ C)
+ (hsmall : ∀ N, ∃ n ≥ N, circuitSize (MvPolynomial.map (Int.castRingHom k) (P n)) ≤ n ^ C) :
+ ∃ (S : BlockSchedule k) (B : S.Templates), ∃ f : B.Entry → k, B.IsSolution f := by
+ obtain ⟨S⟩ := exists_blockSchedule (wire_expanders_of_small_circuits k hC hsmall)
+ obtain ⟨B⟩ := S.exists_templates
+ exact ⟨S, B, B.exists_solution⟩
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointLabelBounds.lean b/lean/OAI/Computability/VPVNP/JointLabelBounds.lean
new file mode 100644
index 0000000000..c9d1c71b7d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointLabelBounds.lean
@@ -0,0 +1,161 @@
+import OAI.Computability.VPVNP.JointLabelSystem
+import OAI.Computability.VPVNP.GrammarCoefficientBounds
+import OAI.Computability.VPVNP.PolynomialBounds
+import Mathlib.Data.Nat.Size
+
+/-!
+# Degree and coefficient bounds for the joint integer equations
+
+In §8.1, a parse contributing to a grammar equation contains one label per
+vertex of a full ordered binary tree with `n` leaves. The integer constant
+subtracted from its parse count comes from the clocked accepting paths. The
+additional motif equations depend only on the fixed integral tensors.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointLabelSystem
+
+open MvPolynomial
+
+/-- Every accepting path has its canonical string of clocked choices. -/
+theorem acceptingCount_le {n : ℕ} (x : Fin n → Bool) :
+ acceptingCount x ≤ 2 ^ (n ^ clockExponent) := by
+ rw [acceptingCount_eq_card_witnesses]
+ exact (Finset.card_filter_le _ _).trans_eq (by simp)
+
+/-- The designated query is homogeneous of degree `2n - 1` before
+subtraction of its integer constant. -/
+theorem grammarEquation_totalDegree_le {n : ℕ} (hn : 2 ≤ n) (c : ℕ) (x : Fin n → Bool) :
+ (grammarEquation hn c x).totalDegree ≤ 2 * n - 1 := by
+ apply (totalDegree_sub_C_le _ _).trans
+ apply (labelQuery_isHomogeneous _ _ _).totalDegree_le.trans
+ change 2 * (n - 1) + 1 ≤ 2 * n - 1
+ omega
+
+/-- An exponent bounding the parse count. The factors account for ordered
+tree shapes, child states and terminal variables. -/
+def parseExponent (c n : ℕ) := 2 * n + n * (c + 5) * (2 * n) + (2 * n) * n
+
+private theorem parse_count_bound {n : ℕ} (hn : 2 ≤ n) (c : ℕ) :
+ 4 ^ (n - 1) * (n ^ (c + 5)) ^ (2 * (n - 1)) * (n * 2) ^ (n - 1 + 1)
+ ≤ 2 ^ parseExponent c n := by
+ have hshape : 4 ^ (n - 1) ≤ 2 ^ (2 * n) := calc
+ 4 ^ (n - 1) ≤ 4 ^ n := Nat.pow_le_pow_right (by decide) (by omega)
+ _ = 2 ^ (2 * n) := by rw [pow_mul]; rfl
+ have hstate : n ^ (c + 5) ≤ 2 ^ (n * (c + 5)) := by
+ rw [pow_mul]
+ exact Nat.pow_le_pow_left Nat.lt_two_pow_self.le _
+ have hstates : (n ^ (c + 5)) ^ (2 * (n - 1)) ≤ 2 ^ (n * (c + 5) * (2 * n)) := by
+ rw [pow_mul _ _ (2 * n)]
+ exact (Nat.pow_le_pow_left hstate _).trans (Nat.pow_le_pow_right Nat.one_le_two_pow (by omega))
+ have hterm : (n * 2) ^ (n - 1 + 1) ≤ 2 ^ (2 * n * n) := by
+ rw [show n - 1 + 1 = n by omega, Nat.mul_comm n 2, pow_mul]
+ exact Nat.pow_le_pow_left Nat.lt_two_pow_self.le _
+ simpa only [parseExponent, pow_add] using Nat.mul_le_mul (Nat.mul_le_mul hshape hstates) hterm
+
+/-- An exponent bounding the magnitude of any integer grammar coefficient. -/
+def grammarExponent (c n : ℕ) := parseExponent c n + n ^ clockExponent + 1
+
+theorem grammarEquation_coeff_natAbs_le {n : ℕ} (hn : 2 ≤ n) (c : ℕ) (x : Fin n → Bool)
+ (e : Production n c →₀ ℕ) : ((grammarEquation hn c x).coeff e).natAbs ≤ 2 ^ grammarExponent c n := by
+ classical
+ let d : Fin n := ⟨n - 1, by omega⟩
+ let h : Fin (n ^ (c + 5)) := ⟨0, pow_pos (by omega) _⟩
+ obtain ⟨hpos, hcount⟩ := coeff_labelQuery_bounds d h x e
+ have hparse : ((labelQuery d h x).coeff e).natAbs ≤ 2 ^ parseExponent c n := by
+ apply le_trans _ (parse_count_bound hn c)
+ apply Int.ofNat_le.mp
+ rw [Int.natAbs_of_nonneg hpos]
+ simpa only [d, Fintype.card_prod, Fintype.card_fin, Fintype.card_bool] using hcount
+ have hpath : ((C (acceptingCount x : ℤ) : MvPolynomial (Production n c) ℤ).coeff e).natAbs ≤
+ 2 ^ (n ^ clockExponent) := by
+ rw [coeff_C]
+ split_ifs <;> simp [acceptingCount_le]
+ rw [grammarEquation, coeff_sub]
+ refine (Int.natAbs_sub_le _ _).trans ((Nat.add_le_add hparse hpath).trans ?_)
+ let a := parseExponent c n + n ^ clockExponent
+ have hp : 2 ^ parseExponent c n ≤ 2 ^ a :=
+ Nat.pow_le_pow_right (by decide) (Nat.le_add_right _ _)
+ have hw : 2 ^ (n ^ clockExponent) ≤ 2 ^ a :=
+ Nat.pow_le_pow_right (by decide) (Nat.le_add_left _ _)
+ simpa only [grammarExponent, pow_succ, Nat.mul_two, a] using Nat.add_le_add hp hw
+
+variable {J Z : Type*} [Fintype J] (G : MotifParameters.Data J Z)
+
+/-- One matrix entry per party is multiplied by a constant tensor coordinate
+in each summand of a base identity. -/
+theorem motifEquation_totalDegree_le (o : G.Output) : (G.equation o).totalDegree ≤ Fintype.card J := by
+ classical
+ unfold MotifParameters.Data.equation
+ apply (totalDegree_sub _ _).trans
+ refine max_le (by rw [totalDegree_C]; exact Nat.zero_le _) (totalDegree_finsetSum_le fun t _ => ?_)
+ unfold WireTensor.applyLocal
+ refine totalDegree_finsetSum_le fun b _ => (totalDegree_mul _ _).trans ?_
+ rw [totalDegree_C, Nat.add_zero]
+ simpa only [MotifParameters.Data.localMap, totalDegree_X, Finset.sum_const,
+ Finset.card_univ, smul_eq_mul, mul_one] using
+ totalDegree_finsetProd Finset.univ (fun j => X (R := ℤ) (⟨o.1, t, j, o.2 j, b j⟩ : G.Entry))
+
+variable [Fintype Z]
+
+/-- The fixed integer coefficient height of all local motif equations. -/
+noncomputable def motifHeight : ℕ := by
+ classical exact Finset.univ.sup fun o : G.Output =>
+ (G.equation o).support.sup fun e => ((G.equation o).coeff e).natAbs
+
+theorem motifEquation_coeff_natAbs_le (o : G.Output) (e : G.Entry →₀ ℕ) :
+ ((G.equation o).coeff e).natAbs ≤ motifHeight G := by
+ classical
+ by_cases he : e ∈ (G.equation o).support
+ · unfold motifHeight
+ exact (Finset.le_sup (f := fun e => ((G.equation o).coeff e).natAbs) he).trans
+ (Finset.le_sup (f := fun o : G.Output => (G.equation o).support.sup
+ fun e => ((G.equation o).coeff e).natAbs) (Finset.mem_univ o))
+ · simp [notMem_support_iff.mp he]
+
+/-- The union of the two systems preserves the separate degree estimates. -/
+theorem equations_totalDegree_le {n : ℕ} (hn : 2 ≤ n) (c : ℕ)
+ (G : MotifParameters.Data J Z) (j : (Fin n → Bool) ⊕ G.Output) :
+ (equations hn c G j).totalDegree ≤ max (2 * n - 1) (Fintype.card J) :=
+ unionEquations_totalDegree_le _ _
+ (fun x => (grammarEquation_totalDegree_le hn c x).trans (le_max_left ..))
+ (fun o => (motifEquation_totalDegree_le G o).trans (le_max_right ..)) j
+
+/-- One exponent for the entire joint system at length `n`. -/
+noncomputable def coefficientExponent (c : ℕ) (G : MotifParameters.Data J Z) (n : ℕ) :=
+ grammarExponent c n + motifHeight G
+
+theorem equations_coeff_natAbs_le {n : ℕ} (hn : 2 ≤ n) (c : ℕ)
+ (G : MotifParameters.Data J Z) (j : (Fin n → Bool) ⊕ G.Output)
+ (e : Fin (Fintype.card (Production n c ⊕ G.Entry)) →₀ ℕ) :
+ ((equations hn c G j).coeff e).natAbs ≤ 2 ^ coefficientExponent c G n := by
+ refine unionEquations_coeff_natAbs_le _ _ (fun x a => ?_) (fun o a => ?_) j e
+ · exact (grammarEquation_coeff_natAbs_le hn c x a).trans
+ (Nat.pow_le_pow_right (by decide) (Nat.le_add_right _ _))
+ · exact ((motifEquation_coeff_natAbs_le G o a).trans Nat.lt_two_pow_self.le).trans
+ (Nat.pow_le_pow_right (by decide) (Nat.le_add_left _ _))
+
+/-- The joint height exponent is a polynomial bound for each fixed circuit
+size exponent and fixed motif system, uniformly in the equation and monomial. -/
+theorem polynomiallyBounded_coefficientExponent (c : ℕ) (G : MotifParameters.Data J Z) :
+ PolynomiallyBounded (coefficientExponent c G) := by
+ let h := PolynomiallyBounded.id
+ let h₂ := (PolynomiallyBounded.const 2).mul h
+ have hp := (h₂.add ((h.mul (PolynomiallyBounded.const (c + 5))).mul h₂)).add (h₂.mul h)
+ exact (((hp.add (h.pow clockExponent)).add (PolynomiallyBounded.const 1)).add
+ (PolynomiallyBounded.const (motifHeight G)))
+
+/-- The unsigned bit length of any coefficient is at most the common exponent plus one. -/
+theorem equations_coeff_size_le {n : ℕ} (hn : 2 ≤ n) (c : ℕ) (G : MotifParameters.Data J Z)
+ (j : (Fin n → Bool) ⊕ G.Output) (e : Fin (Fintype.card (Production n c ⊕ G.Entry)) →₀ ℕ) :
+ ((equations hn c G j).coeff e).natAbs.size ≤ coefficientExponent c G n + 1 := by
+ simpa only [Nat.size_pow] using Nat.size_le_size (equations_coeff_natAbs_le hn c G j e)
+
+end JointLabelSystem
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointLabelEvaluator.lean b/lean/OAI/Computability/VPVNP/JointLabelEvaluator.lean
new file mode 100644
index 0000000000..d8f697f3e4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointLabelEvaluator.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.JointLabelBounds
+import OAI.Computability.VPVNP.LabelEvaluator
+
+/-!
+# Applying the finite-algebra evaluator to the small-circuit label equations
+
+At a length with a circuit of size at most `n^c`, the grammar assignment and
+the fixed motif solution descend together. The prime is fixed in positive
+characteristic and has polynomially bounded bit length in characteristic zero.
+The resulting finite algebra therefore satisfies all instances of (8.1) and
+all the local wire identities, with one normalized evaluator for every label
+exponent vector.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointLabelSystem
+
+open MvPolynomial LabelEvaluator
+
+variable {J Z : Type*} [Fintype J] [Fintype Z] {n : ℕ}
+
+/-- Degree bound for all grammar and motif equations, raised to at least three for the
+finite-algebra construction. -/
+def degreeBound (J : Type*) [Fintype J] (n : ℕ) : ℕ := max 3 (max (2 * n - 1) (Fintype.card J))
+
+/-- When the joint grammar and motif equations have a characteristic-zero solution, descent
+yields a finite model at a prime bounded by two to this exponent. -/
+noncomputable def primeBits (c : ℕ) (G : MotifParameters.Data J Z) (n : ℕ) : ℕ :=
+ let t := Fintype.card (Production n c ⊕ G.Entry)
+ let d := degreeBound J n
+ let a := Nat.clog 2 (multiplierDegree t d + d + 1) * t
+ 2 * (a + Nat.clog 2 (a + coefficientExponent c G n + 2)) + 1
+
+/-- The exponent in the good-prime size bound is polynomial in the input length. -/
+theorem primeBits_polynomiallyBounded (c : ℕ) (G : MotifParameters.Data J Z) :
+ PolynomiallyBounded (primeBits c G) := by
+ let t (n : ℕ) := Fintype.card (Production n c ⊕ G.Entry)
+ have ht : PolynomiallyBounded t := variable_count_polynomiallyBounded G c
+ have hd : PolynomiallyBounded (degreeBound J) :=
+ (((PolynomiallyBounded.const 3).add ((PolynomiallyBounded.const 2).mul PolynomiallyBounded.id)).add
+ (.const (Fintype.card J))).of_le (fun n => by dsimp [degreeBound]; omega)
+ have clog {g : ℕ → ℕ} (hg : PolynomiallyBounded g) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (g n)) :=
+ hg.of_le (fun _ => Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le)
+ exact RadicalCertificate.polynomiallyBounded_good_prime_bits ht
+ (RadicalCertificate.polynomiallyBounded_clog_paperBound ht (clog hd))
+ (clog hd) (clog (polynomiallyBounded_coefficientExponent c G))
+
+/-- An actual small circuit and motif solution yield the finite-algebra
+evaluator for the joint system. Both characteristic cases preserve the
+specified quantifier order with respect to the input exponent vectors. -/
+theorem exists_evaluator_of_circuit {k : Type*} [Field k] (q : ℕ) [CharP k q] {c s : ℕ}
+ (hn : 2 ≤ n) (hc : 1 ≤ c) (hs : s ≤ n ^ c) (circuit : Circuit k (Fin n × Bool) s)
+ (hpoly : circuit.polynomial = map (Int.castRingHom k) (P n))
+ (G : MotifParameters.Data J Z) (κ : G.Entry → k) (hκ : G.IsSolution κ) :
+ ∃ p : Nat.Primes, (q ≠ 0 → p.val = q) ∧ (q = 0 → p.val ≤ 2 ^ primeBits c G n) ∧
+ Nonempty (Model p (degreeBound J n) (equations hn c G)) := by
+ classical
+ let : Fintype G.Output := Fintype.ofFinite _
+ obtain ⟨a, ha⟩ := exists_solution hn hc hs circuit hpoly G κ hκ
+ have hdeg (i) : (equations hn c G i).totalDegree ≤ degreeBound J n :=
+ (equations_totalDegree_le hn c G i).trans (le_max_right ..)
+ have hd : 3 ≤ degreeBound J n := le_max_left ..
+ rcases CharP.char_is_prime_or_zero k q with hp | rfl
+ · let p : Nat.Primes := ⟨q, hp⟩
+ exact ⟨p, fun _ => rfl, fun h => (hp.ne_zero h).elim, exists_model_positive p _
+ (degreeBound J n) hd hdeg a ha⟩
+ · have := CharP.charP_to_charZero k
+ obtain ⟨p, hp, hM⟩ := exists_model_charZero (equations hn c G) _ _ hd hdeg
+ (equations_coeff_natAbs_le hn c G) a ha
+ exact ⟨p, fun h => (h rfl).elim, fun _ => hp, hM⟩
+
+/-- The single reduced algebra furnished by the evaluator satisfies every
+path-count coefficient identity and every fixed motif equation simultaneously. -/
+theorem evaluator_label_identities (hn : 2 ≤ n) (c : ℕ) (G : MotifParameters.Data J Z)
+ {p : Nat.Primes} (M : Model p (degreeBound J n) (equations hn c G)) :
+ (∀ x : Fin n → Bool, eval₂Hom (Int.castRingHom M.algebra)
+ (M.labels ∘ leftIndex (Production n c) G.Entry)
+ (labelQuery ⟨n - 1, by omega⟩ ⟨0, pow_pos (by omega) _⟩ x) = (acceptingCount x : M.algebra)) ∧
+ G.IsSolution (M.labels ∘ rightIndex (Production n c) G.Entry) :=
+ (solution_iff hn c G M.labels).mp M.solution
+
+end JointLabelSystem
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointLabelSystem.lean b/lean/OAI/Computability/VPVNP/JointLabelSystem.lean
new file mode 100644
index 0000000000..603b1e4222
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointLabelSystem.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.GrammarAssignment
+import OAI.Computability.VPVNP.GrammarSize
+import OAI.Computability.VPVNP.PolynomialBounds
+import OAI.Computability.VPVNP.MotifParameters
+
+/-!
+# The joint integer label equations of Section 8.1
+
+The grammar labels and the entries of the fixed motif maps are disjoint sets
+of variables. Enumerating their union gives one finite list of variables for
+the field-descent and Macaulay constructions. Every solution specializes the
+two systems simultaneously, over any commutative coefficient ring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointLabelSystem
+
+open MvPolynomial
+
+variable {V W I J : Type*} [Fintype V] [Fintype W]
+
+/-- Index of a variable from the first system in the joint coordinate list. -/
+noncomputable def leftIndex (V W : Type*) [Fintype V] [Fintype W] :
+ V ↪ Fin (Fintype.card (V ⊕ W)) :=
+ ⟨fun v => Fintype.equivFin (V ⊕ W) (.inl v), (Fintype.equivFin _).injective.comp Sum.inl_injective⟩
+
+/-- Index of a variable from the second system in the joint coordinate list. -/
+noncomputable def rightIndex (V W : Type*) [Fintype V] [Fintype W] :
+ W ↪ Fin (Fintype.card (V ⊕ W)) :=
+ ⟨fun w => Fintype.equivFin (V ⊕ W) (.inr w), (Fintype.equivFin _).injective.comp Sum.inr_injective⟩
+
+/-- Place the two lists of integer equations in one ring on numbered variables. -/
+noncomputable def unionEquations (F : I → MvPolynomial V ℤ) (G : J → MvPolynomial W ℤ) :
+ I ⊕ J → MvPolynomial (Fin (Fintype.card (V ⊕ W))) ℤ :=
+ Sum.elim (fun i => rename (leftIndex V W) (F i)) (fun j => rename (rightIndex V W) (G j))
+
+/-- Pulling a joint assignment back along the two coordinate embeddings yields
+exactly the simultaneous solutions of the original systems. -/
+theorem unionEquations_solution_iff {R : Type*} [CommRing R] (F : I → MvPolynomial V ℤ)
+ (G : J → MvPolynomial W ℤ) (a : Fin (Fintype.card (V ⊕ W)) → R) :
+ (∀ j, eval₂Hom (Int.castRingHom R) a (unionEquations F G j) = 0) ↔
+ (∀ i, eval₂Hom (Int.castRingHom R) (a ∘ leftIndex V W) (F i) = 0) ∧
+ (∀ j, eval₂Hom (Int.castRingHom R) (a ∘ rightIndex V W) (G j) = 0) := by
+ simp only [Sum.forall, unionEquations, Sum.elim_inl, Sum.elim_inr, eval₂Hom_rename]
+
+/-- Combine two label assignments into the common list of numbered coordinates. -/
+noncomputable def joinAssignment {R : Type*} (a : V → R) (b : W → R) :
+ Fin (Fintype.card (V ⊕ W)) → R :=
+ Sum.elim a b ∘ (Fintype.equivFin (V ⊕ W)).symm
+
+@[simp] theorem joinAssignment_left {R : Type*} (a : V → R) (b : W → R) :
+ joinAssignment a b ∘ leftIndex V W = a := by
+ funext v
+ simp [joinAssignment, leftIndex]
+
+@[simp] theorem joinAssignment_right {R : Type*} (a : V → R) (b : W → R) :
+ joinAssignment a b ∘ rightIndex V W = b := by
+ funext w
+ simp [joinAssignment, rightIndex]
+
+theorem unionEquations_totalDegree_le (F : I → MvPolynomial V ℤ) (G : J → MvPolynomial W ℤ)
+ {d : ℕ} (hF : ∀ i, (F i).totalDegree ≤ d) (hG : ∀ j, (G j).totalDegree ≤ d) (j : I ⊕ J) :
+ (unionEquations F G j).totalDegree ≤ d := by
+ cases j with
+ | inl i => exact (totalDegree_rename_le (leftIndex V W) (F i)).trans (hF i)
+ | inr j => exact (totalDegree_rename_le (rightIndex V W) (G j)).trans (hG j)
+
+private theorem coeff_natAbs_rename_le {A B : Type*} (f : A ↪ B) (p : MvPolynomial A ℤ)
+ {M : ℕ} (hp : ∀ e, (p.coeff e).natAbs ≤ M) (e : B →₀ ℕ) :
+ ((rename f p).coeff e).natAbs ≤ M := by
+ by_cases hz : (rename f p).coeff e = 0
+ · simp [hz]
+ · obtain ⟨u, rfl, _⟩ := coeff_rename_ne_zero f p e hz
+ rw [coeff_rename_mapDomain f f.injective]
+ exact hp u
+
+theorem unionEquations_coeff_natAbs_le (F : I → MvPolynomial V ℤ) (G : J → MvPolynomial W ℤ)
+ {B : ℕ} (hF : ∀ i e, ((F i).coeff e).natAbs ≤ B)
+ (hG : ∀ j e, ((G j).coeff e).natAbs ≤ B) (j : I ⊕ J)
+ (e : Fin (Fintype.card (V ⊕ W)) →₀ ℕ) : ((unionEquations F G j).coeff e).natAbs ≤ B := by
+ cases j with
+ | inl i => exact coeff_natAbs_rename_le _ _ (hF i) _
+ | inr j => exact coeff_natAbs_rename_le _ _ (hG j) _
+
+/-- Production labels at the width used for a size `n^c` circuit. -/
+abbrev Production (n c : ℕ) := GrammarLabel (Fin n × Bool) (Fin (n ^ (c + 5))) n
+
+/-- The integer equation `Bₓ - Uₙ(x) = 0` at the designated start state. -/
+noncomputable def grammarEquation {n : ℕ} (hn : 2 ≤ n) (c : ℕ) (x : Fin n → Bool) :
+ MvPolynomial (Production n c) ℤ :=
+ labelQuery ⟨n - 1, by omega⟩ ⟨0, pow_pos (by omega) _⟩ x - C (acceptingCount x : ℤ)
+
+section Motif
+
+variable {Z : Type*} [Fintype Z] [Fintype J] {n : ℕ}
+
+/-- The full integer polynomial system for the production labels and the motif
+matrix entries, in the finite coordinate format of Section 8.2. -/
+noncomputable def equations (hn : 2 ≤ n) (c : ℕ) (G : MotifParameters.Data J Z) :
+ (Fin n → Bool) ⊕ G.Output → MvPolynomial (Fin (Fintype.card (Production n c ⊕ G.Entry))) ℤ :=
+ unionEquations (grammarEquation hn c) G.equation
+
+/-- There is one equation per Boolean input in addition to the fixed output
+coordinates of the motif data. -/
+theorem equation_count [DecidableEq J] (G : MotifParameters.Data J Z) (n : ℕ) :
+ Fintype.card ((Fin n → Bool) ⊕ G.Output) = 2 ^ n + Fintype.card G.Output := by
+ simp
+
+/-- The variable count of the joint system grows polynomially at each fixed
+circuit exponent and fixed motif data. -/
+theorem variable_count_le (G : MotifParameters.Data J Z) (n c : ℕ) :
+ Fintype.card (Production n c ⊕ G.Entry) ≤
+ n ^ (c + 5) * (n * 2) + n ^ 2 * (n ^ (c + 5)) ^ 3 + Fintype.card G.Entry := by
+ rw [Fintype.card_sum]
+ apply Nat.add_le_add_right
+ simpa only [Fintype.card_fin, Fintype.card_prod, Fintype.card_bool] using
+ card_grammarLabel_le (Fin n × Bool) (Fin (n ^ (c + 5))) n
+
+theorem variable_count_polynomiallyBounded (G : MotifParameters.Data J Z) (c : ℕ) :
+ PolynomiallyBounded (fun n => Fintype.card (Production n c ⊕ G.Entry)) := by
+ have hw := PolynomiallyBounded.id.pow (c + 5)
+ exact (((hw.mul (PolynomiallyBounded.id.mul (.const 2))).add
+ ((PolynomiallyBounded.id.pow 2).mul (hw.pow 3))).add (.const _)).of_le
+ (fun n => variable_count_le G n c)
+
+/-- A solution in any commutative ring gives the path counts for every input
+word and specializes the integral motif identities in the same ring. -/
+theorem solution_iff {R : Type*} [CommRing R] (hn : 2 ≤ n) (c : ℕ)
+ (G : MotifParameters.Data J Z) (a : Fin (Fintype.card (Production n c ⊕ G.Entry)) → R) :
+ (∀ j, eval₂Hom (Int.castRingHom R) a (equations hn c G j) = 0) ↔
+ (∀ x : Fin n → Bool, eval₂Hom (Int.castRingHom R) (a ∘ leftIndex (Production n c) G.Entry)
+ (labelQuery ⟨n - 1, by omega⟩ ⟨0, pow_pos (by omega) _⟩ x) = (acceptingCount x : R)) ∧
+ G.IsSolution (a ∘ rightIndex (Production n c) G.Entry) := by
+ rw [equations, unionEquations_solution_iff]
+ simp [grammarEquation, MotifParameters.Data.IsSolution, sub_eq_zero]
+
+/-- An actual small circuit and a solution of the fixed local motif equations
+give a joint solution in the circuit's coefficient ring. -/
+theorem exists_solution {R : Type*} [CommRing R] {c s : ℕ} (hn : 2 ≤ n) (hc : 1 ≤ c)
+ (hs : s ≤ n ^ c) (circuit : Circuit R (Fin n × Bool) s)
+ (hpoly : circuit.polynomial = map (Int.castRingHom R) (P n))
+ (G : MotifParameters.Data J Z) (κ : G.Entry → R) (hκ : G.IsSolution κ) :
+ ∃ a : Fin (Fintype.card (Production n c ⊕ G.Entry)) → R,
+ ∀ j, eval₂Hom (Int.castRingHom R) a (equations hn c G j) = 0 := by
+ obtain ⟨labels, hl⟩ := pathCount_labelEquations hn hc hs circuit hpoly
+ refine ⟨joinAssignment labels κ, (solution_iff hn c G _).mpr ?_⟩
+ simpa only [joinAssignment_left, joinAssignment_right] using And.intro hl hκ
+
+end Motif
+
+end JointLabelSystem
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarCircuit.lean b/lean/OAI/Computability/VPVNP/JointScalarCircuit.lean
new file mode 100644
index 0000000000..f655d89132
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarCircuit.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.JointScalarCore
+import OAI.Computability.VPVNP.JointScalarMotifCircuit
+
+/-!
+# The advised signed scalar checker
+
+This Boolean circuit takes the raw binary equation address, the formal
+exponent array, and a polarity bit. Its witness banks are counted by the
+fixed bit-stack enumerator. Inactive banks are forced to zero, preserving
+the number of accepting witnesses on the selected branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar
+
+open VerifierNetwork ParseGrammar
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+ (Expr.eval Expr.size Expr.and Expr.mux Expr.eval_mux Expr.disjoin Expr.eval_disjoin_true Expr.size_disjoin_le
+ Expr.eval_rename Expr.size_rename)
+open scoped Classical
+
+variable {n high t W flags clock motif g m q : ℕ}
+
+/-- Wire the parse verifier to the low equation-address bits, the formal exponent array and the
+parse-event flags of the joint checker. -/
+def parseWire : ParseOracle.Input n t W flags → Input n high t W flags clock motif :=
+ Sum.elim (Fin.addCases (fun j => rowWire (j.castAdd high))
+ (fun j => let jb := finProdFinEquiv.symm j; exponentWire jb.1 jb.2)) flagWire
+
+/-- Wire the universal-machine path verifier to the low equation-address bits and the clocked
+choice bits of the joint checker. -/
+def pathWire : Fin n ⊕ Fin clock → Input n high t W flags clock motif :=
+ Sum.elim (fun j => rowWire (j.castAdd high)) choiceWire
+
+private theorem assign_parse (negative : Bool) (row : ℕ) (a : Fin t → ℕ) (f : Fin flags → Bool)
+ (u : Fin clock → Bool) (b : Fin motif → Bool) :
+ assignment (n := n) (high := high) (W := W) negative row a f u b ∘ parseWire =
+ Sum.elim (ParseOracle.query (fun j => row.testBit j.val) a W) f := by
+ funext i
+ rcases i with i | i
+ · refine Fin.addCases (fun j => ?_) (fun j => ?_) i <;>
+ simp [parseWire, ParseOracle.query]
+ · simp [parseWire]
+
+private theorem assign_path (negative : Bool) (row : ℕ) (a : Fin t → ℕ) (f : Fin flags → Bool)
+ (u : Fin clock → Bool) (b : Fin motif → Bool) :
+ assignment (n := n) (high := high) (W := W) negative row a f u b ∘ pathWire =
+ Sum.elim (fun j => row.testBit j.val) u := by
+ funext i
+ cases i <;> simp [pathWire]
+
+/-- Boolean expression testing whether every supplied fixed-width exponent word represents
+zero. -/
+def zeroWords {σ : Type*} (wire : Fin m → Fin W → σ) : Expr σ :=
+ .not (Expr.disjoin (List.ofFn fun i => .not (OracleBinaryTarget.expr (wire i) 0)))
+
+private theorem zeroWords_eval {σ : Type*} (wire : Fin m → Fin W → σ) (a : Fin m → ℕ)
+ (ha : ∀ i, a i < 2^W) (x : σ → Bool) (hx : ∀ i j, x (wire i j) = (a i).testBit j.val) :
+ (zeroWords wire).eval x = decide (∀ i, a i = 0) := by
+ apply Bool.eq_iff_iff.mpr
+ rw [decide_eq_true_eq]
+ simp only [zeroWords, Expr.eval, Bool.not_eq_true']
+ rw [Bool.eq_false_iff]
+ change (¬ (Expr.disjoin _).eval x = true) ↔ _
+ rw [Expr.eval_disjoin_true]
+ simp only [List.mem_ofFn, exists_exists_eq_and, Expr.eval, Bool.not_eq_true',
+ OracleBinaryTarget.expr_eval _ _ _ (ha _) x (hx _), decide_eq_false_iff_not, not_exists, not_not]
+
+/-- The two Boolean outputs retained from the parse verifier and the clocked path verifier. -/
+abbrev Checks := Unit ⊕ Unit
+
+/-- Formal coordinate placements are encoded in the circuit wiring. The
+negative grammar branch is enabled precisely for the zero exponent. -/
+def finish (prod : Fin g → Fin t) (localMap : Fin m → Fin t)
+ (tables : Fin q → Motif.Table m) :
+ Expr (Input n high t W flags clock motif ⊕ Checks) :=
+ let raw : Input n high t W flags clock motif → _ := Sum.inl
+ let gram := Motif.below (raw ∘ rowWire) (2^n)
+ let maskProd := zeroWords fun i j => raw (exponentWire (prod i) j)
+ let maskMotif := zeroWords fun i j => raw (exponentWire (localMap i) j)
+ let maskAll := zeroWords fun i j => raw (exponentWire i j)
+ let padF := allZero (raw ∘ flagWire)
+ let padU := allZero (raw ∘ choiceWire)
+ let padM := allZero (raw ∘ motifWire)
+ let pos := Expr.and (.input (.inr (.inl ()))) (.and maskMotif (.and padU padM))
+ let neg := Expr.and (.input (.inr (.inr ()))) (.and maskAll (.and padF padM))
+ let getRow := fun j : Fin q => OracleBinaryTarget.expr (raw ∘ rowWire) (2^n + j.val)
+ let mt := Motif.expr tables getRow (fun i j => raw (exponentWire (localMap i) j)) (raw polarity) (raw ∘ motifWire)
+ Expr.mux gram (Expr.mux (.input (raw polarity)) neg pos) (.and mt (.and maskProd (.and padF padU)))
+
+/-- Use the actual grammar and clock circuits as shared subcircuits on the
+same raw inputs. -/
+noncomputable def frame (prod : Fin g → Fin t) (localMap : Fin m → Fin t)
+ (tables : Fin q → Motif.Table m) (parse : Frame (ParseOracle.Input n t W flags) Unit)
+ (path : Frame (Fin n ⊕ Fin clock) Unit) : Frame (Input n high t W flags clock motif) Unit :=
+ let checks := parallel (parse.subst (Frame.initial parseWire)) (path.subst (Frame.initial pathWire))
+ checks.withInput.step fun _ : Unit => finish prod localMap tables
+
+private theorem frame_eval (prod : Fin g → Fin t) (localMap : Fin m → Fin t)
+ (tables : Fin q → Motif.Table m) (parse : Frame (ParseOracle.Input n t W flags) Unit)
+ (path : Frame (Fin n ⊕ Fin clock) Unit) (x : Input n high t W flags clock motif → Bool) :
+ (frame prod localMap tables parse path).eval x () =
+ (finish prod localMap tables).eval (Sum.elim x (Sum.elim
+ (parse.eval (x ∘ parseWire)) (path.eval (x ∘ pathWire)))) := by
+ rw [frame, Frame.step_eval]
+ congr 1
+ funext i
+ rcases i with i | (i | i) <;> simp [Function.comp_def]
+ all_goals
+ congr 1
+ funext j
+ simp
+
+private theorem all_false_iff {α : Type*} (f : α → Bool) : (∀ i, f i = false) ↔ f = fun _ => false :=
+ funext_iff.symm
+
+/-- On a grammar row the sign bit selects either the positive parse count or
+the negative constant path count. -/
+theorem eval_grammar (prod : Fin g → Fin t) (localMap : Fin m → Fin t)
+ (tables : Fin q → Motif.Table m) (parse : Frame (ParseOracle.Input n t W flags) Unit)
+ (path : Frame (Fin n ⊕ Fin clock) Unit) (negative : Bool) (row : ℕ) (hr : row < 2^n)
+ (a : Fin t → ℕ) (ha : ∀ j, a j < 2^W) (f : Fin flags → Bool)
+ (u : Fin clock → Bool) (b : Fin motif → Bool) :
+ (frame (high := high) prod localMap tables parse path).eval (assignment negative row a f u b) () =
+ if negative then
+ path.eval (Sum.elim (fun j => row.testBit j.val) u) () &&
+ decide ((∀ j, a j = 0) ∧ f = (fun _ => false) ∧ b = (fun _ => false))
+ else
+ parse.eval (Sum.elim (ParseOracle.query (fun j => row.testBit j.val) a W) f) () &&
+ decide ((∀ j, a (localMap j) = 0) ∧ u = (fun _ => false) ∧ b = (fun _ => false)) := by
+ have hfit := hr.trans_le (Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.le_add_right n high))
+ rw [frame_eval, assign_parse, assign_path]
+ simp only [finish, Expr.eval_mux]
+ rw [Motif.below_eval _ _ row hfit _ (fun j => by simp)]
+ simp only [hr, decide_true, ite_true, Expr.eval, Sum.elim_inl, Sum.elim_inr, assignment_polarity]
+ rw [zeroWords_eval _ a ha _ (by simp), zeroWords_eval _ (fun i => a (localMap i)) (fun i => ha _) _ (by simp)]
+ simp [allZero_eval, Function.comp_def, all_false_iff]
+
+/-- On a fixed row the signed coefficient is counted by an unsigned witness
+comparison. The two machine banks contribute their unique all-zero strings. -/
+theorem eval_motif (prod : Fin g → Fin t) (localMap : Fin m → Fin t)
+ (tables : Fin q → Motif.Table m) (parse : Frame (ParseOracle.Input n t W flags) Unit)
+ (path : Frame (Fin n ⊕ Fin clock) Unit) (negative : Bool) (o : Fin q)
+ (hr : 2^n + o.val < 2^(n+high)) (a : Fin t → ℕ) (ha : ∀ j, a j < 2^W) (f : Fin flags → Bool)
+ (u : Fin clock → Bool) (v : Fin (2^motif)) :
+ (frame (high := high) prod localMap tables parse path).eval
+ (assignment negative (2^n+o.val) a f u (RAMSerialization.wordBits motif v)) () =
+ decide (v.val < Motif.part negative (JointLabelSystem.FixedRows.tableLookup (tables o) (a ∘ localMap)) ∧
+ (∀ i, a (prod i) = 0) ∧ f = (fun _ => false) ∧ u = (fun _ => false)) := by
+ rw [frame_eval, assign_parse, assign_path]
+ simp only [finish, Expr.eval_mux]
+ rw [Motif.below_eval _ _ (2^n + o.val) hr _ (fun j => by simp)]
+ simp only [Nat.not_lt_of_ge (Nat.le_add_right ..), decide_false, Bool.false_eq_true, ite_false, Expr.eval]
+ rw [zeroWords_eval _ (fun i => a (prod i)) (fun i => ha _) _ (by simp)]
+ rw [Motif.eval_selected _ _ _ _ _ o (a ∘ localMap) v.val (fun i => ha _) v.isLt _ ?_ ?_ ?_]
+ · simp [allZero_eval, Function.comp_def, all_false_iff]
+ rfl
+ · intro j
+ rw [OracleBinaryTarget.expr_eval _ _ (2^n + o.val) hr _ (by simp)]
+ simp [Fin.ext_iff, eq_comm]
+ · simp
+ · intro j
+ simpa using (LiveHeader.testBit_wordBits v j).symm
+
+end JointScalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarCore.lean b/lean/OAI/Computability/VPVNP/JointScalarCore.lean
new file mode 100644
index 0000000000..8dc781f005
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarCore.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.ParseOracleResources
+import OAI.Computability.VPVNP.LiveHeaderBits
+
+/-!
+# Gates and bit addresses of the joint scalar query
+
+The input contains the sign selector, the unsigned equation address, and one
+fixed-width exponent per formal coordinate. Witnesses for the parse, the
+clocked computation, and the fixed motif comparison occupy separate banks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar
+
+open VerifierNetwork
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit (Expr.eval Expr.size Expr.disjoin Expr.eval_disjoin_true Expr.size_disjoin_le Expr.input)
+
+/-- Evaluate two verifier frames on a shared input and expose both sets of outputs, indexed by
+their disjoint union. -/
+noncomputable def parallel {X A B : Type*} [Fintype X] [Fintype A] [Fintype B]
+ (p : Frame X A) (q : Frame X B) : Frame X (A ⊕ B) :=
+ let retained := (q.subst (Frame.initial (Sum.inl : X → X ⊕ A))).withInput.subst p.withInput
+ retained.select (Sum.elim (Sum.inl ∘ Sum.inr) Sum.inr)
+
+@[simp] theorem parallel_eval {X A B : Type*} [Fintype X] [Fintype A] [Fintype B]
+ (p : Frame X A) (q : Frame X B) (x : X → Bool) (i : A ⊕ B) :
+ (parallel p q).eval x i = Sum.elim (p.eval x) (q.eval x) i := by
+ cases i with
+ | inl i => simp [parallel]
+ | inr i =>
+ simp only [parallel, Frame.select_eval, Sum.elim_inr, Frame.subst_eval, Frame.withInput_eval_inr]
+ congr 1
+ funext j
+ simp
+
+@[simp] theorem parallel_size {X A B : Type*} [Fintype X] [Fintype A] [Fintype B]
+ (p : Frame X A) (q : Frame X B) : (parallel p q).size = p.size + q.size := by simp [parallel]
+
+/-- A linear-size conjunction checking that every specified bit is zero. -/
+def allZero {X : Type*} {k : ℕ} (wire : Fin k → X) : Expr X :=
+ .not (Expr.disjoin (List.ofFn fun j => .input (wire j)))
+
+theorem allZero_eval {X : Type*} {k : ℕ} (wire : Fin k → X) (x : X → Bool) :
+ (allZero wire).eval x = decide (∀ j, x (wire j) = false) := by
+ apply Bool.eq_iff_iff.mpr
+ rw [decide_eq_true_eq]
+ rw [allZero, Expr.eval, Bool.not_eq_true', Bool.eq_false_iff]
+ change ¬(_ = true) ↔ _
+ rw [Expr.eval_disjoin_true]
+ simp only [List.mem_ofFn, exists_exists_eq_and, Expr.eval, not_exists, Bool.not_eq_true]
+
+theorem allZero_size {X : Type*} {k : ℕ} (wire : Fin k → X) :
+ (allZero wire).size ≤ 2*k + 2 := by
+ have h := Expr.size_disjoin_le (List.ofFn fun j => Expr.input (wire j)) 1 (by
+ intro e he
+ obtain ⟨j,rfl⟩ := List.mem_ofFn.mp he
+ rfl)
+ simp only [List.length_ofFn] at h
+ change _ + 1 ≤ _
+ omega
+
+/-- Number of bits for the sign selector, equation address and fixed-width array of formal
+exponents. -/
+abbrev queryWidth (n high t W : ℕ) := 1 + ((n + high) + t * W)
+/-- Combined width of the parse flags, clocked computation choices and motif coefficient
+witness. -/
+abbrev witnessWidth (flags clock motif : ℕ) := flags + (clock + motif)
+/-- Input addresses of the signed coefficient checker, divided between the coefficient query
+and its witness. -/
+abbrev Input (n high t W flags clock motif : ℕ) :=
+ Fin (queryWidth n high t W) ⊕ Fin (witnessWidth flags clock motif)
+
+section
+
+variable {n high t W flags clock motif : ℕ}
+
+/-- First query wire, which selects the positive or negative part of the requested coefficient. -/
+def polarity : Input n high t W flags clock motif := .inl 0
+
+/-- Query wire carrying a specified little-endian bit of the joint equation address. -/
+def rowWire (j : Fin (n + high)) : Input n high t W flags clock motif :=
+ .inl ((j.castAdd (t*W)).natAdd 1)
+
+/-- Query wire carrying bit `b` of the fixed-width exponent of formal label `j`. -/
+def exponentWire (j : Fin t) (b : Fin W) : Input n high t W flags clock motif :=
+ .inl (((finProdFinEquiv (j,b)).natAdd (n+high)).natAdd 1)
+
+/-- Witness wire carrying one parse-event flag at the start of the witness array. -/
+def flagWire (j : Fin flags) : Input n high t W flags clock motif := .inr (j.castAdd (clock+motif))
+/-- Witness wire carrying one clocked machine choice after the parse-event flags. -/
+def choiceWire (j : Fin clock) : Input n high t W flags clock motif := .inr ((j.castAdd motif).natAdd flags)
+/-- Witness wire carrying one bit of the motif coefficient witness after the parse and
+clocked-choice fields. -/
+def motifWire (j : Fin motif) : Input n high t W flags clock motif := .inr ((j.natAdd clock).natAdd flags)
+
+/-- Physical little-endian row and exponent words. The sign bit is the head. -/
+def query (negative : Bool) (row : ℕ) (a : Fin t → ℕ) : Fin (queryWidth n high t W) → Bool :=
+ Fin.append (fun _ : Fin 1 => negative)
+ (Fin.append (fun j : Fin (n + high) => row.testBit j.val)
+ (fun j : Fin (t*W) => (a (finProdFinEquiv.symm j).1).testBit (finProdFinEquiv.symm j).2.val))
+
+/-- The physical witness bit string has the three banks in this order. -/
+def witnesses (f : Fin flags → Bool) (u : Fin clock → Bool) (m : Fin motif → Bool) :
+ Fin (witnessWidth flags clock motif) → Bool := Fin.append f (Fin.append u m)
+
+/-- Supply the signed row and exponent query together with the parse, clock and motif witness
+bits to the checker. -/
+def assignment (negative : Bool) (row : ℕ) (a : Fin t → ℕ) (f : Fin flags → Bool)
+ (u : Fin clock → Bool) (m : Fin motif → Bool) : Input n high t W flags clock motif → Bool :=
+ Sum.elim (query negative row a) (witnesses f u m)
+
+variable (negative : Bool) (row : ℕ) (a : Fin t → ℕ) (f : Fin flags → Bool)
+ (u : Fin clock → Bool) (m : Fin motif → Bool)
+
+@[simp] theorem assignment_polarity :
+ assignment (n := n) (high := high) (W := W) negative row a f u m polarity = negative := rfl
+
+@[simp] theorem assignment_rowWire (j : Fin (n+high)) :
+ assignment (W := W) negative row a f u m (rowWire j) = row.testBit j.val := by
+ simp [assignment, query, rowWire]
+
+@[simp] theorem assignment_exponentWire (j : Fin t) (b : Fin W) :
+ assignment (n := n) (high := high) negative row a f u m (exponentWire j b) = (a j).testBit b.val := by
+ simp only [assignment, exponentWire, query, Sum.elim_inl, Fin.append_right, Equiv.symm_apply_apply]
+
+@[simp] theorem assignment_flagWire (j : Fin flags) :
+ assignment (n := n) (high := high) (W := W) negative row a f u m (flagWire j) = f j := by
+ simp [assignment, witnesses, flagWire]
+
+@[simp] theorem assignment_choiceWire (j : Fin clock) :
+ assignment (n := n) (high := high) (W := W) negative row a f u m (choiceWire j) = u j := by
+ simp [assignment, witnesses, choiceWire]
+
+@[simp] theorem assignment_motifWire (j : Fin motif) :
+ assignment (n := n) (high := high) (W := W) negative row a f u m (motifWire j) = m j := by
+ simp [assignment, witnesses, motifWire]
+
+end
+
+/-- Split a sum over joint witnesses into three independent sums in physical
+bit order. This permits zero padding on every inactive bank without changing
+the number of accepted witnesses. -/
+theorem sum_witnesses {a b c : ℕ} (p : (Fin (witnessWidth a b c) → Bool) → ℕ) :
+ (∑ w, p w) = ∑ f : Fin a → Bool, ∑ u : Fin b → Bool, ∑ m : Fin c → Bool, p (witnesses f u m) := by
+ let join (a b : ℕ) : ((Fin a → Bool) × (Fin b → Bool)) ≃ (Fin (a+b) → Bool) :=
+ (Equiv.sumArrowEquivProdArrow (Fin a) (Fin b) Bool).symm.trans (finSumFinEquiv.arrowCongr (Equiv.refl _))
+ have h (a b : ℕ) (f : Fin a → Bool) (u : Fin b → Bool) : join a b (f,u) = Fin.append f u := by
+ funext i
+ refine Fin.addCases (fun i => ?_) (fun i => ?_) i <;> simp [join]
+ rw [← (join a (b+c)).sum_comp p, Fintype.sum_prod_type]
+ apply Finset.sum_congr rfl
+ intro f _
+ rw [← (join b c).sum_comp (fun w => p (join a (b+c) (f,w))), Fintype.sum_prod_type]
+ simp only [h, witnesses]
+
+end JointScalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarCount.lean b/lean/OAI/Computability/VPVNP/JointScalarCount.lean
new file mode 100644
index 0000000000..2bf10fa228
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarCount.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.JointScalarCircuit
+
+/-!
+# Counting the witnesses of the signed joint row checker
+
+Fixing the row address selects one witness bank. The other two banks must be
+all zero, so summing the physical bit witnesses gives precisely the active
+count. Both signs of each motif coefficient use the same comparison table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar
+
+open VerifierNetwork JointLabelSystem.FixedRows
+
+variable {n high t W flags clock motif g m q : ℕ}
+variable (prod : Fin g → Fin t) (localMap : Fin m → Fin t) (tables : Fin q → Motif.Table m)
+variable (parse : Frame (ParseOracle.Input n t W flags) Unit) (path : Frame (Fin n ⊕ Fin clock) Unit)
+
+private theorem assignment_eq (neg : Bool) (row : ℕ) (a : Fin t → ℕ) (f : Fin flags → Bool)
+ (u : Fin clock → Bool) (b : Fin motif → Bool) :
+ Sum.elim (query (n := n) (high := high) (W := W) neg row a) (witnesses f u b) = assignment neg row a f u b := rfl
+
+private theorem bool_count_and (b : Bool) (p : Prop) [Decidable p] :
+ (b && decide p).toNat = if p then b.toNat else 0 := by
+ by_cases hp : p <;> simp [hp]
+
+theorem count_grammar (negative : Bool) (row : ℕ) (hr : row < 2^n)
+ (a : Fin t → ℕ) (ha : ∀ j, a j < 2^W) :
+ (∑ w, (((frame (high := high) (motif := motif) prod localMap tables parse path).circuit ()).eval
+ (Sum.elim (query negative row a) w)).toNat) =
+ if negative then
+ (if ∀ j, a j = 0 then
+ ∑ u, (path.eval (Sum.elim (fun j => row.testBit j.val) u) ()).toNat else 0)
+ else
+ (if ∀ j, a (localMap j) = 0 then
+ ∑ f, (parse.eval (Sum.elim (ParseOracle.query (fun j => row.testBit j.val) a W) f) ()).toNat else 0) := by
+ classical
+ rw [sum_witnesses]
+ simp only [Frame.circuit_eval, assignment_eq, eval_grammar prod localMap tables parse path negative row hr a ha]
+ cases negative with
+ | false =>
+ simp only [Bool.false_eq_true, ite_false, bool_count_and]
+ by_cases hm : ∀ j, a (localMap j) = 0
+ · simp [hm, ite_and]
+ · simp [hm]
+ | true =>
+ simp only [ite_true, bool_count_and]
+ by_cases hm : ∀ j, a j = 0
+ · simp [hm, ite_and]
+ · simp [hm]
+
+theorem count_motif (negative : Bool) (o : Fin q) (hr : 2^n+o.val < 2^(n+high))
+ (a : Fin t → ℕ) (ha : ∀ j, a j < 2^W)
+ (hfit : Motif.part negative (tableLookup (tables o) (a ∘ localMap)) ≤ 2^motif) :
+ (∑ w, (((frame (motif := motif) prod localMap tables parse path).circuit ()).eval
+ (Sum.elim (query (high := high) negative (2^n+o.val) a) w)).toNat) =
+ if ∀ i, a (prod i) = 0 then Motif.part negative (tableLookup (tables o) (a ∘ localMap)) else 0 := by
+ classical
+ let M := Motif.part negative (tableLookup (tables o) (a ∘ localMap))
+ rw [sum_witnesses]
+ have hinner (f : Fin flags → Bool) (u : Fin clock → Bool) :
+ (∑ b : Fin motif → Bool, (((frame (high := high) prod localMap tables parse path).circuit ()).eval
+ (assignment negative (2^n+o.val) a f u b)).toNat) =
+ if (∀ i, a (prod i) = 0) ∧ f = (fun _ => false) ∧ u = (fun _ => false) then M else 0 := by
+ rw [← (RAMSerialization.wordBits motif).sum_comp]
+ simp only [Frame.circuit_eval, eval_motif prod localMap tables parse path negative o hr a ha]
+ by_cases h : (∀ i, a (prod i) = 0) ∧ f = (fun _ => false) ∧ u = (fun _ => false)
+ · rw [ite_eq_left h]
+ simp only [h, and_true, implies_true]
+ calc
+ _ = ∑ v : Fin (2^motif), if v.val < M then 1 else 0 := Finset.sum_congr rfl fun v _ => by
+ change (decide (v.val < M)).toNat = _
+ by_cases hv : v.val < M <;> simp [hv]
+ _ = M := by
+ rw [Finset.sum_boole, ← Fintype.card_subtype (fun v : Fin (2^motif) => v.val < M)]
+ exact Fintype.card_fin_lt_of_le hfit
+ · simp [h]
+ simp only [assignment_eq, hinner]
+ by_cases hp : ∀ i, a (prod i) = 0
+ · simp [hp, ite_and, M]
+ · simp [hp]
+
+end JointScalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarLeaf.lean b/lean/OAI/Computability/VPVNP/JointScalarLeaf.lean
new file mode 100644
index 0000000000..cafd4490b9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarLeaf.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.JointScalarLeafCall
+import OAI.Computability.VPVNP.JointScalarLeafEncoding
+
+/-! # Returning field-scalar query for the grammar and local motif equations
+
+The input words carry the decoded equation number and the residual monomial.
+Both remain available after the call. One fixed finite program returns the
+formal integer coefficient cast to the presented scalar ring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar.Leaf
+
+open MvPolynomial RAMTape UniversalCountStack JointLabelSystem RadicalCertificate.MonomialIndex
+
+variable (V I : Type*) [Fintype V] [Fintype I] (F : I → MvPolynomial V ℤ) {n : ℕ} (c : ℕ)
+
+/-- Immutable advice for the signed coefficient callback. -/
+noncomputable def layout (hn : 2 ≤ n) (W p e v : ℕ) : Layout where
+ prime := p
+ degree := e
+ limbWidth := v
+ rowBits := n + highWidth I
+ witnessBits := witnessWidth (ParseOracle.Flags n n (Fin (n^(c+5)))) (n^clockExponent) (motifWidth V I F)
+ circuitAdvice := AdviceCircuit.encode (AdviceCircuit.compile (checker V I F c hn W))
+
+set_option maxHeartbeats 1600000 in
+/-- The two counts and the field conversion are actual nested calls in the
+finite machine, with separate bounds on time and maximum stack height. -/
+theorem coefficient_bounded (hn : 2 ≤ n) (W : ℕ) {p e v : ℕ} [Fact p.Prime] [NeZero e]
+ (modulus : SliceArithmetic.Vector p e) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (wr : ℕ) (row : Fin (2^n + Fintype.card I)) (hj : row.val < 2^wr)
+ (a : Fin (FixedRows.labelTotal V n c) → ℕ) (ha : ∀ i, a i < 2^W) :
+ let C := checker V I F c hn W
+ let L := layout V I F c hn W p e v
+ let b := bankSize L wr (FixedRows.labelTotal V n c * W)
+ let k := localCost L b
+ let z := (unionEquations (grammarEquation hn c) F (FixedRows.rowIndex I n row)).coeff (exponentVector a)
+ ∃ steps ≤ 2*(2^L.witnessBits * perChoice C) + k,
+ machine.BoundedRun (max (stackLimit C) b + k) steps
+ (clean L (digits wr row.val) (packed W a) [])
+ (clean L (digits wr row.val) (packed W a) (RankQuery.Stack.Engine.scalar v (z : RankQuery.Stack.Scalar modulus))) := by
+ intro C L b k z
+ have signed (s : Bool) : TapeWord.value (digits (L.witnessBits+1) (Motif.part s z)) = Motif.part s z :=
+ scalar_digits_value V I F c hn W row s a ha
+ have joint := call_bounded modulus hv L rfl rfl rfl wr row.val hj (packed W a)
+ (fun s => Motif.part s z) z (stackLimit C) (2^L.witnessBits*perChoice C) (fun s => by
+ have eq : s :: (digits L.rowBits row.val ++ packed W a) =
+ List.ofFn (query (n := n) (high := highWidth I) (W := W) s row.val a) :=
+ (query_bits n (highWidth I) W s row.val a).symm
+ rw [eq]
+ dsimp only [L, layout, C, z, Layout.witnessBits, Layout.circuitAdvice]
+ exact scalar_runs V I F c hn W row s a ha)
+ (by rw [signed false,signed true]; exact signedParts_sub z)
+ have hlen := packed_length W a
+ rw [hlen] at joint
+ exact joint
+
+end JointScalar.Leaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarLeafCall.lean b/lean/OAI/Computability/VPVNP/JointScalarLeafCall.lean
new file mode 100644
index 0000000000..cb1513bef6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarLeafCall.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.JointScalarLeafPrepare
+
+/-! # Composing the two count calls and the signed field conversion -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar.Leaf
+
+open RAMTape UniversalCountStack
+
+/-- The same finite control is used for every row, modulus, and circuit. -/
+def machine : FiniteRoutine Port :=
+ ((((((load.followedBy prependRow).followedBy (pushSign false)).followedBy (counter false)).followedBy
+ switchSign).followedBy (counter true)).followedBy reduce).followedBy cleanup
+
+/-- Maximum of the static and live words needed at subroutine boundaries. -/
+def bankSize (L : Layout) (wr payload : ℕ) :=
+ wr + payload + L.rowBits + L.witnessBits + L.limbWidth + L.degree + L.degree*L.limbWidth +
+ L.circuitAdvice.length + 2
+
+/-- All work except the two witness enumerations, including their field conversion. -/
+def localCost (L : Layout) (b : ℕ) :=
+ (4*(5*b+2)+1) + (9*L.rowBits+3) + 3 + (4*(b+1)+1) +
+ (2*(L.witnessBits+1) + L.degree + L.limbWidth) +
+ SliceArithmeticSignedCount.callCap (L.witnessBits+1) (L.witnessBits+1) L.degree L.limbWidth
+
+private theorem bank_le (L : Layout) (row payload q ch pos neg result : List Bool)
+ (b : ℕ) (hrow : row.length ≤ b) (hpayload : payload.length ≤ b) (hq : q.length ≤ b)
+ (hc : ch.length ≤ b) (hp : pos.length ≤ b) (hn : neg.length ≤ b) (hr : result.length ≤ b)
+ (ha : L.circuitAdvice.length ≤ b) (hw : L.rowBits ≤ b) (hk : L.witnessBits+1 ≤ b)
+ (hv : L.limbWidth ≤ b) (he : L.degree ≤ b) : ∀ j, (bank L row payload q ch pos neg result j).length ≤ b := by
+ intro j
+ cases j with
+ | count i => cases i with
+ | aux i => cases i <;> first | exact hq | exact ha | exact Nat.zero_le _
+ | _ => first | exact hc | exact Nat.zero_le _
+ | arithmetic i =>
+ rcases i with i|i
+ · cases i with
+ | divide j => cases j <;> exact Nat.zero_le _
+ | _ => exact Nat.zero_le _
+ · cases i <;> first | exact hp | exact hn | exact hr | simpa [bank, SliceArithmeticSignedCount.clean,
+ SliceArithmeticSignedCount.frame, SliceArithmeticSignedCount.external] using hv |
+ simpa [bank, SliceArithmeticSignedCount.clean, SliceArithmeticSignedCount.frame,
+ SliceArithmeticSignedCount.external] using he
+ | row => exact hrow
+ | packed => exact hpayload
+ | rowWidth => simpa [bank] using hw
+ | blankChoice => simpa [bank] using (show L.witnessBits ≤ b by omega)
+ | blankTotal => simpa [bank] using hk
+ | saved | staged => exact Nat.zero_le _
+
+/-- Every immutable width template and circuit advice stack in the
+initial coefficient bank fits its live-space budget. -/
+theorem clean_length_le (L : Layout) (wr payload : ℕ) (i : Port) :
+ (clean L [] [] [] i).length ≤ bankSize L wr payload := by
+ apply bank_le
+ all_goals simp [bankSize] <;> omega
+
+private theorem short_bounded {r : FiniteRoutine Port} {steps b cap : ℕ} {s u : Stacks Port}
+ (run : r.Runs steps s u) (room : ∀ i, (s i).length ≤ b) (hc : b+steps ≤ cap) :
+ r.BoundedRun cap steps s u :=
+ spaceRun_of_steps run fun i => (Nat.add_le_add_right (room i) steps).trans hc
+
+/-- Frame-preserving composition with separate count time and space bounds. -/
+theorem call_bounded {p e v : ℕ} [Fact p.Prime] [NeZero e] (modulus : SliceArithmetic.Vector p e)
+ (hv : SliceArithmetic.Word.workingWidth p ≤ v) (L : Layout) (hp : L.prime = p)
+ (he : L.degree = e) (hw : L.limbWidth = v) (wr j : ℕ) (hj : j < 2^wr) (payload : List Bool)
+ (value : Bool → ℕ) (z : ℤ) (countSpace countTime : ℕ)
+ (counts : ∀ sign, ∃ ticks ≤ countTime, SpaceRun countCircuit.standalone countSpace ticks
+ (some countCircuit.entry) (UniversalCountStack.bank
+ (AdviceCountAdapter.inputs (sign :: (digits L.rowBits j ++ payload)) L.circuitAdvice)
+ (digits L.witnessBits 0) (digits (L.witnessBits+1) 0) [] []) none
+ (UniversalCountStack.bank
+ (AdviceCountAdapter.inputs (sign :: (digits L.rowBits j ++ payload)) L.circuitAdvice)
+ (digits L.witnessBits 0) (digits (L.witnessBits+1) (value sign)) [] []))
+ (signed : (TapeWord.value (digits (L.witnessBits+1) (value false)) : ℤ) -
+ (TapeWord.value (digits (L.witnessBits+1) (value true)) : ℤ) = z) :
+ let b := bankSize L wr payload.length
+ let k := localCost L b
+ ∃ steps ≤ 2*countTime+k, machine.BoundedRun (max countSpace b+k) steps
+ (clean L (digits wr j) payload [])
+ (clean L (digits wr j) payload (RankQuery.Stack.Engine.scalar v (z : RankQuery.Stack.Scalar modulus))) := by
+ intro b k
+ let cap := max countSpace b+k
+ let row := digits wr j
+ let q := digits L.rowBits j ++ payload
+ let ch := digits L.witnessBits 0
+ let zero := digits (L.witnessBits+1) 0
+ let out (s : Bool) := digits (L.witnessBits+1) (value s)
+ let bits := RankQuery.Stack.Engine.scalar v (z : RankQuery.Stack.Scalar modulus)
+ have hrow : row.length ≤ b := by simp [row,b,bankSize]; omega
+ have hpay : payload.length ≤ b := by dsimp [b,bankSize]; omega
+ have hrowbits : L.rowBits ≤ b := by dsimp [b,bankSize]; omega
+ have hwit : L.witnessBits+1 ≤ b := by dsimp [b,bankSize]; omega
+ have hv' : L.limbWidth ≤ b := by dsimp [b,bankSize]; omega
+ have he' : L.degree ≤ b := by dsimp [b,bankSize]; omega
+ have hadv : L.circuitAdvice.length ≤ b := by dsimp [b,bankSize]; omega
+ have hq : q.length+1 ≤ b := by simp [q,b,bankSize]; omega
+ have hch : ch.length ≤ b := by simp [ch]; omega
+ have hz : zero.length ≤ b := by simpa [zero] using hwit
+ have hout (s) : (out s).length ≤ b := by simpa [out] using hwit
+ have hbits : bits.length ≤ b := by simp [bits,b,bankSize,he,hw]; omega
+ have hbank (q' ch' p' n' r' : List Bool) (hq' : q'.length ≤ b) (hc : ch'.length ≤ b)
+ (hp' : p'.length ≤ b) (hn : n'.length ≤ b) (hr : r'.length ≤ b) :=
+ bank_le L row payload q' ch' p' n' r' b hrow hpay hq' hc hp' hn hr hadv hrowbits hwit hv' he'
+ have hcspace : countSpace ≤ cap := by dsimp [cap]; omega
+ have hbc : b+k ≤ cap := by dsimp [cap]; omega
+ have hbc' : b ≤ cap := by omega
+ obtain ⟨ta,hta,ra⟩ := load_runs L row payload [] b hpay hwit
+ obtain ⟨tb,htb,rb⟩ := prefix_runs L wr j hj payload payload ch zero zero []
+ have rc := pushSign_runs L row payload q ch zero zero [] false
+ have a := short_bounded ra (hbank [] [] [] [] [] (by simp) (by simp) (by simp) (by simp) (by simp))
+ (cap := cap) (by dsimp [k,localCost] at hbc; omega)
+ have b' := short_bounded rb (hbank payload ch zero zero [] hpay hch hz hz (by simp))
+ (cap := cap) (by dsimp [k,localCost] at hbc; omega)
+ have c' := short_bounded rc (hbank q ch zero zero [] (by omega) hch hz hz (by simp))
+ (cap := cap) (by dsimp [k,localCost] at hbc; omega)
+ have hqs (s : Bool) : (s::q).length ≤ b := by simpa using hq
+ have hbankCap (q' ch' p' n' r' : List Bool) (hq' : q'.length ≤ b) (hc : ch'.length ≤ b)
+ (hp' : p'.length ≤ b) (hn : n'.length ≤ b) (hr : r'.length ≤ b) (i : Port) :=
+ (hbank q' ch' p' n' r' hq' hc hp' hn hr i).trans hbc'
+ obtain ⟨td,htd,rd⟩ := counts false
+ have d := counter_bounded false L row payload (false::q) ch zero zero (out false) []
+ (rd.mono_cap hcspace) (hbankCap _ _ _ _ _ (hqs false) hch hz hz (by simp))
+ have f := short_bounded (switchSign_runs L row payload q ch (out false) zero [])
+ (hbank (false::q) ch (out false) zero [] (hqs false) hch (hout false) hz (by simp))
+ (cap := cap) (by dsimp [k,localCost] at hbc; omega)
+ obtain ⟨tg,htg,rg⟩ := counts true
+ have g := counter_bounded true L row payload (true::q) ch (out false) zero (out true) []
+ (rg.mono_cap hcspace) (hbankCap _ _ _ _ _ (hqs true) hch (hout false) hz (by simp))
+ obtain ⟨th,hth,h⟩ := reduce_bounded modulus hv L hp he hw z row payload (true::q) ch (out false) (out true) []
+ signed cap (by
+ simp only [out,length_digits,List.length_nil,add_zero]
+ dsimp [k,localCost] at hbc
+ rw [he,hw] at hbc
+ omega)
+ (hbankCap _ _ _ _ _ (hqs true) hch (hout false) (hout true) (by simp))
+ simp only [List.append_nil] at h
+ obtain ⟨ti,hti,ri⟩ := cleanup_runs L row payload (true::q) ch (out false) (out true) bits b
+ (hqs true) hch (hout false) (hout true)
+ have i := short_bounded ri (hbank _ _ _ _ _ (hqs true) hch (hout false) (hout true) hbits)
+ (cap := cap) (by dsimp [k,localCost] at hbc; omega)
+ refine ⟨_,?_,((((((a.followedBy b').followedBy c').followedBy d).followedBy f).followedBy g).followedBy h).followedBy i⟩
+ dsimp only [k,localCost]
+ simp only [out,length_digits] at hth
+ rw [he,hw]
+ omega
+
+end JointScalar.Leaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarLeafEncoding.lean b/lean/OAI/Computability/VPVNP/JointScalarLeafEncoding.lean
new file mode 100644
index 0000000000..df7cef2242
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarLeafEncoding.lean
@@ -0,0 +1,48 @@
+import OAI.Computability.VPVNP.JointScalarCore
+import OAI.Computability.VPVNP.JointScalarRowPrefix
+
+/-! # Packing the exponent coordinates of a signed original-row query -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar.Leaf
+
+open UniversalCountStack
+
+/-- Concatenate the low `W` bits of each exponent in coordinate order, least significant bit
+first within each coordinate. -/
+def packed {t : ℕ} (W : ℕ) (a : Fin t → ℕ) : List Bool :=
+ (List.ofFn a).flatMap (digits W)
+
+@[simp] theorem packed_length {t : ℕ} (W : ℕ) (a : Fin t → ℕ) : (packed W a).length = t*W := by
+ simp [packed, List.length_flatMap, Function.comp_def, List.ofFn_const]
+
+/-- The little-endian binary words sent to the interpreter are the inputs
+of the gate checker in the order of its formal wires. -/
+theorem query_bits {t : ℕ} (n high W : ℕ) (negative : Bool) (row : ℕ) (a : Fin t → ℕ) :
+ List.ofFn (query (n := n) (high := high) (W := W) negative row a) =
+ negative :: (digits (n+high) row ++ packed W a) := by
+ simp only [query, List.ofFn_fin_append, List.ofFn_const, List.replicate_one, List.singleton_append,
+ RowPrefix.digits_ofFn]
+ congr 2
+ rw [List.ofFn_mul]
+ change _ = ((List.ofFn a).map (digits W)).flatten
+ rw [List.map_ofFn]
+ apply congrArg List.flatten
+ apply congrArg List.ofFn
+ funext i
+ rw [Function.comp_apply, RowPrefix.digits_ofFn]
+ apply congrArg List.ofFn
+ funext j
+ have idx (h : i.val * W + j.val < t * W) :
+ (⟨i.val * W + j.val, h⟩ : Fin (t*W)) = finProdFinEquiv (i,j) :=
+ Fin.ext (by change _ = j.val + W * i.val; ring)
+ simp only [idx, Equiv.symm_apply_apply]
+
+end JointScalar.Leaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarLeafPorts.lean b/lean/OAI/Computability/VPVNP/JointScalarLeafPorts.lean
new file mode 100644
index 0000000000..a46bd7ddbf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarLeafPorts.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.JointScalarMachine
+import OAI.Computability.VPVNP.RankQueryStackSignedCount
+import OAI.Computability.VPVNP.RankQueryGramReadSpace
+import OAI.Computability.VPVNP.SliceArithmeticCallCopies
+
+/-!
+# Returning ports for an original Macaulay coefficient
+
+The packed residual exponents and row register are immutable. The two
+invocations of the counted checker share their input and advice, and write
+their totals into the positive and negative operands of the field converter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar.Leaf
+
+open RAMTape UniversalCountStack
+
+/-- Stack names for the row and exponent inputs, counter templates, row-prefix scratch, Boolean
+checker and signed field conversion. -/
+inductive Port where
+ | row | packed | rowWidth | blankChoice | blankTotal | saved | staged
+ | count (p : AdviceCountAdapter.Port)
+ | arithmetic (p : SliceArithmeticSignedCount.Port)
+ deriving DecidableEq, Fintype
+
+/-- Checker input stack holding the polarity bit, equation address and packed exponent
+coordinates. -/
+abbrev queryPort : Port := .count (.aux .query)
+/-- Counter stack holding the current Boolean witness for the advised circuit. -/
+abbrev choicePort : Port := .count .choice
+/-- Arithmetic input stack that receives the witness count for the selected polarity. A true
+argument selects the negative count. -/
+abbrev totalPort (neg : Bool) : Port := .arithmetic (.inr (SliceArithmeticSignedCount.source neg))
+/-- Stack onto which the converter prepends the signed coefficient in the extension field’s
+polynomial basis. -/
+abbrev resultPort : Port := .arithmetic (.inr .result)
+/-- Persistent checker stack containing the encoded gate instructions used for both witness
+counts. -/
+abbrev advicePort : Port := .count (.aux .advice)
+
+/-- Static bank data, supplied once for the family of queries. The row width
+is the expected width of the equation address in the circuit query. -/
+structure Layout where
+ /-- Prime modulus used to reduce the two integer witness counts. -/
+ prime : ℕ
+ /-- Number of base-field coordinates in the polynomial-basis encoding of a field element. -/
+ degree : ℕ
+ /-- Bit width of each base-field coordinate in the packed field result. -/
+ limbWidth : ℕ
+ /-- Number of row-address bits to place between the polarity bit and the exponent payload. -/
+ rowBits : ℕ
+ /-- Width of the enumerated witness word. Each count receives one extra bit to hold the total
+ when every witness accepts. -/
+ witnessBits : ℕ
+ /-- Encoded Boolean gate instructions shared by the positive and negative coefficient
+ queries. -/
+ circuitAdvice : List Bool
+
+/-- Initialize the leaf’s named stacks with the row, exponents, checker inputs, two count
+operands and output suffix, using the layout for the advice and width templates. -/
+def bank (L : Layout) (row packed query choice positive negative result : List Bool) : Stacks Port
+ | .row => row
+ | .packed => packed
+ | .rowWidth => List.replicate L.rowBits false
+ | .blankChoice => digits L.witnessBits 0
+ | .blankTotal => digits (L.witnessBits+1) 0
+ | .saved | .staged => []
+ | .count p => UniversalCountStack.bank (AdviceCountAdapter.inputs query L.circuitAdvice) choice [] [] [] p
+ | .arithmetic p => SliceArithmeticSignedCount.clean
+ (SliceArithmeticSignedCount.external L.prime L.degree L.limbWidth positive negative result) p
+
+/-- Leaf bank at a call boundary, with the row, packed exponents and output suffix in place and
+the query, witness and count registers empty. -/
+abbrev clean (L : Layout) (row packed result : List Bool) := bank L row packed [] [] [] [] result
+
+/-- Route the checker’s total to the arithmetic operand for the selected polarity and its other
+ports to the checker bank. -/
+def countPorts (negative : Bool) : AdviceCountAdapter.Port → Port
+ | .total => totalPort negative
+ | p => .count p
+
+private theorem countPorts_injective (negative : Bool) : Function.Injective (countPorts negative) := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [countPorts, totalPort]
+
+/-- Run the fixed circuit-witness enumerator with its total directed to the selected
+signed-count operand. -/
+def counter (neg : Bool) : FiniteRoutine Port := (FiniteRoutine.ofRoutine countCircuit).onPorts (countPorts neg)
+
+/-- Reduce the two counts modulo the advised prime and prepend their difference as a constant
+element of the extension field. -/
+def reduce : FiniteRoutine Port := SliceArithmeticSignedCount.machine.onPorts Port.arithmetic
+
+/-- Lift a counted checker call without charging its exponential elapsed time
+to the space bound. The unselected count operand remains available. -/
+theorem counter_bounded (neg : Bool) (L : Layout) (row packed query choice other input output suffix : List Bool)
+ {cap t : ℕ}
+ (small : SpaceRun countCircuit.standalone cap t (some countCircuit.entry)
+ (UniversalCountStack.bank (AdviceCountAdapter.inputs query L.circuitAdvice) choice input [] []) none
+ (UniversalCountStack.bank (AdviceCountAdapter.inputs query L.circuitAdvice) choice output [] []))
+ (hin : ∀ p, (bank L row packed query choice (if neg then other else input)
+ (if neg then input else other) suffix p).length ≤ cap) :
+ (counter neg).BoundedRun cap t
+ (bank L row packed query choice (if neg then other else input) (if neg then input else other) suffix)
+ (bank L row packed query choice (if neg then other else output) (if neg then output else other) suffix) := by
+ apply FiniteRoutine.BoundedRun.framed (countPorts_injective neg) (r := FiniteRoutine.ofRoutine countCircuit)
+ small hin
+ · intro i
+ cases i <;> cases neg <;> rfl
+ · intro i
+ cases i <;> cases neg <;> rfl
+ · intro i h
+ cases i with
+ | arithmetic a =>
+ rcases a with a|a
+ · cases a with
+ | divide i => cases i <;> rfl
+ | _ => rfl
+ · cases a <;> cases neg <;> first | rfl | exact (h .total rfl).elim
+ | _ => rfl
+
+/-- The converter reads both totals in place and writes only the field-result
+port. The larger stack bank keeps the row, packed input and checker advice. -/
+theorem reduce_bounded {p e v : ℕ} [Fact p.Prime] [NeZero e] (c : SliceArithmetic.Vector p e)
+ (hv : SliceArithmetic.Word.workingWidth p ≤ v) (L : Layout) (hp : L.prime = p)
+ (he : L.degree = e) (hwidth : L.limbWidth = v) (z : ℤ)
+ (row packed query choice positive negative result : List Bool)
+ (hsign : (TapeWord.value positive : ℤ) - (TapeWord.value negative : ℤ) = z) (cap : ℕ)
+ (hcap : positive.length+negative.length+result.length+e+v+
+ SliceArithmeticSignedCount.callCap positive.length negative.length e v ≤ cap)
+ (hin : ∀ a, (bank L row packed query choice positive negative result a).length ≤ cap) :
+ ∃ ticks ≤ SliceArithmeticSignedCount.callCap positive.length negative.length e v,
+ reduce.BoundedRun cap ticks (bank L row packed query choice positive negative result)
+ (bank L row packed query choice positive negative (RankQuery.Stack.Engine.scalar v (z : RankQuery.Stack.Scalar c) ++ result)) := by
+ obtain ⟨ticks,ht,hr⟩ := RankQuery.Stack.Scalar.signedCount_spaceRun hv c z positive negative result hsign
+ refine ⟨ticks,ht,?_⟩
+ apply FiniteRoutine.BoundedRun.framed (fun _ _ h => Port.arithmetic.inj h)
+ (r := SliceArithmeticSignedCount.machine) (hr.mono_cap hcap) hin
+ · intro a
+ simp only [bank, hp, he, hwidth]
+ · intro a
+ simp only [bank, hp, he, hwidth]
+ · intro a h
+ cases a <;> first | rfl | exact (h _ rfl).elim
+
+end JointScalar.Leaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarLeafPrepare.lean b/lean/OAI/Computability/VPVNP/JointScalarLeafPrepare.lean
new file mode 100644
index 0000000000..6e07e6e18f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarLeafPrepare.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.JointScalarLeafPorts
+import OAI.Computability.VPVNP.JointScalarRowPrefix
+
+/-!
+# Physical preparation and cleanup of a returning signed coefficient query
+
+Copy the exponent payload and blank counters from immutable ports. Prepend
+the low row-address bits and the polarity. Switching polarity consumes and
+replaces only the first query bit. Cleanup returns the count registers and
+the query workspace to empty stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar.Leaf
+
+open RAMTape UniversalCountStack SliceArithmetic
+
+/-- Four source–destination pairs that initialize the checker query, witness word and two count
+operands. -/
+def copies : List (Port × Port) :=
+ [(.packed,queryPort),(.blankChoice,choicePort),(.blankTotal,totalPort false),(.blankTotal,totalPort true)]
+
+/-- Copy the packed exponents into the query and the zero templates into the three counter
+registers, using the saved-bits stack as scratch. -/
+def load : FiniteRoutine Port := CallCopies.copyPlan .saved copies
+
+private theorem copy_ok : CallCopies.Valid Port.saved copies := by decide
+
+private theorem copied (L : Layout) (row packed result : List Bool) :
+ CallCopies.copied copies (clean L row packed result) =
+ bank L row packed packed (digits L.witnessBits 0) (digits (L.witnessBits+1) 0)
+ (digits (L.witnessBits+1) 0) result := by
+ funext p
+ cases p with
+ | count i => cases i with
+ | aux j => cases j <;> rfl
+ | _ => rfl
+ | arithmetic i =>
+ rcases i with i|i
+ · cases i with
+ | divide j => cases j <;> rfl
+ | _ => rfl
+ · cases i <;> rfl
+ | _ => rfl
+
+theorem load_runs (L : Layout) (row packed result : List Bool) (b : ℕ)
+ (hpacked : packed.length ≤ b) (hk : L.witnessBits+1 ≤ b) :
+ ∃ steps ≤ 4*(5*b+2)+1, load.Runs steps (clean L row packed result)
+ (bank L row packed packed (digits L.witnessBits 0) (digits (L.witnessBits+1) 0)
+ (digits (L.witnessBits+1) 0) result) := by
+ obtain ⟨steps,h,run⟩ := CallCopies.copyPlan_runs Port.saved copies (clean L row packed result) b
+ copy_ok rfl (by intro p hp; simp [copies] at hp; rcases hp with rfl|rfl|rfl|rfl <;> rfl)
+ (by intro p hp; simp [copies] at hp; rcases hp with rfl|rfl|rfl|rfl
+ · exact hpacked
+ · change (digits L.witnessBits 0).length ≤ b; simp; omega
+ · simpa only [clean,bank,length_digits] using hk
+ · simpa only [clean,bank,length_digits] using hk)
+ rw [copied] at run
+ exact ⟨steps,h,run⟩
+
+/-- Connect the row-prefix routine to the leaf’s row register, width template, query stack and
+two scratch stacks. -/
+def prefixPorts : RowPrefix.Port → Port
+ | .source => .row | .width => .rowWidth | .dst => queryPort | .saved => .saved | .staged => .staged
+
+private theorem prefix_injective : Function.Injective prefixPorts := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [prefixPorts, queryPort]
+
+/-- Prepend the prescribed number of low row-address bits to the query, padding missing high
+bits with zero and restoring the row register. -/
+def prependRow : FiniteRoutine Port := (RowPrefix.body false).onPorts prefixPorts
+
+theorem prefix_runs (L : Layout) (wr j : ℕ) (hj : j < 2^wr) (packed q choices pos neg result : List Bool) :
+ ∃ steps ≤ 9*L.rowBits+3, prependRow.Runs steps
+ (bank L (digits wr j) packed q choices pos neg result)
+ (bank L (digits wr j) packed (digits L.rowBits j ++ q) choices pos neg result) := by
+ obtain ⟨steps,h,r⟩ := RowPrefix.runs false L.rowBits wr j hj q
+ refine ⟨steps,h,?_⟩
+ apply (RowPrefix.body false).runs_onPorts_framed prefix_injective r
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> rfl
+ · intro i hi
+ cases i with
+ | count i => cases i with
+ | aux j => cases j <;> first | rfl | exact (hi .dst rfl).elim
+ | _ => rfl
+ | _ => rfl
+
+/-- Prepend the requested polarity bit to the checker query. -/
+def pushSign (b : Bool) : FiniteRoutine Port := .ofRoutine (Routine.push queryPort b)
+
+private def popSign : FiniteRoutine Port :=
+ .ofRoutine (⟨(), fun _ => .pop queryPort (fun _ => none)⟩ : Routine Port Unit)
+
+/-- Replace the positive query’s leading false bit with true to select the negative count on
+the same row and exponents. -/
+def switchSign : FiniteRoutine Port := popSign.followedBy (pushSign true)
+
+private theorem update_query (L : Layout) (row packed q choices pos neg result q' : List Bool) :
+ Function.update (bank L row packed q choices pos neg result) queryPort q' =
+ bank L row packed q' choices pos neg result := by
+ funext i
+ cases i with
+ | count i => cases i with
+ | aux j => cases j <;> rfl
+ | _ => rfl
+ | _ => rfl
+
+theorem pushSign_runs (L : Layout) (row packed q choices pos neg result : List Bool) (b : Bool) :
+ (pushSign b).Runs 1 (bank L row packed q choices pos neg result)
+ (bank L row packed (b::q) choices pos neg result) := by
+ rw [← update_query L row packed q choices pos neg result (b::q)]
+ exact Routine.runs_push _ _ _
+
+theorem switchSign_runs (L : Layout) (row packed q choices pos neg result : List Bool) :
+ switchSign.Runs 2 (bank L row packed (false::q) choices pos neg result)
+ (bank L row packed (true::q) choices pos neg result) := by
+ apply FiniteRoutine.Runs.followedBy (m := 1) (n := 1) _ (pushSign_runs ..)
+ rw [← update_query L row packed (false::q) choices pos neg result q]
+ exact .cons (.pop rfl) (.nil ..)
+
+/-- The query, witness and two count-operand stacks cleared at return. -/
+def cleanPorts : List Port := [queryPort,choicePort,totalPort false,totalPort true]
+/-- Clear the query, witness and both count operands to return the leaf bank to its clean call
+boundary. -/
+def cleanup : FiniteRoutine Port := CallClear.cleanup cleanPorts
+
+theorem cleanup_runs (L : Layout) (row packed q choices pos neg result : List Bool) (b : ℕ)
+ (hq : q.length ≤ b) (hc : choices.length ≤ b) (hp : pos.length ≤ b) (hn : neg.length ≤ b) :
+ ∃ steps ≤ 4*(b+1)+1, cleanup.Runs steps (bank L row packed q choices pos neg result)
+ (clean L row packed result) := by
+ let s := bank L row packed q choices pos neg result
+ obtain ⟨steps,h,run⟩ := CallClear.cleanup_runs cleanPorts s b (by
+ intro i hi; simp [cleanPorts] at hi; rcases hi with rfl|rfl|rfl|rfl
+ · exact hq
+ · exact hc
+ · exact hp
+ · exact hn)
+ have hu : CallClear.erased cleanPorts s = clean L row packed result := by
+ funext i
+ cases i with
+ | count i => cases i with
+ | aux j => cases j <;> rfl
+ | _ => rfl
+ | arithmetic i =>
+ rcases i with i|i
+ · cases i with
+ | divide j => cases j <;> rfl
+ | _ => rfl
+ · cases i <;> rfl
+ | _ => rfl
+ exact ⟨steps,h,hu ▸ run⟩
+
+end JointScalar.Leaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarLeafResources.lean b/lean/OAI/Computability/VPVNP/JointScalarLeafResources.lean
new file mode 100644
index 0000000000..3ca77b6bd7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarLeafResources.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.JointScalarLeaf
+import OAI.Computability.VPVNP.JointScalarResources
+
+/-! # Uniform space and time budgets of the returning signed scalar callback -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar.Leaf
+
+open RAMTape UniversalCountStack JointLabelSystem
+
+/-- Unary width templates, copies, cleanup, and reduction modulo the field
+prime have quadratic cost in the size of the caller's bank. -/
+theorem localCost_le (L : Layout) (wr pay : ℕ) :
+ let b := bankSize L wr pay
+ localCost L b ≤ 6000*(b+1)^2 := by
+ intro b
+ have h1 : L.witnessBits+1+ (L.witnessBits+1) + L.degree + L.limbWidth + 1 ≤ 3*(b+1) := by
+ dsimp [b,bankSize]; omega
+ have h2 := SliceArithmeticSignedCount.callCap_le (L.witnessBits+1) (L.witnessBits+1) L.degree L.limbWidth
+ have h3 := h2.trans (Nat.mul_le_mul_left 600 (Nat.pow_le_pow_left h1 2))
+ have h4 : L.rowBits ≤ b := by dsimp [b,bankSize]; omega
+ have h5 : 2*(L.witnessBits+1) + L.degree + L.limbWidth ≤ 3*(b+1) := by omega
+ unfold localCost
+ ring_nf at h3 ⊢
+ omega
+
+private theorem time_le {time T k work : ℕ} (h : time ≤ 2^T) (hk : k ≤ work) :
+ 2*time+k ≤ 2^(T+work+2) := by
+ have hpos := Nat.one_le_two_pow (n := T)
+ have hwpos := Nat.one_le_two_pow (n := work)
+ have hsmall : work ≤ 2^work := Nat.lt_two_pow_self.le
+ rw [pow_add,pow_add]
+ norm_num
+ nlinarith [Nat.mul_le_mul_left (2^T) hwpos, Nat.mul_le_mul_right (2^work) hpos]
+
+set_option maxHeartbeats 400000 in
+/-- The row/exponent/field widths may depend on the length. The polynomial
+caps apply also when the selected prime and its field presentation depend
+on the original circuit. -/
+theorem budgets (V I : Type*) [Fintype V] [Fintype I] (F : I → MvPolynomial V ℤ) (c : ℕ)
+ {width row degree limb : ℕ → ℕ} (hW : PolynomiallyBounded width) (hr : PolynomiallyBounded row)
+ (he : PolynomiallyBounded degree) (hv : PolynomiallyBounded limb) :
+ ∃ space exp : ℕ → ℕ, PolynomiallyBounded space ∧ PolynomiallyBounded exp ∧
+ ∀ n (hn : 2 ≤ n) (p e v wr : ℕ), e ≤ degree n → v ≤ limb n → wr ≤ row n →
+ let L := layout V I F c hn (width n) p e v
+ let C := checker V I F c hn (width n)
+ let b := bankSize L wr (FixedRows.labelTotal V n c * width n)
+ let k := localCost L b
+ max (stackLimit C) b + k ≤ space n ∧ 2*(2^L.witnessBits * perChoice C) + k ≤ 2^(exp n) := by
+ obtain ⟨A,B,S,T,hA,_,hS,hT,bounds⟩ := Resources.checker_polynomial_resources V I F c hW
+ let k (n : ℕ) := witnessWidth (ParseOracle.flagCount c n) (n^clockExponent) (motifWidth V I F)
+ let b (n : ℕ) := row n + FixedRows.labelTotal V n c * width n + (n+highWidth I) + k n + limb n +
+ degree n + degree n*limb n + A n + 2
+ let work (n : ℕ) := 6000*(b n+1)^2
+ have hk : PolynomiallyBounded k := (ParseOracle.flagCount_polynomial c).add
+ ((PolynomiallyBounded.id.pow clockExponent).add (.const _))
+ have hpay := (FixedRows.labelTotal_polynomiallyBounded V c).mul hW
+ have hb : PolynomiallyBounded b := (((((((hr.add hpay).add (PolynomiallyBounded.id.add (.const _))).add hk).add hv).add he).add (he.mul hv)).add hA).add (.const 2)
+ have hwork : PolynomiallyBounded work := (PolynomiallyBounded.const 6000).mul ((hb.add (.const 1)).pow 2)
+ refine ⟨fun n => S n+b n+work n, fun n => T n+work n+2, (hS.add hb).add hwork,
+ (hT.add hwork).add (.const 2), ?_⟩
+ intro n hn p e v wr hed hvl hwr L C live cost
+ obtain ⟨ha,_,hs,ht⟩ := bounds n hn
+ have hwitness : L.witnessBits = k n := congrArg
+ (fun f => witnessWidth f (n^clockExponent) (motifWidth V I F)) (ParseOracle.flags_eq_flagCount c n)
+ have hbank : live ≤ b n := by
+ change wr + _ + (n+highWidth I) + L.witnessBits + v + e + e*v + L.circuitAdvice.length + 2 ≤ _
+ dsimp only [b]
+ rw [hwitness]
+ have hadvice : L.circuitAdvice.length ≤ A n := by
+ dsimp only [L,layout,Layout.circuitAdvice]
+ exact ha
+ exact Nat.add_le_add_right (Nat.add_le_add
+ (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add
+ (Nat.add_le_add_right (Nat.add_le_add_right (Nat.add_le_add_right hwr _) _) _) hvl) hed)
+ (Nat.mul_le_mul hed hvl)) hadvice) 2
+ have hlocal : cost ≤ work n := (localCost_le L wr _).trans
+ (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (Nat.add_le_add_right hbank 1) 2))
+ have htime : 2^L.witnessBits*perChoice C ≤ 2^(T n) := by
+ dsimp only [L,layout,Layout.witnessBits,C]
+ exact ht
+ have hspace : stackLimit C ≤ S n := hs
+ constructor
+ · exact Nat.add_le_add (max_le (hspace.trans (Nat.le_add_right ..)) (hbank.trans (Nat.le_add_left ..))) hlocal
+ · exact time_le htime hlocal
+
+end JointScalar.Leaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarMachine.lean b/lean/OAI/Computability/VPVNP/JointScalarMachine.lean
new file mode 100644
index 0000000000..638382ead4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarMachine.lean
@@ -0,0 +1,219 @@
+import OAI.Computability.VPVNP.JointScalarCount
+import OAI.Computability.VPVNP.GrammarCoefficientBounds
+
+/-!
+# Physical signed coefficient read for the joint integer system
+
+The same finite bit-stack control executes all original row reads. Its
+gate-stream advice specifies the two verifier circuits and the fixed motif
+tables. The public query is one sign bit, the binary equation address and
+the array of formal exponents. The returned unsigned integer is the selected
+positive or negative part of the formal coefficient.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar
+
+open MvPolynomial ParseGrammar VerifierNetwork JointLabelSystem UniversalCountStack
+open RadicalCertificate.MonomialIndex
+open scoped Classical
+
+variable (V I : Type*) [Fintype V] [Fintype I] (F : I → MvPolynomial V ℤ) {n : ℕ} (c : ℕ)
+
+/-- Sparse integer coefficient tables of the fixed equations, indexed in their finite row
+order. -/
+noncomputable abbrev sparseRows := FixedRows.fixedTable V I F ∘ (Fintype.equivFin I).symm
+/-- Number of bits reserved above the low input word to address the fixed equations following
+the grammar rows. -/
+abbrev highWidth := Nat.clog 2 (Fintype.card I + 1) + 1
+/-- Width of the witness word that counts each signed part of a coefficient in the fixed
+equations. -/
+noncomputable abbrev motifWidth := Motif.witnessBits (sparseRows V I F)
+/-- Formal variable index of a grammar production in the joint grammar and motif system. -/
+noncomputable abbrev productionAddress := leftIndex (Production n c) V
+/-- Translate a production number from the primed parser's order into its formal variable
+index. -/
+noncomputable abbrev denseProduction := productionAddress V (n := n) c ∘ (PrimedStackRAM.labelIndex n n _).symm
+/-- Translate a finite motif-entry number into its formal variable index in the joint system. -/
+noncomputable abbrev denseLocal := rightIndex (Production n c) V ∘ (Fintype.equivFin V).symm
+/-- Final grammar layer `n - 1`, from which the coefficient verifier starts a parse. -/
+abbrev rootLayer (hn : 2 ≤ n) : Fin n := ⟨n-1, by omega⟩
+/-- State zero at the root of the grammar used for the joint coefficient query. -/
+abbrev rootState (hn : 2 ≤ n) : Fin (n^(c+5)) := ⟨0, pow_pos (by omega) _⟩
+
+/-- Grammar verifier frame rooted at the final layer and state zero, with label exponents
+addressed in the joint system. -/
+noncomputable abbrev parseBlock (hn : 2 ≤ n) (W : ℕ) :=
+ ParseOracle.frame (parseOracleMetadata (Fin n × Bool) (Fin (n^(c+5))) n
+ (rootLayer hn) (rootState c hn)) (productionAddress V c) W
+
+/-- The exact advised checker. Its input wiring uses the formal coordinate
+number of each grammar and motif label. -/
+noncomputable abbrev rowFrame (hn : 2 ≤ n) (W : ℕ) :=
+ frame (high := highWidth I) (motif := motifWidth V I F)
+ (denseProduction V c) (denseLocal V c) (sparseRows V I F) (parseBlock V c hn W) (VerifierMachine.verifierFrame n)
+
+/-- Single-output Boolean circuit for counting the selected sign of a joint equation
+coefficient. -/
+noncomputable abbrev checker (hn : 2 ≤ n) (W : ℕ) := (rowFrame V I F c hn W).circuit ()
+
+private theorem row_fits (o : Fin (2^n + Fintype.card I)) : o.val < 2^(n + highWidth I) := by
+ have h := Nat.le_pow_clog (by decide : 1 < 2) (Fintype.card I + 1)
+ have h₁ := Nat.one_le_two_pow (n := n)
+ have h₂ := Nat.one_le_two_pow (n := Nat.clog 2 (Fintype.card I + 1))
+ rw [highWidth, pow_add, pow_succ]
+ apply o.isLt.trans_le
+ nlinarith [Nat.mul_le_mul_left (2^n) h, Nat.mul_le_mul_right (Fintype.card I + 1) h₁]
+
+private theorem part_grammar (p u : ℕ) (neg : Bool) (inBlock constant : Prop)
+ [Decidable inBlock] [Decidable constant] (hz : constant → p = 0) :
+ (if neg then (if inBlock ∧ constant then u else 0) else (if inBlock then p else 0)) =
+ Motif.part neg (if inBlock then (p : ℤ) - (if constant then (u : ℤ) else 0) else 0) := by
+ by_cases hi : inBlock <;> by_cases hc : constant <;> cases neg <;>
+ simp [hi, hc, Motif.part, show constant → p = 0 from hz] at *
+
+private theorem count_clock (x : Fin n → Bool) :
+ (∑ u, ((VerifierMachine.verifierFrame n).eval (Sum.elim x u) ()).toNat) = acceptingCount x := by
+ have hc := acceptingCount_eq_sum_witnesses (R := ℕ) x
+ simp only [Nat.cast_id] at hc
+ rw [hc]
+ exact Finset.sum_congr rfl fun u _ => by rw [VerifierMachine.verifierFrame_eval]; cases verifiesInput x u <;> rfl
+
+private theorem wordBits_eq (j : Fin (2^n)) :
+ (fun b : Fin n => j.val.testBit b.val) = RAMSerialization.wordBits n j :=
+ funext (LiveHeader.testBit_wordBits j)
+
+/-- Count the checker witnesses at a grammar row. -/
+private theorem checker_grammar (hn : 2 ≤ n) (W : ℕ) (j : Fin (2^n)) (neg : Bool)
+ (a : Fin (FixedRows.labelTotal V n c) → ℕ) (ha : ∀ v, a v < 2^W) :
+ (∑ w, ((checker V I F c hn W).eval (Sum.elim (query neg j.val a) w)).toNat) =
+ Motif.part neg ((unionEquations (grammarEquation hn c) F (.inl (RAMSerialization.wordBits n j))).coeff
+ (exponentVector a)) := by
+ let l := leftIndex (Production n c) V
+ let r := rightIndex (Production n c) V
+ let b := (exponentVector a).comapDomain l l.injective.injOn
+ let x := RAMSerialization.wordBits n j
+ let B := labelQuery (rootLayer hn) (rootState c hn) x
+ have hnonneg := (coeff_labelQuery_bounds (rootLayer hn) (rootState c hn) x b).1
+ have hₚ : (∑ w, ((parseBlock V c hn W).eval (Sum.elim (ParseOracle.query x a W) w) ()).toNat) =
+ (B.coeff b).toNat := by
+ have h := ParseOracle.count_checker (rootLayer hn) (rootState c hn) l x a (W := W)
+ (fun z => ha (l z)) b (fun _ => rfl)
+ simpa only [ParseOracle.checker, Frame.circuit_eval] using h
+ have hz : b = 0 → (B.coeff b).toNat = 0 := by
+ rintro hb
+ rw [hb]
+ have h0 : B.coeff 0 = 0 := (labelQuery_isHomogeneous ..).coeff_eq_zero (by simp)
+ simp [h0]
+ have htotal : (∀ j, a j = 0) ↔ (∀ v, a (r v) = 0) ∧ b = 0 := by
+ constructor
+ · intro h
+ exact ⟨fun _ => h _, Finsupp.ext fun v => h (l v)⟩
+ · rintro ⟨h,hb⟩ i
+ rcases FixedRows.index_cover (V := Production n c) (W := V) i with ⟨v,rfl⟩ | ⟨v,rfl⟩
+ · change b v = 0
+ rw [hb, Finsupp.zero_apply]
+ · exact h v
+ have hlocal : (∀ i, a (denseLocal V c i) = 0) ↔ ∀ v, a (r v) = 0 := by
+ exact ((Fintype.equivFin V).symm.surjective.forall (p := fun v => a (r v) = 0)).symm
+ change (∑ w, (((rowFrame V I F c hn W).circuit ()).eval _).toNat) = Motif.part neg
+ ((rename l (grammarEquation hn c x)).coeff (exponentVector a))
+ rw [rowFrame, count_grammar _ _ _ _ _ neg j.val j.isLt a ha, wordBits_eq, hₚ, count_clock]
+ rw [FixedRows.coeff_of_rename_blocks l r FixedRows.index_disjoint FixedRows.index_cover]
+ change _ = Motif.part neg (if ∀ v, a (r v) = 0 then (grammarEquation hn c x).coeff b else 0)
+ simp only [grammarEquation, coeff_sub, coeff_C, eq_comm (a := (0 : Production n c →₀ ℕ)) (b := b)]
+ simp only [hlocal, htotal]
+ exact (part_grammar (B.coeff b).toNat (acceptingCount x) neg (∀ v, a (r v) = 0) (b = 0) hz).trans
+ (by rw [Int.toNat_of_nonneg hnonneg])
+
+/-- Count the checker witnesses at a motif row. -/
+private theorem checker_motif (hn : 2 ≤ n) (W : ℕ) (o : Fin (Fintype.card I)) (neg : Bool)
+ (a : Fin (FixedRows.labelTotal V n c) → ℕ) (ha : ∀ v, a v < 2^W) :
+ (∑ w, ((checker V I F c hn W).eval (Sum.elim (query neg (2^n+o.val) a) w)).toNat) =
+ Motif.part neg ((unionEquations (grammarEquation hn c) F (.inr ((Fintype.equivFin I).symm o))).coeff
+ (exponentVector a)) := by
+ let l := leftIndex (Production n c) V
+ let r := rightIndex (Production n c) V
+ let b := (exponentVector a).comapDomain r r.injective.injOn
+ have hprod : (∀ i, a (denseProduction V c i) = 0) ↔ ∀ v, a (l v) = 0 :=
+ ((PrimedStackRAM.labelIndex n n _).symm.surjective.forall (p := fun v => a (l v) = 0)).symm
+ have htable : FixedRows.tableLookup (sparseRows V I F o) (a ∘ denseLocal V c) =
+ (F ((Fintype.equivFin I).symm o)).coeff b :=
+ FixedRows.tableLookup_fixedTable V I F _ b
+ change (∑ w, (((rowFrame V I F c hn W).circuit ()).eval _).toNat) = Motif.part neg
+ ((rename r (F ((Fintype.equivFin I).symm o))).coeff (exponentVector a))
+ rw [rowFrame, count_motif _ _ _ _ _ neg o (row_fits I (o.natAdd (2^n))) a ha (Motif.part_fits ..)]
+ rw [FixedRows.coeff_of_rename_blocks r l (fun w v => (FixedRows.index_disjoint v w).symm)
+ (fun i => (FixedRows.index_cover i).symm)]
+ simp only [hprod, htable]
+ change (if ∀ v, a (l v) = 0 then Motif.part neg _ else 0) =
+ Motif.part neg (if ∀ v, a (l v) = 0 then _ else 0)
+ split_ifs <;> cases neg <;> simp [Motif.part, b]
+
+/-- One bit-stack count gives the selected part of the actual integer row. -/
+theorem checker_count (hn : 2 ≤ n) (W : ℕ) (row : Fin (2^n+Fintype.card I)) (negative : Bool)
+ (a : Fin (FixedRows.labelTotal V n c) → ℕ) (ha : ∀ v, a v < 2^W) :
+ (∑ w, ((checker V I F c hn W).eval (Sum.elim (query negative row.val a) w)).toNat) =
+ Motif.part negative ((unionEquations (grammarEquation hn c) F (FixedRows.rowIndex I n row)).coeff
+ (exponentVector a)) := by
+ obtain ⟨(j | o), rfl⟩ := (finSumFinEquiv (m := 2^n) (n := Fintype.card I)).surjective row
+ · simpa [FixedRows.rowIndex] using checker_grammar V I F c hn W j negative a ha
+ · simpa [FixedRows.rowIndex] using checker_motif V I F c hn W o negative a ha
+
+/-- Execution of the fixed finite routine from its concrete port bank. The
+signed part of the formal coefficient appears as a little-endian word on
+the `.total` stack. The circuit advice depends only on the dimensions and
+the fixed equation family. -/
+theorem scalar_runs (hn : 2 ≤ n) (W : ℕ) (row : Fin (2^n+Fintype.card I)) (negative : Bool)
+ (a : Fin (FixedRows.labelTotal V n c) → ℕ) (ha : ∀ v, a v < 2^W) :
+ let C := checker V I F c hn W
+ let x := query negative row.val a
+ let aux := scalarInputs C x
+ let w := witnessWidth (ParseOracle.Flags n n (Fin (n^(c+5)))) (n^clockExponent) (motifWidth V I F)
+ let value := ((unionEquations (grammarEquation hn c) F (FixedRows.rowIndex I n row)).coeff (exponentVector a))
+ ∃ ticks ≤ 2^w * perChoice C, SpaceRun countCircuit.standalone (stackLimit C) ticks (some countCircuit.entry)
+ (bank aux (digits w 0) (digits (w+1) 0) [] []) none
+ (bank aux (digits w 0) (digits (w+1) (Motif.part negative value)) [] []) := by
+ dsimp only
+ simpa only [checker_count V I F c hn W row negative a ha] using
+ countCircuit_runs (checker V I F c hn W) (query negative row.val a)
+
+/-- The count is at most the number of full witness strings. -/
+theorem scalar_part_lt (hn : 2 ≤ n) (W : ℕ) (row : Fin (2^n+Fintype.card I)) (negative : Bool)
+ (a : Fin (FixedRows.labelTotal V n c) → ℕ) (ha : ∀ v, a v < 2^W) :
+ let w := witnessWidth (ParseOracle.Flags n n (Fin (n^(c+5)))) (n^clockExponent) (motifWidth V I F)
+ let z := ((unionEquations (grammarEquation hn c) F (FixedRows.rowIndex I n row)).coeff (exponentVector a))
+ Motif.part negative z < 2^(w+1) := by
+ intro w z
+ have h := checker_count V I F c hn W row negative a ha
+ have hb : Motif.part negative z ≤ 2^w := by
+ rw [← h]
+ calc
+ _ ≤ ∑ _ : Fin w → Bool, 1 := Finset.sum_le_sum fun _ _ => Bool.toNat_le _
+ _ = 2^w := by simp
+ exact hb.trans_lt (by rw [pow_succ]; have := Nat.two_pow_pos w; omega)
+
+/-- Reading the returned count word retains the selected part in full. -/
+theorem scalar_digits_value (hn : 2 ≤ n) (W : ℕ) (row : Fin (2^n+Fintype.card I)) (negative : Bool)
+ (a : Fin (FixedRows.labelTotal V n c) → ℕ) (ha : ∀ v, a v < 2^W) :
+ let w := witnessWidth (ParseOracle.Flags n n (Fin (n^(c+5)))) (n^clockExponent) (motifWidth V I F)
+ let z := ((unionEquations (grammarEquation hn c) F (FixedRows.rowIndex I n row)).coeff (exponentVector a))
+ TapeWord.value (digits (w+1) (Motif.part negative z)) = Motif.part negative z := by
+ exact (value_digits ..).trans (Nat.mod_eq_of_lt (scalar_part_lt V I F c hn W row negative a ha))
+
+theorem signedParts_sub (z : ℤ) : (Motif.part false z : ℤ) - (Motif.part true z : ℤ) = z := by
+ cases z <;> simp [Motif.part]
+ omega
+
+theorem signedParts_cast {R : Type*} [CommRing R] (z : ℤ) :
+ (Motif.part false z : R) - (Motif.part true z : R) = (z : R) := by
+ exact_mod_cast congrArg (Int.castRingHom R) (signedParts_sub z)
+
+end JointScalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarMotifCircuit.lean b/lean/OAI/Computability/VPVNP/JointScalarMotifCircuit.lean
new file mode 100644
index 0000000000..c319a81d01
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarMotifCircuit.lean
@@ -0,0 +1,293 @@
+import OAI.Computability.VPVNP.OracleBinaryTarget
+import OAI.Computability.VPVNP.FixedLabelReadback
+import OAI.Computability.VPVNP.LiveHeaderBits
+
+/-!
+# A signed coefficient circuit for the fixed motif rows
+
+The row selector and the motif exponent wires may be placed anywhere in the
+joint query. The sparse tables and their integer coefficients are fixed for
+the motif. The circuit compares one unsigned witness against the selected
+positive or negative part. Repeated table keys are combined using the same
+integer lookup as the scalar reader.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar.Motif
+
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+open JointLabelSystem.FixedRows (tableLookup)
+
+variable {σ : Type*} {q m W k : ℕ}
+
+/-- Sparse representation of one motif equation as exponent vectors paired with integer
+coefficients. -/
+abbrev Table (m : ℕ) := List ((Fin m → ℕ) × ℤ)
+
+/-- Natural magnitude of the selected sign of an integer, equal to zero when that sign
+contributes nothing. -/
+def part (negative : Bool) (c : ℤ) : ℕ := (if negative then -c else c).toNat
+
+/-- Compare an unsigned word to a static threshold, from the high bit down.
+Every level uses just one copy of the lower-bit comparison. -/
+def below : {k : ℕ} → (Fin k → σ) → ℕ → Expr σ
+ | 0, _, b => .const (decide (0 < b))
+ | k+1, wire, b =>
+ let highZero := Expr.not (.input (wire (Fin.last k)))
+ let low := wire ∘ Fin.castSucc
+ if b ≤ 2^k then .and highZero (below low b)
+ else .or highZero (below low (b-2^k))
+
+theorem below_eval (wire : Fin k → σ) (b u : ℕ) (hu : u < 2^k) (x : σ → Bool)
+ (hw : ∀ j, x (wire j) = u.testBit j.val) : (below wire b).eval x = decide (u < b) := by
+ induction k generalizing b u with
+ | zero =>
+ obtain rfl : u = 0 := by simpa using hu
+ rfl
+ | succ k ih =>
+ have bound : u < 2^k*2 := by simpa only [pow_succ] using hu
+ have hpos := Nat.two_pow_pos k
+ have hl : ∀ j : Fin k, x ((wire ∘ Fin.castSucc) j) = (u % 2^k).testBit j.val := by
+ intro j
+ simp [hw, j.isLt]
+ have low := fun t => ih (wire ∘ Fin.castSucc) t _ (Nat.mod_lt u hpos) hl
+ have high := hw (Fin.last k)
+ change x (wire (Fin.last k)) = u.testBit k at high
+ by_cases small : u < 2^k
+ · rw [Nat.testBit_lt_two_pow small] at high
+ rw [Nat.mod_eq_of_lt small] at low
+ by_cases cap : b ≤ 2^k
+ · simp [below, cap, Expr.eval, high, low]
+ · simp [below, cap, Expr.eval, high, show u < b by omega]
+ · have quotient : u / 2^k = 1 := Nat.div_eq_of_lt_le (by omega) (by simpa [Nat.mul_comm] using bound)
+ have hbit : u.testBit k = true := by simp [Nat.testBit_eq_decide_div_mod_eq, quotient]
+ rw [hbit] at high
+ have rem : u % 2^k = u - 2^k := by
+ have eq := Nat.mod_add_div u (2^k)
+ rw [quotient, Nat.mul_one] at eq
+ omega
+ rw [rem] at low
+ by_cases cap : b ≤ 2^k
+ · simp [below, cap, Expr.eval, high, show ¬u < b by omega]
+ · simp [below, cap, Expr.eval, high, low, show (u-2^k < b-2^k) ↔ u < b by omega]
+
+theorem below_size (wire : Fin k → σ) (b : ℕ) : (below wire b).size = 3*k+1 := by
+ induction k generalizing b with
+ | zero => rfl
+ | succ k ih => simp only [below]; split <;> simp only [Expr.size, ih, Nat.mul_succ] <;> omega
+
+private def exponentMatch (wire : Fin m → Fin W → σ) (z : Fin m → ℕ) : Expr σ :=
+ .not (Expr.disjoin (List.ofFn fun i => .not (OracleBinaryTarget.expr (wire i) (z i))))
+
+private theorem exponentMatch_eval (wire : Fin m → Fin W → σ) (e z : Fin m → ℕ)
+ (fit : ∀ i, z i < 2^W) (x : σ → Bool) (hx : ∀ i j, x (wire i j) = (z i).testBit j.val) :
+ (exponentMatch wire e).eval x = true ↔ z = e := by
+ simp only [exponentMatch, Expr.eval, Bool.not_eq_true']
+ rw [Bool.eq_false_iff]
+ change (¬(Expr.disjoin _).eval x = true) ↔ _
+ rw [Expr.eval_disjoin_true, funext_iff]
+ simp only [List.mem_ofFn, exists_exists_eq_and, Expr.eval, Bool.not_eq_true',
+ OracleBinaryTarget.expr_eval _ _ _ (fit _) x (hx _), decide_eq_false_iff_not, not_exists, not_not]
+
+private def signAndWitness (negative : σ) (wire : Fin k → σ) (c : ℤ) : Expr σ :=
+ .and (if c < 0 then .input negative else .not (.input negative)) (below wire c.natAbs)
+
+private theorem signAndWitness_eval (negative : σ) (wire : Fin k → σ) (c : ℤ) (u : ℕ)
+ (hu : u < 2^k) (x : σ → Bool) (hx : ∀ j, x (wire j) = u.testBit j.val) :
+ (signAndWitness negative wire c).eval x = true ↔ u < part (x negative) c := by
+ cases c with
+ | ofNat n =>
+ have hn : ¬(n : ℤ) < 0 := by omega
+ cases h : x negative <;> simp [signAndWitness, hn, Expr.eval, part, h, below_eval _ _ _ hu x hx]
+ | negSucc n =>
+ cases h : x negative <;> simp [signAndWitness, Expr.eval, part, h, below_eval _ _ _ hu x hx]
+
+private def rowExpr (row : Table m) (expo : Fin m → Fin W → σ) (negative : σ)
+ (witness : Fin k → σ) : Expr σ :=
+ Expr.disjoin (row.map fun entry => .and (exponentMatch expo entry.1)
+ (signAndWitness negative witness (tableLookup row entry.1)))
+
+private theorem tableLookup_absent (row : Table m) (z : Fin m → ℕ) (ha : ∀ e ∈ row, e.1 ≠ z) :
+ tableLookup row z = 0 := by
+ unfold tableLookup
+ induction row with
+ | nil => rfl
+ | cons e es ih =>
+ simp only [List.foldl_cons, ite_eq_right (ha e (by simp))]
+ exact ih (fun a h => ha a (List.mem_cons_of_mem _ h))
+
+/-- The largest magnitude in the fixed motif table after equal keys are combined. -/
+def height (rows : Fin q → Table m) : ℕ :=
+ Finset.univ.sup fun o => (rows o).toFinset.sup fun e => (tableLookup (rows o) e.1).natAbs
+
+/-- Width of an unsigned witness whose initial segment can count either sign of every
+coefficient in the motif tables. -/
+def witnessBits (rows : Fin q → Table m) : ℕ := Nat.clog 2 (height rows)
+
+/-- The fixed witness width covers both polarities of every sparse lookup,
+including a key absent from the table. -/
+theorem part_fits (rows : Fin q → Table m) (o : Fin q) (z : Fin m → ℕ) (neg : Bool) :
+ part neg (tableLookup (rows o) z) ≤ 2^(witnessBits rows) := by
+ apply le_trans _ (Nat.le_pow_clog (by decide : 1 < 2) (height rows))
+ by_cases key : ∃ e ∈ rows o, e.1 = z
+ · obtain ⟨e, he, rfl⟩ := key
+ have small (c : ℤ) : part neg c ≤ c.natAbs := by cases c <;> cases neg <;> simp [part]
+ let rowHeight (j : Fin q) := (rows j).toFinset.sup fun v => (tableLookup (rows j) v.1).natAbs
+ have hm : e ∈ (rows o).toFinset := List.mem_toFinset.mpr he
+ have hr : (tableLookup (rows o) e.1).natAbs ≤ rowHeight o :=
+ Finset.le_sup (f := fun v : (Fin m → ℕ) × ℤ => (tableLookup (rows o) v.1).natAbs) hm
+ have ha : rowHeight o ≤ height rows := Finset.le_sup (f := rowHeight) (Finset.mem_univ o)
+ exact (small _).trans (hr.trans ha)
+ · rw [tableLookup_absent (rows o) z (fun e hm hz => key ⟨e,hm,hz⟩)]
+ cases neg <;> simp [part]
+
+private theorem rowExpr_eval (row : Table m) (expo : Fin m → Fin W → σ) (negative : σ)
+ (witness : Fin k → σ) (z : Fin m → ℕ) (u : ℕ) (hz : ∀ i, z i < 2^W) (hu : u < 2^k)
+ (x : σ → Bool) (he : ∀ i j, x (expo i j) = (z i).testBit j.val)
+ (hw : ∀ j, x (witness j) = u.testBit j.val) :
+ (rowExpr row expo negative witness).eval x = true ↔ u < part (x negative) (tableLookup row z) := by
+ rw [rowExpr, Expr.eval_disjoin_true]
+ constructor
+ · rintro ⟨test, hm, ht⟩
+ obtain ⟨e, _, rfl⟩ := List.mem_map.mp hm
+ rw [Expr.eval, Bool.and_eq_true, exponentMatch_eval _ _ _ hz x he,
+ signAndWitness_eval _ _ _ _ hu x hw] at ht
+ exact ht.1 ▸ ht.2
+ · intro hu'
+ by_cases existsKey : ∃ e ∈ row, e.1 = z
+ · obtain ⟨e, hm, hz'⟩ := existsKey
+ refine ⟨_, List.mem_map_of_mem (f := _) hm, ?_⟩
+ rw [Expr.eval, Bool.and_eq_true, exponentMatch_eval _ _ _ hz x he,
+ signAndWitness_eval _ _ _ _ hu x hw, hz']
+ exact ⟨rfl,hu'⟩
+ · rw [tableLookup_absent row z (fun e hm he => existsKey ⟨e,hm,he⟩)] at hu'
+ cases hn : x negative <;> simp [part, hn] at hu'
+
+/-- A true selector enables one sparse row. Non-motif coordinates are checked
+by the enclosing joint-query circuit. -/
+def expr (rows : Fin q → Table m) (rowMatches : Fin q → Expr σ)
+ (expo : Fin m → Fin W → σ) (negative : σ) (witness : Fin k → σ) : Expr σ :=
+ Expr.disjoin (List.ofFn fun o => .and (rowMatches o) (rowExpr (rows o) expo negative witness))
+
+theorem eval_selected (rows : Fin q → Table m) (rowMatches : Fin q → Expr σ)
+ (expo : Fin m → Fin W → σ) (negative : σ) (witness : Fin k → σ)
+ (o : Fin q) (z : Fin m → ℕ) (u : ℕ) (hz : ∀ i, z i < 2^W) (hu : u < 2^k) (x : σ → Bool)
+ (hr : ∀ j, (rowMatches j).eval x = decide (j = o))
+ (he : ∀ i j, x (expo i j) = (z i).testBit j.val) (hw : ∀ j, x (witness j) = u.testBit j.val) :
+ (expr rows rowMatches expo negative witness).eval x = decide (u < part (x negative) (tableLookup (rows o) z)) := by
+ apply Bool.eq_iff_iff.mpr
+ simp [expr, Expr.eval_disjoin_true, List.mem_ofFn, Expr.eval, hr, rowExpr_eval _ _ _ _ _ _ hz hu x he hw]
+
+/-- Addresses outside the motif range produce zero for every witness. -/
+theorem eval_unselected (rows : Fin q → Table m) (rowMatches : Fin q → Expr σ)
+ (expo : Fin m → Fin W → σ) (negative : σ) (witness : Fin k → σ)
+ (x : σ → Bool) (hr : ∀ j, (rowMatches j).eval x = false) :
+ (expr rows rowMatches expo negative witness).eval x = false := by
+ rw [Bool.eq_false_iff]
+ simp [expr, Expr.eval_disjoin_true, List.mem_ofFn, Expr.eval, hr]
+
+/-- Number of expression nodes, uniformly in the table entries' magnitudes.
+`R` bounds a row selector and `L` bounds the length of a sparse row. -/
+def sizeBound (q m W k R L : ℕ) := q * (R + L * (m * (W*3+4) + 3*k + 8) + 3) + 1
+
+private theorem exponentMatch_size (wire : Fin m → Fin W → σ) (z : Fin m → ℕ) :
+ (exponentMatch wire z).size ≤ m * (W*3+4) + 2 := by
+ have h := Expr.size_disjoin_le (List.ofFn fun i => Expr.not (OracleBinaryTarget.expr (wire i) (z i)))
+ (W*3+3) (by
+ intro e he
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp he
+ have h := OracleBinaryTarget.expr_size_le (wire i) (z i)
+ change _ + 1 ≤ _
+ omega)
+ simp only [List.length_ofFn, show W*3+3+1 = W*3+4 by omega] at h
+ change _ + 1 ≤ _
+ omega
+
+private theorem signAndWitness_size (negative : σ) (wire : Fin k → σ) (c : ℤ) :
+ (signAndWitness negative wire c).size ≤ 3*k+4 := by
+ unfold signAndWitness
+ split <;> simp only [Expr.size, below_size] <;> omega
+
+private theorem rowExpr_size (row : Table m) (expo : Fin m → Fin W → σ) (negative : σ) (witness : Fin k → σ) :
+ (rowExpr row expo negative witness).size ≤ row.length * (m * (W*3+4) + 3*k + 8) + 1 := by
+ unfold rowExpr
+ apply (Expr.size_disjoin_le _ (m * (W*3+4) + 3*k + 7) ?_).trans (by simp)
+ intro e he
+ obtain ⟨entry, _, rfl⟩ := List.mem_map.mp he
+ have h₁ := exponentMatch_size expo entry.1
+ have h₂ := signAndWitness_size negative witness (tableLookup row entry.1)
+ change _ + _ + 1 ≤ _
+ omega
+
+theorem expr_size_le (rows : Fin q → Table m) (rowMatches : Fin q → Expr σ)
+ (expo : Fin m → Fin W → σ) (negative : σ) (witness : Fin k → σ) (R L : ℕ)
+ (hr : ∀ j, (rowMatches j).size ≤ R) (hl : ∀ j, (rows j).length ≤ L) :
+ (expr rows rowMatches expo negative witness).size ≤ sizeBound q m W k R L := by
+ unfold expr sizeBound
+ apply (Expr.size_disjoin_le _ (R + L*(m*(W*3+4)+3*k+8)+2) ?_).trans (by simp)
+ intro e he
+ obtain ⟨o, rfl⟩ := List.mem_ofFn.mp he
+ have h₁ := rowExpr_size (rows o) expo negative witness
+ have h₂ := Nat.mul_le_mul_right (m*(W*3+4)+3*k+8) (hl o)
+ have h₃ := hr o
+ change _ + _ + 1 ≤ _
+ omega
+
+/-- Gate compilation of the predicate, using the joint verifier's network. -/
+noncomputable def frame [Fintype σ] (rows : Fin q → Table m) (rowMatches : Fin q → Expr σ)
+ (expo : Fin m → Fin W → σ) (negative : σ) (witness : Fin k → σ) : VerifierNetwork.Frame σ Unit :=
+ (VerifierNetwork.Frame.initial (id : σ → σ)).step (fun _ => expr rows rowMatches expo negative witness)
+
+theorem circuit_eval [Fintype σ] (rows : Fin q → Table m) (rowMatches : Fin q → Expr σ)
+ (expo : Fin m → Fin W → σ) (negative : σ) (witness : Fin k → σ) (x : σ → Bool) :
+ ((frame rows rowMatches expo negative witness).circuit ()).eval x =
+ (expr rows rowMatches expo negative witness).eval x := by
+ have h : (VerifierNetwork.Frame.initial (id : σ → σ)).eval x = x := by funext i; simp
+ simp [frame, h]
+
+theorem circuit_size_le [Fintype σ] (rows : Fin q → Table m) (rowMatches : Fin q → Expr σ)
+ (expo : Fin m → Fin W → σ) (negative : σ) (witness : Fin k → σ) (R L : ℕ)
+ (hr : ∀ j, (rowMatches j).size ≤ R) (hl : ∀ j, (rows j).length ≤ L) :
+ (frame rows rowMatches expo negative witness).circuitSize () ≤ 4 * sizeBound q m W k R L := by
+ apply (VerifierNetwork.Frame.circuitSize_le _ ()).trans
+ apply Nat.mul_le_mul_left
+ have hs := VerifierNetwork.Frame.step_size_le (VerifierNetwork.Frame.initial (id : σ → σ))
+ (fun _ : Unit => expr rows rowMatches expo negative witness) _ (fun _ =>
+ expr_size_le rows rowMatches expo negative witness R L hr hl)
+ simpa [frame] using hs
+
+/-- Summing over the physical little-endian witness bank yields precisely the
+selected part. This includes zero coefficients and a threshold equal to the
+full word capacity. -/
+theorem count_selected (rows : Fin q → Table m) (rowMatches : Fin q → Expr σ)
+ (expo : Fin m → Fin W → σ) (negative : σ) (witness : Fin k → σ)
+ (o : Fin q) (z : Fin m → ℕ) (neg : Bool) (hz : ∀ i, z i < 2^W)
+ (fit : part neg (tableLookup (rows o) z) ≤ 2^k)
+ (x : (Fin k → Bool) → σ → Bool) (hn : ∀ bits, x bits negative = neg)
+ (hr : ∀ bits j, (rowMatches j).eval (x bits) = decide (j = o))
+ (he : ∀ bits i j, x bits (expo i j) = (z i).testBit j.val)
+ (hw : ∀ bits j, x bits (witness j) = bits j) :
+ (∑ bits : Fin k → Bool, ((expr rows rowMatches expo negative witness).eval (x bits)).toNat) =
+ part neg (tableLookup (rows o) z) := by
+ rw [← (RAMSerialization.wordBits k).sum_comp]
+ let M := part neg (tableLookup (rows o) z)
+ calc
+ _ = ∑ u : Fin (2^k), (if u.val < M then 1 else 0) := by
+ apply Finset.sum_congr rfl
+ intro u _
+ let bits := RAMSerialization.wordBits k u
+ rw [eval_selected rows rowMatches expo negative witness o z u.val hz u.isLt
+ (x bits) (hr bits) (he bits) (fun j => (hw bits j).trans (LiveHeader.testBit_wordBits u j).symm), hn]
+ by_cases h : u.val < M <;> simp [← show M = part neg (tableLookup (rows o) z) from rfl, h]
+ _ = M := by
+ rw [Finset.sum_boole, ← Fintype.card_subtype (fun u : Fin (2^k) => u.val < M)]
+ exact Fintype.card_fin_lt_of_le fit
+
+end JointScalar.Motif
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarResources.lean b/lean/OAI/Computability/VPVNP/JointScalarResources.lean
new file mode 100644
index 0000000000..e987ce6489
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarResources.lean
@@ -0,0 +1,241 @@
+import OAI.Computability.VPVNP.JointScalarMachine
+
+/-!
+# Resources of the joint signed scalar checker
+
+The two shared subcircuits process grammar and clock witnesses. The final
+layer compares row, exponent and motif words and forces unused banks to zero.
+Gate count and all stack budgets are uniform in the query's numerical values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar.Resources
+
+open VerifierNetwork ParseGrammar UniversalCountStack
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit (Expr.eval Expr.size Expr.mux Expr.size_disjoin_le Expr.not)
+
+variable {n high t W flags clock motif g m q : ℕ}
+
+/-- Size bound for the final Boolean expression that selects the equation and sign, compares
+exponents and checks unused witness bits. -/
+def finishBound (n high t W flags clock motif g m q L : ℕ) :=
+ 2*(3*(n+high)+1) + (g+m+t)*(W*3+4) + 4*(flags+clock+motif) +
+ Motif.sizeBound q m W motif ((n+high)*3+2) L + 39
+
+theorem zeroWords_size {σ : Type*} (wire : Fin m → Fin W → σ) :
+ (zeroWords wire).size ≤ m*(W*3+4)+2 := by
+ have h := Expr.size_disjoin_le (List.ofFn fun i => Expr.not (OracleBinaryTarget.expr (wire i) 0))
+ (W*3+3) (by
+ intro e he
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp he
+ have h := OracleBinaryTarget.expr_size_le (wire i) 0
+ change _ + 1 ≤ _
+ omega)
+ simp only [List.length_ofFn, show W*3+3+1 = W*3+4 by omega] at h
+ change _ + 1 ≤ _
+ omega
+
+theorem finish_size_le (prod : Fin g → Fin t) (localMap : Fin m → Fin t)
+ (tables : Fin q → Motif.Table m) (L : ℕ) (hL : ∀ o, (tables o).length ≤ L) :
+ (finish (n := n) (high := high) (W := W) (flags := flags) (clock := clock) (motif := motif)
+ prod localMap tables).size ≤ finishBound n high t W flags clock motif g m q L := by
+ let raw : Input n high t W flags clock motif → Input n high t W flags clock motif ⊕ Checks := Sum.inl
+ let expo := fun i j => raw (exponentWire i j)
+ let rows := fun j : Fin q => OracleBinaryTarget.expr (raw ∘ rowWire) (2^n+j.val)
+ have hr := Motif.below_size (raw ∘ rowWire) (2^n)
+ have hprod := zeroWords_size (expo ∘ prod)
+ have hmot := zeroWords_size (expo ∘ localMap)
+ have htot := zeroWords_size expo
+ have hpadF := allZero_size (raw ∘ flagWire)
+ have hpadU := allZero_size (raw ∘ choiceWire)
+ have hpadM := allZero_size (raw ∘ motifWire)
+ have ht := Motif.expr_size_le tables rows (expo ∘ localMap) (raw polarity) (raw ∘ motifWire)
+ ((n+high)*3+2) L (fun j => OracleBinaryTarget.expr_size_le _ _) hL
+ dsimp only [raw, rows, expo, Function.comp_def] at *
+ simp only [Nat.add_mul] at ht
+ simp only [finish, Expr.mux, Expr.size, Function.comp_def, finishBound, Nat.add_mul]
+ omega
+
+/-- Combining subcircuits preserves sharing before the final layer is added. -/
+theorem frame_size_le (prod : Fin g → Fin t) (localMap : Fin m → Fin t) (tables : Fin q → Motif.Table m)
+ (parse : Frame (ParseOracle.Input n t W flags) Unit) (path : Frame (Fin n ⊕ Fin clock) Unit)
+ (L : ℕ) (hL : ∀ o, (tables o).length ≤ L) :
+ (JointScalar.frame (high := high) (motif := motif) prod localMap tables parse path).size ≤
+ parse.size + path.size + finishBound n high t W flags clock motif g m q L := by
+ unfold JointScalar.frame
+ exact (Frame.step_size_le _ _ _ (fun _ => finish_size_le prod localMap tables L hL)).trans
+ (by simp)
+
+/-- The number of query-independent Boolean gates in the joint checker. -/
+noncomputable def gateBound (C high motif m q L n t g W : ℕ) :=
+ 4 * (ParseOracle.gateBound C n W + (VerifierMachine.verifierFrame n).size +
+ finishBound n high t W (ParseOracle.flagCount C n) (n^clockExponent) motif g m q L)
+
+/-- Upper bound for the encoded Boolean checker length in terms of its gate count and query and
+witness widths. -/
+def adviceBound (G U K : ℕ) := (G+2)*(2*(G+U+K+2)+3)
+
+/-- Stack-step bound for testing one witness and advancing the enumerator for a signed
+coefficient query. -/
+def choiceBound (G U K : ℕ) := 32*(adviceBound G U K + (G+2) + U + K + 1) + 8*K + 9
+
+/-- Bound on the number of bits in each stack during the complete enumeration of coefficient
+witnesses. -/
+def stackBound (G U K : ℕ) := U + adviceBound G U K + (K+1) + choiceBound G U K
+
+/-- Instantiate the bounds with the grammar incidence circuit and the actual
+clocked path verifier at the given length. Both coordinate placements may vary
+with the length. The threshold and all query bits are runtime inputs. -/
+theorem specialized_le (C n t g W high motif : ℕ) (d : Fin n) (s : ParseOracle.States C n)
+ (addr : ParseOracle.Label n n (ParseOracle.States C n) → Fin t) (prod : Fin g → Fin t)
+ (localMap : Fin m → Fin t) (tables : Fin q → Motif.Table m) (L : ℕ) (hL : ∀ o, (tables o).length ≤ L) :
+ let flags := ParseOracle.Flags n n (ParseOracle.States C n)
+ let f := JointScalar.frame (high := high) (motif := motif) prod localMap tables
+ (ParseOracle.frame (parseOracleMetadata (ParseOracle.Var n) (ParseOracle.States C n) n d s) addr W)
+ (VerifierMachine.verifierFrame n)
+ let c := f.circuit ()
+ let G := gateBound C high motif m q L n t g W
+ let U := queryWidth n high t W
+ let K := witnessWidth flags (n^clockExponent) motif
+ f.circuitSize () ≤ G ∧ (AdviceCircuit.encode (AdviceCircuit.compile c)).length ≤ adviceBound G U K ∧
+ perChoice c ≤ choiceBound G U K ∧ stackLimit c ≤ stackBound G U K ∧
+ 2^K * perChoice c ≤ 2^(K + choiceBound G U K) := by
+ intro flags f c G U K
+ have hparse := ParseOracle.checker_frame_size_le d s addr W
+ have hframe := frame_size_le (high := high) (motif := motif) prod localMap tables
+ (ParseOracle.frame (parseOracleMetadata (ParseOracle.Var n) (ParseOracle.States C n) n d s) addr W)
+ (VerifierMachine.verifierFrame n) L hL
+ have hflags : Fintype.card (EventCode (ParseOracle.Var n) (ParseOracle.States C n) n) =
+ ParseOracle.flagCount C n := ParseOracle.flags_eq_flagCount C n
+ have hg : f.circuitSize () ≤ G := by
+ apply (Frame.circuitSize_le f ()).trans
+ apply Nat.mul_le_mul_left
+ rw [← hflags]
+ exact hframe.trans (Nat.add_le_add_right (Nat.add_le_add_right (by omega) _) _)
+ have ha : (AdviceCircuit.encode (AdviceCircuit.compile c)).length ≤ adviceBound G U K := by
+ apply (AdviceCircuit.compile_size c).trans
+ change (f.circuitSize () + 2)*(2*(f.circuitSize ()+U+K+2)+3) ≤ _
+ unfold adviceBound
+ gcongr
+ have hc : perChoice c ≤ choiceBound G U K := by
+ unfold perChoice choiceBound
+ rw [AdviceCircuit.compile_length]
+ change 32*((AdviceCircuit.encode (AdviceCircuit.compile c)).length + (f.circuitSize ()+2) + U + K + 1) + 8*K + 9 ≤ _
+ omega
+ have hs : stackLimit c ≤ stackBound G U K := by
+ unfold stackLimit stackBound
+ change max (max U _) (K+1) + perChoice c ≤ _
+ omega
+ refine ⟨hg, ha, hc, hs, ?_⟩
+ rw [pow_add 2 K (choiceBound G U K)]
+ exact Nat.mul_le_mul_left _ (hc.trans Nat.lt_two_pow_self.le)
+
+variable {width labels productions : ℕ → ℕ}
+
+/-- All parameters except the grammar, its coordinate count, and its exponent
+width are fixed independently of the input length. -/
+theorem gateBound_polynomial (C high motif m q L : ℕ) (hW : PolynomiallyBounded width)
+ (ht : PolynomiallyBounded labels) (hg : PolynomiallyBounded productions) :
+ PolynomiallyBounded (fun n => gateBound C high motif m q L n (labels n) (productions n) (width n)) := by
+ let hrow := PolynomiallyBounded.id.add (.const high)
+ let hflags := ParseOracle.flagCount_polynomial C
+ let hclock := PolynomiallyBounded.id.pow clockExponent
+ let hcmp := (hW.mul (.const 3)).add (.const 4)
+ let hmask := ((hg.add (.const m)).add ht).mul hcmp
+ let hpad := (PolynomiallyBounded.const 4).mul ((hflags.add hclock).add (.const motif))
+ let hentry := (((PolynomiallyBounded.const m).mul hcmp).add (.const (3*motif))).add (.const 8)
+ let hsel := (hrow.mul (.const 3)).add (.const 2)
+ let htab := ((PolynomiallyBounded.const q).mul
+ ((hsel.add ((PolynomiallyBounded.const L).mul hentry)).add (.const 3))).add (.const 1)
+ let hfirst := (PolynomiallyBounded.const 2).mul
+ (((PolynomiallyBounded.const 3).mul hrow).add (.const 1))
+ let hfinish := ((((hfirst.add hmask).add hpad).add htab).add (.const 39))
+ exact (PolynomiallyBounded.const 4).mul (((ParseOracle.gateBound_polynomial C hW).add
+ VerifierMachine.verifierFrame_polynomiallyBounded).add hfinish)
+
+/-- Convert gate count and physical word-bank lengths to bounds for the
+actual unary-address advice program and the stack enumerator. -/
+theorem stack_bounds_polynomial {G U K : ℕ → ℕ}
+ (hg : PolynomiallyBounded G) (hu : PolynomiallyBounded U) (hk : PolynomiallyBounded K) :
+ PolynomiallyBounded (fun n => adviceBound (G n) (U n) (K n)) ∧
+ PolynomiallyBounded (fun n => choiceBound (G n) (U n) (K n)) ∧
+ PolynomiallyBounded (fun n => stackBound (G n) (U n) (K n)) ∧
+ PolynomiallyBounded (fun n => K n + choiceBound (G n) (U n) (K n)) := by
+ let ha := (hg.add (.const 2)).mul (((PolynomiallyBounded.const 2).mul
+ (((hg.add hu).add hk).add (.const 2))).add (.const 3))
+ let hp := (((PolynomiallyBounded.const 32).mul
+ ((((ha.add (hg.add (.const 2))).add hu).add hk).add (.const 1))).add
+ ((PolynomiallyBounded.const 8).mul hk)).add (.const 9)
+ exact ⟨ha, hp, ((hu.add ha).add (hk.add (.const 1))).add hp, hk.add hp⟩
+
+/-- Polynomial resource bounds for the joint system in the formal coordinate
+order, for every exponent width polynomial in the input length. The table
+parameters depend only on the fixed motif system. -/
+theorem specialized_polynomial (V : Type*) [Fintype V] (C high motif q L : ℕ)
+ (hW : PolynomiallyBounded width) :
+ let t := fun n => JointLabelSystem.FixedRows.labelTotal V n C
+ let g := fun n => JointLabelSystem.FixedRows.productionCount n C
+ let G := fun n => gateBound C high motif (Fintype.card V) q L n (t n) (g n) (width n)
+ let U := fun n => queryWidth n high (t n) (width n)
+ let K := fun n => witnessWidth (ParseOracle.flagCount C n) (n^clockExponent) motif
+ PolynomiallyBounded G ∧ PolynomiallyBounded (fun n => adviceBound (G n) (U n) (K n)) ∧
+ PolynomiallyBounded (fun n => choiceBound (G n) (U n) (K n)) ∧
+ PolynomiallyBounded (fun n => stackBound (G n) (U n) (K n)) ∧
+ PolynomiallyBounded (fun n => K n + choiceBound (G n) (U n) (K n)) := by
+ intro t g G U K
+ have ht : PolynomiallyBounded t := JointLabelSystem.FixedRows.labelTotal_polynomiallyBounded V C
+ have hprod : PolynomiallyBounded g := ht.of_le (fun n => by
+ have h := JointLabelSystem.FixedRows.labelOrder_length V n C
+ change JointLabelSystem.FixedRows.productionCount n C ≤ JointLabelSystem.FixedRows.labelTotal V n C
+ omega)
+ have hgate : PolynomiallyBounded G := gateBound_polynomial C high motif _ q L hW ht hprod
+ have hu : PolynomiallyBounded U := (PolynomiallyBounded.const 1).add
+ ((PolynomiallyBounded.id.add (.const high)).add (ht.mul hW))
+ have hk : PolynomiallyBounded K := (ParseOracle.flagCount_polynomial C).add
+ ((PolynomiallyBounded.id.pow clockExponent).add (.const motif))
+ exact ⟨hgate, stack_bounds_polynomial hgate hu hk⟩
+
+/-- The same four polynomial bounds work for every physical query to the
+fixed motif and grammar checker at every length `n ≥ 2`. The fourth bounds
+the exponent of the exhaustive counting time. -/
+theorem checker_polynomial_resources (V I : Type*) [Fintype V] [Fintype I]
+ (F : I → MvPolynomial V ℤ) (C : ℕ) (hW : PolynomiallyBounded width) :
+ ∃ A B S T : ℕ → ℕ, PolynomiallyBounded A ∧ PolynomiallyBounded B ∧
+ PolynomiallyBounded S ∧ PolynomiallyBounded T ∧ ∀ n (hn : 2 ≤ n),
+ let c := checker V I F C hn (width n)
+ let k := witnessWidth (ParseOracle.Flags n n (ParseOracle.States C n)) (n^clockExponent) (motifWidth V I F)
+ (AdviceCircuit.encode (AdviceCircuit.compile c)).length ≤ A n ∧
+ perChoice c ≤ B n ∧ stackLimit c ≤ S n ∧ 2^k * perChoice c ≤ 2^(T n) := by
+ classical
+ let tables := sparseRows V I F
+ let L := Finset.univ.sup (fun o => (tables o).length)
+ have hL (o) : (tables o).length ≤ L := Finset.le_sup (f := fun o => (tables o).length) (Finset.mem_univ o)
+ let high := highWidth I
+ let motif := motifWidth V I F
+ let labels := fun n => JointLabelSystem.FixedRows.labelTotal V n C
+ let productions := fun n => JointLabelSystem.FixedRows.productionCount n C
+ let G := fun n => gateBound C high motif (Fintype.card V) (Fintype.card I) L n (labels n) (productions n) (width n)
+ let U := fun n => queryWidth n high (labels n) (width n)
+ let K := fun n => witnessWidth (ParseOracle.flagCount C n) (n^clockExponent) motif
+ obtain ⟨_, ha, hb, hs, ht⟩ := specialized_polynomial V C high motif (Fintype.card I) L hW
+ refine ⟨fun n => adviceBound (G n) (U n) (K n), fun n => choiceBound (G n) (U n) (K n),
+ fun n => stackBound (G n) (U n) (K n), fun n => K n + choiceBound (G n) (U n) (K n),
+ ha, hb, hs, ht, ?_⟩
+ intro n hn
+ have r := (specialized_le C n (labels n) (productions n) (width n) high motif
+ (rootLayer hn) (rootState C hn) (productionAddress V C) (denseProduction V C) (denseLocal V C)
+ tables L hL).2
+ have hk : K n = witnessWidth (ParseOracle.Flags n n (ParseOracle.States C n)) (n^clockExponent) motif :=
+ congrArg (fun k => witnessWidth k (n^clockExponent) motif) (ParseOracle.flags_eq_flagCount C n).symm
+ dsimp only
+ rw [hk]
+ exact r
+
+end JointScalar.Resources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/JointScalarRowPrefix.lean b/lean/OAI/Computability/VPVNP/JointScalarRowPrefix.lean
new file mode 100644
index 0000000000..d16f96ccda
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/JointScalarRowPrefix.lean
@@ -0,0 +1,189 @@
+import OAI.Computability.VPVNP.UniversalCountStackBounds
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.LiveHeaderBits
+
+/-!
+# Prepending the equation address to a packed scalar query
+
+The index register and the row field of the scalar query can have different
+widths. The length of an immutable unary template selects the low bits to
+prepend. A missing high bit is copied as zero. The two scratch stacks allow
+the source to be restored and the bits to be emitted in little-endian order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace JointScalar.RowPrefix
+
+open RAMTape UniversalCountStack BurstRAM
+
+set_option backward.isDefEq.respectTransparency false in
+/-- Stacks for the source equation address, unary output width, destination and two temporary
+bit sequences. -/
+inductive Port where | source | width | dst | saved | staged deriving DecidableEq, Fintype
+
+/-- Control states for staging the low address bits, restoring the source and emitting the
+resized row prefix. -/
+inductive Phase where
+ | scan | read | save (b : Bool) | stage (b : Bool) | restore | replace (b : Bool)
+ | flush | emit (b : Bool) | mark
+ deriving DecidableEq, Fintype
+
+private def code (marker : Bool) : Routine Port Phase where
+ entry := .scan
+ code
+ | .scan => .pop .width fun b => some (if b.isSome then .read else .restore)
+ | .read => .pop .source fun b => some (b.elim (.stage false) .save)
+ | .save b => .push .saved b (some (.stage b))
+ | .stage b => .push .staged b (some .scan)
+ | .restore => .pop .saved fun b => some (b.elim .flush .replace)
+ | .replace b => .push .source b (some .restore)
+ | .flush => .pop .staged (Option.map .emit)
+ | .emit b => .push .dst b (some .mark)
+ | .mark => .push .width marker (some .flush)
+
+/-- Prepend the equation address at the width specified by the unary template, restoring the
+source and template on return. -/
+def body (marker : Bool) : FiniteRoutine Port := .ofRoutine (code marker)
+
+/-- Assign the equation address, width template, destination and both temporary sequences to
+their respective stacks. -/
+def bank (row width dst saved staged : List Bool) : Stacks Port
+ | .source => row | .width => width | .dst => dst | .saved => saved | .staged => staged
+
+private theorem update_bank (x w y a b v : List Bool) (p : Port) :
+ Function.update (bank x w y a b) p v = match p with
+ | .source => bank v w y a b | .width => bank x v y a b | .dst => bank x w v a b
+ | .saved => bank x w y v b | .staged => bank x w y a v := by
+ funext j; cases p <;> cases j <;> rfl
+
+local macro "row_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [bank, update_bank, List.head?_nil, List.head?_cons, List.tail_nil, List.tail_cons,
+ Option.isSome_none, Option.isSome_some, Option.elim_none, Option.elim_some, Option.map_none,
+ Option.map_some, Bool.false_eq_true, ite_false, ite_true])
+
+/-- Take the requested number of low bits from a little-endian word, filling any missing high
+bits with zero. -/
+def resize : ℕ → List Bool → List Bool
+ | 0, _ => []
+ | n+1, xs => xs.headD false :: resize n xs.tail
+
+@[simp] theorem resize_length (n : ℕ) (xs : List Bool) : (resize n xs).length = n := by
+ induction n generalizing xs <;> simp [resize, *]
+
+private theorem resize_get (n : ℕ) (xs : List Bool) (i : ℕ) (hi : i < n) :
+ (resize n xs)[i]'(by simpa using hi) = xs[i]?.getD false := by
+ induction n generalizing xs i with
+ | zero => omega
+ | succ n ih =>
+ cases i with
+ | zero => cases xs <;> rfl
+ | succ i =>
+ change (resize n xs.tail)[i]'(by rw [resize_length]; omega) = _
+ rw [ih _ _ (by omega)]
+ cases xs <;> rfl
+
+/-- Canonical physical little-endian digits of an integer at any width. -/
+theorem digits_ofFn (r i : ℕ) : digits r i = List.ofFn (fun j : Fin r => i.testBit j.val) := by
+ apply congrArg List.ofFn
+ funext j
+ rw [← LiveHeader.testBit_wordBits]
+ simp [j.isLt]
+
+/-- Resize the low-bit array of a natural number. The source must represent
+the number. The result is the canonical low target-width word even on truncation. -/
+theorem resize_digits (target wr i : ℕ) (hi : i < 2^wr) : resize target (digits wr i) = digits target i := by
+ rw [digits_ofFn, digits_ofFn]
+ apply List.ext_getElem (by simp)
+ intro j hj _
+ rw [resize_get _ _ _ (by simpa using hj), List.getElem_ofFn]
+ by_cases h : j < wr
+ · rw [List.getElem?_eq_getElem (by simpa using h), List.getElem_ofFn]
+ rfl
+ · rw [List.getElem?_eq_none (by simp; omega)]
+ exact (Nat.testBit_lt_two_pow (hi.trans_le (Nat.pow_le_pow_right (by decide) (by omega : wr ≤ j)))).symm
+
+private theorem scan (marker : Bool) (n : ℕ) (xs y a b : List Bool) :
+ ∃ ticks ≤ 4*n, StackRuns (code marker).standalone ticks (some .scan)
+ (bank xs (List.replicate n marker) y a b) (some .scan)
+ (bank (xs.drop n) [] y ((xs.take n).reverse ++ a) ((resize n xs).reverse ++ b)) := by
+ induction n generalizing xs a b with
+ | zero =>
+ refine ⟨0, by simp, ?_⟩
+ simpa [resize] using StackRuns.nil (code := (code marker).standalone) (some Phase.scan) (bank xs [] y a b)
+ | succ n ih =>
+ cases xs with
+ | nil =>
+ obtain ⟨ticks, ht, run⟩ := ih [] a (false :: b)
+ refine ⟨ticks+3, by omega, ?_⟩
+ simp only [List.replicate_succ, resize, List.headD_nil, List.tail_nil, List.take_nil, List.drop_nil,
+ List.reverse_nil, List.nil_append, List.reverse_cons, List.append_assoc, List.singleton_append]
+ row_step
+ row_step
+ row_step
+ simpa using run
+ | cons x xs =>
+ obtain ⟨ticks, ht, run⟩ := ih xs (x :: a) (x :: b)
+ refine ⟨ticks+4, by omega, ?_⟩
+ simp only [List.replicate_succ, resize, List.headD_cons, List.tail_cons, List.take_succ_cons,
+ List.drop_succ_cons, List.reverse_cons, List.append_assoc, List.singleton_append]
+ row_step
+ row_step
+ row_step
+ row_step
+ exact run
+
+private theorem restore (marker : Bool) (xs y a b : List Bool) :
+ StackRuns (code marker).standalone (2*a.length+1) (some .restore) (bank xs [] y a b)
+ (some .flush) (bank (a.reverse ++ xs) [] y [] b) := by
+ induction a generalizing xs with
+ | nil => row_step; exact .nil ..
+ | cons u a ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ row_step
+ row_step
+ exact ih (u::xs)
+
+private theorem flush (marker : Bool) (xs y b : List Bool) (markers : ℕ) :
+ StackRuns (code marker).standalone (3*b.length+1) (some .flush)
+ (bank xs (List.replicate markers marker) y [] b) none
+ (bank xs (List.replicate (markers+b.length) marker) (b.reverse ++ y) [] []) := by
+ induction b generalizing y markers with
+ | nil => row_step; exact .nil ..
+ | cons u b ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ row_step
+ row_step
+ row_step
+ simpa only [List.replicate_succ, Nat.succ_add, Nat.add_succ] using ih (u::y) (markers+1)
+
+/-- All input stacks are restored. Only the destination gains bits. -/
+theorem runs (marker : Bool) (target wr i : ℕ) (hi : i < 2^wr) (dst : List Bool) :
+ ∃ ticks ≤ 9*target+3, (body marker).Runs ticks
+ (bank (digits wr i) (List.replicate target marker) dst [] [])
+ (bank (digits wr i) (List.replicate target marker) (digits target i ++ dst) [] []) := by
+ let xs := digits wr i
+ let a := (xs.take target).reverse
+ let b := (resize target xs).reverse
+ obtain ⟨n, hn, first⟩ := scan marker target xs dst [] []
+ simp only [List.append_nil] at first
+ have hrest : StackRuns (code marker).standalone (2*a.length+1+1) (some .scan)
+ (bank (xs.drop target) [] dst a b) (some .flush) (bank xs [] dst [] b) := by
+ row_step
+ simpa [a] using restore marker (xs.drop target) dst a b
+ have final := (first.trans hrest).trans (flush marker xs dst b 0)
+ have ha : a.length ≤ target := by simp [a]
+ have hb : b.length = target := by simp [b]
+ refine ⟨n + (2*a.length+1+1) + (3*b.length+1), by omega, ?_⟩
+ change StackRuns (code marker).standalone _ (some .scan) _ none _
+ simpa only [b, List.replicate_zero, Nat.zero_add, List.reverse_reverse, List.length_reverse,
+ resize_length, xs, resize_digits target wr i hi, length_digits] using final
+
+end JointScalar.RowPrefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LabelEvaluator.lean b/lean/OAI/Computability/VPVNP/LabelEvaluator.lean
new file mode 100644
index 0000000000..ed72c684f2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LabelEvaluator.lean
@@ -0,0 +1,186 @@
+import OAI.Computability.VPVNP.EffectiveNullstellensatz
+import OAI.Computability.VPVNP.ScalarDescent
+import OAI.Computability.VPVNP.SliceEvaluator
+import OAI.Computability.VPVNP.SliceField
+import OAI.Computability.VPVNP.SliceGeometry
+
+/-!
+# Algebraic descent and the matrix-path identity for the label evaluator
+
+For a satisfiable integer label system, Section 8.2 chooses one prime and one
+finite algebra with normalized functional for all exponent inputs. In positive
+characteristic the prime is the original characteristic. In characteristic
+zero its bit length is bounded using the actual coefficient matrix. The
+coordinate pins, slice field and monomial list have explicit bounds.
+The counted branches below are the matrix-index paths of equation (8.2).
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LabelEvaluator
+
+open MvPolynomial RadicalCertificate FiniteSlice SliceGeometry
+
+variable {t : ℕ} {ι : Type*}
+
+local instance (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+
+/-- Bound on multiplier degrees in the effective polynomial-identity certificate for a system
+in `t` variables of degree at most `d`. -/
+abbrev multiplierDegree (t d : ℕ) := (2 * d) ^ (4 * (t + 2))
+/-- Bound on the number of monomial columns used in the corresponding bounded-degree
+coefficient system. -/
+abbrev columnCountBound (t d : ℕ) := (multiplierDegree t d + d + 1) ^ t
+/-- Uniform upper bound on the number of geometric points in the finite slice. -/
+abbrev pointCountBound (t d : ℕ) := (2 * columnCountBound t d) ^ t
+
+/-- Finite extension of the prime field chosen from the column-count bound to supply slice
+coordinates. -/
+abbrev Ground (p : Nat.Primes) (t d : ℕ) := SliceField.FieldOf p.val (columnCountBound t d)
+/-- Algebraic closure of the prime field in which the geometric zero set is taken. -/
+abbrev Ambient (p : Nat.Primes) := AlgebraicClosure (ZMod p.val)
+
+/-- Finite enumeration of the label evaluator's slice ground field. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+/-- Regard the ambient algebraic closure as an algebra over the finite slice ground field via
+its embedding. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) :=
+ (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra
+
+private theorem aeval_map_int {R A : Type*} [CommRing R] [CommRing A] [Algebra R A]
+ (u : Fin t → A) (f : MvPolynomial (Fin t) ℤ) :
+ aeval u (map (Int.castRingHom R) f) = eval₂ (Int.castRingHom A) u f := by
+ rw [aeval_def, eval₂_map]
+ exact congrArg (fun h => eval₂ h u f) (Subsingleton.elim _ _)
+
+/-- The affine ideal obtained by base change and pinning the selected coordinates. -/
+noncomputable abbrev sliceIdeal (p : Nat.Primes) (d : ℕ) (F : ι → MvPolynomial (Fin t) ℤ)
+ (s : Finset (Fin t)) (a : Fin t → Ground p t d) : Ideal (MvPolynomial (Fin t) (Ground p t d)) :=
+ pinnedIdeal (fun i => map (Int.castRingHom (Ground p t d)) (F i)) s a
+
+/-- The slice chosen for this system, including its ordered monomial basis. -/
+structure Model (p : Nat.Primes) (d : ℕ) (F : ι → MvPolynomial (Fin t) ℤ) where
+ /-- Coordinates fixed by affine equations when selecting this model's finite geometric slice. -/
+ pins : Finset (Fin t)
+ /-- Ground-field values assigned to the pinned coordinates of the slice. -/
+ values : Fin t → Ground p t d
+ nonempty : (zeroLocus (Ambient p) (sliceIdeal p d F pins values)).Nonempty
+ finite : (zeroLocus (Ambient p) (sliceIdeal p d F pins values)).Finite
+ pointCount_le : (zeroLocus (Ambient p) (sliceIdeal p d F pins values)).ncard ≤ pointCountBound t d
+ /-- Monomial basis presentation of the coordinate algebra of the finite slice, up to the
+ point-count bound. -/
+ presentation : SliceEvaluator.Presentation (Ground p t d) (sliceIdeal p d F pins values)
+ (pointCountBound t d) (E := Ambient p)
+ listing_length_le : presentation.lastIndex + 1 ≤ (pointCountBound t d + 1) ^ t
+
+variable {p : Nat.Primes} {d : ℕ} {F : ι → MvPolynomial (Fin t) ℤ}
+
+/-- Reduced coordinate algebra of the slice defined by the original label equations and the
+model's pinned coordinates. -/
+abbrev Model.algebra (M : Model p d F) :=
+ CoordinateAlgebra (Ground p t d) (zeroLocus (Ambient p) (sliceIdeal p d F M.pins M.values))
+
+/-- Elements of the coordinate algebra represented by the original label variables. -/
+noncomputable abbrev Model.labels (M : Model p d F) : Fin t → M.algebra :=
+ coordinateLabel (zeroLocus (Ambient p) (sliceIdeal p d F M.pins M.values))
+
+/-- Normalized prime-field linear functional used to evaluate products of the model's labels. -/
+noncomputable abbrev Model.functional (M : Model p d F) : M.algebra →ₗ[ZMod p.val] ZMod p.val :=
+ M.presentation.functional
+
+theorem Model.finite_algebra (M : Model p d F) : Finite M.algebra := by
+ let : Fintype (zeroLocus (Ambient p) (sliceIdeal p d F M.pins M.values)) := M.finite.fintype
+ have h := coordinateAlgebra_finite_finrank (E := Ambient p) (sliceIdeal p d F M.pins M.values)
+ let : Module.Finite (Ground p t d) M.algebra := h.1
+ exact Module.finite_of_finite (Ground p t d)
+
+theorem Model.reduced (M : Model p d F) : IsReduced M.algebra :=
+ coordinateAlgebra_isReduced _
+
+theorem Model.solution (M : Model p d F) (i : ι) :
+ eval₂ (Int.castRingHom M.algebra) M.labels (F i) = 0 := by
+ have hf : map (Int.castRingHom (Ground p t d)) (F i) ∈ sliceIdeal p d F M.pins M.values :=
+ Ideal.subset_span ⟨Sum.inl i, rfl⟩
+ rw [← aeval_map_int (R := Ground p t d), aeval_coordinateLabel]
+ exact equation_eq_zero _ _ hf
+
+theorem Model.functional_one (M : Model p d F) : M.functional 1 = 1 := M.presentation.functional_one
+
+/-- The count uses the same field, basis, labels and functional at every input width. -/
+theorem Model.branchCount_mod (M : Model p d F) (width : ℕ) (e : Fin t → ℕ)
+ (he : ∀ i, e i < 2 ^ width) :
+ (M.presentation.branchCount p.val width e : ZMod p.val) = M.functional (∏ i, M.labels i ^ e i) :=
+ M.presentation.branchCount_mod width e he
+
+/-- The slice field and ordered evaluator data exist from a geometric point in
+the chosen prime characteristic, with the effective bound discharged. -/
+theorem model_of_geometric_solution [Fintype ι] (p : Nat.Primes) (d : ℕ) (hd : 3 ≤ d)
+ (F : ι → MvPolynomial (Fin t) ℤ) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (x : Fin t → Ambient p) (hx : ∀ i, eval₂ (Int.castRingHom (Ambient p)) x (F i) = 0) :
+ Nonempty (Model p d F) := by
+ let H := multiplierDegree t d
+ let K := Ground p t d
+ let G (i : ι) := map (Int.castRingHom K) (F i)
+ have hcard : projectionBound t H d < Fintype.card K := by
+ rw [← Nat.card_eq_fintype_card]
+ exact SliceField.field_card_gt _ _
+ have hdeg (i : ι) : (G i).totalDegree ≤ d :=
+ (Finset.sup_mono (support_map_subset _ _)).trans (hF i)
+ have hG (i : ι) : aeval x (G i) = 0 :=
+ (aeval_map_int (R := K) x (F i)).trans (hx i)
+ obtain ⟨s, a, hn, hfin, hc⟩ := exists_finite_coordinate_slice G hdeg (by omega) hcard
+ ⟨x, hG⟩ (effective_weakCertificateBound (Ambient p) _ hd)
+ let I := sliceIdeal p d F s a
+ let : Fintype (zeroLocus (Ambient p) I) := hfin.fintype
+ have : Nonempty (zeroLocus (Ambient p) I) := hn.to_subtype
+ have hc' : Fintype.card (zeroLocus (Ambient p) I) ≤ pointCountBound t d := by
+ rw [← Nat.card_eq_fintype_card]
+ exact hc
+ obtain ⟨P, hlist, _⟩ := SliceEvaluator.exists_sliceEvaluator p.val I hc'
+ exact ⟨⟨s, a, hn, hfin, hc, P, hlist⟩⟩
+
+/-- A solution in any field of positive characteristic gives the evaluator in
+that same characteristic. -/
+theorem exists_model_positive [Fintype ι] {k : Type*} [Field k] (p : Nat.Primes) [CharP k p.val]
+ (F : ι → MvPolynomial (Fin t) ℤ) (d : ℕ) (hd : 3 ≤ d) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (x : Fin t → k) (hx : ∀ i, eval₂ (Int.castRingHom k) x (F i) = 0) :
+ Nonempty (Model p d F) := by
+ let := ZMod.algebra k p.val
+ let G (i : ι) := map (Int.castRingHom (ZMod p.val)) (F i)
+ obtain ⟨y, hy⟩ := polynomialSystem_descent (K := Ambient p) (Set.range G) x (by
+ rintro _ ⟨i, rfl⟩
+ exact (aeval_map_int (R := ZMod p.val) x (F i)).trans (hx i))
+ exact model_of_geometric_solution p d hd F hF y fun i =>
+ (aeval_map_int (R := ZMod p.val) y (F i)).symm.trans (hy _ ⟨i, rfl⟩)
+
+/-- The chosen prime in characteristic zero admits a geometric solution of the
+original integer equations. The effective multiplier bound is proved internally. -/
+theorem exists_prime_solution [Fintype ι] {k : Type*} [Field k] [CharZero k]
+ (F : ι → MvPolynomial (Fin t) ℤ) (d b : ℕ) (hd : 3 ≤ d) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (hcoeff : ∀ i a, ((F i).coeff a).natAbs ≤ 2 ^ b)
+ (x : Fin t → k) (hx : ∀ i, eval₂ (Int.castRingHom k) x (F i) = 0) :
+ let a := Nat.clog 2 (multiplierDegree t d + d + 1) * t
+ ∃ p : Nat.Primes, p.val ≤ 2 ^ (2 * (a + Nat.clog 2 (a + b + 2)) + 1) ∧
+ ∃ y : Fin t → Ambient p, ∀ i, eval₂ (Int.castRingHom (Ambient p)) y (F i) = 0 :=
+ CertificateReduction.exists_prime_solution_of_weakCertificateBound F
+ (multiplierDegree t d) d b hF hcoeff x hx (fun p => effective_weakCertificateBound (Ambient p) ι hd)
+
+/-- Characteristic-zero descent, with the prime-size bound independent of the
+subsequent exponent width and processor program. -/
+theorem exists_model_charZero [Fintype ι] {k : Type*} [Field k] [CharZero k]
+ (F : ι → MvPolynomial (Fin t) ℤ) (d b : ℕ) (hd : 3 ≤ d) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (hcoeff : ∀ i a, ((F i).coeff a).natAbs ≤ 2 ^ b)
+ (x : Fin t → k) (hx : ∀ i, eval₂ (Int.castRingHom k) x (F i) = 0) :
+ let a := Nat.clog 2 (multiplierDegree t d + d + 1) * t
+ ∃ p : Nat.Primes, p.val ≤ 2 ^ (2 * (a + Nat.clog 2 (a + b + 2)) + 1) ∧
+ Nonempty (Model p d F) := by
+ obtain ⟨p, hp, y, hy⟩ := exists_prime_solution F d b hd hF hcoeff x hx
+ exact ⟨p, hp, model_of_geometric_solution p d hd F hF y hy⟩
+
+end LabelEvaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LabelEvaluatorCanonical.lean b/lean/OAI/Computability/VPVNP/LabelEvaluatorCanonical.lean
new file mode 100644
index 0000000000..77f2b4591c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LabelEvaluatorCanonical.lean
@@ -0,0 +1,249 @@
+import OAI.Computability.VPVNP.LabelEvaluatorIndexedPins
+import OAI.Computability.VPVNP.MacaulaySliceBasis
+
+/-!
+# The graded monomial basis of the label evaluator
+
+The dense ordinals returned by the prefix-rank algorithm are identified with
+the retained indices of a slice presentation. Multiplication and Frobenius
+entries in this presentation are exactly the scalars returned by the indexed
+query. The distinguished unit is dense ordinal zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.QueryData
+
+open MvPolynomial FiniteSlice RankQuery
+
+variable {K E : Type*} [Field K] [Fintype K] [DecidableEq K] [Field E] [Algebra K E]
+ {t k : ℕ}
+
+/-- A slice presentation whose listing, dense basis ordinals and field-valued
+queries use the same enumeration of monomials. -/
+structure Canonical (S : QueryData t k K) (I : Ideal (MvPolynomial (Fin t) K)) where
+ /-- Monomial presentation of the finite-slice coordinate algebra identified with the bounded
+ rank-query data. -/
+ presentation : SliceEvaluator.Presentation K I S.pointBound (E := E)
+ size_eq : presentation.lastIndex + 1 = size t S.pointBound
+ listing_eq (j : Fin (presentation.lastIndex + 1)) : presentation.listing j =
+ Ideal.Quotient.mkₐ K (vanishingIdeal K (zeroLocus E I))
+ (monomialAt t S.pointBound (j.cast size_eq))
+ /-- Equivalence from dense basis ordinals to the greedy pivot indices in the canonical
+ monomial listing. -/
+ ordinal : Fin S.dimension ≃ greedyIndices K presentation.listing
+ ordinal_val (j : Fin S.dimension) : (ordinal j).val.val = (S.basisIndex j).val
+ unit_ordinal : (ordinal.symm presentation.unitIndex).val = 0
+ entry_eq (op : Operation t) (i j : Fin S.dimension) :
+ S.matrixEntry op i j = presentation.basis.repr
+ (op.apply S.fieldOrder (coordinateLabel (zeroLocus E I)) (presentation.basis (ordinal j))) (ordinal i)
+
+private noncomputable def gradedListing (V : Set (Fin t → E)) (N : ℕ) (j : Fin (size t N)) :
+ CoordinateAlgebra K V :=
+ Ideal.Quotient.mkₐ K (vanishingIdeal K V) (monomialAt t N j)
+
+private def reindexRetained {A : Type*} [AddCommGroup A] [Module K A]
+ {n m : ℕ} (h : m = n) (v : Fin n → A) :
+ greedyIndices K v ≃ greedyIndices K (fun j : Fin m => v (j.cast h)) := by
+ subst m
+ exact Equiv.refl _
+
+omit [Fintype K] [DecidableEq K] in
+private theorem reindexRetained_val {A : Type*} [AddCommGroup A] [Module K A]
+ {n m : ℕ} (h : m = n) (v : Fin n → A) (j : greedyIndices K v) :
+ ((reindexRetained h v) j).val.val = j.val.val := by subst m; rfl
+
+/-- Build the canonical presentation from the very equations used to query
+the matrix, allowing any equal presentation of their affine ideal. -/
+theorem exists_canonical [IsAlgClosed E] (S : QueryData t k K)
+ (F : Fin k → MvPolynomial (Fin t) K) (h : S.Presents F)
+ (I : Ideal (MvPolynomial (Fin t) K)) (hI : I = Ideal.span (Set.range F))
+ (hn : (zeroLocus E I).Nonempty) (hfin : (zeroLocus E I).Finite)
+ (hc : (zeroLocus E I).ncard ≤ S.pointBound) : Nonempty (Canonical (E := E) S I) := by
+ classical
+ let V := zeroLocus E I
+ let N := S.pointBound
+ let v := gradedListing (K := K) V N
+ let z : Fin (size t N) := ⟨0, size_pos t N⟩
+ have hv : V = points F E := by ext x; simp [V, hI, points, zeroLocus_span]
+ have data : Set.range v = MonomialBasis.monomials (coordinateLabel V) N ∧ v z = 1 ∧
+ Set.range S.basisIndex = (greedyIndices K v : Set _) ∧
+ ∃ b : Module.Basis (Fin S.dimension) K (CoordinateAlgebra K V),
+ (∀ i, b i = v (S.basisIndex i)) ∧ (∃ u : Fin S.dimension, u.val = 0 ∧ b u = 1) ∧
+ ∀ op i j, S.matrixEntry op i j =
+ b.repr (op.apply S.fieldOrder (coordinateLabel V) (b j)) i := by
+ have hn' : V.Nonempty := hn
+ have hf' : V.Finite := hfin
+ have hc' : V.ncard ≤ N := hc
+ dsimp only [v]
+ rw [hv] at hn' hf' hc' ⊢
+ obtain ⟨b, hb, hu, _, hm⟩ := S.finite_slice_coordinate_queries F h hn' hf' hc'
+ exact ⟨S.listing_range F, S.listing_first F, Set.ext (S.basisIndex_mem_iff F h),
+ b, hb, hu, hm⟩
+ obtain ⟨hrange, hz, hindices, b, hb, ⟨u, hu, hbu⟩, hm⟩ := data
+ have : Nonempty V := hn.to_subtype
+ have : Nontrivial (CoordinateAlgebra K V) := coordinateAlgebra_nontrivial V
+ have hz' : z ∈ greedyIndices K v := by
+ have hempty : Set.Iio z = ∅ := by ext i; simp [z, Fin.le_def]
+ rw [mem_greedyIndices, hempty, hz]
+ simp
+ have hzrange : z ∈ Set.range S.basisIndex := hindices.symm ▸ hz'
+ obtain ⟨j, hj⟩ := hzrange
+ have hj' : b j = 1 := (hb j).trans (hj ▸ hz)
+ have hunit : S.basisIndex u = z := b.injective (hbu.trans hj'.symm) ▸ hj
+ let n := size t N - 1
+ have hsz : n + 1 = size t N := by dsimp [n]; have := size_pos t N; omega
+ let listing (i : Fin (n+1)) := v (i.cast hsz)
+ let raw := (Equiv.ofInjective S.basisIndex (suffixBasisIndex_injective S.equations S.monomials)).trans
+ (Set.equivOfEq hindices)
+ let ord := raw.trans (reindexRetained hsz v)
+ have hord (i) : (ord i).val.val = (S.basisIndex i).val :=
+ reindexRetained_val hsz v (raw i)
+ let basis := b.reindex ord
+ have hlist (i : greedyIndices K listing) : basis i = listing i.val := by
+ obtain ⟨j, rfl⟩ := ord.surjective i
+ rw [Module.Basis.reindex_apply, Equiv.symm_apply_apply, hb]
+ exact congrArg v (Fin.ext (hord j).symm)
+ have hlistRange : Set.range listing = Set.range v :=
+ (finCongr hsz).surjective.range_comp v
+ let P : SliceEvaluator.Presentation K I N (E := E) :=
+ ⟨n, listing, hlistRange.trans hrange, hz, basis, hlist, ord u, Fin.ext ((hord u).trans (congrArg Fin.val hunit))⟩
+ refine ⟨⟨P, hsz, fun _ => rfl, ord, hord, ?_, ?_⟩⟩
+ · change (ord.symm (ord u)).val = 0
+ rwa [Equiv.symm_apply_apply]
+ · intro op i j
+ change _ = (b.reindex ord).repr (op.apply _ _ ((b.reindex ord) (ord j))) (ord i)
+ simp only [Module.Basis.reindex_apply, Module.Basis.repr_reindex_apply, Equiv.symm_apply_apply]
+ exact hm op i j
+
+end RadicalCertificate.MonomialIndex.QueryData
+
+namespace RadicalCertificate.MonomialIndex.QueryData
+
+open MvPolynomial FiniteSlice
+
+variable {K E : Type*} [Field K] [Fintype K] [DecidableEq K] [Field E] [Algebra K E]
+ {t k : ℕ} {S : QueryData t k K} {I : Ideal (MvPolynomial (Fin t) K)}
+
+/-- The canonical presentation's basis, indexed by the dense machine ordinals. -/
+noncomputable def Canonical.denseBasis (D : Canonical (E := E) S I) :
+ Module.Basis (Fin S.dimension) K (CoordinateAlgebra K (zeroLocus E I)) :=
+ D.presentation.basis.reindex D.ordinal.symm
+
+omit [Fintype K] in
+/-- Ordinal `i` denotes exactly the basis monomial returned by the numeric prefix ranks. -/
+theorem Canonical.denseBasis_apply (D : Canonical (E := E) S I) (i : Fin S.dimension) :
+ D.denseBasis i = Ideal.Quotient.mkₐ K (vanishingIdeal K (zeroLocus E I))
+ (monomialAt t S.pointBound (S.basisIndex i)) := by
+ rw [denseBasis, Module.Basis.reindex_apply, Equiv.symm_symm, D.presentation.basis_apply, D.listing_eq]
+ exact congrArg (fun j => Ideal.Quotient.mkₐ K _ (monomialAt t S.pointBound j)) (Fin.ext (D.ordinal_val i))
+
+omit [Fintype K] in
+/-- The physical query stores the coefficient at the destination ordinal. -/
+theorem Canonical.matrixEntry_dense (D : Canonical (E := E) S I) (op : Operation t)
+ (dest src : Fin S.dimension) :
+ S.matrixEntry op dest src = D.denseBasis.repr
+ (op.apply S.fieldOrder (coordinateLabel (zeroLocus E I)) (D.denseBasis src)) dest := by
+ simpa only [denseBasis, Module.Basis.reindex_apply, Module.Basis.repr_reindex_apply, Equiv.symm_symm]
+ using D.entry_eq op dest src
+
+omit [Fintype K] in
+/-- The path matrix is transposed relative to the coefficient array of label multiplication. -/
+theorem Canonical.label_transition (D : Canonical (E := E) S I) (j : Fin t)
+ (src dest : Fin S.dimension) :
+ ((LinearMap.toMatrixAlgEquiv D.denseBasis)
+ (LinearMap.mulLeft K (coordinateLabel (zeroLocus E I) j))).transpose src dest =
+ S.matrixEntry (.label j) dest src := by
+ rw [D.matrixEntry_dense, Matrix.transpose_apply, LinearMap.toMatrixAlgEquiv_apply]
+ rfl
+
+/-- The Frobenius path matrix has the same destination/source convention. -/
+theorem Canonical.frobenius_transition (D : Canonical (E := E) S I) (hQ : S.fieldOrder = Fintype.card K)
+ (src dest : Fin S.dimension) :
+ ((LinearMap.toMatrixAlgEquiv D.denseBasis)
+ (FiniteField.frobeniusAlgHom K _).toLinearMap).transpose src dest =
+ S.matrixEntry .frobenius dest src := by
+ rw [D.matrixEntry_dense, Matrix.transpose_apply, LinearMap.toMatrixAlgEquiv_apply, hQ]
+ rfl
+
+omit [Fintype K] in
+/-- The dense unit ordinal labels the constant monomial. -/
+theorem Canonical.denseBasis_unit (D : Canonical (E := E) S I) :
+ D.denseBasis (D.ordinal.symm D.presentation.unitIndex) = 1 := by
+ rw [denseBasis, Module.Basis.reindex_apply, Equiv.symm_symm, Equiv.apply_symm_apply,
+ D.presentation.basis_apply, D.presentation.unitIndex_val, D.presentation.first_eq_one]
+
+/-- The output functional first reads the dense unit ordinal and then the
+prime-field coordinate of that coefficient. -/
+theorem Canonical.functional_apply {p : ℕ} [Fact p.Prime] [Algebra (ZMod p) K]
+ (D : Canonical (E := E) S I) (x : CoordinateAlgebra K (zeroLocus E I)) :
+ D.presentation.functional (p := p) x = SliceEvaluator.primeCoordinate p K
+ (D.denseBasis.repr x (D.ordinal.symm D.presentation.unitIndex)) := by
+ simp only [denseBasis, Module.Basis.repr_reindex_apply, Equiv.symm_symm, Equiv.apply_symm_apply]
+ rfl
+
+end RadicalCertificate.MonomialIndex.QueryData
+
+namespace LabelEvaluator
+
+open MvPolynomial RadicalCertificate RadicalCertificate.MonomialIndex
+
+local instance (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+/-- Finite enumeration of the ground field used to identify the canonical rank-query
+presentation. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+/-- Decidable equality on the finite ground field used to select canonical pivots. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : DecidableEq (Ground p t d) := Classical.decEq _
+/-- Algebra structure on the ambient field induced by the ground-field embedding for the
+canonical presentation. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) :=
+ (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra
+
+variable {p : Nat.Primes} {t d m : ℕ} {ι : Type*} {F : ι → MvPolynomial (Fin t) ℤ}
+
+/-- Select the presentation for this exact input reader, prime and advised slice. -/
+noncomputable def Model.canonicalPresentation (M : Model p d F) (r : Fin m ≃ ι)
+ (read : Fin m → (Fin t → ℕ) → ℤ) (hd : 3 ≤ d) (hdeg : ∀ i, (F i).totalDegree ≤ d)
+ (hread : ∀ i a, read i a = (F (r i)).coeff (exponentVector a)) :
+ (M.queryData read).Canonical (E := Ambient p) (sliceIdeal p d F M.pins M.values) :=
+ Classical.choice ((M.queryData read).exists_canonical (M.indexedEquations r)
+ (M.queryData_presents r read hd hdeg hread) _ (M.span_indexedEquations r).symm
+ M.nonempty M.finite M.pointCount_le)
+
+/-- Use the verified ordinal basis in the algebraic label evaluator at every
+input exponent vector and every bit width. -/
+noncomputable def Model.withCanonicalPresentation (M : Model p d F) {read : Fin m → (Fin t → ℕ) → ℤ}
+ (D : (M.queryData read).Canonical (E := Ambient p) (sliceIdeal p d F M.pins M.values)) : Model p d F :=
+ { M with
+ presentation := D.presentation
+ listing_length_le := by rw [D.size_eq, size_eq_card]; exact card_boundedMonomial_le .. }
+
+/-- For the rebuilt model the actual physical ordinal in the first coordinate
+of the functional has value zero. -/
+theorem Model.canonical_functional (M : Model p d F) {read : Fin m → (Fin t → ℕ) → ℤ}
+ (D : (M.queryData read).Canonical (E := Ambient p) (sliceIdeal p d F M.pins M.values)) :
+ ∃ u : Fin (M.queryData read).dimension, u.val = 0 ∧
+ ∀ x : M.algebra, (M.withCanonicalPresentation D).functional x =
+ SliceEvaluator.primeCoordinate p.val (Ground p t d) (D.denseBasis.repr x u) :=
+ ⟨D.ordinal.symm D.presentation.unitIndex, D.unit_ordinal, D.functional_apply⟩
+
+/-- Counting matrix-index paths on the actual dense ordinals recovers the
+functional of the canonical model modulo the advised prime. -/
+theorem Model.canonical_pathCount_mod (M : Model p d F) {read : Fin m → (Fin t → ℕ) → ℤ}
+ (D : (M.queryData read).Canonical (E := Ambient p) (sliceIdeal p d F M.pins M.values))
+ (width : ℕ) (a : Fin t → ℕ) (ha : ∀ i, a i < 2 ^ width) :
+ let u := D.ordinal.symm D.presentation.unitIndex
+ (Fintype.card (Evaluator.AcceptingBranches (SliceEvaluator.primeCoordinate p.val (Ground p t d))
+ (Evaluator.transitionMatrices D.denseBasis (Evaluator.digitProgram (Ground p t d) M.labels width a))
+ u u) : ZMod p.val) = (M.withCanonicalPresentation D).functional (∏ i, M.labels i ^ a i) := by
+ intro u
+ rw [Evaluator.finiteAlgebra_pathCount D.denseBasis u D.denseBasis_unit _ _ _ _ ha]
+ exact (D.functional_apply _).symm
+
+end LabelEvaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LabelEvaluatorIndexedPins.lean b/lean/OAI/Computability/VPVNP/LabelEvaluatorIndexedPins.lean
new file mode 100644
index 0000000000..8c989fcbf1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LabelEvaluatorIndexedPins.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.LabelEvaluator
+import OAI.Computability.VPVNP.AffineSliceQuery
+
+/-!
+# The indexed equations of the label evaluator's actual slice
+
+An enumeration of the original equations is followed by one slot per
+coordinate. The slot contains the advised coordinate equation when its mask
+bit is set, and the zero polynomial otherwise.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LabelEvaluator
+
+open RadicalCertificate.MonomialIndex MvPolynomial SliceGeometry
+
+local instance (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+/-- Finite enumeration of the ground field used to index possible values of pinned coordinates. -/
+noncomputable local instance (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+
+variable {p : Nat.Primes} {t d m : ℕ} {ι : Type*} {F : ι → MvPolynomial (Fin t) ℤ}
+
+/-- The zero or affine pin in one coordinate slot. -/
+noncomputable def Model.pinCut (M : Model p d F) (j : Fin t) : AffineCut t (Ground p t d) :=
+ if j ∈ M.pins then ⟨-M.values j, Pi.single j 1⟩ else ⟨0, 0⟩
+
+theorem Model.pinCut_polynomial (M : Model p d F) (j : Fin t) :
+ (M.pinCut j).polynomial = if j ∈ M.pins then X j - C (M.values j) else 0 := by
+ by_cases h : j ∈ M.pins
+ · simp only [pinCut, h, ↓reduceIte, AffineCut.polynomial, map_neg]
+ rw [Finset.sum_eq_single j]
+ · simp [sub_eq_add_neg, add_comm, X]
+ · intro i _ hij
+ simp [Pi.single_eq_of_ne hij]
+ · simp
+ · simp [pinCut, h, AffineCut.polynomial]
+
+/-- Numeric row order of the exact polynomial system presented by the advice. -/
+noncomputable def Model.indexedEquations (M : Model p d F) (r : Fin m ≃ ι) :
+ Fin (m+t) → MvPolynomial (Fin t) (Ground p t d) :=
+ slicedSystem (F ∘ r) M.pinCut
+
+/-- Macaulay queries use the original integer coefficient reader and the
+advised pins in the same order as `indexedEquations`. -/
+noncomputable def Model.queryData (M : Model p d F)
+ (read : Fin m → (Fin t → ℕ) → ℤ) : QueryData t (m+t) (Ground p t d) :=
+ slicedQueryData (Fintype.card (Ground p t d)) d (pointCountBound t d) read M.pinCut
+
+theorem Model.queryData_presents (M : Model p d F) (r : Fin m ≃ ι)
+ (read : Fin m → (Fin t → ℕ) → ℤ) (hd : 3 ≤ d) (hdeg : ∀ i, (F i).totalDegree ≤ d)
+ (hread : ∀ i a, read i a = (F (r i)).coeff (exponentVector a)) :
+ (M.queryData read).Presents (M.indexedEquations r) :=
+ slicedQueryData_presents (F ∘ r) _ _ _ read M.pinCut rfl hd (fun i => hdeg (r i)) hread
+
+theorem Model.span_indexedEquations (M : Model p d F) (r : Fin m ≃ ι) :
+ Ideal.span (Set.range (M.indexedEquations r)) = sliceIdeal p d F M.pins M.values := by
+ change Ideal.span _ = Ideal.span (Set.range (pinnedEquations _ _ _))
+ apply congrArg Ideal.span
+ ext x
+ constructor
+ · rintro ⟨i, rfl⟩
+ refine Fin.addCases (m := m) (n := t) (motive := fun i => M.indexedEquations r i ∈ _) ?_ ?_ i
+ · intro j
+ exact ⟨Sum.inl (r j), by simp [indexedEquations, slicedSystem, pinnedEquations]⟩
+ · intro j
+ exact ⟨Sum.inr j, by simp [indexedEquations, slicedSystem, pinnedEquations, pinCut_polynomial]⟩
+ · rintro ⟨i | j, rfl⟩
+ · exact ⟨(r.symm i).castAdd t, by simp [indexedEquations, slicedSystem, pinnedEquations]⟩
+ · exact ⟨j.natAdd m, by simp [indexedEquations, slicedSystem, pinnedEquations, pinCut_polynomial]⟩
+
+end LabelEvaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LabelEvaluatorReaderWidth.lean b/lean/OAI/Computability/VPVNP/LabelEvaluatorReaderWidth.lean
new file mode 100644
index 0000000000..d380df5385
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LabelEvaluatorReaderWidth.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.MacaulayReaderWidth
+import OAI.Computability.VPVNP.LabelEvaluatorIndexedPins
+import OAI.Computability.VPVNP.EvaluatorAdviceBounds
+
+/-! # Prime-independent word widths for the actual finite-slice equations -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LabelEvaluator
+
+open RadicalCertificate.MonomialIndex PolynomiallyBounded
+
+local instance readerWidthsPrime (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+/-- Finite enumeration of the ground field used in bounding the reader's register widths. -/
+noncomputable local instance readerWidthsFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+
+/-- Address widths chosen before the prime, pins, or target monomial. -/
+def readerPlan (m t d primeBits : ℕ) : ReaderPlan :=
+ ⟨t,m,t,d,pointCountBound t d,2^(1+Nat.clog 2 (columnCountBound t d)+primeBits)⟩
+
+theorem readerPlan_covers {p : Nat.Primes} {m t d primeBits : ℕ} {ι : Type*}
+ {F : ι → MvPolynomial (Fin t) ℤ} (M : Model p d F) (read : Fin m → (Fin t → ℕ) → ℤ)
+ (hp : p.val ≤ 2^primeBits) :
+ (readerPlan m t d primeBits).Covers (M.queryData read) := by
+ refine ⟨Fintype.one_lt_card, ?_, le_rfl, le_rfl⟩
+ change Fintype.card (Ground p t d) ≤ 2^(1 + Nat.clog 2 (columnCountBound t d) + primeBits)
+ rw [← Nat.card_eq_fintype_card]
+ exact (Nat.clog_le_iff_le_pow (by decide : 1<2)).mp (ground_card_clog_le p t d primeBits hp)
+
+/-- Uniform polynomial in the input length for the register width of the
+augmented matrix and its target rows. -/
+theorem readerWordWidth_polynomial {m t d b : ℕ → ℕ} (hm : PolynomiallyBounded fun n => Nat.clog 2 (m n))
+ (ht : PolynomiallyBounded t) (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n))
+ (hb : PolynomiallyBounded b) : PolynomiallyBounded (fun n => (readerPlan (m n) (t n) (d n) (b n)).wordWidth) :=
+ ReaderPlan.width_polynomial _ ht hm ht.clog hd (pointCountBound_clog ht hd)
+ (clog_pow (clog (PolynomiallyBounded.const 2)) (((PolynomiallyBounded.const 1).add (columnCountBound_clog ht hd)).add hb))
+
+/-- Uniform working widths for the coefficient limbs and the number of
+extension coefficients staged in each matrix reader. -/
+def readerLimbWidth (b : ℕ) := 2*b+1
+
+/-- Bound for the extension degree in terms of the monomial column count and a bound on the
+prime's bit length. -/
+def readerExtensionBound (t d b : ℕ) := 2*(1+Nat.clog 2 (columnCountBound t d)+b)
+
+theorem readerFieldWidths {p : Nat.Primes} {t d b : ℕ} (hp : p.val ≤ 2^b) :
+ SliceArithmetic.Word.workingWidth p.val ≤ readerLimbWidth b ∧
+ SliceField.extensionDegree p.val (columnCountBound t d) ≤ readerExtensionBound t d b :=
+ ⟨Nat.add_le_add_right (Nat.mul_le_mul_left 2 ((Nat.clog_le_iff_le_pow (by decide : 1<2)).mpr hp)) 1,
+ (extensionDegree_le_width p t d).trans (elementWidth_le p t d b hp)⟩
+
+theorem readerFieldWidths_polynomial {t d b : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hd : PolynomiallyBounded fun n => Nat.clog 2 (d n)) (hb : PolynomiallyBounded b) :
+ PolynomiallyBounded (fun n => readerLimbWidth (b n)) ∧
+ PolynomiallyBounded (fun n => readerExtensionBound (t n) (d n) (b n)) :=
+ ⟨((PolynomiallyBounded.const 2).mul hb).add (.const 1),
+ (PolynomiallyBounded.const 2).mul (((PolynomiallyBounded.const 1).add (columnCountBound_clog ht hd)).add hb)⟩
+
+end LabelEvaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LaneReindex.lean b/lean/OAI/Computability/VPVNP/LaneReindex.lean
new file mode 100644
index 0000000000..dda185972d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LaneReindex.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.DegreeRefreshActualStep
+import OAI.Computability.VPVNP.NetworkHalfIso
+
+/-!
+# Relabeling the binary lanes of a wire network
+
+The compression steps split the current lane into fresh port or packing
+coordinates and the remaining lane. An additive equivalence on lanes
+transports every base displacement, and its inverse recovers each original
+width. This gives a network isomorphism and preserves the wire energy.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+open NetworkKernel Refresh
+
+variable {V A B : Type} {d : ℕ} [AddCommGroup A] [AddCommGroup B]
+
+/-- Relabel all lane displacements using the same additive equivalence. -/
+def relane (G : LiftedSlots V d A) (e : A ≃+ B) : LiftedSlots V d B where
+ base := G.base
+ displacement p := e (G.displacement p)
+
+/-- A wire keeps the width at its original outgoing slot and lane. -/
+def relaneWidths (e : A ≃+ B) (w : (V × Fin d) × A → ℕ) (p : (V × Fin d) × B) : ℕ :=
+ w (p.1,e.symm p.2)
+
+variable [Fintype V] [Fintype A] [Fintype B]
+
+/-- Inverse lane relabeling identifies both ends and the payload of each
+actual wire. Separate slots remain separate edges. -/
+noncomputable def relaneIso (G : LiftedSlots V d A) (e : A ≃+ B) (w : (V × Fin d) × A → ℕ) :
+ Network.Iso (actualWireGraph (relane G e) (relaneWidths e w)) (actualWireGraph G w) where
+ site := (Equiv.refl V).prodCongr e.symm.toEquiv
+ edge := ((Equiv.refl V).prodCongr e.symm.toEquiv).prodCongr (Equiv.refl (Fin d))
+ src _ := rfl
+ dst := by
+ rintro ⟨⟨x,g⟩,i⟩
+ change ((G.base.target (x,i)).1, e.symm (g + e (G.displacement (x,i)))) = _
+ rw [map_add, e.symm_apply_apply]
+ rfl
+ payload _ := Equiv.refl _
+
+/-- The lane coordinate change preserves the number of positions. -/
+theorem relane_card_sites (e : A ≃+ B) : Fintype.card (V × B) = Fintype.card (V × A) :=
+ Fintype.card_congr ((Equiv.refl V).prodCongr e.symm.toEquiv)
+
+/-- Every sum over wire widths is preserved, in particular the sum of
+squared widths divided by the common arc mass. -/
+theorem relane_sum_widths (e : A ≃+ B) (w : (V × Fin d) × A → ℕ)
+ {R : Type*} [AddCommMonoid R] (f : ℕ → R) :
+ (∑ p, f (relaneWidths e w p)) = ∑ p, f (w p) :=
+ ((Equiv.refl (V × Fin d)).prodCongr e.symm.toEquiv).sum_comp (fun p => f (w p))
+
+end Compression
+
+namespace NetworkKernel
+
+@[simp] theorem Step.reindexInput_output {N M : Network} {R : Type*} [CommSemiring R]
+ (s : Step R N) (input : N.Iso M) (i : s.Choice) :
+ ((s.reindexInput input).term i).output = (s.term i).output := rfl
+
+end NetworkKernel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LayerWalk.lean b/lean/OAI/Computability/VPVNP/LayerWalk.lean
new file mode 100644
index 0000000000..7d818b7ed1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LayerWalk.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.PortMatching
+import OAI.Computability.VPVNP.WalkEnergy
+import Mathlib.Algebra.BigOperators.Field
+
+/-!
+# Loop removal at bounded Poincaré cost
+
+Section 5.3 of *VP and VNP differ over every field* removes loops from a
+regular graph by doubling its vertex set. Each step moves to the opposite
+layer, choosing equally between an old edge and a vertical edge.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {V X : Type*} [Fintype V] [DecidableEq V] [PseudoMetricSpace X]
+
+/-- The transition matrix of the loopless double cover. -/
+noncomputable def layerWalk (P : Matrix V V ℝ) : Matrix (V × Bool) (V × Bool) ℝ :=
+ fun p q ↦ if q.2 = !p.2 then (P p.1 q.1 + (if q.1 = p.1 then 1 else 0)) / 2 else 0
+
+omit [Fintype V] in
+/-- Dividing the doubled graph's integer multiplicities by its degree gives
+the crossing/vertical transition kernel. -/
+theorem layerArcs_normalize (G : V → V → ℕ) {b : ℕ} (hb : 0 < b) (p q : V × Bool) :
+ (layerArcs G b p q : ℝ) / (2 * b) =
+ layerWalk (fun u v ↦ (G u v : ℝ) / b) p q := by
+ have hb' : (b : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr hb.ne'
+ simp only [layerArcs, layerWalk]
+ split_ifs <;> push_cast <;> field_simp <;> ring
+
+private noncomputable def crossEnergy (P : Matrix V V ℝ) (x : V × Bool → X) (i : Bool) : ℝ :=
+ ∑ v, ∑ w, P v w * dist (x (w, !i)) (x (v, i)) ^ 2
+
+private noncomputable def verticalEnergy (x : V × Bool → X) : ℝ :=
+ ∑ v, dist (x (v, true)) (x (v, false)) ^ 2
+
+private theorem layerWalk_energy (P : Matrix V V ℝ) (hs : ∀ u v, P u v = P v u)
+ (x : V × Bool → X) :
+ walkEnergy (layerWalk P) x = crossEnergy P x false + verticalEnergy x := by
+ have hc : crossEnergy P x true = crossEnergy P x false := by
+ unfold crossEnergy
+ rw [Finset.sum_comm]
+ exact Finset.sum_congr rfl fun v _ ↦ Finset.sum_congr rfl fun w _ ↦ by
+ simp only [Bool.not_true, Bool.not_false]
+ rw [hs w v, dist_comm]
+ have row (v : V) (i : Bool) :
+ ∑ q, layerWalk P (v, i) q * dist (x q) (x (v, i)) ^ 2 =
+ ((∑ w, P v w * dist (x (w, !i)) (x (v, i)) ^ 2) +
+ dist (x (v, !i)) (x (v, i)) ^ 2) / 2 := by
+ rw [Fintype.sum_prod_type]
+ simp only [layerWalk, ite_mul, zero_mul, Finset.sum_ite_eq', Finset.mem_univ, ite_true,
+ div_mul_eq_mul_div, add_mul, one_mul, ← Finset.sum_div, Finset.sum_add_distrib]
+ rw [walkEnergy, Fintype.sum_prod_type, Finset.sum_comm]
+ simp_rw [row, ← Finset.sum_div, Finset.sum_add_distrib]
+ simp only [Fintype.sum_bool, Bool.not_true, Bool.not_false]
+ rw [show (∑ v, dist (x (v, false)) (x (v, true)) ^ 2) = verticalEnergy x from
+ Finset.sum_congr rfl fun v _ ↦ by rw [dist_comm]]
+ change (crossEnergy P x true + crossEnergy P x false +
+ (verticalEnergy x + verticalEnergy x)) / 2 = _
+ rw [hc]
+ ring
+
+omit [DecidableEq V] in
+private theorem firstLayer_energy_le (P : Matrix V V ℝ) (hn : ∀ v w, 0 ≤ P v w)
+ (hcol : ∀ w, ∑ v, P v w = 1) (x : V × Bool → X) :
+ walkEnergy P (fun v ↦ x (v, false)) ≤ 2 * (crossEnergy P x false + verticalEnergy x) := by
+ have edge (v w : V) :
+ dist (x (w, false)) (x (v, false)) ^ 2 ≤
+ 2 * (dist (x (w, true)) (x (v, false)) ^ 2 + dist (x (w, true)) (x (w, false)) ^ 2) := by
+ have h := dist_triangle (x (w, false)) (x (w, true)) (x (v, false))
+ rw [dist_comm (x (w, false)) (x (w, true))] at h
+ have h' := pow_le_pow_left₀ dist_nonneg h 2
+ nlinarith [sq_nonneg (dist (x (w, true)) (x (v, false)) - dist (x (w, true)) (x (w, false)))]
+ have hc : (∑ v, ∑ w, P v w * dist (x (w, true)) (x (w, false)) ^ 2) = verticalEnergy x := by
+ rw [Finset.sum_comm]
+ simp only [← Finset.sum_mul, hcol, one_mul, verticalEnergy]
+ calc
+ _ ≤ ∑ v, ∑ w, 2 * (P v w * dist (x (w, true)) (x (v, false)) ^ 2 +
+ P v w * dist (x (w, true)) (x (w, false)) ^ 2) := by
+ apply Finset.sum_le_sum
+ intro v _
+ apply Finset.sum_le_sum
+ intro w _
+ have h := mul_le_mul_of_nonneg_left (edge v w) (hn v w)
+ linarith only [h]
+ _ = _ := by simp only [← Finset.mul_sum, Finset.sum_add_distrib, hc, crossEnergy, Bool.not_false]
+
+/-- The loopless double cover of a symmetric stochastic walk inherits a
+uniform Poincaré constant. The estimate applies to every metric target. -/
+theorem layerWalk_hasPoincareBound [Nonempty V] (P : Matrix V V ℝ)
+ (hn : ∀ v w, 0 ≤ P v w) (hs : ∀ v w, P v w = P w v) (hcol : ∀ w, ∑ v, P v w = 1)
+ {γ : ℝ} (hγ : 0 ≤ γ) (hP : HasPoincareBound X P γ) :
+ HasPoincareBound X (layerWalk P) (6 + 12 * γ) := by
+ intro x
+ let y (p : V × Bool) := x (p.1, false)
+ have disp : (∑ p, dist (x p) (y p) ^ 2) = verticalEnergy x := by
+ rw [Fintype.sum_prod_type]
+ simp [y, verticalEnergy]
+ have pairs : (∑ p, ∑ q, dist (y p) (y q) ^ 2) =
+ 4 * (∑ v, ∑ w, dist (x (v, false)) (x (w, false)) ^ 2) := by
+ simp only [Fintype.sum_prod_type, y, Finset.sum_const, Finset.card_univ, Fintype.card_bool,
+ nsmul_eq_mul, Nat.cast_ofNat, ← Finset.mul_sum]
+ ring
+ have hCard : (0 : ℝ) < Fintype.card V := Nat.cast_pos.mpr Fintype.card_pos
+ have hCard' : (Fintype.card (V × Bool) : ℝ) = 2 * Fintype.card V := by
+ simp [mul_comm]
+ have hvar := pairVariance_le_displacement_variance x y
+ rw [disp, pairs, hCard'] at hvar
+ have hold := (div_le_iff₀ hCard).mp (hP (fun v ↦ x (v, false)))
+ have he := firstLayer_energy_le P hn hcol x
+ have hnCross : 0 ≤ crossEnergy P x false :=
+ Finset.sum_nonneg fun _ _ ↦ Finset.sum_nonneg fun _ _ ↦ mul_nonneg (hn _ _) (sq_nonneg _)
+ rw [hCard', layerWalk_energy P hs x]
+ apply (div_le_iff₀ (by positivity)).mpr
+ nlinarith only [hvar, hold, mul_nonneg hCard.le hnCross,
+ mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left he hγ) hCard.le]
+
+omit [DecidableEq V] in
+/-- A Poincaré inequality for a target with two separated points forces the
+support of a symmetric walk to be connected. Test with a two-valued map
+constant on every component. -/
+theorem reachable_of_poincare (z₀ z₁ : X) (hsep : 0 < dist z₀ z₁) (P : Matrix V V ℝ) (hn : ∀ i j, 0 ≤ P i j)
+ (hs : ∀ i j, P i j = P j i) {γ : ℝ} (hP : HasPoincareBound X P γ) (u v : V) :
+ Relation.ReflTransGen (fun i j ↦ 0 < P i j) u v := by
+ classical
+ let reachable := Relation.ReflTransGen (fun i j ↦ 0 < P i j) u
+ by_contra hv
+ let f (i : V) : X := if reachable i then z₀ else z₁
+ have hsame (i j : V) (hij : 0 < P i j) : reachable i ↔ reachable j :=
+ ⟨fun h ↦ h.tail hij, fun h ↦ h.tail ((hs i j) ▸ hij)⟩
+ have zero (i j : V) : P i j * dist (f j) (f i) ^ 2 = 0 := by
+ rcases (hn i j).eq_or_lt with h | h
+ · rw [← h, zero_mul]
+ · simp [f, hsame i j h]
+ have energy : walkEnergy P f = 0 := by simp [walkEnergy, zero]
+ have hu : reachable u := .refl
+ have hpair : 0 < dist (f u) (f v) ^ 2 := by
+ change ¬ reachable v at hv
+ simpa [f, hu, hv] using sq_pos_of_pos hsep
+ have hp : 0 < ∑ i, ∑ j, dist (f i) (f j) ^ 2 :=
+ Finset.sum_pos' (fun _ _ ↦ Finset.sum_nonneg fun _ _ ↦ sq_nonneg _)
+ ⟨u, Finset.mem_univ u, Finset.sum_pos' (fun _ _ ↦ sq_nonneg _) ⟨v, Finset.mem_univ v, hpair⟩⟩
+ have : Nonempty V := ⟨u⟩
+ have hnCard : (0 : ℝ) < Fintype.card V := Nat.cast_pos.mpr Fintype.card_pos
+ have h := hP f
+ rw [energy, mul_zero] at h
+ exact (div_pos hp hnCard).not_ge h
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LeafBijection.lean b/lean/OAI/Computability/VPVNP/LeafBijection.lean
new file mode 100644
index 0000000000..d2b59f5822
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LeafBijection.lean
@@ -0,0 +1,83 @@
+import Mathlib.Data.List.FinRange
+import Mathlib.Data.List.OfFn
+import Mathlib.Data.Multiset.Defs
+import Mathlib.Data.Fintype.EquivFin
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# Matching terminal occurrences to query slots
+
+The terminal word and the query have a label-preserving bijection of positions
+exactly when they represent the same multiset. For a query with distinct labels
+the bijection is unique.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+/-- An assignment of every terminal occurrence to a distinct query slot with its label. -/
+abbrev LeafBijection {V : Type*} {m : ℕ} (l : List V) (q : Fin m → V) :=
+ { e : Fin l.length ≃ Fin m // ∀ i, l.get i = q (e i) }
+
+namespace LeafBijection
+
+private theorem exists_equiv_of_perm {V : Type*} {l r : List V} (h : l.Perm r) :
+ ∃ e : Fin l.length ≃ Fin r.length, ∀ i, l.get i = r.get (e i) := by
+ induction h with
+ | nil => exact ⟨Equiv.refl _, fun _ => rfl⟩
+ | @cons a l r _ ih =>
+ obtain ⟨e, he⟩ := ih
+ refine ⟨((finSuccEquiv l.length).trans (Equiv.optionCongr e)).trans
+ (finSuccEquiv r.length).symm, ?_⟩
+ intro i
+ refine Fin.cases ?_ (fun j => ?_) i
+ · simp
+ · simpa using he j
+ | swap a b l =>
+ let z : Fin (l.length + 2) := 0
+ let o : Fin (l.length + 2) := (0 : Fin (l.length + 1)).succ
+ refine ⟨Equiv.swap z o, ?_⟩
+ intro i
+ refine Fin.cases ?_ (fun j => Fin.cases ?_ (fun k => ?_) j) i
+ · rw [show (0 : Fin (l.length + 2)) = z from rfl, Equiv.swap_apply_left]
+ rfl
+ · rw [show (0 : Fin (l.length + 1)).succ = o from rfl, Equiv.swap_apply_right]
+ rfl
+ · rw [Equiv.swap_apply_of_ne_of_ne (by simp [z]) (fun h => Fin.succ_ne_zero k (Fin.succ_inj.mp h))]
+ rfl
+ | trans _ _ ih₁ ih₂ =>
+ obtain ⟨e, he⟩ := ih₁
+ obtain ⟨f, hf⟩ := ih₂
+ exact ⟨e.trans f, fun i => (he i).trans (hf (e i))⟩
+
+/-- Assignments exist exactly for the multiset of terminals selected by the query. -/
+theorem nonempty_iff {V : Type*} {m : ℕ} (l : List V) (q : Fin m → V) :
+ Nonempty (LeafBijection l q) ↔
+ (l : Multiset V) = (List.ofFn q : Multiset V) := by
+ rw [Multiset.coe_eq_coe]
+ constructor
+ · rintro ⟨⟨e, he⟩⟩
+ have hlen : l.length = m := by simpa using Fintype.card_congr e
+ subst m
+ have h : l.get = q ∘ e := funext he
+ have hw : l = List.ofFn (q ∘ e) := (List.ofFn_get l).symm.trans (congrArg List.ofFn h)
+ exact (congrArg (fun w => w.Perm (List.ofFn q)) hw).mpr (Equiv.Perm.ofFn_comp_perm e q)
+ · intro h
+ obtain ⟨e, he⟩ := exists_equiv_of_perm h
+ refine ⟨⟨e.trans (finCongr List.length_ofFn), fun i => ?_⟩⟩
+ exact (he i).trans (List.get_ofFn q (e i))
+
+/-- Distinct query labels determine the assignment at every terminal occurrence. -/
+theorem subsingleton_of_injective {V : Type*} {m : ℕ} (l : List V)
+ {q : Fin m → V} (hq : Function.Injective q) : Subsingleton (LeafBijection l q) :=
+ ⟨fun a b => Subtype.ext <| Equiv.ext fun i => hq ((a.2 i).symm.trans (b.2 i))⟩
+
+end LeafBijection
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LinearNormalization.lean b/lean/OAI/Computability/VPVNP/LinearNormalization.lean
new file mode 100644
index 0000000000..23baf8f616
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LinearNormalization.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.LinearNormalizationDimension
+import OAI.Computability.VPVNP.LinearNormalizationStep
+import OAI.Computability.VPVNP.LinearNormalizationTower
+
+/-!
+# Noether normalization by linear combinations of specified generators
+
+Over an infinite field, a dependent tuple admits a linear shear after
+which one generator can be removed while preserving integrality. Repeating
+this reduction gives an independent tuple in the linear span of the
+original one. In a polynomial algebra the length of the tuple is its
+number of variables.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LinearNormalization
+
+open MvPolynomial
+
+variable {K A : Type*} [Field K] [Infinite K] [CommRing A] [Nontrivial A] [Algebra K A]
+
+/-- Linear normalization for a tuple whose generated subalgebra has an integral
+extension to the whole ambient algebra. -/
+theorem exists_of_integral_adjoin {n : ℕ} (g : Fin n → A)
+ (hg : ∀ a : A, IsIntegral (Algebra.adjoin K (Set.range g)) a) :
+ ∃ (s : ℕ) (Q : Fin s → A),
+ (∀ j, Q j ∈ Submodule.span K (Set.range g)) ∧
+ Function.Injective (aeval Q : MvPolynomial (Fin s) K →ₐ[K] A) ∧
+ ∀ a : A, IsIntegral (Algebra.adjoin K (Set.range Q)) a := by
+ induction n with
+ | zero =>
+ refine ⟨0, g, fun j => j.elim0, ?_, hg⟩
+ intro p q he
+ rw [eq_C_of_isEmpty p, eq_C_of_isEmpty q] at he ⊢
+ exact congrArg C ((algebraMap K A).injective (by simpa only [aeval_C] using he))
+ | succ n ih =>
+ by_cases hi : Function.Injective (aeval g : MvPolynomial (Fin (n + 1)) K →ₐ[K] A)
+ · exact ⟨n + 1, g, fun j => Submodule.subset_span ⟨j, rfl⟩, hi, hg⟩
+ obtain ⟨v, hv⟩ := exists_integral_shear g hi
+ let g' (j : Fin n) := g j.succ - v j • g 0
+ obtain ⟨s, Q, hQ, hinj, hint⟩ := ih g' (fun a =>
+ integral_over_new_generators (Algebra.adjoin K (Set.range g')) g hv a (hg a))
+ refine ⟨s, Q, fun j => ?_, hinj, hint⟩
+ have hle : Submodule.span K (Set.range g') ≤ Submodule.span K (Set.range g) := by
+ apply Submodule.span_le.mpr
+ rintro _ ⟨i, rfl⟩
+ exact Submodule.sub_mem _ (Submodule.subset_span ⟨i.succ, rfl⟩)
+ (Submodule.smul_mem _ _ (Submodule.subset_span ⟨0, rfl⟩))
+ exact hle (hQ j)
+
+/-- An explicitly generated polynomial algebra in `m` variables has an integral
+normalization by exactly `m` linear combinations of the given generators. -/
+theorem exists_linear_normalization {m : ℕ} {I : Type*} [Fintype I]
+ (g : I → MvPolynomial (Fin m) K) (hg : Algebra.adjoin K (Set.range g) = ⊤) :
+ ∃ Q : Fin m → MvPolynomial (Fin m) K,
+ (∀ j, Q j ∈ Submodule.span K (Set.range g)) ∧
+ Function.Injective (aeval Q : MvPolynomial (Fin m) K →ₐ[K] MvPolynomial (Fin m) K) ∧
+ ∀ p : MvPolynomial (Fin m) K, IsIntegral (aeval Q : MvPolynomial (Fin m) K →ₐ[K] MvPolynomial (Fin m) K).range p := by
+ let g' := g ∘ (Fintype.equivFin I).symm
+ have hr : Set.range g' = Set.range g := (Fintype.equivFin I).symm.surjective.range_comp g
+ have hgi (p : MvPolynomial (Fin m) K) : IsIntegral (Algebra.adjoin K (Set.range g')) p := by
+ let t : Algebra.adjoin K (Set.range g') := ⟨p, by rw [hr, hg]; trivial⟩
+ exact isIntegral_algebraMap (x := t)
+ obtain ⟨s, Q, hspan, hinj, hint⟩ := exists_of_integral_adjoin g' hgi
+ let f : MvPolynomial (Fin s) K →ₐ[K] MvPolynomial (Fin m) K := aeval Q
+ have h : ∀ p : MvPolynomial (Fin m) K, IsIntegral f.range p := by
+ have hrange : Algebra.adjoin K (Set.range Q) = f.range := Algebra.adjoin_range_eq_range_aeval K Q
+ exact hrange ▸ hint
+ have hsm := numVars_eq_of_integral_injective f hinj ((isIntegral_iff_range f).2 h)
+ subst s
+ exact ⟨Q, fun j => hr ▸ hspan j, hinj, h⟩
+
+end LinearNormalization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LinearNormalizationDimension.lean b/lean/OAI/Computability/VPVNP/LinearNormalizationDimension.lean
new file mode 100644
index 0000000000..7da45efe58
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LinearNormalizationDimension.lean
@@ -0,0 +1,50 @@
+import Mathlib.RingTheory.AlgebraicIndependent.TranscendenceBasis
+
+/-!
+# Number of variables in an integral polynomial normalization
+
+In a polynomial ring over a field, an injective integral normalization has
+as many coordinates as the ambient polynomial ring has variables.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LinearNormalization
+
+/-- Integrality of an algebra homomorphism makes each target element integral
+over its image subalgebra. -/
+theorem isIntegral_range {K A B : Type*} [CommRing K] [CommRing A] [CommRing B]
+ [Algebra K A] [Algebra K B] (f : A →ₐ[K] B) (hf : f.IsIntegral)
+ (p : B) : IsIntegral f.range p :=
+ RingHom.IsIntegralElem.of_comp
+ (f := f.rangeRestrict.toRingHom) (g := algebraMap f.range B) (hf p)
+
+/-- Integrality over the image characterizes an integral homomorphism. -/
+theorem isIntegral_iff_range {K A B : Type*} [CommRing K] [CommRing A] [CommRing B]
+ [Algebra K A] [Algebra K B] (f : A →ₐ[K] B) :
+ f.IsIntegral ↔ ∀ p : B, IsIntegral f.range p := by
+ refine ⟨isIntegral_range f, fun h ↦ ?_⟩
+ exact RingHom.IsIntegral.trans f.rangeRestrict.toRingHom (algebraMap f.range B)
+ (RingHom.isIntegral_of_surjective _ f.rangeRestrict_surjective) h
+
+/-- The image of the source variables is a transcendence basis of the target,
+so the two polynomial rings have the same number of variables. -/
+theorem numVars_eq_of_integral_injective {K : Type*} [Field K] {s m : ℕ}
+ (f : MvPolynomial (Fin s) K →ₐ[K] MvPolynomial (Fin m) K)
+ (hf : Function.Injective f) (hi : f.IsIntegral) : s = m := by
+ let P := MvPolynomial (Fin s) K
+ let Q := MvPolynomial (Fin m) K
+ let : Algebra P Q := f.toRingHom.toAlgebra
+ let : IsScalarTower K P Q := .of_algebraMap_eq fun k ↦ (f.commutes k).symm
+ let : FaithfulSMul P Q := (faithfulSMul_iff_algebraMap_injective P Q).mpr hf
+ let : Algebra.IsIntegral P Q := ⟨hi⟩
+ have h := (IsTranscendenceBasis.mvPolynomial (Fin s) K).algebraMap_comp (A := Q)
+ simpa using h.cardinalMk_eq (IsTranscendenceBasis.mvPolynomial (Fin m) K)
+
+end LinearNormalization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LinearNormalizationDirection.lean b/lean/OAI/Computability/VPVNP/LinearNormalizationDirection.lean
new file mode 100644
index 0000000000..a58562fcfe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LinearNormalizationDirection.lean
@@ -0,0 +1,49 @@
+import Mathlib.Algebra.MvPolynomial.Funext
+import Mathlib.RingTheory.MvPolynomial.Homogeneous
+
+/-!
+# Choosing a direction for linear Noether normalization
+
+Over an infinite field the highest homogeneous part of a nonzero polynomial
+has a nonzero value on some vector whose first coordinate is nonzero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LinearNormalization
+
+open MvPolynomial
+
+/-- A monomial of maximal degree survives in the top homogeneous component. -/
+theorem topComponent_ne_zero {σ R : Type*} [CommSemiring R] {p : MvPolynomial σ R}
+ (hp : p ≠ 0) : homogeneousComponent p.totalDegree p ≠ 0 := by
+ classical
+ obtain ⟨d, hd, hdeg⟩ :=
+ p.support.exists_mem_eq_sup (support_nonempty.mpr hp) (fun d => d.degree)
+ change p.totalDegree = d.degree at hdeg
+ intro h
+ apply mem_support_iff.mp hd
+ simpa [coeff_homogeneousComponent, hdeg.symm] using
+ congrArg (fun q : MvPolynomial σ R => q.coeff d) h
+
+/-- Choose a direction avoiding both the coordinate hyperplane and the zero set
+of the highest homogeneous part. -/
+theorem exists_direction {K : Type*} [Field K] [Infinite K] {n : ℕ}
+ {p : MvPolynomial (Fin (n + 1)) K} (hp : p ≠ 0) :
+ ∃ v : Fin (n + 1) → K, v 0 ≠ 0 ∧ eval v (homogeneousComponent p.totalDegree p) ≠ 0 := by
+ classical
+ by_contra! h
+ apply mul_ne_zero (X_ne_zero (R := K) (0 : Fin (n + 1))) (topComponent_ne_zero hp)
+ apply MvPolynomial.funext
+ intro v
+ by_cases hv : v 0 = 0
+ · simp [hv]
+ · simp [h v hv]
+
+end LinearNormalization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LinearNormalizationLine.lean b/lean/OAI/Computability/VPVNP/LinearNormalizationLine.lean
new file mode 100644
index 0000000000..433ab3ae85
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LinearNormalizationLine.lean
@@ -0,0 +1,88 @@
+import Mathlib.RingTheory.MvPolynomial.Homogeneous
+import Mathlib.Algebra.Polynomial.BigOperators
+
+/-!
+# Highest coefficient on an affine line
+
+Substitute `hᵢ + vᵢT` in a polynomial of total degree `d`. The resulting
+polynomial in `T` has degree at most `d`, and its coefficient of `Tᵈ` is the
+degree-`d` homogeneous component evaluated at the direction `v`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LinearNormalization
+
+variable {I E A : Type*} [CommSemiring E] [CommSemiring A] [Algebra E A]
+
+/-- Restriction to the affine line through `h` with direction `v`. -/
+noncomputable def line (p : MvPolynomial I E) (h : I → A) (v : I → E) : Polynomial A :=
+ MvPolynomial.aeval (fun i => Polynomial.C (h i) + Polynomial.C (algebraMap E A (v i)) * Polynomial.X) p
+
+private theorem top_product (s : Finset I) (f : I → Polynomial A) (d : I → ℕ)
+ (hd : ∀ i ∈ s, (f i).natDegree ≤ d i) :
+ (∏ i ∈ s, f i).natDegree ≤ ∑ i ∈ s, d i ∧
+ (∏ i ∈ s, f i).coeff (∑ i ∈ s, d i) = ∏ i ∈ s, (f i).coeff (d i) := by
+ classical
+ induction s using Finset.induction_on with
+ | empty => simp
+ | @insert i s hi ih =>
+ obtain ⟨hds, hcs⟩ := ih (fun j hj => hd j (Finset.mem_insert_of_mem hj))
+ have hdi := hd i (Finset.mem_insert_self i s)
+ simp only [Finset.prod_insert hi, Finset.sum_insert hi]
+ exact ⟨Polynomial.natDegree_mul_le.trans (Nat.add_le_add hdi hds),
+ (Polynomial.coeff_mul_add_eq_of_natDegree_le hdi hds).trans (congrArg (_ * ·) hcs)⟩
+
+private theorem line_monomial (e : I →₀ ℕ) (r : E) (h : I → A) (v : I → E) :
+ (line (MvPolynomial.monomial e r) h v).natDegree ≤ e.degree ∧
+ (line (MvPolynomial.monomial e r) h v).coeff e.degree =
+ algebraMap E A (MvPolynomial.eval v (MvPolynomial.monomial e r)) := by
+ let f (i : I) := Polynomial.C (h i) + Polynomial.C (algebraMap E A (v i)) * Polynomial.X
+ have hf (i : I) : (f i).natDegree ≤ 1 :=
+ (Polynomial.natDegree_add_le _ _).trans (max_le (by simp)
+ ((Polynomial.natDegree_C_mul_le _ _).trans Polynomial.natDegree_X_le))
+ have hc (i : I) : (f i).coeff 1 = algebraMap E A (v i) := by simp [f]
+ have hfd (i : I) : (f i ^ e i).natDegree ≤ e i := by
+ simpa using Polynomial.natDegree_pow_le_of_le (e i) (hf i)
+ have hfc (i : I) : (f i ^ e i).coeff (e i) = algebraMap E A (v i) ^ e i := by
+ simpa [hc] using Polynomial.coeff_pow_of_natDegree_le (m := e i) (hf i)
+ obtain ⟨hdeg, hcoeff⟩ := top_product e.support (fun i => f i ^ e i) e (fun i _ => hfd i)
+ simp only [line, MvPolynomial.aeval_monomial, Polynomial.algebraMap_apply, Finsupp.prod,
+ Finsupp.degree_apply, MvPolynomial.eval_monomial, map_mul, map_prod, map_pow]
+ exact ⟨(Polynomial.natDegree_C_mul_le _ _).trans hdeg,
+ by rw [Polynomial.coeff_C_mul, hcoeff]; simp_rw [hfc]⟩
+
+private theorem line_eq_sum (p : MvPolynomial I E) (h : I → A) (v : I → E) :
+ line p h v = ∑ e ∈ p.support, line (MvPolynomial.monomial e (p.coeff e)) h v := by
+ unfold line
+ conv_lhs => rw [p.as_sum, map_sum]
+
+/-- Restriction to an affine line cannot increase the total degree. -/
+theorem natDegree_line_le (p : MvPolynomial I E) (h : I → A) (v : I → E) :
+ (line p h v).natDegree ≤ p.totalDegree := by
+ rw [line_eq_sum]
+ exact Polynomial.natDegree_sum_le_of_forall_le _ _ fun e he =>
+ (line_monomial e _ h v).1.trans (MvPolynomial.le_totalDegree he)
+
+/-- Only the top homogeneous component contributes to the coefficient of the
+highest possible power of the line parameter. -/
+theorem coeff_line_totalDegree (p : MvPolynomial I E) (h : I → A) (v : I → E) :
+ (line p h v).coeff p.totalDegree =
+ algebraMap E A (MvPolynomial.eval v (MvPolynomial.homogeneousComponent p.totalDegree p)) := by
+ classical
+ rw [line_eq_sum, Polynomial.finsetSum_coeff, MvPolynomial.homogeneousComponent_apply,
+ map_sum, map_sum, Finset.sum_filter]
+ refine Finset.sum_congr rfl fun e he => ?_
+ by_cases hd : e.degree = p.totalDegree
+ · simpa only [hd, ite_true] using (line_monomial e (p.coeff e) h v).2
+ · rw [ite_eq_right hd]
+ exact Polynomial.coeff_eq_zero_of_natDegree_lt ((line_monomial e _ h v).1.trans_lt
+ (lt_of_le_of_ne (MvPolynomial.le_totalDegree he) hd))
+
+end LinearNormalization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LinearNormalizationRoot.lean b/lean/OAI/Computability/VPVNP/LinearNormalizationRoot.lean
new file mode 100644
index 0000000000..23ce6078bf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LinearNormalizationRoot.lean
@@ -0,0 +1,38 @@
+import OAI.Computability.VPVNP.LinearNormalizationLine
+import Mathlib.RingTheory.IntegralClosure.IsIntegral.Basic
+
+/-!
+# Integrality from a polynomial restricted to a line
+
+A direction where the top homogeneous part is nonzero makes the leading
+coefficient of the line polynomial a unit. Rescaling this relation gives
+a monic equation for every root in an extension algebra.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LinearNormalization
+
+variable {K B A I : Type*} [Field K] [CommRing B] [Nontrivial B] [Algebra K B]
+ [CommRing A] [Algebra B A]
+
+theorem isIntegral_of_line_root (p : MvPolynomial I K) (h : I → B) (v : I → K) (x : A)
+ (ht : MvPolynomial.eval v (MvPolynomial.homogeneousComponent p.totalDegree p) ≠ 0)
+ (hx : Polynomial.aeval x (line p h v) = 0) : IsIntegral B x := by
+ have htop : IsUnit ((line p h v).coeff p.totalDegree) := by
+ rw [coeff_line_totalDegree]
+ exact ht.isUnit.map (algebraMap K B)
+ have hdegree := Polynomial.natDegree_eq_of_le_of_coeff_ne_zero
+ (natDegree_line_le p h v) htop.ne_zero
+ have hu : IsUnit (line p h v).leadingCoeff := by simpa [Polynomial.leadingCoeff, hdegree] using htop
+ refine ⟨hu.unit⁻¹.val • line p h v, Polynomial.monic_of_isUnit_leadingCoeff_inv_smul hu, ?_⟩
+ change Polynomial.aeval x (hu.unit⁻¹.val • line p h v) = 0
+ rw [map_smul, hx, smul_zero]
+
+end LinearNormalization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LinearNormalizationStep.lean b/lean/OAI/Computability/VPVNP/LinearNormalizationStep.lean
new file mode 100644
index 0000000000..7f3ac67541
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LinearNormalizationStep.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.LinearNormalizationDirection
+import OAI.Computability.VPVNP.LinearNormalizationRoot
+import Mathlib.RingTheory.IntegralClosure.Algebra.Basic
+
+/-!
+# A linear shear eliminating one generator
+
+Given a relation on generators `g₀,…,gₙ`, choose a direction where the
+highest homogeneous component of the relation is nonzero. Its restriction to
+a line through the sheared generators gives an integral equation. Each original
+generator is then integral over the algebra of the `n` sheared generators.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LinearNormalization
+
+open MvPolynomial
+
+private theorem aeval_line {K B A I : Type*} [CommSemiring K] [CommSemiring B] [CommSemiring A]
+ [Algebra K B] [Algebra K A] [Algebra B A] [IsScalarTower K B A]
+ (p : MvPolynomial I K) (h : I → B) (v : I → K) (x : A) :
+ Polynomial.aeval x (line p h v) =
+ aeval (fun i => algebraMap B A (h i) + v i • x) p := by
+ let f : Polynomial B →ₐ[K] A := (Polynomial.aeval x).restrictScalars K
+ change f (aeval _ p) = _
+ rw [MvPolynomial.comp_aeval_apply]
+ apply congrArg (fun z : I → A => aeval z p)
+ funext i
+ simp [f, Algebra.smul_def, ← IsScalarTower.algebraMap_apply K B A]
+
+/-- A nontrivial polynomial relation permits removing one generator by a linear
+change of coordinates, with an integral extension of the resulting algebra. -/
+theorem exists_integral_shear {K A : Type*} [Field K] [Infinite K] [CommRing A] [Algebra K A]
+ {n : ℕ} (g : Fin (n + 1) → A)
+ (hg : ¬ Function.Injective (aeval g : MvPolynomial (Fin (n + 1)) K →ₐ[K] A)) :
+ ∃ v : Fin n → K, ∀ i : Fin (n + 1),
+ IsIntegral (Algebra.adjoin K (Set.range (fun j : Fin n => g j.succ - v j • g 0))) (g i) := by
+ classical
+ rcases subsingleton_or_nontrivial A with hs | hs
+ · refine ⟨0, fun i => ?_⟩
+ rw [Subsingleton.elim (g i) 0]
+ exact isIntegral_zero
+ rw [injective_iff_map_eq_zero] at hg
+ push Not at hg
+ obtain ⟨p, hp, hne⟩ := hg
+ obtain ⟨v, hv, htop⟩ := exists_direction hne
+ let w (j : Fin n) := v j.succ * (v 0)⁻¹
+ let sh (j : Fin n) := g j.succ - w j • g 0
+ let B := Algebra.adjoin K (Set.range sh)
+ let h : Fin (n + 1) → B :=
+ Fin.cons 0 (fun j => ⟨sh j, Algebra.subset_adjoin ⟨j, rfl⟩⟩)
+ let x := (v 0)⁻¹ • g 0
+ have coords (i : Fin (n + 1)) : algebraMap B A (h i) + v i • x = g i := by
+ refine Fin.cases ?_ (fun j => ?_) i
+ · change (0 : A) + v 0 • ((v 0)⁻¹ • g 0) = g 0
+ simp [smul_smul, hv]
+ · change sh j + v j.succ • ((v 0)⁻¹ • g 0) = g j.succ
+ simp [sh, w, smul_smul]
+ have hroot : Polynomial.aeval x (line p h v) = 0 := by
+ rw [aeval_line, funext coords]
+ exact hp
+ have hx : IsIntegral B x := isIntegral_of_line_root p h v x htop hroot
+ refine ⟨w, fun i => ?_⟩
+ change IsIntegral B (g i)
+ rw [← coords i]
+ exact isIntegral_algebraMap.add (hx.smul (v i))
+
+end LinearNormalization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LinearNormalizationTower.lean b/lean/OAI/Computability/VPVNP/LinearNormalizationTower.lean
new file mode 100644
index 0000000000..5a86193726
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LinearNormalizationTower.lean
@@ -0,0 +1,34 @@
+import Mathlib.RingTheory.IntegralClosure.IsIntegralClosure.Basic
+
+/-!
+# Descending integrality along a change of generators
+
+If the old generators are integral over a new subalgebra, all their
+polynomial expressions belong to its integral closure. Any element integral
+over the old generators is consequently integral over the new subalgebra.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LinearNormalization
+
+variable {K A I : Type*} [CommRing K] [CommRing A] [Algebra K A]
+
+theorem integral_over_new_generators (B : Subalgebra K A) (g : I → A)
+ (hgen : ∀ i, IsIntegral B (g i)) (a : A)
+ (ha : IsIntegral (Algebra.adjoin K (Set.range g)) a) : IsIntegral B a := by
+ let T := integralClosure B A
+ have hle : Algebra.adjoin K (Set.range g) ≤ T.restrictScalars K :=
+ Algebra.adjoin_le (by rintro x ⟨i, rfl⟩; exact hgen i)
+ let f := Subalgebra.inclusion hle
+ have h : IsIntegral T a :=
+ RingHom.IsIntegralElem.of_comp (f := f.toRingHom) (g := algebraMap T A) ha
+ exact isIntegral_trans (A := T) a h
+
+end LinearNormalization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveActiveGroupCounts.lean b/lean/OAI/Computability/VPVNP/LiveActiveGroupCounts.lean
new file mode 100644
index 0000000000..c04b2c397c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveActiveGroupCounts.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.LiveHeaderPaddingCount
+
+/-!
+# Incoming checks on the active branches
+
+On a first-half or midpoint input the native header tests the incoming
+padding directly. At a later incoming cut a nonzero transition count forces
+a decodable configuration. Consequently, after both header scans succeed,
+the native active branch may use the raw pair or transition count directly.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.Fields
+open LiveHeaderSchedule LiveHeaderDescriptors LiveHeader ChainAssignments
+open CutSchedule ExponentTrace LiveChain LiveEvaluatorEncoding
+open scoped Classical
+
+variable {s : Sizes} {t Z M w : ℕ} {E : UniversalMachine.Program}
+variable {Nom : Type*} [Fintype Nom]
+variable {Path : Exterior s.h s.delta → Fin (2^s.h) → Nom → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+
+private theorem left_pairPadding {tag : Mode.Tag} (ev : tag ≠ Mode.Tag.unit) (he : s.e = t*Z) (hd : 0 < s.delta)
+ {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))} {i : Fin (2^s.h)}
+ (atCut : g.castSucc = firstCut i) (valid : ValidPadding s cuts g tag .left) :
+ pairPadding t Z (liveCutEquiv s.h s.delta cuts).1 i := by
+ have e : incidentCut .left g = firstCut i := atCut
+ have hpos : 0 < (incidentCut .left g).val := e ▸ Nat.succ_pos _
+ have hhalf : (incidentCut .left g).val ≤ 2^s.h := e ▸ i.isLt
+ unfold ValidPadding at valid
+ rw [interval_pair s g tag ev .left .padding hd hpos hhalf,he] at valid
+ unfold incidentWidth at valid
+ rw [e] at valid
+ exact valid
+
+private theorem left_decoded_of_count (layout : LiveEvaluatorTail.Layout E.extra M w s.delta)
+ (initial : Code E.extra M) (bits : TailBits s.h s.delta) (k : Fin (2^s.h-1))
+ (j : Fin (2^s.h)) (hj : j.val = k.val+1) (count : tailCount E layout initial bits j ≠ 0) :
+ (LiveEvaluatorTail.readCut layout k (bits k)).isSome = true := by
+ cases hr : LiveEvaluatorTail.readCut layout k (bits k) with
+ | some v => rfl
+ | none =>
+ have hmid : LiveEvaluatorTail.boundary layout initial bits j.castSucc = none := by
+ have h₀ : j.val ≠ 0 := by omega
+ have hL : j.val ≠ 2^s.h := j.isLt.ne
+ simp only [LiveEvaluatorTail.boundary,Fin.val_castSucc,h₀,hL,↓reduceDIte]
+ have h : (⟨j.val-1,by have := j.isLt; omega⟩ : Fin (2^s.h-1)) = k := Fin.ext (by simp [hj])
+ rw [h]; exact hr
+ exfalso
+ apply count
+ unfold tailCount
+ apply Finset.sum_eq_zero
+ intro bit _
+ apply ite_eq_right
+ rintro ⟨a,b,ha,_⟩
+ rw [hmid] at ha
+ contradiction
+
+/-- The potentially stronger incoming check contributes no further factor
+once the physical padding passes and the active group's count is nonzero. -/
+theorem incoming_of_active_nonzero {tag : Mode.Tag} (ev : tag ≠ .unit) (he : s.e = t*Z)
+ (fit : 1+t*Z ≤ s.delta) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (layout : LiveEvaluatorTail.Layout E.extra M w s.delta) (init : (Fin t → ℕ) → Code E.extra M)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1)))
+ (left : ValidPadding s cuts g tag .left) (count : groupEvaluation fit inc E layout init cuts g ≠ 0) :
+ incomingChecks t Z layout cuts g := by
+ rcases coverCuts g.castSucc with z | l | ⟨i,hi⟩ | ⟨k,hk⟩
+ · exact incomingChecks_initial t Z layout cuts (congrArg Fin.val z)
+ · exact (Fin.castSucc_ne_last g l).elim
+ · exact (incomingChecks_pair t Z layout cuts i hi).2 (left_pairPadding ev he (by omega) hi left)
+ · let j : Fin (2^s.h) := ⟨k.val+1,by have := k.isLt; omega⟩
+ have same : g = halves s.h (.inr j) := Fin.ext (congrArg (fun v : Fin (2^(s.h+1)+1) => v.val) hk)
+ rw [same] at count
+ simp only [groupEvaluation,Equiv.symm_apply_apply,Sum.elim_inr] at count
+ have hr := left_decoded_of_count layout _ _ k j rfl count
+ obtain ⟨x,hx⟩ := Option.isSome_iff_exists.mp hr
+ exact (incomingChecks_tail t Z layout cuts k hk).2 ⟨x,(LiveEvaluatorTail.readCut_iff layout k _ x).1 hx⟩
+
+theorem specified_eq_evaluation {tag : Mode.Tag} (ev : tag ≠ .unit) (he : s.e = t*Z)
+ (fit : 1+t*Z ≤ s.delta) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (layout : LiveEvaluatorTail.Layout E.extra M w s.delta) (init : (Fin t → ℕ) → Code E.extra M)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1)))
+ (selected : physicalTag cuts g = some tag) (left : ValidPadding s cuts g tag .left) :
+ specifiedGroupCount fit inc E layout init cuts g = groupEvaluation fit inc E layout init cuts g := by
+ rw [← routed_specifiedGroupCount fit inc E layout init cuts g s.e s.config,selected]
+ cases tag with
+ | unit => contradiction
+ | pair | tail =>
+ by_cases h : incomingChecks t Z layout cuts g
+ · simp [routedCount,h]
+ · have hz : groupEvaluation fit inc E layout init cuts g = 0 := by
+ by_contra hn
+ exact h (incoming_of_active_nonzero ev he fit inc layout init cuts g left hn)
+ simp [routedCount,h,hz]
+
+end LiveHeaderProgram.Fields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveAuxiliaryDescriptorInit.lean b/lean/OAI/Computability/VPVNP/LiveAuxiliaryDescriptorInit.lean
new file mode 100644
index 0000000000..013a5cfd8b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveAuxiliaryDescriptorInit.lean
@@ -0,0 +1,274 @@
+import OAI.Computability.VPVNP.LiveHeaderSparseLayout
+import OAI.Computability.VPVNP.LiveHeaderCopyDispatch
+
+/-!
+# Constructing the auxiliary header descriptors on the live RAM
+
+A fixed straight-line call reads the two exterior cut lengths from live scratch
+memory. It calculates all seven packed ends and sparse target addresses, then
+writes the twenty-one descriptor words into a contiguous table. All reads precede
+the first table write.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveAuxiliaryDescriptorInit
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM LiveAuxiliaryHeaders LiveHeaderCopyDispatch
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Straight-line descriptor-initializer operations over 32 registers and 14 public operands. -/
+abbrev Ops := List (Op 32 14)
+
+/-- The initializer's public operands, including header dimensions, the histogram length,
+workspace addresses, and the seven source array bases. -/
+def data (L : Lengths) (N : ℕ) (shadow table lengthsSource : Word w) (source : Fin 7 → Word w) :
+ Fin 14 → Word w :=
+ ![(L.index : Word w), (L.advice : Word w), (L.cutCapacity : Word w), (N : Word w), shadow, table,
+ lengthsSource, source 0, source 1, source 2, source 3, source 4, source 5, source 6]
+
+private def endReg (i : Fin 7) : Fin 32 := ⟨12 + i.val, by omega⟩
+private def targetReg (i : Fin 7) : Fin 32 := ⟨19 + i.val, by omega⟩
+private def sourcePort (i : Fin 7) : Fin 14 := Fin.natAdd 7 i
+
+private theorem data_source (L : Lengths) (N : ℕ) (shadow table lengthsSource : Word w)
+ (source : Fin 7 → Word w) (i : Fin 7) : data L N shadow table lengthsSource source (sourcePort i) = source i := by
+ fin_cases i <;> rfl
+
+/-- Read the two live cut lengths, compute cumulative ends and shadow destinations for all
+seven fields, and advance the incoming state word. -/
+def setup : Ops :=
+ [.constant 0 1, .constant 1 3, .publicWord 2 0, .publicWord 3 1, .publicWord 4 2, .publicWord 5 3,
+ .publicWord 6 4, .publicWord 7 5, .publicWord 8 6, .constant 9 2, .binary .add 9 8 9, .read 10 8,
+ .read 11 9, .copy 12 1, .binary .add 13 12 2, .binary .add 14 13 2, .binary .add 15 14 3,
+ .binary .add 16 15 10, .binary .add 17 16 11, .binary .add 18 17 5, .copy 19 6,
+ .binary .add 20 19 1, .binary .add 21 20 2, .binary .add 22 21 2, .binary .add 23 22 3,
+ .binary .add 24 23 4, .binary .add 25 24 4, .stateWord 27, .binary .add 27 27 0]
+
+private def rowOps (i : Fin 7) : Ops :=
+ [.write 7 (endReg i), .binary .add 7 7 0, .publicWord 26 (sourcePort i), .write 7 26,
+ .binary .add 7 7 0, .write 7 (targetReg i), .binary .add 7 7 0]
+
+/-- The complete initializer instruction sequence, performing setup before writing the seven
+descriptor triples. -/
+def ops : Ops := setup ++ (List.finRange 7).flatMap rowOps
+
+/-- Instantiate the descriptor initializer on the supplied lengths and addresses, returning the
+advanced state word from register 27. -/
+def program (L : Lengths) (N : ℕ) (shadow table lengthsSource : Word w) (source : Fin 7 → Word w) :=
+ ((template ops 27).instantiate w (data L N shadow table lengthsSource source)).program
+
+/-- The descriptor for one auxiliary field, recording its exclusive packed end, source address,
+and destination in the sparse shadow. -/
+def rows (L : Lengths) (N : ℕ) (shadow : Word w) (source : Fin 7 → Word w) (i : Fin 7) : Descriptor w :=
+ ⟨(rangeStart L N i.succ : Word w), source i, ((shadow.val + destinationStart L i : ℕ) : Word w)⟩
+
+/-- Write the cumulative end, source base, and destination base of one row, in order. -/
+def putRow (table : Word w) (i : Fin 7) (row : Descriptor w) (m : Memory w) : Memory w :=
+ let m₁ := writeMemory m (address table i 0) row.endOffset
+ let m₂ := writeMemory m₁ (address table i 1) row.sourceBase
+ writeMemory m₂ (address table i 2) row.targetBase
+
+/-- The interpreter stores rows in the order of the supplied list. -/
+def storeRows (table : Word w) (rows : Fin 7 → Descriptor w) : List (Fin 7) → Memory w → Memory w
+ | [], m => m
+ | i :: is, m => storeRows table rows is (putRow table i (rows i) m)
+
+theorem address_val (table : Word w) (fit : table.val + 21 ≤ 2^w) (i : Fin 7) (f : Fin 3) :
+ (address table i f).val = table.val + (3*i.val + f.val) := by
+ have hi := i.isLt
+ have hf := f.isLt
+ have offsetFit : 3*i.val + f.val < 2^w := by omega
+ rw [address, Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt offsetFit, Nat.mod_eq_of_lt (by omega)]
+
+private theorem address_eq_iff (table : Word w) (fit : table.val + 21 ≤ 2^w)
+ (i j : Fin 7) (f g : Fin 3) :
+ (address table i f).val = (address table j g).val ↔ i = j ∧ f = g := by
+ rw [address_val table fit, address_val table fit]
+ have hf := f.isLt
+ have hg := g.isLt
+ simp only [Fin.ext_iff]
+ omega
+
+private def rowWord (row : Descriptor w) (f : Fin 3) : Word w :=
+ if f = 0 then row.endOffset else if f = 1 then row.sourceBase else row.targetBase
+
+private theorem putRow_at (table : Word w) (fit : table.val + 21 ≤ 2^w)
+ (i j : Fin 7) (row : Descriptor w) (m : Memory w) (f : Fin 3) :
+ putRow table j row m (address table i f).val =
+ if i = j then rowWord row f else m (address table i f).val := by
+ by_cases h : i = j
+ · subst j
+ fin_cases f <;> simp (config := {decide := true}) [putRow, writeMemory, rowWord, address_eq_iff table fit]
+ · simp [putRow, writeMemory, address_eq_iff table fit, h]
+
+private theorem storeRows_at (table : Word w) (fit : table.val + 21 ≤ 2^w)
+ (rows : Fin 7 → Descriptor w) (cells : List (Fin 7)) (m : Memory w) (i : Fin 7) (f : Fin 3) :
+ storeRows table rows cells m (address table i f).val =
+ if i ∈ cells then rowWord (rows i) f else m (address table i f).val := by
+ induction cells generalizing m with
+ | nil => simp [storeRows]
+ | cons j js ih =>
+ rw [storeRows, ih, putRow_at table fit]
+ by_cases h : i = j
+ · subst j
+ simp
+ · simp [h]
+
+theorem storeRows_spec (table : Word w) (fit : table.val + 21 ≤ 2^w)
+ (rows : Fin 7 → Descriptor w) (m : Memory w) :
+ Spec table rows (storeRows table rows (List.finRange 7) m) := by
+ constructor <;> intro i <;>
+ rw [storeRows_at table fit, ite_eq_left (List.mem_finRange i)] <;> rfl
+
+/-- The sequence of row writes preserves every address outside the table. -/
+theorem storeRows_outside (table : Word w) (fit : table.val + 21 ≤ 2^w)
+ (rows : Fin 7 → Descriptor w) (cells : List (Fin 7)) (m : Memory w) (a : ℕ)
+ (ha : a < table.val ∨ table.val + 21 ≤ a) : storeRows table rows cells m a = m a := by
+ have away (i : Fin 7) (f : Fin 3) : a ≠ (address table i f).val := by
+ rw [address_val table fit]
+ have hi := i.isLt
+ have hf := f.isLt
+ omega
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih => simp [storeRows, ih, putRow, writeMemory, away]
+
+private structure Prepared (L : Lengths) (N : ℕ) (shadow state : Word w) (rs : Regs w 32) : Prop where
+ one : rs 0 = 1
+ next : rs 27 = state + 1
+ ends : ∀ i, rs (endReg i) = (rangeStart L N i.succ : Word w)
+ targets : ∀ i, rs (targetReg i) = ((shadow.val + destinationStart L i : ℕ) : Word w)
+
+private theorem setup_trace (L : Lengths) (N : ℕ) (shadow table lengthsSource : Word w)
+ (source : Fin 7 → Word w) (state : Word w) (m : Memory w)
+ (hleft : m lengthsSource.val = (L.leftCut : Word w))
+ (hright : m (lengthsSource + 2).val = (L.rightCut : Word w)) :
+ ∃ es out, trace (data L N shadow table lengthsSource source) state setup (fun _ => 0) m = some (es,out,m) ∧
+ after m es = m ∧ es.length = 29 ∧ countProbes es = 2 ∧ choiceBits es = [] ∧
+ out 7 = table ∧ Prepared L N shadow state out := by
+ let es : List (Event w) := List.replicate 11 .tick ++ [.read lengthsSource (L.leftCut : Word w),
+ .read (lengthsSource+2) (L.rightCut : Word w)] ++ List.replicate 16 .tick
+ let regs : Regs w 32 := ![1, 3, (L.index : Word w), (L.advice : Word w), (L.cutCapacity : Word w),
+ (N : Word w), shadow, table, lengthsSource, lengthsSource + 2, (L.leftCut : Word w), (L.rightCut : Word w),
+ 3, 3 + L.index, 3 + 2*(L.index : Word w), 3 + 2*(L.index : Word w) + L.advice,
+ 3 + 2*(L.index : Word w) + L.advice + L.leftCut,
+ 3 + 2*(L.index : Word w) + L.advice + L.leftCut + L.rightCut,
+ 3 + 2*(L.index : Word w) + L.advice + L.leftCut + L.rightCut + N,
+ shadow, shadow+3, shadow+3+L.index, shadow+3+2*(L.index : Word w),
+ shadow+3+2*(L.index : Word w)+L.advice, shadow+3+2*(L.index : Word w)+L.advice+L.cutCapacity,
+ shadow+3+2*(L.index : Word w)+L.advice+2*(L.cutCapacity : Word w), 0, state+1, 0, 0, 0, 0]
+ refine ⟨es, regs, ?_, rfl, rfl, rfl, rfl, rfl, ⟨rfl, rfl, ?_, ?_⟩⟩
+ · simp (config := {decide := true}) [setup, trace, Op.effect, Function.update, data,
+ show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl, hleft, hright, es,
+ List.replicate_succ]
+ funext i
+ fin_cases i <;> simp (config := {decide := true}) [regs, Function.update] <;> ring
+ · intro i
+ fin_cases i <;> simp [endReg, rangeStart, exteriorBase, regs]
+ · intro i
+ fin_cases i <;> simp [targetReg, destinationStart, exteriorBase, Header.count, regs] <;> ring
+
+private theorem row_trace (L : Lengths) (N : ℕ) (shadow table lengthsSource : Word w)
+ (source : Fin 7 → Word w) (state : Word w) (m : Memory w) (rs : Regs w 32)
+ (i : Fin 7) (ready : Prepared L N shadow state rs) (ptr : rs 7 = address table i 0) :
+ let mem := putRow table i (rows L N shadow source i) m
+ ∃ es out, trace (data L N shadow table lengthsSource source) state (rowOps i) rs m = some (es,out,mem) ∧
+ after m es = mem ∧ es.length = 7 ∧ countProbes es = 3 ∧ choiceBits es = [] ∧
+ out 7 = table + ((3*(i.val+1) : ℕ) : Word w) ∧ Prepared L N shadow state out := by
+ dsimp only
+ let row := rows L N shadow source i
+ let es : List (Event w) := [.write (address table i 0) row.endOffset, .tick, .tick,
+ .write (address table i 1) row.sourceBase, .tick, .write (address table i 2) row.targetBase, .tick]
+ let out := Function.update (Function.update (Function.update (Function.update rs 7 (rs 7+1))
+ 26 (source i)) 7 (rs 7+1+1)) 7 (rs 7+1+1+1)
+ have a₁ : rs 7 + 1 = address table i 1 := by simp [ptr,address,add_assoc]
+ have a₂ : rs 7 + 1 + 1 = address table i 2 := by simp [ptr,address]; ring
+ have ne₁ (j : Fin 7) : targetReg j ≠ 7 := by simp [targetReg, Fin.ext_iff]; omega
+ have ne₂ (j : Fin 7) : targetReg j ≠ 26 := by simp [targetReg, Fin.ext_iff]; omega
+ have ne₃ (j : Fin 7) : endReg j ≠ 7 := by simp [endReg, Fin.ext_iff]; omega
+ have ne₄ (j : Fin 7) : endReg j ≠ 26 := by simp [endReg, Fin.ext_iff]; omega
+ refine ⟨es,out,?_,rfl,rfl,rfl,rfl,?_,?_⟩
+ · simp (config := {decide := true}) [rowOps, trace, Op.effect,
+ show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl, out, es, row,
+ putRow, rows, ready.one, ready.ends, ready.targets, data_source, ne₁, ne₂,
+ Function.update_of_ne, ← ptr, ← a₁, ← a₂]
+ · change rs 7+1+1+1 = _
+ rw [ptr]; simp [address]; ring
+ · refine ⟨ready.one, ready.next, ?_, ?_⟩
+ · intro j
+ simp [out, ne₃, ne₄, ready.ends]
+ · intro j
+ simp [out, ne₁, ne₂, ready.targets]
+
+private theorem count_append (es fs : List (Event w)) :
+ countProbes (es ++ fs) = countProbes es + countProbes fs := by
+ induction es with
+ | nil => simp [countProbes]
+ | cons e es ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+private theorem trace_cells (L : Lengths) (N : ℕ) (shadow table lengthsSource : Word w)
+ (source : Fin 7 → Word w) (state : Word w) (cells : List (Fin 7)) (start : ℕ)
+ (aligned : cells.map Fin.val = List.range' start cells.length) (m : Memory w) (rs : Regs w 32)
+ (ready : Prepared L N shadow state rs) (ptr : rs 7 = table + ((3*start : ℕ) : Word w)) :
+ let mem := storeRows table (rows L N shadow source) cells m
+ ∃ es out, trace (data L N shadow table lengthsSource source) state (cells.flatMap rowOps) rs m = some (es,out,mem) ∧
+ after m es = mem ∧ es.length = 7*cells.length ∧ countProbes es = 3*cells.length ∧
+ choiceBits es = [] ∧ out 27 = state+1 := by
+ dsimp only
+ induction cells generalizing start m rs with
+ | nil => exact ⟨[],rs,rfl,rfl,rfl,rfl,rfl,ready.next⟩
+ | cons i cells ih =>
+ simp only [List.map_cons, List.length_cons, List.range'_succ, List.cons.injEq] at aligned
+ obtain ⟨rfl, aligned⟩ := aligned
+ obtain ⟨es, tmp, he, hm, hl, hp, hb, hptr, hr⟩ :=
+ row_trace L N shadow table lengthsSource source state m rs i ready (by simpa [address] using ptr)
+ obtain ⟨fs, out, hf, hn, hfLen, hfProbe, hfBits, hnext⟩ := ih _ aligned (putRow table i (rows L N shadow source i) m) tmp hr hptr
+ refine ⟨es ++ fs, out, ?_, ?_, ?_, ?_, ?_, hnext⟩
+ · rw [List.flatMap_cons, trace_append, he]
+ simp [hf,storeRows]
+ · rw [after, List.foldl_append, show es.foldl update m = _ from hm]
+ exact hn
+ · simp only [List.length_append, hl, hfLen, List.length_cons]; omega
+ · simp only [count_append, hp, hfProbe, List.length_cons]; omega
+ · simp [Flow.choiceBits_append,hb,hfBits]
+
+/-- Construct the descriptor table from the public layout and the two exterior lengths
+already stored in scratch memory. A single native call reads two words and writes twenty-one. -/
+theorem init_native (L : Lengths) (N : ℕ) (shadow table lengthsSource : Word w) (source : Fin 7 → Word w)
+ (state : Word w) (m : Memory w) (fit : table.val + 21 ≤ 2^w)
+ (hleft : m lengthsSource.val = (L.leftCut : Word w)) (hright : m (lengthsSource+2).val = (L.rightCut : Word w)) :
+ let P := program L N shadow table lengthsSource source
+ ∃ es, execute P 79 (P.start state) m [] = some ⟨es,some (state+1)⟩ ∧
+ Spec table (rows L N shadow source) (after m es) ∧
+ (∀ a, a < table.val ∨ table.val + 21 ≤ a → after m es a = m a) ∧
+ es.length = 78 ∧ countProbes es = 23 ∧ choiceBits es = [] := by
+ dsimp only
+ obtain ⟨es, rs, he, hm, hl, hp, hb, ptr, ready⟩ :=
+ setup_trace L N shadow table lengthsSource source state m hleft hright
+ obtain ⟨fs, out, hf, hn, hflen, hfprobe, hfbits, hret⟩ := trace_cells L N shadow table lengthsSource source
+ state (List.finRange 7) 0 (by decide) m rs ready (by simpa using ptr)
+ have hafter : after m (es ++ fs) = storeRows table (rows L N shadow source) (List.finRange 7) m := by
+ rw [after, List.foldl_append, show es.foldl update m = m from hm]
+ exact hn
+ refine ⟨es ++ fs, ?_, hafter ▸ storeRows_spec table fit _ m, ?_, ?_, ?_, ?_⟩
+ · let pub := data L N shadow table lengthsSource source
+ change execute ((template ops 27).instantiate w pub).program (1+ops.length) ⟨_,state,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace, ops, trace_append, he]
+ simp [pub, hf, hret]
+ · intro a ha
+ rw [hafter]
+ exact storeRows_outside table fit _ _ m a ha
+ · simp [hl,hflen]
+ · simp [count_append,hp,hfprobe]
+ · simp [Flow.choiceBits_append,hb,hfbits]
+
+end LiveAuxiliaryDescriptorInit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveAuxiliaryGuardedCopy.lean b/lean/OAI/Computability/VPVNP/LiveAuxiliaryGuardedCopy.lean
new file mode 100644
index 0000000000..b1a0feefbd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveAuxiliaryGuardedCopy.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.LiveAuxiliaryStages
+import OAI.Computability.VPVNP.LiveAuxiliaryHeaderSweep
+import OAI.Computability.VPVNP.LiveHeaderProtectedCore
+
+/-!
+# Executing the indirect cursor guard on the complete sparse header copy
+
+Each live call rereads the last descriptor's packed end. The source sweep
+writes only its current sparse destination, so all descriptors retain their
+values across the active calls. At the packed end one additional call reads
+the limit and accepts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveAuxiliaryStages
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM LiveAuxiliaryHeaders LiveHeaderCopyDispatch
+open scoped Fin.CommRing
+
+variable {w : ℕ} {desc : Word w} {base : ℕ} {L : Lengths}
+variable {hdr : Header L → Bool} {hist : List (Word w)} {src : Fin 7 → Word w}
+
+private abbrev guarded (desc : Word w) := (copy.instantiate w (copyData desc)).program
+
+private theorem loaded_limit {m : Memory w} (h : Prepared desc base L hdr hist src m) :
+ LiveCountedStage.limit true (address desc 6 0) m = (populated L hist.length : Word w) :=
+ h.descriptors.ends 6
+
+/-- Add the four indirect-guard instructions to each call of a successful
+source prefix. The two runs have identical memory at every return. -/
+private theorem lift_prefix (fit : base+span L hist.length ≤ 2^w) (width : populated L hist.length < 2^w)
+ (sep : Separated desc base L hist.length src fit) (fuel : ℕ) (room : 68 ≤ fuel)
+ (tag : Word w) (outside : tag.val < base ∨ base+span L hist.length ≤ tag.val)
+ (len start : ℕ) (bound : start+len ≤ populated L hist.length) {m : Memory w}
+ (ready : Prepared desc base L hdr hist src m) {rs : List (Report w)}
+ (run : runSegment (program desc) 64 (some (start : Word w)) m (List.replicate len []) = some rs) :
+ ∃ gs, runSegment (guarded desc) fuel (some (start : Word w)) m (List.replicate len []) = some gs ∧
+ endState (some (start : Word w)) gs = some ((start+len : ℕ) : Word w) ∧
+ after m (eventLog gs) = after m (eventLog rs) ∧ Prepared desc base L hdr hist src (after m (eventLog gs)) ∧
+ gs.length = len ∧ (∀ r ∈ gs, r.events.length < 68 ∧ r.probes ≤ 12 ∧ choiceBits r.events = []) ∧
+ LiveStageLink.PreservesTagOnReturns tag m gs := by
+ induction len generalizing start m rs with
+ | zero =>
+ simp only [List.replicate_zero, runSegment, Option.some.injEq] at run
+ subst rs
+ exact ⟨[],rfl,rfl,rfl,ready,rfl,by simp,trivial⟩
+ | succ len ih =>
+ let i : Fin (populated L hist.length) := ⟨start, by omega⟩
+ obtain ⟨es, hr, hm, hl, hp, hb⟩ := native_cell fit width ready i
+ let raw : Report w := ⟨es,some ((start : Word w)+1)⟩
+ let gsHead := LiveCountedStage.prefixReport true (address desc 6 0) m raw
+ have guard : (start : Word w) < LiveCountedStage.limit true (address desc 6 0) m := by
+ rw [loaded_limit ready]
+ change (start : Word w).val < (populated L hist.length : Word w).val
+ rw [Fin.val_cast_of_lt (i.isLt.trans width), Fin.val_cast_of_lt width]
+ exact i.isLt
+ have hg : execute (guarded desc) 68 ((guarded desc).start (start : Word w)) m [] = some gsHead := by
+ rw [show execute (guarded desc) 68 ((guarded desc).start (start : Word w)) m [] = _ from
+ LiveCountedStage.execute_active (flow.template (some 11)) true (fun _ => desc)
+ (address desc 6 0) 64 (start : Word w) m guard []]
+ change (execute (program desc) 64 ((program desc).start (start : Word w)) m []).map _ = _
+ rw [hr]; rfl
+ have hgfuel := execute_extend hg (fuel-68)
+ rw [Nat.add_sub_cancel' room] at hgfuel
+ have prepared : Prepared desc base L hdr hist src (after m es) := hm ▸ ready.write sep i _
+ have head_mem : after m gsHead.events = after m es := rfl
+ have head_st : gsHead.result = some ((start+1 : ℕ) : Word w) := by simp [gsHead,raw]
+ have preserve : after m gsHead.events tag.val = m tag.val := by
+ rw [head_mem, hm]
+ apply ite_eq_right
+ change tag.val ≠ base+(sparseOffset L hist.length i).val
+ have hi := (sparseOffset L hist.length i).isLt
+ omega
+ rw [List.replicate_succ,runSegment,hr] at run
+ obtain ⟨rest, hrest, rfl⟩ := Option.map_eq_some_iff.mp run
+ change runSegment (program desc) 64 (some ((start : Word w)+1)) (after m es) _ = _ at hrest
+ rw [← Nat.cast_one (R := Word w), ← Nat.cast_add] at hrest
+ obtain ⟨gs, hs, he, same, prepared', length, costs, frame⟩ :=
+ ih (start+1) (by omega) prepared hrest
+ refine ⟨gsHead::gs, ?_, ?_, ?_, ?_, by simp [length], ?_, ?_⟩
+ · simp only [List.replicate_succ, runSegment, hgfuel, head_st, head_mem, hs, Option.map_some]
+ · change endState gsHead.result gs = _
+ rw [head_st, he]
+ congr 2
+ omega
+ · change after m (gsHead.events ++ eventLog gs) = after m (es ++ eventLog rest)
+ simp only [after,List.foldl_append]
+ change after (after m gsHead.events) (eventLog gs) = after (after m es) (eventLog rest)
+ rw [head_mem]
+ exact same
+ · change Prepared _ _ _ _ _ _ (after m (gsHead.events ++ eventLog gs))
+ simp only [after,List.foldl_append]
+ change Prepared _ _ _ _ _ _ (after (after m gsHead.events) (eventLog gs))
+ rw [head_mem]
+ exact prepared'
+ · intro r h
+ rcases List.mem_cons.mp h with rfl | h
+ · refine ⟨?_,?_,hb⟩
+ · change (LiveCountedStage.guardEvents true (address desc 6 0) m ++ es).length < 68
+ rw [List.length_append,LiveCountedStage.guardEvents_length]; omega
+ · change 1+countProbes es ≤ 12
+ omega
+ · exact costs r h
+ · exact ⟨fun _ => preserve, head_mem ▸ frame⟩
+
+/-- The actual auxiliary copy component performs one guarded call for every
+populated word and one closing call. Its final memory is precisely the sparse
+installation used by the virtual auxiliary machine. -/
+theorem guarded_copy_native (fit : base+span L hist.length ≤ 2^w) (width : populated L hist.length < 2^w)
+ (sep : Separated desc base L hist.length src fit) (fuel : ℕ) (room : 68 ≤ fuel)
+ (tag : Word w) (outside : tag.val < base ∨ base+span L hist.length ≤ tag.val)
+ {m : Memory w} (ready : Prepared desc base L hdr hist src m) :
+ let n := populated L hist.length
+ let P := (copy.instantiate w (copyData desc)).program
+ ∃ (active : List (Report w)) (closed : Report w),
+ runSegment P fuel (some 0) m (List.replicate (n+1) []) = some (active++[closed]) ∧
+ endState (some 0) (active++[closed]) = none ∧
+ after m (eventLog (active++[closed])) = install base L hdr hist fit m ∧
+ active.length = n ∧ (∀ r ∈ active, r.events.length < 68 ∧ r.probes ≤ 12 ∧ choiceBits r.events = []) ∧
+ closed.events.length = 4 ∧ closed.probes = 1 ∧ choiceBits closed.events = [] ∧
+ LiveStageLink.PreservesTagOnReturns tag m (active++[closed]) := by
+ dsimp only
+ let n := populated L hist.length
+ obtain ⟨rs, run, _, mem, _, _⟩ := sweep_native fit width sep ready
+ obtain ⟨active, hg, he, same, prep, len, costs, frame⟩ := lift_prefix fit width sep fuel room tag outside n 0
+ (by simp [n]) ready (by simpa only [Nat.cast_zero] using run)
+ simp only [Nat.cast_zero, Nat.zero_add] at hg he
+ let current := after m (eventLog active)
+ let closed : Report w := ⟨LiveCountedStage.guardEvents true (address desc 6 0) current, none⟩
+ have hc : execute (guarded desc) fuel ((guarded desc).start (n : Word w)) current [] = some closed := by
+ rw [show fuel = (fuel-5)+5 by omega]
+ exact copy_closed desc (records L hist.length base src) current prep.descriptors (fuel-5) (n : Word w) le_rfl []
+ refine ⟨active,closed,?_,?_,?_,len,costs,rfl,rfl,rfl,
+ frame.append (LiveStageLink.PreservesTagOnReturns.singleton_accept _ _ closed rfl)⟩
+ · change runSegment (guarded desc) fuel (some 0) m (List.replicate (n+1) []) = _
+ rw [List.replicate_succ',PrimedSchedule.runSegment_append,hg]
+ simp only [Option.bind_some,he,runSegment,show execute (guarded desc) fuel
+ ((guarded desc).start (n : Word w)) (after m (eventLog active)) [] = _ from hc,Option.map_some]
+ · rw [endState_append]; rfl
+ · simp only [eventLog,List.flatMap_append,List.flatMap_singleton,after,List.foldl_append]
+ exact same.trans mem
+
+end LiveAuxiliaryStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaderInputs.lean b/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaderInputs.lean
new file mode 100644
index 0000000000..5eaf875cd4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaderInputs.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.LiveAuxiliaryHeaderSweep
+
+/-!
+# Linking the seven input arrays to the auxiliary coefficient machine
+
+The sparse writer reads one word per length, primed index bit, advice bit,
+exterior bit, and nominated histogram entry. The field equations below
+are the contracts provided by their individual producer routines.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveAuxiliaryHeaders
+
+open BurstRAM PrimedInputRAM LiveHeaderCopyDispatch
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The seven field lengths in copy order, covering the three length words, both index fields,
+advice, exterior cuts, and nominated histogram. -/
+def fieldSize (L : Lengths) (N : ℕ) : Fin 7 → ℕ :=
+ ![3,L.index,L.index,L.advice,L.leftCut,L.rightCut,N]
+
+private theorem field_end (L : Lengths) (N : ℕ) (f : Fin 7) :
+ rangeStart L N f.castSucc + fieldSize L N f = rangeStart L N f.succ := by
+ fin_cases f <;> simp [rangeStart, fieldSize, exteriorBase]
+ omega
+
+private def atWord (m : Memory w) (base : Word w) (offset : ℕ) := m (base + (offset : Word w)).val
+
+/-- Memory equations for the producer outputs, before writing the sparse O header. -/
+structure InputArrays (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w))
+ (source : Fin 7 → Word w) (m : Memory w) : Prop where
+ lengths : ∀ j : Fin 3, m (source 0 + (j.val : Word w)).val = Fin.ofNat _ (cutLength L j)
+ leftIndex : ∀ j : Fin L.index, m (source 1 + (j.val : Word w)).val = encodeBit w (hdr (.group 0 j))
+ rightIndex : ∀ j : Fin L.index, m (source 2 + (j.val : Word w)).val = encodeBit w (hdr (.group 1 j))
+ advice : ∀ j : Fin L.advice, m (source 3 + (j.val : Word w)).val = encodeBit w (hdr (.advice j))
+ leftCut : ∀ j : Fin L.leftCut, m (source 4 + (j.val : Word w)).val = encodeBit w (hdr (.leftCut j))
+ rightCut : ∀ j : Fin L.rightCut, m (source 5 + (j.val : Word w)).val = encodeBit w (hdr (.rightCut j))
+ nominations : ∀ j : Fin hist.length, m (source 6 + (j.val : Word w)).val = hist[j]
+
+variable {L : Lengths} {hdr : Header L → Bool} {hist : List (Word w)}
+ {src : Fin 7 → Word w} {m : Memory w}
+
+private theorem InputArrays.field (ha : InputArrays L hdr hist src m) (f : Fin 7)
+ (j : Fin (fieldSize L hist.length f)) :
+ atWord m (src f) j.val = headerMemory L hdr hist (destinationStart L f + j.val) := by
+ fin_cases f
+ · simpa [atWord, destinationStart, headerMemory_length L hdr hist j] using ha.lengths j
+ · exact (ha.leftIndex j).trans (by
+ simpa [destinationStart, Header.address] using (headerMemory_bits L hdr hist (.group 0 j)).symm)
+ · exact (ha.rightIndex j).trans (by
+ simpa [destinationStart, Header.address] using (headerMemory_bits L hdr hist (.group 1 j)).symm)
+ · exact (ha.advice j).trans (headerMemory_bits L hdr hist (.advice j)).symm
+ · exact (ha.leftCut j).trans (headerMemory_bits L hdr hist (.leftCut j)).symm
+ · exact (ha.rightCut j).trans (headerMemory_bits L hdr hist (.rightCut j)).symm
+ · change atWord m (src 6) j.val = headerMemory L hdr hist (Header.count L + j.val)
+ rw [headerMemory_hist, List.getElem?_eq_getElem (by exact j.isLt), Option.getD_some]
+ exact ha.nominations ⟨j.val, j.isLt⟩
+
+/-- Every packed read lands on its producer's word and every destination is
+the address the auxiliary machine will query for that field. -/
+theorem InputArrays.read (ha : InputArrays L hdr hist src m) (i : Fin (populated L hist.length)) :
+ m (sourceAddress L hist.length src i).val = headerMemory L hdr hist (sparseOffset L hist.length i).val := by
+ let f := rangeAt L hist.length i
+ let k := i.val - rangeStart L hist.length f.castSucc
+ have hlo : rangeStart L hist.length f.castSucc ≤ i.val := (rangeAt_bounds L hist.length i).1
+ have hi : i.val < rangeStart L hist.length f.castSucc + fieldSize L hist.length f := by
+ rw [field_end]; exact (rangeAt_bounds L hist.length i).2
+ have hk : k < fieldSize L hist.length f := by dsimp [k]; omega
+ rw [sparseOffset_at_range]
+ exact ha.field f ⟨k,hk⟩
+
+theorem InputArrays.prepared (ha : InputArrays L hdr hist src m) {desc : Word w} {base : ℕ}
+ (ht : Spec desc (records L hist.length base src) m) : Prepared desc base L hdr hist src m :=
+ ⟨ht, ha.read⟩
+
+end LiveAuxiliaryHeaders
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaderPreparation.lean b/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaderPreparation.lean
new file mode 100644
index 0000000000..590ec1e2e7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaderPreparation.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.LiveAuxiliaryHeaderInputs
+import OAI.Computability.VPVNP.LiveAuxiliaryDescriptorInit
+import OAI.Computability.VPVNP.LiveOneShot
+
+/-!
+# Preparing a live group's sparse auxiliary RAM header
+
+One native call reads the two exterior lengths and constructs the seven
+descriptors. A sequence of native copy calls then writes the header the
+auxiliary pair computation will see. The initialization phase has an accepting
+exit, allowing the enclosing live stage linker to start the copy cursor at zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveAuxiliaryHeaders
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Normal acceptance after the twenty-one descriptor words have been written. -/
+def initTable := LiveOneShot.oneShot (template LiveAuxiliaryDescriptorInit.ops 27)
+
+/-- The length-array base is the first of the seven source bases. -/
+def initData (L : Lengths) (labels : ℕ) (shadow table : Word w) (src : Fin 7 → Word w) :=
+ LiveAuxiliaryDescriptorInit.data L labels shadow table (src 0) src
+
+/-- Physical address bounds used by the two stages. Table words, source words
+and auxiliary destinations can be placed in distinct live scratch regions. -/
+structure Areas (table shadow : Word w) (L : Lengths) (N : ℕ) (src : Fin 7 → Word w) : Prop where
+ tableFit : table.val + 21 ≤ 2^w
+ shadowFit : shadow.val + span L N ≤ 2^w
+ countFit : populated L N < 2^w
+ sourcesTable : ∀ i, (sourceAddress L N src i).val < table.val ∨ table.val + 21 ≤ (sourceAddress L N src i).val
+ tableShadow : table.val + 21 ≤ shadow.val ∨ shadow.val + span L N ≤ table.val
+ separated : Separated table shadow.val L N src shadowFit
+
+/-- Both stages execute on the original live memory, including the true label
+nominations. Every virtual address in the reserved zero-initialized region
+returns the exact word of the §11 auxiliary header. -/
+theorem prepare_native (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w))
+ (src : Fin 7 → Word w) (table shadow : Word w) (m : Memory w)
+ (areas : Areas table shadow L hist.length src) (inputs : InputArrays L hdr hist src m)
+ (fresh : ∀ a < span L hist.length, m (shadow.val+a) = 0) :
+ let init := (initTable.instantiate w (initData L hist.length shadow table src)).program
+ let copy := LiveHeaderCopyDispatch.program table
+ let n := populated L hist.length
+ ∃ es rs, execute init 79 (init.start 0) m [] = some ⟨es, none⟩ ∧
+ runSegment copy 64 (some 0) (after m es) (List.replicate n []) = some rs ∧
+ endState (some 0) rs = some (n : Word w) ∧ rs.length = n ∧
+ (∀ a < span L hist.length,
+ after (after m es) (eventLog rs) (shadow.val + a) = headerMemory L hdr hist a) ∧
+ (∀ a, (a < table.val ∨ table.val+21 ≤ a) → (a < shadow.val ∨ shadow.val+span L hist.length ≤ a) →
+ after (after m es) (eventLog rs) a = m a) ∧
+ es.length = 78 ∧ countProbes es = 23 ∧ choiceBits es = [] ∧
+ ∀ r ∈ rs, r.events.length < 64 ∧ countProbes r.events ≤ 11 ∧ choiceBits r.events = [] := by
+ have hleft : m (src 0).val = (L.leftCut : Word w) := by
+ simpa [cutLength] using inputs.lengths 0
+ have hright : m (src 0 + 2).val = (L.rightCut : Word w) := by
+ simpa [cutLength] using inputs.lengths 2
+ obtain ⟨es, he, tableReady, preserved, hl, hp, hc⟩ := LiveAuxiliaryDescriptorInit.init_native
+ L hist.length shadow table (src 0) src 0 m areas.tableFit hleft hright
+ have hprep : Prepared table shadow.val L hdr hist src (after m es) := by
+ refine ⟨tableReady, fun i => ?_⟩
+ rw [preserved _ (areas.sourcesTable i)]
+ exact inputs.read i
+ obtain ⟨rs, hr, hstate, hm, hlen, hcost⟩ :=
+ sweep_native areas.shadowFit areas.countFit areas.separated hprep
+ refine ⟨es, rs, ?_, hr, hstate, hlen, ?_, ?_, hl, hp, hc, hcost⟩
+ · change execute ((LiveOneShot.oneShot (template LiveAuxiliaryDescriptorInit.ops 27)).instantiate w
+ (initData L hist.length shadow table src)).program 79
+ ((LiveAuxiliaryDescriptorInit.program L hist.length shadow table (src 0) src).start 0) m [] = _
+ rw [LiveOneShot.execute_oneShot]
+ change Option.map (fun t : Report w => (⟨t.events, none⟩ : Report w)) (execute (LiveAuxiliaryDescriptorInit.program L hist.length shadow table (src 0) src) 79 _ m []) = _
+ rw [he]
+ rfl
+ · intro a ha
+ rw [hm]
+ apply install_read
+ rw [preserved _ (by rcases areas.tableShadow with h | h <;> omega)]
+ exact fresh a ha
+ · intro a ht hs
+ rw [hm, install_outside _ _ _ _ _ _ _ hs, preserved _ ht]
+
+end LiveAuxiliaryHeaders
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaderSweep.lean b/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaderSweep.lean
new file mode 100644
index 0000000000..0c7c91d5cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaderSweep.lean
@@ -0,0 +1,188 @@
+import OAI.Computability.VPVNP.LiveHeaderSparseLayout
+import OAI.Computability.VPVNP.LiveHeaderCopyDispatch
+import OAI.Computability.VPVNP.RAMChain
+
+/-!
+# Copying the seven populated auxiliary header fields
+
+The persistent cursor ranges over a packed interval even though the virtual
+header reserves space for both exterior fields at full capacity. The actual
+machine reads the seven descriptors from external memory and writes the selected
+word into the separate auxiliary region.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveAuxiliaryHeaders
+
+open BurstRAM PrimedInputRAM LiveHeaderCopyDispatch
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Descriptor ends are packed cursor positions; targets use sparse virtual offsets. -/
+def records (L : Lengths) (N base : ℕ) (source : Fin 7 → Word w) (j : Fin 7) : Descriptor w :=
+ ⟨(rangeStart L N j.succ : Word w), source j, ((base + destinationStart L j : ℕ) : Word w)⟩
+
+private theorem prev_records (L : Lengths) (N base : ℕ) (source : Fin 7 → Word w) (j : Fin 7) :
+ prevEnd (records L N base source) j = (rangeStart L N j.castSucc : Word w) := by
+ fin_cases j <;> simp [prevEnd, records, rangeStart]
+
+/-- The original, contiguous array address of each word in the packed iteration. -/
+noncomputable def sourceAddress (L : Lengths) (N : ℕ) (source : Fin 7 → Word w)
+ (i : Fin (populated L N)) : Word w :=
+ let j := rangeAt L N i
+ source j + ((i.val - rangeStart L N j.castSucc : ℕ) : Word w)
+
+private theorem target_eq (L : Lengths) (N base : ℕ) (source : Fin 7 → Word w)
+ (hfit : base + span L N ≤ 2^w) (i : Fin (populated L N)) :
+ let j := rangeAt L N i
+ let ds := records L N base source
+ (ds j).targetBase + ((i.val : Word w) - prevEnd ds j) =
+ scratchAddress base hfit (sparseOffset L N i) := by
+ dsimp only
+ rw [prev_records, ← Nat.cast_sub (rangeAt_bounds L N i).1]
+ change ((base + destinationStart L (rangeAt L N i) : ℕ) : Word w) + _ = _
+ rw [← Nat.cast_add, Nat.add_assoc, ← sparseOffset_at_range]
+ apply Fin.ext
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt ((Nat.add_lt_add_left (sparseOffset L N i).isLt base).trans_le hfit)]
+ rfl
+
+private theorem store_mem_congr {n : ℕ} (dst : Fin n ↪ Word w) (v : Fin n → Word w)
+ (a b : List (Fin n)) (h : ∀ j, j ∈ a ↔ j ∈ b) (m : Memory w) :
+ store dst v a m = store dst v b m := by
+ funext p
+ by_cases ht : ∃ i ∈ a, (dst i).val = p
+ · obtain ⟨i,hi,rfl⟩ := ht
+ rw [store_at _ _ _ _ hi, store_at _ _ _ _ ((h i).1 hi)]
+ · have outside (i : Fin n) (hi : i ∈ a) : p ≠ (dst i).val :=
+ fun e => ht ⟨i, hi, e.symm⟩
+ rw [store_outside _ _ _ _ _ outside,
+ store_outside _ _ _ _ _ (fun i hi => outside i ((h i).2 hi))]
+
+private theorem store_packed_eq_install (base : ℕ) (L : Lengths) (hdr : Header L → Bool)
+ (hist : List (Word w)) (hfit : base + span L hist.length ≤ 2^w) (m : Memory w) :
+ store (scratchAddress base hfit) (fun j => headerMemory L hdr hist j.val)
+ ((List.finRange (populated L hist.length)).map (sparseOffset L hist.length)) m =
+ install base L hdr hist hfit m := by
+ apply store_mem_congr
+ intro j
+ rw [sparseOffset_range]
+ simp
+
+/-- Working areas and the dispatcher table are disjoint from every destination
+word written by the sparse copy. Only the addresses actually read are required. -/
+structure Separated (desc : Word w) (base : ℕ) (L : Lengths) (N : ℕ)
+ (src : Fin 7 → Word w) (fit : base + span L N ≤ 2^w) : Prop where
+ sources : ∀ i j : Fin (populated L N),
+ (sourceAddress L N src i).val ≠ (scratchAddress base fit (sparseOffset L N j)).val
+ table : ∀ row field (j : Fin (populated L N)),
+ (address desc row field).val ≠ (scratchAddress base fit (sparseOffset L N j)).val
+
+/-- State of the read-only arrays required for the copy. The three length words
+and all populated data bits match the auxiliary machine's prescribed header. -/
+structure Prepared (desc : Word w) (base : ℕ) (L : Lengths) (hdr : Header L → Bool)
+ (hist : List (Word w)) (src : Fin 7 → Word w) (m : Memory w) : Prop where
+ descriptors : Spec desc (records L hist.length base src) m
+ sources : ∀ i : Fin (populated L hist.length),
+ m (sourceAddress L hist.length src i).val = headerMemory L hdr hist (sparseOffset L hist.length i).val
+
+theorem Prepared.write {desc : Word w} {base : ℕ} {L : Lengths} {hdr : Header L → Bool}
+ {hist : List (Word w)} {src : Fin 7 → Word w} {m : Memory w}
+ (h : Prepared desc base L hdr hist src m) {fit : base + span L hist.length ≤ 2^w}
+ (sep : Separated desc base L hist.length src fit) (j : Fin (populated L hist.length)) (x : Word w) :
+ Prepared desc base L hdr hist src (writeMemory m (scratchAddress base fit (sparseOffset L hist.length j)) x) := by
+ constructor
+ · constructor
+ · intro r; simpa only [writeMemory, ite_eq_right (sep.table r 0 j)] using h.descriptors.ends r
+ · intro r; simpa only [writeMemory, ite_eq_right (sep.table r 1 j)] using h.descriptors.sources r
+ · intro r; simpa only [writeMemory, ite_eq_right (sep.table r 2 j)] using h.descriptors.targets r
+ · intro i; simpa only [writeMemory, ite_eq_right (sep.sources i j)] using h.sources i
+
+variable {desc : Word w} {base : ℕ} {L : Lengths} {hdr : Header L → Bool}
+ {hist : List (Word w)} {src : Fin 7 → Word w}
+
+theorem native_cell (fit : base + span L hist.length ≤ 2^w)
+ (hwidth : populated L hist.length < 2^w) {m : Memory w}
+ (h : Prepared desc base L hdr hist src m) (i : Fin (populated L hist.length)) :
+ ∃ es, execute (program desc) 64 ((program desc).start (i.val : Word w)) m [] =
+ some ⟨es, some ((i.val : Word w)+1)⟩ ∧
+ after m es = writeMemory m (scratchAddress base fit (sparseOffset L hist.length i))
+ (headerMemory L hdr hist (sparseOffset L hist.length i).val) ∧
+ es.length < 64 ∧ countProbes es ≤ 11 ∧ choiceBits es = [] := by
+ let ds := records L hist.length base src
+ let row := rangeAt L hist.length i
+ have endval (j : Fin 7) : (ds j).endOffset.val = rangeStart L hist.length j.succ := by
+ exact Nat.mod_eq_of_lt ((rangeEnd_le L hist.length j).trans_lt hwidth)
+ have curval : ((i.val : Word w) : ℕ) = i.val := Nat.mod_eq_of_lt (i.isLt.trans hwidth)
+ have hskip (j : Fin 7) (hj : j < row) : (ds j).endOffset ≤ (i.val : Word w) := by
+ change (ds j).endOffset.val ≤ ((i.val : Word w) : ℕ)
+ rw [endval, curval]
+ exact rangeAt_skips L hist.length i j hj
+ have hhit : (i.val : Word w) < (ds row).endOffset := by
+ change ((i.val : Word w) : ℕ) < (ds row).endOffset.val
+ rw [endval, curval]
+ exact (rangeAt_bounds L hist.length i).2
+ have hs : (ds row).sourceBase + ((i.val : Word w) - prevEnd ds row) =
+ sourceAddress L hist.length src i := by
+ rw [prev_records, ← Nat.cast_sub (rangeAt_bounds L hist.length i).1]
+ rfl
+ obtain ⟨es,hr,hm,hh⟩ := row_native desc ds (i.val : Word w) m h.descriptors row hskip hhit
+ rw [hs, target_eq L hist.length base src fit i, h.sources i] at hm
+ exact ⟨es,hr,hm,hh⟩
+
+private theorem run_packed (fit : base + span L hist.length ≤ 2^w)
+ (hwidth : populated L hist.length < 2^w) (sep : Separated desc base L hist.length src fit)
+ (indices : List (Fin (populated L hist.length))) (start : ℕ)
+ (haligned : indices.map Fin.val = List.range' start indices.length)
+ {m : Memory w} (h : Prepared desc base L hdr hist src m) :
+ ∃ rs, runSegment (program desc) 64 (some (start : Word w)) m (List.replicate indices.length []) = some rs ∧
+ endState (some (start : Word w)) rs = some ((start + indices.length : ℕ) : Word w) ∧
+ after m (eventLog rs) = store (scratchAddress base fit) (fun j => headerMemory L hdr hist j.val)
+ (indices.map (sparseOffset L hist.length)) m ∧
+ rs.length = indices.length ∧ ∀ r ∈ rs, r.events.length < 64 ∧ countProbes r.events ≤ 11 ∧ choiceBits r.events = [] := by
+ induction indices generalizing start m with
+ | nil => exact ⟨[], rfl, rfl, rfl, rfl, by simp⟩
+ | cons i indices ih =>
+ simp only [List.map_cons, List.length_cons, List.range'_succ, List.cons.injEq] at haligned
+ obtain ⟨rfl,haligned⟩ := haligned
+ obtain ⟨es, hr, hm, hl, hp, hc⟩ := native_cell fit hwidth h i
+ have hprep : Prepared desc base L hdr hist src (after m es) := hm ▸ h.write sep i _
+ obtain ⟨rs, hn, hs, hu, hlen, hh⟩ := ih (i.val+1) haligned hprep
+ refine ⟨⟨es, some ((i.val : Word w)+1)⟩ :: rs, ?_, ?_, ?_, ?_, ?_⟩
+ · simp only [List.length_cons, List.replicate_succ, runSegment, hr, ← Nat.cast_one (R := Word w), ← Nat.cast_add]
+ rw [hn]
+ rfl
+ · simpa [endState, Nat.add_assoc, Nat.add_comm 1] using hs
+ · change after m (es ++ eventLog rs) = store _ _ _ (writeMemory m _ _)
+ rw [← hm]
+ simpa [after] using hu
+ · simp [hlen]
+ · intro r hmem
+ rcases List.mem_cons.mp hmem with rfl | hmem
+ · exact ⟨hl,hp,hc⟩
+ · exact hh r hmem
+
+/-- The compiled fixed dispatcher writes precisely the auxiliary header memory.
+The count of calls is the number of populated words. No call visits a reserved
+exterior padding slot. -/
+theorem sweep_native (fit : base + span L hist.length ≤ 2^w)
+ (hwidth : populated L hist.length < 2^w) (sep : Separated desc base L hist.length src fit)
+ {m : Memory w} (h : Prepared desc base L hdr hist src m) :
+ let n := populated L hist.length
+ ∃ rs, runSegment (program desc) 64 (some 0) m (List.replicate n []) = some rs ∧
+ endState (some 0) rs = some (n : Word w) ∧ after m (eventLog rs) = install base L hdr hist fit m ∧
+ rs.length = n ∧ ∀ r ∈ rs, r.events.length < 64 ∧ countProbes r.events ≤ 11 ∧ choiceBits r.events = [] := by
+ let n := populated L hist.length
+ have aligned : (List.finRange n).map Fin.val = List.range' 0 (List.finRange n).length := by
+ simp [List.range_eq_range']
+ have hr := run_packed fit hwidth sep (List.finRange n) 0 aligned h
+ simpa only [n, Nat.cast_zero, List.length_finRange, Nat.zero_add, store_packed_eq_install] using hr
+
+end LiveAuxiliaryHeaders
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaders.lean b/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaders.lean
new file mode 100644
index 0000000000..666c71150b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveAuxiliaryHeaders.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.LiveHeaderBits
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+
+/-!
+# Sparse initialization of the auxiliary pair counter
+
+The live group stores the prescribed §11 header in a separate area of its
+external memory. Only the cut lengths, index bits, advice bits, actual exterior
+bits and nominated histogram words are written. The two exterior fields use
+fixed capacities for addressing even when an endpoint has an empty cut.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveAuxiliaryHeaders
+
+open BurstRAM PrimedInputRAM
+
+variable {w : ℕ}
+
+/-- Offset of the first exterior field after the three lengths, indices and advice. -/
+def exteriorBase (L : Lengths) := 3 + 2 * L.index + L.advice
+
+/-- Reserved header prefix, including padding in both exterior fields. -/
+def span (L : Lengths) (labels : ℕ) := Header.count L + labels
+
+private def block {N : ℕ} (start len : ℕ) (fit : start + len ≤ N) : List (Fin N) :=
+ List.ofFn fun i : Fin len ↦ ⟨start + i.val, (Nat.add_lt_add_left i.isLt start).trans_le fit⟩
+
+private theorem mem_block {N start len : ℕ} (fit : start + len ≤ N) (i : Fin N) :
+ i ∈ block start len fit ↔ start ≤ i.val ∧ i.val < start + len := by
+ rw [block, List.mem_ofFn]
+ constructor
+ · rintro ⟨j, rfl⟩
+ have := j.isLt
+ change start ≤ start + j.val ∧ start + j.val < start + len
+ omega
+ · rintro ⟨h₁, h₂⟩
+ exact ⟨⟨i.val - start, by omega⟩, Fin.ext (by simp; omega)⟩
+
+/-- Physical offsets visited by the writer in ascending order. The first range
+also contains the populated part of the left exterior field. -/
+def cells (L : Lengths) (labels : ℕ) : List (Fin (span L labels)) :=
+ block 0 (exteriorBase L + L.leftCut) (by
+ have := L.leftFit; unfold exteriorBase span Header.count; omega) ++
+ block (exteriorBase L + L.cutCapacity) L.rightCut (by
+ have := L.rightFit; unfold exteriorBase span Header.count; omega) ++
+ block (Header.count L) labels (by rfl)
+
+/-- The write count uses the actual cut lengths, including at an empty endpoint. -/
+theorem cells_length (L : Lengths) (labels : ℕ) :
+ (cells L labels).length = exteriorBase L + L.leftCut + L.rightCut + labels := by
+ simp [cells, block, Nat.add_assoc]
+
+theorem mem_cells (L : Lengths) (labels : ℕ) (i : Fin (span L labels)) :
+ i ∈ cells L labels ↔ i.val < exteriorBase L + L.leftCut ∨
+ (exteriorBase L + L.cutCapacity ≤ i.val ∧
+ i.val < exteriorBase L + L.cutCapacity + L.rightCut) ∨ Header.count L ≤ i.val := by
+ have hi : i.val < Header.count L + labels := i.isLt
+ simp only [cells, List.mem_append, mem_block]
+ rw [mem_block (start := Header.count L) (len := labels) (N := span L labels) (by rfl) i]
+ omega
+
+theorem headerMemory_padding (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w))
+ (i : Fin (span L hist.length)) (hi : i ∉ cells L hist.length) :
+ headerMemory L hdr hist i.val = 0 := by
+ rw [mem_cells] at hi
+ simp only [exteriorBase] at hi
+ unfold headerMemory
+ dsimp only
+ split_ifs <;> first | rfl | omega
+
+theorem headerMemory_past_end (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w))
+ {i : ℕ} (hi : span L hist.length ≤ i) : headerMemory L hdr hist i = 0 := by
+ unfold span at hi
+ rw [show i = Header.count L + (i - Header.count L) by omega, headerMemory_hist,
+ List.getElem?_eq_none (by omega)]
+ rfl
+
+/-- Sparse writes into the live machine's separate area for the pair's headers. -/
+def install (base : ℕ) (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w))
+ (fit : base + span L hist.length ≤ 2 ^ w) (m : Memory w) : Memory w :=
+ store (scratchAddress base fit) (fun i ↦ headerMemory L hdr hist i.val) (cells L hist.length) m
+
+/-- All writes fall within the reserved prefix. In particular, separate live
+scratch addresses may already hold data. -/
+theorem install_outside (base : ℕ) (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w))
+ (fit : base + span L hist.length ≤ 2 ^ w) (m : Memory w) (a : ℕ)
+ (ha : a < base ∨ base + span L hist.length ≤ a) :
+ install base L hdr hist fit m a = m a := by
+ apply store_outside
+ intro i _h
+ have := i.isLt
+ change a ≠ base + i.val
+ omega
+
+/-- Reading a translated virtual address in a zero-initialized header area
+recovers the prescribed word. This includes all padding and unused sites. -/
+theorem install_read (base : ℕ) (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w))
+ (fit : base + span L hist.length ≤ 2 ^ w) (m : Memory w) (a : ℕ)
+ (hz : m (base + a) = 0) :
+ install base L hdr hist fit m (base + a) = headerMemory L hdr hist a := by
+ by_cases h : a < span L hist.length
+ · let i : Fin (span L hist.length) := ⟨a, h⟩
+ by_cases hi : i ∈ cells L hist.length
+ · exact store_at (scratchAddress base fit) (fun j ↦ headerMemory L hdr hist j.val) _ m hi
+ · change install base L hdr hist fit m (base + a) = headerMemory L hdr hist i.val
+ rw [headerMemory_padding _ _ _ _ hi, ← hz]
+ apply store_outside
+ intro j hj he
+ have hij : i = j := Fin.ext (Nat.add_left_cancel he)
+ exact hi (hij ▸ hj)
+ · rw [headerMemory_past_end _ _ _ (Nat.le_of_not_gt h),
+ install_outside _ _ _ _ _ _ _ (Or.inr (by omega)), hz]
+
+open BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+/-- Copy a full computed word at offset `state - pub 0` between the arrays
+at `pub 1` and `pub 2`. Used for cut lengths and histogram components. -/
+def copyWord : List (Op 8 3) :=
+ [.stateWord 0, .publicWord 1 0, .binary .sub 2 0 1, .publicWord 3 1, .binary .add 3 3 2,
+ .read 4 3, .publicWord 5 2, .binary .add 5 5 2, .write 5 4, .constant 6 1, .binary .add 7 0 6]
+
+/-- Each native word-copy call performs one read and one write and advances the
+persistent cursor without branching. -/
+theorem copyWord_native (pub : Fin 3 → Word w) (state : Word w) (m : Memory w) :
+ let offset := state - pub 0
+ let src := pub 1 + offset
+ let dst := pub 2 + offset
+ let machine := (template copyWord 7).instantiate w pub
+ ∃ es, execute machine.program 12 (machine.program.start state) m [] =
+ some ⟨es, some (state + 1)⟩ ∧
+ after m es = writeMemory m dst (m src.val) ∧ es.length = 11 ∧
+ countProbes es = 2 ∧ choiceBits es = [] := by
+ dsimp only
+ let src := pub 1 + (state - pub 0)
+ let dst := pub 2 + (state - pub 0)
+ let es : List (Event w) := [.tick, .tick, .tick, .tick, .tick, .read src (m src.val),
+ .tick, .tick, .write dst (m src.val), .tick, .tick]
+ refine ⟨es, ?_, rfl, rfl, rfl, rfl⟩
+ change execute ((template copyWord 7).instantiate w pub).program (1 + copyWord.length)
+ ⟨_, state, fun _ ↦ 0, fun _ ↦ 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]
+ simp (config := { decide := true }) [copyWord, trace, Op.effect, Function.update, es, src, dst,
+ show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.sub.eval = (· - · : Word w → Word w → Word w) from rfl]
+
+end LiveAuxiliaryHeaders
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveAuxiliaryStages.lean b/lean/OAI/Computability/VPVNP/LiveAuxiliaryStages.lean
new file mode 100644
index 0000000000..990ab5661e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveAuxiliaryStages.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.LiveAuxiliaryHeaderPreparation
+import OAI.Computability.VPVNP.LiveCountedStage
+import OAI.Computability.VPVNP.LiveHeaderBounded
+import OAI.Computability.VPVNP.LiveHeaderSchedule
+import OAI.Computability.VPVNP.LiveNominationSweep
+
+/-!
+# Stage tables for nomination and auxiliary header preparation
+
+The nomination stage accepts when the cursor reaches the public production-label
+count. The descriptor initializer accepts after one call. The copy stage uses the
+seventh descriptor's cumulative end, read from live scratch on each call. Both
+boundary checks have deterministic accepting exits on an empty choice stream.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveAuxiliaryStages
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+open LiveHeaderCopyDispatch
+open scoped Fin.CommRing
+
+/-- Run the nomination worker under a public production-label bound, accepting at the end of
+the label scan. -/
+def nomination := LiveHeaderBounded.bounded (LiveNominations.flow.template (some 7))
+
+/-- The one-call stage that creates the auxiliary header descriptor table. -/
+abbrev «initialize» := LiveAuxiliaryHeaders.initTable
+
+/-- The counted sparse-copy stage whose stopping bound is read from the last auxiliary
+descriptor. -/
+def copy := LiveCountedStage.counted (LiveHeaderCopyDispatch.flow.template (some 11)) true
+
+variable {w b : ℕ}
+
+/-- The nomination worker's public data extended with the label count used by its stage guard. -/
+def nominationData (b : ℕ) (base : Word w) (count : Word w) :=
+ LiveHeaderBounded.publicData (LiveNominations.data b base) count
+
+/-- The final packed end is field zero of the seventh descriptor. -/
+def copyData (table : Word w) :=
+ LiveCountedStage.publicData (fun _ : Fin 1 => table) (address table 6 0)
+
+/-- The output ranges produced by the preceding header recovery and nomination stages. -/
+def headerSources (s : LiveHeaderSchedule.Sizes) (headerBase : ℕ) (muBase : Word w) : Fin 7 → Word w :=
+ ![(LiveHeaderSchedule.widthAddr headerBase .primedLeft : Word w),
+ (LiveHeaderSchedule.leftIndexBase s headerBase : Word w),
+ (LiveHeaderSchedule.rightIndexBase s headerBase : Word w),
+ (LiveHeaderSchedule.adviceBase s headerBase : Word w),
+ (LiveHeaderSchedule.exteriorBase s headerBase .left : Word w),
+ (LiveHeaderSchedule.exteriorBase s headerBase .right : Word w), muBase]
+
+/-- The initializer's public input uses capacities and addresses only. The two
+exterior lengths that depend on the group are read from the first source array. -/
+def initializeData (index advice capacity labels : ℕ) (shadow table : Word w) (src : Fin 7 → Word w) :
+ Fin 14 → Word w :=
+ ![(index : Word w),(advice : Word w),(capacity : Word w),(labels : Word w),shadow,table,src 0,
+ src 0,src 1,src 2,src 3,src 4,src 5,src 6]
+
+theorem initializeData_eq (L : Lengths) (labels : ℕ) (shadow table : Word w) (src : Fin 7 → Word w) :
+ initializeData L.index L.advice L.cutCapacity labels shadow table src =
+ LiveAuxiliaryHeaders.initData L labels shadow table src := rfl
+
+theorem copy_endAddress (table : Word w) : address table 6 0 = table + 18 := by rfl
+
+/-- The component template and the cursor guard together consume the specified
+bits, preserving the stored value and the one-probe bound. -/
+theorem nomination_active (hb : b ≤ w) (base count state : Word w) (hs : state < count)
+ (m : Memory w) (v : Word b) :
+ let P := (nomination.instantiate w (nominationData b base count)).program
+ ∃ es, execute P (5*b+15) (P.start state) m (wordBits v) = some ⟨es, some (state+1)⟩ ∧
+ after m es = writeMemory m (base+state) (Fin.ofNat (2^w) v.val) ∧
+ es.length = 5*b+14 ∧ countProbes es = 1 ∧ choiceBits es = wordBits v := by
+ obtain ⟨es, he, hm, hl, hp, hc⟩ := LiveNominations.component_native hb base state m v
+ refine ⟨.tick :: .tick :: .tick :: es, ?_, hm, ?_, hp, hc⟩
+ · apply (LiveHeaderBounded.execute_active (LiveNominations.flow.template (some 7))
+ (LiveNominations.data b base) count (5*b+12) state hs m (wordBits v)).trans
+ change (execute (LiveNominations.program b base) _ ((LiveNominations.program b base).start state) _ _).map _ = _
+ rw [he]; rfl
+ · simp only [List.length_cons, hl]
+
+/-- The last nomination call transfers to descriptor initialization, including
+when the production-label count is zero. -/
+theorem nomination_closed (b fuel : ℕ) (base count state : Word w) (hs : count ≤ state)
+ (m : Memory w) (bits : List Bool) :
+ let P := (nomination.instantiate w (nominationData b base count)).program
+ execute P (fuel+4) (P.start state) m bits =
+ if bits = [] then some ⟨[.tick,.tick,.tick], none⟩ else none :=
+ LiveHeaderBounded.execute_closed _ _ count fuel state hs m bits
+
+/-- The copy wrapper performs one extra read of the cumulative end, then the
+dispatcher copies the selected word. -/
+theorem copy_active (table : Word w) (ds : Fin 7 → Descriptor w) (m : Memory w)
+ (ready : Spec table ds m) (state : Word w) (endFits : state < (ds 6).endOffset)
+ (i : Fin 7) (hskip : ∀ j < i, (ds j).endOffset ≤ state) (hhit : state < (ds i).endOffset) :
+ let P := (copy.instantiate w (copyData table)).program
+ let offset := state - prevEnd ds i
+ ∃ es, execute P 68 (P.start state) m [] = some ⟨es, some (state+1)⟩ ∧
+ after m es = writeMemory m ((ds i).targetBase + offset) (m ((ds i).sourceBase + offset).val) ∧
+ es.length < 68 ∧ countProbes es ≤ 12 ∧ choiceBits es = [] := by
+ let addr := address table 6 0
+ have ha : state < LiveCountedStage.limit true addr m := by
+ change state < m (address table 6 0).val
+ rw [ready.ends]
+ exact endFits
+ obtain ⟨es, he, hm, hl, hp, hc⟩ := row_native table ds state m ready i hskip hhit
+ refine ⟨LiveCountedStage.guardEvents true addr m ++ es, ?_, hm, ?_, ?_, hc⟩
+ · apply (LiveCountedStage.execute_active (LiveHeaderCopyDispatch.flow.template (some 11))
+ true (fun _ => table) addr 64 state m ha []).trans
+ change (execute (LiveHeaderCopyDispatch.program table) _ ((LiveHeaderCopyDispatch.program table).start state) _ _).map _ = _
+ rw [he]; rfl
+ · simp [LiveCountedStage.guardEvents]; omega
+ · change 1 + countProbes es ≤ 12
+ omega
+
+/-- The cursor at the end of the populated header accepts without touching
+the sparse virtual destinations. -/
+theorem copy_closed (table : Word w) (ds : Fin 7 → Descriptor w) (m : Memory w)
+ (ready : Spec table ds m) (fuel : ℕ) (state : Word w) (hs : (ds 6).endOffset ≤ state)
+ (bits : List Bool) :
+ let P := (copy.instantiate w (copyData table)).program
+ execute P (fuel+5) (P.start state) m bits =
+ if bits = [] then some ⟨LiveCountedStage.guardEvents true (address table 6 0) m, none⟩ else none :=
+ LiveCountedStage.execute_closed _ true _ (address table 6 0) fuel state m
+ (by change m (address table 6 0).val ≤ state; rw [ready.ends]; exact hs) bits
+
+end LiveAuxiliaryStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCertificateAssembly.lean b/lean/OAI/Computability/VPVNP/LiveCertificateAssembly.lean
new file mode 100644
index 0000000000..6786a030f0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCertificateAssembly.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.LiveVirtualPairs
+import OAI.Computability.VPVNP.LiveLocalGroupCount
+
+/-!
+# Assembling the certificate on the fixed live instruction table
+
+The live dispatcher uses lengths computed by public arithmetic; the
+diagonal theorem describes them by powers of n. The two continuation
+contracts below transport the same physical cuts between these length
+notations. The virtual coefficient counter and the evaluator consume
+the advice field of a single scalar model. Their path counts then fill
+the local certificate for the actual processor program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+open BurstRAM CutSchedule ChainAssignments ExponentTrace LiveEvaluatorEncoding
+open PairStages LocalCount
+
+variable {G : Group} {R H h Δ a t Z M : ℕ} (W : Conditions G R H)
+variable (hh : h = (profile G).h) (hΔ : Δ = (profile G).delta) (ha : a = (profile G).advice)
+variable (adv : Bits a) (fit : 1+t*Z ≤ Δ)
+
+section Pair
+variable {Nom : Type*} [Fintype Nom] {Path : Exterior h Δ → Fin (2^h) → Nom → Type*}
+ [∀ ξ i μ, Fintype (Path ξ i μ)]
+
+/-- The pair continuation on the mathematical lengths of the fixed program. -/
+def pairObligation (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ) : Prop := by
+ subst h
+ subst Δ
+ subst a
+ exact PairContinuation W adv fit inc
+
+end Pair
+
+/-- The tail continuation on the same lengths, advice and initial states. -/
+def tailObligation (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w Δ)
+ (init : (Fin t → ℕ) → Code G.evaluator.extra M) : Prop := by
+ subst h
+ subst Δ
+ subst a
+ exact TailContinuation W adv fit layout init
+
+variable {Nom : Type*} [Fintype Nom] {Path : Exterior h Δ → Fin (2^h) → Nom → Type*}
+ [∀ ξ i μ, Fintype (Path ξ i μ)] (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w Δ) (init : (Fin t → ℕ) → Code G.evaluator.extra M)
+
+theorem checked_group (he : (profile G).e = t*Z) (hc : (profile G).config = fieldWords M*G.w)
+ (pair : pairObligation W hh hΔ ha adv fit inc) (tail : tailObligation W hΔ ha adv fit layout init)
+ (cuts : AllCuts h Δ) (j : Fin (2^(h+1))) :
+ Nat.card (ActualPaths (machine G.constants G.evaluator G.pair G.g G.lit).program G.clock 0
+ (LiveHeader.physicalMemory (d := G.g.d) W.word adv cuts j) (withinCaps R H)) =
+ specifiedGroupCount fit inc G.evaluator layout init cuts j := by
+ subst h
+ subst Δ
+ subst a
+ exact LocalCount.group W adv fit inc layout init he hc pair tail cuts j
+
+end LiveProgram
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork LabelEvaluator BurstRAM LiveProgram CutSchedule ExponentTrace LiveEvaluatorEncoding
+open JointLabelSystem
+
+/-- Classical decidable equality for productions used when assembling a fixed program's
+certificate. -/
+noncomputable local instance (n C : ℕ) : DecidableEq (Production n C) := Classical.decEq _
+
+universe v
+variable {K : Type v} [Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) {n C : ℕ} (hn : 2 ≤ n)
+
+/-- Assemble the live stage group from the fixed evaluator, pair, geometry, literal prefix, and
+the clock n^10000. -/
+noncomputable def executionGroup (n : ℕ) (ht : 21 ≤ 2^(D.geometry n).w) (hf : 44 ≤ n^10000) : PairStages.Group :=
+ ⟨D.constants,D.evaluator,D.pair,D.geometry n,CounterPublic.actualPrefix D.literal,n^10000,ht,hf⟩
+
+/-- The physical metadata agrees with the certificate's six mathematical
+field lengths, including the complete evaluator word image. -/
+theorem profile_eq {ht hf} (hC : D.constants.circuitExponent = C)
+ (hg : D.constants.motifLabels = Fintype.card B.Entry) :
+ LocalCount.profile (D.executionGroup n ht hf) =
+ ⟨D.chainHeight n,n^D.constants.deltaPower,n^D.constants.advicePower,
+ B.denseCount n C * D.counterWidth n, fieldWords (n^D.constants.radiusPower) * (D.geometry n).w⟩ := by
+ unfold LocalCount.profile Header.sizes executionGroup Constants.lengths Lengths.eval
+ simp only [Constants.labels, eval_add, Constants.grammarLabels_eq, hg, hC,
+ Constants.height, Constants.Z, Constants.configWords, Constants.radius, eval_mul,
+ PublicExpr.eval_natPow, PublicExpr.eval, chainHeight, counterWidth, geometry]
+ rfl
+
+variable {D B hn} {p : Nat.Primes} {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M)
+ (processorFit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C)
+
+/-- The dense production exponents credited to a compressed path, computed from its motif
+counts and the selected nomination. -/
+noncomputable abbrev increments :=
+ let paths := V.pairData data processorFit
+ fun ξ i μ (q : paths.Path ξ i μ) => B.denseExponent (fun j => (μ j).val) (paths.ν ξ i μ q)
+
+variable {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+variable (W : LocalCount.Conditions (D.executionGroup n ht hf) (2^(D.geometry n).d) ((D.geometry n).H))
+variable (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+variable (cutFit : 1+B.denseCount n C * D.counterWidth n ≤ n^D.constants.deltaPower)
+variable (image : LiveEvaluatorTail.Layout D.evaluator.extra (n^D.constants.radiusPower) (D.geometry n).w
+ (n^D.constants.deltaPower))
+
+theorem heights : D.chainHeight n = (LocalCount.profile (D.executionGroup n ht hf)).h := by
+ change n^D.constants.chainPower-1 = (D.constants.lengths.eval (D.geometry n)).h
+ simp [Constants.lengths, Lengths.eval, Constants.height, PublicExpr.eval, geometry]
+
+theorem deltas : n^D.constants.deltaPower = (LocalCount.profile (D.executionGroup n ht hf)).delta := by
+ change _ = (D.constants.lengths.eval (D.geometry n)).delta
+ simp [Constants.lengths, Lengths.eval, PublicExpr.eval, geometry]
+
+theorem adviceSizes : n^D.constants.advicePower = (LocalCount.profile (D.executionGroup n ht hf)).advice := by
+ change _ = (D.constants.lengths.eval (D.geometry n)).advice
+ simp [Constants.lengths, Lengths.eval, PublicExpr.eval, geometry]
+
+/-- Construct the actual single-length certificate. Its only stage premises
+are the successful native pair and tail continuations on the selected
+compressed occurrence type and the selected evaluator input. -/
+noncomputable def assembleLocalCertificate (zero : D.initialLiteral = 0)
+ (hcap : 2^(D.geometry n).d * (D.geometry n).H < 2^(D.geometry n).w)
+ (hR : 4*n ≤ 2^(D.geometry n).d) (hZ : D.chainHeight n + 2*(D.geometry n).d ≤ D.counterWidth n)
+ (pair : pairObligation W heights deltas adviceSizes data.advice cutFit (increments data processorFit V))
+ (tail : tailObligation W deltas adviceSizes data.advice cutFit image data.init) :
+ D.Certificate B hn M processorFit where
+ hw := W.word
+ hc := hcap
+ hR := hR
+ hZ := hZ
+ advice := data.advice
+ fit := cutFit
+ layout := image
+ Path := (V.pairData data processorFit).Path
+ pathFintype := (V.pairData data processorFit).pathFintype
+ ν := (V.pairData data processorFit).ν
+ hν := (V.pairData data processorFit).bounded
+ hpair := (V.pairData data processorFit).weight
+ initial := D.initial n data.raw
+ init := data.init
+ hi := data.init_state
+ histories := data.histories
+ htail := data.value
+ group cuts j := by
+ have shape := profile_eq D B (ht := ht) (hf := hf) hC hg
+ have he := congrArg LiveHeaderSchedule.Sizes.e shape
+ have hc := congrArg LiveHeaderSchedule.Sizes.config shape
+ have h := checked_group W heights deltas adviceSizes data.advice cutFit (increments data processorFit V)
+ image data.init he hc pair tail cuts j
+ have hzero : Fin.ofNat (2^(D.geometry n).w) D.initialLiteral = 0 := by
+ rw [zero]
+ apply Fin.ext
+ simp
+ rw [hzero]
+ exact h
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairBlockClock.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairBlockClock.lean
new file mode 100644
index 0000000000..298a6aaf5c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairBlockClock.lean
@@ -0,0 +1,53 @@
+import OAI.Computability.VPVNP.CompressorBlockClock
+import OAI.Computability.VPVNP.CompressorWorkspaceCore
+import OAI.Computability.VPVNP.LiveCompressedPairOnlineRates
+
+/-! # The literal block clock on chronological source reports -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM Compression CursorBounds CursorNetwork CompressorRecords Filter
+open Schedule BranchSegments
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+local notation "scr" => BlockProgram.script B
+
+/-- The literal small source clock controls every chronological report.
+The total bound can have a different polylogarithmic exponent, including
+zero. Both estimates are used before adding the six workspace reads. -/
+theorem eventually_online_core_caps (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ (rate q link : ℕ) :
+ ∀ᶠ n : ℕ in atTop, let w := wordBits b n
+ let small := BlockClock.small B b n
+ small+link ≤ n ∧ (∀ cap, small ≤ cap → Online.Run.ControlBounds (scr).plan cap (w := w)) ∧
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 publicWords G
+local notation "fuel₀" => fuel G
+local notation "start" => cursorStartupLogs b ports B n base m initial phases d
+local notation "entry" => after m (eventLog start)
+local notation "table₀" => terminalBody shape limit segments
+
+variable {Z : Type*} {R : Type*} [CommRing R] {L : Type} [Fintype L] {κ : L → R} {net : Z → Network}
+ {arc : (z : Z) → ScanPhase (net z)} {sites : (z : Z) → SiteParsers κ (net z)}
+ (descriptor : Z ≃ StagePaths b plan (terminalBody shape limit segments) (publicWords G) (fuel G) Stage.online
+ (after m (eventLog (cursorStartupLogs b (publicWords G) B n base m initial phases d))))
+ (branches : ∀ z, TerminalBranch (G := G) (B := B) (n := n) (base := base) (m := m)
+ (b := b) (plan := plan) (shape := shape) (limit := limit) (segments := segments) descriptor (arc z) (sites z) z)
+
+/-- The actual five-phase trace selected by a terminal wire and vertex assignment. -/
+noncomputable abbrev TerminalBranchData.chosenTrace {w : ℕ} {workers : TerminalLink.Stage → PairTable}
+ {pub : Fin 11 → Word w} {cap : ℕ} {mem : Memory w} {N : Network} {sc : ScanPhase N}
+ {P : SiteParsers κ N} (s : TerminalBranchData workers pub cap mem sc P) (x : TerminalData sc P) :=
+ s.setup.trace (s.bitPaths x.arcs) (s.vertexPaths x.arcs x.choices)
+
+/-- The resource field consumed by the live group uses the actual reports of
+its descriptor, wire assignment and terminal witnesses. The only dynamic
+charges are the source calendar rows and the individual native vertex calls. -/
+theorem branchReports_caps (z : Z) (x : TerminalData (arc z) (sites z))
+ (X : State a g) (Y : State a' g') (chain : TermChain R X.network Y.network)
+ (R₀ H steps T site q bootBound : ℕ) (hR : 128 ≤ R₀) (hH : 16 ≤ H) (clock : 136 ≤ fuel₀)
+ (startup : StartupResult b plan table₀ ports B n base m fuel₀)
+ (burst : ∀ i, sourceFuel b initial phases n i+5 ≤ H) (privateRoom : ∀ i, sourceFuel b initial phases n i+77 ≤ fuel₀)
+ (online : List (Report G.w)) (source : ordinaryReports (descriptor z) = OnlineWorkspace.framed (ports 2) entry online)
+ (onlineRow : ∀ r ∈ online, r.probes+11 ≤ H ∧ r.events.length+101 ≤ fuel₀)
+ (onlineTotal : 64*RAMBuckets.cost Report.probes online ≤ R₀*H)
+ (prelude : PreludeCosts X Y ports ((branches z).chosenTrace x) steps limit T bootBound)
+ (bootCap : bootBound+9 ≤ H ∧ bootBound+107 ≤ fuel₀)
+ (arenaCap : TraversalController.callFuel limit+9 ≤ H ∧ TraversalController.callFuel limit+107 ≤ fuel₀)
+ (bitMemory last : Memory G.w) (bits : Fin Y.totalWidth → Bool)
+ (bitRows : ((branches z).chosenTrace x).sharedBits.logs.map Prod.snd = FinalBits.Worker.reports ports 0 bitMemory bits)
+ (vertex : Y.network.Site → Report G.w)
+ (vertexRows : ((branches z).chosenTrace x).vertices.logs.map Prod.snd = (List.ofFn fun i => vertex ((siteOrder Y).entries i)) ++
+ [VertexImage.closingReport ports last])
+ (hq : 1 ≤ q) (hT : T ≤ n.log2+1)
+ (siteRow : ∀ v, 1+(vertex v).probes ≤ siteAccesses Y chain site q n v ∧ (vertex v).events.length+107 ≤ fuel₀)
+ (allSites : ∀ v, siteAccesses Y chain site q n v+9 ≤ H)
+ (share : 320*branchAccesses X Y chain (terminalCoefficient (2^a') steps limit bootBound 1 site) q n ≤ R₀*H) :
+ let rs := start ++ (onlineReports (descriptor z) ++
+ (TerminalLink.reports (TerminalLink.header ports) ((branches z).chosenTrace x).logs).map (report ports Stage.terminal))
+ (∀ r ∈ rs, r.events.length+4 ≤ fuel₀) ∧ 4*RAMBuckets.cost Report.probes rs ≤ R₀*H ∧
+ ∀ r ∈ rs, 3+r.probes ≤ H := by
+ intro rs
+ have bootProbes := (probes_le_length prelude.boot.events).trans prelude.bootWork
+ have closeProbes : (VertexImage.closingReport ports last).probes = 1 := rfl
+ have closeWork : (VertexImage.closingReport ports last).events.length = 14 := rfl
+ have clocked := five_execution_caps X Y chain ports b B n base m initial phases d (ports 2) entry online
+ ((branches z).chosenTrace x) R₀ H fuel₀ hR hH clock startup.sourceCost burst privateRoom onlineRow onlineTotal
+ prelude.boot (VertexImage.closingReport ports last) bootBound 1 prelude.initialRow
+ ⟨bootProbes, (Nat.add_le_add_right bootProbes _).trans bootCap.1,
+ (Nat.add_le_add_right prelude.bootWork _).trans bootCap.2⟩
+ ⟨closeProbes.le, by omega, by omega⟩ prelude.scan steps limit T prelude.arenaTotal
+ (fun r hr => by obtain ⟨p,t⟩ := prelude.arenaRow r hr; omega)
+ bitMemory bits bitRows vertex vertexRows site q hq hT siteRow allSites share
+ dsimp only [rs,onlineReports]
+ rw [source]
+ exact clocked
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairClockBundle.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairClockBundle.lean
new file mode 100644
index 0000000000..de40d0c9c5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairClockBundle.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.CompressorChronologicalRate
+import OAI.Computability.VPVNP.LiveCompressedPairBlockClock
+import OAI.Computability.VPVNP.LiveCompressedPairSourceCaps
+import OAI.Computability.VPVNP.PairTraversalControllerSelectedRun
+import OAI.Computability.VPVNP.PairTraversalTerminalBootstrap
+
+/-! # Simultaneous clocks for a selected physical compression branch -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM Compression CursorNetwork CursorBounds CompressorRecords Schedule Filter PairSimulation
+open ScheduledTrace BranchSegments PairSimulation.LocalHistory
+
+universe v
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+local notation "scr" => BlockProgram.script B
+local notation "bootBound" => TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit + 1
+local notation "arena" => TraversalController.callFuel B.recordLimit
+
+/-- One length supplies the private clocks and live bucket shares used by
+the fixed program. Every mathematical choice and native report is quantified
+inside the bounds at this length. -/
+structure BranchClocks (u : PairExponents B.growthConstant) (b : ℕ) (bs : Bootstrap)
+ (initial phases raw site q link n : ℕ) : Prop where
+ n2048 : 2048 ≤ n
+ processors : 128 ≤ processorCount b n
+ capacity : 16 ≤ liveCapacity u n
+ blocks : blockCount (u.θ : ℝ) n ≤ n.log2+1
+ privateRoom : ∀ G : PairStages.Group, G.clock = n^10000 → n^9999+107 ≤ G.clockAt LiveProgram.Stage.pair
+ startBurst : ∀ i, sourceFuel bs initial phases n i + 5 ≤ liveCapacity u n
+ startTicks : ∀ i, sourceFuel bs initial phases n i + 77 ≤ n
+ bootBurst : bootBound + 9 ≤ liveCapacity u n
+ bootTicks : bootBound + 107 ≤ n
+ arenaBurst : arena + 9 ≤ liveCapacity u n
+ arenaTicks : arena + 107 ≤ n
+ sourceClock : BlockClock.small B b n + link ≤ n
+ controls : ∀ cap, BlockClock.small B b n ≤ cap → Online.Run.ControlBounds (scr).plan cap (w := wordBits b n)
+ online : ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (pub : Fin 11 → Word (wordBits b n)) {st : Option (Word (wordBits b n))} {m : Memory (wordBits b n)} {clock : ℕ}
+ (segment : Segment (OnlineWorkspace.program (scr).plan pub) clock st m)
+ (source : OnlineWorkspace.Core scr pub segment (BlockClock.small B b n)),
+ RAMBuckets.cost Report.probes source.logs ≤ chronologicalRate B raw*(pairInput S labels hD).positions*(n.log2+1) →
+ 64*RAMBuckets.cost Report.probes source.logs ≤ processorCount b n*liveCapacity u n ∧
+ ∀ r ∈ source.logs, r.probes+11 ≤ liveCapacity u n ∧ r.events.length+101 ≤ n
+ terminal : ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n*S.laneBits ≤ lanes) (A : Type v) [CommRing A] (f : B.Entry → A)
+ (hf : B.IsSolution f), let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ ∀ z : E.Choices, let Y := E.finalState z
+ let chain := E.termChain (B.records f hf T hT X) z
+ 320*branchAccesses X Y chain (terminalCoefficient S.baseDegree S.steps B.recordLimit bootBound 1 site) q n ≤
+ processorCount b n*liveCapacity u n ∧ ∀ v, siteAccesses Y chain site q n v+9 ≤ liveCapacity u n
+
+/-- Fix the script, address exponent, pass charge and vertex charge first.
+The resulting threshold works for every finite model and each of its branches. -/
+theorem eventually_branchClocks (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ (bs : Bootstrap) (initial phases raw site q link : ℕ) :
+ ∀ᶠ n : ℕ in atTop, BranchClocks.{v} B u b bs initial phases raw site q link n := by
+ let K := max (bootBound) (arena)
+ filter_upwards [eventually_online_core_caps B u b hb (chronologicalRate B raw) 1 link,
+ eventually_terminal_share B u b hb (bootBound) 1 site q, eventually_startup_burst u bs initial phases 5,
+ eventually_sourceFuel bs initial phases 77, eventually_liveCapacity_ge u (K+16),
+ eventually_numeric B u b 1 hb (by decide), eventually_ge_atTop (K+107),
+ eventually_ge_atTop 2048] with n online terminal burst ticks hH numeric hK hn
+ have bootK : (bootBound) ≤ K := le_max_left ..
+ have arenaK : (arena) ≤ K := le_max_right ..
+ refine ⟨hn,by have := numeric.2.2.1; omega,by omega,terminal.1,
+ fun G hc => private_clock_room G (by omega) hc,burst,ticks,by omega,by omega,by omega,by omega,
+ online.1,online.2.1,?_,terminal.2⟩
+ intro base lanes labels hD pub st m clock segment source bound
+ exact online.2.2 labels hD pub segment source (by simpa only [pow_one] using bound)
+
+namespace BranchClocks
+
+set_option exponentiation.threshold 10000
+
+attribute [local irreducible] BlockProgram.script BlockClock.small CursorNetwork.cursorState
+set_option maxHeartbeats 1200000
+
+variable {B} {u : PairExponents B.growthConstant} {b : ℕ} {bs : Bootstrap}
+variable {initial phases raw site q link n : ℕ}
+variable (h : BranchClocks.{v} B u b bs initial phases raw site q link n)
+include h
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "P" => initialPositions b n
+
+/-- Convert the fixed-length ceilings to the actual private clock in the
+physical group. This also gives room for every active site's private bound. -/
+theorem groupCaps (G : PairStages.Group) (clock : G.clock = n^10000) :
+ let fuel := G.clockAt LiveProgram.Stage.pair
+ n ≤ fuel ∧ 136 ≤ fuel ∧ n^45 ≤ fuel ∧
+ (∀ i, sourceFuel bs initial phases n i+77 ≤ fuel) ∧
+ (bootBound+9 ≤ liveCapacity u n ∧ bootBound+107 ≤ fuel) ∧
+ (arena+9 ≤ liveCapacity u n ∧ arena+107 ≤ fuel) := by
+ intro fuel
+ have hn := h.n2048
+ have big := h.privateRoom G clock
+ change n^9999+107 ≤ fuel at big
+ have pos : 0 < n := by omega
+ have lt : n ≤ n^9999 := by simpa only [pow_one] using Nat.pow_le_pow_right pos (by decide : 1 ≤ 9999)
+ have room : n^9999 ≤ fuel := (Nat.le_add_right _ 107).trans big
+ have fit : n ≤ fuel := lt.trans room
+ have active : n^45 ≤ n^9999 := Nat.pow_le_pow_right pos (by decide : 45 ≤ 9999)
+ exact ⟨fit,(by decide : 136 ≤ 2048).trans (hn.trans fit),active.trans room,fun i => (h.startTicks i).trans fit,
+ ⟨h.bootBurst,h.bootTicks.trans fit⟩,h.arenaBurst,h.arenaTicks.trans fit⟩
+
+variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f}
+variable {a g a' g' : ℕ} {X : State a g} {E : StateExecution R a' g' X}
+variable {origin : PassOrigins B f hf E} {W : E.MapWitnesses f} {readers : ExecutionReaders E W}
+variable {resident : Resident B f hf (wordBits b n)} {past : List (SelectedLevel B f hf)}
+variable {pub : Fin 11 → Word (wordBits b n)} {pitch : Word (wordBits b n)} {m : Memory (wordBits b n)} {cap total : ℕ}
+
+/-- Specialize the two online bounds to the actual initial interval and
+scheduled result, using the startup estimate returned by descriptor execution.
+The numbering of the cursor's input positions is immaterial here. -/
+theorem selectedOnline {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n)
+ (start : QuietInterval scr pub cap (BlockClock.small B b n) (some 0) m)
+ (first : RAMBuckets.cost Report.probes start.source.logs ≤ initialRate B*(P+1))
+ (result : Result resident pub pitch total cap (BlockClock.small B b n)
+ (T*(S.steps+1)*(nativePassRate scr raw*P)+4) E origin W readers past start.segment.state start.segment.memory)
+ (G : PairStages.Group) (clock : G.clock = n^10000) (z : E.Choices) :
+ let core := start.combinedCore result.trace result.source z
+ 64*RAMBuckets.cost Report.probes core.logs ≤ processorCount b n*liveCapacity u n ∧
+ ∀ r ∈ core.logs, r.probes+11 ≤ liveCapacity u n ∧ r.events.length+101 ≤ G.clockAt LiveProgram.Stage.pair := by
+ intro core
+ have positions := pairInput_positions S labels hD
+ have pos := (pairInput S labels hD).positions_pos
+ rw [positions] at pos
+ have cost := h.online labels hD pub _ core (by
+ rw [positions]
+ change RAMBuckets.cost Report.probes (start.combinedCore result.trace result.source z).logs ≤ _
+ rw [start.combinedCost]
+ exact (Nat.add_le_add first (result.cost z)).trans (by
+ simpa only [Nat.add_assoc] using chronological_charge B raw P T n pos h.blocks))
+ have fit := (h.groupCaps G clock).1
+ exact ⟨cost.1,fun r hr => ⟨(cost.2 r hr).1,(cost.2 r hr).2.trans fit⟩⟩
+
+end BranchClocks
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairCursorStartup.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairCursorStartup.lean
new file mode 100644
index 0000000000..c40da20b29
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairCursorStartup.lean
@@ -0,0 +1,274 @@
+import OAI.Computability.VPVNP.LiveProgramCompressedPair
+import OAI.Computability.VPVNP.CompressorTransferredStartup
+import OAI.Computability.VPVNP.LiveStageSegments
+
+/-!
+# Executing the compressed pair's native startup stages
+
+Each initializer reads the memory left by the preceding linked call, including
+the enclosing stage tag. A successful initializer hands off at cursor zero.
+Their concatenation gives the deterministic prefix of every accepting pair
+path and the actual memory passed to the online descriptor calendar.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Concatenate a fixed number of verified calls whose persistent return is zero. -/
+private theorem calls {Q : Type*} (P : BurstRAM.Program w Q) (cap k : ℕ)
+ (entry : Fin (k+1) → Memory w) (rs : Fin k → Report w)
+ (run : ∀ i, execute P cap (P.start 0) (entry i.castSucc) [] = some (rs i))
+ (state : ∀ i, (rs i).result = some 0)
+ (memory : ∀ i, after (entry i.castSucc) (rs i).events = entry i.succ) :
+ runSegment P cap (some 0) (entry 0) (List.replicate k []) = some (List.ofFn rs) ∧
+ endState (some 0) (List.ofFn rs) = some 0 ∧
+ after (entry 0) (eventLog (List.ofFn rs)) = entry (Fin.last k) := by
+ induction k with
+ | zero => simp [runSegment, endState, eventLog, after]
+ | succ k ih =>
+ obtain ⟨rt, st, mt⟩ := ih (fun j => entry j.succ) (fun i => rs i.succ)
+ (fun i => run i.succ) (fun i => state i.succ) (fun i => memory i.succ)
+ have r0 := run 0
+ have m0 := memory 0
+ change execute P cap (P.start 0) (entry 0) [] = some (rs 0) at r0
+ change after (entry 0) (rs 0).events = entry (0 : Fin (k+1)).succ at m0
+ rw [List.ofFn_succ, List.replicate_succ, runSegment, r0]
+ simp only [state, m0, rt, Option.map_some, endState, st, true_and]
+ change after (entry 0) ((rs 0).events ++ eventLog _) = _
+ rw [show ∀ m : Memory w, ∀ es fs, after m (es++fs) = after (after m es) fs from
+ fun _ _ _ => List.foldl_append, m0]
+ exact mt
+
+variable {d initial phases : ℕ} {C : Catalog d} (b : Bootstrap)
+ (plan : Online.Config C initial phases) (terminal : PairTable) (pub : Fin 11 → Word w)
+
+/-- Link a sequence of accepting component calls on its actual successive
+memories. Each handoff returns cursor zero and installs the destination tag.
+The probe count includes both the tag lookup and the transfer. -/
+theorem linked_startup {k : ℕ} (stage : Fin (k+1) → Stage)
+ (source : Fin k → Report w) (fuel : Fin k → ℕ) (entry : Fin (k+1) → Memory w)
+ (cap : ℕ) (fit : 10 ≤ 2^w) (clock : ∀ i, fuel i+30 ≤ cap)
+ (step : ∀ i : Fin k, next (stage i.castSucc) = some (stage i.succ))
+ (tag : ∀ i : Fin k, entry i.castSucc (PairTag.address pub).val = LiveStageLink.tagWord w (stage i.castSucc))
+ (closed : ∀ i, (source i).result = none)
+ (run : ∀ i, let S := original b plan terminal pub (stage i.castSucc)
+ execute S (fuel i) (S.start 0) (entry i.castSucc) [] = some (source i))
+ (transfer : ∀ i, writeMemory (after (entry i.castSucc) (source i).events)
+ (PairTag.address pub) (LiveStageLink.tagWord w (stage i.succ)) = entry i.succ) :
+ let rs := fun i : Fin k => report pub (stage i.castSucc) (source i)
+ runSegment (program b plan terminal pub) cap (some 0) (entry 0) (List.replicate k []) =
+ some (List.ofFn rs) ∧ endState (some 0) (List.ofFn rs) = some 0 ∧
+ after (entry 0) (eventLog (List.ofFn rs)) = entry (Fin.last k) ∧
+ branchPaths (List.ofFn rs) = List.replicate k [] ∧
+ ∀ i, (rs i).probes = (source i).probes+2 ∧ (rs i).events.length ≤ (source i).events.length+30 := by
+ intro rs
+ have run' (i : Fin k) := execute_stage b plan terminal pub (stage i.castSucc) fit
+ (fuel i) cap (clock i) 0 (entry i.castSucc) (tag i) [] (source i) (run i)
+ have state (i : Fin k) : (rs i).result = some 0 := by
+ change (LiveStageLink.linkedReport next (PairTag.address pub) (stage i.castSucc) (source i)).result = _
+ rw [LiveStageLink.linkedReport_result, closed i, step i]
+ rfl
+ have effects (i : Fin k) := report_effect pub (stage i.castSucc) (source i) (entry i.castSucc)
+ have hm (i : Fin k) : after (entry i.castSucc) (rs i).events = entry i.succ := by
+ have h := (effects i).2.2.2
+ rw [closed i, step i] at h
+ exact h.trans (transfer i)
+ obtain ⟨hr, hs, he⟩ := calls (program b plan terminal pub) cap k entry rs run' state hm
+ refine ⟨hr, hs, he, (runSegment_iff ..).mp hr |>.2.2, fun i => ?_⟩
+ have hp := (effects i).2.1
+ rw [closed i, step i] at hp
+ exact ⟨hp, (effects i).2.2.1⟩
+
+/-- Instruction caps of the eight source calls, in their actual stage order. -/
+def sourceFuel (b : Bootstrap) (initial phases n : ℕ) : Fin 8 → ℕ :=
+ ![CalendarRows.ticks (OnlineWorkspace.rowsSpec initial phases b.numerator b.denominator) n + 2,
+ (DescriptorParameters.raw b.shape b.degreeBits initial phases b.lanesPerBlock).recipe.code.length+1,
+ VirtualParameters.ticks n+43+4*17, (DescriptorParameters.copy b.shape).recipe.code.length+1,
+ 1+DescriptorStride.cost b.shape, 1+HistoryArenaBase.cost b.shape initial phases b.steps, 42, 6]
+
+private theorem clock_bound (D : CalendarRows.Spec) (fixed extra n : ℕ) :
+ max (CalendarRows.ticks D n + 2) (max (VirtualParameters.ticks n+43+4*17) fixed) + extra ≤
+ (142+6*D.p+fixed+extra)*(n.log2+1) := by
+ have count := CalendarRows.ticks_le D n
+ have virtual := VirtualParameters.ticks_le n
+ have small := clog_le_log2_succ n
+ have a : Nat.clog 2 n * D.p ≤ (n.log2+1) * D.p := Nat.mul_le_mul_right _ small
+ simp only [Nat.add_mul, Nat.one_mul] at a
+ rw [← max_add_add_right, ← max_add_add_right]
+ apply max_le _ (max_le _ _)
+ all_goals nlinarith
+/-- Every startup cap is bounded by a fixed multiple of the logarithm of the
+input length, uniformly in the selected stage and in the group. -/
+theorem sourceFuel_log (b : Bootstrap) (initial phases extra : ℕ) :
+ ∃ K, ∀ n (i : Fin 8), sourceFuel b initial phases n i + extra ≤ K*(n.log2+1) := by
+ let D := OnlineWorkspace.rowsSpec initial phases b.numerator b.denominator
+ let fixed := max ((DescriptorParameters.raw b.shape b.degreeBits initial phases b.lanesPerBlock).recipe.code.length+1)
+ (max ((DescriptorParameters.copy b.shape).recipe.code.length+1)
+ (max (1+DescriptorStride.cost b.shape) (max (1+HistoryArenaBase.cost b.shape initial phases b.steps) 42)))
+ refine ⟨142+6*D.p+fixed+extra, fun n i => ?_⟩
+ apply le_trans _ (clock_bound D fixed extra n)
+ dsimp only [fixed]
+ fin_cases i
+ · change CalendarRows.ticks D n+2+extra ≤ _
+ omega
+ · change (DescriptorParameters.raw b.shape b.degreeBits initial phases b.lanesPerBlock).recipe.code.length+1+extra ≤ _
+ omega
+ · change VirtualParameters.ticks n+43+4*17+extra ≤ _
+ omega
+ · change (DescriptorParameters.copy b.shape).recipe.code.length+1+extra ≤ _
+ omega
+ · change 1+DescriptorStride.cost b.shape+extra ≤ _
+ omega
+ · change 1+HistoryArenaBase.cost b.shape initial phases b.steps+extra ≤ _
+ omega
+ · change 42+extra ≤ _
+ omega
+ · change 6+extra ≤ _
+ omega
+
+/-- The linked prefix fits the private clock for every sufficiently large input. -/
+theorem eventually_sourceFuel (b : Bootstrap) (initial phases extra : ℕ) :
+ ∀ᶠ n : ℕ in Filter.atTop, ∀ i : Fin 8, sourceFuel b initial phases n i + extra ≤ n := by
+ obtain ⟨K, hk⟩ := sourceFuel_log b initial phases extra
+ filter_upwards [eventually_polylog_le K 1] with n h
+ exact fun i => (hk n i).trans (by simpa only [pow_one] using h)
+
+private theorem probes_le_length (es : List (Event w)) : countProbes es ≤ es.length := by
+ induction es with
+ | nil => rfl
+ | cons e es ih => cases e <;> simp only [countProbes, List.length_cons] <;> omega
+
+/-- The startup specification for the initial rows and repeated block phases using the
+bootstrap's block ratio. -/
+abbrev bootstrapRows (b : Bootstrap) (initial phases : ℕ) :=
+ OnlineWorkspace.rowsSpec initial phases b.numerator b.denominator
+
+/-- The cursor workspace layout with its directory sized to the exact calendar row count for
+this input. -/
+noncomputable def startupLayout (b : Bootstrap) (initial phases B n base : ℕ) :=
+ LevelFields.tightDirectory (DescriptorSpace.cursorLayout b.shape B b.steps
+ ((b.numerator : ℝ)/b.denominator) base n) (CalendarRows.rows (bootstrapRows b initial phases) n)
+
+private def startupStage (i : Fin 9) : Stage := i.castLE (by decide)
+
+variable (B n base : ℕ) (m : Memory w)
+
+/-- The eight transferred initializer calls on the pair's actual tag, public operands, and
+input memory. -/
+noncomputable abbrev startupTrace (initial phases d : ℕ) := TransferredStartup.trace
+ (bootstrapRows b initial phases) d (startupLayout b initial phases B n base) B n
+ b.degreeBits b.lanesPerBlock b.steps pub (PairTag.address pub) m
+
+/-- Wrap one initializer's source report with the dispatch and transfer events for its linked
+startup stage. -/
+noncomputable def startupReport (initial phases d : ℕ) (i : Fin 8) : Report w :=
+ report pub (startupStage i.castSucc) ((startupTrace b pub B n base m initial phases d).source i)
+
+/-- The eight linked startup reports in call order, whose combined effects supply the online
+calendar's entry memory. -/
+noncomputable abbrev cursorStartupLogs (initial phases d : ℕ) :=
+ List.ofFn (startupReport b pub B n base m initial phases d)
+
+/-- The original reports with the stage labels used by the live group's
+resource accounting. -/
+noncomputable def cursorStartupSources (initial phases d : ℕ) : List (Stage × Report w) :=
+ List.ofFn fun i : Fin 8 =>
+ (startupStage i.castSucc, (startupTrace b pub B n base m initial phases d).source i)
+
+theorem cursorStartupLogs_eq (initial phases d : ℕ) :
+ cursorStartupLogs b pub B n base m initial phases d =
+ (cursorStartupSources b pub B n base m initial phases d).map (fun p => report pub p.1 p.2) := by
+ rw [cursorStartupSources, List.map_ofFn]
+ rfl
+
+local notation "D" => bootstrapRows b initial phases
+local notation "L" => startupLayout b initial phases B n base
+local notation "logs" => cursorStartupLogs b pub B n base m initial phases d
+local notation "out" => after m (eventLog logs)
+
+/-- Observable state at the boundary between the bootstrap and online calls. -/
+structure StartupResult (cap : ℕ) : Prop where
+ executed : runSegment (program b plan terminal pub) cap (some 0) m (List.replicate 8 []) = some logs
+ cursor : endState (some 0) logs = some 0
+ choices : branchPaths logs = List.replicate 8 []
+ tagged : out (PairTag.address pub).val = 8
+ ready : OnlineWorkspace.Ready d (arity C) (pub 2) (CalendarRows.rows D n) (DescriptorSpace.levelWords L) out
+ saved : Frame.data (DescriptorParameters.saved L w) out = DescriptorParameters.outputs L B n
+ b.degreeBits (roundedDown b.numerator b.denominator n*b.lanesPerBlock) w
+ arena : (out (DescriptorSpace.levelStart L 0+14)).val = DescriptorSpace.endAddress L
+ levels : (out (DescriptorSpace.levelStart L 0+28)).val = (L).levels
+ length : (out (DescriptorSpace.levelStart L 0+29)).val = n
+ cost : ∀ i, let r := startupReport b pub B n base m initial phases d i
+ r.probes+1 ≤ sourceFuel b initial phases n i+30 ∧ r.events.length+1 ≤ sourceFuel b initial phases n i+30
+
+ sourceCost : ∀ p ∈ cursorStartupSources b pub B n base m initial phases d, ∃ i : Fin 8,
+ p.2.probes < sourceFuel b initial phases n i ∧ p.2.events.length < sourceFuel b initial phases n i
+
+/-- The eight concrete components reach the online tag on the same memory
+that holds the saved cursor geometry and history-arena bounds. -/
+theorem cursor_startup (cap : ℕ) (arityEq : b.shape.arity = arity C) (fit : 10 ≤ 2^w)
+ (clock : ∀ i : Fin 8, sourceFuel b initial phases n i+30 ≤ cap)
+ (initialTag : m (PairTag.address pub).val = 0)
+ (runs : TransferredStartup.Runs D d L B n b.degreeBits b.lanesPerBlock b.steps pub (PairTag.address pub) m)
+ (hn : n < 2^w) (hs : 30 ≤ b.shape.scalarFields) (alloc : DescriptorSpace.endAddress L < 2^w) :
+ StartupResult b plan terminal pub B n base m cap := by
+ let t := startupTrace b pub B n base m initial phases d
+ let tag := PairTag.address pub
+ have run (i : Fin 8) : let S := original b plan terminal pub (startupStage i.castSucc)
+ execute S (sourceFuel b initial phases n i) (S.start 0) (t.entry tag m i.castSucc) [] = some (t.source i) := by
+ fin_cases i
+ · exact runs.frame.callRow
+ · exact runs.frame.callRaw
+ · exact runs.frame.callLoad
+ · exact runs.frame.callCopy
+ · exact runs.calendar.callStride
+ · exact runs.calendar.callArena
+ · have h := runs.calendar.callBank
+ change OnlineCursorStartup.Call (Workspace.initTable b.shape.arity) pub 42 0
+ (t.entry tag m 6) (t.source 6) at h
+ rw [arityEq] at h
+ exact h
+ · exact runs.calendar.callArm
+ have tagged (i : Fin 9) : t.entry tag m i tag.val = LiveStageLink.tagWord w (startupStage i) := by
+ cases i using Fin.cases with
+ | zero => exact initialTag
+ | succ j => rw [t.transfer]; exact ite_eq_left rfl
+ have steps (i : Fin 8) : next (startupStage i.castSucc) = some (startupStage i.succ) := by
+ have h : (startupStage i.castSucc).val+1 < 10 := by change i.val+1 < 10; omega
+ exact dite_eq_left h
+ obtain ⟨hr,hc,hm,hb,cost⟩ := linked_startup b plan terminal pub startupStage t.source
+ (sourceFuel b initial phases n) (t.entry tag m) cap fit clock steps
+ (fun i => tagged i.castSucc) (fun i => TransferredStartup.source_closed D d L B n b.degreeBits b.lanesPerBlock b.steps pub tag m i) run
+ (fun i => (t.transfer tag m i).symm)
+ change out = t.entry tag m (Fin.last 8) at hm
+ have positive : 0 < (L).levels := Nat.add_pos_left (by decide : 0 < 1) _
+ obtain ⟨ready, saved, arena, levels, len, tagged'⟩ := runs.output hn positive hs alloc
+ change OnlineWorkspace.Ready d b.shape.arity _ _ _ _ at ready
+ rw [arityEq] at ready
+ have sourceBudget (i : Fin 8) : (t.source i).events.length < sourceFuel b initial phases n i :=
+ (BurstRAM.execute_spec (run i)).1.length_lt
+ refine ⟨hr,hc,hb,hm ▸ tagged',hm ▸ ready,hm ▸ saved,hm ▸ arena,hm ▸ levels,hm ▸ len,?_,?_⟩
+ · intro i
+ obtain ⟨hp,hl⟩ := cost i
+ dsimp only at hp hl
+ have probes : (t.source i).probes ≤ (t.source i).events.length := probes_le_length _
+ have budget := sourceBudget i
+ change (report pub _ (t.source i)).probes+1 ≤ _ ∧ (report pub _ (t.source i)).events.length+1 ≤ _
+ omega
+ · intro p hp
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hp
+ exact ⟨i, (probes_le_length _).trans_lt (sourceBudget i), sourceBudget i⟩
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairDescriptorPaths.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairDescriptorPaths.lean
new file mode 100644
index 0000000000..a5bd78bc18
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairDescriptorPaths.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.CompressorInitialTraceEquiv
+import OAI.Computability.VPVNP.CompressorScheduledTraceData
+import OAI.Computability.VPVNP.LiveCompressedPairWorkspaceFrame
+import OAI.Computability.VPVNP.LiveCompressedPairReindex
+
+/-! # Physical online descriptor paths from the initial rows and the selected execution
+
+The initial cursor rows and the recursive block trace run on one Fin-11
+workspace table. Their framed reports determine the stage path, the memory
+handed to the terminal traversal, and the protected headers on every partial
+path. The smaller inner clock supplies the room for the outer stage transfer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace LiveProgram.CompressedPair.DescriptorPaths
+
+open BurstRAM Compression CompressorRecords ScheduledTrace BranchSegments
+open PairSimulation.LocalHistory LiveStageLink
+open scoped Fin.CommRing
+
+private theorem framed_room {w stages small cap : ℕ} (next : Fin stages → Option (Fin stages))
+ (addr : Word w) (stage : Fin stages) (base : Word w) (m : Memory w) (rs : List (Report w))
+ (slack : small+3 ≤ cap) (lengths : ∀ r ∈ rs, r.events.length < small) :
+ ∀ r ∈ OnlineWorkspace.framed base m rs, room next addr stage (cap+24) r := by
+ induction rs generalizing m with
+ | nil => simp [OnlineWorkspace.framed]
+ | cons r rs ih =>
+ rw [OnlineWorkspace.framed,List.forall_mem_cons]
+ constructor
+ · have length := lengths r List.mem_cons_self
+ have framed := (Workspace.report_effect base m r).1
+ cases he : (Workspace.report base m r).result <;> cases hn : next stage <;>
+ simp only [room,exitReport,he,hn,transferEvents,List.length_append,List.length_cons,List.length_nil,framed] <;> omega
+ · exact ih _ (fun q hq => lengths q (List.mem_cons_of_mem _ hq))
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f}
+variable {w cap small total budget a g b n : ℕ} {X : Compression.State a g} {E : StateExecution R b n X}
+variable {origin : PassOrigins B f hf E} {W : E.MapWitnesses f} {readers : ExecutionReaders E W}
+variable {resident : ScheduledTrace.Resident B f hf w} {past : List (SelectedLevel B f hf)}
+variable {pub : Fin 11 → Word w} {pitch : Word w} {m : Memory w}
+variable (initial : QuietInterval (BlockProgram.script B) pub cap small (some 0) m)
+variable (result : ScheduledTrace.Result resident pub pitch total cap small budget E origin W readers past
+ initial.segment.state initial.segment.memory)
+local notation "plan" => BlockPlanner.Script.plan (BlockProgram.script B)
+local notation "allCut" => initial.withTrace result.trace
+private abbrev allowReports (pub : Fin 11 → Word w) (cap : ℕ) (rs : List (Report w)) :=
+ ∀ r ∈ rs, room CompressedPair.next (PairTag.address pub) Stage.online (cap+24) r
+
+local notation "allow" => allowReports pub cap
+
+private theorem allowed (slack : small+3 ≤ cap) (z : E.Choices) : allow ((allCut).part z).logs := by
+ let core := initial.combinedCore result.trace result.source z
+ change allow ((initial.withTrace result.trace).part z).logs
+ rw [core.frame]
+ exact framed_room _ _ _ _ _ _ slack core.ticks
+
+variable (boot : Bootstrap) (finalTable : PairTable) (clock : ℕ)
+variable (hclock : cap+24 = clockAt pub clock Stage.online) (slack : small+3 ≤ cap)
+
+/-- Each mathematical compression choice determines exactly one actual
+online stage path on the memory reached after the eight startup calls. -/
+def paths : E.Choices ≃ StagePaths boot plan finalTable pub clock Stage.online m :=
+ (initial.allAccepted result.trace allow (allowed initial result slack)).trans
+ (Equiv.subtypeEquivRight fun bs => by
+ change (∃ rs, runSegment (OnlineWorkspace.program plan pub) (cap+24) (some 0) m bs = some rs ∧
+ endState (some 0) rs = none ∧ allow rs) ↔
+ ∃ rs, runSegment (sourceProgram (components boot plan finalTable) pub Stage.online)
+ (clockAt pub clock Stage.online) (some 0) m bs = some rs ∧ endState (some 0) rs = none ∧ _
+ rw [source_segment,← hclock]
+ rfl)
+
+local notation "e" => paths initial result boot finalTable clock hclock slack
+
+theorem paths_bits (z : E.Choices) : (e z).val = ((allCut).part z).bits :=
+ initial.allAccepted_bits result.trace allow (allowed initial result slack) z
+
+theorem paths_reports (z : E.Choices) : ordinaryReports (e z) = ((allCut).part z).logs := by
+ have run := ordinaryRun (e z)
+ rw [source_segment,paths_bits] at run
+ conv_lhs at run => arg 2; rw [← hclock]
+ exact Option.some.inj (run.symm.trans ((allCut).part z).run)
+
+/-- The final RAM handed to the next stage contains the selected execution's
+entire post-memory and the terminal-stage tag written by the transfer. -/
+theorem paths_post (z : E.Choices) :
+ onlinePost (e z) = writeMemory (result.trace.cut.part z).memory (PairTag.address pub) (tagWord w Stage.terminal) := by
+ rw [onlinePost,paths_reports]
+ change writeMemory ((allCut).part z).memory _ _ = _
+ rw [initial.withTrace_memory]
+ rfl
+
+/-- The combined log includes the initial cursor rows and each chosen block
+exactly once. Every inner call contributes six extra framing probes. -/
+theorem paths_cost (z : E.Choices) :
+ let core := initial.combinedCore result.trace result.source z
+ RAMBuckets.cost Report.probes (ordinaryReports (e z)) ≤
+ 6*core.logs.length + RAMBuckets.cost Report.probes initial.source.logs + budget := by
+ intro core
+ rw [paths_reports]
+ rw [core.frame,(OnlineWorkspace.framed_effect (pub 2) m core.logs (some 0)).2.2]
+ have hc := initial.combinedCost result.trace result.source z
+ change RAMBuckets.cost Report.probes core.logs = _ at hc
+ rw [hc,Nat.add_assoc]
+ exact Nat.add_le_add_left (Nat.add_le_add_left (result.cost z) _) _
+
+/-- The unframed reports and their cost are those of the very same chronological
+choice, including the initial interval and each subsequent pass. -/
+theorem paths_core (z : E.Choices) :
+ let core := initial.combinedCore result.trace result.source z
+ ordinaryReports (e z) = OnlineWorkspace.framed (pub 2) m core.logs ∧
+ RAMBuckets.cost Report.probes core.logs ≤ RAMBuckets.cost Report.probes initial.source.logs+budget := by
+ intro core
+ refine ⟨(paths_reports initial result boot finalTable clock hclock slack z).trans core.frame,?_⟩
+ have cost := initial.combinedCost result.trace result.source z
+ change RAMBuckets.cost Report.probes core.logs = _ at cost
+ rw [cost]
+ exact Nat.add_le_add_left (result.cost z) _
+
+include result hclock in
+private theorem keep {st : Word w} {mem : Memory w} {bits : List Bool} {r : Report w}
+ (reach : SourceReachable boot plan finalTable pub clock Stage.online m st mem)
+ (call : execute (original boot plan finalTable pub Stage.online) (clockAt pub clock Stage.online)
+ ((original boot plan finalTable pub Stage.online).start st) mem bits = some r)
+ (x : ℕ) (hx : x < (pub 2).val+6) : after mem r.events x = mem x := by
+ apply reach.online_keep_of_prefix (lo := (pub 2).val+6) _ call x hx
+ intro bs rs run
+ rw [← hclock] at run
+ exact initial.withTrace_stable result.trace result.frame run
+
+/-- The low bank frame holds even on a successful native prefix whose
+unprocessed motifs have no accepting extension. -/
+def protectedStage (below : (PairTag.address pub).val < (pub 2).val+6) :
+ Protected boot plan finalTable pub clock Stage.online m :=
+ Protected.ofSource boot plan finalTable pub clock Stage.online m
+ (fun reach _ call _ => keep initial result boot finalTable clock hclock reach call _ below)
+
+theorem protectedStage_word (below : (PairTag.address pub).val < (pub 2).val+6)
+ (x : ℕ) (hx : x < (pub 2).val+6) :
+ (protectedStage initial result boot finalTable clock hclock below).word x :=
+ Protected.ofSource_word boot plan finalTable pub clock Stage.online m x
+ (fun reach _ call _ => keep initial result boot finalTable clock hclock reach call _ below)
+ (fun reach _ call => keep initial result boot finalTable clock hclock reach call x hx)
+
+end LiveProgram.CompressedPair.DescriptorPaths
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairDescriptorRoom.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairDescriptorRoom.lean
new file mode 100644
index 0000000000..5809b81716
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairDescriptorRoom.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.LiveCompressedPairPaperStartup
+import OAI.Computability.VPVNP.CompressorBlockCapacity
+import OAI.Computability.VPVNP.CompressorBlockClock
+
+/-! # Uniform workspace and clock bounds of the concrete pair table
+
+The workspace operand is the evaluated live layout address, uniformly over
+the execution group's prefix. The complete block directory and data arenas
+fit there at all sufficiently large lengths. The same length bound supplies
+the calendar's tag width and fixed overhead on both clocks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+open Compression CursorBounds CursorNetwork BurstRAM LiveProgram LiveProgram.CompressedPair Filter
+open CompressorRecords DescriptorSpace PairStages.Group.CompressedPaths
+
+variable {K : Type} [Field K] {S : BlockSchedule K} (B : S.Templates) (u : PairExponents B.growthConstant)
+variable (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry)
+variable (E : UniversalMachine.Program) (addr : ℕ) (positive : 1 ≤ addr)
+local notation "D" => paperProgram B u c labels E addr positive
+
+theorem eventually_descriptor_room :
+ ∀ᶠ n : ℕ in atTop, ∀ (ht : 21 ≤ 2^((D).geometry n).w) (hf : 44 ≤ n^10000),
+ let G := (D).executionGroup n ht hf
+ let pub := publicWords G
+ let base := (LiveProgram.Layout.pairWorkspace c).eval ((D).geometry n)
+ let L := BlockProgram.layout B (pub 2).val (initialPositions addr n) (blockCount (u.θ : ℝ) n)
+ (pub 2).val = base ∧ endAddress L < 2^wordBits addr n ∧
+ ∀ cap ≥ BlockClock.small B addr n,
+ Schedule.Online.Run.ControlBounds (BlockProgram.script B).plan cap (w := wordBits addr n) := by
+ let H := liveCapacity u
+ let base n := (LiveProgram.Layout.pairWorkspace c).eval (paperGeometry addr H n)
+ have hH := liveCapacity_polynomial u
+ have bounded : PolynomiallyBounded base := startup_workspace_polynomial c positive hH
+ have theta : (u.θ : ℝ) ≤ 1 := by exact_mod_cast (le_trans u.theta_lt.le (by norm_num : (1/100 : ℚ) ≤ 1))
+ have room := BlockProgram.eventually_end B addr positive theta bounded (PolynomiallyBounded.const 0)
+ filter_upwards [room,BlockClock.eventually_room B addr positive 3,eventually_startup_inputs c positive hH]
+ with n fits bounds start ht hf
+ let G := (D).executionGroup n ht hf
+ obtain ⟨workspace,_,_,_⟩ := start G.lit
+ change (publicWords G 2).val = base n at workspace
+ refine ⟨workspace,?_,bounds.2⟩
+ change endAddress (BlockProgram.layout B (publicWords G 2).val _ _) < _
+ rw [workspace]
+ simpa only [Nat.add_zero] using fits
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairExecution.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairExecution.lean
new file mode 100644
index 0000000000..fc4efc6e01
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairExecution.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.LiveProgramCompressedPair
+import OAI.Computability.VPVNP.LiveHeaderProtectedCore
+
+/-!
+# Replaying calls of the nested compressed pair table
+
+A call begins with five private instructions, scans to the tag, and then
+executes one unrelocated component with the original bit stream. Its
+accepting exit can require three transfer instructions. The exact amount of
+fuel left at that point characterizes all successful reports, including
+arbitrary continuing words. Out-of-range tags reject.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+
+variable {d initial phases : ℕ} {C : Catalog d} (b : Bootstrap) (plan : Online.Config C initial phases)
+ (finalTable : PairTable) {w : ℕ} (pub : Fin 11 → Word w)
+
+/-- Number of entry ticks and tag-dispatch events preceding a source-stage call in the
+compressed pair. -/
+abbrev overhead (i : Stage) := (dispatchEvents (PairTag.address pub) i).length + 5
+
+/-- A native call at an in-range tag returns exactly a linked source report
+whose possible handoff also fits within the remaining fuel. -/
+private theorem execute_ready (i : Stage) (fit : 10 ≤ 2^w) (cap : ℕ)
+ (enough : overhead pub i ≤ cap) (st : Word w) (m : Memory w)
+ (tag : m (PairTag.address pub).val = tagWord w i) (bits : List Bool) (out : Report w) :
+ execute (program b plan finalTable pub) cap ((program b plan finalTable pub).start st) m bits = some out ↔
+ ∃ rep : Report w, execute (original b plan finalTable pub i) (cap-overhead pub i)
+ ((original b plan finalTable pub i).start st) m bits = some rep ∧
+ (exitReport next (PairTag.address pub) i rep).events.length < cap-overhead pub i ∧
+ out = report pub i rep := by
+ let T := components b plan finalTable
+ let addr := PairTag.address pub
+ let L := linked T next
+ let f := cap-overhead pub i
+ let scan := (dispatchEvents addr i).length
+ have hc : (f+scan)+5=cap := by dsimp only [f,scan,addr,overhead] at *; omega
+ have outer := PairTag.execute_start L pub (f+scan) st m bits
+ change execute (program b plan finalTable pub) ((f+scan)+5)
+ ((program b plan finalTable pub).start st) m bits = (execute (LiveStageLink.machine T next pub addr).program
+ (f+scan) ((LiveStageLink.machine T next pub addr).program.start st) m bits).map _ at outer
+ rw [hc,execute_linked T next pub addr i fit st f m tag bits] at outer
+ have lower := execute_widen_start (stages b plan finalTable i).table (embedding b plan finalTable i) id pub f st m bits
+ change execute ((T i).instantiate w pub).program f (((T i).instantiate w pub).program.start st) m bits =
+ execute (original b plan finalTable pub i) f ((original b plan finalTable pub i).start st) m bits at lower
+ rw [lower] at outer
+ rw [outer]
+ change _ ↔ ∃ rep, execute (original b plan finalTable pub i) f ((original b plan finalTable pub i).start st)
+ m bits = some rep ∧ (exitReport next addr i rep).events.length < f ∧ out = report pub i rep
+ cases h : execute (original b plan finalTable pub i) f ((original b plan finalTable pub i).start st) m bits with
+ | none => simp
+ | some rep =>
+ simp only [Option.bind_some,Option.some.injEq,exists_eq_left']
+ unfold boundedExit
+ by_cases room : (exitReport next addr i rep).events.length < f
+ · simp [room,report,linkedReport,addr,eq_comm]
+ · simp [room]
+
+/-- Exact replay for every cap, including clocks too short to reach the tag. -/
+theorem execute_stage_iff (i : Stage) (fit : 10 ≤ 2^w) (cap : ℕ) (st : Word w) (m : Memory w)
+ (tag : m (PairTag.address pub).val = tagWord w i) (bits : List Bool) (out : Report w) :
+ execute (program b plan finalTable pub) cap ((program b plan finalTable pub).start st) m bits = some out ↔
+ ∃ rep : Report w, execute (original b plan finalTable pub i) (cap-overhead pub i)
+ ((original b plan finalTable pub i).start st) m bits = some rep ∧
+ (exitReport next (PairTag.address pub) i rep).events.length < cap-overhead pub i ∧
+ out = report pub i rep := by
+ by_cases enough : overhead pub i ≤ cap
+ · exact execute_ready b plan finalTable pub i fit cap enough st m tag bits out
+ · have low : cap-overhead pub i = 0 := Nat.sub_eq_zero_of_le (Nat.le_of_not_ge enough)
+ constructor
+ · intro run
+ have big := execute_extend run (overhead pub i-cap)
+ rw [Nat.add_sub_cancel' (Nat.le_of_not_ge enough)] at big
+ obtain ⟨rep,_,room,_⟩ := (execute_ready b plan finalTable pub i fit (overhead pub i)
+ le_rfl st m tag bits out).mp big
+ simp at room
+ · rintro ⟨rep,_,room,_⟩
+ omega
+
+/-- Invalid tag words reject for any input stream and continuing word. -/
+theorem execute_bad_tag (fit : 10 ≤ 2^w) (fuel : ℕ) (st : Word w) (m : Memory w)
+ (bad : 10 ≤ (m (PairTag.address pub).val).val) (bits : List Bool) :
+ execute (program b plan finalTable pub) fuel ((program b plan finalTable pub).start st) m bits = none := by
+ let T := components b plan finalTable
+ let L := linked T next
+ have outer := PairTag.execute_start L pub fuel st m bits
+ change execute (program b plan finalTable pub) (fuel+5) ((program b plan finalTable pub).start st) m bits =
+ (execute (LiveStageLink.machine T next pub (PairTag.address pub)).program fuel
+ ((LiveStageLink.machine T next pub (PairTag.address pub)).program.start st) m bits).map _ at outer
+ rw [execute_invalid T next pub (PairTag.address pub) fit st fuel m bad bits] at outer
+ cases h : execute (program b plan finalTable pub) fuel ((program b plan finalTable pub).start st) m bits with
+ | none => rfl
+ | some rep =>
+ have large := execute_extend h 5
+ rw [outer] at large
+ contradiction
+
+/-- The pair dispatcher preserves a protected word whenever each applicable
+source component preserves it and the inner transfer tag has another address.
+The statement applies to every successful call, even if later calls reject. -/
+theorem preserves_word (fit : 10 ≤ 2^w) (cap : ℕ) (st : Word w) (m : Memory w) (bits : List Bool)
+ (out : Report w) (run : execute (program b plan finalTable pub) cap
+ ((program b plan finalTable pub).start st) m bits = some out)
+ (a : ℕ) (distinct : a ≠ (PairTag.address pub).val)
+ (component : ∀ i : Stage, ∀ r : Report w, execute (original b plan finalTable pub i) (cap-overhead pub i)
+ ((original b plan finalTable pub i).start st) m bits = some r → after m r.events a = m a) :
+ after m out.events a = m a := by
+ by_cases good : (m (PairTag.address pub).val).val < 10
+ · let i : Stage := ⟨_,good⟩
+ have tag : m (PairTag.address pub).val = tagWord w i := Fin.ext (Nat.mod_eq_of_lt (m _).isLt).symm
+ obtain ⟨rep,source,_,rfl⟩ := (execute_stage_iff b plan finalTable pub i fit cap st m tag bits out).mp run
+ rw [(report_effect pub i rep m).2.2.2]
+ cases rep.result <;> cases next i <;> simp [writeMemory,distinct,component i rep source]
+ · rw [execute_bad_tag b plan finalTable pub fit cap st m (le_of_not_gt good) bits] at run
+ contradiction
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairExecutionCaps.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairExecutionCaps.lean
new file mode 100644
index 0000000000..9eac0f1bac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairExecutionCaps.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.LiveCompressedPairReportCaps
+
+/-! # The three resource fields of the native compressed-pair execution -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM CompressorRecords PairSimulation
+
+variable {w : ℕ} (pub : Fin 11 → Word w)
+
+private theorem innerBounds (s : Stage) (r : Report w) :
+ (report pub s r).probes ≤ r.probes+2 ∧ (report pub s r).events.length ≤ r.events.length+30 := by
+ obtain ⟨_,hp,ht,_⟩ := report_effect pub s r (fun _ => 0)
+ exact ⟨by split at hp <;> omega,ht⟩
+
+private theorem framedCost (base : Word w) (m : Memory w) (rs : List (Report w)) :
+ RAMBuckets.cost Report.probes ((OnlineWorkspace.framed base m rs).map (report pub Stage.online)) ≤
+ 9*RAMBuckets.cost Report.probes rs := by
+ induction rs generalizing m with
+ | nil => rfl
+ | cons a rs ih =>
+ have frame := (Workspace.report_effect base m a).2.1
+ have link := (innerBounds pub .online (Workspace.report base m a)).1
+ have rest := ih (after m a.events)
+ change 1+(report pub Stage.online (Workspace.report base m a)).probes+
+ RAMBuckets.cost _ ((OnlineWorkspace.framed base (after m a.events) rs).map _) ≤
+ 9*(1+a.probes+RAMBuckets.cost _ rs)
+ omega
+
+private theorem frameRows (base : Word w) (m : Memory w) (rs : List (Report w)) {a : Report w}
+ (h : a ∈ (OnlineWorkspace.framed base m rs).map (report pub Stage.online)) :
+ ∃ r ∈ rs, a.probes ≤ r.probes+8 ∧ a.events.length ≤ r.events.length+54 := by
+ induction rs generalizing m with
+ | nil => contradiction
+ | cons r rs ih =>
+ change a ∈ report pub Stage.online (Workspace.report base m r) ::
+ (OnlineWorkspace.framed base (after m r.events) rs).map _ at h
+ rcases List.mem_cons.mp h with rfl | h
+ · obtain ⟨_,hp,ht,_,_⟩ := Workspace.report_effect base m r
+ have ⟨p,t⟩ := innerBounds pub .online (Workspace.report base m r)
+ exact ⟨r,by simp,by omega,by omega⟩
+ · obtain ⟨j,hj,p,t⟩ := ih (after m r.events) h
+ exact ⟨j,List.mem_cons_of_mem _ hj,p,t⟩
+
+private theorem termCost (addr : Word w) (ls : List (TerminalLink.Entry w × Report w)) :
+ RAMBuckets.cost Report.probes ((terminalWorkers addr ls).map (report pub Stage.terminal)) ≤
+ 9*RAMBuckets.cost Report.probes (ls.map Prod.snd) := by
+ induction ls with
+ | nil => rfl
+ | cons p ls ih =>
+ have a := TerminalLink.report_probes_le addr p.1 p.2
+ have b := (innerBounds pub .terminal (TerminalLink.report addr p.1 p.2)).1
+ change 1+(report pub Stage.terminal (TerminalLink.report addr p.1 p.2)).probes+
+ RAMBuckets.cost _ ((terminalWorkers addr ls).map _) ≤ 9*(1+p.2.probes+RAMBuckets.cost _ _)
+ omega
+
+private theorem initialCost (s : List (Stage × Report w)) (H : ℕ) (small : ∀ p ∈ s, p.2.probes+5 ≤ H) :
+ RAMBuckets.cost Report.probes (s.map (fun p => report pub p.1 p.2)) ≤ s.length*H := by
+ induction s with
+ | nil => simp [RAMBuckets.cost]
+ | cons p s ih =>
+ have h := (innerBounds pub p.1 p.2).1
+ have cap := small p List.mem_cons_self
+ have rest := ih (fun x hx => small x (List.mem_cons_of_mem _ hx))
+ change 1+(report pub p.1 p.2).probes+RAMBuckets.cost _ (s.map _) ≤ (s.length+1)*H
+ rw [Nat.succ_mul]
+ omega
+
+/-- Work, total charged accesses, and maximal burst for
+`CompressedPaths.Execution`, before the live group adds its tag. -/
+theorem cursor_execution_caps (addr : Word w) (b : Bootstrap) (B n base : ℕ) (startMem : Memory w)
+ (initial phases d : ℕ) (onlineBase : Word w) (onlineMem : Memory w)
+ (online : List (Report w)) (terminal : List (TerminalLink.Entry w × Report w))
+ (S H fuel : ℕ) (hS : 128 ≤ S)
+ (hs : ∀ p ∈ cursorStartupSources b pub B n base startMem initial phases d,
+ ∃ i : Fin 8, p.2.probes < sourceFuel b initial phases n i ∧ p.2.events.length < sourceFuel b initial phases n i)
+ (hb : ∀ i, sourceFuel b initial phases n i+5 ≤ H)
+ (hf : ∀ i, sourceFuel b initial phases n i+77 ≤ fuel)
+ (ho : ∀ r ∈ online, r.probes+11 ≤ H ∧ r.events.length+101 ≤ fuel)
+ (ht : ∀ r ∈ terminal.map Prod.snd, r.probes+9 ≤ H ∧ r.events.length+107 ≤ fuel)
+ (oc : 64*RAMBuckets.cost Report.probes online ≤ S*H)
+ (tc : 320*RAMBuckets.cost Report.probes (terminal.map Prod.snd) ≤ S*H) :
+ let rs := cursorStartupLogs b pub B n base startMem initial phases d ++
+ ((OnlineWorkspace.framed onlineBase onlineMem online).map (report pub Stage.online) ++
+ (terminalWorkers addr terminal).map (report pub Stage.terminal))
+ (∀ r ∈ rs, r.events.length+4 ≤ fuel) ∧ 4*RAMBuckets.cost Report.probes rs ≤ S*H ∧
+ ∀ r ∈ rs, 3+r.probes ≤ H := by
+ intro rs
+ let src := cursorStartupSources b pub B n base startMem initial phases d
+ have initialRows := startup_rows_le b initial phases n H fuel src hs hb hf
+ have rows (r : Report w) (hr : r ∈ rs) : r.events.length+4 ≤ fuel ∧ 3+r.probes ≤ H := by
+ simp only [rs,List.mem_append,cursorStartupLogs_eq] at hr
+ rcases hr with hr | hr | hr
+ · obtain ⟨p,hp,rfl⟩ := List.mem_map.mp hr
+ have ⟨h₁,h₂⟩ := initialRows p hp
+ have ⟨a,c⟩ := innerBounds pub p.1 p.2
+ exact ⟨by omega,by omega⟩
+ · obtain ⟨a,ha,h₁,h₂⟩ := frameRows pub onlineBase onlineMem online hr
+ have ⟨p,t⟩ := ho a ha
+ exact ⟨by omega,by omega⟩
+ · obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hr
+ obtain ⟨p,hp,rfl⟩ := List.mem_map.mp ha
+ have ⟨h₁,h₂⟩ := ht p.2 (List.mem_map_of_mem hp)
+ have c₁ := TerminalLink.report_probes_le addr p.1 p.2
+ have c₂ := TerminalLink.report_length_le addr p.1 p.2
+ have ⟨p',t'⟩ := innerBounds pub .terminal (TerminalLink.report addr p.1 p.2)
+ exact ⟨by omega,by omega⟩
+ refine ⟨fun r hr => (rows r hr).1,?_,fun r hr => (rows r hr).2⟩
+ have init := initialCost pub src H (fun p hp => (initialRows p hp).1)
+ rw [show src.length=8 from List.length_ofFn] at init
+ have onlineBound := framedCost pub onlineBase onlineMem online
+ have terminalBound := termCost pub addr terminal
+ have size := Nat.mul_le_mul_right H hS
+ change RAMBuckets.cost Report.probes ((cursorStartupSources b pub B n base startMem initial phases d).map _) ≤ 8*H at init
+ simp only [rs,RAMBuckets.cost_append,cursorStartupLogs_eq]
+ omega
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairFiveCaps.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairFiveCaps.lean
new file mode 100644
index 0000000000..88d64822e4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairFiveCaps.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.LiveCompressedPairSourceCaps
+import OAI.Computability.VPVNP.PairSimulationTerminalFive
+
+/-! # Resource bounds for the actual five-phase terminal controller -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM Compression CursorNetwork NetworkKernel PairSimulation CompressorRecords LocalHistory
+
+variable {w : ℕ}
+
+/-- Replay the joined bootstrap, online and five terminal phases. The only
+dynamic communication estimates are the individual descriptor and vertex
+estimates of this selected history. The geometric estimate is uniform in
+the choice of that history. -/
+theorem five_execution_caps {A : Type*} {a b g h : ℕ}
+ (X : State a g) (Y : State b h) (chain : TermChain A X.network Y.network)
+ (pub : Fin 11 → Word w) (boot : Bootstrap) (B n base : ℕ) (startMem : Memory w)
+ (initial phases d : ℕ) (onlineBase : Word w) (onlineMem : Memory w) (online : List (Report w))
+ {workers : TerminalLink.Stage → PairTable} {termClock : ℕ} {termMem : Memory w}
+ (trace : TerminalLink.FiveTrace workers pub termClock termMem)
+ (S H fuel : ℕ) (hS : 128 ≤ S) (hH : 16 ≤ H) (clock : 136 ≤ fuel)
+ (hstart : ∀ p ∈ cursorStartupSources boot pub B n base startMem initial phases d,
+ ∃ i : Fin 8, p.2.probes < sourceFuel boot initial phases n i ∧ p.2.events.length < sourceFuel boot initial phases n i)
+ (hburst : ∀ i, sourceFuel boot initial phases n i+5 ≤ H)
+ (hfuel : ∀ i, sourceFuel boot initial phases n i+77 ≤ fuel)
+ (onlineRow : ∀ r ∈ online, r.probes+11 ≤ H ∧ r.events.length+101 ≤ fuel)
+ (onlineTotal : 64*RAMBuckets.cost Report.probes online ≤ S*H)
+ (bootstrap close : Report w) (bootBound closeBound : ℕ)
+ (initialRow : trace.bootstrap.logs.map Prod.snd = [bootstrap])
+ (bootData : bootstrap.probes ≤ bootBound ∧ bootstrap.probes+9 ≤ H ∧ bootstrap.events.length+107 ≤ fuel)
+ (closeData : close.probes ≤ closeBound ∧ close.probes+9 ≤ H ∧ close.events.length+107 ≤ fuel)
+ {dir : IncidenceDirectory w} {prefixBase : Word w} {prefixMemory : Memory w}
+ (scan : TerminalPrefix.Segment.Run pub Y dir prefixBase prefixMemory (trace.prefixRows.logs.map Prod.snd))
+ (steps limit T : ℕ)
+ (arenaTotal : RAMBuckets.cost Report.probes (trace.traversalRows.logs.map Prod.snd) ≤
+ (2*limit+1294)*(((steps+1)*T+1)*X.positions))
+ (arenaRow : ∀ r ∈ trace.traversalRows.logs.map Prod.snd, r.probes+9 ≤ H ∧ r.events.length+107 ≤ fuel)
+ (bitMemory : Memory w) (bits : Fin Y.totalWidth → Bool)
+ (bitData : trace.sharedBits.logs.map Prod.snd = FinalBits.Worker.reports pub 0 bitMemory bits)
+ (vertex : Y.network.Site → Report w)
+ (vertexData : trace.vertices.logs.map Prod.snd = (List.ofFn fun i => vertex ((siteOrder Y).entries i)) ++ [close])
+ (site q : ℕ) (hq : 1 ≤ q) (hT : T ≤ n.log2+1)
+ (siteRow : ∀ v, 1+(vertex v).probes ≤ siteAccesses Y chain site q n v ∧ (vertex v).events.length+107 ≤ fuel)
+ (allSites : ∀ v, siteAccesses Y chain site q n v+9 ≤ H)
+ (share : 320*branchAccesses X Y chain (terminalCoefficient (2^b) steps limit bootBound closeBound site) q n ≤ S*H) :
+ let rs := cursorStartupLogs boot pub B n base startMem initial phases d ++
+ ((OnlineWorkspace.framed onlineBase onlineMem online).map (report pub Stage.online) ++
+ (TerminalLink.reports (TerminalLink.header pub) trace.logs).map (report pub Stage.terminal))
+ (∀ r ∈ rs, r.events.length+4 ≤ fuel) ∧ 4*RAMBuckets.cost Report.probes rs ≤ S*H ∧
+ ∀ r ∈ rs, 3+r.probes ≤ H := by
+ intro rs
+ let arena := trace.traversalRows.logs.map Prod.snd
+ let prefixRows := trace.prefixRows.logs.map Prod.snd
+ let visits := List.ofFn fun i => vertex ((siteOrder Y).entries i)
+ let raw := [bootstrap] ++ prefixRows ++ arena ++ FinalBits.Worker.reports pub 0 bitMemory bits ++ visits ++ [close]
+ have actual : trace.logs.map Prod.snd = raw := by
+ simp only [TerminalLink.FiveTrace.logs,List.map_append,raw,prefixRows,arena,visits,initialRow,bitData,
+ vertexData,List.append_assoc]
+ refine cursor_execution_caps pub (TerminalLink.header pub) boot B n base startMem initial phases d onlineBase onlineMem
+ online trace.logs S H fuel hS hstart hburst hfuel onlineRow ?_ onlineTotal ?_
+ · rw [actual]
+ apply terminal_source_rows Y pub bootstrap close H fuel bootData.2 closeData.2 scan arena arenaRow bitMemory
+ bits vertex _ hH clock
+ intro v
+ obtain ⟨p,t⟩ := siteRow v
+ have h := allSites v
+ exact ⟨by omega,t⟩
+ · rw [actual]
+ exact (Nat.mul_le_mul_left 320 (terminal_source_charge X Y chain pub bootstrap close bootBound closeBound
+ bootData.1 closeData.1 scan arena steps limit T arenaTotal bitMemory bits vertex site q n hq hT
+ (fun v => (siteRow v).1))).trans share
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairFrames.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairFrames.lean
new file mode 100644
index 0000000000..0f3a450dac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairFrames.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.LiveCompressedPairHandoff
+import OAI.Computability.VPVNP.LiveCompressedPairExecution
+import OAI.Computability.VPVNP.LiveProgramCompressedPairPaths
+import OAI.Computability.VPVNP.LiveExponentOperands
+
+/-!
+# Reachable memory frames for nested compressed-pair stages
+
+A prefix is traced on the original finite table at its actual reduced clock.
+At the outer level, only the stage named by the current tag can produce a
+report. Thus an address frame need only be checked on that selected table at
+the physically reached cursor and memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+
+variable {w d initial phases : ℕ} {C : Catalog d} (b : Bootstrap) (plan : Online.Config C initial phases)
+variable (finalTable : PairTable) (pub : Fin 11 → Word w)
+
+/-- Prefixes on a selected original component, before any pair-tag transfer. -/
+inductive SourceReachable (clock : ℕ) (s : Stage) (m : Memory w) : Word w → Memory w → Prop
+ | start : SourceReachable clock s m 0 m
+ | more {st mem bits r st'} : SourceReachable clock s m st mem →
+ execute (original b plan finalTable pub s) (clockAt pub clock s)
+ ((original b plan finalTable pub s).start st) mem bits = some r → r.result = some st' →
+ SourceReachable clock s m st' (after mem r.events)
+
+/-- Recover the inner tag invariant from an external-address frame for actual
+continuing executions of the original online or terminal instruction table. -/
+def Protected.ofSource (clock : ℕ) (s : Stage) (m : Memory w)
+ (protect : ∀ {st mem bits r st'}, SourceReachable b plan finalTable pub clock s m st mem →
+ mem (PairTag.address pub).val = tagWord w s →
+ execute (original b plan finalTable pub s) (clockAt pub clock s)
+ ((original b plan finalTable pub s).start st) mem bits = some r → r.result = some st' →
+ after mem r.events (PairTag.address pub).val = mem (PairTag.address pub).val) :
+ Protected b plan finalTable pub clock s m where
+ invariant := SourceReachable b plan finalTable pub clock s m
+ ready := .start
+ frame := by
+ intro st mem bits r st' reached tag run cont
+ have hr : execute (original b plan finalTable pub s) (clockAt pub clock s)
+ ((original b plan finalTable pub s).start st) mem bits = some r :=
+ (execute_widen_start (stages b plan finalTable s).table (embedding b plan finalTable s) id pub
+ (clockAt pub clock s) st mem bits).symm.trans run
+ exact ⟨reached.more hr cont,(protect reached tag hr cont).trans tag⟩
+
+theorem outerTag_lt (G : PairStages.Group) (fits : (Layout.shadow G.constants).eval G.g < 2^G.w) :
+ G.addr.val < (PairTag.address (PairStages.Group.CompressedPaths.publicWords G)).val := by
+ let c := G.constants
+ let g := G.g
+ obtain ⟨tagLo,headerLo,descriptorEnd,_⟩ := PairStages.Group.Auxiliary.geometry_order G
+ have hr : Layout.stageTag.eval g < (Layout.counter c).eval g := by
+ change Layout.stageTag.eval g < PairStages.Group.Auxiliary.counterBase G
+ rw [← descriptorEnd]
+ exact tagLo.trans_le (headerLo.trans (Nat.le_add_right _ _))
+ have h₁ : Layout.stageTag.eval g < (Layout.oldState c).eval g := hr.trans_le (Nat.le_add_right _ _)
+ have h₂ : (Layout.oldState c).eval g < 2^g.w := (PairStages.Group.Auxiliary.counter_end_le_shadow G).trans_lt fits
+ rw [show PairTag.address (PairStages.Group.CompressedPaths.publicWords G) =
+ Pieces.word g G.lit (.geometry (Layout.oldState c)) from tag_address c g G.lit]
+ change Layout.stageTag.eval g % 2^g.w < (Layout.oldState c).eval g % 2^g.w
+ rwa [Nat.mod_eq_of_lt (h₁.trans h₂),Nat.mod_eq_of_lt h₂]
+
+/-- Protect the live outer tag across every native prefix of the concrete
+nested table. A malformed inner tag rejects before any source instruction.
+For a valid tag the source-frame obligation uses only the selected stage. -/
+theorem preservesOuter (G : PairStages.Group) (body : G.pair = pairTable b plan finalTable)
+ (fits : (Layout.shadow G.constants).eval G.g < 2^G.w) (m : Memory G.w)
+ (sourceFrame : ∀ {st mem bits rep}, PairStages.Group.CompressedPaths.Reachable G m st mem →
+ ∀ s : Stage,
+ mem (PairTag.address (PairStages.Group.CompressedPaths.publicWords G)).val = tagWord G.w s →
+ execute (original b plan finalTable (PairStages.Group.CompressedPaths.publicWords G) s)
+ (PairStages.Group.CompressedPaths.fuel G - overhead (PairStages.Group.CompressedPaths.publicWords G) s)
+ ((original b plan finalTable (PairStages.Group.CompressedPaths.publicWords G) s).start st) mem bits = some rep →
+ after mem rep.events G.addr.val = mem G.addr.val) :
+ PairStages.Group.CompressedPaths.PreservesTag G m := by
+ intro st mem bits out st' reached run _
+ let operands := PairStages.Group.CompressedPaths.publicWords G
+ let fuel := PairStages.Group.CompressedPaths.fuel G
+ let addr := PairTag.address operands
+ have fit : 10 ≤ 2^G.w := (by decide : 10 ≤ 21).trans G.tagFit
+ have hr : execute (program b plan finalTable operands) fuel ((program b plan finalTable operands).start st)
+ mem bits = some out :=
+ (congrArg (fun P : PairTable => let p := (P.table.instantiate G.w operands).program
+ execute p fuel (p.start st) mem bits) body).symm.trans run
+ by_cases good : (mem addr.val).val < 10
+ · let s : Stage := ⟨_,good⟩
+ have tag : mem addr.val = tagWord G.w s := Fin.ext (Nat.mod_eq_of_lt (mem _).isLt).symm
+ obtain ⟨rep,src,_,rfl⟩ := (execute_stage_iff b plan finalTable operands s fit fuel st mem tag bits out).mp hr
+ have eq := sourceFrame reached s tag src
+ have ne : G.addr.val ≠ (PairTag.address operands).val := (outerTag_lt G fits).ne
+ rw [(report_effect operands s rep mem).2.2.2]
+ cases rep.result <;> cases next s <;> simp [writeMemory,ne,eq]
+ · have rejected := execute_bad_tag b plan finalTable operands fit fuel st mem (Nat.le_of_not_gt good) bits
+ rw [rejected] at hr
+ contradiction
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairHandoff.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairHandoff.lean
new file mode 100644
index 0000000000..511d048f21
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairHandoff.lean
@@ -0,0 +1,303 @@
+import OAI.Computability.VPVNP.LiveProgramCompressedPair
+import OAI.Computability.VPVNP.LivePairStageTagPaths
+import OAI.Computability.VPVNP.LiveStagePaths
+import OAI.Computability.VPVNP.LiveDeterministicPaths
+
+/-!
+# Factoring native compressed-pair paths into online and terminal stages
+
+After the eight deterministic initialization calls, the online calendar and
+the terminal evaluator can both use nondeterminism. Their actual choice tapes
+are concatenated. At the boundary the first stage's accepting exit writes
+the terminal tag and resets the cursor. The cap examines the reports from
+both stages, including their exact tag reads, writes and private entry ticks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+
+variable {w d initial phases : ℕ} {C : Catalog d} (b : Bootstrap) (plan : Online.Config C initial phases)
+variable (finalTable : PairTable) (pub : Fin 11 → Word w)
+
+/-- The inner program linking all compressed-pair components through the pair tag and stage
+successor function. -/
+abbrev innerProgram := (LiveStageLink.machine (components b plan finalTable) next pub (PairTag.address pub)).program
+
+/-- The fuel available to the selected source stage after the five entry ticks and its tag
+dispatch. -/
+def clockAt (clock : ℕ) (s : Stage) := clock-5-(dispatchEvents (PairTag.address pub) s).length
+
+theorem clock_add (clock : ℕ) (enough : 27 ≤ clock) (s : Stage) :
+ clockAt pub clock s + (dispatchEvents (PairTag.address pub) s).length = clock-5 := by
+ unfold clockAt
+ apply Nat.sub_add_cancel
+ simp [dispatchEvents]; have h := s.isLt; omega
+
+/-- The ordinary accepted paths of one component stage, beginning at cursor zero on the given
+memory and stage fuel. -/
+abbrev StagePaths (clock : ℕ) (s : Stage) (m : Memory w) :=
+ Ordinary (components b plan finalTable) next pub (PairTag.address pub) s (clockAt pub clock s) 0 m
+
+/-- The reachable invariant protects the pair-level tag at every continuing
+source call. It may depend on the actual state and memory. -/
+structure Protected (clock : ℕ) (s : Stage) (m : Memory w) where
+ /-- The predicate on the current cursor and memory used to preserve the stage tag across
+ continuing calls. -/
+ invariant : Word w → Memory w → Prop
+ frame : TagFrame (components b plan finalTable) pub (PairTag.address pub) s (clockAt pub clock s) invariant
+ ready : invariant 0 m
+
+private theorem widened_segment {p r r' k : ℕ} (T : Template p r k) (ρ : Fin r ↪ Fin r')
+ (operands : Fin k → Word w) (fuel : ℕ) (st : Option (Word w)) (m : Memory w)
+ (bs : List (List Bool)) :
+ runSegment ((widen T ρ id).instantiate w operands).program fuel st m bs =
+ runSegment (T.instantiate w operands).program fuel st m bs := by
+ induction bs generalizing st m with
+ | nil => rfl
+ | cons bits rest ih =>
+ cases st with
+ | none => rfl
+ | some st =>
+ simp only [runSegment,execute_widen_start,Function.comp_id]
+ cases execute (T.instantiate w operands).program fuel ((T.instantiate w operands).program.start st) m bits with
+ | none => rfl
+ | some r => exact congrArg (Option.map (r :: ·)) (ih r.result (after m r.events))
+
+theorem source_segment (s : Stage) (fuel : ℕ) (st : Option (Word w)) (m : Memory w)
+ (bs : List (List Bool)) :
+ runSegment (sourceProgram (components b plan finalTable) pub s) fuel st m bs =
+ runSegment (original b plan finalTable pub s) fuel st m bs :=
+ widened_segment (stages b plan finalTable s).table (embedding b plan finalTable s) pub fuel st m bs
+
+/-- Rewriting a fuel bound preserves the native private choice sequence. -/
+private def fuelEquiv {K : Type*} (P : BurstRAM.Program w K) {f f' : ℕ} (h : f = f') (st : Word w)
+ (m : Memory w) (cap : List (Report w) → Prop) : ActualPaths P f st m cap ≃ ActualPaths P f' st m cap :=
+ Equiv.subtypeEquivRight fun _ => by rw [h]
+
+private theorem report_room {K : Type*} {P : BurstRAM.Program w K} {fuel : ℕ}
+ {st : Option (Word w)} {m : Memory w} {bs : List (List Bool)} {rs : List (Report w)}
+ (run : runSegment P fuel st m bs = some rs) : ∀ r ∈ rs, r.events.length < fuel := by
+ induction bs generalizing st m rs with
+ | nil => simp [runSegment] at run; subst rs; simp
+ | cons bits rest ih =>
+ cases st with
+ | none => contradiction
+ | some st =>
+ cases h : execute P fuel (P.start st) m bits with
+ | none => simp [runSegment,h] at run
+ | some r =>
+ simp only [runSegment,h,Option.map_eq_some_iff] at run
+ obtain ⟨tail,hr,rfl⟩ := run
+ exact List.forall_mem_cons.mpr ⟨(execute_spec h).1.length_lt,ih hr⟩
+
+/-- Exact terminal-stage path equivalence before the pure address prelude is
+added. Since this stage accepts the entire pair, a successful continuation
+has no remaining calls. -/
+noncomputable def terminalEquiv (clock : ℕ) (hclock : 27 ≤ clock) (fit : 10 ≤ 2^w) (m : Memory w)
+ (ht : m (PairTag.address pub).val = tagWord w Stage.terminal)
+ (safe : Protected b plan finalTable pub clock Stage.terminal m) (cap : List (Report w) → Prop) :
+ ActualPaths (original b plan finalTable pub Stage.terminal) (clockAt pub clock Stage.terminal) 0 m
+ (fun rs => cap (rs.map (linkedReport next (PairTag.address pub) Stage.terminal))) ≃
+ ActualPaths (innerProgram b plan finalTable pub) (clock-5) 0 m cap := by
+ let s := Stage.terminal
+ let T := components b plan finalTable
+ let addr := PairTag.address pub
+ let f := clockAt pub clock s
+ have noNext : next s = none := rfl
+ have hx (r : Report w) : exitReport next addr s r = r := by
+ cases r with | mk es res => cases res <;> simp [exitReport,noNext]
+ let Src := ActualPaths (original b plan finalTable pub s) f 0 m (fun rs => cap (rs.map (linkedReport next addr s)))
+ let ord (a : Src) : StagePaths b plan finalTable pub clock s m := ⟨a.val, by
+ obtain ⟨rs,hr,hh,_⟩ := a.property
+ refine ⟨rs,(source_segment b plan finalTable pub s f _ _ _).trans hr,hh,?_⟩
+ intro r h
+ change (exitReport next addr s r).events.length < f
+ rw [hx]; exact report_room hr r h⟩
+ let add (a : Src) : Σ x : StagePaths b plan finalTable pub clock s m, Remainder cap x :=
+ ⟨ord a,⟨[],[],rfl,by simp [transferState,noNext,endState],by
+ obtain ⟨rs,hr,_,hc⟩ := a.property
+ have eq := (ordinaryRun (ord a)).symm.trans ((source_segment b plan finalTable pub s f _ _ _).trans hr)
+ simpa only [← Option.some.inj eq,List.append_nil] using hc⟩⟩
+ have e := ordinaryEquiv (next := next) (cap := cap) fit safe.frame safe.ready ht
+ apply Equiv.trans (Equiv.ofBijective add ?_)
+ · exact e.trans (fuelEquiv _ (clock_add pub clock hclock s) _ _ _)
+ constructor
+ · intro x y h; exact Subtype.ext (congrArg (fun z => z.1.val) h)
+ · rintro ⟨x,rest⟩
+ obtain ⟨bs,rs,hr,_,hc⟩ := rest
+ have hh : transferState (w := w) next s = none := by simp [transferState,noNext]
+ rw [hh] at hr
+ cases bs with
+ | cons _ _ => contradiction
+ | nil =>
+ simp only [runSegment,Option.some.injEq] at hr
+ subst rs
+ refine ⟨⟨x.val,ordinaryReports x,(source_segment b plan finalTable pub s f _ _ _).symm.trans (ordinaryRun x),
+ x.property.choose_spec.2.1,by simpa only [List.append_nil] using hc⟩,?_⟩
+ rfl
+
+variable {b plan finalTable pub}
+
+/-- The memory passed to the terminal stage after replaying an online path and writing the
+successor stage tag. -/
+noncomputable def onlinePost {clock : ℕ} {m : Memory w} (a : StagePaths b plan finalTable pub clock Stage.online m) : Memory w :=
+ transferMemory (PairTag.address pub) (next Stage.online) (after m (eventLog (ordinaryReports a)))
+
+/-- The online path's ordinary reports wrapped with the physical pair's dispatch and transfer
+events. -/
+noncomputable def onlineReports {clock : ℕ} {m : Memory w} (a : StagePaths b plan finalTable pub clock Stage.online m) :=
+ (ordinaryReports a).map (report pub Stage.online)
+
+variable (b plan finalTable pub)
+
+/-- The complete pair body from its online tag. The branch stream is a
+unique online path followed by a terminal path in its actual post-memory.
+The latter runs the original terminal evaluator's finite instruction table. -/
+noncomputable def onlineTerminalEquiv (clock : ℕ) (hclock : 27 ≤ clock) (fit : 10 ≤ 2^w) (m : Memory w)
+ (tagged : m (PairTag.address pub).val = tagWord w Stage.online)
+ (onlineSafe : Protected b plan finalTable pub clock Stage.online m)
+ (terminalSafe : ∀ a : StagePaths b plan finalTable pub clock Stage.online m,
+ Protected b plan finalTable pub clock Stage.terminal (onlinePost a)) (cap : List (Report w) → Prop) :
+ (Σ a : StagePaths b plan finalTable pub clock Stage.online m,
+ ActualPaths (original b plan finalTable pub Stage.terminal) (clockAt pub clock Stage.terminal) 0 (onlinePost a)
+ (fun rs => cap (onlineReports a ++ rs.map (report pub Stage.terminal)))) ≃
+ ActualPaths (program b plan finalTable pub) clock 0 m cap := by
+ let addr := PairTag.address pub
+ let T := components b plan finalTable
+ let innerCap (rs : List (Report w)) := cap (rs.map PairTag.prefixReport)
+ let online := ordinaryEquiv (next := next) (cap := innerCap) fit onlineSafe.frame onlineSafe.ready tagged
+ let lift := PairTag.pathEquiv (LiveStageLink.linked T next) pub (clock-5) 0 m cap
+ have hl : clock-5+5 = clock := by omega
+ let middle (a : StagePaths b plan finalTable pub clock Stage.online m) := Remainder innerCap a
+ refine (Equiv.sigmaCongrRight (β₂ := middle) (fun a => ?_)).trans
+ (online.trans ((fuelEquiv _ (clock_add pub clock hclock Stage.online) _ _ _).trans
+ (lift.trans (fuelEquiv _ hl _ _ _))))
+ let prev := (ordinaryReports a).map (linkedReport next addr Stage.online)
+ let suffixCap (rs : List (Report w)) := innerCap (prev++rs)
+ have htag : (onlinePost a) addr.val = tagWord w Stage.terminal := by
+ change writeMemory _ addr (tagWord w Stage.terminal) addr.val = _
+ simp [writeMemory]
+ let e := terminalEquiv b plan finalTable pub clock hclock fit (onlinePost a) htag (terminalSafe a) suffixCap
+ refine (Equiv.subtypeEquivRight (fun bits => ?_)).trans (e.trans (Equiv.subtypeEquivRight fun bits => ?_))
+ · have he (rs : List (Report w)) :
+ suffixCap (rs.map (linkedReport next (PairTag.address pub) Stage.terminal)) =
+ cap (onlineReports a ++ rs.map (report pub Stage.terminal)) := by
+ simp only [suffixCap,innerCap,prev,onlineReports,List.map_append,List.map_map]
+ rfl
+ simp only [he]
+ · dsimp only [middle,Remainder,transferState,onlinePost,prev,suffixCap]
+ rw [clock_add pub clock hclock]
+ rfl
+
+attribute [local irreducible] stages regs components
+
+private theorem ordinary_tape {r k n : ℕ} {pcs : Fin n → ℕ} {T : (s : Fin n) → Template (pcs s) r k}
+ {nextStage : Fin n → Option (Fin n)} {operands : Fin k → Word w} {addr : Word w} {s : Fin n}
+ {fuel : ℕ} {st : Word w} {m : Memory w} {cap : List (Report w) → Prop}
+ (fit : n ≤ 2^w) {inv : Word w → Memory w → Prop} (frame : TagFrame T operands addr s fuel inv)
+ (hi : inv st m) (ht : m addr.val = tagWord w s)
+ (v : Σ x : Ordinary T nextStage operands addr s fuel st m, Remainder cap x) :
+ (ordinaryEquiv fit frame hi ht v).val = v.1.val ++ v.2.val := rfl
+
+private theorem terminal_tape (clock : ℕ) (hclock : 27 ≤ clock) (fit : 10 ≤ 2^w) (m : Memory w)
+ (ht : m (PairTag.address pub).val = tagWord w Stage.terminal)
+ (safe : Protected b plan finalTable pub clock Stage.terminal m) (cap : List (Report w) → Prop)
+ (z : ActualPaths (original b plan finalTable pub Stage.terminal) (clockAt pub clock Stage.terminal) 0 m
+ (fun rs => cap (rs.map (linkedReport next (PairTag.address pub) Stage.terminal)))) :
+ (terminalEquiv b plan finalTable pub clock hclock fit m ht safe cap z).val = z.val := by
+ simp only [terminalEquiv,Equiv.trans_apply,fuelEquiv,Equiv.subtypeEquivRight_apply,ordinary_tape]
+ dsimp only [Equiv.ofBijective,Equiv.coe_fn_mk]
+ rw [List.append_nil]
+
+theorem onlineTerminalEquiv_tape (clock : ℕ) (hclock : 27 ≤ clock) (fit : 10 ≤ 2^w) (m : Memory w)
+ (tagged : m (PairTag.address pub).val = tagWord w Stage.online)
+ (onlineSafe : Protected b plan finalTable pub clock Stage.online m)
+ (terminalSafe : ∀ a : StagePaths b plan finalTable pub clock Stage.online m,
+ Protected b plan finalTable pub clock Stage.terminal (onlinePost a)) (cap : List (Report w) → Prop)
+ (a : StagePaths b plan finalTable pub clock Stage.online m)
+ (z : ActualPaths (original b plan finalTable pub Stage.terminal) (clockAt pub clock Stage.terminal) 0
+ (onlinePost a) (fun rs => cap (onlineReports a ++ rs.map (report pub Stage.terminal)))) :
+ (onlineTerminalEquiv b plan finalTable pub clock hclock fit m tagged onlineSafe terminalSafe cap ⟨a,z⟩).val =
+ a.val ++ z.val := by
+ simp only [onlineTerminalEquiv,Equiv.trans_apply,fuelEquiv,Equiv.subtypeEquivRight_apply,PairTag.pathEquiv,
+ Equiv.sigmaCongrRight_apply,terminal_tape]
+ exact ordinary_tape (nextStage := next) fit onlineSafe.frame onlineSafe.ready tagged _
+
+/-- Include all eight native setup calls in the path bijection. The tag,
+memory and cap at the join use their actual reports. -/
+noncomputable def fullEquiv (clock : ℕ) (hclock : 27 ≤ clock) (fit : 10 ≤ 2^w) (m : Memory w)
+ (startup : List (Report w))
+ (boot : runSegment (program b plan finalTable pub) clock (some 0) m (List.replicate 8 []) = some startup)
+ (ready : endState (some 0) startup = some 0)
+ (tagged : (after m (eventLog startup)) (PairTag.address pub).val = tagWord w Stage.online)
+ (onlineSafe : Protected b plan finalTable pub clock Stage.online (after m (eventLog startup)))
+ (terminalSafe : ∀ a : StagePaths b plan finalTable pub clock Stage.online (after m (eventLog startup)),
+ Protected b plan finalTable pub clock Stage.terminal (onlinePost a)) (cap : List (Report w) → Prop) :
+ (Σ a : StagePaths b plan finalTable pub clock Stage.online (after m (eventLog startup)),
+ ActualPaths (original b plan finalTable pub Stage.terminal) (clockAt pub clock Stage.terminal) 0 (onlinePost a)
+ (fun rs => cap (startup ++ (onlineReports a ++ rs.map (report pub Stage.terminal))))) ≃
+ ActualPaths (program b plan finalTable pub) clock 0 m cap :=
+ (onlineTerminalEquiv b plan finalTable pub clock hclock fit _ tagged onlineSafe terminalSafe
+ (fun rs => cap (startup++rs))).trans
+ ((Equiv.subtypeEquivRight fun _ => by rw [ready]).trans (emptySegmentEquiv boot cap))
+
+private theorem empty_tape {K : Type*} {P : BurstRAM.Program w K} {fuel n : ℕ} {st : Option (Word w)}
+ {m : Memory w} {rs : List (Report w)} (boot : runSegment P fuel st m (List.replicate n []) = some rs)
+ (cap : List (Report w) → Prop)
+ (z : PathsFrom P fuel (endState st rs) (after m (eventLog rs)) (fun tail => cap (rs++tail))) :
+ (emptySegmentEquiv boot cap z).val = List.replicate n [] ++ z.val := rfl
+
+theorem fullEquiv_tape (clock : ℕ) (hclock : 27 ≤ clock) (fit : 10 ≤ 2^w) (m : Memory w)
+ (startup : List (Report w))
+ (boot : runSegment (program b plan finalTable pub) clock (some 0) m (List.replicate 8 []) = some startup)
+ (ready : endState (some 0) startup = some 0)
+ (tagged : (after m (eventLog startup)) (PairTag.address pub).val = tagWord w Stage.online)
+ (onlineSafe : Protected b plan finalTable pub clock Stage.online (after m (eventLog startup)))
+ (terminalSafe : ∀ a : StagePaths b plan finalTable pub clock Stage.online (after m (eventLog startup)),
+ Protected b plan finalTable pub clock Stage.terminal (onlinePost a)) (cap : List (Report w) → Prop)
+ (a : StagePaths b plan finalTable pub clock Stage.online (after m (eventLog startup)))
+ (z : ActualPaths (original b plan finalTable pub Stage.terminal) (clockAt pub clock Stage.terminal) 0 (onlinePost a)
+ (fun rs => cap (startup ++ (onlineReports a ++ rs.map (report pub Stage.terminal))))) :
+ (fullEquiv b plan finalTable pub clock hclock fit m startup boot ready tagged onlineSafe terminalSafe cap ⟨a,z⟩).val =
+ List.replicate 8 [] ++ (a.val ++ z.val) := by
+ simp only [fullEquiv,Equiv.coe_trans,Function.comp_apply,empty_tape,Equiv.subtypeEquivRight_apply_coe,
+ onlineTerminalEquiv_tape]
+
+/-- Replay the exact native boot, online and terminal report streams. The
+same witness gives both the path classification and its physical memory. -/
+theorem full_run (clock : ℕ) (hclock : 27 ≤ clock) (fit : 10 ≤ 2^w) (m : Memory w)
+ (startup : List (Report w))
+ (boot : runSegment (program b plan finalTable pub) clock (some 0) m (List.replicate 8 []) = some startup)
+ (ready : endState (some 0) startup = some 0)
+ (tagged : (after m (eventLog startup)) (PairTag.address pub).val = tagWord w Stage.online)
+ (onlineSafe : Protected b plan finalTable pub clock Stage.online (after m (eventLog startup)))
+ (terminalSafe : ∀ a : StagePaths b plan finalTable pub clock Stage.online (after m (eventLog startup)),
+ Protected b plan finalTable pub clock Stage.terminal (onlinePost a))
+ (a : StagePaths b plan finalTable pub clock Stage.online (after m (eventLog startup))) (bs : List (List Bool))
+ (terminal : List (Report w))
+ (run : runSegment (original b plan finalTable pub Stage.terminal) (clockAt pub clock Stage.terminal)
+ (some 0) (onlinePost a) bs = some terminal) (halt : endState (some 0) terminal = none) :
+ let joined := startup ++ (onlineReports a ++ terminal.map (report pub Stage.terminal))
+ runSegment (program b plan finalTable pub) clock (some 0) m (List.replicate 8 [] ++ (a.val ++ bs)) =
+ some joined ∧ endState (some 0) joined = none := by
+ let joined := startup ++ (onlineReports a ++ terminal.map (report pub Stage.terminal))
+ let cap := fun rs => rs = joined
+ let z : ActualPaths (original b plan finalTable pub Stage.terminal) (clockAt pub clock Stage.terminal) 0 (onlinePost a)
+ (fun rs => cap (startup ++ (onlineReports a ++ rs.map (report pub Stage.terminal)))) :=
+ ⟨bs,terminal,run,halt,rfl⟩
+ obtain ⟨logs,hr,hh,hc⟩ :=
+ (fullEquiv b plan finalTable pub clock hclock fit m startup boot ready tagged onlineSafe terminalSafe cap ⟨a,z⟩).property
+ rw [fullEquiv_tape] at hr
+ change logs = joined at hc
+ subst logs
+ exact ⟨hr,hh⟩
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairHeaderMemory.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairHeaderMemory.lean
new file mode 100644
index 0000000000..1e93a1466b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairHeaderMemory.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.LiveCompressedPairStartupFootprint
+import OAI.Computability.VPVNP.LiveCompressedPairReindex
+import OAI.Computability.VPVNP.LiveCompressedPairStartupInputs
+
+/-!
+# Header readback after an actual compressed pair
+
+The accepting terminal report must preserve the header as well as every
+returning report. Replay the forced eight-call setup and then each source
+report in its reachable online or terminal phase. This identifies the header
+read by the exponent checker with the one supplied to the compressed pair.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+open PairStages.Group.CompressedPaths
+
+open private native from OAI.Computability.VPVNP.LiveCompressedPairReachable
+
+variable {w d initial phases : ℕ} {C : Catalog d} {b : Bootstrap} {plan : Online.Config C initial phases}
+ {finalTable : PairTable} {pub : Fin 11 → Word w} {clock : ℕ} {input : Memory w}
+variable (online : Protected b plan finalTable pub clock Stage.online input)
+variable (terminal : ∀ p : StagePaths b plan finalTable pub clock Stage.online input,
+ Protected b plan finalTable pub clock Stage.terminal (onlinePost p))
+variable (fit : 10 ≤ 2^w) (a : ℕ) (separate : a ≠ (PairTag.address pub).val)
+ (wo : online.word a) (wt : ∀ p, (terminal p).word a)
+
+include separate in
+private theorem preserves_link {s : Stage} {r : Report w} {m : Memory w}
+ (h : after m r.events a = m a) : after m (report pub s r).events a = m a := by
+ rw [(report_effect pub s r m).2.2.2]
+ cases r.result <;> cases next s <;> simp [writeMemory,separate,h]
+
+include fit separate wo wt in
+private theorem phase_word {st : Word w} {m : Memory w} {bits : List Bool} {out : Report w}
+ (active : Phase online terminal st m)
+ (run : execute (program b plan finalTable pub) clock ((program b plan finalTable pub).start st) m bits = some out) :
+ after m out.events a = m a := by
+ rcases active with ⟨inv,tag,_⟩ | ⟨p,inv,tag⟩
+ · obtain ⟨r,src,_,rfl⟩ := native fit tag run
+ exact preserves_link a separate (wo _ _ _ _ inv tag src)
+ · obtain ⟨r,src,_,rfl⟩ := native fit tag run
+ exact preserves_link a separate (wt p _ _ _ _ inv tag src)
+
+include fit separate wo wt in
+theorem Phase.run_frame {st : Word w} {m : Memory w} {bits : List (List Bool)} {rs : List (Report w)}
+ (active : Phase online terminal st m)
+ (run : runSegment (program b plan finalTable pub) clock (some st) m bits = some rs) :
+ after m (eventLog rs) a = m a := by
+ induction bits generalizing st m rs with
+ | nil => simp [runSegment] at run; subst rs; rfl
+ | cons bits rest ih =>
+ cases he : execute (program b plan finalTable pub) clock ((program b plan finalTable pub).start st) m bits with
+ | none => simp [runSegment,he] at run
+ | some r =>
+ rw [runSegment,he,Option.map_eq_some_iff] at run
+ obtain ⟨tail,hTail,rfl⟩ := run
+ change after m (r.events ++ eventLog tail) a = m a
+ rw [show after m (r.events ++ eventLog tail) = after (after m r.events) (eventLog tail) by
+ simp only [after,List.foldl_append]]
+ cases cont : r.result with
+ | none =>
+ rw [cont] at hTail
+ cases rest with
+ | nil => simp [runSegment] at hTail; subst tail; exact phase_word online terminal fit a separate wo wt active he
+ | cons b bs => contradiction
+ | some st' =>
+ rw [cont] at hTail
+ obtain ⟨inv,word⟩ := Phase.step online terminal fit a separate wo wt active he cont
+ exact (ih inv hTail).trans word
+
+variable {G : PairStages.Group} {B n base : ℕ} {m : Memory G.w}
+local notation "ports" => publicWords G
+local notation "D" => bootstrapRows b initial phases
+local notation "L" => startupLayout b initial phases B n base
+local notation "startLogs" => cursorStartupLogs b ports B n base m initial phases d
+
+/-- On every actual accepting physical tape, an address protected by the
+source phases still contains its original word. -/
+theorem PhysicalStages.readback (S : PhysicalStages b plan finalTable G B n base m)
+ (runs : TransferredStartup.Runs D d L B n b.degreeBits b.lanesPerBlock b.steps ports (PairTag.address ports) m)
+ (a : ℕ) (low : a < base) (distinct : a ≠ (PairTag.address ports).val)
+ (onlineWord : S.onlineFrame.word a) (terminalWord : ∀ p, (S.terminalFrame p).word a)
+ {bits : List (List Bool)} {rs : List (Report G.w)}
+ (run : runSegment (PairStages.Group.CompressedPaths.native G) (fuel G) (some 0) m bits = some rs)
+ (halt : endState (some 0) rs = none) :
+ after m (eventLog rs) a = m a := by
+ change runSegment (G.pair.table.instantiate G.w ports).program (fuel G) (some 0) m bits = some rs at run
+ rw [S.body] at run
+ obtain ⟨rest,tail,_,rfl,hTail⟩ := split_empty_segment S.init.executed run halt
+ rw [S.init.cursor] at hTail
+ have suffix := Phase.run_frame S.onlineFrame S.terminalFrame ((by decide : 10 ≤ 21).trans G.tagFit)
+ a distinct onlineWord terminalWord (Phase.start S.onlineFrame S.terminalFrame S.init.tagged) hTail
+ have front := cursorStartup_after_below b ports B n base m runs a low distinct
+ simpa only [eventLog,List.flatMap_append,after,List.foldl_append] using suffix.trans front
+
+/-- The whole live header precedes both the nested pair tag and the
+descriptor workspace; the address arithmetic is untruncated under the
+workspace fit. -/
+theorem PhysicalStages.headerReadback (S : PhysicalStages b plan finalTable G B n base m)
+ (runs : TransferredStartup.Runs D d L B n b.degreeBits b.lanesPerBlock b.steps ports (PairTag.address ports) m)
+ (baseEq : base = (Layout.pairWorkspace G.constants).eval G.g) (baseFit : base < 2^G.w)
+ (a : ℕ) (header : a < PairStages.Group.Auxiliary.tableBase G)
+ (onlineWord : S.onlineFrame.word a) (terminalWord : ∀ p, (S.terminalFrame p).word a)
+ {bits : List (List Bool)} {rs : List (Report G.w)}
+ (run : runSegment (PairStages.Group.CompressedPaths.native G) (fuel G) (some 0) m bits = some rs)
+ (halt : endState (some 0) rs = none) : after m (eventLog rs) a = m a := by
+ have old : (Layout.oldState G.constants).eval G.g < base := baseEq ▸ tag_before_workspace G.constants G.g
+ have tag : (PairTag.address ports).val = (Layout.oldState G.constants).eval G.g := by
+ change (PairTag.address (Pieces.word G.g G.lit ∘ StageOperands.pair G.constants)).val = _
+ rw [tag_address]
+ exact Nat.mod_eq_of_lt (old.trans baseFit)
+ have table := (PairStages.Group.Auxiliary.geometry_order G).2.2.1
+ have lo : a < (Layout.oldState G.constants).eval G.g := by
+ change a < PairStages.Group.Auxiliary.counterBase G + G.constants.labels.eval G.g
+ omega
+ exact S.readback runs a (lo.trans old) (tag ▸ lo.ne) onlineWord terminalWord run halt
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairInitialTag.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairInitialTag.lean
new file mode 100644
index 0000000000..1007932a7d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairInitialTag.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.LiveProgramPairPreparation
+import OAI.Computability.VPVNP.LiveProgramCompressedPair
+
+/-!
+# The compressed pair starts in its row-count stage
+
+The linker uses the first old-state word, immediately after the grammar and
+motif counters. The header's zero suffix covers this cell. The nomination,
+auxiliary initialization and shadow-copy calls preserve it through pair entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM ChainAssignments CutSchedule LiveHeader LiveHeaderProgram
+
+variable {G : Group} {m : Memory G.w} {i : Fin (2^(sizes G).h)}
+ {hdr : PrimedInputRAM.Header (pairLengths G i) → Bool} {hw : 4 ≤ G.w}
+ {advice : Bits (sizes G).advice} {cuts : AllCuts (sizes G).h (sizes G).delta} {mode : Mode.Tag}
+
+theorem PreparedBranch.startup_tag
+ (out : Output (sizes G) (headerBase G) G.g.d hw advice cuts (halves (sizes G).h (.inl i)) mode m)
+ (F : Nominations.Fits G) (tag : G.tagged Stage.nominations m) (μ : Nominations.Nom G)
+ (P : PreparedBranch G m i hdr (Nominations.indexed G F m tag) μ) (hs : shadowBase G < 2^G.w) :
+ let pub := Pieces.word G.g G.lit ∘ StageOperands.pair G.constants
+ P.copy.memory () (PairTag.address pub).val = 0 := by
+ intro pub
+ let cell := (Layout.oldState G.constants).eval G.g
+ have hi : cell < shadowBase G := by
+ change cell < ((((((cell + G.constants.configWords.eval G.g) + G.constants.configWords.eval G.g) + 5) + 24)
+ + G.constants.prefixCapacity.eval G.g) + G.constants.labels.eval G.g)
+ omega
+ have lo : counterBase G + histLength G ≤ cell := by
+ change counterBase G + histLength G ≤ counterBase G + (histLength G + G.constants.motifLabels)
+ omega
+ have atCell : (PairTag.address pub).val = cell := by
+ rw [CompressedPair.tag_address G.constants G.g G.lit]
+ exact Nat.mod_eq_of_lt (hi.trans hs)
+ obtain ⟨h0,h1,h2,_⟩ := geometry_order G
+ obtain ⟨addr,_,base,_⟩ := address_values G hs
+ have hheader : LiveHeaderSchedule.limit (sizes G) (headerBase G) ≤ (counter G).val := by
+ change tableBase G ≤ (counter G).val
+ omega
+ rw [atCell, P.counterFrame cell (by omega) hi, Nominations.memory_eq]
+ simp only [LiveStageLink.transferMemory, writeMemory, ite_eq_right (by omega : cell ≠ G.addr.val)]
+ exact (out.nomination_frame (counter G) F.address hheader μ).2 cell
+ (by change (counter G).val+histLength G ≤ cell; omega)
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairMemory.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairMemory.lean
new file mode 100644
index 0000000000..52319ca115
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairMemory.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.LiveCompressedPairHandoff
+
+/-! # Readback of actual online and terminal memory through both pair dispatches -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+
+variable {w d initial phases : ℕ} {C : Catalog d}
+variable {b : Bootstrap} {plan : Online.Config C initial phases} {finalTable : PairTable} {pub : Fin 11 → Word w}
+
+private theorem afterCons (m : Memory w) (r : Report w) (rs : List (Report w)) :
+ after m (eventLog (r :: rs)) = after (after m r.events) (eventLog rs) := by
+ simp only [eventLog,List.flatMap_cons,after,List.foldl_append]
+
+private theorem completed_after {s : Stage} {f : ℕ} {st : Word w} {m : Memory w}
+ {bs : List (List Bool)} {rs : List (Report w)} {last : Memory w}
+ (h : Completion (components b plan finalTable) next pub (PairTag.address pub) s f st m bs rs last) :
+ after m (eventLog (rs.map (report pub s))) = transferMemory (PairTag.address pub) (next s) last := by
+ induction h with
+ | last _ hh _ =>
+ rw [List.map_cons,afterCons,(report_effect pub s _ _).2.2.2,hh]
+ cases next s <;> rfl
+ | more _ hh _ _ ih =>
+ rw [List.map_cons,afterCons,(report_effect pub s _ _).2.2.2,hh]
+ exact ih
+
+theorem online_after {clock : ℕ} {m : Memory w}
+ (a : StagePaths b plan finalTable pub clock Stage.online m) :
+ after m (eventLog (onlineReports a)) = onlinePost a :=
+ completed_after (completion_of_run (ordinaryRun a) a.property.choose_spec.2.1 a.property.choose_spec.2.2)
+
+theorem terminal_after (m : Memory w) (rs : List (Report w)) :
+ after m (eventLog (rs.map (report pub Stage.terminal))) = after m (eventLog rs) := by
+ induction rs generalizing m with
+ | nil => rfl
+ | cons r rs ih =>
+ rw [List.map_cons,afterCons,afterCons,(report_effect pub Stage.terminal r m).2.2.2]
+ cases r.result <;> exact ih _
+
+/-- Replaying the complete nested reports leaves precisely the physical
+terminal worker's final memory, including its counter writes. -/
+theorem joined_after (m : Memory w) (startup : List (Report w)) {clock : ℕ}
+ (a : StagePaths b plan finalTable pub clock Stage.online (after m (eventLog startup)))
+ (rs : List (Report w)) :
+ after m (eventLog (startup ++ (onlineReports a ++ rs.map (report pub Stage.terminal)))) =
+ after (onlinePost a) (eventLog rs) := by
+ have append (mem : Memory w) (x y : List (Report w)) :
+ after mem (eventLog (x++y)) = after (after mem (eventLog x)) (eventLog y) := by
+ simp only [eventLog,List.flatMap_append,after,List.foldl_append]
+ rw [append,append,online_after,terminal_after]
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairOccurrence.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairOccurrence.lean
new file mode 100644
index 0000000000..c26e1c6503
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairOccurrence.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.LiveProgramCompressedPairPaths
+
+/-!
+# Compressed path occurrences and the native exponent-stage handoff
+
+The ordinary completion of the pair table is followed by one outer tag
+write. The header interval and all dense counter addresses lie beyond the
+tag. The output of the simulator can therefore be read at its actual
+word addresses by the subsequent exponent check.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.CompressedPaths
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink LiveExponent PairSimulation.LocalHistory
+
+variable {G : Group} {m : Memory G.w} {i : Fin (2^(Auxiliary.sizes G).h)}
+ {hdr : PrimedInputRAM.Header (Auxiliary.pairLengths G i) → Bool}
+ {N : Indexed G Stage.nominations m (Nominations.Nom G)} {μ : Nominations.Nom G}
+ (B : Auxiliary.PreparedBranch G m i hdr N μ)
+
+/-- Facts measured on the actual native pair table and its real prepared
+input. The path correspondence covers both directions of accepting tapes.
+It records the selected descriptor and site streams via `SelectorReindex`.
+The output and bounds below concern its unrelocated reports. -/
+structure Execution (G : Group) (input : Memory G.w) (X : Type) (inc : X → Fin (labelCount G) → ℕ) (S H : ℕ) where
+ /-- The trace encoding that records the selector and traversal choices of each mathematical
+ occurrence. -/
+ encoding : TraceEncoding X
+ /-- The reindexing that emits and decodes the encoded selector choices for the physical
+ execution. -/
+ emission : SelectorReindex encoding
+ /-- The equivalence between emitted selector traces and accepted native pair paths on the
+ prepared input memory. -/
+ paths : Set.range emission.emit ≃ Raw G input
+ tag : PreservesTag G input
+ work : ∀ p : Set.range emission.emit, ∀ r ∈ reports (paths p), r.events.length+4 ≤ fuel G
+ header : ∀ p : Set.range emission.emit, ∀ a, Auxiliary.headerBase G ≤ a → a < Auxiliary.tableBase G →
+ after input (eventLog (reports (paths p))) a = input a
+ counters : ∀ p : Set.range emission.emit, ∀ a : Fin (labelCount G),
+ (after input (eventLog (reports (paths p))) (Auxiliary.counterBase G+a)).val = inc (emission.decode p) a
+ total : ∀ p : Set.range emission.emit, 4*RAMBuckets.cost Report.probes (reports (paths p)) ≤ S*H
+ calls : ∀ p : Set.range emission.emit, ∀ r ∈ reports (paths p), 3+r.probes ≤ H
+
+variable {X : Type} {inc : X → Fin (labelCount G) → ℕ} {S H : ℕ}
+ (E : Execution G (B.copy.memory ()) X inc S H)
+
+include E in
+private theorem enough (p : Raw G (B.copy.memory ())) : ∀ r ∈ reports p, room G.nextStage G.addr Stage.pair (fuel G) r := by
+ obtain ⟨p,rfl⟩ := E.paths.surjective p
+ exact fun r hr => room_of_work (E.work p r hr)
+
+/-- Each physical array read by the exponent stage names the corresponding
+dense counter cell in the native simulator's final memory. -/
+theorem counter_address (G : Group) (fit : Auxiliary.shadowBase G < 2^G.w) (a : Fin (labelCount G)) :
+ (counterAddr G.exponentPub a).val = Auxiliary.counterBase G+a := by
+ have base := (Auxiliary.address_values G fit).2.2.1
+ change (G.exponentPub 2).val = Auxiliary.counterBase G at base
+ have h := Auxiliary.counter_end_le_shadow G
+ rw [counterAddr_val _ _ (by rw [base]; exact h.trans fit.le),base]
+
+/-- Construct the single compressed component of the first-half chronology
+from its native execution, preserving the accepting tape and all counters. -/
+noncomputable def Execution.pairCall (fit : Auxiliary.shadowBase G < 2^G.w) : PairCall B X inc where
+ indexed := indexed E.emission E.paths (B.copy.tagged_memory rfl ()) E.tag (enough B E)
+ header q a lo hi := by
+ obtain ⟨p,rfl⟩ := E.emission.decode.surjective q
+ rw [indexed_memory]
+ have htag := (Auxiliary.address_values G fit).1
+ have horder := (Auxiliary.geometry_order G).1
+ change (if a = G.addr.val then _ else _) = _
+ rw [ite_eq_right (by omega)]
+ exact E.header p a lo hi
+ count q a := by
+ obtain ⟨p,rfl⟩ := E.emission.decode.surjective q
+ rw [indexed_memory,counter_address G fit a]
+ have htag := (Auxiliary.address_values G fit).1
+ obtain ⟨h₀,h₁,h₂,_⟩ := Auxiliary.geometry_order G
+ change ((if Auxiliary.counterBase G+a.val = G.addr.val then _ else _ : Word G.w)).val = _
+ rw [ite_eq_right (by omega)]
+ exact E.counters p a
+
+theorem Execution.pairCall_budget (fit : Auxiliary.shadowBase G < 2^G.w) (hH : 4 ≤ H) (q : X) :
+ let rs := (E.pairCall B fit).indexed.logs q
+ RAMBuckets.cost Report.probes rs ≤ S*(H-1) ∧ ∀ r ∈ rs, 1+r.probes ≤ H := by
+ obtain ⟨p,rfl⟩ := E.emission.decode.surjective q
+ exact indexed_budget E.emission E.paths (B.copy.tagged_memory rfl ()) E.tag (enough B E) p S H hH (E.total p) (E.calls p)
+
+end LiveProgram.PairStages.Group.CompressedPaths
+
+namespace LiveProgram.LocalCount
+
+open BurstRAM LiveHeaderProgram LiveHeader PairStages PairStages.Group ChainAssignments CutSchedule ExponentTrace
+open scoped Classical
+
+variable {G : Group} {S H : ℕ} {Nom : Type}
+ {Path : Exterior (profile G).h (profile G).delta → Fin (2^(profile G).h) → Nom → Type}
+
+theorem compressedCalls_of_execution (W : Conditions G S H) (P : PairStageConditions G S H)
+ (order : Nominations.Nom G ≃ Nom) (adv : Bits (profile G).advice)
+ (fit : 1+labelCount G*expWidth G ≤ (profile G).delta) (inc : ∀ ξ i μ, Path ξ i μ → Fin (labelCount G) → ℕ)
+ (native : ∀ (cuts : AllCuts (profile G).h (profile G).delta) (i : Fin (2^(profile G).h)),
+ let j := halves (profile G).h (.inl i)
+ physicalTag cuts j = some .pair → (∀ side, Fields.ValidPadding (profile G) cuts j .pair side) →
+ ∀ tr : Prepared W adv cuts j .pair, Output (profile G) (Header.base G.g) G.g.d W.word adv cuts j .pair (memory tr) →
+ let ξ := exteriorOf fit (fst cuts)
+ let F := Auxiliary.nominationFits G i (P.room i) P.width.le P.nominations
+ let N := Nominations.indexed G F (memory tr) tr.tag
+ ∀ μ, ∀ B : Auxiliary.PreparedBranch G (memory tr) i (PairedChain.headers adv ξ i) N μ,
+ Nonempty (CompressedPaths.Execution G (B.copy.memory ()) (Path ξ i (order μ)) (inc ξ i (order μ)) S H)) :
+ CompressedCalls W P order adv fit inc := by
+ intro cuts i j mode pad tr out ξ F N μ B
+ obtain ⟨E⟩ := native cuts i mode pad tr out μ B
+ have spanPos : 0 < LiveAuxiliaryHeaders.span (Auxiliary.pairLengths G i) (Auxiliary.histLength G) := by
+ simp [LiveAuxiliaryHeaders.span,PrimedInputRAM.Header.count]
+ have below : Auxiliary.shadowBase G < 2^G.w := by have := P.room i; omega
+ exact ⟨E.pairCall B below, E.pairCall_budget B below ((by decide : 4 ≤ 26).trans P.bucket)⟩
+
+end LiveProgram.LocalCount
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairOnlineRates.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairOnlineRates.lean
new file mode 100644
index 0000000000..3556bfcbb6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairOnlineRates.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.LiveVirtualPairStartupBudget
+import OAI.Computability.VPVNP.PairLinkSlack
+
+/-!
+# Online report budgets from chronological work bounds
+
+A single length threshold covers every report sequence whose total probes are
+linear in the input positions times a fixed power of the binary logarithm,
+and whose individual bursts have polylogarithmic length. The estimates apply
+directly to the concatenated chronological runs, including repeated visits
+to the same abstract level.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM Compression CursorNetwork CursorBounds Filter
+open private probes_le_length from OAI.Computability.VPVNP.LiveCompressedPairCursorStartup
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+/-- Total probes take at most one sixty-fourth of the live group, and each
+report fits both the burst and private clock with the enclosing link costs. -/
+theorem eventually_online_of_local_rates (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (_hb : max S.laneBits 5 ≤ b) (rate q : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (rs : List (Report (wordBits b n))),
+ RAMBuckets.cost Report.probes rs ≤ rate * (pairInput S labels hD).positions * (n.log2+1)^q →
+ (∀ r ∈ rs, r.events.length ≤ rate * (n.log2+1)^q) →
+ 64 * RAMBuckets.cost Report.probes rs ≤ processorCount b n * liveCapacity u n ∧
+ ∀ r ∈ rs, r.probes+11 ≤ liveCapacity u n ∧ r.events.length+101 ≤ n := by
+ have gap : (3/4 : ℝ) < 1 - (u.δ : ℝ) := by
+ have ht := (Rat.cast_lt (K := ℝ)).mpr u.theta_lt
+ have hd := (Rat.cast_lt (K := ℝ)).mpr u.delta_lt
+ push_cast at ht hd
+ linarith
+ have global := eventually_absorb_polylog (64 * (rate : ℝ) * (2 * ((b : ℝ)+2))) (2+q)
+ gap (by norm_num : (0 : ℝ) < 1)
+ have localBound := eventually_absorb_polylog (rate : ℝ) q (by norm_num : (0 : ℝ) < 1/2)
+ (by norm_num : (0 : ℝ) < 1)
+ filter_upwards [global,localBound,eventually_pairBurstSlack u 11,
+ eventually_polylog_le (rate+101) q,eventually_ge_atTop 2] with n hglobal hlocal hburst hticks hn
+ intro base lanes labels hD rs hcost hreport
+ rw [pairInput_positions] at hcost
+ rw [liveCapacity_eq]
+ let R := (processorCount b n : ℝ)
+ let log := (n.log2 : ℝ) + 1
+ have pos := initialPositions_bound b n hn
+ have total : (64 : ℝ) * (RAMBuckets.cost Report.probes rs : ℝ) ≤
+ R * (liveBucket u.δ n : ℝ) := calc
+ _ ≤ 64 * ((rate : ℝ) * (initialPositions b n : ℝ) * log^q) := by
+ dsimp only [log]
+ exact_mod_cast Nat.mul_le_mul_left 64 hcost
+ _ ≤ 64 * ((rate : ℝ) * ((2*((b : ℝ)+2))*R*(n : ℝ)^(3/4 : ℝ)*log^2) * log^q) := by
+ gcongr
+ _ = R * ((64*(rate : ℝ)*(2*((b : ℝ)+2)))*(n : ℝ)^(3/4 : ℝ)*log^(2+q)) := by
+ rw [pow_add]; ring
+ _ ≤ R * (n : ℝ)^(1-(u.δ : ℝ)) := by
+ apply mul_le_mul_of_nonneg_left _ (Nat.cast_nonneg _)
+ simpa only [one_mul] using hglobal
+ _ ≤ _ := mul_le_mul_of_nonneg_left (liveBucket_bounds (by linarith) (by omega)).1 (Nat.cast_nonneg _)
+ dsimp only [R] at total
+ refine ⟨by exact_mod_cast total,?_⟩
+ intro r hr
+ have lengthBound := hreport r hr
+ have probes : r.probes ≤ rate * (n.log2+1)^q := (probes_le_length r.events).trans lengthBound
+ have hsmall : ((rate * (n.log2+1)^q : ℕ) : ℝ) ≤ (n : ℝ)^(1/2 : ℝ) := by
+ push_cast
+ simpa only [Real.rpow_zero,mul_one,one_mul] using hlocal
+ have live : (rate * (n.log2+1)^q : ℕ) + 11 ≤ liveBucket u.δ n := by
+ exact_mod_cast (add_le_add_left hsmall (11 : ℝ)).trans hburst
+ have padded : 101 ≤ 101 * (n.log2+1)^q :=
+ Nat.le_mul_of_pos_right _ (Nat.one_le_pow _ _ (Nat.succ_pos _))
+ rw [Nat.add_mul] at hticks
+ exact ⟨by omega,by omega⟩
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairOnlineWord.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairOnlineWord.lean
new file mode 100644
index 0000000000..00b8ca9ff8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairOnlineWord.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.LiveCompressedPairReachable
+import OAI.Computability.VPVNP.LiveCompressedPairCursorStartup
+import OAI.Computability.VPVNP.LiveCompressedPairStartupFootprint
+
+/-! # Exact protected word readback after the eight setup calls and online stage -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM LiveStageLink CompressorRecords CompressorRecords.Schedule
+
+variable {w d initial phases : ℕ} {C : Catalog d} {b : Bootstrap} {plan : Online.Config C initial phases}
+ {terminal : PairTable} {pub : Fin 11 → Word w} {clock : ℕ} {m : Memory w}
+
+private theorem completion_word {s : Stage} {entry : Memory w} (safe : Protected b plan terminal pub clock s entry)
+ {a : ℕ} (keep : safe.word a) {st mem bs rs out}
+ (run : Completion (components b plan terminal) next pub (PairTag.address pub) s (clockAt pub clock s) st mem bs rs out)
+ (ready : safe.invariant st mem) (tag : mem (PairTag.address pub).val = tagWord w s) : out a = mem a := by
+ induction run with
+ | last call _ _ => exact keep _ _ _ _ ready tag call
+ | more call cont _ _ ih =>
+ obtain ⟨nextReady,nextTag⟩ := safe.frame _ _ _ _ _ ready tag call cont
+ exact (ih nextReady nextTag).trans (keep _ _ _ _ ready tag call)
+
+/-- Protect the readback across all actual source calls and the transfer
+to the terminal tag. The ordinary path may have any finite length. -/
+theorem Protected.onlinePost_word (safe : Protected b plan terminal pub clock Stage.online m)
+ (p : StagePaths b plan terminal pub clock Stage.online m) (a : ℕ)
+ (apart : a ≠ (PairTag.address pub).val) (keep : safe.word a)
+ (tag : m (PairTag.address pub).val = tagWord w Stage.online) : onlinePost p a = m a := by
+ have comp := completion_of_run (ordinaryRun p) p.property.choose_spec.2.1 p.property.choose_spec.2.2
+ have effect := completion_word safe keep comp safe.ready tag
+ change writeMemory (after m (eventLog (ordinaryReports p))) (PairTag.address pub) (tagWord w Stage.terminal) a = m a
+ simpa only [writeMemory,ite_eq_right apart] using effect
+
+/-- A completed genuine online run preserves the original prepared input
+at every low cell protected by the selected source-frame invariant. -/
+theorem Protected.after_startup_word (B n base : ℕ) (input : Memory w)
+ (runs : TransferredStartup.Runs (bootstrapRows b initial phases) d (startupLayout b initial phases B n base)
+ B n b.degreeBits b.lanesPerBlock b.steps pub (PairTag.address pub) input)
+ (start : StartupResult b plan terminal pub B n base input clock)
+ (safe : Protected b plan terminal pub clock Stage.online
+ (after input (eventLog (cursorStartupLogs b pub B n base input initial phases d))))
+ (p : StagePaths b plan terminal pub clock Stage.online
+ (after input (eventLog (cursorStartupLogs b pub B n base input initial phases d))))
+ (a : ℕ) (low : a < base) (apart : a ≠ (PairTag.address pub).val) (keep : safe.word a) :
+ onlinePost p a = input a :=
+ (safe.onlinePost_word p a apart keep start.tagged).trans (cursorStartup_after_below b pub B n base input runs a low apart)
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairPaperStartup.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairPaperStartup.lean
new file mode 100644
index 0000000000..f730d7bffe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairPaperStartup.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.LiveCompressedPairPaperTable
+import OAI.Computability.VPVNP.CompressorInitialLiveBoundary
+import OAI.Computability.VPVNP.FixedProgramParameters
+import OAI.Computability.VPVNP.LiveVirtualPairOccurrence
+
+/-! # Starting the chosen fixed pair on the live group's memory
+
+A single threshold applies to every header, nomination, coefficient ring
+and solution at every larger length. The first eight calls supply the
+transferred startup needed by the frame proofs and the initial resident
+boundary needed by the descriptor scheduler.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+universe v
+open Compression CursorBounds CursorNetwork BurstRAM LiveProgram LiveProgram.CompressedPair
+open CompressorRecords PairStages.Group.CompressedPaths
+
+variable {K : Type} [Field K] {S : BlockSchedule K} (B : S.Templates)
+ (u : PairExponents B.growthConstant) (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry)
+ (E : UniversalMachine.Program) (addr : ℕ) (positive : 1 ≤ addr)
+
+/-- The fixed live table, using the concrete pair body and the chosen address multiplier. -/
+def paperProgram :=
+ ofPaperConstants c E (paperTable B u c labels) addr positive (liveRatio u)
+
+local notation "D" => paperProgram B u c labels E addr positive
+local notation "boot" => paperBootstrap B u
+local notation "A" => BlockProgram.script B
+
+/-- The startup certificate before inspecting any descriptor branch. -/
+def PaperStartup (n : ℕ) (ht : 21 ≤ 2^((D).geometry n).w) (hf : 44 ≤ n^10000)
+ (m : Memory (wordBits addr n)) (hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0)) : Prop :=
+ let G := (D).executionGroup n ht hf
+ let pub := publicWords G
+ let base := (LiveProgram.Layout.pairWorkspace c).eval ((D).geometry n)
+ base < 2^(wordBits addr n) ∧
+ TransferredStartup.Runs (bootstrapRows boot (A).initial.length (A).block.length) (A).size
+ (startupLayout boot (A).initial.length (A).block.length addr n base) addr n (S.degreeExponent 0)
+ S.laneBits S.steps pub (PairTag.address pub) m ∧
+ ∀ {R : Type v} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ ScheduledTrace.InitialLive B f hf (blockRatio u).num (blockRatio u).den addr n base (fuel G)
+ (paperTerminal B u c labels) pub m hd
+
+/-- The paper's eleven public words and all eight native startup rows at one
+common threshold before the length-dependent scalar ring or solution. -/
+theorem eventually_paperStartup (lanes : S.laneBits ≤ addr) :
+ ∃ hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0),
+ ∀ᶠ n : ℕ in Filter.atTop, ∀ (ht : 21 ≤ 2^((D).geometry n).w) (hf : 44 ≤ n^10000)
+ (m : Memory (wordBits addr n)),
+ m (PairTag.address (publicWords ((D).executionGroup n ht hf))).val = 0 →
+ PaperStartup.{v} B u c labels E addr positive n ht hf m hd := by
+ let H := liveCapacity u
+ let base n := (LiveProgram.Layout.pairWorkspace c).eval (paperGeometry addr H n)
+ have hH := liveCapacity_polynomial u
+ have hb : PolynomiallyBounded base := startup_workspace_polynomial c positive hH
+ have hθ : ((blockRatio u).num : ℝ)/(blockRatio u).den ≤ 1 := by
+ rw [(blockRatio u).value]
+ exact_mod_cast (le_trans u.theta_lt.le (by norm_num))
+ obtain ⟨hd,initial⟩ := ScheduledTrace.eventually_initial_live_uniform B c (paperTerminal B u c labels)
+ (blockRatio u).num (blockRatio u).den addr (blockRatio u).den_pos positive hθ lanes hH
+ have ha : 7 ≤ (boot).shape.arity := (by decide : 7 ≤ 11).trans (InitialTransferred.arity B)
+ have fields : 30 ≤ (boot).shape.scalarFields := by change 30 ≤ 54; decide
+ have runs := TransferredStartup.eventually_run (bootstrapRows boot (A).initial.length (A).block.length)
+ (A).size (boot).shape addr (S.degreeExponent 0) S.laneBits S.steps positive (blockRatio u).den_pos
+ (InitialTransferred.phases_pos B) hθ lanes ha fields hb
+ refine ⟨hd,?_⟩
+ filter_upwards [initial,runs,eventually_startup_inputs c positive hH] with n ready transferred inputs
+ intro ht hf m tag
+ let G := (D).executionGroup n ht hf
+ obtain ⟨workspace,length,width,below⟩ := inputs G.lit
+ change (publicWords G 2).val = base n at workspace
+ refine ⟨workspace.symm.trans_lt (publicWords G 2).isLt,
+ transferred (publicWords G) (PairTag.address (publicWords G)) workspace length width (below.trans_le workspace.le) m,?_⟩
+ intro R _ f hf
+ exact ready f hf G.lit m G rfl tag
+
+end FixedProgramDiagonal.Program
+
+namespace LiveProgram.LocalCount
+open BurstRAM CutSchedule PairStages PairStages.Group PairStages.Group.CompressedPaths
+
+/-- The actual auxiliary copy supplies the zero linker tag required by the
+fixed pair startup, for every valid nominated first-half group. -/
+theorem CompressedInput.pairStartTag {G : Group} {S H : ℕ} {W : Conditions G S H} {P : PairStageConditions G S H}
+ {adv : Bits (profile G).advice} {fit : 1+labelCount G*expWidth G ≤ (profile G).delta}
+ (I : CompressedInput W P adv fit) :
+ I.branch.copy.memory () (PairTag.address (publicWords G)).val = 0 :=
+ I.branch.startup_tag I.out I.nominationFits I.trace.tag I.μ I.shadowFit
+
+end LiveProgram.LocalCount
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairPaperTable.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairPaperTable.lean
new file mode 100644
index 0000000000..8688fb6b4c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairPaperTable.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.LiveProgramCompressedPair
+import OAI.Computability.VPVNP.PairTerminalVertexBank
+import OAI.Computability.VPVNP.PairShrinkVertexImage
+import OAI.Computability.VPVNP.PairRefreshVertexRun
+import OAI.Computability.VPVNP.PaperPairParameters
+
+/-! # The compressed-pair table fixed before the diagonal length
+
+The online stage and terminal refresh use the same fixed refresh record
+width and tie order. Both terminal map roles write into the same suffix
+of the live histogram. The outer linker installs these instructions once,
+before the scalar model, group headers, and selected compression branches.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace LiveProgram.CompressedPair
+
+open Compression CompressorRecords PairSimulation CursorBounds CursorNetwork BurstRAM
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (u : PairExponents B.growthConstant) (c : Constants)
+ (labels : c.motifLabels = Fintype.card B.Entry)
+
+/-- Compile the exact block calendar ratio and the physical descriptor shape. -/
+def paperBootstrap : Bootstrap where
+ shape := BlockProgram.allocationShape B
+ degreeBits := S.degreeExponent 0
+ lanesPerBlock := S.laneBits
+ steps := S.steps
+ numerator := (blockRatio u).num
+ denominator := (blockRatio u).den
+
+/-- Ordinal of a parameter in the suffix of the live counter bank. -/
+def entryOrdinal : B.Entry ≃ Fin c.motifLabels :=
+ (Fintype.equivFin B.Entry).trans (finCongr labels).symm
+
+/-- The installed shrinking role counts occurrences in the live parameter order. -/
+def shrinkRole : VertexImage.Segment := ShrinkVertexImage.shrinkSegment B (entryOrdinal B c labels)
+
+/-- The installed refresh role uses the same tie order and record stride as the descriptor writer. -/
+def refreshRole : VertexImage.Segment := RefreshVertex.refreshSegment B (RefreshBlockPlan.order B)
+ (RefreshBlockPlan.shape B).stride (entryOrdinal B c labels)
+
+/-- The actual geometry, root gather, cursor leaf and both map roles. The
+geometry computes the live bucket from the same ratio as the outer program. -/
+def paperSegments := TerminalProgram.installedSegments c S (liveRatio u).num (liveRatio u).den
+ (shrinkRole B c labels) (refreshRole B c labels)
+
+/-- The five linked terminal worker stages of the fixed compressed pair. -/
+def paperTerminal : PairTable := TerminalProgram.installedTable B c (liveRatio u).num (liveRatio u).den
+ (shrinkRole B c labels) (refreshRole B c labels)
+
+/-- The complete eleven-operand pair subroutine, independent of the input length. -/
+def paperTable : PairTable :=
+ pairTable (paperBootstrap B u) (BlockProgram.script B).plan (paperTerminal B u c labels)
+
+theorem paper_terminal_rows (base positions blocks : ℕ) :
+ TerminalProgram.table (BlockProgram.layout B base positions blocks).shape B.recordLimit
+ (paperSegments B u c labels) = paperTerminal B u c labels :=
+ TerminalProgram.installed_at_layout ..
+
+theorem paper_block_count (n : ℕ) :
+ roundedDown (paperBootstrap B u).numerator (paperBootstrap B u).denominator n =
+ blockCount (u.θ : ℝ) n :=
+ blockRatio_floor u n
+
+end LiveProgram.CompressedPair
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairPreludeCosts.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairPreludeCosts.lean
new file mode 100644
index 0000000000..fb774c5dbf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairPreludeCosts.lean
@@ -0,0 +1,39 @@
+import OAI.Computability.VPVNP.PairTerminalSelectedPrefixCosts
+
+/-! # The source charges of the forced terminal prelude -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM Compression CursorNetwork CompressorRecords PairSimulation LocalHistory
+
+variable {a g a' g' w : ℕ} {workers : TerminalLink.Stage → PairTable} {clk : ℕ} {input : Memory w}
+
+/-- The forced prefix of the five-stage terminal table. Its row budget comes
+from the actual selected history-directory execution. -/
+structure PreludeCosts (X : State a g) (Y : State a' g') (pub : Fin 11 → Word w)
+ (trace : TerminalLink.FiveTrace workers pub clk input) (steps limit T bound : ℕ) where
+ /-- The single source report that initializes the terminal header. -/
+ boot : Report w
+ initialRow : trace.bootstrap.logs.map Prod.snd = [boot]
+ bootWork : boot.events.length ≤ bound
+ /-- The selected final state's physical incidence directory. -/
+ dir : IncidenceDirectory w
+ /-- Address of the first entry of the wire-offset table. -/
+ prefixBase : Word w
+ /-- Memory read by the wire-width scan after the bootstrap. -/
+ prefixMemory : Memory w
+ scan : TerminalPrefix.Segment.Run pub Y dir prefixBase prefixMemory (trace.prefixRows.logs.map Prod.snd)
+ arenaTotal : RAMBuckets.cost Report.probes (trace.traversalRows.logs.map Prod.snd) ≤
+ (2*limit+1294)*(((steps+1)*T+1)*X.positions)
+ arenaRow : ∀ r ∈ trace.traversalRows.logs.map Prod.snd, r.probes ≤ r.events.length ∧
+ r.events.length < TraversalController.callFuel limit
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairProtection.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairProtection.lean
new file mode 100644
index 0000000000..0d7b01f035
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairProtection.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.LiveCompressedPairReachable
+import OAI.Computability.VPVNP.LiveDeterministicReachable
+import OAI.Computability.VPVNP.LiveCompressedPairFrames
+
+/-!
+# Protecting live memory throughout the actual compressed pair
+
+The eight forced startup tapes reach the online calendar. From that point,
+every returning physical call preserves an outer address whenever its online
+or terminal source invariant does. The terminal invariant starts on the
+post-memory of the actual completed online branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+
+variable {w d initial phases : ℕ} {C : Catalog d} (b : Bootstrap) (plan : Online.Config C initial phases)
+ (finalTable : PairTable) (pub : Fin 11 → Word w) (clock : ℕ) (fit : 10 ≤ 2^w)
+
+/-- A source-table frame on genuinely reachable states supplies the second
+address of the nested linker invariant, with unchanged bits and reports. -/
+theorem Protected.ofSource_word (s : Stage) (m : Memory w) (a : ℕ)
+ (inner : ∀ {st mem bits r st'}, SourceReachable b plan finalTable pub clock s m st mem →
+ mem (PairTag.address pub).val = tagWord w s →
+ execute (original b plan finalTable pub s) (clockAt pub clock s)
+ ((original b plan finalTable pub s).start st) mem bits = some r → r.result = some st' →
+ after mem r.events (PairTag.address pub).val = mem (PairTag.address pub).val)
+ (source : ∀ {st mem bits r}, SourceReachable b plan finalTable pub clock s m st mem →
+ mem (PairTag.address pub).val = tagWord w s →
+ execute (original b plan finalTable pub s) (clockAt pub clock s)
+ ((original b plan finalTable pub s).start st) mem bits = some r → after mem r.events a = mem a) :
+ (Protected.ofSource b plan finalTable pub clock s m inner).word a := by
+ intro st mem bits r reached tag run
+ exact source reached tag ((execute_widen_start (stages b plan finalTable s).table
+ (embedding b plan finalTable s) id pub (clockAt pub clock s) st mem bits).symm.trans run)
+
+include fit in
+theorem protectsAddress (m : Memory w) (logs : List (Report w))
+ (startup : runSegment (program b plan finalTable pub) clock (some 0) m (List.replicate 8 []) = some logs)
+ (cursor : endState (some 0) logs = some 0)
+ (tag : (after m (eventLog logs)) (PairTag.address pub).val = tagWord w Stage.online)
+ (online : Protected b plan finalTable pub clock Stage.online (after m (eventLog logs)))
+ (terminal : ∀ p : StagePaths b plan finalTable pub clock Stage.online (after m (eventLog logs)),
+ Protected b plan finalTable pub clock Stage.terminal (onlinePost p))
+ (a : ℕ) (separate : a ≠ (PairTag.address pub).val)
+ (bootFrame : ∀ r ∈ logs, ∀ entry, after entry r.events a = entry a)
+ (onlineFrame : online.word a) (terminalFrame : ∀ p, (terminal p).word a) :
+ ProtectsAddress (program b plan finalTable pub) clock 0 m a := by
+ apply protects_after_empty_prefix startup cursor bootFrame
+ apply ProtectsAddress.of_invariant (Phase online terminal) (Phase.start online terminal tag)
+ exact fun active run cont => Phase.step online terminal fit a separate onlineFrame terminalFrame active run cont
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairReachable.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairReachable.lean
new file mode 100644
index 0000000000..d0d6c0a46a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairReachable.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.LiveCompressedPairHandoff
+import OAI.Computability.VPVNP.LiveCompressedPairExecution
+
+/-!
+# The reachable online and terminal phases of a compressed pair
+
+When the online calendar returns, the next call stays in its source
+invariant. When it accepts, the native transfer installs the terminal tag
+in the actual memory belonging to a complete online path. Thus every
+continuing call after the deterministic startup belongs to one of these
+two source phases, including prefixes that may subsequently reject.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+
+variable {w d initial phases : ℕ} {C : Catalog d} {b : Bootstrap} {plan : Online.Config C initial phases}
+ {finalTable : PairTable} {pub : Fin 11 → Word w} {clock : ℕ}
+
+local notation "T" => components b plan finalTable
+local notation "addr" => PairTag.address pub
+
+/-- Source invariants need to protect an outer address only on calls
+reachable within that phase. This includes the source accepting exit. -/
+def Protected.word {s : Stage} {input : Memory w} (safe : Protected b plan finalTable pub clock s input) (a : ℕ) : Prop :=
+ ∀ st m bits r, safe.invariant st m → m (addr).val = tagWord w s →
+ execute (sourceProgram T pub s) (clockAt pub clock s) ((sourceProgram T pub s).start st) m bits = some r →
+ after m r.events a = m a
+
+private def Back (input : Memory w) (st : Word w) (m : Memory w) : Prop :=
+ ∀ bs rs finish, Completion T next pub addr Stage.online (clockAt pub clock Stage.online) st m bs rs finish →
+ ∃ qs logs, Completion T next pub addr Stage.online (clockAt pub clock Stage.online) 0 input qs logs finish
+
+private theorem post_of_completion {input finish : Memory w} {bits : List (List Bool)} {rs : List (Report w)}
+ (done : Completion T next pub addr Stage.online (clockAt pub clock Stage.online) 0 input bits rs finish) :
+ ∃ path : StagePaths b plan finalTable pub clock Stage.online input,
+ onlinePost path = writeMemory finish addr (tagWord w Stage.terminal) := by
+ obtain ⟨hr,hh,hm,hf⟩ := done.spec
+ let a : StagePaths b plan finalTable pub clock Stage.online input := ⟨bits,rs,hr,hh,hf⟩
+ have hlogs : ordinaryReports a = rs := Option.some.inj ((ordinaryRun a).symm.trans hr)
+ exact ⟨a,by unfold onlinePost; rw [hlogs,hm]; rfl⟩
+
+private theorem native {s : Stage} {st : Word w} {m : Memory w} {bits : List Bool} {out : Report w}
+ (fit : 10 ≤ 2^w) (tag : m (addr).val = tagWord w s)
+ (run : execute (program b plan finalTable pub) clock ((program b plan finalTable pub).start st) m bits = some out) :
+ ∃ rep, execute (sourceProgram T pub s) (clockAt pub clock s) ((sourceProgram T pub s).start st) m bits = some rep ∧
+ room next addr s (clockAt pub clock s) rep ∧ out = report pub s rep := by
+ have fuel : clockAt pub clock s = clock-overhead pub s := by simp [clockAt,overhead,Nat.sub_sub,Nat.add_comm]
+ obtain ⟨r,h,hr,ho⟩ := (execute_stage_iff b plan finalTable pub s fit clock st m tag bits out).mp run
+ have exactCall := execute_widen_start (stages b plan finalTable s).table (embedding b plan finalTable s) id pub
+ (clockAt pub clock s) st m bits
+ rw [← fuel] at h hr
+ exact ⟨r,exactCall.trans h,hr,ho⟩
+
+variable {input : Memory w} (online : Protected b plan finalTable pub clock Stage.online input)
+variable (terminal : ∀ p : StagePaths b plan finalTable pub clock Stage.online input,
+ Protected b plan finalTable pub clock Stage.terminal (onlinePost p))
+
+/-- The terminal invariant is indexed by the actual completed online path. -/
+def Phase (st : Word w) (m : Memory w) : Prop :=
+ (online.invariant st m ∧ m (addr).val = tagWord w Stage.online ∧
+ Back (b := b) (plan := plan) (finalTable := finalTable) (pub := pub) (clock := clock) input st m) ∨
+ ∃ p : StagePaths b plan finalTable pub clock Stage.online input,
+ (terminal p).invariant st m ∧ m (addr).val = tagWord w Stage.terminal
+
+theorem Phase.start (tag : input (addr).val = tagWord w Stage.online) : Phase online terminal 0 input :=
+ Or.inl ⟨online.ready,tag,fun bs rs _ done => ⟨bs,rs,done⟩⟩
+
+/-- One arbitrary continuing native call stays in its recorded phase or
+enters the terminal phase with the right post-memory, and preserves the
+chosen address. No accepting extension of this call is required. -/
+theorem Phase.step (fit : 10 ≤ 2^w) (a : ℕ) (separate : a ≠ (addr).val)
+ (wo : online.word a) (wt : ∀ p, (terminal p).word a)
+ {st st' : Word w} {m : Memory w} {bits : List Bool} {out : Report w}
+ (active : Phase online terminal st m)
+ (run : execute (program b plan finalTable pub) clock ((program b plan finalTable pub).start st) m bits = some out)
+ (continues : out.result = some st') :
+ Phase online terminal st' (after m out.events) ∧ after m out.events a = m a := by
+ rcases active with ⟨inv,tag,back⟩ | ⟨p,inv,tag⟩
+ · obtain ⟨r,source,room,rfl⟩ := native fit tag run
+ have word := wo _ _ _ _ inv tag source
+ have effect := (report_effect pub Stage.online r m).2.2.2
+ cases result : r.result with
+ | some s =>
+ have hs : s = st' := by simpa only [report,linkedReport,prependLog,exitReport,result,Option.some.injEq] using continues
+ subst s
+ rw [result] at effect
+ rw [effect]
+ obtain ⟨I,ht⟩ := online.frame st m bits r st' inv tag source result
+ exact ⟨Or.inl ⟨I,ht,fun _ _ _ tail => back _ _ _ (.more source result room tail)⟩,word⟩
+ | none =>
+ have stzero : (0 : Word w) = st' := by
+ simpa only [report,linkedReport,prependLog,exitReport,result,show next Stage.online=some Stage.terminal from rfl,
+ Option.some.injEq] using continues
+ subst st'
+ obtain ⟨qs,rs,done⟩ := back _ _ _ (.last source result room)
+ obtain ⟨p,hp⟩ := post_of_completion done
+ rw [result,show next Stage.online=some Stage.terminal from rfl] at effect
+ rw [effect]
+ refine ⟨Or.inr ⟨p,Eq.mp (congrArg ((terminal p).invariant 0) hp) (terminal p).ready,?_⟩,?_⟩
+ · simp [writeMemory]
+ · simp [writeMemory,separate,word]
+ · obtain ⟨r,source,_,rfl⟩ := native fit tag run
+ have word := wt p _ _ _ _ inv tag source
+ have effect := (report_effect pub Stage.terminal r m).2.2.2
+ cases result : r.result with
+ | none =>
+ simp only [report,linkedReport,prependLog,exitReport,result,show next Stage.terminal=none from rfl] at continues
+ contradiction
+ | some s =>
+ have hs : s = st' := by simpa only [report,linkedReport,prependLog,exitReport,result,Option.some.injEq] using continues
+ subst s
+ rw [result] at effect
+ rw [effect]
+ obtain ⟨I,ht⟩ := (terminal p).frame st m bits r st' inv tag source result
+ exact ⟨Or.inr ⟨p,I,ht⟩,word⟩
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairReindex.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairReindex.lean
new file mode 100644
index 0000000000..178882ea47
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairReindex.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.LiveCompressedPairCursorStartup
+import OAI.Computability.VPVNP.LiveCompressedPairFrames
+import OAI.Computability.VPVNP.LiveCompressedPairMemory
+
+/-!
+# Joining descriptor choices and per-terminal branch data in the real pair table
+
+A descriptor choice fixes the online path and its memory. The terminal
+interpretation of that choice supplies the native arc and vertex paths on
+that memory. The two classifications and the checked eight-call bootstrap
+give the physical path corresponding to an ordinal emission, including every
+deterministic setup and scheduling call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+open PairStages.Group.CompressedPaths
+
+variable {d initial phases : ℕ} {C : Catalog d} (b : Bootstrap) (plan : Online.Config C initial phases)
+variable (finalTable : PairTable) (G : PairStages.Group)
+variable (B n base : ℕ) (m : Memory G.w)
+
+local notation "operands" => publicWords G
+local notation "clock" => fuel G
+local notation "startup" => cursorStartupLogs b operands B n base m initial phases d
+local notation "entry" => after m (eventLog startup)
+local notation "onlinePath" => StagePaths b plan finalTable operands clock Stage.online entry
+
+/-- The actual source-clock room required by the online transfer. -/
+def originalOnlineEquiv :
+ ActualPaths (original b plan finalTable operands Stage.online) (clockAt operands clock Stage.online) 0 entry
+ (fun rs => ∀ r ∈ rs, room next (PairTag.address operands) Stage.online (clockAt operands clock Stage.online) r)
+ ≃ onlinePath :=
+ Equiv.subtypeEquivRight fun bs => by
+ simp only [source_segment b plan finalTable operands Stage.online]
+
+/-- Instantiation of the genuine source tables on one group's actual memory. -/
+structure PhysicalStages where
+ body : G.pair = pairTable b plan finalTable
+ enough : 27 ≤ clock
+ init : StartupResult b plan finalTable operands B n base m clock
+ /-- The stage-tag protection established for the online calendar on the memory produced by
+ startup. -/
+ onlineFrame : Protected b plan finalTable operands clock Stage.online entry
+ /-- The terminal-stage tag protection on the actual memory returned by each selected online
+ path. -/
+ terminalFrame : ∀ a : onlinePath, Protected b plan finalTable operands clock Stage.terminal (onlinePost a)
+
+attribute [local irreducible] stages regs components
+
+namespace PhysicalStages
+
+variable {b plan finalTable G B n base m}
+variable (S : PhysicalStages b plan finalTable G B n base m)
+
+include S in
+private theorem onlineTag : entry (PairTag.address operands).val = tagWord G.w Stage.online := by
+ exact S.init.tagged
+
+private def rawEquiv :
+ ActualPaths (program b plan finalTable operands) clock 0 m (fun _ => True) ≃ Raw G m :=
+ Equiv.subtypeEquivRight fun bs => by
+ change _ ↔ ∃ rs, runSegment (G.pair.table.instantiate G.w operands).program clock (some 0) m bs = some rs ∧
+ endState (some 0) rs = none ∧ True
+ rw [S.body]
+
+variable {Z I : Type*} {D : Z → Type*} (emit : (Σ z : Z, D z) ≃ I)
+variable (descriptorPaths : Z ≃ StagePaths b plan finalTable (publicWords G) (fuel G) Stage.online
+ (after m (eventLog (cursorStartupLogs b (publicWords G) B n base m initial phases d))))
+variable (vertexPaths : ∀ z : Z, D z ≃ ActualPaths (original b plan finalTable (publicWords G) Stage.terminal)
+ (clockAt (publicWords G) (fuel G) Stage.terminal) 0 (onlinePost (descriptorPaths z)) (fun _ => True))
+
+include S emit descriptorPaths vertexPaths
+
+/-- Reindex the semantic ordinal emission by every actual accepting path in
+the compiled pair table. Both component correspondences are bidirectional. -/
+noncomputable def reindex : I ≃ Raw G m :=
+ emit.symm.trans ((Equiv.sigmaCongr (β₂ := fun a : onlinePath => ActualPaths (original b plan finalTable operands Stage.terminal)
+ (clockAt operands clock Stage.terminal) 0 (onlinePost a) (fun _ => True)) descriptorPaths vertexPaths).trans
+ ((fullEquiv b plan finalTable operands clock S.enough ((by decide : 10 ≤ 21).trans G.tagFit) m
+ startup S.init.executed S.init.cursor S.onlineTag S.onlineFrame S.terminalFrame (fun _ => True)).trans S.rawEquiv))
+
+theorem reindex_tape (z : Z) (x : D z) :
+ (S.reindex emit descriptorPaths vertexPaths (emit ⟨z,x⟩)).val =
+ List.replicate 8 [] ++ ((descriptorPaths z).val ++ (vertexPaths z x).val) := by
+ simp only [reindex,Equiv.trans_apply,Equiv.symm_apply_apply,rawEquiv,Equiv.subtypeEquivRight_apply_coe,
+ Equiv.sigmaCongr,Equiv.sigmaCongrRight_apply,Equiv.sigmaCongrLeft_apply,fullEquiv_tape]
+
+/-- The actual reports at the handoff to the exponent checker, before the
+outer linker adds its own tag dispatch and transfer events. -/
+theorem reindex_logs (z : Z) (x : D z) :
+ reports (S.reindex emit descriptorPaths vertexPaths (emit ⟨z,x⟩)) =
+ startup ++ (onlineReports (descriptorPaths z) ++ (vertexPaths z x).property.choose.map (report operands Stage.terminal)) := by
+ apply Option.some.inj
+ have actual := rawRun (S.reindex emit descriptorPaths vertexPaths (emit ⟨z,x⟩))
+ rw [reindex_tape] at actual
+ have eq := congrArg (fun P : PairTable =>
+ runSegment (P.table.instantiate G.w operands).program clock (some 0) m
+ (List.replicate 8 [] ++ ((descriptorPaths z).val ++ (vertexPaths z x).val))) S.body
+ exact actual.symm.trans (eq.trans (full_run b plan finalTable operands clock S.enough ((by decide : 10 ≤ 21).trans G.tagFit)
+ m startup S.init.executed S.init.cursor S.onlineTag S.onlineFrame S.terminalFrame (descriptorPaths z) (vertexPaths z x).val
+ (vertexPaths z x).property.choose (vertexPaths z x).property.choose_spec.1 (vertexPaths z x).property.choose_spec.2.1).1)
+
+/-- The readback for dense exponents and preserved header cells is exactly
+the final native terminal memory on the selected descriptor branch. -/
+theorem reindex_after (z : Z) (x : D z) :
+ after m (eventLog (reports (S.reindex emit descriptorPaths vertexPaths (emit ⟨z,x⟩)))) =
+ after (onlinePost (descriptorPaths z)) (eventLog (vertexPaths z x).property.choose) := by
+ rw [reindex_logs]
+ exact joined_after m startup (descriptorPaths z) _
+
+
+end PhysicalStages
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairReportCaps.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairReportCaps.lean
new file mode 100644
index 0000000000..5b04d1a655
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairReportCaps.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.LiveVirtualPairStartupBudget
+import OAI.Computability.VPVNP.PairSimulationTerminalReports
+
+/-!
+# Burst and private-clock bounds on the complete native compressed pair
+
+The bootstrap, online calendar, and terminal worker report streams below
+are the three consecutive stages of the actual fixed pair instruction
+table. We charge the controller's phase and cursor writes on terminal
+returns, the six online pointer reads, and both enclosing tag switches.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM CompressorRecords PairSimulation
+
+variable {w : ℕ} (addr : Word w)
+
+/-- The terminal controller adds the phase reads and exit writes to each worker report. -/
+abbrev terminalWorkers (src : List (TerminalLink.Entry w × Report w)) :=
+ src.map (fun p => TerminalLink.report addr p.1 p.2)
+
+theorem terminal_worker_cost (src : List (TerminalLink.Entry w × Report w)) :
+ RAMBuckets.cost Report.probes (terminalWorkers addr src) ≤
+ 5 * RAMBuckets.cost Report.probes (src.map Prod.snd) := by
+ induction src with
+ | nil => rfl
+ | cons a rest ih =>
+ have h := TerminalLink.report_probes_le addr a.1 a.2
+ change 1+(TerminalLink.report addr a.1 a.2).probes + RAMBuckets.cost _ (terminalWorkers addr rest) ≤
+ 5*(1+a.2.probes+RAMBuckets.cost _ (rest.map Prod.snd))
+ omega
+
+/-- The physical report stream consumed by the enclosing live row has
+exactly the two resource bounds of a first-half `PairCall`. Its private
+clock is bounded on the same reports. -/
+theorem cursor_run_caps (E : UniversalMachine.Program) (outer : Word w) (b : Bootstrap)
+ (pub : Fin 11 → Word w) (B n base : ℕ) (startMem : Memory w)
+ (initial phases d : ℕ) (onlineBase : Word w) (onlineMem : Memory w)
+ (online : List (Report w)) (terminal : List (TerminalLink.Entry w × Report w))
+ (S H cap : ℕ) (hS : 32 ≤ S) (hH : 2 ≤ H)
+ (hs : ∀ p ∈ cursorStartupSources b pub B n base startMem initial phases d,
+ ∃ i : Fin 8, p.2.probes < sourceFuel b initial phases n i ∧
+ p.2.events.length < sourceFuel b initial phases n i)
+ (hb : ∀ i, sourceFuel b initial phases n i+5 ≤ H)
+ (hf : ∀ i, sourceFuel b initial phases n i+77 ≤ cap)
+ (ho : ∀ r ∈ online, r.probes+11 ≤ H ∧ r.events.length+101 ≤ cap)
+ (ht : ∀ r ∈ terminal.map Prod.snd, r.probes+9 ≤ H ∧ r.events.length+107 ≤ cap)
+ (oc : 64*RAMBuckets.cost Report.probes online ≤ S*H)
+ (tc : 320*RAMBuckets.cost Report.probes (terminal.map Prod.snd) ≤ S*H) :
+ let rs := (cursorStartupLogs b pub B n base startMem initial phases d ++
+ ((OnlineWorkspace.framed onlineBase onlineMem online).map (report pub Stage.online) ++
+ (terminalWorkers addr terminal).map (report pub Stage.terminal))).map
+ (LiveStageLink.linkedReport (LiveProgram.next E) outer LiveProgram.Stage.pair)
+ RAMBuckets.cost Report.probes rs ≤ S*(H-1) ∧
+ ∀ r ∈ rs, 1+r.probes ≤ H ∧ r.events.length ≤ cap := by
+ intro rs
+ let startup := cursorStartupSources b pub B n base startMem initial phases d
+ have bound : rs = logs pub E outer onlineBase onlineMem startup online (terminalWorkers addr terminal) := by
+ simp only [rs,startup,cursorStartupLogs_eq,List.map_append,List.map_map,logs,
+ wrappedStartup,onlineLogs,terminalLogs,List.append_assoc]
+ rfl
+ rw [bound]
+ refine linked_caps pub E outer onlineBase onlineMem startup online (terminalWorkers addr terminal)
+ S H cap hS hH ?_ (startup_rows_le b initial phases n H cap startup hs hb hf) ho ?_ oc ?_
+ · simp [startup,cursorStartupSources]
+ · intro r hr
+ obtain ⟨p,hp,rfl⟩ := List.mem_map.mp hr
+ have ⟨p₁,p₂⟩ := ht p.2 (List.mem_map_of_mem hp)
+ have hl := TerminalLink.report_length_le addr p.1 p.2
+ have hc := TerminalLink.report_probes_le addr p.1 p.2
+ omega
+ · have := terminal_worker_cost addr terminal
+ omega
+
+/-- Convert the little-o estimates of the cursor geometry to the integer
+charges of the two finite traversals. -/
+theorem integer_cost_share {k charge S H : ℕ} (hk : 0 < k)
+ (h : (charge : ℝ) < (1/(k : ℝ))*(S : ℝ)*H) : k*charge ≤ S*H := by
+ have kp : (0 : ℝ) < k := by exact_mod_cast hk
+ rw [show (1/(k : ℝ))*(S : ℝ)*H = ((S : ℝ)*H)/(k : ℝ) by ring] at h
+ have := (lt_div_iff₀ kp).mp h
+ rw [mul_comm] at this
+ exact_mod_cast this.le
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairSourceCaps.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairSourceCaps.lean
new file mode 100644
index 0000000000..d8841a7f9f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairSourceCaps.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.LiveCompressedPairExecutionCaps
+import OAI.Computability.VPVNP.LiveCompressedPairTerminalShare
+import OAI.Computability.VPVNP.PairOnlineLiveBudget
+
+/-! # Simultaneous native pair bounds at a fixed input length -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM Compression CursorNetwork CursorBounds CompressorRecords Schedule PairSimulation
+open Filter LocalHistory PhaseVisits
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+set_option exponentiation.threshold 10000 in
+theorem private_clock_room (G : PairStages.Group) {n : ℕ} (hn : 128 ≤ n) (clock : G.clock = n^10000) :
+ n^9999+107 ≤ G.clockAt LiveProgram.Stage.pair := by
+ have disp : (LiveStageLink.dispatchEvents G.addr LiveProgram.Stage.pair).length ≤ 44 := by
+ simp only [LiveStageLink.dispatchEvents,List.length_cons,List.length_replicate]
+ decide
+ have large : 151 ≤ n^9999 := by
+ have n2 : 151 ≤ n^2 := (by decide : 151 ≤ 128^2).trans (Nat.pow_le_pow_left hn 2)
+ exact n2.trans (Nat.pow_le_pow_right (by omega) (by decide))
+ have grow : 2*n^9999 ≤ n^10000 := by
+ exact (Nat.mul_le_mul_right (n^9999) (by omega : 2 ≤ n)).trans_eq (pow_succ' n 9999).symm
+ change n^9999+107 ≤ G.clock-_
+ rw [clock]
+ omega
+
+/-- Bounds on the selected online rows and the canonical terminal charge at
+one length. The same length threshold works for every field model, term
+choice and native memory, after fixing the program and its address exponent. -/
+theorem eventually_native_source_caps (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) (bs : Bootstrap) (P : Plan S)
+ (workerCap initialFactor onlinePower : ℕ) {d i j : ℕ} {C : Catalog d} (plan : Online.Config C i j)
+ (boot close site terminalPower : ℕ) :
+ let localCoeff := workerCap+30+2*(i+j)+20+6*(arity C+1)+2*Online.N d (i+j)+5
+ let terminalCoeff := terminalCoefficient S.baseDegree S.steps B.recordLimit boot close site
+ ∀ᶠ n : ℕ in atTop,
+ let R := processorCount b n
+ let H := liveCapacity u n
+ let w := wordBits b n
+ let T := blockCount (u.θ : ℝ) n
+ 128 ≤ n ∧ 128 ≤ R ∧ 16 ≤ H ∧ T ≤ n.log2+1 ∧
+ (∀ idx : Fin 8, sourceFuel bs i j n idx+5 ≤ H ∧ sourceFuel bs i j n idx+77 ≤ n) ∧
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : T*S.laneBits ≤ lanes) (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let E := B.execute f hf T hT X
+ ∀ z : E.Choices, let Y := E.finalState z
+ let chain := E.termChain (B.records f hf T hT X) z
+ 320*branchAccesses X Y chain terminalCoeff terminalPower n ≤ R*H ∧
+ (∀ v, siteAccesses Y chain site terminalPower n v+9 ≤ H) ∧
+ ∀ (p : Ports w) (initial : List (Directory.Row d w))
+ (groups : ∀ v : SelectedLevel B f hf, LevelRows (d := d) (w := w) X.positions v)
+ (steps : List (Online.Run.Step d (i+j) w)) (m : Memory w),
+ calls initial ≤ initialFactor*X.positions →
+ Online.Run.Valid plan p (localCoeff*(n.log2+1)^onlinePower) m steps →
+ m p.tag.val = LiveStageLink.tagWord w (Online.calendarIndex d (i+j)) →
+ steps.map Online.Run.Step.row = branchRows P X.positions (executeLevels B f hf T hT X z) initial groups →
+ let rs := Online.Run.reports plan p m steps
+ 64*RAMBuckets.cost Report.probes rs ≤ R*H ∧ ∀ r ∈ rs, r.probes+11 ≤ H ∧ r.events.length+101 ≤ n := by
+ intro localCoeff terminalCoeff
+ filter_upwards [eventually_terminal_share B u b hb boot close site terminalPower,
+ eventually_selectedOnline B u P workerCap initialFactor onlinePower b hb plan 10 101 (ε := 1/64) (by norm_num),
+ eventually_startup_burst u bs i j 5, eventually_sourceFuel bs i j 77,
+ eventually_liveCapacity_ge u 16, eventually_numeric B u b 1 hb (by decide),
+ eventually_ge_atTop 128] with n terminal online hb' hf' Hge geometry hn
+ intro R H w T
+ refine ⟨hn,(by have := geometry.2.2.1; omega),Hge,terminal.1,fun idx => ⟨hb' idx,hf' idx⟩,?_⟩
+ intro base lanes labels hD hT A _ f hf X E z Y chain
+ have ⟨global,vertex⟩ := terminal.2 labels hD hT A f hf z
+ refine ⟨global,vertex,?_⟩
+ intro p initial groups steps m init valid tag rows rs
+ have output := online labels hD hT A f hf z p initial groups steps m 0 init valid tag rows
+ have cap := integer_cost_share (by decide : 0<64) output.2.2.2.2
+ change 64*RAMBuckets.cost Report.probes rs ≤ processorCount b n*liveCapacity u n ∧
+ ∀ r ∈ rs, r.probes+11 ≤ liveCapacity u n ∧ r.events.length+101 ≤ n
+ rw [liveCapacity_eq]
+ exact ⟨cap,fun r hr => by
+ obtain ⟨a,t⟩ := output.2.2.2.1 r hr
+ exact ⟨by omega,t⟩⟩
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairStageFrames.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairStageFrames.lean
new file mode 100644
index 0000000000..f12054cc71
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairStageFrames.lean
@@ -0,0 +1,36 @@
+import OAI.Computability.VPVNP.LiveCompressedPairReindex
+import OAI.Computability.VPVNP.LiveCompressedPairStartupFootprint
+
+/-! # The outer live tag along actual compressed-pair continuations -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair.PhysicalStages
+
+open BurstRAM CompressorRecords CompressorRecords.Schedule PairStages.Group.CompressedPaths
+
+variable {d initial phases : ℕ} {C : Catalog d} {b : Bootstrap} {plan : Online.Config C initial phases}
+ {finalTable : PairTable} {G : PairStages.Group} {B n base : ℕ} {m : Memory G.w}
+ (S : PhysicalStages b plan finalTable G B n base m)
+
+/-- The deterministic bootstrap and the two remaining selected stages
+protect the outer live tag on every physically reachable continuing call. -/
+theorem preservesOuterTag (fits : (Layout.shadow G.constants).eval G.g < 2^G.w) (before : G.addr.val < base)
+ (runs : TransferredStartup.Runs (bootstrapRows b initial phases) d (startupLayout b initial phases B n base)
+ B n b.degreeBits b.lanesPerBlock b.steps (publicWords G) (PairTag.address (publicWords G)) m)
+ (online : S.onlineFrame.word G.addr.val) (terminal : ∀ p, (S.terminalFrame p).word G.addr.val) :
+ PreservesTag G m := by
+ apply preservesTag_of_protectsAddress
+ unfold native
+ rw [S.body]
+ exact protectsAddress_startup b (publicWords G) B n base m plan finalTable (fuel G)
+ ((by decide : 10 ≤ 21).trans G.tagFit) runs S.init G.addr.val before (outerTag_lt G fits).ne
+ S.onlineFrame S.terminalFrame online terminal
+
+end LiveProgram.CompressedPair.PhysicalStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairStartupFootprint.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairStartupFootprint.lean
new file mode 100644
index 0000000000..bb592ca823
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairStartupFootprint.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.CompressorTransferredStartupFootprint
+import OAI.Computability.VPVNP.LiveCompressedPairCursorStartup
+import OAI.Computability.VPVNP.LiveCompressedPairProtection
+
+/-!
+# Address protection for the actual eight linked pair-startup reports
+
+Replay the startup on the intermediate memories read by the native code. The
+linker reads its own tag and appends its stage-transfer write to each report.
+Every other cell below the descriptor workspace survives every returning call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+open scoped Fin.CommRing
+open private startupStage from OAI.Computability.VPVNP.LiveCompressedPairCursorStartup
+
+variable {w d initial phases : ℕ} {C : Catalog d}
+variable (b : Bootstrap) (pub : Fin 11 → Word w) (B n base : ℕ) (m : Memory w)
+
+/-- The frames of the eight source traces persist after their actual linker writes. -/
+theorem cursorStartup_frame (runs : TransferredStartup.Runs (bootstrapRows b initial phases) d
+ (startupLayout b initial phases B n base) B n b.degreeBits b.lanesPerBlock b.steps pub (PairTag.address pub) m)
+ (x : ℕ) (hx : x < base) (ht : x ≠ (PairTag.address pub).val) :
+ ReplayFrame x m (cursorStartupLogs b pub B n base m initial phases d) := by
+ let t := startupTrace b pub B n base m initial phases d
+ let tag := PairTag.address pub
+ let entries := t.entry tag m
+ apply ReplayFrame.ofFn entries (startupReport b pub B n base m initial phases d)
+ · intro i
+ change after (entries i.castSucc) (report pub (startupStage i.castSucc) (t.source i)).events = _
+ rw [(report_effect pub _ _ _).2.2.2]
+ have hclosed : (t.source i).result = none := TransferredStartup.source_closed ..
+ have hn : next (startupStage i.castSucc) = some (startupStage i.succ) := by
+ have h : (startupStage i.castSucc).val+1 < 10 := by change i.val+1 < 10; omega
+ exact dite_eq_left h
+ rw [hclosed,hn]
+ exact (t.transfer tag m i).symm
+ · intro i
+ exact (runs.entry_below i.succ x hx ht).trans (runs.entry_below i.castSucc x hx ht).symm
+
+/-- The linked startup's full event log leaves the original protected word
+in the memory supplied to the online calendar. -/
+theorem cursorStartup_after_below (runs : TransferredStartup.Runs (bootstrapRows b initial phases) d
+ (startupLayout b initial phases B n base) B n b.degreeBits b.lanesPerBlock b.steps pub (PairTag.address pub) m)
+ (x : ℕ) (hx : x < base) (ht : x ≠ (PairTag.address pub).val) :
+ after m (eventLog (cursorStartupLogs b pub B n base m initial phases d)) x = m x :=
+ ReplayFrame.after_eventLog _ _ (cursorStartup_frame b pub B n base m runs x hx ht)
+
+variable (plan : Online.Config C initial phases) (finalTable : PairTable) (clock : ℕ)
+
+/-- Protect an address on every continuing history of the native pair, using
+the established frames of its online and final-stage calls. -/
+theorem protectsAddress_startup (fit : 10 ≤ 2^w)
+ (runs : TransferredStartup.Runs (bootstrapRows b initial phases) d (startupLayout b initial phases B n base)
+ B n b.degreeBits b.lanesPerBlock b.steps pub (PairTag.address pub) m)
+ (start : StartupResult b plan finalTable pub B n base m clock)
+ (x : ℕ) (hx : x < base) (ht : x ≠ (PairTag.address pub).val)
+ (online : Protected b plan finalTable pub clock Stage.online
+ (after m (eventLog (cursorStartupLogs b pub B n base m initial phases d))))
+ (terminal : ∀ p : StagePaths b plan finalTable pub clock Stage.online
+ (after m (eventLog (cursorStartupLogs b pub B n base m initial phases d))),
+ Protected b plan finalTable pub clock Stage.terminal (onlinePost p))
+ (onlineFrame : online.word x) (terminalFrame : ∀ p, (terminal p).word x) :
+ ProtectsAddress (program b plan finalTable pub) clock 0 m x := by
+ apply protects_after_replayed_prefix start.executed start.cursor (cursorStartup_frame b pub B n base m runs x hx ht)
+ apply ProtectsAddress.of_invariant (Phase online terminal) (Phase.start online terminal start.tagged)
+ exact fun active run cont => Phase.step online terminal fit x ht onlineFrame terminalFrame active run cont
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairStartupInputs.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairStartupInputs.lean
new file mode 100644
index 0000000000..f7e7b4a4f7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairStartupInputs.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.LiveProgramCompressedPair
+import OAI.Computability.VPVNP.LiveLayoutWordFit
+
+/-!
+# Cursor startup inputs in the live pair ABI
+
+The pair gets its workspace, input length and address width from public slots
+two, six and seven. Its dispatch tag is the first old-state word, below the
+auxiliary shadow and the cursor workspace. For a polynomially bounded bucket
+size all four addresses or values fit the paper's word width eventually.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM Filter
+
+/-- The old-state tag precedes the entire cursor workspace, for every layout. -/
+theorem tag_before_workspace (c : Constants) (g : Geometry) :
+ (Layout.oldState c).eval g < (Layout.pairWorkspace c).eval g := by
+ change (Layout.oldState c).eval g <
+ (((((((Layout.oldState c).eval g + c.configWords.eval g) + c.configWords.eval g) + 5) + 24) +
+ c.prefixCapacity.eval g) + c.labels.eval g) + 2^(Layout.virtualSiteBits.eval g)
+ apply lt_of_lt_of_le _ (Nat.le_add_right ..)
+ omega
+
+/-- Read the three startup words and the address computed by the actual tag prologue.
+Their values are independent of the literal-prefix operands in slots zero and one. -/
+theorem startup_inputs (c : Constants) (g : Geometry) (lit : LiteralPrefix)
+ (workspace : (Layout.pairWorkspace c).eval g < 2^g.w) (length : g.n < 2^g.w)
+ (address : g.d < 2^g.w) :
+ let pub := Pieces.word g lit ∘ StageOperands.pair c
+ (pub 2).val = (Layout.pairWorkspace c).eval g ∧ (pub 6).val = g.n ∧
+ (pub 7).val = g.d ∧ (PairTag.address pub).val < (pub 2).val := by
+ intro pub
+ have hw : (pub 2).val = (Layout.pairWorkspace c).eval g := Nat.mod_eq_of_lt workspace
+ refine ⟨hw, Nat.mod_eq_of_lt length, Nat.mod_eq_of_lt address, ?_⟩
+ have lower := tag_before_workspace c g
+ have old : (Pieces.word g lit (.geometry (Layout.oldState c))).val = (Layout.oldState c).eval g :=
+ Nat.mod_eq_of_lt (lower.trans workspace)
+ change (PairTag.address (Pieces.word g lit ∘ StageOperands.pair c)).val < (pub 2).val
+ rw [hw, tag_address, old]
+ exact lower
+
+/-- The workspace addresses form a polynomially bounded sequence even though
+their offset includes every site of the virtual auxiliary RAM. -/
+theorem startup_workspace_polynomial (c : Constants) {B : ℕ} {H : ℕ → ℕ}
+ (hB : 1 ≤ B) (hH : PolynomiallyBounded H) :
+ PolynomiallyBounded (fun n => (Layout.pairWorkspace c).eval (paperGeometry B H n)) :=
+ ((Layout.pairWorkspace_sitePowers c).fits hB hH).1
+
+/-- One length threshold works for every literal program prefix. -/
+theorem eventually_startup_inputs (c : Constants) {B : ℕ} {H : ℕ → ℕ}
+ (hB : 1 ≤ B) (hH : PolynomiallyBounded H) :
+ ∀ᶠ n : ℕ in atTop, ∀ lit : LiteralPrefix,
+ let g := paperGeometry B H n
+ let pub := Pieces.word g lit ∘ StageOperands.pair c
+ (pub 2).val = (Layout.pairWorkspace c).eval g ∧ (pub 6).val = n ∧
+ (pub 7).val = CursorBounds.addressBits B n ∧ (PairTag.address pub).val < (pub 2).val := by
+ filter_upwards [((Layout.pairWorkspace_sitePowers c).fits hB hH).2,
+ (PublicExpr.SitePowers.fits hB hH (e := .n) trivial).2,
+ (PublicExpr.SitePowers.fits hB hH (e := .d) trivial).2] with n space length address
+ exact fun lit => startup_inputs c (paperGeometry B H n) lit space.1 length.1 address.1
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairStartupRun.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairStartupRun.lean
new file mode 100644
index 0000000000..f598e22fcf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairStartupRun.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.LiveCompressedPairCursorStartup
+import OAI.Computability.VPVNP.LiveCompressedPairStartupInputs
+import OAI.Computability.VPVNP.LiveCompressedPairInitialTag
+
+/-!
+# Physical cursor startup at the paper's dimensions
+
+The fixed compressed pair executes eight native calls on the actual eleven
+public operands. One logarithmic private clock covers every call, uniformly
+over the program prefix and incoming memory. The auxiliary shadow-copy stage
+supplies the row counter's initial tag by `PreparedBranch.startup_tag`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM CursorBounds CompressorRecords CompressorRecords.Schedule
+open scoped Fin.CommRing
+
+variable {d initial phases : ℕ} {C : Catalog d}
+
+/-- For the physical pair ABI, one logarithmic clock suffices at every large
+input length. The incoming tag condition is the one established by the
+preceding auxiliary preparation. -/
+theorem eventually_physical_startup (c : Constants) (b : Bootstrap)
+ (plan : Online.Config C initial phases) (terminal : PairTable) (B : ℕ) {H : ℕ → ℕ}
+ (hB : 1 ≤ B) (hH : PolynomiallyBounded H) (hq : 0 < b.denominator) (hph : 0 < phases)
+ (hθ : (b.numerator : ℝ)/b.denominator ≤ 1) (hlanes : b.lanesPerBlock ≤ B)
+ (hArity : b.shape.arity = arity C) (arityFit : 7 ≤ b.shape.arity) (scalars : 30 ≤ b.shape.scalarFields) :
+ ∃ K : ℕ, ∀ᶠ n : ℕ in Filter.atTop, ∀ (lit : LiteralPrefix) (m : Memory (wordBits B n)) (cap : ℕ),
+ let g := paperGeometry B H n
+ let pub := Pieces.word g lit ∘ StageOperands.pair c
+ let base := (Layout.pairWorkspace c).eval g
+ m (PairTag.address pub).val = 0 → K*(n.log2+1) ≤ cap →
+ StartupResult b plan terminal pub B n base m cap := by
+ let D := bootstrapRows b initial phases
+ let base n := (Layout.pairWorkspace c).eval (paperGeometry B H n)
+ have hb : PolynomiallyBounded base := startup_workspace_polynomial c hB hH
+ obtain ⟨K,clock⟩ := sourceFuel_log b initial phases 30
+ refine ⟨K,?_⟩
+ filter_upwards [eventually_startup_inputs c hB hH,
+ TransferredStartup.eventually_run D d b.shape B b.degreeBits b.lanesPerBlock b.steps hB hq hph hθ
+ hlanes arityFit scalars hb,
+ DescriptorParameters.eventually_tight_end D b.shape B b.steps hB hb, Filter.eventually_ge_atTop 10]
+ with n args start room size
+ intro lit m cap g pub address initialTag large
+ obtain ⟨hbase,len,width,tagBelow⟩ := args lit
+ change (pub 6).val = n at len
+ have hn : n < 2^wordBits B n := len.symm.trans_lt (pub 6).isLt
+ have tagFit : 10 ≤ 2^wordBits B n := size.trans hn.le
+ have lower : (PairTag.address pub).val < base n := lt_of_lt_of_eq tagBelow hbase
+ have runs := start pub (PairTag.address pub) hbase len width lower m
+ exact cursor_startup b plan terminal pub B n address m cap hArity tagFit (fun i ↦ (clock n i).trans large)
+ initialTag runs hn scalars room
+
+/-- A nonempty calendar runs its first online dispatch directly on the native
+pair program, using the memory and tag left by the eight linked startup calls. -/
+theorem StartupResult.first_online {w B n base cap : ℕ} {b : Bootstrap} {plan : Online.Config C initial phases}
+ {terminal : PairTable} {pub : Fin 11 → Word w} {m : Memory w}
+ (done : StartupResult b plan terminal pub B n base m cap)
+ (positive : 0 < (CalendarRows.rows (bootstrapRows b initial phases) n : Word w))
+ (j : Fin (initial+phases)) (hj : j.val = 0) (fit : 10 ≤ 2^w)
+ (onlineFit : Online.N d (initial+phases) ≤ 2^w) {innerCap : ℕ}
+ (budget : 30+2*(initial+phases)+2*Online.N d (initial+phases)+5 ≤ innerCap) :
+ let mem := after m (eventLog (cursorStartupLogs b pub B n base m initial phases d))
+ let p := Workspace.ports (arity C) (pub 2)
+ let online := Online.linked p (Online.calendarIndex d (initial+phases))
+ (LevelCalendar.dispatchReport (Online.calendar plan) p.data mem (Online.phaseIndex plan j))
+ let P := program b plan terminal pub
+ execute P (innerCap+24+30) (P.start 0) mem [] = some (report pub Stage.online (Workspace.report (pub 2) mem online)) := by
+ intro mem p online P
+ have dispatch := OnlineWorkspace.first_dispatch plan pub 0 mem _ _ done.ready positive j hj onlineFit budget
+ exact execute_stage b plan terminal pub Stage.online fit (innerCap+24) _ le_rfl 0 mem done.tagged [] _ dispatch
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairTerminalAssembly.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairTerminalAssembly.lean
new file mode 100644
index 0000000000..adaeed73c8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairTerminalAssembly.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.LiveCompressedPairReindex
+import OAI.Computability.VPVNP.PairSimulationTerminalDataPaths
+import OAI.Computability.VPVNP.PairSimulationTerminalProgram
+
+/-!
+# The compressed pair with the five-stage terminal table
+
+For each selected descriptor branch, the genuine terminal program runs on
+the online stage's transferred memory. Its deterministic setup, shared-bit
+scan and per-site witnesses give a single branch-indexed equivalence for the
+complete eleven-word pair table and its actual dense-counter readback.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM CompressorRecords CompressorRecords.Schedule PairSimulation LocalHistory NetworkKernel
+open PairStages.Group.CompressedPaths
+
+variable {d initial phases : ℕ} {C : Catalog d} (b : Bootstrap) (plan : Online.Config C initial phases)
+variable (shape : DescriptorSpace.Shape) (limit : ℕ) (segments : VertexImage.Part → VertexImage.Segment)
+variable (G : PairStages.Group) (B n base : ℕ) (m : Memory G.w)
+
+/-- The outer table already separates enough word values for all 32
+terminal-header offsets. -/
+theorem terminal_tag_fits (G : PairStages.Group) : 32 ≤ 2^G.w := by
+ by_cases h : 5 ≤ G.w
+ · exact (by decide : 32 ≤ 2^5).trans (Nat.pow_le_pow_right (by decide) h)
+ · have small := Nat.pow_le_pow_right (n := 2) (by decide) (show G.w ≤ 4 by omega)
+ have hf : 21 ≤ 2^G.w := G.tagFit
+ norm_num at small
+ omega
+
+/-- Both nested dispatches leave the private clock needed for the shared
+bit phase, including its bounded source-to-physical replay. -/
+theorem terminal_clock_fits (G : PairStages.Group) (hc : 154 ≤ G.clock) :
+ 54 ≤ clockAt (publicWords G) (fuel G) Stage.terminal := by
+ have outer : (LiveStageLink.dispatchEvents G.addr LiveProgram.Stage.pair).length ≤ 44 := by
+ simp only [LiveStageLink.dispatchEvents,List.length_cons,List.length_replicate]
+ decide
+ have inner : (LiveStageLink.dispatchEvents (PairTag.address (publicWords G)) Stage.terminal).length = 22 := by
+ simp only [LiveStageLink.dispatchEvents,List.length_cons,List.length_replicate]
+ decide
+ change 54 ≤ (G.clock - (LiveStageLink.dispatchEvents G.addr LiveProgram.Stage.pair).length) - 5 -
+ (LiveStageLink.dispatchEvents (PairTag.address (publicWords G)) Stage.terminal).length
+ omega
+
+/-- The static five-worker program for the particular fixed pair. -/
+noncomputable abbrev terminalBody := TerminalProgram.table shape limit segments
+
+variable {b plan shape limit segments G B n base m}
+variable (S : PhysicalStages b plan (terminalBody shape limit segments) G B n base m)
+
+local notation "operands" => publicWords G
+local notation "clock" => fuel G
+local notation "finalTable" => terminalBody shape limit segments
+local notation "startup" => cursorStartupLogs b operands B n base m initial phases d
+local notation "entry" => after m (eventLog startup)
+
+variable {Z I : Type*} (descriptorPaths :
+ Z ≃ StagePaths b plan (terminalBody shape limit segments) (publicWords G) (fuel G) Stage.online
+ (after m (eventLog (cursorStartupLogs b (publicWords G) B n base m initial phases d))))
+
+/-- A selected terminal execution uses three forced metadata stages, then a
+shared arc phase and a vertex phase for that specific arc assignment. -/
+structure TerminalBranchData {w : ℕ} (workers : TerminalLink.Stage → PairTable) (ports : Fin 11 → Word w)
+ (f : ℕ) (mem : Memory w) {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A}
+ {N : Network} (sc : ScanPhase N) (P : SiteParsers κ N) where
+ /-- The deterministic terminal prefix on the selected online path's post-memory. -/
+ setup : TerminalLink.QuietPrefix workers ports f mem
+ /-- The equivalence between the mathematical shared-wire scan paths and the terminal prefix's
+ native bit paths. -/
+ bitPaths : sc.Path ≃ setup.BitPaths
+ /-- For each shared-bit path, the equivalence between the sites' witness choices and the
+ native vertex paths on that assignment. -/
+ vertexPaths : ∀ a : sc.Path,
+ (∀ v, (P.witnesses v (WireTensor.edgeAssignment N.src N.dst (sc.payload a) v)).Choice) ≃
+ setup.VertexPaths (bitPaths a)
+
+attribute [local irreducible] regs components TerminalProgram.workers
+
+/-- The terminal setup, shared-bit paths, and vertex-path evidence specialized to one selected
+descriptor path. -/
+noncomputable abbrev TerminalBranch {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A}
+ {N : Network} (sc : ScanPhase N) (P : SiteParsers κ N) (z : Z) :=
+ TerminalBranchData (TerminalProgram.workers shape limit segments) (publicWords G)
+ (clockAt (publicWords G) (fuel G) Stage.terminal) (onlinePost (descriptorPaths z)) sc P
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {N : Z → Network}
+variable {sc : (z : Z) → ScanPhase (N z)} {sites : (z : Z) → SiteParsers κ (N z)}
+variable (tagFits : 32 ≤ 2^G.w) (clockFits : 26 ≤ clockAt (publicWords G) (fuel G) Stage.terminal)
+variable (branches : ∀ z : Z, TerminalBranch descriptorPaths (sc z) (sites z) z)
+variable (emit : (Σ z : Z, TerminalData (sc z) (sites z)) ≃ I)
+
+/-- Identify the mathematical terminal data of a descriptor choice with accepted executions of
+its actual terminal program. -/
+noncomputable def terminalPaths (z : Z) :
+ TerminalData (sc z) (sites z) ≃
+ ActualPaths (original b plan finalTable operands Stage.terminal) (clockAt operands clock Stage.terminal)
+ 0 (onlinePost (descriptorPaths z)) (fun _ => True) :=
+ (branches z).setup.dataPaths (branches z).bitPaths (branches z).vertexPaths tagFits clockFits (fun _ => True)
+ (fun _ => trivial)
+
+/-- Combine startup, descriptor choices, and terminal witnesses to identify the full emitted
+index with a raw accepted pair path. -/
+noncomputable def PhysicalStages.reindexTerminal : I ≃ Raw G m :=
+ S.reindex emit descriptorPaths (terminalPaths descriptorPaths tagFits clockFits branches)
+
+theorem PhysicalStages.reindexTerminal_tapes (z : Z) (x : TerminalData (sc z) (sites z)) :
+ (S.reindexTerminal descriptorPaths tagFits clockFits branches emit (emit ⟨z,x⟩)).val =
+ List.replicate 8 [] ++ ((descriptorPaths z).val ++
+ ((branches z).setup.trace ((branches z).bitPaths x.arcs) ((branches z).vertexPaths x.arcs x.choices)).choices) := by
+ rw [reindexTerminal,reindex_tape]
+ rfl
+
+theorem PhysicalStages.reindexTerminal_logs (z : Z) (x : TerminalData (sc z) (sites z)) :
+ reports (S.reindexTerminal descriptorPaths tagFits clockFits branches emit (emit ⟨z,x⟩)) =
+ startup ++ (onlineReports (descriptorPaths z) ++
+ (TerminalLink.reports (TerminalLink.header operands)
+ ((branches z).setup.trace ((branches z).bitPaths x.arcs) ((branches z).vertexPaths x.arcs x.choices)).logs).map
+ (report operands Stage.terminal)) := by
+ rw [reindexTerminal,reindex_logs]
+ congr 3
+ exact TerminalLink.QuietPrefix.dataPaths_logs ..
+
+theorem PhysicalStages.reindexTerminal_after (z : Z) (x : TerminalData (sc z) (sites z)) :
+ after m (eventLog (reports (S.reindexTerminal descriptorPaths tagFits clockFits branches emit (emit ⟨z,x⟩)))) =
+ ((branches z).vertexPaths x.arcs x.choices).val.memory := by
+ rw [reindexTerminal,reindex_after]
+ exact TerminalLink.QuietPrefix.dataPaths_after ..
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairTerminalCharge.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairTerminalCharge.lean
new file mode 100644
index 0000000000..cabbe98543
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairTerminalCharge.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.PairTraversalControllerMemory
+import OAI.Computability.VPVNP.PairTerminalPrefixSegment
+import OAI.Computability.VPVNP.PairSimulationFinalBitScan
+import OAI.Computability.VPVNP.CursorBranchCommunication
+
+/-!
+# Communication of the five native terminal stages
+
+The final outgoing-arc prefix scan, tagged history-directory construction,
+shared-bit guesses, and vertex evaluations all run on the same selected
+network. This calculation includes the closing reports and the two complete
+passes over the history directories, including their repeated operand reads.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM Compression CursorNetwork NetworkKernel PairSimulation CompressorRecords
+open LocalHistory
+
+variable {w : ℕ}
+
+private theorem ofFn_cost {n : ℕ} (rs : Fin n → Report w) :
+ RAMBuckets.cost Report.probes (List.ofFn rs) = ∑ i, (1+(rs i).probes) := by
+ induction n with
+ | zero => simp [RAMBuckets.cost]
+ | succ n ih => rw [List.ofFn_succ,RAMBuckets.cost,Fin.sum_univ_succ,ih]
+
+theorem arc_count_positions {a g : ℕ} (Y : State a g) : TerminalPrefix.arcCount Y = Y.positions*2^a := by
+ have h : (siteOrder Y).length = Y.positions := by
+ change (siteOrder Y).length = Fintype.card Y.network.Site
+ simpa only [Fintype.card_fin] using Fintype.card_congr (siteOrder Y).entries
+ exact congrArg (· * 2^a) h
+
+/-- Fixed coefficient for the initial header, both row-building passes,
+the wire-prefix and shared-bit scans, and all vertex reports. -/
+def terminalCoefficient (degree steps recordLimit bootstrap close site : ℕ) :=
+ bootstrap+close+9+8*degree+(2*recordLimit+1294)*(steps+2)+4+site
+
+private theorem terminalEstimate {xp yp wt occ l q degree steps term limit boot close site : ℕ}
+ (hx : 1 ≤ xp) (hl : 1 ≤ l) (ht : term ≤ l) (hq : 1 ≤ q) :
+ boot+close+9+8*(yp*degree)+(2*limit+1294)*(((steps+1)*term+1)*xp)+4*wt+
+ site*(xp*l^q+3*wt+yp+occ*l^q) ≤
+ terminalCoefficient degree steps limit boot close site*(xp*l^q+3*wt+yp+occ*l^q) := by
+ let total := xp*l^q+3*wt+yp+occ*l^q
+ have hlq := Nat.pow_le_pow_right hl hq
+ rw [pow_one] at hlq
+ have x : 1 ≤ total := by
+ have hp := Nat.mul_le_mul hx (hl.trans hlq)
+ dsimp only [total]; omega
+ have t : (steps+1)*term+1 ≤ (steps+2)*l := by
+ have := Nat.mul_le_mul_left (steps+1) ht
+ nlinarith only [this,hl]
+ have hc := Nat.mul_le_mul_right xp t
+ rw [show ((steps+2)*l)*xp = (steps+2)*(xp*l) by ring] at hc
+ have hxl : xp*l ≤ total := by
+ exact (Nat.mul_le_mul_left _ hlq).trans (by dsimp [total]; omega)
+ have hstage := Nat.mul_le_mul_left (2*limit+1294) (hc.trans (Nat.mul_le_mul_left _ hxl))
+ rw [← Nat.mul_assoc (2*limit+1294) (steps+2) total] at hstage
+ have hy : yp ≤ total := by dsimp [total]; omega
+ have hw : wt ≤ total := by dsimp [total]; omega
+ have hb := Nat.mul_le_mul_left (boot+close+9) x
+ have hp := Nat.mul_le_mul_left (8*degree) hy
+ have hf := Nat.mul_le_mul_left 4 hw
+ change _ ≤ terminalCoefficient degree steps limit boot close site*total
+ calc
+ _ ≤ (boot+close+9)*total+(8*degree)*total+((2*limit+1294)*(steps+2))*total+4*total+site*total := by
+ rw [show 8*(yp*degree)=(8*degree)*yp by ring]
+ exact Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add
+ (by simpa only [Nat.mul_one] using hb) hp) hstage) hf) _
+ _ = _ := by unfold terminalCoefficient; ring
+
+/-- Bound the actual bootstrap, wire-prefix, history-table, final-bit and
+per-vertex report lists by the compressed branch's geometric charge. The
+history constructor supplies its two-pass charge and the vertex routines
+supply their own occurrence-by-occurrence charges. -/
+theorem terminal_source_charge {A : Type*} {a b g h : ℕ}
+ (X : State a g) (Y : State b h) (chain : TermChain A X.network Y.network)
+ (pub : Fin 11 → Word w) (bootstrap close : Report w) (bootBound closeBound : ℕ)
+ (hboot : bootstrap.probes ≤ bootBound) (hclose : close.probes ≤ closeBound)
+ {dir : IncidenceDirectory w} {base : Word w} {prefixMemory : Memory w} {prefixRows : List (Report w)}
+ (scan : TerminalPrefix.Segment.Run pub Y dir base prefixMemory prefixRows)
+ (arena : List (Report w)) (steps limit T : ℕ)
+ (ha : RAMBuckets.cost Report.probes arena ≤ (2*limit+1294)*(((steps+1)*T+1)*X.positions))
+ (bitMemory : Memory w) (bits : Fin Y.totalWidth → Bool)
+ (vertex : Y.network.Site → Report w) (site q n : ℕ) (hq : 1 ≤ q) (hT : T ≤ n.log2+1)
+ (hsite : ∀ v, 1+(vertex v).probes ≤ siteAccesses Y chain site q n v) :
+ let visits := List.ofFn fun i => vertex ((siteOrder Y).entries i)
+ let rs := [bootstrap] ++ prefixRows ++ arena ++ FinalBits.Worker.reports pub 0 bitMemory bits ++ visits ++ [close]
+ RAMBuckets.cost Report.probes rs ≤
+ branchAccesses X Y chain (terminalCoefficient (2^b) steps limit bootBound closeBound site) q n := by
+ intro visits rs
+ have hv : RAMBuckets.cost Report.probes visits ≤ ∑ v, siteAccesses Y chain site q n v := by
+ change RAMBuckets.cost _ (List.ofFn _) ≤ _
+ rw [ofFn_cost]
+ calc
+ _ ≤ ∑ i, siteAccesses Y chain site q n ((siteOrder Y).entries i) :=
+ Finset.sum_le_sum (fun _ _ => hsite _)
+ _ = _ := (siteOrder Y).entries.sum_comp _
+ have sub : (∑ v, siteAccesses Y chain site q n v) ≤ branchAccesses X Y chain site q n :=
+ Nat.le_add_left ..
+ have verts := hv.trans sub
+ rw [branchAccesses_eq] at verts ⊢
+ have pref := scan.charge
+ rw [arc_count_positions] at pref
+ have wire := (FinalBits.Worker.scan_cost pub _ 0 bitMemory bits).2.1
+ simp only [rs,RAMBuckets.cost_append,RAMBuckets.cost, Nat.add_zero]
+ rw [pref,wire]
+ have estimate := @terminalEstimate X.positions Y.positions Y.totalWidth (totalOccurrences chain)
+ (n.log2+1) q (2^b) steps T limit bootBound closeBound site X.positions_pos (Nat.succ_pos _) hT hq
+ apply le_trans _ estimate
+ omega
+
+/-- The local cap on the same chronological reports, including both
+guard closures and all external reads from the history directories. -/
+theorem terminal_source_rows {a g : ℕ} (Y : State a g) (pub : Fin 11 → Word w)
+ (bootstrap close : Report w) (H fuel : ℕ)
+ (hboot : bootstrap.probes+9 ≤ H ∧ bootstrap.events.length+107 ≤ fuel)
+ (hclose : close.probes+9 ≤ H ∧ close.events.length+107 ≤ fuel)
+ {dir : IncidenceDirectory w} {base : Word w} {prefixMemory : Memory w} {prefixRows : List (Report w)}
+ (scan : TerminalPrefix.Segment.Run pub Y dir base prefixMemory prefixRows)
+ (arena : List (Report w)) (arenaBound : ∀ r ∈ arena, r.probes+9 ≤ H ∧ r.events.length+107 ≤ fuel)
+ (bitMemory : Memory w) (bits : Fin Y.totalWidth → Bool) (vertex : Y.network.Site → Report w)
+ (siteBound : ∀ v, (vertex v).probes+9 ≤ H ∧ (vertex v).events.length+107 ≤ fuel)
+ (hH : 16 ≤ H) (hfuel : 136 ≤ fuel) :
+ let visits := List.ofFn fun i => vertex ((siteOrder Y).entries i)
+ let rs := [bootstrap] ++ prefixRows ++ arena ++ FinalBits.Worker.reports pub 0 bitMemory bits ++ visits ++ [close]
+ ∀ r ∈ rs, r.probes+9 ≤ H ∧ r.events.length+107 ≤ fuel := by
+ intro visits rs r hr
+ simp only [rs,List.mem_append,List.mem_singleton] at hr
+ rcases hr with ((((rfl | h) | h) | h) | h) | rfl
+ · exact hboot
+ · have ⟨p,t⟩ := scan.bounds r h
+ exact ⟨by omega,by omega⟩
+ · exact arenaBound r h
+ · have ⟨p,t⟩ := (FinalBits.Worker.scan_cost pub _ 0 bitMemory bits).2.2 r h
+ exact ⟨by omega,by omega⟩
+ · obtain ⟨i,rfl⟩ := List.mem_ofFn.mp h
+ exact siteBound _
+ · exact hclose
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairTerminalShare.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairTerminalShare.lean
new file mode 100644
index 0000000000..dc5091d00e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairTerminalShare.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.LiveCompressedPairTerminalCharge
+import OAI.Computability.VPVNP.LiveCompressedPairReportCaps
+import OAI.Computability.VPVNP.CompressorDirectoryBudget
+import OAI.Computability.VPVNP.PairLinkSlack
+
+/-! # A uniform share of the live budget for the entire terminal traversal -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open Compression CursorNetwork CursorBounds NetworkKernel Filter BurstRAM
+open private blocks_le_log from OAI.Computability.VPVNP.CompressorDirectoryBudget
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+/-- A single length threshold covers every selected history and every
+final vertex. The resource estimates use only the fixed program constants. -/
+theorem eventually_terminal_share (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) (boot close site q : ℕ) :
+ let C := terminalCoefficient S.baseDegree S.steps B.recordLimit boot close site
+ ∀ᶠ n : ℕ in atTop,
+ let T := blockCount (u.θ : ℝ) n
+ T ≤ n.log2+1 ∧ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : T*S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let E := B.execute f hf T hT X
+ ∀ z : E.Choices,
+ let Y := E.finalState z
+ let chain := E.termChain (B.records f hf T hT X) z
+ 320*branchAccesses X Y chain C q n ≤ processorCount b n * liveCapacity u n ∧
+ ∀ v, siteAccesses Y chain site q n v + 9 ≤ liveCapacity u n := by
+ intro C
+ filter_upwards [eventually_pairAccesses B u b hb C q (ε := 1/320) (by norm_num),
+ eventually_pairBurstSlack u 9, eventually_ge_atTop 1] with n estimates margin hn
+ intro T
+ refine ⟨blocks_le_log B u hn,?_⟩
+ intro base lanes labels hD hT A _ f hf X E z Y chain
+ have result := estimates labels hD hT A f hf z
+ rw [liveCapacity_eq]
+ refine ⟨integer_cost_share (by decide : 0<320) result.1,?_⟩
+ intro v
+ have hsite : siteAccesses Y chain site q n v ≤ siteAccesses Y chain C q n v := by
+ apply Nat.mul_le_mul_right
+ exact Nat.le_add_left ..
+ have small := (Nat.cast_le.mpr hsite : (siteAccesses Y chain site q n v : ℝ) ≤ _).trans (result.2.1 v)
+ have lim : (siteAccesses Y chain site q n v : ℝ)+9 ≤ (liveBucket u.δ n : ℝ) := by
+ exact (add_le_add_left small 9).trans margin
+ exact_mod_cast lim
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairVertexAssembly.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairVertexAssembly.lean
new file mode 100644
index 0000000000..28f11d6cf5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairVertexAssembly.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.LiveCompressedPairTerminalAssembly
+import OAI.Computability.VPVNP.PairSimulationPhysicalScanData
+import OAI.Computability.VPVNP.PairVertexOrdinalPhase
+import OAI.Computability.VPVNP.PairVertexAscendingCosts
+
+/-!
+# Building a terminal branch from the actual wire scan and site table
+
+For a selected compression state, the shared-bit worker traverses the
+ordered payload bank and the fixed vertex program runs one burst for each
+site ordinal, followed by the final closing call. The constructor uses the
+source-to-physical replay at the two controller words and leaves exactly
+the selected sum of site exponents at each motif counter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords SourceTransport NetworkKernel
+open PairSimulation LocalHistory TerminalLink
+open scoped Fin.CommRing
+
+attribute [local irreducible] VertexImage.template VertexImage.segments TerminalProgram.workers PhysicalScanData.physical stateScanPhase
+
+variable {a g v p r k : ℕ} (X : State a g) (M : Machine v p r k)
+ (pc : Fin 10 → Fin p) (reg : Fin 2 ↪ Fin r) (bank : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg bank done) (he : M.entry=pc 0)
+ (oldLow : ℕ) (bankAddr : M.publicData bank = FinalBits.cursor v oldLow 0) (oldMem : Memory v)
+ (extra : ℕ) (oldFit : oldLow + X.totalWidth < 2^v)
+
+local notation "scan₀" => stateScanPhase X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+
+variable {w cap ns labels : ℕ} {R : Type*} [CommRing R] {Label : Type} [Fintype Label] {κ : Label → R}
+ (parsers : SiteParsers κ X.network) (order : Fin ns ≃ X.network.Site) (names : Fin labels ≃ Label)
+ (shape : DescriptorSpace.Shape) (limit : ℕ) {geometry rootFields leaf shrink refresh : VertexImage.Segment}
+ (ports : Fin 11 → Word w)
+
+local notation "code" => VertexImage.segments geometry rootFields leaf shrink refresh
+local notation "workers₀" => TerminalProgram.workers shape limit code
+
+variable {mem : Memory w} (q : QuietPrefix (TerminalProgram.workers shape limit (VertexImage.segments geometry rootFields leaf shrink refresh)) ports cap mem)
+ (lo : ℕ) (beforeBits : Memory w) (wireLayout : FinalBits.Worker.Layout ports beforeBits lo X.totalWidth)
+ (clockRoom : 54 ≤ cap) (headerRoom : (header ports).val + 32 ≤ 2^w)
+ (below : lo + X.totalWidth ≤ (header ports).val)
+ (readAgree : Agree (workerCell (header ports)) beforeBits q.traversalRows.val.memory)
+
+local notation "shared" => PhysicalScanData.physical X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ shape limit code ports cap beforeBits q.traversalRows.val.memory lo wireLayout clockRoom headerRoom below readAgree
+
+variable (counter grammar : ℕ)
+local notation "siteFields" x => WireTensor.edgeAssignment X.network.src X.network.dst (ScanPhase.payload scan₀ x)
+local notation "ordinal" x => VertexImage.siteOrdinals parsers order names (siteFields x)
+local notation "machine₀" => Machine.program (Template.instantiate (VertexImage.template code) w ports)
+
+/-- Local physical facts still needed for each single active site burst.
+The ascending traversal, source-to-controller replay and wire assignment
+are constructed by the terminal branch below. -/
+structure SelectedSites (x : (scan₀).Path) where
+ /-- Memory against which the worker checks the unchanged descriptor cells. -/
+ reference : Memory w
+ /-- Memory from which the unlinked ascending vertex worker starts. -/
+ sourceMem : Memory w
+ active : VertexImage.ActiveCalls (ordinal x) machine₀ cap counter grammar
+ (VertexFrame.Linked (header ports) counter grammar labels reference)
+ stored : ∀ m, VertexFrame.Linked (header ports) counter grammar labels reference ns m →
+ m (TerminalSiteStart.headerWord ports + 7).val = (ns : Word w)
+ checks : ∀ (i : Fin ns) (m : Memory w), VertexFrame.Linked (header ports) counter grammar labels reference i.val m →
+ ∀ (y : (ordinal x).Choice i) (rep : Report w),
+ execute machine₀ cap ((machine₀).start (i.val : Word w)) m ((ordinal x).encode i y) = some rep →
+ Reads (workerCell (header ports)) rep.events ∧ rep.events.length+1 ≤ cap-30
+ sourceReady : VertexFrame.Linked (header ports) counter grammar labels reference 0 sourceMem
+ physicalReady : VertexFrame.Linked (header ports) counter grammar labels reference 0 (shared x).val.memory
+ agree : Agree (workerCell (header ports)) sourceMem (shared x).val.memory
+
+variable (visit : ∀ x : (stateScanPhase X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit).Path,
+ SelectedSites X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ parsers order names shape limit ports q lo beforeBits wireLayout clockRoom headerRoom below readAgree counter grammar x)
+
+private theorem siteReplay (x : (scan₀).Path) :
+ WorkerFrame workers₀ ports cap (.resume TerminalLink.Stage.vertices 0) (visit x).sourceMem (shared x).val.memory :=
+ VertexImage.ordinalWorkerFrame (D := ordinal x) (cap := cap) (base := counter) (grammar := grammar)
+ (geometry := geometry) (rootFields := rootFields) (leaf := leaf) (shrink := shrink) (refresh := refresh) shape limit (visit x).reference (visit x).sourceMem (shared x).val.memory
+ (visit x).active (VertexImage.template_closes (geometry := geometry) (rootFields := rootFields) (leaf := leaf) (shrink := shrink) (refresh := refresh) (pub := ports) (by omega : 15 ≤ cap) (visit x).stored) headerRoom
+ (by omega : 45 ≤ cap) (visit x).checks (visit x).sourceReady (visit x).physicalReady (visit x).agree
+
+local notation "replay" => siteReplay X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ parsers order names shape limit ports q lo beforeBits wireLayout clockRoom headerRoom below readAgree counter grammar visit
+
+/-- The two nondeterministic phases of the fixed finite terminal program,
+with every wire bit and site witness interpreted on its selected memory. -/
+noncomputable def selectedTerminalBranch : TerminalBranchData workers₀ ports cap mem scan₀ parsers where
+ setup := q
+ bitPaths := shared
+ vertexPaths x := VertexImage.sitePhysical (Frame := VertexFrame.Linked (header ports) counter grammar labels (visit x).reference) parsers order names (siteFields x) shape limit
+ (visit x).sourceMem (shared x).val.memory (visit x).active (by omega : 15 ≤ cap)
+ (visit x).sourceReady (visit x).stored (replay x)
+
+local notation "branch" => selectedTerminalBranch X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ parsers order names shape limit ports q lo beforeBits wireLayout clockRoom headerRoom below readAgree counter grammar visit
+
+theorem selectedTerminalBranch_tapes (x : (scan₀).Path)
+ (ys : ∀ v, (parsers.witnesses v ((siteFields x) v)).Choice) :
+ ((branch).bitPaths x).val.choices = (scan₀).calls x ++ [[]] ∧
+ ((branch).vertexPaths x ys).val.choices =
+ (List.ofFn fun j => (parsers.read (order j) ((siteFields x) (order j))).encode (ys (order j))) ++ [[]] :=
+ ⟨PhysicalScanData.physical_choices ..,rfl⟩
+
+theorem selectedTerminalBranch_readback (x : (scan₀).Path)
+ (ys : ∀ v, (parsers.witnesses v ((siteFields x) v)).Choice) :
+ Agree (workerCell (header ports)) ((ordinal x).finalMemory counter grammar (visit x).sourceMem
+ (fun j => ys (order j))) ((branch).vertexPaths x ys).val.memory :=
+ VertexImage.physicalSite_memory parsers order names (siteFields x) shape limit (visit x).sourceMem
+ (shared x).val.memory (visit x).active (by omega : 15 ≤ cap) (visit x).sourceReady (visit x).stored (replay x) ys
+
+/-- The gadget-label counter is updated by the sum of the powers of the
+chosen terminal site witnesses. Its incoming value is the actual source word. -/
+theorem selectedTerminalBranch_counter (x : (scan₀).Path)
+ (ys : ∀ v, (parsers.witnesses v ((siteFields x) v)).Choice) (l : Fin labels)
+ (cell : workerCell (header ports) (counter + grammar + l)) :
+ ((branch).vertexPaths x ys).val.memory (counter + grammar + l) =
+ (visit x).sourceMem (counter + grammar + l) +
+ ((∑ v, (parsers.witnesses v ((siteFields x) v)).exponents (ys v) (names l) : ℕ) : Word w) :=
+ VertexImage.physicalSite_histogram parsers order names (siteFields x) shape limit (visit x).sourceMem
+ (shared x).val.memory (visit x).active (by omega : 15 ≤ cap) (visit x).sourceReady (visit x).stored (replay x) ys l cell
+
+/-- The last two native stages contain one scan report per shared bit and
+one charged vertex report per ordinal, followed by their respective guards.
+The bound for a vertex can depend on its selected occurrence tree. -/
+theorem selectedTerminalBranch_rows (x : (scan₀).Path)
+ (ys : ∀ v, (parsers.witnesses v ((siteFields x) v)).Choice)
+ (ok : X.network.Site → Report w → Prop)
+ (checks : ∀ i m, VertexFrame.Linked (header ports) counter grammar labels (visit x).reference i.val m →
+ ∀ (y : (ordinal x).Choice i) r, execute machine₀ cap ((machine₀).start (i.val : Word w)) m
+ ((ordinal x).encode i y) = some r → ok (order i) r) :
+ let bits := PhysicalScanData.assignment X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit x
+ let last := (ordinal x).finalMemory counter grammar (visit x).sourceMem (fun i => ys (order i))
+ ((branch).bitPaths x).val.logs.map Prod.snd = FinalBits.Worker.reports ports 0 beforeBits bits ∧
+ ∃ reps : X.network.Site → Report w, (∀ v, ok v (reps v)) ∧
+ ((branch).vertexPaths x ys).val.logs.map Prod.snd = (List.ofFn fun i => reps (order i)) ++
+ [VertexImage.closingReport ports last] := by
+ intro bits last
+ refine ⟨?_,?_⟩
+ · unfold selectedTerminalBranch PhysicalScanData.physical
+ exact stageLogs_raw (.resume TerminalLink.Stage.sharedBits 0) _
+ · exact VertexImage.physicalSite_rows parsers order names (siteFields x) shape limit (visit x).sourceMem
+ (shared x).val.memory (visit x).active (by omega : 15 ≤ cap) (visit x).sourceReady (visit x).stored
+ (replay x) ys ok checks
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCompressedPairWorkspaceFrame.lean b/lean/OAI/Computability/VPVNP/LiveCompressedPairWorkspaceFrame.lean
new file mode 100644
index 0000000000..8ad123454d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCompressedPairWorkspaceFrame.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.CompressorPrefixFrames
+import OAI.Computability.VPVNP.LiveCompressedPairProtection
+
+/-! # The compressed-pair tags and headers across reachable online calls -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM CompressorRecords CompressorRecords.Schedule BranchSegments
+open LiveStageLink Compression
+
+variable {w d initial phases : ℕ} {C : Catalog d} {b : Bootstrap} {plan : Online.Config C initial phases}
+ {finalTable : PairTable} {pub : Fin 11 → Word w} {clock : ℕ} {s : Stage} {initialMem : Memory w}
+
+/-- Recover the complete native prefix witnessing the reached call boundary. -/
+private theorem SourceReachable.log {cursor : Word w} {mem : Memory w}
+ (h : SourceReachable b plan finalTable pub clock s initialMem cursor mem) :
+ ∃ bs rs, runSegment (original b plan finalTable pub s) (clockAt pub clock s) (some 0) initialMem bs = some rs ∧
+ endState (some 0) rs = some cursor ∧ after initialMem (eventLog rs) = mem := by
+ induction h with
+ | start => exact ⟨[],[],rfl,rfl,rfl⟩
+ | @more st mem bits rep st' _ call returned ih =>
+ obtain ⟨bs,rs,run,state,memory⟩ := ih
+ refine ⟨bs++[bits],rs++[rep],?_,?_,?_⟩
+ · rw [PrimedSchedule.runSegment_append,run]
+ change (runSegment _ _ (endState _ rs) (after initialMem (eventLog rs)) [bits]).map _ = _
+ rw [state,memory,runSegment,call]
+ rfl
+ · rw [endState_append,state]
+ exact returned
+ · rw [SourceWalk.after_append,memory]
+ simp only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil]
+
+/-- Every successful online call reached by the outer component preserves
+each protected word, including a call on a branch that eventually rejects. -/
+theorem SourceReachable.online_keep_of_prefix {lo : ℕ}
+ (stable : ∀ bs rs, runSegment (OnlineWorkspace.program plan pub) (clockAt pub clock Stage.online)
+ (some 0) initialMem bs = some rs → SourceBankFrame.Stable lo initialMem rs)
+ {st : Word w} {mem : Memory w} {bits : List Bool} {r : Report w}
+ (reach : SourceReachable b plan finalTable pub clock Stage.online initialMem st mem)
+ (call : execute (original b plan finalTable pub Stage.online) (clockAt pub clock Stage.online)
+ ((original b plan finalTable pub Stage.online).start st) mem bits = some r) (x : ℕ) (hx : x < lo) :
+ after mem r.events x = mem x := by
+ obtain ⟨bs,rs,run,state,memory⟩ := reach.log
+ have complete : runSegment (OnlineWorkspace.program plan pub) (clockAt pub clock Stage.online) (some 0)
+ initialMem (bs++[bits]) = some (rs++[r]) := by
+ change runSegment (original b plan finalTable pub Stage.online) _ _ _ _ = _
+ rw [PrimedSchedule.runSegment_append,run]
+ change (runSegment _ _ (endState _ rs) (after initialMem (eventLog rs)) [bits]).map _ = _
+ rw [state,memory,runSegment,call]
+ rfl
+ have full := (stable _ _ complete).take_eq (rs++[r]).length x hx
+ rw [List.take_length,SourceWalk.after_append,memory] at full
+ have before := (stable _ _ run).take_eq rs.length x hx
+ rw [List.take_length,memory] at before
+ simpa only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] using full.trans before.symm
+
+variable {R : Type*} [CommSemiring R] {a g c n : ℕ} {X : Compression.State a g}
+variable {E : StateExecution R c n X}
+variable {trace : ExecutionTrace (OnlineWorkspace.program plan pub) (clockAt pub clock Stage.online) E (some 0) initialMem}
+variable {lo : ℕ} (framed : trace.Framed lo)
+
+include framed in
+theorem SourceReachable.online_keep {st : Word w} {mem : Memory w} {bits : List Bool} {r : Report w}
+ (reach : SourceReachable b plan finalTable pub clock Stage.online initialMem st mem)
+ (call : execute (original b plan finalTable pub Stage.online) (clockAt pub clock Stage.online)
+ ((original b plan finalTable pub Stage.online).start st) mem bits = some r) (x : ℕ) (hx : x < lo) :
+ after mem r.events x = mem x :=
+ reach.online_keep_of_prefix (fun _ _ run => framed.stable run) call x hx
+
+/-- The actual recursive online trace supplies the pair linker's invariant. -/
+def onlineProtected (b : Bootstrap) (finalTable : PairTable) (before : (PairTag.address pub).val < lo) :
+ Protected b plan finalTable pub clock Stage.online initialMem :=
+ Protected.ofSource b plan finalTable pub clock Stage.online initialMem
+ (fun reach _ call _ => SourceReachable.online_keep framed reach call _ before)
+
+/-- The same invariant protects the surrounding live tag and the virtual
+header words, for every address below the descriptor pointer bank. -/
+theorem onlineProtected_word (b : Bootstrap) (finalTable : PairTable)
+ (before : (PairTag.address pub).val < lo) (x : ℕ) (hx : x < lo) :
+ (onlineProtected framed b finalTable before).word x :=
+ Protected.ofSource_word b plan finalTable pub clock Stage.online initialMem x
+ (fun reach _ call _ => SourceReachable.online_keep framed reach call _ before)
+ (fun reach _ call => SourceReachable.online_keep framed reach call x hx)
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveConfigGather.lean b/lean/OAI/Computability/VPVNP/LiveConfigGather.lean
new file mode 100644
index 0000000000..d5afc11e2e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveConfigGather.lean
@@ -0,0 +1,289 @@
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import OAI.Computability.VPVNP.RAMTapeWord
+import Mathlib.Data.ZMod.Defs
+import Mathlib.Tactic.Ring
+
+/-!
+# Gathering a live configuration word from contiguous bit cells
+
+One burst call reads the `w` bits of one cut word, least significant first.
+Each source cell must be zero or one. The running sum and binary place are
+machine words; doubling the place at the final bit may wrap. The completed
+word is written once, then the next call processes the next word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveConfigGather
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+/-- A native configuration-gather code block with 32 registers and four public operands. -/
+abbrev Block := Flow 32 4
+/-- The four public operand indices of the configuration-gather worker. -/
+abbrev Pub := Fin 4
+/-- The 32 register indices available to the configuration-gather worker. -/
+abbrev Reg := Fin 32
+variable {w : ℕ}
+
+private def block (first : Op 32 4) (rest : List (Op 32 4)) : Block := straight first rest
+
+/-- The public parameters are source bit base, destination word base, word
+width and word count. A call's persistent word is its destination index. -/
+def load : Block := block (.constant 0 0)
+ [.constant 1 1, .constant 2 2, .publicWord 3 0, .publicWord 4 1, .publicWord 5 2,
+ .publicWord 30 3, .stateWord 7, .guardLt 7 30, .binary .mul 8 7 5, .binary .add 8 3 8,
+ .binary .add 9 4 7, .constant 10 0, .constant 11 0, .constant 12 1]
+
+/-- Read one source cell, verify that it holds a bit, add its place value to the word, and
+advance the bit index and place. -/
+def readBit : Block := block (.binary .add 13 8 10)
+ [.read 14 13, .guardLt 14 2, .binary .mul 15 14 12, .binary .add 11 11 15,
+ .binary .add 12 12 12, .binary .add 10 10 1]
+
+/-- Repeat the bit-reading block until the current word's specified width has been processed. -/
+def scan : Block := .whileLt 10 5 readBit
+
+/-- Write the gathered word at the destination and prepare the next word's cursor. -/
+def save : Block := block (.write 9 11) [.binary .add 29 7 1]
+
+/-- The complete word-gathering flow, from loading operands through the bit scan to the
+destination write. -/
+def body : Block := .seq load (.seq scan save)
+
+/-- The native burst-call template for gathering one word, using the next cursor and word-count
+registers to control its return. -/
+def table := PrimedCounter.Call.template body 29 30
+
+private def put (r : Regs w 32) (l : List (Reg × Word w)) : Regs w 32 :=
+ l.foldl (fun s x => Function.update s x.1 x.2) r
+
+/-- The register bank at scan entry, with source and destination addresses for the current
+word, a zero accumulator, and unit place. -/
+def loaded (pub : Pub → Word w) (state : Word w) (r : Regs w 32) : Regs w 32 :=
+ put r [(0,0), (1,1), (2,2), (3,pub 0), (4,pub 1), (5,pub 2), (30,pub 3),
+ (7,state), (8,pub 0 + state * pub 2), (9,pub 1 + state),
+ (10,0), (11,0), (12,1)]
+
+private theorem load_exec (pub : Pub → Word w) (state : Word w) (r : Regs w 32) (m : Memory w)
+ (h : state < pub 3) : Flow.Exec pub state load r m (List.replicate 15 .tick) (loaded pub state r) m := by
+ apply (Flow.once_sound pub state false load r m ?_).1
+ simp (config := { decide := true }) [load, block, straight, Flow.once, Op.effect, BinaryOp.eval, pure, bind, h]
+ rfl
+
+/-- The register bank after consuming one source bit, including the updated sum, doubled place,
+and incremented bit index. -/
+def advanced (r : Regs w 32) (v : Word w) : Regs w 32 :=
+ put r [(13,r 8 + r 10), (14,v), (15,v * r 12), (11,r 11 + v * r 12),
+ (12,r 12 + r 12), (10,r 10 + r 1)]
+
+private def bitEvents (addr v : Word w) : List (Event w) :=
+ [.tick, .read addr v, .tick, .tick, .tick, .tick, .tick]
+
+private theorem bit_exec (pub : Pub → Word w) (state : Word w) (r : Regs w 32) (m : Memory w)
+ (v : Word w) (hread : m (r 8 + r 10).val = v) (hval : v < r 2) :
+ Flow.Exec pub state readBit r m (bitEvents (r 8 + r 10) v) (advanced r v) m := by
+ apply (Flow.once_sound pub state false readBit r m ?_).1
+ simp (config := { decide := true }) [readBit, block, straight, Flow.once, Op.effect, BinaryOp.eval, pure, bind, hread, hval]
+ constructor <;> rfl
+
+/-- The register bank after incorporating the supplied bits in little-endian order. -/
+def folded (r : Regs w 32) (bs : List Bool) : Regs w 32 :=
+ bs.foldl (fun s b => advanced s (b.toNat : Word w)) r
+
+/-- The loop-test, source-read, and arithmetic events for scanning the given sequence of
+configuration bits. -/
+def scanEvents (r : Regs w 32) : List Bool → List (Event w)
+ | [] => [.tick]
+ | b :: bs => .tick :: (bitEvents (r 8 + r 10) (b.toNat : Word w) ++
+ scanEvents (advanced r (b.toNat : Word w)) bs)
+
+theorem folded_acc (r : Regs w 32) (bs : List Bool) :
+ folded r bs 11 = r 11 + r 12 * (TapeWord.value bs : Word w) := by
+ induction bs generalizing r with
+ | nil => simp [folded, TapeWord.value]
+ | cons b bs ih =>
+ change folded (advanced r _) bs 11 = _
+ rw [ih]
+ change r 11 + (b.toNat : Word w) * r 12 + (r 12 + r 12) * (TapeWord.value bs : Word w) = _
+ simp only [TapeWord.value, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+ ring
+
+private theorem folded_keep (r : Regs w 32) (bs : List Bool) (i : Reg) (hi : i.val < 10 ∨ 15 < i.val) :
+ folded r bs i = r i := by
+ induction bs generalizing r with
+ | nil => rfl
+ | cons b bs ih =>
+ change folded (advanced r _) bs i = _
+ rw [ih]
+ simp only [advanced, put, List.foldl_cons, List.foldl_nil]
+ repeat rw [Function.update_of_ne (by intro he; subst i; exact (by decide : ¬ _) hi)]
+
+private theorem scan_exec (pub : Pub → Word w) (state : Word w) (r : Regs w 32) (m : Memory w)
+ (bs : List Bool) (h1 : r 1 = 1) (h2 : r 2 = 2) (hw : 2 ≤ w)
+ (hlen : (r 10).val + bs.length = (r 5).val)
+ (hr : ∀ (j : ℕ) (hj : j < bs.length), m (r 8 + r 10 + (j : Word w)).val = (bs[j].toNat : Word w)) :
+ Flow.Exec pub state scan r m (scanEvents r bs) (folded r bs) m := by
+ induction bs generalizing r with
+ | nil =>
+ apply Flow.Exec.whileDone
+ change ¬(r 10).val < (r 5).val
+ simp only [List.length_nil, Nat.add_zero] at hlen
+ omega
+ | cons b bs ih =>
+ let v : Word w := b.toNat
+ let s := advanced r v
+ have ht : r 10 < r 5 := by rw [Fin.lt_def]; simp only [List.length_cons] at hlen; omega
+ have hv : m (r 8 + r 10).val = v := by
+ have h := hr 0 (by simp)
+ change m (r 8 + r 10 + 0).val = v at h
+ simpa using h
+ have cap : 4 ≤ 2 ^ w := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ have hb : v < r 2 := by
+ rw [h2, Fin.lt_def]
+ have ht : (2 : Word w).val = 2 := Nat.mod_eq_of_lt (by omega : 2 < 2 ^ w)
+ rw [ht]
+ cases b <;> simp [v, Nat.mod_eq_of_lt (by omega : 1 < 2 ^ w)]
+ have hs : (s 10).val = (r 10).val + 1 := by
+ change (r 10 + r 1).val = _
+ rw [h1, Fin.val_add_eq_of_add_lt]
+ · rw [show (1 : Word w).val = 1 from Nat.mod_eq_of_lt (by omega : 1 < 2 ^ w)]
+ · rw [show (1 : Word w).val = 1 from Nat.mod_eq_of_lt (by omega : 1 < 2 ^ w)]
+ exact (Nat.succ_le_of_lt ht).trans_lt (r 5).isLt
+ refine .whileStep ht (bit_exec pub state r m v hv hb) (ih s h1 h2 ?_ ?_)
+ · change (s 10).val + bs.length = (r 5).val
+ rw [hs]; simp only [List.length_cons] at hlen; omega
+ · intro j hj
+ have h := hr (j + 1) (by simpa using hj)
+ change m (r 8 + (r 10 + r 1) + (j : Word w)).val = _
+ rw [h1, show r 8 + (r 10 + 1) + (j : Word w) = r 8 + r 10 + ((j+1 : ℕ) : Word w) by
+ push_cast; ring]
+ exact h
+
+private theorem save_exec (pub : Pub → Word w) (state : Word w) (r : Regs w 32) (m : Memory w) :
+ Flow.Exec pub state save r m [.write (r 9) (r 11), .tick]
+ (Function.update r 29 (r 7 + r 1)) (writeMemory m (r 9) (r 11)) :=
+ .seq (.line rfl) (.line rfl)
+
+/-- The full event sequence for a successful word-gather call, ending with the reconstructed
+word's destination write. -/
+def events (pub : Pub → Word w) (state : Word w) (r : Regs w 32) (v : Word w) :=
+ List.replicate 15 .tick ++ (scanEvents (loaded pub state r) (wordBits v) ++
+ [.write (pub 1 + state) v, .tick])
+
+/-- A complete word's little-endian bit image at its source address. -/
+def BitImage (m : Memory w) (addr : Word w) (v : Word w) : Prop :=
+ ∀ i : Fin w, m (addr + (i.val : Word w)).val = ((RAMSerialization.wordBits w v i).toNat : Word w)
+
+/-- The genuine scheduled call executes the bit loop and writes the entire
+decoded word. Surplus branch bits are rejected at its terminal instruction. -/
+theorem gather_call (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (m : Memory w)
+ (hw : 2 ≤ w) (hp : (pub 2).val = w) (hi : state < pub 3) (v : Word w)
+ (hv : BitImage m (pub 0 + state * pub 2) v)
+ (priv : Word w → Word w) (bits : List Bool) (fuel : ℕ) :
+ let machine := table.instantiate w pub
+ let es := events pub state rs v
+ execute machine.program (es.length + (fuel + 2)) ⟨machine.entry, state, rs, priv⟩ m bits =
+ if bits.isEmpty then some ⟨es ++ [.tick], if state + 1 = pub 3 then none else some (state + 1)⟩
+ else none := by
+ let pre := loaded pub state rs
+ let post := folded pre (wordBits v)
+ have hscan : Flow.Exec pub state scan pre m (scanEvents pre (wordBits v)) post m := by
+ apply scan_exec pub state pre m (wordBits v) rfl rfl hw
+ · change (0 : Word w).val + (wordBits v).length = (pub 2).val
+ simp [hp]
+ · intro j hj
+ have h : j < w := by simpa using hj
+ change m ((pub 0 + state * pub 2) + 0 + (j : Word w)).val = _
+ simpa [wordBits] using hv ⟨j,h⟩
+ have hacc : post 11 = v := by
+ rw [show post 11 = _ from folded_acc pre (wordBits v), TapeWord.value_wordBits]
+ change 0 + 1 * (v.val : Word w) = _
+ simp
+ have hdest : post 9 = pub 1 + state := folded_keep pre _ 9 (by decide)
+ have hstate : post 7 = state := folded_keep pre _ 7 (by decide)
+ have hone : post 1 = 1 := folded_keep pre _ 1 (by decide)
+ have htotal : post 30 = pub 3 := folded_keep pre _ 30 (by decide)
+ let out := Function.update post (29 : Reg) (post 7 + post 1)
+ have hbody : Flow.Exec pub state body rs m (events pub state rs v) out
+ (writeMemory m (pub 1 + state) v) := by
+ have h := Flow.Exec.seq (load_exec pub state rs m hi) (Flow.Exec.seq hscan (save_exec pub state post m))
+ simpa only [body, events, pre, hdest, hacc] using h
+ have noBits (r : Regs w 32) (b : List Bool) : choiceBits (scanEvents r b) = [] := by
+ induction b generalizing r with
+ | nil => rfl
+ | cons b bs ih => simp [scanEvents, bitEvents, choiceBits, ih]
+ have hb : choiceBits (events pub state rs v) = [] := by
+ simp [events, Flow.choiceBits_append, noBits, List.replicate_succ, choiceBits]
+ have h29 : out 29 = state + 1 := by simp [out, hstate, hone]
+ have h30 : out 30 = pub 3 := by change post 30 = _; exact htotal
+ simpa only [table, hb, List.nil_append, h29, h30] using
+ PrimedCounter.Call.execute_body body 29 30 pub state rs priv m hbody bits fuel
+
+/-- The complete native report, including the final cursor comparison. -/
+def report (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (v : Word w) : Report w :=
+ ⟨events pub state rs v ++ [.tick], if state + 1 = pub 3 then none else some (state + 1)⟩
+
+private theorem scan_length (r : Regs w 32) (bs : List Bool) :
+ (scanEvents r bs).length = 8 * bs.length + 1 := by
+ induction bs generalizing r with
+ | nil => rfl
+ | cons b bs ih => simp [scanEvents, bitEvents, ih]; omega
+
+theorem events_length (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (v : Word w) :
+ (events pub state rs v).length = 8 * w + 18 := by simp [events, scan_length]
+
+private theorem probes_append (xs ys : List (Event w)) :
+ countProbes (xs ++ ys) = countProbes xs + countProbes ys := by
+ induction xs with
+ | nil => simp [countProbes]
+ | cons e xs ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+private theorem scan_probes (r : Regs w 32) (bs : List Bool) :
+ countProbes (scanEvents r bs) = bs.length := by
+ induction bs generalizing r with
+ | nil => rfl
+ | cons b bs ih => simp [scanEvents, bitEvents, countProbes, ih]; omega
+
+theorem report_probes (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (v : Word w) :
+ (report pub state rs v).probes = w + 1 := by
+ simp [report, events, Report.probes, probes_append, scan_probes, List.replicate_succ, countProbes]
+
+private theorem after_scan (m : Memory w) (r : Regs w 32) (bs : List Bool) :
+ after m (scanEvents r bs) = m := by
+ induction bs generalizing r with
+ | nil => rfl
+ | cons b bs ih =>
+ change after m (scanEvents (advanced r _) bs) = m
+ exact ih _
+
+theorem report_memory (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (m : Memory w) (v : Word w) :
+ after m (report pub state rs v).events = writeMemory m (pub 1 + state) v := by
+ change after m ((List.replicate 15 .tick ++ (scanEvents _ _ ++ _)) ++ [.tick]) = _
+ simp only [after, List.foldl_append]
+ change writeMemory (after m (scanEvents (loaded pub state rs) (wordBits v))) (pub 1 + state) v = _
+ rw [after_scan]
+
+/-- Uniform fuel bound at every cursor, with the exact report for a normal
+call and rejection of every nonempty choice stream. -/
+theorem gather_call_at_fuel (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (m : Memory w)
+ (hw : 2 ≤ w) (hp : (pub 2).val = w) (hi : state < pub 3) (v : Word w)
+ (hv : BitImage m (pub 0 + state * pub 2) v) (priv : Word w → Word w) (bits : List Bool)
+ {fuel : ℕ} (hf : 8 * w + 20 ≤ fuel) :
+ let machine := table.instantiate w pub
+ execute machine.program fuel ⟨machine.entry, state, rs, priv⟩ m bits =
+ if bits.isEmpty then some (report pub state rs v) else none := by
+ have h := gather_call pub state rs m hw hp hi v hv priv bits (fuel - (8 * w + 20))
+ dsimp only at h
+ rw [events_length, show 8*w + 18 + (fuel - (8*w+20) + 2) = fuel by omega] at h
+ exact h
+
+end LiveConfigGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveConfigGatherImage.lean b/lean/OAI/Computability/VPVNP/LiveConfigGatherImage.lean
new file mode 100644
index 0000000000..1d3a51339d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveConfigGatherImage.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.LiveConfigGather
+import OAI.Computability.VPVNP.LiveEvaluatorRAMImage
+import OAI.Computability.VPVNP.PrimedInputRAMChoices
+import OAI.Computability.VPVNP.RAMChain
+
+/-!
+# Memory image of gathered configuration words
+
+A contiguous cut holds one zero-or-one word per bit. Each scheduled gather
+call reconstructs one little-endian field word in a disjoint bank. Replaying
+the reports installs the checked decoder's entire array of words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveConfigGather
+
+open BurstRAM PrimedInputRAM RAMSerialization
+open scoped Fin.CommRing
+
+variable {k w extra M : ℕ}
+
+/-- Every cut bit occupies one full machine word. -/
+def ArrayBitImage (m : Memory w) (base : Word w) (bits : Fin (k*w) → Bool) : Prop :=
+ ∀ i, m (base.val + i.val) = ((bits i).toNat : Word w)
+
+private theorem offset_val (base : Word w) (n : ℕ) (h : base.val + n < 2 ^ w) :
+ (base + (n : Word w)).val = base.val + n := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt h]
+
+/-- Restricting a complete cut to a single word gives the exact input image
+expected by the native gathering call. -/
+theorem bitImage_word {pub : Pub → Word w} {m : Memory w} {bits : Fin (k*w) → Bool}
+ (img : ArrayBitImage m (pub 0) bits) (srcFit : (pub 0).val + k*w ≤ 2^w)
+ (hp : (pub 2).val = w) (i : Fin k) :
+ BitImage m (pub 0 + (i.val : Word w) * pub 2) ((arrayBits k w).symm bits i) := by
+ intro j
+ let f := finProdFinEquiv (i,j)
+ have hf : f.val = i.val * w + j.val := by simp [f, finProdFinEquiv, Nat.mul_comm, Nat.add_comm]
+ have hw : pub 2 = (w : Word w) :=
+ (Fin.cast_val_eq_self (pub 2)).symm.trans (congrArg (fun n : ℕ => (n : Word w)) hp)
+ have ha : pub 0 + (i.val : Word w) * pub 2 + (j.val : Word w) = pub 0 + (f.val : Word w) := by
+ rw [hw, hf]
+ push_cast
+ ring
+ rw [ha, offset_val _ _ (by have := f.isLt; omega), img]
+ have hb := arrayBits_at ((arrayBits k w).symm bits) i j
+ rw [Equiv.apply_symm_apply] at hb
+ rw [← hb]
+
+/-- A write to the disjoint destination bank leaves the complete source bit
+image available to every later cursor. -/
+theorem ArrayBitImage.after_write {m : Memory w} {base dst : Word w} {bits : Fin (k*w) → Bool}
+ (img : ArrayBitImage m base bits) (destFit : dst.val + k ≤ 2^w)
+ (hsep : base.val + k*w ≤ dst.val ∨ dst.val + k ≤ base.val) (i : Fin k) (v : Word w) :
+ ArrayBitImage (writeMemory m (dst + (i.val : Word w)) v) base bits := by
+ intro j
+ have hn : base.val + j.val ≠ (dst + (i.val : Word w)).val := by
+ rw [offset_val dst i.val (by have := i.isLt; omega)]
+ have := i.isLt
+ have := j.isLt
+ omega
+ simpa [writeMemory, hn] using img j
+
+/-- The ordered destination writes from the actual native reports. -/
+theorem replay_reports (pub : Pub → Word w) (fit : (pub 1).val + k ≤ 2^w)
+ (rs : PrimedStackRAM.Regs w 32) (vals : Fin k → Word w) (cells : List (Fin k)) (m : Memory w) :
+ after m (eventLog (cells.map fun i => report pub (i.val : Word w) rs (vals i))) =
+ store (scratchAddress (pub 1).val fit) vals cells m := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih =>
+ let r := report pub (i.val : Word w) rs (vals i)
+ change after m (r.events ++ eventLog _) = store _ _ cells (writeMemory m _ _)
+ have hd : pub 1 + (i.val : Word w) = scratchAddress (pub 1).val fit i :=
+ Fin.ext (offset_val _ _ (by have := i.isLt; omega))
+ rw [show after m (r.events ++ eventLog _) = after (after m r.events) (eventLog _) from List.foldl_append,
+ show after m r.events = _ from report_memory pub _ rs m (vals i), hd, ih]
+
+/-- Packed words after all destinations have been visited. -/
+def gathered (dst : Word w) (fit : dst.val + k ≤ 2^w) (bits : Fin (k*w) → Bool) (m : Memory w) : Memory w :=
+ store (scratchAddress dst.val fit) ((arrayBits k w).symm bits) (List.finRange k) m
+
+theorem gathered_at (dst : Word w) (fit : dst.val + k ≤ 2^w) (bits : Fin (k*w) → Bool)
+ (m : Memory w) (i : Fin k) :
+ gathered dst fit bits m (dst + (i.val : Word w)).val = (arrayBits k w).symm bits i := by
+ rw [offset_val _ _ (by have := i.isLt; omega)]
+ exact store_at (scratchAddress dst.val fit) _ _ m (List.mem_finRange i)
+
+theorem gathered_outside (dst : Word w) (fit : dst.val + k ≤ 2^w) (bits : Fin (k*w) → Bool)
+ (m : Memory w) (j : ℕ) (hj : j < dst.val ∨ dst.val + k ≤ j) :
+ gathered dst fit bits m j = m j := by
+ apply store_outside
+ intro i _
+ change j ≠ dst.val + i.val
+ have := i.isLt
+ omega
+
+open LiveEvaluatorEncoding (fieldWords stateField firstField secondField words format)
+open LiveEvaluatorRAM (ConfigAt)
+
+/-- The memory image characterizes every field of the checked decoder,
+including every padding cell of a halt. -/
+theorem configAt_iff_words (hw : 2 ≤ w) (hs : extra+2 ≤ 2^w) (dst : Word w) (m : Memory w)
+ (c : LiveEvaluatorEncoding.Code extra M) :
+ ConfigAt m dst c ↔ ∀ f, m (dst + (f.val : Word w)).val = (format hw hs).words c f := by
+ refine ⟨?_, LiveEvaluatorRAM.configAt_of_words hw hs c⟩
+ intro hc f
+ apply Fin.ext
+ change (m (dst + (f.val : Word w)).val).val = (words hw hs c f).val
+ by_cases h0 : f.val = 0
+ · have he : f = stateField M := Fin.ext h0
+ rw [he, LiveEvaluatorEncoding.words_state]
+ simpa [stateField] using hc.state
+ by_cases hf : f.val < 1 + (2*M+1)
+ · let i : Fin (2*M+1) := ⟨f.val - 1, by omega⟩
+ have he : f = firstField i := by apply Fin.ext; change f.val = 1 + (f.val - 1); omega
+ rw [he, LiveEvaluatorEncoding.words_first]
+ simpa only [firstField, Nat.cast_add, Nat.cast_one, ← add_assoc] using hc.first i
+ · have hlen : f.val < 1 + (2*M+1) + (2*M+1) := f.isLt
+ let i : Fin (2*M+1) := ⟨f.val - (1+(2*M+1)), by omega⟩
+ have he : f = secondField i := by
+ apply Fin.ext; change f.val = 1 + (2*M+1) + (f.val - (1+(2*M+1))); omega
+ rw [he, LiveEvaluatorEncoding.words_second]
+ change (m (dst + ((1 + (2*M+1) + i.val : ℕ) : Word w)).val).val = _
+ rw [Nat.cast_add, Nat.cast_add, Nat.cast_one, ← add_assoc, ← add_assoc]
+ exact hc.second i
+
+/-- For arbitrary cut bits, the packed memory is the image of a configuration
+exactly when the checked binary decoder returns that configuration. -/
+theorem gathered_configAt_iff (hw : 2 ≤ w) (hs : extra+2 ≤ 2^w) (dst : Word w)
+ (fit : dst.val + fieldWords M ≤ 2^w) (bits : Fin (fieldWords M*w) → Bool) (m : Memory w)
+ (c : LiveEvaluatorEncoding.Code extra M) :
+ ConfigAt (gathered dst fit bits m) dst c ↔ (format hw hs).decode bits = some c := by
+ rw [configAt_iff_words hw hs, LiveEvaluatorEncoding.decode_iff]
+ simp only [gathered_at]
+ change (∀ f, (arrayBits (fieldWords M) w).symm bits f = (format hw hs).words c f) ↔
+ bits = arrayBits (fieldWords M) w ((format hw hs).words c)
+ exact ⟨fun h => (Equiv.symm_apply_eq _).mp (funext h),
+ fun h => congrFun ((Equiv.symm_apply_eq _).mpr h)⟩
+
+/-- A malformed cut cannot realize any canonical configuration in the destination bank. -/
+theorem gathered_decode_none_iff (hw : 2 ≤ w) (hs : extra+2 ≤ 2^w) (dst : Word w)
+ (fit : dst.val + fieldWords M ≤ 2^w) (bits : Fin (fieldWords M*w) → Bool) (m : Memory w) :
+ (format hw hs).decode bits = none ↔
+ ¬ ∃ c : LiveEvaluatorEncoding.Code extra M, ConfigAt (gathered dst fit bits m) dst c := by
+ constructor
+ · rintro h ⟨c, hc⟩
+ have he := (gathered_configAt_iff hw hs dst fit bits m c).mp hc
+ rw [h] at he
+ cases he
+ · intro h
+ cases he : (format hw hs).decode bits with
+ | none => rfl
+ | some c => exact (h ⟨c, (gathered_configAt_iff hw hs dst fit bits m c).mpr he⟩).elim
+
+end LiveConfigGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveConfigGatherRun.lean b/lean/OAI/Computability/VPVNP/LiveConfigGatherRun.lean
new file mode 100644
index 0000000000..15d8393616
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveConfigGatherRun.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.LiveConfigGatherImage
+
+/-!
+# The complete native configuration-gather scan
+
+The persistent cursor visits every destination exactly once. Each successful
+completion consists of one empty choice list per word. The individual reports
+identify the actual writes and permit replay on the live group's external memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveConfigGather
+
+open BurstRAM
+open scoped Fin.CommRing
+
+variable {w k : ℕ}
+
+/-- Instantiate the gathering table on the live public operands to obtain its executable RAM
+program. -/
+abbrev machine (pub : Pub → Word w) := (table.instantiate w pub).program
+
+/-- The gather report for one indexed word of a configuration, using that word's index as the
+persistent cursor. -/
+def wordReport (pub : Pub → Word w) (words : Fin k → Word w) (i : Fin k) :=
+ report pub (i.val : Word w) (fun _ => 0) (words i)
+
+private def cursor (w k i : ℕ) : Option (Word w) :=
+ if i = k then none else some (i : Word w)
+
+private theorem report_result (pub : Pub → Word w) (hk : (pub 3).val = k) (words : Fin k → Word w)
+ (i : Fin k) : (wordReport pub words i).result = cursor w k (i.val + 1) := by
+ have cap : k < 2 ^ w := hk ▸ (pub 3).isLt
+ have hl : i.val + 1 < 2 ^ w := (Nat.succ_le_of_lt i.isLt).trans_lt cap
+ have h : (i.val : Word w) + 1 = ((i.val+1 : ℕ) : Word w) := by simp
+ have he : ((i.val+1 : ℕ) : Word w) = pub 3 ↔ i.val + 1 = k := by
+ rw [Fin.ext_iff, Fin.val_natCast, Nat.mod_eq_of_lt hl, hk]
+ simp only [wordReport, report, cursor, h, he]
+
+private theorem ordered_run (pub : Pub → Word w) (words : Fin k → Word w) (hw : 2 ≤ w)
+ (hp : (pub 2).val = w) (hk : (pub 3).val = k) {fuel : ℕ} (hf : 8*w+20 ≤ fuel)
+ (inv : Memory w → Prop)
+ (img : ∀ m, inv m → ∀ i : Fin k, BitImage m (pub 0 + (i.val : Word w) * pub 2) (words i))
+ (pres : ∀ m, inv m → ∀ i : Fin k, inv (writeMemory m (pub 1 + (i.val : Word w)) (words i)))
+ (cells : List (Fin k)) (start : ℕ) (hend : start + cells.length = k)
+ (ord : ∀ j (hj : j < cells.length), cells[j].val = start + j)
+ (m : Memory w) (hm : inv m) (bs : List (List Bool)) (reps : List (Report w)) :
+ (runSegment (machine pub) fuel (cursor w k start) m bs = some reps ∧
+ endState (cursor w k start) reps = none) ↔
+ bs = List.replicate cells.length [] ∧ reps = cells.map (wordReport pub words) := by
+ induction cells generalizing start m bs reps with
+ | nil =>
+ simp only [List.length_nil, Nat.add_zero] at hend
+ subst start
+ cases bs <;> cases reps <;> simp [cursor, runSegment, endState]
+ | cons i cells ih =>
+ have hi : i.val = start := by
+ have he := ord 0 (by simp)
+ change i.val = start + 0 at he
+ exact he
+ subst start
+ have htail : i.val + 1 + cells.length = k := by simp only [List.length_cons] at hend; omega
+ have hseq (j : ℕ) (hj : j < cells.length) : cells[j].val = i.val + 1 + j := by
+ have he := ord (j+1) (by simpa using hj)
+ change cells[j].val = i.val + (j+1) at he
+ omega
+ have hlt : (i.val : Word w) < pub 3 := by
+ rw [Fin.lt_def, Fin.val_natCast, Nat.mod_eq_of_lt (i.isLt.trans (hk ▸ (pub 3).isLt)), hk]
+ exact i.isLt
+ have hc : cursor w k i.val = some (i.val : Word w) := by simp [cursor, i.isLt.ne]
+ cases bs with
+ | nil => cases reps <;> simp [hc, runSegment, endState, List.replicate_succ]
+ | cons b bs =>
+ have run := gather_call_at_fuel pub (i.val : Word w) (fun _ => 0) m hw hp hlt (words i) (img m hm i)
+ (fun _ => 0) b hf
+ change execute (machine pub) fuel ((machine pub).start (i.val : Word w)) m b =
+ (if b.isEmpty then some (wordReport pub words i) else none) at run
+ rw [hc, runSegment, run]
+ cases b with
+ | cons bit more => simp [List.replicate_succ]
+ | nil =>
+ let rep := wordReport pub words i
+ have hn := report_result pub hk words i
+ have hmem : after m rep.events = writeMemory m (pub 1 + (i.val : Word w)) (words i) := report_memory ..
+ simp only [List.isEmpty_nil, ite_true, List.length_cons, List.replicate_succ, List.map_cons,
+ List.cons.injEq, true_and, hn, Option.map_eq_some_iff]
+ cases reps with
+ | nil => simp
+ | cons z zs =>
+ simp only [List.cons.injEq, endState]
+ by_cases hz : rep = z
+ · subst z
+ simpa [rep, hn, hmem] using
+ ih (i.val+1) htail hseq _ (pres m hm i) bs zs
+ · simp [rep] at hz
+ simp [hz, Ne.symm hz]
+
+/-- Exact choices and reports of a complete execution, for an array of
+words whose source bits survive the earlier writes. -/
+theorem run_words (pub : Pub → Word w) (words : Fin k → Word w) (hw : 2 ≤ w) (hp : (pub 2).val = w)
+ (hk : (pub 3).val = k) (hpos : 0 < k) {fuel : ℕ} (hf : 8*w+20 ≤ fuel) (inv : Memory w → Prop)
+ (img : ∀ m, inv m → ∀ i : Fin k, BitImage m (pub 0 + (i.val : Word w) * pub 2) (words i))
+ (pres : ∀ m, inv m → ∀ i : Fin k, inv (writeMemory m (pub 1 + (i.val : Word w)) (words i)))
+ (m : Memory w) (hm : inv m) (bs : List (List Bool)) (reps : List (Report w)) :
+ (runSegment (machine pub) fuel (some 0) m bs = some reps ∧ endState (some 0) reps = none) ↔
+ bs = List.replicate k [] ∧ reps = (List.finRange k).map (wordReport pub words) := by
+ simpa [cursor, hpos.ne] using ordered_run pub words hw hp hk hf inv img pres (List.finRange k) 0
+ (by simp) (by intro j hj; simp) m hm bs reps
+
+/-- Exact native completion and memory replay for the unpacked live cut:
+the stage admits one deterministic transcript and installs every decoded
+word in the destination bank. -/
+theorem run_array (pub : Pub → Word w) (bits : Fin (k*w) → Bool) (hw : 2 ≤ w)
+ (hp : (pub 2).val = w) (hk : (pub 3).val = k) (hpos : 0 < k) {fuel : ℕ}
+ (hf : 8*w+20 ≤ fuel) (srcFit : (pub 0).val + k*w ≤ 2^w) (destFit : (pub 1).val + k ≤ 2^w)
+ (hsep : (pub 0).val + k*w ≤ (pub 1).val ∨ (pub 1).val + k ≤ (pub 0).val)
+ (m : Memory w) (hm : ArrayBitImage m (pub 0) bits)
+ (bs : List (List Bool)) (reps : List (Report w)) (out : Memory w) :
+ (runSegment (machine pub) fuel (some 0) m bs = some reps ∧ endState (some 0) reps = none ∧
+ after m (eventLog reps) = out) ↔
+ bs = List.replicate k [] ∧
+ reps = (List.finRange k).map (wordReport pub ((RAMSerialization.arrayBits k w).symm bits)) ∧
+ out = gathered (pub 1) destFit bits m := by
+ let words := (RAMSerialization.arrayBits k w).symm bits
+ have hr := run_words pub words hw hp hk hpos hf (fun u => ArrayBitImage u (pub 0) bits)
+ (fun _ h i => bitImage_word h srcFit hp i)
+ (fun _ h i => h.after_write destFit hsep i (words i)) m hm bs reps
+ have hm' : after m (eventLog ((List.finRange k).map (wordReport pub words))) =
+ gathered (pub 1) destFit bits m := replay_reports pub destFit _ words (List.finRange k) m
+ constructor
+ · rintro ⟨run, he, hmem⟩
+ obtain ⟨hbs, hrep⟩ := hr.mp ⟨run, he⟩
+ exact ⟨hbs, hrep, hmem.symm.trans (hrep ▸ hm')⟩
+ · rintro ⟨hbs, hrep, rfl⟩
+ obtain ⟨run, he⟩ := hr.mpr ⟨hbs, hrep⟩
+ exact ⟨run, he, hrep ▸ hm'⟩
+
+end LiveConfigGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCountedStage.lean b/lean/OAI/Computability/VPVNP/LiveCountedStage.lean
new file mode 100644
index 0000000000..e92bfbda00
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCountedStage.lean
@@ -0,0 +1,214 @@
+import OAI.Computability.VPVNP.LiveStageOperands
+import OAI.Computability.VPVNP.RAMRecords
+import Mathlib.Tactic.FinCases
+
+/-!
+# A native counted stage with a public or memory-resident bound
+
+The guard reads the last public word as either the capacity or its external address.
+Below that capacity the original table runs. At or above it the stage accepts,
+so the enclosing stage linker can hand control to the next table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveCountedStage
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {p r k w : ℕ}
+
+private def regs (r : ℕ) : Fin r ↪ Fin (r+2) := ⟨Fin.castAdd 2, Fin.castAdd_injective r 2⟩
+
+private def cursorReg (r : ℕ) : Fin (r+2) := (0 : Fin 2).natAdd r
+private def boundReg (r : ℕ) : Fin (r+2) := (1 : Fin 2).natAdd r
+
+private def pre (p : ℕ) (i : Fin 5) := i.castAdd p
+private def body (i : Fin p) := i.natAdd 5
+
+/-- Shift only the jump destinations of a native instruction. -/
+private def shift : Instr w p r k → Instr w (5+p) r k
+ | .constant a v j => .constant a v (body j)
+ | .publicWord a x j => .publicWord a x (body j)
+ | .stateWord a j => .stateWord a (body j)
+ | .copy a b j => .copy a b (body j)
+ | .binary op a b c j => .binary op a b c (body j)
+ | .loadPrivate a b j => .loadPrivate a b (body j)
+ | .storePrivate a b j => .storePrivate a b (body j)
+ | .jumpEq a b yes no => .jumpEq a b (body yes) (body no)
+ | .jumpLt a b yes no => .jumpLt a b (body yes) (body no)
+ | .choose yes no => .choose (body yes) (body no)
+ | .readExternal a b j => .readExternal a b (body j)
+ | .writeExternal a b j => .writeExternal a b (body j)
+ | .returnState a => .returnState a
+ | .accept => .accept
+ | .reject => .reject
+
+private def wide (T : Template p r k) := LiveStageLink.widen T (regs r) Fin.castSucc
+
+private def guardCode (indirect : Bool) (entry : Fin p) : Fin 5 → Instr w (5+p) (r+2) (k+1)
+ | 0 => .stateWord (cursorReg r) (pre p 1)
+ | 1 => .publicWord (boundReg r) (Fin.last k) (pre p 2)
+ | 2 => if indirect then .readExternal (boundReg r) (boundReg r) (pre p 3)
+ else .copy (boundReg r) (boundReg r) (pre p 3)
+ | 3 => .jumpLt (cursorReg r) (boundReg r) (body entry) (pre p 4)
+ | 4 => .accept
+
+/-- Guard the original table using a direct word or an external memory cell. -/
+def counted (T : Template p r k) (indirect : Bool) : Template (5+p) (r+2) (k+1) where
+ literalWidth := T.literalWidth
+ entry := pre p 0
+ code := Fin.addCases (guardCode indirect T.entry) (fun j => shift ((wide T).code j))
+
+/-- Append the stage's bound or bound address as the final public operand of its worker. -/
+def publicData (pub : Fin k → Word w) (bound : Word w) : Fin (k+1) → Word w := Fin.snoc pub bound
+
+variable (T : Template p r k) (indirect : Bool) (pub : Fin k → Word w) (bound : Word w)
+
+/-- Instantiate the counted wrapper and underlying worker with their public operands and the
+selected bound mode. -/
+abbrev machine := (counted T indirect).instantiate w (publicData pub bound)
+
+private theorem code_pre (j : Fin 5) : (machine T indirect pub bound).code (pre p j) = guardCode indirect T.entry j := by
+ simp only [machine, counted, pre, Template.instantiate, Fin.addCases_left]
+ fin_cases j <;> cases indirect <;> rfl
+
+private theorem code_body (j : Fin p) : (machine T indirect pub bound).code (body j) =
+ shift (((wide T).instantiate w (publicData pub bound)).code j) := by
+ simp only [machine, counted, body, Template.instantiate, Fin.addCases_right]
+ cases (wide T).code j <;> rfl
+
+private def embed (c : Config w p r) : Config w (5+p) r := ⟨body c.pc, c.persistent, c.reg, c.privateMem⟩
+
+private def embedAction : CallAction w (Config w p r) → CallAction w (Config w (5+p) r)
+ | .localStep c => .localStep (embed c)
+ | .branch q => .branch (embed ∘ q)
+ | .read a q => .read a (embed ∘ q)
+ | .write a v c => .write a v (embed c)
+ | .finish s => .finish s
+ | .reject => .reject
+
+private theorem step_body (c : Config w p (r+2)) :
+ (machine T indirect pub bound).program.step (embed c) =
+ embedAction (((wide T).instantiate w (publicData pub bound)).program.step c) := by
+ change ((machine T indirect pub bound).code (body c.pc)).run (publicData pub bound) (embed c) = _
+ rw [code_body]
+ change (shift _).run _ _ = embedAction ((((wide T).instantiate w (publicData pub bound)).code c.pc).run _ c)
+ cases ((wide T).instantiate w (publicData pub bound)).code c.pc <;>
+ simp only [shift, Instr.run, embedAction, embed, Config.put, Config.store, Function.comp_def]
+ all_goals first | rfl | (simp only [apply_ite body] <;> rfl)
+
+private theorem execute_body (fuel : ℕ) (c : Config w p (r+2)) (m : Memory w) (bits : List Bool) :
+ execute (machine T indirect pub bound).program fuel (embed c) m bits =
+ execute ((wide T).instantiate w (publicData pub bound)).program fuel c m bits := by
+ induction fuel generalizing c m bits with
+ | zero => rfl
+ | succ f ih =>
+ rw [execute, step_body, execute]
+ cases ((wide T).instantiate w (publicData pub bound)).program.step c <;>
+ simp only [embedAction, Function.comp_apply]
+ all_goals first | rfl | (rw [ih]) | (cases bits <;> simp [ih])
+
+private def bootRegs (st bound : Word w) : Fin (r+2) → Word w :=
+ Function.update (Function.update (fun _ => 0) (cursorReg r) st) (boundReg r) bound
+
+private def bootConfig (pc : Fin (5+p)) (st bound : Word w) : Config w (5+p) (r+2) :=
+ ⟨pc, st, bootRegs st bound, fun _ => 0⟩
+
+private theorem cursor_ne_bound : cursorReg r ≠ boundReg r := by
+ intro he
+ have := congrArg Fin.val he
+ simp [cursorReg, boundReg] at this
+
+/-- Effective stop cursor, as it is read at the start of the current call. -/
+def limit (indirect : Bool) (operand : Word w) (m : Memory w) : Word w :=
+ if indirect then m operand.val else operand
+
+/-- The guard log records an actual external read precisely for an indirect limit. -/
+def guardEvents (indirect : Bool) (operand : Word w) (m : Memory w) : List (Event w) :=
+ [.tick, .tick, if indirect then .read operand (m operand.val) else .tick, .tick]
+
+/-- Prepend the direct or indirect bound check's events to a worker report while retaining its
+return state. -/
+def prefixReport (indirect : Bool) (operand : Word w) (m : Memory w) (rep : Report w) : Report w :=
+ ⟨guardEvents indirect operand m ++ rep.events, rep.result⟩
+
+@[simp] theorem guardEvents_length (indirect : Bool) (operand : Word w) (m : Memory w) :
+ (guardEvents indirect operand m).length = 4 := rfl
+
+@[simp] theorem prefixReport_after (indirect : Bool) (operand : Word w) (m : Memory w)
+ (rep : Report w) : after m (prefixReport indirect operand m rep).events = after m rep.events := by
+ cases indirect <;> rfl
+
+@[simp] theorem prefixReport_choices (indirect : Bool) (operand : Word w) (m : Memory w)
+ (rep : Report w) : choiceBits (prefixReport indirect operand m rep).events = choiceBits rep.events := by
+ cases indirect <;> rfl
+
+@[simp] theorem prefixReport_result (indirect : Bool) (operand : Word w) (m : Memory w)
+ (rep : Report w) : (prefixReport indirect operand m rep).result = rep.result := rfl
+
+@[simp] theorem prefixReport_probes (indirect : Bool) (operand : Word w) (m : Memory w)
+ (rep : Report w) : (prefixReport indirect operand m rep).probes =
+ (if indirect then 1 else 0) + rep.probes := by
+ cases indirect <;> simp [prefixReport, guardEvents, Report.probes, countProbes]
+
+private theorem boot_run (fuel : ℕ) (st : Word w) (m : Memory w) (bits : List Bool) :
+ let P := (machine T indirect pub bound).program
+ let b := limit indirect bound m
+ execute P (fuel+4) (P.start st) m bits =
+ (execute P fuel (bootConfig (if st < b then body T.entry else pre p 4) st b) m bits).map
+ (prefixReport indirect bound m) := by
+ dsimp only
+ have hpub : (machine T indirect pub bound).publicData (Fin.last k) = bound := by
+ simp [machine, Template.instantiate, publicData]
+ change execute _ (fuel+4) (Config.mk (pre p 0) st (fun _ => 0) (fun _ => 0)) _ _ = _
+ cases indirect <;>
+ simp only [execute, Machine.program, code_pre, guardCode, Instr.run, Config.put, hpub,
+ Bool.false_eq_true, ite_false, ite_true, Function.update_of_ne cursor_ne_bound,
+ Function.update_self, Function.update_idem, Option.map_map, limit]
+ all_goals rfl
+
+/-- Four guard instructions precede the original call, with exact remaining fuel,
+branch stream, memory effects, and returned word. -/
+theorem execute_active (fuel : ℕ) (st : Word w) (m : Memory w)
+ (hlt : st < limit indirect bound m) (bits : List Bool) :
+ let P := (machine T indirect pub bound).program
+ let S := (T.instantiate w pub).program
+ execute P (fuel+4) (P.start st) m bits = (execute S fuel (S.start st) m bits).map
+ (prefixReport indirect bound m) := by
+ dsimp only
+ rw [boot_run, ite_eq_left hlt]
+ let c : Config w p (r+2) := ⟨T.entry, st, bootRegs st (limit indirect bound m), fun _ => 0⟩
+ change (execute _ fuel (embed c) m bits).map _ = _
+ rw [execute_body, wide, LiveStageLink.execute_widen]
+ have hpub : publicData pub bound ∘ Fin.castSucc = pub := by funext j; simp [publicData]
+ rw [hpub]
+ have hcfg : LiveStageLink.restrictConfig (regs r) c = (T.instantiate w pub).program.start st := by
+ change Config.mk _ _ _ _ = Config.mk _ _ _ _
+ congr 1
+ funext j
+ have h₀ : (regs r) j ≠ cursorReg r := by
+ intro he; have hv := congrArg Fin.val he; simp [regs, cursorReg] at hv; omega
+ have h₁ : (regs r) j ≠ boundReg r := by
+ intro he; have hv := congrArg Fin.val he; simp [regs, boundReg] at hv; omega
+ simp [c, bootRegs, Function.comp_apply, h₀, h₁]
+ rw [hcfg]
+
+/-- At and beyond the limit, including an initial limit of zero, the wrapper
+accepts the empty choice stream and rejects every nonempty stream. -/
+theorem execute_closed (fuel : ℕ) (st : Word w) (m : Memory w)
+ (hle : limit indirect bound m ≤ st) (bits : List Bool) :
+ let P := (machine T indirect pub bound).program
+ execute P (fuel+5) (P.start st) m bits =
+ if bits = [] then some ⟨guardEvents indirect bound m, none⟩ else none := by
+ dsimp only
+ rw [show fuel+5 = (fuel+1)+4 by omega, boot_run, ite_eq_right (not_lt.mpr hle)]
+ cases bits <;> simp [execute, Machine.program, bootConfig, code_pre, guardCode, Instr.run, prefixReport]
+
+end LiveCountedStage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveCutAssignments.lean b/lean/OAI/Computability/VPVNP/LiveCutAssignments.lean
new file mode 100644
index 0000000000..b668f04294
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveCutAssignments.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.ChainAssignments
+import OAI.Computability.VPVNP.LiveModes
+
+/-! # Raw cut assignments of the two live modes
+
+The cut at the midpoint carries the accumulated exponents. Each later
+interior cut carries a configuration of the evaluator. The two missing
+endpoint cuts have unique empty strings. Local agreement of neighboring
+mode flags forces a single flag throughout the whole chain.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ChainAssignments
+
+open CutSchedule ExponentTrace LiveChain
+
+/-- The cut following a first-half group, counting from the first interior cut through the
+midpoint. -/
+def firstCut {h : ℕ} (i : Fin (2^h)) : Fin (2^(h+1)+1) :=
+ ⟨i.val+1, by have := i.isLt; rw [pow_succ]; omega⟩
+
+/-- An interior cut strictly after the midpoint, indexed by its position among the evaluator
+configuration cuts. -/
+def laterCut {h : ℕ} (i : Fin (2^h-1)) : Fin (2^(h+1)+1) :=
+ ⟨2^h+(i.val+1), by have := i.isLt; rw [pow_succ]; omega⟩
+
+theorem coverCuts {h : ℕ} (j : Fin (2^(h+1)+1)) :
+ j = 0 ∨ j = Fin.last (2^(h+1)) ∨ (∃ i, j = firstCut i) ∨ ∃ i, j = laterCut i := by
+ by_cases hz : j.val = 0
+ · exact Or.inl (Fin.ext hz)
+ by_cases hl : j.val = 2^(h+1)
+ · exact Or.inr (Or.inl (Fin.ext hl))
+ by_cases hj : j.val ≤ 2^h
+ · exact Or.inr (Or.inr (Or.inl ⟨⟨j.val-1, by omega⟩, Fin.ext (by dsimp [firstCut]; omega)⟩))
+ have hb := j.isLt
+ have hp := pow_succ (2 : ℕ) h
+ exact Or.inr (Or.inr (Or.inr ⟨⟨j.val-(2^h+1), by omega⟩, Fin.ext (by dsimp [laterCut]; omega)⟩))
+
+private def joinCuts {h Δ : ℕ} (fst : LiveBits h Δ) (lst : TailBits h Δ) (j : Fin (2^(h+1)+1)) :
+ Bits (width (h+1) Δ j.val) :=
+ if hj : 0 < j.val ∧ j.val ≤ 2^h then
+ let i : Fin (2^h) := ⟨j.val-1, by omega⟩
+ (show i.val+1 = j.val by dsimp [i]; omega) ▸ fst i
+ else if hk : 2^h < j.val ∧ j.val < 2^(h+1) then
+ let i : Fin (2^h-1) := ⟨j.val-(2^h+1), by have := pow_succ (2 : ℕ) h; omega⟩
+ (show 2^h + (i.val+1) = j.val by dsimp [i]; omega) ▸ lst i
+ else fun _ => false
+
+private theorem join_first {h Δ : ℕ} (fst : LiveBits h Δ) (lst : TailBits h Δ) (i : Fin (2^h)) :
+ joinCuts fst lst (firstCut i) = fst i := by
+ have hi := i.isLt
+ simp [joinCuts, firstCut, Nat.succ_le_iff.mpr hi]
+
+private theorem join_later {h Δ : ℕ} (fst : LiveBits h Δ) (lst : TailBits h Δ) (i : Fin (2^h-1)) :
+ joinCuts fst lst (laterCut i) = lst i := by
+ have hi := i.isLt
+ have h1 : ¬(0 < 2^h+(i.val+1) ∧ 2^h+(i.val+1) ≤ 2^h) := by omega
+ have h2 : 2^h < 2^h+(i.val+1) ∧ 2^h+(i.val+1) < 2^(h+1) := by rw [pow_succ]; omega
+ have heq : 2^h + (i.val+1) - (2^h+1) = i.val := by omega
+ dsimp only [joinCuts, laterCut]
+ split
+ · contradiction
+ · have transport (k : Fin (2^h-1)) (same : k = i)
+ (hw : 2^h+(k.val+1) = 2^h+(i.val+1)) :
+ (hw ▸ lst k : Bits (width (h+1) Δ (2^h+(i.val+1)))) = lst i := by
+ subst k
+ rfl
+ apply transport
+ exact Fin.ext heq
+
+/-- Raw physical cuts are exactly the first-half and tail fields with no
+extra choices for either missing endpoint. -/
+def liveCutEquiv (h Δ : ℕ) : AllCuts h Δ ≃ LiveBits h Δ × TailBits h Δ where
+ toFun c := (fun i => c (firstCut i), fun i => c (laterCut i))
+ invFun x := joinCuts x.1 x.2
+ left_inv c := by
+ funext j
+ rcases coverCuts j with rfl | rfl | ⟨i,rfl⟩ | ⟨i,rfl⟩
+ · funext k
+ exact Fin.elim0 (k.cast (width_zero _ _))
+ · funext k
+ exact Fin.elim0 (k.cast (width_end _ _))
+ · apply join_first
+ · apply join_later
+ right_inv x := Prod.ext (funext (join_first x.1 x.2)) (funext (join_later x.1 x.2))
+
+/-- Equality at every interior group propagates the first mode flag to all
+interior cuts. The case of a single interior cut needs no comparisons. -/
+theorem commonMode {n : ℕ} (flags : Fin (n+1) → Bool)
+ (interior : ∀ i : Fin n, flags i.castSucc = flags i.succ) :
+ ∃! mode, ∀ i, flags i = mode := by
+ refine ⟨flags 0, ?_, fun mode hm => (hm 0).symm⟩
+ intro i
+ induction i using Fin.induction with
+ | zero => rfl
+ | succ j ih => exact (interior j).symm.trans ih
+
+end ChainAssignments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveDeterministicPaths.lean b/lean/OAI/Computability/VPVNP/LiveDeterministicPaths.lean
new file mode 100644
index 0000000000..eb4769c3e5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveDeterministicPaths.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.LiveProgramRouting
+import OAI.Computability.VPVNP.LiveHeaderUnique
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+
+/-!
+# Removing a completed deterministic segment from a native group path
+
+A canonical verified run can be a proper initial part of the group, ending
+with a returned word. Exact-use choice strings force every accepting group
+path to have precisely those initial bursts, including their full reports.
+The remainder retains the original cap applied to the concatenated reports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+open BurstRAM
+
+variable {w : ℕ} {C : Type*} {P : BurstRAM.Program w C} {fuel : ℕ}
+
+/-- All accepting paths from a given optional call state. -/
+abbrev PathsFrom (P : BurstRAM.Program w C) (fuel : ℕ) (st : Option (Word w)) (m : Memory w)
+ (cap : List (Report w) → Prop) :=
+ {bs : List (List Bool) // ∃ logs, runSegment P fuel st m bs = some logs ∧
+ endState st logs = none ∧ cap logs}
+
+/-- Every native accepting run beginning at the given state contains the
+entire verified deterministic prefix in both its choice stream and its log. -/
+theorem split_empty_segment {n : ℕ} {st : Option (Word w)} {m : Memory w} {prefixLogs logs : List (Report w)}
+ {bs : List (List Bool)} (prefixRun : runSegment P fuel st m (List.replicate n []) = some prefixLogs)
+ (run : runSegment P fuel st m bs = some logs) (halt : endState st logs = none) :
+ ∃ rest tailLogs, bs = List.replicate n [] ++ rest ∧ logs = prefixLogs ++ tailLogs ∧
+ runSegment P fuel (endState st prefixLogs) (after m (eventLog prefixLogs)) rest = some tailLogs := by
+ induction n generalizing st m bs prefixLogs logs with
+ | zero =>
+ simp [runSegment] at prefixRun; subst prefixLogs
+ exact ⟨bs,logs,rfl,rfl,run⟩
+ | succ n ih =>
+ simp only [List.replicate_succ] at prefixRun ⊢
+ cases st with
+ | none => contradiction
+ | some st =>
+ cases bs with
+ | nil => simp [runSegment] at run; subst logs; contradiction
+ | cons b bs =>
+ rw [runSegment] at prefixRun run
+ cases hp : BurstRAM.execute P fuel (P.start st) m [] with
+ | none => simp [hp] at prefixRun
+ | some r =>
+ cases hb : BurstRAM.execute P fuel (P.start st) m b with
+ | none => simp [hb] at run
+ | some s =>
+ obtain ⟨rfl,rfl⟩ := execute_empty_forces hp hb
+ simp only [hp,Option.map_eq_some_iff] at prefixRun run
+ obtain ⟨pr,hpr,rfl⟩ := prefixRun
+ obtain ⟨rs,hrs,rfl⟩ := run
+ obtain ⟨rest,tail,hb',hrs',hr⟩ := ih hpr hrs halt
+ refine ⟨rest,tail,by simp [hb'],by simp [hrs'],?_⟩
+ simpa only [endState,eventLog,List.flatMap_cons,after,List.foldl_append] using hr
+
+/-- The equivalence is concatenation on branch strings, so even different
+branch choices in the suffix with the same output state remain distinct. -/
+noncomputable def emptySegmentEquiv {n : ℕ} {st : Option (Word w)} {m : Memory w} {prefixLogs : List (Report w)}
+ (prefixRun : runSegment P fuel st m (List.replicate n []) = some prefixLogs) (cap : List (Report w) → Prop) :
+ PathsFrom P fuel (endState st prefixLogs) (after m (eventLog prefixLogs)) (fun rs => cap (prefixLogs++rs)) ≃
+ PathsFrom P fuel st m cap := by
+ let add : PathsFrom P fuel (endState st prefixLogs) (after m (eventLog prefixLogs)) (fun rs => cap (prefixLogs++rs)) →
+ PathsFrom P fuel st m cap := fun a => ⟨List.replicate n [] ++ a.val,by
+ obtain ⟨tail,hr,hh,hc⟩ := a.property
+ refine ⟨prefixLogs++tail,?_,?_,hc⟩
+ · rw [PrimedSchedule.runSegment_append,prefixRun]; simp [hr]
+ · simpa only [endState_append] using hh⟩
+ apply Equiv.ofBijective add
+ constructor
+ · intro a b eq
+ exact Subtype.ext (List.append_cancel_left (congrArg Subtype.val eq))
+ · rintro ⟨bs,logs,hr,hh,hc⟩
+ obtain ⟨rest,tail,rfl,rfl,ht⟩ := split_empty_segment prefixRun hr hh
+ refine ⟨⟨rest,tail,ht,?_,hc⟩,rfl⟩
+ rwa [endState_append] at hh
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveDeterministicReachable.lean b/lean/OAI/Computability/VPVNP/LiveDeterministicReachable.lean
new file mode 100644
index 0000000000..947320069d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveDeterministicReachable.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.LiveHeaderUnique
+
+/-!
+# Address preservation on every continuing native history
+
+A continuing history records every successful call which returned a cursor.
+It may have no accepting extension. A verified prefix of empty-choice calls
+can be removed when proving address preservation: the first report of each
+such call is forced, and every continuing history beyond the prefix starts
+from its actual cursor and memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- All states and memories reached through a finite number of continuing calls. -/
+inductive Reached (P : Program w C) (fuel : ℕ) (st : Word w) (m : Memory w) : Word w → Memory w → Prop
+ | start : Reached P fuel st m st m
+ | more {cursor mem bits r next} : Reached P fuel st m cursor mem →
+ execute P fuel (P.start cursor) mem bits = some r → r.result = some next →
+ Reached P fuel st m next (after mem r.events)
+
+/-- Every returning call leaves this address unchanged, even on a history
+whose subsequent calls may reject. -/
+def ProtectsAddress (P : Program w C) (fuel : ℕ) (st : Word w) (m : Memory w) (a : ℕ) : Prop :=
+ ∀ {cursor mem bits r next}, Reached P fuel st m cursor mem →
+ execute P fuel (P.start cursor) mem bits = some r → r.result = some next →
+ after mem r.events a = mem a
+
+variable {P : Program w C} {fuel : ℕ} {st : Word w} {m : Memory w} {a : ℕ}
+
+/-- A state and memory invariant can establish the address frame on all
+continuing histories by one-call induction. -/
+theorem ProtectsAddress.of_invariant (I : Word w → Memory w → Prop) (start : I st m)
+ (step : ∀ {cursor mem bits r next}, I cursor mem → execute P fuel (P.start cursor) mem bits = some r →
+ r.result = some next → I next (after mem r.events) ∧ after mem r.events a = mem a) :
+ ProtectsAddress P fuel st m a := by
+ have inv : ∀ {cursor mem}, Reached P fuel st m cursor mem → I cursor mem := by
+ intro cursor mem reached
+ induction reached with
+ | start => exact start
+ | more _ call cont ih => exact (step ih call cont).1
+ intro cursor mem bits r next reached run result
+ exact (step (inv reached) run result).2
+
+private theorem protects_after_empty_call {r : Report w} {next : Word w}
+ (run : execute P fuel (P.start st) m [] = some r) (result : r.result = some next)
+ (frame : after m r.events a = m a) (suffix : ProtectsAddress P fuel next (after m r.events) a) :
+ ProtectsAddress P fuel st m a := by
+ let I := fun cursor mem => (cursor = st ∧ mem = m) ∨ Reached P fuel next (after m r.events) cursor mem
+ apply ProtectsAddress.of_invariant I (Or.inl ⟨rfl,rfl⟩)
+ intro cursor mem bits q v inv call cont
+ rcases inv with ⟨rfl,rfl⟩ | reached
+ · obtain ⟨_,rfl⟩ := execute_empty_forces run call
+ have hv : v = next := Option.some.inj (cont.symm.trans result)
+ subst v
+ exact ⟨Or.inr .start,frame⟩
+ · exact ⟨Or.inr (.more reached call cont),suffix reached call cont⟩
+
+/-- Replay each report on its actual input memory, preserving the protected address. -/
+def ReplayFrame (a : ℕ) : Memory w → List (Report w) → Prop
+ | _, [] => True
+ | m, r :: rs => after m r.events a = m a ∧ ReplayFrame a (after m r.events) rs
+
+/-- The memory reached after the full replay retains the protected cell. -/
+theorem ReplayFrame.after_eventLog (rs : List (Report w)) (m : Memory w) (h : ReplayFrame a m rs) :
+ after m (eventLog rs) a = m a := by
+ induction rs generalizing m with
+ | nil => rfl
+ | cons r rs ih =>
+ change after m (r.events ++ eventLog rs) a = m a
+ rw [show after m (r.events ++ eventLog rs) = after (after m r.events) (eventLog rs) from List.foldl_append]
+ exact (ih _ h.2).trans h.1
+
+/-- An indexed sequence of actual intermediate memories supplies the frame
+for every report along its replay. -/
+theorem ReplayFrame.ofFn {n : ℕ} (entry : Fin (n+1) → Memory w) (rs : Fin n → Report w)
+ (step : ∀ i : Fin n, after (entry i.castSucc) (rs i).events = entry i.succ)
+ (frame : ∀ i : Fin n, entry i.succ a = entry i.castSucc a) : ReplayFrame a (entry 0) (List.ofFn rs) := by
+ induction n with
+ | zero => simp [ReplayFrame]
+ | succ n ih =>
+ rw [List.ofFn_succ]
+ constructor
+ · exact (congrFun (step 0) a).trans (frame 0)
+ · rw [show after (entry 0) (rs 0).events = entry (Fin.succ 0) from step 0]
+ exact ih (fun i => entry i.succ) (Fin.tail rs) (fun i => step i.succ) (fun i => frame i.succ)
+
+/-- A deterministic startup with address-preserving reports can precede any
+address-preserving suffix. The post-startup memory is obtained by replaying
+its complete event log, and its persistent word is the reported final cursor. -/
+theorem protects_after_replayed_prefix {n : ℕ} {logs : List (Report w)} {next : Word w}
+ (run : runSegment P fuel (some st) m (List.replicate n []) = some logs)
+ (finish : endState (some st) logs = some next)
+ (frame : ReplayFrame a m logs)
+ (suffix : ProtectsAddress P fuel next (after m (eventLog logs)) a) : ProtectsAddress P fuel st m a := by
+ induction n generalizing st m logs with
+ | zero =>
+ simp only [List.replicate_zero,runSegment,Option.some.injEq] at run
+ subst logs
+ change some st = some next at finish
+ exact Option.some.inj finish ▸ suffix
+ | succ n ih =>
+ rw [List.replicate_succ,runSegment] at run
+ cases call : execute P fuel (P.start st) m [] with
+ | none => simp [call] at run
+ | some r =>
+ simp only [call,Option.map_eq_some_iff] at run
+ obtain ⟨rest,run,rfl⟩ := run
+ change endState r.result rest = some next at finish
+ have tail : ProtectsAddress P fuel next (after (after m r.events) (eventLog rest)) a := by
+ rw [show after (after m r.events) (eventLog rest) = after m (eventLog (r::rest)) by
+ simp only [eventLog,List.flatMap_cons,after,List.foldl_append]]
+ exact @suffix
+ cases cont : r.result with
+ | none =>
+ rw [cont] at run finish
+ cases n with
+ | zero => simp [runSegment] at run; subst rest; contradiction
+ | succ n => simp [List.replicate_succ,runSegment] at run
+ | some cursor =>
+ rw [cont] at run finish
+ apply protects_after_empty_call call cont frame.1
+ apply ih run finish frame.2
+ exact @tail
+
+/-- The uniform memory frame implies the frame on the actual prefix. -/
+theorem protects_after_empty_prefix {n : ℕ} {logs : List (Report w)} {next : Word w}
+ (run : runSegment P fuel (some st) m (List.replicate n []) = some logs)
+ (finish : endState (some st) logs = some next)
+ (frame : ∀ r ∈ logs, ∀ mem, after mem r.events a = mem a)
+ (suffix : ProtectsAddress P fuel next (after m (eventLog logs)) a) : ProtectsAddress P fuel st m a := by
+ have lift (es : List (Report w)) (mem : Memory w)
+ (keep : ∀ r ∈ es, ∀ m', after m' r.events a = m' a) : ReplayFrame a mem es := by
+ induction es generalizing mem with
+ | nil => trivial
+ | cons r rs ih => exact ⟨keep r (by simp) mem, ih _ (fun q hq => keep q (List.mem_cons_of_mem _ hq))⟩
+ apply protects_after_replayed_prefix run finish (lift logs m frame)
+ exact @suffix
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAction.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAction.lean
new file mode 100644
index 0000000000..ece037af55
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAction.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMCell
+import OAI.Computability.VPVNP.LiveEvaluatorRAMDispatch
+
+/-!
+# Successful live evaluator instructions
+
+The preparing call chooses an instruction and publishes five words. A carried
+accept uses one all-zero-motion instruction. The two scheduled tape scans
+check the proposed target. Together these checks characterize exactly the
+nonrejecting successors of the bounded evaluator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAction
+
+open UniversalMachine LiveEvaluatorEncoding LiveEvaluatorStep
+
+variable {M extra : ℕ}
+
+/-- The five scratch fields written when carrying an accepting halt. -/
+def carry (extra : ℕ) : Instruction extra :=
+ ⟨⟨1, by omega⟩, 0, 0, 0, 0⟩
+
+/-- A selected native table slot. Canonical padding on a carried halt takes
+choice zero and malformed choices have no successful slot. -/
+def pick (p : Program) (old : Code p.extra M) (bit : Bool) : Option (Instruction p.extra) :=
+ match old with
+ | .accepted => if bit then none else some (carry _)
+ | .rejected => none
+ | .running c _ => chosenInstruction (row p c) bit
+
+/-- The native call consumes a branch bit exactly on a two-slot running row. -/
+def branchBits (p : Program) (s : Code p.extra M) (bit : Bool) : List Bool :=
+ match s with
+ | .running c _ => LiveEvaluatorRAMDispatch.dispatchBits (row p c) bit
+ | .accepted | .rejected => []
+
+/-- Accepted slots with identical native bit strings have the same padded
+witness bit. This also covers the zero-bit native accepting carry. -/
+theorem pick_bit_unique (p : Program) (s : Code p.extra M) {b b' : Bool} {a a' : Instruction p.extra}
+ (h : pick p s b = some a) (h' : pick p s b' = some a')
+ (hb : branchBits p s b = branchBits p s b') : b = b' := by
+ cases s with
+ | rejected => contradiction
+ | accepted => cases b <;> cases b' <;> simp_all [pick]
+ | running c hc =>
+ cases he : row p c <;> cases b <;> cases b' <;>
+ simp_all [pick, branchBits, chosenInstruction, LiveEvaluatorRAMDispatch.dispatchBits]
+
+/-- The first tape's finite cell window extracted from an encoded evaluator configuration. -/
+def first (s : Code extra M) : TapeWindow M := ⟨s.firstCell⟩
+/-- The second tape's finite cell window extracted from an encoded evaluator configuration. -/
+def second (s : Code extra M) : TapeWindow M := ⟨s.secondCell⟩
+
+/-- At an accepting target the comparison scans the zero tape fields. At a
+continuing target it scans the shift, write and clipped endpoints. -/
+def tapeCheck (halt : Bool) (old out : TapeWindow M) (write move : Symbol) : Prop :=
+ if halt then ∀ i, out.cells i = 0
+ else boundaryBlank old write move = true ∧ out = updatedWindow old write move
+
+/-- The successful-transition test requiring a positive matching target state and the proposed
+write and motion on both tape windows. -/
+def checks (old out : Code extra M) (a : Instruction extra) : Prop :=
+ 0 < a.target.val ∧ out.stateWord = a.target ∧
+ tapeCheck (decide (a.target.val = 1)) (first old) (first out) a.firstSymbol a.firstMove ∧
+ tapeCheck (decide (a.target.val = 1)) (second old) (second out) a.secondSymbol a.secondMove
+
+private theorem stateWord_accept_iff (z : Code extra M) : z.stateWord.val = 1 ↔ z = .accepted := by
+ cases z with
+ | accepted | rejected => simp [Code.stateWord]
+ | running c hc => simp [Code.stateWord, show c.state.val ≠ 1 by omega]
+
+private theorem checks_carry (z : Code extra M) : checks .accepted z (carry _) ↔ z = .accepted := by
+ constructor
+ · intro h
+ exact (stateWord_accept_iff z).mp (congrArg Fin.val h.2.1)
+ · rintro rfl
+ simp [checks, carry, first, second, tapeCheck, Code.stateWord, Code.firstCell, Code.secondCell]
+
+theorem checks_advance_iff (s : ConfigWindow extra M) (hs : 2 ≤ s.state.val) (z : Code extra M)
+ (a : Instruction extra) :
+ checks (.running s hs) z a ↔ advanceCode s a = some z ∧ z ≠ .rejected := by
+ by_cases ha : a.target.val = 1
+ · have hw (v : Code extra M) : v.stateWord = a.target ↔ v = .accepted := by
+ rw [Fin.ext_iff, ha, stateWord_accept_iff]
+ cases z <;> simp [checks, hw, advanceCode, ha, tapeCheck, first, second, Code.firstCell, Code.secondCell]
+ by_cases hr : a.target.val = 0
+ · simp [checks, advanceCode, hr, eq_comm]
+ have ht : 2 ≤ a.target.val := by omega
+ cases z with
+ | accepted =>
+ have hne : (Code.accepted (extra := extra) (M := M)).stateWord ≠ a.target :=
+ fun h => ha (congrArg Fin.val h.symm)
+ simp [checks, advanceCode, ha, hr, hne]
+ | rejected =>
+ have hne : (Code.rejected (extra := extra) (M := M)).stateWord ≠ a.target :=
+ fun h => hr (congrArg Fin.val h.symm)
+ simp [checks, hne]
+ | running z hz =>
+ have hfirst (v : ConfigWindow extra M) (hv : 2 ≤ v.state.val) :
+ first (.running v hv) = v.firstTape := rfl
+ have hsecond (v : ConfigWindow extra M) (hv : 2 ≤ v.state.val) :
+ second (.running v hv) = v.secondTape := rfl
+ simp [checks, tapeCheck, ha, Code.stateWord, hfirst, hsecond, advanceCode, hr,
+ show 0 < a.target.val by omega, ConfigWindow.ext_iff]
+ tauto
+
+/-- This equivalence preserves the specified choice bit, even for distinct
+slots whose five published words coincide. -/
+theorem pick_checks_iff (p : Program) (old out : Code p.extra M) (bit : Bool) :
+ (∃ a, pick p old bit = some a ∧ checks old out a) ↔
+ nextCode p old bit = some out ∧ out ≠ .rejected := by
+ cases old with
+ | accepted => cases bit <;> cases out <;> simp [pick, nextCode, checks_carry]
+ | rejected => simp [pick, nextCode, eq_comm]
+ | running s hs =>
+ simp only [pick, nextCode]
+ cases h : chosenInstruction (row p s) bit with
+ | none => simp [eq_comm]
+ | some a => simp [checks_advance_iff]
+
+end LiveEvaluatorAction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceBanks.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceBanks.lean
new file mode 100644
index 0000000000..63203b999c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceBanks.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.LiveEvaluatorInitialize
+import OAI.Computability.VPVNP.LiveHeaderAdvice
+
+/-!
+# Little-endian rows of the evaluator's distributed advice
+
+A row may be shorter than a machine word. Only the requested source bits
+enter it, and all higher bits and bits past the end of the source are zero.
+Writing one verified source bit with the RAM's shift and bitwise-or opcodes
+extends this partially assembled row. The same operation packs the raw
+evaluator prefix and the separate table of permutation ordinals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceBanks
+
+open BurstRAM (Word Memory)
+open BurstRAM.PrivateRAM (BinaryOp)
+open RAMSerialization (wordBits arrayBits)
+open PrimedInputRAM (encodeBit)
+
+/-- Pack the requested low-order source bits of one advice row into a machine word, zeroing
+unused positions and absent source bits. -/
+def packedPrefix (w fw : ℕ) (raw : List Bool) (row count : ℕ) : Word w :=
+ (wordBits w).symm (fun i => decide (i.val < fw ∧ i.val < count) && raw[row*fw+i.val]?.getD false)
+
+/-- Pack a complete advice row at the specified field width, using zero padding past the end of
+the raw advice. -/
+def packedWord (w fw : ℕ) (raw : List Bool) (row : ℕ) := packedPrefix w fw raw row fw
+
+theorem packedPrefix_bit (w fw : ℕ) (raw : List Bool) (row count : ℕ) (i : Fin w) :
+ (packedPrefix w fw raw row count).val.testBit i.val =
+ (decide (i.val < fw ∧ i.val < count) && raw[row*fw+i.val]?.getD false) := by
+ rw [LiveHeader.testBit_wordBits]
+ simp [packedPrefix]
+
+private theorem extBits {w : ℕ} {a b : Word w} (h : ∀ i : Fin w, a.val.testBit i.val = b.val.testBit i.val) :
+ a = b := by
+ apply (wordBits w).injective
+ funext i
+ simpa only [LiveHeader.testBit_wordBits] using h i
+
+theorem packedPrefix_zero (w fw : ℕ) (raw : List Bool) (row : ℕ) :
+ packedPrefix w fw raw row 0 = 0 := by
+ apply extBits
+ intro i
+ simp [packedPrefix_bit]
+
+private theorem insertBit {w : ℕ} (v : Word w) (bit : Bool) (k : Fin w) (i : Fin w) :
+ (BinaryOp.bitOr.eval v (BinaryOp.shiftLeft.eval (encodeBit w bit) (Fin.ofNat (2^w) k.val))).val.testBit i.val =
+ (v.val.testBit i.val || (decide (k = i) && bit)) := by
+ have hk : k.val < 2^w := k.isLt.trans (Nat.lt_two_pow_self (n := w))
+ have hv : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by have := k.isLt; omega))
+ have hshift : BinaryOp.shiftLeft.eval (encodeBit w bit) (Fin.ofNat (2^w) k.val) =
+ if bit then Fin.ofNat (2^w) (2^k.val) else 0 := by
+ cases bit <;> simp only [BinaryOp.eval, encodeBit, Fin.val_ofNat, Nat.mod_eq_of_lt hk,
+ k.isLt, ite_true, Bool.false_eq_true, ite_false, Fin.val_zero, hv, Nat.zero_shiftLeft, Nat.one_shiftLeft]
+ rfl
+ rw [hshift]
+ cases bit <;> simp [BinaryOp.eval, Nat.testBit_mod_two_pow, i.isLt, Nat.testBit_or,
+ Nat.testBit_two_pow, Fin.ext_iff]
+
+/-- Inserting the next source bit is exactly one native shift followed by bitwise or. -/
+theorem packedPrefix_succ (w fw : ℕ) (raw : List Bool) (row k : ℕ) (hk : k < fw) (hw : fw ≤ w) :
+ BinaryOp.bitOr.eval (packedPrefix w fw raw row k)
+ (BinaryOp.shiftLeft.eval (encodeBit w (raw[row*fw+k]?.getD false)) (Fin.ofNat (2^w) k)) =
+ packedPrefix w fw raw row (k+1) := by
+ apply extBits
+ intro i
+ rw [insertBit (k := (⟨k,hk.trans_le hw⟩ : Fin w)), packedPrefix_bit, packedPrefix_bit]
+ by_cases he : i.val = k
+ · simp [Fin.ext_iff, he, hk]
+ · by_cases hi : i.val < k
+ · simp [Fin.ext_iff, hi, hi.trans hk, show i.val < k+1 by omega, Ne.symm he]
+ · simp [Fin.ext_iff, hi, show ¬ i.val < k+1 by omega, Ne.symm he]
+
+/-- A cropped column past the end of the raw input leaves the row unchanged. -/
+theorem packedPrefix_skip (w fw : ℕ) (raw : List Bool) (row k : ℕ)
+ (hend : raw.length ≤ row*fw+k) :
+ packedPrefix w fw raw row (k+1) = packedPrefix w fw raw row k := by
+ apply extBits
+ intro i
+ rw [packedPrefix_bit, packedPrefix_bit]
+ by_cases he : i.val = k
+ · simp [he, List.getElem?_eq_none hend]
+ · by_cases hi : i.val < k
+ · simp [hi, show i.val < k+1 by omega]
+ · simp [hi, show ¬ i.val < k+1 by omega]
+
+/-- Full-width output rows are the words the midpoint initialization actually reads. -/
+theorem packedWord_inputWord (w : ℕ) (raw : List Bool) (row : ℕ) :
+ packedWord w w raw row = LiveEvaluatorInitialize.inputWord w raw row := by
+ apply (wordBits w).injective
+ funext i
+ simp [packedWord, packedPrefix, LiveEvaluatorInitialize.inputWord]
+
+/-- Packing a serialized array row returns that ordinal, extended to the runtime word width. -/
+theorem packedWord_arrayBits {w t fw : ℕ} (hw : fw ≤ w) (values : Fin t → Word fw) (j : Fin t) :
+ packedWord w fw (List.ofFn (arrayBits t fw values)) j.val =
+ Fin.castLE (Nat.pow_le_pow_right (by decide : 0 < 2) hw) (values j) := by
+ apply extBits
+ intro i
+ rw [packedWord, packedPrefix_bit]
+ by_cases hi : i.val < fw
+ · let k : Fin fw := ⟨i.val,hi⟩
+ let ix := finProdFinEquiv (j,k)
+ have hv : ix.val = j.val*fw+i.val := by simp [ix,k,finProdFinEquiv,Nat.add_comm,Nat.mul_comm]
+ have hbits : arrayBits t fw values ix = wordBits fw (values j) k := by
+ simp [ix,arrayBits]
+ rw [← hv, List.getElem?_ofFn, dite_eq_left ix.isLt]
+ simp [hi, hbits, ← LiveHeader.testBit_wordBits, k]
+ · have hz : (values j).val.testBit i.val = false := Nat.testBit_lt_two_pow (by
+ exact (values j).isLt.trans_le (Nat.pow_le_pow_right (by decide) (le_of_not_gt hi)))
+ simpa [hi] using hz.symm
+
+end LiveEvaluatorAdviceBanks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceDistribution.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceDistribution.lean
new file mode 100644
index 0000000000..dec766c20a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceDistribution.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.LiveHeaderAdvice
+import OAI.Computability.VPVNP.LiveEvaluatorAdvicePackSweep
+
+/-!
+# The distributed advice used to initialize the evaluator
+
+The copied header array carries the raw bit length as one little-endian word,
+the raw payload in a padded region, and the ordinal lookup table. These are
+precisely the three source regions of the native packing stages. The ordinal
+region begins at the end of the allocated payload capacity, independently of
+the actual raw length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceBanks
+
+open BurstRAM CutSchedule ChainAssignments
+open scoped Fin.CommRing
+
+variable {w ordW t a d h Δ : ℕ}
+
+/-- Little-endian length field of the raw evaluator input. -/
+def lengthBits (w : ℕ) (raw : List Bool) : List Bool := wordBits (Fin.ofNat (2^w) raw.length : Word w)
+
+/-- Little-endian, row-major ordinal table. -/
+def ordinalBits (values : Fin t → Word ordW) := List.ofFn (RAMSerialization.arrayBits t ordW values)
+
+/-- Complete advice layout with the two allocated padding regions. -/
+def distribution (w capacity : ℕ) (raw : List Bool) (values : Fin t → Word ordW) (padding : ℕ) : List Bool :=
+ lengthBits w raw ++ (raw ++ (List.replicate (capacity-raw.length) false ++
+ (ordinalBits values ++ List.replicate padding false)))
+
+@[simp] theorem length_lengthBits (w : ℕ) (raw : List Bool) : (lengthBits w raw).length = w := by
+ simp [lengthBits]
+
+@[simp] theorem length_ordinalBits (values : Fin t → Word ordW) :
+ (ordinalBits values).length = t*ordW := by simp [ordinalBits]
+
+theorem distribution_length (capacity padding : ℕ) (raw : List Bool) (values : Fin t → Word ordW)
+ (hfit : raw.length ≤ capacity) :
+ (distribution w capacity raw values padding).length = w + capacity + t*ordW + padding := by
+ simp [distribution]
+ omega
+
+/-- A copied header array supplies every native word read of any contiguous
+sublist, including a zero-length sublist. -/
+theorem packSource_of_slice {m : Memory w} {advice : Bits a} {base : ℕ}
+ (copied : ∀ i : Fin a, m (base+i.val) = PrimedInputRAM.encodeBit w (advice i))
+ (pub : Fin 5 → Word w) (pre chunk tail : List Bool)
+ (htape : List.ofFn advice = pre ++ (chunk ++ tail)) (hbase : (pub 0).val = base + pre.length) :
+ PackSource pub chunk m := by
+ intro j hj
+ have hlen := congrArg List.length htape
+ simp only [List.length_ofFn, List.length_append] at hlen
+ let i : Fin a := ⟨pre.length + j, by omega⟩
+ have he := congrArg (fun xs : List Bool => xs[pre.length+j]?) htape
+ change (List.ofFn advice)[pre.length+j]? = (pre ++ (chunk ++ tail))[pre.length+j]? at he
+ rw [List.getElem?_ofFn, dite_eq_left i.isLt, List.getElem?_append_right (by omega),
+ Nat.add_sub_cancel_left, List.getElem?_append_left hj] at he
+ have hbit : advice i = chunk[j]?.getD false := by rw [← he]; rfl
+ simpa only [i, hbase, Nat.add_assoc, ← hbit] using copied i
+
+/-- The copied advice bits suffice to identify the three source regions. -/
+theorem distribution_sources_of_copied {advice : Bits a}
+ {base capacity padding : ℕ} {m : Memory w} {raw : List Bool} {values : Fin t → Word ordW}
+ (copied : ∀ i : Fin a, m (base+i.val) = PrimedInputRAM.encodeBit w (advice i))
+ (lenPub rawPub ordPub : Fin 5 → Word w)
+ (htape : List.ofFn advice = distribution w capacity raw values padding)
+ (hraw : raw.length ≤ capacity) (hl : (lenPub 0).val = base)
+ (hr : (rawPub 0).val = base+w) (ho : (ordPub 0).val = base+w+capacity) :
+ PackSource lenPub (lengthBits w raw) m ∧ PackSource rawPub raw m ∧ PackSource ordPub (ordinalBits values) m := by
+ have h₁ := packSource_of_slice copied lenPub [] (lengthBits w raw)
+ (raw ++ (List.replicate (capacity-raw.length) false ++ (ordinalBits values ++ List.replicate padding false)))
+ htape hl
+ have h₂ := packSource_of_slice copied rawPub (lengthBits w raw) raw
+ (List.replicate (capacity-raw.length) false ++ (ordinalBits values ++ List.replicate padding false))
+ htape (by simpa using hr)
+ let pre := lengthBits w raw ++ (raw ++ List.replicate (capacity-raw.length) false)
+ have hpre : pre.length = w+capacity := by simp [pre]; omega
+ have h₃ := packSource_of_slice copied ordPub pre (ordinalBits values) (List.replicate padding false)
+ (by simpa [pre, distribution, List.append_assoc] using htape) (by rw [hpre, ho, Nat.add_assoc])
+ exact ⟨h₁, h₂, h₃⟩
+
+/-- The physical header copy supplies exactly the input required by each
+native packing call. The source of the ordinal table is fixed by capacity. -/
+theorem distribution_sources {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ} {g : Fin (2^(h+1))}
+ {base capacity padding : ℕ} {m₀ m : Memory w} {raw : List Bool} {values : Fin t → Word ordW}
+ (img : LiveHeader.AdviceImage (d := d) hw advice cuts g base m₀ m)
+ (lenPub rawPub ordPub : Fin 5 → Word w)
+ (htape : List.ofFn advice = distribution w capacity raw values padding)
+ (hraw : raw.length ≤ capacity) (hl : (lenPub 0).val = base)
+ (hr : (rawPub 0).val = base+w) (ho : (ordPub 0).val = base+w+capacity) :
+ PackSource lenPub (lengthBits w raw) m ∧ PackSource rawPub raw m ∧ PackSource ordPub (ordinalBits values) m :=
+ distribution_sources_of_copied img.copied lenPub rawPub ordPub htape hraw hl hr ho
+
+/-- Packing the first full word recovers the actual raw length without truncation. -/
+theorem packed_length (raw : List Bool) (hfit : raw.length < 2^w) :
+ (packedWord w w (lengthBits w raw) 0).val = raw.length := by
+ have he : packedWord w w (lengthBits w raw) 0 = Fin.ofNat (2^w) raw.length := by
+ apply (RAMSerialization.wordBits w).injective
+ funext i
+ simp [packedWord, packedPrefix, lengthBits, wordBits]
+ rw [he, Fin.val_ofNat, Nat.mod_eq_of_lt hfit]
+
+/-- The native length sweep returns that length in the designated word. -/
+theorem packMemory_length (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w)
+ (hwidth : (pub 2).val = w) (hrows : 0 < (pub 4).val) (hfit : raw.length < 2^w) :
+ (packMemory pub (lengthBits w raw) m (packCalls pub) (pub 1).val).val = raw.length := by
+ have he := packMemory_full pub (lengthBits w raw) m 0 hrows
+ rw [Nat.add_zero, hwidth] at he
+ rw [he]
+ exact packed_length raw hfit
+
+/-- Each full-width raw payload row is the packed input word of initialization. -/
+theorem packMemory_raw (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w)
+ (hwidth : (pub 2).val = w) (j : ℕ) (hj : j < (pub 4).val) :
+ packMemory pub raw m (packCalls pub) ((pub 1).val+j) = LiveEvaluatorInitialize.inputWord w raw j := by
+ rw [packMemory_full pub raw m j hj, hwidth]
+ exact packedWord_inputWord w raw j
+
+/-- Each ordinal keeps its source value when extended to the working word width. -/
+theorem packMemory_ordinal (pub : Fin 5 → Word w) (values : Fin t → Word ordW) (m : Memory w)
+ (hwidth : (pub 2).val = ordW) (hw : ordW ≤ w) (hrows : t ≤ (pub 4).val) (j : Fin t) :
+ packMemory pub (ordinalBits values) m (packCalls pub) ((pub 1).val+j.val) =
+ (values j).castLE (Nat.pow_le_pow_right (by decide : 0 < 2) hw) := by
+ rw [packMemory_full pub _ m _ (j.isLt.trans_le hrows), hwidth]
+ exact packedWord_arrayBits hw values j
+
+/-- Source bits for a later packing stage remain available after a disjoint
+earlier stage, including after any partial prefix of its execution. -/
+theorem PackSource.after_other_bank {m : Memory w} {pub : Fin 5 → Word w} {bits : List Bool}
+ (hs : PackSource pub bits m) (other : Fin 5 → Word w) (raw : List Bool) (i : ℕ)
+ (sep : (pub 0).val + bits.length ≤ (other 1).val ∨
+ (other 1).val + (other 4).val ≤ (pub 0).val) :
+ PackSource pub bits (packMemory other raw m i) := by
+ intro j hj
+ rw [packMemory_outside other raw m i _ (by omega), hs j hj]
+
+end LiveEvaluatorAdviceBanks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrameReadback.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrameReadback.lean
new file mode 100644
index 0000000000..ecb5a46f6f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrameReadback.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceFrames
+import OAI.Computability.VPVNP.CompressorRecordFrame
+
+/-!
+# Reading the published midpoint frames on the native machine
+
+Every successful initializer call has the same empty choice stream and
+the specified report. Its four output arrays are exactly the public
+operand banks that the external-frame compiler fetches for later stages.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceFrames
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem store_no_choices {pub : FramePub w} {st : Word w}
+ (ss : List (Option (Fin 32))) {rs m es out m'} (h : Flow.Exec pub st (storeFlow ss) rs m es out m') :
+ choiceBits es = [] := by
+ induction ss generalizing rs m es out m' with
+ | nil => cases h with | line he => exact Flow.line_choices he
+ | cons a ss ih =>
+ cases a with
+ | none =>
+ cases h with
+ | seq hl hr => cases hl with | line he => simp only [Flow.choiceBits_append, Flow.line_choices he, ih hr, List.nil_append]
+ | some r =>
+ cases h with
+ | seq hl hr =>
+ cases hl with
+ | line he =>
+ cases hr with
+ | seq hi ht =>
+ cases hi with
+ | line hg => simp only [Flow.choiceBits_append, Flow.line_choices he, Flow.line_choices hg, ih ht, List.nil_append]
+
+private theorem valid_body {pub : FramePub w} {st : Word w} {rs m es out m'}
+ (h : Flow.Exec pub st body rs m es out m') :
+ actualLength pub m ≤ pub 1 ∧ 0 < pub 2 ∧ choiceBits es = [] := by
+ cases h with
+ | seq hs hr =>
+ obtain ⟨hcap,hw,hes,-,-⟩ := (setup_iff pub st rs m _ _ _).mp hs
+ have hb : choiceBits (setupEvents pub m) = [] := rfl
+ exact ⟨hcap,hw,by rw [Flow.choiceBits_append, hes, hb, store_no_choices _ hr]; rfl⟩
+
+/-- Exact acceptance and report for any sufficient clock, including the native
+surplus-choice rejection at the single-call stage exit. -/
+theorem execute_frames_iff (pub : FramePub w) (st : Word w) (m : Memory w) (bs : List Bool)
+ (fuel : ℕ) (hf : 83 ≤ fuel) (r : Report w) :
+ let machine := template.instantiate w pub
+ execute machine.program fuel (machine.program.start st) m bs = some r ↔
+ actualLength pub m ≤ pub 1 ∧ 0 < pub 2 ∧ bs = [] ∧ r = ⟨events pub m,none⟩ := by
+ have run (hcap : actualLength pub m ≤ pub 1) (hw : 0 < pub 2) :
+ let machine := template.instantiate w pub
+ execute machine.program fuel (machine.program.start st) m [] = some ⟨events pub m,none⟩ := by
+ have h := (execute_frames pub st m hcap hw).1
+ obtain ⟨out,mem,he,hr,hlen,hb⟩ := (Flow.template_execute_iff body none pub st _ _ m 83 [] _).mp h
+ exact (Flow.template_execute_iff body none pub st _ _ m fuel [] _).mpr
+ ⟨out,mem,he,hr,lt_of_lt_of_le hlen hf,hb⟩
+ constructor
+ · intro h
+ obtain ⟨out,mem,he,-,-,hb⟩ := (Flow.template_execute_iff body none pub st _ _ m fuel bs r).mp h
+ obtain ⟨hc,hw,hbits⟩ := valid_body he
+ have hbs := hb.symm.trans hbits
+ rw [hbs] at h
+ exact ⟨hc,hw,hbs,Option.some.inj (h.symm.trans (run hc hw))⟩
+ · rintro ⟨hc,hw,rfl,rfl⟩
+ exact run hc hw
+
+private theorem offsetData {k : ℕ} (base : Word w) (mem : Memory w) (offset : ℕ)
+ (hfit : base.val+offset+k ≤ 2^w) (j : Fin k) :
+ CompressorRecords.Frame.data (base + (offset : Word w)) mem j = mem (base.val+offset+j.val) := by
+ have ho : offset < 2^w := by have := j.isLt; omega
+ have hv : ((offset : Word w) : ℕ) = offset := Nat.mod_eq_of_lt ho
+ have hbase : (base+(offset : Word w)).val = base.val+offset :=
+ (Fin.val_add_eq_of_add_lt (by rw [hv]; have := j.isLt; omega)).trans (congrArg (base.val + ·) hv)
+ rw [CompressorRecords.Frame.data_at _ _ (by rw [hbase]; exact hfit), hbase]
+
+/-- The four operand banks seen through the exact loader used by `Frame.compile`. -/
+theorem frameData (pub : FramePub w) (m : Memory w) (hw : 0 < w) (hf : (pub 3).val+22 ≤ 2^w) :
+ let out := published pub m
+ CompressorRecords.Frame.data (pub 3) out = prefixFrame pub m ∧
+ CompressorRecords.Frame.data (pub 3+8) out = copyFrame pub m ∧
+ CompressorRecords.Frame.data (pub 3+13) out = skeletonFrame pub m ∧
+ CompressorRecords.Frame.data (pub 3+17) out = scatterFrame pub m := by
+ obtain ⟨hP,hC,hS,hE⟩ := published_at pub m hw hf
+ dsimp only
+ refine ⟨funext (fun j => ?_), funext (fun j => ?_), funext (fun j => ?_), funext (fun j => ?_)⟩
+ · exact (CompressorRecords.Frame.data_at _ _ (by omega) j).trans (hP j)
+ · exact (offsetData _ _ 8 (by omega) j).trans (hC j)
+ · exact (offsetData _ _ 13 (by omega) j).trans (hS j)
+ · exact (offsetData _ _ 17 (by omega) j).trans (hE j)
+
+end LiveEvaluatorAdviceFrames
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrameSetup.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrameSetup.lean
new file mode 100644
index 0000000000..74a984289b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrameSetup.lean
@@ -0,0 +1,277 @@
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import Mathlib.Data.ZMod.Defs
+import Mathlib.Algebra.Order.Floor.Div
+import Mathlib.Tactic.Ring
+
+/-!
+# Computing the middle-group operand frames
+
+The length word at frame offset 22 specifies how many bits of the reserved
+prefix belong to the evaluator. Its value is checked against the capacity.
+The computed destination for runtime fields follows the actual prefix on
+the tape, while the order table begins beyond the reserved prefix in the
+distributed advice. Quotient and remainder round the number of packed
+words up without adding the full word width to the prefix length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceFrames
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+/-- A native advice-frame initializer flow with 32 registers and eleven public operands. -/
+abbrev FrameCode := Flow 32 11
+/-- The eleven public words supplied to the midpoint advice-frame initializer. -/
+abbrev FramePub (w : ℕ) := Fin 11 → Word w
+variable {w : ℕ}
+
+private abbrev Ops := List (Op 32 11)
+
+private def install (rs : Regs w 32) (vs : List (Fin 32 × Word w)) :=
+ vs.foldl (fun r kv => Function.update r kv.1 kv.2) rs
+
+/-- The address at frame offset 22 that stores the actual evaluator prefix length. -/
+def lengthAddress (pub : FramePub w) : Word w := pub 3 + 22
+/-- Read the evaluator prefix's actual bit length from its reserved frame cell. -/
+def actualLength (pub : FramePub w) (m : Memory w) := m (lengthAddress pub).val
+
+/-- Number of packed prefix words, computed from the checked exact length. -/
+def prefixRows (pub : FramePub w) (m : Memory w) : Word w :=
+ let a := actualLength pub m
+ let q := BinaryOp.div.eval a (pub 2)
+ if BinaryOp.mod.eval a (pub 2) = 0 then q else q + 1
+
+/-- The first runtime field address on the tape after the input data and actual evaluator
+prefix. -/
+def runtimeBase (pub : FramePub w) (m : Memory w) : Word w :=
+ pub 6 + 1 + pub 5 + actualLength pub m
+
+/-- The total word count of the runtime skeleton computed from the two public dimensions. -/
+def skeletonSize (pub : FramePub w) : Word w := 2 * pub 8 + 6 * pub 7 + 4
+
+/-- The first exponent-scatter destination after the leading runtime fields. -/
+def scatterBase (pub : FramePub w) (m : Memory w) : Word w :=
+ runtimeBase pub m + 2 * pub 7 + 2
+
+/-- Public operands are advice base, prefix capacity, width, frame base,
+packed prefix base, radius, old-state base, exponent width, exponent bank
+length, incoming exponent base and permutation map base. -/
+private def loadOps : Ops :=
+ [.constant 0 0, .constant 1 1, .constant 2 2, .constant 3 3,
+ .publicWord 4 3, .publicWord 5 1, .publicWord 6 2, .publicWord 7 0, .publicWord 8 4,
+ .publicWord 9 5, .publicWord 10 6, .publicWord 11 7, .publicWord 12 8,
+ .publicWord 13 9, .publicWord 14 10,
+ .binary .mul 22 3 3, .binary .add 22 22 2, .binary .add 22 22 22, .binary .add 22 4 22,
+ .read 15 22, .copy 22 4]
+
+private def load : FrameCode := lines loadOps (by decide)
+
+private def loaded (pub : FramePub w) (rs : Regs w 32) (m : Memory w) :=
+ install rs [(0,0),(1,1),(2,2),(3,3),(4,pub 3),(5,pub 1),(6,pub 2),(7,pub 0),(8,pub 4),
+ (9,pub 5),(10,pub 6),(11,pub 7),(12,pub 8),(13,pub 9),(14,pub 10),(22,3*3),
+ (22,3*3+2),(22,(3*3+2)+(3*3+2)),(22,lengthAddress pub),(15,actualLength pub m),(22,pub 3)]
+
+private def loadEvents (pub : FramePub w) (m : Memory w) : List (Event w) :=
+ List.replicate 19 .tick ++ [.read (lengthAddress pub) (actualLength pub m),.tick]
+
+private theorem load_iff (pub : FramePub w) (st : Word w) (rs : Regs w 32) (m : Memory w) (es out m') :
+ Flow.Exec pub st load rs m es out m' ↔ es = loadEvents pub m ∧ out = loaded pub rs m ∧ m' = m := by
+ rw [load, PrimedCounter.Admin.exec_lines_iff_trace]
+ have h22 : (3*3+2 : Word w) + (3*3+2) = 22 := by ring
+ have ht : trace pub st loadOps rs m = some (loadEvents pub m,loaded pub rs m,m) := by
+ unfold loadEvents loaded actualLength lengthAddress
+ rw [← h22]
+ rfl
+ rw [ht]; simp [eq_comm]
+
+private def computeOps : Ops :=
+ [.binary .add 16 7 6, .binary .div 17 15 6, .binary .mod 18 15 6,
+ .binary .add 19 10 1, .binary .add 19 19 9, .binary .add 19 19 15,
+ .binary .add 23 11 11, .binary .add 24 23 23, .binary .add 20 23 24,
+ .binary .add 24 12 12, .binary .add 20 20 24, .binary .add 24 2 2,
+ .binary .add 20 20 24, .binary .add 21 19 23, .binary .add 21 21 2]
+
+private def compute : FrameCode := lines computeOps (by decide)
+
+private def computed (pub : FramePub w) (rs : Regs w 32) (m : Memory w) :=
+ let a := actualLength pub m
+ let z := pub 7
+ let twoZ := z+z
+ let fourZ := twoZ+twoZ
+ let sixZ := twoZ+fourZ
+ let twoTZ := pub 8 + pub 8
+ install (loaded pub rs m)
+ [(16,pub 0+pub 2),(17,BinaryOp.div.eval a (pub 2)),(18,BinaryOp.mod.eval a (pub 2)),
+ (19,pub 6+1),(19,pub 6+1+pub 5),(19,runtimeBase pub m),
+ (23,twoZ),(24,fourZ),(20,sixZ),(24,twoTZ),(20,sixZ+twoTZ),(24,2+2),
+ (20,skeletonSize pub),(21,runtimeBase pub m+twoZ),(21,scatterBase pub m)]
+
+private theorem compute_iff (pub : FramePub w) (st : Word w) (rs : Regs w 32) (m : Memory w) (es out m') :
+ Flow.Exec pub st compute (loaded pub rs m) m es out m' ↔
+ es = List.replicate 15 .tick ∧ out = computed pub rs m ∧ m' = m := by
+ rw [compute, PrimedCounter.Admin.exec_lines_iff_trace]
+ have hsize : skeletonSize pub =
+ (pub 7 + pub 7 + ((pub 7 + pub 7) + (pub 7 + pub 7))) + (pub 8 + pub 8) + (2+2) := by
+ unfold skeletonSize; ring
+ have hbase : scatterBase pub m = runtimeBase pub m + (pub 7+pub 7) + 2 := by
+ unfold scatterBase; ring
+ have ht : trace pub st computeOps (loaded pub rs m) m =
+ some (List.replicate 15 .tick,computed pub rs m,m) := by
+ unfold computed
+ rw [hsize,hbase]
+ rfl
+ rw [ht]; simp [eq_comm]
+
+private def reject : FrameCode := .line (.guardLt 0 0)
+private def roundUp : FrameCode := .ifEq 18 0 (.line (.copy 17 17)) (.line (.binary .add 17 17 1))
+
+/-- Read and validate the actual prefix length and field width, then compute destinations and
+the rounded-up prefix row count. -/
+def setup : FrameCode :=
+ .seq load (.ifLt 5 15 reject (.seq (.line (.guardLt 0 6)) (.seq compute roundUp)))
+
+/-- The bank of computed operands before publication. -/
+def ready (pub : FramePub w) (rs : Regs w 32) (m : Memory w) : Regs w 32 :=
+ Function.update (computed pub rs m) 17 (prefixRows pub m)
+
+/-- The initializer's load events followed by the local ticks used to compute the four frames'
+operands. -/
+def setupEvents (pub : FramePub w) (m : Memory w) : List (Event w) :=
+ loadEvents pub m ++ List.replicate 19 .tick
+
+private theorem round_iff (pub : FramePub w) (st : Word w) (rs : Regs w 32) (m : Memory w)
+ (es out m') :
+ Flow.Exec pub st roundUp (computed pub rs m) m es out m' ↔
+ es = [.tick,.tick] ∧ out = ready pub rs m ∧ m' = m := by
+ let r := computed pub rs m
+ let q := BinaryOp.div.eval (actualLength pub m) (pub 2)
+ let rem := BinaryOp.mod.eval (actualLength pub m) (pub 2)
+ have hrem : r 18 = rem := rfl
+ have hq : r 17 = q := rfl
+ have h0 : r 0 = 0 := rfl
+ have h1 : r 1 = 1 := rfl
+ have hz : (r 18 = r 0) = (rem = 0) := by rw [hrem,h0]
+ constructor
+ · intro h
+ cases h with
+ | ifEqYes hh hb =>
+ cases hb with
+ | line he =>
+ have hn : rem = 0 := hz ▸ hh
+ simpa [Op.effect, ready, prefixRows, hn, ← hq, ← hrem, r, rem, q, eq_comm] using he
+ | ifEqNo hh hb =>
+ cases hb with
+ | line he =>
+ have hn : rem ≠ 0 := fun h => hh (hz.symm ▸ h)
+ have hr : ready pub rs m = Function.update r 17 (r 17 + r 1) := by
+ change Function.update r 17 (if rem = 0 then q else q+1) = _
+ rw [ite_eq_right hn, h1, hq]
+ rw [hr]
+ simpa [Op.effect, BinaryOp.eval, r, eq_comm] using he
+ · rintro ⟨rfl,rfl,rfl⟩
+ by_cases hn : rem = 0
+ · apply Flow.Exec.ifEqYes (hz.symm ▸ hn)
+ apply Flow.Exec.line
+ simp only [Op.effect, ready, prefixRows, show BinaryOp.mod.eval (actualLength pub _) (pub 2) = 0 from hn,
+ ite_true]
+ rfl
+ · apply Flow.Exec.ifEqNo (fun h => hn (hz ▸ h))
+ apply Flow.Exec.line
+ simp only [Op.effect, ready, prefixRows, show BinaryOp.mod.eval (actualLength pub _) (pub 2) ≠ 0 from hn,
+ ite_false]
+ rfl
+
+theorem setup_iff (pub : FramePub w) (st : Word w) (rs : Regs w 32) (m : Memory w) (es out m') :
+ Flow.Exec pub st setup rs m es out m' ↔
+ actualLength pub m ≤ pub 1 ∧ 0 < pub 2 ∧
+ es = setupEvents pub m ∧ out = ready pub rs m ∧ m' = m := by
+ constructor
+ · intro h
+ cases h with
+ | seq hl h =>
+ obtain ⟨rfl,rfl,rfl⟩ := (load_iff pub st rs m _ _ _).mp hl
+ cases h with
+ | ifLtYes _ hbad =>
+ cases hbad with | line he => simp [Op.effect] at he
+ | ifLtNo hn h =>
+ cases h with
+ | seq hg h =>
+ cases hg with
+ | line he =>
+ change (if 0 < pub 2 then some _ else none) = _ at he
+ split at he
+ · rename_i hp
+ obtain ⟨rfl,rfl,rfl⟩ := by simpa using he
+ cases h with
+ | seq hc hr =>
+ obtain ⟨rfl,rfl,rfl⟩ := (compute_iff pub st rs _ _ _ _).mp hc
+ obtain ⟨rfl,rfl,rfl⟩ := (round_iff pub st rs _ _ _ _).mp hr
+ exact ⟨le_of_not_gt hn,hp,rfl,rfl,rfl⟩
+ · contradiction
+ · rintro ⟨hcap,hpos,rfl,rfl,rfl⟩
+ exact .seq ((load_iff pub st rs _ _ _ _).mpr ⟨rfl,rfl,rfl⟩)
+ (.ifLtNo (not_lt_of_ge hcap) (.seq (.line (by simp [Op.effect, show loaded pub rs _ 0 = 0 from rfl,
+ show loaded pub rs _ 6 = pub 2 from rfl, hpos]))
+ (.seq ((compute_iff pub st rs _ _ _ _).mpr ⟨rfl,rfl,rfl⟩)
+ ((round_iff pub st rs _ _ _ _).mpr ⟨rfl,rfl,rfl⟩))))
+
+
+/-- The validated length is read at the ordinary reserved address. -/
+theorem actualLength_at (pub : FramePub w) (m : Memory w) (hfit : (pub 3).val+22 < 2^w) :
+ actualLength pub m = m ((pub 3).val+22) := by
+ have hv : (22 : Word w).val = 22 := Nat.mod_eq_of_lt (show (22 : ℕ) < 2^w by omega)
+ rw [actualLength, lengthAddress, Fin.val_add_eq_of_add_lt (by rw [hv]; exact hfit), hv]
+
+private theorem ceilDiv_remainder (a b : ℕ) (hb : 0 < b) :
+ a ⌈/⌉ b = a / b + (if a % b = 0 then 0 else 1) := by
+ have hm := Nat.mod_lt a hb
+ have hd := Nat.div_add_mod a b
+ rw [Nat.ceilDiv_eq_add_pred_div, show a+b-1 = b*(a/b)+(a%b+b-1) by omega, Nat.mul_add_div hb]
+ by_cases h : a%b = 0
+ · simp [h, Nat.div_eq_of_lt (show b-1 < b by omega)]
+ · rw [ite_eq_right h]
+ congr 1
+ apply Nat.div_eq_of_lt_le <;> omega
+
+/-- Exact natural word count in the prefix packer's fifth operand. -/
+theorem prefixRows_val (pub : FramePub w) (m : Memory w) (hw : 0 < (pub 2).val) :
+ (prefixRows pub m).val = (actualLength pub m).val ⌈/⌉ (pub 2).val := by
+ let a := actualLength pub m
+ let b := pub 2
+ have hr : (BinaryOp.mod.eval a b).val = a.val % b.val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt a.isLt)
+ have hq : (BinaryOp.div.eval a b).val = a.val / b.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt a.isLt)
+ change 0 < b.val at hw
+ change (if BinaryOp.mod.eval a b = 0 then BinaryOp.div.eval a b else BinaryOp.div.eval a b + 1).val = a.val ⌈/⌉ b.val
+ rw [ceilDiv_remainder _ _ hw]
+ by_cases h : a.val % b.val = 0
+ · have he : BinaryOp.mod.eval a b = 0 := Fin.ext (hr.trans h)
+ simp only [ite_eq_left he, hq, h, ite_true, Nat.add_zero]
+ · have he : BinaryOp.mod.eval a b ≠ 0 := fun e => h (hr.symm.trans (congrArg Fin.val e))
+ have ha : 0 < a.val := by
+ by_contra! hh
+ exact h (by rw [show a.val = 0 by omega, Nat.zero_mod])
+ have hb : 1 < b.val := by
+ by_contra! hh
+ exact h (by rw [show b.val = 1 by omega, Nat.mod_one])
+ have hv : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (show (1 : ℕ) < 2^w from hb.trans b.isLt)
+ have hsum : (BinaryOp.div.eval a b).val + (1 : Word w).val < 2^w := by
+ rw [hq,hv]; have := Nat.div_lt_self ha hb; have := a.isLt; omega
+ simp only [ite_eq_right he, Fin.val_add_eq_of_add_lt hsum, hq, hv, ite_eq_right h]
+
+/-- The initializer's register calculations depend on the read length alone. -/
+theorem ready_congr_length (pub : FramePub w) (rs : Regs w 32) (m u : Memory w)
+ (h : actualLength pub m = actualLength pub u) : ready pub rs m = ready pub rs u := by
+ simp only [ready, computed, loaded, runtimeBase, scatterBase, prefixRows, h]
+
+end LiveEvaluatorAdviceFrames
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrameStore.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrameStore.lean
new file mode 100644
index 0000000000..e733e40744
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrameStore.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import Mathlib.Data.ZMod.Defs
+import Mathlib.Tactic.Ring
+
+/-!
+# Writing an advice frame with reserved holes
+
+Register 22 points at the first frame word and register 1 holds the stride.
+A present slot writes its source register, while a hole leaves memory intact.
+Both advance the cursor by the same stride.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceFrames
+
+open BurstRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- A static schedule of register stores and holes. -/
+def storeFlow : List (Option (Fin 32)) → Flow 32 11
+ | [] => .line (.guardEq 0 0)
+ | none :: rest => .seq (.line (.binary .add 22 22 1)) (storeFlow rest)
+ | some r :: rest => .seq (.line (.write 22 r)) (.seq (.line (.binary .add 22 22 1)) (storeFlow rest))
+
+private def advance (rs : Regs w 32) := Function.update rs 22 (rs 22 + rs 1)
+
+/-- Advance the frame-writing cursor once per slot, including reserved holes, to obtain the
+registers after publication. -/
+def storeRegs : List (Option (Fin 32)) → Regs w 32 → Regs w 32
+ | [], rs => rs
+ | _ :: rest, rs => storeRegs rest (advance rs)
+
+/-- The memory after writing each present register word into its frame slot and advancing over
+reserved holes. -/
+def frameMemory : List (Option (Fin 32)) → Regs w 32 → Memory w → Memory w
+ | [], _, m => m
+ | none :: rest, rs, m => frameMemory rest (advance rs) m
+ | some r :: rest, rs, m => frameMemory rest (advance rs) (writeMemory m (rs 22) (rs r))
+
+/-- The chronological frame writes and cursor-advance ticks for the given slot assignment. -/
+def storeEvents : List (Option (Fin 32)) → Regs w 32 → List (Event w)
+ | [], _ => [.tick]
+ | none :: rest, rs => .tick :: storeEvents rest (advance rs)
+ | some r :: rest, rs => .write (rs 22) (rs r) :: .tick :: storeEvents rest (advance rs)
+
+/-- Exact registers, external memory and events after the fixed instruction schedule. -/
+theorem store_exec (pub : Fin 11 → Word w) (st : Word w) (slots : List (Option (Fin 32)))
+ (rs : Regs w 32) (m : Memory w) :
+ Flow.Exec pub st (storeFlow slots) rs m (storeEvents slots rs) (storeRegs slots rs) (frameMemory slots rs m) := by
+ induction slots generalizing rs m with
+ | nil => exact .line (by simp [Op.effect, storeRegs, frameMemory])
+ | cons slot rest ih =>
+ cases slot with
+ | none => exact (Flow.Exec.line rfl).seq (ih (advance rs) m)
+ | some r => exact (Flow.Exec.line rfl).seq ((Flow.Exec.line rfl).seq (ih (advance rs) _))
+
+theorem storeRegs_other (slots : List (Option (Fin 32))) (rs : Regs w 32) (r : Fin 32) (hr : r ≠ 22) :
+ storeRegs slots rs r = rs r := by
+ induction slots generalizing rs with
+ | nil => rfl
+ | cons x xs ih => exact (ih _).trans (Function.update_of_ne hr ..)
+
+theorem storeRegs_cursor (slots : List (Option (Fin 32))) (rs : Regs w 32) :
+ storeRegs slots rs 22 = rs 22 + (slots.length : Word w) * rs 1 := by
+ induction slots generalizing rs with
+ | nil => simp [storeRegs]
+ | cons x xs ih =>
+ rw [storeRegs, ih, List.length_cons, Nat.cast_add, Nat.cast_one]
+ change rs 22 + rs 1 + (xs.length : Word w) * rs 1 = _
+ ring
+
+theorem storeEvents_counts (slots : List (Option (Fin 32))) (rs : Regs w 32) :
+ choiceBits (storeEvents slots rs) = [] ∧ countProbes (storeEvents slots rs) = (slots.filterMap id).length ∧
+ (storeEvents slots rs).length = slots.length + (slots.filterMap id).length + 1 := by
+ induction slots generalizing rs with
+ | nil => exact ⟨rfl, rfl, rfl⟩
+ | cons slot rest ih =>
+ obtain ⟨hb, hp, hl⟩ := ih (advance rs)
+ cases slot <;> simp [storeEvents, countProbes, choiceBits, hb, hp, hl] <;> omega
+
+/-- The natural-address version of the same sequence, using the fixed entry
+bank for all source registers. -/
+private def naturalMemory : List (Option (Fin 32)) → Regs w 32 → ℕ → Memory w → Memory w
+ | [], _, _, m => m
+ | none :: rest, rs, base, m => naturalMemory rest rs (base+1) m
+ | some r :: rest, rs, base, m => naturalMemory rest rs (base+1) (Function.update m base (rs r))
+
+private theorem natural_eq (slots : List (Option (Fin 32))) (rs source : Regs w 32) (m : Memory w)
+ (hsrc : ∀ r, some r ∈ slots → rs r = source r) (hno : some 22 ∉ slots)
+ (h1 : (rs 1).val = 1) (hfit : (rs 22).val + slots.length ≤ 2 ^ w) :
+ frameMemory slots rs m = naturalMemory slots source (rs 22).val m := by
+ induction slots generalizing rs m with
+ | nil => rfl
+ | cons slot rest ih =>
+ have hn : some (22 : Fin 32) ∉ rest := fun h => hno (List.mem_cons_of_mem _ h)
+ have hsrc' (r : Fin 32) (hr : some r ∈ rest) : advance rs r = source r := by
+ have hne : r ≠ 22 := fun h => hn (h ▸ hr)
+ exact (Function.update_of_ne hne ..).trans (hsrc _ (List.mem_cons_of_mem _ hr))
+ have hw (r : Fin 32) : writeMemory m (rs 22) (rs r) = Function.update m (rs 22).val (rs r) := by
+ funext a
+ by_cases h : a = (rs 22).val <;> simp [writeMemory, h]
+ by_cases hnil : rest = []
+ · subst rest
+ cases slot with
+ | none => rfl
+ | some r => rw [frameMemory, naturalMemory, hw, hsrc r (by simp)]; rfl
+ · have hpos : 0 < rest.length := List.length_pos_iff.mpr hnil
+ have hv : (advance rs 22).val = (rs 22).val + 1 := by
+ change (rs 22 + rs 1).val = _
+ simp only [List.length_cons] at hfit
+ rw [Fin.val_add, h1, Nat.mod_eq_of_lt (by omega)]
+ have hf : (advance rs 22).val + rest.length ≤ 2^w := by rw [hv]; simp only [List.length_cons] at hfit; omega
+ cases slot with
+ | none => rw [frameMemory, naturalMemory, ih _ _ hsrc' hn h1 hf, hv]
+ | some r => rw [frameMemory, naturalMemory, ih _ _ hsrc' hn h1 hf, hv, hw, hsrc r (by simp)]
+
+private theorem natural_outside (slots : List (Option (Fin 32))) (rs : Regs w 32) (m : Memory w)
+ (base a : ℕ) (ha : a < base ∨ base + slots.length ≤ a) :
+ naturalMemory slots rs base m a = m a := by
+ induction slots generalizing base m with
+ | nil => rfl
+ | cons x xs ih =>
+ simp only [List.length_cons] at ha
+ cases x with
+ | none => exact ih _ _ (by omega)
+ | some r => exact (ih _ _ (by omega)).trans (Function.update_of_ne (by omega : a ≠ base) ..)
+
+/-- Words outside the frame survive every write. -/
+theorem frameMemory_outside (slots : List (Option (Fin 32))) (rs : Regs w 32) (m : Memory w)
+ (h1 : (rs 1).val = 1) (hfit : (rs 22).val + slots.length ≤ 2^w) (hno : some 22 ∉ slots)
+ (a : ℕ) (ha : a < (rs 22).val ∨ (rs 22).val + slots.length ≤ a) : frameMemory slots rs m a = m a := by
+ rw [natural_eq slots rs rs m (fun _ _ => rfl) hno h1 hfit]
+ exact natural_outside slots rs m _ a ha
+
+private theorem natural_at (slots : List (Option (Fin 32))) (rs : Regs w 32) (m : Memory w)
+ (base i : ℕ) (hi : i < slots.length) :
+ naturalMemory slots rs base m (base+i) = (slots[i].map rs).getD (m (base+i)) := by
+ induction slots generalizing base i m with
+ | nil => simp at hi
+ | cons slot rest ih =>
+ cases i with
+ | zero =>
+ cases slot <;> rw [naturalMemory, natural_outside rest rs _ _ _ (by omega)]
+ · rfl
+ · simp
+ | succ i =>
+ have hi' : i < rest.length := by simpa using hi
+ have he : base + (i+1) = base+1+i := by omega
+ cases slot with
+ | none => rw [naturalMemory, he, ih _ _ _ hi']; rfl
+ | some r =>
+ rw [naturalMemory, he, ih _ _ _ hi', Function.update_of_ne (by omega : base+1+i ≠ base)]
+ rfl
+
+/-- A written slot reads back its entry register, while a hole reads back the entry memory. -/
+theorem frameMemory_at (slots : List (Option (Fin 32))) (rs : Regs w 32) (m : Memory w)
+ (h1 : (rs 1).val = 1) (hfit : (rs 22).val + slots.length ≤ 2^w) (hno : some 22 ∉ slots)
+ (i : ℕ) (hi : i < slots.length) :
+ frameMemory slots rs m ((rs 22).val+i) = (slots[i].map rs).getD (m ((rs 22).val+i)) := by
+ rw [natural_eq slots rs rs m (fun _ _ => rfl) hno h1 hfit]
+ exact natural_at slots rs m _ i hi
+
+end LiveEvaluatorAdviceFrames
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrames.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrames.lean
new file mode 100644
index 0000000000..56dc52b9b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceFrames.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceFrameSetup
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceFrameStore
+import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete
+import OAI.Computability.VPVNP.PrimedCounterCallPaths
+import OAI.Computability.VPVNP.PrimedStackRAMLeafVisit
+
+/-!
+# Publishing the four midpoint operand frames
+
+The native initializer reads the packed prefix length at offset 22, checks
+its capacity, and writes the operands of the prefix packer, input copy,
+runtime skeleton and exponent scatter. Their frames start at offsets 0, 8,
+13 and 17. The three holes at 5–7 and the stored length at 22 are preserved.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceFrames
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The register-to-frame assignment for the four midpoint workers, reserving holes at offsets
+5 through 7. -/
+def slots : List (Option (Fin 32)) :=
+ [some 16,some 8,some 6,some 15,some 17,none,none,none,
+ some 9,some 10,some 8,some 6,some 15,
+ some 11,some 12,some 19,some 20,
+ some 13,some 14,some 21,some 11,some 12]
+
+/-- Compute the midpoint operands and store them into their assigned slots in the shared frame. -/
+def body : FrameCode := .seq setup (storeFlow slots)
+
+/-- One deterministic native call. Its normal exit accepts the stage. -/
+def template := body.template none
+
+/-- The five operands for packing the evaluator prefix, including source, destination, field
+width, actual bit count, and row count. -/
+def prefixFrame (pub : FramePub w) (m : Memory w) : Fin 5 → Word w :=
+ ![pub 0+pub 2, pub 4, pub 2, actualLength pub m, prefixRows pub m]
+
+/-- The five words supplying the input-copy worker with its input size, tape location, packed
+advice location, field width, and prefix length. -/
+def copyFrame (pub : FramePub w) (m : Memory w) : Fin 5 → Word w :=
+ ![pub 5, pub 6, pub 4, pub 2, actualLength pub m]
+
+/-- The runtime skeleton's two size parameters, computed base address, and total length. -/
+def skeletonFrame (pub : FramePub w) (m : Memory w) : Fin 4 → Word w :=
+ ![pub 7, pub 8, runtimeBase pub m, skeletonSize pub]
+
+/-- The five operands used to scatter production exponents into the runtime area. -/
+def scatterFrame (pub : FramePub w) (m : Memory w) : Fin 5 → Word w :=
+ ![pub 9, pub 10, scatterBase pub m, pub 7, pub 8]
+
+/-- The external memory after computing and writing all four midpoint operand frames. -/
+def published (pub : FramePub w) (m : Memory w) : Memory w :=
+ frameMemory slots (ready pub (fun _ => 0) m) m
+
+/-- The successful initializer's complete load, calculation, and frame-store event sequence. -/
+def events (pub : FramePub w) (m : Memory w) : List (Event w) :=
+ setupEvents pub m ++ storeEvents slots (ready pub (fun _ => 0) m)
+
+private theorem body_exec (pub : FramePub w) (st : Word w) (m : Memory w)
+ (hcap : actualLength pub m ≤ pub 1) (hw : 0 < pub 2) :
+ Flow.Exec pub st body (fun _ => 0) m (events pub m)
+ (storeRegs slots (ready pub (fun _ => 0) m)) (published pub m) :=
+ .seq ((setup_iff pub st _ m _ _ _).mpr ⟨hcap,hw,rfl,rfl,rfl⟩) (store_exec ..)
+
+/-- The sole length read and 19 operand writes are the only external probes. -/
+theorem events_cost (pub : FramePub w) (m : Memory w) :
+ choiceBits (events pub m) = [] ∧ countProbes (events pub m) = 20 ∧ (events pub m).length = 82 := by
+ obtain ⟨hb,hp,hl⟩ := storeEvents_counts slots (ready pub (fun _ => 0) m)
+ have h0 : choiceBits (setupEvents pub m) = [] := rfl
+ have h1 : countProbes (setupEvents pub m) = 1 := rfl
+ have h2 : (setupEvents pub m).length = 40 := rfl
+ simp only [events, Flow.choiceBits_append, PrimedStackRAM.probes_append, List.length_append,
+ h0,h1,h2,hb,hp,hl]
+ decide
+
+theorem execute_frames (pub : FramePub w) (st : Word w) (m : Memory w)
+ (hcap : actualLength pub m ≤ pub 1) (hw : 0 < pub 2) :
+ let machine := template.instantiate w pub
+ execute machine.program 83 (machine.program.start st) m [] = some ⟨events pub m,none⟩ ∧
+ after m (events pub m) = published pub m := by
+ have he := body_exec pub st m hcap hw
+ have ⟨hb,_,hl⟩ := events_cost pub m
+ constructor
+ · apply (Flow.template_execute_iff body none pub st (fun _ => 0) (fun _ => 0) m 83 [] _).mpr
+ exact ⟨_,_,he,rfl,by simp [hl],hb⟩
+ · exact PrimedCounter.Call.exec_memory he
+
+/-- A malformed length or a zero word-width parameter rejects at any fuel and on every stream. -/
+theorem reject_frames (pub : FramePub w) (st : Word w) (m : Memory w) (bs : List Bool) (fuel : ℕ)
+ (hb : pub 1 < actualLength pub m ∨ pub 2 = 0) :
+ let machine := template.instantiate w pub
+ execute machine.program fuel (machine.program.start st) m bs = none := by
+ apply Option.eq_none_iff_forall_not_mem.mpr
+ intro r hr
+ obtain ⟨_,_,he,-⟩ := (Flow.template_execute_iff body none pub st _ _ m fuel bs r).mp hr
+ generalize hev : r.events = es at he
+ cases he with
+ | seq hs _ =>
+ obtain ⟨hl,hw,-⟩ := (setup_iff pub st _ m _ _ _).mp hs
+ rcases hb with h | h
+ · exact (not_lt_of_ge hl) h
+ · rw [h] at hw; exact (lt_irrefl _) hw
+
+/-- The exact stored frame payloads as read by the dynamic operand adapter. -/
+structure PublishedAt (pub : FramePub w) (m out : Memory w) : Prop where
+ prefixWord (i : Fin 5) : out ((pub 3).val + i.val) = prefixFrame pub m i
+ copyWord (i : Fin 5) : out ((pub 3).val + 8 + i.val) = copyFrame pub m i
+ skeletonWord (i : Fin 4) : out ((pub 3).val + 13 + i.val) = skeletonFrame pub m i
+ scatterWord (i : Fin 5) : out ((pub 3).val + 17 + i.val) = scatterFrame pub m i
+
+theorem published_at (pub : FramePub w) (m : Memory w) (hw : 0 < w) (hfit : (pub 3).val+22 ≤ 2^w) :
+ PublishedAt pub m (published pub m) := by
+ let r := ready pub (fun _ => 0) m
+ have h1 : (r 1).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')
+ have hv (i : ℕ) (hi : i < 22) :
+ published pub m ((pub 3).val+i) = ((slots[i]'hi).map r).getD (m ((pub 3).val+i)) :=
+ frameMemory_at slots r m h1 hfit (by decide) i hi
+ constructor <;> intro i <;> fin_cases i <;>
+ simp only [Nat.add_assoc] <;> rw [hv _ (by decide)] <;> rfl
+
+theorem published_outside (pub : FramePub w) (m : Memory w) (hw : 0 < w)
+ (hfit : (pub 3).val+22 ≤ 2^w) (k : ℕ) (hk : k < (pub 3).val ∨ (pub 3).val+22 ≤ k) :
+ published pub m k = m k :=
+ frameMemory_outside slots _ m (Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')) hfit (by decide) k hk
+
+end LiveEvaluatorAdviceFrames
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePackStage.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePackStage.lean
new file mode 100644
index 0000000000..ca45f2734b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePackStage.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAdvicePackSweep
+
+/-!
+# Advice packing as a linkable stage
+
+The wrapped table uses the ordinary sweep when rows are allocated. An empty
+bank takes one accepting call with zero probes, so the stage linker advances
+in both cases. The unique accepting stream has one empty list per call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceBanks
+
+open BurstRAM
+
+variable {w : ℕ}
+
+/-- Allocated nonempty rows have one reset plus one call per column. The
+empty bank has one accepting call at its zero cursor. -/
+def stageCalls (pub : Fin 5 → Word w) := max 1 (packCalls pub)
+
+/-- At an individual cursor the native stage produces one deterministic report
+and advances the entire row-prefix memory, including the empty-bank handoff. -/
+theorem stageStep {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (m : Memory w) (hs : PackSource pub raw m) {fuel : ℕ} (hf : stageFuel ≤ fuel)
+ (i : ℕ) (hi : i < stageCalls pub) :
+ let P := (stageTable.instantiate w pub).program
+ let mem := packMemory pub raw m (min i (packCalls pub))
+ ∃ es, (∀ bs, execute P fuel (P.start (Fin.ofNat (2^w) i)) mem bs =
+ if bs = [] then some ⟨es, packControl w (stageCalls pub) (i+1)⟩ else none) ∧
+ after mem es = packMemory pub raw m (min (i+1) (packCalls pub)) ∧ countProbes es ≤ 3 := by
+ intro P mem
+ by_cases hz : pub 4 = 0
+ · have hpack : packCalls pub = 0 := by simp [packCalls, hz]
+ have hcount : stageCalls pub = 1 := by simp [stageCalls, hpack]
+ have hzero : i = 0 := by omega
+ subst i
+ have hmem : mem = m := by simp [mem, hpack, packMemory_zero]
+ rw [hmem]
+ let rep := stageReport pub 0 m
+ refine ⟨rep.events, ?_, ?_, stageReport_probes_le ..⟩
+ · intro bs
+ have hx := execute_stage_empty pub m hz (fun _ => 0) (fun _ => 0) bs hf
+ change execute P fuel (P.start 0) m bs = if bs.isEmpty then some rep else none at hx
+ have hs : packControl w (stageCalls pub) 1 = none := by simp [packControl, hcount]
+ have hr : rep = ⟨rep.events, packControl w (stageCalls pub) 1⟩ := by
+ rw [hs]
+ simp [rep, stageReport, hz]
+ rw [← hr]
+ cases bs <;> exact hx
+ · simp [hpack, packMemory_zero, rep, stageReport_memory, hz]
+ · have hpos : 0 < packCalls pub := by
+ have h : 0 < (pub 4).val := Nat.pos_of_ne_zero fun he => hz (Fin.ext he)
+ exact Nat.mul_pos h (Nat.succ_pos _)
+ have hcount : stageCalls pub = packCalls pub := max_eq_right hpos
+ rw [hcount] at hi
+ have hm' : mem = packMemory pub raw m i := by rw [show mem = packMemory pub raw m (min i (packCalls pub)) from rfl, min_eq_left hi.le]
+ have hsrc : PackSource pub raw mem := hm' ▸ packMemory_source pub raw m L hs i
+ let st := Fin.ofNat (2^w) i
+ obtain ⟨hcur, hb, hnext⟩ := packStep_guards L mem hsrc i hi
+ let rep := stageReport pub st mem
+ refine ⟨rep.events, ?_, ?_, stageReport_probes_le ..⟩
+ · intro bs
+ have hx := execute_stage_step pub st mem hz hcur hb (fun _ => 0) (fun _ => 0) bs hf
+ change execute P fuel (P.start st) mem bs = if bs.isEmpty then some rep else none at hx
+ have hr : rep = ⟨rep.events, packControl w (stageCalls pub) (i+1)⟩ := by
+ rw [hcount, ← hnext]
+ simp [rep, stageReport, hz, st]
+ rw [← hr]
+ cases bs <;> exact hx
+ · change after mem (stageReport pub st mem).events = _
+ rw [stageReport_memory, ite_eq_right hz, hm']
+ rw [min_eq_left hi]
+ exact packMemory_step L m hs i hi
+
+/-- The linked-stage table prepares all word rows and has one exact native
+stream, including when there are zero output rows. -/
+theorem packStageSweep {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (m : Memory w) (hs : PackSource pub raw m) {fuel : ℕ} (hf : stageFuel ≤ fuel) :
+ let P := (stageTable.instantiate w pub).program
+ ∃ reports, after m (eventLog reports) = packMemory pub raw m (packCalls pub) ∧
+ reports.length = stageCalls pub ∧ RAMBuckets.cost Report.probes reports ≤ 4*stageCalls pub ∧
+ (∀ r ∈ reports, r.probes ≤ 3 ∧ r.events.length < fuel) ∧
+ ∀ bits rs, (runSegment P fuel (some 0) m bits = some rs ∧ endState (some 0) rs = none) ↔
+ bits = List.replicate (stageCalls pub) [] ∧ rs = reports := by
+ intro P
+ let inv := fun i mem => mem = packMemory pub raw m (min i (packCalls pub))
+ have initial : inv 0 m := by simp [inv, packMemory_zero]
+ have step (i : ℕ) (hi : i < stageCalls pub) (mem : Memory w) (hm : inv i mem) := hm ▸ stageStep L m hs hf i hi
+ have hn : 0 < stageCalls pub := Nat.zero_lt_one.trans_le (le_max_left ..)
+ have hc : packControl w (stageCalls pub) 0 = some 0 := by simp [packControl, hn.ne]
+ have hle : packCalls pub ≤ stageCalls pub := le_max_right ..
+ simpa only [hc, inv, min_eq_right hle] using
+ deterministic_scan P fuel (stageCalls pub) 3 inv step (stageCalls pub) 0 (Nat.zero_add _) m initial
+
+/-- The wrapper has native path multiplicity one under Lemma 10.1's caps. -/
+theorem packStagePathCount {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (m : Memory w) (hs : PackSource pub raw m) {fuel : ℕ} (hf : stageFuel ≤ fuel)
+ {S H : ℕ} (hcost : 4*stageCalls pub ≤ S*H) (hcap : 4 ≤ H) :
+ Nat.card (ActualPaths (stageTable.instantiate w pub).program fuel 0 m (withinCaps S H)) = 1 := by
+ let paths := ActualPaths (stageTable.instantiate w pub).program fuel 0 m (withinCaps S H)
+ obtain ⟨reports, _, _, hc, hcalls, hall⟩ := packStageSweep L m hs hf
+ have hwithin : withinCaps S H reports :=
+ ⟨hc.trans hcost, fun r hr => by have := (hcalls r hr).1; omega⟩
+ have uniq (b : paths) : b.val = List.replicate (stageCalls pub) [] := by
+ obtain ⟨rs, hr, he, _⟩ := b.property
+ exact ((hall b.val rs).mp ⟨hr, he⟩).1
+ have ⟨hr, he⟩ := (hall (List.replicate (stageCalls pub) []) reports).mpr ⟨rfl, rfl⟩
+ exact Nat.card_eq_one_iff_unique.mpr
+ ⟨⟨fun a b => Subtype.ext ((uniq a).trans (uniq b).symm)⟩,
+ ⟨⟨List.replicate (stageCalls pub) [], reports, hr, he, hwithin⟩⟩⟩
+
+end LiveEvaluatorAdviceBanks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePackStep.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePackStep.lean
new file mode 100644
index 0000000000..273590a8f4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePackStep.lean
@@ -0,0 +1,396 @@
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PrimedCounterCallPaths
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import Mathlib.Data.ZMod.Defs
+
+/-!
+# Packing the evaluator's advice bit banks
+
+The initial cursor of each output row writes zero to the destination word.
+Each of its remaining cursors installs one low-endian bit if that bit lies
+in the actual raw advice. The padding cursors leave the partial final word
+intact. Every call makes at most three probes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceBanks
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+/-- A native advice-packing flow with 32 registers and five public operands. -/
+abbrev PackCode := Flow 32 5
+variable {w : ℕ}
+
+/-- Number of cursor positions per packed row, including the initial clear and one position per
+source bit. -/
+def stride (pub : Fin 5 → Word w) := pub 2 + 1
+/-- Number of advice-packing cursor positions across all destination rows. -/
+def total (pub : Fin 5 → Word w) := pub 4 * stride pub
+/-- Recover the packed row number from a linear packing cursor. -/
+def row (pub : Fin 5 → Word w) (st : Word w) := BinaryOp.div.eval st (stride pub)
+/-- Recover the position within a packing row, with zero reserved for clearing its destination. -/
+def column (pub : Fin 5 → Word w) (st : Word w) := BinaryOp.mod.eval st (stride pub)
+/-- The zero-based raw advice bit index corresponding to a bit-installation cursor. -/
+def index (pub : Fin 5 → Word w) (st : Word w) := row pub st * pub 2 + (column pub st - 1)
+/-- The packed destination word address for the current row. -/
+def dst (pub : Fin 5 → Word w) (st : Word w) := pub 1 + row pub st
+/-- The raw advice bit address for the current bit-installation cursor. -/
+def src (pub : Fin 5 → Word w) (st : Word w) := pub 0 + index pub st
+
+/-- The specified native shift and OR of the bit read and the accumulated destination. -/
+def packedValue (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) :=
+ BinaryOp.bitOr.eval (m (dst pub st).val) (BinaryOp.shiftLeft.eval (m (src pub st).val) (column pub st - 1))
+
+/-- The memory effect of one packing cursor, clearing a new row, installing an in-range bit, or
+skipping padding. -/
+def stepMemory (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) : Memory w :=
+ if column pub st = 0 then writeMemory m (dst pub st) 0
+ else if index pub st < pub 3 then writeMemory m (dst pub st) (packedValue pub st m)
+ else m
+
+private def load : PackCode := straight (.constant 0 0)
+ [.constant 1 1, .constant 2 2, .publicWord 3 0, .publicWord 4 1, .publicWord 5 2,
+ .publicWord 6 3, .publicWord 7 4, .stateWord 8, .binary .add 9 5 1, .binary .mul 30 7 9,
+ .binary .div 10 8 9, .binary .mod 11 8 9, .binary .add 12 4 10, .binary .sub 13 11 1,
+ .binary .mul 14 10 5, .binary .add 14 14 13, .binary .add 15 3 14, .binary .add 29 8 1]
+
+private def installBit : PackCode := straight (.read 16 15)
+ [.guardLt 16 2, .read 17 12, .binary .shiftLeft 18 16 13, .binary .bitOr 19 17 18, .write 12 19]
+
+/-- Public words in order are source bit base, destination word base, field
+width, actual source length and number of destination rows. -/
+def stepBody : PackCode := .seq load (.seq (.line (.guardLt 8 30))
+ (.ifEq 11 0 (.line (.write 12 0)) (.ifLt 14 6 installBit (.line (.copy 20 0)))))
+
+/-- The native call template implementing one advice-packing cursor step. -/
+def stepTable := PrimedCounter.Call.template stepBody 29 30
+
+private def loadRegs (pub : Fin 5 → Word w) (st : Word w) (r : Regs w 32) : Regs w 32 :=
+ let f : List (Fin 32 × Word w) := [(0,0), (1,1), (2,2), (3,pub 0), (4,pub 1), (5,pub 2),
+ (6,pub 3), (7,pub 4), (8,st), (9,stride pub), (30,total pub), (10,row pub st), (11,column pub st),
+ (12,dst pub st), (13,column pub st-1), (14,row pub st * pub 2), (14,index pub st),
+ (15,src pub st), (29,st+1)]
+ f.foldl (fun s x => Function.update s x.1 x.2) r
+
+private def bitRegs (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) (r : Regs w 32) : Regs w 32 :=
+ let f : List (Fin 32 × Word w) := [(16,m (src pub st).val), (17,m (dst pub st).val),
+ (18,BinaryOp.shiftLeft.eval (m (src pub st).val) (column pub st-1)), (19,packedValue pub st m)]
+ f.foldl (fun s x => Function.update s x.1 x.2) r
+
+private def bitEvents (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) : List (Event w) :=
+ [.read (src pub st) (m (src pub st).val), .tick, .read (dst pub st) (m (dst pub st).val), .tick,
+ .tick, .write (dst pub st) (packedValue pub st m)]
+
+/-- The local ticks and probes of a packing step, selected by the row-clear, in-range bit, or
+padding case. -/
+def stepEvents (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) : List (Event w) :=
+ List.replicate 19 .tick ++ [.tick] ++ .tick ::
+ (if column pub st = 0 then [.write (dst pub st) 0] else .tick ::
+ (if index pub st < pub 3 then bitEvents pub st m else [.tick]))
+
+/-- The packing step's events and return state, closing at the end of the last row. -/
+def stepReport (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) : Report w :=
+ ⟨stepEvents pub st m ++ [.tick], if st+1 = total pub then none else some (st+1)⟩
+
+private theorem load_exec (pub : Fin 5 → Word w) (st : Word w) (r : Regs w 32) (m : Memory w) :
+ Flow.Exec pub st load r m (List.replicate 19 .tick) (loadRegs pub st r) m :=
+ (Flow.once_sound pub st false load r m rfl).1
+
+private theorem installBit_exec (pub : Fin 5 → Word w) (st : Word w) (r : Regs w 32) (m : Memory w)
+ (hb : m (src pub st).val < (2 : Word w)) :
+ let s := loadRegs pub st r
+ Flow.Exec pub st installBit s m (bitEvents pub st m) (bitRegs pub st m s)
+ (writeMemory m (dst pub st) (packedValue pub st m)) := by
+ intro s
+ let readRegs := Function.update s (16 : Fin 32) (m (src pub st).val)
+ have hg : Flow.Exec pub st (.line (.guardLt 16 2)) readRegs m [.tick] readRegs m := by
+ apply Flow.Exec.line
+ change (if m (src pub st).val < (2 : Word w) then some _ else none) = _
+ rw [ite_eq_left hb]
+ exact (Flow.Exec.line rfl).seq (hg.seq ((Flow.Exec.line rfl).seq
+ ((Flow.Exec.line rfl).seq ((Flow.Exec.line rfl).seq (Flow.Exec.line rfl)))))
+
+/-- Every valid cursor produces the specified trace and final memory, with
+the next cursor and total in the common closing registers. -/
+theorem step_exec (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) (r : Regs w 32)
+ (hcur : st < total pub)
+ (hbit : column pub st ≠ 0 → index pub st < pub 3 → m (src pub st).val < (2 : Word w)) :
+ ∃ out, Flow.Exec pub st stepBody r m (stepEvents pub st m) out (stepMemory pub st m) ∧
+ out 29 = st+1 ∧ out 30 = total pub := by
+ let s := loadRegs pub st r
+ have hg : Flow.Exec pub st (.line (.guardLt 8 30)) s m [.tick] s m := by
+ apply Flow.Exec.line
+ change (if st < total pub then some _ else none) = _
+ rw [ite_eq_left hcur]
+ have hl := load_exec pub st r m
+ by_cases hz : column pub st = 0
+ · rw [stepEvents, stepMemory, ite_eq_left hz, ite_eq_left hz]
+ exact ⟨s, hl.seq (hg.seq (.ifEqYes hz (.line rfl))), rfl, rfl⟩
+ · by_cases hi : index pub st < pub 3
+ · rw [stepEvents, stepMemory, ite_eq_right hz, ite_eq_right hz, ite_eq_left hi, ite_eq_left hi]
+ exact ⟨_, hl.seq (hg.seq (.ifEqNo hz (.ifLtYes hi (installBit_exec pub st r m (hbit hz hi))))), rfl, rfl⟩
+ · rw [stepEvents, stepMemory, ite_eq_right hz, ite_eq_right hz, ite_eq_right hi, ite_eq_right hi]
+ exact ⟨_, hl.seq (hg.seq (.ifEqNo hz (.ifLtNo hi (.line rfl)))), rfl, rfl⟩
+
+theorem stepReport_memory (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) :
+ after m (stepReport pub st m).events = stepMemory pub st m := by
+ unfold stepReport stepEvents stepMemory
+ split_ifs <;> rfl
+
+theorem stepReport_probes_le (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) :
+ (stepReport pub st m).probes ≤ 3 := by
+ unfold stepReport stepEvents
+ split_ifs <;> first | exact (by decide : 1 ≤ 3) | exact (by decide : 3 ≤ 3) | exact (by decide : 0 ≤ 3)
+
+private theorem stepEvents_bounds (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) :
+ (stepEvents pub st m).length ≤ 28 ∧ choiceBits (stepEvents pub st m) = [] := by
+ unfold stepEvents
+ split_ifs <;> exact ⟨by simp [bitEvents], rfl⟩
+
+/-- At most 28 body instructions and two closing instructions. -/
+def callFuel : ℕ := 30
+
+theorem stepReport_length_le (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) :
+ (stepReport pub st m).events.length ≤ 29 := by
+ simpa [stepReport] using Nat.succ_le_succ (stepEvents_bounds pub st m).1
+
+/-- Native execution rejects surplus choice bits. Every valid cursor with a
+canonical source bit returns its single deterministic report. -/
+theorem execute_step (pub : Fin 5 → Word w) (st : Word w) (m : Memory w)
+ (hcur : st < total pub)
+ (hbit : column pub st ≠ 0 → index pub st < pub 3 → m (src pub st).val < (2 : Word w))
+ (rs : Regs w 32) (priv : Word w → Word w) (choices : List Bool) {fuel : ℕ} (hf : callFuel ≤ fuel) :
+ let mach := stepTable.instantiate w pub
+ execute mach.program fuel ⟨mach.entry, st, rs, priv⟩ m choices =
+ if choices.isEmpty then some (stepReport pub st m) else none := by
+ obtain ⟨out, run, hn, ht⟩ := step_exec pub st m rs hcur hbit
+ obtain ⟨hlen, hb⟩ := stepEvents_bounds pub st m
+ have h := PrimedCounter.Call.execute_body stepBody 29 30 pub st rs priv m run choices
+ (fuel - ((stepEvents pub st m).length + 2))
+ rw [show (stepEvents pub st m).length + (fuel - ((stepEvents pub st m).length + 2) + 2) = fuel by
+ unfold callFuel at hf; omega, hn, ht, hb, List.nil_append] at h
+ exact h
+
+private theorem trace_of_straight {pub : Fin 5 → Word w} {st : Word w} {r out : Regs w 32}
+ {m mem : Memory w} {es : List (Event w)} {op : Op 32 5} {ops : List (Op 32 5)}
+ (h : Flow.Exec pub st (straight op ops) r m es out mem) :
+ trace pub st (op :: ops) r m = some (es, out, mem) :=
+ (PrimedCounter.Admin.exec_lines_iff_trace (ops := op :: ops) (by simp)).mp h
+
+private theorem guard_result {pub : Fin 5 → Word w} {st : Word w} {r out : Regs w 32}
+ {m mem : Memory w} {es : List (Event w)} {i j : Fin 32}
+ (h : Flow.Exec pub st (.line (.guardLt i j)) r m es out mem) :
+ r i < r j ∧ out = r ∧ mem = m := by
+ cases h with
+ | line he =>
+ by_cases hlt : r i < r j
+ · simp only [Op.effect, hlt, ite_true, Option.some.injEq, Prod.mk.injEq] at he
+ exact ⟨hlt, he.2.1.symm, he.2.2.symm⟩
+ · simp [Op.effect, hlt] at he
+
+/-- The source-range test is imposed only for data columns that read a real bit.
+An invalid cursor or a nonbinary word read from that interval cannot exit. -/
+theorem step_required {pub : Fin 5 → Word w} {st : Word w} {m mem : Memory w} {r out : Regs w 32}
+ {es : List (Event w)} (run : Flow.Exec pub st stepBody r m es out mem) :
+ st < total pub ∧ (column pub st ≠ 0 → index pub st < pub 3 → m (src pub st).val < (2 : Word w)) := by
+ cases run with
+ | seq hl ht =>
+ have hx := trace_of_straight hl
+ have hy := trace_of_straight (load_exec pub st r m)
+ obtain ⟨-, rfl, rfl⟩ := (show _ ∧ _ ∧ _ by simpa using hx.symm.trans hy)
+ cases ht with
+ | seq hg htail =>
+ obtain ⟨hcur, rfl, rfl⟩ := guard_result hg
+ refine ⟨hcur, ?_⟩
+ intro hz hi
+ cases htail with
+ | ifEqYes he _ => exact (hz he).elim
+ | ifEqNo _ hc =>
+ cases hc with
+ | ifLtNo hn _ => exact (hn hi).elim
+ | ifLtYes _ hb =>
+ cases hb with
+ | seq hread hrest =>
+ cases hread with
+ | line he =>
+ simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at he
+ obtain ⟨-, rfl, rfl⟩ := he
+ cases hrest with
+ | seq hg _ => exact (guard_result hg).1
+
+/-- Exact successful reports on arbitrary raw memory and arbitrary choices,
+including rejection of nonbinary source words and out-of-range cursors. -/
+theorem execute_step_iff (pub : Fin 5 → Word w) (st : Word w) (m : Memory w)
+ (rs : Regs w 32) (priv : Word w → Word w) (choices : List Bool) {fuel : ℕ}
+ (hf : callFuel ≤ fuel) (rep : Report w) :
+ let mach := stepTable.instantiate w pub
+ execute mach.program fuel ⟨mach.entry, st, rs, priv⟩ m choices = some rep ↔
+ st < total pub ∧ (column pub st ≠ 0 → index pub st < pub 3 → m (src pub st).val < (2 : Word w)) ∧
+ choices = [] ∧ rep = stepReport pub st m := by
+ constructor
+ · intro h
+ obtain ⟨_, _, _, run, -⟩ := (PrimedCounter.Call.execute_iff stepBody 29 30 pub st rs priv m choices fuel rep).mp h
+ obtain ⟨hc, hb⟩ := step_required run
+ rw [execute_step pub st m hc hb rs priv choices hf] at h
+ cases choices with
+ | nil => exact ⟨hc, hb, rfl, (Option.some.inj h).symm⟩
+ | cons => cases h
+ · rintro ⟨hc, hb, rfl, rfl⟩
+ exact execute_step pub st m hc hb rs priv [] hf
+
+private def stageStart : PackCode := straight (.constant 0 0) [.publicWord 7 4]
+
+private def emptyStage : PackCode := straight (.stateWord 8)
+ [.guardEq 8 0, .constant 29 1, .constant 30 1]
+
+/-- The linkable stage treats an empty bank as one accepting call at cursor zero. -/
+def stageBody : PackCode := .seq stageStart (.ifEq 7 0 emptyStage stepBody)
+
+/-- The native advice-packing stage template, including the test for a zero row count. -/
+def stageTable := PrimedCounter.Call.template stageBody 29 30
+
+/-- The 33-step private clock bound for a native advice-packing stage call. -/
+def stageFuel : ℕ := 33
+
+/-- Native report with the row-count test included in the event stream. -/
+def stageReport (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) : Report w :=
+ if pub 4 = 0 then ⟨List.replicate 8 .tick, none⟩ else
+ ⟨List.replicate 3 .tick ++ (stepReport pub st m).events, (stepReport pub st m).result⟩
+
+private def stageRegs (pub : Fin 5 → Word w) (rs : Regs w 32) : Regs w 32 :=
+ Function.update (Function.update rs 0 0) 7 (pub 4)
+
+private theorem stageStart_exec (pub : Fin 5 → Word w) (st : Word w) (rs : Regs w 32) (m : Memory w) :
+ Flow.Exec pub st stageStart rs m [.tick, .tick] (stageRegs pub rs) m :=
+ (Flow.Exec.line rfl).seq (Flow.Exec.line rfl)
+
+theorem execute_stage_step (pub : Fin 5 → Word w) (st : Word w) (m : Memory w)
+ (hn : pub 4 ≠ 0) (hc : st < total pub)
+ (hb : column pub st ≠ 0 → index pub st < pub 3 → m (src pub st).val < (2 : Word w))
+ (rs : Regs w 32) (priv : Word w → Word w) (choices : List Bool) {fuel : ℕ} (hf : stageFuel ≤ fuel) :
+ let mach := stageTable.instantiate w pub
+ execute mach.program fuel ⟨mach.entry, st, rs, priv⟩ m choices =
+ if choices.isEmpty then some (stageReport pub st m) else none := by
+ obtain ⟨out, hrun, hnext, ht⟩ := step_exec pub st m (stageRegs pub rs) hc hb
+ have hr : Flow.Exec pub st stageBody rs m (List.replicate 3 .tick ++ stepEvents pub st m) out
+ (stepMemory pub st m) := (stageStart_exec ..).seq (.ifEqNo hn hrun)
+ obtain ⟨hlen, hbits⟩ := stepEvents_bounds pub st m
+ have h := PrimedCounter.Call.execute_body stageBody 29 30 pub st rs priv m hr choices
+ (fuel - ((stepEvents pub st m).length+5))
+ simp only [List.length_append, List.length_replicate] at h
+ rw [show 3 + (stepEvents pub st m).length + (fuel - ((stepEvents pub st m).length+5) + 2) = fuel by
+ unfold stageFuel at hf; omega,
+ hnext, ht] at h
+ change execute _ _ _ _ (choiceBits (stepEvents pub st m) ++ choices) = _ at h
+ rw [hbits, List.nil_append] at h
+ simpa only [stageTable, stageReport, ite_eq_right hn, stepReport, List.append_assoc] using h
+
+theorem execute_stage_empty (pub : Fin 5 → Word w) (m : Memory w) (hz : pub 4 = 0)
+ (rs : Regs w 32) (priv : Word w → Word w) (choices : List Bool) {fuel : ℕ} (hf : stageFuel ≤ fuel) :
+ let mach := stageTable.instantiate w pub
+ execute mach.program fuel ⟨mach.entry, 0, rs, priv⟩ m choices =
+ if choices.isEmpty then some (stageReport pub 0 m) else none := by
+ let s := stageRegs pub rs
+ let s' := Function.update s 8 0
+ let out := Function.update (Function.update s' 29 1) 30 1
+ have hg : Flow.Exec pub (0 : Word w) (.line (.guardEq 8 0)) s' m [.tick] s' m := by
+ apply Flow.Exec.line
+ change (if (0 : Word w) = 0 then some _ else none) = _
+ rw [ite_eq_left rfl]
+ have he : Flow.Exec pub 0 emptyStage s m (List.replicate 4 .tick) out m :=
+ (Flow.Exec.line rfl).seq (hg.seq ((Flow.Exec.line rfl).seq (Flow.Exec.line rfl)))
+ have hr : Flow.Exec pub 0 stageBody rs m (List.replicate 7 .tick) out m :=
+ (stageStart_exec ..).seq (.ifEqYes hz he)
+ have h := PrimedCounter.Call.execute_body stageBody 29 30 pub 0 rs priv m hr choices (fuel-9)
+ change execute _ (7+(fuel-9+2)) _ _ choices = _ at h
+ rw [show 7+(fuel-9+2)=fuel by unfold stageFuel at hf; omega, ite_eq_left (show out 29 = out 30 from rfl)] at h
+ have hevents : List.replicate 7 (Event.tick (w := w)) ++ [.tick] = List.replicate 8 .tick :=
+ (List.replicate_add 7 1 _).symm
+ simpa only [stageTable, stageReport, ite_eq_left hz, hevents] using h
+
+theorem stageReport_memory (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) :
+ after m (stageReport pub st m).events = if pub 4 = 0 then m else stepMemory pub st m := by
+ by_cases h : pub 4 = 0
+ · rw [stageReport, ite_eq_left h, ite_eq_left h]; rfl
+ · rw [stageReport, ite_eq_right h, ite_eq_right h]
+ exact stepReport_memory ..
+
+theorem stageReport_probes_le (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) :
+ (stageReport pub st m).probes ≤ 3 := by
+ by_cases h : pub 4 = 0
+ · rw [stageReport, ite_eq_left h]; exact (by decide : 0 ≤ 3)
+ · rw [stageReport, ite_eq_right h]; exact stepReport_probes_le ..
+
+private theorem stage_required {pub : Fin 5 → Word w} {st : Word w} {m mem : Memory w}
+ {rs out : Regs w 32} {es : List (Event w)} (run : Flow.Exec pub st stageBody rs m es out mem) :
+ if pub 4 = 0 then st = 0 else
+ st < total pub ∧ (column pub st ≠ 0 → index pub st < pub 3 → m (src pub st).val < (2 : Word w)) := by
+ cases run with
+ | seq head tail =>
+ have hx := trace_of_straight head
+ have hy := trace_of_straight (stageStart_exec pub st rs m)
+ obtain ⟨-, rfl, rfl⟩ := (show _ ∧ _ ∧ _ by simpa using hx.symm.trans hy)
+ cases tail with
+ | ifEqNo hn hr =>
+ change pub 4 ≠ 0 at hn
+ rw [ite_eq_right hn]
+ exact step_required hr
+ | ifEqYes hz hr =>
+ change pub 4 = 0 at hz
+ rw [ite_eq_left hz]
+ cases hr with
+ | seq hs rest =>
+ cases hs with
+ | line he =>
+ simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at he
+ obtain ⟨-, rfl, rfl⟩ := he
+ cases rest with
+ | seq hg _ =>
+ cases hg with
+ | line he =>
+ by_contra hn
+ change (if st = 0 then some _ else none) = _ at he
+ rw [ite_eq_right hn] at he
+ cases he
+
+/-- The linkable stage also checks the empty bank's initial cursor, and
+rejects every surplus branch bit in both branches. -/
+theorem execute_stage_iff (pub : Fin 5 → Word w) (st : Word w) (m : Memory w)
+ (rs : Regs w 32) (priv : Word w → Word w) (choices : List Bool) {fuel : ℕ}
+ (hf : stageFuel ≤ fuel) (rep : Report w) :
+ let mach := stageTable.instantiate w pub
+ execute mach.program fuel ⟨mach.entry, st, rs, priv⟩ m choices = some rep ↔
+ (if pub 4 = 0 then st = 0 else st < total pub ∧
+ (column pub st ≠ 0 → index pub st < pub 3 → m (src pub st).val < (2 : Word w))) ∧
+ choices = [] ∧ rep = stageReport pub st m := by
+ have he (ha : if pub 4 = 0 then st = 0 else st < total pub ∧
+ (column pub st ≠ 0 → index pub st < pub 3 → m (src pub st).val < (2 : Word w))) :
+ let mach := stageTable.instantiate w pub
+ execute mach.program fuel ⟨mach.entry, st, rs, priv⟩ m choices =
+ if choices.isEmpty then some (stageReport pub st m) else none := by
+ by_cases hz : pub 4 = 0
+ · rw [ite_eq_left hz] at ha
+ subst st
+ exact execute_stage_empty pub m hz rs priv choices hf
+ · rw [ite_eq_right hz] at ha
+ exact execute_stage_step pub st m hz ha.1 ha.2 rs priv choices hf
+ constructor
+ · intro h
+ obtain ⟨_, _, _, run, -⟩ := (PrimedCounter.Call.execute_iff stageBody 29 30 pub st rs priv m choices fuel rep).mp h
+ have ha := stage_required run
+ rw [he ha] at h
+ cases choices with
+ | nil => exact ⟨ha, rfl, (Option.some.inj h).symm⟩
+ | cons => cases h
+ · rintro ⟨ha, hbits, rfl⟩
+ simpa [hbits] using he ha
+
+end LiveEvaluatorAdviceBanks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePackSweep.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePackSweep.lean
new file mode 100644
index 0000000000..c55691d899
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePackSweep.lean
@@ -0,0 +1,407 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceBanks
+import OAI.Computability.VPVNP.LiveEvaluatorAdvicePackStep
+import OAI.Computability.VPVNP.RAMSuccessor
+import Mathlib.SetTheory.Cardinal.Finite
+
+/-!
+# Native sweeps for packing the evaluator's bit banks
+
+Each output row begins with one reset call. Further calls install the row's
+occupied source bits and leave its padding zero. The resulting memory is
+specified at every address. Every nonempty sweep has a single accepting
+branch stream and incurs at most four calls-plus-probes per cursor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceBanks
+
+open BurstRAM
+open BurstRAM.PrivateRAM (BinaryOp)
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The cursor for an unfinished call, or the halted control after all rows. -/
+def packControl (w count i : ℕ) : Option (Word w) :=
+ if i = count then none else some (Fin.ofNat (2^w) i)
+
+/-- The reported memory, call count, clock and total probe cost of a native
+deterministic scan, with an exact characterization on arbitrary branch streams. -/
+theorem deterministic_scan {C : Type*} (P : Program w C) (fuel count bound : ℕ)
+ (inv : ℕ → Memory w → Prop)
+ (step : ∀ i < count, ∀ m, inv i m → ∃ es,
+ (∀ bs, execute P fuel (P.start (Fin.ofNat (2^w) i)) m bs =
+ if bs = [] then some ⟨es, packControl w count (i+1)⟩ else none) ∧
+ inv (i+1) (after m es) ∧ countProbes es ≤ bound)
+ (n i : ℕ) (hn : i+n = count) (m : Memory w) (hi : inv i m) :
+ ∃ reports, inv count (after m (eventLog reports)) ∧ reports.length = n ∧
+ RAMBuckets.cost Report.probes reports ≤ (1+bound)*n ∧
+ (∀ r ∈ reports, r.probes ≤ bound ∧ r.events.length < fuel) ∧
+ ∀ bits rs, (runSegment P fuel (packControl w count i) m bits = some rs ∧
+ endState (packControl w count i) rs = none) ↔ bits = List.replicate n [] ∧ rs = reports := by
+ induction n generalizing i m with
+ | zero =>
+ simp only [Nat.add_zero] at hn
+ subst i
+ refine ⟨[], hi, rfl, by simp [RAMBuckets.cost], by simp, ?_⟩
+ intro bits rs
+ cases bits <;> cases rs <;> simp [packControl, runSegment, endState]
+ | succ n ih =>
+ have hlt : i < count := by omega
+ obtain ⟨es, hrun, hnext, hprobes⟩ := step i hlt m hi
+ let r : Report w := ⟨es, packControl w count (i+1)⟩
+ have he : execute P fuel (P.start (Fin.ofNat (2^w) i)) m [] = some r := by simpa [r] using hrun []
+ have hclock := (execute_spec he).1.length_lt
+ obtain ⟨tail, hm, hl, hc, hcaps, hu⟩ := ih (i+1) (by omega) (after m es) hnext
+ refine ⟨r :: tail, ?_, by simp [hl], ?_, ?_, ?_⟩
+ · simpa only [eventLog, List.flatMap_cons, after, List.foldl_append, r] using hm
+ · change 1 + countProbes es + _ ≤ _
+ rw [Nat.mul_succ]
+ omega
+ · rw [List.forall_mem_cons]
+ exact ⟨⟨hprobes, hclock⟩, hcaps⟩
+ · intro bits rs
+ rw [packControl, ite_eq_right hlt.ne]
+ cases bits with
+ | nil => cases rs <;> simp [runSegment, endState, List.replicate_succ]
+ | cons bs more =>
+ by_cases hb : bs = []
+ · subst bs
+ rw [runSegment, he]
+ simp only [Option.map_eq_some_iff, List.replicate_succ, List.cons.injEq, true_and]
+ constructor
+ · rintro ⟨⟨rest, hr, rfl⟩, hhalt⟩
+ obtain ⟨hbits, rfl⟩ := (hu more rest).mp ⟨hr, hhalt⟩
+ exact ⟨hbits, rfl⟩
+ · rintro ⟨hbits, rfl⟩
+ obtain ⟨hr, hhalt⟩ := (hu more tail).mpr ⟨hbits, rfl⟩
+ exact ⟨⟨tail, hr, rfl⟩, hhalt⟩
+ · rw [runSegment, hrun bs, ite_eq_right hb]
+ simp [List.replicate_succ, hb]
+
+
+/-- Each row is overwritten when its reset call occurs. Subsequent calls in
+the same row expose one more little-endian bit, up to the fixed field width. -/
+def packMemory (pub : Fin 5 → Word w) (raw : List Bool) (original : Memory w) (i : ℕ) : Memory w :=
+ fun a =>
+ let base := (pub 1).val
+ let fw := (pub 2).val
+ let j := a-base
+ if base ≤ a ∧ j < (pub 4).val ∧ j*(fw+1) < i then
+ packedPrefix w fw raw j (min fw (i-(j*(fw+1)+1)))
+ else original a
+
+/-- Number of native calls, including the initial reset of every row. -/
+def packCalls (pub : Fin 5 → Word w) : ℕ := (pub 4).val*((pub 2).val+1)
+
+/-- The public geometry and the word bounds used for packing. Addresses are
+ordinary naturals until they are shown to fit in a native word. -/
+structure PackLayout (pub : Fin 5 → Word w) (raw : List Bool) : Prop where
+ width : 2 ≤ w
+ fieldWidth : (pub 2).val ≤ w
+ rawLength : (pub 3).val = raw.length
+ cursorFit : packCalls pub < 2^w
+ srcFit : (pub 0).val + raw.length ≤ 2^w
+ dstFit : (pub 1).val + (pub 4).val ≤ 2^w
+ disjoint : (pub 1).val + (pub 4).val ≤ (pub 0).val ∨ (pub 0).val + raw.length ≤ (pub 1).val
+
+/-- Source advice occupies one Boolean word at each actual bit address. -/
+def PackSource (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w) : Prop :=
+ ∀ k < raw.length, m ((pub 0).val+k) = PrimedInputRAM.encodeBit w (raw[k]?.getD false)
+
+theorem packMemory_zero (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w) :
+ packMemory pub raw m 0 = m := by
+ funext a
+ simp [packMemory]
+
+theorem packMemory_outside (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w) (i a : ℕ)
+ (ha : a < (pub 1).val ∨ (pub 1).val+(pub 4).val ≤ a) :
+ packMemory pub raw m i a = m a := by
+ have hn : ¬((pub 1).val ≤ a ∧ a-(pub 1).val < (pub 4).val ∧
+ (a-(pub 1).val)*((pub 2).val+1) < i) := by omega
+ exact ite_eq_right hn
+
+theorem packMemory_source (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w)
+ (L : PackLayout pub raw) (src : PackSource pub raw m) (i : ℕ) :
+ PackSource pub raw (packMemory pub raw m i) := by
+ intro k hk
+ rw [packMemory_outside]
+ · exact src k hk
+ · rcases L.disjoint with h | h <;> omega
+
+theorem packMemory_row (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w) (i j : ℕ)
+ (hj : j < (pub 4).val) :
+ packMemory pub raw m i ((pub 1).val+j) =
+ if j*((pub 2).val+1) < i then
+ packedPrefix w (pub 2).val raw j (min (pub 2).val (i-(j*((pub 2).val+1)+1)))
+ else m ((pub 1).val+j) := by
+ simp [packMemory, hj]
+
+/-- At the end all row words are fully written, even if padding calls have
+been needed after the end of the raw advice. -/
+theorem packMemory_full (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w) (j : ℕ)
+ (hj : j < (pub 4).val) :
+ packMemory pub raw m (packCalls pub) ((pub 1).val+j) =
+ packedPrefix w (pub 2).val raw j (pub 2).val := by
+ have h := Nat.mul_le_mul_right ((pub 2).val+1) hj
+ rw [Nat.succ_mul] at h
+ rw [packMemory_row, packCalls, ite_eq_left (by omega), min_eq_left (by omega)]
+ exact hj
+
+private theorem packMemory_succ_other (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w)
+ (i j c a : ℕ) (hij : i = j*((pub 2).val+1)+c) (hc : c ≤ (pub 2).val)
+ (ha : a ≠ (pub 1).val+j) :
+ packMemory pub raw m (i+1) a = packMemory pub raw m i a := by
+ by_cases hOut : a < (pub 1).val ∨ (pub 1).val+(pub 4).val ≤ a
+ · rw [packMemory_outside _ _ _ _ _ hOut, packMemory_outside _ _ _ _ _ hOut]
+ let r := a-(pub 1).val
+ have har : a = (pub 1).val+r := by dsimp [r]; omega
+ have hr : r < (pub 4).val := by dsimp [r]; omega
+ have hne : r ≠ j := by intro he; rw [he] at har; contradiction
+ rw [har, packMemory_row _ _ _ _ _ hr, packMemory_row _ _ _ _ _ hr]
+ rcases lt_or_gt_of_ne hne with h | h
+ · have hx := Nat.mul_le_mul_right ((pub 2).val+1) h
+ rw [Nat.succ_mul] at hx
+ rw [ite_eq_left (by omega), ite_eq_left (by omega), min_eq_left (by omega), min_eq_left (by omega)]
+ · have hx := Nat.mul_le_mul_right ((pub 2).val+1) h
+ rw [Nat.succ_mul] at hx
+ rw [ite_eq_right (by omega), ite_eq_right (by omega)]
+
+private theorem packMemory_current (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w)
+ (j c : ℕ) (hj : j < (pub 4).val) (hc : c ≤ (pub 2).val) :
+ packMemory pub raw m (j*((pub 2).val+1)+c+1) ((pub 1).val+j) =
+ packedPrefix w (pub 2).val raw j c := by
+ rw [packMemory_row _ _ _ _ _ hj, ite_eq_left (by omega), min_eq_right (by omega)]
+ congr 1
+ omega
+
+
+private theorem pack_stride {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw) :
+ (stride pub).val = (pub 2).val+1 := by
+ apply Fin.val_add_one_of_lt'
+ have h := L.fieldWidth
+ have h₁ := L.width
+ obtain ⟨u, hu⟩ := Nat.exists_eq_add_of_le h₁
+ have hp := Nat.lt_two_pow_self (n := u)
+ have hh : w+1 < 2^w := by rw [hu, pow_add]; omega
+ omega
+
+private theorem pack_total {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw) :
+ (total pub).val = packCalls pub := by
+ rw [total, Fin.val_mul, pack_stride L]
+ exact Nat.mod_eq_of_lt L.cursorFit
+
+private theorem packCoordinates {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (i : ℕ) (hi : i < packCalls pub) :
+ let st := Fin.ofNat (2^w) i
+ let j := (row pub st).val
+ let c := (column pub st).val
+ i = j*((pub 2).val+1)+c ∧ c ≤ (pub 2).val ∧ j < (pub 4).val ∧
+ (dst pub st).val = (pub 1).val+j := by
+ intro st j c
+ have hst : st.val = i := Nat.mod_eq_of_lt (hi.trans L.cursorFit)
+ have hj : j = i/((pub 2).val+1) := by
+ change (st.val / (stride pub).val) % 2^w = _
+ rw [Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt st.isLt), hst, pack_stride L]
+ have hc : c = i%((pub 2).val+1) := by
+ change (st.val % (stride pub).val) % 2^w = _
+ rw [Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt st.isLt), hst, pack_stride L]
+ have hjlt : j < (pub 4).val := by
+ rw [hj, Nat.div_lt_iff_lt_mul (by omega)]
+ exact hi
+ refine ⟨?_, ?_, hjlt, ?_⟩
+ · rw [hj, hc, Nat.div_add_mod']
+ · rw [hc]; exact Nat.le_of_lt_succ (Nat.mod_lt _ (Nat.succ_pos _))
+ · change ((pub 1).val+j) % 2^w = _
+ have := L.dstFit
+ exact Nat.mod_eq_of_lt (by omega)
+
+/-- On a nonreset column the live source offset is the ordinary row-major
+bit index. All arithmetic in the native registers stays within the modulus. -/
+private theorem pack_index {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (i : ℕ) (hi : i < packCalls pub) {k : ℕ}
+ (hk : (column pub (Fin.ofNat (2^w) i)).val = k+1) :
+ let st := Fin.ofNat (2^w) i
+ let j := (row pub st).val
+ (column pub st - 1) = Fin.ofNat (2^w) k ∧ (index pub st).val = j*(pub 2).val+k := by
+ intro st j
+ have ⟨he, _, _, _⟩ := packCoordinates L i hi
+ change i = j*((pub 2).val+1)+(column pub st).val at he
+ have hf := hi.trans L.cursorFit
+ have hu : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by have := L.width; omega))
+ have hle : (1 : Word w) ≤ column pub st := by rw [Fin.le_def, hu, hk]; omega
+ have hv : (column pub st - 1).val = k := by rw [Fin.sub_val_of_le hle, hu, hk]; omega
+ have hkj : k < 2^w := by have := (column pub st).isLt; rw [hk] at this; omega
+ have hsub : column pub st-1 = Fin.ofNat (2^w) k := Fin.ext (hv.trans (Nat.mod_eq_of_lt hkj).symm)
+ refine ⟨hsub, ?_⟩
+ rw [Nat.mul_add, Nat.mul_one, hk] at he
+ change ((j*(pub 2).val) % 2^w + (column pub st-1).val) % 2^w = _
+ rw [Nat.mod_eq_of_lt (by omega : j*(pub 2).val < 2^w), hv, Nat.mod_eq_of_lt (by omega)]
+
+private theorem pack_src {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (st : Word w) (h : index pub st < pub 3) :
+ (src pub st).val = (pub 0).val+(index pub st).val := by
+ change ((pub 0).val+(index pub st).val) % 2^w = _
+ change (index pub st).val < (pub 3).val at h
+ rw [L.rawLength] at h
+ have := L.srcFit
+ exact Nat.mod_eq_of_lt (by omega)
+
+/-- The natural row-prefix invariant advances exactly once for the native
+reset, active bit, or padding call. -/
+theorem packMemory_step {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (m : Memory w) (hs : PackSource pub raw m) (i : ℕ) (hi : i < packCalls pub) :
+ stepMemory pub (Fin.ofNat (2^w) i) (packMemory pub raw m i) = packMemory pub raw m (i+1) := by
+ let st := Fin.ofNat (2^w) i
+ let j := (row pub st).val
+ let c := (column pub st).val
+ obtain ⟨he, hc, hj, hd⟩ := packCoordinates L i hi
+ change i = j*((pub 2).val+1)+c at he
+ change c ≤ (pub 2).val at hc
+ change j < (pub 4).val at hj
+ change (dst pub st).val = (pub 1).val+j at hd
+ change stepMemory pub st _ = _
+ funext a
+ by_cases ha : a = (pub 1).val+j
+ · subst a
+ have hpost := packMemory_current pub raw m j c hj hc
+ rw [← he] at hpost
+ rw [hpost]
+ cases hx : c with
+ | zero =>
+ have hz : column pub st = 0 := Fin.ext hx
+ simp [stepMemory, hz, writeMemory, hd, packedPrefix_zero]
+ | succ k =>
+ have hz : column pub st ≠ 0 := by
+ intro h
+ have hh := congrArg Fin.val h
+ change c = 0 at hh
+ omega
+ have ⟨hsub, hidx⟩ := pack_index L i hi hx
+ have hk : k < (pub 2).val := by omega
+ have hprev := packMemory_current pub raw m j k hj (by omega)
+ rw [show j*((pub 2).val+1)+k+1 = i by omega] at hprev
+ rw [stepMemory, ite_eq_right hz]
+ by_cases hactive : index pub st < pub 3
+ · have hsrc := pack_src L st hactive
+ have hidx' : j*(pub 2).val+k < raw.length := by
+ change (index pub st).val < (pub 3).val at hactive
+ rwa [L.rawLength, hidx] at hactive
+ rw [ite_eq_left hactive, writeMemory, hd, ite_eq_left rfl]
+ unfold packedValue
+ rw [hd, hprev, hsrc, hidx, packMemory_source pub raw m L hs i _ hidx', hsub]
+ exact packedPrefix_succ w _ raw j k hk L.fieldWidth
+ · rw [ite_eq_right hactive, hprev, packedPrefix_skip]
+ change ¬(index pub st).val < (pub 3).val at hactive
+ rw [L.rawLength, hidx] at hactive
+ exact Nat.le_of_not_gt hactive
+ · rw [packMemory_succ_other pub raw m i j c a he hc ha]
+ have hne : a ≠ (dst pub st).val := hd ▸ ha
+ unfold stepMemory
+ split_ifs <;> simp [writeMemory, hne]
+
+
+/-- The valid natural cursor satisfies both native guards, and its footer
+publishes the next ordinary cursor unless the complete scan has ended. -/
+theorem packStep_guards {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (m : Memory w) (hs : PackSource pub raw m) (i : ℕ) (hi : i < packCalls pub) :
+ let st := Fin.ofNat (2^w) i
+ st < total pub ∧
+ (column pub st ≠ 0 → index pub st < pub 3 → m (src pub st).val < (2 : Word w)) ∧
+ (stepReport pub st m).result = packControl w (packCalls pub) (i+1) := by
+ intro st
+ have hst : st.val = i := Nat.mod_eq_of_lt (hi.trans L.cursorFit)
+ have htotal := pack_total L
+ have hsuc : (st+1).val = i+1 := by
+ rw [Fin.val_add_one_of_lt' (by rw [hst]; exact Nat.lt_of_le_of_lt hi L.cursorFit), hst]
+ refine ⟨by rw [Fin.lt_def, hst, htotal]; exact hi, ?_, ?_⟩
+ · intro _ hindex
+ have haddr := pack_src L st hindex
+ change (index pub st).val < (pub 3).val at hindex
+ rw [L.rawLength] at hindex
+ rw [haddr, hs _ hindex]
+ have hpow : 4 ≤ 2^w := Nat.pow_le_pow_right (by decide : 0 < 2) L.width
+ cases raw[(index pub st).val]?.getD false <;>
+ simp [PrimedInputRAM.encodeBit, Fin.lt_def, Nat.mod_eq_of_lt (by omega : 2 < 2^w),
+ Nat.mod_eq_of_lt (by omega : 1 < 2^w)]
+ · have he : st+1 = total pub ↔ i+1 = packCalls pub := by rw [Fin.ext_iff, hsuc, htotal]
+ have hword : st+1 = Fin.ofNat (2^w) (i+1) :=
+ Fin.ext (hsuc.trans (Nat.mod_eq_of_lt (Nat.lt_of_le_of_lt hi L.cursorFit)).symm)
+ change (if st+1 = total pub then none else some (st+1)) = _
+ rw [packControl, if_congr he rfl (congrArg some hword)]
+
+/-- All accepted runs of the actual packed-advice program, including streams
+of unintended lengths or surplus bits, with exact final memory. -/
+theorem packSweep {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (m : Memory w) (hs : PackSource pub raw m) (hpos : 0 < packCalls pub) {fuel : ℕ} (hf : callFuel ≤ fuel) :
+ let P := (stepTable.instantiate w pub).program
+ ∃ reports, after m (eventLog reports) = packMemory pub raw m (packCalls pub) ∧
+ reports.length = packCalls pub ∧ RAMBuckets.cost Report.probes reports ≤ 4*packCalls pub ∧
+ (∀ r ∈ reports, r.probes ≤ 3 ∧ r.events.length < fuel) ∧
+ ∀ bits rs, (runSegment P fuel (some 0) m bits = some rs ∧ endState (some 0) rs = none) ↔
+ bits = List.replicate (packCalls pub) [] ∧ rs = reports := by
+ intro P
+ let inv := fun i mem => mem = packMemory pub raw m i
+ have initial : inv 0 m := (packMemory_zero pub raw m).symm
+ have step (i : ℕ) (hi : i < packCalls pub) (mem : Memory w) (hm : inv i mem) :
+ ∃ es, (∀ bs, execute P fuel (P.start (Fin.ofNat (2^w) i)) mem bs =
+ if bs = [] then some ⟨es, packControl w (packCalls pub) (i+1)⟩ else none) ∧
+ inv (i+1) (after mem es) ∧ countProbes es ≤ 3 := by
+ let st := Fin.ofNat (2^w) i
+ let rep := stepReport pub st mem
+ have hsrc : PackSource pub raw mem := hm ▸ packMemory_source pub raw m L hs i
+ obtain ⟨hcur, hb, hstate⟩ := packStep_guards L mem hsrc i hi
+ refine ⟨rep.events, ?_, ?_, stepReport_probes_le pub st mem⟩
+ · intro bs
+ have hx := execute_step pub st mem hcur hb (fun _ => 0) (fun _ => 0) bs hf
+ have hr : rep = ⟨rep.events, packControl w (packCalls pub) (i+1)⟩ := by
+ change stepReport pub st mem = ⟨_, _⟩
+ rw [← hstate]
+ change execute P fuel (P.start st) mem bs = if bs = [] then some _ else none
+ rw [← hr]
+ change execute P fuel (P.start st) mem bs = if bs.isEmpty then some rep else none at hx
+ cases bs <;> exact hx
+ · change after mem (stepReport pub st mem).events = _
+ rw [stepReport_memory, hm]
+ exact packMemory_step L m hs i hi
+ have hc : packControl w (packCalls pub) 0 = some 0 := by simp [packControl, hpos.ne]
+ simpa only [hc] using deterministic_scan P fuel (packCalls pub) 3 inv step (packCalls pub) 0
+ (Nat.zero_add _) m initial
+
+/-- A zero-row interval takes zero calls. Its starting cursor and memory are
+available to the next phase. -/
+theorem packSweep_zero (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w) (fuel : ℕ)
+ (h : packCalls pub = 0) :
+ runSegment (stepTable.instantiate w pub).program fuel (some 0) m
+ (List.replicate (packCalls pub) []) = some [] ∧
+ endState (some (0 : Word w)) [] = some 0 ∧
+ after m (eventLog []) = packMemory pub raw m (packCalls pub) := by
+ rw [h, packMemory_zero]
+ exact ⟨rfl, rfl, rfl⟩
+
+/-- The nonempty advice sweep contributes exactly one native path under the
+paper's per-call and global transcript caps. -/
+theorem packPathCount {pub : Fin 5 → Word w} {raw : List Bool} (L : PackLayout pub raw)
+ (m : Memory w) (hs : PackSource pub raw m) (hpos : 0 < packCalls pub) {fuel : ℕ} (hf : callFuel ≤ fuel)
+ {S H : ℕ} (hcost : 4*packCalls pub ≤ S*H) (hcap : 4 ≤ H) :
+ Nat.card (ActualPaths (stepTable.instantiate w pub).program fuel 0 m (withinCaps S H)) = 1 := by
+ let paths := ActualPaths (stepTable.instantiate w pub).program fuel 0 m (withinCaps S H)
+ obtain ⟨reports, _, _, hc, hcalls, hall⟩ := packSweep L m hs hpos hf
+ have hwithin : withinCaps S H reports :=
+ ⟨hc.trans hcost, fun r hr => by have := (hcalls r hr).1; omega⟩
+ have uniq (b : paths) : b.val = List.replicate (packCalls pub) [] := by
+ obtain ⟨rs, hr, he, _⟩ := b.property
+ exact ((hall b.val rs).mp ⟨hr, he⟩).1
+ have ⟨hr, he⟩ := (hall (List.replicate (packCalls pub) []) reports).mpr ⟨rfl, rfl⟩
+ exact Nat.card_eq_one_iff_unique.mpr
+ ⟨⟨fun a b => Subtype.ext ((uniq a).trans (uniq b).symm)⟩,
+ ⟨⟨List.replicate (packCalls pub) [], reports, hr, he, hwithin⟩⟩⟩
+
+end LiveEvaluatorAdviceBanks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePrepared.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePrepared.lean
new file mode 100644
index 0000000000..a73dd7d6c9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdvicePrepared.lean
@@ -0,0 +1,297 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceDistribution
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceFrameReadback
+import OAI.Computability.VPVNP.LiveEvaluatorAdvicePackStage
+
+/-!
+# Preparing the evaluator's advice banks in physical memory
+
+First the native packer reads the raw length. The next call validates it and
+publishes four operand frames. The prefix packer takes its operands from the
+first published frame, and the ordinal packer fills the lookup table. The
+four stages run successively on the memory produced by their predecessors.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceBanks
+
+open BurstRAM CutSchedule ChainAssignments LiveEvaluatorAdviceFrames
+open scoped Fin.CommRing
+
+variable {w t ordW a d h Δ : ℕ}
+
+/-- The public operands and their allocated address intervals. The cursor
+bounds cover the reset column as well as every data column. -/
+structure PreparedLayout (lp : Fin 5 → Word w) (fp : FramePub w) (op : Fin 5 → Word w)
+ (raw : List Bool) (t ordW : ℕ) : Prop where
+ width : 4 ≤ w
+ frameWidth : (fp 2).val = w
+ rawFits : raw.length ≤ (fp 1).val
+ lengthSource : (lp 0).val = (fp 0).val
+ lengthDest : (lp 1).val = (fp 3).val+22
+ lengthWidth : (lp 2).val = w
+ lengthCount : (lp 3).val = w
+ lengthRows : (lp 4).val = 1
+ ordinalSource : (op 0).val = (fp 0).val+w+(fp 1).val
+ ordinalDest : op 1 = fp 10
+ ordinalWidth : (op 2).val = ordW
+ ordinalFits : ordW ≤ w
+ ordinalCount : (op 3).val = t*ordW
+ ordinalRows : (op 4).val = t
+ adviceBeforeFrame : (fp 0).val+w+(fp 1).val+t*ordW ≤ (fp 3).val
+ frameBeforePrefix : (fp 3).val+23 ≤ (fp 4).val
+ prefixBeforeOrder : (fp 4).val+(raw.length ⌈/⌉ w) ≤ (op 1).val
+ orderFit : (op 1).val+t ≤ 2^w
+ prefixCursorFit : (raw.length ⌈/⌉ w)*(w+1) < 2^w
+ orderCursorFit : t*(ordW+1) < 2^w
+
+/-- Memory after the initial length pack, whose only output is the length
+at frame offset 22. -/
+def lengthMemory (lp : Fin 5 → Word w) (raw : List Bool) (m : Memory w) : Memory w :=
+ packMemory lp (lengthBits w raw) m (packCalls lp)
+
+/-- Five dynamically published operands of the prefix stage. -/
+def rawOperands (lp : Fin 5 → Word w) (fp : FramePub w) (raw : List Bool) (m : Memory w) :=
+ prefixFrame fp (lengthMemory lp raw m)
+
+/-- Memory after frame publication and prefix packing. -/
+def rawMemory (lp : Fin 5 → Word w) (fp : FramePub w) (raw : List Bool) (m : Memory w) : Memory w :=
+ let rp := rawOperands lp fp raw m
+ packMemory rp raw (published fp (lengthMemory lp raw m)) (packCalls rp)
+
+/-- Final memory of the four native stages. -/
+def preparedAdviceMemory (lp : Fin 5 → Word w) (fp : FramePub w) (op : Fin 5 → Word w)
+ (raw : List Bool) (values : Fin t → Word ordW) (m : Memory w) : Memory w :=
+ packMemory op (ordinalBits values) (rawMemory lp fp raw m) (packCalls op)
+
+variable {lp op : Fin 5 → Word w} {fp : FramePub w} {raw : List Bool}
+
+private theorem frameFit (L : PreparedLayout lp fp op raw t ordW) : (fp 3).val+22 < 2^w :=
+ lt_of_lt_of_le (by have := L.frameBeforePrefix; omega) (fp 4).isLt.le
+
+/-- The frame program reads the newly packed length at its designated address. -/
+theorem prepared_length (L : PreparedLayout lp fp op raw t ordW) (m : Memory w) :
+ (actualLength fp (lengthMemory lp raw m)).val = raw.length := by
+ rw [actualLength_at fp _ (frameFit L), ← L.lengthDest]
+ exact packMemory_length lp raw m L.lengthWidth (by rw [L.lengthRows]; decide)
+ (L.rawFits.trans_lt (fp 1).isLt)
+
+private theorem rawSourceAddress (L : PreparedLayout lp fp op raw t ordW) (m : Memory w) :
+ ((rawOperands lp fp raw m) 0).val = (fp 0).val+w := by
+ change (fp 0+fp 2).val = _
+ rw [Fin.val_add, L.frameWidth, Nat.mod_eq_of_lt (by have := L.adviceBeforeFrame; have := (fp 3).isLt; omega)]
+
+theorem rawOperands_length (L : PreparedLayout lp fp op raw t ordW) (m : Memory w) :
+ ((rawOperands lp fp raw m) 3).val = raw.length := prepared_length L m
+
+theorem rawOperands_rows (L : PreparedLayout lp fp op raw t ordW) (m : Memory w) :
+ ((rawOperands lp fp raw m) 4).val = raw.length ⌈/⌉ w := by
+ change (prefixRows fp _).val = _
+ rw [prefixRows_val fp _ (by rw [L.frameWidth]; have := L.width; omega),
+ prepared_length L m, L.frameWidth]
+
+theorem lengthLayout (L : PreparedLayout lp fp op raw t ordW) : PackLayout lp (lengthBits w raw) := by
+ have hw := L.width
+ have hsf := L.adviceBeforeFrame
+ have hlf := L.frameBeforePrefix
+ have hpf := (fp 4).isLt
+ have hwfit : w+1 < 2^w := by
+ obtain ⟨n, hn⟩ := Nat.exists_eq_add_of_le hw
+ have := Nat.lt_two_pow_self (n := n)
+ rw [hn, pow_add]; omega
+ refine ⟨by omega, L.lengthWidth.le, by rw [L.lengthCount, length_lengthBits], ?_, ?_, ?_, ?_⟩
+ · simpa [packCalls, L.lengthWidth, L.lengthRows] using hwfit
+ · rw [L.lengthSource, length_lengthBits]; omega
+ · rw [L.lengthDest, L.lengthRows]; omega
+ · right; rw [L.lengthSource, L.lengthDest, length_lengthBits]; omega
+
+theorem rawLayout (L : PreparedLayout lp fp op raw t ordW) (m : Memory w) :
+ PackLayout (rawOperands lp fp raw m) raw := by
+ have hdest : rawOperands lp fp raw m 1 = fp 4 := rfl
+ have hwidth : (rawOperands lp fp raw m 2).val = w := L.frameWidth
+ have h₁ := L.adviceBeforeFrame
+ have h₂ := L.frameBeforePrefix
+ have h₃ := L.prefixBeforeOrder
+ have h₄ := L.rawFits
+ have h₅ := (op 1).isLt
+ refine ⟨by have := L.width; omega, hwidth.le, prepared_length L m, ?_, ?_, ?_, ?_⟩
+ · rw [packCalls, rawOperands_rows L m, hwidth]; exact L.prefixCursorFit
+ · rw [rawSourceAddress L m]; omega
+ · rw [hdest, rawOperands_rows L m]; omega
+ · right; rw [rawSourceAddress L m, hdest]; omega
+
+theorem orderLayout (L : PreparedLayout lp fp op raw t ordW) (values : Fin t → Word ordW) :
+ PackLayout op (ordinalBits values) := by
+ have h₁ := L.adviceBeforeFrame
+ have h₂ := L.frameBeforePrefix
+ have h₃ := L.prefixBeforeOrder
+ have h₄ := (op 1).isLt
+ refine ⟨by have := L.width; omega, L.ordinalWidth.trans_le L.ordinalFits,
+ by rw [L.ordinalCount, length_ordinalBits], ?_, ?_, ?_, ?_⟩
+ · rw [packCalls, L.ordinalRows, L.ordinalWidth]; exact L.orderCursorFit
+ · rw [L.ordinalSource, length_ordinalBits]; omega
+ · rw [L.ordinalRows]; exact L.orderFit
+ · right; rw [L.ordinalSource, length_ordinalBits]; omega
+
+private theorem before_frames (L : PreparedLayout lp fp op raw t ordW) (m : Memory w)
+ (k : ℕ) (hk : k < (fp 3).val) :
+ published fp (lengthMemory lp raw m) k = m k := by
+ rw [published_outside fp _ (by have := L.width; omega) (frameFit L).le k (.inl hk)]
+ apply packMemory_outside
+ left; rw [L.lengthDest]; omega
+
+private theorem final_before_prefix (L : PreparedLayout lp fp op raw t ordW)
+ (values : Fin t → Word ordW) (m : Memory w) (k : ℕ) (hk : k < (fp 4).val) :
+ preparedAdviceMemory lp fp op raw values m k = published fp (lengthMemory lp raw m) k := by
+ rw [preparedAdviceMemory, packMemory_outside op _ _ _ _ (.inl (by have := L.prefixBeforeOrder; omega))]
+ exact packMemory_outside _ _ _ _ _ (.inl hk)
+
+/-- Final readback of the four operand frames and the three packed banks.
+Outside the frame interval, packed prefix and ordinal table, memory agrees
+pointwise with its value before the length stage. -/
+structure PreparedImage (lp : Fin 5 → Word w) (fp : FramePub w) (op : Fin 5 → Word w)
+ (raw : List Bool) (values : Fin t → Word ordW) (m out : Memory w) : Prop where
+ frames : PublishedAt fp (lengthMemory lp raw m) out
+ lengthWord : (out ((fp 3).val+22)).val = raw.length
+ rawWord (j : ℕ) (hj : j < raw.length ⌈/⌉ w) :
+ out ((fp 4).val+j) = LiveEvaluatorInitialize.inputWord w raw j
+ ordinalWord (j : Fin t) : (out ((op 1).val+j.val)).val = (values j).val
+ outside (k : ℕ) (hf : k < (fp 3).val ∨ (fp 3).val+23 ≤ k)
+ (hr : k < (fp 4).val ∨ (fp 4).val+(raw.length ⌈/⌉ w) ≤ k)
+ (ho : k < (op 1).val ∨ (op 1).val+t ≤ k) : out k = m k
+
+theorem prepared_image (L : PreparedLayout lp fp op raw t ordW) (values : Fin t → Word ordW) (m : Memory w) :
+ PreparedImage lp fp op raw values m (preparedAdviceMemory lp fp op raw values m) := by
+ have hw : 0 < w := by have := L.width; omega
+ have hF := L.frameBeforePrefix
+ have hO := L.prefixBeforeOrder
+ have ht := published_at fp (lengthMemory lp raw m) hw (frameFit L).le
+ constructor
+ · constructor <;> intro j
+ · exact (final_before_prefix L _ m _ (by have := j.isLt; omega)).trans (ht.prefixWord j)
+ · exact (final_before_prefix L _ m _ (by have := j.isLt; omega)).trans (ht.copyWord j)
+ · exact (final_before_prefix L _ m _ (by have := j.isLt; omega)).trans (ht.skeletonWord j)
+ · exact (final_before_prefix L _ m _ (by have := j.isLt; omega)).trans (ht.scatterWord j)
+ · rw [final_before_prefix L _ m _ (by omega), published_outside _ _ hw (frameFit L).le _ (.inr le_rfl)]
+ simpa only [actualLength_at fp _ (frameFit L)] using prepared_length L m
+ · intro j hj
+ rw [preparedAdviceMemory, packMemory_outside op _ _ _ _ (.inl (by omega))]
+ exact packMemory_raw (rawOperands lp fp raw m) raw _ L.frameWidth j ((rawOperands_rows L m).symm ▸ hj)
+ · intro j
+ have ho := packMemory_ordinal op values (rawMemory lp fp raw m) L.ordinalWidth L.ordinalFits
+ L.ordinalRows.symm.le j
+ exact congrArg Fin.val ho
+ · intro k hf hr ho
+ have hro : (rawOperands lp fp raw m 1).val = (fp 4).val := rfl
+ rw [preparedAdviceMemory, packMemory_outside _ _ _ _ _ (L.ordinalRows ▸ ho), rawMemory,
+ packMemory_outside _ _ _ _ _ (by rw [hro, rawOperands_rows L m]; exact hr),
+ published_outside _ _ hw (frameFit L).le _ (by omega), lengthMemory, packMemory_outside]
+ rw [L.lengthDest, L.lengthRows]; omega
+
+/-- Exact deterministic call sequence, costs and post-memory of one native
+packing bank. -/
+structure PackHistory (pub : Fin 5 → Word w) (bits : List Bool) (m : Memory w)
+ (fuel : ℕ) (reports : List (Report w)) : Prop where
+ memory : after m (eventLog reports) = packMemory pub bits m (packCalls pub)
+ calls : reports.length = stageCalls pub
+ cost : RAMBuckets.cost Report.probes reports ≤ 4*stageCalls pub
+ caps : ∀ r ∈ reports, r.probes ≤ 3 ∧ r.events.length < fuel
+ path (bs : List (List Bool)) (rs : List (Report w)) :
+ (runSegment (stageTable.instantiate w pub).program fuel (some 0) m bs = some rs ∧
+ endState (some 0) rs = none) ↔ bs = List.replicate (stageCalls pub) [] ∧ rs = reports
+
+private theorem pack_history {pub : Fin 5 → Word w} {bits : List Bool} {fuel : ℕ}
+ (L : PackLayout pub bits) (m : Memory w) (hs : PackSource pub bits m) (hf : stageFuel ≤ fuel) :
+ ∃ rs, PackHistory pub bits m fuel rs := by
+ obtain ⟨rs, hm, hlen, hc, hr, hp⟩ := packStageSweep L m hs hf
+ exact ⟨rs, hm, hlen, hc, hr, hp⟩
+
+/-- Source readback in the successive input memories of the three native
+packing stages, using only the copied header bits. -/
+theorem preparedSources {advice : Bits a} {m : Memory w} {values : Fin t → Word ordW} {padding : ℕ}
+ (L : PreparedLayout lp fp op raw t ordW)
+ (copied : ∀ i : Fin a, m ((fp 0).val+i.val) = PrimedInputRAM.encodeBit w (advice i))
+ (htape : List.ofFn advice = distribution w (fp 1).val raw values padding) :
+ PackSource lp (lengthBits w raw) m ∧
+ PackSource (rawOperands lp fp raw m) raw (published fp (lengthMemory lp raw m)) ∧
+ PackSource op (ordinalBits values) (rawMemory lp fp raw m) := by
+ let rp := rawOperands lp fp raw m
+ let m₂ := published fp (lengthMemory lp raw m)
+ let m₃ := rawMemory lp fp raw m
+ have hbefore := L.adviceBeforeFrame
+ have hfp := L.frameBeforePrefix
+ have hraw := L.rawFits
+ obtain ⟨hs₁, hs₂, hs₃⟩ := distribution_sources_of_copied copied lp rp op htape L.rawFits L.lengthSource
+ (rawSourceAddress L m) L.ordinalSource
+ have hsrc₂ : PackSource rp raw m₂ := by
+ intro j hj
+ rw [show m₂ _ = _ from before_frames L m ((rp 0).val+j) (by rw [rawSourceAddress L m]; omega), hs₂ j hj]
+ have hsrc₃ : PackSource op (ordinalBits values) m₂ := by
+ intro j hj
+ rw [length_ordinalBits] at hj
+ rw [show m₂ _ = _ from before_frames L m ((op 0).val+j) (by rw [L.ordinalSource]; omega),
+ hs₃ j (by rwa [length_ordinalBits])]
+ have hsrc₄ : PackSource op (ordinalBits values) m₃ := hsrc₃.after_other_bank rp raw (packCalls rp)
+ (.inl (by rw [L.ordinalSource, length_ordinalBits]; change _ ≤ (fp 4).val; omega))
+ exact ⟨hs₁, hsrc₂, hsrc₄⟩
+
+/-- Source images, native reports and final data for the consecutive length,
+frame, prefix and ordinal stages. The prefix machine sees its public words
+through the just-published operand loader. -/
+theorem prepareAdvice {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ} {g : Fin (2^(h+1))}
+ {original m : Memory w} {values : Fin t → Word ordW} {padding fuel : ℕ}
+ (L : PreparedLayout lp fp op raw t ordW)
+ (image : LiveHeader.AdviceImage (d := d) hw advice cuts g (fp 0).val original m)
+ (htape : List.ofFn advice = distribution w (fp 1).val raw values padding) (hf : 83 ≤ fuel) :
+ let m₁ := lengthMemory lp raw m
+ let m₂ := published fp m₁
+ let rp := rawOperands lp fp raw m
+ let m₃ := rawMemory lp fp raw m
+ ∃ lrs rrs ors, PackHistory lp (lengthBits w raw) m fuel lrs ∧
+ (∀ bs rep, execute (LiveEvaluatorAdviceFrames.template.instantiate w fp).program fuel
+ ((LiveEvaluatorAdviceFrames.template.instantiate w fp).program.start 0) m₁ bs = some rep ↔
+ bs = [] ∧ rep = ⟨events fp m₁, none⟩) ∧ after m₁ (events fp m₁) = m₂ ∧
+ CompressorRecords.Frame.data (fp 3) m₂ = rp ∧ PackHistory rp raw m₂ fuel rrs ∧
+ PackHistory op (ordinalBits values) m₃ fuel ors ∧
+ PreparedImage lp fp op raw values m (preparedAdviceMemory lp fp op raw values m) := by
+ intro m₁ m₂ rp m₃
+ have hw' : 0 < w := by omega
+ have hcap : actualLength fp m₁ ≤ fp 1 := (prepared_length L m).le.trans L.rawFits
+ have hwidth : 0 < fp 2 := (L.frameWidth.symm ▸ hw' : 0 < (fp 2).val)
+ have hclock : stageFuel ≤ fuel := by unfold stageFuel; omega
+ obtain ⟨hs₁, hs₂, hs₃⟩ := preparedSources L image.copied htape
+ obtain ⟨lrs, hlen⟩ := pack_history (lengthLayout L) m hs₁ hclock
+ obtain ⟨rrs, hprefix⟩ := pack_history (rawLayout L m) m₂ hs₂ hclock
+ obtain ⟨ors, horder⟩ := pack_history (orderLayout L values) m₃ hs₃ hclock
+ refine ⟨lrs, rrs, ors, hlen, ?_, (execute_frames fp 0 m₁ hcap hwidth).2,
+ (frameData fp m₁ hw' (frameFit L).le).1, hprefix, horder, prepared_image L values m⟩
+ intro bs rep
+ simpa only [hcap, hwidth, true_and] using execute_frames_iff fp 0 m₁ bs fuel hf rep
+
+/-- All four dynamic operand loaders still read their complete frames after
+both data banks have been packed. -/
+theorem PreparedImage.frameData {values : Fin t → Word ordW} {m out : Memory w}
+ (image : PreparedImage lp fp op raw values m out) (hf : (fp 3).val + 22 ≤ 2^w) :
+ CompressorRecords.Frame.data (fp 3) out = prefixFrame fp (lengthMemory lp raw m) ∧
+ CompressorRecords.Frame.data (fp 3+8) out = copyFrame fp (lengthMemory lp raw m) ∧
+ CompressorRecords.Frame.data (fp 3+13) out = skeletonFrame fp (lengthMemory lp raw m) ∧
+ CompressorRecords.Frame.data (fp 3+17) out = scatterFrame fp (lengthMemory lp raw m) := by
+ have data {n : ℕ} (offset : ℕ) (h : offset + n ≤ 22) (j : Fin n) :
+ CompressorRecords.Frame.data (fp 3 + (offset : Word w)) out j = out ((fp 3).val + offset + j.val) := by
+ have hv : (fp 3 + (offset : Word w)).val = (fp 3).val+offset := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt (by have := j.isLt; omega)]
+ rw [CompressorRecords.Frame.data_at _ _ (by rw [hv]; omega), hv]
+ obtain ⟨hp, hc, hs, ho⟩ := image.frames
+ refine ⟨funext (fun j => ?_), funext (fun j => ?_), funext (fun j => ?_), funext (fun j => ?_)⟩
+ · exact (CompressorRecords.Frame.data_at _ _ (by omega) j).trans (hp j)
+ · exact (data 8 (by decide) j).trans (hc j)
+ · exact (data 13 (by decide) j).trans (hs j)
+ · exact (data 17 (by decide) j).trans (ho j)
+
+end LiveEvaluatorAdviceBanks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceResources.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceResources.lean
new file mode 100644
index 0000000000..62b47e36f3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceResources.lean
@@ -0,0 +1,220 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAdvicePackStage
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceFrameReadback
+import OAI.Computability.VPVNP.LiveEvaluatorTailCost
+
+/-!
+# Cost of the four linked advice preparation stages
+
+The packed length occupies one row. The actual advice prefix occupies the
+rounded-up number of rows and reads a five-word operand frame per call. The
+ordinal table uses one row per ordinal. A single initializer publishes the
+frames. These bounds charge the native probe logs and the live linker's
+dispatch and transfer at each call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorAdviceResources
+
+open BurstRAM
+open LiveEvaluatorAdviceBanks
+open LiveEvaluatorTailCost (linked frameReads)
+open LiveProgram (Stage)
+open scoped Nat
+
+variable {w : ℕ}
+
+/-- The number of calls budgeted to pack the evaluator prefix, including the terminating call
+for zero rows. -/
+def prefixCalls (A w : ℕ) := max 1 ((A ⌈/⌉ w)*(w+1))
+/-- The number of calls budgeted to pack the ordinal rows at the specified bit width, including
+the empty-table case. -/
+def orderCalls (t ordW : ℕ) := max 1 (t*(ordW+1))
+
+/-- The combined probe charge for packing the length, prefix, and ordinal rows and publishing
+the four midpoint frames. -/
+def setupCost (w A t ordW : ℕ) := 6*(w+1) + 11*prefixCalls A w + 6*orderCalls t ordW + 23
+
+/-- Ceiling rounding and one reset per row add at most a word of padding
+and one extra bit call per occupied bit. -/
+theorem prefixCalls_le (A w : ℕ) (hw : 0 < w) : prefixCalls A w ≤ 1 + 2*(A+w) := by
+ rw [prefixCalls, Nat.ceilDiv_eq_add_pred_div, Nat.mul_add, Nat.mul_one]
+ have hm := Nat.div_mul_le_self (A+w-1) w
+ have hd := Nat.div_le_self (A+w-1) w
+ omega
+
+theorem orderCalls_le (t ordW w : ℕ) (hw : ordW ≤ w) : orderCalls t ordW ≤ 1+t*(w+1) := by
+ have h := Nat.mul_le_mul_left t (Nat.add_le_add_right hw 1)
+ unfold orderCalls
+ omega
+
+theorem setupCost_le (w A t ordW : ℕ) (hw : 0 < w) (ho : ordW ≤ w) :
+ setupCost w A t ordW ≤ 6*(w+1) + 11*(1+2*(A+w)) + 6*(1+t*(w+1)) + 23 := by
+ unfold setupCost
+ have := prefixCalls_le A w hw
+ have := orderCalls_le t ordW w ho
+ omega
+
+private theorem stageClock (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) :
+ (stageReport pub st m).events.length ≤ 32 := by
+ by_cases hz : pub 4 = 0
+ · simp [stageReport, hz]
+ · simp only [stageReport, ite_eq_right hz, List.length_append, List.length_replicate]
+ have := stepReport_length_le pub st m
+ omega
+
+/-- The worker clock bound holds even when the caller supplies more fuel.
+Successful partial or complete executions consume one report per choice list. -/
+theorem pack_run_bounds (pub : Fin 5 → Word w) {fuel : ℕ} (hf : stageFuel ≤ fuel)
+ (st : Option (Word w)) (m : Memory w) (bits : List (List Bool)) (rs : List (Report w))
+ (hr : runSegment (stageTable.instantiate w pub).program fuel st m bits = some rs) :
+ rs.length = bits.length ∧ ∀ r ∈ rs, r.probes ≤ 3 ∧ r.events.length ≤ 32 := by
+ induction bits generalizing st m rs with
+ | nil =>
+ simp [runSegment] at hr
+ subst rs
+ simp
+ | cons b bs ih =>
+ cases st with
+ | none => contradiction
+ | some st =>
+ rw [runSegment] at hr
+ let P := (stageTable.instantiate w pub).program
+ cases he : execute P fuel (P.start st) m b with
+ | none => simp [P, he] at hr
+ | some r =>
+ rw [show execute (stageTable.instantiate w pub).program fuel
+ ((stageTable.instantiate w pub).program.start st) m b = some r from he,
+ Option.map_eq_some_iff] at hr
+ obtain ⟨rest, hrest, rfl⟩ := hr
+ obtain ⟨_, _, rfl⟩ := (execute_stage_iff pub st m (fun _ => 0) (fun _ => 0) b hf r).mp he
+ obtain ⟨hl, hc⟩ := ih _ _ rest hrest
+ rw [List.length_cons, List.length_cons, hl, List.forall_mem_cons]
+ exact ⟨rfl, ⟨stageReport_probes_le .., stageClock ..⟩, hc⟩
+
+/-- Reports in the same order as the midpoint branch of the native live
+program. Each entry contains the memory from which its operand frame is read. -/
+def setupReports (p : UniversalMachine.Program) (tag frame : Word w)
+ (lengths : List (Memory w × Report w)) (framePub : LiveEvaluatorAdviceFrames.FramePub w)
+ (frameMem : Memory w) (prefixReports ordinals : List (Memory w × Report w)) : List (Report w) :=
+ lengths.map (linked p tag frame Stage.prefixLength) ++
+ [linked p tag frame Stage.adviceFrames (frameMem, ⟨LiveEvaluatorAdviceFrames.events framePub frameMem, none⟩)] ++
+ prefixReports.map (linked p tag frame Stage.prefixPack) ++ ordinals.map (linked p tag frame Stage.orderPack)
+
+private theorem link_bounds (p : UniversalMachine.Program) (tag frame : Word w) (s : Stage)
+ (x : Memory w × Report w) :
+ (linked p tag frame s x).probes ≤ x.2.probes + frameReads s + 2 ∧
+ (linked p tag frame s x).events.length ≤ x.2.events.length + 4*frameReads s + 47 := by
+ have ⟨hlen,hpr,_⟩ := CompressorRecords.Frame.frame_cost frame x.1 0 (frameReads s) x.2
+ unfold linked
+ constructor
+ · rw [LiveStageLink.linkedReport_probes, hpr]
+ split <;> omega
+ · have h := LiveStageLink.linkedReport_length_le (LiveProgram.next p) tag s
+ (LiveStageLink.prependLog (CompressorRecords.Frame.loadEvents frame x.1 0 (frameReads s)) x.2)
+ rw [hlen] at h
+ omega
+
+private theorem reportsCost {reports : List (Report w)} (b : ℕ) (hb : ∀ r ∈ reports, r.probes ≤ b) :
+ RAMBuckets.cost Report.probes reports ≤ (1+b)*reports.length := by
+ induction reports with
+ | nil => simp [RAMBuckets.cost]
+ | cons r rs ih =>
+ rw [List.forall_mem_cons] at hb
+ rw [RAMBuckets.cost, List.length_cons, Nat.mul_succ]
+ have := ih hb.2
+ omega
+
+private theorem linked_pack_bounds (p : UniversalMachine.Program) (tag frame : Word w) (s : Stage)
+ (calls : List (Memory w × Report w)) (pub : Fin 5 → Word w) (m : Memory w) (n fuel : ℕ)
+ (hf : stageFuel ≤ fuel) (run : runSegment (stageTable.instantiate w pub).program fuel
+ (some 0) m (List.replicate n []) = some (calls.map Prod.snd)) :
+ let outs := calls.map (linked p tag frame s)
+ outs.length = n ∧ RAMBuckets.cost Report.probes outs ≤ (6+frameReads s)*n ∧
+ ∀ r ∈ outs, r.probes ≤ 5+frameReads s ∧ r.events.length ≤ 79+4*frameReads s := by
+ intro outs
+ have ⟨hl,hc⟩ := pack_run_bounds pub hf _ m _ _ run
+ simp only [List.length_map, List.length_replicate] at hl
+ have hout : outs.length = n := by simpa [outs] using hl
+ have hx : ∀ r ∈ outs, r.probes ≤ 5+frameReads s ∧ r.events.length ≤ 79+4*frameReads s := by
+ intro r hr
+ obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hr
+ have ⟨hp, ht⟩ := hc x.2 (List.mem_map.mpr ⟨x, hx, rfl⟩)
+ have ⟨hpl, htl⟩ := link_bounds p tag frame s x
+ omega
+ refine ⟨hout, ?_, hx⟩
+ have hb := reportsCost (5+frameReads s) (fun r hr => (hx r hr).1)
+ simpa only [hout, ← Nat.add_assoc] using hb
+
+private theorem summary (ls ps os : List (Report w)) (init : Report w) (l a o : ℕ)
+ (ll : ls.length = l) (pl : ps.length = a) (ol : os.length = o)
+ (lc : RAMBuckets.cost Report.probes ls ≤ 6*l)
+ (pc : RAMBuckets.cost Report.probes ps ≤ 11*a)
+ (oc : RAMBuckets.cost Report.probes os ≤ 6*o)
+ (lp : ∀ r ∈ ls, r.probes ≤ 5 ∧ r.events.length ≤ 79)
+ (pp : ∀ r ∈ ps, r.probes ≤ 10 ∧ r.events.length ≤ 99)
+ (op : ∀ r ∈ os, r.probes ≤ 5 ∧ r.events.length ≤ 79)
+ (ip : init.probes ≤ 22) (it : init.events.length ≤ 129) :
+ let reports := ls ++ [init] ++ ps ++ os
+ reports.length = l+a+o+1 ∧ RAMBuckets.cost Report.probes reports ≤ 6*l+11*a+6*o+23 ∧
+ ∀ r ∈ reports, 1+r.probes ≤ 23 ∧ r.events.length+1 ≤ 130 := by
+ simp only [List.length_append, List.length_singleton, ll, pl, ol, RAMBuckets.cost_append]
+ constructor
+ · omega
+ constructor
+ · have hi : RAMBuckets.cost Report.probes [init] ≤ 23 := by
+ change 1+init.probes+0 ≤ 23
+ omega
+ omega
+ · intro r hr
+ simp only [List.mem_append, List.mem_singleton] at hr
+ rcases hr with ((hl | h) | hp) | ho
+ · obtain ⟨h₁, h₂⟩ := lp r hl; omega
+ · subst r; omega
+ · obtain ⟨h₁, h₂⟩ := pp r hp; omega
+ · obtain ⟨h₁, h₂⟩ := op r ho; omega
+
+private theorem init_bound (p : UniversalMachine.Program) (tag frame : Word w) (m : Memory w)
+ (r : Report w) (hp : r.probes = 20) (ht : r.events.length = 82) :
+ (linked p tag frame Stage.adviceFrames (m,r)).probes ≤ 22 ∧
+ (linked p tag frame Stage.adviceFrames (m,r)).events.length ≤ 129 := by
+ simpa only [show frameReads Stage.adviceFrames = 0 from rfl, hp, ht] using
+ link_bounds p tag frame Stage.adviceFrames (m,r)
+
+/-- The full four-stage bounds from the native packing runs, the initializer's
+actual report, the five cached prefix operands and all dispatch/transfer
+events. In the 21-stage live program the largest dispatch clock is 130. -/
+theorem linkedSetupResources (p : UniversalMachine.Program) (tag frame : Word w)
+ (framePub : LiveEvaluatorAdviceFrames.FramePub w) (frameMem : Memory w)
+ (lPub aPub oPub : Fin 5 → Word w) (lm am om : Memory w)
+ (lengths prefixReports ordinals : List (Memory w × Report w)) (A t ordW : ℕ)
+ {lFuel aFuel oFuel : ℕ} (hl : stageFuel ≤ lFuel) (ha : stageFuel ≤ aFuel) (ho : stageFuel ≤ oFuel)
+ (lr : runSegment (stageTable.instantiate w lPub).program lFuel (some 0) lm
+ (List.replicate (w+1) []) = some (lengths.map Prod.snd))
+ (ar : runSegment (stageTable.instantiate w aPub).program aFuel (some 0) am
+ (List.replicate (prefixCalls A w) []) = some (prefixReports.map Prod.snd))
+ (orr : runSegment (stageTable.instantiate w oPub).program oFuel (some 0) om
+ (List.replicate (orderCalls t ordW) []) = some (ordinals.map Prod.snd)) :
+ let reports := setupReports p tag frame lengths framePub frameMem prefixReports ordinals
+ reports.length = w+1 + prefixCalls A w + orderCalls t ordW + 1 ∧
+ RAMBuckets.cost Report.probes reports ≤ setupCost w A t ordW ∧
+ ∀ r ∈ reports, 1+r.probes ≤ 23 ∧ r.events.length+1 ≤ 130 := by
+ obtain ⟨ll,lc,le⟩ := linked_pack_bounds p tag frame Stage.prefixLength lengths lPub lm (w+1) lFuel hl lr
+ obtain ⟨al,ac,ae⟩ := linked_pack_bounds p tag frame Stage.prefixPack prefixReports aPub am (prefixCalls A w) aFuel ha ar
+ obtain ⟨ol,oc,oe⟩ := linked_pack_bounds p tag frame Stage.orderPack ordinals oPub om (orderCalls t ordW) oFuel ho orr
+ let init : Report w := ⟨LiveEvaluatorAdviceFrames.events framePub frameMem, none⟩
+ let linkedInit := linked p tag frame Stage.adviceFrames (frameMem, init)
+ have ⟨_,hp,ht⟩ := LiveEvaluatorAdviceFrames.events_cost framePub frameMem
+ change init.probes = 20 at hp
+ change init.events.length = 82 at ht
+ have ⟨ip,it⟩ := init_bound p tag frame frameMem init hp ht
+ exact summary (lengths.map _) (prefixReports.map _) (ordinals.map _) linkedInit (w+1) (prefixCalls A w) (orderCalls t ordW)
+ ll al ol lc ac oc le ae oe ip it
+
+end LiveEvaluatorAdviceResources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceTag.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceTag.lean
new file mode 100644
index 0000000000..821a49a250
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorAdviceTag.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAdvicePrepared
+
+/-!
+# The stage tag and the evaluator's advice banks
+
+The linked program keeps its stage tag below the advice sources, destination
+arrays and operand frames. Updating the tag therefore commutes with every
+packed row write and with publication of the four operand frames.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.Advice
+
+open BurstRAM LiveEvaluatorAdviceFrames LiveEvaluatorAdviceBanks PrimedStackRAM
+
+variable {w : ℕ}
+
+theorem write_tag_twice (m : Memory w) (tag v v' : Word w) :
+ writeMemory (writeMemory m tag v) tag v' = writeMemory m tag v' := by
+ funext k
+ by_cases he : k = tag.val <;> simp [writeMemory, he]
+
+/-- A packer's source array agrees before and after a lower tag write. -/
+theorem packSource_write_tag (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w) (tag v : Word w)
+ (ht : tag.val < (pub 0).val) :
+ PackSource pub raw (writeMemory m tag v) ↔ PackSource pub raw m := by
+ have h (i : ℕ) : (pub 0).val + i ≠ tag.val := by omega
+ simp only [PackSource, writeMemory, h, ite_false]
+
+/-- Any prefix of a packing sweep commutes with a write below its destination bank. -/
+theorem packMemory_write_tag (pub : Fin 5 → Word w) (raw : List Bool) (m : Memory w)
+ (tag v : Word w) (i : ℕ) (ht : tag.val < (pub 1).val) :
+ packMemory pub raw (writeMemory m tag v) i = writeMemory (packMemory pub raw m i) tag v := by
+ funext k
+ by_cases he : k = tag.val
+ · subst k
+ rw [packMemory_outside _ _ _ _ _ (.inl ht)]
+ simp [writeMemory]
+ · simp [packMemory, writeMemory, he]
+
+theorem actualLength_write_tag (fp : FramePub w) (m : Memory w) (tag v : Word w)
+ (ht : tag.val < (fp 3).val) (hf : (fp 3).val+22 < 2^w) :
+ actualLength fp (writeMemory m tag v) = actualLength fp m := by
+ rw [actualLength_at fp _ hf, actualLength_at fp _ hf, writeMemory, ite_eq_right (by omega)]
+
+theorem prefixFrame_write_tag (fp : FramePub w) (m : Memory w) (tag v : Word w)
+ (ht : tag.val < (fp 3).val) (hf : (fp 3).val+22 < 2^w) :
+ prefixFrame fp (writeMemory m tag v) = prefixFrame fp m := by
+ simp only [prefixFrame, prefixRows, actualLength_write_tag fp m tag v ht hf]
+
+/-- The frame builder reads the same validated length and writes the same
+operand words, leaving the independent stage tag at the supplied value. -/
+theorem published_write_tag (fp : FramePub w) (m : Memory w) (tag v : Word w)
+ (ht : tag.val < (fp 3).val) (hw : 0 < w) (hf : (fp 3).val+22 < 2^w) :
+ published fp (writeMemory m tag v) = writeMemory (published fp m) tag v := by
+ funext k
+ by_cases hk : k < (fp 3).val ∨ (fp 3).val + 22 ≤ k
+ · rw [published_outside _ _ hw hf.le _ hk]
+ by_cases he : k = tag.val
+ · simp [writeMemory, he]
+ · simp [writeMemory, he, published_outside _ _ hw hf.le _ hk]
+ · let r := ready fp (fun _ => 0) m
+ have he : ready fp (fun _ => 0) (writeMemory m tag v) = r :=
+ ready_congr_length fp _ _ _ (actualLength_write_tag fp m tag v ht hf)
+ have h1 : (r 1).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')
+ have hfit : (r 22).val + slots.length ≤ 2^w := hf.le
+ let j := k - (fp 3).val
+ have hj : j < slots.length := by change k - (fp 3).val < 22; omega
+ have hkj : k = (r 22).val+j := by change k = (fp 3).val+(k-(fp 3).val); omega
+ have hne : k ≠ tag.val := by omega
+ rw [published, he, writeMemory, ite_eq_right hne, published, hkj]
+ rw [frameMemory_at slots r _ h1 hfit (by decide) j hj, frameMemory_at slots r m h1 hfit (by decide) j hj,
+ ← hkj, writeMemory, ite_eq_right hne]
+
+end LiveProgram.Advice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorCellEquivalence.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorCellEquivalence.lean
new file mode 100644
index 0000000000..6e5b6c2b8e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorCellEquivalence.lean
@@ -0,0 +1,139 @@
+import OAI.Computability.VPVNP.LiveEvaluatorStep
+
+/-!
+# Equivalence of the scheduled cell comparisons with a tape transition
+
+The private RAM visits old cells in increasing order. A one-cell move
+permutes the output positions cyclically and pairs the old discarded
+endpoint with the new blank endpoint. The extra blank check on that old
+endpoint makes this exactly the unbounded-tape move.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorStep
+
+open UniversalMachine LiveEvaluatorEncoding RAMTape
+
+variable {M : ℕ}
+
+/-- The destination paired with old cell `i` in the RAM scan. -/
+def cellDestination (move : Symbol) (i : WindowCell M) : WindowCell M :=
+ if move = 0 then i
+ else if move = 1 then
+ if h : i.val = 2 * M then ⟨0, by omega⟩ else ⟨i.val + 1, by have := i.isLt; omega⟩
+ else if i.val = 0 then ⟨2 * M, by omega⟩ else ⟨i.val - 1, by omega⟩
+
+/-- Whether a nonstationary tape move clips this old cell at the boundary of the finite window. -/
+def cellClipped (move : Symbol) (i : WindowCell M) : Prop :=
+ move ≠ 0 ∧ (if move = 1 then i.val = 2 * M else i.val = 0)
+
+instance (move : Symbol) (i : WindowCell M) : Decidable (cellClipped move i) :=
+ inferInstanceAs (Decidable (_ ∧ _))
+
+/-- The symbol after writing at the head position, using the previous symbol at every other
+cell. -/
+def writtenSymbol (t : TapeWindow M) (write : Symbol) (i : WindowCell M) : Symbol :=
+ if i.val = M then write else t.cells i
+
+theorem cellDestination_surjective (move : Symbol) : Function.Surjective (cellDestination (M := M) move) := by
+ intro j
+ fin_cases move
+ · exact ⟨j, rfl⟩
+ · by_cases h : j.val = 0
+ · exact ⟨⟨2 * M, by omega⟩, by apply Fin.ext; simp [cellDestination, h]⟩
+ · exact ⟨⟨j.val - 1, by omega⟩, by
+ apply Fin.ext
+ simp [cellDestination, show j.val - 1 ≠ 2 * M by omega]
+ omega⟩
+ · by_cases h : j.val = 2 * M
+ · exact ⟨⟨0, by omega⟩, by apply Fin.ext; simp [cellDestination, h]⟩
+ · exact ⟨⟨j.val + 1, by omega⟩, by apply Fin.ext; simp [cellDestination]⟩
+
+private theorem updatedCell_at_index (t : TapeWindow M) (write move : Symbol) (j : ℤ)
+ (i : WindowCell M) (h : j + moveDelta move = (i.val : ℤ) - M) :
+ updatedCell t write move j = writtenSymbol t write i := by
+ simp only [updatedCell, h, TapeWindow.read_index, writtenSymbol]
+ by_cases hi : i.val = M <;> simp [hi, show ((i.val : ℤ) - M = 0) ↔ i.val = M by omega]
+
+private theorem updatedCell_far (t : TapeWindow M) (write move : Symbol) (j : ℤ)
+ (h : j + moveDelta move < -(M : ℤ) ∨ (M : ℤ) < j + moveDelta move) :
+ updatedCell t write move j = 0 := by
+ rw [updatedCell, ite_eq_right (by omega), TapeWindow.read, dite_eq_right (by omega)]
+
+private theorem shifted_eq_source (t : TapeWindow M) (write move : Symbol) (i : WindowCell M) :
+ (updatedWindow t write move).cells (cellDestination move i) =
+ if cellClipped move i then 0 else writtenSymbol t write i := by
+ change updatedCell t write move ((↑(cellDestination move i).val : ℤ) - M) = _
+ fin_cases move <;> simp [cellClipped, cellDestination]
+ · apply updatedCell_at_index; simp
+ · split
+ next h => apply updatedCell_far; simp
+ next h => apply updatedCell_at_index; simp; omega
+ · split
+ next h => apply updatedCell_far; simp; omega
+ next h =>
+ apply updatedCell_at_index
+ have hi : 0 < i.val := by simpa [Nat.pos_iff_ne_zero] using h
+ simp [Int.ofNat_sub (show 1 ≤ i.val from hi)]; omega
+
+theorem boundaryBlank_iff_clipped (t : TapeWindow M) (write move : Symbol) :
+ boundaryBlank t write move = true ↔
+ ∀ i : WindowCell M, cellClipped move i → writtenSymbol t write i = 0 := by
+ let lo : WindowCell M := ⟨0, by omega⟩
+ let hi : WindowCell M := ⟨2 * M, by omega⟩
+ fin_cases move
+ · change boundaryBlank t write 0 = true ↔ ∀ i, cellClipped 0 i → writtenSymbol t write i = 0
+ have h₁ := updatedCell_far t write 0 (-(M : ℤ) - 1) (by simp)
+ have h₂ := updatedCell_far t write 0 ((M : ℤ) + 1) (by simp)
+ simp [boundaryBlank, h₁, h₂, cellClipped]
+ · change boundaryBlank t write 1 = true ↔ ∀ i, cellClipped 1 i → writtenSymbol t write i = 0
+ have h₁ := updatedCell_far t write 1 (-(M : ℤ) - 1) (by simp; omega)
+ have h₂ := updatedCell_at_index t write 1 ((M : ℤ) + 1) hi (by simp [hi]; omega)
+ simp only [boundaryBlank, decide_eq_true_eq, h₁, true_and, h₂]
+ constructor
+ · intro h i hc
+ have he : i = hi := Fin.ext (by simpa [cellClipped, hi] using hc)
+ exact he ▸ h
+ · exact fun h => h hi (by simp [cellClipped, hi])
+ · change boundaryBlank t write 2 = true ↔ ∀ i, cellClipped 2 i → writtenSymbol t write i = 0
+ have h₁ := updatedCell_at_index t write 2 (-(M : ℤ) - 1) lo (by simp [lo])
+ have h₂ := updatedCell_far t write 2 ((M : ℤ) + 1) (by simp; omega)
+ simp only [boundaryBlank, decide_eq_true_eq, h₁, h₂, and_true]
+ constructor
+ · intro h i hc
+ have he : i = lo := Fin.ext (by simpa [cellClipped, lo] using hc)
+ exact he ▸ h
+ · exact fun h => h lo (by simp [cellClipped, lo])
+
+/-- The RAM comparison at every old cell is equivalent to both the exterior
+blank guard and the complete equality of the proposed output tape. -/
+theorem cellChecks_iff (old out : TapeWindow M) (write move : Symbol) :
+ (∀ i : WindowCell M,
+ (cellClipped move i → writtenSymbol old write i = 0) ∧
+ out.cells (cellDestination move i) = writtenSymbol old write i) ↔
+ boundaryBlank old write move = true ∧ out = updatedWindow old write move := by
+ rw [boundaryBlank_iff_clipped]
+ constructor
+ · intro h
+ refine ⟨fun i => (h i).1, TapeWindow.ext ?_⟩
+ funext j
+ obtain ⟨i, rfl⟩ := cellDestination_surjective move j
+ rw [(h i).2, shifted_eq_source]
+ split
+ · exact (h i).1 ‹_›
+ · rfl
+ · rintro ⟨h, rfl⟩ i
+ refine ⟨h i, ?_⟩
+ rw [shifted_eq_source]
+ split
+ · exact (h i ‹_›).symm
+ · rfl
+
+end LiveEvaluatorStep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorCells.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorCells.lean
new file mode 100644
index 0000000000..682112fa61
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorCells.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAction
+import OAI.Computability.VPVNP.LiveEvaluatorRAMScheduleData
+
+/-!
+# Semantics of all noninitial calls of one live evaluator group
+
+The persistent cursor visits the old cells in each of the two tapes.
+The comparison instruction has no nondeterministic choices. On memory
+containing the published action, the complete scan verifies the two
+tape conditions of that action, including the blank fields of a halt.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorGroup
+
+open BurstRAM (Word Memory)
+open UniversalMachine (Program Instruction Symbol)
+open PrimedInputRAM (Flow)
+open LiveEvaluatorEncoding (Code TapeWindow)
+open LiveEvaluatorRAM (ConfigAt ActionAt TapeCellData)
+open LiveEvaluatorRAM.Schedule
+open LiveEvaluatorAction (tapeCheck checks first second pick)
+open scoped Fin.CommRing
+
+variable {M w : ℕ}
+
+/-- Every noninitial call starts with fresh private registers and checks its
+unique cell at the public one-based cursor. -/
+def AllCells (M : ℕ) (p : Program) (pub : Pub → Word w) (m : Memory w) : Prop :=
+ ∀ (side : Bool) (i : Fin (2 * M + 1)), ∃ es regs mem,
+ Flow.Exec pub (cellCursor side i : Word w) (body (LiveEvaluatorRAMPrepare.prepare p))
+ (fun _ => 0) m es regs mem
+
+private theorem halt_eq {e : ℕ} (z : Code e M) (hz : z.stateWord.val = 1) : z = .accepted := by
+ cases z with
+ | accepted => rfl
+ | rejected => contradiction
+ | running c hc =>
+ change c.state.val = 1 at hz
+ omega
+
+private theorem source_ne_accept (p : Program) (s : Code p.extra M) (bit : Bool) (a : Instruction p.extra)
+ (h : pick p s bit = some a) (ha : a.target.val ≠ 1) : s.stateWord.val ≠ 1 := by
+ intro hs
+ have he := halt_eq s hs
+ subst s
+ cases bit
+ · change some (LiveEvaluatorAction.carry p.extra) = some a at h
+ exact ha (congrArg (fun r => r.target.val) (Option.some.inj h).symm)
+ · contradiction
+
+private theorem cellCursor_ne_zero (side : Bool) (i : Fin (2 * M + 1)) (hc : calls M < 2 ^ w) :
+ (cellCursor side i : Word w) ≠ 0 := by
+ have hlt := (cellCursor_lt_calls side i).trans hc
+ intro hz
+ have he := congrArg Fin.val hz
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt hlt, Fin.val_zero] at he
+ simp [cellCursor] at he
+
+private theorem tapeVisits_iff (p : Program) (pub : Pub → Word w) (m : Memory w)
+ (old out : Code p.extra M) (a : Instruction p.extra) (side : Bool)
+ (hw : 2 ≤ w) (hM : (pub 0).val = M) (hc : calls M < 2 ^ w)
+ (ho : ConfigAt m (pub 1) old) (hn : ConfigAt m (pub 2) out)
+ (hs : ActionAt m (pub 3) a.target.val a.firstSymbol a.firstMove a.secondSymbol a.secondMove)
+ (he : a.target = out.stateWord) (hsrc : a.target.val ≠ 1 → old.stateWord.val ≠ 1) :
+ (∀ i : Fin (2 * M + 1), ∃ es regs mem,
+ Flow.Exec pub (cellCursor side i : Word w) (body (LiveEvaluatorRAMPrepare.prepare p))
+ (fun _ => 0) m es regs mem) ↔
+ tapeCheck (decide (a.target.val = 1)) (window old side) (window out side)
+ (if side then a.secondSymbol else a.firstSymbol) (if side then a.secondMove else a.firstMove) := by
+ have hact : ActionAt m (pub 3) out.stateWord.val a.firstSymbol a.firstMove a.secondSymbol a.secondMove :=
+ he ▸ hs
+ have data := fun i => scheduled_tape_data pub (fun _ => 0) m old out a.firstSymbol a.firstMove
+ a.secondSymbol a.secondMove side i hw hM hc ho hn hact
+ simp_rw [noninitial_call_iff p pub (cellCursor_ne_zero side _ hc)]
+ change (∀ i, LiveEvaluatorRAM.cellTest (bank pub (fun _ => 0) m side i) m) ↔ _
+ by_cases ha : a.target.val = 1
+ · have hout : out = .accepted := halt_eq _ (he ▸ ha)
+ subst out
+ have hblank (i : Fin (2 * M + 1)) : (window (Code.accepted (extra := p.extra)) side).cells i = 0 := by cases side <;> rfl
+ simp only [tapeCheck, ha, decide_true, ite_true, hblank, forall_const, iff_true]
+ intro i
+ let r := bank pub (fun _ => 0) m side i
+ obtain ⟨hr, h₅, h₁₆⟩ := data i
+ have h₅' : r 5 = r 1 := Fin.ext (h₅.trans hr.one.symm)
+ have hnew := hr.outCell _ i hr.index
+ rw [LiveEvaluatorRAM.cellTest, ite_eq_left h₅']
+ constructor
+ · split
+ next hh =>
+ have h₁ : old.stateWord.val = 1 := h₁₆.symm.trans ((congrArg Fin.val hh).trans hr.one)
+ have ho' := halt_eq _ h₁
+ apply Fin.ext
+ rw [hr.oldCell, hr.zero, ho']
+ cases side <;> rfl
+ next =>
+ change (m _).val < (r 3).val
+ rw [hr.oldCell, hr.three]
+ exact ((window old side).cells i).isLt
+ · apply Fin.ext
+ rw [hnew, hr.zero]
+ cases side <;> rfl
+ · simp only [tapeCheck, decide_eq_false ha, Bool.false_eq_true, ite_false]
+ rw [← LiveEvaluatorStep.cellChecks_iff]
+ apply forall_congr'
+ intro i
+ obtain ⟨hr, h₅, h₁₆⟩ := data i
+ apply LiveEvaluatorRAM.cellTest_running_iff hr
+ · exact fun heq => hsrc ha (h₁₆.symm.trans ((congrArg Fin.val heq).trans hr.one))
+ · exact fun heq => ha ((congrArg Fin.val he).trans (h₅.symm.trans ((congrArg Fin.val heq).trans hr.one)))
+
+/-- For a selected nonrejecting instruction with matching target, the two
+sweeps perform exactly the checks on that instruction in the semantic code. -/
+theorem allCells_iff (p : Program) (pub : Pub → Word w) (m : Memory w)
+ (old out : Code p.extra M) (a : Instruction p.extra) (bit : Bool)
+ (hw : 2 ≤ w) (hM : (pub 0).val = M) (hc : calls M < 2 ^ w)
+ (ho : ConfigAt m (pub 1) old) (hn : ConfigAt m (pub 2) out)
+ (hs : ActionAt m (pub 3) a.target.val a.firstSymbol a.firstMove a.secondSymbol a.secondMove)
+ (hslot : pick p old bit = some a) (hpos : 0 < a.target.val) (he : a.target = out.stateWord) :
+ AllCells M p pub m ↔ checks old out a := by
+ unfold AllCells
+ rw [Bool.forall_bool, tapeVisits_iff p pub m old out a false hw hM hc ho hn hs he (source_ne_accept p old bit a hslot),
+ tapeVisits_iff p pub m old out a true hw hM hc ho hn hs he (source_ne_accept p old bit a hslot)]
+ simp only [checks, hpos, he.symm, true_and, window, first, second, Bool.false_eq_true, ite_false, ite_true]
+
+end LiveEvaluatorGroup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorEncoding.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorEncoding.lean
new file mode 100644
index 0000000000..8ac8389244
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorEncoding.lean
@@ -0,0 +1,311 @@
+import OAI.Computability.VPVNP.EvaluatorTail
+
+/-!
+# Finite configurations on a live evaluator cut
+
+The two-way tapes in `UniversalMachine.Config` use head-relative coordinates.
+The field for each tape on a cut records its cells at offsets `-M,…,M`, with
+the head at position `M`. Cells outside the field are blank. A running state
+carries both fields. Acceptance and rejection each have a single representation,
+independent of the tape contents at the halt.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorEncoding
+
+open UniversalMachine
+
+/-- A finite field of cells, with its head at index `M`. -/
+@[ext] structure TapeWindow (M : ℕ) where
+ /-- The symbols at offsets from minus the radius through plus the radius, with the head in
+ the central cell. -/
+ cells : Fin (2 * M + 1) → Symbol
+ deriving DecidableEq
+
+/-- Every cell outside the indicated head-relative interval is blank. -/
+def TapeFits (M : ℕ) (t : Turing.Tape Symbol) : Prop :=
+ ∀ j : ℤ, j < -(M : ℤ) ∨ (M : ℤ) < j → t.nth j = 0
+
+variable {M extra : ℕ}
+
+/-- Read a head-relative window of the specified radius from a two-way tape. -/
+def TapeWindow.ofTape (M : ℕ) (t : Turing.Tape Symbol) : TapeWindow M where
+ cells i := t.nth ((i.val : ℤ) - M)
+
+/-- Extend the array on both sides by blanks. Each half tape begins
+at the cell nearest the head. -/
+def TapeWindow.toTape (t : TapeWindow M) : Turing.Tape Symbol where
+ head := t.cells ⟨M, by omega⟩
+ left := Turing.ListBlank.mk (List.ofFn fun i : Fin M => t.cells ⟨M - (i + 1), by omega⟩)
+ right := Turing.ListBlank.mk (List.ofFn fun i : Fin M => t.cells ⟨M + (i + 1), by omega⟩)
+
+/-- The window indexed by the signed displacement from its head. -/
+def TapeWindow.read (t : TapeWindow M) (j : ℤ) : Symbol :=
+ if h : -(M : ℤ) ≤ j ∧ j ≤ (M : ℤ) then t.cells ⟨(j + M).toNat, by omega⟩ else 0
+
+private theorem half_nth (f : Fin M → Symbol) (n : ℕ) :
+ (Turing.ListBlank.mk (List.ofFn f)).nth n = if h : n < M then f ⟨n, h⟩ else 0 := by
+ rw [Turing.ListBlank.nth_mk]
+ by_cases h : n < M
+ · rw [dite_eq_left h, List.getI_eq_getElem _ (by simpa using h), List.getElem_ofFn]
+ · rw [dite_eq_right h, List.getI_eq_default _ (by simpa using Nat.le_of_not_gt h)]
+ rfl
+
+theorem TapeWindow.toTape_nth (t : TapeWindow M) (j : ℤ) :
+ t.toTape.nth j = t.read j := by
+ cases j with
+ | ofNat n =>
+ cases n with
+ | zero =>
+ change t.cells _ = t.read 0
+ unfold read
+ rw [dite_eq_left (by omega)]
+ congr 2; omega
+ | succ n =>
+ change (Turing.ListBlank.mk (List.ofFn _)).nth n = t.read ((n : ℤ) + 1)
+ rw [half_nth]
+ unfold read
+ split_ifs <;> first | rfl | omega | (apply congrArg t.cells; apply Fin.ext; dsimp; omega)
+ | negSucc n =>
+ change (Turing.ListBlank.mk (List.ofFn _)).nth n = t.read (-((n : ℤ) + 1))
+ rw [half_nth]
+ unfold read
+ split_ifs <;> first | rfl | omega | (apply congrArg t.cells; apply Fin.ext; dsimp; omega)
+
+@[simp] theorem TapeWindow.read_index (t : TapeWindow M) (i : Fin (2 * M + 1)) :
+ t.read ((i.val : ℤ) - M) = t.cells i := by
+ unfold read
+ rw [dite_eq_left (by omega)]
+ congr 2; omega
+
+theorem TapeWindow.toTape_fits (t : TapeWindow M) : TapeFits M t.toTape := by
+ intro j hj
+ rw [toTape_nth, read, dite_eq_right (by omega)]
+
+@[simp] theorem TapeWindow.ofTape_toTape (t : TapeWindow M) :
+ ofTape M t.toTape = t := by
+ apply TapeWindow.ext
+ funext i
+ exact (t.toTape_nth _).trans (t.read_index i)
+
+/-- Extensionality in signed head-relative coordinates. -/
+theorem tape_ext {s t : Turing.Tape Symbol} (h : ∀ j : ℤ, s.nth j = t.nth j) : s = t := by
+ have hh : s.head = t.head := h 0
+ have hl : s.left = t.left := Turing.ListBlank.ext fun n => h (.negSucc n)
+ have hr : s.right = t.right := Turing.ListBlank.ext fun n => h (.ofNat (n + 1))
+ cases s
+ cases t
+ congr
+
+@[simp] theorem TapeWindow.toTape_ofTape (t : Turing.Tape Symbol) (h : TapeFits M t) :
+ (ofTape M t).toTape = t := by
+ apply tape_ext
+ intro j
+ rw [toTape_nth, read]
+ split
+ · rename_i hj
+ change t.nth (((j + M).toNat : ℤ) - M) = _
+ congr 1; omega
+ · exact (h j (by omega)).symm
+
+/-- The bounded data of one running evaluator. -/
+@[ext] structure ConfigWindow (extra M : ℕ) where
+ /-- The finite control state stored alongside the two tape windows. -/
+ state : Fin (extra + 2)
+ /-- The first tape's symbols in the finite window around its head. -/
+ firstTape : TapeWindow M
+ /-- The second tape's symbols in the finite window around its head. -/
+ secondTape : TapeWindow M
+ deriving DecidableEq
+
+/-- Recover a machine configuration by extending both stored windows with blank symbols outside
+their bounds. -/
+def ConfigWindow.toConfig (c : ConfigWindow extra M) : Config extra :=
+ ⟨c.state, c.firstTape.toTape, c.secondTape.toTape⟩
+
+/-- Record the control state and the two radius-bounded tape windows of a machine
+configuration. -/
+def ConfigWindow.ofConfig (M : ℕ) (c : Config extra) : ConfigWindow extra M :=
+ ⟨c.state, TapeWindow.ofTape M c.firstTape, TapeWindow.ofTape M c.secondTape⟩
+
+/-- Both tapes of the configuration are blank outside the specified radius of their heads. -/
+def ConfigFits (M : ℕ) (c : Config extra) : Prop :=
+ TapeFits M c.firstTape ∧ TapeFits M c.secondTape
+
+@[simp] theorem ConfigWindow.ofConfig_toConfig (c : ConfigWindow extra M) :
+ ofConfig M c.toConfig = c := by
+ cases c
+ simp [ofConfig, toConfig]
+
+@[simp] theorem ConfigWindow.toConfig_ofConfig (c : Config extra) (h : ConfigFits M c) :
+ (ofConfig M c).toConfig = c := by
+ cases c
+ simp [ofConfig, toConfig, h.1, h.2]
+
+theorem ConfigWindow.toConfig_fits (c : ConfigWindow extra M) : ConfigFits M c.toConfig :=
+ ⟨c.firstTape.toTape_fits, c.secondTape.toTape_fits⟩
+
+/-- A live cut has a unique code for either kind of halt. -/
+inductive Code (extra M : ℕ) where
+ | accepted
+ | rejected
+ | running (c : ConfigWindow extra M) (hr : 2 ≤ c.state.val)
+ deriving DecidableEq
+
+/-- Interpret a finite cut code as an evaluator state, preserving its halt status or
+reconstructing its running configuration. -/
+def Code.toState : Code extra M → EvaluatorTail.State extra
+ | .accepted => .accepted
+ | .rejected => .rejected
+ | .running c _ => .running c.toConfig
+
+/-- Canonical bounded states use the two halting constructors exclusively
+and retain the complete finite-support tapes in every running state. -/
+def StateFits (M : ℕ) : EvaluatorTail.State extra → Prop
+ | .accepted | .rejected => True
+ | .running c => 2 ≤ c.state.val ∧ ConfigFits M c
+
+/-- Encode a fitting evaluator state on a cut, using canonical halt codes and bounded windows
+for a running state. -/
+def Code.ofState (s : EvaluatorTail.State extra) (h : StateFits M s) : Code extra M :=
+ match s with
+ | .accepted => .accepted
+ | .rejected => .rejected
+ | .running c => .running (ConfigWindow.ofConfig M c) h.1
+
+theorem Code.toState_fits (s : Code extra M) : StateFits M s.toState := by
+ cases s with
+ | accepted | rejected => trivial
+ | running c hr => exact ⟨hr, c.toConfig_fits⟩
+
+/-- Forgetting the serialization data identifies precisely the canonical
+bounded states, including early halts and a zero-radius window. -/
+def codeEquiv (extra M : ℕ) : Code extra M ≃ {s : EvaluatorTail.State extra // StateFits M s} where
+ toFun s := ⟨s.toState, s.toState_fits⟩
+ invFun s := Code.ofState s.val s.property
+ left_inv s := by cases s <;> simp [Code.ofState, Code.toState]
+ right_inv s := by
+ rcases s with ⟨s, h⟩
+ apply Subtype.ext
+ cases s with
+ | accepted | rejected => rfl
+ | running c => simp [Code.ofState, Code.toState, h.2]
+
+/-- One state word and two consecutive fixed-width tape fields. -/
+def fieldWords (M : ℕ) : ℕ := 1 + (2 * M + 1) + (2 * M + 1)
+
+/-- The control-state field at word zero of the serialized configuration. -/
+def stateField (M : ℕ) : Fin (fieldWords M) := ⟨0, by unfold fieldWords; omega⟩
+
+/-- The serialized word position of a first-tape cell, immediately following the control state. -/
+def firstField (i : Fin (2 * M + 1)) : Fin (fieldWords M) :=
+ ⟨1 + i, by unfold fieldWords; omega⟩
+
+/-- The serialized word position of a second-tape cell, following the control state and all
+first-tape cells. -/
+def secondField (i : Fin (2 * M + 1)) : Fin (fieldWords M) :=
+ ⟨1 + (2 * M + 1) + i, by unfold fieldWords; omega⟩
+
+/-- The control field is the machine's own state number. -/
+def Code.stateWord (c : Code extra M) : Fin (extra + 2) :=
+ match c with
+ | .rejected => ⟨0, by omega⟩
+ | .accepted => ⟨1, by omega⟩
+ | .running r _ => r.state
+
+/-- Read a first-tape symbol from a cut code, using blank for either canonical halt. -/
+def Code.firstCell (c : Code extra M) (i : Fin (2 * M + 1)) : Symbol :=
+ match c with
+ | .running r _ => r.firstTape.cells i
+ | .accepted | .rejected => 0
+
+/-- Read a second-tape symbol from a cut code, using blank for either canonical halt. -/
+def Code.secondCell (c : Code extra M) (i : Fin (2 * M + 1)) : Symbol :=
+ match c with
+ | .running r _ => r.secondTape.cells i
+ | .accepted | .rejected => 0
+
+variable {w : ℕ}
+
+private theorem symbolFits (hw : 2 ≤ w) : 3 ≤ 2 ^ w :=
+ (by decide : 3 ≤ 2 ^ 2).trans (Nat.pow_le_pow_right (by decide : 0 < 2) hw)
+
+/-- Store the state, then the first tape and the second tape in increasing
+cell order. The halt codes zero every tape field. -/
+def words (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w) (c : Code extra M)
+ (k : Fin (fieldWords M)) : BurstRAM.Word w :=
+ if hz : k.val = 0 then (c.stateWord).castLE hs
+ else if hf : k.val < 1 + (2 * M + 1) then
+ (c.firstCell ⟨k.val - 1, by omega⟩).castLE (symbolFits hw)
+ else (c.secondCell ⟨k.val - (1 + (2 * M + 1)), by
+ have hk := k.isLt
+ unfold fieldWords at hk
+ omega⟩).castLE (symbolFits hw)
+
+@[simp] theorem words_state (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w) (c : Code extra M) :
+ (words hw hs c (stateField M)).val = c.stateWord.val := by
+ simp [words, stateField]
+
+@[simp] theorem words_first (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w) (c : Code extra M)
+ (i : Fin (2 * M + 1)) : (words hw hs c (firstField i)).val = (c.firstCell i).val := by
+ simp [words, firstField, show i.val ≤ 2 * M by omega]
+
+@[simp] theorem words_second (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w) (c : Code extra M)
+ (i : Fin (2 * M + 1)) : (words hw hs c (secondField i)).val = (c.secondCell i).val := by
+ simp [words, secondField]
+
+private def parseCell (x : BurstRAM.Word w) : Symbol := ⟨x.val % 3, Nat.mod_lt _ (by decide)⟩
+
+private def parseWords (a : Fin (fieldWords M) → BurstRAM.Word w) : Code extra M :=
+ let state := (a (stateField M)).val
+ if state = 1 then .accepted else
+ if h : 2 ≤ state ∧ state < extra + 2 then
+ .running ⟨⟨state, h.2⟩, ⟨fun i => parseCell (a (firstField i))⟩,
+ ⟨fun i => parseCell (a (secondField i))⟩⟩ h.1
+ else .rejected
+
+/-- The checked binary decoder requires canonical symbols and zeroes at every
+unused position. There are exactly `fieldWords M * w` bits on the field. -/
+def format (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w) :
+ RAMSerialization.Format w (fieldWords M) (Code extra M) where
+ words := words hw hs
+ parse := parseWords
+ parse_words c := by
+ cases c with
+ | accepted | rejected => simp [parseWords, Code.stateWord]
+ | running c hr =>
+ have hne : c.state.val ≠ 1 := by omega
+ have hlt := c.state.isLt
+ simp only [parseWords, words_state, Code.stateWord, hne, ↓reduceIte, hr, hlt, and_self,
+ ↓reduceDIte]
+ congr 1
+ apply ConfigWindow.ext
+ · rfl
+ · apply TapeWindow.ext
+ funext i
+ apply Fin.ext
+ simp [parseCell, Code.firstCell, Nat.mod_eq_of_lt (c.firstTape.cells i).isLt]
+ · apply TapeWindow.ext
+ funext i
+ apply Fin.ext
+ simp [parseCell, Code.secondCell, Nat.mod_eq_of_lt (c.secondTape.cells i).isLt]
+
+theorem decode_iff (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w) (c : Code extra M)
+ (b : CutSchedule.Bits (fieldWords M * w)) :
+ (format hw hs).decode b = some c ↔ b = (format hw hs).encode c :=
+ RAMSerialization.Format.decode_iff ..
+
+/-- Bounded evaluator configurations, including the two canonical halts,
+are in bijection with all valid bit strings of the allocated width. -/
+def stateBitsEquiv (M : ℕ) (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w) :
+ {s : EvaluatorTail.State extra // StateFits M s} ≃ {b // ((format (M := M) hw hs).decode b).isSome} :=
+ (codeEquiv extra M).symm.trans (format hw hs).canonicalEquiv
+
+end LiveEvaluatorEncoding
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorGatheredGroup.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorGatheredGroup.lean
new file mode 100644
index 0000000000..ce52ba89db
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorGatheredGroup.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMMalformed
+import OAI.Computability.VPVNP.LiveConfigGatherImage
+
+/-!
+# Tail-group path count after gathering both cut fields
+
+Gathering the outgoing field preserves the disjoint incoming configuration
+bank. On these two memory images the literal native group accepts precisely
+the semantic branch choices, for arbitrary field bits including malformed
+encodings.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorGroup
+
+open BurstRAM (Word Memory ActualPaths withinCaps)
+open LiveEvaluatorEncoding (Code format fieldWords)
+open LiveEvaluatorRAM (ConfigAt PrepLayout)
+open LiveEvaluatorRAM.Schedule (Pub nativeProgram callFuel calls capPathEquiv)
+open LiveConfigGather (gathered gathered_outside gathered_configAt_iff)
+open UniversalMachine (Program)
+open scoped Fin.CommRing Classical
+
+variable {w M k extra : ℕ}
+
+theorem configAt_gathered_disjoint_iff {base dst : Word w} (m : Memory w)
+ (hbase : base.val + calls M ≤ 2 ^ w) (hdst : dst.val + k ≤ 2 ^ w)
+ (hdis : base.val + calls M ≤ dst.val ∨ dst.val + k ≤ base.val)
+ (bits : Fin (k*w) → Bool) (c : Code extra M) :
+ ConfigAt (gathered dst hdst bits m) base c ↔ ConfigAt m base c := by
+ have he (i : ℕ) (hi : i < calls M) :
+ gathered dst hdst bits m (base + (i : Word w)).val = m (base + (i : Word w)).val := by
+ apply gathered_outside
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)]
+ omega
+ exact ⟨fun hc => configAt_congr_block hc he, fun hc => configAt_congr_block hc fun i hi => (he i hi).symm⟩
+
+theorem fieldWords_eq_calls (M : ℕ) : fieldWords M = calls M := by unfold fieldWords calls; omega
+
+/-- Both gathered banks represent exactly their decoded cut codes.
+`PrepLayout` separately reserves the five-word instruction scratch area. -/
+theorem gathered_boundary_images {p : Program} {pub : Pub → Word w} (hl : PrepLayout p pub M)
+ (hdis : (pub 1).val + calls M ≤ (pub 2).val ∨ (pub 2).val + calls M ≤ (pub 1).val)
+ (incoming outgoing : Fin (fieldWords M*w) → Bool) (m : Memory w) :
+ let m₁ := gathered (k := fieldWords M) (pub 1) (by simpa only [fieldWords_eq_calls] using hl.oldFit) incoming m
+ let m₂ := gathered (k := fieldWords M) (pub 2) (by simpa only [fieldWords_eq_calls] using hl.outFit) outgoing m₁
+ (∀ c : Code p.extra M, ConfigAt m₂ (pub 1) c ↔ (format hl.width hl.states).decode incoming = some c) ∧
+ (∀ c : Code p.extra M, ConfigAt m₂ (pub 2) c ↔ (format hl.width hl.states).decode outgoing = some c) := by
+ exact ⟨fun c => (configAt_gathered_disjoint_iff _ hl.oldFit (by simpa only [fieldWords_eq_calls] using hl.outFit) (by simpa [fieldWords_eq_calls] using hdis) outgoing c).trans
+ (gathered_configAt_iff ..), fun c => gathered_configAt_iff ..⟩
+
+/-- The capped native count on both gathers, written directly as a function
+of the adjacent raw cut fields. A malformed field contributes zero. -/
+theorem card_two_gathers {p : Program} {pub : Pub → Word w} (hl : PrepLayout p pub M)
+ (hdis : (pub 1).val + calls M ≤ (pub 2).val ∨ (pub 2).val + calls M ≤ (pub 1).val)
+ (incoming outgoing : Fin (fieldWords M*w) → Bool) (m : Memory w) {S H : ℕ}
+ (hcost : 10 + 7 * (2 * (2 * M + 1)) ≤ S * H) (hcap : 10 ≤ H) :
+ let m₁ := gathered (k := fieldWords M) (pub 1) (by simpa only [fieldWords_eq_calls] using hl.oldFit) incoming m
+ let m₂ := gathered (k := fieldWords M) (pub 2) (by simpa only [fieldWords_eq_calls] using hl.outFit) outgoing m₁
+ Nat.card (ActualPaths (nativeProgram p pub) (callFuel p) 0 m₂ (withinCaps S H)) =
+ ∑ bit : Bool, if ∃ c z : Code p.extra M,
+ (format hl.width hl.states).decode incoming = some c ∧
+ (format hl.width hl.states).decode outgoing = some z ∧
+ LiveEvaluatorStep.nextCode p c bit = some z ∧ z ≠ .rejected then 1 else 0 := by
+ let m₂ := gathered (k := fieldWords M) (pub 2) (by simpa only [fieldWords_eq_calls] using hl.outFit) outgoing
+ (gathered (k := fieldWords M) (pub 1) (by simpa only [fieldWords_eq_calls] using hl.oldFit) incoming m)
+ obtain ⟨ho, hz⟩ := gathered_boundary_images hl hdis incoming outgoing m
+ dsimp only
+ rw [Nat.card_congr (capPathEquiv p pub m₂ hl.radius (calls_fit hl).le hl.width hl.states hcost hcap)]
+ cases ha : (format hl.width hl.states).decode incoming with
+ | none =>
+ have := native_empty_of_malformed (m := m₂) hl (.inl fun ⟨c, hc⟩ => by simpa [ha] using (ho c).mp hc)
+ simp
+ | some c =>
+ cases hb : (format hl.width hl.states).decode outgoing with
+ | none =>
+ have := native_empty_of_malformed (m := m₂) hl (.inr fun ⟨z, h⟩ => by simpa [hb] using (hz z).mp h)
+ simp
+ | some z =>
+ rw [card_nativeGroup hl ((ho c).mpr ha) ((hz z).mpr hb)]
+ simp
+
+end LiveEvaluatorGroup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorGroup.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorGroup.lean
new file mode 100644
index 0000000000..43c7046e58
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorGroup.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.LiveEvaluatorCells
+import OAI.Computability.VPVNP.LiveEvaluatorRAMPrepareImage
+
+/-!
+# Exact choice multiplicity of one native live evaluator group
+
+The preparing call is the only call that can consume a choice bit. It
+publishes one instruction in scratch and all later calls check its tape
+cells without altering memory. The successful preparation bit streams are
+in bijection with exactly the nonrejecting choices of the evaluator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorGroup
+
+open BurstRAM (Word Memory)
+open UniversalMachine (Program)
+open LiveEvaluatorEncoding (Code)
+open LiveEvaluatorRAM (PrepLayout ConfigAt Prepared prepared_iff preparedMemory preparedMemory_images)
+open LiveEvaluatorRAM.Schedule (Pub calls)
+open LiveEvaluatorAction (pick_checks_iff checks pick_bit_unique branchBits)
+open LiveEvaluatorStep (nextCode)
+
+variable {M w : ℕ} {p : Program} {pub : Pub → Word w} {m : Memory w} {old out : Code p.extra M}
+
+theorem calls_fit (hl : PrepLayout p pub M) : calls M < 2 ^ w := by
+ have h := hl.oldFit
+ obtain ha | ha := hl.oldDisjoint
+ · exact (Nat.le_add_left ..).trans_lt (ha.trans_lt (pub 3).isLt)
+ · omega
+
+/-- Accepting native streams after the entire cell scan. -/
+def SuccessfulStream (M : ℕ) (p : Program) (pub : Pub → Word w) (m : Memory w) (bs : List Bool) : Prop :=
+ ∃ mem, Prepared p pub m mem bs ∧ AllCells M p pub mem
+
+/-- No assumptions about which evaluator row or native slot was selected
+are needed. The memory contents and choice string determine that selection. -/
+theorem successfulStream_iff (hl : PrepLayout p pub M)
+ (ho : ConfigAt m (pub 1) old) (hz : ConfigAt m (pub 2) out) (bs : List Bool) :
+ SuccessfulStream M p pub m bs ↔
+ ∃ bit, bs = branchBits p old bit ∧ nextCode p old bit = some out ∧ out ≠ .rejected := by
+ constructor
+ · rintro ⟨mem, hp, hc⟩
+ obtain ⟨bit, a, ha, hpos, he, hb, rfl⟩ := (prepared_iff hl ho hz).mp hp
+ obtain ⟨ho', hz', himg⟩ := preparedMemory_images hl ho hz ha
+ have hchecks := (allCells_iff p pub _ old out a bit hl.width hl.radius (calls_fit hl)
+ ho' hz' himg ha hpos he).mp hc
+ exact ⟨bit, hb, (pick_checks_iff p old out bit).mp ⟨a, ha, hchecks⟩⟩
+ · rintro ⟨bit, hb, hstep⟩
+ obtain ⟨a, ha, hchecks⟩ := (pick_checks_iff p old out bit).mpr hstep
+ obtain ⟨ho', hz', himg⟩ := preparedMemory_images hl ho hz ha
+ have hpos := hchecks.1
+ have he := hchecks.2.1.symm
+ exact ⟨preparedMemory p pub m old a, (prepared_iff hl ho hz).mpr ⟨bit, a, ha, hpos, he, hb, rfl⟩,
+ (allCells_iff p pub _ old out a bit hl.width hl.radius (calls_fit hl) ho' hz' himg ha hpos he).mpr hchecks⟩
+
+/-- The group preserves path counts, including two slots with the same
+successor, without introducing a choice in a deterministic row or carry. -/
+noncomputable def streamEquiv (hl : PrepLayout p pub M)
+ (ho : ConfigAt m (pub 1) old) (hz : ConfigAt m (pub 2) out) :
+ {bit : Bool // nextCode p old bit = some out ∧ out ≠ .rejected} ≃
+ {bs : List Bool // SuccessfulStream M p pub m bs} := by
+ refine Equiv.ofBijective
+ (fun bit => ⟨branchBits p old bit.val, (successfulStream_iff hl ho hz _).mpr ⟨bit.val, rfl, bit.property⟩⟩)
+ ⟨?_, ?_⟩
+ · intro b d h
+ obtain ⟨a, ha, _⟩ := (pick_checks_iff ..).mpr b.property
+ obtain ⟨a', ha', _⟩ := (pick_checks_iff ..).mpr d.property
+ exact Subtype.ext (pick_bit_unique p old ha ha' (congrArg Subtype.val h))
+ · rintro ⟨bs, hbs⟩
+ obtain ⟨bit, hb, hs⟩ := (successfulStream_iff hl ho hz bs).mp hbs
+ exact ⟨⟨bit, hs⟩, Subtype.ext hb.symm⟩
+
+theorem card_streams (hl : PrepLayout p pub M)
+ (ho : ConfigAt m (pub 1) old) (hz : ConfigAt m (pub 2) out) :
+ Nat.card {bs : List Bool // SuccessfulStream M p pub m bs} =
+ Nat.card {bit : Bool // nextCode p old bit = some out ∧ out ≠ .rejected} :=
+ Nat.card_congr (streamEquiv hl ho hz).symm
+
+end LiveEvaluatorGroup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorInitialize.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorInitialize.lean
new file mode 100644
index 0000000000..885741d056
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorInitialize.lean
@@ -0,0 +1,198 @@
+import OAI.Computability.VPVNP.LiveEvaluatorTail
+import OAI.Computability.VPVNP.EvaluatorInputBank
+import OAI.Computability.VPVNP.LiveHeaderBits
+
+/-!
+# Initial and final words of an evaluator group
+
+At the midpoint the input tape starts at its leftmost input bit, and the
+second tape is blank. In the head-relative field the first input bit goes
+at cell `M`. A fixed native RAM call reads one packed input bit and stores
+its tape symbol. Cells outside the raw input retain their initial zeroes.
+The last group's required accepting configuration has state one and zero
+in every tape field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorInitialize
+
+open UniversalMachine LiveEvaluatorEncoding
+
+/-- A raw bit is nonblank, including a zero input bit. -/
+def bitSymbol (b : Bool) : Symbol := if b then 2 else 1
+
+/-- At cell `i` the head-relative input offset is `i - M`. -/
+def inputCell (M : ℕ) (raw : UniversalMachine.Word) (i : ℕ) : Symbol :=
+ if i < M then 0 else (raw[i - M]?.map bitSymbol).getD 0
+
+private theorem initial_nth (raw : UniversalMachine.Word) (j : ℤ) :
+ (Turing.Tape.mk₁ (raw.map bitSymbol)).nth j =
+ if j < 0 then 0 else (raw[j.toNat]?.map bitSymbol).getD 0 := by
+ cases j with
+ | ofNat n =>
+ change (Turing.Tape.mk' _ _).nth (n : ℤ) = _
+ rw [Turing.Tape.mk'_nth_nat, Turing.ListBlank.nth_mk, List.getI_eq_getElem?_getD, List.getElem?_map]
+ simp
+ | negSucc n =>
+ change (Turing.ListBlank.mk ([] : List Symbol)).nth n = _
+ rw [Turing.ListBlank.nth_mk, List.getI_eq_default _ (by simp)]
+ rw [ite_eq_left (Int.negSucc_lt_zero n)]
+ rfl
+
+theorem initial_firstTape (p : Program) (raw : UniversalMachine.Word) (M : ℕ) (i : Fin (2 * M + 1)) :
+ (TapeWindow.ofTape M (initial p raw).firstTape).cells i = inputCell M raw i.val := by
+ change (Turing.Tape.mk₁ (raw.map bitSymbol)).nth _ = _
+ rw [initial_nth]
+ simp [inputCell, show ((i.val : ℤ) - M < 0) ↔ i.val < M by omega,
+ show ((i.val : ℤ) - M).toNat = i.val - M by omega]
+
+theorem initial_secondTape (p : Program) (raw : UniversalMachine.Word) (M : ℕ) (i : Fin (2 * M + 1)) :
+ (TapeWindow.ofTape M (initial p raw).secondTape).cells i = 0 := by
+ change (Turing.Tape.mk₁ (([] : List Bool).map bitSymbol)).nth _ = _
+ rw [initial_nth]
+ split <;> rfl
+
+/-- The state word is one for the empty table and two for a nonempty
+machine, even if it rejects on its first transition. -/
+theorem initial_state (p : Program) (raw : UniversalMachine.Word) (M : ℕ) :
+ (LiveEvaluatorTail.initialCode M (initial p raw)).stateWord.val =
+ if p.extra = 0 then 1 else 2 := by
+ by_cases he : p.extra = 0 <;> simp [LiveEvaluatorTail.initialCode, initial, he, Code.stateWord,
+ ConfigWindow.ofConfig]
+
+theorem initial_first (p : Program) (raw : UniversalMachine.Word) (M : ℕ) (i : Fin (2 * M + 1)) :
+ (LiveEvaluatorTail.initialCode M (initial p raw)).firstCell i =
+ if p.extra = 0 then 0 else inputCell M raw i.val := by
+ by_cases he : p.extra = 0
+ · simp [LiveEvaluatorTail.initialCode, initial, he, Code.firstCell]
+ · simpa [LiveEvaluatorTail.initialCode, initial, he, Code.firstCell, ConfigWindow.ofConfig]
+ using initial_firstTape p raw M i
+
+theorem initial_second (p : Program) (raw : UniversalMachine.Word) (M : ℕ) (i : Fin (2 * M + 1)) :
+ (LiveEvaluatorTail.initialCode M (initial p raw)).secondCell i = 0 := by
+ by_cases he : p.extra = 0
+ · simp [LiveEvaluatorTail.initialCode, initial, he, Code.secondCell]
+ · simpa [LiveEvaluatorTail.initialCode, initial, he, Code.secondCell, ConfigWindow.ofConfig]
+ using initial_secondTape p raw M i
+
+/-- Address a field bit by the exact length of all preceding port fields. -/
+theorem rawInput_at_field {K : Type} (before after : List K) (k : K) (bank : RAMTape.Stacks K)
+ (j : Fin (Evaluator.InputBank.fieldBits (bank k)).length) :
+ (Evaluator.InputBank.rawInput (before ++ k :: after) bank)[
+ (Evaluator.InputBank.rawInput before bank).length + j.val]? =
+ some ((Evaluator.InputBank.fieldBits (bank k))[j.val]) := by
+ simp only [Evaluator.InputBank.rawInput, List.flatMap_append, List.flatMap_cons]
+ rw [List.getElem?_append_right (by omega), Nat.add_sub_cancel_left,
+ List.getElem?_append_left j.isLt, List.getElem?_eq_getElem j.isLt]
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Pack the raw stream in little-endian words. Bits in the last incomplete
+word and all words beyond the stream use zero padding. -/
+def inputWord (w : ℕ) (raw : UniversalMachine.Word) (row : ℕ) : BurstRAM.Word w :=
+ (RAMSerialization.wordBits w).symm (fun i => raw[row * w + i.val]?.getD false)
+
+theorem inputWord_bit (hw : 0 < w) (raw : UniversalMachine.Word) (j : ℕ) :
+ (inputWord w raw (j / w)).val.testBit (j % w) = raw[j]?.getD false := by
+ let slot : Fin w := ⟨j % w, Nat.mod_lt _ hw⟩
+ rw [show j % w = slot.val from rfl, LiveHeader.testBit_wordBits]
+ simp [inputWord, slot, Nat.div_add_mod']
+
+/-- Public words give the radius, destination state base, packed raw input
+base and word width, in that order. The persistent state is the input bit
+number. Register 29 returns the next bit number. -/
+def copyBit : List (Op 32 4) :=
+ [.constant 1 1, .stateWord 26, .publicWord 11 0, .publicWord 23 1,
+ .publicWord 24 2, .publicWord 22 3,
+ .binary .div 18 26 22, .binary .mod 19 26 22, .binary .add 20 24 18,
+ .read 21 20, .binary .shiftRight 21 21 19, .binary .bitAnd 21 21 1,
+ .binary .add 21 21 1, .binary .add 20 23 1, .binary .add 20 20 11,
+ .binary .add 20 20 26, .write 20 21, .binary .add 29 26 1]
+
+/-- Store the canonical state word into an otherwise blank bank. The same
+native call with tag one prepares the required output at the final group. -/
+def putState (tag : BurstRAM.Word 2) : List (Op 32 4) :=
+ [.publicWord 23 1, .constant 16 tag, .write 23 16, .stateWord 29]
+
+private theorem wordMod_lt (hw : 0 < w) (n : ℕ) : n % w < 2 ^ w :=
+ (Nat.mod_lt n hw).trans (Nat.lt_two_pow_self (n := w))
+
+/-- The address of the packed input word containing the specified input bit. -/
+def sourceAddress (pub : Fin 4 → BurstRAM.Word w) (pos : BurstRAM.Word w) :=
+ pub 2 + Fin.ofNat (2 ^ w) (pos.val / w)
+
+/-- The first-tape cell receiving an input bit, counting forward from the head in the
+serialized configuration. -/
+def targetAddress (pub : Fin 4 → BurstRAM.Word w) (pos : BurstRAM.Word w) :=
+ pub 1 + 1 + pub 0 + pos
+
+theorem copyBit_trace_replay (hw : 2 ≤ w) (pub : Fin 4 → BurstRAM.Word w) (hwidth : (pub 3).val = w)
+ (pos : BurstRAM.Word w) (rs : Regs w 32) (m : Memory w) :
+ let bit := (m (sourceAddress pub pos).val).val.testBit (pos.val % w)
+ let symbol := PrimedInputRAM.encodeBit w bit + 1
+ ∃ es out, trace pub pos copyBit rs m = some (es, out, writeMemory m (targetAddress pub pos) symbol) ∧
+ out 29 = pos + 1 ∧ after m es = writeMemory m (targetAddress pub pos) symbol ∧
+ es.length = 18 ∧ countProbes es = 2 ∧ choiceBits es = [] ∧ ∀ u, after u es = writeMemory u (targetAddress pub pos) symbol := by
+ have hmod := wordMod_lt (by omega : 0 < w) pos.val
+ simp (config := { decide := true }) [copyBit, trace, Op.effect, Function.update,
+ show BinaryOp.add.eval = (· + · : BurstRAM.Word w → BurstRAM.Word w → BurstRAM.Word w) from rfl,
+ show BinaryOp.div.eval = (fun (x y : BurstRAM.Word w) => Fin.ofNat _ (x.val / y.val)) from rfl,
+ show BinaryOp.mod.eval = (fun (x y : BurstRAM.Word w) => Fin.ofNat _ (x.val % y.val)) from rfl,
+ PrimedInputRAM.Opcodes.readBit_word (by omega : 0 < w), hwidth,
+ Nat.mod_eq_of_lt hmod, sourceAddress, targetAddress, after, update, countProbes, choiceBits]
+
+theorem copyBit_trace (hw : 2 ≤ w) (pub : Fin 4 → BurstRAM.Word w) (hwidth : (pub 3).val = w)
+ (pos : BurstRAM.Word w) (rs : Regs w 32) (m : Memory w) :
+ let bit := (m (sourceAddress pub pos).val).val.testBit (pos.val % w)
+ let symbol := PrimedInputRAM.encodeBit w bit + 1
+ ∃ es out, trace pub pos copyBit rs m = some (es, out, writeMemory m (targetAddress pub pos) symbol) ∧
+ out 29 = pos + 1 ∧ after m es = writeMemory m (targetAddress pub pos) symbol ∧
+ es.length = 18 ∧ countProbes es = 2 ∧ choiceBits es = [] := by
+ obtain ⟨es, out, run, next, effect, size, probes, bits, _⟩ := copyBit_trace_replay hw pub hwidth pos rs m
+ exact ⟨es, out, run, next, effect, size, probes, bits⟩
+
+/-- Native code emits exactly one initialized input symbol with a single
+read and write, advancing its persistent cursor. -/
+theorem copyBit_native (hw : 2 ≤ w) (pub : Fin 4 → BurstRAM.Word w) (hwidth : (pub 3).val = w)
+ (pos : BurstRAM.Word w) (m : Memory w) (raw : UniversalMachine.Word) (hj : pos.val < raw.length)
+ (hpack : m (sourceAddress pub pos).val = inputWord w raw (pos.val / w)) :
+ let machine := (template copyBit 29).instantiate w pub
+ ∃ es, execute machine.program 19 (machine.program.start pos) m [] = some ⟨es, some (pos + 1)⟩ ∧
+ after m es = writeMemory m (targetAddress pub pos) (PrimedInputRAM.encodeBit w raw[pos.val] + 1) ∧
+ es.length = 18 ∧ countProbes es = 2 ∧ choiceBits es = [] := by
+ dsimp only
+ obtain ⟨es, out, ht, ho, hm, hl, hp, hb⟩ := copyBit_trace hw pub hwidth pos (fun _ => 0) m
+ refine ⟨es, ?_, ?_, hl, hp, hb⟩
+ · change execute ((template copyBit 29).instantiate w pub).program (1 + copyBit.length)
+ ⟨_,pos,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [ho]
+ · simpa [hpack, inputWord_bit (by omega : 0 < w), List.getElem?_eq_getElem hj] using hm
+
+/-- One native write prepares the state field. The full halt-bank contents
+are canonical if its tape fields are in zero-default memory. -/
+theorem putState_native (pub : Fin 4 → BurstRAM.Word w) (pos : BurstRAM.Word w) (m : Memory w)
+ (tag : BurstRAM.Word 2) :
+ let machine := (template (putState tag) 29).instantiate w pub
+ ∃ es, execute machine.program 5 (machine.program.start pos) m [] = some ⟨es, some pos⟩ ∧
+ after m es = writeMemory m (pub 1) (Fin.ofNat _ tag.val) ∧
+ es.length = 4 ∧ countProbes es = 1 ∧ choiceBits es = [] := by
+ dsimp only
+ let es : List (Event w) := [.tick, .tick, .write (pub 1) (Fin.ofNat _ tag.val), .tick]
+ refine ⟨es, ?_, rfl, rfl, rfl, rfl⟩
+ change execute ((template (putState tag) 29).instantiate w pub).program (1 + (putState tag).length)
+ ⟨_,pos,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]
+ simp (config := {decide := true}) [putState, trace, Op.effect, es, Function.update]
+
+end LiveEvaluatorInitialize
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorInitializeStages.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorInitializeStages.lean
new file mode 100644
index 0000000000..1df9ca9d85
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorInitializeStages.lean
@@ -0,0 +1,336 @@
+import OAI.Computability.VPVNP.LiveEvaluatorInitializeSweep
+import OAI.Computability.VPVNP.PrimedCounterRename
+
+/-!
+# Linkable stages for the evaluator endpoints
+
+The control-word write accepts immediately. The tape-copy stage returns its
+cursor on an intermediate bit and accepts on the last bit. If the public
+active length is zero, one call accepts without reading or writing memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorInitialize
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM LiveEvaluatorEncoding
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The control-word write is a complete native stage. -/
+def putStage (tag : Word 2) : Template 4 32 4 where
+ literalWidth := 2
+ entry := 0
+ code
+ | 0 => .publicWord 23 1 1
+ | 1 => .constant 16 tag 2
+ | 2 => .writeExternal 23 16 3
+ | 3 => .accept
+
+/-- Exact result and branch string for the one-call stage. -/
+theorem execute_putStage (tag : Word 2) (pub : Fin 4 → Word w) (s : Word w)
+ (m : Memory w) (bits : List Bool) (f : ℕ) :
+ let P := ((putStage tag).instantiate w pub).program
+ execute P (f+4) (P.start s) m bits = if bits = [] then
+ some ⟨[.tick, .tick, .write (pub 1) (Fin.ofNat _ tag.val)], none⟩ else none := by
+ cases bits <;> rfl
+
+/-- The endpoint stage that writes the accepting control word and finishes in one call. -/
+abbrev finalStage : Template 4 32 4 := putStage 1
+
+/-- One native stage prepares the accepting endpoint in its scratch bank. -/
+theorem finalStage_stores {extra M : ℕ} (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w)
+ (pub : Fin 4 → Word w) (s : Word w) (m : Memory w)
+ (zero : ∀ k : Fin (fieldWords M), m ((pub 1).val + k.val) = 0) :
+ let P := (finalStage.instantiate w pub).program
+ ∃ es, execute P 4 (P.start s) m [] = some ⟨es, none⟩ ∧
+ Stores hw hs (pub 1).val (after m es) (.accepted : Code extra M) ∧
+ es.length = 3 ∧ countProbes es = 1 ∧ choiceBits es = [] := by
+ refine ⟨[.tick, .tick, .write (pub 1) 1], ?_, final_stores hw hs _ _ zero, rfl, rfl, rfl⟩
+ exact execute_putStage 1 pub s m [] 0
+
+private def copyOps : List (Op 32 5) := copyBit.map (PrimedCounter.renameOp id Fin.castSucc)
+
+/-- The fifth public word is the active bit length. The entry guard bypasses
+the packed input for a zero-length sweep. The exit test hands off the stage
+on the call that actually wrote the last input symbol. -/
+def copyStage : Template 25 32 5 where
+ literalWidth := 2
+ entry := 21
+ code i := if h : i.val < copyOps.length then
+ copyOps[i.val].emit ⟨i.val+1, by have : copyOps.length = 18 := rfl; omega⟩ 24
+ else if i = 18 then .jumpLt 29 30 19 20
+ else if i = 19 then .returnState 29
+ else if i = 20 then .accept
+ else if i = 21 then .stateWord 26 22
+ else if i = 22 then .publicWord 30 4 23
+ else if i = 23 then .jumpLt 26 30 0 20
+ else .reject
+
+/-- Place the active bit count after the four existing evaluator operands. -/
+def copyPublic (pub : Fin 4 → Word w) (count : Word w) : Fin 5 → Word w := Fin.snoc pub count
+
+private theorem contains_copy (data : Fin 5 → Word w) :
+ Contains (copyStage.instantiate w data) 24 0 copyOps 18 := by
+ iterate 18 apply Contains.cons rfl
+ exact .nil _
+
+private def entryRegs (s count : Word w) : Regs w 32 :=
+ Function.update (Function.update (fun _ => 0) 26 s) 30 count
+
+private theorem execute_entry (data : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (bits : List Bool) (f : ℕ) (hs : s < data 4) :
+ let M := copyStage.instantiate w data
+ execute M.program (f+3) (M.program.start s) m bits =
+ (execute M.program f ⟨0,s,entryRegs s (data 4),fun _ => 0⟩ m bits).map
+ (fun r => r.prepend .tick |>.prepend .tick |>.prepend .tick) := by
+ dsimp only
+ simp (config := { decide := true }) [execute, Machine.program, copyStage, Template.instantiate,
+ Instr.resize, Instr.run, Config.put, Function.update, hs, Option.map_map, Function.comp_def, entryRegs, copyOps, copyBit]
+
+/-- When the cursor is already at the public capacity, the guard accepts
+with three local ticks and leaves memory intact. -/
+theorem execute_copyStage_skip (data : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (bits : List Bool) (f : ℕ) (hs : data 4 ≤ s) :
+ let P := (copyStage.instantiate w data).program
+ execute P (f+4) (P.start s) m bits =
+ if bits = [] then some ⟨[.tick,.tick,.tick], none⟩ else none := by
+ cases bits <;>
+ simp (config := { decide := true }) [execute, Machine.program, copyStage, Template.instantiate,
+ Instr.resize, Instr.run, Config.put, Function.update, not_lt.mpr hs, copyOps, copyBit, Report.prepend]
+
+private theorem execute_exit (data : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (bits : List Bool) (f : ℕ) (regs : Regs w 32) :
+ let M := copyStage.instantiate w data
+ execute M.program (f+2) ⟨18,s,regs,fun _ => 0⟩ m bits =
+ if bits = [] then some ⟨[.tick], if regs 29 < regs 30 then some (regs 29) else none⟩ else none := by
+ by_cases h : regs 29 < regs 30 <;> cases bits <;>
+ simp (config := { decide := true }) [execute, Machine.program, copyStage, Template.instantiate,
+ Instr.resize, Instr.run, h, copyOps, copyBit, Report.prepend]
+
+/-- Execute one active bit at any sufficient instruction cap. Only the
+empty branch string succeeds. Every such call performs the packed source
+read, the destination write, and four extra control ticks. -/
+theorem execute_copyStage_active_replay (hw : 2 ≤ w) (pub : Fin 4 → Word w)
+ (width : (pub 3).val = w) (bound s : Word w) (active : s < bound)
+ (m : Memory w) (bits : List Bool) (f : ℕ) :
+ let P := (copyStage.instantiate w (copyPublic pub bound)).program
+ let bit := (m (sourceAddress pub s).val).val.testBit (s.val % w)
+ ∃ es, execute P (f+23) (P.start s) m bits = (if bits = [] then
+ some ⟨es, if s+1 < bound then some (s+1) else none⟩ else none) ∧
+ after m es = writeMemory m (targetAddress pub s) (PrimedInputRAM.encodeBit w bit + 1) ∧
+ es.length = 22 ∧ countProbes es = 2 ∧ choiceBits es = [] ∧
+ ∀ u, after u es = writeMemory u (targetAddress pub s) (PrimedInputRAM.encodeBit w bit + 1) := by
+ let data := copyPublic pub bound
+ have hdata : data 4 = bound := Fin.snoc_last ..
+ let regs := entryRegs s bound
+ obtain ⟨es, out, ht, hout, hmem, hl, hp, hb, replay⟩ := copyBit_trace_replay hw pub width s regs m
+ have hout' : out 30 = bound := by
+ have hf : out 30 = regs 30 := trace_preserves (by decide : ∀ op ∈ copyBit, op.destination ≠ some 30) ht
+ rw [hf]
+ exact Function.update_self ..
+ have ht' : trace data s copyOps regs m = _ := ht
+ let M := copyStage.instantiate w data
+ have hrun := (contains_copy data).execute (by rfl) s regs (fun _ => 0) m bits (f+2)
+ change execute M.program (f+20) ⟨0,s,regs,fun _ => 0⟩ m bits = _ at hrun
+ rw [run_eq_trace] at hrun
+ change trace M.publicData s copyOps regs m = _ at ht'
+ rw [ht'] at hrun
+ dsimp only [Option.bind_some] at hrun
+ rw [execute_exit data, hout, hout'] at hrun
+ dsimp only
+ refine ⟨.tick :: .tick :: .tick :: (es ++ [.tick]), ?_, ?_, by simp [hl], ?_, ?_, ?_⟩
+ · change execute M.program (f+23) (M.program.start s) m bits = _
+ rw [show f+23 = (f+20)+3 by omega, execute_entry data s m bits _ (by rwa [hdata]), hdata, hrun]
+ cases bits <;> simp [Report.prepend]
+ · simpa [after, List.foldl_append, update] using hmem
+ · change countProbes (es ++ [.tick]) = 2
+ have ha (xs : List (Event w)) : countProbes (xs ++ [.tick]) = countProbes xs := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih => cases x <;> simp [countProbes, ih]
+ rwa [ha]
+ · change choiceBits (es ++ [.tick]) = []
+ have ha (xs : List (Event w)) : choiceBits (xs ++ [.tick]) = choiceBits xs := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih => cases x <;> simp [choiceBits, ih]
+ rwa [ha]
+
+ · intro u
+ simpa only [after, List.foldl_append, List.foldl_cons, List.foldl_nil, update] using replay u
+
+theorem execute_copyStage_active (hw : 2 ≤ w) (pub : Fin 4 → Word w)
+ (width : (pub 3).val = w) (bound s : Word w) (active : s < bound)
+ (m : Memory w) (bits : List Bool) (f : ℕ) :
+ let P := (copyStage.instantiate w (copyPublic pub bound)).program
+ let bit := (m (sourceAddress pub s).val).val.testBit (s.val % w)
+ ∃ es, execute P (f+23) (P.start s) m bits = (if bits = [] then
+ some ⟨es, if s+1 < bound then some (s+1) else none⟩ else none) ∧
+ after m es = writeMemory m (targetAddress pub s) (PrimedInputRAM.encodeBit w bit + 1) ∧
+ es.length = 22 ∧ countProbes es = 2 ∧ choiceBits es = [] := by
+ obtain ⟨es, run, effect, size, probes, choices, _⟩ :=
+ execute_copyStage_active_replay hw pub width bound s active m bits f
+ exact ⟨es, run, effect, size, probes, choices⟩
+
+private abbrev copyProgram (pub : Fin 4 → Word w) :=
+ ((template copyBit 29).instantiate w pub).program
+
+private abbrev stageProgram (pub : Fin 4 → Word w) (count : Word w) :=
+ (copyStage.instantiate w (copyPublic pub count)).program
+
+/-- The bounded and unbounded copies differ only in control events and their
+return state. They read and write the same actual memory. -/
+private theorem copy_pair (hw : 2 ≤ w) (pub : Fin 4 → Word w) (width : (pub 3).val = w)
+ (bound s : Word w) (active : s < bound) (m : Memory w) :
+ ∃ es fs, execute (copyProgram pub) 19 ((copyProgram pub).start s) m [] = some ⟨es,some (s+1)⟩ ∧
+ execute (stageProgram pub bound) 23 ((stageProgram pub bound).start s) m [] =
+ some ⟨fs, if s+1 < bound then some (s+1) else none⟩ ∧
+ after m es = after m fs ∧ fs.length = 22 ∧ countProbes fs = 2 ∧ choiceBits fs = [] := by
+ obtain ⟨es, out, ht, ho, hm, _, _, _⟩ := copyBit_trace hw pub width s (fun _ => 0) m
+ obtain ⟨fs, hf, hm', hl, hp, hb⟩ := execute_copyStage_active hw pub width bound s active m [] 0
+ refine ⟨es,fs,?_,hf,hm.trans hm'.symm,hl,hp,hb⟩
+ change execute (copyProgram pub) (1+copyBit.length) ⟨_,s,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [ho]
+
+private theorem eventLog_after_cons (m : Memory w) (r : Report w) (rs : List (Report w)) :
+ after m (eventLog (r :: rs)) = after (after m r.events) (eventLog rs) := by
+ simp [after, eventLog, List.foldl_append]
+
+private theorem replay_positive (hw : 2 ≤ w) (pub : Fin 4 → Word w) (width : (pub 3).val = w)
+ (bound : Word w) (n j : ℕ) (remaining : j + (n+1) = bound.val) (m : Memory w)
+ (old : List (Report w))
+ (hr : runSegment (copyProgram pub) 19 (some (j : Word w)) m (List.replicate (n+1) []) = some old) :
+ ∃ rs, runSegment (stageProgram pub bound) 23 (some (j : Word w)) m (List.replicate (n+1) []) = some rs ∧
+ endState (some (j : Word w)) rs = none ∧ after m (eventLog rs) = after m (eventLog old) ∧
+ rs.length = n+1 ∧ ∀ r ∈ rs, r.events.length = 22 ∧ countProbes r.events = 2 ∧ choiceBits r.events = [] := by
+ induction n generalizing j m old with
+ | zero =>
+ have hj : (j : Word w).val = j := Fin.val_cast_of_lt (by have := bound.isLt; omega)
+ have hactive : (j : Word w) < bound := Fin.lt_def.mpr (by omega)
+ have hnext : (j : Word w) + 1 = bound := by
+ apply Fin.ext
+ rw [Fin.val_add_one_of_lt' (by have := bound.isLt; omega), hj]; omega
+ obtain ⟨es, fs, he, hf, hm, hl, hp, hb⟩ := copy_pair hw pub width bound _ hactive m
+ change runSegment (copyProgram pub) 19 (some (j : Word w)) m [[]] = some old at hr
+ simp only [runSegment, he, Option.map_some, Option.some.injEq] at hr
+ subst old
+ simp only [hnext, lt_irrefl, ite_false] at hf
+ refine ⟨[⟨fs,none⟩], ?_, rfl, ?_, rfl, ?_⟩
+ · change runSegment (stageProgram pub bound) 23 (some (j : Word w)) m [[]] = _
+ simp [runSegment, hf]
+ · simpa [eventLog] using hm.symm
+ · simpa using And.intro hl (And.intro hp hb)
+ | succ n ih =>
+ have hj : (j : Word w).val = j := Fin.val_cast_of_lt (by have := bound.isLt; omega)
+ have hactive : (j : Word w) < bound := Fin.lt_def.mpr (by omega)
+ have hcast : (j : Word w)+1 = ((j+1 : ℕ) : Word w) := by simp
+ have hnext : (j : Word w)+1 < bound :=
+ Fin.lt_def.mpr (by rw [Fin.val_add_one_of_lt' (by have := bound.isLt; omega), hj]; omega)
+ obtain ⟨es, fs, he, hf, hm, hl, hp, hb⟩ := copy_pair hw pub width bound _ hactive m
+ rw [ite_eq_left hnext, hcast] at hf
+ rw [hcast] at he
+ rw [List.replicate_succ, runSegment, he] at hr
+ obtain ⟨oldTail, ht, rfl⟩ := Option.map_eq_some_iff.mp hr
+ obtain ⟨rs, hrun, hend, hmem, hlen, hcost⟩ := ih (j+1) (by omega) (after m es) oldTail ht
+ let r : Report w := ⟨fs, some ((j+1 : ℕ) : Word w)⟩
+ refine ⟨r :: rs, ?_, hend, ?_, by simpa only [List.length_cons] using congrArg (·+1) hlen, ?_⟩
+ · rw [List.replicate_succ, runSegment, hf]
+ dsimp only
+ rw [← hm, hrun]
+ rfl
+ · simpa only [eventLog_after_cons, r, ← hm] using hmem
+ · intro t ht
+ rcases List.mem_cons.mp ht with rfl | ht
+ · exact ⟨hl,hp,hb⟩
+ · exact hcost t ht
+
+/-- Starting at cursor zero, the copy stage uses exactly one call per active
+bit, or one empty skip for a zero-length input. Its last call accepts, and its
+memory contains the same initialized symbols as the unbounded copy sweep. -/
+theorem copyStage_sweep (hw : 2 ≤ w) (pub : Fin 4 → Word w) (width : (pub 3).val = w)
+ (p : UniversalMachine.Program) (raw : UniversalMachine.Word) (original : Memory w)
+ (fit : firstData pub + activeLength p raw ≤ 2 ^ w)
+ (packed : ∀ j < activeLength p raw,
+ original (sourceAddress pub (j : Word w)).val = inputWord w raw (j / w))
+ (disjoint : ∀ j < activeLength p raw, (sourceAddress pub (j : Word w)).val < firstData pub ∨
+ firstData pub + activeLength p raw ≤ (sourceAddress pub (j : Word w)).val) :
+ let count := activeLength p raw
+ let P := (copyStage.instantiate w (copyPublic pub (count : Word w))).program
+ ∃ rs, runSegment P 23 (some 0) original (List.replicate (max 1 count) []) = some rs ∧
+ endState (some 0) rs = none ∧ Copied raw (firstData pub) count original (after original (eventLog rs)) ∧
+ rs.length = max 1 count ∧ ∀ r ∈ rs,
+ r.events.length ≤ 22 ∧ countProbes r.events ≤ 2 ∧ choiceBits r.events = [] := by
+ dsimp only
+ let count := activeLength p raw
+ have hfit : count < 2 ^ w := by dsimp [firstData] at fit; change activeLength p raw < _; omega
+ have hval : (count : Word w).val = count := Fin.val_cast_of_lt hfit
+ obtain ⟨old, hr, _, hcopy, _, _⟩ := copy_segment hw pub width p raw original fit packed disjoint
+ change runSegment (copyProgram pub) 19 (some 0) original (List.replicate count []) = some old at hr
+ change Copied raw _ count _ _ at hcopy
+ change ∃ rs : List (Report w), runSegment (stageProgram pub (count : Word w)) 23 (some 0) original (List.replicate (max 1 count) []) = some rs ∧
+ endState (some 0) rs = none ∧ Copied raw _ count original (after original (eventLog rs)) ∧ rs.length = max 1 count ∧ _
+ cases hc : count with
+ | zero =>
+ rw [hc] at hr hcopy
+ simp only [List.replicate_zero, runSegment, Option.some.injEq] at hr
+ subst old
+ let r : Report w := ⟨[.tick,.tick,.tick],none⟩
+ refine ⟨[r], ?_, rfl, hcopy, rfl, ?_⟩
+ · change (runSegment (stageProgram pub 0) 23 (some 0) original [[]]) = _
+ have he := execute_copyStage_skip (copyPublic pub 0) 0 original [] 19
+ (by have heq : copyPublic pub 0 4 = 0 := Fin.snoc_last ..; exact heq.le)
+ rw [runSegment, he]
+ rfl
+ · simp [r, countProbes, choiceBits]
+ | succ n =>
+ rw [max_eq_right (by omega : 1 ≤ n+1)]
+ rw [hc] at hval hcopy
+ have hr' : runSegment (copyProgram pub) 19 (some (0 : Word w)) original (List.replicate (n+1) []) = some old := by
+ simpa [hc] using hr
+ obtain ⟨rs, hrun, hend, hm, hl, hp⟩ := replay_positive hw pub width ((n+1 : ℕ) : Word w)
+ n 0 (by omega) original old hr'
+ refine ⟨rs,hrun,hend,hm ▸ hcopy,hl,?_⟩
+ intro r hr
+ obtain ⟨h₁,h₂,h₃⟩ := hp r hr
+ exact ⟨h₁.le,h₂.le,h₃⟩
+
+/-- The two accepting stages, with a fresh cursor at the handoff, prepare the
+actual evaluator's initial bank from the packed input words. -/
+theorem prepareStages (hw : 2 ≤ w) (pub : Fin 4 → Word w) (width : (pub 3).val = w)
+ (p : UniversalMachine.Program) (hs : p.extra + 2 ≤ 2 ^ w)
+ (raw : UniversalMachine.Word) (blank : Memory w)
+ (space : raw.length ≤ (pub 0).val + 1)
+ (fit : firstData pub + activeLength p raw ≤ 2 ^ w)
+ (zero : ∀ k : Fin (fieldWords (pub 0).val), blank ((pub 1).val + k.val) = 0)
+ (packed : ∀ j < activeLength p raw, blank (sourceAddress pub (j : Word w)).val = inputWord w raw (j / w))
+ (disjoint : ∀ j < activeLength p raw, let a := (sourceAddress pub (j : Word w)).val
+ a ≠ (pub 1).val ∧ (a < firstData pub ∨ firstData pub + activeLength p raw ≤ a)) :
+ let count := activeLength p raw
+ let S := ((putStage (controlTag p)).instantiate w pub).program
+ let P := (copyStage.instantiate w (copyPublic pub (count : Word w))).program
+ ∃ es rs, execute S 4 (S.start 0) blank [] = some ⟨es,none⟩ ∧
+ runSegment P 23 (some 0) (after blank es) (List.replicate (max 1 count) []) = some rs ∧
+ endState (some 0) rs = none ∧ Stores hw hs (pub 1).val (after (after blank es) (eventLog rs))
+ (LiveEvaluatorTail.initialCode (pub 0).val (UniversalMachine.initial p raw)) ∧
+ es.length = 3 ∧ countProbes es = 1 ∧ choiceBits es = [] ∧ rs.length = max 1 count ∧
+ ∀ r ∈ rs, r.events.length ≤ 22 ∧ countProbes r.events ≤ 2 ∧ choiceBits r.events = [] := by
+ let es : List (Event w) := [.tick,.tick,.write (pub 1) (Fin.ofNat _ (controlTag p).val)]
+ have hm : after blank es = writeMemory blank (pub 1) (Fin.ofNat _ (controlTag p).val) := rfl
+ have saved (j : ℕ) (hj : j < activeLength p raw) :
+ after blank es (sourceAddress pub (j : Word w)).val = inputWord w raw (j / w) := by
+ rw [hm, writeMemory, ite_eq_right (disjoint j hj).1, packed j hj]
+ obtain ⟨rs, hrun, hend, hcopy, hl, hp⟩ :=
+ copyStage_sweep hw pub width p raw (after blank es) fit saved (fun j hj => (disjoint j hj).2)
+ refine ⟨es, rs, execute_putStage _ _ _ _ _ 0, hrun, hend, ?_, rfl, rfl, rfl, hl, hp⟩
+ exact copied_stores hw pub p hs raw blank _ space zero hcopy
+
+end LiveEvaluatorInitialize
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorInitializeSweep.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorInitializeSweep.lean
new file mode 100644
index 0000000000..62472f4304
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorInitializeSweep.lean
@@ -0,0 +1,229 @@
+import OAI.Computability.VPVNP.LiveEvaluatorInitialize
+import OAI.Computability.VPVNP.LiveHeaderRuns
+
+/-!
+# Complete native scan of the evaluator's initial tape
+
+The initialized state bank occupies consecutive words for the control and
+both tapes. A state write is followed by one native burst per input bit on a
+running evaluator. An initially halted evaluator and the final accepting
+endpoint each use a single state write.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorInitialize
+
+open UniversalMachine (Program)
+open LiveEvaluatorEncoding
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Number of input bits to copy into the initial tape, zero for an evaluator that starts
+halted. -/
+def activeLength (p : Program) (raw : UniversalMachine.Word) : ℕ :=
+ if p.extra = 0 then 0 else raw.length
+
+/-- The initial control word, one for an initially accepting evaluator and two for its first
+running state. -/
+def controlTag (p : Program) : Word 2 := if p.extra = 0 then 1 else 2
+
+/-- A complete word image of the code in the contiguous memory region. -/
+def Stores {extra M : ℕ} (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w) (base : ℕ)
+ (m : Memory w) (c : Code extra M) : Prop :=
+ ∀ k : Fin (fieldWords M), m (base + k.val) = words hw hs c k
+
+/-- Each configuration word is the control field or one indexed tape symbol. -/
+theorem field_cases {M : ℕ} (k : Fin (fieldWords M)) :
+ k = stateField M ∨ (∃ i, k = firstField i) ∨ (∃ i, k = secondField i) := by
+ have hk := k.isLt
+ unfold fieldWords at hk
+ by_cases h₀ : k.val = 0
+ · exact Or.inl (Fin.ext h₀)
+ by_cases h₁ : k.val < 1 + (2 * M + 1)
+ · exact Or.inr (Or.inl ⟨⟨k.val - 1, by omega⟩, Fin.ext (by dsimp [firstField]; omega)⟩)
+ · exact Or.inr (Or.inr ⟨⟨k.val - (1 + (2 * M + 1)), by omega⟩,
+ Fin.ext (by dsimp [secondField]; omega)⟩)
+
+/-- The natural address of the head cell of the first tape, where copying the initial input
+begins. -/
+def firstData (pub : Fin 4 → Word w) : ℕ := (pub 1).val + 1 + (pub 0).val
+
+/-- Precisely the first `cursor` symbols have been written. -/
+structure Copied (raw : UniversalMachine.Word) (base cursor : ℕ) (original m : Memory w) : Prop where
+ symbols : ∀ j < cursor, m (base + j) = PrimedInputRAM.encodeBit w (raw[j]?.getD false) + 1
+ outside : ∀ a, a < base ∨ base + cursor ≤ a → m a = original a
+
+private theorem word_add_val (a b : Word w) (h : a.val + b.val < 2 ^ w) :
+ (a + b).val = a.val + b.val := by rw [Fin.val_add, Nat.mod_eq_of_lt h]
+
+/-- The native run over every input bit, including the empty run when
+the evaluator starts in its accepting state. The source words may be on
+either side of the writable input interval. -/
+theorem copy_segment (hw : 2 ≤ w) (pub : Fin 4 → Word w) (width : (pub 3).val = w)
+ (p : Program) (raw : UniversalMachine.Word) (original : Memory w)
+ (fit : firstData pub + activeLength p raw ≤ 2 ^ w)
+ (packed : ∀ j < activeLength p raw,
+ original (sourceAddress pub (j : Word w)).val = inputWord w raw (j / w))
+ (disjoint : ∀ j < activeLength p raw, (sourceAddress pub (j : Word w)).val < firstData pub ∨
+ firstData pub + activeLength p raw ≤ (sourceAddress pub (j : Word w)).val) :
+ let P := ((template copyBit 29).instantiate w pub).program
+ ∃ reports, runSegment P 19 (some 0) original (List.replicate (activeLength p raw) []) = some reports ∧
+ endState (some 0) reports = some (activeLength p raw : Word w) ∧
+ Copied raw (firstData pub) (activeLength p raw) original (after original (eventLog reports)) ∧
+ reports.length = activeLength p raw ∧ ∀ r ∈ reports, countProbes r.events ≤ 2 := by
+ apply LiveHeader.run_cursor_segment _ 19 _ 2 (fun n => Copied raw (firstData pub) n original) original
+ · exact ⟨fun _ hj => (Nat.not_lt_zero _ hj).elim, fun _ _ => rfl⟩
+ intro j hj m h
+ have hval : (j : Word w).val = j := Fin.val_cast_of_lt (by omega)
+ have hraw : j < raw.length := by unfold activeLength at hj; split at hj <;> omega
+ have hread := h.outside _ ((disjoint j hj).imp_right fun ha => by omega)
+ have hadd := fit
+ unfold firstData at hadd
+ have hOne : (1 : Word w).val = 1 := by simp [Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega : w ≠ 0))]
+ have haddr : (targetAddress pub (j : Word w)).val = firstData pub + j := by
+ unfold targetAddress firstData
+ have h₁ := word_add_val (pub 1) 1 (by rw [hOne]; omega)
+ have h₂ := word_add_val (pub 1 + 1) (pub 0) (by rw [h₁, hOne]; omega)
+ rw [word_add_val _ _ (by rw [h₂, h₁, hOne, hval]; omega), h₂, h₁, hOne, hval]
+ obtain ⟨es, he, hm, _, hp, _⟩ := copyBit_native hw pub width (j : Word w) m raw
+ (by rw [hval]; exact hraw) (by rw [hread, packed j hj, hval])
+ refine ⟨es, by simpa only [Nat.cast_add, Nat.cast_one] using he, ?_, hp.le⟩
+ rw [hm]
+ constructor
+ · intro i hi
+ by_cases hij : i = j
+ · subst i
+ simp [writeMemory, haddr, hval, List.getElem?_eq_getElem hraw]
+ · simp [writeMemory, haddr, hij, h.symbols i (by omega)]
+ · intro a ha
+ have hn : a ≠ firstData pub + j := by omega
+ simp [writeMemory, haddr, hn, h.outside a (by omega)]
+
+private theorem encodeBit_add_one (hw : 2 ≤ w) (b : Bool) :
+ (PrimedInputRAM.encodeBit w b + 1 : Word w).val = (bitSymbol b).val := by
+ have h4 : 4 ≤ 2 ^ w := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ cases b <;> simp [PrimedInputRAM.encodeBit, bitSymbol, Fin.val_add,
+ Nat.mod_eq_of_lt (by omega : 1 < 2 ^ w), Nat.mod_eq_of_lt (by omega : 2 < 2 ^ w)]
+
+private theorem tagWord_val (hw : 2 ≤ w) (tag : Word 2) : (Fin.ofNat (2 ^ w) tag.val).val = tag.val :=
+ (Fin.val_ofNat ..).trans (Nat.mod_eq_of_lt (tag.isLt.trans_le (Nat.pow_le_pow_right (by decide) hw)))
+
+/-- After the last burst the entire two-tape bank is the canonical initial
+code. The untouched left side, second tape, and right padding use zero-default
+memory. An empty program has only its state word. -/
+theorem copied_stores (hw : 2 ≤ w) (pub : Fin 4 → Word w) (p : Program)
+ (hs : p.extra + 2 ≤ 2 ^ w) (raw : UniversalMachine.Word) (blank m : Memory w)
+ (space : raw.length ≤ (pub 0).val + 1)
+ (zero : ∀ k : Fin (fieldWords (pub 0).val), blank ((pub 1).val + k.val) = 0)
+ (h : Copied raw (firstData pub) (activeLength p raw)
+ (writeMemory blank (pub 1) (Fin.ofNat _ (controlTag p).val)) m) :
+ Stores hw hs (pub 1).val m (LiveEvaluatorTail.initialCode (pub 0).val (UniversalMachine.initial p raw)) := by
+ intro k
+ apply Fin.ext
+ rcases field_cases k with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩
+ · rw [words_state, initial_state]
+ simp only [stateField, Nat.add_zero]
+ rw [h.outside _ (Or.inl (by dsimp [firstData]; omega))]
+ rw [writeMemory, ite_eq_left rfl, tagWord_val hw]
+ split <;> simp_all [controlTag]
+ · rw [words_first, initial_first]
+ let M := (pub 0).val
+ let addr := (pub 1).val + (firstField i).val
+ have ha : addr = (pub 1).val + (1 + i.val) := rfl
+ change (m addr).val = _
+ by_cases active : p.extra ≠ 0 ∧ M ≤ i.val ∧ i.val - M < raw.length
+ · obtain ⟨he, hi, hj⟩ := active
+ have eq : addr = firstData pub + (i.val - M) := by dsimp [firstData, M] at *; omega
+ rw [eq, h.symbols _ (by simpa [activeLength, he]), encodeBit_add_one hw, ite_eq_right he]
+ simp [inputCell, M, Nat.not_lt_of_ge hi, List.getElem?_eq_getElem hj]
+ · have outside : addr < firstData pub ∨ firstData pub + activeLength p raw ≤ addr := by
+ dsimp [firstData, activeLength, M] at *
+ split <;> omega
+ have ha' : addr ≠ (pub 1).val := by omega
+ rw [h.outside _ outside, writeMemory, ite_eq_right ha', zero (firstField i)]
+ by_cases he : p.extra = 0
+ · simp [he]
+ · by_cases hi : i.val < M
+ · simp [he, inputCell, hi, M] at *
+ · have hj : raw.length ≤ i.val - M := by omega
+ simp [he, inputCell, M, List.getElem?_eq_none (by exact hj)]
+ · rw [words_second, initial_second]
+ have hoff : firstData pub + activeLength p raw ≤ (pub 1).val + (secondField i).val := by
+ simp only [firstData, activeLength, secondField]
+ split <;> omega
+ have hne : (pub 1).val + (secondField i).val ≠ (pub 1).val := by dsimp [secondField]; omega
+ rw [h.outside _ (Or.inr hoff), writeMemory, ite_eq_right hne, zero (secondField i)]
+ rfl
+
+/-- At the last group the outgoing scratch bank is the accepting sentinel.
+Only one control word is written. There is no outgoing physical cut. -/
+theorem final_stores {extra M : ℕ} (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w)
+ (base : Word w) (blank : Memory w)
+ (zero : ∀ k : Fin (fieldWords M), blank (base.val + k.val) = 0) :
+ Stores hw hs base.val (writeMemory blank base 1) (.accepted : Code extra M) := by
+ intro k
+ apply Fin.ext
+ rcases field_cases k with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩
+ · rw [words_state]
+ simp [writeMemory, stateField, Code.stateWord,
+ Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega : w ≠ 0))]
+ · rw [words_first, writeMemory, ite_eq_right (by dsimp [firstField]; omega), zero (firstField i)]
+ rfl
+ · rw [words_second, writeMemory, ite_eq_right (by dsimp [secondField]; omega), zero (secondField i)]
+ rfl
+
+/-- The control-write call and all input-bit calls together prepare the actual
+initial evaluator bank. The packed input buffer must survive the control write
+and lie outside the writable tape interval. -/
+theorem prepare_native (hw : 2 ≤ w) (pub : Fin 4 → Word w) (width : (pub 3).val = w)
+ (p : Program) (hs : p.extra + 2 ≤ 2 ^ w) (raw : UniversalMachine.Word) (blank : Memory w)
+ (space : raw.length ≤ (pub 0).val + 1)
+ (fit : firstData pub + activeLength p raw ≤ 2 ^ w)
+ (zero : ∀ k : Fin (fieldWords (pub 0).val), blank ((pub 1).val + k.val) = 0)
+ (packed : ∀ j < activeLength p raw, blank (sourceAddress pub (j : Word w)).val = inputWord w raw (j / w))
+ (disjoint : ∀ j < activeLength p raw, let a := (sourceAddress pub (j : Word w)).val
+ a ≠ (pub 1).val ∧ (a < firstData pub ∨ firstData pub + activeLength p raw ≤ a)) :
+ let tag := controlTag p
+ let S := ((template (putState tag) 29).instantiate w pub).program
+ let P := ((template copyBit 29).instantiate w pub).program
+ ∃ es reports, execute S 5 (S.start 0) blank [] = some ⟨es, some 0⟩ ∧
+ runSegment P 19 (some 0) (after blank es) (List.replicate (activeLength p raw) []) = some reports ∧
+ endState (some 0) reports = some (activeLength p raw : Word w) ∧
+ Stores hw hs (pub 1).val (after (after blank es) (eventLog reports))
+ (LiveEvaluatorTail.initialCode (pub 0).val (UniversalMachine.initial p raw)) ∧
+ es.length = 4 ∧ countProbes es = 1 ∧ choiceBits es = [] ∧
+ reports.length = activeLength p raw ∧ ∀ r ∈ reports, countProbes r.events ≤ 2 := by
+ obtain ⟨es, he, hm, hel, hep, heb⟩ := putState_native pub 0 blank (controlTag p)
+ have saved (j : ℕ) (hj : j < activeLength p raw) : after blank es (sourceAddress pub (j : Word w)).val = inputWord w raw (j / w) := by
+ rw [hm, writeMemory, ite_eq_right (disjoint j hj).1, packed j hj]
+ obtain ⟨reports, hr, hend, hcopy, hlen, hprobes⟩ := copy_segment hw pub width p raw
+ (after blank es) fit saved (fun j hj => (disjoint j hj).2)
+ refine ⟨es, reports, he, hr, hend, ?_, hel, hep, heb, hlen, hprobes⟩
+ apply copied_stores hw pub p hs raw blank _ space zero
+ rw [hm] at hcopy ⊢
+ exact hcopy
+
+/-- The last tail group compares against a native-prepared canonical accept
+bank without receiving an outgoing cut from a nonexistent neighbor. -/
+theorem final_native {extra M : ℕ} (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w)
+ (pub : Fin 4 → Word w) (pos : Word w) (blank : Memory w)
+ (zero : ∀ k : Fin (fieldWords M), blank ((pub 1).val + k.val) = 0) :
+ let S := ((template (putState 1) 29).instantiate w pub).program
+ ∃ es, execute S 5 (S.start pos) blank [] = some ⟨es, some pos⟩ ∧
+ Stores hw hs (pub 1).val (after blank es) (.accepted : Code extra M) ∧
+ es.length = 4 ∧ countProbes es = 1 ∧ choiceBits es = [] := by
+ obtain ⟨es, he, hm, hl, hp, hb⟩ := putState_native pub pos blank 1
+ refine ⟨es, he, ?_, hl, hp, hb⟩
+ rw [hm]
+ exact final_stores hw hs (pub 1) blank zero
+
+end LiveEvaluatorInitialize
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorInputStages.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorInputStages.lean
new file mode 100644
index 0000000000..1e65e95e90
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorInputStages.lean
@@ -0,0 +1,178 @@
+import OAI.Computability.VPVNP.LiveEvaluatorReindexPrepare
+import OAI.Computability.VPVNP.LiveEvaluatorReindexSkeleton
+import OAI.Computability.VPVNP.LiveEvaluatorReindexSweep
+import OAI.Computability.VPVNP.LiveHeaderUnique
+
+/-!
+# Native preparation of the midpoint evaluator input
+
+The four stages write the control, copy the true advice prefix, generate
+the zero-exponent runtime field, and install the permuted exponent payloads.
+Their executions share ordinary external memory. The source banks are
+preserved throughout preparation, and the final bank contains exactly the
+tape machine's initial configuration on the advice and true exponents.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorInputStages
+
+open BurstRAM BurstRAM.PrivateRAM LiveEvaluatorInitialize LiveEvaluatorReindex
+open EvaluatorProgramRawInput
+open scoped Fin.CommRing
+
+variable {w d t Z : ℕ}
+
+/-- Public-word addresses and capacities for the two writes preceding the
+scatter. Only the occupied prefix of the advised stream is copied. -/
+structure Layout (cp sk sc : Fin 4 → Word w) (permPub : Fin 5 → Word w) (d t Z a : ℕ) : Prop where
+ controlBase : sc 1 = cp 1
+ wordWidth : (cp 3).val = w
+ prefixFit : firstData cp + a ≤ 2^w
+ packedSeparate : ∀ j < a, let x := (sourceAddress cp (j : Word w)).val
+ x ≠ (cp 1).val ∧ (x < firstData cp ∨ firstData cp+a ≤ x)
+ runtimeWidth : (sk 0).val = Z
+ runtimeBits : (sk 1).val = t*Z
+ runtimeBase : (sk 2).val = firstData cp + a
+ runtimeLength : (sk 3).val = 2*(t*Z)+6*Z+4
+ runtimeFit : (sk 2).val + (sk 3).val ≤ 2^w
+ scatter : LiveEvaluatorReindex.Layout permPub d t Z (cp 1).val (cp 0).val a
+ incomingSeparate : ∀ q : Fin (d*Z), let x := (permPub 0).val + q.val
+ x ≠ (cp 1).val ∧ (x < firstData cp ∨ firstData cp+a+(sk 3).val ≤ x)
+ mapSeparate : ∀ i : Fin d, let x := (permPub 1).val + i.val
+ x ≠ (cp 1).val ∧ (x < firstData cp ∨ firstData cp+a+(sk 3).val ≤ x)
+
+/-- Cost of all four midpoint stages before linked stage dispatch. -/
+def costBound (a runtimeLen count : ℕ) : ℕ :=
+ 2 + 3 * max 1 a + 2 * runtimeLen + 4 * max 1 count
+
+private theorem reportCost_le (rs : List (Report w)) (b : ℕ) (h : ∀ r ∈ rs, countProbes r.events ≤ b) :
+ RAMBuckets.cost Report.probes rs ≤ (1+b)*rs.length := by
+ induction rs with
+ | nil => simp [RAMBuckets.cost]
+ | cons r rs ih =>
+ have head := h r (by simp)
+ have tail := ih (fun r hr => h r (List.mem_cons_of_mem _ hr))
+ change 1+countProbes r.events+RAMBuckets.cost Report.probes rs ≤ (1+b)*(rs.length+1)
+ rw [Nat.mul_succ]
+ omega
+
+/-- Actual terminated RAM calls for the four phases, in their execution order. -/
+def Runs (cp sk sc : Fin 4 → Word w) (permPub : Fin 5 → Word w) (p : UniversalMachine.Program)
+ (a runtimeLen count : ℕ) (m₀ m₄ : Memory w) : Prop :=
+ let S := ((putStage (controlTag p)).instantiate w sc).program
+ let C := (copyStage.instantiate w (copyPublic cp (a : Word w))).program
+ let K := (LiveEvaluatorReindexSkeleton.skeletonStage.instantiate w sk).program
+ let R := (scatterPhase.instantiate w permPub).program
+ ∃ es cs ks rs,
+ let m₁ := after m₀ es
+ let m₂ := after m₁ (eventLog cs)
+ let m₃ := after m₂ (eventLog ks)
+ execute S 4 (S.start 0) m₀ [] = some ⟨es, none⟩ ∧
+ runSegment C 23 (some 0) m₁ (List.replicate (max 1 a) []) = some cs ∧ endState (some 0) cs = none ∧
+ runSegment K 28 (some 0) m₂ (List.replicate runtimeLen []) = some ks ∧ endState (some 0) ks = none ∧
+ runSegment R 27 (some 0) m₃ (List.replicate (max 1 count) []) = some rs ∧ endState (some 0) rs = none ∧
+ after m₃ (eventLog rs) = m₄ ∧
+ countProbes es = 1 ∧ (∀ r ∈ cs, countProbes r.events ≤ 2) ∧
+ (∀ r ∈ ks, countProbes r.events ≤ 1) ∧ (∀ r ∈ rs, countProbes r.events ≤ 3) ∧
+ RAMBuckets.cost Report.probes (⟨es, none⟩ :: (cs ++ ks ++ rs)) ≤ costBound a runtimeLen count
+
+/-- Given the physical packed advice bank and the incoming and order-advice
+buffers, the four fixed native stages produce the actual evaluator input. -/
+theorem run (hw : 2 ≤ w) (cp sk sc : Fin 4 → Word w) (permPub : Fin 5 → Word w)
+ (p : UniversalMachine.Program) (running : p.extra ≠ 0) (hs : p.extra+2 ≤ 2^w)
+ (perm : Fin d ≃ Fin t) (dense : Fin d → Word Z) (formal : Fin t → Word Z)
+ (order : ∀ i, formal (perm i) = dense i) (A : List Bool)
+ (L : Layout cp sk sc permPub d t Z A.length) (m₀ : Memory w)
+ (space : (A ++ runtime formal).length ≤ (cp 0).val+1)
+ (blank : ∀ k : Fin (LiveEvaluatorEncoding.fieldWords (cp 0).val), m₀ ((cp 1).val+k.val) = 0)
+ (packed : ∀ j < A.length, m₀ (sourceAddress cp (j : Word w)).val = inputWord w A (j/w))
+ (source : Sources permPub perm dense m₀) :
+ ∃ m₄, Runs cp sk sc permPub p A.length (2*(t*Z)+6*Z+4) (d*Z) m₀ m₄ ∧
+ Stores hw hs (cp 1).val m₄
+ (LiveEvaluatorTail.initialCode (cp 0).val (UniversalMachine.initial p (A ++ runtime formal))) := by
+ let es : List (Event w) := [.tick, .tick, .write (sc 1) (Fin.ofNat _ (controlTag p).val)]
+ let m₁ := after m₀ es
+ have hs₁ : m₁ = writeMemory m₀ (cp 1) (Fin.ofNat _ (controlTag p).val) := by
+ change writeMemory m₀ (sc 1) _ = _
+ rw [L.controlBase]
+ have hact : activeLength p A = A.length := ite_eq_right running
+ have saved (j : ℕ) (hj : j < A.length) :
+ m₁ (sourceAddress cp (j : Word w)).val = inputWord w A (j/w) := by
+ rw [hs₁, writeMemory, ite_eq_right (L.packedSeparate j hj).1, packed j hj]
+ obtain ⟨cs, hcs, hcend, hc, hcl, hcp⟩ := copyStage_sweep hw cp L.wordWidth p A m₁
+ (by simpa only [hact] using L.prefixFit) (by simpa only [hact] using saved)
+ (by simpa only [hact] using fun (j : ℕ) (hj : j < A.length) => (L.packedSeparate j hj).2)
+ rw [hact] at hcs hc hcl
+ let m₂ := after m₁ (eventLog cs)
+ let zeros := runtime (fun _ : Fin t => (0 : Word Z))
+ have hzeros : zeros.length = 2*(t*Z)+6*Z+4 := runtime_length _
+ obtain ⟨ks, hks, hkend, hk, hkl, hkp⟩ := LiveEvaluatorReindexSkeleton.skeletonStage_sweep hw sk m₂
+ L.runtimeWidth L.runtimeBits L.runtimeLength L.runtimeFit
+ change Copied zeros (sk 2).val zeros.length m₂ (after m₂ (eventLog ks)) at hk
+ rw [L.runtimeBase] at hk
+ let m₃ := after m₂ (eventLog ks)
+ have he₃ : ∀ x, x ≠ (cp 1).val → (x < firstData cp ∨ firstData cp+A.length+(sk 3).val ≤ x) → m₃ x = m₀ x := by
+ intro x hx ha
+ have copied := hc.append hk
+ change m₃ x = m₀ x
+ have hy := copied.outside x (by rw [List.length_append, hzeros]; rw [L.runtimeLength] at ha; omega)
+ exact hy.trans (by rw [hs₁, writeMemory, ite_eq_right hx])
+ have src₃ : Sources permPub perm dense m₃ := {
+ incoming := fun q => (he₃ _ (L.incomingSeparate q).1 (L.incomingSeparate q).2).trans (source.incoming q)
+ order := fun i => (congrArg Fin.val (he₃ _ (L.mapSeparate i).1 (L.mapSeparate i).2)).trans (source.order i) }
+ have prep := prefix_runtime_stores hw cp p running hs A m₀ m₂ m₃
+ (by simpa only [List.length_append, runtime_length] using space) blank (hs₁ ▸ hc)
+ (by simpa only [← hzeros] using hk)
+ obtain ⟨rs, hrs, hrend, store, hrl, hrp⟩ := sweep_native hw permPub perm dense formal order p running hs
+ A (cp 1).val (cp 0).val L.scatter m₃ src₃ space prep
+ refine ⟨_, ?_, store⟩
+ refine ⟨es, cs, ks, rs, execute_putStage _ _ _ _ _ 0, hcs, hcend,
+ by simpa only [runtime_length] using hks, hkend, hrs, hrend, rfl, rfl,
+ fun r hr => (hcp r hr).2.1, hkp, hrp, ?_⟩
+ have cpBound := reportCost_le cs 2 (fun r hr => (hcp r hr).2.1)
+ have skBound := reportCost_le ks 1 hkp
+ have scBound := reportCost_le rs 3 hrp
+ rw [hcl] at cpBound
+ rw [hkl, runtime_length] at skBound
+ rw [hrl] at scBound
+ change 1+1+RAMBuckets.cost Report.probes (cs ++ ks ++ rs) ≤ _
+ simp only [RAMBuckets.cost_append, costBound]
+ omega
+
+/-- Every accepting execution of these four stages uses the indicated empty
+branch streams. In particular the preparation cannot multiply path counts. -/
+theorem Runs.forces {cp sk sc : Fin 4 → Word w} {permPub : Fin 5 → Word w} {p : UniversalMachine.Program}
+ {a runtimeLen count : ℕ} {m₀ m₄ : Memory w} (h : Runs cp sk sc permPub p a runtimeLen count m₀ m₄)
+ (stateBits : List Bool) (copyBits runtimeBits scatterBits : List (List Bool))
+ (es : List (Event w)) (cs ks rs : List (Report w))
+ (stateRun : let S := ((putStage (controlTag p)).instantiate w sc).program
+ execute S 4 (S.start 0) m₀ stateBits = some ⟨es, none⟩)
+ (copyRun : let P := (copyStage.instantiate w (copyPublic cp (a : Word w))).program
+ runSegment P 23 (some 0) (after m₀ es) copyBits = some cs)
+ (copyEnd : endState (some 0) cs = none)
+ (runtimeRun : let P := (LiveEvaluatorReindexSkeleton.skeletonStage.instantiate w sk).program
+ runSegment P 28 (some 0) (after (after m₀ es) (eventLog cs)) runtimeBits = some ks)
+ (runtimeEnd : endState (some 0) ks = none)
+ (scatterRun : let P := (scatterPhase.instantiate w permPub).program
+ runSegment P 27 (some 0) (after (after (after m₀ es) (eventLog cs)) (eventLog ks)) scatterBits = some rs)
+ (scatterEnd : endState (some 0) rs = none) :
+ stateBits = [] ∧ copyBits = List.replicate (max 1 a) [] ∧ runtimeBits = List.replicate runtimeLen [] ∧
+ scatterBits = List.replicate (max 1 count) [] ∧
+ after (after (after (after m₀ es) (eventLog cs)) (eventLog ks)) (eventLog rs) = m₄ := by
+ obtain ⟨es₀, cs₀, ks₀, rs₀, he, hc, hce, hk, hke, hr, hre, hafter, _⟩ := h
+ obtain ⟨sb, hreport⟩ := execute_empty_forces he stateRun
+ have heq : es = es₀ := congrArg Report.events hreport
+ subst es
+ obtain ⟨cb, rfl⟩ := accepted_empty_unique hc hce copyRun copyEnd
+ obtain ⟨kb, rfl⟩ := accepted_empty_unique hk hke runtimeRun runtimeEnd
+ obtain ⟨rb, rfl⟩ := accepted_empty_unique hr hre scatterRun scatterEnd
+ exact ⟨sb, cb, kb, rb, hafter⟩
+
+end LiveEvaluatorInputStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorNativeGroup.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorNativeGroup.lean
new file mode 100644
index 0000000000..ce003f2b4e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorNativeGroup.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.LiveEvaluatorGroup
+import OAI.Computability.VPVNP.LiveEvaluatorRAMSegment
+import OAI.Computability.VPVNP.LiveGroupContraction
+
+/-!
+# Path counts of the literal scheduled tail-group program
+
+A complete native RAM segment includes the preparing call, each cell call
+on both tapes, and the final acceptance of the cursor. Its accepting paths
+on the two decoded cut configurations have exactly the local multiplicity
+used in the live chain contraction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorGroup
+
+open BurstRAM (Word Memory ActualPaths)
+open UniversalMachine (Program)
+open LiveEvaluatorEncoding (Code)
+open LiveEvaluatorRAM (ConfigAt PrepLayout)
+open LiveEvaluatorRAM.Schedule (Pub nativeProgram callFuel actualPathEquiv)
+open LiveEvaluatorStep (nextCode)
+open scoped Classical
+
+variable {M w : ℕ} {p : Program} {pub : Pub → Word w} {m : Memory w} {old out : Code p.extra M}
+
+/-- Every successful native RAM path has one semantic branch choice and
+conversely. Deterministic calls use the empty choice stream. -/
+noncomputable def nativeGroupEquiv (hl : PrepLayout p pub M)
+ (ho : ConfigAt m (pub 1) old) (hz : ConfigAt m (pub 2) out) :
+ ActualPaths (nativeProgram p pub) (callFuel p) 0 m (fun _ => True) ≃
+ {bit : Bool // nextCode p old bit = some out ∧ out ≠ .rejected} :=
+ (actualPathEquiv p pub m hl.radius (calls_fit hl).le).trans (streamEquiv hl ho hz).symm
+
+theorem card_nativeGroup (hl : PrepLayout p pub M)
+ (ho : ConfigAt m (pub 1) old) (hz : ConfigAt m (pub 2) out) :
+ Nat.card (ActualPaths (nativeProgram p pub) (callFuel p) 0 m (fun _ => True)) =
+ ∑ bit : Bool, if nextCode p old bit = some out ∧ out ≠ .rejected then 1 else 0 := by
+ rw [Nat.card_congr (nativeGroupEquiv hl ho hz), Nat.card_eq_fintype_card, Fintype.card_subtype,
+ Finset.sum_boole]
+ simp
+
+/-- For any two successfully decoded boundaries of a tail group, its factor
+in the contraction is the number of accepted segments of the compiled table. -/
+theorem tailCount_eq_native {h Δ : ℕ} (layout : LiveEvaluatorTail.Layout p.extra M w Δ)
+ (init : Code p.extra M) (bits : LiveChain.TailBits h Δ) (i : Fin (2 ^ h))
+ (ha : LiveEvaluatorTail.boundary layout init bits i.castSucc = some old)
+ (hb : LiveEvaluatorTail.boundary layout init bits i.succ = some out)
+ (hl : PrepLayout p pub M) (ho : ConfigAt m (pub 1) old) (hz : ConfigAt m (pub 2) out) :
+ ChainAssignments.tailCount p layout init bits i =
+ Nat.card (ActualPaths (nativeProgram p pub) (callFuel p) 0 m (fun _ => True)) := by
+ rw [card_nativeGroup hl ho hz]
+ simp [ChainAssignments.tailCount, ha, hb]
+
+end LiveEvaluatorGroup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAM.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAM.lean
new file mode 100644
index 0000000000..f96a6a9c67
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAM.lean
@@ -0,0 +1,257 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Checking one tape cell of a live evaluator transition
+
+Each scheduled cell call reads one old symbol and one proposed new symbol.
+The head-relative window is shifted cyclically at its endpoints. At a clipped
+endpoint, the overwritten old symbol must be blank and the newly exposed
+cell is checked against that blank. Thus every input and every output cell
+is examined, including when the radius is zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+
+/-- The register indices of the 32-register native evaluator transition checker. -/
+abbrev Reg := Fin 32
+/-- Native transition-checking code over 32 registers and a parameterized public operand bank. -/
+abbrev Code (k : ℕ) := Flow 32 k
+
+variable {w k : ℕ}
+
+/-- Can this fragment reach its normal exit with the stated postcondition? -/
+def exits (pub : Fin k → Word w) (state : Word w) (a : Code k)
+ (rs : Regs w 32) (m : Memory w) (post : Regs w 32 → Memory w → Prop) :=
+ ∃ es out mem, Flow.Exec pub state a rs m es out mem ∧ post out mem
+
+theorem exits_seq (pub : Fin k → Word w) (state : Word w) (a b : Code k)
+ (rs : Regs w 32) (m : Memory w) (post : Regs w 32 → Memory w → Prop) :
+ exits pub state (.seq a b) rs m post ↔
+ exits pub state a rs m (fun r u => exits pub state b r u post) := by
+ constructor
+ · rintro ⟨_, _, _, h, hp⟩
+ cases h with
+ | seq ha hb => exact ⟨_, _, _, ha, _, _, _, hb, hp⟩
+ · rintro ⟨_, _, _, ha, _, _, _, hb, hp⟩
+ exact ⟨_, _, _, .seq ha hb, hp⟩
+
+theorem exits_line (pub : Fin k → Word w) (state : Word w) (op : Op 32 k)
+ (rs : Regs w 32) (m : Memory w) (post : Regs w 32 → Memory w → Prop) :
+ exits pub state (.line op) rs m post ↔
+ ∃ e out mem, op.effect pub state rs m = some (e, out, mem) ∧ post out mem := by
+ constructor
+ · rintro ⟨_, _, _, h, hp⟩
+ cases h with | line he => exact ⟨_, _, _, he, hp⟩
+ · rintro ⟨_, _, _, h, hp⟩
+ exact ⟨_, _, _, .line h, hp⟩
+
+theorem exits_ifEq (pub : Fin k → Word w) (state : Word w) (i j : Reg) (a b : Code k)
+ (rs : Regs w 32) (m : Memory w) (post : Regs w 32 → Memory w → Prop) :
+ exits pub state (.ifEq i j a b) rs m post ↔
+ if rs i = rs j then exits pub state a rs m post else exits pub state b rs m post := by
+ constructor
+ · rintro ⟨_, _, _, h, hp⟩
+ cases h with
+ | ifEqYes ht hb => exact (ite_eq_left ht).symm ▸ ⟨_, _, _, hb, hp⟩
+ | ifEqNo ht hb => exact (ite_eq_right ht).symm ▸ ⟨_, _, _, hb, hp⟩
+ · split
+ · rename_i h
+ rintro ⟨_, _, _, ha, hp⟩
+ exact ⟨_, _, _, .ifEqYes h ha, hp⟩
+ · rename_i h
+ rintro ⟨_, _, _, hb, hp⟩
+ exact ⟨_, _, _, .ifEqNo h hb, hp⟩
+
+private def line (op : Op 32 k) : Code k := .line op
+
+private def add (dst x y : Reg) : Code k := line (.binary .add dst x y)
+
+private def guardEq (x y : Reg) : Code k := line (.guardEq x y)
+
+private def fetch (dst base idx : Reg) : Code k :=
+ .seq (add 20 base idx) (line (.read dst 20))
+
+/-- Compare the symbol at an output index to a specified register. -/
+private def compareCell (idx expect : Reg) : Code k :=
+ .seq (fetch 21 15 idx) (guardEq 21 expect)
+
+/-- For a running target the old cell either maps to an adjacent output cell,
+or leaves the window and pairs with the newly exposed blank. -/
+private def moved (expect : Reg) : Code k :=
+ .ifEq 7 0 (compareCell 13 expect)
+ (.ifEq 7 1
+ (.ifEq 13 12 (.seq (guardEq expect 0) (compareCell 0 expect))
+ (.seq (add 19 13 1) (compareCell 19 expect)))
+ (.ifEq 13 0 (.seq (guardEq expect 0) (compareCell 12 expect))
+ (.seq (line (.binary .sub 19 13 1)) (compareCell 19 expect))))
+
+/-- Registers 0–3 contain their literal values, 5 is the target state, 6 and
+7 are this tape's write symbol and move, 11 and 12 are the radius and last
+cell, 13 is the old cell index, 14 and 15 are the old and new tape-field base
+addresses, and 16 is the source state. Scratch registers are 17 and 19–21. -/
+def cell : Code k :=
+ .seq (fetch 17 14 13) (.seq
+ (.ifEq 16 1 (guardEq 17 0) (line (.guardLt 17 3)))
+ (.ifEq 5 1 (compareCell 13 0)
+ (.ifEq 13 11 (moved 6) (moved 17))))
+
+private theorem exits_add (pub : Fin k → Word w) (state : Word w) (dst x y : Reg)
+ (rs : Regs w 32) (m : Memory w) (post : Regs w 32 → Memory w → Prop) :
+ exits pub state (add dst x y) rs m post ↔ post (Function.update rs dst (rs x + rs y)) m := by
+ simp [add, line, exits_line, Op.effect, BinaryOp.eval]
+
+private theorem exits_guardEq (pub : Fin k → Word w) (state : Word w) (x y : Reg)
+ (rs : Regs w 32) (m : Memory w) (post : Regs w 32 → Memory w → Prop) :
+ exits pub state (guardEq x y) rs m post ↔ rs x = rs y ∧ post rs m := by
+ simp [guardEq, line, exits_line, Op.effect]
+
+private theorem exits_fetch (pub : Fin k → Word w) (state : Word w) (dst base idx : Reg)
+ (rs : Regs w 32) (m : Memory w) (post : Regs w 32 → Memory w → Prop) :
+ exits pub state (fetch dst base idx) rs m post ↔
+ post (Function.update (Function.update rs 20 (rs base + rs idx)) dst
+ (m (rs base + rs idx).val)) m := by
+ simp [fetch, exits_seq, exits_add, line, exits_line, Op.effect]
+
+private theorem exits_compare (pub : Fin k → Word w) (state : Word w) (idx expect : Reg)
+ (he : expect ≠ 20) (hf : expect ≠ 21) (rs : Regs w 32) (m : Memory w) :
+ exits pub state (compareCell idx expect) rs m (fun _ _ => True) ↔
+ m (rs 15 + rs idx).val = rs expect := by
+ simp [compareCell, exits_seq, exits_fetch, exits_guardEq, Function.update_of_ne, he, hf]
+
+/-- Destination of an old cell in head-relative word coordinates, with the
+clipped endpoint paired to the newly exposed opposite endpoint. -/
+def destination (zero one last move i : Word w) : Word w :=
+ if move = zero then i
+ else if move = one then (if i = last then zero else i + one)
+ else if i = zero then last else i - one
+
+/-- Whether the written old symbol would move outside the window. -/
+def clipped (zero one last move i : Word w) : Prop :=
+ move ≠ zero ∧ (if move = one then i = last else i = zero)
+
+private theorem exits_moved (pub : Fin k → Word w) (state : Word w) (expect : Reg)
+ (he : expect ≠ 19) (hf : expect ≠ 20) (hg : expect ≠ 21) (rs : Regs w 32) (m : Memory w) :
+ exits pub state (moved expect) rs m (fun _ _ => True) ↔
+ (clipped (rs 0) (rs 1) (rs 12) (rs 7) (rs 13) → rs expect = rs 0) ∧
+ m (rs 15 + destination (rs 0) (rs 1) (rs 12) (rs 7) (rs 13)).val = rs expect := by
+ simp only [moved, exits_ifEq, exits_seq, exits_add, exits_guardEq, exits_compare _ _ _ _ hf hg,
+ destination, clipped]
+ split_ifs <;> simp_all (config := { decide := true }) [line, exits_line, Op.effect, BinaryOp.eval,
+ Function.update_of_ne]
+
+/-- Local condition on the two addressed memory words. The first condition
+validates the source symbol, even if the transition overwrites it. A halting
+target has zero in every cell. -/
+def cellTest (rs : Regs w 32) (m : Memory w) : Prop :=
+ let old := m (rs 14 + rs 13).val
+ (if rs 16 = rs 1 then old = rs 0 else old < rs 3) ∧
+ if rs 5 = rs 1 then m (rs 15 + rs 13).val = rs 0 else
+ let written := if rs 13 = rs 11 then rs 6 else old
+ (clipped (rs 0) (rs 1) (rs 12) (rs 7) (rs 13) → written = rs 0) ∧
+ m (rs 15 + destination (rs 0) (rs 1) (rs 12) (rs 7) (rs 13)).val = written
+
+/-- Successful execution of the fixed cell code is equivalent to checking
+the source, the clipped boundary and the proposed output symbol. -/
+theorem cell_exec_iff (pub : Fin k → Word w) (state : Word w) (rs : Regs w 32) (m : Memory w) :
+ (∃ es out mem, Flow.Exec pub state cell rs m es out mem) ↔ cellTest rs m := by
+ have h : (∃ es out mem, Flow.Exec pub state cell rs m es out mem) ↔
+ exits pub state cell rs m (fun _ _ => True) := by simp [exits]
+ rw [h]
+ simp (config := { decide := true }) only [cell, exits_seq, exits_fetch, exits_ifEq, exits_guardEq,
+ exits_compare, exits_moved, cellTest, Function.update_self]
+ split_ifs <;> simp_all (config := { decide := true }) [line, exits_line, Op.effect]
+
+/-- Certify a fixed read count for acyclic code with neither writes nor
+choices. Both continuations of a comparison must have the same read count. -/
+private def reads : Code k → Option ℕ
+ | .line (.read ..) => some 1
+ | .line (.write ..) => none
+ | .line _ => some 0
+ | .seq a b => Option.map₂ (· + ·) (reads a) (reads b)
+ | .ifEq _ _ a b | .ifLt _ _ a b => if reads a = reads b then reads a else none
+ | .branch .. | .whileLt .. => none
+
+private theorem probes_append (a b : List (Event w)) :
+ countProbes (a ++ b) = countProbes a + countProbes b := by
+ induction a with
+ | nil => simp [countProbes]
+ | cons e a ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+private theorem reads_line {pub : Fin k → Word w} {st : Word w} {rs : Regs w 32} {m : Memory w}
+ {op : Op 32 k} {e out mem n} (h : op.effect pub st rs m = some (e, out, mem))
+ (hr : reads (.line op) = some n) :
+ mem = m ∧ choiceBits [e] = [] ∧ countProbes [e] = n := by
+ cases op <;> simp_all [Op.effect, reads]
+ all_goals subst n
+ all_goals rcases h with ⟨_, rfl, rfl, rfl⟩
+ all_goals try subst e
+ all_goals constructor <;> rfl
+
+private theorem reads_sound {pub : Fin k → Word w} {st : Word w} {a : Code k} {rs m es out mem}
+ (run : Flow.Exec pub st a rs m es out mem) {n} (h : reads a = some n) :
+ mem = m ∧ choiceBits es = [] ∧ countProbes es = n ∧ es.length ≤ a.length := by
+ induction run generalizing n with
+ | line he =>
+ obtain ⟨hm, hb, hc⟩ := reads_line he h
+ exact ⟨hm, hb, hc, le_rfl⟩
+ | seq _ _ ih₁ ih₂ =>
+ simp only [reads, Option.map₂_eq_some_iff] at h
+ obtain ⟨i, j, hi, hj, rfl⟩ := h
+ obtain ⟨rfl, hb, hc, hl⟩ := ih₁ hi
+ obtain ⟨rfl, hb', hc', hl'⟩ := ih₂ hj
+ simp [Flow.choiceBits_append, probes_append, hb, hb', hc, hc', Flow.length, Nat.add_le_add hl hl']
+ | ifEqYes _ _ ih | ifLtYes _ _ ih | ifEqNo _ _ ih | ifLtNo _ _ ih =>
+ simp only [reads] at h
+ split at h
+ next eq =>
+ obtain ⟨rfl, hb, hc, hl⟩ := ih (by first | exact h | exact eq ▸ h)
+ simp [choiceBits, countProbes, hb, hc, Flow.length]; omega
+ next => contradiction
+ | branchYes | branchNo | whileDone | whileStep => contradiction
+
+/-- Each successful cell check makes exactly two read probes, consumes no
+choice bit and leaves the external memory unchanged. -/
+theorem cell_cost {pub : Fin k → Word w} {st : Word w} {rs m es out mem}
+ (run : Flow.Exec pub st cell rs m es out mem) :
+ mem = m ∧ choiceBits es = [] ∧ countProbes es = 2 ∧ es.length ≤ (cell : Code k).length :=
+ reads_sound run rfl
+
+/-- Loop-free fragments have a fixed maximum instruction count across
+all branch choices, independent of word width and tape radius. -/
+def loopFree {r k : ℕ} : Flow r k → Bool
+ | .line _ => true
+ | .seq a b | .ifEq _ _ a b | .ifLt _ _ a b | .branch a b => loopFree a && loopFree b
+ | .whileLt .. => false
+
+theorem length_le_of_loopFree {r k : ℕ} {a : Flow r k} {pub : Fin k → Word w} {st : Word w}
+ {rs m es out mem} (run : Flow.Exec pub st a rs m es out mem) (h : loopFree a = true) :
+ es.length ≤ a.length := by
+ induction run with
+ | line => exact le_rfl
+ | seq _ _ ih₁ ih₂ =>
+ simp only [loopFree, Bool.and_eq_true] at h
+ simpa only [List.length_append, Flow.length] using Nat.add_le_add (ih₁ h.1) (ih₂ h.2)
+ | ifEqYes _ _ ih | ifLtYes _ _ ih | branchYes _ ih =>
+ simp only [loopFree, Bool.and_eq_true] at h
+ have hl := ih h.1
+ simp only [List.length_cons, Flow.length]; omega
+ | ifEqNo _ _ ih | ifLtNo _ _ ih | branchNo _ ih =>
+ simp only [loopFree, Bool.and_eq_true] at h
+ have hl := ih h.2
+ simp only [List.length_cons, Flow.length]; omega
+ | whileDone | whileStep => contradiction
+
+theorem cell_loopFree : loopFree (cell : Code k) = true := rfl
+
+end LiveEvaluatorRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMCell.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMCell.lean
new file mode 100644
index 0000000000..575d020d78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMCell.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAM
+import OAI.Computability.VPVNP.LiveEvaluatorCellEquivalence
+
+/-!
+# Word-level correctness of the finite evaluator tape scan
+
+The source-indexed tests in the fixed private-RAM template read the old
+symbol and its paired destination in memory. Reading all these pairs
+checks the full unbounded evaluator tape transition.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM
+
+open BurstRAM PrimedInputRAM PrimedStackRAM UniversalMachine LiveEvaluatorEncoding LiveEvaluatorStep
+open scoped Fin.CommRing
+
+variable {w k M : ℕ}
+
+/-- The numeric fields of one call and its two memory slices. Each bit-field
+word has already been unpacked at its agreed memory address. -/
+structure TapeCellData (rs : Regs w 32) (m : Memory w) (old out : TapeWindow M)
+ (write move : Symbol) (i : WindowCell M) : Prop where
+ zero : (rs 0).val = 0
+ one : (rs 1).val = 1
+ three : (rs 3).val = 3
+ writeVal : (rs 6).val = write.val
+ moveVal : (rs 7).val = move.val
+ center : (rs 11).val = M
+ last : (rs 12).val = 2 * M
+ index : (rs 13).val = i.val
+ oldCell : (m (rs 14 + rs 13).val).val = (old.cells i).val
+ outCell : ∀ (j : BurstRAM.Word w) (f : WindowCell M), j.val = f.val →
+ (m (rs 15 + j).val).val = (out.cells f).val
+
+theorem destination_val_of_limbs (z o last mw idx : Word w) (move : Symbol) (i : WindowCell M)
+ (hz₀ : z.val = 0) (h₁ : o.val = 1) (hmax : last.val = 2 * M)
+ (hm : mw.val = move.val) (hi₀ : idx.val = i.val) :
+ (destination z o last mw idx).val = (cellDestination move i).val := by
+ have hz : mw = z ↔ move = 0 := by simp only [Fin.ext_iff, hm, hz₀, Fin.val_zero]
+ have ho : mw = o ↔ move = 1 := by simp only [Fin.ext_iff, hm, h₁]; rfl
+ have hl : idx = last ↔ i.val = 2 * M := by simp only [Fin.ext_iff, hi₀, hmax]
+ have hi : idx = z ↔ i.val = 0 := by simp only [Fin.ext_iff, hi₀, hz₀]
+ simp only [destination, cellDestination, hz, ho, hl, hi]
+ split_ifs <;> try first | exact hi₀ | exact hz₀ | exact hmax
+ · rw [Fin.val_add_eq_of_add_lt, hi₀, h₁]
+ have := (last).isLt
+ rw [hmax] at this
+ rw [hi₀, h₁]
+ omega
+ · rw [Fin.sub_val_of_le, hi₀, h₁]
+ change (o).val ≤ (idx).val
+ rw [hi₀, h₁]
+ omega
+
+private theorem destination_val (rs : Regs w 32) (m : Memory w) (old out : TapeWindow M)
+ (write move : Symbol) (i : WindowCell M) (h : TapeCellData rs m old out write move i) :
+ (destination (rs 0) (rs 1) (rs 12) (rs 7) (rs 13)).val = (cellDestination move i).val :=
+ destination_val_of_limbs _ _ _ _ _ _ _ h.zero h.one h.last h.moveVal h.index
+
+private theorem clipped_iff (rs : Regs w 32) (m : Memory w) (old out : TapeWindow M)
+ (write move : Symbol) (i : WindowCell M) (h : TapeCellData rs m old out write move i) :
+ clipped (rs 0) (rs 1) (rs 12) (rs 7) (rs 13) ↔ cellClipped move i := by
+ simp only [clipped, cellClipped, ne_eq, Fin.ext_iff, h.zero, h.one, h.last, h.moveVal, h.index, Fin.val_zero]; rfl
+
+theorem cellTest_running_iff {rs : Regs w 32} {m : Memory w} {old out : TapeWindow M}
+ {write move : Symbol} {i : WindowCell M} (h : TapeCellData rs m old out write move i)
+ (hs : rs 16 ≠ rs 1) (ht : rs 5 ≠ rs 1) :
+ cellTest rs m ↔ (cellClipped move i → writtenSymbol old write i = 0) ∧
+ out.cells (cellDestination move i) = writtenSymbol old write i := by
+ have hlt : m (rs 14 + rs 13).val < rs 3 := by
+ change (m (rs 14 + rs 13).val).val < (rs 3).val
+ rw [h.oldCell, h.three]
+ exact (old.cells i).isLt
+ have hc : rs 13 = rs 11 ↔ i.val = M := by simp [Fin.ext_iff, h.index, h.center]
+ have hd := h.outCell _ _ (destination_val _ _ _ _ _ _ _ h)
+ simp only [cellTest, ite_eq_right hs, ite_eq_right ht, hlt, true_and]
+ simp only [clipped_iff _ _ _ _ _ _ _ h, writtenSymbol, hc]
+ split_ifs <;> simp only [Fin.ext_iff, h.zero, h.writeVal, h.oldCell, hd, Fin.val_zero]
+
+/-- Each native fragment exits precisely on a matching symbol pair. All
+fragments together check both endpoints and every proposed tape cell. -/
+theorem tapeScan_exec_iff (pub : Fin k → BurstRAM.Word w) (state : BurstRAM.Word w)
+ (m : Memory w) (old out : TapeWindow M) (write move : Symbol) (rs : WindowCell M → Regs w 32)
+ (h : ∀ i, TapeCellData (rs i) m old out write move i)
+ (hs : ∀ i, rs i 16 ≠ rs i 1) (ht : ∀ i, rs i 5 ≠ rs i 1) :
+ (∀ i, ∃ es regs mem, Flow.Exec pub state cell (rs i) m es regs mem) ↔
+ boundaryBlank old write move = true ∧ out = updatedWindow old write move := by
+ rw [← cellChecks_iff]
+ exact forall_congr' fun i => (cell_exec_iff ..).trans (cellTest_running_iff (h i) (hs i) (ht i))
+
+end LiveEvaluatorRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMDispatch.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMDispatch.lean
new file mode 100644
index 0000000000..3235274d50
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMDispatch.lean
@@ -0,0 +1,394 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete
+import OAI.Computability.VPVNP.LiveEvaluatorRAM
+import OAI.Computability.VPVNP.VerifierMachineSimulation
+
+/-!
+# The evaluator's fixed row dispatch in a live group
+
+The evaluator program is fixed, so its finite row table is part of the
+control graph. Register 4 contains the zero-based row number. Each skipped
+row costs a test and a decrement. Only two-slot rows execute a choice, with
+false selecting the first slot and true selecting the second. A zero-slot
+row or an out-of-range row jumps to the rejecting exit.
+
+Registers 5–9 receive the five fields of the chosen instruction. The target
+state is assembled from zero and unit increments. Each tape symbol and move
+is a single two-bit literal. Consequently the instruction text is fixed
+independently of the word width and live window size.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAMDispatch
+
+open BurstRAM (Word Memory Event choiceBits)
+open BurstRAM.PrivateRAM (BinaryOp)
+open PrimedInputRAM (Flow)
+open PrimedStackRAM (Op Regs)
+open UniversalMachine (Program Instruction Branches Symbol chosenInstruction)
+
+variable {w k extra : ℕ}
+
+/-- The four bounded tape fields fit directly in the RAM's literal format. -/
+private def literal (v : Symbol) : Word 2 := ⟨v.val, by have := v.isLt; omega⟩
+
+/-- Load a fixed natural number into register 5 using only zero and unit increments. -/
+def targetFlow : ℕ → Flow 32 k
+ | 0 => .line (.constant 5 0)
+ | n + 1 => .seq (targetFlow n) (.line (.binary .add 5 5 1))
+
+private def record (a : Instruction extra) : Flow 32 k :=
+ .seq (targetFlow a.target.val) <|
+ .seq (.line (.constant 6 (literal a.firstSymbol))) <|
+ .seq (.line (.constant 7 (literal a.firstMove))) <|
+ .seq (.line (.constant 8 (literal a.secondSymbol)))
+ (.line (.constant 9 (literal a.secondMove)))
+
+private def reject : Flow 32 k := .line (.guardLt 0 0)
+
+private def rowFlow : Branches extra → Flow 32 k
+ | .stop => reject
+ | .one a => record a
+ | .two a b => .branch (record b) (record a)
+
+private def scan : List (Branches extra) → Flow 32 k
+ | [] => reject
+ | b :: bs => .ifEq 4 0 (rowFlow b) (.seq (.line (.binary .sub 4 4 1)) (scan bs))
+
+/-- The native structured flow compiled from a fixed coefficient machine. -/
+def dispatch (p : Program) : Flow 32 k := scan p.rows
+
+/-- Registers after writing the instruction's five fields. -/
+def instructionRegs (rs : Regs w 32) (a : Instruction extra) : Regs w 32 :=
+ let s := Function.update rs 5 (Fin.ofNat (2^w) a.target.val)
+ let s := Function.update s 6 (Fin.ofNat (2^w) a.firstSymbol.val)
+ let s := Function.update s 7 (Fin.ofNat (2^w) a.firstMove.val)
+ let s := Function.update s 8 (Fin.ofNat (2^w) a.secondSymbol.val)
+ Function.update s 9 (Fin.ofNat (2^w) a.secondMove.val)
+
+theorem instructionRegs_fields (rs : Regs w 32) (a : Instruction extra)
+ (hw : 2 ≤ w) (ht : extra + 2 ≤ 2 ^ w) :
+ ((instructionRegs rs a) 5).val = a.target.val ∧
+ ((instructionRegs rs a) 6).val = a.firstSymbol.val ∧
+ ((instructionRegs rs a) 7).val = a.firstMove.val ∧
+ ((instructionRegs rs a) 8).val = a.secondSymbol.val ∧
+ ((instructionRegs rs a) 9).val = a.secondMove.val := by
+ have h4 : 4 ≤ 2 ^ w := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ simp (config := {decide := true}) [instructionRegs, Function.update, Fin.ofNat,
+ Nat.mod_eq_of_lt (a.target.isLt.trans_le ht),
+ Nat.mod_eq_of_lt (a.firstSymbol.isLt.trans_le (by omega : 3 ≤ 2 ^ w)),
+ Nat.mod_eq_of_lt (a.firstMove.isLt.trans_le (by omega : 3 ≤ 2 ^ w)),
+ Nat.mod_eq_of_lt (a.secondSymbol.isLt.trans_le (by omega : 3 ≤ 2 ^ w)),
+ Nat.mod_eq_of_lt (a.secondMove.isLt.trans_le (by omega : 3 ≤ 2 ^ w))]
+
+theorem instructionRegs_other (rs : Regs w 32) (a : Instruction extra) (j : Fin 32)
+ (hj : j.val < 5 ∨ 9 < j.val) : instructionRegs rs a j = rs j := by
+ simp only [instructionRegs]
+ repeat rw [Function.update_of_ne (by intro he; subst j; exact (by decide : ¬ _) hj)]
+
+/-- Nondeterministic input consumed by a successful dispatch. -/
+def dispatchBits (b : Branches extra) (bit : Bool) : List Bool :=
+ match b with
+ | .two .. => [bit]
+ | _ => []
+
+/-- The consumed RAM bit list uniquely identifies every occupied slot in a given row.
+In particular the two copies of a repeated instruction have different encodings. -/
+theorem dispatchBits_injective {b : Branches extra} {x y : Bool} {a c : Instruction extra}
+ (hx : chosenInstruction b x = some a) (hy : chosenInstruction b y = some c)
+ (he : dispatchBits b x = dispatchBits b y) : x = y := by
+ cases b <;> cases x <;> cases y <;> simp_all [chosenInstruction, dispatchBits]
+
+/-- A trace of the specified number of local instruction steps in the fixed evaluator row
+dispatch. -/
+def ticks (n : ℕ) : List (Event w) := List.replicate n .tick
+
+private def rowEvents (b : Branches extra) (bit : Bool) (a : Instruction extra) : List (Event w) :=
+ let es := ticks (a.target.val + 5)
+ match b with
+ | .two .. => .choice bit :: es
+ | _ => es
+
+/-- The exact native trace, including each countdown operation and target increment. -/
+def dispatchEvents (i : ℕ) (b : Branches extra) (bit : Bool) (a : Instruction extra) :
+ List (Event w) :=
+ ticks (2*i+1) ++ rowEvents b bit a
+
+theorem choiceBits_ticks (n : ℕ) : choiceBits (ticks (w := w) n) = [] := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa [ticks, List.replicate_succ, choiceBits] using ih
+
+theorem dispatchEvents_bits (i : ℕ) (b : Branches extra) (bit : Bool) (a : Instruction extra) :
+ choiceBits (dispatchEvents (w := w) i b bit a) = dispatchBits b bit := by
+ cases b <;> simp [dispatchEvents, Flow.choiceBits_append, rowEvents, dispatchBits,
+ choiceBits, choiceBits_ticks]
+
+theorem dispatchEvents_length (i : ℕ) (b : Branches extra) (bit : Bool) (a : Instruction extra) :
+ (dispatchEvents (w := w) i b bit a).length =
+ 2*i + 1 + (dispatchBits b bit).length + a.target.val + 5 := by
+ cases b <;> simp [dispatchEvents, dispatchBits, rowEvents, ticks] <;> omega
+
+theorem target_exec (pub : Fin k → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (h1 : rs 1 = 1) (n : ℕ) :
+ Flow.Exec pub state (targetFlow n) rs m (ticks (n+1)) (Function.update rs 5 (Fin.ofNat (2^w) n)) m := by
+ induction n with
+ | zero => exact .line rfl
+ | succ n ih =>
+ have hadd : Fin.ofNat (2^w) n + 1 = Fin.ofNat (2^w) (n+1) := by
+ apply Fin.ext
+ exact (Nat.add_mod ..).symm
+ have hl : Flow.Exec pub state (.line (.binary .add 5 5 1)) (Function.update rs 5 (Fin.ofNat (2^w) n)) m
+ [.tick] (Function.update rs 5 (Fin.ofNat (2^w) n.succ)) m := by
+ apply Flow.Exec.line
+ simp (config := {decide := true}) [Op.effect, BinaryOp.eval, Function.update_self,
+ Function.update_of_ne, Function.update_idem, h1]
+ exact congrArg (Function.update rs 5) hadd
+ have he := ih.seq hl
+ exact (show ticks (w := w) (n.succ+1) = ticks (n+1) ++ [.tick] from
+ List.replicate_add (n+1) 1 (Event.tick (w := w))) ▸ he
+
+private theorem record_exec (pub : Fin k → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (h1 : rs 1 = 1) (a : Instruction extra) :
+ Flow.Exec pub state (record a) rs m (ticks (a.target.val + 5)) (instructionRegs rs a) m := by
+ have h : ticks (w := w) (a.target.val + 5) =
+ ticks (a.target.val+1) ++ [.tick,.tick,.tick,.tick] :=
+ List.replicate_add (a.target.val+1) 4 (Event.tick (w := w))
+ rw [h]
+ exact (target_exec pub state rs m h1 _).seq
+ ((Flow.Exec.line rfl).seq ((Flow.Exec.line rfl).seq ((Flow.Exec.line rfl).seq (.line rfl))))
+
+/-- Determinism of the straight-line portion that writes one selected record. -/
+private inductive Straight : Flow 32 k → Prop
+ | line (op : Op 32 k) : Straight (.line op)
+ | seq {f g : Flow 32 k} (hf : Straight f) (hg : Straight g) : Straight (.seq f g)
+
+private theorem Straight.unique {f : Flow 32 k} (h : Straight f) {pub : Fin k → Word w}
+ {state rs m es rs' m' fs rs'' m''}
+ (x : Flow.Exec pub state f rs m es rs' m') (y : Flow.Exec pub state f rs m fs rs'' m'') :
+ es = fs ∧ rs' = rs'' ∧ m' = m'' := by
+ induction h generalizing rs m es rs' m' fs rs'' m'' with
+ | line op =>
+ cases x with
+ | line hx =>
+ cases y with
+ | line hy =>
+ have he := Option.some.inj (hx.symm.trans hy)
+ simp only [Prod.mk.injEq] at he
+ obtain ⟨rfl,rfl,rfl⟩ := he
+ exact ⟨rfl,rfl,rfl⟩
+ | seq _ _ iha ihb =>
+ cases x with
+ | seq xa xb =>
+ cases y with
+ | seq ya yb =>
+ obtain ⟨rfl,rfl,rfl⟩ := iha xa ya
+ obtain ⟨rfl,rfl,rfl⟩ := ihb xb yb
+ exact ⟨rfl,rfl,rfl⟩
+
+private theorem target_straight (n : ℕ) : Straight (targetFlow (k := k) n) := by
+ induction n with
+ | zero => exact .line _
+ | succ n ih => exact ih.seq (.line _)
+
+private theorem record_straight (a : Instruction extra) : Straight (record (k := k) a) :=
+ (target_straight _).seq ((Straight.line _).seq ((Straight.line _).seq ((Straight.line _).seq (.line _))))
+
+private theorem no_reject_exec {pub : Fin k → Word w} {state rs m es rs' m'} :
+ ¬ Flow.Exec pub state reject rs m es rs' m' := by
+ intro h
+ cases h with
+ | line he => simp [Op.effect] at he
+
+private theorem row_exec_iff (pub : Fin k → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (h1 : rs 1 = 1) (b : Branches extra) (es rs' m') :
+ Flow.Exec pub state (rowFlow b) rs m es rs' m' ↔
+ ∃ bit a, chosenInstruction b bit = some a ∧ es = rowEvents b bit a ∧
+ rs' = instructionRegs rs a ∧ m' = m := by
+ constructor
+ · intro h
+ cases b with
+ | stop => exact (no_reject_exec h).elim
+ | one a =>
+ exact ⟨false, a, rfl, (record_straight a).unique h (record_exec pub state rs m h1 a)⟩
+ | two a b =>
+ cases h with
+ | branchYes he =>
+ obtain ⟨rfl,rfl,rfl⟩ := (record_straight b).unique he (record_exec pub state rs m h1 b)
+ exact ⟨true,b,rfl,rfl,rfl,rfl⟩
+ | branchNo he =>
+ obtain ⟨rfl,rfl,rfl⟩ := (record_straight a).unique he (record_exec pub state rs m h1 a)
+ exact ⟨false,a,rfl,rfl,rfl,rfl⟩
+ · rintro ⟨bit,a,ha,rfl,rfl,rfl⟩
+ cases b with
+ | stop => contradiction
+ | one x =>
+ cases bit
+ · cases ha
+ exact record_exec pub state rs _ h1 _
+ · contradiction
+ | two x y =>
+ cases bit <;> cases ha
+ · exact .branchNo (record_exec pub state rs _ h1 _)
+ · exact .branchYes (record_exec pub state rs _ h1 _)
+
+
+private theorem dispatchEvents_succ (i : ℕ) (b : Branches extra) (bit : Bool) (a : Instruction extra) :
+ dispatchEvents (w := w) (i+1) b bit a = .tick :: .tick :: dispatchEvents i b bit a := by
+ simp only [dispatchEvents, ticks, show 2*(i+1)+1 = (2*i+1)+1+1 by omega,
+ List.replicate_succ, List.cons_append]
+
+private theorem scan_exec_iff (pub : Fin k → Word w) (state : Word w) (hw : 2 ≤ w)
+ (bs : List (Branches extra)) (rs : Regs w 32) (m : Memory w) (h0 : rs 0 = 0)
+ (h1 : rs 1 = 1) (i : ℕ) (hi : (rs 4).val = i) (es rs' m') :
+ Flow.Exec pub state (scan bs) rs m es rs' m' ↔
+ ∃ bit a, chosenInstruction (bs[i]?.getD .stop) bit = some a ∧
+ es = dispatchEvents i (bs[i]?.getD .stop) bit a ∧
+ rs' = instructionRegs (Function.update rs 4 0) a ∧ m' = m := by
+ induction bs generalizing rs i es with
+ | nil =>
+ constructor
+ · exact fun h => (no_reject_exec h).elim
+ · rintro ⟨bit,a,ha,-⟩
+ simp [chosenInstruction] at ha
+ | cons b bs ih =>
+ cases i with
+ | zero =>
+ have h4 : rs 4 = 0 := Fin.ext hi
+ have heq : rs 4 = rs 0 := h4.trans h0.symm
+ have hup : Function.update rs 4 0 = rs := by
+ conv_lhs => arg 3; rw [← h4]
+ exact Function.update_eq_self _ _
+ simp only [List.getElem?_cons_zero, Option.getD_some, hup]
+ constructor
+ · intro h
+ cases h with
+ | ifEqYes _ hr =>
+ obtain ⟨bit,a,ha,rfl,hr,hm⟩ := (row_exec_iff pub state rs m h1 b _ _ _).mp hr
+ exact ⟨bit,a,ha,rfl,hr,hm⟩
+ | ifEqNo hn _ => contradiction
+ · rintro ⟨bit,a,ha,rfl,hr,hm⟩
+ exact .ifEqYes heq ((row_exec_iff pub state rs m h1 b _ _ _).mpr ⟨bit,a,ha,rfl,hr,hm⟩)
+ | succ i =>
+ have hne : rs 4 ≠ rs 0 := by
+ rw [h0]; intro hz; rw [hz] at hi; change 0 = i+1 at hi; omega
+ let q := Function.update rs 4 (rs 4 - rs 1)
+ have hq0 : q 0 = 0 := by simpa [q, Function.update_of_ne (by decide : (0 : Fin 32) ≠ 4)] using h0
+ have hq1 : q 1 = 1 := by simpa [q, Function.update_of_ne (by decide : (1 : Fin 32) ≠ 4)] using h1
+ have hv : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega))
+ have hle : (1 : Word w) ≤ rs 4 := by change (1 : Word w).val ≤ (rs 4).val; rw [hv, hi]; omega
+ have hq4 : (q 4).val = i := by
+ simp only [q, Function.update_self, h1, Fin.sub_val_of_le hle, hv, hi, Nat.succ_sub_one]
+ have hline : Flow.Exec pub state (.line (.binary .sub 4 4 1)) rs m [.tick] q m := .line rfl
+ have hup : Function.update q 4 0 = Function.update rs 4 0 := Function.update_idem _ _ _
+ simp only [List.getElem?_cons_succ, dispatchEvents_succ]
+ constructor
+ · intro h
+ cases h with
+ | ifEqYes heq _ => contradiction
+ | ifEqNo _ hskip =>
+ cases hskip with
+ | seq hdec htail =>
+ obtain ⟨rfl,rfl,rfl⟩ := (Straight.line _).unique hdec hline
+ obtain ⟨bit,a,ha,hes,hr,hm⟩ := (ih _ hq0 hq1 _ hq4 _).mp htail
+ exact ⟨bit,a,ha,by simp [hes],hup ▸ hr,hm⟩
+ · rintro ⟨bit,a,ha,rfl,hr,hm⟩
+ exact .ifEqNo hne (hline.seq ((ih _ hq0 hq1 _ hq4 _).mpr
+ ⟨bit,a,ha,rfl,hup.symm ▸ hr,hm⟩))
+
+/-- Successful dispatches are precisely the occupied slots of the indexed
+row. This also describes the whole event log and register frame. -/
+theorem dispatch_exec_iff (p : Program) (pub : Fin k → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (hw : 2 ≤ w) (h0 : rs 0 = 0) (h1 : rs 1 = 1) (es rs' m') :
+ Flow.Exec pub state (dispatch p) rs m es rs' m' ↔
+ ∃ bit a, chosenInstruction (p.rows[(rs 4).val]?.getD .stop) bit = some a ∧
+ es = dispatchEvents (rs 4).val (p.rows[(rs 4).val]?.getD .stop) bit a ∧
+ rs' = instructionRegs (Function.update rs 4 0) a ∧ m' = m :=
+ scan_exec_iff pub state hw p.rows rs m h0 h1 _ rfl es rs' m'
+
+/-- Construct the native execution for a selected table slot. -/
+theorem dispatch_exec (p : Program) (pub : Fin k → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (hw : 2 ≤ w) (h0 : rs 0 = 0) (h1 : rs 1 = 1)
+ (bit : Bool) (a : Instruction p.extra)
+ (ha : chosenInstruction (p.rows[(rs 4).val]?.getD .stop) bit = some a) :
+ Flow.Exec pub state (dispatch p) rs m
+ (dispatchEvents (rs 4).val (p.rows[(rs 4).val]?.getD .stop) bit a)
+ (instructionRegs (Function.update rs 4 0) a) m :=
+ (dispatch_exec_iff p pub state rs m hw h0 h1 _ _ _).mpr ⟨bit,a,ha,rfl,rfl,rfl⟩
+
+/-- The instruction budget is uniform in the word width, input and live window size. -/
+theorem dispatchEvents_bound (p : Program) (i : ℕ) (bit : Bool) (a : Instruction p.extra)
+ (ha : chosenInstruction (p.rows[i]?.getD .stop) bit = some a) :
+ (dispatchEvents (w := w) i (p.rows[i]?.getD .stop) bit a).length ≤ 19 * p.extra + 6 := by
+ have hi : i < p.rows.length := by
+ by_contra! hn
+ rw [List.getElem?_eq_none hn] at ha
+ contradiction
+ have hb : (dispatchBits (p.rows[i]?.getD .stop) bit).length ≤ 1 := by
+ cases p.rows[i]?.getD .stop <;> simp [dispatchBits]
+ rw [dispatchEvents_length]
+ rw [p.rows_length] at hi
+ have ht := a.target.isLt
+ omega
+
+/-- A stop row has no successful native execution for any amount of fuel
+or any branch stream. This includes out-of-range row indices. -/
+theorem dispatch_rejects (p : Program) (pub : Fin k → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (hw : 2 ≤ w) (h0 : rs 0 = 0) (h1 : rs 1 = 1)
+ (hstop : p.rows[(rs 4).val]?.getD .stop = .stop) (result : Option (Fin 32))
+ (priv : Word w → Word w) (fuel : ℕ) (bits : List Bool) :
+ let f : Flow 32 k := dispatch p
+ BurstRAM.execute ((f.template result).instantiate w pub).program fuel
+ ⟨f.pc f.entry,state,rs,priv⟩ m bits = none := by
+ dsimp only
+ apply Option.eq_none_iff_forall_not_mem.mpr
+ intro out hout
+ obtain ⟨rs',m',he,-⟩ := (Flow.template_execute_iff _ _ _ _ _ _ _ _ _ _).mp hout
+ obtain ⟨bit,a,ha,-⟩ := (dispatch_exec_iff p pub state rs m hw h0 h1 _ rs' m').mp he
+ rw [hstop] at ha
+ contradiction
+
+theorem target_loopFree (n : ℕ) : LiveEvaluatorRAM.loopFree (targetFlow (k := k) n) = true := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [targetFlow, LiveEvaluatorRAM.loopFree, ih]
+
+theorem dispatch_loopFree (p : Program) : LiveEvaluatorRAM.loopFree (dispatch (k := k) p) = true := by
+ have hrec (a : Instruction p.extra) : LiveEvaluatorRAM.loopFree (record (k := k) a) = true := by
+ simp [record, LiveEvaluatorRAM.loopFree, target_loopFree]
+ have hr (b : Branches p.extra) : LiveEvaluatorRAM.loopFree (rowFlow (k := k) b) = true := by
+ cases b <;> simp [rowFlow, reject, LiveEvaluatorRAM.loopFree, hrec]
+ unfold dispatch
+ induction p.rows with
+ | nil => rfl
+ | cons b bs ih => simp [scan, LiveEvaluatorRAM.loopFree, hr, ih]
+
+theorem countProbes_ticks_append (n : ℕ) (es : List (Event w)) :
+ BurstRAM.countProbes (ticks n ++ es) = BurstRAM.countProbes es := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa [ticks, List.replicate_succ, BurstRAM.countProbes] using ih
+
+theorem dispatchEvents_probes_append (i : ℕ) (b : Branches extra) (bit : Bool) (a : Instruction extra)
+ (es : List (Event w)) :
+ BurstRAM.countProbes (dispatchEvents i b bit a ++ es) = BurstRAM.countProbes es := by
+ cases b <;> simp [dispatchEvents, List.append_assoc, rowEvents, countProbes_ticks_append,
+ BurstRAM.countProbes]
+
+/-- The fixed natural loader has no other successful execution. -/
+theorem target_exec_iff (pub : Fin k → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (h1 : rs 1 = 1) (n : ℕ) (es rs' m') :
+ Flow.Exec pub state (targetFlow n) rs m es rs' m' ↔
+ es = ticks (n+1) ∧ rs' = Function.update rs 5 (Fin.ofNat (2^w) n) ∧ m' = m := by
+ constructor
+ · exact fun h => (target_straight n).unique h (target_exec pub state rs m h1 n)
+ · rintro ⟨rfl,rfl,rfl⟩
+ exact target_exec pub state rs _ h1 n
+
+end LiveEvaluatorRAMDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMImage.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMImage.lean
new file mode 100644
index 0000000000..9cfd55fea7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMImage.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.LiveEvaluatorEncoding
+import Mathlib.Data.ZMod.Defs
+
+/-!
+# External memory occupied by live evaluator configurations and scratch
+
+One packed word stores the state, followed by the two consecutive
+head-relative tape windows. The chosen transition occupies five separate
+scratch words in target, first write, first move, second write, second move order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM
+
+open BurstRAM LiveEvaluatorEncoding
+open scoped Fin.CommRing
+
+variable {w extra M : ℕ}
+
+/-- The specified external memory contains the complete canonical code. -/
+structure ConfigAt (m : Memory w) (base : Word w) (c : LiveEvaluatorEncoding.Code extra M) : Prop where
+ state : (m base.val).val = c.stateWord.val
+ first (i : Fin (2 * M + 1)) : (m (base + 1 + (i.val : Word w)).val).val = (c.firstCell i).val
+ second (i : Fin (2 * M + 1)) :
+ (m (base + 1 + ((2 * M + 1 : ℕ) : Word w) + (i.val : Word w)).val).val = (c.secondCell i).val
+
+/-- The five words selected once at the start of this group. -/
+structure ActionAt (m : Memory w) (base : Word w) (target : ℕ)
+ (firstWrite firstMove secondWrite secondMove : UniversalMachine.Symbol) : Prop where
+ targetVal : (m base.val).val = target
+ firstWriteVal : (m (base + 1).val).val = firstWrite.val
+ firstMoveVal : (m (base + 2).val).val = firstMove.val
+ secondWriteVal : (m (base + 3).val).val = secondWrite.val
+ secondMoveVal : (m (base + 4).val).val = secondMove.val
+
+/-- Installing the words of the checked cut decoder gives the exact memory
+image used by the native scan. -/
+theorem configAt_of_words (hw : 2 ≤ w) (hs : extra + 2 ≤ 2 ^ w) {m : Memory w} {base : Word w}
+ (c : LiveEvaluatorEncoding.Code extra M)
+ (h : ∀ f, m (base + (f.val : Word w)).val = (format hw hs).words c f) :
+ ConfigAt m base c := by
+ constructor
+ · have he := congrArg Fin.val (h (stateField M))
+ simpa [stateField] using he.trans (words_state hw hs c)
+ · intro i
+ have he := congrArg Fin.val (h (firstField i))
+ simpa [firstField, add_assoc] using he.trans (words_first hw hs c i)
+ · intro i
+ have he := congrArg Fin.val (h (secondField i))
+ simpa [secondField, add_assoc] using he.trans (words_second hw hs c i)
+
+end LiveEvaluatorRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMMalformed.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMMalformed.lean
new file mode 100644
index 0000000000..9ee6725ce6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMMalformed.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.LiveEvaluatorNativeGroup
+import OAI.Computability.VPVNP.LiveEvaluatorRawCells
+import OAI.Computability.VPVNP.LiveEvaluatorRawPrepare
+import OAI.Computability.VPVNP.LiveEvaluatorRAMSegmentCost
+
+/-!
+# Native evaluator-group counts on arbitrary configuration words
+
+If a complete native path accepts, the preparing call checks both state
+words and the two scans check every symbol. Thus malformed words admit no
+accepting path. The cost-capped path count agrees with the decoded local
+tail factor even when a configuration fails to decode.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorGroup
+
+open BurstRAM (Word Memory ActualPaths withinCaps)
+open LiveEvaluatorRAM (PrepLayout ConfigAt)
+open LiveEvaluatorRAM.Schedule (Pub calls nativeProgram callFuel actualPathEquiv capPathEquiv)
+open LiveEvaluatorEncoding (Code)
+open UniversalMachine (Program)
+open scoped Classical Fin.CommRing
+
+variable {M w : ℕ} {p : Program} {pub : Pub → Word w} {m : Memory w}
+
+/-- Native success forces the original raw memory of each boundary to
+represent an evaluator configuration, including canonical halt padding. -/
+theorem native_forces_configAt (hl : PrepLayout p pub M)
+ (run : ActualPaths (nativeProgram p pub) (callFuel p) 0 m (fun _ => True)) :
+ (∃ c : Code p.extra M, ConfigAt m (pub 1) c) ∧ (∃ c : Code p.extra M, ConfigAt m (pub 2) c) := by
+ obtain ⟨_, mem, hprep, hall⟩ := actualPathEquiv p pub m hl.radius (calls_fit hl).le run
+ obtain ⟨hpos, hlt, he₁, he₂, a, hapos, htarget, hact⟩ := hprep.raw_facts hl
+ have hst₁ : mem (pub 1).val = m (pub 1).val := by simpa using he₁ 0 (by simp [calls])
+ have hst₂ : mem (pub 2).val = m (pub 2).val := by simpa using he₂ 0 (by simp [calls])
+ obtain ⟨⟨c, hc⟩, z, hz⟩ := rawCells_force_images p pub mem a hl hall hact
+ (hst₁ ▸ ⟨hpos, hlt⟩) hapos (hst₂ ▸ htarget)
+ exact ⟨⟨c, configAt_congr_block hc he₁⟩, ⟨z, configAt_congr_block hz he₂⟩⟩
+
+theorem native_empty_of_malformed (hl : PrepLayout p pub M)
+ (hbad : (¬ ∃ c : Code p.extra M, ConfigAt m (pub 1) c) ∨
+ (¬ ∃ z : Code p.extra M, ConfigAt m (pub 2) z)) :
+ IsEmpty (ActualPaths (nativeProgram p pub) (callFuel p) 0 m (fun _ => True)) :=
+ ⟨fun run => by obtain ⟨h₁, h₂⟩ := native_forces_configAt hl run; exact hbad.elim (· h₁) (· h₂)⟩
+
+/-- The native count under the actual global and per-call transcript caps
+equals the local tail factor for every cut field. The endpoint memory
+hypotheses identify the gathered words with their checked decoder, so the
+two invalid-decoder cases give zero on both sides. -/
+theorem tailCount_eq_capped {h Δ S H : ℕ} (layout : LiveEvaluatorTail.Layout p.extra M w Δ)
+ (init : Code p.extra M) (bits : LiveChain.TailBits h Δ) (i : Fin (2 ^ h))
+ (hl : PrepLayout p pub M)
+ (ho : ∀ c, LiveEvaluatorTail.boundary layout init bits i.castSucc = some c ↔ ConfigAt m (pub 1) c)
+ (hz : ∀ z, LiveEvaluatorTail.boundary layout init bits i.succ = some z ↔ ConfigAt m (pub 2) z)
+ (hcost : 10 + 7 * (2 * (2 * M + 1)) ≤ S * H) (hcap : 10 ≤ H) :
+ ChainAssignments.tailCount p layout init bits i =
+ Nat.card (ActualPaths (nativeProgram p pub) (callFuel p) 0 m (withinCaps S H)) := by
+ rw [Nat.card_congr (capPathEquiv p pub m hl.radius (calls_fit hl).le hl.width hl.states hcost hcap)]
+ cases ha : LiveEvaluatorTail.boundary layout init bits i.castSucc with
+ | none =>
+ have := native_empty_of_malformed (m := m) hl (.inl (fun ⟨c, hc⟩ => by simpa [ha] using (ho c).mpr hc))
+ simp [ChainAssignments.tailCount, ha]
+ | some a =>
+ cases hb : LiveEvaluatorTail.boundary layout init bits i.succ with
+ | none =>
+ have := native_empty_of_malformed (m := m) hl (.inr (fun ⟨z, hh⟩ => by simpa [hb] using (hz z).mpr hh))
+ simp [ChainAssignments.tailCount, hb]
+ | some b => exact tailCount_eq_native layout init bits i ha hb hl ((ho a).mp ha) ((hz b).mp hb)
+
+end LiveEvaluatorGroup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMPrepare.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMPrepare.lean
new file mode 100644
index 0000000000..d49a39191f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMPrepare.lean
@@ -0,0 +1,462 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMDispatch
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PrimedStackRAMLeafVisit
+
+/-!
+# Preparing a live evaluator transition
+
+The first scheduled call checks the old state, reads the two heads of a
+running configuration, chooses a row slot, and checks the proposed output
+state. It writes the selected target, first write and move, and second write
+and move to five consecutive scratch words. An accepting source carries
+state one and four zeros without a choice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAMPrepare
+
+open BurstRAM (Word Memory Event choiceBits countProbes writeMemory)
+open BurstRAM.PrivateRAM (BinaryOp)
+open PrimedInputRAM (Flow)
+open PrimedStackRAM (Op Regs lines trace)
+open UniversalMachine (Program Instruction Branches chosenInstruction)
+open LiveEvaluatorRAMDispatch
+
+/-- The transition-preparation flow with 32 registers and four public configuration operands. -/
+abbrev Code := Flow 32 4
+private abbrev Ops := List (Op 32 4)
+variable {w : ℕ}
+
+/-- The head of the first tape follows the state word and the left half-window. -/
+def firstAddress (rs : Regs w 32) : Word w := rs 23 + rs 1 + rs 11
+
+/-- The second tape starts one complete window after the first. -/
+def secondAddress (rs : Regs w 32) : Word w := firstAddress rs + rs 22
+
+/-- Read the symbol under the old first-tape head from its external configuration address. -/
+def firstHead (rs : Regs w 32) (m : Memory w) := m (firstAddress rs).val
+/-- Read the symbol under the old second-tape head from its external configuration address. -/
+def secondHead (rs : Regs w 32) (m : Memory w) := m (secondAddress rs).val
+
+/-- The zero-based row number computed in machine-word arithmetic. -/
+def rowNumber (rs : Regs w 32) (m : Memory w) : Word w :=
+ (rs 16 - rs 2) * (rs 3 * rs 3) + firstHead rs m * rs 3 + secondHead rs m
+
+private def rowOps : Ops :=
+ [.binary .add 10 23 1, .binary .add 10 10 11, .read 17 10, .guardLt 17 3,
+ .binary .add 10 10 22, .read 18 10, .guardLt 18 3,
+ .binary .mul 19 3 3, .binary .sub 4 16 2, .binary .mul 4 4 19,
+ .binary .mul 20 17 3, .binary .add 4 4 20, .binary .add 4 4 18]
+
+private def indexRow : Code := lines rowOps (by decide)
+
+/-- The register bank after reading both heads and computing the instruction row indexed by the
+old state and the two symbols. -/
+def rowRegs (rs : Regs w 32) (m : Memory w) : Regs w 32 :=
+ let s := Function.update rs 10 (firstAddress rs)
+ let s := Function.update s 17 (firstHead rs m)
+ let s := Function.update s 10 (secondAddress rs)
+ let s := Function.update s 18 (secondHead rs m)
+ let s := Function.update s 19 (rs 3 * rs 3)
+ let s := Function.update s 4 ((rs 16 - rs 2) * (rs 3 * rs 3))
+ let s := Function.update s 20 (firstHead rs m * rs 3)
+ Function.update s 4 (rowNumber rs m)
+
+/-- The two external head reads and arithmetic ticks used to locate the running configuration's
+dispatch row. -/
+def rowTrace (rs : Regs w 32) (m : Memory w) : List (Event w) :=
+ [.tick,.tick,.read (firstAddress rs) (firstHead rs m),.tick,.tick,
+ .read (secondAddress rs) (secondHead rs m),.tick,.tick,.tick,.tick,.tick,.tick,.tick]
+
+set_option maxHeartbeats 2000000 in
+private theorem indexRow_iff (pub : Fin 4 → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (es out m') :
+ Flow.Exec pub state indexRow rs m es out m' ↔
+ firstHead rs m < rs 3 ∧ secondHead rs m < rs 3 ∧
+ es = rowTrace rs m ∧ out = rowRegs rs m ∧ m' = m := by
+ rw [indexRow, PrimedCounter.Admin.exec_lines_iff_trace]
+ by_cases ha : firstHead rs m < rs 3 <;> by_cases hb : secondHead rs m < rs 3
+ all_goals
+ simp only [firstHead, secondHead, firstAddress, secondAddress] at ha hb
+ simp (config := {decide := true}) [rowOps, trace, Op.effect, BinaryOp.eval,
+ rowTrace, rowRegs, rowNumber, firstHead, secondHead, firstAddress, secondAddress,
+ Function.update, ha, hb] <;> try tauto
+
+private def carryOps : Ops :=
+ [.copy 5 1,.copy 6 0,.copy 7 0,.copy 8 0,.copy 9 0]
+
+private def carry : Code := lines carryOps (by decide)
+
+/-- Set the instruction registers to the accepting carry transition, with target one and zero
+tape writes and motions. -/
+def carryRegs (rs : Regs w 32) : Regs w 32 :=
+ let s := Function.update rs 5 (rs 1)
+ let s := Function.update s 6 (rs 0)
+ let s := Function.update s 7 (rs 0)
+ let s := Function.update s 8 (rs 0)
+ Function.update s 9 (rs 0)
+
+private theorem carry_iff (pub : Fin 4 → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (es out m') :
+ Flow.Exec pub state carry rs m es out m' ↔ es = ticks 5 ∧ out = carryRegs rs ∧ m' = m := by
+ rw [carry, PrimedCounter.Admin.exec_lines_iff_trace]
+ have ht : trace pub state carryOps rs m = some (ticks 5, carryRegs rs, m) := rfl
+ rw [ht]; simp [eq_comm]
+
+private def publishOps : Ops :=
+ [.guardLt 0 5, .read 10 24, .guardEq 10 5,
+ .write 25 5, .binary .add 10 25 1, .write 10 6, .binary .add 10 10 1, .write 10 7,
+ .binary .add 10 10 1, .write 10 8, .binary .add 10 10 1, .write 10 9]
+
+private def publish : Code := lines publishOps (by decide)
+
+/-- The physical scratch addresses visited in order; all increments are native word additions. -/
+def scratchAddress (rs : Regs w 32) : ℕ → Word w
+ | 0 => rs 25
+ | i+1 => scratchAddress rs i + rs 1
+
+/-- The exact external memory after the five consecutive writes. -/
+def scratchMemory (rs : Regs w 32) (m : Memory w) : Memory w :=
+ let m := writeMemory m (scratchAddress rs 0) (rs 5)
+ let m := writeMemory m (scratchAddress rs 1) (rs 6)
+ let m := writeMemory m (scratchAddress rs 2) (rs 7)
+ let m := writeMemory m (scratchAddress rs 3) (rs 8)
+ writeMemory m (scratchAddress rs 4) (rs 9)
+
+/-- The register bank at the end of publishing an instruction, with the address cursor on its
+fifth scratch word. -/
+def publishRegs (rs : Regs w 32) : Regs w 32 := Function.update rs 10 (scratchAddress rs 4)
+
+/-- The destination state read and five scratch writes that publish the checked target, tape
+symbols, and motions. -/
+def publishTrace (rs : Regs w 32) (m : Memory w) : List (Event w) :=
+ [.tick,.read (rs 24) (m (rs 24).val),.tick,.write (scratchAddress rs 0) (rs 5),
+ .tick,.write (scratchAddress rs 1) (rs 6),.tick,.write (scratchAddress rs 2) (rs 7),
+ .tick,.write (scratchAddress rs 3) (rs 8),.tick,.write (scratchAddress rs 4) (rs 9)]
+
+private theorem publish_iff (pub : Fin 4 → Word w) (state : Word w) (rs : Regs w 32)
+ (m : Memory w) (es out m') :
+ Flow.Exec pub state publish rs m es out m' ↔
+ rs 0 < rs 5 ∧ m (rs 24).val = rs 5 ∧
+ es = publishTrace rs m ∧ out = publishRegs rs ∧ m' = scratchMemory rs m := by
+ rw [publish, PrimedCounter.Admin.exec_lines_iff_trace]
+ by_cases hpos : rs 0 < rs 5 <;> by_cases heq : m (rs 24).val = rs 5
+ all_goals
+ simp (config := {decide := true}) [publishOps, trace, Op.effect, BinaryOp.eval,
+ scratchMemory, scratchAddress, publishTrace, publishRegs, Function.update, hpos, heq] <;> try tauto
+
+/-- Install the highest permitted control-state number in the register used for the state bound
+check. -/
+def boundsRegs (p : Program) (rs : Regs w 32) : Regs w 32 :=
+ Function.update rs 5 (Fin.ofNat (2^w) (p.extra+1))
+
+private def reject : Code := .line (.guardLt 0 0)
+
+private def select (p : Program) : Code :=
+ .ifEq 16 1 carry (.seq indexRow (dispatch p))
+
+/-- Register 16 is the source state, 11 the window radius, 22 the window length,
+23 and 24 the input and output state-word addresses, and 25 the scratch base.
+Registers 0 through 3 carry their respective constants. -/
+def prepare (p : Program) : Code :=
+ .seq (.line (.guardLt 0 16)) <| .seq (targetFlow (p.extra+1)) <|
+ .ifLt 5 16 reject (.seq (select p) publish)
+
+/-- Only fixed straight-line blocks and the machine's finite dispatch occur. -/
+theorem prepare_loopFree (p : Program) : LiveEvaluatorRAM.loopFree (prepare p) = true := by
+ simp only [prepare, select, LiveEvaluatorRAM.loopFree, target_loopFree, dispatch_loopFree,
+ show LiveEvaluatorRAM.loopFree carry = true by rfl,
+ show LiveEvaluatorRAM.loopFree indexRow = true by rfl,
+ show LiveEvaluatorRAM.loopFree publish = true by rfl,
+ show LiveEvaluatorRAM.loopFree reject = true by rfl]
+ rfl
+
+
+/-- The fixed program row addressed by the two actual head reads. -/
+def tableRow (p : Program) (rs : Regs w 32) (m : Memory w) : Branches p.extra :=
+ p.rows[(rowNumber rs m).val]?.getD .stop
+
+/-- The register bank after locating the row and installing the chosen instruction's five
+fields. -/
+def selectedRegs {extra : ℕ} (rs : Regs w 32) (m : Memory w) (a : Instruction extra) : Regs w 32 :=
+ instructionRegs (Function.update (rowRegs rs m) 4 0) a
+
+/-- The two successful possibilities before checking and publishing the proposed target. -/
+inductive Selected (p : Program) (rs : Regs w 32) (m : Memory w) :
+ List (Event w) → Regs w 32 → Prop
+ | carry (h : rs 16 = rs 1) : Selected p rs m (.tick :: ticks 5) (carryRegs rs)
+ | slot (h : rs 16 ≠ rs 1) (hf : firstHead rs m < rs 3) (hs : secondHead rs m < rs 3)
+ (bit : Bool) (a : Instruction p.extra) (ha : chosenInstruction (tableRow p rs m) bit = some a) :
+ Selected p rs m (.tick :: (rowTrace rs m ++ dispatchEvents (rowNumber rs m).val (tableRow p rs m) bit a))
+ (selectedRegs rs m a)
+
+private theorem select_iff (p : Program) (pub : Fin 4 → Word w) (st : Word w) (rs : Regs w 32)
+ (m : Memory w) (hw : 2 ≤ w) (h0 : rs 0 = 0) (h1 : rs 1 = 1) (es out m') :
+ Flow.Exec pub st (select p) rs m es out m' ↔ Selected p rs m es out ∧ m' = m := by
+ have hr0 : (rowRegs rs m) 0 = 0 := h0
+ have hr1 : (rowRegs rs m) 1 = 1 := h1
+ constructor
+ · intro h
+ cases h with
+ | ifEqYes he hc =>
+ obtain ⟨rfl,rfl,hm⟩ := (carry_iff pub st rs m _ _ _).mp hc
+ exact ⟨.carry he,hm⟩
+ | ifEqNo he hr =>
+ cases hr with
+ | seq hi hd =>
+ obtain ⟨hf,hs,rfl,rfl,hm⟩ := (indexRow_iff pub st rs m _ _ _).mp hi
+ subst_vars
+ obtain ⟨bit,a,ha,rfl,rfl,hm'⟩ := (dispatch_exec_iff p pub st _ _ hw hr0 hr1 _ _ _).mp hd
+ exact ⟨.slot he hf hs bit a ha,hm'⟩
+ · rintro ⟨h,rfl⟩
+ cases h with
+ | carry he => exact .ifEqYes he ((carry_iff pub st rs _ _ _ _).mpr ⟨rfl,rfl,rfl⟩)
+ | slot he hf hs bit a ha =>
+ exact .ifEqNo he (.seq ((indexRow_iff pub st rs _ _ _ _).mpr ⟨hf,hs,rfl,rfl,rfl⟩)
+ (dispatch_exec p pub st _ _ hw hr0 hr1 bit a ha))
+
+/-- The complete event stream for a successful preparing call. -/
+def prepareTrace (p : Program) (fs : List (Event w)) (s : Regs w 32) (m : Memory w) :=
+ .tick :: (ticks (p.extra+2) ++ (.tick :: (fs ++ publishTrace s m)))
+
+private theorem guard_iff (pub : Fin 4 → Word w) (st : Word w) (x y : Fin 32)
+ (rs : Regs w 32) (m : Memory w) (es out m') :
+ Flow.Exec pub st (.line (.guardLt x y)) rs m es out m' ↔
+ rs x < rs y ∧ es = [.tick] ∧ out = rs ∧ m' = m := by
+ constructor
+ · intro h
+ cases h with
+ | line he =>
+ by_cases ht : rs x < rs y
+ · simp only [Op.effect, ht, ite_true, Option.some.injEq, Prod.mk.injEq] at he
+ obtain ⟨rfl,rfl,rfl⟩ := he
+ exact ⟨ht,rfl,rfl,rfl⟩
+ · simp [Op.effect, ht] at he
+ · rintro ⟨ht,rfl,rfl,rfl⟩
+ exact .line (by simp [Op.effect,ht])
+
+/-- Characterization for *all* raw source words, proposed outputs and choice streams.
+A successful run validates the source-state range, the chosen slot, the nonzero target
+and the matching output word before performing precisely the five scratch writes. -/
+theorem prepare_exec_iff (p : Program) (pub : Fin 4 → Word w) (st : Word w) (rs : Regs w 32)
+ (m : Memory w) (hw : 2 ≤ w) (hcap : p.extra+2 ≤ 2^w) (h0 : rs 0 = 0) (h1 : rs 1 = 1)
+ (es out m') :
+ Flow.Exec pub st (prepare p) rs m es out m' ↔
+ 0 < (rs 16).val ∧ (rs 16).val ≤ p.extra+1 ∧
+ ∃ fs s, Selected p (boundsRegs p rs) m fs s ∧
+ s 0 < s 5 ∧ m (s 24).val = s 5 ∧
+ es = prepareTrace p fs s m ∧ out = publishRegs s ∧ m' = scratchMemory s m := by
+ let u := boundsRegs p rs
+ have hu0 : u 0 = 0 := h0
+ have hu1 : u 1 = 1 := h1
+ have hu5 : (u 5).val = p.extra+1 := Nat.mod_eq_of_lt (by omega)
+ have hu16 : u 16 = rs 16 := rfl
+ constructor
+ · intro h
+ cases h with
+ | seq hg h =>
+ obtain ⟨hpos,rfl,rfl,hm⟩ := (guard_iff pub st 0 16 rs m _ _ _).mp hg
+ subst_vars
+ cases h with
+ | seq ht h =>
+ obtain ⟨rfl,rfl,hm⟩ := (target_exec_iff pub st _ _ h1 (p.extra+1) _ _ _).mp ht
+ subst_vars
+ cases h with
+ | ifLtYes _ hr =>
+ obtain ⟨h,-⟩ := (guard_iff pub st 0 0 _ _ _ _ _).mp hr
+ exact (lt_irrefl _ h).elim
+ | ifLtNo hle h =>
+ cases h with
+ | seq hs hp =>
+ obtain ⟨hsel,hm⟩ := (select_iff p pub st u _ hw hu0 hu1 _ _ _).mp hs
+ subst_vars
+ obtain ⟨hpt,heq,rfl,rfl,hm'⟩ := (publish_iff pub st _ _ _ _ _).mp hp
+ change ¬ (u 5).val < (u 16).val at hle
+ rw [hu5, hu16] at hle
+ exact ⟨by simpa [h0] using hpos, le_of_not_gt hle, _, _, hsel,hpt,heq,rfl,rfl,hm'⟩
+ · rintro ⟨hpos,hle,fs,s,hsel,hpt,heq,rfl,rfl,rfl⟩
+ have hg := (guard_iff pub st 0 16 rs m _ _ _).mpr
+ ⟨show rs 0 < rs 16 by rw [h0]; exact hpos, rfl,rfl,rfl⟩
+ have ht := target_exec pub st rs m h1 (p.extra+1)
+ have hle' : ¬ u 5 < u 16 := by change ¬ (u 5).val < (u 16).val; rw [hu5,hu16]; omega
+ have hs := (select_iff p pub st u m hw hu0 hu1 _ _ _).mpr ⟨hsel,rfl⟩
+ have hp := (publish_iff pub st s m _ _ _).mpr ⟨hpt,heq,rfl,rfl,rfl⟩
+ exact hg.seq (ht.seq (.ifLtNo hle' (hs.seq hp)))
+
+
+/-- A previously accepting state is carried deterministically after checking its proposed successor. -/
+theorem prepare_accept_exec (p : Program) (pub : Fin 4 → Word w) (st : Word w) (rs : Regs w 32)
+ (m : Memory w) (hw : 2 ≤ w) (hcap : p.extra+2 ≤ 2^w) (h0 : rs 0 = 0) (h1 : rs 1 = 1)
+ (hold : rs 16 = 1) (hout : m (rs 24).val = 1) :
+ let s := carryRegs (boundsRegs p rs)
+ Flow.Exec pub st (prepare p) rs m (prepareTrace p (.tick :: ticks 5) s m)
+ (publishRegs s) (scratchMemory s m) := by
+ let u := boundsRegs p rs
+ let s := carryRegs u
+ have hv : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega))
+ have hval : (rs 16).val = 1 := by rw [hold,hv]
+ have hs : Selected p u m (.tick :: ticks 5) s := .carry (hold.trans h1.symm)
+ have hs0 : s 0 = 0 := h0
+ have hs5 : s 5 = 1 := h1
+ have hp : s 0 < s 5 := by rw [hs0,hs5]; change 0 < (1 : Word w).val; omega
+ exact (prepare_exec_iff p pub st rs m hw hcap h0 h1 _ _ _).mpr
+ ⟨by omega,by omega,_,s,hs,hp,hout.trans hs5.symm,rfl,rfl,rfl⟩
+
+/-- An occupied slot of a running source executes with its actual head reads and exact target. -/
+theorem prepare_running_exec (p : Program) (pub : Fin 4 → Word w) (st : Word w) (rs : Regs w 32)
+ (m : Memory w) (hw : 2 ≤ w) (hcap : p.extra+2 ≤ 2^w) (h0 : rs 0 = 0) (h1 : rs 1 = 1)
+ (hold : 2 ≤ (rs 16).val) (hstate : (rs 16).val ≤ p.extra+1)
+ (hf : firstHead rs m < rs 3) (hs : secondHead rs m < rs 3)
+ (bit : Bool) (a : Instruction p.extra) (ha : chosenInstruction (tableRow p rs m) bit = some a)
+ (hp : 0 < a.target.val) (hout : (m (rs 24).val).val = a.target.val) :
+ let s := selectedRegs (boundsRegs p rs) m a
+ let fs := .tick :: (rowTrace rs m ++ dispatchEvents (rowNumber rs m).val (tableRow p rs m) bit a)
+ Flow.Exec pub st (prepare p) rs m (prepareTrace p fs s m) (publishRegs s) (scratchMemory s m) := by
+ let u := boundsRegs p rs
+ let s := selectedRegs u m a
+ have hv : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega))
+ have hne : u 16 ≠ u 1 := by
+ change rs 16 ≠ rs 1
+ intro he; rw [he,h1,hv] at hold; omega
+ have hsel := Selected.slot (p := p) (rs := u) (m := m) hne hf hs bit a ha
+ have hs0 : s 0 = 0 := h0
+ have hs5 : (s 5).val = a.target.val := (instructionRegs_fields _ a hw hcap).1
+ have hpt : s 0 < s 5 := by rw [hs0]; change 0 < (s 5).val; omega
+ exact (prepare_exec_iff p pub st rs m hw hcap h0 h1 _ _ _).mpr
+ ⟨by omega,hstate,_,s,hsel,hpt,Fin.ext (hout.trans hs5.symm),rfl,rfl,rfl⟩
+
+theorem prepareTrace_bits (p : Program) (fs : List (Event w)) (s : Regs w 32) (m : Memory w) :
+ choiceBits (prepareTrace p fs s m) = choiceBits fs := by
+ simp [prepareTrace, choiceBits, Flow.choiceBits_append, choiceBits_ticks, publishTrace]
+
+theorem prepareTrace_probes (p : Program) (fs : List (Event w)) (s : Regs w 32) (m : Memory w) :
+ countProbes (prepareTrace p fs s m) = countProbes fs + 6 := by
+ have ht : countProbes (ticks (w := w) (p.extra+2)) = 0 := by
+ simpa [countProbes] using countProbes_ticks_append (p.extra+2) ([] : List (Event w))
+ simp [prepareTrace, countProbes, PrimedStackRAM.probes_append, ht, publishTrace]
+
+theorem prepareTrace_length (p : Program) (fs : List (Event w)) (s : Regs w 32) (m : Memory w) :
+ (prepareTrace p fs s m).length = p.extra + 16 + fs.length := by
+ simp [prepareTrace, ticks, publishTrace]; omega
+
+/-- The exact bit stream for a successful running slot, including the genuine bit
+distinguishing the two slots even when both instructions are identical. -/
+theorem prepare_slot_bits (p : Program) (rs : Regs w 32) (m : Memory w) (bit : Bool)
+ (a : Instruction p.extra) (s : Regs w 32) :
+ choiceBits (prepareTrace p (.tick :: (rowTrace rs m ++
+ dispatchEvents (rowNumber rs m).val (tableRow p rs m) bit a)) s m) =
+ dispatchBits (tableRow p rs m) bit := by
+ simp [prepareTrace_bits, choiceBits, rowTrace, dispatchEvents_bits]
+
+/-- All successful preparing calls make six probes for a carried accepting state
+and eight probes for a running source. Only an occupied two-slot row consumes a bit. -/
+theorem prepare_cost (p : Program) (pub : Fin 4 → Word w) (st : Word w) (rs : Regs w 32)
+ (m : Memory w) (hw : 2 ≤ w) (hcap : p.extra+2 ≤ 2^w) (h0 : rs 0 = 0) (h1 : rs 1 = 1)
+ {es out m'} (he : Flow.Exec pub st (prepare p) rs m es out m') :
+ countProbes es = (if rs 16 = rs 1 then 6 else 8) ∧
+ (choiceBits es).length ≤ 1 ∧ es.length ≤ 20*p.extra + 36 := by
+ obtain ⟨-, -, fs,s,hsel,-,-,rfl,-,-⟩ := (prepare_exec_iff p pub st rs m hw hcap h0 h1 _ _ _).mp he
+ clear he
+ rw [prepareTrace_probes, prepareTrace_bits, prepareTrace_length]
+ cases hsel with
+ | carry he =>
+ change rs 16 = rs 1 at he
+ simp [he, ticks, countProbes, choiceBits]
+ omega
+ | slot hn hf hs bit a ha =>
+ let u := boundsRegs p rs
+ change rs 16 ≠ rs 1 at hn
+ have hp : countProbes (dispatchEvents (w := w) (rowNumber u m).val (tableRow p u m) bit a) = 0 := by
+ simpa [countProbes] using dispatchEvents_probes_append (rowNumber u m).val (tableRow p u m) bit a
+ ([] : List (Event w))
+ have hbits : (dispatchBits (tableRow p u m) bit).length ≤ 1 := by
+ cases tableRow p u m <;> simp [dispatchBits]
+ have hlen := dispatchEvents_bound (w := w) p (rowNumber u m).val bit a ha
+ change (dispatchEvents (w := w) (rowNumber u m).val (tableRow p u m) bit a).length ≤ _ at hlen
+ simp only [u] at hp hbits hlen
+ simp [hn, rowTrace, countProbes, choiceBits, hp, hbits, dispatchEvents_bits]
+ omega
+
+/-- If the first head address fits, its machine word is the ordinary
+input base plus the state-word offset and the window radius. -/
+theorem firstAddress_val (rs : Regs w 32) (h1 : (rs 1).val = 1)
+ (hfit : (rs 23).val + 1 + (rs 11).val < 2^w) :
+ (firstAddress rs).val = (rs 23).val + 1 + (rs 11).val := by
+ simpa only [firstAddress, Fin.val_add, h1, Nat.mod_add_mod] using Nat.mod_eq_of_lt hfit
+
+/-- When the second address fits, the second head lies exactly one window
+length after the first head. -/
+theorem secondAddress_val (rs : Regs w 32) (h1 : (rs 1).val = 1)
+ (hfit : (rs 23).val + 1 + (rs 11).val + (rs 22).val < 2^w) :
+ (secondAddress rs).val = (rs 23).val + 1 + (rs 11).val + (rs 22).val := by
+ rw [secondAddress, Fin.val_add, firstAddress_val rs h1 (by omega), Nat.mod_eq_of_lt hfit]
+
+/-- The machine computes the natural row index whenever the source state is
+a running state and the final index fits. Intermediate products may wrap. -/
+theorem rowNumber_val (rs : Regs w 32) (m : Memory w)
+ (h2 : (rs 2).val = 2) (h3 : (rs 3).val = 3) (hstate : 2 ≤ (rs 16).val)
+ (hfit : ((rs 16).val - 2) * 9 + (firstHead rs m).val * 3 + (secondHead rs m).val < 2^w) :
+ (rowNumber rs m).val =
+ ((rs 16).val - 2) * 9 + (firstHead rs m).val * 3 + (secondHead rs m).val := by
+ have hle : rs 2 ≤ rs 16 := by change (rs 2).val ≤ (rs 16).val; omega
+ simpa only [rowNumber, Fin.val_add, Fin.val_mul, Fin.sub_val_of_le hle, h2, h3,
+ Nat.mul_mod_mod, Nat.mod_add_mod, Nat.add_mod_mod, Nat.reduceMul] using Nat.mod_eq_of_lt hfit
+
+/-- Unit increments give the ordinary consecutive scratch address whenever it fits. -/
+theorem scratchAddress_val (rs : Regs w 32) (h1 : (rs 1).val = 1) (i : ℕ)
+ (hfit : (rs 25).val + i < 2 ^ w) :
+ (scratchAddress rs i).val = (rs 25).val + i := by
+ induction i with
+ | zero => rfl
+ | succ i ih =>
+ have hi := ih (by omega)
+ rw [scratchAddress, Fin.val_add_eq_of_add_lt, hi, h1]
+ · omega
+ · rw [hi, h1]
+ omega
+
+/-- At each allocated scratch offset the caller reads the corresponding instruction register. -/
+theorem scratchMemory_at (rs : Regs w 32) (m : Memory w) (h1 : (rs 1).val = 1)
+ (hfit : (rs 25).val + 5 ≤ 2 ^ w) (i : Fin 5) :
+ scratchMemory rs m ((rs 25).val + i.val) = rs ⟨5 + i.val, by omega⟩ := by
+ have hv (j : ℕ) (hj : j < 5) : (scratchAddress rs j).val = (rs 25).val + j :=
+ scratchAddress_val rs h1 j (by omega)
+ fin_cases i <;>
+ simp (config := { decide := true }) [scratchMemory, writeMemory, hv]
+
+/-- Publishing leaves every address outside the five-word scratch interval intact. -/
+theorem scratchMemory_outside (rs : Regs w 32) (m : Memory w) (h1 : (rs 1).val = 1)
+ (hfit : (rs 25).val + 5 ≤ 2 ^ w) (k : ℕ)
+ (hk : k < (rs 25).val ∨ (rs 25).val + 5 ≤ k) :
+ scratchMemory rs m k = m k := by
+ have hne (j : ℕ) (hj : j < 5) : k ≠ (scratchAddress rs j).val := by
+ rw [scratchAddress_val rs h1 j (by omega)]
+ omega
+ simp (config := { decide := true }) [scratchMemory, writeMemory, hne]
+
+/-- Selecting a transition preserves the four constants, window coordinates, source state,
+and the registers above the row-calculation workspace. -/
+theorem Selected.frame {p : Program} {rs : Regs w 32} {m : Memory w} {es s}
+ (h : Selected p rs m es s) (j : Fin 32)
+ (hj : j.val < 4 ∨ (10 < j.val ∧ j.val < 17) ∨ 20 < j.val) : s j = rs j := by
+ cases h with
+ | carry h =>
+ simp only [carryRegs]
+ repeat rw [Function.update_of_ne (by intro he; subst j; exact (by decide : ¬ _) hj)]
+ | slot h hf hs bit a ha =>
+ rw [selectedRegs, instructionRegs_other _ _ _ (by omega)]
+ simp only [rowRegs]
+ repeat rw [Function.update_of_ne (by intro he; subst j; exact (by decide : ¬ _) hj)]
+
+/-- Publication uses only register 10 as its scratch-address cursor. -/
+theorem publishRegs_other (rs : Regs w 32) (j : Fin 32) (hj : j ≠ 10) :
+ publishRegs rs j = rs j := Function.update_of_ne hj ..
+
+end LiveEvaluatorRAMPrepare
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMPrepareImage.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMPrepareImage.lean
new file mode 100644
index 0000000000..fa35f1ec07
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMPrepareImage.lean
@@ -0,0 +1,254 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAction
+import OAI.Computability.VPVNP.LiveEvaluatorRAMScratchImage
+import OAI.Computability.VPVNP.LiveEvaluatorRAMSchedule
+
+/-!
+# The scheduled preparing call on configuration images
+
+The first call reads the old state and the two head symbols and consults the
+fixed evaluator's row. The selected five words must match the proposed state
+and are published to disjoint scratch memory. The choice stream distinguishes
+the slots even if they specify identical instructions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM
+
+open BurstRAM (Word Memory choiceBits)
+open PrimedStackRAM (Regs)
+open PrimedInputRAM (Flow)
+open UniversalMachine (Program Instruction chosenInstruction windowCenter)
+open LiveEvaluatorEncoding (ConfigWindow)
+open LiveEvaluatorRAMPrepare
+open LiveEvaluatorRAMDispatch (ticks dispatchBits instructionRegs_fields)
+open scoped Fin.CommRing
+
+variable {w M : ℕ}
+
+/-- The allocation supplies enough bits for every program row, both
+configurations, and the separate five-word scratch area. -/
+structure PrepLayout (p : Program) (pub : Fin 4 → Word w) (M : ℕ) : Prop where
+ width : 2 ≤ w
+ states : p.extra + 2 ≤ 2 ^ w
+ rows : 9 * p.extra ≤ 2 ^ w
+ radius : (pub 0).val = M
+ oldFit : (pub 1).val + Schedule.calls M ≤ 2 ^ w
+ outFit : (pub 2).val + Schedule.calls M ≤ 2 ^ w
+ scratchFit : (pub 3).val + 5 ≤ 2 ^ w
+ oldDisjoint : (pub 1).val + Schedule.calls M ≤ (pub 3).val ∨ (pub 3).val + 5 ≤ (pub 1).val
+ outDisjoint : (pub 2).val + Schedule.calls M ≤ (pub 3).val ∨ (pub 3).val + 5 ≤ (pub 2).val
+
+/-- A native run from cursor zero, indexed by its final memory and consumed bits. -/
+def Prepared (p : Program) (pub : Fin 4 → Word w) (m mem : Memory w) (bs : List Bool) : Prop :=
+ ∃ es rs, Flow.Exec pub 0 (Schedule.body (prepare p)) (fun _ => 0) m es rs mem ∧ choiceBits es = bs
+
+private abbrev entryRegs (pub : Fin 4 → Word w) (m : Memory w) : Regs w 32 :=
+ Schedule.loaded pub 0 (fun _ => 0) m
+
+private abbrev selectRegs (p : Program) (pub : Fin 4 → Word w) (m : Memory w) : Regs w 32 :=
+ boundsRegs p (entryRegs pub m)
+
+private def recordRegs (p : Program) (pub : Fin 4 → Word w) (m : Memory w)
+ (old : LiveEvaluatorEncoding.Code p.extra M) (a : Instruction p.extra) : Regs w 32 :=
+ match old with
+ | .accepted => carryRegs (selectRegs p pub m)
+ | _ => selectedRegs (selectRegs p pub m) m a
+
+/-- Memory obtained by publishing the selected record of this source. -/
+def preparedMemory (p : Program) (pub : Fin 4 → Word w) (m : Memory w)
+ (old : LiveEvaluatorEncoding.Code p.extra M) (a : Instruction p.extra) : Memory w :=
+ scratchMemory (recordRegs p pub m old a) m
+
+private theorem numeral_val {n : ℕ} (h : n < 2 ^ w) : (n : Word w).val = n :=
+ Nat.mod_eq_of_lt h
+
+private theorem head_values {p : Program} {pub : Fin 4 → Word w} {m : Memory w}
+ {old : LiveEvaluatorEncoding.Code p.extra M} (hl : PrepLayout p pub M)
+ (ho : ConfigAt m (pub 1) old) :
+ (firstHead (selectRegs p pub m) m).val = (old.firstCell (windowCenter M)).val ∧
+ (secondHead (selectRegs p pub m) m).val = (old.secondCell (windowCenter M)).val := by
+ have hr : pub 0 = (M : Word w) := by rw [← hl.radius, Fin.cast_val_eq_self]
+ have hlen : pub 0 + pub 0 + 1 = ((2*M+1 : ℕ) : Word w) := by
+ rw [hr]
+ push_cast
+ ring
+ change (m (pub 1 + 1 + pub 0).val).val = _ ∧
+ (m (pub 1 + 1 + pub 0 + (pub 0 + pub 0 + 1)).val).val = _
+ rw [hlen, hr, add_right_comm (pub 1 + 1) (M : Word w)]
+ exact ⟨ho.first (windowCenter M), ho.second (windowCenter M)⟩
+
+private theorem tableRow_eq {p : Program} {pub : Fin 4 → Word w} {m : Memory w}
+ {c : ConfigWindow p.extra M} {hc : 2 ≤ c.state.val} (hl : PrepLayout p pub M)
+ (ho : ConfigAt m (pub 1) (.running c hc)) :
+ tableRow p (selectRegs p pub m) m = LiveEvaluatorStep.row p c := by
+ let rs := selectRegs p pub m
+ have h4 : 4 ≤ 2^w := Nat.pow_le_pow_right (by decide : 0 < 2) hl.width
+ have h2 : (rs 2).val = 2 := numeral_val (n := 2) (by omega)
+ have h3 : (rs 3).val = 3 := numeral_val (n := 3) (by omega)
+ have hstate : (rs 16).val = c.state.val := ho.state
+ have ⟨hf, hs⟩ := head_values hl ho
+ change (firstHead rs m).val = (c.firstTape.cells (windowCenter M)).val at hf
+ change (secondHead rs m).val = (c.secondTape.cells (windowCenter M)).val at hs
+ have hfit : ((rs 16).val - 2) * 9 + (firstHead rs m).val * 3 + (secondHead rs m).val < 2^w := by
+ rw [hstate, hf, hs]
+ have := c.state.isLt
+ have := (c.firstTape.cells (windowCenter M)).isLt
+ have := (c.secondTape.cells (windowCenter M)).isLt
+ have := hl.rows
+ omega
+ change p.rows[(rowNumber rs m).val]?.getD .stop = _
+ rw [rowNumber_val rs m h2 h3 (hstate ▸ hc) hfit, hstate, hf, hs]
+ rfl
+
+private theorem selected_iff {p : Program} {pub : Fin 4 → Word w} {m : Memory w}
+ {old : LiveEvaluatorEncoding.Code p.extra M} (hl : PrepLayout p pub M)
+ (ho : ConfigAt m (pub 1) old) (hpos : 0 < old.stateWord.val) (s : Regs w 32) (bs : List Bool) :
+ (∃ fs, Selected p (selectRegs p pub m) m fs s ∧ choiceBits fs = bs) ↔
+ ∃ bit a, LiveEvaluatorAction.pick p old bit = some a ∧ s = recordRegs p pub m old a ∧
+ bs = LiveEvaluatorAction.branchBits p old bit := by
+ let u := selectRegs p pub m
+ have h4 : 4 ≤ 2^w := Nat.pow_le_pow_right (by decide : 0 < 2) hl.width
+ have hu1 : (u 1).val = 1 := numeral_val (n := 1) (by omega)
+ have hu3 : (u 3).val = 3 := numeral_val (n := 3) (by omega)
+ have hstate : (u 16).val = old.stateWord.val := ho.state
+ cases old with
+ | rejected => exact (Nat.lt_irrefl 0 hpos).elim
+ | accepted =>
+ change (u 16).val = 1 at hstate
+ have heq : u 16 = u 1 := Fin.ext (hstate.trans hu1.symm)
+ have hbits : choiceBits (.tick :: ticks (w := w) 5) = [] := rfl
+ constructor
+ · rintro ⟨fs, sel, hb⟩
+ cases sel with
+ | carry => exact ⟨false, LiveEvaluatorAction.carry _, rfl, rfl, hb.symm.trans hbits⟩
+ | slot hne => exact (hne heq).elim
+ · rintro ⟨bit, a, ha, rfl, rfl⟩
+ exact ⟨_, .carry heq, hbits⟩
+ | running c hc =>
+ change (u 16).val = c.state.val at hstate
+ have hne : u 16 ≠ u 1 := by intro he; rw [he, hu1] at hstate; omega
+ have hrow := tableRow_eq hl ho
+ have ⟨hv₁, hv₂⟩ := head_values hl ho
+ have hf : firstHead u m < u 3 := by
+ change (firstHead u m).val < (u 3).val
+ rw [hu3, hv₁]
+ exact (c.firstTape.cells _).isLt
+ have hs : secondHead u m < u 3 := by
+ change (secondHead u m).val < (u 3).val
+ rw [hu3, hv₂]
+ exact (c.secondTape.cells _).isLt
+ have hbits (bit : Bool) (a : Instruction p.extra) :
+ choiceBits (.tick :: (rowTrace u m ++
+ LiveEvaluatorRAMDispatch.dispatchEvents (rowNumber u m).val (tableRow p u m) bit a)) =
+ LiveEvaluatorAction.branchBits p (.running c hc) bit := by
+ rw [LiveEvaluatorAction.branchBits, ← hrow]
+ simp [u, choiceBits, rowTrace, LiveEvaluatorRAMDispatch.dispatchEvents_bits]
+ constructor
+ · rintro ⟨fs, sel, hb⟩
+ cases sel with
+ | carry heq => exact (hne heq).elim
+ | slot _ _ _ bit a ha =>
+ exact ⟨bit, a, by simpa only [LiveEvaluatorAction.pick, ← hrow] using ha, rfl,
+ hb.symm.trans (hbits bit a)⟩
+ · rintro ⟨bit, a, ha, rfl, rfl⟩
+ exact ⟨_, .slot hne hf hs bit a (by simpa only [LiveEvaluatorAction.pick, ← hrow] using ha), hbits bit a⟩
+
+private theorem record_fields {p : Program} {pub : Fin 4 → Word w} {m : Memory w}
+ {old : LiveEvaluatorEncoding.Code p.extra M} {bit : Bool} {a : Instruction p.extra}
+ (hl : PrepLayout p pub M) (ha : LiveEvaluatorAction.pick p old bit = some a) :
+ let rs := recordRegs p pub m old a
+ (rs 5).val = a.target.val ∧ (rs 6).val = a.firstSymbol.val ∧
+ (rs 7).val = a.firstMove.val ∧ (rs 8).val = a.secondSymbol.val ∧
+ (rs 9).val = a.secondMove.val := by
+ cases old with
+ | accepted =>
+ cases bit <;> simp [LiveEvaluatorAction.pick] at ha
+ subst a
+ have h4 : 4 ≤ 2^w := Nat.pow_le_pow_right (by decide : 0 < 2) hl.width
+ exact ⟨numeral_val (n := 1) (by omega), rfl, rfl, rfl, rfl⟩
+ | rejected => cases ha
+ | running c hc => exact instructionRegs_fields (Function.update (rowRegs (selectRegs p pub m) m) 4 0) a hl.width hl.states
+
+private theorem record_frame {p : Program} {pub : Fin 4 → Word w} {m : Memory w}
+ (old : LiveEvaluatorEncoding.Code p.extra M) (a : Instruction p.extra) :
+ let rs := recordRegs p pub m old a
+ rs 0 = 0 ∧ rs 1 = 1 ∧ rs 24 = pub 2 ∧ rs 25 = pub 3 := by
+ cases old <;> exact ⟨rfl, rfl, rfl, rfl⟩
+
+/-- Execution at cursor zero is equivalent to picking an occupied slot with
+a nonrejecting target equal to the proposed state. Both the consumed bits and
+the resulting external memory are specified. -/
+theorem prepared_iff {p : Program} {pub : Fin 4 → Word w} {m mem : Memory w} {bs : List Bool}
+ {old out : LiveEvaluatorEncoding.Code p.extra M} (hl : PrepLayout p pub M)
+ (ho : ConfigAt m (pub 1) old) (hz : ConfigAt m (pub 2) out) :
+ Prepared p pub m mem bs ↔
+ ∃ bit a, LiveEvaluatorAction.pick p old bit = some a ∧ 0 < a.target.val ∧
+ a.target = out.stateWord ∧ bs = LiveEvaluatorAction.branchBits p old bit ∧
+ mem = preparedMemory p pub m old a := by
+ rw [Prepared, Schedule.initial_choices_iff]
+ let rs := entryRegs pub m
+ have hstate : (rs 16).val = old.stateWord.val := ho.state
+ have he := prepare_exec_iff p pub 0 rs m hl.width hl.states rfl rfl
+ constructor
+ · rintro ⟨es, reg, run, hb⟩
+ obtain ⟨hp, -, fs, s, sel, hpt, hout, hes, -, hmem⟩ := (he _ _ _).mp run
+ rw [hes, prepareTrace_bits] at hb
+ rw [hstate] at hp
+ obtain ⟨bit, a, ha, rfl, hbits⟩ := (selected_iff hl ho hp s bs).mp ⟨fs, sel, hb⟩
+ obtain ⟨hs0, -, hs24, -⟩ := record_frame (pub := pub) (m := m) old a
+ have ht := (record_fields (m := m) hl ha).1
+ rw [hs0] at hpt
+ rw [hs24] at hout
+ exact ⟨bit, a, ha, ht ▸ hpt, Fin.ext (ht.symm.trans ((congrArg Fin.val hout).symm.trans hz.state)),
+ hbits, hmem⟩
+ · rintro ⟨bit, a, ha, hpt, hout, hb, rfl⟩
+ have hp : 0 < old.stateWord.val := by
+ cases old with
+ | accepted => exact Nat.zero_lt_one
+ | rejected => cases ha
+ | running c hc => change 0 < c.state.val; omega
+ let s := recordRegs p pub m old a
+ obtain ⟨fs, sel, hbits⟩ := (selected_iff hl ho hp s bs).mpr ⟨bit, a, ha, rfl, hb⟩
+ obtain ⟨hs0, -, hs24, -⟩ := record_frame (pub := pub) (m := m) old a
+ have ht := (record_fields (m := m) hl ha).1
+ have hlt : s 0 < s 5 := by
+ rw [show s 0 = 0 from hs0]
+ change 0 < (s 5).val
+ rwa [show (s 5).val = _ from ht]
+ have hm : m (s 24).val = s 5 := by
+ apply Fin.ext
+ rw [show s 24 = pub 2 from hs24, hz.state, ← hout]
+ exact ht.symm
+ have hrange := old.stateWord.isLt
+ refine ⟨_, _, (he _ _ _).mpr ⟨hstate ▸ hp, by omega, fs, s, sel, hlt, hm, rfl, rfl, rfl⟩, ?_⟩
+ rw [prepareTrace_bits, hbits]
+
+/-- Publication preserves the two configuration images and installs the five
+chosen instruction words at the address subsequently used by the cell scans. -/
+theorem preparedMemory_images {p : Program} {pub : Fin 4 → Word w} {m : Memory w}
+ {old out : LiveEvaluatorEncoding.Code p.extra M} {bit : Bool} {a : Instruction p.extra}
+ (hl : PrepLayout p pub M) (ho : ConfigAt m (pub 1) old) (hz : ConfigAt m (pub 2) out)
+ (ha : LiveEvaluatorAction.pick p old bit = some a) :
+ let mem := preparedMemory p pub m old a
+ ConfigAt mem (pub 1) old ∧ ConfigAt mem (pub 2) out ∧
+ ActionAt mem (pub 3) a.target.val a.firstSymbol a.firstMove a.secondSymbol a.secondMove := by
+ let s := recordRegs p pub m old a
+ have h4 : 4 ≤ 2^w := Nat.pow_le_pow_right (by decide : 0 < 2) hl.width
+ obtain ⟨-, h1, -, h25⟩ := record_frame (pub := pub) (m := m) old a
+ have hu : (s 1).val = 1 := (congrArg Fin.val h1).trans (numeral_val (n := 1) (by omega))
+ have hbase : s 25 = pub 3 := h25
+ have hfit : (s 25).val + 5 ≤ 2^w := hbase ▸ hl.scratchFit
+ obtain ⟨h5, h6, h7, h8, h9⟩ := record_fields (m := m) hl ha
+ refine ⟨ho.after_scratch s hu hfit hl.oldFit (hbase ▸ hl.oldDisjoint),
+ hz.after_scratch s hu hfit hl.outFit (hbase ▸ hl.outDisjoint), ?_⟩
+ rw [← hbase]
+ exact actionAt_scratch hu hfit h5 h6 h7 h8 h9
+
+end LiveEvaluatorRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMSchedule.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMSchedule.lean
new file mode 100644
index 0000000000..7a36da0e40
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMSchedule.lean
@@ -0,0 +1,352 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMPrepare
+import OAI.Computability.VPVNP.PrimedCounterCall
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import Mathlib.Data.ZMod.Defs
+import Mathlib.Tactic.Ring
+
+/-!
+# Scheduled burst calls for one live evaluator transition
+
+Cursor zero selects the transition and saves its five fields in external
+scratch. The following calls check one cell of the first tape and then one
+cell of the second tape. All four public words are lengths or addresses.
+The instruction table is independent of the radius, word width and addresses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM.Schedule
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+
+/-- A native block for the scheduled transition checker with four public operands. -/
+abbrev Block := LiveEvaluatorRAM.Code 4
+/-- The operand indices for window radius, old configuration, proposed configuration, and
+instruction scratch. -/
+abbrev Pub := Fin 4
+/-- A single scheduled transition-checker operation over its 32 registers and four public
+operands. -/
+abbrev Op := PrimedStackRAM.Op 32 4
+
+variable {w : ℕ}
+
+/-- Sequence of one or more elementary opcodes in their indicated order. -/
+private def ops (a : Op) (rest : List Op) : Block :=
+ PrimedStackRAM.straight a rest
+
+/-- Public words are radius, old configuration base, new configuration base,
+and the base of five scratch words. The old state is read once per call. -/
+def load : Block := ops (.constant 0 0)
+ [.constant 1 1, .constant 2 2, .constant 3 3, .publicWord 11 0, .binary .add 12 11 11,
+ .binary .add 22 12 1, .publicWord 23 1, .publicWord 24 2, .publicWord 25 3,
+ .stateWord 26, .read 16 23]
+
+/-- Select the first tape and its first write/move pair in scratch. -/
+private def first : Block := ops (.binary .add 14 23 1)
+ [.binary .add 15 24 1, .binary .add 20 25 1]
+
+/-- Select the second tape, subtract the first tape length from the old cell
+index, and select its second write/move pair in scratch. -/
+private def second : Block := ops (.binary .sub 13 13 22)
+ [.binary .add 14 23 1, .binary .add 14 14 22, .binary .add 15 24 1,
+ .binary .add 15 15 22, .binary .add 20 25 3]
+
+/-- Read the target state and the write/move pair of the scheduled tape. -/
+def locate : Block :=
+ .seq (ops (.binary .sub 13 26 1) [.read 5 25])
+ (.seq (.ifLt 13 22 first second)
+ (ops (.read 6 20) [.binary .add 20 20 1, .read 7 20]))
+
+/-- Compute the next cursor and total number of calls afresh after checking
+the cell. This also works after the first call's transition dispatch. -/
+def finish : Block := ops (.stateWord 29)
+ [.constant 1 1, .binary .add 29 29 1, .publicWord 30 0, .binary .add 30 30 30,
+ .binary .add 30 30 1, .binary .add 30 30 30, .binary .add 30 30 1]
+
+/-- At cursor zero prepare a transition, otherwise locate and check the indexed tape cell, then
+compute the return cursor. -/
+def body (prepare : Block) : Block :=
+ .seq load (.seq (.ifEq 26 0 prepare (.seq locate cell)) finish)
+
+/-- The burst-call template for the transition schedule with its supplied
+instruction-preparation block. -/
+def table (prepare : Block) := PrimedCounter.Call.template (body prepare) 29 30
+
+/-- One dispatch, followed by a visit to every cell in each tape window. -/
+def calls (M : ℕ) := 1 + 2 * (2 * M + 1)
+
+/-- Whether a cell-check ordinal belongs to the first tape's window. -/
+def isFirst {M : ℕ} (i : Fin (2 * (2 * M + 1))) := i.val < 2 * M + 1
+
+/-- The scheduled visits form a bijection between the two tape fields and
+the noninitial calls, in tape order and increasing cell order. -/
+def visit (M : ℕ) : (Fin 2 × Fin (2 * M + 1)) ≃ Fin (2 * (2 * M + 1)) := finProdFinEquiv
+
+@[simp] theorem visit_first {M : ℕ} (j : Fin (2 * M + 1)) :
+ (visit M (0, j)).val = j.val := by simp [visit, finProdFinEquiv]
+
+@[simp] theorem visit_second {M : ℕ} (j : Fin (2 * M + 1)) :
+ (visit M (1, j)).val = j.val + (2 * M + 1) := by simp [visit, finProdFinEquiv]
+
+/-- Apply an ordered list of word assignments to the evaluator register bank. -/
+def install (rs : Regs w 32) (fields : List (Reg × Word w)) : Regs w 32 :=
+ fields.foldl (fun r x => Function.update r x.1 x.2) rs
+
+/-- The register bank after loading the radius, configuration and scratch addresses, persistent
+cursor, and old control word. -/
+def loaded (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (m : Memory w) : Regs w 32 :=
+ let M := pub 0
+ install rs [(0, 0), (1, 1), (2, 2), (3, 3), (11, M), (12, M + M), (22, M + M + 1),
+ (23, pub 1), (24, pub 2), (25, pub 3), (26, state), (16, m (pub 1).val)]
+
+/-- A complete register-bank witness and event trace for the common prefix. -/
+theorem load_exec (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (m : Memory w) :
+ Flow.Exec pub state load rs m
+ (List.replicate 11 .tick ++ [.read (pub 1) (m (pub 1).val)]) (loaded pub state rs m) m :=
+ (Flow.once_sound pub state false load rs m rfl).1
+
+/-- Selected tape index, bases, target, write symbol and move after three
+reads from the five words saved by the preparation call. -/
+def located (rs : Regs w 32) (m : Memory w) : Regs w 32 :=
+ let i := rs 26 - rs 1
+ let a := install rs [(13, i), (5, m (rs 25).val)]
+ let b := if i < rs 22 then
+ install a [(14, rs 23 + rs 1), (15, rs 24 + rs 1), (20, rs 25 + rs 1)]
+ else
+ install a [(13, i - rs 22), (14, rs 23 + rs 1), (14, rs 23 + rs 1 + rs 22),
+ (15, rs 24 + rs 1), (15, rs 24 + rs 1 + rs 22), (20, rs 25 + rs 3)]
+ let addr := if i < rs 22 then rs 25 + rs 1 else rs 25 + rs 3
+ install b [(6, m addr.val), (20, addr + rs 1), (7, m (addr + rs 1).val)]
+
+/-- The read of the selected target and the reads of the write symbol and motion for the tape
+chosen by the cursor. -/
+def locateEvents (rs : Regs w 32) (m : Memory w) : List (Event w) :=
+ let f := rs 26 - rs 1 < rs 22
+ let addr := if f then rs 25 + rs 1 else rs 25 + rs 3
+ [.tick, .read (rs 25) (m (rs 25).val), .tick] ++ List.replicate (if f then 3 else 6) .tick ++
+ [.read addr (m addr.val), .tick, .read (addr + rs 1) (m (addr + rs 1).val)]
+
+theorem locate_exec (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (m : Memory w) :
+ Flow.Exec pub state locate rs m (locateEvents rs m) (located rs m) m := by
+ apply (Flow.once_sound pub state false locate rs m ?_).1
+ by_cases h : rs 26 - rs 1 < rs 22
+ all_goals simp only [locateEvents, located, h, ↓reduceIte]
+ all_goals
+ simp (config := { decide := true }) [locate, ops, PrimedStackRAM.straight, Flow.once, Op.effect, BinaryOp.eval, pure, bind, h]
+ rfl
+
+/-- Closing register bank has successor cursor and total call count. -/
+def finished (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) : Regs w 32 :=
+ let M := pub 0
+ let last := M + M
+ let width := last + 1
+ install rs [(29, state), (1, 1), (29, state + 1), (30, M), (30, last), (30, width),
+ (30, width + width), (30, width + width + 1)]
+
+theorem finish_exec (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) (m : Memory w) :
+ Flow.Exec pub state finish rs m (List.replicate 8 .tick) (finished pub state rs) m :=
+ (Flow.once_sound pub state false finish rs m rfl).1
+
+theorem finish_next (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) :
+ finished pub state rs 29 = state + 1 := rfl
+
+open scoped Fin.CommRing in
+theorem finish_total (pub : Pub → Word w) (state : Word w) (rs : Regs w 32) :
+ finished pub state rs 30 = (calls (pub 0).val : Word w) := by
+ change (pub 0 + pub 0 + 1) + (pub 0 + pub 0 + 1) + 1 = _
+ simp only [calls, Nat.cast_add, Nat.cast_mul, Nat.cast_one, Nat.cast_ofNat, Fin.cast_val_eq_self]
+ ring
+
+theorem body_loopFree (prepare : Block) (h : loopFree prepare = true) :
+ loopFree (body prepare) = true := by
+ change (true && ((loopFree prepare && true) && true)) = true
+ simp [h]
+
+/-- Actual word program for every scheduled call of a fixed evaluator. -/
+def program (p : UniversalMachine.Program) := table (LiveEvaluatorRAMPrepare.prepare p)
+
+theorem program_bound (p : UniversalMachine.Program) {pub : Pub → Word w} {state : Word w}
+ {rs m es out mem} (run : Flow.Exec pub state (body (LiveEvaluatorRAMPrepare.prepare p)) rs m es out mem) :
+ es.length ≤ (body (LiveEvaluatorRAMPrepare.prepare p)).length :=
+ length_le_of_loopFree run (body_loopFree _ (LiveEvaluatorRAMPrepare.prepare_loopFree p))
+
+private def deterministic : Block → Bool
+ | .line _ => true
+ | .seq a b | .ifEq _ _ a b | .ifLt _ _ a b => deterministic a && deterministic b
+ | .branch .. | .whileLt .. => false
+
+private theorem once_of_exec {pub : Pub → Word w} {st : Word w} {a : Block} {rs m es out mem}
+ (run : Flow.Exec pub st a rs m es out mem) (h : deterministic a = true) :
+ Flow.once pub st false a rs m = some (es, out, mem) := by
+ induction run with
+ | line he => simp [Flow.once, he]
+ | seq _ _ ia ib =>
+ simp only [deterministic, Bool.and_eq_true] at h
+ simp [Flow.once, ia h.1, ib h.2]
+ | ifEqYes ht _ ih | ifLtYes ht _ ih =>
+ simp only [deterministic, Bool.and_eq_true] at h
+ simp only [Flow.once, ht, ite_true, ih h.1, Option.map_some]
+ rfl
+ | ifEqNo ht _ ih | ifLtNo ht _ ih =>
+ simp only [deterministic, Bool.and_eq_true] at h
+ simp only [Flow.once, ht, ite_false, ih h.2, Option.map_some]
+ rfl
+ | branchYes | branchNo | whileDone | whileStep => contradiction
+
+private theorem unique_exec {pub : Pub → Word w} {st : Word w} {a : Block} {rs m es out mem fs r' m'}
+ (ha : deterministic a = true) (x : Flow.Exec pub st a rs m es out mem)
+ (y : Flow.Exec pub st a rs m fs r' m') :
+ es = fs ∧ out = r' ∧ mem = m' := by
+ simpa using (once_of_exec x ha).symm.trans (once_of_exec y ha)
+
+private theorem exits_unique {pub : Pub → Word w} {st : Word w} {a : Block} {rs m es out mem}
+ (ha : deterministic a = true) (run : Flow.Exec pub st a rs m es out mem)
+ (post : Regs w 32 → Memory w → Prop) :
+ exits pub st a rs m post ↔ post out mem := by
+ constructor
+ · rintro ⟨_, _, _, hy, hp⟩
+ obtain ⟨rfl, rfl, rfl⟩ := unique_exec ha run hy
+ exact hp
+ · exact fun hp => ⟨_, _, _, run, hp⟩
+
+/-- At cursor zero the body executes preparation. At all other cursors it
+checks exactly the addressed cell. Both phases compute the successor cursor
+in the same final fragment. This equivalence holds on arbitrary memory. -/
+theorem body_exits (p : UniversalMachine.Program) (pub : Pub → Word w) (st : Word w)
+ (rs : Regs w 32) (m : Memory w) (post : Regs w 32 → Memory w → Prop) :
+ let pre := loaded pub st rs m
+ let close := fun out mem => post (finished pub st out) mem
+ exits pub st (body (LiveEvaluatorRAMPrepare.prepare p)) rs m post ↔
+ if st = 0 then exits pub st (LiveEvaluatorRAMPrepare.prepare p) pre m close
+ else exits pub st cell (located pre m) m close := by
+ dsimp only
+ rw [body, exits_seq, exits_unique (by rfl) (load_exec ..), exits_seq, exits_ifEq]
+ have h (a : Block) (r : Regs w 32) (u : Memory w) :
+ exits pub st a r u (fun r' u' => exits pub st finish r' u' post) ↔
+ exits pub st a r u (fun r' u' => post (finished pub st r') u') := by
+ have e (r' : Regs w 32) (u' : Memory w) :=
+ exits_unique (by rfl) (finish_exec pub st r' u') post
+ have heq : (fun r' u' => exits pub st finish r' u' post) =
+ (fun r' u' => post (finished pub st r') u') := funext fun r' => funext fun u' => propext (e r' u')
+ rw [heq]
+ change (if st = 0 then _ else _) ↔ _
+ split
+ · exact h ..
+ · rw [exits_seq, exits_unique (by rfl) (locate_exec ..), h]
+
+theorem noninitial_call_iff (p : UniversalMachine.Program) (pub : Pub → Word w) {st : Word w}
+ (hs : st ≠ 0) (rs : Regs w 32) (m : Memory w) :
+ (∃ es out mem, Flow.Exec pub st (body (LiveEvaluatorRAMPrepare.prepare p)) rs m es out mem) ↔
+ cellTest (located (loaded pub st rs m) m) m := by
+ have he := body_exits p pub st rs m (fun _ _ => True)
+ simpa only [ite_eq_right hs, exits, and_true, cell_exec_iff] using he
+
+/-- Every normal exit publishes the successor and the total, including a
+branch of the preparation call that changes external scratch memory. -/
+theorem body_cursor {p : UniversalMachine.Program} {pub : Pub → Word w} {st : Word w}
+ {rs m es out mem} (run : Flow.Exec pub st (body (LiveEvaluatorRAMPrepare.prepare p)) rs m es out mem) :
+ out 29 = st + 1 ∧ out 30 = Fin.ofNat (2 ^ w) (calls (pub 0).val) := by
+ cases run with
+ | seq _ tail =>
+ cases tail with
+ | seq _ close =>
+ obtain ⟨_, rfl, _⟩ := unique_exec (by rfl) close (finish_exec ..)
+ exact ⟨finish_next .., finish_total ..⟩
+
+/-- Exact native report, with surplus choice bits rejected at the common
+exit. Only the final cell accepts instead of returning another cursor. -/
+theorem execute_call {p : UniversalMachine.Program} {pub : Pub → Word w} {st : Word w}
+ {rs m es out mem} (run : Flow.Exec pub st (body (LiveEvaluatorRAMPrepare.prepare p)) rs m es out mem)
+ (privateMem : Word w → Word w) (extra : List Bool) (fuel : ℕ) :
+ let machine := (program p).instantiate w pub
+ execute machine.program (es.length + (fuel + 2)) ⟨machine.entry, st, rs, privateMem⟩ m
+ (choiceBits es ++ extra) =
+ if extra.isEmpty then some ⟨es ++ [.tick],
+ if st + 1 = Fin.ofNat (2 ^ w) (calls (pub 0).val) then none else some (st + 1)⟩ else none := by
+ obtain ⟨hn, ht⟩ := body_cursor run
+ simpa only [program, table, hn, ht] using
+ PrimedCounter.Call.execute_body _ 29 30 pub st rs privateMem m run extra fuel
+
+private theorem phase_run {pub : Pub → Word w} {st : Word w} {p : UniversalMachine.Program}
+ {rs m es out mem} (run : Flow.Exec pub st (body (LiveEvaluatorRAMPrepare.prepare p)) rs m es out mem)
+ (hs : st ≠ 0) :
+ ∃ fs rc, Flow.Exec pub st cell (located (loaded pub st rs m) m) m fs rc mem ∧
+ es = (List.replicate 11 .tick ++ [.read (pub 1) (m (pub 1).val)]) ++
+ .tick :: ((locateEvents (loaded pub st rs m) m ++ fs) ++ List.replicate 8 .tick) := by
+ cases run with
+ | seq pre tail =>
+ obtain ⟨rfl, rfl, rfl⟩ := unique_exec (by rfl) pre (load_exec ..)
+ cases tail with
+ | seq test close =>
+ obtain ⟨rfl, rfl, rfl⟩ := unique_exec (by rfl) close (finish_exec ..)
+ cases test with
+ | ifEqYes ht _ => exact (hs ht).elim
+ | ifEqNo _ data =>
+ cases data with
+ | seq loc checks =>
+ obtain ⟨rfl, rfl, rfl⟩ := unique_exec (by rfl) loc (locate_exec ..)
+ exact ⟨_, _, checks, by simp⟩
+
+/-- Noninitial calls read the old state, three scratch words, one input
+cell and one output cell. They never write or consume a choice. -/
+theorem cell_call_cost {pub : Pub → Word w} {st : Word w} {p : UniversalMachine.Program} {rs m es out mem}
+ (run : Flow.Exec pub st (body (LiveEvaluatorRAMPrepare.prepare p)) rs m es out mem) (hs : st ≠ 0) :
+ mem = m ∧ choiceBits es = [] ∧ countProbes es = 6 := by
+ obtain ⟨fs, rc, hr, rfl⟩ := phase_run run hs
+ obtain ⟨rfl, hb, hc, _⟩ := cell_cost hr
+ have probes (xs ys : List (Event w)) : countProbes (xs ++ ys) = countProbes xs + countProbes ys := by
+ induction xs with
+ | nil => simp [countProbes]
+ | cons e xs ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+ dsimp only [locateEvents]
+ split_ifs <;> simp [probes, Flow.choiceBits_append, List.replicate_succ, choiceBits, countProbes, hb, hc]
+
+/-- The initial call has exactly the preparation fragment's branch choices
+and final scratch memory. Loading the public geometry and closing the
+cursor are deterministic, including on an initially accepting evaluator. -/
+theorem initial_choices_iff (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (rs : Regs w 32) (m mem : Memory w) (bs : List Bool) :
+ (∃ es out, Flow.Exec pub 0 (body (LiveEvaluatorRAMPrepare.prepare p)) rs m es out mem ∧
+ choiceBits es = bs) ↔
+ ∃ es out, Flow.Exec pub 0 (LiveEvaluatorRAMPrepare.prepare p) (loaded pub 0 rs m) m es out mem ∧
+ choiceBits es = bs := by
+ constructor
+ · rintro ⟨_, _, run, hb⟩
+ cases run with
+ | seq pre tail =>
+ obtain ⟨rfl, rfl, rfl⟩ := unique_exec (by rfl) pre (load_exec ..)
+ cases tail with
+ | seq test close =>
+ obtain ⟨rfl, rfl, rfl⟩ := unique_exec (by rfl) close (finish_exec ..)
+ cases test with
+ | ifEqNo ht _ => exact (ht rfl).elim
+ | ifEqYes _ h =>
+ exact ⟨_, _, h, by simpa [Flow.choiceBits_append, List.replicate_succ, choiceBits] using hb⟩
+ · rintro ⟨es, out, h, hb⟩
+ refine ⟨_, _, .seq (load_exec ..) (.seq (.ifEqYes rfl h) (finish_exec ..)), ?_⟩
+ simp [Flow.choiceBits_append, List.replicate_succ, choiceBits, hb]
+
+/-- The only choice list of a successful cell call is empty, its memory is
+unchanged, and its local success predicate is exactly the cell comparison. -/
+theorem noninitial_choices_iff (p : UniversalMachine.Program) (pub : Pub → Word w) {st : Word w}
+ (hs : st ≠ 0) (rs : Regs w 32) (m mem : Memory w) (bs : List Bool) :
+ (∃ es out, Flow.Exec pub st (body (LiveEvaluatorRAMPrepare.prepare p)) rs m es out mem ∧
+ choiceBits es = bs) ↔
+ cellTest (located (loaded pub st rs m) m) m ∧ bs = [] ∧ mem = m := by
+ constructor
+ · rintro ⟨es, out, run, hb⟩
+ obtain ⟨hm, he, _⟩ := cell_call_cost run hs
+ exact ⟨(noninitial_call_iff p pub hs rs m).mp ⟨_, _, _, run⟩, hb.symm.trans he, hm⟩
+ · rintro ⟨hc, hb, hm⟩
+ subst bs mem
+ obtain ⟨es, out, mem, run⟩ := (noninitial_call_iff p pub hs rs m).mpr hc
+ obtain ⟨rfl, hb, _⟩ := cell_call_cost run hs
+ exact ⟨es, out, run, hb⟩
+
+end LiveEvaluatorRAM.Schedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMScheduleData.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMScheduleData.lean
new file mode 100644
index 0000000000..f8ba6ec17e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMScheduleData.lean
@@ -0,0 +1,139 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMSchedule
+import OAI.Computability.VPVNP.LiveEvaluatorRAMCell
+import OAI.Computability.VPVNP.LiveEvaluatorRAMImage
+
+/-!
+# Scheduled cell operands in the actual live configuration memory
+
+The noninitial call numbers enumerate first the old cells of tape one and
+then the old cells of tape two. Reconstructing the private registers from
+each call number supplies exactly the operands required by the cell test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM.Schedule
+
+open BurstRAM PrimedStackRAM LiveEvaluatorEncoding
+open scoped Fin.CommRing
+
+variable {w M extra : ℕ}
+
+/-- The one-based persistent call cursor for a selected tape and cell. -/
+def cellCursor (second : Bool) (i : Fin (2 * M + 1)) :=
+ (if second then 2 * M + 1 else 0) + i.val + 1
+
+theorem cellCursor_lt_calls (second : Bool) (i : Fin (2 * M + 1)) :
+ cellCursor second i < calls M := by
+ cases second <;> simp [cellCursor, calls] <;> omega
+
+theorem cellCursor_word_ne_zero (second : Bool) (i : Fin (2 * M + 1)) (hc : calls M < 2 ^ w) :
+ (cellCursor second i : Word w) ≠ 0 := by
+ have h := (cellCursor_lt_calls second i).trans hc
+ rw [ne_eq, Fin.ext_iff, Fin.val_natCast, Nat.mod_eq_of_lt h, Fin.val_zero]
+ simp [cellCursor]
+
+/-- Every noninitial call below the accepting cursor visits exactly one
+tape and cell. -/
+theorem exists_unique_visit {c : ℕ} (hp : 0 < c) (hc : c < calls M) :
+ ∃! x : Bool × Fin (2 * M + 1), cellCursor x.1 x.2 = c := by
+ unfold calls at hc
+ by_cases h : c ≤ 2 * M + 1
+ · refine ⟨(false, ⟨c-1, by omega⟩), by simp [cellCursor]; omega, ?_⟩
+ rintro ⟨b, j⟩ hj
+ cases b <;> simp [cellCursor] at hj ⊢
+ · apply Fin.ext; dsimp; omega
+ · omega
+ · refine ⟨(true, ⟨c - (2*M+1) - 1, by omega⟩), by simp [cellCursor]; omega, ?_⟩
+ rintro ⟨b, j⟩ hj
+ cases b <;> simp [cellCursor] at hj ⊢
+ · omega
+ · apply Fin.ext; dsimp; omega
+
+/-- The literal selected tape, including the canonical blank tapes at halts. -/
+def window (s : LiveEvaluatorEncoding.Code extra M) (second : Bool) : TapeWindow M :=
+ ⟨if second then s.secondCell else s.firstCell⟩
+
+/-- Reconstruct the register bank used by the elementary cell fragment. -/
+def bank (pub : Pub → Word w) (rs : Regs w 32) (m : Memory w)
+ (second : Bool) (i : Fin (2 * M + 1)) : Regs w 32 :=
+ located (loaded pub (cellCursor second i : Word w) rs m) m
+
+/-- The start address of the selected tape window within a serialized configuration. -/
+def baseOf (addr : Word w) (M : ℕ) (second : Bool) : Word w :=
+ if second then addr + 1 + ((2 * M + 1 : ℕ) : Word w) else addr + 1
+
+/-- The instruction-scratch address of the proposed write symbol for the selected tape. -/
+def writeAddr (addr : Word w) (second : Bool) := if second then addr + 3 else addr + 1
+
+theorem bank_operands (pub : Pub → Word w) (rs : Regs w 32) (m : Memory w)
+ (second : Bool) (i : Fin (2 * M + 1)) (hM : (pub 0).val = M) (hc : calls M < 2 ^ w) :
+ let r := bank pub rs m second i
+ r 0 = 0 ∧ r 1 = 1 ∧ r 3 = 3 ∧ r 5 = m (pub 3).val ∧
+ r 6 = m (writeAddr (pub 3) second).val ∧ r 7 = m (writeAddr (pub 3) second + 1).val ∧
+ r 11 = (M : Word w) ∧ r 12 = ((2 * M : ℕ) : Word w) ∧ r 13 = (i.val : Word w) ∧
+ r 14 = baseOf (pub 1) M second ∧ r 15 = baseOf (pub 2) M second ∧ r 16 = m (pub 1).val := by
+ have hM' : pub 0 = (M : Word w) := by rw [← hM, Fin.cast_val_eq_self]
+ let N := 2 * M + 1
+ have hN : N < 2 ^ w := by unfold N calls at *; omega
+ have hNN : N + i.val < 2 ^ w := by have := i.isLt; unfold N calls at *; omega
+ cases second with
+ | false =>
+ have hi : (cellCursor false i : Word w) - 1 = (i.val : Word w) := by simp [cellCursor]
+ have hlt : (i.val : Word w) < (N : Word w) := by
+ rw [Fin.lt_def, Fin.val_natCast, Fin.val_natCast, Nat.mod_eq_of_lt (i.isLt.trans hN),
+ Nat.mod_eq_of_lt hN]
+ exact i.isLt
+ have hh : (i.val : Word w) < (M : Word w) + M + 1 := by simpa [N, two_mul] using hlt
+ simp (config := { decide := true }) [bank, located, loaded, install, baseOf, writeAddr,
+ Function.update, hi, hh, hM', two_mul]
+ | true =>
+ have hi : (cellCursor true i : Word w) - 1 = ((N + i.val : ℕ) : Word w) := by simp [cellCursor, N]
+ have hlt : ¬ ((N + i.val : ℕ) : Word w) < (N : Word w) := by
+ rw [Fin.lt_def, Fin.val_natCast, Fin.val_natCast, Nat.mod_eq_of_lt hNN, Nat.mod_eq_of_lt hN]
+ omega
+ have hh : ¬(M : Word w) + M + 1 + (i.val : Word w) < (M : Word w) + M + 1 := by
+ simpa [N, two_mul] using hlt
+ simp (config := { decide := true }) [bank, located, loaded, install, baseOf, writeAddr,
+ Function.update, hi, hh, hM', N, two_mul]
+
+/-- Every actual scheduled register bank refers to the right tape cells,
+source and target states, and the instruction fields saved in scratch. -/
+theorem scheduled_tape_data (pub : Pub → Word w) (rs : Regs w 32) (m : Memory w)
+ (old out : LiveEvaluatorEncoding.Code extra M)
+ (fw fm sw sm : UniversalMachine.Symbol) (second : Bool) (i : Fin (2 * M + 1))
+ (hw : 2 ≤ w) (hM : (pub 0).val = M) (hc : calls M < 2 ^ w)
+ (ho : ConfigAt m (pub 1) old) (hn : ConfigAt m (pub 2) out)
+ (ha : ActionAt m (pub 3) out.stateWord.val fw fm sw sm) :
+ let r := bank pub rs m second i
+ TapeCellData r m (window old second) (window out second)
+ (if second then sw else fw) (if second then sm else fm) i ∧
+ (r 5).val = out.stateWord.val ∧ (r 16).val = old.stateWord.val := by
+ let r := bank pub rs m second i
+ obtain ⟨h0, h1, h3, h5, h6, h7, h11, h12, h13, h14, h15, h16⟩ := bank_operands pub rs m second i hM hc
+ refine ⟨?_, (congrArg Fin.val h5).trans ha.targetVal, (congrArg Fin.val h16).trans ho.state⟩
+ have h4 : 4 ≤ 2 ^ w := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ have hcap : 2 * M + 1 < 2 ^ w := by unfold calls at hc; omega
+ constructor
+ · rw [h0]; rfl
+ · rw [h1]; exact Nat.mod_eq_of_lt (by omega : (1 : ℕ) < 2 ^ w)
+ · rw [h3]; exact Nat.mod_eq_of_lt (by omega : (3 : ℕ) < 2 ^ w)
+ · rw [h6]; cases second <;> first | exact ha.firstWriteVal | exact ha.secondWriteVal
+ · rw [h7]; cases second <;> simp only [writeAddr, Bool.false_eq_true, ↓reduceIte]
+ · rw [show pub 3 + 1 + 1 = pub 3 + 2 by ring]; exact ha.firstMoveVal
+ · rw [show pub 3 + 3 + 1 = pub 3 + 4 by ring]; exact ha.secondMoveVal
+ · rw [h11, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ · rw [h12, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ · rw [h13, Fin.val_natCast, Nat.mod_eq_of_lt (i.isLt.trans hcap)]
+ · rw [h14, h13]; cases second <;> first | exact ho.first i | exact ho.second i
+ · intro j f hj
+ have he : j = (f.val : Word w) := by rw [← hj, Fin.cast_val_eq_self]
+ rw [h15, he]; cases second <;> first | exact hn.first f | exact hn.second f
+
+end LiveEvaluatorRAM.Schedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMScratchImage.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMScratchImage.lean
new file mode 100644
index 0000000000..c793240b94
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMScratchImage.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMImage
+import OAI.Computability.VPVNP.LiveEvaluatorRAMSchedule
+
+/-!
+# Memory images after publishing an evaluator instruction
+
+The native preparation writes the five instruction registers in scratch. A
+disjoint configuration still decodes to the same bounded evaluator state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM
+
+open BurstRAM (Word Memory)
+open PrimedStackRAM (Regs)
+open UniversalMachine (Symbol Instruction)
+open LiveEvaluatorRAMPrepare (scratchMemory scratchMemory_at scratchMemory_outside carryRegs selectedRegs)
+open scoped Fin.CommRing
+
+variable {w M extra : ℕ}
+
+/-- The five register values published by preparation constitute the memory
+image read by all subsequent scheduled cells. -/
+theorem actionAt_scratch {rs : Regs w 32} {m : Memory w} {target : ℕ}
+ {firstWrite firstMove secondWrite secondMove : Symbol}
+ (h1 : (rs 1).val = 1) (hs : (rs 25).val + 5 ≤ 2 ^ w)
+ (h5 : (rs 5).val = target) (h6 : (rs 6).val = firstWrite.val)
+ (h7 : (rs 7).val = firstMove.val) (h8 : (rs 8).val = secondWrite.val)
+ (h9 : (rs 9).val = secondMove.val) :
+ ActionAt (scratchMemory rs m) (rs 25) target firstWrite firstMove secondWrite secondMove := by
+ have h (i : Fin 5) :
+ (scratchMemory rs m (rs 25 + (i.val : Word w)).val).val = (rs ⟨5 + i.val, by omega⟩).val := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)]
+ exact congrArg Fin.val (scratchMemory_at rs m h1 hs i)
+ exact ⟨by simpa using (h 0).trans h5, (h 1).trans h6, (h 2).trans h7,
+ (h 3).trans h8, (h 4).trans h9⟩
+
+/-- Carrying an accepting evaluator publishes state one and four zero tape fields. -/
+theorem actionAt_carryRegs (rs : Regs w 32) (m : Memory w) (h0 : (rs 0).val = 0)
+ (h1 : (rs 1).val = 1) (hs : (rs 25).val + 5 ≤ 2 ^ w) :
+ ActionAt (scratchMemory (carryRegs rs) m) (rs 25) 1 0 0 0 0 :=
+ actionAt_scratch (rs := carryRegs rs) h1 hs h1 h0 h0 h0 h0
+
+/-- A selected table slot publishes all five fields of that instruction. -/
+theorem actionAt_selectedRegs (rs : Regs w 32) (m : Memory w) (a : Instruction extra)
+ (hw : 2 ≤ w) (hcap : extra + 2 ≤ 2 ^ w) (h1 : (rs 1).val = 1)
+ (hs : (rs 25).val + 5 ≤ 2 ^ w) :
+ ActionAt (scratchMemory (selectedRegs rs m a) m) (rs 25) a.target.val
+ a.firstSymbol a.firstMove a.secondSymbol a.secondMove := by
+ obtain ⟨h5, h6, h7, h8, h9⟩ := LiveEvaluatorRAMDispatch.instructionRegs_fields
+ (Function.update (LiveEvaluatorRAMPrepare.rowRegs rs m) 4 0) a hw hcap
+ exact actionAt_scratch (rs := selectedRegs rs m a) h1 hs h5 h6 h7 h8 h9
+
+/-- Configuration and scratch can be allocated in either order. The fit
+bounds ensure that neither block wraps in machine-word arithmetic. -/
+theorem ConfigAt.after_scratch {m : Memory w} {base : Word w} {c : LiveEvaluatorEncoding.Code extra M}
+ (hc : ConfigAt m base c) (rs : Regs w 32) (h1 : (rs 1).val = 1)
+ (hs : (rs 25).val + 5 ≤ 2 ^ w) (hfit : base.val + Schedule.calls M ≤ 2 ^ w)
+ (hdis : base.val + Schedule.calls M ≤ (rs 25).val ∨ (rs 25).val + 5 ≤ base.val) :
+ ConfigAt (scratchMemory rs m) base c := by
+ have h (i : ℕ) (hi : i < Schedule.calls M) :
+ scratchMemory rs m (base + (i : Word w)).val = m (base + (i : Word w)).val := by
+ apply scratchMemory_outside rs m h1 hs
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)]
+ omega
+ constructor
+ · have hz : scratchMemory rs m base.val = m base.val := by
+ simpa using h 0 (by simp [Schedule.calls])
+ rw [hz, hc.state]
+ · intro i
+ have hf := h (1 + i.val) (by unfold Schedule.calls; omega)
+ simp only [Nat.cast_add, Nat.cast_one, ← add_assoc] at hf
+ rw [hf, hc.first]
+ · intro i
+ have hf := h (1 + (2 * M + 1) + i.val) (by unfold Schedule.calls; omega)
+ rw [Nat.cast_add, Nat.cast_add, Nat.cast_one, ← add_assoc, ← add_assoc] at hf
+ rw [hf, hc.second]
+
+end LiveEvaluatorRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMSegment.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMSegment.lean
new file mode 100644
index 0000000000..47c6455c52
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMSegment.lean
@@ -0,0 +1,192 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMTranscript
+import OAI.Computability.VPVNP.LiveEvaluatorRAMPrepareImage
+import OAI.Computability.VPVNP.LiveEvaluatorCells
+import OAI.Computability.VPVNP.RAMChain
+
+/-!
+# Accepting paths of a complete live evaluator group
+
+The first call selects and publishes the action. The remaining calls each
+check one cell and preserve that memory. Acceptance of the actual native
+segment therefore fixes both the length of its branch stream and every entry
+after the first. The memory on which the cell tests run is the memory obtained
+by replaying the complete native report.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM.Schedule
+
+open BurstRAM
+open PrimedInputRAM (Flow)
+open LiveEvaluatorRAMPrepare (prepare)
+open LiveEvaluatorGroup (AllCells)
+open scoped Fin.CommRing
+
+variable {w M : ℕ}
+
+/-- The concrete interpreter halts on these branch lists and leaves the
+specified external memory. -/
+private def Finishes (p : UniversalMachine.Program) (pub : Pub → Word w) (s : Option (Word w))
+ (m : Memory w) (bits : List (List Bool)) (mem : Memory w) : Prop :=
+ ∃ rs, runSegment (nativeProgram p pub) (callFuel p) s m bits = some rs ∧
+ endState s rs = none ∧ after m (eventLog rs) = mem
+
+private theorem after_cons_report (m : Memory w) (r : Report w) (rs : List (Report w)) :
+ after m (eventLog (r :: rs)) = after (after m r.events) (eventLog rs) := by
+ simp [after, eventLog, List.foldl_append]
+
+private theorem finishes_cons (p : UniversalMachine.Program) (pub : Pub → Word w) (st : Word w)
+ (m : Memory w) (bs : List Bool) (tail : List (List Bool)) (mem : Memory w) :
+ Finishes p pub (some st) m (bs :: tail) mem ↔
+ ∃ mid, (∃ es out, Flow.Exec pub st (body (prepare p)) (fun _ => 0) m es out mid ∧
+ choiceBits es = bs) ∧ Finishes p pub (nextState pub st) mid tail mem := by
+ constructor
+ · rintro ⟨rs, hr, hhalt, hmem⟩
+ rw [runSegment] at hr
+ cases he : execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start st) m bs with
+ | none => simp [he] at hr
+ | some r =>
+ simp only [he, Option.map_eq_some_iff] at hr
+ obtain ⟨rest, hrest, rfl⟩ := hr
+ obtain ⟨es, out, mid, hbody, hbits, _, hstate, hmid⟩ := (nativeStep_iff ..).mp he
+ rw [hstate, hmid] at hrest
+ refine ⟨mid, ⟨es, out, hbody, hbits⟩, rest, hrest, ?_, ?_⟩
+ · simpa only [endState, hstate] using hhalt
+ · simpa only [after_cons_report, hmid] using hmem
+ · rintro ⟨mid, hbody, rest, hrest, hhalt, hmem⟩
+ obtain ⟨r, he, hmid⟩ := (nativeStep_exists_iff ..).mpr hbody
+ obtain ⟨_, _, _, _, _, _, hstate, _⟩ := (nativeStep_iff ..).mp he
+ refine ⟨r :: rest, ?_, ?_, ?_⟩
+ · simp only [runSegment, he, hstate, hmid, hrest, Option.map_some]
+ · simpa only [endState, hstate] using hhalt
+ · simpa only [after_cons_report, hmid] using hmem
+
+private def control (w total i : ℕ) : Option (Word w) :=
+ if i = total then none else some (i : Word w)
+
+private def cellAt (pub : Pub → Word w) (m : Memory w) (i : ℕ) : Prop :=
+ cellTest (located (loaded pub (i : Word w) (fun _ => 0) m) m) m
+
+private theorem cursor_ne_zero {i : ℕ} (hi : 0 < i) (hf : i < 2 ^ w) : (i : Word w) ≠ 0 := by
+ intro hz
+ have h := congrArg Fin.val hz
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt hf, Fin.val_zero] at h
+ omega
+
+/-- Starting in the cell scan, the only possible accepting stream consists
+of one empty entry per remaining cell. This includes the empty suffix at halt. -/
+private theorem scan_finishes (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (hfit : calls (pub 0).val ≤ 2 ^ w) (m mem : Memory w)
+ (n i : ℕ) (hi : 0 < i) (hcount : i + n = calls (pub 0).val) (bits : List (List Bool)) :
+ Finishes p pub (control w (calls (pub 0).val) i) m bits mem ↔
+ bits = List.replicate n [] ∧ m = mem ∧
+ ∀ j, i ≤ j → j < calls (pub 0).val → cellAt pub m j := by
+ induction n generalizing i bits with
+ | zero =>
+ simp only [Nat.add_zero] at hcount
+ subst i
+ cases bits <;> simp [Finishes, control, runSegment, endState, eventLog, after]
+ all_goals omega
+ | succ n ih =>
+ have hlt : i < calls (pub 0).val := by omega
+ have hn : nextState pub (i : Word w) = control w (calls (pub 0).val) (i+1) :=
+ nextState_at pub i hlt hfit
+ have hz := cursor_ne_zero hi (hlt.trans_le hfit)
+ rw [control, ite_eq_right hlt.ne]
+ cases bits with
+ | nil => simp [Finishes, runSegment, endState, List.replicate_succ]
+ | cons b tail =>
+ rw [finishes_cons, hn]
+ simp_rw [noninitial_choices_iff p pub hz]
+ constructor
+ · rintro ⟨mid, ⟨htest, rfl, rfl⟩, hr⟩
+ obtain ⟨rfl, hmem, htail⟩ := (ih (i+1) (by omega) (by omega) tail).mp hr
+ refine ⟨List.replicate_succ.symm, hmem, ?_⟩
+ intro j hj hbound
+ rcases hj.eq_or_lt with rfl | hlt'
+ · exact htest
+ · exact htail j hlt' hbound
+ · rw [List.replicate_succ, List.cons.injEq]
+ rintro ⟨⟨rfl, htail⟩, hmem, hc⟩
+ exact ⟨m, ⟨hc i le_rfl hlt, rfl, rfl⟩, (ih (i+1) (by omega) (by omega) tail).mpr
+ ⟨htail, hmem, fun j hj => hc j (by omega)⟩⟩
+
+private theorem allCells_iff_interval (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (m : Memory w) (hfit : calls M ≤ 2 ^ w) :
+ AllCells M p pub m ↔ ∀ j, 1 ≤ j → j < calls M → cellAt pub m j := by
+ have phase (s : Bool) (i : Fin (2*M+1)) :
+ (∃ es regs mem, Flow.Exec pub (cellCursor s i : Word w) (body (prepare p))
+ (fun _ => 0) m es regs mem) ↔ cellAt pub m (cellCursor s i) :=
+ noninitial_call_iff p pub (cursor_ne_zero (by simp [cellCursor])
+ ((cellCursor_lt_calls s i).trans_le hfit)) _ m
+ constructor
+ · intro hall j hj hlt
+ by_cases hfirst : j ≤ 2*M+1
+ · let i : Fin (2*M+1) := ⟨j-1, by omega⟩
+ have h : cellCursor false i = j := by simp [cellCursor, i]; omega
+ rw [← h]
+ exact (phase false i).mp (hall false i)
+ · let i : Fin (2*M+1) := ⟨j-(2*M+1)-1, by unfold calls at hlt; omega⟩
+ have h : cellCursor true i = j := by simp [cellCursor, i]; omega
+ rw [← h]
+ exact (phase true i).mp (hall true i)
+ · intro hall s i
+ exact (phase s i).mpr (hall _ (by simp [cellCursor]) (cellCursor_lt_calls s i))
+
+/-- Exact path and final-memory characterization for the actual group program.
+The first choice list survives, including when two slots publish equal records. -/
+theorem acceptedSegment_iff (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (m mem : Memory w) (bits : List (List Bool)) (hM : (pub 0).val = M)
+ (hfit : calls M ≤ 2 ^ w) :
+ (∃ rs, runSegment (nativeProgram p pub) (callFuel p) (some 0) m bits = some rs ∧
+ endState (some 0) rs = none ∧ after m (eventLog rs) = mem) ↔
+ ∃ bs, bits = bs :: List.replicate (2*(2*M+1)) [] ∧
+ Prepared p pub m mem bs ∧ AllCells M p pub mem := by
+ subst M
+ change Finishes p pub (some 0) m bits mem ↔ _
+ have hpos : 0 < calls (pub 0).val := by simp [calls]
+ have hn : nextState pub 0 = control w (calls (pub 0).val) 1 :=
+ nextState_at pub 0 hpos hfit
+ cases bits with
+ | nil => simp [Finishes, runSegment, endState]
+ | cons b tail =>
+ rw [finishes_cons, hn]
+ simp_rw [scan_finishes p pub hfit _ mem (2*(2*(pub 0).val+1)) 1 (by decide) rfl tail]
+ simp only [List.cons.injEq]
+ constructor
+ · rintro ⟨mid, hbody, htail, rfl, hall⟩
+ exact ⟨b, ⟨rfl, htail⟩, hbody, (allCells_iff_interval p pub mid hfit).mpr hall⟩
+ · rintro ⟨_, ⟨rfl, htail⟩, hbody, hall⟩
+ exact ⟨mem, hbody, htail, rfl, (allCells_iff_interval p pub mem hfit).mp hall⟩
+
+/-- A group path is determined by the first call's actual branch string.
+All successful cell calls consume empty strings. -/
+def actualPathEquiv (p : UniversalMachine.Program) (pub : Pub → Word w) (m : Memory w)
+ (hM : (pub 0).val = M) (hfit : calls M ≤ 2 ^ w) :
+ ActualPaths (nativeProgram p pub) (callFuel p) 0 m (fun _ => True) ≃
+ {bs : List Bool // ∃ mem, Prepared p pub m mem bs ∧ AllCells M p pub mem} where
+ toFun b := ⟨b.val.headD [], by
+ obtain ⟨rs, hr, hhalt, _⟩ := b.property
+ obtain ⟨bs, he, hp, hc⟩ := (acceptedSegment_iff p pub m _ b.val hM hfit).mp ⟨rs, hr, hhalt, rfl⟩
+ exact he ▸ ⟨_, hp, hc⟩⟩
+ invFun b := ⟨b.val :: List.replicate (2*(2*M+1)) [], by
+ obtain ⟨mem, hp, hc⟩ := b.property
+ obtain ⟨rs, hr, hhalt, _⟩ := (acceptedSegment_iff p pub m mem _ hM hfit).mpr ⟨b.val, rfl, hp, hc⟩
+ exact ⟨rs, hr, hhalt, trivial⟩⟩
+ left_inv b := by
+ apply Subtype.ext
+ obtain ⟨rs, hr, hhalt, _⟩ := b.property
+ obtain ⟨bs, he, _, _⟩ := (acceptedSegment_iff p pub m _ b.val hM hfit).mp ⟨rs, hr, hhalt, rfl⟩
+ change b.val.headD [] :: _ = b.val
+ rw [he]
+ rfl
+ right_inv _ := rfl
+
+end LiveEvaluatorRAM.Schedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMSegmentCost.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMSegmentCost.lean
new file mode 100644
index 0000000000..9e877a1441
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMSegmentCost.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMSegment
+import OAI.Computability.VPVNP.RAMSuccessor
+
+/-!
+# Native evaluator-group costs in the transcript model
+
+One cost unit pays for each call and one for each external probe. The first
+call costs eight units for an accepting carry and ten for a running source.
+Each of the two tape scans costs seven units per cell.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM.Schedule
+
+open BurstRAM
+open scoped Fin.CommRing
+
+variable {w M : ℕ}
+
+private theorem scan_resources (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (hfit : calls (pub 0).val ≤ 2 ^ w) (n i : ℕ) (hi : 0 < i) (hn : i+n = calls (pub 0).val)
+ (m : Memory w) (rs : List (Report w))
+ (hr : runSegment (nativeProgram p pub) (callFuel p)
+ (if i = calls (pub 0).val then none else some (i : Word w)) m (List.replicate n []) = some rs) :
+ RAMBuckets.cost Report.probes rs = 7*n ∧ rs.length = n ∧
+ ∀ r ∈ rs, r.probes = 6 ∧ r.events.length < callFuel p := by
+ induction n generalizing i rs m with
+ | zero =>
+ simp [runSegment] at hr
+ subst rs
+ simp [RAMBuckets.cost]
+ | succ n ih =>
+ have hlt : i < calls (pub 0).val := by omega
+ have hz : (i : Word w) ≠ 0 := by
+ intro he
+ have h := congrArg Fin.val he
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt (hlt.trans_le hfit), Fin.val_zero] at h
+ omega
+ rw [ite_eq_right hlt.ne, List.replicate_succ, runSegment] at hr
+ cases he : execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start (i : Word w)) m [] with
+ | none => simp [he] at hr
+ | some r =>
+ simp only [he, Option.map_eq_some_iff] at hr
+ obtain ⟨tail, htail, rfl⟩ := hr
+ obtain ⟨_, hmem, hprobes, hstate⟩ := nativeCell_report p pub (i : Word w) m [] r hz he
+ rw [hstate, show nextState pub (i : Word w) = _ from nextState_at pub i hlt hfit, hmem] at htail
+ obtain ⟨hcost, hlen, hcalls⟩ := ih (i+1) (by omega) (by omega) m tail htail
+ rw [RAMBuckets.cost, hprobes, hcost, List.length_cons, hlen, List.forall_mem_cons]
+ exact ⟨by omega, rfl, ⟨hprobes, nativeStep_report_length p pub _ m _ r he⟩, hcalls⟩
+
+/-- Exact total cost and call count, with a constant clock and probe cap on
+every report returned by an accepting native evaluator segment. -/
+theorem segmentResources (p : UniversalMachine.Program) (pub : Pub → Word w) (m : Memory w)
+ (bits : List (List Bool)) (rs : List (Report w)) (hM : (pub 0).val = M)
+ (hfit : calls M ≤ 2^w) (hw : 2 ≤ w) (hstates : p.extra+2 ≤ 2^w)
+ (hr : runSegment (nativeProgram p pub) (callFuel p) (some 0) m bits = some rs)
+ (hhalt : endState (some 0) rs = none) :
+ RAMBuckets.cost Report.probes rs = 1 + (if m (pub 1).val = 1 then 7 else 9) +
+ 7*(2*(2*M+1)) ∧ rs.length = calls M ∧
+ ∀ r ∈ rs, r.probes ≤ 9 ∧ r.events.length < callFuel p := by
+ subst M
+ obtain ⟨bs, rfl, _, _⟩ := (acceptedSegment_iff p pub m _ bits rfl hfit).mp ⟨rs, hr, hhalt, rfl⟩
+ rw [runSegment] at hr
+ cases he : execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start 0) m bs with
+ | none => simp [he] at hr
+ | some r =>
+ simp only [he, Option.map_eq_some_iff] at hr
+ obtain ⟨tail, htail, rfl⟩ := hr
+ obtain ⟨hprobes, _⟩ := nativePrepare_report p pub m bs r hw hstates he
+ obtain ⟨_, _, _, _, _, _, hstate, _⟩ := (nativeStep_iff ..).mp he
+ have hn := nextState_at pub 0 (by simp [calls]) hfit
+ rw [hstate, show nextState pub 0 = _ from hn] at htail
+ obtain ⟨hcost, hlen, hcalls⟩ := scan_resources p pub hfit _ 1 (by decide) rfl _ tail htail
+ rw [RAMBuckets.cost, hprobes, hcost, List.length_cons, hlen, List.forall_mem_cons]
+ refine ⟨rfl, by unfold calls; omega, ⟨?_, nativeStep_report_length p pub _ m _ r he⟩, ?_⟩
+ · rw [hprobes]; split <;> decide
+ · intro rep hrep
+ obtain ⟨h, hclock⟩ := hcalls rep hrep
+ exact ⟨by omega, hclock⟩
+
+/-- The native group lies within the successor-chain caps used in Lemma 10.1. -/
+theorem segmentWithinCaps (p : UniversalMachine.Program) (pub : Pub → Word w) (m : Memory w)
+ (bits : List (List Bool)) (rs : List (Report w)) (hM : (pub 0).val = M)
+ (hfit : calls M ≤ 2^w) (hw : 2 ≤ w) (hstates : p.extra+2 ≤ 2^w)
+ {S H : ℕ} (hcost : 10 + 7*(2*(2*M+1)) ≤ S*H) (hcap : 10 ≤ H)
+ (hr : runSegment (nativeProgram p pub) (callFuel p) (some 0) m bits = some rs)
+ (hhalt : endState (some 0) rs = none) : withinCaps S H rs := by
+ obtain ⟨ht, _, hc⟩ := segmentResources p pub m bits rs hM hfit hw hstates hr hhalt
+ constructor
+ · rw [ht]; split <;> omega
+ · intro r h
+ have := (hc r h).1
+ omega
+
+/-- Imposing the native transcript caps preserves each accepting branch path. -/
+def capPathEquiv (p : UniversalMachine.Program) (pub : Pub → Word w) (m : Memory w)
+ (hM : (pub 0).val = M) (hfit : calls M ≤ 2^w) (hw : 2 ≤ w) (hstates : p.extra+2 ≤ 2^w)
+ {S H : ℕ} (hcost : 10 + 7*(2*(2*M+1)) ≤ S*H) (hcap : 10 ≤ H) :
+ ActualPaths (nativeProgram p pub) (callFuel p) 0 m (withinCaps S H) ≃
+ ActualPaths (nativeProgram p pub) (callFuel p) 0 m (fun _ => True) where
+ toFun b := ⟨b.val, by
+ obtain ⟨rs, hr, ha, _⟩ := b.property
+ exact ⟨rs, hr, ha, trivial⟩⟩
+ invFun b := ⟨b.val, by
+ obtain ⟨rs, hr, ha, _⟩ := b.property
+ exact ⟨rs, hr, ha, segmentWithinCaps p pub m b.val rs hM hfit hw hstates hcost hcap hr ha⟩⟩
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+end LiveEvaluatorRAM.Schedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMTranscript.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMTranscript.lean
new file mode 100644
index 0000000000..0cb9dc2963
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRAMTranscript.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMSchedule
+import OAI.Computability.VPVNP.PrimedCounterCallPaths
+
+/-!
+# Native reports of scheduled live evaluator calls
+
+A scheduled call starts with zeroed registers and private memory, executes
+the fixed evaluator body, then compares the successor cursor with the call
+count. The comparison contributes one final tick to the report. The two
+footer instructions fit in a uniform allowance independent of the tape
+radius and word width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM.Schedule
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open UniversalMachine (Program)
+open LiveEvaluatorRAMPrepare (prepare)
+
+variable {w : ℕ}
+
+/-- The concrete finite program specialized only by the word width and its four public words. -/
+abbrev nativeProgram (p : UniversalMachine.Program) (pub : Pub → Word w) :=
+ ((program p).instantiate w pub).program
+
+/-- Enough fuel for every route through the acyclic body and both footer opcodes. -/
+def callFuel (p : UniversalMachine.Program) : ℕ := (body (prepare p)).length + 2
+
+/-- The terminal cursor comparison at the end of an actual call. -/
+def nextState (pub : Pub → Word w) (st : Word w) : Option (Word w) :=
+ if st + 1 = Fin.ofNat (2^w) (calls (pub 0).val) then none else some (st+1)
+
+/-- The allocated cursor sequence halts on its last call, even when the total
+number of calls is exactly the word modulus. -/
+theorem nextState_at (pub : Pub → Word w) (i : ℕ) (hi : i < calls (pub 0).val)
+ (hfit : calls (pub 0).val ≤ 2^w) :
+ nextState pub (Fin.ofNat (2^w) i) =
+ if i+1 = calls (pub 0).val then none else some (Fin.ofNat (2^w) (i+1)) := by
+ have hadd : Fin.ofNat (2^w) i + 1 = Fin.ofNat (2^w) (i+1) :=
+ Fin.ext (Nat.add_mod ..).symm
+ rw [nextState, hadd]
+ by_cases hl : i+1 = calls (pub 0).val
+ · simp [hl]
+ · have hsmall : i+1 < 2^w := by omega
+ have hne : Fin.ofNat (2^w) (i+1) ≠ Fin.ofNat (2^w) (calls (pub 0).val) := by
+ intro he
+ have hv := congrArg Fin.val he
+ change (i+1) % (2^w) = (calls (pub 0).val) % (2^w) at hv
+ rw [Nat.mod_eq_of_lt hsmall] at hv
+ rcases hfit.lt_or_eq with hs | hs
+ · exact hl (hv.trans (Nat.mod_eq_of_lt hs))
+ · rw [hs, Nat.mod_self] at hv; omega
+ rw [ite_eq_right hne, ite_eq_right hl]
+
+/-- Exact native success at the reset entry point. Report replay obtains precisely
+the external memory produced by the body; the footer consumes no choice bit. -/
+theorem nativeStep_iff (p : UniversalMachine.Program) (pub : Pub → Word w) (st : Word w)
+ (m : Memory w) (bs : List Bool) (r : Report w) :
+ execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start st) m bs = some r ↔
+ ∃ es out m', Flow.Exec pub st (body (prepare p)) (fun _ => 0) m es out m' ∧
+ choiceBits es = bs ∧ r.events = es ++ [.tick] ∧
+ r.result = nextState pub st ∧ after m r.events = m' := by
+ rw [show execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start st) m bs = some r ↔ _
+ from PrimedCounter.Call.execute_iff (body (prepare p)) 29 30 pub st (fun _ => 0)
+ (fun _ => 0) m bs (callFuel p) r]
+ constructor
+ · rintro ⟨es,out,m',he,-,hb,ht,hr,hm⟩
+ obtain ⟨hn,hT⟩ := body_cursor he
+ exact ⟨es,out,m',he,hb,ht,by simpa only [nextState,hn,hT] using hr,hm⟩
+ · rintro ⟨es,out,m',he,hb,ht,hr,hm⟩
+ obtain ⟨hn,hT⟩ := body_cursor he
+ exact ⟨es,out,m',he,Nat.add_le_add_right (program_bound p he) 2,hb,ht,by simpa [nextState,hn,hT] using hr,hm⟩
+
+/-- Compute the actual report from a successful scheduled body execution. -/
+theorem nativeStep_of_exec {p : UniversalMachine.Program} {pub : Pub → Word w} {st : Word w}
+ {m es out m'} (he : Flow.Exec pub st (body (prepare p)) (fun _ => 0) m es out m') :
+ execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start st) m (choiceBits es) =
+ some ⟨es ++ [.tick],nextState pub st⟩ := by
+ refine (nativeStep_iff p pub st m _ _).mpr ⟨es,out,m',he,rfl,rfl,rfl,?_⟩
+ change after m (es ++ [.tick]) = m'
+ simpa [after, update] using PrimedCounter.Call.exec_memory he
+
+/-- Existential report form for composing calls on a specified post-call memory. -/
+theorem nativeStep_exists_iff (p : UniversalMachine.Program) (pub : Pub → Word w) (st : Word w)
+ (m : Memory w) (bs : List Bool) (m' : Memory w) :
+ (∃ r, execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start st) m bs = some r ∧
+ after m r.events = m') ↔
+ ∃ es out, Flow.Exec pub st (body (prepare p)) (fun _ => 0) m es out m' ∧ choiceBits es = bs := by
+ constructor
+ · rintro ⟨r,hr,hm⟩
+ obtain ⟨es,out,mem,he,hb,-,-,hrm⟩ := (nativeStep_iff p pub st m bs r).mp hr
+ exact ⟨es,out,hrm.symm.trans hm ▸ he,hb⟩
+ · rintro ⟨es,out,he,rfl⟩
+ refine ⟨_, nativeStep_of_exec he, ?_⟩
+ change after m (es ++ [.tick]) = m'
+ simpa [after, update] using PrimedCounter.Call.exec_memory he
+
+/-- Every actual cell call leaves external memory intact, has an empty branch stream,
+and makes exactly six external reads. -/
+theorem nativeCell_report (p : UniversalMachine.Program) (pub : Pub → Word w) (st : Word w)
+ (m : Memory w) (bs : List Bool) (r : Report w) (hs : st ≠ 0)
+ (he : execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start st) m bs = some r) :
+ bs = [] ∧ after m r.events = m ∧ r.probes = 6 ∧ r.result = nextState pub st := by
+ obtain ⟨es,out,m',hex,hbits,hr,hn,hm⟩ := (nativeStep_iff p pub st m bs r).mp he
+ obtain ⟨hmem,hb,hp⟩ := cell_call_cost hex hs
+ refine ⟨hbits.symm.trans hb,hm.trans hmem,?_,hn⟩
+ simp [Report.probes, hr, PrimedStackRAM.probes_append, hp, countProbes]
+
+
+/-- Native cost of the cursor-zero call. Its initial source-state read is the
+only extra probe beyond preparing the five scratch words. -/
+theorem nativePrepare_report (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (m : Memory w) (bs : List Bool) (r : Report w) (hw : 2 ≤ w) (hcap : p.extra+2 ≤ 2^w)
+ (he : execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start 0) m bs = some r) :
+ r.probes = (if m (pub 1).val = 1 then 7 else 9) ∧ bs.length ≤ 1 := by
+ obtain ⟨es,rs,m',hb,hbits,-,-,-⟩ := (nativeStep_iff p pub 0 m bs r).mp he
+ obtain ⟨ep,rp,hprep,hbs⟩ := (initial_choices_iff p pub (fun _ => 0) m m' bs).mp
+ ⟨es,rs,hb,hbits⟩
+ let pre := loaded pub 0 (fun _ => 0) m
+ have hcost := LiveEvaluatorRAMPrepare.prepare_cost p pub 0 pre m hw hcap rfl rfl hprep
+ change countProbes ep = (if m (pub 1).val = 1 then 6 else 8) ∧ _ at hcost
+ have hrun : Flow.Exec pub 0 (body (prepare p)) (fun _ => 0) m
+ ((List.replicate 11 .tick ++ [.read (pub 1) (m (pub 1).val)]) ++
+ (.tick :: ep) ++ List.replicate 8 .tick) (finished pub 0 rp) m' := by
+ simpa only [body, List.append_assoc, List.cons_append] using
+ (Flow.Exec.seq (load_exec pub 0 (fun _ => 0) m)
+ (Flow.Exec.seq (Flow.Exec.ifEqYes (a := prepare p) (b := .seq locate cell) (l := 26) (q := 0) rfl
+ hprep) (finish_exec pub 0 rp m')))
+ have hh := nativeStep_of_exec hrun
+ simp only [Flow.choiceBits_append, List.replicate_succ, List.replicate_zero,
+ choiceBits, List.nil_append, List.append_nil, hbs] at hh
+ have hr := congrArg Report.events (Option.some.inj (he.symm.trans hh))
+ refine ⟨?_,hbs ▸ hcost.2.1⟩
+ by_cases h : m (pub 1).val = 1 <;>
+ simp [Report.probes, hr, PrimedStackRAM.probes_append,
+ countProbes, hcost.1, h]
+
+/-- Every returned report uses less than the fixed allowance, including its final tick. -/
+theorem nativeStep_report_length (p : UniversalMachine.Program) (pub : Pub → Word w) (st : Word w)
+ (m : Memory w) (bs : List Bool) (r : Report w)
+ (he : execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start st) m bs = some r) :
+ r.events.length < callFuel p := by
+ obtain ⟨es,rs,m',hb,-,hev,-,-⟩ := (nativeStep_iff p pub st m bs r).mp he
+ have hl := program_bound p hb
+ simp [hev, callFuel]; omega
+
+end LiveEvaluatorRAM.Schedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRadius.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRadius.lean
new file mode 100644
index 0000000000..b0f4c2ad8a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRadius.lean
@@ -0,0 +1,67 @@
+import OAI.Computability.VPVNP.LiveEvaluatorTail
+import OAI.Computability.VPVNP.PolynomialBounds
+
+/-!
+# One length-dependent window for all middle-cut inputs
+
+The raw input length and reachable stack storage are polynomially bounded
+independently of the particular accumulated exponents. A fixed power of the
+input length thus provides the radius the live RAM computes. The exponent
+is chosen before the later group-width and processor constants.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRadius
+
+open LiveEvaluatorEncoding LiveEvaluatorTail UniversalMachine RAMTape RAMTape.StackCompiler
+
+/-- Enlarging a head-relative window retains all the data of a bounded state. -/
+theorem fits_mono {extra A B : ℕ} (h : A ≤ B) (s : EvaluatorTail.State extra)
+ (hs : StateFits A s) : StateFits B s := by
+ cases s with
+ | accepted | rejected => trivial
+ | running c =>
+ have enlarge (t : Turing.Tape Symbol) (ht : TapeFits A t) : TapeFits B t :=
+ fun j hj => ht j (by omega)
+ exact ⟨hs.1, enlarge _ hs.2.1, enlarge _ hs.2.2⟩
+
+/-- A single exponent and threshold bound the relative tape radius for every
+admissible middle input and stack bound at each length. -/
+theorem exists_length_radius {inputLength stackSpace : ℕ → ℕ}
+ (hl : PolynomiallyBounded inputLength) (hs : PolynomiallyBounded stackSpace) :
+ ∃ m N : ℕ, ∀ n ≥ N, ∀ l ≤ inputLength n, ∀ b ≤ stackSpace n,
+ l + (7 * b + 4) + (7 * b + 4) ≤ n ^ m := by
+ have hr := ((PolynomiallyBounded.const 7).mul hs).add (.const 4)
+ obtain ⟨A, k, N, hN⟩ := (hl.add hr).add hr
+ refine ⟨k + 1, max A N, fun n hn l hL b hB => ?_⟩
+ have hle := hN n ((le_max_right ..).trans hn)
+ have hr' : 7 * b + 4 ≤ 7 * stackSpace n + 4 := by omega
+ exact (Nat.add_le_add (Nat.add_le_add hL hr') hr').trans <| hle.trans <| by
+ rw [pow_succ, mul_comm]
+ exact Nat.mul_le_mul_left _ ((le_max_left ..).trans hn)
+
+/-- Apply the literal tail count at the common, length-only radius.
+Each input may use strictly less stack storage and fewer input bits. -/
+theorem card_labeled_of_le {K Q : Type*} [DecidableEq K] [Fintype K] [Fintype Q]
+ (input : K) (code : StackCode K Q) (start : Q) (raw : Word) {B M : ℕ}
+ (bounded : ∀ ⦃q s⦄, Reach code start (labeledInput input raw) q s →
+ Fintype.card K + 1 + ∑ a, (s a).length ≤ B)
+ (fits : raw.length + (7 * B + 4) + (7 * B + 4) ≤ M)
+ {h w Δ : ℕ} (layout : Layout (labeledProgram input code start).extra M w Δ) :
+ let p := labeledProgram input code start
+ Nat.card (Runs (h := h) layout (initialCode M (initial p raw))) = paths p (2 ^ h) (initial p raw) := by
+ let p := labeledProgram input code start
+ have hf (t : ℕ) (bits : Fin t → Bool) (i : Fin (t+1)) :
+ StateFits M (EvaluatorTail.history p t (initial p raw) bits i) :=
+ fits_mono fits _ (LiveEvaluatorSpace.history_fits_labeled input code start raw bounded t bits i)
+ exact card_runs layout (initial p raw) (initialCode M (initial p raw))
+ (initialCode_toState _ (hf 0 Fin.elim0 0)) (fun bits _ i => hf _ bits i)
+
+end LiveEvaluatorRadius
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRawCells.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRawCells.lean
new file mode 100644
index 0000000000..9dd894fc7e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRawCells.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.LiveEvaluatorGroup
+
+/-!
+# Raw cell words on successful live evaluator calls
+
+On a successful group the source check examines every word, even the
+overwritten head cell. Destination words are either zero (for a halt) or
+equal to a legal written symbol. The old-cell permutation covers every
+destination, so an accepting computation forces both configuration arrays
+to have canonical symbol fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorGroup
+
+open BurstRAM (Word Memory)
+open UniversalMachine (Symbol Instruction Program WindowCell)
+open LiveEvaluatorEncoding (Code TapeWindow ConfigWindow)
+open LiveEvaluatorRAM (ConfigAt ActionAt PrepLayout cellTest destination destination_val_of_limbs)
+open LiveEvaluatorRAM.Schedule
+open LiveEvaluatorStep (cellDestination cellDestination_surjective)
+open scoped Fin.CommRing
+
+variable {w M extra : ℕ}
+
+/-- Read the machine word for a given tape cell from the physical configuration array. -/
+def cellWord (m : Memory w) (base : Word w) (side : Bool) (i : WindowCell M) : Word w :=
+ m (baseOf base M side + (i.val : Word w)).val
+
+/-- The actual state and symbol words determine a canonical cut configuration
+if the state and symbol ranges and halt padding pass. -/
+theorem configAt_of_valid (m : Memory w) (base : Word w)
+ (hp : 0 < (m base.val).val) (hs : (m base.val).val < extra + 2)
+ (cells : ∀ side (i : WindowCell M), (cellWord m base side i).val < 3 ∧
+ ((m base.val).val = 1 → (cellWord m base side i).val = 0)) :
+ ∃ c : Code extra M, ConfigAt m base c := by
+ by_cases ha : (m base.val).val = 1
+ · refine ⟨.accepted, ha, fun i => (cells false i).2 ha, fun i => (cells true i).2 ha⟩
+ · let t (side : Bool) : TapeWindow M :=
+ ⟨fun i => ⟨(cellWord m base side i).val, (cells side i).1⟩⟩
+ let c : ConfigWindow extra M := ⟨⟨_, hs⟩, t false, t true⟩
+ exact ⟨.running c (by change 2 ≤ (m base.val).val; omega), rfl, fun _ => rfl, fun _ => rfl⟩
+
+theorem configAt_congr_block {m m' : Memory w} {base : Word w} {c : Code extra M}
+ (hc : ConfigAt m base c)
+ (h : ∀ i < calls M, m (base + (i : Word w)).val = m' (base + (i : Word w)).val) :
+ ConfigAt m' base c := by
+ constructor
+ · have he := h 0 (by simp [calls])
+ simp at he
+ exact (congrArg Fin.val he).symm.trans hc.state
+ · intro i
+ have he := h (1 + i.val) (by unfold calls; omega)
+ simpa [add_assoc] using (congrArg Fin.val he).symm.trans (by simpa [add_assoc] using hc.first i)
+ · intro i
+ have he := h (1 + (2*M+1) + i.val) (by unfold calls; omega)
+ simpa [add_assoc] using (congrArg Fin.val he).symm.trans (by simpa [add_assoc] using hc.second i)
+
+private theorem acceptedCellFacts (p : Program) (pub : Pub → Word w) (m : Memory w)
+ (a : Instruction p.extra) (hl : PrepLayout p pub M) (hr : AllCells M p pub m)
+ (hact : ActionAt m (pub 3) a.target.val a.firstSymbol a.firstMove a.secondSymbol a.secondMove)
+ (htarget : (m (pub 2).val).val = a.target.val)
+ (side : Bool) (i : WindowCell M) :
+ let move := if side then a.secondMove else a.firstMove
+ let j := if a.target.val = 1 then i else cellDestination move i
+ ((cellWord m (pub 1) side i).val < 3 ∧
+ ((m (pub 1).val).val = 1 → (cellWord m (pub 1) side i).val = 0)) ∧
+ ((cellWord m (pub 2) side j).val < 3 ∧
+ ((m (pub 2).val).val = 1 → (cellWord m (pub 2) side j).val = 0)) := by
+ dsimp only
+ let st : Word w := (cellCursor side i : Word w)
+ let r := bank pub (fun _ => 0) m side i
+ have hval : st.val = cellCursor side i :=
+ Nat.mod_eq_of_lt ((cellCursor_lt_calls side i).trans (calls_fit hl))
+ have hs : st ≠ 0 := by
+ intro h
+ have : cellCursor side i = 0 := hval.symm.trans (congrArg Fin.val h)
+ simp [cellCursor] at this
+ have he : cellTest r m := (noninitial_call_iff p pub hs _ m).mp (hr side i)
+ obtain ⟨hz, h₁, h₃, h₅, h₆, h₇, _, h₁₂, h₁₃, h₁₄, h₁₅, h₁₆⟩ :=
+ bank_operands pub (fun _ => 0) m side i hl.radius (calls_fit hl)
+ change r 0 = _ at hz
+ change r 1 = _ at h₁
+ change r 3 = _ at h₃
+ change r 5 = _ at h₅
+ change r 6 = _ at h₆
+ change r 7 = _ at h₇
+ change r 12 = _ at h₁₂
+ change r 13 = _ at h₁₃
+ change r 14 = _ at h₁₄
+ change r 15 = _ at h₁₅
+ change r 16 = _ at h₁₆
+ let move := if side then a.secondMove else a.firstMove
+ let write := if side then a.secondSymbol else a.firstSymbol
+ have hfour : 4 ≤ 2 ^ w := Nat.pow_le_pow_right (by decide : 0 < 2) hl.width
+ have hzero : (r 0).val = 0 := by rw [hz]; rfl
+ have hone : (r 1).val = 1 := by rw [h₁]; exact Nat.mod_eq_of_lt (by omega : 1 < 2 ^ w)
+ have hthree : (r 3).val = 3 := by rw [h₃]; exact Nat.mod_eq_of_lt (by omega : 3 < 2 ^ w)
+ have hmax : (r 12).val = 2*M := by
+ rw [h₁₂, Fin.val_natCast, Nat.mod_eq_of_lt]
+ have := calls_fit hl
+ unfold calls at this
+ omega
+ have hindex : (r 13).val = i.val := by
+ rw [h₁₃, Fin.val_natCast, Nat.mod_eq_of_lt]
+ have := calls_fit hl
+ unfold calls at this
+ omega
+ have hm : (r 7).val = move.val := by
+ rw [h₇]
+ cases side <;> simp only [move, writeAddr, Bool.false_eq_true, ↓reduceIte]
+ · rw [show pub 3 + 1 + 1 = pub 3 + 2 by ring]
+ exact hact.firstMoveVal
+ · rw [show pub 3 + 3 + 1 = pub 3 + 4 by ring]
+ exact hact.secondMoveVal
+ have hw : (r 6).val = write.val := by
+ rw [h₆]
+ cases side <;> first | exact hact.firstWriteVal | exact hact.secondWriteVal
+ have hs₁ : r 16 = r 1 ↔ (m (pub 1).val).val = 1 := by
+ rw [Fin.ext_iff, hone, h₁₆]
+ have ht₁ : r 5 = r 1 ↔ a.target.val = 1 := by
+ rw [Fin.ext_iff, hone, h₅, hact.targetVal]
+ have hsrc : m (r 14 + r 13).val = cellWord m (pub 1) side i := by
+ rw [h₁₄, h₁₃]; rfl
+ obtain ⟨hold, hout⟩ := he
+ change (if r 16 = r 1 then m (r 14 + r 13).val = r 0 else m (r 14 + r 13).val < r 3) at hold
+ rw [hsrc] at hold
+ have valid : (cellWord m (pub 1) side i).val < 3 ∧
+ ((m (pub 1).val).val = 1 → (cellWord m (pub 1) side i).val = 0) := by
+ split at hold
+ · have h := (congrArg Fin.val hold).trans hzero
+ exact ⟨by omega, fun _ => h⟩
+ · exact ⟨(show (cellWord m (pub 1) side i).val < (r 3).val from hold).trans_le hthree.le,
+ fun h => False.elim (‹r 16 ≠ r 1› (hs₁.mpr h))⟩
+ refine ⟨valid, ?_⟩
+ by_cases hhalt : a.target.val = 1
+ · simp only [hhalt, ite_true]
+ rw [ite_eq_left (ht₁.mpr hhalt)] at hout
+ have heq : (cellWord m (pub 2) side i).val = 0 := by
+ rw [h₁₅, h₁₃] at hout
+ exact (congrArg Fin.val hout).trans hzero
+ exact ⟨by omega, fun _ => heq⟩
+ · simp only [hhalt, ite_false]
+ rw [ite_eq_right (fun h => hhalt (ht₁.mp h))] at hout
+ obtain ⟨_, ho⟩ := hout
+ let d := destination (r 0) (r 1) (r 12) (r 7) (r 13)
+ have hd := destination_val_of_limbs _ _ _ _ _ move i hzero hone hmax hm hindex
+ have hdc : d = ((cellDestination move i).val : Word w) := by rw [← hd, Fin.cast_val_eq_self]
+ change m (r 15 + d).val = if r 13 = r 11 then r 6 else m (r 14 + r 13).val at ho
+ rw [h₁₅, hdc, hsrc] at ho
+ have hlt : (cellWord m (pub 2) side (cellDestination move i)).val < 3 := by
+ split at ho
+ · exact ((congrArg Fin.val ho).trans hw) ▸ write.isLt
+ · exact congrArg Fin.val ho ▸ valid.1
+ exact ⟨hlt, fun h => False.elim (hhalt (htarget ▸ h))⟩
+
+/-- An occupied scratch instruction and successful scan force all old and
+new tape fields to encode canonical evaluator symbols. -/
+theorem rawCells_force_images (p : Program) (pub : Pub → Word w) (m : Memory w)
+ (a : Instruction p.extra) (hl : PrepLayout p pub M) (hr : AllCells M p pub m)
+ (hact : ActionAt m (pub 3) a.target.val a.firstSymbol a.firstMove a.secondSymbol a.secondMove)
+ (hold : 0 < (m (pub 1).val).val ∧ (m (pub 1).val).val < p.extra + 2)
+ (hpos : 0 < a.target.val) (htarget : (m (pub 2).val).val = a.target.val) :
+ (∃ c : Code p.extra M, ConfigAt m (pub 1) c) ∧ (∃ c : Code p.extra M, ConfigAt m (pub 2) c) := by
+ have h := acceptedCellFacts p pub m a hl hr hact htarget
+ refine ⟨configAt_of_valid m (pub 1) hold.1 hold.2 (fun s i => (h s i).1), ?_⟩
+ apply configAt_of_valid m (pub 2) (htarget ▸ hpos) (htarget ▸ a.target.isLt)
+ intro side j
+ by_cases ha : a.target.val = 1
+ · simpa only [ha, ite_true] using (h side j).2
+ · obtain ⟨i, rfl⟩ := cellDestination_surjective (if side then a.secondMove else a.firstMove) j
+ simpa only [ha, ite_false] using (h side i).2
+
+end LiveEvaluatorGroup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorRawPrepare.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorRawPrepare.lean
new file mode 100644
index 0000000000..9935232422
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorRawPrepare.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.LiveEvaluatorRAMPrepareImage
+
+/-!
+# Preparing a transition from raw configuration words
+
+A successful first call bounds the source state, verifies the proposed target
+and publishes its instruction. Every word of both configuration blocks can
+still be read at the same address after the call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorRAM
+
+open BurstRAM (Word Memory)
+open PrimedStackRAM (Regs)
+open UniversalMachine (Program Instruction)
+open LiveEvaluatorRAMPrepare
+open scoped Fin.CommRing
+
+variable {w M : ℕ} {p : Program} {pub : Fin 4 → Word w} {m mem : Memory w} {bs : List Bool}
+
+/-- Consequences of native preparation before either tape block has been decoded. -/
+theorem Prepared.raw_facts (run : Prepared p pub m mem bs) (hl : PrepLayout p pub M) :
+ 0 < (m (pub 1).val).val ∧ (m (pub 1).val).val < p.extra + 2 ∧
+ (∀ i < Schedule.calls M, mem (pub 1 + (i : Word w)).val = m (pub 1 + (i : Word w)).val) ∧
+ (∀ i < Schedule.calls M, mem (pub 2 + (i : Word w)).val = m (pub 2 + (i : Word w)).val) ∧
+ ∃ a : Instruction p.extra, 0 < a.target.val ∧ (m (pub 2).val).val = a.target.val ∧
+ ActionAt mem (pub 3) a.target.val a.firstSymbol a.firstMove a.secondSymbol a.secondMove := by
+ rw [Prepared, Schedule.initial_choices_iff] at run
+ obtain ⟨es, reg, exec, _⟩ := run
+ let rs : Regs w 32 := Schedule.loaded pub 0 (fun _ => 0) m
+ obtain ⟨hp, hb, fs, s, sel, hpt, hout, _, _, rfl⟩ :=
+ (prepare_exec_iff p pub 0 rs m hl.width hl.states rfl rfl es reg mem).mp exec
+ change (m (pub 1).val).val ≤ p.extra + 1 at hb
+ have h1 : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by have := hl.width; omega))
+ have hs1 : (s 1).val = 1 := (congrArg Fin.val (sel.frame 1 (by decide))).trans h1
+ have hs25 : s 25 = pub 3 := sel.frame 25 (by decide)
+ have hsfit : (s 25).val + 5 ≤ 2 ^ w := hs25 ▸ hl.scratchFit
+ have block (b : Word w) (hfit : b.val + Schedule.calls M ≤ 2 ^ w)
+ (hdis : b.val + Schedule.calls M ≤ (pub 3).val ∨ (pub 3).val + 5 ≤ b.val)
+ (i : ℕ) (hi : i < Schedule.calls M) :
+ scratchMemory s m (b + (i : Word w)).val = m (b + (i : Word w)).val := by
+ apply scratchMemory_outside s m hs1 hsfit
+ rw [hs25, Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)]
+ omega
+ refine ⟨hp, by omega, block _ hl.oldFit hl.oldDisjoint, block _ hl.outFit hl.outDisjoint, ?_⟩
+ have hs0 : s 0 = 0 := sel.frame 0 (by decide)
+ have hs24 : s 24 = pub 2 := sel.frame 24 (by decide)
+ rw [hs24] at hout
+ rw [hs0] at hpt
+ change 0 < (s 5).val at hpt
+ let u := boundsRegs p rs
+ cases sel with
+ | carry =>
+ exact ⟨LiveEvaluatorAction.carry _, Nat.zero_lt_one, (congrArg Fin.val hout).trans h1,
+ actionAt_carryRegs u m rfl h1 hl.scratchFit⟩
+ | slot _ _ _ bit a ha =>
+ have ht : (selectedRegs u m a 5).val = a.target.val :=
+ (LiveEvaluatorRAMDispatch.instructionRegs_fields _ a hl.width hl.states).1
+ exact ⟨a, ht ▸ hpt, (congrArg Fin.val hout).trans ht,
+ actionAt_selectedRegs u m a hl.width hl.states h1 hl.scratchFit⟩
+
+end LiveEvaluatorRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorReindex.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindex.lean
new file mode 100644
index 0000000000..fc04aca703
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindex.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.EvaluatorProgramRawInput
+import OAI.Computability.VPVNP.LiveEvaluatorInitializeSweep
+
+/-!
+# Exponent coordinates on the physical evaluator input
+
+The middle cut sends dense production rows followed by dense gadget rows.
+The advised permutation identifies the corresponding formal coordinate of
+the evaluator. Each low-endian row bit appears once in the raw input,
+as the payload of a reversed tagged field. All remaining bytes of the
+initial tape are identical to the raw input with zero exponent rows.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorReindex
+
+open Evaluator.InputBank EvaluatorProgramRawInput RAMSerialization
+open BurstRAM (Word)
+variable {d t Z : ℕ}
+
+/-- Lift the coordinate permutation, keeping every row's bit index fixed. -/
+def bitOrder (perm : Fin d ≃ Fin t) (Z : ℕ) : Fin (d * Z) ≃ Fin (t * Z) :=
+ finProdFinEquiv.symm.trans ((perm.prodCongr (Equiv.refl _)).trans finProdFinEquiv)
+
+@[simp] theorem bitOrder_at (perm : Fin d ≃ Fin t) (i : Fin d) (j : Fin Z) :
+ bitOrder perm Z (finProdFinEquiv (i, j)) = finProdFinEquiv (perm i, j) := by
+ simp [bitOrder]
+
+theorem bitOrder_read (perm : Fin d ≃ Fin t) (dense : Fin d → Word Z) (formal : Fin t → Word Z)
+ (h : ∀ i, formal (perm i) = dense i) (q : Fin (d * Z)) :
+ arrayBits t Z formal (bitOrder perm Z q) = arrayBits d Z dense q := by
+ obtain ⟨⟨i, j⟩, rfl⟩ := finProdFinEquiv.surjective q
+ simp [arrayBits_at, h]
+
+/-- Address inside the tagged exponent field of the bit whose formal index
+in the forward, low-endian array is `q`. -/
+def payload {T : ℕ} (q : Fin T) : ℕ := 2 * (T - 1 - q.val) + 1
+
+theorem payload_injective {T : ℕ} : Function.Injective (payload (T := T)) := by
+ intro i j he
+ apply Fin.ext
+ unfold payload at he
+ omega
+
+private theorem field_at {T : ℕ} (f : Fin T → Bool) (q : Fin T) :
+ (fieldBits (List.ofFn f))[payload q]? = some (f q) := by
+ let i : Fin (List.ofFn f).length := ⟨T-1-q.val, by rw [List.length_ofFn]; omega⟩
+ have he := fieldBits_payload (List.ofFn f) i
+ simp only [List.getElem_reverse, List.length_ofFn, List.getElem_ofFn] at he
+ have hi : T-1-i.val = q.val := by dsimp [i]; omega
+ rw [List.getElem?_eq_getElem (by rw [length_fieldBits, List.length_ofFn]; unfold payload; omega)]
+ apply congrArg some
+ change (fieldBits (List.ofFn f))[2*i.val+1]'_ = f q
+ exact he.trans (congrArg f (Fin.ext hi))
+
+private theorem field_else {T : ℕ} (f g : Fin T → Bool) (j : ℕ)
+ (hj : ∀ q : Fin T, j ≠ payload q) : (fieldBits (List.ofFn f))[j]? = (fieldBits (List.ofFn g))[j]? := by
+ by_cases h : j < 2*T+1
+ · have hget (b : Fin T → Bool) : j < (fieldBits (List.ofFn b)).length := by simpa [length_fieldBits] using h
+ rw [List.getElem?_eq_getElem (hget f), List.getElem?_eq_getElem (hget g)]
+ by_cases hend : j = 2*T
+ · subst j
+ have he (b : Fin T → Bool) := fieldBits_end (List.ofFn b)
+ simp only [List.length_ofFn] at he
+ rw [he, he]
+ · have heven : j = 2*(j/2) := by
+ by_contra hn
+ let q : Fin T := ⟨T-1-(j/2), by omega⟩
+ exact hj q (by dsimp [payload, q]; omega)
+ have tag (b : Fin T → Bool) := fieldBits_tag (List.ofFn b)
+ ⟨j/2, by rw [List.length_ofFn]; omega⟩
+ rw [show (fieldBits (List.ofFn f))[j]'(hget f) = true from by simpa only [← heven] using tag f,
+ show (fieldBits (List.ofFn g))[j]'(hget g) = true from by simpa only [← heven] using tag g]
+ · simp [List.getElem?_eq_none (by simpa [length_fieldBits] using Nat.le_of_not_gt h :
+ (fieldBits (List.ofFn f)).length ≤ j),
+ List.getElem?_eq_none (by simpa [length_fieldBits] using Nat.le_of_not_gt h :
+ (fieldBits (List.ofFn g)).length ≤ j)]
+
+/-- Offset in the raw evaluator input, after the advised prefix and the
+initial unary width field. -/
+def rawSlot (adviceLength Z : ℕ) {T : ℕ} (q : Fin T) : ℕ :=
+ adviceLength + (2 * Z + 1) + payload q
+
+private def start (A : List Bool) (Z : ℕ) : List Bool := A ++ fieldBits (List.replicate Z true)
+
+private def ending (Z : ℕ) : List Bool :=
+ fieldBits (List.replicate Z true) ++ fieldBits (List.replicate Z true)
+
+private theorem raw_parts (A : List Bool) (e : Fin t → Word Z) :
+ A ++ runtime e = start A Z ++ (fieldBits (List.ofFn (arrayBits t Z e)) ++ ending Z) := by
+ simp [start, ending, runtime, List.append_assoc]
+
+@[simp] private theorem start_length (A : List Bool) : (start A Z).length = A.length + (2*Z+1) := by
+ simp [start, length_fieldBits]
+
+theorem raw_at (A : List Bool) (e : Fin t → Word Z) (q : Fin (t*Z)) :
+ (A ++ runtime e)[rawSlot A.length Z q]? = some (arrayBits t Z e q) := by
+ rw [raw_parts]
+ rw [List.getElem?_append_right (by simp [rawSlot])]
+ simp only [start_length, rawSlot, Nat.add_sub_cancel_left]
+ rw [List.getElem?_append_left (by rw [length_fieldBits, List.length_ofFn]; unfold payload; omega),
+ field_at]
+
+theorem raw_else (A : List Bool) (e f : Fin t → Word Z) (j : ℕ)
+ (hj : ∀ q : Fin (t*Z), j ≠ rawSlot A.length Z q) :
+ (A ++ runtime e)[j]? = (A ++ runtime f)[j]? := by
+ rw [raw_parts, raw_parts]
+ by_cases h : j < (start A Z).length
+ · rw [List.getElem?_append_left h, List.getElem?_append_left h]
+ rw [List.getElem?_append_right (Nat.le_of_not_gt h), List.getElem?_append_right (Nat.le_of_not_gt h)]
+ let k := j - (start A Z).length
+ have hlen (x : Fin t → Word Z) : (fieldBits (List.ofFn (arrayBits t Z x))).length = 2*(t*Z)+1 := by
+ rw [length_fieldBits, List.length_ofFn]
+ by_cases hk : k < 2*(t*Z)+1
+ · rw [List.getElem?_append_left (by rwa [hlen]), List.getElem?_append_left (by rwa [hlen])]
+ apply field_else
+ intro q he
+ apply hj q
+ rw [rawSlot, ← start_length, ← he]
+ omega
+ · rw [List.getElem?_append_right (by rw [hlen]; exact Nat.le_of_not_gt hk),
+ List.getElem?_append_right (by rw [hlen]; exact Nat.le_of_not_gt hk), hlen, hlen]
+
+/-- The word read from dense row `q / Z` supplies exactly the payload
+of the formal-coordinate evaluator field. -/
+theorem raw_dense_at (A : List Bool) (perm : Fin d ≃ Fin t) (dense : Fin d → Word Z)
+ (formal : Fin t → Word Z) (h : ∀ i, formal (perm i) = dense i) (q : Fin (d*Z)) :
+ (A ++ runtime formal)[rawSlot A.length Z (bitOrder perm Z q)]? = some (arrayBits d Z dense q) := by
+ rw [raw_at, bitOrder_read perm dense formal h]
+
+end LiveEvaluatorReindex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexImage.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexImage.lean
new file mode 100644
index 0000000000..e0942d8c9e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexImage.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.LiveEvaluatorReindex
+
+/-!
+# Memory invariant for the evaluator's exponent scatter
+
+Each dense exponent bit has a distinct destination in the first tape. The
+invariant describes exactly the visited payload slots and preserves every
+other address. At completion the initial zero-exponent bank has become the
+bank for the actual evaluator input in formal-coordinate order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorReindex
+
+open LiveEvaluatorEncoding LiveEvaluatorInitialize EvaluatorProgramRawInput
+open BurstRAM (Word Memory writeMemory)
+open RAMSerialization
+open scoped Fin.CommRing
+
+variable {d t Z w : ℕ}
+
+/-- Physical word address of an exponent payload symbol. -/
+def symbolAddress (stateBase M adviceLength Z : ℕ) {T : ℕ} (q : Fin T) : ℕ :=
+ stateBase + 1 + M + rawSlot adviceLength Z q
+
+private theorem address_injective {base M A : ℕ} {T : ℕ} :
+ Function.Injective (symbolAddress base M A Z (T := T)) := by
+ intro i j he
+ exact payload_injective (by simpa [symbolAddress, rawSlot] using he)
+
+/-- Dense source `q` has been read if its position precedes the cursor. -/
+structure Image (perm : Fin d ≃ Fin t) (dense : Fin d → Word Z)
+ (base M adviceLength cursor : ℕ) (before after : Memory w) : Prop where
+ copied : ∀ q : Fin (d*Z), q.val < cursor →
+ after (symbolAddress base M adviceLength Z (bitOrder perm Z q)) =
+ PrimedInputRAM.encodeBit w (arrayBits d Z dense q) + 1
+ outside : ∀ addr, (∀ q : Fin (d*Z), q.val < cursor →
+ addr ≠ symbolAddress base M adviceLength Z (bitOrder perm Z q)) → after addr = before addr
+
+theorem Image.zero (perm : Fin d ≃ Fin t) (dense : Fin d → Word Z) (base M A : ℕ) (m : Memory w) :
+ Image perm dense base M A 0 m m :=
+ ⟨fun _ h => (Nat.not_lt_zero _ h).elim, fun _ _ => rfl⟩
+
+theorem Image.write {perm : Fin d ≃ Fin t} {dense : Fin d → Word Z} {base M A : ℕ}
+ {before m : Memory w} (q : Fin (d*Z)) (h : Image perm dense base M A q.val before m)
+ (addr : Word w) (ha : addr.val = symbolAddress base M A Z (bitOrder perm Z q)) :
+ Image perm dense base M A (q.val+1) before
+ (writeMemory m addr (PrimedInputRAM.encodeBit w (arrayBits d Z dense q) + 1)) := by
+ constructor
+ · intro q' hq'
+ by_cases he : q' = q
+ · subst q'
+ simp [writeMemory, ha]
+ · have hne : symbolAddress base M A Z (bitOrder perm Z q') ≠ addr.val := by
+ rw [ha]
+ exact fun eq => he ((bitOrder perm Z).injective (address_injective eq))
+ rw [writeMemory, ite_eq_right hne, h.copied q' (by have h' : q'.val ≠ q.val := fun eq => he (Fin.ext eq); omega)]
+ · intro a hn
+ rw [writeMemory, ite_eq_right (ha ▸ hn q (by omega))]
+ exact h.outside a (fun q' hq' => hn q' (by omega))
+
+private theorem slot_lt (A : List Bool) (e : Fin t → Word Z) (q : Fin (t*Z)) :
+ rawSlot A.length Z q < (A ++ runtime e).length := by
+ have h := raw_at A e q
+ by_contra! hn
+ rw [List.getElem?_eq_none hn] at h
+ contradiction
+
+private theorem wordBit_symbol (hw : 2 ≤ w) (b : Bool) :
+ (PrimedInputRAM.encodeBit w b + 1 : Word w).val = (bitSymbol b).val := by
+ have h4 : 4 ≤ 2 ^ w := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ cases b <;> simp [PrimedInputRAM.encodeBit, bitSymbol, Fin.val_add,
+ Nat.mod_eq_of_lt (by omega : 1 < 2 ^ w), Nat.mod_eq_of_lt (by omega : 2 < 2 ^ w)]
+
+/-- The completed scatter gives every word of the initialized evaluator on
+the real exponent vector, including all unchanged advice, width tags, padding,
+state and second-tape words. -/
+theorem stores_formal (p : UniversalMachine.Program) (hr : p.extra ≠ 0)
+ (hw : 2 ≤ w) (hs : p.extra + 2 ≤ 2 ^ w) (perm : Fin d ≃ Fin t)
+ (dense : Fin d → Word Z) (formal : Fin t → Word Z) (order : ∀ i, formal (perm i) = dense i)
+ (A : List Bool) (base M : ℕ) (space : (A ++ runtime formal).length ≤ M+1)
+ (before after : Memory w) (prepared : Stores hw hs base before
+ (LiveEvaluatorTail.initialCode M (UniversalMachine.initial p (A ++ runtime (fun _ : Fin t => (0 : Word Z))))))
+ (finished : Image perm dense base M A.length (d*Z) before after) :
+ Stores hw hs base after (LiveEvaluatorTail.initialCode M (UniversalMachine.initial p (A ++ runtime formal))) := by
+ intro k
+ apply Fin.ext
+ rcases field_cases k with rfl | ⟨i, rfl⟩ | ⟨i, rfl⟩
+ · rw [finished.outside _ (by intro q _; dsimp [stateField, symbolAddress]; omega),
+ prepared (stateField M), words_state, words_state, initial_state, initial_state]
+ · let addr := base + (firstField i).val
+ by_cases hit : ∃ q, addr = symbolAddress base M A.length Z (bitOrder perm Z q)
+ · obtain ⟨q, he⟩ := hit
+ have hidx : i.val = M + rawSlot A.length Z (bitOrder perm Z q) := by
+ dsimp [addr, firstField, symbolAddress] at he
+ omega
+ change (after addr).val = _
+ rw [he, finished.copied _ q.isLt, wordBit_symbol hw, words_first, initial_first, ite_eq_right hr]
+ simp [inputCell, hidx, raw_dense_at A perm dense formal order]
+ · have hne (q : Fin (d*Z)) : addr ≠ symbolAddress base M A.length Z (bitOrder perm Z q) :=
+ fun he => hit ⟨q, he⟩
+ rw [finished.outside _ (fun q _ => hne q), prepared (firstField i), words_first, words_first,
+ initial_first, initial_first, ite_eq_right hr, ite_eq_right hr]
+ by_cases hi : i.val < M
+ · simp [inputCell, hi]
+ · have hout (f : Fin (t*Z)) : i.val - M ≠ rawSlot A.length Z f := by
+ obtain ⟨q, rfl⟩ := (bitOrder perm Z).surjective f
+ intro eq
+ apply hne q
+ dsimp [addr, firstField, symbolAddress]
+ omega
+ simp only [inputCell, hi, ite_false]
+ rw [raw_else A _ formal _ hout]
+ · rw [finished.outside _ (by
+ intro q _
+ have hlt := slot_lt A formal (bitOrder perm Z q)
+ dsimp [secondField, symbolAddress]
+ omega), prepared (secondField i), words_second, words_second, initial_second, initial_second]
+
+end LiveEvaluatorReindex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexNative.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexNative.lean
new file mode 100644
index 0000000000..82810df1b4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexNative.lean
@@ -0,0 +1,363 @@
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+import OAI.Computability.VPVNP.RAMRecords
+import OAI.Computability.VPVNP.LiveHeaderRuns
+
+/-!
+# Native scatter of dense exponent bits into the initial evaluator tape
+
+The incoming cut stores one bit per word, in dense label order and
+least-significant digit first. The map table gives the formal evaluator label
+of each dense label. On the evaluator tape the exponent payload is in reverse
+order and one delimiter separates consecutive payload symbols. A native call
+reads one bit and one map entry, and writes exactly one tape symbol.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorReindex
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Public words are the incoming bit base, label-map base, first exponent
+payload symbol address, bits per label, and total number of payload bits. -/
+def scatterOps : List (Op 32 5) :=
+ [.constant 1 1, .stateWord 26, .publicWord 4 4, .publicWord 3 3,
+ .publicWord 5 0, .binary .add 5 5 26, .read 6 5,
+ .publicWord 7 1, .binary .div 8 26 3, .binary .add 7 7 8, .read 9 7,
+ .binary .mul 9 9 3, .binary .mod 10 26 3, .binary .add 9 9 10,
+ .binary .sub 11 4 1, .binary .sub 11 11 9, .binary .add 11 11 11,
+ .publicWord 12 2, .binary .add 11 12 11, .binary .add 6 6 1,
+ .write 11 6, .binary .add 29 26 1]
+
+/-- The source address of one serialized exponent bit on the incoming cut. -/
+def incomingAddress (pub : Fin 5 → Word w) (q : Word w) := pub 0 + q
+
+/-- The address of the formal label ordinal corresponding to the dense exponent row containing
+this bit. -/
+def mapAddress (pub : Fin 5 → Word w) (q : Word w) :=
+ pub 1 + BinaryOp.div.eval q (pub 3)
+
+/-- The bit index in formal label order, combining the mapped label ordinal with the bit's
+within-row position. -/
+def formalBit (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) :=
+ m (mapAddress pub q).val * pub 3 + BinaryOp.mod.eval q (pub 3)
+
+/-- The bit's destination in the reverse-ordered evaluator tape payload, accounting for the
+interleaved delimiter cells. -/
+def targetAddress (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) :=
+ let back := pub 4 - 1 - formalBit pub q m
+ pub 2 + (back + back)
+
+/-- Encode the incoming exponent bit as a nonblank evaluator tape symbol by adding one. -/
+def inputSymbol (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) :=
+ m (incomingAddress pub q).val + 1
+
+/-- The two reads precede the write, so the read values are both from the
+memory at entry. All arithmetic and cursor updates produce ticks. -/
+def scatterEvents (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) : List (Event w) :=
+ [.tick,.tick,.tick,.tick,.tick,.tick,.read (incomingAddress pub q) (m (incomingAddress pub q).val),
+ .tick,.tick,.tick,.read (mapAddress pub q) (m (mapAddress pub q).val),
+ .tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,
+ .write (targetAddress pub q m) (inputSymbol pub q m),.tick]
+
+theorem scatterEvents_counts (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) :
+ (scatterEvents pub q m).length = 22 ∧ countProbes (scatterEvents pub q m) = 3 ∧
+ choiceBits (scatterEvents pub q m) = [] := ⟨rfl,rfl,rfl⟩
+
+theorem after_scatterEvents (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) :
+ after m (scatterEvents pub q m) =
+ writeMemory m (targetAddress pub q m) (inputSymbol pub q m) := rfl
+
+theorem scatter_trace (pub : Fin 5 → Word w) (q : Word w) (rs : Regs w 32) (m : Memory w) :
+ ∃ out, trace pub q scatterOps rs m = some (scatterEvents pub q m, out,
+ writeMemory m (targetAddress pub q m) (inputSymbol pub q m)) ∧
+ out 29 = q+1 ∧ out 4 = pub 4 := by
+ simp (config := {decide := true}) [scatterOps, trace, Op.effect, Function.update,
+ BinaryOp.eval, scatterEvents, incomingAddress, mapAddress, targetAddress, formalBit, inputSymbol]
+
+theorem scatter_native (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) :
+ let P := ((template scatterOps 29).instantiate w pub).program
+ execute P 23 (P.start q) m [] = some ⟨scatterEvents pub q m,some (q+1)⟩ := by
+ obtain ⟨out,ht,hr,-⟩ := scatter_trace pub q (fun _ => 0) m
+ change execute ((template scatterOps 29).instantiate w pub).program (1 + scatterOps.length) ⟨_,q,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [hr]
+
+theorem incomingAddress_val (pub : Fin 5 → Word w) (q : Word w)
+ (fit : (pub 0).val + q.val < 2 ^ w) :
+ (incomingAddress pub q).val = (pub 0).val + q.val := Nat.mod_eq_of_lt fit
+
+private theorem div_val (q z : Word w) : (BinaryOp.div.eval q z).val = q.val / z.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt q.isLt)
+
+private theorem mod_val (q z : Word w) : (BinaryOp.mod.eval q z).val = q.val % z.val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt q.isLt)
+
+theorem mapAddress_val (pub : Fin 5 → Word w) (q : Word w)
+ (fit : (pub 1).val + q.val / (pub 3).val < 2 ^ w) :
+ (mapAddress pub q).val = (pub 1).val + q.val / (pub 3).val := by
+ rw [mapAddress, Fin.val_add, div_val, Nat.mod_eq_of_lt fit]
+
+/-- With a valid formal bit number, its product and digit addition fit a
+word. The two subtractions are in increasing distance from the right end. -/
+theorem targetAddress_val (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) (hw : 2 ≤ w)
+ (formal : (m (mapAddress pub q).val).val * (pub 3).val + q.val % (pub 3).val < (pub 4).val)
+ (fit : (pub 2).val + 2 * ((pub 4).val - 1 -
+ ((m (mapAddress pub q).val).val * (pub 3).val + q.val % (pub 3).val)) < 2 ^ w) :
+ (targetAddress pub q m).val = (pub 2).val + 2 * ((pub 4).val - 1 -
+ ((m (mapAddress pub q).val).val * (pub 3).val + q.val % (pub 3).val)) := by
+ have total := (pub 4).isLt
+ have one : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega))
+ have hf : (formalBit pub q m).val = (m (mapAddress pub q).val).val * (pub 3).val +
+ q.val % (pub 3).val := by
+ rw [formalBit, Fin.val_add, Fin.val_mul, mod_val,
+ Nat.mod_eq_of_lt (by omega : (m (mapAddress pub q).val).val * (pub 3).val < 2 ^ w),
+ Nat.mod_eq_of_lt (formal.trans total)]
+ have ht : (pub 4 - 1).val = (pub 4).val - 1 := by
+ rw [Fin.sub_val_of_le, one]
+ change (1 : Word w).val ≤ _
+ omega
+ have hb : (pub 4 - 1 - formalBit pub q m).val =
+ (pub 4).val - 1 - ((m (mapAddress pub q).val).val * (pub 3).val + q.val % (pub 3).val) := by
+ rw [Fin.sub_val_of_le, ht, hf]
+ change (formalBit pub q m).val ≤ (pub 4 - 1).val
+ omega
+ dsimp only [targetAddress]
+ rw [Fin.val_add, Fin.val_add, hb, ← two_mul, Nat.add_mod_mod, Nat.mod_eq_of_lt fit]
+
+theorem inputSymbol_val (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) (hw : 2 ≤ w)
+ (bit : (m (incomingAddress pub q).val).val < 2) :
+ (inputSymbol pub q m).val = (m (incomingAddress pub q).val).val + 1 := by
+ have cap : 4 ≤ 2^w := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ rw [inputSymbol, Fin.val_add_one_of_lt' (by omega)]
+
+/-- The phase enters through a cursor check. A completed final write
+accepts in the same burst. On an empty array the initial call accepts
+without accessing either array or the destination tape. -/
+def scatterPhase : Template 30 32 5 where
+ literalWidth := 2
+ entry := 26
+ code i := if h : i.val < scatterOps.length then
+ (scatterOps[i.val]).emit ⟨i.val + 1, by have : scatterOps.length = 22 := rfl; omega⟩ 25
+ else if i = 22 then .jumpEq 29 4 24 23
+ else if i = 23 then .returnState 29
+ else if i = 24 then .accept
+ else if i = 26 then .publicWord 4 4 27
+ else if i = 27 then .stateWord 26 28
+ else if i = 28 then .jumpLt 26 4 0 29
+ else if i = 29 then .jumpEq 26 0 24 25
+ else .reject
+
+/-- Three entry ticks and a final cursor test surround the two reads and
+one write of the scatter block. -/
+def phaseEvents (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) : List (Event w) :=
+ .tick :: .tick :: .tick :: (scatterEvents pub q m ++ [.tick])
+
+theorem phaseEvents_counts (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) :
+ (phaseEvents pub q m).length = 26 ∧ countProbes (phaseEvents pub q m) = 3 ∧
+ choiceBits (phaseEvents pub q m) = [] := ⟨rfl,rfl,rfl⟩
+
+theorem after_phaseEvents (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) :
+ after m (phaseEvents pub q m) =
+ writeMemory m (targetAddress pub q m) (inputSymbol pub q m) := rfl
+
+private theorem contains_scatter (pub : Fin 5 → Word w) :
+ Contains (scatterPhase.instantiate w pub) 25 0 scatterOps 22 := by
+ repeat' first | exact .nil _ | refine .cons (next := _) rfl ?_
+
+private theorem phase_entry (pub : Fin 5 → Word w) (q : Word w) (m : Memory w)
+ (bs : List Bool) (fuel : ℕ) (hq : q < pub 4) :
+ let M := scatterPhase.instantiate w pub
+ let rs : Regs w 32 := Function.update (Function.update (fun _ => 0) 4 (pub 4)) 26 q
+ execute M.program (fuel+3) (M.program.start q) m bs =
+ (execute M.program fuel ⟨0,q,rs,fun _ => 0⟩ m bs).map
+ (fun r => r.prepend .tick |>.prepend .tick |>.prepend .tick) := by
+ dsimp only
+ simp (config := {decide := true}) [execute, Machine.program, scatterPhase, Template.instantiate,
+ Instr.resize, Instr.run, Config.put, Function.update, hq, Option.map_map, Function.comp_def]
+
+private theorem phase_finish (pub : Fin 5 → Word w) (q : Word w) (rs : Regs w 32)
+ (m : Memory w) (bs : List Bool) (fuel : ℕ) :
+ let M := scatterPhase.instantiate w pub
+ execute M.program (fuel+2) ⟨22,q,rs,fun _ => 0⟩ m bs =
+ if bs = [] then some ⟨[.tick], if rs 29 = rs 4 then none else some (rs 29)⟩ else none := by
+ by_cases hb : bs = [] <;> by_cases he : rs 29 = rs 4 <;>
+ simp (config := {decide := true}) [execute, Machine.program, scatterPhase, Template.instantiate,
+ Instr.resize, Instr.run, Report.prepend, hb, he]
+
+/-- Exact execution of the entire native phase on every active cursor and
+choice stream. A nonterminal call returns the next cursor. -/
+theorem execute_phase_active (pub : Fin 5 → Word w) (q : Word w) (m : Memory w)
+ (bs : List Bool) (fuel : ℕ) (hq : q < pub 4) :
+ let P := (scatterPhase.instantiate w pub).program
+ execute P (fuel+27) (P.start q) m bs =
+ if bs = [] then some ⟨phaseEvents pub q m, if q+1 = pub 4 then none else some (q+1)⟩ else none := by
+ let rs : Regs w 32 := Function.update (Function.update (fun _ => 0) 4 (pub 4)) 26 q
+ have hc := (contains_scatter pub).execute (by rfl) q rs (fun _ => 0) m bs (fuel+2)
+ have ⟨out,ht,hn,htotal⟩ := scatter_trace pub q rs m
+ dsimp only
+ rw [show fuel+27 = (fuel+2+scatterOps.length)+3 by rfl, phase_entry pub q m bs _ hq,
+ hc, run_eq_trace]
+ change ((trace pub q scatterOps rs m).bind _).map _ = _
+ rw [ht, Option.bind_some]
+ dsimp only
+ rw [phase_finish, hn, htotal]
+ by_cases hb : bs = [] <;> simp [hb, phaseEvents, Report.prepend]
+
+/-- A zero-capacity phase at its initial cursor consumes no choices and
+does no memory operations. -/
+theorem execute_phase_empty (pub : Fin 5 → Word w) (m : Memory w) (bs : List Bool)
+ (fuel : ℕ) (empty : pub 4 = 0) :
+ let P := (scatterPhase.instantiate w pub).program
+ execute P (fuel+5) (P.start 0) m bs =
+ if bs = [] then some ⟨[.tick,.tick,.tick,.tick],none⟩ else none := by
+ by_cases hb : bs = [] <;> simp (config := {decide := true}) [execute, Machine.program, scatterPhase,
+ Template.instantiate, Instr.resize, Instr.run, Config.put, empty, Report.prepend, hb]
+
+/-- Positive out-of-range cursors cannot accept the phase. -/
+theorem execute_phase_past (pub : Fin 5 → Word w) (q : Word w) (m : Memory w) (bs : List Bool)
+ (fuel : ℕ) (past : pub 4 ≤ q) (positive : q ≠ 0) :
+ let P := (scatterPhase.instantiate w pub).program
+ execute P (fuel+5) (P.start q) m bs = none := by
+ simp (config := {decide := true}) [execute, Machine.program, scatterPhase, Template.instantiate,
+ Instr.resize, Instr.run, Config.put, Function.update, not_lt.mpr past, positive]
+
+/-- A complete native scatter sweep. Every nonempty row contributes its
+payload calls, with the final call accepting. The empty sweep uses its
+single accepting entry check and preserves the initial memory. -/
+theorem scatterPhase_segment (pub : Fin 5 → Word w) (T : ℕ) (total : (pub 4).val = T)
+ (inv : ℕ → Memory w → Prop) (original : Memory w) (init : inv 0 original)
+ (step : ∀ j < T, ∀ m, inv j m → inv (j+1) (after m (phaseEvents pub (j : Word w) m))) :
+ let P := (scatterPhase.instantiate w pub).program
+ ∃ rs, runSegment P 27 (some 0) original (List.replicate (max 1 T) []) = some rs ∧
+ endState (some 0) rs = none ∧ inv T (after original (eventLog rs)) ∧
+ rs.length = max 1 T ∧ ∀ r ∈ rs, countProbes r.events ≤ 3 := by
+ let P := (scatterPhase.instantiate w pub).program
+ cases T with
+ | zero =>
+ let last : Report w := ⟨[.tick,.tick,.tick,.tick],none⟩
+ have he : execute P 27 (P.start 0) original [] = some last := by
+ simpa only [ite_true] using execute_phase_empty pub original [] 22 (Fin.ext total)
+ refine ⟨[last], ?_, rfl, init, rfl, ?_⟩
+ · change (match execute P 27 (P.start 0) original [] with
+ | none => none | some r => some [r]) = some [last]
+ rw [he]
+ · intro r hr
+ have := List.mem_singleton.mp hr
+ subst r
+ change 0 ≤ 3
+ decide
+ | succ n =>
+ have fit := (pub 4).isLt
+ have val (j : ℕ) (hj : j ≤ n+1) : (j : Word w).val = j :=
+ Fin.val_cast_of_lt (by omega)
+ have call (j : ℕ) (hj : j ≤ n) (m : Memory w) :
+ execute P 27 (P.start (j : Word w)) m [] =
+ some ⟨phaseEvents pub (j : Word w) m, if j = n then none else some ((j+1 : ℕ) : Word w)⟩ := by
+ have hq : (j : Word w) < pub 4 := by
+ rw [Fin.lt_def, val _ (by omega), total]
+ omega
+ have hn : (j : Word w) + 1 = ((j+1 : ℕ) : Word w) := by simp
+ have iff : ((j+1 : ℕ) : Word w) = pub 4 ↔ j = n := by
+ rw [Fin.ext_iff, val _ (by omega), total]
+ omega
+ simpa only [ite_true, hn, iff] using execute_phase_active pub (j : Word w) m [] 0 hq
+ obtain ⟨rs,hr,hs,hi,hl,hp⟩ := LiveHeader.run_cursor_segment P 27 n 3 inv original init
+ (fun j hj m hm => ⟨phaseEvents pub (j : Word w) m, by
+ simpa only [ite_eq_right (Nat.ne_of_lt hj)] using call j hj.le m,
+ step j (by omega) m hm, (phaseEvents_counts pub _ m).2.1.le⟩)
+ let m := after original (eventLog rs)
+ let last : Report w := ⟨phaseEvents pub (n : Word w) m, none⟩
+ have he : execute P 27 (P.start (n : Word w)) m [] = some last := by
+ simpa only [ite_true] using call n le_rfl m
+ rw [max_eq_right (by omega : 1 ≤ n+1)]
+ refine ⟨rs ++ [last], ?_, ?_, ?_, by simp [hl], ?_⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, hr]
+ simp only [Option.bind_some, hs, runSegment]
+ rw [he]
+ rfl
+ · rw [endState_append]
+ rfl
+ · simpa only [last, m, eventLog, List.flatMap_append, List.flatMap_singleton, after, List.foldl_append]
+ using step n (by omega) m hi
+ · intro r hr'
+ rcases List.mem_append.mp hr' with h | h
+ · exact hp r h
+ · have eq : r = last := List.mem_singleton.mp h
+ exact eq ▸ (phaseEvents_counts pub (n : Word w) m).2.1.le
+
+/-- An accepting run from any cursor consumes exactly its remaining calls,
+each with the empty choice stream. This includes runs of arbitrary
+proposed lengths and establishes uniqueness of the initialization path. -/
+theorem scatterPhase_choices (pub : Fin 5 → Word w) (q : Word w) (m : Memory w)
+ (bs : List (List Bool)) (rs : List (Report w)) (fuel : ℕ)
+ (run : runSegment (scatterPhase.instantiate w pub).program (fuel+27) (some q) m bs = some rs)
+ (halt : endState (some q) rs = none) :
+ bs = List.replicate (max 1 ((pub 4).val - q.val)) [] := by
+ induction bs generalizing q m rs with
+ | nil =>
+ change some [] = some rs at run
+ cases run
+ contradiction
+ | cons b bs ih =>
+ let P := (scatterPhase.instantiate w pub).program
+ rw [runSegment] at run
+ cases h : execute P (fuel+27) (P.start q) m b with
+ | none => simp [P] at h; simp [h] at run
+ | some r =>
+ change execute (scatterPhase.instantiate w pub).program (fuel+27)
+ ((scatterPhase.instantiate w pub).program.start q) m b = some r at h
+ rw [h, Option.map_eq_some_iff] at run
+ obtain ⟨rest, tail, rfl⟩ := run
+ change endState r.result rest = none at halt
+ have final (done : r.result = none) : bs = [] := by
+ rw [done] at tail
+ cases bs <;> first | rfl | contradiction
+ by_cases active : q < pub 4
+ · rw [execute_phase_active pub q m b fuel active] at h
+ split at h
+ · rename_i empty
+ subst b
+ obtain rfl := (Option.some.inj h).symm
+ have hv : (q+1).val = q.val+1 := Fin.val_add_one_of_lt' ((Nat.succ_le_of_lt active).trans_lt (pub 4).isLt)
+ by_cases last : q+1 = pub 4
+ · rw [final (ite_eq_left last)]
+ have he := congrArg Fin.val last
+ rw [hv] at he
+ rw [show max 1 ((pub 4).val - q.val) = 1 by omega]
+ rfl
+ · rw [ite_eq_right last] at tail halt
+ rw [ih (q+1) _ _ tail halt]
+ have hlt : q.val < (pub 4).val := active
+ have hne : (q+1).val ≠ (pub 4).val := fun e => last (Fin.ext e)
+ rw [hv] at hne ⊢
+ rw [show max 1 ((pub 4).val - q.val) = max 1 ((pub 4).val - (q.val+1)) + 1 by omega,
+ List.replicate_succ]
+ · contradiction
+ · by_cases zero : q = 0
+ · subst q
+ have empty : pub 4 = 0 := Fin.ext (by
+ change ¬ (0 : Word w).val < (pub 4).val at active
+ simpa using Nat.eq_zero_of_not_pos active)
+ rw [show fuel+27 = (fuel+22)+5 by omega, execute_phase_empty pub m b _ empty] at h
+ split at h
+ · rename_i hb
+ subst b
+ obtain rfl := (Option.some.inj h).symm
+ rw [final rfl]
+ simp [empty]
+ · contradiction
+ · rw [show fuel+27 = (fuel+22)+5 by omega,
+ execute_phase_past pub q m b _ (le_of_not_gt active) zero] at h
+ contradiction
+
+end LiveEvaluatorReindex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexPrepare.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexPrepare.lean
new file mode 100644
index 0000000000..7d1855a282
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexPrepare.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.LiveEvaluatorReindexImage
+
+/-!
+# Joining the physical prefix and runtime initialization writes
+
+The prefix copy stops at the true length of the advised evaluator input.
+The runtime skeleton starts at that address. Together these prepare the
+state bank used by the exponent scatter phase.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorInitialize
+
+open BurstRAM LiveEvaluatorEncoding EvaluatorProgramRawInput
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Adjacent completed native copies agree with a single copy of the
+concatenated stream, including the case of an empty first or second piece. -/
+theorem Copied.append {A R : List Bool} {base : ℕ} {m₀ m₁ m₂ : Memory w}
+ (prefixCopy : Copied A base A.length m₀ m₁)
+ (runtimeCopy : Copied R (base+A.length) R.length m₁ m₂) :
+ Copied (A++R) base (A++R).length m₀ m₂ := by
+ constructor
+ · intro j hj
+ rw [List.length_append] at hj
+ by_cases hp : j < A.length
+ · rw [runtimeCopy.outside _ (Or.inl (by omega)), prefixCopy.symbols _ hp,
+ List.getElem?_append_left hp]
+ · have eq : base+j = (base+A.length)+(j-A.length) := by omega
+ rw [eq, runtimeCopy.symbols _ (by omega), List.getElem?_append_right (Nat.le_of_not_gt hp)]
+ · intro a ha
+ rw [List.length_append] at ha
+ exact (runtimeCopy.outside a (by omega)).trans (prefixCopy.outside a (by omega))
+
+/-- Native control, exact advice-prefix and runtime-skeleton writes prepare
+the zero-exponent bank. The addresses here use the actual prefix length. -/
+theorem prefix_runtime_stores {t Z : ℕ} (hw : 2 ≤ w) (pub : Fin 4 → Word w)
+ (p : UniversalMachine.Program) (running : p.extra ≠ 0) (hs : p.extra+2 ≤ 2^w) (A : List Bool)
+ (blank m₁ m₂ : Memory w)
+ (space : (A ++ runtime (fun _ : Fin t => (0 : Word Z))).length ≤ (pub 0).val + 1)
+ (zero : ∀ k : Fin (fieldWords (pub 0).val), blank ((pub 1).val + k.val) = 0)
+ (prefixCopy : Copied A (firstData pub) A.length
+ (writeMemory blank (pub 1) (Fin.ofNat _ (controlTag p).val)) m₁)
+ (runtimeCopy : Copied (runtime (fun _ : Fin t => (0 : Word Z))) (firstData pub+A.length)
+ (2*(t*Z)+6*Z+4) m₁ m₂) :
+ Stores hw hs (pub 1).val m₂ (LiveEvaluatorTail.initialCode (pub 0).val (UniversalMachine.initial p
+ (A ++ runtime (fun _ : Fin t => (0 : Word Z))))) := by
+ apply copied_stores hw pub p hs _ blank m₂ space zero
+ rw [activeLength, ite_eq_right running]
+ exact prefixCopy.append (by simpa only [runtime_length] using runtimeCopy)
+
+end LiveEvaluatorInitialize
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexSkeleton.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexSkeleton.lean
new file mode 100644
index 0000000000..e534bffc73
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexSkeleton.lean
@@ -0,0 +1,395 @@
+import OAI.Computability.VPVNP.LiveEvaluatorReindex
+import OAI.Computability.VPVNP.LiveEvaluatorInitializeStages
+
+/-!
+# Writing the zero-exponent evaluator input on the live tape
+
+The runtime suffix consists of three unary width fields and one exponent
+field, with a zero terminator after each field. The exponent payload symbols
+start at zero and are overwritten by the subsequent coordinate scatter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorReindexSkeleton
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Evaluator.InputBank
+open scoped Fin.CommRing
+
+variable {w t Z : ℕ}
+
+/-- Characterization of the zero-exponent runtime input by absolute address.
+The exponent field begins at an odd offset, so its tags have odd addresses. -/
+def skeletonBit (Z T j : ℕ) : Bool :=
+ if j = 2*Z ∨ j = 2*Z+1+2*T ∨ j = 4*Z+2+2*T ∨ j+1 = 2*T+6*Z+4 then false
+ else if 2*Z < j ∧ j < 2*Z+1+2*T then decide (j%2 = 1) else true
+
+private theorem constant_field (n j : ℕ) (b : Bool) (hj : j < 2*n+1) :
+ (fieldBits (List.replicate n b))[j]? =
+ some (if j = 2*n then false else if j%2 = 0 then true else b) := by
+ let xs := List.replicate n b
+ have hx : xs.length = n := List.length_replicate ..
+ rw [List.getElem?_eq_getElem (by rw [length_fieldBits, List.length_replicate]; omega)]
+ apply congrArg some
+ by_cases h : j = 2*n
+ · subst j
+ simpa [hx, xs] using fieldBits_end xs
+ let i : Fin xs.length := ⟨j/2, by omega⟩
+ by_cases he : j%2 = 0
+ · have hi : 2*i.val = j := by dsimp [i]; omega
+ simpa [hi,h,he] using fieldBits_tag xs i
+ · have hi : 2*i.val+1 = j := by dsimp [i]; omega
+ simpa [hi,h,he,xs] using fieldBits_payload xs i
+
+private theorem zero_array (t Z : ℕ) :
+ List.ofFn (RAMSerialization.arrayBits t Z (fun _ => 0)) = List.replicate (t*Z) false := by
+ apply List.ext_getElem
+ · simp
+ · intro j hj hk
+ simp only [List.getElem_ofFn, List.getElem_replicate]
+ obtain ⟨⟨a,b⟩,he⟩ := finProdFinEquiv.surjective (⟨j,by simpa using hj⟩ : Fin (t*Z))
+ rw [← he, RAMSerialization.arrayBits_at, RAMSerialization.wordBits_zero]
+
+/-- Every generated symbol is the corresponding byte of the actual serialized
+evaluator input for the zero exponent vector. -/
+theorem runtime_zero_at (t Z j : ℕ) (hj : j < 2*(t*Z)+6*Z+4) :
+ (EvaluatorProgramRawInput.runtime (fun _ : Fin t => (0 : Word Z)))[j]? =
+ some (skeletonBit Z (t*Z) j) := by
+ let T := t*Z
+ let U := fieldBits (List.replicate Z true)
+ let E := fieldBits (List.replicate T false)
+ have hU : U.length = 2*Z+1 := by simp [U, length_fieldBits]
+ have hE : E.length = 2*T+1 := by simp [E, length_fieldBits]
+ change j < 2*T+6*Z+4 at hj
+ rw [EvaluatorProgramRawInput.runtime, zero_array, List.append_assoc, List.append_assoc]
+ change (U ++ (E ++ (U ++ U)))[j]? = some (skeletonBit Z T j)
+ by_cases h₀ : j < U.length
+ · rw [List.getElem?_append_left h₀, constant_field Z j true (by omega)]
+ simp only [skeletonBit]; split_ifs <;> first | rfl | omega
+ rw [List.getElem?_append_right (Nat.le_of_not_gt h₀)]
+ by_cases h₁ : j-U.length < E.length
+ · rw [List.getElem?_append_left h₁, constant_field T _ false (by omega)]
+ simp only [skeletonBit]; split_ifs <;> simp_all <;> omega
+ rw [List.getElem?_append_right (Nat.le_of_not_gt h₁)]
+ by_cases h₂ : j-U.length-E.length < U.length
+ · rw [List.getElem?_append_left h₂, constant_field Z _ true (by omega)]
+ simp only [skeletonBit]; split_ifs <;> first | rfl | omega
+ rw [List.getElem?_append_right (Nat.le_of_not_gt h₂), constant_field Z _ true (by omega)]
+ simp only [skeletonBit]; split_ifs <;> first | rfl | omega
+
+
+/-- Public words give the unary width, total number of exponent bits, first
+destination symbol address, and total length of the runtime suffix. -/
+def setupOps : List (Op 32 4) :=
+ [.constant 1 1, .constant 2 2, .stateWord 3, .publicWord 4 0, .publicWord 5 1,
+ .publicWord 6 2, .publicWord 7 3, .binary .add 8 4 4, .binary .add 9 5 5,
+ .binary .add 9 9 8, .binary .add 9 9 1, .binary .add 10 8 9,
+ .binary .add 10 10 1, .binary .add 11 3 1, .binary .add 12 6 3,
+ .binary .mod 13 3 2, .binary .add 13 13 1]
+
+/-- Every active path uses eight local control instructions after setup to
+select the tape symbol, one write, and one last-cursor test. -/
+def skeletonStage : Template 38 32 4 where
+ literalWidth := 2
+ entry := 0
+ code i := if h : i.val < setupOps.length then
+ setupOps[i.val].emit ⟨i.val+1, by have : setupOps.length = 17 := rfl; omega⟩ 31
+ else match i.val with
+ | 17 => .jumpLt 3 7 18 31
+ | 18 => .jumpEq 3 8 32 19
+ | 19 => .jumpEq 3 9 33 20
+ | 20 => .jumpEq 3 10 34 21
+ | 21 => .jumpEq 11 7 35 22
+ | 22 => .jumpLt 8 3 23 24
+ | 23 => .jumpLt 3 9 25 26
+ | 24 => .copy 15 15 26
+ | 25 => .copy 15 13 27
+ | 26 => .copy 15 2 27
+ | 27 => .writeExternal 12 15 28
+ | 28 => .jumpEq 11 7 29 30
+ | 29 => .accept
+ | 30 => .returnState 11
+ | 32 => .copy 15 1 33
+ | 33 => .copy 15 1 34
+ | 34 => .copy 15 1 35
+ | 35 => .copy 15 1 36
+ | 36 => .copy 15 1 37
+ | 37 => .copy 15 1 27
+ | _ => .reject
+
+private def end₀ (pub : Fin 4 → Word w) := pub 0 + pub 0
+private def end₁ (pub : Fin 4 → Word w) := (pub 1 + pub 1) + end₀ pub + 1
+private def end₂ (pub : Fin 4 → Word w) := end₀ pub + end₁ pub + 1
+
+private def selected (pub : Fin 4 → Word w) (j : Word w) : Word w :=
+ if j = end₀ pub ∨ j = end₁ pub ∨ j = end₂ pub ∨ j+1 = pub 3 then 1
+ else if end₀ pub < j ∧ j < end₁ pub then BinaryOp.mod.eval j 2 + 1 else 2
+
+private theorem setup_trace (pub : Fin 4 → Word w) (j : Word w) (regs : Regs w 32) (m : Memory w) :
+ ∃ out, trace pub j setupOps regs m = some (List.replicate 17 .tick, out, m) ∧
+ out 1 = 1 ∧ out 2 = 2 ∧ out 3 = j ∧ out 7 = pub 3 ∧ out 8 = end₀ pub ∧
+ out 9 = end₁ pub ∧ out 10 = end₂ pub ∧ out 11 = j+1 ∧ out 12 = pub 2 + j ∧
+ out 13 = BinaryOp.mod.eval j 2 + 1 := by
+ simp (config := {decide := true}) [setupOps, trace, Op.effect, Function.update,
+ BinaryOp.eval, end₀, end₁, end₂]
+
+private theorem contains_setup (pub : Fin 4 → Word w) :
+ Contains (skeletonStage.instantiate w pub) 31 0 setupOps 17 := by
+ iterate 17 apply Contains.cons rfl
+ exact .nil _
+
+private def regSymbol (r : Regs w 32) : Word w :=
+ if r 3 = r 8 ∨ r 3 = r 9 ∨ r 3 = r 10 ∨ r 11 = r 7 then r 1
+ else if r 8 < r 3 ∧ r 3 < r 9 then r 13 else r 2
+
+private abbrev SkelMachine (w : ℕ) := Machine w 38 32 4
+private abbrev SkelPC := Fin 38
+private abbrev SkelReg := Fin 32
+
+private theorem execLt (M : SkelMachine w) (pc yes no : SkelPC) (a b : SkelReg)
+ (h : M.code pc = .jumpLt a b yes no) (j : Word w) (r : Regs w 32) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute M.program (f+1) ⟨pc,j,r,fun _ => 0⟩ m bits =
+ (execute M.program f ⟨if r a < r b then yes else no,j,r,fun _ => 0⟩ m bits).map (Report.prepend .tick) := by
+ simp only [execute, Machine.program, h, Instr.run]
+
+private theorem execEq (M : SkelMachine w) (pc yes no : SkelPC) (a b : SkelReg)
+ (h : M.code pc = .jumpEq a b yes no) (j : Word w) (r : Regs w 32) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute M.program (f+1) ⟨pc,j,r,fun _ => 0⟩ m bits =
+ (execute M.program f ⟨if r a = r b then yes else no,j,r,fun _ => 0⟩ m bits).map (Report.prepend .tick) := by
+ simp only [execute, Machine.program, h, Instr.run]
+
+private theorem execCopy (M : SkelMachine w) (pc next : SkelPC) (src : SkelReg)
+ (h : M.code pc = .copy 15 src next) (j : Word w) (r : Regs w 32) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute M.program (f+1) ⟨pc,j,r,fun _ => 0⟩ m bits =
+ (execute M.program f ⟨next,j,Function.update r 15 (r src),fun _ => 0⟩ m bits).map (Report.prepend .tick) := by
+ simp only [execute, Machine.program, h, Instr.run, Config.put]
+
+private theorem execWrite (pub : Fin 4 → Word w) (j : Word w) (r : Regs w 32)
+ (m : Memory w) (bits : List Bool) (f : ℕ) :
+ let M := skeletonStage.instantiate w pub
+ execute M.program (f+3) ⟨27,j,r,fun _ => 0⟩ m bits = if bits = [] then
+ some ⟨[.write (r 12) (r 15),.tick], if r 11 = r 7 then none else some (r 11)⟩ else none := by
+ let M := skeletonStage.instantiate w pub
+ have h27 : M.code 27 = .writeExternal 12 15 28 := rfl
+ have h28 : M.code 28 = .jumpEq 11 7 29 30 := rfl
+ have h29 : M.code 29 = .accept := rfl
+ have h30 : M.code 30 = .returnState 11 := rfl
+ change execute M.program (f+3) _ m bits = _
+ by_cases he : r 11 = r 7 <;> cases bits <;>
+ simp only [execute, Machine.program, h27,h28,h29,h30, Instr.run, he, ↓reduceIte,
+ reduceCtorEq, Option.map_some, Option.map_none, Report.prepend]
+
+private theorem control_exec (pub : Fin 4 → Word w) (j : Word w) (r : Regs w 32) (m : Memory w)
+ (f : ℕ) (bits : List Bool) (active : r 3 < r 7) :
+ let M := skeletonStage.instantiate w pub
+ execute M.program (f+11) ⟨17,j,r,fun _ => 0⟩ m bits = if bits = [] then
+ some ⟨List.replicate 8 .tick ++ [.write (r 12) (regSymbol r),.tick],
+ if r 11 = r 7 then none else some (r 11)⟩ else none := by
+ let M := skeletonStage.instantiate w pub
+ change execute M.program (f+11) _ m bits = _
+ have op17 := execLt M 17 18 31 3 7 (by rfl)
+ have op18 := execEq M 18 32 19 3 8 (by rfl)
+ have op19 := execEq M 19 33 20 3 9 (by rfl)
+ have op20 := execEq M 20 34 21 3 10 (by rfl)
+ have op21 := execEq M 21 35 22 11 7 (by rfl)
+ have op22 := execLt M 22 23 24 8 3 (by rfl)
+ have op23 := execLt M 23 25 26 3 9 (by rfl)
+ have op24 := execCopy M 24 26 15 (by rfl)
+ have op25 := execCopy M 25 27 13 (by rfl)
+ have op26 := execCopy M 26 27 2 (by rfl)
+ have op32 := execCopy M 32 33 1 (by rfl)
+ have op33 := execCopy M 33 34 1 (by rfl)
+ have op34 := execCopy M 34 35 1 (by rfl)
+ have op35 := execCopy M 35 36 1 (by rfl)
+ have op36 := execCopy M 36 37 1 (by rfl)
+ have op37 := execCopy M 37 27 1 (by rfl)
+ have write := execWrite pub j
+ change ∀ (r : Regs w 32) (m : Memory w) (bs : List Bool) (f : ℕ), execute M.program (f+3) _ m bs = _ at write
+ rw [op17, ite_eq_left active, op18]
+ by_cases h₀ : r 3 = r 8
+ · rw [ite_eq_left h₀, op32, op33, op34, op35, op36, op37, write]
+ cases bits <;> simp (config := {decide := true}) [regSymbol,h₀,Function.update,Report.prepend]
+ rw [ite_eq_right h₀, op19]
+ by_cases h₁ : r 3 = r 9
+ · rw [ite_eq_left h₁, op33, op34, op35, op36, op37, write]
+ cases bits <;> simp (config := {decide := true}) [regSymbol,h₁,Function.update,Report.prepend]
+ rw [ite_eq_right h₁, op20]
+ by_cases h₂ : r 3 = r 10
+ · rw [ite_eq_left h₂, op34, op35, op36, op37, write]
+ cases bits <;> simp (config := {decide := true}) [regSymbol,h₂,Function.update,Report.prepend]
+ rw [ite_eq_right h₂, op21]
+ by_cases h₃ : r 11 = r 7
+ · rw [ite_eq_left h₃, op35, op36, op37, write]
+ cases bits <;> simp (config := {decide := true}) [regSymbol,h₃,Function.update,Report.prepend]
+ rw [ite_eq_right h₃, op22]
+ by_cases h₄ : r 8 < r 3
+ · rw [ite_eq_left h₄,op23]
+ by_cases h₅ : r 3 < r 9
+ · rw [ite_eq_left h₅,op25,write]
+ cases bits <;> simp (config := {decide := true}) [regSymbol,h₀,h₁,h₂,h₃,h₄,h₅,Function.update,Report.prepend]
+ · rw [ite_eq_right h₅,op26,write]
+ cases bits <;> simp (config := {decide := true}) [regSymbol,h₀,h₁,h₂,h₃,h₅,Function.update,Report.prepend]
+ · rw [ite_eq_right h₄,op24,op26,write]
+ cases bits <;> simp (config := {decide := true}) [regSymbol,h₀,h₁,h₂,h₃,h₄,Function.update,Report.prepend]
+
+/-- An active call is deterministic and emits exactly one symbol write.
+The last cell hands off to the next stage in that same call. -/
+private theorem execute_active_word (pub : Fin 4 → Word w) (j : Word w) (m : Memory w)
+ (f : ℕ) (bits : List Bool) (active : j < pub 3) :
+ let P := (skeletonStage.instantiate w pub).program
+ execute P (f+28) (P.start j) m bits = if bits = [] then
+ some ⟨List.replicate 25 .tick ++ [.write (pub 2 + j) (selected pub j),.tick],
+ if j+1 = pub 3 then none else some (j+1)⟩ else none := by
+ obtain ⟨rs, ht, h1,h2,h3,h7,h8,h9,h10,h11,h12,h13⟩ := setup_trace pub j (fun _ => 0) m
+ have he := (contains_setup pub).execute (by rfl) j (fun _ => 0) (fun _ => 0) m bits (f+11)
+ dsimp only
+ change execute _ (f+11+setupOps.length) (Config.mk 0 j (fun _ => 0) (fun _ => 0)) m bits = _
+ rw [he, run_eq_trace]
+ change (trace pub j setupOps (fun _ => 0) m).bind _ = _
+ rw [ht, Option.bind_some]
+ dsimp only
+ rw [control_exec pub j rs m f bits (by rwa [h3,h7])]
+ simp only [regSymbol, selected, h1,h2,h3,h7,h8,h9,h10,h11,h12,h13]
+ cases bits <;> rfl
+
+
+private theorem selected_eq (hw : 2 ≤ w) (pub : Fin 4 → Word w) (j : Word w)
+ (hlen : (pub 3).val = 2*(pub 1).val + 6*(pub 0).val + 4) (active : j < pub 3) :
+ selected pub j = PrimedInputRAM.encodeBit w (skeletonBit (pub 0).val (pub 1).val j.val) + 1 := by
+ have cap := (pub 3).isLt
+ have hj := Fin.lt_def.mp active
+ have a : (end₀ pub).val = 2*(pub 0).val := by
+ rw [end₀, Fin.val_add_eq_of_add_lt (by omega)]; omega
+ have b : (end₁ pub).val = 2*(pub 0).val + 1 + 2*(pub 1).val := by
+ unfold end₁
+ have d : (pub 1 + pub 1).val = 2*(pub 1).val := by
+ rw [Fin.val_add_eq_of_add_lt (by omega)]; omega
+ have e : ((pub 1 + pub 1) + end₀ pub).val = 2*(pub 1).val + 2*(pub 0).val :=
+ by rw [Fin.val_add_eq_of_add_lt (by omega), d, a]
+ rw [Fin.val_add_one_of_lt' (by omega), e]; omega
+ have c : (end₂ pub).val = 4*(pub 0).val + 2 + 2*(pub 1).val := by
+ unfold end₂
+ have e := Fin.val_add_eq_of_add_lt (a := end₀ pub) (b := end₁ pub) (by omega)
+ rw [Fin.val_add_one_of_lt' (by omega), e,a,b]; omega
+ have hn : (j+1).val = j.val+1 := Fin.val_add_one_of_lt' (by omega)
+ have htwo : (2 : Word w).val = 2 :=
+ Nat.mod_eq_of_lt (lt_of_lt_of_le (by decide : 2 < 2^2) (Nat.pow_le_pow_right (by decide) hw))
+ have parity : BinaryOp.mod.eval j 2 = if j.val%2 = 1 then 1 else 0 := by
+ change Fin.ofNat _ (j.val % (2 : Word w).val) = _
+ rw [htwo]
+ by_cases h : j.val%2 = 1
+ · rw [ite_eq_left h,h]; rfl
+ · rw [ite_eq_right h, show j.val%2 = 0 by omega]; rfl
+ simp only [selected, skeletonBit, parity, show j = end₀ pub ↔ j.val = 2*(pub 0).val by rw [Fin.ext_iff,a],
+ show j = end₁ pub ↔ j.val = 2*(pub 0).val+1+2*(pub 1).val by rw [Fin.ext_iff,b],
+ show j = end₂ pub ↔ j.val = 4*(pub 0).val+2+2*(pub 1).val by rw [Fin.ext_iff,c],
+ show j+1 = pub 3 ↔ j.val+1 = 2*(pub 1).val+6*(pub 0).val+4 by rw [Fin.ext_iff,hn,hlen],
+ Fin.lt_def, a, b]
+ split_ifs <;> simp_all [PrimedInputRAM.encodeBit]
+ norm_num
+
+/-- Report for one runtime position: local control ticks, one external write,
+and the local cursor test. -/
+def events (addr symbol : Word w) : List (Event w) :=
+ List.replicate 25 .tick ++ [.write addr symbol, .tick]
+
+theorem events_counts (addr symbol : Word w) :
+ (events addr symbol).length = 27 ∧ countProbes (events addr symbol) = 1 ∧
+ choiceBits (events addr symbol) = [] := ⟨rfl,rfl,rfl⟩
+
+theorem events_after (addr symbol : Word w) (m : Memory w) :
+ after m (events addr symbol) = writeMemory m addr symbol := rfl
+
+/-- With the actual evaluator dimensions, the native stage writes the actual
+serialized input bit, encoded as a nonblank two-tape symbol. -/
+theorem skeletonStage_call (hw : 2 ≤ w) (pub : Fin 4 → Word w) (j : Word w) (m : Memory w)
+ (width : (pub 0).val = Z) (total : (pub 1).val = t*Z)
+ (length : (pub 3).val = 2*(t*Z)+6*Z+4) (active : j < pub 3) (bits : List Bool) (f : ℕ) :
+ let P := (skeletonStage.instantiate w pub).program
+ let raw := EvaluatorProgramRawInput.runtime (fun _ : Fin t => (0 : Word Z))
+ let symbol := PrimedInputRAM.encodeBit w (raw[j.val]?.getD false) + 1
+ execute P (f+28) (P.start j) m bits = if bits = [] then
+ some ⟨events (pub 2 + j) symbol, if j+1 = pub 3 then none else some (j+1)⟩ else none := by
+ have ha : j.val < 2*(t*Z)+6*Z+4 := by simpa [← length] using Fin.lt_def.mp active
+ dsimp only
+ rw [execute_active_word pub j m f bits active, selected_eq hw pub j (by rwa [width,total]) active,
+ width, total, runtime_zero_at t Z j.val ha]
+ rfl
+
+
+/-- The complete runtime preparation uses one deterministic call per symbol.
+The four terminating zeros guarantee a nonempty sweep even if either
+dimension vanishes. Every address outside the prepared interval is preserved. -/
+theorem skeletonStage_sweep (hw : 2 ≤ w) (pub : Fin 4 → Word w) (original : Memory w)
+ (width : (pub 0).val = Z) (total : (pub 1).val = t*Z)
+ (length : (pub 3).val = 2*(t*Z)+6*Z+4) (fit : (pub 2).val + (pub 3).val ≤ 2^w) :
+ let raw := EvaluatorProgramRawInput.runtime (fun _ : Fin t => (0 : Word Z))
+ let P := (skeletonStage.instantiate w pub).program
+ ∃ rs, runSegment P 28 (some 0) original (List.replicate raw.length []) = some rs ∧
+ endState (some 0) rs = none ∧
+ LiveEvaluatorInitialize.Copied raw (pub 2).val raw.length original (after original (eventLog rs)) ∧
+ rs.length = raw.length ∧ ∀ r ∈ rs, countProbes r.events ≤ 1 := by
+ let raw := EvaluatorProgramRawInput.runtime (fun _ : Fin t => (0 : Word Z))
+ let n := raw.length - 1
+ have hlen : raw.length = n+1 := by
+ have h : raw.length = 2*(t*Z)+6*Z+4 := EvaluatorProgramRawInput.runtime_length _
+ dsimp [n]; omega
+ have hpub : (pub 3).val = n+1 := length.trans ((EvaluatorProgramRawInput.runtime_length _).symm.trans hlen)
+ let P := (skeletonStage.instantiate w pub).program
+ let inv (j : ℕ) := LiveEvaluatorInitialize.Copied raw (pub 2).val j original
+ let ev (j : ℕ) := events (pub 2 + (j : Word w)) (PrimedInputRAM.encodeBit w (raw[j]?.getD false) + 1)
+ have hcast (j : ℕ) (h : j ≤ n+1) : (j : Word w).val = j :=
+ Fin.val_cast_of_lt (by have := (pub 3).isLt; omega)
+ have call (j : ℕ) (hj : j ≤ n) (m : Memory w) :
+ execute P 28 (P.start (j : Word w)) m [] =
+ some ⟨ev j, if j = n then none else some ((j+1 : ℕ) : Word w)⟩ := by
+ have ha : (j : Word w) < pub 3 := Fin.lt_def.mpr (by rw [hcast j (by omega),hpub]; omega)
+ have hn : (j : Word w) + 1 = ((j+1 : ℕ) : Word w) := by simp
+ have iff : ((j+1 : ℕ) : Word w) = pub 3 ↔ j = n := by
+ rw [Fin.ext_iff, hcast _ (by omega), hpub]; omega
+ simpa only [ev, raw, hcast j (by omega), hn, iff, ite_true]
+ using skeletonStage_call hw pub (j : Word w) m width total length ha [] 0
+ have step (j : ℕ) (hj : j ≤ n) (m : Memory w) (h : inv j m) : inv (j+1) (after m (ev j)) := by
+ have addr : (pub 2 + (j : Word w)).val = (pub 2).val+j := by
+ rw [Fin.val_add_eq_of_add_lt (by rw [hcast j (by omega)]; omega), hcast j (by omega)]
+ dsimp only [ev]
+ rw [events_after]
+ constructor
+ · intro i hi
+ by_cases eq : i = j
+ · subst i; simp [writeMemory, addr]
+ · simp [writeMemory, addr, eq, h.symbols i (by omega)]
+ · intro a ha
+ rw [writeMemory, ite_eq_right (by omega)]
+ exact h.outside _ (by omega)
+ have initial : inv 0 original := ⟨fun _ h => (Nat.not_lt_zero _ h).elim, fun _ _ => rfl⟩
+ obtain ⟨rs,hr,hs,hi,hl,hp⟩ := LiveHeader.run_cursor_segment P 28 n 1 inv original initial
+ (fun j hj m hm => ⟨ev j, by simpa only [ite_eq_right (Nat.ne_of_lt hj)] using call j hj.le m,
+ step j hj.le m hm, (events_counts ..).2.1.le⟩)
+ let last : Report w := ⟨ev n,none⟩
+ have he : execute P 28 (P.start (n : Word w)) (after original (eventLog rs)) [] = some last := by
+ simpa only [ite_true] using call n le_rfl (after original (eventLog rs))
+ change ∃ rs : List (Report w), runSegment P 28 (some 0) original (List.replicate raw.length []) = some rs ∧
+ endState (some 0) rs = none ∧ inv raw.length (after original (eventLog rs)) ∧ rs.length = raw.length ∧ _
+ rw [hlen]
+ refine ⟨rs ++ [last], ?_, ?_, ?_, by simp [hl], ?_⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, hr]
+ simp only [Option.bind_some, hs, runSegment]
+ rw [he]
+ rfl
+ · rw [endState_append]; rfl
+ · simpa only [last, eventLog, List.flatMap_append, List.flatMap_singleton, after, List.foldl_append]
+ using step n le_rfl _ hi
+ · intro r hr
+ rcases List.mem_append.mp hr with h | h
+ · exact hp r h
+ · have heq : r = last := List.mem_singleton.mp h
+ exact heq ▸ (events_counts ..).2.1.le
+
+end LiveEvaluatorReindexSkeleton
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexSweep.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexSweep.lean
new file mode 100644
index 0000000000..c031b76193
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorReindexSweep.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.LiveEvaluatorReindexImage
+import OAI.Computability.VPVNP.LiveEvaluatorReindexNative
+
+/-!
+# Native permutation of all dense exponent bits
+
+The incoming scratch stores one binary digit per word. The decoded order
+table names its formal row. Every native scatter reads exactly these two
+words, computes the reversed tagged payload position, and writes one tape
+symbol. Its last burst accepts, including the empty permutation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorReindex
+
+open BurstRAM BurstRAM.PrivateRAM RAMSerialization EvaluatorProgramRawInput
+open scoped Fin.CommRing
+
+variable {d t Z w : ℕ}
+
+/-- Length parameters and disjoint intervals used by the native scan. -/
+structure Layout (pub : Fin 5 → Word w) (d t Z stateBase M A : ℕ) : Prop where
+ width : (pub 3).val = Z
+ total : (pub 4).val = t*Z
+ target : (pub 2).val = stateBase + 1 + M + A + (2*Z+1) + 1
+ sourceFit : (pub 0).val + d*Z ≤ 2^w
+ mapFit : (pub 1).val + d ≤ 2^w
+ targetFit : (pub 2).val + 2*(t*Z) ≤ 2^w
+ sourceDisjoint : (pub 0).val + d*Z ≤ (pub 2).val ∨ (pub 2).val + 2*(t*Z) ≤ (pub 0).val
+ mapDisjoint : (pub 1).val + d ≤ (pub 2).val ∨ (pub 2).val + 2*(t*Z) ≤ (pub 1).val
+
+/-- Values of the incoming digit and order-advice buffers after the live
+header scan and advice unpacking stages. -/
+structure Sources (pub : Fin 5 → Word w) (perm : Fin d ≃ Fin t) (dense : Fin d → Word Z)
+ (m : Memory w) : Prop where
+ incoming : ∀ q : Fin (d*Z), m ((pub 0).val + q.val) = PrimedInputRAM.encodeBit w (arrayBits d Z dense q)
+ order : ∀ i : Fin d, (m ((pub 1).val + i.val)).val = (perm i).val
+
+private theorem bitOrder_val (perm : Fin d ≃ Fin t) (q : Fin (d*Z)) :
+ (bitOrder perm Z q).val = (perm q.divNat).val * Z + q.val % Z := by
+ change q.val % Z + Z * (perm q.divNat).val = _
+ ac_rfl
+
+private theorem address_eq {pub : Fin 5 → Word w} {base M A : ℕ} (L : Layout pub d t Z base M A)
+ (f : Fin (t*Z)) : symbolAddress base M A Z f = (pub 2).val + 2*(t*Z-1-f.val) := by
+ rw [L.target]
+ unfold symbolAddress rawSlot payload
+ omega
+
+private theorem image_step (hw : 2 ≤ w) (pub : Fin 5 → Word w) (perm : Fin d ≃ Fin t)
+ (dense : Fin d → Word Z) {base M A : ℕ} (L : Layout pub d t Z base M A)
+ {original m : Memory w} (src : Sources pub perm dense original) (q : Fin (d*Z))
+ (h : Image perm dense base M A q.val original m) :
+ Image perm dense base M A (q.val+1) original (after m (phaseEvents pub (q.val : Word w) m)) := by
+ have hq : (q.val : Word w).val = q.val := Fin.val_cast_of_lt (q.isLt.trans_le ((Nat.le_add_left ..).trans L.sourceFit))
+ have ha := incomingAddress_val pub (q.val : Word w) (by rw [hq]; have := q.isLt; have := L.sourceFit; omega)
+ rw [hq] at ha
+ have hj : q.val / Z < d := q.divNat.isLt
+ have hm := mapAddress_val pub (q.val : Word w) (by rw [hq, L.width]; have := L.mapFit; omega)
+ rw [hq, L.width] at hm
+ have hdata : m (incomingAddress pub (q.val : Word w)).val =
+ PrimedInputRAM.encodeBit w (arrayBits d Z dense q) := by
+ rw [ha, h.outside ((pub 0).val + q.val) (by
+ intro s _
+ rw [address_eq L]
+ have := L.sourceDisjoint
+ have := q.isLt
+ have := (bitOrder perm Z s).isLt
+ omega), src.incoming]
+ have hmap : (m (mapAddress pub (q.val : Word w)).val).val = (perm q.divNat).val := by
+ rw [hm, h.outside ((pub 1).val + q.val / Z) (by
+ intro s _
+ rw [address_eq L]
+ rcases L.mapDisjoint with lo | hi
+ · exact ne_of_lt ((Nat.add_lt_add_left hj _).trans_le (lo.trans (Nat.le_add_right ..)))
+ · have hs := (bitOrder perm Z s).isLt
+ have hback : 2*(t*Z-1-(bitOrder perm Z s).val) < 2*(t*Z) := by omega
+ exact ne_of_gt ((Nat.add_lt_add_left hback _).trans_le (hi.trans (Nat.le_add_right ..))))]
+ exact src.order q.divNat
+ have hf : (m (mapAddress pub (q.val : Word w)).val).val * (pub 3).val +
+ (q.val : Word w).val % (pub 3).val = (bitOrder perm Z q).val := by
+ rw [hq, hmap, L.width, bitOrder_val]
+ have hdest := targetAddress_val pub (q.val : Word w) m hw
+ (by rw [hf, L.total]; exact (bitOrder perm Z q).isLt)
+ (by rw [hf, L.total]; have := L.targetFit; have := (bitOrder perm Z q).isLt; omega)
+ rw [hf, L.total, ← address_eq L] at hdest
+ rw [after_phaseEvents, inputSymbol, hdata]
+ exact h.write q _ hdest
+
+/-- The real native phase accepts after exactly one call per input bit, or
+one no-op call if the dense vector is empty. Its final bank is the exact
+two-tape initial configuration expected by the formal-coordinate evaluator. -/
+theorem sweep_native (hw : 2 ≤ w) (pub : Fin 5 → Word w) (perm : Fin d ≃ Fin t)
+ (dense : Fin d → Word Z) (formal : Fin t → Word Z) (order : ∀ i, formal (perm i) = dense i)
+ (p : UniversalMachine.Program) (running : p.extra ≠ 0) (hs : p.extra+2 ≤ 2^w)
+ (A : List Bool) (base M : ℕ) (L : Layout pub d t Z base M A.length) (before : Memory w)
+ (src : Sources pub perm dense before) (space : (A ++ runtime formal).length ≤ M+1)
+ (prepared : LiveEvaluatorInitialize.Stores hw hs base before
+ (LiveEvaluatorTail.initialCode M (UniversalMachine.initial p (A ++ runtime (fun _ : Fin t => (0 : Word Z)))))) :
+ let P := (scatterPhase.instantiate w pub).program
+ ∃ rs, runSegment P 27 (some 0) before (List.replicate (max 1 (d*Z)) []) = some rs ∧
+ endState (some 0) rs = none ∧
+ LiveEvaluatorInitialize.Stores hw hs base (after before (eventLog rs))
+ (LiveEvaluatorTail.initialCode M (UniversalMachine.initial p (A ++ runtime formal))) ∧
+ rs.length = max 1 (d*Z) ∧ ∀ r ∈ rs, countProbes r.events ≤ 3 := by
+ have hdt : d = t := by simpa using Fintype.card_congr perm
+ obtain ⟨rs, hr, halt, image, len, probes⟩ := scatterPhase_segment pub (d*Z) (by rw [hdt, L.total])
+ (fun n => Image perm dense base M A.length n before) before (Image.zero ..)
+ (fun j hj _ h => image_step hw pub perm dense L src ⟨j, hj⟩ h)
+ exact ⟨rs, hr, halt, stores_formal p running hw hs perm dense formal order A base M space before _ prepared image,
+ len, probes⟩
+
+end LiveEvaluatorReindex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorSpace.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorSpace.lean
new file mode 100644
index 0000000000..dbbc8abb09
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorSpace.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.LiveEvaluatorStep
+import OAI.Computability.VPVNP.RAMTapeSpaceNamed
+
+/-!
+# Window radius for the compiled evaluator
+
+An absolute bound on both head positions bounds every tape write. The
+nonblank support of the initial input is retained as well. Translating
+these absolute positions to the current head yields a time-independent
+window bound at every cut, including prefixes of malformed choice strings.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorSpace
+
+open UniversalMachine LiveEvaluatorEncoding EvaluatorTail RAMTape RAMTape.StackCompiler
+
+/-- All nonblank symbols lie in a fixed physical interval centered at the
+initial head. `pos` is the position of the current head. -/
+def SupportedAt (S : ℕ) (pos : ℤ) (t : Turing.Tape Symbol) : Prop :=
+ ∀ j : ℤ, pos + j < -(S : ℤ) ∨ (S : ℤ) < pos + j → t.nth j = 0
+
+private theorem support_update {S : ℕ} {pos : ℤ} {t : Turing.Tape Symbol}
+ (ht : SupportedAt S pos t) (hp : -(S : ℤ) ≤ pos ∧ pos ≤ S) (write move : Symbol) :
+ SupportedAt S (pos + moveDelta move) (updateTape t write move) := by
+ intro j hj
+ rw [LiveEvaluatorStep.updateTape_nth, ite_eq_right (by omega)]
+ exact ht _ (by omega)
+
+private theorem support_step (p : Program) {c : Config p.extra} (b : Bool) {S : ℕ} {x y : ℤ}
+ (h : HeadBox S x y) (hx : SupportedAt S x c.firstTape) (hy : SupportedAt S y c.secondTape) :
+ let m := choiceMotion p c b
+ let c' := choiceStep p c b
+ SupportedAt S (x + m.1) c'.firstTape ∧ SupportedAt S (y + m.2) c'.secondTape := by
+ dsimp only
+ by_cases ha : c.state.val = 1
+ · have hr : ¬ 2 ≤ c.state.val := by omega
+ cases b <;> simpa [choiceStep, choiceMotion, ha, hr, reject] using And.intro hx hy
+ by_cases hz : c.state.val = 0
+ · simpa [choiceStep, choiceMotion, hz] using And.intro hx hy
+ have hr : 2 ≤ c.state.val := by omega
+ have go (a : Instruction p.extra) :
+ SupportedAt S (x + moveDelta a.firstMove) (advance c a).firstTape ∧
+ SupportedAt S (y + moveDelta a.secondMove) (advance c a).secondTape :=
+ ⟨support_update hx ⟨h.1, h.2.1⟩ _ _, support_update hy h.2.2 _ _⟩
+ simp only [choiceStep, choiceMotion, ha, hz, hr, ite_false, ite_true]
+ cases row : branches p c <;> cases b <;> simp [chosenInstruction, reject] <;> first
+ | exact ⟨hx, hy⟩
+ | exact go _
+
+private theorem fits_of_supported {R S : ℕ} {pos : ℤ} {t : Turing.Tape Symbol}
+ (h : SupportedAt S pos t) (hp : -(R : ℤ) ≤ pos ∧ pos ≤ R) : TapeFits (S + R) t := by
+ intro j hj
+ exact h _ (by push_cast at hj; omega)
+
+private theorem canonical_fits {p M : ℕ} (c : Config p) (h : ConfigFits M c) :
+ StateFits M (canonical c) := by
+ unfold canonical
+ split
+ · trivial
+ split
+ · trivial
+ exact ⟨by omega, h⟩
+
+private theorem history_fits_from (p : Program) {R S : ℕ} (hRS : R ≤ S)
+ (t : ℕ) (c : Config p.extra) (x y : ℤ) (hx : SupportedAt S x c.firstTape)
+ (hy : SupportedAt S y c.secondTape)
+ (hbox : ∀ bits, let d := choiceDisplacement p c bits; HeadBox R (x + d.1) (y + d.2))
+ (w : Fin t → Bool) (i : Fin (t + 1)) : StateFits (S + R) (history p t c w i) := by
+ induction t generalizing c x y
+ all_goals
+ have h : HeadBox R x y := by simpa [choiceDisplacement] using hbox []
+ have hS : HeadBox S x y := by
+ unfold HeadBox at *
+ omega
+ have hc : StateFits (S + R) (canonical c) := canonical_fits _
+ ⟨fits_of_supported hx ⟨h.1, h.2.1⟩, fits_of_supported hy h.2.2⟩
+ case zero => exact hc
+ case succ t ih =>
+ refine Fin.cases hc (fun j => ?_) i
+ have hs := support_step p (w 0) hS hx hy
+ apply ih _ _ _ hs.1 hs.2
+ intro bits
+ simpa [choiceDisplacement, add_assoc] using hbox (w 0 :: bits)
+
+private theorem initial_support (s : List Symbol) (S : ℕ) (hs : s.length ≤ S) :
+ SupportedAt S 0 (Turing.Tape.mk₁ s) := by
+ intro j hj
+ cases j with
+ | ofNat n =>
+ change (0 : ℤ) + (n : ℤ) < -(S : ℤ) ∨ (S : ℤ) < 0 + (n : ℤ) at hj
+ change (Turing.Tape.mk' _ _).nth (n : ℤ) = _
+ rw [Turing.Tape.mk'_nth_nat, Turing.ListBlank.nth_mk, List.getI_eq_default _ (by omega)]
+ rfl
+ | negSucc n =>
+ change (Turing.ListBlank.mk ([] : List Symbol)).nth n = 0
+ rw [Turing.ListBlank.nth_mk, List.getI_eq_default _ (by simp)]
+ rfl
+
+/-- Any evaluator whose heads remain within radius `R` has canonical bounded
+cut configurations on every branch, for every clock. -/
+theorem history_fits (p : Program) (raw : Word) (R : ℕ)
+ (bounded : ∀ bits, let d := choiceDisplacement p (initial p raw) bits; HeadBox R d.1 d.2)
+ (t : ℕ) (w : Fin t → Bool) (i : Fin (t + 1)) :
+ StateFits (raw.length + R + R) (history p t (initial p raw) w i) := by
+ apply history_fits_from p (Nat.le_add_left ..) t _ 0 0
+ · apply initial_support
+ simp
+ · apply initial_support
+ simp
+ · intro bits
+ simpa using bounded bits
+
+/-- On the literal machine compiled from a finite stack evaluator, a bound on
+the total stack storage supplies the cut window independently of its time. -/
+theorem history_fits_labeled {K Q : Type*} [DecidableEq K] [Fintype K] [Fintype Q]
+ (input : K) (code : StackCode K Q) (start : Q) (raw : Word) {B : ℕ}
+ (bounded : ∀ ⦃q s⦄, Reach code start (labeledInput input raw) q s →
+ Fintype.card K + 1 + ∑ a, (s a).length ≤ B)
+ (t : ℕ) (w : Fin t → Bool) (i : Fin (t + 1)) :
+ let p := labeledProgram input code start
+ StateFits (raw.length + (7 * B + 4) + (7 * B + 4)) (history p t (initial p raw) w i) :=
+ history_fits _ _ _ (input_space_labeled input code start raw bounded) t w i
+
+end LiveEvaluatorSpace
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorStep.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorStep.lean
new file mode 100644
index 0000000000..7e80ce657a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorStep.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.LiveEvaluatorEncoding
+import Mathlib.Tactic.FinCases
+import OAI.Computability.VPVNP.VerifierMachineSimulation
+import OAI.Computability.VPVNP.RAMTapeSpaceTravel
+
+/-!
+# One finite-window evaluator transition in a live group
+
+Each output cell reads a single offset from the previous window. Two
+additional blank checks, immediately outside the new window, detect any
+loss of nonblank tape data. Halts carry the unique canonical state code.
+One choice bit selects a table slot, so equal instructions in a branching
+row remain distinguishable.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorStep
+
+open UniversalMachine LiveEvaluatorEncoding RAMTape
+
+variable {M extra : ℕ}
+
+theorem updateTape_nth (t : Turing.Tape Symbol) (write move : Symbol) (j : ℤ) :
+ (updateTape t write move).nth j =
+ if j + moveDelta move = 0 then write else t.nth (j + moveDelta move) := by
+ fin_cases move <;> simp [updateTape, sub_eq_add_neg] <;> rfl
+
+/-- Symbol at signed displacement `j` after writing at the old head and moving. -/
+def updatedCell (t : TapeWindow M) (write move : Symbol) (j : ℤ) : Symbol :=
+ let old := j + moveDelta move
+ if old = 0 then write else t.read old
+
+theorem updatedCell_eq_nth (t : TapeWindow M) (write move : Symbol) (j : ℤ) :
+ updatedCell t write move j = (updateTape t.toTape write move).nth j := by
+ rw [updateTape_nth, t.toTape_nth]
+ rfl
+
+/-- The only two exterior positions which can receive a nonblank cell. -/
+def boundaryBlank (t : TapeWindow M) (write move : Symbol) : Bool :=
+ decide (updatedCell t write move (-(M : ℤ) - 1) = 0 ∧ updatedCell t write move (M + 1) = 0)
+
+theorem boundaryBlank_iff (t : TapeWindow M) (write move : Symbol) :
+ boundaryBlank t write move = true ↔ TapeFits M (updateTape t.toTape write move) := by
+ simp only [boundaryBlank, decide_eq_true_eq, updatedCell_eq_nth]
+ constructor
+ · intro h j hj
+ by_cases hl : j = -(M : ℤ) - 1
+ · exact hl ▸ h.1
+ by_cases hr : j = (M : ℤ) + 1
+ · exact hr ▸ h.2
+ have hd := delta_range move
+ have hfar : j + moveDelta move < -(M : ℤ) ∨ (M : ℤ) < j + moveDelta move := by omega
+ rw [updateTape_nth, ite_eq_right (by omega)]
+ exact t.toTape_fits _ hfar
+ · intro h
+ exact ⟨h _ (by omega), h _ (by omega)⟩
+
+/-- The finite head-relative tape window resulting from the proposed head write and movement. -/
+def updatedWindow (t : TapeWindow M) (write move : Symbol) : TapeWindow M :=
+ ⟨fun i => updatedCell t write move ((i.val : ℤ) - M)⟩
+
+theorem updatedWindow_eq (t : TapeWindow M) (write move : Symbol) :
+ updatedWindow t write move = TapeWindow.ofTape M (updateTape t.toTape write move) := by
+ apply TapeWindow.ext
+ funext i
+ exact updatedCell_eq_nth t write move _
+
+/-- Check a selected instruction. The two boundary reads are necessary only
+when its target is running, since the representation discards both tapes on a halt. -/
+def advanceCode (s : ConfigWindow extra M) (a : Instruction extra) : Option (Code extra M) :=
+ if ha : a.target.val = 1 then some .accepted
+ else if hr : a.target.val = 0 then some .rejected
+ else if boundaryBlank s.firstTape a.firstSymbol a.firstMove &&
+ boundaryBlank s.secondTape a.secondSymbol a.secondMove then
+ some (.running ⟨a.target, updatedWindow s.firstTape a.firstSymbol a.firstMove,
+ updatedWindow s.secondTape a.secondSymbol a.secondMove⟩ (by change 2 ≤ a.target.val; omega))
+ else none
+
+/-- Read the fixed row table at the state and the two current symbols. -/
+def row (p : Program) (s : ConfigWindow p.extra M) : Branches p.extra :=
+ p.rows[(s.state.val - 2) * 9 + (s.firstTape.cells (windowCenter M)).val * 3 +
+ (s.secondTape.cells (windowCenter M)).val]?.getD .stop
+
+theorem row_eq (p : Program) (s : ConfigWindow p.extra M) : row p s = branches p s.toConfig := rfl
+
+/-- Advance a cut code using one row-selection bit, handling carried halts, missing slots, and
+the finite-window transition check. -/
+def nextCode (p : Program) (s : Code p.extra M) (bit : Bool) : Option (Code p.extra M) :=
+ match s with
+ | .accepted => some (if bit then .rejected else .accepted)
+ | .rejected => some .rejected
+ | .running c _ =>
+ match chosenInstruction (row p c) bit with
+ | none => some .rejected
+ | some a => advanceCode c a
+
+private theorem toState_injective : Function.Injective (Code.toState (extra := extra) (M := M)) :=
+ fun _ _ h => (codeEquiv extra M).injective (Subtype.ext h)
+
+private theorem code_eq_state (s z : Code extra M) : s = z ↔ z.toState = s.toState :=
+ ⟨fun h => h ▸ rfl, fun h => (toState_injective h).symm⟩
+
+/-- A transition emits precisely the bounded representation of the true
+successor. If it clips a tape, no outgoing code passes the transition test. -/
+theorem advanceCode_iff (s : ConfigWindow extra M) (a : Instruction extra) (z : Code extra M) :
+ advanceCode s a = some z ↔ z.toState = EvaluatorTail.canonical (advance s.toConfig a) := by
+ by_cases ha : a.target.val = 1
+ · simpa [advanceCode, ha, EvaluatorTail.canonical, advance, Code.toState] using code_eq_state Code.accepted z
+ by_cases hr : a.target.val = 0
+ · simpa [advanceCode, hr, EvaluatorTail.canonical, advance, Code.toState] using code_eq_state Code.rejected z
+ let c := advance s.toConfig a
+ have hcanon : EvaluatorTail.canonical c = .running c := by simp [c, EvaluatorTail.canonical, advance, ha, hr]
+ rw [show advance s.toConfig a = c from rfl, hcanon]
+ by_cases hf : ConfigFits M c
+ · have h₁ := hf.1
+ have h₂ := hf.2
+ have hb₁ := (boundaryBlank_iff s.firstTape a.firstSymbol a.firstMove).mpr h₁
+ have hb₂ := (boundaryBlank_iff s.secondTape a.secondSymbol a.secondMove).mpr h₂
+ simp [advanceCode, ha, hr, hb₁, hb₂, updatedWindow_eq]
+ let v : Code extra M := .running (ConfigWindow.ofConfig M c) (by change 2 ≤ a.target.val; omega)
+ change v = z ↔ _
+ have hv : v.toState = EvaluatorTail.State.running c := by
+ change EvaluatorTail.State.running ((ConfigWindow.ofConfig M c).toConfig) = _
+ rw [ConfigWindow.toConfig_ofConfig _ hf]
+ exact ⟨fun h => h ▸ hv, fun h => toState_injective (hv.trans h.symm)⟩
+ · have hb : ¬ (boundaryBlank s.firstTape a.firstSymbol a.firstMove &&
+ boundaryBlank s.secondTape a.secondSymbol a.secondMove) = true := by
+ intro h
+ rw [Bool.and_eq_true] at h
+ exact hf ⟨(boundaryBlank_iff ..).mp h.1, (boundaryBlank_iff ..).mp h.2⟩
+ simp [advanceCode, ha, hr, hb]
+ intro hz
+ have h := z.toState_fits
+ rw [hz] at h
+ exact hf h.2
+
+theorem nextCode_iff (p : Program) (s z : Code p.extra M) (bit : Bool) :
+ nextCode p s bit = some z ↔ z.toState = EvaluatorTail.step p s.toState bit := by
+ cases s with
+ | accepted =>
+ cases bit
+ · exact (Option.some.injEq ..).to_iff.trans (code_eq_state Code.accepted z)
+ · exact (Option.some.injEq ..).to_iff.trans (code_eq_state Code.rejected z)
+ | rejected => exact (Option.some.injEq ..).to_iff.trans (code_eq_state Code.rejected z)
+ | running c hc =>
+ have ha : c.toConfig.state.val ≠ 1 := by change c.state.val ≠ 1; omega
+ have hr : c.toConfig.state.val ≠ 0 := by change c.state.val ≠ 0; omega
+ simp only [nextCode, row_eq, Code.toState, EvaluatorTail.step, choiceStep, ha, hr, ite_false]
+ cases hb : branches p c.toConfig <;> cases bit <;>
+ first | exact advanceCode_iff .. |
+ simpa [chosenInstruction, EvaluatorTail.canonical, reject, Code.toState] using code_eq_state Code.rejected z
+
+end LiveEvaluatorStep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorTail.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorTail.lean
new file mode 100644
index 0000000000..f2893c5545
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorTail.lean
@@ -0,0 +1,284 @@
+import OAI.Computability.VPVNP.LiveEvaluatorSpace
+import OAI.Computability.VPVNP.LiveModes
+
+/-!
+# Counting actual configuration strings on the live tail
+
+For each of the `2^h` tail groups the input is either the initialized machine or
+a decoded incoming cut. The output is either a decoded outgoing cut or the
+mandatory accepting halt at the endpoint. Each interior cut checks the live
+mode, the fixed-width word encoding of both tapes and the control, and zero
+padding. The resulting count is the machine's accepting path count whenever
+its accepting histories fit in the chosen tape window.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorTail
+
+open UniversalMachine EvaluatorTail LiveEvaluatorEncoding CutSchedule
+
+variable {h Δ M w : ℕ}
+
+/-- The fixed fields and bit-capacity proofs shared by all groups of the tail. -/
+structure Layout (extra M w Δ : ℕ) : Prop where
+ symbolWidth : 2 ≤ w
+ stateWidth : extra + 2 ≤ 2 ^ w
+ cutWidth : 1 + fieldWords M * w ≤ Δ
+
+variable {p : Program} (layout : Layout p.extra M w Δ)
+
+private def fields (j : Fin (2 ^ h - 1)) :=
+ tailLayout h Δ (2 ^ h + (j.val + 1)) (fieldWords M * w) (by omega)
+ (by rw [pow_succ]; have := j.isLt; omega) layout.cutWidth
+
+/-- The bits emitted at the cut after tail group `j + 1`. -/
+def writeCut (j : Fin (2 ^ h - 1)) (s : Code p.extra M) :
+ Bits (width (h + 1) Δ (2 ^ h + (j.val + 1))) :=
+ (fields layout j).symm (true, (format layout.symbolWidth layout.stateWidth).encode s, fun _ => false)
+
+/-- Parse all three fields, rejecting malformed words, mode, or padding. -/
+def readCut (j : Fin (2 ^ h - 1)) (b : Bits (width (h + 1) Δ (2 ^ h + (j.val + 1)))) :
+ Option (Code p.extra M) :=
+ let f := fields layout j b
+ if f.1 = true ∧ f.2.2 = fun _ => false then (format layout.symbolWidth layout.stateWidth).decode f.2.1
+ else none
+
+theorem readCut_iff (j : Fin (2 ^ h - 1)) (b : Bits (width (h + 1) Δ (2 ^ h + (j.val + 1))))
+ (s : Code p.extra M) : readCut layout j b = some s ↔ b = writeCut layout j s := by
+ constructor
+ · unfold readCut
+ dsimp only
+ split
+ · rename_i hv
+ intro hd
+ apply (fields layout j).injective
+ rw [writeCut, Equiv.apply_symm_apply]
+ exact Prod.ext hv.1 (Prod.ext ((decode_iff ..).mp hd) hv.2)
+ · simp
+ · rintro rfl
+ simp [readCut, writeCut, decode_iff]
+
+private def timeAfter (j : Fin (2 ^ h - 1)) : Fin (2 ^ h + 1) :=
+ ⟨j.val + 1, by have := j.isLt; omega⟩
+
+/-- The first tail group receives its initialized state from the middle
+exponents. The last group compares its successor to the accepting halt. -/
+def boundary (initialCode : Code p.extra M) (bits : LiveChain.TailBits h Δ)
+ (i : Fin (2 ^ h + 1)) : Option (Code p.extra M) :=
+ if h₀ : i.val = 0 then some initialCode else if hT : i.val = 2 ^ h then some .accepted
+ else readCut layout ⟨i.val - 1, by omega⟩ (bits ⟨i.val - 1, by omega⟩)
+
+@[simp] theorem boundary_zero (init : Code p.extra M) (bits : LiveChain.TailBits h Δ) :
+ boundary layout init bits 0 = some init := by simp [boundary]
+
+@[simp] theorem boundary_last (init : Code p.extra M) (bits : LiveChain.TailBits h Δ) :
+ boundary layout init bits (Fin.last (2 ^ h)) = some .accepted := by simp [boundary]
+
+private theorem boundary_after (init : Code p.extra M) (bits : LiveChain.TailBits h Δ)
+ (j : Fin (2 ^ h - 1)) :
+ boundary layout init bits (timeAfter j) = readCut layout j (bits j) := by
+ simp [boundary, timeAfter, show j.val + 1 ≠ 2 ^ h by have := j.isLt; omega]
+
+/-- Each physical group checks its two endpoints and one literal branch
+choice. A rejecting halt fails the group that reaches it. -/
+def Valid (init : Code p.extra M) (choice : Fin (2 ^ h) → Bool) (bits : LiveChain.TailBits h Δ) : Prop :=
+ ∀ i, ∃ a b, boundary layout init bits i.castSucc = some a ∧
+ boundary layout init bits i.succ = some b ∧ LiveEvaluatorStep.nextCode p a (choice i) = some b ∧
+ b ≠ .rejected
+
+private theorem successful_not_rejected (T : ℕ) (c : Config p.extra) (choice : Fin T → Bool)
+ (ha : acceptsChoices p T c choice) (i : Fin (T + 1)) : history p T c choice i ≠ .rejected := by
+ induction i using Fin.reverseInduction with
+ | last => rw [(history_last ..).mpr ha]; simp
+ | cast i ih =>
+ intro hr
+ apply ih
+ rw [history_step, hr]
+ rfl
+
+/-- The accepted runs lie in the supplied tape-space bound at every group. -/
+def HistoriesFit (p : Program) (M T : ℕ) (c : Config p.extra) : Prop :=
+ ∀ choice, acceptsChoices p T c choice → ∀ i, StateFits M (history p T c choice i)
+
+variable (c : Config p.extra) (init : Code p.extra M) (hi : init.toState = canonical c)
+ (space : HistoriesFit p M (2 ^ h) c)
+
+private def expectedCode (choice : Fin (2 ^ h) → Bool) (ha : acceptsChoices p (2 ^ h) c choice)
+ (i : Fin (2 ^ h + 1)) : Code p.extra M :=
+ Code.ofState (history p (2 ^ h) c choice i) (space choice ha i)
+
+private theorem toState_expected (choice : Fin (2 ^ h) → Bool) (ha : acceptsChoices p (2 ^ h) c choice)
+ (i : Fin (2 ^ h + 1)) :
+ (expectedCode c space choice ha i).toState = history p (2 ^ h) c choice i :=
+ congrArg Subtype.val ((codeEquiv p.extra M).apply_symm_apply
+ ⟨history p (2 ^ h) c choice i, space choice ha i⟩)
+
+private theorem toState_injective : Function.Injective (Code.toState (extra := p.extra) (M := M)) :=
+ fun _ _ he => (codeEquiv p.extra M).injective (Subtype.ext he)
+
+private def expectedBits (choice : Fin (2 ^ h) → Bool) (ha : acceptsChoices p (2 ^ h) c choice) :
+ LiveChain.TailBits h Δ :=
+ fun j => writeCut layout j (expectedCode c space choice ha (timeAfter j))
+
+include hi in
+private theorem boundary_expected (choice : Fin (2 ^ h) → Bool) (ha : acceptsChoices p (2 ^ h) c choice)
+ (i : Fin (2 ^ h + 1)) :
+ boundary layout init (expectedBits layout c space choice ha) i = some (expectedCode c space choice ha i) := by
+ by_cases h₀ : i.val = 0
+ · have he : i = 0 := Fin.ext h₀
+ subst i
+ rw [boundary_zero]
+ exact congrArg some (toState_injective (by rw [hi, toState_expected, history_zero]))
+ by_cases hT : i.val = 2 ^ h
+ · have he : i = Fin.last (2 ^ h) := Fin.ext hT
+ subst i
+ rw [boundary_last]
+ exact congrArg some (toState_injective (by rw [toState_expected, (history_last ..).mpr ha]; rfl))
+ let j : Fin (2 ^ h - 1) := ⟨i.val - 1, by omega⟩
+ have he : i = timeAfter j := Fin.ext (by dsimp [timeAfter, j]; omega)
+ rw [he, boundary_after, readCut_iff]
+ rfl
+
+include hi in
+private theorem valid_expected (choice : Fin (2 ^ h) → Bool) (ha : acceptsChoices p (2 ^ h) c choice) :
+ Valid layout init choice (expectedBits layout c space choice ha) := by
+ intro i
+ refine ⟨_, _, boundary_expected layout c init hi space choice ha i.castSucc,
+ boundary_expected layout c init hi space choice ha i.succ, ?_, ?_⟩
+ · rw [LiveEvaluatorStep.nextCode_iff, toState_expected, toState_expected, history_step]
+ · intro hr
+ apply successful_not_rejected _ c choice ha i.succ
+ rw [← toState_expected c space choice ha i.succ, hr]
+ rfl
+
+include hi in
+private theorem boundary_history (choice : Fin (2 ^ h) → Bool) (bits : LiveChain.TailBits h Δ)
+ (valid : Valid layout init choice bits) (i : Fin (2 ^ h + 1)) :
+ ∃ s, boundary layout init bits i = some s ∧ s.toState = history p (2 ^ h) c choice i := by
+ induction i using Fin.induction with
+ | zero => exact ⟨init, boundary_zero .., hi.trans (history_zero ..).symm⟩
+ | succ j ih =>
+ obtain ⟨a, ha, hstate⟩ := ih
+ obtain ⟨a', b, ha', hb, hn, _⟩ := valid j
+ have he := Option.some.inj (ha.symm.trans ha')
+ subst a'
+ exact ⟨b, hb, ((LiveEvaluatorStep.nextCode_iff ..).mp hn).trans
+ (by rw [hstate, history_step])⟩
+
+include hi in
+private theorem accepts_of_valid (choice : Fin (2 ^ h) → Bool) (bits : LiveChain.TailBits h Δ)
+ (hv : Valid layout init choice bits) : acceptsChoices p (2 ^ h) c choice := by
+ obtain ⟨s, hs, he⟩ := boundary_history layout c init hi choice bits hv (Fin.last (2 ^ h))
+ rw [boundary_last, Option.some.injEq] at hs
+ subst s
+ exact (history_last ..).mp he.symm
+
+/-- The only data counted are branch bits and the actual interior cut bits.
+No configuration string is placed at either endpoint. -/
+abbrev Runs (init : Code p.extra M) := (choice : Fin (2 ^ h) → Bool) ×
+ {bits : LiveChain.TailBits h Δ // Valid layout init choice bits}
+
+/-- On an accepting computation all cut fields are forced. Reading just the
+bits at adjacent cuts conversely recovers a unique accepting computation. -/
+def runsEquiv :
+ {choice : Fin (2 ^ h) → Bool // acceptsChoices p (2 ^ h) c choice} ≃
+ Runs (h := h) layout init where
+ toFun choice := ⟨choice.val, expectedBits layout c space choice.val choice.property,
+ valid_expected layout c init hi space choice.val choice.property⟩
+ invFun run := ⟨run.1, accepts_of_valid layout c init hi run.1 run.2.val run.2.property⟩
+ left_inv _ := rfl
+ right_inv run := by
+ rcases run with ⟨choice, bits, hv⟩
+ refine Sigma.ext ?_ ?_
+ · rfl
+ apply heq_of_eq
+ apply Subtype.ext
+ funext j
+ obtain ⟨s, hs, he⟩ := boundary_history layout c init hi choice bits hv (timeAfter j)
+ rw [boundary_after, readCut_iff] at hs
+ change writeCut layout j (expectedCode c space choice _ (timeAfter j)) = bits j
+ rw [hs]
+ exact congrArg (writeCut layout j) (toState_injective ((toState_expected ..).trans he.symm))
+
+include hi space in
+/-- The tail contributes exactly the clocked accepting path count, including
+initial acceptance, early acceptance and coincident branching successors. -/
+theorem card_runs : Nat.card (Runs (h := h) layout init) = paths p (2 ^ h) c := by
+ rw [← Nat.card_congr (runsEquiv layout c init hi space), Nat.card_eq_fintype_card,
+ Fintype.card_subtype, paths_eq_card_choices]
+
+/-- Initialize the bounded fields from the tape machine at the middle cut. -/
+def initialCode (M : ℕ) (c : Config p.extra) : Code p.extra M :=
+ if ha : c.state.val = 1 then .accepted else if hz : c.state.val = 0 then .rejected else
+ .running (ConfigWindow.ofConfig M c) (by change 2 ≤ c.state.val; omega)
+
+theorem initialCode_toState (c : Config p.extra) (hf : StateFits M (canonical c)) :
+ (initialCode M c).toState = canonical c := by
+ by_cases ha : c.state.val = 1
+ · simp [initialCode, canonical, ha, Code.toState]
+ by_cases hz : c.state.val = 0
+ · simp [initialCode, canonical, hz, Code.toState]
+ simp only [canonical, ha, hz, ite_false] at hf
+ simp [initialCode, canonical, ha, hz, Code.toState, hf.2]
+
+open RAMTape RAMTape.StackCompiler
+
+/-- For a bounded-head tape program all running states reached on a choice
+string fit into a common window. This specializes the bit-string count with
+no remaining hypothesis about the validity of individual configurations. -/
+theorem card_of_head_bound (p : Program) (raw : UniversalMachine.Word) (R : ℕ)
+ (bounded : ∀ bits, let d := choiceDisplacement p (initial p raw) bits; HeadBox R d.1 d.2)
+ (layout : Layout p.extra (raw.length + R + R) w Δ) :
+ Nat.card (Runs (h := h) layout (initialCode _ (initial p raw))) =
+ paths p (2 ^ h) (initial p raw) := by
+ apply card_runs
+ · apply initialCode_toState
+ exact LiveEvaluatorSpace.history_fits p raw R bounded 0 (fun i => i.elim0) 0
+ · exact fun choice _ i => LiveEvaluatorSpace.history_fits p raw R bounded (2 ^ h) choice i
+
+/-- Specialization to the literal two-tape machine emitted by the finite
+stack compiler. The storage bound is required only on reachable stack states. -/
+theorem card_labeled {K Q : Type*} [DecidableEq K] [Fintype K] [Fintype Q]
+ (input : K) (code : StackCode K Q) (start : Q) (raw : UniversalMachine.Word) {B : ℕ}
+ (bounded : ∀ ⦃q s⦄, Reach code start (labeledInput input raw) q s →
+ Fintype.card K + 1 + ∑ a, (s a).length ≤ B)
+ (layout : Layout (labeledProgram input code start).extra (raw.length + (7 * B + 4) + (7 * B + 4)) w Δ) :
+ let E := labeledProgram input code start
+ Nat.card (Runs (h := h) layout (initialCode _ (initial E raw))) = paths E (2 ^ h) (initial E raw) :=
+ card_of_head_bound _ _ _ (input_space_labeled input code start raw bounded) layout
+
+open ExponentTrace
+
+/-- Recover the evaluator input from the counter words on the physical middle
+cut, with the input format, advice and length parameter supplied by `assemble`. -/
+def middleInput {t Z : ℕ} (hfit : 1 + t * Z ≤ Δ) (assemble : (Fin t → ℕ) → UniversalMachine.Word)
+ (live : LiveBits h Δ) : UniversalMachine.Word :=
+ assemble (fun a => (counters hfit live (Fin.last (2 ^ h)) a).val)
+
+theorem middleInput_eq {t Z : ℕ} (hfit : 1 + t * Z ≤ Δ) (assemble : (Fin t → ℕ) → UniversalMachine.Word)
+ (ξ : Exterior h Δ) (inc : Fin (2 ^ h) → Fin t → ℕ) (live : LiveBits h Δ)
+ (valid : ExponentTrace.Valid hfit ξ inc live) :
+ middleInput hfit assemble live = assemble (fun a => ∑ i, inc i a) :=
+ congrArg assemble (funext (middle_counters hfit ξ inc live valid))
+
+/-- The middle cut supplies the actual initial input to the first tail
+transition. The count for the entire tail is the evaluator's accepting count
+on the sum of the nominated production and gadget exponents. -/
+theorem card_middle {t Z : ℕ} (hfit : 1 + t * Z ≤ Δ) (assemble : (Fin t → ℕ) → UniversalMachine.Word)
+ (ξ : Exterior h Δ) (inc : Fin (2 ^ h) → Fin t → ℕ) (live : LiveBits h Δ)
+ (valid : ExponentTrace.Valid hfit ξ inc live) (p : Program) (R : ℕ)
+ (bounded : ∀ bits, let d := choiceDisplacement p (initial p (middleInput hfit assemble live)) bits
+ HeadBox R d.1 d.2)
+ (layout : Layout p.extra ((middleInput hfit assemble live).length + R + R) w Δ) :
+ Nat.card (Runs (h := h) layout (initialCode _ (initial p (middleInput hfit assemble live)))) =
+ paths p (2 ^ h) (initial p (assemble (fun a => ∑ i, inc i a))) := by
+ rw [card_of_head_bound p _ R bounded, middleInput_eq hfit assemble ξ inc live valid]
+
+end LiveEvaluatorTail
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorTailCost.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorTailCost.lean
new file mode 100644
index 0000000000..0cc0898a22
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorTailCost.lean
@@ -0,0 +1,174 @@
+import OAI.Computability.VPVNP.LiveProgram
+import OAI.Computability.VPVNP.LiveEvaluatorRAMSegmentCost
+import OAI.Computability.VPVNP.LiveStageLinkPaths
+
+/-!
+# Cost of the evaluator stages in the linked live program
+
+Starting at the first-tail router, the native trace initializes the evaluator
+or gathers its incoming configuration, then prepares or gathers its outgoing
+configuration and runs one transition. The bounds include framed operand
+loads, the dispatcher tag read, and the transfer write. Header preparation
+and the earlier live-mode router are outside this interval.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorTailCost
+
+open LiveProgram BurstRAM
+
+variable {w : ℕ}
+
+/-- Raw prefix bit length, row width and row count are taken before choosing
+the transcript capacity. The order-advice row has `clog 2 t` bits. -/
+structure Parameters where
+ /-- The advice prefix size used to bound the number of native packing calls. -/
+ advice : ℕ
+ /-- The number of exponent rows whose label ordinals and digits are prepared for the
+ evaluator. -/
+ rows : ℕ
+ /-- The number of binary exponent digits per row. -/
+ rowWidth : ℕ
+ /-- The radius on either side of the head in each finite evaluator tape window. -/
+ radius : ℕ
+ /-- The number of bits packed into a native advice word. -/
+ wordWidth : ℕ
+
+/-- Total number of exponent digits across all label rows. -/
+def Parameters.exponentBits (u : Parameters) := u.rows*u.rowWidth
+/-- Length of the serialized runtime skeleton, including exponent payloads, width fields, and
+delimiters. -/
+def Parameters.runtimeBits (u : Parameters) := 2*u.exponentBits+6*u.rowWidth+4
+/-- Number of words needed for the control state and both full radius-bounded tape windows. -/
+def Parameters.configWords (u : Parameters) := 4*u.radius+3
+/-- The linked cost allowance for one instruction-preparation call and the two windows'
+cell-check calls. -/
+def Parameters.transitionCost (u : Parameters) := 10+14*(2*u.radius+1)
+
+/-- Number of cursors used to pack the length word, including its initial clear. -/
+def Parameters.lengthPackCalls (u : Parameters) := u.wordWidth+1
+/-- A call bound for packing the advice prefix into rounded-up word rows, including the
+empty-prefix case. -/
+def Parameters.prefixPackCalls (u : Parameters) :=
+ max 1 (((u.advice+u.wordWidth-1)/u.wordWidth)*(u.wordWidth+1))
+/-- A call bound for packing one binary ordinal per label, including each row's initial clear
+and the empty-table case. -/
+def Parameters.orderPackCalls (u : Parameters) := max 1 (u.rows*(Nat.clog 2 u.rows+1))
+
+/-- The component stages that run between mode dispatch and termination. -/
+def tailStages (first last empty : Bool) : List Stage :=
+ [Stage.firstTail] ++
+ (if first then [Stage.initialState] ++
+ (if empty then [] else [Stage.prefixLength, Stage.adviceFrames, Stage.prefixPack, Stage.orderPack,
+ Stage.prefixCopy, Stage.skeleton, Stage.scatter])
+ else [Stage.oldGather]) ++ [Stage.last] ++
+ (if last then [Stage.finalState] else [Stage.newGather]) ++ [Stage.transition]
+
+/-- The linked cost of all the tail stages following mode dispatch. -/
+def groupBound (u : Parameters) (first last empty : Bool) : ℕ :=
+ let pack := 6*u.lengthPackCalls + 23 + 11*u.prefixPackCalls + 6*u.orderPackCalls
+ let init := 4 + pack + 10*(max 1 u.advice) + 8*u.runtimeBits + 11*(max 1 u.exponentBits)
+ let gather := (u.wordWidth+4)*u.configWords
+ 8 + u.transitionCost + 2*u.configWords +
+ (if first then (if empty then 4 else init) else gather) + (if last then 4 else gather)
+
+/-- The first component is the number of calls. The second is the cost
+including probes but before operand loading and stage dispatch. -/
+def rawBudget (u : Parameters) (s : Stage) : ℕ × ℕ :=
+ match s.val with
+ | 7 | 17 => (1, 3)
+ | 8 | 18 => (1, 2)
+ | 9 => (u.lengthPackCalls, 4*u.lengthPackCalls)
+ | 10 => (1, 21)
+ | 11 => (u.prefixPackCalls, 4*u.prefixPackCalls)
+ | 12 => (u.orderPackCalls, 4*u.orderPackCalls)
+ | 13 => (max 1 u.advice, 3*max 1 u.advice)
+ | 14 => (u.runtimeBits, 2*u.runtimeBits)
+ | 15 => (max 1 u.exponentBits, 4*max 1 u.exponentBits)
+ | 16 | 19 => (u.configWords, (u.wordWidth+2)*u.configWords)
+ | 20 => (u.configWords, u.transitionCost)
+ | _ => (0, 0)
+
+/-- Exactly the prefix pack, prefix copy, skeleton and scatter use operand
+frames among these stages, with the arities of the tables in `LiveProgram.rows`. -/
+def frameReads (s : Stage) : ℕ :=
+ match s.val with
+ | 11 | 13 | 15 => 5
+ | 14 => 4
+ | _ => 0
+
+private def dispatchProbes (s : Stage) : ℕ := if s = Stage.firstTail ∨ s = Stage.last then 1 else 2
+
+/-- Apply the two native report transformations at a stage boundary.
+Each report retains the memory at its call entry for the frame read values. -/
+def linked (p : UniversalMachine.Program) (tag frame : Word w) (s : Stage) (x : Memory w × Report w) : Report w :=
+ LiveStageLink.linkedReport (next p) tag s (LiveStageLink.prependLog
+ (CompressorRecords.Frame.loadEvents frame x.1 0 (frameReads s)) x.2)
+
+private theorem linked_probes_le (p : UniversalMachine.Program) (tag frame : Word w) (s : Stage)
+ (x : Memory w × Report w) :
+ (linked p tag frame s x).probes ≤ x.2.probes + frameReads s + dispatchProbes s := by
+ rw [linked, LiveStageLink.linkedReport_probes, (CompressorRecords.Frame.frame_cost ..).2.1]
+ unfold dispatchProbes
+ by_cases hr : s = Stage.firstTail ∨ s = Stage.last
+ · rcases hr with rfl | rfl <;> simp [next, Stage.firstTail, Stage.last] <;> omega
+ · rw [ite_eq_right hr]
+ split <;> omega
+
+theorem linked_stage_cost (p : UniversalMachine.Program) (tag frame : Word w) (s : Stage)
+ (calls : List (Memory w × Report w)) :
+ RAMBuckets.cost Report.probes (calls.map (linked p tag frame s)) ≤
+ RAMBuckets.cost Report.probes (calls.map Prod.snd) + (frameReads s+dispatchProbes s)*calls.length := by
+ induction calls with
+ | nil => simp [RAMBuckets.cost]
+ | cons x xs ih =>
+ simp only [List.map_cons, List.length_cons, RAMBuckets.cost, Nat.mul_succ]
+ have := linked_probes_le p tag frame s x
+ omega
+
+/-- Per-stage facts furnished by the component execution theorems. -/
+def Bounded (u : Parameters) (s : Stage) (calls : List (Memory w × Report w)) : Prop :=
+ calls.length ≤ (rawBudget u s).1 ∧ RAMBuckets.cost Report.probes (calls.map Prod.snd) ≤ (rawBudget u s).2
+
+private def stageBudget (u : Parameters) (s : Stage) :=
+ (rawBudget u s).2 + (frameReads s + dispatchProbes s)*(rawBudget u s).1
+
+private theorem cost_list (p : UniversalMachine.Program) (u : Parameters) (tag : Word w)
+ (frame : Stage → Word w) (calls : Stage → List (Memory w × Report w)) (ss : List Stage)
+ (bounds : ∀ s ∈ ss, Bounded u s (calls s)) :
+ RAMBuckets.cost Report.probes (ss.flatMap fun s => (calls s).map (linked p tag (frame s) s)) ≤
+ (ss.map (stageBudget u)).sum := by
+ induction ss with
+ | nil => simp [RAMBuckets.cost]
+ | cons s ss ih =>
+ rw [List.flatMap_cons, RAMBuckets.cost_append, List.map_cons, List.sum_cons]
+ apply Nat.add_le_add _ (ih fun i hi => bounds i (List.mem_cons_of_mem _ hi))
+ obtain ⟨hl, hc⟩ := bounds s (List.mem_cons_self ..)
+ exact (linked_stage_cost ..).trans (Nat.add_le_add hc (Nat.mul_le_mul_left _ hl))
+
+private theorem budget_sum (u : Parameters) (first last empty : Bool) :
+ ((tailStages first last empty).map (stageBudget u)).sum = groupBound u first last empty := by
+ cases first <;> cases last <;> cases empty <;>
+ simp [tailStages, stageBudget, groupBound, rawBudget, frameReads, dispatchProbes,
+ Stage.firstTail, Stage.last, Stage.initialState, Stage.finalState, Stage.prefixLength, Stage.adviceFrames,
+ Stage.prefixPack, Stage.orderPack, Stage.prefixCopy, Stage.skeleton, Stage.scatter,
+ Stage.oldGather, Stage.newGather, Stage.transition] <;> ring
+
+/-- A single symbolic RAM-cost bound for a first, interior, last, or sole
+tail group. The hypothesis concerns its component traces. The conclusion
+charges the framed reports and the real dispatcher/transfer reports. -/
+theorem tail_group_cost (p : UniversalMachine.Program) (u : Parameters) (first last : Bool)
+ (tag : Word w) (frame : Stage → Word w) (calls : Stage → List (Memory w × Report w))
+ (bounds : ∀ s ∈ tailStages first last (decide (p.extra = 0)), Bounded u s (calls s)) :
+ RAMBuckets.cost Report.probes ((tailStages first last (decide (p.extra = 0))).flatMap
+ fun s => (calls s).map (linked p tag (frame s) s)) ≤ groupBound u first last (decide (p.extra = 0)) :=
+ (cost_list p u tag frame calls _ bounds).trans_eq (budget_sum ..)
+
+end LiveEvaluatorTailCost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveEvaluatorTailCostFacts.lean b/lean/OAI/Computability/VPVNP/LiveEvaluatorTailCostFacts.lean
new file mode 100644
index 0000000000..98912a8cd3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveEvaluatorTailCostFacts.lean
@@ -0,0 +1,196 @@
+import OAI.Computability.VPVNP.LiveEvaluatorTailCost
+import OAI.Computability.VPVNP.LiveConfigGatherRun
+import OAI.Computability.VPVNP.RAMChoicePrefix
+
+/-!
+# Resource bounds for native tail-group calls
+
+The incoming and outgoing configuration gathers read one bit cell per bit and
+write one cell per word. The two routing decisions and control-word writes
+have constant cost. The final transition uses its native preparation and
+cell-scan reports. These estimates apply before stage linking.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveEvaluatorTailCost
+
+open LiveProgram BurstRAM
+
+variable {w k : ℕ}
+
+private theorem cost_of_constant_probes (rs : List (Report w)) (b : ℕ)
+ (h : ∀ r ∈ rs, r.probes = b) : RAMBuckets.cost Report.probes rs = rs.length * (b+1) := by
+ induction rs with
+ | nil => simp [RAMBuckets.cost]
+ | cons r rs ih =>
+ rw [RAMBuckets.cost, h r (List.mem_cons_self ..),
+ ih (fun t ht => h t (List.mem_cons_of_mem r ht)), List.length_cons, Nat.succ_mul]
+ omega
+
+/-- Each native gather report charges exactly one read per bit and one write. -/
+theorem gather_cost (pub : LiveConfigGather.Pub → Word w) (words : Fin k → Word w) :
+ let rs := (List.finRange k).map (LiveConfigGather.wordReport pub words)
+ rs.length = k ∧ RAMBuckets.cost Report.probes rs = k * (w+2) ∧
+ ∀ r ∈ rs, r.probes = w+1 := by
+ intro rs
+ have hl : rs.length = k := by simp [rs]
+ have hp : ∀ r ∈ rs, r.probes = w+1 := by
+ intro r hr
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp hr
+ exact LiveConfigGather.report_probes ..
+ exact ⟨hl, (cost_of_constant_probes rs (w+1) hp).trans (by rw [hl]), hp⟩
+
+/-- An accepting exit reads the tested flag. A transfer also writes the next stage tag. -/
+theorem route_cost (pub : Fin 2 → Word w) (flag : Word w) (i : Fin 3) (t : Route.Target)
+ (bits : List Bool) (r : Report w) (h : Route.report pub flag i t bits = some r) :
+ RAMBuckets.cost Report.probes [r] ≤ 3 ∧ r.probes ≤ 2 := by
+ have hp : r.probes ≤ 2 := by
+ cases bits <;> cases t <;> simp [Route.report] at h
+ all_goals subst r; fin_cases i <;> first | exact (by decide : 1 ≤ 2) | exact le_rfl
+ exact ⟨by simp [RAMBuckets.cost]; omega, hp⟩
+
+/-- The accepted-state sentinel and the initial control tag both cost two units. -/
+theorem putState_cost (tag : Word 2) (pub : Fin 4 → Word w) (s : Word w) (m : Memory w)
+ (fuel : ℕ) (bits : List Bool) (r : Report w)
+ (h : let P := ((LiveEvaluatorInitialize.putStage tag).instantiate w pub).program
+ execute P fuel (P.start s) m bits = some r) :
+ RAMBuckets.cost Report.probes [r] = 2 ∧ r.probes = 1 := by
+ have base := LiveEvaluatorInitialize.execute_putStage tag pub s m [] 0
+ simp only [ite_true] at base
+ obtain ⟨_, rfl⟩ := execute_prefix_unique (suffix := bits) base (by simpa only [List.nil_append] using h)
+ exact ⟨rfl,rfl⟩
+
+/-- A successful call publishes all four advice frames in nineteen writes
+following its one length read. -/
+theorem frames_cost (pub : LiveEvaluatorAdviceFrames.FramePub w) (s : Word w) (m : Memory w)
+ (fuel : ℕ) (bits : List Bool) (r : Report w)
+ (h : let P := (LiveEvaluatorAdviceFrames.template.instantiate w pub).program
+ execute P fuel (P.start s) m bits = some r) :
+ RAMBuckets.cost Report.probes [r] = 21 ∧ r.probes = 20 := by
+ have valid : LiveEvaluatorAdviceFrames.actualLength pub m ≤ pub 1 ∧ 0 < pub 2 := by
+ by_contra! hn
+ have bad : pub 1 < LiveEvaluatorAdviceFrames.actualLength pub m ∨ pub 2 = 0 := by
+ by_cases hc : LiveEvaluatorAdviceFrames.actualLength pub m ≤ pub 1
+ · exact Or.inr (le_antisymm (hn hc) (Fin.zero_le _))
+ · exact Or.inl (lt_of_not_ge hc)
+ have hf := LiveEvaluatorAdviceFrames.reject_frames pub s m bits fuel bad
+ cases hf.symm.trans h
+ have base := (LiveEvaluatorAdviceFrames.execute_frames pub s m valid.1 valid.2).1
+ obtain ⟨_, rfl⟩ := execute_prefix_unique (suffix := bits) base (by simpa only [List.nil_append] using h)
+ have hp := (LiveEvaluatorAdviceFrames.events_cost pub m).2.1
+ change 1 + countProbes _ + 0 = 21 ∧ countProbes _ = 20
+ rw [hp]
+ decide
+
+open LiveEvaluatorRAM.Schedule LiveEvaluatorRAMPrepare in
+private theorem step_at_callFuel (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (s : Word w) (m : Memory w) (bits : List Bool) (r : Report w) {fuel : ℕ}
+ (h : execute (nativeProgram p pub) fuel ((nativeProgram p pub).start s) m bits = some r) :
+ execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start s) m bits = some r := by
+ let run := fun f => PrimedCounter.Call.execute_iff (body (prepare p)) 29 30 pub s
+ (fun _ => 0) (fun _ => 0) m bits f r
+ obtain ⟨es, regs, mem, he, _, rest⟩ := (run fuel).mp h
+ exact (run (callFuel p)).mpr ⟨es, regs, mem, he, Nat.add_le_add_right (program_bound p he) 2, rest⟩
+
+open LiveEvaluatorRAM.Schedule in
+/-- Any successful segment can replay the same reports with the evaluator's
+fixed clock because every route through its body is acyclic. -/
+theorem transition_at_callFuel (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (s : Option (Word w)) (m : Memory w) (bits : List (List Bool)) (rs : List (Report w)) {fuel : ℕ}
+ (h : runSegment (nativeProgram p pub) fuel s m bits = some rs) :
+ runSegment (nativeProgram p pub) (callFuel p) s m bits = some rs := by
+ induction bits generalizing rs s m with
+ | nil => exact h
+ | cons b bs ih =>
+ cases s with
+ | none => simp [runSegment] at h
+ | some s =>
+ cases hr : execute (nativeProgram p pub) fuel ((nativeProgram p pub).start s) m b with
+ | none => simp [runSegment,hr] at h
+ | some r =>
+ simp only [runSegment,hr,Option.map_eq_some_iff] at h
+ obtain ⟨tail, ht, rfl⟩ := h
+ simp only [runSegment, step_at_callFuel p pub s m b r hr, ih r.result (after m r.events) tail ht,
+ Option.map_some]
+
+open LiveEvaluatorRAM.Schedule in
+/-- A completed transition scans both tapes over their entire radius. -/
+theorem transition_cost (p : UniversalMachine.Program) (pub : Pub → Word w) (m : Memory w)
+ (bits : List (List Bool)) (rs : List (Report w)) (M : ℕ) (hM : (pub 0).val = M)
+ (hfit : calls M ≤ 2^w) (hw : 2 ≤ w) (hstates : p.extra+2 ≤ 2^w)
+ {fuel : ℕ} (hr : runSegment (nativeProgram p pub) fuel (some 0) m bits = some rs)
+ (halt : endState (some 0) rs = none) :
+ rs.length = 4*M+3 ∧ RAMBuckets.cost Report.probes rs ≤ 10+14*(2*M+1) ∧
+ ∀ r ∈ rs, r.probes ≤ 9 := by
+ have replay := transition_at_callFuel p pub (some 0) m bits rs hr
+ obtain ⟨hc, hl, hp⟩ := segmentResources p pub m bits rs hM hfit hw hstates replay halt
+ refine ⟨?_, ?_, fun r hr => (hp r hr).1⟩
+ · rw [hl, calls]
+ omega
+ · rw [hc]
+ split <;> omega
+
+private theorem bounded_of_reports (u : Parameters) (s : Stage) (calls : List (Memory w × Report w))
+ (rs : List (Report w)) (reports : calls.map Prod.snd = rs)
+ (hl : rs.length ≤ (rawBudget u s).1) (hc : RAMBuckets.cost Report.probes rs ≤ (rawBudget u s).2) :
+ Bounded u s calls := by
+ constructor
+ · simpa only [← reports, List.length_map] using hl
+ · simpa only [reports] using hc
+
+theorem bounded_gather (u : Parameters) (s : Stage) (hs : s = Stage.oldGather ∨ s = Stage.newGather)
+ (pub : LiveConfigGather.Pub → Word w) (words : Fin k → Word w) (hw : w = u.wordWidth)
+ (hk : k = u.configWords) (calls : List (Memory w × Report w))
+ (reports : calls.map Prod.snd = (List.finRange k).map (LiveConfigGather.wordReport pub words)) :
+ Bounded u s calls := by
+ obtain ⟨hl,hc,_⟩ := gather_cost pub words
+ apply bounded_of_reports u s calls _ reports
+ · rcases hs with rfl | rfl <;> exact (hl.trans hk).le
+ · rcases hs with rfl | rfl <;> change _ ≤ (u.wordWidth+2)*u.configWords <;>
+ rw [hc, hw, hk, Nat.mul_comm]
+
+theorem bounded_route (u : Parameters) (s : Stage) (hs : s = Stage.firstTail ∨ s = Stage.last)
+ (pub : Fin 2 → Word w) (flag : Word w) (i : Fin 3) (t : Route.Target) (bits : List Bool)
+ (r : Report w) (h : Route.report pub flag i t bits = some r)
+ (calls : List (Memory w × Report w)) (reports : calls.map Prod.snd = [r]) :
+ Bounded u s calls := by
+ have hc := (route_cost pub flag i t bits r h).1
+ rcases hs with rfl | rfl <;> exact bounded_of_reports u _ calls [r] reports (by rfl) hc
+
+theorem bounded_putState (u : Parameters) (stage : Stage)
+ (hs : stage = Stage.initialState ∨ stage = Stage.finalState)
+ (tag : Word 2) (pub : Fin 4 → Word w) (s : Word w) (m : Memory w)
+ (fuel : ℕ) (bits : List Bool) (r : Report w)
+ (h : let P := ((LiveEvaluatorInitialize.putStage tag).instantiate w pub).program
+ execute P fuel (P.start s) m bits = some r)
+ (calls : List (Memory w × Report w)) (reports : calls.map Prod.snd = [r]) :
+ Bounded u stage calls := by
+ have hc := (putState_cost tag pub s m fuel bits r h).1.le
+ rcases hs with rfl | rfl <;> exact bounded_of_reports u _ calls [r] reports (by rfl) hc
+
+theorem bounded_frames (u : Parameters) (pub : LiveEvaluatorAdviceFrames.FramePub w)
+ (s : Word w) (m : Memory w) (fuel : ℕ) (bits : List Bool) (r : Report w)
+ (h : let P := (LiveEvaluatorAdviceFrames.template.instantiate w pub).program
+ execute P fuel (P.start s) m bits = some r)
+ (calls : List (Memory w × Report w)) (reports : calls.map Prod.snd = [r]) :
+ Bounded u Stage.adviceFrames calls :=
+ bounded_of_reports u _ calls [r] reports (by rfl) (frames_cost pub s m fuel bits r h).1.le
+
+open LiveEvaluatorRAM.Schedule in
+theorem bounded_transition (u : Parameters) (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (m : Memory w) (bits : List (List Bool)) (rs : List (Report w))
+ (hM : (pub 0).val = u.radius) (hfit : calls u.radius ≤ 2^w) (hw : 2 ≤ w)
+ (hstates : p.extra+2 ≤ 2^w) {fuel : ℕ} (hr : runSegment (nativeProgram p pub) fuel (some 0) m bits = some rs)
+ (halt : endState (some 0) rs = none) (entryCalls : List (Memory w × Report w))
+ (reports : entryCalls.map Prod.snd = rs) : Bounded u Stage.transition entryCalls := by
+ obtain ⟨hl,hc,_⟩ := transition_cost p pub m bits rs u.radius hM hfit hw hstates hr halt
+ exact bounded_of_reports u _ entryCalls rs reports hl.le hc
+
+end LiveEvaluatorTailCost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveExponentBuffers.lean b/lean/OAI/Computability/VPVNP/LiveExponentBuffers.lean
new file mode 100644
index 0000000000..642a488f56
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveExponentBuffers.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.LiveExponentSweep
+
+/-!
+# The exponent stage on the paper's serialized cut buffers
+
+The addresses are three disjoint flat arrays. The input and output buffers
+contain the little-endian serialization of their exponent words. Processing
+a label clears that label's counter word and leaves every other label's
+initial increment available for its own row of calls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveExponent
+
+open BurstRAM RAMSerialization
+open scoped Classical Fin.CommRing
+
+variable {w t Z : ℕ}
+
+/-- Address of the increment word for a label. -/
+def counterAddr (pub : Fin 5 → Word w) (a : Fin t) : Word w := pub 2 + Fin.ofNat _ a.val
+
+/-- Encode the flattened address offset of a given label and exponent digit. -/
+def posWord (a : Fin t) (j : Fin Z) : Word w := Fin.ofNat _ (a.val * Z + j.val)
+
+/-- Data and address contract of the stage after the header and pair phases. -/
+structure BufferLayout (pub : Fin 5 → Word w) (t Z : ℕ) : Prop where
+ width : (pub 3).val = Z
+ size : (pub 4).val = t*Z
+ incoming_disjoint : ∀ (a b : Fin t) (j : Fin Z), incomingAddress pub (posWord a j) ≠ counterAddr pub b
+ outgoing_disjoint : ∀ (a b : Fin t) (j : Fin Z), outgoingAddress pub (posWord a j) ≠ counterAddr pub b
+
+/-- The actual little-endian word arrays produced by the header scan. -/
+structure BufferValues (pub : Fin 5 → Word w) (x y : Fin t → Word Z) (m : Memory w) : Prop where
+ incoming : ∀ a j, (m (incomingAddress pub (posWord a j)).val).val = (wordBits Z (x a) j).toNat
+ outgoing : ∀ a j, (m (outgoingAddress pub (posWord a j)).val).val = (wordBits Z (y a) j).toNat
+
+/-- Clearing a completed carry preserves both read-only arrays. -/
+theorem BufferValues.write_counter {pub : Fin 5 → Word w} (L : BufferLayout pub t Z)
+ {x y : Fin t → Word Z} {m : Memory w} (v : BufferValues pub x y m) (b : Fin t) (c : Word w) :
+ BufferValues pub x y (writeMemory m (counterAddr pub b) c) := by
+ constructor <;> intro a j
+ · rw [writeMemory, ite_eq_right (fun e => L.incoming_disjoint a b j (Fin.ext e))]
+ exact v.incoming a j
+ · rw [writeMemory, ite_eq_right (fun e => L.outgoing_disjoint a b j (Fin.ext e))]
+ exact v.outgoing a j
+
+private theorem pos_lt (a : Fin t) (j : Fin Z) : a.val*Z+j.val < t*Z := by
+ calc
+ a.val*Z+j.val < a.val*Z+Z := Nat.add_lt_add_left j.isLt _
+ _ = (a.val+1)*Z := (Nat.succ_mul ..).symm
+ _ ≤ t*Z := Nat.mul_le_mul_right _ a.isLt
+
+theorem counterAddr_injective {pub : Fin 5 → Word w} (L : BufferLayout pub t Z) (hZ : 0 < Z) :
+ Function.Injective (counterAddr (t := t) pub) := by
+ intro a b he
+ have hab : (Fin.ofNat (2^w) a.val : Word w) = Fin.ofNat (2^w) b.val :=
+ add_left_cancel (show pub 2 + _ = pub 2 + _ from he)
+ have ht : t ≤ t*Z := Nat.le_mul_of_pos_right t hZ
+ have hcap : t*Z < 2^w := L.size ▸ (pub 4).isLt
+ apply Fin.ext
+ exact (Nat.mod_eq_of_lt ((a.isLt.trans_le ht).trans hcap)).symm.trans
+ ((congrArg Fin.val hab).trans (Nat.mod_eq_of_lt ((b.isLt.trans_le ht).trans hcap)))
+
+/-- One row of the digit scan in its physical order. -/
+def wordRow (x y : Word Z) : List (Bool × Bool) := List.ofFn fun j => (wordBits Z x j, wordBits Z y j)
+
+@[simp] theorem wordRow_length (x y : Word Z) : (wordRow x y).length = Z := List.length_ofFn
+
+theorem wordRow_checks (x y : Word Z) (c : ℕ) :
+ Checks c ((wordRow x y).map Prod.fst) ((wordRow x y).map Prod.snd) ↔ y.val = x.val+c := by
+ simpa [wordRow, List.map_ofFn, BurstRAM.wordBits, Function.comp_def] using checks_words c x y
+
+theorem BufferValues.rowCells {pub : Fin 5 → Word w} (L : BufferLayout pub t Z) (hZ : 0 < Z)
+ {x y : Fin t → Word Z} {m : Memory w} (v : BufferValues pub x y m) (a : Fin t) :
+ RowCells pub (counterAddr pub a) (a.val*Z) (wordRow (x a) (y a)) m := by
+ constructor
+ · rw [wordRow_length, ← Nat.succ_mul, L.size]
+ exact Nat.mul_le_mul_right _ a.isLt
+ · intro j hj
+ have hjZ : j < Z := by simpa using hj
+ let k : Fin Z := ⟨j,hjZ⟩
+ have hpos : (posWord (w := w) a k).val = a.val*Z+j :=
+ Nat.mod_eq_of_lt ((pos_lt a k).trans (L.size ▸ (pub 4).isLt))
+ have hcarry : carryAddress pub (posWord a k) = counterAddr pub a := by
+ unfold carryAddress counterAddr
+ congr 1
+ change Fin.ofNat _ ((posWord (w := w) a k).val / (pub 3).val) = _
+ rw [hpos, L.width, Nat.mul_comm a.val Z, Nat.mul_add_div hZ, Nat.div_eq_of_lt hjZ, Nat.add_zero]
+ refine ⟨hcarry,L.incoming_disjoint a a k,L.outgoing_disjoint a a k,?_,?_,?_⟩
+ · simpa [wordRow, k, posWord, atPos] using v.incoming a k
+ · simpa [wordRow, k, posWord, atPos] using v.outgoing a k
+ · simp [L.width, Nat.mul_comm a.val Z, Nat.mod_eq_of_lt hjZ]
+
+/-- Full native row specification on the actual serialized buffers. -/
+theorem run_wordRow {pub : Fin 5 → Word w} (L : BufferLayout pub t Z) (hZ : 0 < Z) (hw : 2 ≤ w)
+ {x y : Fin t → Word Z} {m : Memory w} (v : BufferValues pub x y m) (a : Fin t)
+ (hc : (m (counterAddr pub a).val).val + 1 < 2^w)
+ (bits : List (List Bool)) (hlen : bits.length = Z) (tail : List (List Bool)) (f : ℕ) :
+ let P := (digitTemplate.instantiate w pub).program
+ runSegment P (f+31) (some (Fin.ofNat _ (a.val*Z))) m (bits ++ tail) =
+ if (y a).val = (x a).val + (m (counterAddr pub a).val).val ∧ bits = List.replicate Z [] then
+ (runSegment P (f+31) (some (Fin.ofNat _ ((a.val+1)*Z))) (writeMemory m (counterAddr pub a) 0)
+ tail).map (rowReports pub Z (a.val*Z) m ++ ·)
+ else none := by
+ have hn : wordRow (x a) (y a) ≠ [] := by
+ intro hn
+ have he := congrArg List.length hn
+ simp at he
+ omega
+ have he := run_row hw (L.width ▸ hZ) (v.rowCells L hZ a) hc hn bits (by simpa using hlen) tail f
+ rw [wordRow_checks, wordRow_length, ← Nat.succ_mul] at he
+ by_cases hgood : (y a).val = (x a).val + (m (counterAddr pub a).val).val ∧ bits = List.replicate Z []
+ · simpa only [hgood, ite_true, atPos, Nat.succ_eq_add_one] using he
+ · simpa only [hgood, ite_false, atPos, Nat.succ_eq_add_one] using he
+
+end LiveExponent
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveExponentDigits.lean b/lean/OAI/Computability/VPVNP/LiveExponentDigits.lean
new file mode 100644
index 0000000000..a937655c19
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveExponentDigits.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Checking a running exponent one bit at a time
+
+In the first half of the live chain an increment fits in one RAM word, while
+the incoming and outgoing exponents may occupy many words. A digit call
+checks the low bit of the sum and passes its quotient by two to the next
+digit. Requiring zero final carry checks ordinary natural-number addition.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveExponent
+
+open BurstRAM
+open PrimedCounter.GuessWord (value)
+
+private theorem boolDigit (b : Bool) : (finTwoEquiv.symm b).val = b.toNat := by
+ cases b <;> rfl
+
+/-- The carry and the low input bit of one digit. -/
+def total (c : ℕ) (b : Bool) := c + b.toNat
+
+/-- Each digit must match the outgoing bit. The final digit's carry must vanish. -/
+def Checks : ℕ → List Bool → List Bool → Prop
+ | c, [], [] => c = 0
+ | c, x :: xs, y :: ys => y.toNat = total c x % 2 ∧ Checks (total c x / 2) xs ys
+ | _, _, _ => False
+
+/-- The checks enforce the full-width equation including overflow. -/
+theorem checks_iff {c : ℕ} {xs ys : List Bool} (hlen : xs.length = ys.length) :
+ Checks c xs ys ↔ value ys = value xs + c := by
+ induction xs generalizing c ys with
+ | nil =>
+ cases ys <;> simp_all [Checks, value, eq_comm]
+ | cons b xs ih =>
+ cases ys with
+ | nil => simp at hlen
+ | cons d ys =>
+ simp only [List.length_cons, Nat.add_right_cancel_iff] at hlen
+ rw [Checks, ih hlen]
+ simp only [value, boolDigit, total]
+ have hd : d.toNat ≤ 1 := by cases d <;> decide
+ omega
+
+/-- Specialization to the actual little-endian cut encoding. -/
+theorem checks_words {Z : ℕ} (c : ℕ) (x y : Word Z) :
+ Checks c (wordBits x) (wordBits y) ↔ y.val = x.val + c := by
+ rw [checks_iff (by simp), PrimedCounter.GuessWord.value_wordBits,
+ PrimedCounter.GuessWord.value_wordBits]
+
+/-- Even with a long binary input exponent, the carry never grows above the
+larger of the initial increment and one. -/
+theorem carry_le {B c : ℕ} (hc : c ≤ B) (b : Bool) : total c b / 2 ≤ B := by
+ have hb : b.toNat ≤ 1 := by cases b <;> decide
+ unfold total
+ omega
+
+end LiveExponent
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveExponentFrame.lean b/lean/OAI/Computability/VPVNP/LiveExponentFrame.lean
new file mode 100644
index 0000000000..35b7fabdbe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveExponentFrame.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.LiveExponentPaths
+import OAI.Computability.VPVNP.LiveStagePaths
+
+/-!
+# Frame and address guarantees for the linked exponent stage
+
+The public bases are selected so the two input areas precede the carry
+array, and all three arrays fit in the RAM address space. The native
+program only changes the current label's carry. In particular its
+continuing calls preserve the live-program dispatch tag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveExponent
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {w t Z : ℕ}
+
+theorem counterAddr_val (pub : Fin 5 → Word w) (a : Fin t) (hfit : (pub 2).val+t ≤ 2^w) :
+ (counterAddr pub a).val = (pub 2).val+a.val := by
+ have ha := a.isLt
+ rw [counterAddr, Fin.val_add, Fin.val_ofNat, Nat.mod_eq_of_lt (show a.val < 2^w by omega), Nat.mod_eq_of_lt (by omega)]
+
+private theorem bufferAddress_val (base : Word w) (a : Fin t) (j : Fin Z)
+ (fit : base.val+t*Z ≤ 2^w) : (base+posWord a j).val = base.val+(a.val*Z+j.val) := by
+ have hj : a.val*Z+j.val < t*Z := calc
+ _ < a.val*Z+Z := Nat.add_lt_add_left j.isLt _
+ _ = (a.val+1)*Z := (Nat.succ_mul ..).symm
+ _ ≤ t*Z := Nat.mul_le_mul_right _ a.isLt
+ rw [Fin.val_add]
+ change (base.val + ((a.val*Z+j.val) % (2^w))) % (2^w) = _
+ rw [Nat.mod_eq_of_lt (show a.val*Z+j.val < 2^w by omega), Nat.mod_eq_of_lt (by omega)]
+
+/-- A numerical memory layout sufficient for the actual digit table.
+The two read-only arrays may be separated by other scratch regions. -/
+theorem layout_of_ranges (pub : Fin 5 → Word w) (hz : (pub 3).val = Z) (ht : (pub 4).val = t*Z)
+ (left : (pub 0).val+t*Z ≤ (pub 2).val) (right : (pub 1).val+t*Z ≤ (pub 2).val)
+ (fit : (pub 2).val+t ≤ 2^w) : BufferLayout pub t Z := by
+ refine ⟨hz,ht,?_,?_⟩ <;> intro a b j he
+ · have h := congrArg Fin.val he
+ rw [incomingAddress, bufferAddress_val _ _ _ (left.trans (pub 2).isLt.le), counterAddr_val _ _ fit] at h
+ have hi := (finProdFinEquiv (a,j)).isLt
+ change j.val+Z*a.val < t*Z at hi
+ rw [Nat.mul_comm Z a.val] at hi
+ omega
+ · have h := congrArg Fin.val he
+ rw [outgoingAddress, bufferAddress_val _ _ _ (right.trans (pub 2).isLt.le), counterAddr_val _ _ fit] at h
+ have hi := (finProdFinEquiv (a,j)).isLt
+ change j.val+Z*a.val < t*Z at hi
+ rw [Nat.mul_comm Z a.val] at hi
+ omega
+
+/-- Continuing native calls advance the cursor within its range and
+preserve any cell outside the entire carry array. -/
+theorem frame_result {pub : Fin 5 → Word w} (L : BufferLayout pub t Z)
+ {addr : Word w} (fresh : ∀ a : Fin t, counterAddr pub a ≠ addr)
+ {s s' : Word w} {m : Memory w} {b : List Bool} {r : Report w} {f : ℕ}
+ (hs : s ≤ pub 4)
+ (hc : execute (digitTemplate.instantiate w pub).program (f+31)
+ ((digitTemplate.instantiate w pub).program.start s) m b = some r)
+ (next : r.result = some s') : s' ≤ pub 4 ∧ after m r.events addr.val = m addr.val := by
+ rcases lt_or_eq_of_le hs with hlt | rfl
+ · obtain ⟨_, rfl⟩ := data_result hlt hc
+ obtain rfl : s+1 = s' := Option.some.inj next
+ have hv : s.val < t*Z := L.size ▸ hlt
+ have hz : 0 < Z := by by_contra! hh; simp [Nat.eq_zero_of_le_zero hh] at hv
+ let a : Fin t := ⟨s.val/Z, (Nat.div_lt_iff_lt_mul hz).mpr hv⟩
+ have ea : carryAddress pub s = counterAddr pub a := by
+ change pub 2 + Fin.ofNat _ (s.val/(pub 3).val) = _
+ rw [L.width]
+ rfl
+ refine ⟨?_,?_⟩
+ · change (s+1).val ≤ (pub 4).val
+ have hlt' : s.val < (pub 4).val := hlt
+ rw [Fin.val_add_one_of_lt' (lt_of_le_of_lt hlt' (pub 4).isLt)]
+ exact hlt'
+ · rw [digitReport_after, ea, writeMemory, ite_eq_right (fun h => fresh a (Fin.ext h.symm))]
+ · rw [show f+31 = (f+26)+5 by omega, execute_done pub (pub 4) m b (f+26) rfl] at hc
+ split at hc
+ · cases hc
+ contradiction
+ · contradiction
+
+end LiveExponent
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveExponentOperands.lean b/lean/OAI/Computability/VPVNP/LiveExponentOperands.lean
new file mode 100644
index 0000000000..45fdbf371d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveExponentOperands.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.LiveExponentFrame
+import OAI.Computability.VPVNP.LiveProgramLayout
+import Mathlib.Data.Fin.VecNotation
+
+/-!
+# Public operands of the live exponent table
+
+These five expressions are evaluated from the processor's public geometry.
+The header scan and the pair subroutine refer to the very same bit and
+counter buffers. The stage dispatcher sits below the header workspace.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.ExponentStage
+
+open BurstRAM LiveHeaderWidths LiveExponent
+
+/-- Public expressions for the incoming and outgoing digit arrays, increment counters, digit
+width, and total digit count. -/
+def operands (c : Constants) : Fin 5 → PublicExpr :=
+ ![HeaderLayout.exponent c.lengths Layout.header .left,
+ HeaderLayout.exponent c.lengths Layout.header .right,
+ Layout.counter c, c.Z, c.labels*c.Z]
+
+/-- Evaluate the exponent stage's five public address and size expressions as machine words for
+the supplied geometry. -/
+def words (c : Constants) (g : Geometry) : Fin 5 → Word g.w :=
+ fun i => Fin.ofNat _ ((operands c i).eval g)
+
+private theorem ranges (c : Constants) (g : Geometry) :
+ let t := c.labels.eval g
+ let Z := c.Z.eval g
+ ((operands c 0).eval g + t*Z ≤ (Layout.counter c).eval g) ∧
+ ((operands c 1).eval g + t*Z ≤ (Layout.counter c).eval g) ∧
+ Layout.stageTag.eval g < (Layout.counter c).eval g := by
+ dsimp only
+ simp [operands, Layout.counter, Layout.descriptor, Layout.header, HeaderLayout.limit, HeaderLayout.config,
+ HeaderLayout.exponent, HeaderLayout.exterior, HeaderLayout.advice, HeaderLayout.rightIndex,
+ HeaderLayout.leftIndex, HeaderLayout.population, HeaderLayout.high, HeaderLayout.index, Constants.lengths,
+ show (21 : PublicExpr).eval g = 21 from rfl]
+ omega
+
+theorem layout (c : Constants) (g : Geometry)
+ (fit : (Layout.oldState c).eval g ≤ 2^g.w) (hasLabels : 0 < c.labels.eval g) :
+ BufferLayout (words c g) (c.labels.eval g) (c.Z.eval g) := by
+ obtain ⟨hl, hr, htag⟩ := ranges c g
+ change (Layout.counter c).eval g + c.labels.eval g ≤ 2^g.w at fit
+ have hc : (Layout.counter c).eval g < 2^g.w := by omega
+ have hlen : c.labels.eval g*c.Z.eval g < 2^g.w := by omega
+ have hwidth : c.Z.eval g < 2^g.w :=
+ (Nat.le_mul_of_pos_left _ hasLabels).trans_lt hlen
+ have hi : (operands c 0).eval g < 2^g.w := by omega
+ have ho : (operands c 1).eval g < 2^g.w := by omega
+ apply layout_of_ranges
+ · exact Nat.mod_eq_of_lt hwidth
+ · exact Nat.mod_eq_of_lt hlen
+ · change (operands c 0).eval g % (2^g.w) + _ ≤ (Layout.counter c).eval g % (2^g.w)
+ rwa [Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt hc]
+ · change (operands c 1).eval g % (2^g.w) + _ ≤ (Layout.counter c).eval g % (2^g.w)
+ rwa [Nat.mod_eq_of_lt ho, Nat.mod_eq_of_lt hc]
+ · change (Layout.counter c).eval g % (2^g.w) + c.labels.eval g ≤ 2^g.w
+ rwa [Nat.mod_eq_of_lt hc]
+
+theorem tag_fresh (c : Constants) (g : Geometry) (fit : (Layout.oldState c).eval g ≤ 2^g.w)
+ (a : Fin (c.labels.eval g)) :
+ counterAddr (words c g) a ≠ Fin.ofNat _ (Layout.stageTag.eval g) := by
+ have ht := (ranges c g).2.2
+ change (Layout.counter c).eval g + c.labels.eval g ≤ 2^g.w at fit
+ have ha := a.isLt
+ have hc : (Layout.counter c).eval g < 2^g.w := by omega
+ have hv : (words c g 2).val = (Layout.counter c).eval g := Nat.mod_eq_of_lt hc
+ have hfit : (words c g 2).val + c.labels.eval g ≤ 2^g.w := hv ▸ fit
+ intro eq
+ have h := congrArg Fin.val eq
+ rw [counterAddr_val _ _ hfit, hv, Fin.val_ofNat, Nat.mod_eq_of_lt (ht.trans hc)] at h
+ omega
+
+end LiveProgram.ExponentStage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveExponentPaths.lean b/lean/OAI/Computability/VPVNP/LiveExponentPaths.lean
new file mode 100644
index 0000000000..25cea048e9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveExponentPaths.lean
@@ -0,0 +1,164 @@
+import OAI.Computability.VPVNP.LiveExponentRows
+import OAI.Computability.VPVNP.RAMSuccessor
+import Mathlib.SetTheory.Cardinal.Finite
+
+/-!
+# Native path multiplicity and resource bounds of exponent addition
+
+For any initialized buffers the exponent stage accepts either once or zero
+times. A successful run has one data call for every physical cut digit, one
+accepting end call, and no binary choices. The count covers all finite native
+call streams, including streams of unintended lengths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveExponent
+
+open BurstRAM
+open scoped Classical
+
+variable {w t Z : ℕ}
+
+private theorem halted_stream (pub : Fin 5 → Word w) (f : ℕ) (bs : List (List Bool))
+ (s : Word w) (m : Memory w) (rs : List (Report w)) (hs : s ≤ pub 4)
+ (hr : runSegment (digitTemplate.instantiate w pub).program (f+31) (some s) m bs = some rs)
+ (he : endState (some s) rs = none) : bs = List.replicate ((pub 4).val + 1 - s.val) [] := by
+ induction bs generalizing s m rs with
+ | nil =>
+ change some [] = some rs at hr
+ cases hr
+ contradiction
+ | cons b bs ih =>
+ rw [runSegment] at hr
+ cases h : execute (digitTemplate.instantiate w pub).program (f+31)
+ ((digitTemplate.instantiate w pub).program.start s) m b with
+ | none => simp [h] at hr
+ | some r =>
+ rw [h, Option.map_eq_some_iff] at hr
+ obtain ⟨rest, htail, rfl⟩ := hr
+ change endState r.result rest = none at he
+ rcases lt_or_eq_of_le hs with hlt | rfl
+ · obtain ⟨rfl,rfl⟩ := data_result hlt h
+ have hsp : (s+1).val = s.val+1 := Fin.val_add_one_of_lt' (by
+ have := (pub 4).isLt
+ change s.val < (pub 4).val at hlt
+ omega)
+ change runSegment _ _ (some (s+1)) _ _ = _ at htail
+ change endState (some (s+1)) rest = none at he
+ have hle : s+1 ≤ pub 4 := by
+ change (s+1).val ≤ (pub 4).val
+ rw [hsp]
+ exact hlt
+ change s.val < (pub 4).val at hlt
+ rw [ih (s+1) _ rest hle htail he, hsp,
+ show (pub 4).val + 1 - s.val = ((pub 4).val + 1 - (s.val+1))+1 by omega,
+ List.replicate_succ]
+ · rw [show f+31 = (f+26)+5 by omega, execute_done pub (pub 4) m b (f+26) rfl] at h
+ by_cases hb : b = []
+ · simp only [hb, ite_true, Option.some.injEq] at h
+ subst r
+ cases bs with
+ | nil => simp [hb]
+ | cons c bs => contradiction
+ · simp [hb] at h
+
+/-- All successful digit reports followed by the accepting call. -/
+def stageReports (pub : Fin 5 → Word w) (t Z : ℕ) (m : Memory w) : List (Report w) :=
+ rowsReports pub Z (List.finRange t) m ++ [⟨[.tick,.tick,.tick,.tick],none⟩]
+
+private theorem flatten_empty (rows : List (Fin t)) :
+ rows.flatMap (fun _ => List.replicate Z ([] : List Bool)) = List.replicate (rows.length*Z) [] := by
+ induction rows with
+ | nil => simp
+ | cons a rows ih =>
+ rw [List.flatMap_cons, ih, List.replicate_append_replicate, List.length_cons, Nat.succ_mul, Nat.add_comm]
+
+private theorem canonical_stage {pub : Fin 5 → Word w} (L : BufferLayout pub t Z) (hZ : 0 < Z) (hw : 2 ≤ w)
+ {x y : Fin t → Word Z} {m : Memory w} (v : BufferValues pub x y m)
+ (inc : Fin t → Word w) (hi : ∀ a, m (counterAddr pub a).val = inc a)
+ (hc : ∀ a, (inc a).val+1 < 2^w) (f : ℕ) :
+ runSegment (digitTemplate.instantiate w pub).program (f+31) (some 0) m
+ (List.replicate (t*Z+1) []) =
+ if ∀ a, (y a).val = (x a).val+(inc a).val then some (stageReports pub t Z m) else none := by
+ have he := run_stage L hZ hw v inc hi hc (fun _ => List.replicate Z []) (by simp) [] f
+ rw [flatten_empty, List.length_finRange] at he
+ simpa [stageReports, List.replicate_add] using he
+
+/-- The cardinality of native accepting paths for any report cap. -/
+theorem pathCount {pub : Fin 5 → Word w} (L : BufferLayout pub t Z) (hZ : 0 < Z) (hw : 2 ≤ w)
+ {x y : Fin t → Word Z} {m : Memory w} (v : BufferValues pub x y m)
+ (inc : Fin t → Word w) (hi : ∀ a, m (counterAddr pub a).val = inc a)
+ (hc : ∀ a, (inc a).val+1 < 2^w) (f : ℕ) (cap : List (Report w) → Prop) :
+ Nat.card (ActualPaths (digitTemplate.instantiate w pub).program (f+31) 0 m cap) =
+ if (∀ a, (y a).val = (x a).val+(inc a).val) ∧ cap (stageReports pub t Z m) then 1 else 0 := by
+ let paths := ActualPaths (digitTemplate.instantiate w pub).program (f+31) 0 m cap
+ have uniq (a : paths) : a.val = List.replicate (t*Z+1) [] := by
+ obtain ⟨rs, hr, he, _⟩ := a.property
+ simpa [L.size] using halted_stream pub f a.val 0 m rs (Fin.zero_le _) hr he
+ have run := canonical_stage L hZ hw v inc hi hc f
+ by_cases hgood : (∀ a, (y a).val = (x a).val+(inc a).val) ∧ cap (stageReports pub t Z m)
+ · rw [ite_eq_left hgood]
+ apply Nat.card_eq_one_iff_unique.mpr
+ refine ⟨⟨fun a b => Subtype.ext ((uniq a).trans (uniq b).symm)⟩, ⟨⟨List.replicate (t*Z+1) [],stageReports pub t Z m,?_,?_,hgood.2⟩⟩⟩
+ · exact run.trans (ite_eq_left hgood.1)
+ · rw [stageReports, endState_append]
+ rfl
+ · rw [ite_eq_right hgood]
+ have : IsEmpty paths := ⟨fun a => by
+ obtain ⟨rs, hr, _, hp⟩ := a.property
+ rw [uniq a, run] at hr
+ split at hr
+ · rename_i he
+ exact hgood ⟨he, Option.some.inj hr ▸ hp⟩
+ · contradiction⟩
+ exact Nat.card_of_isEmpty
+
+private theorem rowResources (pub : Fin 5 → Word w) (n p : ℕ) (m : Memory w) :
+ RAMBuckets.cost Report.probes (rowReports pub n p m) = 5*n ∧
+ (rowReports pub n p m).length = n ∧
+ ∀ r ∈ rowReports pub n p m, r.probes = 4 ∧ r.events.length = 30 := by
+ induction n generalizing p m with
+ | zero => simp [rowReports, RAMBuckets.cost]
+ | succ n ih =>
+ let r := digitReport pub (atPos p) m
+ have h := ih (p+1) (after m r.events)
+ change 1+r.probes+_ = _ ∧ (_:: _).length = _ ∧ ∀ a ∈ r :: _, _
+ rw [(digitReport_cost pub (atPos p) m).1, h.1, List.length_cons, h.2.1, List.forall_mem_cons]
+ exact ⟨by omega, rfl, ⟨(digitReport_cost ..).1, (digitReport_cost ..).2.1⟩, h.2.2⟩
+
+private theorem rowsResources (pub : Fin 5 → Word w) (rows : List (Fin t)) (m : Memory w) :
+ RAMBuckets.cost Report.probes (rowsReports pub Z rows m) = 5*(rows.length*Z) ∧
+ (rowsReports pub Z rows m).length = rows.length*Z ∧
+ ∀ r ∈ rowsReports pub Z rows m, r.probes = 4 ∧ r.events.length = 30 := by
+ induction rows generalizing m with
+ | nil => simp [rowsReports, RAMBuckets.cost]
+ | cons a rows ih =>
+ have h := rowResources pub Z (a.val*Z) m
+ have h' := ih (writeMemory m (counterAddr pub a) 0)
+ simp only [rowsReports, RAMBuckets.cost_append, h.1, h'.1, List.length_append, h.2.1, h'.2.1,
+ List.length_cons, Nat.succ_mul, List.forall_mem_append]
+ exact ⟨by ring, by omega, h.2.2, h'.2.2⟩
+
+/-- Total native cost, call count and per-call clock/probe bound. -/
+theorem stageResources (pub : Fin 5 → Word w) (t Z : ℕ) (m : Memory w) :
+ RAMBuckets.cost Report.probes (stageReports pub t Z m) = 5*(t*Z)+1 ∧
+ (stageReports pub t Z m).length = t*Z+1 ∧
+ ∀ r ∈ stageReports pub t Z m, r.probes ≤ 4 ∧ r.events.length ≤ 30 := by
+ have h := rowsResources (Z := Z) pub (List.finRange t) m
+ simp only [List.length_finRange] at h
+ simp only [stageReports, RAMBuckets.cost_append, h.1, List.length_append, h.2.1,
+ List.forall_mem_append, List.forall_mem_singleton]
+ exact ⟨rfl,rfl,fun r hr => ⟨(h.2.2 r hr).1.le,(h.2.2 r hr).2.le⟩,show 0 ≤ 4 ∧ 4 ≤ 30 from by decide⟩
+
+theorem stageCaps (pub : Fin 5 → Word w) (m : Memory w) {S H : ℕ}
+ (hcost : 5*(t*Z)+1 ≤ S*H) (hb : 5 ≤ H) : withinCaps S H (stageReports pub t Z m) :=
+ ⟨(stageResources ..).1 ▸ hcost, fun r hr => by have := (stageResources pub t Z m).2.2 r hr; omega⟩
+
+end LiveExponent
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveExponentRAM.lean b/lean/OAI/Computability/VPVNP/LiveExponentRAM.lean
new file mode 100644
index 0000000000..9afa1837a3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveExponentRAM.lean
@@ -0,0 +1,303 @@
+import OAI.Computability.VPVNP.LiveExponentDigits
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Native burst RAM digit calls for the live exponent update
+
+The persistent word indexes the flattened exponent array. Public words
+designate the incoming bit array, outgoing bit array, increment array,
+digit width and total digit count, respectively. The increment array
+initially holds the nominated grammar counts followed by the gadget
+counts. Its entry for a label doubles as that label's carry. Each call
+uses four external probes regardless of the length of an exponent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveExponent
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+/-- A native digit-update operation over sixteen registers and five public operands. -/
+abbrev DigitOp := Op 16 5
+
+/-- Register zero is the digit cursor and register one receives its successor.
+Registers 2, 3, 4 hold incoming, outgoing and carry addresses. Registers 5, 6, 7
+hold their loaded values. Registers 8 and 9 hold the total and next carry.
+The last bit of each label additionally requires the carry to vanish. -/
+def digitOps : List DigitOp :=
+ [.stateWord 0, .publicWord 10 3, .publicWord 2 0, .binary .add 2 2 0,
+ .read 5 2, .publicWord 3 1, .binary .add 3 3 0, .read 6 3,
+ .binary .div 11 0 10, .publicWord 4 2, .binary .add 4 4 11, .read 7 4,
+ .constant 12 2, .guardLt 5 12, .binary .add 8 7 5,
+ .binary .mod 11 8 12, .guardEq 6 11, .binary .div 9 8 12,
+ .constant 13 1, .binary .mod 11 0 10, .binary .add 11 11 13,
+ .binary .div 11 11 10, .binary .mul 11 11 9, .constant 14 0,
+ .guardEq 11 14, .write 4 9, .binary .add 1 0 13]
+
+variable {w : ℕ}
+
+/-- Address of the incoming cut bit at the flattened digit cursor. -/
+def incomingAddress (pub : Fin 5 → Word w) (s : Word w) := pub 0 + s
+
+/-- Address of the proposed outgoing cut bit at the flattened digit cursor. -/
+def outgoingAddress (pub : Fin 5 → Word w) (s : Word w) := pub 1 + s
+
+/-- Address of the current label's increment word, used as the carry during its digit scan. -/
+def carryAddress (pub : Fin 5 → Word w) (s : Word w) :=
+ pub 2 + BinaryOp.div.eval s (pub 3)
+
+private def sumWord (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) :=
+ m (carryAddress pub s).val + m (incomingAddress pub s).val
+
+private def lastMask (pub : Fin 5 → Word w) (s : Word w) :=
+ BinaryOp.div.eval ((BinaryOp.mod.eval s (pub 3)) + Fin.ofNat (2^w) (1 : Word 2).val) (pub 3)
+
+private def carryWord (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) :=
+ BinaryOp.div.eval (sumWord pub s m) 2
+
+private def NativeTest (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : Prop :=
+ m (incomingAddress pub s).val < 2 ∧
+ m (outgoingAddress pub s).val = BinaryOp.mod.eval (sumWord pub s m) 2 ∧
+ lastMask pub s * carryWord pub s m = 0
+
+private instance (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : Decidable (NativeTest pub s m) := by
+ unfold NativeTest
+ infer_instance
+
+/-- Exact event stream of a successful digit block, including its three
+memory reads and its single write. -/
+def digitEvents (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : List (Event w) :=
+ [.tick, .tick, .tick, .tick, .read (incomingAddress pub s) (m (incomingAddress pub s).val),
+ .tick, .tick, .read (outgoingAddress pub s) (m (outgoingAddress pub s).val),
+ .tick, .tick, .tick, .read (carryAddress pub s) (m (carryAddress pub s).val),
+ .tick, .tick, .tick, .tick, .tick, .tick, .tick, .tick, .tick, .tick,
+ .tick, .tick, .tick, .write (carryAddress pub s) (carryWord pub s m), .tick]
+
+theorem digitEvents_counts (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) :
+ (digitEvents pub s m).length = 27 ∧ countProbes (digitEvents pub s m) = 4 ∧
+ choiceBits (digitEvents pub s m) = [] := by
+ exact ⟨rfl, rfl, rfl⟩
+
+theorem after_digitEvents (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) :
+ after m (digitEvents pub s m) = writeMemory m (carryAddress pub s) (carryWord pub s m) := rfl
+
+private theorem digit_trace_pass (pub : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (regs : Regs w 16) (ht : NativeTest pub s m) :
+ ∃ rs, trace pub s digitOps regs m = some (digitEvents pub s m, rs,
+ writeMemory m (carryAddress pub s) (carryWord pub s m)) ∧ rs 1 = s+1 := by
+ rcases ht with ⟨ha,hb,hc⟩
+ simp (config := { decide := true }) [incomingAddress, outgoingAddress, carryAddress,
+ sumWord, carryWord, lastMask, BinaryOp.eval] at ha hb hc
+ simp (config := { decide := true }) [digitOps, trace, Op.effect, Function.update,
+ BinaryOp.eval, ha, hb, hc, digitEvents, incomingAddress, outgoingAddress,
+ carryAddress, sumWord, carryWord]
+ rfl
+
+private theorem digit_trace_fail (pub : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (regs : Regs w 16) (ht : ¬NativeTest pub s m) :
+ trace pub s digitOps regs m = none := by
+ by_cases ha : m (incomingAddress pub s).val < 2
+ · by_cases hb : m (outgoingAddress pub s).val = BinaryOp.mod.eval (sumWord pub s m) 2
+ · have hc : lastMask pub s * carryWord pub s m ≠ 0 := fun e => ht ⟨ha, hb, e⟩
+ simp (config := { decide := true }) [incomingAddress, outgoingAddress, carryAddress,
+ sumWord, carryWord, lastMask, BinaryOp.eval] at ha hb hc
+ simp (config := { decide := true }) [digitOps, trace, Op.effect, Function.update,
+ BinaryOp.eval, ha, hb, hc]
+ · simp (config := { decide := true }) [incomingAddress, outgoingAddress, carryAddress,
+ sumWord, BinaryOp.eval] at ha hb
+ simp (config := { decide := true }) [digitOps, trace, Op.effect, Function.update, BinaryOp.eval, ha, hb]
+ · change ¬m (pub 0 + s).val < 2 at ha
+ simp (config := { decide := true }) [digitOps, trace, Op.effect, Function.update, BinaryOp.eval, ha]
+
+/-- The extra entry test ends the stage at cursor `t * Z`. Each prior call
+executes one copy of the same digit block and returns cursor plus one. -/
+def digitTemplate : Template 34 16 5 where
+ literalWidth := 2
+ entry := 29
+ code i := if h : i.val < digitOps.length then
+ (digitOps[i.val]).emit ⟨i.val+1, by have : digitOps.length = 27 := rfl; omega⟩ 28
+ else if i = 27 then .returnState 1
+ else if i = 29 then .stateWord 0 30
+ else if i = 30 then .publicWord 15 4 31
+ else if i = 31 then .jumpLt 0 15 0 32
+ else if i = 32 then .jumpEq 0 15 33 28
+ else if i = 33 then .accept
+ else .reject
+
+private theorem indexedContains {p r k : ℕ} (M : Machine w p r k) (bad : Fin p)
+ (ops : List (Op r k)) (pc : Fin (ops.length+1) → Fin p)
+ (hc : ∀ i : Fin ops.length, M.code (pc i.castSucc) =
+ (ops[i.val].emit (pc i.succ) bad).resize w) :
+ Contains M bad (pc 0) ops (pc (Fin.last ops.length)) := by
+ induction ops with
+ | nil => exact .nil _
+ | cons o ops ih =>
+ apply Contains.cons (next := pc (⟨0, by simp⟩ : Fin (o :: ops).length).succ) (hc ⟨0, by simp⟩)
+ exact ih (fun i => pc i.succ) (fun i => hc i.succ)
+
+private theorem contains_digit (pub : Fin 5 → Word w) :
+ Contains (digitTemplate.instantiate w pub) 28 0 digitOps 27 := by
+ apply indexedContains _ _ _ (fun i => ⟨i.val, by have := i.isLt; change _ < 28 at this; omega⟩)
+ intro i
+ simp [digitTemplate, Template.instantiate, i.isLt]
+
+/-- Native report of one successful call, including its entry instructions. -/
+def digitReport (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : Report w :=
+ ⟨.tick :: .tick :: .tick :: digitEvents pub s m, some (s+1)⟩
+
+theorem digitReport_cost (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) :
+ (digitReport pub s m).probes = 4 ∧ (digitReport pub s m).events.length = 30 ∧
+ choiceBits (digitReport pub s m).events = [] := ⟨rfl, rfl, rfl⟩
+
+theorem digitReport_after (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) :
+ after m (digitReport pub s m).events = writeMemory m (carryAddress pub s) (carryWord pub s m) := rfl
+
+private theorem execute_entry (pub : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (bs : List Bool) (f : ℕ) (hs : s < pub 4) :
+ let M := digitTemplate.instantiate w pub
+ let regs : Regs w 16 := Function.update (Function.update (fun _ => 0) 0 s) 15 (pub 4)
+ execute M.program (f+3) (M.program.start s) m bs =
+ (execute M.program f ⟨0, s, regs, fun _ => 0⟩ m bs).map
+ (fun r => r.prepend .tick |>.prepend .tick |>.prepend .tick) := by
+ dsimp only
+ simp (config := { decide := true }) [execute, Machine.program, digitTemplate, Template.instantiate,
+ Instr.resize, Instr.run, Config.put, Function.update, hs, Option.map_map, Function.comp_def]
+
+private theorem execute_block (pub : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (regs : Regs w 16) (bs : List Bool) (f : ℕ) :
+ let M := digitTemplate.instantiate w pub
+ execute M.program (f+28) ⟨0,s,regs,fun _ => 0⟩ m bs =
+ (trace pub s digitOps regs m).bind fun (es, rs, _) =>
+ if bs = [] then some ⟨es, some (rs 1)⟩ else none := by
+ dsimp only
+ have h := (contains_digit pub).execute (by rfl) s regs (fun _ => 0) m bs (f+1)
+ rw [show f+28 = f+1+digitOps.length by rfl, h, run_eq_trace]
+ congr 1
+ funext z
+ obtain ⟨es, rs, mem⟩ := z
+ change ((execute (digitTemplate.instantiate w pub).program (f+1) ⟨27,s,rs,fun _ => 0⟩ mem bs).map _) = _
+ simp (config := { decide := true }) [execute, digitTemplate, Template.instantiate, Machine.program,
+ Instr.resize, Instr.run]
+
+private theorem execute_digit (pub : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (bs : List Bool) (f : ℕ) (hs : s < pub 4) :
+ execute (digitTemplate.instantiate w pub).program (f+31)
+ ((digitTemplate.instantiate w pub).program.start s) m bs =
+ if NativeTest pub s m ∧ bs = [] then some (digitReport pub s m) else none := by
+ classical
+ rw [show f+31 = (f+28)+3 by omega, execute_entry pub s m bs _ hs, execute_block]
+ by_cases ht : NativeTest pub s m
+ · obtain ⟨rs, hr, hv⟩ := digit_trace_pass pub s m (Function.update (Function.update (fun _ => 0) 0 s) 15 (pub 4)) ht
+ simp only [hr, Option.bind_some, hv, ht, true_and]
+ by_cases hb : bs = [] <;> simp [hb, digitReport, Report.prepend]
+ · simp [digit_trace_fail pub s m _ ht, ht]
+
+/-- The completed stage accepts with exactly four entry ticks and no choices. -/
+theorem execute_done (pub : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (bs : List Bool) (f : ℕ) (hs : s = pub 4) :
+ execute (digitTemplate.instantiate w pub).program (f+5)
+ ((digitTemplate.instantiate w pub).program.start s) m bs =
+ if bs = [] then some ⟨[.tick, .tick, .tick, .tick], none⟩ else none := by
+ subst s
+ simp (config := { decide := true }) [execute, Machine.program, digitTemplate, Template.instantiate,
+ Instr.resize, Instr.run, Config.put, Function.update]
+ split <;> simp [Report.prepend]
+
+/-- Ordinary integer addition, phrased using the natural values of the cells
+read by one call. The final bit of each label also checks for overflow. -/
+def DigitTest (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : Prop :=
+ let x := (m (incomingAddress pub s).val).val
+ let y := (m (outgoingAddress pub s).val).val
+ let c := (m (carryAddress pub s).val).val
+ x < 2 ∧ y = (c+x)%2 ∧ (s.val % (pub 3).val + 1 = (pub 3).val → (c+x)/2 = 0)
+
+private instance (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : Decidable (DigitTest pub s m) := by
+ unfold DigitTest
+ infer_instance
+
+private theorem val_div (x y : Word w) : (BinaryOp.div.eval x y).val = x.val / y.val :=
+ Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.div_le_self ..) x.isLt)
+
+private theorem val_mod (x y : Word w) : (BinaryOp.mod.eval x y).val = x.val % y.val :=
+ Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.mod_le ..) x.isLt)
+
+private theorem two_val (hw : 2 ≤ w) : (2 : Word w).val = 2 :=
+ Nat.mod_eq_of_lt (lt_of_lt_of_le (show 2 < 2^2 by decide) (Nat.pow_le_pow_right (by decide) hw))
+
+private theorem lastMask_val (pub : Fin 5 → Word w) (s : Word w) (hz : 0 < (pub 3).val) :
+ (lastMask pub s).val = if s.val % (pub 3).val + 1 = (pub 3).val then 1 else 0 := by
+ have hj := Nat.mod_lt s.val hz
+ have hf : s.val % (pub 3).val + 1 < 2^w := (Nat.succ_le_of_lt hj).trans_lt (pub 3).isLt
+ rw [lastMask, val_div]
+ change ((BinaryOp.mod.eval s (pub 3)) + 1 : Word w).val / (pub 3).val = _
+ rw [Fin.val_add_one_of_lt', val_mod]
+ · split
+ · rename_i he
+ rw [he, Nat.div_self hz]
+ · rename_i hn
+ exact Nat.div_eq_of_lt (by omega)
+ · rw [val_mod]
+ exact hf
+
+theorem carryWord_val (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) (hw : 2 ≤ w)
+ (hfit : (m (carryAddress pub s).val).val + (m (incomingAddress pub s).val).val < 2^w) :
+ (carryWord pub s m).val =
+ ((m (carryAddress pub s).val).val + (m (incomingAddress pub s).val).val) / 2 := by
+ rw [carryWord, val_div, two_val hw, sumWord, Fin.val_add, Nat.mod_eq_of_lt hfit]
+
+private theorem nativeTest_iff (pub : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (hw : 2 ≤ w) (hz : 0 < (pub 3).val)
+ (hfit : (m (carryAddress pub s).val).val + (m (incomingAddress pub s).val).val < 2^w) :
+ NativeTest pub s m ↔ DigitTest pub s m := by
+ have hc := carryWord_val pub s m hw hfit
+ have hmask := lastMask_val pub s hz
+ have ho : (BinaryOp.mod.eval (sumWord pub s m) 2).val =
+ ((m (carryAddress pub s).val).val + (m (incomingAddress pub s).val).val) % 2 := by
+ rw [val_mod, two_val hw, sumWord, Fin.val_add, Nat.mod_eq_of_lt hfit]
+ unfold NativeTest DigitTest
+ rw [Fin.lt_def, two_val hw, Fin.ext_iff, ho]
+ by_cases he : s.val % (pub 3).val + 1 = (pub 3).val
+ · have one_val : (1 : Word w).val = 1 :=
+ Nat.mod_eq_of_lt (lt_of_lt_of_le (by decide : 1 < 2^2) (Nat.pow_le_pow_right (by decide) hw))
+ have hm : lastMask pub s = 1 := Fin.ext (by rw [one_val]; simpa only [he, ite_true] using hmask)
+ rw [hm, one_mul, Fin.ext_iff, hc]
+ simp [he]
+ · have hm : lastMask pub s = 0 := Fin.ext (by simpa [he] using hmask)
+ simp [hm, he]
+
+/-- Every well-sized nonterminal call has exactly the branch stream and report
+specified by the arithmetic test. The fuel bound counts the final return. -/
+theorem execute_digit_iff (pub : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (hw : 2 ≤ w) (hz : 0 < (pub 3).val) (hs : s < pub 4)
+ (hfit : (m (carryAddress pub s).val).val + (m (incomingAddress pub s).val).val < 2^w)
+ (bs : List Bool) (f : ℕ) :
+ execute (digitTemplate.instantiate w pub).program (f+31)
+ ((digitTemplate.instantiate w pub).program.start s) m bs =
+ if DigitTest pub s m ∧ bs = [] then some (digitReport pub s m) else none := by
+ rw [execute_digit pub s m bs f hs]
+ by_cases h : DigitTest pub s m
+ · simp [(nativeTest_iff pub s m hw hz hfit).mpr h, h]
+ · simp [mt (nativeTest_iff pub s m hw hz hfit).mp h, h]
+
+/-- Every successful nonterminal call consumes an empty choice stream and
+returns the next cursor, including on arbitrary initial memory. -/
+theorem data_result {pub : Fin 5 → Word w} {s : Word w} {m : Memory w}
+ {bs : List Bool} {f : ℕ} {r : Report w} (hs : s < pub 4)
+ (hr : execute (digitTemplate.instantiate w pub).program (f+31)
+ ((digitTemplate.instantiate w pub).program.start s) m bs = some r) :
+ bs = [] ∧ r = digitReport pub s m := by
+ rw [execute_digit pub s m bs f hs] at hr
+ split at hr
+ · rename_i h
+ exact ⟨h.2, (Option.some.inj hr).symm⟩
+ · contradiction
+
+end LiveExponent
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveExponentRows.lean b/lean/OAI/Computability/VPVNP/LiveExponentRows.lean
new file mode 100644
index 0000000000..673235c326
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveExponentRows.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.LiveExponentBuffers
+
+/-!
+# The complete first-half exponent phase
+
+After the chosen pair path has supplied all grammar and gadget increments,
+the deterministic stage scans the labels in address order. It succeeds
+exactly when the outgoing cut contains their sum with the incoming cut.
+There is one terminal call and one constant-probe call per encoded bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveExponent
+
+open BurstRAM
+open scoped Classical
+
+variable {w t Z : ℕ}
+
+/-- Clearing the consumed increment words in address order. -/
+def clearCounters (pub : Fin 5 → Word w) (rows : List (Fin t)) (m : Memory w) : Memory w :=
+ rows.foldl (fun mem a => writeMemory mem (counterAddr pub a) 0) m
+
+/-- Exact report sequence of all data calls. -/
+def rowsReports (pub : Fin 5 → Word w) (Z : ℕ) : List (Fin t) → Memory w → List (Report w)
+ | [], _ => []
+ | a :: rest, m => rowReports pub Z (a.val*Z) m ++
+ rowsReports pub Z rest (writeMemory m (counterAddr pub a) 0)
+
+private theorem run_rows_aux {pub : Fin 5 → Word w} (L : BufferLayout pub t Z) (hZ : 0 < Z) (hw : 2 ≤ w)
+ {x y : Fin t → Word Z} (inc : Fin t → Word w) (hc : ∀ i, (inc i).val+1 < 2^w)
+ (bits : Fin t → List (List Bool)) (hwidth : ∀ i, (bits i).length = Z) (f : ℕ)
+ (rows : List (Fin t)) (start : ℕ) (m : Memory w) (v : BufferValues pub x y m)
+ (hmap : rows.map Fin.val = List.range' start rows.length) (huniq : rows.Nodup)
+ (hi : ∀ a ∈ rows, m (counterAddr pub a).val = inc a) (tail : List (List Bool)) :
+ let P := (digitTemplate.instantiate w pub).program
+ runSegment P (f+31) (some (atPos (start*Z))) m (rows.flatMap bits ++ tail) =
+ if ∀ a ∈ rows, (y a).val = (x a).val+(inc a).val ∧ bits a = List.replicate Z [] then
+ (runSegment P (f+31) (some (atPos ((start+rows.length)*Z))) (clearCounters pub rows m)
+ tail).map (rowsReports pub Z rows m ++ ·)
+ else none := by
+ dsimp only
+ induction rows generalizing start m with
+ | nil => simp [clearCounters, rowsReports]
+ | cons a rows ih =>
+ simp only [List.map_cons, List.length_cons, List.range'_succ, List.cons.injEq] at hmap
+ obtain ⟨rfl, hmap⟩ := hmap
+ obtain ⟨hnot, hn⟩ := List.nodup_cons.mp huniq
+ have haddr := hi a (List.mem_cons_self ..)
+ let m' := writeMemory m (counterAddr pub a) 0
+ have hh : ∀ b ∈ rows, m' (counterAddr pub b).val = inc b := by
+ intro b hb
+ have hne : (counterAddr pub b).val ≠ (counterAddr pub a).val := by
+ intro e
+ exact hnot ((counterAddr_injective L hZ (Fin.ext e)) ▸ hb)
+ change writeMemory m (counterAddr pub a) 0 (counterAddr pub b).val = inc b
+ rw [writeMemory, ite_eq_right hne]
+ exact hi b (List.mem_cons_of_mem _ hb)
+ have hrow := run_wordRow L hZ hw v a (haddr ▸ hc a) (bits a) (hwidth a)
+ (rows.flatMap bits ++ tail) f
+ rw [List.flatMap_cons, List.append_assoc, hrow, haddr]
+ have htail := ih (a.val+1) m' (v.write_counter L a 0) hmap hn hh
+ simp only [List.forall_mem_cons]
+ by_cases hgood : (y a).val = (x a).val+(inc a).val ∧ bits a = List.replicate Z []
+ · rw [ite_eq_left hgood]
+ rw [htail]
+ simp only [hgood, true_and]
+ by_cases ht : ∀ b ∈ rows, (y b).val = (x b).val+(inc b).val ∧ bits b = List.replicate Z []
+ · rw [ite_eq_left ht, ite_eq_left ht, Option.map_map]
+ have he : a.val+(a::rows).length = a.val+1+rows.length := by simp; omega
+ rw [he]
+ simp [Function.comp_def, rowsReports, clearCounters, m', List.append_assoc]
+ · simp [ht]
+ · simp [hgood]
+
+/-- Exact native execution of all data calls, with any succeeding call sequence.
+The first stage cursor is zero and the final one equals the total digit count. -/
+theorem run_rows {pub : Fin 5 → Word w} (L : BufferLayout pub t Z) (hZ : 0 < Z) (hw : 2 ≤ w)
+ {x y : Fin t → Word Z} {m : Memory w} (v : BufferValues pub x y m)
+ (inc : Fin t → Word w) (hi : ∀ a, m (counterAddr pub a).val = inc a)
+ (hc : ∀ a, (inc a).val+1 < 2^w) (bits : Fin t → List (List Bool))
+ (hwidth : ∀ a, (bits a).length = Z) (tail : List (List Bool)) (f : ℕ) :
+ let P := (digitTemplate.instantiate w pub).program
+ runSegment P (f+31) (some 0) m ((List.finRange t).flatMap bits ++ tail) =
+ if ∀ a, (y a).val = (x a).val+(inc a).val ∧ bits a = List.replicate Z [] then
+ (runSegment P (f+31) (some (pub 4)) (clearCounters pub (List.finRange t) m)
+ tail).map (rowsReports pub Z (List.finRange t) m ++ ·)
+ else none := by
+ have hmap : (List.finRange t).map Fin.val = List.range' 0 (List.finRange t).length := by
+ apply List.ext_getElem (by simp)
+ intro i hi hi'
+ simp
+ have he := run_rows_aux L hZ hw inc hc bits hwidth f (List.finRange t) 0 m v hmap
+ (List.nodup_finRange t) (fun a _ => hi a) tail
+ have hlast : atPos (w := w) (t*Z) = pub 4 := Fin.ext (by rw [← L.size]; exact Nat.mod_eq_of_lt (pub 4).isLt)
+ simp only [List.length_finRange, Nat.zero_add] at he
+ rw [hlast] at he
+ simpa using he
+
+/-- All data calls followed by the unique accepting end call. -/
+theorem run_stage {pub : Fin 5 → Word w} (L : BufferLayout pub t Z) (hZ : 0 < Z) (hw : 2 ≤ w)
+ {x y : Fin t → Word Z} {m : Memory w} (v : BufferValues pub x y m)
+ (inc : Fin t → Word w) (hi : ∀ a, m (counterAddr pub a).val = inc a)
+ (hc : ∀ a, (inc a).val+1 < 2^w) (bits : Fin t → List (List Bool))
+ (hwidth : ∀ a, (bits a).length = Z) (last : List Bool) (f : ℕ) :
+ let P := (digitTemplate.instantiate w pub).program
+ runSegment P (f+31) (some 0) m ((List.finRange t).flatMap bits ++ [last]) =
+ if (∀ a, (y a).val = (x a).val+(inc a).val ∧ bits a = List.replicate Z []) ∧ last = [] then
+ some (rowsReports pub Z (List.finRange t) m ++ [⟨[.tick,.tick,.tick,.tick],none⟩])
+ else none := by
+ dsimp only
+ rw [run_rows L hZ hw v inc hi hc bits hwidth [last] f]
+ by_cases hs : ∀ a, (y a).val = (x a).val+(inc a).val ∧ bits a = List.replicate Z []
+ · rw [ite_eq_left hs]
+ simp only [runSegment]
+ rw [show f+31 = (f+26)+5 by omega, execute_done pub (pub 4) _ last (f+26) rfl]
+ by_cases hl : last = []
+ · rw [ite_eq_left hl, ite_eq_left ⟨hs,hl⟩]
+ rfl
+ · rw [ite_eq_right hl, ite_eq_right (fun h => hl h.2)]
+ rfl
+ · simp [hs]
+
+end LiveExponent
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveExponentSweep.lean b/lean/OAI/Computability/VPVNP/LiveExponentSweep.lean
new file mode 100644
index 0000000000..a060f6e4be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveExponentSweep.lean
@@ -0,0 +1,186 @@
+import OAI.Computability.VPVNP.LiveExponentRAM
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+
+/-!
+# Executing a row of the first-half exponent check
+
+Each digit runs in a fresh private workspace. The only shared cell changed
+by an entire row is that label's increment word. Its final value on success
+is zero. The input and output bit buffers may be read at any disjoint
+addresses computed by the stage.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveExponent
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Classical
+
+variable {w : ℕ}
+
+/-- Convert a natural exponent-sweep cursor to its persistent machine word. -/
+abbrev atPos (p : ℕ) : Word w := Fin.ofNat _ p
+
+private theorem atPos_val {p : ℕ} (h : p < 2^w) : (atPos (w := w) p).val = p :=
+ Nat.mod_eq_of_lt h
+
+private theorem atPos_succ (p : ℕ) : atPos (w := w) (p+1) = atPos p + 1 := by
+ apply Fin.ext
+ exact Nat.add_mod p 1 (2^w)
+
+/-- The read-only and writable cells used by a nonempty suffix of one row.
+The final digit test is taken exactly at the end of the row. -/
+structure RowCells (pub : Fin 5 → Word w) (addr : Word w) (p : ℕ)
+ (ds : List (Bool × Bool)) (m : Memory w) : Prop where
+ fits : p + ds.length ≤ (pub 4).val
+ cells : ∀ i (hi : i < ds.length),
+ let s := atPos (w := w) (p+i)
+ carryAddress pub s = addr ∧ incomingAddress pub s ≠ addr ∧ outgoingAddress pub s ≠ addr ∧
+ (m (incomingAddress pub s).val).val = ds[i].1.toNat ∧
+ (m (outgoingAddress pub s).val).val = ds[i].2.toNat ∧
+ ((p+i) % (pub 3).val + 1 = (pub 3).val ↔ i+1 = ds.length)
+
+private theorem RowCells.tail {pub : Fin 5 → Word w} {addr : Word w} {p : ℕ}
+ {d : Bool × Bool} {ds : List (Bool × Bool)} {m : Memory w}
+ (h : RowCells pub addr p (d::ds) m) (v : Word w) :
+ RowCells pub addr (p+1) ds (writeMemory m addr v) := by
+ constructor
+ · simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using h.fits
+ · intro i hi
+ obtain ⟨ha, hb, hc, hx, hy, he⟩ := h.cells (i+1) (by simpa using hi)
+ have ep : p+1+i = p+(i+1) := by omega
+ rw [ep]
+ refine ⟨ha,hb,hc,?_,?_,?_⟩
+ · rw [writeMemory, ite_eq_right (fun e => hb (Fin.ext e))]
+ exact hx
+ · rw [writeMemory, ite_eq_right (fun e => hc (Fin.ext e))]
+ exact hy
+ · simpa using he
+
+/-- Expected digit reports, even if a check would stop the actual run.
+They determine the only possible complete transcript. -/
+def rowReports (pub : Fin 5 → Word w) : ℕ → ℕ → Memory w → List (Report w)
+ | 0, _, _ => []
+ | n+1, p, m =>
+ let r := digitReport pub (atPos p) m
+ r :: rowReports pub n (p+1) (after m r.events)
+
+private theorem bool_le (b : Bool) : b.toNat ≤ 1 := by cases b <;> decide
+
+private theorem carry_head {pub : Fin 5 → Word w} {addr : Word w} {p : ℕ}
+ {d : Bool × Bool} {ds : List (Bool × Bool)} {m : Memory w}
+ (h : RowCells pub addr p (d :: ds) m) (hw : 2 ≤ w) (hc : (m addr.val).val + 1 < 2^w) :
+ let r := digitReport pub (atPos p) m
+ let next := after m r.events
+ (next addr.val).val = total (m addr.val).val d.1 / 2 ∧
+ RowCells pub addr (p+1) ds next ∧ (next addr.val).val+1 < 2^w := by
+ dsimp only
+ obtain ⟨ha, _, _, hx, _, _⟩ := h.cells 0 (by simp)
+ simp only [Nat.add_zero, List.getElem_cons_zero] at ha hx
+ rw [digitReport_after, ha]
+ have hb := bool_le d.1
+ have hfit : (m (carryAddress pub (atPos p)).val).val +
+ (m (incomingAddress pub (atPos p)).val).val < 2^w := by rw [ha, hx]; omega
+ have hv := carryWord_val pub (atPos p) m hw hfit
+ rw [ha, hx] at hv
+ refine ⟨by simpa [writeMemory,total] using hv, h.tail _, ?_⟩
+ rw [writeMemory, ite_eq_left rfl, hv]
+ omega
+
+/-- Execute the digit calls of one row with any continuation. An incorrect
+output bit, overflow, or any extra binary choice rejects the call sequence. -/
+theorem run_row {pub : Fin 5 → Word w} {addr : Word w} {p : ℕ} {ds : List (Bool × Bool)}
+ {m : Memory w} (hw : 2 ≤ w) (hz : 0 < (pub 3).val) (h : RowCells pub addr p ds m)
+ (hc : (m addr.val).val + 1 < 2^w) (hne : ds ≠ [])
+ (bits : List (List Bool)) (hlen : bits.length = ds.length) (tail : List (List Bool)) (f : ℕ) :
+ let P := (digitTemplate.instantiate w pub).program
+ runSegment P (f+31) (some (atPos p)) m (bits ++ tail) =
+ if Checks (m addr.val).val (ds.map Prod.fst) (ds.map Prod.snd) ∧ bits = List.replicate ds.length [] then
+ (runSegment P (f+31) (some (atPos (p+ds.length))) (writeMemory m addr 0) tail).map
+ (rowReports pub ds.length p m ++ ·)
+ else none := by
+ classical
+ dsimp only
+ induction ds generalizing p m bits with
+ | nil => contradiction
+ | cons d ds ih =>
+ cases bits with
+ | nil => simp at hlen
+ | cons b bits =>
+ simp only [List.length_cons, Nat.add_right_cancel_iff] at hlen
+ let s := atPos (w := w) p
+ let r := digitReport pub s m
+ let m' := after m r.events
+ obtain ⟨ha, _, _, hx, hy, he⟩ := h.cells 0 (by simp)
+ simp only [Nat.add_zero, List.getElem_cons_zero, List.length_cons] at ha hx hy he
+ change carryAddress pub s = addr at ha
+ change (m (incomingAddress pub s).val).val = d.1.toNat at hx
+ change (m (outgoingAddress pub s).val).val = d.2.toNat at hy
+ have hp : p < (pub 4).val := by have := h.fits; simp only [List.length_cons] at this; omega
+ have hsp : s.val = p := atPos_val (hp.trans (pub 4).isLt)
+ have hs : s < pub 4 := by simpa only [Fin.lt_def, hsp] using hp
+ have hd := bool_le d.1
+ have hfit : (m (carryAddress pub s).val).val + (m (incomingAddress pub s).val).val < 2^w := by
+ rw [ha, hx]; omega
+ have htest : DigitTest pub s m ↔
+ d.2.toNat = total (m addr.val).val d.1 % 2 ∧ (ds = [] → total (m addr.val).val d.1 / 2 = 0) := by
+ have he' : p % (pub 3).val + 1 = (pub 3).val ↔ ds = [] := he.trans (by simp)
+ rw [DigitTest, ha, hx, hy, hsp, he', total]
+ exact and_iff_right (by omega)
+ have hmem := carry_head h hw hc
+ change (m' addr.val).val = _ ∧ RowCells _ _ _ _ m' ∧ _ at hmem
+ have hret : r.result = some (atPos (w := w) (p+1)) := congrArg some (atPos_succ p).symm
+ rw [List.cons_append, runSegment, execute_digit_iff pub (atPos p) m hw hz hs hfit]
+ change (match (if DigitTest pub s m ∧ b = [] then some r else none) with
+ | none => none
+ | some rep => (runSegment (digitTemplate.instantiate w pub).program (f+31)
+ rep.result (after m rep.events) (bits ++ tail)).map (rep :: ·)) = _
+ simp only [List.map_cons, Checks, List.length_cons, List.replicate_succ, List.cons.injEq]
+ by_cases hb : b = []
+ · by_cases hdigit : d.2.toNat = total (m addr.val).val d.1 % 2
+ · cases ds with
+ | nil =>
+ have hb0 : bits = [] := List.length_eq_zero_iff.mp (by simpa using hlen)
+ subst bits
+ by_cases hc0 : total (m addr.val).val d.1 / 2 = 0
+ · have ht := htest.mpr ⟨hdigit, fun _ => hc0⟩
+ have hm0 : m' = writeMemory m addr 0 := by
+ change after m (digitReport pub s m).events = _
+ rw [digitReport_after, ha]
+ congr 1
+ apply Fin.ext
+ have eqv := hmem.1.trans hc0
+ change (after m (digitReport pub s m).events addr.val).val = 0 at eqv
+ rw [digitReport_after, ha, writeMemory, ite_eq_left rfl] at eqv
+ exact eqv
+ simp only [ht, hdigit, hc0, hb, true_and, and_true, ite_true, Checks, List.map_nil,
+ List.nil_append]
+ rw [hret, show after m r.events = _ from hm0]
+ rfl
+ · have hn : ¬DigitTest pub s m := fun ht => hc0 ((htest.mp ht).2 rfl)
+ simp [hn, hc0, Checks]
+ | cons e es =>
+ have ht := htest.mpr ⟨hdigit, by simp⟩
+ have hh := ih hmem.2.1 hmem.2.2 (by simp) bits hlen
+ have hm0 : writeMemory m' addr 0 = writeMemory m addr 0 := by
+ change writeMemory (after m (digitReport pub s m).events) addr 0 = _
+ rw [digitReport_after, ha]
+ funext i
+ by_cases hi : i = addr.val <;> simp [writeMemory, hi]
+ simp only [ht, hb, hdigit, true_and, ite_true]
+ rw [hret, show after m r.events = m' from rfl, hh, hm0, hmem.1]
+ have ep : p+((e::es).length+1) = p+1+(e::es).length := by omega
+ rw [ep]
+ split <;> simp [rowReports, Option.map_map, Function.comp_def, r, s, m']
+ · have hn : ¬DigitTest pub s m := fun ht => hdigit (htest.mp ht).1
+ simp [hn, hdigit]
+ · simp [hb]
+
+end LiveExponent
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveFirstTailBudget.lean b/lean/OAI/Computability/VPVNP/LiveFirstTailBudget.lean
new file mode 100644
index 0000000000..584a2c9a38
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveFirstTailBudget.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.LiveOutsideTailCount
+import OAI.Computability.VPVNP.LiveOutsideAllCaps
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorGeometry
+import OAI.Computability.VPVNP.LiveProgramHeader
+
+/-!
+# The transcript budget of the initialized first tail group
+
+The first nonempty evaluator group executes the header, both routers, the
+initial state writer, the packing and input stages, and one terminal
+transition. The outgoing gather allowance also pays for the last sentinel
+when this is the only tail group. The common outside-work bound therefore
+provides the budget for every accepting continuation from the midpoint.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.FirstTailBudget
+
+open PairStages LiveEvaluatorTailCost OutsideTailStages OutsideTailCount
+open Filter CursorBounds CursorNetwork
+
+/-- The specific amount charged by the post-initialization count theorem,
+including the header and mode router. -/
+def cost (G : Group) (raw : ℕ) : ℕ :=
+ LiveHeaderSchedule.costBound (Header.sizes G.constants G.g)+4+8+
+ packWork (params G raw)+inputWork (params G raw)+
+ routeCost G.w (EvaluatorRoutes.radius G)+transitionCost (EvaluatorRoutes.radius G)
+
+private theorem group_cost (u : Parameters) :
+ 8+packWork u+inputWork u+routeCost u.wordWidth u.radius+transitionCost u.radius ≤
+ groupBound u true false false := by
+ have hwords : LiveEvaluatorEncoding.fieldWords u.radius = u.configWords := by
+ unfold LiveEvaluatorEncoding.fieldWords Parameters.configWords; omega
+ have hroute : routeCost u.wordWidth u.radius = 4+(u.wordWidth+4)*u.configWords := by
+ rw [routeCost, hwords, Nat.mul_comm]
+ have htrans : transitionCost u.radius = u.transitionCost+u.configWords := by
+ unfold transitionCost Parameters.transitionCost Parameters.configWords LiveEvaluatorRAM.Schedule.calls
+ omega
+ rw [hroute, htrans, ← groupBudget]
+ simp only [firstBudget, lastBudget, ite_true, Bool.false_eq_true, ite_false]
+ omega
+
+/-- The physical route budget is covered by the common outside-work bound
+with the ordinary outgoing-gather allowance. -/
+theorem cost_le_actualBound (G : Group) (raw : ℕ) :
+ cost G raw ≤ OutsideBudget.actualBound G.constants G.g raw true false false := by
+ have h := group_cost (params G raw)
+ change 8 + packWork (params G raw) + inputWork (params G raw) +
+ routeCost G.w (EvaluatorRoutes.radius G) + transitionCost (EvaluatorRoutes.radius G) ≤ _ at h
+ unfold cost OutsideBudget.actualBound
+ dsimp only
+ change LiveHeaderSchedule.costBound (Header.sizes G.constants G.g)+4+8+
+ packWork (params G raw)+inputWork (params G raw)+routeCost G.w (EvaluatorRoutes.radius G)+
+ transitionCost (EvaluatorRoutes.radius G) ≤ LiveHeaderSchedule.costBound (Header.sizes G.constants G.g)+
+ 8+4*(G.constants.labels.eval G.g+1)+100+16*(OutsideBudget.auxWords (Header.sizes G.constants G.g)
+ (G.constants.labels.eval G.g)+1)+7*(G.constants.labels.eval G.g*G.constants.Z.eval G.g+1)+
+ groupBound (params G raw) true false false
+ omega
+
+/-- The site exponent is chosen before the length threshold. For every
+bounded advice prefix, the ordinary per-call cap and the full initialized
+group budget then hold simultaneously. -/
+theorem eventually_countCaps {C : ℕ} (u : PairExponents C) (c : Constants) (E : UniversalMachine.Program) :
+ ∃ B₀, ∀ B ≥ B₀, ∀ᶠ n : ℕ in atTop, ∀ G : Group,
+ G.g = paperGeometry B (liveCapacity u) n → G.constants = c → G.evaluator = E →
+ ∀ raw, raw ≤ G.constants.prefixCapacity.eval G.g →
+ cost G raw ≤ processorCount B n*G.g.H ∧ OutsideTailStages.callBound G.w ≤ G.g.H := by
+ obtain ⟨B₀, h⟩ := OutsideTraces.eventually_all_caps u c E
+ refine ⟨B₀, fun B hB => ?_⟩
+ filter_upwards [h B hB] with n hn G hg hc he raw hraw
+ obtain ⟨hcost, hcap, _⟩ := hn G hg hc he raw true false false hraw
+ have hpos : 0 < G.g.H := (by decide : 0 < 26).trans_le ((le_max_left ..).trans hcap)
+ exact ⟨(cost_le_actualBound G raw).trans (hcost.le.trans (Nat.le_mul_of_pos_right _ hpos)),
+ (le_max_right ..).trans hcap⟩
+
+end LiveProgram.FirstTailBudget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveFirstTailCount.lean b/lean/OAI/Computability/VPVNP/LiveFirstTailCount.lean
new file mode 100644
index 0000000000..bfb001353b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveFirstTailCount.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.LiveFirstTailOutput
+import OAI.Computability.VPVNP.LiveOutsideTailCount
+
+/-!
+# Counting the first evaluator transition after midpoint initialization
+
+The first router writes the initial control word. The deterministic midpoint
+preparation returns at the last router. Removing both prefixes from the
+accepting paths retains their actual reports in the bucket cap.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM PairStages LiveEvaluatorEncoding LiveEvaluatorRAM
+open OutsideTraces OutsideTailStages OutsideTailCount
+open scoped Fin.CommRing
+
+variable (G : Group)
+
+/-- Count after the native preparation, charging every initialization burst
+to the same global cap as the eventual transition. -/
+theorem countAfterInitialization {S H h Δ M n cost preCost : ℕ}
+ (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w Δ)
+ (init : Code G.evaluator.extra M) (bits : LiveChain.TailBits h Δ)
+ (i : Fin (2^h)) (first : i.val = 0) (m final : Memory G.w)
+ (fit : GeometryFit G M) (start : G.tagged Stage.firstTail m)
+ (flag : m ((Router.firstTail.data G.g G.lit) 0).val = 1)
+ (run : Advice.Returning G.P G.clock n 22 (putMemory G false m) final)
+ (work : Advice.CostLimit G.P G.clock n (putMemory G false m) cost)
+ (config : ConfigAt final (G.transitionPub 1) init) (tag : G.tagged Stage.last final)
+ (o : Output G final (LiveEvaluatorTail.boundary layout init bits i.succ))
+ (pre : List (Report G.w)) (hr : Resources pre preCost 11 G.clock)
+ (hcall : callBound G.w ≤ H)
+ (budget : preCost+8+cost+routeCost G.w M+transitionCost M ≤ S*H) :
+ Nat.card (ActualPaths G.P G.clock 0 m (fun rs => withinCaps S H (pre++rs))) =
+ ChainAssignments.tailCount G.evaluator layout init bits i := by
+ obtain ⟨rs,exec,ends,mem,_,bound⟩ := run
+ have hres : Resources rs cost 23 G.clock :=
+ ⟨work _ exec, fun r h => by have := (bound r h).1; omega,
+ fun r h => by have := (bound r h).2; omega⟩
+ have old (c : Code G.evaluator.extra M) : LiveEvaluatorTail.boundary layout init bits i.castSucc = some c ↔
+ ConfigAt final (G.transitionPub 1) c := by
+ have hz : i.castSucc = 0 := Fin.ext first
+ rw [hz,LiveEvaluatorTail.boundary_zero,Option.some.injEq,eq_comm]
+ exact (configAt_eq_iff G fit.prep.width fit.prep.states config c).symm
+ have allRes := (hr.append (putRoute G false)).append hres
+ have counted := lastCount_capped G layout init bits i final fit tag old o _ allRes
+ (by unfold callBound at hcall ⊢; omega) budget
+ have hclk := fit.gatherClock
+ rw [Nat.card_congr (putHandoff G false fit.prep.width (by omega) m start flag _).symm]
+ let cap := fun xs => withinCaps S H (pre++(putLogs G false++xs))
+ have e := emptySegmentEquiv exec cap
+ rw [ends,mem] at e
+ rw [Nat.card_congr e.symm]
+ simpa only [cap,List.append_assoc] using counted
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveFirstTailHeader.lean b/lean/OAI/Computability/VPVNP/LiveFirstTailHeader.lean
new file mode 100644
index 0000000000..19c038b8d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveFirstTailHeader.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.LiveHeaderOutputFrame
+import OAI.Computability.VPVNP.LiveProgramHeader
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorGeometry
+import OAI.Computability.VPVNP.LiveProgramAdviceInputLayout
+
+/-!
+# The first evaluator group after the initial-state write
+
+At the midpoint the incoming cut still uses the pair format. The first
+tail group therefore receives the accumulated exponents and the copied
+advice in their physical header arrays. The router and the state writer
+touch only the stage tag and old control word, leaving every old tape cell
+blank and both input arrays intact for the advice and input sweeps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.FirstTailHeader
+
+open BurstRAM LiveEvaluatorInitialize LiveEvaluatorEncoding PairStages
+open LiveHeaderProgram LiveHeaderSchedule LiveHeader LiveHeaderDescriptors
+open ChainAssignments CutSchedule ExponentTrace
+open scoped Fin.CommRing
+
+variable (G : Group)
+
+/-- The header dimensions evaluated at the physical group's constants and geometry. -/
+abbrev size := Header.sizes G.constants G.g
+/-- The group's evaluated number of exponent labels. -/
+abbrev labelCount := G.constants.labels.eval G.g
+/-- The group's evaluated digit width for each exponent. -/
+abbrev exponentWidth := G.constants.Z.eval G.g
+/-- The physical group index of the first evaluator group, at the start of the second half. -/
+abbrev middle (G : Group) : Fin (2^((size G).h+1)) := halves (size G).h (.inr 0)
+
+/-- The typed exponent field of the same midpoint cut used in
+`groupEvaluation` and in the evaluator's initial code. -/
+abbrev middleWords (cuts : AllCuts (size G).h (size G).delta)
+ (fit : 1+labelCount G*exponentWidth G ≤ (size G).delta) :=
+ counters fit (liveCutEquiv (size G).h (size G).delta cuts).1 (Fin.last (2^(size G).h))
+
+variable {hw : 4 ≤ G.w} {m : Memory G.w}
+variable {advice : Bits (size G).advice} {cuts : AllCuts (size G).h (size G).delta}
+
+/-- The physical input bank is precisely the last vector of first-half
+counters, including the low-endian order of the bits within each label. -/
+theorem middle_bits (out : Output (size G) (Header.base G.g) G.g.d hw advice cuts (middle G) .tail m)
+ (fit : 1+labelCount G*exponentWidth G ≤ (size G).delta) :
+ ∀ q : Fin (labelCount G*exponentWidth G),
+ m ((HeaderLayout.exponent G.constants.lengths Layout.header .left).eval G.g+q.val) =
+ PrimedInputRAM.encodeBit G.w (RAMSerialization.arrayBits _ _ (middleWords G cuts fit) q) := by
+ let s := size G
+ let k : Fin (2^s.h) := ⟨2^s.h-1, by have := Nat.two_pow_pos s.h; omega⟩
+ have hsucc : k.succ = Fin.last (2^s.h) := Fin.ext (by
+ change (2^s.h-1)+1 = 2^s.h; have := Nat.two_pow_pos s.h; omega)
+ have cut : incidentCut .left (middle G) = firstCut k := by
+ apply Fin.ext
+ change 2^s.h+(0 : Fin (2^s.h)).val = (2^s.h-1)+1
+ rw [Fin.val_zero]
+ have := Nat.two_pow_pos s.h
+ omega
+ have pos : 0 < (incidentCut .left (middle G)).val := by rw [cut]; exact Nat.succ_pos _
+ have half : (incidentCut .left (middle G)).val ≤ 2^s.h := by rw [cut]; exact k.isLt
+ have fields (j : Fin (2^(s.h+1)+1)) (hj : j = firstCut k) (lo : 0 < j.val) (hi : j.val ≤ 2^s.h) :
+ (firstHalfLayout s.h s.delta j.val (labelCount G) (exponentWidth G) lo hi fit (cuts j)).2.2.1 =
+ counters fit (liveCutEquiv s.h s.delta cuts).1 k.succ := by subst j; rfl
+ obtain ⟨_, _, img⟩ := out.fieldImage
+ have stored := img.pair_exponents (by decide) .left
+ (rfl : s.e = labelCount G*exponentWidth G) fit pos half
+ rw [fields _ cut pos half, hsucc] at stored
+ intro q
+ obtain ⟨⟨i, b⟩, rfl⟩ := finProdFinEquiv.surjective q
+ rw [RAMSerialization.arrayBits_at]
+ have atBit := stored i b
+ have hq : (finProdFinEquiv (i,b)).val = i.val*exponentWidth G+b.val := by
+ simp [finProdFinEquiv, Nat.mul_comm, Nat.add_comm]
+ rw [hq]
+ exact atBit
+
+/-- After the nonempty evaluator's first state write, all arrays consumed
+by the packing and input stages are in their concrete program locations. -/
+theorem prepared (out : Output (size G) (Header.base G.g) G.g.d hw advice cuts (middle G) .tail m)
+ (fit : 1+labelCount G*exponentWidth G ≤ (size G).delta)
+ (hlimit : (Layout.shadow G.constants).eval G.g < 2^G.w) (running : G.evaluator.extra ≠ 0) :
+ let result := EvaluatorRoutes.putMemory G false m
+ let cp := Advice.copyBank G.constants G.g
+ G.tagged Stage.prefixLength result ∧
+ (∀ j : Fin (size G).advice, result (((Advice.fp G.constants G.g) 0).val+j.val) =
+ PrimedInputRAM.encodeBit G.w (advice j)) ∧
+ (∀ q : Fin (labelCount G*exponentWidth G),
+ result ((HeaderLayout.exponent G.constants.lengths Layout.header .left).eval G.g+q.val) =
+ PrimedInputRAM.encodeBit G.w (RAMSerialization.arrayBits _ _ (middleWords G cuts fit) q)) ∧
+ result (cp 1).val = Fin.ofNat _ (controlTag G.evaluator).val ∧
+ ∀ k : Fin (fieldWords (cp 0).val), 0 < k.val → result ((cp 1).val+k.val) = 0 := by
+ intro result cp
+ let s := size G
+ let hb := Header.base G.g
+ let ad := adviceBase s hb
+ let ex := exponentBase s hb .left
+ let old := (Layout.oldState G.constants).eval G.g
+ let t := 2^G.g.d
+ have htad : t < ad := by
+ simp only [ad, adviceBase, rightIndexBase, leftIndexBase, populationAddr, highAddr, indexBase, hb, Header.base, t]
+ omega
+ have hadex : ad+s.advice ≤ ex := by dsimp [ad, ex, exponentBase, exteriorBase]; omega
+ have hexlim : ex+s.e ≤ LiveHeaderSchedule.limit s hb := by
+ dsimp only [ex, LiveHeaderSchedule.limit, configBase, exponentBase]
+ omega
+ have hlimold : LiveHeaderSchedule.limit s hb ≤ old := by
+ change LiveHeaderSchedule.limit s hb ≤ LiveHeaderSchedule.limit s hb+21+labelCount G
+ omega
+ have hfit : old < 2^G.w := by
+ have h : old ≤ (Layout.shadow G.constants).eval G.g := by
+ simp only [old, Layout.shadow, Layout.orderMap, Layout.packedPrefix, Layout.adviceFrames,
+ Layout.transitionScratch, Layout.newState, eval_add]
+ omega
+ exact h.trans_lt hlimit
+ have tagVal : G.addr.val = t := Nat.mod_eq_of_lt (by omega : t < 2^G.w)
+ have advVal : ((Advice.fp G.constants G.g) 0).val = ad := Nat.mod_eq_of_lt (by omega : ad < 2^G.w)
+ have stateVal : (cp 1).val = old := Nat.mod_eq_of_lt hfit
+ have hend : EvaluatorSentinel.destination G false = Stage.prefixLength := by
+ simp [EvaluatorSentinel.destination, running]
+ have stateWord : EvaluatorSentinel.operands G false 1 = cp 1 := rfl
+ have htagstate : G.addr.val < (cp 1).val := by omega
+ have afterWrite : result = writeMemory (writeMemory (EvaluatorRoutes.retag G Stage.initialState m)
+ (cp 1) (Fin.ofNat _ (controlTag G.evaluator).val)) G.addr (LiveStageLink.tagWord G.w Stage.prefixLength) := by
+ change EvaluatorSentinel.transferred G false _ = _
+ rw [EvaluatorSentinel.transferred, EvaluatorSentinel.put, stateWord, hend]
+ rfl
+ have unchanged (a : ℕ) (htag : G.addr.val < a) (hstate : a ≠ (cp 1).val) : result a = m a := by
+ rw [afterWrite]
+ simp only [EvaluatorRoutes.retag, writeMemory, ite_eq_right htag.ne', ite_eq_right hstate]
+ refine ⟨?_, ?_, ?_, ?_, ?_⟩
+ · rw [afterWrite]
+ exact (show writeMemory _ G.addr _ G.addr.val = _ by simp [writeMemory])
+ · intro j
+ have hj : j.val < s.advice := j.isLt
+ rw [advVal, unchanged _ (by omega) (by omega)]
+ exact out.adviceWords j
+ · intro q
+ change result (ex+q.val) = _
+ have hq : q.val < s.e := q.isLt
+ rw [unchanged _ (by omega) (by omega)]
+ exact middle_bits G out fit q
+ · rw [afterWrite]
+ simp [writeMemory, htagstate.ne']
+ · intro k hk
+ rw [unchanged _ (by omega) (by omega)]
+ exact out.fresh_after_limit _ (by omega : LiveHeaderSchedule.limit s hb ≤ (cp 1).val+k.val)
+
+end LiveProgram.FirstTailHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveFirstTailOutput.lean b/lean/OAI/Computability/VPVNP/LiveFirstTailOutput.lean
new file mode 100644
index 0000000000..27c8eaf7fe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveFirstTailOutput.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorTransport
+import OAI.Computability.VPVNP.LiveProgramAdviceInputLayout
+
+/-!
+# Preserving the outgoing cut during midpoint initialization
+
+The outgoing flag and distributed cut lie below the old configuration. The
+new configuration lies between the old configuration and the advice frames.
+Initialization of the old tape and the four advice stages therefore preserve
+all three inputs to the outgoing router.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM PairStages LiveEvaluatorEncoding LiveEvaluatorAdviceBanks
+open scoped Fin.CommRing
+
+variable (G : Group)
+
+/-- The advice frame follows the five transition-scratch words. -/
+theorem frameAfterScratch (fits : limit G < 2^G.w) :
+ (Advice.fp G.constants G.g 3).val = (G.transitionPub 3).val + 5 := by
+ let s := (Layout.transitionScratch G.constants).eval G.g
+ have hf : s+5 < 2^G.w := by
+ change (Layout.shadow G.constants).eval G.g < _ at fits
+ simp only [Layout.shadow,Layout.orderMap,Layout.packedPrefix,Layout.adviceFrames,eval_add] at fits
+ change s+5+24+_+_ < _ at fits
+ omega
+ change (s+5) % (2^G.w) = s % (2^G.w) + 5
+ rw [Nat.mod_eq_of_lt hf,Nat.mod_eq_of_lt (by omega : s < 2^G.w)]
+
+/-- Pointwise preservation on the two physical ranges surrounding the
+incoming bank suffices for the outgoing router's complete input. -/
+theorem frameOfRanges (fits : limit G < 2^G.w) (m m' : Memory G.w)
+ (preserve : ∀ x : ℕ, G.addr.val < x → x < (Advice.fp G.constants G.g 3).val →
+ (x < (G.transitionPub 1).val ∨ (G.transitionPub 1).val+k G ≤ x) → m' x = m x) :
+ OutputFrame G (radius G) m m' := by
+ obtain ⟨l,r,e,flag,fl,o,n,s,rad,wc,kc⟩ := addresses G fits
+ have hf := frameAfterScratch G fits
+ refine ⟨preserve _ flag (by omega) (.inl (by omega)), ?_, ?_⟩
+ · intro j
+ have hj : j.val < k G * G.w := j.isLt
+ exact preserve _ (by omega) (by omega) (.inl (by omega))
+ · intro j
+ have hj : j.val < k G := j.isLt
+ exact preserve _ (by omega) (by omega) (.inr (by omega))
+
+/-- Compose the control-word write, advice preparation, and the incoming
+tape's writes. The outgoing cut is read from the original physical header. -/
+theorem initialOutputFrame (fits : limit G < 2^G.w) (raw : List Bool)
+ (values : Fin (G.constants.labels.eval G.g) → Word (Nat.clog 2 (G.constants.labels.eval G.g)))
+ (L : PreparedLayout (Advice.lp G.constants G.g) (Advice.fp G.constants G.g)
+ (Advice.op G.constants G.g) raw (G.constants.labels.eval G.g) (Nat.clog 2 (G.constants.labels.eval G.g)))
+ (m final : Memory G.w)
+ (outside : ∀ x : ℕ, x ≠ G.addr.val →
+ (x < (G.transitionPub 1).val ∨ (G.transitionPub 1).val+k G ≤ x) →
+ final x = Advice.finalMemory G.constants G.g G.lit raw values (putMemory G false m) x) :
+ OutputFrame G (radius G) m final := by
+ let written := putMemory G false m
+ have F₁ := putInitialFrame G (addresses G fits) m
+ have F₂ : OutputFrame G (radius G) written final := by
+ apply frameOfRanges G fits
+ intro x above below ext
+ exact (outside x (by omega) ext).trans
+ (Advice.beforeFrame_preserved G.constants G.g G.lit raw values written L fits x above below)
+ exact ⟨F₂.flag.trans F₁.flag,fun j => (F₂.field j).trans (F₁.field j),
+ fun j => (F₂.bank j).trans (F₁.bank j)⟩
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveFirstTailPhysicalCount.lean b/lean/OAI/Computability/VPVNP/LiveFirstTailPhysicalCount.lean
new file mode 100644
index 0000000000..604d8e877a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveFirstTailPhysicalCount.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.LiveFirstTailCount
+import OAI.Computability.VPVNP.LiveFirstTailHeader
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorLocalCount
+
+/-!
+# The first evaluator group on the native distributed memory
+
+At the midpoint the incoming exponent field is the final counter vector of
+the pair half. The ordinal advice reindexes that vector into the evaluator's
+formal input order. The live program packs the advice, copies its exact raw
+prefix, generates the runtime fields, and scatters the exponent bits before
+the first transition.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM PairStages LiveEvaluatorEncoding LiveEvaluatorRAM LiveHeaderDescriptors LiveHeader
+open ChainAssignments LiveChain LocalCount LiveEvaluatorAdviceBanks
+open OutsideTailStages OutsideTailCount
+open scoped Fin.CommRing
+
+variable (G : Group)
+
+/-- The evaluator starts on the raw prefix followed immediately by its
+runtime fields in formal label order. -/
+def midpointInitial (raw : List Bool)
+ (perm : Equiv.Perm (Fin (FirstTailHeader.labelCount G)))
+ (dense : Fin (FirstTailHeader.labelCount G) → ℕ) : Code G.evaluator.extra (radius G) :=
+ LiveEvaluatorTail.initialCode (radius G) (UniversalMachine.initial G.evaluator
+ (raw ++ EvaluatorProgramRawInput.runtime
+ (fun a => Fin.ofNat (2^(FirstTailHeader.exponentWidth G)) (dense (perm.symm a)))))
+
+/-- Count on the actual post-header memory for a nonempty evaluator at the
+first tail group, under the cap on the entire physical group. -/
+theorem nonemptyFirstPhysicalCount {S H padding : ℕ}
+ (W : Conditions G S H) (adv : CutSchedule.Bits (sizes G).advice)
+ (fits : limit G < 2^G.w) (fit : GeometryFit G (radius G))
+ (expFit : 1+FirstTailHeader.labelCount G*FirstTailHeader.exponentWidth G ≤ (sizes G).delta)
+ (layout : LiveEvaluatorTail.Layout G.evaluator.extra (radius G) G.w (sizes G).delta)
+ (raw : List Bool) (perm : Equiv.Perm (Fin (FirstTailHeader.labelCount G)))
+ (values : Fin (FirstTailHeader.labelCount G) → Word (Nat.clog 2 (FirstTailHeader.labelCount G)))
+ (ordinal : ∀ a, (values a).val = (perm a).val)
+ (capacity : G.w + G.constants.prefixCapacity.eval G.g +
+ FirstTailHeader.labelCount G * Nat.clog 2 (FirstTailHeader.labelCount G) ≤ (sizes G).advice)
+ (rawFits : raw.length ≤ G.constants.prefixCapacity.eval G.g)
+ (literal : List.ofFn adv = distribution G.w (G.constants.prefixCapacity.eval G.g) raw values padding)
+ (space : raw.length + (2*(FirstTailHeader.labelCount G*FirstTailHeader.exponentWidth G)+
+ 6*FirstTailHeader.exponentWidth G+4) ≤ radius G+1)
+ (running : G.evaluator.extra ≠ 0)
+ (cuts : AllCuts (sizes G).h (sizes G).delta) (i : Fin (2^(sizes G).h)) (first : i.val = 0)
+ (mode : physicalTag cuts (halves (sizes G).h (.inr i)) = some .tail)
+ (pad : LiveHeaderProgram.Fields.ValidPadding (sizes G) cuts (halves (sizes G).h (.inr i)) .tail .right)
+ (tr : Prepared W adv cuts (halves (sizes G).h (.inr i)) .tail)
+ (header : LiveHeaderProgram.Output (sizes G) (headerBase G) G.g.d W.word adv cuts
+ (halves (sizes G).h (.inr i)) .tail (memory tr))
+ (hcall : callBound G.w ≤ H)
+ (budget : LiveHeaderSchedule.costBound (sizes G)+4+8+packWork (params G raw.length)+
+ inputWork (params G raw.length)+routeCost G.w (radius G)+transitionCost (radius G) ≤ S*H) :
+ Nat.card (remaining tr) = tailCount G.evaluator layout
+ (midpointInitial G raw perm (fun a => (FirstTailHeader.middleWords G cuts expFit a).val))
+ (liveCutEquiv (sizes G).h (sizes G).delta cuts).2 i := by
+ have hi : i = 0 := Fin.ext first
+ subst i
+ let m := memory tr
+ let u := putMemory G false m
+ let dense := FirstTailHeader.middleWords G cuts expFit
+ let formal := fun a => dense (perm.symm a)
+ let init := midpointInitial G raw perm (fun a => (dense a).val)
+ let c := G.constants
+ let g := G.g
+ let cp := Advice.copyBank c g
+ have he := headerBelowOld G fits
+ have flag := HeaderFlags.firstTail c g G.lit (he.trans_lt (G.transitionPub 1).isLt) header
+ change m _ = (if 2^(sizes G).h+(0 : Fin (2^(sizes G).h)).val+1 = 2^(sizes G).h+1 then 1 else 0) at flag
+ rw [Fin.val_zero,Nat.add_zero,ite_eq_left rfl] at flag
+ obtain ⟨tag,copied,inc,ctrl,zero⟩ := FirstTailHeader.prepared G header expFit fits running
+ have L := Advice.preparedLayout c g raw W.word fits capacity rawFits
+ have rad : (cp 0).val = radius G := (addresses G fits).radiusWord
+ have cfit : c.prefixCapacity.eval g < 2^G.w := by
+ change (Layout.shadow c).eval g < _ at fits
+ simp only [Layout.shadow,Layout.orderMap,Layout.packedPrefix,eval_add] at fits
+ omega
+ have hcap : ((Advice.fp c g) 1).val = c.prefixCapacity.eval g := Nat.mod_eq_of_lt cfit
+ have hh := Advice.fourStages_budget c G.evaluator G.pair g G.lit u raw values adv L copied
+ (by simpa only [hcap] using literal) fits (cap := G.clock) ((by decide : 130 ≤ 154).trans W.clock) tag
+ rw [← G.program_eq] at hh
+ have blank : ∀ j : Fin (fieldWords (radius G)), 0 < j.val → u ((cp 1).val+j.val) = 0 :=
+ fun j hj => zero ⟨j.val,by change j.val < fieldWords (cp 0).val; rw [rad]; exact j.isLt⟩ hj
+ obtain ⟨final,r⟩ := G.suffixRun_actual raw u values perm dense formal
+ (fun j => by simp [formal]) ordinal L fits ((by decide : 94 ≤ 154).trans W.clock) running
+ fit.prep.states space inc ctrl blank
+ have rt := Advice.returning_append hh.1 r.returning
+ have cw := Advice.costLimit_append hh.1 r.returning hh.2 r.cost
+ have costEq := advice_work G raw u L
+ rw [costEq] at cw
+ have typed : ConfigAt final (G.transitionPub 1) init := by
+ have cfg := r.config
+ change ConfigAt final (G.transitionPub 1) (LiveEvaluatorTail.initialCode (cp 0).val
+ (UniversalMachine.initial G.evaluator (raw ++ EvaluatorProgramRawInput.runtime formal))) at cfg
+ rw [rad] at cfg
+ have row (a : Fin (FirstTailHeader.labelCount G)) :
+ Fin.ofNat (2^(FirstTailHeader.exponentWidth G)) (dense (perm.symm a)).val = formal a :=
+ Fin.ext (Nat.mod_eq_of_lt (dense (perm.symm a)).isLt)
+ simpa only [init,midpointInitial,funext row] using cfg
+ have frame := initialOutputFrame G fits raw values L m final (fun x hx ho =>
+ r.outside x hx (by
+ change x < (G.transitionPub 1).val ∨ (G.transitionPub 1).val+fieldWords (cp 0).val ≤ x
+ rw [rad]; exact ho))
+ obtain ⟨o⟩ := physicalOutput G header layout init mode fits pad
+ exact countAfterInitialization G layout init _ 0 rfl m final fit tr.tag flag rt cw typed r.tag
+ (o.transport frame) tr.logs (headerResources W adv cuts 0 tr) hcall (by
+ simpa only [Nat.add_assoc,params,packWork,inputWork,LiveEvaluatorTailCost.Parameters.runtimeBits,
+ LiveEvaluatorTailCost.Parameters.exponentBits] using budget)
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveGroupContraction.lean b/lean/OAI/Computability/VPVNP/LiveGroupContraction.lean
new file mode 100644
index 0000000000..bd075e980f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveGroupContraction.lean
@@ -0,0 +1,215 @@
+import OAI.Computability.VPVNP.LiveCutAssignments
+import OAI.Computability.VPVNP.LiveEvaluatorTail
+
+/-! # Contracting the evaluation mode of the live chain
+
+For a fixed first-half cut assignment, each pair reads the exterior bits at
+its two adjacent cuts and checks its outgoing counters. Each tail group then
+reads two adjacent configuration fields and checks one transition. Summing
+the products of these local counts eliminates the forced counter fields and
+configuration strings, leaving the actual evaluator path multiplicity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ChainAssignments
+
+open CutSchedule ExponentTrace LiveChain UniversalMachine LiveEvaluatorEncoding
+open scoped Classical
+
+variable {h Δ t Z M w : ℕ}
+
+private def outgoing (fit : 1 + t * Z ≤ Δ) (fst : LiveBits h Δ) (i : Fin (2^h)) :=
+ firstHalfLayout h Δ (i.val+1) t Z (by omega) i.isLt fit (fst i)
+
+/-- Exterior primed bits are read from the first-half cuts. The initial cut
+has width zero. -/
+def exteriorOf (fit : 1 + t * Z ≤ Δ) (fst : LiveBits h Δ) : Exterior h Δ :=
+ Fin.cons (fun _ => false) (fun i => (outgoing fit fst i).2.1)
+
+private theorem exterior_eq {fit : 1 + t * Z ≤ Δ} {fst : LiveBits h Δ} {ξ : Exterior h Δ}
+ (same : ∀ i, (outgoing fit fst i).2.1 = ξ i.succ) : exteriorOf fit fst = ξ := by
+ funext j
+ refine Fin.cases ?_ (fun i => ?_) j
+ · funext k
+ exact Fin.elim0 (k.cast (by simp))
+ · exact same i
+
+/-- One pair checks the canonical outgoing fields and the increment over
+its incoming counters. Both sides of each counter comparison are natural
+numbers, so overflow cannot create additional paths. -/
+def firstCheck (fit : 1 + t * Z ≤ Δ) (fst : LiveBits h Δ) (ξ : Exterior h Δ)
+ (i : Fin (2^h)) (inc : Fin t → ℕ) : Prop :=
+ outgoing fit fst i = (true, ξ i.succ, counters fit fst i.succ, fun _ => false) ∧
+ ∀ a, (counters fit fst i.succ a).val = (counters fit fst i.castSucc a).val + inc a
+
+private theorem allFirstChecks (fit : 1 + t * Z ≤ Δ) (fst : LiveBits h Δ) (ξ : Exterior h Δ)
+ (inc : Fin (2^h) → Fin t → ℕ) :
+ (∀ i, firstCheck fit fst ξ i (inc i)) ↔ ExponentTrace.Valid fit ξ inc fst := by
+ exact forall_and
+
+private theorem exteriorOf_valid (fit : 1 + t * Z ≤ Δ) (fst : LiveBits h Δ) (ξ : Exterior h Δ)
+ (inc : Fin (2^h) → Fin t → ℕ) (ok : ExponentTrace.Valid fit ξ inc fst) : exteriorOf fit fst = ξ :=
+ exterior_eq fun i => congrArg (fun a => a.2.1) (ok.1 i)
+
+variable {Nom : Type*} [Fintype Nom]
+variable {Path : Exterior h Δ → Fin (2^h) → Nom → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+
+/-- The local count of evaluation-mode paths through a first-half group. -/
+noncomputable def pairCount (fit : 1 + t * Z ≤ Δ)
+ (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ) (fst : LiveBits h Δ) (i : Fin (2^h)) : ℕ :=
+ let ξ := exteriorOf fit fst
+ ∑ μ, ∑ q : Path ξ i μ, if firstCheck fit fst ξ i (inc ξ i μ q) then 1 else 0
+
+/-- Number of branch bits yielding exactly the two specified adjacent tail
+states. Distinct choices count separately even at coincident successors. -/
+noncomputable def tailCount (p : Program) (layout : LiveEvaluatorTail.Layout p.extra M w Δ)
+ (init : Code p.extra M) (lst : TailBits h Δ) (i : Fin (2^h)) : ℕ :=
+ ∑ bit : Bool, if ∃ a b, LiveEvaluatorTail.boundary layout init lst i.castSucc = some a ∧
+ LiveEvaluatorTail.boundary layout init lst i.succ = some b ∧
+ LiveEvaluatorStep.nextCode p a bit = some b ∧ b ≠ .rejected then 1 else 0
+
+private theorem tailProduct (p : Program) (layout : LiveEvaluatorTail.Layout p.extra M w Δ)
+ (init : Code p.extra M) :
+ (∑ lst : TailBits h Δ, ∏ i : Fin (2^h), tailCount p layout init lst i) =
+ Nat.card (LiveEvaluatorTail.Runs (h := h) layout init) := by
+ unfold tailCount LiveEvaluatorTail.Runs
+ simp_rw [Fintype.prod_sum, Fintype.prod_ite_zero, Finset.prod_const_one]
+ rw [Finset.sum_comm, Nat.card_eq_fintype_card, Fintype.card_sigma]
+ apply Finset.sum_congr rfl
+ intro choices _
+ simp only [Finset.sum_boole, LiveEvaluatorTail.Valid]
+ symm
+ convert! Fintype.card_subtype (LiveEvaluatorTail.Valid layout init choices) using 1
+ apply congrArg Finset.card
+ ext b
+ simp [LiveEvaluatorTail.Valid]
+
+private theorem pairProduct (fit : 1 + t * Z ≤ Δ) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (fst : LiveBits h Δ) :
+ (∏ i, pairCount fit inc fst i) = ∑ ξ : Exterior h Δ, ∑ μ : Fin (2^h) → Nom,
+ ∑ q : (i : Fin (2^h)) → Path ξ i (μ i),
+ if ExponentTrace.Valid fit ξ (fun i => inc ξ i (μ i) (q i)) fst then 1 else 0 := by
+ rw [Finset.sum_eq_single (exteriorOf fit fst)]
+ · unfold pairCount
+ dsimp only
+ rw [Fintype.prod_sum]
+ apply Finset.sum_congr rfl
+ intro μ _
+ rw [Fintype.prod_sum]
+ apply Finset.sum_congr rfl
+ intro q _
+ simp only [Fintype.prod_ite_zero, Finset.prod_const_one, allFirstChecks]
+ · intro ξ _ hne
+ apply Finset.sum_eq_zero
+ intro μ _
+ apply Finset.sum_eq_zero
+ intro q _
+ exact ite_eq_right (fun ok => hne (exteriorOf_valid fit fst ξ _ ok).symm)
+ · simp
+
+/-- The evaluation mode contracts to the sum over exterior assignments,
+nomination vectors and local pair paths, followed by a single evaluator on
+the componentwise sum of their increments. -/
+theorem evaluation_contraction (fit : 1 + t * Z ≤ Δ) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (bound : ∀ ξ (μ : Fin (2^h) → Nom) (q : (i : Fin (2^h)) → Path ξ i (μ i)) (i : Fin (2^h)) a,
+ partialSum (fun j => inc ξ j (μ j) (q j)) i.succ a < 2^Z)
+ (p : Program) (layout : LiveEvaluatorTail.Layout p.extra M w Δ)
+ (initial : (Fin t → ℕ) → Config p.extra) (init : (Fin t → ℕ) → Code p.extra M)
+ (hi : ∀ e, (init e).toState = EvaluatorTail.canonical (initial e))
+ (space : ∀ e, LiveEvaluatorTail.HistoriesFit p M (2^h) (initial e)) :
+ (∑ fst : LiveBits h Δ, ∑ lst : TailBits h Δ, (∏ i, pairCount fit inc fst i) *
+ ∏ i, tailCount p layout (init (fun a => (counters fit fst (Fin.last _) a).val)) lst i) =
+ ∑ ξ : Exterior h Δ, ∑ μ : Fin (2^h) → Nom, ∑ q : (i : Fin (2^h)) → Path ξ i (μ i),
+ paths p (2^h) (initial (fun a => ∑ i, inc ξ i (μ i) (q i) a)) := by
+ let endCounts (fst : LiveBits h Δ) (a : Fin t) := (counters fit fst (Fin.last _) a).val
+ have tail (fst : LiveBits h Δ) : (∑ lst : TailBits h Δ, ∏ i : Fin (2^h),
+ tailCount p layout (init (endCounts fst)) lst i) = paths p (2^h) (initial (endCounts fst)) :=
+ (tailProduct p layout _).trans (LiveEvaluatorTail.card_runs layout _ _ (hi _) (space _))
+ change (∑ fst, ∑ lst, (∏ i, pairCount fit inc fst i) * ∏ i, tailCount p layout (init (endCounts fst)) lst i) = _
+ simp_rw [← Finset.mul_sum, tail, pairProduct, Finset.sum_mul, ite_mul, one_mul, zero_mul]
+ rw [Finset.sum_comm]
+ apply Finset.sum_congr rfl
+ intro ξ _
+ rw [Finset.sum_comm]
+ apply Finset.sum_congr rfl
+ intro μ _
+ rw [Finset.sum_comm]
+ apply Finset.sum_congr rfl
+ intro q _
+ obtain ⟨fst, ok, uniq⟩ := existsUnique_live fit ξ (fun i => inc ξ i (μ i) (q i)) (bound ξ μ q)
+ rw [Finset.sum_eq_single fst, ite_eq_left ok]
+ · congr 2
+ exact funext (middle_counters fit ξ _ fst ok)
+ · exact fun other _ hne => ite_eq_right fun ho => hne (uniq _ ho)
+ · simp
+
+/-- A successful first-half group sets the literal first bit of its outgoing cut. -/
+theorem pairCount_mode (fit : 1 + t * Z ≤ Δ) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (fst : LiveBits h Δ) (i : Fin (2^h)) (ok : pairCount fit inc fst i ≠ 0) :
+ distributedBit (fst i) 0 = true := by
+ have hw : 0 < width (h+1) Δ (i.val+1) := by rw [width_double h Δ _ (by omega) i.isLt]; omega
+ have raw : (outgoing fit fst i).1 = fst i ⟨0, hw⟩ := rfl
+ simp only [distributedBit, hw, ↓reduceDIte, ← raw]
+ by_contra no
+ apply ok
+ unfold pairCount
+ apply Finset.sum_eq_zero
+ intro μ _
+ apply Finset.sum_eq_zero
+ intro q _
+ exact ite_eq_right fun hv => no (congrArg Prod.fst hv.1)
+
+/-- A successful tail group with an outgoing cut sets its literal first bit. -/
+theorem tailCount_mode (p : Program) (layout : LiveEvaluatorTail.Layout p.extra M w Δ)
+ (init : Code p.extra M) (lst : TailBits h Δ) (j : Fin (2^h-1))
+ (ok : tailCount p layout init lst ⟨j.val, by have := j.isLt; omega⟩ ≠ 0) :
+ distributedBit (lst j) 0 = true := by
+ let i : Fin (2^h) := ⟨j.val, by have := j.isLt; omega⟩
+ have hj : j.val+1 ≠ 2^h := by have := j.isLt; omega
+ have hb : LiveEvaluatorTail.boundary layout init lst i.succ = LiveEvaluatorTail.readCut layout j (lst j) := by
+ simp [LiveEvaluatorTail.boundary, i, hj]
+ have hlt : 2^h+(j.val+1) < 2^(h+1) := by rw [pow_succ]; have := j.isLt; omega
+ have hw : 0 < width (h+1) Δ (2^h+(j.val+1)) := by rw [width_tail h Δ _ (by omega) hlt]; have := layout.cutWidth; omega
+ by_contra no
+ apply ok
+ unfold tailCount
+ apply Finset.sum_eq_zero
+ intro bit _
+ apply ite_eq_right
+ rintro ⟨a,b,_,hout,_,_⟩
+ change LiveEvaluatorTail.boundary layout init lst i.succ = some b at hout
+ rw [hb, LiveEvaluatorTail.readCut_iff] at hout
+ apply no
+ rw [hout]
+ let e := tailLayout h Δ (2^h+(j.val+1)) (fieldWords M*w) (by omega) hlt layout.cutWidth
+ have raw (bits : Bits (width (h+1) Δ (2^h+(j.val+1)))) : (e bits).1 = distributedBit bits 0 := by
+ simp only [distributedBit, hw, ↓reduceDIte]; rfl
+ rw [← raw]
+ exact congrArg Prod.fst (e.apply_symm_apply _)
+
+/-- The two contiguous halves, in order of their physical group indices. -/
+def halves (h : ℕ) : Fin (2^h) ⊕ Fin (2^h) ≃ Fin (2^(h+1)) :=
+ finSumFinEquiv.trans (finCongr (by rw [pow_succ]; omega))
+
+/-- Product and sum reindexing for a per-group evaluation-mode count on raw cuts. -/
+theorem contract_halves (ev : AllCuts h Δ → Fin (2^(h+1)) → ℕ)
+ (f : LiveBits h Δ → Fin (2^h) → ℕ) (g : LiveBits h Δ → TailBits h Δ → Fin (2^h) → ℕ)
+ (left : ∀ c i, ev c (halves h (.inl i)) = f (liveCutEquiv h Δ c).1 i)
+ (right : ∀ c i, ev c (halves h (.inr i)) = g (liveCutEquiv h Δ c).1 (liveCutEquiv h Δ c).2 i) :
+ (∑ c : AllCuts h Δ, ∏ j, ev c j) = ∑ fst, ∑ lst, (∏ i, f fst i) * ∏ i, g fst lst i := by
+ rw [← (liveCutEquiv h Δ).symm.sum_comp, Fintype.sum_prod_type]
+ apply Finset.sum_congr rfl
+ intro fst _
+ apply Finset.sum_congr rfl
+ intro lst _
+ rw [← (halves h).prod_comp, Fintype.prod_sum_type]
+ simp only [left, right, Equiv.apply_symm_apply]
+
+end ChainAssignments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveGroupModeInput.lean b/lean/OAI/Computability/VPVNP/LiveGroupModeInput.lean
new file mode 100644
index 0000000000..2570f56a26
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveGroupModeInput.lean
@@ -0,0 +1,292 @@
+import OAI.Computability.VPVNP.LiveHeaderCutInput
+import OAI.Computability.VPVNP.LiveHeaderMode
+import OAI.Computability.VPVNP.LivePhysicalContraction
+
+/-!
+# Physical mode selection and the unit group count
+
+The mode table reads slots two and three of processor zero and the widths
+of the two cuts. Its unit tag, followed by the two padding scans, is
+equivalent to the unit summand of the contraction. Its other tag selects
+the evaluation summand of the first half or the tail, including at both
+ends and when adjacent cuts have incompatible modes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ChainAssignments
+open CutSchedule LiveHeaderDescriptors
+open scoped Classical Fin.CommRing
+
+variable {w d a h Δ t Z M : ℕ}
+
+/-- The scheduled width of the cut incident to the given side of a group. -/
+abbrev incidentWidth (side : Side) (g : Fin (2^(h+1))) :=
+ width (h+1) Δ (incidentCut side g).val
+
+/-- The Boolean test that a group lies in the initial half of the chain. -/
+def firstHalfFlag (g : Fin (2^(h+1))) := decide (g.val+1 ≤ 2^h)
+
+/-- The tag computed from the actual incident widths and processor-zero bits. -/
+def physicalTag (cuts : AllCuts h Δ) (g : Fin (2^(h+1))) :=
+ Mode.selected (incidentWidth (Δ := Δ) .left g) (incidentWidth (Δ := Δ) .right g)
+ (distributedBit (cuts g.castSucc) 0) (distributedBit (cuts g.succ) 0) (firstHalfFlag g)
+
+private theorem width_pos_iff {H j : ℕ} (hΔ : 0 < Δ) :
+ 0 < width H Δ j ↔ 0 < j ∧ j < 2^H := by
+ rw [width]
+ by_cases hj : 0 < j ∧ j < 2^H
+ · rw [ite_eq_left hj]
+ have hlog := Nat.log_lt_of_lt_pow hj.1.ne' hj.2
+ exact iff_of_true (Nat.mul_pos (by omega) hΔ) hj
+ · simp [hj]
+
+private theorem has_incident (hΔ : 0 < Δ) (g : Fin (2^(h+1))) :
+ incidentWidth (Δ := Δ) .left g ≠ 0 ∨ incidentWidth (Δ := Δ) .right g ≠ 0 := by
+ by_cases first : g.val = 0
+ · apply Or.inr
+ apply Nat.ne_of_gt ((width_pos_iff hΔ).mpr ?_)
+ change 0 < g.val+1 ∧ g.val+1 < 2^(h+1)
+ rw [first, Nat.zero_add]
+ exact ⟨by decide, Nat.one_lt_two_pow (by omega)⟩
+ · apply Or.inl
+ exact Nat.ne_of_gt ((width_pos_iff hΔ).mpr ⟨Nat.pos_of_ne_zero first,g.isLt⟩)
+
+private theorem selected_iff {l r : ℕ} (present : l ≠ 0 ∨ r ≠ 0) (x y f : Bool) :
+ (Mode.selected l r x y f = some .unit ↔ (l = 0 ∨ x = false) ∧ (r = 0 ∨ y = false)) ∧
+ (Mode.selected l r x y f = some (Mode.selectTag true f) ↔ (l = 0 ∨ x = true) ∧ (r = 0 ∨ y = true)) := by
+ by_cases hl : l = 0 <;> by_cases hr : r = 0 <;> cases x <;> cases y <;> cases f <;>
+ simp [Mode.selected,Mode.selectTag,hl,hr] at *
+
+private theorem eval_mode_iff (hΔ : 0 < Δ) (cuts : AllCuts h Δ) (i : Fin (2^(h+1)+1)) :
+ evalCutMode cuts i ↔ width (h+1) Δ i.val = 0 ∨ distributedBit (cuts i) 0 = true := by
+ have hp := width_pos_iff (j := i.val) (H := h+1) hΔ
+ constructor
+ · intro he
+ by_cases hz : width (h+1) Δ i.val = 0
+ · exact Or.inl hz
+ · have ⟨a,b⟩ := hp.mp (Nat.pos_of_ne_zero hz)
+ exact Or.inr (he a b)
+ · rintro (hz | hb) a b
+ · exact False.elim ((hp.mpr ⟨a,b⟩).ne' hz)
+ · exact hb
+
+/-- Evaluation is selected exactly when both actual interior modes are true.
+The first-half flag distinguishes the pair and tail tags. -/
+theorem physicalTag_evaluation (hΔ : 0 < Δ) (cuts : AllCuts h Δ) (g : Fin (2^(h+1))) :
+ physicalTag cuts g = some (Mode.selectTag true (firstHalfFlag g)) ↔
+ evalCutMode cuts g.castSucc ∧ evalCutMode cuts g.succ := by
+ rw [eval_mode_iff hΔ, eval_mode_iff hΔ]
+ exact (selected_iff (has_incident hΔ g) _ _ _).2
+
+private theorem mode_site_zero_iff {W : ℕ} (bits : Bits W) :
+ (W = 0 ∨ distributedBit bits 0 = false) ↔ ∀ i : Fin W, i.val = 0 → bits i = false := by
+ by_cases hz : 0 < W
+ · simp only [hz.ne',false_or,distributedBit,dite_eq_left hz]
+ constructor
+ · intro zero i hi
+ exact (congrArg bits (Fin.ext hi)).trans zero
+ · exact fun zero => zero ⟨0,hz⟩ rfl
+ · have hW : W = 0 := by omega
+ exact iff_of_true (Or.inl hW) (fun i _ => False.elim (by have := i.isLt; omega))
+
+/-- The two trailing padding intervals in unit mode. They may be empty. -/
+def unitPads (cuts : AllCuts h Δ) (g : Fin (2^(h+1))) (e c : ℕ) : Prop :=
+ ∀ side, Physical.ZeroSlice (cuts (incidentCut side g))
+ (span .unit (incidentWidth (Δ := Δ) side g) Δ e c .padding)
+
+/-- Both complete cuts are zero precisely when the physical table chooses
+the unit tag and the two padding intervals pass. -/
+theorem physicalTag_unit (hΔ : 0 < Δ) (cuts : AllCuts h Δ) (g : Fin (2^(h+1))) (e c : ℕ) :
+ (physicalTag cuts g = some .unit ∧ unitPads cuts g e c) ↔
+ cuts g.castSucc = (fun _ => false) ∧ cuts g.succ = (fun _ => false) := by
+ have hu := (selected_iff (has_incident hΔ g) (distributedBit (cuts g.castSucc) 0)
+ (distributedBit (cuts g.succ) 0) (firstHalfFlag g)).1
+ constructor
+ · rintro ⟨tag,pads⟩
+ have ht := hu.mp tag
+ exact ⟨funext ((Physical.unit_zero_iff _ Δ e c).mp ⟨(mode_site_zero_iff _).mp ht.1,pads .left⟩),
+ funext ((Physical.unit_zero_iff _ Δ e c).mp ⟨(mode_site_zero_iff _).mp ht.2,pads .right⟩)⟩
+ · rintro ⟨hl,hr⟩
+ have left := (Physical.unit_zero_iff _ Δ e c).mpr (congrFun hl)
+ have right := (Physical.unit_zero_iff _ Δ e c).mpr (congrFun hr)
+ refine ⟨hu.mpr ⟨(mode_site_zero_iff _).mpr left.1,(mode_site_zero_iff _).mpr right.1⟩,?_⟩
+ intro side
+ cases side
+ · exact left.2
+ · exact right.2
+
+private theorem unit_span_fit (W Δ e c : ℕ) :
+ let iv := span .unit W Δ e c .padding
+ iv.1+iv.2 ≤ W := by
+ dsimp [span,count,start,mode,exterior,exponents,config]
+ split_ifs <;> omega
+
+/-- The native padding scan for the selected side succeeds on its full deterministic sequence
+of calls. -/
+abbrev PaddingSuccess (side : Side) (pub : Fin 3 → Word w) (m : Memory w) (len : ℕ) : Prop :=
+ let P := ((template (checkPaddingCell (cutSlot side)) 7).instantiate w pub).program
+ (runSegment P 15 (some (pub 0)) m (List.replicate len [])).isSome = true
+
+/-- Native acceptance of the two unit-padding scans, on the actual packed
+headers and descriptor words, computes exactly the unit contribution. -/
+theorem native_unit_count {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (hΔ : 0 < Δ) (headers : SiteHeaders d hw advice cuts g m)
+ (e c : ℕ) (pub : Side → Fin 3 → Word w)
+ (source : ∀ side, (m (pub side 1).val).val = (span .unit (incidentWidth (Δ := Δ) side g) Δ e c .padding).1)
+ (sites : ∀ side, incidentWidth (Δ := Δ) side g ≤ 2^d) (fit : 2^d ≤ 2^w) :
+ (if physicalTag cuts g = some .unit ∧
+ (∀ side, PaddingSuccess side (pub side) m (span .unit (incidentWidth (Δ := Δ) side g) Δ e c .padding).2)
+ then 1 else 0) = unitGroupCount cuts g := by
+ have h (side : Side) := physical_padding_native_iff headers side
+ (span .unit (incidentWidth (Δ := Δ) side g) Δ e c .padding) (pub side) (source side)
+ ((unit_span_fit ..).trans (sites side)) (unit_span_fit ..) ((unit_span_fit ..).trans ((sites side).trans fit))
+ have hp : (∀ side, PaddingSuccess side (pub side) m
+ (span .unit (incidentWidth (Δ := Δ) side g) Δ e c .padding).2) ↔ unitPads cuts g e c :=
+ forall_congr' h
+ apply ite_congr _ (fun _ => rfl) (fun _ => rfl)
+ exact propext ((and_congr_right fun _ => hp).trans (physicalTag_unit hΔ cuts g e c))
+
+/-- Public words 0 and 1 address the computed widths. The third scalar is
+the first-half flag. From these words the fixed native table realizes
+exactly the tag above on physical memory. -/
+theorem physical_mode_native {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (pub : Fin 16 → Word w) (state : Word w) (tag : Mode.Tag)
+ (left : (m (pub 0).val).val = incidentWidth (Δ := Δ) .left g)
+ (right : (m (pub 1).val).val = incidentWidth (Δ := Δ) .right g)
+ (flag : m (pub 2).val = PrimedInputRAM.encodeBit w (firstHalfFlag g)) (sel : physicalTag cuts g = some tag) :
+ let v := Fin.ofNat (2^w) tag.code.val
+ let P := ((Mode.program.template none).instantiate w pub).program
+ ∃ es, execute P 25 (P.start state) m [] = some ⟨es,none⟩ ∧
+ es.length ≤ 24 ∧ countProbes es = 5 ∧ choiceBits es = [] ∧ after m es = writeMemory m (pub 3) v := by
+ let zero : Fin (2^d) := ⟨0,Nat.two_pow_pos _⟩
+ apply Mode.native_selected pub state m hw (physicalHeader advice cuts g zero) (firstHalfFlag g) tag
+ (headers zero) flag
+ rw [left,right]
+ exact sel
+
+/-- When the two occupied modes disagree the native dispatcher rejects at
+all fuel bounds and for every nondeterministic choice tape. -/
+theorem physical_mode_rejects {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (pub : Fin 16 → Word w) (state : Word w)
+ (left : (m (pub 0).val).val = incidentWidth (Δ := Δ) .left g)
+ (right : (m (pub 1).val).val = incidentWidth (Δ := Δ) .right g)
+ (flag : m (pub 2).val = PrimedInputRAM.encodeBit w (firstHalfFlag g)) (sel : physicalTag cuts g = none)
+ (fuel : ℕ) (bits : List Bool) :
+ let P := ((Mode.program.template none).instantiate w pub).program
+ execute P fuel (P.start state) m bits = none := by
+ let zero : Fin (2^d) := ⟨0,Nat.two_pow_pos _⟩
+ apply Mode.native_rejected pub state m hw (physicalHeader advice cuts g zero) (firstHalfFlag g)
+ (headers zero) flag _ fuel bits
+ rw [left,right]
+ exact sel
+
+private theorem selected_cases (l r : ℕ) (x y f : Bool) :
+ Mode.selected l r x y f = none ∨ Mode.selected l r x y f = some .unit ∨
+ Mode.selected l r x y f = some (Mode.selectTag true f) := by
+ unfold Mode.selected
+ split_ifs <;> cases x <;> cases y <;> simp [Mode.selectTag]
+
+/-- The pair tag occurs precisely on evaluation-mode groups of the first half. -/
+theorem physicalTag_pair (hΔ : 0 < Δ) (cuts : AllCuts h Δ) (g : Fin (2^(h+1))) :
+ physicalTag cuts g = some .pair ↔
+ (evalCutMode cuts g.castSucc ∧ evalCutMode cuts g.succ) ∧ g.val+1 ≤ 2^h := by
+ have eval := physicalTag_evaluation hΔ cuts g
+ have casesTag := selected_cases (incidentWidth (Δ := Δ) .left g) (incidentWidth (Δ := Δ) .right g)
+ (distributedBit (cuts g.castSucc) 0) (distributedBit (cuts g.succ) 0) (firstHalfFlag g)
+ change physicalTag cuts g = none ∨ physicalTag cuts g = some .unit ∨
+ physicalTag cuts g = some (Mode.selectTag true (firstHalfFlag g)) at casesTag
+ by_cases hf : g.val+1 ≤ 2^h
+ · simpa [firstHalfFlag,Mode.selectTag,hf] using eval
+ · simp only [hf,and_false,iff_false]
+ rcases casesTag with hs | hs | hs <;> simp [hs,Mode.selectTag,firstHalfFlag,hf]
+
+/-- The tail tag occurs precisely on evaluation-mode groups after the midpoint. -/
+theorem physicalTag_tail (hΔ : 0 < Δ) (cuts : AllCuts h Δ) (g : Fin (2^(h+1))) :
+ physicalTag cuts g = some .tail ↔
+ (evalCutMode cuts g.castSucc ∧ evalCutMode cuts g.succ) ∧ 2^h < g.val+1 := by
+ have eval := physicalTag_evaluation hΔ cuts g
+ have casesTag := selected_cases (incidentWidth (Δ := Δ) .left g) (incidentWidth (Δ := Δ) .right g)
+ (distributedBit (cuts g.castSucc) 0) (distributedBit (cuts g.succ) 0) (firstHalfFlag g)
+ change physicalTag cuts g = none ∨ physicalTag cuts g = some .unit ∨
+ physicalTag cuts g = some (Mode.selectTag true (firstHalfFlag g)) at casesTag
+ by_cases hf : g.val+1 ≤ 2^h
+ · simp only [hf.not_gt,and_false,iff_false]
+ rcases casesTag with hs | hs | hs <;> simp [hs,Mode.selectTag,firstHalfFlag,hf]
+ · simpa [firstHalfFlag,Mode.selectTag,hf,Nat.lt_of_not_ge hf] using eval
+
+/-- Dispatching by the actual mode-table result, with unit and evaluation
+branches enforcing their respective checks. -/
+noncomputable def routedCount (tag : Option Mode.Tag) (unitPad incoming : Prop) (count : ℕ) : ℕ :=
+ match tag with
+ | none => 0
+ | some .unit => if unitPad then 1 else 0
+ | some .pair | some .tail => if incoming then count else 0
+
+private theorem routedCount_eq (tag : Option Mode.Tag) (pad incoming : Prop) (count : ℕ) :
+ routedCount tag pad incoming count =
+ (if tag = some .unit ∧ pad then 1 else 0) +
+ (if (tag = some .pair ∨ tag = some .tail) ∧ incoming then count else 0) := by
+ cases tag with
+ | none => simp [routedCount]
+ | some x => cases x <;> simp [routedCount]
+
+variable {Nom : Type*} [Fintype Nom] {Path : ExponentTrace.Exterior h Δ → Fin (2^h) → Nom → Type*}
+ [∀ ξ i μ, Fintype (Path ξ i μ)]
+variable (fit : 1+t*Z ≤ Δ) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (E : UniversalMachine.Program) (layout : LiveEvaluatorTail.Layout E.extra M w Δ)
+ (init : (Fin t → ℕ) → LiveEvaluatorEncoding.Code E.extra M)
+
+/-- The locally specified count on every raw cut assignment is the branch
+chosen by the actual dispatcher. This includes malformed and mismatched modes. -/
+theorem routed_specifiedGroupCount (cuts : AllCuts h Δ) (g : Fin (2^(h+1))) (e c : ℕ) :
+ routedCount (physicalTag cuts g) (unitPads cuts g e c) (incomingChecks t Z layout cuts g)
+ (groupEvaluation fit inc E layout init cuts g) = specifiedGroupCount fit inc E layout init cuts g := by
+ have hΔ : 0 < Δ := by omega
+ have he : (physicalTag cuts g = some .pair ∨ physicalTag cuts g = some .tail) ↔
+ evalCutMode cuts g.castSucc ∧ evalCutMode cuts g.succ := by
+ rw [physicalTag_pair hΔ,physicalTag_tail hΔ]
+ constructor
+ · rintro (hx | hx) <;> exact hx.1
+ · intro hx
+ rcases le_or_gt (g.val+1) (2^h) with hl | hr
+ · exact Or.inl ⟨hx,hl⟩
+ · exact Or.inr ⟨hx,hr⟩
+ rw [routedCount_eq,specifiedGroupCount]
+ congr 1
+ · exact ite_congr (propext (physicalTag_unit hΔ cuts g e c)) (fun _ => rfl) (fun _ => rfl)
+ · apply ite_congr _ (fun _ => rfl) (fun _ => rfl)
+ exact propext ((and_congr_left (fun _ => he)).trans and_assoc)
+
+/-- A first-half evaluation tag runs the pair whose raw exterior bits and
+cumulative exponent fields occupy these physical cuts. -/
+theorem routed_pair_count (cuts : AllCuts h Δ) (i : Fin (2^h)) (e c : ℕ) :
+ let g := halves h (.inl i)
+ routedCount (physicalTag cuts g) (unitPads cuts g e c) (incomingChecks t Z layout cuts g)
+ (pairCount fit inc (liveCutEquiv h Δ cuts).1 i) = specifiedGroupCount fit inc E layout init cuts g := by
+ simpa only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inl] using
+ routed_specifiedGroupCount fit inc E layout init cuts (halves h (.inl i)) e c
+
+/-- The first tail group obtains its initial code from the middle exponents.
+Each subsequent group parses the canonical code from its incoming cut. -/
+theorem routed_tail_count (cuts : AllCuts h Δ) (i : Fin (2^h)) (e c : ℕ) :
+ let g := halves h (.inr i)
+ let fst := (liveCutEquiv h Δ cuts).1
+ let lst := (liveCutEquiv h Δ cuts).2
+ routedCount (physicalTag cuts g) (unitPads cuts g e c) (incomingChecks t Z layout cuts g)
+ (tailCount E layout (init (fun a => (ExponentTrace.counters fit fst (Fin.last _) a).val)) lst i) =
+ specifiedGroupCount fit inc E layout init cuts g := by
+ simpa only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inr] using
+ routed_specifiedGroupCount fit inc E layout init cuts (halves h (.inr i)) e c
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderAcceptance.lean b/lean/OAI/Computability/VPVNP/LiveHeaderAcceptance.lean
new file mode 100644
index 0000000000..e3122d2c88
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderAcceptance.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.LiveHeaderPaddingReject
+import OAI.Computability.VPVNP.LiveHeaderModeReject
+
+/-!
+# Exact native acceptance and path multiplicity for live headers
+
+Under the stated capacities a compatible, canonically padded header has one
+accepted native path. Every malformed mode or padding assignment has zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeader ChainAssignments
+open scoped Classical
+
+variable {w d : ℕ}
+
+/-- The physical cuts select a tag for this group and both incident fields have valid padding
+under that tag. -/
+def Acceptable (s : Sizes) (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) : Prop :=
+ ∃ tag, physicalTag cuts g = some tag ∧ ∀ side, Fields.ValidPadding s cuts g tag side
+
+theorem accepting_iff (s : Sizes) (base cap : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1)))
+ (bounds : Fields.Bounds s base d w) (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d)
+ (tagFit : stages.length ≤ 2^w) (fuel : 107 ≤ cap) :
+ let P := nativeHeader w s base
+ let m := physicalMemory (d := d) hw advice cuts g
+ (∃ bs rs, runSegment P cap (some 0) m bs = some rs ∧ endState (some 0) rs = none) ↔ Acceptable s cuts g := by
+ dsimp only
+ cases hsel : physicalTag cuts g with
+ | none =>
+ have no := bad_mode_native s base cap hw advice cuts g hsel indices adv bounds.scratch bounds.fit.le tagFit fuel
+ simp [no,Acceptable,hsel]
+ | some tag =>
+ simpa [Acceptable,hsel] using native_padding_iff s base cap hw advice cuts g tag bounds indices adv tagFit fuel hsel
+
+/-- Count native accepting paths using the same global and local budget
+predicate as the processor contraction. -/
+theorem actualPaths_card (s : Sizes) (base cap sites bucket : ℕ) (hw : 4 ≤ w)
+ (advice : CutSchedule.Bits s.advice) (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1)))
+ (bounds : Fields.Bounds s base d w) (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d)
+ (tagFit : stages.length ≤ 2^w) (fuel : 107 ≤ cap) (total : costBound s ≤ sites*bucket) (localFit : 9 ≤ bucket) :
+ let P := nativeHeader w s base
+ let m := physicalMemory (d := d) hw advice cuts g
+ Nat.card (ActualPaths P cap 0 m (withinCaps sites bucket)) = if Acceptable s cuts g then 1 else 0 := by
+ classical
+ dsimp only
+ let P := nativeHeader w s base
+ let m := physicalMemory (d := d) hw advice cuts g
+ let paths := ActualPaths P cap 0 m (withinCaps sites bucket)
+ by_cases ok : Acceptable s cuts g
+ · rw [ite_eq_left ok,Nat.card_eq_one_iff_exists]
+ obtain ⟨tag,hsel,hvalid⟩ := ok
+ obtain ⟨rs,hr,hl,_,_,cost,each,hunique⟩ := valid_native s base cap hw advice cuts g tag bounds indices adv
+ tagFit fuel hsel hvalid
+ have hcap : withinCaps sites bucket rs := ⟨by omega, fun x hx => by have := each x hx; omega⟩
+ let one : paths := ⟨_,rs,hr,hl,hcap⟩
+ refine ⟨one,fun x => ?_⟩
+ obtain ⟨r,ha,he,_⟩ := x.property
+ apply Subtype.ext
+ exact (hunique x.val r ha he).1
+ · rw [ite_eq_right ok]
+ have no := (accepting_iff s base cap hw advice cuts g bounds indices adv tagFit fuel).not.mpr ok
+ have hempty : IsEmpty paths := ⟨fun x => by
+ obtain ⟨rs,hr,hl,_⟩ := x.property
+ exact no ⟨x.val,rs,hr,hl⟩⟩
+ exact @Nat.card_of_isEmpty paths hempty
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderAdvice.lean b/lean/OAI/Computability/VPVNP/LiveHeaderAdvice.lean
new file mode 100644
index 0000000000..771950408e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderAdvice.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.LiveHeaderCutInput
+import OAI.Computability.VPVNP.LiveHeaderBoundedRun
+
+/-!
+# Copying the distributed live advice
+
+Processor `j` holds advice bit `j` in slot one of its physical header. The
+native scan reads each occupied header and writes its bit as a separate word
+in the public advice array. The scratch array starts beyond the processor
+sites, so later stages can still read all four fields at every site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ChainAssignments CutSchedule
+open scoped Fin.CommRing
+
+variable {w d a h Δ : ℕ}
+
+/-- The native table for the advice stage. -/
+abbrev adviceTable := template (copyCell 1) 7
+
+/-- Advice readback, preservation of the packed site headers, and the frame
+for every word outside the allocated advice array. -/
+structure AdviceImage (hw : 4 ≤ w) (advice : Bits a) (cuts : AllCuts h Δ) (g : Fin (2^(h+1)))
+ (base : ℕ) (original out : Memory w) : Prop where
+ copied : ∀ i : Fin a, out (base+i.val) = PrimedInputRAM.encodeBit w (advice i)
+ headers : SiteHeaders d hw advice cuts g out
+ frame : ∀ addr, addr < base ∨ base+a ≤ addr → out addr = original addr
+
+private theorem adviceImage_of_copy {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m out : Memory w} {base : ℕ} (headers : SiteHeaders d hw advice cuts g m)
+ (sites : a ≤ 2^d) (scratch : 2^d ≤ base) (copy : FieldCopy m 1 0 base a out) :
+ AdviceImage (d := d) hw advice cuts g base m out := by
+ refine ⟨?_, ?_, copy.frame⟩
+ · intro i
+ let v : Fin (2^d) := ⟨i.val, i.isLt.trans_le sites⟩
+ have hb := headers.bit v 1
+ change (m i.val).val.testBit (1 : Fin 4).val = distributedBit advice i.val at hb
+ simpa only [Nat.zero_add, hb, distributedBit, dite_eq_left i.isLt] using copy.copied i.val i.isLt
+ · intro v
+ rw [copy.frame v.val (Or.inl (v.isLt.trans_le scratch)), headers v]
+
+private theorem advice_step (hw : 4 ≤ w) (pub : Fin 2 → Word w) (zero : pub 0 = 0)
+ (m : Memory w) (j len : ℕ) (hj : j < len) (disjoint : len ≤ (pub 1).val)
+ (fit : (pub 1).val + len ≤ 2^w) (mem : Memory w) (inv : FieldCopy m 1 0 (pub 1).val j mem) :
+ let P := (adviceTable.instantiate w pub).program
+ ∃ es, execute P 13 (P.start (j : Word w)) mem [] = some ⟨es, some ((j+1 : ℕ) : Word w)⟩ ∧
+ FieldCopy m 1 0 (pub 1).val (j+1) (after mem es) ∧ countProbes es ≤ 2 := by
+ have hjv : (j : Word w).val = j := Fin.val_cast_of_lt (by omega)
+ have dst : (pub 1 + (j : Word w)).val = (pub 1).val+j := by
+ rw [Fin.val_add, hjv, Nat.mod_eq_of_lt (by omega)]
+ have hread := inv.frame j (Or.inl (by omega))
+ obtain ⟨es, rs, ht, hr, _, hp, _⟩ := copyCell_trace hw 1 pub (j : Word w) (fun _ => 0) mem
+ refine ⟨es, ?_, ?_, hp.le⟩
+ · change execute ((template (copyCell 1) 7).instantiate w pub).program (1+(copyCell 1).length)
+ ⟨_,(j : Word w),fun _ => 0,fun _ => 0⟩ mem [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [hr]
+ · rw [trace_after ht, zero, sub_zero, hjv, hread]
+ constructor
+ · intro i hi
+ by_cases he : i = j
+ · simp [writeMemory, dst, he]
+ · simpa [writeMemory, dst, he] using inv.copied i (by omega)
+ · intro addr outside
+ have hn : addr ≠ (pub 1).val+j := by omega
+ simp [writeMemory, dst, hn, inv.frame addr (by omega)]
+
+/-- Execute all occupied advice cells starting with any memory that retains
+the physical headers. Zero-length advice gives an empty scan. -/
+theorem physical_advice_scan_native {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (pub : Fin 2 → Word w) (zero : pub 0 = 0) (sites : a ≤ 2^d) (scratch : 2^d ≤ (pub 1).val)
+ (fit : (pub 1).val+a ≤ 2^w) :
+ let P := (adviceTable.instantiate w pub).program
+ ∃ rs, runSegment P 13 (some 0) m (List.replicate a []) = some rs ∧
+ endState (some 0) rs = some (a : Word w) ∧ rs.length = a ∧
+ (∀ rep ∈ rs, countProbes rep.events ≤ 2) ∧
+ AdviceImage (d := d) hw advice cuts g (pub 1).val m (after m (eventLog rs)) := by
+ obtain ⟨rs, run, last, copy, len, probes⟩ := run_cursor_segment (adviceTable.instantiate w pub).program 13 a 2
+ (FieldCopy m 1 0 (pub 1).val) m (FieldCopy.initial ..)
+ (fun i hi => advice_step hw pub zero m i a hi (sites.trans scratch) fit)
+ exact ⟨rs, run, last, len, probes, adviceImage_of_copy headers sites scratch copy⟩
+
+/-- The bounded advice table executes one active call per bit and closes
+with a zero-probe accepting call. Its final memory contains the same advice
+image, including when the advice array is empty. -/
+theorem physical_advice_bounded_native {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (pub : Fin 2 → Word w) (zero : pub 0 = 0) (sites : a ≤ 2^d) (scratch : 2^d ≤ (pub 1).val)
+ (fit : (pub 1).val+a ≤ 2^w) :
+ let P := (LiveHeaderBounded.machine adviceTable pub (a : Word w)).program
+ ∃ rs, runSegment P 16 (some 0) m (List.replicate (a+1) []) = some rs ∧
+ endState (some 0) rs = none ∧ rs.length = a+1 ∧
+ (∀ rep ∈ rs, countProbes rep.events ≤ 2) ∧
+ AdviceImage (d := d) hw advice cuts g (pub 1).val m (after m (eventLog rs)) := by
+ let P := (LiveHeaderBounded.machine adviceTable pub (a : Word w)).program
+ have apos := Nat.two_pow_pos d
+ have ha : (a : Word w).val = a := Fin.val_cast_of_lt (by omega)
+ obtain ⟨rs, run, last, copy, len, probes⟩ := run_cursor_segment P 16 a 2 (FieldCopy m 1 0 (pub 1).val) m
+ (FieldCopy.initial ..) (by
+ intro j hj mem inv
+ have hjv : (j : Word w).val = j := Fin.val_cast_of_lt (by omega)
+ have hlt : (j : Word w) < (a : Word w) := Fin.lt_def.mpr (by rwa [hjv, ha])
+ obtain ⟨es, he, hnext, hp⟩ := advice_step hw pub zero m j a hj (sites.trans scratch) fit mem inv
+ have active := LiveHeaderBounded.execute_active adviceTable pub (a : Word w) 13 (j : Word w) hlt mem []
+ dsimp only at active
+ rw [he] at active
+ exact ⟨.tick :: .tick :: .tick :: es, active, hnext, hp⟩)
+ let closed := LiveHeaderBounded.closedReport w
+ have halt := LiveHeaderBounded.execute_closed adviceTable pub (a : Word w) 12 (a : Word w) le_rfl
+ (after m (eventLog rs)) []
+ dsimp only at halt
+ refine ⟨rs ++ [closed], ?_, ?_, by simp [len], ?_, ?_⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, run]
+ simp only [Option.bind_some, last, runSegment]
+ rw [halt]
+ rfl
+ · rw [endState_append]
+ rfl
+ · intro rep hrep
+ rcases List.mem_append.mp hrep with h | h
+ · exact probes rep h
+ · obtain rfl := List.mem_singleton.mp h
+ exact Nat.zero_le _
+ · have he : after m (eventLog (rs ++ [closed])) = after m (eventLog rs) := by
+ simp only [eventLog, List.flatMap_append, List.flatMap_singleton, after, List.foldl_append]
+ rfl
+ rw [he]
+ exact adviceImage_of_copy headers sites scratch copy
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderAdviceStages.lean b/lean/OAI/Computability/VPVNP/LiveHeaderAdviceStages.lean
new file mode 100644
index 0000000000..2f395d012c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderAdviceStages.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.LiveHeaderIndexStages
+import OAI.Computability.VPVNP.LiveHeaderAdvice
+import OAI.Computability.VPVNP.LiveHeaderPrefix
+
+/-! # The distributed advice scan in the native header table -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ChainAssignments LiveHeaderSchedule LiveHeader
+open scoped Fin.CommRing
+
+variable {w d : ℕ}
+
+/-- Public operands for scanning the distributed advice into its allocated header array,
+starting at cursor zero. -/
+def adviceWords (w : ℕ) (s : Sizes) (base : ℕ) : Fin 2 → Word w := ![0, Fin.ofNat _ (adviceBase s base)]
+
+theorem advice_row (w : ℕ) (s : Sizes) (base : ℕ) :
+ rowData w s base .advice ∘ includeFin (by decide : 2+1 ≤ 17) =
+ LiveHeaderBounded.publicData (adviceWords w s base) (Fin.ofNat _ s.advice) := by
+ funext j
+ fin_cases j <;> rfl
+
+theorem advice_step (hw : 4 ≤ w) (pub : Fin 2 → Word w) (zero : pub 0 = 0) (bound : ℕ)
+ (fit : (pub 1).val+bound ≤ 2^w) (addr : Word w) (htag : addr.val < (pub 1).val)
+ (i : ℕ) (hi : i < bound) (m : Memory w) (bits : List Bool) (rep : Report w) {fuel : ℕ}
+ (h : execute (adviceTable.instantiate w pub).program fuel
+ ((adviceTable.instantiate w pub).program.start (i : Word w)) m bits = some rep) :
+ rep.result = some ((i+1 : ℕ) : Word w) ∧ after m rep.events addr.val = m addr.val := by
+ obtain ⟨es, rs', ht, hresult, _, _, _⟩ := copyCell_trace hw 1 pub (i : Word w) (fun _ => 0) m
+ have he : execute (adviceTable.instantiate w pub).program 13
+ ((adviceTable.instantiate w pub).program.start (i : Word w)) m [] = some ⟨es, some ((i+1 : ℕ) : Word w)⟩ := by
+ change execute (adviceTable.instantiate w pub).program (1+(copyCell 1).length) ⟨_,(i : Word w),fun _ => 0,fun _ => 0⟩ _ [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [hresult]
+ obtain ⟨_, rfl⟩ := execute_empty_forces_anyFuel he h
+ refine ⟨rfl, ?_⟩
+ change after m es addr.val = m addr.val
+ rw [trace_after ht,zero,sub_zero]
+ have hiv : (i : Word w).val = i := Fin.val_cast_of_lt (by omega)
+ have hd : (pub 1 + (i : Word w)).val = (pub 1).val+i := by rw [Fin.val_add, hiv, Nat.mod_eq_of_lt (by omega)]
+ simp [writeMemory,hd,show addr.val ≠ (pub 1).val+i by omega]
+
+theorem advice_stage_native (s : Sizes) (base : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (m : Memory w)
+ (headers : SiteHeaders d hw advice cuts g m) (sites : s.advice ≤ 2^d)
+ (scratch : 2^d ≤ base) (fit : limit s base ≤ 2^w) :
+ let P := ((stageTemplate .advice).2.instantiate w (rowData w s base .advice)).program
+ ∃ rs, runSegment P 16 (some 0) m (List.replicate (calls s .advice) []) = some rs ∧
+ endState (some 0) rs = none ∧ rs.length = calls s .advice ∧
+ (∀ rep ∈ rs, rep.probes ≤ probes .advice) ∧
+ LiveStageLink.PreservesTagOnReturns (Fin.ofNat _ base) m rs ∧
+ AdviceImage (d := d) hw advice cuts g (adviceBase s base) m (after m (eventLog rs)) := by
+ let pub := adviceWords w s base
+ let addr : Word w := Fin.ofNat _ base
+ have hrow (bits : List (List Bool)) :
+ runSegment ((stageTemplate .advice).2.instantiate w (rowData w s base .advice)).program 16 (some 0) m bits =
+ runSegment (LiveHeaderBounded.machine adviceTable pub (s.advice : Word w)).program 16 (some 0) m bits := by
+ change runSegment ((entry (LiveHeaderBounded.bounded adviceTable)).2.instantiate w (rowData w s base .advice)).program _ _ _ _ = _
+ rw [run_entry,advice_row]
+ rfl
+ dsimp only
+ rw [limit_eq] at fit
+ have dst : adviceBase s base = base + 17 + 3*(s.h+2) := by
+ dsimp [adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase]
+ omega
+ by_cases empty : s.advice = 0
+ · let rep := LiveHeaderBounded.closedReport w
+ have he := LiveHeaderBounded.execute_closed adviceTable pub (s.advice : Word w) 12 0
+ (by simp [empty]) m []
+ dsimp only at he
+ refine ⟨[rep], ?_, rfl, by simp [calls, empty], ?_, LiveStageLink.PreservesTagOnReturns.singleton_accept _ _ _ rfl, ?_⟩
+ · rw [hrow, show calls s .advice = 1 by simp [calls,empty], List.replicate_one,runSegment,he]
+ rfl
+ · intro r hr; obtain rfl := List.mem_singleton.mp hr; exact Nat.zero_le _
+ · refine ⟨fun i => ?_, headers, fun _ _ => rfl⟩
+ have := i.isLt; omega
+ have hv : (pub 1).val = adviceBase s base := Nat.mod_eq_of_lt (by rw [dst]; omega)
+ have ha : (s.advice : Word w).val = s.advice := Fin.val_cast_of_lt (by omega)
+ have hfit : (pub 1).val+s.advice ≤ 2^w := by rw [hv,dst]; omega
+ have hscratch : 2^d ≤ (pub 1).val := by rw [hv,dst]; omega
+ have htag : addr.val < (pub 1).val := by
+ change base % (2^w) < _
+ rw [Nat.mod_eq_of_lt (by omega), hv, dst]; omega
+ obtain ⟨raw, hr, _, hl, hp, image⟩ := physical_advice_scan_native headers pub rfl sites hscratch hfit
+ have frame := runSegment_cursor_frame (adviceTable.instantiate w pub).program 13 s.advice addr
+ (fun i hi mem rep he => advice_step hw pub rfl _ hfit addr htag i hi mem [] rep he)
+ 0 s.advice m raw (by omega) hr
+ have complete := LiveHeaderBounded.runSegment_cursor_complete adviceTable pub (s.advice : Word w)
+ (by decide : 0 < 13) 0 m (List.replicate s.advice []) raw (by rw [List.length_replicate,Nat.zero_add,ha]) hr
+ (fun i hi mem bits rep he => (advice_step hw pub rfl _ hfit addr htag i (by rwa [ha] at hi) mem bits rep he).1)
+ let outs := raw.map LiveHeaderBounded.activeReport ++ [LiveHeaderBounded.closedReport w]
+ refine ⟨outs, ?_, ?_, ?_, ?_, guarded_frame frame, ?_⟩
+ · rw [hrow, show calls s .advice = s.advice+1 from rfl, List.replicate_succ']
+ exact complete
+ · rw [show outs = _ ++ _ from rfl, endState_append]; rfl
+ · simp [outs,hl,calls]
+ · intro r hm
+ rcases List.mem_append.mp hm with hh | hh
+ · obtain ⟨x,hx,rfl⟩ := List.mem_map.mp hh; exact hp x hx
+ · obtain rfl := List.mem_singleton.mp hh; exact Nat.zero_le _
+ · have he : after m (eventLog outs) = after m (eventLog (raw.map LiveHeaderBounded.activeReport)) := by
+ simp only [outs,eventLog,List.flatMap_append,after,List.foldl_append,List.flatMap_singleton]
+ rfl
+ rw [he,LiveHeaderBounded.after_activeReports,← hv]
+ exact image
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderAllocated.lean b/lean/OAI/Computability/VPVNP/LiveHeaderAllocated.lean
new file mode 100644
index 0000000000..7ba05b0905
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderAllocated.lean
@@ -0,0 +1,367 @@
+import OAI.Computability.VPVNP.LiveHeaderFields
+import OAI.Computability.VPVNP.LiveHeaderRuns
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PrimedCounterRenameRun
+
+/-!
+# Fixed-capacity scans with a runtime field count
+
+Each call reads the count from the descriptor and tests the current position
+relative to the phase's first cursor. Occupied positions run the actual
+payload copy or padding guard. An idle position advances the cursor without
+reading the field offset or the packed header. The scheduling capacity can
+therefore be public while the length of the occupied interval is private.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader.Allocated
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM PrimedCounter
+
+/-- Public operand indices identifying the first cursor, source-offset cell, destination base,
+and runtime count for a bounded field scan. -/
+structure Parameters where
+ /-- Index of the public word from which the field-relative cursor is measured. -/
+ firstCursor : Fin 16
+ /-- Index of the public address of the descriptor cell holding the packed source offset. -/
+ srcOffsetAddress : Fin 16
+ /-- Index of the public destination base used to store copied field bits. -/
+ destinationBase : Fin 16
+ /-- Index of the public address of the field's live count word. -/
+ countAddress : Fin 16
+
+private def setupOps (p : Parameters) : List (Op 48 16) :=
+ [.stateWord 4, .publicWord 6 p.firstCursor, .binary .sub 8 4 6,
+ .publicWord 6 p.countAddress, .read 9 6]
+
+private def setup (p : Parameters) := lines (setupOps p) (by simp [setupOps])
+
+private def cellRegs : Fin 12 ↪ Fin 48 where
+ toFun i := i.castLE (by decide)
+ inj' _ _ h := Fin.ext (congrArg (Fin.val : Fin 48 → ℕ) h)
+
+private def cellParams (p : Parameters) : Fin 3 → Fin 16 :=
+ ![p.firstCursor, p.srcOffsetAddress, p.destinationBase]
+
+private def cellOps (slot : Fin 4) (padding : Bool) :=
+ if padding then checkPaddingCell slot else copyFieldCell slot
+
+private theorem cell_ne_nil (slot : Fin 4) (padding : Bool) : cellOps slot padding ≠ [] := by
+ cases padding <;> exact List.cons_ne_nil _ _
+
+private def activeCell (p : Parameters) (slot : Fin 4) (padding : Bool) : Flow 48 16 :=
+ renameFlow cellRegs (cellParams p) (lines (cellOps slot padding) (cell_ne_nil slot padding))
+
+private def idleCell : Flow 48 16 := straight (.constant 3 1) [.binary .add 7 4 3]
+
+/-- Register 7 contains the successor on every normal return. -/
+def block (p : Parameters) (slot : Fin 4) (padding : Bool) : Flow 48 16 :=
+ .seq (setup p) (.ifLt 8 9 (activeCell p slot padding) idleCell)
+
+/-- The allocated-field worker table for either copying or padding-checking the selected packed
+bit slot. -/
+def table (p : Parameters) (slot : Fin 4) (padding : Bool) :=
+ (block p slot padding).template (some 7)
+
+variable {w : ℕ}
+
+/-- The field-relative cursor obtained by subtracting the phase's first cursor. -/
+def position (p : Parameters) (pub : Fin 16 → Word w) (state : Word w) :=
+ state - pub p.firstCursor
+
+/-- The cursor lies within the occupied prefix specified by the live count word. -/
+def Active (p : Parameters) (pub : Fin 16 → Word w) (state : Word w) (m : Memory w) :=
+ position p pub state < m (pub p.countAddress).val
+
+/-- The selected slot bit read from the packed source word at the current field-relative
+position. -/
+def bitAt (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w) (state : Word w) (m : Memory w) :=
+ (m (m (pub p.srcOffsetAddress).val + position p pub state).val).val.testBit slot.val
+
+/-- The address to which an occupied payload bit is copied. -/
+def destination (p : Parameters) (pub : Fin 16 → Word w) (state : Word w) :=
+ pub p.destinationBase + position p pub state
+
+private def loaded (p : Parameters) (pub : Fin 16 → Word w) (state : Word w)
+ (rs : Regs w 48) (m : Memory w) : Regs w 48 :=
+ let a := Function.update rs 4 state
+ let b := Function.update a 6 (pub p.firstCursor)
+ let c := Function.update b 8 (position p pub state)
+ let d := Function.update c 6 (pub p.countAddress)
+ Function.update d 9 (m (pub p.countAddress).val)
+
+private def setupEvents (p : Parameters) (pub : Fin 16 → Word w) (m : Memory w) : List (Event w) :=
+ [.tick, .tick, .tick, .tick, .read (pub p.countAddress) (m (pub p.countAddress).val)]
+
+private theorem setup_trace (p : Parameters) (pub : Fin 16 → Word w) (state : Word w)
+ (rs : Regs w 48) (m : Memory w) :
+ trace pub state (setupOps p) rs m = some (setupEvents p pub m, loaded p pub state rs m, m) := rfl
+
+/-- The complete event log, including the count read, witnesses the effect on
+memory and the cost of the successful call. -/
+abbrev Returns (p : Parameters) (slot : Fin 4) (padding : Bool) (pub : Fin 16 → Word w)
+ (state : Word w) (rs : Regs w 48) (m final : Memory w) (steps probes : ℕ) : Prop :=
+ ∃ es out, Flow.Exec pub state (block p slot padding) rs m es out final ∧ out 7 = state+1 ∧
+ after m es = final ∧ es.length = steps ∧ countProbes es = probes ∧ choiceBits es = []
+
+private theorem active_returns (p : Parameters) (slot : Fin 4) (padding : Bool) (pub : Fin 16 → Word w)
+ (state : Word w) (rs : Regs w 48) (m final : Memory w) (ha : Active p pub state m)
+ {es : List (Event w)} {small : Regs w 12} {n q : ℕ}
+ (run : trace (pub ∘ cellParams p) state (cellOps slot padding)
+ (loaded p pub state rs m ∘ cellRegs) m = some (es,small,final))
+ (next : small 7 = state+1) (hlen : es.length = n) (hpr : countProbes es = q)
+ (hbits : choiceBits es = []) :
+ Returns p slot padding pub state rs m final (6+n) (1+q) := by
+ let r := loaded p pub state rs m
+ have hs := Admin.exec_lines_iff_trace (by simp [setupOps]) |>.mpr (setup_trace p pub state rs m)
+ obtain ⟨out, h, he, _⟩ := liftExec cellRegs (cellParams p) pub
+ ((Admin.exec_lines_iff_trace (cell_ne_nil slot padding)).mpr run) r rfl
+ have hh : r 8 < r 9 := ha
+ refine ⟨setupEvents p pub m ++ .tick :: es, out, hs.seq (.ifLtYes hh h),
+ (congrFun he 7).trans next, ?_, ?_, ?_, hbits⟩
+ · change after m es = final
+ exact trace_after run
+ · change es.length + 6 = 6+n
+ omega
+ · change 1 + countProbes es = _
+ rw [hpr]
+
+/-- An active payload call copies the selected bit and advances the cursor.
+The four probes are count, offset, packed word, and destination. -/
+theorem copy_exec (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (state : Word w) (rs : Regs w 48) (m : Memory w) (ha : Active p pub state m) :
+ Returns p slot false pub state rs m
+ (writeMemory m (destination p pub state) (encodeBit w (bitAt p slot pub state m))) 21 4 := by
+ obtain ⟨_, _, h, hn, hl, hp, hb⟩ := copyFieldCell_trace hw slot (pub ∘ cellParams p) state
+ (loaded p pub state rs m ∘ cellRegs) m
+ exact active_returns p slot false pub state rs m _ ha h hn hl hp hb
+
+/-- Occupied zero padding passes the guard and leaves memory unchanged. -/
+theorem padding_exec (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (state : Word w) (rs : Regs w 48) (m : Memory w) (ha : Active p pub state m)
+ (hz : bitAt p slot pub state m = false) : Returns p slot true pub state rs m m 20 3 := by
+ have h := checkPaddingCell_trace hw slot (pub ∘ cellParams p) state
+ (loaded p pub state rs m ∘ cellRegs) m
+ have hbit : (m (sourceSite (pub ∘ cellParams p) state m).val).val.testBit slot.val = false := hz
+ simp only [hbit, Bool.false_eq_true, ↓reduceIte] at h
+ obtain ⟨_, _, h, hn, hl, hp, hb⟩ := h
+ exact active_returns p slot true pub state rs m m ha h hn hl hp hb
+
+/-- At every unoccupied position the count is the only external read. -/
+theorem idle_exec (p : Parameters) (slot : Fin 4) (padding : Bool) (pub : Fin 16 → Word w)
+ (state : Word w) (rs : Regs w 48) (m : Memory w) (ha : ¬ Active p pub state m) :
+ Returns p slot padding pub state rs m m 8 1 := by
+ let r := loaded p pub state rs m
+ let u := Function.update r (3 : Fin 48) (1 : Word w)
+ let out := Function.update u (7 : Fin 48) (state+1)
+ have hs := Admin.exec_lines_iff_trace (by simp [setupOps]) |>.mpr (setup_trace p pub state rs m)
+ have hi : Flow.Exec pub state idleCell r m [.tick,.tick] out m := (Flow.Exec.line rfl).seq (.line rfl)
+ have hh : ¬r 8 < r 9 := ha
+ exact ⟨_,out,hs.seq (.ifLtNo hh hi), rfl, rfl, rfl, rfl, rfl⟩
+
+/-- No successful derivation can bypass a failing guard on an occupied
+padding position, whatever the initial register file. -/
+theorem padding_rejects (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (state : Word w) (rs : Regs w 48) (m : Memory w) (ha : Active p pub state m)
+ (hn : bitAt p slot pub state m = true) {es out final} :
+ ¬ Flow.Exec pub state (block p slot true) rs m es out final := by
+ intro h
+ cases h with
+ | seq first branch =>
+ have h₁ := (Admin.exec_lines_iff_trace (by simp [setupOps])).mp first
+ rw [setup_trace] at h₁
+ obtain ⟨rfl, rfl, rfl⟩ := Option.some.inj h₁
+ cases branch with
+ | ifLtNo hbad _ => exact hbad ha
+ | ifLtYes _ body =>
+ have ht := (Admin.exec_lines_iff_trace (cell_ne_nil slot true)).mp
+ (restrictExec cellRegs (cellParams p) pub _ body).1
+ have hfail := checkPaddingCell_trace hw slot (pub ∘ cellParams p) state
+ (loaded p pub state rs m ∘ cellRegs) m
+ have hbit : (m (sourceSite (pub ∘ cellParams p) state m).val).val.testBit slot.val = true := hn
+ simp only [hbit, ↓reduceIte] at hfail
+ change trace _ _ (checkPaddingCell slot) _ _ = some _ at ht
+ rw [hfail] at ht
+ contradiction
+
+/-- Every successful execution, on any initial register file and memory,
+consists entirely of deterministic instructions. -/
+theorem exec_choices {p : Parameters} {slot : Fin 4} {padding : Bool} {pub : Fin 16 → Word w}
+ {state : Word w} {rs m es out final} (run : Flow.Exec pub state (block p slot padding)
+ rs m es out final) : choiceBits es = [] := by
+ cases run with
+ | seq pre branch =>
+ rw [Flow.choiceBits_append, Admin.trace_choiceBits ((Admin.exec_lines_iff_trace
+ (by simp [setupOps])).mp pre), List.nil_append]
+ cases branch with
+ | ifLtYes _ body =>
+ simp only [choiceBits]
+ exact Admin.trace_choiceBits ((Admin.exec_lines_iff_trace (cell_ne_nil slot padding)).mp
+ (restrictExec cellRegs (cellParams p) pub _ body).1)
+ | ifLtNo _ body =>
+ simp only [choiceBits]
+ exact Admin.trace_choiceBits ((Admin.exec_lines_iff_trace
+ (ops := [Op.constant (r := 48) (k := 16) 3 1, .binary .add 7 4 3]) (by decide)).mp body)
+
+/-- A successful block has the same effect in the native fixed table when
+the allotted fuel includes its return instruction. -/
+theorem native_of_returns {p : Parameters} {slot : Fin 4} {padding : Bool} {pub : Fin 16 → Word w}
+ {state : Word w} {m final : Memory w} {steps probes fuel : ℕ}
+ (h : Returns p slot padding pub state (fun _ => 0) m final steps probes) (hf : steps < fuel) :
+ let P := ((table p slot padding).instantiate w pub).program
+ ∃ es, execute P fuel (P.start state) m [] = some ⟨es, some (state+1)⟩ ∧
+ after m es = final ∧ es.length = steps ∧ countProbes es = probes ∧ choiceBits es = [] := by
+ obtain ⟨es,out,run,hnext,hmem,hlen,hprobes,hbits⟩ := h
+ refine ⟨es, ?_, hmem, hlen, hprobes, hbits⟩
+ apply (Flow.template_execute_iff (block p slot padding) (some 7) pub state
+ (fun _ => 0) (fun _ => 0) m fuel [] _).mpr
+ exact ⟨out,final,run,congrArg some hnext.symm,hlen.trans_lt hf,hbits⟩
+
+/-- An arbitrary successful native report realizes the very same cursor,
+memory effect and cost. This also accounts for surplus choice tapes and
+arbitrary proposed fuel bounds. -/
+theorem native_report_of_returns {p : Parameters} {slot : Fin 4} {padding : Bool}
+ {pub : Fin 16 → Word w} {state : Word w} {m final : Memory w} {steps probes fuel : ℕ}
+ {bits : List Bool} {report : Report w}
+ (h : Returns p slot padding pub state (fun _ => 0) m final steps probes)
+ (hr : let P := ((table p slot padding).instantiate w pub).program
+ execute P fuel (P.start state) m bits = some report) :
+ bits = [] ∧ report.result = some (state+1) ∧ after m report.events = final ∧
+ report.events.length = steps ∧ countProbes report.events = probes := by
+ let P := ((table p slot padding).instantiate w pub).program
+ have iffRun := Flow.template_execute_iff (block p slot padding) (some 7) pub state
+ (fun _ => 0) (fun _ => 0) m
+ obtain ⟨r,m',run,hnext,hlen,hbits⟩ := (iffRun fuel bits report).mp hr
+ have hno := exec_choices run
+ obtain rfl : bits = [] := hbits.symm.trans hno
+ let budget := fuel + steps + 1
+ have hmore : execute P budget (P.start state) m [] = some report :=
+ (iffRun budget [] report).mpr ⟨r,m',run,hnext,by dsimp [budget]; omega,hno⟩
+ obtain ⟨es,he,hm,hl,hp,_⟩ := native_of_returns h (show steps < budget by dsimp [budget]; omega)
+ obtain rfl : report = ⟨es,some (state+1)⟩ := Option.some.inj (hmore.symm.trans he)
+ exact ⟨rfl,rfl,hm,hl,hp⟩
+
+/-- Failing active padding rejects the native call for every choice tape and
+fuel bound. -/
+theorem padding_native_rejects (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (state : Word w) (m : Memory w) (ha : Active p pub state m) (hn : bitAt p slot pub state m = true)
+ (fuel : ℕ) (bits : List Bool) :
+ let P := ((table p slot true).instantiate w pub).program
+ execute P fuel (P.start state) m bits = none := by
+ let P := ((table p slot true).instantiate w pub).program
+ change execute P fuel (P.start state) m bits = none
+ cases h : execute P fuel (P.start state) m bits with
+ | none => rfl
+ | some out =>
+ obtain ⟨r,m',hr,_⟩ := (Flow.template_execute_iff (block p slot true) (some 7) pub state
+ (fun _ => 0) (fun _ => 0) m fuel bits out).mp h
+ exact (padding_rejects hw p slot pub state _ m ha hn hr).elim
+
+/-- Every successful allocated cell, including an idle padding check, is
+deterministic and advances the persistent cursor. -/
+theorem report_successor (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (padding : Bool)
+ (pub : Fin 16 → Word w) (state : Word w) (m : Memory w) (bits : List Bool) (fuel : ℕ) {rep : Report w}
+ (hr : let P := ((table p slot padding).instantiate w pub).program
+ execute P fuel (P.start state) m bits = some rep) :
+ bits = [] ∧ rep.result = some (state+1) := by
+ have use {padding : Bool} {m' : Memory w} {n q : ℕ}
+ (ret : Returns p slot padding pub state (fun _ => 0) m m' n q)
+ (call : let P := ((table p slot padding).instantiate w pub).program
+ execute P fuel (P.start state) m bits = some rep) : bits = [] ∧ rep.result = some (state+1) := by
+ have hp := native_report_of_returns ret call
+ exact ⟨hp.1,hp.2.1⟩
+ by_cases ha : Active p pub state m
+ · cases padding
+ · exact use (copy_exec hw p slot pub state _ m ha) hr
+ · cases hz : bitAt p slot pub state m with
+ | false => exact use (padding_exec hw p slot pub state _ m ha hz) hr
+ | true =>
+ have hf := padding_native_rejects hw p slot pub state m ha hz fuel bits
+ have impossible : (none : Option (Report w)) = some rep := hf.symm.trans hr
+ contradiction
+ · exact use (idle_exec p slot padding pub state _ m ha) hr
+
+private def readOnly {r k : ℕ} : Op r k → Bool
+ | .write .. => false
+ | _ => true
+
+private theorem trace_readOnly {r k : ℕ} {pub : Fin k → Word w} {state : Word w} {ops : List (Op r k)}
+ {rs out : Regs w r} {m final : Memory w} {es : List (Event w)}
+ (ht : trace pub state ops rs m = some (es,out,final)) (hs : ops.all readOnly = true)
+ (replay : Memory w) : after replay es = replay := by
+ induction ops generalizing rs m es with
+ | nil => simp [trace] at ht; rw [ht.1]; rfl
+ | cons op rest ih =>
+ obtain ⟨hhead,htail⟩ := Bool.and_eq_true_iff.mp hs
+ cases he : op.effect pub state rs m with
+ | none => simp [trace,he] at ht
+ | some u =>
+ obtain ⟨e,rs',m'⟩ := u
+ have hupdate : update replay e = replay := by
+ cases op <;> simp only [readOnly,Op.effect,Option.some.injEq,Prod.mk.injEq] at he hhead
+ all_goals first | contradiction | (rw [← he.1]; rfl) | (split at he <;> simp at he; rw [← he.1]; rfl)
+ cases hr : trace pub state rest rs' m' with
+ | none => simp [trace,he,hr] at ht
+ | some u =>
+ obtain ⟨es',out',final'⟩ := u
+ simp [trace,he,hr] at ht
+ obtain ⟨hh,rfl,rfl⟩ := ht
+ rw [← hh]
+ change after (update replay e) es' = replay
+ rw [hupdate]
+ exact ih hr htail
+
+private theorem active_frame {p : Parameters} {slot : Fin 4} {padding : Bool} {pub : Fin 16 → Word w}
+ {state : Word w} {rs : Regs w 48} {m final : Memory w} {es out}
+ (he : Flow.Exec pub state (activeCell p slot padding) rs m es out final) (addr : Word w)
+ (safe : padding = true ∨ addr ≠ destination p pub state) (replay : Memory w) :
+ after replay es addr.val = replay addr.val := by
+ have ht := (Admin.exec_lines_iff_trace (cell_ne_nil slot padding)).mp
+ (restrictExec cellRegs (cellParams p) pub _ he).1
+ cases padding with
+ | false =>
+ have hn := safe.resolve_left (by decide)
+ have hnv : addr.val ≠ (destination p pub state).val := fun eq => hn (Fin.ext eq)
+ simp (config := { decide := true }) [cellOps, copyFieldCell,locateCell,fetch,trace,Op.effect,
+ Function.update] at ht
+ rw [← ht.1]
+ change writeMemory replay (destination p pub state) _ addr.val = replay addr.val
+ exact ite_eq_right hnv
+ | true =>
+ rw [trace_readOnly ht (by rfl) replay]
+
+/-- A report preserves the reserved tag under replay on every memory.
+Only an active copy has a write, and it targets the current destination. -/
+theorem report_frame (p : Parameters) (slot : Fin 4) (padding : Bool) (pub : Fin 16 → Word w)
+ (state : Word w) (m : Memory w) (bits : List Bool) (fuel : ℕ) {rep : Report w}
+ (hr : let P := ((table p slot padding).instantiate w pub).program
+ execute P fuel (P.start state) m bits = some rep) (addr : Word w)
+ (safe : Active p pub state m → padding = true ∨ addr ≠ destination p pub state)
+ (replay : Memory w) : after replay rep.events addr.val = replay addr.val := by
+ obtain ⟨out,final,he,_⟩ := (Flow.template_execute_iff (block p slot padding) (some 7) pub state
+ (fun _ => 0) (fun _ => 0) m fuel bits rep).mp hr
+ generalize hs : rep.events = es at he ⊢
+ cases he with
+ | seq pre branch =>
+ have hpre := (Admin.exec_lines_iff_trace (by simp [setupOps])).mp pre
+ rw [setup_trace] at hpre
+ obtain ⟨rfl,rfl,rfl⟩ := Option.some.inj hpre
+ cases branch with
+ | ifLtYes ht body =>
+ change after replay _ addr.val = replay addr.val
+ exact active_frame body addr (safe ht) replay
+ | ifLtNo _ body =>
+ have hb := (Admin.exec_lines_iff_trace
+ (ops := [Op.constant (r := 48) (k := 16) 3 1, .binary .add 7 4 3]) (by decide)).mp body
+ simp [trace,Op.effect] at hb
+ rw [← hb.1]
+ rfl
+
+end LiveHeader.Allocated
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderAllocatedRuns.lean b/lean/OAI/Computability/VPVNP/LiveHeaderAllocatedRuns.lean
new file mode 100644
index 0000000000..686c5407ac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderAllocatedRuns.lean
@@ -0,0 +1,402 @@
+import OAI.Computability.VPVNP.LiveHeaderAllocated
+import OAI.Computability.VPVNP.LiveHeaderCutInput
+import OAI.Computability.VPVNP.LiveHeaderBoundedRun
+import OAI.Computability.VPVNP.LiveStageSegments
+
+/-!
+# Fixed-capacity native live-cut scans
+
+Each stage performs exactly its public number of calls. The runtime count
+occupies a prefix, followed by idle calls that only read the count. Every
+successful report preserves the reserved tag under arbitrary replay. A final
+bounded call accepts and transfers control to the next stage.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader.Allocated
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM ChainAssignments CutSchedule
+open scoped Fin.CommRing
+
+variable {w d a h Δ : ℕ}
+
+/-- Instantiate the allocated-field worker on the selected slot, copy or padding mode, and
+public operands. -/
+abbrev program (p : Parameters) (slot : Fin 4) (pad : Bool) (pub : Fin 16 → Word w) :=
+ ((table p slot pad).instantiate w pub).program
+
+/-- An address precedes the field array or lies at or beyond its exclusive end. -/
+def Outside (base len addr : ℕ) : Prop := addr < base ∨ base+len ≤ addr
+
+/-- Runtime offset and count were written by the descriptor stage. -/
+structure Loaded (p : Parameters) (pub : Fin 16 → Word w) (iv : ℕ × ℕ) (m : Memory w) : Prop where
+ offset : (m (pub p.srcOffsetAddress).val).val = iv.1
+ count : (m (pub p.countAddress).val).val = iv.2
+
+/-- Public scan capacity and bounds needed to read the occupied source sites. -/
+structure Sizes (p : Parameters) (pub : Fin 16 → Word w) (iv : ℕ × ℕ) (cap : ℕ) : Prop where
+ zero : pub p.firstCursor = 0
+ occupied : iv.2 ≤ cap
+ capFit : cap < 2^w
+ sourceFit : iv.1+iv.2 ≤ 2^w
+
+/-- The occupied destination is disjoint from its sources, count and offset. -/
+structure CopyLayout (p : Parameters) (pub : Fin 16 → Word w) (iv : ℕ × ℕ) : Prop where
+ sourceBefore : iv.1+iv.2 ≤ (pub p.destinationBase).val
+ destinationFit : (pub p.destinationBase).val+iv.2 ≤ 2^w
+ offsetOutside : Outside (pub p.destinationBase).val iv.2 (pub p.srcOffsetAddress).val
+ countOutside : Outside (pub p.destinationBase).val iv.2 (pub p.countAddress).val
+
+private theorem index_val {p pub iv cap} (size : Sizes (w := w) p pub iv cap) {j : ℕ} (hj : j < cap) :
+ (j : Word w).val = j := Fin.val_cast_of_lt (hj.trans size.capFit)
+
+private theorem active_iff {p pub iv cap} (size : Sizes (w := w) p pub iv cap)
+ {j : ℕ} (hj : j < cap) {m : Memory w} (count : (m (pub p.countAddress).val).val = iv.2) :
+ Active p pub (j : Word w) m ↔ j < iv.2 := by
+ unfold Active position
+ rw [size.zero, sub_zero]
+ change (j : Word w).val < _ ↔ _
+ rw [index_val size hj,count]
+
+private theorem address_add (base : Word w) {j : ℕ} (fit : base.val+j < 2^w) :
+ (base+(j : Word w)).val = base.val+j := by
+ rw [Fin.val_add, Fin.val_cast_of_lt (show j < 2^w by omega), Nat.mod_eq_of_lt fit]
+
+private theorem destination_val {p pub iv cap} (size : Sizes (w := w) p pub iv cap)
+ (layout : CopyLayout p pub iv) {j : ℕ} (hj : j < iv.2) :
+ (destination p pub (j : Word w)).val = (pub p.destinationBase).val+j := by
+ rw [destination,position,size.zero,sub_zero,address_add _ (by have := layout.destinationFit; omega)]
+
+private theorem read_bit {p pub iv cap} (size : Sizes (w := w) p pub iv cap) {m : Memory w}
+ (offset : (m (pub p.srcOffsetAddress).val).val = iv.1) (slot : Fin 4) {j : ℕ} (hj : j < iv.2) :
+ bitAt p slot pub (j : Word w) m = (m (iv.1+j)).val.testBit slot.val := by
+ unfold bitAt position
+ rw [size.zero,sub_zero,address_add _ (by rw [offset]; have := size.sourceFit; omega),offset]
+
+private theorem run_good {C : Type*} (P : Program w C) (fuel cap : ℕ) (m : Memory w)
+ (inv : ℕ → Memory w → Prop) (good : Report w → Prop) (init : inv 0 m)
+ (step : ∀ j < cap, ∀ mem, inv j mem → ∃ es,
+ execute P fuel (P.start (j : Word w)) mem [] = some ⟨es,some ((j+1 : ℕ) : Word w)⟩ ∧
+ inv (j+1) (after mem es) ∧ good ⟨es,some ((j+1 : ℕ) : Word w)⟩) :
+ ∃ rs, runSegment P fuel (some 0) m (List.replicate cap []) = some rs ∧
+ endState (some 0) rs = some (cap : Word w) ∧ inv cap (after m (eventLog rs)) ∧
+ rs.length = cap ∧ ∀ r ∈ rs, good r := by
+ have go (n : ℕ) (hn : n ≤ cap) : ∃ rs, runSegment P fuel (some 0) m (List.replicate n []) = some rs ∧
+ endState (some 0) rs = some (n : Word w) ∧ inv n (after m (eventLog rs)) ∧
+ rs.length = n ∧ ∀ r ∈ rs, good r := by
+ induction n with
+ | zero => exact ⟨[],rfl,rfl,init,rfl,by simp⟩
+ | succ n ih =>
+ obtain ⟨rs,hr,he,hi,hlen,hg⟩ := ih (by omega)
+ obtain ⟨es,hs,hnext,hrep⟩ := step n (by omega) _ hi
+ let r : Report w := ⟨es,some ((n+1 : ℕ) : Word w)⟩
+ refine ⟨rs++[r], ?_, ?_, ?_, by simp [hlen], ?_⟩
+ · rw [List.replicate_succ',PrimedSchedule.runSegment_append,hr]
+ simp only [Option.bind_some,he,runSegment,hs,Option.map_some,r]
+ · rw [endState_append]; rfl
+ · simpa only [eventLog,List.flatMap_append,List.flatMap_singleton,after,List.foldl_append] using hnext
+ · intro x hx
+ rcases List.mem_append.mp hx with hold | hnew
+ · exact hg x hold
+ · exact (List.mem_singleton.mp hnew) ▸ hrep
+ exact go cap le_rfl
+
+private theorem write_next {slot : Fin 4} {src dst j : ℕ} {original m : Memory w}
+ (inv : FieldCopy original slot src dst j m) (addr : Word w) (ha : addr.val = dst+j) :
+ FieldCopy original slot src dst (j+1)
+ (writeMemory m addr (encodeBit w ((original (src+j)).val.testBit slot.val))) := by
+ constructor
+ · intro k hk
+ by_cases he : k = j
+ · simp [writeMemory,ha,he]
+ · simp [writeMemory,ha,he,inv.copied k (by omega)]
+ · intro z hz
+ have ne : z ≠ dst+j := by omega
+ simp [writeMemory,ha,ne,inv.frame z (by omega)]
+
+/-- All active and idle calls, before the bounded wrapper's accepting call.
+The final copy has exactly the runtime length and every report, even under
+arbitrary replay, preserves any designated address outside its destination. -/
+theorem copy_sweep (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (original : Memory w) (iv : ℕ × ℕ) (cap : ℕ) (size : Sizes p pub iv cap) (load : Loaded p pub iv original)
+ (layout : CopyLayout p pub iv) (tag : Word w) (outside : Outside (pub p.destinationBase).val iv.2 tag.val) :
+ ∃ rs, runSegment (program p slot false pub) 22 (some 0) original (List.replicate cap []) = some rs ∧
+ endState (some 0) rs = some (cap : Word w) ∧
+ FieldCopy original slot iv.1 (pub p.destinationBase).val iv.2 (after original (eventLog rs)) ∧
+ rs.length = cap ∧ (∀ r ∈ rs, countProbes r.events ≤ 4) ∧ LiveStageLink.PreservesTag tag rs := by
+ let dst := (pub p.destinationBase).val
+ let inv j := FieldCopy original slot iv.1 dst (min j iv.2)
+ let good (r : Report w) := countProbes r.events ≤ 4 ∧ ∀ m, after m r.events tag.val = m tag.val
+ have step (j : ℕ) (hj : j < cap) (mem : Memory w) (hi : inv j mem) :
+ ∃ es, execute (program p slot false pub) 22 ((program p slot false pub).start (j : Word w)) mem [] =
+ some ⟨es,some ((j+1 : ℕ) : Word w)⟩ ∧ inv (j+1) (after mem es) ∧ good ⟨es,some ((j+1 : ℕ) : Word w)⟩ := by
+ have unchanged (z : ℕ) (ho : Outside dst iv.2 z) : mem z = original z := by
+ apply hi.frame
+ exact ho.imp_right ((Nat.add_le_add_left (Nat.min_le_right ..) dst).trans ·)
+ have hc := (congrArg Fin.val (unchanged _ layout.countOutside)).trans load.count
+ have hoff := (congrArg Fin.val (unchanged _ layout.offsetOutside)).trans load.offset
+ by_cases ha : j < iv.2
+ · have act := (active_iff size hj hc).mpr ha
+ have hd := destination_val size layout ha
+ have hsrc : mem (iv.1+j) = original (iv.1+j) :=
+ unchanged _ (Or.inl (by have := layout.sourceBefore; dsimp [dst]; omega))
+ have safe : tag ≠ destination p pub (j : Word w) := by
+ intro same
+ have he := (congrArg Fin.val same).trans hd
+ rcases outside with lo | hi <;> omega
+ obtain ⟨es,hr,hm,_,hp,_⟩ := native_of_returns (copy_exec hw p slot pub (j : Word w) _ mem act)
+ (show 21 < 22 by decide)
+ have frame := report_frame p slot false pub (j : Word w) mem [] 22 hr tag (fun _ => Or.inr safe)
+ refine ⟨es,by simpa using hr,?_,hp.le,frame⟩
+ rw [hm,read_bit size hoff slot ha,hsrc]
+ dsimp [inv] at hi ⊢
+ rw [Nat.min_eq_left ha.le] at hi
+ rw [Nat.min_eq_left ha]
+ exact write_next hi _ hd
+ · have idle := mt (active_iff size hj hc).mp ha
+ obtain ⟨es,hr,hm,_,hp,_⟩ := native_of_returns (idle_exec p slot false pub (j : Word w) _ mem idle)
+ (show 8 < 22 by decide)
+ have frame := report_frame p slot false pub (j : Word w) mem [] 22 hr tag (fun h => (idle h).elim)
+ refine ⟨es,by simpa using hr,?_,by change countProbes es ≤ 4; omega,frame⟩
+ dsimp [inv] at hi ⊢
+ rw [hm,Nat.min_eq_right (by omega)]
+ simpa [Nat.min_eq_right (Nat.le_of_not_gt ha)] using hi
+ obtain ⟨rs,hr,he,hi,hl,hg⟩ := run_good _ 22 cap original inv good (FieldCopy.initial ..) step
+ exact ⟨rs,hr,he,by simpa [inv,Nat.min_eq_right size.occupied] using hi,hl,
+ fun r h => (hg r h).1,fun r h => (hg r h).2⟩
+
+/-- The occupied padding positions are zero in the original processor words. -/
+def ZeroPad (slot : Fin 4) (iv : ℕ × ℕ) (m : Memory w) :=
+ ∀ j < iv.2, (m (iv.1+j)).val.testBit slot.val = false
+
+theorem padding_sweep (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (original : Memory w) (iv : ℕ × ℕ) (cap : ℕ) (size : Sizes p pub iv cap) (load : Loaded p pub iv original)
+ (tag : Word w) (zero : ZeroPad slot iv original) :
+ ∃ rs, runSegment (program p slot true pub) 22 (some 0) original (List.replicate cap []) = some rs ∧
+ endState (some 0) rs = some (cap : Word w) ∧ after original (eventLog rs) = original ∧
+ rs.length = cap ∧ (∀ r ∈ rs, countProbes r.events ≤ 3) ∧ LiveStageLink.PreservesTag tag rs := by
+ let good (r : Report w) := countProbes r.events ≤ 3 ∧ ∀ m, after m r.events tag.val = m tag.val
+ have step (j : ℕ) (hj : j < cap) (mem : Memory w) (hi : mem = original) :
+ ∃ es, execute (program p slot true pub) 22 ((program p slot true pub).start (j : Word w)) mem [] =
+ some ⟨es,some ((j+1 : ℕ) : Word w)⟩ ∧ after mem es = original ∧ good ⟨es,some ((j+1 : ℕ) : Word w)⟩ := by
+ subst mem
+ have use {steps probes : ℕ} (ret : Returns p slot true pub (j : Word w) (fun _ => 0) original original steps probes)
+ (fuel : steps < 22) (bound : probes ≤ 3) : ∃ es,
+ execute (program p slot true pub) 22 ((program p slot true pub).start (j : Word w)) original [] =
+ some ⟨es,some ((j+1 : ℕ) : Word w)⟩ ∧ after original es = original ∧ good ⟨es,some ((j+1 : ℕ) : Word w)⟩ := by
+ obtain ⟨es,hr,hm,_,hp,_⟩ := native_of_returns ret fuel
+ have frame := report_frame p slot true pub (j : Word w) original [] 22 hr tag (fun _ => Or.inl rfl)
+ exact ⟨es,by simpa using hr,hm,hp.le.trans bound,frame⟩
+ by_cases active : j < iv.2
+ · exact use (padding_exec hw p slot pub (j : Word w) _ original ((active_iff size hj load.count).mpr active)
+ ((read_bit size load.offset slot active).trans (zero j active))) (by decide) le_rfl
+ · exact use (idle_exec p slot true pub (j : Word w) _ original (mt (active_iff size hj load.count).mp active))
+ (by decide) (by decide)
+ obtain ⟨rs,hr,he,hm,hl,hg⟩ := run_good _ 22 cap original (fun _ mem => mem = original) good rfl step
+ exact ⟨rs,hr,he,hm,hl,fun r h => (hg r h).1, fun r h => (hg r h).2⟩
+
+private theorem pad_report {p pub iv cap} (hw : 4 ≤ w) (slot : Fin 4) (size : Sizes p pub iv cap)
+ {m : Memory w} (load : Loaded p pub iv m) {j : ℕ} (hj : j < cap) (fuel : ℕ)
+ (bits : List Bool) {r : Report w}
+ (hr : execute (program p slot true pub) fuel ((program p slot true pub).start (j : Word w)) m bits = some r) :
+ r.result = some ((j+1 : ℕ) : Word w) ∧ after m r.events = m ∧
+ (j < iv.2 → (m (iv.1+j)).val.testBit slot.val = false) := by
+ by_cases active : j < iv.2
+ · have ha := (active_iff size hj load.count).mpr active
+ have he := read_bit size load.offset slot active
+ cases hb : (m (iv.1+j)).val.testBit slot.val with
+ | false =>
+ have hrep := native_report_of_returns (padding_exec hw p slot pub (j : Word w) _ m ha (he.trans hb)) hr
+ exact ⟨by simpa using hrep.2.1,hrep.2.2.1,fun _ => rfl⟩
+ | true =>
+ have fail := padding_native_rejects hw p slot pub (j : Word w) m ha (he.trans hb) fuel bits
+ have eq : none = some r := fail.symm.trans hr
+ contradiction
+ · have idle := mt (active_iff size hj load.count).mp active
+ have hrep := native_report_of_returns (idle_exec p slot true pub (j : Word w) _ m idle) hr
+ exact ⟨by simpa using hrep.2.1,hrep.2.2.1,fun h => (active h).elim⟩
+
+private theorem pad_prefix_sound {C : Type*} (P : Program w C) (fuel cap : ℕ) (slot : Fin 4)
+ (iv : ℕ × ℕ) (m : Memory w)
+ (one : ∀ j < cap, ∀ bits r, execute P fuel (P.start (j : Word w)) m bits = some r →
+ r.result = some ((j+1 : ℕ) : Word w) ∧ after m r.events = m ∧
+ (j < iv.2 → (m (iv.1+j)).val.testBit slot.val = false))
+ (bs : List (List Bool)) (start : ℕ) {rs : List (Report w)} (fit : start+bs.length ≤ cap)
+ (hr : runSegment P fuel (some (start : Word w)) m bs = some rs) :
+ ∀ j, start ≤ j → j < start+bs.length → j < iv.2 → (m (iv.1+j)).val.testBit slot.val = false := by
+ induction bs generalizing start rs with
+ | nil => intro j lo hi _; simp at hi; omega
+ | cons b bs ih =>
+ simp only [List.length_cons] at fit ⊢
+ simp only [runSegment] at hr
+ cases hx : execute P fuel (P.start (start : Word w)) m b with
+ | none => simp [hx] at hr
+ | some r =>
+ simp only [hx, Option.map_eq_some_iff] at hr
+ obtain ⟨rest,hr,_⟩ := hr
+ obtain ⟨hnext,hm,hbit⟩ := one start (by omega) b r hx
+ rw [hnext,hm] at hr
+ intro j lo hi present
+ rcases eq_or_lt_of_le lo with rfl | hlt
+ · exact hbit present
+ · exact ih (start+1) (by omega) hr j (by omega) (by omega) present
+
+/-- Any successful sequence of padding calls covering the whole public
+allocation forces each occupied original site to be zero. -/
+theorem padding_sweep_sound (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (m : Memory w) (iv : ℕ × ℕ) (cap : ℕ) (size : Sizes p pub iv cap) (load : Loaded p pub iv m)
+ (fuel : ℕ) (bs : List (List Bool)) (length : bs.length = cap) {rs : List (Report w)}
+ (hr : runSegment (program p slot true pub) fuel (some 0) m bs = some rs) : ZeroPad slot iv m := by
+ have sound := pad_prefix_sound (program p slot true pub) fuel cap slot iv m
+ (fun _ hj b _ he => pad_report hw slot size load hj fuel b he) bs 0 (by simp [length]) hr
+ intro j hj
+ exact sound j (Nat.zero_le _) (by simpa [length] using hj.trans_le size.occupied) hj
+
+/-- The instantiated allocated-field worker wrapped in a public capacity check. -/
+abbrev boundedProgram (p : Parameters) (slot : Fin 4) (pad : Bool) (pub : Fin 16 → Word w) (cap : ℕ) :=
+ (LiveHeaderBounded.machine (table p slot pad) pub (cap : Word w)).program
+
+private theorem close_sweep (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pad : Bool)
+ (pub : Fin 16 → Word w) (cap : ℕ) (hcap : cap < 2^w) (m : Memory w) (tag : Word w)
+ (probes : ℕ) {rs : List (Report w)}
+ (hr : runSegment (program p slot pad pub) 22 (some 0) m (List.replicate cap []) = some rs)
+ (hl : rs.length = cap) (hp : ∀ r ∈ rs, countProbes r.events ≤ probes)
+ (hf : LiveStageLink.PreservesTag tag rs) :
+ let out := rs.map LiveHeaderBounded.activeReport ++ [LiveHeaderBounded.closedReport w]
+ runSegment (boundedProgram p slot pad pub cap) 25 (some 0) m (List.replicate (cap+1) []) = some out ∧
+ endState (some 0) out = none ∧ after m (eventLog out) = after m (eventLog rs) ∧
+ out.length = cap+1 ∧ (∀ r ∈ out, countProbes r.events ≤ probes) ∧ LiveStageLink.PreservesTag tag out := by
+ dsimp only
+ have run := LiveHeaderBounded.runSegment_cursor_complete (table p slot pad) pub (cap : Word w)
+ (by decide : 0 < 22) 0 m (List.replicate cap []) rs (by simp [Fin.val_cast_of_lt hcap]) hr (by
+ intro j _ mem bits r h
+ simpa using (report_successor hw p slot pad pub (j : Word w) mem bits 22 h).2)
+ refine ⟨by simpa only [List.replicate_succ',Nat.cast_zero] using run,?_,?_,by simp [hl],?_,?_⟩
+ · rw [endState_append]; rfl
+ · rw [eventLog,List.flatMap_append,List.flatMap_singleton,after,List.foldl_append]
+ exact LiveHeaderBounded.after_activeReports m rs
+ · intro r h
+ rcases List.mem_append.mp h with h | h
+ · obtain ⟨r,hr,rfl⟩ := List.mem_map.mp h
+ exact hp r hr
+ · obtain rfl := List.mem_singleton.mp h
+ exact Nat.zero_le _
+ · intro r h mem
+ rcases List.mem_append.mp h with h | h
+ · obtain ⟨r,hr,rfl⟩ := List.mem_map.mp h
+ exact hf r hr mem
+ · obtain rfl := List.mem_singleton.mp h
+ rfl
+
+/-- The source stage in the native linker. Its accepting path includes one
+closing call after the public capacity, and has the exact occupied copy. -/
+theorem copy_bounded (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (m : Memory w) (iv : ℕ × ℕ) (cap : ℕ) (size : Sizes p pub iv cap) (load : Loaded p pub iv m)
+ (layout : CopyLayout p pub iv) (tag : Word w) (outside : Outside (pub p.destinationBase).val iv.2 tag.val) :
+ ∃ rs, runSegment (boundedProgram p slot false pub cap) 25 (some 0) m (List.replicate (cap+1) []) = some rs ∧
+ endState (some 0) rs = none ∧ FieldCopy m slot iv.1 (pub p.destinationBase).val iv.2 (after m (eventLog rs)) ∧
+ rs.length = cap+1 ∧ (∀ r ∈ rs, countProbes r.events ≤ 4) ∧ LiveStageLink.PreservesTag tag rs := by
+ obtain ⟨rs,hr,_,hc,hl,hp,hf⟩ := copy_sweep hw p slot pub m iv cap size load layout tag outside
+ obtain ⟨run,last,mem,len,probes,frame⟩ := close_sweep hw p slot false pub cap size.capFit m tag 4 hr hl hp hf
+ exact ⟨_,run,last,mem.symm ▸ hc,len,probes,frame⟩
+
+/-- The complete bounded padding stage succeeds on a zero padding field.
+Neither its active nor its idle calls write any memory. -/
+theorem padding_bounded (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (m : Memory w) (iv : ℕ × ℕ) (cap : ℕ) (size : Sizes p pub iv cap) (load : Loaded p pub iv m)
+ (tag : Word w) (zero : ZeroPad slot iv m) :
+ ∃ rs, runSegment (boundedProgram p slot true pub cap) 25 (some 0) m (List.replicate (cap+1) []) = some rs ∧
+ endState (some 0) rs = none ∧ after m (eventLog rs) = m ∧
+ rs.length = cap+1 ∧ (∀ r ∈ rs, countProbes r.events ≤ 3) ∧ LiveStageLink.PreservesTag tag rs := by
+ obtain ⟨rs,hr,_,hm,hl,hp,hf⟩ := padding_sweep hw p slot pub m iv cap size load tag zero
+ obtain ⟨run,last,mem,len,probes,frame⟩ := close_sweep hw p slot true pub cap size.capFit m tag 3 hr hl hp hf
+ exact ⟨_,run,last,mem.trans hm,len,probes,frame⟩
+
+/-- On arbitrary choice strings and for every allocated fuel, an accepting
+bounded scan has checked every occupied original padding bit. Early stopping
+leaves a live cursor and cannot skip a failing padding position. -/
+theorem padding_bounded_sound (hw : 4 ≤ w) (p : Parameters) (slot : Fin 4) (pub : Fin 16 → Word w)
+ (m : Memory w) (iv : ℕ × ℕ) (cap : ℕ) (size : Sizes p pub iv cap) (load : Loaded p pub iv m)
+ (f : ℕ) (bs : List (List Bool)) {rs : List (Report w)}
+ (hr : runSegment (boundedProgram p slot true pub cap) (f+3) (some 0) m bs = some rs)
+ (last : endState (some 0) rs = none) : ZeroPad slot iv m := by
+ let P := boundedProgram p slot true pub cap
+ have go (bs : List (List Bool)) (start : ℕ) (rs : List (Report w))
+ (run : runSegment P (f+3) (some (start : Word w)) m bs = some rs)
+ (last : endState (some (start : Word w)) rs = none) :
+ ∀ j, start ≤ j → j < iv.2 → (m (iv.1+j)).val.testBit slot.val = false := by
+ induction bs generalizing start rs with
+ | nil =>
+ simp only [runSegment,Option.some.injEq] at run
+ subst rs
+ contradiction
+ | cons b bs ih =>
+ intro j lo hj
+ have here : start < cap := lo.trans_lt (hj.trans_le size.occupied)
+ have active : (start : Word w) < (cap : Word w) := by
+ change (start : Word w).val < (cap : Word w).val
+ rwa [index_val size here,Fin.val_cast_of_lt size.capFit]
+ have heq := LiveHeaderBounded.execute_active (table p slot true) pub (cap : Word w) f
+ (start : Word w) active m b
+ simp only [runSegment] at run
+ cases he : execute P (f+3) (P.start (start : Word w)) m b with
+ | none => simp [he] at run
+ | some r =>
+ simp only [he,Option.map_eq_some_iff] at run
+ obtain ⟨rest,tail,rfl⟩ := run
+ have hx : (execute (program p slot true pub) f ((program p slot true pub).start (start : Word w)) m b).map
+ LiveHeaderBounded.activeReport = some r := heq.symm.trans he
+ obtain ⟨source,hs,rfl⟩ := Option.map_eq_some_iff.mp hx
+ obtain ⟨next,mem,checked⟩ := pad_report hw slot size load here f b hs
+ change runSegment P (f+3) source.result (after m source.events) bs = some rest at tail
+ change endState source.result rest = none at last
+ rw [next,mem] at tail
+ rw [next] at last
+ rcases eq_or_lt_of_le lo with rfl | later
+ · exact checked hj
+ · exact ih (start+1) rest tail last j (by omega) hj
+ exact fun j hj => go bs 0 rs hr last j (Nat.zero_le _) hj
+
+/-- Runtime descriptors and the preserved headers identify the actual
+incident cut in the completed fixed-capacity copy, with a full scratch
+frame and the per-report linker frame. -/
+theorem physical_copy_bounded {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ} {g : Fin (2^(h+1))}
+ {m : Memory w} (headers : SiteHeaders d hw advice cuts g m) (side : LiveHeaderDescriptors.Side)
+ (p : Parameters) (pub : Fin 16 → Word w) (iv : ℕ × ℕ) (cap : ℕ) (size : Sizes p pub iv cap)
+ (load : Loaded p pub iv m) (layout : CopyLayout p pub iv) (tag : Word w)
+ (outside : Outside (pub p.destinationBase).val iv.2 tag.val)
+ (sites : iv.1+iv.2 ≤ 2^d) (scratch : 2^d ≤ (pub p.destinationBase).val) :
+ ∃ rs, runSegment (boundedProgram p (cutSlot side) false pub cap) 25 (some 0) m (List.replicate (cap+1) []) = some rs ∧
+ endState (some 0) rs = none ∧ rs.length = cap+1 ∧
+ (∀ r ∈ rs, countProbes r.events ≤ 4) ∧ LiveStageLink.PreservesTag tag rs ∧
+ FieldCopy m (cutSlot side) iv.1 (pub p.destinationBase).val iv.2 (after m (eventLog rs)) ∧
+ CopiedSlice (cuts (incidentCut side g)) iv (pub p.destinationBase).val (after m (eventLog rs)) ∧
+ SiteHeaders d hw advice cuts g (after m (eventLog rs)) := by
+ obtain ⟨rs,run,last,copy,len,hp,frame⟩ := copy_bounded hw p (cutSlot side) pub m iv cap size load layout tag outside
+ exact ⟨rs,run,last,len,hp,frame,copy,copy.physical headers side iv _ sites scratch⟩
+
+/-- Among all possible paths through the bounded table, an accepting
+path exists exactly for canonical zero padding in the actual cut field. -/
+theorem physical_padding_bounded_iff {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ} {g : Fin (2^(h+1))}
+ {m : Memory w} (headers : SiteHeaders d hw advice cuts g m) (side : LiveHeaderDescriptors.Side)
+ (p : Parameters) (pub : Fin 16 → Word w) (iv : ℕ × ℕ) (cap : ℕ) (size : Sizes p pub iv cap)
+ (load : Loaded p pub iv m) (tag : Word w) (sites : iv.1+iv.2 ≤ 2^d)
+ (inside : iv.1+iv.2 ≤ width (h+1) Δ (incidentCut side g).val) :
+ (∃ bs rs, runSegment (boundedProgram p (cutSlot side) true pub cap) 25 (some 0) m bs = some rs ∧
+ endState (some 0) rs = none) ↔ LiveHeaderDescriptors.Physical.ZeroSlice (cuts (incidentCut side g)) iv := by
+ rw [← headers.zeroSlice side iv sites inside]
+ constructor
+ · rintro ⟨bs,rs,hr,last⟩
+ exact padding_bounded_sound hw p (cutSlot side) pub m iv cap size load 22 bs hr last
+ · intro hz
+ obtain ⟨rs,run,last,_⟩ := padding_bounded hw p (cutSlot side) pub m iv cap size load tag hz
+ exact ⟨_,rs,run,last⟩
+
+end LiveHeader.Allocated
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderAuxiliaryArrays.lean b/lean/OAI/Computability/VPVNP/LiveHeaderAuxiliaryArrays.lean
new file mode 100644
index 0000000000..95a753c4c6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderAuxiliaryArrays.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.LiveHeaderPairReadback
+import OAI.Computability.VPVNP.LiveAuxiliaryHeaderInputs
+import OAI.Computability.VPVNP.LiveAuxiliaryStages
+
+/-!
+# The seven source arrays for the native auxiliary pair
+
+The live header supplies three computed widths, both primed group numbers,
+the advice and the two decoded exterior fields. Nomination supplies the
+seventh array while preserving the occupied header addresses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM LiveHeaderSchedule LiveHeaderWidths PrimedInputRAM ChainAssignments CutSchedule LiveHeader
+open scoped Fin.CommRing
+
+variable {s : Sizes} {base d w t Z : ℕ} {hw : 4 ≤ w} {advice : Bits s.advice}
+variable {cuts : AllCuts s.h s.delta} {tag : Mode.Tag} {m : Memory w}
+
+private def lengthSlot : Fin 3 → Slot := ![.primedLeft, .primedMiddle, .primedRight]
+
+private theorem length_address (base : ℕ) (j : Fin 3) :
+ widthAddr base .primedLeft+j.val = widthAddr base (lengthSlot j) := by
+ fin_cases j <;> rfl
+
+private theorem pair_length (s : Sizes) (i : Fin (2^s.h)) (j : Fin 3) :
+ width (s.h+1) s.delta (index (i.val+1) (lengthSlot j)) =
+ cutLength (PairedChain.lengths s.h s.delta s.advice i) j := by
+ fin_cases j <;> change width _ _ _ = width _ _ _
+ all_goals congr 1
+
+/-- The post-nomination memory meets every input-array premise of the sparse
+auxiliary initializer at its real public source addresses. -/
+theorem Output.auxiliaryInputArrays (i : Fin (2^s.h))
+ (out : Output s base d hw advice cuts (halves s.h (.inl i)) tag m)
+ (ev : tag ≠ .unit) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta) (room : limit s base ≤ 2^w)
+ (muBase : Word w) (hist : List (Word w)) (afterNom : Memory w)
+ (stable : ∀ a, base < a → a < limit s base → afterNom a = m a)
+ (nominations : ∀ j : Fin hist.length, afterNom (muBase+(j.val : Word w)).val = hist[j]) :
+ let L := PairedChain.lengths s.h s.delta s.advice i
+ let ξ := exteriorOf fit (liveCutEquiv s.h s.delta cuts).1
+ LiveAuxiliaryHeaders.InputArrays L (PairedChain.headers advice ξ i) hist
+ (LiveAuxiliaryStages.headerSources s base muBase) afterNom := by
+ dsimp only
+ let L := PairedChain.lengths s.h s.delta s.advice i
+ let ξ := exteriorOf fit (liveCutEquiv s.h s.delta cuts).1
+ have read (b j : ℕ) (lo : base < b+j) (hi : b+j < limit s base) :
+ afterNom ((b : Word w)+(j : Word w)).val = m (b+j) := by
+ rw [← Nat.cast_add,Fin.val_cast_of_lt (hi.trans_le room),stable _ lo hi]
+ have read_exterior (side : LiveHeaderDescriptors.Side) (j : ℕ) (hj : j < s.capacity .exterior) :
+ afterNom ((exteriorBase s base side : Word w)+(j : Word w)).val = m (exteriorBase s base side+j) := by
+ have upper := (dest_bounds s base side .exterior (by decide)).2
+ change exteriorBase s base side+s.capacity .exterior ≤ limit s base at upper
+ apply read
+ · cases side <;> dsimp [exteriorBase,adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase] <;> omega
+ · omega
+ obtain ⟨leftCut,rightCut⟩ := out.pairExteriorWords i ev he fit
+ constructor
+ · intro j
+ change afterNom ((widthAddr base .primedLeft : Word w)+(j.val : Word w)).val = Fin.ofNat _ (cutLength L j)
+ have hbound := j.isLt
+ rw [read _ _ (by dsimp [widthAddr]; omega) (by rw [limit_eq]; dsimp [widthAddr]; omega), length_address]
+ have h := out.scalars (.width (lengthSlot j)) (Or.inl i.isLt)
+ change (m (widthAddr base (lengthSlot j))).val = width (s.h+1) s.delta (index (i.val+1) (lengthSlot j)) at h
+ rw [pair_length] at h
+ apply Fin.ext
+ change (m (widthAddr base (lengthSlot j))).val = cutLength L j % 2^w
+ rw [← h, Nat.mod_eq_of_lt (m _).isLt]
+ · intro j
+ change afterNom ((leftIndexBase s base : Word w)+(j.val : Word w)).val =
+ encodeBit w (RAMSerialization.wordBits _ (PairedChain.groupIndex i 0) j)
+ have hj : j.val < s.h+2 := j.isLt
+ rw [read, out.primedLeft _ hj, ← testBit_wordBits (PairedChain.groupIndex i 0) j]
+ · change encodeBit w ((2*(i.val+1)-1).testBit j.val) = encodeBit w ((2*i.val+0+1).testBit j.val)
+ rw [show 2*(i.val+1)-1 = 2*i.val+0+1 by omega]
+ · dsimp [leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ · rw [limit_eq]; dsimp [leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ · intro j
+ change afterNom ((rightIndexBase s base : Word w)+(j.val : Word w)).val =
+ encodeBit w (RAMSerialization.wordBits _ (PairedChain.groupIndex i 1) j)
+ have hj : j.val < s.h+2 := j.isLt
+ rw [read, out.primedRight _ hj, ← testBit_wordBits (PairedChain.groupIndex i 1) j]
+ · change encodeBit w ((2*(i.val+1)).testBit j.val) = encodeBit w ((2*i.val+1+1).testBit j.val)
+ rw [show 2*(i.val+1) = 2*i.val+1+1 by omega]
+ · dsimp [rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ · rw [limit_eq]; dsimp [rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ · intro j
+ change afterNom ((adviceBase s base : Word w)+(j.val : Word w)).val = encodeBit w (advice j)
+ have hj : j.val < s.advice := j.isLt
+ rw [read, out.adviceWords j]
+ · dsimp [adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ · rw [limit_eq]; dsimp [adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ · intro j
+ change afterNom ((exteriorBase s base .left : Word w)+(j.val : Word w)).val = encodeBit w (ξ i.castSucc j)
+ rw [read_exterior .left j.val (j.isLt.trans_le L.leftFit)]
+ exact leftCut j
+ · intro j
+ change afterNom ((exteriorBase s base .right : Word w)+(j.val : Word w)).val = encodeBit w (ξ i.succ j)
+ rw [read_exterior .right j.val (j.isLt.trans_le L.rightFit)]
+ exact rightCut j
+ · exact nominations
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderAuxiliaryStored.lean b/lean/OAI/Computability/VPVNP/LiveHeaderAuxiliaryStored.lean
new file mode 100644
index 0000000000..68829058df
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderAuxiliaryStored.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.LiveHeaderAuxiliaryArrays
+import OAI.Computability.VPVNP.LiveHeaderOutputFrame
+
+/-!
+# Auxiliary source arrays after the nomination handoff
+
+The nomination sweep writes its histogram above the live header allocation.
+The outer stage tag lies below all seven source arrays, so their contents
+are available at the start of the auxiliary stage.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM LiveHeaderSchedule LiveHeader ChainAssignments CutSchedule
+open scoped Fin.CommRing
+
+variable {s : Sizes} {base d w t Z T b stages : ℕ} {hw : 4 ≤ w} {advice : Bits s.advice}
+variable {cuts : AllCuts s.h s.delta} {tag : Mode.Tag} {m : Memory w}
+
+/-- The memory passed by the nomination stage contains the six decoded header
+arrays and the nominated counters in their public source ranges. -/
+theorem Output.auxiliaryStoredInputArrays (i : Fin (2^s.h))
+ (out : Output s base d hw advice cuts (halves s.h (.inl i)) tag m)
+ (ev : tag ≠ .unit) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta)
+ (muBase : Word w) (muFit : muBase.val+T ≤ 2^w) (afterHeader : limit s base ≤ muBase.val)
+ (μ : Fin T → Word b) (outer : Word w) (dest : Option (Fin stages)) (below : outer.val ≤ base) :
+ let L := PairedChain.lengths s.h s.delta s.advice i
+ let ξ := exteriorOf fit (liveCutEquiv s.h s.delta cuts).1
+ let hist := List.ofFn fun k => Fin.ofNat (2^w) (μ k).val
+ LiveAuxiliaryHeaders.InputArrays L (PairedChain.headers advice ξ i) hist
+ (LiveAuxiliaryStages.headerSources s base muBase)
+ (LiveStageLink.transferMemory outer dest (LiveNominations.stored muBase muFit μ m)) := by
+ dsimp only
+ have unchanged (a : ℕ) (ha : base < a) :
+ LiveStageLink.transferMemory outer dest (LiveNominations.stored muBase muFit μ m) a =
+ LiveNominations.stored muBase muFit μ m a := by
+ cases dest <;> simp [LiveStageLink.transferMemory, writeMemory, (below.trans_lt ha).ne']
+ apply out.auxiliaryInputArrays i ev he fit (afterHeader.trans muBase.isLt.le)
+ · intro a lo hi
+ exact (unchanged a lo).trans ((out.nomination_frame muBase muFit afterHeader μ).1 a hi)
+ · intro j
+ have hj : j.val < T := by simpa only [List.length_ofFn] using j.isLt
+ have addr : (muBase + (j.val : Word w)).val = muBase.val+j.val := by
+ have hj' : ((j.val : Word w) : ℕ) = j.val := Fin.val_cast_of_lt (by omega)
+ rw [Fin.val_add_eq_of_add_lt (by rw [hj']; omega), hj']
+ have lo : base < muBase.val := by rw [limit_eq] at afterHeader; omega
+ rw [addr, unchanged _ (by omega)]
+ change _ = (List.ofFn fun k => Fin.ofNat (2^w) (μ k).val)[j.val]
+ rw [List.getElem_ofFn]
+ exact LiveNominations.stored_at muBase muFit μ m ⟨j.val,hj⟩
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderBits.lean b/lean/OAI/Computability/VPVNP/LiveHeaderBits.lean
new file mode 100644
index 0000000000..6cda54cacb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderBits.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeFields
+import OAI.Computability.VPVNP.RAMSiteInput
+
+/-!
+# Native reads of the distributed live header
+
+One processor location stores its four local header bits in the low end of
+one external word. A microcall addresses a single site, extracts a statically
+chosen field, and stores one bit in a separate scratch array. The cursor and
+the array base are words, independently of the distributed index length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+theorem testBit_wordBits (x : Word w) (i : Fin w) :
+ x.val.testBit i.val = RAMSerialization.wordBits w x i := by
+ rw [Nat.testBit_eq_decide_div_mod_eq]
+ change decide (x.val / 2 ^ i.val % 2 = 1) = (finFunctionFinEquiv.symm x i == 1)
+ rw [Bool.eq_iff_iff, decide_eq_true_iff, beq_iff_eq, Fin.ext_iff, finFunctionFinEquiv_symm_apply_val]
+ rfl
+
+theorem extract_packed_bit (hw : 4 ≤ w) (h : ProcessorInput.Header) (slot : Fin 4) :
+ BinaryOp.bitAnd.eval (BinaryOp.shiftRight.eval (ProcessorInput.headerWord hw h)
+ (Fin.ofNat _ slot.val)) 1 = PrimedInputRAM.encodeBit w (h slot) := by
+ have hlt : slot.val < 2^w := slot.isLt.trans_le (show 4 ≤ 2^w from by
+ have := Nat.pow_le_pow_right (by decide : 0 < 2) hw; norm_num at this; omega)
+ rw [PrimedInputRAM.Opcodes.readBit_word (by omega), Fin.val_ofNat, Nat.mod_eq_of_lt hlt]
+ rw [show slot.val = (slot.castLE hw).val from rfl, testBit_wordBits, ProcessorInput.headerWord_bit]
+
+/-- A slot extractor. Register 0 holds the site address. Register 1 receives
+the bit word. The scratch registers are 2 and 3. -/
+def fetch (slot : Fin 4) {k : ℕ} : List (Op 12 k) :=
+ [.read 1 0, .constant 2 slot, .binary .shiftRight 1 1 2, .constant 3 1, .binary .bitAnd 1 1 3]
+
+/-- Copy one field of the processor at `state - pub 0` to the same offset in
+the scratch array beginning at `pub 1`, and advance the persistent cursor.
+This is a constant instruction list at every input length. -/
+def copyCell (slot : Fin 4) : List (Op 12 2) :=
+ [.stateWord 4, .publicWord 5 0, .binary .sub 0 4 5] ++ fetch slot ++
+ [.publicWord 6 1, .binary .add 6 6 0, .write 6 1, .binary .add 7 4 3]
+
+/-- The exact interpreter trace of a copy call, on arbitrary external memory. -/
+theorem copyCell_trace (hw : 4 ≤ w) (slot : Fin 4) (pub : Fin 2 → Word w)
+ (state : Word w) (rs : Regs w 12) (m : Memory w) :
+ let addr := state - pub 0
+ let dst := pub 1 + addr
+ let v := m addr.val
+ let b := PrimedInputRAM.encodeBit w (v.val.testBit slot.val)
+ ∃ es rs', trace pub state (copyCell slot) rs m = some (es, rs', writeMemory m dst b) ∧
+ rs' 7 = state + 1 ∧ es.length = 12 ∧ countProbes es = 2 ∧ choiceBits es = [] := by
+ have hlt : slot.val < 2 ^ w := slot.isLt.trans_le (show 4 ≤ 2^w from by
+ have := Nat.pow_le_pow_right (by decide : 0 < 2) hw; norm_num at this; omega)
+ simp (config := { decide := true }) [copyCell, fetch, trace, Op.effect, Function.update,
+ show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.sub.eval = (· - · : Word w → Word w → Word w) from rfl,
+ PrimedInputRAM.Opcodes.readBit_word (by omega : 0 < w),
+ Nat.mod_eq_of_lt hlt, countProbes, choiceBits]
+
+/-- A correctly packed header is copied to the unpacked destination array as a
+single bit. The native program takes two probes and returns the next cursor. -/
+theorem copyCell_native (hw : 4 ≤ w) (slot : Fin 4) (pub : Fin 2 → Word w)
+ (state : Word w) (m : Memory w) (h : ProcessorInput.Header)
+ (hm : m (state - pub 0).val = ProcessorInput.headerWord hw h) :
+ let dst := pub 1 + (state - pub 0)
+ let machine := (template (copyCell slot) 7).instantiate w pub
+ ∃ es, execute machine.program 13 (machine.program.start state) m [] = some ⟨es, some (state + 1)⟩ ∧
+ after m es = writeMemory m dst (PrimedInputRAM.encodeBit w (h slot)) ∧
+ es.length = 12 ∧ countProbes es = 2 ∧ choiceBits es = [] := by
+ dsimp only
+ let addr := state - pub 0
+ obtain ⟨es, rs, ht, hr, hl, hp, hc⟩ := copyCell_trace hw slot pub state (fun _ => 0) m
+ have hbit : (m addr.val).val.testBit slot.val = h slot := by
+ change (m (state - pub 0).val).val.testBit (slot.castLE hw).val = h slot
+ rw [hm, testBit_wordBits, ProcessorInput.headerWord_bit]
+ refine ⟨es, ?_, ?_, hl, hp, hc⟩
+ · change execute ((template (copyCell slot) 7).instantiate w pub).program (1 + (copyCell slot).length)
+ ⟨_,state,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [hr]
+ · have hd : after m es = writeMemory m (pub 1 + addr)
+ (PrimedInputRAM.encodeBit w ((m addr.val).val.testBit slot.val)) := by
+ simp (config := { decide := true }) [copyCell, fetch, trace, Op.effect, Function.update] at ht
+ rw [← ht.1]
+ exact ht.2.2
+ rwa [hbit] at hd
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderBootstrap.lean b/lean/OAI/Computability/VPVNP/LiveHeaderBootstrap.lean
new file mode 100644
index 0000000000..9410c2ef06
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderBootstrap.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.LiveHeaderAdviceStages
+import OAI.Computability.VPVNP.LiveHeaderScalarStages
+
+/-!
+# Native recovery of the distributed index and advice
+
+The first two stages start on the actual processor memory. Their two tag
+writes are carried into the next dispatch. The resulting memory contains
+the original packed headers, the index summaries and copied bits, and all
+advice words. Every address outside the written regions keeps its value.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ChainAssignments LiveHeaderSchedule LiveHeader
+open scoped Fin.CommRing
+
+variable {w d : ℕ}
+
+/-- The bootstrap's recovered group index, summary, advice words, and packed headers, with a
+frame for memory outside its writes. -/
+structure BootstrapState (s : Sizes) (base : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (out : Memory w) : Prop where
+ headers : SiteHeaders d hw advice cuts g out
+ summary : Summary s base (g.val+1) out
+ index : ∀ j < s.h+2, out (indexBase base+j) = PrimedInputRAM.encodeBit w ((g.val+1).testBit j)
+ adviceWords : ∀ j : Fin s.advice, out (adviceBase s base + j.val) = PrimedInputRAM.encodeBit w (advice j)
+ frame : ∀ k, k ≠ base → (k < indexBase base ∨ populationAddr s base < k) →
+ (k < adviceBase s base ∨ adviceBase s base+s.advice ≤ k) →
+ out k = physicalMemory (d := d) hw advice cuts g k
+
+private theorem transfer_other {base : ℕ} {addr : Word w} {i : StageId} {m : Memory w}
+ {k : ℕ} (haddr : addr.val = base) (hk : k ≠ base) :
+ LiveStageLink.transferMemory addr (some i) m k = m k := by simp [LiveStageLink.transferMemory,writeMemory,haddr,hk]
+
+theorem index_advice_prefix (s : Sizes) (base : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d)
+ (scratch : 2^d ≤ base) (fit : limit s base ≤ 2^w) :
+ ∃ xs out, StagePrefix s base (some (⟨0, by decide⟩ : StageId)) (physicalMemory (d := d) hw advice cuts g)
+ xs (some (⟨2, by decide⟩ : StageId)) out ∧ (∀ x ∈ xs, x.Good s) ∧
+ BootstrapState (d := d) s base hw advice cuts g out := by
+ let addr : Word w := Fin.ofNat _ base
+ let id₀ : StageId := ⟨0,by decide⟩
+ let id₁ : StageId := ⟨1,by decide⟩
+ let id₂ : StageId := ⟨2,by decide⟩
+ let m := physicalMemory (d := d) hw advice cuts g
+ obtain ⟨r₀, hr₀, he₀, hl₀, hp₀, hf₀, data₀⟩ := index_stage_native s base hw advice cuts g indices scratch fit
+ let x₀ : StageTrace w := ⟨id₀,25,List.replicate (calls s .index) [],r₀⟩
+ let before := after m (eventLog r₀)
+ let m₁ := x₀.finalMem addr m
+ have run₀ : x₀.Exec s base m := ⟨hr₀,he₀,hf₀⟩
+ have good₀ : x₀.Good s := ⟨(by decide : 25 ≤ 40),rfl,hl₀,hp₀⟩
+ have tagFit : addr.val = base := by
+ apply Nat.mod_eq_of_lt
+ rw [limit_eq] at fit
+ omega
+ have pass₀ (k : ℕ) (hk : k ≠ base) : m₁ k = before k :=
+ transfer_other (i := id₁) tagFit hk
+ have hdr₁ : SiteHeaders d hw advice cuts g m₁ := fun v =>
+ (pass₀ v.val (Nat.ne_of_lt (v.isLt.trans_le scratch))).trans (data₀.headers v)
+ obtain ⟨r₁, hr₁, he₁, hl₁, hp₁, hf₁, data₁⟩ := advice_stage_native s base hw advice cuts g m₁ hdr₁ adv scratch fit
+ let x₁ : StageTrace w := ⟨id₁,16,List.replicate (calls s .advice) [],r₁⟩
+ let copied := after m₁ (eventLog r₁)
+ let out := x₁.finalMem addr m₁
+ have run₁ : x₁.Exec s base m₁ := ⟨hr₁,he₁,hf₁⟩
+ have good₁ : x₁.Good s := ⟨(by decide : 16 ≤ 40),rfl,hl₁,hp₁⟩
+ have pass₁ (k : ℕ) (hk : k ≠ base) : out k = copied k :=
+ transfer_other (i := id₂) tagFit hk
+ have keep (k : ℕ) (hk : k ≠ base) (ha : k < adviceBase s base ∨ adviceBase s base + s.advice ≤ k) :
+ out k = before k := (pass₁ k hk).trans ((data₁.frame k ha).trans (pass₀ k hk))
+ let pub := indexWords w s base
+ have fit' := fit
+ rw [limit_eq] at fit'
+ have va : (pub 0).val = indexBase base := Nat.mod_eq_of_lt (by dsimp [indexBase]; omega)
+ have vh : (pub 1).val = highAddr s base := Nat.mod_eq_of_lt (by dsimp [highAddr,indexBase]; omega)
+ have vc : (pub 2).val = populationAddr s base := Nat.mod_eq_of_lt (by dsimp [populationAddr,highAddr,indexBase]; omega)
+ have horder : base < indexBase base ∧ indexBase base ≤ highAddr s base ∧
+ highAddr s base < populationAddr s base ∧ populationAddr s base < adviceBase s base := by
+ dsimp [adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase]
+ omega
+ have hidx (j : ℕ) (hj : j < s.h+2) : out (indexBase base+j) = PrimedInputRAM.encodeBit w ((g.val+1).testBit j) := by
+ have hbound : indexBase base+j < highAddr s base := by dsimp [highAddr]; omega
+ rw [keep _ (by omega) (Or.inl (by omega)), ←va]
+ exact data₀.copied j hj
+ refine ⟨[x₀,x₁],out,StagePrefix.cons x₀ run₀ (StagePrefix.cons x₁ run₁ (.nil _ _)), ?_, ?_⟩
+ · intro x hx
+ rcases List.mem_cons.mp hx with rfl | hx
+ · exact good₀
+ · obtain rfl := List.mem_singleton.mp hx
+ exact good₁
+ · constructor
+ · intro v
+ rw [pass₁ v.val (Nat.ne_of_lt (v.isLt.trans_le scratch))]
+ exact data₁.headers v
+ · constructor
+ · rw [keep _ (by omega) (Or.inl (by omega)), ←vh]; exact data₀.high
+ · rw [keep _ (by omega) (Or.inl (by omega)), ←vc]; exact data₀.count
+ · rw [← data₀.count]; exact data₀.singleton
+ · simpa using hidx 0 (by omega)
+ · exact hidx
+ · intro j
+ rw [pass₁ _ (by omega)]
+ exact data₁.copied j
+ · intro k hb hi ha
+ rw [keep k hb ha]
+ apply data₀.frame
+ · change k < (pub 0).val ∨ (pub 0).val+(s.h+2) ≤ k
+ rw [va]
+ change k < indexBase base ∨ highAddr s base ≤ k
+ omega
+ · change k ≠ (pub 1).val
+ rw [vh]; omega
+ · change k ≠ (pub 2).val
+ rw [vc]; omega
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderBounded.lean b/lean/OAI/Computability/VPVNP/LiveHeaderBounded.lean
new file mode 100644
index 0000000000..ab7c0a1124
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderBounded.lean
@@ -0,0 +1,171 @@
+import OAI.Computability.VPVNP.LiveStageOperands
+import Mathlib.Tactic.FinCases
+
+/-!
+# A public cursor bound for a native stage
+
+Three local instructions compare the persistent cursor with a public capacity.
+Below that capacity the original table runs. At or above it the stage accepts,
+so the enclosing stage linker can hand control to the next table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderBounded
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {p r k w : ℕ}
+
+private def regs (r : ℕ) : Fin r ↪ Fin (r+2) := ⟨Fin.castAdd 2, Fin.castAdd_injective r 2⟩
+
+private def cursorReg (r : ℕ) : Fin (r+2) := (0 : Fin 2).natAdd r
+private def boundReg (r : ℕ) : Fin (r+2) := (1 : Fin 2).natAdd r
+
+private def pre (p : ℕ) (i : Fin 4) := i.castAdd p
+private def body (i : Fin p) := i.natAdd 4
+
+/-- Shift only the jump destinations of a native instruction. -/
+private def shift : Instr w p r k → Instr w (4+p) r k
+ | .constant a v j => .constant a v (body j)
+ | .publicWord a x j => .publicWord a x (body j)
+ | .stateWord a j => .stateWord a (body j)
+ | .copy a b j => .copy a b (body j)
+ | .binary op a b c j => .binary op a b c (body j)
+ | .loadPrivate a b j => .loadPrivate a b (body j)
+ | .storePrivate a b j => .storePrivate a b (body j)
+ | .jumpEq a b yes no => .jumpEq a b (body yes) (body no)
+ | .jumpLt a b yes no => .jumpLt a b (body yes) (body no)
+ | .choose yes no => .choose (body yes) (body no)
+ | .readExternal a b j => .readExternal a b (body j)
+ | .writeExternal a b j => .writeExternal a b (body j)
+ | .returnState a => .returnState a
+ | .accept => .accept
+ | .reject => .reject
+
+private def wide (T : Template p r k) := LiveStageLink.widen T (regs r) Fin.castSucc
+
+private def guardCode (entry : Fin p) : Fin 4 → Instr w (4+p) (r+2) (k+1)
+ | 0 => .stateWord (cursorReg r) (pre p 1)
+ | 1 => .publicWord (boundReg r) (Fin.last k) (pre p 2)
+ | 2 => .jumpLt (cursorReg r) (boundReg r) (body entry) (pre p 3)
+ | 3 => .accept
+
+/-- Wrap a worker in a public cursor-bound check that accepts when its capacity is reached. -/
+def bounded (T : Template p r k) : Template (4+p) (r+2) (k+1) where
+ literalWidth := T.literalWidth
+ entry := pre p 0
+ code := Fin.addCases (guardCode T.entry) (fun j => shift ((wide T).code j))
+
+/-- Append the stage's capacity word to the worker's original public operand bank. -/
+def publicData (pub : Fin k → Word w) (bound : Word w) : Fin (k+1) → Word w := Fin.snoc pub bound
+
+variable (T : Template p r k) (pub : Fin k → Word w) (bound : Word w)
+
+/-- Instantiate the cursor-bounded worker on its original operands and supplied capacity. -/
+abbrev machine := (bounded T).instantiate w (publicData pub bound)
+
+private theorem code_pre (j : Fin 4) : (machine T pub bound).code (pre p j) = guardCode T.entry j := by
+ simp only [machine, bounded, pre, Template.instantiate, Fin.addCases_left]
+ fin_cases j <;> rfl
+
+private theorem code_body (j : Fin p) : (machine T pub bound).code (body j) =
+ shift (((wide T).instantiate w (publicData pub bound)).code j) := by
+ simp only [machine, bounded, body, Template.instantiate, Fin.addCases_right]
+ cases (wide T).code j <;> rfl
+
+private def embed (c : Config w p r) : Config w (4+p) r := ⟨body c.pc, c.persistent, c.reg, c.privateMem⟩
+
+private def embedAction : CallAction w (Config w p r) → CallAction w (Config w (4+p) r)
+ | .localStep c => .localStep (embed c)
+ | .branch q => .branch (embed ∘ q)
+ | .read a q => .read a (embed ∘ q)
+ | .write a v c => .write a v (embed c)
+ | .finish s => .finish s
+ | .reject => .reject
+
+private theorem step_body (c : Config w p (r+2)) :
+ (machine T pub bound).program.step (embed c) =
+ embedAction (((wide T).instantiate w (publicData pub bound)).program.step c) := by
+ change ((machine T pub bound).code (body c.pc)).run (publicData pub bound) (embed c) = _
+ rw [code_body]
+ change (shift _).run _ _ = embedAction ((((wide T).instantiate w (publicData pub bound)).code c.pc).run _ c)
+ cases ((wide T).instantiate w (publicData pub bound)).code c.pc <;>
+ simp only [shift, Instr.run, embedAction, embed, Config.put, Config.store, Function.comp_def]
+ all_goals first | rfl | (simp only [apply_ite body] <;> rfl)
+
+private theorem execute_body (fuel : ℕ) (c : Config w p (r+2)) (m : Memory w) (bits : List Bool) :
+ execute (machine T pub bound).program fuel (embed c) m bits =
+ execute ((wide T).instantiate w (publicData pub bound)).program fuel c m bits := by
+ induction fuel generalizing c m bits with
+ | zero => rfl
+ | succ f ih =>
+ rw [execute, step_body, execute]
+ cases ((wide T).instantiate w (publicData pub bound)).program.step c <;>
+ simp only [embedAction, Function.comp_apply]
+ all_goals first | rfl | (rw [ih]) | (cases bits <;> simp [ih])
+
+private def bootRegs (st bound : Word w) : Fin (r+2) → Word w :=
+ Function.update (Function.update (fun _ => 0) (cursorReg r) st) (boundReg r) bound
+
+private def bootConfig (pc : Fin (4+p)) (st bound : Word w) : Config w (4+p) (r+2) :=
+ ⟨pc, st, bootRegs st bound, fun _ => 0⟩
+
+private theorem cursor_ne_bound : cursorReg r ≠ boundReg r := by
+ intro he
+ have := congrArg Fin.val he
+ simp [cursorReg, boundReg] at this
+
+private theorem boot_run (fuel : ℕ) (st : Word w) (m : Memory w) (bits : List Bool) :
+ let P := (machine T pub bound).program
+ execute P (fuel+3) (P.start st) m bits =
+ (execute P fuel (bootConfig (if st < bound then body T.entry else pre p 3) st bound) m bits).map
+ (fun rep => ⟨.tick :: .tick :: .tick :: rep.events, rep.result⟩) := by
+ dsimp only
+ have hpub : (machine T pub bound).publicData (Fin.last k) = bound := by simp [machine, Template.instantiate, publicData]
+ change execute _ (fuel+3) (Config.mk (pre p 0) st (fun _ => 0) (fun _ => 0)) _ _ = _
+ simp only [execute, Machine.program, code_pre, guardCode, Instr.run, Config.put, hpub,
+ Function.update_of_ne cursor_ne_bound, Function.update_self, Option.map_map]
+ rfl
+
+/-- The only overhead on an active call is three ticks. The original choices,
+probes, result, and remaining fuel have their exact native semantics. -/
+theorem execute_active (fuel : ℕ) (st : Word w) (hlt : st < bound) (m : Memory w) (bits : List Bool) :
+ let P := (machine T pub bound).program
+ let S := (T.instantiate w pub).program
+ execute P (fuel+3) (P.start st) m bits = (execute S fuel (S.start st) m bits).map
+ (fun rep => ⟨.tick :: .tick :: .tick :: rep.events, rep.result⟩) := by
+ dsimp only
+ rw [boot_run, ite_eq_left hlt]
+ let c : Config w p (r+2) := ⟨T.entry, st, bootRegs st bound, fun _ => 0⟩
+ change (execute _ fuel (embed c) m bits).map _ = _
+ rw [execute_body, wide, LiveStageLink.execute_widen]
+ have hpub : publicData pub bound ∘ Fin.castSucc = pub := by funext j; simp [publicData]
+ rw [hpub]
+ have hcfg : LiveStageLink.restrictConfig (regs r) c = (T.instantiate w pub).program.start st := by
+ change Config.mk _ _ _ _ = Config.mk _ _ _ _
+ congr 1
+ funext j
+ have h₀ : (regs r) j ≠ cursorReg r := by
+ intro he; have hv := congrArg Fin.val he; simp [regs, cursorReg] at hv; omega
+ have h₁ : (regs r) j ≠ boundReg r := by
+ intro he; have hv := congrArg Fin.val he; simp [regs, boundReg] at hv; omega
+ simp [c, bootRegs, Function.comp_apply, h₀, h₁]
+ rw [hcfg]
+
+/-- At the capacity the unique successful input is the empty choice string. -/
+theorem execute_closed (fuel : ℕ) (st : Word w) (hle : bound ≤ st) (m : Memory w) (bits : List Bool) :
+ let P := (machine T pub bound).program
+ execute P (fuel+4) (P.start st) m bits =
+ if bits = [] then some ⟨[.tick,.tick,.tick], none⟩ else none := by
+ dsimp only
+ rw [show fuel+4 = (fuel+1)+3 by omega, boot_run, ite_eq_right (not_lt.mpr hle)]
+ cases bits <;> simp [execute, Machine.program, bootConfig, code_pre, guardCode, Instr.run]
+
+end LiveHeaderBounded
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderBoundedRun.lean b/lean/OAI/Computability/VPVNP/LiveHeaderBoundedRun.lean
new file mode 100644
index 0000000000..353f4dae19
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderBoundedRun.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.LiveHeaderBounded
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+import OAI.Computability.VPVNP.RAMRecords
+import Mathlib.Data.ZMod.Defs
+
+/-!
+# Completing a bounded native stage
+
+The active calls preserve all source choices and memory effects. A single
+extra empty choice list acknowledges the end cursor and produces the
+accepting report seen by the linker.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderBounded
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- An active worker's report with the three local cursor-bound instructions prepended. -/
+def activeReport (rep : Report w) : Report w := ⟨.tick :: .tick :: .tick :: rep.events, rep.result⟩
+
+/-- The terminal report of the bound check, accepting after its three local instructions. -/
+def closedReport (w : ℕ) : Report w := ⟨[.tick,.tick,.tick], none⟩
+
+@[simp] theorem activeReport_probes (rep : Report w) : (activeReport rep).probes = rep.probes := rfl
+
+@[simp] theorem closedReport_probes : (closedReport w).probes = 0 := rfl
+
+@[simp] theorem activeReport_after (m : Memory w) (rep : Report w) :
+ after m (activeReport rep).events = after m rep.events := rfl
+
+@[simp] theorem activeReport_choiceBits (rep : Report w) : choiceBits (activeReport rep).events = choiceBits rep.events := rfl
+
+/-- Every source call begins with an active cursor. The result of the last
+call may be the bound itself. -/
+def Active (bound : Word w) : Option (Word w) → List (Report w) → Prop
+ | _, [] => True
+ | none, _ :: _ => False
+ | some st, x :: xs => st < bound ∧ Active bound x.result xs
+
+theorem endState_activeReports (s : Option (Word w)) (rs : List (Report w)) :
+ endState s (rs.map activeReport) = endState s rs := by
+ induction rs generalizing s with
+ | nil => rfl
+ | cons r rs ih => exact ih r.result
+
+theorem after_activeReports (m : Memory w) (rs : List (Report w)) :
+ after m (eventLog (rs.map activeReport)) = after m (eventLog rs) := by
+ induction rs generalizing m with
+ | nil => rfl
+ | cons r rs ih =>
+ simpa only [eventLog, List.map_cons, List.flatMap_cons, after, List.foldl_append,
+ activeReport, List.foldl_cons, update] using ih (after m r.events)
+
+variable (T : Template p r k) (pub : Fin k → Word w) (bound : Word w)
+
+/-- Exact trace equivalence for all the calls below the bound. -/
+theorem runSegment_active_iff (fuel : ℕ) (s : Option (Word w)) (m : Memory w)
+ (bs : List (List Bool)) (rs : List (Report w)) (h : Active bound s rs) :
+ runSegment (machine T pub bound).program (fuel+3) s m bs = some (rs.map activeReport) ↔
+ runSegment (T.instantiate w pub).program fuel s m bs = some rs := by
+ induction bs generalizing s m rs with
+ | nil => cases rs <;> simp [runSegment]
+ | cons bits bs ih =>
+ cases s with
+ | none => simp [runSegment]
+ | some st =>
+ cases rs with
+ | nil =>
+ simp only [List.map_nil, runSegment]
+ cases execute (machine T pub bound).program (fuel+3) ((machine T pub bound).program.start st) m bits <;>
+ cases execute (T.instantiate w pub).program fuel ((T.instantiate w pub).program.start st) m bits <;>
+ simp [Option.map_eq_some_iff]
+ | cons r rs =>
+ obtain ⟨hlt, hrest⟩ := h
+ simp only [List.map_cons, runSegment, execute_active T pub bound fuel st hlt]
+ cases he : execute (T.instantiate w pub).program fuel ((T.instantiate w pub).program.start st) m bits with
+ | none => simp
+ | some t =>
+ change ((runSegment _ _ t.result (after m t.events) bs).map (activeReport t :: ·)) = _ ↔
+ ((runSegment _ _ t.result (after m t.events) bs).map (t :: ·)) = _
+ by_cases htr : t = r
+ · subst t
+ simpa only [Option.map_eq_some_iff, List.cons.injEq, true_and, exists_eq_right] using
+ ih r.result (after m r.events) rs hrest
+ · have hwrapped : activeReport t ≠ activeReport r := by
+ intro hEq
+ cases t with | mk es out => cases r with | mk fs val =>
+ simp [activeReport] at hEq
+ exact htr (by simp [hEq])
+ simp [Option.map_eq_some_iff, htr, hwrapped]
+
+/-- Append the closing call to a successful active segment. -/
+theorem runSegment_complete {fuel : ℕ} (hfuel : 0 < fuel) (s : Option (Word w)) (m : Memory w)
+ (bs : List (List Bool)) (rs : List (Report w)) (st : Word w) (h : Active bound s rs)
+ (hsource : runSegment (T.instantiate w pub).program fuel s m bs = some rs)
+ (hend : endState s rs = some st) (hclosed : bound ≤ st) :
+ runSegment (machine T pub bound).program (fuel+3) s m (bs ++ [[]]) =
+ some (rs.map activeReport ++ [closedReport w]) := by
+ have ha := (runSegment_active_iff T pub bound fuel s m bs rs h).mpr hsource
+ rw [PrimedSchedule.runSegment_append, ha]
+ simp only [Option.bind_some, endState_activeReports, hend, runSegment]
+ have hc := execute_closed T pub bound (fuel-1) st hclosed (after m (eventLog (rs.map activeReport))) []
+ rw [show fuel-1+4 = fuel+3 by omega] at hc
+ simp only [ite_true] at hc
+ rw [hc]
+ rfl
+
+/-- For a table advancing its cursor by one on every successful call, every
+prefix of an in-bounds source scan satisfies the guard. -/
+theorem active_of_cursor_run (fuel start : ℕ) (m : Memory w)
+ (bs : List (List Bool)) (rs : List (Report w)) (hsize : start + bs.length ≤ bound.val)
+ (hrun : runSegment (T.instantiate w pub).program fuel (some (start : Word w)) m bs = some rs)
+ (hnext : ∀ i < bound.val, ∀ mem bits rep,
+ execute (T.instantiate w pub).program fuel ((T.instantiate w pub).program.start (i : Word w)) mem bits = some rep →
+ rep.result = some ((i+1 : ℕ) : Word w)) :
+ Active bound (some (start : Word w)) rs ∧
+ endState (some (start : Word w)) rs = some ((start+bs.length : ℕ) : Word w) := by
+ induction bs generalizing start m rs with
+ | nil =>
+ simp only [runSegment, Option.some.injEq] at hrun
+ subst rs
+ simp [Active, endState]
+ | cons bits bs ih =>
+ have hi : start < bound.val := by simp only [List.length_cons] at hsize; omega
+ have hword : (start : Word w) < bound := by
+ change start % (2^w) < bound.val
+ rwa [Nat.mod_eq_of_lt (hi.trans bound.isLt)]
+ simp only [runSegment] at hrun
+ cases he : execute (T.instantiate w pub).program fuel
+ ((T.instantiate w pub).program.start (start : Word w)) m bits with
+ | none => simp [he] at hrun
+ | some r =>
+ simp only [he, Option.map_eq_some_iff] at hrun
+ obtain ⟨rest, htail, rfl⟩ := hrun
+ have hres := hnext start hi m bits r he
+ rw [hres] at htail
+ obtain ⟨ha, hs⟩ := ih (start+1) (after m r.events) rest
+ (by simp only [List.length_cons] at hsize; omega) htail
+ refine ⟨⟨hword, hres ▸ ha⟩, ?_⟩
+ simpa only [endState, hres, List.length_cons, Nat.add_right_comm start 1 bs.length, Nat.add_assoc] using hs
+
+/-- Finish a complete cursor scan without requiring a separate prefix proof
+for its concrete report list. -/
+theorem runSegment_cursor_complete {fuel : ℕ} (hfuel : 0 < fuel) (start : ℕ) (m : Memory w)
+ (bs : List (List Bool)) (rs : List (Report w)) (hsize : start + bs.length = bound.val)
+ (hrun : runSegment (T.instantiate w pub).program fuel (some (start : Word w)) m bs = some rs)
+ (hnext : ∀ i < bound.val, ∀ mem bits rep,
+ execute (T.instantiate w pub).program fuel ((T.instantiate w pub).program.start (i : Word w)) mem bits = some rep →
+ rep.result = some ((i+1 : ℕ) : Word w)) :
+ runSegment (machine T pub bound).program (fuel+3) (some (start : Word w)) m (bs ++ [[]]) =
+ some (rs.map activeReport ++ [closedReport w]) := by
+ obtain ⟨ha, hs⟩ := active_of_cursor_run T pub bound fuel start m bs rs hsize.le hrun hnext
+ have hcast : (bound.val : Word w) = bound := Fin.ext (Nat.mod_eq_of_lt bound.isLt)
+ rw [hsize, hcast] at hs
+ exact runSegment_complete T pub bound hfuel _ m bs rs bound ha hrun hs le_rfl
+
+end LiveHeaderBounded
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderComplete.lean b/lean/OAI/Computability/VPVNP/LiveHeaderComplete.lean
new file mode 100644
index 0000000000..0c22fc6361
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderComplete.lean
@@ -0,0 +1,175 @@
+import OAI.Computability.VPVNP.LiveHeaderPrepared
+import OAI.Computability.VPVNP.LiveHeaderFieldSuffix
+import OAI.Computability.VPVNP.LiveHeaderFieldFormats
+import OAI.Computability.VPVNP.LiveHeaderUnique
+import OAI.Computability.VPVNP.LiveHeaderResources
+
+/-!
+# Complete native recovery of the live group's headers
+
+On compatible modes and canonically padded cuts, the one fixed template
+has exactly one accepting path. The resulting external memory contains the
+physical primed indices, advice, incident fields and dispatch words. The
+cost estimate includes room for an enclosing native stage linker.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderWidths LiveHeaderDescriptors
+open LiveHeader PrimedInputRAM ChainAssignments
+
+variable {w d : ℕ}
+
+theorem Prepared.sources {s : Sizes} {base : ℕ} {hw : 4 ≤ w} {advice : CutSchedule.Bits s.advice}
+ {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))} {tag : Mode.Tag} {m : Memory w}
+ (ready : Prepared (d := d) s base hw advice cuts g tag m) : Fields.Sources s base d hw advice cuts g tag m := by
+ refine ⟨ready.headers,?_,?_,ready.scalars (.flag .firstHalf),ready.scalars .firstTail⟩
+ · intro side
+ cases side with
+ | left =>
+ have hv := ready.scalars (.width .liveLeft) (Or.inr (Or.inl rfl))
+ change (m (widthAddr base .liveLeft)).val = CutSchedule.width (s.h+1) s.delta g.val
+ simpa only [Metadata.Field.address,index,Nat.add_sub_cancel] using hv
+ | right => exact ready.scalars (.width .liveRight) (Or.inr (Or.inr rfl))
+ · have htag := ready.scalars .mode
+ change m (tagAddr base) = Fin.ofNat (2^w) tag.code.val at htag
+ rw [htag,Fin.val_ofNat,Nat.mod_eq_of_lt]
+ exact tag.code.isLt.trans_le (Nat.pow_le_pow_right (by decide) (by omega : 2 ≤ w))
+
+/-- Readback in the final memory. The intermediate memory records the initial
+zero defaults used when a cut field is absent. -/
+structure Output (s : Sizes) (base d : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (m : Memory w) : Prop where
+ sources : Fields.Sources s base d hw advice cuts g tag m
+ scalars : ∀ f : Metadata.Field, Metadata.Correct s (g.val+1) tag f (m (f.address base))
+ adviceWords : ∀ j : Fin s.advice, m (adviceBase s base+j.val) = encodeBit w (advice j)
+ primedLeft : ∀ j < s.h+2, m (leftIndexBase s base+j) = encodeBit w ((2*(g.val+1)-1).testBit j)
+ primedRight : ∀ j < s.h+2, m (rightIndexBase s base+j) = encodeBit w ((2*(g.val+1)).testBit j)
+ fieldImage : ∃ before, (∀ a, exteriorBase s base .left ≤ a → before a = 0) ∧
+ Fields.Image s base cuts g tag 8 before m
+
+private theorem assembledOutput {s : Sizes} {base : ℕ} {hw : 4 ≤ w} {advice : CutSchedule.Bits s.advice}
+ {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))} {tag : Mode.Tag} {before m : Memory w}
+ (ready : Prepared (d := d) s base hw advice cuts g tag before)
+ (src : Fields.Sources s base d hw advice cuts g tag m) (img : Fields.Image s base cuts g tag 8 before m) :
+ Output s base d hw advice cuts g tag m := by
+ have frame (a : ℕ) (hb : a ≠ base) (ho : a ≠ offsetAddr base) (hc : a ≠ countAddr base)
+ (h : a < adviceBase s base+s.advice) : m a = before a :=
+ img.frame _ ⟨hb,ho,hc,fun side f hf => Or.inl (h.trans_le (dest_bounds s base side f hf).1)⟩
+ have keep (a : ℕ) (h : base+14 < a) (hle : a < adviceBase s base+s.advice) : m a = before a :=
+ frame _ (by omega) (by dsimp [offsetAddr]; omega) (by dsimp [countAddr]; omega) hle
+ have hL : base+14 < leftIndexBase s base := by dsimp [leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ have hR : leftIndexBase s base+(s.h+2) = rightIndexBase s base := rfl
+ have hA : rightIndexBase s base+(s.h+2) = adviceBase s base := rfl
+ refine ⟨src,?_,?_,?_,?_,⟨before,ready.zero,img⟩⟩
+ · intro f
+ have hs : base < f.address base ∧ f.address base < offsetAddr base := by
+ cases f with
+ | width slot => cases slot <;> dsimp [Metadata.Field.address,widthAddr,offsetAddr] <;> omega
+ | flag flag => cases flag <;> dsimp [Metadata.Field.address,flagAddr,offsetAddr] <;> omega
+ | firstTail | mode => dsimp [Metadata.Field.address,tagAddr,firstTailAddr,offsetAddr]; omega
+ rw [frame _ hs.1.ne' hs.2.ne (by dsimp [countAddr,offsetAddr] at *; omega)
+ (by dsimp [offsetAddr] at hs; omega)]
+ exact ready.scalars f
+ · intro j
+ rw [keep _ (by omega) (Nat.add_lt_add_left j.isLt _)]
+ exact ready.adviceWords j
+ · intro j hj
+ rw [keep _ (by omega) (by omega)]
+ exact ready.primedLeft j hj
+ · intro j hj
+ rw [keep _ (by omega) (by omega)]
+ exact ready.primedRight j hj
+
+/-- All 31 component stages run from the actual initialized processor
+memory with empty choice strings. -/
+theorem complete_stages (s : Sizes) (base : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : Mode.Tag)
+ (bounds : Fields.Bounds s base d w) (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d)
+ (hsel : physicalTag cuts g = some tag) (valid : ∀ side, Fields.ValidPadding s cuts g tag side) :
+ let m := physicalMemory (d := d) hw advice cuts g
+ ∃ xs out, StageRuns s base (some (⟨0,by decide⟩ : StageId)) m xs ∧
+ (∀ x ∈ xs, x.Good s) ∧ finalMemory (Fin.ofNat _ base) m xs = out ∧
+ Output s base d hw advice cuts g tag out := by
+ obtain ⟨xs,mid,first,g₁,ready⟩ := prepared_prefix s base hw advice cuts g tag hsel indices adv
+ bounds.scratch bounds.fit.le
+ obtain ⟨ys,out,g₂,last,_,src,img⟩ := Fields.suffix_native bounds ready.sources valid
+ have all := first.append last
+ refine ⟨xs++ys,out,by simpa using all.finish (.done out),?_,all.finalMemory,assembledOutput ready src img⟩
+ intro x hx
+ exact (List.mem_append.mp hx).elim (g₁ x) (g₂ x)
+
+private theorem flatten_replicates {α β : Type*} (n : α → ℕ) (v : β) (xs : List α) :
+ (xs.map (fun x => List.replicate (n x) v)).flatten = List.replicate (xs.map n).sum v := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih => simp only [List.map_cons,List.flatten_cons,List.sum_cons,List.replicate_add,ih]
+
+/-- The linked native interpreter has one accepting run, with precisely the
+scheduled number of empty choices. Its output and cost are independent of
+any external path oracle. -/
+theorem valid_native (s : Sizes) (base cap : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : Mode.Tag)
+ (bounds : Fields.Bounds s base d w) (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d)
+ (tagFit : stages.length ≤ 2^w) (fuel : 107 ≤ cap)
+ (hsel : physicalTag cuts g = some tag) (valid : ∀ side, Fields.ValidPadding s cuts g tag side) :
+ let P := (program.instantiate w (publicData w s base)).program
+ let m := physicalMemory (d := d) hw advice cuts g
+ ∃ rs, runSegment P cap (some 0) m (List.replicate (callBound s) []) = some rs ∧
+ endState (some 0) rs = none ∧ Output s base d hw advice cuts g tag (after m (eventLog rs)) ∧
+ rs.length = callBound s ∧ RAMBuckets.cost Report.probes rs + 2*rs.length ≤ costBound s ∧
+ (∀ x ∈ rs, x.probes ≤ 8) ∧
+ ∀ bs other, runSegment P cap (some 0) m bs = some other → endState (some 0) other = none →
+ bs = List.replicate (callBound s) [] ∧ other = rs := by
+ let m := physicalMemory (d := d) hw advice cuts g
+ obtain ⟨xs,out,full,good,hout,data⟩ := complete_stages s base hw advice cuts g tag bounds indices adv hsel valid
+ have room (x : StageTrace w) (hx : x ∈ xs) : x.fuel + 2*stages.length+5 ≤ cap := by
+ have h := (good x hx).1
+ rw [stage_count]
+ omega
+ let addr : Word w := Fin.ofNat _ base
+ let rs := xs.flatMap (fun x => x.output addr)
+ have haddr : addr.val = base := by
+ have h := bounds.fit
+ rw [limit_eq] at h
+ exact Nat.mod_eq_of_lt (by omega)
+ have hz : m addr.val = 0 := by
+ have h := bounds.scratch
+ simp [m,physicalMemory,RAMMemory.initialMemory,haddr,show ¬base < 2^d by omega]
+ have ids : xs.map (fun x => stage x.id) = stages := full.schedule
+ have hpaths : xs.flatMap StageTrace.paths = List.replicate (callBound s) [] := by
+ calc
+ xs.flatMap StageTrace.paths = (xs.map (fun x => List.replicate (calls s (stage x.id)) [])).flatten := by
+ rw [List.flatMap_def]
+ exact congrArg List.flatten (List.map_congr_left (fun x hx => (good x hx).2.1))
+ _ = List.replicate (xs.map (fun x => calls s (stage x.id))).sum [] := flatten_replicates _ _ _
+ _ = List.replicate (callBound s) [] := by
+ rw [← sum_calls,← ids,List.map_map,Function.comp_def]
+ obtain ⟨hr,ha,hm,cost⟩ := run_of_stages s base cap tagFit full room (by rintro i ⟨⟩; exact hz)
+ have len : rs.length = callBound s := by
+ rw [calls_output,← sum_calls,← ids,List.map_map]
+ exact congrArg List.sum (List.map_congr_left fun x hx => (good x hx).2.2.1)
+ obtain ⟨_,budget⟩ := complete_budget s base full (fun x hx => (good x hx).2.2.1.le)
+ (fun x hx => (good x hx).2.2.2)
+ refine ⟨rs,hpaths ▸ hr,ha,hm ▸ hout ▸ data,len,?_,?_,?_⟩
+ · rw [cost,calls_output]
+ exact budget
+ · intro y hy
+ obtain ⟨x,hx,hy⟩ := List.mem_flatMap.mp hy
+ obtain ⟨z,hz',rfl⟩ := List.mem_map.mp hy
+ rw [LiveStageLink.linkedReport_probes]
+ have h := ((good x hx).2.2.2 z hz').trans (probe_limit _)
+ split <;> omega
+ · intro bs other hbs hother
+ obtain ⟨hb,he⟩ := BurstRAM.accepted_empty_unique (hpaths ▸ hr) ha hbs hother
+ exact ⟨hb,he⟩
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderCopyDispatch.lean b/lean/OAI/Computability/VPVNP/LiveHeaderCopyDispatch.lean
new file mode 100644
index 0000000000..c399d75359
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderCopyDispatch.lean
@@ -0,0 +1,305 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete
+import OAI.Computability.VPVNP.RAMRecords
+import Mathlib.Data.ZMod.Defs
+import Mathlib.Tactic.Ring
+import Mathlib.Tactic.FinCases
+
+/-!
+# Native dispatch over the seven auxiliary header segments
+
+Each three-word descriptor contains its cumulative end, source base and destination
+base. A call uses the persistent cursor to find the first descriptor whose end
+exceeds it, copies one word at the corresponding offset, and advances the cursor.
+The entire dispatch table is fixed independently of the input length and word size.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderCopyDispatch
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- One entry in the seven-segment auxiliary copy table, specifying its exclusive end and its
+two array bases. -/
+structure Descriptor (w : ℕ) where
+ /-- The cumulative exclusive cursor bound for this copy segment. -/
+ endOffset : Word w
+ /-- The source address of the first word in this segment. -/
+ sourceBase : Word w
+ /-- The destination address of the first word in this segment. -/
+ targetBase : Word w
+
+/-- Three consecutive descriptor words, addressed in the RAM word arithmetic. -/
+def address (base : Word w) (i : Fin 7) (field : Fin 3) : Word w :=
+ base + ((3 * i.val + field.val : ℕ) : Word w)
+
+/-- The external table stores the exclusive end, source, and destination for each of the seven
+copy descriptors at its assigned addresses. -/
+structure Spec (base : Word w) (records : Fin 7 → Descriptor w) (m : Memory w) : Prop where
+ ends : ∀ i, m (address base i 0).val = (records i).endOffset
+ sources : ∀ i, m (address base i 1).val = (records i).sourceBase
+ targets : ∀ i, m (address base i 2).val = (records i).targetBase
+
+/-- The cumulative end of the preceding descriptor, or zero for the first, used to form a
+segment-relative offset. -/
+def prevEnd (records : Fin 7 → Descriptor w) (i : Fin 7) : Word w :=
+ if h : 0 < i.val then (records ⟨i.val - 1, by omega⟩).endOffset else 0
+
+/-- Native header-copy dispatch code over twelve registers and the public descriptor-table
+base. -/
+abbrev Code := Flow 12 1
+
+/-- Load the persistent cursor and descriptor pointer, initialize the previous end to zero, and
+set the word and descriptor strides. -/
+def setup : Code :=
+ .seq (.line (.stateWord 0)) <| .seq (.line (.publicWord 1 0)) <| .seq (.line (.constant 2 0)) <|
+ .seq (.line (.constant 3 1)) (.line (.constant 4 3))
+
+/-- Copy the word at the cursor's relative position in the selected descriptor and compute the
+next cursor. -/
+def hit : Code :=
+ .seq (.line (.binary .sub 6 0 2)) <| .seq (.line (.binary .add 7 1 3)) <| .seq (.line (.read 8 7)) <|
+ .seq (.line (.binary .add 7 7 3)) <| .seq (.line (.read 9 7)) <| .seq (.line (.binary .add 8 8 6)) <|
+ .seq (.line (.binary .add 9 9 6)) <| .seq (.line (.read 10 8)) <| .seq (.line (.write 9 10))
+ (.line (.binary .add 11 0 3))
+
+/-- Remember the current descriptor's end and advance the pointer by three words to inspect the
+next descriptor. -/
+def skip : Code := .seq (.line (.copy 2 5)) (.line (.binary .add 1 1 4))
+
+/-- An exhausted table rejects by comparing a register strictly with itself. -/
+def scan : ℕ → Code
+ | 0 => .line (.guardLt 0 0)
+ | n + 1 => .seq (.line (.read 5 1)) (.ifLt 0 5 hit (.seq skip (scan n)))
+
+/-- Initialize the copy dispatcher and search its seven descriptors for the segment containing
+the cursor. -/
+def flow : Code := .seq setup (scan 7)
+
+/-- Instantiate the seven-segment copy dispatcher at the supplied external table base. -/
+def program (base : Word w) := ((flow.template (some 11)).instantiate w (fun _ => base)).program
+
+private theorem addr_one (base : Word w) (i : Fin 7) : address base i 0 + 1 = address base i 1 := by
+ simp [address, add_assoc]
+
+private theorem addr_two (base : Word w) (i : Fin 7) : address base i 0 + 1 + 1 = address base i 2 := by
+ simp [address, add_assoc]
+ ring
+
+private theorem addr_next (base : Word w) (i j : Fin 7) (hj : j.val = i.val + 1) :
+ address base i 0 + 3 = address base j 0 := by
+ simp [address, hj]; ring
+
+private theorem prev_next (records : Fin 7 → Descriptor w) (i j : Fin 7) (hj : j.val = i.val + 1) :
+ prevEnd records j = (records i).endOffset := by
+ simp [prevEnd, hj]
+
+private theorem hit_exec (pub : Fin 1 → Word w) (state : Word w) (m : Memory w) (rs : Regs w 12)
+ (h0 : rs 0 = state) (h3 : rs 3 = 1) (src dst : Word w)
+ (hsrc : m (rs 1 + 1).val = src) (hdst : m (rs 1 + 1 + 1).val = dst) :
+ let fromAddr := src + (state - rs 2)
+ let toAddr := dst + (state - rs 2)
+ ∃ es out, Flow.Exec pub state hit rs m es out (writeMemory m toAddr (m fromAddr.val)) ∧
+ out 11 = state+1 ∧ after m es = writeMemory m toAddr (m fromAddr.val) ∧
+ es.length = 10 ∧ countProbes es = 4 ∧ choiceBits es = [] := by
+ dsimp only
+ let fromAddr := src + (state-rs 2)
+ let toAddr := dst + (state-rs 2)
+ let es : List (Event w) := [.tick, .tick, .read (rs 1+1) src, .tick,
+ .read (rs 1+1+1) dst, .tick, .tick, .read fromAddr (m fromAddr.val), .write toAddr (m fromAddr.val), .tick]
+ have exec : ∃ out, Flow.once pub state false hit rs m = some (es, out, writeMemory m toAddr (m fromAddr.val)) ∧
+ out 11 = state+1 := by
+ simp (config := { decide := true }) [hit, Flow.once, Op.effect, Function.update,
+ show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.sub.eval = (· - · : Word w → Word w → Word w) from rfl, h0, h3, hsrc, hdst,
+ es, fromAddr, toAddr]
+ obtain ⟨out, hx, hout⟩ := exec
+ exact ⟨es, out, (Flow.once_sound _ _ _ _ _ _ hx).1, hout, rfl, rfl, rfl, rfl⟩
+
+private theorem scan_exec (base : Word w) (records : Fin 7 → Descriptor w) (state : Word w)
+ (m : Memory w) (spec : Spec base records m) (i : Fin 7)
+ (hskip : ∀ j, j < i → (records j).endOffset ≤ state) (hhit : state < (records i).endOffset)
+ (n : ℕ) (j : Fin 7) (hj : j ≤ i) (hn : i.val < j.val + n) (rs : Regs w 12)
+ (h0 : rs 0 = state) (h1 : rs 1 = address base j 0) (h2 : rs 2 = prevEnd records j)
+ (h3 : rs 3 = 1) (h4 : rs 4 = 3) :
+ let src := (records i).sourceBase + (state - prevEnd records i)
+ let dst := (records i).targetBase + (state - prevEnd records i)
+ ∃ es out, Flow.Exec (fun _ => base) state (scan n) rs m es out (writeMemory m dst (m src.val)) ∧
+ out 11 = state+1 ∧ after m es = writeMemory m dst (m src.val) ∧
+ es.length = 4 * (i.val-j.val) + 12 ∧ countProbes es = i.val-j.val+5 ∧ choiceBits es = [] := by
+ dsimp only
+ induction n generalizing j rs with
+ | zero => have := Fin.le_iff_val_le_val.mp hj; omega
+ | succ n ih =>
+ let r := Function.update rs (5 : Fin 12) (records j).endOffset
+ let e := Event.read (address base j 0) (records j).endOffset
+ have rd : Flow.Exec (fun _ : Fin 1 => base) state (.line (.read 5 1)) rs m [e] r m := by
+ apply Flow.Exec.line
+ simp [Op.effect, e, r, h1, spec.ends]
+ have r0 : r 0 = state := h0
+ have r1 : r 1 = address base j 0 := h1
+ have r2 : r 2 = prevEnd records j := h2
+ have r3 : r 3 = 1 := h3
+ have r4 : r 4 = 3 := h4
+ have r5 : r 5 = (records j).endOffset := Function.update_self ..
+ by_cases hi : j = i
+ · subst j
+ obtain ⟨es, out, he, hret, hmem, hlen, hprobe, hbits⟩ := hit_exec (fun _ => base) state m r r0 r3
+ (records i).sourceBase (records i).targetBase (by rw [r1, addr_one, spec.sources])
+ (by rw [r1, addr_two, spec.targets])
+ rw [r2] at he hmem
+ refine ⟨e :: .tick :: es, out, rd.seq (.ifLtYes (by rwa [r0, r5]) he), hret, hmem, ?_, ?_, hbits⟩
+ · simp [hlen]
+ · simp [e, countProbes, hprobe]
+ · have hlt := lt_of_le_of_ne hj hi
+ let j' : Fin 7 := ⟨j.val+1, Nat.lt_of_le_of_lt hlt i.isLt⟩
+ have hj' : j' ≤ i := hlt
+ have hn' : i.val < j'.val+n := by change i.val < (j.val+1)+n; omega
+ let next := Function.update (Function.update r (2 : Fin 12) (r 5)) (1 : Fin 12) (r 1+r 4)
+ have hs : Flow.Exec (fun _ => base) state skip r m [.tick,.tick] next m :=
+ (Flow.once_sound _ _ false skip r m rfl).1
+ have n1 : next 1 = address base j' 0 := by
+ change r 1 + r 4 = _
+ rw [r1, r4, addr_next base j j' rfl]
+ have n2 : next 2 = prevEnd records j' := by
+ change r 5 = _
+ rw [r5, prev_next records j j' rfl]
+ obtain ⟨es, out, he, hret, hmem, hlen, hprobe, hbits⟩ := ih j' hj' hn' next r0 n1 n2 r3 r4
+ refine ⟨e :: .tick :: .tick :: .tick :: es, out,
+ rd.seq (.ifLtNo (by rw [r0,r5]; exact not_lt.mpr (hskip j hlt)) (hs.seq he)),
+ hret, hmem, ?_, ?_, hbits⟩
+ have hv : j.val < i.val := hlt
+ · simp only [List.length_cons, hlen, j']; omega
+ · simp only [e, countProbes, hprobe, j']; omega
+
+/-- The first descriptor ending strictly above the cursor performs one word copy.
+At most eleven probes are needed, including the descriptor reads and the data access. -/
+theorem row_native (base : Word w) (records : Fin 7 → Descriptor w) (state : Word w) (m : Memory w)
+ (hspec : Spec base records m) (i : Fin 7) (hskip : ∀ j, j < i → (records j).endOffset ≤ state)
+ (hhit : state < (records i).endOffset) :
+ let src := (records i).sourceBase + (state - prevEnd records i)
+ let dst := (records i).targetBase + (state - prevEnd records i)
+ ∃ es, execute (program base) 64 ((program base).start state) m [] = some ⟨es, some (state+1)⟩ ∧
+ after m es = writeMemory m dst (m src.val) ∧ es.length < 64 ∧ countProbes es ≤ 11 ∧ choiceBits es = [] := by
+ dsimp only
+ let regs : Regs w 12 := ![state, base, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0]
+ have init : Flow.Exec (fun _ => base) state setup (fun _ => 0) m (List.replicate 5 .tick) regs m := by
+ apply (Flow.once_sound _ _ false setup _ _ ?_).1
+ simp (config := { decide := true }) [setup, Flow.once, Op.effect, regs]
+ funext k
+ fin_cases k <;> rfl
+ obtain ⟨es, out, he, hret, hmem, hlen, hprobe, hbits⟩ :=
+ scan_exec base records state m hspec i hskip hhit 7 0 (Fin.zero_le _) (by simp) regs
+ rfl (by simp [regs,address]) (by simp [regs,prevEnd]) rfl rfl
+ let log := List.replicate 5 (.tick : Event w) ++ es
+ have len : log.length < 64 := by simp [log, hlen]; have := i.isLt; omega
+ have bits : choiceBits log = [] := hbits
+ refine ⟨log, ?_, hmem, len, ?_, bits⟩
+ · apply (Flow.template_execute_iff flow (some 11) (fun _ => base) state (fun _ => 0) (fun _ => 0) m _ _ _).2
+ exact ⟨out, _, init.seq he, congrArg some hret.symm, len, bits⟩
+ · change countProbes es ≤ 11
+ simp only [hprobe, Fin.val_zero, Nat.sub_zero]
+ have := i.isLt
+ omega
+
+private theorem scan_reject {pub : Fin 1 → Word w} {state : Word w} {m m' : Memory w}
+ {rs out : Regs w 12} {es : List (Event w)} (n : ℕ) (stride : rs 4 = 3)
+ (ends : ∀ j < n, m (rs 1 + ((3 * j : ℕ) : Word w)).val ≤ rs 0) :
+ ¬ Flow.Exec pub state (scan n) rs m es out m' := by
+ induction n generalizing rs es with
+ | zero =>
+ intro he
+ cases he with
+ | line h => simp [Op.effect] at h
+ | succ n ih =>
+ intro he
+ cases he with
+ | seq first branch =>
+ cases first with
+ | line hread =>
+ simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at hread
+ obtain ⟨rfl, rfl, rfl⟩ := hread
+ cases branch with
+ | ifLtYes h _ =>
+ have h₀ := ends 0 (by omega)
+ simp only [Nat.mul_zero, Nat.cast_zero, add_zero] at h₀
+ exact (not_lt_of_ge h₀) (by simpa (config := {decide := true}) [Function.update] using h)
+ | ifLtNo _ skipped =>
+ cases skipped with
+ | seq prep rest =>
+ cases prep with
+ | seq copied moved =>
+ cases copied with
+ | line hc =>
+ simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at hc
+ obtain ⟨rfl,rfl,rfl⟩ := hc
+ cases moved with
+ | line hm =>
+ simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at hm
+ obtain ⟨rfl,rfl,rfl⟩ := hm
+ apply ih _ _ rest
+ · simpa (config := {decide := true}) [Function.update] using stride
+ · intro j hj
+ have h := ends (j+1) (by omega)
+ simpa (config := {decide := true}) [Function.update, BinaryOp.eval, stride,
+ Nat.mul_add, add_assoc, add_left_comm, add_comm] using h
+
+/-- No successful structured execution starts beyond the cumulative ends. -/
+theorem flow_reject {base state : Word w} {records : Fin 7 → Descriptor w} {m : Memory w}
+ (layout : Spec base records m) (outside : ∀ i, (records i).endOffset ≤ state)
+ (rs out : Regs w 12) (es : List (Event w)) (m' : Memory w) :
+ ¬ Flow.Exec (fun _ => base) state flow rs m es out m' := by
+ intro he
+ cases he with
+ | seq prep tail =>
+ unfold setup at prep
+ iterate 4
+ cases prep
+ rename_i head prep
+ cases head
+ rename_i h
+ simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at h
+ obtain ⟨rfl,rfl,rfl⟩ := h
+ cases prep
+ rename_i h
+ simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at h
+ obtain ⟨rfl,rfl,rfl⟩ := h
+ apply scan_reject 7 (by rfl) _ tail
+ intro j hj
+ let i : Fin 7 := ⟨j,hj⟩
+ change m (address base i 0).val ≤ state
+ rw [layout.ends]
+ exact outside i
+
+/-- Every state past the last occupied descriptor fails, including with arbitrary
+fuel and an arbitrary branch tape. The rejecting comparison also covers an empty sweep. -/
+theorem reject_outside (base state : Word w) (records : Fin 7 → Descriptor w) (m : Memory w)
+ (layout : Spec base records m) (outside : ∀ i, (records i).endOffset ≤ state)
+ (fuel : ℕ) (bits : List Bool) :
+ execute (program base) fuel ((program base).start state) m bits = none := by
+ cases h : execute (program base) fuel ((program base).start state) m bits with
+ | none => rfl
+ | some rep =>
+ have hh := (Flow.template_execute_iff flow (some 11) (fun _ => base) state
+ (fun _ => 0) (fun _ => 0) m fuel bits rep).mp h
+ obtain ⟨out,m',he,_⟩ := hh
+ exact False.elim (flow_reject layout outside _ _ _ _ he)
+
+/-- For cumulative ends in order, the last end is the exclusive upper bound on the cursor. -/
+theorem reject_ge_last (base state : Word w) (records : Fin 7 → Descriptor w) (m : Memory w)
+ (layout : Spec base records m) (ordered : Monotone fun i => (records i).endOffset)
+ (past : (records (Fin.last 6)).endOffset ≤ state) (fuel : ℕ) (bits : List Bool) :
+ execute (program base) fuel ((program base).start state) m bits = none :=
+ reject_outside base state records m layout (fun i => (ordered (Fin.le_last i)).trans past) fuel bits
+
+end LiveHeaderCopyDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderCursorFrame.lean b/lean/OAI/Computability/VPVNP/LiveHeaderCursorFrame.lean
new file mode 100644
index 0000000000..45ba97cf13
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderCursorFrame.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.LiveStageSegments
+import OAI.Computability.VPVNP.LiveHeaderBoundedRun
+
+/-!
+# Frames of continuing live-header scan calls
+
+A scan increments its cursor and preserves the reserved stage word at each
+step. The extra ticks of the bound check and its closing call preserve this
+property for the reported native stage.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink LiveHeaderBounded
+open scoped Fin.CommRing
+
+variable {w : ℕ} {C : Type*}
+
+theorem runSegment_cursor_frame (P : Program w C) (fuel bound : ℕ) (addr : Word w)
+ (step : ∀ i < bound, ∀ mem rep, execute P fuel (P.start (i : Word w)) mem [] = some rep →
+ rep.result = some ((i+1 : ℕ) : Word w) ∧ after mem rep.events addr.val = mem addr.val)
+ (start n : ℕ) (m : Memory w) (rs : List (Report w)) (hle : start+n ≤ bound)
+ (hrun : runSegment P fuel (some (start : Word w)) m (List.replicate n []) = some rs) :
+ PreservesTagOnReturns addr m rs := by
+ induction n generalizing start m rs with
+ | zero =>
+ simp [runSegment] at hrun
+ subst rs
+ trivial
+ | succ n ih =>
+ rw [List.replicate_succ,runSegment] at hrun
+ cases he : execute P fuel (P.start (start : Word w)) m [] with
+ | none => simp [he] at hrun
+ | some rep =>
+ simp only [he, Option.map_eq_some_iff] at hrun
+ obtain ⟨rest, hr, rfl⟩ := hrun
+ obtain ⟨hnext, hframe⟩ := step start (by omega) m rep he
+ rw [hnext] at hr
+ exact ⟨fun _ => hframe, ih (start+1) _ rest (by omega) hr⟩
+
+theorem guarded_frame {addr : Word w} {m : Memory w} {rs : List (Report w)}
+ (h : PreservesTagOnReturns addr m rs) : PreservesTagOnReturns addr m (rs.map activeReport ++ [closedReport w]) := by
+ apply PreservesTagOnReturns.append
+ · induction rs generalizing m with
+ | nil => trivial
+ | cons r rs ih => exact ⟨h.1, ih h.2⟩
+ · exact PreservesTagOnReturns.singleton_accept _ _ _ rfl
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderCutInput.lean b/lean/OAI/Computability/VPVNP/LiveHeaderCutInput.lean
new file mode 100644
index 0000000000..23b85aebfc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderCutInput.lean
@@ -0,0 +1,270 @@
+import OAI.Computability.VPVNP.LiveExponentBuffers
+import OAI.Computability.VPVNP.LiveHeaderFieldRuns
+import OAI.Computability.VPVNP.LiveHeaderIndexInput
+import OAI.Computability.VPVNP.LiveHeaderPhysical
+
+/-!
+# Native readback of the two incident live cuts
+
+The incoming cut at a group is its preceding cut and the outgoing cut is
+its following cut. A copy interval reads the corresponding slot of the
+original physical processor header and writes one encoded bit per word.
+The same physical readback identifies the native padding guard with the
+canonical zero padding of each typed layout.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ChainAssignments
+open CutSchedule LiveHeaderDescriptors
+open scoped Fin.CommRing
+
+variable {w d a h Δ W t Z c : ℕ}
+
+/-- The two incident cut slots in the four-bit processor word. -/
+def cutSlot : Side → Fin 4
+ | .left => 2
+ | .right => 3
+
+/-- Index of the physical cut shared by consecutive groups. -/
+def incidentCut (side : Side) (g : Fin (2^(h+1))) : Fin (2^(h+1)+1) :=
+ match side with
+ | .left => g.castSucc
+ | .right => g.succ
+
+/-- The processor sites still contain the original packed headers at this
+point in the computation. Scratch memory is allowed to contain live data. -/
+def SiteHeaders (d : ℕ) (hw : 4 ≤ w) (advice : Bits a) (cuts : AllCuts h Δ)
+ (g : Fin (2^(h+1))) (m : Memory w) : Prop :=
+ ∀ v : Fin (2^d), m v.val = ProcessorInput.headerWord hw (physicalHeader advice cuts g v)
+
+theorem siteHeaders_initial (hw : 4 ≤ w) (advice : Bits a) (cuts : AllCuts h Δ)
+ (g : Fin (2^(h+1))) :
+ SiteHeaders d hw advice cuts g (physicalMemory (d := d) hw advice cuts g) :=
+ physicalMemory_word hw advice cuts g
+
+theorem SiteHeaders.bit {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (v : Fin (2^d)) (slot : Fin 4) : (m v.val).val.testBit slot.val = physicalHeader advice cuts g v slot := by
+ rw [headers v]
+ change (ProcessorInput.headerWord hw (physicalHeader advice cuts g v)).val.testBit
+ (slot.castLE hw).val = _
+ rw [testBit_wordBits, ProcessorInput.headerWord_bit]
+
+theorem SiteHeaders.cutBit {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (side : Side) (v : Fin (2^d)) :
+ (m v.val).val.testBit (cutSlot side).val = distributedBit (cuts (incidentCut side g)) v.val := by
+ rw [headers.bit]
+ cases side <;> rfl
+
+/-- The exact original cut bits at consecutive scratch addresses. -/
+def CopiedSlice (bits : Bits W) (iv : ℕ × ℕ) (dst : ℕ) (m : Memory w) : Prop :=
+ ∀ (j : ℕ) (site : Fin W), j < iv.2 → site.val = iv.1+j →
+ m (dst+j) = PrimedInputRAM.encodeBit w (bits site)
+
+/-- Interpret a completed copy, including one performed by a fixed-capacity
+runner, in terms of the group cut supplied to the contraction. -/
+theorem FieldCopy.physical {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m out : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (side : Side) (iv : ℕ × ℕ) (dst : ℕ) (sites : iv.1+iv.2 ≤ 2^d) (scratch : 2^d ≤ dst)
+ (copy : FieldCopy m (cutSlot side) iv.1 dst iv.2 out) :
+ CopiedSlice (cuts (incidentCut side g)) iv dst out ∧ SiteHeaders d hw advice cuts g out := by
+ constructor
+ · intro j site hj hs
+ have hsite : iv.1+j < 2^d := by omega
+ let v : Fin (2^d) := ⟨iv.1+j,hsite⟩
+ rw [copy.copied j hj, headers.cutBit side v]
+ have hlt : v.val < width (h+1) Δ (incidentCut side g).val := by
+ change iv.1+j < _
+ rw [← hs]
+ exact site.isLt
+ rw [distributedBit, dite_eq_left hlt]
+ exact congrArg (fun b => PrimedInputRAM.encodeBit w (cuts (incidentCut side g) b)) (Fin.ext hs.symm)
+ · intro v
+ rw [copy.frame v.val (Or.inl (v.isLt.trans_le scratch)), headers v]
+
+/-- Execute the native bit-copy table with the descriptor installed in
+memory. The same reports give the typed readback and preserve every site. -/
+theorem physical_copy_native {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (side : Side) (iv : ℕ × ℕ) (pub : Fin 3 → Word w) (source : (m (pub 1).val).val = iv.1)
+ (sites : iv.1+iv.2 ≤ 2^d) (scratch : 2^d ≤ (pub 2).val)
+ (hdesc : (pub 1).val < (pub 2).val ∨ (pub 2).val+iv.2 ≤ (pub 1).val)
+ (hfit : (pub 2).val+iv.2 ≤ 2^w) :
+ let P := ((template (copyFieldCell (cutSlot side)) 7).instantiate w pub).program
+ ∃ rs, runSegment P 16 (some (pub 0)) m (List.replicate iv.2 []) = some rs ∧
+ endState (some (pub 0)) rs = some (pub 0 + (iv.2 : Word w)) ∧ rs.length = iv.2 ∧
+ (∀ x ∈ rs, countProbes x.events ≤ 3) ∧
+ FieldCopy m (cutSlot side) iv.1 (pub 2).val iv.2 (after m (eventLog rs)) ∧
+ CopiedSlice (cuts (incidentCut side g)) iv (pub 2).val (after m (eventLog rs)) ∧
+ SiteHeaders d hw advice cuts g (after m (eventLog rs)) := by
+ obtain ⟨rs, hr, he, hc, hl, hp⟩ := copy_field_native hw (cutSlot side) pub m iv.2
+ (by rw [source]; exact sites.trans scratch) hdesc hfit
+ rw [source] at hc
+ exact ⟨rs, hr, he, hl, hp, hc, hc.physical headers side iv _ sites scratch⟩
+
+/-- Exact interpretation of the padding reads. An interval with no sites
+imposes the empty conjunction. -/
+theorem SiteHeaders.zeroSlice {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (side : Side) (iv : ℕ × ℕ) (sites : iv.1+iv.2 ≤ 2^d)
+ (inside : iv.1+iv.2 ≤ width (h+1) Δ (incidentCut side g).val) :
+ (∀ j < iv.2, (m (iv.1+j)).val.testBit (cutSlot side).val = false) ↔
+ Physical.ZeroSlice (cuts (incidentCut side g)) iv := by
+ have read (j : ℕ) (hj : j < iv.2) :
+ (m (iv.1+j)).val.testBit (cutSlot side).val =
+ cuts (incidentCut side g) ⟨iv.1+j, by omega⟩ := by
+ let v : Fin (2^d) := ⟨iv.1+j, by omega⟩
+ rw [headers.cutBit side v, distributedBit, dite_eq_left (show v.val < _ by dsimp [v]; omega)]
+ constructor
+ · intro hz j site hj hs
+ have he : site = ⟨iv.1+j, by omega⟩ := Fin.ext hs
+ rw [he, ← read j hj]
+ exact hz j hj
+ · intro hz j hj
+ rw [read j hj]
+ exact hz j _ hj rfl
+
+/-- Native success on arbitrary physical cut input is equivalent to the
+mathematical zero-slice condition. -/
+theorem physical_padding_native_iff {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (side : Side) (iv : ℕ × ℕ) (pub : Fin 3 → Word w) (source : (m (pub 1).val).val = iv.1)
+ (sites : iv.1+iv.2 ≤ 2^d) (inside : iv.1+iv.2 ≤ width (h+1) Δ (incidentCut side g).val)
+ (fits : iv.1+iv.2 ≤ 2^w) :
+ let P := ((template (checkPaddingCell (cutSlot side)) 7).instantiate w pub).program
+ (runSegment P 15 (some (pub 0)) m (List.replicate iv.2 [])).isSome = true ↔
+ Physical.ZeroSlice (cuts (incidentCut side g)) iv := by
+ have htest := padding_native_iff hw (cutSlot side) pub m iv.2 (by simpa [source] using fits)
+ dsimp only at htest ⊢
+ rw [source] at htest
+ exact htest.trans (headers.zeroSlice side iv sites inside)
+
+/-- A physical zero slice gives a complete native padding trace with
+unchanged memory and the prescribed probe bound. -/
+theorem physical_padding_native {hw : 4 ≤ w} {advice : Bits a} {cuts : AllCuts h Δ}
+ {g : Fin (2^(h+1))} {m : Memory w} (headers : SiteHeaders d hw advice cuts g m)
+ (side : Side) (iv : ℕ × ℕ) (pub : Fin 3 → Word w) (source : (m (pub 1).val).val = iv.1)
+ (sites : iv.1+iv.2 ≤ 2^d) (inside : iv.1+iv.2 ≤ width (h+1) Δ (incidentCut side g).val)
+ (fits : iv.1+iv.2 ≤ 2^w) (hz : Physical.ZeroSlice (cuts (incidentCut side g)) iv) :
+ let P := ((template (checkPaddingCell (cutSlot side)) 7).instantiate w pub).program
+ ∃ rs, runSegment P 15 (some (pub 0)) m (List.replicate iv.2 []) = some rs ∧
+ endState (some (pub 0)) rs = some (pub 0 + (iv.2 : Word w)) ∧ after m (eventLog rs) = m ∧
+ rs.length = iv.2 ∧ ∀ x ∈ rs, countProbes x.events ≤ 2 := by
+ apply padding_native hw (cutSlot side) pub m iv.2 (by simpa [source] using fits)
+ simpa [source] using (headers.zeroSlice side iv sites inside).mpr hz
+
+/-- A scan of a disjoint buffer preserves bits copied by an earlier scan. -/
+theorem CopiedSlice.congr {bits : Bits W} {iv : ℕ × ℕ} {dst : ℕ} {m m' : Memory w}
+ (copy : CopiedSlice bits iv dst m) (frame : ∀ j < iv.2, m' (dst+j) = m (dst+j)) :
+ CopiedSlice bits iv dst m' := by
+ intro j site hj hs
+ rw [frame j hj, copy j site hj hs]
+
+private theorem exponent_position (a : Fin t) (b : Fin Z) : a.val*Z+b.val < t*Z :=
+ (Nat.add_lt_add_left b.isLt _).trans_le ((Nat.succ_mul ..) ▸ Nat.mul_le_mul_right Z a.isLt)
+
+/-- The flat scratch buffer consumed by the exponent stage. -/
+def ExponentWords (x : Fin t → Word Z) (dst : ℕ) (m : Memory w) : Prop :=
+ ∀ a b, m (dst + (a.val*Z+b.val)) = PrimedInputRAM.encodeBit w (RAMSerialization.wordBits Z (x a) b)
+
+private theorem pair_span_fit {i : ℕ} (hi : 0 < i) (hle : i ≤ 2^h) (hfit : 1+t*Z ≤ Δ) (f : Field) :
+ let iv := span .pair (width (h+1) Δ i) Δ (t*Z) 0 f
+ iv.1 + iv.2 ≤ width (h+1) Δ i := by
+ have hw := width_double h Δ i hi hle
+ exact span_fit hfit (by omega) (fun _ => by omega) f
+
+/-- The exponent block has one scratch word per bit, in label-major order
+and little-endian order within each label. -/
+theorem CopiedSlice.pair_exponents {i dst : ℕ} (hi : 0 < i) (hle : i ≤ 2^h) (hfit : 1+t*Z ≤ Δ)
+ {bits : Bits (width (h+1) Δ i)} {m : Memory w}
+ (copy : CopiedSlice bits (span .pair (width (h+1) Δ i) Δ (t*Z) 0 .exponents) dst m) :
+ ExponentWords ((firstHalfLayout h Δ i t Z hi hle hfit bits).2.2.1) dst m := by
+ intro a b
+ let iv := span .pair (width (h+1) Δ i) Δ (t*Z) 0 .exponents
+ have hj : a.val*Z+b.val < iv.2 := exponent_position a b
+ have hinside : iv.1+iv.2 ≤ width (h+1) Δ i := pair_span_fit hi hle hfit _
+ let site : Fin (width (h+1) Δ i) := ⟨iv.1+(a.val*Z+b.val), by omega⟩
+ rw [copy _ site hj rfl, Physical.pair_exponent hi hle hfit bits a b site (Nat.add_assoc ..).symm]
+
+/-- Exterior bits in the auxiliary primed group header. -/
+theorem CopiedSlice.pair_exterior {i dst : ℕ} (hi : 0 < i) (hle : i ≤ 2^h) (hfit : 1+t*Z ≤ Δ)
+ {bits : Bits (width (h+1) Δ i)} {m : Memory w}
+ (copy : CopiedSlice bits (span .pair (width (h+1) Δ i) Δ (t*Z) 0 .exterior) dst m)
+ (j : Fin (width (h+1) Δ (2*i))) :
+ m (dst+j.val) = PrimedInputRAM.encodeBit w ((firstHalfLayout h Δ i t Z hi hle hfit bits).2.1 j) := by
+ let iv := span .pair (width (h+1) Δ i) Δ (t*Z) 0 .exterior
+ have hj : j.val < iv.2 := by
+ change j.val < exterior .pair _ Δ
+ rw [LiveHeaderDescriptors.pair_exterior h Δ i hi hle]
+ exact j.isLt
+ have hinside : iv.1+iv.2 ≤ width (h+1) Δ i := pair_span_fit hi hle hfit _
+ let site : Fin (width (h+1) Δ i) := ⟨iv.1+j.val, by omega⟩
+ rw [copy _ site hj rfl, Physical.pair_exterior hi hle hfit bits j site rfl]
+
+/-- The exact canonical serialized evaluator configuration at a tail cut. -/
+theorem CopiedSlice.tail_config {i dst : ℕ} (hhalf : 2^h ≤ i) (hend : i < 2^(h+1)) (hfit : 1+c ≤ Δ)
+ {bits : Bits (width (h+1) Δ i)} {m : Memory w}
+ (copy : CopiedSlice bits (span .tail (width (h+1) Δ i) Δ 0 c .config) dst m) (j : Fin c) :
+ m (dst+j.val) = PrimedInputRAM.encodeBit w ((tailLayout h Δ i c hhalf hend hfit bits).2.1 j) := by
+ let iv := span .tail (width (h+1) Δ i) Δ 0 c .config
+ have hj : j.val < iv.2 := j.isLt
+ have hw := width_tail h Δ i hhalf hend
+ have hinside : iv.1+iv.2 ≤ width (h+1) Δ i := span_fit (by omega) hfit (fun _ => hw.ge) .config
+ let site : Fin (width (h+1) Δ i) := ⟨iv.1+j.val, by omega⟩
+ rw [copy _ site hj rfl, Physical.tail_config hhalf hend hfit bits j site rfl]
+
+/-- No incoming exponent field exists in the first group. Its dedicated
+scratch starts with the little-endian representation of all-zero exponents. -/
+theorem first_incoming_exponents (hw : 4 ≤ w) (advice : Bits a) (cuts : AllCuts h Δ)
+ (g : Fin (2^(h+1))) (first : g.val = 0) (dst : ℕ) (scratch : 2^d ≤ dst) :
+ (span .missing (width (h+1) Δ (incidentCut .left g).val) Δ (t*Z) c .exponents).2 = 0 ∧
+ width (h+1) Δ (incidentCut .left g).val = 0 ∧
+ ExponentWords (t := t) (Z := Z) (fun _ => 0) dst (physicalMemory (d := d) hw advice cuts g) := by
+ refine ⟨rfl, ?_, ?_⟩
+ · change width (h+1) Δ g.val = 0
+ rw [first, width_zero]
+ · intro a b
+ simp [physicalMemory, RAMMemory.initialMemory, show ¬ dst + (a.val*Z+b.val) < 2^d by omega,
+ RAMSerialization.wordBits_zero, PrimedInputRAM.encodeBit]
+
+/-- Keep an already decoded exponent vector through a later phase that
+preserves its scratch interval. -/
+theorem ExponentWords.congr {x : Fin t → Word Z} {dst : ℕ} {m m' : Memory w}
+ (exps : ExponentWords x dst m) (frame : ∀ j < t*Z, m' (dst+j) = m (dst+j)) :
+ ExponentWords x dst m' := by
+ intro a b
+ rw [frame _ (exponent_position a b), exps a b]
+
+private theorem exponent_address (base : Word w) (a : Fin t) (b : Fin Z) (fits : base.val+t*Z ≤ 2^w) :
+ (base + LiveExponent.posWord a b).val = base.val+(a.val*Z+b.val) := by
+ have hj := exponent_position a b
+ have hv : (LiveExponent.posWord (w := w) a b).val = a.val*Z+b.val := Nat.mod_eq_of_lt (by omega)
+ rw [Fin.val_add, hv, Nat.mod_eq_of_lt (by omega)]
+
+private theorem bitValue (hw : 0 < w) (b : Bool) :
+ (PrimedInputRAM.encodeBit w b).val = b.toNat := by
+ cases b
+ · rfl
+ · exact Fin.val_cast_of_lt (Nat.one_lt_two_pow (by omega))
+
+/-- The input hypothesis of the native exponent checker follows from the
+two physically decoded exponent arrays, including the zero endpoint. -/
+theorem exponentBufferValues (hw : 0 < w) (pub : Fin 5 → Word w) {x y : Fin t → Word Z} {m : Memory w}
+ (incoming : ExponentWords x (pub 0).val m) (outgoing : ExponentWords y (pub 1).val m)
+ (leftFit : (pub 0).val+t*Z ≤ 2^w) (rightFit : (pub 1).val+t*Z ≤ 2^w) :
+ LiveExponent.BufferValues pub x y m := by
+ constructor <;> intro a b
+ · rw [LiveExponent.incomingAddress, exponent_address _ a b leftFit, incoming a b, bitValue hw]
+ · rw [LiveExponent.outgoingAddress, exponent_address _ a b rightFit, outgoing a b, bitValue hw]
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderDescriptors.lean b/lean/OAI/Computability/VPVNP/LiveHeaderDescriptors.lean
new file mode 100644
index 0000000000..9d42b20687
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderDescriptors.lean
@@ -0,0 +1,312 @@
+import OAI.Computability.VPVNP.LiveHeaderShapes
+
+/-!
+# Native descriptor writes for Section 14.1
+
+A fixed straight-line block takes an incident side and a field. It reads
+the width, tag, and two phase flags, then writes the field's source offset
+and length. The block handles clamped endpoints, the incoming midpoint
+of the first tail group, and all zero-length intervals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderDescriptors
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+/-- Public data are small sizes and scratch addresses. Exponent size is the
+total `t*Z`. Configuration size excludes the mode and zero padding. -/
+structure Parameters where
+ /-- Public operand index for the address holding the incident cut width. -/
+ widthAddress : Fin 16
+ /-- Public operand index for the address holding the selected live-mode tag. -/
+ tagAddress : Fin 16
+ /-- Public operand index for the address of the first-half flag. -/
+ firstHalfAddress : Fin 16
+ /-- Public operand index for the address marking the first evaluator group after the
+ midpoint. -/
+ firstTailAddress : Fin 16
+ /-- Public operand index supplying the cut's basic width parameter. -/
+ delta : Fin 16
+ /-- Public operand index supplying the allocated exponent field size. -/
+ exponentSize : Fin 16
+ /-- Public operand index supplying the allocated evaluator configuration size. -/
+ configSize : Fin 16
+ /-- Public operand index for the destination cell of the computed source offset. -/
+ offsetAddress : Fin 16
+ /-- Public operand index for the destination cell of the computed field length. -/
+ countAddress : Fin 16
+
+namespace Native
+
+private abbrev Pub := Fin 16
+private abbrev Reg := Fin 48
+private abbrev Code := Flow 48 16
+
+/-- Load the public sizes and descriptor destinations and read the live width, mode tag, and
+phase flags. -/
+def load (p : Parameters) : Code :=
+ straight (.constant 1 1) [
+ .publicWord 2 p.widthAddress, .publicWord 3 p.tagAddress, .publicWord 4 p.firstHalfAddress,
+ .publicWord 5 p.firstTailAddress, .publicWord 6 p.delta, .publicWord 7 p.exponentSize,
+ .publicWord 8 p.configSize, .publicWord 9 p.offsetAddress, .publicWord 10 p.countAddress,
+ .read 2 2, .read 3 3, .read 4 4, .read 5 5]
+
+/-- Registers 15 and 16 indicate respectively a pair-format and a tail-format
+payload. Register 11 is the length of the mode (zero or one). -/
+def masks (side : Side) : Code :=
+ straight (.binary .div 11 2 2) [.binary .div 12 3 3, .binary .mul 13 11 12,
+ (match side with | .left => .binary .bitOr 14 4 5 | .right => .copy 14 4),
+ .binary .mul 15 13 14, .binary .sub 16 1 14, .binary .mul 16 13 16]
+
+/-- Apply the phase and mode masks to obtain the exterior, exponent, and configuration field
+lengths. -/
+def lengths : Code := straight (.binary .sub 17 2 6) [
+ .binary .mul 17 17 15, .binary .mul 18 7 15, .binary .mul 19 8 16]
+
+/-- Compute successive field offsets and the residual padding length from the live width and
+the enabled field lengths. -/
+def starts : Code := straight (.binary .add 20 11 17) [
+ .binary .add 21 20 18, .binary .add 22 21 19, .binary .sub 23 2 22]
+
+/-- Select the register containing the computed source offset for the requested field. -/
+def startReg : Field → Reg
+ | .exterior => 11 | .exponents => 20 | .config => 21 | .padding => 22
+
+/-- Select the register containing the computed length for the requested field. -/
+def countReg : Field → Reg
+ | .exterior => 17 | .exponents => 18 | .config => 19 | .padding => 23
+
+/-- Write the field length and its offset, setting the offset to zero when the interval is
+empty. -/
+def emit (f : Field) : Code := straight (.binary .div 24 (countReg f) (countReg f)) [
+ .binary .mul 25 (startReg f) 24, .write 9 25, .write 10 (countReg f)]
+
+/-- The descriptor worker that reads metadata, selects the masks for the incident side,
+computes its field intervals, and publishes one interval. -/
+def block (p : Parameters) (side : Side) (f : Field) : Code :=
+ .seq (load p) (.seq (masks side) (.seq lengths (.seq starts (emit f))))
+
+variable {w : ℕ}
+
+private def putAll (rs : Regs w 48) (vs : List (Reg × Word w)) :=
+ vs.foldl (fun a j => Function.update a j.1 j.2) rs
+
+private def loadRegs (pub : Pub → Word w) (p : Parameters) (m : Memory w) (rs : Regs w 48) : Regs w 48 :=
+ putAll rs [(1,1),(2,pub p.widthAddress),(3,pub p.tagAddress),(4,pub p.firstHalfAddress),
+ (5,pub p.firstTailAddress),(6,pub p.delta),(7,pub p.exponentSize),(8,pub p.configSize),
+ (9,pub p.offsetAddress),(10,pub p.countAddress),(2,m (pub p.widthAddress).val),
+ (3,m (pub p.tagAddress).val),(4,m (pub p.firstHalfAddress).val),(5,m (pub p.firstTailAddress).val)]
+
+private def loadEvents (pub : Pub → Word w) (p : Parameters) (m : Memory w) : List (Event w) :=
+ List.replicate 10 .tick ++ [.read (pub p.widthAddress) (m (pub p.widthAddress).val),
+ .read (pub p.tagAddress) (m (pub p.tagAddress).val),
+ .read (pub p.firstHalfAddress) (m (pub p.firstHalfAddress).val),
+ .read (pub p.firstTailAddress) (m (pub p.firstTailAddress).val)]
+
+private def nz (x : Word w) := BinaryOp.div.eval x x
+private def sideWord (side : Side) (rs : Regs w 48) : Word w :=
+ match side with | .left => BinaryOp.bitOr.eval (rs 4) (rs 5) | .right => rs 4
+
+private def maskRegs (side : Side) (rs : Regs w 48) : Regs w 48 :=
+ let active := nz (rs 2) * nz (rs 3)
+ let group := sideWord side rs
+ putAll rs [(11,nz (rs 2)),(12,nz (rs 3)),(13,active),(14,group),(15,active*group),
+ (16,rs 1 - group),(16,active*(rs 1-group))]
+
+private def lengthRegs (rs : Regs w 48) : Regs w 48 :=
+ putAll rs [(17,rs 2 - rs 6),(17,(rs 2-rs 6)*rs 15),(18,rs 7*rs 15),(19,rs 8*rs 16)]
+
+private def startRegs (rs : Regs w 48) : Regs w 48 :=
+ let x := rs 11 + rs 17
+ let y := x + rs 18
+ let z := y + rs 19
+ putAll rs [(20,x),(21,y),(22,z),(23,rs 2-z)]
+
+/-- Zero-length fields receive offset zero. -/
+private def offWord (rs : Regs w 48) (f : Field) := rs (startReg f) * nz (rs (countReg f))
+
+private theorem raw_exec (pub : Pub → Word w) (p : Parameters) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) (side : Side) (f : Field) :
+ let a := startRegs (lengthRegs (maskRegs side (loadRegs pub p m rs)))
+ let v := offWord a f
+ let l := a (countReg f)
+ ∃ out, Flow.Exec pub state (block p side f) rs m
+ (loadEvents pub p m ++ (List.replicate 7 .tick ++ (List.replicate 4 .tick ++
+ (List.replicate 4 .tick ++ [.tick,.tick,.write (a 9) v,.write (a 10) l])))) out
+ (writeMemory (writeMemory m (a 9) v) (a 10) l) := by
+ let a := loadRegs pub p m rs
+ let b := maskRegs side a
+ let d := lengthRegs b
+ let g := startRegs d
+ have ha : Flow.Exec pub state (load p) rs m (loadEvents pub p m) a m :=
+ (Flow.once_sound pub state false _ rs m rfl).1
+ have hb : Flow.Exec pub state (masks side) a m (List.replicate 7 .tick) b m := by
+ apply (Flow.once_sound pub state false _ a m ?_).1
+ cases side <;> rfl
+ have hd : Flow.Exec pub state lengths b m (List.replicate 4 .tick) d m :=
+ (Flow.once_sound pub state false _ b m rfl).1
+ have hg : Flow.Exec pub state starts d m (List.replicate 4 .tick) g m :=
+ (Flow.once_sound pub state false _ d m rfl).1
+ let v := offWord g f
+ let l := g (countReg f)
+ let out := putAll g [(24,nz l),(25,v)]
+ have hw : Flow.Exec pub state (emit f) g m [.tick,.tick,.write (g 9) v,.write (g 10) l] out
+ (writeMemory (writeMemory m (g 9) v) (g 10) l) := by
+ apply (Flow.once_sound pub state false _ g m ?_).1
+ cases f <;> rfl
+ exact ⟨out,ha.seq (hb.seq (hd.seq (hg.seq hw)))⟩
+
+private theorem nz_eq (x : Word w) : nz x = (if x.val = 0 then 0 else 1) := by
+ apply Fin.ext
+ change (x.val / x.val) % 2^w = _
+ by_cases hz : x.val = 0
+ · simp [hz]
+ · rw [Nat.div_self (Nat.pos_of_ne_zero hz), ite_eq_right hz]; rfl
+
+private theorem nz_val (x : Word w) (hw : 0 < w) : (nz x).val = mode x.val := by
+ rw [nz_eq, mode]
+ split_ifs with hz
+ · rfl
+ · exact Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')
+
+private theorem or_bits (hw : 0 < w) (x y : Bool) :
+ BinaryOp.bitOr.eval (encodeBit w x) (encodeBit w y) = encodeBit w (x || y) := by
+ have ho := Nat.one_lt_two_pow hw.ne'
+ cases x <;> cases y <;> apply Fin.ext <;>
+ simp [BinaryOp.eval, encodeBit, Nat.mod_eq_of_lt ho]
+
+private theorem shapeMasks (hw : 0 < w) (side : Side) (a : Regs w 48) (W tag : ℕ)
+ (half firstTail : Bool) (h1 : a 1 = 1) (hW : (a 2).val = W) (htag : (a 3).val = tag)
+ (hhalf : a 4 = encodeBit w half) (htail : a 5 = encodeBit w firstTail) :
+ let b := maskRegs side a
+ let form := shape side W tag half firstTail
+ b 15 = (if form = .pair then 1 else 0) ∧ b 16 = (if form = .tail then 1 else 0) := by
+ let g := half || (decide (side = .left) && firstTail)
+ have hgroup : sideWord side a = encodeBit w g := by
+ cases side
+ · simpa [sideWord, g, hhalf, htail] using or_bits (w := w) hw half firstTail
+ · simpa [sideWord, g] using hhalf
+ let active := nz (a 2) * nz (a 3)
+ change active*sideWord side a = _ ∧ active*(a 1-sideWord side a) = _
+ rw [hgroup,h1]
+ dsimp only [active]
+ rw [nz_eq, nz_eq, hW, htag]
+ change _ = (if (if W = 0 then Shape.missing else if tag = 0 then .unit else if g then .pair else .tail)
+ = .pair then _ else _) ∧ _ = (if (if W = 0 then Shape.missing else if tag = 0 then .unit else
+ if g then .pair else .tail) = .tail then _ else _)
+ by_cases hz : W = 0 <;> by_cases hu : tag = 0 <;> cases g <;> simp [hz, hu, encodeBit]
+
+private theorem geometry {side : Side} (a : Regs w 48) (W tag Δ e c : ℕ) (half firstTail : Bool)
+ (hW : (a 2).val = W) (hΔ : (a 6).val = Δ) (he : (a 7).val = e) (hc : (a 8).val = c)
+ (hmode : (a 11).val = mode W)
+ (hpair : a 15 = if shape side W tag half firstTail = .pair then 1 else 0)
+ (htail : a 16 = if shape side W tag half firstTail = .tail then 1 else 0)
+ (hefit : 1+e ≤ Δ) (hcfit : 1+c ≤ Δ) (hblock : W = 0 ∨ Δ ≤ W) (f : Field) :
+ let g := startRegs (lengthRegs a)
+ let form := shape side W tag half firstTail
+ (g (startReg f)).val = start form W Δ e c f ∧ (g (countReg f)).val = count form W Δ e c f := by
+ let d := lengthRegs a
+ let g := startRegs d
+ let form := shape side W tag half firstTail
+ have hδ := shape_fit (side := side) (tag := tag) (half := half) (firstTail := firstTail) hblock
+ have hbound := payload_le hefit hcfit hδ
+ change mode W + exterior form W Δ + exponents form e + config form c ≤ W at hbound
+ have hf := (a 2).isLt
+ rw [hW] at hf
+ have h17 : (d 17).val = exterior form W Δ := by
+ change ((a 2-a 6)*a 15).val = _
+ change a 15 = (if form = .pair then 1 else 0) at hpair
+ rw [hpair,exterior]
+ split_ifs with hp
+ · rw [mul_one, Fin.sub_val_of_le (by change (a 6).val ≤ _; rw [hΔ,hW]; exact hδ (Or.inl hp)),hW,hΔ]
+ · rw [mul_zero]; rfl
+ have h18 : (d 18).val = exponents form e := by
+ change (a 7*a 15).val = _
+ change a 15 = (if form = .pair then 1 else 0) at hpair
+ rw [hpair,exponents]; split_ifs <;> simp [he]
+ have h19 : (d 19).val = config form c := by
+ change (a 8*a 16).val = _
+ change a 16 = (if form = .tail then 1 else 0) at htail
+ rw [htail,config]; split_ifs <;> simp [hc]
+ have h11 : (d 11).val = mode W := hmode
+ have h20 : (g 20).val = start form W Δ e c .exponents := by
+ change (d 11+d 17).val = _
+ rw [Fin.val_add_eq_of_add_lt (by omega),h11,h17]; rfl
+ have h21 : (g 21).val = start form W Δ e c .config := by
+ change (g 20+d 18).val = _
+ simp only [start] at h20 ⊢
+ rw [Fin.val_add_eq_of_add_lt (by omega),h20,h18]
+ have h22 : (g 22).val = start form W Δ e c .padding := by
+ change (g 21+d 19).val = _
+ simp only [start] at h21 ⊢
+ rw [Fin.val_add_eq_of_add_lt (by omega),h21,h19]
+ have h23 : (g 23).val = count form W Δ e c .padding := by
+ change (a 2 - g 22).val = _
+ rw [Fin.sub_val_of_le (by change (g 22).val ≤ _; rw [h22,hW]; exact hbound),hW,h22]; rfl
+ cases f with
+ | exterior => exact ⟨h11,h17⟩
+ | exponents => exact ⟨h20,h18⟩
+ | config => exact ⟨h21,h19⟩
+ | padding => exact ⟨h22,h23⟩
+
+/-- Four scratch reads and two writes. The other twenty-seven operations
+are register arithmetic and public parameter loads. -/
+def events (pub : Pub → Word w) (p : Parameters) (m : Memory w) (o l : Word w) : List (Event w) :=
+ loadEvents pub p m ++ (List.replicate 7 .tick ++ (List.replicate 4 .tick ++
+ (List.replicate 4 .tick ++ [.tick,.tick,.write (pub p.offsetAddress) o,.write (pub p.countAddress) l])))
+
+theorem event_cost (pub : Pub → Word w) (p : Parameters) (m : Memory w) (o l : Word w) :
+ countProbes (events pub p m o l) = 6 ∧ choiceBits (events pub p m o l) = [] ∧
+ (events pub p m o l).length = 33 := ⟨rfl,rfl,rfl⟩
+
+/-- The block materializes both descriptor words at designated addresses.
+Their exact natural values fit because the whole source interval fits in
+the incident width. All parameter cells are read before either write. -/
+theorem block_exec (hw : 0 < w) (pub : Pub → Word w) (p : Parameters) (state : Word w)
+ (m : Memory w) (rs : Regs w 48) (side : Side) (f : Field) (W tag Δ e c : ℕ) (half firstTail : Bool)
+ (hW : (m (pub p.widthAddress).val).val = W) (ht : (m (pub p.tagAddress).val).val = tag)
+ (hh : m (pub p.firstHalfAddress).val = encodeBit w half)
+ (hft : m (pub p.firstTailAddress).val = encodeBit w firstTail)
+ (hΔ : (pub p.delta).val = Δ) (he : (pub p.exponentSize).val = e) (hc : (pub p.configSize).val = c)
+ (hefit : 1+e ≤ Δ) (hcfit : 1+c ≤ Δ) (hblock : W = 0 ∨ Δ ≤ W) :
+ let form := shape side W tag half firstTail
+ let iv := span form W Δ e c f
+ ∃ out o l, Flow.Exec pub state (block p side f) rs m (events pub p m o l) out
+ (writeMemory (writeMemory m (pub p.offsetAddress) o) (pub p.countAddress) l) ∧
+ o.val = iv.1 ∧ l.val = iv.2 := by
+ let a := loadRegs pub p m rs
+ let b := maskRegs side a
+ let g := startRegs (lengthRegs b)
+ let form := shape side W tag half firstTail
+ obtain ⟨out,hr⟩ := raw_exec pub p state m rs side f
+ obtain ⟨hp,hq⟩ := shapeMasks hw side a W tag half firstTail rfl hW ht hh hft
+ have hm : (b 11).val = mode W := (nz_val (a 2) hw).trans (congrArg mode hW)
+ obtain ⟨hs,hl⟩ := geometry (side := side) b W tag Δ e c half firstTail hW hΔ he hc hm hp hq hefit hcfit hblock f
+ have ho : (offWord g f).val = (span form W Δ e c f).1 := by
+ change (g (startReg f) * nz (g (countReg f))).val =
+ (if count form W Δ e c f = 0 then 0 else start form W Δ e c f)
+ change (g (countReg f)).val = count form W Δ e c f at hl
+ change (g (startReg f)).val = start form W Δ e c f at hs
+ rw [nz_eq,hl]
+ split_ifs <;> simp [hs]
+ exact ⟨out,offWord g f,g (countReg f),hr,ho,hl⟩
+
+/-- When the chosen output cells are distinct, the field runner reads back
+the offset and count deposited by the descriptor block. -/
+theorem output_words (m : Memory w) (dstOff dstCount o l : Word w) (h : dstOff ≠ dstCount) :
+ let after := writeMemory (writeMemory m dstOff o) dstCount l
+ after dstOff.val = o ∧ after dstCount.val = l := by
+ have hn : dstOff.val ≠ dstCount.val := fun e => h (Fin.ext e)
+ simp [writeMemory, hn]
+
+end Native
+end LiveHeaderDescriptors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderExpressions.lean b/lean/OAI/Computability/VPVNP/LiveHeaderExpressions.lean
new file mode 100644
index 0000000000..2d93d5f6ea
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderExpressions.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.LivePublicExpr
+import OAI.Computability.VPVNP.LiveHeaderProgram
+
+/-!
+# Arithmetic expressions for the complete live header operand bank
+
+Only the four inputs of the physical site reader and fixed constants appear
+in these expressions. Their values include the nested stage tag address,
+all source and destination buffer addresses, and the public scan limits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+open LiveHeaderSchedule LiveHeaderWidths LiveHeaderDescriptors
+
+instance : Add PublicExpr := ⟨PublicExpr.add⟩
+instance : Mul PublicExpr := ⟨PublicExpr.mul⟩
+instance (n : ℕ) : OfNat PublicExpr n := ⟨PublicExpr.lit n⟩
+
+@[simp] theorem eval_add (g : Geometry) (a b : PublicExpr) : (a+b).eval g = a.eval g + b.eval g := rfl
+@[simp] theorem eval_mul (g : Geometry) (a b : PublicExpr) : (a*b).eval g = a.eval g * b.eval g := rfl
+@[simp] theorem eval_numeral (g : Geometry) (n : ℕ) : (OfNat.ofNat n : PublicExpr).eval g = n := rfl
+
+/-- The five public size expressions used to allocate and parameterize live-header storage for
+any processor geometry. -/
+structure Lengths where
+ /-- The public expression for the chain-height parameter used in group and cut numbering. -/
+ h : PublicExpr
+ /-- The public expression for the basic cut width used in the exterior and padding
+ capacities. -/
+ delta : PublicExpr
+ /-- The public expression for the number of distributed advice bits. -/
+ advice : PublicExpr
+ /-- The public expression for the serialized exponent field length. -/
+ e : PublicExpr
+ /-- The public expression for the serialized evaluator configuration length. -/
+ config : PublicExpr
+
+/-- Evaluate the five public header dimensions at the supplied geometry. -/
+def Lengths.eval (s : Lengths) (g : Geometry) : Sizes :=
+ ⟨s.h.eval g, s.delta.eval g, s.advice.eval g, s.e.eval g, s.config.eval g⟩
+
+namespace HeaderLayout
+
+/-- The maximum scan length allocated to the requested incident field. -/
+def capacity (s : Lengths) : Field → PublicExpr
+ | .exterior | .padding => (s.h+1)*s.delta
+ | .exponents => s.e
+ | .config => s.config
+
+/-- The workspace address holding the computed cut width for one of the five live or primed
+slots. -/
+def width (b : PublicExpr) : Slot → PublicExpr
+ | .liveLeft => b+1 | .liveRight => b+2 | .primedLeft => b+3 | .primedMiddle => b+4 | .primedRight => b+5
+
+/-- The workspace address holding the selected group-phase flag. -/
+def flag (b : PublicExpr) : Flag → PublicExpr
+ | .first => b+6 | .middle => b+7 | .firstHalf => b+8 | .last => b+9
+
+/-- The workspace cell marking the first evaluator group. -/
+def firstTail (b : PublicExpr) := b+10
+/-- The workspace cell holding the selected unit, pair, or tail mode. -/
+def mode (b : PublicExpr) := b+11
+/-- The shared descriptor cell holding the next incident field's source offset. -/
+def offset (b : PublicExpr) := b+12
+/-- The shared descriptor cell holding the next incident field's live length. -/
+def count (b : PublicExpr) := b+13
+/-- The workspace cell carrying the borrow while constructing primed group indices. -/
+def borrow (b : PublicExpr) := b+14
+/-- The base address of the unpacked one-based group index. -/
+def index (b : PublicExpr) := b+15
+/-- The cell after the group-index array storing the position of its highest set bit. -/
+def high (s : Lengths) (b : PublicExpr) := index b+(s.h+2)
+/-- The cell storing the number of set bits in the group index. -/
+def population (s : Lengths) (b : PublicExpr) := high s b+1
+/-- The base of the unpacked left primed group index. -/
+def leftIndex (s : Lengths) (b : PublicExpr) := population s b+1
+/-- The base of the unpacked right primed group index, following the left index array. -/
+def rightIndex (s : Lengths) (b : PublicExpr) := leftIndex s b+(s.h+2)
+/-- The distributed advice array's base following both primed index arrays. -/
+def advice (s : Lengths) (b : PublicExpr) := rightIndex s b+(s.h+2)
+
+/-- The base of the selected side's exterior payload, with a full reserved interval per side. -/
+def exterior (s : Lengths) (b : PublicExpr) : Side → PublicExpr
+ | .left => advice s b+s.advice
+ | .right => advice s b+s.advice+capacity s .exterior
+
+/-- The base of the selected side's exponent buffer following both exterior reservations. -/
+def exponent (s : Lengths) (b : PublicExpr) : Side → PublicExpr
+ | .left => exterior s b .right+capacity s .exterior
+ | .right => exterior s b .right+capacity s .exterior+s.e
+
+/-- The base of the selected side's evaluator configuration buffer following the exponent
+buffers. -/
+def config (s : Lengths) (b : PublicExpr) : Side → PublicExpr
+ | .left => exponent s b .right+s.e
+ | .right => exponent s b .right+s.e+s.config
+
+/-- The exclusive end of the live-header workspace, immediately after the right configuration
+buffer. -/
+def limit (s : Lengths) (b : PublicExpr) := config s b .right + s.config
+
+/-- The destination base for a side's payload field, using zero as the unused operand of a
+padding check. -/
+def dest (s : Lengths) (b : PublicExpr) (side : Side) : Field → PublicExpr
+ | .exterior => exterior s b side
+ | .exponents => exponent s b side
+ | .config => config s b side
+ | .padding => 0
+
+/-- Assemble the selected header stage's public operand expressions from the size parameters
+and workspace layout. -/
+def row (s : Lengths) (b : PublicExpr) (st : LiveHeaderSchedule.Stage) : List PublicExpr :=
+ let widthInputs (out : PublicExpr) := [s.h+1,s.delta,high s b,population s b,out,index b]
+ let groupInputs := [index b,leftIndex s b,rightIndex s b,borrow b]
+ match st with
+ | .index => [index b,high s b,population s b,s.h+2]
+ | .advice => [0,advice s b,s.advice]
+ | .width slot => widthInputs (width b slot)
+ | .flag f => widthInputs (flag b f)
+ | .firstTail => widthInputs (firstTail b)
+ | .mode => [width b .liveLeft,width b .liveRight,flag b .firstHalf,mode b]
+ | .primedInit => groupInputs
+ | .primedDigits => groupInputs ++ [s.h+1]
+ | .descriptor side _ => [width b (if side = .left then .liveLeft else .liveRight),mode b,flag b .firstHalf,
+ firstTail b,s.delta,s.e,s.config,offset b,count b]
+ | .scan side f => [0,offset b,dest s b side f,count b] ++ List.replicate 12 0 ++ [capacity s f]
+
+private theorem row_value (s : Lengths) (b : PublicExpr) (g : Geometry) (st : LiveHeaderSchedule.Stage)
+ (j : Fin 17) : (((row s b st)[j.val]?).getD 0).eval g =
+ LiveHeaderProgram.publicRow (s.eval g) (b.eval g) st j := by
+ have lookup (l : List PublicExpr) (i : ℕ) : ((l[i]?).getD 0).eval g =
+ ((l.map (PublicExpr.eval g))[i]?).getD 0 := by
+ rw [List.getElem?_map]; cases l[i]? <;> rfl
+ rw [lookup]
+ cases st <;> first | (rename_i a; cases a <;> rfl) | (rename_i a f; cases a <;> cases f <;> rfl) | rfl
+
+/-- Flatten the fixed 31 rows, appending the address of the header-stage tag. -/
+def operands (s : Lengths) (b : PublicExpr) : Fin (LiveHeaderSchedule.stages.length*17+1) → PublicExpr :=
+ Fin.snoc (fun j : LiveHeaderProgram.PublicIndex =>
+ let p := finProdFinEquiv.symm j
+ ((row s b (LiveHeaderProgram.stage p.1))[p.2.val]?).getD 0) b
+
+/-- The expression bank instantiates precisely the native header's ABI. -/
+theorem operands_eq (g : Geometry) (s : Lengths) (b : PublicExpr) (i : Fin (LiveHeaderSchedule.stages.length*17+1)) :
+ Fin.ofNat (2^g.w) ((operands s b i).eval g) = LiveHeaderProgram.publicData g.w (s.eval g) (b.eval g) i := by
+ refine Fin.lastCases ?_ (fun j => ?_) i
+ · simp [operands,LiveHeaderProgram.publicData,LiveStageLink.publicData]
+ · simp only [operands,LiveHeaderProgram.publicData,LiveStageLink.publicData,Fin.snoc_castSucc,row_value]
+
+end HeaderLayout
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderFieldFormats.lean b/lean/OAI/Computability/VPVNP/LiveHeaderFieldFormats.lean
new file mode 100644
index 0000000000..cf75fc30b9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderFieldFormats.lean
@@ -0,0 +1,195 @@
+import OAI.Computability.VPVNP.LiveHeaderFieldUnitPadding
+
+/-!
+# Decoding both incident fields from a completed live header
+
+The incident cut index determines the evaluated layout, including the pair
+layout at the midpoint on the input side of the first tail group. Each
+interior padding condition refers to the same bits as the typed layout.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.Fields
+
+open BurstRAM CutSchedule ChainAssignments LiveHeaderSchedule LiveHeaderDescriptors LiveHeader
+open scoped Fin.CommRing
+
+variable {w t Z : ℕ} {s : Sizes} {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))} {tag : Mode.Tag}
+
+private theorem interval_at_index (s : Sizes) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (side : Side) (f : Field) :
+ let i := (incidentCut side g).val
+ let W := width (s.h+1) s.delta i
+ interval s g tag side f = span (if W = 0 then .missing else if tag = .unit then .unit else
+ if i ≤ 2^s.h then .pair else .tail) W s.delta s.e s.config f := by
+ dsimp only
+ dsimp only [interval, firstHalfFlag]
+ rw [shape_at_group s.h (g.val+1) tag.code.val side (incidentWidth (Δ := s.delta) side g)]
+ have hi : cutIndex side (g.val+1) = (incidentCut side g).val := by cases side <;> simp [incidentCut,cutIndex]
+ rw [hi]
+ cases tag <;> rfl
+
+/-- A missing endpoint has no field on either side, in every mode. -/
+theorem interval_endpoint (s : Sizes) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (side : Side) (f : Field)
+ (endpt : (incidentCut side g).val = 0 ∨ (incidentCut side g).val = 2^(s.h+1)) :
+ interval s g tag side f = (0,0) := by
+ have hw : incidentWidth (Δ := s.delta) side g = 0 := by
+ rcases endpt with h | h <;> simp [incidentWidth,h]
+ rw [interval_at_index]
+ change width (s.h+1) s.delta (incidentCut side g).val = 0 at hw
+ rw [hw, ite_eq_left rfl]
+ cases f <;> rfl
+
+/-- The payload at a first-half cut uses the pair layout up to and including the midpoint. -/
+theorem interval_pair (s : Sizes) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (ev : tag ≠ .unit)
+ (side : Side) (f : Field) (hΔ : 0 < s.delta) (hi : 0 < (incidentCut side g).val)
+ (half : (incidentCut side g).val ≤ 2^s.h) :
+ interval s g tag side f = span .pair (incidentWidth (Δ := s.delta) side g) s.delta s.e 0 f := by
+ rw [interval_at_index]
+ have hw : width (s.h+1) s.delta (incidentCut side g).val ≠ 0 := by
+ rw [width_double s.h s.delta _ hi half]; omega
+ rw [ite_eq_right hw, ite_eq_right ev, ite_eq_left half]
+ cases f <;> rfl
+
+/-- Every interior cut strictly after the midpoint uses the serialized configuration layout. -/
+theorem interval_tail (s : Sizes) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (ev : tag ≠ .unit)
+ (side : Side) (f : Field) (hΔ : 0 < s.delta) (half : 2^s.h < (incidentCut side g).val)
+ (hend : (incidentCut side g).val < 2^(s.h+1)) :
+ interval s g tag side f = span .tail (incidentWidth (Δ := s.delta) side g) s.delta 0 s.config f := by
+ rw [interval_at_index]
+ have hw : width (s.h+1) s.delta (incidentCut side g).val ≠ 0 := by
+ rw [width_tail s.h s.delta _ half.le hend]
+ exact hΔ.ne'
+ rw [ite_eq_right hw, ite_eq_right ev, ite_eq_right half.not_ge]
+ cases f <;> rfl
+
+/-- At each missing endpoint the padding guard is vacuous. -/
+theorem validPadding_endpoint (side : Side)
+ (endpt : (incidentCut side g).val = 0 ∨ (incidentCut side g).val = 2^(s.h+1)) :
+ ValidPadding s cuts g tag side := by
+ unfold ValidPadding
+ rw [interval_endpoint s g tag side .padding endpt]
+ exact fun _ _ hj _ => False.elim (Nat.not_lt_zero _ hj)
+
+theorem validPadding_pair_iff (ev : tag ≠ .unit) (side : Side) (he : s.e = t*Z)
+ (fit : 1+t*Z ≤ s.delta) (hi : 0 < (incidentCut side g).val) (half : (incidentCut side g).val ≤ 2^s.h) :
+ ValidPadding s cuts g tag side ↔
+ (firstHalfLayout s.h s.delta (incidentCut side g).val t Z hi half fit (cuts (incidentCut side g))).2.2.2 =
+ fun _ => false := by
+ unfold ValidPadding
+ rw [interval_pair s g tag ev side .padding (by omega) hi half, he]
+ exact Physical.pair_padding_zero hi half fit _
+
+theorem validPadding_tail_iff (ev : tag ≠ .unit) (side : Side) (fit : 1+s.config ≤ s.delta)
+ (half : 2^s.h < (incidentCut side g).val) (hend : (incidentCut side g).val < 2^(s.h+1)) :
+ ValidPadding s cuts g tag side ↔
+ (tailLayout s.h s.delta (incidentCut side g).val s.config half.le hend fit (cuts (incidentCut side g))).2.2 =
+ fun _ => false := by
+ unfold ValidPadding
+ rw [interval_tail s g tag ev side .padding (by omega) half hend]
+ exact Physical.tail_padding_zero half.le hend fit _
+
+/-- Canonical trailing bits in the layout of one cut. Endpoint strings have no entries. -/
+def decodedPadding (s : Sizes) (cuts : AllCuts s.h s.delta) (t Z : ℕ)
+ (he : 1+t*Z ≤ s.delta) (hc : 1+s.config ≤ s.delta) (i : Fin (2^(s.h+1)+1)) : Prop :=
+ if interior : 0 < i.val ∧ i.val < 2^(s.h+1) then
+ if half : i.val ≤ 2^s.h then
+ (firstHalfLayout s.h s.delta i.val t Z interior.1 half he (cuts i)).2.2.2 = fun _ => false
+ else (tailLayout s.h s.delta i.val s.config (by omega) interior.2 hc (cuts i)).2.2 = fun _ => false
+ else True
+
+/-- The two evaluated padding guards are exactly the typed trailing-bit tests
+on the incoming and outgoing cut, including endpoint and midpoint cases. -/
+theorem validPadding_evaluated_iff (ev : tag ≠ .unit) (he : s.e = t*Z) (hpair : 1+t*Z ≤ s.delta)
+ (htail : 1+s.config ≤ s.delta) :
+ (∀ side, ValidPadding s cuts g tag side) ↔
+ ∀ side, decodedPadding s cuts t Z hpair htail (incidentCut side g) := by
+ apply forall_congr'
+ intro side
+ let i := incidentCut side g
+ unfold decodedPadding
+ split_ifs with interior half
+ · exact validPadding_pair_iff ev side he hpair interior.1 half
+ · exact validPadding_tail_iff ev side htail (Nat.lt_of_not_ge half) interior.2
+ · exact iff_true_intro (validPadding_endpoint side (by have := i.isLt; dsimp [i] at *; omega))
+
+variable {base : ℕ} {before m : Memory w}
+
+/-- A complete image contains the occupied part of each of the six payload buffers. -/
+theorem Image.copiedField (img : Image s base cuts g tag 8 before m) (side : Side) (f : Field)
+ (hf : f ≠ .padding) :
+ CopiedSlice (cuts (incidentCut side g)) (interval s g tag side f) (dest s base side f) m := by
+ obtain ⟨k, hk⟩ := key_surj (side,f)
+ let copied (p : Side × Field) := CopiedSlice (cuts (incidentCut p.1 g))
+ (interval s g tag p.1 p.2) (dest s base p.1 p.2) m
+ exact (congrArg copied hk).mp (img.copies k k.isLt (by simpa only [hk] using hf))
+
+/-- An unoccupied word of a payload buffer retains its value at entry to the field suffix. -/
+theorem Image.unoccupied {n : ℕ} (img : Image s base cuts g tag n before m) (side : Side) (f : Field)
+ (hf : f ≠ .padding) (j : ℕ) (low : (interval s g tag side f).2 ≤ j) (high : j < s.capacity f) :
+ m (dest s base side f+j) = before (dest s base side f+j) := by
+ apply img.frame
+ have pre := before_destination s base side f hf
+ refine ⟨by omega, by unfold offsetAddr; omega, by unfold countAddr; omega, ?_⟩
+ intro side' f' hf'
+ by_cases same : (side,f) = (side',f')
+ · rcases Prod.mk.inj same with ⟨rfl,rfl⟩
+ exact Or.inr (Nat.add_le_add_left low _)
+ · have cap := interval_capacity s g tag side' f'
+ rcases dest_disjoint s base hf hf' same with left | right
+ · exact Or.inl ((Nat.add_lt_add_left high _).trans_le left)
+ · exact Or.inr (by omega)
+
+/-- The actual buffer at either pair-format cut represents its decoded exponent vector. -/
+theorem Image.pair_exponents (img : Image s base cuts g tag 8 before m) (ev : tag ≠ .unit)
+ (side : Side) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta)
+ (hi : 0 < (incidentCut side g).val) (half : (incidentCut side g).val ≤ 2^s.h) :
+ ExponentWords
+ ((firstHalfLayout s.h s.delta (incidentCut side g).val t Z hi half fit (cuts (incidentCut side g))).2.2.1)
+ (exponentBase s base side) m := by
+ have copy := img.copiedField side .exponents (by decide)
+ rw [interval_pair s g tag ev side .exponents (by omega) hi half, he] at copy
+ exact copy.pair_exponents hi half fit
+
+/-- The exterior scratch words contain the exact bits of the doubled primed cut. -/
+theorem Image.pair_exterior (img : Image s base cuts g tag 8 before m) (ev : tag ≠ .unit)
+ (side : Side) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta)
+ (hi : 0 < (incidentCut side g).val) (half : (incidentCut side g).val ≤ 2^s.h)
+ (j : Fin (width (s.h+1) s.delta (2*(incidentCut side g).val))) :
+ m (exteriorBase s base side+j.val) = PrimedInputRAM.encodeBit w
+ ((firstHalfLayout s.h s.delta (incidentCut side g).val t Z hi half fit (cuts (incidentCut side g))).2.1 j) := by
+ have copy := img.copiedField side .exterior (by decide)
+ rw [interval_pair s g tag ev side .exterior (by omega) hi half, he] at copy
+ exact copy.pair_exterior hi half fit j
+
+/-- Each tail configuration word is the corresponding decoded configuration bit. -/
+theorem Image.tail_config (img : Image s base cuts g tag 8 before m) (ev : tag ≠ .unit)
+ (side : Side) (fit : 1+s.config ≤ s.delta)
+ (half : 2^s.h < (incidentCut side g).val) (hend : (incidentCut side g).val < 2^(s.h+1))
+ (j : Fin s.config) :
+ m (configBase s base side+j.val) = PrimedInputRAM.encodeBit w
+ ((tailLayout s.h s.delta (incidentCut side g).val s.config half.le hend fit (cuts (incidentCut side g))).2.1 j) := by
+ have copy := img.copiedField side .config (by decide)
+ rw [interval_tail s g tag ev side .config (by omega) half hend] at copy
+ exact copy.tail_config half.le hend fit j
+
+/-- The missing incoming cut at the first group preserves the zero exponent vector
+installed before the suffix. This also applies at any intermediate suffix cursor. -/
+theorem Image.first_exponents {n : ℕ} (img : Image s base cuts g tag n before m)
+ (first : g.val = 0) (he : s.e = t*Z)
+ (initial : ExponentWords (t := t) (Z := Z) (fun _ => 0) (exponentBase s base .left) before) :
+ ExponentWords (t := t) (Z := Z) (fun _ => 0) (exponentBase s base .left) m := by
+ apply initial.congr
+ intro j hj
+ apply img.unoccupied .left .exponents (by decide) j
+ · rw [interval_endpoint s g tag .left .exponents (Or.inl first)]
+ exact Nat.zero_le _
+ · simpa only [Sizes.capacity, he] using hj
+
+end LiveHeaderProgram.Fields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderFieldRuns.lean b/lean/OAI/Computability/VPVNP/LiveHeaderFieldRuns.lean
new file mode 100644
index 0000000000..c4dac262b9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderFieldRuns.lean
@@ -0,0 +1,191 @@
+import OAI.Computability.VPVNP.LiveHeaderRuns
+import OAI.Computability.VPVNP.LiveHeaderFields
+
+/-!
+# Native payload scans of the incident cuts
+
+Each completed field scan copies exactly the specified interval to the
+designated buffer. Every word outside that buffer still has its input value.
+Source intervals refer to the original packed processor headers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The prefix written to scratch, together with a frame for all other cells. -/
+structure FieldCopy (original : Memory w) (slot : Fin 4) (src dst cursor : ℕ) (m : Memory w) : Prop where
+ copied : ∀ j < cursor, m (dst+j) = PrimedInputRAM.encodeBit w ((original (src+j)).val.testBit slot.val)
+ frame : ∀ a, a < dst ∨ dst+cursor ≤ a → m a = original a
+
+theorem FieldCopy.initial (original : Memory w) (slot : Fin 4) (src dst : ℕ) :
+ FieldCopy original slot src dst 0 original := ⟨by simp, fun _ _ => rfl⟩
+
+private theorem word_val_add (a b : Word w) (h : a.val + b.val < 2 ^ w) :
+ (a+b).val = a.val+b.val := by rw [Fin.val_add, Nat.mod_eq_of_lt h]
+
+private theorem cursor_sub (pub : Fin 3 → Word w) (j : ℕ) :
+ (((pub 0).val + j : ℕ) : Word w) - pub 0 = (j : Word w) := by
+ rw [Nat.cast_add, Fin.cast_val_eq_self, add_sub_cancel_left]
+
+/-- A fixed, fifteen-instruction table copies every bit of the occupied source
+field and preserves all memory outside the destination. Each step has three
+probes. Empty fields have the empty execution and leave all cells intact. -/
+theorem copy_field_native (hw : 4 ≤ w) (slot : Fin 4) (pub : Fin 3 → Word w)
+ (original : Memory w) (len : ℕ) (hsrc : (original (pub 1).val).val + len ≤ (pub 2).val)
+ (hdesc : (pub 1).val < (pub 2).val ∨ (pub 2).val + len ≤ (pub 1).val)
+ (hfit : (pub 2).val + len ≤ 2 ^ w) :
+ let P := ((template (copyFieldCell slot) 7).instantiate w pub).program
+ ∃ rs, runSegment P 16 (some (pub 0)) original (List.replicate len []) = some rs ∧
+ endState (some (pub 0)) rs = some (pub 0 + (len : Word w)) ∧
+ FieldCopy original slot (original (pub 1).val).val (pub 2).val len
+ (after original (eventLog rs)) ∧ rs.length = len ∧ ∀ x ∈ rs, countProbes x.events ≤ 3 := by
+ let P := ((template (copyFieldCell slot) 7).instantiate w pub).program
+ let src := (original (pub 1).val).val
+ let dst := (pub 2).val
+ let inv := FieldCopy original slot src dst
+ have hi := FieldCopy.initial original slot src dst
+ have step (j : ℕ) (hj : j < len) (m : Memory w) (h : inv j m) : ∃ es,
+ execute P 16 (P.start (((pub 0).val+j : ℕ) : Word w)) m [] =
+ some ⟨es, some (((pub 0).val+(j+1) : ℕ) : Word w)⟩ ∧
+ inv (j+1) (after m es) ∧ countProbes es ≤ 3 := by
+ let state : Word w := ((pub 0).val + j : ℕ)
+ have hΔ : state - pub 0 = (j : Word w) := cursor_sub pub j
+ have hjval : (j : Word w).val = j := (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt (by omega))
+ have hd : (pub 2 + (state - pub 0)).val = dst+j := by
+ rw [hΔ, word_val_add _ _ (by rw [hjval]; omega), hjval]
+ have hreadDesc := h.frame (pub 1).val (hdesc.imp_right (by dsimp [dst]; omega))
+ have hs : (sourceSite pub state m).val = src+j := by
+ simp only [sourceSite, hΔ, hreadDesc]
+ rw [word_val_add _ _ (by rw [hjval]; omega), hjval]
+ have hbefore : src+j < dst := by dsimp [src,dst]; omega
+ have hreadSite := h.frame (src+j) (Or.inl hbefore)
+ obtain ⟨es, rs, ht, hr, _, hp, _⟩ := copyFieldCell_trace hw slot pub state (fun _ => 0) m
+ refine ⟨es, ?_, ?_, hp.le⟩
+ · change execute ((template (copyFieldCell slot) 7).instantiate w pub).program
+ (1 + (copyFieldCell slot).length) ⟨_,state,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [hr,state,add_assoc]
+ · rw [trace_after ht,hs,hreadSite]
+ constructor
+ · intro k hk
+ simp only [writeMemory,hd]
+ by_cases he : k = j
+ · simp [he]
+ · simp [he,h.copied k (by omega)]
+ · intro a ha
+ have hne : a ≠ dst+j := by omega
+ simp [writeMemory,hd,hne,h.frame a (by omega)]
+ simpa only [Nat.cast_add, Fin.cast_val_eq_self] using
+ run_cursor_segment_at P (pub 0).val 16 len 3 inv original hi step
+
+/-- The guard reads two words and returns the next cursor precisely on a zero
+bit. Its successful trace leaves memory untouched. -/
+theorem padding_step (hw : 4 ≤ w) (slot : Fin 4) (pub : Fin 3 → Word w) (s : Word w) (m : Memory w) :
+ let P := ((template (checkPaddingCell slot) 7).instantiate w pub).program
+ if (m (sourceSite pub s m).val).val.testBit slot.val then
+ execute P 15 (P.start s) m [] = none
+ else ∃ es, execute P 15 (P.start s) m [] = some ⟨es, some (s+1)⟩ ∧ after m es = m ∧
+ countProbes es = 2 := by
+ dsimp only
+ change (if _ then execute ((template (checkPaddingCell slot) 7).instantiate w pub).program (1 + (checkPaddingCell slot).length) ⟨_,s,fun _ => 0,fun _ => 0⟩ m [] = _
+ else ∃ es, execute ((template (checkPaddingCell slot) 7).instantiate w pub).program (1 + (checkPaddingCell slot).length) ⟨_,s,fun _ => 0,fun _ => 0⟩ m [] = _ ∧ _)
+ have ht := checkPaddingCell_trace hw slot pub s (fun _ => 0) m
+ split_ifs with hb
+ · simp only [hb,↓reduceIte] at ht
+ rw [execute_template,run_eq_trace,ht]
+ rfl
+ · simp only [hb] at ht
+ obtain ⟨es, rs, ht, hr, _, hp, _⟩ := ht
+ refine ⟨es, ?_, trace_after ht, hp⟩
+ rw [execute_template,run_eq_trace,ht]
+ simp [hr]
+
+/-- On arbitrary cut input, the full padding scan succeeds exactly if every
+padding bit is zero. It touches only the specified interval, even on malformed input. -/
+theorem padding_native_iff (hw : 4 ≤ w) (slot : Fin 4) (pub : Fin 3 → Word w) (m : Memory w)
+ (len : ℕ) (hfit : (m (pub 1).val).val + len ≤ 2 ^ w) :
+ let P := ((template (checkPaddingCell slot) 7).instantiate w pub).program
+ (runSegment P 15 (some (pub 0)) m (List.replicate len [])).isSome = true ↔
+ ∀ j < len, (m ((m (pub 1).val).val+j)).val.testBit slot.val = false := by
+ let P := ((template (checkPaddingCell slot) 7).instantiate w pub).program
+ have go (n k : ℕ) (hkn : k+n ≤ len) :
+ (runSegment P 15 (some (pub 0 + (k : Word w))) m (List.replicate n [])).isSome = true ↔
+ ∀ j, k ≤ j → j < k+n → (m ((m (pub 1).val).val+j)).val.testBit slot.val = false := by
+ induction n generalizing k with
+ | zero => simp [runSegment]; intro j hj hlt; omega
+ | succ n ih =>
+ have hk : k < len := by omega
+ have hkval : (k : Word w).val = k := Fin.val_cast_of_lt (by omega)
+ let s := pub 0 + (k : Word w)
+ have hs : (sourceSite pub s m).val = (m (pub 1).val).val+k := by
+ dsimp [s,sourceSite]
+ rw [add_sub_cancel_left, word_val_add _ _ (by rw [hkval]; omega), hkval]
+ have ht := padding_step hw slot pub s m
+ dsimp only at ht
+ rw [hs] at ht
+ cases hbit : (m ((m (pub 1).val).val+k)).val.testBit slot.val with
+ | true =>
+ simp only [hbit,↓reduceIte] at ht
+ rw [List.replicate_succ,runSegment]
+ change (match execute P 15 (P.start s) m [] with
+ | none => none
+ | some r => (runSegment P 15 r.result (after m r.events) (List.replicate n [])).map (r :: ·)).isSome = true ↔ _
+ rw [ht]
+ simp only [Option.isSome_none, Bool.false_eq_true, false_iff]
+ exact fun hn => Bool.noConfusion ((hn k le_rfl (by omega)).symm.trans hbit)
+ | false =>
+ simp only [hbit,Bool.false_eq_true,↓reduceIte] at ht
+ obtain ⟨es, he, hm, _⟩ := ht
+ rw [List.replicate_succ,runSegment]
+ change (match execute P 15 (P.start s) m [] with
+ | none => none
+ | some r => (runSegment P 15 r.result (after m r.events) (List.replicate n [])).map (r :: ·)).isSome = true ↔ _
+ rw [he]
+ simp only [hm,Option.isSome_map]
+ have hnext : s+1 = pub 0 + ((k+1 : ℕ) : Word w) := by simp [s,add_assoc]
+ rw [hnext,ih (k+1) (by omega)]
+ constructor
+ · intro hn j hj hlt
+ rcases eq_or_lt_of_le hj with heq | hlt'
+ · simpa [← heq] using hbit
+ · exact hn j (by omega) (by omega)
+ · intro hn j hj hlt
+ exact hn j (by omega) (by omega)
+ simpa using go len 0 (by simp)
+
+/-- Every successful padding call has precisely two probes, and its entire
+segment preserves every cell. -/
+theorem padding_native (hw : 4 ≤ w) (slot : Fin 4) (pub : Fin 3 → Word w) (m : Memory w)
+ (len : ℕ) (hfit : (m (pub 1).val).val + len ≤ 2 ^ w)
+ (hz : ∀ j < len, (m ((m (pub 1).val).val+j)).val.testBit slot.val = false) :
+ let P := ((template (checkPaddingCell slot) 7).instantiate w pub).program
+ ∃ rs, runSegment P 15 (some (pub 0)) m (List.replicate len []) = some rs ∧
+ endState (some (pub 0)) rs = some (pub 0 + (len : Word w)) ∧ after m (eventLog rs) = m ∧
+ rs.length = len ∧ ∀ x ∈ rs, countProbes x.events ≤ 2 := by
+ let P := ((template (checkPaddingCell slot) 7).instantiate w pub).program
+ have h := run_cursor_segment_at P (pub 0).val 15 len 2 (fun _ mem => mem = m) m rfl
+ apply (by simpa only [Nat.cast_add,Fin.cast_val_eq_self] using h)
+ intro j hj mem hm
+ subst mem
+ let s : Word w := ((pub 0).val+j : ℕ)
+ have hs : (sourceSite pub s m).val = (m (pub 1).val).val+j := by
+ have hjval : (j : Word w).val = j := Fin.val_cast_of_lt (by omega)
+ rw [sourceSite,cursor_sub,word_val_add _ _ (by rw [hjval]; omega),hjval]
+ have ht := padding_step hw slot pub s m
+ simp only [hs,hz j hj,Bool.false_eq_true,↓reduceIte] at ht
+ obtain ⟨es, he, hm, hp⟩ := ht
+ exact ⟨es, by simpa [s,P,add_assoc] using he, hm, hp.le⟩
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderFieldState.lean b/lean/OAI/Computability/VPVNP/LiveHeaderFieldState.lean
new file mode 100644
index 0000000000..f1d2b27dcf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderFieldState.lean
@@ -0,0 +1,187 @@
+import OAI.Computability.VPVNP.LiveHeaderProgramFit
+import OAI.Computability.VPVNP.LiveHeaderSingleRun
+
+/-!
+# Memory invariants for the sixteen incident-field stages
+
+Each incident field has a descriptor stage and a consumer stage. All six
+nonpadding payloads occupy disjoint public ranges. An unoccupied part of
+an array retains its original scratch value, including the initial zero
+exponent vector at the first group.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.Fields
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderDescriptors
+open ChainAssignments CutSchedule LiveHeader PrimedInputRAM
+
+variable {w d : ℕ}
+
+/-- Enumerate the four incident fields on the left and then the four on the right in extraction
+order. -/
+def key : Fin 8 → Side × Field :=
+ ![(.left,.exterior),(.left,.exponents),(.left,.config),(.left,.padding),
+ (.right,.exterior),(.right,.exponents),(.right,.config),(.right,.padding)]
+
+theorem key_inj : Function.Injective key := by
+ intro i j
+ fin_cases i <;> fin_cases j <;> decide
+
+theorem key_surj : Function.Surjective key := by
+ rintro ⟨side,f⟩
+ cases side <;> cases f <;> decide
+
+/-- The stage number of the descriptor computation for the given incident-field ordinal. -/
+def descId (k : Fin 8) : StageId := ⟨15+2*k.val,by have := k.isLt; rw [stage_count]; omega⟩
+/-- The stage number of the bounded field scan immediately following its descriptor
+computation. -/
+def scanId (k : Fin 8) : StageId := ⟨16+2*k.val,by have := k.isLt; rw [stage_count]; omega⟩
+/-- The descriptor stage that begins the indicated remaining field, or no stage once all eight
+fields have run. -/
+def startId (n : ℕ) : Option StageId := if h : n < 8 then some (descId ⟨n,h⟩) else none
+
+@[simp] theorem stage_desc (k : Fin 8) : stage (descId k) = .descriptor (key k).1 (key k).2 := by
+ fin_cases k <;> rfl
+
+@[simp] theorem stage_scan (k : Fin 8) : stage (scanId k) = .scan (key k).1 (key k).2 := by
+ fin_cases k <;> rfl
+
+@[simp] theorem next_desc (k : Fin 8) : next (descId k) = some (scanId k) := by fin_cases k <;> rfl
+
+@[simp] theorem next_scan (k : Fin 8) : next (scanId k) = startId (k.val+1) := by fin_cases k <;> rfl
+
+@[simp] theorem start_at (k : Fin 8) : startId k.val = some (descId k) := by
+ simp [startId,k.isLt]
+
+/-- The source offset and length of one incident field for the group's actual width, phase, and
+mode. -/
+def interval (s : Sizes) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (side : Side) (f : Field) :=
+ let W := incidentWidth (Δ := s.delta) side g
+ span (shape side W tag.code.val (firstHalfFlag g) (decide (g.val+1 = 2^s.h+1))) W s.delta s.e s.config f
+
+theorem interval_capacity (s : Sizes) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (side : Side) (f : Field) :
+ (interval s g tag side f).2 ≤ s.capacity f :=
+ occupied_le_capacity s f _ (cut_width_le_capacity s _)
+
+theorem interval_inside (s : Sizes) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (side : Side) (f : Field)
+ (he : 1+s.e ≤ s.delta) (hc : 1+s.config ≤ s.delta) :
+ (interval s g tag side f).1+(interval s g tag side f).2 ≤ incidentWidth (Δ := s.delta) side g :=
+ span_fit he hc (shape_fit (width_ge_block (s.h+1) s.delta _)) f
+
+/-- Scalar and packed source words surviving from the earlier header stages. -/
+structure Sources (s : Sizes) (base d : ℕ) (hw : 4 ≤ w) (advice : Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (m : Memory w) : Prop where
+ headers : SiteHeaders d hw advice cuts g m
+ width : ∀ side, (m (widthAddr base (if side = .left then .liveLeft else .liveRight))).val =
+ incidentWidth (Δ := s.delta) side g
+ mode : (m (tagAddr base)).val = tag.code.val
+ half : m (flagAddr base .firstHalf) = encodeBit w (firstHalfFlag g)
+ firstTail : m (firstTailAddr base) = encodeBit w (decide (g.val+1 = 2^s.h+1))
+
+/-- Addresses read by later stages may contain any value at entry. All words
+except the handoff tag, the descriptors, and the actually occupied payloads
+must retain that value through the field suffix. -/
+def Protected (s : Sizes) (base : ℕ) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (addr : ℕ) : Prop :=
+ addr ≠ base ∧ addr ≠ offsetAddr base ∧ addr ≠ countAddr base ∧
+ ∀ side f, f ≠ .padding → Allocated.Outside (dest s base side f) (interval s g tag side f).2 addr
+
+/-- All nonpadding fields with index below the cursor have been copied. The
+frame retains zero in each unused part of a payload array. -/
+structure Image (s : Sizes) (base : ℕ) (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1)))
+ (tag : Mode.Tag) (cursor : ℕ) (before m : Memory w) : Prop where
+ copies : ∀ k : Fin 8, k.val < cursor → (key k).2 ≠ .padding →
+ CopiedSlice (cuts (incidentCut (key k).1 g)) (interval s g tag (key k).1 (key k).2)
+ (dest s base (key k).1 (key k).2) m
+ frame : ∀ addr, Protected s base g tag addr → m addr = before addr
+
+theorem Image.initial (s : Sizes) (base : ℕ) (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1)))
+ (tag : Mode.Tag) (m : Memory w) : Image s base cuts g tag 0 m m := ⟨by omega,fun _ _ => rfl⟩
+
+/-- Physical zero padding selected by the actual descriptor shape. -/
+def ValidPadding (s : Sizes) (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (side : Side) :=
+ Physical.ZeroSlice (cuts (incidentCut side g)) (interval s g tag side .padding)
+
+/-- Writing a descriptor and consuming that one field cannot change any
+other payload. Only the tag and descriptor words change on handoff. -/
+structure FieldEffect (s : Sizes) (base : ℕ) (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1)))
+ (tag : Mode.Tag) (side : Side) (f : Field) (before m : Memory w) : Prop where
+ copy : f ≠ .padding → CopiedSlice (cuts (incidentCut side g)) (interval s g tag side f) (dest s base side f) m
+ frame : ∀ addr, addr ≠ base → addr ≠ offsetAddr base → addr ≠ countAddr base →
+ (f = .padding ∨ Allocated.Outside (dest s base side f) (interval s g tag side f).2 addr) →
+ m addr = before addr
+
+theorem before_destination (s : Sizes) (base : ℕ) (side : Side) (f : Field) (hf : f ≠ .padding) :
+ base+14 < dest s base side f := by
+ have h := (dest_bounds s base side f hf).1
+ dsimp [adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase] at h
+ omega
+
+theorem Image.advance {s : Sizes} {base : ℕ} {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))}
+ {tag : Mode.Tag} {before m out : Memory w} (k : Fin 8) (img : Image s base cuts g tag k.val before m)
+ (step : FieldEffect s base cuts g tag (key k).1 (key k).2 m out) : Image s base cuts g tag (k.val+1) before out := by
+ constructor
+ · intro i hi hf
+ by_cases same : i = k
+ · subst i
+ exact step.copy hf
+ · have hi' : i.val < k.val := by have hv : i.val ≠ k.val := fun he => same (Fin.ext he); omega
+ apply (img.copies i hi' hf).congr
+ intro j hj
+ have hbase := before_destination s base (key i).1 (key i).2 hf
+ apply step.frame _ (by omega) (by unfold offsetAddr; omega) (by unfold countAddr; omega)
+ by_cases hpad : (key k).2 = .padding
+ · exact Or.inl hpad
+ · apply Or.inr
+ have hne : ((key i).1,(key i).2) ≠ ((key k).1,(key k).2) := fun eq => same (key_inj eq)
+ have h₁ := interval_capacity s g tag (key i).1 (key i).2
+ have h₂ := interval_capacity s g tag (key k).1 (key k).2
+ rcases dest_disjoint s base hf hpad hne with left | right <;> unfold Allocated.Outside <;> omega
+ · intro addr ha
+ rcases ha with ⟨hb,ho,hc,other⟩
+ have hs := step.frame addr hb ho hc (by
+ by_cases hpad : (key k).2 = .padding
+ · exact Or.inl hpad
+ · exact Or.inr (other _ _ hpad))
+ exact hs.trans (img.frame addr ⟨hb,ho,hc,other⟩)
+
+theorem Sources.congr {s : Sizes} {base d : ℕ} {hw : 4 ≤ w} {advice : Bits s.advice}
+ {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))} {tag : Mode.Tag} {m out : Memory w}
+ (old : Sources s base d hw advice cuts g tag m) (sites : 2^d ≤ base)
+ (frame : ∀ addr, addr ≠ base → addr ≠ offsetAddr base → addr ≠ countAddr base →
+ addr < base+14 → out addr = m addr) : Sources s base d hw advice cuts g tag out := by
+ constructor
+ · intro v
+ have h := v.isLt
+ rw [frame v.val (by omega) (by unfold offsetAddr; omega) (by unfold countAddr; omega) (by omega), old.headers v]
+ · intro side
+ rw [← old.width side]
+ congr 1
+ apply frame <;> cases side <;> dsimp [widthAddr,countAddr,offsetAddr] <;> omega
+ · rw [frame,old.mode]
+ all_goals dsimp [tagAddr,countAddr,offsetAddr]; omega
+ · rw [frame,old.half]
+ all_goals dsimp [flagAddr,countAddr,offsetAddr]; omega
+ · rw [frame,old.firstTail]
+ all_goals dsimp [firstTailAddr,countAddr,offsetAddr]; omega
+
+theorem Sources.afterField {s : Sizes} {base d : ℕ} {hw : 4 ≤ w} {advice : Bits s.advice}
+ {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))} {tag : Mode.Tag} {m out : Memory w}
+ (old : Sources s base d hw advice cuts g tag m) (sites : 2^d ≤ base)
+ (side : Side) (f : Field) (effect : FieldEffect s base cuts g tag side f m out) :
+ Sources s base d hw advice cuts g tag out := by
+ apply old.congr sites
+ intro addr hb ho hc low
+ apply effect.frame _ hb ho hc
+ by_cases hpad : f = .padding
+ · exact Or.inl hpad
+ · exact Or.inr (Or.inl (low.trans (before_destination s base side f hpad)))
+
+end LiveHeaderProgram.Fields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderFieldSuffix.lean b/lean/OAI/Computability/VPVNP/LiveHeaderFieldSuffix.lean
new file mode 100644
index 0000000000..e53e88abc4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderFieldSuffix.lean
@@ -0,0 +1,242 @@
+import OAI.Computability.VPVNP.LiveHeaderFieldState
+import OAI.Computability.VPVNP.LiveHeaderScanRows
+
+/-!
+# The full native incident-field suffix
+
+The final sixteen scheduled stages alternate a private descriptor with a
+bounded scan. The descriptors always run on the real width, mode and phase
+words, and the scans read the original packed headers. Each accepted stage
+hands off its actual final memory. Malformed padding yields a valid prefix
+leading to a scan with no accepting continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.Fields
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderDescriptors
+open ChainAssignments CutSchedule LiveHeader PrimedInputRAM
+
+variable {s : Sizes} {base d w : ℕ} {hw : 4 ≤ w} {advice : Bits s.advice}
+ {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))} {tag : Mode.Tag}
+
+/-- Public bounds for these sixteen stages. -/
+structure Bounds (s : Sizes) (base d w : ℕ) : Prop where
+ fit : limit s base < 2^w
+ scratch : 2^d ≤ base
+ sites : s.capacity .exterior ≤ 2^d
+ exponents : 1+s.e ≤ s.delta
+ config : 1+s.config ≤ s.delta
+
+private theorem base_val (bounds : Bounds s base d w) : (Fin.ofNat (2^w) base).val = base := by
+ have h := bounds.fit
+ rw [limit_eq] at h
+ exact Nat.mod_eq_of_lt (by omega)
+
+private theorem transfer_at (bounds : Bounds s base d w) (id : Option StageId) (m : Memory w) (a : ℕ)
+ (other : a ≠ base) : LiveStageLink.transferMemory (Fin.ofNat _ base) id m a = m a := by
+ cases id with
+ | none => rfl
+ | some _ => exact ite_eq_right (by simpa only [base_val bounds] using other)
+
+/-- The descriptor output contains the requested offset and length, with only the tag and those
+two scratch cells allowed to change. -/
+structure Prepared (s : Sizes) (base : ℕ) (iv : ℕ × ℕ) (before out : Memory w) : Prop where
+ offset : (out (offsetAddr base)).val = iv.1
+ count : (out (countAddr base)).val = iv.2
+ frame : ∀ addr, addr ≠ base → addr ≠ offsetAddr base → addr ≠ countAddr base → out addr = before addr
+
+private theorem descriptor_prefix (bounds : Bounds s base d w) {m : Memory w}
+ (src : Sources s base d hw advice cuts g tag m) (k : Fin 8) :
+ ∃ x out, x.Good s ∧ StagePrefix s base (some (descId k)) m [x] (some (scanId k)) out ∧
+ Prepared s base (interval s g tag (key k).1 (key k).2) m out ∧
+ Sources s base d hw advice cuts g tag out := by
+ let side := (key k).1
+ let f := (key k).2
+ let W := incidentWidth (Δ := s.delta) side g
+ have hblock : W = 0 ∨ s.delta ≤ W := width_ge_block _ _ _
+ obtain ⟨o,l,hoff,hlen,run⟩ := descriptor_run s base side f m (by omega : 0 < w)
+ (scalarFit_of_limit bounds.fit.le) W tag.code.val (firstHalfFlag g) (decide (g.val+1 = 2^s.h+1))
+ (src.width side) src.mode src.half src.firstTail bounds.exponents bounds.config hblock
+ obtain ⟨x,_,good,history⟩ := run.prefix (descId k) (stage_desc k) rfl
+ rw [next_desc] at history
+ let mid := writeMemory (writeMemory m (Fin.ofNat _ (offsetAddr base)) o) (Fin.ofNat _ (countAddr base)) l
+ let out := LiveStageLink.transferMemory (Fin.ofNat _ base) (some (scanId k)) mid
+ have fit := bounds.fit
+ rw [limit_eq] at fit
+ have ho : (Fin.ofNat (2^w) (offsetAddr base)).val = offsetAddr base := Nat.mod_eq_of_lt (by unfold offsetAddr; omega)
+ have hc : (Fin.ofNat (2^w) (countAddr base)).val = countAddr base := Nat.mod_eq_of_lt (by unfold countAddr; omega)
+ have prepared : Prepared s base (interval s g tag side f) m out := by
+ constructor
+ · rw [show out (offsetAddr base) = mid (offsetAddr base) from transfer_at bounds _ _ _ (by unfold offsetAddr; omega)]
+ simp only [mid,writeMemory,ho,hc,ite_eq_right (show offsetAddr base ≠ countAddr base by unfold offsetAddr countAddr; omega),ite_true]
+ exact hoff
+ · rw [show out (countAddr base) = mid (countAddr base) from transfer_at bounds _ _ _ (by unfold countAddr; omega)]
+ simp only [mid,writeMemory,hc,ite_true]
+ exact hlen
+ · intro a hb h₁ h₂
+ rw [show out a = mid a from transfer_at bounds _ _ _ hb]
+ simp only [mid,writeMemory,ho,hc,ite_eq_right h₁,ite_eq_right h₂]
+ exact ⟨x,out,good,history,prepared,src.congr bounds.scratch (fun a hb h₁ h₂ _ => prepared.frame a hb h₁ h₂)⟩
+
+private theorem scan_prefix {id : StageId} {st : Stage} (hid : stage id = st) {m : Memory w} {rs : List (Report w)}
+ (run : runSegment ((stageTemplate st).2.instantiate w (rowData w s base st)).program 25
+ (some 0) m (List.replicate (calls s st) []) = some rs)
+ (last : endState (some 0) rs = none) (len : rs.length = calls s st)
+ (hp : ∀ r ∈ rs, r.probes ≤ probes st) (frame : LiveStageLink.PreservesTag (Fin.ofNat _ base) rs) :
+ ∃ x, x.Good s ∧ StagePrefix s base (some id) m [x] (next id)
+ (LiveStageLink.transferMemory (Fin.ofNat _ base) (next id) (after m (eventLog rs))) := by
+ let x : StageTrace w := ⟨id,25,List.replicate (calls s st) [],rs⟩
+ have he : x.Exec s base m := by
+ constructor
+ · change runSegment ((stageTemplate (stage id)).2.instantiate w (rowData w s base (stage id))).program
+ 25 (some 0) m (List.replicate (calls s st) []) = some rs
+ rw [hid]; exact run
+ · exact last
+ · exact frame.onReturns m
+ have hgood : x.Good s := by
+ change 25 ≤ 40 ∧ _ = List.replicate (calls s (stage id)) [] ∧ rs.length = calls s (stage id) ∧ _
+ rw [hid]
+ exact ⟨by decide,rfl,len,hp⟩
+ exact ⟨x,hgood,StagePrefix.single he⟩
+
+private theorem pair_prefix (bounds : Bounds s base d w) {m : Memory w}
+ (src : Sources s base d hw advice cuts g tag m) (k : Fin 8)
+ (valid : (key k).2 = .padding → ValidPadding s cuts g tag (key k).1) :
+ ∃ xs out, (∀ x ∈ xs, x.Good s) ∧ StagePrefix s base (startId k.val) m xs (startId (k.val+1)) out ∧
+ FieldEffect s base cuts g tag (key k).1 (key k).2 m out := by
+ let side := (key k).1
+ let f := (key k).2
+ let iv := interval s g tag side f
+ obtain ⟨x,mid,hx,pre,prepared,srcMid⟩ := descriptor_prefix bounds src k
+ have inside : iv.1+iv.2 ≤ incidentWidth (Δ := s.delta) side g := interval_inside _ _ _ _ _ bounds.exponents bounds.config
+ have sites : iv.1+iv.2 ≤ 2^d := inside.trans ((cut_width_le_capacity s _).trans bounds.sites)
+ have hcap := interval_capacity s g tag side f
+ have finish {y : StageTrace w} {out : Memory w} (hy : y.Good s)
+ (second : StagePrefix s base (some (scanId k)) mid [y] (startId (k.val+1)) out)
+ (effect : FieldEffect s base cuts g tag side f m out) :
+ ∃ xs out, (∀ x ∈ xs, x.Good s) ∧ StagePrefix s base (startId k.val) m xs (startId (k.val+1)) out ∧
+ FieldEffect s base cuts g tag side f m out := by
+ refine ⟨[x]++[y],out,?_,by simpa only [start_at] using pre.append second,effect⟩
+ intro z hz
+ rcases List.mem_append.mp hz with a | b
+ · exact (List.mem_singleton.mp a) ▸ hx
+ · exact (List.mem_singleton.mp b) ▸ hy
+ by_cases pad : f = .padding
+ · have zero := (srcMid.headers.zeroSlice side iv sites inside).mpr (by change Physical.ZeroSlice _ (interval s g tag side f); rw [pad]; exact valid pad)
+ obtain ⟨rs,run,last,hm,len,hp,frame⟩ := ScanRows.padding_run hw s base d bounds.fit bounds.scratch side
+ mid iv sites (pad ▸ hcap) prepared.offset prepared.count zero
+ have hid : stage (scanId k) = .scan side .padding := (stage_scan k).trans (congrArg (Stage.scan side) pad)
+ obtain ⟨y,hy,second⟩ := scan_prefix (s := s) (base := base) hid run last len hp frame
+ rw [next_scan] at second
+ apply finish hy second
+ constructor
+ · exact fun hn => (hn pad).elim
+ · intro a hb ho hc _
+ rw [transfer_at bounds _ _ _ hb,hm,prepared.frame a hb ho hc]
+ · obtain ⟨rs,run,last,copy,len,hp,frame⟩ := ScanRows.copy_run hw s base d bounds.fit bounds.scratch side f
+ pad mid iv sites hcap prepared.offset prepared.count
+ obtain ⟨y,hy,second⟩ := scan_prefix (s := s) (base := base) (stage_scan k) run last len hp frame
+ rw [next_scan] at second
+ have hd := before_destination s base side f pad
+ have read := (copy.physical srcMid.headers side iv _ sites (bounds.scratch.trans (by omega))).1
+ apply finish hy second
+ constructor
+ · intro _
+ exact read.congr (fun j _ => transfer_at bounds _ _ _ (by omega))
+ · intro a hb ho hc safe
+ rw [transfer_at bounds _ _ _ hb,copy.frame a (safe.resolve_left pad),prepared.frame a hb ho hc]
+
+/-- Execute all descriptor/scan pairs whose indices precede the cursor.
+The reachable image is strong enough to continue at the next pair. -/
+theorem reach (bounds : Bounds s base d w) {m : Memory w} (src : Sources s base d hw advice cuts g tag m)
+ (n : ℕ) (le : n ≤ 8) (valid : ∀ k : Fin 8, k.val < n → (key k).2 = .padding → ValidPadding s cuts g tag (key k).1) :
+ ∃ xs out, (∀ x ∈ xs, x.Good s) ∧ StagePrefix s base (startId 0) m xs (startId n) out ∧
+ Sources s base d hw advice cuts g tag out ∧ Image s base cuts g tag n m out := by
+ induction n with
+ | zero => exact ⟨[],m,by simp,.nil _ _,src,Image.initial ..⟩
+ | succ n ih =>
+ let k : Fin 8 := ⟨n,by omega⟩
+ obtain ⟨xs,mid,good,history,srcMid,img⟩ := ih (by omega) (fun j hj => valid j (by omega))
+ obtain ⟨ys,out,good',second,effect⟩ := pair_prefix bounds srcMid k (valid k (by dsimp [k]; omega))
+ refine ⟨xs++ys,out,?_,history.append second,srcMid.afterField bounds.scratch _ _ effect,img.advance k effect⟩
+ intro z hz
+ exact (List.mem_append.mp hz).elim (good z) (good' z)
+
+/-- From the actual post-index, post-mode and post-primed memory, all sixteen
+remaining stages accept on canonical padding, yielding every copied field
+and the complete frame outside the occupied fields and three admin cells. -/
+theorem suffix_native (bounds : Bounds s base d w) {m : Memory w} (src : Sources s base d hw advice cuts g tag m)
+ (valid : ∀ side, ValidPadding s cuts g tag side) :
+ ∃ xs out, (∀ x ∈ xs, x.Good s) ∧ StagePrefix s base (some (⟨15,by decide⟩ : StageId)) m xs none out ∧
+ StageRuns s base (some (⟨15,by decide⟩ : StageId)) m xs ∧ Sources s base d hw advice cuts g tag out ∧
+ Image s base cuts g tag 8 m out := by
+ obtain ⟨xs,out,good,pre,source,img⟩ := reach bounds src 8 le_rfl (fun k _ _ => valid (key k).1)
+ have final : StagePrefix s base (some (⟨15,by decide⟩ : StageId)) m xs none out := pre
+ exact ⟨xs,out,good,final,by simpa using final.finish (.done out),source,img⟩
+
+/-- Reach a malformed padding scan after a valid prefix. Its entry retains
+the actual headers and the offset/count words of the failing descriptor. -/
+theorem bad_prefix_at (bounds : Bounds s base d w) {m : Memory w} (src : Sources s base d hw advice cuts g tag m)
+ (k : Fin 8) (pad : (key k).2 = .padding) (bad : ¬ ValidPadding s cuts g tag (key k).1)
+ (earlier : ∀ i : Fin 8, i.val < k.val → (key i).2 = .padding → ValidPadding s cuts g tag (key i).1) :
+ ∃ xs mid, (∀ x ∈ xs, x.Good s) ∧ StagePrefix s base (startId 0) m xs (some (scanId k)) mid ∧
+ Sources s base d hw advice cuts g tag mid ∧
+ (mid (offsetAddr base)).val = (interval s g tag (key k).1 .padding).1 ∧
+ (mid (countAddr base)).val = (interval s g tag (key k).1 .padding).2 ∧
+ ¬ Allocated.ZeroPad (cutSlot (key k).1) (interval s g tag (key k).1 .padding) mid := by
+ obtain ⟨xs,m',hg,pre,src',_⟩ := reach bounds src k.val k.isLt.le earlier
+ obtain ⟨x,mid,hx,desc,prepared,srcMid⟩ := descriptor_prefix bounds src' k
+ rw [start_at k] at pre
+ have inside := interval_inside s g tag (key k).1 .padding bounds.exponents bounds.config
+ have sites := inside.trans ((cut_width_le_capacity s _).trans bounds.sites)
+ refine ⟨xs++[x],mid,?_,pre.append desc,srcMid,?_,?_,?_⟩
+ · intro y hy
+ rcases List.mem_append.mp hy with prev | last
+ · exact hg y prev
+ · exact (List.mem_singleton.mp last) ▸ hx
+ · simpa only [pad] using prepared.offset
+ · simpa only [pad] using prepared.count
+ · exact mt (srcMid.headers.zeroSlice (key k).1 _ sites inside).mp bad
+
+/-- Choose the first malformed side in the actual public order. -/
+theorem first_bad_padding (bad : ¬ ∀ side, ValidPadding s cuts g tag side) :
+ ∃ k : Fin 8, (key k).2 = .padding ∧ ¬ ValidPadding s cuts g tag (key k).1 ∧
+ ∀ i : Fin 8, i.val < k.val → (key i).2 = .padding → ValidPadding s cuts g tag (key i).1 := by
+ by_cases left : ValidPadding s cuts g tag .left
+ · have right : ¬ ValidPadding s cuts g tag .right := fun hr => bad (fun side => by cases side <;> assumption)
+ refine ⟨7,rfl,right,?_⟩
+ intro i hi he
+ fin_cases i <;> first | exact left | contradiction
+ · refine ⟨3,rfl,left,?_⟩
+ intro i hi he
+ fin_cases i <;> contradiction
+
+/-- A malformed padding bit leads to a scheduled native scan at which no
+choice tape and no fuel bound can produce an accepting exit. -/
+theorem bad_prefix (bounds : Bounds s base d w) {m : Memory w} (src : Sources s base d hw advice cuts g tag m)
+ (bad : ¬ ∀ side, ValidPadding s cuts g tag side) :
+ ∃ (side : Side) (id : StageId) (xs : List (StageTrace w)) (mid : Memory w), stage id = .scan side .padding ∧ (∀ x ∈ xs, x.Good s) ∧
+ StagePrefix s base (startId 0) m xs (some id) mid ∧
+ ∀ fuel bits rs, runSegment ((stageTemplate (stage id)).2.instantiate w (rowData w s base (stage id))).program
+ fuel (some 0) mid bits = some rs → endState (some 0) rs ≠ none := by
+ obtain ⟨k,pad,invalid,earlier⟩ := first_bad_padding bad
+ obtain ⟨xs,mid,good,pre,_,hoff,hcount,hbad⟩ := bad_prefix_at bounds src k pad invalid earlier
+ let side := (key k).1
+ let iv := interval s g tag side .padding
+ have hid : stage (scanId k) = .scan side .padding := (stage_scan k).trans (congrArg (Stage.scan side) pad)
+ refine ⟨side,scanId k,xs,mid,hid,good,pre,?_⟩
+ intro fuel bits rs run last
+ rw [hid] at run
+ exact hbad (ScanRows.padding_sound_any hw s base d bounds.fit bounds.scratch side mid iv
+ ((interval_inside s g tag side .padding bounds.exponents bounds.config).trans ((cut_width_le_capacity s _).trans bounds.sites))
+ (interval_capacity s g tag side .padding) hoff hcount fuel bits run last)
+
+end LiveHeaderProgram.Fields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderFieldUnitPadding.lean b/lean/OAI/Computability/VPVNP/LiveHeaderFieldUnitPadding.lean
new file mode 100644
index 0000000000..8b6d7c29fa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderFieldUnitPadding.lean
@@ -0,0 +1,36 @@
+import OAI.Computability.VPVNP.LiveHeaderFieldState
+
+/-!
+# Padding in the unit branch of the field program
+
+For either incident cut the unit descriptor checks the bits following the mode.
+At an endpoint the descriptor uses the missing shape and checks an empty interval.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.Fields
+
+open LiveHeaderSchedule LiveHeaderDescriptors LiveHeader ChainAssignments
+
+theorem interval_unit_padding (s : Sizes) (g : Fin (2^(s.h+1))) (side : Side) :
+ interval s g .unit side .padding =
+ span .unit (incidentWidth (Δ := s.delta) side g) s.delta s.e s.config .padding := by
+ unfold interval
+ by_cases empty : incidentWidth (Δ := s.delta) side g = 0
+ · rw [empty]
+ rfl
+ · simp [shape, empty, Mode.Tag.code]
+
+theorem validPadding_unit_iff (s : Sizes) (cuts : AllCuts s.h s.delta)
+ (g : Fin (2^(s.h+1))) :
+ (∀ side, ValidPadding s cuts g .unit side) ↔ unitPads cuts g s.e s.config := by
+ simp only [ValidPadding, unitPads, interval_unit_padding]
+
+end LiveHeaderProgram.Fields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderFields.lean b/lean/OAI/Computability/VPVNP/LiveHeaderFields.lean
new file mode 100644
index 0000000000..6170fbc6a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderFields.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.LiveHeaderBits
+
+/-!
+# Copying payload and validating zero padding in a live cut
+
+An incoming or outgoing cut bit resides in the packed header of the processor
+at its cut offset. The offset of a payload field can depend on the distributed
+group index. A descriptor word supplies that offset. The destination array is
+fixed across groups, including for the two exponent buffers and tail configurations.
+Each call checks or copies one bit and advances its persistent cursor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Public slots are the phase's first cursor, the address of the source
+offset descriptor, and the fixed base of the destination array. Register 4
+holds the absolute cursor, register 5 the position within this field. -/
+def locateCell (slot : Fin 4) : List (Op 12 3) :=
+ [.stateWord 4, .publicWord 6 0, .binary .sub 5 4 6,
+ .publicWord 6 1, .read 6 6, .binary .add 0 6 5] ++ fetch slot
+
+/-- Copy one bit to the same offset in the designated unpacked field. -/
+def copyFieldCell (slot : Fin 4) : List (Op 12 3) :=
+ locateCell slot ++ [.publicWord 6 2, .binary .add 6 6 5, .write 6 1, .binary .add 7 4 3]
+
+/-- Reject a nonzero padding bit. This same guard checks all nonmode bits
+of an incident cut in unit mode. -/
+def checkPaddingCell (slot : Fin 4) : List (Op 12 3) :=
+ locateCell slot ++ [.constant 6 0, .guardEq 1 6, .binary .add 7 4 3]
+
+/-- The packed-header source address found by adding the current field-relative cursor to the
+offset read from the descriptor. -/
+def sourceSite (pub : Fin 3 → Word w) (state : Word w) (m : Memory w) : Word w :=
+ m (pub 1).val + (state - pub 0)
+
+theorem copyFieldCell_trace (hw : 4 ≤ w) (slot : Fin 4) (pub : Fin 3 → Word w)
+ (state : Word w) (rs : Regs w 12) (m : Memory w) :
+ let dst := pub 2 + (state - pub 0)
+ let v := m (sourceSite pub state m).val
+ let b := PrimedInputRAM.encodeBit w (v.val.testBit slot.val)
+ ∃ es rs', trace pub state (copyFieldCell slot) rs m = some (es, rs', writeMemory m dst b) ∧
+ rs' 7 = state + 1 ∧ es.length = 15 ∧ countProbes es = 3 ∧ choiceBits es = [] := by
+ have hlt : slot.val < 2 ^ w := slot.isLt.trans_le (show 4 ≤ 2^w from by
+ have := Nat.pow_le_pow_right (by decide : 0 < 2) hw; norm_num at this; omega)
+ simp (config := { decide := true }) [copyFieldCell, locateCell, fetch, trace, Op.effect, Function.update,
+ show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.sub.eval = (· - · : Word w → Word w → Word w) from rfl,
+ PrimedInputRAM.Opcodes.readBit_word (by omega : 0 < w), Nat.mod_eq_of_lt hlt,
+ sourceSite, countProbes, choiceBits]
+
+theorem checkPaddingCell_trace (hw : 4 ≤ w) (slot : Fin 4) (pub : Fin 3 → Word w)
+ (state : Word w) (rs : Regs w 12) (m : Memory w) :
+ if (m (sourceSite pub state m).val).val.testBit slot.val then
+ trace pub state (checkPaddingCell slot) rs m = none
+ else ∃ es rs', trace pub state (checkPaddingCell slot) rs m = some (es, rs', m) ∧
+ rs' 7 = state + 1 ∧ es.length = 14 ∧ countProbes es = 2 ∧ choiceBits es = [] := by
+ have hlt : slot.val < 2 ^ w := slot.isLt.trans_le (show 4 ≤ 2^w from by
+ have := Nat.pow_le_pow_right (by decide : 0 < 2) hw; norm_num at this; omega)
+ have hone : (1 : Word w) ≠ 0 := by
+ rw [ne_eq, Fin.ext_iff]
+ have h := Nat.one_lt_two_pow (by omega : w ≠ 0)
+ simp [Nat.mod_eq_of_lt h]
+ unfold sourceSite
+ cases hb : (m (m (pub 1).val + (state - pub 0)).val).val.testBit slot.val <;>
+ simp (config := { decide := true }) [checkPaddingCell, locateCell, fetch, trace, Op.effect,
+ Function.update, show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.sub.eval = (· - · : Word w → Word w → Word w) from rfl,
+ PrimedInputRAM.Opcodes.readBit_word (by omega : 0 < w), Nat.mod_eq_of_lt hlt,
+ hb, PrimedInputRAM.encodeBit, hone, countProbes, choiceBits]
+
+/-- For the real packed header at the computed site, the padding microcall
+has a successful native return exactly when the designated field bit is zero. -/
+theorem checkPaddingCell_native_iff (hw : 4 ≤ w) (slot : Fin 4) (pub : Fin 3 → Word w)
+ (state : Word w) (m : Memory w) (h : ProcessorInput.Header)
+ (hm : m (sourceSite pub state m).val = ProcessorInput.headerWord hw h) :
+ let machine := (template (checkPaddingCell slot) 7).instantiate w pub
+ (execute machine.program 15 (machine.program.start state) m []).isSome = true ↔ h slot = false := by
+ dsimp only
+ change (execute ((template (checkPaddingCell slot) 7).instantiate w pub).program
+ (1 + (checkPaddingCell slot).length) ⟨_,state,fun _ => 0,fun _ => 0⟩ m []).isSome = true ↔ _
+ rw [execute_template, run_eq_trace]
+ have ht := checkPaddingCell_trace hw slot pub state (fun _ => 0) m
+ have hbit : (m (sourceSite pub state m).val).val.testBit slot.val = h slot := by
+ rw [hm, show slot.val = (slot.castLE hw).val from rfl, testBit_wordBits, ProcessorInput.headerWord_bit]
+ rw [hbit] at ht
+ cases he : h slot with
+ | false =>
+ simp only [he, Bool.false_eq_true, ↓reduceIte] at ht
+ obtain ⟨es, rs, ht, _⟩ := ht
+ simp [ht]
+ | true =>
+ simp only [he, ↓reduceIte] at ht
+ simp [ht]
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderIndexInput.lean b/lean/OAI/Computability/VPVNP/LiveHeaderIndexInput.lean
new file mode 100644
index 0000000000..0cf10b0ac0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderIndexInput.lean
@@ -0,0 +1,161 @@
+import OAI.Computability.VPVNP.LiveHeaderRuns
+import OAI.Computability.VPVNP.GroupContraction
+
+/-!
+# Scanning the index in the physical live-group headers
+
+Group `g` in the contraction has one-based number `g.val + 1`. Its bits
+occupy slot zero of the first `h+2` processor headers. The native scan reads
+those packed words and writes only its designated scratch, leaving all four
+fields of every processor header available to the later phases.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ChainAssignments
+open scoped Fin.CommRing
+
+variable {w d a h Δ : ℕ}
+
+/-- Only the copy buffer and the two summary words can change. -/
+def IndexFrame (pub : Fin 3 → Word w) (len : ℕ) (before out : Memory w) : Prop :=
+ ∀ addr, (addr < (pub 0).val ∨ (pub 0).val + len ≤ addr) →
+ addr ≠ (pub 1).val → addr ≠ (pub 2).val → out addr = before addr
+
+private theorem index_scan_frame (hw : 4 ≤ w) (pub : Fin 3 → Word w) (len : ℕ) (m : Memory w)
+ (layout : ScanLayout pub len) :
+ let P := ((template indexCell 11).instantiate w pub).program
+ ∃ rs, runSegment P 22 (some 0) m (List.replicate len []) = some rs ∧
+ IndexFrame pub len m (after m (eventLog rs)) := by
+ obtain ⟨rs, hr, _, frame, _, _⟩ := run_cursor_segment
+ ((template indexCell 11).instantiate w pub).program 22 len 6
+ (fun _ mem => IndexFrame pub len m mem) m (fun _ _ _ _ => rfl) (by
+ intro j hj mem hframe
+ have hafter := layout.highAfter
+ have hfit := (pub 1).isLt
+ have hjv : (j : Word w).val = j := (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt (by omega))
+ have ha : (pub 0 + (j : Word w)).val = (pub 0).val + j := by
+ rw [Fin.val_add, hjv, Nat.mod_eq_of_lt (by omega)]
+ obtain ⟨es, rs', ht, hn, _, hp, _⟩ := indexCell_trace hw pub (j : Word w) (fun _ => 0) mem
+ refine ⟨es, ?_, ?_, hp.le⟩
+ · change execute ((template indexCell 11).instantiate w pub).program (1+indexCell.length)
+ ⟨_,(j : Word w),fun _ => 0,fun _ => 0⟩ mem [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [hn]
+ · rw [trace_after ht]
+ intro addr hout hhi hcount
+ simpa [indexUpdate, writeMemory, ha, hhi, hcount, show addr ≠ (pub 0).val + j by omega]
+ using hframe addr hout hhi hcount)
+ exact ⟨rs, hr, frame⟩
+
+/-- The original scan invariant and the full memory frame hold on the same
+deterministic segment. -/
+theorem index_scan_native_framed (hw : 4 ≤ w) (pub : Fin 3 → Word w) (index len : ℕ)
+ (m : Memory w) (layout : ScanLayout pub len) (init : ScanInv pub index len 0 m) :
+ let P := ((template indexCell 11).instantiate w pub).program
+ ∃ rs, runSegment P 22 (some 0) m (List.replicate len []) = some rs ∧
+ endState (some 0) rs = some (len : Word w) ∧ rs.length = len ∧
+ (∀ x ∈ rs, countProbes x.events ≤ 6) ∧ ScanInv pub index len len (after m (eventLog rs)) ∧
+ IndexFrame pub len m (after m (eventLog rs)) := by
+ obtain ⟨rs, hr, he, inv, hlen, hp⟩ := index_scan_native hw pub index len m layout init
+ obtain ⟨rs', hr', frame⟩ := index_scan_frame hw pub len m layout
+ have eq : rs = rs' := Option.some.inj (hr.symm.trans hr')
+ exact ⟨rs, hr, he, hlen, hp, inv, eq ▸ frame⟩
+
+private theorem group_fit (g : Fin (2^(h+1))) : g.val+1 < 2^(h+2) := by
+ have := g.isLt
+ have : 2^(h+2) = 2^(h+1) * 2 := pow_succ 2 (h+1)
+ omega
+
+/-- Slot zero of each occupied processor holds the corresponding bit of the
+one-based group number, including the highest bit of the last group. -/
+theorem physical_index_bit (advice : CutSchedule.Bits a) (cuts : AllCuts h Δ)
+ (g : Fin (2^(h+1))) (v : Fin (2^d)) (hv : v.val < h+2) :
+ physicalHeader advice cuts g v 0 = (g.val + 1).testBit v.val := by
+ let n : Word (h+2) := ⟨g.val+1, group_fit g⟩
+ change distributedBit (RAMSerialization.wordBits (h+2) n) v.val = _
+ rw [distributedBit, dite_eq_left hv]
+ exact (testBit_wordBits n ⟨v.val,hv⟩).symm
+
+/-- The actual memory installed for a live group in the contraction. -/
+abbrev physicalMemory (hw : 4 ≤ w) (advice : CutSchedule.Bits a) (cuts : AllCuts h Δ)
+ (g : Fin (2^(h+1))) : Memory w :=
+ RAMMemory.initialMemory (2^d) (liveHeader (d := d) hw advice cuts g)
+
+/-- Readback of all four physical header bits as their original packed word. -/
+theorem physicalMemory_word (hw : 4 ≤ w) (advice : CutSchedule.Bits a) (cuts : AllCuts h Δ)
+ (g : Fin (2^(h+1))) (v : Fin (2^d)) :
+ physicalMemory (d := d) hw advice cuts g v.val = ProcessorInput.headerWord hw (physicalHeader advice cuts g v) := by
+ simp [physicalMemory, RAMMemory.initialMemory, liveHeader, v.isLt]
+
+/-- Exact summaries and bit arrays available to the live program after the
+scan. All later reads of the site headers see the prescribed physical words. -/
+structure PhysicalIndex (hw : 4 ≤ w) (pub : Fin 3 → Word w) (advice : CutSchedule.Bits a)
+ (cuts : AllCuts h Δ) (g : Fin (2^(h+1))) (out : Memory w) : Prop where
+ copied : ∀ j < h+2, out ((pub 0).val+j) = PrimedInputRAM.encodeBit w ((g.val+1).testBit j)
+ high : (out (pub 1).val).val = Nat.log 2 (g.val+1)
+ count : (out (pub 2).val).val = (prefixOnes (g.val+1) (h+2)).card
+ low : out (pub 0).val = PrimedInputRAM.encodeBit w ((g.val+1).testBit 0)
+ first : (out (pub 1).val).val = 0 ↔ g.val = 0
+ singleton : (out (pub 2).val).val = 1 ↔ g.val+1 = 2^(Nat.log 2 (g.val+1))
+ headers : ∀ v : Fin (2^d), out v.val = ProcessorInput.headerWord hw (physicalHeader advice cuts g v)
+ frame : IndexFrame pub (h+2) (physicalMemory (d := d) hw advice cuts g) out
+
+/-- Run the index scan starting at the actual header memory of the group,
+with its two scalar scratch cells initially zero by RAM initialization. -/
+theorem physical_index_scan_native (hw : 4 ≤ w) (pub : Fin 3 → Word w) (advice : CutSchedule.Bits a)
+ (cuts : AllCuts h Δ) (g : Fin (2^(h+1))) (sites : h+2 ≤ 2^d) (scratch : 2^d ≤ (pub 0).val)
+ (layout : ScanLayout pub (h+2)) :
+ let P := ((template indexCell 11).instantiate w pub).program
+ let m := physicalMemory (d := d) hw advice cuts g
+ ∃ rs, runSegment P 22 (some 0) m (List.replicate (h+2) []) = some rs ∧
+ endState (some 0) rs = some ((h+2 : ℕ) : Word w) ∧ rs.length = h+2 ∧
+ (∀ x ∈ rs, countProbes x.events ≤ 6) ∧
+ PhysicalIndex (d := d) hw pub advice cuts g (after m (eventLog rs)) := by
+ let m := physicalMemory (d := d) hw advice cuts g
+ have hafter := layout.highAfter
+ have hcafter := layout.countAfter
+ have hmod := (pub 2).isLt
+ have hinit : ScanInv pub (g.val+1) (h+2) 0 m := by
+ constructor
+ · intro j hj
+ let v : Fin (2^d) := ⟨j, hj.trans_le sites⟩
+ change (physicalMemory (d := d) hw advice cuts g v.val).val.testBit (0 : Fin 4).val = _
+ rw [physicalMemory_word]
+ change (ProcessorInput.headerWord hw (physicalHeader advice cuts g v)).val.testBit
+ ((0 : Fin 4).castLE hw).val = _
+ rw [testBit_wordBits, ProcessorInput.headerWord_bit]
+ exact physical_index_bit advice cuts g v hj
+ · simp [m, physicalMemory, RAMMemory.initialMemory, show ¬(pub 1).val < 2^d by omega,
+ prefixHigh, prefixOnes]
+ · simp [m, physicalMemory, RAMMemory.initialMemory, show ¬(pub 2).val < 2^d by omega,
+ prefixOnes]
+ · omega
+ obtain ⟨rs, run, last, len, hp, inv, frame⟩ := index_scan_native_framed hw pub _ _ m layout hinit
+ have hfit := group_fit g
+ have ⟨hhigh, hone⟩ := summary_correct (by omega : g.val+1 ≠ 0) hfit
+ have hlog : Nat.log 2 (g.val+1) < h+2 := (Nat.log_lt_iff_lt_pow (by decide) (by omega)).mpr hfit
+ have hcount : (prefixOnes (g.val+1) (h+2)).card ≤ h+2 := by
+ simpa [prefixOnes] using Finset.card_filter_le (Finset.range (h+2)) (fun j => (g.val+1).testBit j)
+ have high : ((after m (eventLog rs)) (pub 1).val).val = Nat.log 2 (g.val+1) := by
+ rw [inv.high, hhigh, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ have count : ((after m (eventLog rs)) (pub 2).val).val = (prefixOnes (g.val+1) (h+2)).card := by
+ rw [inv.count, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ refine ⟨rs, run, last, len, hp, inv.copied, high, count, ?_, ?_, count ▸ hone, ?_, frame⟩
+ · simpa using inv.copied 0 (by omega)
+ · rw [high, Nat.log_eq_zero_iff]
+ omega
+ · intro v
+ have hv := v.isLt
+ rw [frame v.val (Or.inl (hv.trans_le scratch)) (by omega) (by omega)]
+ exact physicalMemory_word hw advice cuts g v
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderIndexStages.lean b/lean/OAI/Computability/VPVNP/LiveHeaderIndexStages.lean
new file mode 100644
index 0000000000..4ce25f14cf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderIndexStages.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.LiveHeaderIndexInput
+import OAI.Computability.VPVNP.LiveHeaderProtectedCore
+import OAI.Computability.VPVNP.LiveHeaderCursorFrame
+
+/-!
+# The initial index stage of the physical live-header program
+
+The public row supplies the index array, its two summary cells and the scan
+length. The actual distributed headers supply the one-based group number.
+The closing call accepts and hands its memory to the advice stage.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ChainAssignments LiveHeaderSchedule LiveHeader
+open scoped Fin.CommRing
+
+variable {w d : ℕ}
+
+/-- The burst table for copying one distributed group-index bit and updating its summary. -/
+abbrev indexTable := template indexCell 11
+
+/-- The index worker's three public addresses for the unpacked digits, highest set position,
+and population count. -/
+def indexWords (w : ℕ) (s : Sizes) (base : ℕ) : Fin 3 → Word w :=
+ ![Fin.ofNat _ (indexBase base), Fin.ofNat _ (highAddr s base), Fin.ofNat _ (populationAddr s base)]
+
+theorem index_row (w : ℕ) (s : Sizes) (base : ℕ) :
+ rowData w s base .index ∘ includeFin (by decide : 3+1 ≤ 17) =
+ LiveHeaderBounded.publicData (indexWords w s base) (Fin.ofNat _ (s.h+2)) := by
+ funext j
+ fin_cases j <;> rfl
+
+/-- Every successful index-cell call increments the cursor and leaves the
+tag unchanged in its real external memory. -/
+theorem index_step (hw : 4 ≤ w) (pub : Fin 3 → Word w) (bound : ℕ) (addr : Word w)
+ (ha : (pub 0).val + bound ≤ (pub 1).val) (hb : (pub 1).val < (pub 2).val) (htag : addr.val < (pub 0).val)
+ (i : ℕ) (hi : i < bound) (m : Memory w) (bits : List Bool) (rep : Report w) {fuel : ℕ}
+ (h : execute (indexTable.instantiate w pub).program fuel
+ ((indexTable.instantiate w pub).program.start (i : Word w)) m bits = some rep) :
+ rep.result = some ((i+1 : ℕ) : Word w) ∧ after m rep.events addr.val = m addr.val := by
+ obtain ⟨es, rs', ht, hresult, _, _, _⟩ := indexCell_trace hw pub (i : Word w) (fun _ => 0) m
+ have he : execute (indexTable.instantiate w pub).program 22
+ ((indexTable.instantiate w pub).program.start (i : Word w)) m [] = some ⟨es, some ((i+1 : ℕ) : Word w)⟩ := by
+ change execute ((template indexCell 11).instantiate w pub).program (1+indexCell.length) ⟨_,(i : Word w),fun _ => 0,fun _ => 0⟩ _ [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [hresult]
+ obtain ⟨_, rfl⟩ := execute_empty_forces_anyFuel he h
+ refine ⟨rfl, ?_⟩
+ change after m es addr.val = m addr.val
+ rw [trace_after ht]
+ have hc := (pub 2).isLt
+ have hiv : (i : Word w).val = i := Fin.val_cast_of_lt (by omega)
+ have hd : (pub 0 + (i : Word w)).val = (pub 0).val+i := by
+ rw [Fin.val_add, hiv, Nat.mod_eq_of_lt (by omega)]
+ simp [indexUpdate,writeMemory,hd,show addr.val ≠ (pub 2).val by omega,
+ show addr.val ≠ (pub 1).val by omega,show addr.val ≠ (pub 0).val+i by omega]
+
+/-- The concrete widened index component reads all occupied processor words,
+accepts at its capacity, and installs the high bit, population and copied
+digits with the prescribed call and probe bounds. -/
+theorem index_stage_native (s : Sizes) (base : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (sites : s.h+2 ≤ 2^d)
+ (scratch : 2^d ≤ base) (fit : limit s base ≤ 2^w) :
+ let pub := indexWords w s base
+ let m := physicalMemory (d := d) hw advice cuts g
+ let P := ((stageTemplate .index).2.instantiate w (rowData w s base .index)).program
+ ∃ rs, runSegment P 25 (some 0) m (List.replicate (calls s .index) []) = some rs ∧
+ endState (some 0) rs = none ∧ rs.length = calls s .index ∧
+ (∀ rep ∈ rs, rep.probes ≤ probes .index) ∧
+ LiveStageLink.PreservesTagOnReturns (Fin.ofNat _ base) m rs ∧
+ PhysicalIndex (d := d) hw pub advice cuts g (after m (eventLog rs)) := by
+ let pub := indexWords w s base
+ let m := physicalMemory (d := d) hw advice cuts g
+ let addr : Word w := Fin.ofNat _ base
+ rw [limit_eq] at fit
+ have va : (pub 0).val = indexBase base := by
+ change (indexBase base) % (2^w) = _
+ exact Nat.mod_eq_of_lt (by unfold indexBase; omega)
+ have vh : (pub 1).val = highAddr s base := by
+ change (highAddr s base) % (2^w) = _
+ exact Nat.mod_eq_of_lt (by unfold highAddr indexBase; omega)
+ have vc : (pub 2).val = populationAddr s base := by
+ change (populationAddr s base) % (2^w) = _
+ exact Nat.mod_eq_of_lt (by unfold populationAddr highAddr indexBase; omega)
+ have vtag : addr.val = base := Nat.mod_eq_of_lt (by omega)
+ have htag : addr.val < (pub 0).val := by rw [vtag, va]; unfold indexBase; omega
+ have hcap : ((s.h+2 : ℕ) : Word w).val = s.h+2 := Fin.val_cast_of_lt (by omega)
+ have hscratch : 2^d ≤ (pub 0).val := by rw [va]; unfold indexBase; omega
+ have layout : ScanLayout pub (s.h+2) := ⟨sites.trans hscratch, by rw [vh,va]; rfl, by rw [vc,vh]; exact Nat.lt_succ_self _⟩
+ obtain ⟨raw, hrun, _, hlen, hprobes, hindex⟩ :=
+ physical_index_scan_native hw pub advice cuts g sites hscratch layout
+ have hframe : LiveStageLink.PreservesTagOnReturns addr m raw :=
+ runSegment_cursor_frame (indexTable.instantiate w pub).program 22 (s.h+2) addr
+ (fun i hi mem rep he => index_step hw pub _ addr layout.highAfter layout.countAfter htag i hi mem [] rep he)
+ 0 (s.h+2) m raw (by omega) hrun
+ let outs := raw.map LiveHeaderBounded.activeReport ++ [LiveHeaderBounded.closedReport w]
+ have hcomplete := LiveHeaderBounded.runSegment_cursor_complete indexTable pub ((s.h+2 : ℕ) : Word w)
+ (by decide : 0 < 22) 0 m (List.replicate (s.h+2) []) raw (by rw [List.length_replicate, Nat.zero_add, hcap]) hrun
+ (fun i hi mem bits rep he => (index_step hw pub _ addr layout.highAfter layout.countAfter htag i (by rwa [hcap] at hi) mem bits rep he).1)
+ refine ⟨outs, ?_, ?_, ?_, ?_, guarded_frame hframe, ?_⟩
+ · change runSegment ((entry (LiveHeaderBounded.bounded indexTable)).2.instantiate w (rowData w s base .index)).program
+ 25 (some 0) m (List.replicate (s.h+2+1) []) = some outs
+ rw [run_entry, index_row, List.replicate_succ']
+ exact hcomplete
+ · rw [show outs = raw.map LiveHeaderBounded.activeReport ++ [LiveHeaderBounded.closedReport w] from rfl, endState_append]
+ rfl
+ · simp [outs,hlen,calls]
+ · intro rep hm
+ rcases List.mem_append.mp hm with h | h
+ · obtain ⟨x, hx, rfl⟩ := List.mem_map.mp h
+ exact hprobes x hx
+ · obtain rfl := List.mem_singleton.mp h
+ exact Nat.zero_le _
+ · have hlast : after m (eventLog outs) = after m (eventLog (raw.map LiveHeaderBounded.activeReport)) := by
+ simp only [outs, eventLog, List.flatMap_append, after, List.foldl_append, List.flatMap_singleton]
+ rfl
+ rw [hlast, LiveHeaderBounded.after_activeReports]
+ exact hindex
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderMetadata.lean b/lean/OAI/Computability/VPVNP/LiveHeaderMetadata.lean
new file mode 100644
index 0000000000..1be7cf0cd8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderMetadata.lean
@@ -0,0 +1,178 @@
+import OAI.Computability.VPVNP.LiveHeaderSingleRun
+import OAI.Computability.VPVNP.LiveHeaderProgramFit
+
+/-!
+# Running all width, phase, and mode stages consecutively
+
+The eleven scalar stages fill consecutive scratch words. A frame outside the
+written prefix transports the scan summary, advice and original packed sites
+across the real linker handoffs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.Metadata
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderWidths LiveHeaderDescriptors
+open PrimedInputRAM
+
+variable {w : ℕ}
+
+/-- A scalar metadata item produced by the live header, covering five cut widths, four phase
+flags, the first-tail flag, and mode. -/
+inductive Field where
+ | width (s : Slot) | flag (f : Flag) | firstTail | mode
+
+/-- The header stage that computes the selected scalar metadata item. -/
+def Field.stage : Field → Stage
+ | .width s => .width s | .flag f => .flag f | .firstTail => .firstTail | .mode => .mode
+
+/-- The physical scratch address at which the selected scalar metadata item is stored. -/
+def Field.address (base : ℕ) : Field → ℕ
+ | .width s => widthAddr base s | .flag f => flagAddr base f
+ | .firstTail => firstTailAddr base | .mode => tagAddr base
+
+/-- The order of the eleven scalar metadata calls, beginning with cut widths and ending with
+the mode. -/
+def order : Fin 11 → Field :=
+ ![.width .liveLeft,.width .liveRight,.width .primedLeft,.width .primedMiddle,.width .primedRight,
+ .flag .first,.flag .middle,.flag .firstHalf,.flag .last,.firstTail,.mode]
+
+/-- Convert a metadata position to its header stage number, with position eleven denoting the
+following stage. -/
+def stageId (j : ℕ) (hj : j ≤ 11) : StageId := ⟨j+2,by rw [stage_count]; omega⟩
+
+theorem stage_at (j : Fin 11) : stage (stageId j.val j.isLt.le) = (order j).stage := by
+ fin_cases j <;> rfl
+
+theorem next_at (j : Fin 11) : next (stageId j.val j.isLt.le) = some (stageId (j.val+1) j.isLt) := by
+ unfold next
+ split
+ · rfl
+ · rename_i hh
+ change ¬ j.val+2+1 < stages.length at hh
+ rw [stage_count] at hh
+ have := j.isLt
+ omega
+
+private theorem address_at (base : ℕ) (j : Fin 11) : (order j).address base = base+1+j.val := by
+ fin_cases j <;> rfl
+
+/-- The stored word has the scheduled width when needed, the encoded truth value for a flag, or
+the selected mode code. -/
+def Correct (s : Sizes) (i : ℕ) (tag : LiveHeader.Mode.Tag) : Field → Word w → Prop
+ | .width slot,v => Needed s.h i slot → v.val = CutSchedule.width (s.h+1) s.delta (index i slot)
+ | .flag f,v => v = encodeBit w (decide (f.holds s.h i))
+ | .firstTail,v => v = encodeBit w (decide (i=2^s.h+1))
+ | .mode,v => v = Fin.ofNat _ tag.code.val
+
+/-- Completed fields have their mathematical values. Later cells and packed
+processor sites still have their values at entry to the width stage. -/
+structure Image (s : Sizes) (base i : ℕ) (tag : LiveHeader.Mode.Tag) (original m : Memory w) (done : ℕ) : Prop where
+ readback : ∀ j : Fin 11, j.val < done → Correct s i tag (order j) (m (base+1+j.val))
+ frame : ∀ a, a < base ∨ base+done < a → m a = original a
+
+theorem Image.summary {s : Sizes} {base i : ℕ} {tag : LiveHeader.Mode.Tag} {original m : Memory w}
+ {done : ℕ} (img : Image s base i tag original m done) (hdone : done ≤ 11)
+ (h : Summary s base i original) : Summary s base i m := by
+ have hhigh := img.frame (highAddr s base) (Or.inr (by dsimp [highAddr,indexBase]; omega))
+ have hpop := img.frame (populationAddr s base) (Or.inr (by dsimp [populationAddr,highAddr,indexBase]; omega))
+ have hlow := img.frame (indexBase base) (Or.inr (by dsimp [indexBase]; omega))
+ exact ⟨hhigh ▸ h.high,hpop ▸ h.count,h.singleton,hlow ▸ h.low⟩
+
+private theorem mode_last (j : Fin 11) (h : order j = .mode) : j = 10 := by
+ fin_cases j <;> first | exact rfl | contradiction
+
+private theorem step (s : Sizes) (base d : ℕ) {hw : 4 ≤ w} (advice : CutSchedule.Bits s.advice)
+ (cuts : ChainAssignments.AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : LiveHeader.Mode.Tag)
+ (fit : ScalarFit w s base) (hsites : 2^d ≤ base) (original m : Memory w)
+ (headers : LiveHeader.SiteHeaders d hw advice cuts g original) (sum : Summary s base (g.val+1) original)
+ (j : Fin 11) (img : Image s base (g.val+1) tag original m j.val)
+ (selected : order j = .mode → LiveHeader.physicalTag cuts g = some tag) :
+ ∃ v : Word w, SingleRun s base (order j).stage m (writeMemory m (Fin.ofNat _ ((order j).address base)) v) ∧
+ Correct s (g.val+1) tag (order j) v := by
+ have summary := img.summary j.isLt.le sum
+ have hg : g.val+1 ≤ 2^(s.h+1) := g.isLt
+ cases he : order j with
+ | width slot => exact width_run s base (g.val+1) slot m fit (by omega) hg summary
+ | flag f => exact ⟨_,flag_run s base (g.val+1) f m fit (by omega) hg summary,rfl⟩
+ | firstTail => exact ⟨_,firstTail_run (by omega) s base (g.val+1) m fit (by omega) hg summary,rfl⟩
+ | mode =>
+ have hj := mode_last j he
+ have hv : j.val = 10 := by rw [hj]; rfl
+ have left := img.readback 0 (by rw [hv]; decide)
+ have right := img.readback 1 (by rw [hv]; decide)
+ have firstHalf := img.readback 7 (by rw [hv]; decide)
+ have hl := left (Or.inr (Or.inl rfl))
+ have hr := right (Or.inr (Or.inr rfl))
+ have cur : LiveHeader.SiteHeaders d hw advice cuts g m :=
+ fun v => (img.frame v.val (Or.inl (v.isLt.trans_le hsites))).trans (headers v)
+ refine ⟨_,mode_run s base d advice cuts g m fit cur ?_ ?_ firstHalf tag (selected he),rfl⟩
+ · change (m (base+1)).val = CutSchedule.width (s.h+1) s.delta g.val
+ change (m (base+1)).val = CutSchedule.width (s.h+1) s.delta (g.val+1-1) at hl
+ simpa using hl
+ · exact hr
+
+private theorem extend (s : Sizes) (base i : ℕ) (tag : LiveHeader.Mode.Tag)
+ (fit : ScalarFit w s base) {original m : Memory w} {j : Fin 11} (img : Image s base i tag original m j.val)
+ {v : Word w} (hc : Correct s i tag (order j) v) :
+ Image s base i tag original
+ (LiveStageLink.transferMemory (Fin.ofNat _ base) (next (stageId j.val j.isLt.le))
+ (writeMemory m (Fin.ofNat _ ((order j).address base)) v)) (j.val+1) := by
+ have h := fit.address
+ rw [limit_eq] at h
+ have hj := j.isLt
+ have hb : (Fin.ofNat (2^w) base).val = base := Nat.mod_eq_of_lt (by omega)
+ have ha : (Fin.ofNat (2^w) ((order j).address base)).val = base+1+j.val := by
+ rw [address_at,Fin.val_ofNat,Nat.mod_eq_of_lt (by omega)]
+ rw [next_at]
+ constructor
+ · intro k hk
+ simp only [LiveStageLink.transferMemory,writeMemory,hb,ha,show base+1+k.val ≠ base by omega,↓reduceIte]
+ by_cases he : k = j
+ · subst k; simpa using hc
+ · have hv : k.val ≠ j.val := fun e => he (Fin.ext e)
+ simpa [hv] using img.readback k (by omega)
+ · intro a ha'
+ have hn : a ≠ base := by omega
+ have hn' : a ≠ base+1+j.val := by omega
+ simpa only [LiveStageLink.transferMemory,writeMemory,hb,ha,hn,hn',↓reduceIte] using img.frame a (by omega)
+
+/-- Execute any prefix of the eleven scalar stages. The first ten can run
+before the two mode bits are known to be compatible. -/
+theorem run_prefix (s : Sizes) (base d : ℕ) {hw : 4 ≤ w} (advice : CutSchedule.Bits s.advice)
+ (cuts : ChainAssignments.AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : LiveHeader.Mode.Tag)
+ (fit : ScalarFit w s base) (hsites : 2^d ≤ base) (m : Memory w)
+ (headers : LiveHeader.SiteHeaders d hw advice cuts g m) (sum : Summary s base (g.val+1) m)
+ (done : ℕ) (hdone : done ≤ 11) (modeOK : done = 11 → LiveHeader.physicalTag cuts g = some tag) :
+ ∃ xs out, StagePrefix s base (some (stageId 0 (by decide))) m xs (some (stageId done hdone)) out ∧
+ (∀ x ∈ xs, x.Good s) ∧ Image s base (g.val+1) tag m out done := by
+ induction done with
+ | zero => exact ⟨[],m,.nil ..,by simp,⟨by simp, fun _ _ => rfl⟩⟩
+ | succ n ih =>
+ have hn : n < 11 := by omega
+ let j : Fin 11 := ⟨n,hn⟩
+ obtain ⟨xs,cur,old,good,img⟩ := ih hn.le (by omega)
+ have sel : order j = .mode → LiveHeader.physicalTag cuts g = some tag := by
+ intro h
+ have hj := congrArg Fin.val (mode_last j h)
+ change n = 10 at hj
+ apply modeOK (by omega)
+ obtain ⟨v,run,hv⟩ := step s base d advice cuts g tag fit hsites m cur headers sum j img sel
+ have one : calls s (order j).stage = 1 := by cases order j <;> rfl
+ obtain ⟨x,_,hgood,seg⟩ := run.prefix (stageId n hn.le) (stage_at j) one
+ have image := extend s base (g.val+1) tag fit img hv
+ rw [next_at j] at seg image
+ refine ⟨xs++[x],_,old.append seg,?_,image⟩
+ intro y hy
+ rcases List.mem_append.mp hy with h | h
+ · exact good y h
+ · exact (List.mem_singleton.mp h) ▸ hgood
+
+end LiveHeaderProgram.Metadata
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderMode.lean b/lean/OAI/Computability/VPVNP/LiveHeaderMode.lean
new file mode 100644
index 0000000000..039228c064
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderMode.lean
@@ -0,0 +1,258 @@
+import OAI.Computability.VPVNP.LiveHeaderBits
+import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete
+
+/-!
+# The native live-mode dispatch of Section 14.1
+
+Processor zero supplies the mode at each nonempty incident cut in header
+slots 2 and 3. A boundary group reads its one incident mode. An interior
+group rejects unequal modes. The result tag selects the unit check, the
+primed pair, or the evaluator tail.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+namespace Mode
+
+/-- The three live continuations selected by cut-mode agreement and group phase. -/
+inductive Tag | unit | pair | tail deriving DecidableEq
+
+/-- Encode the unit, pair, and evaluator-tail continuations as machine tags zero, one, and two. -/
+def Tag.code : Tag → Word 2
+ | .unit => 0
+ | .pair => 1
+ | .tail => 2
+
+/-- Choose unit mode for a cleared mode bit, otherwise select pair or evaluator tail according
+to the group half. -/
+def selectTag (mode first : Bool) : Tag :=
+ if mode then (if first then .pair else .tail) else .unit
+
+/-- Both-empty is outside the chain domain and is rejected. -/
+def selected (left right : ℕ) (incoming outgoing first : Bool) : Option Tag :=
+ if left = 0 then
+ if right = 0 then none else some (selectTag outgoing first)
+ else if right = 0 ∨ incoming = outgoing then some (selectTag incoming first) else none
+
+private abbrev Code := Flow 48 16
+
+/-- Public words 0 through 3 give the scratch addresses of the left and
+right lengths, first-half flag and output tag. The packed site header is at
+address zero. Registers 10 and 11 receive its two mode bits. -/
+private def prepare : Code := Opcodes.sequence (Opcodes.set 0 0)
+ [Opcodes.set 1 1, Opcodes.set 2 2, Opcodes.set 3 3,
+ Opcodes.load 4 0, Opcodes.read 5 4, Opcodes.load 4 1, Opcodes.read 6 4,
+ Opcodes.load 4 2, Opcodes.read 7 4, Opcodes.load 8 3, Opcodes.read 9 0,
+ Opcodes.bin .shiftRight 10 9 2, Opcodes.bin .bitAnd 10 10 1,
+ Opcodes.bin .shiftRight 11 9 3, Opcodes.bin .bitAnd 11 11 1]
+
+/-- Select a mode in register 12, checking nonemptiness and agreement. -/
+private def chooseMode : Code :=
+ .ifEq 5 0
+ (.seq (.line (.guardLt 0 6)) (.line (.copy 12 11)))
+ (.ifEq 6 0 (.line (.copy 12 10)) (.seq (.line (.guardEq 10 11)) (.line (.copy 12 10))))
+
+/-- The chosen tag goes into register 13 and the designated scratch word. -/
+private def emitTag : Code := .seq
+ (.ifEq 12 0 (Opcodes.set 13 0) (.ifEq 7 0 (Opcodes.set 13 2) (Opcodes.set 13 1)))
+ (Opcodes.write 8 13)
+
+/-- The native routine that checks the applicable incident mode bits and publishes the
+resulting continuation tag. -/
+def program : Flow 48 16 := .seq prepare (.seq chooseMode emitTag)
+
+/-- The instruction list and register count are independent of the chain length. -/
+theorem program_length : program.length = 29 := by decide
+
+private def simple {r k : ℕ} : Flow r k → Prop
+ | .line _ => True
+ | .seq a b | .ifEq _ _ a b | .ifLt _ _ a b => simple a ∧ simple b
+ | .branch .. | .whileLt .. => False
+
+/-- A successful derivation of a deterministic acyclic block must be the
+one computed by the straight-line interpreter. -/
+private theorem once_of_exec {w r k : ℕ} {pub : Fin k → Word w} {state : Word w} {a : Flow r k}
+ {rs rs' : Regs w r} {m m' : Memory w} {es : List (Event w)}
+ (h : Flow.Exec pub state a rs m es rs' m') (hs : simple a) :
+ Flow.once pub state false a rs m = some (es, rs', m') := by
+ induction h with
+ | line he => simp [Flow.once, he]
+ | seq h₁ h₂ ih₁ ih₂ => simp [Flow.once, ih₁ hs.1, ih₂ hs.2]
+ | ifEqYes ht hb ih | ifLtYes ht hb ih => simp [Flow.once, ht, ih hs.1]; rfl
+ | ifEqNo ht hb ih | ifLtNo ht hb ih => simp [Flow.once, ht, ih hs.2]; rfl
+ | branchYes | branchNo | whileDone | whileStep => contradiction
+
+private theorem program_simple : simple program := by
+ simp [program, prepare, chooseMode, emitTag, Opcodes.sequence, Opcodes.set, Opcodes.load, Opcodes.read,
+ Opcodes.write, Opcodes.line, Opcodes.bin, simple]
+
+variable {w : ℕ} (pub : Fin 16 → Word w) (state : Word w) (rs : Regs w 48) (m : Memory w)
+
+private def before (h : Word w) : List (Event w) :=
+ [.tick, .tick, .tick, .tick, .tick, .read (pub 0) (m (pub 0).val), .tick,
+ .read (pub 1) (m (pub 1).val), .tick, .read (pub 2) (m (pub 2).val), .tick, .read 0 h,
+ .tick, .tick, .tick, .tick]
+
+private def prepared (h l r : Word w) : Regs w 48 := by
+ let a := Function.update (Function.update (Function.update (Function.update rs (0 : Fin 48) 0) 1 1) 2 2) 3 3
+ let b := Function.update (Function.update a (4 : Fin 48) (pub 0)) 5 (m (pub 0).val)
+ let c := Function.update (Function.update b (4 : Fin 48) (pub 1)) 6 (m (pub 1).val)
+ let d := Function.update (Function.update c (4 : Fin 48) (pub 2)) 7 (m (pub 2).val)
+ exact Function.update (Function.update (Function.update (Function.update d (8 : Fin 48) (pub 3)) 9 h) 10 l) 11 r
+
+set_option maxHeartbeats 2000000 in
+private theorem once_prepare (hw : 4 ≤ w) (header : ProcessorInput.Header)
+ (hh : m 0 = ProcessorInput.headerWord hw header) :
+ Flow.once pub state false prepare rs m = some (before pub m (ProcessorInput.headerWord hw header),
+ prepared pub rs m (ProcessorInput.headerWord hw header)
+ (encodeBit w (header 2)) (encodeBit w (header 3)), m) := by
+ have h₂ := extract_packed_bit hw header (2 : Fin 4)
+ have h₃ := extract_packed_bit hw header (3 : Fin 4)
+ change BinaryOp.bitAnd.eval (BinaryOp.shiftRight.eval _ 2) 1 = _ at h₂
+ change BinaryOp.bitAnd.eval (BinaryOp.shiftRight.eval _ 3) 1 = _ at h₃
+ simp (config := { decide := true }) [prepare, Opcodes.sequence, Opcodes.set, Opcodes.load,
+ Opcodes.bin, Opcodes.read, Opcodes.line, Flow.once, Op.effect, Function.update, before, hh, h₂, h₃]
+ rfl
+
+private def activeBit (left right : ℕ) (incoming outgoing : Bool) : Option Bool :=
+ if left = 0 then (if right = 0 then none else some outgoing)
+ else if right = 0 ∨ incoming = outgoing then some incoming else none
+
+private def chooseTicks (left right : ℕ) : ℕ := if left = 0 ∨ right = 0 then 3 else 4
+
+private theorem choose_once (hw : 4 ≤ w) (left right : Word w) (incoming outgoing : Bool)
+ (h0 : rs 0 = 0) (h5 : rs 5 = left) (h6 : rs 6 = right)
+ (h10 : rs 10 = encodeBit w incoming) (h11 : rs 11 = encodeBit w outgoing) :
+ Flow.once pub state false chooseMode rs m = (activeBit left.val right.val incoming outgoing).map
+ (fun b => (List.replicate (chooseTicks left.val right.val) .tick, Function.update rs 12 (encodeBit w b), m)) := by
+ have hone : (1 : Word w) ≠ 0 := by
+ intro he
+ have hv := congrArg Fin.val he
+ simp [Nat.mod_eq_of_lt (Nat.one_lt_two_pow (show w ≠ 0 by omega))] at hv
+ cases incoming <;> cases outgoing <;> by_cases hl : left = 0 <;> by_cases hr : right = 0 <;>
+ simp (config := { decide := true }) [chooseMode, Flow.once, Op.effect, h0, h5, h6, h10, h11,
+ activeBit, chooseTicks, Fin.pos_iff_ne_zero', Fin.val_eq_zero_iff, hl, hr, encodeBit, hone, Ne.symm hone]
+ all_goals rfl
+
+private theorem emit_once (hw : 4 ≤ w) (mode first : Bool) (h0 : rs 0 = 0)
+ (h7 : rs 7 = encodeBit w first) (h12 : rs 12 = encodeBit w mode) :
+ let value := Fin.ofNat (2 ^ w) (selectTag mode first).code.val
+ Flow.once pub state false emitTag rs m =
+ some (List.replicate (if mode then 3 else 2) .tick ++ [.write (rs 8) value],
+ Function.update rs 13 value, writeMemory m (rs 8) value) := by
+ have hone : (1 : Word w) ≠ 0 := by
+ intro he
+ have hv := congrArg Fin.val he
+ simp [Nat.mod_eq_of_lt (Nat.one_lt_two_pow (show w ≠ 0 by omega))] at hv
+ cases mode <;> cases first <;>
+ simp (config := { decide := true }) [emitTag, Flow.once, Opcodes.set, Opcodes.write, Opcodes.line,
+ Op.effect, selectTag, Tag.code, h0, h7, h12, encodeBit, hone]
+ all_goals exact ⟨rfl, rfl, rfl⟩
+
+/-- The trace has four reads, one tag write, and no nondeterministic choices.
+Its length is at most 24, including both comparison tests at an interior cut. -/
+private def events (header : Word w) (left right : ℕ) (mode : Bool) (value : Word w) :=
+ before pub m header ++ (List.replicate (chooseTicks left right) .tick ++
+ (List.replicate (if mode then 3 else 2) .tick ++ [.write (pub 3) value]))
+
+private theorem once_program (hw : 4 ≤ w) (header : ProcessorInput.Header) (first : Bool)
+ (hh : m 0 = ProcessorInput.headerWord hw header) (hf : m (pub 2).val = encodeBit w first) :
+ let l := m (pub 0).val
+ let r := m (pub 1).val
+ let R := prepared pub rs m (ProcessorInput.headerWord hw header) (encodeBit w (header 2)) (encodeBit w (header 3))
+ Flow.once pub state false program rs m = (activeBit l.val r.val (header 2) (header 3)).map
+ (fun b =>
+ let v := Fin.ofNat (2 ^ w) (selectTag b first).code.val
+ (events pub m (ProcessorInput.headerWord hw header) l.val r.val b v,
+ Function.update (Function.update R 12 (encodeBit w b)) 13 v, writeMemory m (pub 3) v)) := by
+ intro l r R
+ have hc := choose_once pub state R m hw l r (header 2) (header 3) rfl rfl rfl rfl rfl
+ simp only [program, Flow.once, once_prepare pub state rs m hw header hh]
+ change (do
+ let (eb,rb,mb) ← (do
+ let (ec,rc,mc) ← Flow.once pub state false chooseMode R m
+ let (ed,rd,md) ← Flow.once pub state false emitTag rc mc
+ pure (ec ++ ed,rd,md))
+ pure (before pub m (ProcessorInput.headerWord hw header) ++ eb,rb,mb)) = _
+ rw [hc]
+ cases he : activeBit l.val r.val (header 2) (header 3) with
+ | none => rfl
+ | some b =>
+ simp only [Option.map_some, bind, Option.bind_some]
+ have hu : (Function.update R (12 : Fin 48) (encodeBit w b)) 7 = encodeBit w first := hf
+ rw [emit_once pub state _ m hw b first rfl hu (Function.update_self ..)]
+ rfl
+
+private theorem selected_eq_map (l r : ℕ) (a b first : Bool) :
+ selected l r a b first = (activeBit l r a b).map (fun bit => selectTag bit first) := by
+ simp only [selected, activeBit]
+ split_ifs <;> rfl
+
+private theorem events_bounds (h : Word w) (l r : ℕ) (b : Bool) (v : Word w) :
+ (events pub m h l r b v).length ≤ 24 ∧ countProbes (events pub m h l r b v) = 5 ∧
+ choiceBits (events pub m h l r b v) = [] ∧ after m (events pub m h l r b v) = writeMemory m (pub 3) v := by
+ cases b <;> by_cases hz : l = 0 ∨ r = 0 <;>
+ simp [events, before, chooseTicks, hz, countProbes, choiceBits, after, update]
+
+/-- The executable mode block reads the packed word and dispatches to its
+unique tag in at most 24 events and exactly five probes. -/
+theorem exec_selected (hw : 4 ≤ w) (header : ProcessorInput.Header) (first : Bool) (tag : Tag)
+ (hh : m 0 = ProcessorInput.headerWord hw header) (hf : m (pub 2).val = encodeBit w first)
+ (hsel : selected (m (pub 0).val).val (m (pub 1).val).val (header 2) (header 3) first = some tag) :
+ let v := Fin.ofNat (2 ^ w) tag.code.val
+ ∃ es rs', Flow.Exec pub state program rs m es rs' (writeMemory m (pub 3) v) ∧ rs' 13 = v ∧
+ es.length ≤ 24 ∧ countProbes es = 5 ∧ choiceBits es = [] ∧ after m es = writeMemory m (pub 3) v := by
+ rw [selected_eq_map] at hsel
+ obtain ⟨b, hb, rfl⟩ := Option.map_eq_some_iff.mp hsel
+ let v := Fin.ofNat (2 ^ w) (selectTag b first).code.val
+ have ho := once_program pub state rs m hw header first hh hf
+ simp only [hb, Option.map_some] at ho
+ exact ⟨_, _, (Flow.once_sound pub state false program rs m ho).1, Function.update_self ..,
+ events_bounds pub m _ _ _ b v⟩
+
+/-- A correctly selected tag is written by the compiled standalone call.
+The normal exit hands control to the next stage of a linked live program. -/
+theorem native_selected (hw : 4 ≤ w) (header : ProcessorInput.Header) (first : Bool) (tag : Tag)
+ (hh : m 0 = ProcessorInput.headerWord hw header) (hf : m (pub 2).val = encodeBit w first)
+ (hsel : selected (m (pub 0).val).val (m (pub 1).val).val (header 2) (header 3) first = some tag) :
+ let v := Fin.ofNat (2 ^ w) tag.code.val
+ let machine := (program.template none).instantiate w pub
+ ∃ es, execute machine.program 25 (machine.program.start state) m [] = some ⟨es, none⟩ ∧
+ es.length ≤ 24 ∧ countProbes es = 5 ∧ choiceBits es = [] ∧ after m es = writeMemory m (pub 3) v := by
+ obtain ⟨es, rs', he, _, ht, hp, hb, hm⟩ := exec_selected pub state (fun _ => 0) m hw header first tag hh hf hsel
+ exact ⟨es, (Flow.template_execute_iff program none pub state (fun _ => 0) (fun _ => 0) m 25 [] _).mpr
+ ⟨rs', _, he, rfl, Nat.lt_succ_of_le ht, hb⟩, ht, hp, hb, hm⟩
+
+/-- Unequal modes on two nonempty cuts, or two absent cuts, reject at every
+fuel bound and for every supplied list of choices. -/
+theorem native_rejected (hw : 4 ≤ w) (header : ProcessorInput.Header) (first : Bool)
+ (hh : m 0 = ProcessorInput.headerWord hw header) (hf : m (pub 2).val = encodeBit w first)
+ (hsel : selected (m (pub 0).val).val (m (pub 1).val).val (header 2) (header 3) first = none)
+ (fuel : ℕ) (bits : List Bool) :
+ let machine := (program.template none).instantiate w pub
+ execute machine.program fuel (machine.program.start state) m bits = none := by
+ rw [selected_eq_map, Option.map_eq_none_iff] at hsel
+ have ho := once_program pub state (fun _ => 0) m hw header first hh hf
+ simp only [hsel, Option.map_none] at ho
+ dsimp only
+ cases he : execute _ _ _ _ _ with
+ | none => rfl
+ | some out =>
+ obtain ⟨rs', m', hr, _⟩ := (Flow.template_execute_iff program none pub state (fun _ => 0)
+ (fun _ => 0) m fuel bits out).mp he
+ rw [once_of_exec hr program_simple] at ho
+ contradiction
+
+end Mode
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderModeReject.lean b/lean/OAI/Computability/VPVNP/LiveHeaderModeReject.lean
new file mode 100644
index 0000000000..1d8aceca79
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderModeReject.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.LiveHeaderPrepared
+import OAI.Computability.VPVNP.LiveHeaderPrefixReject
+
+/-! # Rejection of incompatible incident modes by the complete native header table -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderWidths LiveHeader
+open LiveHeaderDescriptors ChainAssignments PrimedInputRAM
+
+variable {w d : ℕ}
+
+theorem bad_mode_native (s : Sizes) (base cap : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (bad : physicalTag cuts g = none)
+ (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d) (scratch : 2^d ≤ base)
+ (fit : limit s base ≤ 2^w) (tagFit : stages.length ≤ 2^w) (fuel : 107 ≤ cap) :
+ ¬ ∃ bs out, runSegment (nativeHeader w s base) cap (some 0) (physicalMemory (d := d) hw advice cuts g) bs =
+ some out ∧ endState (some (0 : Word w)) out = none := by
+ obtain ⟨xs,ma,first,goodA,ready⟩ := index_advice_prefix s base hw advice cuts g indices adv scratch fit
+ obtain ⟨ys,m,second,goodB,img⟩ := Metadata.run_prefix s base d advice cuts g .unit
+ (scalarFit_of_limit fit) scratch ma ready.headers ready.summary 10 (by decide) (by omega)
+ let id : StageId := ⟨12,by decide⟩
+ have pre : StagePrefix s base (some (⟨0,by decide⟩ : StageId)) (physicalMemory (d := d) hw advice cuts g)
+ (xs++ys) (some id) m := first.append second
+ have haddr (n : ℕ) (h : n ≤ base+14) : (Fin.ofNat (2^w) n).val = n := by
+ apply Nat.mod_eq_of_lt
+ rw [limit_eq] at fit
+ omega
+ have hg : ∀ x ∈ xs++ys, x.Good s := by
+ intro x hx
+ exact (List.mem_append.mp hx).elim (goodA x) (goodB x)
+ have startTag : ∀ i, some (⟨0,by decide⟩ : StageId) = some i →
+ physicalMemory (d := d) hw advice cuts g (Fin.ofNat (2^w) base).val = LiveStageLink.tagWord w i := by
+ rintro _ ⟨⟩
+ change physicalMemory (d := d) hw advice cuts g (Fin.ofNat (2^w) base).val = 0
+ rw [haddr _ (by omega)]
+ simp [physicalMemory,RAMMemory.initialMemory,show ¬base < 2^d by omega]
+ have reject : ∀ f bits, execute (nativeStage w s base id) f ((nativeStage w s base id).start 0) m bits = none := by
+ intro f bits
+ let pub := scalarPub w s base .mode
+ have left := img.readback 0 (by decide)
+ have right := img.readback 1 (by decide)
+ have half := img.readback 7 (by decide)
+ have hl := left (Or.inr (Or.inl rfl))
+ have hr := right (Or.inr (Or.inr rfl))
+ have hdr : SiteHeaders d hw advice cuts g m :=
+ fun v => (img.frame v.val (Or.inl (v.isLt.trans_le scratch))).trans (ready.headers v)
+ have h0 : (pub 0).val = widthAddr base .liveLeft := haddr _ (by change base+1 ≤ base+14; omega)
+ have h1 : (pub 1).val = widthAddr base .liveRight := haddr _ (by change base+2 ≤ base+14; omega)
+ have h2 : (pub 2).val = flagAddr base .firstHalf := haddr _ (by change base+8 ≤ base+14; omega)
+ let P := ((entry (Mode.program.template none)).2.instantiate w (rowData w s base .mode)).program
+ change execute P f (P.start 0) m bits = none
+ dsimp only [P]
+ rw [entry_start]
+ apply physical_mode_rejects hdr pub 0 ?_ ?_ ?_ bad f bits
+ · rw [h0]
+ change (m (base+1)).val = CutSchedule.width (s.h+1) s.delta g.val
+ change (m (base+1)).val = CutSchedule.width (s.h+1) s.delta (g.val+1-1) at hl
+ simpa using hl
+ · rw [h1]; exact hr
+ · rw [h2]; exact half
+ exact pre.rejects_entry hg tagFit (by rw [stage_count]; omega) startTag reject
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderOutputFrame.lean b/lean/OAI/Computability/VPVNP/LiveHeaderOutputFrame.lean
new file mode 100644
index 0000000000..bc1ef5f75b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderOutputFrame.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.LiveHeaderComplete
+import OAI.Computability.VPVNP.LiveNominationSweep
+
+/-!
+# Memory passed from the live header into the nomination phase
+
+The enclosing stage tag lies after the processor array and before header
+scratch. Updating that tag preserves all decoded fields. The end of the
+header allocation also gives the zero-initialization property used for the
+auxiliary shadow, including after the nominations are stored.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderDescriptors
+open LiveHeader ChainAssignments PrimedInputRAM
+
+variable {s : Sizes} {base d w : ℕ} {hw : 4 ≤ w} {advice : CutSchedule.Bits s.advice}
+ {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))} {tag : Mode.Tag} {m : Memory w}
+
+private theorem scalar_lower (b : ℕ) (f : Metadata.Field) : b ≤ f.address b := by
+ cases f with
+ | width i => cases i <;> simp [Metadata.Field.address,widthAddr]
+ | flag i => cases i <;> simp [Metadata.Field.address,flagAddr]
+ | firstTail | mode => simp [Metadata.Field.address,firstTailAddr,tagAddr]
+
+private theorem payload_lower (s : Sizes) (base : ℕ) : base ≤ exteriorBase s base .left := by
+ dsimp [exteriorBase,adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase]
+ omega
+
+/-- Updating the outer dispatch cell keeps the complete physical output
+image. Its value may change more than once before nominations begin. -/
+theorem Output.write_outer (out : Output s base d hw advice cuts g tag m) (addr v : Word w)
+ (afterSites : 2^d ≤ addr.val) (below : addr.val < base) :
+ Output s base d hw advice cuts g tag (writeMemory m addr v) := by
+ have hi (a : ℕ) (ha : base ≤ a) : writeMemory m addr v a = m a := ite_eq_right (by omega)
+ have indexLow : base ≤ leftIndexBase s base := by
+ dsimp [leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ have indexRight : leftIndexBase s base ≤ rightIndexBase s base := Nat.le_add_right ..
+ have advLow : rightIndexBase s base ≤ adviceBase s base := Nat.le_add_right ..
+ refine ⟨?_,?_,?_,?_,?_,?_⟩
+ · constructor
+ · intro j
+ rw [writeMemory,ite_eq_right (by have := j.isLt; omega),out.sources.headers]
+ · intro side
+ rw [hi, out.sources.width]
+ cases side <;> simp [widthAddr]
+ · rw [hi (tagAddr base) (Nat.le_add_right ..),out.sources.mode]
+ · rw [hi (flagAddr base .firstHalf) (Nat.le_add_right ..),out.sources.half]
+ · rw [hi (firstTailAddr base) (Nat.le_add_right ..),out.sources.firstTail]
+ · intro f
+ rw [hi _ (scalar_lower base f)]
+ exact out.scalars f
+ · intro i
+ rw [hi _ (by omega),out.adviceWords i]
+ · intro i h
+ rw [hi _ (by omega),out.primedLeft i h]
+ · intro i h
+ rw [hi _ (by omega),out.primedRight i h]
+ · obtain ⟨before,zero,img⟩ := out.fieldImage
+ refine ⟨writeMemory before addr v,?_,?_,?_⟩
+ · intro a low
+ have lower := payload_lower s base
+ rw [writeMemory,ite_eq_right (by omega),zero a low]
+ · intro k hk hf
+ apply (img.copies k hk hf).congr
+ intro j _
+ exact hi _ (by have := Fields.before_destination s base (Fields.key k).1 (Fields.key k).2 hf; omega)
+ · intro a safe
+ by_cases eq : a = addr.val
+ · simp only [writeMemory,eq,ite_true]
+ · simp only [writeMemory,ite_eq_right eq,img.frame a safe]
+
+/-- Unallocated scratch beyond the header stays at the RAM's zero default. -/
+theorem Output.fresh_after_limit (out : Output s base d hw advice cuts g tag m) (a : ℕ) (high : limit s base ≤ a) :
+ m a = 0 := by
+ obtain ⟨before,zero,img⟩ := out.fieldImage
+ have h := limit_eq s base
+ apply (img.frame a ?_).trans
+ · apply zero
+ exact ((Nat.le_add_right _ (s.capacity .exterior)).trans (dest_bounds s base .left .exterior (by decide)).2).trans high
+ · refine ⟨by omega,by dsimp [offsetAddr]; omega,by dsimp [countAddr]; omega,?_⟩
+ intro side f hf
+ exact Or.inr ((Nat.add_le_add_left (Fields.interval_capacity s g tag side f) _).trans
+ ((dest_bounds s base side f hf).2.trans high))
+
+/-- Storing the nominated histogram preserves the header banks and leaves
+every later address at the header's original zero default. -/
+theorem Output.nomination_frame {T b : ℕ} (out : Output s base d hw advice cuts g tag m)
+ (muBase : Word w) (muFit : muBase.val+T ≤ 2^w) (afterHeader : limit s base ≤ muBase.val)
+ (μ : Fin T → Word b) :
+ (∀ a < limit s base, LiveNominations.stored muBase muFit μ m a = m a) ∧
+ (∀ a, muBase.val+T ≤ a → LiveNominations.stored muBase muFit μ m a = 0) := by
+ constructor
+ · intro a ha
+ exact LiveNominations.stored_outside muBase muFit μ m a (Or.inl (ha.trans_le afterHeader))
+ · intro a ha
+ exact (LiveNominations.stored_outside muBase muFit μ m a (Or.inr ha)).trans (out.fresh_after_limit a (by omega))
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPaddingCount.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPaddingCount.lean
new file mode 100644
index 0000000000..9c9f05ed6d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPaddingCount.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.LiveHeaderFieldFormats
+
+/-!
+# The specified group count enforces both native padding guards
+
+On evaluation paths the incoming-format check supplies the left cut's
+padding. A nonzero outgoing pair count supplies the right exponents' padding,
+and a nonzero outgoing tail count supplies a canonical evaluator cut. Unit
+paths use the all-zero cuts on both sides.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.Fields
+
+open ChainAssignments CutSchedule LiveHeader LiveHeaderDescriptors LiveHeaderSchedule
+open ExponentTrace LiveEvaluatorEncoding
+open scoped Classical
+
+variable {s : Sizes} {t Z M w : ℕ} {E : UniversalMachine.Program}
+variable {cuts : AllCuts s.h s.delta} {g : Fin (2^(s.h+1))} {tag : Mode.Tag}
+
+private theorem padding_of_pair (ev : tag ≠ .unit) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta)
+ (side : Side) (i : Fin (2^s.h)) (atCut : incidentCut side g = firstCut i)
+ (pad : pairPadding t Z (liveCutEquiv s.h s.delta cuts).1 i) :
+ ValidPadding s cuts g tag side := by
+ have hi : 0 < (incidentCut side g).val := by rw [atCut]; exact Nat.succ_pos _
+ have half : (incidentCut side g).val ≤ 2^s.h := by rw [atCut]; exact i.isLt
+ unfold ValidPadding
+ rw [interval_pair s g tag ev side .padding (by omega) hi half, he]
+ unfold incidentWidth
+ rw [atCut]
+ exact pad
+
+private theorem padding_of_read (ev : tag ≠ .unit) (hc : s.config = fieldWords M*w)
+ (layout : LiveEvaluatorTail.Layout E.extra M w s.delta)
+ (side : Side) (k : Fin (2^s.h-1)) (atCut : incidentCut side g = laterCut k)
+ (read : (LiveEvaluatorTail.readCut layout k (cuts (laterCut k))).isSome = true) :
+ ValidPadding s cuts g tag side := by
+ have half : 2^s.h < (incidentCut side g).val := by rw [atCut]; change _ < _+(k.val+1); omega
+ have hend : (incidentCut side g).val < 2^(s.h+1) := by
+ rw [atCut]
+ change 2^s.h+(k.val+1) < 2^(s.h+1)
+ rw [pow_succ]
+ have := k.isLt
+ omega
+ have fit : 1+s.config ≤ s.delta := hc ▸ layout.cutWidth
+ unfold ValidPadding
+ rw [interval_tail s g tag ev side .padding (by omega) half hend, hc]
+ unfold incidentWidth
+ rw [atCut]
+ apply (Physical.tail_padding_zero (show 2^s.h ≤ (laterCut k).val from by dsimp [laterCut]; omega)
+ (show (laterCut k).val < 2^(s.h+1) from atCut ▸ hend) layout.cutWidth _).mpr
+ unfold LiveEvaluatorTail.readCut at read
+ dsimp only at read
+ split at read
+ · rename_i checked
+ exact checked.2
+ · contradiction
+
+variable {Nom : Type*} [Fintype Nom]
+variable {Path : Exterior s.h s.delta → Fin (2^s.h) → Nom → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+
+private theorem evaluation_padding (ev : tag ≠ .unit) (he : s.e = t*Z) (hc : s.config = fieldWords M*w)
+ (fit : 1+t*Z ≤ s.delta) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (E : UniversalMachine.Program) (layout : LiveEvaluatorTail.Layout E.extra M w s.delta)
+ (init : (Fin t → ℕ) → Code E.extra M) (incoming : incomingChecks t Z layout cuts g)
+ (count : groupEvaluation fit inc E layout init cuts g ≠ 0) :
+ ∀ side, ValidPadding s cuts g tag side := by
+ intro side
+ rcases coverCuts (incidentCut side g) with zero | last | ⟨i,first⟩ | ⟨k,later⟩
+ · exact validPadding_endpoint side (Or.inl (zero ▸ rfl))
+ · exact validPadding_endpoint side (Or.inr (last ▸ rfl))
+ · apply padding_of_pair ev he fit side i first
+ cases side with
+ | left => exact incoming.1 i first
+ | right =>
+ have same : g = halves s.h (.inl i) := by
+ apply Fin.ext
+ change g.val = i.val
+ have h := congrArg Fin.val first
+ change g.val+1 = i.val+1 at h
+ omega
+ rw [same] at count
+ simp only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inl] at count
+ exact pairCount_padding fit inc _ i count
+ · apply padding_of_read ev hc layout side k later
+ cases side with
+ | left => exact incoming.2 k later
+ | right =>
+ let j : Fin (2^s.h) := ⟨k.val,by have := k.isLt; omega⟩
+ have same : g = halves s.h (.inr j) := by
+ apply Fin.ext
+ change g.val = 2^s.h+k.val
+ have h := congrArg Fin.val later
+ change g.val+1 = 2^s.h+(k.val+1) at h
+ omega
+ rw [same] at count
+ simp only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inr] at count
+ exact tailCount_decoded layout _ (liveCutEquiv s.h s.delta cuts).2 k count
+
+/-- A nonzero mathematical group count forces both scheduled physical padding
+scans to accept, for the actual mode selected on those cuts. -/
+theorem specifiedGroupCount_ne_zero_valid (he : s.e = t*Z) (hc : s.config = fieldWords M*w)
+ (fit : 1+t*Z ≤ s.delta) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (E : UniversalMachine.Program) (layout : LiveEvaluatorTail.Layout E.extra M w s.delta)
+ (init : (Fin t → ℕ) → Code E.extra M) (selected : physicalTag cuts g = some tag)
+ (count : specifiedGroupCount fit inc E layout init cuts g ≠ 0) :
+ ∀ side, ValidPadding s cuts g tag side := by
+ rw [← routed_specifiedGroupCount fit inc E layout init cuts g s.e s.config, selected] at count
+ cases tag with
+ | unit =>
+ apply (validPadding_unit_iff s cuts g).mpr
+ by_contra bad
+ simp [routedCount, bad] at count
+ | pair | tail =>
+ by_cases incoming : incomingChecks t Z layout cuts g
+ · simp only [routedCount, ite_eq_left incoming] at count
+ exact evaluation_padding (by decide) he hc fit inc E layout init incoming count
+ · simp [routedCount, incoming] at count
+
+end LiveHeaderProgram.Fields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPaddingReject.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPaddingReject.lean
new file mode 100644
index 0000000000..b01419ee64
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPaddingReject.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.LiveHeaderComplete
+import OAI.Computability.VPVNP.LiveHeaderPrefixReject
+
+/-!
+# Rejection of malformed padding by the complete native header table
+
+The deterministic prefix from the physical processor headers reaches the
+first malformed padding interval with its actual offset and count. Every
+continuing padding report leaves the linker's tag intact. Any accepting
+header path would therefore complete that scan, contradicting its guard.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderDescriptors
+open LiveHeader ChainAssignments
+
+variable {w d : ℕ}
+
+/-- Arbitrary branch lists and all enclosing fuel bounds above the fixed
+instruction budget fail on malformed incident padding. -/
+theorem bad_padding_native (s : Sizes) (base cap : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : Mode.Tag)
+ (bounds : Fields.Bounds s base d w) (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d)
+ (tagFit : stages.length ≤ 2^w) (fuel : 107 ≤ cap)
+ (hsel : physicalTag cuts g = some tag) (bad : ¬ ∀ side, Fields.ValidPadding s cuts g tag side) :
+ let P := (program.instantiate w (publicData w s base)).program
+ let m := physicalMemory (d := d) hw advice cuts g
+ ¬ ∃ bs rs, runSegment P cap (some 0) m bs = some rs ∧ endState (some 0) rs = none := by
+ let m := physicalMemory (d := d) hw advice cuts g
+ obtain ⟨xs,mid,pre,firstGood,ready⟩ := prepared_prefix s base hw advice cuts g tag hsel indices adv
+ bounds.scratch bounds.fit.le
+ obtain ⟨side,id,ys,atScan,hid,restGood,rest,rejected⟩ := Fields.bad_prefix bounds ready.sources bad
+ have full := pre.append rest
+ have allGood (x : StageTrace w) (hx : x ∈ xs++ys) := (List.mem_append.mp hx).elim (firstGood x) (restGood x)
+ have hbase : (Fin.ofNat (2^w) base).val = base := by
+ have ht := bounds.fit
+ rw [limit_eq] at ht
+ exact Nat.mod_eq_of_lt (by omega)
+ have hz : m (Fin.ofNat (2^w) base).val = 0 := by
+ simp only [m,physicalMemory,RAMMemory.initialMemory,hbase,ite_eq_right bounds.scratch.not_gt]
+ apply full.rejects allGood tagFit (by simpa only [stage_count] using fuel) (by rintro i ⟨⟩; exact hz) rejected
+ intro f st mem b r run _
+ unfold nativeStage at run
+ rw [hid] at run
+ exact ScanRows.padding_call_frame s base side f st mem b run _ mem
+
+/-- Under an agreed mode, the complete header accepts exactly when the
+two actual cuts are canonically padded. -/
+theorem native_padding_iff (s : Sizes) (base cap : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : Mode.Tag)
+ (bounds : Fields.Bounds s base d w) (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d)
+ (tagFit : stages.length ≤ 2^w) (fuel : 107 ≤ cap) (hsel : physicalTag cuts g = some tag) :
+ let P := (program.instantiate w (publicData w s base)).program
+ let m := physicalMemory (d := d) hw advice cuts g
+ (∃ bs rs, runSegment P cap (some 0) m bs = some rs ∧ endState (some 0) rs = none) ↔
+ ∀ side, Fields.ValidPadding s cuts g tag side := by
+ constructor
+ · intro accept
+ by_contra bad
+ exact bad_padding_native s base cap hw advice cuts g tag bounds indices adv tagFit fuel hsel bad accept
+ · intro valid
+ obtain ⟨rs,run,last,_⟩ := valid_native s base cap hw advice cuts g tag bounds indices adv tagFit fuel hsel valid
+ exact ⟨_,rs,run,last⟩
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPairReadback.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPairReadback.lean
new file mode 100644
index 0000000000..32479266b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPairReadback.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.LiveHeaderComplete
+
+/-!
+# Physical input and output exponent words of a nominated pair
+
+The first-half count uses the counter arrays on the two adjacent cuts of
+the live chain. In the first group the preceding array is all zero. The
+header's output memory supplies both arrays to the native exponent checker,
+also after the auxiliary computation has modified its own scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM CutSchedule ChainAssignments ExponentTrace LiveHeader LiveHeaderSchedule
+open LiveHeaderDescriptors
+open scoped Fin.CommRing
+
+variable {w d t Z base : ℕ} {s : Sizes} {hw : 4 ≤ w} {advice : Bits s.advice} {cuts : AllCuts s.h s.delta}
+ {tag : Mode.Tag} {m : Memory w}
+
+private theorem counters_at {q : Fin (2^(s.h+1)+1)} (k : Fin (2^s.h)) (eq : q = firstCut k)
+ (hi : 0 < q.val) (half : q.val ≤ 2^s.h) (fit : 1+t*Z ≤ s.delta) :
+ (firstHalfLayout s.h s.delta q.val t Z hi half fit (cuts q)).2.2.1 =
+ counters fit (liveCutEquiv s.h s.delta cuts).1 k.succ := by
+ subst q
+ rfl
+
+private theorem decoded_side {g : Fin (2^(s.h+1))} (out : Output s base d hw advice cuts g tag m)
+ (side : Side) (k : Fin (2^s.h)) (cut : incidentCut side g = firstCut k)
+ (ev : tag ≠ .unit) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta) :
+ ExponentWords (counters fit (liveCutEquiv s.h s.delta cuts).1 k.succ) (exponentBase s base side) m := by
+ have pos : 0 < (incidentCut side g).val := by rw [cut]; exact Nat.succ_pos _
+ have half : (incidentCut side g).val ≤ 2^s.h := by rw [cut]; exact k.isLt
+ obtain ⟨before,_,img⟩ := out.fieldImage
+ have decoded := img.pair_exponents ev side he fit pos half
+ rwa [counters_at k cut pos half fit] at decoded
+
+/-- All outgoing counters and the immediately preceding incoming counters
+from the mathematical contraction are present in the real scratch banks. -/
+theorem Output.pairExponentWords (i : Fin (2^s.h))
+ (out : Output s base d hw advice cuts (halves s.h (.inl i)) tag m)
+ (ev : tag ≠ .unit) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta) :
+ let fst := (liveCutEquiv s.h s.delta cuts).1
+ ExponentWords (counters fit fst i.castSucc) (exponentBase s base .left) m ∧
+ ExponentWords (counters fit fst i.succ) (exponentBase s base .right) m := by
+ dsimp only
+ refine ⟨?_,decoded_side out .right i (Fin.ext rfl) ev he fit⟩
+ by_cases first : i.val = 0
+ · have hi : i.castSucc = 0 := Fin.ext first
+ rw [hi]
+ obtain ⟨before,zero,img⟩ := out.fieldImage
+ apply img.first_exponents first he
+ intro a b
+ have low : exteriorBase s base .left ≤ exponentBase s base .left := by
+ dsimp [exponentBase,exteriorBase]; omega
+ rw [zero _ (low.trans (Nat.le_add_right ..)), RAMSerialization.wordBits_zero]
+ rfl
+ · let k : Fin (2^s.h) := ⟨i.val-1,(Nat.sub_le _ _).trans_lt i.isLt⟩
+ have val : k.val+1 = i.val := by dsimp [k]; omega
+ have hi : i.castSucc = k.succ := Fin.ext val.symm
+ rw [hi]
+ exact decoded_side out .left k (Fin.ext val.symm) ev he fit
+
+/-- Exactly the buffer hypothesis consumed by the native first-half
+exponent-stage count. The two public operands address the decoded banks. -/
+theorem Output.pairBufferValues (i : Fin (2^s.h))
+ (out : Output s base d hw advice cuts (halves s.h (.inl i)) tag m)
+ (ev : tag ≠ .unit) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta) (room : limit s base ≤ 2^w)
+ (pub : Fin 5 → BurstRAM.Word w) (left : (pub 0).val = exponentBase s base .left)
+ (right : (pub 1).val = exponentBase s base .right) :
+ let fst := (liveCutEquiv s.h s.delta cuts).1
+ LiveExponent.BufferValues pub (counters fit fst i.castSucc) (counters fit fst i.succ) m := by
+ obtain ⟨before,after⟩ := out.pairExponentWords i ev he fit
+ have bounds (side : Side) : exponentBase s base side+t*Z ≤ 2^w := by
+ rw [← he]
+ exact (dest_bounds s base side .exponents (by decide)).2.trans room
+ exact exponentBufferValues (by omega) pub (left ▸ before) (right ▸ after)
+ (left ▸ bounds .left) (right ▸ bounds .right)
+
+/-- The nomination and pair phases may change scratch outside the two
+read-only banks. The same native checker then sees the original counters. -/
+theorem Output.pairBufferValues_after (i : Fin (2^s.h))
+ (out : Output s base d hw advice cuts (halves s.h (.inl i)) tag m)
+ (ev : tag ≠ .unit) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta) (room : limit s base ≤ 2^w)
+ (pub : Fin 5 → BurstRAM.Word w) (left : (pub 0).val = exponentBase s base .left)
+ (right : (pub 1).val = exponentBase s base .right) (afterPair : Memory w)
+ (frame : ∀ side j, j < t*Z → afterPair (exponentBase s base side+j) = m (exponentBase s base side+j)) :
+ let fst := (liveCutEquiv s.h s.delta cuts).1
+ LiveExponent.BufferValues pub (counters fit fst i.castSucc) (counters fit fst i.succ) afterPair := by
+ obtain ⟨before,after⟩ := out.pairExponentWords i ev he fit
+ have bounds (side : Side) : exponentBase s base side+t*Z ≤ 2^w := by
+ rw [← he]
+ exact (dest_bounds s base side .exponents (by decide)).2.trans room
+ exact exponentBufferValues (by omega) pub (left ▸ before.congr (frame .left)) (right ▸ after.congr (frame .right))
+ (left ▸ bounds .left) (right ▸ bounds .right)
+
+private theorem exterior_at {q : Fin (2^(s.h+1)+1)} (k : Fin (2^s.h)) (eq : q = firstCut k)
+ (hi : 0 < q.val) (half : q.val ≤ 2^s.h) (fit : 1+t*Z ≤ s.delta) (dst : ℕ)
+ (stored : ∀ j : Fin (width (s.h+1) s.delta (2*q.val)),
+ m (dst+j.val) = PrimedInputRAM.encodeBit w ((firstHalfLayout s.h s.delta q.val t Z hi half fit (cuts q)).2.1 j)) :
+ ∀ j : Fin (width (s.h+1) s.delta (2*k.succ.val)),
+ m (dst+j.val) = PrimedInputRAM.encodeBit w (exteriorOf fit (liveCutEquiv s.h s.delta cuts).1 k.succ j) := by
+ subst q
+ exact stored
+
+private theorem decoded_exterior {g : Fin (2^(s.h+1))} (out : Output s base d hw advice cuts g tag m)
+ (side : Side) (k : Fin (2^s.h)) (cut : incidentCut side g = firstCut k)
+ (ev : tag ≠ .unit) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta) :
+ ∀ j : Fin (width (s.h+1) s.delta (2*k.succ.val)), m (exteriorBase s base side+j.val) =
+ PrimedInputRAM.encodeBit w (exteriorOf fit (liveCutEquiv s.h s.delta cuts).1 k.succ j) := by
+ have pos : 0 < (incidentCut side g).val := by rw [cut]; exact Nat.succ_pos _
+ have half : (incidentCut side g).val ≤ 2^s.h := by rw [cut]; exact k.isLt
+ obtain ⟨_,_,img⟩ := out.fieldImage
+ exact exterior_at k cut pos half fit _ (img.pair_exterior ev side he fit pos half)
+
+/-- The two exterior fields are the actual physical sources of the
+auxiliary RAM at the adjacent primed even cuts. Empty fields at either
+primed endpoint have no read addresses. -/
+theorem Output.pairExteriorWords (i : Fin (2^s.h))
+ (out : Output s base d hw advice cuts (halves s.h (.inl i)) tag m)
+ (ev : tag ≠ .unit) (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta) :
+ let ξ := exteriorOf fit (liveCutEquiv s.h s.delta cuts).1
+ let L := PairedChain.lengths s.h s.delta s.advice i
+ (∀ j : Fin L.leftCut, m (exteriorBase s base .left+j.val) = PrimedInputRAM.encodeBit w (ξ i.castSucc j)) ∧
+ (∀ j : Fin L.rightCut, m (exteriorBase s base .right+j.val) = PrimedInputRAM.encodeBit w (ξ i.succ j)) := by
+ dsimp only
+ refine ⟨?_, decoded_exterior out .right i (Fin.ext rfl) ev he fit⟩
+ change ∀ j : Fin (width (s.h+1) s.delta (2*i.castSucc.val)), m (exteriorBase s base .left+j.val) =
+ PrimedInputRAM.encodeBit w (exteriorOf fit (liveCutEquiv s.h s.delta cuts).1 i.castSucc j)
+ by_cases first : i.val = 0
+ · intro j
+ have zero : (width (s.h+1) s.delta (2*i.castSucc.val)) = 0 := by
+ change width (s.h+1) s.delta (2*i.val) = 0
+ simp [first]
+ exact Fin.elim0 (j.cast zero)
+ · let k : Fin (2^s.h) := ⟨i.val-1,(Nat.sub_le _ _).trans_lt i.isLt⟩
+ have val : k.val+1 = i.val := by dsimp [k]; omega
+ have hi : i.castSucc = k.succ := Fin.ext val.symm
+ rw [hi]
+ exact decoded_exterior out .left k (Fin.ext val.symm) ev he fit
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPhases.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPhases.lean
new file mode 100644
index 0000000000..68525b8981
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPhases.lean
@@ -0,0 +1,357 @@
+import OAI.Computability.VPVNP.LiveHeaderWidthCode
+import OAI.Computability.VPVNP.LiveHeaderScan
+
+/-!
+# Live group flags computed from the scanned header
+
+The live program tests whether it is at the first group, at the midpoint,
+in the first half, or at the last group. Each test uses the scanned high
+bit position and population count. The tests also apply when the first
+group is the midpoint.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderWidths
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+
+/-- The first-group, midpoint, first-half, and last-group predicates computed from the
+one-based index. -/
+inductive Flag where | first | middle | firstHalf | last
+
+/-- Evaluate a phase flag against a one-based group index and the chain's height. -/
+def Flag.holds (h i : ℕ) : Flag → Prop
+ | .first => i = 1
+ | .middle => i = 2^h
+ | .firstHalf => i ≤ 2^h
+ | .last => i = 2^(h+1)
+
+instance (h i : ℕ) (f : Flag) : Decidable (f.holds h i) := by cases f <;> unfold Flag.holds <;> infer_instance
+
+
+/-- The complete scanned prefix is the finite set of binary positions. -/
+private theorem allOnes {i len : ℕ} (hlt : i < 2^len) :
+ LiveHeader.prefixOnes i len = i.bitIndices.toFinset := by
+ ext j
+ simp only [LiveHeader.prefixOnes, Finset.mem_filter, Finset.mem_range, List.mem_toFinset,
+ Nat.mem_bitIndices, and_iff_right_iff_imp]
+ intro ht
+ by_contra! hh
+ have hz := Nat.testBit_lt_two_pow (hlt.trans_le (Nat.pow_le_pow_right (by decide) hh))
+ simp_all
+
+/-- In the nondegenerate case, the first tail index has precisely bits
+zero and `h` set. The low bit distinguishes it from other tail indices
+of population two. -/
+theorem firstTail_iff {h i : ℕ} (hh : 0 < h) (hi : 0 < i) (hend : i ≤ 2^(h+1)) :
+ Nat.log 2 i = h ∧ (LiveHeader.prefixOnes i (h+2)).card = 2 ∧ i.testBit 0 = true ↔ i = 2^h+1 := by
+ have hfit : i < 2^(h+2) := by rw [show h+2=(h+1)+1 by omega, pow_succ]; omega
+ have hs : ([0,h] : List ℕ).SortedLT := by simp [hh, List.sortedLT_nil]
+ have hb := Nat.bitIndices_sum_map_two_pow hs
+ simp only [List.map_cons, List.map_nil, List.sum_cons, List.sum_nil, Nat.add_zero, pow_zero,
+ Nat.add_comm 1] at hb
+ rw [allOnes hfit]
+ constructor
+ · rintro ⟨hk, hc, hl⟩
+ have hlo : 0 ∈ i.bitIndices := Nat.mem_bitIndices.mpr hl
+ have hhi : h ∈ i.bitIndices := by
+ have ht := Nat.testBit_log2 hi.ne'
+ rw [Nat.log2_eq_log_two, hk] at ht
+ exact Nat.mem_bitIndices.mpr ht
+ have hsub : ({0,h} : Finset ℕ) ⊆ i.bitIndices.toFinset := by
+ simp [Finset.insert_subset_iff, hlo, hhi]
+ have hcard : ({0,h} : Finset ℕ).card = 2 := by rw [Finset.card_insert_of_notMem (by simpa using hh.ne'.symm), Finset.card_singleton]
+ have he := Finset.eq_of_subset_of_card_le hsub (hc.trans hcard.symm).le
+ apply Nat.eq_of_testBit_eq
+ intro j
+ apply Bool.eq_iff_iff.mpr
+ rw [← Nat.mem_bitIndices, ← Nat.mem_bitIndices, hb, ← List.mem_toFinset, ← he]
+ simp
+ · rintro rfl
+ have hp := Nat.one_lt_two_pow hh.ne'
+ have hk : Nat.log 2 (2^h+1) = h :=
+ Nat.log_eq_of_pow_le_of_lt_pow (by omega) (by rw [pow_succ]; omega)
+ rw [hk, hb, ← Nat.mem_bitIndices, hb]
+ simp
+ change ({0,h} : Finset ℕ).card = 2
+ rw [Finset.card_insert_of_notMem (by simpa using hh.ne'.symm), Finset.card_singleton]
+
+
+namespace PhaseCode
+
+private abbrev Pub := Fin 16
+private abbrev Reg := Fin 48
+private abbrev Code := Flow 48 16
+
+/-- The public parameters locate the two index-scan words and the destination. -/
+def setup (p : Parameters) : Code :=
+ straight (.constant 0 0) [.constant 1 1, .publicWord 2 p.height, .binary .sub 3 2 1,
+ .publicWord 4 p.highestAddress, .publicWord 5 p.populationAddress, .publicWord 6 p.outputAddress,
+ .read 7 4, .read 8 5]
+
+private def store (b : Bool) : Code := .line (.write 6 (if b then 1 else 0))
+private def single : Code := .ifEq 8 1 (store true) (store false)
+private def middle : Code := .ifEq 7 3 single (store false)
+
+/-- Select the native comparison and Boolean store that implement the requested phase flag. -/
+def dispatch : Flag → Code
+ | .first => .ifEq 7 0 (store true) (store false)
+ | .middle => middle
+ | .firstHalf => .ifLt 7 3 (store true) middle
+ | .last => .ifEq 7 2 (store true) (store false)
+
+/-- Load the scanned index summary and execute the test for the requested group flag. -/
+def block (p : Parameters) (f : Flag) : Code := .seq (setup p) (dispatch f)
+
+variable {w : ℕ}
+
+private def loaded (pub : Pub → Word w) (p : Parameters) (m : Memory w) (rs : Regs w 48) : Regs w 48 :=
+ let vs : List (Reg × Word w) :=
+ [(0,0),(1,1),(2,pub p.height),(3,pub p.height-1),
+ (4,pub p.highestAddress),(5,pub p.populationAddress),(6,pub p.outputAddress),
+ (7,m (pub p.highestAddress).val),(8,m (pub p.populationAddress).val)]
+ vs.foldl (fun a j => Function.update a j.1 j.2) rs
+
+private def setupEvents (pub : Pub → Word w) (p : Parameters) (m : Memory w) : List (Event w) :=
+ List.replicate 7 .tick ++ [.read (pub p.highestAddress) (m (pub p.highestAddress).val),
+ .read (pub p.populationAddress) (m (pub p.populationAddress).val)]
+
+private theorem setup_exec (pub : Pub → Word w) (p : Parameters) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) : Flow.Exec pub state (setup p) rs m (setupEvents pub p m) (loaded pub p m rs) m :=
+ (Flow.once_sound pub state false (setup p) rs m rfl).1
+
+private def Verdict (rs : Regs w 48) : Flag → Prop
+ | .first => rs 7 = rs 0
+ | .middle => rs 7 = rs 3 ∧ rs 8 = rs 1
+ | .firstHalf => rs 7 < rs 3 ∨ rs 7 = rs 3 ∧ rs 8 = rs 1
+ | .last => rs 7 = rs 2
+
+private instance (rs : Regs w 48) (f : Flag) : Decidable (Verdict rs f) := by
+ cases f <;> unfold Verdict <;> infer_instance
+
+/-- A successful flag write after at most three conditional instructions. -/
+private def Writes (pub : Pub → Word w) (state : Word w) (rs : Regs w 48) (m : Memory w)
+ (a : Code) (v : Word w) (k : ℕ) : Prop :=
+ ∃ n ≤ k, Flow.Exec pub state a rs m (List.replicate n .tick ++ [.write (rs 6) v]) rs (writeMemory m (rs 6) v)
+
+private theorem Writes.store {pub : Pub → Word w} {state : Word w} {rs : Regs w 48} {m : Memory w}
+ (b : Bool) : Writes pub state rs m (store b) (if b then rs 1 else rs 0) 0 := by
+ cases b <;> exact ⟨0,by decide,.line rfl⟩
+
+private theorem Writes.guard {pub : Pub → Word w} {state : Word w} {rs : Regs w 48} {m : Memory w}
+ {a b : Code} {v : Word w} {k : ℕ} (hw : Writes pub state rs m a v k)
+ (lift : ∀ es, Flow.Exec pub state a rs m es rs (writeMemory m (rs 6) v) →
+ Flow.Exec pub state b rs m (.tick :: es) rs (writeMemory m (rs 6) v)) :
+ Writes pub state rs m b v (k+1) := by
+ obtain ⟨n,hn,hr⟩ := hw
+ exact ⟨n+1,by omega,by simpa [List.replicate_succ] using lift _ hr⟩
+
+private theorem Writes.weaken {pub : Pub → Word w} {state : Word w} {rs : Regs w 48} {m : Memory w}
+ {a : Code} {v : Word w} {k k' : ℕ} (hw : Writes pub state rs m a v k) (h : k ≤ k') :
+ Writes pub state rs m a v k' := by obtain ⟨n,hn,hr⟩ := hw; exact ⟨n,hn.trans h,hr⟩
+
+private theorem eq_exec {pub : Pub → Word w} {state : Word w} {rs : Regs w 48} {m : Memory w}
+ (x y : Reg) : Writes pub state rs m (.ifEq x y (store true) (store false))
+ (if rs x = rs y then rs 1 else rs 0) 1 := by
+ split_ifs with h
+ · exact (Writes.store true).guard (fun _ e => .ifEqYes h e)
+ · exact (Writes.store false).guard (fun _ e => .ifEqNo h e)
+
+private theorem middle_exec {pub : Pub → Word w} {state : Word w} {rs : Regs w 48} {m : Memory w} :
+ Writes pub state rs m middle (if rs 7 = rs 3 ∧ rs 8 = rs 1 then rs 1 else rs 0) 2 := by
+ by_cases h : rs 7 = rs 3
+ · simp only [h, true_and]
+ exact (eq_exec 8 1).guard (fun _ e => .ifEqYes h e)
+ · rw [ite_eq_right (fun he => h he.1)]
+ exact ((Writes.store false).guard (fun _ e => .ifEqNo h e)).weaken (by decide)
+
+private theorem dispatch_exec {pub : Pub → Word w} {state : Word w} {rs : Regs w 48} {m : Memory w}
+ (f : Flag) : Writes pub state rs m (dispatch f) (if Verdict rs f then rs 1 else rs 0) 3 := by
+ cases f with
+ | first => exact (eq_exec 7 0).weaken (by decide)
+ | last => exact (eq_exec 7 2).weaken (by decide)
+ | middle => exact middle_exec.weaken (by decide)
+ | firstHalf =>
+ by_cases h : rs 7 < rs 3
+ · have hv : Verdict rs .firstHalf := Or.inl h
+ rw [ite_eq_left hv]
+ exact ((Writes.store true).guard (fun _ e => .ifLtYes h e)).weaken (by decide)
+ · have hv : Verdict rs .firstHalf ↔ rs 7 = rs 3 ∧ rs 8 = rs 1 := by simp [Verdict, h]
+ rw [if_congr hv rfl rfl]
+ exact middle_exec.guard (fun _ e => .ifLtNo h e)
+
+/-- A deterministic native flag computation on the output of the index scan.
+Its two reads and one write take at most thirteen instructions including tests. -/
+theorem block_exec (pub : Pub → Word w) (p : Parameters) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) (h i c : ℕ) (f : Flag) (hi : 0 < i) (hend : i ≤ 2^(h+1))
+ (hc : c = 1 ↔ i = 2 ^ Nat.log 2 i) (hh : (pub p.height).val = h+1)
+ (hk' : (m (pub p.highestAddress).val).val = Nat.log 2 i)
+ (hc' : (m (pub p.populationAddress).val).val = c) :
+ let v := encodeBit w (decide (f.holds h i))
+ ∃ es out, Flow.Exec pub state (block p f) rs m es out (writeMemory m (pub p.outputAddress) v) ∧
+ countProbes es = 3 ∧ choiceBits es = [] ∧ es.length ≤ 13 := by
+ let a := loaded pub p m rs
+ obtain ⟨n,hn,hr⟩ := dispatch_exec (pub := pub) (state := state) (rs := a) (m := m) f
+ have hgt := (pub p.height).isLt
+ rw [hh] at hgt
+ have h0 : (a 0).val = 0 := rfl
+ have h1 : (a 1).val = 1 := by
+ change (1 : Word w).val = 1
+ exact Nat.mod_eq_of_lt (by omega : 1 < 2^w)
+ have h2 : (a 2).val = h+1 := hh
+ have h3 : (a 3).val = h := by
+ change (a 2 - a 1).val = h
+ rw [Fin.sub_val_of_le (by change (a 1).val ≤ _; omega),h2,h1]
+ omega
+ have h7 : (a 7).val = Nat.log 2 i := hk'
+ have h8 : (a 8).val = c := hc'
+ have hz := endpoints_iff (h+1) i hi hend
+ have hv : Verdict a f ↔ f.holds h i := by
+ cases f <;> simp only [Verdict, Flag.holds, Fin.ext_iff, Fin.lt_def, h0, h1, h2, h3, h7, h8]
+ · exact hz.1
+ · constructor
+ · rintro ⟨he,hc'⟩
+ simpa [he] using hc.mp hc'
+ · rintro rfl
+ simp [Nat.log_pow (by decide : 1 < 2), hc]
+ · exact firstHalf_iff h i c hi hc
+ · exact hz.2
+ let v := encodeBit w (decide (f.holds h i))
+ have hv' : (if Verdict a f then a 1 else a 0) = v := by
+ by_cases he : f.holds h i
+ · rw [ite_eq_left (hv.mpr he)]; simp [v, he, encodeBit]; rfl
+ · rw [ite_eq_right (mt hv.mp he)]; simp [v, he, encodeBit]; rfl
+ have hout : a 6 = pub p.outputAddress := rfl
+ rw [hv', hout] at hr
+ refine ⟨_,a,(setup_exec pub p state m rs).seq hr, ?_, ?_, ?_⟩
+ · have hn' : n = 0 ∨ n = 1 ∨ n = 2 ∨ n = 3 := by omega
+ rcases hn' with rfl | rfl | rfl | rfl <;> rfl
+ · have hn' : n = 0 ∨ n = 1 ∨ n = 2 ∨ n = 3 := by omega
+ rcases hn' with rfl | rfl | rfl | rfl <;> rfl
+ · simp [setupEvents]; omega
+
+/-- The first tail group needs the low bit as well as the high position and
+population. Its low bit is at the base of the copied index array. -/
+private def lowLoad (lowAddress : Pub) : Code :=
+ straight (.constant 9 2) [.publicWord 10 lowAddress, .read 11 10]
+
+private def twoLow : Code := .ifEq 8 9 (.ifEq 11 1 (store true) (store false)) (store false)
+private def highTwoLow : Code := .ifEq 7 3 twoLow (store false)
+private def tailDispatch : Code :=
+ .ifEq 3 0 (dispatch .last) highTwoLow
+
+/-- Load the index summary and low digit to test whether this is the first group after the
+midpoint. -/
+def firstTailBlock (p : Parameters) (lowAddress : Pub) : Code :=
+ .seq (setup p) (.seq (lowLoad lowAddress) tailDispatch)
+
+private def lowRegs (pub : Pub → Word w) (lowAddress : Pub) (m : Memory w) (rs : Regs w 48) :=
+ Function.update (Function.update (Function.update rs (9 : Reg) 2) (10 : Reg) (pub lowAddress))
+ (11 : Reg) (m (pub lowAddress).val)
+
+private theorem lowLoad_exec (pub : Pub → Word w) (lowAddress : Pub) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) : Flow.Exec pub state (lowLoad lowAddress) rs m
+ [.tick,.tick,.read (pub lowAddress) (m (pub lowAddress).val)] (lowRegs pub lowAddress m rs) m :=
+ (Flow.once_sound pub state false _ rs m rfl).1
+
+private theorem andEq {pub : Pub → Word w} {state : Word w} {rs : Regs w 48} {m : Memory w}
+ {a : Code} {x y : Reg} {P : Prop} [Decidable P] {k : ℕ}
+ (hw : Writes pub state rs m a (if P then rs 1 else rs 0) k) :
+ Writes pub state rs m (.ifEq x y a (store false)) (if rs x = rs y ∧ P then rs 1 else rs 0) (k+1) := by
+ by_cases he : rs x = rs y
+ · simp only [he, true_and]
+ exact hw.guard (fun _ e => .ifEqYes he e)
+ · simp only [he, false_and, ↓reduceIte]
+ exact ((Writes.store false).guard (fun _ e => .ifEqNo he e)).weaken (by omega)
+
+private theorem tailDispatch_exec {pub : Pub → Word w} {state : Word w} {rs : Regs w 48} {m : Memory w} :
+ let value := if rs 3 = rs 0 then (if rs 7 = rs 2 then rs 1 else rs 0)
+ else if rs 7 = rs 3 ∧ rs 8 = rs 9 ∧ rs 11 = rs 1 then rs 1 else rs 0
+ Writes pub state rs m tailDispatch value 4 := by
+ dsimp only
+ by_cases he : rs 3 = rs 0
+ · rw [ite_eq_left he]
+ exact ((eq_exec 7 2).guard (fun _ e => .ifEqYes he e)).weaken (by decide)
+ · rw [ite_eq_right he]
+ exact (andEq (andEq (eq_exec 11 1))).guard (fun _ e => .ifEqNo he e)
+
+/-- The group after the midpoint alone is designated for initialization.
+This test covers the two-group chain and reads a total of three scratch
+words before writing its decision. -/
+theorem firstTail_exec (hw : 2 ≤ w) (pub : Pub → Word w) (p : Parameters) (lowAddress : Pub)
+ (state : Word w) (m : Memory w) (rs : Regs w 48) (h i : ℕ) (hi : 0 < i) (hend : i ≤ 2^(h+1))
+ (hh : (pub p.height).val = h+1) (hk : (m (pub p.highestAddress).val).val = Nat.log 2 i)
+ (hc : (m (pub p.populationAddress).val).val = (LiveHeader.prefixOnes i (h+2)).card)
+ (hlo : m (pub lowAddress).val = encodeBit w (i.testBit 0)) :
+ let v := encodeBit w (decide (i = 2^h+1))
+ ∃ es out, Flow.Exec pub state (firstTailBlock p lowAddress) rs m es out (writeMemory m (pub p.outputAddress) v) ∧
+ countProbes es = 4 ∧ choiceBits es = [] ∧ es.length ≤ 17 := by
+ let a := loaded pub p m rs
+ let b := lowRegs pub lowAddress m a
+ obtain ⟨n,hn,hr⟩ := tailDispatch_exec (pub := pub) (state := state) (rs := b) (m := m)
+ have ht : 2 < 2^w := calc
+ 2 < 2^2 := by decide
+ _ ≤ 2^w := Nat.pow_le_pow_right (by decide) hw
+ have h0 : (b 0).val = 0 := rfl
+ have h1 : (b 1).val = 1 := Nat.mod_eq_of_lt (by omega : 1 < 2^w)
+ have h2 : (b 2).val = h+1 := hh
+ have h3 : (b 3).val = h := by
+ change (b 2 - b 1).val = h
+ rw [Fin.sub_val_of_le (by change (b 1).val ≤ _; omega), h2, h1]
+ omega
+ have h7 : (b 7).val = Nat.log 2 i := hk
+ have h8 : (b 8).val = (LiveHeader.prefixOnes i (h+2)).card := hc
+ have h9 : (b 9).val = 2 := Nat.mod_eq_of_lt ht
+ have h11 : b 11 = b 1 ↔ i.testBit 0 = true := by
+ change m (pub lowAddress).val = (1 : Word w) ↔ _
+ rw [hlo, encodeBit_eq_one (by omega)]
+ let v := encodeBit w (decide (i = 2^h+1))
+ have hv : (if b 3 = b 0 then (if b 7 = b 2 then b 1 else b 0)
+ else if b 7 = b 3 ∧ b 8 = b 9 ∧ b 11 = b 1 then b 1 else b 0) = v := by
+ have hz : b 3 = b 0 ↔ h = 0 := by simp only [Fin.ext_iff,h3,h0]
+ by_cases he : h = 0
+ · rw [ite_eq_left (hz.mpr he)]
+ have hlast : b 7 = b 2 ↔ i = 2^h+1 := by
+ rw [Fin.ext_iff, h7, h2, (endpoints_iff (h+1) i hi hend).2, he]
+ rfl
+ rw [if_congr hlast rfl rfl]
+ by_cases ht : i = 2^h+1 <;> simp [v,ht,encodeBit] <;> rfl
+ · rw [ite_eq_right (mt hz.mp he)]
+ have hs : b 7 = b 3 ∧ b 8 = b 9 ∧ b 11 = b 1 ↔ i = 2^h+1 := by
+ rw [h11]
+ simpa only [Fin.ext_iff, h7,h3,h8,h9] using firstTail_iff (by omega : 0 < h) hi hend
+ rw [if_congr hs rfl rfl]
+ by_cases ht : i = 2^h+1 <;> simp [v,ht,encodeBit] <;> rfl
+ have hout : b 6 = pub p.outputAddress := rfl
+ rw [hv,hout] at hr
+ refine ⟨_,b,(setup_exec pub p state m rs).seq ((lowLoad_exec pub lowAddress state m a).seq hr), ?_, ?_, ?_⟩
+ · have hn' : n = 0 ∨ n = 1 ∨ n = 2 ∨ n = 3 ∨ n = 4 := by omega
+ rcases hn' with rfl | rfl | rfl | rfl | rfl <;> rfl
+ · have hn' : n = 0 ∨ n = 1 ∨ n = 2 ∨ n = 3 ∨ n = 4 := by omega
+ rcases hn' with rfl | rfl | rfl | rfl | rfl <;> rfl
+ · simp [setupEvents]; omega
+
+end PhaseCode
+
+/-- Direct composition with the two summary words of the header scan. -/
+theorem scanned_width_exec {w : ℕ} (pub : Fin 16 → Word w) (p : Parameters) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) (s : Slot) (h Δ i : ℕ) (hi : 0 < i) (hend : i ≤ 2^(h+1)) (hneed : Needed h i s)
+ (hh : (pub p.height).val = h+1) (hΔ : (pub p.delta).val = Δ)
+ (hk : (m (pub p.highestAddress).val).val = LiveHeader.prefixHigh i (h+2))
+ (hc : (m (pub p.populationAddress).val).val = (LiveHeader.prefixOnes i (h+2)).card)
+ (hfit : (h+1)*Δ < 2^w) :
+ let v : Word w := Fin.ofNat _ (CutSchedule.width (h+1) Δ (index i s))
+ ∃ out, Flow.Exec pub state (WidthCode.block p s) rs m (WidthCode.events pub p m s v) out
+ (writeMemory m (pub p.outputAddress) v) ∧ v.val = CutSchedule.width (h+1) Δ (index i s) := by
+ have hb : i < 2^(h+2) := by rw [show h+2 = (h+1)+1 by omega, pow_succ]; omega
+ obtain ⟨hk',hc'⟩ := LiveHeader.summary_correct hi.ne' hb
+ exact WidthCode.needed_exec pub p state m rs s h Δ i _ hi hend hneed hc' hh hΔ (hk.trans hk') hc hfit
+
+end LiveHeaderWidths
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPhysical.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPhysical.lean
new file mode 100644
index 0000000000..ca40280bd5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPhysical.lean
@@ -0,0 +1,195 @@
+import OAI.Computability.VPVNP.LiveHeaderShapes
+
+/-!
+# Typed cut fields at their physical processor sites
+
+The descriptor arithmetic addresses the same bits as the paper's typed
+cut layout. In particular the exponent vector uses label-major order,
+with the least significant bit first inside each label word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderDescriptors.Physical
+
+open CutSchedule
+
+section Pair
+
+variable {h Δ i t Z : ℕ} (hi : 0 < i) (hle : i ≤ 2^h) (hfit : 1+t*Z ≤ Δ)
+variable (bits : Bits (width (h+1) Δ i))
+
+theorem pair_mode (site : Fin (width (h+1) Δ i)) (hs : site.val = 0) :
+ (firstHalfLayout h Δ i t Z hi hle hfit bits).1 = bits site := by
+ change bits _ = bits site
+ apply congrArg bits
+ exact Fin.ext hs.symm
+
+private theorem pair_starts (f : Field) (j : ℕ) (hj : j < count .pair (width (h+1) Δ i) Δ (t*Z) 0 f) :
+ (span .pair (width (h+1) Δ i) Δ (t*Z) 0 f).1 = start .pair (width (h+1) Δ i) Δ (t*Z) 0 f := by
+ simp [span, show count .pair (width (h+1) Δ i) Δ (t*Z) 0 f ≠ 0 by omega]
+
+theorem pair_exterior (j : Fin (width (h+1) Δ (2*i))) (site : Fin (width (h+1) Δ i))
+ (hs : site.val = (span .pair (width (h+1) Δ i) Δ (t*Z) 0 .exterior).1 + j.val) :
+ (firstHalfLayout h Δ i t Z hi hle hfit bits).2.1 j = bits site := by
+ have hlen := LiveHeaderDescriptors.pair_exterior h Δ i hi hle
+ have hmode : mode (width (h+1) Δ i) = 1 := by
+ rw [mode, width_double h Δ i hi hle, ite_eq_right (by omega)]
+ have hj : j.val < count .pair (width (h+1) Δ i) Δ (t*Z) 0 .exterior := by
+ change j.val < exterior .pair (width (h+1) Δ i) Δ
+ rw [hlen]; exact j.isLt
+ rw [pair_starts .exterior j.val hj, start, hmode] at hs
+ change bits _ = bits site
+ apply congrArg bits
+ exact Fin.ext hs.symm
+
+private theorem pair_exp_bits (a : Fin t) (b : Fin Z) :
+ let q := firstHalfLayout h Δ i t Z hi hle hfit bits
+ RAMSerialization.wordBits Z (q.2.2.1 a) b =
+ RAMSerialization.arrayBits t Z q.2.2.1 (finProdFinEquiv (a,b)) :=
+ (RAMSerialization.arrayBits_at _ a b).symm
+
+theorem pair_exponent (a : Fin t) (b : Fin Z) (site : Fin (width (h+1) Δ i))
+ (hs : site.val = (span .pair (width (h+1) Δ i) Δ (t*Z) 0 .exponents).1 + a.val*Z + b.val) :
+ RAMSerialization.wordBits Z ((firstHalfLayout h Δ i t Z hi hle hfit bits).2.2.1 a) b = bits site := by
+ let j := finProdFinEquiv (a,b)
+ have hj : j.val < count .pair (width (h+1) Δ i) Δ (t*Z) 0 .exponents := j.isLt
+ have hlen := LiveHeaderDescriptors.pair_exterior h Δ i hi hle
+ have hmode : mode (width (h+1) Δ i) = 1 := by
+ rw [mode, width_double h Δ i hi hle, ite_eq_right (by omega)]
+ rw [pair_starts .exponents j.val hj, start, hmode, hlen] at hs
+ rw [pair_exp_bits hi hle hfit bits a b]
+ change RAMSerialization.arrayBits t Z ((RAMSerialization.arrayBits t Z).symm _) j = _
+ rw [Equiv.apply_symm_apply]
+ change bits _ = bits site
+ apply congrArg bits
+ apply Fin.ext
+ change 1+(width (h+1) Δ (2*i)+(b.val+Z*a.val)) = site.val
+ rw [Nat.mul_comm Z a.val]
+ omega
+
+theorem pair_padding (j : Fin (Δ-(1+t*Z))) (site : Fin (width (h+1) Δ i))
+ (hs : site.val = (span .pair (width (h+1) Δ i) Δ (t*Z) 0 .padding).1 + j.val) :
+ (firstHalfLayout h Δ i t Z hi hle hfit bits).2.2.2 j = bits site := by
+ have hlen := LiveHeaderDescriptors.pair_exterior h Δ i hi hle
+ have hw := width_double h Δ i hi hle
+ have hmode : mode (width (h+1) Δ i) = 1 := by rw [mode, hw, ite_eq_right (by omega)]
+ have hstart : start .pair (width (h+1) Δ i) Δ (t*Z) 0 .padding = 1+width (h+1) Δ (2*i)+t*Z := by
+ simp [start,hmode,hlen,exponents,config]
+ have hj : j.val < count .pair (width (h+1) Δ i) Δ (t*Z) 0 .padding := by
+ rw [count, hstart, hw]
+ have := j.isLt
+ omega
+ rw [pair_starts .padding j.val hj, hstart] at hs
+ change bits _ = bits site
+ apply congrArg bits
+ apply Fin.ext
+ change 1+(width (h+1) Δ (2*i)+(t*Z+j.val)) = site.val
+ omega
+
+end Pair
+
+section Tail
+
+variable {h Δ i c : ℕ} (hhalf : 2^h ≤ i) (hend : i < 2^(h+1)) (hfit : 1+c ≤ Δ)
+variable (bits : Bits (width (h+1) Δ i))
+
+theorem tail_mode (site : Fin (width (h+1) Δ i)) (hs : site.val = 0) :
+ (tailLayout h Δ i c hhalf hend hfit bits).1 = bits site := by
+ change bits _ = bits site
+ apply congrArg bits
+ exact Fin.ext hs.symm
+
+theorem tail_config (j : Fin c) (site : Fin (width (h+1) Δ i))
+ (hs : site.val = (span .tail (width (h+1) Δ i) Δ 0 c .config).1 + j.val) :
+ (tailLayout h Δ i c hhalf hend hfit bits).2.1 j = bits site := by
+ have hc : c ≠ 0 := fun he => by have := j.isLt; omega
+ have hΔ : Δ ≠ 0 := by omega
+ simp [span, count, start, mode, exterior, exponents, config, width_tail h Δ i hhalf hend, hc, hΔ] at hs
+ change bits _ = bits site
+ apply congrArg bits
+ exact Fin.ext hs.symm
+
+theorem tail_padding (j : Fin (Δ-(1+c))) (site : Fin (width (h+1) Δ i))
+ (hs : site.val = (span .tail (width (h+1) Δ i) Δ 0 c .padding).1 + j.val) :
+ (tailLayout h Δ i c hhalf hend hfit bits).2.2 j = bits site := by
+ have hΔ : Δ ≠ 0 := by omega
+ have hp : Δ-(1+c) ≠ 0 := fun he => by have := j.isLt; omega
+ simp [span, count, start, mode, exterior, exponents, config, width_tail h Δ i hhalf hend, hp, hΔ] at hs
+ change bits _ = bits site
+ apply congrArg bits
+ apply Fin.ext
+ change 1+(c+j.val) = site.val
+ omega
+
+end Tail
+/-- The field runner tests exactly these bits for zero. -/
+def ZeroSlice {W : ℕ} (bits : Bits W) (iv : ℕ × ℕ) : Prop :=
+ ∀ (j : ℕ) (site : Fin W), j < iv.2 → site.val = iv.1 + j → bits site = false
+
+private theorem decoded_zero {W n : ℕ} (bits : Bits W) (iv : ℕ × ℕ) (field : Fin n → Bool)
+ (hlen : iv.2 = n) (hfit : iv.1 + iv.2 ≤ W)
+ (hphys : ∀ (j : Fin n) (site : Fin W), site.val = iv.1+j.val → field j = bits site) :
+ ZeroSlice bits iv ↔ field = fun _ => false := by
+ constructor
+ · intro hz
+ funext j
+ have hj := j.isLt
+ let site : Fin W := ⟨iv.1+j.val,by omega⟩
+ rw [hphys j site rfl]
+ exact hz j.val site (by omega) rfl
+ · intro h j site hj hs
+ let k : Fin n := ⟨j,by omega⟩
+ rw [← hphys k site hs, h]
+
+/-- Unit mode accepts exactly the all-zero cut once its mode bit is checked. -/
+theorem unit_zero_iff {W : ℕ} (bits : Bits W) (Δ e c : ℕ) :
+ ((∀ site : Fin W, site.val = 0 → bits site = false) ∧
+ ZeroSlice bits (span .unit W Δ e c .padding)) ↔ ∀ site, bits site = false := by
+ constructor
+ · rintro ⟨hm,hz⟩ site
+ by_cases h0 : site.val = 0
+ · exact hm site h0
+ · have h := site.isLt
+ have hW : W ≠ 0 := by omega
+ have hpad : W-1 ≠ 0 := by omega
+ have hiv : span .unit W Δ e c .padding = (1,W-1) := by
+ simp [span,count,start,mode,exterior,exponents,config,hW,hpad]
+ rw [hiv] at hz
+ exact hz (site.val-1) site (by change _ < W-1; omega) (by change site.val = 1+_; omega)
+ · intro h
+ exact ⟨fun site _ => h site, fun _ site _ _ => h site⟩
+
+/-- The physical padding guard on a first-half cut is exactly the zero
+padding constraint in the typed path equivalence. -/
+theorem pair_padding_zero {h Δ i t Z : ℕ} (hi : 0 < i) (hle : i ≤ 2^h) (hfit : 1+t*Z ≤ Δ)
+ (bits : Bits (width (h+1) Δ i)) :
+ ZeroSlice bits (span .pair (width (h+1) Δ i) Δ (t*Z) 0 .padding) ↔
+ (firstHalfLayout h Δ i t Z hi hle hfit bits).2.2.2 = fun _ => false := by
+ have hw := width_double h Δ i hi hle
+ have hlen := LiveHeaderDescriptors.pair_exterior h Δ i hi hle
+ have hmode : mode (width (h+1) Δ i) = 1 := by rw [mode, hw, ite_eq_right (by omega)]
+ apply decoded_zero
+ · change width (h+1) Δ i - start .pair (width (h+1) Δ i) Δ (t*Z) 0 .padding = Δ-(1+t*Z)
+ simp [start, hmode, hlen, exponents, config]
+ omega
+ · exact span_fit hfit (by omega) (fun _ => by omega) .padding
+ · exact pair_padding hi hle hfit bits
+
+theorem tail_padding_zero {h Δ i c : ℕ} (hhalf : 2^h ≤ i) (hend : i < 2^(h+1))
+ (hfit : 1+c ≤ Δ) (bits : Bits (width (h+1) Δ i)) :
+ ZeroSlice bits (span .tail (width (h+1) Δ i) Δ 0 c .padding) ↔
+ (tailLayout h Δ i c hhalf hend hfit bits).2.2 = fun _ => false := by
+ have hw := width_tail h Δ i hhalf hend
+ apply decoded_zero
+ · simp [span, count, start, mode, exterior, exponents, config, hw, show Δ ≠ 0 by omega]
+ · exact span_fit (by omega) hfit (fun _ => hw.ge) .padding
+ · exact tail_padding hhalf hend hfit bits
+
+end LiveHeaderDescriptors.Physical
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPrefix.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPrefix.lean
new file mode 100644
index 0000000000..624608bab6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPrefix.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.LiveHeaderProgramRun
+
+/-!
+# Composable native header prefixes
+
+Each prefix starts and ends at a particular stage and memory. This makes
+the transfer write and cursor reset part of the interface between successive
+blocks, including at the boundary between the index and advice scans.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule
+variable {w : ℕ}
+
+/-- A full component run in the actual row, with enough budget for the
+uniform outer instruction cap. -/
+def StageTrace.Good (x : StageTrace w) (s : Sizes) : Prop :=
+ x.fuel ≤ 40 ∧ x.paths = List.replicate (calls s (stage x.id)) [] ∧
+ x.reports.length = calls s (stage x.id) ∧ ∀ r ∈ x.reports, r.probes ≤ probes (stage x.id)
+
+/-- The source stage runs from the given cursor zero and accepts. -/
+structure StageTrace.Exec (x : StageTrace w) (s : Sizes) (base : ℕ) (m : Memory w) : Prop where
+ source : runSegment ((stageTemplate (stage x.id)).2.instantiate w (rowData w s base (stage x.id))).program
+ x.fuel (some 0) m x.paths = some x.reports
+ accept : endState (some 0) x.reports = none
+ frame : LiveStageLink.PreservesTagOnReturns (Fin.ofNat _ base) m x.reports
+
+/-- A consecutive sequence of executed header stages whose transferred memory and next stage
+match the entry to each succeeding call. -/
+inductive StagePrefix (s : Sizes) (base : ℕ) :
+ Option StageId → Memory w → List (StageTrace w) → Option StageId → Memory w → Prop
+ | nil (id : Option StageId) (m : Memory w) : StagePrefix s base id m [] id m
+ | cons (x : StageTrace w) {m : Memory w} {xs : List (StageTrace w)} {dest : Option StageId} {final : Memory w}
+ (localRun : x.Exec s base m)
+ (rest : StagePrefix s base (next x.id) (x.finalMem (Fin.ofNat _ base) m) xs dest final) :
+ StagePrefix s base (some x.id) m (x :: xs) dest final
+
+theorem StagePrefix.single {s : Sizes} {base : ℕ} {m : Memory w} {x : StageTrace w}
+ (hx : x.Exec s base m) :
+ StagePrefix s base (some x.id) m [x] (next x.id) (x.finalMem (Fin.ofNat _ base) m) :=
+ .cons x hx (.nil _ _)
+
+theorem StagePrefix.append {s : Sizes} {base : ℕ} {i j k : Option StageId} {m n o : Memory w}
+ {xs ys : List (StageTrace w)} (a : StagePrefix s base i m xs j n) (b : StagePrefix s base j n ys k o) :
+ StagePrefix s base i m (xs++ys) k o := by
+ induction a with
+ | nil => exact b
+ | cons x run _ ih => exact .cons x run (ih b)
+
+theorem StagePrefix.finish {s : Sizes} {base : ℕ} {i j : Option StageId} {m n : Memory w}
+ {xs ys : List (StageTrace w)} (a : StagePrefix s base i m xs j n) (b : StageRuns s base j n ys) :
+ StageRuns s base i m (xs++ys) := by
+ induction a with
+ | nil => exact b
+ | cons x run _ ih => exact .cons x run.source run.accept run.frame (ih b)
+
+theorem StagePrefix.finalMemory {s : Sizes} {base : ℕ} {i j : Option StageId} {m n : Memory w}
+ {xs : List (StageTrace w)} (a : StagePrefix s base i m xs j n) :
+ LiveHeaderProgram.finalMemory (Fin.ofNat _ base) m xs = n := by
+ induction a with
+ | nil => rfl
+ | cons _ _ _ ih => exact ih
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPrefixCancel.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPrefixCancel.lean
new file mode 100644
index 0000000000..91e7f3aeda
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPrefixCancel.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.LiveHeaderUnique
+
+/-!
+# Deterministic prefixes of accepting RAM paths
+
+An empty-choice prefix ending at a persistent state fixes its reports and
+memory effects in any accepting execution from the same initial state.
+The remaining branch inputs execute from the resulting physical memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+theorem accepted_suffix_of_empty_prefix {P : Program w C} {fuel n : ℕ}
+ {s : Option (Word w)} {st : Word w} {m : Memory w} {rs outs : List (Report w)}
+ {bs : List (List Bool)}
+ (hr : runSegment P fuel s m (List.replicate n []) = some rs) (he : endState s rs = some st)
+ (h : runSegment P fuel s m bs = some outs) (halt : endState s outs = none) :
+ ∃ btail rtail, bs = List.replicate n [] ++ btail ∧ outs = rs ++ rtail ∧
+ runSegment P fuel (some st) (after m (eventLog rs)) btail = some rtail ∧
+ endState (some st) rtail = none := by
+ induction n generalizing s m rs bs outs with
+ | zero =>
+ simp only [List.replicate_zero,runSegment,Option.some.injEq] at hr
+ subst rs
+ change s = some st at he
+ subst s
+ exact ⟨bs,outs,rfl,rfl,h,halt⟩
+ | succ n ih =>
+ rw [List.replicate_succ] at hr ⊢
+ cases s with
+ | none => simp [runSegment] at hr
+ | some start =>
+ cases bs with
+ | nil => simp [runSegment] at h; subst outs; contradiction
+ | cons b bs =>
+ simp only [runSegment] at hr h
+ cases hfirst : execute P fuel (P.start start) m [] with
+ | none => simp [hfirst] at hr
+ | some r =>
+ cases hother : execute P fuel (P.start start) m b with
+ | none => simp [hother] at h
+ | some t =>
+ obtain ⟨rfl,rfl⟩ := execute_empty_forces hfirst hother
+ simp only [hfirst,Option.map_eq_some_iff] at hr h
+ obtain ⟨rest,hrest,rfl⟩ := hr
+ obtain ⟨other,hrun,rfl⟩ := h
+ obtain ⟨btail,rtail,rfl,rfl,htail,hstop⟩ := ih hrest he hrun halt
+ refine ⟨btail,rtail,rfl,rfl,?_,hstop⟩
+ simpa only [eventLog,List.flatMap_cons,after,List.foldl_append] using htail
+
+/-- A rejected call immediately after such a prefix excludes every
+accepting branch path, even if that path uses different choice lists. -/
+theorem no_accept_after_empty_prefix {P : Program w C} {fuel n : ℕ}
+ {s : Option (Word w)} {st : Word w} {m : Memory w} {rs : List (Report w)}
+ (hr : runSegment P fuel s m (List.replicate n []) = some rs) (he : endState s rs = some st)
+ (reject : ∀ b, execute P fuel (P.start st) (after m (eventLog rs)) b = none) :
+ ¬∃ bs outs, runSegment P fuel s m bs = some outs ∧ endState s outs = none := by
+ rintro ⟨bs,outs,h,halt⟩
+ obtain ⟨btail,rtail,_,_,hrest,hend⟩ := accepted_suffix_of_empty_prefix hr he h halt
+ cases btail with
+ | nil => simp [runSegment] at hrest; subst rtail; contradiction
+ | cons b rest => simp [runSegment,reject b] at hrest
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPrefixReject.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPrefixReject.lean
new file mode 100644
index 0000000000..941888017d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPrefixReject.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.LiveHeaderPrefixRun
+import OAI.Computability.VPVNP.LiveHeaderPrefixCancel
+import OAI.Computability.VPVNP.LiveStageLinkInversion
+
+/-! # Rejection at a reached stage excludes all accepting live-header paths -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule
+
+variable {w : ℕ} {s : Sizes} {base cap : ℕ}
+variable {fromId : Option StageId} {failed : StageId} {m atStage : Memory w} {xs : List (StageTrace w)}
+
+/-- The single native header stage instantiated with its own row of public operands. -/
+abbrev nativeStage (w : ℕ) (s : Sizes) (base : ℕ) (i : StageId) :=
+ ((stageTemplate (stage i)).2.instantiate w (rowData w s base (stage i))).program
+
+/-- The complete linked header program instantiated at the given word width and workspace base. -/
+abbrev nativeHeader (w : ℕ) (s : Sizes) (base : ℕ) := (program.instantiate w (publicData w s base)).program
+
+/-- For a deterministic successful prefix, an accepted path would have to
+continue from its verified postmemory, persistent word zero, and actual tag. -/
+private theorem StagePrefix.suffix_of_accepted (p : StagePrefix s base fromId m xs (some failed) atStage)
+ (good : ∀ x ∈ xs, x.Good s) (hfits : stages.length ≤ 2^w) (hcap : 40+2*stages.length+5 ≤ cap)
+ (htag : ∀ i, fromId = some i → m (Fin.ofNat (2^w) base).val = LiveStageLink.tagWord w i)
+ {bs : List (List Bool)} {outs : List (Report w)}
+ (hr : runSegment (nativeHeader w s base) cap (fromId.map (fun _ => 0)) m bs = some outs)
+ (he : endState (fromId.map (fun _ => (0 : Word w))) outs = none) :
+ atStage (Fin.ofNat (2^w) base).val = LiveStageLink.tagWord w failed ∧
+ ∃ bits rs, runSegment (nativeHeader w s base) cap (some 0) atStage bits = some rs ∧
+ endState (some 0) rs = none := by
+ have room (x : StageTrace w) (hx : x ∈ xs) : x.fuel+2*stages.length+5 ≤ cap := by
+ have := (good x hx).1; omega
+ obtain ⟨hpre,hstate,hmem,ht⟩ := p.run hfits room htag
+ have hempty : xs.flatMap StageTrace.paths = List.replicate (xs.flatMap StageTrace.paths).length [] := by
+ apply List.eq_replicate_length.mpr
+ intro b hb
+ obtain ⟨x,hx,hb⟩ := List.mem_flatMap.mp hb
+ rw [(good x hx).2.1] at hb
+ exact (List.mem_replicate.mp hb).2
+ rw [hempty] at hpre
+ obtain ⟨bt,rt,_,_,hr',he'⟩ := accepted_suffix_of_empty_prefix hpre hstate hr he
+ rw [hmem] at hr'
+ exact ⟨ht failed rfl,bt,rt,hr',he'⟩
+
+/-- If the reached component has no accepting source segment, its native
+linker cannot advance beyond that stage or accept. Continuing source calls
+only need to preserve the one reserved stage-tag word. -/
+theorem StagePrefix.rejects (p : StagePrefix s base fromId m xs (some failed) atStage)
+ (good : ∀ x ∈ xs, x.Good s) (hfits : stages.length ≤ 2^w) (hcap : 40+2*stages.length+5 ≤ cap)
+ (htag : ∀ i, fromId = some i → m (Fin.ofNat (2^w) base).val = LiveStageLink.tagWord w i)
+ (hbad : ∀ fuel bs rs, runSegment (nativeStage w s base failed) fuel (some 0) atStage bs = some rs →
+ endState (some 0) rs ≠ none)
+ (hframe : ∀ fuel (st : Word w) mem b rep,
+ execute (nativeStage w s base failed) fuel ((nativeStage w s base failed).start st) mem b = some rep →
+ rep.result.isSome → after mem rep.events (Fin.ofNat (2^w) base).val = mem (Fin.ofNat (2^w) base).val) :
+ ¬∃ bs outs, runSegment (nativeHeader w s base) cap (fromId.map (fun _ => 0)) m bs = some outs ∧
+ endState (fromId.map (fun _ => (0 : Word w))) outs = none := by
+ rintro ⟨bs,outs,hr,he⟩
+ obtain ⟨ht,bits,rs,hs,hstop⟩ := p.suffix_of_accepted good hfits hcap htag hr he
+ let addr : Word w := Fin.ofNat _ base
+ obtain ⟨before,_,source,_,hr',ha'⟩ := LiveStageLink.recover_accepting_stage component next (bank w s base) addr failed
+ hfits (by omega : 2*stages.length+2 ≤ cap) 0 atStage bits rs ht (by
+ intro st mem b rep h success
+ rw [component_start] at h
+ exact hframe _ st mem b rep h success) hs hstop
+ rw [run_component] at hr'
+ exact hbad _ before source hr' ha'
+
+/-- Immediate rejection at a mode check needs no assumptions on that
+component's behavior at other memories. -/
+theorem StagePrefix.rejects_entry (p : StagePrefix s base fromId m xs (some failed) atStage)
+ (good : ∀ x ∈ xs, x.Good s) (hfits : stages.length ≤ 2^w) (hcap : 40+2*stages.length+5 ≤ cap)
+ (htag : ∀ i, fromId = some i → m (Fin.ofNat (2^w) base).val = LiveStageLink.tagWord w i)
+ (hbad : ∀ fuel bits, execute (nativeStage w s base failed) fuel ((nativeStage w s base failed).start 0) atStage bits = none) :
+ ¬∃ bs outs, runSegment (nativeHeader w s base) cap (fromId.map (fun _ => 0)) m bs = some outs ∧
+ endState (fromId.map (fun _ => (0 : Word w))) outs = none := by
+ rintro ⟨bs,outs,hr,he⟩
+ obtain ⟨ht,bits,rs,hs,hstop⟩ := p.suffix_of_accepted good hfits hcap htag hr he
+ cases bits with
+ | nil => simp [runSegment] at hs; subst rs; contradiction
+ | cons b bits =>
+ simp only [runSegment] at hs
+ cases hcall : execute (nativeHeader w s base) cap ((nativeHeader w s base).start 0) atStage b with
+ | none => simp [hcall] at hs
+ | some r =>
+ obtain ⟨rep, hsrc, _⟩ := LiveStageLink.recover_call component next (bank w s base) (Fin.ofNat _ base) failed
+ hfits (by omega : 2*stages.length+2 ≤ cap) 0 atStage b r ht hcall
+ rw [component_start] at hsrc
+ change execute (nativeStage w s base failed) _ ((nativeStage w s base failed).start 0) atStage b = _ at hsrc
+ rw [hbad] at hsrc
+ contradiction
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPrefixRun.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPrefixRun.lean
new file mode 100644
index 0000000000..d89bf2ba2e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPrefixRun.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.LiveHeaderPrefix
+import OAI.Computability.VPVNP.LiveHeaderUnique
+
+/-! # Executing a partial header schedule and ruling out paths after rejection -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule
+
+variable {w : ℕ}
+
+/-- The actual linked header machine reaches the scheduled suffix with the
+specified persistent word, memory and stage tag. -/
+theorem StagePrefix.run {s : Sizes} {base cap : ℕ} {fromId toId : Option StageId}
+ {m out : Memory w} {xs : List (StageTrace w)} (a : StagePrefix s base fromId m xs toId out)
+ (hfits : stages.length ≤ 2^w) (hroom : ∀ x ∈ xs, x.fuel+2*stages.length+5 ≤ cap)
+ (htag : ∀ i, fromId = some i → m (Fin.ofNat (2^w) base).val = LiveStageLink.tagWord w i) :
+ let addr : Word w := Fin.ofNat _ base
+ let outs := xs.flatMap (fun x => x.output addr)
+ let initial := fromId.map (fun _ => (0 : Word w))
+ runSegment (program.instantiate w (publicData w s base)).program cap initial m (xs.flatMap StageTrace.paths) = some outs ∧
+ endState initial outs = toId.map (fun _ => (0 : Word w)) ∧ after m (eventLog outs) = out ∧
+ (∀ i, toId = some i → out addr.val = LiveStageLink.tagWord w i) := by
+ induction a with
+ | nil => exact ⟨rfl,rfl,rfl,htag⟩
+ | @cons x m xs finalId finalMem run _ ih =>
+ let addr : Word w := Fin.ofNat _ base
+ have hc := (run_component s base x.id x.fuel (some 0) m x.paths).trans run.source
+ obtain ⟨hr,hs,hm,_⟩ := LiveStageLink.runSegment_accepting component next (bank w s base) addr
+ x.id hfits (hroom x (by simp)) 0 m x.paths x.reports (htag x.id rfl) run.frame hc run.accept
+ change runSegment (program.instantiate w (publicData w s base)).program cap (some 0) m x.paths = some (x.output addr) at hr
+ change endState (some 0) (x.output addr) = _ at hs
+ change after m (eventLog (x.output addr)) = x.finalMem addr m at hm
+ have ht : ∀ i, next x.id = some i → x.finalMem addr m addr.val = LiveStageLink.tagWord w i := by
+ intro i hi
+ unfold StageTrace.finalMem
+ rw [hi,LiveStageLink.transferMemory_tag]
+ obtain ⟨hr', hs', hm', ht'⟩ := ih (fun y hy => hroom y (List.mem_cons_of_mem _ hy)) ht
+ change runSegment _ cap (some 0) m (x.paths++xs.flatMap StageTrace.paths) =
+ some (x.output addr++xs.flatMap (fun y => y.output addr)) ∧
+ endState (some 0) (x.output addr++xs.flatMap (fun y => y.output addr)) = finalId.map (fun _ => 0) ∧
+ after m (eventLog (x.output addr++xs.flatMap (fun y => y.output addr))) = finalMem ∧ _
+ refine ⟨?_,?_,?_,ht'⟩
+ · rw [PrimedSchedule.runSegment_append,hr]
+ simp only [Option.bind_some,hs,hm]
+ rw [hr']; rfl
+ · rw [endState_append,hs]; exact hs'
+ · have hsplit (u v : List (Report w)) : after m (eventLog (u++v)) = after (after m (eventLog u)) (eventLog v) := by
+ simp [eventLog,after,List.foldl_append]
+ rw [hsplit,hm]; exact hm'
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPrepared.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPrepared.lean
new file mode 100644
index 0000000000..9d85d5091d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPrepared.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.LiveHeaderBootstrap
+import OAI.Computability.VPVNP.LiveHeaderMetadata
+import OAI.Computability.VPVNP.LiveHeaderPrimedStages
+
+/-!
+# The native header prefix before incident-field extraction
+
+Index and advice scans, all scalar dispatches, and both primed-index stages
+run on a single physical memory. The prefix leaves the field buffers zero
+and the processor headers intact.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderWidths LiveHeaderDescriptors
+open LiveHeader PrimedInputRAM ChainAssignments
+
+variable {w d : ℕ}
+
+/-- The scalar field's position in the eleven-stage metadata sequence. -/
+def Metadata.ordinal : Metadata.Field → Fin 11
+ | .width .liveLeft => 0 | .width .liveRight => 1 | .width .primedLeft => 2
+ | .width .primedMiddle => 3 | .width .primedRight => 4
+ | .flag .first => 5 | .flag .middle => 6 | .flag .firstHalf => 7 | .flag .last => 8
+ | .firstTail => 9 | .mode => 10
+
+private theorem metadata_read {s : Sizes} {base i : ℕ} {tag : Mode.Tag} {m out : Memory w}
+ (img : Metadata.Image s base i tag m out 11) (f : Metadata.Field) :
+ Metadata.Correct s i tag f (out (f.address base)) := by
+ have h := img.readback (Metadata.ordinal f) (Metadata.ordinal f).isLt
+ cases f with
+ | width slot => cases slot <;> exact h
+ | flag flag => cases flag <;> exact h
+ | firstTail | mode => exact h
+
+/-- Values at the interface from the primed-index phase to the field scans. -/
+structure Prepared (s : Sizes) (base : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : Mode.Tag) (out : Memory w) : Prop where
+ headers : SiteHeaders d hw advice cuts g out
+ scalars : ∀ f : Metadata.Field, Metadata.Correct s (g.val+1) tag f (out (f.address base))
+ adviceWords : ∀ j : Fin s.advice, out (adviceBase s base+j.val) = encodeBit w (advice j)
+ primedLeft : ∀ j < s.h+2, out (leftIndexBase s base+j) = encodeBit w ((2*(g.val+1)-1).testBit j)
+ primedRight : ∀ j < s.h+2, out (rightIndexBase s base+j) = encodeBit w ((2*(g.val+1)).testBit j)
+ zero : ∀ a, exteriorBase s base .left ≤ a → out a = 0
+
+private theorem scalar_range (base : ℕ) (f : Metadata.Field) :
+ base < f.address base ∧ f.address base < borrowAddr base := by
+ cases f with
+ | width slot => cases slot <;> dsimp [Metadata.Field.address,widthAddr,borrowAddr] <;> omega
+ | flag flag => cases flag <;> dsimp [Metadata.Field.address,flagAddr,borrowAddr] <;> omega
+ | firstTail | mode => dsimp [Metadata.Field.address,tagAddr,firstTailAddr,borrowAddr]; omega
+
+/-- The first fifteen actual stages, with the exact state seen by the
+incoming and outgoing field descriptor scans. -/
+theorem prepared_prefix (s : Sizes) (base : ℕ) (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice)
+ (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (tag : Mode.Tag)
+ (hsel : physicalTag cuts g = some tag) (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d)
+ (scratch : 2^d ≤ base) (fit : limit s base ≤ 2^w) :
+ ∃ xs out, StagePrefix s base (some (⟨0,by decide⟩ : StageId)) (physicalMemory (d := d) hw advice cuts g)
+ xs (some (⟨15,by decide⟩ : StageId)) out ∧ (∀ x ∈ xs, x.Good s) ∧
+ Prepared (d := d) s base hw advice cuts g tag out := by
+ obtain ⟨a,ma,ha,ga,ready⟩ := index_advice_prefix s base hw advice cuts g indices adv scratch fit
+ obtain ⟨b,mb,hb,gb,im⟩ := Metadata.run_prefix s base d advice cuts g tag (scalarFit_of_limit fit) scratch
+ ma ready.headers ready.summary 11 le_rfl (fun _ => hsel)
+ have indexInput (j : ℕ) (hj : j < s.h+1) : mb (indexBase base+j) = encodeBit w ((g.val+1).testBit j) :=
+ (im.frame _ (Or.inr (by dsimp [indexBase]; omega))).trans (ready.index j (by omega))
+ obtain ⟨c,out,hc,gc,primed⟩ := PrimedStages.primed_prefix s base fit g mb indexInput
+ have hbase : (Fin.ofNat (2^w) base).val = base := by
+ apply Nat.mod_eq_of_lt
+ rw [limit_eq] at fit
+ omega
+ have keep (a : ℕ) (ht : a ≠ base) (hr : a ≠ borrowAddr base)
+ (hl : a < leftIndexBase s base ∨ leftIndexBase s base+(s.h+2) ≤ a)
+ (hr' : a < rightIndexBase s base ∨ rightIndexBase s base+(s.h+2) ≤ a) : out a = mb a := by
+ rw [primed.frame a hr hl hr']
+ simp only [LiveStageLink.transferMemory,writeMemory,hbase,ht,↓reduceIte]
+ refine ⟨(a++b)++c,out,(ha.append hb).append hc,?_,?_,?_,?_,primed.left,primed.right,?_⟩
+ · intro x hx
+ rcases List.mem_append.mp hx with hx | hx
+ · rcases List.mem_append.mp hx with hx | hx
+ · exact ga x hx
+ · exact gb x hx
+ · exact gc x hx
+ · intro v
+ have hv := v.isLt.trans_le scratch
+ rw [keep _ hv.ne (by dsimp [borrowAddr]; omega) (Or.inl (by
+ dsimp [leftIndexBase,populationAddr,highAddr,indexBase]; omega)) (Or.inl (by
+ dsimp [rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase]; omega))]
+ exact (im.frame _ (Or.inl hv)).trans (ready.headers v)
+ · intro f
+ have ⟨hl,hr⟩ := scalar_range base f
+ have hL : f.address base < leftIndexBase s base := by
+ dsimp [borrowAddr] at hr
+ dsimp [leftIndexBase,populationAddr,highAddr,indexBase]
+ omega
+ have hR : f.address base < rightIndexBase s base := by dsimp [rightIndexBase]; omega
+ rw [keep _ hl.ne' hr.ne (Or.inl hL) (Or.inl hR)]
+ exact metadata_read im f
+ · intro j
+ let atAdvice := adviceBase s base+j.val
+ have hright : rightIndexBase s base+(s.h+2) ≤ atAdvice := by dsimp [atAdvice,adviceBase]; omega
+ have hleft : leftIndexBase s base+(s.h+2) ≤ atAdvice := by dsimp [rightIndexBase] at hright; omega
+ have hhi : base+14 < atAdvice := by dsimp [leftIndexBase,populationAddr,highAddr,indexBase] at hleft; omega
+ change out atAdvice = _
+ rw [keep _ (by omega) (by dsimp [borrowAddr]; omega) (Or.inr hleft) (Or.inr hright)]
+ exact (im.frame _ (Or.inr (by omega))).trans (ready.adviceWords j)
+ · intro a ha
+ have hright : rightIndexBase s base+(s.h+2) ≤ a := by dsimp [exteriorBase,adviceBase] at ha; omega
+ have hleft : leftIndexBase s base+(s.h+2) ≤ a := by dsimp [rightIndexBase] at hright; omega
+ have hpop : populationAddr s base < a := by dsimp [leftIndexBase] at hleft; omega
+ have hhi : base+14 < a := by dsimp [populationAddr,highAddr,indexBase] at hpop; omega
+ rw [keep _ (by omega) (by dsimp [borrowAddr]; omega) (Or.inr hleft) (Or.inr hright),
+ im.frame _ (Or.inr (by omega)),ready.frame _ (by omega) (Or.inr hpop) (Or.inr ha)]
+ simp [physicalMemory,RAMMemory.initialMemory,show ¬a < 2^d by omega]
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPrimedProtected.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPrimedProtected.lean
new file mode 100644
index 0000000000..05c1c11598
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPrimedProtected.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.LiveHeaderPrimedStages
+import OAI.Computability.VPVNP.LiveHeaderProtectedCore
+
+/-!
+# Protected memory in the primed header stages
+
+The digit guard bounds both shifted output addresses, even for an arbitrary
+persistent state. The digit and borrow values read from memory can be arbitrary
+words since they only determine the data stored at those addresses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.PrimedStages
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM LiveHeaderSchedule
+open LiveHeader.PrimedGroupIndices
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Every successful initialization call preserves all words below the stage tag. -/
+theorem init_protected (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w)
+ (fuel : ℕ) (st : Word w) (m : Memory w) (bits : List Bool) (rep : Report w)
+ (h : let P := ((stageTemplate .primedInit).2.instantiate w (rowData w s base .primedInit)).program
+ execute P fuel (P.start st) m bits = some rep) :
+ ∀ a < base, after m rep.events a = m a := by
+ let pub := operands w s base
+ have hrow : rowData w s base .primedInit ∘ includeFin (by decide : 4 ≤ 17) = pub := by
+ funext j
+ fin_cases j <;> rfl
+ have hentry := entry_start ((lines setup (by decide)).template none) (by decide) (by decide)
+ (rowData w s base .primedInit) fuel st m bits
+ rw [hrow] at hentry
+ obtain ⟨_,mem,hexec,_⟩ := (Flow.template_execute_iff (lines setup (by decide)) none pub st
+ (fun _ => 0) (fun _ => 0) m fuel bits rep).mp (hentry.symm.trans h)
+ have ht := (PrimedCounter.Admin.exec_lines_iff_trace (by decide : setup ≠ [])).mp hexec
+ rw [LiveHeader.trace_after ht]
+ have hm : initialized pub m = mem := by
+ simp (config := { decide := true }) [setup, trace, Op.effect, Function.update] at ht
+ exact ht.2.2
+ rw [← hm]
+ obtain ⟨_,hl,hr,hb,_,_⟩ := operand_values s base fit
+ intro a ha
+ have l : a ≠ leftIndexBase s base := by unfold leftIndexBase populationAddr highAddr indexBase; omega
+ have r : a ≠ rightIndexBase s base := by unfold rightIndexBase leftIndexBase populationAddr highAddr indexBase; omega
+ have b : a ≠ borrowAddr base := by unfold borrowAddr; omega
+ simp only [initialized, pub, writeMemory, hb, hl, hr, ite_eq_right b, ite_eq_right r, ite_eq_right l]
+
+private theorem digit_writes (pub : Fin 4 → Word w) (st : Word w) (m : Memory w) :
+ let P := ((template digit 11).instantiate w pub).program
+ ∃ r : Report w, execute P 21 (P.start st) m [] = some r ∧
+ ∀ a, a ≠ (pub 1 + (st+1)).val → a ≠ (pub 2 + (st+1)).val → a ≠ (pub 3).val →
+ after m r.events a = m a := by
+ dsimp only
+ let x := m (pub 0 + st).val
+ let c := m (pub 3).val
+ let b := (1-x)*c
+ let es : List (Event w) := [.tick, .tick, .tick, .tick, .tick, .read (pub 0 + st) x,
+ .tick, .tick, .tick, .tick, .tick, .read (pub 3) c, .tick, .tick, .tick, .tick, .tick,
+ .write (pub 1 + (st + 1)) (x - c + b + b), .write (pub 2 + (st + 1)) x, .write (pub 3) b]
+ refine ⟨⟨es, some (st+1)⟩, ?_, ?_⟩
+ · change execute ((template digit 11).instantiate w pub).program (1 + digit.length)
+ ⟨_,st,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]
+ simp (config := { decide := true }) [digit, trace, Op.effect, Function.update, es, x, c, b,
+ show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.sub.eval = (· - · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.mul.eval = (· * · : Word w → Word w → Word w) from rfl]
+ · intro a hl hr hb
+ simp only [es, after, List.foldl_cons, List.foldl_nil, update, writeMemory, hl, hr, hb,
+ ite_false]
+
+private theorem shifted_addresses (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w)
+ (st : Word w) (active : st < ((s.h+1 : ℕ) : Word w)) :
+ let pub := operands w s base
+ base ≤ (pub 1 + (st+1)).val ∧ base ≤ (pub 2 + (st+1)).val ∧ base ≤ (pub 3).val := by
+ dsimp only
+ let pub := operands w s base
+ obtain ⟨-,hl,hr,hb,-,hcap⟩ := operand_values s base fit
+ have layout := layout_of_fit s base fit
+ have hc : st.val < s.h+1 := by
+ change st.val < (s.h+1) % (2^w) at active
+ rwa [Nat.mod_eq_of_lt hcap] at active
+ have hleft := offset_val (pub 1) (st.val+1) (by have := layout.leftFit; dsimp [pub]; omega)
+ have hright := offset_val (pub 2) (st.val+1) (by have := layout.rightFit; dsimp [pub]; omega)
+ have hst : (st.val : Word w) = st := Fin.ext (Nat.mod_eq_of_lt st.isLt)
+ simp only [Nat.cast_add, Nat.cast_one, hst] at hleft hright
+ change base ≤ (pub 1 + (st+1)).val ∧ base ≤ (pub 2 + (st+1)).val ∧ base ≤ (pub 3).val
+ rw [hleft,hright]
+ dsimp only [pub]
+ rw [hl,hr,hb]
+ simp only [rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase,borrowAddr]
+ omega
+
+/-- Every successful guarded digit call preserves the protected memory below the stage tag. -/
+theorem digits_protected (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w)
+ (fuel : ℕ) (st : Word w) (m : Memory w) (bits : List Bool) (rep : Report w)
+ (h : let P := ((stageTemplate .primedDigits).2.instantiate w (rowData w s base .primedDigits)).program
+ execute P fuel (P.start st) m bits = some rep) :
+ ∀ a < base, after m rep.events a = m a := by
+ let pub := operands w s base
+ let bound : Word w := (s.h+1 : ℕ)
+ have hrow : rowData w s base .primedDigits ∘ includeFin (by decide : 5 ≤ 17) =
+ LiveHeaderBounded.publicData pub bound := by
+ funext j
+ fin_cases j <;> rfl
+ have he := entry_start (LiveHeaderBounded.bounded (template digit 11)) (by decide) (by decide)
+ (rowData w s base .primedDigits) fuel st m bits
+ rw [hrow] at he
+ intro a ha
+ apply LiveHeaderBounded.frame_any (template digit 11) pub bound fuel st m bits rep (he.symm.trans h) a
+ intro f r active run
+ obtain ⟨out,hex,frame⟩ := digit_writes pub st m
+ obtain ⟨_,rfl⟩ := execute_empty_forces_anyFuel hex run
+ obtain ⟨hl,hr,hb⟩ := shifted_addresses s base fit st active
+ exact frame a (ha.trans_le hl).ne (ha.trans_le hr).ne (ha.trans_le hb).ne
+
+end LiveHeaderProgram.PrimedStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderPrimedStages.lean b/lean/OAI/Computability/VPVNP/LiveHeaderPrimedStages.lean
new file mode 100644
index 0000000000..ec1249ad20
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderPrimedStages.lean
@@ -0,0 +1,428 @@
+import OAI.Computability.VPVNP.LiveHeaderPrefix
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PairedChain
+
+/-!
+# Native primed index stages in the live header program
+
+The setup stage initializes the borrow and both low bits. The following
+bounded stage reads one unpacked group digit per call and writes the shifted
+digits of the two primed indices. The all-zero low digits of the last group
+are included in the same execution, with the borrow still set at the end.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.PrimedStages
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM LiveHeaderSchedule
+open LiveHeader.PrimedGroupIndices
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The four addresses of the original group digits, the two primed digit arrays, and the
+shared borrow cell. -/
+def operands (w : ℕ) (s : Sizes) (base : ℕ) : Fin 4 → Word w :=
+ ![(indexBase base : Word w), (leftIndexBase s base : Word w),
+ (rightIndexBase s base : Word w), (borrowAddr base : Word w)]
+
+private theorem init_row (s : Sizes) (base : ℕ) :
+ rowData w s base .primedInit ∘ includeFin (by decide : 4 ≤ 17) = operands w s base := by
+ funext j
+ fin_cases j <;> rfl
+
+private theorem digits_row (s : Sizes) (base : ℕ) :
+ rowData w s base .primedDigits ∘ includeFin (by decide : 5 ≤ 17) =
+ LiveHeaderBounded.publicData (operands w s base) ((s.h+1 : ℕ) : Word w) := by
+ funext j
+ fin_cases j <;> rfl
+
+theorem operand_values (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w) :
+ ((operands w s base) 0).val = indexBase base ∧
+ ((operands w s base) 1).val = leftIndexBase s base ∧
+ ((operands w s base) 2).val = rightIndexBase s base ∧
+ ((operands w s base) 3).val = borrowAddr base ∧ base < 2^w ∧ s.h+1 < 2^w := by
+ rw [limit_eq] at fit
+ change (indexBase base : Word w).val = _ ∧ (leftIndexBase s base : Word w).val = _ ∧
+ (rightIndexBase s base : Word w).val = _ ∧ (borrowAddr base : Word w).val = _ ∧ _
+ simp only [Fin.val_natCast, indexBase, leftIndexBase, rightIndexBase, populationAddr,
+ highAddr, borrowAddr]
+ repeat' constructor
+ all_goals first | apply Nat.mod_eq_of_lt; omega | omega
+
+/-- The three operands addressed by a digit are disjoint, fit in word memory,
+and all input digits are outside the two output buffers and borrow cell. -/
+theorem layout_of_fit (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w) :
+ Layout (operands w s base) (s.h+1) := by
+ obtain ⟨ha,hl,hr,hb,-,-⟩ := operand_values s base fit
+ rw [limit_eq] at fit
+ constructor
+ all_goals simp only [outside, ha,hl,hr,hb, rightIndexBase,leftIndexBase,populationAddr,
+ highAddr,indexBase,borrowAddr]
+ all_goals omega
+
+theorem tag_outside (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w) :
+ outside (operands w s base) (s.h+1) base := by
+ obtain ⟨-,hl,hr,hb,-,-⟩ := operand_values s base fit
+ simp only [outside, hl, hr, hb, rightIndexBase,leftIndexBase,populationAddr,
+ highAddr,indexBase,borrowAddr]
+ omega
+
+private def setupEvents (pub : Fin 4 → Word w) : List (Event w) :=
+ [.tick, .tick, .tick, .tick, .tick, .write (pub 1) 1, .write (pub 2) 0, .write (pub 3) 1]
+
+private theorem setup_exec (pub : Fin 4 → Word w) (m : Memory w) :
+ let P := (((lines setup (by decide)).template none).instantiate w pub).program
+ execute P 9 (P.start 0) m [] = some ⟨setupEvents pub,none⟩ := by
+ have ht : ∃ rs', trace pub 0 setup (fun _ => 0) m = some (setupEvents pub,rs',initialized pub m) := by
+ simp (config := { decide := true }) [setup,setupEvents,trace,Op.effect,Function.update,initialized]
+ obtain ⟨rs',h⟩ := ht
+ apply (Flow.template_execute_iff _ none pub 0 (fun _ => 0) (fun _ => 0) m 9 [] _).mpr
+ exact ⟨rs', initialized pub m,(PrimedCounter.Admin.exec_lines_iff_trace (by decide)).mpr h,
+ rfl, by change 8 < 9; decide, rfl⟩
+
+/-- The accepting setup call has exactly three writes and initializes the
+three scalar cells before the enclosing linker advances the stage tag. -/
+theorem init_run (s : Sizes) (base : ℕ) (m : Memory w) :
+ let pub := operands w s base
+ let P := ((stageTemplate .primedInit).2.instantiate w (rowData w s base .primedInit)).program
+ ∃ rs, runSegment P 9 (some 0) m [[]] = some rs ∧ endState (some 0) rs = none ∧
+ after m (eventLog rs) = initialized pub m ∧ rs.length = calls s .primedInit ∧
+ (∀ rep ∈ rs, rep.probes = 3 ∧ choiceBits rep.events = []) ∧
+ RAMBuckets.cost Report.probes rs = 4 ∧
+ LiveStageLink.PreservesTagOnReturns (Fin.ofNat _ base) m rs := by
+ dsimp only
+ let rep : Report w := ⟨setupEvents (operands w s base),none⟩
+ have he := entry_start ((lines setup (by decide)).template none) (by decide) (by decide)
+ (rowData w s base .primedInit) 9 0 m []
+ rw [init_row] at he
+ refine ⟨[rep], ?_, rfl, rfl, rfl, ?_, rfl,
+ LiveStageLink.PreservesTagOnReturns.singleton_accept _ _ _ rfl⟩
+ · simp only [stageTemplate, runSegment]
+ rw [he, setup_exec]
+ rfl
+ · intro y hy
+ obtain rfl := List.mem_singleton.mp hy
+ exact ⟨rfl, rfl⟩
+
+/-- Values supplied by the primed initialization stage. -/
+structure Ready (pub : Fin 4 → Word w) (m : Memory w) : Prop where
+ borrow : m (pub 3).val = 1
+ left : m (pub 1).val = 1
+ right : m (pub 2).val = 0
+
+theorem ready_initialized (pub : Fin 4 → Word w) (n : ℕ) (layout : Layout pub n) (m : Memory w) :
+ Ready pub (initialized pub m) := by
+ have hl := layout.borrowLeft
+ have hr := layout.borrowRight
+ have hsep := layout.outputsApart
+ constructor <;> simp only [initialized,writeMemory,ite_true,show (pub 1).val ≠ (pub 3).val by omega,
+ show (pub 1).val ≠ (pub 2).val by omega,show (pub 2).val ≠ (pub 3).val by omega,ite_false]
+
+private theorem ready_inv {pub : Fin 4 → Word w} {i n : ℕ} (hi : 0 < i) {m : Memory w}
+ (ready : Ready pub m) : Invariant pub i n 0 m m := by
+ have hodd : (2*i-1).testBit 0 = true := by simp [Nat.testBit_eq_decide_div_mod_eq]; omega
+ have heven : (2*i).testBit 0 = false := by simp [Nat.testBit_eq_decide_div_mod_eq]
+ refine ⟨ready.borrow, ?_, ?_, fun _ _ => rfl⟩
+ · intro j hj
+ obtain rfl : j = 0 := by omega
+ simpa [hodd,encodeBit] using ready.left
+ · intro j hj
+ obtain rfl : j = 0 := by omega
+ simpa [heven,encodeBit] using ready.right
+
+private abbrev digitMachine (w : ℕ) (s : Sizes) (base : ℕ) :=
+ ((stageTemplate .primedDigits).2.instantiate w (rowData w s base .primedDigits)).program
+
+private theorem digits_execute (s : Sizes) (base : ℕ) (st : Word w) (m : Memory w) :
+ let P := digitMachine w s base
+ let S := (LiveHeaderBounded.machine (template digit 11) (operands w s base) ((s.h+1 : ℕ) : Word w)).program
+ execute P 24 (P.start st) m [] = execute S 24 (S.start st) m [] := by
+ have h := entry_start (LiveHeaderBounded.bounded (template digit 11)) (by decide) (by decide)
+ (rowData w s base .primedDigits) 24 st m []
+ rw [digits_row] at h
+ exact h
+
+/-- Prefix of the bounded source stage, including each active call's choices
+and probes and preservation of the linker's tag at every returned cursor. -/
+private theorem active_digits (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w) (i : ℕ) (hi : 0 < i)
+ (m : Memory w) (ready : Ready (operands w s base) m) (input : stores m (operands w s base 0) (s.h+1) i)
+ (n : ℕ) (hn : n ≤ s.h+1) :
+ let pub := operands w s base
+ let P := digitMachine w s base
+ ∃ rs, runSegment P 24 (some 0) m (List.replicate n []) = some rs ∧
+ endState (some 0) rs = some (n : Word w) ∧
+ Invariant pub i (s.h+1) n m (after m (eventLog rs)) ∧ rs.length = n ∧
+ (∀ rep ∈ rs, rep.probes = 5 ∧ choiceBits rep.events = []) ∧
+ LiveStageLink.PreservesTagOnReturns (Fin.ofNat _ base) m rs := by
+ dsimp only
+ let pub := operands w s base
+ have layout : Layout pub (s.h+1) := layout_of_fit s base fit
+ obtain ⟨-,-,-,-,hbase,hsize⟩ := operand_values s base fit
+ have baseval : (Fin.ofNat (2^w) base).val = base := Nat.mod_eq_of_lt hbase
+ induction n with
+ | zero => exact ⟨[],rfl,rfl,ready_inv hi ready,rfl,by simp,trivial⟩
+ | succ j ih =>
+ obtain ⟨rs,hr,hs,inv,hlen,hcounts,htags⟩ := ih (by omega)
+ let mem := after m (eventLog rs)
+ change Invariant pub i (s.h+1) j m mem at inv
+ have hj : j < s.h+1 := by omega
+ have hx : mem (pub 0 + (j : Word w)).val = encodeBit w (i.testBit j) := by
+ rw [offset_val _ j (by have := layout.inputFit; omega),inv.frame _ (layout.inputOutside j hj)]
+ exact input j hj
+ obtain ⟨es,hd,hm,_,hp,hb⟩ := digit_native pub (j : Word w) mem _ _ hx inv.borrowCell
+ let rep : Report w := ⟨.tick :: .tick :: .tick :: es, some ((j+1 : ℕ) : Word w)⟩
+ have ha : (j : Word w) < ((s.h+1 : ℕ) : Word w) := by
+ change j % 2^w < (s.h+1) % 2^w
+ rwa [Nat.mod_eq_of_lt (hj.trans hsize),Nat.mod_eq_of_lt hsize]
+ have hrun : execute (digitMachine w s base) 24 ((digitMachine w s base).start (j : Word w)) mem [] = some rep := by
+ rw [digits_execute,LiveHeaderBounded.execute_active _ _ _ 21 _ ha,hd]
+ simp only [rep,Nat.cast_add,Nat.cast_one,Option.map_some]
+ have hmem : after mem rep.events = updated pub (j : Word w) mem (i.testBit j) (borrow i j) := hm
+ have inv' : Invariant pub i (s.h+1) (j+1) m (after mem rep.events) := by
+ rw [hmem]
+ exact invariant_succ pub hi layout hj inv
+ have hframe : after mem rep.events (Fin.ofNat (2^w) base).val = mem (Fin.ofNat (2^w) base).val := by
+ rw [baseval,inv'.frame base (tag_outside s base fit), inv.frame base (tag_outside s base fit)]
+ refine ⟨rs ++ [rep], ?_, ?_, ?_, by simp [hlen], ?_, htags.append ⟨fun _ => hframe,trivial⟩⟩
+ · rw [List.replicate_succ',PrimedSchedule.runSegment_append,hr]
+ simp only [Option.bind_some,hs,runSegment,hrun,mem,Option.map_some]
+ · rw [endState_append]; rfl
+ · simpa only [eventLog,List.flatMap_append,List.flatMap_singleton,after,List.foldl_append,mem] using inv'
+ · intro x hx
+ rcases List.mem_append.mp hx with hx | hx
+ · exact hcounts x hx
+ · obtain rfl := List.mem_singleton.mp hx
+ exact ⟨hp,hb⟩
+
+private theorem cost_five (rs : List (Report w)) (h : ∀ x ∈ rs, x.probes = 5) :
+ RAMBuckets.cost Report.probes rs = 6*rs.length := by
+ induction rs with
+ | nil => rfl
+ | cons r rs ih =>
+ rw [RAMBuckets.cost,h r (by simp),ih (fun x hx => h x (List.mem_cons_of_mem _ hx))]
+ simp only [List.length_cons,Nat.mul_add]
+ omega
+
+/-- Readback at the actual scheduled addresses. Every entry is one RAM word
+containing one low-endian digit. The borrow distinguishes the last group.
+All scratch words outside those three output regions retain their values. -/
+structure Output (s : Sizes) (base : ℕ) (g : Fin (2^(s.h+1))) (m out : Memory w) : Prop where
+ left : ∀ j < s.h+2, out (leftIndexBase s base+j) = encodeBit w ((2*(g.val+1)-1).testBit j)
+ right : ∀ j < s.h+2, out (rightIndexBase s base+j) = encodeBit w ((2*(g.val+1)).testBit j)
+ borrow : out (borrowAddr base) = encodeBit w (decide (g.val+1 = 2^(s.h+1)))
+ frame : ∀ a, a ≠ borrowAddr base →
+ (a < leftIndexBase s base ∨ leftIndexBase s base+(s.h+2) ≤ a) →
+ (a < rightIndexBase s base ∨ rightIndexBase s base+(s.h+2) ≤ a) → out a = m a
+
+/-- The complete bounded stage on an arbitrary physical group, including
+the last all-zero scanned index. It accepts after precisely one closing
+call, having used exactly five probes and zero choice bits per active digit. -/
+theorem digits_run (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w) (g : Fin (2^(s.h+1)))
+ (m : Memory w) (ready : Ready (operands w s base) m)
+ (input : ∀ j < s.h+1, m (indexBase base+j) = encodeBit w ((g.val+1).testBit j)) :
+ let P := ((stageTemplate .primedDigits).2.instantiate w (rowData w s base .primedDigits)).program
+ ∃ rs, runSegment P 24 (some 0) m (List.replicate (calls s .primedDigits) []) = some rs ∧
+ endState (some 0) rs = none ∧ Output s base g m (after m (eventLog rs)) ∧
+ rs.length = calls s .primedDigits ∧
+ (∀ rep ∈ rs, rep.probes ≤ probes .primedDigits ∧ choiceBits rep.events = []) ∧
+ RAMBuckets.cost Report.probes rs = 6*(s.h+1)+1 ∧
+ LiveStageLink.PreservesTagOnReturns (Fin.ofNat _ base) m rs := by
+ dsimp only
+ let pub := operands w s base
+ let z := LiveHeaderBounded.closedReport w
+ let bound : Word w := (s.h+1 : ℕ)
+ have hi : 0 < g.val+1 := Nat.zero_lt_succ _
+ obtain ⟨ha,hl,hr,hb,-,-⟩ := operand_values s base fit
+ have hx : stores m (pub 0) (s.h+1) (g.val+1) := by
+ simpa only [pub,stores,ha] using input
+ obtain ⟨rs,hactive,hs,inv,hlen,hcounts,htags⟩ := active_digits s base fit _ hi m ready hx _ le_rfl
+ let mem := after m (eventLog rs)
+ have hclosed : execute (digitMachine w s base) 24 ((digitMachine w s base).start bound) mem [] = some z := by
+ rw [digits_execute,LiveHeaderBounded.execute_closed _ _ _ 20 _ le_rfl]
+ rfl
+ have hfinal : after m (eventLog (rs ++ [z])) = mem := by
+ simp only [eventLog,List.flatMap_append,List.flatMap_singleton,after,List.foldl_append]
+ rfl
+ refine ⟨rs ++ [z], ?_, ?_, ?_, by simp [hlen,calls], ?_, ?_,
+ htags.append (LiveStageLink.PreservesTagOnReturns.singleton_accept _ _ z rfl)⟩
+ · change runSegment (digitMachine w s base) 24 (some 0) m (List.replicate ((s.h+1)+1) []) = _
+ rw [List.replicate_succ',PrimedSchedule.runSegment_append,hactive]
+ dsimp only [bound,mem] at hclosed
+ simp only [Option.bind_some,hs,runSegment,hclosed,Option.map_some]
+ · rw [endState_append]; rfl
+ · rw [hfinal]
+ refine ⟨?_, ?_, ?_, ?_⟩
+ · simpa only [stores,hl] using inv.left
+ · simpa only [stores,hr] using inv.right
+ · simpa only [hb,borrow_endpoint hi g.isLt] using inv.borrowCell
+ · intro a ha₁ ha₂ ha₃
+ exact inv.frame a (by simp only [outside,hl,hr,hb]; omega)
+ · intro x hx
+ rcases List.mem_append.mp hx with hx | hx
+ · exact ⟨(hcounts x hx).1.le,(hcounts x hx).2⟩
+ · obtain rfl := List.mem_singleton.mp hx
+ exact ⟨Nat.zero_le _,rfl⟩
+ · rw [RAMBuckets.cost_append,cost_five rs (fun r hr => (hcounts r hr).1),hlen]
+ rfl
+
+/-- The initialization-to-digit handoff preserves the copied input and
+the three freshly initialized words. -/
+theorem handoff_ready {d : ℕ} (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w)
+ (dest : Option (Fin d)) (m : Memory w) :
+ let pub := operands w s base
+ let out := LiveStageLink.transferMemory (Fin.ofNat _ base) dest (initialized pub m)
+ Ready pub out ∧ (∀ j < s.h+1, out (indexBase base+j) = m (indexBase base+j)) := by
+ dsimp only
+ let pub := operands w s base
+ have layout := layout_of_fit s base fit
+ obtain ⟨ha,hl,hr,hb,hbase,-⟩ := operand_values s base fit
+ have hz : (Fin.ofNat (2^w) base).val = base := Nat.mod_eq_of_lt hbase
+ have hnon (a : ℕ) (h : a ≠ base) :
+ LiveStageLink.transferMemory (Fin.ofNat (2^w) base) dest (initialized pub m) a = initialized pub m a := by
+ cases dest with
+ | none => rfl
+ | some next => simp only [LiveStageLink.transferMemory,writeMemory,hz,ite_eq_right h]
+ have ready := ready_initialized _ _ layout m
+ have ho := tag_outside s base fit
+ simp only [outside,hl,hr,hb] at ho
+ constructor
+ · refine ⟨?_,?_,?_⟩
+ · rw [hnon _ (by rw [hb]; omega)]; exact ready.borrow
+ · rw [hnon _ (by rw [hl]; omega)]; exact ready.left
+ · rw [hnon _ (by rw [hr]; omega)]; exact ready.right
+ · intro j hj
+ have hf := layout.inputOutside j hj
+ simp only [outside,ha,hl,hr,hb] at hf
+ rw [hnon _ (by simp [indexBase]; omega)]
+ simp only [pub,initialized,writeMemory,hb,hl,hr,ite_eq_right hf.1,
+ ite_eq_right (show indexBase base+j ≠ rightIndexBase s base by omega),
+ ite_eq_right (show indexBase base+j ≠ leftIndexBase s base by omega)]
+
+/-- For every group whose doubled index fits, the arrays decode to the
+two primed indices. This includes the whole first half, where they are used. -/
+theorem Output.values {s : Sizes} {base : ℕ} {g : Fin (2^(s.h+1))} {m out : Memory w}
+ (result : Output s base g m out) (hw : 0 < w) (fit : limit s base ≤ 2^w)
+ (hle : g.val+1 < 2^(s.h+1)) :
+ let pub := operands w s base
+ PrimedCounter.GuessWord.value (storedBits out (pub 1) (s.h+2)) = 2*(g.val+1)-1 ∧
+ PrimedCounter.GuessWord.value (storedBits out (pub 2) (s.h+2)) = 2*(g.val+1) := by
+ obtain ⟨-,hl,hr,-,-,-⟩ := operand_values s base fit
+ exact pair_values hw hle (by simpa only [stores,hl] using result.left)
+ (by simpa only [stores,hr] using result.right)
+
+/-- In the last group the mathematical even primed index is the next power
+of two. Its low buffer is zero, its predecessor buffer is all ones, and
+the scalar retains the final borrow. -/
+theorem Output.last_group {s : Sizes} {base : ℕ} {g : Fin (2^(s.h+1))} {m out : Memory w}
+ (result : Output s base g m out) (last : g.val+1 = 2^(s.h+1)) :
+ (∀ j < s.h+2, out (leftIndexBase s base+j) = 1 ∧ out (rightIndexBase s base+j) = 0) ∧
+ out (borrowAddr base) = 1 := by
+ have hpow : 2*(g.val+1) = 2^(s.h+2) := by rw [last,pow_succ 2 (s.h+1),Nat.mul_comm]
+ refine ⟨?_,by simpa [last,encodeBit] using result.borrow⟩
+ intro j hj
+ rw [result.left j hj,result.right j hj,hpow,Nat.testBit_two_pow_sub_one,Nat.testBit_two_pow_of_ne hj.ne']
+ simp [encodeBit,hj]
+
+/-- The first-half buffers are precisely the two group fields queried in
+the auxiliary input. Address arithmetic is the RAM's modular addition;
+the scratch layout ensures that these additions do not wrap. -/
+theorem Output.auxiliary_group_bits {s : Sizes} {base : ℕ} {g : Fin (2^(s.h+1))} {m out : Memory w}
+ (result : Output s base g m out) (fit : limit s base ≤ 2^w) (i : Fin (2^s.h)) (same : g.val = i.val)
+ (advice : CutSchedule.Bits s.advice) (exterior : ExponentTrace.Exterior s.h s.delta) :
+ let pub := operands w s base
+ let hdr := PairedChain.headers advice exterior i
+ ∀ j : Fin (s.h+2),
+ out (pub 1+(j.val : Word w)).val = encodeBit w (hdr (.group 0 j)) ∧
+ out (pub 2+(j.val : Word w)).val = encodeBit w (hdr (.group 1 j)) := by
+ dsimp only
+ intro j
+ have layout := layout_of_fit s base fit
+ have hj := j.isLt
+ obtain ⟨-,hl,hr,-,-,-⟩ := operand_values s base fit
+ have hleft : (2*(g.val+1)-1) = (PairedChain.groupIndex i 0).val := by
+ change 2*(g.val+1)-1 = 2*i.val+0+1
+ omega
+ have hright : 2*(g.val+1) = (PairedChain.groupIndex i 1).val := by
+ change 2*(g.val+1) = 2*i.val+1+1
+ omega
+ rw [offset_val _ j.val (by have := layout.leftFit; omega),
+ offset_val _ j.val (by have := layout.rightFit; omega),hl,hr,
+ result.left j.val hj,result.right j.val hj,hleft,hright]
+ exact ⟨congrArg (encodeBit w) (LiveHeader.testBit_wordBits _ j),congrArg (encodeBit w) (LiveHeader.testBit_wordBits _ j)⟩
+
+private abbrev initId : StageId := ⟨13,by decide⟩
+private abbrev digitId : StageId := ⟨14,by decide⟩
+private abbrev descriptorId : StageId := ⟨15,by decide⟩
+
+/-- Execute and link the two primed stages in their actual positions. The
+frame in the returned output includes the final handoff at the reserved
+stage tag. Every preceding width, flag, physical header and input digit
+outside the writable regions retains its value. -/
+theorem primed_prefix (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w) (g : Fin (2^(s.h+1)))
+ (m : Memory w) (input : ∀ j < s.h+1, m (indexBase base+j) = encodeBit w ((g.val+1).testBit j)) :
+ ∃ xs out, StagePrefix s base (some (⟨13,by decide⟩ : StageId)) m xs
+ (some (⟨15,by decide⟩ : StageId)) out ∧ (∀ x ∈ xs, x.Good s) ∧
+ Output s base g (LiveStageLink.transferMemory (Fin.ofNat _ base) (some (⟨15,by decide⟩ : StageId)) m) out := by
+ let addr : Word w := Fin.ofNat _ base
+ let pub := operands w s base
+ obtain ⟨ri,hir,hia,him,hil,hip,-,hif⟩ := init_run s base m
+ let x : StageTrace w := ⟨initId,9,[[]],ri⟩
+ have hx : x.Exec s base m := ⟨hir,hia,hif⟩
+ have gx : x.Good s := ⟨by change 9 ≤ 40; decide,rfl,hil,fun r h => (hip r h).1.le⟩
+ let m₁ := LiveStageLink.transferMemory addr (some digitId) (initialized pub m)
+ have hmem : x.finalMem addr m = m₁ := by
+ change LiveStageLink.transferMemory addr (some digitId) (after m (eventLog ri)) = _
+ rw [him]
+ obtain ⟨ready,keep⟩ := handoff_ready s base fit (some digitId) m
+ obtain ⟨rd,hdr,hda,result,hdl,hdp,-,hdf⟩ := digits_run s base fit g m₁ ready
+ (fun j hj => (keep j hj).trans (input j hj))
+ let y : StageTrace w := ⟨digitId,24,List.replicate (calls s .primedDigits) [],rd⟩
+ have hy : y.Exec s base m₁ := ⟨hdr,hda,hdf⟩
+ have gy : y.Good s := ⟨by change 24 ≤ 40; decide,rfl,hdl,fun r h => (hdp r h).1⟩
+ have px : StagePrefix s base (some initId) m [x] (some digitId) m₁ := hmem ▸ StagePrefix.single hx
+ have py : StagePrefix s base (some digitId) m₁ [y] (some descriptorId) (y.finalMem addr m₁) := StagePrefix.single hy
+ refine ⟨[x,y],y.finalMem addr m₁,px.append py,?_,?_⟩
+ · intro z hz
+ rcases List.mem_cons.mp hz with rfl | hz
+ · exact gx
+ · exact (List.mem_singleton.mp hz) ▸ gy
+ · let raw := after m₁ (eventLog rd)
+ change Output s base g m₁ raw at result
+ change Output s base g (LiveStageLink.transferMemory addr (some descriptorId) m)
+ (LiveStageLink.transferMemory addr (some descriptorId) raw)
+ obtain ⟨-,hl,hr,hb,hbase,-⟩ := operand_values s base fit
+ have va : addr.val = base := Nat.mod_eq_of_lt hbase
+ have transfer (a : ℕ) (h : a ≠ base) (id : StageId) (mem : Memory w) :
+ LiveStageLink.transferMemory addr (some id) mem a = mem a := by
+ simp only [LiveStageLink.transferMemory,writeMemory,va,ite_eq_right h]
+ have lessLeft : base < leftIndexBase s base := by
+ simp only [leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ have lessRight : base < rightIndexBase s base := by unfold rightIndexBase; omega
+ constructor
+ · intro j hj
+ rw [transfer _ (by omega)]
+ exact result.left j hj
+ · intro j hj
+ rw [transfer _ (by omega)]
+ exact result.right j hj
+ · rw [transfer _ (by unfold borrowAddr; omega)]
+ exact result.borrow
+ · intro a ab al ar
+ by_cases eq : a = base
+ · rw [eq,← va,LiveStageLink.transferMemory_tag,LiveStageLink.transferMemory_tag]
+ · rw [transfer a eq, transfer a eq,result.frame a ab al ar]
+ change LiveStageLink.transferMemory addr (some digitId) (initialized pub m) a = m a
+ rw [transfer a eq]
+ simp only [pub,initialized,writeMemory,hb,hl,hr,ite_eq_right ab,
+ ite_eq_right (show a ≠ rightIndexBase s base by omega),
+ ite_eq_right (show a ≠ leftIndexBase s base by omega)]
+
+end LiveHeaderProgram.PrimedStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderProgram.lean b/lean/OAI/Computability/VPVNP/LiveHeaderProgram.lean
new file mode 100644
index 0000000000..24cca3555e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderProgram.lean
@@ -0,0 +1,164 @@
+import OAI.Computability.VPVNP.LiveHeaderSchedule
+import OAI.Computability.VPVNP.LiveHeaderDescriptors
+import OAI.Computability.VPVNP.LiveHeaderBounded
+import OAI.Computability.VPVNP.LiveHeaderAllocated
+import OAI.Computability.VPVNP.LivePrimedGroupIndices
+import OAI.Computability.VPVNP.LiveStageOperands
+
+/-!
+# The live group's native header program
+
+The same table parses every group and input length. The public-data function
+uses the chain and field sizes and the scratch base. The group number, advice,
+mode, cut lengths, field offsets and payloads come from word-memory probes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM LiveHeaderSchedule
+open LiveHeaderDescriptors
+
+/-- Uniform scratch-register and local public-operand capacities of a stage. -/
+abbrev StageTemplate := (p : ℕ) × Template p 50 17
+
+/-- Embed a smaller register or operand index into a larger bank at the same numerical
+position. -/
+def includeFin {n m : ℕ} (h : n ≤ m) : Fin n ↪ Fin m :=
+ ⟨fun j => j.castLE h, fun _ _ eq => Fin.ext (congrArg (fun x : Fin m => x.val) eq)⟩
+
+/-- Widen a native component template to the common header stage interface of 50 registers and
+17 public operands. -/
+def entry {p r k : ℕ} (T : Template p r k) (hr : r ≤ 50 := by decide)
+ (hk : k ≤ 17 := by decide) : StageTemplate :=
+ ⟨p, LiveStageLink.widen T (includeFin hr) (includeFin hk)⟩
+
+/-- The fixed public operand assignment for the scalar cut-width and flag calculations. -/
+def widthSlots : LiveHeaderWidths.Parameters := ⟨0,1,2,3,4⟩
+/-- The nine public slots assigned to the descriptor worker's width, flags, dimensions, and
+output cells. -/
+def descriptorSlots : LiveHeaderDescriptors.Parameters := ⟨0,1,2,3,4,5,6,7,8⟩
+/-- The four public slots assigned to the field scan's first cursor, source offset,
+destination, and runtime count. -/
+def scanSlots : LiveHeader.Allocated.Parameters := ⟨0,1,2,3⟩
+
+/-- Each stage either accepts after one microcall or is wrapped with a
+public-capacity test. In particular, a zero-capacity scan makes one terminating call. -/
+def stageTemplate : Stage → StageTemplate
+ | .index => entry (LiveHeaderBounded.bounded (template LiveHeader.indexCell 11))
+ | .advice => entry (LiveHeaderBounded.bounded (template (LiveHeader.copyCell 1) 7))
+ | .width slot => entry (LiveHeaderWidths.WidthCode.table widthSlots slot)
+ | .flag f => entry ((LiveHeaderWidths.PhaseCode.block widthSlots f).template none)
+ | .firstTail => entry ((LiveHeaderWidths.PhaseCode.firstTailBlock widthSlots 5).template none)
+ | .mode => entry (LiveHeader.Mode.program.template none)
+ | .primedInit => entry ((lines LiveHeader.PrimedGroupIndices.setup (by decide)).template none)
+ | .primedDigits => entry (LiveHeaderBounded.bounded (template LiveHeader.PrimedGroupIndices.digit 11))
+ | .descriptor side f => entry ((Native.block descriptorSlots side f).template none)
+ | .scan side f => entry (LiveHeaderBounded.bounded
+ (LiveHeader.Allocated.table scanSlots (if side = Side.left then 2 else 3) (decide (f = .padding))))
+
+/-- One row of public operands. The last operand of every bounded stage
+holds the capacity at the position expected by its own wrapper. -/
+def publicRow (s : Sizes) (base : ℕ) (st : Stage) (j : Fin 17) : ℕ :=
+ let widthInputs (out : ℕ) := [s.h+1,s.delta,highAddr s base,populationAddr s base,out,indexBase base]
+ let groupInputs := [indexBase base,leftIndexBase s base,rightIndexBase s base,borrowAddr base]
+ let row := match st with
+ | .index => [indexBase base,highAddr s base,populationAddr s base,s.h+2]
+ | .advice => [0,adviceBase s base,s.advice]
+ | .width slot => widthInputs (widthAddr base slot)
+ | .flag f => widthInputs (flagAddr base f)
+ | .firstTail => widthInputs (firstTailAddr base)
+ | .mode => [widthAddr base .liveLeft,widthAddr base .liveRight,flagAddr base .firstHalf,tagAddr base]
+ | .primedInit => groupInputs
+ | .primedDigits => groupInputs ++ [s.h+1]
+ | .descriptor side _ =>
+ [widthAddr base (if side = Side.left then .liveLeft else .liveRight),tagAddr base,
+ flagAddr base .firstHalf,firstTailAddr base,s.delta,s.e,s.config,offsetAddr base,countAddr base]
+ | .scan side f =>
+ [0,offsetAddr base,dest s base side f,countAddr base] ++ List.replicate 12 0 ++ [s.capacity f]
+ row[j.val]?.getD 0
+
+/-- An index into the fixed list of native live-header stages. -/
+abbrev StageId := Fin stages.length
+/-- An index in the flat bank containing seventeen public words per header stage. -/
+abbrev PublicIndex := Fin (stages.length * 17)
+
+/-- Retrieve the scheduled header operation at a given stage index. -/
+def stage (i : StageId) := stages.get i
+
+/-- Embed a local operand position in the seventeen-word public row of the selected stage. -/
+def rowEmbedding (i : StageId) : Fin 17 ↪ PublicIndex :=
+ ⟨fun j => finProdFinEquiv (i,j), fun _ _ h => (Prod.mk.inj (finProdFinEquiv.injective h)).2⟩
+
+/-- Relocate all public operands into their respective fixed rows. -/
+def component (i : StageId) : Template (stageTemplate (stage i)).1 50 (stages.length*17) :=
+ LiveStageLink.widen (stageTemplate (stage i)).2 (Function.Embedding.refl _) (rowEmbedding i)
+
+/-- Advance to the following header stage, returning no successor at the end of the list. -/
+def next (i : StageId) : Option StageId :=
+ if h : i.val+1 < stages.length then some ⟨i.val+1,h⟩ else none
+
+/-- A standalone executable native template, which accepts only after the
+last padding scan reaches its limit. Inner stage handoffs reset the cursor. -/
+def program := LiveStageLink.linked component next
+
+/-- Exact finite operand vector used by the linked header program. `base`
+also serves as the inner linker's tag address, initially in zero memory. -/
+def publicData (w : ℕ) (s : Sizes) (base : ℕ) : Fin (stages.length*17+1) → Word w :=
+ LiveStageLink.publicData (fun j : PublicIndex =>
+ let pair := finProdFinEquiv.symm j
+ Fin.ofNat _ (publicRow s base (stage pair.1) pair.2)) (Fin.ofNat _ base)
+
+theorem public_at_stage (w : ℕ) (s : Sizes) (base : ℕ) (i : StageId) (j : Fin 17) :
+ publicData w s base ((rowEmbedding i j).castSucc) =
+ Fin.ofNat _ (publicRow s base (stage i) j) := by
+ simp only [publicData,LiveStageLink.publicData,Fin.snoc_castSucc]
+ change Fin.ofNat _ (publicRow s base (stage (finProdFinEquiv.symm (finProdFinEquiv (i,j))).1)
+ (finProdFinEquiv.symm (finProdFinEquiv (i,j))).2) = _
+ rw [Equiv.symm_apply_apply]
+
+theorem public_tag (w : ℕ) (s : Sizes) (base : ℕ) :
+ publicData w s base (Fin.last _) = Fin.ofNat _ base := by simp [publicData,LiveStageLink.publicData]
+
+/-- Public operands before relocation into the combined header table. -/
+def rowData (w : ℕ) (s : Sizes) (base : ℕ) (st : Stage) (j : Fin 17) : Word w :=
+ Fin.ofNat _ (publicRow s base st j)
+
+/-- Read the flattened public operand by recovering its stage row and offset and evaluating the
+corresponding row data. -/
+def bank (w : ℕ) (s : Sizes) (base : ℕ) (j : PublicIndex) : Word w :=
+ let pair := finProdFinEquiv.symm j
+ rowData w s base (stage pair.1) pair.2
+
+theorem bank_row (w : ℕ) (s : Sizes) (base : ℕ) (i : StageId) :
+ bank w s base ∘ rowEmbedding i = rowData w s base (stage i) := by
+ funext j
+ change rowData w s base (stage (finProdFinEquiv.symm (finProdFinEquiv (i,j))).1)
+ (finProdFinEquiv.symm (finProdFinEquiv (i,j))).2 = _
+ rw [Equiv.symm_apply_apply]
+
+theorem entry_start {p r k w : ℕ} (T : Template p r k) (hr : r ≤ 50) (hk : k ≤ 17)
+ (pub : Fin 17 → Word w) (fuel : ℕ) (state : Word w) (m : Memory w) (bits : List Bool) :
+ let big := ((entry T hr hk).2.instantiate w pub).program
+ let small := (T.instantiate w (pub ∘ includeFin hk)).program
+ execute big fuel (big.start state) m bits = execute small fuel (small.start state) m bits :=
+ LiveStageLink.execute_widen_start T _ _ pub fuel state m bits
+
+/-- A call in a linked operand bank executes the original stage with its
+own prescribed public row. The two relocations add no work or branch bits. -/
+theorem component_start (w : ℕ) (s : Sizes) (base : ℕ) (i : StageId) (fuel : ℕ)
+ (state : Word w) (m : Memory w) (bits : List Bool) :
+ let big := ((component i).instantiate w (bank w s base)).program
+ let small := ((stageTemplate (stage i)).2.instantiate w (rowData w s base (stage i))).program
+ execute big fuel (big.start state) m bits = execute small fuel (small.start state) m bits := by
+ simpa only [component,bank_row] using LiveStageLink.execute_widen_start (stageTemplate (stage i)).2
+ (Function.Embedding.refl _) (rowEmbedding i) (bank w s base) fuel state m bits
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderProgramFit.lean b/lean/OAI/Computability/VPVNP/LiveHeaderProgramFit.lean
new file mode 100644
index 0000000000..64842680a7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderProgramFit.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.LiveHeaderScalarStages
+import OAI.Computability.VPVNP.LiveHeaderAllocatedRuns
+import OAI.Computability.VPVNP.LiveHeaderResources
+
+/-!
+# Scratch geometry of the linked live-header program
+
+The native stages use one contiguous scratch allocation after the packed
+processor headers. Its end gives a single word-size bound for all occupied
+cells. Distinct copied fields have disjoint destinations, so later scans
+preserve earlier decoded fields and the fixed scratch prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM LiveHeaderSchedule LiveHeaderWidths LiveHeaderDescriptors
+
+variable {w base : ℕ} {s : Sizes}
+
+/-- All scalar fit requirements follow from the end of the scratch allocation. -/
+theorem scalarFit_of_limit (fit : limit s base ≤ 2^w) : ScalarFit w s base := by
+ have h := fit
+ rw [limit_eq] at h
+ have hd : s.delta ≤ (s.h+1)*s.delta := by rw [Nat.succ_mul]; omega
+ exact ⟨by omega, by omega, by omega, fit⟩
+
+/-- Field capacities fit even when an empty buffer starts exactly at the
+exclusive end of memory. -/
+theorem field_capacity_lt (fit : limit s base ≤ 2^w) (f : Field) : s.capacity f < 2^w := by
+ rw [limit_eq] at fit
+ cases f <;> dsimp [Sizes.capacity] <;> omega
+
+/-- Bound the live cut width before selecting a field. -/
+theorem cut_width_le_capacity (s : Sizes) (i : ℕ) :
+ CutSchedule.width (s.h+1) s.delta i ≤ s.capacity .exterior := by
+ unfold CutSchedule.width Sizes.capacity
+ split_ifs
+ · exact Nat.mul_le_mul_right _ (Nat.sub_le ..)
+ · exact Nat.zero_le _
+
+theorem occupied_le_capacity (s : Sizes) (f : Field) (form : Shape) {W : ℕ}
+ (hW : W ≤ s.capacity .exterior) : (span form W s.delta s.e s.config f).2 ≤ s.capacity f := by
+ cases f <;> cases form <;> simp [span, count, exterior, exponents, config, Sizes.capacity] at * <;> omega
+
+private theorem zero_offset_of_empty (form : Shape) (W d e c : ℕ) (f : Field)
+ (h : (span form W d e c f).2 = 0) : (span form W d e c f).1 = 0 := by
+ change count form W d e c f = 0 at h
+ simp [span,h]
+
+/-- Payload buffers start after the descriptor words and the unpacked
+index/advice fields and end before the next component's allocation. -/
+theorem dest_bounds (s : Sizes) (base : ℕ) (side : Side) (f : Field) (hf : f ≠ .padding) :
+ adviceBase s base + s.advice ≤ dest s base side f ∧
+ dest s base side f + s.capacity f ≤ limit s base := by
+ cases side <;> cases f <;> simp [dest, limit, configBase, exponentBase, exteriorBase, Sizes.capacity] at * <;> omega
+
+/-- Distinct allocated destinations occupy disjoint half-open ranges. -/
+theorem dest_disjoint (s : Sizes) (base : ℕ) {a b : Side} {f g : Field}
+ (hf : f ≠ .padding) (hg : g ≠ .padding) (hne : (a,f) ≠ (b,g)) :
+ dest s base a f + s.capacity f ≤ dest s base b g ∨
+ dest s base b g + s.capacity g ≤ dest s base a f := by
+ cases a <;> cases b <;> cases f <;> cases g <;>
+ simp [dest, configBase, exponentBase, exteriorBase, Sizes.capacity] at * <;> omega
+
+/-- The row of public scan operands gives the constant cursor zero and
+the two allocated descriptor words. -/
+theorem scan_public (fit : limit s base ≤ 2^w) (side : Side) (f : Field) :
+ let p := scalarPub w s base (.scan side f)
+ p scanSlots.firstCursor = 0 ∧
+ (p scanSlots.srcOffsetAddress).val = offsetAddr base ∧
+ (p scanSlots.countAddress).val = countAddr base ∧
+ p scanSlots.destinationBase = Fin.ofNat _ (dest s base side f) := by
+ dsimp only
+ refine ⟨rfl, ?_, ?_, rfl⟩
+ · change (Fin.ofNat _ (offsetAddr base)).val = _
+ apply Nat.mod_eq_of_lt
+ rw [limit_eq] at fit
+ unfold offsetAddr
+ omega
+ · change (Fin.ofNat _ (countAddr base)).val = _
+ apply Nat.mod_eq_of_lt
+ rw [limit_eq] at fit
+ unfold countAddr
+ omega
+
+/-- The scan sizes require only the physical source extent and the allocation
+bound. Its cursor starts at zero for every stage. -/
+theorem scan_sizes (fit : limit s base ≤ 2^w) (side : Side) (f : Field) (iv : ℕ × ℕ)
+ (hcap : iv.2 ≤ s.capacity f) (hs : iv.1 + iv.2 ≤ base) :
+ LiveHeader.Allocated.Sizes scanSlots (scalarPub w s base (.scan side f)) iv (s.capacity f) := by
+ have ha := fit
+ rw [limit_eq] at ha
+ exact ⟨(scan_public fit side f).1,hcap,field_capacity_lt fit f,by omega⟩
+
+private theorem descriptor_before_dest (s : Sizes) (base : ℕ) (side : Side) (f : Field) (hf : f ≠ .padding) :
+ countAddr base < dest s base side f ∧ offsetAddr base < dest s base side f ∧ base < dest s base side f := by
+ have h := (dest_bounds s base side f hf).1
+ dsimp [adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase,countAddr,offsetAddr] at *
+ omega
+
+/-- A full copy-stage layout at the exact public operands. For a zero-length
+field the descriptor writes offset zero, including if the unused destination
+address wraps at the exclusive end of memory. -/
+theorem scan_copyLayout (fit : limit s base ≤ 2^w) (side : Side) (f : Field) (hf : f ≠ .padding)
+ (iv : ℕ × ℕ) (hcap : iv.2 ≤ s.capacity f) (hs : iv.1 + iv.2 ≤ base)
+ (h0 : iv.2 = 0 → iv.1 = 0) :
+ let p := scalarPub w s base (.scan side f)
+ LiveHeader.Allocated.CopyLayout scanSlots p iv ∧
+ LiveHeader.Allocated.Outside (p scanSlots.destinationBase).val iv.2 base := by
+ intro p
+ obtain ⟨_, ho, hc, hd⟩ := scan_public fit side f
+ obtain ⟨_, hmax⟩ := dest_bounds s base side f hf
+ obtain ⟨hcount, hoff, hbase⟩ := descriptor_before_dest s base side f hf
+ by_cases empty : iv.2 = 0
+ · have hfin := (p scanSlots.destinationBase).isLt
+ refine ⟨⟨by simp [empty,h0 empty], by rw [empty, Nat.add_zero]; exact hfin.le, ?_, ?_⟩, ?_⟩
+ all_goals unfold LiveHeader.Allocated.Outside; omega
+ · have he : (p scanSlots.destinationBase).val = dest s base side f := by
+ rw [show p scanSlots.destinationBase = _ from hd]
+ exact Nat.mod_eq_of_lt (by omega)
+ refine ⟨⟨?_, ?_, Or.inl ?_, Or.inl ?_⟩, Or.inl ?_⟩
+ · exact hs.trans (he.symm ▸ hbase.le)
+ · rw [he]
+ omega
+ · exact (show (p scanSlots.srcOffsetAddress).val = _ from ho) ▸ he.symm ▸ hoff
+ · exact (show (p scanSlots.countAddress).val = _ from hc) ▸ he.symm ▸ hcount
+ · exact he.symm ▸ hbase
+
+/-- All scan operands for a descriptor computed on an incident cut. -/
+theorem scan_fit_of_shape (fit : limit s base ≤ 2^w) (side : Side) (f : Field) (tag : ℕ)
+ (half firstTail : Bool) (i : ℕ) (hprefix : s.capacity .exterior ≤ base)
+ (he : 1+s.e ≤ s.delta) (hc : 1+s.config ≤ s.delta) :
+ let W := CutSchedule.width (s.h+1) s.delta i
+ let form := shape side W tag half firstTail
+ let iv := span form W s.delta s.e s.config f
+ let p := scalarPub w s base (.scan side f)
+ LiveHeader.Allocated.Sizes scanSlots p iv (s.capacity f) ∧
+ (f ≠ .padding → LiveHeader.Allocated.CopyLayout scanSlots p iv ∧
+ LiveHeader.Allocated.Outside (p scanSlots.destinationBase).val iv.2 base) := by
+ intro W form iv p
+ have hW := cut_width_le_capacity s i
+ have hb : iv.1+iv.2 ≤ W := span_fit he hc (shape_fit (width_ge_block (s.h+1) s.delta i)) f
+ have hs := hb.trans (hW.trans hprefix)
+ have hcap := occupied_le_capacity s f form hW
+ exact ⟨scan_sizes fit side f iv hcap hs, fun hf =>
+ scan_copyLayout fit side f hf iv hcap hs (zero_offset_of_empty form W s.delta s.e s.config f)⟩
+
+/-- A later copy retains every bit of an earlier, distinct payload field. -/
+theorem preserve_copied_field {a b : Side} {f g : Field} {s : Sizes} {base : ℕ}
+ (hf : f ≠ .padding) (hg : g ≠ .padding) (hne : (a,f) ≠ (b,g))
+ {W : ℕ} {bits : CutSchedule.Bits W} {iv : ℕ × ℕ} {m m' : Memory w} {src len : ℕ} {slot : Fin 4}
+ (hfirst : LiveHeader.CopiedSlice bits iv (dest s base a f) m) (hcap : iv.2 ≤ s.capacity f)
+ (hsecond : LiveHeader.FieldCopy m slot src (dest s base b g) len m') (hcap' : len ≤ s.capacity g) :
+ LiveHeader.CopiedSlice bits iv (dest s base a f) m' := by
+ apply hfirst.congr
+ intro j hj
+ apply hsecond.frame
+ rcases dest_disjoint s base hf hg hne with h | h <;> omega
+
+/-- Copying a payload preserves the packed sites, descriptor words and all
+unpacked index and advice words before the payload area. -/
+theorem fieldCopy_prefix {s : Sizes} {base : ℕ} {side : Side} {f : Field} (hf : f ≠ .padding)
+ {m m' : Memory w} {src len : ℕ} {slot : Fin 4}
+ (hcopy : LiveHeader.FieldCopy m slot src (dest s base side f) len m') {j : ℕ}
+ (hj : j < adviceBase s base + s.advice) : m' j = m j :=
+ hcopy.frame j (Or.inl (hj.trans_le (dest_bounds s base side f hf).1))
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderProgramRun.lean b/lean/OAI/Computability/VPVNP/LiveHeaderProgramRun.lean
new file mode 100644
index 0000000000..d528ceb5d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderProgramRun.lean
@@ -0,0 +1,237 @@
+import OAI.Computability.VPVNP.LiveHeaderProgram
+import OAI.Computability.VPVNP.LiveStageSegments
+import OAI.Computability.VPVNP.LiveHeaderBoundedRun
+
+/-!
+# Composing native live-header stages on shared external memory
+
+The source executions use their own seventeen-word parameter rows. At every
+accepting boundary the native linker updates the reserved tag word and resets
+the cursor. The combined report records each dispatch read and each handoff
+write, with an exact cost in calls and external probes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule
+
+variable {w : ℕ}
+
+/-- Row relocation preserves the native segment of the small stage table. -/
+theorem run_component (s : Sizes) (base : ℕ) (i : StageId) (fuel : ℕ) (st : Option (Word w))
+ (m : Memory w) (bits : List (List Bool)) :
+ runSegment ((component i).instantiate w (bank w s base)).program fuel st m bits =
+ runSegment ((stageTemplate (stage i)).2.instantiate w (rowData w s base (stage i))).program fuel st m bits := by
+ induction bits generalizing st m with
+ | nil => rfl
+ | cons b bits ih =>
+ cases st with
+ | none => rfl
+ | some st =>
+ simp only [runSegment, component_start]
+ cases execute ((stageTemplate (stage i)).2.instantiate w (rowData w s base (stage i))).program fuel
+ (((stageTemplate (stage i)).2.instantiate w (rowData w s base (stage i))).program.start st) m b <;> simp only [ih]
+
+/-- Embed a complete native stage segment in the fixed header register file. -/
+theorem run_entry {p r k : ℕ} (T : Template p r k) (hr : r ≤ 50) (hk : k ≤ 17)
+ (pub : Fin 17 → Word w) (fuel : ℕ) (st : Option (Word w)) (m : Memory w) (bits : List (List Bool)) :
+ runSegment ((entry T hr hk).2.instantiate w pub).program fuel st m bits =
+ runSegment (T.instantiate w (pub ∘ includeFin hk)).program fuel st m bits := by
+ induction bits generalizing st m with
+ | nil => rfl
+ | cons b bits ih =>
+ cases st with
+ | none => rfl
+ | some st =>
+ simp only [runSegment, entry_start]
+ cases execute (T.instantiate w (pub ∘ includeFin hk)).program fuel
+ ((T.instantiate w (pub ∘ includeFin hk)).program.start st) m b <;> simp only [ih]
+
+/-- Reports and branch choices of a complete source stage. -/
+structure StageTrace (w : ℕ) where
+ /-- The header stage whose source reports this trace records. -/
+ id : StageId
+ /-- The source-stage clock used to execute the recorded calls. -/
+ fuel : ℕ
+ /-- The private choice tape supplied to each successive source-stage call. -/
+ paths : List (List Bool)
+ /-- The ordered source reports returned by the recorded calls before linker dispatch and
+ handoff events. -/
+ reports : List (Report w)
+
+/-- The source reports wrapped with the header linker's dispatch and stage-transfer events. -/
+def StageTrace.output (x : StageTrace w) (addr : Word w) : List (Report w) :=
+ x.reports.map (LiveStageLink.linkedReport next addr x.id)
+
+/-- The source cost plus a dispatch probe per report and a transfer probe when the stage has a
+successor. -/
+def StageTrace.cost (x : StageTrace w) :=
+ RAMBuckets.cost Report.probes x.reports + x.reports.length + (if (next x.id).isSome then 1 else 0)
+
+/-- The memory after the source reports and the linker's transfer to the next header stage. -/
+def StageTrace.finalMem (x : StageTrace w) (addr : Word w) (m : Memory w) : Memory w :=
+ LiveStageLink.transferMemory addr (next x.id) (after m (eventLog x.reports))
+
+/-- Source runs in the prescribed order, each with its fresh cursor and the
+memory actually passed from its predecessor. -/
+inductive StageRuns (s : Sizes) (base : ℕ) :
+ Option StageId → Memory w → List (StageTrace w) → Prop
+ | done (m : Memory w) : StageRuns s base none m []
+ | cons (x : StageTrace w) {m : Memory w} {xs : List (StageTrace w)}
+ (source : runSegment ((stageTemplate (stage x.id)).2.instantiate w (rowData w s base (stage x.id))).program
+ x.fuel (some 0) m x.paths = some x.reports)
+ (accept : endState (some 0) x.reports = none)
+ (frame : LiveStageLink.PreservesTagOnReturns (Fin.ofNat _ base) m x.reports)
+ (rest : StageRuns s base (next x.id) (x.finalMem (Fin.ofNat _ base) m) xs) :
+ StageRuns s base (some x.id) m (x :: xs)
+
+/-- Replay a list of header stages in order, including the transfer writes between stages. -/
+def finalMemory (addr : Word w) (m : Memory w) (xs : List (StageTrace w)) : Memory w :=
+ xs.foldl (fun mem x => x.finalMem addr mem) m
+
+/-- Every linked call corresponds to one source call; there are no extra
+handoff calls between stages. -/
+theorem calls_output (addr : Word w) (xs : List (StageTrace w)) :
+ (xs.flatMap (fun x => x.output addr)).length = (xs.map (fun x => x.reports.length)).sum := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih =>
+ simp only [List.flatMap_cons, List.length_append, ih, List.map_cons, List.sum_cons]
+ simp [StageTrace.output]
+
+/-- Execute a complete suffix of the scheduled native header program with
+the original branch inputs. The accepted output and its cost are exact. -/
+theorem run_of_stages (s : Sizes) (base cap : ℕ) (hfits : stages.length ≤ 2^w) {id : Option StageId}
+ {m : Memory w} {xs : List (StageTrace w)} (h : StageRuns s base id m xs)
+ (hroom : ∀ x ∈ xs, x.fuel + 2*stages.length+5 ≤ cap)
+ (htag : ∀ i, id = some i → m (Fin.ofNat (2^w) base).val = LiveStageLink.tagWord w i) :
+ let addr : Word w := Fin.ofNat _ base
+ let out := xs.flatMap (fun x => x.output addr)
+ let st := id.map (fun _ => (0 : Word w))
+ runSegment (program.instantiate w (publicData w s base)).program cap st m (xs.flatMap StageTrace.paths) = some out ∧
+ endState st out = none ∧ after m (eventLog out) = finalMemory addr m xs ∧
+ RAMBuckets.cost Report.probes out = (xs.map StageTrace.cost).sum := by
+ induction h with
+ | done m => exact ⟨rfl, rfl, rfl, rfl⟩
+ | @cons x m xs source accept frame rest ih =>
+ let addr : Word w := Fin.ofNat _ base
+ have hc := (run_component s base x.id x.fuel (some 0) m x.paths).trans source
+ obtain ⟨hr, hs, hm, hcost⟩ := LiveStageLink.runSegment_accepting component next
+ (bank w s base) addr x.id hfits (hroom x (by simp)) 0 m x.paths x.reports
+ (htag x.id rfl) frame hc accept
+ change runSegment (program.instantiate w (publicData w s base)).program cap (some 0) m x.paths = some (x.output addr) at hr
+ change endState (some 0) (x.output addr) = _ at hs
+ change after m (eventLog (x.output addr)) = x.finalMem addr m at hm
+ change RAMBuckets.cost Report.probes (x.output addr) = x.cost at hcost
+ have htag' : ∀ i, next x.id = some i → x.finalMem addr m addr.val = LiveStageLink.tagWord w i := by
+ intro i hi
+ unfold StageTrace.finalMem
+ rw [hi, LiveStageLink.transferMemory_tag]
+ obtain ⟨hr', hs', hm', hcost'⟩ := ih (fun y hy => hroom y (List.mem_cons_of_mem _ hy)) htag'
+ change runSegment _ cap (some 0) m (x.paths ++ xs.flatMap StageTrace.paths) =
+ some (x.output addr ++ xs.flatMap (fun y => y.output addr)) ∧
+ endState (some 0) (x.output addr ++ xs.flatMap (fun y => y.output addr)) = none ∧
+ after m (eventLog (x.output addr ++ xs.flatMap (fun y => y.output addr))) = finalMemory addr m (x::xs) ∧
+ RAMBuckets.cost Report.probes (x.output addr ++ xs.flatMap (fun y => y.output addr)) = (List.map StageTrace.cost (x :: xs)).sum
+ refine ⟨?_, ?_, ?_, ?_⟩
+ · rw [PrimedSchedule.runSegment_append, hr]
+ simp only [Option.bind_some, hs, hm]
+ rw [hr']
+ rfl
+ · rw [endState_append, hs]
+ exact hs'
+ · have hsplit (a b : List (Report w)) : after m (eventLog (a++b)) =
+ after (after m (eventLog a)) (eventLog b) := by simp [eventLog,after,List.foldl_append]
+ rw [hsplit, hm]
+ exact hm'
+ · rw [RAMBuckets.cost_append, hcost, hcost']
+ rfl
+
+/-- The suffix of the header schedule starting at the given stage, empty after completion. -/
+def remainingStages (id : Option StageId) : List Stage :=
+ match id with
+ | some i => stages.drop i.val
+ | none => []
+
+private theorem remaining_next (i : StageId) : remainingStages (some i) = stage i :: remainingStages (next i) := by
+ change stages.drop i.val = stage i :: _
+ rw [List.drop_eq_getElem_cons i.isLt]
+ congr 1
+ unfold next
+ split_ifs with h
+ · rfl
+ · exact List.drop_eq_nil_of_le (Nat.le_of_not_gt h)
+
+/-- Accepted execution traverses precisely the suffix prescribed by the
+header's sequential successor, even when a scan has zero active entries. -/
+theorem StageRuns.schedule {s : Sizes} {base : ℕ} {id : Option StageId} {m : Memory w}
+ {xs : List (StageTrace w)} (h : StageRuns s base id m xs) :
+ xs.map (fun x => stage x.id) = remainingStages id := by
+ induction h with
+ | done => rfl
+ | cons x _ _ _ _ ih => simp only [List.map_cons, ih, remaining_next]
+
+private theorem rawCost (rs : List (Report w)) (hp : ∀ r ∈ rs, r.probes ≤ 6) :
+ RAMBuckets.cost Report.probes rs ≤ 7*rs.length := by
+ induction rs with
+ | nil => simp [RAMBuckets.cost]
+ | cons r rs ih =>
+ have hr := hp r (by simp)
+ have hb := ih fun t ht => hp t (List.mem_cons_of_mem _ ht)
+ simp only [RAMBuckets.cost, List.length_cons]
+ omega
+
+private theorem sum_le_map {α : Type*} (a b : α → ℕ) (xs : List α) (h : ∀ x ∈ xs, a x ≤ b x) :
+ (xs.map a).sum ≤ (xs.map b).sum := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih =>
+ simp only [List.map_cons, List.sum_cons]
+ exact Nat.add_le_add (h x (by simp)) (ih fun y hy => h y (List.mem_cons_of_mem _ hy))
+
+/-- Bounds for the full program at the prescribed entry. The second inequality
+also budgets two enclosing-dispatch probes per header call. -/
+theorem complete_budget (s : Sizes) (base : ℕ) {m : Memory w} {xs : List (StageTrace w)}
+ (h : StageRuns s base (some (⟨0, by decide⟩ : StageId)) m xs)
+ (hl : ∀ x ∈ xs, x.reports.length ≤ calls s (stage x.id))
+ (hp : ∀ x ∈ xs, ∀ rep ∈ x.reports, rep.probes ≤ probes (stage x.id)) :
+ (xs.map (fun x => x.reports.length)).sum ≤ callBound s ∧
+ (xs.map StageTrace.cost).sum + 2*(xs.map (fun x => x.reports.length)).sum ≤ costBound s := by
+ have sched : xs.map (fun x => stage x.id) = stages := h.schedule
+ have hs : (xs.map (fun x => calls s (stage x.id))).sum = callBound s := by
+ simpa only [← sched, List.map_map, Function.comp_def] using sum_calls s
+ have hl' := sum_le_map (fun x : StageTrace w => x.reports.length) (fun x => calls s (stage x.id)) xs hl
+ rw [hs] at hl'
+ have estimate (x : StageTrace w) (hx : x ∈ xs) : x.cost ≤ 9 * x.reports.length := by
+ have hr := rawCost x.reports fun r hmem => (hp x hx r hmem).trans (probe_limit (stage x.id))
+ have hn : 0 < x.reports.length := by
+ have positive {idx : Option StageId} {mem : Memory w} {ys : List (StageTrace w)}
+ (hsteps : StageRuns s base idx mem ys) : ∀ y ∈ ys, y.reports ≠ [] := by
+ induction hsteps with
+ | done => simp
+ | cons y _ accept _ _ ih =>
+ intro z hz
+ rcases List.mem_cons.mp hz with rfl | hz
+ · intro he; rw [he] at accept; contradiction
+ · exact ih z hz
+ exact List.length_pos_iff.mpr (positive h x hx)
+ unfold StageTrace.cost
+ split <;> omega
+ have hsum := sum_le_map StageTrace.cost (fun x => 9*x.reports.length) xs estimate
+ have distrib (ys : List (StageTrace w)) :
+ (ys.map (fun x => 9*x.reports.length)).sum = 9 * (ys.map (fun x => x.reports.length)).sum := by
+ induction ys with
+ | nil => rfl
+ | cons x ys ih => simp [ih, Nat.mul_add]
+ rw [distrib] at hsum
+ exact ⟨hl', by unfold costBound; omega⟩
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderProtected.lean b/lean/OAI/Computability/VPVNP/LiveHeaderProtected.lean
new file mode 100644
index 0000000000..f067caf450
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderProtected.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.LiveHeaderScalarProtected
+import OAI.Computability.VPVNP.LiveHeaderPrimedProtected
+import OAI.Computability.VPVNP.LiveHeaderScanProtected
+import OAI.Computability.VPVNP.LiveHeaderAdviceStages
+import OAI.Computability.VPVNP.LiveStageLinkInversion
+
+/-!
+# The native header machine preserves every address below its scratch base
+
+The statement covers every successful native call, including calls started
+on malformed input or intermediate memories. Thus the enclosing dispatcher
+can keep its own stage tag immediately before the header scratch area.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM LiveHeaderSchedule LiveHeader
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem index_protected (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w) (hw : 4 ≤ w)
+ (fuel : ℕ) (state : Word w) (m : Memory w) (bits : List Bool) (rep : Report w)
+ (run : let P := ((stageTemplate .index).2.instantiate w (rowData w s base .index)).program
+ execute P fuel (P.start state) m bits = some rep) (a : ℕ) (ha : a < base) : after m rep.events a = m a := by
+ rw [limit_eq] at fit
+ let pub := indexWords w s base
+ let bound : Word w := Fin.ofNat _ (s.h+2)
+ let addr : Word w := Fin.ofNat _ a
+ have ha' : addr.val = a := Nat.mod_eq_of_lt (by omega)
+ have va : (pub 0).val = indexBase base := Nat.mod_eq_of_lt (by dsimp [indexBase]; omega)
+ have vh : (pub 1).val = highAddr s base := Nat.mod_eq_of_lt (by dsimp [highAddr,indexBase]; omega)
+ have vc : (pub 2).val = populationAddr s base := Nat.mod_eq_of_lt (by dsimp [populationAddr,highAddr,indexBase]; omega)
+ have vb : bound.val = s.h+2 := Nat.mod_eq_of_lt (by omega)
+ have hafter : (pub 0).val+(s.h+2) ≤ (pub 1).val := by rw [vh,va]; rfl
+ have hcount : (pub 1).val < (pub 2).val := by rw [vc,vh]; exact Nat.lt_succ_self _
+ dsimp only [stageTemplate] at run
+ rw [entry_start,index_row] at run
+ apply LiveHeaderBounded.frame_any indexTable pub bound fuel state m bits rep run a
+ intro f r hlt hr
+ have ht : addr.val < (pub 0).val := by rw [ha',va]; dsimp [indexBase]; omega
+ have hi : state.val < s.h+2 := vb ▸ Fin.lt_def.mp hlt
+ have hcast : (state.val : Word w) = state := Fin.ext (Nat.mod_eq_of_lt state.isLt)
+ rw [←ha']
+ exact (index_step hw pub _ addr hafter hcount ht state.val hi m bits r (hcast.symm ▸ hr)).2
+
+private theorem advice_protected (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w) (hw : 4 ≤ w)
+ (fuel : ℕ) (state : Word w) (m : Memory w) (bits : List Bool) (rep : Report w)
+ (run : let P := ((stageTemplate .advice).2.instantiate w (rowData w s base .advice)).program
+ execute P fuel (P.start state) m bits = some rep) (a : ℕ) (ha : a < base) : after m rep.events a = m a := by
+ rw [limit_eq] at fit
+ let pub := adviceWords w s base
+ let bound : Word w := Fin.ofNat _ s.advice
+ let addr : Word w := Fin.ofNat _ a
+ have ha' : addr.val = a := Nat.mod_eq_of_lt (by omega)
+ have vb : bound.val = s.advice := Nat.mod_eq_of_lt (by omega)
+ dsimp only [stageTemplate] at run
+ rw [entry_start,advice_row] at run
+ apply LiveHeaderBounded.frame_any adviceTable pub bound fuel state m bits rep run a
+ intro f r hlt hr
+ have hi : state.val < s.advice := vb ▸ Fin.lt_def.mp hlt
+ have dst : adviceBase s base = base + 17 + 3*(s.h+2) := by
+ dsimp [adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase]; omega
+ have hv : (pub 1).val = adviceBase s base := Nat.mod_eq_of_lt (by rw [dst]; omega)
+ have hfit : (pub 1).val+s.advice ≤ 2^w := by rw [hv,dst]; omega
+ have ht : addr.val < (pub 1).val := by rw [ha',hv,dst]; omega
+ have hcast : (state.val : Word w) = state := Fin.ext (Nat.mod_eq_of_lt state.isLt)
+ rw [←ha']
+ exact (advice_step hw pub rfl _ hfit addr ht state.val hi m bits r (hcast.symm ▸ hr)).2
+
+/-- Each of the thirty-one source stages protects the lower part of memory
+independently of the values read from scratch or processor words. -/
+theorem component_protected (s : Sizes) (base : ℕ) (stg : Stage) (fit : limit s base ≤ 2^w) (hw : 4 ≤ w)
+ (fuel : ℕ) (state : Word w) (m : Memory w) (bits : List Bool) (rep : Report w)
+ (run : let P := ((stageTemplate stg).2.instantiate w (rowData w s base stg)).program
+ execute P fuel (P.start state) m bits = some rep) (a : ℕ) (ha : a < base) : after m rep.events a = m a := by
+ cases stg with
+ | index => exact index_protected s base fit hw fuel state m bits rep run a ha
+ | advice => exact advice_protected s base fit hw fuel state m bits rep run a ha
+ | primedInit => exact PrimedStages.init_protected s base fit fuel state m bits rep run a ha
+ | primedDigits => exact PrimedStages.digits_protected s base fit fuel state m bits rep run a ha
+ | scan side f => exact ScanRows.call_preserves_below s base side f fit fuel state m bits run a ha
+ | width slot => exact scalar_call_frame s base (.width slot) trivial fit fuel state m bits rep run a ha
+ | flag flag => exact scalar_call_frame s base (.flag flag) trivial fit fuel state m bits rep run a ha
+ | firstTail => exact scalar_call_frame s base .firstTail trivial fit fuel state m bits rep run a ha
+ | mode => exact scalar_call_frame s base .mode trivial fit fuel state m bits rep run a ha
+ | descriptor side f => exact scalar_call_frame s base (.descriptor side f) trivial fit fuel state m bits rep run a ha
+
+/-- The linked header dispatcher itself preserves every word below the
+scratch base. Its only extra write is to the inner tag at the base. -/
+theorem native_protected (s : Sizes) (base : ℕ) (fit : limit s base ≤ 2^w) (hw : 4 ≤ w)
+ (hfits : stages.length ≤ 2^w) (fuel : ℕ) (state : Word w) (m : Memory w) (bits : List Bool) (rep : Report w)
+ (run : let P := (program.instantiate w (publicData w s base)).program
+ execute P fuel (P.start state) m bits = some rep) (a : ℕ) (ha : a < base) : after m rep.events a = m a := by
+ let addr : Word w := Fin.ofNat _ base
+ have hv : addr.val = base := Nat.mod_eq_of_lt (by rw [limit_eq] at fit; omega)
+ change execute (LiveStageLink.machine component next (bank w s base) addr).program fuel
+ ((LiveStageLink.machine component next (bank w s base) addr).program.start state) m bits = some rep at run
+ by_cases hgood : (m addr.val).val < stages.length
+ · let i : StageId := ⟨(m addr.val).val,hgood⟩
+ have htag : m addr.val = LiveStageLink.tagWord w i := Fin.ext (Nat.mod_eq_of_lt (m addr.val).isLt).symm
+ have hrun := execute_extend run (2*stages.length+2)
+ obtain ⟨r,hr,rfl⟩ := LiveStageLink.recover_call component next (bank w s base) addr i hfits (by omega) state m bits rep htag hrun
+ rw [component_start] at hr
+ have hf := component_protected s base (stage i) fit hw _ state m bits r hr a ha
+ rw [LiveStageLink.linkedReport_after]
+ cases r.result <;> cases next i <;> simp_all [writeMemory, Nat.ne_of_lt ha]
+ · have hbad := LiveStageLink.execute_invalid component next (bank w s base) addr hfits state fuel m (le_of_not_gt hgood) bits
+ dsimp only at hbad
+ rw [run] at hbad
+ contradiction
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderProtectedCore.lean b/lean/OAI/Computability/VPVNP/LiveHeaderProtectedCore.lean
new file mode 100644
index 0000000000..2f1ddb4c06
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderProtectedCore.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.LiveHeaderUnique
+
+/-! # Memory frames under arbitrary instruction caps and public cursor guards -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+private theorem Guessed.add_fuel {P : Program w C} {f : ℕ} {c : C} {es : List (Event w)} {out : Option (Word w)}
+ (hg : Guessed P f c es out) (pad : ℕ) : Guessed P (f+pad) c es out := by
+ induction hg with
+ | done hs => simpa [Nat.succ_add] using Guessed.done (f := _+pad) hs
+ | step hs _ ih => simpa [Nat.succ_add] using Guessed.step hs ih
+ | branch hs _ ih => simpa [Nat.succ_add] using Guessed.branch hs ih
+ | read hs _ ih => simpa [Nat.succ_add] using Guessed.read hs ih
+ | write hs _ ih => simpa [Nat.succ_add] using Guessed.write hs ih
+
+/-- Extra instruction fuel preserves a successful native path and its report. -/
+theorem execute_extend {P : Program w C} {f : ℕ} {c : C} {m : Memory w} {bs : List Bool} {r : Report w}
+ (hr : execute P f c m bs = some r) (pad : ℕ) : execute P (f+pad) c m bs = some r := by
+ obtain ⟨hg,hm,hbits⟩ := execute_spec hr
+ apply execute_iff.mpr
+ refine ⟨?_,hm,hbits⟩
+ exact hg.add_fuel pad
+
+theorem execute_empty_forces_anyFuel {P : Program w C} {f g : ℕ} {c : C} {m : Memory w} {bits : List Bool}
+ {r t : Report w} (h : execute P f c m [] = some r) (ht : execute P g c m bits = some t) :
+ bits = [] ∧ t = r := by
+ have forced := execute_prefix_unique (suffix := bits) h ht
+ exact ⟨forced.1,forced.2.symm⟩
+
+end BurstRAM
+
+namespace LiveHeaderBounded
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {w p r k : ℕ}
+
+/-- For any successful call of the guarded table it suffices to check
+the frame on successful source calls whose cursor is below the capacity. -/
+theorem frame_any (T : Template p r k) (pub : Fin k → Word w) (bound : Word w) (fuel : ℕ) (st : Word w)
+ (m : Memory w) (bits : List Bool) (rep : Report w)
+ (run : execute (machine T pub bound).program fuel ((machine T pub bound).program.start st) m bits = some rep)
+ (a : ℕ) (frame : ∀ f r, st < bound →
+ execute (T.instantiate w pub).program f ((T.instantiate w pub).program.start st) m bits = some r →
+ after m r.events a = m a) : after m rep.events a = m a := by
+ by_cases hlt : st < bound
+ · have h := execute_extend run 3
+ rw [execute_active T pub bound fuel st hlt,Option.map_eq_some_iff] at h
+ obtain ⟨r,hr,rfl⟩ := h
+ exact frame fuel r hlt hr
+ · have he := execute_closed T pub bound 0 st (le_of_not_gt hlt) m []
+ dsimp only [ite_true] at he
+ obtain ⟨_,rfl⟩ := execute_empty_forces_anyFuel he run
+ rfl
+
+end LiveHeaderBounded
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderResources.lean b/lean/OAI/Computability/VPVNP/LiveHeaderResources.lean
new file mode 100644
index 0000000000..5a59529b54
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderResources.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.LiveHeaderSchedule
+import OAI.Computability.VPVNP.CursorBounds
+import OAI.Computability.VPVNP.RAMSiteBounds
+
+/-!
+# Choosing the site exponent after the header sizes
+
+Both the read-and-copy clock and the reserved scratch size are polynomial in
+quantities fixed before the address exponent is chosen. Thus the prescribed
+physical processor array and the word address space suffice simultaneously.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderSchedule
+
+open Filter CursorBounds
+open scoped Topology
+
+theorem limit_le_cost (s : Sizes) (base : ℕ) : limit s base ≤ base + costBound s := by
+ rw [limit_eq]
+ unfold costBound callBound
+ omega
+
+theorem field_le_cost (s : Sizes) :
+ s.h+2 ≤ costBound s ∧ s.advice ≤ costBound s ∧ (s.h+1)*s.delta ≤ costBound s ∧
+ s.e ≤ costBound s ∧ s.config ≤ costBound s := by
+ unfold costBound callBound
+ omega
+
+private theorem pow_le_processorCount (B n : ℕ) : n^B ≤ processorCount B n := by
+ calc
+ n^B ≤ (2^(Nat.clog 2 n))^B := Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) _
+ _ = processorCount B n := by rw [← pow_mul,Nat.mul_comm]; rfl
+
+/-- A single lower bound on B works for all sufficiently large lengths.
+Its choice uses only the already selected header sizes. -/
+theorem eventually_resources {S : ℕ → Sizes}
+ (hh : PolynomiallyBounded fun n => (S n).h) (hd : PolynomiallyBounded fun n => (S n).delta)
+ (ha : PolynomiallyBounded fun n => (S n).advice) (he : PolynomiallyBounded fun n => (S n).e)
+ (hc : PolynomiallyBounded fun n => (S n).config) :
+ ∃ B₀, ∀ B ≥ B₀, ∀ᶠ n : ℕ in atTop,
+ costBound (S n) < processorCount B n ∧
+ limit (S n) (processorCount B n) < 2 ^ wordBits B n := by
+ obtain ⟨A,d,N,hbound⟩ := polynomial_cost hh hd ha he hc
+ refine ⟨d+1, fun B hB => ?_⟩
+ filter_upwards [eventually_ge_atTop (max N (A+1))] with n hn
+ have hN := (le_max_left N (A+1)).trans hn
+ have hA := (le_max_right N (A+1)).trans hn
+ have hnpos : 0 < n := by omega
+ have hcost : costBound (S n) < processorCount B n := by
+ calc
+ _ ≤ A * n^d := hbound n hN
+ _ < n^(d+1) := by rw [pow_succ, Nat.mul_comm A (n^d)]; exact Nat.mul_lt_mul_of_pos_left (by omega) (Nat.pow_pos hnpos)
+ _ ≤ n^B := Nat.pow_le_pow_right hnpos hB
+ _ ≤ _ := pow_le_processorCount B n
+ refine ⟨hcost, ?_⟩
+ have hw : addressBits B n + 1 ≤ wordBits B n := by
+ unfold wordBits
+ generalize addressBits B n = r
+ nlinarith [Nat.zero_le (r*r),Nat.zero_le (r*r*r),Nat.zero_le (r*r*r*r)]
+ have hdouble : processorCount B n + processorCount B n ≤ 2 ^ wordBits B n := by
+ simpa [processorCount,pow_succ,Nat.mul_two] using Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ exact (limit_le_cost ..).trans_lt ((Nat.add_lt_add_left hcost _).trans_le hdouble)
+
+end LiveHeaderSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderRuns.lean b/lean/OAI/Computability/VPVNP/LiveHeaderRuns.lean
new file mode 100644
index 0000000000..c7e884d05d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderRuns.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.LiveHeaderScan
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+
+/-!
+# Sequential execution of the distributed index scan
+
+The invariant states exactly what the six probes per call have read and
+written. Addresses for the three scratch regions are disjoint from the site
+headers. Thus the last call sees the real highest position and population
+count, even for a group index much larger than the RAM word modulus.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w r k : ℕ}
+
+theorem trace_after {pub : Fin k → Word w} {state : Word w} {ops : List (Op r k)}
+ {rs rs' : Regs w r} {m m' : Memory w} {es : List (Event w)}
+ (ht : trace pub state ops rs m = some (es, rs', m')) : after m es = m' := by
+ induction ops generalizing rs m es with
+ | nil => simp [trace] at ht; rw [ht.1]; exact ht.2.2
+ | cons op ops ih =>
+ cases ho : op.effect pub state rs m with
+ | none => simp [trace, ho] at ht
+ | some out =>
+ obtain ⟨e, r₁, m₁⟩ := out
+ cases hrest : trace pub state ops r₁ m₁ with
+ | none => simp [trace, ho, hrest] at ht
+ | some out =>
+ obtain ⟨rest, r₂, m₂⟩ := out
+ simp [trace, ho, hrest] at ht
+ obtain ⟨hes, rfl, rfl⟩ := ht
+ rw [← hes]
+ have hupdate : update m e = m₁ := by
+ cases op <;> simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at ho
+ all_goals first | exact ho.1 ▸ ho.2.2 | split at ho <;> simp at ho
+ all_goals exact ho.1 ▸ ho.2.2
+ change after (update m e) rest = _
+ rw [hupdate]
+ exact ih hrest
+
+/-- Consecutive deterministic microcalls realize a memory invariant after
+each cursor and cost at most `probeBound + 1` per cursor. -/
+theorem run_cursor_segment_at {C : Type*} (P : Program w C) (start fuel count probeBound : ℕ)
+ (inv : ℕ → Memory w → Prop) (m : Memory w) (h₀ : inv 0 m)
+ (step : ∀ i < count, ∀ mem, inv i mem → ∃ es,
+ execute P fuel (P.start ((start+i : ℕ) : Word w)) mem [] = some ⟨es, some ((start+(i+1) : ℕ) : Word w)⟩ ∧
+ inv (i+1) (after mem es) ∧ countProbes es ≤ probeBound) :
+ ∃ rs, runSegment P fuel (some (start : Word w)) m (List.replicate count []) = some rs ∧
+ endState (some (start : Word w)) rs = some ((start+count : ℕ) : Word w) ∧ inv count (after m (eventLog rs)) ∧
+ rs.length = count ∧ ∀ x ∈ rs, countProbes x.events ≤ probeBound := by
+ have go (j : ℕ) (hj : j ≤ count) : ∃ rs, runSegment P fuel (some (start : Word w)) m (List.replicate j []) = some rs ∧
+ endState (some (start : Word w)) rs = some ((start+j : ℕ) : Word w) ∧ inv j (after m (eventLog rs)) ∧
+ rs.length = j ∧ ∀ x ∈ rs, countProbes x.events ≤ probeBound := by
+ induction j with
+ | zero => exact ⟨[], rfl, by simp [endState], h₀, rfl, by simp⟩
+ | succ j ih =>
+ obtain ⟨rs, hr, hs, hi, hl, hb⟩ := ih (by omega)
+ obtain ⟨es, he, hnext, hp⟩ := step j (by omega) _ hi
+ let z : Report w := ⟨es, some ((start+(j+1) : ℕ) : Word w)⟩
+ refine ⟨rs ++ [z], ?_, ?_, ?_, by simp [hl], ?_⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, hr]
+ simp only [Option.bind_some, hs, runSegment, he, Option.map_some, z]
+ · rw [endState_append]; rfl
+ · simpa only [eventLog, List.flatMap_append, List.flatMap_singleton, after, List.foldl_append] using hnext
+ · intro x hx
+ rcases List.mem_append.mp hx with h | h
+ · exact hb x h
+ · have hxz : x = z := List.mem_singleton.mp h
+ exact hxz ▸ hp
+ exact go count le_rfl
+
+theorem run_cursor_segment {C : Type*} (P : Program w C) (fuel count probeBound : ℕ)
+ (inv : ℕ → Memory w → Prop) (m : Memory w) (h₀ : inv 0 m)
+ (step : ∀ i < count, ∀ mem, inv i mem → ∃ es,
+ execute P fuel (P.start (i : Word w)) mem [] = some ⟨es, some ((i+1 : ℕ) : Word w)⟩ ∧
+ inv (i+1) (after mem es) ∧ countProbes es ≤ probeBound) :
+ ∃ rs, runSegment P fuel (some 0) m (List.replicate count []) = some rs ∧
+ endState (some 0) rs = some (count : Word w) ∧ inv count (after m (eventLog rs)) ∧
+ rs.length = count ∧ ∀ x ∈ rs, countProbes x.events ≤ probeBound := by
+ simpa using run_cursor_segment_at P 0 fuel count probeBound inv m h₀ (by simpa using step)
+
+/-- The concrete scratch layout for one scan: original site words below
+`length`, an unpacked array beginning at `pub 0`, then the two scalar cells. -/
+structure ScanLayout (pub : Fin 3 → Word w) (length : ℕ) : Prop where
+ nonoverlap : length ≤ (pub 0).val
+ highAfter : (pub 0).val + length ≤ (pub 1).val
+ countAfter : (pub 1).val < (pub 2).val
+
+/-- Exact invariant over the real external word memory after `cursor` cells. -/
+structure ScanInv (pub : Fin 3 → Word w) (index length cursor : ℕ) (m : Memory w) : Prop where
+ input : ∀ i < length, (m i).val.testBit 0 = index.testBit i
+ high : m (pub 1).val = (prefixHigh index cursor : Word w)
+ count : m (pub 2).val = ((prefixOnes index cursor).card : Word w)
+ copied : ∀ i < cursor, m ((pub 0).val + i) = PrimedInputRAM.encodeBit w (index.testBit i)
+
+private theorem scanInv_next (pub : Fin 3 → Word w) {index length j : ℕ} {m : Memory w}
+ (layout : ScanLayout pub length) (hj : j < length) (hi : ScanInv pub index length j m) :
+ ScanInv pub index length (j+1) (indexUpdate pub (j : Word w) m (index.testBit j)) := by
+ have h₁ := layout.nonoverlap
+ have h₂ := layout.highAfter
+ have h₃ := layout.countAfter
+ have h₄ := (pub 2).isLt
+ have hjw : (j : Word w).val = j := (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt (by omega))
+ have hdst : (pub 0 + (j : Word w)).val = (pub 0).val + j := by
+ rw [Fin.val_add, hjw, Nat.mod_eq_of_lt (by omega)]
+ constructor
+ · intro i hil
+ simpa [indexUpdate, writeMemory, hdst, show i ≠ (pub 2).val by omega,
+ show i ≠ (pub 1).val by omega, show i ≠ (pub 0).val + j by omega] using hi.input i hil
+ · simp [indexUpdate, writeMemory, show (pub 1).val ≠ (pub 2).val by omega, prefixHigh_succ, hi.high]
+ · simp [indexUpdate, writeMemory, prefixCount_succ, hi.count, PrimedInputRAM.encodeBit]
+ cases index.testBit j <;> simp
+ · intro i hij
+ have hHigh : (pub 0).val + i ≠ (pub 1).val := by omega
+ have hCount : (pub 0).val + i ≠ (pub 2).val := by omega
+ simp only [indexUpdate, writeMemory, hHigh, hCount, ↓reduceIte, hdst, Nat.add_left_cancel_iff]
+ by_cases he : i = j
+ · simp [he]
+ · simp [he, hi.copied i (by omega)]
+
+/-- The native `indexCell` table reads exactly the occupied index positions.
+Its end state points to the next phase and each call costs seven calls-plus-probes. -/
+theorem index_scan_native (hw : 4 ≤ w) (pub : Fin 3 → Word w) (index length : ℕ)
+ (m : Memory w) (layout : ScanLayout pub length) (h₀ : ScanInv pub index length 0 m) :
+ let P := ((template indexCell 11).instantiate w pub).program
+ ∃ rs, runSegment P 22 (some 0) m (List.replicate length []) = some rs ∧
+ endState (some 0) rs = some (length : Word w) ∧
+ ScanInv pub index length length (after m (eventLog rs)) ∧ rs.length = length ∧
+ ∀ x ∈ rs, countProbes x.events ≤ 6 := by
+ apply run_cursor_segment _ _ _ _ _ _ h₀
+ intro j hj mem hi
+ have jfit : j < 2 ^ w := lt_of_lt_of_le hj (layout.nonoverlap.trans (pub 0).isLt.le)
+ have hjv : (j : Word w).val = j := (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt jfit)
+ obtain ⟨es, rs, ht, hr, _, hp, _⟩ := indexCell_trace hw pub (j : Word w) (fun _ => 0) mem
+ refine ⟨es, ?_, ?_, hp.le⟩
+ · change execute ((template indexCell 11).instantiate w pub).program (1 + indexCell.length)
+ ⟨_,(j : Word w),fun _ => 0,fun _ => 0⟩ mem [] = _
+ rw [execute_template, run_eq_trace, ht]
+ simp [hr]
+ · rw [trace_after ht, hjv, hi.input j hj]
+ exact scanInv_next pub layout hj hi
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderScalarProtected.lean b/lean/OAI/Computability/VPVNP/LiveHeaderScalarProtected.lean
new file mode 100644
index 0000000000..c4c4565163
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderScalarProtected.lean
@@ -0,0 +1,183 @@
+import OAI.Computability.VPVNP.LiveHeaderScalarStages
+
+/-!
+# Protected addresses in arbitrary scalar-stage calls
+
+The structured program text tracks which registers contain addresses read
+from designated public slots. Every external write of a scalar header stage
+uses such a register. This remains true on malformed memory, regardless of
+branch choices or fuel, so the outer dispatch tag below the scratch base is
+preserved at every continuing call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM LiveHeaderSchedule
+open LiveHeaderDescriptors
+
+namespace WriteAnalysis
+
+variable {w r k : ℕ}
+
+/-- A Boolean mark per register identifying those tracked by the analysis of external write
+addresses. -/
+abbrev Marks (r : ℕ) := Fin r → Bool
+
+/-- A set register bit certifies that it holds an address different from the
+protected cell. Arithmetic and external reads discard this information. -/
+def line (slots : Fin k → Bool) (marked : Marks r) : Op r k → Bool × Marks r
+ | .publicWord dst slot => (true,Function.update marked dst (slots slot))
+ | .copy dst src => (true,Function.update marked dst (marked src))
+ | .constant dst _ | .stateWord dst | .binary _ dst _ _ | .read dst _ =>
+ (true,Function.update marked dst false)
+ | .write addr _ => (marked addr,marked)
+ | .guardEq .. | .guardLt .. => (true,marked)
+
+private def merge (a b : Bool × Marks r) : Bool × Marks r :=
+ (a.1 && b.1,fun i => a.2 i && b.2 i)
+
+/-- Sequential code passes its output marks to the next instruction. A
+branch retains exactly the marks common to its two exits. -/
+def analyze (slots : Fin k → Bool) : Flow r k → Marks r → Bool × Marks r
+ | .line op, marked => line slots marked op
+ | .seq x y, marked =>
+ let a := analyze slots x marked
+ let b := analyze slots y a.2
+ (a.1 && b.1,b.2)
+ | .ifEq _ _ x y, marked | .ifLt _ _ x y, marked | .branch x y, marked =>
+ merge (analyze slots x marked) (analyze slots y marked)
+ | .whileLt .., _ => (false,fun _ => false)
+
+/-- Every marked register's word address differs from the designated protected address. -/
+def Valid (addr : ℕ) (marked : Marks r) (rs : Regs w r) :=
+ ∀ i, marked i = true → (rs i).val ≠ addr
+
+private theorem valid_put {addr : ℕ} {marked : Marks r} {rs : Regs w r}
+ (h : Valid addr marked rs) (dst : Fin r) (bit : Bool) (v : Word w) (hv : bit = true → v.val ≠ addr) :
+ Valid addr (Function.update marked dst bit) (Function.update rs dst v) := by
+ intro j hj
+ by_cases hdst : j = dst
+ · subst j; simpa using hv (by simpa using hj)
+ · simpa [hdst] using h j (by simpa [hdst] using hj)
+
+private theorem line_sound {pub : Fin k → Word w} {st : Word w} (slots : Fin k → Bool) (addr : ℕ)
+ (hslots : ∀ i, slots i = true → (pub i).val ≠ addr) (op : Op r k) {rs rs' : Regs w r}
+ {m m' : Memory w} {e : Event w} (hr : op.effect pub st rs m = some (e,rs',m'))
+ (mark : Marks r) (valid : Valid addr mark rs) (safe : (line slots mark op).1 = true) :
+ Valid addr (line slots mark op).2 rs' ∧ m' addr = m addr := by
+ cases op <;> simp only [Op.effect] at hr
+ all_goals first | split at hr | skip
+ all_goals simp at hr
+ all_goals obtain ⟨rfl,rfl,rfl⟩ := hr
+ all_goals first
+ | exact ⟨valid_put valid _ _ _ (hslots _),rfl⟩
+ | exact ⟨valid_put valid _ _ _ (valid _),rfl⟩
+ | exact ⟨valid_put valid _ _ _ (by simp),rfl⟩
+ | exact ⟨valid,rfl⟩
+ | exact ⟨valid,ite_eq_right (Ne.symm (valid _ safe))⟩
+
+private theorem common_left (A B : Bool × Marks r) {addr : ℕ} {rs : Regs w r} (h : Valid addr A.2 rs) :
+ Valid addr (merge A B).2 rs := fun j hj => h j (Bool.and_eq_true_iff.mp hj).1
+
+private theorem common_right (A B : Bool × Marks r) {addr : ℕ} {rs : Regs w r} (h : Valid addr B.2 rs) :
+ Valid addr (merge A B).2 rs := fun j hj => h j (Bool.and_eq_true_iff.mp hj).2
+
+theorem sound {pub : Fin k → Word w} {st : Word w} {body : Flow r k} {rs rs' : Regs w r} {m m' : Memory w}
+ {es : List (Event w)} (exec : Flow.Exec pub st body rs m es rs' m') (slots : Fin k → Bool)
+ (addr : ℕ) (hslots : ∀ i, slots i = true → (pub i).val ≠ addr) (marked : Marks r)
+ (hvalid : Valid addr marked rs) (safe : (analyze slots body marked).1 = true) :
+ Valid addr (analyze slots body marked).2 rs' ∧ m' addr = m addr := by
+ induction exec generalizing marked with
+ | line hr => exact line_sound slots addr hslots _ hr marked hvalid safe
+ | seq _ _ ih₁ ih₂ =>
+ have hs := Bool.and_eq_true_iff.mp safe
+ obtain ⟨v₁,h₁⟩ := ih₁ marked hvalid hs.1
+ obtain ⟨v₂,h₂⟩ := ih₂ _ v₁ hs.2
+ exact ⟨v₂,h₂.trans h₁⟩
+ | ifEqYes _ _ ih | ifLtYes _ _ ih | branchYes _ ih =>
+ have hs := Bool.and_eq_true_iff.mp safe
+ obtain ⟨v,h⟩ := ih marked hvalid hs.1
+ exact ⟨common_left _ _ v,h⟩
+ | ifEqNo _ _ ih | ifLtNo _ _ ih | branchNo _ ih =>
+ have hs := Bool.and_eq_true_iff.mp safe
+ obtain ⟨v,h⟩ := ih marked hvalid hs.2
+ exact ⟨common_right _ _ v,h⟩
+ | whileDone | whileStep => exact Bool.noConfusion safe
+
+end WriteAnalysis
+
+/-- The widths, four boundary flags, first-tail flag, mode and eight
+descriptors each write into statically designated scalar scratch cells. -/
+def scalarStage : Stage → Prop
+ | .width _ | .flag _ | .firstTail | .mode | .descriptor .. => True
+ | _ => False
+
+private theorem checked_call {w : ℕ} (s : Sizes) (base : ℕ) (stg : Stage) (body : Flow 48 16)
+ (hbody : stageTemplate stg = entry (body.template none)) (slots : Fin 16 → Bool)
+ (hs : (WriteAnalysis.analyze slots body (fun _ => false)).1 = true)
+ (hpub : ∀ i, slots i = true → base ≤ (scalarPub w s base stg i).val)
+ (fuel : ℕ) (state : Word w) (m : Memory w) (bits : List Bool) (rep : Report w)
+ (hr : let P := ((stageTemplate stg).2.instantiate w (rowData w s base stg)).program
+ execute P fuel (P.start state) m bits = some rep) (a : ℕ) (ha : a < base) : after m rep.events a = m a := by
+ dsimp only at hr
+ rw [hbody,entry_start] at hr
+ obtain ⟨out,final,exec,_,_,_⟩ := (Flow.template_execute_iff body none (scalarPub w s base stg)
+ state (fun _ => 0) (fun _ => 0) m fuel bits rep).mp hr
+ rw [PrimedCounter.Call.exec_memory exec]
+ exact (WriteAnalysis.sound exec slots a (fun i hi => (ha.trans_le (hpub i hi)).ne.symm)
+ (fun _ => false) (fun _ h => by contradiction) hs).2
+
+private def output4 (i : Fin 16) := decide (i = 4)
+private def output3 (i : Fin 16) := decide (i = 3)
+private def output78 (i : Fin 16) := decide (i = 7 ∨ i = 8)
+
+theorem scalar_call_frame {w : ℕ} (s : Sizes) (base : ℕ) (stg : Stage) (scalar : scalarStage stg)
+ (fit : limit s base ≤ 2^w) (fuel : ℕ) (state : Word w) (m : Memory w) (bits : List Bool) (rep : Report w)
+ (run : let P := ((stageTemplate stg).2.instantiate w (rowData w s base stg)).program
+ execute P fuel (P.start state) m bits = some rep) (a : ℕ) (ha : a < base) : after m rep.events a = m a := by
+ have small {n : ℕ} (h : n ≤ 14) : base ≤ (Fin.ofNat (2^w) (base+n)).val := by
+ rw [limit_eq] at fit
+ rw [Fin.val_ofNat,Nat.mod_eq_of_lt (by omega)]
+ omega
+ cases stg with
+ | width slot =>
+ apply checked_call s base (.width slot) (LiveHeaderWidths.WidthCode.block widthSlots slot) rfl
+ output4 (by cases slot <;> rfl) ?_ fuel state m bits rep run a ha
+ intro i hi
+ obtain rfl : i = 4 := of_decide_eq_true hi
+ cases slot <;> apply small <;> decide
+ | flag flag =>
+ apply checked_call s base (.flag flag) (LiveHeaderWidths.PhaseCode.block widthSlots flag) rfl
+ output4 (by cases flag <;> rfl) ?_ fuel state m bits rep run a ha
+ intro i hi
+ obtain rfl : i = 4 := of_decide_eq_true hi
+ cases flag <;> apply small <;> decide
+ | firstTail =>
+ apply checked_call s base .firstTail (LiveHeaderWidths.PhaseCode.firstTailBlock widthSlots 5) rfl
+ output4 rfl ?_ fuel state m bits rep run a ha
+ intro i hi
+ obtain rfl : i = 4 := of_decide_eq_true hi
+ exact small (n := 10) (by decide)
+ | mode =>
+ apply checked_call s base .mode LiveHeader.Mode.program rfl output3 rfl ?_ fuel state m bits rep run a ha
+ intro i hi
+ obtain rfl : i = 3 := of_decide_eq_true hi
+ exact small (n := 11) (by decide)
+ | descriptor side f =>
+ apply checked_call s base (.descriptor side f) (Native.block descriptorSlots side f) rfl
+ output78 (by cases side <;> cases f <;> rfl) ?_ fuel state m bits rep run a ha
+ intro i hi
+ rcases (of_decide_eq_true hi : i=7 ∨ i=8) with rfl | rfl
+ · exact small (n := 12) (by decide)
+ · exact small (n := 13) (by decide)
+ | index | advice | primedInit | primedDigits | scan _ _ => exact False.elim scalar
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderScalarStages.lean b/lean/OAI/Computability/VPVNP/LiveHeaderScalarStages.lean
new file mode 100644
index 0000000000..1953e55214
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderScalarStages.lean
@@ -0,0 +1,183 @@
+import OAI.Computability.VPVNP.LiveHeaderProgramRun
+import OAI.Computability.VPVNP.LiveGroupModeInput
+import OAI.Computability.VPVNP.PrimedCounterCallPaths
+
+/-!
+# Executions of the scalar stages of the live header program
+
+These stages run once and end with an accepting exit to the next stage. They
+read the summary words produced by the index scan and write only their own
+specified outputs. Every local operand is the one wired in the complete table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderWidths
+open LiveHeaderDescriptors PrimedInputRAM
+
+variable {w : ℕ}
+
+/-- A single accepted call to the relocated stage, with its real memory effect. -/
+def SingleRun (s : Sizes) (base : ℕ) (st : Stage) (before final : Memory w) : Prop :=
+ let P := ((stageTemplate st).2.instantiate w (rowData w s base st)).program
+ ∃ es, execute P 40 (P.start 0) before [] = some ⟨es,none⟩ ∧ after before es = final ∧
+ es.length < 40 ∧ countProbes es ≤ probes st ∧ choiceBits es = []
+
+/-- The first sixteen words of the selected header stage's public row, used by its scalar
+worker. -/
+def scalarPub (w : ℕ) (s : Sizes) (base : ℕ) (st : Stage) : Fin 16 → Word w :=
+ rowData w s base st ∘ includeFin (by decide)
+
+theorem single_of_flow (s : Sizes) (base : ℕ) (st : Stage) (a : Flow 48 16)
+ (hc : stageTemplate st = entry (a.template none)) (m : Memory w) {es out final}
+ (hr : Flow.Exec (scalarPub w s base st) 0 a (fun _ => 0) m es out final)
+ (hf : es.length < 40) (hp : countProbes es ≤ probes st) (hb : choiceBits es = []) :
+ SingleRun s base st m final := by
+ unfold SingleRun
+ rw [hc]
+ refine ⟨es, ?_, PrimedCounter.Call.exec_memory hr, hf, hp, hb⟩
+ rw [entry_start]
+ exact (Flow.template_execute_iff a none (scalarPub w s base st) 0 (fun _ => 0) (fun _ => 0) m 40 [] _).mpr
+ ⟨out,final,hr,rfl,hf,hb⟩
+
+/-- The four scratch words consumed after index scanning. -/
+structure Summary (s : Sizes) (base i : ℕ) (m : Memory w) : Prop where
+ high : (m (highAddr s base)).val = Nat.log 2 i
+ count : (m (populationAddr s base)).val = (LiveHeader.prefixOnes i (s.h+2)).card
+ singleton : (LiveHeader.prefixOnes i (s.h+2)).card = 1 ↔ i = 2 ^ Nat.log 2 i
+ low : m (indexBase base) = encodeBit w (i.testBit 0)
+
+/-- The public and scratch words used by the width and phase stages. -/
+structure ScalarFit (w : ℕ) (s : Sizes) (base : ℕ) : Prop where
+ height : s.h+1 < 2^w
+ delta : s.delta < 2^w
+ cut : (s.h+1)*s.delta < 2^w
+ address : limit s base ≤ 2^w
+
+private theorem highFit {s : Sizes} {base : ℕ} (fit : ScalarFit w s base) : highAddr s base < 2^w := by
+ have h := fit.address
+ rw [limit_eq] at h
+ unfold highAddr indexBase
+ omega
+
+private theorem populationFit {s : Sizes} {base : ℕ} (fit : ScalarFit w s base) : populationAddr s base < 2^w := by
+ have h := fit.address
+ rw [limit_eq] at h
+ unfold populationAddr highAddr indexBase
+ omega
+
+private theorem indexFit {s : Sizes} {base : ℕ} (fit : ScalarFit w s base) : indexBase base < 2^w := by
+ have h := highFit fit
+ unfold highAddr at h
+ omega
+
+private theorem wordAt (n : ℕ) (hn : n < 2^w) : (Fin.ofNat (2^w) n).val = n := Nat.mod_eq_of_lt hn
+
+/-- Every width stage has a successful source call. All requested widths
+have their exact clamped value, including both incident cuts in the tail. -/
+theorem width_run (s : Sizes) (base i : ℕ) (slot : Slot) (m : Memory w) (fit : ScalarFit w s base)
+ (hi : 0 < i) (hi' : i ≤ 2^(s.h+1)) (summary : Summary s base i m) :
+ ∃ v : Word w, SingleRun s base (.width slot) m (writeMemory m (Fin.ofNat _ (widthAddr base slot)) v) ∧
+ (Needed s.h i slot → v.val = CutSchedule.width (s.h+1) s.delta (index i slot)) := by
+ let pub := scalarPub w s base (.width slot)
+ have finish (v : Word w) {out} (hr : Flow.Exec pub 0 (WidthCode.block widthSlots slot) (fun _ => 0) m
+ (WidthCode.events pub widthSlots m slot v) out (writeMemory m (pub widthSlots.outputAddress) v)) :
+ SingleRun s base (.width slot) m (writeMemory m (Fin.ofNat _ (widthAddr base slot)) v) := by
+ obtain ⟨hp,hb,hl⟩ := WidthCode.event_cost pub widthSlots m slot v
+ exact single_of_flow s base (.width slot) _ rfl _ hr (by omega) hp.le hb
+ by_cases need : Needed s.h i slot
+ · have hh : (pub widthSlots.height).val = s.h+1 := wordAt _ fit.height
+ have hd : (pub widthSlots.delta).val = s.delta := wordAt _ fit.delta
+ have hk : (pub widthSlots.highestAddress).val = highAddr s base := wordAt _ (highFit fit)
+ have hc : (pub widthSlots.populationAddress).val = populationAddr s base := wordAt _ (populationFit fit)
+ obtain ⟨out,hr,hv⟩ := WidthCode.needed_exec pub widthSlots 0 m (fun _ => 0) slot s.h s.delta i
+ _ hi hi' need summary.singleton hh hd (hk ▸ summary.high) (hc ▸ summary.count) fit.cut
+ exact ⟨_, finish _ hr, fun _ => hv⟩
+ · obtain ⟨v,out,hr⟩ := WidthCode.unconditional_exec pub widthSlots 0 m (fun _ => 0) slot
+ exact ⟨v,finish _ hr,fun h => (need h).elim⟩
+
+theorem flag_run (s : Sizes) (base i : ℕ) (flag : Flag) (m : Memory w) (fit : ScalarFit w s base)
+ (hi : 0 < i) (hi' : i ≤ 2^(s.h+1)) (summary : Summary s base i m) :
+ SingleRun s base (.flag flag) m (writeMemory m (Fin.ofNat _ (flagAddr base flag))
+ (encodeBit w (decide (flag.holds s.h i)))) := by
+ let pub := scalarPub w s base (.flag flag)
+ have hh : (pub widthSlots.height).val = s.h+1 := wordAt _ fit.height
+ have hk : (pub widthSlots.highestAddress).val = highAddr s base := wordAt _ (highFit fit)
+ have hc : (pub widthSlots.populationAddress).val = populationAddr s base := wordAt _ (populationFit fit)
+ obtain ⟨es,out,hr,hp,hb,hl⟩ := PhaseCode.block_exec pub widthSlots 0 m (fun _ => 0) s.h i _
+ flag hi hi' summary.singleton hh (hk ▸ summary.high) (hc ▸ summary.count)
+ exact single_of_flow s base (.flag flag) _ rfl _ hr (by omega) hp.le hb
+
+theorem firstTail_run (hw : 2 ≤ w) (s : Sizes) (base i : ℕ) (m : Memory w) (fit : ScalarFit w s base)
+ (hi : 0 < i) (hi' : i ≤ 2^(s.h+1)) (summary : Summary s base i m) :
+ SingleRun s base .firstTail m (writeMemory m (Fin.ofNat _ (firstTailAddr base))
+ (encodeBit w (decide (i = 2^s.h+1)))) := by
+ let pub := scalarPub w s base .firstTail
+ have hh : (pub widthSlots.height).val = s.h+1 := wordAt _ fit.height
+ have hk : (pub widthSlots.highestAddress).val = highAddr s base := wordAt _ (highFit fit)
+ have hc : (pub widthSlots.populationAddress).val = populationAddr s base := wordAt _ (populationFit fit)
+ have hlow : (pub 5).val = indexBase base := wordAt _ (indexFit fit)
+ obtain ⟨es,out,hr,hp,hb,hl⟩ := PhaseCode.firstTail_exec hw pub widthSlots 5 0 m (fun _ => 0)
+ s.h i hi hi' hh (hk ▸ summary.high) (hc ▸ summary.count) (hlow ▸ summary.low)
+ exact single_of_flow s base .firstTail _ rfl _ hr (by omega) hp.le hb
+
+private theorem scalarAddrFit {s : Sizes} {base addr : ℕ} (fit : ScalarFit w s base)
+ (ha : addr < indexBase base) : addr < 2^w := ha.trans (indexFit fit)
+
+theorem mode_run (s : Sizes) (base d : ℕ) {hw : 4 ≤ w} (advice : CutSchedule.Bits s.advice)
+ (cuts : ChainAssignments.AllCuts s.h s.delta) (g : Fin (2^(s.h+1))) (m : Memory w)
+ (fit : ScalarFit w s base) (headers : LiveHeader.SiteHeaders d hw advice cuts g m)
+ (left : (m (widthAddr base .liveLeft)).val = LiveHeader.incidentWidth (Δ := s.delta) .left g)
+ (right : (m (widthAddr base .liveRight)).val = LiveHeader.incidentWidth (Δ := s.delta) .right g)
+ (flag : m (flagAddr base .firstHalf) = encodeBit w (LiveHeader.firstHalfFlag g))
+ (tag : LiveHeader.Mode.Tag) (hsel : LiveHeader.physicalTag cuts g = some tag) :
+ SingleRun s base .mode m (writeMemory m (Fin.ofNat _ (tagAddr base)) (Fin.ofNat _ tag.code.val)) := by
+ let pub := scalarPub w s base .mode
+ let zero : Fin (2^d) := ⟨0, Nat.two_pow_pos _⟩
+ have hl : (pub 0).val = widthAddr base .liveLeft := wordAt (widthAddr base .liveLeft) (scalarAddrFit fit (by dsimp [widthAddr,indexBase]; omega))
+ have hr : (pub 1).val = widthAddr base .liveRight := wordAt (widthAddr base .liveRight) (scalarAddrFit fit (by dsimp [widthAddr,indexBase]; omega))
+ have hf : (pub 2).val = flagAddr base .firstHalf := wordAt (flagAddr base .firstHalf) (scalarAddrFit fit (by dsimp [flagAddr,indexBase]; omega))
+ obtain ⟨es,out,he,_,ht,hp,hb,_⟩ := LiveHeader.Mode.exec_selected pub 0 (fun _ => 0) m hw
+ (ChainAssignments.physicalHeader advice cuts g zero) (LiveHeader.firstHalfFlag g) tag (headers zero)
+ (hf ▸ flag) (by rw [hl,hr,left,right]; exact hsel)
+ exact single_of_flow s base .mode _ rfl _ he (by omega) hp.le hb
+
+/-- Each descriptor stage publishes the exact interval to its immediately
+following scan. The scratch words are reused between successive fields. -/
+theorem descriptor_run (s : Sizes) (base : ℕ) (side : Side) (f : Field) (m : Memory w)
+ (hw : 0 < w) (fit : ScalarFit w s base) (W tag : ℕ) (half firstTail : Bool)
+ (hW : (m (widthAddr base (if side = .left then .liveLeft else .liveRight))).val = W)
+ (ht : (m (tagAddr base)).val = tag)
+ (hh : m (flagAddr base .firstHalf) = encodeBit w half)
+ (hft : m (firstTailAddr base) = encodeBit w firstTail)
+ (hefit : 1+s.e ≤ s.delta) (hcfit : 1+s.config ≤ s.delta) (hblock : W = 0 ∨ s.delta ≤ W) :
+ let iv := span (shape side W tag half firstTail) W s.delta s.e s.config f
+ ∃ o l : Word w, o.val = iv.1 ∧ l.val = iv.2 ∧
+ SingleRun s base (.descriptor side f) m (writeMemory (writeMemory m (Fin.ofNat _ (offsetAddr base)) o)
+ (Fin.ofNat _ (countAddr base)) l) := by
+ let pub := scalarPub w s base (.descriptor side f)
+ have hwaddr : (pub descriptorSlots.widthAddress).val = widthAddr base
+ (if side = .left then .liveLeft else .liveRight) := wordAt (widthAddr base (if side = .left then .liveLeft else .liveRight)) (scalarAddrFit fit (by
+ cases side <;> simp [widthAddr,indexBase]))
+ have htaddr : (pub descriptorSlots.tagAddress).val = tagAddr base :=
+ wordAt (tagAddr base) (scalarAddrFit fit (by dsimp [tagAddr,indexBase]; omega))
+ have hhaddr : (pub descriptorSlots.firstHalfAddress).val = flagAddr base .firstHalf :=
+ wordAt (flagAddr base .firstHalf) (scalarAddrFit fit (by dsimp [flagAddr,indexBase]; omega))
+ have hfaddr : (pub descriptorSlots.firstTailAddress).val = firstTailAddr base :=
+ wordAt (firstTailAddr base) (scalarAddrFit fit (by dsimp [firstTailAddr,indexBase]; omega))
+ obtain ⟨out,o,l,hr,ho,hl⟩ := Native.block_exec hw pub descriptorSlots 0 m (fun _ => 0) side f W tag
+ s.delta s.e s.config half firstTail (hwaddr ▸ hW) (htaddr ▸ ht) (hhaddr ▸ hh) (hfaddr ▸ hft)
+ (wordAt s.delta fit.delta) (wordAt s.e (by have := fit.delta; omega)) (wordAt s.config (by have := fit.delta; omega))
+ hefit hcfit hblock
+ obtain ⟨hp,hb,hLen⟩ := Native.event_cost pub descriptorSlots m o l
+ exact ⟨o,l,ho,hl,single_of_flow s base (.descriptor side f) _ rfl _ hr (by omega) hp.le hb⟩
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderScan.lean b/lean/OAI/Computability/VPVNP/LiveHeaderScan.lean
new file mode 100644
index 0000000000..22e1953091
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderScan.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.LiveHeaderBits
+import Mathlib.Data.Nat.BitIndices
+import Mathlib.Data.Nat.Log
+
+/-!
+# Streaming the long live group index
+
+The one-based group number can have polynomially many bits. Each burst reads
+one bit at its processor, appends it to the scratch array, and updates the
+index of the last set bit and the number of set bits. At completion these two
+word-sized statistics give its base-two logarithm and the power-of-two test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Positions of the set bits observed before the next cursor. -/
+def prefixOnes (index cursor : ℕ) : Finset ℕ :=
+ (Finset.range cursor).filter (fun k => index.testBit k)
+
+/-- Highest observed position, or zero in the empty prefix. -/
+def prefixHigh (index cursor : ℕ) := (prefixOnes index cursor).sup id
+
+theorem prefixOnes_succ (index cursor : ℕ) :
+ prefixOnes index (cursor+1) = if index.testBit cursor then
+ insert cursor (prefixOnes index cursor) else prefixOnes index cursor := by
+ rw [prefixOnes, Finset.range_add_one, Finset.filter_insert]
+ rfl
+
+theorem prefixCount_succ (index cursor : ℕ) :
+ (prefixOnes index (cursor+1)).card = (prefixOnes index cursor).card + (index.testBit cursor).toNat := by
+ have hn : cursor ∉ prefixOnes index cursor := by simp [prefixOnes]
+ cases h : index.testBit cursor <;> simp [prefixOnes_succ, h, hn]
+
+theorem prefixHigh_succ (index cursor : ℕ) :
+ prefixHigh index (cursor+1) = if index.testBit cursor then cursor else prefixHigh index cursor := by
+ have hle : prefixHigh index cursor ≤ cursor := Finset.sup_le fun j hj =>
+ (Finset.mem_range.mp (Finset.mem_filter.mp hj).1).le
+ cases h : index.testBit cursor
+ · simp [prefixHigh, prefixOnes_succ, h]
+ · rw [prefixHigh, prefixOnes_succ, h, ite_eq_left rfl, ite_eq_left rfl, Finset.sup_insert]
+ exact max_eq_left hle
+
+/-- Once all bits have been read, the last set bit is the binary logarithm
+and exactly one set bit characterizes a power of two. -/
+theorem summary_correct {index length : ℕ} (hpos : index ≠ 0) (hfit : index < 2 ^ length) :
+ prefixHigh index length = Nat.log 2 index ∧
+ ((prefixOnes index length).card = 1 ↔ index = 2 ^ Nat.log 2 index) := by
+ let k := Nat.log 2 index
+ have hk : k < length := (Nat.log_lt_iff_lt_pow (by decide) hpos).mpr hfit
+ have hmem : k ∈ prefixOnes index length := by
+ have ht := Nat.testBit_log2 hpos
+ rw [Nat.log2_eq_log_two] at ht
+ exact Finset.mem_filter.mpr ⟨Finset.mem_range.mpr hk, ht⟩
+ have hle (j : ℕ) (hj : j ∈ prefixOnes index length) : j ≤ k :=
+ Nat.le_log_of_pow_le (by decide) (Nat.two_pow_le_of_mem_bitIndices
+ (Nat.mem_bitIndices.mpr (Finset.mem_filter.mp hj).2))
+ refine ⟨le_antisymm (Finset.sup_le hle) (Finset.le_sup (f := id) hmem), ?_⟩
+ constructor
+ · intro hc
+ obtain ⟨j, hj⟩ := Finset.card_eq_one.mp hc
+ have hjk : j = k := (Finset.mem_singleton.mp (hj ▸ hmem)).symm
+ subst j
+ apply Nat.eq_of_testBit_eq
+ intro j
+ rw [Nat.testBit_two_pow]
+ by_cases h : j < length
+ · rw [Bool.eq_iff_iff, decide_eq_true_iff]
+ have he := Finset.ext_iff.mp hj j
+ simpa only [prefixOnes, Finset.mem_filter, Finset.mem_range, h, true_and,
+ Finset.mem_singleton, eq_comm] using he
+ · have hzero := Nat.testBit_lt_two_pow (hfit.trans_le (Nat.pow_le_pow_right (by decide) (by omega : length ≤ j)))
+ simp [hzero, show Nat.log 2 index ≠ j from by change k ≠ j; omega]
+ · intro hi
+ suffices prefixOnes index length = {k} by simp [this]
+ ext j
+ change j ∈ (Finset.range length).filter (fun a => index.testBit a) ↔ _
+ change index = 2 ^ k at hi
+ rw [Finset.mem_filter, Finset.mem_range, hi, Nat.testBit_two_pow, decide_eq_true_iff, Finset.mem_singleton]
+ constructor
+ · exact fun h => h.2.symm
+ · rintro rfl
+ exact ⟨hk, rfl⟩
+
+/-- Public words are the bit-array base, high-index cell, and population-count
+cell. The persistent state is the next site address. All reads precede writes. -/
+def indexCell : List (Op 12 3) :=
+ [.stateWord 0] ++ fetch 0 ++
+ [.publicWord 4 0, .publicWord 5 1, .publicWord 6 2, .read 7 5, .read 8 6,
+ .binary .sub 9 3 1, .binary .mul 7 7 9, .binary .mul 9 0 1, .binary .add 7 7 9,
+ .binary .add 8 8 1, .binary .add 4 4 0, .write 4 1, .write 5 7, .write 6 8,
+ .binary .add 11 0 3]
+
+/-- Store one group-index bit, update the highest set position if the bit is one, and add it to
+the population count. -/
+def indexUpdate (pub : Fin 3 → Word w) (state : Word w) (m : Memory w) (b : Bool) : Memory w :=
+ let copied := writeMemory m (pub 0 + state) (PrimedInputRAM.encodeBit w b)
+ let indexed := writeMemory copied (pub 1) (if b then state else m (pub 1).val)
+ writeMemory indexed (pub 2) (m (pub 2).val + PrimedInputRAM.encodeBit w b)
+
+/-- Exactly one call visits this bit. The trace has three reads, three writes,
+twenty-one instructions and no branch choices. -/
+theorem indexCell_trace (hw : 4 ≤ w) (pub : Fin 3 → Word w) (state : Word w)
+ (rs : Regs w 12) (m : Memory w) :
+ let b := (m state.val).val.testBit 0
+ ∃ es rs', trace pub state indexCell rs m = some (es, rs', indexUpdate pub state m b) ∧
+ rs' 11 = state + 1 ∧ es.length = 21 ∧ countProbes es = 6 ∧ choiceBits es = [] := by
+ cases hb : (m state.val).val.testBit 0 <;>
+ simp only [Nat.testBit_eq_decide_div_mod_eq, pow_zero, Nat.div_one, decide_eq_false_iff_not, decide_eq_true_iff] at hb <;>
+ simp (config := { decide := true }) [indexCell, fetch, trace, Op.effect, Function.update,
+ show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.sub.eval = (· - · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.mul.eval = (· * · : Word w → Word w → Word w) from rfl,
+ PrimedInputRAM.Opcodes.readBit_word (by omega : 0 < w), hb, PrimedInputRAM.encodeBit,
+ indexUpdate, countProbes, choiceBits]
+
+end LiveHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderScanProtected.lean b/lean/OAI/Computability/VPVNP/LiveHeaderScanProtected.lean
new file mode 100644
index 0000000000..b18f92a4d4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderScanProtected.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.LiveHeaderScanRows
+import OAI.Computability.VPVNP.LiveHeaderProtectedCore
+
+/-!
+# Processor-site preservation during arbitrary scheduled scans
+
+Even a malformed count or offset cannot redirect a write into the processor
+sites. The public cursor guard bounds the destination within its allocated
+buffer on every successful copy call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.ScanRows
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderDescriptors LiveHeader
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem payload_address (s : Sizes) (base : ℕ) (side : Side) (f : Field)
+ (fit : limit s base ≤ 2^w) (hf : f ≠ .padding) (st : Word w) (cursor : st < (s.capacity f : Word w)) :
+ base ≤ (Allocated.destination scanSlots (scalarPub w s base (.scan side f)) st).val := by
+ let pub := scalarPub w s base (.scan side f)
+ obtain ⟨zero, _, _, destWord⟩ := scan_public fit side f
+ obtain ⟨lo, hi⟩ := dest_bounds s base side f hf
+ have capFit := field_capacity_lt fit f
+ have hcursor : st.val < s.capacity f := by
+ change st.val < (s.capacity f : Word w).val at cursor
+ rwa [Fin.val_cast_of_lt capFit] at cursor
+ have destFit : dest s base side f < 2^w := by omega
+ have destVal : (pub scanSlots.destinationBase).val = dest s base side f := by
+ rw [show pub scanSlots.destinationBase = _ from destWord]
+ exact Nat.mod_eq_of_lt destFit
+ change base ≤ (pub scanSlots.destinationBase + (st - pub scanSlots.firstCursor)).val
+ rw [show pub scanSlots.firstCursor = _ from zero, sub_zero, Fin.val_add, destVal,
+ Nat.mod_eq_of_lt (by omega)]
+ dsimp [adviceBase, rightIndexBase, leftIndexBase, populationAddr, highAddr, indexBase] at lo
+ omega
+
+/-- Any successful scheduled scan preserves every address below the scratch base,
+even with arbitrary descriptor words, branch input and initial cursor. -/
+theorem call_preserves_below (s : Sizes) (base : ℕ) (side : Side) (f : Field)
+ (fit : limit s base ≤ 2^w) (fuel : ℕ) (st : Word w) (m : Memory w) (bits : List Bool)
+ {rep : Report w}
+ (run : let P := ((stageTemplate (.scan side f)).2.instantiate w (rowData w s base (.scan side f))).program
+ execute P fuel (P.start st) m bits = some rep) (a : ℕ) (ha : a < base) :
+ after m rep.events a = m a := by
+ let pub := scalarPub w s base (.scan side f)
+ let pad := decide (f = .padding)
+ let addr : Word w := Fin.ofNat _ a
+ have addrVal : addr.val = a := Nat.mod_eq_of_lt (by rw [limit_eq] at fit; omega)
+ have bounded := (execute_scan s base side f fuel st m bits).symm.trans run
+ apply LiveHeaderBounded.frame_any (Allocated.table scanSlots (cutSlot side) pad) pub
+ (s.capacity f : Word w) fuel st m bits rep bounded a
+ intro inner raw cursor source
+ rw [← addrVal]
+ apply Allocated.report_frame scanSlots (cutSlot side) pad pub st m bits inner source addr _ m
+ intro _
+ by_cases hf : f = .padding
+ · exact Or.inl (decide_eq_true hf)
+ · apply Or.inr
+ intro eq
+ have lo := payload_address s base side f fit hf st cursor
+ change base ≤ (Allocated.destination scanSlots pub st).val at lo
+ rw [← eq, addrVal] at lo
+ omega
+
+end LiveHeaderProgram.ScanRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderScanRows.lean b/lean/OAI/Computability/VPVNP/LiveHeaderScanRows.lean
new file mode 100644
index 0000000000..d7279290a5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderScanRows.lean
@@ -0,0 +1,214 @@
+import OAI.Computability.VPVNP.LiveHeaderProgramFit
+
+/-!
+# Field scans at the live header's scheduled addresses
+
+The descriptor's two words supply the occupied interval. The scheduled row
+supplies the destination and capacity. The processor sites precede scratch,
+so an active copy preserves the remaining source bits and descriptor words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.ScanRows
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule LiveHeaderDescriptors LiveHeader
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The first sixteen words of the scan row, before its wrapper appends the capacity. -/
+private abbrev operands (w : ℕ) (s : Sizes) (base : ℕ) (side : Side) (f : Field) :=
+ scalarPub w s base (.scan side f)
+
+private theorem scan_row (s : Sizes) (base : ℕ) (side : Side) (f : Field) :
+ rowData w s base (.scan side f) ∘ includeFin (by decide : 17 ≤ 17) =
+ LiveHeaderBounded.publicData (operands w s base side f) (s.capacity f : Word w) := by
+ funext j
+ refine Fin.lastCases ?_ (fun k => ?_) j
+ · rw [LiveHeaderBounded.publicData, Fin.snoc_last]
+ rfl
+ · rw [LiveHeaderBounded.publicData, Fin.snoc_castSucc]
+ rfl
+
+private abbrev machine (w : ℕ) (s : Sizes) (base : ℕ) (side : Side) (f : Field) :=
+ ((stageTemplate (.scan side f)).2.instantiate w (rowData w s base (.scan side f))).program
+
+/-- A scheduled scan call executes the bounded field table with its exact public row. -/
+theorem execute_scan (s : Sizes) (base : ℕ) (side : Side) (f : Field) (fuel : ℕ)
+ (st : Word w) (m : Memory w) (bits : List Bool) :
+ let P := ((stageTemplate (.scan side f)).2.instantiate w (rowData w s base (.scan side f))).program
+ let Q := Allocated.boundedProgram scanSlots (cutSlot side) (decide (f = .padding))
+ (scalarPub w s base (.scan side f)) (s.capacity f)
+ execute P fuel (P.start st) m bits = execute Q fuel (Q.start st) m bits := by
+ dsimp only
+ unfold stageTemplate
+ rw [entry_start, scan_row]
+ cases side <;> rfl
+
+private theorem run_scan (s : Sizes) (base : ℕ) (side : Side) (f : Field) (fuel : ℕ)
+ (st : Option (Word w)) (m : Memory w) (bs : List (List Bool)) :
+ runSegment (machine w s base side f) fuel st m bs =
+ runSegment (Allocated.boundedProgram scanSlots (cutSlot side) (decide (f = .padding))
+ (operands w s base side f) (s.capacity f)) fuel st m bs := by
+ have hs : (if side = Side.left then 2 else 3 : Fin 4) = cutSlot side := by cases side <;> rfl
+ unfold machine stageTemplate
+ rw [run_entry, scan_row, hs]
+
+private theorem scan_loaded (s : Sizes) (base : ℕ) (fit : limit s base < 2^w)
+ (side : Side) (f : Field) (m : Memory w) (iv : ℕ × ℕ)
+ (offset : (m (offsetAddr base)).val = iv.1) (count : (m (countAddr base)).val = iv.2) :
+ Allocated.Loaded scanSlots (operands w s base side f) iv m := by
+ obtain ⟨_, ho, hc, _⟩ := scan_public fit.le side f
+ exact ⟨ho ▸ offset, hc ▸ count⟩
+
+/-- The complete native scan copies exactly the occupied field to its scheduled
+destination. Every successful report preserves the linker's tag on replay. -/
+theorem copy_run (hw : 4 ≤ w) (s : Sizes) (base d : ℕ) (fit : limit s base < 2^w)
+ (scratch : 2^d ≤ base) (side : Side) (f : Field) (hf : f ≠ .padding)
+ (m : Memory w) (iv : ℕ × ℕ) (sites : iv.1+iv.2 ≤ 2^d) (capacity : iv.2 ≤ s.capacity f)
+ (offset : (m (offsetAddr base)).val = iv.1) (count : (m (countAddr base)).val = iv.2) :
+ let st := Stage.scan side f
+ let P := ((stageTemplate st).2.instantiate w (rowData w s base st)).program
+ ∃ rs, runSegment P 25 (some 0) m (List.replicate (calls s st) []) = some rs ∧
+ endState (some 0) rs = none ∧ FieldCopy m (cutSlot side) iv.1 (dest s base side f) iv.2
+ (after m (eventLog rs)) ∧ rs.length = calls s st ∧
+ (∀ r ∈ rs, r.probes ≤ probes st) ∧ LiveStageLink.PreservesTag (Fin.ofNat _ base) rs := by
+ dsimp only
+ let pub := operands w s base side f
+ obtain ⟨prefixBound, endFit⟩ := dest_bounds s base side f hf
+ have sep : countAddr base < dest s base side f := by
+ unfold countAddr adviceBase rightIndexBase leftIndexBase populationAddr highAddr indexBase at *
+ omega
+ obtain ⟨_, ho, hc, hdword⟩ := scan_public fit.le side f
+ have hd : (pub scanSlots.destinationBase).val = dest s base side f := by
+ rw [show pub scanSlots.destinationBase = _ from hdword]
+ exact Nat.mod_eq_of_lt (by omega)
+ have hbase : base < 2^w := by unfold countAddr at sep; omega
+ have layout : Allocated.CopyLayout scanSlots pub iv := by
+ constructor
+ all_goals simp only [Allocated.Outside, hd, show (pub scanSlots.srcOffsetAddress).val = _ from ho,
+ show (pub scanSlots.countAddress).val = _ from hc]
+ all_goals unfold offsetAddr countAddr at *; omega
+ have tag : Allocated.Outside (pub scanSlots.destinationBase).val iv.2
+ (Fin.ofNat (2^w) base).val := by
+ rw [hd, show (Fin.ofNat (2^w) base).val = base from Nat.mod_eq_of_lt hbase]
+ exact Or.inl (by unfold countAddr at sep; omega)
+ obtain ⟨rs, run, last, copy, len, hp, frame⟩ := Allocated.copy_bounded hw scanSlots (cutSlot side) pub
+ m iv (s.capacity f) (scan_sizes fit.le side f iv capacity (sites.trans scratch))
+ (scan_loaded s base fit side f m iv offset count) layout (Fin.ofNat _ base) tag
+ rw [hd] at copy
+ refine ⟨rs, ?_, last, copy, len, ?_, frame⟩
+ · change runSegment (machine w s base side f) _ _ _ _ = _
+ rw [run_scan, decide_eq_false hf]
+ exact run
+ · have hprobes : probes (.scan side f) = 4 := by cases f <;> simp_all [probes]
+ rw [hprobes]
+ exact hp
+
+/-- A zero padding interval accepts after its scheduled calls and leaves
+every scratch cell and every packed processor word intact. -/
+theorem padding_run (hw : 4 ≤ w) (s : Sizes) (base d : ℕ) (fit : limit s base < 2^w)
+ (scratch : 2^d ≤ base) (side : Side) (m : Memory w) (iv : ℕ × ℕ)
+ (sites : iv.1+iv.2 ≤ 2^d) (capacity : iv.2 ≤ s.capacity .padding)
+ (offset : (m (offsetAddr base)).val = iv.1) (count : (m (countAddr base)).val = iv.2)
+ (zero : Allocated.ZeroPad (cutSlot side) iv m) :
+ let st := Stage.scan side .padding
+ let P := ((stageTemplate st).2.instantiate w (rowData w s base st)).program
+ ∃ rs, runSegment P 25 (some 0) m (List.replicate (calls s st) []) = some rs ∧
+ endState (some 0) rs = none ∧ after m (eventLog rs) = m ∧ rs.length = calls s st ∧
+ (∀ r ∈ rs, r.probes ≤ probes st) ∧ LiveStageLink.PreservesTag (Fin.ofNat _ base) rs := by
+ dsimp only
+ obtain ⟨rs, run, last, mem, len, hp, frame⟩ := Allocated.padding_bounded hw scanSlots (cutSlot side)
+ (operands w s base side .padding) m iv (s.capacity .padding)
+ (scan_sizes fit.le side .padding iv capacity (sites.trans scratch))
+ (scan_loaded s base fit side .padding m iv offset count) (Fin.ofNat _ base) zero
+ refine ⟨rs, ?_, last, mem, len, hp, frame⟩
+ change runSegment (machine w s base side .padding) _ _ _ _ = _
+ rw [run_scan]
+ exact run
+
+/-- Arbitrary choice strings and an arbitrary source fuel cannot skip a
+nonzero occupied padding bit on an accepting row execution. -/
+theorem padding_sound (hw : 4 ≤ w) (s : Sizes) (base d : ℕ) (fit : limit s base < 2^w)
+ (scratch : 2^d ≤ base) (side : Side) (m : Memory w) (iv : ℕ × ℕ)
+ (sites : iv.1+iv.2 ≤ 2^d) (capacity : iv.2 ≤ s.capacity .padding)
+ (offset : (m (offsetAddr base)).val = iv.1) (count : (m (countAddr base)).val = iv.2)
+ (fuel : ℕ) (bs : List (List Bool)) {rs : List (Report w)}
+ (run : runSegment ((stageTemplate (.scan side .padding)).2.instantiate w
+ (rowData w s base (.scan side .padding))).program (fuel+3) (some 0) m bs = some rs)
+ (last : endState (some 0) rs = none) : Allocated.ZeroPad (cutSlot side) iv m := by
+ change runSegment (machine w s base side .padding) _ _ _ _ = _ at run
+ rw [run_scan] at run
+ exact Allocated.padding_bounded_sound hw scanSlots (cutSlot side) (operands w s base side .padding)
+ m iv (s.capacity .padding) (scan_sizes fit.le side .padding iv capacity (sites.trans scratch))
+ (scan_loaded s base fit side .padding m iv offset count) fuel bs run last
+
+/-- A complete call must execute the three guard instructions and a terminal instruction. -/
+private theorem short_call (s : Sizes) (base : ℕ) (side : Side) (fuel : ℕ) (short : fuel ≤ 3)
+ (st : Word w) (m : Memory w) (bits : List Bool) :
+ let P := machine w s base side .padding
+ execute P fuel (P.start st) m bits = none := by
+ dsimp only
+ unfold machine stageTemplate
+ rw [entry_start]
+ interval_cases fuel <;> rfl
+
+/-- Soundness for every total fuel, including attempts to stop during the guard. -/
+theorem padding_sound_any (hw : 4 ≤ w) (s : Sizes) (base d : ℕ) (fit : limit s base < 2^w)
+ (scratch : 2^d ≤ base) (side : Side) (m : Memory w) (iv : ℕ × ℕ)
+ (sites : iv.1+iv.2 ≤ 2^d) (capacity : iv.2 ≤ s.capacity .padding)
+ (offset : (m (offsetAddr base)).val = iv.1) (count : (m (countAddr base)).val = iv.2)
+ (fuel : ℕ) (bs : List (List Bool)) {rs : List (Report w)}
+ (run : runSegment ((stageTemplate (.scan side .padding)).2.instantiate w
+ (rowData w s base (.scan side .padding))).program fuel (some 0) m bs = some rs)
+ (last : endState (some 0) rs = none) : Allocated.ZeroPad (cutSlot side) iv m := by
+ by_cases room : 3 ≤ fuel
+ · apply padding_sound hw s base d fit scratch side m iv sites capacity offset count (fuel-3) bs _ last
+ rwa [Nat.sub_add_cancel room]
+ · cases bs with
+ | nil => simp only [runSegment, Option.some.injEq] at run; subst rs; contradiction
+ | cons b bs =>
+ change runSegment (machine w s base side .padding) fuel (some 0) m (b::bs) = some rs at run
+ simp only [runSegment, short_call s base side fuel (by omega) 0 m b] at run
+ contradiction
+
+/-- On every successful call of the scheduled padding row, its event log leaves
+every replay address intact. This includes returning calls before an eventual
+failure and the closing call. No descriptor validity is required. -/
+theorem padding_call_frame (s : Sizes) (base : ℕ) (side : Side) (fuel : ℕ) (st : Word w)
+ (m : Memory w) (bits : List Bool) {rep : Report w}
+ (run : let P := ((stageTemplate (.scan side .padding)).2.instantiate w
+ (rowData w s base (.scan side .padding))).program
+ execute P fuel (P.start st) m bits = some rep) (addr : Word w) (replay : Memory w) :
+ after replay rep.events addr.val = replay addr.val := by
+ change execute (machine w s base side .padding) fuel ((machine w s base side .padding).start st) m bits = some rep at run
+ by_cases room : 4 ≤ fuel
+ · replace run := (execute_scan s base side .padding fuel st m bits).symm.trans run
+ let pub := operands w s base side .padding
+ let bound : Word w := s.capacity .padding
+ let T := Allocated.table scanSlots (cutSlot side) true
+ change execute (LiveHeaderBounded.machine T pub bound).program fuel
+ ((LiveHeaderBounded.machine T pub bound).program.start st) m bits = some rep at run
+ by_cases active : st < bound
+ · rw [show fuel = (fuel-3)+3 by omega,
+ LiveHeaderBounded.execute_active T pub bound (fuel-3) st active] at run
+ obtain ⟨raw, hr, rfl⟩ := Option.map_eq_some_iff.mp run
+ exact Allocated.report_frame scanSlots (cutSlot side) true pub st m bits (fuel-3) hr addr
+ (fun _ => Or.inl rfl) replay
+ · rw [show fuel = (fuel-4)+4 by omega,
+ LiveHeaderBounded.execute_closed T pub bound (fuel-4) st (le_of_not_gt active)] at run
+ split at run
+ · obtain rfl := Option.some.inj run
+ rfl
+ · contradiction
+ · rw [short_call s base side fuel (by omega) st m bits] at run
+ contradiction
+
+end LiveHeaderProgram.ScanRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderSchedule.lean b/lean/OAI/Computability/VPVNP/LiveHeaderSchedule.lean
new file mode 100644
index 0000000000..920beb817e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderSchedule.lean
@@ -0,0 +1,177 @@
+import OAI.Computability.VPVNP.LiveHeaderPhysical
+import OAI.Computability.VPVNP.LiveHeaderPhases
+import OAI.Computability.VPVNP.LiveHeaderMode
+import OAI.Computability.VPVNP.PolynomialBounds
+
+/-!
+# Public schedule and scratch addresses for live header recovery
+
+A group's number and its incoming and outgoing cuts stay in external memory.
+The stage order, allocated buffer sizes and per-stage limits are public. Each
+bounded field scan consults the private descriptor before probing a site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderSchedule
+
+open LiveHeaderWidths LiveHeaderDescriptors
+
+/-- The four field sizes selected before the simulation exponent is chosen.
+The chain has height `h+1`. The exponent array has `e=tZ` individual bits. -/
+structure Sizes where
+ /-- The height parameter of the live chain, whose two halves each contain two to this power
+ groups. -/
+ h : ℕ
+ /-- The cut block width used to bound exterior and padding scans. -/
+ delta : ℕ
+ /-- The number of distributed advice bits copied into the live header workspace. -/
+ advice : ℕ
+ /-- The number of bits allocated to each exponent payload. -/
+ e : ℕ
+ /-- The serialized bit length allocated to each evaluator configuration. -/
+ config : ℕ
+
+/-- The stages of header recovery, from copying index and advice through metadata, primed
+indices, and per-field descriptor and scan calls. -/
+inductive Stage where
+ | index | advice | width (s : Slot) | flag (f : Flag) | firstTail | mode
+ | primedInit | primedDigits | descriptor (side : Side) (f : Field) | scan (side : Side) (f : Field)
+
+/-- Descriptors and their consumers always alternate. The two descriptor
+words can therefore be reused for all eight fields. -/
+def stages : List Stage :=
+ [.index,.advice,.width .liveLeft,.width .liveRight,.width .primedLeft,.width .primedMiddle,
+ .width .primedRight,.flag .first,.flag .middle,.flag .firstHalf,.flag .last,.firstTail,
+ .mode,.primedInit,.primedDigits] ++
+ [Side.left,.right].flatMap fun side => [Field.exterior,.exponents,.config,.padding].flatMap
+ fun f => [.descriptor side f,.scan side f]
+
+theorem stage_count : stages.length = 31 := rfl
+
+/-- The public number of positions available for scanning the specified incident field. -/
+def Sizes.capacity (s : Sizes) : Field → ℕ
+ | .exterior | .padding => (s.h+1)*s.delta
+ | .exponents => s.e
+ | .config => s.config
+
+/-- A finite bound on each stage's number of microcalls. A bounded scan
+uses one last, zero-probe call at its public limit to hand off. -/
+def calls (s : Sizes) : Stage → ℕ
+ | .index => s.h+2+1
+ | .advice => s.advice+1
+ | .primedDigits => s.h+1+1
+ | .scan _ f => s.capacity f+1
+ | _ => 1
+
+/-- Per-stage local probes per active call, before the linking tag reads. -/
+def probes : Stage → ℕ
+ | .index => 6
+ | .advice => 2
+ | .firstTail => 4
+ | .mode => 5
+ | .primedDigits => 5
+ | .descriptor .. => 6
+ | .scan _ .padding => 3
+ | .scan .. => 4
+ | _ => 3
+
+theorem probe_limit (i : Stage) : probes i ≤ 6 := by
+ cases i <;> try (dsimp only [probes]; omega)
+ rename_i f
+ cases f <;> dsimp only [probes] <;> omega
+
+/-- Allocating both sides and each public bound costs only polynomially many
+calls. No multiplicative factor of the number of sites occurs. -/
+def callBound (s : Sizes) : ℕ :=
+ 31 + (s.h+2) + s.advice + (s.h+1) + 4*((s.h+1)*s.delta) + 2*s.e + 2*s.config
+
+theorem sum_calls (s : Sizes) : (stages.map (calls s)).sum = callBound s := by
+ simp only [stages, List.flatMap_cons, List.flatMap_nil, List.cons_append, List.nil_append,
+ List.map_cons, List.map_nil, List.sum_cons, List.sum_nil, calls, Sizes.capacity, callBound]
+ omega
+
+/-- The nested native stage dispatcher adds one tag probe per call and at
+most one tag write at handoff. Including the enclosing dispatcher and the
+call itself gives a bound of eleven cost units per call. -/
+def costBound (s : Sizes) := 11 * callBound s
+
+theorem polynomial_cost {S : ℕ → Sizes}
+ (hh : PolynomiallyBounded fun n => (S n).h) (hd : PolynomiallyBounded fun n => (S n).delta)
+ (ha : PolynomiallyBounded fun n => (S n).advice) (he : PolynomiallyBounded fun n => (S n).e)
+ (hc : PolynomiallyBounded fun n => (S n).config) :
+ PolynomiallyBounded fun n => costBound (S n) := by
+ open PolynomiallyBounded in
+ exact (const 11).mul (((((((const 31).add (hh.add (const 2))).add ha).add (hh.add (const 1))).add
+ ((const 4).mul ((hh.add (const 1)).mul hd))).add ((const 2).mul he)).add ((const 2).mul hc))
+
+/-- Widths for the auxiliary header occupy three consecutive words. -/
+def widthAddr (base : ℕ) : Slot → ℕ
+ | .liveLeft => base+1 | .liveRight => base+2 | .primedLeft => base+3
+ | .primedMiddle => base+4 | .primedRight => base+5
+
+/-- Address of the selected first, midpoint, first-half, or last flag in header scratch. -/
+def flagAddr (base : ℕ) : Flag → ℕ
+ | .first => base+6 | .middle => base+7 | .firstHalf => base+8 | .last => base+9
+
+/-- Address of the scratch flag identifying the first evaluator group. -/
+def firstTailAddr (base : ℕ) := base+10
+/-- Address holding the selected live-header mode tag. -/
+def tagAddr (base : ℕ) := base+11
+/-- Address of the scratch word giving the next incident field's source offset. -/
+def offsetAddr (base : ℕ) := base+12
+/-- Address of the scratch word giving the next incident field's occupied length. -/
+def countAddr (base : ℕ) := base+13
+/-- Address of the borrow bit carried through primed index construction. -/
+def borrowAddr (base : ℕ) := base+14
+/-- Start of the unpacked one-based group index in header scratch. -/
+def indexBase (base : ℕ) := base+15
+/-- The cell after the group-index digits recording the highest set-bit position. -/
+def highAddr (s : Sizes) (base : ℕ) := indexBase base + (s.h+2)
+/-- The cell recording the number of set bits in the group index. -/
+def populationAddr (s : Sizes) (base : ℕ) := highAddr s base + 1
+/-- The first cell of the unpacked left primed index, after the index summary. -/
+def leftIndexBase (s : Sizes) (base : ℕ) := populationAddr s base + 1
+/-- The first cell of the unpacked right primed index, after the left index. -/
+def rightIndexBase (s : Sizes) (base : ℕ) := leftIndexBase s base + (s.h+2)
+/-- The first advice cell after both primed index arrays. -/
+def adviceBase (s : Sizes) (base : ℕ) := rightIndexBase s base + (s.h+2)
+/-- The base of the reserved exterior payload interval on the selected incident side. -/
+def exteriorBase (s : Sizes) (base : ℕ) : Side → ℕ
+ | .left => adviceBase s base + s.advice
+ | .right => adviceBase s base + s.advice + s.capacity .exterior
+
+/-- The base of the selected side's exponent array after both exterior reservations. -/
+def exponentBase (s : Sizes) (base : ℕ) : Side → ℕ
+ | .left => exteriorBase s base .right + s.capacity .exterior
+ | .right => exteriorBase s base .right + s.capacity .exterior + s.e
+
+/-- The base of the selected side's evaluator configuration array after the exponent arrays. -/
+def configBase (s : Sizes) (base : ℕ) : Side → ℕ
+ | .left => exponentBase s base .right + s.e
+ | .right => exponentBase s base .right + s.e + s.config
+
+/-- First address available to another module. The tag used to dispatch
+among the header stages is at `base`, separate from the emitted mode tag. -/
+def limit (s : Sizes) (base : ℕ) := configBase s base .right + s.config
+
+theorem limit_eq (s : Sizes) (base : ℕ) :
+ limit s base = base + 17 + 3*(s.h+2) + s.advice + 2*((s.h+1)*s.delta) + 2*s.e + 2*s.config := by
+ simp [limit,configBase,exponentBase,exteriorBase,adviceBase,rightIndexBase,leftIndexBase,populationAddr,highAddr,indexBase,Sizes.capacity]
+ omega
+
+/-- The destination address of a copied incident payload, with a dummy zero address for padding
+checks. -/
+def dest (s : Sizes) (base : ℕ) (side : Side) : Field → ℕ
+ | .exterior => exteriorBase s base side
+ | .exponents => exponentBase s base side
+ | .config => configBase s base side
+ | .padding => 0
+
+end LiveHeaderSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderShapes.lean b/lean/OAI/Computability/VPVNP/LiveHeaderShapes.lean
new file mode 100644
index 0000000000..d8ea0d0921
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderShapes.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.LiveHeaderPhases
+
+/-!
+# Field intervals for the live incident cuts
+
+In the unit mode all nonmode bits form a single zero-padding interval.
+In the simulation mode the cut carries the exterior and exponents up
+to and including the midpoint, then the evaluator configuration. Missing
+cuts and empty payloads have no sites to visit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderDescriptors
+
+/-- The incoming left or outgoing right side of the group whose incident cut is being parsed. -/
+inductive Side where | left | right deriving DecidableEq
+/-- The payload or padding interval requested from a live incident cut. -/
+inductive Field where | exterior | exponents | config | padding deriving DecidableEq
+/-- The cut formats governing field lengths, covering absent endpoints, unit mode, paired
+computation, and evaluator tail. -/
+inductive Shape where | missing | unit | pair | tail deriving DecidableEq
+
+/-- The first tail group's left cut is the midpoint, so it still has the
+pair layout even though the group's own mode dispatch chose the tail. -/
+def shape (side : Side) (width tag : ℕ) (firstHalf firstTail : Bool) : Shape :=
+ if width = 0 then .missing else if tag = 0 then .unit else
+ if firstHalf || (decide (side = .left) && firstTail) then .pair else .tail
+
+/-- The index of the left or right incident cut of a one-based group. -/
+def cutIndex (side : Side) (group : ℕ) := match side with | .left => group - 1 | .right => group
+
+/-- The index-based flag dispatch produces the layout of the incident cut
+itself. In particular the group just after the midpoint has different
+layouts on its two sides. -/
+theorem shape_at_group (h group tag : ℕ) (side : Side) (W : ℕ) :
+ shape side W tag (decide (group ≤ 2^h)) (decide (group = 2^h+1)) =
+ if W = 0 then .missing else if tag = 0 then .unit else
+ if cutIndex side group ≤ 2^h then .pair else .tail := by
+ cases side
+ · have he : group ≤ 2^h ∨ group = 2^h+1 ↔ group-1 ≤ 2^h := by
+ constructor
+ · rintro (he | he)
+ · exact (Nat.sub_le group 1).trans he
+ · simp [he]
+ · intro he
+ by_cases hl : group ≤ 2^h
+ · exact Or.inl hl
+ · exact Or.inr (by omega)
+ simp [shape, cutIndex, he]
+ · simp [shape, cutIndex]; rfl
+
+/-- Natural-number lengths for the three payloads, in their physical order. -/
+def exterior (form : Shape) (W Δ : ℕ) : ℕ := if form = .pair then W-Δ else 0
+/-- The occupied exponent length for a cut shape, equal to the supplied exponent size on a pair
+cut. -/
+def exponents (form : Shape) (e : ℕ) : ℕ := if form = .pair then e else 0
+/-- The occupied configuration length for a cut shape, equal to the supplied configuration size
+on a tail cut. -/
+def config (form : Shape) (c : ℕ) : ℕ := if form = .tail then c else 0
+/-- The length occupied by the leading mode bit, zero at a missing cut and one on a nonempty
+cut. -/
+def mode (W : ℕ) := if W = 0 then 0 else 1
+
+/-- The offset of the requested field after the mode bit and preceding enabled payloads. -/
+def start (form : Shape) (W Δ e c : ℕ) : Field → ℕ
+ | .exterior => mode W
+ | .exponents => mode W + exterior form W Δ
+ | .config => mode W + exterior form W Δ + exponents form e
+ | .padding => mode W + exterior form W Δ + exponents form e + config form c
+
+/-- The occupied length of the specified field, assigning the remainder of the cut to padding. -/
+def count (form : Shape) (W Δ e c : ℕ) : Field → ℕ
+ | .exterior => exterior form W Δ
+ | .exponents => exponents form e
+ | .config => config form c
+ | .padding => W - start form W Δ e c .padding
+
+/-- No source address is used for an empty field; its offset word is zero. -/
+def span (form : Shape) (W Δ e c : ℕ) (f : Field) : ℕ × ℕ :=
+ let length := count form W Δ e c f
+ (if length = 0 then 0 else start form W Δ e c f, length)
+
+/-- The largest nonpadding prefix ends at or before the cut boundary. -/
+theorem payload_le {form : Shape} {W Δ e c : ℕ} (he : 1+e ≤ Δ) (hc : 1+c ≤ Δ)
+ (hp : form = .pair ∨ form = .tail → Δ ≤ W) :
+ start form W Δ e c .padding ≤ W := by
+ cases form <;> simp [start, exterior, exponents, config, mode] at * <;> split_ifs <;> omega
+
+/-- After the mode bit these four consecutive fields cover every site. -/
+theorem partition {form : Shape} {W Δ e c : ℕ} (he : 1+e ≤ Δ) (hc : 1+c ≤ Δ)
+ (hp : form = .pair ∨ form = .tail → Δ ≤ W) :
+ mode W + count form W Δ e c .exterior + count form W Δ e c .exponents +
+ count form W Δ e c .config + count form W Δ e c .padding = W :=
+ Nat.add_sub_of_le (payload_le he hc hp)
+
+/-- Every emitted interval lies inside the supplied cut. -/
+theorem span_fit {form : Shape} {W Δ e c : ℕ} (he : 1+e ≤ Δ) (hc : 1+c ≤ Δ)
+ (hp : form = .pair ∨ form = .tail → Δ ≤ W) (f : Field) :
+ (span form W Δ e c f).1 + (span form W Δ e c f).2 ≤ W := by
+ have h := payload_le he hc hp
+ change (if count form W Δ e c f = 0 then 0 else start form W Δ e c f) + count form W Δ e c f ≤ W
+ split_ifs with hz
+ · simp [hz]
+ · cases f <;> simp only [count, start] at * <;> omega
+
+/-- Every nonempty cut has at least one full block under equation (9.1). -/
+theorem width_ge_block (H Δ j : ℕ) :
+ CutSchedule.width H Δ j = 0 ∨ Δ ≤ CutSchedule.width H Δ j := by
+ unfold CutSchedule.width
+ split_ifs with hi
+ · right
+ have := Nat.log_lt_of_lt_pow hi.1.ne' hi.2
+ simpa using Nat.mul_le_mul_right Δ (show 1 ≤ H - Nat.log 2 j by omega)
+ · exact Or.inl rfl
+
+theorem shape_fit {side : Side} {W Δ tag : ℕ} {half firstTail : Bool}
+ (hW : W = 0 ∨ Δ ≤ W) :
+ shape side W tag half firstTail = .pair ∨ shape side W tag half firstTail = .tail → Δ ≤ W := by
+ rcases hW with rfl | h
+ · simp [shape]
+ · exact fun _ => h
+
+/-- A pair-layout outgoing live cut carries exactly the primed exterior
+at twice its index, including the midpoint where that exterior is empty. -/
+theorem pair_exterior (h Δ i : ℕ) (hi : 0 < i) (hle : i ≤ 2^h) :
+ exterior .pair (CutSchedule.width (h+1) Δ i) Δ = CutSchedule.width (h+1) Δ (2*i) := by
+ simp [exterior, CutSchedule.width_double h Δ i hi hle]
+
+/-- At the middle cut the exponents start immediately after the mode. -/
+theorem midpoint_exterior (h Δ : ℕ) : exterior .pair (CutSchedule.width (h+1) Δ (2^h)) Δ = 0 := by
+ rw [pair_exterior h Δ (2^h) (Nat.two_pow_pos h) le_rfl, ← pow_succ', CutSchedule.width_end]
+
+end LiveHeaderDescriptors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderSingleRun.lean b/lean/OAI/Computability/VPVNP/LiveHeaderSingleRun.lean
new file mode 100644
index 0000000000..e283979822
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderSingleRun.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.LiveHeaderScalarStages
+import OAI.Computability.VPVNP.LiveHeaderPrefix
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule
+
+/-- One scalar stage in the combined instruction table, including the native
+handoff write and cursor reset. -/
+theorem SingleRun.prefix {w : ℕ} {s : Sizes} {base : ℕ} {st : Stage} {m final : Memory w}
+ (run : SingleRun s base st m final) (id : StageId) (hid : stage id = st) (hc : calls s st = 1) :
+ ∃ x : StageTrace w, x.id = id ∧ x.Good s ∧
+ StagePrefix s base (some id) m [x] (next id)
+ (LiveStageLink.transferMemory (Fin.ofNat _ base) (next id) final) := by
+ obtain ⟨es,hr,hm,_,hp,_⟩ := run
+ let rep : Report w := ⟨es,none⟩
+ let x : StageTrace w := ⟨id,40,[[]],[rep]⟩
+ have hx : x.Exec s base m := by
+ constructor
+ · change runSegment ((stageTemplate (stage id)).2.instantiate w (rowData w s base (stage id))).program
+ 40 (some 0) m [[]] = some [rep]
+ rw [hid]
+ simp [runSegment,hr,rep]
+ · rfl
+ · exact LiveStageLink.PreservesTagOnReturns.singleton_accept _ _ _ rfl
+ have hgood : x.Good s := by
+ simp only [StageTrace.Good,x,hid,hc,List.replicate_succ,List.replicate_zero,List.length_singleton,
+ List.mem_singleton,forall_eq,le_refl,true_and]
+ exact hp
+ have hend : x.finalMem (Fin.ofNat _ base) m =
+ LiveStageLink.transferMemory (Fin.ofNat _ base) (next id) final := by
+ simp [StageTrace.finalMem,x,rep,eventLog,hm]
+ exact ⟨x,rfl,hgood,hend ▸ StagePrefix.single hx⟩
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderSitePowers.lean b/lean/OAI/Computability/VPVNP/LiveHeaderSitePowers.lean
new file mode 100644
index 0000000000..4604e7528f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderSitePowers.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.LiveWordCapacity
+
+/-!
+# Powers of two in the live header operand bank
+
+All addresses and scan limits in a header row combine the base address and
+the five public lengths by addition and multiplication. Thus each row, its
+zero padding, and the appended stage tag preserve the site-power restriction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.HeaderLayout
+
+open LiveHeaderWidths LiveHeaderDescriptors
+
+variable {s : Lengths} {b : PublicExpr}
+variable (hh : s.h.SitePowers) (hd : s.delta.SitePowers) (ha : s.advice.SitePowers)
+variable (he : s.e.SitePowers) (hc : s.config.SitePowers) (hb : b.SitePowers)
+
+local macro "header_arith" : tactic => `(tactic|
+ repeat' first | assumption | exact True.intro | constructor)
+
+include hh hb in
+@[simp] theorem advice_sitePowers : (advice s b).SitePowers := by header_arith
+
+include hh hd ha hb in
+@[simp] theorem exterior_sitePowers (side : Side) : (exterior s b side).SitePowers := by
+ cases side <;> header_arith
+
+include hh hd ha he hb in
+@[simp] theorem exponent_sitePowers (side : Side) : (exponent s b side).SitePowers := by
+ cases side <;> header_arith
+
+include hh hd ha he hc hb in
+@[simp] theorem config_sitePowers (side : Side) : (config s b side).SitePowers := by
+ cases side <;> header_arith
+
+include hh hd ha he hc hb in
+@[simp] theorem limit_sitePowers : (limit s b).SitePowers := by header_arith
+
+include hh hd ha he hc hb in
+private theorem row_sitePowers (st : LiveHeaderSchedule.Stage) :
+ ∀ e ∈ row s b st, e.SitePowers := by
+ cases st
+ case' width slot => cases slot
+ case' flag f => cases f
+ case' descriptor side _ => cases side
+ case' scan side f => cases side <;> cases f
+ all_goals
+ simp [row]
+ header_arith
+
+include hh hd ha he hc hb in
+/-- Every operand, including default words of short rows, preserves the
+restriction on exponential operands inherited from the public layout. -/
+@[simp] theorem operands_sitePowers (j : Fin (LiveHeaderSchedule.stages.length*17+1)) :
+ (operands s b j).SitePowers := by
+ refine Fin.lastCases ?_ (fun i => ?_) j
+ · simpa only [operands, Fin.snoc_last] using hb
+ · simp only [operands, Fin.snoc_castSucc]
+ let p := finProdFinEquiv.symm i
+ let st := LiveHeaderProgram.stage p.1
+ change (((row s b st)[p.2.val]?).getD 0).SitePowers
+ cases h : (row s b st)[p.2.val]? with
+ | none => trivial
+ | some e => exact row_sitePowers hh hd ha he hc hb st e (List.mem_of_getElem? h)
+
+end LiveProgram.HeaderLayout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderSparseLayout.lean b/lean/OAI/Computability/VPVNP/LiveHeaderSparseLayout.lean
new file mode 100644
index 0000000000..15dd34ee1b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderSparseLayout.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.LiveAuxiliaryHeaders
+import Mathlib.Tactic.FinCases
+
+/-!
+# Dense iteration over the sparse auxiliary header
+
+A cursor visits the three cut lengths, the two primed group indices, the
+advice, both exterior cuts and the nominations. The destination skips the
+unused capacity after each exterior field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveAuxiliaryHeaders
+
+open PrimedInputRAM
+
+/-- Cumulative starts, ending with the exact count of populated words. -/
+def rangeStart (L : Lengths) (labels : ℕ) : Fin 8 → ℕ :=
+ ![0, 3, 3+L.index, 3+2*L.index, exteriorBase L, exteriorBase L+L.leftCut,
+ exteriorBase L+L.leftCut+L.rightCut, exteriorBase L+L.leftCut+L.rightCut+labels]
+
+/-- The number of words actually visited by the auxiliary copy sweep over all seven input
+fields. -/
+def populated (L : Lengths) (labels : ℕ) := rangeStart L labels 7
+
+/-- Offsets in the virtual machine's actual header, including capacity holes. -/
+def destinationStart (L : Lengths) : Fin 7 → ℕ :=
+ ![0, 3, 3+L.index, 3+2*L.index, exteriorBase L, exteriorBase L+L.cutCapacity, Header.count L]
+
+private theorem starts_monotone (L : Lengths) (N : ℕ) : Monotone (rangeStart L N) := by
+ apply Fin.monotone_iff_le_succ.mpr
+ intro i
+ fin_cases i <;> simp [rangeStart, exteriorBase]
+ omega
+
+private theorem hasRange (L : Lengths) (N : ℕ) (i : Fin (populated L N)) :
+ ∃ j : Fin 7, rangeStart L N j.castSucc ≤ i.val ∧ i.val < rangeStart L N j.succ := by
+ by_contra! h
+ have hb (j : Fin 8) : rangeStart L N j ≤ i.val := by
+ induction j using Fin.induction with
+ | zero => exact Nat.zero_le _
+ | succ j ih => exact h j ih
+ exact i.isLt.not_ge (hb 7)
+
+/-- The descriptor containing a packed cursor; the RAM dispatcher performs the
+corresponding seven comparisons directly. -/
+noncomputable def rangeAt (L : Lengths) (N : ℕ) (i : Fin (populated L N)) : Fin 7 :=
+ (hasRange L N i).choose
+
+theorem rangeAt_bounds (L : Lengths) (N : ℕ) (i : Fin (populated L N)) :
+ rangeStart L N (rangeAt L N i).castSucc ≤ i.val ∧ i.val < rangeStart L N (rangeAt L N i).succ :=
+ (hasRange L N i).choose_spec
+
+theorem rangeAt_skips (L : Lengths) (N : ℕ) (i : Fin (populated L N)) (j : Fin 7)
+ (h : j < rangeAt L N i) : rangeStart L N j.succ ≤ i.val :=
+ (starts_monotone L N (by change j.val + 1 ≤ (rangeAt L N i).val; exact h)).trans
+ (rangeAt_bounds L N i).1
+
+theorem rangeEnd_le (L : Lengths) (N : ℕ) (j : Fin 7) :
+ rangeStart L N j.succ ≤ populated L N := starts_monotone L N (Fin.le_last _)
+
+/-- Map a dense copy cursor to its shadow offset, skipping unused exterior capacity before the
+next field. -/
+def sparseOffset (L : Lengths) (N : ℕ) (i : Fin (populated L N)) : Fin (span L N) :=
+ let left := exteriorBase L + L.leftCut
+ let right := left + L.rightCut
+ ⟨if i.val < left then i.val else if i.val < right then
+ exteriorBase L + L.cutCapacity + (i.val-left) else Header.count L + (i.val-right), by
+ have hi : i.val < exteriorBase L + L.leftCut + L.rightCut + N := i.isLt
+ have := L.leftFit
+ have := L.rightFit
+ by_cases hl : i.val < left <;> by_cases hr : i.val < right <;>
+ simp only [hl, hr, ite_true, ite_false] <;>
+ dsimp only [right, left, exteriorBase, span, Header.count] at * <;> omega⟩
+
+theorem sparseOffset_at_range (L : Lengths) (N : ℕ) (i : Fin (populated L N)) :
+ (sparseOffset L N i).val = destinationStart L (rangeAt L N i) +
+ (i.val - rangeStart L N (rangeAt L N i).castSucc) := by
+ have h := rangeAt_bounds L N i
+ generalize he : rangeAt L N i = j at h ⊢
+ by_cases hl : i.val < exteriorBase L + L.leftCut <;>
+ by_cases hr : i.val < exteriorBase L + L.leftCut + L.rightCut <;>
+ simp only [sparseOffset, hl, hr, ite_true, ite_false] <;>
+ fin_cases j <;> norm_num [rangeStart, destinationStart, exteriorBase] at h hl hr ⊢ <;> omega
+
+theorem sparseOffset_range (L : Lengths) (N : ℕ) (j : Fin (span L N)) :
+ j ∈ cells L N ↔ ∃ i : Fin (populated L N), sparseOffset L N i = j := by
+ have hleft := L.leftFit
+ have hright := L.rightFit
+ have hj : j.val < Header.count L + N := j.isLt
+ rw [mem_cells]
+ constructor
+ · rintro (h | ⟨h₁,h₂⟩ | h)
+ · refine ⟨⟨j.val, ?_⟩, ?_⟩
+ · change j.val < exteriorBase L + L.leftCut + L.rightCut + N
+ omega
+ · exact Fin.ext (ite_eq_left h)
+ · let v := exteriorBase L + L.leftCut + (j.val - (exteriorBase L + L.cutCapacity))
+ have lo : exteriorBase L + L.leftCut ≤ v := by dsimp [v]; omega
+ have hi : v < exteriorBase L + L.leftCut + L.rightCut := by dsimp [v]; omega
+ refine ⟨⟨v, (hi.trans_le (Nat.le_add_right ..))⟩, Fin.ext ?_⟩
+ simp only [sparseOffset, ite_eq_right lo.not_gt, ite_eq_left hi, v]
+ omega
+ · let v := exteriorBase L + L.leftCut + L.rightCut + (j.val - Header.count L)
+ have lo : exteriorBase L + L.leftCut + L.rightCut ≤ v := by dsimp [v]; omega
+ have hi : v < exteriorBase L + L.leftCut + L.rightCut + N := by dsimp [v]; omega
+ refine ⟨⟨v, hi⟩, Fin.ext ?_⟩
+ simp only [sparseOffset, ite_eq_right lo.not_gt, ite_eq_right (by omega : ¬v < exteriorBase L + L.leftCut), v]
+ omega
+ · rintro ⟨i,rfl⟩
+ by_cases hl : i.val < exteriorBase L + L.leftCut
+ · exact Or.inl (by simpa only [sparseOffset, ite_eq_left hl] using hl)
+ · by_cases hr : i.val < exteriorBase L + L.leftCut + L.rightCut
+ · refine Or.inr (Or.inl ?_)
+ simp only [sparseOffset, ite_eq_right hl, ite_eq_left hr]
+ omega
+ · refine Or.inr (Or.inr ?_)
+ simp only [sparseOffset, ite_eq_right hl, ite_eq_right hr]
+ omega
+
+end LiveAuxiliaryHeaders
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderUnique.lean b/lean/OAI/Computability/VPVNP/LiveHeaderUnique.lean
new file mode 100644
index 0000000000..0a0dd6638e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderUnique.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.LiveHeaderProgramRun
+import OAI.Computability.VPVNP.RAMChoicePrefix
+
+/-!
+# Uniqueness of the native header path
+
+A successful call with the empty choice string executes no binary-choice
+instruction. All surplus choices are therefore rejected. Repeating this
+argument along the verified header stages proves exact path uniqueness,
+including the position of the accepting call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- A successful empty-input call forces both its branch input and its report. -/
+theorem execute_empty_forces {P : Program w C} {fuel : ℕ} {c : C} {m : Memory w} {r t : Report w}
+ {bits : List Bool} (h : execute P fuel c m [] = some r) (hb : execute P fuel c m bits = some t) :
+ bits = [] ∧ t = r := by
+ have forced := execute_prefix_unique (suffix := bits) h hb
+ exact ⟨forced.1,forced.2.symm⟩
+
+/-- If the empty choice list succeeds at each call and the last call accepts,
+this is the sole accepting path at that start state, memory and fuel. -/
+theorem accepted_empty_unique {P : Program w C} {fuel n : ℕ} {s : Option (Word w)} {m : Memory w}
+ {rs ts : List (Report w)} {bs : List (List Bool)}
+ (h : runSegment P fuel s m (List.replicate n []) = some rs) (he : endState s rs = none)
+ (hb : runSegment P fuel s m bs = some ts) (hbe : endState s ts = none) :
+ bs = List.replicate n [] ∧ ts = rs := by
+ induction n generalizing s m rs ts bs with
+ | zero =>
+ simp only [List.replicate_zero,runSegment,Option.some.injEq] at h
+ subst rs
+ change s = none at he
+ subst s
+ cases bs <;> simp_all [runSegment]
+ | succ n ih =>
+ rw [List.replicate_succ] at h ⊢
+ cases s with
+ | none => simp [runSegment] at h
+ | some st =>
+ cases bs with
+ | nil => simp [runSegment] at hb; subst ts; contradiction
+ | cons b bs =>
+ simp only [runSegment] at h hb
+ cases hfirst : execute P fuel (P.start st) m [] with
+ | none => simp [hfirst] at h
+ | some r =>
+ cases hother : execute P fuel (P.start st) m b with
+ | none => simp [hother] at hb
+ | some t =>
+ obtain ⟨rfl, rfl⟩ := execute_empty_forces hfirst hother
+ simp only [hfirst, Option.map_eq_some_iff] at h hb
+ obtain ⟨rest, hr, rfl⟩ := h
+ obtain ⟨other, ho, rfl⟩ := hb
+ obtain ⟨rfl, rfl⟩ := ih hr he ho hbe
+ exact ⟨rfl, rfl⟩
+
+end BurstRAM
+
+namespace LiveHeaderProgram
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule
+
+variable {w : ℕ}
+
+/-- The physical header table admits exactly one accepted native path when
+the scheduled source reports are produced by deterministic microcalls. -/
+theorem accepted_path_unique (s : Sizes) (base cap : ℕ) (hfits : stages.length ≤ 2^w)
+ {m : Memory w} {xs : List (StageTrace w)} (h : StageRuns s base (some (⟨0, by decide⟩ : StageId)) m xs)
+ (hroom : ∀ x ∈ xs, x.fuel + 2*stages.length+5 ≤ cap) (htag : m (Fin.ofNat (2^w) base).val = 0)
+ (hchoice : ∀ x ∈ xs, ∀ b ∈ x.paths, b = [])
+ {bs : List (List Bool)} {out : List (Report w)}
+ (hr : runSegment (program.instantiate w (publicData w s base)).program cap (some 0) m bs = some out)
+ (ha : endState (some 0) out = none) :
+ bs = xs.flatMap StageTrace.paths ∧ out = xs.flatMap (fun x => x.output (Fin.ofNat _ base)) := by
+ obtain ⟨hrun,haccept,_,_⟩ := run_of_stages s base cap hfits h hroom (by rintro i ⟨⟩; exact htag)
+ have heq : xs.flatMap StageTrace.paths = List.replicate (xs.flatMap StageTrace.paths).length [] := by
+ apply List.eq_replicate_length.mpr
+ intro b hb
+ obtain ⟨x,hx,hb⟩ := List.mem_flatMap.mp hb
+ exact hchoice x hx b hb
+ rw [heq] at hrun
+ obtain ⟨hbs, hout⟩ := accepted_empty_unique hrun haccept hr ha
+ exact ⟨hbs.trans heq.symm, hout⟩
+
+end LiveHeaderProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderWidthCode.lean b/lean/OAI/Computability/VPVNP/LiveHeaderWidthCode.lean
new file mode 100644
index 0000000000..041b5330c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderWidthCode.lean
@@ -0,0 +1,264 @@
+import OAI.Computability.VPVNP.LiveHeaderWidths
+import OAI.Computability.VPVNP.PrimedStackRAMNodeTable
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Native word code for the five first-half cut widths
+
+Each output word uses two reads from the index-scan scratch and one
+write. Word division computes the two indicator bits: `1 / count` for
+a power of two and `high / high` for a group other than the first.
+The RAM uses natural division with zero quotient on a zero divisor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderWidths
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+
+/-- Public words containing the two geometric parameters and three addresses. -/
+structure Parameters where
+ /-- The public operand index supplying the cut-schedule height. -/
+ height : Fin 16
+ /-- The public operand index supplying the basic block width that scales the computed cut
+ length. -/
+ delta : Fin 16
+ /-- The public operand index for the cell containing the highest set position in the group
+ index. -/
+ highestAddress : Fin 16
+ /-- The public operand index for the group index's population-count cell. -/
+ populationAddress : Fin 16
+ /-- The public operand index for the destination of the computed cut width. -/
+ outputAddress : Fin 16
+
+namespace WidthCode
+
+variable {w : ℕ}
+
+private abbrev Pub := Fin 16
+private abbrev Code := Flow 48 16
+private abbrev Reg := Fin 48
+
+/-- Load the two small summary words and compute the two unshifted block
+counts. The live group index itself is distributed over header bits. -/
+def setup (p : Parameters) : Code :=
+ straight (.constant 1 1) [
+ .publicWord 2 p.height, .publicWord 3 p.delta, .publicWord 4 p.highestAddress,
+ .publicWord 5 p.populationAddress, .publicWord 6 p.outputAddress, .read 7 4, .read 8 5,
+ .binary .div 9 1 8, .binary .sub 10 2 7, .binary .sub 11 10 1, .binary .div 12 7 7]
+
+/-- Place the appropriate block count in register 13. -/
+def select : Slot → Code
+ | .liveLeft => straight (.binary .add 13 10 9) [.binary .mul 13 13 12]
+ | .liveRight => .line (.copy 13 10)
+ | .primedLeft => straight (.binary .add 13 11 9) [.binary .mul 13 13 12]
+ | .primedMiddle => .line (.binary .add 13 11 9)
+ | .primedRight => .line (.copy 13 11)
+
+/-- Multiply the selected block count by the basic block width and write the resulting cut
+length. -/
+def commit : Code := straight (.binary .mul 14 13 3) [.write 6 14]
+
+/-- Load the scanned index summary, compute the requested live or primed block count, and
+publish its width. -/
+def block (p : Parameters) (s : Slot) : Code := .seq (setup p) (.seq (select s) commit)
+
+/-- The physical instruction and public-field table is independent of word width. -/
+def table (p : Parameters) (s : Slot) := (block p s).template none
+
+private def setupEvents (pub : Pub → Word w) (p : Parameters) (m : Memory w) : List (Event w) :=
+ List.replicate 6 .tick ++ [.read (pub p.highestAddress) (m (pub p.highestAddress).val),
+ .read (pub p.populationAddress) (m (pub p.populationAddress).val)] ++ List.replicate 4 .tick
+
+/-- Exact external probes and arithmetic ticks, including the final write. -/
+def events (pub : Pub → Word w) (p : Parameters) (m : Memory w) (s : Slot) (v : Word w) :
+ List (Event w) :=
+ setupEvents pub p m ++ (List.replicate (select s).length .tick ++ [.tick,.write (pub p.outputAddress) v])
+
+theorem event_cost (pub : Pub → Word w) (p : Parameters) (m : Memory w) (s : Slot) (v : Word w) :
+ countProbes (events pub p m s v) = 3 ∧ choiceBits (events pub p m s v) = [] ∧
+ (events pub p m s v).length ≤ 16 := by
+ cases s <;> exact ⟨rfl,rfl,by first | exact Nat.le_refl 16 | exact Nat.le_succ 15⟩
+
+private def wordOne (w : ℕ) : Word w := Fin.ofNat _ 1
+
+private def loaded (pub : Pub → Word w) (p : Parameters) (m : Memory w) (rs : Regs w 48) : Regs w 48 :=
+ let k := m (pub p.highestAddress).val
+ let c := m (pub p.populationAddress).val
+ let b := BinaryOp.sub.eval (pub p.height) k
+ let vals : List (Reg × Word w) :=
+ [(1,wordOne w),(2,pub p.height),(3,pub p.delta),(4,pub p.highestAddress),
+ (5,pub p.populationAddress),(6,pub p.outputAddress),(7,k),(8,c),
+ (9,BinaryOp.div.eval (wordOne w) c),(10,b),(11,BinaryOp.sub.eval b (wordOne w)),
+ (12,BinaryOp.div.eval k k)]
+ vals.foldl (fun a j => Function.update a j.1 j.2) rs
+
+private theorem setup_exec (pub : Pub → Word w) (p : Parameters) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) : Flow.Exec pub state (setup p) rs m (setupEvents pub p m) (loaded pub p m rs) m :=
+ (Flow.once_sound pub state false (setup p) rs m rfl).1
+
+private def chosen (rs : Regs w 48) : Slot → Word w
+ | .liveLeft => (rs 10 + rs 9) * rs 12
+ | .liveRight => rs 10
+ | .primedLeft => (rs 11 + rs 9) * rs 12
+ | .primedMiddle => rs 11 + rs 9
+ | .primedRight => rs 11
+
+private theorem select_exec (pub : Pub → Word w) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) (s : Slot) : ∃ out,
+ Flow.Exec pub state (select s) rs m (List.replicate (select s).length .tick) out m ∧
+ out 13 = chosen rs s ∧ out 3 = rs 3 ∧ out 6 = rs 6 := by
+ let initial : Regs w 48 := match s with
+ | .liveLeft => Function.update rs 13 (rs 10 + rs 9)
+ | .primedLeft => Function.update rs 13 (rs 11 + rs 9)
+ | _ => rs
+ let out := Function.update initial (13 : Reg) (chosen rs s)
+ refine ⟨out, ?_, ?_, ?_, ?_⟩
+ · apply (Flow.once_sound pub state false _ rs m ?_).1
+ cases s <;> rfl
+ all_goals cases s <;> rfl
+
+private theorem commit_exec (pub : Pub → Word w) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) :
+ let v := rs 13 * rs 3
+ Flow.Exec pub state commit rs m [.tick,.write (rs 6) v] (Function.update rs 14 v)
+ (writeMemory m (rs 6) v) :=
+ (Flow.once_sound pub state false commit rs m rfl).1
+
+/-- On groups outside the first half, unused primed lengths are still
+computed by the same straight-line table. Its only write is its output. -/
+theorem unconditional_exec (pub : Pub → Word w) (p : Parameters) (state : Word w)
+ (m : Memory w) (rs : Regs w 48) (s : Slot) :
+ ∃ v out, Flow.Exec pub state (block p s) rs m (events pub p m s v) out
+ (writeMemory m (pub p.outputAddress) v) := by
+ let a := loaded pub p m rs
+ obtain ⟨b,hs,_,_,h₆⟩ := select_exec pub state m a s
+ have hb : b 6 = pub p.outputAddress := h₆
+ have commitRun := commit_exec pub state m b
+ dsimp only at commitRun
+ rw [hb] at commitRun
+ exact ⟨_,_,(setup_exec pub p state m rs).seq (hs.seq commitRun)⟩
+
+private theorem div_val (x y : Word w) : (BinaryOp.div.eval x y).val = x.val / y.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)
+
+private theorem chosen_val (pub : Pub → Word w) (p : Parameters) (m : Memory w) (rs : Regs w 48)
+ (s : Slot) (H k c : ℕ) (hH : 0 < H) (hk : k ≤ H)
+ (hs : s = .liveLeft ∨ s = .liveRight ∨ k < H)
+ (hh : (pub p.height).val = H) (hk' : (m (pub p.highestAddress).val).val = k)
+ (hc' : (m (pub p.populationAddress).val).val = c) :
+ (chosen (loaded pub p m rs) s).val = blocks H k c s := by
+ let a := loaded pub p m rs
+ have ht := (pub p.height).isLt
+ rw [hh] at ht
+ have ho : (wordOne w).val = 1 := Nat.mod_eq_of_lt (by omega)
+ have hk7 : (a 7).val = k := hk'
+ have hc8 : (a 8).val = c := hc'
+ have he : (a 9).val = (if c = 1 then 1 else 0) := by
+ change (BinaryOp.div.eval (wordOne w) (a 8)).val = _
+ rw [div_val, ho, hc8]
+ split_ifs with he
+ · simp [he]
+ · rcases Nat.eq_zero_or_pos c with hz | hp
+ · simp [hz]
+ · exact Nat.div_eq_of_lt (by omega)
+ have hb : (a 10).val = H-k := by
+ change (pub p.height - a 7).val = _
+ rw [Fin.sub_val_of_le (by change (a 7).val ≤ _; omega), hh, hk7]
+ have hd (hshift : k < H) : (a 11).val = H-k-1 := by
+ change (a 10 - wordOne w).val = _
+ rw [Fin.sub_val_of_le (by change (wordOne w).val ≤ _; omega), hb, ho]
+ have hm : (a 12).val = if k = 0 then 0 else 1 := by
+ change (BinaryOp.div.eval (a 7) (a 7)).val = _
+ rw [div_val, hk7]
+ split_ifs with hz
+ · simp [hz]
+ · exact Nat.div_self (by omega)
+ have he1 : (a 9).val ≤ 1 := by rw [he]; split_ifs <;> omega
+ have hdadd (hshift : k < H) : (a 11 + a 9).val = (a 11).val + (a 9).val :=
+ Fin.val_add_eq_of_add_lt (by have := hd hshift; omega)
+ have hzero (x : Word w) (hz : k = 0) : (x * a 12).val = 0 := by
+ rw [Fin.val_mul, hm, ite_eq_left hz, Nat.mul_zero, Nat.zero_mod]
+ have hkeep (x : Word w) (hz : k ≠ 0) : (x * a 12).val = x.val := by
+ rw [Fin.val_mul, hm, ite_eq_right hz, Nat.mul_one, Nat.mod_eq_of_lt x.isLt]
+ change (chosen a s).val = _
+ cases s with
+ | liveLeft =>
+ by_cases hz : k = 0
+ · exact (hzero _ hz).trans (by simp [blocks,hz])
+ · rw [chosen, hkeep _ hz, Fin.val_add_eq_of_add_lt (by omega), hb, he, blocks, ite_eq_right hz]
+ | liveRight => exact hb
+ | primedLeft =>
+ have hs' : k < H := by simpa using hs
+ by_cases hz : k = 0
+ · exact (hzero _ hz).trans (by simp [blocks,hz])
+ · rw [chosen, hkeep _ hz, hdadd hs', hd hs', he, blocks, ite_eq_right hz]
+ | primedMiddle =>
+ have hs' : k < H := by simpa using hs
+ exact (hdadd hs').trans (by rw [hd hs', he, blocks])
+ | primedRight => exact hd (by simpa using hs)
+
+/-- Execution from arbitrary registers computes the true paper width. The
+height, block size, highest set bit and population count are read at runtime.
+The bound on the output word follows from the largest possible cut length. -/
+theorem needed_exec (pub : Pub → Word w) (p : Parameters) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) (s : Slot) (h Δ i c : ℕ) (hi : 0 < i) (hend : i ≤ 2^(h+1)) (hneed : Needed h i s)
+ (hc : c = 1 ↔ i = 2 ^ Nat.log 2 i)
+ (hh : (pub p.height).val = h+1) (hΔ : (pub p.delta).val = Δ)
+ (hk' : (m (pub p.highestAddress).val).val = Nat.log 2 i)
+ (hc' : (m (pub p.populationAddress).val).val = c) (hfit : (h+1)*Δ < 2^w) :
+ let width := CutSchedule.width (h+1) Δ (index i s)
+ let v : Word w := Fin.ofNat _ width
+ ∃ out, Flow.Exec pub state (block p s) rs m (events pub p m s v) out
+ (writeMemory m (pub p.outputAddress) v) ∧ v.val = width := by
+ let a := loaded pub p m rs
+ obtain ⟨b,hs,h13,h3,h6⟩ := select_exec pub state m a s
+ have hk : Nat.log 2 i ≤ h+1 := by
+ simpa [Nat.log_pow (by decide : 1 < 2)] using Nat.log_mono_right (b := 2) hend
+ have hs' : s = .liveLeft ∨ s = .liveRight ∨ Nat.log 2 i < h+1 := by
+ rcases hneed with hf | he | he
+ · have hlog : Nat.log 2 i ≤ h := by
+ simpa [Nat.log_pow (by decide : 1 < 2)] using Nat.log_mono_right (b := 2) hf
+ exact Or.inr (Or.inr (by omega))
+ · exact Or.inl he
+ · exact Or.inr (Or.inl he)
+ have hb := chosen_val pub p m rs s (h+1) (Nat.log 2 i) c (by omega) hk hs' hh hk' hc'
+ have hw := needed_width h Δ i c s hi hend hc hneed
+ have hf := (Nat.mul_le_mul_right Δ (blocks_le (h+1) (Nat.log 2 i) c s (by omega))).trans_lt hfit
+ have h3' : b 3 = pub p.delta := h3
+ have h6' : b 6 = pub p.outputAddress := h6
+ have hv : (b 13 * b 3).val = CutSchedule.width (h+1) Δ (index i s) := by
+ rw [Fin.val_mul, h13, h3', hΔ, hb, Nat.mod_eq_of_lt hf, hw]
+ let v : Word w := Fin.ofNat _ (CutSchedule.width (h+1) Δ (index i s))
+ have hv' : v.val = CutSchedule.width (h+1) Δ (index i s) :=
+ Nat.mod_eq_of_lt (hw ▸ hf)
+ have he : b 13 * b 3 = v := Fin.ext (hv.trans hv'.symm)
+ have hwrites := commit_exec pub state m b
+ dsimp only at hwrites
+ rw [he, h6'] at hwrites
+ exact ⟨_,(setup_exec pub p state m rs).seq (hs.seq hwrites),hv'⟩
+
+/-- First-half groups may request any of the five lengths. -/
+theorem block_exec (pub : Pub → Word w) (p : Parameters) (state : Word w) (m : Memory w)
+ (rs : Regs w 48) (s : Slot) (h Δ i c : ℕ) (hi : 0 < i) (hle : i ≤ 2^h)
+ (hc : c = 1 ↔ i = 2 ^ Nat.log 2 i)
+ (hh : (pub p.height).val = h+1) (hΔ : (pub p.delta).val = Δ)
+ (hk' : (m (pub p.highestAddress).val).val = Nat.log 2 i)
+ (hc' : (m (pub p.populationAddress).val).val = c) (hfit : (h+1)*Δ < 2^w) :
+ let width := CutSchedule.width (h+1) Δ (index i s)
+ let v : Word w := Fin.ofNat _ width
+ ∃ out, Flow.Exec pub state (block p s) rs m (events pub p m s v) out
+ (writeMemory m (pub p.outputAddress) v) ∧ v.val = width :=
+ needed_exec pub p state m rs s h Δ i c hi (hle.trans (Nat.pow_le_pow_right (by decide) (by omega)))
+ (Or.inl hle) hc hh hΔ hk' hc' hfit
+
+end WidthCode
+end LiveHeaderWidths
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveHeaderWidths.lean b/lean/OAI/Computability/VPVNP/LiveHeaderWidths.lean
new file mode 100644
index 0000000000..f331690f48
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveHeaderWidths.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.CutSchedule
+
+/-!
+# Computing the cut lengths from the distributed group index
+
+The first-half group numbered `i` needs the two incident lengths and the
+three lengths at its primed pair. Equation (9.1) lets the group compute
+all five using the position of the highest set bit and the number of set
+bits in its index, without storing the index in a RAM word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderWidths
+
+/-- Two incident cuts and the three cuts of the primed pair. -/
+inductive Slot where
+ | liveLeft | liveRight | primedLeft | primedMiddle | primedRight
+ deriving DecidableEq
+
+/-- Convert a group number and width slot to the cut index used in the live or primed chain. -/
+def index (i : ℕ) : Slot → ℕ
+ | .liveLeft => i - 1
+ | .liveRight => i
+ | .primedLeft => 2*i - 2
+ | .primedMiddle => 2*i - 1
+ | .primedRight => 2*i
+
+/-- Each block has `Δ` bits. Subtracting one from the group index crosses
+a power of two precisely when the population count is one. -/
+def blocks (H high count : ℕ) : Slot → ℕ
+ | .liveLeft => if high = 0 then 0 else (H - high) + (if count = 1 then 1 else 0)
+ | .liveRight => H - high
+ | .primedLeft => if high = 0 then 0 else (H - high - 1) + (if count = 1 then 1 else 0)
+ | .primedMiddle => (H - high - 1) + (if count = 1 then 1 else 0)
+ | .primedRight => H - high - 1
+
+theorem blocks_le (H high count : ℕ) (s : Slot) (hH : 0 < H) : blocks H high count s ≤ H := by
+ cases s <;> simp only [blocks] <;> (try split_ifs) <;> omega
+
+private theorem log_pred {i : ℕ} (hi : 1 < i) :
+ Nat.log 2 (i - 1) =
+ Nat.log 2 i - (if i = 2 ^ Nat.log 2 i then 1 else 0) := by
+ have hlo := Nat.pow_log_le_self 2 (by omega : i ≠ 0)
+ have hhi := Nat.lt_pow_succ_log_self (by decide : 1 < 2) i
+ split_ifs with hp
+ · have hk : Nat.log 2 i ≠ 0 := by
+ intro hz
+ rw [hz, pow_zero] at hp
+ omega
+ have he : Nat.log 2 i - 1 + 1 = Nat.log 2 i := by omega
+ apply Nat.log_eq_of_pow_le_of_lt_pow
+ · have h := congrArg (fun k => 2^k) he
+ rw [pow_succ, ← hp] at h
+ have := Nat.two_pow_pos (Nat.log 2 i - 1)
+ omega
+ · rw [he, ← hp]
+ omega
+ · rw [Nat.sub_zero]
+ apply Nat.log_eq_of_pow_le_of_lt_pow <;> omega
+
+private theorem log_twice_pred {i : ℕ} (hi : 0 < i) :
+ Nat.log 2 (2*i - 1) = Nat.log 2 i + 1 - (if i = 2 ^ Nat.log 2 i then 1 else 0) := by
+ have hd : Nat.log 2 (2*i) = Nat.log 2 i + 1 := by
+ rw [Nat.mul_comm, Nat.log_mul_base (by decide : 1 < 2) hi.ne']
+ rw [log_pred (by omega : 1 < 2*i), hd, pow_succ]
+ have hp : 2 * i = 2 ^ Nat.log 2 i * 2 ↔ i = 2 ^ Nat.log 2 i := by omega
+ rw [if_congr hp rfl rfl]
+
+/-- The number of set bits is needed only to distinguish powers of two.
+The two clamped endpoints are covered, including the case of just one
+first-half group. -/
+theorem blocks_width (h Δ i count : ℕ) (s : Slot) (hi : 0 < i) (hle : i ≤ 2^h)
+ (hc : count = 1 ↔ i = 2 ^ Nat.log 2 i) :
+ blocks (h+1) (Nat.log 2 i) count s * Δ = CutSchedule.width (h+1) Δ (index i s) := by
+ have hlt : i < 2^(h+1) := by rw [pow_succ]; omega
+ have hk : Nat.log 2 i ≤ h := by
+ simpa [Nat.log_pow (by decide : 1 < 2)] using Nat.log_mono_right (b := 2) hle
+ have hz : Nat.log 2 i = 0 ↔ i = 1 := by
+ rw [Nat.log_eq_zero_iff]; omega
+ have hright : blocks (h+1) (Nat.log 2 i) count .liveRight * Δ =
+ CutSchedule.width (h+1) Δ i := by simp [blocks, CutSchedule.width, hi, hlt]
+ have hleft : blocks (h+1) (Nat.log 2 i) count .liveLeft * Δ =
+ CutSchedule.width (h+1) Δ (i-1) := by
+ by_cases he : i = 1
+ · simp [blocks, he]
+ · have hn := mt hz.mp he
+ have hin : 0 < i-1 ∧ i-1 < 2^(h+1) := by omega
+ rw [CutSchedule.width, ite_eq_left hin, log_pred (by omega), ← if_congr hc rfl rfl]
+ simp only [blocks, ite_eq_right hn]
+ congr 1
+ split_ifs <;> omega
+ cases s with
+ | liveLeft => exact hleft
+ | liveRight => exact hright
+ | primedMiddle =>
+ have hm : 0 < 2*i-1 ∧ 2*i-1 < 2^(h+1) := by rw [pow_succ]; omega
+ rw [index, CutSchedule.width, ite_eq_left hm, log_twice_pred hi, ← if_congr hc rfl rfl, blocks]
+ congr 1
+ split_ifs <;> omega
+ | primedRight =>
+ have hd := CutSchedule.width_double h Δ i hi hle
+ rw [← hright] at hd
+ change (h+1-Nat.log 2 i)*Δ = _ at hd
+ have hh : h+1-Nat.log 2 i = (h+1-Nat.log 2 i - 1) + 1 := by omega
+ rw [hh, Nat.succ_mul] at hd
+ exact Nat.add_right_cancel hd
+ | primedLeft =>
+ by_cases he : i = 1
+ · simp [blocks, index, he]
+ · have hn := mt hz.mp he
+ have hd := CutSchedule.width_double h Δ (i-1) (by omega) (by omega)
+ rw [← hleft] at hd
+ simp only [blocks, ite_eq_right hn] at hd ⊢
+ rw [index, show 2*i-2 = 2*(i-1) by omega]
+ have hh : (h+1-Nat.log 2 i) + (if count = 1 then 1 else 0) =
+ ((h+1-Nat.log 2 i - 1) + (if count = 1 then 1 else 0)) + 1 := by omega
+ rw [hh, Nat.succ_mul] at hd
+ exact Nat.add_right_cancel hd
+
+/-- Slots actually used at a group. A tail group needs only its incident cuts. -/
+def Needed (h i : ℕ) (s : Slot) : Prop := i ≤ 2^h ∨ s = .liveLeft ∨ s = .liveRight
+
+/-- Correctness of every requested length throughout the chain, including
+the final group, where the outgoing live width is clamped to zero. -/
+theorem needed_width (h Δ i count : ℕ) (s : Slot) (hi : 0 < i) (hend : i ≤ 2^(h+1))
+ (hc : count = 1 ↔ i = 2 ^ Nat.log 2 i) (hs : Needed h i s) :
+ blocks (h+1) (Nat.log 2 i) count s * Δ = CutSchedule.width (h+1) Δ (index i s) := by
+ by_cases hf : i ≤ 2^h
+ · exact blocks_width h Δ i count s hi hf hc
+ have hleft : CutSchedule.width (h+1) Δ (i-1) = Δ := CutSchedule.width_tail _ _ _ (by omega) (by omega)
+ have hs' := hs.resolve_left hf
+ by_cases he : i = 2^(h+1)
+ · have hk : Nat.log 2 i = h+1 := he ▸ Nat.log_pow (by decide) _
+ have hp : count = 1 := hc.mpr (hk ▸ he)
+ rcases hs' with rfl | rfl
+ · simp [blocks, index, hk, hp, hleft]
+ · simp [blocks, index, he]
+ · have hk : Nat.log 2 i = h := Nat.log_eq_of_pow_le_of_lt_pow (by omega) (by omega)
+ have hp : count ≠ 1 := by intro hh; have heq := hc.mp hh; rw [hk] at heq; omega
+ have hh : h ≠ 0 := by rintro rfl; norm_num at *; omega
+ have hright : CutSchedule.width (h+1) Δ i = Δ := CutSchedule.width_tail _ _ _ (by omega) (by omega)
+ rcases hs' with rfl | rfl
+ · simp [blocks, index, hk, hp, hh, hleft]
+ · simp [blocks, index, hk, hright]
+
+/-- The position and the population suffice to dispatch the two halves.
+A group whose highest bit is at the halfway exponent belongs to the first
+half precisely when that bit is its only set bit. -/
+theorem firstHalf_iff (h i c : ℕ) (hi : 0 < i) (hc : c = 1 ↔ i = 2 ^ Nat.log 2 i) :
+ Nat.log 2 i < h ∨ Nat.log 2 i = h ∧ c = 1 ↔ i ≤ 2^h := by
+ rw [Nat.log_lt_iff_lt_pow (by decide) hi.ne', hc]
+ constructor
+ · rintro (hl | ⟨hk, he⟩)
+ · exact hl.le
+ · simpa [hk] using he.le
+ · intro hle
+ rcases lt_or_eq_of_le hle with hlt | rfl
+ · exact Or.inl hlt
+ · simp [Nat.log_pow (by decide : 1 < 2)]
+
+/-- Endpoint tests in the same small word representation. -/
+theorem endpoints_iff (H i : ℕ) (hi : 0 < i) (hend : i ≤ 2^H) :
+ (Nat.log 2 i = 0 ↔ i = 1) ∧ (Nat.log 2 i = H ↔ i = 2^H) := by
+ constructor
+ · rw [Nat.log_eq_zero_iff]; omega
+ · constructor
+ · intro hk
+ have := Nat.pow_log_le_self 2 hi.ne'
+ rw [hk] at this
+ omega
+ · rintro rfl
+ exact Nat.log_pow (by decide) _
+
+end LiveHeaderWidths
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveIncomingPadding.lean b/lean/OAI/Computability/VPVNP/LiveIncomingPadding.lean
new file mode 100644
index 0000000000..09ec34f1b1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveIncomingPadding.lean
@@ -0,0 +1,151 @@
+import OAI.Computability.VPVNP.LiveGroupContraction
+import OAI.Computability.VPVNP.LiveHeaderPhysical
+
+/-!
+# Canonical incoming cuts in the live group count
+
+Section 14.1 checks the padding of both incident cuts. The recurrence for
+exponent vectors already checks a pair's outgoing padding, and a tail step
+checks its outgoing configuration. Here those outgoing conditions imply
+every incoming format check whenever the product of all groups is nonzero.
+The incoming midpoint is a pair-format cut, even at the first tail group.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ChainAssignments
+
+open CutSchedule ExponentTrace LiveChain LiveHeaderDescriptors
+open scoped Classical
+
+variable {h Δ t Z M w : ℕ} {Nom : Type*} [Fintype Nom]
+variable {Path : Exterior h Δ → Fin (2^h) → Nom → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+
+/-- The trailing padding on an outgoing pair-format cut, at its physical sites. -/
+def pairPadding (t Z : ℕ) (bits : LiveBits h Δ) (i : Fin (2^h)) : Prop :=
+ Physical.ZeroSlice (bits i) (span .pair (width (h+1) Δ (i.val+1)) Δ (t*Z) 0 .padding)
+
+/-- The physical check on the input side of a group. The initial cut has
+no condition. Up to the midpoint the incoming padding is checked. Later
+incoming cuts must decode to canonical evaluator configurations. -/
+def incomingChecks (t Z : ℕ) {E : UniversalMachine.Program}
+ (layout : LiveEvaluatorTail.Layout E.extra M w Δ) (cuts : AllCuts h Δ) (j : Fin (2^(h+1))) : Prop :=
+ (∀ i, j.castSucc = firstCut i → pairPadding t Z (liveCutEquiv h Δ cuts).1 i) ∧
+ ∀ k, j.castSucc = laterCut k → (LiveEvaluatorTail.readCut layout k (cuts (laterCut k))).isSome = true
+
+private theorem first_ne_later (i : Fin (2^h)) (k : Fin (2^h-1)) : firstCut i ≠ laterCut k := by
+ intro he
+ have hh := congrArg Fin.val he
+ have hi := i.isLt
+ dsimp [firstCut,laterCut] at hh
+ omega
+
+private theorem first_inj {i j : Fin (2^h)} (he : firstCut i = firstCut j) : i = j := by
+ apply Fin.ext
+ have := congrArg Fin.val he
+ simpa [firstCut] using this
+
+private theorem later_inj {i j : Fin (2^h-1)} (he : laterCut i = laterCut j) : i = j := by
+ apply Fin.ext
+ have := congrArg Fin.val he
+ simpa [laterCut] using this
+
+theorem incomingChecks_initial (t Z : ℕ) {E : UniversalMachine.Program}
+ (layout : LiveEvaluatorTail.Layout E.extra M w Δ) (cuts : AllCuts h Δ) {j : Fin (2^(h+1))}
+ (first : j.val = 0) : incomingChecks t Z layout cuts j := by
+ constructor <;> intro i he <;> have := congrArg Fin.val he <;>
+ simp [firstCut,laterCut,first] at this
+
+/-- This includes the input of the first tail group, whose cut carries
+exponents rather than a serialized evaluator state. -/
+theorem incomingChecks_pair (t Z : ℕ) {E : UniversalMachine.Program}
+ (layout : LiveEvaluatorTail.Layout E.extra M w Δ) (cuts : AllCuts h Δ) {j : Fin (2^(h+1))}
+ (i : Fin (2^h)) (hin : j.castSucc = firstCut i) :
+ incomingChecks t Z layout cuts j ↔ pairPadding t Z (liveCutEquiv h Δ cuts).1 i := by
+ constructor
+ · exact fun hc => hc.1 i hin
+ · intro hc
+ constructor
+ · intro i' he
+ obtain rfl := first_inj (hin.symm.trans he)
+ exact hc
+ · intro k he
+ exact (first_ne_later i k (hin.symm.trans he)).elim
+
+/-- A tail-format input passes exactly when its literal cut equals one of
+the canonical mode/configuration/padding strings. -/
+theorem incomingChecks_tail (t Z : ℕ) {E : UniversalMachine.Program}
+ (layout : LiveEvaluatorTail.Layout E.extra M w Δ) (cuts : AllCuts h Δ) {j : Fin (2^(h+1))}
+ (k : Fin (2^h-1)) (hin : j.castSucc = laterCut k) :
+ incomingChecks t Z layout cuts j ↔ ∃ s, cuts (laterCut k) = LiveEvaluatorTail.writeCut layout k s := by
+ constructor
+ · intro hc
+ obtain ⟨s, hs⟩ := Option.isSome_iff_exists.mp (hc.2 k hin)
+ exact ⟨s, (LiveEvaluatorTail.readCut_iff layout k _ s).mp hs⟩
+ · rintro ⟨s, hs⟩
+ constructor
+ · intro i he
+ exact (first_ne_later i k (he.symm.trans hin)).elim
+ · intro k' he
+ obtain rfl := later_inj (hin.symm.trans he)
+ rw [(LiveEvaluatorTail.readCut_iff layout k _ s).mpr hs]
+ rfl
+
+/-- The first tail group receives the last cumulative exponent vector.
+It validates the midpoint's remaining bits using the first-half layout. -/
+theorem incomingChecks_midpoint (t Z : ℕ) {E : UniversalMachine.Program}
+ (layout : LiveEvaluatorTail.Layout E.extra M w Δ) (cuts : AllCuts h Δ) {j : Fin (2^(h+1))}
+ (mid : j.val = 2^h) :
+ incomingChecks t Z layout cuts j ↔ pairPadding t Z (liveCutEquiv h Δ cuts).1
+ ⟨2^h-1,by have := Nat.two_pow_pos h; omega⟩ := by
+ apply incomingChecks_pair
+ apply Fin.ext
+ dsimp [firstCut]
+ have := Nat.two_pow_pos h
+ omega
+
+/-- Every nonzero pair factor enforces the physical zero-padding interval
+of its output cut. -/
+theorem pairCount_padding (fit : 1+t*Z ≤ Δ) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (bits : LiveBits h Δ) (i : Fin (2^h)) (ok : pairCount fit inc bits i ≠ 0) :
+ pairPadding t Z bits i := by
+ apply (Physical.pair_padding_zero (Nat.succ_pos _) i.isLt fit (bits i)).mpr
+ by_contra bad
+ apply ok
+ unfold pairCount
+ apply Finset.sum_eq_zero
+ intro μ _
+ apply Finset.sum_eq_zero
+ intro q _
+ exact ite_eq_right (fun hv => bad (congrArg (fun a => a.2.2.2) hv.1))
+
+/-- Every nonzero tail factor with an outgoing interior cut has produced a
+decodable canonical configuration. -/
+theorem tailCount_decoded {E : UniversalMachine.Program} (layout : LiveEvaluatorTail.Layout E.extra M w Δ)
+ (init : LiveEvaluatorEncoding.Code E.extra M) (lst : TailBits h Δ) (k : Fin (2^h-1))
+ (ok : tailCount E layout init lst ⟨k.val,by have := k.isLt; omega⟩ ≠ 0) :
+ (LiveEvaluatorTail.readCut layout k (lst k)).isSome = true := by
+ let i : Fin (2^h) := ⟨k.val,by have := k.isLt; omega⟩
+ have hj : k.val+1 ≠ 2^h := by have := k.isLt; omega
+ have hbd : LiveEvaluatorTail.boundary layout init lst i.succ = LiveEvaluatorTail.readCut layout k (lst k) := by
+ simp [LiveEvaluatorTail.boundary, i, hj]
+ cases he : LiveEvaluatorTail.readCut layout k (lst k) with
+ | some _ => rfl
+ | none =>
+ apply False.elim (ok ?_)
+ unfold tailCount
+ apply Finset.sum_eq_zero
+ intro bit _
+ apply ite_eq_right
+ rintro ⟨s,u,_,hout,_,_⟩
+ change LiveEvaluatorTail.boundary layout init lst i.succ = some u at hout
+ rw [hbd, he] at hout
+ contradiction
+
+end ChainAssignments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLayoutWordFit.lean b/lean/OAI/Computability/VPVNP/LiveLayoutWordFit.lean
new file mode 100644
index 0000000000..9f24921483
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLayoutWordFit.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.LiveWordCapacity
+
+/-!
+# Site-count powers in the live program's workspace layout
+
+The physical and virtual site counts are the only power-of-two operations in
+these address expressions. Fixed natural powers, such as the label bound and
+the evaluator radius, are compiled as iterated word multiplications.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+local macro "site_expr" : tactic => `(tactic| repeat' first
+ | assumption
+ | exact True.intro
+ | apply PublicExpr.SitePowers.natPow
+ | exact Or.inl rfl
+ | exact Or.inr rfl
+ | constructor)
+
+namespace Constants
+
+@[simp] theorem states_sitePowers (c : Constants) : c.states.SitePowers := by site_expr
+
+@[simp] theorem grammarLabels_sitePowers (c : Constants) : c.grammarLabels.SitePowers := by
+ have := c.states_sitePowers
+ site_expr
+
+@[simp] theorem labels_sitePowers (c : Constants) : c.labels.SitePowers := by
+ have := c.grammarLabels_sitePowers
+ site_expr
+
+@[simp] theorem height_sitePowers (c : Constants) : c.height.SitePowers := by site_expr
+
+@[simp] theorem Z_sitePowers (c : Constants) : c.Z.SitePowers := by
+ have := c.height_sitePowers
+ site_expr
+
+@[simp] theorem radius_sitePowers (c : Constants) : c.radius.SitePowers := by site_expr
+
+@[simp] theorem configWords_sitePowers (c : Constants) : c.configWords.SitePowers := by
+ have := c.radius_sitePowers
+ site_expr
+
+@[simp] theorem prefixCapacity_sitePowers (c : Constants) : c.prefixCapacity.SitePowers := by site_expr
+
+@[simp] theorem lengths_h_sitePowers (c : Constants) : c.lengths.h.SitePowers := by
+ have := c.height_sitePowers
+ site_expr
+
+@[simp] theorem lengths_delta_sitePowers (c : Constants) : c.lengths.delta.SitePowers := by site_expr
+@[simp] theorem lengths_advice_sitePowers (c : Constants) : c.lengths.advice.SitePowers := by site_expr
+
+@[simp] theorem lengths_e_sitePowers (c : Constants) : c.lengths.e.SitePowers := by
+ have := c.labels_sitePowers
+ have := c.Z_sitePowers
+ site_expr
+
+@[simp] theorem lengths_config_sitePowers (c : Constants) : c.lengths.config.SitePowers := by
+ have := c.configWords_sitePowers
+ site_expr
+
+end Constants
+
+namespace Layout
+
+@[simp] theorem stageTag_sitePowers : stageTag.SitePowers := by site_expr
+
+@[simp] theorem header_sitePowers : header.SitePowers := by
+ have := stageTag_sitePowers
+ site_expr
+
+@[simp] theorem descriptor_sitePowers (c : Constants) : (descriptor c).SitePowers := by
+ have := header_sitePowers
+ have := c.lengths_h_sitePowers
+ have := c.lengths_delta_sitePowers
+ have := c.lengths_advice_sitePowers
+ have := c.lengths_e_sitePowers
+ have := c.lengths_config_sitePowers
+ site_expr
+
+@[simp] theorem counter_sitePowers (c : Constants) : (counter c).SitePowers := by
+ have := descriptor_sitePowers c
+ site_expr
+
+@[simp] theorem oldState_sitePowers (c : Constants) : (oldState c).SitePowers := by
+ have := counter_sitePowers c
+ have := c.labels_sitePowers
+ site_expr
+
+@[simp] theorem newState_sitePowers (c : Constants) : (newState c).SitePowers := by
+ have := oldState_sitePowers c
+ have := c.configWords_sitePowers
+ site_expr
+
+@[simp] theorem transitionScratch_sitePowers (c : Constants) : (transitionScratch c).SitePowers := by
+ have := newState_sitePowers c
+ have := c.configWords_sitePowers
+ site_expr
+
+@[simp] theorem adviceFrames_sitePowers (c : Constants) : (adviceFrames c).SitePowers := by
+ have := transitionScratch_sitePowers c
+ site_expr
+
+@[simp] theorem packedPrefix_sitePowers (c : Constants) : (packedPrefix c).SitePowers := by
+ have := adviceFrames_sitePowers c
+ site_expr
+
+@[simp] theorem orderMap_sitePowers (c : Constants) : (orderMap c).SitePowers := by
+ have := packedPrefix_sitePowers c
+ have := c.prefixCapacity_sitePowers
+ site_expr
+
+@[simp] theorem shadow_sitePowers (c : Constants) : (shadow c).SitePowers := by
+ have := orderMap_sitePowers c
+ have := c.labels_sitePowers
+ site_expr
+
+@[simp] theorem virtualSiteBits_sitePowers : virtualSiteBits.SitePowers := by
+ have := stageTag_sitePowers
+ site_expr
+
+@[simp] theorem virtualSiteCount_sitePowers : (PublicExpr.pow2 virtualSiteBits).SitePowers :=
+ ⟨virtualSiteBits_sitePowers,Or.inr rfl⟩
+
+@[simp] theorem pairWorkspace_sitePowers (c : Constants) : (pairWorkspace c).SitePowers := by
+ have := shadow_sitePowers c
+ have := virtualSiteCount_sitePowers
+ site_expr
+
+end Layout
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorCount.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorCount.lean
new file mode 100644
index 0000000000..72e1ba9d9b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorCount.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorImages
+
+/-!
+# Exact tail counts from the linked first and last routers
+
+At an interior incoming cut, a zero flag routes through the old-state gather.
+At the last router, a zero flag gathers the outgoing cut and a one flag installs
+the accepting sentinel. The transition then counts each literal evaluator
+branch separately. All earlier reports are included in the same transcript cap.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM LiveStageLink PairStages LiveEvaluatorEncoding LiveEvaluatorRAM LiveConfigGather
+open LiveEvaluatorRAM.Schedule (callFuel calls)
+open scoped Fin.CommRing
+
+variable (G : PairStages.Group) {M : ℕ}
+
+/-- Geometry and clock for an entire linked evaluator group. -/
+structure GeometryFit (M : ℕ) : Prop where
+ prep : PrepLayout G.evaluator G.transitionPub M
+ transitionClock : callFuel G.evaluator ≤ G.clockAt Stage.transition
+ scratchTag : G.addr.val < (G.transitionPub 3).val ∨ (G.transitionPub 3).val+5 ≤ G.addr.val
+ gatherClock : 8*G.w+67 ≤ G.clock
+ oldTag : G.addr.val < (G.transitionPub 1).val ∨ (G.transitionPub 1).val+fieldWords M ≤ G.addr.val
+ oldBeforeNew : (G.transitionPub 1).val+fieldWords M ≤ (G.transitionPub 2).val
+
+/-- The physical outgoing header field or the final sentinel. The cut case
+permits any raw configuration encoding, including malformed words. -/
+inductive Output (m : Memory G.w) (b : Option (Code G.evaluator.extra M)) : Type
+ | cut (F : EvaluatorGather.Fit G true (fieldWords M)) (bits : Fin (fieldWords M*G.w) → Bool)
+ (flag : m ((Router.last.data G.g G.lit) 0).val = 0)
+ (image : ArrayBitImage m (EvaluatorGather.operands G true 0) bits)
+ (fresh : G.addr.val < (EvaluatorGather.operands G true 0).val ∨
+ (EvaluatorGather.operands G true 0).val+fieldWords M*G.w ≤ G.addr.val)
+ (hs : G.evaluator.extra+2 ≤ 2^G.w) (value : b = (format F.width hs).decode bits)
+ | final (flag : m ((Router.last.data G.g G.lit) 0).val = 1)
+ (zero : ∀ i : Fin (fieldWords M), m ((G.transitionPub 2).val+i.val) = 0)
+ (fresh : G.addr.val < (G.transitionPub 2).val ∨ (G.transitionPub 2).val+fieldWords M ≤ G.addr.val)
+ (value : b = some .accepted)
+
+namespace Output
+variable {G} {m : Memory G.w} {b : Option (Code G.evaluator.extra M)}
+
+/-- The proposed outgoing configuration's physical memory, obtained by gathering the cut or
+installing the accepting endpoint. -/
+def memory (o : Output G m b) : Memory G.w := match o with
+ | .cut F bits .. => gatherMemory G true F m bits
+ | .final .. => putMemory G true m
+
+/-- The linked router and worker reports for the chosen outgoing cut gather or final control
+write. -/
+def logs (o : Output G m b) : List (Report G.w) := match o with
+ | .cut _ bits .. => gatherLogs G true bits
+ | .final .. => putLogs G true
+
+/-- Identify continuations on the prepared outgoing memory with paths before preparation,
+charging the outgoing router and worker reports to the cap. -/
+noncomputable def handoff (o : Output G m b) (fit : GeometryFit G M) (ht : G.tagged Stage.last m)
+ (cap : List (Report G.w) → Prop) : ActualPaths G.P G.clock 0 o.memory (fun rs => cap (o.logs++rs)) ≃
+ ActualPaths G.P G.clock 0 m cap := by
+ cases o with
+ | cut F bits flag image fresh => exact gatherHandoff G true F fit.gatherClock m bits ht flag image fresh cap
+ | final flag => exact putHandoff G true fit.prep.width (by have := fit.gatherClock; omega) m ht flag cap
+
+theorem tagged (o : Output G m b) : G.tagged Stage.transition o.memory := by
+ cases o <;> exact tagged_retag ..
+
+theorem old_image (o : Output G m b) (fit : GeometryFit G M) (c : Code G.evaluator.extra M) :
+ ConfigAt o.memory (G.transitionPub 1) c ↔ ConfigAt m (G.transitionPub 1) c := by
+ cases o with
+ | cut F bits => exact gather_frame G F m bits fit.prep fit.oldTag (Or.inl fit.oldBeforeNew) c
+ | final => exact put_frame G m fit.prep fit.oldTag (Or.inr fit.oldBeforeNew) c
+
+theorem new_image (o : Output G m b) (fit : GeometryFit G M) (z : Code G.evaluator.extra M) :
+ b = some z ↔ ConfigAt o.memory (G.transitionPub 2) z := by
+ cases o with
+ | cut F bits flag img fresh hs value => dsimp only [memory]; rw [value]; exact (gather_image G true F hs m bits z).symm
+ | final flag zero fresh value =>
+ dsimp only [memory]; rw [value, Option.some.injEq, eq_comm]; exact (put_image G m fit.prep zero fresh z).symm
+
+end Output
+
+/-- Counts a complete suffix from the last router with all earlier reports
+included. Only the incident fields and the finite transcript budget enter. -/
+theorem lastCount {h Δ S H : ℕ} (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w Δ)
+ (init : Code G.evaluator.extra M) (bits : LiveChain.TailBits h Δ) (i : Fin (2^h)) (m : Memory G.w)
+ (fit : GeometryFit G M) (ht : G.tagged Stage.last m)
+ (incoming : ∀ c, LiveEvaluatorTail.boundary layout init bits i.castSucc = some c ↔ ConfigAt m (G.transitionPub 1) c)
+ (o : Output G m (LiveEvaluatorTail.boundary layout init bits i.succ))
+ (pre : List (Report G.w)) (hcap : 11 ≤ H) (preCalls : ∀ r ∈ pre++o.logs, 1+r.probes ≤ H)
+ (hcost : RAMBuckets.cost Report.probes (pre++o.logs) + (10+7*(2*(2*M+1))) + calls M ≤ S*H) :
+ Nat.card (ActualPaths G.P G.clock 0 m (fun rs => withinCaps S H (pre++rs))) =
+ ChainAssignments.tailCount G.evaluator layout init bits i := by
+ rw [Nat.card_congr (o.handoff fit ht _).symm]
+ simpa only [List.append_assoc] using G.linkedTailCount layout init bits i o.memory fit.prep fit.transitionClock
+ fit.scratchTag o.tagged (fun c => (incoming c).trans (o.old_image fit c).symm) (o.new_image fit)
+ (pre++o.logs) hcap preCalls hcost
+
+/-- Complete noninitial evaluator count starting at the first router. The
+incoming field is gathered, after which the outgoing bank is gathered or
+initialized with the accepting state and one literal transition is checked. -/
+theorem nonfirstCount {h Δ S H : ℕ} (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w Δ)
+ (init : Code G.evaluator.extra M) (bits : LiveChain.TailBits h Δ) (i : Fin (2^h)) (m : Memory G.w)
+ (fit : GeometryFit G M) (ht : G.tagged Stage.firstTail m) (flag : m ((Router.firstTail.data G.g G.lit) 0).val = 0)
+ (F : EvaluatorGather.Fit G false (fieldWords M)) (raw : Fin (fieldWords M*G.w) → Bool)
+ (image : ArrayBitImage m (EvaluatorGather.operands G false 0) raw)
+ (fresh : G.addr.val < (EvaluatorGather.operands G false 0).val ∨
+ (EvaluatorGather.operands G false 0).val+fieldWords M*G.w ≤ G.addr.val)
+ (value : LiveEvaluatorTail.boundary layout init bits i.castSucc = (format F.width fit.prep.states).decode raw)
+ (o : Output G (gatherMemory G false F m raw) (LiveEvaluatorTail.boundary layout init bits i.succ))
+ (pre : List (Report G.w)) (hcap : 11 ≤ H)
+ (preCalls : ∀ r ∈ (pre++gatherLogs G false raw)++o.logs, 1+r.probes ≤ H)
+ (hcost : RAMBuckets.cost Report.probes ((pre++gatherLogs G false raw)++o.logs) +
+ (10+7*(2*(2*M+1))) + calls M ≤ S*H) :
+ Nat.card (ActualPaths G.P G.clock 0 m (fun rs => withinCaps S H (pre++rs))) =
+ ChainAssignments.tailCount G.evaluator layout init bits i := by
+ rw [Nat.card_congr (gatherHandoff G false F fit.gatherClock m raw ht flag image fresh _).symm]
+ simpa only [List.append_assoc] using lastCount G layout init bits i (gatherMemory G false F m raw) fit
+ (tagged_retag ..) (fun c => value ▸ (gather_image G false F fit.prep.states m raw c).symm) o
+ (pre++gatherLogs G false raw) hcap preCalls hcost
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorCut.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorCut.lean
new file mode 100644
index 0000000000..48aa152640
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorCut.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.LiveHeaderComplete
+import OAI.Computability.VPVNP.LiveGroupModeInput
+import OAI.Computability.VPVNP.LiveConfigGatherImage
+
+/-!
+# The two ordinary incident cuts of an evaluator tail group
+
+The physical header contains the configuration bits in its left or right
+bank. The mode guard and padding guard check the other two fields of exactly
+the cut used by the chain contraction. Hence gathering this bank feeds the
+same configuration decoder as the semantic boundary, including malformed
+word encodings.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeaderProgram.Output
+
+open BurstRAM CutSchedule ChainAssignments LiveEvaluatorEncoding
+open LiveHeader LiveHeaderSchedule LiveHeaderDescriptors LiveConfigGather
+open scoped Fin.CommRing
+
+variable {w d base M : ℕ} {s : Sizes} {hw : 4 ≤ w} {advice : Bits s.advice}
+variable {cuts : AllCuts s.h s.delta} {m : Memory w} {p : UniversalMachine.Program}
+
+private theorem typed_payload {h Δ i c : ℕ} (half : 2^h ≤ i) (hend : i < 2^(h+1))
+ (hc : 1+c ≤ Δ) (config : c = fieldWords M*w)
+ (layout : LiveEvaluatorTail.Layout p.extra M w Δ) (b : Bits (width (h+1) Δ i))
+ (source : Word w) (m : Memory w)
+ (image : ∀ j : Fin c, m (source.val+j.val) = PrimedInputRAM.encodeBit w
+ ((tailLayout h Δ i c half hend hc b).2.1 j))
+ (pad : (tailLayout h Δ i c half hend hc b).2.2 = fun _ => false) :
+ let f := tailLayout h Δ i (fieldWords M*w) half hend layout.cutWidth b
+ ArrayBitImage m source f.2.1 ∧ f.2.2 = fun _ => false := by
+ subst c
+ refine ⟨?_, pad⟩
+ intro j
+ rw [image j]
+ cases (tailLayout h Δ i (fieldWords M*w) half hend hc b).2.1 j <;> rfl
+
+private theorem fields_congr {h Δ c : ℕ} (cuts : AllCuts h Δ) {a b : Fin (2^(h+1)+1)}
+ (hab : a = b) (ha₁ : 2^h ≤ a.val) (ha₂ : a.val < 2^(h+1))
+ (hb₁ : 2^h ≤ b.val) (hb₂ : b.val < 2^(h+1)) (fit : 1+c ≤ Δ) :
+ tailLayout h Δ a.val c ha₁ ha₂ fit (cuts a) = tailLayout h Δ b.val c hb₁ hb₂ fit (cuts b) := by
+ subst b
+ rfl
+
+private theorem interiorCut {g : Fin (2^(s.h+1))}
+ (output : Output s base d hw advice cuts g .tail m)
+ (layout : LiveEvaluatorTail.Layout p.extra M w s.delta) (init : Code p.extra M)
+ (config : s.config = fieldWords M*w) (tag : physicalTag cuts g = some .tail)
+ (side : Side) (pad : Fields.ValidPadding s cuts g .tail side)
+ (source : Word w) (addr : source.val = configBase s base side)
+ (j : Fin (2^s.h-1)) (cut : incidentCut side g = laterCut j)
+ (x : Fin (2^s.h+1)) (time : x.val = j.val+1) :
+ ∃ b : Fin (fieldWords M*w) → Bool, ArrayBitImage m source b ∧
+ LiveEvaluatorTail.boundary layout init (liveCutEquiv s.h s.delta cuts).2 x =
+ (format layout.symbolWidth layout.stateWidth).decode b := by
+ have hj := j.isLt
+ have half : 2^s.h < (incidentCut side g).val := by rw [cut]; change 2^s.h < 2^s.h+(j.val+1); omega
+ have hend : (incidentCut side g).val < 2^(s.h+1) := by rw [cut]; change 2^s.h+(j.val+1) < _; rw [pow_succ]; omega
+ have fit : 1+s.config ≤ s.delta := config ▸ layout.cutWidth
+ have hΔ : 0 < s.delta := by omega
+ let k := incidentCut side g
+ have hmode : evalCutMode cuts k := by
+ obtain ⟨hm, _⟩ := (physicalTag_tail hΔ cuts g).mp tag
+ cases side <;> first | exact hm.1 | exact hm.2
+ have hsite : 0 < width (s.h+1) s.delta k.val := by
+ rw [width_tail s.h s.delta k.val half.le hend]
+ exact hΔ
+ let zero : Fin (width (s.h+1) s.delta k.val) := ⟨0,hsite⟩
+ have hbit : cuts k zero = true := by
+ have h := hmode (by have := Nat.two_pow_pos s.h; omega) hend
+ simpa only [distributedBit, dite_eq_left hsite] using h
+ have hfieldmode := (Physical.tail_mode half.le hend layout.cutWidth (cuts k) zero rfl).trans hbit
+ obtain ⟨before, _, img⟩ := output.fieldImage
+ have image (i : Fin s.config) : m (source.val+i.val) = PrimedInputRAM.encodeBit w
+ ((tailLayout s.h s.delta k.val s.config half.le hend fit (cuts k)).2.1 i) := by
+ rw [addr]
+ exact img.tail_config (by decide) side fit half hend i
+ have hpad := (Fields.validPadding_tail_iff (tag := .tail) (by decide) side fit half hend).mp pad
+ obtain ⟨him, hp⟩ := typed_payload half.le hend fit config layout (cuts k) source m image hpad
+ change k = laterCut j at cut
+ let f := tailLayout s.h s.delta (laterCut j).val (fieldWords M*w) (by change _ ≤ 2^s.h+(j.val+1); omega)
+ (by change 2^s.h+(j.val+1) < _; rw [pow_succ]; omega) layout.cutWidth (cuts (laterCut j))
+ have he : tailLayout s.h s.delta k.val (fieldWords M*w) half.le hend layout.cutWidth (cuts k) = f :=
+ fields_congr cuts cut half.le hend _ _ layout.cutWidth
+ have hp' : f.2.2 = fun _ => false := he ▸ hp
+ have hm' : f.1 = true := he ▸ hfieldmode
+ refine ⟨f.2.1, he ▸ him, ?_⟩
+ have hx : x.val ≠ 0 := by omega
+ have hT : x.val ≠ 2^s.h := by omega
+ rw [LiveEvaluatorTail.boundary, dite_eq_right hx, dite_eq_right hT]
+ have hidx : (⟨x.val-1, by omega⟩ : Fin (2^s.h-1)) = j := Fin.ext (by change x.val-1 = j.val; omega)
+ rw [hidx]
+ change (if f.1 = true ∧ f.2.2 = fun _ => false then _ else _) = _
+ rw [ite_eq_left ⟨hm', hp'⟩]
+ rfl
+
+variable {i : Fin (2^s.h)}
+
+/-- Incoming configuration after the first evaluator group. The midpoint
+itself supplies the explicitly initialized input. -/
+theorem tail_incoming {src : Word w}
+ (output : Output s base d hw advice cuts (halves s.h (.inr i)) .tail m)
+ (layout : LiveEvaluatorTail.Layout p.extra M w s.delta) (init : Code p.extra M)
+ (config : s.config = fieldWords M*w)
+ (tag : physicalTag cuts (halves s.h (.inr i)) = some .tail)
+ (pad : Fields.ValidPadding s cuts (halves s.h (.inr i)) .tail .left)
+ (addr : src.val = configBase s base .left) (nonfirst : 0 < i.val) :
+ ∃ b : Fin (fieldWords M*w) → Bool, ArrayBitImage m src b ∧
+ LiveEvaluatorTail.boundary layout init (liveCutEquiv s.h s.delta cuts).2 i.castSucc =
+ (format layout.symbolWidth layout.stateWidth).decode b := by
+ let j : Fin (2^s.h-1) := ⟨i.val-1, by have := i.isLt; omega⟩
+ apply interiorCut output layout init config tag .left pad src addr j
+ · apply Fin.ext
+ change 2^s.h+i.val = 2^s.h+(j.val+1)
+ dsimp only [j]
+ omega
+ · change i.val = (i.val-1)+1
+ omega
+
+/-- Outgoing configuration before the last evaluator group. The terminal
+endpoint uses the explicitly prepared accepting sentinel. -/
+theorem tail_outgoing {src : Word w}
+ (output : Output s base d hw advice cuts (halves s.h (.inr i)) .tail m)
+ (layout : LiveEvaluatorTail.Layout p.extra M w s.delta) (init : Code p.extra M)
+ (config : s.config = fieldWords M*w)
+ (tag : physicalTag cuts (halves s.h (.inr i)) = some .tail)
+ (pad : Fields.ValidPadding s cuts (halves s.h (.inr i)) .tail .right)
+ (addr : src.val = configBase s base .right) (nonlast : i.val+1 < 2^s.h) :
+ ∃ b : Fin (fieldWords M*w) → Bool, ArrayBitImage m src b ∧
+ LiveEvaluatorTail.boundary layout init (liveCutEquiv s.h s.delta cuts).2 i.succ =
+ (format layout.symbolWidth layout.stateWidth).decode b := by
+ let j : Fin (2^s.h-1) := ⟨i.val, by omega⟩
+ apply interiorCut output layout init config tag .right pad src addr j
+ · apply Fin.ext
+ change 2^s.h+i.val+1 = 2^s.h+(j.val+1)
+ dsimp only [j]
+ omega
+ · rfl
+
+end LiveHeaderProgram.Output
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorFrame.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorFrame.lean
new file mode 100644
index 0000000000..c686e5ea71
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorFrame.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorHandoff
+import OAI.Computability.VPVNP.LiveProgramAdviceSplice
+
+/-!
+# Returning from a framed evaluator stage in the linked program
+
+A native scan supplies its exact reports at fixed operands. If its writes
+leave the operand frame and tag intact, the physical program reads the same
+operands on every call. Its last call writes the destination stage tag and
+returns persistent cursor zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink CompressorRecords
+
+variable {G : Group} {k r p : ℕ} {s dest : Stage} {T : Template p r k}
+ {base : Word G.w} {pub : Fin k → Word G.w} {fuel b : ℕ}
+
+private theorem framedSegment (same : ∀ st mem bits,
+ let C := Pieces.component G.components s G.g G.lit
+ let R := (Frame.machine T base).program
+ execute C (fuel+4*k) (C.start st) mem bits = execute R (fuel+4*k) (R.start st) mem bits)
+ {st : Option (Word G.w)} {m : Memory G.w} {bs : List (List Bool)} {rs : List (Report G.w)}
+ (data : Frame.data base m = pub)
+ (run : runSegment (T.instantiate G.w pub).program fuel st m bs = some rs)
+ (probes : ∀ rep ∈ rs, rep.probes ≤ b)
+ (keep : ∀ rep ∈ rs, ∀ u, after u rep.events G.addr.val = u G.addr.val ∧
+ Frame.data base (after u rep.events) = (Frame.data base u : Fin k → Word G.w)) :
+ ∃ logs, runSegment (Pieces.component G.components s G.g G.lit) (fuel+4*k) st m bs = some logs ∧
+ endState st logs = endState st rs ∧ after m (eventLog logs) = after m (eventLog rs) ∧
+ logs.length = rs.length ∧ PreservesTagOnReturns G.addr m logs ∧
+ ∀ rep ∈ logs, rep.probes ≤ b+k ∧ rep.events.length < fuel+4*k := by
+ induction bs generalizing st m rs with
+ | nil =>
+ obtain rfl := Option.some.inj run
+ exact ⟨[], rfl, rfl, rfl, rfl, trivial, by simp⟩
+ | cons bits bs ih =>
+ cases st with
+ | none => cases run
+ | some st =>
+ let P := (T.instantiate G.w pub).program
+ change runSegment P fuel (some st) m (bits :: bs) = some rs at run
+ rw [runSegment] at run
+ cases hx : execute P fuel (P.start st) m bits with
+ | none => simp [hx] at run
+ | some rep =>
+ rw [hx, Option.map_eq_some_iff] at run
+ obtain ⟨tail, htail, rfl⟩ := run
+ have ⟨ht, hf⟩ := keep rep (by simp) m
+ obtain ⟨ls, hls, he, hm, hn, hpres, hcost⟩ := ih (hf.trans data) htail
+ (fun a ha => probes a (List.mem_cons_of_mem _ ha))
+ (fun a ha => keep a (List.mem_cons_of_mem _ ha))
+ let z := prependLog (Frame.loadEvents base m 0 k) rep
+ have hwrap := Frame.execute_frame T base st fuel m bits
+ dsimp only at hwrap
+ rw [data, hx] at hwrap
+ have hz := (same st m bits).trans hwrap
+ have ⟨_, hp, _, hmem, hres⟩ := Frame.frame_cost base m 0 k rep
+ change after m z.events = after m rep.events at hmem
+ change z.result = rep.result at hres
+ change z.probes = k + rep.probes at hp
+ change _ = some z at hz
+ refine ⟨z :: ls, ?_, ?_, ?_, by simp [hn], ?_, ?_⟩
+ · simp only [runSegment, hz, hmem, hres, hls, Option.map_some]
+ · simpa only [endState, hres] using he
+ · simpa only [eventLog, List.flatMap_cons, after, List.foldl_append] using
+ (hmem ▸ hm : after (after m z.events) (eventLog ls) = after (after m rep.events) (eventLog tail))
+ · exact ⟨fun _ => (congrFun hmem _).trans ht, hmem ▸ hpres⟩
+ · rw [List.forall_mem_cons]
+ have := probes rep (by simp)
+ exact ⟨⟨by omega, (execute_spec hz).1.length_lt⟩, hcost⟩
+
+/-- Lift a certified native source run through the physical operand loader
+and stage dispatcher, including the transfer tag and the private clock. -/
+theorem framedReturning {m : Memory G.w} {n : ℕ} {rs : List (Report G.w)}
+ (fit : fuel+4*k+47 ≤ G.clock) (tagged : G.tagged s m) (next : G.nextStage s = some dest)
+ (data : Frame.data base m = pub)
+ (same : ∀ st mem bits, let C := Pieces.component G.components s G.g G.lit
+ let R := (Frame.machine T base).program
+ execute C (fuel+4*k) (C.start st) mem bits = execute R (fuel+4*k) (R.start st) mem bits)
+ (run : runSegment (T.instantiate G.w pub).program fuel (some 0) m (List.replicate n []) = some rs)
+ (halt : endState (some (0 : Word G.w)) rs = none) (hlen : rs.length = n)
+ (probes : ∀ rep ∈ rs, rep.probes ≤ b)
+ (keep : ∀ rep ∈ rs, ∀ u, after u rep.events G.addr.val = u G.addr.val ∧
+ Frame.data base (after u rep.events) = (Frame.data base u : Fin k → Word G.w)) :
+ Advice.Returning G.P G.clock n (b+k+2) m
+ (writeMemory (after m (eventLog rs)) G.addr (tagWord G.w dest)) := by
+ obtain ⟨logs, hr, he, hm, hlen', hframe, hcost⟩ := framedSegment same data run probes keep
+ obtain ⟨houter, hend, hmem, _⟩ := G.component_completion fit tagged hframe hr (he.trans halt)
+ rw [next] at hend
+ rw [next, hm] at hmem
+ refine ⟨G.linkedLogs s logs, houter, hend, hmem, by simp [linkedLogs, hlen', hlen], ?_⟩
+ intro rep hrep
+ obtain ⟨inner, hi, rfl⟩ := List.mem_map.mp hrep
+ obtain ⟨hp, hl⟩ := hcost inner hi
+ refine ⟨?_, ?_⟩
+ · rw [linkedReport_probes]
+ split <;> omega
+ · have hle := linkedReport_length_le G.nextStage G.addr s inner
+ change _ ≤ inner.events.length + 2*21+5 at hle
+ omega
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorGather.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorGather.lean
new file mode 100644
index 0000000000..b050f75b0b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorGather.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorHandoff
+import OAI.Computability.VPVNP.LiveConfigGatherRun
+
+/-!
+# The two evaluator configuration gathers in the complete live group
+
+On a noninitial tail group the incoming gather hands off to the last-group
+router. On a nonfinal group the outgoing gather hands off to the evaluator
+transition. In each case the source is the actual bit scratch region and
+the continuation receives the packed word bank and the new stage tag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorGather
+
+open BurstRAM LiveStageLink PairStages LiveConfigGather
+open scoped Fin.CommRing
+
+/-- The two actual rows of the outer table which gather cut configurations. -/
+def stage (outgoing : Bool) : Stage := if outgoing then Stage.newGather else Stage.oldGather
+
+/-- The stage reached after a configuration gather, the last-group router for incoming data or
+transition checking for outgoing data. -/
+def destination (outgoing : Bool) : Stage := if outgoing then Stage.transition else Stage.last
+
+/-- The live configuration-gather operands selecting the left or right cut source and the
+corresponding old or new state bank. -/
+def operands (G : PairStages.Group) (outgoing : Bool) : Fin 4 → Word G.w :=
+ Pieces.word G.g G.lit ∘ InputOperand.geometry ∘
+ if outgoing then StageOperands.gather G.constants .right (Layout.newState G.constants)
+ else StageOperands.gather G.constants .left (Layout.oldState G.constants)
+
+variable (G : PairStages.Group) (outgoing : Bool) {k : ℕ}
+
+private theorem source_run (fuel : ℕ) (m : Memory G.w) (bs : List (List Bool)) :
+ runSegment (Pieces.component G.components (stage outgoing) G.g G.lit) fuel (some 0) m bs =
+ runSegment (LiveConfigGather.machine (operands G outgoing)) fuel (some 0) m bs := by cases outgoing <;> rfl
+
+/-- The native word reports for gathering a serialized configuration, in destination-word
+order. -/
+def reports (bits : Fin (k * G.w) → Bool) : List (Report G.w) :=
+ (List.finRange k).map (wordReport (operands G outgoing) ((RAMSerialization.arrayBits k G.w).symm bits))
+
+/-- Conditions on the four physically computed operands and their memory
+regions. A separate destination region preserves all unread source bits. -/
+structure Fit (k : ℕ) : Prop where
+ positive : 0 < k
+ width : 2 ≤ G.w
+ wordWidth : ((operands G outgoing) 2).val = G.w
+ count : ((operands G outgoing) 3).val = k
+ source : ((operands G outgoing) 0).val + k * G.w ≤ 2 ^ G.w
+ dest : ((operands G outgoing) 1).val + k ≤ 2 ^ G.w
+ disjoint : ((operands G outgoing) 0).val + k * G.w ≤ ((operands G outgoing) 1).val ∨
+ ((operands G outgoing) 1).val + k ≤ ((operands G outgoing) 0).val
+ tagOutside : G.addr.val < ((operands G outgoing) 1).val ∨
+ ((operands G outgoing) 1).val + k ≤ G.addr.val
+
+private theorem report_frame (bits : Fin (k * G.w) → Bool) (F : Fit G outgoing k) :
+ PreservesTag G.addr (reports G outgoing bits) := by
+ intro rep hrep m
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp hrep
+ rw [wordReport, report_memory]
+ let base := (operands G outgoing) 1
+ have hf := F.dest
+ change base.val + k ≤ 2 ^ G.w at hf
+ have he : (base + (i.val : Word G.w)).val = base.val + i.val := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)]
+ have hd := F.tagOutside
+ change G.addr.val < base.val ∨ base.val + k ≤ G.addr.val at hd
+ exact ite_eq_right (show G.addr.val ≠ (base + (i.val : Word G.w)).val by rw [he]; omega)
+
+private theorem next_stage : G.nextStage (stage outgoing) = some (destination outgoing) := by
+ cases outgoing <;> rfl
+
+/-- Remove the entire deterministic gather prefix from an accepting outer
+path. Its retained log includes all native reads and writes and all dispatch
+and transfer costs, and the tail starts in the actual post-gather memory. -/
+noncomputable def handoff (F : Fit G outgoing k) (hclock : 8 * G.w + 67 ≤ G.clock)
+ (m : Memory G.w) (bits : Fin (k * G.w) → Bool) (ht : G.tagged (stage outgoing) m)
+ (hsrc : ArrayBitImage m ((operands G outgoing) 0) bits) (cap : List (Report G.w) → Prop) :
+ let bank := gathered ((operands G outgoing) 1) F.dest bits m
+ let logs := G.linkedLogs (stage outgoing) (reports G outgoing bits)
+ ActualPaths G.P G.clock 0 (writeMemory bank G.addr (tagWord G.w (destination outgoing)))
+ (fun rs => cap (logs ++ rs)) ≃ ActualPaths G.P G.clock 0 m cap := by
+ let data := operands G outgoing
+ let bank := gathered (data 1) F.dest bits m
+ have hr := (run_array data bits F.width F.wordWidth F.count F.positive (fuel := 8*G.w+20) le_rfl
+ F.source F.dest F.disjoint m hsrc (List.replicate k []) (reports G outgoing bits) bank).mpr ⟨rfl,rfl,rfl⟩
+ exact G.deterministicHandoff (by omega) ht ((report_frame G outgoing bits F).onReturns m)
+ (next_stage G outgoing) ((source_run G outgoing ..).trans hr.1) hr.2.1 hr.2.2 cap
+
+/-- Number of reports, native probes, and the unique final transfer all
+contribute to the resource accounting of this gather in the outer table. -/
+theorem linked_cost (bits : Fin (k * G.w) → Bool) (F : Fit G outgoing k)
+ (hclock : 8*G.w+67 ≤ G.clock) (m : Memory G.w) (ht : G.tagged (stage outgoing) m)
+ (hsrc : ArrayBitImage m ((operands G outgoing) 0) bits) :
+ RAMBuckets.cost Report.probes (G.linkedLogs (stage outgoing) (reports G outgoing bits)) =
+ k * (G.w + 3) + 1 := by
+ let data := operands G outgoing
+ let bank := gathered (data 1) F.dest bits m
+ obtain ⟨hr, hh, _⟩ := (run_array data bits F.width F.wordWidth F.count F.positive
+ (fuel := 8*G.w+20) le_rfl F.source F.dest F.disjoint m hsrc
+ (List.replicate k []) (reports G outgoing bits) bank).mpr ⟨rfl,rfl,rfl⟩
+ have hc := (G.component_completion (by omega) ht ((report_frame G outgoing bits F).onReturns m)
+ ((source_run G outgoing ..).trans hr) hh).2.2.2
+ rw [hc, next_stage]
+ have count (xs : List (Fin k)) :
+ RAMBuckets.cost Report.probes (xs.map (wordReport data ((RAMSerialization.arrayBits k G.w).symm bits))) =
+ xs.length * (G.w+2) := by
+ induction xs with
+ | nil => simp [RAMBuckets.cost]
+ | cons j xs ih =>
+ simp only [List.map_cons, RAMBuckets.cost, List.length_cons, ih, wordReport, report_probes, Nat.succ_mul]
+ omega
+ unfold reports
+ rw [count, List.length_map, List.length_finRange]
+ simp
+ ring
+
+end LiveProgram.EvaluatorGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorGeometry.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorGeometry.lean
new file mode 100644
index 0000000000..5dc6e43438
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorGeometry.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorCount
+
+/-!
+# Physical allocation for the linked evaluator routes
+
+The old and new evaluator banks follow the distributed-header buffers. Each has
+exactly one word per control or tape field. The scratch region follows both
+banks, so the same upper bound on the shadow base controls every address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM PairStages LiveEvaluatorEncoding LiveEvaluatorRAM
+open LiveEvaluatorRAM.Schedule (callFuel)
+open scoped Fin.CommRing
+
+variable (G : PairStages.Group)
+
+/-- The evaluator tape-window radius computed at this group's public geometry. -/
+abbrev radius := G.constants.radius.eval G.g
+/-- Number of words in a physical evaluator configuration at the group's window radius. -/
+abbrev k := fieldWords (radius G)
+/-- The first source bit cell used by the incoming or outgoing configuration gather. -/
+abbrev cutSource (outgoing : Bool) := EvaluatorGather.operands G outgoing 0
+/-- The shadow base, used as an upper bound for the evaluator configuration banks and
+transition scratch. -/
+abbrev limit := (Layout.shadow G.constants).eval G.g
+
+/-- Ordered physical intervals in the real public operand bank. -/
+structure Addresses : Prop where
+ leftStart : G.addr.val < (cutSource G false).val
+ rightStart : (cutSource G false).val + k G * G.w = (cutSource G true).val
+ sourceEnd : (cutSource G true).val + k G * G.w ≤ (G.transitionPub 1).val
+ lastFlag : G.addr.val < ((Router.last.data G.g G.lit) 0).val
+ flagEnd : ((Router.last.data G.g G.lit) 0).val < (cutSource G false).val
+ oldEnd : (G.transitionPub 1).val + k G = (G.transitionPub 2).val
+ newEnd : (G.transitionPub 2).val + k G = (G.transitionPub 3).val
+ scratchEnd : (G.transitionPub 3).val + 5 ≤ limit G
+ radiusWord : (G.transitionPub 0).val = radius G
+ widthWord (outgoing : Bool) : (EvaluatorGather.operands G outgoing 2).val = G.w
+ countWord (outgoing : Bool) : (EvaluatorGather.operands G outgoing 3).val = k G
+
+theorem addresses (fits : limit G < 2^G.w) : Addresses G := by
+ let t := Layout.stageTag.eval G.g
+ let f := (HeaderLayout.flag Layout.header .last).eval G.g
+ let a := (HeaderLayout.config G.constants.lengths Layout.header .left).eval G.g
+ let b := (HeaderLayout.config G.constants.lengths Layout.header .right).eval G.g
+ let o := (Layout.oldState G.constants).eval G.g
+ let n := (Layout.newState G.constants).eval G.g
+ let s := (Layout.transitionScratch G.constants).eval G.g
+ let W := 2^G.w
+ have hk : G.constants.configWords.eval G.g = k G := rfl
+ have hw : G.constants.lengths.config.eval G.g = k G * G.w := rfl
+ have htf : t < f := by change t < t+1+9; omega
+ have hfa : f < a := by
+ simp only [a,f,HeaderLayout.config,HeaderLayout.exponent,HeaderLayout.exterior,HeaderLayout.advice,
+ HeaderLayout.rightIndex,HeaderLayout.leftIndex,HeaderLayout.population,HeaderLayout.high,
+ HeaderLayout.index,HeaderLayout.flag,eval_add]
+ rw [show (9 : PublicExpr).eval G.g = 9 from rfl, show (15 : PublicExpr).eval G.g = 15 from rfl]; omega
+ have hab : a+k G*G.w = b := rfl
+ have hbo : b+k G*G.w ≤ o := by
+ change b+k G*G.w ≤ b+G.constants.lengths.config.eval G.g+21+G.constants.labels.eval G.g
+ rw [hw]; omega
+ have hon : o+k G = n := rfl
+ have hns : n+k G = s := rfl
+ have hs : s+5 ≤ limit G := by
+ change s+5 ≤ s+5+24+G.constants.prefixCapacity.eval G.g+G.constants.labels.eval G.g; omega
+ have hkr : radius G < k G := by dsimp [k,fieldWords]; omega
+ have hwidth := Nat.lt_two_pow_self (n := G.w)
+ have val (x : ℕ) (hx : x < W) : (Fin.ofNat (2^G.w) x).val = x := Nat.mod_eq_of_lt hx
+ have hlim : limit G < W := fits
+ have tv : G.addr.val = t := val t (by omega)
+ have av : (cutSource G false).val = a := val a (by omega)
+ have bv : (cutSource G true).val = b := val b (by omega)
+ have fv : ((Router.last.data G.g G.lit) 0).val = f := val f (by omega)
+ have ov : (G.transitionPub 1).val = o := val o (by omega)
+ have nv : (G.transitionPub 2).val = n := val n (by omega)
+ have sv : (G.transitionPub 3).val = s := val s (by omega)
+ refine ⟨by omega, by omega, by omega, by omega, by omega, by omega, by omega, by omega,
+ val (radius G) (by omega), ?_, ?_⟩
+ · intro out; cases out <;> exact val _ hwidth
+ · intro out; cases out <;> exact val _ (by omega : k G < W)
+
+/-- One global address fit and the table and burst sizes imply the native
+transition and gather geometry, for the true length-dependent radius. -/
+theorem geometryFit (fits : limit G < 2^G.w) (hw : 2 ≤ G.w) (states : G.evaluator.extra+2 ≤ 2^G.w)
+ (rows : 9*G.evaluator.extra ≤ 2^G.w) (gather : 8*G.w+67 ≤ G.clock)
+ (clock : callFuel G.evaluator ≤ G.clockAt Stage.transition) : GeometryFit G (radius G) := by
+ obtain ⟨l,r,e,_,_,o,n,s,rad,_,_⟩ := addresses G fits
+ have kcalls : k G = Schedule.calls (radius G) := LiveEvaluatorGroup.fieldWords_eq_calls _
+ refine ⟨⟨hw,states,rows,rad,?_,?_,?_,Or.inl ?_,Or.inl ?_⟩,clock,Or.inl ?_,gather,Or.inl ?_,?_⟩
+ all_goals try change (G.transitionPub 1).val + k G ≤ (G.transitionPub 2).val
+ all_goals omega
+
+theorem gatherFit (fits : limit G < 2^G.w) (hw : 2 ≤ G.w) (out : Bool) : EvaluatorGather.Fit G out (k G) := by
+ obtain ⟨l,r,e,_,_,o,n,s,rad,wc,kc⟩ := addresses G fits
+ have hk : 0 < k G := by dsimp [k,fieldWords]; omega
+ refine ⟨hk,hw,wc out,kc out,?_,?_,Or.inl ?_,Or.inl ?_⟩
+ all_goals cases out
+ all_goals first | change (cutSource G _).val + k G*G.w ≤ _ | skip
+ all_goals try change (G.transitionPub 1).val + k G ≤ 2^G.w
+ all_goals try change (G.transitionPub 2).val + k G ≤ 2^G.w
+ all_goals try change (cutSource G false).val+k G*G.w ≤ (G.transitionPub 1).val
+ all_goals try change (cutSource G true).val+k G*G.w ≤ (G.transitionPub 2).val
+ all_goals try change G.addr.val < (G.transitionPub 1).val
+ all_goals try change G.addr.val < (G.transitionPub 2).val
+ all_goals omega
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorHandoff.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorHandoff.lean
new file mode 100644
index 0000000000..e0570f09e1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorHandoff.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.LiveProgramTerminalStage
+
+/-!
+# Handoff of a deterministic evaluator stage in the complete live program
+
+A successful standalone scan has one empty choice string per call. If its
+returning reports preserve the stage tag, the outer dispatcher adds its
+exact reports, retags the final memory and starts the next stage at zero.
+The inverse direction removes this forced prefix from every accepted path.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+
+open BurstRAM LiveStageLink
+
+variable (G : Group)
+
+/-- Add the group dispatch and handoff events to each source report of the selected stage. -/
+abbrev linkedLogs (s : Stage) (rs : List (Report G.w)) := rs.map (linkedReport G.nextStage G.addr s)
+
+theorem component_completion {s : Stage} {fuel : ℕ} {st : Word G.w} {m : Memory G.w}
+ {bs : List (List Bool)} {rs : List (Report G.w)} (fit : fuel + 47 ≤ G.clock)
+ (ht : G.tagged s m) (frame : PreservesTagOnReturns G.addr m rs)
+ (run : runSegment (Pieces.component G.components s G.g G.lit) fuel (some st) m bs = some rs)
+ (halt : endState (some st) rs = none) :
+ runSegment G.P G.clock (some st) m bs = some (G.linkedLogs s rs) ∧
+ endState (some st) (G.linkedLogs s rs) = (G.nextStage s).map (fun _ => 0) ∧
+ after m (eventLog (G.linkedLogs s rs)) = transferMemory G.addr (G.nextStage s) (after m (eventLog rs)) ∧
+ RAMBuckets.cost Report.probes (G.linkedLogs s rs) =
+ RAMBuckets.cost Report.probes rs + rs.length + (if (G.nextStage s).isSome then 1 else 0) :=
+ runSegment_accepting G.T G.nextStage G.pub G.addr s G.tagFit fit st m bs rs ht frame
+ ((component_segment G s ..).trans run) halt
+
+/-- Each accepted continuation corresponds to exactly one complete choice
+stream with the verified empty-choice prefix. The cap includes every
+dispatch, return and final stage transfer in that prefix. -/
+noncomputable def deterministicHandoff {s dest : Stage} {fuel n : ℕ} {m m' : Memory G.w}
+ {rs : List (Report G.w)} (fit : fuel + 47 ≤ G.clock) (ht : G.tagged s m)
+ (frame : PreservesTagOnReturns G.addr m rs) (hn : G.nextStage s = some dest)
+ (run : runSegment (Pieces.component G.components s G.g G.lit) fuel (some 0) m
+ (List.replicate n []) = some rs)
+ (halt : endState (some (0 : Word G.w)) rs = none) (hm : after m (eventLog rs) = m')
+ (cap : List (Report G.w) → Prop) :
+ ActualPaths G.P G.clock 0 (writeMemory m' G.addr (tagWord G.w dest))
+ (fun tail => cap (G.linkedLogs s rs ++ tail)) ≃ ActualPaths G.P G.clock 0 m cap := by
+ obtain ⟨h, hstate, hmem, _⟩ := G.component_completion fit ht frame run halt
+ have e := emptySegmentEquiv h cap
+ rw [hstate, hmem, hn, hm] at e
+ exact e
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorImages.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorImages.lean
new file mode 100644
index 0000000000..1abe76386b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorImages.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorRoutes
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorTransition
+import OAI.Computability.VPVNP.LiveEvaluatorGatheredGroup
+
+/-!
+# Evaluator configuration images after linked routes
+
+Tag transfers leave the disjoint configuration banks intact. Each completed
+gather represents exactly its raw field, and the one-call final state writer
+represents the canonical accepting halt on a blank outgoing bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM LiveStageLink PairStages LiveConfigGather LiveEvaluatorEncoding LiveEvaluatorRAM
+open LiveEvaluatorGroup (fieldWords_eq_calls configAt_gathered_disjoint_iff)
+open scoped Fin.CommRing
+
+variable (G : PairStages.Group) {M : ℕ}
+
+private theorem offset (b : Word G.w) (i : Fin (fieldWords M)) (fit : b.val+fieldWords M ≤ 2^G.w) :
+ (b+(i.val : Word G.w)).val = b.val+i.val := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt (by have := i.isLt; omega)]
+
+theorem configAt_write_iff {b addr v : Word G.w} (m : Memory G.w)
+ (hw : 2 ≤ G.w) (hs : G.evaluator.extra+2 ≤ 2^G.w) (fit : b.val+fieldWords M ≤ 2^G.w)
+ (fresh : addr.val < b.val ∨ b.val+fieldWords M ≤ addr.val) (c : Code G.evaluator.extra M) :
+ ConfigAt (writeMemory m addr v) b c ↔ ConfigAt m b c := by
+ rw [configAt_iff_words hw hs, configAt_iff_words hw hs]
+ apply forall_congr'
+ intro i
+ have he : (b+(i.val : Word G.w)).val ≠ addr.val := by rw [offset G b i fit]; have := i.isLt; omega
+ rw [writeMemory, ite_eq_right he]
+
+/-- A native configuration image fixes the represented code uniquely. -/
+theorem configAt_eq_iff {b : Word G.w} {m : Memory G.w} (hw : 2 ≤ G.w)
+ (hs : G.evaluator.extra+2 ≤ 2^G.w) {c : Code G.evaluator.extra M} (h : ConfigAt m b c)
+ (z : Code G.evaluator.extra M) : ConfigAt m b z ↔ z = c := by
+ constructor
+ · intro hz
+ let f := format (M := M) hw hs
+ apply Function.LeftInverse.injective f.parse_words
+ exact funext fun i => ((configAt_iff_words hw hs b m z).mp hz i).symm.trans
+ ((configAt_iff_words hw hs b m c).mp h i)
+ · rintro rfl; exact h
+
+/-- The just-gathered bank is valid precisely for the decoded cut value. -/
+theorem gather_image (outgoing : Bool) (F : EvaluatorGather.Fit G outgoing (fieldWords M))
+ (hs : G.evaluator.extra+2 ≤ 2^G.w) (m : Memory G.w) (bits : Fin (fieldWords M*G.w) → Bool)
+ (c : Code G.evaluator.extra M) :
+ ConfigAt (gatherMemory G outgoing F m bits) (EvaluatorGather.operands G outgoing 1) c ↔
+ (format F.width hs).decode bits = some c :=
+ (configAt_write_iff G _ F.width hs F.dest F.tagOutside c).trans (gathered_configAt_iff ..)
+
+/-- The incoming evaluator image survives all outgoing gather and router writes. -/
+theorem gather_frame (F : EvaluatorGather.Fit G true (fieldWords M)) (m : Memory G.w)
+ (bits : Fin (fieldWords M*G.w) → Bool) (hl : PrepLayout G.evaluator G.transitionPub M)
+ (fresh : G.addr.val < (G.transitionPub 1).val ∨ (G.transitionPub 1).val+fieldWords M ≤ G.addr.val)
+ (sep : (G.transitionPub 1).val+fieldWords M ≤ (G.transitionPub 2).val ∨
+ (G.transitionPub 2).val+fieldWords M ≤ (G.transitionPub 1).val) (c : Code G.evaluator.extra M) :
+ ConfigAt (gatherMemory G true F m bits) (G.transitionPub 1) c ↔ ConfigAt m (G.transitionPub 1) c := by
+ have fit := hl.oldFit
+ rw [← fieldWords_eq_calls] at fit
+ have hbase : EvaluatorGather.operands G true 1 = G.transitionPub 2 := rfl
+ unfold gatherMemory retag
+ rw [configAt_write_iff G _ F.width hl.states fit fresh c]
+ refine (configAt_gathered_disjoint_iff _ hl.oldFit F.dest ?_ bits c).trans
+ (configAt_write_iff G _ F.width hl.states fit fresh c)
+ simpa only [← fieldWords_eq_calls, hbase] using sep
+
+/-- The final endpoint's router and state writer preserve the incoming image. -/
+theorem put_frame (m : Memory G.w) (hl : PrepLayout G.evaluator G.transitionPub M)
+ (fresh : G.addr.val < (G.transitionPub 1).val ∨ (G.transitionPub 1).val+fieldWords M ≤ G.addr.val)
+ (sep : (G.transitionPub 2).val < (G.transitionPub 1).val ∨
+ (G.transitionPub 1).val+fieldWords M ≤ (G.transitionPub 2).val) (c : Code G.evaluator.extra M) :
+ ConfigAt (putMemory G true m) (G.transitionPub 1) c ↔ ConfigAt m (G.transitionPub 1) c := by
+ have fit := hl.oldFit
+ rw [← fieldWords_eq_calls] at fit
+ unfold putMemory EvaluatorSentinel.transferred EvaluatorSentinel.put retag
+ rw [show EvaluatorSentinel.operands G true 1 = G.transitionPub 2 from rfl, configAt_write_iff G _ hl.width hl.states fit fresh c, configAt_write_iff G _ hl.width hl.states fit sep c,
+ configAt_write_iff G _ hl.width hl.states fit fresh c]
+
+/-- On a blank outgoing bank the final route imposes exactly the accepting halt. -/
+theorem put_image (m : Memory G.w) (hl : PrepLayout G.evaluator G.transitionPub M)
+ (zero : ∀ i : Fin (fieldWords M), m ((G.transitionPub 2).val+i.val) = 0)
+ (fresh : G.addr.val < (G.transitionPub 2).val ∨ (G.transitionPub 2).val+fieldWords M ≤ G.addr.val)
+ (z : Code G.evaluator.extra M) : ConfigAt (putMemory G true m) (G.transitionPub 2) z ↔ z = .accepted := by
+ have fit := hl.outFit
+ rw [← fieldWords_eq_calls] at fit
+ apply configAt_eq_iff G hl.width hl.states _ z
+ apply configAt_of_words hl.width hl.states .accepted
+ intro i
+ rw [offset G _ i fit]
+ apply EvaluatorSentinel.final_image G hl.width hl.states _ _ fresh i
+ intro j
+ have he : (G.transitionPub 2).val+j.val ≠ G.addr.val := by have := j.isLt; omega
+ rw [show EvaluatorSentinel.operands G true 1 = G.transitionPub 2 from rfl, retag, writeMemory, ite_eq_right he, zero]
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorLocalCount.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorLocalCount.lean
new file mode 100644
index 0000000000..0b59d24ac5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorLocalCount.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.LiveLocalGroupCount
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorPhysical
+import OAI.Computability.VPVNP.LiveOutsideTailCount
+
+/-!
+# Local evaluator multiplicity from the physical header memory
+
+Every noninitial evaluator group gathers its actual incoming cut. Its outgoing
+case uses the header's raw field or the canonical last sentinel. For an empty
+evaluator, the first router writes the already-accepting control state and
+skips preparation. Both paths include the concrete header prefix in the cap.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM PairStages LiveEvaluatorEncoding LiveEvaluatorRAM LiveHeaderDescriptors LiveHeader
+open ChainAssignments LiveChain LocalCount
+open scoped Fin.CommRing
+
+variable {G : PairStages.Group} {S H : ℕ} (W : Conditions G S H)
+variable (adv : CutSchedule.Bits (sizes G).advice)
+variable (fits : limit G < 2^G.w) (fit : GeometryFit G (radius G))
+variable (layout : LiveEvaluatorTail.Layout G.evaluator.extra (radius G) G.w (sizes G).delta)
+variable (init : Code G.evaluator.extra (radius G))
+variable (cuts : AllCuts (sizes G).h (sizes G).delta) (i : Fin (2^(sizes G).h))
+variable (mode : physicalTag cuts (halves (sizes G).h (.inr i)) = some .tail)
+variable (pad : ∀ side, LiveHeaderProgram.Fields.ValidPadding (sizes G) cuts (halves (sizes G).h (.inr i)) .tail side)
+variable (tr : Prepared W adv cuts (halves (sizes G).h (.inr i)) .tail)
+variable (header : LiveHeaderProgram.Output (sizes G) (headerBase G) G.g.d W.word adv cuts
+ (halves (sizes G).h (.inr i)) .tail (memory tr))
+
+/-- The checked header reports fit the resource interface used by the native
+evaluator suffix, at the same burst clock as every continuation. -/
+theorem headerResources : OutsideTraces.Resources tr.logs (LiveHeaderSchedule.costBound (sizes G)+4) 11 G.clock := by
+ refine ⟨tr.cost, fun r hr => by have := tr.probes r hr; omega, fun r hr => ?_⟩
+ exact localSegment_event_bound ((runSegment_iff ..).mp tr.run).1 r hr
+
+variable (call : max 11 (G.w+4) ≤ H)
+variable (budget : LiveHeaderSchedule.costBound (sizes G)+4 + 2*OutsideTailCount.routeCost G.w (radius G) +
+ OutsideTailCount.transitionCost (radius G) ≤ S*H)
+include fits fit mode pad header call budget
+
+/-- Full physical post-header count for every noninitial evaluator group. -/
+theorem nonfirstPhysicalCount (nonfirst : 0 < i.val) :
+ Nat.card (remaining tr) = tailCount G.evaluator layout init (liveCutEquiv (sizes G).h (sizes G).delta cuts).2 i := by
+ obtain ⟨o⟩ := physicalOutput G header layout init mode fits (pad .right)
+ obtain ⟨flag,raw,img,value⟩ := physicalIncoming G header layout init mode fits nonfirst (pad .left)
+ let F := gatherFit G fits layout.symbolWidth false
+ let frame := gatheredOutputFrame G (addresses G fits) F (memory tr) raw
+ exact OutsideTailCount.nonfirstCount_capped G layout init _ i (memory tr) fit tr.tag flag F raw img
+ (Or.inl (addresses G fits).leftStart) value (o.transport frame) tr.logs (headerResources W adv cuts i tr) (by simpa using call) budget
+
+/-- With no evaluator rows the canonical initial code is the accepting halt.
+No prefix-copy, skeleton or scatter stage is entered at the middle cut. -/
+theorem emptyFirstPhysicalCount (first : i.val = 0) (empty : G.evaluator.extra = 0) (initEq : init = .accepted) :
+ Nat.card (remaining tr) = tailCount G.evaluator layout init (liveCutEquiv (sizes G).h (sizes G).delta cuts).2 i := by
+ obtain ⟨o⟩ := physicalOutput G header layout init mode fits (pad .right)
+ have he := headerBelowOld G fits
+ have hf := HeaderFlags.firstTail G.constants G.g G.lit (he.trans_lt (G.transitionPub 1).isLt) header
+ change memory tr _ = (if 2^(sizes G).h+i.val+1 = 2^(sizes G).h+1 then 1 else 0) at hf
+ rw [ite_eq_left (by omega)] at hf
+ have hclk := fit.gatherClock
+ rw [Nat.card_congr (putHandoff G false fit.prep.width (by omega) (memory tr) tr.tag hf _).symm]
+ let m := putMemory G false (memory tr)
+ have tag : G.tagged Stage.last m := by
+ have hn : EvaluatorSentinel.destination G false = Stage.last := by simp [EvaluatorSentinel.destination,empty]
+ unfold m putMemory EvaluatorSentinel.transferred
+ rw [hn]; exact tagged_retag ..
+ have old (c : Code G.evaluator.extra (radius G)) : LiveEvaluatorTail.boundary layout init
+ (liveCutEquiv (sizes G).h (sizes G).delta cuts).2 i.castSucc = some c ↔ ConfigAt m (G.transitionPub 1) c := by
+ have hi : i.castSucc = 0 := Fin.ext first
+ rw [hi, LiveEvaluatorTail.boundary_zero, initEq, Option.some.injEq, eq_comm]
+ exact (empty_initial_image G (memory tr) empty fit (fun j => header.fresh_after_limit _ (he.trans (Nat.le_add_right ..))) c).symm
+ let o' := o.transport (putInitialFrame G (addresses G fits) (memory tr))
+ have hp := OutsideTailStages.putRoute G false
+ have hp' : OutsideTraces.Resources (putLogs G false) 8 4 (OutsideTailStages.instructionBound G) :=
+ ⟨hp.cost,fun r hr => (putLogs_calls G false r hr).le,hp.work⟩
+ have pre := (headerResources W adv cuts i tr).append hp'
+ have hc := OutsideTailCount.lastCount_capped (S := S) (H := H) G layout init _ i m fit tag old o'
+ (tr.logs++putLogs G false) pre (by simpa using call) ?budget
+ · simpa only [List.append_assoc] using hc
+ case budget =>
+ have hk : 1 ≤ fieldWords (radius G) := by unfold fieldWords; omega
+ have hlow := Nat.mul_le_mul_right (G.w+4) hk
+ simp only [Nat.one_mul] at hlow
+ unfold OutsideTailCount.routeCost at budget ⊢
+ omega
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorPhysical.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorPhysical.lean
new file mode 100644
index 0000000000..7f46a52cba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorPhysical.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorTransport
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorCut
+import OAI.Computability.VPVNP.LivePhysicalRoutes
+import OAI.Computability.VPVNP.LiveHeaderOutputFrame
+
+/-!
+# Evaluator inputs and outputs from the actual physical header
+
+The live header parser supplies the mode, the two router flags, the raw cut
+field and the zero-default outgoing endpoint. This proof reconstructs the
+outgoing case at every evaluator group and the incoming field at every
+noninitial group, without assuming well-formed configuration words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM PairStages LiveConfigGather LiveEvaluatorEncoding LiveEvaluatorRAM LiveHeaderDescriptors
+open ChainAssignments LiveHeader
+open LiveHeaderSchedule (Sizes configBase)
+open scoped Fin.CommRing
+
+variable (G : PairStages.Group)
+/-- The evaluated header dimensions used to recover the evaluator routes from the physical cut. -/
+abbrev sizes := Header.sizes G.constants G.g
+/-- The physical header workspace base for the current evaluator group. -/
+abbrev headerBase := Header.base G.g
+/-- The first address past the group's live-header buffers. -/
+abbrev headerEnd := LiveHeaderSchedule.limit (sizes G) (headerBase G)
+
+theorem headerBelowOld (fits : limit G < 2^G.w) : headerEnd G ≤ (G.transitionPub 1).val := by
+ let old := (Layout.oldState G.constants).eval G.g
+ have h : headerEnd G ≤ old := by change headerEnd G ≤ headerEnd G+21+G.constants.labels.eval G.g; omega
+ have fit : old < 2^G.w := by
+ change old+G.constants.configWords.eval G.g+G.constants.configWords.eval G.g+5+24+
+ G.constants.prefixCapacity.eval G.g+G.constants.labels.eval G.g < 2^G.w at fits; omega
+ have he : (G.transitionPub 1).val = old := Nat.mod_eq_of_lt fit
+ rwa [he]
+
+theorem physicalSource (fits : limit G < 2^G.w) (out : Bool) :
+ (cutSource G out).val = configBase (sizes G) (headerBase G) (if out then Side.right else Side.left) := by
+ have he := headerBelowOld G fits
+ have hb := (G.transitionPub 1).isLt
+ have left : configBase (sizes G) (headerBase G) .left ≤ headerEnd G := by
+ change configBase (sizes G) (headerBase G) .left ≤ configBase (sizes G) (headerBase G) .left+
+ (sizes G).config+(sizes G).config; omega
+ have right : configBase (sizes G) (headerBase G) .right ≤ headerEnd G := Nat.le_add_right ..
+ cases out with
+ | false => exact Nat.mod_eq_of_lt (show configBase (sizes G) (headerBase G) .left < 2^G.w by omega)
+ | true => exact Nat.mod_eq_of_lt (show configBase (sizes G) (headerBase G) .right < 2^G.w by omega)
+
+variable {hw : 4 ≤ G.w} {advice : CutSchedule.Bits (sizes G).advice}
+variable {cuts : AllCuts (sizes G).h (sizes G).delta} {i : Fin (2^(sizes G).h)} {m : Memory G.w}
+variable (header : LiveHeaderProgram.Output (sizes G) (headerBase G) G.g.d hw advice cuts
+ (halves (sizes G).h (.inr i)) .tail m)
+variable (layout : LiveEvaluatorTail.Layout G.evaluator.extra (radius G) G.w (sizes G).delta)
+variable (init : Code G.evaluator.extra (radius G))
+variable (mode : physicalTag cuts (halves (sizes G).h (.inr i)) = some .tail)
+include header mode
+
+/-- The actual header supplies every outgoing constructor input. A last cut
+uses the zero-default memory beyond the header allocation. -/
+theorem physicalOutput (fits : limit G < 2^G.w)
+ (pad : LiveHeaderProgram.Fields.ValidPadding (sizes G) cuts (halves (sizes G).h (.inr i)) .tail .right) :
+ Nonempty (Output G m (LiveEvaluatorTail.boundary layout init (liveCutEquiv (sizes G).h (sizes G).delta cuts).2 i.succ)) := by
+ let a := addresses G fits
+ have he := headerBelowOld G fits
+ have hf := HeaderFlags.last G.constants G.g G.lit (he.trans_lt (G.transitionPub 1).isLt) header
+ change m _ = (if 2^(sizes G).h+i.val+1 = 2^((sizes G).h+1) then 1 else 0) at hf
+ rw [pow_succ] at hf
+ by_cases last : i.val+1 = 2^(sizes G).h
+ · rw [ite_eq_left (by omega)] at hf
+ refine ⟨.final hf (fun j => header.fresh_after_limit _ (by change headerEnd G ≤ _; have := a.oldEnd; omega))
+ (Or.inl (by have := a.leftStart; have := a.rightStart; have := a.sourceEnd; have := a.oldEnd; omega)) ?_⟩
+ have hi : i.succ = Fin.last (2^(sizes G).h) := Fin.ext last
+ rw [hi, LiveEvaluatorTail.boundary_last]
+ · have interior : i.val+1 < 2^(sizes G).h := by have := i.isLt; omega
+ rw [ite_eq_right (by omega)] at hf
+ obtain ⟨raw,img,value⟩ := header.tail_outgoing layout init rfl mode pad (physicalSource G fits true) interior
+ exact ⟨.cut (gatherFit G fits layout.symbolWidth true) raw hf img
+ (Or.inl (by have := a.leftStart; have := a.rightStart; change G.addr.val < (cutSource G true).val; omega))
+ layout.stateWidth value⟩
+
+/-- The incoming zero-flag case recovers its actual raw array from the left
+incident cut. The semantic boundary includes its mode and padding tests. -/
+theorem physicalIncoming (fits : limit G < 2^G.w) (nonfirst : 0 < i.val)
+ (pad : LiveHeaderProgram.Fields.ValidPadding (sizes G) cuts (halves (sizes G).h (.inr i)) .tail .left) :
+ m ((Router.firstTail.data G.g G.lit) 0).val = 0 ∧
+ ∃ raw : Fin (k G*G.w) → Bool, ArrayBitImage m (cutSource G false) raw ∧
+ LiveEvaluatorTail.boundary layout init (liveCutEquiv (sizes G).h (sizes G).delta cuts).2 i.castSucc =
+ (format layout.symbolWidth layout.stateWidth).decode raw := by
+ have he := headerBelowOld G fits
+ have hf := HeaderFlags.firstTail G.constants G.g G.lit (he.trans_lt (G.transitionPub 1).isLt) header
+ change m _ = (if 2^(sizes G).h+i.val+1 = 2^(sizes G).h+1 then 1 else 0) at hf
+ rw [ite_eq_right (by omega)] at hf
+ exact ⟨hf, header.tail_incoming layout init rfl mode pad (physicalSource G fits false) nonfirst⟩
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorRouteCost.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorRouteCost.lean
new file mode 100644
index 0000000000..64a6fad4ed
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorRouteCost.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.LiveOutsideTailStages
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorCount
+
+/-!
+# Costs of the incoming and outgoing routes to the evaluator
+
+The zero-flag route makes one router jump followed by one gather call per
+configuration word. The one-flag route makes a jump and a control-word
+write. In both cases the charged reports include the stage dispatcher and
+its transfer to the next row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM LiveStageLink PairStages LiveEvaluatorEncoding
+open scoped Fin.CommRing
+
+variable (G : Group) {k M : ℕ}
+
+theorem gatherLogs_cost (outgoing : Bool) (bits : Fin (k*G.w) → Bool) :
+ RAMBuckets.cost Report.probes (gatherLogs G outgoing bits) ≤ 4+k*(G.w+4) := by
+ simpa only [Nat.mul_comm k (G.w+4)] using (OutsideTailStages.gatherRoute G outgoing bits).cost
+
+/-- The gather reads the bits of one word and writes the reconstructed word.
+The linked route adds at most two probes to each such report. -/
+theorem gatherLogs_calls (outgoing : Bool) (bits : Fin (k*G.w) → Bool) :
+ ∀ r ∈ gatherLogs G outgoing bits, 1+r.probes ≤ G.w+4 := by
+ rw [gatherLogs, List.forall_mem_cons]
+ constructor
+ · have hp := (router outgoing).outer_jump_probes G.evaluator G.g G.lit 0
+ ((0 : Fin 3).val : Word G.w) (EvaluatorGather.stage outgoing)
+ change (jumpReport G (router outgoing) 0 (EvaluatorGather.stage outgoing)).probes = 3 at hp
+ rw [hp]; omega
+ · intro rep hrep
+ obtain ⟨raw, hraw, rfl⟩ := List.mem_map.mp hrep
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp hraw
+ have hp : (LiveConfigGather.wordReport (EvaluatorGather.operands G outgoing)
+ ((RAMSerialization.arrayBits k G.w).symm bits) i).probes = G.w+1 := LiveConfigGather.report_probes ..
+ rw [linkedReport_probes, hp]
+ split <;> omega
+
+private theorem put_probes (outgoing : Bool) :
+ (linkedReport G.nextStage G.addr (EvaluatorSentinel.stage outgoing) (EvaluatorSentinel.report G outgoing)).probes = 3 := by
+ rw [linkedReport_probes]
+ have nextSome : (G.nextStage (EvaluatorSentinel.stage outgoing)).isSome := by
+ cases outgoing with
+ | true => rfl
+ | false =>
+ change (if G.evaluator.extra = 0 then some Stage.last else some Stage.prefixLength).isSome = true
+ split <;> rfl
+ rw [ite_eq_left ⟨rfl, nextSome⟩]
+ rfl
+
+/-- Each endpoint path consists of two four-unit calls. -/
+theorem putLogs_cost (outgoing : Bool) : RAMBuckets.cost Report.probes (putLogs G outgoing) = 8 := by
+ have hj := (router outgoing).outer_jump_probes G.evaluator G.g G.lit 1
+ ((1 : Fin 3).val : Word G.w) (EvaluatorSentinel.stage outgoing)
+ change (jumpReport G (router outgoing) 1 (EvaluatorSentinel.stage outgoing)).probes = 3 at hj
+ simp only [putLogs, Group.linkedLogs, List.map_singleton, RAMBuckets.cost, hj, put_probes]
+
+theorem putLogs_calls (outgoing : Bool) :
+ ∀ r ∈ putLogs G outgoing, 1+r.probes = 4 := by
+ have hj := (router outgoing).outer_jump_probes G.evaluator G.g G.lit 1
+ ((1 : Fin 3).val : Word G.w) (EvaluatorSentinel.stage outgoing)
+ change (jumpReport G (router outgoing) 1 (EvaluatorSentinel.stage outgoing)).probes = 3 at hj
+ simp [putLogs, Group.linkedLogs, hj, put_probes]
+
+namespace Output
+
+variable {G} {m : Memory G.w} {b : Option (Code G.evaluator.extra M)}
+
+/-- Either kind of outgoing field fits the word-gather allowance. -/
+theorem logs_cost (o : Output G m b) :
+ RAMBuckets.cost Report.probes o.logs ≤ 4+fieldWords M*(G.w+4) := by
+ cases o with
+ | cut _ bits => exact gatherLogs_cost G true bits
+ | final =>
+ change RAMBuckets.cost Report.probes (putLogs G true) ≤ _
+ rw [putLogs_cost]
+ have h : 1 ≤ fieldWords M := by unfold fieldWords; omega
+ have h' := Nat.mul_le_mul_right (G.w+4) h
+ rw [Nat.one_mul] at h'
+ omega
+
+theorem logs_calls (o : Output G m b) : ∀ r ∈ o.logs, 1+r.probes ≤ G.w+4 := by
+ cases o with
+ | cut _ bits => exact gatherLogs_calls G true bits
+ | final =>
+ intro r hr
+ have := putLogs_calls G true r hr
+ omega
+
+end Output
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorRoutes.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorRoutes.lean
new file mode 100644
index 0000000000..7b7b415c59
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorRoutes.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorGather
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorSentinel
+import OAI.Computability.VPVNP.LiveProgramHandoffs
+
+/-!
+# From the two tail routers to their evaluator banks
+
+The zero flag of each router selects the corresponding gathered configuration.
+A one at the last router selects the accepting sentinel, and a one at the first
+router selects the initial state writer. Each pair of stages contributes its
+literal ordered reports, including all tag updates, to the transcript cap.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM LiveStageLink PairStages LiveConfigGather
+open scoped Fin.CommRing
+
+variable (G : PairStages.Group)
+
+/-- The first-tail router for incoming preparation or the last-group router for outgoing
+preparation. -/
+abbrev router (outgoing : Bool) : Router := if outgoing then Router.last else Router.firstTail
+
+/-- Write the selected stage's tag into the physical group's dispatcher cell. -/
+def retag (s : Stage) (m : Memory G.w) := writeMemory m G.addr (tagWord G.w s)
+
+theorem tagged_retag (s : Stage) (m : Memory G.w) : G.tagged s (retag G s m) := by
+ simp [Group.tagged, retag, writeMemory]
+
+/-- The physical outer report of a router jump to the specified stage through the chosen branch
+slot. -/
+def jumpReport (r : Router) (i : Fin 3) (dest : Stage) :=
+ r.outerReport G.evaluator G.g G.lit (r.jumpReport G.g G.lit i (i.val : Word G.w) dest)
+
+private noncomputable def jump (r : Router) (i : Fin 3) (dest : Stage)
+ (target : r.target i = .jump (dest.castLE (by decide)))
+ (hclock : 57 ≤ G.clock) (hw : 2 ≤ G.w) (m : Memory G.w) (ht : G.tagged r.stage m)
+ (flag : m ((r.data G.g G.lit) 0).val = (i.val : Word G.w)) (cap : List (Report G.w) → Prop) :
+ ActualPaths G.P G.clock 0 (retag G dest m) (fun rs => cap (jumpReport G r i dest :: rs)) ≃
+ ActualPaths G.P G.clock 0 m cap := by
+ rw [G.program_eq]
+ simpa only [retag, jumpReport, flag] using r.jumpEquiv G.constants G.evaluator G.pair G.g G.lit
+ G.tagFit hw cap G.clock hclock 0 m i flag ht dest target
+
+/-- A stage-tag update outside the source cut preserves every unpacked bit. -/
+theorem image_retag {k : ℕ} (s : Stage) {base : Word G.w} {m : Memory G.w}
+ {bits : Fin (k*G.w) → Bool} (h : ArrayBitImage m base bits)
+ (outside : G.addr.val < base.val ∨ base.val+k*G.w ≤ G.addr.val) :
+ ArrayBitImage (retag G s m) base bits := by
+ intro i
+ have he : base.val+i.val ≠ G.addr.val := by have := i.isLt; omega
+ rw [retag, writeMemory, ite_eq_right he, h]
+
+/-- The memory after routing into the gather, packing the cut bits into the selected state
+bank, and transferring to its successor. -/
+def gatherMemory {k : ℕ} (outgoing : Bool) (F : EvaluatorGather.Fit G outgoing k)
+ (m : Memory G.w) (bits : Fin (k*G.w) → Bool) :=
+ retag G (EvaluatorGather.destination outgoing) (gathered (EvaluatorGather.operands G outgoing 1) F.dest bits
+ (retag G (EvaluatorGather.stage outgoing) m))
+
+/-- The router jump followed by the linked configuration-word gather reports for the selected
+incident side. -/
+def gatherLogs {k : ℕ} (outgoing : Bool) (bits : Fin (k*G.w) → Bool) :=
+ jumpReport G (router outgoing) 0 (EvaluatorGather.stage outgoing) ::
+ G.linkedLogs (EvaluatorGather.stage outgoing) (EvaluatorGather.reports G outgoing bits)
+
+/-- The full zero-flag route, including the gathered word array and the
+transfer to the last router or terminal transition. -/
+noncomputable def gatherHandoff {k : ℕ} (outgoing : Bool) (F : EvaluatorGather.Fit G outgoing k)
+ (hclock : 8*G.w+67 ≤ G.clock) (m : Memory G.w) (bits : Fin (k*G.w) → Bool)
+ (ht : G.tagged (router outgoing).stage m) (flag : m (((router outgoing).data G.g G.lit) 0).val = 0)
+ (img : ArrayBitImage m (EvaluatorGather.operands G outgoing 0) bits)
+ (fresh : G.addr.val < (EvaluatorGather.operands G outgoing 0).val ∨
+ (EvaluatorGather.operands G outgoing 0).val+k*G.w ≤ G.addr.val) (cap : List (Report G.w) → Prop) :
+ ActualPaths G.P G.clock 0 (gatherMemory G outgoing F m bits)
+ (fun rs => cap (gatherLogs G outgoing bits ++ rs)) ≃ ActualPaths G.P G.clock 0 m cap := by
+ have route : (router outgoing).target 0 = .jump ((EvaluatorGather.stage outgoing).castLE (by decide)) := by
+ cases outgoing <;> rfl
+ exact (EvaluatorGather.handoff G outgoing F hclock _ bits (tagged_retag ..)
+ (image_retag G _ img fresh) _).trans (jump G _ 0 _ route (by omega) F.width m ht flag cap)
+
+/-- The memory after routing into an endpoint writer, storing the control word, and setting the
+next stage tag. -/
+def putMemory (outgoing : Bool) (m : Memory G.w) :=
+ EvaluatorSentinel.transferred G outgoing (retag G (EvaluatorSentinel.stage outgoing) m)
+
+/-- The router jump and linked control-write report for preparing an evaluator endpoint. -/
+def putLogs (outgoing : Bool) :=
+ jumpReport G (router outgoing) 1 (EvaluatorSentinel.stage outgoing) ::
+ G.linkedLogs (EvaluatorSentinel.stage outgoing) [EvaluatorSentinel.report G outgoing]
+
+/-- The full one-flag route writes the endpoint state and enters the next
+live row with cursor zero. This includes the first group's empty evaluator. -/
+noncomputable def putHandoff (outgoing : Bool) (hw : 2 ≤ G.w) (hclock : 57 ≤ G.clock)
+ (m : Memory G.w) (ht : G.tagged (router outgoing).stage m)
+ (flag : m (((router outgoing).data G.g G.lit) 0).val = 1) (cap : List (Report G.w) → Prop) :
+ ActualPaths G.P G.clock 0 (putMemory G outgoing m)
+ (fun rs => cap (putLogs G outgoing ++ rs)) ≃ ActualPaths G.P G.clock 0 m cap := by
+ have route : (router outgoing).target 1 = .jump ((EvaluatorSentinel.stage outgoing).castLE (by decide)) := by
+ cases outgoing <;> rfl
+ exact (EvaluatorSentinel.handoff G outgoing (by omega) _ (tagged_retag ..) _).trans
+ (jump G _ 1 _ route hclock hw m ht flag cap)
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorSentinel.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorSentinel.lean
new file mode 100644
index 0000000000..983216b778
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorSentinel.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorHandoff
+import OAI.Computability.VPVNP.LiveEvaluatorInitializeStages
+
+/-!
+# Native control-word writes at evaluator endpoints
+
+The first group writes its initial state and the last group writes the accepting
+state. Both single-call stages have a unique empty choice string. They enter the
+next row of the actual live program with an updated control word and stage tag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorSentinel
+
+open BurstRAM LiveStageLink PairStages LiveEvaluatorInitialize LiveEvaluatorEncoding
+open scoped Fin.CommRing
+
+variable (G : PairStages.Group)
+
+/-- Select the initial-state or final-state control writer for the corresponding endpoint. -/
+def stage (final : Bool) : Stage := if final then Stage.finalState else Stage.initialState
+
+/-- The successor of the endpoint writer, accounting for a halted initial evaluator and for
+prefix preparation on a running one. -/
+def destination (final : Bool) : Stage := if final then Stage.transition else
+ if G.evaluator.extra = 0 then Stage.last else Stage.prefixLength
+
+/-- The evaluator control word to install, accepting at the final endpoint or giving the
+program's initial control state. -/
+def tag (final : Bool) : Word 2 := if final then 1 else controlTag G.evaluator
+
+/-- The public control-write operands selecting the old state bank at the start or the new
+state bank at the end. -/
+def operands (final : Bool) : Fin 4 → Word G.w := Pieces.word G.g G.lit ∘ InputOperand.geometry ∘
+ StageOperands.control G.constants (if final then Layout.newState G.constants else Layout.oldState G.constants)
+
+/-- The terminating source report that writes the endpoint control word after two local steps. -/
+def report (final : Bool) : Report G.w :=
+ ⟨[.tick, .tick, .write (operands G final 1) (Fin.ofNat _ (tag G final).val)], none⟩
+
+/-- Store the endpoint control tag at the selected state bank's control-word address. -/
+def put (final : Bool) (m : Memory G.w) :=
+ writeMemory m (operands G final 1) (Fin.ofNat _ (tag G final).val)
+
+/-- The endpoint-writer memory after the enclosing linker also writes the destination stage
+tag. -/
+def transferred (final : Bool) (m : Memory G.w) := writeMemory (put G final m) G.addr (tagWord G.w (destination G final))
+
+private theorem next_stage (final : Bool) : G.nextStage (stage final) = some (destination G final) := by
+ cases final
+ · change (if G.evaluator.extra = 0 then some Stage.last else some Stage.prefixLength) = _
+ by_cases h : G.evaluator.extra = 0 <;> simp [destination, h]
+ · rfl
+
+private theorem source_run (final : Bool) (m : Memory G.w) :
+ runSegment (Pieces.component G.components (stage final) G.g G.lit) 4 (some 0) m
+ (List.replicate 1 []) = some [report G final] := by
+ have h := execute_putStage (tag G final) (operands G final) 0 m [] 0
+ change execute _ 4 _ m [] = some (report G final) at h
+ have hc : execute (Pieces.component G.components (stage final) G.g G.lit) 4
+ ((Pieces.component G.components (stage final) G.g G.lit).start 0) m [] = some (report G final) := by
+ cases final <;> exact h
+ simp only [List.replicate_succ, List.replicate_zero, runSegment, hc, Option.map_some]
+
+/-- Every accepted continuation has a unique preimage after the initial or
+final control write, with its complete linked report added to the cap. -/
+noncomputable def handoff (final : Bool) (hclock : 51 ≤ G.clock) (m : Memory G.w)
+ (ht : G.tagged (stage final) m) (cap : List (Report G.w) → Prop) :
+ ActualPaths G.P G.clock 0 (transferred G final m)
+ (fun rs => cap (G.linkedLogs (stage final) [report G final] ++ rs)) ≃
+ ActualPaths G.P G.clock 0 m cap :=
+ G.deterministicHandoff hclock ht (PreservesTagOnReturns.singleton_accept _ _ _ (by rfl))
+ (next_stage G final) (source_run G final m) (by rfl) (by rfl) cap
+
+theorem linked_cost (final : Bool) (hclock : 51 ≤ G.clock) (m : Memory G.w)
+ (ht : G.tagged (stage final) m) :
+ RAMBuckets.cost Report.probes (G.linkedLogs (stage final) [report G final]) = 4 := by
+ have hc := (G.component_completion hclock ht (PreservesTagOnReturns.singleton_accept _ _ _ (by rfl))
+ (source_run G final m) (by rfl)).2.2.2
+ rw [hc, next_stage]; rfl
+
+/-- After the tag transfer the final bank still stores precisely the accepting
+configuration, including all zero tape cells. -/
+theorem final_image {M : ℕ} (hw : 2 ≤ G.w) (hs : G.evaluator.extra+2 ≤ 2^G.w)
+ (m : Memory G.w) (zero : ∀ k : Fin (fieldWords M), m ((operands G true 1).val+k.val) = 0)
+ (outside : G.addr.val < (operands G true 1).val ∨ (operands G true 1).val+fieldWords M ≤ G.addr.val) :
+ Stores hw hs (operands G true 1).val (transferred G true m) (.accepted : Code G.evaluator.extra M) := by
+ intro k
+ have h := final_stores hw hs (operands G true 1) m zero k
+ change writeMemory (put G true m) G.addr _ _ = _
+ have he : (operands G true 1).val + k.val ≠ G.addr.val := by have := k.isLt; omega
+ rw [writeMemory, ite_eq_right he]
+ exact h
+
+end LiveProgram.EvaluatorSentinel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorSuffix.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorSuffix.lean
new file mode 100644
index 0000000000..a55059edeb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorSuffix.lean
@@ -0,0 +1,239 @@
+import OAI.Computability.VPVNP.LiveProgramPrefixCopyRun
+import OAI.Computability.VPVNP.LiveProgramSkeletonRun
+import OAI.Computability.VPVNP.LiveProgramScatterRun
+import OAI.Computability.VPVNP.LiveProgramAdviceInputLayout
+
+/-!
+# The linked midpoint prefix copy, skeleton generation and exponent scatter
+
+All three calls read their operands from published frames. The only changes
+outside the initialized tape bank are the stage transfers. The accepting
+continuation therefore starts with the intended initial code and the tag
+of the last-group router.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+
+open BurstRAM LiveStageLink CompressorRecords LiveEvaluatorInitialize
+open LiveEvaluatorReindex (Sources)
+open EvaluatorProgramRawInput (runtime runtime_length)
+open LiveEvaluatorEncoding (fieldWords)
+open scoped Fin.CommRing
+
+variable {d t Z : ℕ}
+
+/-- The concrete suffix runs and its final evaluator bank. -/
+structure SuffixRun (G : Group) (cp : Fin 4 → Word G.w) (raw : List Bool)
+ (formal : Fin t → Word Z) (d : ℕ) (m final : Memory G.w) : Prop where
+ returning : Advice.Returning G.P G.clock (max 1 raw.length + (2*(t*Z)+6*Z+4) + max 1 (d*Z)) 10 m final
+ cost : Advice.CostLimit G.P G.clock (max 1 raw.length + (2*(t*Z)+6*Z+4) + max 1 (d*Z)) m
+ (10*max 1 raw.length + 8*(2*(t*Z)+6*Z+4) + 11*max 1 (d*Z))
+ config : LiveEvaluatorRAM.ConfigAt final (cp 1) (LiveEvaluatorTail.initialCode (cp 0).val
+ (UniversalMachine.initial G.evaluator (raw ++ runtime formal)))
+ tag : G.tagged Stage.last final
+ outside (j : ℕ) (hTag : j ≠ G.addr.val) (hBank : j < (cp 1).val ∨ (cp 1).val + fieldWords (cp 0).val ≤ j) :
+ final j = m j
+
+/-- Static frame addresses and input banks lie outside the tape area being written. -/
+structure SuffixRoom (G : Group) (cp : Fin 4 → Word G.w) (sc : Fin 5 → Word G.w) : Prop where
+ tagState : G.addr.val < (cp 1).val
+ tagInput : G.addr.val < (sc 0).val
+ tagOrder : G.addr.val < (sc 1).val
+ stateFit : (cp 1).val + fieldWords (cp 0).val ≤ 2^G.w
+ prefixWord (i : Fin 5) : (cp 1).val + fieldWords (cp 0).val ≤ (G.prefixCopyBase + (i.val : Word G.w)).val
+ skeleton (i : Fin 4) : (cp 1).val + fieldWords (cp 0).val ≤ (G.skeletonBase + (i.val : Word G.w)).val
+ scatter (i : Fin 5) : (cp 1).val + fieldWords (cp 0).val ≤ (ScatterRun.operandBase G + (i.val : Word G.w)).val
+
+/-- Execute the three framed native tables at their actual stage tags.
+The initial control word has already been installed and the tape cells are
+blank. -/
+theorem suffixRun (G : Group) (cp sk state : Fin 4 → Word G.w) (sc : Fin 5 → Word G.w)
+ (raw : List Bool) (perm : Fin d ≃ Fin t) (dense : Fin d → Word Z) (formal : Fin t → Word Z)
+ (order : ∀ i, formal (perm i) = dense i) (m : Memory G.w) (clock : 94 ≤ G.clock)
+ (hw : 2 ≤ G.w) (running : G.evaluator.extra ≠ 0) (hs : G.evaluator.extra+2 ≤ 2^G.w)
+ (L : LiveEvaluatorInputStages.Layout cp sk state sc d t Z raw.length)
+ (room : SuffixRoom G cp sc) (space : raw.length+(2*(t*Z)+6*Z+4) ≤ (cp 0).val+1)
+ (start : G.tagged Stage.prefixCopy m)
+ (control : m (cp 1).val = Fin.ofNat _ (controlTag G.evaluator).val)
+ (zeros : ∀ i : Fin (fieldWords (cp 0).val), 0 < i.val → m ((cp 1).val+i.val) = 0)
+ (packed : ∀ j < raw.length, m (sourceAddress cp (j : Word G.w)).val = inputWord G.w raw (j/G.w))
+ (src : Sources sc perm dense m) (cpData : Frame.data G.prefixCopyBase m = copyPublic cp (raw.length : Word G.w))
+ (skData : Frame.data G.skeletonBase m = sk) (scData : Frame.data (ScatterRun.operandBase G) m = sc) :
+ ∃ final, SuffixRun G cp raw formal d m final := by
+ let zeroRuntime := runtime (fun _ : Fin t => (0 : Word Z))
+ have hlen : zeroRuntime.length = 2*(t*Z)+6*Z+4 := runtime_length ..
+ have hTag := room.tagState
+ have hEnd : firstData cp + raw.length + zeroRuntime.length ≤ (cp 1).val + fieldWords (cp 0).val := by
+ rw [hlen, firstData, fieldWords]; omega
+ have hpre : G.addr.val < firstData cp := by unfold firstData; omega
+ have hsk := L.runtimeBase
+ obtain ⟨u, hu, copied⟩ := G.prefixCopyRun cp raw m hw L.wordWidth running L.prefixFit packed
+ (fun j hj => (L.packedSeparate j hj).2) cpData start (.inl hpre)
+ (fun j => .inr (by have := room.prefixWord j; omega)) (by omega)
+ let m₁ := writeMemory u G.addr (tagWord G.w Stage.skeleton)
+ have frame₁ : Frame.data G.skeletonBase m₁ = sk := by
+ rw [← skData]
+ funext j
+ have hj := room.skeleton j
+ change writeMemory u G.addr _ _ = _
+ rw [writeMemory, ite_eq_right (by omega), copied.outside _ (.inr (by omega))]; rfl
+ obtain ⟨v, hv, _, copied'⟩ := G.skeletonRun sk m₁ hw L.runtimeWidth L.runtimeBits L.runtimeLength L.runtimeFit
+ frame₁ (by simp [tagged, m₁, writeMemory]) (.inl (by omega))
+ (fun j => .inr (by rw [hsk, L.runtimeLength]; have := room.skeleton j; omega)) (by omega)
+ let taggedInput := writeMemory m G.addr (tagWord G.w Stage.scatter)
+ let taggedCopy := writeMemory u G.addr (tagWord G.w Stage.scatter)
+ let m₂ := writeMemory v G.addr (tagWord G.w Stage.scatter)
+ have hcopy : Copied raw (firstData cp) raw.length taggedInput taggedCopy :=
+ copied_with_tag copied G.addr _ (.inl hpre)
+ have hskel : Copied zeroRuntime (firstData cp + raw.length) zeroRuntime.length taggedCopy m₂ := by
+ simpa only [m₁, Advice.write_tag_twice, taggedCopy, m₂, zeroRuntime, hsk] using copied'
+ have both := hcopy.append hskel
+ have agree (a : ℕ) (hne : a ≠ G.addr.val) (ho : a < firstData cp ∨ firstData cp+raw.length+zeroRuntime.length ≤ a) :
+ m₂ a = m a := by
+ have he := both.outside a (by simpa only [List.length_append, Nat.add_assoc] using ho)
+ exact he.trans (ite_eq_right hne)
+ have hsrc : Sources sc perm dense m₂ := by
+ constructor
+ · intro j
+ have hp := L.incomingSeparate j
+ have he := agree ((sc 0).val+j.val) (by have := room.tagInput; omega) (by rw [hlen]; simpa only [L.runtimeLength] using hp.2)
+ rw [he, src.incoming]
+ · intro j
+ have hp := L.mapSeparate j
+ have he := agree ((sc 1).val+j.val) (by have := room.tagOrder; omega) (by rw [hlen]; simpa only [L.runtimeLength] using hp.2)
+ rw [he, src.order]
+ have frame₂ : Frame.data (ScatterRun.operandBase G) m₂ = sc := by
+ rw [← scData]
+ funext j
+ have hj := room.scatter j
+ exact agree _ (by omega) (.inr (by omega))
+ let blank := writeMemory taggedInput (cp 1) 0
+ have hz : ∀ i : Fin (fieldWords (cp 0).val), blank ((cp 1).val+i.val) = 0 := by
+ intro i
+ by_cases he : i.val = 0
+ · simp [blank, writeMemory, he]
+ · simp only [blank, taggedInput, writeMemory, ite_eq_right (by omega : (cp 1).val+i.val ≠ (cp 1).val),
+ ite_eq_right (by omega : (cp 1).val+i.val ≠ G.addr.val), zeros i (by omega)]
+ have hcontrol : writeMemory blank (cp 1) (Fin.ofNat _ (controlTag G.evaluator).val) = taggedInput := by
+ rw [show blank = _ from rfl, Advice.write_tag_twice]
+ funext j
+ by_cases he : j = (cp 1).val
+ · subst j; simp [taggedInput, writeMemory, show (cp 1).val ≠ G.addr.val by omega, control]
+ · simp [writeMemory, he]
+ have prepared := prefix_runtime_stores (t := t) (Z := Z) hw cp G.evaluator running hs raw blank taggedCopy m₂
+ (by simpa only [List.length_append, runtime_length] using space) hz (hcontrol ▸ hcopy)
+ (by simpa only [zeroRuntime, runtime_length] using hskel)
+ have hscl : (sc 2).val + 2*(sc 4).val ≤ (cp 1).val+fieldWords (cp 0).val := by
+ rw [L.scatter.target, L.scatter.total, fieldWords]; omega
+ obtain ⟨final, hret, _, hconfig, tag, cost, keep⟩ := ScatterRun.returning_outside G clock hw sc perm dense formal order
+ running hs raw (cp 1) (cp 0).val L.scatter m₂ hsrc (by simpa only [List.length_append, runtime_length] using space)
+ prepared (by simp [tagged, m₂, writeMemory]) frame₂
+ (fun j => .inr (hscl.trans (room.scatter j))) (.inl room.tagState) room.stateFit
+ change Advice.Returning G.P G.clock zeroRuntime.length 7 m₁ m₂ at hv
+ rw [hlen] at hv
+ have firstTwo := Advice.returning_append hu hv
+ refine ⟨final, Advice.returning_append firstTwo hret,
+ Advice.costLimit_append firstTwo hret
+ (Advice.costLimit_append hu hv (Advice.returning_cost hu) (Advice.returning_cost hv)) cost, hconfig, tag, ?_⟩
+ intro j ht hb
+ have hbase : (cp 1).val ≤ firstData cp := by unfold firstData; omega
+ have htarget : (cp 1).val ≤ (sc 2).val := by rw [L.scatter.target]; omega
+ exact (keep j ht (by unfold ScatterRun.Outside; omega)).trans (agree j ht (by omega))
+
+/-- Removing the unique complete suffix prefix preserves the full accepting
+continuation and its cap on the concatenated event log. -/
+noncomputable def SuffixRun.suffixEquiv {G : Group} {cp : Fin 4 → Word G.w} {raw : List Bool}
+ {formal : Fin t → Word Z} {d : ℕ} {m final : Memory G.w} (h : SuffixRun G cp raw formal d m final)
+ (cap : List (Report G.w) → Prop) :
+ ActualPaths G.P G.clock 0 final (fun rs => cap (h.returning.choose ++ rs)) ≃ ActualPaths G.P G.clock 0 m cap := by
+ have hr := h.returning.choose_spec
+ have e := emptySegmentEquiv hr.1 cap
+ rw [hr.2.1, hr.2.2.1] at e
+ exact e
+
+open Advice
+
+/-- The physical midpoint program uses the three published operand rows of
+the validated advice. Its old-state bank is the exact bounded initial code
+on the complete raw prefix and formal exponents at the last-group router. -/
+theorem suffixRun_actual (G : Group) (raw : List Bool) (m : Memory G.w)
+ (values : Fin (G.constants.labels.eval G.g) → Word (Nat.clog 2 (G.constants.labels.eval G.g)))
+ (perm : Fin (G.constants.labels.eval G.g) ≃ Fin (G.constants.labels.eval G.g))
+ (dense formal : Fin (G.constants.labels.eval G.g) → Word (G.constants.Z.eval G.g))
+ (order : ∀ i, formal (perm i) = dense i) (ordinal : ∀ i, (values i).val = (perm i).val)
+ (L : LiveEvaluatorAdviceBanks.PreparedLayout (lp G.constants G.g) (fp G.constants G.g)
+ (op G.constants G.g) raw (G.constants.labels.eval G.g) (Nat.clog 2 (G.constants.labels.eval G.g)))
+ (hlimit : (Layout.shadow G.constants).eval G.g < 2^G.w) (clock : 94 ≤ G.clock)
+ (running : G.evaluator.extra ≠ 0) (hs : G.evaluator.extra+2 ≤ 2^G.w)
+ (space : raw.length + (2*(G.constants.labels.eval G.g*G.constants.Z.eval G.g)+6*G.constants.Z.eval G.g+4) ≤
+ G.constants.radius.eval G.g+1)
+ (incoming : ∀ q : Fin (G.constants.labels.eval G.g*G.constants.Z.eval G.g),
+ m ((HeaderLayout.exponent G.constants.lengths Layout.header .left).eval G.g+q.val) =
+ PrimedInputRAM.encodeBit G.w (RAMSerialization.arrayBits _ _ dense q))
+ (control : m ((copyBank G.constants G.g) 1).val = Fin.ofNat _ (controlTag G.evaluator).val)
+ (zeros : ∀ i : Fin (fieldWords (G.constants.radius.eval G.g)), 0 < i.val →
+ m (((copyBank G.constants G.g) 1).val+i.val) = 0) :
+ ∃ final, SuffixRun G (copyBank G.constants G.g) raw formal (G.constants.labels.eval G.g)
+ (finalMemory G.constants G.g G.lit raw values m) final := by
+ let c := G.constants
+ let g := G.g
+ let cp := copyBank c g
+ let sk := skeletonBank c g raw m
+ let sc := scatterBank c g raw m
+ let base := (fp c g) 3
+ let entry := finalMemory c g G.lit raw values m
+ have R := inputRegions c g raw m L hlimit space
+ have I := inputLayout c g raw m L hlimit space
+ obtain ⟨hdc, hds, hda⟩ := suffixFrameData c g G.lit raw values m L hlimit
+ obtain ⟨hpacked, hsrc, hframe⟩ := preparedInput c g G.lit raw values m L hlimit space perm dense ordinal incoming
+ have addr (offset : ℕ) : Pieces.word g G.lit (.geometry (Layout.adviceFrames c + (.lit offset : PublicExpr))) =
+ base + (offset : Word G.w) := by
+ change (((Layout.adviceFrames c).eval g + offset : ℕ) : Word G.w) = (((Layout.adviceFrames c).eval g : ℕ) : Word G.w) + _
+ exact Nat.cast_add ..
+ have hc : G.prefixCopyBase = base + 8 := addr 8
+ have hk : G.skeletonBase = base + 13 := addr 13
+ have ha : ScatterRun.operandBase G = base + 17 := addr 17
+ have before : base.val+23 ≤ ((fp c g) 4).val := L.frameBeforePrefix
+ have hfit : base.val+22 < 2^g.w := (Nat.le_succ _).trans_lt (before.trans_lt ((fp c g) 4).isLt)
+ have words {n : ℕ} (offset : ℕ) (j : Fin n) (h : offset + n ≤ 22) :
+ base.val ≤ ((base + (offset : Word G.w)) + (j.val : Word G.w)).val := by
+ have ho : offset < 2^g.w := by have := j.isLt; omega
+ have hj : j.val < 2^g.w := by have := j.isLt; omega
+ rw [Fin.val_add, Fin.val_add, Fin.val_natCast, Fin.val_natCast, Nat.mod_eq_of_lt ho, Nat.mod_eq_of_lt hj,
+ Nat.mod_eq_of_lt (by omega : base.val+offset < 2^g.w), Nat.mod_eq_of_lt (by have := j.isLt; omega)]
+ omega
+ have ht : G.addr.val < ((fp c g) 0).val := tag_before_advice c g G.lit hlimit
+ have htin : G.addr.val < (sc 0).val := ht.trans_le R.incomingStart
+ have hts : G.addr.val < (cp 1).val := htin.trans_le ((Nat.le_add_right ..).trans R.incomingEnd)
+ have hend : (cp 1).val + fieldWords (cp 0).val ≤ base.val := by rw [show (cp 0).val = _ from R.radius]; exact R.configEnd
+ have hto : G.addr.val < (sc 1).val := by
+ change G.addr.val < ((fp c g) 10).val
+ rw [← L.ordinalDest]
+ have hb : ((fp c g) 4).val ≤ ((op c g) 1).val := (Nat.le_add_right ..).trans L.prefixBeforeOrder
+ exact hts.trans_le (((Nat.le_add_right ..).trans hend).trans (((Nat.le_add_right ..).trans before).trans hb))
+ have room : SuffixRoom G cp sc := ⟨hts, htin, hto, hend.trans base.isLt.le,
+ fun j => hc ▸ hend.trans (words 8 j (by decide)), fun j => hk ▸ hend.trans (words 13 j (by decide)),
+ fun j => ha ▸ hend.trans (words 17 j (by decide))⟩
+ have old : ∀ i : Fin (fieldWords (cp 0).val), entry ((cp 1).val+i.val) = m ((cp 1).val+i.val) :=
+ fun i => hframe ⟨i.val, by simpa only [show (cp 0).val = _ from R.radius] using i.isLt⟩
+ have hzero : ∀ i : Fin (fieldWords (cp 0).val), 0 < i.val → entry ((cp 1).val+i.val) = 0 := by
+ intro i hi
+ rw [old]
+ exact zeros ⟨i.val, by simpa only [show (cp 0).val = _ from R.radius] using i.isLt⟩ hi
+ have hctrl : entry (cp 1).val = Fin.ofNat _ (controlTag G.evaluator).val := by
+ have hz := old ⟨0, by unfold fieldWords; omega⟩
+ exact hz.trans control
+ exact G.suffixRun cp sk (stateBank c g) sc raw perm dense formal order entry clock
+ ((by decide : 2 ≤ 4).trans L.width) running hs I room (by rw [show (cp 0).val = _ from R.radius]; exact space)
+ (by change (if G.addr.val = G.addr.val then _ else _) = _; rw [ite_eq_left rfl])
+ hctrl hzero hpacked hsrc (hc ▸ hdc) (hk ▸ hds) (ha ▸ hda)
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorTransition.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorTransition.lean
new file mode 100644
index 0000000000..ab5b2adff3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorTransition.lean
@@ -0,0 +1,214 @@
+import OAI.Computability.VPVNP.LiveProgramTerminalStage
+import OAI.Computability.VPVNP.LiveEvaluatorTailCostFacts
+import OAI.Computability.VPVNP.LiveEvaluatorRAMMalformed
+
+/-!
+# The terminal transition of the linked live evaluator
+
+The initial call changes five scratch words. Each subsequent cell call
+preserves external memory. The outer stage tag therefore persists throughout
+the terminal scan, on arbitrary input words. The cap on its linked reports
+retains one dispatcher probe per call and the full cost of any preceding
+reports. Malformed raw cut fields contribute zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+
+open BurstRAM LiveStageLink LiveEvaluatorRAM
+open LiveEvaluatorRAM.Schedule (Pub nativeProgram callFuel)
+open scoped Classical Fin.CommRing
+
+variable (G : Group) {M : ℕ}
+
+/-- The four evaluated operands of the native transition check in this physical group. -/
+abbrev transitionPub : Fin 4 → Word G.w :=
+ Pieces.word G.g G.lit ∘ InputOperand.geometry ∘ StageOperands.transition G.constants
+
+private theorem transition_call_eq {w : ℕ} (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (st : Word w) (m : Memory w) (bits : List Bool) {fuel : ℕ} (hf : callFuel p ≤ fuel) :
+ let P := nativeProgram p pub
+ execute P fuel (P.start st) m bits = execute P (callFuel p) (P.start st) m bits := by
+ intro P
+ apply Option.ext
+ intro r
+ let a := Schedule.body (LiveEvaluatorRAMPrepare.prepare p)
+ have run (f : ℕ) := PrimedCounter.Call.execute_iff a 29 30 pub st
+ (fun _ => 0) (fun _ => 0) m bits f r
+ constructor
+ · intro h
+ obtain ⟨es, regs, mem, hr, _, rest⟩ := (run fuel).mp h
+ exact (run (callFuel p)).mpr ⟨es, regs, mem, hr, Nat.add_le_add_right (Schedule.program_bound p hr) 2, rest⟩
+ · intro h
+ obtain ⟨es, regs, mem, hr, ht, rest⟩ := (run (callFuel p)).mp h
+ exact (run fuel).mpr ⟨es, regs, mem, hr, ht.trans hf, rest⟩
+
+private theorem transition_segment_eq {w : ℕ} (p : UniversalMachine.Program) (pub : Pub → Word w)
+ (s : Option (Word w)) (m : Memory w) (bits : List (List Bool)) {fuel : ℕ} (hf : callFuel p ≤ fuel) :
+ runSegment (nativeProgram p pub) fuel s m bits = runSegment (nativeProgram p pub) (callFuel p) s m bits := by
+ induction bits generalizing s m with
+ | nil => rfl
+ | cons b bs ih =>
+ cases s with
+ | none => rfl
+ | some st =>
+ rw [runSegment, runSegment, transition_call_eq p pub st m b hf]
+ cases execute (nativeProgram p pub) (callFuel p) ((nativeProgram p pub).start st) m b with
+ | none => rfl
+ | some r => exact congrArg (Option.map (r :: ·)) (ih r.result (after m r.events))
+
+private theorem prepare_outside {w : ℕ} {p : UniversalMachine.Program} {pub : Pub → Word w}
+ {m mem : Memory w} {bs : List Bool} (hl : PrepLayout p pub M) (run : Prepared p pub m mem bs)
+ (k : ℕ) (hk : k < (pub 3).val ∨ (pub 3).val+5 ≤ k) : mem k = m k := by
+ rw [Prepared, Schedule.initial_choices_iff] at run
+ obtain ⟨es, reg, he, _⟩ := run
+ let rs : PrimedStackRAM.Regs w 32 := Schedule.loaded pub 0 (fun _ => 0) m
+ obtain ⟨_, _, _, s, sel, _, _, _, _, rfl⟩ :=
+ (LiveEvaluatorRAMPrepare.prepare_exec_iff p pub 0 rs m hl.width hl.states rfl rfl es reg mem).mp he
+ have h1 : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by have := hl.width; omega))
+ have hs1 : (s 1).val = 1 := (congrArg Fin.val (sel.frame 1 (by decide))).trans h1
+ have hs25 : s 25 = pub 3 := sel.frame 25 (by decide)
+ exact LiveEvaluatorRAMPrepare.scratchMemory_outside s m hs1 (hs25 ▸ hl.scratchFit) k (hs25 ▸ hk)
+
+/-- A terminal evaluator entry retains the stage tag on every returning
+native call, including arbitrary scratch contents and malformed cut fields. -/
+theorem transition_frame (hl : PrepLayout G.evaluator G.transitionPub M)
+ (hf : callFuel G.evaluator ≤ G.clockAt Stage.transition)
+ (fresh : G.addr.val < (G.transitionPub 3).val ∨ (G.transitionPub 3).val+5 ≤ G.addr.val) :
+ TagFrame G.T G.pub G.addr Stage.transition (G.clockAt Stage.transition) (fun _ _ => True) := by
+ intro st mem bs rep _ _ ht he _
+ have hx := (Pieces.component_eq G.components G.g G.lit Stage.transition
+ (G.clockAt Stage.transition) st mem bs).symm.trans he
+ let P := nativeProgram G.evaluator G.transitionPub
+ change execute P (G.clockAt Stage.transition) (P.start st) mem bs = some rep at hx
+ rw [transition_call_eq G.evaluator G.transitionPub st mem bs hf] at hx
+ refine ⟨trivial, ?_⟩
+ by_cases hz : st = 0
+ · subst st
+ obtain ⟨es, regs, mid, hb, hbits, _, _, hm⟩ := (Schedule.nativeStep_iff ..).mp hx
+ rw [hm]
+ exact (prepare_outside hl ⟨es, regs, hb, hbits⟩ G.addr.val fresh).trans ht
+ · rw [(Schedule.nativeCell_report _ _ _ _ _ _ hz hx).2.1]
+ exact ht
+
+/-- The entire outer accepting suffix at the transition tag is precisely
+the standalone evaluator segment, with the cap applied to every mapped
+dispatcher report. It accepts the same individual branch streams. -/
+noncomputable def transitionEquiv (hl : PrepLayout G.evaluator G.transitionPub M)
+ (hf : callFuel G.evaluator ≤ G.clockAt Stage.transition)
+ (fresh : G.addr.val < (G.transitionPub 3).val ∨ (G.transitionPub 3).val+5 ≤ G.addr.val)
+ (m : Memory G.w) (tag : G.tagged Stage.transition m) (cap : List (Report G.w) → Prop) :
+ ActualPaths G.P G.clock 0 m cap ≃
+ ActualPaths (nativeProgram G.evaluator G.transitionPub) (callFuel G.evaluator) 0 m
+ (fun rs => cap (rs.map (linkedReport G.nextStage G.addr Stage.transition))) := by
+ let entry : Entry G Stage.transition m := ⟨fun _ _ => True, G.transition_frame hl hf fresh, trivial, tag⟩
+ apply (terminalEquiv entry (by rfl) cap).symm.trans
+ apply Equiv.subtypeEquivRight
+ intro bits
+ change (∃ rs, runSegment (nativeProgram G.evaluator G.transitionPub) (G.clockAt Stage.transition)
+ (some 0) m bits = some rs ∧ _) ↔ _
+ rw [transition_segment_eq _ _ _ _ _ hf]
+
+/-- A terminal transition adds exactly one dispatcher probe per native report. -/
+theorem terminal_cost (rs : List (Report G.w)) :
+ RAMBuckets.cost Report.probes (rs.map (linkedReport G.nextStage G.addr Stage.transition)) =
+ RAMBuckets.cost Report.probes rs + rs.length := by
+ induction rs with
+ | nil => rfl
+ | cons r rs ih =>
+ have hp := linkedReport_probes G.nextStage G.addr Stage.transition r
+ have he : G.nextStage Stage.transition = none := rfl
+ rw [he] at hp
+ simp only [List.map_cons, RAMBuckets.cost, List.length_cons, ih]
+ simp only [Option.isSome_none, Bool.false_eq_true, and_false, ite_false, Nat.add_zero] at hp
+ omega
+
+/-- The linked terminal stage charges one dispatch read per native call,
+keeps the returned call count, and uses at most 47 additional instructions. -/
+theorem linked_transition_resources (hl : PrepLayout G.evaluator G.transitionPub M)
+ (m : Memory G.w) (bits : List (List Bool)) (rs : List (Report G.w)) {fuel : ℕ}
+ (hr : runSegment (nativeProgram G.evaluator G.transitionPub) fuel (some 0) m bits = some rs)
+ (hh : endState (some 0) rs = none) :
+ let out := rs.map (linkedReport G.nextStage G.addr Stage.transition)
+ out.length = 4*M+3 ∧ RAMBuckets.cost Report.probes out ≤ 10+14*(2*M+1)+(4*M+3) ∧
+ ∀ r ∈ out, r.probes ≤ 10 ∧ r.events.length < callFuel G.evaluator+47 := by
+ intro out
+ have hc := LiveEvaluatorTailCost.transition_cost G.evaluator G.transitionPub m bits rs M hl.radius
+ (LiveEvaluatorGroup.calls_fit hl).le hl.width hl.states hr hh
+ have replay := LiveEvaluatorTailCost.transition_at_callFuel G.evaluator G.transitionPub _ m bits rs hr
+ have hlocal := (Schedule.segmentResources G.evaluator G.transitionPub m bits rs hl.radius
+ (LiveEvaluatorGroup.calls_fit hl).le hl.width hl.states replay hh).2.2
+ refine ⟨by simpa [out] using hc.1, ?_, ?_⟩
+ · change RAMBuckets.cost Report.probes (rs.map _) ≤ _
+ rw [G.terminal_cost, hc.1]
+ exact Nat.add_le_add_right hc.2.1 _
+ · intro rep hrep
+ obtain ⟨r, h, rfl⟩ := List.mem_map.mp hrep
+ have hp := linkedReport_probes G.nextStage G.addr Stage.transition r
+ rw [show G.nextStage Stage.transition = none from rfl] at hp
+ simp only [Option.isSome_none, Bool.false_eq_true, and_false, ite_false, Nat.add_zero] at hp
+ have hlen := linkedReport_length_le G.nextStage G.addr Stage.transition r
+ have ⟨h₁,h₂⟩ := hlocal r h
+ omega
+
+/-- Global and per-call transcript caps after prefixing the exact linked
+transition reports by the already executed calls. -/
+theorem linkedTransitionFits (hl : PrepLayout G.evaluator G.transitionPub M)
+ (m : Memory G.w) (pre : List (Report G.w)) {S H : ℕ} (hcap : 11 ≤ H)
+ (preCalls : ∀ r ∈ pre, 1+r.probes ≤ H)
+ (hcost : RAMBuckets.cost Report.probes pre + (10+7*(2*(2*M+1))) + Schedule.calls M ≤ S*H)
+ (bits : List (List Bool)) (rs : List (Report G.w))
+ (hr : runSegment (nativeProgram G.evaluator G.transitionPub) (callFuel G.evaluator) (some 0) m bits = some rs)
+ (hh : endState (some 0) rs = none) :
+ withinCaps S H (pre ++ rs.map (linkedReport G.nextStage G.addr Stage.transition)) := by
+ obtain ⟨hc, hlr, hcalls⟩ := Schedule.segmentResources G.evaluator G.transitionPub m bits rs hl.radius
+ (LiveEvaluatorGroup.calls_fit hl).le hl.width hl.states hr hh
+ constructor
+ · rw [RAMBuckets.cost_append, G.terminal_cost, hlr, hc]
+ split <;> omega
+ · rw [List.forall_mem_append]
+ refine ⟨preCalls, ?_⟩
+ intro r h
+ obtain ⟨s, hs, rfl⟩ := List.mem_map.mp h
+ have hp := linkedReport_probes G.nextStage G.addr Stage.transition s
+ rw [show G.nextStage Stage.transition = none from rfl] at hp
+ simp only [Option.isSome_none, Bool.false_eq_true, and_false, ite_false, Nat.add_zero] at hp
+ have := (hcalls s hs).1
+ omega
+
+/-- Under the accumulated transcript budget the linked terminal suffix has
+the paper's exact local tail multiplicity on raw boundary fields. This also
+covers an invalid decoder output on either boundary. -/
+theorem linkedTailCount {h Δ S H : ℕ} (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w Δ)
+ (init : LiveEvaluatorEncoding.Code G.evaluator.extra M) (bits : LiveChain.TailBits h Δ) (i : Fin (2^h))
+ (m : Memory G.w) (hl : PrepLayout G.evaluator G.transitionPub M)
+ (hf : callFuel G.evaluator ≤ G.clockAt Stage.transition)
+ (fresh : G.addr.val < (G.transitionPub 3).val ∨ (G.transitionPub 3).val+5 ≤ G.addr.val)
+ (tag : G.tagged Stage.transition m)
+ (ho : ∀ c, LiveEvaluatorTail.boundary layout init bits i.castSucc = some c ↔ ConfigAt m (G.transitionPub 1) c)
+ (hz : ∀ z, LiveEvaluatorTail.boundary layout init bits i.succ = some z ↔ ConfigAt m (G.transitionPub 2) z)
+ (pre : List (Report G.w)) (hcap : 11 ≤ H) (preCalls : ∀ r ∈ pre, 1+r.probes ≤ H)
+ (hcost : RAMBuckets.cost Report.probes pre + (10+7*(2*(2*M+1))) + Schedule.calls M ≤ S*H) :
+ Nat.card (ActualPaths G.P G.clock 0 m (fun rs => withinCaps S H (pre++rs))) =
+ ChainAssignments.tailCount G.evaluator layout init bits i := by
+ rw [Nat.card_congr (G.transitionEquiv hl hf fresh m tag _)]
+ rw [LiveEvaluatorGroup.tailCount_eq_capped (S := S) (H := H) layout init bits i hl ho hz
+ (by omega) (by omega)]
+ apply Nat.card_congr
+ apply Equiv.subtypeEquivRight
+ intro bs
+ constructor
+ · rintro ⟨rs, hr, hh, _⟩
+ exact ⟨rs, hr, hh, Schedule.segmentWithinCaps _ _ _ _ _ hl.radius (LiveEvaluatorGroup.calls_fit hl).le
+ hl.width hl.states (by omega) (by omega) hr hh⟩
+ · rintro ⟨rs, hr, hh, _⟩
+ exact ⟨rs, hr, hh, G.linkedTransitionFits hl m pre hcap preCalls hcost bs rs hr hh⟩
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorTransport.lean b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorTransport.lean
new file mode 100644
index 0000000000..dc581d5b80
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLinkedEvaluatorTransport.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorGeometry
+
+/-!
+# Preservation of the outgoing physical cut during incoming preparation
+
+The last-group flag, the outgoing header configuration field, and the outgoing
+configuration bank suffice to reuse the same output data after initialization.
+The incoming gather leaves these cells unchanged by disjoint allocation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM PairStages LiveConfigGather LiveEvaluatorEncoding
+open scoped Fin.CommRing
+
+variable (G : PairStages.Group) {M : ℕ}
+
+/-- The two memories agree on the last-group flag, all outgoing configuration bits, and every
+word of the proposed output state bank. -/
+structure OutputFrame (M : ℕ) (m m' : Memory G.w) : Prop where
+ flag : m' ((Router.last.data G.g G.lit) 0).val = m ((Router.last.data G.g G.lit) 0).val
+ field (j : Fin (fieldWords M * G.w)) : m' ((cutSource G true).val+j.val) = m ((cutSource G true).val+j.val)
+ bank (i : Fin (fieldWords M)) : m' ((G.transitionPub 2).val+i.val) = m ((G.transitionPub 2).val+i.val)
+
+namespace Output
+variable {G} {m m' : Memory G.w} {b : Option (Code G.evaluator.extra M)}
+
+/-- Reuse an outgoing cut or endpoint witness in a new memory that agrees on the output frame. -/
+def transport (o : Output G m b) (frame : OutputFrame G M m m') : Output G m' b := match o with
+ | .cut F bits flag img fresh hs value => .cut F bits (frame.flag.trans flag) (fun j => (frame.field j).trans (img j)) fresh hs value
+ | .final flag zero fresh value => .final (frame.flag.trans flag) (fun j => (frame.bank j).trans (zero j)) fresh value
+
+theorem transport_logs (o : Output G m b) (frame : OutputFrame G M m m') : (o.transport frame).logs = o.logs := by
+ cases o <;> rfl
+
+end Output
+
+theorem gatherMemory_outside (F : EvaluatorGather.Fit G false (k G)) (m : Memory G.w)
+ (bits : Fin (k G * G.w) → Bool) (a : ℕ) (ht : a ≠ G.addr.val)
+ (outside : a < (G.transitionPub 1).val ∨ (G.transitionPub 1).val+k G ≤ a) :
+ gatherMemory G false F m bits a = m a := by
+ unfold gatherMemory retag
+ have hsep : a < (EvaluatorGather.operands G false 1).val ∨ (EvaluatorGather.operands G false 1).val + k G ≤ a := outside
+ rw [writeMemory, ite_eq_right ht, gathered_outside _ _ _ _ _ hsep, writeMemory, ite_eq_right ht]
+
+theorem gatheredOutputFrame (a : Addresses G) (F : EvaluatorGather.Fit G false (k G)) (m : Memory G.w)
+ (bits : Fin (k G * G.w) → Bool) : OutputFrame G (radius G) m (gatherMemory G false F m bits) := by
+ obtain ⟨l,r,e,flag,fl,o,n,s,rad,wc,kc⟩ := a
+ refine ⟨gatherMemory_outside G F m bits _ (by omega) (Or.inl (by omega)), ?_, ?_⟩
+ · intro j
+ have hj : j.val < k G * G.w := j.isLt
+ exact gatherMemory_outside G F m bits _ (by omega) (Or.inl (by omega))
+ · intro j
+ exact gatherMemory_outside G F m bits _ (by omega) (Or.inr (by omega))
+
+private theorem putMemory_outside (m : Memory G.w) (j : ℕ) (htag : j ≠ G.addr.val)
+ (hbank : j ≠ (G.transitionPub 1).val) : putMemory G false m j = m j := by
+ change writeMemory (writeMemory (writeMemory m G.addr _) (G.transitionPub 1) _) G.addr _ j = m j
+ simp only [writeMemory, ite_eq_right htag, ite_eq_right hbank]
+
+theorem putInitialFrame (a : Addresses G) (m : Memory G.w) : OutputFrame G (radius G) m (putMemory G false m) := by
+ obtain ⟨l,r,e,flag,fl,o,n,s,rad,wc,kc⟩ := a
+ have hk : 0 < k G := by dsimp [k,fieldWords]; omega
+ refine ⟨putMemory_outside G m _ (by omega) (by omega), ?_, ?_⟩
+ · intro j
+ have hj : j.val < k G*G.w := j.isLt
+ exact putMemory_outside G m _ (by omega) (by omega)
+ · intro j
+ exact putMemory_outside G m _ (by omega) (by omega)
+
+/-- An empty evaluator starts in its canonical accepting state, and the
+first router skips all input-tape preparation. -/
+theorem empty_initial_image (m : Memory G.w) (empty : G.evaluator.extra = 0)
+ (fit : GeometryFit G M) (zero : ∀ j : Fin (fieldWords M), m ((G.transitionPub 1).val+j.val) = 0)
+ (c : Code G.evaluator.extra M) : LiveEvaluatorRAM.ConfigAt (putMemory G false m) (G.transitionPub 1) c ↔
+ c = .accepted := by
+ have hf := fit.prep.oldFit
+ rw [← LiveEvaluatorGroup.fieldWords_eq_calls] at hf
+ have ht : EvaluatorSentinel.tag G false = 1 := by simp [EvaluatorSentinel.tag, LiveEvaluatorInitialize.controlTag, empty]
+ apply configAt_eq_iff G fit.prep.width fit.prep.states _ c
+ apply LiveEvaluatorRAM.configAt_of_words fit.prep.width fit.prep.states .accepted
+ intro j
+ have hindex : (G.transitionPub 1 + (j.val : Word G.w)).val = (G.transitionPub 1).val+j.val := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt (by have := j.isLt; omega)]
+ rw [hindex]
+ unfold putMemory EvaluatorSentinel.transferred EvaluatorSentinel.put retag
+ have fresh (i : Fin (fieldWords M)) : (G.transitionPub 1).val+i.val ≠ G.addr.val := by
+ have := fit.oldTag; have := i.isLt; omega
+ rw [writeMemory, ite_eq_right (fresh j), ht, show EvaluatorSentinel.operands G false 1 = G.transitionPub 1 from rfl]
+ apply LiveEvaluatorInitialize.final_stores fit.prep.width fit.prep.states (G.transitionPub 1) _ _ j
+ intro i
+ rw [writeMemory, ite_eq_right (fresh i), zero]
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLocalCountConditions.lean b/lean/OAI/Computability/VPVNP/LiveLocalCountConditions.lean
new file mode 100644
index 0000000000..37c755f914
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLocalCountConditions.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.LiveLocalGroupCount
+import OAI.Computability.VPVNP.LiveProgramPaperParameters
+import OAI.Computability.VPVNP.PaperPairParameters
+import OAI.Computability.VPVNP.LiveHeaderResources
+
+/-!
+# Numeric bounds for the native local group count
+
+Section 9 chooses the cut, evaluator-space and advice powers before the
+processor exponent. The same choice made by `paper_parameters` supplies all
+word, header and cost bounds needed for `LocalCount.group`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.LocalCount
+open Filter LiveHeaderSchedule LiveEvaluatorEncoding PairStages CursorBounds
+
+private theorem header_le_shadow (c : Constants) (g : Geometry) :
+ LiveHeaderSchedule.limit (c.lengths.eval g) (2^g.d+1) ≤ (Layout.shadow c).eval g := by
+ change (Layout.descriptor c).eval g ≤ _
+ simp only [Layout.shadow,Layout.orderMap,Layout.packedPrefix,Layout.adviceFrames,Layout.transitionScratch,
+ Layout.newState,Layout.oldState,Layout.counter,eval_add]
+ omega
+
+/-- Direct adapter for any choice of the public powers and processor exponent
+satisfying the size bounds of `paper_parameters`. -/
+theorem conditions_of_majorant (G : Group) (word : 5 ≤ G.g.w) (bucket : 11 ≤ G.g.H) (clock : 154 ≤ G.clock)
+ (fit : 1 + G.constants.labels.eval G.g * G.constants.Z.eval G.g ≤ G.g.n^G.constants.deltaPower)
+ (layout : LiveEvaluatorTail.Layout G.evaluator.extra (G.g.n^G.constants.radiusPower) G.g.w (G.g.n^G.constants.deltaPower))
+ (width : G.g.w ≤ G.g.n) (major : OutsideBudget.majorant G.constants G.g.n < 2^G.g.d)
+ (shadow : (Layout.shadow G.constants).eval G.g < 2^G.g.w) :
+ Conditions G (2^G.g.d) G.g.H := by
+ let s := profile G
+ have he : 1+s.e ≤ s.delta := by simpa only [s,profile,Header.sizes,Lengths.eval,Constants.lengths,
+ PublicExpr.eval_natPow,eval_mul,PublicExpr.eval] using fit
+ have hf : 1+s.config ≤ s.delta := by
+ simpa only [s,profile,Header.sizes,Lengths.eval,Constants.lengths,Constants.configWords,Constants.radius,
+ PublicExpr.eval_natPow,eval_mul,eval_add,eval_numeral,PublicExpr.eval,fieldWords] using layout.cutWidth
+ have hbound := OutsideBudget.actual_le G.constants G.g 0 false false true width (Nat.zero_le _)
+ have hcost : costBound s+3 ≤ 2^G.g.d := by
+ have h := hbound.trans_lt major
+ change costBound s+8+_+100+_+_+_ < _ at h
+ omega
+ have hfields := field_le_cost s
+ have tagfit : stages.length ≤ 2^G.g.w := by
+ exact (by decide : stages.length ≤ 2^5).trans (Nat.pow_le_pow_right (by decide) word)
+ refine ⟨by omega,clock,⟨(header_le_shadow G.constants G.g).trans_lt shadow,?_,?_,he,hf⟩,
+ ?_,?_,tagfit,?_,bucket⟩
+ · change 2^G.g.d ≤ 2^G.g.d+1; omega
+ · change (s.h+1)*s.delta ≤ 2^G.g.d; omega
+ · change s.h+2 ≤ 2^G.g.d; omega
+ · change s.advice ≤ 2^G.g.d; omega
+ · exact hcost.trans (Nat.le_mul_of_pos_right _ (by omega))
+
+/-- The fixed instruction clock and live bucket meet the two constant lower
+bounds simultaneously at every sufficiently large length. -/
+theorem eventually_conditions_adapter {C₂ : ℕ} (u : CursorNetwork.PairExponents C₂) (c : Constants) (B : ℕ) :
+ ∀ᶠ n : ℕ in atTop, let g := paperGeometry B (liveCapacity u) n
+ ∀ G : Group, G.constants = c → G.g = g → n^10000 ≤ G.clock →
+ 1 + c.labels.eval g * c.Z.eval g ≤ n^c.deltaPower →
+ LiveEvaluatorTail.Layout G.evaluator.extra (n^c.radiusPower) g.w (n^c.deltaPower) →
+ g.w ≤ n → OutsideBudget.majorant c n < processorCount B n →
+ (Layout.shadow c).eval g < 2^g.w → Conditions G (processorCount B n) (liveCapacity u n) := by
+ filter_upwards [eventually_liveCapacity_ge u 11,eventually_ge_atTop 154] with n bucket hn
+ dsimp only
+ intro G constants geometry hclock fit layout width major shadow
+ have w : 5 ≤ (paperGeometry B (liveCapacity u) n).w :=
+ (by decide : 5 ≤ 10^4).trans (Nat.pow_le_pow_left (Nat.le_add_left 10 (addressBits B n)) 4)
+ have hp : n ≤ n^10000 := by
+ simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0 < n) (by decide : 1 ≤ 10000)
+ have cfit := hn.trans (hp.trans hclock)
+ have gR : 2^G.g.d = processorCount B n := by rw [geometry]; rfl
+ have gH : G.g.H = liveCapacity u n := by rw [geometry]; rfl
+ rw [← gR,← gH]
+ apply conditions_of_majorant G (geometry ▸ w) (gH ▸ bucket) cfit
+ · rw [constants,geometry]; exact fit
+ · rw [constants,geometry]; exact layout
+ · rw [geometry]; exact width
+ · rw [constants,geometry]; exact major
+ · rw [constants,geometry]; exact shadow
+
+/-- Select all length powers before the processor exponent and obtain the
+actual local-count conditions at all sufficiently large lengths. -/
+theorem eventually_paper_conditions {C₂ : ℕ} (u : CursorNetwork.PairExponents C₂) (C motif : ℕ)
+ {P rawLength : ℕ → ℕ} (radius : ℕ → ℕ → ℕ) (hP : PolynomiallyBounded P)
+ (hraw : PolynomiallyBounded rawLength) (hr : ∀ a, PolynomiallyBounded (fun n => radius n (2*n^a)))
+ (E : UniversalMachine.Program) :
+ ∃ a dA d₁ d₂ r B₀ : ℕ, 2 ≤ a ∧ 1 ≤ B₀ ∧ ∀ k B : ℕ, B₀ ≤ B → ∀ᶠ n : ℕ in atTop,
+ let c : Constants := ⟨C,a,d₁,d₂,r,dA,motif⟩
+ let g := paperGeometry B (liveCapacity u) n
+ 2^(P n)*(2*n^a+1)^k ≤ 2^(n^a-1) ∧ radius n (2*n^a) ≤ n^r ∧ rawLength n ≤ n^dA ∧
+ g.w+n^dA+c.labels.eval g*Nat.clog 2 (c.labels.eval g) ≤ n^d₁ ∧
+ 1+c.labels.eval g*(2*n^a) ≤ n^d₂ ∧ LiveEvaluatorTail.Layout E.extra (n^r) g.w (n^d₂) ∧
+ (∀ G : Group, G.constants = c → G.g = g → G.evaluator = E → n^10000 ≤ G.clock →
+ Conditions G (processorCount B n) (liveCapacity u n)) := by
+ obtain ⟨a,dA,d₁,d₂,r,B₀,ha,hB₀,all⟩ := paper_parameters C motif radius hP hraw (liveCapacity_polynomial u) hr E
+ refine ⟨a,dA,d₁,d₂,r,B₀,ha,hB₀,fun k B hB => ?_⟩
+ let c : Constants := ⟨C,a,d₁,d₂,r,dA,motif⟩
+ filter_upwards [all k B hB,eventually_conditions_adapter u c B] with n pp adapter
+ obtain ⟨time,space,raw,advice,field,layout,major,width,_,shadow,_⟩ := pp
+ refine ⟨time,space,raw,advice,field,layout,fun G constants geometry evaluator clock => ?_⟩
+ apply adapter G constants geometry clock
+ · simpa only [c,Constants.Z,Constants.height,eval_mul,eval_numeral,PublicExpr.eval_natPow,paperGeometry,PublicExpr.eval] using field
+ · rw [evaluator]; exact layout
+ · exact width
+ · exact major
+ · exact shadow
+
+end LiveProgram.LocalCount
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveLocalGroupCount.lean b/lean/OAI/Computability/VPVNP/LiveLocalGroupCount.lean
new file mode 100644
index 0000000000..5ac7672761
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveLocalGroupCount.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.LivePhysicalRoutes
+import OAI.Computability.VPVNP.LivePhysicalUnit
+import OAI.Computability.VPVNP.LiveActiveGroupCounts
+
+/-!
+# Assembling the native local count on every physical cut assignment
+
+Only the two active continuations enter the assembly. They start in the real
+post-header memory at the corresponding native stage. The unit branch, mixed
+modes, malformed padding and the incoming-cut condition are discharged here.
+The cap on each continuation includes the actual preceding header and router
+reports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.LocalCount
+open BurstRAM LiveHeaderSchedule LiveHeaderProgram LiveHeader ChainAssignments
+open ExponentTrace LiveChain LiveEvaluatorEncoding PairStages
+open scoped Classical
+
+/-- The evaluated live-header sizes governing this group's cuts and advice. -/
+abbrev profile (G : Group) := Header.sizes G.constants G.g
+
+/-- Physical address, clock and bucket bounds needed by the checked header. -/
+structure Conditions (G : Group) (S H : ℕ) : Prop where
+ word : 4 ≤ G.g.w
+ clock : 154 ≤ G.clock
+ bounds : Fields.Bounds (profile G) (Header.base G.g) G.g.d G.g.w
+ indices : (profile G).h+2 ≤ 2^G.g.d
+ advice : (profile G).advice ≤ 2^G.g.d
+ tags : stages.length ≤ 2^G.g.w
+ cost : costBound (profile G)+3 ≤ S*H
+ call : 11 ≤ H
+
+variable {G : Group} {S H t Z M : ℕ} {Nom : Type*} [Fintype Nom]
+variable {Path : Exterior (profile G).h (profile G).delta → Fin (2^(profile G).h) → Nom → Type*}
+variable [∀ ξ i μ, Fintype (Path ξ i μ)]
+
+/-- State of the checked physical prefix from which a pair or tail routine
+actually starts. The same object gives the accumulated report cap and tag. -/
+abbrev Prepared (W : Conditions G S H) (adv : CutSchedule.Bits (profile G).advice)
+ (cuts : AllCuts (profile G).h (profile G).delta) (j : Fin (2^((profile G).h+1))) (mode : Header.ActiveMode) :=
+ Header.PrefixTrace G (physicalMemory (d := G.g.d) W.word adv cuts j) mode.stage
+ (callBound (profile G)+1) (costBound (profile G)+4)
+
+/-- The actual continuation memory obtained by replaying the prepared header reports on the
+distributed input. -/
+abbrev memory {W : Conditions G S H} {adv : CutSchedule.Bits (profile G).advice}
+ {cuts : AllCuts (profile G).h (profile G).delta} {j : Fin (2^((profile G).h+1))}
+ {mode : Header.ActiveMode} (tr : Prepared W adv cuts j mode) :=
+ after (physicalMemory (d := G.g.d) W.word adv cuts j) (eventLog tr.logs)
+
+/-- Accepted continuations from the prepared memory whose reports fit the caps together with
+the preceding header reports. -/
+abbrev remaining {W : Conditions G S H} {adv : CutSchedule.Bits (profile G).advice}
+ {cuts : AllCuts (profile G).h (profile G).delta} {j : Fin (2^((profile G).h+1))}
+ {mode : Header.ActiveMode} (tr : Prepared W adv cuts j mode) :=
+ ActualPaths G.P G.clock 0 (memory tr) (fun rs => withinCaps S H (tr.logs++rs))
+
+/-- The first-half proof obligation after mode and padding validation. -/
+def PairContinuation (W : Conditions G S H) (adv : CutSchedule.Bits (profile G).advice)
+ (fit : 1+t*Z ≤ (profile G).delta) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ) : Prop :=
+ ∀ (cuts : AllCuts (profile G).h (profile G).delta) (i : Fin (2^(profile G).h)),
+ let j := halves (profile G).h (.inl i)
+ physicalTag cuts j = some .pair → (∀ side, Fields.ValidPadding (profile G) cuts j .pair side) →
+ ∀ tr : Prepared W adv cuts j .pair,
+ Output (profile G) (Header.base G.g) G.g.d W.word adv cuts j .pair (memory tr) →
+ Nat.card (remaining tr) = pairCount fit inc (liveCutEquiv (profile G).h (profile G).delta cuts).1 i
+
+/-- The second-half proof obligation, including a possible malformed
+incoming configuration and the final group's accepting endpoint. -/
+def TailContinuation (W : Conditions G S H) (adv : CutSchedule.Bits (profile G).advice)
+ (fit : 1+t*Z ≤ (profile G).delta)
+ (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w (profile G).delta)
+ (init : (Fin t → ℕ) → Code G.evaluator.extra M) : Prop :=
+ ∀ (cuts : AllCuts (profile G).h (profile G).delta) (i : Fin (2^(profile G).h)),
+ let j := halves (profile G).h (.inr i)
+ let b := liveCutEquiv (profile G).h (profile G).delta cuts
+ physicalTag cuts j = some .tail → (∀ side, Fields.ValidPadding (profile G) cuts j .tail side) →
+ ∀ tr : Prepared W adv cuts j .tail,
+ Output (profile G) (Header.base G.g) G.g.d W.word adv cuts j .tail (memory tr) →
+ Nat.card (remaining tr) = tailCount G.evaluator layout (init (fun a => (counters fit b.1 (Fin.last _) a).val)) b.2 i
+
+variable (W : Conditions G S H) (adv : CutSchedule.Bits (profile G).advice)
+variable (fit : 1+t*Z ≤ (profile G).delta) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+variable (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w (profile G).delta)
+variable (init : (Fin t → ℕ) → Code G.evaluator.extra M)
+variable (he : (profile G).e = t*Z) (hc : (profile G).config = fieldWords M*G.w)
+include he hc
+
+private theorem active (cuts : AllCuts (profile G).h (profile G).delta) (j : Fin (2^((profile G).h+1)))
+ (mode : Header.ActiveMode) (sel : physicalTag cuts j = some mode.tag)
+ (body : (∀ side, Fields.ValidPadding (profile G) cuts j mode.tag side) →
+ ∀ tr : Prepared W adv cuts j mode,
+ Output (profile G) (Header.base G.g) G.g.d W.word adv cuts j mode.tag (memory tr) →
+ Nat.card (remaining tr) = groupEvaluation fit inc G.evaluator layout init cuts j) :
+ Nat.card (ActualPaths (machine G.constants G.evaluator G.pair G.g G.lit).program G.clock 0
+ (physicalMemory (d := G.g.d) W.word adv cuts j) (withinCaps S H)) =
+ specifiedGroupCount fit inc G.evaluator layout init cuts j := by
+ by_cases good : ∀ side, Fields.ValidPadding (profile G) cuts j mode.tag side
+ · obtain ⟨tr,out⟩ := Header.active_prefix G W.word W.clock adv cuts j W.bounds W.indices W.advice W.tags mode sel good
+ rw [Fields.specified_eq_evaluation (tag := mode.tag) (by cases mode <;> decide) he fit inc layout init cuts j sel (good .left)]
+ rw [← G.program_eq]
+ exact (Nat.card_congr (tr.equiv (withinCaps S H)).symm).trans (body good tr out)
+ · have invalid : ¬ ∃ tag, physicalTag cuts j = some tag ∧ ∀ side, Fields.ValidPadding (profile G) cuts j tag side := by
+ rintro ⟨tag,hs,hv⟩
+ rw [sel] at hs
+ obtain rfl := Option.some.inj hs
+ exact good hv
+ rw [UnitGroup.physical_card_zero G W.word W.clock adv cuts j W.bounds W.indices W.advice W.tags invalid]
+ by_contra bad
+ exact good (Fields.specifiedGroupCount_ne_zero_valid he hc fit inc G.evaluator layout init sel (Ne.symm bad))
+
+/-- The exact `group` conclusion used in `FixedModelDiagonal.LocalCertificate`
+for the real instruction table, start word zero, physical memory, and native
+report caps. The supplied components are confined to their valid active routes. -/
+theorem group (pair : PairContinuation (Path := Path) W adv fit inc)
+ (tail : TailContinuation W adv fit layout init)
+ (cuts : AllCuts (profile G).h (profile G).delta) (j : Fin (2^((profile G).h+1))) :
+ Nat.card (ActualPaths (machine G.constants G.evaluator G.pair G.g G.lit).program G.clock 0
+ (physicalMemory (d := G.g.d) W.word adv cuts j) (withinCaps S H)) =
+ specifiedGroupCount fit inc G.evaluator layout init cuts j := by
+ have hd : 0 < (profile G).delta := by omega
+ by_cases ev : evalCutMode cuts j.castSucc ∧ evalCutMode cuts j.succ
+ · rcases (halves (profile G).h).surjective j with ⟨i,rfl⟩
+ cases i with
+ | inl i =>
+ have hs := (physicalTag_pair hd cuts (halves (profile G).h (.inl i))).2 ⟨ev,i.isLt⟩
+ apply active W adv fit inc layout init he hc cuts _ .pair hs
+ intro pads tr out
+ simpa only [groupEvaluation,Equiv.symm_apply_apply,Sum.elim_inl] using pair cuts i hs pads tr out
+ | inr i =>
+ have hhalf : 2^(profile G).h < (halves (profile G).h (.inr i)).val+1 := by
+ change 2^(profile G).h < 2^(profile G).h+i.val+1; omega
+ have hs := (physicalTag_tail hd cuts (halves (profile G).h (.inr i))).2 ⟨ev,hhalf⟩
+ apply active W adv fit inc layout init he hc cuts _ .tail hs
+ intro pads tr out
+ simpa only [groupEvaluation,Equiv.symm_apply_apply,Sum.elim_inr] using tail cuts i hs pads tr out
+ · rw [UnitGroup.physical_unitGroupCount G W.word W.clock adv cuts j W.bounds W.indices W.advice W.tags W.cost W.call ev]
+ simp [specifiedGroupCount,← and_assoc,ev]
+
+end LiveProgram.LocalCount
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveModes.lean b/lean/OAI/Computability/VPVNP/LiveModes.lean
new file mode 100644
index 0000000000..645623b5bb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveModes.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.EvaluatorTail
+import OAI.Computability.VPVNP.ExponentTrace
+import OAI.Computability.VPVNP.Diagonal
+
+/-!
+# First-half and tail paths in the live chain
+
+For fixed primed exterior bits, nominations, and pair paths, each first-half
+group checks its incoming and outgoing counters. The middle cut initializes
+the evaluator. Each tail group checks a single transition and the uniquely
+encoded outgoing configuration. Forgetting these forced fields leaves just
+one accepting path of the evaluator on the full sum of the exponents.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveChain
+
+open CutSchedule ExponentTrace UniversalMachine
+
+variable {h Δ t Z csize : ℕ}
+
+/-- There are `2^h - 1` cuts strictly after the midpoint and before the final
+endpoint. On each of these the tail sends an evaluator configuration. -/
+abbrev TailBits (h Δ : ℕ) :=
+ (j : Fin (2 ^ h - 1)) → Bits (width (h + 1) Δ (2 ^ h + (j.val + 1)))
+
+private def layout (hfit : 1 + csize ≤ Δ) (j : Fin (2 ^ h - 1)) :=
+ tailLayout h Δ (2 ^ h + (j.val + 1)) csize (by omega)
+ (by rw [pow_succ]; have := j.isLt; omega) hfit
+
+private def timeAfter (j : Fin (2 ^ h - 1)) : Fin (2 ^ h + 1) :=
+ ⟨j.val + 1, by have := j.isLt; omega⟩
+
+/-- Every outgoing tail cut encodes the configuration reached after the
+corresponding transition and contains only zero padding. -/
+def TailValid (hfit : 1 + csize ≤ Δ) (E : Program) (encode : EvaluatorTail.State E.extra → Bits csize)
+ (states : Fin (2 ^ h + 1) → EvaluatorTail.State E.extra) (bits : TailBits h Δ) : Prop :=
+ ∀ j, layout hfit j (bits j) = (true, encode (states (timeAfter j)), fun _ => false)
+
+theorem tailBits_unique (hfit : 1 + csize ≤ Δ) (E : Program)
+ (encode : EvaluatorTail.State E.extra → Bits csize)
+ (states : Fin (2 ^ h + 1) → EvaluatorTail.State E.extra) :
+ ∃! bits, TailValid hfit E encode states bits := by
+ refine ⟨fun j => (layout hfit j).symm (true, encode (states (timeAfter j)), fun _ => false),
+ fun j => (layout hfit j).apply_symm_apply _, ?_⟩
+ intro bits hb
+ exact funext fun j => (layout hfit j).eq_symm_apply.mpr (hb j)
+
+/-- One set of local paths with their constrained first-half bit fields,
+their branch-distinguished tail history, and their serialized tail cuts. -/
+abbrev LocalRun (hfit : 1 + t * Z ≤ Δ) (hconfig : 1 + csize ≤ Δ)
+ (ξ : Exterior h Δ) (inc : Fin (2 ^ h) → Fin t → ℕ) (E : Program)
+ (initial : (Fin t → ℕ) → Config E.extra) (encode : EvaluatorTail.State E.extra → Bits csize) :=
+ (live : {bits : LiveBits h Δ // Valid hfit ξ inc bits}) ×
+ (trace : EvaluatorTail.Traces E (2 ^ h)
+ (initial (fun a => (counters hfit live.val (Fin.last (2 ^ h)) a).val))) ×
+ {bits : TailBits h Δ // TailValid hconfig E encode trace.2.val bits}
+
+/-- A fixed collection of pair choices has one canonically filled first half,
+then exactly as many completions as the evaluator has accepting paths. -/
+noncomputable def localRunEquiv (hfit : 1 + t * Z ≤ Δ) (hconfig : 1 + csize ≤ Δ)
+ (ξ : Exterior h Δ) (inc : Fin (2 ^ h) → Fin t → ℕ)
+ (hbound : ∀ (i : Fin (2 ^ h)) a, partialSum inc i.succ a < 2 ^ Z) (E : Program)
+ (initial : (Fin t → ℕ) → Config E.extra) (encode : EvaluatorTail.State E.extra → Bits csize) :
+ LocalRun hfit hconfig ξ inc E initial encode ≃
+ Fin (paths E (2 ^ h) (initial (fun a => ∑ i, inc i a))) := by
+ let first := {bits : LiveBits h Δ // Valid hfit ξ inc bits}
+ let liveDefault : Unique first := ((unique_subtype_iff_existsUnique _).mpr (existsUnique_live hfit ξ inc hbound)).some
+ let initialAt (live : first) := initial (fun a => (counters hfit live.val (Fin.last (2 ^ h)) a).val)
+ let hist (live : first) := EvaluatorTail.Traces E (2 ^ h) (initialAt live)
+ let tail (live : first) (tr : hist live) := {bits : TailBits h Δ //
+ TailValid hconfig E encode tr.2.val bits}
+ let tailDefault (live : first) (tr : hist live) : Unique (tail live tr) :=
+ ((unique_subtype_iff_existsUnique _).mpr (tailBits_unique hconfig E encode tr.2.val)).some
+ let initialConfig := initial (fun a => ∑ i, inc i a)
+ have init_eq (live : first) : initialAt live = initialConfig :=
+ congrArg initial (funext (middle_counters hfit ξ inc live.val live.property))
+ let stripTail (live : first) : ((tr : hist live) × tail live tr) ≃ hist live :=
+ Equiv.sigmaUnique _ _
+ let stripFirst : ((live : first) × hist live) ≃ hist (default : first) := Equiv.uniqueSigma _
+ let tailPaths := EvaluatorTail.tracesEquiv E (2 ^ h) initialConfig
+ let choices := {w : Fin (2 ^ h) → Bool // acceptsChoices E (2 ^ h) initialConfig w}
+ have hc : Fintype.card choices = paths E (2 ^ h) initialConfig := by
+ rw [paths_eq_card_choices, Fintype.card_subtype]
+ let last : hist (default : first) ≃ Fin (paths E (2 ^ h) initialConfig) :=
+ (Equiv.cast (congrArg (EvaluatorTail.Traces E (2 ^ h)) (init_eq default))).trans
+ (tailPaths.symm.trans (Fintype.equivFinOfCardEq hc))
+ exact ((Equiv.sigmaCongrRight stripTail).trans stripFirst).trans last
+
+/-- Applying the local path bijection at every nomination gives the exact
+two-mode path type of Proposition 9.1. -/
+noncomputable def liveModesEquiv {Nom : Type*} {Path : Exterior h Δ → Fin (2 ^ h) → Nom → Type*}
+ (hfit : 1 + t * Z ≤ Δ) (hconfig : 1 + csize ≤ Δ) (E : Program)
+ (initial : (Fin t → ℕ) → Config E.extra) (encode : EvaluatorTail.State E.extra → Bits csize)
+ (inc : ∀ ξ (μ : Fin (2 ^ h) → Nom), ((i : Fin (2 ^ h)) → Path ξ i (μ i)) →
+ Fin (2 ^ h) → Fin t → ℕ)
+ (hbound : ∀ ξ μ q (i : Fin (2 ^ h)) a, partialSum (inc ξ μ q) i.succ a < 2 ^ Z) :
+ (Unit ⊕ ((ξ : Exterior h Δ) × (μ : Fin (2 ^ h) → Nom) ×
+ (q : (i : Fin (2 ^ h)) → Path ξ i (μ i)) ×
+ LocalRun hfit hconfig ξ (inc ξ μ q) E initial encode)) ≃
+ Diagonal.LiveModes (fun ξ μ q => paths E (2 ^ h) (initial (fun a => ∑ i, inc ξ μ q i a))) :=
+ (Equiv.refl Unit).sumCongr <| Equiv.sigmaCongrRight fun ξ => Equiv.sigmaCongrRight fun μ =>
+ Equiv.sigmaCongrRight fun q =>
+ localRunEquiv hfit hconfig ξ (inc ξ μ q) (hbound ξ μ q) E initial encode
+
+end LiveChain
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveNativePairContinuation.lean b/lean/OAI/Computability/VPVNP/LiveNativePairContinuation.lean
new file mode 100644
index 0000000000..a232b68507
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveNativePairContinuation.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.LivePairStageConditions
+import OAI.Computability.VPVNP.LiveOutsidePreparedPair
+import OAI.Computability.VPVNP.LiveProgramPairNominationOrder
+import OAI.Computability.VPVNP.LiveLocalGroupCount
+
+/-!
+# From a native compressed pair call to the physical first-half continuation
+
+The prefix in the cap already contains the mode-router report. We add the
+actual nomination, initialization, copy and exponent reports exactly once.
+Reindexing the nomination sum puts the resulting local count in the order of
+the formal productions. The remaining native call obligation concerns only
+the compressed computation at its actual input and output addresses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.LocalCount
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink LiveExponent LiveHeaderProgram PairStages PairStages.Group
+open ChainAssignments CutSchedule ExponentTrace LiveHeader
+open scoped Classical
+
+variable {G : Group} {S H : ℕ}
+
+private theorem joinedCap {m : Memory G.w} {i : Fin (2^(profile G).h)}
+ {hdr : PrimedInputRAM.Header (Auxiliary.pairLengths G i) → Bool} (fit : PairStageConditions G S H)
+ (pre : List (Report G.w)) (preCost : RAMBuckets.cost Report.probes pre ≤ LiveHeaderSchedule.costBound (profile G)+4)
+ (preCalls : ∀ r ∈ pre, r.probes ≤ 10) (tag : G.tagged Stage.nominations m)
+ (μ : Nominations.Nom G) (F : Nominations.Fits G)
+ (B : Auxiliary.PreparedBranch G m i hdr (Nominations.indexed G F m tag) μ)
+ {X : Type*} (A : Indexed G Stage.pair (B.copy.memory ()) X) (q : X)
+ (hcost : RAMBuckets.cost Report.probes (A.logs q) ≤ S*(H-1)) (hcalls : ∀ r ∈ A.logs q, 1+r.probes ≤ H) :
+ withinCaps S H (pre ++ ((Nominations.indexed G F m tag).logs μ ++
+ (B.init.logs () ++ (B.copy.logs () ++ A.logs q))) ++
+ (stageReports G.exponentPub (labelCount G) (expWidth G) (A.memory q)).map
+ (linkedReport G.nextStage G.addr Stage.exponents)) := by
+ obtain ⟨nom,init,copy⟩ := OutsideBudget.prepared_resources G i F m tag μ B (fit.room i) (by have := fit.copy; omega)
+ have exp := OutsideBudget.exponent_resources G (labelCount G) (expWidth G) (A.memory q)
+ have rout := fit.cost
+ have bucket := fit.bucket
+ constructor
+ · simp only [RAMBuckets.cost_append]
+ have hc : LiveHeaderSchedule.costBound (profile G)+4 + (4*(labelCount G+1) +
+ (100 + 16*(OutsideBudget.auxWords (profile G) (labelCount G)+1))) + 7*(labelCount G*expWidth G+1) ≤ S := by
+ unfold OutsideBudget.actualBound at rout
+ change LiveHeaderSchedule.costBound (profile G) + 8 + 4*(labelCount G+1) + 100 +
+ 16*(OutsideBudget.auxWords (profile G) (labelCount G)+1) + 7*(labelCount G*expWidth G+1) + _ ≤ S at rout
+ omega
+ have heq : S+S*(H-1) = S*H := by rw [Nat.add_comm S,← Nat.mul_succ,show (H-1).succ=H by omega]
+ have hn := nom.cost
+ have hi := init.cost
+ have hp := copy.cost
+ have he := exp.cost
+ change _ ≤ 4*(labelCount G+1) at hn
+ change _ ≤ 16*(OutsideBudget.auxWords (profile G) (labelCount G)+1) at hp
+ rw [← heq]
+ omega
+ · intro r h
+ simp only [List.mem_append] at h
+ rcases h with h | h
+ · rcases h with h | h
+ · have := preCalls r h; omega
+ · rcases h with h | h | h | h
+ · exact (nom.calls r h).trans (by omega)
+ · exact (init.calls r h).trans bucket
+ · exact (copy.calls r h).trans (by omega)
+ · exact hcalls r h
+ · exact (exp.calls r h).trans (by omega)
+
+variable {Nom : Type*} [Fintype Nom]
+ {Path : Exterior (profile G).h (profile G).delta → Fin (2^(profile G).h) → Nom → Type*}
+ [finitePaths : ∀ ξ i μ, Fintype (Path ξ i μ)]
+
+/-- Reindex the exact count of local paths by an equivalence of the two
+nomination formats, carrying each nomination's dependent path space with it. -/
+private theorem pairCount_equiv (order : Nominations.Nom G ≃ Nom)
+ (fit : 1+labelCount G*expWidth G ≤ (profile G).delta)
+ (inc : ∀ ξ i μ, Path ξ i μ → Fin (labelCount G) → ℕ)
+ (first : LiveBits (profile G).h (profile G).delta) (i : Fin (2^(profile G).h)) :
+ pairCount fit (fun ξ j μ => inc ξ j (order μ)) first i = pairCount fit inc first i := by
+ unfold pairCount
+ let ξ := exteriorOf fit first
+ exact order.sum_comp (fun μ : Nom => ∑ q : Path ξ i μ, if firstCheck fit first ξ i (inc ξ i μ q) then 1 else 0)
+
+/-- Native compressed calls at the physical inputs built for this prefix.
+Each accepted local stream corresponds to one path of the formal witness.
+The `PairCall` reads back the counters in dense order and preserves the
+header buffers. Its two budget conditions account for the linked reports
+of the compressed call alone. -/
+def CompressedCalls (W : Conditions G S H) (P : PairStageConditions G S H) (order : Nominations.Nom G ≃ Nom)
+ (adv : Bits (profile G).advice) (fit : 1+labelCount G*expWidth G ≤ (profile G).delta)
+ (inc : ∀ ξ i μ, Path ξ i μ → Fin (labelCount G) → ℕ) : Prop :=
+ ∀ (cuts : AllCuts (profile G).h (profile G).delta) (i : Fin (2^(profile G).h)),
+ let j := halves (profile G).h (.inl i)
+ physicalTag cuts j = some .pair → (∀ side, Fields.ValidPadding (profile G) cuts j .pair side) →
+ ∀ tr : Prepared W adv cuts j .pair, Output (profile G) (Header.base G.g) G.g.d W.word adv cuts j .pair (memory tr) →
+ let ξ := exteriorOf fit (fst cuts)
+ let F := Auxiliary.nominationFits G i (P.room i) P.width.le P.nominations
+ let N := Nominations.indexed G F (memory tr) tr.tag
+ ∀ μ, ∀ B : Auxiliary.PreparedBranch G (memory tr) i (PairedChain.headers adv ξ i) N μ,
+ ∃ C : PairCall B (Path ξ i (order μ)) (inc ξ i (order μ)), ∀ q,
+ RAMBuckets.cost Report.probes (C.indexed.logs q) ≤ S*(H-1) ∧ ∀ r ∈ C.indexed.logs q, 1+r.probes ≤ H
+
+/-- The physical post-header first-half count from local compressed-call
+semantics, the public scalar fits, and the witness's counter bound. -/
+theorem pairContinuation_of_compressed (W : Conditions G S H) (P : PairStageConditions G S H)
+ (order : Nominations.Nom G ≃ Nom) (adv : Bits (profile G).advice)
+ (fit : 1+labelCount G*expWidth G ≤ (profile G).delta) (inc : ∀ ξ i μ, Path ξ i μ → Fin (labelCount G) → ℕ)
+ (small : ∀ ξ i μ q a, inc ξ i μ q a < 2^(2*G.g.d)) (native : CompressedCalls W P order adv fit inc) :
+ PairContinuation W adv fit inc := by
+ intro cuts i j mode pad tr out
+ have smallWord (μ) (q : Path (exteriorOf fit (fst cuts)) i (order μ)) (a) :
+ inc (exteriorOf fit (fst cuts)) i (order μ) q a + 1 < 2^G.w :=
+ (Nat.succ_le_of_lt (small _ _ _ q a)).trans_lt (Nat.pow_lt_pow_right (by decide) P.width)
+ apply Eq.trans _ (pairCount_equiv order fit inc (fst cuts) i)
+ apply @post_header_count G _ i cuts fit (fun ξ j μ => Path ξ j (order μ)) (fun ξ j μ => finitePaths ξ j (order μ)) (fun ξ j μ => inc ξ j (order μ)) _ adv out mode (pad .right) tr.tag (P.room i) P.width.le
+ P.nominations P.initializer P.copy P.exponents P.labels P.row smallWord S H tr.logs
+ intro ξ F N μ B
+ obtain ⟨C,hC⟩ := native cuts i mode pad tr out μ B
+ refine ⟨C,fun q => ?_⟩
+ obtain ⟨cost,calls⟩ := hC q
+ exact joinedCap P tr.logs tr.cost tr.probes tr.tag μ F B C.indexed q cost calls
+
+end LiveProgram.LocalCount
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveNominationSweep.lean b/lean/OAI/Computability/VPVNP/LiveNominationSweep.lean
new file mode 100644
index 0000000000..13e189c46c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveNominationSweep.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.LiveNominations
+import OAI.Computability.VPVNP.PrimedInputRAMChoices
+import OAI.Computability.VPVNP.RAMWordBits
+import OAI.Computability.VPVNP.RAMChain
+
+/-!
+# Chronological RAM calls for the nominated histogram
+
+The first-half groups in §14.1 guess one fixed-width word for each production
+label. The persistent cursor runs in increasing label order. The calls consume
+exactly the row-major binary encoding of the histogram and store its entries
+in the contiguous array beginning at the public base address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveNominations
+
+open BurstRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {w b T : ℕ}
+
+/-- One little-endian binary choice list per production label. -/
+def calls (μ : Fin T → Word b) : List (List Bool) := List.ofFn fun i => wordBits (μ i)
+
+/-- Flattening the interpreter's choices gives the canonical array encoding, a bijection
+between histograms and binary tapes of length `T * b`. -/
+theorem flatten_calls (μ : Fin T → Word b) :
+ (calls μ).flatten = List.ofFn (RAMSerialization.arrayBits T b μ) := by
+ have h := List.ofFn_mul (RAMSerialization.arrayBits T b μ)
+ have eq : List.ofFn (RAMSerialization.arrayBits T b μ) =
+ (List.ofFn fun i : Fin T => List.ofFn fun j : Fin b =>
+ RAMSerialization.arrayBits T b μ (finProdFinEquiv (i,j))).flatten := by
+ simpa only [finProdFinEquiv, Equiv.coe_fn_mk, Nat.mul_comm b, Nat.add_comm] using h
+ simpa only [RAMSerialization.arrayBits_at, calls, wordBits] using eq.symm
+
+/-- Contents of the histogram area after the last component call. -/
+def stored (base : Word w) (fit : base.val + T ≤ 2 ^ w) (μ : Fin T → Word b) (m : Memory w) :
+ Memory w := store (scratchAddress base.val fit) (fun i => Fin.ofNat _ (μ i).val) (List.finRange T) m
+
+theorem stored_at (base : Word w) (fit : base.val + T ≤ 2 ^ w) (μ : Fin T → Word b)
+ (m : Memory w) (i : Fin T) : stored base fit μ m (base.val + i.val) = Fin.ofNat _ (μ i).val :=
+ store_at (scratchAddress base.val fit) _ _ m (List.mem_finRange i)
+
+/-- Each stored counter has the nominated natural value, without truncation. -/
+theorem stored_at_val (hb : b ≤ w) (base : Word w) (fit : base.val + T ≤ 2 ^ w)
+ (μ : Fin T → Word b) (m : Memory w) (i : Fin T) :
+ (stored base fit μ m (base.val + i.val)).val = (μ i).val := by
+ rw [stored_at, Fin.val_ofNat, Nat.mod_eq_of_lt]
+ exact (μ i).isLt.trans_le (Nat.pow_le_pow_right (by decide) hb)
+
+/-- The sweep touches only the designated array. -/
+theorem stored_outside (base : Word w) (fit : base.val + T ≤ 2 ^ w) (μ : Fin T → Word b)
+ (m : Memory w) (a : ℕ) (ha : a < base.val ∨ base.val + T ≤ a) : stored base fit μ m a = m a := by
+ apply store_outside
+ intro i _
+ change a ≠ base.val + i.val
+ have := i.isLt
+ omega
+
+private theorem base_add_cursor (base : Word w) (fit : base.val + T ≤ 2 ^ w) (i : Fin T) :
+ base + (i.val : Word w) = scratchAddress base.val fit i := by
+ have ha := (Nat.add_lt_add_left i.isLt base.val).trans_le fit
+ have hv : ((i.val : Word w) : ℕ) = i.val := by
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ apply Fin.ext
+ rw [Fin.val_add_eq_of_add_lt (by simpa only [hv] using ha), hv]
+ rfl
+
+private theorem run_cells {C : Type*} (P : Program w C) (fuel steps : ℕ)
+ (base : Word w) (fit : base.val + T ≤ 2 ^ w) (μ : Fin T → Word b)
+ (hstep : ∀ (i : Fin T) (m : Memory w), ∃ es,
+ execute P fuel (P.start (i.val : Word w)) m (wordBits (μ i)) = some ⟨es, some ((i.val : Word w) + 1)⟩ ∧
+ after m es = writeMemory m (base + (i.val : Word w)) (Fin.ofNat _ (μ i).val) ∧
+ es.length = steps ∧ countProbes es = 1)
+ (cells : List (Fin T)) (start : ℕ) (hc : cells.map Fin.val = List.range' start cells.length)
+ (m : Memory w) : ∃ rs,
+ runSegment P fuel (some (start : Word w)) m (cells.map fun i => wordBits (μ i)) = some rs ∧
+ endState (some (start : Word w)) rs = some ((start + cells.length : ℕ) : Word w) ∧
+ after m (eventLog rs) = store (scratchAddress base.val fit) (fun i => Fin.ofNat _ (μ i).val) cells m ∧
+ rs.length = cells.length ∧ ∀ r ∈ rs, r.events.length = steps ∧ countProbes r.events = 1 := by
+ induction cells generalizing m start with
+ | nil => exact ⟨[], rfl, rfl, rfl, rfl, by simp⟩
+ | cons i cells ih =>
+ simp only [List.map_cons, List.length_cons, List.range'_succ, List.cons.injEq] at hc
+ obtain ⟨rfl, aligned⟩ := hc
+ obtain ⟨es, he, hm, hl, hp⟩ := hstep i m
+ rw [base_add_cursor base fit i] at hm
+ obtain ⟨rs, hr, hend, hmem, hlen, hcost⟩ := ih (i.val + 1) aligned (after m es)
+ refine ⟨⟨es, some ((i.val : Word w) + 1)⟩ :: rs, ?_, ?_, ?_, by simp [hlen], ?_⟩
+ · simp only [List.map_cons, runSegment, he, ← Nat.cast_one (R := Word w), ← Nat.cast_add]
+ rw [hr]
+ rfl
+ · simpa [endState, Nat.add_assoc, Nat.add_comm 1] using hend
+ · change after m (es ++ eventLog rs) = store _ _ cells (writeMemory m _ _)
+ rw [← hm]
+ simpa [after] using hmem
+ · intro r h
+ rcases List.mem_cons.mp h with rfl | h
+ · exact ⟨hl, hp⟩
+ · exact hcost r h
+
+private theorem finRange_aligned (T : ℕ) :
+ (List.finRange T).map Fin.val = List.range' 0 (List.finRange T).length := by
+ apply List.ext_getElem (by simp)
+ intro i _ _
+ simp
+
+private theorem all_words_of_run {C : Type*} {P : Program w C} {fuel : ℕ}
+ (hword : ∀ (s : Word w) (m : Memory w) bs r,
+ execute P fuel (P.start s) m bs = some r → ∃ v : Word b, bs = wordBits v)
+ {initial : Option (Word w)} {m : Memory w} {bs : List (List Bool)} {rs : List (Report w)}
+ (hr : runSegment P fuel initial m bs = some rs) :
+ ∀ digits ∈ bs, ∃ v : Word b, digits = wordBits v := by
+ induction bs generalizing initial m rs with
+ | nil => simp
+ | cons digits bs ih =>
+ cases initial with
+ | none => simp [runSegment] at hr
+ | some s =>
+ cases h : execute P fuel (P.start s) m digits with
+ | none => simp [runSegment, h] at hr
+ | some r =>
+ simp only [runSegment, h, Option.map_eq_some_iff] at hr
+ obtain ⟨ts, ht, _⟩ := hr
+ exact List.forall_mem_cons.mpr ⟨hword s m digits r h, ih ht⟩
+
+private theorem wordBits_injective : Function.Injective (wordBits (w := b)) :=
+ List.ofFn_injective.comp (RAMSerialization.wordBits b).injective
+
+/-- Run all nominations with reset private registers at each call, preserving the external
+memory and advancing the cursor. At `T = 2^w` the final word is zero modulo `2^w`. -/
+theorem sweep_native (hb : b ≤ w) (base : Word w) (fit : base.val + T ≤ 2 ^ w)
+ (μ : Fin T → Word b) (m : Memory w) : ∃ rs,
+ runSegment (program b base) (5*b+12) (some 0) m (calls μ) = some rs ∧
+ endState (some 0) rs = some (T : Word w) ∧ after m (eventLog rs) = stored base fit μ m ∧
+ rs.length = T ∧ ∀ r ∈ rs, r.events.length = 5*b+11 ∧ countProbes r.events = 1 := by
+ have h := run_cells (program b base) (5*b+12) (5*b+11) base fit μ (fun i mem => by
+ obtain ⟨es, he, hm, hl, hp, _⟩ := component_native hb base (i.val : Word w) mem (μ i)
+ exact ⟨es, he, hm, hl, hp⟩) (List.finRange T) 0 (finRange_aligned T) m
+ simpa only [calls, List.ofFn_eq_map, stored, Nat.cast_zero, List.length_finRange, Nat.zero_add] using h
+
+/-- Native paths of the nomination phase, with one call per production label. -/
+abbrev SweepPaths (T b : ℕ) (base : Word w) (m : Memory w) :=
+ {bs : List (List Bool) // bs.length = T ∧
+ ∃ rs, runSegment (program b base) (5*b+12) (some 0) m bs = some rs}
+
+/-- Every binary path of the required number of calls is the unique encoding of a histogram. -/
+noncomputable def sweepEquiv (hb : b ≤ w) (base : Word w) (fit : base.val + T ≤ 2 ^ w)
+ (m : Memory w) : (Fin T → Word b) ≃ SweepPaths T b base m := by
+ let encode (μ : Fin T → Word b) : SweepPaths T b base m := ⟨calls μ, by simp [calls], by
+ obtain ⟨rs, hr, _⟩ := sweep_native hb base fit μ m
+ exact ⟨rs, hr⟩⟩
+ apply Equiv.ofBijective encode
+ constructor
+ · intro μ ν he
+ have h : (fun i => wordBits (μ i)) = (fun i => wordBits (ν i)) :=
+ List.ofFn_inj.mp (congrArg Subtype.val he)
+ exact funext fun i => wordBits_injective (congrFun h i)
+ · rintro ⟨bs, hT, rs, hr⟩
+ have all := all_words_of_run (b := b) (fun s mem ds r hd => by
+ obtain ⟨v, hv, _⟩ := component_only hb base s mem hd
+ exact ⟨v, hv⟩) hr
+ subst T
+ choose μ hμ using fun i : Fin bs.length => all bs[i] (List.getElem_mem i.isLt)
+ refine ⟨μ, Subtype.ext ?_⟩
+ change List.ofFn (fun i => wordBits (μ i)) = bs
+ simp_rw [← hμ]
+ exact List.ofFn_getElem
+
+@[simp] theorem sweepEquiv_apply (hb : b ≤ w) (base : Word w) (fit : base.val + T ≤ 2 ^ w)
+ (m : Memory w) (μ : Fin T → Word b) : (sweepEquiv hb base fit m μ).val = calls μ := rfl
+
+end LiveNominations
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveNominations.lean b/lean/OAI/Computability/VPVNP/LiveNominations.lean
new file mode 100644
index 0000000000..56553b1187
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveNominations.lean
@@ -0,0 +1,215 @@
+import OAI.Computability.VPVNP.RAMChoicePrefix
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Native binary nominations in a first-half live group
+
+Section 14.1 guesses exactly `2r` little-endian bits per production label.
+This fixed RAM call takes the bit count and destination base as public words.
+Its persistent state indexes the component. It writes one word and returns
+the next component index. The same control works for any nomination width
+that fits a RAM word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveNominations
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+private def setup : Flow 8 2 :=
+ .seq (.line (.constant 0 0)) <| .seq (.line (.constant 1 1)) <| .seq (.line (.constant 2 0)) <|
+ .seq (.line (.publicWord 3 0)) (.line (.constant 4 1))
+
+private def bitBody : Flow 8 2 :=
+ .seq (.branch (.line (.binary .add 0 0 1)) (.line (.copy 0 0))) <|
+ .seq (.line (.binary .add 1 1 1)) (.line (.binary .add 2 2 4))
+
+private def loop : Flow 8 2 := .whileLt 2 3 bitBody
+
+private def finish : Flow 8 2 :=
+ .seq (.line (.stateWord 5)) <| .seq (.line (.publicWord 6 1)) <|
+ .seq (.line (.binary .add 6 6 5)) <| .seq (.line (.write 6 0)) (.line (.binary .add 7 5 4))
+
+/-- Registers 0, 1 and 2 accumulate the value, bit weight and iteration count. -/
+def flow : Flow 8 2 := .seq setup (.seq loop finish)
+
+variable {w b : ℕ}
+
+/-- The nomination worker's public bit count and base address for the per-label output words. -/
+def data (b : ℕ) (base : Word w) : Fin 2 → Word w := ![Fin.ofNat _ b, base]
+
+/-- The instantiated burst program that guesses a label's bits, stores the nominated word, and
+returns the next label cursor. -/
+def program (b : ℕ) (base : Word w) :=
+ ((flow.template (some 7)).instantiate w (data b base)).program
+
+private def regsAfterSetup (pub : Fin 2 → Word w) (s : Regs w 8) :=
+ Function.update (Function.update (Function.update (Function.update
+ (Function.update s (0 : Fin 8) 0) 1 1) 2 0) 3 (pub 0)) 4 1
+
+private def advance (s : Regs w 8) (v : Bool) :=
+ Function.update (Function.update (Function.update s (0 : Fin 8)
+ (if v then s 0 + s 1 else s 0)) 1 (s 1 + s 1)) 2 (s 2 + s 4)
+
+private def regsAfterFinish (s : Regs w 8) (st base : Word w) :=
+ Function.update (Function.update (Function.update s (5 : Fin 8) st) 6 (base+st)) 7 (st+s 4)
+
+private def bitEvents (v : Bool) : List (Event w) := [.choice v, .tick, .tick, .tick]
+
+private def loopEvents : List Bool → List (Event w)
+ | [] => [.tick]
+ | v :: vs => .tick :: (bitEvents v ++ loopEvents vs)
+
+private theorem setup_exec (pub : Fin 2 → Word w) (st : Word w) (s : Regs w 8) (m : Memory w) :
+ Flow.Exec pub st setup s m (List.replicate 5 .tick) (regsAfterSetup pub s) m :=
+ (Flow.once_sound pub st false setup s m rfl).1
+
+private theorem body_exec (pub : Fin 2 → Word w) (st : Word w) (s : Regs w 8) (m : Memory w)
+ (v : Bool) : Flow.Exec pub st bitBody s m (bitEvents v) (advance s v) m := by
+ apply (Flow.once_sound pub st v bitBody s m ?_).1
+ cases v <;> rfl
+
+private theorem finish_exec (pub : Fin 2 → Word w) (st : Word w) (s : Regs w 8) (m : Memory w) :
+ Flow.Exec pub st finish s m [.tick,.tick,.tick,.write (pub 1 + st) (s 0),.tick]
+ (regsAfterFinish s st (pub 1)) (writeMemory m (pub 1 + st) (s 0)) := by
+ apply (Flow.once_sound pub st false finish s m ?_).1
+ simp (config := { decide := true }) [finish, Flow.once, Op.effect, Function.update,
+ regsAfterFinish, show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl]
+
+private theorem loop_exec (pub : Fin 2 → Word w) (st : Word w) (m : Memory w) (vs : List Bool)
+ (s : Regs w 8) (hone : s 4 = 1) (hlen : (s 2).val + vs.length = (s 3).val) :
+ ∃ out, Flow.Exec pub st loop s m (loopEvents vs) out m ∧
+ out 0 = s 0 + s 1 * (PrimedCounter.GuessWord.value vs : Word w) ∧ out 4 = 1 := by
+ induction vs generalizing s with
+ | nil =>
+ refine ⟨s, Flow.Exec.whileDone ?_, ?_, hone⟩
+ · change ¬ (s 2).val < (s 3).val
+ simp only [List.length_nil, Nat.add_zero] at hlen
+ omega
+ · simp [PrimedCounter.GuessWord.value]
+ | cons v vs ih =>
+ let s' := advance s v
+ have h₂ : (s' 2).val = (s 2).val+1 := by
+ change (s 2 + s 4).val = _
+ rw [hone]
+ apply Fin.val_add_one_of_lt'
+ have := (s 3).isLt
+ simp only [List.length_cons] at hlen
+ omega
+ have h₃ : s' 3 = s 3 := rfl
+ have h₄ : s' 4 = 1 := hone
+ obtain ⟨u, hu, hv, hlast⟩ := ih s' h₄ (by rw [h₂, h₃]; simpa [Nat.add_assoc, Nat.add_comm,
+ Nat.add_left_comm] using hlen)
+ have ht : s 2 < s 3 := by change (s 2).val < (s 3).val; simp only [List.length_cons] at hlen; omega
+ refine ⟨u, Flow.Exec.whileStep ht (body_exec pub st s m v) hu, ?_, hlast⟩
+ rw [hv]
+ cases v <;> simp [s', advance, PrimedCounter.GuessWord.value, Function.update] <;> ring
+
+private def resultEvents (base st v : Word w) (bits : List Bool) : List (Event w) :=
+ List.replicate 5 .tick ++ (loopEvents bits ++ [.tick,.tick,.tick,.write (base+st) v,.tick])
+
+private theorem loop_cost (vs : List Bool) :
+ (loopEvents (w := w) vs).length = 5 * vs.length + 1 ∧
+ choiceBits (loopEvents (w := w) vs) = vs ∧ countProbes (loopEvents (w := w) vs) = 0 := by
+ induction vs with
+ | nil => exact ⟨rfl,rfl,rfl⟩
+ | cons v vs ih =>
+ simp only [loopEvents, bitEvents, List.cons_append, List.nil_append, List.length_cons,
+ choiceBits, countProbes, ih.1, ih.2.1, ih.2.2, Nat.mul_succ]
+ exact ⟨trivial, trivial, trivial⟩
+
+private theorem loop_after (vs : List Bool) (m : Memory w) : after m (loopEvents vs) = m := by
+ induction vs with
+ | nil => rfl
+ | cons v vs ih => exact ih
+
+private theorem probe_append (xs ys : List (Event w)) :
+ countProbes (xs ++ ys) = countProbes xs + countProbes ys := by
+ induction xs with
+ | nil => simp [countProbes]
+ | cons e xs ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+private theorem result_cost (base st v : Word w) (bs : List Bool) :
+ (resultEvents base st v bs).length = 5 * bs.length + 11 ∧
+ countProbes (resultEvents base st v bs) = 1 ∧ choiceBits (resultEvents base st v bs) = bs := by
+ obtain ⟨hl,hb,hp⟩ := loop_cost (w := w) bs
+ simp only [resultEvents, List.length_append, List.length_replicate, hl, List.length_cons,
+ List.length_nil, probe_append, Flow.choiceBits_append, hp, hb]
+ exact ⟨by omega, rfl, by simp [choiceBits, List.replicate_succ]⟩
+
+private theorem result_after (base st v : Word w) (bs : List Bool) (m : Memory w) :
+ after m (resultEvents base st v bs) = writeMemory m (base+st) v := by
+ change after m (loopEvents bs ++ [.tick,.tick,.tick,.write (base+st) v,.tick]) = _
+ rw [after, List.foldl_append, show (loopEvents bs).foldl update m = m from loop_after bs m]
+ rfl
+
+/-- The native microcall has exactly one write. Its binary choices are precisely
+the bits of the nominated component, even when it has leading zeros. -/
+theorem component_native (hb : b ≤ w) (base state : Word w) (m : Memory w) (v : Word b) :
+ ∃ es, execute (program b base) (5*b+12) ((program b base).start state) m (wordBits v) =
+ some ⟨es, some (state+1)⟩ ∧
+ after m es = writeMemory m (base+state) (Fin.ofNat (2^w) v.val) ∧
+ es.length = 5*b+11 ∧ countProbes es = 1 ∧ choiceBits es = wordBits v := by
+ let pub := data b base
+ let rs := regsAfterSetup pub (fun _ => 0)
+ have hfit : b < 2^w := hb.trans_lt (Nat.lt_pow_self (by decide))
+ have hlen : (rs 2).val + (wordBits v).length = (rs 3).val := by
+ change 0 + (wordBits v).length = b % 2^w
+ rw [Nat.mod_eq_of_lt hfit, length_wordBits, Nat.zero_add]
+ obtain ⟨out, hloop, hval, hone⟩ := loop_exec pub state m (wordBits v) rs rfl hlen
+ have hv : out 0 = Fin.ofNat (2^w) v.val := by
+ rw [hval, PrimedCounter.GuessWord.value_wordBits]
+ change 0 + 1 * (v.val : Word w) = _
+ simp
+ let es := resultEvents base state (Fin.ofNat _ v.val) (wordBits v)
+ obtain ⟨hl, hp, hc⟩ := result_cost base state (Fin.ofNat _ v.val) (wordBits v)
+ rw [length_wordBits] at hl
+ refine ⟨es, ?_, result_after .., hl, hp, hc⟩
+ apply (Flow.template_execute_iff flow (some 7) pub state (fun _ => 0) (fun _ => 0) m _ _ _).2
+ refine ⟨regsAfterFinish out state base, writeMemory m (base+state) (Fin.ofNat _ v.val),
+ ?_, ?_, ?_, hc⟩
+ · have exec := Flow.Exec.seq (setup_exec pub state (fun _ => 0) m)
+ (Flow.Exec.seq hloop (finish_exec pub state out m))
+ simpa only [hv, es, resultEvents, flow, show pub 1 = base from rfl] using exec
+ · change some (state + 1) = some (state + out 4)
+ rw [hone]
+ · change es.length < 5*b+12
+ change es.length = _ at hl
+ omega
+
+private theorem word_of_bits (bs : List Bool) (h : bs.length = b) : ∃ v : Word b, bs = wordBits v := by
+ subst b
+ refine ⟨(RAMSerialization.wordBits bs.length).symm bs.get, ?_⟩
+ simp [wordBits]
+
+/-- Every successful call consumes exactly one fixed-width component and has
+its specified memory effect, for any amount of interpreter fuel. -/
+theorem component_only (hb : b ≤ w) (base state : Word w) (m : Memory w) {fuel : ℕ}
+ {bs : List Bool} {r : Report w}
+ (hr : execute (program b base) fuel ((program b base).start state) m bs = some r) :
+ ∃ v : Word b, bs = wordBits v ∧ r.result = some (state+1) ∧
+ after m r.events = writeMemory m (base+state) (Fin.ofNat (2^w) v.val) ∧
+ r.events.length = 5*b+11 ∧ countProbes r.events = 1 ∧ choiceBits r.events = bs := by
+ have hfull (xs : List Bool) (hx : xs.length = b) : ∃ f t,
+ execute (program b base) f ((program b base).start state) m xs = some t := by
+ obtain ⟨v, rfl⟩ := word_of_bits xs hx
+ obtain ⟨es, h, _⟩ := component_native hb base state m v
+ exact ⟨_, _, h⟩
+ obtain ⟨v, rfl⟩ := word_of_bits bs (execute_length_of_complete hfull hr)
+ obtain ⟨es, h, hm, hl, hp, hc⟩ := component_native hb base state m v
+ have he := (execute_prefix_unique hr (suffix := []) (by simpa using h)).2
+ subst r
+ exact ⟨v, rfl, rfl, hm, hl, hp, hc⟩
+
+end LiveNominations
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOneShot.lean b/lean/OAI/Computability/VPVNP/LiveOneShot.lean
new file mode 100644
index 0000000000..6dfded27fc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOneShot.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.RAMUniform
+
+/-!
+# Closing a single-call stage of the live program
+
+The descriptor initializer ends by returning a word. At its stage boundary
+this is a normal accepting exit that lets the linker select the next stage.
+The instruction trace, bit consumption, memory probes, and required fuel
+agree with the original call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveOneShot
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {p r k w : ℕ}
+
+private def closeInstruction : Instr w p r k → Instr w p r k
+ | .returnState _ => .accept
+ | i => i
+
+/-- Close the returning exits of a single-call native template so the enclosing linker can
+advance after its first call. -/
+def oneShot (T : Template p r k) : Template p r k :=
+ { T with code := fun pc => closeInstruction (T.code pc) }
+
+private def closeAction {C : Type*} : CallAction w C → CallAction w C
+ | .finish _ => .finish none
+ | action => action
+
+private theorem step_eq (T : Template p r k) (pub : Fin k → Word w) (c : Config w p r) :
+ ((oneShot T).instantiate w pub).program.step c =
+ closeAction ((T.instantiate w pub).program.step c) := by
+ simp only [oneShot, Template.instantiate, Machine.program]
+ cases T.code c.pc <;> rfl
+
+/-- Executing the closed table changes every successful return to acceptance. -/
+theorem execute_oneShot (T : Template p r k) (pub : Fin k → Word w) (fuel : ℕ)
+ (c : Config w p r) (m : Memory w) (bs : List Bool) :
+ execute ((oneShot T).instantiate w pub).program fuel c m bs =
+ (execute (T.instantiate w pub).program fuel c m bs).map (fun t => ⟨t.events, none⟩) := by
+ induction fuel generalizing c m bs with
+ | zero => rfl
+ | succ fuel ih =>
+ simp only [execute, step_eq]
+ cases (T.instantiate w pub).program.step c with
+ | finish v => cases bs <;> rfl
+ | reject => rfl
+ | branch f => cases bs <;> simp [closeAction, ih, Option.map_map, Function.comp_def, Report.prepend]
+ | localStep next | read a next | write a v next =>
+ simp [closeAction, ih, Option.map_map, Function.comp_def, Report.prepend]
+
+end LiveOneShot
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsideAllCaps.lean b/lean/OAI/Computability/VPVNP/LiveOutsideAllCaps.lean
new file mode 100644
index 0000000000..554a5f7779
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsideAllCaps.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.LiveOutsidePreparedGroup
+import OAI.Computability.VPVNP.LiveOutsideCallCapacity
+
+/-!
+# Simultaneous resource bounds for Section 14.2
+
+The site exponent is selected after the public dimensions. For every larger
+fixed exponent the length threshold works for every group, route, bounded
+advice prefix and native outside trace. The compressed part of a paired
+trace has its own Section 13 estimate.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideTraces
+
+open BurstRAM OutsideBudget CursorBounds CursorNetwork Filter
+
+theorem eventually_all_caps {C : ℕ} (u : PairExponents C) (c : Constants) (E : UniversalMachine.Program) :
+ ∃ B₀, ∀ B ≥ B₀, ∀ᶠ n : ℕ in atTop, ∀ G : PairStages.Group,
+ G.g = paperGeometry B (liveCapacity u) n → G.constants = c → G.evaluator = E →
+ ∀ raw first last empty, raw ≤ G.constants.prefixCapacity.eval G.g →
+ actualBound G.constants G.g raw first last empty < processorCount B n ∧
+ max 26 (OutsideTailStages.callBound G.w) ≤ G.g.H ∧
+ max 154 (max (5*(2*G.g.d)+23) (OutsideTailStages.instructionBound G)) ≤ n^10000 := by
+ obtain ⟨B₀,hs⟩ := eventually_actual c
+ refine ⟨B₀,fun B hB => ?_⟩
+ filter_upwards [hs B hB,eventually_groupReportCaps u B E] with n size clocks
+ intro G hg hc hE raw first last empty hraw
+ obtain ⟨per,work⟩ := clocks G hg hE
+ refine ⟨?_,per,work⟩
+ rw [hg,hc] at hraw ⊢
+ exact size (liveCapacity u n) raw first last empty hraw
+
+/-- Application of the common eventual bounds to an actual report list.
+All returned inequalities concern the physical words and buckets. -/
+theorem eventually_trace_caps {C : ℕ} (u : PairExponents C) (c : Constants) (E : UniversalMachine.Program) :
+ ∃ B₀, ∀ B ≥ B₀, ∀ᶠ n : ℕ in atTop, ∀ G : PairStages.Group,
+ G.g = paperGeometry B (liveCapacity u) n → G.constants = c → G.evaluator = E →
+ ∀ raw first last empty, raw ≤ G.constants.prefixCapacity.eval G.g →
+ ∀ (rs : List (Report G.w)) per work,
+ Resources rs (actualBound G.constants G.g raw first last empty) per work →
+ per ≤ max 26 (OutsideTailStages.callBound G.w) →
+ work ≤ max 154 (max (5*(2*G.g.d)+23) (OutsideTailStages.instructionBound G)) →
+ RAMBuckets.cost Report.probes rs < processorCount B n ∧
+ (∀ r ∈ rs, 1+r.probes ≤ G.g.H ∧ r.events.length+1 ≤ n^10000) := by
+ obtain ⟨B₀,h⟩ := eventually_all_caps u c E
+ refine ⟨B₀,fun B hB => ?_⟩
+ filter_upwards [h B hB] with n fits G hg hc hE raw first last empty hraw rs per work resource hper hwork
+ obtain ⟨ct,pc,wc⟩ := fits G hg hc hE raw first last empty hraw
+ exact ⟨resource.cost.trans_lt ct,fun r hr => ⟨(resource.calls r hr).trans (hper.trans pc),
+ (resource.work r hr).trans (hwork.trans wc)⟩⟩
+
+end LiveProgram.OutsideTraces
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsideBudget.lean b/lean/OAI/Computability/VPVNP/LiveOutsideBudget.lean
new file mode 100644
index 0000000000..46e6e648a4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsideBudget.lean
@@ -0,0 +1,232 @@
+import OAI.Computability.VPVNP.LiveEvaluatorTailCost
+import OAI.Computability.VPVNP.LiveHeaderResources
+import OAI.Computability.VPVNP.LiveProgramLayout
+import OAI.Computability.VPVNP.LiveWordCapacity
+
+/-!
+# Choosing the physical processor count after the live preparation costs
+
+The bound covers the header, preparation of the auxiliary inputs, the
+exponent check and the evaluator tail. It bounds the tail uniformly over
+all actual advice prefixes of the reserved size. The majorant substitutes
+the input length for the RAM word width. For every fixed address exponent
+this substitution holds eventually, so the polynomial degree in the
+majorant is selected before that address exponent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideBudget
+
+open Filter CursorBounds LiveEvaluatorTailCost
+
+/-- A polynomial expression dominating either tail route at any raw prefix
+length up to `A` and word width up to `W`. -/
+def tailMajorant (A t Z M W : ℕ) :=
+ let T := t*Z
+ let k := 4*M+3
+ let pack := 6*(W+1) + 23 + 11*(1+(A+W)*(W+1)) + 6*(1+t*(t+1))
+ let init := 4 + pack + 10*(1+A) + 8*(2*T+6*Z+4) + 11*(1+T)
+ 8 + (10+14*(2*M+1)) + 2*k + init + 2*((W+4)*k) + 4
+
+theorem tail_le (u : Parameters) (first last empty : Bool) {A W : ℕ}
+ (hA : u.advice ≤ A) (hW : u.wordWidth ≤ W) :
+ groupBound u first last empty ≤ tailMajorant A u.rows u.rowWidth u.radius W := by
+ have hpack : u.prefixPackCalls ≤ 1+(A+W)*(W+1) := by
+ unfold Parameters.prefixPackCalls
+ have hp := Nat.div_le_self (u.advice+u.wordWidth-1) u.wordWidth
+ have h := Nat.mul_le_mul (show (u.advice+u.wordWidth-1)/u.wordWidth ≤ A+W by omega)
+ (Nat.succ_le_succ hW)
+ simp only [Nat.succ_eq_add_one] at h
+ omega
+ have horder : u.orderPackCalls ≤ 1 + u.rows*(u.rows+1) := by
+ unfold Parameters.orderPackCalls
+ have hc : Nat.clog 2 u.rows ≤ u.rows := Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le
+ have h := Nat.mul_le_mul_left u.rows (Nat.succ_le_succ hc)
+ simp only [Nat.succ_eq_add_one] at h
+ omega
+ have hgat : (u.wordWidth+4)*u.configWords ≤ (W+4)*u.configWords :=
+ Nat.mul_le_mul_right _ (by omega)
+ simp only [Parameters.configWords] at hgat
+ cases first <;> cases last <;> cases empty <;>
+ simp only [groupBound, tailMajorant, Parameters.lengthPackCalls, Parameters.runtimeBits,
+ Parameters.transitionCost, Parameters.configWords, Parameters.exponentBits, Bool.false_eq_true,
+ ite_true, ite_false] <;> omega
+
+/-- Polynomially bounded components remain polynomially bounded under the
+tail majorant, without a common degree assumption on their five functions. -/
+theorem tail_polynomial {A t Z M W : ℕ → ℕ} (hA : PolynomiallyBounded A) (ht : PolynomiallyBounded t)
+ (hZ : PolynomiallyBounded Z) (hM : PolynomiallyBounded M) (hW : PolynomiallyBounded W) :
+ PolynomiallyBounded (fun n => tailMajorant (A n) (t n) (Z n) (M n) (W n)) := by
+ let c := PolynomiallyBounded.const
+ have hT := ht.mul hZ
+ have hk := ((c 4).mul hM).add (c 3)
+ have pack := ((((c 6).mul (hW.add (c 1))).add (c 23)).add
+ ((c 11).mul ((c 1).add ((hA.add hW).mul (hW.add (c 1)))))).add
+ ((c 6).mul ((c 1).add (ht.mul (ht.add (c 1)))))
+ have init := ((((c 4).add pack).add ((c 10).mul ((c 1).add hA))).add
+ ((c 8).mul ((((c 2).mul hT).add ((c 6).mul hZ)).add (c 4)))).add ((c 11).mul ((c 1).add hT))
+ have tr := (c 10).add ((c 14).mul (((c 2).mul hM).add (c 1)))
+ have first := (((c 8).add tr).add ((c 2).mul hk)).add init
+ exact (first.add ((c 2).mul ((hW.add (c 4)).mul hk))).add (c 4)
+
+/-- Raw dimensions, independent of the address exponent. -/
+def dimensions (n : ℕ) : Geometry := ⟨n,n,n,n⟩
+
+/-- Evaluate the header dimensions at the bounding geometry for input length n to estimate the
+outside-stage work. -/
+def upperHeader (c : Constants) (n : ℕ) := c.lengths.eval (dimensions n)
+
+private theorem labels_polynomial (c : Constants) :
+ PolynomiallyBounded (fun n => c.labels.eval (dimensions n)) := by
+ let id := PolynomiallyBounded.id
+ let C := PolynomiallyBounded.const
+ let state := id.pow (c.circuitExponent+5)
+ let pair := (id.mul id).of_le fun n => show n*(n-1)/2 ≤ n*n from
+ (Nat.div_le_self ..).trans (Nat.mul_le_mul_left _ (Nat.sub_le ..))
+ simp only [Constants.labels, Constants.grammarLabels, Constants.states, eval_add,
+ PublicExpr.eval_natPow, PublicExpr.eval, dimensions]
+ exact (((state.mul id).mul (C 2)).add (((pair.mul state).mul state).mul state)).add (C c.motifLabels)
+
+private theorem header_polynomial (c : Constants) :
+ PolynomiallyBounded (fun n => LiveHeaderSchedule.costBound (upperHeader c n)) := by
+ let id := PolynomiallyBounded.id
+ let C := PolynomiallyBounded.const
+ have h := id.pow c.chainPower
+ have z := (C 2).mul h
+ have rad := id.pow c.radiusPower
+ have k := ((C 1).add (((C 2).mul rad).add (C 1))).add (((C 2).mul rad).add (C 1))
+ apply LiveHeaderSchedule.polynomial_cost
+ all_goals simp only [upperHeader, Lengths.eval, Constants.lengths, Constants.height, Constants.Z,
+ Constants.configWords, Constants.radius, eval_mul, PublicExpr.eval_natPow, PublicExpr.eval, dimensions]
+ · exact h.of_le fun n => Nat.sub_le (n^c.chainPower) 1
+ · exact id.pow c.deltaPower
+ · exact id.pow c.advicePower
+ · exact (labels_polynomial c).mul z
+ · exact k.mul id
+
+/-- Maximum number of populated words of the auxiliary header. It excludes
+both unused tails of the two exterior buffers. -/
+def auxWords (s : LiveHeaderSchedule.Sizes) (t : ℕ) :=
+ 3 + 2*(s.h+2) + s.advice + 2*((s.h+1)*s.delta) + t
+
+/-- Header checks and all non-compression phases of a single live group.
+Both route costs may be added when taking the common bound. -/
+def majorant (c : Constants) (n : ℕ) :=
+ let g := dimensions n
+ let t := c.labels.eval g
+ let Z := c.Z.eval g
+ let s := upperHeader c n
+ LiveHeaderSchedule.costBound s + 8 + 4*(t+1) + 100 + 16*(auxWords s t+1) + 7*(t*Z+1) +
+ tailMajorant (c.prefixCapacity.eval g) t Z (c.radius.eval g) n
+
+theorem polynomial_majorant (c : Constants) : PolynomiallyBounded (majorant c) := by
+ let id := PolynomiallyBounded.id
+ let C := PolynomiallyBounded.const
+ have hh := (id.pow c.chainPower).of_le fun n => Nat.sub_le (n^c.chainPower) 1
+ have hd := id.pow c.deltaPower
+ have ha := id.pow c.advicePower
+ have t := labels_polynomial c
+ have z := (C 2).mul (id.pow c.chainPower)
+ have aux := ((((C 3).add ((C 2).mul (hh.add (C 2)))).add ha).add
+ ((C 2).mul ((hh.add (C 1)).mul hd))).add t
+ have tail := tail_polynomial (id.pow c.prefixPower) t z (id.pow c.radiusPower) id
+ have poly := (((((((header_polynomial c).add (C 8)).add ((C 4).mul (t.add (C 1)))).add (C 100)).add
+ ((C 16).mul (aux.add (C 1)))).add ((C 7).mul ((t.mul z).add (C 1)))).add tail)
+ unfold majorant auxWords
+ simpa only [upperHeader, Lengths.eval, Constants.lengths, Constants.height, Constants.Z,
+ Constants.configWords, Constants.radius, Constants.prefixCapacity, eval_mul, PublicExpr.eval_natPow,
+ PublicExpr.eval, dimensions] using poly
+
+/-- The group budget in the actual word geometry, with its true advice prefix
+length and actual selected tail route. Compression is accounted separately. -/
+def actualBound (c : Constants) (g : Geometry) (raw : ℕ) (first last empty : Bool) :=
+ let s := c.lengths.eval g
+ let t := c.labels.eval g
+ let Z := c.Z.eval g
+ LiveHeaderSchedule.costBound s + 8 + 4*(t+1) + 100 + 16*(auxWords s t+1) + 7*(t*Z+1) +
+ groupBound ⟨raw,t,Z,c.radius.eval g,g.w⟩ first last empty
+
+private theorem labels_eq (c : Constants) (g : Geometry) :
+ c.labels.eval g = c.labels.eval (dimensions g.n) := by
+ simp only [Constants.labels, eval_add, Constants.grammarLabels_eq, PublicExpr.eval, dimensions]
+
+theorem actual_le (c : Constants) (g : Geometry) (raw : ℕ) (first last empty : Bool)
+ (hw : g.w ≤ g.n) (hraw : raw ≤ c.prefixCapacity.eval g) :
+ actualBound c g raw first last empty ≤ majorant c g.n := by
+ have htail := tail_le (⟨raw,c.labels.eval g,c.Z.eval g,c.radius.eval g,g.w⟩ : Parameters)
+ first last empty hraw hw
+ dsimp only at htail
+ have hl := labels_eq c g
+ have hs : LiveHeaderSchedule.costBound (c.lengths.eval g) ≤
+ LiveHeaderSchedule.costBound (upperHeader c g.n) := by
+ simp only [upperHeader, Lengths.eval, Constants.lengths, Constants.height, Constants.Z, Constants.configWords,
+ Constants.radius, eval_mul, PublicExpr.eval_natPow, PublicExpr.eval, dimensions,
+ LiveHeaderSchedule.costBound, LiveHeaderSchedule.callBound]
+ rw [hl]
+ gcongr
+ exact le_rfl
+ have haux : auxWords (c.lengths.eval g) (c.labels.eval g) =
+ auxWords (upperHeader c g.n) (c.labels.eval (dimensions g.n)) := by
+ simp only [auxWords, upperHeader, Lengths.eval, Constants.lengths, Constants.height,
+ PublicExpr.eval_natPow, PublicExpr.eval, dimensions]
+ rw [hl]
+ rfl
+ unfold actualBound majorant
+ dsimp only
+ have hz : c.Z.eval g = c.Z.eval (dimensions g.n) := by
+ simp only [Constants.Z, Constants.height, eval_mul, PublicExpr.eval_natPow, PublicExpr.eval, dimensions]
+ have hr : c.radius.eval g = c.radius.eval (dimensions g.n) := by
+ simp only [Constants.radius, PublicExpr.eval_natPow, PublicExpr.eval, dimensions]
+ have hp : c.prefixCapacity.eval g = c.prefixCapacity.eval (dimensions g.n) := by
+ simp only [Constants.prefixCapacity, PublicExpr.eval_natPow, PublicExpr.eval, dimensions]
+ rw [hl, hz, hr, hp] at htail
+ rw [haux, hl, hz, hr]
+ omega
+
+private theorem pow_le_R (B n : ℕ) : n^B ≤ processorCount B n := by
+ calc
+ _ ≤ (2^Nat.clog 2 n)^B := Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) n) B
+ _ = _ := by rw [← pow_mul, Nat.mul_comm]; rfl
+
+/-- The choice of B precedes the eventual threshold and applies uniformly
+to the physical word widths and all bounded group inputs. -/
+theorem eventually_budget (c : Constants) :
+ ∃ B₀ : ℕ, ∀ B ≥ B₀, ∀ᶠ n : ℕ in atTop,
+ majorant c n < processorCount B n ∧ CursorBounds.wordBits B n ≤ n := by
+ obtain ⟨A,d,N,hm⟩ := polynomial_majorant c
+ refine ⟨d+1, fun B hB => ?_⟩
+ filter_upwards [eventually_ge_atTop (max N (A+1)), BurstRAM.eventually_word_stage_le B 0] with n hn hw
+ have hN := (le_max_left N (A+1)).trans hn
+ have hA := (le_max_right N (A+1)).trans hn
+ have hn0 : 0 < n := by omega
+ have hmod : CursorBounds.wordBits B n ≤ n :=
+ (hw _ 0 (Nat.mul_le_mul_left B (BurstRAM.clog_le_log2_succ n)) (by simp)).1
+ refine ⟨(hm n hN).trans_lt ?_, hmod⟩
+ calc
+ A*n^d < n*n^d := Nat.mul_lt_mul_of_pos_right (by omega) (Nat.pow_pos hn0)
+ _ = n^(d+1) := (pow_succ' ..).symm
+ _ ≤ n^B := Nat.pow_le_pow_right hn0 hB
+ _ ≤ processorCount B n := pow_le_R B n
+
+/-- One eventual threshold works for every physical group, every eligible
+advice string and every choice of the tail route. -/
+theorem eventually_actual (c : Constants) :
+ ∃ B₀ : ℕ, ∀ B ≥ B₀, ∀ᶠ n : ℕ in atTop, ∀ (H raw : ℕ) (first last empty : Bool),
+ let g := paperGeometry B (fun _ => H) n
+ raw ≤ c.prefixCapacity.eval g → actualBound c g raw first last empty < processorCount B n := by
+ obtain ⟨B₀, h⟩ := eventually_budget c
+ refine ⟨B₀, fun B hB => ?_⟩
+ filter_upwards [h B hB] with n hn
+ intro H raw first last empty
+ dsimp only
+ intro hr
+ exact (actual_le c (paperGeometry B (fun _ => H) n) raw first last empty hn.2 hr).trans_lt hn.1
+
+end LiveProgram.OutsideBudget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsideCallCapacity.lean b/lean/OAI/Computability/VPVNP/LiveOutsideCallCapacity.lean
new file mode 100644
index 0000000000..9265f9e415
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsideCallCapacity.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.LiveOutsideTailStages
+import OAI.Computability.VPVNP.PaperPairParameters
+
+/-!
+# Eventual call and instruction caps for the live group's outside work
+
+The only growing probe count is the gather of a physical word on a tail
+route. Its quartic logarithmic width fits inside the live bucket. The
+nomination sweep and the tail gather have linearly many private instructions
+in the address width and word width respectively. All estimates hold before
+choosing a group, an input header or a successful branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideBudget
+
+open BurstRAM CursorBounds Compression CursorNetwork Filter
+
+/-- Every outside report, including a gather of all bits of one physical
+word, fits the per-call capacity of the live machine. -/
+theorem eventually_outsideCalls_le (B : ℕ) {δ : ℝ} (hδ : δ < 1) :
+ ∀ᶠ n : ℕ in atTop, max 26 (OutsideTailStages.callBound (CursorBounds.wordBits B n)) ≤ liveBucket δ n := by
+ let A := (B+10)^4+26
+ filter_upwards [eventually_polylog_le_rpow A 4 (sub_pos.mpr hδ), eventually_ge_atTop 1] with n hpoly hn
+ let L := n.log2+1
+ have hd : addressBits B n ≤ B*L := Nat.mul_le_mul_left B (clog_le_log2_succ n)
+ have hwidth : addressBits B n+10 ≤ (B+10)*L := by
+ rw [Nat.add_mul]
+ have : 1 ≤ L := Nat.succ_pos _
+ omega
+ have hw : CursorBounds.wordBits B n ≤ (B+10)^4*L^4 := by
+ simpa only [CursorBounds.wordBits, mul_pow] using Nat.pow_le_pow_left hwidth 4
+ have hone : 1 ≤ L^4 := Nat.pow_pos (Nat.succ_pos _) (n := 4)
+ have hsum : max 26 (OutsideTailStages.callBound (CursorBounds.wordBits B n)) ≤ A*L^4 := by
+ unfold A OutsideTailStages.callBound
+ rw [Nat.add_mul]
+ omega
+ have hcap := hpoly.trans (liveBucket_bounds hδ.le hn).1
+ exact hsum.trans (by exact_mod_cast hcap)
+
+set_option exponentiation.threshold 10000 in
+/-- The actual private work of each outside stage fits the fixed live
+private-instruction clock of Section 14.2. -/
+theorem eventually_outsideInstructions_le (B : ℕ) (E : UniversalMachine.Program) :
+ ∀ᶠ n : ℕ in atTop, max 154 (max (5*(2*addressBits B n)+23)
+ (max 130 (max (8*CursorBounds.wordBits B n+67) (LiveEvaluatorRAM.Schedule.callFuel E+47)))) ≤ n^10000 := by
+ filter_upwards [eventually_word_stage_le B B, eventually_ge_atTop (max 154 (LiveEvaluatorRAM.Schedule.callFuel E+47))]
+ with n hword hlarge
+ have hd : addressBits B n ≤ B*(n.log2+1) := Nat.mul_le_mul_left B (clog_le_log2_succ n)
+ obtain ⟨hw, hdn⟩ := hword (addressBits B n) (addressBits B n) hd hd
+ change CursorBounds.wordBits B n ≤ n at hw
+ have hn : 154 ≤ n := (le_max_left ..).trans hlarge
+ have hwork : max 154 (max (5*(2*addressBits B n)+23)
+ (max 130 (max (8*CursorBounds.wordBits B n+67) (LiveEvaluatorRAM.Schedule.callFuel E+47)))) ≤ 11*n := by omega
+ have hsq : 11*n ≤ n^2 := by rw [sq]; exact Nat.mul_le_mul_right n (by omega)
+ exact hwork.trans (hsq.trans (Nat.pow_le_pow_right (lt_of_lt_of_le (by decide : 0 < 154) hn) (by decide : 2 ≤ 10000)))
+
+/-- The paper's exact rounded live bucket and the concrete instruction
+clocks of all three group modes, uniformly in the choice of group. -/
+theorem eventually_groupReportCaps {C : ℕ} (u : PairExponents C) (B : ℕ) (E : UniversalMachine.Program) :
+ ∀ᶠ n : ℕ in atTop, ∀ G : PairStages.Group, G.g = paperGeometry B (liveCapacity u) n → G.evaluator = E →
+ max 26 (OutsideTailStages.callBound G.w) ≤ G.g.H ∧
+ max 154 (max (5*(2*G.g.d)+23) (OutsideTailStages.instructionBound G)) ≤ n^10000 := by
+ have hδ : (u.δ : ℝ) < 1 := by exact_mod_cast (show u.δ < 1 by linarith [u.delta_lt,u.theta_lt])
+ filter_upwards [eventually_outsideCalls_le B hδ, eventually_outsideInstructions_le B E] with n hc hw
+ intro G hg he
+ rw [← liveCapacity_eq u n] at hc
+ unfold OutsideTailStages.instructionBound PairStages.Group.w
+ rw [hg, he]
+ exact ⟨hc, hw⟩
+
+end LiveProgram.OutsideBudget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsideGroupTraces.lean b/lean/OAI/Computability/VPVNP/LiveOutsideGroupTraces.lean
new file mode 100644
index 0000000000..ba97dd0376
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsideGroupTraces.lean
@@ -0,0 +1,194 @@
+import OAI.Computability.VPVNP.LiveOutsidePairStages
+import OAI.Computability.VPVNP.LiveOutsideTailStages
+import OAI.Computability.VPVNP.LiveProgramPairCount
+
+/-!
+# Resource caps for the physical unit and paired group traces
+
+The pair chronology places the compressed computation between the
+auxiliary-input copy and the exponent check. Its cost is charged separately.
+All other reports in the same path are charged to the public polynomial
+bound from Section 14.2.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideTraces
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule OutsideBudget
+
+variable (G : PairStages.Group)
+
+/-- The linked mode-router report selecting the paired branch and entering nominations. -/
+def modePairReport := Router.mode.outerReport G.evaluator G.g G.lit
+ (Router.mode.jumpReport G.g G.lit 1 1 LiveProgram.Stage.nominations)
+
+/-- The linked mode-router report selecting the evaluator branch and entering the first-tail
+router. -/
+def modeTailReport := Router.mode.outerReport G.evaluator G.g G.lit
+ (Router.mode.jumpReport G.g G.lit 2 2 LiveProgram.Stage.firstTail)
+
+/-- The live-header dimensions used to charge this physical group's outside reports. -/
+abbrev sizes := G.constants.lengths.eval G.g
+/-- The number of labels in the live exponent check at this group's geometry. -/
+abbrev labels := G.constants.labels.eval G.g
+/-- The number of binary exponent digits per label at this group's geometry. -/
+abbrev rowWidth := G.constants.Z.eval G.g
+
+/-- Unit mode consists of the recovered headers and one accepting mode router call. -/
+theorem unit_resources (header : List (Report G.w)) (hr : Resources header (costBound (sizes G)) 11 154)
+ (raw : ℕ) (first last empty : Bool) :
+ Resources (header++[UnitGroup.report G]) (actualBound G.constants G.g raw first last empty) 11 154 := by
+ have rt := router_halt Router.mode G.evaluator G.g G.lit 0 0
+ have sum := hr.append rt
+ refine ⟨sum.cost.trans ?_,sum.calls,sum.work⟩
+ dsimp only [actualBound,sizes]
+ omega
+
+variable {G} {m : Memory G.w} {Nom : Type*} {Path : Nom → Type*}
+variable (A : PairStages.Group.Chronology G m Nom Path)
+
+/-- The linked exponent-check reports starting on the memory returned by the selected native
+pair path. -/
+noncomputable def exponentLogs (μ : Nom) (q : Path μ) :=
+ (LiveExponent.stageReports G.exponentPub (labels G) (rowWidth G) ((A.pair μ).memory q)).map
+ (LiveStageLink.linkedReport G.nextStage G.addr LiveProgram.Stage.exponents)
+
+/-- Precisely the reports outside the compressed pair subroutine. -/
+noncomputable def outsidePair (header : List (Report G.w)) (μ : Nom) (q : Path μ) :=
+ (header ++ [modePairReport G]) ++ (A.nominations.logs μ ++ ((A.init μ).logs () ++
+ ((A.copy μ).logs () ++ exponentLogs A μ q)))
+
+/-- Full paired branch in the same order as the actual native path bijection. -/
+noncomputable def wholePair (header : List (Report G.w)) (μ : Nom) (q : Path μ) :=
+ (header ++ [modePairReport G]) ++ (A.prefixLogs μ q ++ exponentLogs A μ q)
+
+theorem pair_cost_identity (header : List (Report G.w)) (μ : Nom) (q : Path μ) :
+ RAMBuckets.cost Report.probes (wholePair A header μ q) =
+ RAMBuckets.cost Report.probes (outsidePair A header μ q) + RAMBuckets.cost Report.probes ((A.pair μ).logs q) := by
+ simp only [wholePair,outsidePair,PairStages.Group.Chronology.prefixLogs,RAMBuckets.cost_append]
+ omega
+
+private theorem member_pair {header : List (Report G.w)} {μ : Nom} {q : Path μ} {r : Report G.w}
+ (h : r ∈ wholePair A header μ q) : r ∈ outsidePair A header μ q ∨ r ∈ (A.pair μ).logs q := by
+ simp only [wholePair,outsidePair,PairStages.Group.Chronology.prefixLogs,List.mem_append] at *
+ tauto
+
+/-- The exact measured preparation stages, with the compiled exponent sweep
+on the memory passed out by the compressed computation. The three source
+stage bounds are furnished by the native nomination, initialization and
+copy theorems in `LiveOutsidePairStages`. -/
+theorem pair_outside_resources (header : List (Report G.w)) (μ : Nom) (q : Path μ)
+ (hr : Resources header (costBound (sizes G)) 11 154)
+ (hn : Resources (A.nominations.logs μ) (4*(labels G+1)) 3 (5*(2*G.g.d)+23))
+ (hi : Resources ((A.init μ).logs ()) 100 26 92)
+ (hc : Resources ((A.copy μ).logs ()) (16*(auxWords (sizes G) (labels G)+1)) 15 115)
+ (raw : ℕ) (first last empty : Bool) :
+ Resources (outsidePair A header μ q) (actualBound G.constants G.g raw first last empty)
+ 26 (max 154 (5*(2*G.g.d)+23)) := by
+ have route := router_jump Router.mode G.evaluator G.g G.lit 1 1 LiveProgram.Stage.nominations
+ have exp := exponent_resources G (labels G) (rowWidth G) ((A.pair μ).memory q)
+ have sum := (hr.append route).append (hn.append (hi.append (hc.append exp)))
+ refine ⟨sum.cost.trans ?_,fun r h => (sum.calls r h).trans ?_,fun r h => (sum.work r h).trans ?_⟩
+ · dsimp only [actualBound,sizes,labels,rowWidth]
+ omega
+ · decide
+ · omega
+
+/-- The outside trace fits one processor array. The remaining bucket capacity
+covers the compressed subroutine. The per-call check follows the report
+membership on the very same chronological path. -/
+theorem pair_withinCaps (header : List (Report G.w)) (μ : Nom) (q : Path μ)
+ {cost work S H : ℕ} (outside : Resources (outsidePair A header μ q) cost 26 work)
+ (hout : cost ≤ S) (hH : 26 ≤ H)
+ (pairCost : RAMBuckets.cost Report.probes ((A.pair μ).logs q) ≤ S*(H-1))
+ (pairCalls : ∀ r ∈ (A.pair μ).logs q, 1+r.probes ≤ H) : withinCaps S H (wholePair A header μ q) := by
+ constructor
+ · rw [pair_cost_identity]
+ calc
+ _ ≤ S + S*(H-1) := Nat.add_le_add (outside.cost.trans hout) pairCost
+ _ = S*H := by rw [Nat.add_comm S,← Nat.mul_succ,show (H-1).succ=H by omega]
+ · intro r hr
+ exact (member_pair A hr).elim (fun h => (outside.calls r h).trans hH) (pairCalls r)
+
+/-- A uniform clock for the private instructions of the complete paired group. -/
+theorem pair_private (header : List (Report G.w)) (μ : Nom) (q : Path μ)
+ {cost work clock : ℕ} (outside : Resources (outsidePair A header μ q) cost 26 work)
+ (hout : work ≤ clock) (pairWork : ∀ r ∈ (A.pair μ).logs q, r.events.length+1 ≤ clock) :
+ ∀ r ∈ wholePair A header μ q, r.events.length+1 ≤ clock := by
+ intro r hr
+ exact (member_pair A hr).elim (fun h => (outside.work r h).trans hout) (pairWork r)
+
+/-- The full evaluator branch, including the common header, the mode jump,
+both boundary routers, the selected setup and gather stages, and the
+actual terminal evaluator burst. -/
+theorem tail_group_resources (G : PairStages.Group) (header : List (Report G.w))
+ (hr : Resources header (costBound (sizes G)) 11 154)
+ (raw : List Bool) {first last : Bool} {xs ys : List (Report G.w)}
+ (incoming : OutsideTailStages.Incoming G raw first xs) (outgoing : OutsideTailStages.Outgoing G raw last ys)
+ (hl : LiveEvaluatorRAM.PrepLayout G.evaluator G.transitionPub (OutsideTailStages.params G raw.length).radius)
+ (mem : Memory G.w) (bits : List (List Bool)) (rs : List (Report G.w)) {f : ℕ}
+ (run : runSegment (LiveEvaluatorRAM.Schedule.nativeProgram G.evaluator G.transitionPub) f (some 0) mem bits = some rs)
+ (halt : endState (some 0) rs = none) :
+ Resources ((header++[modeTailReport G]) ++ (xs++ys++G.linkedLogs LiveProgram.Stage.transition rs))
+ (actualBound G.constants G.g raw.length first last (decide (G.evaluator.extra=0)))
+ (OutsideTailStages.callBound G.w) (max 154 (OutsideTailStages.instructionBound G)) := by
+ have route := router_jump Router.mode G.evaluator G.g G.lit 2 2 LiveProgram.Stage.firstTail
+ have tail := OutsideTailStages.tail_resources G raw incoming outgoing hl mem bits rs run halt
+ have bound := (hr.append route).append tail
+ refine ⟨bound.cost.trans ?_,fun r h => (bound.calls r h).trans ?_,fun r h => (bound.work r h).trans ?_⟩
+ · dsimp only [actualBound,OutsideTailStages.params,sizes,PairStages.Group.w]
+ omega
+ · unfold OutsideTailStages.callBound
+ omega
+ · omega
+
+/-- A complete outside-only route uses at most one processor array. Its
+per-call resource estimate gives the other half of the transcript cap. -/
+theorem outside_only_cap {w : ℕ} {rs : List (Report w)} {cost per work S H : ℕ}
+ (resource : Resources rs cost per work) (hc : cost ≤ S) (hH : 0 < H) (hp : per ≤ H) :
+ withinCaps S H rs := resource.cap (hc.trans (Nat.le_mul_of_pos_right _ hH)) hp
+
+theorem unit_group_cap (G : PairStages.Group) (header : List (Report G.w))
+ (hr : Resources header (costBound (sizes G)) 11 154) (raw S H : ℕ) (first last empty : Bool)
+ (hc : actualBound G.constants G.g raw first last empty ≤ S) (hH : 11 ≤ H) :
+ withinCaps S H (header++[UnitGroup.report G]) :=
+ outside_only_cap (unit_resources G header hr raw first last empty) hc (by omega) hH
+
+theorem tail_group_cap (G : PairStages.Group) (header : List (Report G.w))
+ (hr : Resources header (costBound (sizes G)) 11 154)
+ (raw : List Bool) {first last : Bool} {xs ys : List (Report G.w)}
+ (incoming : OutsideTailStages.Incoming G raw first xs) (outgoing : OutsideTailStages.Outgoing G raw last ys)
+ (hl : LiveEvaluatorRAM.PrepLayout G.evaluator G.transitionPub (OutsideTailStages.params G raw.length).radius)
+ (mem : Memory G.w) (bits : List (List Bool)) (rs : List (Report G.w)) {f S H : ℕ}
+ (run : runSegment (LiveEvaluatorRAM.Schedule.nativeProgram G.evaluator G.transitionPub) f (some 0) mem bits = some rs)
+ (halt : endState (some 0) rs = none)
+ (hc : actualBound G.constants G.g raw.length first last (decide (G.evaluator.extra=0)) ≤ S)
+ (hH : OutsideTailStages.callBound G.w ≤ H) :
+ withinCaps S H ((header++[modeTailReport G]) ++ (xs++ys++G.linkedLogs LiveProgram.Stage.transition rs)) := by
+ have hpos : 0 < H := by unfold OutsideTailStages.callBound at hH; omega
+ exact outside_only_cap (tail_group_resources G header hr raw incoming outgoing hl mem bits rs run halt) hc hpos hH
+
+/-- The same choice of B works for every valid trace, every route, and
+every actual advice prefix up to the public capacity. -/
+theorem eventually_below_R (c : Constants) :
+ ∃ B₀ : ℕ, ∀ B ≥ B₀, ∀ᶠ n : ℕ in Filter.atTop, ∀ H raw first last empty,
+ let g := paperGeometry B (fun _ => H) n
+ ∀ (rs : List (Report g.w)) (per work : ℕ), raw ≤ c.prefixCapacity.eval g →
+ Resources rs (actualBound c g raw first last empty) per work →
+ RAMBuckets.cost Report.probes rs < CursorBounds.processorCount B n := by
+ obtain ⟨B₀,h⟩ := eventually_actual c
+ refine ⟨B₀,fun B hB => ?_⟩
+ filter_upwards [h B hB] with n hn
+ intro H raw first last empty
+ dsimp only
+ intro rs per work hraw res
+ exact res.cost.trans_lt (hn H raw first last empty hraw)
+
+end LiveProgram.OutsideTraces
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsidePairStages.lean b/lean/OAI/Computability/VPVNP/LiveOutsidePairStages.lean
new file mode 100644
index 0000000000..e909602da5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsidePairStages.lean
@@ -0,0 +1,274 @@
+import OAI.Computability.VPVNP.LiveProgramNominationPaths
+import OAI.Computability.VPVNP.LiveOutsideTraces
+import OAI.Computability.VPVNP.LiveAuxiliaryGuardedCopy
+import OAI.Computability.VPVNP.LiveProgramPairExponent
+import OAI.Computability.VPVNP.LiveProgramPairAuxiliary
+import OAI.Computability.VPVNP.LiveAuxiliaryHeaderPreparation
+
+/-!
+# Physical costs outside the compressed first-half pair
+
+These estimates count the actual linked reports, including the dispatch read
+and the transfer write on a nonterminal closing call. The auxiliary header
+copy visits its populated entries only. Its two reserved exterior capacities
+give a uniform upper bound independent of the incident group index.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideBudget
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink LiveExponent LiveAuxiliaryHeaders PrimedInputRAM
+
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem linked_terminal_cost {n : ℕ} (next : Fin n → Option (Fin n)) (addr : Word w)
+ (s : Fin n) (stop : next s = none) (rs : List (Report w)) :
+ RAMBuckets.cost Report.probes (rs.map (linkedReport next addr s)) =
+ RAMBuckets.cost Report.probes rs + rs.length := by
+ induction rs with
+ | nil => rfl
+ | cons r rs ih =>
+ simp only [List.map_cons,RAMBuckets.cost,linkedReport_probes,stop,Option.isSome_none,
+ Bool.false_eq_true,and_false,ite_false,Nat.add_zero,ih,List.length_cons]
+ omega
+
+/-- Exact terminal exponent cost in the actual pair chronology. A digit
+call reads three words, writes one counter, and reads the outer tag. -/
+theorem exponent_cost (G : PairStages.Group) (t Z : ℕ) (m : Memory G.w) :
+ let out := (stageReports G.exponentPub t Z m).map (linkedReport G.nextStage G.addr Stage.exponents)
+ RAMBuckets.cost Report.probes out = 6*(t*Z)+2 ∧
+ RAMBuckets.cost Report.probes out ≤ 7*(t*Z+1) ∧
+ ∀ r ∈ out, r.probes ≤ 5 ∧ r.events.length ≤ 77 := by
+ let rs := stageReports G.exponentPub t Z m
+ obtain ⟨raw,len,each⟩ := stageResources G.exponentPub t Z m
+ have stop : G.nextStage Stage.exponents = none := rfl
+ have cost : RAMBuckets.cost Report.probes (rs.map (linkedReport G.nextStage G.addr Stage.exponents)) =
+ 6*(t*Z)+2 := by
+ rw [linked_terminal_cost _ _ _ stop,show RAMBuckets.cost Report.probes rs = _ from raw,
+ show rs.length = _ from len]
+ omega
+ refine ⟨cost,cost.trans_le (by omega),?_⟩
+ intro r hr
+ obtain ⟨source,hs,rfl⟩ := List.mem_map.mp hr
+ obtain ⟨hp,ht⟩ := each source hs
+ constructor
+ · rw [linkedReport_probes,stop]
+ simp; omega
+ · exact (linkedReport_length_le G.nextStage G.addr Stage.exponents source).trans (by omega)
+
+/-- The physical pair's packed source interval is bounded by the prescribed
+two exterior capacities and the total label count. -/
+theorem auxiliary_word_bound (s : LiveHeaderSchedule.Sizes) (i : Fin (2^s.h)) (N t : ℕ) (labels : N ≤ t) :
+ populated (PairedChain.lengths s.h s.delta s.advice i) N ≤ auxWords s t := by
+ let L := PairedChain.lengths s.h s.delta s.advice i
+ have left : L.leftCut ≤ (s.h+1)*s.delta := L.leftFit
+ have right : L.rightCut ≤ (s.h+1)*s.delta := L.rightFit
+ change 3+2*(s.h+2)+s.advice+L.leftCut+L.rightCut+N ≤ _
+ unfold auxWords
+ omega
+
+/-- A successful initializer burst is the native 78-event trace publishing
+all seven descriptors. It has exactly 23 source probes and then transfers
+to the auxiliary copy stage. This holds for arbitrary successful fuel. -/
+theorem initializer_cost (G : PairStages.Group) (L : PrimedInputRAM.Lengths) (N : ℕ) (shadow table : Word G.w)
+ (src : Fin 7 → Word G.w) (m : Memory G.w) (tableFit : table.val+21 ≤ 2^G.w)
+ (left : m (src 0).val = (L.leftCut : Word G.w)) (right : m (src 0+2).val = (L.rightCut : Word G.w))
+ (fuel : ℕ) (bits : List Bool) (r : Report G.w)
+ (run : let P := (initTable.instantiate G.w (initData L N shadow table src)).program
+ execute P fuel (P.start 0) m bits = some r) :
+ let linked := linkedReport G.nextStage G.addr Stage.auxiliaryInit r
+ bits = [] ∧ r.result = none ∧ linked.probes = 25 ∧ RAMBuckets.cost Report.probes [linked] = 26 ∧
+ RAMBuckets.cost Report.probes [linked] ≤ 100 ∧ linked.events.length = 91 := by
+ obtain ⟨es,hs,_,_,hlen,hp,_⟩ := LiveAuxiliaryDescriptorInit.init_native L N shadow table (src 0) src 0 m tableFit left right
+ let P := (initTable.instantiate G.w (initData L N shadow table src)).program
+ have hr : execute P 79 (P.start 0) m [] = some ⟨es,none⟩ := by
+ change execute ((LiveOneShot.oneShot (PrimedStackRAM.template LiveAuxiliaryDescriptorInit.ops 27)).instantiate G.w
+ (initData L N shadow table src)).program 79 _ _ _ = _
+ rw [LiveOneShot.execute_oneShot]
+ change (execute (LiveAuxiliaryDescriptorInit.program L N shadow table (src 0) src) 79
+ ((LiveAuxiliaryDescriptorInit.program L N shadow table (src 0) src).start 0) m []).map _ = _
+ rw [hs]
+ rfl
+ obtain ⟨hb,rfl⟩ := execute_prefix_unique hr (suffix := bits) (by simpa only [List.nil_append] using run)
+ let raw : Report G.w := ⟨es,none⟩
+ have pr : (linkedReport G.nextStage G.addr Stage.auxiliaryInit raw).probes = 25 := by
+ rw [linkedReport_probes]
+ change countProbes es+1+1 = 25
+ omega
+ refine ⟨hb,rfl,pr,?_,?_,?_⟩
+ · change 1+(linkedReport G.nextStage G.addr Stage.auxiliaryInit raw).probes+0 = 26
+ rw [pr]
+ · change 1+(linkedReport G.nextStage G.addr Stage.auxiliaryInit raw).probes+0 ≤ 100
+ rw [pr]; decide
+ · change ((dispatchEvents G.addr Stage.auxiliaryInit) ++ es ++ transferEvents G.addr Stage.auxiliaryCopy).length = 91
+ simp only [List.length_append,hlen]
+ rfl
+
+/-- Every actually nominated histogram has one linked burst per production
+label and one closing burst, each costing three units. -/
+theorem nomination_resources (G : PairStages.Group) (fit : PairStages.Group.Nominations.Fits G)
+ (m : Memory G.w) (tag : G.tagged Stage.nominations m) (μ : PairStages.Group.Nominations.Nom G) :
+ let logs := (PairStages.Group.Nominations.indexed G fit m tag).logs μ
+ OutsideTraces.Resources logs (4*(G.constants.labels.eval G.g+1)) 3 (5*(2*G.g.d)+23) := by
+ dsimp only
+ constructor
+ · rw [PairStages.Group.Nominations.logs_cost]
+ change (G.constants.grammarLabels.eval G.g+1)*3 ≤ 4*(G.constants.grammarLabels.eval G.g+G.constants.motifLabels+1)
+ omega
+ · intro r hr
+ rw [PairStages.Group.Nominations.logs_probes G fit m tag μ r hr]
+ · intro r hr
+ have ht : r.events.length ∈ ((PairStages.Group.Nominations.indexed G fit m tag).logs μ).map (fun u => u.events.length) := List.mem_map.mpr ⟨r,hr,rfl⟩
+ rw [PairStages.Group.Nominations.logs_lengths G fit m tag μ] at ht
+ rcases List.mem_append.mp ht with ha | hc
+ · rw [(List.mem_replicate.mp ha).2]
+ · rw [List.mem_singleton.mp hc]
+ omega
+
+theorem exponent_resources (G : PairStages.Group) (t Z : ℕ) (m : Memory G.w) :
+ OutsideTraces.Resources ((stageReports G.exponentPub t Z m).map (linkedReport G.nextStage G.addr Stage.exponents))
+ (7*(t*Z+1)) 6 78 := by
+ obtain ⟨_,hc,each⟩ := exponent_cost G t Z m
+ exact ⟨hc, fun r hr => by have hp := (each r hr).1; omega,
+ fun r hr => by have ht := (each r hr).2; omega⟩
+
+theorem initializer_resources (G : PairStages.Group) (L : PrimedInputRAM.Lengths) (N : ℕ) (shadow table : Word G.w)
+ (src : Fin 7 → Word G.w) (m : Memory G.w) (tableFit : table.val+21 ≤ 2^G.w)
+ (left : m (src 0).val = (L.leftCut : Word G.w)) (right : m (src 0+2).val = (L.rightCut : Word G.w))
+ (fuel : ℕ) (bits : List Bool) (r : Report G.w)
+ (run : let P := (initTable.instantiate G.w (initData L N shadow table src)).program
+ execute P fuel (P.start 0) m bits = some r) :
+ OutsideTraces.Resources [linkedReport G.nextStage G.addr Stage.auxiliaryInit r] 100 26 92 := by
+ obtain ⟨_,_,hp,_,cost,clock⟩ := initializer_cost G L N shadow table src m tableFit left right fuel bits r run
+ refine ⟨cost,?_,?_⟩
+ · intro a ha
+ obtain rfl := List.mem_singleton.mp ha
+ rw [hp]
+ · intro a ha
+ obtain rfl := List.mem_singleton.mp ha
+ rw [clock]
+
+private theorem cost_length {α : Type*} (p : α → ℕ) (xs : List α) (b : ℕ)
+ (each : ∀ x ∈ xs, 1+p x ≤ b) : RAMBuckets.cost p xs ≤ b*xs.length := by
+ induction xs with
+ | nil => simp [RAMBuckets.cost]
+ | cons x xs ih =>
+ have hx := each x (by simp)
+ have ht := ih fun a ha => each a (List.mem_cons_of_mem _ ha)
+ simp only [RAMBuckets.cost,List.length_cons,Nat.mul_succ]
+ omega
+
+/-- Every accepting run through the runtime-guarded copy component has
+precisely the native sparse-copy reports. Dispatch and handoff are included
+in all three bounds, and arbitrary choices cannot shorten the required copy. -/
+theorem copy_resources (G : PairStages.Group) (s : LiveHeaderSchedule.Sizes) (i : Fin (2^s.h)) (t : ℕ)
+ {base : ℕ} {desc : Word G.w} {src : Fin 7 → Word G.w} {hist : List (Word G.w)} (labels : hist.length ≤ t)
+ {hdr : Header (PairedChain.lengths s.h s.delta s.advice i) → Bool} {m : Memory G.w}
+ (fit : base+span (PairedChain.lengths s.h s.delta s.advice i) hist.length ≤ 2^G.w)
+ (width : populated (PairedChain.lengths s.h s.delta s.advice i) hist.length < 2^G.w)
+ (sep : Separated desc base (PairedChain.lengths s.h s.delta s.advice i) hist.length src fit)
+ (ready : Prepared desc base (PairedChain.lengths s.h s.delta s.advice i) hdr hist src m)
+ (fuel : ℕ) (room : 68 ≤ fuel)
+ (outside : G.addr.val < base ∨ base+span (PairedChain.lengths s.h s.delta s.advice i) hist.length ≤ G.addr.val)
+ {bs rs} (run : let P := (LiveAuxiliaryStages.copy.instantiate G.w (LiveAuxiliaryStages.copyData desc)).program
+ runSegment P fuel (some 0) m bs = some rs) (halt : endState (some (0 : Word G.w)) rs = none) :
+ OutsideTraces.Resources (rs.map (linkedReport G.nextStage G.addr Stage.auxiliaryCopy)) (16*(auxWords s t+1)) 15 115 := by
+ obtain ⟨active,closed,hraw,hh,_,hlen,each,hclosed,pclosed,_,_⟩ :=
+ LiveAuxiliaryStages.guarded_copy_native fit width sep fuel room G.addr outside ready
+ obtain ⟨_,rfl⟩ := accepted_empty_unique hraw hh run halt
+ let out := (active++[closed]).map (linkedReport G.nextStage G.addr Stage.auxiliaryCopy)
+ have per (r : Report G.w) (hr : r ∈ out) : 1+r.probes ≤ 15 ∧ r.events.length+1 ≤ 115 := by
+ obtain ⟨raw,hraw,rfl⟩ := List.mem_map.mp hr
+ have bounds : raw.probes ≤ 12 ∧ raw.events.length < 68 := by
+ rcases List.mem_append.mp hraw with live | done
+ · exact ⟨(each raw live).2.1,(each raw live).1⟩
+ · obtain rfl := List.mem_singleton.mp done
+ omega
+ have hlen := linkedReport_length_le G.nextStage G.addr Stage.auxiliaryCopy raw
+ change _ ≤ raw.events.length + 2*21+5 at hlen
+ rw [linkedReport_probes]
+ split <;> omega
+ refine ⟨?_,fun r h => (per r h).1, fun r h => (per r h).2⟩
+ have hc := cost_length Report.probes out 15 (fun r h => (per r h).1)
+ have n : out.length = active.length+1 := by simp [out]
+ have small := auxiliary_word_bound s i hist.length t labels
+ change RAMBuckets.cost Report.probes out ≤ _
+ omega
+
+open PairStages.Group.Auxiliary
+
+/-- Resource bound on the actual initializer logs of an indexed chronology.
+Its single source report follows from native execution on the seven producer
+arrays, so this applies to any indexing of the same component paths. -/
+theorem initializer_logs_resources (G : PairStages.Group) (i : Fin (2^(sizes G).h)) {m : Memory G.w}
+ {hist : List (Word G.w)} {hdr : Header (pairLengths G i) → Bool}
+ (hlen : hist.length = G.constants.grammarLabels.eval G.g)
+ (areas : Areas (desc G) (shadow G) (pairLengths G i) hist.length (source G))
+ (inputs : InputArrays (pairLengths G i) hdr hist (source G) m) {ι : Type*}
+ (A : PairStages.Group.Indexed G Stage.auxiliaryInit m ι) (u : ι) :
+ OutsideTraces.Resources (A.logs u) 100 26 92 := by
+ let L := pairLengths G i
+ let path := A.traces u
+ let rs := ordinaryReports path
+ let f := G.clockAt Stage.auxiliaryInit
+ let P := (initTable.instantiate G.w (initData L hist.length (shadow G) (desc G) (source G))).program
+ have hr : runSegment P f (some 0) m path.val = some rs := by
+ have h := (PairStages.Group.component_segment G Stage.auxiliaryInit f (some 0) m path.val).symm.trans (ordinaryRun path)
+ change runSegment (initTable.instantiate G.w
+ (Pieces.word G.g G.lit ∘ InputOperand.geometry ∘ StageOperands.auxiliary G.constants)).program _ _ _ _ = _ at h
+ rwa [init_data G i hist hlen] at h
+ have hh : endState (some 0) rs = none := path.property.choose_spec.2.1
+ have left : m (source G 0).val = (L.leftCut : Word G.w) := by simpa [cutLength] using inputs.lengths 0
+ have right : m (source G 0+2).val = (L.rightCut : Word G.w) := by simpa [cutLength] using inputs.lengths 2
+ change OutsideTraces.Resources (rs.map (linkedReport G.nextStage G.addr Stage.auxiliaryInit)) 100 26 92
+ cases stream : path.val with
+ | nil =>
+ rw [stream,runSegment,Option.some.injEq] at hr
+ rw [← hr] at hh
+ contradiction
+ | cons b bs =>
+ rw [stream,runSegment] at hr
+ cases he : execute P f (P.start 0) m b with
+ | none => simp [he] at hr
+ | some rep =>
+ rw [he,Option.map_eq_some_iff] at hr
+ obtain ⟨tail,ht,same⟩ := hr
+ have cost := initializer_cost G L hist.length (shadow G) (desc G) (source G) m areas.tableFit left right f b rep he
+ rw [cost.2.1] at ht
+ cases bs with
+ | cons _ _ => contradiction
+ | nil =>
+ change some [] = some tail at ht
+ obtain rfl : tail = [] := (Option.some.inj ht).symm
+ rw [← same]
+ exact initializer_resources G L hist.length (shadow G) (desc G) (source G) m areas.tableFit left right f b rep he
+
+/-- Resource bound on the actual copy logs of any indexed chronology.
+The public-bank equality recovers the guarded copy component at this stage. -/
+theorem copy_logs_resources (G : PairStages.Group) (i : Fin (2^(sizes G).h)) {m : Memory G.w}
+ {hist : List (Word G.w)} {hdr : Header (pairLengths G i) → Bool}
+ (labels : hist.length ≤ G.constants.labels.eval G.g)
+ (areas : Areas (desc G) (shadow G) (pairLengths G i) hist.length (source G))
+ (ready : Prepared (desc G) (shadow G).val (pairLengths G i) hdr hist (source G) m)
+ (clock : 68 ≤ G.clockAt Stage.auxiliaryCopy) (before : G.addr.val < (shadow G).val)
+ {ι : Type*} (A : PairStages.Group.Indexed G Stage.auxiliaryCopy m ι) (u : ι) :
+ OutsideTraces.Resources (A.logs u) (16*(auxWords (sizes G) (G.constants.labels.eval G.g)+1)) 15 115 := by
+ let path := A.traces u
+ let f := G.clockAt Stage.auxiliaryCopy
+ have hr := (PairStages.Group.component_segment G Stage.auxiliaryCopy f (some 0) m path.val).symm.trans (ordinaryRun path)
+ change runSegment (LiveAuxiliaryStages.copy.instantiate G.w
+ (Pieces.word G.g G.lit ∘ InputOperand.geometry ∘ StageOperands.auxiliaryCopy G.constants)).program _ _ _ _ = _ at hr
+ rw [copy_data] at hr
+ exact copy_resources G (sizes G) i _ labels areas.shadowFit areas.countFit areas.separated ready f clock
+ (Or.inl before) hr path.property.choose_spec.2.1
+
+end LiveProgram.OutsideBudget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsidePreparedGroup.lean b/lean/OAI/Computability/VPVNP/LiveOutsidePreparedGroup.lean
new file mode 100644
index 0000000000..a6de640dde
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsidePreparedGroup.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.LiveOutsidePreparedPair
+import OAI.Computability.VPVNP.LiveOutsideGroupTraces
+
+/-!
+# Charging the prepared first-half branch at the actual native cap
+
+The auxiliary preparation supplies the two indexed stages and the input
+memory facts used to bound their native logs. The only separately charged
+work is the compressed pair simulation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideTraces
+
+open BurstRAM BurstRAM.PrivateRAM PairStages.Group PairStages.Group.Auxiliary
+open LiveAuxiliaryHeaders PrimedInputRAM
+
+variable (G : PairStages.Group) (i : Fin (2^(Auxiliary.sizes G).h))
+variable (F : Nominations.Fits G) (m : Memory G.w) (tag : G.tagged Stage.nominations m)
+variable (hdr : Header (pairLengths G i) → Bool)
+variable (B : ∀ μ, PreparedBranch G m i hdr (Nominations.indexed G F m tag) μ)
+variable {Path : Nominations.Nom G → Type*}
+variable (pair : ∀ μ, Indexed G Stage.pair ((B μ).copy.memory ()) (Path μ))
+
+/-- The native chronology induced by the actually prepared auxiliary input
+and the indexed compressed computation. -/
+noncomputable def preparedChronology : Chronology G m (Nominations.Nom G) Path :=
+ ⟨Nominations.indexed G F m tag,fun μ => (B μ).init,fun μ => (B μ).copy,pair⟩
+
+/-- A direct bound on all non-compression reports of an accepted first-half
+path. No separate clock or probe estimates for the three preparation stages
+are required. -/
+theorem prepared_outside (header : List (Report G.w))
+ (hr : Resources header (LiveHeaderSchedule.costBound (OutsideTraces.sizes G)) 11 154)
+ (fit : shadowBase G+span (pairLengths G i) (histLength G) ≤ 2^G.w)
+ (clock : 68 ≤ G.clockAt Stage.auxiliaryCopy) (μ : Nominations.Nom G) (q : Path μ)
+ (raw : ℕ) (first last empty : Bool) :
+ Resources (outsidePair (preparedChronology G i F m tag hdr B pair) header μ q)
+ (OutsideBudget.actualBound G.constants G.g raw first last empty)
+ 26 (max 154 (5*(2*G.g.d)+23)) := by
+ obtain ⟨hn,hi,hc⟩ := OutsideBudget.prepared_resources G i F m tag μ (B μ) fit clock
+ exact pair_outside_resources (preparedChronology G i F m tag hdr B pair) header μ q hr hn hi hc raw first last empty
+
+/-- The report-cap premise of `Chronology.count` on the prepared pair.
+An accepted compressed computation consumes the remaining bucket capacity. -/
+theorem prepared_enough (header : List (Report G.w))
+ (hr : Resources header (LiveHeaderSchedule.costBound (OutsideTraces.sizes G)) 11 154)
+ (fit : shadowBase G+span (pairLengths G i) (histLength G) ≤ 2^G.w)
+ (clock : 68 ≤ G.clockAt Stage.auxiliaryCopy) (μ : Nominations.Nom G) (q : Path μ)
+ (raw S H : ℕ) (first last empty : Bool)
+ (hout : OutsideBudget.actualBound G.constants G.g raw first last empty ≤ S) (hH : 26 ≤ H)
+ (pairCost : RAMBuckets.cost Report.probes ((pair μ).logs q) ≤ S*(H-1))
+ (pairCalls : ∀ r ∈ (pair μ).logs q, 1+r.probes ≤ H) :
+ let A := preparedChronology G i F m tag hdr B pair
+ withinCaps S H ((header++[modePairReport G]) ++ (A.prefixLogs μ q ++ exponentLogs A μ q)) := by
+ have outside := prepared_outside G i F m tag hdr B pair header hr fit clock μ q raw first last empty
+ exact pair_withinCaps (preparedChronology G i F m tag hdr B pair) header μ q outside hout hH pairCost pairCalls
+
+end LiveProgram.OutsideTraces
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsidePreparedPair.lean b/lean/OAI/Computability/VPVNP/LiveOutsidePreparedPair.lean
new file mode 100644
index 0000000000..2ea1cf3e42
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsidePreparedPair.lean
@@ -0,0 +1,40 @@
+import OAI.Computability.VPVNP.LiveOutsidePairStages
+import OAI.Computability.VPVNP.LiveProgramPairPreparation
+
+/-! # Outside resource bounds of a physically prepared first-half group -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideBudget
+
+open BurstRAM PrimedInputRAM LiveAuxiliaryHeaders PairStages.Group PairStages.Group.Auxiliary
+
+/-- The three non-compression preparation logs in the first-half chronology
+satisfy their resource bounds on the actual memories, histogram and pair
+header. The workspace fit supplies all descriptor and copy separations. -/
+theorem prepared_resources (G : PairStages.Group) (i : Fin (2^(sizes G).h)) (F : Nominations.Fits G)
+ (m : Memory G.w) (tag : G.tagged Stage.nominations m) (μ : Nominations.Nom G)
+ {hdr : Header (pairLengths G i) → Bool}
+ (branch : PreparedBranch G m i hdr (Nominations.indexed G F m tag) μ)
+ (fit : shadowBase G+span (pairLengths G i) (histLength G) ≤ 2^G.w)
+ (clock : 68 ≤ G.clockAt Stage.auxiliaryCopy) :
+ let t := G.constants.labels.eval G.g
+ OutsideTraces.Resources ((Nominations.indexed G F m tag).logs μ) (4*(t+1)) 3 (5*(2*G.g.d)+23) ∧
+ OutsideTraces.Resources (branch.init.logs ()) 100 26 92 ∧
+ OutsideTraces.Resources (branch.copy.logs ()) (16*(auxWords (sizes G) t+1)) 15 115 := by
+ have hlen : (histogram G μ).length = histLength G := by simp [histogram]
+ have ht : (histogram G μ).length ≤ G.constants.labels.eval G.g := by
+ rw [hlen]
+ exact Nat.le_add_right (histLength G) G.constants.motifLabels
+ have layout := geometry G i (histogram G μ).length hlen (hlen ▸ fit)
+ exact ⟨nomination_resources G F m tag μ,
+ initializer_logs_resources G i hlen layout.areas branch.initInputs branch.init (),
+ copy_logs_resources G i ht layout.areas branch.copyPrepared clock layout.tagShadow branch.copy ()⟩
+
+end LiveProgram.OutsideBudget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsideTailCount.lean b/lean/OAI/Computability/VPVNP/LiveOutsideTailCount.lean
new file mode 100644
index 0000000000..6592eefc86
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsideTailCount.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.LiveOutsideTailStages
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorRouteCost
+
+/-! # Applying the actual outside-stage budgets to the tail path count
+
+The cost of the completed prefix is charged before counting the transition.
+The gathered bit words and the endpoint sentinel have their canonical linked
+logs. Thus a single numerical budget suffices for all paths of a noninitial
+group, including groups whose cut fields decode to malformed configurations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideTailCount
+
+open BurstRAM LiveStageLink PairStages LiveEvaluatorEncoding LiveEvaluatorRAM LiveConfigGather
+open LiveEvaluatorRAM.Schedule (calls)
+open EvaluatorRoutes OutsideTraces OutsideTailStages
+open scoped Fin.CommRing
+
+variable (G : PairStages.Group) {M : ℕ}
+
+/-- A common bound for either exit of the last router. -/
+def routeCost (w M : ℕ) := 4+fieldWords M*(w+4)
+
+/-- The cost allowance for transition preparation and all cell checks, including a dispatch
+charge for every call. -/
+def transitionCost (M : ℕ) := (10+7*(2*(2*M+1)))+calls M
+
+theorem output_resources {m : Memory G.w} {b : Option (Code G.evaluator.extra M)} (o : Output G m b) :
+ Resources o.logs (routeCost G.w M) (G.w+4) (instructionBound G) := by
+ refine ⟨o.logs_cost,o.logs_calls,?_⟩
+ cases o with
+ | cut _ bits => exact (gatherRoute G true bits).work
+ | final => exact (putRoute G true).work
+
+/-- Count starting at the last router, from an already accounted prefix. -/
+theorem lastCount_capped {h Δ S H : ℕ} (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w Δ)
+ (init : Code G.evaluator.extra M) (bits : LiveChain.TailBits h Δ) (i : Fin (2^h)) (m : Memory G.w)
+ (fit : GeometryFit G M) (tag : G.tagged Stage.last m)
+ (incoming : ∀ c, LiveEvaluatorTail.boundary layout init bits i.castSucc = some c ↔ ConfigAt m (G.transitionPub 1) c)
+ (o : Output G m (LiveEvaluatorTail.boundary layout init bits i.succ))
+ (pre : List (Report G.w)) {a b instr : ℕ} (hr : Resources pre a b instr)
+ (hcall : max b (max 11 (G.w+4)) ≤ H) (budget : a+routeCost G.w M+transitionCost M ≤ S*H) :
+ Nat.card (ActualPaths G.P G.clock 0 m (fun rs => withinCaps S H (pre++rs))) =
+ ChainAssignments.tailCount G.evaluator layout init bits i := by
+ have hrs := hr.append (output_resources G o)
+ apply lastCount G layout init bits i m fit tag incoming o pre
+ · omega
+ · intro r hm; have hp := hrs.calls r hm; omega
+ · have hc := hrs.cost
+ unfold transitionCost at budget
+ omega
+
+/-- Count from the first router of every noninitial tail group. The
+incoming gather, outgoing route, and complete linked transition fit the
+same cap chosen before the choices of that transition. -/
+theorem nonfirstCount_capped {h Δ S H : ℕ} (layout : LiveEvaluatorTail.Layout G.evaluator.extra M G.w Δ)
+ (init : Code G.evaluator.extra M) (bits : LiveChain.TailBits h Δ) (i : Fin (2^h)) (m : Memory G.w)
+ (fit : GeometryFit G M) (tag : G.tagged Stage.firstTail m) (flag : m ((Router.firstTail.data G.g G.lit) 0).val = 0)
+ (F : EvaluatorGather.Fit G false (fieldWords M)) (raw : Fin (fieldWords M*G.w) → Bool)
+ (image : ArrayBitImage m (EvaluatorGather.operands G false 0) raw)
+ (fresh : G.addr.val < (EvaluatorGather.operands G false 0).val ∨
+ (EvaluatorGather.operands G false 0).val+fieldWords M*G.w ≤ G.addr.val)
+ (value : LiveEvaluatorTail.boundary layout init bits i.castSucc = (format F.width fit.prep.states).decode raw)
+ (o : Output G (gatherMemory G false F m raw) (LiveEvaluatorTail.boundary layout init bits i.succ))
+ (pre : List (Report G.w)) {a b instr : ℕ} (hr : Resources pre a b instr)
+ (hcall : max b (max 11 (G.w+4)) ≤ H) (budget : a+2*routeCost G.w M+transitionCost M ≤ S*H) :
+ Nat.card (ActualPaths G.P G.clock 0 m (fun rs => withinCaps S H (pre++rs))) =
+ ChainAssignments.tailCount G.evaluator layout init bits i := by
+ have hi : Resources (gatherLogs G false raw) (routeCost G.w M) (G.w+4) (instructionBound G) :=
+ ⟨gatherLogs_cost G false raw,gatherLogs_calls G false raw,(gatherRoute G false raw).work⟩
+ have hrs := (hr.append hi).append (output_resources G o)
+ apply nonfirstCount G layout init bits i m fit tag flag F raw image fresh value o pre
+ · omega
+ · intro r hm; have hp := hrs.calls r hm; omega
+ · have hc := hrs.cost
+ unfold transitionCost at budget
+ omega
+
+end LiveProgram.OutsideTailCount
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsideTailStages.lean b/lean/OAI/Computability/VPVNP/LiveOutsideTailStages.lean
new file mode 100644
index 0000000000..b1ffc3727e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsideTailStages.lean
@@ -0,0 +1,359 @@
+import OAI.Computability.VPVNP.LiveOutsideTraces
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorRoutes
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorTransition
+import OAI.Computability.VPVNP.LiveProgramAdviceRun
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorSuffix
+
+/-! # Resource bounds for the reports of the native tail stages
+
+The endpoint stages issue one control-word write, and each configuration
+gather contributes one report per word of the cut. The dynamic advice
+prefix and the transition use the same linked reports as the path-count
+handoffs. Bounds include both the outer stage dispatcher and its tag write.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideTailStages
+
+open BurstRAM LiveStageLink LiveEvaluatorTailCost OutsideTraces LiveEvaluatorAdviceBanks
+open scoped Fin.CommRing
+
+variable (G : PairStages.Group)
+
+/-- The resource parameters for this tail execution, using the raw prefix length and the
+group's label, exponent, tape, and word dimensions. -/
+def params (raw : ℕ) : Parameters :=
+ ⟨raw,G.constants.labels.eval G.g,G.constants.Z.eval G.g,G.constants.radius.eval G.g,G.w⟩
+
+/-- The charge for packing the length, advice prefix, and ordinal rows and publishing their
+operand frames. -/
+def packWork (u : Parameters) := 6*u.lengthPackCalls+23+11*u.prefixPackCalls+6*u.orderPackCalls
+
+/-- The charge for copying the input bits, writing the runtime skeleton, and scattering the
+exponents. -/
+def inputWork (u : Parameters) := 10*(max 1 u.advice)+8*u.runtimeBits+11*(max 1 u.exponentBits)
+
+/-- The incoming-side budget for either a gathered configuration or an initial control write
+with any required advice and input setup. -/
+def firstBudget (u : Parameters) (first empty : Bool) :=
+ if first then (if empty then 4 else 4+packWork u+inputWork u) else (u.wordWidth+4)*u.configWords
+
+/-- The outgoing-side budget for either a gathered configuration or the final accepting control
+write. -/
+def lastBudget (u : Parameters) (last : Bool) := if last then 4 else (u.wordWidth+4)*u.configWords
+
+/-- Uniform maximum cost of one actual linked tail report. -/
+def callBound (w : ℕ) := max 23 (w+4)
+
+/-- The advice and exponent sweep clocks are constants. The gather scans
+one physical RAM word, and the terminal call uses its own evaluator clock. -/
+def instructionBound := max 130 (max (8*G.w+67) (LiveEvaluatorRAM.Schedule.callFuel G.evaluator+47))
+
+theorem groupBudget (u : Parameters) (first last empty : Bool) :
+ 4+firstBudget u first empty+4+lastBudget u last+(u.transitionCost+2*u.configWords) =
+ groupBound u first last empty := by
+ cases first <;> cases last <;> cases empty <;>
+ simp [firstBudget,lastBudget,groupBound,packWork,inputWork] <;> omega
+
+private theorem resources_of_members {w : ℕ} {rs : List (Report w)} {per inst : ℕ}
+ (hc : ∀ r ∈ rs, 1+r.probes ≤ per) (hi : ∀ r ∈ rs, r.events.length+1 ≤ inst) :
+ Resources rs (per*rs.length) per inst := by
+ refine ⟨?_,hc,hi⟩
+ induction rs with
+ | nil => simp [RAMBuckets.cost]
+ | cons r rs ih =>
+ have hp := hc r (by simp)
+ have h := ih (fun r hr => hc r (by simp [hr])) (fun r hr => hi r (by simp [hr]))
+ simp only [RAMBuckets.cost,List.length_cons,Nat.mul_succ]
+ omega
+
+private theorem enlarge {w : ℕ} {rs : List (Report w)} {a b c a' b' c' : ℕ}
+ (h : Resources rs a b c) (ha : a ≤ a') (hb : b ≤ b') (hc : c ≤ c') : Resources rs a' b' c' :=
+ ⟨h.cost.trans ha, fun r hr => (h.calls r hr).trans hb, fun r hr => (h.work r hr).trans hc⟩
+
+theorem sentinel (final : Bool) :
+ Resources (G.linkedLogs (EvaluatorSentinel.stage final) [EvaluatorSentinel.report G final])
+ 4 (callBound G.w) (instructionBound G) := by
+ let raw := EvaluatorSentinel.report G final
+ let rep := linkedReport G.nextStage G.addr (EvaluatorSentinel.stage final) raw
+ have hraw : raw.probes = 1 := rfl
+ have hlen : raw.events.length = 3 := rfl
+ have hp : 1+rep.probes ≤ 4 := by
+ rw [show rep = _ from rfl,linkedReport_probes]; split <;> omega
+ have hl := linkedReport_length_le G.nextStage G.addr (EvaluatorSentinel.stage final) raw
+ change rep.events.length ≤ raw.events.length + 2*21+5 at hl
+ change Resources [rep] _ _ _
+ refine ⟨by simp [RAMBuckets.cost]; omega, ?_, ?_⟩
+ · intro r h; obtain rfl := List.mem_singleton.mp h; unfold callBound; omega
+ · intro r h; obtain rfl := List.mem_singleton.mp h; unfold instructionBound; omega
+
+/-- Gathered word reports carry the actual source reads in their native
+order. This bound also covers empty lists of words. -/
+theorem gather {k : ℕ} (outgoing : Bool) (bits : Fin (k*G.w) → Bool) :
+ Resources (G.linkedLogs (EvaluatorGather.stage outgoing) (EvaluatorGather.reports G outgoing bits))
+ ((G.w+4)*k) (callBound G.w) (instructionBound G) := by
+ let src := EvaluatorGather.reports G outgoing bits
+ let logs := G.linkedLogs (EvaluatorGather.stage outgoing) src
+ have hl : logs.length = k := by simp [logs,src,EvaluatorGather.reports]
+ have hb (r : Report G.w) (hr : r ∈ logs) : 1+r.probes ≤ G.w+4 ∧ r.events.length+1 ≤ 8*G.w+67 := by
+ obtain ⟨r',hr',rfl⟩ := List.mem_map.mp hr
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp hr'
+ let pub := EvaluatorGather.operands G outgoing
+ let words := (RAMSerialization.arrayBits k G.w).symm bits
+ have hp : (LiveConfigGather.wordReport pub words i).probes = G.w+1 := LiveConfigGather.report_probes ..
+ have hh : (LiveConfigGather.wordReport pub words i).events.length = 8*G.w+19 := by
+ simp [LiveConfigGather.wordReport,LiveConfigGather.report,LiveConfigGather.events_length]
+ have he := linkedReport_length_le G.nextStage G.addr (EvaluatorGather.stage outgoing) (LiveConfigGather.wordReport pub words i)
+ change _ ≤ (LiveConfigGather.wordReport pub words i).events.length + 2*21+5 at he
+ constructor
+ · change 1+(linkedReport G.nextStage G.addr _ (LiveConfigGather.wordReport pub words i)).probes ≤ _
+ rw [linkedReport_probes,hp]; split <;> omega
+ · change (linkedReport G.nextStage G.addr _ (LiveConfigGather.wordReport pub words i)).events.length+1 ≤ _
+ omega
+ exact enlarge (resources_of_members (fun r hr => (hb r hr).1) (fun r hr => (hb r hr).2))
+ (by rw [hl]) (le_max_right ..) (by unfold instructionBound; omega)
+
+/-- The singleton physical report for the first-tail or last-group router's choice of endpoint
+write or configuration gather. -/
+def jump (initial flag : Bool) : List (Report G.w) :=
+ let r := if initial then Router.firstTail else Router.last
+ let i : Fin 3 := if flag then 1 else 0
+ let dest := if initial then (if flag then Stage.initialState else Stage.oldGather)
+ else (if flag then Stage.finalState else Stage.newGather)
+ [r.outerReport G.evaluator G.g G.lit (r.jumpReport G.g G.lit i (i.val : Word G.w) dest)]
+
+theorem jump_resources (initial flag : Bool) :
+ Resources (jump G initial flag) 4 (callBound G.w) (instructionBound G) := by
+ apply enlarge (OutsideTraces.router_jump ..) le_rfl
+ · unfold callBound; omega
+ · unfold instructionBound; omega
+
+theorem advice_work (raw : List Bool) (m : Memory G.w)
+ (L : PreparedLayout (Advice.lp G.constants G.g) (Advice.fp G.constants G.g) (Advice.op G.constants G.g)
+ raw (G.constants.labels.eval G.g) (Nat.clog 2 (G.constants.labels.eval G.g))) :
+ Advice.work G.constants G.g raw m = packWork (params G raw.length) := by
+ let lp := Advice.lp G.constants G.g
+ let fp := Advice.fp G.constants G.g
+ let op := Advice.op G.constants G.g
+ let rp := rawOperands lp fp raw m
+ have hraw : (rp 4).val = raw.length ⌈/⌉ G.w := rawOperands_rows L m
+ have hwidth : (rp 2).val = G.w := L.frameWidth
+ change 6*(max 1 ((lp 4).val*((lp 2).val+1))) + 23 + 11*(max 1 ((rp 4).val*((rp 2).val+1))) +
+ 6*(max 1 ((op 4).val*((op 2).val+1))) = _
+ rw [hraw,hwidth,L.lengthRows,L.lengthWidth,L.ordinalRows,L.ordinalWidth,one_mul]
+ simp [params,packWork,Parameters.lengthPackCalls,Parameters.prefixPackCalls,Parameters.orderPackCalls,
+ Nat.ceilDiv_eq_add_pred_div]
+
+/-- Private-clock independence for two complete executions on the same
+choice words. Only the bound on each microcall changes. -/
+private theorem same_logs {w : ℕ} {C : Type*} {P : BurstRAM.Program w C} {s : Option (Word w)}
+ {m : Memory w} {bs : List (List Bool)} {a b : ℕ} {xs ys : List (Report w)}
+ (h : runSegment P a s m bs = some xs) (h' : runSegment P b s m bs = some ys) : xs = ys := by
+ induction bs generalizing s m xs ys with
+ | nil => simp_all [runSegment]
+ | cons z zs ih =>
+ cases s with
+ | none => contradiction
+ | some st =>
+ cases he : execute P a (P.start st) m z with
+ | none => simp [runSegment,he] at h
+ | some r =>
+ cases he' : execute P b (P.start st) m z with
+ | none => simp [runSegment,he'] at h'
+ | some r' =>
+ have eq := execute_prefix_unique (suffix := []) he (by simpa using he')
+ obtain ⟨_,rfl⟩ := eq
+ simp only [runSegment,he,he',Option.map_eq_some_iff] at h h'
+ obtain ⟨xs,hx,rfl⟩ := h
+ obtain ⟨ys,hy,rfl⟩ := h'
+ exact congrArg (r::·) (ih hx hy)
+
+/-- The actual deterministic four-stage advice prefix is charged at its
+four distinct tariffs. Its private work is bounded at the short native clock. -/
+theorem advice (m : Memory G.w) (raw : List Bool)
+ (values : Fin (G.constants.labels.eval G.g) → Word (Nat.clog 2 (G.constants.labels.eval G.g)))
+ {a padding : ℕ} (ad : Fin a → Bool)
+ (L : PreparedLayout (Advice.lp G.constants G.g) (Advice.fp G.constants G.g) (Advice.op G.constants G.g)
+ raw (G.constants.labels.eval G.g) (Nat.clog 2 (G.constants.labels.eval G.g)))
+ (copied : ∀ i : Fin a, m (((Advice.fp G.constants G.g) 0).val+i.val) = PrimedInputRAM.encodeBit G.w (ad i))
+ (htape : List.ofFn ad = distribution G.w ((Advice.fp G.constants G.g) 1).val raw values padding)
+ (fit : (Layout.shadow G.constants).eval G.g < 2^G.w) (tag : G.tagged Stage.prefixLength m)
+ {fuel : ℕ} (rs : List (Report G.w))
+ (h : runSegment G.P fuel (some 0) m (List.replicate (Advice.calls G.constants G.g raw m) []) = some rs) :
+ Resources rs (packWork (params G raw.length)) (callBound G.w) (instructionBound G) := by
+ obtain ⟨hr,hc⟩ := Advice.fourStages_budget G.constants G.evaluator G.pair G.g G.lit m raw values ad L
+ copied htape fit (cap := 130) le_rfl tag
+ obtain ⟨xs,hx,_,_,_,hw⟩ := hr
+ rw [G.program_eq] at h
+ obtain rfl := same_logs hx h
+ exact ⟨(hc _ hx).trans_eq (advice_work G raw m L), fun r hr => by
+ have := (hw r hr).1; unfold callBound; omega, fun r hr => by
+ have := (hw r hr).2; unfold instructionBound; omega⟩
+
+
+theorem gatherRoute {k : ℕ} (outgoing : Bool) (bits : Fin (k*G.w) → Bool) :
+ Resources (EvaluatorRoutes.gatherLogs G outgoing bits) (4+(G.w+4)*k) (callBound G.w) (instructionBound G) := by
+ have h := (jump_resources G (!outgoing) false).append (gather G outgoing bits)
+ simp only [max_self] at h
+ cases outgoing <;> exact h
+
+theorem putRoute (outgoing : Bool) :
+ Resources (EvaluatorRoutes.putLogs G outgoing) 8 (callBound G.w) (instructionBound G) := by
+ have h := (jump_resources G (!outgoing) true).append (sentinel G outgoing)
+ simp only [max_self] at h
+ cases outgoing <;> exact h
+
+theorem transition {M : ℕ} (hl : LiveEvaluatorRAM.PrepLayout G.evaluator G.transitionPub M)
+ (m : Memory G.w) (bits : List (List Bool)) (rs : List (Report G.w)) {fuel : ℕ}
+ (run : runSegment (LiveEvaluatorRAM.Schedule.nativeProgram G.evaluator G.transitionPub) fuel (some 0) m bits = some rs)
+ (halt : endState (some 0) rs = none) :
+ Resources (G.linkedLogs Stage.transition rs) (10+14*(2*M+1)+(4*M+3)) (callBound G.w) (instructionBound G) := by
+ obtain ⟨_,hc,hp⟩ := G.linked_transition_resources hl m bits rs run halt
+ exact ⟨hc,fun r hr => by have := (hp r hr).1; unfold callBound; omega,
+ fun r hr => by have := (hp r hr).2; unfold instructionBound; omega⟩
+
+/-- A four-stage prefix on the exact distributed advice tape. -/
+structure AdviceExecution (raw : List Bool) (logs : List (Report G.w)) where
+ /-- The physical memory at entry to the advice prefix-length stage, holding the copied
+ distributed advice bits. -/
+ memory : Memory G.w
+ /-- The word-sized ordinals published by the advice layout for the evaluator's label order. -/
+ values : Fin (G.constants.labels.eval G.g) → Word (Nat.clog 2 (G.constants.labels.eval G.g))
+ /-- The length of the distributed advice bit string copied into the physical preparation
+ buffer. -/
+ count : ℕ
+ /-- The padding length in the serialized advice distribution after accounting for the raw
+ prefix and ordinal data. -/
+ padding : ℕ
+ /-- The actual copied bits whose sequence encodes the raw advice, ordinal map, and padding. -/
+ bits : Fin count → Bool
+ layout : PreparedLayout (Advice.lp G.constants G.g) (Advice.fp G.constants G.g) (Advice.op G.constants G.g)
+ raw (G.constants.labels.eval G.g) (Nat.clog 2 (G.constants.labels.eval G.g))
+ copied : ∀ i : Fin count, memory (((Advice.fp G.constants G.g) 0).val+i.val) = PrimedInputRAM.encodeBit G.w (bits i)
+ tape : List.ofFn bits = distribution G.w ((Advice.fp G.constants G.g) 1).val raw values padding
+ fit : (Layout.shadow G.constants).eval G.g < 2^G.w
+ tagged : G.tagged Stage.prefixLength memory
+ run : runSegment G.P G.clock (some 0) memory (List.replicate (Advice.calls G.constants G.g raw memory) []) = some logs
+
+/-- The published permutation, physical middle exponents and blank tape
+of the nonempty first tail group. The suffix starts exactly in the memory
+returned by the preceding four advice stages. -/
+structure InputExecution {raw : List Bool} {ad : List (Report G.w)}
+ (prep : AdviceExecution G raw ad) (logs : List (Report G.w)) where
+ /-- The published permutation from physical dense labels to formal evaluator labels. -/
+ perm : Fin (params G raw.length).rows ≃ Fin (params G raw.length).rows
+ /-- The exponent words in physical order on the incoming midpoint cut. -/
+ dense : Fin (params G raw.length).rows → Word (params G raw.length).rowWidth
+ /-- The exponent words in formal label order, related to the dense input by the published
+ permutation. -/
+ formal : Fin (params G raw.length).rows → Word (params G raw.length).rowWidth
+ order : ∀ i, formal (perm i) = dense i
+ ordinal : ∀ i, (prep.values i).val = (perm i).val
+ stateFit : G.evaluator.extra+2 ≤ 2^G.w
+ capacity : raw.length + (params G raw.length).runtimeBits ≤ (params G raw.length).radius+1
+ incoming : ∀ q : Fin (params G raw.length).exponentBits,
+ prep.memory ((HeaderLayout.exponent G.constants.lengths Layout.header .left).eval G.g+q.val) =
+ PrimedInputRAM.encodeBit G.w (RAMSerialization.arrayBits _ _ dense q)
+ control : prep.memory ((Advice.copyBank G.constants G.g) 1).val =
+ Fin.ofNat _ (LiveEvaluatorInitialize.controlTag G.evaluator).val
+ zeros : ∀ i : Fin (LiveEvaluatorEncoding.fieldWords (params G raw.length).radius), 0 < i.val →
+ prep.memory (((Advice.copyBank G.constants G.g) 1).val+i.val) = 0
+ run : runSegment G.P G.clock (some 0) (Advice.finalMemory G.constants G.g G.lit raw prep.values prep.memory)
+ (List.replicate (max 1 raw.length + (params G raw.length).runtimeBits + max 1 (params G raw.length).exponentBits) []) =
+ some logs
+
+/-- Invoke the three linked tables at their actual addresses. The short
+clock gives the private instruction bound even when the caller replays the
+same advice and choices at a larger group clock. -/
+theorem input_resources {raw : List Bool} {ad : List (Report G.w)} (prep : AdviceExecution G raw ad)
+ {rs : List (Report G.w)} (running : G.evaluator.extra ≠ 0) (sw : InputExecution G prep rs) :
+ Resources rs (inputWork (params G raw.length)) (callBound G.w) (instructionBound G) := by
+ let short : PairStages.Group := {G with clock := 130, dispatchFit := by decide}
+ obtain ⟨final,ret⟩ := short.suffixRun_actual raw prep.memory prep.values sw.perm sw.dense sw.formal
+ sw.order sw.ordinal prep.layout prep.fit (by decide : 94 ≤ 130) running sw.stateFit sw.capacity
+ sw.incoming sw.control sw.zeros
+ obtain ⟨xs,hr,_,_,_,hp⟩ := ret.returning
+ have hc := ret.cost xs hr
+ obtain rfl := same_logs hr sw.run
+ exact ⟨hc,fun r h => by have := (hp r h).1; unfold callBound; omega,fun r h => by
+ have ht : r.events.length < 130 := (hp r h).2; unfold instructionBound; omega⟩
+
+/-- Report shapes produced by the first-tail router and its native
+deterministic prefix, before the last-group router. -/
+inductive Incoming (raw : List Bool) : Bool → List (Report G.w) → Prop
+ | interior (bits : Fin ((params G raw.length).configWords*G.w) → Bool) :
+ Incoming raw false (EvaluatorRoutes.gatherLogs G false bits)
+ | empty (h : G.evaluator.extra = 0) :
+ Incoming raw true (EvaluatorRoutes.putLogs G false)
+ | initialized (h : G.evaluator.extra ≠ 0) {ad suffix : List (Report G.w)}
+ (prep : AdviceExecution G raw ad) (sweeps : InputExecution G prep suffix) :
+ Incoming raw true (EvaluatorRoutes.putLogs G false ++ ad ++ suffix)
+
+/-- The last-group router selects either the gathered successor or its
+accepting control-word sentinel. -/
+inductive Outgoing (raw : List Bool) : Bool → List (Report G.w) → Prop
+ | interior (bits : Fin ((params G raw.length).configWords*G.w) → Bool) :
+ Outgoing raw false (EvaluatorRoutes.gatherLogs G true bits)
+ | last : Outgoing raw true (EvaluatorRoutes.putLogs G true)
+
+theorem incoming_resources (raw : List Bool) {first : Bool} {xs : List (Report G.w)} (incoming : Incoming G raw first xs) :
+ Resources xs (4+firstBudget (params G raw.length) first (decide (G.evaluator.extra=0)))
+ (callBound G.w) (instructionBound G) := by
+ cases incoming with
+ | interior b => exact gatherRoute G false b
+ | empty h => simpa [firstBudget,h] using putRoute G false
+ | initialized h prep sw =>
+ have hA := advice G prep.memory raw prep.values prep.bits prep.layout prep.copied prep.tape
+ prep.fit prep.tagged _ prep.run
+ have hh := ((putRoute G false).append hA).append (input_resources G prep h sw)
+ simp only [max_self] at hh
+ apply enlarge hh _ le_rfl le_rfl
+ simp [firstBudget,inputWork,h]
+ omega
+
+theorem outgoing_resources (raw : List Bool) {last : Bool} {ys : List (Report G.w)} (outgoing : Outgoing G raw last ys) :
+ Resources ys (4+lastBudget (params G raw.length) last) (callBound G.w) (instructionBound G) := by
+ cases outgoing with
+ | interior b => exact gatherRoute G true b
+ | last => exact putRoute G true
+
+/-- Total and per-call bounds for an actual native tail suffix, including
+both router transfers and the successful terminal transition. -/
+theorem tail_resources (raw : List Bool) {first last : Bool} {xs ys : List (Report G.w)}
+ (incoming : Incoming G raw first xs) (outgoing : Outgoing G raw last ys)
+ (hl : LiveEvaluatorRAM.PrepLayout G.evaluator G.transitionPub (params G raw.length).radius)
+ (m : Memory G.w) (bits : List (List Bool)) (rs : List (Report G.w)) {fuel : ℕ}
+ (run : runSegment (LiveEvaluatorRAM.Schedule.nativeProgram G.evaluator G.transitionPub) fuel (some 0) m bits = some rs)
+ (halt : endState (some 0) rs = none) :
+ Resources (xs++ys++G.linkedLogs Stage.transition rs)
+ (groupBound (params G raw.length) first last (decide (G.evaluator.extra=0))) (callBound G.w) (instructionBound G) := by
+ let u := params G raw.length
+ let emp := decide (G.evaluator.extra = 0)
+ have hi := incoming_resources G raw incoming
+ have ho := outgoing_resources G raw outgoing
+ have ht := transition G hl m bits rs run halt
+ have h := (hi.append ho).append ht
+ simp only [max_self] at h
+ apply enlarge h _ le_rfl le_rfl
+ change 4+firstBudget u first emp + (4+lastBudget u last) + (u.transitionCost+u.configWords) ≤ groupBound u first last emp
+ rw [← groupBudget]; omega
+
+theorem tail_majorant (raw : List Bool) {first last : Bool} {xs ys : List (Report G.w)}
+ (incoming : Incoming G raw first xs) (outgoing : Outgoing G raw last ys)
+ (hl : LiveEvaluatorRAM.PrepLayout G.evaluator G.transitionPub (params G raw.length).radius)
+ (m : Memory G.w) (bits : List (List Bool)) (rs : List (Report G.w)) {fuel : ℕ}
+ (run : runSegment (LiveEvaluatorRAM.Schedule.nativeProgram G.evaluator G.transitionPub) fuel (some 0) m bits = some rs)
+ (halt : endState (some 0) rs = none) {A W : ℕ} (ha : raw.length ≤ A) (hw : G.w ≤ W) :
+ Resources (xs++ys++G.linkedLogs Stage.transition rs)
+ (OutsideBudget.tailMajorant A (G.constants.labels.eval G.g) (G.constants.Z.eval G.g) (G.constants.radius.eval G.g) W)
+ (callBound G.w) (instructionBound G) :=
+ enlarge (tail_resources G raw incoming outgoing hl m bits rs run halt) (OutsideBudget.tail_le _ _ _ _ ha hw) le_rfl le_rfl
+
+end LiveProgram.OutsideTailStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveOutsideTraces.lean b/lean/OAI/Computability/VPVNP/LiveOutsideTraces.lean
new file mode 100644
index 0000000000..2b4df46dc7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveOutsideTraces.lean
@@ -0,0 +1,210 @@
+import OAI.Computability.VPVNP.LiveOutsideBudget
+import OAI.Computability.VPVNP.LiveHeaderAcceptance
+import OAI.Computability.VPVNP.LiveProgramUnit
+import OAI.Computability.VPVNP.LiveProgramHeader
+
+/-!
+# Outside costs of the actual live group reports
+
+The outer dispatcher reads its tag once per call and can write a successor
+tag on an accepting handoff. The bounds below charge these events on the
+real header and router logs, along with the private instruction events.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.OutsideTraces
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderSchedule ChainAssignments
+
+variable {w d : ℕ}
+
+open private guessed_addFuel from OAI.Computability.VPVNP.LiveStageLinkPaths
+
+/-- Total cost, maximal call cost, and maximal private instruction count.
+A report logs every instruction except its final return or acceptance. -/
+structure Resources (rs : List (Report w)) (total perCall instructions : ℕ) : Prop where
+ cost : RAMBuckets.cost Report.probes rs ≤ total
+ calls : ∀ r ∈ rs, 1+r.probes ≤ perCall
+ work : ∀ r ∈ rs, r.events.length+1 ≤ instructions
+
+theorem Resources.append {rs ts : List (Report w)} {a b c a' b' c' : ℕ}
+ (hr : Resources rs a b c) (ht : Resources ts a' b' c') :
+ Resources (rs++ts) (a+a') (max b b') (max c c') := by
+ constructor
+ · rw [RAMBuckets.cost_append]; exact Nat.add_le_add hr.cost ht.cost
+ · intro r h
+ exact (List.mem_append.mp h).elim (fun h => (hr.calls r h).trans (le_max_left ..))
+ (fun h => (ht.calls r h).trans (le_max_right ..))
+ · intro r h
+ exact (List.mem_append.mp h).elim (fun h => (hr.work r h).trans (le_max_left ..))
+ (fun h => (ht.work r h).trans (le_max_right ..))
+
+theorem Resources.cap {rs : List (Report w)} {a b c S H : ℕ} (h : Resources rs a b c)
+ (ht : a ≤ S*H) (hl : b ≤ H) : withinCaps S H rs := ⟨h.cost.trans ht,fun r hr => (h.calls r hr).trans hl⟩
+
+private theorem linked_cost_le {t : ℕ} (next : Fin t → Option (Fin t)) (addr : Word w) (stage : Fin t)
+ (rs : List (Report w)) :
+ RAMBuckets.cost Report.probes (rs.map (LiveStageLink.linkedReport next addr stage)) ≤
+ RAMBuckets.cost Report.probes rs + 2*rs.length := by
+ induction rs with
+ | nil => rfl
+ | cons r rs ih =>
+ simp only [List.map_cons,RAMBuckets.cost,List.length_cons,Nat.mul_succ,LiveStageLink.linkedReport_probes]
+ split <;> omega
+
+private theorem source_clock {s : Sizes} {base : ℕ} {id : Option LiveHeaderProgram.StageId}
+ {m : Memory w} {xs : List (LiveHeaderProgram.StageTrace w)}
+ (runs : LiveHeaderProgram.StageRuns s base id m xs) :
+ ∀ x ∈ xs, ∀ r ∈ x.reports, r.events.length < x.fuel := by
+ induction runs with
+ | done => simp
+ | cons x hsrc _ _ _ ih =>
+ intro y hy r hr
+ rcases List.mem_cons.mp hy with rfl | hy
+ · exact localSegment_event_bound ((runSegment_iff ..).mp hsrc).1 r hr
+ · exact ih y hy r hr
+
+/-- Reports of the actual header stage after the outer D dispatch and
+handoff. This map does not add a microcall. -/
+def headerReports (p : UniversalMachine.Program) (addr : Word w) (raw : List (Report w)) :=
+ raw.map (LiveStageLink.linkedReport (next p) addr LiveProgram.Stage.header)
+
+/-- Every successful physical header path, at any admissible caller clock,
+has the same cost and private-work bound as the short compiled run. -/
+theorem header_resources (p : UniversalMachine.Program) (outer : Word w) (s : Sizes) (base cap : ℕ)
+ (hw : 4 ≤ w) (advice : CutSchedule.Bits s.advice) (cuts : AllCuts s.h s.delta) (g : Fin (2^(s.h+1)))
+ (bounds : LiveHeaderProgram.Fields.Bounds s base d w) (indices : s.h+2 ≤ 2^d) (adv : s.advice ≤ 2^d)
+ (tagFit : LiveHeaderSchedule.stages.length ≤ 2^w) (fuel : 107 ≤ cap) {bs raw}
+ (hr : runSegment (LiveHeaderProgram.nativeHeader w s base) cap (some 0)
+ (LiveHeader.physicalMemory (d := d) hw advice cuts g) bs = some raw)
+ (he : endState (some (0 : Word w)) raw = none) :
+ Resources (headerReports p outer raw) (costBound s) 11 154 := by
+ obtain ⟨tag,hsel,pads⟩ := (LiveHeaderProgram.accepting_iff s base cap hw advice cuts g bounds indices adv
+ tagFit fuel).mp ⟨bs,raw,hr,he⟩
+ obtain ⟨rs,_,_,_,_,hcost,hprobe,hunique⟩ := LiveHeaderProgram.valid_native s base cap hw advice cuts g
+ tag bounds indices adv tagFit fuel hsel pads
+ obtain ⟨_,rfl⟩ := hunique bs raw hr he
+ obtain ⟨xs,_,full,good,_,_⟩ := LiveHeaderProgram.complete_stages s base hw advice cuts g tag bounds
+ indices adv hsel pads
+ let inner : Word w := Fin.ofNat _ base
+ have hroom (x : LiveHeaderProgram.StageTrace w) (hx : x ∈ xs) : x.fuel+2*stages.length+5 ≤ cap := by
+ have := (good x hx).1
+ rw [stage_count]; omega
+ have hval : inner.val = base := by
+ have hb := bounds.fit
+ rw [limit_eq] at hb
+ exact Nat.mod_eq_of_lt (by omega)
+ have hz : LiveHeader.physicalMemory (d := d) hw advice cuts g inner.val = 0 := by
+ have hb := bounds.scratch
+ simp [LiveHeader.physicalMemory,RAMMemory.initialMemory,hval,show ¬base < 2^d by omega]
+ have hempty (x : LiveHeaderProgram.StageTrace w) (hx : x ∈ xs) (b : List Bool) (hb : b ∈ x.paths) : b = [] := by
+ rw [(good x hx).2.1] at hb
+ exact (List.mem_replicate.mp hb).2
+ have hrows := (LiveHeaderProgram.accepted_path_unique s base cap tagFit full hroom hz hempty hr he).2
+ constructor
+ · exact (linked_cost_le _ _ _ _).trans hcost
+ · intro r h
+ obtain ⟨r',hr',rfl⟩ := List.mem_map.mp h
+ rw [LiveStageLink.linkedReport_probes]
+ have := hprobe r' hr'
+ split <;> omega
+ · intro r h
+ obtain ⟨r',hr',rfl⟩ := List.mem_map.mp h
+ have outerLen := LiveStageLink.linkedReport_length_le (next p) outer LiveProgram.Stage.header r'
+ rw [hrows] at hr'
+ obtain ⟨x,hx,hx'⟩ := List.mem_flatMap.mp hr'
+ obtain ⟨v,hv,rfl⟩ := List.mem_map.mp hx'
+ have src := source_clock full x hx v hv
+ have hclock := (good x hx).1
+ have innerLen := LiveStageLink.linkedReport_length_le LiveHeaderProgram.next inner x.id v
+ change (LiveStageLink.linkedReport LiveHeaderProgram.next (Fin.ofNat (2^w) base) x.id v).events.length ≤ v.events.length + 2*31+5 at innerLen
+ change _ ≤ _ + 2*21+5 at outerLen
+ omega
+
+private theorem local_more {C : Type*} (P : BurstRAM.Program w C) {f g : ℕ} (hfg : f ≤ g) {st : Option (Word w)}
+ {rs : List (Report w)} (h : LocalSegment P f st rs) : LocalSegment P g st rs := by
+ induction rs generalizing st with
+ | nil => trivial
+ | cons r rs ih =>
+ cases st with
+ | none => contradiction
+ | some st => exact ⟨by simpa only [Nat.add_sub_cancel' hfg] using guessed_addFuel h.1 (g-f),ih h.2⟩
+
+/-- The prefix executed by the outer physical machine has bounded work
+at every call, even when the group clock is much larger than 154. -/
+theorem actual_header (G : PairStages.Group) (hw : 4 ≤ G.w) (advice : CutSchedule.Bits (Header.sizes G.constants G.g).advice)
+ (cuts : AllCuts (Header.sizes G.constants G.g).h (Header.sizes G.constants G.g).delta)
+ (i : Fin (2^((Header.sizes G.constants G.g).h+1))) (tag : LiveHeader.Mode.Tag)
+ (bounds : LiveHeaderProgram.Fields.Bounds (Header.sizes G.constants G.g) (Header.base G.g) G.g.d G.w)
+ (hi : (Header.sizes G.constants G.g).h+2 ≤ 2^G.g.d) (had : (Header.sizes G.constants G.g).advice ≤ 2^G.g.d)
+ (ht : stages.length ≤ 2^G.w) (hclock : 154 ≤ G.clock) (mode : LiveHeader.physicalTag cuts i = some tag)
+ (pad : ∀ side, LiveHeaderProgram.Fields.ValidPadding (Header.sizes G.constants G.g) cuts i tag side) :
+ let s := Header.sizes G.constants G.g
+ let m := LiveHeader.physicalMemory (d := G.g.d) hw advice cuts i
+ ∃ rs, runSegment G.P G.clock (some 0) m (List.replicate (callBound s) []) = some rs ∧
+ endState (some 0) rs = some 0 ∧ LiveHeaderProgram.Output s (Header.base G.g) G.g.d hw advice cuts i tag
+ (after m (eventLog rs)) ∧ G.tagged LiveProgram.Stage.mode (after m (eventLog rs)) ∧
+ Resources rs (costBound s) 11 154 := by
+ obtain ⟨rs,hr,hs,output,htag,_,hc,hp⟩ := Header.valid_prefix G.constants G.evaluator G.pair G.g G.lit 154
+ hw advice cuts i tag bounds hi had ht le_rfl mode pad
+ have ⟨localRun,hm,hb⟩ := (runSegment_iff ..).mp hr
+ refine ⟨rs,?_,hs,output,htag,hc,fun r h => by have := hp r h; omega,fun r h => ?_⟩
+ · rw [G.program_eq]
+ exact (runSegment_iff ..).mpr ⟨local_more _ hclock localRun,hm,hb⟩
+ · exact localSegment_event_bound localRun r h
+
+/-- A selected jump, including the flag read, explicit route write and outer
+tag read. No branch bit is charged. -/
+theorem router_jump (r : Router) (p : UniversalMachine.Program) (g : Geometry) (lit : LiteralPrefix)
+ (i : Fin 3) (flag : Word g.w) (dest : LiveProgram.Stage) :
+ Resources [r.outerReport p g lit (r.jumpReport g lit i flag dest)] 4 4 60 := by
+ let raw := r.jumpReport g lit i flag dest
+ have probes : raw.probes = 2 := by fin_cases i <;> rfl
+ have rawLen : raw.events.length ≤ 12 := by
+ have := i.isLt
+ simp [raw,Router.jumpReport]; omega
+ let out := r.outerReport p g lit raw
+ have hp : out.probes = 3 := by
+ dsimp only [out,Router.outerReport]
+ rw [LiveStageLink.linkedReport_probes,r.terminal p]
+ simp [probes]
+ have hw : out.events.length+1 ≤ 60 := by
+ have h := LiveStageLink.linkedReport_length_le (next p) (Pieces.word g lit (.geometry Layout.stageTag)) r.stage raw
+ change out.events.length ≤ raw.events.length + 2*21+5 at h
+ omega
+ change Resources [out] 4 4 60
+ refine ⟨by simp [RAMBuckets.cost,hp],?_,?_⟩
+ · intro x hx; obtain rfl := List.mem_singleton.mp hx; omega
+ · intro x hx; obtain rfl := List.mem_singleton.mp hx; exact hw
+
+/-- Unit mode terminates with one flag read and one outer tag read. -/
+theorem router_halt (r : Router) (p : UniversalMachine.Program) (g : Geometry) (lit : LiteralPrefix)
+ (i : Fin 3) (flag : Word g.w) :
+ Resources [r.outerReport p g lit (r.haltReport g lit i flag)] 3 3 56 := by
+ let raw := r.haltReport g lit i flag
+ have probes : raw.probes = 1 := by fin_cases i <;> rfl
+ have rawLen : raw.events.length ≤ 8 := by
+ have := i.isLt
+ simp [raw,Router.haltReport]; omega
+ let out := r.outerReport p g lit raw
+ have hp : out.probes = 2 := by
+ dsimp only [out,Router.outerReport]
+ rw [LiveStageLink.linkedReport_probes,r.terminal p]
+ simp [probes]
+ have hw : out.events.length+1 ≤ 56 := by
+ have h := LiveStageLink.linkedReport_length_le (next p) (Pieces.word g lit (.geometry Layout.stageTag)) r.stage raw
+ change out.events.length ≤ raw.events.length + 2*21+5 at h
+ omega
+ change Resources [out] 3 3 56
+ refine ⟨by simp [RAMBuckets.cost,hp],?_,?_⟩
+ · intro x hx; obtain rfl := List.mem_singleton.mp hx; omega
+ · intro x hx; obtain rfl := List.mem_singleton.mp hx; exact hw
+
+end LiveProgram.OutsideTraces
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePairExponentCount.lean b/lean/OAI/Computability/VPVNP/LivePairExponentCount.lean
new file mode 100644
index 0000000000..74f6fe49e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePairExponentCount.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.LiveExponentPaths
+import OAI.Computability.VPVNP.LiveGroupContraction
+
+/-!
+# Native exponent paths in the first-half group count
+
+The physical format supplies the exterior cut and both adjacent exponent
+vectors. Once the mode and zero padding have passed, a nominated histogram
+and a chosen compressor occurrence contribute one native completion exactly
+when all outgoing exponents match. This includes the zero incoming vector
+at the first group and the empty exterior field at the midpoint.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveExponent
+
+open BurstRAM CutSchedule ExponentTrace ChainAssignments
+open scoped Classical
+
+variable {w t Z h Δ S H : ℕ}
+
+/-- Decode the first-half cut's exterior and exponent fields for the selected group using the
+fitted pair layout. -/
+def pairFields (fit : 1 + t*Z ≤ Δ) (fst : LiveBits h Δ) (i : Fin (2^h)) :=
+ firstHalfLayout h Δ (i.val+1) t Z (by omega) i.isLt fit (fst i)
+
+/-- The outgoing format tests outside the exponent stage. -/
+def pairFormat (fit : 1 + t*Z ≤ Δ) (fst : LiveBits h Δ) (i : Fin (2^h)) : Prop :=
+ (pairFields fit fst i).1 = true ∧ (pairFields fit fst i).2.2.2 = fun _ => false
+
+theorem firstCheck_iff (fit : 1 + t*Z ≤ Δ) (fst : LiveBits h Δ) (i : Fin (2^h)) (inc : Fin t → ℕ) :
+ firstCheck fit fst (exteriorOf fit fst) i inc ↔ pairFormat fit fst i ∧
+ ∀ a, (counters fit fst i.succ a).val = (counters fit fst i.castSucc a).val + inc a := by
+ unfold firstCheck pairFormat
+ change (pairFields fit fst i = (true, (pairFields fit fst i).2.1,
+ (pairFields fit fst i).2.2.1, fun _ => false) ∧ _) ↔ _
+ cases pairFields fit fst i with
+ | mk mode rest =>
+ obtain ⟨ext, counts, pad⟩ := rest
+ simp
+
+variable {Nom : Type*} [Fintype Nom]
+variable {Path : Exterior h Δ → Fin (2^h) → Nom → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+
+/-- Sum of the actual capped exponent-stage path counts after each nomination
+and compressor path. The adjacent field test selects the local integer
+factor in the contraction of the live chain. -/
+theorem native_pairCount (fit : 1 + t*Z ≤ Δ) (fst : LiveBits h Δ) (i : Fin (2^h))
+ (inc : ∀ ξ j μ, Path ξ j μ → Fin t → ℕ)
+ (pub : Fin 5 → BurstRAM.Word w) (L : BufferLayout pub t Z) (hZ : 0 < Z) (hw : 2 ≤ w)
+ (mem : ∀ μ, Path (exteriorOf fit fst) i μ → Memory w)
+ (data : ∀ μ q, BufferValues pub (counters fit fst i.castSucc) (counters fit fst i.succ) (mem μ q))
+ (read : ∀ μ q a, ((mem μ q) (counterAddr pub a).val).val = inc (exteriorOf fit fst) i μ q a)
+ (small : ∀ μ q a, inc (exteriorOf fit fst) i μ q a + 1 < 2^w)
+ (f : ℕ) (hcost : 5*(t*Z)+1 ≤ S*H) (hb : 5 ≤ H) :
+ (if pairFormat fit fst i then ∑ μ, ∑ q : Path (exteriorOf fit fst) i μ,
+ Nat.card (ActualPaths (digitTemplate.instantiate w pub).program (f+31) 0 (mem μ q) (withinCaps S H))
+ else 0) = pairCount fit inc fst i := by
+ unfold pairCount
+ dsimp only
+ by_cases good : pairFormat fit fst i
+ · rw [ite_eq_left good]
+ apply Finset.sum_congr rfl
+ intro μ _
+ apply Finset.sum_congr rfl
+ intro q _
+ let start (a : Fin t) : BurstRAM.Word w := mem μ q (counterAddr pub a).val
+ have h := pathCount L hZ hw (data μ q) start (fun _ => rfl)
+ (fun a => (read μ q a) ▸ small μ q a) f (withinCaps S H)
+ rw [h]
+ simp only [stageCaps pub (mem μ q) hcost hb, and_true, start, read, firstCheck_iff, good, true_and]
+ · simp [good, firstCheck_iff]
+
+end LiveExponent
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePairStageConditions.lean b/lean/OAI/Computability/VPVNP/LivePairStageConditions.lean
new file mode 100644
index 0000000000..23d8a013d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePairStageConditions.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.LiveOutsideCallCapacity
+import OAI.Computability.VPVNP.LiveProgramPairActive
+
+/-! # Native first-half stage conditions at the paper's length parameters -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.LocalCount
+
+open Filter CursorBounds BurstRAM PairStages PairStages.Group LiveAuxiliaryHeaders
+
+/-- Conditions on the concrete RAM alone. The first inequality includes the
+unpopulated header slots, so the address bound is uniform over every cut. -/
+structure PairStageConditions (G : Group) (S H : ℕ) : Prop where
+ room : ∀ i, Auxiliary.shadowBase G + span (Auxiliary.pairLengths G i) (Auxiliary.histLength G) ≤ 2^G.w
+ width : 2*G.g.d < G.w
+ nominations : 5*(2*G.g.d)+15 ≤ G.clockAt Stage.nominations
+ initializer : 82 ≤ G.clockAt Stage.auxiliaryInit
+ copy : 71 ≤ G.clockAt Stage.auxiliaryCopy
+ exponents : 31 ≤ G.clockAt Stage.exponents
+ labels : 0 < labelCount G
+ row : 0 < expWidth G
+ cost : OutsideBudget.actualBound G.constants G.g 0 false false true ≤ S
+ bucket : 26 ≤ H
+
+set_option exponentiation.threshold 10000 in
+/-- The same address exponent as in the outside-work majorant suffices for
+the native first-half calls and all their physical input arrays. -/
+theorem eventually_pairStageConditions {C₂ : ℕ} (u : CursorNetwork.PairExponents C₂) (c : Constants) :
+ ∃ B₀ : ℕ, ∀ B ≥ B₀, ∀ᶠ n : ℕ in atTop, ∀ G : Group,
+ G.constants = c → G.g = paperGeometry B (liveCapacity u) n → n^10000 ≤ G.clock →
+ PairStageConditions G (processorCount B n) (liveCapacity u n) := by
+ obtain ⟨B₁,hmajor⟩ := OutsideBudget.eventually_budget c
+ refine ⟨max 1 B₁,fun B hB => ?_⟩
+ have h1 : 1 ≤ B := (le_max_left ..).trans hB
+ have hspan : (Layout.shadow c + Auxiliary.headerSpan c).SitePowers :=
+ ⟨Layout.shadow_sitePowers c, Auxiliary.headerSpan_sitePowers c⟩
+ filter_upwards [(hspan.fits h1 (liveCapacity_polynomial u)).2,
+ hmajor B ((le_max_right ..).trans hB), eventually_liveCapacity_ge u 26,
+ eventually_ge_atTop 160, eventually_word_stage_le B B] with n hfit hsize hbucket hn hword
+ intro G hc hg clock
+ have hr (i : Fin (2^(Auxiliary.sizes G).h)) :
+ Auxiliary.shadowBase G + span (Auxiliary.pairLengths G i) (Auxiliary.histLength G) ≤ 2^G.w := by
+ rw [← Auxiliary.headerSpan_eval G i]
+ change ((Layout.shadow G.constants + Auxiliary.headerSpan G.constants).eval G.g) ≤ 2^G.g.w
+ rw [hc,hg]
+ exact hfit.1.le
+ have hd : G.g.d ≤ n := by
+ rw [hg]
+ exact (hword _ _ (Nat.mul_le_mul_left B (clog_le_log2_succ n)) (Nat.mul_le_mul_left B (clog_le_log2_succ n))).2
+ have hwidth : 2*G.g.d < G.w := by
+ change 2*G.g.d < G.g.w
+ rw [hg]
+ change 2*addressBits B n < (addressBits B n+10)^4
+ have hs := Nat.pow_le_pow_right (Nat.succ_pos (addressBits B n+9)) (by decide : 2 ≤ 4)
+ nlinarith only [hs]
+ have h10 : 11*n ≤ n^10000 := calc
+ _ ≤ n^2 := by rw [sq]; exact Nat.mul_le_mul_right n (by omega)
+ _ ≤ n^10000 := Nat.pow_le_pow_right (by omega : 0 .publicWord (reg dst) i (body j))
+
+private def lower : Instr w p r 12 → Instr w (5+p) (r+2) 11
+ | .constant a v j => .constant (reg a) v (body j)
+ | .publicWord a i j => operand a j i
+ | .stateWord a j => .stateWord (reg a) (body j)
+ | .copy a b j => .copy (reg a) (reg b) (body j)
+ | .binary op a b c j => .binary op (reg a) (reg b) (reg c) (body j)
+ | .loadPrivate a b j => .loadPrivate (reg a) (reg b) (body j)
+ | .storePrivate a b j => .storePrivate (reg a) (reg b) (body j)
+ | .jumpEq a b y n => .jumpEq (reg a) (reg b) (body y) (body n)
+ | .jumpLt a b y n => .jumpLt (reg a) (reg b) (body y) (body n)
+ | .choose y n => .choose (body y) (body n)
+ | .readExternal a b j => .readExternal (reg a) (reg b) (body j)
+ | .writeExternal a b j => .writeExternal (reg a) (reg b) (body j)
+ | .returnState a => .returnState (reg a)
+ | .accept => .accept
+ | .reject => .reject
+
+private def bootCode (entry : Fin p) : Fin 5 → Instr w (5+p) (r+2) 11
+ | 0 => .publicWord (cache r) 4 (pre p 1)
+ | 1 => .publicWord (tmp r) 5 (pre p 2)
+ | 2 => .binary .add (cache r) (cache r) (tmp r) (pre p 3)
+ | 3 => .publicWord (tmp r) 9 (pre p 4)
+ | _ => .binary .add (cache r) (cache r) (tmp r) (body entry)
+
+/-- Compile a twelve-operand linked table to the eleven-operand pair interface by computing its
+tag address in five entry instructions. -/
+def compile (T : Template p r 12) : Template (5+p) (r+2) 11 where
+ literalWidth := T.literalWidth
+ entry := pre p 0
+ code := Fin.addCases (bootCode T.entry) (fun j => lower (T.code j))
+
+private def registers (rs : Fin r → Word w) (a t : Word w) : Fin (r+2) → Word w := Fin.append rs ![a,t]
+
+private def embed (pub : Fin 11 → Word w) (c : Config w p r) : Config w (5+p) (r+2) :=
+ ⟨body c.pc,c.persistent,registers c.reg (address pub) (pub 9),c.privateMem⟩
+
+private theorem registers_reg (rs : Fin r → Word w) (a t : Word w) (i : Fin r) :
+ registers rs a t (reg i) = rs i := by simp [registers,reg]
+
+private theorem update_reg (rs : Fin r → Word w) (a t v : Word w) (i : Fin r) :
+ Function.update (registers rs a t) (reg i) v = registers (Function.update rs i v) a t := by
+ funext j
+ cases j using Fin.addCases with
+ | left j =>
+ by_cases h : j = i
+ · subst j; simp [registers,reg]
+ · simp [registers,reg,Function.update,h]
+ | right j =>
+ have h : j.natAdd r ≠ i.castAdd 2 := by intro he; have hv := congrArg Fin.val he; simp at hv; omega
+ simp [registers,reg,Function.update_of_ne h]
+
+private theorem lower_resize {v : ℕ} (op : Instr v p r 12) : (lower op).resize w = lower (op.resize w) := by
+ cases op with
+ | publicWord a i j => cases i using Fin.lastCases <;> simp only [lower,operand,Fin.lastCases_last,Fin.lastCases_castSucc,Instr.resize]
+ | _ => rfl
+
+private theorem code_body (T : Template p r 12) (pub : Fin 11 → Word w) (j : Fin p) :
+ ((compile T).instantiate w pub).code (body j) = lower ((T.instantiate w (data pub)).code j) := by
+ simp [compile,Template.instantiate,body,Fin.addCases_right,lower_resize]
+
+private def mapAction {A B : Type*} (f : A → B) : CallAction w A → CallAction w B
+ | .localStep c => .localStep (f c)
+ | .branch g => .branch (f ∘ g)
+ | .read a g => .read a (f ∘ g)
+ | .write a v c => .write a v (f c)
+ | .finish s => .finish s
+ | .reject => .reject
+
+private theorem body_step (T : Template p r 12) (pub : Fin 11 → Word w) (c : Config w p r) :
+ ((compile T).instantiate w pub).program.step (embed pub c) =
+ mapAction (embed pub) ((T.instantiate w (data pub)).program.step c) := by
+ change (((compile T).instantiate w pub).code (body c.pc)).run pub _ = _
+ rw [code_body]
+ change (lower _).run pub _ = mapAction _ (((T.instantiate w (data pub)).code c.pc).run (data pub) c)
+ generalize (T.instantiate w (data pub)).code c.pc = op
+ cases op with
+ | publicWord a i j =>
+ cases i using Fin.lastCases <;>
+ simp only [lower,operand,Fin.lastCases_last,Fin.lastCases_castSucc,Instr.run,mapAction,embed,Config.put,
+ data,Fin.snoc_last,Fin.snoc_castSucc,update_reg]
+ · congr 2; simp [cache,registers]
+ | _ =>
+ simp only [lower,Instr.run,mapAction,embed,Config.put,Config.store,registers_reg,update_reg,Function.comp_def]
+ all_goals first | rfl | (congr 1; simp [registers,apply_ite body])
+
+private theorem body_execute (T : Template p r 12) (pub : Fin 11 → Word w) (fuel : ℕ)
+ (c : Config w p r) (m : Memory w) (bs : List Bool) :
+ execute ((compile T).instantiate w pub).program fuel (embed pub c) m bs =
+ execute (T.instantiate w (data pub)).program fuel c m bs := by
+ induction fuel generalizing c m bs with
+ | zero => rfl
+ | succ f ih =>
+ rw [execute,body_step,execute]
+ cases hs : (T.instantiate w (data pub)).program.step c <;> simp only [mapAction,Function.comp_apply]
+ all_goals first | rfl | rw [ih] | (cases bs <;> simp [ih])
+
+private theorem code_pre (T : Template p r 12) (pub : Fin 11 → Word w) (i : Fin 5) :
+ ((compile T).instantiate w pub).code (pre p i) = bootCode T.entry i := by
+ simp only [compile,Template.instantiate,pre,Fin.addCases_left]
+ fin_cases i <;> rfl
+
+private theorem cache_ne_tmp : cache r ≠ tmp r := by
+ intro e; have h := congrArg Fin.val e; simp [cache,tmp] at h
+
+private theorem boot_regs (a b c : Word w) :
+ Function.update (Function.update (Function.update (Function.update (Function.update (fun _ => 0) (cache r) a) (tmp r) b)
+ (cache r) (a+b)) (tmp r) c) (cache r) (a+b+c) = registers (fun _ : Fin r => 0) (a+b+c) c := by
+ funext j
+ cases j using Fin.addCases with
+ | left j =>
+ have ne (i : Fin 2) : j.castAdd 2 ≠ i.natAdd r := by intro h; have hv := congrArg Fin.val h; simp at hv; omega
+ simp [Function.update_of_ne (ne _),cache,tmp,registers]
+ | right j =>
+ fin_cases j <;> simp [cache,tmp,registers,Function.update,Fin.natAdd_inj]
+
+/-- Five deterministic ticks recover the extra operand. The original report,
+including every continuing word, external access and binary choice, is then
+returned exactly, at every runtime width and remaining fuel. -/
+theorem execute_start (T : Template p r 12) (pub : Fin 11 → Word w) (fuel : ℕ)
+ (st : Word w) (m : Memory w) (bs : List Bool) :
+ let P := ((compile T).instantiate w pub).program
+ let S := (T.instantiate w (data pub)).program
+ execute P (fuel+5) (P.start st) m bs =
+ (execute S fuel (S.start st) m bs).map (LiveStageLink.prependLog (List.replicate 5 .tick)) := by
+ dsimp only
+ change execute ((compile T).instantiate w pub).program (fuel+5) ⟨pre p 0,st,fun _ => 0,fun _ => 0⟩ m bs = _
+ simp only [execute, Machine.program,code_pre,bootCode,Instr.run,Config.put,Function.update_self,
+ Function.update_of_ne cache_ne_tmp,BinaryOp.eval,boot_regs]
+ let P := ((compile T).instantiate w pub).program
+ let S := (T.instantiate w (data pub)).program
+ let tick := Report.prepend (Event.tick : Event w)
+ change (((((execute P fuel (embed pub (S.start st)) m bs).map tick).map tick).map tick).map tick).map tick =
+ (execute S fuel (S.start st) m bs).map (LiveStageLink.prependLog (List.replicate 5 .tick))
+ rw [body_execute T pub fuel (S.start st) m bs]
+ cases execute S fuel (S.start st) m bs <;> rfl
+
+end LiveProgram.PairTag
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePairStageTagPaths.lean b/lean/OAI/Computability/VPVNP/LivePairStageTagPaths.lean
new file mode 100644
index 0000000000..4c28be352e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePairStageTagPaths.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.LivePairStageTag
+
+/-!
+# Full path semantics of the pair tag-address calculation
+
+Computing the stage address on each fresh call uses only private ticks.
+Removing these ticks is an equivalence of the capped native branch streams,
+with exactly the same memory, continuing word and branch choices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairTag
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {p r w : ℕ} (T : Template p r 12) (pub : Fin 11 → Word w)
+
+/-- Prepend the five private ticks spent computing the pair tag address to a source call
+report. -/
+def prefixReport (rep : Report w) : Report w := LiveStageLink.prependLog (List.replicate 5 .tick) rep
+
+theorem prefix_effect (rep : Report w) (m : Memory w) :
+ after m (prefixReport rep).events = after m rep.events ∧ (prefixReport rep).result = rep.result ∧
+ choiceBits (prefixReport rep).events = choiceBits rep.events ∧ (prefixReport rep).probes = rep.probes ∧
+ (prefixReport rep).events.length = 5+rep.events.length := by
+ exact ⟨rfl,rfl,rfl,rfl,by simp [prefixReport,LiveStageLink.prependLog]; omega⟩
+
+@[simp] theorem prefix_after (rep : Report w) (m : Memory w) :
+ after m (prefixReport rep).events = after m rep.events := (prefix_effect rep m).1
+
+@[simp] theorem prefix_result (rep : Report w) : (prefixReport rep).result = rep.result := rfl
+
+theorem segment (f : ℕ) (st : Option (Word w)) (m : Memory w) (bits : List (List Bool)) :
+ runSegment ((compile T).instantiate w pub).program (f+5) st m bits =
+ (runSegment (T.instantiate w (data pub)).program f st m bits).map (List.map prefixReport) := by
+ induction bits generalizing st m with
+ | nil => rfl
+ | cons b bs ih =>
+ cases st with
+ | none => rfl
+ | some st =>
+ rw [runSegment,runSegment,execute_start]
+ cases h : execute (T.instantiate w (data pub)).program f ((T.instantiate w (data pub)).program.start st) m b with
+ | none => rfl
+ | some rep =>
+ change (runSegment _ _ (prefixReport rep).result (after m (prefixReport rep).events) bs).map (prefixReport rep :: ·) = _
+ rw [prefix_result,prefix_after,ih]
+ let run := runSegment (T.instantiate w (data pub)).program f rep.result (after m rep.events) bs
+ change (run.map (List.map prefixReport)).map (prefixReport rep :: ·) = (run.map (rep :: ·)).map (List.map prefixReport)
+ cases run <;> rfl
+
+@[simp] theorem end_prefix (st : Option (Word w)) (rs : List (Report w)) :
+ endState st (rs.map prefixReport) = endState st rs := by
+ induction rs generalizing st with
+ | nil => rfl
+ | cons r rs ih => exact ih r.result
+
+@[simp] theorem after_prefix (m : Memory w) (rs : List (Report w)) :
+ after m (eventLog (rs.map prefixReport)) = after m (eventLog rs) := by
+ induction rs generalizing m with
+ | nil => rfl
+ | cons r rs ih =>
+ simp only [List.map_cons,eventLog,List.flatMap_cons,after,List.foldl_append]
+ exact ih (after m r.events)
+
+/-- The branch strings are identical on both sides, and the predicate sees
+the actually executed sequence of reports. -/
+def pathEquiv (f : ℕ) (st : Word w) (m : Memory w) (cap : List (Report w) → Prop) :
+ ActualPaths (T.instantiate w (data pub)).program f st m (fun rs => cap (rs.map prefixReport)) ≃
+ ActualPaths ((compile T).instantiate w pub).program (f+5) st m cap :=
+ Equiv.subtypeEquivRight fun bits => by
+ constructor
+ · rintro ⟨rs,hr,hh,hc⟩
+ exact ⟨rs.map prefixReport,by rw [segment,hr]; rfl,(end_prefix _ _).trans hh,hc⟩
+ · rintro ⟨es,hr,hh,hc⟩
+ rw [segment,Option.map_eq_some_iff] at hr
+ obtain ⟨rs,hr,rfl⟩ := hr
+ exact ⟨rs,hr,(end_prefix _ _).symm.trans hh,hc⟩
+
+end LiveProgram.PairTag
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePhysicalContraction.lean b/lean/OAI/Computability/VPVNP/LivePhysicalContraction.lean
new file mode 100644
index 0000000000..4ead6b304a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePhysicalContraction.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.ChainModeProduct
+import OAI.Computability.VPVNP.GroupContraction
+import OAI.Computability.VPVNP.LiveIncomingPadding
+
+/-! # The integer count from the physical live program
+
+The group program's specification is local. On each group it checks the two
+incident mode bits, then accepts in unit mode or runs the first-half pair or
+the tail transition. Reindexing the raw shared bits and summing these native
+counts yields one unit path plus the full evaluator sum, on the same processor
+prefix and advice as the primed contraction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ChainAssignments
+
+open ExponentTrace LiveChain LiveEvaluatorEncoding
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Classical
+
+variable {h Δ t Z M w : ℕ} {Nom : Type*} [Fintype Nom]
+variable {Path : Exterior h Δ → Fin (2^h) → Nom → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+variable (fit : 1 + t * Z ≤ Δ) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+variable (E : UniversalMachine.Program) (layout : LiveEvaluatorTail.Layout E.extra M w Δ)
+variable (init : (Fin t → ℕ) → Code E.extra M)
+
+/-- First-half and tail checks, selected by the one-based group number in
+its header. Agreement of the mode bits is imposed separately. -/
+noncomputable def groupEvaluation (cuts : AllCuts h Δ) (j : Fin (2^(h+1))) : ℕ :=
+ let c := liveCutEquiv h Δ cuts
+ Sum.elim (pairCount fit inc c.1)
+ (tailCount E layout (init (fun a => (counters fit c.1 (Fin.last _) a).val)) c.2)
+ ((halves h).symm j)
+
+/-- The integer count required from one native group, including mixed mode,
+clamped endpoints, and failure of a first-half or tail check. -/
+noncomputable def specifiedGroupCount (c : AllCuts h Δ) (j : Fin (2^(h+1))) : ℕ :=
+ unitGroupCount c j + if evalCutMode c j.castSucc ∧ evalCutMode c j.succ ∧ incomingChecks t Z layout c j
+ then groupEvaluation fit inc E layout init c j else 0
+
+private theorem groupEvaluation_active (c : AllCuts h Δ)
+ (ok : (∏ j, groupEvaluation fit inc E layout init c j) ≠ 0) : activeCuts c := by
+ have hn := Finset.prod_ne_zero_iff.mp ok
+ intro j
+ rcases coverCuts j with rfl | rfl | ⟨i,rfl⟩ | ⟨i,rfl⟩
+ · intro ht; exact (Nat.lt_irrefl _ ht).elim
+ · intro _ ht; exact (Nat.lt_irrefl _ ht).elim
+ · intro _ _
+ have hx := hn (halves h (.inl i)) (Finset.mem_univ _)
+ simp only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inl] at hx
+ exact pairCount_mode fit inc (liveCutEquiv h Δ c).1 i hx
+ · intro _ _
+ let s : Fin (2^h) := ⟨i.val, by have := i.isLt; omega⟩
+ have hx := hn (halves h (.inr s)) (Finset.mem_univ _)
+ simp only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inr] at hx
+ exact tailCount_mode E layout _ (liveCutEquiv h Δ c).2 i hx
+
+/-- Every nonzero product supplies the canonical incoming first-half or tail
+format from the predecessor's own successful outgoing check. -/
+theorem groupEvaluation_incoming (c : AllCuts h Δ)
+ (ok : (∏ j, groupEvaluation fit inc E layout init c j) ≠ 0) (j : Fin (2^(h+1))) :
+ incomingChecks t Z layout c j := by
+ have hn := Finset.prod_ne_zero_iff.mp ok
+ constructor
+ · intro i _
+ have hx := hn (halves h (.inl i)) (Finset.mem_univ _)
+ simp only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inl] at hx
+ exact pairCount_padding fit inc _ i hx
+ · intro k _
+ let i : Fin (2^h) := ⟨k.val,by have := k.isLt; omega⟩
+ have hx := hn (halves h (.inr i)) (Finset.mem_univ _)
+ simp only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inr] at hx
+ exact tailCount_decoded layout _ (liveCutEquiv h Δ c).2 k hx
+
+/-- At fixed physical cuts, enforcing both incident formats in each
+group preserves the original product. A malformed incoming cut already
+forces a zero factor at its predecessor. -/
+theorem specifiedGroupCount_product (c : AllCuts h Δ) :
+ (∏ j, specifiedGroupCount fit inc E layout init c j) =
+ (if c = (fun _ _ => false) then 1 else 0) + ∏ j, groupEvaluation fit inc E layout init c j := by
+ let ev (c : AllCuts h Δ) (j : Fin (2^(h+1))) :=
+ if evalCutMode c j.castSucc ∧ evalCutMode c j.succ ∧ incomingChecks t Z layout c j
+ then groupEvaluation fit inc E layout init c j else 0
+ have mode c j (ok : ev c j ≠ 0) : evalCutMode c j.castSucc ∧ evalCutMode c j.succ := by
+ by_cases hc : evalCutMode c j.castSucc ∧ evalCutMode c j.succ ∧ incomingChecks t Z layout c j
+ · exact ⟨hc.1, hc.2.1⟩
+ · exact (ok (ite_eq_right hc)).elim
+ change (∏ j, (unitGroupCount c j + ev c j)) = _
+ rw [group_mode_product ev mode c]
+ congr 1
+ by_cases hp : (∏ j, groupEvaluation fit inc E layout init c j) = 0
+ · obtain ⟨j, hj, hz⟩ := Finset.prod_eq_zero_iff.mp hp
+ rw [hp]
+ exact Finset.prod_eq_zero hj (by simp [ev, hz])
+ · have active := groupEvaluation_active fit inc E layout init c hp
+ exact Finset.prod_congr rfl fun j _ => ite_eq_left
+ ⟨active _, active _, groupEvaluation_incoming fit inc E layout init c hp j⟩
+
+private theorem group_sum : (∑ c : AllCuts h Δ, ∏ j, specifiedGroupCount fit inc E layout init c j) =
+ 1 + ∑ c : AllCuts h Δ, ∏ j, groupEvaluation fit inc E layout init c j := by
+ simp_rw [specifiedGroupCount_product fit inc E layout init, Finset.sum_add_distrib]
+ simp
+
+/-- The integer identity from Section 14.3, reduced to the native site and
+single-group specifications. It holds for the very same prefix whose clocked
+path count occurs in the integer family. -/
+theorem physical_two_modes {n a d e pc regs pubs : ℕ} (table : UniversalMachine.Program)
+ (hf : ProcessorInput.Fits table n d (2^e) w) (advice : CutSchedule.Bits a)
+ (D : Machine w pc regs pubs) (fuel : ℕ) (start : BurstRAM.Word w)
+ (hw : 4 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (processor : ∀ (v : Fin (2^d)) (hdr : ProcessorInput.Header) bits,
+ acceptingCount (ProcessorInput.encode table n v hdr bits hf) =
+ Nat.card (D.IncidentPaths fuel start (ProcessorInput.headerWord hw hdr) (by omega) hc v bits))
+ (group : ∀ (c : AllCuts h Δ) (j : Fin (2^(h+1))),
+ Nat.card (ActualPaths D.program fuel start (RAMMemory.initialMemory (2^d)
+ (liveHeader (d := d) hw advice c j)) (withinCaps (2^d) (2^e))) =
+ specifiedGroupCount fit inc E layout init c j)
+ (bound : ∀ ξ (μ : Fin (2^h) → Nom) (q : (i : Fin (2^h)) → Path ξ i (μ i)) (i : Fin (2^h)) a,
+ partialSum (fun j => inc ξ j (μ j) (q j)) i.succ a < 2^Z)
+ (initial : (Fin t → ℕ) → UniversalMachine.Config E.extra)
+ (hi : ∀ e, (init e).toState = EvaluatorTail.canonical (initial e))
+ (space : ∀ e, LiveEvaluatorTail.HistoriesFit E M (2^h) (initial e)) :
+ PairedChain.original (h := h) (Δ := Δ) table hf advice = 1 +
+ ∑ ξ : Exterior h Δ, ∑ μ : Fin (2^h) → Nom, ∑ q : (i : Fin (2^h)) → Path ξ i (μ i),
+ UniversalMachine.paths E (2^h) (initial (fun a => ∑ i, inc ξ i (μ i) (q i) a)) := by
+ rw [original_eq_group_counts table hf advice D fuel start hw hc processor]
+ simp_rw [group]
+ rw [group_sum, contract_halves (groupEvaluation fit inc E layout init)
+ (pairCount fit inc) (fun fst lst => tailCount E layout
+ (init (fun a => (counters fit fst (Fin.last _) a).val)) lst)]
+ · rw [evaluation_contraction fit inc bound E layout initial init hi space]
+ all_goals intro c i; simp only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inl, Sum.elim_inr]
+
+end ChainAssignments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePhysicalContractionRealized.lean b/lean/OAI/Computability/VPVNP/LivePhysicalContractionRealized.lean
new file mode 100644
index 0000000000..a1b31f50cd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePhysicalContractionRealized.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.LivePhysicalContraction
+import OAI.Computability.VPVNP.GroupIncidentContraction
+
+/-!
+# Two live modes on actual RAM link assignments
+
+The fixed table reads the realized physical link bits at each site. Regrouping
+those coefficients and applying the mode and cut checks gives the integer
+identity used in the diagonal argument.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ChainAssignments
+
+open ExponentTrace LiveChain LiveEvaluatorEncoding
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Classical
+
+variable {h Δ t Z M w : ℕ} {Nom : Type*} [Fintype Nom]
+variable {Path : Exterior h Δ → Fin (2^h) → Nom → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+variable (fit : 1 + t * Z ≤ Δ) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+variable (E : UniversalMachine.Program) (layout : LiveEvaluatorTail.Layout E.extra M w Δ)
+variable (init : (Fin t → ℕ) → Code E.extra M)
+
+/-- The integer identity from Section 14.3, reduced to the native site and
+single-group specifications. It holds for the very same prefix whose clocked
+path count occurs in the integer family. -/
+theorem physical_two_modes_realized {n a d e pc regs pubs : ℕ} (table : UniversalMachine.Program)
+ (hf : ProcessorInput.Fits table n d (2^e) w) (advice : CutSchedule.Bits a)
+ (D : Machine w pc regs pubs) (fuel : ℕ) (start : BurstRAM.Word w)
+ (hw : 4 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (processor : ∀ (v : Fin (2^d)) (hdr : ProcessorInput.Header) (sends : RAMLayout.SendArrays d (2^e) w),
+ acceptingCount (ProcessorInput.encode table n v hdr (RAMLayout.incidentBits sends v) hf) =
+ Nat.card (D.IncidentPaths fuel start (ProcessorInput.headerWord hw hdr) (by omega) hc v (RAMLayout.incidentBits sends v)))
+ (group : ∀ (c : AllCuts h Δ) (j : Fin (2^(h+1))),
+ Nat.card (ActualPaths D.program fuel start (RAMMemory.initialMemory (2^d)
+ (liveHeader (d := d) hw advice c j)) (withinCaps (2^d) (2^e))) =
+ specifiedGroupCount fit inc E layout init c j)
+ (bound : ∀ ξ (μ : Fin (2^h) → Nom) (q : (i : Fin (2^h)) → Path ξ i (μ i)) (i : Fin (2^h)) a,
+ partialSum (fun j => inc ξ j (μ j) (q j)) i.succ a < 2^Z)
+ (initial : (Fin t → ℕ) → UniversalMachine.Config E.extra)
+ (hi : ∀ e, (init e).toState = EvaluatorTail.canonical (initial e))
+ (space : ∀ e, LiveEvaluatorTail.HistoriesFit E M (2^h) (initial e)) :
+ PairedChain.original (h := h) (Δ := Δ) table hf advice = 1 +
+ ∑ ξ : Exterior h Δ, ∑ μ : Fin (2^h) → Nom, ∑ q : (i : Fin (2^h)) → Path ξ i (μ i),
+ UniversalMachine.paths E (2^h) (initial (fun a => ∑ i, inc ξ i (μ i) (q i) a)) := by
+ rw [original_eq_incident_counts table hf advice D fuel start hw hc processor]
+ simp_rw [group]
+ have sumModes : (∑ c : AllCuts h Δ, ∏ j, specifiedGroupCount fit inc E layout init c j) =
+ 1 + ∑ c : AllCuts h Δ, ∏ j, groupEvaluation fit inc E layout init c j := by
+ simp_rw [specifiedGroupCount_product fit inc E layout init, Finset.sum_add_distrib]
+ simp
+ rw [sumModes, contract_halves (groupEvaluation fit inc E layout init)
+ (pairCount fit inc) (fun fst lst => tailCount E layout
+ (init (fun a => (counters fit fst (Fin.last _) a).val)) lst)]
+ · rw [evaluation_contraction fit inc bound E layout initial init hi space]
+ all_goals intro c i; simp only [groupEvaluation, Equiv.symm_apply_apply, Sum.elim_inl, Sum.elim_inr]
+
+end ChainAssignments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePhysicalRoutes.lean b/lean/OAI/Computability/VPVNP/LivePhysicalRoutes.lean
new file mode 100644
index 0000000000..7551605566
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePhysicalRoutes.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.LiveProgramHeaderFlags
+import OAI.Computability.VPVNP.LiveProgramHeader
+import OAI.Computability.VPVNP.LiveProgramPairStages
+
+/-!
+# Physical header path equivalences for pair and evaluator groups
+
+The same code recovers the actual literals and cut payloads and decides the
+mode. At a valid active group the entire choice-free prefix is forced on
+every accepting path. Its continuation begins at nomination or at the
+first-tail test, with the checked payloads in their physical memory banks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.Header
+open BurstRAM LiveHeaderProgram LiveHeaderSchedule LiveHeader ChainAssignments PairStages
+open scoped Fin.CommRing
+
+/-- A checked finite prefix ending at a named outer stage. -/
+structure PrefixTrace (G : Group) (m : Memory G.w) (s : Stage) (count budget : ℕ) where
+ /-- Chronological reports of the deterministic header calls that reach the stated outer
+ stage. -/
+ logs : List (Report G.w)
+ run : runSegment G.P G.clock (some 0) m (List.replicate count []) = some logs
+ state : endState (some 0) logs = some 0
+ tag : G.tagged s (after m (eventLog logs))
+ length : logs.length = count
+ cost : RAMBuckets.cost Report.probes logs ≤ budget
+ probes : ∀ r ∈ logs, r.probes ≤ 10
+
+namespace PrefixTrace
+variable {G : Group} {m : Memory G.w} {s : Stage} {n budget : ℕ}
+
+/-- Every accepting path from the original physical memory has exactly these
+header bursts. The predicate on the remaining path accounts for their cost. -/
+noncomputable def equiv (h : PrefixTrace G m s n budget) (cap : List (Report G.w) → Prop) :
+ ActualPaths G.P G.clock 0 (after m (eventLog h.logs)) (fun rs => cap (h.logs++rs)) ≃
+ ActualPaths G.P G.clock 0 m cap := by
+ have e := emptySegmentEquiv h.run cap
+ rw [h.state] at e
+ exact e
+
+end PrefixTrace
+
+variable (G : Group) (hw : 4 ≤ G.g.w) (fuel : 154 ≤ G.clock)
+variable (advice : CutSchedule.Bits (sizes G.constants G.g).advice)
+variable (cuts : AllCuts (sizes G.constants G.g).h (sizes G.constants G.g).delta)
+variable (i : Fin (2^((sizes G.constants G.g).h+1)))
+variable (bounds : Fields.Bounds (sizes G.constants G.g) (base G.g) G.g.d G.g.w)
+variable (hi : (sizes G.constants G.g).h+2 ≤ 2^G.g.d) (had : (sizes G.constants G.g).advice ≤ 2^G.g.d)
+variable (ht : LiveHeaderSchedule.stages.length ≤ 2^G.g.w)
+include fuel bounds hi had ht
+
+/-- The deterministic physical prefix up to the mode router, with the exact
+header image that the three subsequent cases consume. -/
+theorem valid_prefix_equiv (tag : Mode.Tag) (hmode : physicalTag cuts i = some tag)
+ (pad : ∀ side, Fields.ValidPadding (sizes G.constants G.g) cuts i tag side) :
+ let s := sizes G.constants G.g
+ let m := physicalMemory (d := G.g.d) hw advice cuts i
+ ∃ h : PrefixTrace G m Stage.mode (callBound s) (costBound s),
+ Output s (base G.g) G.g.d hw advice cuts i tag (after m (eventLog h.logs)) := by
+ obtain ⟨logs,run,state,out,tagged,len,cost,probes⟩ := valid_prefix G.constants G.evaluator G.pair G.g
+ G.lit G.clock hw advice cuts i tag bounds hi had ht fuel hmode pad
+ exact ⟨⟨logs,G.program_eq ▸ run,state,tagged,len,cost,probes⟩,out⟩
+
+/-- The two modes in which a checked group continues computation, either counting a primed pair
+or checking an evaluator transition. -/
+inductive ActiveMode where | pair | tail deriving DecidableEq
+
+/-- The header mode tag for the active pair or evaluator-tail branch. -/
+def ActiveMode.tag : ActiveMode → Mode.Tag | .pair => .pair | .tail => .tail
+/-- Numeric flag read by the mode router, one for a pair group and two for an evaluator-tail
+group. -/
+def ActiveMode.flag : ActiveMode → Fin 3 | .pair => 1 | .tail => 2
+/-- First continuation after the mode router, the nomination stage for a pair or the first-tail
+test for an evaluator group. -/
+def ActiveMode.stage : ActiveMode → Stage | .pair => Stage.nominations | .tail => Stage.firstTail
+
+/-- Start the actual nominated pair computation or the evaluator-tail
+computation, after the header and mode router have both run. -/
+theorem active_prefix (active : ActiveMode) (hmode : physicalTag cuts i = some active.tag)
+ (pad : ∀ side, Fields.ValidPadding (sizes G.constants G.g) cuts i active.tag side) :
+ let s := sizes G.constants G.g
+ let m := physicalMemory (d := G.g.d) hw advice cuts i
+ ∃ h : PrefixTrace G m active.stage (callBound s+1) (costBound s+4),
+ Output s (base G.g) G.g.d hw advice cuts i active.tag (after m (eventLog h.logs)) := by
+ let s := sizes G.constants G.g
+ let m := physicalMemory (d := G.g.d) hw advice cuts i
+ obtain ⟨h,out⟩ := valid_prefix_equiv G hw fuel advice cuts i bounds hi had ht active.tag hmode pad
+ let mem := after m (eventLog h.logs)
+ let r := Router.mode
+ let flag := mem ((r.data G.g G.lit) 0).val
+ let rep := r.outerReport G.evaluator G.g G.lit (r.jumpReport G.g G.lit active.flag flag active.stage)
+ have readback : flag = (active.flag.val : Word G.w) := by
+ have H := HeaderFlags.mode G.constants G.g G.lit bounds.fit out
+ cases active <;> exact H
+ have route : r.target active.flag = .jump (active.stage.castLE (by decide)) := by cases active <;> rfl
+ have call : BurstRAM.execute G.P G.clock (G.P.start 0) mem [] = some rep := by
+ rw [G.program_eq]
+ exact r.jump_call G.constants G.evaluator G.pair G.g G.lit G.tagFit (by omega) G.clock (by omega) 0 mem active.flag readback h.tag _ route
+ have hrun : runSegment G.P G.clock (some 0) m (List.replicate (callBound s+1) []) = some (h.logs++[rep]) := by
+ rw [List.replicate_add,PrimedSchedule.runSegment_append,h.run]
+ simp only [Option.bind_some,h.state,show List.replicate 1 ([] : List Bool) = [[]] by rfl]
+ change (runSegment G.P G.clock (some 0) mem [[]]).map (h.logs++·) = _
+ simp [runSegment,call]
+ have post : after m (eventLog (h.logs++[rep])) = writeMemory mem G.addr (LiveStageLink.tagWord G.w active.stage) := by
+ have hafter : after m (eventLog (h.logs++[rep])) = after mem rep.events := by
+ simp [mem,eventLog,after,List.foldl_append]
+ exact hafter.trans (r.after_jump G.evaluator G.g G.lit mem active.flag flag active.stage)
+ have hp : rep.probes = 3 := r.outer_jump_probes G.evaluator G.g G.lit active.flag flag active.stage
+ have hva := addr_value G.g G.lit G.constants bounds.fit.le
+ have hh : G.addr.val < base G.g := by change (addr G.g G.lit).val < 2^G.g.d+1; omega
+ refine ⟨⟨h.logs++[rep],hrun,?_,?_,?_,?_,?_⟩,?_⟩
+ · rw [endState_append,h.state]; rfl
+ · change after m (eventLog (h.logs++[rep])) G.addr.val = _
+ rw [post]; simp [writeMemory]
+ · simp [h.length]
+ · rw [RAMBuckets.cost_append]; simp [RAMBuckets.cost,hp]; exact h.cost
+ · intro a ha
+ obtain ha | ha := List.mem_append.mp ha
+ · exact h.probes a ha
+ · obtain rfl := List.mem_singleton.mp ha; omega
+ · change Output s (base G.g) G.g.d hw advice cuts i active.tag (after m (eventLog (h.logs++[rep])))
+ rw [post]
+ exact out.write_outer _ _ hva.ge hh
+
+end LiveProgram.Header
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePhysicalUnit.lean b/lean/OAI/Computability/VPVNP/LivePhysicalUnit.lean
new file mode 100644
index 0000000000..ceac0d8b5a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePhysicalUnit.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.LiveProgramHeaderFlags
+import OAI.Computability.VPVNP.LiveProgramHeader
+import OAI.Computability.VPVNP.LiveProgramUnit
+import OAI.Computability.VPVNP.LiveHeaderFieldUnitPadding
+
+/-!
+# The physical unit-mode group has one capped native path
+
+The starting memory is the paper's distributed processor header, with zero
+default outside it. The theorem runs the complete header and outer router,
+including the mode agreement and zero-padding checks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.UnitGroup
+open BurstRAM LiveHeaderProgram LiveHeaderSchedule LiveHeader ChainAssignments PairStages
+
+theorem physical_card_one (G : Group) (hw : 4 ≤ G.g.w) (fuel : 154 ≤ G.clock)
+ (advice : CutSchedule.Bits (Header.sizes G.constants G.g).advice)
+ (cuts : AllCuts (Header.sizes G.constants G.g).h (Header.sizes G.constants G.g).delta)
+ (i : Fin (2^((Header.sizes G.constants G.g).h+1)))
+ (bounds : Fields.Bounds (Header.sizes G.constants G.g) (Header.base G.g) G.g.d G.g.w)
+ (hi : (Header.sizes G.constants G.g).h+2 ≤ 2^G.g.d) (had : (Header.sizes G.constants G.g).advice ≤ 2^G.g.d)
+ (ht : stages.length ≤ 2^G.g.w) (mode : physicalTag cuts i = some .unit)
+ (pads : ∀ side, Fields.ValidPadding (Header.sizes G.constants G.g) cuts i .unit side)
+ {S H : ℕ} (hc : costBound (Header.sizes G.constants G.g) + 3 ≤ S*H) (hH : 11 ≤ H) :
+ Nat.card (ActualPaths (machine G.constants G.evaluator G.pair G.g G.lit).program G.clock 0
+ (physicalMemory (d := G.g.d) hw advice cuts i) (withinCaps S H)) = 1 := by
+ let m := physicalMemory (d := G.g.d) hw advice cuts i
+ obtain ⟨logs,hr,he,out,tagged,_,hcost,hprobes⟩ := Header.valid_prefix G.constants G.evaluator G.pair G.g
+ G.lit G.clock hw advice cuts i .unit bounds hi had ht fuel mode pads
+ have hrun : runSegment G.P G.clock (some 0) m (List.replicate (callBound (Header.sizes G.constants G.g)) []) = some logs := by
+ rw [G.program_eq]; exact hr
+ have hmode : (after m (eventLog logs)) ((Router.mode.data G.g G.lit) 0).val = 0 :=
+ HeaderFlags.mode G.constants G.g G.lit bounds.fit out
+ rw [← G.program_eq]
+ apply card_one G (by change 2 ≤ G.g.w; omega) (by omega) hrun he hmode tagged
+ apply (cap_iff G S H logs).2
+ exact ⟨by omega, fun r hr => by have := hprobes r hr; omega, by omega⟩
+
+/-- Disagreeing incident modes or malformed padding make the entire native
+path set empty, regardless of the clock-independent path cap. -/
+theorem physical_card_zero (G : Group) (hw : 4 ≤ G.g.w) (fuel : 154 ≤ G.clock)
+ (advice : CutSchedule.Bits (Header.sizes G.constants G.g).advice)
+ (cuts : AllCuts (Header.sizes G.constants G.g).h (Header.sizes G.constants G.g).delta)
+ (i : Fin (2^((Header.sizes G.constants G.g).h+1)))
+ (bounds : Fields.Bounds (Header.sizes G.constants G.g) (Header.base G.g) G.g.d G.g.w)
+ (hi : (Header.sizes G.constants G.g).h+2 ≤ 2^G.g.d) (had : (Header.sizes G.constants G.g).advice ≤ 2^G.g.d)
+ (ht : stages.length ≤ 2^G.g.w)
+ (invalid : ¬ ∃ tag, physicalTag cuts i = some tag ∧ ∀ side, Fields.ValidPadding (Header.sizes G.constants G.g) cuts i tag side)
+ (cap : List (Report G.w) → Prop) :
+ Nat.card (ActualPaths (machine G.constants G.evaluator G.pair G.g G.lit).program G.clock 0
+ (physicalMemory (d := G.g.d) hw advice cuts i) cap) = 0 := by
+ apply Nat.card_eq_zero.mpr (Or.inl ?_)
+ refine ⟨?_⟩
+ rintro ⟨bs,logs,hr,hh,_⟩
+ exact invalid (Header.necessary G.constants G.evaluator G.pair G.g G.lit G.clock hw advice cuts i
+ bounds hi had ht fuel bs logs hr hh)
+
+/-- Whenever the incident bits fail the evaluation-mode test of (9.4), the
+entire native path count equals the exact unit summand of the contraction.
+This includes unequal mode bits and a zero mode with nonzero payload. -/
+theorem physical_unitGroupCount (G : Group) (hw : 4 ≤ G.g.w) (fuel : 154 ≤ G.clock)
+ (advice : CutSchedule.Bits (Header.sizes G.constants G.g).advice)
+ (cuts : AllCuts (Header.sizes G.constants G.g).h (Header.sizes G.constants G.g).delta)
+ (i : Fin (2^((Header.sizes G.constants G.g).h+1)))
+ (bounds : Fields.Bounds (Header.sizes G.constants G.g) (Header.base G.g) G.g.d G.g.w)
+ (hi : (Header.sizes G.constants G.g).h+2 ≤ 2^G.g.d) (had : (Header.sizes G.constants G.g).advice ≤ 2^G.g.d)
+ (ht : stages.length ≤ 2^G.g.w) {S H : ℕ} (hc : costBound (Header.sizes G.constants G.g) + 3 ≤ S*H)
+ (hH : 11 ≤ H) (inactive : ¬ (evalCutMode cuts i.castSucc ∧ evalCutMode cuts i.succ)) :
+ Nat.card (ActualPaths (machine G.constants G.evaluator G.pair G.g G.lit).program G.clock 0
+ (physicalMemory (d := G.g.d) hw advice cuts i) (withinCaps S H)) = unitGroupCount cuts i := by
+ classical
+ let s := Header.sizes G.constants G.g
+ have hd : 0 < s.delta := by have h := bounds.exponents; change 1+s.e ≤ s.delta at h; omega
+ have spec := physicalTag_unit hd cuts i s.e s.config
+ unfold unitGroupCount
+ split_ifs with hz
+ · obtain ⟨mode,pad⟩ := spec.mpr hz
+ exact physical_card_one G hw fuel advice cuts i bounds hi had ht mode ((Fields.validPadding_unit_iff ..).2 pad) hc hH
+ · apply physical_card_zero G hw fuel advice cuts i bounds hi had ht
+ rintro ⟨tag,mode,pad⟩
+ cases tag with
+ | unit => exact hz (spec.mp ⟨mode,(Fields.validPadding_unit_iff ..).1 pad⟩)
+ | pair => exact inactive ((physicalTag_pair hd cuts i).1 mode).1
+ | tail => exact inactive ((physicalTag_tail hd cuts i).1 mode).1
+
+end LiveProgram.UnitGroup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePreparedPairCounters.lean b/lean/OAI/Computability/VPVNP/LivePreparedPairCounters.lean
new file mode 100644
index 0000000000..168bebde9a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePreparedPairCounters.lean
@@ -0,0 +1,49 @@
+import OAI.Computability.VPVNP.LiveProgramPairPreparation
+
+/-! # The live counter array at entry to the compressed pair program -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM ChainAssignments CutSchedule LiveHeader LiveHeaderProgram
+
+variable {G : Group} {m : Memory G.w} {i : Fin (2^(sizes G).h)} {hdr : PrimedInputRAM.Header (pairLengths G i) → Bool}
+ {hw : 4 ≤ G.w} {advice : Bits (sizes G).advice} {cuts : AllCuts (sizes G).h (sizes G).delta}
+ {mode : Mode.Tag} (out : Output (sizes G) (headerBase G) G.g.d hw advice cuts (halves (sizes G).h (.inl i)) mode m)
+ (F : Nominations.Fits G) (tag : G.tagged Stage.nominations m) (μ : Nominations.Nom G)
+ (P : PreparedBranch G m i hdr (Nominations.indexed G F m tag) μ) (hs : shadowBase G < 2^G.w)
+
+include out hs
+
+/-- The grammar prefix retains the nominated values, and every motif counter
+starts at zero in the actual memory handed to the compressed computation. -/
+theorem PreparedBranch.initialCounters :
+ (∀ j : Fin (histLength G), (P.copy.memory () (counterBase G+j.val)).val = (μ j).val) ∧
+ (∀ j : Fin G.constants.motifLabels, P.copy.memory () (counterBase G+histLength G+j.val) = 0) := by
+ obtain ⟨h0,h1,h2,h3⟩ := geometry_order G
+ obtain ⟨addr,_,base,_⟩ := address_values G hs
+ have endFit := counter_end_le_shadow G
+ change counterBase G + (histLength G + G.constants.motifLabels) ≤ shadowBase G at endFit
+ have afterHeader : LiveHeaderSchedule.limit (sizes G) (headerBase G) ≤ (counter G).val := by
+ change tableBase G ≤ (counter G).val
+ omega
+ have read (a : ℕ) (lo : counterBase G ≤ a) (hi : a < shadowBase G) :
+ P.copy.memory () a = LiveNominations.stored (counter G) F.address μ m a := by
+ rw [P.counterFrame _ lo hi,Nominations.memory_eq]
+ exact ite_eq_right (by omega)
+ constructor
+ · intro j
+ rw [read _ (by omega) (by have := j.isLt; omega),← base]
+ exact LiveNominations.stored_at_val F.width_le _ _ _ _ _
+ · intro j
+ rw [read _ (by omega) (by have := j.isLt; omega)]
+ exact (out.nomination_frame (counter G) F.address afterHeader μ).2 _ (by change (counter G).val+histLength G ≤ _; omega)
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePrimedGroupIndices.lean b/lean/OAI/Computability/VPVNP/LivePrimedGroupIndices.lean
new file mode 100644
index 0000000000..2dccfdd3f6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePrimedGroupIndices.lean
@@ -0,0 +1,296 @@
+import OAI.Computability.VPVNP.LiveHeaderRuns
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Preparing the two primed group indices
+
+In Section 14.1, a first-half live group numbered `i` supplies the auxiliary
+machine with two little-endian indices. Their low bits are one and zero. The
+remaining bits represent `i - 1` and `i`. Each digit call propagates a
+single borrow through external scratch, even when the index exceeds a RAM word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveHeader.PrimedGroupIndices
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The borrow entering digit `j` in the subtraction `i - 1`. -/
+def borrow (i : ℕ) : ℕ → Bool
+ | 0 => true
+ | j + 1 => borrow i j && !i.testBit j
+
+private theorem borrow_quotient {i : ℕ} (hi : 0 < i) (j : ℕ) :
+ i / 2^j = (i - 1) / 2^j + (borrow i j).toNat := by
+ induction j with
+ | zero => simp [borrow]; omega
+ | succ j ih =>
+ rw [pow_succ, ← Nat.div_div_eq_div_mul, ← Nat.div_div_eq_div_mul, borrow]
+ cases h : borrow i j <;> cases b : i.testBit j <;>
+ simp [Nat.testBit_eq_decide_div_mod_eq] at b <;> simp [h] at ih ⊢ <;> omega
+
+private theorem pred_digit {i : ℕ} (hi : 0 < i) (j : ℕ) :
+ (i - 1).testBit j = (i.testBit j ^^ borrow i j) := by
+ have hq := borrow_quotient hi j
+ cases h : borrow i j <;> cases b : i.testBit j <;>
+ simp [h] at hq <;> simp [Nat.testBit_eq_decide_div_mod_eq] at b ⊢ <;> omega
+
+private theorem shifted_digits {i : ℕ} (hi : 0 < i) (j : ℕ) :
+ (2*i-1).testBit (j+1) = (i-1).testBit j ∧ (2*i).testBit (j+1) = i.testBit j := by
+ have hl : 2*i-1 = Nat.bit true (i-1) := by simp [Nat.bit]; omega
+ have hr : 2*i = Nat.bit false i := by simp [Nat.bit]
+ rw [hl, hr, Nat.testBit_bit_succ, Nat.testBit_bit_succ]
+ trivial
+
+/-- In the last group the scanned low digits are all zero and subtraction
+still carries its borrow. In every earlier group the borrow has cleared. -/
+theorem borrow_endpoint {i h : ℕ} (hi : 0 < i) (hle : i ≤ 2^h) :
+ borrow i h = decide (i = 2^h) := by
+ have q := borrow_quotient hi h
+ rw [Nat.div_eq_of_lt (by omega : i - 1 < 2^h), Nat.zero_add] at q
+ by_cases he : i = 2^h
+ · subst i
+ rw [Nat.div_self (Nat.two_pow_pos h)] at q
+ cases hb : borrow (2^h) h
+ · simp [hb] at q
+ · simp
+ · rw [Nat.div_eq_of_lt (by omega : i < 2^h)] at q
+ cases hb : borrow i h
+ · simp [he]
+ · simp [hb] at q
+
+/-- Public words give the input base, left and right output bases, and the
+borrow address. The initialization sets both low bits and starts the borrow. -/
+def setup : List (Op 12 4) :=
+ [.constant 0 0, .constant 1 1, .publicWord 2 1, .publicWord 3 2, .publicWord 4 3,
+ .write 2 1, .write 3 0, .write 4 1]
+
+/-- Set the low bits of the left and right primed indices to one and zero and initialize the
+borrow for subtracting one from the live group index. -/
+def initialized (pub : Fin 4 → Word w) (m : Memory w) : Memory w :=
+ writeMemory (writeMemory (writeMemory m (pub 1) 1) (pub 2) 0) (pub 3) 1
+
+/-- Both reads precede the three writes. Register 9 receives the new
+borrow, register 10 the bit of the predecessor, and register 11 the next cursor. -/
+def digit : List (Op 12 4) :=
+ [.stateWord 0, .constant 1 1, .binary .add 11 0 1,
+ .publicWord 2 0, .binary .add 2 2 0, .read 5 2,
+ .publicWord 3 1, .binary .add 3 3 11, .publicWord 4 2, .binary .add 4 4 11,
+ .publicWord 6 3, .read 7 6,
+ .binary .sub 9 1 5, .binary .mul 9 9 7,
+ .binary .sub 10 5 7, .binary .add 10 10 9, .binary .add 10 10 9,
+ .write 3 10, .write 4 5, .write 6 9]
+
+/-- Store the next digits of the two primed indices, using the incoming borrow for the left
+digit, and propagate the new borrow. -/
+def updated (pub : Fin 4 → Word w) (state : Word w) (m : Memory w) (x c : Bool) : Memory w :=
+ let m₁ := writeMemory m (pub 1 + (state + 1)) (encodeBit w (x ^^ c))
+ let m₂ := writeMemory m₁ (pub 2 + (state + 1)) (encodeBit w x)
+ writeMemory m₂ (pub 3) (encodeBit w (c && !x))
+
+private theorem borrowWord (x c : Bool) :
+ (1 - encodeBit w x) * encodeBit w c = encodeBit w (c && !x) := by
+ cases x <;> cases c <;> simp [encodeBit]
+
+private theorem predWord (x c : Bool) :
+ encodeBit w x - encodeBit w c + encodeBit w (c && !x) + encodeBit w (c && !x) =
+ encodeBit w (x ^^ c) := by
+ cases x <;> cases c <;> simp [encodeBit]
+
+/-- A native initialization call takes three probes and returns cursor zero. -/
+theorem initialize_native (pub : Fin 4 → Word w) (state : Word w) (m : Memory w) :
+ let machine := (template setup 0).instantiate w pub
+ ∃ es, execute machine.program 9 (machine.program.start state) m [] = some ⟨es, some 0⟩ ∧
+ after m es = initialized pub m ∧ es.length = 8 ∧ countProbes es = 3 ∧ choiceBits es = [] := by
+ dsimp only
+ let es : List (Event w) := [.tick, .tick, .tick, .tick, .tick, .write (pub 1) 1,
+ .write (pub 2) 0, .write (pub 3) 1]
+ refine ⟨es, ?_, rfl, rfl, rfl, rfl⟩
+ change execute ((template setup 0).instantiate w pub).program (1 + setup.length)
+ ⟨_,state,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]
+ simp (config := { decide := true }) [setup, trace, Op.effect, Function.update, es]
+
+/-- Executing the same fixed table at every digit takes five probes. -/
+theorem digit_native (pub : Fin 4 → Word w) (state : Word w) (m : Memory w) (x c : Bool)
+ (hx : m (pub 0 + state).val = encodeBit w x) (hc : m (pub 3).val = encodeBit w c) :
+ let machine := (template digit 11).instantiate w pub
+ ∃ es, execute machine.program 21 (machine.program.start state) m [] =
+ some ⟨es, some (state + 1)⟩ ∧
+ after m es = updated pub state m x c ∧ es.length = 20 ∧ countProbes es = 5 ∧ choiceBits es = [] := by
+ dsimp only
+ let es : List (Event w) := [.tick, .tick, .tick, .tick, .tick, .read (pub 0 + state) (encodeBit w x),
+ .tick, .tick, .tick, .tick, .tick, .read (pub 3) (encodeBit w c), .tick, .tick, .tick, .tick, .tick,
+ .write (pub 1 + (state + 1)) (encodeBit w (x ^^ c)), .write (pub 2 + (state + 1)) (encodeBit w x),
+ .write (pub 3) (encodeBit w (c && !x))]
+ refine ⟨es, ?_, rfl, rfl, rfl, rfl⟩
+ change execute ((template digit 11).instantiate w pub).program (1 + digit.length)
+ ⟨_,state,fun _ => 0,fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]
+ simp (config := { decide := true }) [digit, trace, Op.effect, Function.update, es, hx, hc,
+ show BinaryOp.add.eval = (· + · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.sub.eval = (· - · : Word w → Word w → Word w) from rfl,
+ show BinaryOp.mul.eval = (· * · : Word w → Word w → Word w) from rfl, borrowWord, predWord]
+
+/-- Addresses outside both output arrays and the scalar borrow cell. -/
+def outside (pub : Fin 4 → Word w) (h a : ℕ) : Prop :=
+ a ≠ (pub 3).val ∧ (a < (pub 1).val ∨ (pub 1).val + h < a) ∧
+ (a < (pub 2).val ∨ (pub 2).val + h < a)
+
+/-- All array addresses fit and writable regions are disjoint. Bases can
+occur in any physical order, and unrelated scratch may surround them. -/
+structure Layout (pub : Fin 4 → Word w) (h : ℕ) : Prop where
+ inputFit : (pub 0).val + h ≤ 2^w
+ leftFit : (pub 1).val + h < 2^w
+ rightFit : (pub 2).val + h < 2^w
+ outputsApart : (pub 1).val + h < (pub 2).val ∨ (pub 2).val + h < (pub 1).val
+ borrowLeft : (pub 3).val < (pub 1).val ∨ (pub 1).val + h < (pub 3).val
+ borrowRight : (pub 3).val < (pub 2).val ∨ (pub 2).val + h < (pub 3).val
+ inputOutside : ∀ j < h, outside pub h ((pub 0).val + j)
+
+/-- Each address holds one unpacked bit of a little-endian integer. -/
+def stores (m : Memory w) (base : Word w) (width n : ℕ) : Prop :=
+ ∀ j < width, m (base.val + j) = encodeBit w (n.testBit j)
+
+/-- Read an unpacked array as a little-endian bit string. -/
+def storedBits (m : Memory w) (base : Word w) (width : ℕ) : List Bool :=
+ List.ofFn fun j : Fin width => (m (base.val + j.val)).val.testBit 0
+
+private theorem encodeBit_low (hw : 0 < w) (b : Bool) : (encodeBit w b).val.testBit 0 = b := by
+ cases b <;> simp [encodeBit, Nat.testBit_eq_decide_div_mod_eq,
+ Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')]
+
+/-- The decoded value uses arbitrary natural-number precision, independently of
+the width of a single RAM word. -/
+theorem stores_value (hw : 0 < w) {m : Memory w} {base : Word w} {width n : ℕ}
+ (fit : n < 2^width) (hs : stores m base width n) :
+ PrimedCounter.GuessWord.value (storedBits m base width) = n := by
+ let v : Word width := ⟨n, fit⟩
+ have he : storedBits m base width = wordBits v := by
+ apply congrArg List.ofFn
+ funext j
+ rw [hs j.val j.isLt, encodeBit_low hw]
+ exact testBit_wordBits v j
+ rw [he, PrimedCounter.GuessWord.value_wordBits]
+
+/-- Both output integers fit even when doubling sets a new high bit. -/
+theorem pair_values (hw : 0 < w) {m : Memory w} {left right : Word w} {h i : ℕ}
+ (fit : i < 2^h) (hl : stores m left (h+1) (2*i-1)) (hr : stores m right (h+1) (2*i)) :
+ PrimedCounter.GuessWord.value (storedBits m left (h+1)) = 2*i-1 ∧
+ PrimedCounter.GuessWord.value (storedBits m right (h+1)) = 2*i :=
+ ⟨stores_value hw (by rw [pow_succ]; omega) hl, stores_value hw (by rw [pow_succ]; omega) hr⟩
+
+/-- After processing `j` digits, the two output prefixes store the low `j + 1` bits of `2*i -
+1` and `2*i`, the borrow cell is current, and memory outside the workspace agrees with its
+initial contents. -/
+structure Invariant (pub : Fin 4 → Word w) (i h j : ℕ) (original m : Memory w) : Prop where
+ borrowCell : m (pub 3).val = encodeBit w (borrow i j)
+ left : stores m (pub 1) (j+1) (2*i-1)
+ right : stores m (pub 2) (j+1) (2*i)
+ frame : ∀ a, outside pub h a → m a = original a
+
+theorem invariant_zero (pub : Fin 4 → Word w) {i h : ℕ} (hi : 0 < i)
+ (layout : Layout pub h) (m : Memory w) : Invariant pub i h 0 m (initialized pub m) := by
+ have hLR := layout.outputsApart
+ have hBL := layout.borrowLeft
+ have hBR := layout.borrowRight
+ have hlow : (2*i-1).testBit 0 = true := by simp [Nat.testBit_eq_decide_div_mod_eq]; omega
+ have hzero : (2*i).testBit 0 = false := by simp [Nat.testBit_eq_decide_div_mod_eq]
+ refine ⟨by simp [initialized, writeMemory, borrow, encodeBit], ?_, ?_, ?_⟩
+ · intro j hj
+ obtain rfl : j = 0 := by omega
+ simp [initialized, writeMemory, show (pub 1).val ≠ (pub 3).val by omega,
+ show (pub 1).val ≠ (pub 2).val by omega, hlow, encodeBit]
+ · intro j hj
+ obtain rfl : j = 0 := by omega
+ simp [initialized, writeMemory, show (pub 2).val ≠ (pub 3).val by omega, hzero, encodeBit]
+ · rintro a ⟨hb, hl, hr⟩
+ simp [initialized, writeMemory, hb, show a ≠ (pub 1).val by omega, show a ≠ (pub 2).val by omega]
+
+theorem offset_val (base : Word w) (j : ℕ) (hj : base.val + j < 2^w) :
+ (base + (j : Word w)).val = base.val + j := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (show j < 2^w by omega), Nat.mod_eq_of_lt hj]
+
+theorem invariant_succ (pub : Fin 4 → Word w) {i h j : ℕ} (hi : 0 < i)
+ (layout : Layout pub h) (hj : j < h) {m₀ m : Memory w} (inv : Invariant pub i h j m₀ m) :
+ Invariant pub i h (j+1) m₀ (updated pub (j : Word w) m (i.testBit j) (borrow i j)) := by
+ have hLR := layout.outputsApart
+ have hBL := layout.borrowLeft
+ have hBR := layout.borrowRight
+ have hL := layout.leftFit
+ have hR := layout.rightFit
+ have lval : (pub 1 + ((j : Word w) + 1)).val = (pub 1).val + (j+1) := by
+ simpa only [Nat.cast_add, Nat.cast_one] using offset_val (pub 1) (j+1) (by omega)
+ have rval : (pub 2 + ((j : Word w) + 1)).val = (pub 2).val + (j+1) := by
+ simpa only [Nat.cast_add, Nat.cast_one] using offset_val (pub 2) (j+1) (by omega)
+ have ⟨left, right⟩ := shifted_digits hi j
+ rw [pred_digit hi] at left
+ refine ⟨by simp [updated, writeMemory, borrow], ?_, ?_, ?_⟩
+ · intro k hk
+ simp only [updated, writeMemory, lval, rval, show (pub 1).val + k ≠ (pub 3).val by omega,
+ show (pub 1).val + k ≠ (pub 2).val + (j+1) by omega, ↓reduceIte, Nat.add_left_cancel_iff]
+ by_cases hkj : k = j+1
+ · simp [hkj, left]
+ · simpa [hkj] using inv.left k (by omega)
+ · intro k hk
+ simp only [updated, writeMemory, lval, rval, show (pub 2).val + k ≠ (pub 3).val by omega,
+ show (pub 2).val + k ≠ (pub 1).val + (j+1) by omega, ↓reduceIte, Nat.add_left_cancel_iff]
+ by_cases hkj : k = j+1
+ · simp [hkj, right]
+ · simpa [hkj] using inv.right k (by omega)
+ · intro a ha
+ obtain ⟨hb, hl, hr⟩ := ha
+ simpa [updated, writeMemory, lval, rval, hb, show a ≠ (pub 1).val + (j+1) by omega,
+ show a ≠ (pub 2).val + (j+1) by omega] using inv.frame a ⟨hb, hl, hr⟩
+
+/-- One setup call followed by `h` deterministic digit calls gives the exact
+`h+1` output bits, clears the borrow, and preserves every other memory cell.
+For the middle live group the right array includes the high bit of `L`. -/
+theorem native (pub : Fin 4 → Word w) (h i : ℕ) (hi : 0 < i) (fit : i < 2^h)
+ (layout : Layout pub h) (state : Word w) (m : Memory w) (input : stores m (pub 0) h i) :
+ let init := (template setup 0).instantiate w pub
+ let P := ((template digit 11).instantiate w pub).program
+ ∃ es rs, execute init.program 9 (init.program.start state) m [] = some ⟨es, some 0⟩ ∧
+ countProbes es = 3 ∧
+ runSegment P 21 (some 0) (after m es) (List.replicate h []) = some rs ∧
+ endState (some 0) rs = some (h : Word w) ∧ rs.length = h ∧
+ (∀ r ∈ rs, countProbes r.events ≤ 5) ∧
+ let out := after (after m es) (eventLog rs)
+ stores out (pub 1) (h+1) (2*i-1) ∧ stores out (pub 2) (h+1) (2*i) ∧
+ out (pub 3).val = 0 ∧ ∀ a, outside pub h a → out a = m a := by
+ dsimp only
+ obtain ⟨es, he, hm, _, hp, _⟩ := initialize_native pub state m
+ have hz := invariant_zero pub hi layout m
+ obtain ⟨rs, hs, hend, inv, hlen, probes⟩ := run_cursor_segment
+ ((template digit 11).instantiate w pub).program 21 h 5
+ (fun j mem => Invariant pub i h j m mem) (initialized pub m) hz (by
+ intro j hj mem hjmem
+ have addr := offset_val (pub 0) j (by have := layout.inputFit; omega)
+ have hx : mem (pub 0 + (j : Word w)).val = encodeBit w (i.testBit j) := by
+ rw [addr, hjmem.frame _ (layout.inputOutside j hj), input j hj]
+ obtain ⟨fs, hf, hm', _, hp', _⟩ := digit_native pub (j : Word w) mem _ _ hx hjmem.borrowCell
+ refine ⟨fs, by simpa only [Nat.cast_add, Nat.cast_one] using hf, ?_, hp'.le⟩
+ rw [hm']
+ exact invariant_succ pub hi layout hj hjmem)
+ have hb : borrow i h = false := by
+ have q := borrow_quotient hi h
+ rw [Nat.div_eq_of_lt fit, Nat.div_eq_of_lt (by omega)] at q
+ cases hh : borrow i h
+ · rfl
+ · simp [hh] at q
+ refine ⟨es, rs, he, hp, ?_⟩
+ rw [hm]
+ exact ⟨hs, hend, hlen, probes, inv.left, inv.right,
+ by simpa [hb, encodeBit] using inv.borrowCell, inv.frame⟩
+
+end LiveHeader.PrimedGroupIndices
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgram.lean b/lean/OAI/Computability/VPVNP/LiveProgram.lean
new file mode 100644
index 0000000000..a1f37a54a6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgram.lean
@@ -0,0 +1,265 @@
+import OAI.Computability.VPVNP.LiveProgramLayout
+import OAI.Computability.VPVNP.LiveProgramPieces
+import OAI.Computability.VPVNP.LiveRoute
+import OAI.Computability.VPVNP.LiveAuxiliaryStages
+import OAI.Computability.VPVNP.LiveExponentRows
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceFrames
+import OAI.Computability.VPVNP.LiveEvaluatorAdvicePackStep
+import OAI.Computability.VPVNP.LiveEvaluatorInitializeStages
+import OAI.Computability.VPVNP.LiveEvaluatorReindexSkeleton
+import OAI.Computability.VPVNP.LiveEvaluatorReindexNative
+import OAI.Computability.VPVNP.LiveEvaluatorRAMSchedule
+import OAI.Computability.VPVNP.LiveConfigGather
+import OAI.Computability.VPVNP.CompressorRecordFrame
+
+/-!
+# The native control flow of the live group computation
+
+The header program runs first and checks the incident cuts. Three short
+routers read its mode, first-tail and last-group flags. Pair groups construct
+the shadow of the auxiliary machine, execute the compressed pair routine,
+and check the exponent update. Tail groups construct or read the incoming
+configuration and check one evaluator transition against the required output.
+
+The compressed pair computation is a separately supplied native instruction
+table with eleven operands. Its two literal-prefix operands come from the
+processor's own input. The other operands of the live program use the
+length-only arithmetic expressions of `LiveProgramLayout`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+open BurstRAM BurstRAM.PrivateRAM
+open LiveHeaderDescriptors
+
+/-- The twenty-one stage tags of the native live group program, covering header checks, the
+pair counter and the evaluator tail. -/
+abbrev Stage := Fin 21
+
+namespace Stage
+/-- Read and validate the incident header and cuts, and publish the mode and endpoint flags. -/
+abbrev header : Stage := 0
+/-- Read the checked mode tag to finish a unit group or enter its pair or evaluator-tail
+computation. -/
+abbrev mode : Stage := 1
+/-- Guess the production counts for a primed pair and store one nominated word per grammar
+label. -/
+abbrev nominations : Stage := 2
+/-- Prepare the copy descriptors for the primed pair counter's external header and nominated
+histogram. -/
+abbrev auxiliaryInit : Stage := 3
+/-- Copy the recovered header fields and nominated counts into the pair counter's shadow
+memory. -/
+abbrev auxiliaryCopy : Stage := 4
+/-- Execute the supplied compressed pair counter on its shadow header and workspace. -/
+abbrev pair : Stage := 5
+/-- Check that each outgoing exponent equals its incoming exponent plus the increments produced
+by the pair path. -/
+abbrev exponents : Stage := 6
+/-- Test whether to initialize the evaluator at the first tail group or gather its incoming
+configuration. -/
+abbrev firstTail : Stage := 7
+/-- Install the initial evaluator control state in the old configuration bank. -/
+abbrev initialState : Stage := 8
+/-- Pack the prefix length from the header's advice bits into a word for preparing the
+evaluator input. -/
+abbrev prefixLength : Stage := 9
+/-- Check the packed prefix length and publish the operand frames for prefix packing, copying,
+runtime initialization and exponent scatter. -/
+abbrev adviceFrames : Stage := 10
+/-- Pack the active prefix bits from the advice into words for the evaluator's input tape. -/
+abbrev prefixPack : Stage := 11
+/-- Pack the advised label ordering into the lookup table used to reindex exponents. -/
+abbrev orderPack : Stage := 12
+/-- Copy the packed program prefix into the evaluator's initial tape window. -/
+abbrev prefixCopy : Stage := 13
+/-- Write the evaluator runtime suffix with its width fields, delimiters and initially zero
+exponent positions. -/
+abbrev skeleton : Stage := 14
+/-- Write the incoming exponent bits into the runtime tape using the advised label order. -/
+abbrev scatter : Stage := 15
+/-- Gather the incoming configuration from the left cut into the old evaluator state bank. -/
+abbrev oldGather : Stage := 16
+/-- Test whether the outgoing configuration must be the final accepting state or should be
+gathered from the right cut. -/
+abbrev last : Stage := 17
+/-- Install the prescribed accepting evaluator endpoint in the new configuration bank. -/
+abbrev finalState : Stage := 18
+/-- Gather the outgoing configuration from the right cut into the new evaluator state bank. -/
+abbrev newGather : Stage := 19
+/-- Check one evaluator transition against the old and new configurations, including both tape
+windows. -/
+abbrev transition : Stage := 20
+end Stage
+
+private def jump (s : Stage) : Route.Target := .jump (s.castLE (by decide))
+
+/-- Decode the mode flag. Zero accepts the unit group, one enters nominations and two enters
+the first-tail test. -/
+def modeTarget : Fin 3 → Route.Target := ![.accept,jump Stage.nominations,jump Stage.firstTail]
+/-- Route flag zero to incoming-state gathering and flag one to evaluator initialization. Flag
+two rejects. -/
+def firstTarget : Fin 3 → Route.Target := ![jump Stage.oldGather,jump Stage.initialState,.reject]
+/-- Route flag zero to outgoing-state gathering and flag one to the prescribed accepting state.
+Flag two rejects. -/
+def lastTarget : Fin 3 → Route.Target := ![jump Stage.newGather,jump Stage.finalState,.reject]
+
+/-- A router selects its destination by writing the outer tag and returning
+zero. Its accepting exit therefore finishes the whole group. The accepting
+exit of an ordinary stage transfers to its specified successor. -/
+def next (p : UniversalMachine.Program) : Stage → Option Stage :=
+ ![some Stage.mode,none,some Stage.auxiliaryInit,some Stage.auxiliaryCopy,some Stage.pair,
+ some Stage.exponents,none,none,if p.extra = 0 then some Stage.last else some Stage.prefixLength,
+ some Stage.adviceFrames,some Stage.prefixPack,some Stage.orderPack,some Stage.prefixCopy,
+ some Stage.skeleton,some Stage.scatter,some Stage.last,some Stage.last,none,
+ some Stage.transition,some Stage.transition,none]
+
+/-- The compressed pair's input ABI. The original processor's program prefix
+is read from its literal input. Every group-specific value is obtained from
+header or workspace addresses. -/
+structure PairTable where
+ /-- Number of instruction addresses in the supplied compressed pair counter. -/
+ pcs : ℕ
+ /-- Number of private registers used by the supplied compressed pair counter. -/
+ regs : ℕ
+ /-- Native instruction template of the compressed pair counter, with eleven public operand
+ slots. -/
+ table : Template pcs regs 11
+
+namespace StageOperands
+
+/-- Supply the router with the address of the flag to read and the outer stage-tag address to
+update. -/
+def router (flag : PublicExpr) : Fin 2 → PublicExpr := ![flag,Layout.stageTag]
+/-- Supply the per-label guess width, the nomination counter base and the number of grammar
+labels. -/
+def nomination (c : Constants) : Fin 3 → PublicExpr := ![2*PublicExpr.d,Layout.counter c,c.grammarLabels]
+
+/-- Fourteen operands describing header sizes, shadow and descriptor bases, and the physical
+sources of the primed indices, advice, cuts and histogram. -/
+def auxiliary (c : Constants) : Fin 14 → PublicExpr :=
+ let s := c.lengths
+ let b := Layout.header
+ let lengths := HeaderLayout.width b .primedLeft
+ ![s.h+2,s.advice,HeaderLayout.capacity s .exterior,c.grammarLabels,Layout.shadow c,Layout.descriptor c,
+ lengths,lengths,HeaderLayout.leftIndex s b,HeaderLayout.rightIndex s b,HeaderLayout.advice s b,
+ HeaderLayout.exterior s b .left,HeaderLayout.exterior s b .right,Layout.counter c]
+
+/-- Supply the copy descriptor table base and the address of the final packed-end word in its
+seventh descriptor. -/
+def auxiliaryCopy (c : Constants) : Fin 2 → PublicExpr := ![Layout.descriptor c, Layout.descriptor c+18]
+
+/-- Public operands of the compressed pair stage, including the original processor's literal
+prefix word and length, workspace and shadow bases, counter and geometry. -/
+def pair (c : Constants) : Fin 11 → InputOperand :=
+ ![.prefixWord,.prefixLength,.geometry (Layout.pairWorkspace c),.geometry (Layout.shadow c),
+ .geometry (Layout.counter c),.geometry c.grammarLabels,.geometry .n,.geometry .d,
+ .geometry 0,.geometry (.lit c.motifLabels),.geometry (HeaderLayout.index Layout.header)]
+
+/-- The left and right exponent bases, increment counter base, digit width and extent used to
+check the exponent update. -/
+def exponents (c : Constants) : Fin 5 → PublicExpr :=
+ ![HeaderLayout.exponent c.lengths Layout.header .left,HeaderLayout.exponent c.lengths Layout.header .right,
+ Layout.counter c,c.Z,c.lengths.e]
+
+/-- Supply the evaluator control-state writer with its radius, destination bank, zero operand
+and machine word width. -/
+def control (c : Constants) (dest : PublicExpr) : Fin 4 → PublicExpr := ![c.radius,dest,0,PublicExpr.w]
+
+/-- Five operands for reading one width-`w` prefix length from advice and storing it at offset
+22 of the frame area. -/
+def lengthPack (c : Constants) : Fin 5 → PublicExpr :=
+ ![HeaderLayout.advice c.lengths Layout.header,Layout.adviceFrames c+22,PublicExpr.w,PublicExpr.w,1]
+
+/-- Supply the frame publisher with the advice and prefix geometry, evaluator banks, exponent
+dimensions and label-order map base. -/
+def adviceFrames (c : Constants) : Fin 11 → PublicExpr :=
+ ![HeaderLayout.advice c.lengths Layout.header,c.prefixCapacity,PublicExpr.w,Layout.adviceFrames c,
+ Layout.packedPrefix c,c.radius,Layout.oldState c,c.Z,c.lengths.e,
+ HeaderLayout.exponent c.lengths Layout.header .left,Layout.orderMap c]
+
+/-- Operands for packing one order-map entry per label from the advice interval after the
+prefix capacity, using the ceiling binary logarithm of the label count as its bit width. -/
+def orderPack (c : Constants) : Fin 5 → PublicExpr :=
+ let width := PublicExpr.clog2 c.labels
+ ![HeaderLayout.advice c.lengths Layout.header + .w + c.prefixCapacity,Layout.orderMap c,width,c.labels*width,c.labels]
+
+/-- Supply the selected cut's configuration address, destination state bank, word width and
+number of configuration words. -/
+def gather (c : Constants) (side : Side) (dest : PublicExpr) : Fin 4 → PublicExpr :=
+ ![HeaderLayout.config c.lengths Layout.header side,dest,PublicExpr.w,c.configWords]
+
+/-- Supply the evaluator step checker with the tape radius, old and new state bases and
+transition scratch address. -/
+def transition (c : Constants) : Fin 4 → PublicExpr :=
+ ![c.radius,Layout.oldState c,Layout.newState c,Layout.transitionScratch c]
+
+end StageOperands
+
+private def framed {p r k : ℕ} (T : Template p r k) (b : PublicExpr) : Piece :=
+ Piece.ofTable (CompressorRecords.Frame.compile T) (fun _ => b)
+
+/-- Each row is a concrete native stage. `O` supplies the separate compressed
+pair computation. Its input bank has the same fixed layout for every length. -/
+def rows (c : Constants) (p : UniversalMachine.Program) (O : PairTable) : Stage → Piece :=
+ let h := Layout.header
+ let frame := Layout.adviceFrames c
+ ![Piece.ofTable LiveHeaderProgram.program (HeaderLayout.operands c.lengths h),
+ Piece.ofTable (Route.table modeTarget) (StageOperands.router (HeaderLayout.mode h)),
+ Piece.ofTable LiveAuxiliaryStages.nomination (StageOperands.nomination c),
+ Piece.ofTable LiveAuxiliaryStages.initialize (StageOperands.auxiliary c),
+ Piece.ofTable LiveAuxiliaryStages.copy (StageOperands.auxiliaryCopy c),
+ ⟨O.pcs,O.regs,11,O.table,StageOperands.pair c⟩,
+ Piece.ofTable LiveExponent.digitTemplate (StageOperands.exponents c),
+ Piece.ofTable (Route.table firstTarget) (StageOperands.router (HeaderLayout.firstTail h)),
+ Piece.ofTable (LiveEvaluatorInitialize.putStage (LiveEvaluatorInitialize.controlTag p)) (StageOperands.control c (Layout.oldState c)),
+ Piece.ofTable LiveEvaluatorAdviceBanks.stageTable (StageOperands.lengthPack c),
+ Piece.ofTable LiveEvaluatorAdviceFrames.template (StageOperands.adviceFrames c),
+ framed LiveEvaluatorAdviceBanks.stageTable frame,
+ Piece.ofTable LiveEvaluatorAdviceBanks.stageTable (StageOperands.orderPack c),
+ framed LiveEvaluatorInitialize.copyStage (frame+8),
+ framed LiveEvaluatorReindexSkeleton.skeletonStage (frame+13),
+ framed LiveEvaluatorReindex.scatterPhase (frame+17),
+ Piece.ofTable LiveConfigGather.table (StageOperands.gather c .left (Layout.oldState c)),
+ Piece.ofTable (Route.table lastTarget) (StageOperands.router (HeaderLayout.flag h .last)),
+ Piece.ofTable LiveEvaluatorInitialize.finalStage (StageOperands.control c (Layout.newState c)),
+ Piece.ofTable LiveConfigGather.table (StageOperands.gather c .right (Layout.newState c)),
+ Piece.ofTable (LiveEvaluatorRAM.Schedule.program p) (StageOperands.transition c)]
+
+/-- The fixed table is independent of input geometry, advice contents, and
+own-prefix values. It can be compiled before choosing the eventual length. -/
+def program (c : Constants) (p : UniversalMachine.Program) (O : PairTable) :=
+ Pieces.program (rows c p O) (next p)
+
+/-- Flatten the live stages' public operand expressions and append the outer stage-tag address. -/
+def operand (c : Constants) (p : UniversalMachine.Program) (O : PairTable) :=
+ Pieces.operand (rows c p O) Layout.stageTag
+
+/-- Evaluate the flattened operands for the chosen geometry and literal processor prefix as
+machine words. -/
+def publicData (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) := Pieces.publicData (rows c p O) Layout.stageTag g lit
+
+/-- Instantiate the linked live group program at the given word width with its evaluated public
+operands. -/
+def machine (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) := Pieces.machine (rows c p O) (next p) Layout.stageTag g lit
+
+/-- Exact native all-path semantics at each length and clock, with choices
+retained across all handoffs, including repeated equal evaluator outcomes. -/
+theorem paths (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (hfit : 21 ≤ 2^g.w) (fuel : ℕ) (hf : 44 ≤ fuel)
+ (st : Option (Word g.w)) (m : Memory g.w) (bs : List (List Bool)) :
+ runSegment (machine c p O g lit).program fuel st m bs =
+ LiveStageLink.stageSegment (Pieces.table (rows c p O)) (next p)
+ (Pieces.word g lit ∘ Pieces.bank (rows c p O)) (Pieces.word g lit (.geometry Layout.stageTag)) fuel st m bs :=
+ Pieces.paths_eq (rows c p O) (next p) Layout.stageTag g lit hfit fuel hf st m bs
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramAdviceCapacity.lean b/lean/OAI/Computability/VPVNP/LiveProgramAdviceCapacity.lean
new file mode 100644
index 0000000000..5c3a65157e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramAdviceCapacity.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceDistribution
+import OAI.Computability.VPVNP.EvaluatorNativeResources
+import OAI.Computability.VPVNP.CursorBounds
+import OAI.Computability.VPVNP.RAMClock
+
+/-!
+# Choosing the live advice exponents before the address multiplier
+
+The raw evaluator prefix and the number of labels have bounds independent
+of the processor geometry. For each fixed address multiplier the quartic
+word width eventually fits in the input length. Thus one pair of exponents
+suffices for the raw prefix capacity and the entire distributed advice
+array for every later choice of multiplier.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.Advice
+
+open Filter BurstRAM LiveEvaluatorAdviceBanks
+
+theorem eventually_power {f : ℕ → ℕ} (hf : PolynomiallyBounded f) :
+ ∃ d : ℕ, ∀ᶠ n : ℕ in atTop, f n ≤ n^d := by
+ obtain ⟨A, k, N, bound⟩ := hf
+ refine ⟨k+1, ?_⟩
+ filter_upwards [eventually_ge_atTop A, eventually_ge_atTop N] with n ha hn
+ rw [pow_succ, Nat.mul_comm]
+ exact (bound n hn).trans (Nat.mul_le_mul_right _ ha)
+
+private theorem eventually_word_le (B : ℕ) : ∀ᶠ n : ℕ in atTop, CursorBounds.wordBits B n ≤ n := by
+ filter_upwards [eventually_word_stage_le B 0] with n h
+ exact (h (addressWidth B n) 0 (Nat.mul_le_mul_left B (clog_le_log2_succ n)) (by simp)).1
+
+/-- The exponents are uniform in the address multiplier. The first capacity
+bounds the actual raw input, and the second bounds the length word, the
+padded raw region and the serialized ordinal table together. -/
+theorem capacity_exponents {rawLength labels : ℕ → ℕ} (hr : PolynomiallyBounded rawLength)
+ (ht : PolynomiallyBounded labels) :
+ ∃ dA d₁ : ℕ, ∀ B : ℕ, ∀ᶠ n : ℕ in atTop,
+ rawLength n ≤ n^dA ∧ CursorBounds.wordBits B n + n^dA + labels n * Nat.clog 2 (labels n) ≤ n^d₁ := by
+ obtain ⟨dA, hA⟩ := eventually_power hr
+ have hc : PolynomiallyBounded (fun n => Nat.clog 2 (labels n)) :=
+ ht.of_le fun _ => Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le
+ obtain ⟨d₁, h₁⟩ := eventually_power ((PolynomiallyBounded.id.add (PolynomiallyBounded.id.pow dA)).add (ht.mul hc))
+ refine ⟨dA, d₁, fun B => ?_⟩
+ filter_upwards [hA, h₁, eventually_word_le B] with n raw total width
+ exact ⟨raw, (Nat.add_le_add_right (Nat.add_le_add_right width _) _).trans total⟩
+
+/-- The canonical distributed tape includes exactly the remaining number
+of zero padding cells after the ordinal table. -/
+def adviceTape {t ordW : ℕ} (w cap size : ℕ) (raw : List Bool) (values : Fin t → Word ordW) : Fin size → Bool :=
+ let padding := size - (w + cap + t*ordW)
+ fun i => (distribution w cap raw values padding)[i.val]?.getD false
+
+theorem adviceTape_words {t ordW : ℕ} (w cap size : ℕ) (raw : List Bool) (values : Fin t → Word ordW)
+ (hr : raw.length ≤ cap) (hs : w + cap + t*ordW ≤ size) :
+ List.ofFn (adviceTape w cap size raw values) =
+ distribution w cap raw values (size - (w + cap + t*ordW)) := by
+ have hlen : (distribution w cap raw values (size - (w + cap + t*ordW))).length = size := by
+ rw [distribution_length cap _ raw values hr]
+ omega
+ apply List.ext_getElem (by rw [List.length_ofFn, hlen])
+ intro i hi hj
+ simp [adviceTape, List.getElem?_eq_getElem hj]
+
+/-- The same exponents also give a canonical advice tape of exactly the
+prescribed size for every possible raw string and ordinal table within
+the uniform bounds. -/
+theorem adviceTape_eventually {bound labels : ℕ → ℕ} (hb : PolynomiallyBounded bound)
+ (ht : PolynomiallyBounded labels) :
+ ∃ dA d₁ : ℕ, ∀ B : ℕ, ∀ᶠ n : ℕ in atTop,
+ let w := CursorBounds.wordBits B n
+ let t := labels n
+ let o := Nat.clog 2 t
+ ∀ (raw : List Bool) (values : Fin t → Word o), raw.length ≤ bound n →
+ raw.length ≤ n^dA ∧ w + n^dA + t*o ≤ n^d₁ ∧
+ List.ofFn (adviceTape w (n^dA) (n^d₁) raw values) =
+ distribution w (n^dA) raw values (n^d₁ - (w + n^dA + t*o)) := by
+ obtain ⟨dA, d₁, h⟩ := capacity_exponents hb ht
+ refine ⟨dA, d₁, fun B => ?_⟩
+ filter_upwards [h B] with n hn
+ intro w t o raw values hr
+ exact ⟨hr.trans hn.1, hn.2, adviceTape_words w _ _ raw values (hr.trans hn.1) hn.2⟩
+
+/-- The raw capacity can be chosen once for the native evaluator's actual
+bit-stack advice, uniformly over its endpoint, stack contents and divisor
+whenever the divisor length and the payload bank satisfy the stated envelopes. -/
+theorem native_capacity_exponents (fields : ℕ) {labels divisorBits footprint : ℕ → ℕ}
+ (ht : PolynomiallyBounded labels) (hd : PolynomiallyBounded divisorBits)
+ (hf : PolynomiallyBounded footprint) :
+ ∃ dA d₁ : ℕ, ∀ B : ℕ, ∀ᶠ n : ℕ in atTop,
+ Evaluator.MatrixCallbacks.adviceCap fields (labels n) (divisorBits n) (footprint n) ≤ n^dA ∧
+ CursorBounds.wordBits B n + n^dA + labels n * Nat.clog 2 (labels n) ≤ n^d₁ :=
+ capacity_exponents (Evaluator.MatrixCallbacks.adviceCap_polynomial fields ht hd hf) ht
+
+open Evaluator RAMTape SliceArithmetic
+
+/-- Applying a single native capacity bound to the concrete advice payload.
+The field, basis coordinates and endpoint may vary without changing the bound. -/
+theorem native_raw_fits {P : Type} {p e ew v t fields divisorBits footprint cap : ℕ} [Fact p.Prime]
+ {K : Type} [Field K] [Algebra (ZMod p) K] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (dim : Word v) (extra : Stacks P) (d : List Bool)
+ (extraSpace : ℕ) (hextra : ∀ k, (extra k).length ≤ extraSpace) (ps : List (WeightedStep.Port P))
+ (s : Fin dim.val × K) (hps : ps.length ≤ fields) (hd : d.length ≤ divisorBits)
+ (hroom : WeightedStep.bankSpace v e ew extraSpace ≤ footprint)
+ (hcap : MatrixCallbacks.adviceCap fields t divisorBits footprint ≤ cap) :
+ (EvaluatorProgramRawInput.advice ps t d (MatrixCallbacks.payload φ dim extra ew s)).length ≤ cap := by
+ apply (MatrixCallbacks.advice_le (w := ew) (t := t) φ dim extra d extraSpace hextra ps s).trans
+ apply le_trans _ hcap
+ unfold MatrixCallbacks.adviceCap
+ gcongr
+
+end LiveProgram.Advice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramAdviceInputLayout.lean b/lean/OAI/Computability/VPVNP/LiveProgramAdviceInputLayout.lean
new file mode 100644
index 0000000000..764dec43fc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramAdviceInputLayout.lean
@@ -0,0 +1,303 @@
+import OAI.Computability.VPVNP.LiveProgramAdviceRun
+import OAI.Computability.VPVNP.LiveEvaluatorInputStages
+
+/-!
+# The live program's midpoint tape layout
+
+The old state bank contains a head-relative two-tape window. The raw prefix
+starts at its central cell, followed immediately by the evaluator runtime
+fields. All scatter sources lie in the earlier header workspace, and the
+permutation lookup table lies beyond both configuration banks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.Advice
+
+open BurstRAM (Word Memory)
+open LiveEvaluatorAdviceFrames LiveEvaluatorAdviceBanks
+open LiveEvaluatorInitialize (firstData sourceAddress inputWord)
+open scoped Fin.CommRing
+
+/-- The four fixed prefix-copy operands, in order the tape radius, old state base, packed
+prefix base and word width. -/
+def copyBank (c : Constants) (g : Geometry) : Fin 4 → Word g.w :=
+ let f := fp c g
+ ![f 5,f 6,f 4,f 2]
+
+/-- Evaluated control-state operands that target the old evaluator configuration bank. -/
+def stateBank (c : Constants) (g : Geometry) :=
+ bank g (StageOperands.control c (Layout.oldState c))
+
+/-- Memory after the length packer has stored the active raw prefix's length. -/
+abbrev initialLengthMemory (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w) :=
+ lengthMemory (lp c g) raw m
+
+/-- The four runtime-skeleton operands evaluated using the stored prefix length, including the
+suffix start and size. -/
+def skeletonBank (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w) :=
+ skeletonFrame (fp c g) (initialLengthMemory c g raw m)
+
+/-- The five operands of the exponent scatter, with its tape destination determined from the
+stored prefix length. -/
+def scatterBank (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w) :=
+ scatterFrame (fp c g) (initialLengthMemory c g raw m)
+
+/-- Address order and exact words supplied to the subsequent three stages. -/
+structure InputRegions (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w) : Prop where
+ radius : (copyBank c g 0).val = c.radius.eval g
+ state : (copyBank c g 1).val = (Layout.oldState c).eval g
+ exponentWidth : (skeletonBank c g raw m 0).val = c.Z.eval g
+ exponentBits : (skeletonBank c g raw m 1).val = c.labels.eval g*c.Z.eval g
+ runtime : (skeletonBank c g raw m 2).val = firstData (copyBank c g) + raw.length
+ runtimeSize : (skeletonBank c g raw m 3).val = 2*(c.labels.eval g*c.Z.eval g)+6*c.Z.eval g+4
+ scatterStart : (scatterBank c g raw m 2).val = firstData (copyBank c g) + raw.length + (2*c.Z.eval g+1)+1
+ incoming : (scatterBank c g raw m 0).val = (HeaderLayout.exponent c.lengths Layout.header .left).eval g
+ incomingStart : ((fp c g) 0).val ≤ (scatterBank c g raw m 0).val
+ incomingEnd : (scatterBank c g raw m 0).val + c.labels.eval g*c.Z.eval g ≤ (copyBank c g 1).val
+ configEnd : (copyBank c g 1).val + LiveEvaluatorEncoding.fieldWords (c.radius.eval g) ≤ ((fp c g) 3).val
+
+theorem inputRegions (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)))
+ (hlimit : (Layout.shadow c).eval g < 2^g.w)
+ (hspace : raw.length + (2*(c.labels.eval g*c.Z.eval g)+6*c.Z.eval g+4) ≤ c.radius.eval g+1) :
+ InputRegions c g raw m := by
+ let M := c.radius.eval g
+ let Z := c.Z.eval g
+ let t := c.labels.eval g
+ let N := t*Z
+ let state := (Layout.oldState c).eval g
+ let incoming := (HeaderLayout.exponent c.lengths Layout.header .left).eval g
+ let source := (HeaderLayout.advice c.lengths Layout.header).eval g
+ let frame := (Layout.adviceFrames c).eval g
+ let f := fp c g
+ let u := initialLengthMemory c g raw m
+ change raw.length+(2*N+6*Z+4) ≤ M+1 at hspace
+ have src_order : source ≤ incoming := by
+ simp only [source,incoming,HeaderLayout.exponent,HeaderLayout.exterior,eval_add]; omega
+ have inp_order : incoming + N ≤ state := by
+ have hh : incoming+N ≤ (HeaderLayout.limit c.lengths Layout.header).eval g := by
+ change (HeaderLayout.exponent c.lengths Layout.header .left).eval g + c.lengths.e.eval g ≤ _
+ simp only [HeaderLayout.limit,HeaderLayout.config,HeaderLayout.exponent,HeaderLayout.exterior,eval_add]
+ omega
+ exact hh.trans (by simp only [state,Layout.oldState,Layout.counter,Layout.descriptor,eval_add]; omega)
+ have fieldEnd : state+(1+(2*M+1)+(2*M+1)) ≤ frame := by
+ change (Layout.oldState c).eval g+c.configWords.eval g ≤ _
+ simp only [frame,Layout.adviceFrames,Layout.transitionScratch,Layout.newState,eval_add]; omega
+ have frameFit : frame < 2^g.w := by
+ change (Layout.adviceFrames c).eval g < _
+ simp only [Layout.shadow,Layout.orderMap,Layout.packedPrefix,eval_add] at hlimit
+ omega
+ have val (x : ℕ) (h : x < 2^g.w) : (Fin.ofNat (2^g.w) x).val = x := Nat.mod_eq_of_lt h
+ have f0 : (f 0).val = source := val source (by omega)
+ have f3 : (f 3).val = frame := val frame frameFit
+ have f5 : (f 5).val = M := val M (by omega)
+ have f6 : (f 6).val = state := val state (by omega)
+ have f7 : (f 7).val = Z := val Z (by omega)
+ have f8 : (f 8).val = N := val N (by omega)
+ have f9 : (f 9).val = incoming := val incoming (by omega)
+ have ha : (actualLength f u).val = raw.length := prepared_length L m
+ have h16 : 16 ≤ 2^g.w := Nat.pow_le_pow_right (by decide : 0 < 2) L.width
+ have v1 : (1 : Word g.w).val = 1 := val 1 (by omega)
+ have v2 : (2 : Word g.w).val = 2 := val 2 (by omega)
+ have v4 : (4 : Word g.w).val = 4 := val 4 (by omega)
+ have v6 : (6 : Word g.w).val = 6 := val 6 (by omega)
+ have hrun : (runtimeBase f u).val = state+1+M+raw.length := by
+ simp only [runtimeBase,Fin.val_add,Nat.mod_add_mod,f5,f6,v1,ha]
+ exact Nat.mod_eq_of_lt (by omega)
+ have hsize : (skeletonSize f).val = 2*N+6*Z+4 := by
+ simp only [skeletonSize,Fin.val_add,Fin.val_mul,Nat.mod_add_mod,Nat.add_mod_mod,f7,f8,v2,v4,v6]
+ exact Nat.mod_eq_of_lt (by omega)
+ have hscat : (scatterBase f u).val = state+1+M+raw.length+(2*Z+1)+1 := by
+ simp only [scatterBase,Fin.val_add,Fin.val_mul,Nat.mod_add_mod,Nat.add_mod_mod,hrun,f7,v2]
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+ constructor
+ · exact f5
+ · exact f6
+ · exact f7
+ · exact f8
+ · change (runtimeBase f u).val = (f 6).val+1+(f 5).val+raw.length
+ rwa [f6,f5]
+ · exact hsize
+ · change (scatterBase f u).val = (f 6).val+1+(f 5).val+raw.length+(2*Z+1)+1
+ rwa [f6,f5]
+ · exact f9
+ · change (f 0).val ≤ (f 9).val; rwa [f0,f9]
+ · change (f 9).val + N ≤ (f 6).val; rwa [f9,f6]
+ · change (f 6).val+(1+(2*M+1)+(2*M+1)) ≤ (f 3).val; rwa [f6,f3]
+
+private theorem prefixSource (c : Constants) (g : Geometry) (raw : List Bool) (j : ℕ) (hj : j < raw.length)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g))) :
+ (sourceAddress (copyBank c g) (j : Word g.w)).val = ((fp c g) 4).val+j/g.w ∧
+ j/g.w < raw.length ⌈/⌉ g.w := by
+ have hw : 0 < g.w := by have := L.width; omega
+ have ha : raw.length ≤ g.w*(raw.length ⌈/⌉ g.w) := (ceilDiv_le_iff_le_mul hw).mp le_rfl
+ have hr : j/g.w < raw.length ⌈/⌉ g.w := (Nat.div_lt_iff_lt_mul hw).mpr (hj.trans_le (by rwa [Nat.mul_comm]))
+ have hjw := Fin.val_cast_of_lt (hj.trans_le L.rawFits |>.trans ((fp c g) 1).isLt)
+ refine ⟨?_,hr⟩
+ have hsum : ((fp c g) 4).val+j/g.w < 2^g.w := by
+ have h := L.prefixBeforeOrder
+ have h' := ((op c g) 1).isLt
+ omega
+ simp only [sourceAddress,Fin.val_add,Fin.val_ofNat,hjw,Nat.add_mod_mod]
+ exact Nat.mod_eq_of_lt hsum
+
+/-- All capacities and nonaliasing conditions for prefix copy, skeleton and
+scatter on the three published operand banks. -/
+theorem inputLayout (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)))
+ (hlimit : (Layout.shadow c).eval g < 2^g.w)
+ (hspace : raw.length + (2*(c.labels.eval g*c.Z.eval g)+6*c.Z.eval g+4) ≤ c.radius.eval g+1) :
+ LiveEvaluatorInputStages.Layout (copyBank c g) (skeletonBank c g raw m) (stateBank c g)
+ (scatterBank c g raw m) (c.labels.eval g) (c.labels.eval g) (c.Z.eval g) raw.length := by
+ let cp := copyBank c g
+ let sk := skeletonBank c g raw m
+ let sc := scatterBank c g raw m
+ let f := fp c g
+ let M := c.radius.eval g
+ let Z := c.Z.eval g
+ let N := c.labels.eval g*Z
+ have R := inputRegions c g raw m L hlimit hspace
+ change raw.length+(2*N+6*Z+4) ≤ M+1 at hspace
+ have hd : firstData cp = (cp 1).val+1+M := by rw [firstData,R.radius]
+ have he : (cp 1).val+(1+(2*M+1)+(2*M+1)) ≤ (f 3).val := R.configEnd
+ have hf : (f 3).val+23 ≤ (f 4).val := L.frameBeforePrefix
+ have hm : (f 4).val + (raw.length ⌈/⌉ g.w) ≤ (sc 1).val := L.prefixBeforeOrder
+ have hi : (sc 0).val+N ≤ (cp 1).val := R.incomingEnd
+ have hb : (sk 2).val = firstData cp+raw.length := R.runtime
+ have hl : (sk 3).val = 2*N+6*Z+4 := R.runtimeSize
+ have hs : (sc 2).val = firstData cp+raw.length+(2*Z+1)+1 := R.scatterStart
+ have hw := (f 3).isLt
+ have hsep : firstData cp+raw.length+(sk 3).val ≤ (f 3).val := by omega
+ change LiveEvaluatorInputStages.Layout cp sk _ sc _ _ Z _
+ constructor
+ · rfl
+ · exact L.frameWidth
+ · omega
+ · intro j hj
+ have hx : (sourceAddress cp (j : Word g.w)).val = (f 4).val + j/g.w := (prefixSource c g raw j hj L).1
+ change (sourceAddress cp (j : Word g.w)).val ≠ (cp 1).val ∧
+ ((sourceAddress cp (j : Word g.w)).val < firstData cp ∨
+ firstData cp+raw.length ≤ (sourceAddress cp (j : Word g.w)).val)
+ rw [hx]
+ have lower : (f 4).val ≤ (f 4).val+j/g.w := Nat.le_add_right ..
+ exact ⟨(lt_of_lt_of_le (show (cp 1).val < (f 4).val by omega) lower).ne',
+ Or.inr ((show firstData cp+raw.length ≤ (f 4).val by omega).trans lower)⟩
+ · exact R.exponentWidth
+ · exact R.exponentBits
+ · exact hb
+ · exact hl
+ · omega
+ · exact ⟨R.exponentWidth,R.exponentBits,by rw [hs,hd,R.radius],by omega,L.orderFit,by omega,
+ Or.inl (by omega),Or.inr (by omega)⟩
+ · intro q
+ have hq : q.val < N := q.isLt
+ dsimp only
+ exact ⟨by omega,Or.inl (by omega)⟩
+ · intro i
+ dsimp only
+ exact ⟨by omega,Or.inr (by omega)⟩
+
+
+/-- In particular the four stages do not touch the old configuration or the
+header's incoming exponent bank between the reserved tag and frame base. -/
+theorem beforeFrame_preserved (c : Constants) (g : Geometry) (lit : LiteralPrefix) (raw : List Bool)
+ (values : Fin (c.labels.eval g) → Word (Nat.clog 2 (c.labels.eval g))) (m : Memory g.w)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)))
+ (hlimit : (Layout.shadow c).eval g < 2^g.w) (k : ℕ)
+ (htag : (tagAddr g lit).val < k) (hbefore : k < ((fp c g) 3).val) :
+ finalMemory c g lit raw values m k = m k := by
+ have h := finalImage c g lit raw values m L hlimit
+ have hf := L.frameBeforePrefix
+ have ho := L.prefixBeforeOrder
+ rw [h.outside k (.inl hbefore) (.inl (by omega)) (.inl (by omega)), BurstRAM.writeMemory,
+ ite_eq_right (by omega)]
+
+/-- Every physical operand loader in the final three middle stages reads the
+four- or five-word bank computed from the validated raw length. -/
+theorem suffixFrameData (c : Constants) (g : Geometry) (lit : LiteralPrefix) (raw : List Bool)
+ (values : Fin (c.labels.eval g) → Word (Nat.clog 2 (c.labels.eval g))) (m : Memory g.w)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)))
+ (hlimit : (Layout.shadow c).eval g < 2^g.w) :
+ let out := finalMemory c g lit raw values m
+ let base := (fp c g) 3
+ CompressorRecords.Frame.data (base+8) out = LiveEvaluatorInitialize.copyPublic (copyBank c g) (raw.length : Word g.w) ∧
+ CompressorRecords.Frame.data (base+13) out = skeletonBank c g raw m ∧
+ CompressorRecords.Frame.data (base+17) out = scatterBank c g raw m := by
+ let f := fp c g
+ let u := initialLengthMemory c g raw m
+ let mt := BurstRAM.writeMemory m (tagAddr g lit) (LiveStageLink.tagWord g.w Stage.prefixCopy)
+ let v := initialLengthMemory c g raw mt
+ have hf : (f 3).val+23 ≤ (f 4).val := L.frameBeforePrefix
+ have hfit : (f 3).val+22 ≤ 2^g.w := by have := (f 4).isLt; omega
+ have hA : (actualLength f v).val = raw.length := prepared_length L mt
+ have hU : (actualLength f u).val = raw.length := prepared_length L m
+ have hlen : actualLength f v = (raw.length : Word g.w) := Fin.ext (hA.trans (Fin.val_cast_of_lt
+ (L.rawFits.trans_lt (f 1).isLt)).symm)
+ have heq : actualLength f v = actualLength f u := Fin.ext (hA.trans hU.symm)
+ have h := (finalImage c g lit raw values m L hlimit).frameData hfit
+ refine ⟨h.2.1.trans ?_, h.2.2.1.trans ?_, h.2.2.2.trans ?_⟩
+ · change copyFrame f v = LiveEvaluatorInitialize.copyPublic (copyBank c g) _
+ funext i; fin_cases i <;> first | exact hlen | rfl
+ · change skeletonFrame f v = skeletonFrame f u
+ simp only [skeletonFrame,runtimeBase,heq]
+ · change scatterFrame f v = scatterFrame f u
+ simp only [scatterFrame,scatterBase,runtimeBase,heq]
+
+/-- Starting in the tagged prepared memory, the prefix copier reads exactly
+the evaluator prefix, the scatter sees the incoming exponent and order words,
+and every cell of the previously initialized control bank is preserved. -/
+theorem preparedInput (c : Constants) (g : Geometry) (lit : LiteralPrefix) (raw : List Bool)
+ (values : Fin (c.labels.eval g) → Word (Nat.clog 2 (c.labels.eval g))) (m : Memory g.w)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)))
+ (hlimit : (Layout.shadow c).eval g < 2^g.w)
+ (hspace : raw.length + (2*(c.labels.eval g*c.Z.eval g)+6*c.Z.eval g+4) ≤ c.radius.eval g+1)
+ (perm : Fin (c.labels.eval g) ≃ Fin (c.labels.eval g)) (dense : Fin (c.labels.eval g) → Word (c.Z.eval g))
+ (horder : ∀ i, (values i).val = (perm i).val)
+ (incoming : ∀ q : Fin (c.labels.eval g*c.Z.eval g),
+ m ((HeaderLayout.exponent c.lengths Layout.header .left).eval g+q.val) =
+ PrimedInputRAM.encodeBit g.w (RAMSerialization.arrayBits _ _ dense q)) :
+ let out := finalMemory c g lit raw values m
+ (∀ j < raw.length, out (sourceAddress (copyBank c g) (j : Word g.w)).val = inputWord g.w raw (j/g.w)) ∧
+ LiveEvaluatorReindex.Sources (scatterBank c g raw m) perm dense out ∧
+ (∀ k : Fin (LiveEvaluatorEncoding.fieldWords (c.radius.eval g)), out (((copyBank c g) 1).val + k.val) =
+ m (((copyBank c g) 1).val+k.val)) := by
+ let cp := copyBank c g
+ let sc := scatterBank c g raw m
+ let t := c.labels.eval g
+ let Z := c.Z.eval g
+ let M := c.radius.eval g
+ let f := fp c g
+ have R := inputRegions c g raw m L hlimit hspace
+ have image := finalImage c g lit raw values m L hlimit
+ have hs : (tagAddr g lit).val < (f 0).val := tag_before_advice c g lit hlimit
+ have hs' : (f 0).val ≤ (sc 0).val := R.incomingStart
+ have hi : (sc 0).val + t*Z ≤ (cp 1).val := R.incomingEnd
+ have hc : (cp 1).val + LiveEvaluatorEncoding.fieldWords M ≤ (f 3).val := R.configEnd
+ refine ⟨?_,⟨?_,?_⟩,?_⟩
+ · intro j hj
+ obtain ⟨ha,hr⟩ := prefixSource c g raw j hj L
+ rw [ha]
+ exact image.rawWord _ hr
+ · intro q
+ change finalMemory c g lit raw values m ((sc 0).val+q.val) = _
+ have hq : q.val < t*Z := q.isLt
+ rw [beforeFrame_preserved c g lit raw values m L hlimit _ (by omega)
+ (show (sc 0).val+q.val < (f 3).val by omega)]
+ exact R.incoming ▸ incoming q
+ · intro i
+ exact (image.ordinalWord i).trans (horder i)
+ · intro k
+ have hk : k.val < LiveEvaluatorEncoding.fieldWords M := k.isLt
+ exact beforeFrame_preserved c g lit raw values m L hlimit _
+ (show (tagAddr g lit).val < (cp 1).val + k.val by omega)
+ (show (cp 1).val+k.val < (f 3).val by omega)
+
+end LiveProgram.Advice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramAdviceLayout.lean b/lean/OAI/Computability/VPVNP/LiveProgramAdviceLayout.lean
new file mode 100644
index 0000000000..c31365a8da
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramAdviceLayout.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.LiveProgram
+import OAI.Computability.VPVNP.LiveEvaluatorAdvicePrepared
+
+/-!
+# The live program's concrete advice allocations
+
+The length, prefix and order stages use the public expressions installed in
+the linked program. A single upper bound on the end of the order map puts
+all their public addresses, lengths and scheduled cursors in range.
+The physical header length bounds the distributed source interval, and the
+prefix capacity bounds the number of packed prefix words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.Advice
+
+open BurstRAM (Word)
+open LiveEvaluatorAdviceBanks (PreparedLayout)
+
+/-- Evaluate a bank of public geometry expressions and encode each result as a word of the
+geometry's width. -/
+def bank {k : ℕ} (g : Geometry) (xs : Fin k → PublicExpr) : Fin k → Word g.w :=
+ fun i => Fin.ofNat (2^g.w) ((xs i).eval g)
+
+/-- The actual three operand rows meet every address, count and disjointness
+hypothesis of the four-stage native advice initializer. -/
+theorem preparedLayout (c : Constants) (g : Geometry) (raw : List Bool)
+ (hw : 4 ≤ g.w) (hlimit : (Layout.shadow c).eval g < 2^g.w)
+ (hadvice : g.w + c.prefixCapacity.eval g + c.labels.eval g * Nat.clog 2 (c.labels.eval g) ≤
+ c.lengths.advice.eval g)
+ (hraw : raw.length ≤ c.prefixCapacity.eval g) :
+ PreparedLayout (bank g (StageOperands.lengthPack c)) (bank g (StageOperands.adviceFrames c))
+ (bank g (StageOperands.orderPack c)) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)) := by
+ let src := (HeaderLayout.advice c.lengths Layout.header).eval g
+ let frame := (Layout.adviceFrames c).eval g
+ let packed := (Layout.packedPrefix c).eval g
+ let ord := (Layout.orderMap c).eval g
+ let t := c.labels.eval g
+ let o := Nat.clog 2 t
+ let C := c.prefixCapacity.eval g
+ let W := 2^g.w
+ change g.w + C + t*o ≤ c.lengths.advice.eval g at hadvice
+ change raw.length ≤ C at hraw
+ have hH : src + c.lengths.advice.eval g ≤ (HeaderLayout.limit c.lengths Layout.header).eval g := by
+ simp only [HeaderLayout.limit, HeaderLayout.config, HeaderLayout.exponent, HeaderLayout.exterior,
+ eval_add, src]
+ omega
+ have hF : (HeaderLayout.limit c.lengths Layout.header).eval g ≤ frame := by
+ simp only [frame, Layout.adviceFrames, Layout.transitionScratch, Layout.newState, Layout.oldState,
+ Layout.counter, Layout.descriptor, eval_add]
+ omega
+ have hsource : src + g.w + C + t*o ≤ frame := by omega
+ have hP : packed = frame+24 := rfl
+ have hO : ord = packed+C := rfl
+ change ord + t < W at hlimit
+ have hord : o ≤ g.w := Nat.clog_le_of_le_pow (by change t ≤ W; omega)
+ let q := raw.length ⌈/⌉ g.w
+ have hwpos : 0 < g.w := by omega
+ have hq : q ≤ raw.length := (ceilDiv_le_iff_le_mul hwpos).mpr
+ (Nat.le_mul_of_pos_left _ hwpos)
+ have hqmul : q*g.w ≤ raw.length+g.w := by
+ change ((raw.length+g.w-1)/g.w)*g.w ≤ _
+ exact (Nat.div_mul_le_self ..).trans (Nat.sub_le ..)
+ have hcur : q*(g.w+1) < W := by rw [Nat.mul_add, Nat.mul_one]; omega
+ have oCur : t*(o+1) < W := by rw [Nat.mul_add, Nat.mul_one]; omega
+ have val (x : ℕ) (h : x < W) : (Fin.ofNat (2^g.w) x).val = x := Nat.mod_eq_of_lt h
+ let lp := bank g (StageOperands.lengthPack c)
+ let fp := bank g (StageOperands.adviceFrames c)
+ let op := bank g (StageOperands.orderPack c)
+ have f0 : (fp 0).val = src := val (src) (by omega)
+ have f1 : (fp 1).val = C := val (C) (by omega)
+ have f2 : (fp 2).val = g.w := val (g.w) (by omega)
+ have f3 : (fp 3).val = frame := val (frame) (by omega)
+ have f4 : (fp 4).val = packed := val (packed) (by omega)
+ have l1 : (lp 1).val = frame+22 := val (frame+22) (by omega)
+ have l2 : (lp 2).val = g.w := f2
+ have l4 : (lp 4).val = 1 := val (1) (by omega)
+ have o0 : (op 0).val = src+g.w+C := val (src+g.w+C) (by omega)
+ have o1 : (op 1).val = ord := val (ord) (by omega)
+ have o2 : (op 2).val = o := val (o) (by omega)
+ have o3 : (op 3).val = t*o := val (t*o) (by omega)
+ have o4 : (op 4).val = t := val (t) (by omega)
+ change PreparedLayout lp fp op raw t o
+ refine ⟨hw,f2,by omega,rfl,by omega,l2,l2,l4,by omega,rfl,o2,hord,o3,o4,by omega,by omega,?_,
+ by omega,hcur,oCur⟩
+ change (fp 4).val + q ≤ (op 1).val
+ omega
+
+end LiveProgram.Advice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramAdvicePackRun.lean b/lean/OAI/Computability/VPVNP/LiveProgramAdvicePackRun.lean
new file mode 100644
index 0000000000..ec91d58914
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramAdvicePackRun.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.LiveProgram
+import OAI.Computability.VPVNP.LiveStageSegments
+import OAI.Computability.VPVNP.LiveEvaluatorAdvicePackStage
+
+/-!
+# The three advice pack sweeps in the outer live program
+
+The fixed component dispatches its row cells on the shared external memory.
+Every intermediate cursor preserves the stage tag. The last report replaces
+the tag by the destination and returns zero. The indirect prefix stage reads
+its five public operands from a stable external frame on every call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.AdvicePackRun
+
+open BurstRAM LiveEvaluatorAdviceBanks
+open LiveStageLink (tagWord linkedReport)
+open CompressorRecords
+open scoped Fin.CommRing
+
+/-- External address of the outer stage tag used when the packed advice stages transfer
+control. -/
+abbrev tagAddr (g : Geometry) (lit : LiteralPrefix) := Pieces.word g lit (.geometry Layout.stageTag)
+
+variable {c : Constants} {p : UniversalMachine.Program} {O : PairTable}
+variable {g : Geometry} {lit : LiteralPrefix} {s dest : Stage}
+variable {pub : Fin 5 → Word g.w} {raw : List Bool} {cap : ℕ}
+
+private theorem run_fixed {w : ℕ} {C : Type*} (P : BurstRAM.Program w C) (fuel n bound : ℕ)
+ (state : ℕ → Word w) (mem : ℕ → Memory w)
+ (step : ∀ i < n, ∃ r, execute P fuel (P.start (state i)) (mem i) [] = some r ∧
+ r.result = some (state (i+1)) ∧ after (mem i) r.events = mem (i+1) ∧ r.probes ≤ bound) :
+ ∃ rs, runSegment P fuel (some (state 0)) (mem 0) (List.replicate n []) = some rs ∧
+ endState (some (state 0)) rs = some (state n) ∧ after (mem 0) (eventLog rs) = mem n ∧
+ rs.length = n ∧ ∀ r ∈ rs, r.probes ≤ bound ∧ r.events.length < fuel := by
+ induction n with
+ | zero => exact ⟨[], rfl, rfl, rfl, rfl, by simp⟩
+ | succ n ih =>
+ obtain ⟨rs, hrun, hstate, hmem, hlen, hcost⟩ := ih (fun i hi => step i (by omega))
+ obtain ⟨r, hr, hs, hm, hp⟩ := step n (by omega)
+ refine ⟨rs ++ [r], ?_, ?_, ?_, by simp [hlen], ?_⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, hrun]
+ simp only [Option.bind_some, hstate, hmem, runSegment, hr, Option.map_some]
+ · simpa only [endState_append, endState] using hs
+ · simpa only [eventLog, List.flatMap_append, List.flatMap_singleton, after, List.foldl_append] using
+ (show after (after (mem 0) (eventLog rs)) r.events = _ by rwa [hmem])
+ · rw [List.forall_mem_append, List.forall_mem_singleton]
+ exact ⟨hcost, hp, (execute_spec hr).1.length_lt⟩
+
+private abbrev image (pub : Fin 5 → Word g.w) (raw : List Bool) (m : Memory g.w) (i : ℕ) :=
+ packMemory pub raw m (min i (packCalls pub))
+
+/-- Endpoint and resource specification of the linked advice stage. -/
+def LinkedPack (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (dest : Stage) (pub : Fin 5 → Word g.w) (raw : List Bool)
+ (m : Memory g.w) (cap probes : ℕ) : Prop :=
+ ∃ logs, runSegment (machine c p O g lit).program cap (some 0) m
+ (List.replicate (stageCalls pub) []) = some logs ∧
+ endState (some 0) logs = some 0 ∧ after m (eventLog logs) =
+ writeMemory (packMemory pub raw m (packCalls pub)) (tagAddr g lit) (tagWord g.w dest) ∧
+ logs.length = stageCalls pub ∧ ∀ r ∈ logs, r.probes ≤ probes ∧ r.events.length < cap
+
+private theorem lift (m : Memory g.w) (hnext : next p s = some dest) (fit : 21 ≤ 2^g.w)
+ (f b : ℕ) (hcap : f+47 ≤ cap) (htag : m (tagAddr g lit).val = tagWord g.w s)
+ (outside : (tagAddr g lit).val < (pub 1).val ∨ (pub 1).val+(pub 4).val ≤ (tagAddr g lit).val)
+ (step : ∀ i < stageCalls pub,
+ let Q := Pieces.component (rows c p O) s g lit
+ let mem := image pub raw m i
+ ∃ r, execute Q f (Q.start (Fin.ofNat (2^g.w) i)) mem [] = some r ∧
+ r.result = packControl g.w (stageCalls pub) (i+1) ∧ after mem r.events = image pub raw m (i+1) ∧
+ r.probes ≤ b) : LinkedPack c p O g lit dest pub raw m cap (b+2) := by
+ let tag := tagAddr g lit
+ let total := stageCalls pub
+ let cursor := fun i => if i = total then (0 : Word g.w) else Fin.ofNat (2^g.w) i
+ let mem := fun i => if i = total then writeMemory (image pub raw m i) tag (tagWord g.w dest)
+ else image pub raw m i
+ let P := (machine c p O g lit).program
+ have one (i : ℕ) (hi : i < total) : ∃ r, execute P cap (P.start (cursor i)) (mem i) [] = some r ∧
+ r.result = some (cursor (i+1)) ∧ after (mem i) r.events = mem (i+1) ∧ r.probes ≤ b+2 := by
+ obtain ⟨r, hr, hstate, hmem, hprobes⟩ := step i hi
+ have tagged : image pub raw m i tag.val = tagWord g.w s := by
+ rw [image, packMemory_outside _ _ _ _ _ outside, htag]
+ let out := linkedReport (next p) tag s r
+ have hcall := Pieces.execute_component (rows c p O) (next p) Layout.stageTag g lit s fit hcap
+ (Fin.ofNat (2^g.w) i) (image pub raw m i) tagged [] r hr
+ refine ⟨out, ?_, ?_, ?_, ?_⟩
+ · rw [show mem i = image pub raw m i from ite_eq_right hi.ne,
+ show cursor i = Fin.ofNat (2^g.w) i from ite_eq_right hi.ne]
+ exact hcall
+ · rw [show out.result = _ from LiveStageLink.linkedReport_result (next p) tag s r, hstate]
+ by_cases hlast : i+1 = total
+ · simp only [packControl, cursor, total, ite_eq_left (show i+1 = stageCalls pub from hlast),
+ hnext, Option.map_some]
+ · simp only [packControl, cursor, show ¬i+1 = stageCalls pub from hlast, hlast, ite_false]
+ · rw [show mem i = image pub raw m i from ite_eq_right hi.ne]
+ rw [show after (image pub raw m i) out.events = _ from
+ LiveStageLink.linkedReport_after (next p) tag s r _, hstate, hmem]
+ by_cases hlast : i+1 = total
+ · simp only [packControl, mem, total, ite_eq_left (show i+1 = stageCalls pub from hlast), hnext]
+ · simp only [packControl, mem, show ¬i+1 = stageCalls pub from hlast, hlast, ite_false]
+ · have hp := LiveStageLink.linkedReport_probes (next p) tag s r
+ change (linkedReport (next p) tag s r).probes ≤ b+2
+ rw [hp]
+ split <;> omega
+ have ht : 0 < total := Nat.zero_lt_one.trans_le (le_max_left ..)
+ have hc : packCalls pub ≤ total := le_max_right ..
+ simpa only [LinkedPack, P, cursor, mem, ite_eq_right ht.ne, ite_eq_left rfl, image, tag,
+ show Fin.ofNat (2^g.w) 0 = 0 from rfl,
+ Nat.zero_min, packMemory_zero, min_eq_right hc] using run_fixed P cap total (b+2) cursor mem one
+
+/-- The linked program executes a directly supplied row packer and advances
+to the next stage with its destination tag and zero cursor. -/
+theorem linkedPack_direct (L : PackLayout pub raw) (m : Memory g.w) (hs : PackSource pub raw m)
+ (hnext : next p s = some dest) (fit : 21 ≤ 2^g.w) (hcap : 80 ≤ cap)
+ (htag : m (tagAddr g lit).val = tagWord g.w s)
+ (outside : (tagAddr g lit).val < (pub 1).val ∨ (pub 1).val+(pub 4).val ≤ (tagAddr g lit).val)
+ (same : ∀ st mem bits, let Q := Pieces.component (rows c p O) s g lit
+ let R := (stageTable.instantiate g.w pub).program
+ execute Q 33 (Q.start st) mem bits = execute R 33 (R.start st) mem bits) :
+ LinkedPack c p O g lit dest pub raw m cap 5 := by
+ apply lift m hnext fit 33 3 hcap htag outside
+ intro i hi Q mem
+ obtain ⟨es, hr, hm, hp⟩ := stageStep L m hs (fuel := 33) le_rfl i hi
+ exact ⟨⟨es, packControl g.w (stageCalls pub) (i+1)⟩, (same _ mem []).trans (hr []), rfl, hm, hp⟩
+
+/-- Loading five public operands on every call preserves the same output
+memory. The frame remains readable throughout because each of its five
+addresses lies outside the bank being written. -/
+theorem linkedPack_framed (L : PackLayout pub raw) (m : Memory g.w) (hs : PackSource pub raw m)
+ (hnext : next p s = some dest) (fit : 21 ≤ 2^g.w) (hcap : 100 ≤ cap)
+ (htag : m (tagAddr g lit).val = tagWord g.w s)
+ (outside : (tagAddr g lit).val < (pub 1).val ∨ (pub 1).val+(pub 4).val ≤ (tagAddr g lit).val)
+ (base : Word g.w) (hdata : Frame.data base m = pub)
+ (frameOutside : ∀ j : Fin 5, (base+Fin.ofNat (2^g.w) j.val).val < (pub 1).val ∨
+ (pub 1).val+(pub 4).val ≤ (base+Fin.ofNat (2^g.w) j.val).val)
+ (same : ∀ st mem bits, let Q := Pieces.component (rows c p O) s g lit
+ let R := (Frame.machine stageTable base).program
+ execute Q 53 (Q.start st) mem bits = execute R 53 (R.start st) mem bits) :
+ LinkedPack c p O g lit dest pub raw m cap 10 := by
+ apply lift m hnext fit 53 8 hcap htag outside
+ intro i hi Q mem
+ obtain ⟨es, hr, hm, hp⟩ := stageStep L m hs (fuel := 33) le_rfl i hi
+ let st := Fin.ofNat (2^g.w) i
+ let r : Report g.w := ⟨es, packControl g.w (stageCalls pub) (i+1)⟩
+ let wrapped := LiveStageLink.prependLog (Frame.loadEvents base mem 0 5) r
+ have bank : Frame.data base mem = pub := by
+ rw [← hdata]
+ funext j
+ exact packMemory_outside pub raw m _ _ (frameOutside j)
+ have hsource : execute (stageTable.instantiate g.w pub).program 33
+ ((stageTable.instantiate g.w pub).program.start st) mem [] = some r := hr []
+ have hwrap := Frame.execute_frame stageTable base st 33 mem []
+ dsimp only at hwrap
+ rw [bank, hsource] at hwrap
+ obtain ⟨_, hpr, _, hmemory, hresult⟩ := Frame.frame_cost base mem 0 5 r
+ have hbound : wrapped.probes ≤ 8 := by
+ change r.probes ≤ 3 at hp
+ change wrapped.probes = 5+r.probes at hpr
+ omega
+ exact ⟨wrapped, (same st mem []).trans hwrap, hresult, hmemory.trans hm, hbound⟩
+
+end LiveProgram.AdvicePackRun
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramAdviceRun.lean b/lean/OAI/Computability/VPVNP/LiveProgramAdviceRun.lean
new file mode 100644
index 0000000000..4f1bae5efa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramAdviceRun.lean
@@ -0,0 +1,279 @@
+import OAI.Computability.VPVNP.LiveProgramAdviceSplice
+import OAI.Computability.VPVNP.LiveProgramAdvicePackRun
+import OAI.Computability.VPVNP.LiveDeterministicPaths
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceResources
+
+/-!
+# The four linked advice stages of the live program
+
+Starting at the length-field stage, the linked machine packs the length,
+publishes and validates the four operand frames, packs the evaluator's
+actual prefix through its dynamic frame, and packs the ordinal table.
+Each transfer writes only the reserved stage tag. The last report returns
+cursor zero to the prefix-copy stage with the full prepared memory image.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.Advice
+
+open BurstRAM (Word Memory writeMemory)
+open LiveStageLink (tagWord)
+open LiveEvaluatorAdviceBanks
+open LiveEvaluatorAdviceFrames (actualLength published frameData)
+open scoped Fin.CommRing
+
+/-- The evaluated public operand bank for packing the advised prefix length. -/
+abbrev lp (c : Constants) (g : Geometry) := bank g (StageOperands.lengthPack c)
+/-- The evaluated public operand bank for publishing the four midpoint input frames. -/
+abbrev fp (c : Constants) (g : Geometry) := bank g (StageOperands.adviceFrames c)
+/-- The evaluated public operand bank for packing the advised label order. -/
+abbrev op (c : Constants) (g : Geometry) := bank g (StageOperands.orderPack c)
+
+/-- Number of burst calls across length packing, the single frame publication, active-prefix
+packing and order packing. -/
+def calls (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w) :=
+ stageCalls (lp c g) + 1 + stageCalls (rawOperands (lp c g) (fp c g) raw m) + stageCalls (op c g)
+
+/-- The prepared advice memory with the outer tag set to enter prefix copying. -/
+def finalMemory (c : Constants) (g : Geometry) (lit : LiteralPrefix) (raw : List Bool)
+ (values : Fin (c.labels.eval g) → Word (Nat.clog 2 (c.labels.eval g))) (m : Memory g.w) :=
+ writeMemory (preparedAdviceMemory (lp c g) (fp c g) (op c g) raw values m) (tagAddr g lit)
+ (tagWord g.w Stage.prefixCopy)
+
+/-- Upper bound on calls plus external probes for the four advice preparation stages, including
+the fixed frame-publication charge. -/
+def work (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w) :=
+ 6*stageCalls (lp c g) + 23 + 11*stageCalls (rawOperands (lp c g) (fp c g) raw m) +
+ 6*stageCalls (op c g)
+
+/-- Every successful execution of the given number of choice-free calls from cursor zero has
+total calls-plus-probes cost at most the supplied limit. -/
+def CostLimit {w : ℕ} {C : Type*} (P : BurstRAM.Program w C) (fuel calls : ℕ)
+ (m : Memory w) (cost : ℕ) : Prop :=
+ ∀ logs, BurstRAM.runSegment P fuel (some 0) m (List.replicate calls []) = some logs →
+ RAMBuckets.cost BurstRAM.Report.probes logs ≤ cost
+
+private theorem reportCost {w q : ℕ} (logs : List (BurstRAM.Report w))
+ (hp : ∀ r ∈ logs, r.probes ≤ q) : RAMBuckets.cost BurstRAM.Report.probes logs ≤ (q+1)*logs.length := by
+ induction logs with
+ | nil => simp [RAMBuckets.cost]
+ | cons r rs ih =>
+ have h := hp r (by simp)
+ have t := ih (fun r hr => hp r (List.mem_cons_of_mem _ hr))
+ simp only [RAMBuckets.cost, List.length_cons, Nat.mul_succ]; omega
+
+theorem returning_cost {w : ℕ} {C : Type*} {P : BurstRAM.Program w C} {f n q} {m u : Memory w}
+ (h : Returning P f n q m u) : CostLimit P f n m ((q+1)*n) := by
+ obtain ⟨logs,hr,-,-,hl,hb⟩ := h
+ intro rs hrun
+ obtain rfl := Option.some.inj (hr.symm.trans hrun)
+ rw [← hl]
+ exact reportCost _ (fun r h => (hb r h).1)
+
+theorem costLimit_append {w : ℕ} {C : Type*} {P : BurstRAM.Program w C} {f a b qa qb x y}
+ {m u v : Memory w} (ha : Returning P f a qa m u) (hb : Returning P f b qb u v)
+ (cx : CostLimit P f a m x) (cy : CostLimit P f b u y) :
+ CostLimit P f (a+b) m (x+y) := by
+ obtain ⟨xs,hx,hxe,hxm,-,-⟩ := ha
+ obtain ⟨ys,hy,-,-,-,-⟩ := hb
+ intro logs hr
+ rw [List.replicate_add, PrimedSchedule.runSegment_append, hx] at hr
+ have he : xs++ys = logs := by simpa only [Option.bind_some,hxe,hxm,hy,Option.map_some,Option.some.injEq] using hr
+ rw [← he, RAMBuckets.cost_append]
+ exact Nat.add_le_add (cx _ hx) (cy _ hy)
+
+/-- Execute the complete native advice prefix in the shared machine with its
+real tag writes and repeated fetches of the dynamic prefix-packer frame. -/
+theorem fourStages_budget (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (m : Memory g.w) (raw : List Bool)
+ (values : Fin (c.labels.eval g) → Word (Nat.clog 2 (c.labels.eval g)))
+ {a padding : ℕ} (advice : Fin a → Bool)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)))
+ (copied : ∀ i : Fin a, m (((fp c g) 0).val+i.val) = PrimedInputRAM.encodeBit g.w (advice i))
+ (htape : List.ofFn advice = distribution g.w ((fp c g) 1).val raw values padding)
+ (hlimit : (Layout.shadow c).eval g < 2^g.w) {cap : ℕ} (hf : 130 ≤ cap)
+ (htag : m (tagAddr g lit).val = tagWord g.w Stage.prefixLength) :
+ Returning (machine c p O g lit).program cap (calls c g raw m) 22 m (finalMemory c g lit raw values m) ∧
+ CostLimit (machine c p O g lit).program cap (calls c g raw m) m (work c g raw m) := by
+ let lenPub := lp c g
+ let framePub := fp c g
+ let ordPub := op c g
+ let rawPub := rawOperands lenPub framePub raw m
+ let P := (machine c p O g lit).program
+ let tag := tagAddr g lit
+ let tagged (mem : Memory g.w) (s : Stage) := writeMemory mem tag (tagWord g.w s)
+ let m₁ := lengthMemory lenPub raw m
+ let m₂ := published framePub m₁
+ let m₃ := rawMemory lenPub framePub raw m
+ let m₄ := preparedAdviceMemory lenPub framePub ordPub raw values m
+ have htag' (mem : Memory g.w) (s : Stage) : tagged mem s tag.val = tagWord g.w s := by
+ simp [tagged,writeMemory]
+ have hsrc : tag.val < (framePub 0).val := tag_before_advice c g lit hlimit
+ have hframe : tag.val < (framePub 3).val := by
+ have h := L.adviceBeforeFrame
+ change (framePub 0).val + g.w + (framePub 1).val + _ ≤ (framePub 3).val at h
+ omega
+ have hbefore : (framePub 3).val + 23 ≤ (framePub 4).val := L.frameBeforePrefix
+ have hroom : (framePub 3).val+22 < 2^g.w := by have := (framePub 4).isLt; omega
+ have hw : 0 < g.w := by have := L.width; omega
+ have hfit : 21 ≤ 2^g.w := by omega
+ obtain ⟨hlength,hraw,hord⟩ := preparedSources L copied htape
+ have r1 : Returning P cap (stageCalls lenPub) 5 m (tagged m₁ Stage.adviceFrames) :=
+ AdvicePackRun.linkedPack_direct (c := c) (p := p) (O := O) (s := Stage.prefixLength)
+ (dest := Stage.adviceFrames) (g := g) (lit := lit) (lengthLayout L) m hlength rfl hfit
+ (by omega) htag (.inl (show tag.val < (lenPub 1).val by have h : (lenPub 1).val = (framePub 3).val+22 := L.lengthDest; omega))
+ (fun _ _ _ => rfl)
+ have hcap : actualLength framePub (tagged m₁ Stage.adviceFrames) ≤ framePub 1 := by
+ rw [actualLength_write_tag framePub m₁ tag _ hframe hroom]
+ exact (prepared_length L m).le.trans L.rawFits
+ have hpub : published framePub (tagged m₁ Stage.adviceFrames) = tagged m₂ Stage.adviceFrames :=
+ published_write_tag framePub m₁ tag _ hframe hw hroom
+ have r2 : Returning P cap 1 22 (tagged m₁ Stage.adviceFrames) (tagged m₂ Stage.prefixPack) := by
+ have hr := returning_frames c p O g lit (tagged m₁ Stage.adviceFrames) cap hfit hf
+ (htag' ..) hcap (show 0 < (framePub 2).val by rw [L.frameWidth]; exact hw)
+ change Returning P cap 1 22 _ (tagged (published framePub _) Stage.prefixPack) at hr
+ simpa only [hpub,tagged,write_tag_twice] using hr
+ have hbase : (rawPub 0).val = (framePub 0).val+g.w := by
+ change (framePub 0 + framePub 2).val = _
+ rw [Fin.val_add,L.frameWidth,Nat.mod_eq_of_lt (by
+ have h : (framePub 0).val+g.w+(framePub 1).val+_ ≤ (framePub 3).val := L.adviceBeforeFrame
+ have := (framePub 3).isLt; omega)]
+ have hrSrc : PackSource rawPub raw (tagged m₂ Stage.prefixPack) :=
+ (packSource_write_tag rawPub raw m₂ tag _ (by omega)).mpr hraw
+ have hrawDest : rawPub 1 = framePub 4 := rfl
+ have outside (j : Fin 5) : (framePub 3 + Fin.ofNat (2^g.w) j.val).val < (rawPub 1).val := by
+ rw [Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod, Nat.mod_eq_of_lt (by have := j.isLt; omega),hrawDest]
+ have := j.isLt; omega
+ have hdata : CompressorRecords.Frame.data (framePub 3) (tagged m₂ Stage.prefixPack) = rawPub := by
+ change CompressorRecords.Frame.data (framePub 3) (tagged m₂ Stage.prefixPack) =
+ LiveEvaluatorAdviceFrames.prefixFrame framePub m₁
+ rw [← (frameData framePub m₁ hw hroom.le).1]
+ funext j
+ have hsum : (framePub 3 + (j.val : Word g.w)).val = (framePub 3).val+j.val := by
+ rw [Fin.val_add,Fin.val_natCast,Nat.add_mod_mod,Nat.mod_eq_of_lt (by have := j.isLt; omega)]
+ simp [CompressorRecords.Frame.data,tagged,writeMemory,hsum,show (framePub 3).val+j.val ≠ tag.val by omega,m₂]
+ have r3 : Returning P cap (stageCalls rawPub) 10 (tagged m₂ Stage.prefixPack) (tagged m₃ Stage.orderPack) := by
+ have hr := AdvicePackRun.linkedPack_framed (c := c) (p := p) (O := O) (s := Stage.prefixPack)
+ (dest := Stage.orderPack) (g := g) (lit := lit) (rawLayout L m) (tagged m₂ Stage.prefixPack) hrSrc rfl hfit
+ (show 100 ≤ cap by omega) (htag' ..) (.inl (show tag.val < (rawPub 1).val by rw [hrawDest]; omega)) (framePub 3) hdata
+ (fun j => Or.inl (outside j)) (fun _ _ _ => rfl)
+ change Returning P cap (stageCalls rawPub) 10 _ (tagged (packMemory rawPub raw _ _) Stage.orderPack) at hr
+ change Returning P cap _ 10 _ (tagged (packMemory rawPub raw m₂ (packCalls rawPub)) Stage.orderPack)
+ simpa only [tagged,packMemory_write_tag _ _ _ _ _ _ (show tag.val < (rawPub 1).val by rw [hrawDest]; omega),
+ write_tag_twice] using hr
+ have hOrderSrc : tag.val < (ordPub 0).val := by
+ have h : (ordPub 0).val = (framePub 0).val+g.w+(framePub 1).val := L.ordinalSource
+ omega
+ have hOrderDst : tag.val < (ordPub 1).val := by
+ have h : (framePub 4).val + (raw.length ⌈/⌉ g.w) ≤ (ordPub 1).val := L.prefixBeforeOrder
+ omega
+ have r4 : Returning P cap (stageCalls ordPub) 5 (tagged m₃ Stage.orderPack) (tagged m₄ Stage.prefixCopy) := by
+ have hs := (packSource_write_tag ordPub (ordinalBits values) m₃ tag (tagWord g.w Stage.orderPack) hOrderSrc).mpr hord
+ have hr := AdvicePackRun.linkedPack_direct (c := c) (p := p) (O := O) (s := Stage.orderPack)
+ (dest := Stage.prefixCopy) (g := g) (lit := lit) (orderLayout L values) (tagged m₃ Stage.orderPack) hs
+ rfl hfit (show 80 ≤ cap by omega) (htag' ..) (.inl hOrderDst) (fun _ _ _ => rfl)
+ change Returning P cap (stageCalls ordPub) 5 _ (tagged (packMemory ordPub (ordinalBits values) _ _) _) at hr
+ change Returning P cap _ 5 _ (tagged (packMemory ordPub (ordinalBits values) m₃ (packCalls ordPub)) Stage.prefixCopy)
+ simpa only [tagged,packMemory_write_tag _ _ _ _ _ _ hOrderDst,write_tag_twice] using hr
+ have r12 := returning_append r1 r2
+ have r123 := returning_append r12 r3
+ have c12 := costLimit_append r1 r2 (returning_cost r1) (returning_cost r2)
+ have c123 := costLimit_append r12 r3 c12 (returning_cost r3)
+ exact ⟨returning_append r123 r4,costLimit_append r123 r4 c123 (returning_cost r4)⟩
+
+/-- Returning execution and final image of the four stages. -/
+theorem fourStages (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (m : Memory g.w) (raw : List Bool)
+ (values : Fin (c.labels.eval g) → Word (Nat.clog 2 (c.labels.eval g)))
+ {a padding : ℕ} (advice : Fin a → Bool)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)))
+ (copied : ∀ i : Fin a, m (((fp c g) 0).val+i.val) = PrimedInputRAM.encodeBit g.w (advice i))
+ (htape : List.ofFn advice = distribution g.w ((fp c g) 1).val raw values padding)
+ (hlimit : (Layout.shadow c).eval g < 2^g.w) {cap : ℕ} (hf : 130 ≤ cap)
+ (htag : m (tagAddr g lit).val = tagWord g.w Stage.prefixLength) :
+ Returning (machine c p O g lit).program cap (calls c g raw m) 22 m (finalMemory c g lit raw values m) :=
+ (fourStages_budget c p O g lit m raw values advice L copied htape hlimit hf htag).1
+
+
+/-- The end of the four-stage run retains all prepared banks. Its only extra
+write is the prefix-copy tag, so the frame statement compares with the
+initial memory carrying that same tag. -/
+theorem finalImage (c : Constants) (g : Geometry) (lit : LiteralPrefix) (raw : List Bool)
+ (values : Fin (c.labels.eval g) → Word (Nat.clog 2 (c.labels.eval g))) (m : Memory g.w)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)))
+ (hlimit : (Layout.shadow c).eval g < 2^g.w) :
+ PreparedImage (lp c g) (fp c g) (op c g) raw values
+ (writeMemory m (tagAddr g lit) (tagWord g.w Stage.prefixCopy)) (finalMemory c g lit raw values m) := by
+ let tag := tagAddr g lit
+ let v := tagWord g.w Stage.prefixCopy
+ let lenPub := lp c g
+ let framePub := fp c g
+ let ordPub := op c g
+ let rp := rawOperands lenPub framePub raw m
+ have ht : tag.val < (framePub 0).val := tag_before_advice c g lit hlimit
+ have hsrc : (framePub 0).val+g.w+(framePub 1).val+_ ≤ (framePub 3).val := L.adviceBeforeFrame
+ have hf : (framePub 3).val+23 ≤ (framePub 4).val := L.frameBeforePrefix
+ have hfit : (framePub 3).val+22 < 2^g.w := by have := (framePub 4).isLt; omega
+ have htFrame : tag.val < (framePub 3).val := by omega
+ have hw : 0 < g.w := by have := L.width; omega
+ have htLen : tag.val < (lenPub 1).val := by have h : (lenPub 1).val = (framePub 3).val+22 := L.lengthDest; omega
+ have htOrd : tag.val < (ordPub 1).val := by
+ have h : (framePub 4).val + (raw.length ⌈/⌉ g.w) ≤ (ordPub 1).val := L.prefixBeforeOrder
+ omega
+ have hm₁ : lengthMemory lenPub raw (writeMemory m tag v) = writeMemory (lengthMemory lenPub raw m) tag v :=
+ packMemory_write_tag lenPub _ m tag v _ htLen
+ have hrp : rawOperands lenPub framePub raw (writeMemory m tag v) = rp := by
+ rw [rawOperands,hm₁,prefixFrame_write_tag framePub _ tag v htFrame hfit]
+ rfl
+ have hm₃ : rawMemory lenPub framePub raw (writeMemory m tag v) =
+ writeMemory (rawMemory lenPub framePub raw m) tag v := by
+ simp only [rawMemory,hrp,hm₁,published_write_tag framePub _ tag v htFrame hw hfit]
+ exact packMemory_write_tag rp raw _ tag v _ (show tag.val < (framePub 4).val by omega)
+ have hm₄ : preparedAdviceMemory lenPub framePub ordPub raw values (writeMemory m tag v) =
+ finalMemory c g lit raw values m := by
+ rw [preparedAdviceMemory,hm₃,packMemory_write_tag ordPub _ _ tag v _ htOrd]
+ rfl
+ exact hm₄ ▸ prepared_image L values (writeMemory m tag v)
+
+/-- These four stages give an equivalence on all accepting choice tapes for any
+report cap on the continuation, including caps on the concatenated group. -/
+theorem fourStages_paths {c p O g lit m raw values cap}
+ (h : Returning (machine c p O g lit).program cap (calls c g raw m) 22 m
+ (finalMemory c g lit raw values m)) (within : List (BurstRAM.Report g.w) → Prop) :
+ ∃ logs, Nonempty (PathsFrom (machine c p O g lit).program cap (some 0)
+ (finalMemory c g lit raw values m) (fun rs => within (logs++rs)) ≃
+ PathsFrom (machine c p O g lit).program cap (some 0) m within) ∧
+ logs.length = calls c g raw m ∧ ∀ r ∈ logs, r.probes ≤ 22 ∧ r.events.length < cap := by
+ obtain ⟨logs,hx,he,hm,hl,hb⟩ := h
+ have hpath := emptySegmentEquiv hx within
+ rw [he,hm] at hpath
+ exact ⟨logs,⟨hpath⟩,hl,hb⟩
+
+/-- The canonical call counts use the actual raw prefix length and the table's
+encoded ordinal width, including the empty-bank return when there are no rows. -/
+theorem callCounts (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g))) :
+ stageCalls (lp c g) = g.w+1 ∧
+ stageCalls (rawOperands (lp c g) (fp c g) raw m) = LiveEvaluatorAdviceResources.prefixCalls raw.length g.w ∧
+ stageCalls (op c g) = LiveEvaluatorAdviceResources.orderCalls (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)) := by
+ have hwidth : (rawOperands (lp c g) (fp c g) raw m 2).val = g.w := L.frameWidth
+ simp only [stageCalls,packCalls,LiveEvaluatorAdviceResources.prefixCalls,LiveEvaluatorAdviceResources.orderCalls,
+ L.lengthWidth,L.lengthRows,rawOperands_rows L m,hwidth,L.ordinalRows,L.ordinalWidth,Nat.one_mul]
+ simp
+
+theorem work_eq_setupCost (c : Constants) (g : Geometry) (raw : List Bool) (m : Memory g.w)
+ (L : PreparedLayout (lp c g) (fp c g) (op c g) raw (c.labels.eval g) (Nat.clog 2 (c.labels.eval g))) :
+ work c g raw m = LiveEvaluatorAdviceResources.setupCost g.w raw.length
+ (c.labels.eval g) (Nat.clog 2 (c.labels.eval g)) := by
+ obtain ⟨hl,hr,ho⟩ := callCounts c g raw m L
+ rw [work,hl,hr,ho,LiveEvaluatorAdviceResources.setupCost]
+ omega
+
+end LiveProgram.Advice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramAdviceSplice.lean b/lean/OAI/Computability/VPVNP/LiveProgramAdviceSplice.lean
new file mode 100644
index 0000000000..fcb74600eb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramAdviceSplice.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.LiveProgramAdviceLayout
+import OAI.Computability.VPVNP.LiveEvaluatorAdviceTag
+import OAI.Computability.VPVNP.LiveStageSegments
+
+/-!
+# Returning native stages in the middle-group preparation
+
+Every successful stage in this prefix transfers to another stage with
+persistent cursor zero. Consecutive stage logs concatenate with their
+actual external memory effects. The fixed frame initializer has one such
+call, whose log includes the outer tag read and transfer write.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.Advice
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink
+open LiveEvaluatorAdviceFrames
+
+variable {w : ℕ}
+
+/-- A verified deterministic prefix of a linked machine, including the
+post-call cursor, memory image, and exact number of empty branch streams. -/
+def Returning {C : Type*} (P : BurstRAM.Program w C) (fuel calls probes : ℕ) (m final : Memory w) : Prop :=
+ ∃ logs, runSegment P fuel (some 0) m (List.replicate calls []) = some logs ∧
+ endState (some 0) logs = some 0 ∧ after m (eventLog logs) = final ∧
+ logs.length = calls ∧ ∀ r ∈ logs, r.probes ≤ probes ∧ r.events.length < fuel
+
+/-- The memory seen by each suffix is exactly that returned by its predecessor. -/
+theorem returning_append {C : Type*} {P : BurstRAM.Program w C} {fuel a b qa qb : ℕ} {m u v : Memory w}
+ (ha : Returning P fuel a qa m u) (hb : Returning P fuel b qb u v) :
+ Returning P fuel (a+b) (max qa qb) m v := by
+ obtain ⟨xs,hx,hxe,hxm,hxl,hxr⟩ := ha
+ obtain ⟨ys,hy,hye,hym,hyl,hyr⟩ := hb
+ refine ⟨xs++ys,?_,?_,?_,by simp [hxl,hyl],?_⟩
+ · rw [List.replicate_add, PrimedSchedule.runSegment_append,hx]
+ simp [hxe,hxm,hy]
+ · rw [endState_append,hxe,hye]
+ · simpa only [eventLog, List.flatMap_append, after, List.foldl_append] using
+ (congrArg (fun z => after z (eventLog ys)) hxm).trans hym
+ · intro r hr
+ rcases List.mem_append.mp hr with hr | hr
+ · exact ⟨(hxr r hr).1.trans (le_max_left ..),(hxr r hr).2⟩
+ · exact ⟨(hyr r hr).1.trans (le_max_right ..),(hyr r hr).2⟩
+
+/-- Word address of the outer stage tag used to splice a returning advice stage into the live
+program. -/
+abbrev tagAddr (g : Geometry) (lit : LiteralPrefix) := Pieces.word g lit (.geometry Layout.stageTag)
+
+theorem tag_before_advice (c : Constants) (g : Geometry) (lit : LiteralPrefix)
+ (hlimit : (Layout.shadow c).eval g < 2^g.w) :
+ (tagAddr g lit).val < ((bank g (StageOperands.adviceFrames c)) 0).val := by
+ let base := (HeaderLayout.advice c.lengths Layout.header).eval g
+ have ht : Layout.stageTag.eval g < base := by
+ simp only [base,HeaderLayout.advice,HeaderLayout.rightIndex,HeaderLayout.leftIndex,
+ HeaderLayout.population,HeaderLayout.high,HeaderLayout.index,Layout.header,eval_add,show (1 : PublicExpr).eval g = 1 from rfl]
+ omega
+ have hb : base ≤ (Layout.shadow c).eval g := by
+ simp only [base,Layout.shadow,Layout.orderMap,Layout.packedPrefix,Layout.adviceFrames,
+ Layout.transitionScratch,Layout.newState,Layout.oldState,Layout.counter,Layout.descriptor,
+ HeaderLayout.limit,HeaderLayout.config,HeaderLayout.exponent,HeaderLayout.exterior,eval_add]
+ omega
+ change Layout.stageTag.eval g % (2^g.w) < base % (2^g.w)
+ rwa [Nat.mod_eq_of_lt (ht.trans_le hb |>.trans hlimit),Nat.mod_eq_of_lt (hb.trans_lt hlimit)]
+
+/-- Execute the single frame-initialization call as stage 10 of the actual
+live machine. The next dispatch sees stage 11 and the newly published operands. -/
+theorem returning_frames (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (m : Memory g.w) (cap : ℕ)
+ (fit : 21 ≤ 2^g.w) (hf : 130 ≤ cap)
+ (htag : m (tagAddr g lit).val = tagWord g.w Stage.adviceFrames)
+ (hl : actualLength (bank g (StageOperands.adviceFrames c)) m ≤ (bank g (StageOperands.adviceFrames c)) 1)
+ (hw : 0 < (bank g (StageOperands.adviceFrames c)) 2) :
+ let fp := bank g (StageOperands.adviceFrames c)
+ Returning (machine c p O g lit).program cap 1 22 m
+ (writeMemory (published fp m) (tagAddr g lit) (tagWord g.w Stage.prefixPack)) := by
+ let fp := bank g (StageOperands.adviceFrames c)
+ let rep : Report g.w := ⟨events fp m,none⟩
+ let out := linkedReport (next p) (tagAddr g lit) Stage.adviceFrames rep
+ obtain ⟨he,hm⟩ := execute_frames fp 0 m hl hw
+ have hc : execute (Pieces.component (rows c p O) Stage.adviceFrames g lit) 83
+ ((Pieces.component (rows c p O) Stage.adviceFrames g lit).start 0) m [] = some rep := he
+ have hx : execute (machine c p O g lit).program cap ((machine c p O g lit).program.start 0) m [] = some out :=
+ Pieces.execute_component (rows c p O) (next p) Layout.stageTag g lit Stage.adviceFrames fit
+ (by omega) 0 m htag [] rep hc
+ have hn : next p Stage.adviceFrames = some Stage.prefixPack := rfl
+ have hv : out.result = some 0 := by rw [show out = _ from rfl, linkedReport_result]; rfl
+ have hpost : after m out.events = writeMemory (published fp m) (tagAddr g lit) (tagWord g.w Stage.prefixPack) := by
+ rw [show out = _ from rfl, linkedReport_after, hn]
+ change writeMemory (after m (events fp m)) _ _ = _
+ rw [hm]
+ have hprobes : out.probes ≤ 22 := by
+ rw [show out = _ from rfl, linkedReport_probes, hn]
+ have h := (events_cost fp m).2.1
+ change countProbes (events fp m) + 1 + 1 ≤ 22
+ omega
+ refine ⟨[out],?_,?_,?_,rfl,?_⟩
+ · simp [runSegment, hx]
+ · simpa [endState] using hv
+ · simpa [eventLog] using hpost
+ · intro r hr
+ obtain rfl := List.mem_singleton.mp hr
+ exact ⟨hprobes,(execute_spec hx).1.length_lt⟩
+
+end LiveProgram.Advice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramCaps.lean b/lean/OAI/Computability/VPVNP/LiveProgramCaps.lean
new file mode 100644
index 0000000000..f59f740008
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramCaps.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.LiveProgram
+import OAI.Computability.VPVNP.LiveOutsideBudget
+
+/-!
+# Combining the auxiliary pair charge with the outer live program
+
+The small-o estimate for the compressed pair can be used with constant
+one quarter. Dispatch adds at most two probes per pair call. The rest of
+the group costs at most one physical processor array. These two estimates
+suffice for the total transcript cap, while the two-probe and finite
+instruction margins account for every individual dispatch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+open BurstRAM LiveStageLink
+
+variable {w d : ℕ}
+
+theorem linked_cost_le_three (next : Fin d → Option (Fin d)) (addr : Word w) (s : Fin d)
+ (rs : List (Report w)) :
+ RAMBuckets.cost Report.probes (rs.map (linkedReport next addr s)) ≤ 3*RAMBuckets.cost Report.probes rs := by
+ induction rs with
+ | nil => simp [RAMBuckets.cost]
+ | cons r rs ih =>
+ simp only [List.map_cons, RAMBuckets.cost, linkedReport_probes]
+ split <;> omega
+
+/-- The physically charged prefix, linked pair, and suffix all satisfy the
+same `withinCaps` condition used by the parsimonious transcript theorem. -/
+theorem withinCaps_pair_group {S H : ℕ} (hH : 4 ≤ H)
+ (next : Fin d → Option (Fin d)) (addr : Word w) (s : Fin d) (pre pair post : List (Report w))
+ (outside : RAMBuckets.cost Report.probes pre + RAMBuckets.cost Report.probes post ≤ S)
+ (oneQuarter : 4*RAMBuckets.cost Report.probes pair ≤ S*H)
+ (eachOutside : ∀ r ∈ pre ++ post, 1+r.probes ≤ H)
+ (eachPair : ∀ r ∈ pair, 3+r.probes ≤ H) :
+ withinCaps S H (pre ++ pair.map (linkedReport next addr s) ++ post) := by
+ constructor
+ · rw [RAMBuckets.cost_append, RAMBuckets.cost_append]
+ have h := linked_cost_le_three next addr s pair
+ have hS : 4*S ≤ S*H := by simpa [Nat.mul_comm] using Nat.mul_le_mul_left S hH
+ omega
+ · intro r hr
+ rcases List.mem_append.mp hr with h | h
+ · rcases List.mem_append.mp h with h | h
+ · exact eachOutside r (List.mem_append_left _ h)
+ · obtain ⟨a,ha,rfl⟩ := List.mem_map.mp h
+ rw [linkedReport_probes]
+ have := eachPair a ha
+ split <;> omega
+ · exact eachOutside r (List.mem_append_right _ h)
+
+/-- For the fixed outer table, a pair trace with a finite additive clock
+margin executes within the live `n^10000` private-work budget. -/
+theorem linked_pair_clock (next : Stage → Option Stage) (addr : Word w) (s : Stage)
+ (r : Report w) {n : ℕ} (margin : r.events.length + 48 ≤ n^10000) :
+ (linkedReport next addr s r).events.length + 1 ≤ n^10000 := by
+ have h := linkedReport_length_le next addr s r
+ change (linkedReport next addr s r).events.length ≤ r.events.length+2*21+5 at h
+ omega
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramCompressedPair.lean b/lean/OAI/Computability/VPVNP/LiveProgramCompressedPair.lean
new file mode 100644
index 0000000000..e6f5942484
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramCompressedPair.lean
@@ -0,0 +1,193 @@
+import OAI.Computability.VPVNP.LiveProgram
+import OAI.Computability.VPVNP.LivePairStageTag
+import OAI.Computability.VPVNP.CompressorRecordsOnlineWorkspace
+import OAI.Computability.VPVNP.CompressorDescriptorCursorFrame
+import OAI.Computability.VPVNP.CompressorHistoryArenaBase
+
+/-!
+# The eleven-operand compressed pair instruction table
+
+The group enters at cursor zero with the histogram and auxiliary shadow already
+prepared. The pair computes the online calendar size from `n`, publishes the
+cursor geometry, derives and saves its actual level stride, and arms the online
+calendar. The online program then invokes its planners and workers. On its
+accepting exit the final field and vertex evaluator starts at cursor zero.
+An accepting exit there returns to the live exponent checker.
+
+The catalog, calendar recipes and final evaluator are finite instruction
+tables selected before the input length. All mutable tags, pointers, widths
+and entries are recovered or computed at runtime from the actual pair ABI.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.Schedule
+open scoped Fin.CommRing
+
+/-- Index of one of the ten components in the compressed pair, ordered from calendar
+initialization through online compression to terminal evaluation. -/
+abbrev Stage := Fin 10
+
+namespace Stage
+/-- First stage, which computes the online calendar’s row count from the live input length and
+fixed block-count ratio. -/
+abbrev calendarRows : Stage := 0
+/-- Bootstrap stage that prepares the cursor-parameter inputs in the workspace frame. -/
+abbrev cursorFrame : Stage := 1
+/-- Load the prepared frame and publish the computed cursor parameters in level zero. -/
+abbrev cursorGeometry : Stage := 2
+/-- Copy the saved cursor parameters back to the active workspace frame for the stride
+calculation. -/
+abbrev copyGeometry : Stage := 3
+/-- Compute and save the runtime address stride between successive descriptor levels. -/
+abbrev stride : Stage := 4
+/-- Install the history arena base at the end of the descriptor allocation, together with the
+level count and input length. -/
+abbrev arenaBase : Stage := 5
+/-- Install the scheduler’s six workspace pointers and reset its tag and ordinal. -/
+abbrev pointers : Stage := 6
+/-- Set the inner scheduler tag to the calendar entry before online compression begins. -/
+abbrev calendarStart : Stage := 7
+/-- Run the online calendar, planners, and workers that construct the compressed descriptor
+history. -/
+abbrev online : Stage := 8
+/-- Run the final field and vertex evaluator on the compressed history. -/
+abbrev terminal : Stage := 9
+end Stage
+
+/-- Fixed geometric parameters used by the native descriptor bootstrap.
+The ratio is the numerator and denominator of the block-count exponent. -/
+structure Bootstrap where
+ /-- Fixed dimensions of the descriptor directory, level headers, incidence columns, and slot
+ tables. -/
+ shape : DescriptorSpace.Shape
+ /-- Initial degree exponent used to set up the descriptor cursor parameters. -/
+ degreeBits : ℕ
+ /-- Number of lane bits per compression block supplied to the initial cursor calculation. -/
+ lanesPerBlock : ℕ
+ /-- Fixed step count of the block schedule used to compute the descriptor allocation and
+ traversal limits. -/
+ steps : ℕ
+ /-- Numerator of the block-count exponent used by the calendar’s row-count calculation. -/
+ numerator : ℕ
+ /-- Denominator of the block-count exponent used by the calendar’s row-count calculation. -/
+ denominator : ℕ
+
+private def pack {p r : ℕ} (T : Template p r 11) : PairTable := ⟨p,r,T⟩
+
+variable {d initial phases : ℕ} {C : Catalog d} (b : Bootstrap) (plan : Online.Config C initial phases)
+variable (finalTable : PairTable)
+
+/-- Ten native pair tables in execution order, comprising eight bootstrap stages, the online
+scheduler, and the supplied terminal evaluator. -/
+def stages : Stage → PairTable :=
+ ![pack (CalendarRows.table (OnlineWorkspace.rowsSpec initial phases b.numerator b.denominator)),
+ pack (LiveOneShot.oneShot (DescriptorParameters.table b.shape b.degreeBits initial phases b.lanesPerBlock)),
+ pack (LiveOneShot.oneShot DescriptorParameters.loader),
+ pack (LiveOneShot.oneShot (DescriptorParameters.copyTable b.shape)),
+ pack (OnlineWorkspace.strideTable b.shape),
+ pack (LiveOneShot.oneShot (HistoryArenaBase.table b.shape initial phases b.steps)),
+ pack (Workspace.initTable (arity C)),
+ pack (Workspace.calendarStart d),
+ pack (OnlineWorkspace.table plan),
+ finalTable]
+
+/-- Successor of a completed pair stage in execution order, with no successor after terminal
+evaluation. -/
+def next (s : Stage) : Option Stage :=
+ if h : s.val+1 < 10 then some ⟨s.val+1,h⟩ else none
+
+/-- Maximum register count among the ten native pair tables, used as their common register-bank
+size. -/
+def regs := Finset.univ.sup fun i => (stages b plan finalTable i).regs
+
+private def includeRegister (R : Stage → ℕ) (i : Stage) : Fin (R i) ↪ Fin (Finset.univ.sup R) :=
+ ⟨fun x => x.castLE (Finset.le_sup (Finset.mem_univ i)), fun _ _ e =>
+ Fin.ext (congrArg (fun j : Fin (Finset.univ.sup R) => j.val) e)⟩
+
+/-- Include a component’s registers into the common pair register bank at the same register
+indices. -/
+def embedding (i : Stage) : Fin (stages b plan finalTable i).regs ↪ Fin (regs b plan finalTable) :=
+ includeRegister (fun j => (stages b plan finalTable j).regs) i
+
+/-- Widen the selected native pair template to the common register bank while retaining its
+eleven public operand indices. -/
+def components (i : Stage) : Template (stages b plan finalTable i).pcs (regs b plan finalTable) 11 :=
+ LiveStageLink.widen (stages b plan finalTable i).table (embedding b plan finalTable i) id
+
+/-- Single fixed native body, with the same eleven public words as the pair
+row in the outer live program. -/
+def pairTable : PairTable :=
+ pack (PairTag.compile (LiveStageLink.linked (components b plan finalTable) next))
+
+variable {w : ℕ} (pub : Fin 11 → Word w)
+
+/-- Burst RAM program obtained by instantiating the linked compressed-pair table with the
+supplied word width and eleven public words. -/
+abbrev program := ((pairTable b plan finalTable).table.instantiate w pub).program
+/-- Burst RAM program of the selected native component before register widening and stage
+linking. -/
+abbrev original (i : Stage) := ((stages b plan finalTable i).table.instantiate w pub).program
+
+/-- Wrap a native component report with five ticks to calculate the pair tag address, the tag
+dispatch, and any transfer to the next component. -/
+def report (i : Stage) (rep : Report w) := LiveStageLink.prependLog (List.replicate 5 .tick)
+ (LiveStageLink.linkedReport next (PairTag.address pub) i rep)
+
+/-- The outer pair linker uses the otherwise unused tail-state word. The
+physical auxiliary shadow, and even its final site, are independent of this tag. -/
+theorem tag_address (c : Constants) (g : Geometry) (lit : LiteralPrefix) :
+ PairTag.address (Pieces.word g lit ∘ StageOperands.pair c) = Pieces.word g lit (.geometry (Layout.oldState c)) := by
+ change ((Fin.ofNat (2^g.w) ((Layout.counter c).eval g) : Word g.w) +
+ Fin.ofNat (2^g.w) (c.grammarLabels.eval g)) + Fin.ofNat (2^g.w) c.motifLabels =
+ Fin.ofNat (2^g.w) (((Layout.counter c).eval g) + (c.grammarLabels.eval g+c.motifLabels))
+ change (((Layout.counter c).eval g : ℕ) : Word g.w) + ((c.grammarLabels.eval g : ℕ) : Word g.w) + (c.motifLabels : Word g.w) =
+ (((Layout.counter c).eval g + (c.grammarLabels.eval g + c.motifLabels) : ℕ) : Word g.w)
+ simp [add_assoc]
+
+/-- Five ticks to compute the tag address, followed by the native stage
+scan, source execution and, when applicable, a single tag transfer write. -/
+theorem execute_stage (i : Stage) (fit : 10 ≤ 2^w) (f cap : ℕ) (room : f+30 ≤ cap)
+ (st : Word w) (m : Memory w) (tag : m (PairTag.address pub).val = LiveStageLink.tagWord w i)
+ (bs : List Bool) (rep : Report w) (source : execute (original b plan finalTable pub i) f
+ ((original b plan finalTable pub i).start st) m bs = some rep) :
+ execute (program b plan finalTable pub) cap ((program b plan finalTable pub).start st) m bs = some (report pub i rep) := by
+ let T := components b plan finalTable
+ let L := LiveStageLink.linked T next
+ have comp : execute ((T i).instantiate w pub).program f (((T i).instantiate w pub).program.start st) m bs = some rep :=
+ (LiveStageLink.execute_widen_start (stages b plan finalTable i).table (embedding b plan finalTable i) id pub f st m bs).trans source
+ have run := LiveStageLink.execute_linked_of_stage T next pub (PairTag.address pub) i fit (by omega : f+2*10+5 ≤ cap-5) st m tag bs rep comp
+ have outer := PairTag.execute_start L pub (cap-5) st m bs
+ change execute (program b plan finalTable pub) (cap-5+5) ((program b plan finalTable pub).start st) m bs =
+ (execute (LiveStageLink.machine T next pub (PairTag.address pub)).program (cap-5)
+ ((LiveStageLink.machine T next pub (PairTag.address pub)).program.start st) m bs).map _ at outer
+ rw [show cap-5+5 = cap by omega,run] at outer
+ exact outer
+
+/-- Accounting of every deterministic pair-level link action. -/
+theorem report_effect (i : Stage) (rep : Report w) (m : Memory w) :
+ choiceBits (report pub i rep).events = choiceBits rep.events ∧
+ (report pub i rep).probes = rep.probes + 1 + (if rep.result = none ∧ (next i).isSome then 1 else 0) ∧
+ (report pub i rep).events.length ≤ rep.events.length + 30 ∧
+ after m (report pub i rep).events = match rep.result, next i with
+ | none, some j => writeMemory (after m rep.events) (PairTag.address pub) (LiveStageLink.tagWord w j)
+ | _, _ => after m rep.events := by
+ have a := LiveStageLink.linkedReport_choiceBits next (PairTag.address pub) i rep
+ have b := LiveStageLink.linkedReport_probes next (PairTag.address pub) i rep
+ have l := LiveStageLink.linkedReport_length_le next (PairTag.address pub) i rep
+ have e := LiveStageLink.linkedReport_after next (PairTag.address pub) i rep m
+ refine ⟨a,b,?_,?_⟩
+ · simp only [report,LiveStageLink.prependLog,List.length_append,List.length_replicate]
+ omega
+ · change after m (List.replicate 5 .tick ++ _) = _
+ rw [after,List.foldl_append,show (List.replicate 5 .tick).foldl update m = m by rfl]
+ cases hs : rep.result <;> cases hn : next i <;> simpa only [hs,hn,after] using e
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramCompressedPairPaths.lean b/lean/OAI/Computability/VPVNP/LiveProgramCompressedPairPaths.lean
new file mode 100644
index 0000000000..70ca0723f1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramCompressedPairPaths.lean
@@ -0,0 +1,161 @@
+import OAI.Computability.VPVNP.LiveNativePairContinuation
+import OAI.Computability.VPVNP.LiveProgramCaps
+import OAI.Computability.VPVNP.LiveDeterministicReachable
+import OAI.Computability.VPVNP.PairSimulationSelectorReindex
+
+/-!
+# Relocating the compressed pair's complete native paths into the live table
+
+The pair instruction table runs on eleven public words. Relocation preserves
+every supplied tape, report and memory write. A common prefix and the
+branch-dependent terminal calls thus enter the outer linker on their original
+chronological list. Only the dispatch and successor-tag events are appended
+when charging the outer reports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.CompressedPaths
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink LiveExponent PairSimulation.LocalHistory
+
+variable (G : Group)
+
+/-- Eleven words supplied to the pair stage, obtained by selecting its operands from the live
+group’s geometry and literal prefix. -/
+abbrev publicWords := Pieces.word G.g G.lit ∘ StageOperands.pair G.constants
+/-- Unrelocated burst RAM program of the group’s pair table instantiated at the group word
+width and pair operands. -/
+abbrev native := (G.pair.table.instantiate G.w (publicWords G)).program
+/-- Per-call instruction allowance assigned to the pair stage by the live group’s clock. -/
+abbrev fuel := G.clockAt Stage.pair
+/-- Lists of call tapes that take the native pair from cursor zero and the specified memory to
+an accepting halt within the per-call fuel. -/
+abbrev Raw (m : Memory G.w) := ActualPaths (native G) (fuel G) 0 m (fun _ => True)
+
+variable {G} {m : Memory G.w}
+/-- Chronological reports returned by running the call tapes of an accepting native pair path. -/
+noncomputable def reports (p : Raw G m) : List (Report G.w) := p.property.choose
+
+theorem rawRun (p : Raw G m) :
+ runSegment (native G) (fuel G) (some 0) m p.val = some (reports p) := p.property.choose_spec.1
+
+/-- The memory and state of any actual continuing prefix, including one
+which may later reject. -/
+inductive Reachable (G : Group) (initial : Memory G.w) : Word G.w → Memory G.w → Prop
+ | start : Reachable G initial 0 initial
+ | more {st mem bits r st'} : Reachable G initial st mem →
+ execute (native G) (fuel G) ((native G).start st) mem bits = some r → r.result = some st' →
+ Reachable G initial st' (after mem r.events)
+
+/-- Every continuing call in this physical component preserves the outer
+tag, even when the supplied tape has no accepting extension. -/
+def PreservesTag (G : Group) (initial : Memory G.w) : Prop :=
+ ∀ {st mem bits r st'}, Reachable G initial st mem →
+ execute (native G) (fuel G) ((native G).start st) mem bits = some r → r.result = some st' →
+ after mem r.events G.addr.val = mem G.addr.val
+
+/-- The generic address-preservation proof on the original native table
+supplies the tag invariant required after relocation. -/
+theorem preservesTag_of_protectsAddress (G : Group) (m : Memory G.w)
+ (h : ProtectsAddress (native G) (fuel G) 0 m G.addr.val) : PreservesTag G m := by
+ have embed {s u} (reached : Reachable G m s u) : Reached (native G) (fuel G) 0 m s u := by
+ induction reached with
+ | start => exact .start
+ | more _ call cont ih => exact .more ih call cont
+ intro st mem bits r st' reached call result
+ exact h (embed reached) call result
+
+private theorem relocated {st : Option (Word G.w)} {mem : Memory G.w} {bs : List (List Bool)} :
+ runSegment (sourceProgram G.T G.pub Stage.pair) (fuel G) st mem bs =
+ runSegment (native G) (fuel G) st mem bs :=
+ component_segment G Stage.pair (fuel G) st mem bs
+
+private theorem frame (preserves : PreservesTag G m) :
+ TagFrame G.T G.pub G.addr Stage.pair (fuel G) (Reachable G m) := by
+ intro st mem bits r st' reached tag run cont
+ have localRun : execute (native G) (fuel G) ((native G).start st) mem bits = some r :=
+ (Pieces.component_eq G.components G.g G.lit Stage.pair (fuel G) st mem bits).symm.trans run
+ exact ⟨reached.more localRun cont,(preserves reached localRun cont).trans tag⟩
+
+/-- Room for the final transfer follows from a private-instruction bound on
+the actual, unrelocated pair reports. All earlier pair calls return directly. -/
+theorem room_of_work {r : Report G.w} (hr : r.events.length + 4 ≤ fuel G) :
+ room G.nextStage G.addr Stage.pair (fuel G) r := by
+ unfold room exitReport
+ have nextPair : G.nextStage Stage.pair = some Stage.exponents := rfl
+ rw [nextPair]
+ cases r.result <;> simp only [transferEvents,List.length_append,List.length_cons,List.length_nil] <;> omega
+
+/-- Equality on the entire tape list gives a bijection between the original
+pair completion and its ordinary stage in the outer table. -/
+noncomputable def ordinary (fits : ∀ p : Raw G m, ∀ r ∈ reports p, room G.nextStage G.addr Stage.pair (fuel G) r) :
+ Raw G m ≃ G.StagePaths Stage.pair m where
+ toFun p := ⟨p.val,reports p,relocated.trans (rawRun p),p.property.choose_spec.2.1,fits p⟩
+ invFun p := ⟨p.val,ordinaryReports p,relocated.symm.trans (ordinaryRun p),p.property.choose_spec.2.1,trivial⟩
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+/-- Classify the physical stage by the range of the descriptor/arc/DFS tape
+emission and its decoding equivalence to the *same* monomial witness. -/
+noncomputable def indexed {X : Type} {enc : TraceEncoding X} (R : SelectorReindex enc)
+ (paths : Set.range R.emit ≃ Raw G m) (tag : G.tagged Stage.pair m) (preserves : PreservesTag G m)
+ (fits : ∀ p : Raw G m, ∀ r ∈ reports p, room G.nextStage G.addr Stage.pair (fuel G) r) :
+ Indexed G Stage.pair m X :=
+ ⟨⟨Reachable G m,frame preserves,.start,tag⟩,R.decode.symm.trans (paths.trans (ordinary fits))⟩
+
+variable {X : Type} {enc : TraceEncoding X} (R : SelectorReindex enc) (paths : Set.range R.emit ≃ Raw G m)
+ (tag : G.tagged Stage.pair m) (preserves : PreservesTag G m)
+ (fits : ∀ p : Raw G m, ∀ r ∈ reports p, room G.nextStage G.addr Stage.pair (fuel G) r)
+
+/-- The chronological descriptor prefix, arc bits and independent site
+tapes all survive relocation. -/
+theorem indexed_tapes (p : Set.range R.emit) :
+ ((indexed R paths tag preserves fits).traces (R.decode p)).val = (paths p).val := by
+ simp only [indexed,Equiv.trans_apply,Equiv.symm_apply_apply,ordinary,Equiv.coe_fn_mk]
+
+theorem indexed_reports (p : Set.range R.emit) :
+ ordinaryReports ((indexed R paths tag preserves fits).traces (R.decode p)) = reports (paths p) := by
+ apply Option.some.inj
+ have h := ordinaryRun ((indexed R paths tag preserves fits).traces (R.decode p))
+ rw [relocated,indexed_tapes] at h
+ exact h.symm.trans (rawRun _)
+
+theorem indexed_memory (p : Set.range R.emit) :
+ (indexed R paths tag preserves fits).memory (R.decode p) =
+ transferMemory G.addr (some Stage.exponents) (after m (eventLog (reports (paths p)))) := by
+ rw [Indexed.memory,indexed_reports]
+ rfl
+
+theorem indexed_logs (p : Set.range R.emit) :
+ (indexed R paths tag preserves fits).logs (R.decode p) =
+ (reports (paths p)).map (linkedReport G.nextStage G.addr Stage.pair) := by
+ rw [Indexed.logs,indexed_reports]
+
+/-- Charge the outer dispatch and control transfer to the slack left by the
+native pair simulator. The resulting reports fit the exact pair allowance
+in the first-half chronology. -/
+theorem indexed_budget (p : Set.range R.emit) (S H : ℕ) (hH : 4 ≤ H)
+ (total : 4*RAMBuckets.cost Report.probes (reports (paths p)) ≤ S*H)
+ (each : ∀ r ∈ reports (paths p), 3+r.probes ≤ H) :
+ let rs := (indexed R paths tag preserves fits).logs (R.decode p)
+ RAMBuckets.cost Report.probes rs ≤ S*(H-1) ∧ ∀ r ∈ rs, 1+r.probes ≤ H := by
+ rw [indexed_logs]
+ constructor
+ · have a := linked_cost_le_three G.nextStage G.addr Stage.pair (reports (paths p))
+ have b : 4*S ≤ S*H := by simpa only [Nat.mul_comm 4 S] using Nat.mul_le_mul_left S hH
+ have eq : S*(H-1)+S=S*H := by rw [← Nat.mul_succ,show (H-1).succ=H by omega]
+ omega
+ · intro r hr
+ obtain ⟨src,hs,rfl⟩ := List.mem_map.mp hr
+ rw [linkedReport_probes]
+ have h := each src hs
+ split <;> omega
+
+end LiveProgram.PairStages.Group.CompressedPaths
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramHandoffs.lean b/lean/OAI/Computability/VPVNP/LiveProgramHandoffs.lean
new file mode 100644
index 0000000000..851d9e0567
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramHandoffs.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.LiveProgramRouting
+import OAI.Computability.VPVNP.LiveHeaderUnique
+
+/-!
+# Exact transfers of the outer live router
+
+At a jump, the continuation runs with cursor zero in the newly tagged
+memory. An accepting router contributes exactly one path if its own report
+fits the cap. These statements apply at a common group clock and keep every
+report from the deterministic dispatch and flag test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+namespace Router
+
+variable (r : Router) (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+variable (g : Geometry) (lit : LiteralPrefix)
+
+private theorem dispatch_le (addr : Word g.w) :
+ (LiveStageLink.dispatchEvents addr r.stage).length ≤ 44 := by
+ simp [LiveStageLink.dispatchEvents]; have := r.stage.isLt; omega
+
+/-- Router report for a selected jump. It reads the flag, tests the indicated branch, writes
+the destination tag, and returns cursor zero. -/
+def jumpReport (i : Fin 3) (flag : Word g.w) (dest : Stage) : Report g.w :=
+ let pub := r.data g lit
+ ⟨[.tick,.read (pub 0) flag] ++ List.replicate (2*(i.val+1)) .tick ++
+ [.tick,.tick,.write (pub 1) (LiveStageLink.tagWord g.w dest),.tick],some 0⟩
+
+/-- Accepting router report consisting of the flag read and the tests through the selected
+branch. -/
+def haltReport (i : Fin 3) (flag : Word g.w) : Report g.w :=
+ ⟨[.tick,.read ((r.data g lit) 0) flag] ++ List.replicate (2*(i.val+1)) .tick,none⟩
+
+private theorem selected_jump (i : Fin 3) (dest : Stage) (flag : Word g.w)
+ (h : r.target i = .jump (dest.castLE (by decide))) :
+ Route.report (r.data g lit) flag i (r.target i) [] = some (r.jumpReport g lit i flag dest) := by rw [h]; rfl
+
+private theorem selected_halt (i : Fin 3) (flag : Word g.w) (h : r.target i = .accept) :
+ Route.report (r.data g lit) flag i (r.target i) [] = some (r.haltReport g lit i flag) := by rw [h]; rfl
+
+/-- Wrap the router’s own report with the live stage linker’s dispatch and exit events at the
+outer stage-tag address. -/
+def outerReport (src : Report g.w) := LiveStageLink.linkedReport (next p)
+ (Pieces.word g lit (.geometry Layout.stageTag)) r.stage src
+
+/-- A jump costs one tag read in the linker and a read and write in the router. -/
+theorem outer_jump_probes (i : Fin 3) (flag : Word g.w) (dest : Stage) :
+ (r.outerReport p g lit (r.jumpReport g lit i flag dest)).probes = 3 := by
+ rw [outerReport,LiveStageLink.linkedReport_probes]
+ fin_cases i <;> rfl
+
+/-- A terminal route reads the two tags and writes no word. -/
+theorem outer_halt_probes (i : Fin 3) (flag : Word g.w) :
+ (r.outerReport p g lit (r.haltReport g lit i flag)).probes = 2 := by
+ cases r <;> fin_cases i <;> rfl
+
+theorem outer_jump_clock (i : Fin 3) (flag : Word g.w) (dest : Stage) :
+ (r.outerReport p g lit (r.jumpReport g lit i flag dest)).events.length < 57 := by
+ cases r <;> fin_cases i <;> simp [outerReport,LiveStageLink.linkedReport,LiveStageLink.prependLog,LiveStageLink.dispatchEvents,
+ LiveStageLink.exitReport,jumpReport,stage]
+
+theorem after_jump (m : Memory g.w) (i : Fin 3) (flag : Word g.w) (dest : Stage) :
+ after m (r.outerReport p g lit (r.jumpReport g lit i flag dest)).events =
+ writeMemory m (Pieces.word g lit (.geometry Layout.stageTag)) (LiveStageLink.tagWord g.w dest) := by
+ rw [outerReport, LiveStageLink.linkedReport_after]
+ cases r <;> fin_cases i <;> rfl
+
+private theorem result_jump (i : Fin 3) (flag : Word g.w) (dest : Stage) :
+ (r.outerReport p g lit (r.jumpReport g lit i flag dest)).result = some 0 := rfl
+
+/-- The actual choice-free jump at the group's common clock. -/
+theorem jump_call (fit : 21 ≤ 2^g.w) (hw : 2 ≤ g.w) (clock : ℕ) (hclock : 57 ≤ clock)
+ (st : Word g.w) (m : Memory g.w) (i : Fin 3)
+ (hf : m ((r.data g lit) 0).val = (i.val : Word g.w))
+ (ht : m (Pieces.word g lit (.geometry Layout.stageTag)).val = LiveStageLink.tagWord g.w r.stage)
+ (dest : Stage) (h : r.target i = .jump (dest.castLE (by decide))) :
+ let P := (machine c p O g lit).program
+ BurstRAM.execute P clock (P.start st) m [] = some (r.outerReport p g lit (r.jumpReport g lit i (m ((r.data g lit) 0).val) dest)) := by
+ let addr := Pieces.word g lit (.geometry Layout.stageTag)
+ let f := clock-(13+(LiveStageLink.dispatchEvents addr r.stage).length)
+ have hc : f+13+(LiveStageLink.dispatchEvents addr r.stage).length = clock := by
+ have := dispatch_le r g addr; dsimp [f]; omega
+ have he := r.execute c p O g lit hw fit st m i hf addr rfl ht [] f
+ rw [hc,selected_jump r g lit i dest _ h] at he
+ exact he
+
+/-- Exact all-path transfer after a successful first-tail, last-tail, or pair
+selection. The tag write is the only change in external memory. -/
+noncomputable def jumpEquiv (fit : 21 ≤ 2^g.w) (hw : 2 ≤ g.w) (cap : List (Report g.w) → Prop)
+ (clock : ℕ) (hclock : 57 ≤ clock) (st : Word g.w) (m : Memory g.w)
+ (i : Fin 3) (hf : m ((r.data g lit) 0).val = (i.val : Word g.w))
+ (ht : m (Pieces.word g lit (.geometry Layout.stageTag)).val = LiveStageLink.tagWord g.w r.stage)
+ (dest : Stage) (h : r.target i = .jump (dest.castLE (by decide))) :
+ let P := (machine c p O g lit).program
+ let addr := Pieces.word g lit (.geometry Layout.stageTag)
+ let rep := r.outerReport p g lit (r.jumpReport g lit i (m ((r.data g lit) 0).val) dest)
+ ActualPaths P clock 0 (writeMemory m addr (LiveStageLink.tagWord g.w dest)) (fun rs => cap (rep::rs)) ≃
+ ActualPaths P clock st m cap := by
+ let addr := Pieces.word g lit (.geometry Layout.stageTag)
+ let f := clock - (13+(LiveStageLink.dispatchEvents addr r.stage).length)
+ have hc : f+13+(LiveStageLink.dispatchEvents addr r.stage).length = clock := by
+ have := dispatch_le r g addr; dsimp [f]; omega
+ have hsel := r.selected_jump g lit i dest (m ((r.data g lit) 0).val) h
+ have e := r.pathEquiv c p O g lit hw fit st m i hf ht f _ hsel cap
+ let clock' := f+13+(LiveStageLink.dispatchEvents addr r.stage).length
+ change Continuations (machine c p O g lit).program clock' m (r.outerReport p g lit _) cap ≃
+ ActualPaths (machine c p O g lit).program clock' st m cap at e
+ have htClock : clock' = clock := hc
+ rw [htClock] at e
+ unfold Continuations at e
+ rw [result_jump, after_jump r p g lit m i _ dest] at e
+ exact e
+
+/-- A checked unit-mode flag finishes the group at the router, with exactly
+one possible choice stream consisting of a single empty call. -/
+theorem unit_accept_iff (fit : 21 ≤ 2^g.w) (hw : 2 ≤ g.w) (cap : List (Report g.w) → Prop)
+ (clock : ℕ) (hclock : 57 ≤ clock) (st : Word g.w) (m : Memory g.w)
+ (hf : m ((Router.mode.data g lit) 0).val = 0)
+ (ht : m (Pieces.word g lit (.geometry Layout.stageTag)).val = LiveStageLink.tagWord g.w Stage.mode)
+ (bs : List (List Bool)) :
+ let P := (machine c p O g lit).program
+ let rep := Router.mode.outerReport p g lit (Router.mode.haltReport g lit 0 0)
+ (∃ rs, runSegment P clock (some st) m bs = some rs ∧ endState (some st) rs = none ∧ cap rs) ↔
+ bs = [[]] ∧ cap [rep] := by
+ let P := (machine c p O g lit).program
+ let rep := Router.mode.outerReport p g lit (Router.mode.haltReport g lit 0 0)
+ let addr := Pieces.word g lit (.geometry Layout.stageTag)
+ let f := clock-(13+(LiveStageLink.dispatchEvents addr Router.mode.stage).length)
+ have hc : f+13+(LiveStageLink.dispatchEvents addr Router.mode.stage).length = clock := by
+ have := dispatch_le Router.mode g addr; dsimp [f]; omega
+ have he := Router.mode.execute c p O g lit hw fit st m 0 (by exact hf) addr rfl ht [] f
+ rw [hc,hf,Router.mode.selected_halt g lit 0 0 rfl] at he
+ change BurstRAM.execute P clock (P.start st) m [] = some rep at he
+ have stop : rep.result = none := rfl
+ have hrun : runSegment P clock (some st) m (List.replicate 1 []) = some [rep] := by simp [List.replicate_succ,runSegment,he]
+ have halt : endState (some st) [rep] = none := stop
+ change (∃ rs, runSegment P clock (some st) m bs = some rs ∧ endState (some st) rs = none ∧ cap rs) ↔ _
+ constructor
+ · rintro ⟨rs,hr,hh,hhc⟩
+ obtain ⟨hx,rfl⟩ := BurstRAM.accepted_empty_unique hrun halt hr hh
+ exact ⟨hx,hhc⟩
+ · rintro ⟨rfl,h⟩; exact ⟨[rep],hrun,halt,h⟩
+
+end Router
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramHeader.lean b/lean/OAI/Computability/VPVNP/LiveProgramHeader.lean
new file mode 100644
index 0000000000..23ee5ae194
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramHeader.lean
@@ -0,0 +1,210 @@
+import OAI.Computability.VPVNP.LiveProgramSchedule
+import OAI.Computability.VPVNP.LiveHeaderProtected
+import OAI.Computability.VPVNP.LiveHeaderOutputFrame
+import OAI.Computability.VPVNP.LiveHeaderModeReject
+import OAI.Computability.VPVNP.LiveHeaderPaddingReject
+import OAI.Computability.VPVNP.LiveDeterministicPaths
+
+/-!
+# Entering and leaving the header stage of the full live program
+
+The physical machine reads the outer tag at the first address beyond its
+processor array. Its header stage reserves the next address for its own
+dispatcher. Every header call protects the outer tag. The accepting call
+updates that tag to the mode router and resets the cursor to zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.Header
+
+open BurstRAM BurstRAM.PrivateRAM LiveHeaderProgram LiveHeaderSchedule LiveHeader ChainAssignments
+
+/-- The concrete live header lengths obtained by evaluating the fixed size expressions at the
+group geometry. -/
+def sizes (c : Constants) (g : Geometry) := c.lengths.eval g
+/-- Base of the header workspace, one word beyond the outer stage tag that follows the
+processor array. -/
+def base (g : Geometry) := 2^g.d+1
+/-- Word address of the outer stage tag checked and updated by the linked header program. -/
+abbrev addr (g : Geometry) (lit : LiteralPrefix) := Pieces.word g lit (.geometry Layout.stageTag)
+private abbrev tables (c : Constants) (p : UniversalMachine.Program) (O : PairTable) := Pieces.table (rows c p O)
+private abbrev words (c : Constants) (p : UniversalMachine.Program) (O : PairTable) (g : Geometry) (lit : LiteralPrefix) :=
+ Pieces.word g lit ∘ Pieces.bank (rows c p O)
+
+private theorem relocated_call (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (fuel : ℕ) (st : Word g.w) (m : Memory g.w) (bits : List Bool) :
+ let T := ((tables c p O Stage.header).instantiate g.w (words c p O g lit)).program
+ let P := (LiveHeaderProgram.program.instantiate g.w (LiveHeaderProgram.publicData g.w (sizes c g) (base g))).program
+ execute T fuel (T.start st) m bits = execute P fuel (P.start st) m bits := by
+ dsimp only
+ rw [Pieces.component_eq]
+ let ops := fun j => Fin.ofNat (2^g.w) ((HeaderLayout.operands c.lengths Layout.header j).eval g)
+ have h : ops = LiveHeaderProgram.publicData g.w (sizes c g) (base g) := funext (HeaderLayout.operands_eq g c.lengths Layout.header)
+ change execute (LiveHeaderProgram.program.instantiate g.w ops).program fuel ((LiveHeaderProgram.program.instantiate g.w ops).program.start st) m bits = _
+ rw [h]
+
+private theorem segment_eq {w : ℕ} {C D : Type*} (T : BurstRAM.Program w C) (P : BurstRAM.Program w D)
+ (fuel : ℕ) (h : ∀ st mem b, execute T fuel (T.start st) mem b = execute P fuel (P.start st) mem b)
+ (st : Option (Word w)) (m : Memory w) (bs : List (List Bool)) :
+ runSegment T fuel st m bs = runSegment P fuel st m bs := by
+ induction bs generalizing st m with
+ | nil => rfl
+ | cons b bs ih =>
+ cases st with
+ | none => rfl
+ | some st =>
+ simp only [runSegment,h]
+ cases execute P fuel (P.start st) m b <;> simp only [ih]
+
+private theorem relocated_segment (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (fuel : ℕ) (st : Option (Word g.w)) (m : Memory g.w) (bs : List (List Bool)) :
+ let T := ((tables c p O Stage.header).instantiate g.w (words c p O g lit)).program
+ let P := (LiveHeaderProgram.program.instantiate g.w (LiveHeaderProgram.publicData g.w (sizes c g) (base g))).program
+ runSegment T fuel st m bs = runSegment P fuel st m bs :=
+ segment_eq _ _ fuel (relocated_call c p O g lit fuel) st m bs
+
+theorem addr_value (g : Geometry) (lit : LiteralPrefix) (c : Constants) (hfit : limit (sizes c g) (base g) ≤ 2^g.w) :
+ (addr g lit).val = 2^g.d := by
+ change 2^g.d % (2^g.w) = _
+ apply Nat.mod_eq_of_lt
+ rw [limit_eq] at hfit
+ unfold base at hfit
+ omega
+
+private theorem outer_program (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) :
+ (LiveProgram.machine c p O g lit).program =
+ (LiveStageLink.machine (tables c p O) (LiveProgram.next p) (words c p O g lit) (addr g lit)).program := by
+ unfold LiveProgram.machine Pieces.machine Pieces.program
+ rw [Pieces.data_eq]
+ rfl
+
+/-- Every continuing source call of the physical header leaves the outer
+stage tag intact, for arbitrary processor and scratch contents. -/
+theorem tagFrame (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (fuel : ℕ) (hw : 4 ≤ g.w) (fit : limit (sizes c g) (base g) ≤ 2^g.w)
+ (ht : stages.length ≤ 2^g.w) :
+ LiveStageLink.TagFrame (tables c p O) (words c p O g lit) (addr g lit) Stage.header fuel (fun _ _ => True) := by
+ intro st m bits rep st' _ htag hc _
+ rw [relocated_call] at hc
+ have ha : (addr g lit).val < base g := by rw [addr_value g lit c fit]; exact Nat.lt_succ_self _
+ exact ⟨trivial,(native_protected (sizes c g) (base g) fit hw ht fuel st m bits rep hc _ ha).trans htag⟩
+
+private theorem segment_frame {w : ℕ} {C : Type*} (P : BurstRAM.Program w C) (fuel : ℕ) (a : Word w)
+ (frame : ∀ st m b r, execute P fuel (P.start st) m b = some r → after m r.events a.val = m a.val)
+ {st : Option (Word w)} {m : Memory w} {bs : List (List Bool)} {rs : List (Report w)}
+ (hr : runSegment P fuel st m bs = some rs) : LiveStageLink.PreservesTagOnReturns a m rs := by
+ induction bs generalizing st m rs with
+ | nil => simp [runSegment] at hr; subst rs; trivial
+ | cons b bs ih =>
+ cases st with
+ | none => simp [runSegment] at hr
+ | some st =>
+ simp only [runSegment] at hr
+ cases hc : execute P fuel (P.start st) m b with
+ | none => simp [hc] at hr
+ | some r =>
+ simp only [hc,Option.map_eq_some_iff] at hr
+ obtain ⟨rest,hrest,rfl⟩ := hr
+ exact ⟨fun _ => frame st m b r hc,ih hrest⟩
+
+set_option maxHeartbeats 1500000 in
+/-- The actual linked live program reaches its mode router on exactly the
+deterministic header choices. The transferred memory still has the complete
+header output image, and the cost includes both dispatchers. -/
+theorem valid_prefix (c : Constants) (p : UniversalMachine.Program) (O : PairTable) (g : Geometry)
+ (lit : LiteralPrefix) (fuel : ℕ) (hw : 4 ≤ g.w) (advice : CutSchedule.Bits (sizes c g).advice)
+ (cuts : AllCuts (sizes c g).h (sizes c g).delta) (i : Fin (2^((sizes c g).h+1))) (tag : Mode.Tag)
+ (bounds : Fields.Bounds (sizes c g) (base g) g.d g.w) (hi : (sizes c g).h+2 ≤ 2^g.d)
+ (had : (sizes c g).advice ≤ 2^g.d) (ht : stages.length ≤ 2^g.w) (hcap : 154 ≤ fuel)
+ (mode : physicalTag cuts i = some tag) (pad : ∀ side, Fields.ValidPadding (sizes c g) cuts i tag side) :
+ let m := physicalMemory (d := g.d) hw advice cuts i
+ ∃ rs, runSegment (LiveProgram.machine c p O g lit).program fuel (some 0) m (List.replicate (callBound (sizes c g)) []) = some rs ∧
+ endState (some 0) rs = some 0 ∧ Output (sizes c g) (base g) g.d hw advice cuts i tag (after m (eventLog rs)) ∧
+ after m (eventLog rs) (addr g lit).val = LiveStageLink.tagWord g.w Stage.mode ∧
+ rs.length = callBound (sizes c g) ∧ RAMBuckets.cost Report.probes rs ≤ costBound (sizes c g) ∧
+ ∀ r ∈ rs, r.probes ≤ 10 := by
+ let s := sizes c g
+ let m := physicalMemory (d := g.d) hw advice cuts i
+ obtain ⟨raw,hr,he,image,len,budget,probes,_⟩ := valid_native s (base g) 107 hw advice cuts i tag bounds hi had ht le_rfl mode pad
+ have av := addr_value g lit c bounds.fit.le
+ have below : (addr g lit).val < base g := by rw [av]; exact Nat.lt_succ_self _
+ have hz : m (addr g lit).val = LiveStageLink.tagWord g.w Stage.header := by
+ simp [m,physicalMemory,RAMMemory.initialMemory,av,LiveStageLink.tagWord,Stage.header]
+ have hr' := (relocated_segment c p O g lit 107 (some 0) m _).trans hr
+ let T := ((tables c p O Stage.header).instantiate g.w (words c p O g lit)).program
+ have frame := segment_frame T 107 (addr g lit) (fun st mem b r h => native_protected s (base g) bounds.fit.le hw ht
+ 107 st mem b r ((relocated_call c p O g lit 107 st mem b).symm.trans h) _ below) hr'
+ have fit21 : 21 ≤ 2^g.w := (by decide : 21 ≤ stages.length).trans ht
+ obtain ⟨hrun,hstate,hm,hcost⟩ := LiveStageLink.runSegment_accepting (tables c p O) (LiveProgram.next p) (words c p O g lit)
+ (addr g lit) Stage.header fit21 (by omega : 107+2*21+5 ≤ fuel) 0 m _ raw hz frame hr' he
+ let logs := raw.map (LiveStageLink.linkedReport (LiveProgram.next p) (addr g lit) Stage.header)
+ have hn : LiveProgram.next p Stage.header = some Stage.mode := rfl
+ rw [hn] at hm hcost hstate
+ have hmem : after m (eventLog logs) = writeMemory (after m (eventLog raw)) (addr g lit) (LiveStageLink.tagWord g.w Stage.mode) := hm
+ refine ⟨logs, ?_, hstate, ?_, ?_, ?_, ?_, ?_⟩
+ · rw [outer_program]; exact hrun
+ · rw [hmem]; exact image.write_outer _ _ av.ge below
+ · rw [hmem]; simp [writeMemory]
+ · simpa [logs] using len
+ · change RAMBuckets.cost Report.probes logs ≤ costBound s
+ have hx : RAMBuckets.cost Report.probes logs = RAMBuckets.cost Report.probes raw + raw.length + 1 := hcost
+ rw [hx]
+ have hp : 0 < raw.length := by rw [len]; unfold callBound; omega
+ omega
+ · intro r h
+ obtain ⟨u,hu,rfl⟩ := List.mem_map.mp h
+ rw [LiveStageLink.linkedReport_probes]
+ have hp := probes u hu
+ split <;> omega
+
+set_option maxHeartbeats 1000000 in
+/-- Any accepted path of the full live program must first accept the physical
+header checks at its actual remaining source cap. -/
+theorem necessary (c : Constants) (p : UniversalMachine.Program) (O : PairTable) (g : Geometry)
+ (lit : LiteralPrefix) (fuel : ℕ) (hw : 4 ≤ g.w) (advice : CutSchedule.Bits (sizes c g).advice)
+ (cuts : AllCuts (sizes c g).h (sizes c g).delta) (i : Fin (2^((sizes c g).h+1)))
+ (bounds : Fields.Bounds (sizes c g) (base g) g.d g.w) (hi : (sizes c g).h+2 ≤ 2^g.d)
+ (had : (sizes c g).advice ≤ 2^g.d) (ht : stages.length ≤ 2^g.w) (hcap : 154 ≤ fuel)
+ (bs : List (List Bool)) (logs : List (Report g.w))
+ (run : runSegment (LiveProgram.machine c p O g lit).program fuel (some 0)
+ (physicalMemory (d := g.d) hw advice cuts i) bs = some logs)
+ (halt : endState (some 0) logs = none) :
+ ∃ tag, physicalTag cuts i = some tag ∧ ∀ side, Fields.ValidPadding (sizes c g) cuts i tag side := by
+ let s := sizes c g
+ let m := physicalMemory (d := g.d) hw advice cuts i
+ let a := addr g lit
+ have av := addr_value g lit c bounds.fit.le
+ have below : a.val < base g := by change (addr g lit).val < _; rw [av]; exact Nat.lt_succ_self _
+ have hz : m a.val = LiveStageLink.tagWord g.w Stage.header := by
+ simp [a,m,physicalMemory,RAMMemory.initialMemory,av,LiveStageLink.tagWord,Stage.header]
+ have fit21 : 21 ≤ 2^g.w := (by decide : 21 ≤ stages.length).trans ht
+ rw [outer_program] at run
+ obtain ⟨before,_,raw,_,source,stop⟩ := LiveStageLink.recover_accepting_stage
+ (tables c p O) (LiveProgram.next p) (words c p O g lit) a Stage.header fit21
+ (by omega : 2*21+2 ≤ fuel) 0 m bs logs hz (by
+ intro st mem bits rep he _
+ have hs := (relocated_call c p O g lit _ st mem bits).symm.trans he
+ exact native_protected s (base g) bounds.fit.le hw ht _ st mem bits rep hs _ below) run halt
+ rw [relocated_segment] at source
+ let cap := fuel-(LiveStageLink.dispatchEvents a Stage.header).length
+ have disp : (LiveStageLink.dispatchEvents a Stage.header).length = 4 := rfl
+ have capFit : 107 ≤ cap := by dsimp only [cap]; rw [disp]; omega
+ cases tagEq : physicalTag cuts i with
+ | none =>
+ exact (bad_mode_native s (base g) cap hw advice cuts i tagEq hi had bounds.scratch bounds.fit.le ht capFit
+ ⟨before,raw,source,stop⟩).elim
+ | some tag =>
+ refine ⟨tag,rfl,?_⟩
+ by_contra bad
+ exact bad_padding_native s (base g) cap hw advice cuts i tag bounds hi had ht capFit tagEq bad
+ ⟨before,raw,source,stop⟩
+
+end LiveProgram.Header
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramHeaderFlags.lean b/lean/OAI/Computability/VPVNP/LiveProgramHeaderFlags.lean
new file mode 100644
index 0000000000..48aa0ab550
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramHeaderFlags.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.LiveProgramHandoffs
+import OAI.Computability.VPVNP.LiveHeaderComplete
+
+/-! # Reading the physical header flags used by the outer routers -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.HeaderFlags
+open BurstRAM LiveHeaderProgram LiveHeaderSchedule LiveHeaderWidths ChainAssignments
+open scoped Fin.CommRing
+
+variable (c : Constants) (g : Geometry) (lit : LiteralPrefix)
+
+/-- The evaluated header dimensions used to locate the physical router flags in this group. -/
+abbrev size := c.lengths.eval g
+/-- Header workspace base for locating the mode, first-tail and last-group flags after the
+processor array and outer tag. -/
+abbrev base := 2^g.d+1
+
+/-- The loaded router flag word names the same checked physical metadata cell
+as the standalone header parser. The address arithmetic fits before resizing. -/
+theorem flag_address (r : Router) (fit : LiveHeaderSchedule.limit (size c g) (base g) < 2^g.w) :
+ ((r.data g lit) 0).val = match r with
+ | .mode => tagAddr (base g)
+ | .firstTail => firstTailAddr (base g)
+ | .last => flagAddr (base g) .last := by
+ rw [LiveHeaderSchedule.limit_eq] at fit
+ cases r with
+ | mode => exact Nat.mod_eq_of_lt (by change base g+11 < 2^g.w; omega)
+ | firstTail => exact Nat.mod_eq_of_lt (by change base g+10 < 2^g.w; omega)
+ | last => exact Nat.mod_eq_of_lt (by change base g+9 < 2^g.w; omega)
+
+variable {hw : 4 ≤ g.w} {advice : CutSchedule.Bits (size c g).advice}
+variable {cuts : AllCuts (size c g).h (size c g).delta}
+variable {site : Fin (2^((size c g).h+1))} {tag : LiveHeader.Mode.Tag} {m : Memory g.w}
+
+/-- The native mode router reads the exact zero/unit, one/pair, two/tail code. -/
+theorem mode (fit : LiveHeaderSchedule.limit (size c g) (base g) < 2^g.w)
+ (out : Output (size c g) (base g) g.d hw advice cuts site tag m) :
+ m ((Router.mode.data g lit) 0).val = Fin.ofNat (2^g.w) tag.code.val := by
+ rw [flag_address c g lit .mode fit]
+ exact out.scalars .mode
+
+/-- The middle cut supplies exponents exactly to the group immediately after it. -/
+theorem firstTail (fit : LiveHeaderSchedule.limit (size c g) (base g) < 2^g.w)
+ (out : Output (size c g) (base g) g.d hw advice cuts site tag m) :
+ m ((Router.firstTail.data g lit) 0).val =
+ (if site.val+1 = 2^(size c g).h+1 then 1 else 0) := by
+ rw [flag_address c g lit .firstTail fit]
+ simpa [Metadata.Correct,Metadata.Field.address,PrimedInputRAM.encodeBit] using out.scalars .firstTail
+
+/-- The last flag distinguishes a prescribed accepting endpoint from an
+outgoing configuration stored on a physical cut. -/
+theorem last (fit : LiveHeaderSchedule.limit (size c g) (base g) < 2^g.w)
+ (out : Output (size c g) (base g) g.d hw advice cuts site tag m) :
+ m ((Router.last.data g lit) 0).val =
+ (if site.val+1 = 2^((size c g).h+1) then 1 else 0) := by
+ rw [flag_address c g lit .last fit]
+ by_cases h : site.val+1 = 2^((size c g).h+1) <;>
+ simpa [Metadata.Correct,Metadata.Field.address,Flag.holds,PrimedInputRAM.encodeBit,h] using out.scalars (.flag .last)
+
+end LiveProgram.HeaderFlags
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramLayout.lean b/lean/OAI/Computability/VPVNP/LiveProgramLayout.lean
new file mode 100644
index 0000000000..3d20dbaf70
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramLayout.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.LiveHeaderExpressions
+import OAI.Computability.VPVNP.PrimedStackRAMLayout
+import OAI.Computability.VPVNP.RAMParameters
+
+/-!
+# Public geometry and disjoint working regions of the live program
+
+The group header occupies addresses below `2^d`. The external tag, the
+header parser's own workspace and the remaining arrays start above it. The
+shadow of the auxiliary RAM has room for every virtual site. Unused shadow
+addresses have zero default and need no initialization.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+open PublicExpr
+
+/-- Fixed choices for a circuit exponent and a fixed expander and evaluator. -/
+structure Constants where
+ /-- Circuit-size exponent used in the grammar state bound `n^(circuitExponent + 5)`. -/
+ circuitExponent : ℕ
+ /-- Exponent giving the height parameter of the paired chain as a power of the input length. -/
+ chainPower : ℕ
+ /-- Exponent giving the capacity of the live header’s advice field as a power of the input
+ length. -/
+ advicePower : ℕ
+ /-- Exponent giving the cut-width parameter of the live header as a power of the input
+ length. -/
+ deltaPower : ℕ
+ /-- Exponent giving the radius of the bounded tape windows in an evaluator configuration. -/
+ radiusPower : ℕ
+ /-- Exponent reserving space for the packed literal prefix in the live memory layout. -/
+ prefixPower : ℕ
+ /-- Number of motif labels appended to the grammar production labels. -/
+ motifLabels : ℕ
+
+namespace Constants
+
+/-- Public expression for the number of grammar states at length n, namely n raised to the
+circuit exponent plus five. -/
+def states (c : Constants) := PublicExpr.n.natPow (c.circuitExponent + 5)
+
+/-- Number of terminal and ordered binary production labels. Terminals contribute two per
+position and state, and each degree split contributes one per ordered triple of states. -/
+def grammarLabels (c : Constants) : PublicExpr :=
+ let states := c.states
+ let pairs := .divConst (.mul .n (.sub .n 1)) 2
+ states * .n * 2 + ((pairs*states)*states)*states
+
+/-- Total number of counters for grammar productions and motif labels together. -/
+def labels (c : Constants) := c.grammarLabels + .lit c.motifLabels
+/-- Public chain height `n^chainPower`, one more than the header’s chain parameter h. -/
+def height (c : Constants) := PublicExpr.n.natPow c.chainPower
+/-- Number of exponent bits per label, twice the public chain height. -/
+def Z (c : Constants) := 2 * c.height
+/-- Radius of each evaluator tape window at the current input length. -/
+def radius (c : Constants) := PublicExpr.n.natPow c.radiusPower
+/-- Words per evaluator configuration, comprising one state word and two tape windows of twice
+the radius plus one cell each. -/
+def configWords (c : Constants) := 1 + (2*c.radius+1) + (2*c.radius+1)
+/-- Reserved capacity for storing the program prefix at the current input length. -/
+def prefixCapacity (c : Constants) := PublicExpr.n.natPow c.prefixPower
+
+/-- Header parameters for chain height minus one, cut width, advice capacity, total exponent
+bits, and the two-tape configuration’s bit length. -/
+def lengths (c : Constants) : Lengths := ⟨.sub c.height 1, PublicExpr.n.natPow c.deltaPower,
+ PublicExpr.n.natPow c.advicePower, c.labels*c.Z, c.configWords * .w⟩
+
+/-- Concrete triangular production index used in the auxiliary preorder parser. -/
+theorem grammarLabels_eq (c : Constants) (g : Geometry) :
+ c.grammarLabels.eval g = PrimedStackRAM.labelCount g.n g.n (g.n^(c.circuitExponent+5)) := by
+ simp [grammarLabels, states, PublicExpr.eval, PrimedStackRAM.labelCount, Nat.choose_two_right]
+
+end Constants
+
+namespace Layout
+
+/-- Address of the external dispatch tag, immediately above the range of the d-bit site
+addresses. -/
+def stageTag : PublicExpr := .pow2 .d
+/-- Start of the live header parser’s workspace, one word after the stage tag. -/
+def header := stageTag + 1
+/-- Start of the auxiliary descriptor table at the end of the live header workspace. -/
+def descriptor (c : Constants) := HeaderLayout.limit c.lengths header
+/-- Start of the label-counter array after the seven three-word auxiliary descriptors. -/
+def counter (c : Constants) := descriptor c + 21
+/-- Start of the saved evaluator configuration immediately after the label counters. -/
+def oldState (c : Constants) := counter c + c.labels
+/-- Start of the next evaluator configuration after the saved configuration’s word array. -/
+def newState (c : Constants) := oldState c + c.configWords
+/-- Start of temporary storage for evaluator transitions after both configuration arrays. -/
+def transitionScratch (c : Constants) := newState c + c.configWords
+/-- Start of the advice frames after the five transition scratch words. -/
+def adviceFrames (c : Constants) := transitionScratch c + 5
+/-- Start of the packed literal-prefix area after the twenty-four advice-frame words. -/
+def packedPrefix (c : Constants) := adviceFrames c + 24
+/-- Reserve the full prefix capacity in addresses. Packing uses at most one
+word per bit, including when the active prefix is shorter than its capacity. -/
+def orderMap (c : Constants) := packedPrefix c + c.prefixCapacity
+/-- Start of the virtual RAM shadow after the order map, which reserves one entry per label. -/
+def shadow (c : Constants) := orderMap c + c.labels
+
+/-- Virtual bucket exponent obtained by rounding the ceiling binary logarithm of n up to the
+next multiple of four and dividing by four. -/
+def virtualBucketBits : PublicExpr := .divConst (.add (.clog2 .n) 3) 4
+/-- Virtual site address width obtained by subtracting the virtual bucket exponent from the
+ceiling binary logarithm of the total virtual capacity. -/
+def virtualSiteBits : PublicExpr := .sub (.clog2 (stageTag * .n * (.clog2 .n))) virtualBucketBits
+/-- Start of the pair table’s workspace after reserving one shadow word per virtual site. -/
+def pairWorkspace (c : Constants) := shadow c + .pow2 virtualSiteBits
+
+theorem virtualSiteBits_eq (g : Geometry) (hn : 1 ≤ g.n) :
+ virtualSiteBits.eval g = BurstRAM.virtualSiteExponent g.d g.n := by
+ have he := Compression.bucketExponent_ratio_eq (a := 1) (b := 4) (by decide) hn
+ have h := BurstRAM.roundedUp_eq 1 4 g.n
+ simp only [pow_one] at he
+ rw [BurstRAM.virtualSiteExponent, h, he]
+ change Nat.clog 2 (2^g.d * g.n * Nat.clog 2 g.n) - (Nat.clog 2 g.n + 3)/4 = _
+ rw [show Nat.clog 2 g.n + 4 - 1 = Nat.clog 2 g.n + 3 by omega]
+
+end Layout
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramNominationCalls.lean b/lean/OAI/Computability/VPVNP/LiveProgramNominationCalls.lean
new file mode 100644
index 0000000000..791a41d0d6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramNominationCalls.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.LiveProgramPairStages
+import OAI.Computability.VPVNP.LiveAuxiliaryStages
+import OAI.Computability.VPVNP.LiveHeaderProtectedCore
+
+/-! # Actual nomination calls in the linked first-half group -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Nominations
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink LiveAuxiliaryStages
+open scoped Fin.CommRing
+
+variable (G : Group)
+
+/-- Width in bits of each nominated grammar-production count, twice the site-address width. -/
+abbrev width := 2*G.g.d
+/-- Number of grammar-production positions visited by the nomination stage. -/
+abbrev labels := G.constants.grammarLabels.eval G.g
+/-- RAM word addressing the first counter to which a nominated production count is written. -/
+abbrev base := Pieces.word G.g G.lit (.geometry (Layout.counter G.constants))
+/-- Grammar-label count encoded as the terminating cursor value in the group’s word width. -/
+abbrev limit : Word G.w := Fin.ofNat _ (labels G)
+/-- Instruction fuel available to a nomination call after outer dispatch. -/
+abbrev fuel := G.clockAt Stage.nominations
+/-- Nomination-stage source program with the linked table’s actual public operands. -/
+abbrev P := sourceProgram G.T G.pub Stage.nominations
+
+private theorem pub_eq :
+ (fun j => Pieces.word G.g G.lit (.geometry (StageOperands.nomination G.constants j))) =
+ nominationData (width G) (base G) (limit G) := by
+ funext j
+ fin_cases j <;> rfl
+
+theorem execute_eq (f : ℕ) (s : Word G.w) (m : Memory G.w) (bs : List Bool) :
+ let Q := (nomination.instantiate G.w (nominationData (width G) (base G) (limit G))).program
+ execute (P G) f ((P G).start s) m bs = execute Q f (Q.start s) m bs := by
+ have h := Pieces.component_eq G.components G.g G.lit Stage.nominations f s m bs
+ change execute (P G) f ((P G).start s) m bs =
+ execute (nomination.instantiate G.w _).program f ((nomination.instantiate G.w _).program.start s) m bs at h
+ rw [← pub_eq]
+ exact h
+
+/-- A forward component and its unique successful decoding, with the actual
+common outer clock after deducting dispatch. -/
+theorem active (hb : width G ≤ G.w) (hf : 5*width G+15 ≤ fuel G) (s : Word G.w) (hs : s < limit G)
+ (m : Memory G.w) (v : Word (width G)) :
+ ∃ r, execute (P G) (fuel G) ((P G).start s) m (wordBits v) = some r ∧
+ r.result = some (s+1) ∧ after m r.events = writeMemory m (base G+s) (Fin.ofNat _ v.val) ∧
+ r.events.length = 5*width G+14 ∧ countProbes r.events = 1 := by
+ obtain ⟨es,he,hm,hl,hp,_⟩ := nomination_active hb (base G) (limit G) s hs m v
+ refine ⟨⟨es,some (s+1)⟩, ?_, rfl, hm, hl, hp⟩
+ rw [execute_eq]
+ simpa only [Nat.add_sub_of_le hf] using execute_extend he (fuel G-(5*width G+15))
+
+theorem active_only (hb : width G ≤ G.w) (hf : 3 ≤ fuel G) (s : Word G.w) (hs : s < limit G)
+ (m : Memory G.w) {bs : List Bool} {r : Report G.w}
+ (hc : execute (P G) (fuel G) ((P G).start s) m bs = some r) :
+ ∃ v : Word (width G), bs = wordBits v ∧ r.result = some (s+1) ∧
+ after m r.events = writeMemory m (base G+s) (Fin.ofNat _ v.val) := by
+ rw [execute_eq] at hc
+ have eq := LiveHeaderBounded.execute_active (LiveNominations.flow.template (some 7))
+ (LiveNominations.data (width G) (base G)) (limit G) (fuel G-3) s hs m bs
+ rw [Nat.sub_add_cancel hf] at eq
+ obtain ⟨rep, he, rfl⟩ := Option.map_eq_some_iff.mp (eq.symm.trans hc)
+ obtain ⟨v,hv,hr,hm,_⟩ := LiveNominations.component_only hb (base G) s m he
+ exact ⟨v,hv,hr,hm⟩
+
+/-- Three-tick closing nomination report with no returned state. -/
+def closing (w : ℕ) : Report w := ⟨[.tick,.tick,.tick],none⟩
+
+theorem closed (hf : 4 ≤ fuel G) (s : Word G.w) (hs : limit G ≤ s) (m : Memory G.w) (bs : List Bool) :
+ execute (P G) (fuel G) ((P G).start s) m bs = if bs=[] then some (closing G.w) else none := by
+ rw [execute_eq]
+ have h := nomination_closed (width G) (fuel G-4) (base G) (limit G) s hs m bs
+ rw [Nat.sub_add_cancel hf] at h
+ cases bs <;> simpa [closing] using h
+
+theorem limit_val (hT : labels G < 2^G.w) : (limit G).val = labels G := Nat.mod_eq_of_lt hT
+
+theorem base_add (fit : (base G).val + labels G ≤ 2^G.w) (i : Fin (labels G)) :
+ base G + (i.val : Word G.w) = PrimedInputRAM.scratchAddress (base G).val fit i := by
+ have ha := (Nat.add_lt_add_left i.isLt (base G).val).trans_le fit
+ have hv : ((i.val : Word G.w) : ℕ) = i.val := by rw [Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ apply Fin.ext
+ rw [Fin.val_add_eq_of_add_lt (by simpa only [hv] using ha), hv]
+ rfl
+
+theorem frame (hb : width G ≤ G.w) (hT : labels G < 2^G.w) (hf : 5*width G+15 ≤ fuel G)
+ (fit : (base G).val + labels G ≤ 2^G.w)
+ (fresh : G.addr.val < (base G).val ∨ (base G).val+labels G ≤ G.addr.val) :
+ TagFrame G.T G.pub G.addr Stage.nominations (fuel G) (fun s _ => s ≤ limit G) := by
+ intro s m bs r next hs tag call ret
+ rcases lt_or_eq_of_le hs with h | rfl
+ · obtain ⟨v,_,hv,hm⟩ := active_only G hb (by omega) s h m call
+ have hr := Option.some.inj (ret.symm.trans hv)
+ have hval : s.val < labels G := (show s.val < (limit G).val from h).trans_eq (limit_val G hT)
+ have room : (base G).val + s.val < 2^G.w := by omega
+ refine ⟨?_, ?_⟩
+ · change next.val ≤ (limit G).val
+ rw [hr,Fin.val_add_one_of_lt' (show s.val+1 < 2^G.w by omega), limit_val G hT]
+ omega
+ · rw [hm]
+ change (if G.addr.val=(base G+s).val then _ else _) = _
+ rw [Fin.val_add_eq_of_add_lt room, ite_eq_right (by omega)]
+ exact tag
+ · rw [closed G (by omega) _ le_rfl] at call
+ split at call
+ · simp [← Option.some.inj call, closing] at ret
+ · contradiction
+
+end LiveProgram.PairStages.Group.Nominations
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramNominationPaths.lean b/lean/OAI/Computability/VPVNP/LiveProgramNominationPaths.lean
new file mode 100644
index 0000000000..baa91ed15a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramNominationPaths.lean
@@ -0,0 +1,230 @@
+import OAI.Computability.VPVNP.LiveProgramNominationCalls
+
+/-! # Bijection between histogram nominations and native stage histories -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Nominations
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink PrimedInputRAM
+open scoped Fin.CommRing
+
+variable (G : Group)
+
+/-- One fixed-width nominated count at every position of the dense grammar-label array. -/
+abbrev Nom := Fin (labels G) → Word (width G)
+
+private theorem aligned (T : ℕ) :
+ (List.finRange T).map Fin.val = List.range' 0 (List.finRange T).length := by
+ apply List.ext_getElem (by simp)
+ intro i _ _
+ simp
+
+/-- An active nomination call returns a state, uses one probe, and records exactly five times
+the nomination width plus fourteen events. -/
+def activeReport (r : Report G.w) : Prop :=
+ r.result.isSome ∧ r.events.length = 5*width G+14 ∧ r.probes = 1
+
+private theorem emit (hb : width G ≤ G.w) (hT : labels G < 2^G.w) (hf : 5*width G+15 ≤ fuel G)
+ (fit : (base G).val + labels G ≤ 2^G.w) (μ : Nom G) (cells : List (Fin (labels G)))
+ (j : ℕ) (ha : cells.map Fin.val = List.range' j cells.length) (hj : j+cells.length = labels G) (m : Memory G.w) :
+ ∃ rs, rs.length = cells.length ∧ (∀ r ∈ rs, activeReport G r) ∧
+ Completion G.T G.nextStage G.pub G.addr Stage.nominations (fuel G) (j : Word G.w) m
+ ((cells.map fun i => wordBits (μ i)) ++ [[]]) (rs ++ [closing G.w])
+ (store (scratchAddress (base G).val fit) (fun i => Fin.ofNat _ (μ i).val) cells m) := by
+ induction cells generalizing j m with
+ | nil =>
+ simp only [List.length_nil,Nat.add_zero] at hj
+ subst j
+ have ce := closed G (by omega) (limit G) le_rfl m []
+ have call : execute (P G) (fuel G) ((P G).start (labels G : Word G.w)) m [] = some (closing G.w) := by
+ simpa using ce
+ have enough : room G.nextStage G.addr Stage.nominations (fuel G) (closing G.w) := by
+ change 6 < fuel G
+ omega
+ exact ⟨[],rfl,by simp,.last call rfl enough⟩
+ | cons i is ih =>
+ simp only [List.map_cons,List.length_cons,List.range'_succ,List.cons.injEq] at ha
+ obtain ⟨rfl,ha⟩ := ha
+ have hs : (i.val : Word G.w) < limit G := by
+ change ((i.val : Word G.w) : ℕ) < (limit G).val
+ rw [Fin.val_natCast,Nat.mod_eq_of_lt (i.isLt.trans hT),limit_val G hT]
+ exact i.isLt
+ obtain ⟨r,hc,hr,hm,hl,hp⟩ := active G hb hf _ hs m (μ i)
+ have enough : room G.nextStage G.addr Stage.nominations (fuel G) r := by
+ simp only [room,exitReport,hr]; omega
+ have hnext : (i.val : Word G.w)+1 = ((i.val+1 : ℕ) : Word G.w) := by simp
+ obtain ⟨rs, len, each, tail⟩ := ih (i.val+1) ha (by simp only [List.length_cons] at hj; omega) (after m r.events)
+ rw [← hnext] at tail
+ rw [base_add G fit i] at hm
+ have ht := Completion.more hc hr enough tail
+ rw [hm] at ht
+ refine ⟨r::rs, by simp [len], List.forall_mem_cons.mpr ⟨?_,each⟩, ht⟩
+ simp [activeReport,hr,hl,Report.probes,hp]
+
+private theorem decode {m : Memory G.w} {bs rs m'} {s : Word G.w}
+ (hb : width G ≤ G.w) (hf : 5*width G+15 ≤ fuel G)
+ (h : Completion G.T G.nextStage G.pub G.addr Stage.nominations (fuel G) s m bs rs m')
+ (hs : s ≤ limit G) :
+ ∃ xs : List (Word (width G)), xs.length + s.val = (limit G).val ∧ bs = xs.map wordBits ++ [[]] := by
+ induction h with
+ | @last s m bits rep call halt _ =>
+ rcases lt_or_eq_of_le hs with lt | rfl
+ · obtain ⟨_,_,ret,_⟩ := active_only G hb (by omega) s lt m call
+ rw [ret] at halt; contradiction
+ · rw [closed G (by omega) _ le_rfl] at call
+ split at call
+ · exact ⟨[],by simp,by simp_all⟩
+ · contradiction
+ | @more s m bits rep s' bs rs m' call cont _ _ ih =>
+ rcases lt_or_eq_of_le hs with lt | rfl
+ · obtain ⟨v, hv, hr, _⟩ := active_only G hb (by omega) s lt m call
+ have hs' : s' = s+1 := Option.some.inj (cont.symm.trans hr)
+ have hh : s'.val = s.val+1 := by
+ rw [hs',Fin.val_add_one_of_lt' (show s.val+1 < 2^G.w from (show s.val+1 ≤ (limit G).val from lt).trans_lt (limit G).isLt)]
+ obtain ⟨xs,len,out⟩ := ih (by change s'.val ≤ (limit G).val; rw [hh]; exact lt)
+ exact ⟨v::xs,by simp [hh] at len; simp; omega,by simp [hv,out]⟩
+ · rw [closed G (by omega) _ le_rfl] at call
+ split at call
+ · simp [← Option.some.inj call,closing] at cont
+ · contradiction
+
+/-- The source reports, before the dispatch read and closing tag transfer. -/
+theorem history (hb : width G ≤ G.w) (hT : labels G < 2^G.w) (hf : 5*width G+15 ≤ fuel G)
+ (fit : (base G).val + labels G ≤ 2^G.w) (μ : Nom G) (m : Memory G.w) :
+ ∃ rs, rs.length = labels G ∧ (∀ r ∈ rs, activeReport G r) ∧
+ Completion G.T G.nextStage G.pub G.addr Stage.nominations (fuel G) 0 m
+ (LiveNominations.calls μ ++ [[]]) (rs ++ [closing G.w]) (LiveNominations.stored (base G) fit μ m) := by
+ have h := emit G hb hT hf fit μ (List.finRange (labels G)) 0 (aligned _) (by simp) m
+ simpa only [List.length_finRange,Nat.cast_zero,LiveNominations.calls,List.ofFn_eq_map,LiveNominations.stored] using h
+
+private noncomputable def path (hb : width G ≤ G.w) (hT : labels G < 2^G.w) (hf : 5*width G+15 ≤ fuel G)
+ (fit : (base G).val + labels G ≤ 2^G.w) (m : Memory G.w) (μ : Nom G) : G.StagePaths Stage.nominations m :=
+ ⟨LiveNominations.calls μ ++ [[]], by
+ obtain ⟨rs,_,_,h⟩ := history G hb hT hf fit μ m
+ exact ⟨_,h.spec.1,h.spec.2.1,h.spec.2.2.2⟩⟩
+
+/-- Bijection from nomination arrays to complete nomination-stage paths, obtained by encoding
+and decoding the guessed words in grammar-label order. -/
+noncomputable def equiv (hb : width G ≤ G.w) (hT : labels G < 2^G.w) (hf : 5*width G+15 ≤ fuel G)
+ (fit : (base G).val + labels G ≤ 2^G.w) (m : Memory G.w) : Nom G ≃ G.StagePaths Stage.nominations m := by
+ apply Equiv.ofBijective (path G hb hT hf fit m)
+ constructor
+ · intro μ ν h
+ have ht : LiveNominations.calls μ ++ [[]] = LiveNominations.calls ν ++ [[]] := congrArg Subtype.val h
+ have hw := List.ofFn_inj.mp (List.append_cancel_right ht)
+ exact funext fun i => (List.ofFn_injective.comp (RAMSerialization.wordBits _).injective) (congrFun hw i)
+ · intro p
+ obtain ⟨xs,hlen,hb'⟩ := decode G hb hf
+ (completion_of_run (ordinaryRun p) p.property.choose_spec.2.1 p.property.choose_spec.2.2)
+ (by exact Fin.zero_le _)
+ have len : xs.length = labels G := by rw [limit_val G hT] at hlen; simpa using hlen
+ let μ : Nom G := fun i => xs[i.val]'(len.symm ▸ i.isLt)
+ refine ⟨μ,Subtype.ext ?_⟩
+ change LiveNominations.calls μ ++ [[]] = p.val
+ rw [hb']
+ congr 1
+ apply List.ext_getElem (by simp [LiveNominations.calls,len])
+ intro i _ _
+ simp [LiveNominations.calls,μ]
+
+/-- Word, clock and memory layout conditions of the nomination stage. -/
+structure Fits : Prop where
+ width_le : width G ≤ G.w
+ labels_lt : labels G < 2^G.w
+ clock_le : 5*width G+15 ≤ fuel G
+ address : (base G).val + labels G ≤ 2^G.w
+ tagOutside : G.addr.val < (base G).val ∨ (base G).val+labels G ≤ G.addr.val
+
+/-- Index the actual tagged nomination-stage histories by their nomination arrays, using the
+cursor bound and the word, address, and clock fits. -/
+noncomputable def indexed (F : Fits G) (m : Memory G.w) (tag : G.tagged Stage.nominations m) :
+ Indexed G Stage.nominations m (Nom G) where
+ inv s _ := s ≤ limit G
+ frame := frame G F.width_le F.labels_lt F.clock_le F.address F.tagOutside
+ ready := Fin.zero_le _
+ tag := tag
+ traces := equiv G F.width_le F.labels_lt F.clock_le F.address m
+
+theorem indexed_apply (F : Fits G) (m : Memory G.w) (tag : G.tagged Stage.nominations m) (μ : Nom G) :
+ ((indexed G F m tag).traces μ).val = LiveNominations.calls μ ++ [[]] := rfl
+
+private theorem reports (F : Fits G) (m : Memory G.w) (tag : G.tagged Stage.nominations m) (μ : Nom G) :
+ ∃ rs, rs.length = labels G ∧ (∀ r ∈ rs, activeReport G r) ∧
+ ordinaryReports ((indexed G F m tag).traces μ) = rs ++ [closing G.w] ∧
+ after m (eventLog (rs ++ [closing G.w])) = LiveNominations.stored (base G) F.address μ m := by
+ obtain ⟨rs,hl,hp,hc⟩ := history G F.width_le F.labels_lt F.clock_le F.address μ m
+ have hr := ordinaryRun ((indexed G F m tag).traces μ)
+ rw [indexed_apply] at hr
+ exact ⟨rs,hl,hp,Option.some.inj (hr.symm.trans hc.spec.1),hc.spec.2.2.1⟩
+
+theorem memory_eq (F : Fits G) (m : Memory G.w) (tag : G.tagged Stage.nominations m) (μ : Nom G) :
+ (indexed G F m tag).memory μ =
+ transferMemory G.addr (some Stage.auxiliaryInit) (LiveNominations.stored (base G) F.address μ m) := by
+ obtain ⟨_,_,_,hr,hm⟩ := reports G F m tag μ
+ rw [Indexed.memory,hr,hm]
+ rfl
+
+theorem logs_length (F : Fits G) (m : Memory G.w) (tag : G.tagged Stage.nominations m) (μ : Nom G) :
+ ((indexed G F m tag).logs μ).length = labels G + 1 := by
+ obtain ⟨rs,hl,_,hr,_⟩ := reports G F m tag μ
+ simp [Indexed.logs,hr,hl]
+
+theorem logs_probes (F : Fits G) (m : Memory G.w) (tag : G.tagged Stage.nominations m) (μ : Nom G) :
+ ∀ r ∈ (indexed G F m tag).logs μ, r.probes = 2 := by
+ obtain ⟨rs,_,each,hr,_⟩ := reports G F m tag μ
+ rw [Indexed.logs,hr]
+ intro r h
+ obtain ⟨a,ha,rfl⟩ := List.mem_map.mp h
+ rw [linkedReport_probes]
+ rcases List.mem_append.mp ha with h | h
+ · obtain ⟨live,_,one⟩ := each a h
+ have hn : a.result ≠ none := by cases v : a.result <;> simp_all
+ simp [one,hn]
+ · obtain rfl := List.mem_singleton.mp h
+ rfl
+
+theorem logs_cost (F : Fits G) (m : Memory G.w) (tag : G.tagged Stage.nominations m) (μ : Nom G) :
+ RAMBuckets.cost Report.probes ((indexed G F m tag).logs μ) = (labels G + 1)*3 := by
+ have all (xs : List (Report G.w)) (h : ∀ a ∈ xs, a.probes = 2) :
+ RAMBuckets.cost Report.probes xs = xs.length*3 := by
+ induction xs with
+ | nil => rfl
+ | cons a xs ih =>
+ obtain ⟨ha, ht⟩ := List.forall_mem_cons.mp h
+ rw [RAMBuckets.cost,ha,ih ht,List.length_cons,Nat.succ_mul]
+ omega
+ rw [all _ (logs_probes G F m tag μ),logs_length]
+
+/-- Linked active calls have one dispatcher read and one store. The last call
+instead transfers the stage tag. Its shorter local run has a fixed length. -/
+theorem logs_lengths (F : Fits G) (m : Memory G.w) (tag : G.tagged Stage.nominations m) (μ : Nom G) :
+ ((indexed G F m tag).logs μ).map (fun r => r.events.length) =
+ List.replicate (labels G) (5*width G+22) ++ [14] := by
+ obtain ⟨rs,hl,each,hr,_⟩ := reports G F m tag μ
+ have lengths (a : Report G.w) (h : activeReport G a) :
+ (linkedReport G.nextStage G.addr Stage.nominations a).events.length = 5*width G+22 := by
+ rcases h with ⟨live,len,_⟩
+ cases ha : a.result with
+ | none => simp [ha] at live
+ | some v =>
+ simp only [linkedReport,prependLog,exitReport,ha,List.length_append,len]
+ change 8+(5*width G+14) = _
+ omega
+ have hmap : rs.map (fun a => (linkedReport G.nextStage G.addr Stage.nominations a).events.length) =
+ List.replicate rs.length (5*width G+22) := by
+ apply List.ext_getElem (by simp)
+ intro i h₁ h₂
+ simp only [List.getElem_map,List.getElem_replicate]
+ exact lengths _ (each _ (List.getElem_mem _))
+ rw [Indexed.logs,hr,List.map_append,List.map_append,List.map_map]
+ change rs.map (fun a => (linkedReport G.nextStage G.addr Stage.nominations a).events.length) ++ [14] = _
+ rw [hmap,hl]
+
+end LiveProgram.PairStages.Group.Nominations
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPair.lean b/lean/OAI/Computability/VPVNP/LiveProgramPair.lean
new file mode 100644
index 0000000000..6f2082f5b7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPair.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.LiveProgramPairStages
+
+/-!
+# The four ordinary handoffs before the first-half exponent check
+
+Histograms and accepted compressor choices remain separate indices. The
+initializer and copy have one path each. Joining the four stages preserves
+the entire report sequence that enters the final exponent check.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages
+open BurstRAM LiveStageLink
+open scoped Classical
+
+namespace Group
+
+variable {G : Group} {m : Memory G.w} {Nom : Type*} {Path : Nom → Type*}
+
+/-- Local path classifications of the four stages preceding the terminal
+digit test. Each classification concerns only its native component. -/
+structure Chronology (G : Group) (m : Memory G.w) (Nom : Type*) (Path : Nom → Type*) where
+ /-- Nomination-stage histories starting in the group’s initial memory and indexed by the
+ chosen histogram. -/
+ nominations : Indexed G Stage.nominations m Nom
+ /-- The unique auxiliary initialization following each nomination in the memory left by that
+ nomination. -/
+ init (μ : Nom) : Indexed G Stage.auxiliaryInit (nominations.memory μ) Unit
+ /-- The unique auxiliary copy following initialization for the chosen nomination. -/
+ copy (μ : Nom) : Indexed G Stage.auxiliaryCopy ((init μ).memory ()) Unit
+ /-- Pair-stage histories starting in the copy’s actual final memory and indexed by a path for
+ that nomination. -/
+ pair (μ : Nom) : Indexed G Stage.pair ((copy μ).memory ()) (Path μ)
+
+private def single {β : Unit → Type*} : β () ≃ Σ u : Unit, β u where
+ toFun x := ⟨.unit,x⟩
+ invFun x := by rcases x with ⟨u,x⟩; cases u; exact x
+ left_inv _ := rfl
+ right_inv x := by rcases x with ⟨u,x⟩; cases u; rfl
+
+namespace Chronology
+variable (A : Chronology G m Nom Path)
+
+/-- Linked reports from nomination, initialization, sparse copy, and the selected pair path
+concatenated in execution order. -/
+noncomputable def prefixLogs (μ : Nom) (q : Path μ) :=
+ A.nominations.logs μ ++ ((A.init μ).logs .unit ++ ((A.copy μ).logs .unit ++ (A.pair μ).logs q))
+
+/-- Every accepting run through this branch has one and only one nomination,
+one compressed pair path, and one accepting terminal check. The final check's
+cap includes the reports of all four preceding stages. -/
+noncomputable def paths (cap : List (Report G.w) → Prop) :
+ (Σ μ : Nom, Σ q : Path μ, ActualPaths G.P G.clock 0 ((A.pair μ).memory q)
+ (fun tail => cap (A.prefixLogs μ q ++ tail))) ≃ ActualPaths G.P G.clock 0 m cap := by
+ apply Equiv.trans _ (A.nominations.continuationEquiv (s' := Stage.auxiliaryInit) rfl cap)
+ apply Equiv.sigmaCongrRight
+ intro μ
+ let check₁ := fun rest => cap (A.nominations.logs μ ++ rest)
+ let check₂ := fun rest => check₁ ((A.init μ).logs .unit ++ rest)
+ let check₃ := fun rest => check₂ ((A.copy μ).logs .unit ++ rest)
+ apply Equiv.trans _ ((A.init μ).continuationEquiv (s' := Stage.auxiliaryCopy) rfl check₁)
+ apply Equiv.trans _ single
+ apply Equiv.trans _ ((A.copy μ).continuationEquiv (s' := Stage.pair) rfl check₂)
+ apply Equiv.trans _ single
+ apply Equiv.trans _ ((A.pair μ).continuationEquiv (s' := Stage.exponents) rfl check₃)
+ apply Equiv.sigmaCongrRight
+ intro q
+ simp only [check₁,check₂,check₃,prefixLogs,List.append_assoc]
+ exact Equiv.refl _
+
+end Chronology
+end Group
+end LiveProgram.PairStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairActive.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairActive.lean
new file mode 100644
index 0000000000..040307b706
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairActive.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.LiveProgramPairPreparation
+import OAI.Computability.VPVNP.LiveProgramPairCount
+import OAI.Computability.VPVNP.LivePhysicalRoutes
+import OAI.Computability.VPVNP.LiveHeaderFieldFormats
+
+/-! # The native first-half count following the physical mode router
+
+The only stage-specific trace input in the count below concerns the
+compressed pair table itself. The histogram sweep, descriptor initialization,
+sparse copy and final exponent test use their verified native programs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink LiveExponent
+open ChainAssignments CutSchedule ExponentTrace LiveHeader LiveHeaderProgram
+open scoped Classical
+
+variable {G : Group} {m : Memory G.w} {i : Fin (2^(Auxiliary.sizes G).h)}
+
+/-- Number of exponent-test counters, including both grammar-production and motif labels. -/
+abbrev labelCount (G : Group) := G.constants.labels.eval G.g
+/-- Bit width of each label’s exponent field in the live header. -/
+abbrev expWidth (G : Group) := G.constants.Z.eval G.g
+
+/-- Exact-use path semantics of the separately implemented compressed pair
+stage, at its literal input ABI and the actual memory produced by the copy. -/
+structure PairCall {N : Indexed G Stage.nominations m (Nominations.Nom G)} {μ : Nominations.Nom G}
+ {hdr : PrimedInputRAM.Header (Auxiliary.pairLengths G i) → Bool}
+ (B : Auxiliary.PreparedBranch G m i hdr N μ) (X : Type*) (increment : X → Fin (labelCount G) → ℕ) where
+ /-- Path index for the compressed pair program running from the memory actually produced by
+ the auxiliary copy. -/
+ indexed : Indexed G Stage.pair (B.copy.memory ()) X
+ header (q : X) (a : ℕ) : Auxiliary.headerBase G ≤ a → a < Auxiliary.tableBase G →
+ indexed.memory q a = B.copy.memory () a
+ count (q : X) (a : Fin (labelCount G)) :
+ (indexed.memory q (counterAddr G.exponentPub a).val).val = increment q a
+
+private theorem format {s : LiveHeaderSchedule.Sizes} {cuts : AllCuts s.h s.delta}
+ {i : Fin (2^s.h)} {t Z : ℕ} (he : s.e = t*Z) (fit : 1+t*Z ≤ s.delta)
+ (mode : physicalTag cuts (halves s.h (.inl i)) = some .pair)
+ (pad : Fields.ValidPadding s cuts (halves s.h (.inl i)) .pair .right) :
+ pairFormat fit (liveCutEquiv s.h s.delta cuts).1 i := by
+ let j := halves s.h (.inl i)
+ have hi : 0 < j.succ.val := by change 0 < i.val+1; omega
+ have half : j.succ.val ≤ 2^s.h := i.isLt
+ have heval := ((physicalTag_pair (by omega) cuts j).mp mode).1.2 hi
+ (by change i.val+1 < 2^(s.h+1); rw [pow_succ]; have := i.isLt; have := Nat.two_pow_pos s.h; omega)
+ have hwidth : 0 < width (s.h+1) s.delta (i.val+1) := by
+ rw [width_double s.h s.delta _ (Nat.succ_pos _) i.isLt]; omega
+ have hmode : distributedBit ((liveCutEquiv s.h s.delta cuts).1 i) 0 = true := heval
+ have hread := (Fields.validPadding_pair_iff (by decide : Mode.Tag.pair ≠ .unit) .right he fit hi half).mp pad
+ constructor
+ · change ((liveCutEquiv s.h s.delta cuts).1 i) ⟨0,hwidth⟩ = true
+ simpa only [distributedBit,hwidth,↓reduceDIte] using hmode
+ · exact hread
+
+variable {cuts : AllCuts (Auxiliary.sizes G).h (Auxiliary.sizes G).delta}
+ (fit : 1+labelCount G*expWidth G ≤ (Auxiliary.sizes G).delta)
+ {Path : Exterior (Auxiliary.sizes G).h (Auxiliary.sizes G).delta → Fin (2^(Auxiliary.sizes G).h) →
+ Nominations.Nom G → Type*}
+ [∀ ξ j μ, Fintype (Path ξ j μ)]
+ (inc : ∀ ξ j μ, Path ξ j μ → Fin (labelCount G) → ℕ)
+
+/-- The live first-half bit assignment extracted from the physical cuts by the live-cut
+equivalence. -/
+abbrev fst (cuts : AllCuts (Auxiliary.sizes G).h (Auxiliary.sizes G).delta) :=
+ (liveCutEquiv (Auxiliary.sizes G).h (Auxiliary.sizes G).delta cuts).1
+
+/-- The exact contribution on a valid first-half branch after the actual
+header and router prefix. The cap is evaluated on every physically joined
+report, retaining the prefix costs. -/
+theorem post_header_count {hw : 4 ≤ G.w} {advice : Bits (Auxiliary.sizes G).advice}
+ (out : LiveHeaderProgram.Output (Auxiliary.sizes G) (Auxiliary.headerBase G) G.g.d hw advice cuts
+ (halves (Auxiliary.sizes G).h (.inl i)) .pair m)
+ (selected : physicalTag cuts (halves (Auxiliary.sizes G).h (.inl i)) = some .pair)
+ (pad : Fields.ValidPadding (Auxiliary.sizes G) cuts (halves (Auxiliary.sizes G).h (.inl i)) .pair .right)
+ (tag : G.tagged Stage.nominations m)
+ (room : Auxiliary.shadowBase G + LiveAuxiliaryHeaders.span (Auxiliary.pairLengths G i) (Auxiliary.histLength G) ≤ 2^G.w)
+ (hwidth : 2*G.g.d ≤ G.w) (hn : 5*(2*G.g.d)+15 ≤ G.clockAt Stage.nominations)
+ (hi : 82 ≤ G.clockAt Stage.auxiliaryInit) (hc : 71 ≤ G.clockAt Stage.auxiliaryCopy)
+ (he : 31 ≤ G.clockAt Stage.exponents) (ht : 0 < labelCount G) (hZ : 0 < expWidth G)
+ (small : ∀ μ q a, inc (exteriorOf fit (fst cuts)) i μ q a + 1 < 2^G.w)
+ (S H : ℕ) (pre : List (Report G.w))
+ (native : let ξ := exteriorOf fit (fst cuts)
+ let F := Auxiliary.nominationFits G i room hwidth hn
+ let N := Nominations.indexed G F m tag
+ ∀ μ, ∀ B : Auxiliary.PreparedBranch G m i (PairedChain.headers advice ξ i) N μ,
+ ∃ C : PairCall B (Path ξ i μ) (inc ξ i μ), ∀ q,
+ withinCaps S H (pre ++ (N.logs μ ++ ((B.init.logs ()) ++
+ (B.copy.logs () ++ C.indexed.logs q))) ++
+ (stageReports G.exponentPub (labelCount G) (expWidth G) (C.indexed.memory q)).map
+ (linkedReport G.nextStage G.addr Stage.exponents))) :
+ Nat.card (ActualPaths G.P G.clock 0 m (fun tail => withinCaps S H (pre ++ tail))) =
+ pairCount fit inc (fst cuts) i := by
+ let ξ := exteriorOf fit (fst cuts)
+ let F := Auxiliary.nominationFits G i room hwidth hn
+ let N := Nominations.indexed G F m tag
+ let hdr := PairedChain.headers advice ξ i
+ have sz : (Auxiliary.sizes G).e = labelCount G*expWidth G := rfl
+ have good := format sz fit selected pad
+ let B (μ : Nominations.Nom G) : Auxiliary.PreparedBranch G m i hdr N μ :=
+ Classical.choice (Auxiliary.prepare out (by decide) sz fit room hwidth hn hi hc tag μ)
+ choose C hcaps using fun μ => native μ (B μ)
+ let A : Chronology G m (Nominations.Nom G) (Path ξ i) :=
+ ⟨N,fun μ => (B μ).init,fun μ => (B μ).copy,fun μ => (C μ).indexed⟩
+ obtain ⟨htag,hbase,hd,hcounter⟩ := Auxiliary.geometry_order G
+ have hfull := Auxiliary.counter_end_le_shadow G
+ have hspan : 0 < LiveAuxiliaryHeaders.span (Auxiliary.pairLengths G i) (Auxiliary.histLength G) := by
+ simp [LiveAuxiliaryHeaders.span,PrimedInputRAM.Header.count]
+ have hs : Auxiliary.shadowBase G < 2^G.w := by omega
+ have hfit : (Layout.oldState G.constants).eval G.g ≤ 2^G.w := by
+ change Auxiliary.counterBase G + G.constants.labels.eval G.g ≤ _; omega
+ have hlimit : LiveHeaderSchedule.limit (Auxiliary.sizes G) (Auxiliary.headerBase G) ≤ 2^G.w := by
+ change Auxiliary.tableBase G ≤ _; omega
+ let ebase := LiveHeaderSchedule.exponentBase (Auxiliary.sizes G) (Auxiliary.headerBase G)
+ have bounds side := LiveHeaderProgram.dest_bounds (Auxiliary.sizes G) (Auxiliary.headerBase G) side .exponents (by decide)
+ have basefit (side) : ebase side < 2^G.w := by
+ have h := (bounds side).2
+ change ebase side + (Auxiliary.sizes G).e ≤ Auxiliary.tableBase G at h
+ omega
+ have hdata μ q : BufferValues G.exponentPub (counters fit (fst cuts) i.castSucc)
+ (counters fit (fst cuts) i.succ) ((A.pair μ).memory q) := by
+ apply out.pairBufferValues_after i (by decide) sz fit hlimit G.exponentPub
+ (Nat.mod_eq_of_lt (basefit .left)) (Nat.mod_eq_of_lt (basefit .right))
+ intro side j hj
+ have high := (bounds side).2
+ change ebase side + (Auxiliary.sizes G).e ≤ Auxiliary.tableBase G at high
+ have low : Auxiliary.headerBase G ≤ ebase side := by
+ cases side <;> dsimp [ebase,LiveHeaderSchedule.exponentBase,LiveHeaderSchedule.exteriorBase,
+ LiveHeaderSchedule.adviceBase,LiveHeaderSchedule.rightIndexBase,LiveHeaderSchedule.leftIndexBase,
+ LiveHeaderSchedule.populationAddr,LiveHeaderSchedule.highAddr,LiveHeaderSchedule.indexBase] <;> omega
+ have lo : Auxiliary.headerBase G ≤ ebase side+j := by omega
+ have hi' : ebase side+j < Auxiliary.tableBase G := by omega
+ exact ((C μ).header q _ lo hi').trans ((B μ).headerFrame _ lo hi')
+
+ let cap := fun tail => withinCaps S H (pre ++ tail)
+ have hcap (rs) (ok : cap rs) : RAMBuckets.cost Report.probes rs ≤ S*H := by
+ have bound := ok.1; rw [RAMBuckets.cost_append] at bound; omega
+ have eq := A.count fit (fst cuts) i inc (ExponentStage.layout _ _ hfit ht) hZ (by omega) he
+ (ExponentStage.tag_fresh _ _ hfit) hdata (fun μ q a => (C μ).count q a) small cap _ hcap
+ (fun μ q => by simpa only [cap,Chronology.prefixLogs,A,List.append_assoc] using hcaps μ q)
+ exact (ite_eq_left good).symm.trans eq
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairAreas.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairAreas.lean
new file mode 100644
index 0000000000..235e9317cf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairAreas.lean
@@ -0,0 +1,212 @@
+import OAI.Computability.VPVNP.LiveProgramPairAuxiliary
+import OAI.Computability.VPVNP.LiveLayoutWordFit
+import OAI.Computability.VPVNP.LiveProgramNominationPaths
+
+/-! # Disjoint physical arrays for preparing the auxiliary pair counter -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM LiveAuxiliaryHeaders PrimedInputRAM
+open scoped Fin.CommRing
+
+private def starts (s : LiveHeaderSchedule.Sizes) (header counter : ℕ) : Fin 7 → ℕ :=
+ ![LiveHeaderSchedule.widthAddr header .primedLeft,LiveHeaderSchedule.leftIndexBase s header,
+ LiveHeaderSchedule.rightIndexBase s header,LiveHeaderSchedule.adviceBase s header,
+ LiveHeaderSchedule.exteriorBase s header .left,LiveHeaderSchedule.exteriorBase s header .right,counter]
+
+private theorem interval (s : LiveHeaderSchedule.Sizes) (header counter N : ℕ)
+ (hc : LiveHeaderSchedule.limit s header ≤ counter) (i : Fin (2^s.h)) (f : Fin 7) :
+ let L := PairedChain.lengths s.h s.delta s.advice i
+ header ≤ starts s header counter f ∧
+ (starts s header counter f + fieldSize L N f ≤ LiveHeaderSchedule.limit s header ∨
+ counter ≤ starts s header counter f ∧ starts s header counter f + fieldSize L N f ≤ counter+N) := by
+ let L := PairedChain.lengths s.h s.delta s.advice i
+ have h₁ : L.leftCut ≤ (s.h+1)*s.delta := L.leftFit
+ have h₂ : L.rightCut ≤ (s.h+1)*s.delta := L.rightFit
+ rw [LiveHeaderSchedule.limit_eq] at hc ⊢
+ fin_cases f <;> simp only [starts,fieldSize,Matrix.cons_val_zero,Matrix.cons_val_one,Matrix.cons_val,
+ LiveHeaderSchedule.widthAddr,LiveHeaderSchedule.exteriorBase,
+ LiveHeaderSchedule.adviceBase,LiveHeaderSchedule.rightIndexBase,LiveHeaderSchedule.leftIndexBase,
+ LiveHeaderSchedule.populationAddr,LiveHeaderSchedule.highAddr,LiveHeaderSchedule.indexBase,
+ LiveHeaderSchedule.Sizes.capacity,Fin.reduceFinMk]
+ all_goals change _ ∧ (_ ∨ _ ∧ _)
+ all_goals dsimp only [L,PairedChain.lengths] at h₁ h₂ ⊢
+ all_goals omega
+
+variable (G : Group)
+
+/-- Natural base address of the live header workspace at the group geometry. -/
+abbrev headerBase := Layout.header.eval G.g
+/-- Natural base address of the auxiliary descriptor table at the group geometry. -/
+abbrev tableBase := (Layout.descriptor G.constants).eval G.g
+/-- Natural base address of the label-counter array at the group geometry. -/
+abbrev counterBase := (Layout.counter G.constants).eval G.g
+/-- Natural base address of the virtual RAM shadow at the group geometry. -/
+abbrev shadowBase := (Layout.shadow G.constants).eval G.g
+/-- Length of the nominated histogram, one word per grammar production. -/
+abbrev histLength := G.constants.grammarLabels.eval G.g
+
+theorem geometry_order :
+ Layout.stageTag.eval G.g < headerBase G ∧ headerBase G ≤ tableBase G ∧
+ tableBase G+21 = counterBase G ∧ counterBase G+histLength G ≤ shadowBase G := by
+ have hl : tableBase G = LiveHeaderSchedule.limit (sizes G) (headerBase G) := rfl
+ refine ⟨Nat.lt_succ_self _,?_,rfl,?_⟩
+ · rw [hl,LiveHeaderSchedule.limit_eq]; omega
+ · simp only [shadowBase,Layout.shadow,Layout.orderMap,Layout.packedPrefix,Layout.adviceFrames,
+ Layout.transitionScratch,Layout.newState,Layout.oldState,Constants.labels,eval_add,
+ counterBase,histLength]
+ omega
+
+/-- Motif counters follow the grammar counters in the same live array. -/
+theorem counter_end_le_shadow :
+ counterBase G + G.constants.labels.eval G.g ≤ shadowBase G := by
+ simp only [shadowBase,Layout.shadow,Layout.orderMap,Layout.packedPrefix,Layout.adviceFrames,
+ Layout.transitionScratch,Layout.newState,Layout.oldState,eval_add,counterBase]
+ omega
+
+/-- The untruncated public addresses used by all three preparation stages. -/
+theorem address_values (hs : shadowBase G < 2^G.w) :
+ G.addr.val = Layout.stageTag.eval G.g ∧ (desc G).val = tableBase G ∧
+ (counter G).val = counterBase G ∧ (shadow G).val = shadowBase G := by
+ obtain ⟨h₀,h₁,h₂,h₃⟩ := geometry_order G
+ exact ⟨Nat.mod_eq_of_lt (show Layout.stageTag.eval G.g < 2^G.w by omega),
+ Nat.mod_eq_of_lt (show tableBase G < 2^G.w by omega),Nat.mod_eq_of_lt (show counterBase G < 2^G.w by omega),
+ Nat.mod_eq_of_lt hs⟩
+
+private theorem source_cast (f : Fin 7) :
+ source G f = ((starts (sizes G) (headerBase G) (counterBase G) f : ℕ) : Word G.w) := by
+ fin_cases f <;> rfl
+
+private theorem offset_bound (L : PrimedInputRAM.Lengths) (N : ℕ) (j : Fin (populated L N)) :
+ let f := rangeAt L N j
+ j.val-rangeStart L N f.castSucc < fieldSize L N f := by
+ have h := rangeAt_bounds L N j
+ have endEq (f : Fin 7) : rangeStart L N f.castSucc + fieldSize L N f = rangeStart L N f.succ := by
+ fin_cases f <;> simp [rangeStart,fieldSize,LiveAuxiliaryHeaders.exteriorBase]
+ omega
+ rw [← endEq] at h
+ dsimp only; omega
+
+/-- An occupied source lies in the header output area or in the nominated
+counter array. It is above the stage tag and below the virtual shadow. -/
+theorem source_interval (i : Fin (2^(sizes G).h)) (N : ℕ) (hn : N = histLength G)
+ (hs : shadowBase G < 2^G.w) (j : Fin (populated (pairLengths G i) N)) :
+ let a := (sourceAddress (pairLengths G i) N (source G) j).val
+ headerBase G ≤ a ∧ (a < tableBase G ∨ counterBase G ≤ a ∧ a < counterBase G+N) := by
+ let L := pairLengths G i
+ let f := rangeAt L N j
+ let offset := j.val-rangeStart L N f.castSucc
+ let start := starts (sizes G) (headerBase G) (counterBase G) f
+ obtain ⟨_,ht,he,hshadow⟩ := geometry_order G
+ obtain ⟨hlo,hhi⟩ := interval (sizes G) (headerBase G) (counterBase G) N
+ (show tableBase G ≤ counterBase G by omega) i f
+ have hofs : offset < fieldSize L N f := offset_bound L N j
+ change headerBase G ≤ start at hlo
+ change start + fieldSize L N f ≤ tableBase G ∨ counterBase G ≤ start ∧ start + fieldSize L N f ≤ counterBase G+N at hhi
+ have hfit : start+offset < 2^G.w := by omega
+ have val : (sourceAddress L N (source G) j).val = start+offset := by
+ change (source G f + (offset : Word G.w)).val = _
+ rw [source_cast,← Nat.cast_add,Fin.val_natCast,Nat.mod_eq_of_lt hfit]
+ dsimp only
+ rw [val]
+ omega
+
+/-- Address conditions for the selected auxiliary pair and histogram length. The sparse
+descriptor, source, and shadow areas satisfy the copy routine’s separation conditions and
+avoid the stage tag. -/
+structure GeometryAreas (i : Fin (2^(sizes G).h)) (N : ℕ) : Prop where
+ areas : Areas (desc G) (shadow G) (pairLengths G i) N (source G)
+ tagDesc : ∀ j f, (LiveHeaderCopyDispatch.address (desc G) j f).val ≠ G.addr.val
+ tagSource : ∀ j, (sourceAddress (pairLengths G i) N (source G) j).val ≠ G.addr.val
+ tagShadow : G.addr.val < (shadow G).val
+
+/-- A single bound on the occupied prefix of the virtual shadow discharges
+all source, descriptor, stage-tag and destination separation conditions. -/
+theorem geometry (i : Fin (2^(sizes G).h)) (N : ℕ) (hn : N = histLength G)
+ (room : shadowBase G + span (pairLengths G i) N ≤ 2^G.w) : GeometryAreas G i N := by
+ let L := pairLengths G i
+ have spanPos : 0 < span L N := by simp [span,Header.count]
+ have occupied : populated L N ≤ span L N := by
+ have := L.leftFit
+ have := L.rightFit
+ change 3+2*L.index+L.advice+L.leftCut+L.rightCut+N ≤ 3+2*L.index+L.advice+2*L.cutCapacity+N
+ omega
+ have hs : shadowBase G < 2^G.w := by change shadowBase G+span L N ≤ _ at room; omega
+ obtain ⟨h₀,h₁,h₂,h₃⟩ := geometry_order G
+ have descVal : (desc G).val = tableBase G := Nat.mod_eq_of_lt (show tableBase G < 2^G.w by omega)
+ have shadowVal : (shadow G).val = shadowBase G := Nat.mod_eq_of_lt hs
+ have tagVal : G.addr.val = Layout.stageTag.eval G.g := Nat.mod_eq_of_lt (show Layout.stageTag.eval G.g < 2^G.w by omega)
+ have tableFit : (desc G).val+21 ≤ 2^G.w := by omega
+ have shadowFit : (shadow G).val+span L N ≤ 2^G.w := shadowVal.symm ▸ room
+ have hdesc (j : Fin 7) (f : Fin 3) :
+ (LiveHeaderCopyDispatch.address (desc G) j f).val = tableBase G+(3*j.val+f.val) := by
+ rw [LiveAuxiliaryDescriptorInit.address_val _ tableFit, descVal]
+ have src := source_interval G i N hn hs
+ refine ⟨⟨tableFit,shadowFit,?_,?_,Or.inl (by omega),?_,?_⟩,?_,?_,by omega⟩
+ · change populated L N < 2^G.w
+ change shadowBase G+span L N ≤ 2^G.w at room
+ omega
+ · intro j
+ obtain ⟨_, ha | ⟨ha,_⟩⟩ := src j <;> omega
+ · intro j k
+ change _ ≠ (shadow G).val + (sparseOffset L N k).val
+ obtain ⟨_, ha | ⟨_,ha⟩⟩ := src j <;> omega
+ · intro j f k
+ change _ ≠ (shadow G).val + (sparseOffset L N k).val
+ rw [hdesc]
+ have := j.isLt; have := f.isLt; omega
+ · intro j f; rw [hdesc,tagVal]; omega
+ · intro j; obtain ⟨lo,_⟩ := src j; omega
+
+/-- The fixed expression for the reserved virtual header size has no group
+dependence. Only the populated subset varies with the exterior cuts. -/
+def headerSpan (c : Constants) : PublicExpr :=
+ 3 + 2*(c.lengths.h+2) + c.lengths.advice + 2*((c.lengths.h+1)*c.lengths.delta) + c.grammarLabels
+
+theorem headerSpan_eval (i : Fin (2^(sizes G).h)) :
+ (headerSpan G.constants).eval G.g = span (pairLengths G i) (histLength G) := rfl
+
+theorem headerSpan_sitePowers (c : Constants) : (headerSpan c).SitePowers := by
+ have hh := c.lengths_h_sitePowers
+ have hd := c.lengths_delta_sitePowers
+ have ha := c.lengths_advice_sitePowers
+ have ht := c.grammarLabels_sitePowers
+ unfold headerSpan
+ repeat' first | assumption | exact True.intro | constructor
+
+/-- The threshold for disjoint word addresses is uniform over all first-half
+groups, the evaluator and the actual contents of the external arrays. -/
+theorem eventually_geometry (c : Constants) {B : ℕ} (hB : 1 ≤ B) {H : ℕ → ℕ} (hH : PolynomiallyBounded H) :
+ ∀ᶠ n in Filter.atTop, ∀ G : Group, G.constants = c → G.g = paperGeometry B H n →
+ ∀ i, GeometryAreas G i (histLength G) := by
+ have h : ((Layout.shadow c) + headerSpan c).SitePowers := ⟨Layout.shadow_sitePowers c,headerSpan_sitePowers c⟩
+ filter_upwards [(h.fits hB hH).2] with n hf G hc hg i
+ have enough : (Layout.shadow c).eval (paperGeometry B H n) + (headerSpan c).eval (paperGeometry B H n) <
+ 2^(paperGeometry B H n).w := hf.1
+ rw [← hc,← hg] at enough
+ exact geometry G i (histLength G) rfl ((headerSpan_eval G i) ▸ enough.le)
+
+/-- The same address fit discharges the histogram region conditions of the
+preceding nomination stage. -/
+theorem nominationFits (i : Fin (2^(sizes G).h))
+ (room : shadowBase G + span (pairLengths G i) (histLength G) ≤ 2^G.w)
+ (hb : 2*G.g.d ≤ G.w) (hf : 5*(2*G.g.d)+15 ≤ G.clockAt Stage.nominations) : Nominations.Fits G := by
+ have pos : 0 < span (pairLengths G i) (histLength G) := by simp [span,Header.count]
+ obtain ⟨ht,hh,hd,hc⟩ := geometry_order G
+ have hs : shadowBase G < 2^G.w := by omega
+ have tag : G.addr.val = Layout.stageTag.eval G.g := Nat.mod_eq_of_lt (show Layout.stageTag.eval G.g < 2^G.w by omega)
+ have base : (Nominations.base G).val = counterBase G := Nat.mod_eq_of_lt (show counterBase G < 2^G.w by omega)
+ refine ⟨hb,?_,hf,?_,Or.inl ?_⟩
+ · change histLength G < 2^G.w; omega
+ · change (Nominations.base G).val+histLength G ≤ 2^G.w; omega
+ · omega
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairAuxiliary.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairAuxiliary.lean
new file mode 100644
index 0000000000..02cdd3ea6b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairAuxiliary.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.LiveProgramPairStages
+import OAI.Computability.VPVNP.PairedChain
+
+/-! # The public operands of the two sparse-header preparation stages -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+open BurstRAM PrimedInputRAM LiveAuxiliaryHeaders
+open scoped Fin.CommRing
+
+variable (G : Group)
+
+/-- Live header sizes obtained by evaluating the fixed length expressions at the group
+geometry. -/
+abbrev sizes := G.constants.lengths.eval G.g
+/-- Auxiliary input-field lengths for the chosen first-half pair, determined by its index and
+the live chain, cut, and advice sizes. -/
+abbrev pairLengths (i : Fin (2^(sizes G).h)) :=
+ PairedChain.lengths (sizes G).h (sizes G).delta (sizes G).advice i
+
+/-- Descriptor table’s base address encoded at the RAM word width. -/
+abbrev desc := Pieces.word G.g G.lit (.geometry (Layout.descriptor G.constants))
+/-- Virtual shadow’s base address encoded at the RAM word width. -/
+abbrev shadow := Pieces.word G.g G.lit (.geometry (Layout.shadow G.constants))
+/-- Label-counter array’s base address encoded at the RAM word width. -/
+abbrev counter := Pieces.word G.g G.lit (.geometry (Layout.counter G.constants))
+
+/-- The seven physical source addresses from which the auxiliary header copy reads its fields
+and nominated counts. -/
+abbrev source := LiveAuxiliaryStages.headerSources (sizes G) (Layout.header.eval G.g) (counter G)
+
+/-- Every public operand of the initializer agrees with the concrete sparse
+header geometry, including its array of seven physical source addresses. -/
+theorem init_data (i : Fin (2^(sizes G).h)) (hist : List (Word G.w))
+ (hlen : hist.length = G.constants.grammarLabels.eval G.g) :
+ Pieces.word G.g G.lit ∘ InputOperand.geometry ∘ StageOperands.auxiliary G.constants =
+ initData (pairLengths G i) hist.length (shadow G) (desc G) (source G) := by
+ rw [hlen]
+ funext j
+ fin_cases j <;> rfl
+
+/-- The guarded copy reads its end cursor from the final descriptor. -/
+theorem copy_data :
+ Pieces.word G.g G.lit ∘ InputOperand.geometry ∘ StageOperands.auxiliaryCopy G.constants =
+ LiveAuxiliaryStages.copyData (desc G) := by
+ funext j
+ fin_cases j
+ · rfl
+ · rw [LiveAuxiliaryStages.copyData]
+ change Fin.ofNat _ ((Layout.descriptor G.constants).eval G.g + 18) =
+ LiveHeaderCopyDispatch.address (desc G) 6 0
+ rw [LiveAuxiliaryStages.copy_endAddress]
+ exact Nat.cast_add (R := Word G.w) _ _
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairCopy.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairCopy.lean
new file mode 100644
index 0000000000..398085f8df
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairCopy.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.LiveProgramPairAuxiliary
+import OAI.Computability.VPVNP.LiveProgramPairDeterministic
+import OAI.Computability.VPVNP.LiveAuxiliaryGuardedCopy
+
+/-! # The linked sparse-copy stage and the memory passed to the compressed pair -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM LiveStageLink
+open LiveAuxiliaryHeaders
+
+variable {G : Group} {i : Fin (2^(sizes G).h)} {m : Memory G.w}
+ {hdr : Header (pairLengths G i) → Bool} {hist : List (Word G.w)}
+
+theorem copied (areas : Areas (desc G) (shadow G) (pairLengths G i) hist.length (source G))
+ (prepared : Prepared (desc G) (shadow G).val (pairLengths G i) hdr hist (source G) m)
+ (fresh : ∀ a < span (pairLengths G i) hist.length, m ((shadow G).val+a) = 0)
+ (tagBefore : G.addr.val < (shadow G).val)
+ (clock : 71 ≤ G.clockAt Stage.auxiliaryCopy) (tag : G.tagged Stage.auxiliaryCopy m) :
+ ∃ A : Indexed G Stage.auxiliaryCopy m Unit,
+ (∀ a < span (pairLengths G i) hist.length, A.memory () ((shadow G).val+a) = headerMemory (pairLengths G i) hdr hist a) ∧
+ (∀ a, a ≠ G.addr.val → (a < (shadow G).val ∨ (shadow G).val+span (pairLengths G i) hist.length ≤ a) →
+ A.memory () a = m a) ∧
+ (A.logs ()).length = populated (pairLengths G i) hist.length + 1 ∧
+ ∀ r ∈ A.logs (), r.probes ≤ 14 := by
+ let L := pairLengths G i
+ let N := populated L hist.length
+ let f := G.clockAt Stage.auxiliaryCopy
+ let P := Pieces.component G.components Stage.auxiliaryCopy G.g G.lit
+ obtain ⟨active,closed,hg,hh,hm,hlen,hactive,hclose,hprobe,_,frame⟩ :=
+ LiveAuxiliaryStages.guarded_copy_native areas.shadowFit areas.countFit areas.separated f
+ (show 68 ≤ _ by omega) G.addr (Or.inl tagBefore) prepared
+ let rs := active ++ [closed]
+ have hr : runSegment P f (some 0) m (List.replicate (N+1) []) = some rs := by
+ change runSegment (LiveAuxiliaryStages.copy.instantiate G.w
+ (Pieces.word G.g G.lit ∘ InputOperand.geometry ∘ StageOperands.auxiliaryCopy G.constants)).program _ _ _ _ = _
+ rw [copy_data]
+ exact hg
+ have bounds (r : Report G.w) (hr : r ∈ rs) : r.events.length < 68 ∧ r.probes ≤ 12 := by
+ rcases List.mem_append.mp hr with ha | hc
+ · exact ⟨(hactive r ha).1,(hactive r ha).2.1⟩
+ · obtain rfl := List.mem_singleton.mp hc; omega
+ have fit (r : Report G.w) (hr : r ∈ rs) : room G.nextStage G.addr Stage.auxiliaryCopy f r := by
+ obtain ⟨hb,_⟩ := bounds r hr
+ cases r with
+ | mk es result =>
+ cases result with
+ | none =>
+ change (es ++ transferEvents G.addr Stage.pair).length < f
+ rw [List.length_append]; change es.length + 3 < _
+ change es.length < _ at hb
+ dsimp [f]; omega
+ | some st =>
+ change es.length < _
+ change es.length < _ at hb
+ dsimp [f]; omega
+ let A := deterministicIndexed tag hr hh fit frame
+ have hrep : ordinaryReports (A.traces ()) = rs := deterministic_reports ..
+ have hout : A.memory () = writeMemory (install (shadow G).val L hdr hist areas.shadowFit m)
+ G.addr (tagWord G.w Stage.pair) := by
+ change transferMemory G.addr _ (after m (eventLog (ordinaryReports (A.traces ())))) = _
+ rw [hrep,hm]
+ rfl
+ refine ⟨A,?_,?_,?_,?_⟩
+ · intro a ha
+ rw [hout,writeMemory,ite_eq_right (show (shadow G).val+a ≠ G.addr.val by omega)]
+ exact install_read _ _ _ _ _ _ _ (fresh _ ha)
+ · intro a ha houtside; rw [hout,writeMemory,ite_eq_right ha]
+ exact install_outside _ _ _ _ _ _ _ houtside
+ · simp [Indexed.logs,hrep,rs,hlen]
+ · intro r hr
+ rw [Indexed.logs,hrep,List.mem_map] at hr
+ obtain ⟨r,hin,rfl⟩ := hr
+ rw [linkedReport_probes]
+ have h := (bounds _ hin).2
+ split <;> omega
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairCount.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairCount.lean
new file mode 100644
index 0000000000..3c3e784e6e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairCount.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.LiveProgramPair
+import OAI.Computability.VPVNP.LiveProgramPairExponent
+import OAI.Computability.VPVNP.RAMFinite
+
+/-! # The contribution of the native first-half stage sequence
+
+Once the header has accepted its fields, the four completed stages expose
+the histogram and compressed computation. The terminal native test compares
+the physical counters and both incident exponent fields. Resource bounds
+apply to the joined reports, including the earlier header and router.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Chronology
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink LiveExponent ChainAssignments ExponentTrace
+open scoped Classical
+
+variable {G : Group} {m : Memory G.w} {h Δ t Z : ℕ}
+ {Nom : Type*} [Fintype Nom]
+ {Path : ExponentTrace.Exterior h Δ → Fin (2^h) → Nom → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+
+/-- The native branch following the header contributes the paper's local
+`pairCount` on the outgoing mode and padding test. Each stage is classified
+by its own traces, preserving coincident branches as distinct paths. -/
+theorem count (fit : 1+t*Z ≤ Δ) (fst : LiveBits h Δ) (i : Fin (2^h))
+ (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+ (A : Chronology G m Nom (Path (exteriorOf fit fst) i))
+ (L : BufferLayout G.exponentPub t Z) (hZ : 0 < Z) (hw : 2 ≤ G.w)
+ (hf : 31 ≤ G.clockAt Stage.exponents) (fresh : ∀ a : Fin t, counterAddr G.exponentPub a ≠ G.addr)
+ (data : ∀ μ q, BufferValues G.exponentPub (counters fit fst i.castSucc) (counters fit fst i.succ)
+ ((A.pair μ).memory q))
+ (read : ∀ μ q a, (((A.pair μ).memory q) (counterAddr G.exponentPub a).val).val = inc (exteriorOf fit fst) i μ q a)
+ (small : ∀ μ q a, inc (exteriorOf fit fst) i μ q a+1 < 2^G.w)
+ (cap : List (Report G.w) → Prop) (maxCalls : ℕ)
+ (hbound : ∀ rs, cap rs → RAMBuckets.cost Report.probes rs ≤ maxCalls)
+ (enough : ∀ μ q, cap (A.prefixLogs μ q ++
+ (stageReports G.exponentPub t Z ((A.pair μ).memory q)).map
+ (linkedReport G.nextStage G.addr Stage.exponents))) :
+ (if pairFormat fit fst i then Nat.card (ActualPaths G.P G.clock 0 m cap) else 0) =
+ pairCount fit inc fst i := by
+ let Tail (μ : Nom) (q : Path (exteriorOf fit fst) i μ) :=
+ ActualPaths G.P G.clock 0 ((A.pair μ).memory q) (fun rs => cap (A.prefixLogs μ q ++ rs))
+ have (μ : Nom) (q : Path (exteriorOf fit fst) i μ) : Finite (Tail μ q) := by
+ apply finite_actualPaths (maxCalls := maxCalls)
+ intro rs hr
+ have h := hbound _ hr
+ rw [RAMBuckets.cost_append] at h
+ omega
+ unfold pairCount
+ dsimp only
+ by_cases good : pairFormat fit fst i
+ · rw [ite_eq_left good, ← Nat.card_congr (A.paths cap), Nat.card_sigma]
+ apply Finset.sum_congr rfl
+ intro μ _
+ rw [Nat.card_sigma]
+ apply Finset.sum_congr rfl
+ intro q _
+ let last := (A.pair μ).memory q
+ let v := fun a : Fin t => last (counterAddr G.exponentPub a).val
+ have htag : G.tagged Stage.exponents last := (A.pair μ).tagged_memory rfl q
+ have h := G.exponent_count L hZ hw hf fresh last htag _ _ (data μ q) v (fun _ => rfl)
+ (fun a => (read μ q a) ▸ small μ q a) (fun rs => cap (A.prefixLogs μ q ++ rs))
+ rw [h]
+ simp only [enough, and_true,v,last,read,firstCheck_iff,good,true_and]
+ · simp [good,firstCheck_iff]
+
+end LiveProgram.PairStages.Group.Chronology
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairDeterministic.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairDeterministic.lean
new file mode 100644
index 0000000000..76daf6d370
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairDeterministic.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.LiveProgramTerminalStage
+
+/-!
+# Indexing a deterministic stage by its verified empty-choice execution
+
+The invariant consists of the unconsumed part of the verified run. Exact
+use of the input choices implies that every other accepted path begins
+with the same calls and reports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink
+open scoped Classical
+
+variable {G : Group} {s : Stage} {m : Memory G.w} {calls : ℕ} {rs : List (Report G.w)}
+
+private def HasTail (G : Group) (s : Stage) (st : Word G.w) (mem : Memory G.w) : Prop :=
+ ∃ n logs, runSegment (sourceProgram G.T G.pub s) (G.clockAt s) (some st) mem (List.replicate n []) = some logs ∧
+ endState (some st) logs = none ∧ PreservesTagOnReturns G.addr mem logs
+
+private theorem tail_frame (G : Group) (s : Stage) : TagFrame G.T G.pub G.addr s (G.clockAt s) (HasTail G s) := by
+ rintro st mem bits rep st' ⟨n,logs,run,halt,frame⟩ tag call cont
+ cases n with
+ | zero =>
+ simp only [List.replicate_zero,runSegment,Option.some.injEq] at run
+ subst logs; contradiction
+ | succ n =>
+ rw [List.replicate_succ,runSegment] at run
+ cases h : execute (sourceProgram G.T G.pub s) (G.clockAt s) ((sourceProgram G.T G.pub s).start st) mem [] with
+ | none => simp [h] at run
+ | some r =>
+ obtain ⟨rfl,rfl⟩ := execute_empty_forces h call
+ simp only [h,Option.map_eq_some_iff] at run
+ obtain ⟨rest,hrest,rfl⟩ := run
+ refine ⟨⟨n,rest,?_,?_,frame.2⟩,(frame.1 (by simp [cont])).trans tag⟩
+ · simpa only [cont] using hrest
+ · change endState rep.result rest = none at halt
+ simpa only [cont] using halt
+
+/-- Index a deterministic stage by the unique unit value when its verified all-empty-choice
+segment terminates, fits the linked clock, and preserves the tag on returns. -/
+noncomputable def deterministicIndexed (tag : G.tagged s m)
+ (run : runSegment (Pieces.component G.components s G.g G.lit) (G.clockAt s) (some 0) m
+ (List.replicate calls []) = some rs)
+ (halt : endState (some 0) rs = none)
+ (fits : ∀ r ∈ rs, room G.nextStage G.addr s (G.clockAt s) r)
+ (frame : PreservesTagOnReturns G.addr m rs) : Indexed G s m Unit := by
+ have hsrc := (component_segment G s (G.clockAt s) (some 0) m (List.replicate calls [])).trans run
+ let one : G.StagePaths s m := ⟨List.replicate calls [],rs,hsrc,halt,fits⟩
+ refine ⟨⟨HasTail G s,tail_frame G s,⟨calls,rs,hsrc,halt,frame⟩,tag⟩,
+ ⟨fun _ => one,fun _ => (),by intro u; cases u; rfl,?_⟩⟩
+ intro p
+ obtain ⟨logs,hr,hh,_⟩ := p.property
+ obtain ⟨bs,tail,eq,_,runTail⟩ := split_empty_segment hsrc hr hh
+ rw [halt] at runTail
+ cases bs with
+ | nil => exact Subtype.ext (by simpa only [List.append_nil] using eq.symm)
+ | cons _ _ => contradiction
+
+/-- Replaying the unique stage path returns the original, concrete reports. -/
+theorem deterministic_reports (tag : G.tagged s m)
+ (run : runSegment (Pieces.component G.components s G.g G.lit) (G.clockAt s) (some 0) m
+ (List.replicate calls []) = some rs)
+ (halt : endState (some 0) rs = none)
+ (fits : ∀ r ∈ rs, room G.nextStage G.addr s (G.clockAt s) r)
+ (frame : PreservesTagOnReturns G.addr m rs) :
+ ordinaryReports ((deterministicIndexed tag run halt fits frame).traces ()) = rs := by
+ apply Option.some.inj
+ exact (ordinaryRun ((deterministicIndexed tag run halt fits frame).traces ())).symm.trans
+ ((component_segment G s (G.clockAt s) (some 0) m _).trans run)
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairExponent.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairExponent.lean
new file mode 100644
index 0000000000..2d4949f92c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairExponent.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.LiveProgramTerminalStage
+import OAI.Computability.VPVNP.LiveExponentOperands
+import OAI.Computability.VPVNP.LivePairExponentCount
+
+/-! # The terminal exponent test in the linked first-half group
+
+Its ordinary digit calls write only to the addressed counter word. The outer
+dispatcher therefore continues to read the exponent-stage tag. All physical
+dispatch probes occur in the capped count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink LiveExponent
+open scoped Classical
+
+variable (G : Group) {t Z : ℕ}
+
+/-- The exponent-check stage’s public operand words evaluated at this group’s constants and
+geometry. -/
+abbrev exponentPub := ExponentStage.words G.constants G.g
+
+theorem exponent_frame (L : BufferLayout G.exponentPub t Z) (hZ : 0 < Z)
+ (hf : 31 ≤ G.clockAt Stage.exponents)
+ (fresh : ∀ a : Fin t, counterAddr G.exponentPub a ≠ G.addr) :
+ TagFrame G.T G.pub G.addr Stage.exponents (G.clockAt Stage.exponents)
+ (fun s _ => s ≤ G.exponentPub 4) := by
+ intro s mem bits rep s' hstate htag hc hret
+ have hx := (Pieces.component_eq G.components G.g G.lit Stage.exponents (G.clockAt Stage.exponents)
+ s mem bits).symm.trans hc
+ change execute (digitTemplate.instantiate G.w G.exponentPub).program (G.clockAt Stage.exponents)
+ ((digitTemplate.instantiate G.w G.exponentPub).program.start s) mem bits = some rep at hx
+ let f := G.clockAt Stage.exponents - 31
+ have htime : G.clockAt Stage.exponents = f+31 := (Nat.sub_add_cancel hf).symm
+ rw [htime] at hx
+ rcases lt_or_eq_of_le hstate with hs | he
+ · have hrep := (data_result hs hx).2
+ have hs' : s' = s+1 := Option.some.inj (hret.symm.trans (congrArg Report.result hrep))
+ have hnext : (s+1).val = s.val+1 := Fin.val_add_one_of_lt' (by have ht := (G.exponentPub 4).isLt; change s.val < (G.exponentPub 4).val at hs; omega)
+ change s.val < (G.exponentPub 4).val at hs
+ have hd : s.val / Z < t := (Nat.div_lt_iff_lt_mul hZ).mpr (L.size ▸ hs)
+ let a : Fin t := ⟨s.val / Z,hd⟩
+ have haddr : carryAddress G.exponentPub s = counterAddr G.exponentPub a := by
+ unfold carryAddress counterAddr
+ congr 1
+ change Fin.ofNat _ (s.val / (G.exponentPub 3).val) = _
+ rw [L.width]
+ refine ⟨by change s'.val ≤ _; rw [hs',hnext]; omega,?_⟩
+ rw [hrep,digitReport_after,haddr]
+ change (if G.addr.val = (counterAddr G.exponentPub a).val then _ else _) = _
+ rw [ite_eq_right (fun h => fresh a (Fin.ext h.symm))]
+ exact htag
+ · rw [show f+31=(f+26)+5 by omega,execute_done _ _ _ _ _ he] at hx
+ split at hx
+ · have := congrArg Report.result (Option.some.inj hx)
+ simp_all
+ · contradiction
+
+/-- At a physically tagged exponent entry the linked count is either one or
+zero. The test includes the cap on the reports of all preceding stages. -/
+theorem exponent_count (L : BufferLayout G.exponentPub t Z) (hZ : 0 < Z) (hw : 2 ≤ G.w)
+ (hf : 31 ≤ G.clockAt Stage.exponents) (fresh : ∀ a : Fin t, counterAddr G.exponentPub a ≠ G.addr)
+ (m : Memory G.w) (tag : G.tagged Stage.exponents m)
+ (x y : Fin t → Word Z) (v : BufferValues G.exponentPub x y m) (inc : Fin t → Word G.w)
+ (read : ∀ a, m (counterAddr G.exponentPub a).val = inc a) (small : ∀ a, (inc a).val+1 < 2^G.w)
+ (cap : List (Report G.w) → Prop) :
+ Nat.card (ActualPaths G.P G.clock 0 m cap) =
+ if (∀ a, (y a).val = (x a).val+(inc a).val) ∧
+ cap ((stageReports G.exponentPub t Z m).map (linkedReport G.nextStage G.addr Stage.exponents))
+ then 1 else 0 := by
+ let entry : Entry G Stage.exponents m := ⟨_,G.exponent_frame L hZ hf fresh,Fin.zero_le _,tag⟩
+ rw [← Nat.card_congr (terminalEquiv entry (by rfl) cap)]
+ change Nat.card (ActualPaths (digitTemplate.instantiate G.w G.exponentPub).program (G.clockAt Stage.exponents)
+ 0 m (fun rs => cap (rs.map (linkedReport G.nextStage G.addr Stage.exponents)))) = _
+ rw [show G.clockAt Stage.exponents = G.clockAt Stage.exponents-31+31 by omega]
+ exact pathCount L hZ hw v inc read small _ _
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairInitialize.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairInitialize.lean
new file mode 100644
index 0000000000..37be41bda9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairInitialize.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.LiveProgramPairAuxiliary
+import OAI.Computability.VPVNP.LiveProgramPairDeterministic
+import OAI.Computability.VPVNP.LiveAuxiliaryGuardedCopy
+
+/-! # Initializing the seven sparse auxiliary header descriptors in the linked group -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM LiveStageLink
+open LiveAuxiliaryHeaders LiveHeaderCopyDispatch
+open scoped Fin.CommRing
+
+variable {G : Group} {i : Fin (2^(sizes G).h)} {m : Memory G.w}
+ {hdr : Header (pairLengths G i) → Bool} {hist : List (Word G.w)}
+
+/-- The actual initializer has one choice-free path and passes the descriptor
+and source arrays intact to the next tag. Only its descriptor words and the
+linker's tag are modified. -/
+theorem initialized (hlen : hist.length = G.constants.grammarLabels.eval G.g)
+ (areas : Areas (desc G) (shadow G) (pairLengths G i) hist.length (source G))
+ (inputs : InputArrays (pairLengths G i) hdr hist (source G) m)
+ (td : ∀ j f, (address (desc G) j f).val ≠ G.addr.val)
+ (ts : ∀ j, (sourceAddress (pairLengths G i) hist.length (source G) j).val ≠ G.addr.val)
+ (clock : 82 ≤ G.clockAt Stage.auxiliaryInit) (tag : G.tagged Stage.auxiliaryInit m) :
+ ∃ A : Indexed G Stage.auxiliaryInit m Unit,
+ Prepared (desc G) (shadow G).val (pairLengths G i) hdr hist (source G) (A.memory ()) ∧
+ (∀ a, a ≠ G.addr.val → (a < (desc G).val ∨ (desc G).val+21 ≤ a) → A.memory () a = m a) ∧
+ (A.logs ()).length = 1 ∧ ∀ r ∈ A.logs (), r.probes = 25 := by
+ let L := pairLengths G i
+ let N := hist.length
+ let src := source G
+ let table := desc G
+ let sh := shadow G
+ have hleft : m (src 0).val = (L.leftCut : Word G.w) := by simpa [cutLength] using inputs.lengths 0
+ have hright : m (src 0+2).val = (L.rightCut : Word G.w) := by simpa [cutLength] using inputs.lengths 2
+ obtain ⟨es,hr,descOK,outside,hl,hp,_⟩ :=
+ LiveAuxiliaryDescriptorInit.init_native L N sh table (src 0) src 0 m areas.tableFit hleft hright
+ let rep : Report G.w := ⟨es,none⟩
+ let f := G.clockAt Stage.auxiliaryInit
+ have hcall : execute (Pieces.component G.components Stage.auxiliaryInit G.g G.lit) f
+ ((Pieces.component G.components Stage.auxiliaryInit G.g G.lit).start 0) m [] = some rep := by
+ change execute ((initTable.instantiate G.w
+ (Pieces.word G.g G.lit ∘ InputOperand.geometry ∘ StageOperands.auxiliary G.constants)).program) f
+ (((initTable.instantiate G.w
+ (Pieces.word G.g G.lit ∘ InputOperand.geometry ∘ StageOperands.auxiliary G.constants)).program).start 0) m [] = _
+ rw [init_data G i hist hlen]
+ change execute ((LiveOneShot.oneShot (PrimedStackRAM.template LiveAuxiliaryDescriptorInit.ops 27)).instantiate G.w
+ (initData L N sh table src)).program f ((LiveAuxiliaryDescriptorInit.program L N sh table (src 0) src).start 0) m [] = _
+ rw [LiveOneShot.execute_oneShot]
+ have hbig := execute_extend hr (f-79)
+ have he : 79+(f-79) = f := by dsimp [f]; omega
+ rw [he] at hbig
+ exact congrArg (Option.map fun t : Report G.w => (⟨t.events,none⟩ : Report G.w)) hbig
+ have run : runSegment (Pieces.component G.components Stage.auxiliaryInit G.g G.lit) f (some 0) m
+ (List.replicate 1 []) = some [rep] := by simp [runSegment,hcall]
+ have fit : ∀ r ∈ [rep], room G.nextStage G.addr Stage.auxiliaryInit f r := by
+ intro r hr
+ obtain rfl := List.mem_singleton.mp hr
+ change (es ++ transferEvents G.addr Stage.auxiliaryCopy).length < f
+ rw [List.length_append,hl]
+ change 78+3 < _
+ dsimp [f]; omega
+ let A := deterministicIndexed tag run (show endState (some 0) [rep] = none from rfl) fit
+ (PreservesTagOnReturns.singleton_accept G.addr m rep rfl)
+ have hrep : ordinaryReports (A.traces ()) = [rep] := deterministic_reports ..
+ have hm : A.memory () = writeMemory (after m es) G.addr (tagWord G.w Stage.auxiliaryCopy) := by
+ change transferMemory G.addr _ (after m (eventLog (ordinaryReports (A.traces ())))) = _
+ rw [hrep]
+ change writeMemory (after m (es ++ [])) G.addr (tagWord G.w Stage.auxiliaryCopy) = _
+ rw [List.append_nil]
+ have pre : Prepared table sh.val L hdr hist src (after m es) := by
+ refine ⟨descOK,fun j => ?_⟩
+ rw [outside _ (areas.sourcesTable j)]
+ exact inputs.read j
+ refine ⟨A,?_,?_,?_,?_⟩
+ · rw [hm]
+ constructor
+ · exact ⟨fun j => by simpa only [writeMemory,ite_eq_right (td j 0)] using pre.descriptors.ends j,
+ fun j => by simpa only [writeMemory,ite_eq_right (td j 1)] using pre.descriptors.sources j,
+ fun j => by simpa only [writeMemory,ite_eq_right (td j 2)] using pre.descriptors.targets j⟩
+ · intro j; simpa only [writeMemory,ite_eq_right (ts j)] using pre.sources j
+ · intro a ha hd; rw [hm,writeMemory,ite_eq_right ha]; exact outside _ hd
+ · simp [Indexed.logs,hrep]
+ · intro r hr
+ rw [Indexed.logs,hrep,List.map_singleton,List.mem_singleton] at hr
+ rw [hr,linkedReport_probes]
+ change countProbes es + 1 + 1 = 25
+ omega
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairNominationOrder.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairNominationOrder.lean
new file mode 100644
index 0000000000..1bfd9ada90
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairNominationOrder.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.LiveProgramPairPreparation
+import OAI.Computability.VPVNP.PrimedCounterTranscriptCountLabels
+
+/-! # The live nomination order and the auxiliary machine's initial memory -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+open BurstRAM PrimedInputRAM PrimedCounter PrimedStackRAM
+
+variable (G : Group)
+
+/-- Concrete grammar state count used when interpreting the live histogram, `n^(circuitExponent
++ 5)`. -/
+abbrev states := G.g.n^(G.constants.circuitExponent+5)
+/-- Formal nomination assigning a count of width twice the site-address width to each grammar
+production over the group’s state set. -/
+abbrev FormalNom := GrammarDiagonal.Nomination G.g.n G.g.n (2*G.g.d) (Fin (states G))
+
+/-- Lexicographic production positions in the grammar are exactly the
+positions of the dense array guessed by the live nomination stage. -/
+noncomputable def order : GrammarLabel (Fin G.g.n × Bool) (Fin (states G)) G.g.n ≃ Fin (histLength G) :=
+ (labelIndex G.g.n G.g.n (states G)).trans
+ (finCongr (G.constants.grammarLabels_eq G.g).symm)
+
+/-- Relabel the dense live nomination array by the grammar’s lexicographic production order,
+preserving every count word. -/
+noncomputable def nominationEquiv : Nominations.Nom G ≃ FormalNom G :=
+ Equiv.arrowCongr (order G).symm (Equiv.refl _)
+
+variable {G} {i : Fin (2^(sizes G).h)} (Q : PrimedInputRAM.Layout (pairLengths G i) G.g.n G.g.d G.g.H G.w)
+ (degree : Fin G.g.n) (root : Fin (states G)) (hdr : Header (pairLengths G i) → Bool) (μ : Nominations.Nom G)
+
+theorem histogram_eq :
+ (Data.ofNomination Q degree root hdr (nominationEquiv G μ)).hist = histogram G μ := by
+ unfold Data.hist histogram
+ apply List.ext_getElem
+ · simp only [List.length_ofFn]
+ exact (G.constants.grammarLabels_eq G.g).symm
+ · intro k hk hk'
+ simp only [List.getElem_ofFn,Data.ofNomination_word]
+ change Fin.ofNat _ (μ ((order G) ((labelIndex _ _ _).symm _))).val = Fin.ofNat _ (μ _).val
+ rw [order,Equiv.trans_apply,Equiv.apply_symm_apply]
+ rfl
+
+/-- Every address of the actual auxiliary RAM, including unused addresses,
+has its prescribed value immediately after the linked copy stage. -/
+theorem shadow_initial {m : Memory G.w} {N : Indexed G Stage.nominations m (Nominations.Nom G)}
+ (B : PreparedBranch G m i hdr N μ) (a : ℕ) :
+ B.copy.memory () ((shadow G).val+a) = (Data.ofNomination Q degree root hdr (nominationEquiv G μ)).initial a := by
+ rw [B.shadowRead,Data.initial,histogram_eq]
+ rfl
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairPreparation.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairPreparation.lean
new file mode 100644
index 0000000000..9b9af2ec2c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairPreparation.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.LiveProgramPairAreas
+import OAI.Computability.VPVNP.LiveProgramPairInitialize
+import OAI.Computability.VPVNP.LiveProgramPairCopy
+import OAI.Computability.VPVNP.LiveHeaderAuxiliaryStored
+import OAI.Computability.VPVNP.LiveProgramPair
+
+/-!
+# The concrete native preparation of every first-half pair
+
+Starting with the recovered live header, the nominated production words
+stay in the live counter array. The initializer builds the descriptors and
+the copy stage prepares every auxiliary header address in the shadow.
+Unused shadow words have zero default. Header words below the descriptor
+table and counters below the shadow are preserved.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM BurstRAM.PrivateRAM LiveAuxiliaryHeaders PrimedInputRAM LiveStageLink
+open ChainAssignments CutSchedule ExponentTrace
+open scoped Fin.CommRing Classical
+
+variable {G : Group} {m : Memory G.w} {i : Fin (2^(sizes G).h)}
+
+/-- The packed histogram installed at the auxiliary machine's header addresses. -/
+def histogram (G : Group) (μ : Nominations.Nom G) : List (BurstRAM.Word G.w) :=
+ List.ofFn fun j => Fin.ofNat _ (μ j).val
+
+/-- Certificate of auxiliary initialization and copying after a particular nomination,
+including exact shadow contents, preserved header and counters, and bounds on native
+reports and probes. -/
+structure PreparedBranch (G : Group) (m : Memory G.w) (i : Fin (2^(sizes G).h))
+ (hdr : Header (pairLengths G i) → Bool) (N : Indexed G Stage.nominations m (Nominations.Nom G))
+ (μ : Nominations.Nom G) where
+ /-- Unit-indexed initializer starting from the memory reached by the chosen nomination. -/
+ init : Indexed G Stage.auxiliaryInit (N.memory μ) Unit
+ /-- Unit-indexed sparse copy starting from the initializer’s final memory. -/
+ copy : Indexed G Stage.auxiliaryCopy (init.memory ()) Unit
+ initInputs : InputArrays (pairLengths G i) hdr (histogram G μ) (source G) (N.memory μ)
+ copyPrepared : Prepared (desc G) (shadow G).val (pairLengths G i) hdr (histogram G μ) (source G) (init.memory ())
+ shadowRead : ∀ a, copy.memory () ((shadow G).val+a) = headerMemory (pairLengths G i) hdr (histogram G μ) a
+ headerFrame : ∀ a, headerBase G ≤ a → a < tableBase G → copy.memory () a = m a
+ counterFrame : ∀ a, counterBase G ≤ a → a < shadowBase G → copy.memory () a = N.memory μ a
+ initLength : (init.logs ()).length = 1
+ initProbes : ∀ r ∈ init.logs (), r.probes = 25
+ copyLength : (copy.logs ()).length = populated (pairLengths G i) (histLength G)+1
+ copyProbes : ∀ r ∈ copy.logs (), r.probes ≤ 14
+ descriptorFrame : ∀ j f, copy.memory () (LiveHeaderCopyDispatch.address (desc G) j f).val =
+ init.memory () (LiveHeaderCopyDispatch.address (desc G) j f).val
+
+/-- All required stage classifications before the compressed pair, with the
+correct memories and linked report costs. -/
+theorem prepare {hw : 4 ≤ G.w} {t Z : ℕ} {advice : Bits (sizes G).advice}
+ {cuts : AllCuts (sizes G).h (sizes G).delta} {mode : LiveHeader.Mode.Tag}
+ (out : LiveHeaderProgram.Output (sizes G) (headerBase G) G.g.d hw advice cuts
+ (halves (sizes G).h (.inl i)) mode m) (evalMode : mode ≠ .unit)
+ (he : (sizes G).e = t*Z) (fit : 1+t*Z ≤ (sizes G).delta)
+ (room : shadowBase G + span (pairLengths G i) (histLength G) ≤ 2^G.w)
+ (hb : 2*G.g.d ≤ G.w) (hn : 5*(2*G.g.d)+15 ≤ G.clockAt Stage.nominations)
+ (hi : 82 ≤ G.clockAt Stage.auxiliaryInit) (hc : 71 ≤ G.clockAt Stage.auxiliaryCopy)
+ (tag : G.tagged Stage.nominations m) (μ : Nominations.Nom G) :
+ let F := nominationFits G i room hb hn
+ let N := Nominations.indexed G F m tag
+ let ξ := exteriorOf fit (liveCutEquiv (sizes G).h (sizes G).delta cuts).1
+ Nonempty (PreparedBranch G m i (PairedChain.headers advice ξ i) N μ) := by
+ let F := nominationFits G i room hb hn
+ let N := Nominations.indexed G F m tag
+ let L := pairLengths G i
+ let hist := histogram G μ
+ let ξ := exteriorOf fit (liveCutEquiv (sizes G).h (sizes G).delta cuts).1
+ let hdr := PairedChain.headers advice ξ i
+ have hlen : hist.length = histLength G := by simp [hist,histogram]
+ have geometry := geometry G i hist.length hlen (hlen ▸ room)
+ obtain ⟨htag,hhead,htab,hcounters⟩ := geometry_order G
+ have hp : 0 < span (pairLengths G i) (histLength G) := by simp [span,Header.count]
+ have hs : shadowBase G < 2^G.w := by omega
+ obtain ⟨tagVal,descVal,counterVal,shadowVal⟩ := address_values G hs
+ have below : G.addr.val ≤ headerBase G := by omega
+ have hcounter : LiveHeaderSchedule.limit (sizes G) (headerBase G) ≤ (counter G).val := by
+ change tableBase G ≤ (counter G).val; omega
+ have inputs : InputArrays L hdr hist (source G) (N.memory μ) := by
+ rw [Nominations.memory_eq]
+ exact out.auxiliaryStoredInputArrays i evalMode he fit (counter G) F.address hcounter μ G.addr _ below
+ obtain ⟨I,ready,initFrame,initLen,initCost⟩ := initialized hlen geometry.areas inputs
+ geometry.tagDesc geometry.tagSource hi (N.tagged_memory rfl μ)
+ have storedZero := (out.nomination_frame (counter G) F.address hcounter μ).2
+ have nomFrame (a : ℕ) (ha : a ≠ G.addr.val) :
+ N.memory μ a = LiveNominations.stored (counter G) F.address μ m a := by
+ rw [Nominations.memory_eq]
+ exact ite_eq_right ha
+ have initZero (a : ℕ) : I.memory () ((shadow G).val+a) = 0 := by
+ have ht : (shadow G).val+a ≠ G.addr.val := by omega
+ rw [initFrame _ ht (Or.inr (by omega)),nomFrame _ ht]
+ exact storedZero _ (by change (counter G).val + histLength G ≤ _; omega)
+ obtain ⟨C,cs,cf,cl,cp⟩ := copied geometry.areas ready (fun a _ => initZero a) geometry.tagShadow hc
+ (I.tagged_memory rfl ())
+ refine ⟨⟨I,C,inputs,ready,?_,?_,?_,initLen,initCost,hlen ▸ cl,cp,?_⟩⟩
+ · intro a
+ by_cases ha : a < span (pairLengths G i) hist.length
+ · exact cs a ha
+ · rw [cf _ (by omega) (Or.inr (by omega)),initZero,headerMemory_past_end _ _ _ (Nat.le_of_not_gt ha)]
+ · intro a hlow hhigh
+ have ht : a ≠ G.addr.val := by omega
+ rw [cf _ ht (Or.inl (by omega)),initFrame _ ht (Or.inl (by omega)),nomFrame _ ht]
+ exact LiveNominations.stored_outside _ _ _ _ _ (Or.inl (by omega))
+ · intro a hlow hhigh
+ have ht : a ≠ G.addr.val := by omega
+ rw [cf _ ht (Or.inl (by omega)),initFrame _ ht (Or.inr (by omega))]
+ · intro j f
+ apply cf _ (geometry.tagDesc j f) (Or.inl ?_)
+ rw [LiveAuxiliaryDescriptorInit.address_val _ geometry.areas.tableFit, descVal, shadowVal]
+ have := j.isLt
+ have := f.isLt
+ omega
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPairStages.lean b/lean/OAI/Computability/VPVNP/LiveProgramPairStages.lean
new file mode 100644
index 0000000000..09fe4740fd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPairStages.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.LiveProgramSchedule
+import OAI.Computability.VPVNP.LiveDeterministicPaths
+
+/-! # Native first-half stage completions at a common group clock
+
+The dispatcher has a different length at each tag. Subtracting that length
+from one group clock gives the source clock of the selected stage. The
+continuation receives the actual transferred memory and the accumulated
+report cap, including the dispatch and transfer probes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages
+
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink
+open scoped Classical
+
+/-- A live group with its fixed components, physical geometry and literal prefix, common call
+clock, and bounds ensuring that stage tags and dispatch fit. -/
+structure Group where
+ /-- Fixed parameters for the grammar, motif labels, header capacities, and evaluator windows. -/
+ constants : Constants
+ /-- The universal evaluator program used in the group’s component table and stage
+ transitions. -/
+ evaluator : UniversalMachine.Program
+ /-- The pair instruction table mounted at the group’s pair stage. -/
+ pair : PairTable
+ /-- Physical input length, address width, bucket capacity, and RAM word width for the group. -/
+ g : Geometry
+ /-- Literal prefix whose packed value and length can supply public operands. -/
+ lit : LiteralPrefix
+ /-- Common fuel allowance for a linked group call, including outer dispatch. -/
+ clock : ℕ
+ tagFit : 21 ≤ 2^g.w
+ dispatchFit : 44 ≤ clock
+
+namespace Group
+
+variable (G : Group)
+
+/-- RAM word width of this group’s physical geometry. -/
+abbrev w := G.g.w
+/-- Component rows assembled from the fixed constants, evaluator program, and pair table. -/
+abbrev components := rows G.constants G.evaluator G.pair
+/-- Linked private instruction template containing all of the group’s component rows. -/
+abbrev T := Pieces.table G.components
+/-- Public operand words of the linked table, obtained from the geometry and actual literal
+prefix. -/
+abbrev pub := Pieces.word G.g G.lit ∘ Pieces.bank G.components
+/-- The group’s dispatch-tag address encoded as a RAM word. -/
+abbrev addr := Pieces.word G.g G.lit (.geometry Layout.stageTag)
+/-- Successor-stage function for the group’s evaluator program. -/
+abbrev nextStage := next G.evaluator
+/-- Outer dispatcher program with the linked components, successor stages, public operands, and
+actual tag address. -/
+abbrev P := outerProgram G.T G.nextStage G.pub G.addr
+/-- Fuel left for a source-stage call after charging the dispatch events for its selected tag. -/
+abbrev clockAt (s : Stage) := G.clock - (dispatchEvents G.addr s).length
+/-- Complete ordinary source histories starting in state zero at the supplied memory, with the
+selected stage’s residual fuel and linked-report room checks. -/
+abbrev StagePaths (s : Stage) (m : Memory G.w) := Ordinary G.T G.nextStage G.pub G.addr s (G.clockAt s) 0 m
+/-- The memory at the group’s tag address contains the word encoding the selected stage. -/
+abbrev tagged (s : Stage) (m : Memory G.w) := m G.addr.val = tagWord G.w s
+
+theorem clock_add (s : Stage) : G.clockAt s + (dispatchEvents G.addr s).length = G.clock := by
+ have h := G.dispatchFit
+ have hlen : (dispatchEvents G.addr s).length ≤ 44 := by
+ simp only [dispatchEvents,List.length_cons,List.length_replicate]
+ have hs := s.isLt
+ omega
+ exact Nat.sub_add_cancel (hlen.trans h)
+
+/-- The program with flattened, stage-relocated operands is the physical group program. -/
+theorem program_eq : G.P = (LiveProgram.machine G.constants G.evaluator G.pair G.g G.lit).program := by
+ unfold LiveProgram.machine Pieces.machine Pieces.program
+ rw [Pieces.data_eq]
+ rfl
+
+variable {G}
+
+/-- Entry certificate for a tagged stage. Its invariant holds at state zero and supplies the
+tag-preservation condition for the stage’s returns. -/
+structure Entry (G : Group) (s : Stage) (m : Memory G.w) where
+ /-- Invariant on the returned state word and memory used to establish the stage’s tag frame. -/
+ inv : Word G.w → Memory G.w → Prop
+ frame : TagFrame G.T G.pub G.addr s (G.clockAt s) inv
+ ready : inv 0 m
+ tag : G.tagged s m
+
+/-- The ordinary stage traces indexed by their mathematical choices. -/
+structure Indexed (G : Group) (s : Stage) (m : Memory G.w) (ι : Type*) extends Entry G s m where
+ /-- Bijection between the chosen indices and complete ordinary source histories of the stage. -/
+ traces : ι ≃ G.StagePaths s m
+
+namespace Indexed
+
+variable {s : Stage} {m : Memory G.w} {ι : Type*} (A : Indexed G s m ι)
+
+/-- Map the indexed history’s ordinary reports to their linked reports, including outer
+dispatch and stage transfer. -/
+noncomputable def logs (x : ι) : List (Report G.w) :=
+ (ordinaryReports (A.traces x)).map (linkedReport G.nextStage G.addr s)
+
+/-- Memory after the indexed history’s source events and transfer to its successor stage. -/
+noncomputable def memory (x : ι) : Memory G.w :=
+ transferMemory G.addr (G.nextStage s) (after m (eventLog (ordinaryReports (A.traces x))))
+
+/-- The transferred tag of an ordinary stage is visible on entry to its successor. -/
+theorem tagged_memory {s' : Stage} (hnext : G.nextStage s = some s') (x : ι) : G.tagged s' (A.memory x) := by
+ change transferMemory G.addr _ _ G.addr.val = _
+ simp [transferMemory,hnext,writeMemory]
+
+/-- A completed component indexed by its own branch data, followed by an
+arbitrary native continuation at the same outer clock. -/
+noncomputable def continuationEquiv {s' : Stage} (hnext : G.nextStage s = some s')
+ (cap : List (Report G.w) → Prop) :
+ (Σ x : ι, ActualPaths G.P G.clock 0 (A.memory x) (fun rest => cap (A.logs x ++ rest))) ≃
+ ActualPaths G.P G.clock 0 m cap := by
+ let e := ordinaryEquiv (next := G.nextStage) (cap := cap) G.tagFit A.frame A.ready A.tag
+ have htime := G.clock_add s
+ refine (Equiv.sigmaCongr (β₂ := fun p : G.StagePaths s m => Remainder cap p) A.traces (fun x => ?_)).trans ?_
+ · change _ ≃ Remainder cap (A.traces x)
+ unfold Remainder memory logs
+ rw [htime,transferState,hnext]
+ exact Equiv.refl _
+ · simpa only [htime] using e
+
+end Indexed
+end Group
+end LiveProgram.PairStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPaperParameters.lean b/lean/OAI/Computability/VPVNP/LiveProgramPaperParameters.lean
new file mode 100644
index 0000000000..082a3dbb8b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPaperParameters.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.DiagonalClock
+import OAI.Computability.VPVNP.LiveProgramAdviceCapacity
+import OAI.Computability.VPVNP.LiveOutsideBudget
+import OAI.Computability.VPVNP.LiveWorkspaceCapacity
+
+/-!
+# Joint parameter choices for the live evaluator and the diagonal budget
+
+Choose the chain power, raw-prefix and advice exponents, tape radius and cut
+width before choosing the address multiplier. The bound on that multiplier
+depends on these fixed exponents. Only then take the eventual threshold in
+the input length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+open Filter CursorBounds LiveEvaluatorEncoding
+
+private def labelCount (C motif n : ℕ) := PrimedStackRAM.labelCount n n (n^(C+5)) + motif
+
+private theorem polynomial_labels (C motif : ℕ) : PolynomiallyBounded (labelCount C motif) := by
+ let id := PolynomiallyBounded.id
+ let state := id.pow (C+5)
+ have pair := (id.mul id).of_le (fun n => show n*(n-1)/2 ≤ n*n from
+ (Nat.div_le_self ..).trans (Nat.mul_le_mul_left n (Nat.sub_le ..)))
+ change PolynomiallyBounded (fun n => PrimedStackRAM.labelCount n n (n^(C+5)) + motif)
+ simpa [PrimedStackRAM.labelCount, Nat.choose_two_right] using
+ (((state.mul id).mul (.const 2)).add (((pair.mul state).mul state).mul state)).add (.const motif)
+
+/-- One choice of the constants gives simultaneous clock, cut, advice and
+outside-budget bounds, as well as sufficient physical word space. -/
+theorem paper_parameters (C motif : ℕ) {P rawLength H : ℕ → ℕ} (radius : ℕ → ℕ → ℕ)
+ (hP : PolynomiallyBounded P) (hraw : PolynomiallyBounded rawLength) (hH : PolynomiallyBounded H)
+ (hr : ∀ a, PolynomiallyBounded (fun n => radius n (2*n^a))) (E : UniversalMachine.Program) :
+ ∃ a dA d₁ d₂ r B₀ : ℕ, 2 ≤ a ∧ 1 ≤ B₀ ∧ ∀ k B : ℕ, B₀ ≤ B → ∀ᶠ n : ℕ in atTop,
+ let c : Constants := ⟨C, a, d₁, d₂, r, dA, motif⟩
+ let g := paperGeometry B H n
+ let t := c.labels.eval g
+ let Z := 2*n^a
+ 2^(P n) * (Z+1)^k ≤ 2^(n^a-1) ∧ radius n Z ≤ n^r ∧ rawLength n ≤ n^dA ∧
+ g.w + n^dA + t * Nat.clog 2 t ≤ n^d₁ ∧ 1 + t*Z ≤ n^d₂ ∧
+ LiveEvaluatorTail.Layout E.extra (n^r) g.w (n^d₂) ∧
+ OutsideBudget.majorant c n < processorCount B n ∧ g.w ≤ n ∧
+ (Layout.pairWorkspace c).eval g + (processorCount B n)^2 < 2^g.w ∧
+ (Layout.shadow c).eval g < 2^g.w ∧ (Layout.oldState c).eval g < 2^g.w ∧
+ Layout.stageTag.eval g < 2^g.w := by
+ let t := labelCount C motif
+ have ht : PolynomiallyBounded t := polynomial_labels C motif
+ obtain ⟨a, _, _, ha, hclock⟩ := DiagonalClock.parameters radius hP hraw ht hr E
+ obtain ⟨r, hrad⟩ := Advice.eventually_power (hr a)
+ obtain ⟨dA, d₁, had⟩ := Advice.capacity_exponents hraw ht
+ have hfields : PolynomiallyBounded fun n => fieldWords (n^r) :=
+ (((PolynomiallyBounded.const 1).add (((PolynomiallyBounded.const 2).mul
+ (PolynomiallyBounded.id.pow r)).add (.const 1))).add (((PolynomiallyBounded.const 2).mul
+ (PolynomiallyBounded.id.pow r)).add (.const 1)))
+ have hz := (PolynomiallyBounded.const 2).mul (PolynomiallyBounded.id.pow a)
+ obtain ⟨d₂, hcut⟩ := Advice.eventually_power (((PolynomiallyBounded.const 1).add (ht.mul hz)).add
+ ((PolynomiallyBounded.const 1).add (hfields.mul PolynomiallyBounded.id)))
+ let c : Constants := ⟨C, a, d₁, d₂, r, dA, motif⟩
+ obtain ⟨B', hbudget⟩ := OutsideBudget.eventually_budget c
+ refine ⟨a, dA, d₁, d₂, r, max 1 B', ha, le_max_left .., fun k B hB => ?_⟩
+ have hB' := (le_max_left 1 B').trans hB
+ filter_upwards [hclock k B hB', hrad, had B, hcut, hbudget B ((le_max_right ..).trans hB),
+ eventually_workspace c hB' hH] with n time rad adv cut budget work
+ have he : c.labels.eval (paperGeometry B H n) = t n := by rw [Constants.labels, eval_add, Constants.grammarLabels_eq]; rfl
+ change 1+t n*(2*n^a) + (1+fieldWords (n^r)*n) ≤ n^d₂ at cut
+ have hwidth := Nat.mul_le_mul_left (fieldWords (n^r)) budget.2
+ dsimp only
+ change _ ∧ _ ∧ _ ∧ _ + _ + c.labels.eval _ * _ ≤ _ ∧ 1 + c.labels.eval _ * _ ≤ _ ∧ _
+ rw [he]
+ exact ⟨time.1, rad, adv.1, adv.2, by omega, ⟨time.2.2.2.symbolWidth, time.2.2.2.stateWidth,
+ by change 1 + fieldWords (n^r) * wordBits B n ≤ n^d₂; omega⟩, budget.1, budget.2, work⟩
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPieces.lean b/lean/OAI/Computability/VPVNP/LiveProgramPieces.lean
new file mode 100644
index 0000000000..142589cfd1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPieces.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.LivePublicExpr
+import OAI.Computability.VPVNP.LiveStageOperands
+import OAI.Computability.VPVNP.LiveStageLinkPaths
+
+/-!
+# Linking native components with length-computable public operands
+
+Each piece has its own register and operand count. The single finite native
+table shares registers, and numbers the disjoint operand rows by a concrete
+finite equivalence. Its sole additional operand is the outer tag address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+open BurstRAM BurstRAM.PrivateRAM
+
+/-- The processor may read its own literal prefix when constructing the primed
+strings. Supplying these two parsed values avoids embedding its code in itself. -/
+structure LiteralPrefix where
+ /-- Length in bits of the processor's literal program prefix as read from its input. -/
+ length : ℕ
+ /-- Packed natural number representing the bits of that literal program prefix. -/
+ value : ℕ
+
+/-- Source of one public operand, chosen from a geometry expression, the literal prefix length,
+or its packed word. -/
+inductive InputOperand where
+ | geometry (e : PublicExpr)
+ | prefixLength
+ | prefixWord
+
+/-- Evaluate an operand using the supplied geometry and the two parsed literal-prefix values. -/
+def InputOperand.eval (g : Geometry) (p : LiteralPrefix) : InputOperand → ℕ
+ | .geometry e => e.eval g
+ | .prefixLength => p.length
+ | .prefixWord => p.value
+
+/-- A native component with a finite instruction table, register and operand counts, and a
+source for each public operand. -/
+structure Piece where
+ /-- Number of program-counter positions in this component's instruction table. -/
+ pcs : ℕ
+ /-- Number of ordinary registers addressed by this component's instructions. -/
+ regs : ℕ
+ /-- Number of public operand positions in the component. -/
+ count : ℕ
+ /-- The component's burst-RAM template at its specified instruction, register, and operand
+ counts. -/
+ table : Template pcs regs count
+ /-- Select the source of each public word supplied to the component. -/
+ operands : Fin count → InputOperand
+
+/-- Package a native table whose public operands are all evaluated from geometry expressions. -/
+def Piece.ofTable {p r k : ℕ} (T : Template p r k) (operands : Fin k → PublicExpr) : Piece :=
+ ⟨p,r,k,T,InputOperand.geometry ∘ operands⟩
+
+namespace Pieces
+variable {d : ℕ} (rows : Fin d → Piece) (next : Fin d → Option (Fin d)) (tag : PublicExpr)
+
+/-- Size of the shared ordinary register bank, given by the largest component register count. -/
+def regs := Finset.univ.sup fun s => (rows s).regs
+/-- Total length of the public operand bank obtained by concatenating the component operand
+rows. -/
+def count := ∑ s, (rows s).count
+
+/-- Embed a component's register in the shared bank at the same numerical index. -/
+def regEmbedding (s : Fin d) : Fin (rows s).regs ↪ Fin (regs rows) :=
+ ⟨fun i => i.castLE (Finset.le_sup (Finset.mem_univ s)), fun _ _ h => Fin.ext (congrArg (fun x : Fin (regs rows) => x.val) h)⟩
+
+/-- Number a component's local operand in the disjoint union of all component operand rows. -/
+def operandEmbedding (s : Fin d) (i : Fin (rows s).count) : Fin (count rows) := finSigmaFinEquiv ⟨s,i⟩
+
+/-- Relocate a component's ordinary registers and public operands into the shared banks. -/
+def table (s : Fin d) : Template (rows s).pcs (regs rows) (count rows) :=
+ LiveStageLink.widen (rows s).table (regEmbedding rows s) (operandEmbedding rows s)
+
+/-- Link the relocated component tables using the prescribed successor for each accepting stage
+exit. -/
+def program := LiveStageLink.linked (table rows) next
+
+/-- Look up the operand source belonging to a flattened component and operand index. -/
+def bank (i : Fin (count rows)) : InputOperand :=
+ let p := finSigmaFinEquiv.symm i
+ (rows p.1).operands p.2
+
+/-- Append the geometry expression for the linker's stage-tag address to the component operand
+bank. -/
+def operand : Fin (count rows+1) → InputOperand := Fin.snoc (bank rows) (.geometry tag)
+
+/-- Evaluate a public operand and encode its natural value as a word at the geometry's RAM
+width. -/
+def word (g : Geometry) (lit : LiteralPrefix) (e : InputOperand) : Word g.w := Fin.ofNat _ (e.eval g lit)
+
+/-- Encode every linked public operand, including the final stage-tag address, for the given
+geometry and literal prefix. -/
+def publicData (g : Geometry) (lit : LiteralPrefix) := word g lit ∘ operand rows tag
+
+/-- Instantiate the linked native table at the geometry's word width with the evaluated public
+bank. -/
+def machine (g : Geometry) (lit : LiteralPrefix) := (program rows next).instantiate g.w (publicData rows tag g lit)
+
+/-- Instantiate the individual component using its own public operand row at the same geometry
+and literal prefix. -/
+def component (s : Fin d) (g : Geometry) (lit : LiteralPrefix) := ((rows s).table.instantiate g.w (word g lit ∘ (rows s).operands)).program
+
+@[simp] theorem bank_at (s : Fin d) (i : Fin (rows s).count) :
+ bank rows (operandEmbedding rows s i) = (rows s).operands i := by
+ unfold bank operandEmbedding
+ rw [Equiv.symm_apply_apply]
+
+/-- The physical processor can evaluate the flattened bank without receiving
+any extra header contents or choices in its startup registers. -/
+theorem data_eq (g : Geometry) (lit : LiteralPrefix) : publicData rows tag g lit =
+ LiveStageLink.publicData (word g lit ∘ bank rows) (word g lit (.geometry tag)) := by
+ funext i
+ refine Fin.lastCases ?_ (fun j => ?_) i <;> simp [publicData,operand,LiveStageLink.publicData]
+
+/-- Operand relocation is invisible to native execution in each selected stage. -/
+theorem component_eq (g : Geometry) (lit : LiteralPrefix) (s : Fin d) (fuel : ℕ) (st : Word g.w) (m : Memory g.w)
+ (bits : List Bool) :
+ let enlarged := ((table rows s).instantiate g.w (word g lit ∘ bank rows)).program
+ execute enlarged fuel (enlarged.start st) m bits =
+ execute (component rows s g lit) fuel ((component rows s g lit).start st) m bits := by
+ apply (LiveStageLink.execute_widen_start (rows s).table (regEmbedding rows s) (operandEmbedding rows s)
+ (word g lit ∘ bank rows) fuel st m bits).trans
+ have h : (word g lit ∘ bank rows) ∘ operandEmbedding rows s = word g lit ∘ (rows s).operands := by
+ funext i; simp
+ rw [h]; rfl
+
+/-- Every successful original native call appears in the linked machine on
+precisely its own bit string, with the prescribed tag effect and bounded overhead. -/
+theorem execute_component (g : Geometry) (lit : LiteralPrefix) (s : Fin d) (hfit : d ≤ 2^g.w) {f cap : ℕ}
+ (hcap : f+2*d+5 ≤ cap) (st : Word g.w) (m : Memory g.w) (ht : m (word g lit (.geometry tag)).val = LiveStageLink.tagWord g.w s)
+ (bs : List Bool) (rep : Report g.w) (h : execute (component rows s g lit) f ((component rows s g lit).start st) m bs = some rep) :
+ execute (machine rows next tag g lit).program cap ((machine rows next tag g lit).program.start st) m bs =
+ some (LiveStageLink.linkedReport next (word g lit (.geometry tag)) s rep) := by
+ unfold machine program
+ rw [data_eq]
+ exact LiveStageLink.execute_linked_of_stage (table rows) next _ _ s hfit hcap st m ht bs rep
+ ((component_eq rows g lit s f st m bs).trans h)
+
+/-- Exact replay for every choice stream, including rejection and calls after
+termination. The per-stage semantics in this replay are native templates. -/
+theorem paths_eq (g : Geometry) (lit : LiteralPrefix) (hfit : d ≤ 2^g.w) (f : ℕ) (hf : 2*d+2 ≤ f)
+ (st : Option (Word g.w)) (m : Memory g.w) (bs : List (List Bool)) :
+ runSegment (machine rows next tag g lit).program f st m bs =
+ LiveStageLink.stageSegment (table rows) next (word g lit ∘ bank rows) (word g lit (.geometry tag)) f st m bs := by
+ unfold machine program
+ rw [data_eq]
+ exact LiveStageLink.runSegment_eq_stageSegment (table rows) next _ _ hfit f hf st m bs
+
+end Pieces
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramPrefixCopyRun.lean b/lean/OAI/Computability/VPVNP/LiveProgramPrefixCopyRun.lean
new file mode 100644
index 0000000000..4fb189c1d7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramPrefixCopyRun.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorFrame
+import OAI.Computability.VPVNP.LiveEvaluatorInitializeStages
+
+/-! # Linked copying of the midpoint's active evaluator input prefix -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+
+open BurstRAM LiveStageLink LiveEvaluatorInitialize CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem copyReports_outside (hw : 2 ≤ w) (pub : Fin 4 → Word w) (width : (pub 3).val = w)
+ (count : Word w) (fit : firstData pub+count.val ≤ 2^w) {s : Option (Word w)} {m : Memory w}
+ {bits : List (List Bool)} {rs : List (Report w)}
+ (run : runSegment (copyStage.instantiate w (copyPublic pub count)).program 23 s m bits = some rs) :
+ ∀ r ∈ rs, ∀ mem a, a < firstData pub ∨ firstData pub+count.val ≤ a → after mem r.events a = mem a := by
+ induction bits generalizing s m rs with
+ | nil => obtain rfl := Option.some.inj run; simp
+ | cons bs rest ih =>
+ cases s with
+ | none => cases run
+ | some st =>
+ by_cases active : st < count
+ · obtain ⟨es, hr, -, -, -, -, replay⟩ := execute_copyStage_active_replay hw pub width count st active m bs 0
+ rw [runSegment, hr] at run
+ by_cases hb : bs = []
+ · rw [ite_eq_left hb, Option.map_eq_some_iff] at run
+ obtain ⟨tail, run', rfl⟩ := run
+ rw [List.forall_mem_cons]
+ refine ⟨?_, ih run'⟩
+ intro mem a ha
+ change after mem es a = mem a
+ rw [replay, writeMemory, ite_eq_right]
+ have ha' : (targetAddress pub st).val = firstData pub+st.val := by
+ have h1 : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega))
+ change st.val < count.val at active
+ unfold targetAddress firstData
+ simp only [Fin.val_add, h1, Nat.mod_add_mod]
+ exact Nat.mod_eq_of_lt (by unfold firstData at fit; omega)
+ rw [ha']
+ change st.val < count.val at active
+ omega
+ · simp [hb] at run
+ · have hc : (copyPublic pub count) 4 ≤ st := by rw [show (copyPublic pub count) 4 = count from Fin.snoc_last ..]; exact le_of_not_gt active
+ have hr := execute_copyStage_skip (copyPublic pub count) st m bs 19 hc
+ rw [runSegment, hr] at run
+ by_cases hb : bs = []
+ · rw [ite_eq_left hb, Option.map_eq_some_iff] at run
+ obtain ⟨tail, run', rfl⟩ := run
+ rw [List.forall_mem_cons]
+ exact ⟨fun _ _ _ => rfl, ih run'⟩
+ · simp [hb] at run
+
+/-- Retagging both reference and destination preserves the complete prefix-copy specification. -/
+theorem copied_with_tag {raw : List Bool} {base count : ℕ} {original out : Memory w}
+ (h : Copied raw base count original out) (tag v : Word w)
+ (outside : tag.val < base ∨ base+count ≤ tag.val) :
+ Copied raw base count (writeMemory original tag v) (writeMemory out tag v) := by
+ constructor
+ · intro j hj
+ rw [writeMemory, ite_eq_right (by omega), h.symbols _ hj]
+ · intro a ha
+ by_cases he : a = tag.val
+ · simp [writeMemory, he]
+ · simpa only [writeMemory, ite_eq_right he] using h.outside a ha
+
+/-- Base word address of the prefix-copy operand frame, eight words past the advice frame base. -/
+abbrev prefixCopyBase (G : Group) := Pieces.word G.g G.lit (.geometry (Layout.adviceFrames G.constants+8))
+
+/-- Exact framed prefix-copy calls, including a single accepting skip for an empty prefix. -/
+theorem prefixCopyRun (G : Group) (pub : Fin 4 → Word G.w) (raw : List Bool) (m : Memory G.w)
+ (hw : 2 ≤ G.w) (width : (pub 3).val = G.w) (running : G.evaluator.extra ≠ 0)
+ (fit : firstData pub + raw.length ≤ 2^G.w)
+ (packed : ∀ j < raw.length, m (sourceAddress pub (j : Word G.w)).val = inputWord G.w raw (j/G.w))
+ (disjoint : ∀ j < raw.length, (sourceAddress pub (j : Word G.w)).val < firstData pub ∨
+ firstData pub+raw.length ≤ (sourceAddress pub (j : Word G.w)).val)
+ (data : Frame.data G.prefixCopyBase m = copyPublic pub (raw.length : Word G.w))
+ (tag : G.tagged Stage.prefixCopy m)
+ (tagOutside : G.addr.val < firstData pub ∨ firstData pub+raw.length ≤ G.addr.val)
+ (frameOutside : ∀ j : Fin 5, (G.prefixCopyBase+(j.val : Word G.w)).val < firstData pub ∨
+ firstData pub+raw.length ≤ (G.prefixCopyBase+(j.val : Word G.w)).val)
+ (clock : 90 ≤ G.clock) :
+ ∃ out, Advice.Returning G.P G.clock (max 1 raw.length) 9 m (writeMemory out G.addr (tagWord G.w Stage.skeleton)) ∧
+ Copied raw (firstData pub) raw.length m out := by
+ have hactive : activeLength G.evaluator raw = raw.length := ite_eq_right running
+ obtain ⟨rs, hr, he, hc, hl, hp⟩ := copyStage_sweep hw pub width G.evaluator raw m (hactive ▸ fit)
+ (hactive ▸ packed) (hactive ▸ disjoint)
+ rw [hactive] at hr hc hl
+ have hval : (raw.length : Word G.w).val = raw.length :=
+ Fin.val_cast_of_lt (by unfold firstData at fit; omega)
+ have hkeep := copyReports_outside hw pub width (raw.length : Word G.w) (by rwa [hval]) hr
+ simp only [hval] at hkeep
+ refine ⟨after m (eventLog rs), ?_, hc⟩
+ apply framedReturning (T := copyStage) (b := 2) clock tag (dest := Stage.skeleton) rfl data
+ (fun _ _ _ => rfl) hr he hl (fun r h => (hp r h).2.1)
+ intro r h u
+ exact ⟨hkeep r h u _ tagOutside, funext fun j => hkeep r h u _ (frameOutside j)⟩
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramRouting.lean b/lean/OAI/Computability/VPVNP/LiveProgramRouting.lean
new file mode 100644
index 0000000000..4af978b631
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramRouting.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.LiveProgram
+import OAI.Computability.VPVNP.LiveStagePaths
+import OAI.Computability.VPVNP.RAMChoicePrefix
+
+/-!
+# Native path factorization at the three header decisions
+
+A router contributes exactly one choice-free burst. Removing that burst is a
+bijection from accepting paths to accepting continuations, with the report's
+memory effect, returned cursor and contribution to the cost predicate retained.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+/-- The three routing decisions, selecting the group mode, the incoming tail preparation, or
+the outgoing tail preparation. -/
+inductive Router where
+ | mode | firstTail | last
+ deriving DecidableEq
+
+namespace Router
+
+/-- Stage at which the selected routing decision is executed. -/
+def stage : Router → Stage
+ | .mode => Stage.mode | .firstTail => Stage.firstTail | .last => Stage.last
+
+/-- Geometry expression locating the header word that supplies this router's flag. -/
+def address : Router → PublicExpr
+ | .mode => HeaderLayout.mode Layout.header
+ | .firstTail => HeaderLayout.firstTail Layout.header
+ | .last => HeaderLayout.flag Layout.header .last
+
+/-- Map a decoded flag ordinal to this router's acceptance, rejection, or stage-transfer
+target. -/
+def target : Router → Fin 3 → Route.Target
+ | .mode => modeTarget | .firstTail => firstTarget | .last => lastTarget
+
+/-- The router's two evaluated operands, the address of its decision flag and the address of
+the outer stage tag. -/
+def data (r : Router) (g : Geometry) (lit : LiteralPrefix) : Fin 2 → Word g.w :=
+ Pieces.word g lit ∘ InputOperand.geometry ∘ StageOperands.router r.address
+
+theorem terminal (r : Router) (p : UniversalMachine.Program) : next p r.stage = none := by cases r <;> rfl
+
+theorem component (r : Router) (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) :
+ HEq (Pieces.component (rows c p O) r.stage g lit) (((Route.table r.target).instantiate g.w (r.data g lit)).program) := by
+ cases r <;> rfl
+
+private theorem source_call (r : Router) (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (hw : 2 ≤ g.w) (st : Word g.w) (m : Memory g.w) (i : Fin 3)
+ (hf : m ((r.data g lit) 0).val = (i.val : Word g.w)) (bs : List Bool) (f : ℕ) :
+ let P := Pieces.component (rows c p O) r.stage g lit
+ execute P (f+13) (P.start st) m bs = Route.report (r.data g lit) (m ((r.data g lit) 0).val) i (r.target i) bs := by
+ cases r <;> exact Route.execute_flag hw _ _ st m i hf bs f
+
+/-- At a checked flag this is the exact linked report, including rejection on
+surplus choices and every external probe of the router and the outer dispatch. -/
+theorem execute (r : Router) (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (hw : 2 ≤ g.w) (fit : 21 ≤ 2^g.w)
+ (st : Word g.w) (m : Memory g.w) (i : Fin 3) (hf : m ((r.data g lit) 0).val = (i.val : Word g.w))
+ (addr : Word g.w := Pieces.word g lit (.geometry Layout.stageTag))
+ (ha : addr = Pieces.word g lit (.geometry Layout.stageTag) := by rfl)
+ (ht : m addr.val = LiveStageLink.tagWord g.w r.stage) (bs : List Bool) (f : ℕ) :
+ let P := (machine c p O g lit).program
+ BurstRAM.execute P (f+13+(LiveStageLink.dispatchEvents addr r.stage).length) (P.start st) m bs =
+ (Route.report (r.data g lit) (m ((r.data g lit) 0).val) i (r.target i) bs).map
+ (LiveStageLink.linkedReport (next p) addr r.stage) := by
+ subst addr
+ dsimp only
+ let rows' := rows c p O
+ let tag := Pieces.word g lit (.geometry Layout.stageTag)
+ let bank := Pieces.word g lit ∘ Pieces.bank rows'
+ unfold LiveProgram.machine
+ unfold Pieces.machine Pieces.program
+ rw [Pieces.data_eq]
+ change BurstRAM.execute (LiveStageLink.machine (Pieces.table rows') (next p) bank tag).program
+ (f+13+(LiveStageLink.dispatchEvents tag r.stage).length) ((LiveStageLink.machine (Pieces.table rows') (next p) bank tag).program.start st) m bs = _
+ rw [LiveStageLink.execute_linked (Pieces.table rows') (next p) bank tag r.stage fit st (f+13) m ht bs,
+ Pieces.component_eq]
+ have hc := source_call r c p O g lit hw st m i hf bs f
+ rw [← hc]
+ generalize he : BurstRAM.execute (Pieces.component rows' r.stage g lit) (f+13)
+ ((Pieces.component rows' r.stage g lit).start st) m bs = q
+ cases q with
+ | none => rfl
+ | some rep =>
+ have hlen := (execute_spec he).1.length_lt
+ have hx : LiveStageLink.exitReport (next p) tag r.stage rep = rep := by
+ cases rep with | mk es out => cases out <;> simp [LiveStageLink.exitReport,terminal]
+ change ((some rep).bind (LiveStageLink.boundedExit (next p) tag r.stage (f+13))).map _ =
+ (some rep).map (LiveStageLink.linkedReport (next p) tag r.stage)
+ simp [LiveStageLink.linkedReport,LiveStageLink.boundedExit,hx,hlen]
+
+end Router
+
+/-- The remaining calls use the precise memory and persistent word produced by
+this deterministic burst. A terminal burst allows only the empty remainder. -/
+abbrev Continuations {w : ℕ} {C : Type*} (P : BurstRAM.Program w C) (fuel : ℕ) (m : Memory w)
+ (rep : Report w) (cap : List (Report w) → Prop) :=
+ {bits : List (List Bool) // ∃ logs,
+ runSegment P fuel rep.result (after m rep.events) bits = some logs ∧
+ endState rep.result logs = none ∧ cap (rep::logs)}
+
+/-- A known successful choice-free first call is the unique first call on any
+accepting path. This statement permits arbitrary clocks and report-dependent caps. -/
+noncomputable def deterministicEquiv {w : ℕ} {C : Type*} (P : BurstRAM.Program w C) (f : ℕ) (st : Word w) (m : Memory w)
+ (rep : Report w) (call : BurstRAM.execute P f (P.start st) m [] = some rep)
+ (cap : List (Report w) → Prop) : Continuations P f m rep cap ≃ ActualPaths P f st m cap := by
+ let add : Continuations P f m rep cap → ActualPaths P f st m cap := fun path => ⟨[]::path.val, by
+ obtain ⟨logs,hr,hh,hc⟩ := path.property
+ exact ⟨rep::logs,by simp [runSegment,call,hr],hh,hc⟩⟩
+ apply Equiv.ofBijective add
+ constructor
+ · intro a b hab
+ exact Subtype.ext (List.cons.inj (congrArg Subtype.val hab)).2
+ · rintro ⟨bs,logs,hr,hh,hc⟩
+ cases bs with
+ | nil => simp [runSegment] at hr; subst logs; contradiction
+ | cons x xs =>
+ rw [runSegment] at hr
+ cases hx : BurstRAM.execute P f (P.start st) m x with
+ | none => simp [hx] at hr
+ | some a =>
+ obtain ⟨hx',ha⟩ := execute_prefix_unique call (suffix := x) (by simpa using hx)
+ subst x a
+ simp only [call,Option.map_eq_some_iff] at hr
+ obtain ⟨tail,ht,rfl⟩ := hr
+ exact ⟨⟨xs,tail,ht,hh,hc⟩,rfl⟩
+
+/-- Native path bijection at any of the live program's three decisions. -/
+noncomputable def Router.pathEquiv (r : Router) (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (hw : 2 ≤ g.w) (fit : 21 ≤ 2^g.w)
+ (st : Word g.w) (m : Memory g.w) (i : Fin 3) (hf : m ((r.data g lit) 0).val = (i.val : Word g.w))
+ (ht : m (Pieces.word g lit (.geometry Layout.stageTag)).val = LiveStageLink.tagWord g.w r.stage)
+ (f : ℕ) (src : Report g.w)
+ (selected : Route.report (r.data g lit) (m ((r.data g lit) 0).val) i (r.target i) [] = some src)
+ (cap : List (Report g.w) → Prop) :
+ let P := (machine c p O g lit).program
+ let addr := Pieces.word g lit (.geometry Layout.stageTag)
+ let clock := f+13+(LiveStageLink.dispatchEvents addr r.stage).length
+ Continuations P clock m (LiveStageLink.linkedReport (next p) addr r.stage src) cap ≃ ActualPaths P clock st m cap := by
+ apply deterministicEquiv
+ rw [r.execute c p O g lit hw fit st m i hf _ rfl ht [] f,selected]
+ rfl
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramScatterRun.lean b/lean/OAI/Computability/VPVNP/LiveProgramScatterRun.lean
new file mode 100644
index 0000000000..04c381ba13
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramScatterRun.lean
@@ -0,0 +1,237 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorFrame
+import OAI.Computability.VPVNP.LiveProgramAdviceRun
+import OAI.Computability.VPVNP.LiveEvaluatorRAMImage
+import OAI.Computability.VPVNP.LiveEvaluatorReindexSweep
+
+/-!
+# Permuting the exponent bits in the linked evaluator
+
+The scatter writes the exponent payload positions of the initial tape. The incoming
+order table bounds each computed destination. Consequently the linked scatter can reload
+the five operands of its frame at each call and transfer the stage tag on its final call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.ScatterRun
+
+open BurstRAM LiveEvaluatorReindex LiveEvaluatorInitialize LiveEvaluatorEncoding
+open LiveStageLink PairStages CompressorRecords
+open scoped Fin.CommRing
+
+variable {w d t Z base M a : ℕ} {pub : Fin 5 → Word w}
+
+/-- Addresses outside the interval containing all reversed, tagged exponent payloads. -/
+def Outside (pub : Fin 5 → Word w) (j : ℕ) : Prop :=
+ j < (pub 2).val ∨ (pub 2).val + 2*(pub 4).val ≤ j
+
+private theorem active_target (hw : 2 ≤ w) (L : LiveEvaluatorReindex.Layout pub d t Z base M a)
+ (perm : Fin d ≃ Fin t) (m : Memory w) (order : ∀ i : Fin d, (m ((pub 1).val+i.val)).val = (perm i).val)
+ (q : Word w) (active : q < pub 4) :
+ (pub 2).val ≤ (targetAddress pub q m).val ∧
+ (targetAddress pub q m).val < (pub 2).val + 2*(pub 4).val := by
+ have hdt : d = t := by simpa using Fintype.card_congr perm
+ have hq : q.val < d*Z := by rw [hdt, ← L.total]; exact active
+ have hz : 0 < Z := by by_contra! h; simp [Nat.eq_zero_of_le_zero h] at hq
+ have hrow : q.val / Z < d := (Nat.div_lt_iff_lt_mul hz).mpr hq
+ have hm := mapAddress_val pub q (by rw [L.width]; have := L.mapFit; omega)
+ rw [L.width] at hm
+ let i : Fin d := ⟨q.val / Z, hrow⟩
+ have hread : (m (mapAddress pub q).val).val = (perm i).val := by rw [hm]; exact order i
+ have hf : (m (mapAddress pub q).val).val*(pub 3).val + q.val % (pub 3).val < (pub 4).val := by
+ rw [hread, L.width, L.total]
+ have hmul := Nat.mul_le_mul_right Z (perm i).isLt
+ rw [Nat.succ_mul] at hmul
+ have hrem := Nat.mod_lt q.val hz
+ omega
+ have hback : 2*((pub 4).val-1-((m (mapAddress pub q).val).val * (pub 3).val +
+ q.val % (pub 3).val)) < 2*(pub 4).val := by omega
+ have hfit := L.targetFit
+ rw [← L.total] at hfit
+ rw [targetAddress_val pub q m hw hf (by omega)]
+ omega
+
+private theorem report_protects (hw : 2 ≤ w) (L : LiveEvaluatorReindex.Layout pub d t Z base M a)
+ (perm : Fin d ≃ Fin t) (m : Memory w) (order : ∀ i : Fin d, (m ((pub 1).val+i.val)).val = (perm i).val)
+ (q : Word w) (bs : List Bool) (r : Report w)
+ (run : let P := (scatterPhase.instantiate w pub).program
+ execute P 27 (P.start q) m bs = some r) :
+ ∀ m' j, Outside pub j → after m' r.events j = m' j := by
+ dsimp only at run
+ by_cases active : q < pub 4
+ · rw [execute_phase_active pub q m bs 0 active] at run
+ split at run
+ · cases run
+ intro m' j hj
+ obtain ⟨lo, hi⟩ := active_target hw L perm m order q active
+ unfold Outside at hj
+ change writeMemory m' (targetAddress pub q m) (inputSymbol pub q m) j = m' j
+ exact ite_eq_right (by omega)
+ · contradiction
+ · by_cases zero : q = 0
+ · subst q
+ have empty : pub 4 = 0 := le_antisymm (le_of_not_gt active) (Fin.zero_le _)
+ rw [execute_phase_empty pub m bs 22 empty] at run
+ split at run
+ · cases run; intro m' j _; rfl
+ · contradiction
+ · rw [execute_phase_past pub q m bs 22 (le_of_not_gt active) zero] at run
+ contradiction
+
+/-- Replaying any one of the actual call reports on any memory only writes inside the
+payload interval. Earlier scatter writes preserve the advised permutation. -/
+theorem reports_outside (hw : 2 ≤ w) (L : LiveEvaluatorReindex.Layout pub d t Z base M a)
+ (perm : Fin d ≃ Fin t) {m : Memory w} (order : ∀ i : Fin d, (m ((pub 1).val+i.val)).val = (perm i).val)
+ {q : Option (Word w)} {bs : List (List Bool)} {rs : List (Report w)}
+ (run : runSegment (scatterPhase.instantiate w pub).program 27 q m bs = some rs) :
+ ∀ r ∈ rs, ∀ m' j, Outside pub j → after m' r.events j = m' j := by
+ induction bs generalizing q m rs with
+ | nil => have h : rs = [] := by simpa [runSegment] using run.symm
+ simp [h]
+ | cons b bs ih =>
+ cases q with
+ | none => simp [runSegment] at run
+ | some q =>
+ let P := (scatterPhase.instantiate w pub).program
+ cases he : execute P 27 (P.start q) m b with
+ | none => simp [runSegment, P] at he run; simp [he] at run
+ | some r =>
+ change runSegment P 27 (some q) m (b :: bs) = some rs at run
+ rw [runSegment, he] at run
+ obtain ⟨tail, ht, rfl⟩ := Option.map_eq_some_iff.mp run
+ have head := report_protects hw L perm m order q b r he
+ have keep (i : Fin d) : (after m r.events ((pub 1).val+i.val)).val = (perm i).val := by
+ apply (congrArg Fin.val (head m _ _)).trans (order i)
+ rcases L.mapDisjoint with hlo | hhi
+ · exact Or.inl (by have := i.isLt; omega)
+ · exact Or.inr (by rw [L.total]; omega)
+ intro s hs
+ rcases List.mem_cons.mp hs with rfl | hs
+ · exact head
+ · exact ih keep ht s hs
+
+/-- Base word address of the five scatter operands, seventeen words past the advice frame base. -/
+def operandBase (G : PairStages.Group) : Word G.w :=
+ Pieces.word G.g G.lit (.geometry (LiveProgram.Layout.adviceFrames G.constants + 17))
+
+theorem component_eq (G : PairStages.Group) (st : Word G.w) (m : Memory G.w) (bits : List Bool) :
+ let C := Pieces.component G.components Stage.scatter G.g G.lit
+ let R := (Frame.machine scatterPhase (operandBase G)).program
+ execute C 47 (C.start st) m bits = execute R 47 (R.start st) m bits := rfl
+
+/-- Execute the complete framed scatter in the linked group. Its last report hands
+control to the last-group router and the tape bank stores the evaluator's initial
+configuration with the formal-coordinate exponents. -/
+theorem returning_outside (G : PairStages.Group) (clock : 94 ≤ G.clock) (hw : 2 ≤ G.w)
+ (pub : Fin 5 → Word G.w) (perm : Fin d ≃ Fin t) (dense : Fin d → Word Z)
+ (formal : Fin t → Word Z) (order : ∀ i, formal (perm i) = dense i)
+ (running : G.evaluator.extra ≠ 0) (hs : G.evaluator.extra+2 ≤ 2^G.w)
+ (A : List Bool) (stateBase : Word G.w) (radius : ℕ)
+ (L : LiveEvaluatorReindex.Layout pub d t Z stateBase.val radius A.length)
+ (m : Memory G.w) (src : Sources pub perm dense m)
+ (space : (A ++ EvaluatorProgramRawInput.runtime formal).length ≤ radius+1)
+ (prepared : Stores hw hs stateBase.val m
+ (LiveEvaluatorTail.initialCode radius (UniversalMachine.initial G.evaluator
+ (A ++ EvaluatorProgramRawInput.runtime (fun _ : Fin t => (0 : Word Z))))))
+ (tagged : G.tagged Stage.scatter m) (data : Frame.data (operandBase G) m = pub)
+ (frameOutside : ∀ j : Fin 5, Outside pub ((operandBase G)+(j.val : Word G.w)).val)
+ (tagOutside : G.addr.val < stateBase.val ∨ stateBase.val+fieldWords radius ≤ G.addr.val)
+ (bankFit : stateBase.val + fieldWords radius ≤ 2^G.w) :
+ let code := LiveEvaluatorTail.initialCode radius (UniversalMachine.initial G.evaluator
+ (A ++ EvaluatorProgramRawInput.runtime formal))
+ ∃ final, Advice.Returning G.P G.clock (max 1 (d*Z)) 10 m final ∧
+ Stores hw hs stateBase.val final code ∧ LiveEvaluatorRAM.ConfigAt final stateBase code ∧
+ G.tagged Stage.last final ∧ Advice.CostLimit G.P G.clock (max 1 (d*Z)) m (11*max 1 (d*Z)) ∧
+ (∀ j, j ≠ G.addr.val → Outside pub j → final j = m j) := by
+ dsimp only
+ obtain ⟨rs, hr, halt, store, hlen, hprobes⟩ := sweep_native hw pub perm dense formal order
+ G.evaluator running hs A stateBase.val radius L m src space prepared
+ have tagSafe : Outside pub G.addr.val := by
+ unfold Outside
+ rw [L.target, L.total]
+ simp only [List.length_append, EvaluatorProgramRawInput.runtime_length] at space
+ unfold fieldWords at tagOutside
+ omega
+ have protect := reports_outside hw L perm src.order hr
+ let final := writeMemory (after m (eventLog rs)) G.addr (tagWord G.w Stage.last)
+ have ret : Advice.Returning G.P G.clock (max 1 (d*Z)) 10 m final := by
+ apply Group.framedReturning (T := scatterPhase) (b := 3) clock tagged (dest := Stage.last)
+ (by rfl) data (component_eq G) hr halt hlen hprobes
+ intro r h u
+ exact ⟨protect r h u _ tagSafe, funext (fun j => protect r h u _ (frameOutside j))⟩
+ have kept : Stores hw hs stateBase.val final (LiveEvaluatorTail.initialCode radius
+ (UniversalMachine.initial G.evaluator (A ++ EvaluatorProgramRawInput.runtime formal))) := by
+ intro k
+ have hk : stateBase.val + k.val ≠ G.addr.val := by have := k.isLt; omega
+ change writeMemory _ _ _ _ = _
+ rw [writeMemory, ite_eq_right hk]
+ exact store k
+ refine ⟨final, ret, kept, ?_, by simp [Group.tagged, final, writeMemory], ?_, ?_⟩
+ · apply LiveEvaluatorRAM.configAt_of_words hw hs
+ intro k
+ have haddr : (stateBase + (k.val : Word G.w)).val = stateBase.val + k.val := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt (by have := k.isLt; omega)]
+ rw [haddr]
+ exact kept k
+ · obtain ⟨logs, hrun, _, _, hn, hp⟩ := ret
+ intro actual ha
+ obtain rfl := Option.some.inj (ha.symm.trans hrun)
+ rw [← hn]
+ have bound (xs : List (Report G.w)) (hb : ∀ r ∈ xs, r.probes ≤ 10) :
+ RAMBuckets.cost Report.probes xs ≤ 11*xs.length := by
+ induction xs with
+ | nil => simp [RAMBuckets.cost]
+ | cons r xs ih =>
+ have head := hb r (List.mem_cons_self ..)
+ have tail := ih (fun a ha => hb a (List.mem_cons_of_mem _ ha))
+ rw [RAMBuckets.cost, List.length_cons, Nat.mul_succ]
+ omega
+ exact bound actual (fun r h => (hp r h).1)
+
+ · intro j htag hj
+ change writeMemory _ _ _ j = _
+ rw [writeMemory, ite_eq_right htag]
+ have keep (xs : List (Report G.w))
+ (hp : ∀ r ∈ xs, ∀ u : Memory G.w, after u r.events j = u j) (u : Memory G.w) :
+ after u (eventLog xs) j = u j := by
+ induction xs generalizing u with
+ | nil => rfl
+ | cons r xs ih =>
+ change ((r.events ++ eventLog xs).foldl update u) j = _
+ rw [List.foldl_append]
+ exact (ih (fun q hq => hp q (List.mem_cons_of_mem _ hq)) _).trans (hp r (List.mem_cons_self ..) u)
+ exact keep rs (fun r h u => protect r h u j hj) m
+
+/-- Execution and configuration at the scatter handoff. -/
+theorem returning (G : PairStages.Group) (clock : 94 ≤ G.clock) (hw : 2 ≤ G.w)
+ (pub : Fin 5 → Word G.w) (perm : Fin d ≃ Fin t) (dense : Fin d → Word Z)
+ (formal : Fin t → Word Z) (order : ∀ i, formal (perm i) = dense i)
+ (running : G.evaluator.extra ≠ 0) (hs : G.evaluator.extra+2 ≤ 2^G.w)
+ (A : List Bool) (stateBase : Word G.w) (radius : ℕ)
+ (L : LiveEvaluatorReindex.Layout pub d t Z stateBase.val radius A.length)
+ (m : Memory G.w) (src : Sources pub perm dense m)
+ (space : (A ++ EvaluatorProgramRawInput.runtime formal).length ≤ radius+1)
+ (prepared : Stores hw hs stateBase.val m
+ (LiveEvaluatorTail.initialCode radius (UniversalMachine.initial G.evaluator
+ (A ++ EvaluatorProgramRawInput.runtime (fun _ : Fin t => (0 : Word Z))))))
+ (tagged : G.tagged Stage.scatter m) (data : Frame.data (operandBase G) m = pub)
+ (frameOutside : ∀ j : Fin 5, Outside pub ((operandBase G)+(j.val : Word G.w)).val)
+ (tagOutside : G.addr.val < stateBase.val ∨ stateBase.val+fieldWords radius ≤ G.addr.val)
+ (bankFit : stateBase.val + fieldWords radius ≤ 2^G.w) :
+ let code := LiveEvaluatorTail.initialCode radius (UniversalMachine.initial G.evaluator
+ (A ++ EvaluatorProgramRawInput.runtime formal))
+ ∃ final, Advice.Returning G.P G.clock (max 1 (d*Z)) 10 m final ∧
+ Stores hw hs stateBase.val final code ∧ LiveEvaluatorRAM.ConfigAt final stateBase code ∧
+ G.tagged Stage.last final ∧ Advice.CostLimit G.P G.clock (max 1 (d*Z)) m (11*max 1 (d*Z)) := by
+ obtain ⟨final, ret, store, config, tag, cost, _⟩ :=
+ returning_outside G clock hw pub perm dense formal order running hs A stateBase radius L m src
+ space prepared tagged data frameOutside tagOutside bankFit
+ exact ⟨final, ret, store, config, tag, cost⟩
+
+end LiveProgram.ScatterRun
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramSchedule.lean b/lean/OAI/Computability/VPVNP/LiveProgramSchedule.lean
new file mode 100644
index 0000000000..24f7800e17
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramSchedule.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.LiveProgramRouting
+
+/-!
+# Mode-dependent stage schedules of the native live group
+
+The header emits zero, one or two. The same finite table serves every mode.
+The following lists give the complete sequence of stage tags after ordinary
+continuing calls within a stage are suppressed. The first tail group uses its
+middle-cut exponents, later groups gather an incoming configuration, and the
+last group installs the required accepting image instead of gathering an
+outgoing configuration.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+open BurstRAM BurstRAM.PrivateRAM
+
+/-- The unit, pair, and evaluator-tail modes of the native live group. -/
+inductive GroupMode where | unit | pair | tail deriving DecidableEq
+
+/-- Encode unit, pair, and tail modes by the header flag ordinals zero, one, and two. -/
+def GroupMode.flag : GroupMode → Fin 3
+ | .unit => 0 | .pair => 1 | .tail => 2
+
+/-- The seven stages that prepare a running evaluator's initial tape, from prefix-length
+recovery through exponent scattering. -/
+def prepareTail : List Stage := [Stage.prefixLength,Stage.adviceFrames,Stage.prefixPack,Stage.orderPack,
+ Stage.prefixCopy,Stage.skeleton,Stage.scatter]
+
+/-- Stage sequence for this group's mode and endpoint flags. A first tail group runs the tape
+preparation only when the evaluator has extra states. -/
+def schedule (p : UniversalMachine.Program) (mode : GroupMode) (first last : Bool) : List Stage :=
+ [Stage.header,Stage.mode] ++ match mode with
+ | .unit => []
+ | .pair => [Stage.nominations,Stage.auxiliaryInit,Stage.auxiliaryCopy,Stage.pair,Stage.exponents]
+ | .tail => [Stage.firstTail] ++
+ (if first then [Stage.initialState] ++ (if p.extra = 0 then [] else prepareTail) else [Stage.oldGather]) ++
+ [Stage.last,if last then Stage.finalState else Stage.newGather,Stage.transition]
+
+/-- For a known checked header the three dynamic destinations are read from
+exactly the same native router tables used by the complete instruction table. -/
+def destination (t : Route.Target) : Option Stage := match t with
+ | .reject | .accept => none
+ | .jump j => if hj : j.val < 21 then some ⟨j.val,hj⟩ else none
+
+/-- Select the next stage from the mode or endpoint flag at a router and from the program's
+ordinary successor map elsewhere. -/
+def successor (p : UniversalMachine.Program) (mode : GroupMode) (first last : Bool) (i : Stage) : Option Stage :=
+ if i = Stage.mode then destination (modeTarget mode.flag)
+ else if i = Stage.firstTail then destination (firstTarget (if first then 1 else 0))
+ else if i = Stage.last then destination (lastTarget (if last then 1 else 0))
+ else next p i
+
+/-- The full stage list, including the exact terminal stage, follows the
+successor function at each position. -/
+def Follows (step : Stage → Option Stage) : List Stage → Prop
+ | [] => True
+ | [a] => step a = none
+ | a :: b :: rest => step a = some b ∧ Follows step (b::rest)
+
+theorem schedule_follows (p : UniversalMachine.Program) (mode : GroupMode) (first last : Bool) :
+ Follows (successor p mode first last) (schedule p mode first last) := by
+ cases mode <;> cases first <;> cases last <;> by_cases he : p.extra = 0 <;>
+ simp (config := { decide := true }) [schedule,GroupMode.flag,prepareTail,Follows,successor,next,he,
+ destination,modeTarget,firstTarget,lastTarget]
+
+/-- Exact decomposition at any ordinary stage of the outer native program.
+The source path has its original binary choices. The remaining path starts
+with its specified transfer word and tag, retaining the cap on all reports. -/
+noncomputable def stageEquiv (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (g : Geometry) (lit : LiteralPrefix) (s : Stage) (fit : 21 ≤ 2^g.w) (f : ℕ) (st : Word g.w)
+ (m : Memory g.w) (inv : Word g.w → Memory g.w → Prop) (cap : List (Report g.w) → Prop)
+ (frame : LiveStageLink.TagFrame (Pieces.table (rows c p O))
+ (Pieces.word g lit ∘ Pieces.bank (rows c p O)) (Pieces.word g lit (.geometry Layout.stageTag)) s f inv)
+ (hi : inv st m) (tagged : m (Pieces.word g lit (.geometry Layout.stageTag)).val = LiveStageLink.tagWord g.w s) :
+ let T := Pieces.table (rows c p O)
+ let addr := Pieces.word g lit (.geometry Layout.stageTag)
+ let pub := Pieces.word g lit ∘ Pieces.bank (rows c p O)
+ (Σ a : LiveStageLink.Ordinary T (next p) pub addr s f st m, LiveStageLink.Remainder cap a) ≃
+ ActualPaths (machine c p O g lit).program (f+(LiveStageLink.dispatchEvents addr s).length) st m cap := by
+ dsimp only
+ unfold machine Pieces.machine Pieces.program
+ rw [Pieces.data_eq]
+ exact LiveStageLink.ordinaryEquiv fit frame hi tagged
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramSkeletonRun.lean b/lean/OAI/Computability/VPVNP/LiveProgramSkeletonRun.lean
new file mode 100644
index 0000000000..cba3cb63c6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramSkeletonRun.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.LiveLinkedEvaluatorFrame
+import OAI.Computability.VPVNP.LiveEvaluatorReindexSkeleton
+
+/-!
+# The linked runtime-skeleton sweep
+
+The native table writes one nonblank tape symbol for every bit of the
+zero-exponent runtime input. Its reports preserve both the linker tag and
+the four runtime operands. The final linked call writes the scatter tag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+
+open BurstRAM LiveStageLink LiveEvaluatorInitialize LiveEvaluatorReindexSkeleton
+open CompressorRecords
+open scoped Fin.CommRing
+
+variable {w t Z : ℕ}
+
+/-- Every returned native report writes only inside the allocated runtime
+interval. This also applies when replaying that report on another memory. -/
+theorem skeletonReports_outside (hw : 2 ≤ w) (pub : Fin 4 → Word w)
+ (width : (pub 0).val = Z) (total : (pub 1).val = t*Z)
+ (length : (pub 3).val = 2*(t*Z)+6*Z+4) (fit : (pub 2).val+(pub 3).val ≤ 2^w)
+ (s : Option (Word w)) (m : Memory w) (bits : List (List Bool)) (rs : List (Report w))
+ (active : ∀ st, s = some st → st < pub 3)
+ (run : runSegment (skeletonStage.instantiate w pub).program 28 s m bits = some rs) :
+ ∀ r ∈ rs, ∀ mem a, a < (pub 2).val ∨ (pub 2).val+(pub 3).val ≤ a → after mem r.events a = mem a := by
+ induction bits generalizing s m rs with
+ | nil =>
+ simp [runSegment] at run
+ subst rs
+ simp
+ | cons b bs ih =>
+ cases s with
+ | none => contradiction
+ | some st =>
+ have ha := active st rfl
+ have step := skeletonStage_call hw pub st m width total length ha b 0
+ dsimp only at step
+ rw [runSegment, step] at run
+ by_cases hb : b = []
+ · rw [ite_eq_left hb, Option.map_eq_some_iff] at run
+ obtain ⟨rest, hr, rfl⟩ := run
+ rw [List.forall_mem_cons]
+ constructor
+ · intro mem a h
+ change after mem (events _ _) a = _
+ have hav := Fin.lt_def.mp ha
+ have addr := Fin.val_add_eq_of_add_lt (a := pub 2) (b := st) (by omega)
+ rw [events_after, writeMemory, ite_eq_right (by omega)]
+ · apply ih _ _ rest _ hr
+ intro k hk
+ change (if st+1 = pub 3 then none else some (st+1)) = some k at hk
+ split at hk
+ · contradiction
+ · rename_i hn
+ obtain rfl := Option.some.inj hk
+ have hval : (st+1).val = st.val+1 := Fin.val_add_one_of_lt' (Nat.lt_of_le_of_lt (Fin.lt_def.mp ha) (pub 3).isLt)
+ have hne : (st+1).val ≠ (pub 3).val := fun he => hn (Fin.ext he)
+ have hav := Fin.lt_def.mp ha
+ change (st+1).val < (pub 3).val
+ omega
+ · simp [hb] at run
+
+variable (G : Group)
+
+/-- Base word address of the runtime skeleton's four operands, thirteen words past the advice
+frame base. -/
+abbrev skeletonBase := Pieces.word G.g G.lit (.geometry (Layout.adviceFrames G.constants+13))
+
+private theorem copied_tag {raw : List Bool} {base count : ℕ} {original out : Memory G.w}
+ (h : Copied raw base count original out)
+ (outside : G.addr.val < base ∨ base+count ≤ G.addr.val) (tag : Word G.w) :
+ Copied raw base count (writeMemory original G.addr tag) (writeMemory out G.addr tag) := by
+ constructor
+ · intro j hj
+ simp only [writeMemory, ite_eq_right (by omega : base+j ≠ G.addr.val)]
+ exact h.symbols j hj
+ · intro a ha
+ by_cases he : a = G.addr.val
+ · simp [writeMemory, he]
+ · simpa only [writeMemory, ite_eq_right he] using h.outside a ha
+
+/-- On the actual linked skeleton row, the canonical runtime word is written
+to the supplied tape base. At handoff the scatter tag is the only change
+beyond these writes, including on the reference memory for untouched cells. -/
+theorem skeletonRun (pub : Fin 4 → Word G.w) (m : Memory G.w) (hw : 2 ≤ G.w)
+ (width : (pub 0).val = Z) (total : (pub 1).val = t*Z)
+ (length : (pub 3).val = 2*(t*Z)+6*Z+4) (fit : (pub 2).val+(pub 3).val ≤ 2^G.w)
+ (data : Frame.data G.skeletonBase m = pub) (tag : G.tagged Stage.skeleton m)
+ (tagOutside : G.addr.val < (pub 2).val ∨ (pub 2).val+(pub 3).val ≤ G.addr.val)
+ (frameOutside : ∀ j : Fin 4, (G.skeletonBase+(j.val : Word G.w)).val < (pub 2).val ∨
+ (pub 2).val+(pub 3).val ≤ (G.skeletonBase+(j.val : Word G.w)).val)
+ (clock : 91 ≤ G.clock) :
+ let raw := EvaluatorProgramRawInput.runtime (fun _ : Fin t => (0 : Word Z))
+ ∃ out, Advice.Returning G.P G.clock raw.length 7 m (writeMemory out G.addr (tagWord G.w Stage.scatter)) ∧
+ Copied raw (pub 2).val raw.length m out ∧
+ Copied raw (pub 2).val raw.length (writeMemory m G.addr (tagWord G.w Stage.scatter))
+ (writeMemory out G.addr (tagWord G.w Stage.scatter)) := by
+ intro raw
+ obtain ⟨rs, run, halt, hc, hlen, hprobes⟩ := skeletonStage_sweep hw pub m width total length fit
+ have hlen' : raw.length = (pub 3).val := (EvaluatorProgramRawInput.runtime_length _).trans length.symm
+ have protect := skeletonReports_outside hw pub width total length fit (some 0) m _ rs
+ (fun st he => by
+ obtain rfl := Option.some.inj he
+ change 0 < (pub 3).val
+ omega) run
+ refine ⟨after m (eventLog rs), ?_, hc, copied_tag G hc (hlen'.symm ▸ tagOutside) _⟩
+ apply framedReturning (T := skeletonStage) (s := Stage.skeleton) (dest := Stage.scatter)
+ (fuel := 28) (b := 1) (base := G.skeletonBase) clock tag (by rfl) data (fun _ _ _ => rfl) run halt hlen hprobes
+ intro r hr u
+ refine ⟨protect r hr u G.addr.val tagOutside, ?_⟩
+ funext j
+ exact protect r hr u _ (frameOutside j)
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramTerminalStage.lean b/lean/OAI/Computability/VPVNP/LiveProgramTerminalStage.lean
new file mode 100644
index 0000000000..3b927c7045
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramTerminalStage.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.LiveProgramPairStages
+
+/-! # Path and cap at a terminal ordinary stage of the live table -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group
+open BurstRAM BurstRAM.PrivateRAM LiveStageLink
+open scoped Classical
+
+variable {G : Group} {s : Stage} {m : Memory G.w}
+
+/-- Relocation into the shared register and operand banks preserves every native report. -/
+theorem component_segment (G : Group) (s : Stage) (f : ℕ) (st : Option (Word G.w))
+ (m : Memory G.w) (bs : List (List Bool)) :
+ runSegment (sourceProgram G.T G.pub s) f st m bs =
+ runSegment (Pieces.component G.components s G.g G.lit) f st m bs := by
+ induction bs generalizing st m with
+ | nil => rfl
+ | cons b bs ih =>
+ cases st with
+ | none => rfl
+ | some st =>
+ simp only [runSegment,Pieces.component_eq]
+ cases execute (Pieces.component G.components s G.g G.lit) f
+ ((Pieces.component G.components s G.g G.lit).start st) m b with
+ | none => rfl
+ | some r => exact congrArg (Option.map (r :: ·)) (ih r.result (after m r.events))
+
+private theorem run_room {C : Type*} {P : BurstRAM.Program G.w C} {fuel : ℕ} {st : Option (Word G.w)}
+ {mem : Memory G.w} {bs : List (List Bool)} {rs : List (Report G.w)}
+ (h : runSegment P fuel st mem bs = some rs) : ∀ rep ∈ rs, rep.events.length < fuel := by
+ induction bs generalizing st mem rs with
+ | nil => simp only [runSegment,Option.some.injEq] at h; subst rs; simp
+ | cons b bs ih =>
+ cases st with
+ | none => contradiction
+ | some st =>
+ cases he : execute P fuel (P.start st) mem b with
+ | none => simp [runSegment,he] at h
+ | some rep =>
+ simp only [runSegment,he,Option.map_eq_some_iff] at h
+ obtain ⟨rest,hr,rfl⟩ := h
+ exact List.forall_mem_cons.mpr ⟨(execute_spec he).1.length_lt,ih hr⟩
+
+private theorem exit_eq (G : Group) (s : Stage) (h : G.nextStage s = none) (r : Report G.w) :
+ exitReport G.nextStage G.addr s r = r := by
+ cases r with
+ | mk ev res => cases res <;> simp [exitReport,h]
+
+/-- The dispatcher adds its own read at every terminal-stage call. The
+final report halts without transferring, so no further choices are allowed. -/
+noncomputable def terminalEquiv (A : Entry G s m) (hnext : G.nextStage s = none)
+ (cap : List (Report G.w) → Prop) :
+ ActualPaths (Pieces.component G.components s G.g G.lit) (G.clockAt s) 0 m
+ (fun rs => cap (rs.map (linkedReport G.nextStage G.addr s))) ≃
+ ActualPaths G.P G.clock 0 m cap := by
+ let toOrd (a : ActualPaths (Pieces.component G.components s G.g G.lit) (G.clockAt s) 0 m
+ (fun rs => cap (rs.map (linkedReport G.nextStage G.addr s)))) : G.StagePaths s m := ⟨a.val, by
+ obtain ⟨rs,hr,hh,_⟩ := a.property
+ refine ⟨rs,(component_segment ..).trans hr,hh,?_⟩
+ intro rep hrep
+ change (exitReport G.nextStage G.addr s rep).events.length < G.clockAt s
+ rw [exit_eq G s hnext]; exact run_room hr rep hrep⟩
+ let add (a : ActualPaths (Pieces.component G.components s G.g G.lit) (G.clockAt s) 0 m
+ (fun rs => cap (rs.map (linkedReport G.nextStage G.addr s)))) :
+ Σ p : G.StagePaths s m, Remainder cap p := ⟨toOrd a,⟨[],[],rfl,by simp [transferState,hnext,endState],by
+ obtain ⟨rs,hr,_,hc⟩ := a.property
+ have he := (ordinaryRun (toOrd a)).symm.trans ((component_segment ..).trans hr)
+ simpa only [← Option.some.inj he,List.append_nil] using hc⟩⟩
+ let e := ordinaryEquiv (next := G.nextStage) (cap := cap) G.tagFit A.frame A.ready A.tag
+ apply Equiv.trans (Equiv.ofBijective add ?_)
+ · simpa only [G.clock_add s] using e
+ constructor
+ · intro a b h
+ exact Subtype.ext (congrArg (fun x => x.1.val) h)
+ · rintro ⟨p,rest⟩
+ obtain ⟨bs,rs,hr,_,hc⟩ := rest
+ have ht : transferState (w := G.w) G.nextStage s = none := by simp [transferState,hnext]
+ rw [ht] at hr
+ cases bs with
+ | cons _ _ => contradiction
+ | nil =>
+ simp only [runSegment,Option.some.injEq] at hr
+ subst rs
+ refine ⟨⟨p.val,ordinaryReports p,(component_segment ..).symm.trans (ordinaryRun p),
+ p.property.choose_spec.2.1,by simpa only [List.append_nil] using hc⟩,?_⟩
+ rfl
+
+end LiveProgram.PairStages.Group
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramUnit.lean b/lean/OAI/Computability/VPVNP/LiveProgramUnit.lean
new file mode 100644
index 0000000000..0c65acc7a3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramUnit.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.LiveProgramHandoffs
+import OAI.Computability.VPVNP.LiveProgramPairStages
+
+/-!
+# The live unit branch after header verification
+
+Once the physical header has checked both modes and every padding bit, the
+unit group has one possible sequence of native bursts. The last burst costs
+three units, including the outer tag read and the checked mode read.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.UnitGroup
+open BurstRAM BurstRAM.PrivateRAM PairStages
+
+variable (G : Group)
+
+/-- Terminating report of the unit-mode router after header verification, with one outer tag
+read and one mode read. -/
+def report : Report G.w := Router.mode.outerReport G.evaluator G.g G.lit
+ (Router.mode.haltReport G.g G.lit 0 0)
+
+theorem report_result : (report G).result = none := rfl
+
+theorem report_probes : (report G).probes = 2 := rfl
+
+theorem cap_iff (S H : ℕ) (header : List (Report G.w)) :
+ withinCaps S H (header++[report G]) ↔
+ RAMBuckets.cost Report.probes header + 3 ≤ S*H ∧
+ (∀ r ∈ header, 1+r.probes ≤ H) ∧ 3 ≤ H := by
+ simp [withinCaps,RAMBuckets.cost,report_probes,or_imp,forall_and]
+
+/-- The conclusion records every native report, as well as the entire
+choice stream. It holds at the same clock that executed the header. -/
+theorem run {n : ℕ} {m : Memory G.w} {logs : List (Report G.w)}
+ (hw : 2 ≤ G.w) (hc : 57 ≤ G.clock) (hr : runSegment G.P G.clock (some 0) m (List.replicate n []) = some logs)
+ (hcontinue : endState (some 0) logs = some 0)
+ (mode : (after m (eventLog logs)) ((Router.mode.data G.g G.lit) 0).val = 0)
+ (tagged : G.tagged Stage.mode (after m (eventLog logs))) :
+ runSegment G.P G.clock (some 0) m (List.replicate (n+1) []) = some (logs ++ [report G]) ∧
+ endState (some 0) (logs ++ [report G]) = none := by
+ have hex := (Router.unit_accept_iff G.constants G.evaluator G.pair G.g G.lit G.tagFit hw
+ (fun rs => rs = [report G]) G.clock hc 0 (after m (eventLog logs)) mode tagged [[]]).2 ⟨rfl,rfl⟩
+ obtain ⟨_,ht,_,rfl⟩ := hex
+ constructor
+ · rw [List.replicate_add,PrimedSchedule.runSegment_append,hr]
+ simp only [Option.bind_some,hcontinue,show List.replicate 1 ([] : List Bool) = [[]] by rfl,G.program_eq,ht,Option.map_some]
+ · rw [endState_append,hcontinue]; exact report_result G
+
+/-- Arbitrary valid choice streams in unit mode agree with the unique forced
+trace, even if the cap examines every report rather than just the total cost. -/
+theorem accepted_iff {n : ℕ} {m : Memory G.w} {logs : List (Report G.w)}
+ (hw : 2 ≤ G.w) (hc : 57 ≤ G.clock) (hr : runSegment G.P G.clock (some 0) m (List.replicate n []) = some logs)
+ (hcontinue : endState (some 0) logs = some 0)
+ (mode : (after m (eventLog logs)) ((Router.mode.data G.g G.lit) 0).val = 0)
+ (tagged : G.tagged Stage.mode (after m (eventLog logs))) (cap : List (Report G.w) → Prop) (bs : List (List Bool)) :
+ (∃ rs, runSegment G.P G.clock (some 0) m bs = some rs ∧ endState (some 0) rs = none ∧ cap rs) ↔
+ bs = List.replicate (n+1) [] ∧ cap (logs++[report G]) := by
+ obtain ⟨full,done⟩ := run G hw hc hr hcontinue mode tagged
+ constructor
+ · rintro ⟨rs,h,hh,hcap⟩
+ obtain ⟨hbs,rfl⟩ := accepted_empty_unique full done h hh
+ exact ⟨hbs,hcap⟩
+ · rintro ⟨rfl,h⟩; exact ⟨_,full,done,h⟩
+
+/-- A valid unit group contributes the integer one at every permitted clock
+and resource cap covering its verified trace. -/
+theorem card_one {n : ℕ} {m : Memory G.w} {logs : List (Report G.w)}
+ (hw : 2 ≤ G.w) (hc : 57 ≤ G.clock) (hr : runSegment G.P G.clock (some 0) m (List.replicate n []) = some logs)
+ (hcontinue : endState (some 0) logs = some 0)
+ (mode : (after m (eventLog logs)) ((Router.mode.data G.g G.lit) 0).val = 0)
+ (tagged : G.tagged Stage.mode (after m (eventLog logs))) (cap : List (Report G.w) → Prop)
+ (hcap : cap (logs++[report G])) : Nat.card (ActualPaths G.P G.clock 0 m cap) = 1 := by
+ apply Nat.card_eq_one_iff_exists.mpr
+ let eqv := accepted_iff G hw hc hr hcontinue mode tagged cap
+ refine ⟨⟨_, (eqv _).2 ⟨rfl,hcap⟩⟩,?_⟩
+ intro y; exact Subtype.ext ((eqv y.val).1 y.property).1
+
+end LiveProgram.UnitGroup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveProgramWordFit.lean b/lean/OAI/Computability/VPVNP/LiveProgramWordFit.lean
new file mode 100644
index 0000000000..ef759fb6ad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveProgramWordFit.lean
@@ -0,0 +1,233 @@
+import OAI.Computability.VPVNP.LiveLayoutWordFit
+import OAI.Computability.VPVNP.LiveHeaderSitePowers
+import OAI.Computability.VPVNP.LiveProgram
+import OAI.Computability.VPVNP.RAMTapePublicInputOperands
+
+/-!
+# Word fit of the executable live program's public bank
+
+The disjoint operand bank includes all nested header rows and the outer
+dispatch tag. The pair's two literal inputs carry the original program
+prefix. All remaining slots use length-only expressions whose intermediate
+results fit at a common threshold in the input length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+open Filter
+open RAMTape.InputOperandMachine
+
+/-- A literal input bypasses geometry arithmetic in the native bank loader. -/
+def InputOperand.SitePowers : InputOperand → Prop
+ | .geometry e => e.SitePowers
+ | .prefixLength | .prefixWord => True
+
+private theorem vec_all {α : Type*} {P : α → Prop} {n : ℕ} (a : α) (v : Fin n → α) :
+ (∀ j, P (Matrix.vecCons a v j)) ↔ P a ∧ ∀ j, P (v j) :=
+ ⟨fun h => ⟨h 0, fun j => h j.succ⟩,fun ⟨ha,hv⟩ => Fin.cases ha hv⟩
+
+private theorem add_site (a b : PublicExpr) : (a+b).SitePowers ↔ a.SitePowers ∧ b.SitePowers := Iff.rfl
+private theorem mul_site (a b : PublicExpr) : (a*b).SitePowers ↔ a.SitePowers ∧ b.SitePowers := Iff.rfl
+private theorem clog_site (a : PublicExpr) : a.clog2.SitePowers ↔ a.SitePowers := Iff.rfl
+private theorem lit_site (v : ℕ) : (OfNat.ofNat v : PublicExpr).SitePowers := True.intro
+
+local macro "site_vec" : tactic => `(tactic|
+ simp [vec_all,add_site,mul_site,clog_site,lit_site,
+ HeaderLayout.capacity,HeaderLayout.exterior,HeaderLayout.exponent,HeaderLayout.config,
+ HeaderLayout.advice,HeaderLayout.rightIndex,HeaderLayout.leftIndex,HeaderLayout.population,
+ HeaderLayout.high,HeaderLayout.index,HeaderLayout.firstTail,HeaderLayout.mode,HeaderLayout.flag,
+ HeaderLayout.width, *] <;> repeat' first | exact True.intro | assumption | constructor)
+
+namespace StageOperands
+
+private theorem router_safe (e : PublicExpr) (he : e.SitePowers) : ∀ j, (router e j).SitePowers := by
+ unfold router
+ site_vec
+
+private theorem nomination_safe (c : Constants) : ∀ j, (nomination c j).SitePowers := by
+ unfold nomination
+ site_vec
+
+private theorem auxiliary_safe (c : Constants) : ∀ j, (auxiliary c j).SitePowers := by
+ unfold auxiliary
+ site_vec
+
+private theorem auxiliaryCopy_safe (c : Constants) : ∀ j, (auxiliaryCopy c j).SitePowers := by
+ unfold auxiliaryCopy
+ site_vec
+
+private theorem pair_safe (c : Constants) : ∀ j, (pair c j).SitePowers := by
+ intro j
+ fin_cases j <;> simp [pair,InputOperand.SitePowers,HeaderLayout.index,add_site] <;> exact True.intro
+
+private theorem exponents_safe (c : Constants) : ∀ j, (exponents c j).SitePowers := by
+ unfold exponents
+ site_vec
+
+private theorem control_safe (c : Constants) (e : PublicExpr) (he : e.SitePowers) :
+ ∀ j, (control c e j).SitePowers := by
+ unfold control
+ site_vec
+
+private theorem lengthPack_safe (c : Constants) : ∀ j, (lengthPack c j).SitePowers := by
+ unfold lengthPack
+ site_vec
+
+private theorem adviceFrames_safe (c : Constants) : ∀ j, (adviceFrames c j).SitePowers := by
+ unfold adviceFrames
+ site_vec
+
+private theorem orderPack_safe (c : Constants) : ∀ j, (orderPack c j).SitePowers := by
+ unfold orderPack
+ site_vec
+
+private theorem gather_safe (c : Constants) (s : LiveHeaderDescriptors.Side) (e : PublicExpr)
+ (he : e.SitePowers) : ∀ j, (gather c s e j).SitePowers := by
+ cases s <;> unfold gather <;> site_vec
+
+private theorem transition_safe (c : Constants) : ∀ j, (transition c j).SitePowers := by
+ unfold transition
+ site_vec
+
+end StageOperands
+
+open StageOperands
+
+set_option maxRecDepth 4096 in
+private theorem rows_sitePowers (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (header : ∀ j, (HeaderLayout.operands c.lengths Layout.header j).SitePowers)
+ (s : Stage) : ∀ j, ((rows c p O s).operands j).SitePowers := by
+ fin_cases s
+ · exact header
+ · exact router_safe _ (by site_vec)
+ · exact nomination_safe c
+ · exact auxiliary_safe c
+ · exact auxiliaryCopy_safe c
+ · exact pair_safe c
+ · exact exponents_safe c
+ · exact router_safe _ (by site_vec)
+ · exact control_safe c _ (Layout.oldState_sitePowers c)
+ · exact lengthPack_safe c
+ · exact adviceFrames_safe c
+ · exact fun _ => Layout.adviceFrames_sitePowers c
+ · exact orderPack_safe c
+ · exact fun _ => ⟨Layout.adviceFrames_sitePowers c,True.intro⟩
+ · exact fun _ => ⟨Layout.adviceFrames_sitePowers c,True.intro⟩
+ · exact fun _ => ⟨Layout.adviceFrames_sitePowers c,True.intro⟩
+ · exact gather_safe c .left _ (Layout.oldState_sitePowers c)
+ · exact router_safe _ (by site_vec)
+ · exact control_safe c _ (Layout.newState_sitePowers c)
+ · exact gather_safe c .right _ (Layout.newState_sitePowers c)
+ · exact transition_safe c
+
+attribute [local irreducible] Pieces.count
+
+theorem operand_at_row (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (s : Stage) (j : Fin (rows c p O s).count) :
+ operand c p O ((Pieces.operandEmbedding (rows c p O) s j).castSucc) = (rows c p O s).operands j := by
+ unfold operand Pieces.operand
+ rw [Fin.snoc_castSucc,Pieces.bank_at]
+
+/-- All 21 rows and the outer tag satisfy the required syntax restriction.
+The bounded header rows and the outer pair's literal-prefix slots use their
+actual positions in the two nested operand banks. -/
+theorem operand_sitePowers (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (j : Fin (Pieces.count (rows c p O)+1)) : (operand c p O j).SitePowers := by
+ have hh := HeaderLayout.operands_sitePowers c.lengths_h_sitePowers c.lengths_delta_sitePowers
+ c.lengths_advice_sitePowers c.lengths_e_sitePowers c.lengths_config_sitePowers Layout.header_sitePowers
+ refine Fin.lastCases (n := Pieces.count (rows c p O)) ?_ (fun i => ?_) j
+ · simpa only [operand,Pieces.operand,Fin.snoc_last,InputOperand.SitePowers] using Layout.stageTag_sitePowers
+ · simp only [operand,Pieces.operand,Fin.snoc_castSucc,Pieces.bank]
+ exact rows_sitePowers c p O hh _ _
+
+/-- The two literal words in the compressed-pair row bypass the arithmetic
+expression evaluator. Their positions are relocated by the actual linker. -/
+theorem operand_pair_literals (c : Constants) (p : UniversalMachine.Program) (O : PairTable) :
+ operand c p O ((Pieces.operandEmbedding (rows c p O) Stage.pair (0 : Fin 11)).castSucc) = .prefixWord ∧
+ operand c p O ((Pieces.operandEmbedding (rows c p O) Stage.pair (1 : Fin 11)).castSucc) = .prefixLength := by
+ exact ⟨(operand_at_row c p O Stage.pair (0 : Fin 11)).trans rfl,
+ (operand_at_row c p O Stage.pair (1 : Fin 11)).trans rfl⟩
+
+/-- No other public row positions request a literal prefix value. -/
+theorem row_literal_positions (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (s : Stage) (j : Fin (rows c p O s).count) :
+ ((rows c p O s).operands j = .prefixWord ↔ s = Stage.pair ∧ j.val = 0) ∧
+ ((rows c p O s).operands j = .prefixLength ↔ s = Stage.pair ∧ j.val = 1) := by
+ by_cases pair : s = Stage.pair
+ · subst s
+ change Fin 11 at j
+ change (StageOperands.pair c j = .prefixWord ↔ Stage.pair = Stage.pair ∧ j.val = 0) ∧
+ (StageOperands.pair c j = .prefixLength ↔ Stage.pair = Stage.pair ∧ j.val = 1)
+ fin_cases j <;> simp [StageOperands.pair]
+ · have geom : ∃ e, (rows c p O s).operands j = .geometry e := by
+ fin_cases s <;> first | exact ⟨_,rfl⟩ | contradiction
+ obtain ⟨e,he⟩ := geom
+ simp [he,pair]
+
+private theorem geometryOnly_safe {k : ℕ} (args : Fin k → InputOperand) (h : ∀ i, (args i).SitePowers) :
+ ∀ i, (geometryOnly args i).SitePowers := by
+ intro i
+ cases he : args i with
+ | geometry e => simpa only [geometryOnly,he] using (show e.SitePowers by simpa only [he,InputOperand.SitePowers] using h i)
+ | prefixWord | prefixLength => simp only [geometryOnly,he]; exact True.intro
+
+private theorem geometry_and_literals {k : ℕ} (args : Fin k → InputOperand) (lit : LiteralPrefix)
+ (g : Geometry) (modulus : ℕ) (ha : ∀ i, (geometryOnly args i).Fits g modulus)
+ (hl : lit.length < modulus) (hv : lit.value < modulus) :
+ ∀ j, match args j with
+ | .geometry e => e.Fits g modulus
+ | a => a.eval g lit < modulus := by
+ intro j
+ cases he : args j with
+ | geometry e => simpa only [geometryOnly,he] using ha j
+ | prefixLength => exact hl
+ | prefixWord => exact hv
+
+/-- Simultaneous bounds on every intermediate arithmetic word of the
+concrete operand-loading routine, including each nested header expression. -/
+theorem eventually_operand_geometry_fits (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ {B : ℕ} (hB : 1 ≤ B) {H : ℕ → ℕ} (hH : PolynomiallyBounded H) :
+ ∀ᶠ n in atTop, ∀ j, (geometryOnly (operand c p O) j).Fits (paperGeometry B H n) (2^CursorBounds.wordBits B n) := by
+ exact PublicExpr.fits_bank hB hH _ (geometryOnly_safe _ (operand_sitePowers c p O))
+
+/-- A fixed literal prefix also fits at a common length threshold, yielding
+exact unpacked operand values in addition to every intermediate word bound. -/
+theorem eventually_operand_fits (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ (lit : LiteralPrefix) {B : ℕ} (hB : 1 ≤ B) {H : ℕ → ℕ} (hH : PolynomiallyBounded H) :
+ ∀ᶠ n in atTop, ∀ j,
+ match operand c p O j with
+ | .geometry e => e.Fits (paperGeometry B H n) (2^CursorBounds.wordBits B n)
+ | a => a.eval (paperGeometry B H n) lit < 2^CursorBounds.wordBits B n := by
+ have litFits (v : ℕ) : ∀ᶠ n in atTop, v < 2^CursorBounds.wordBits B n :=
+ ((PublicExpr.SitePowers.fits hB hH (show (PublicExpr.lit v).SitePowers from True.intro)).2).mono fun _ h => h.1
+ filter_upwards [eventually_operand_geometry_fits c p O hB hH,litFits lit.length,litFits lit.value] with n h hl hv
+ exact geometry_and_literals (operand c p O) lit _ _ h hl hv
+
+/-- At the same eventual threshold the executable loader fills every
+physical slot with the public operand prescribed by the live machine. -/
+theorem eventually_load_operands (c : Constants) (p : UniversalMachine.Program) (O : PairTable)
+ {B : ℕ} (hB : 1 ≤ B) {H : ℕ → ℕ} (hH : PolynomiallyBounded H) :
+ ∀ᶠ n in atTop, let g := paperGeometry B H n
+ let args := operand c p O
+ ∀ (lit : LiteralPrefix) (st : BurstRAM.Word g.w)
+ (rs : Fin (registers args) → BurstRAM.Word g.w) (log : BurstRAM.PrivateRAM.WriteLog g.w),
+ ∃ t ≤ RAMTape.PublicExprMachine.coefficient (geometryOnly args)*(g.w+1)^2+
+ (Pieces.count (rows c p O)+1)*(8*g.w+3)+2,
+ ∃ out : Fin (registers args) → BurstRAM.Word g.w,
+ (RAMTape.InputOperandMachine.program args).Runs t
+ (RAMTape.ISA.bank (input g lit) st rs log) (RAMTape.ISA.bank (input g lit) st out log) ∧
+ ∀ j, out (slot args j) = publicData c p O g lit j := by
+ filter_upwards [eventually_operand_geometry_fits c p O hB hH] with n hf
+ dsimp only
+ intro lit st rs log
+ exact runs (operand c p O) (paperGeometry B H n) lit hf st rs log
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePublicAssembler.lean b/lean/OAI/Computability/VPVNP/LivePublicAssembler.lean
new file mode 100644
index 0000000000..344b660132
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePublicAssembler.lean
@@ -0,0 +1,173 @@
+import OAI.Computability.VPVNP.LivePublicPaperParser
+import OAI.Computability.VPVNP.LivePublicIncidentWidth
+import OAI.Computability.VPVNP.PairedChain
+
+/-!
+# Assembler operands for the primed pair
+
+The index width is the one-based group's width. The cut field is the maximum
+capacity shared by every pair. Actual cut lengths live in the three initial
+RAM cells and therefore never occur in this public table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.AssemblerPublic
+
+open PrimedInputRAM BurstRAM
+
+/-- Constants of the fixed live program. -/
+structure Spec where
+ /-- The universal-machine program whose literal prefix is placed in the primed pair inputs. -/
+ program : UniversalMachine.Program
+ /-- Exponent controlling the group index width and the height of the first half of the chain. -/
+ groupExp : ℕ
+ /-- Exponent giving the distributed advice length as a power of the input length. -/
+ adviceExp : ℕ
+ /-- Exponent giving the basic cut block width as a power of the input length. -/
+ cutExp : ℕ
+
+/-- Compute the site's address and RAM word widths from the address multiplier and input
+length, and attach the supplied bucket capacity. -/
+def geometry (B n H : ℕ) : Geometry :=
+ ⟨n,addressWidth B n,H,CursorBounds.wordBits B n⟩
+
+namespace Spec
+
+variable (s : Spec)
+
+/-- The paired chain's actual index, advice, and cut lengths for the specified pair at input
+length n. -/
+abbrev lengths (n : ℕ) (i : Fin (2^(n^s.groupExp-1))) :=
+ PairedChain.lengths (n^s.groupExp-1) (n^s.cutExp) (n^s.adviceExp) i
+
+/-- Public expression for the number of sites in one group, two raised to the site-address
+width. -/
+def R : PublicExpr := .pow2 .d
+/-- Total cells in the input rectangle spanning both groups, twice the number of sites per
+group times the input length. -/
+def cells : PublicExpr := ((.lit 2 : PublicExpr).mul R).mul .n
+/-- Public bit width of the one-based group index, one plus the input length raised to the
+group exponent. -/
+def index : PublicExpr := ((.n : PublicExpr).natPow s.groupExp).add (.lit 1)
+/-- Number of advice bits in a primed row, given by the input length raised to the advice
+exponent. -/
+def advice : PublicExpr := (.n : PublicExpr).natPow s.adviceExp
+/-- Common capacity reserved for a cut, given by the input length raised to the sum of the
+group and cut exponents. -/
+def capacity : PublicExpr := (.n : PublicExpr).natPow (s.groupExp+s.cutExp)
+
+/-- The sixteen public operands for primed pair assembly, including geometry, virtual scratch
+base, literal prefix, incident widths, and cut capacity. -/
+def table (virtual : PublicExpr) (j : Fin 16) : PublicExpr :=
+ match j.val with
+ | 0 => cells
+ | 1 => .n
+ | 2 => R
+ | 3 => .d
+ | 4 => .w
+ | 5 => .H
+ | 6 => virtual
+ | 7 => .lit (UniversalMachine.programPrefix s.program).length
+ | 8 => IncidentPublic.incident
+ | 9 => s.index
+ | 10 => s.advice
+ | 11 => s.capacity
+ | 12 => .lit (Opcodes.packedPrefix s.program).val
+ | 13 => IncidentPublic.block
+ | 14 => IncidentPublic.successor
+ | _ => IncidentPublic.bothSuccessors
+
+variable {B n H : ℕ} {i : Fin (2^(n^s.groupExp-1))}
+ (Q : Layout (s.lengths n i) n (addressWidth B n) H (CursorBounds.wordBits B n))
+ (virtual : PublicExpr)
+
+private theorem group_width (hn : 0 < n) : (s.lengths n i).index = n^s.groupExp + 1 := by
+ change n^s.groupExp - 1 + 2 = _
+ have h := Nat.pow_pos hn (n := s.groupExp)
+ omega
+
+private theorem cut_capacity (hn : 0 < n) : (s.lengths n i).cutCapacity = n^(s.groupExp+s.cutExp) := by
+ change (n^s.groupExp-1+1)*n^s.cutExp = _
+ have h := Nat.pow_pos hn (n := s.groupExp)
+ rw [show n^s.groupExp-1+1 = n^s.groupExp by omega,pow_add]
+
+/-- The sixteen expressions are the native assembler's public words before reduction modulo the word width. -/
+theorem table_eval (hp : Q.program = s.program) (hv : virtual.eval (geometry B n H) = Q.scratchBase)
+ (hn : 0 < n) (j : Fin 16) : (s.table virtual j).eval (geometry B n H) = Opcodes.pubNat Q j := by
+ have hk : n^s.groupExp-1+1 = n^s.groupExp := by
+ have h := Nat.pow_pos hn (n := s.groupExp)
+ omega
+ have hpack := congrArg (fun p => (Opcodes.packedPrefix p).val) hp
+ fin_cases j <;> simp [table, cells, R, index, advice, capacity, Opcodes.pubNat, hp,
+ hk, pow_add, IncidentPublic.successor, IncidentPublic.bothSuccessors,
+ geometry, PublicExpr.eval, PrimedInputRAM.positions, PairedChain.lengths, lengths]
+ · exact hv
+ · exact hpack.symm
+ · omega
+
+/-- Word fit for every intermediate of all sixteen assembler expressions. -/
+theorem table_fits (F : Opcodes.ParameterFit Q) (hp : Q.program = s.program)
+ (hv : virtual.Fits (geometry B n H) (2^CursorBounds.wordBits B n))
+ (hB : 1 ≤ B) (hn : 2 ≤ n) (j : Fin 16) :
+ (s.table virtual j).Fits (geometry B n H) (2^CursorBounds.wordBits B n) := by
+ let g := geometry B n H
+ let w := CursorBounds.wordBits B n
+ let r := addressWidth B n
+ let Fit := PublicExpr.Fits g (2^w)
+ have hpos : 0 < n := by omega
+ have hr : 1 ≤ r := Nat.mul_pos hB (Nat.clog_pos (by decide) hn)
+ have fn : Fit .n := ⟨Opcodes.pubNat_lt Q F 1,trivial⟩
+ have fd : Fit .d := ⟨Opcodes.pubNat_lt Q F 3,trivial⟩
+ have fw : Fit .w := ⟨Opcodes.pubNat_lt Q F 4,trivial⟩
+ have fH : Fit .H := ⟨Opcodes.pubNat_lt Q F 5,trivial⟩
+ have fR : Fit R := ⟨Opcodes.pubNat_lt Q F 2,fd⟩
+ have hcells : (2*2^r)*n < 2^w := Opcodes.pubNat_lt Q F 0
+ have hrow := Nat.le_mul_of_pos_right (2*2^r) hpos
+ have hR := Nat.two_pow_pos r
+ have f2 : Fit (.lit 2) := ⟨by change 2 < _; omega,trivial⟩
+ have frows : Fit ((.lit 2 : PublicExpr).mul R) := ⟨by change 2*2^r < _; omega,f2,fR⟩
+ have fcells : Fit cells := ⟨hcells,frows,fn⟩
+ have fprefix : Fit (.lit (UniversalMachine.programPrefix s.program).length) := ⟨by
+ change (UniversalMachine.programPrefix s.program).length < _
+ rw [← hp]; exact Opcodes.pubNat_lt Q F 7,trivial⟩
+ have fpacked : Fit (.lit (Opcodes.packedPrefix s.program).val) := ⟨by
+ change (Opcodes.packedPrefix s.program).val < _
+ rw [← hp]; exact Opcodes.pubNat_lt Q F 12,trivial⟩
+ have hindex : n^s.groupExp+1 < 2^w := by
+ rw [← group_width (i := i) s hpos]; exact Opcodes.pubNat_lt Q F 9
+ have fgroup := PublicExpr.fits_natPow fn hpos s.groupExp (show n^s.groupExp < 2^w by omega)
+ have findex : Fit s.index := ⟨by change ((.n : PublicExpr).natPow s.groupExp).eval g+1 < _
+ rw [PublicExpr.eval_natPow]; exact hindex,
+ fgroup,⟨by change 1 < _; omega,trivial⟩⟩
+ have fadv : Fit s.advice := PublicExpr.fits_natPow fn hpos _ (Opcodes.pubNat_lt Q F 10)
+ have hcap : n^(s.groupExp+s.cutExp) < 2^w := by
+ rw [← cut_capacity (i := i) s hpos]; exact Opcodes.pubNat_lt Q F 11
+ have fcap : Fit s.capacity := PublicExpr.fits_natPow fn hpos _ hcap
+ obtain ⟨fblock,fs,fss,fincident⟩ := IncidentPublic.fits Q F hr rfl g rfl rfl rfl
+ fin_cases j
+ · exact fcells
+ · exact fn
+ · exact fR
+ · exact fd
+ · exact fw
+ · exact fH
+ · exact hv
+ · exact fprefix
+ · exact fincident
+ · exact findex
+ · exact fadv
+ · exact fcap
+ · exact fpacked
+ · exact fblock
+ · exact fs
+ · exact fss
+
+end Spec
+end LiveProgram.AssemblerPublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePublicCounter.lean b/lean/OAI/Computability/VPVNP/LivePublicCounter.lean
new file mode 100644
index 0000000000..dad9e60ade
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePublicCounter.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.LivePublicAssembler
+import OAI.Computability.VPVNP.LivePublicVirtualSites
+import OAI.Computability.VPVNP.LiveProgramLayout
+
+/-!
+# Values of the coefficient counter's public bank
+
+At a given program prefix, the 34 scalar values agree with the operands
+read by the auxiliary machine, uniformly over its pairs, exterior bits and
+nominations. The physical loader of these values reads the prefix from
+the input tape, as proved in `LivePublicCounterOperands`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CounterPublic
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter
+
+/-- Use the supplied program and the live chain, advice, and cut powers as the fixed primed
+assembler specification. -/
+def spec (p : UniversalMachine.Program) (c : Constants) : AssemblerPublic.Spec :=
+ ⟨p,c.chainPower,c.advicePower,c.deltaPower⟩
+
+/-- The coefficient counter's 34 public length expressions, combining the primed assembler,
+paper grammar parser, and call schedule. -/
+def table (p : UniversalMachine.Program) (c : Constants) : Fin 34 → PublicExpr :=
+ (ParserPublic.paperInputs ((spec p c).table virtualSites) c.circuitExponent).table
+
+variable (p : UniversalMachine.Program) (c : Constants) {B n H : ℕ}
+ {i : Fin (2^(n^c.chainPower-1))}
+ (Q : PrimedInputRAM.Layout ((spec p c).lengths n i) n (addressWidth B n) H (CursorBounds.wordBits B n))
+ (D : Data Q (n^(c.circuitExponent+5)))
+
+/-- Every output and every intermediate is correct in an actual fitted parser layout. -/
+theorem correct (hB : 1 ≤ B) (hn : 2 ≤ n) (hp : Q.program = p)
+ (hbase : Q.scratchBase = 2^CursorBounds.virtualBits B n) (hf : D.Fits) (hroot : D.root.val = 0)
+ (j : Fin 34) :
+ Fin.ofNat (2^CursorBounds.wordBits B n) ((table p c j).eval (AssemblerPublic.geometry B n H)) = D.pub j ∧
+ (table p c j).Fits (AssemblerPublic.geometry B n H) (2^CursorBounds.wordBits B n) := by
+ have he : virtualSites.eval (AssemblerPublic.geometry B n H) = Q.scratchBase := by
+ rw [hbase]
+ exact virtualSites_eval _ hn
+ have hb : 2 ^ CursorBounds.virtualBits B n < 2 ^ CursorBounds.wordBits B n := by
+ rw [← hbase]
+ exact PrimedInputRAM.Opcodes.pubNat_lt Q hf.assembler 6
+ have hvirt := virtualSites_fits (H := H) hB hn hb
+ apply ParserPublic.paper_table D _ _ _ hf hroot _ j
+ · exact (spec p c).table_eval Q virtualSites hp he (by omega)
+ · exact (spec p c).table_fits Q virtualSites hf.assembler hp hvirt hB hn
+
+end LiveProgram.CounterPublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePublicCounterOperands.lean b/lean/OAI/Computability/VPVNP/LivePublicCounterOperands.lean
new file mode 100644
index 0000000000..8226e654df
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePublicCounterOperands.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.LivePublicCounterPrefix
+import OAI.Computability.VPVNP.RAMTapePublicInputOperands
+
+/-! # The auxiliary public table in the live linker's operand format -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CounterPublic
+
+open BurstRAM PrimedCounter RAMTape.PublicExprMachine
+
+/-- The length and packed word of the supplied universal-machine program's literal prefix. -/
+def actualPrefix (p : UniversalMachine.Program) : LiteralPrefix :=
+ ⟨(UniversalMachine.programPrefix p).length,(PrimedInputRAM.Opcodes.packedPrefix p).val⟩
+
+/-- Positions 7 and 12 come from the input prefix. Every other operand uses geometry arithmetic. -/
+def operands (c : Constants) (j : Fin 34) : InputOperand :=
+ if j.val = 7 then .prefixLength else if j.val = 12 then .prefixWord else .geometry (shape c j)
+
+variable (c : Constants) {p : UniversalMachine.Program} {B n H : ℕ}
+ {i : Fin (2^(n^c.chainPower-1))}
+ (Q : PrimedInputRAM.Layout ((spec p c).lengths n i) n (addressWidth B n) H (CursorBounds.wordBits B n))
+ (D : Data Q (n^(c.circuitExponent+5)))
+
+theorem operands_correct (hB : 1 ≤ B) (hn : 2 ≤ n) (hp : Q.program = p)
+ (hbase : Q.scratchBase = 2^CursorBounds.virtualBits B n) (hf : D.Fits) (hroot : D.root.val = 0)
+ (j : Fin 34) :
+ let g := AssemblerPublic.geometry B n H
+ Pieces.word g (actualPrefix p) (operands c j) = D.pub j ∧
+ match operands c j with
+ | .geometry e => e.Fits g (2^g.w)
+ | a => a.eval g (actualPrefix p) < 2^g.w := by
+ let g := AssemblerPublic.geometry B n H
+ have hc := correct p c Q D hB hn hp hbase hf hroot j
+ by_cases h7 : j.val = 7
+ · have he : j = 7 := Fin.ext h7
+ subst j
+ have hval : (UniversalMachine.programPrefix p).length < 2^g.w := by
+ rw [← hp]; exact PrimedInputRAM.Opcodes.pubNat_lt Q hf.assembler 7
+ exact ⟨hc.1,hval⟩
+ by_cases h12 : j.val = 12
+ · have he : j = 12 := Fin.ext h12
+ subst j
+ have hval : (PrimedInputRAM.Opcodes.packedPrefix p).val < 2^g.w := by
+ exact (congrArg (fun q => (PrimedInputRAM.Opcodes.packedPrefix q).val) hp).symm ▸
+ (show (PrimedInputRAM.Opcodes.packedPrefix Q.program).val < 2^g.w from
+ PrimedInputRAM.Opcodes.pubNat_lt Q hf.assembler 12)
+ exact ⟨hc.1,hval⟩
+ simp only [operands,h7,h12,↓reduceIte,Pieces.word,InputOperand.eval,table_other c p j h7 h12]
+ exact hc
+
+/-- Physical execution of the auxiliary table loader, with a fixed program independent of its own prefix. -/
+theorem fixed_runs (hB : 1 ≤ B) (hn : 2 ≤ n) (hp : Q.program = p)
+ (hbase : Q.scratchBase = 2^CursorBounds.virtualBits B n) (hf : D.Fits) (hroot : D.root.val = 0)
+ (persistent : Word (CursorBounds.wordBits B n))
+ (rs : Fin (RAMTape.InputOperandMachine.registers (operands c)) → Word (CursorBounds.wordBits B n))
+ (log : BurstRAM.PrivateRAM.WriteLog (CursorBounds.wordBits B n)) :
+ let g := AssemblerPublic.geometry B n H
+ let args := operands c
+ let pub := RAMTape.InputOperandMachine.input g (actualPrefix p)
+ ∃ t ≤ coefficient (RAMTape.InputOperandMachine.geometryOnly args)*(g.w+1)^2 + 34*(8*g.w+3)+2,
+ ∃ out : Fin (RAMTape.InputOperandMachine.registers args) → Word g.w,
+ (RAMTape.InputOperandMachine.program args).Runs t (RAMTape.ISA.bank pub persistent rs log)
+ (RAMTape.ISA.bank pub persistent out log) ∧
+ ∀ j, out (RAMTape.InputOperandMachine.slot args j) = D.pub j := by
+ let g := AssemblerPublic.geometry B n H
+ have h := operands_correct c Q D hB hn hp hbase hf hroot
+ have hfits (j : Fin 34) : (RAMTape.InputOperandMachine.geometryOnly (operands c) j).Fits g (2^g.w) := by
+ have hh := (h j).2
+ cases he : operands c j with
+ | geometry e =>
+ rw [he] at hh
+ simpa only [RAMTape.InputOperandMachine.geometryOnly,he] using hh
+ | prefixWord | prefixLength =>
+ simp only [RAMTape.InputOperandMachine.geometryOnly,he]
+ exact ⟨Nat.two_pow_pos _,trivial⟩
+ obtain ⟨t,ht,out,run,hout⟩ := RAMTape.InputOperandMachine.runs (operands c) g (actualPrefix p) hfits persistent rs log
+ exact ⟨t,ht,out,run,fun j => (hout j).trans (h j).1⟩
+
+end LiveProgram.CounterPublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePublicCounterPrefix.lean b/lean/OAI/Computability/VPVNP/LivePublicCounterPrefix.lean
new file mode 100644
index 0000000000..dfacd46b52
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePublicCounterPrefix.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.LivePublicCounter
+
+/-!
+# Loading the two auxiliary operands read from the processor's own prefix
+
+The live program has no copy of its own text in its instruction table. Its
+fixed expression vector computes the length-only operands and leaves zeros
+in the two prefix slots. It copies the prefix length and packed prefix from
+the parsed input into those two slots.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CounterPublic
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter
+
+/-- The finite expression vector whose instruction table is independent of the actual prefix. -/
+def shape (c : Constants) (j : Fin 34) : PublicExpr :=
+ if j.val = 7 ∨ j.val = 12 then .lit 0 else table UniversalMachine.emptyProgram c j
+
+theorem table_other (c : Constants) (p : UniversalMachine.Program) (j : Fin 34)
+ (h7 : j.val ≠ 7) (h12 : j.val ≠ 12) : shape c j = table p c j := by
+ simp only [shape, h7, h12, or_self, ↓reduceIte]
+ revert h7 h12
+ refine Fin.addCases (m := 16) (n := 18) (fun j ↦ ?_) (fun j ↦ ?_) j
+ · intro h7 h12
+ simp only [table,ParserPublic.Inputs.table, Fin.append_left, ParserPublic.paperInputs]
+ fin_cases j
+ · rfl
+ · rfl
+ · rfl
+ · rfl
+ · rfl
+ · rfl
+ · rfl
+ · exact (h7 rfl).elim
+ · rfl
+ · rfl
+ · rfl
+ · rfl
+ · exact (h12 rfl).elim
+ · rfl
+ · rfl
+ · rfl
+ · intro _ _
+ simp only [table,ParserPublic.Inputs.table, Fin.append_right]
+ rfl
+
+end LiveProgram.CounterPublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePublicExpr.lean b/lean/OAI/Computability/VPVNP/LivePublicExpr.lean
new file mode 100644
index 0000000000..a026c5f7ab
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePublicExpr.lean
@@ -0,0 +1,88 @@
+import Mathlib.Data.Nat.Log
+
+/-!
+# Length-only operands of the live instruction table
+
+The physical reader supplies the input length, address width, bucket size and
+word width. Literals belong to the fixed program. Arithmetic is performed on
+natural numbers before packing each output as a word. `Fits` checks every
+intermediate result, including inputs to division and logarithms.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+/-- Public dimensions read by the live processor, comprising input length, site-address width,
+bucket capacity, and RAM word width. -/
+structure Geometry where
+ /-- The physical input length in bits. -/
+ n : ℕ
+ /-- Bit width of the site address, so a group has two to this power sites. -/
+ d : ℕ
+ /-- The per-site RAM bucket capacity. -/
+ H : ℕ
+ /-- Bit width of a RAM word in this geometry. -/
+ w : ℕ
+ deriving DecidableEq, Repr
+
+/-- Length expression formed from geometry parameters, literals, natural arithmetic, constant
+division, binary logarithms, and powers of two. -/
+inductive PublicExpr where
+ | lit (v : ℕ)
+ | n | d | H | w
+ | add (a b : PublicExpr)
+ | sub (a b : PublicExpr)
+ | mul (a b : PublicExpr)
+ | divConst (a : PublicExpr) (b : ℕ)
+ | log2 (a : PublicExpr)
+ | clog2 (a : PublicExpr)
+ | pow2 (a : PublicExpr)
+ deriving DecidableEq, Repr
+
+namespace PublicExpr
+
+/-- Evaluate a public expression in natural numbers, using truncated subtraction, floor
+division, and the indicated floor or ceiling binary logarithm. -/
+def eval (g : Geometry) : PublicExpr → ℕ
+ | .lit v => v
+ | .n => g.n
+ | .d => g.d
+ | .H => g.H
+ | .w => g.w
+ | .add a b => a.eval g + b.eval g
+ | .sub a b => a.eval g - b.eval g
+ | .mul a b => a.eval g * b.eval g
+ | .divConst a b => a.eval g / b
+ | .log2 a => Nat.log 2 (a.eval g)
+ | .clog2 a => Nat.clog 2 (a.eval g)
+ | .pow2 a => 2^(a.eval g)
+
+/-- Bound on every intermediate register. The denominator of `divConst` is
+also a program literal and must fit if division is performed with word arithmetic. -/
+def Fits (g : Geometry) (bound : ℕ) (e : PublicExpr) : Prop :=
+ e.eval g < bound ∧ match e with
+ | .add a b | .sub a b | .mul a b => a.Fits g bound ∧ b.Fits g bound
+ | .divConst a b => a.Fits g bound ∧ b < bound
+ | .log2 a | .clog2 a | .pow2 a => a.Fits g bound
+ | _ => True
+
+/-- Fixed nonnegative integer powers use repeated multiplication. -/
+def natPow (a : PublicExpr) : ℕ → PublicExpr
+ | 0 => .lit 1
+ | k+1 => .mul (natPow a k) a
+
+@[simp] theorem eval_natPow (a : PublicExpr) (k : ℕ) (g : Geometry) :
+ (a.natPow k).eval g = (a.eval g)^k := by
+ induction k with
+ | zero => simp [natPow, eval]
+ | succ k ih => simp [natPow, eval, ih, Nat.pow_succ]
+
+end PublicExpr
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePublicIncidentWidth.lean b/lean/OAI/Computability/VPVNP/LivePublicIncidentWidth.lean
new file mode 100644
index 0000000000..3269d04178
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePublicIncidentWidth.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.LivePublicExpr
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeParameters
+
+/-!
+# Length expressions for the two kinds of incident fields
+
+The sorter exchanges two blocks per triangular layer. The expression forms
+the triangular numerator before division, so its fit proof bounds that
+numerator independently of the final incident width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.IncidentPublic
+
+open BurstRAM PrimedInputRAM
+
+/-- Bit length of one sorting block, with four times the bucket capacity records of five RAM
+words each. -/
+def block : PublicExpr := (((.lit 4 : PublicExpr).mul .H).mul (.lit 5)).mul .w
+
+/-- Bit length of one successor field containing eight RAM words. -/
+def successor : PublicExpr := (.lit 8 : PublicExpr).mul .w
+
+/-- Combined bit length of the outgoing and incoming successor fields. -/
+def bothSuccessors : PublicExpr := (.lit 2 : PublicExpr).mul successor
+
+/-- Number of bitonic layers on the site-address bits, the triangular number for the address
+width. -/
+def layers : PublicExpr := (((.d : PublicExpr).add (.lit 1)).mul .d).divConst 2
+
+/-- Total incident bit length, comprising both successor fields and two sorting blocks for each
+layer. -/
+def incident : PublicExpr := bothSuccessors.add (layers.mul ((.lit 2 : PublicExpr).mul block))
+
+@[simp] theorem block_eval (g : Geometry) : block.eval g = RAMLayout.blockBits g.H g.w := rfl
+
+@[simp] theorem layers_eval (g : Geometry) : layers.eval g = RAMLayout.layerCount g.d := by
+ simp [layers, PublicExpr.eval, RAMLayout.layerCount, Nat.choose_two_right]
+
+@[simp] theorem incident_eval (g : Geometry) : incident.eval g = RAMLayout.width g.d g.H g.w := by
+ change 2 * (8*g.w) + layers.eval g * (2*block.eval g) = _
+ rw [layers_eval,block_eval]
+ rfl
+
+theorem fits {L : PrimedInputRAM.Lengths} {n r H w : ℕ}
+ (Q : Layout L n r H w) (F : Opcodes.ParameterFit Q) (hr : 1 ≤ r)
+ (hw : w = (r+10)^4) (g : Geometry) (hd : g.d = r) (hH : g.H = H) (hwidth : g.w = w) :
+ block.Fits g (2^w) ∧ successor.Fits g (2^w) ∧ bothSuccessors.Fits g (2^w) ∧ incident.Fits g (2^w) := by
+ have h16w : 16*w < 2^w := Opcodes.pubNat_lt Q F 15
+ have hwpos : 0 < w := by rw [hw]; positivity
+ have hlt : 16 < 2^w := by omega
+ let Fit := PublicExpr.Fits g (2 ^ w)
+ have lit {i : ℕ} (hi : i ≤ 16) : Fit (.lit i) := ⟨hi.trans_lt hlt,trivial⟩
+ have mul {a b : PublicExpr} (fa : Fit a) (fb : Fit b) (hab : a.eval g*b.eval g < 2^w) :
+ Fit (.mul a b) := ⟨hab,fa,fb⟩
+ have fw : Fit .w := ⟨hwidth ▸ (Opcodes.pubNat_lt Q F 4),trivial⟩
+ have fH : Fit .H := ⟨by change g.H < _; rw [hH]; exact Opcodes.pubNat_lt Q F 5,trivial⟩
+ have fd : Fit .d := ⟨by change g.d < _; rw [hd]; exact Opcodes.pubNat_lt Q F 3,trivial⟩
+ have hb := F.blockFits
+ have hwblock : 4*H*5 ≤ 4*H*5*w := Nat.le_mul_of_pos_right _ hwpos
+ change 4*H*5*w < 2^w at hb
+ have f4H := mul (lit (by decide : 4 ≤ 16)) fH (by change 4*g.H < _; rw [hH]; omega)
+ have f5 := mul f4H (lit (by decide : 5 ≤ 16)) (by change 4*g.H*5 < _; rw [hH]; omega)
+ have fb : Fit block := mul f5 fw (by change 4*g.H*5*g.w < _; rwa [hH,hwidth])
+ have fs : Fit successor := mul (lit (by decide)) fw (by change 8*g.w < _; rw [hwidth]; omega)
+ have fss : Fit bothSuccessors := mul (lit (by decide)) fs (by change 2*(8*g.w) < _; rw [hwidth]; omega)
+ have hsub : (r+1)*r ≤ w := by
+ rw [hw]
+ calc
+ _ ≤ (r+10)*(r+10) := Nat.mul_le_mul (by omega) (by omega)
+ _ = (r+10)^2 := (sq _).symm
+ _ ≤ (r+10)^4 := Nat.pow_le_pow_right (by omega) (by decide)
+ have hfit : w < 2^w := Nat.lt_two_pow_self
+ have hinc : r+1 ≤ (r+1)*r := Nat.le_mul_of_pos_right _ hr
+ have fplus : Fit ((.d : PublicExpr).add (.lit 1)) := ⟨by change g.d + 1 < _; rw [hd]; omega,fd,lit (by decide)⟩
+ have fprod := mul fplus fd (by change (g.d+1)*g.d < _; rw [hd]; omega)
+ have flayers : Fit layers := ⟨by change (g.d+1)*g.d / 2 < _; rw [hd]; omega, fprod, by omega⟩
+ have hincfit : RAMLayout.width r H w < 2^w := Opcodes.pubNat_lt Q F 8
+ have hcount : 1 ≤ RAMLayout.layerCount r := PortCode.layerCount_mono (show 1 ≤ r from hr)
+ have hdir : 2*RAMLayout.blockBits H w ≤ RAMLayout.layerCount r*(2*RAMLayout.blockBits H w) :=
+ Nat.le_mul_of_pos_left _ hcount
+ change 2*(8*w)+RAMLayout.layerCount r*(2*RAMLayout.blockBits H w) < _ at hincfit
+ have fdirs := mul (lit (by decide : 2 ≤ 16)) fb (by change 2 * block.eval g < _; rw [block_eval,hH,hwidth]; omega)
+ have fsort := mul flayers fdirs (by
+ change layers.eval g * (2 * block.eval g) < _
+ rw [layers_eval,block_eval,hd,hH,hwidth]; omega)
+ exact ⟨fb,fs,fss,⟨by rw [incident_eval,hd,hH,hwidth]; exact hincfit, fss,fsort⟩⟩
+
+end LiveProgram.IncidentPublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePublicPaperParser.lean b/lean/OAI/Computability/VPVNP/LivePublicPaperParser.lean
new file mode 100644
index 0000000000..c8603b1eec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePublicPaperParser.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.LivePublicParser
+
+/-! # The paper's full-degree parser with its prescribed state count
+
+The grammar family uses state zero as its root and allocates `n^(C+5)`
+states. Both public operands are independent of the coefficients later
+installed in the grammar.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+theorem PublicExpr.fits_natPow {g : Geometry} {e : PublicExpr} {b : ℕ}
+ (hf : e.Fits g b) (hp : 0 < e.eval g) (k : ℕ) (hk : (e.eval g)^k < b) :
+ (e.natPow k).Fits g b := by
+ induction k with
+ | zero => exact ⟨by simpa using hk,trivial⟩
+ | succ k ih =>
+ exact ⟨by simpa only [PublicExpr.eval_natPow] using hk,
+ ih ((Nat.pow_le_pow_right hp (Nat.le_succ k)).trans_lt hk),hf⟩
+
+namespace ParserPublic
+
+open PrimedInputRAM PrimedCounter
+
+/-- Build the full-degree parser inputs with root state zero and grammar state count n^(C+5),
+where n is the assembler input length. -/
+def paperInputs (assembler : Fin 16 → PublicExpr) (C : ℕ) : Inputs :=
+ ⟨assembler,(assembler 1).natPow (C+5),.lit 0⟩
+
+variable {L : PrimedInputRAM.Lengths} {n r H w C : ℕ} {Q : Layout L n r H w}
+ (D : PrimedCounter.Data Q (n^(C+5))) (g : Geometry) (assembler : Fin 16 → PublicExpr)
+
+theorem paper_values (ha : ∀ i, (assembler i).eval g = Opcodes.pubNat Q i)
+ (hroot : D.root.val = 0) : (paperInputs assembler C).Values g D := by
+ refine ⟨ha,?_,hroot.symm⟩
+ change ((assembler 1).natPow (C+5)).eval g = _
+ rw [PublicExpr.eval_natPow, ha]
+ rfl
+
+theorem paper_table (ha : ∀ i, (assembler i).eval g = Opcodes.pubNat Q i)
+ (hf : D.Fits) (hroot : D.root.val = 0) (hasm : ∀ i, (assembler i).Fits g (2^w)) (j : Fin 34) :
+ Fin.ofNat (2^w) (((paperInputs assembler C).table j).eval g) = D.pub j ∧
+ ((paperInputs assembler C).table j).Fits g (2^w) := by
+ have hv := paper_values D g assembler ha hroot
+ have hn : 0 < n := (Nat.zero_le _).trans_lt D.degree.isLt
+ have hnum : (assembler 1).eval g = n := ha 1
+ refine ⟨Inputs.table_eval _ _ D hv hf.degree_eq j, Inputs.table_fits _ _ D hv hf hasm ?_ ?_ j⟩
+ · exact PublicExpr.fits_natPow (hasm 1) (hnum ▸ hn) _ (hnum ▸ hf.states)
+ · exact ⟨Nat.two_pow_pos _,trivial⟩
+
+end ParserPublic
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePublicParser.lean b/lean/OAI/Computability/VPVNP/LivePublicParser.lean
new file mode 100644
index 0000000000..f760bdb566
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePublicParser.lean
@@ -0,0 +1,257 @@
+import OAI.Computability.VPVNP.LivePublicExpr
+import OAI.Computability.VPVNP.PrimedCounterData
+
+/-!
+# Reconstructing the public words of the primed pair parser
+
+In Section 14 the live evaluator reproduces the auxiliary machine's finite
+table. Its last eighteen public words specify scratch addresses, parser
+dimensions and schedule endpoints. Their expressions below use the first
+sixteen public words together with the prescribed grammar-state count and
+root. They use only length data and fixed arithmetic, independently of
+pair-specific cut lengths, exterior bits and nominations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.ParserPublic
+
+open BurstRAM PrimedInputRAM PrimedStackRAM PrimedCounter
+open scoped Fin.CommRing
+
+/-- Length expressions for the assembler's public operands, the grammar state count, and the
+root state. -/
+structure Inputs where
+ /-- The sixteen public operands of the primed input assembler. -/
+ assembler : Fin 16 → PublicExpr
+ /-- Public expression for the number of grammar states. -/
+ states : PublicExpr
+ /-- Public expression for the grammar's root state ordinal. -/
+ root : PublicExpr
+
+namespace Inputs
+
+variable (x : Inputs)
+
+/-- Input length recovered from the assembler's second operand. -/
+def n := x.assembler 1
+/-- Number of sites per group recovered from the assembler's third operand. -/
+def R := x.assembler 2
+/-- Total number of input cells for both groups, taken from the assembler's first operand. -/
+def rectangle := x.assembler 0
+/-- Base of the second-pass assembled input rectangle, immediately after the first-pass choice
+rectangle. -/
+def base := (x.assembler 6).add x.rectangle
+/-- Base of the parser's degree stack, immediately after the assembled input rectangle. -/
+def degreeBase := x.base.add x.rectangle
+/-- Base of the parser's state stack, one input length past the degree stack base. -/
+def stateBase := x.degreeBase.add x.n
+/-- Base of the terminal-position mark array, one input length past the state stack base. -/
+def markBase := x.stateBase.add x.n
+/-- Base of the label histogram, one input length past the mark array base. -/
+def histBase := x.markBase.add x.n
+/-- Largest zero-based degree index for the full-degree grammar, the input length minus one. -/
+def degree := x.n.sub (.lit 1)
+/-- Number of positive binary degree splits over degrees through the input length. -/
+def triangle := (x.n.mul x.degree).divConst 2
+/-- Number of terminal production labels, with one for each state, input position, and Boolean
+bit. -/
+def terminal := (x.states.mul x.n).mul (.lit 2)
+/-- Number of binary production labels, with one for each degree split and ordered triple of
+states. -/
+def binary := ((x.triangle.mul x.states).mul x.states).mul x.states
+/-- Total number of terminal and binary production labels checked by the parser. -/
+def labels := x.terminal.add x.binary
+/-- First word beyond the reserved primed header, after three length words, two group indices,
+advice, and two cut capacities. -/
+def headerEnd := (((PublicExpr.lit 3).add ((.lit 2 : PublicExpr).mul (x.assembler 9))).add
+ (x.assembler 10)).add ((.lit 2 : PublicExpr).mul (x.assembler 11))
+/-- Number of calls across the two rectangular input assembly passes. -/
+def assembly := x.rectangle.add x.rectangle
+/-- Number of parser calls for each site, three times the input length. -/
+def rowSpan := (PublicExpr.lit 3).mul x.n
+/-- Total site rows in the two groups, twice the number of sites per group. -/
+def rows := (PublicExpr.lit 2).mul x.R
+/-- First call cursor of the histogram comparison phase after input assembly and all per-site
+parser calls. -/
+def compareStart := x.assembly.add (x.rows.mul x.rowSpan)
+/-- Total number of scheduled calls through the last label comparison. -/
+def total := x.compareStart.add x.labels
+
+/-- The fourteen parser parameters in the auxiliary machine's order. -/
+def parser : Fin 14 → PublicExpr :=
+ Fin.append ![x.degreeBase,x.stateBase,x.markBase,x.histBase,x.histBase.add x.labels,
+ x.n,x.n,x.states,x.base,x.terminal,x.labels] ![x.degree,x.root,x.headerEnd]
+
+/-- The four bounds partition the absolute cursor into assembly, site and
+final histogram-comparison calls. -/
+def schedule : Fin 4 → PublicExpr := ![x.assembly,x.rowSpan,x.compareStart,x.total]
+
+/-- Assemble the 34 public words in order from the sixteen assembler operands, the parser
+operands, and the schedule operands. -/
+def table : Fin 34 → PublicExpr := Fin.append x.assembler (Fin.append x.parser x.schedule)
+
+variable {L : Lengths} {n r H w s : ℕ} {Q : Layout L n r H w}
+
+/-- Numerical inputs to the suffix construction, before word packing. -/
+structure Values (x : Inputs) (g : Geometry) (D : PrimedCounter.Data Q s) : Prop where
+ assembler (j) : (x.assembler j).eval g = Opcodes.pubNat Q j
+ states : x.states.eval g = s
+ root : x.root.eval g = D.root.val
+
+private theorem span_eq (n : ℕ) (hn : 0 < n) : Cursor.span n (2*n-1) = 3*n := by
+ unfold Cursor.span
+ omega
+
+/-- Re-evaluating the expressions gives the native auxiliary table exactly. -/
+theorem table_eval (g : Geometry) (D : PrimedCounter.Data Q s) (h : x.Values g D)
+ (hd : D.degree.val+1 = n) (j : Fin 34) :
+ Fin.ofNat (2 ^ w) ((x.table j).eval g) = D.pub j := by
+ have hn : 0 < n := by omega
+ have hdeg : n-1 = D.degree.val := by omega
+ have hlabels : x.labels.eval g = D.labels := by
+ simp only [labels, terminal, binary, triangle, degree, Inputs.n, PublicExpr.eval,
+ h.assembler, h.states, Opcodes.pubNat, PrimedCounter.Data.labels, labelCount, Nat.choose_two_right]
+ rfl
+ refine Fin.addCases (m := 16) (n := 18) (fun i ↦ ?_) (fun i ↦ ?_) j
+ · rw [table, Fin.append_left, h.assembler]
+ change Opcodes.pubWord Q i = _
+ exact (Program.public_input (Opcodes.pubWord Q) D.parserPub D.assembly (2*2^r) n (2*n-1) D.labels i).symm
+ · rw [table, Fin.append_right]
+ refine Fin.addCases (m := 14) (n := 4) (fun p ↦ ?_) (fun p ↦ ?_) i
+ · rw [Fin.append_left]
+ change _ = D.pub (Program.parserPub p)
+ rw [PrimedCounter.Data.pub, Program.public_parser, PrimedCounter.Data.parserPub, parser]
+ refine Fin.addCases (m := 11) (n := 3) (fun u ↦ ?_) (fun u ↦ ?_) p
+ · rw [Fin.append_left, Fin.append_left]
+ fin_cases u <;> simp [publicData, base, degreeBase, stateBase, markBase, histBase, Inputs.n,
+ rectangle, terminal, hlabels, PublicExpr.eval, h.assembler, h.states, Opcodes.pubNat]
+ · rw [Fin.append_right, Fin.append_right]
+ fin_cases u <;> simp [degree,Inputs.n,headerEnd,PublicExpr.eval,h.assembler,h.root,Opcodes.pubNat,
+ hdeg,Header.count]
+ · rw [Fin.append_right]
+ have hs := Program.public_schedule (Opcodes.pubWord Q) D.parserPub D.assembly (2*2^r) n (2*n-1) D.labels
+ have he : ∀ u : Fin 4, D.pub ((u.natAdd 14).natAdd 16) =
+ (![↑D.assembly, ↑(Cursor.span n (2*n-1)),
+ ↑(Cursor.compareStart D.assembly (2*2^r) n (2*n-1)), ↑D.total] : Fin 4 → Word w) u := by
+ intro u; fin_cases u <;> first | exact hs.1 | exact hs.2.1 | exact hs.2.2.1 | exact hs.2.2.2
+ rw [he]
+ fin_cases p <;> simp [schedule,assembly,rectangle,rowSpan,Inputs.n,rows,R,compareStart,total,
+ Cursor.compareStart, PrimedCounter.Data.total, Cursor.calls, span_eq n hn, hlabels,
+ PublicExpr.eval,h.assembler,Opcodes.pubNat, Nat.add_assoc]
+
+/-- The existing parser bounds imply that every intermediate computation of
+the suffix is word-sized. In particular, the numerator of the triangular
+label count fits before it is divided by two. -/
+theorem table_fits (g : Geometry) (D : PrimedCounter.Data Q s) (h : x.Values g D) (hf : D.Fits)
+ (ha : ∀ i, (x.assembler i).Fits g (2 ^ w)) (hs : x.states.Fits g (2 ^ w))
+ (hr : x.root.Fits g (2 ^ w)) (j : Fin 34) : (x.table j).Fits g (2 ^ w) := by
+ let F := PublicExpr.Fits g (2 ^ w)
+ have addF {a b : PublicExpr} (fa : F a) (fb : F b) (hb : a.eval g + b.eval g < 2^w) :
+ F (.add a b) := ⟨hb,fa,fb⟩
+ have mulF {a b : PublicExpr} (fa : F a) (fb : F b) (hb : a.eval g * b.eval g < 2^w) :
+ F (.mul a b) := ⟨hb,fa,fb⟩
+ have hn : 0 < n := (Nat.zero_le _).trans_lt D.degree.isLt
+ have hpos : 0 < s := (Nat.zero_le _).trans_lt D.root.isLt
+ have hR : 0 < 2^r := Nat.two_pow_pos _
+ have hnV : x.n.eval g = n := h.assembler 1
+ have hRV : x.R.eval g = 2 ^ r := h.assembler 2
+ have hrectV : x.rectangle.eval g = positions n r := h.assembler 0
+ have hbaseV : x.base.eval g = Q.scratchBase + positions n r := by
+ change (x.assembler 6).eval g + x.rectangle.eval g = _; rw [h.assembler,hrectV]; rfl
+ have hdegV : x.degree.eval g = n - 1 := by change x.n.eval g - 1 = _; rw [hnV]
+ have htriV : x.triangle.eval g = n.choose 2 := by
+ change x.n.eval g * x.degree.eval g / 2 = _; rw [hnV,hdegV,Nat.choose_two_right]
+ have htermV : x.terminal.eval g = s * n * 2 := by
+ change x.states.eval g * x.n.eval g * 2 = _; rw [h.states,hnV]
+ have hbinV : x.binary.eval g = n.choose 2 * s * s * s := by
+ change x.triangle.eval g * x.states.eval g * x.states.eval g * x.states.eval g = _
+ rw [htriV,h.states]
+ have hlabelV : x.labels.eval g = D.labels := by
+ change x.terminal.eval g + x.binary.eval g = _; rw [htermV,hbinV]; rfl
+ have hdepth : D.base + positions n r + n + n + n + D.labels < 2^w := by
+ have hh := hf.scratch
+ change D.base + (positions n r + (n + (n + (n + (D.labels + 1))))) ≤ 2^w at hh
+ omega
+ have htotal : (positions n r + positions n r) + ((2 * 2^r) * (3*n) + D.labels) < 2^w := by
+ have hh := hf.cursor
+ change (positions n r + positions n r) + ((2 * 2^r) * Cursor.span n (2*n-1) + D.labels) < _ at hh
+ rwa [span_eq n hn] at hh
+ have hhend := hf.headers
+ have hheader : 3 + 2*L.index + L.advice + 2*L.cutCapacity < 2^w := by
+ change (3 + 2*L.index + L.advice + 2*L.cutCapacity) + D.labels ≤ Q.scratchBase at hhend
+ change Q.scratchBase + positions n r + positions n r + n + n + n + D.labels < _ at hdepth
+ omega
+ have f1 : F (.lit 1) := ⟨by change 1 < _; omega, trivial⟩
+ have f2 : F (.lit 2) := ⟨hf.word,trivial⟩
+ have f3 : F (.lit 3) := ⟨by change 3 < _; omega, trivial⟩
+ have fn : F x.n := ha 1
+ have fR : F x.R := ha 2
+ have frect : F x.rectangle := ha 0
+ have fbase : F x.base := addF (ha 6) frect (by
+ change x.base.eval g < _; rw [hbaseV]; change D.base < _; omega)
+ have fdBase : F x.degreeBase := addF fbase frect (by rw [hbaseV,hrectV]; change D.base + _ < _; omega)
+ have fdV : x.degreeBase.eval g = D.base + positions n r := by change x.base.eval g + _ = _; rw [hbaseV,hrectV]
+ have fsBase : F x.stateBase := addF fdBase fn (by rw [fdV,hnV]; omega)
+ have fsV : x.stateBase.eval g = D.base + positions n r + n := by change x.degreeBase.eval g + _ = _; rw [fdV,hnV]
+ have fmBase : F x.markBase := addF fsBase fn (by rw [fsV,hnV]; omega)
+ have fmV : x.markBase.eval g = D.base + positions n r + n + n := by change x.stateBase.eval g + _ = _; rw [fsV,hnV]
+ have fhBase : F x.histBase := addF fmBase fn (by rw [fmV,hnV]; omega)
+ have fhV : x.histBase.eval g = D.base + positions n r + n + n + n := by change x.markBase.eval g + _ = _; rw [fmV,hnV]
+ have fd : F x.degree := ⟨by rw [hdegV]; omega,fn,f1⟩
+ have hnum : n*(n-1) < 2^w := (Nat.mul_lt_mul_of_pos_left (by omega : n-1 < n) hn).trans_le
+ (by simpa [pow_two] using hf.triangle)
+ have fnum := mulF fn fd (by rw [hnV,hdegV]; exact hnum)
+ have ftri : F x.triangle := ⟨htriV ▸ ((Nat.choose_two_right n) ▸ ((Nat.div_le_self _ _).trans_lt hnum)),
+ fnum, hf.word⟩
+ have ht : s*n*2 ≤ D.labels := Nat.le_add_right ..
+ have hb : n.choose 2*s*s*s ≤ D.labels := Nat.le_add_left ..
+ have hlfit : D.labels < 2^w := by omega
+ have hss : n.choose 2*s ≤ n.choose 2*s*s := Nat.le_mul_of_pos_right _ hpos
+ have hsss : n.choose 2*s*s ≤ n.choose 2*s*s*s := Nat.le_mul_of_pos_right _ hpos
+ have fterm : F x.terminal := mulF (mulF hs fn (by rw [h.states,hnV]; omega)) f2
+ (by change x.terminal.eval g < _; rw [htermV]; omega)
+ have fs₁ := mulF ftri hs (by rw [htriV,h.states]; omega)
+ have fs₂ := mulF fs₁ hs (by change x.triangle.eval g*x.states.eval g*x.states.eval g < _; rw [htriV,h.states]; omega)
+ have fbin : F x.binary := mulF fs₂ hs (by change x.binary.eval g < _; rw [hbinV]; omega)
+ have flabel : F x.labels := addF fterm fbin (by change x.labels.eval g < _; rw [hlabelV]; exact hlfit)
+ have fdepth := addF fhBase flabel (by rw [fhV,hlabelV]; exact hdepth)
+ have fiV : (x.assembler 9).eval g = L.index := h.assembler 9
+ have faV : (x.assembler 10).eval g = L.advice := h.assembler 10
+ have fcV : (x.assembler 11).eval g = L.cutCapacity := h.assembler 11
+ have fi := mulF f2 (ha 9) (by change 2 * _ < _; rw [fiV]; omega)
+ have fc := mulF f2 (ha 11) (by change 2 * _ < _; rw [fcV]; omega)
+ have fh₁ := addF f3 fi (by change 3 + 2 * _ < _; rw [fiV]; omega)
+ have fh₂ := addF fh₁ (ha 10) (by change 3 + 2*(x.assembler 9).eval g + _ < _; rw [fiV,faV]; omega)
+ have fheader : F x.headerEnd := addF fh₂ fc
+ (by change 3 + 2*(x.assembler 9).eval g + (x.assembler 10).eval g + 2*(x.assembler 11).eval g < _
+ rw [fiV,faV,fcV]; exact hheader)
+ have hrow := Nat.le_mul_of_pos_left (3*n) (by omega : 0 < 2 * 2^r)
+ have hsites := Nat.le_mul_of_pos_right (2*2^r) (by omega : 0 < 3*n)
+ have fspan : F x.rowSpan := mulF f3 fn (by change 3 * _ < _; rw [hnV]; omega)
+ have frows : F x.rows := mulF f2 fR (by change 2 * _ < _; rw [hRV]; omega)
+ have fassembly : F x.assembly := addF frect frect (by rw [hrectV]; omega)
+ have fvisits := mulF frows fspan (by change (2*x.R.eval g)*(3*x.n.eval g) < _; rw [hRV,hnV]; omega)
+ have fcompare : F x.compareStart := addF fassembly fvisits
+ (by change x.rectangle.eval g+x.rectangle.eval g+(2*x.R.eval g)*(3*x.n.eval g) < _; rw [hrectV,hRV,hnV]; omega)
+ have ftotal : F x.total := addF fcompare flabel (by
+ change x.rectangle.eval g+x.rectangle.eval g+(2*x.R.eval g)*(3*x.n.eval g)+x.labels.eval g < _
+ rw [hrectV,hRV,hnV,hlabelV]; omega)
+ refine Fin.addCases (m := 16) (n := 18) (fun i ↦ ?_) (fun i ↦ ?_) j
+ · simpa only [table, Fin.append_left] using ha i
+ · rw [table, Fin.append_right]
+ refine Fin.addCases (m := 14) (n := 4) (fun p ↦ ?_) (fun p ↦ ?_) i
+ · rw [Fin.append_left, parser]
+ refine Fin.addCases (m := 11) (n := 3) (fun u ↦ ?_) (fun u ↦ ?_) p
+ · rw [Fin.append_left]; fin_cases u <;> assumption
+ · rw [Fin.append_right]; fin_cases u <;> assumption
+ · rw [Fin.append_right]; fin_cases p <;> assumption
+
+end Inputs
+end LiveProgram.ParserPublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LivePublicVirtualSites.lean b/lean/OAI/Computability/VPVNP/LivePublicVirtualSites.lean
new file mode 100644
index 0000000000..680102d818
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LivePublicVirtualSites.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.LivePublicExpr
+import OAI.Computability.VPVNP.RAMVirtualParameterBounds
+import OAI.Computability.VPVNP.CursorBounds
+
+/-!
+# Computing the virtual site count from the live address width
+
+The least admissible virtual address width is the ceiling logarithm of the
+probe budget minus the virtual bucket exponent. Adding the live address
+width after taking the logarithm keeps the largest operand of the logarithm
+at `n * clog₂ n`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+open BurstRAM
+
+/-- A fixed expression for the number of virtual sites in Sections 11 and 14. -/
+def virtualSites : PublicExpr :=
+ let c := PublicExpr.clog2 .n
+ .pow2 (.sub (.add .d (.clog2 (.mul .n c))) (.divConst (.add c (.lit 3)) 4))
+
+theorem virtualSites_eval (g : Geometry) (hn : 2 ≤ g.n) :
+ virtualSites.eval g = 2^virtualSiteExponent g.d g.n := by
+ rw [virtualSiteExponent_eq_add_sub _ _ hn]
+ rfl
+
+/-- The input, product, two logarithmic counters and both division operands
+fit the same word as the resulting site count. -/
+theorem virtualSites_fits {B n H : ℕ} (hB : 1 ≤ B) (hn : 2 ≤ n)
+ (hcount : 2^virtualSiteExponent (addressWidth B n) n < 2^CursorBounds.wordBits B n) :
+ virtualSites.Fits ⟨n,addressWidth B n,H,CursorBounds.wordBits B n⟩
+ (2^CursorBounds.wordBits B n) := by
+ let r := addressWidth B n
+ let w := CursorBounds.wordBits B n
+ let c := Nat.clog 2 n
+ let g : Geometry := ⟨n,r,H,w⟩
+ let Fit := PublicExpr.Fits g (2^w)
+ obtain ⟨hprod,hsum,hnum⟩ := virtualParameterOperands_lt hB n
+ change n * c + 1 < 2^w at hprod
+ change r + Nat.clog 2 (n*c) < 2^w at hsum
+ change c + 3 < 2^w at hnum
+ have hc : 0 < c := Nat.clog_pos Nat.one_lt_two hn
+ have hsub := Nat.le_mul_of_pos_right n hc
+ have fN : Fit .n := ⟨by change n < _; omega,trivial⟩
+ have fD : Fit .d := ⟨by change r < _; omega,trivial⟩
+ have fC : Fit (.clog2 .n) := ⟨by change c < _; omega,fN⟩
+ have fNC : Fit (.mul .n (.clog2 .n)) := ⟨by change n*c < _; omega,fN,fC⟩
+ have flog : Fit (.clog2 (.mul .n (.clog2 .n))) := ⟨by change Nat.clog 2 (n*c) < _; omega,fNC⟩
+ have fsum : Fit (.add .d (.clog2 (.mul .n (.clog2 .n)))) := ⟨hsum,fD,flog⟩
+ have fnum : Fit (.add (.clog2 .n) (.lit 3)) := ⟨hnum,fC,⟨by change 3 < _; omega,trivial⟩⟩
+ have fdiv : Fit (.divConst (.add (.clog2 .n) (.lit 3)) 4) :=
+ ⟨by change (c+3)/4 < _; omega,fnum,by omega⟩
+ refine ⟨?_, ?_, fsum, fdiv⟩
+ · change virtualSites.eval g < _
+ rw [virtualSites_eval g hn]
+ exact hcount
+ · change r + Nat.clog 2 (n*c) - (c+3)/4 < _
+ exact (Nat.sub_le _ _).trans_lt hsum
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveRatedArcMemory.lean b/lean/OAI/Computability/VPVNP/LiveRatedArcMemory.lean
new file mode 100644
index 0000000000..369e907d75
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveRatedArcMemory.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.PairVertexRatedSelection
+import OAI.Computability.VPVNP.PairVirtualRootPayload
+
+/-! # Shared wire choices and physical memory of the rated branch -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM PrivateRAM CompressorRecords SourceTransport
+open PairSimulation LocalHistory NetworkKernel LiveProgram CompressedPair TerminalLink CutSchedule ExponentTrace
+open scoped Fin.CommRing
+set_option quotPrecheck false
+set_option maxHeartbeats 1500000
+attribute [local irreducible] VertexImage.template VertexImage.segments PhysicalScanData.physical TerminalProgram.workers
+ BlockSchedule.Templates.execute CursorNetwork.cursorState CursorBounds.wordBits stateScanPhase
+ VertexImage.placement
+open private scanWords scanMachine capacity from OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+
+variable {k : Type} [Field k] {S : BlockSchedule k} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {model : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ {data : D.ScalarData B hn model} {u : PairExponents B.growthConstant} {V : D.VirtualPairs B u hn C}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)} {i : D.groupIndices n} {μ : D.pairNom n C}
+ (scan : CanonicalScan data V ξ i μ) (z : (V.selection (M := model)).Choices)
+
+local notation "w" => CursorBounds.wordBits D.addressFactor n
+local notation "Y" => (V.selection (M := model)).finalState z
+local notation "κ" => B.compressorValues hn model
+local notation "hf" => B.compressorValues_solution hn model
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "ord" => (siteOrder (Y)).entries
+local notation "scanM" => scanMachine w
+local notation "sl" => FinalBits.template_linked (scanWords w)
+local notation "bitFit" => capacity scan z
+local notation "shape" => BlockProgram.allocationShape B
+
+variable {g : ℕ} (names : B.Entry ≃ Fin g) (rowBase counter grammar cap : ℕ)
+ (pub : Fin 11 → BurstRAM.Word (CursorBounds.wordBits D.addressFactor n))
+ {mem : Memory (CursorBounds.wordBits D.addressFactor n)}
+
+local notation "geo" => VertexGeometry.segment D.constants (slotDegree S) D.numerator D.denominator
+local notation "shr" => ShrinkVertexImage.shrinkSegment B names
+local notation "ref" => RefreshVertex.refreshSegment B (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride names
+local notation "code" => VertexImage.segments geo TerminalRootGather.segment LeafRole.segment shr ref
+local notation "W" => TerminalProgram.workers shape B.recordLimit code
+
+local notation "arc" => scan.arc z
+local notation "parsers" => scan.sites z
+
+variable (q lo before layout clock headerFit below agree) {power scanRate : ℕ}
+ (R : RatedSelection (mem := mem) scan z names rowBase counter grammar cap pub q lo before layout clock headerFit
+ below agree power scanRate)
+ (counterEnd : counter+grammar+g ≤ (header pub).val)
+
+local notation "visit₀" => R.selectedSites scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd
+
+local notation "branch₀" => R.branch scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd
+
+
+/-- The physical fourth stage chooses the canonical wire bits, followed
+by the required empty closing burst. -/
+theorem RatedSelection.bitPath_tapes (x : (arc).Path) :
+ (((branch₀).bitPaths x).val).choices = FinalBits.calls (scan.sharedBits z x) ++ [[]] :=
+ (PhysicalScanData.physical_choices (Y) scanM Fin.castSucc (Function.Embedding.refl _) 0 10 sl rfl
+ 0 rfl (fun _ => 0) 0 bitFit shape B.recordLimit code pub cap before q.traversalRows.val.memory
+ lo layout clock headerFit below agree x).trans
+ (congrArg (· ++ [[]]) (PhysicalScanData.calls (Y) scanM Fin.castSucc
+ (Function.Embedding.refl _) 0 10 sl rfl 0 rfl (fun _ => 0) 0 bitFit x))
+
+/-- The active vertex worker starts on the memory produced by the rated
+branch's own completed shared-bit phase. -/
+theorem RatedSelection.sourceMem_eq (x : (arc).Path) :
+ ((visit₀) x).sourceMem = ((branch₀).bitPaths x).val.memory := rfl
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveRatedRowCharges.lean b/lean/OAI/Computability/VPVNP/LiveRatedRowCharges.lean
new file mode 100644
index 0000000000..c914a838c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveRatedRowCharges.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.PairVertexRatedSelection
+import OAI.Computability.VPVNP.LiveTerminalWorkerTransport
+
+/-! # Report bounds of rated rows on the packed terminal table -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM PrivateRAM CompressorRecords SourceTransport
+open PairSimulation LocalHistory NetworkKernel LiveProgram CompressedPair TerminalLink CutSchedule ExponentTrace
+open scoped Fin.CommRing
+set_option quotPrecheck false
+set_option maxHeartbeats 1500000
+attribute [local irreducible] VertexImage.template VertexImage.segments PhysicalScanData.physical TerminalProgram.workers
+ BlockSchedule.Templates.execute CursorNetwork.cursorState CursorBounds.wordBits stateScanPhase
+ VertexImage.placement
+open private scanWords scanMachine capacity from OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+
+variable {k : Type} [Field k] {S : BlockSchedule k} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {model : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ {data : D.ScalarData B hn model} {u : PairExponents B.growthConstant} {V : D.VirtualPairs B u hn C}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)} {i : D.groupIndices n} {μ : D.pairNom n C}
+ (scan : CanonicalScan data V ξ i μ) (z : (V.selection (M := model)).Choices)
+
+local notation "w" => CursorBounds.wordBits D.addressFactor n
+local notation "Y" => (V.selection (M := model)).finalState z
+local notation "κ" => B.compressorValues hn model
+local notation "hf" => B.compressorValues_solution hn model
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "ord" => (siteOrder (Y)).entries
+local notation "scanM" => scanMachine w
+local notation "sl" => FinalBits.template_linked (scanWords w)
+local notation "bitFit" => capacity scan z
+local notation "shape" => BlockProgram.allocationShape B
+
+variable {g : ℕ} (names : B.Entry ≃ Fin g) (rowBase counter grammar cap : ℕ)
+ (pub : Fin 11 → BurstRAM.Word (CursorBounds.wordBits D.addressFactor n))
+ {mem : Memory (CursorBounds.wordBits D.addressFactor n)}
+
+local notation "geo" => VertexGeometry.segment D.constants (slotDegree S) D.numerator D.denominator
+local notation "shr" => ShrinkVertexImage.shrinkSegment B names
+local notation "ref" => RefreshVertex.refreshSegment B (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride names
+local notation "code" => VertexImage.segments geo TerminalRootGather.segment LeafRole.segment shr ref
+local notation "W" => TerminalProgram.workers shape B.recordLimit code
+
+local notation "arc" => scan.arc z
+local notation "parsers" => scan.sites z
+
+variable (q lo before layout clock headerFit below agree) {power scanRate : ℕ}
+ (R : RatedSelection (mem := mem) scan z names rowBase counter grammar cap pub q lo before layout clock headerFit
+ below agree power scanRate)
+ (counterEnd : counter+grammar+g ≤ (header pub).val)
+
+local notation "visit₀" => R.selectedSites scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd
+
+local notation "branch₀" => R.branch scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd
+
+
+
+local notation "C₀" => VertexReportBudget.coefficient S.baseDegree (Fintype.card B.Entry) 6 scanRate 0 0
+
+/-- The packed controller has exactly the shared-bit and vertex reports
+measured on the fixed native bank. -/
+theorem RatedSelection.chosenRows_packed {packed : TerminalLink.Stage → PairTable} (same : W = packed)
+ (large : 2048 ≤ n) (degree : S.baseDegree ≤ n) (labelsFit : Fintype.card B.Entry ≤ n)
+ (width : (Y).maxWireWidth ≤ n)
+ (depth : ∀ v, (selectedChain (V := V) (M := model) z).occurrences (fun _ => 1) v ≤ n)
+ (x : TerminalData (arc) (parsers)) :
+ ∃ (bitMemory last : Memory w) (bits : Fin (Y).totalWidth → Bool) (reps : (Y).network.Site → Report w),
+ (((branch₀).reindexWorkers same).chosenTrace x).sharedBits.logs.map Prod.snd =
+ FinalBits.Worker.reports pub 0 bitMemory bits ∧
+ (((branch₀).reindexWorkers same).chosenTrace x).vertices.logs.map Prod.snd =
+ (List.ofFn fun j => reps (ord j)) ++ [VertexImage.closingReport pub last] ∧
+ ∀ v, 1+(reps v).probes ≤ siteAccesses (Y) (selectedChain (V := V) (M := model) z) C₀ power n v ∧
+ (reps v).events.length+107 ≤ n^45 := by
+ obtain ⟨before,last,bits,reports,shared,vertices,charged⟩ :=
+ R.chosenRows scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd large degree labelsFit width depth x
+ exact ⟨before,last,bits,reports,
+ (congrArg (List.map Prod.snd) ((branch₀).reindex_sharedReports same x)).trans shared,
+ (congrArg (List.map Prod.snd) ((branch₀).reindex_vertexReports same x)).trans vertices,charged⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveRatedTerminalFrames.lean b/lean/OAI/Computability/VPVNP/LiveRatedTerminalFrames.lean
new file mode 100644
index 0000000000..361b4d62d7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveRatedTerminalFrames.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PairVertexRatedSelection
+import OAI.Computability.VPVNP.LiveSelectedTerminalFrame
+import OAI.Computability.VPVNP.PairTerminalQuietHandoff
+
+/-! # Physical frame of the rated terminal vertex execution -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM PrivateRAM CompressorRecords SourceTransport
+open PairSimulation LocalHistory NetworkKernel LiveProgram CompressedPair TerminalLink CutSchedule ExponentTrace
+open scoped Fin.CommRing
+set_option quotPrecheck false
+attribute [local irreducible] VertexImage.template VertexImage.segments PhysicalScanData.physical TerminalProgram.workers
+ BlockSchedule.Templates.execute CursorNetwork.cursorState CursorBounds.wordBits stateScanPhase
+ VertexImage.placement
+open private scanWords scanMachine capacity from OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+
+variable {k : Type} [Field k] {S : BlockSchedule k} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {model : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ {data : D.ScalarData B hn model} {u : PairExponents B.growthConstant} {V : D.VirtualPairs B u hn C}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)} {i : D.groupIndices n} {μ : D.pairNom n C}
+ (scan : CanonicalScan data V ξ i μ) (z : (V.selection (M := model)).Choices)
+
+local notation "w" => CursorBounds.wordBits D.addressFactor n
+local notation "Y" => (V.selection (M := model)).finalState z
+local notation "ord" => (siteOrder (Y)).entries
+local notation "scanM" => scanMachine w
+local notation "sl" => FinalBits.template_linked (scanWords w)
+local notation "bitFit" => capacity scan z
+local notation "shape" => BlockProgram.allocationShape B
+
+variable {g : ℕ} (names : B.Entry ≃ Fin g) (rowBase counter grammar cap : ℕ)
+ (pub : Fin 11 → BurstRAM.Word (CursorBounds.wordBits D.addressFactor n))
+ {mem : Memory (CursorBounds.wordBits D.addressFactor n)}
+
+local notation "geo" => VertexGeometry.segment D.constants (slotDegree S) D.numerator D.denominator
+local notation "shr" => ShrinkVertexImage.shrinkSegment B names
+local notation "ref" => RefreshVertex.refreshSegment B (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride names
+local notation "code" => VertexImage.segments geo TerminalRootGather.segment LeafRole.segment shr ref
+local notation "W" => TerminalProgram.workers shape B.recordLimit code
+
+variable (q : QuietPrefix (TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit
+ (TerminalProgram.nativeSegments B D.constants D.numerator D.denominator names)) pub cap mem)
+ (lo : ℕ) (before : Memory (CursorBounds.wordBits D.addressFactor n))
+ (layout : FinalBits.Worker.Layout pub before lo ((V.selection (M := model)).finalState z).totalWidth)
+ (clock : 54 ≤ cap) (headerFit : (header pub).val+32 ≤ 2^(CursorBounds.wordBits D.addressFactor n))
+ (below : lo+((V.selection (M := model)).finalState z).totalWidth ≤ (header pub).val)
+ (agree : Agree (workerCell (header pub)) before q.traversalRows.val.memory)
+
+variable {power scanRate : ℕ}
+ (R : RatedSelection scan z names rowBase counter grammar cap pub q lo before layout clock headerFit
+ below agree power scanRate)
+ (counterEnd : counter+grammar+g ≤ (header pub).val)
+
+
+local notation "parsers" => scan.sites z
+
+include R counterEnd in
+/-- The concrete rated rows preserve every earlier address outside their
+histogram on all reachable bursts. The conclusion is stated on the actual
+packed worker bank used by the pair linker. -/
+theorem RatedSelection.branch_frames {packed : TerminalLink.Stage → PairTable}
+ (bank : (W) = packed)
+ (low : (pub 2).val ≤ lo)
+ (prefixFrame : ∀ a < (pub 2).val, ReplayFrame a mem q.reportList)
+ (a : ℕ) (beforeWorkspace : a < (pub 2).val)
+ (outside : a < counter+grammar ∨ counter+grammar+g ≤ a) :
+ PreservesCell (TerminalLink.program packed pub) cap 0 mem a := by
+ subst packed
+ have wide : 32 ≤ 2^w := by omega
+ intro st now tape result reached run
+ exact selectedTerminalBranch_word (Y) scanM Fin.castSucc (Function.Embedding.refl _) 0 10 sl rfl
+ 0 rfl (fun _ => 0) 0 bitFit (parsers) ord names.symm shape B.recordLimit pub q lo before layout
+ clock headerFit below agree counter grammar (R.selectedSites scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd) a (beforeWorkspace.trans_le low) outside
+ (prefixFrame a beforeWorkspace) (q.valid_sharedBits wide) reached run
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveRatedVertexDeposits.lean b/lean/OAI/Computability/VPVNP/LiveRatedVertexDeposits.lean
new file mode 100644
index 0000000000..029f761757
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveRatedVertexDeposits.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.PairVertexRatedSelection
+import OAI.Computability.VPVNP.LiveSelectedVertexCounters
+import OAI.Computability.VPVNP.LiveTerminalWorkerTransport
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-! # Counter deposits of the rated canonical vertex branch
+
+The selected row certificates determine the physical reports. In the counter
+interval, the resulting memory equals the fold of the selected preorder jobs'
+exponents over the original pair memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM PrivateRAM CompressorRecords SourceTransport
+open PairSimulation LocalHistory NetworkKernel LiveProgram CompressedPair TerminalLink CutSchedule ExponentTrace
+open scoped Fin.CommRing
+set_option quotPrecheck false
+set_option maxHeartbeats 1500000
+attribute [local irreducible] VertexImage.template VertexImage.segments PhysicalScanData.physical TerminalProgram.workers
+ BlockSchedule.Templates.execute CursorNetwork.cursorState CursorBounds.wordBits stateScanPhase
+ VertexImage.placement
+open private scanWords scanMachine capacity from OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+
+variable {k : Type} [Field k] {S : BlockSchedule k} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {model : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ {data : D.ScalarData B hn model} {u : PairExponents B.growthConstant} {V : D.VirtualPairs B u hn C}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)} {i : D.groupIndices n} {μ : D.pairNom n C}
+ (scan : CanonicalScan data V ξ i μ) (z : (V.selection (M := model)).Choices)
+
+local notation "w" => CursorBounds.wordBits D.addressFactor n
+local notation "Y" => (V.selection (M := model)).finalState z
+local notation "κ" => B.compressorValues hn model
+local notation "hf" => B.compressorValues_solution hn model
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "ord" => (siteOrder (Y)).entries
+local notation "scanM" => scanMachine w
+local notation "sl" => FinalBits.template_linked (scanWords w)
+local notation "bitFit" => capacity scan z
+local notation "shape" => BlockProgram.allocationShape B
+
+variable {g : ℕ} (names : B.Entry ≃ Fin g) (rowBase counter grammar cap : ℕ)
+ (pub : Fin 11 → BurstRAM.Word (CursorBounds.wordBits D.addressFactor n))
+ {mem : Memory (CursorBounds.wordBits D.addressFactor n)}
+
+local notation "geo" => VertexGeometry.segment D.constants (slotDegree S) D.numerator D.denominator
+local notation "shr" => ShrinkVertexImage.shrinkSegment B names
+local notation "ref" => RefreshVertex.refreshSegment B (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride names
+local notation "code" => VertexImage.segments geo TerminalRootGather.segment LeafRole.segment shr ref
+local notation "W" => TerminalProgram.workers shape B.recordLimit code
+
+local notation "arc" => scan.arc z
+local notation "parsers" => scan.sites z
+
+variable (q lo before layout clock headerFit below agree) {power scanRate : ℕ}
+ (R : RatedSelection (mem := mem) scan z names rowBase counter grammar cap pub q lo before layout clock headerFit
+ below agree power scanRate)
+ (counterEnd : counter+grammar+g ≤ (header pub).val)
+
+local notation "visit₀" => R.selectedSites scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd
+
+local notation "branch₀" => R.branch scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd
+
+/-- Deposit the canonical jobs into each grammar or motif counter word. -/
+theorem RatedSelection.deposits (x : TerminalData (arc) (parsers))
+ (ptr : RowPointers (selectedChain (V := V) (M := model) z))
+ (leaf : V.scanState.network.Site → ℕ × ℕ) (input : Memory w)
+ (initial : ∀ j : Fin (grammar+g), ((visit₀) x.arcs).sourceMem (counter+j.val) = input (counter+j.val))
+ (j : Fin (grammar+g)) :
+ ((branch₀).vertexPaths x.arcs x.choices).val.memory (counter+j.val) =
+ Counters.visit counter grammar (fun v k => scan.siteTotals z x ptr leaf v (names.symm k))
+ (List.ofFn ord) input (counter+j.val) := by
+ have cell := TerminalFootprint.below (header pub) (by omega)
+ (show counter+j.val < (header pub).val from (Nat.add_lt_add_left j.isLt counter).trans_le
+ (Nat.add_assoc counter grammar g ▸ counterEnd))
+ let chain := selectedChain (V := V) (M := model) z
+ let readers := selectedParsers B κ hf T le_rfl V.scanState z
+ exact selectedTerminalBranch_deposited (Y) scanM Fin.castSucc (Function.Embedding.refl _) 0 10
+ sl rfl 0 rfl (fun _ => 0) 0 bitFit (parsers) ord names.symm shape B.recordLimit pub q lo before
+ layout clock headerFit below agree counter grammar (visit₀) x
+ (chainTrees chain readers ptr (fun v => leafTree (leaf v))) (vertexJobs chain readers ptr scan.leafSites leaf)
+ (vertexJobs_spec chain readers ptr scan.leafSites leaf) input (counter+j.val) cell (initial j)
+
+/-- Reindexing the worker tables preserves every physical deposit. -/
+theorem RatedSelection.deposits_reindex {current : TerminalLink.Stage → LiveProgram.PairTable}
+ (same : W = current) (x : TerminalData (arc) (parsers))
+ (ptr : RowPointers (selectedChain (V := V) (M := model) z))
+ (leaf : V.scanState.network.Site → ℕ × ℕ) (input : Memory w)
+ (initial : ∀ j : Fin (grammar+g), ((visit₀) x.arcs).sourceMem (counter+j.val) = input (counter+j.val))
+ (j : Fin (grammar+g)) :
+ (((branch₀).reindexWorkers same).vertexPaths x.arcs x.choices).val.memory (counter+j.val) =
+ Counters.visit counter grammar (fun v k => scan.siteTotals z x ptr leaf v (names.symm k))
+ (List.ofFn ord) input (counter+j.val) := by
+ exact (congrFun ((branch₀).reindex_vertexMemory same x) _).trans
+ (R.deposits scan z names rowBase counter grammar cap pub q lo before layout clock headerFit below
+ agree counterEnd x ptr leaf input initial j)
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveRoute.lean b/lean/OAI/Computability/VPVNP/LiveRoute.lean
new file mode 100644
index 0000000000..4a3fbbbc04
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveRoute.lean
@@ -0,0 +1,194 @@
+import OAI.Computability.VPVNP.LiveStageLinkPaths
+import Mathlib.Data.ZMod.Defs
+import Mathlib.Tactic.FinCases
+
+/-!
+# Branching between live stages using checked header flags
+
+The routing call reads one word from the group's header workspace. Each of
+zero, one, and two can select a stage, accept, or reject. A transfer stores
+the selected stage tag at the outer linker's address and returns cursor zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.Route
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+/-- Result of a live router decision, either reject, accept, or jump to the indicated stage
+tag. -/
+inductive Target where
+ | reject | accept | jump (stage : Fin 32)
+ deriving DecidableEq, Repr
+
+private def destination : Target → Instr 5 16 4 2
+ | .reject => .reject
+ | .accept => .accept
+ | .jump s => .constant 3 s 12
+
+/-- Public operands are the tested flag address and the outer stage tag address. -/
+def table (target : Fin 3 → Target) : Template 16 4 2 where
+ literalWidth := 5
+ entry := 0
+ code
+ | 0 => .publicWord 0 0 1
+ | 1 => .readExternal 1 0 2
+ | 2 => .constant 2 0 3
+ | 3 => .jumpEq 1 2 9 4
+ | 4 => .constant 2 1 5
+ | 5 => .jumpEq 1 2 10 6
+ | 6 => .constant 2 2 7
+ | 7 => .jumpEq 1 2 11 8
+ | 8 => .reject
+ | 9 => destination (target 0)
+ | 10 => destination (target 1)
+ | 11 => destination (target 2)
+ | 12 => .publicWord 0 1 13
+ | 13 => .writeExternal 0 3 14
+ | 14 => .constant 2 0 15
+ | _ => .returnState 2
+
+variable {w : ℕ}
+
+/-- Explicit report for each selection and any remaining branch bits. -/
+def report (pub : Fin 2 → Word w) (flag : Word w) (i : Fin 3) (t : Target)
+ (bits : List Bool) : Option (Report w) :=
+ let trace := [.tick, .read (pub 0) flag] ++ List.replicate (2 * (i.val+1)) .tick
+ if bits.isEmpty then match t with
+ | .reject => none
+ | .accept => some ⟨trace, none⟩
+ | .jump s => some ⟨trace ++ [.tick, .tick, .write (pub 1) (Fin.ofNat _ s.val), .tick], some 0⟩
+ else none
+
+private theorem smaller (hw : 2 ≤ w) : (0 : Word w) ≠ 1 ∧ (0 : Word w) ≠ 2 ∧ (1 : Word w) ≠ 2 := by
+ have h := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ refine ⟨?_, ?_, ?_⟩ <;> intro h' <;>
+ have hv := congrArg Fin.val h' <;> simp [Nat.mod_eq_of_lt (by omega : 1 < 2^w),
+ Nat.mod_eq_of_lt (by omega : 2 < 2^w)] at hv
+
+private abbrev machine (target : Fin 3 → Target) (pub : Fin 2 → Word w) := (table target).instantiate w pub
+
+private theorem run_exit (target : Fin 3 → Target) (pub : Fin 2 → Word w) (pc : Fin 16) (t : Target)
+ (hc : (machine target pub).code pc = (destination t).resize w) (st : Word w) (r : Fin 4 → Word w)
+ (priv : Word w → Word w) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute (machine target pub).program (f+5) ⟨pc,st,r,priv⟩ m bits =
+ if bits.isEmpty then match t with
+ | .reject => none
+ | .accept => some ⟨[],none⟩
+ | .jump s => some ⟨[.tick,.tick,.write (pub 1) (Fin.ofNat _ s.val),.tick],some 0⟩
+ else none := by
+ cases t <;> cases bits <;> rw [execute] <;>
+ simp only [Machine.program, hc, destination, Instr.resize, Instr.run, Bool.false_eq_true,
+ List.isEmpty_nil,List.isEmpty_cons,ite_true,ite_false,List.cons_ne_nil]
+ all_goals rfl
+
+private theorem run_0 (target : Fin 3 → Target) (pub : Fin 2 → Word w) (st : Word w)
+ (r : Fin 4 → Word w) (priv : Word w → Word w) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute (machine target pub).program (f+1) ⟨0,st,r,priv⟩ m bits =
+ (execute (machine target pub).program f ⟨1,st,Function.update r 0 (pub 0),priv⟩ m bits).map (Report.prepend .tick) := rfl
+
+private theorem run_1 (target : Fin 3 → Target) (pub : Fin 2 → Word w) (st : Word w)
+ (r : Fin 4 → Word w) (priv : Word w → Word w) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute (machine target pub).program (f+1) ⟨1,st,r,priv⟩ m bits =
+ (execute (machine target pub).program f ⟨2,st,Function.update r 1 (m (r 0).val),priv⟩ m bits).map (Report.prepend (.read (r 0) (m (r 0).val))) := rfl
+
+private theorem run_2 (target : Fin 3 → Target) (pub : Fin 2 → Word w) (st : Word w)
+ (r : Fin 4 → Word w) (priv : Word w → Word w) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute (machine target pub).program (f+1) ⟨2,st,r,priv⟩ m bits =
+ (execute (machine target pub).program f ⟨3,st,Function.update r 2 0,priv⟩ m bits).map (Report.prepend .tick) := rfl
+
+private theorem run_3 (target : Fin 3 → Target) (pub : Fin 2 → Word w) (st : Word w)
+ (r : Fin 4 → Word w) (priv : Word w → Word w) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute (machine target pub).program (f+1) ⟨3,st,r,priv⟩ m bits =
+ (execute (machine target pub).program f ⟨if r 1 = r 2 then 9 else 4,st,r,priv⟩ m bits).map (Report.prepend .tick) := rfl
+
+private theorem run_4 (target : Fin 3 → Target) (pub : Fin 2 → Word w) (st : Word w)
+ (r : Fin 4 → Word w) (priv : Word w → Word w) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute (machine target pub).program (f+1) ⟨4,st,r,priv⟩ m bits =
+ (execute (machine target pub).program f ⟨5,st,Function.update r 2 1,priv⟩ m bits).map (Report.prepend .tick) := rfl
+
+private theorem run_5 (target : Fin 3 → Target) (pub : Fin 2 → Word w) (st : Word w)
+ (r : Fin 4 → Word w) (priv : Word w → Word w) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute (machine target pub).program (f+1) ⟨5,st,r,priv⟩ m bits =
+ (execute (machine target pub).program f ⟨if r 1 = r 2 then 10 else 6,st,r,priv⟩ m bits).map (Report.prepend .tick) := rfl
+
+private theorem run_6 (target : Fin 3 → Target) (pub : Fin 2 → Word w) (st : Word w)
+ (r : Fin 4 → Word w) (priv : Word w → Word w) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute (machine target pub).program (f+1) ⟨6,st,r,priv⟩ m bits =
+ (execute (machine target pub).program f ⟨7,st,Function.update r 2 2,priv⟩ m bits).map (Report.prepend .tick) := rfl
+
+private theorem run_7 (target : Fin 3 → Target) (pub : Fin 2 → Word w) (st : Word w)
+ (r : Fin 4 → Word w) (priv : Word w → Word w) (m : Memory w) (bits : List Bool) (f : ℕ) :
+ execute (machine target pub).program (f+1) ⟨7,st,r,priv⟩ m bits =
+ (execute (machine target pub).program f ⟨if r 1 = r 2 then 11 else 8,st,r,priv⟩ m bits).map (Report.prepend .tick) := rfl
+
+private theorem code_exit (target : Fin 3 → Target) (pub : Fin 2 → Word w) (i : Fin 3) :
+ (machine target pub).code (9+(i.val : Fin 16)) = (destination (target i)).resize w := by
+ fin_cases i <;> rfl
+
+/-- Successful routes have exactly the indicated source flag and destination.
+Unused choice bits reject, including at an immediate accepting exit. -/
+theorem execute_flag (hw : 2 ≤ w) (target : Fin 3 → Target) (pub : Fin 2 → Word w)
+ (st : Word w) (m : Memory w) (i : Fin 3) (hflag : m (pub 0).val = (i.val : Word w))
+ (bits : List Bool) (fuel : ℕ) :
+ let M := ((table target).instantiate w pub).program
+ execute M (fuel+13) (M.start st) m bits = report pub (m (pub 0).val) i (target i) bits := by
+ have ⟨h01,h02,h12⟩ := smaller hw
+ change execute (machine target pub).program (fuel+13) ⟨0,st,fun _ => 0,fun _ => 0⟩ m bits = _
+ fin_cases i
+ · change m (pub 0).val = 0 at hflag
+ simp only [run_0, run_1, run_2, run_3, Function.update_self, hflag, ite_true,
+ Function.update_of_ne (by decide : (1 : Fin 4) ≠ 2)]
+ have hc : (machine target pub).code 9 = (destination (target 0)).resize w := code_exit target pub 0
+ rw [run_exit target pub _ _ hc]
+ change _ = report pub 0 0 (target 0) bits
+ cases ht : target (0 : Fin 3) <;> cases bits <;> rfl
+ · change m (pub 0).val = 1 at hflag
+ simp only [run_0, run_1, run_2, run_3, run_4, run_5, Function.update_self, hflag, ite_true, ite_false,
+ Function.update_of_ne (by decide : (1 : Fin 4) ≠ 2), Ne.symm h01]
+ have hc : (machine target pub).code 10 = (destination (target 1)).resize w := code_exit target pub 1
+ rw [run_exit target pub _ _ hc]
+ change _ = report pub 1 1 (target 1) bits
+ cases ht : target (1 : Fin 3) <;> cases bits <;> rfl
+ · change m (pub 0).val = 2 at hflag
+ simp only [run_0, run_1, run_2, run_3, run_4, run_5, run_6, run_7, Function.update_self, hflag, ite_true, ite_false,
+ Function.update_of_ne (by decide : (1 : Fin 4) ≠ 2), Ne.symm h02, Ne.symm h12]
+ have hc : (machine target pub).code 11 = (destination (target 2)).resize w := code_exit target pub 2
+ rw [run_exit target pub _ _ hc]
+ change _ = report pub 2 2 (target 2) bits
+ cases ht : target (2 : Fin 3) <;> cases bits <;> rfl
+
+/-- An unrecognized flag value always rejects. -/
+theorem execute_unknown (target : Fin 3 → Target) (pub : Fin 2 → Word w)
+ (st : Word w) (m : Memory w) (h0 : m (pub 0).val ≠ 0) (h1 : m (pub 0).val ≠ 1)
+ (h2 : m (pub 0).val ≠ 2) (bits : List Bool) (fuel : ℕ) :
+ let M := ((table target).instantiate w pub).program
+ execute M (fuel+9) (M.start st) m bits = none := by
+ change execute (machine target pub).program (fuel+9) ⟨0,st,fun _ => 0,fun _ => 0⟩ m bits = none
+ simp only [run_0,run_1,run_2,run_3,run_4,run_5,run_6,run_7,Function.update_self,
+ Function.update_of_ne (by decide : (1 : Fin 4) ≠ 2),h0,h1,h2,ite_false]
+ rfl
+
+/-- A successful source decision consumes no choice and uses at most two
+external probes. The jump writes its tag and returns zero, and the accepting
+exit leaves memory untouched. -/
+theorem report_spec (pub : Fin 2 → Word w) (flag : Word w) (i : Fin 3) (t : Target)
+ (bs : List Bool) (rep : Report w) (h : report pub flag i t bs = some rep) (m : Memory w) :
+ bs = [] ∧ choiceBits rep.events = [] ∧ rep.probes ≤ 2 ∧
+ (match t with
+ | .reject => False
+ | .accept => rep.result = none ∧ after m rep.events = m
+ | .jump s => rep.result = some 0 ∧ after m rep.events = writeMemory m (pub 1) (Fin.ofNat _ s.val)) := by
+ cases bs with
+ | cons b bs => simp [report] at h
+ | nil =>
+ fin_cases i <;> cases t <;> simp [report] at h <;> subst rep <;> exact ⟨rfl,rfl,by simp [Report.probes,countProbes],rfl,rfl⟩
+
+end LiveProgram.Route
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveSelectedTerminalFrame.lean b/lean/OAI/Computability/VPVNP/LiveSelectedTerminalFrame.lean
new file mode 100644
index 0000000000..2e36d928ab
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveSelectedTerminalFrame.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.LiveCompressedPairVertexAssembly
+import OAI.Computability.VPVNP.PairTerminalProgramControl
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-! # Address protection on every prefix of the selected terminal traversal -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords SourceTransport NetworkKernel
+open PairSimulation LocalHistory TerminalLink
+open scoped Fin.CommRing
+attribute [local irreducible] VertexImage.template VertexImage.segments TerminalProgram.workers PhysicalScanData.physical stateScanPhase
+
+variable {a g v p r k : ℕ} (X : State a g) (M : Machine v p r k)
+ (pc : Fin 10 → Fin p) (reg : Fin 2 ↪ Fin r) (bank : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg bank done) (he : M.entry=pc 0)
+ (oldLow : ℕ) (bankAddr : M.publicData bank = FinalBits.cursor v oldLow 0) (oldMem : Memory v)
+ (extra : ℕ) (oldFit : oldLow + X.totalWidth < 2^v)
+
+local notation "scan₀" => stateScanPhase X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+
+variable {w cap ns labels : ℕ} {R : Type*} [CommRing R] {Label : Type} [Fintype Label] {κ : Label → R}
+ (parsers : SiteParsers κ X.network) (order : Fin ns ≃ X.network.Site) (names : Fin labels ≃ Label)
+ (shape : DescriptorSpace.Shape) (limit : ℕ) {geometry rootFields leaf shrink refresh : VertexImage.Segment}
+ (ports : Fin 11 → Word w)
+
+local notation "code" => VertexImage.segments geometry rootFields leaf shrink refresh
+local notation "workers₀" => TerminalProgram.workers shape limit code
+
+variable {mem : Memory w} (q : QuietPrefix (TerminalProgram.workers shape limit (VertexImage.segments geometry rootFields leaf shrink refresh)) ports cap mem)
+ (lo : ℕ) (beforeBits : Memory w) (wireLayout : FinalBits.Worker.Layout ports beforeBits lo X.totalWidth)
+ (clockRoom : 54 ≤ cap) (headerRoom : (header ports).val + 32 ≤ 2^w)
+ (below : lo + X.totalWidth ≤ (header ports).val)
+ (readAgree : Agree (workerCell (header ports)) beforeBits q.traversalRows.val.memory)
+
+local notation "shared" => PhysicalScanData.physical X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ shape limit code ports cap beforeBits q.traversalRows.val.memory lo wireLayout clockRoom headerRoom below readAgree
+
+variable (counter grammar : ℕ)
+local notation "siteFields" x => WireTensor.edgeAssignment X.network.src X.network.dst (ScanPhase.payload scan₀ x)
+local notation "ordinal" x => VertexImage.siteOrdinals parsers order names (siteFields x)
+local notation "machine₀" => Machine.program (Template.instantiate (VertexImage.template code) w ports)
+
+variable (visit : ∀ x : (stateScanPhase X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit).Path,
+ SelectedSites X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ parsers order names shape limit ports q lo beforeBits wireLayout clockRoom headerRoom below readAgree counter grammar x)
+
+include visit in
+/-- At every reached terminal call, including a last accepting report and
+any partial run without an accepting extension, an address before the
+wire bank and outside the motif counters retains its physical value. -/
+theorem selectedTerminalBranch_word (address : ℕ) (wireLow : address < lo)
+ (outside : address < counter+grammar ∨ counter+grammar+labels ≤ address)
+ (replayed : ReplayFrame address mem q.reportList)
+ (valid : (Entry.resume TerminalLink.Stage.sharedBits (0 : Word w)).Valid (header ports) q.traversalRows.val.memory) :
+ BurstRAM.PreservesCell (TerminalLink.program workers₀ ports) cap 0 mem address := by
+ have low : address < (header ports).val := by omega
+ have cell : workerCell (header ports) address := TerminalFootprint.below _ (by omega) low
+ intro st now tape out reached ran
+ exact TerminalProgram.preservesCell shape limit ports mem q shared address (by omega) (by omega) replayed valid
+ beforeBits wireLayout headerRoom readAgree (Or.inl wireLow) cell (fun x => ordinal x)
+ (fun x => (visit x).reference) (fun x => (visit x).active)
+ (fun x => (visit x).stored) (fun x => (visit x).physicalReady) outside reached ran
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveSelectedVertexCounters.lean b/lean/OAI/Computability/VPVNP/LiveSelectedVertexCounters.lean
new file mode 100644
index 0000000000..24e446ecd8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveSelectedVertexCounters.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.LiveCompressedPairVertexAssembly
+import OAI.Computability.VPVNP.LiveVertexJobDeposits
+
+/-! # Deposits of the actual selected terminal branch on its input counters -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords SourceTransport NetworkKernel
+open PairSimulation LocalHistory TerminalLink
+open scoped Fin.CommRing
+
+attribute [local irreducible] VertexImage.template VertexImage.segments TerminalProgram.workers PhysicalScanData.physical stateScanPhase
+
+variable {a g v p r k : ℕ} (X : State a g) (M : Machine v p r k)
+ (pc : Fin 10 → Fin p) (reg : Fin 2 ↪ Fin r) (bank : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg bank done) (he : M.entry=pc 0)
+ (oldLow : ℕ) (bankAddr : M.publicData bank = FinalBits.cursor v oldLow 0) (oldMem : Memory v)
+ (extra : ℕ) (oldFit : oldLow + X.totalWidth < 2^v)
+
+local notation "scan₀" => stateScanPhase X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+
+variable {w cap ns labels : ℕ} {R : Type*} [CommRing R] {Label : Type} [Fintype Label] {κ : Label → R}
+ (parsers : SiteParsers κ X.network) (order : Fin ns ≃ X.network.Site) (names : Fin labels ≃ Label)
+ (shape : DescriptorSpace.Shape) (limit : ℕ) {geometry rootFields leaf shrink refresh : VertexImage.Segment}
+ (ports : Fin 11 → Word w)
+
+local notation "code" => VertexImage.segments geometry rootFields leaf shrink refresh
+local notation "workers₀" => TerminalProgram.workers shape limit code
+
+variable {mem : Memory w} (q : QuietPrefix (TerminalProgram.workers shape limit (VertexImage.segments geometry rootFields leaf shrink refresh)) ports cap mem)
+ (lo : ℕ) (beforeBits : Memory w) (wireLayout : FinalBits.Worker.Layout ports beforeBits lo X.totalWidth)
+ (clockRoom : 54 ≤ cap) (headerRoom : (header ports).val + 32 ≤ 2^w)
+ (below : lo + X.totalWidth ≤ (header ports).val)
+ (readAgree : Agree (workerCell (header ports)) beforeBits q.traversalRows.val.memory)
+
+local notation "shared" => PhysicalScanData.physical X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ shape limit code ports cap beforeBits q.traversalRows.val.memory lo wireLayout clockRoom headerRoom below readAgree
+
+variable (counter grammar : ℕ)
+local notation "siteFields" x => WireTensor.edgeAssignment X.network.src X.network.dst (ScanPhase.payload scan₀ x)
+local notation "ordinal" x => VertexImage.siteOrdinals parsers order names (siteFields x)
+local notation "machine₀" => Machine.program (Template.instantiate (VertexImage.template code) w ports)
+
+variable (visit : ∀ x : (stateScanPhase X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit).Path,
+ SelectedSites X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ parsers order names shape limit ports q lo beforeBits wireLayout clockRoom headerRoom below readAgree counter grammar x)
+
+local notation "branch" => selectedTerminalBranch X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ parsers order names shape limit ports q lo beforeBits wireLayout clockRoom headerRoom below readAgree counter grammar visit
+
+/-- On every counter cell the genuine last block writes exactly the
+selected jobs' deposits on the nominated pair memory. The shared-bit
+phase and the earlier metadata stages need only preserve the incoming
+word at this particular cell. -/
+theorem selectedTerminalBranch_deposited (x : TerminalData scan₀ parsers)
+ (trees : X.network.Site → DFS.VertexTree) (jobs : JobsFor parsers) (valid : JobsSpec parsers trees jobs)
+ (input : Memory w) (a : ℕ) (cell : workerCell (header ports) a)
+ (before : (visit x.arcs).sourceMem a = input a) :
+ ((branch).vertexPaths x.arcs x.choices).val.memory a =
+ Counters.visit counter grammar (fun v l => ((x.jobs jobs v).map (fun j => j.increment (names l))).sum)
+ (List.ofFn order) input a := by
+ have read := selectedTerminalBranch_readback X M pc reg bank done hl he oldLow bankAddr oldMem extra oldFit
+ parsers order names shape limit ports q lo beforeBits wireLayout clockRoom headerRoom below readAgree
+ counter grammar visit x.arcs x.choices
+ exact (read a cell).symm.trans (x.deposits order names trees jobs valid counter grammar (visit x.arcs).sourceMem input a before)
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveStageLink.lean b/lean/OAI/Computability/VPVNP/LiveStageLink.lean
new file mode 100644
index 0000000000..110ae3a9fa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveStageLink.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.RAMUniform
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Data.Nat.Log
+
+/-!
+# Linking finite native burst-RAM stages
+
+Each call reads a stage tag at a designated public address. It then runs the
+selected finite instruction table with fresh private memory and the original
+persistent word. A continuing return stays in that stage. An accepting exit
+can finish the entire program or store the next stage tag and return zero for
+its first call. The tables have distinct program-counter spaces and share their
+ordinary register and public-word spaces. Three extra registers hold the tag
+address, its value, and a comparison or transfer literal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveStageLink
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {d r k w : ℕ} {pcs : Fin d → ℕ}
+
+/-- Two startup instructions, a tag scan, relocated component code, and three
+post-accept instructions per possible transfer. -/
+abbrev Label (pcs : Fin d → ℕ) := Fin 2 ⊕ (Fin (d + 1) ⊕ (Fin d ⊕
+ (((i : Fin d) × Fin (pcs i)) ⊕ (Fin d × Fin 3))))
+
+/-- Number of linked program counters for bootstrap, tag scan, tag comparisons, component
+bodies, and three handoff positions per stage. -/
+def codeSize (pcs : Fin d → ℕ) := 2 + ((d + 1) + (d + ((∑ i, pcs i) + d * 3)))
+
+/-- A concrete numbering for the linked program, independent of the runtime word width. -/
+def labelEquiv (pcs : Fin d → ℕ) : Label pcs ≃ Fin (codeSize pcs) :=
+ let body := ((finSigmaFinEquiv (n := pcs)).sumCongr finProdFinEquiv).trans finSumFinEquiv
+ let compare := ((Equiv.refl (Fin d)).sumCongr body).trans finSumFinEquiv
+ let scan := ((Equiv.refl (Fin (d + 1))).sumCongr compare).trans finSumFinEquiv
+ ((Equiv.refl (Fin 2)).sumCongr scan).trans finSumFinEquiv
+
+/-- Linked program counter for one of the two bootstrap instructions. -/
+def boot (pcs : Fin d → ℕ) (j : Fin 2) := labelEquiv pcs (.inl j)
+/-- Linked program counter for a tag-scan position, including the terminal scan position after
+all stages. -/
+def scan (pcs : Fin d → ℕ) (j : Fin (d + 1)) := labelEquiv pcs (.inr (.inl j))
+/-- Linked program counter for the tag comparison with the specified stage. -/
+def compareTag (pcs : Fin d → ℕ) (j : Fin d) := labelEquiv pcs (.inr (.inr (.inl j)))
+/-- Embed a stage-local instruction address in the linked program's disjoint component-body
+region. -/
+def bodyPC (pcs : Fin d → ℕ) (s : Fin d) (j : Fin (pcs s)) := labelEquiv pcs (.inr (.inr (.inr (.inl ⟨s,j⟩))))
+/-- Linked program counter for one of a stage's three handoff instructions. -/
+def handoff (pcs : Fin d → ℕ) (s : Fin d) (j : Fin 3) := labelEquiv pcs (.inr (.inr (.inr (.inr (s,j)))))
+
+/-- Component register numbers occupy the low end of the common file. -/
+def reg (j : Fin r) : Fin (r + 3) := Fin.castAdd 3 j
+
+/-- First extra register after the component bank, holding the address of the outer tag cell. -/
+def addrReg (r : ℕ) : Fin (r + 3) := ⟨r, by omega⟩
+/-- Second extra register, holding the tag value read from external memory. -/
+def tagReg (r : ℕ) : Fin (r + 3) := ⟨r + 1, by omega⟩
+/-- Third extra register, used for the comparison or transfer literal. -/
+def tmpReg (r : ℕ) : Fin (r + 3) := ⟨r + 2, by omega⟩
+
+/-- Relocate each operand and jump target while preserving the ordinary
+opcode. A transfer replaces only the accepting halt of its component. -/
+def bodyInstr (s : Fin d) (next : Option (Fin d)) : Instr w (pcs s) r k → Instr w (codeSize pcs) (r+3) (k+1)
+ | .constant a val j => .constant (reg a) val (bodyPC pcs s j)
+ | .publicWord a x j => .publicWord (reg a) x.castSucc (bodyPC pcs s j)
+ | .stateWord a j => .stateWord (reg a) (bodyPC pcs s j)
+ | .copy a b j => .copy (reg a) (reg b) (bodyPC pcs s j)
+ | .binary op a b c j => .binary op (reg a) (reg b) (reg c) (bodyPC pcs s j)
+ | .loadPrivate a b j => .loadPrivate (reg a) (reg b) (bodyPC pcs s j)
+ | .storePrivate a b j => .storePrivate (reg a) (reg b) (bodyPC pcs s j)
+ | .jumpEq a b yes no => .jumpEq (reg a) (reg b) (bodyPC pcs s yes) (bodyPC pcs s no)
+ | .jumpLt a b yes no => .jumpLt (reg a) (reg b) (bodyPC pcs s yes) (bodyPC pcs s no)
+ | .choose yes no => .choose (bodyPC pcs s yes) (bodyPC pcs s no)
+ | .readExternal a b j => .readExternal (reg a) (reg b) (bodyPC pcs s j)
+ | .writeExternal a b j => .writeExternal (reg a) (reg b) (bodyPC pcs s j)
+ | .returnState a => .returnState (reg a)
+ | .reject => .reject
+ | .accept => match next with
+ | none => .accept
+ | some t => .constant (tmpReg r) (Fin.ofNat _ t.val) (handoff pcs s 0)
+
+variable (T : (s : Fin d) → Template (pcs s) r k) (next : Fin d → Option (Fin d))
+
+/-- The literal width accommodates every component constant and every stage tag. -/
+def literalWidth := max (Finset.univ.sup fun s => (T s).literalWidth) (Nat.clog 2 d)
+
+/-- Encode a stage ordinal as a RAM word at the specified width. -/
+def tagWord (w : ℕ) (s : Fin d) : Word w := Fin.ofNat _ s.val
+
+private def instruction : Label pcs → Instr (literalWidth T) (codeSize pcs) (r+3) (k+1)
+ | .inl 0 => .publicWord (addrReg r) (Fin.last k) (boot pcs 1)
+ | .inl 1 => .readExternal (tagReg r) (addrReg r) (scan pcs 0)
+ | .inr (.inl i) => if h : i.val < d then
+ .constant (tmpReg r) (tagWord _ ⟨i.val,h⟩) (compareTag pcs ⟨i.val,h⟩) else .reject
+ | .inr (.inr (.inl s)) => .jumpEq (tagReg r) (tmpReg r) (bodyPC pcs s (T s).entry) (scan pcs s.succ)
+ | .inr (.inr (.inr (.inl ⟨s,j⟩))) => bodyInstr s (next s) (((T s).code j).resize _)
+ | .inr (.inr (.inr (.inr (s,0)))) => .writeExternal (addrReg r) (tmpReg r) (handoff pcs s 1)
+ | .inr (.inr (.inr (.inr (s,1)))) => .constant (tmpReg r) 0 (handoff pcs s 2)
+ | .inr (.inr (.inr (.inr (_,2)))) => .returnState (tmpReg r)
+
+/-- Combine the stage tables and successor map into a native template with three extra
+registers and one extra public tag-address operand. -/
+def linked : Template (codeSize pcs) (r+3) (k+1) where
+ literalWidth := literalWidth T
+ entry := boot pcs 0
+ code j := instruction T next ((labelEquiv pcs).symm j)
+
+/-- Extend the ordinary public words with the reserved external tag address. -/
+def publicData (pub : Fin k → Word w) (addr : Word w) : Fin (k+1) → Word w := Fin.snoc pub addr
+
+/-- Instantiate the linked template with the component public words and the tag-cell address. -/
+def machine (pub : Fin k → Word w) (addr : Word w) := (linked T next).instantiate w (publicData pub addr)
+
+private theorem tag_fits (s : Fin d) : s.val < 2 ^ literalWidth T := by
+ exact s.isLt.trans_le ((Nat.le_pow_clog (by decide : 1 < 2) d).trans
+ (Nat.pow_le_pow_right (by decide) (le_max_right _ _)))
+
+variable (pub : Fin k → Word w) (addr : Word w)
+
+@[simp] theorem code_boot0 : (machine T next pub addr).code (boot pcs 0) =
+ .publicWord (addrReg r) (Fin.last k) (boot pcs 1) := by
+ simp [machine, linked, Template.instantiate, boot, instruction, Instr.resize]
+
+@[simp] theorem code_boot1 : (machine T next pub addr).code (boot pcs 1) =
+ .readExternal (tagReg r) (addrReg r) (scan pcs 0) := by
+ simp [machine, linked, Template.instantiate, boot, instruction, Instr.resize]
+
+@[simp] theorem code_scan (s : Fin d) : (machine T next pub addr).code (scan pcs s.castSucc) =
+ .constant (tmpReg r) (tagWord w s) (compareTag pcs s) := by
+ simp [machine, linked, Template.instantiate, scan, instruction, s.isLt, Instr.resize, tagWord, Nat.mod_eq_of_lt (tag_fits T s)]
+
+@[simp] theorem code_scan_end : (machine T next pub addr).code (scan pcs (Fin.last d)) = .reject := by
+ simp [machine, linked, Template.instantiate, scan, instruction, Instr.resize]
+
+@[simp] theorem code_compareTag (s : Fin d) : (machine T next pub addr).code (compareTag pcs s) =
+ .jumpEq (tagReg r) (tmpReg r) (bodyPC pcs s (T s).entry) (scan pcs s.succ) := by
+ simp [machine, linked, Template.instantiate, compareTag, instruction, Instr.resize]
+
+@[simp] theorem code_handoff0 (s : Fin d) : (machine T next pub addr).code (handoff pcs s 0) =
+ .writeExternal (addrReg r) (tmpReg r) (handoff pcs s 1) := by
+ simp [machine, linked, Template.instantiate, handoff, instruction, Instr.resize]
+
+@[simp] theorem code_handoff1 (s : Fin d) : (machine T next pub addr).code (handoff pcs s 1) =
+ .constant (tmpReg r) 0 (handoff pcs s 2) := by
+ simp [machine, linked, Template.instantiate, handoff, instruction, Instr.resize]
+
+@[simp] theorem code_handoff2 (s : Fin d) : (machine T next pub addr).code (handoff pcs s 2) =
+ .returnState (tmpReg r) := by simp [machine, linked, Template.instantiate, handoff, instruction, Instr.resize]
+
+@[simp] theorem code_body (s : Fin d) (j : Fin (pcs s)) :
+ (machine T next pub addr).code (bodyPC pcs s j) = bodyInstr s (next s) ((T s).instantiate w pub |>.code j) := by
+ have h : (T s).literalWidth ≤ literalWidth T :=
+ (Finset.le_sup (f := fun t => (T t).literalWidth) (Finset.mem_univ s)).trans (le_max_left _ _)
+ simp only [machine, linked, Template.instantiate, bodyPC, Equiv.symm_apply_apply, instruction]
+ generalize (T s).code j = i
+ have hc (v : Word (T s).literalWidth) : v.val < 2 ^ literalWidth T :=
+ v.isLt.trans_le (Nat.pow_le_pow_right (by decide) h)
+ cases i <;> cases next s <;> simp [bodyInstr, Instr.resize, bodyPC, Nat.mod_eq_of_lt (hc _),
+ Nat.mod_eq_of_lt (tag_fits T _)]
+
+end LiveStageLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveStageLinkInversion.lean b/lean/OAI/Computability/VPVNP/LiveStageLinkInversion.lean
new file mode 100644
index 0000000000..5cdc953629
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveStageLinkInversion.lean
@@ -0,0 +1,63 @@
+import OAI.Computability.VPVNP.LiveStagePaths
+
+/-! # Recovering an accepting source segment from an accepting linked run -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveStageLink
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {d r k w : ℕ} {pcs : Fin d → ℕ}
+variable (T : (s : Fin d) → Template (pcs s) r k) (next : Fin d → Option (Fin d))
+variable (pub : Fin k → Word w) (addr : Word w)
+
+/-- Every successful call at a valid stage tag arises from its actual source
+table on the same bit string. This direction uses exactly the remaining fuel. -/
+theorem recover_call {cap : ℕ} (s : Fin d) (hfits : d ≤ 2^w) (hcap : 2*d+2 ≤ cap)
+ (st : Word w) (m : Memory w) (bits : List Bool) (out : Report w)
+ (htag : m addr.val = tagWord w s)
+ (he : execute (machine T next pub addr).program cap ((machine T next pub addr).program.start st) m bits = some out) :
+ ∃ rep, execute ((T s).instantiate w pub).program (cap-(dispatchEvents addr s).length)
+ (((T s).instantiate w pub).program.start st) m bits = some rep ∧ out = linkedReport next addr s rep := by
+ have hlen : (dispatchEvents addr s).length ≤ cap := by simp [dispatchEvents]; have := s.isLt; omega
+ have h := execute_linked T next pub addr s hfits st (cap-(dispatchEvents addr s).length) m htag bits
+ dsimp only at h
+ rw [Nat.sub_add_cancel hlen, he] at h
+ obtain ⟨ex, hb, hr⟩ := Option.map_eq_some_iff.mp h.symm
+ obtain ⟨rep, hs, hx⟩ := Option.bind_eq_some_iff.mp hb
+ refine ⟨rep, hs, ?_⟩
+ dsimp only [boundedExit] at hx
+ split at hx <;> simp_all [linkedReport]
+
+/-- An accepting run beginning at a known tag contains a complete accepting
+source segment for that tag before any later component can execute. -/
+theorem recover_accepting_stage {cap : ℕ} (s : Fin d) (hfits : d ≤ 2^w) (hcap : 2*d+2 ≤ cap)
+ (st : Word w) (m : Memory w) (bits : List (List Bool)) (out : List (Report w))
+ (htag : m addr.val = tagWord w s)
+ (hframe : ∀ (cursor : Word w) mem b rep,
+ execute ((T s).instantiate w pub).program (cap-(dispatchEvents addr s).length)
+ (((T s).instantiate w pub).program.start cursor) mem b = some rep →
+ rep.result.isSome → after mem rep.events addr.val = mem addr.val)
+ (hr : runSegment (machine T next pub addr).program cap (some st) m bits = some out)
+ (he : endState (some st) out = none) :
+ ∃ before rest rs, bits = before ++ rest ∧
+ runSegment ((T s).instantiate w pub).program (cap-(dispatchEvents addr s).length) (some st) m before = some rs ∧
+ endState (some st) rs = none := by
+ let fuel := cap-(dispatchEvents addr s).length
+ have hlen : (dispatchEvents addr s).length ≤ cap := by simp [dispatchEvents]; have := s.isLt; omega
+ have hfuel : fuel+(dispatchEvents addr s).length = cap := Nat.sub_add_cancel hlen
+ have hstable : TagFrame T pub addr s fuel (fun _ _ => True) := by
+ intro cursor mem b rep st' _ ht hc hv
+ exact ⟨trivial,(hframe cursor mem b rep hc (by simp [hv])).trans ht⟩
+ rw [← hfuel] at hr
+ obtain ⟨before,rest,rs,_,_,hbits,_,completion,_,_⟩ := split_halted hfits hstable trivial htag hr he
+ exact ⟨before,rest,rs,hbits,completion.spec.1,completion.spec.2.1⟩
+
+end LiveStageLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveStageLinkPaths.lean b/lean/OAI/Computability/VPVNP/LiveStageLinkPaths.lean
new file mode 100644
index 0000000000..5351e35646
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveStageLinkPaths.lean
@@ -0,0 +1,193 @@
+import OAI.Computability.VPVNP.LiveStageLinkRun
+
+/-!
+# Consecutive calls and overhead of the linked program
+
+The component interpreter reads the stage tag at each call boundary, runs its
+own instruction table, and updates the shared memory from its report. It agrees
+exactly with the linked finite instruction table on every path, including
+malformed tags, unused branch bits, and calls after termination.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveStageLink
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {d r k w : ℕ} {pcs : Fin d → ℕ}
+variable (T : (s : Fin d) → Template (pcs s) r k) (next : Fin d → Option (Fin d))
+variable (pub : Fin k → Word w) (addr : Word w)
+
+/-- The full external trace, including the deterministic dispatcher and transfer. -/
+def linkedReport (next : Fin d → Option (Fin d)) (addr : Word w) (s : Fin d) (rep : Report w) : Report w :=
+ prependLog (dispatchEvents addr s) (exitReport next addr s rep)
+
+private theorem probe_append (es fs : List (Event w)) : countProbes (es ++ fs) = countProbes es + countProbes fs := by
+ induction es with
+ | nil => simp [countProbes]
+ | cons e es ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+private theorem bits_append (es fs : List (Event w)) : choiceBits (es ++ fs) = choiceBits es ++ choiceBits fs := by
+ induction es with
+ | nil => simp [choiceBits]
+ | cons e es ih => cases e <;> simp [choiceBits, ih]
+
+private theorem ticks (n : ℕ) : countProbes (List.replicate n (.tick : Event w)) = 0 ∧
+ choiceBits (List.replicate n (.tick : Event w)) = [] := by
+ induction n with
+ | zero => simp [countProbes, choiceBits]
+ | succ n ih => simpa [List.replicate_succ, countProbes, choiceBits] using ih
+
+private theorem after_ticks (n : ℕ) (m : Memory w) : after m (List.replicate n .tick) = m := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa [List.replicate_succ, after, update] using ih
+
+/-- The linker never guesses an additional bit and never merges two paths with
+identical computed states but different original branch choices. -/
+theorem linkedReport_choiceBits (s : Fin d) (rep : Report w) :
+ choiceBits (linkedReport next addr s rep).events = choiceBits rep.events := by
+ cases rep with | mk es val =>
+ cases val <;> cases h : next s <;>
+ simp [linkedReport, prependLog, exitReport, dispatchEvents, transferEvents, h,
+ bits_append, choiceBits, (ticks (w := w) _).2]
+
+/-- Each call adds the tag read and at most one transfer write. -/
+theorem linkedReport_probes (s : Fin d) (rep : Report w) :
+ (linkedReport next addr s rep).probes = rep.probes + 1 +
+ if rep.result = none ∧ (next s).isSome then 1 else 0 := by
+ cases rep with | mk es val =>
+ cases val <;> cases h : next s <;>
+ simp [Report.probes, linkedReport, prependLog, exitReport, dispatchEvents, transferEvents, h,
+ probe_append, countProbes, (ticks (w := w) _).1] <;> omega
+
+/-- At most `2d+5` extra instruction dispatches per call. The difference
+in report lengths equals the difference in total dispatches, since both
+computations use one final instruction after their logged events. -/
+theorem linkedReport_length_le (s : Fin d) (rep : Report w) :
+ (linkedReport next addr s rep).events.length ≤ rep.events.length + 2*d + 5 := by
+ cases rep with | mk es val =>
+ cases val <;> cases h : next s <;>
+ simp [linkedReport, prependLog, exitReport, dispatchEvents, transferEvents, h] <;>
+ have := s.isLt <;> omega
+
+/-- The external memory transition is exactly that of the component, followed
+by the one tag write when its accepting exit is connected to a further stage. -/
+theorem linkedReport_after (s : Fin d) (rep : Report w) (m : Memory w) :
+ after m (linkedReport next addr s rep).events = match rep.result, next s with
+ | none, some dest => writeMemory (after m rep.events) addr (tagWord w dest)
+ | _, _ => after m rep.events := by
+ have ha (u v : List (Event w)) : after m (u ++ v) = after (after m u) v := by
+ simp [after, List.foldl_append]
+ have hprefix : after m (dispatchEvents addr s) = m := by
+ simpa [dispatchEvents, after, update] using after_ticks (2 * (s.val + 1)) m
+ cases rep with | mk es val =>
+ cases val <;> cases h : next s <;>
+ simp only [linkedReport, prependLog, exitReport, h, ha, hprefix, transferEvents]
+ all_goals rfl
+
+/-- Replay a single call directly in its source component. Fuel remaining after
+dispatch is charged for any transfer as well as the original component trace. -/
+def stageCall (fuel : ℕ) (st : Word w) (m : Memory w) (bits : List Bool) : Option (Report w) :=
+ if h : (m addr.val).val < d then
+ let s : Fin d := ⟨(m addr.val).val, h⟩
+ let cap := fuel - (dispatchEvents addr s).length
+ let M := ((T s).instantiate w pub).program
+ (((execute M cap (M.start st) m bits).bind (boundedExit next addr s cap))).map
+ (prependLog (dispatchEvents addr s))
+ else none
+
+theorem execute_eq_stageCall (hfits : d ≤ 2^w) (fuel : ℕ) (hcap : 2*d+2 ≤ fuel)
+ (st : Word w) (m : Memory w) (bits : List Bool) :
+ let L := (machine T next pub addr).program
+ execute L fuel (L.start st) m bits = stageCall T next pub addr fuel st m bits := by
+ dsimp only
+ unfold stageCall
+ split_ifs with h
+ · let s : Fin d := ⟨(m addr.val).val, h⟩
+ have htag : m addr.val = tagWord w s := Fin.ext (by simp [s, tagWord])
+ have hl : (dispatchEvents addr s).length ≤ fuel := by
+ simp [dispatchEvents]; have := s.isLt; omega
+ simpa only [Nat.sub_add_cancel hl] using
+ execute_linked T next pub addr s hfits st (fuel - (dispatchEvents addr s).length) m htag bits
+ · exact execute_invalid T next pub addr hfits st fuel m (Nat.le_of_not_gt h) bits
+
+private theorem guessed_addFuel {C : Type*} {P : Program w C} {f : ℕ} {c : C} {es out}
+ (h : Guessed P f c es out) (pad : ℕ) : Guessed P (f + pad) c es out := by
+ induction h with
+ | done hs => simpa [Nat.succ_add] using Guessed.done (f := _ + pad) hs
+ | step hs _ ih => simpa [Nat.succ_add] using Guessed.step hs ih
+ | branch hs _ ih => simpa [Nat.succ_add] using Guessed.branch hs ih
+ | read hs _ ih => simpa [Nat.succ_add] using Guessed.read hs ih
+ | write hs _ ih => simpa [Nat.succ_add] using Guessed.write hs ih
+
+private theorem guessed_length {C : Type*} {P : Program w C} {f : ℕ} {c : C} {es out}
+ (h : Guessed P f c es out) : es.length < f := by induction h <;> simp_all
+
+/-- An ordinary successful component call can be used directly at any linked cap
+with `2d+5` units of slack. Its exact branch string and computed report are retained. -/
+theorem execute_linked_of_stage {f cap : ℕ} (s : Fin d) (hfits : d ≤ 2^w)
+ (hcap : f + 2*d + 5 ≤ cap) (st : Word w) (m : Memory w) (htag : m addr.val = tagWord w s)
+ (bits : List Bool) (rep : Report w)
+ (hcall : execute ((T s).instantiate w pub).program f (((T s).instantiate w pub).program.start st) m bits = some rep) :
+ execute (machine T next pub addr).program cap ((machine T next pub addr).program.start st) m bits =
+ some (linkedReport next addr s rep) := by
+ let startup := (dispatchEvents addr s).length
+ have hs : startup ≤ 2*d+2 := by simp [startup, dispatchEvents]; have := s.isLt; omega
+ have hf : f ≤ cap - startup := by omega
+ obtain ⟨hg, hm, hbits⟩ := execute_spec hcall
+ have hr : execute ((T s).instantiate w pub).program (cap-startup)
+ (((T s).instantiate w pub).program.start st) m bits = some rep := by
+ apply execute_iff.mpr
+ refine ⟨?_, hm, hbits⟩
+ simpa only [Nat.add_sub_cancel' hf] using guessed_addFuel hg (cap-startup-f)
+ have hb : (exitReport next addr s rep).events.length < cap-startup := by
+ have hlen := guessed_length hg
+ have hroom : f + 3 ≤ cap-startup := by omega
+ cases rep with | mk es out =>
+ change es.length < f at hlen
+ cases out <;> cases he : next s <;> simp [exitReport, transferEvents, he] <;> omega
+ have h := execute_linked T next pub addr s hfits st (cap-startup) m htag bits
+ simpa only [show cap-startup+(dispatchEvents addr s).length = cap by omega, hr, Option.bind_some,
+ boundedExit, ite_eq_left hb, Option.map_some, linkedReport] using h
+
+/-- Path composition of the individual source stages, resetting private data
+on every call and using the exact post-state and memory of its predecessor. -/
+def stageSegment (fuel : ℕ) : Option (Word w) → Memory w → List (List Bool) → Option (List (Report w))
+ | _, _, [] => some []
+ | none, _, _ :: _ => none
+ | some st, m, bs :: more => do
+ let rep ← stageCall T next pub addr fuel st m bs
+ let tail ← stageSegment fuel rep.result (after m rep.events) more
+ return rep :: tail
+
+/-- The source-stage path composition and the native linked machine accept
+precisely the same per-call branch strings and produce identical reports. -/
+theorem runSegment_eq_stageSegment (hfits : d ≤ 2^w) (fuel : ℕ) (hcap : 2*d+2 ≤ fuel)
+ (st : Option (Word w)) (m : Memory w) (bits : List (List Bool)) :
+ runSegment (machine T next pub addr).program fuel st m bits =
+ stageSegment T next pub addr fuel st m bits := by
+ induction bits generalizing st m with
+ | nil => rfl
+ | cons bs more ih =>
+ cases st with
+ | none => rfl
+ | some st =>
+ rw [runSegment, stageSegment, execute_eq_stageCall T next pub addr hfits fuel hcap]
+ cases hs : stageCall T next pub addr fuel st m bs with
+ | none => rfl
+ | some rep =>
+ dsimp only
+ rw [ih]
+ change (stageSegment T next pub addr fuel rep.result (after m rep.events) more).map (rep :: ·) =
+ (stageSegment T next pub addr fuel rep.result (after m rep.events) more).bind (fun tail => some (rep :: tail))
+ cases stageSegment T next pub addr fuel rep.result (after m rep.events) more <;> rfl
+
+end LiveStageLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveStageLinkRun.lean b/lean/OAI/Computability/VPVNP/LiveStageLinkRun.lean
new file mode 100644
index 0000000000..a122d63d57
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveStageLinkRun.lean
@@ -0,0 +1,321 @@
+import OAI.Computability.VPVNP.LiveStageLink
+import OAI.Computability.VPVNP.RAMChain
+import OAI.Computability.VPVNP.RAMRecords
+import Mathlib.Tactic.FinCases
+
+/-!
+# Executing a linked native stage
+
+The dispatcher adds one external read per call. Within the selected component,
+registers, private memory, the persistent word and all branches have their
+ordinary meanings. Transferring an accepting exit adds one external write.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveStageLink
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {d r k w : ℕ} {pcs : Fin d → ℕ}
+variable (T : (s : Fin d) → Template (pcs s) r k) (next : Fin d → Option (Fin d))
+variable (pub : Fin k → Word w) (addr : Word w)
+
+private def extraRegs (addr tag tmp : Word w) (i : Fin 3) := if i = 0 then addr else if i = 1 then tag else tmp
+
+/-- Append the linker's address, tag, and temporary register values to the component registers. -/
+def withExtras (small : Fin r → Word w) (addr tag tmp : Word w) : Fin (r+3) → Word w :=
+ Fin.append small (extraRegs addr tag tmp)
+
+@[simp] theorem withExtras_reg (small : Fin r → Word w) (a t v : Word w) (j : Fin r) :
+ withExtras small a t v (reg j) = small j := by simp [withExtras, reg]
+
+@[simp] theorem withExtras_addr (small : Fin r → Word w) (a t v : Word w) :
+ withExtras small a t v (addrReg r) = a := by
+ change Fin.append small (extraRegs a t v) (Fin.natAdd r (0 : Fin 3)) = a
+ simp [extraRegs]
+
+@[simp] theorem withExtras_tag (small : Fin r → Word w) (a t v : Word w) :
+ withExtras small a t v (tagReg r) = t := by
+ change Fin.append small (extraRegs a t v) (Fin.natAdd r (1 : Fin 3)) = t
+ simp [extraRegs]
+
+@[simp] theorem withExtras_tmp (small : Fin r → Word w) (a t v : Word w) :
+ withExtras small a t v (tmpReg r) = v := by
+ change Fin.append small (extraRegs a t v) (Fin.natAdd r (2 : Fin 3)) = v
+ simp [extraRegs]
+
+private theorem update_reg (small : Fin r → Word w) (a t v x : Word w) (j : Fin r) :
+ Function.update (withExtras small a t v) (reg j) x = withExtras (Function.update small j x) a t v := by
+ funext i
+ cases i using Fin.addCases with
+ | left i =>
+ by_cases h : i = j
+ · subst i; simp [withExtras, reg]
+ · simp [withExtras, reg, Function.update, h]
+ | right i =>
+ have h : i.natAdd r ≠ j.castAdd 3 := by intro hh; have := congrArg Fin.val hh; simp at this; omega
+ simp [withExtras, reg, Function.update, h]
+
+private theorem update_extra (small : Fin r → Word w) (a t v x : Word w) (j : Fin 3) :
+ Function.update (withExtras small a t v) (j.natAdd r) x =
+ withExtras small (if j = 0 then x else a) (if j = 1 then x else t) (if j = 2 then x else v) := by
+ funext i
+ cases i using Fin.addCases with
+ | left i =>
+ have h : i.castAdd 3 ≠ j.natAdd r := by intro hh; have := congrArg Fin.val hh; simp at this; omega
+ simp [withExtras, Function.update, h]
+ | right i => fin_cases i <;> fin_cases j <;> simp [withExtras, extraRegs, Function.update]
+
+/-- Embed an arbitrary component configuration at its own relocated program counter. -/
+def embedConfig (s : Fin d) (addr tag tmp : Word w) (c : Config w (pcs s) r) : Config w (codeSize pcs) (r+3) :=
+ ⟨bodyPC pcs s c.pc, c.persistent, withExtras c.reg addr tag tmp, c.privateMem⟩
+
+private def mapAction {A B : Type*} (f : A → B) : CallAction w A → CallAction w B
+ | .localStep c => .localStep (f c)
+ | .branch q => .branch (f ∘ q)
+ | .read a q => .read a (f ∘ q)
+ | .write a v c => .write a v (f c)
+ | .finish s => .finish s
+ | .reject => .reject
+
+private theorem body_step (s : Fin d) (tag tmp : Word w) (c : Config w (pcs s) r)
+ (h : ((T s).instantiate w pub).code c.pc ≠ .accept ∨ next s = none) :
+ (machine T next pub addr).program.step (embedConfig s addr tag tmp c) =
+ mapAction (embedConfig s addr tag tmp) (((T s).instantiate w pub).program.step c) := by
+ change ((machine T next pub addr).code (bodyPC pcs s c.pc)).run (publicData pub addr) _ = _
+ rw [code_body]
+ change (bodyInstr s (next s) _).run _ _ = mapAction _ ((((T s).instantiate w pub).code c.pc).run pub c)
+ generalize heq : ((T s).instantiate w pub).code c.pc = op at h ⊢
+ cases op <;> simp only [bodyInstr, mapAction, Instr.run, embedConfig, Config.put, Config.store,
+ withExtras_reg, update_reg, publicData, Fin.snoc_castSucc, Function.comp_def]
+ all_goals first | rfl | (split <;> rfl) | (congr 1; funext b; cases b <;> rfl) | (rcases h with h | h <;> simp_all)
+
+/-- Overhead at an accepting exit that transfers to another stage. -/
+def transferEvents (addr : Word w) (dest : Fin d) : List (Event w) := [.tick, .write addr (tagWord w dest), .tick]
+
+/-- On an accepting exit with a successor, append the stage transfer events and return cursor
+zero. In other cases retain the component report. -/
+def exitReport (next : Fin d → Option (Fin d)) (addr : Word w) (s : Fin d) (rep : Report w) : Report w :=
+ match rep.result, next s with
+ | none, some dest => ⟨rep.events ++ transferEvents addr dest, some 0⟩
+ | _, _ => rep
+
+private theorem exitReport_prepend (s : Fin d) (rep : Report w) (ev : Event w) :
+ exitReport next addr s (rep.prepend ev) = (exitReport next addr s rep).prepend ev := by
+ cases rep with | mk es val => cases val <;> cases h : next s <;> simp [exitReport, Report.prepend, h]
+
+/-- An exact native report includes one final dispatch in addition to its events. -/
+def boundedExit (next : Fin d → Option (Fin d)) (addr : Word w) (s : Fin d) (fuel : ℕ)
+ (rep : Report w) : Option (Report w) :=
+ let out := exitReport next addr s rep
+ if out.events.length < fuel then some out else none
+
+private theorem bind_prepend (s : Fin d) (f : ℕ) (ev : Event w) (rep : Option (Report w)) :
+ (rep.bind (boundedExit next addr s f)).map (Report.prepend ev) =
+ (rep.map (Report.prepend ev)).bind (boundedExit next addr s (f+1)) := by
+ cases rep with
+ | none => rfl
+ | some r =>
+ simp only [Option.bind_some, Option.map_some, boundedExit]
+ rw [exitReport_prepend]
+ simp only [Report.prepend, List.length_cons, Nat.add_lt_add_iff_right]
+ split <;> rfl
+
+private theorem addr_ne_tmp : addrReg r ≠ tmpReg r := by
+ intro h; have hh := congrArg Fin.val h; dsimp [addrReg, tmpReg] at hh; omega
+
+private theorem body_transfer (s dest : Fin d) (tag tmp : Word w) (c : Config w (pcs s) r)
+ (ha : ((T s).instantiate w pub).code c.pc = .accept) (hd : next s = some dest)
+ (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute (machine T next pub addr).program fuel (embedConfig s addr tag tmp c) m bits =
+ (execute ((T s).instantiate w pub).program fuel c m bits).bind (boundedExit next addr s fuel) := by
+ rcases fuel with _ | _ | _ | _ | fuel <;> cases bits <;>
+ simp [execute, Machine.program, code_body, ha, hd, bodyInstr, Instr.run, Config.put, embedConfig,
+ Function.update_of_ne addr_ne_tmp, boundedExit, exitReport, transferEvents, Report.prepend, tagWord]
+
+/-- Exact finite-fuel semantics of a relocated component. In particular no
+additional successful paths are admitted by increasing the caller's fuel. -/
+theorem execute_body (s : Fin d) (tag tmp : Word w) (fuel : ℕ) (c : Config w (pcs s) r)
+ (m : Memory w) (bits : List Bool) :
+ execute (machine T next pub addr).program fuel (embedConfig s addr tag tmp c) m bits =
+ (execute ((T s).instantiate w pub).program fuel c m bits).bind (boundedExit next addr s fuel) := by
+ induction fuel generalizing c m bits with
+ | zero => rfl
+ | succ fuel ih =>
+ by_cases h : ((T s).instantiate w pub).code c.pc ≠ .accept ∨ next s = none
+ · rw [execute, body_step T next pub addr s tag tmp c h, execute]
+ cases hs : ((T s).instantiate w pub).program.step c with
+ | localStep c' => simp only [mapAction, ih]; exact bind_prepend ..
+ | read a q => simp only [mapAction, Function.comp_apply, ih]; exact bind_prepend ..
+ | write a v c' => simp only [mapAction, ih]; exact bind_prepend ..
+ | branch q => cases bits <;> simp only [mapAction, Function.comp_apply, ih, Option.bind_none]
+ exact bind_prepend ..
+ | reject => rfl
+ | finish out =>
+ have hout : out ≠ none ∨ next s = none := by
+ rcases h with h | h
+ · left; rintro rfl
+ change ((((T s).instantiate w pub).code c.pc).run pub c) = _ at hs
+ cases hi : ((T s).instantiate w pub).code c.pc <;> simp_all [Instr.run]
+ · exact Or.inr h
+ cases bits <;> cases out <;> cases hnext : next s <;>
+ simp_all [mapAction, boundedExit, exitReport]
+ · push Not at h
+ obtain ⟨dest, hd⟩ := Option.ne_none_iff_exists'.mp h.2
+ exact body_transfer T next pub addr s dest tag tmp c h.1 hd _ _ _
+
+/-- The dispatch instructions before the first opcode of the chosen component. -/
+def dispatchEvents (addr : Word w) (s : Fin d) : List (Event w) :=
+ .tick :: .read addr (tagWord w s) :: List.replicate (2 * (s.val + 1)) .tick
+
+/-- Prepend dispatch events to a component report, retaining its result. -/
+def prependLog (es : List (Event w)) (rep : Report w) : Report w := ⟨es ++ rep.events, rep.result⟩
+
+private def control (pc : Fin (codeSize pcs)) (state addr tag tmp : Word w) : Config w (codeSize pcs) (r+3) :=
+ ⟨pc, state, withExtras (fun _ => 0) addr tag tmp, fun _ => 0⟩
+
+private theorem update_addr (small : Fin r → Word w) (a t v x : Word w) :
+ Function.update (withExtras small a t v) (addrReg r) x = withExtras small x t v := by
+ simpa [addrReg, Fin.natAdd] using update_extra small a t v x (0 : Fin 3)
+
+private theorem update_tag (small : Fin r → Word w) (a t v x : Word w) :
+ Function.update (withExtras small a t v) (tagReg r) x = withExtras small a x v := by
+ simpa [tagReg, Fin.natAdd] using update_extra small a t v x (1 : Fin 3)
+
+private theorem update_tmp (small : Fin r → Word w) (a t v x : Word w) :
+ Function.update (withExtras small a t v) (tmpReg r) x = withExtras small a t x := by
+ simpa [tmpReg, Fin.natAdd] using update_extra small a t v x (2 : Fin 3)
+
+private theorem scan_pair (j : Fin d) (tag tmp st : Word w) (f : ℕ) (m : Memory w) (bits : List Bool) :
+ let L := (machine T next pub addr).program
+ let pc := if tag = tagWord w j then bodyPC pcs j (T j).entry else scan pcs j.succ
+ execute L (f+2) (control (scan pcs j.castSucc) st addr tag tmp) m bits =
+ (execute L f (control pc st addr tag (tagWord w j)) m bits).map (prependLog [.tick,.tick]) := by
+ dsimp only
+ simp only [execute, Machine.program, control, code_scan, Instr.run, Config.put,
+ update_tmp, code_compareTag, withExtras_tmp, withExtras_tag, Option.map_map]
+ rfl
+
+private theorem tagWord_injective (hfits : d ≤ 2^w) : Function.Injective (tagWord w (d := d)) := by
+ intro i j he
+ apply Fin.ext
+ simpa [tagWord, Nat.mod_eq_of_lt (i.isLt.trans_le hfits), Nat.mod_eq_of_lt (j.isLt.trans_le hfits)]
+ using congrArg Fin.val he
+
+private theorem scan_run (s : Fin d) (hfits : d ≤ 2^w) (st : Word w) (f : ℕ) (m : Memory w)
+ (bits : List Bool) (u : ℕ) (j : Fin d) (hjs : j.val + u = s.val) (tmp : Word w) :
+ let L := (machine T next pub addr).program
+ execute L (f + 2 * (u + 1)) (control (scan pcs j.castSucc) st addr (tagWord w s) tmp) m bits =
+ (execute L f (control (bodyPC pcs s (T s).entry) st addr (tagWord w s) (tagWord w s)) m bits).map
+ (prependLog (List.replicate (2 * (u + 1)) .tick)) := by
+ dsimp only
+ induction u generalizing j tmp with
+ | zero =>
+ have h : j = s := Fin.ext (by omega)
+ subst j
+ simpa using scan_pair T next pub addr s (tagWord w s) tmp st f m bits
+ | succ u ih =>
+ have hj : j.val < s.val := by omega
+ let j' : Fin d := ⟨j.val+1, by have := s.isLt; omega⟩
+ have hneq : tagWord w s ≠ tagWord w j := fun he => (Fin.ne_of_gt hj) (tagWord_injective hfits he)
+ rw [show f + 2 * (u + 1 + 1) = (f + 2 * (u + 1)) + 2 by omega,
+ scan_pair, ite_eq_right hneq, show j.succ = j'.castSucc from rfl,
+ ih j' (by dsimp [j']; omega), Option.map_map]
+ congr 1
+
+private theorem control_start (st : Word w) :
+ (machine T next pub addr).program.start st = control (boot pcs 0) st 0 0 0 := by
+ change Config.mk _ _ (fun _ => 0) _ = Config.mk _ _ _ _
+ congr 1
+ funext i
+ cases i using Fin.addCases with
+ | left i => simp [withExtras]
+ | right i => simp [withExtras, extraRegs]
+
+/-- Native call semantics, with the tag read, every comparison tick and the
+optional transition write displayed. `fuel` is the number of dispatches left
+for the component and its optional handoff. -/
+theorem execute_linked (s : Fin d) (hfits : d ≤ 2^w) (st : Word w) (fuel : ℕ) (m : Memory w)
+ (htag : m addr.val = tagWord w s) (bits : List Bool) :
+ let L := (machine T next pub addr).program
+ let S := ((T s).instantiate w pub).program
+ execute L (fuel + (dispatchEvents addr s).length) (L.start st) m bits =
+ ((execute S fuel (S.start st) m bits).bind (boundedExit next addr s fuel)).map
+ (prependLog (dispatchEvents addr s)) := by
+ dsimp only
+ rw [control_start]
+ have hr := scan_run T next pub addr s hfits st fuel m bits s.val (⟨0, by have := s.isLt; omega⟩ : Fin d)
+ (by simp) 0
+ dsimp only at hr
+ have he := execute_body T next pub addr s (tagWord w s) (tagWord w s) fuel
+ (((T s).instantiate w pub).program.start st) m bits
+ change execute _ _ (control (bodyPC pcs s (T s).entry) st addr (tagWord w s) (tagWord w s)) _ _ = _ at he
+ simp only [dispatchEvents, List.length_cons, List.length_replicate, ← Nat.add_assoc]
+ rw [execute]
+ have hpub : (machine T next pub addr).publicData (Fin.last k) = addr := by
+ change publicData pub addr (Fin.last k) = addr
+ simp [publicData]
+ simp only [control, Machine.program, code_boot0, Instr.run, Config.put, hpub,
+ update_addr, execute, code_boot1, withExtras_addr, htag, update_tag]
+ change (((execute (machine T next pub addr).program (fuel + 2 * (s.val + 1))
+ (control (scan pcs 0) st addr (tagWord w s) 0) m bits).map (Report.prepend (.read addr (tagWord w s)))).map
+ (Report.prepend .tick)) = ((execute ((T s).instantiate w pub).program fuel
+ (((T s).instantiate w pub).program.start st) m bits).bind (boundedExit next addr s fuel)).map
+ (prependLog (dispatchEvents addr s))
+ have hzero : (⟨0, by have := s.isLt; omega⟩ : Fin d).castSucc = (0 : Fin (d+1)) := Fin.ext (by simp)
+ rw [hzero] at hr
+ rw [hr, he, Option.map_map, Option.map_map]
+ rfl
+
+private theorem invalid_scan (tag st : Word w) (hbad : ∀ s : Fin d, tag ≠ tagWord w s)
+ (m : Memory w) (bits : List Bool) (remain : ℕ) (j : Fin (d+1)) (hj : j.val + remain = d)
+ (fuel : ℕ) (tmp : Word w) :
+ execute (machine T next pub addr).program fuel (control (scan pcs j) st addr tag tmp) m bits = none := by
+ induction remain generalizing j tmp fuel with
+ | zero =>
+ have h : j = Fin.last d := Fin.ext (by simp; omega)
+ subst j
+ cases fuel <;> simp [execute, Machine.program, control, Instr.run]
+ | succ remain ih =>
+ let i : Fin d := ⟨j.val, by omega⟩
+ have hi : j = i.castSucc := Fin.ext rfl
+ rw [hi]
+ rcases fuel with _ | _ | fuel
+ · rfl
+ · simp [execute, Machine.program, control, Instr.run]
+ · rw [scan_pair, ite_eq_right (hbad i), ih i.succ (by simp [i]; omega)]
+ rfl
+
+/-- An out-of-range stage tag rejects for every bit string and every instruction cap. -/
+theorem execute_invalid (hfits : d ≤ 2^w) (st : Word w) (fuel : ℕ) (m : Memory w)
+ (hbad : d ≤ (m addr.val).val) (bits : List Bool) :
+ let L := (machine T next pub addr).program
+ execute L fuel (L.start st) m bits = none := by
+ have hn (i : Fin d) : m addr.val ≠ tagWord w i := by
+ intro h
+ have hv := congrArg Fin.val h
+ simp [tagWord, Nat.mod_eq_of_lt (i.isLt.trans_le hfits)] at hv
+ omega
+ dsimp only
+ rw [control_start]
+ rcases fuel with _ | _ | fuel
+ · rfl
+ · simp [execute, Machine.program, control, Instr.run]
+ · have hpub : (machine T next pub addr).publicData (Fin.last k) = addr := by
+ change publicData pub addr (Fin.last k) = addr
+ simp [publicData]
+ simp only [execute, Machine.program, control, code_boot0, Instr.run, Config.put, hpub,
+ update_addr, code_boot1, withExtras_addr, update_tag]
+ change (((execute (machine T next pub addr).program fuel
+ (control (scan pcs 0) st addr (m addr.val) 0) m bits).map _).map _) = none
+ rw [invalid_scan T next pub addr (m addr.val) st hn m bits d 0 (by simp)]
+ rfl
+
+end LiveStageLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveStageOperands.lean b/lean/OAI/Computability/VPVNP/LiveStageOperands.lean
new file mode 100644
index 0000000000..10aabf0377
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveStageOperands.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.LiveStageLink
+import OAI.Computability.VPVNP.RAMChain
+
+/-!
+# Relocating the operands of a native component template
+
+The live stage linker uses one shared register and public-word format. This
+embedding allows arbitrary finite component tables, including their private
+loads, stores and jumps, to participate in that format. No extra instruction,
+probe or choice is introduced by operand relocation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveStageLink
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {r k r' k' p w : ℕ}
+
+/-- Relabel each native operand while keeping jump targets and literal words fixed. -/
+def relocate (ρ : Fin r → Fin r') (π : Fin k → Fin k') : Instr w p r k → Instr w p r' k'
+ | .constant a v j => .constant (ρ a) v j
+ | .publicWord a i j => .publicWord (ρ a) (π i) j
+ | .stateWord a j => .stateWord (ρ a) j
+ | .copy a b j => .copy (ρ a) (ρ b) j
+ | .binary op a b c j => .binary op (ρ a) (ρ b) (ρ c) j
+ | .loadPrivate a b j => .loadPrivate (ρ a) (ρ b) j
+ | .storePrivate a b j => .storePrivate (ρ a) (ρ b) j
+ | .jumpEq a b y n => .jumpEq (ρ a) (ρ b) y n
+ | .jumpLt a b y n => .jumpLt (ρ a) (ρ b) y n
+ | .choose y n => .choose y n
+ | .readExternal a b j => .readExternal (ρ a) (ρ b) j
+ | .writeExternal a b j => .writeExternal (ρ a) (ρ b) j
+ | .returnState a => .returnState (ρ a)
+ | .accept => .accept
+ | .reject => .reject
+
+/-- Relocate a template's registers and public operand references, preserving its entry and
+instruction positions. -/
+def widen (T : Template p r k) (ρ : Fin r ↪ Fin r') (π : Fin k → Fin k') : Template p r' k' where
+ literalWidth := T.literalWidth
+ entry := T.entry
+ code j := relocate ρ π (T.code j)
+
+/-- Project a relocated configuration onto its component registers while retaining the program
+counter, persistent word, and private memory. -/
+def restrictConfig (ρ : Fin r ↪ Fin r') (c : Config w p r') : Config w p r :=
+ ⟨c.pc, c.persistent, c.reg ∘ ρ, c.privateMem⟩
+
+private theorem restrict_put (ρ : Fin r ↪ Fin r') (c : Config w p r') (j : Fin p) (i : Fin r) (v : Word w) :
+ restrictConfig ρ (c.put j (ρ i) v) = (restrictConfig ρ c).put j i v := by
+ unfold Config.put restrictConfig
+ congr 1
+ funext a
+ by_cases h : a = i <;> simp [Function.comp_apply, h]
+
+private theorem relocate_resize {v : ℕ} (ρ : Fin r → Fin r') (π : Fin k → Fin k') (i : Instr v p r k) :
+ (relocate ρ π i).resize w = relocate ρ π (i.resize w) := by cases i <;> rfl
+
+private def projectAction (ρ : Fin r ↪ Fin r') :
+ CallAction w (Config w p r') → CallAction w (Config w p r)
+ | .localStep c => .localStep (restrictConfig ρ c)
+ | .branch q => .branch (restrictConfig ρ ∘ q)
+ | .read a q => .read a (restrictConfig ρ ∘ q)
+ | .write a v c => .write a v (restrictConfig ρ c)
+ | .finish s => .finish s
+ | .reject => .reject
+
+private theorem project_step (T : Template p r k) (ρ : Fin r ↪ Fin r') (π : Fin k → Fin k')
+ (pub : Fin k' → Word w) (c : Config w p r') :
+ projectAction ρ (((widen T ρ π).instantiate w pub).program.step c) =
+ (T.instantiate w (pub ∘ π)).program.step (restrictConfig ρ c) := by
+ simp only [Machine.program, Template.instantiate, widen, relocate_resize]
+ change projectAction ρ ((relocate ρ π ((T.code c.pc).resize w)).run pub c) =
+ ((T.code c.pc).resize w).run (pub ∘ π) (restrictConfig ρ c)
+ generalize (T.code c.pc).resize w = op
+ cases op <;> simp only [relocate, Instr.run, projectAction, Function.comp_def, restrict_put]
+ all_goals rfl
+
+/-- The enclosing register file executes the component on its own embedded
+operands, with identical event logs, returned words, and rejection behavior. -/
+theorem execute_widen (T : Template p r k) (ρ : Fin r ↪ Fin r') (π : Fin k → Fin k')
+ (pub : Fin k' → Word w) (fuel : ℕ) (c : Config w p r') (m : Memory w) (bits : List Bool) :
+ execute ((widen T ρ π).instantiate w pub).program fuel c m bits =
+ execute (T.instantiate w (pub ∘ π)).program fuel (restrictConfig ρ c) m bits := by
+ induction fuel generalizing c m bits with
+ | zero => rfl
+ | succ f ih =>
+ rw [execute, execute, ← project_step]
+ cases hs : ((widen T ρ π).instantiate w pub).program.step c <;> simp only [projectAction, Function.comp_apply]
+ all_goals first | rfl | (rw [ih]) | (cases bits <;> simp [ih])
+
+/-- At each fresh call boundary operand relocation has zero overhead. -/
+theorem execute_widen_start (T : Template p r k) (ρ : Fin r ↪ Fin r') (π : Fin k → Fin k')
+ (pub : Fin k' → Word w) (fuel : ℕ) (st : Word w) (m : Memory w) (bits : List Bool) :
+ let large := ((widen T ρ π).instantiate w pub).program
+ let small := (T.instantiate w (pub ∘ π)).program
+ execute large fuel (large.start st) m bits = execute small fuel (small.start st) m bits :=
+ execute_widen T ρ π pub fuel _ m bits
+
+end LiveStageLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveStagePaths.lean b/lean/OAI/Computability/VPVNP/LiveStagePaths.lean
new file mode 100644
index 0000000000..9fa86caa2d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveStagePaths.lean
@@ -0,0 +1,384 @@
+import OAI.Computability.VPVNP.LiveStageSegments
+import Mathlib.SetTheory.Cardinal.Finite
+
+/-!
+# Factoring native live-program paths at component completion
+
+A stage may take a different number of calls on each branch. The first
+accepting exit of its original opcode table still gives a unique split
+of the linked machine's private choices. The stage tag is preserved on
+continuing calls, and its accepting exit either writes a successor tag
+or halts. Fuel accounts for the dispatcher and the final transfer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveStageLink
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {w d r k : ℕ} {pcs : Fin d → ℕ}
+variable (T : (s : Fin d) → Template (pcs s) r k) (next : Fin d → Option (Fin d))
+variable (pub : Fin k → Word w) (addr : Word w) (s : Fin d)
+
+/-- Burst-RAM program of a single source stage, obtained by instantiating that stage's
+instruction template with the given public words. -/
+abbrev sourceProgram := ((T s).instantiate w pub).program
+
+/-- Linked burst-RAM program that reads the stage tag at the given address and follows the
+successor map on component completion. -/
+abbrev outerProgram := (machine T next pub addr).program
+
+/-- The continuation starts from a fresh zero state after transfer. -/
+def transferState (next : Fin d → Option (Fin d)) (s : Fin d) : Option (Word w) :=
+ (next s).map (fun _ => 0)
+
+/-- Each successful ordinary call leaves room for its linked exit. -/
+def room (fuel : ℕ) (rep : Report w) : Prop := (exitReport next addr s rep).events.length < fuel
+
+/-- The component may use scratch memory while preserving its outer stage
+tag throughout all calls which continue this component. -/
+def TagFrame (fuel : ℕ) (inv : Word w → Memory w → Prop) : Prop := ∀ st m bits rep st',
+ inv st m → m addr.val = tagWord w s →
+ execute (sourceProgram T pub s) fuel ((sourceProgram T pub s).start st) m bits = some rep →
+ rep.result = some st' → inv st' (after m rep.events) ∧ after m rep.events addr.val = tagWord w s
+
+/-- The exact first source-component completion with its final source memory.
+This relation includes every private choice and native report in its order. -/
+inductive Completion (fuel : ℕ) :
+ Word w → Memory w → List (List Bool) → List (Report w) → Memory w → Prop
+ | last {st m b rep}
+ (call : execute (sourceProgram T pub s) fuel ((sourceProgram T pub s).start st) m b = some rep)
+ (halt : rep.result = none) (fits : room next addr s fuel rep) :
+ Completion fuel st m [b] [rep] (after m rep.events)
+ | more {st m b rep st' bs reps m'}
+ (call : execute (sourceProgram T pub s) fuel ((sourceProgram T pub s).start st) m b = some rep)
+ (cont : rep.result = some st') (fits : room next addr s fuel rep)
+ (tail : Completion fuel st' (after m rep.events) bs reps m') :
+ Completion fuel st m (b :: bs) (rep :: reps) m'
+
+variable {T next pub addr s}
+
+theorem Completion.spec {fuel st m bs reps m'} (h : Completion T next pub addr s fuel st m bs reps m') :
+ runSegment (sourceProgram T pub s) fuel (some st) m bs = some reps ∧
+ endState (some st) reps = none ∧ after m (eventLog reps) = m' ∧ ∀ rep ∈ reps, room next addr s fuel rep := by
+ induction h with
+ | last hc ht hf => simp [runSegment, hc, endState, ht, eventLog, hf]
+ | more hc ht hf _ ih =>
+ refine ⟨by simp only [runSegment, hc, ht, ih.1, Option.map_some],
+ by simpa only [endState, ht] using ih.2.1, ?_, List.forall_mem_cons.mpr ⟨hf, ih.2.2.2⟩⟩
+ simpa only [eventLog, List.flatMap_cons, after, List.foldl_append] using ih.2.2.1
+
+theorem completion_of_run {fuel st m bs reps}
+ (h : runSegment (sourceProgram T pub s) fuel (some st) m bs = some reps)
+ (halt : endState (some st) reps = none) (fits : ∀ rep ∈ reps, room next addr s fuel rep) :
+ Completion T next pub addr s fuel st m bs reps (after m (eventLog reps)) := by
+ induction bs generalizing st m reps with
+ | nil =>
+ simp [runSegment] at h
+ subst reps
+ contradiction
+ | cons b bs ih =>
+ rw [runSegment] at h
+ cases hc : execute (sourceProgram T pub s) fuel ((sourceProgram T pub s).start st) m b with
+ | none => simp [hc] at h
+ | some rep =>
+ rw [hc, Option.map_eq_some_iff] at h
+ obtain ⟨rs, hr, rfl⟩ := h
+ change endState rep.result rs = none at halt
+ obtain ⟨hf,ht⟩ := List.forall_mem_cons.mp fits
+ cases he : rep.result with
+ | none =>
+ rw [he] at hr
+ cases bs with
+ | nil =>
+ simp [runSegment] at hr
+ subst rs
+ simpa [eventLog] using Completion.last hc he hf
+ | cons _ _ => contradiction
+ | some st' =>
+ rw [he] at hr halt
+ simpa only [eventLog, List.flatMap_cons, after, List.foldl_append] using
+ Completion.more hc he hf (ih hr halt ht)
+
+private theorem linked_ok {fuel st m b rep} (hfit : d ≤ 2^w)
+ (htag : m addr.val = tagWord w s)
+ (call : execute (sourceProgram T pub s) fuel ((sourceProgram T pub s).start st) m b = some rep)
+ (fits : room next addr s fuel rep) :
+ execute (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length)
+ ((outerProgram T next pub addr).start st) m b = some (linkedReport next addr s rep) := by
+ rw [execute_linked T next pub addr s hfit st fuel m htag b, call]
+ simp [boundedExit, room] at fits ⊢
+ exact ⟨fits, rfl⟩
+
+private theorem linked_inv {fuel st m b out} (hfit : d ≤ 2^w)
+ (htag : m addr.val = tagWord w s)
+ (call : execute (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length)
+ ((outerProgram T next pub addr).start st) m b = some out) :
+ ∃ rep, execute (sourceProgram T pub s) fuel ((sourceProgram T pub s).start st) m b = some rep ∧
+ room next addr s fuel rep ∧ out = linkedReport next addr s rep := by
+ rw [execute_linked T next pub addr s hfit st fuel m htag b] at call
+ cases hs : execute (sourceProgram T pub s) fuel ((sourceProgram T pub s).start st) m b with
+ | none => simp [hs] at call
+ | some rep =>
+ refine ⟨rep,rfl,?_⟩
+ simp only [hs, Option.bind_some, boundedExit] at call
+ split at call
+ · rename_i hf
+ exact ⟨hf, (Option.some.inj call).symm⟩
+ · contradiction
+
+private theorem linked_continue {rep : Report w} {st : Word w} (h : rep.result = some st) :
+ (linkedReport next addr s rep).result = some st := by simp [linkedReport, prependLog, exitReport, h]
+
+private theorem linked_last {rep : Report w} (h : rep.result = none) :
+ (linkedReport next addr s rep).result = transferState (w := w) next s := by
+ cases hs : next s <;> simp [linkedReport, prependLog, exitReport, transferState, h, hs]
+
+private theorem memory_last {rep : Report w} {m : Memory w} (h : rep.result = none) :
+ after m (linkedReport next addr s rep).events = transferMemory addr (next s) (after m rep.events) := by
+ rw [linkedReport_after]
+ cases next s <;> simp [transferMemory, h]
+
+/-- An ordinary completed stage splices into any continuation without adding
+branch choices. Every native report of that stage gains its linker events. -/
+theorem Completion.splice {fuel st m bs reps m'} (h : Completion T next pub addr s fuel st m bs reps m')
+ (fit : d ≤ 2^w) {inv : Word w → Memory w → Prop} (frame : TagFrame T pub addr s fuel inv)
+ (hi : inv st m) (htag : m addr.val = tagWord w s) (tail : List (List Bool)) :
+ let P := outerProgram T next pub addr
+ let cap := fuel+(dispatchEvents addr s).length
+ runSegment P cap (some st) m (bs ++ tail) =
+ (runSegment P cap (transferState next s) (transferMemory addr (next s) m') tail).map
+ ((reps.map (linkedReport next addr s)) ++ ·) := by
+ dsimp only
+ induction h with
+ | last hc hh hf =>
+ simp only [List.singleton_append, runSegment, linked_ok fit htag hc hf, linked_last hh, memory_last hh,
+ List.map_cons, List.map_nil, List.singleton_append]
+ | more hc hh hf _ ih =>
+ simp only [List.cons_append, runSegment, linked_ok fit htag hc hf, linked_continue hh, linkedReport_after, hh]
+ obtain ⟨hi',ht'⟩ := frame _ _ _ _ _ hi htag hc hh
+ rw [ih hi' ht']
+ simp [Option.map_map, Function.comp_def]
+
+/-- A halted linked path starting in this component must reach its first
+ordinary accepting exit. The suffix has exactly the reset word and memory
+specified by the transfer and can include any number of later stages. -/
+theorem split_halted {fuel st m bs logs} (fit : d ≤ 2^w) {inv : Word w → Memory w → Prop}
+ (frame : TagFrame T pub addr s fuel inv) (hi : inv st m) (htag : m addr.val = tagWord w s)
+ (hr : runSegment (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length)
+ (some st) m bs = some logs) (halt : endState (some st) logs = none) :
+ ∃ first rest reps lastMem tailLogs,
+ bs = first ++ rest ∧ logs = reps.map (linkedReport next addr s) ++ tailLogs ∧
+ Completion T next pub addr s fuel st m first reps lastMem ∧
+ runSegment (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length)
+ (transferState next s) (transferMemory addr (next s) lastMem) rest = some tailLogs ∧
+ endState (transferState next s) tailLogs = none := by
+ induction bs generalizing st m logs with
+ | nil =>
+ simp only [runSegment, Option.some.injEq] at hr
+ subst logs
+ contradiction
+ | cons b bs ih =>
+ rw [runSegment] at hr
+ cases hx : execute (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length)
+ ((outerProgram T next pub addr).start st) m b with
+ | none => simp [hx] at hr
+ | some out =>
+ rw [hx, Option.map_eq_some_iff] at hr
+ obtain ⟨logs',hr,rfl⟩ := hr
+ obtain ⟨rep,hc,hf,rfl⟩ := linked_inv fit htag hx
+ change endState (linkedReport next addr s rep).result logs' = none at halt
+ cases he : rep.result with
+ | none =>
+ rw [linked_last he, memory_last he] at hr
+ rw [linked_last he] at halt
+ exact ⟨[b],bs,[rep],after m rep.events,logs',rfl,rfl,.last hc he hf,hr,halt⟩
+ | some st' =>
+ rw [linked_continue he, linkedReport_after] at hr
+ simp only [he] at hr
+ rw [linked_continue he] at halt
+ obtain ⟨hi',ht'⟩ := frame _ _ _ _ _ hi htag hc he
+ obtain ⟨first,rest,reps,lastMem,tailLogs,rfl,rfl,comp,runTail,stop⟩ := ih hi' ht' hr halt
+ exact ⟨b::first,rest,rep::reps,lastMem,tailLogs,rfl,rfl,.more hc he hf comp,runTail,stop⟩
+
+/-- Determinism of native execution fixes the first completed component
+inside a given complete sequence of choices. The source memory and reports
+are fixed along with the position of the split. -/
+theorem Completion.uniqueSplit {fuel st m first reps lastMem}
+ (one : Completion T next pub addr s fuel st m first reps lastMem)
+ {other reps' lastMem'} (two : Completion T next pub addr s fuel st m other reps' lastMem')
+ {rest rest' : List (List Bool)} (eq : first ++ rest = other ++ rest') :
+ first = other ∧ reps = reps' ∧ lastMem = lastMem' ∧ rest = rest' := by
+ induction one generalizing other reps' lastMem' with
+ | last hc he hf =>
+ cases two with
+ | last hc' he' hf' =>
+ obtain ⟨rfl,rfl⟩ := List.cons.inj eq
+ have hrep := Option.some.inj (hc.symm.trans hc')
+ subst_vars
+ exact ⟨rfl,rfl,rfl,rfl⟩
+ | more hc' he' hf' ht =>
+ obtain ⟨rfl,_⟩ := List.cons.inj eq
+ have hrep := Option.some.inj (hc.symm.trans hc')
+ rw [← hrep, he] at he'
+ contradiction
+ | more hc he hf _ ih =>
+ cases two with
+ | last hc' he' hf' =>
+ obtain ⟨rfl,_⟩ := List.cons.inj eq
+ have hrep := Option.some.inj (hc.symm.trans hc')
+ rw [← hrep, he] at he'
+ contradiction
+ | more hc' he' hf' ht =>
+ obtain ⟨rfl,htail⟩ := List.cons.inj eq
+ obtain rfl := Option.some.inj (hc.symm.trans hc')
+ obtain rfl := Option.some.inj (he.symm.trans he')
+ obtain ⟨rfl,rfl,rfl,rfl⟩ := ih ht htail
+ exact ⟨rfl,rfl,rfl,rfl⟩
+
+variable (T next pub addr s)
+
+/-- A full native branch of the component followed by a native branch of
+the linked remainder. The cap is imposed on the actual concatenated reports. -/
+@[ext] structure Parts (fuel : ℕ) (st : Word w) (m : Memory w) (cap : List (Report w) → Prop) where
+ /-- Per-call choice tapes used through the current source stage's first accepting exit,
+ including the tape for its final call. -/
+ first : List (List Bool)
+ /-- Choice tapes for the linked continuation starting with the state and memory produced by
+ transfer out of the completed stage. -/
+ rest : List (List Bool)
+ /-- Source reports produced by the calls in the first part, in execution order before the
+ linker's dispatcher and transfer events are added. -/
+ reports : List (Report w)
+ /-- Source-stage memory after the final call and before transfer to the successor stage. -/
+ lastMem : Memory w
+ /-- Linked reports produced by running the remaining tapes from the transferred state and
+ memory until the outer program halts. -/
+ tailReports : List (Report w)
+ completed : Completion T next pub addr s fuel st m first reports lastMem
+ tailRun : runSegment (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length)
+ (transferState next s) (transferMemory addr (next s) lastMem) rest = some tailReports
+ tailHalt : endState (transferState next s) tailReports = none
+ within : cap (reports.map (linkedReport next addr s) ++ tailReports)
+
+variable {T next pub addr s}
+
+private theorem Completion.linkedEnd {fuel st m first reps lastMem}
+ (one : Completion T next pub addr s fuel st m first reps lastMem) :
+ endState (some st) (reps.map (linkedReport next addr s)) = transferState next s := by
+ induction one with
+ | last _ he _ => exact linked_last he
+ | more _ he _ _ ih => simpa only [List.map_cons, endState, linked_continue he] using ih
+
+/-- Concatenate the two native choice streams. -/
+def Parts.join {fuel st m cap} (fit : d ≤ 2^w) {inv : Word w → Memory w → Prop}
+ (frame : TagFrame T pub addr s fuel inv) (hi : inv st m) (htag : m addr.val = tagWord w s)
+ (p : Parts T next pub addr s fuel st m cap) :
+ ActualPaths (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length) st m cap :=
+ ⟨p.first ++ p.rest, p.reports.map (linkedReport next addr s) ++ p.tailReports, by
+ rw [p.completed.splice fit frame hi htag p.rest, p.tailRun, Option.map_some],
+ by rw [endState_append, p.completed.linkedEnd, p.tailHalt], p.within⟩
+
+private theorem join_injective {fuel st m cap} (fit : d ≤ 2^w) {inv : Word w → Memory w → Prop}
+ (frame : TagFrame T pub addr s fuel inv) (hi : inv st m) (htag : m addr.val = tagWord w s) :
+ Function.Injective (Parts.join (next := next) (cap := cap) fit frame hi htag) := by
+ intro a b eq
+ obtain ⟨af,ar,ap,am,at',ac,arun,ah,aw⟩ := a
+ obtain ⟨bf,br,bp,bm,bt',bc,bt,bh,bw⟩ := b
+ obtain ⟨rfl,rfl,rfl,rfl⟩ := ac.uniqueSplit bc (congrArg Subtype.val eq)
+ obtain rfl := Option.some.inj (arun.symm.trans bt)
+ rfl
+
+/-- Native accepting paths at the selected tag are bijective to the ordered
+choice of the first completed component and the accepted continuation. The
+bijection remains valid for variable component lengths and resource caps
+depending on the entire joined report sequence. -/
+noncomputable def partsEquiv {fuel st m cap} (fit : d ≤ 2^w) {inv : Word w → Memory w → Prop}
+ (frame : TagFrame T pub addr s fuel inv) (hi : inv st m) (htag : m addr.val = tagWord w s) :
+ Parts T next pub addr s fuel st m cap ≃
+ ActualPaths (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length) st m cap :=
+ Equiv.ofBijective (Parts.join fit frame hi htag) ⟨join_injective fit frame hi htag, by
+ intro a
+ obtain ⟨bits,logs,hr,halt,hcap⟩ := a
+ obtain ⟨first,rest,reps,lastMem,tailLogs,rfl,rfl,comp,runTail,stop⟩ :=
+ split_halted fit frame hi htag hr halt
+ exact ⟨⟨first,rest,reps,lastMem,tailLogs,comp,runTail,stop,hcap⟩,rfl⟩⟩
+
+variable (T next pub addr s)
+
+/-- Ordinary complete paths satisfying the linked stage's per-call clock. -/
+abbrev Ordinary (fuel : ℕ) (st : Word w) (m : Memory w) :=
+ ActualPaths (sourceProgram T pub s) fuel st m (fun rs => ∀ rep ∈ rs, room next addr s fuel rep)
+
+variable {T next pub addr s}
+
+/-- The report list of a completed ordinary source path, recovered from its successful run on
+the path's own choice tapes. -/
+noncomputable def ordinaryReports {fuel st m} (p : Ordinary T next pub addr s fuel st m) : List (Report w) :=
+ p.property.choose
+
+theorem ordinaryRun {fuel st m} (p : Ordinary T next pub addr s fuel st m) :
+ runSegment (sourceProgram T pub s) fuel (some st) m p.val = some (ordinaryReports p) :=
+ p.property.choose_spec.1
+
+/-- Suffix choices carry the *joined* report cap. Their start memory is the
+actual memory after the selected ordinary path and its transfer. -/
+abbrev Remainder {fuel st m} (cap : List (Report w) → Prop) (p : Ordinary T next pub addr s fuel st m) :=
+ {bits : List (List Bool) // ∃ logs,
+ runSegment (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length) (transferState next s)
+ (transferMemory addr (next s) (after m (eventLog (ordinaryReports p)))) bits = some logs ∧
+ endState (transferState next s) logs = none ∧ cap ((ordinaryReports p).map (linkedReport next addr s) ++ logs)}
+
+private noncomputable def pack {fuel st m cap} (p : Ordinary T next pub addr s fuel st m)
+ (q : Remainder cap p) : Parts T next pub addr s fuel st m cap where
+ first := p.val
+ rest := q.val
+ reports := ordinaryReports p
+ lastMem := after m (eventLog (ordinaryReports p))
+ tailReports := q.property.choose
+ completed := completion_of_run (ordinaryRun p) p.property.choose_spec.2.1 p.property.choose_spec.2.2
+ tailRun := q.property.choose_spec.1
+ tailHalt := q.property.choose_spec.2.1
+ within := q.property.choose_spec.2.2
+
+/-- Factorization in ordinary stage-path types. Replaying the first path fixes
+its source reports, final memory, and every argument to the continuation. -/
+noncomputable def ordinaryEquiv {fuel st m cap} (fit : d ≤ 2^w) {inv : Word w → Memory w → Prop}
+ (frame : TagFrame T pub addr s fuel inv) (hi : inv st m) (htag : m addr.val = tagWord w s) :
+ (Σ p : Ordinary T next pub addr s fuel st m, Remainder cap p) ≃
+ ActualPaths (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length) st m cap :=
+ (Equiv.ofBijective (fun p : Σ a : Ordinary T next pub addr s fuel st m, Remainder cap a => pack p.1 p.2) ⟨by
+ rintro ⟨p,q⟩ ⟨p',q'⟩ eq
+ have hp : p = p' := Subtype.ext (congrArg Parts.first eq)
+ subst p'
+ exact congrArg (Sigma.mk p) (Subtype.ext (congrArg Parts.rest eq)), by
+ intro a
+ obtain ⟨first,rest,reps,lastMem,tailLogs,comp,runTail,stop,hcap⟩ := a
+ obtain ⟨run,halt,memEq,roomEq⟩ := comp.spec
+ let p : Ordinary T next pub addr s fuel st m := ⟨first,reps,run,halt,roomEq⟩
+ have er : ordinaryReports p = reps := Option.some.inj ((ordinaryRun p).symm.trans run)
+ let q : Remainder cap p := ⟨rest,tailLogs,by simpa only [er,memEq] using runTail,stop,
+ by simpa only [er] using hcap⟩
+ have et : q.property.choose = tailLogs := by
+ apply Option.some.inj (q.property.choose_spec.1.symm.trans _)
+ simpa only [er,memEq] using runTail
+ refine ⟨⟨p,q⟩,?_⟩
+ apply Parts.ext <;> first | rfl | exact er | exact et | exact (congrArg (fun rs => after m (eventLog rs)) er).trans memEq⟩).trans (partsEquiv fit frame hi htag)
+
+/-- The exact finite sum used when successive live phases are counted. -/
+theorem count_stage_remainders {fuel st m cap} (fit : d ≤ 2^w) {inv : Word w → Memory w → Prop}
+ (frame : TagFrame T pub addr s fuel inv) (hi : inv st m) (htag : m addr.val = tagWord w s)
+ [Fintype (Ordinary T next pub addr s fuel st m)]
+ [∀ p : Ordinary T next pub addr s fuel st m, Finite (Remainder cap p)] :
+ Nat.card (ActualPaths (outerProgram T next pub addr) (fuel+(dispatchEvents addr s).length) st m cap) =
+ ∑ p : Ordinary T next pub addr s fuel st m, Nat.card (Remainder cap p) := by
+ rw [Nat.card_congr (ordinaryEquiv fit frame hi htag).symm, Nat.card_sigma]
+
+end LiveStageLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveStageSegments.lean b/lean/OAI/Computability/VPVNP/LiveStageSegments.lean
new file mode 100644
index 0000000000..e0afbeff1d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveStageSegments.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.LiveStageLinkPaths
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+
+/-!
+# A complete accepting stage inside the native linker
+
+The segment before the accepting report keeps its stage tag and ordinary
+persistent state. The accepting report transfers control, preserving all
+source writes except for the linker's update to its own reserved word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveStageLink
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {d r k w : ℕ} {pcs : Fin d → ℕ}
+
+/-- Each source report preserves the linker's reserved tag address. -/
+def PreservesTag (addr : Word w) (rs : List (Report w)) : Prop :=
+ ∀ rep ∈ rs, ∀ mem, after mem rep.events addr.val = mem addr.val
+
+/-- At each continuing report, the next dispatch sees the same tag. The
+accepting report may write the tag because it immediately halts or transfers. -/
+def PreservesTagOnReturns (addr : Word w) : Memory w → List (Report w) → Prop
+ | _, [] => True
+ | m, rep :: rs =>
+ (rep.result.isSome → after m rep.events addr.val = m addr.val) ∧
+ PreservesTagOnReturns addr (after m rep.events) rs
+
+theorem PreservesTag.onReturns {addr : Word w} {rs : List (Report w)} (h : PreservesTag addr rs) (m : Memory w) :
+ PreservesTagOnReturns addr m rs := by
+ induction rs generalizing m with
+ | nil => trivial
+ | cons r rs ih =>
+ exact ⟨fun _ => h r (by simp) m, ih (fun y hy => h y (List.mem_cons_of_mem _ hy)) _⟩
+
+theorem PreservesTagOnReturns.singleton_accept (addr : Word w) (m : Memory w) (r : Report w)
+ (h : r.result = none) : PreservesTagOnReturns addr m [r] := by simp [PreservesTagOnReturns,h]
+
+theorem PreservesTagOnReturns.append {addr : Word w} {m : Memory w} {xs ys : List (Report w)}
+ (hx : PreservesTagOnReturns addr m xs) (hy : PreservesTagOnReturns addr (after m (eventLog xs)) ys) :
+ PreservesTagOnReturns addr m (xs ++ ys) := by
+ induction xs generalizing m with
+ | nil => exact hy
+ | cons x xs ih =>
+ have ht : after m (eventLog (x::xs)) = after (after m x.events) (eventLog xs) := by simp [after,eventLog,List.foldl_append]
+ rw [ht] at hy
+ exact ⟨hx.1, ih hx.2 hy⟩
+
+/-- Memory passed across an accepting boundary. -/
+def transferMemory (addr : Word w) (dest : Option (Fin d)) (m : Memory w) :=
+ match dest with
+ | some t => writeMemory m addr (tagWord w t)
+ | none => m
+
+theorem transferMemory_tag (addr : Word w) (s : Fin d) (m : Memory w) :
+ transferMemory addr (some s) m addr.val = tagWord w s := by simp [transferMemory, writeMemory]
+
+theorem linkedReport_result (next : Fin d → Option (Fin d)) (addr : Word w) (s : Fin d) (rep : Report w) :
+ (linkedReport next addr s rep).result = match rep.result with
+ | some v => some v | none => (next s).map (fun _ => 0) := by
+ cases rep with
+ | mk es out => cases out <;> cases hn : next s <;> simp [linkedReport, prependLog, exitReport, hn]
+
+private theorem after_eventLog_cons (m : Memory w) (r : Report w) (rs : List (Report w)) :
+ after m (eventLog (r :: rs)) = after (after m r.events) (eventLog rs) := by simp [eventLog,after,List.foldl_append]
+
+variable (T : (s : Fin d) → Template (pcs s) r k) (next : Fin d → Option (Fin d))
+variable (pub : Fin k → Word w) (addr : Word w)
+
+/-- Complete native simulation of one accepting component, including every
+returned cursor, external word effect and the precise cumulative probe cost. -/
+theorem runSegment_accepting {fuel cap : ℕ} (s : Fin d) (hfits : d ≤ 2^w) (hcap : fuel+2*d+5 ≤ cap)
+ (st : Word w) (m : Memory w) (bs : List (List Bool)) (rs : List (Report w))
+ (htag : m addr.val = tagWord w s) (hframe : PreservesTagOnReturns addr m rs)
+ (hsrc : runSegment ((T s).instantiate w pub).program fuel (some st) m bs = some rs)
+ (hend : endState (some st) rs = none) :
+ let outs := rs.map (linkedReport next addr s)
+ runSegment (machine T next pub addr).program cap (some st) m bs = some outs ∧
+ endState (some st) outs = (next s).map (fun _ => 0) ∧
+ after m (eventLog outs) = transferMemory addr (next s) (after m (eventLog rs)) ∧
+ RAMBuckets.cost Report.probes outs =
+ RAMBuckets.cost Report.probes rs + rs.length + (if (next s).isSome then 1 else 0) := by
+ induction bs generalizing st m rs with
+ | nil =>
+ simp only [runSegment, Option.some.injEq] at hsrc
+ subst rs
+ contradiction
+ | cons bits bs ih =>
+ dsimp only
+ simp only [runSegment] at hsrc
+ cases he : execute ((T s).instantiate w pub).program fuel (((T s).instantiate w pub).program.start st) m bits with
+ | none => simp [he] at hsrc
+ | some rep =>
+ simp only [he, Option.map_eq_some_iff] at hsrc
+ obtain ⟨rest, hr, rfl⟩ := hsrc
+ have hex := execute_linked_of_stage T next pub addr s hfits hcap st m htag bits rep he
+ have ho := linkedReport_after next addr s rep m
+ have hv := linkedReport_result next addr s rep
+ have hp := linkedReport_probes next addr s rep
+ cases hout : rep.result with
+ | none =>
+ rw [hout] at hr
+ cases bs with
+ | cons _ _ => simp [runSegment] at hr
+ | nil =>
+ simp [runSegment] at hr
+ subst rest
+ cases hn : next s <;>
+ simp_all [runSegment, List.map_cons, endState, eventLog, RAMBuckets.cost, transferMemory] <;> omega
+ | some st' =>
+ have htail := hframe.2
+ have ht : after m rep.events addr.val = tagWord w s := (hframe.1 (by simp [hout])).trans htag
+ rw [hout] at hr
+ change endState rep.result rest = none at hend
+ rw [hout] at hend
+ obtain ⟨hrun, hstate, hmem, hcost⟩ := ih st' (after m rep.events) rest ht htail hr hend
+ simp only [hout] at hv ho
+ simp [hout] at hp
+ simp only [List.map_cons, runSegment, hex, hv, ho, hrun, Option.map_some,
+ endState, hstate, after_eventLog_cons, hmem, RAMBuckets.cost, hp, List.length_cons, hcost, true_and]
+ omega
+
+end LiveStageLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveTailContinuation.lean b/lean/OAI/Computability/VPVNP/LiveTailContinuation.lean
new file mode 100644
index 0000000000..c2c97f48aa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveTailContinuation.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.LiveFirstTailPhysicalCount
+import OAI.Computability.VPVNP.LiveProgramAdviceCapacity
+
+/-!
+# Realizing the complete evaluator half of the live program
+
+The same fixed native table handles the first, interior and last evaluator
+groups. The distributed advice fixes the raw prefix and the permutation of the
+label coordinates. This yields the specified local path multiplicity on every
+physical cut assignment which passes its mode and padding checks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.EvaluatorRoutes
+
+open BurstRAM PairStages LiveEvaluatorEncoding LiveHeader LocalCount ChainAssignments
+open OutsideTailStages OutsideTailCount
+open scoped Fin.CommRing
+
+variable (G : Group)
+
+/-- Realization on the actual distributed advice and complete word-level
+evaluator program. The two budgets bound an ordinary and an initial group,
+respectively, and include all header, transfer and transition reports. -/
+theorem tailContinuation {S H : ℕ} (W : Conditions G S H)
+ (fits : limit G < 2^G.w) (fit : GeometryFit G (radius G))
+ (expFit : 1+FirstTailHeader.labelCount G*FirstTailHeader.exponentWidth G ≤ (sizes G).delta)
+ (layout : LiveEvaluatorTail.Layout G.evaluator.extra (radius G) G.w (sizes G).delta)
+ (raw : List Bool) (perm : Equiv.Perm (Fin (FirstTailHeader.labelCount G)))
+ (values : Fin (FirstTailHeader.labelCount G) → Word (Nat.clog 2 (FirstTailHeader.labelCount G)))
+ (ordinal : ∀ a, (values a).val = (perm a).val)
+ (capacity : G.w+G.constants.prefixCapacity.eval G.g +
+ FirstTailHeader.labelCount G*Nat.clog 2 (FirstTailHeader.labelCount G) ≤ (sizes G).advice)
+ (rawFits : raw.length ≤ G.constants.prefixCapacity.eval G.g)
+ (space : G.evaluator.extra ≠ 0 → raw.length + (2*(FirstTailHeader.labelCount G*FirstTailHeader.exponentWidth G)+
+ 6*FirstTailHeader.exponentWidth G+4) ≤ radius G+1)
+ (call : callBound G.w ≤ H)
+ (ordinaryBudget : LiveHeaderSchedule.costBound (sizes G)+4+2*routeCost G.w (radius G)+transitionCost (radius G) ≤ S*H)
+ (initialBudget : LiveHeaderSchedule.costBound (sizes G)+4+8+packWork (params G raw.length)+inputWork (params G raw.length)+
+ routeCost G.w (radius G)+transitionCost (radius G) ≤ S*H) :
+ TailContinuation W (Advice.adviceTape G.w (G.constants.prefixCapacity.eval G.g) (sizes G).advice raw values)
+ expFit layout (midpointInitial G raw perm) := by
+ let adv := Advice.adviceTape G.w (G.constants.prefixCapacity.eval G.g) (sizes G).advice raw values
+ intro cuts i
+ dsimp only
+ intro mode pads tr out
+ let middle := fun a => (FirstTailHeader.middleWords G cuts expFit a).val
+ let init := midpointInitial G raw perm middle
+ have hc : max 11 (G.w+4) ≤ H := by unfold callBound at call; omega
+ by_cases first : i.val = 0
+ · by_cases empty : G.evaluator.extra = 0
+ · exact emptyFirstPhysicalCount W adv fits fit layout init cuts i mode pads tr out hc ordinaryBudget first empty
+ (by simp [init, midpointInitial, LiveEvaluatorTail.initialCode, UniversalMachine.initial, empty])
+ · exact nonemptyFirstPhysicalCount G W adv fits fit expFit layout raw perm values ordinal capacity rawFits
+ (Advice.adviceTape_words _ _ _ _ _ rawFits capacity) (space empty) empty cuts i first mode (pads .right) tr out call initialBudget
+ · exact nonfirstPhysicalCount W adv fits fit layout init cuts i mode pads tr out hc ordinaryBudget (by omega)
+
+end LiveProgram.EvaluatorRoutes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveTerminalProtectedAddresses.lean b/lean/OAI/Computability/VPVNP/LiveTerminalProtectedAddresses.lean
new file mode 100644
index 0000000000..09f3a0f89f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveTerminalProtectedAddresses.lean
@@ -0,0 +1,47 @@
+import OAI.Computability.VPVNP.LiveCompressedPairStartupInputs
+import OAI.Computability.VPVNP.LiveProgramCompressedPairPaths
+
+/-!
+# The live addresses protected by the compressed pair terminal traversal
+
+The pair-level tag lies immediately after the dense counter array.
+Every header or input address below the descriptor table precedes the
+grammar counter array. Both ranges precede the final shared wire bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+open BurstRAM PairStages.Group PairStages.Group.CompressedPaths
+
+theorem terminal_protected_addresses (G : PairStages.Group) (lo : ℕ)
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w) (workspaceLow : ((publicWords G) 2).val ≤ lo) :
+ let tag := (PairTag.address (publicWords G)).val
+ (tag < lo ∧ Auxiliary.counterBase G+Auxiliary.histLength G+G.constants.motifLabels = tag) ∧
+ ∀ a < Auxiliary.tableBase G, a < lo ∧ a < Auxiliary.counterBase G + Auxiliary.histLength G := by
+ let c := G.constants
+ let g := G.g
+ let tag := (PairTag.address (publicWords G)).val
+ have ws : ((publicWords G) 2).val = (Layout.pairWorkspace c).eval g := Nat.mod_eq_of_lt fit
+ have ht := tag_before_workspace c g
+ have exactTag : tag = (Layout.oldState c).eval g := by
+ dsimp only [tag,publicWords]
+ rw [tag_address]
+ exact Nat.mod_eq_of_lt (ht.trans fit)
+ have grammar : Auxiliary.counterBase G + Auxiliary.histLength G + G.constants.motifLabels = tag := by
+ rw [exactTag]
+ change _ + _ + _ = (Layout.counter c).eval g + (c.grammarLabels.eval g + c.motifLabels)
+ exact Nat.add_assoc ..
+ have tagLow : tag < lo := by rw [ws] at workspaceLow; exact exactTag.symm ▸ ht.trans_le workspaceLow
+ have table := (Auxiliary.geometry_order G).2.2.1
+ refine ⟨⟨tagLow,grammar⟩,?_⟩
+ intro a ha
+ exact ⟨by omega,by omega⟩
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveTerminalReachableFrame.lean b/lean/OAI/Computability/VPVNP/LiveTerminalReachableFrame.lean
new file mode 100644
index 0000000000..c160c382b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveTerminalReachableFrame.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.LiveCompressedPairProtection
+
+/-! # All reachable terminal reports preserve a selected cell
+
+The forced empty-choice prefix uses its chronological input memories. The
+subsequent calls may halt or continue. Both outcomes preserve the word
+whenever their actual reachable source table preserves it.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- A frame for every successful call, including the final accepting call. -/
+def PreservesCell (P : Program w C) (fuel : ℕ) (st : Word w) (m : Memory w) (a : ℕ) : Prop :=
+ ∀ {cursor mem bits r}, Reached P fuel st m cursor mem →
+ execute P fuel (P.start cursor) mem bits = some r → after mem r.events a = mem a
+
+variable {P : Program w C} {fuel : ℕ} {st : Word w} {m : Memory w} {a : ℕ}
+
+/-- Each reachable boundary is either the starting one or a boundary in
+the suffix of the forced call. -/
+private theorem reached_after_empty_call {r : Report w} {next : Word w}
+ (run : execute P fuel (P.start st) m [] = some r) (result : r.result = some next)
+ {cursor mem} (reached : Reached P fuel st m cursor mem) :
+ (cursor = st ∧ mem = m) ∨ Reached P fuel next (after m r.events) cursor mem := by
+ induction reached with
+ | start => exact Or.inl ⟨rfl,rfl⟩
+ | @more cur now bits rep stop prior call cont ih =>
+ rcases ih with ⟨rfl,rfl⟩ | suffix
+ · obtain ⟨_,rfl⟩ := execute_empty_forces run call
+ have eqn : stop = next := Option.some.inj (cont.symm.trans result)
+ subst stop
+ exact Or.inr .start
+ · exact Or.inr (.more suffix call cont)
+
+private theorem preservesCell_after_empty_call {r : Report w} {next : Word w}
+ (run : execute P fuel (P.start st) m [] = some r) (result : r.result = some next)
+ (frame : after m r.events a = m a) (suffix : PreservesCell P fuel next (after m r.events) a) :
+ PreservesCell P fuel st m a := by
+ intro cursor mem bits q reached call
+ rcases reached_after_empty_call run result reached with ⟨rfl,rfl⟩ | past
+ · obtain ⟨_,rfl⟩ := execute_empty_forces run call
+ exact frame
+ · exact suffix past call
+
+/-- Replay the deterministic reports on their actual incoming memories, then
+apply the suffix's frame to every successful call, including a halting one. -/
+theorem preservesCell_after_replayed_prefix {n : ℕ} {logs : List (Report w)} {next : Word w}
+ (run : runSegment P fuel (some st) m (List.replicate n []) = some logs)
+ (finish : endState (some st) logs = some next)
+ (frame : ReplayFrame a m logs)
+ (suffix : PreservesCell P fuel next (after m (eventLog logs)) a) : PreservesCell P fuel st m a := by
+ induction n generalizing st m logs with
+ | zero =>
+ simp only [List.replicate_zero,runSegment,Option.some.injEq] at run
+ subst logs
+ change some st = some next at finish
+ exact Option.some.inj finish ▸ suffix
+ | succ n ih =>
+ rw [List.replicate_succ,runSegment] at run
+ cases call : execute P fuel (P.start st) m [] with
+ | none => simp [call] at run
+ | some r =>
+ simp only [call,Option.map_eq_some_iff] at run
+ obtain ⟨rest,run,rfl⟩ := run
+ change endState r.result rest = some next at finish
+ have tail : PreservesCell P fuel next (after (after m r.events) (eventLog rest)) a := by
+ rw [show after (after m r.events) (eventLog rest) = after m (eventLog (r::rest)) by
+ simp only [eventLog,List.flatMap_cons,after,List.foldl_append]]
+ exact @suffix
+ cases cont : r.result with
+ | none =>
+ rw [cont] at run finish
+ cases n with
+ | zero => simp [runSegment] at run; subst rest; contradiction
+ | succ n => simp [List.replicate_succ,runSegment] at run
+ | some cursor =>
+ rw [cont] at run finish
+ apply preservesCell_after_empty_call call cont frame.1
+ apply ih run finish frame.2
+ exact @tail
+
+end BurstRAM
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM CompressorRecords CompressorRecords.Schedule LiveStageLink
+variable {w d initial phases : ℕ} {C : Catalog d} {b : Bootstrap} {plan : Online.Config C initial phases}
+ {last : PairTable} {pub : Fin 11 → Word w} {clock : ℕ} {s : Stage} {m : Memory w}
+
+/-- A physically reachable pair source has the same continuing history
+in the ordinary burst RAM semantics. -/
+theorem SourceReachable.reached {st : Word w} {mem : Memory w}
+ (h : SourceReachable b plan last pub clock s m st mem) :
+ Reached (original b plan last pub s) (clockAt pub clock s) 0 m st mem := by
+ induction h with
+ | start => exact .start
+ | more _ call cont ih => exact .more ih call cont
+
+/-- Use a full reachable frame on the source's tag to establish the pair
+linker's invariant, even when a partial computation cannot be extended. -/
+def Protected.ofPreservesCell
+ (tag : PreservesCell (original b plan last pub s) (clockAt pub clock s) 0 m (PairTag.address pub).val) :
+ Protected b plan last pub clock s m :=
+ Protected.ofSource b plan last pub clock s m (fun reach _ call _ => tag reach.reached call)
+
+theorem Protected.ofPreservesCell_word
+ (tag : PreservesCell (original b plan last pub s) (clockAt pub clock s) 0 m (PairTag.address pub).val)
+ {a : ℕ} (cell : PreservesCell (original b plan last pub s) (clockAt pub clock s) 0 m a) :
+ (Protected.ofPreservesCell tag).word a :=
+ Protected.ofSource_word b plan last pub clock s m a
+ (fun reach _ call _ => tag reach.reached call) (fun reach _ call => cell reach.reached call)
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveTerminalWorkerTransport.lean b/lean/OAI/Computability/VPVNP/LiveTerminalWorkerTransport.lean
new file mode 100644
index 0000000000..2f51e16694
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveTerminalWorkerTransport.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.LiveCompressedPairBranchCharge
+import OAI.Computability.VPVNP.PairTerminalQuietHandoff
+
+/-! # The same terminal branch on equal fixed instruction banks
+
+The compressed pair's packed directory is sized at runtime. Reindexing
+a chosen branch along the equality of its five worker tables retains the
+raw vertex memory and all physical report lists used for accounting.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair.TerminalBranchData
+
+open BurstRAM PairSimulation LocalHistory NetworkKernel TerminalLink
+
+variable {w clk : ℕ} {N : Network} {A : Type*} [CommRing A] {L : Type} [Fintype L]
+ {κ : L → A} {arc : ScanPhase N} {sites : SiteParsers κ N} {pub : Fin 11 → Word w} {m : Memory w}
+ {old current : TerminalLink.Stage → PairTable}
+ (branch : TerminalBranchData old pub clk m arc sites) (same : old = current)
+
+/-- Interpret a chosen physical terminal branch on the equal runtime instruction bank. -/
+def reindexWorkers : TerminalBranchData current pub clk m arc sites := same ▸ branch
+
+theorem reindex_bitMemory (x : arc.Path) :
+ ((branch.reindexWorkers same).bitPaths x).val.memory = (branch.bitPaths x).val.memory := by
+ cases same
+ rfl
+
+theorem reindex_vertexMemory (x : TerminalData arc sites) :
+ ((branch.reindexWorkers same).vertexPaths x.arcs x.choices).val.memory =
+ (branch.vertexPaths x.arcs x.choices).val.memory := by
+ cases same
+ rfl
+
+theorem reindex_sharedReports (x : TerminalData arc sites) :
+ ((branch.reindexWorkers same).chosenTrace x).sharedBits.logs =
+ (branch.chosenTrace x).sharedBits.logs := by
+ cases same
+ rfl
+
+theorem reindex_vertexReports (x : TerminalData arc sites) :
+ ((branch.reindexWorkers same).chosenTrace x).vertices.logs =
+ (branch.chosenTrace x).vertices.logs := by
+ cases same
+ rfl
+
+end LiveProgram.CompressedPair.TerminalBranchData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveTranscriptCoefficients.lean b/lean/OAI/Computability/VPVNP/LiveTranscriptCoefficients.lean
new file mode 100644
index 0000000000..a99f7d3830
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveTranscriptCoefficients.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.RAMTapeLiveProcessor
+import OAI.Computability.VPVNP.CursorCoefficientContraction
+import OAI.Computability.VPVNP.GroupIncidentContraction
+
+/-!
+# Contractions of the actual compiled universal coefficients
+
+The processor has one fixed literal program. Its public operand bank is
+computed from the length geometry and that program's own prefix. At all
+sufficiently large lengths its coefficients replace the live sites in the
+original paired contraction, with a single common input fit and word bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveTranscript
+
+open BurstRAM PrivateRAM RAMLayout ProcessorInput RAMTape LiveProgram Filter
+
+variable {p r k n d e w : ℕ}
+
+/-- Exact universal-machine coefficients for every live site's header and incident sends. -/
+structure Coefficients (D : UniversalMachine.Program) (M : Machine w p r k)
+ (n d e fuel : ℕ) (initial : Word w) : Prop where
+ width : 4 ≤ w
+ cap : 2^d*2^e < 2^w
+ fits : Fits D n d (2^e) w
+ count : ∀ (v : Word d) (hdr : Header) (sends : SendArrays d (2^e) w),
+ acceptingCount (encode D n v hdr (RAMLayout.incidentBits sends v) fits) =
+ Nat.card (M.IncidentPaths fuel initial (headerWord width hdr) (by omega) cap v
+ (RAMLayout.incidentBits sends v))
+
+/-- Coefficient identities obtained when the public operand vector fits the current word. -/
+def AtGeometry (T : Template p r k) (args : Fin k → InputOperand) (D : UniversalMachine.Program)
+ (n d e w lit : ℕ) : Prop :=
+ let g : Geometry := ⟨n,d,2^e,w⟩
+ (∀ i, (InputOperandStartup.Expr args i).Fits g (2^w)) →
+ Coefficients D (T.instantiate w (fun i => Pieces.word g (CounterPublic.actualPrefix D) (args i)))
+ n d e (n^10000) (Fin.ofNat (2^w) lit)
+
+theorem eventually_coefficients (T : Template p r k) (args : Fin k → InputOperand)
+ (B a b lit : ℕ) (hB : 1 ≤ B) (hb : 0 < b) (hab : a < b) :
+ ∀ᶠ n : ℕ in atTop, AtGeometry T args (SiteProcessorPorts.machine T args B a b 10000 lit hb) n
+ (addressWidth B n) (roundedUp a b n) (CursorBounds.wordBits B n) lit := by
+ filter_upwards [SiteProcessorPorts.eventually_machine_count T args B a b lit hB hb hab] with n h
+ intro hg
+ obtain ⟨fit, site⟩ := h
+ obtain ⟨hc,_⟩ := site hg 0 (fun _ => false) (fun _ _ => false, fun _ _ _ => false)
+ exact ⟨ProcessorPublic.recordWidth_ge_four _, hc, fit, fun v hdr sends => (site hg v hdr sends).choose_spec⟩
+
+variable {D : UniversalMachine.Program} {M : Machine w p r k} {fuel : ℕ} {initial : Word w}
+ (c : Coefficients D M n d e fuel initial)
+
+theorem Coefficients.groups {a h Δ : ℕ} (advice : CutSchedule.Bits a) :
+ PairedChain.original (h := h) (Δ := Δ) D c.fits advice =
+ ∑ cuts : ChainAssignments.AllCuts h Δ, ∏ j : Fin (2^(h+1)), Nat.card
+ (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2^d)
+ (ChainAssignments.liveHeader (d := d) c.width advice cuts j)) (withinCaps (2^d) (2^e))) :=
+ ChainAssignments.original_eq_incident_counts D c.fits advice M fuel initial c.width c.cap c.count
+
+open CursorNetwork CursorRouting NetworkKernel in
+theorem Coefficients.localPolynomial (hdr : Site d → Header) (v : Site d) (out inc : RAMPayload d (2^e) w) :
+ (P n).coeff (pairedExponent (cursorInput D c.fits hdr v out inc)) =
+ (Nat.card (validatorPaths M fuel initial (headerAt hdr c.width) (by have := c.width; omega)
+ c.cap v out inc) : ℤ) :=
+ cursorInput_coeff D c.fits M fuel initial hdr c.width c.cap (fun v => c.count v (hdr v)) v out inc
+
+open CursorNetwork CursorRouting NetworkKernel in
+open scoped Classical in
+theorem Coefficients.routed [NeZero d] (hdr : Site d → Header) :
+ contract (validatorNetwork d e w) (factors systemMask (fun v out inc => if ActiveSends v out then
+ acceptingCount (cursorInput D c.fits hdr v out inc) else 0)) =
+ Nat.card (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2^d) (headerAt hdr c.width))
+ (withinCaps (2^d) (2^e))) :=
+ cursorInput_contract D c.fits M fuel initial hdr c.width c.cap (fun v => c.count v (hdr v))
+
+end LiveTranscript
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVertexJobDeposits.lean b/lean/OAI/Computability/VPVNP/LiveVertexJobDeposits.lean
new file mode 100644
index 0000000000..4acf89c2b4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVertexJobDeposits.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.PairVertexAscendingPaths
+import OAI.Computability.VPVNP.PairSimulationTraceJobs
+import OAI.Computability.VPVNP.LiveVirtualPairJobCounters
+
+/-!
+# Equality of native vertex deposits and local job increments
+
+The final counter memory of the physical site traversal is a fold over its
+site ordinals. The jobs of each selected local parser have the same exponent
+vector. This includes the grammar prefix, which every site visit preserves.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.Counters
+
+open BurstRAM
+
+theorem visit_congr_at {w g : ℕ} {X : Type*} (base grammar : ℕ) (h : X → Fin g → ℕ) (vs : List X)
+ {m₁ m₂ : Memory w} (a : ℕ) (same : m₁ a=m₂ a) : visit base grammar h vs m₁ a = visit base grammar h vs m₂ a := by
+ by_cases inside : base+grammar ≤ a ∧ a < base+grammar+g
+ · let j : Fin g := ⟨a-(base+grammar),by omega⟩
+ have eq : a = base+grammar+j.val := by dsimp [j]; omega
+ rw [eq,visit_at,visit_at]
+ exact congrArg (· + _) (eq ▸ same)
+ · have outside : a < base+grammar ∨ base+grammar+g ≤ a := by omega
+ rw [visit_outside _ _ _ _ _ _ outside,visit_outside _ _ _ _ _ _ outside]
+ exact same
+
+end PairSimulation.Counters
+
+namespace PairSimulation.LocalHistory
+
+open BurstRAM NetworkKernel CompressorRecords VertexImage
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {N : Network}
+ {scan : ScanPhase N} {P : SiteParsers κ N} (x : TerminalData scan P)
+ {n g w : ℕ} (order : Fin n ≃ N.Site) (labels : Fin g ≃ L)
+ (trees : N.Site → DFS.VertexTree) (jobs : JobsFor P) (valid : JobsSpec P trees jobs)
+
+local notation "incident" => WireTensor.edgeAssignment N.src N.dst (scan.payload x.arcs)
+
+include valid in
+/-- Read any physical address after all selected vertices. Equality of the
+incoming words at that single address suffices, even when the other source
+memory cells differ from those of the actual prepared pair. -/
+theorem TerminalData.deposits (base grammar : ℕ) (source input : Memory w) (a : ℕ) (before : source a=input a) :
+ (siteOrdinals P order labels incident).finalMemory base grammar source (fun i => x.choices (order i)) a =
+ Counters.visit base grammar (fun v l => ((x.jobs jobs v).map (fun j => j.increment (labels l))).sum)
+ (List.ofFn order) input a := by
+ let F := fun (v : N.Site) (l : Fin g) => ((x.jobs jobs v).map (fun j => j.increment (labels l))).sum
+ have stored : (siteOrdinals P order labels incident).finalMemory base grammar source (fun i => x.choices (order i)) =
+ Counters.visit base grammar F (List.ofFn order) source := by
+ unfold IndexedSites.finalMemory
+ apply Counters.visit_eq_of_sums
+ intro l
+ rw [List.map_ofFn,List.map_ofFn,List.sum_ofFn,List.sum_ofFn]
+ apply Finset.sum_congr rfl
+ intro i _
+ exact (valid.increments (order i) (incident (order i)) (x.choices (order i)) (labels l)).symm
+ rw [stored]
+ exact Counters.visit_congr_at base grammar F (List.ofFn order) a before
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualCompressedBudget.lean b/lean/OAI/Computability/VPVNP/LiveVirtualCompressedBudget.lean
new file mode 100644
index 0000000000..4117e02e0c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualCompressedBudget.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.LiveProgramCompressedPair
+import OAI.Computability.VPVNP.LiveNativePairContinuation
+
+/-!
+# Accounting for all linked calls of the compressed pair
+
+The online dispatcher reads six workspace words in addition to its own
+probes. The compressed-pair linker and the surrounding live-group linker
+each read one tag and may write one transfer. The same source report
+sequences determine the two margins in the native single-pair specification.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM CompressorRecords PairStages
+
+variable {w : ℕ} (pub : Fin 11 → Word w) (E : UniversalMachine.Program) (tag : Word w)
+
+/-- Both tags are charged on every call, including the final call of a stage. -/
+def linkedRow (i : Stage) (r : Report w) :=
+ LiveStageLink.linkedReport (LiveProgram.next E) tag LiveProgram.Stage.pair (report pub i r)
+
+theorem linkedRow_bounds (i : Stage) (r : Report w) :
+ (linkedRow pub E tag i r).probes ≤ r.probes+4 ∧
+ (linkedRow pub E tag i r).events.length ≤ r.events.length+77 := by
+ have hi := report_effect pub i r (fun _ => 0)
+ have ho := LiveStageLink.linkedReport_probes (LiveProgram.next E) tag LiveProgram.Stage.pair (report pub i r)
+ have ht := LiveStageLink.linkedReport_length_le (LiveProgram.next E) tag LiveProgram.Stage.pair (report pub i r)
+ change (linkedRow pub E tag i r).events.length ≤ (report pub i r).events.length + 2*21+5 at ht
+ change (linkedRow pub E tag i r).probes = (report pub i r).probes+1+_ at ho
+ obtain ⟨_,hp,ht',_⟩ := hi
+ constructor
+ · split at hp <;> split at ho <;> omega
+ · omega
+
+/-- Online reports after the workspace reads and the two enclosing dispatches. -/
+def onlineLogs (base : Word w) (m : Memory w) (rs : List (Report w)) :=
+ (OnlineWorkspace.framed base m rs).map (linkedRow pub E tag .online)
+
+/-- Terminal reports as executed by the enclosing live pair stage. -/
+def terminalLogs (rs : List (Report w)) := rs.map (linkedRow pub E tag .terminal)
+
+/-- The startup reports, each charged for its own stage transition. -/
+def wrappedStartup (src : List (Stage × Report w)) := src.map (fun p => linkedRow pub E tag p.1 p.2)
+
+/-- The startup, online and terminal reports in their execution order. -/
+def logs (base : Word w) (m : Memory w) (startup : List (Stage × Report w)) (online terminal : List (Report w)) :=
+ wrappedStartup pub E tag startup ++ onlineLogs pub E tag base m online ++ terminalLogs pub E tag terminal
+
+theorem onlineCost (base : Word w) (m : Memory w) (rs : List (Report w)) :
+ RAMBuckets.cost Report.probes (onlineLogs pub E tag base m rs) ≤ 11*RAMBuckets.cost Report.probes rs := by
+ induction rs generalizing m with
+ | nil => simp [onlineLogs,OnlineWorkspace.framed,RAMBuckets.cost]
+ | cons a rs ih =>
+ have frame := (Workspace.report_effect base m a).2.1
+ have link := (linkedRow_bounds pub E tag .online (Workspace.report base m a)).1
+ have tail := ih (after m a.events)
+ change 1+(linkedRow pub E tag .online (Workspace.report base m a)).probes +
+ RAMBuckets.cost Report.probes (onlineLogs pub E tag base (after m a.events) rs) ≤
+ 11*((1+a.probes)+RAMBuckets.cost Report.probes rs)
+ omega
+
+theorem terminalCost (rs : List (Report w)) :
+ RAMBuckets.cost Report.probes (terminalLogs pub E tag rs) ≤ 5*RAMBuckets.cost Report.probes rs := by
+ induction rs with
+ | nil => rfl
+ | cons a rs ih =>
+ have h := (linkedRow_bounds pub E tag .terminal a).1
+ change 1+(linkedRow pub E tag .terminal a).probes+RAMBuckets.cost Report.probes (terminalLogs pub E tag rs) ≤
+ 5*((1+a.probes)+RAMBuckets.cost Report.probes rs)
+ omega
+
+theorem startupCost (src : List (Stage × Report w)) (H : ℕ) (h : ∀ p ∈ src, p.2.probes+5 ≤ H) :
+ RAMBuckets.cost Report.probes (wrappedStartup pub E tag src) ≤ src.length*H := by
+ induction src with
+ | nil => simp [wrappedStartup,RAMBuckets.cost]
+ | cons p xs ih =>
+ have first := (linkedRow_bounds pub E tag p.1 p.2).1
+ have bound := h p (by simp)
+ have tail := ih (fun j hj => h j (List.mem_cons_of_mem _ hj))
+ change 1+(linkedRow pub E tag p.1 p.2).probes+RAMBuckets.cost Report.probes (wrappedStartup pub E tag xs) ≤ _
+ rw [List.length_cons,Nat.succ_mul]
+ omega
+
+theorem onlineRow (base : Word w) (m : Memory w) (rs : List (Report w)) {a : Report w}
+ (h : a ∈ onlineLogs pub E tag base m rs) :
+ ∃ b ∈ rs, a.probes ≤ b.probes+10 ∧ a.events.length ≤ b.events.length+101 := by
+ induction rs generalizing m with
+ | nil => contradiction
+ | cons b rs ih =>
+ change a ∈ linkedRow pub E tag .online (Workspace.report base m b) ::
+ onlineLogs pub E tag base (after m b.events) rs at h
+ rcases List.mem_cons.mp h with rfl | h
+ · have ⟨_,hp,hl,_,_⟩ := Workspace.report_effect base m b
+ have ⟨kp,kl⟩ := linkedRow_bounds pub E tag .online (Workspace.report base m b)
+ exact ⟨b,by simp,by omega,by omega⟩
+ · obtain ⟨a,ha,h₁,h₂⟩ := ih (after m b.events) h
+ exact ⟨a,List.mem_cons_of_mem _ ha,h₁,h₂⟩
+
+/-- The eventual per-branch estimates may be invoked with any fixed
+constant. A sixty-fourth share for each of the two variable traversals
+suffices after both tag protocols and the online pointer reads. -/
+theorem linked_caps (base : Word w) (m : Memory w) (startup : List (Stage × Report w))
+ (online terminal : List (Report w)) (S H cap : ℕ) (hS : 32 ≤ S) (hH : 2 ≤ H)
+ (hstart : startup.length ≤ 8)
+ (hs : ∀ p ∈ startup, p.2.probes+5 ≤ H ∧ p.2.events.length+77 ≤ cap)
+ (ho : ∀ b ∈ online, b.probes+11 ≤ H ∧ b.events.length+101 ≤ cap)
+ (ht : ∀ b ∈ terminal, b.probes+5 ≤ H ∧ b.events.length+77 ≤ cap)
+ (oc : 64*RAMBuckets.cost Report.probes online ≤ S*H)
+ (tc : 64*RAMBuckets.cost Report.probes terminal ≤ S*H) :
+ let rs := logs pub E tag base m startup online terminal
+ RAMBuckets.cost Report.probes rs ≤ S*(H-1) ∧
+ ∀ a ∈ rs, 1+a.probes ≤ H ∧ a.events.length ≤ cap := by
+ intro rs
+ constructor
+ · have c₁ := (startupCost pub E tag startup H (fun p hp => (hs p hp).1)).trans (Nat.mul_le_mul_right H hstart)
+ have c₂ := onlineCost pub E tag base m online
+ have c₃ := terminalCost pub E tag terminal
+ have size := Nat.mul_le_mul_right H hS
+ have gap := Nat.mul_le_mul_left S (show H ≤ 2*(H-1) by omega)
+ rw [show S*(2*(H-1))=2*(S*(H-1)) by ring] at gap
+ simp only [rs,logs,RAMBuckets.cost_append]
+ omega
+ · intro a ha
+ simp only [rs,logs,List.mem_append] at ha
+ rcases ha with (ha|ha)|ha
+ · obtain ⟨p,hp,rfl⟩ := List.mem_map.mp ha
+ have ⟨hp',hl⟩ := hs p hp
+ have ⟨kp,kl⟩ := linkedRow_bounds pub E tag p.1 p.2
+ exact ⟨by omega,by omega⟩
+ · obtain ⟨b,hb,kp,kl⟩ := onlineRow pub E tag base m online ha
+ obtain ⟨hp,hl⟩ := ho b hb
+ exact ⟨by omega,by omega⟩
+ · obtain ⟨b,hb,rfl⟩ := List.mem_map.mp ha
+ obtain ⟨hp,hl⟩ := ht b hb
+ have ⟨kp,kl⟩ := linkedRow_bounds pub E tag .terminal b
+ exact ⟨by omega,by omega⟩
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairBranchCharge.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairBranchCharge.lean
new file mode 100644
index 0000000000..aaba7f6cd6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairBranchCharge.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.LiveVirtualPairBranchClocks
+import OAI.Computability.VPVNP.LiveVirtualPairPaperDescriptor
+import OAI.Computability.VPVNP.LiveVirtualPairSourceAssembly
+import OAI.Computability.VPVNP.LiveCompressedPairBranchCharge
+
+/-! # The physical budget on a selected finite-model pair -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM LiveProgram CompressedPair
+open PairStages.Group.CompressedPaths NetworkKernel PairSimulation LocalHistory CompressorRecords ScheduledTrace
+open scoped Fin.CommRing
+set_option quotPrecheck false
+set_option maxHeartbeats 1200000
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {u : PairExponents B.growthConstant}
+ {D : FixedProgramDiagonal.Program} {C n : ℕ} {hn : 2 ≤ n} (V : D.VirtualPairs B u hn C)
+ {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ {c : Constants} {labels : c.motifLabels = Fintype.card B.Entry} {raw site q link base : ℕ}
+
+local notation "grp" => D.executionGroup n ht hf
+local notation "ports" => publicWords (grp)
+local notation "clk" => fuel (grp)
+local notation "boot" => paperBootstrap B u
+local notation "A" => BlockProgram.script B
+local notation "w" => wordBits D.addressFactor n
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "P" => initialPositions D.addressFactor n
+local notation "L" => BlockProgram.layout B base P T
+local notation "rate" => nativePassRate (A) raw * P
+local notation "bound" => TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit + 1
+local notation "κ" => B.compressorValues hn M
+local notation "ok" => B.compressorValues_solution hn M
+local notation "sel" => V.selection (M := M)
+local notation "lastStage" => terminalBody (L).shape B.recordLimit (paperSegments B u c labels)
+
+attribute [local irreducible] BlockProgram.script BlockProgram.layout CompressedPair.stages CompressedPair.regs
+ CompressedPair.components TerminalProgram.workers CursorNetwork.cursorState
+
+variable {m : Memory (wordBits D.addressFactor n)}
+ (descriptor : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M) c labels base
+ (fuel (D.executionGroup n ht hf)) (nativePassRate (BlockProgram.script B) raw * initialPositions D.addressFactor n)
+ (publicWords (D.executionGroup n ht hf)) m)
+ {arc : (z : (V.selection (M := M)).Choices) → ScanPhase ((V.selection (M := M)).finalState z).network}
+ {sites : (z : (V.selection (M := M)).Choices) → SiteParsers (B.compressorValues hn M) ((V.selection (M := M)).finalState z).network}
+ (branches : ∀ z : (V.selection (M := M)).Choices, TerminalBranch (b := paperBootstrap B u) (plan := (BlockProgram.script B).plan)
+ (shape := (BlockProgram.layout B base (initialPositions D.addressFactor n) (blockCount (u.θ : ℝ) n)).shape)
+ (limit := B.recordLimit) (segments := paperSegments B u c labels) (G := D.executionGroup n ht hf)
+ (B := D.addressFactor) (n := n) (base := base) (m := m) descriptor.paths (arc z) (sites z) z)
+
+set_option maxHeartbeats 800000 in
+/-- The linked online path and terminal phases on the same selected finite-model
+assignment give the full resource field of the native group certificate. -/
+theorem VirtualPairs.PaperDescriptor.branchCharge
+ (h : BranchClocks.{0} B u D.addressFactor boot (A).initial.length (A).block.length raw site q link n)
+ (num : D.numerator = (liveRatio u).num) (den : D.denominator = (liveRatio u).den)
+ (z : (sel).Choices) (x : TerminalData (arc z) (sites z))
+ (hq : 1 ≤ q)
+ (prefixRun : Nonempty (PreludeCosts V.scanState ((sel).finalState z) ports ((branches z).chosenTrace x)
+ S.steps B.recordLimit T bound))
+ (suffixRun : ∃ (bitMemory last : Memory (grp).w) (bits : Fin ((sel).finalState z).totalWidth → Bool)
+ (vertex : ((sel).finalState z).network.Site → Report (grp).w),
+ ((branches z).chosenTrace x).sharedBits.logs.map Prod.snd = FinalBits.Worker.reports ports 0 bitMemory bits ∧
+ ((branches z).chosenTrace x).vertices.logs.map Prod.snd = (List.ofFn fun i => vertex ((siteOrder ((sel).finalState z)).entries i)) ++
+ [VertexImage.closingReport ports last] ∧
+ ∀ v, 1+(vertex v).probes ≤ siteAccesses ((sel).finalState z) (selectedChain (V := V) (M := M) z) site q n v ∧
+ (vertex v).events.length+107 ≤ n^45) :
+ let rs := branchReports descriptor.paths branches z x
+ (∀ r ∈ rs, r.events.length+4 ≤ clk) ∧ 4*RAMBuckets.cost Report.probes rs ≤ 2^(D.geometry n).d*(D.geometry n).H ∧
+ ∀ r ∈ rs, 3+r.probes ≤ (D.geometry n).H := by
+ intro rs
+ obtain ⟨prelude⟩ := prefixRun
+ obtain ⟨bitMemory,last,bits,vertex,bitRows,vertexRows,checked⟩ := suffixRun
+ have hsizes : 2^(D.geometry n).d = processorCount D.addressFactor n ∧ (D.geometry n).H = liveCapacity u n := by
+ rw [paperGeometry_eq D B u num den n]
+ exact ⟨rfl,rfl⟩
+ obtain ⟨_,clock,active,startup,bootCap,arenaCap⟩ := h.groupCaps (grp) rfl
+ have term := V.terminalClock (M := M) h num den z
+ have online := V.onlineClock (M := M) h num den descriptor.cursor.interval descriptor.cursorCost descriptor.result (grp) rfl z
+ let core := descriptor.cursor.interval.combinedCore descriptor.result.trace descriptor.result.source z
+ have framed := (DescriptorPaths.paths_reports descriptor.cursor.interval descriptor.result boot lastStage clk
+ descriptor.clock descriptor.slack z).trans core.frame
+ apply branchReports_caps descriptor.paths branches z x V.scanState ((sel).finalState z) (selectedChain (V := V) (M := M) z)
+ (2^(D.geometry n).d) (D.geometry n).H S.steps T site q bound (hsizes.1.symm ▸ h.processors)
+ (hsizes.2.symm ▸ h.capacity) clock descriptor.init (hsizes.2.symm ▸ h.startBurst) startup
+ core.logs framed online.2 online.1 prelude (hsizes.2.symm ▸ bootCap) (hsizes.2.symm ▸ arenaCap) bitMemory last bits
+ bitRows vertex vertexRows hq h.blocks (fun v => ⟨(checked v).1,(checked v).2.trans active⟩) term.2 term.1
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairBranchClocks.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairBranchClocks.lean
new file mode 100644
index 0000000000..98ca3753a0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairBranchClocks.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.LiveCompressedPairClockBundle
+import OAI.Computability.VPVNP.LiveVirtualPairCursorBoundary
+import OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+import OAI.Computability.VPVNP.FixedProgramOperandFits
+
+/-! # Actual group and finite-model clocks for a selected virtual pair -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds CompressorRecords ScheduledTrace LiveProgram CompressedPair
+open LabelEvaluator BurstRAM PairSimulation LocalHistory
+
+universe v
+variable {K : Type v} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+variable {D : FixedProgramDiagonal.Program} {u : PairExponents B.growthConstant}
+variable {n C : ℕ} {hn : 2 ≤ n} (V : D.VirtualPairs B u hn C)
+variable {p : Nat.Primes} {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+variable {bs : Bootstrap} {initial phases raw site q link : ℕ}
+variable (h : BranchClocks.{0} B u D.addressFactor bs initial phases raw site q link n)
+variable (numerator : D.numerator = (liveRatio u).num) (denominator : D.denominator = (liveRatio u).den)
+local notation "κ" => B.compressorValues hn M
+local notation "ok" => B.compressorValues_solution hn M
+local notation "sel" => V.selection (M := M)
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "P" => initialPositions D.addressFactor n
+local notation "w" => wordBits D.addressFactor n
+local notation "scr" => BlockProgram.script B
+local notation "small" => BlockClock.small B D.addressFactor n
+local notation "bootBound" => TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit + 1
+local notation "coefficient" => terminalCoefficient S.baseDegree S.steps B.recordLimit (bootBound) 1 site
+
+include numerator denominator in
+private theorem group_sizes :
+ 2^(D.geometry n).d = processorCount D.addressFactor n ∧ (D.geometry n).H = liveCapacity u n := by
+ rw [paperGeometry_eq D B u numerator denominator n]
+ exact ⟨rfl,rfl⟩
+
+include h numerator denominator
+
+/-- All final site and total traversal bounds use the finite-model
+coefficient chain actually selected by the virtual pair. -/
+theorem VirtualPairs.terminalClock :
+ ∀ z : (sel).Choices, let chain := selectedChain (V := V) (M := M) z
+ let Y := (sel).finalState z
+ 320*branchAccesses V.scanState Y chain coefficient q n ≤ 2^(D.geometry n).d*(D.geometry n).H ∧
+ ∀ v, siteAccesses Y chain site q n v+9 ≤ (D.geometry n).H := by
+ obtain ⟨processors,capacity⟩ := group_sizes (n := n) numerator denominator
+ rw [processors,capacity]
+ change ∀ z : (B.execute κ ok T le_rfl V.scanState).Choices, let E := B.execute κ ok T le_rfl V.scanState
+ let chain := E.termChain (B.records κ ok T le_rfl V.scanState) z
+ 320*branchAccesses V.scanState (E.finalState z) chain coefficient q n ≤
+ processorCount D.addressFactor n*liveCapacity u n ∧
+ ∀ v, siteAccesses (E.finalState z) chain site q n v+9 ≤ liveCapacity u n
+ rw [V.scanState_pairInput]
+ exact h.terminal (laneLabels _ _ V.lanes) V.dimension le_rfl M.algebra κ ok
+
+/-- The live program's actual initial and recursive descriptor reports
+receive the group and per-burst bounds in the geometry used by the compiler. -/
+theorem VirtualPairs.onlineClock
+ {resident : Resident B κ ok w} {past : List (SelectedLevel B κ ok)}
+ {pub : Fin 11 → Word w} {pitch : Word w} {m : Memory w} {cap total : ℕ}
+ {origin : PassOrigins B κ ok (sel)} {W : (sel).MapWitnesses κ} {readers : ExecutionReaders (sel) W}
+ (start : QuietInterval scr pub cap small (some 0) m)
+ (first : RAMBuckets.cost Report.probes start.source.logs ≤ initialRate B*(P+1))
+ (result : Result resident pub pitch total cap small (T*(S.steps+1)*(nativePassRate scr raw*P)+4)
+ (sel) origin W readers past start.segment.state start.segment.memory)
+ (G : PairStages.Group) (clock : G.clock = n^10000) (z : (sel).Choices) :
+ let core := start.combinedCore result.trace result.source z
+ 64*RAMBuckets.cost Report.probes core.logs ≤ 2^(D.geometry n).d*(D.geometry n).H ∧
+ ∀ r ∈ core.logs, r.probes+11 ≤ (D.geometry n).H ∧ r.events.length+101 ≤ G.clockAt LiveProgram.Stage.pair := by
+ obtain ⟨processors,capacity⟩ := group_sizes (n := n) numerator denominator
+ rw [processors,capacity]
+ exact h.selectedOnline (laneLabels _ _ V.lanes) V.dimension start first result G clock z
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairCanonicalScan.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairCanonicalScan.lean
new file mode 100644
index 0000000000..73bb42a539
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairCanonicalScan.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.LiveVirtualPairOrdinalData
+import OAI.Computability.VPVNP.LiveVirtualPairJobCounters
+
+/-!
+# Payload coordinates and vertex counters of a virtual pair
+
+Index the semantic shared-bit choices by a zero-based scan. Its payload
+equivalence can be composed with the physical shared-bit worker at the
+address computed for a selected descriptor branch. The native readback uses
+the actual address. The ordinal emission and each vertex's increments use
+the same payload and site witnesses through this reindexing.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM BurstRAM.PrivateRAM
+open PairSimulation PairSimulation.LocalHistory NetworkKernel LiveProgram CutSchedule ExponentTrace
+
+universe v
+variable {K : Type v} [Field K] {S : BlockSchedule K} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M) {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C)
+ [NeZero (virtualBits D.addressFactor n)]
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n) (μ : D.pairNom n C)
+
+local notation "width" => CursorBounds.wordBits D.addressFactor n
+local notation "κ" => B.compressorValues hn M
+local notation "κ_ok" => B.compressorValues_solution hn M
+local notation "blocks" => blockCount (u.θ : ℝ) n
+local notation "sel" => V.selection (M := M)
+local notation "source" => V.scanState
+
+attribute [local irreducible] NominationClock
+
+/-- Data for scanning one nominated virtual pair in a fixed model. It bounds the leaf startup
+clock and final wire width and supplies the term workers' inputs for each possible sequence
+of selected passes. -/
+structure CanonicalScan where
+ clock : NominationClock (d := virtualBits D.addressFactor n) (e := roundedUp 1 4 n) (Q := V.layout i)
+ (V.data data.advice ξ i μ) V.cap.tags V.cap.capFits (n^39)
+ widthFit : ∀ z : (sel).Choices, ((sel).finalState z).totalWidth < 2^width
+ /-- Term-worker inputs for the selected compressor execution at its RAM word width, indexed
+ recursively by the originating pass and all subsequent choices. -/
+ inputs : WorkerInputs sel (CompressorRecords.executeOrigins B κ κ_ok blocks le_rfl source) width
+
+variable {data V ξ i μ} (A : CanonicalScan data V ξ i μ)
+variable (processorFit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+
+private abbrev scanWords (w : ℕ) : Fin 1 → BurstRAM.Word w := fun _ => FinalBits.cursor w 0 0
+private abbrev scanMachine (w : ℕ) := FinalBits.template.instantiate w (scanWords w)
+include A in
+private theorem capacity (z : (sel).Choices) : 0+((sel).finalState z).totalWidth < 2^width := by
+ simpa only [Nat.zero_add] using A.widthFit z
+
+local notation "machine" => scanMachine width
+local notation "linked" => FinalBits.template_linked (scanWords width)
+local notation "scanMemory" => (fun _ : (sel).Choices => (fun _ => 0 : Memory width))
+local notation "enc" => V.phaseTrace data processorFit ξ i μ (n^39) A.clock machine Fin.castSucc (Function.Embedding.refl _) 0 10 linked rfl 0 rfl 0 scanMemory (capacity A)
+
+/-- Trace encoding of the nominated pair's algebraic occurrences using the final-bit scanner
+started at cursor zero in zero memory and the clocked nomination leaf readers. -/
+noncomputable abbrev CanonicalScan.encoding := enc
+/-- Injectively re-encode a canonical scan's selector phases as native term tapes in motif
+order, carrying along the same shared-arc and vertex phases. -/
+noncomputable abbrev CanonicalScan.emission : SelectorReindex (A.encoding processorFit) :=
+ V.phaseEmission data processorFit ξ i μ (n^39) A.clock machine Fin.castSucc (Function.Embedding.refl _) 0 10 linked rfl
+ 0 rfl 0 scanMemory (capacity A) A.inputs
+
+/-- Shared-arc scan phase on the terminal network of the selected compression branch, using the
+final-bit machine and its zero starting cursor. -/
+noncomputable abbrev CanonicalScan.arc (z : (sel).Choices) :=
+ stateScanPhase ((sel).finalState z) machine Fin.castSucc (Function.Embedding.refl _) 0 10 linked rfl
+ 0 rfl (scanMemory z) 0 (capacity A z)
+
+/-- Clocked parsers for the initial cursor-network sites, using the nominated auxiliary
+machine, its reset memory and the selected model's label values. -/
+noncomputable abbrev CanonicalScan.leafSites := nominationSites (V.data data.advice ξ i μ) V.cap.tags V.cap.capFits
+ (laneLabels _ _ V.lanes) V.dimension (Nat.add_sub_of_le S.degree_bounds.1) κ (n^39) A.clock
+
+/-- Chain of compression terms along the chosen execution branch, using the templates' record
+data for those passes. -/
+noncomputable abbrev selectedChain (z : (sel).Choices) := (sel).termChain (B.records κ κ_ok blocks le_rfl source) z
+/-- Final-network site parsers obtained by carrying the nomination leaf parsers through the
+chosen chain with that branch's local parsers. -/
+noncomputable abbrev CanonicalScan.sites (z : (sel).Choices) :=
+ finalParsers (selectedChain z) (selectedParsers B κ κ_ok blocks le_rfl source z) A.leafSites
+
+/-- Bijection between a descriptor branch with its terminal arc and site choices and the
+ordinal phase lists emitted by the canonical scan. -/
+noncomputable def CanonicalScan.ordinals :
+ ((z : (sel).Choices) × TerminalData (A.arc z) (A.sites z)) ≃ Set.range (A.emission processorFit).emit :=
+ V.phaseDataEquiv data processorFit ξ i μ (n^39) A.clock machine Fin.castSucc (Function.Embedding.refl _) 0 10 linked rfl
+ 0 rfl 0 scanMemory (capacity A) A.inputs
+
+/-- For every real per-level pointer assignment, the sum of the selected
+preorder jobs at all sites is the exponent of the recovered occurrence. -/
+theorem CanonicalScan.jobSums (z : (sel).Choices) (x : TerminalData (A.arc z) (A.sites z))
+ (ptr : RowPointers (selectedChain z)) (leaves : (source).network.Site → ℕ × ℕ) :
+ let jobs := vertexJobs (selectedChain z) (selectedParsers B κ κ_ok blocks le_rfl source z) ptr A.leafSites leaves
+ let q := (A.emission processorFit).decode (A.ordinals processorFit ⟨z,x⟩)
+ ∀ l, (V.pairData data processorFit).ν ξ i μ q l = ∑ v, ((x.jobs jobs v).map (fun j => j.increment l)).sum :=
+ ((V.choiceData_jobs data processorFit ξ i μ (n^39) A.clock machine Fin.castSucc (Function.Embedding.refl _) 0 10
+ linked rfl 0 rfl 0 scanMemory (capacity A) A.inputs z x).2.2 ptr leaves).2
+
+/-- Sum of increments to one model-label counter over the preorder jobs of one terminal site,
+using the supplied row pointers and leaf addresses. -/
+noncomputable abbrev CanonicalScan.siteTotals (z : (sel).Choices) (x : TerminalData (A.arc z) (A.sites z))
+ (ptr : RowPointers (selectedChain z)) (leaves : (source).network.Site → ℕ × ℕ) (v : ((sel).finalState z).network.Site)
+ (l : B.Entry) : ℕ :=
+ let jobs := vertexJobs (selectedChain z) (selectedParsers B κ κ_ok blocks le_rfl source z) ptr A.leafSites leaves
+ ((x.jobs jobs v).map (fun a => a.increment l)).sum
+
+/-- All real site deposits, in the site's physical order, give the precise
+canonical counter memory required by the pair source-run certificate. -/
+theorem CanonicalScan.flush (z : (sel).Choices) (x : TerminalData (A.arc z) (A.sites z))
+ (ptr : RowPointers (selectedChain z)) (leaves : (source).network.Site → ℕ × ℕ)
+ {g : ℕ} (counterBase grammar : ℕ) (order : Fin g → B.Entry) (m : Memory width) :
+ let jobs := vertexJobs (selectedChain z) (selectedParsers B κ κ_ok blocks le_rfl source z) ptr A.leafSites leaves
+ let q := (A.emission processorFit).decode (A.ordinals processorFit ⟨z,x⟩)
+ Counters.visit counterBase grammar (fun v j => ((x.jobs jobs v).map (fun a => a.increment (order j))).sum)
+ (List.ofFn (siteOrder ((sel).finalState z)).entries) m =
+ Counters.visit counterBase grammar (fun (v : B.Entry → ℕ) j => v (order j))
+ (V.histograms data processorFit ξ i μ q) m := by
+ intro jobs q
+ exact V.siteFlushes_eq data processorFit ξ i μ q (siteOrder ((sel).finalState z)).entries
+ (fun v l => ((x.jobs jobs v).map (fun a => a.increment l)).sum)
+ (fun l => (A.jobSums processorFit z x ptr leaves l).symm) counterBase grammar order m
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairContinuation.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairContinuation.lean
new file mode 100644
index 0000000000..85bcbb108f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairContinuation.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.LiveCertificateAssembly
+import OAI.Computability.VPVNP.LiveNativePairContinuation
+
+/-!
+# First-half continuation for the fixed program's virtual pair witness
+
+The production nominations use the physical parser order. The paths and
+increments are exactly those of `VirtualPairs.pairData`, computed with the
+auxiliary machine's own private fuel. This supplies the pair argument of
+`assembleLocalCertificate` once its local compressed calls have been realized.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+open BurstRAM CutSchedule ChainAssignments ExponentTrace PairStages LocalCount
+
+variable {G : Group} {S H h Δ a t Z : ℕ} {Nom : Type*} [Fintype Nom]
+ {Path : Exterior h Δ → Fin (2^h) → Nom → Type*} [∀ ξ i μ, Fintype (Path ξ i μ)]
+ (W : Conditions G S H) (P : PairStageConditions G S H) (order : Group.Nominations.Nom G ≃ Nom)
+ (hh : h = (profile G).h) (hΔ : Δ = (profile G).delta) (ha : a = (profile G).advice)
+ (ht : t = Group.labelCount G) (hz : Z = Group.expWidth G)
+ (adv : Bits a) (fit : 1+t*Z ≤ Δ) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+
+/-- Compressed calls on the physical group, expressed with the fixed
+program's mathematical dimensions and its exact path family. -/
+def compressedObligation : Prop := by
+ subst h; subst Δ; subst a; subst t; subst Z
+ exact CompressedCalls W P order adv fit inc
+
+theorem pairObligation_of_compressed
+ (small : ∀ ξ i μ q v, inc ξ i μ q v < 2^(2*G.g.d))
+ (native : compressedObligation W P order hh hΔ ha ht hz adv fit inc) :
+ pairObligation W hh hΔ ha adv fit inc := by
+ subst h; subst Δ; subst a; subst t; subst Z
+ exact pairContinuation_of_compressed W P order adv fit inc small native
+
+end LiveProgram
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork LabelEvaluator BurstRAM LiveProgram CutSchedule ExponentTrace LiveProgram.LocalCount
+open LiveProgram.PairStages.Group
+open scoped Classical
+
+/-- Classical decidable equality for the grammar productions at length n and circuit exponent
+C, used locally to index production nominations. -/
+noncomputable local instance (n C : ℕ) : DecidableEq (JointLabelSystem.Production n C) := Classical.decEq _
+
+open private denseExponent_lt from OAI.Computability.VPVNP.FixedModelDiagonal
+
+universe v
+variable {K : Type v} [Field K] {S : BlockSchedule K} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M)
+ (processorFit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C)
+ {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+
+/-- Reindex the dense nomination array by the production labels of the
+very same virtual coefficient counter. -/
+noncomputable def physicalNomination (hC : D.constants.circuitExponent = C) :
+ Nominations.Nom (D.executionGroup n ht hf) ≃ D.pairNom n C :=
+ (Auxiliary.nominationEquiv _).trans (Equiv.cast (congrArg (D.pairNom n) hC))
+
+variable (W : Conditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (P : PairStageConditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (cutFit : 1+B.denseCount n C * D.counterWidth n ≤ n^D.constants.deltaPower)
+
+include hC hg in
+private theorem labelDimension : B.denseCount n C = labelCount (D.executionGroup n ht hf) := by
+ unfold labelCount executionGroup Constants.labels
+ rw [eval_add,Constants.grammarLabels_eq]
+ simp only [hg,hC,geometry,PublicExpr.eval]
+
+private theorem exponentDimension : D.counterWidth n = expWidth (D.executionGroup n ht hf) := by
+ unfold expWidth executionGroup Constants.Z Constants.height
+ rw [eval_mul,PublicExpr.eval_natPow]
+ rfl
+
+/-- The native obligation for the physical inputs of `VirtualPairs.witness`.
+That witness uses `d.machine d.fuel 0 d.initial` with `d := V.data ...`.
+Its dense increments combine the nominated grammar counts with the
+compression-label counts of that exact choice. -/
+noncomputable abbrev VirtualPairs.compressedCalls :=
+ compressedObligation W P (physicalNomination hC) heights deltas adviceSizes
+ (labelDimension hC hg) exponentDimension data.advice cutFit (increments data processorFit V)
+
+/-- The canonical first-half argument of `assembleLocalCertificate`.
+The only remaining stage-specific premise is the native realization and
+budget of the compressed subroutine. -/
+theorem VirtualPairs.pairObligation (native : V.compressedCalls data processorFit W P hC hg cutFit) :
+ LiveProgram.pairObligation W heights deltas adviceSizes data.advice cutFit (increments data processorFit V) := by
+ apply pairObligation_of_compressed W P (physicalNomination hC) heights deltas adviceSizes
+ (labelDimension hC hg) exponentDimension data.advice cutFit (increments data processorFit V) _ native
+ intro ξ i μ q j
+ exact denseExponent_lt B μ ((V.pairData data processorFit).ν ξ i μ q)
+ ((V.pairData data processorFit).bounded ξ i μ q) j
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairCursorBoundary.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairCursorBoundary.lean
new file mode 100644
index 0000000000..c8340a1b87
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairCursorBoundary.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.CompressorInitialLiveBoundary
+import OAI.Computability.VPVNP.CompressorInitialPairInput
+import OAI.Computability.VPVNP.LiveVirtualPairOrdinalData
+
+/-! # The physical startup graph of the actual virtual pair
+
+The compiled ratio reserves the same lanes as the analytic block count.
+The physical cursor's base and lane coordinate order agrees with the graph
+of the mathematical virtual pair after the dimension cast. Thus its true
+startup reports install the boundary for the exact state used in the
+monomial expansion, on the same eleven public operands and incoming memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorRouting CursorBounds BurstRAM LiveProgram LiveProgram.CompressedPair
+open CompressorRecords CompressorRecords.ScheduledTrace CompressorRecords.DescriptorSpace
+open PairSimulation.LocalHistory PairSimulation.TraversalRows PairSimulation.TraversalRoles
+open scoped Fin.CommRing
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {u : PairExponents B.growthConstant}
+variable {D : FixedProgramDiagonal.Program} {n C : ℕ} {hn : 2 ≤ n} (V : D.VirtualPairs B u hn C)
+
+attribute [local irreducible] BlockProgram.script BlockProgram.layout InitialTransferred.bootstrap CursorNetwork.cursorState
+
+theorem VirtualPairs.scanState_pairInput :
+ V.scanState = pairInput S (laneLabels _ _ V.lanes) V.dimension := by
+ have bucket : virtualBucket n = 2^roundedUp 1 4 n := by
+ simp only [virtualBucket,roundedUp_eq,Nat.cast_one,Nat.cast_ofNat]
+ unfold pairInput
+ rw [bucket]
+
+local notation "addr" => D.addressFactor
+local notation "w" => wordBits D.addressFactor n
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "l" => reservedLanes B u n
+local notation "b" => virtualBits D.addressFactor n - reservedLanes B u n
+local notation "A" => BlockProgram.script B
+
+theorem VirtualPairs.cursorState_eq (sum : 1 < b+l) (hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0)) :
+ cursorState (cursorCoordinateLabels b l) sum hd
+ (ramFieldBits (virtualBucket n) w : RAMSystem (virtualBits addr n) → ℕ) = V.scanState :=
+ (initial_pairInput S addr n l V.lanes V.dimension sum hd).symm.trans V.scanState_pairInput.symm
+
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+
+/-- The initial descriptor interval and its endpoint, reindexed to the
+virtual pair's own state, before its first shrinking visit. -/
+theorem VirtualPairs.initial_boundary (base clk : ℕ) (terminal : PairTable) (pub : Fin 11 → Word w)
+ (incoming : Memory w) (hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0))
+ (physical : InitialLive B f hf (blockRatio u).num (blockRatio u).den addr n base clk terminal pub incoming hd) :
+ let boot := InitialTransferred.bootstrap B (blockRatio u).num (blockRatio u).den
+ let L := BlockProgram.layout B base (initialPositions addr n) T
+ let mem := after incoming (eventLog (cursorStartupLogs boot pub addr n base incoming
+ (A).initial.length (A).block.length (A).size))
+ StartupResult boot (A).plan terminal pub addr n base incoming clk ∧
+ ∃ initial : InitialInterval B base (initialPositions addr n) T (sourceCap pub clk) (BlockClock.small B addr n)
+ b l (initialWidth addr n) pub mem,
+ Boundary (CurrentResident.resident B f hf ⟨leafLayer (siteOrder V.scanState),.cursor⟩ L (endAddress L) n
+ (cursorFrame L (S.degreeExponent 0) b l (initialWidth addr n))) pub (levelWords L : Word w)
+ (directoryRows L) 4 [] V.scanState initial.interval.segment.memory ∧
+ RAMBuckets.cost Report.probes initial.interval.source.logs ≤ initialRate B*(initialPositions addr n+1) ∧
+ BlockClock.small B addr n+3 ≤ sourceCap pub clk ∧
+ sourceCap pub clk+24 = clockAt pub clk Stage.online := by
+ unfold InitialLive at physical
+ rw [blockRatio_floor] at physical
+ obtain ⟨setup,sum,initial,ready,cost,slack,clock⟩ := physical
+ have eqn := V.cursorState_eq sum hd
+ exact ⟨setup,initial,eqn ▸ ready,cost,slack,clock⟩
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairDescriptorExecution.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairDescriptorExecution.lean
new file mode 100644
index 0000000000..4ae827f3b5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairDescriptorExecution.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.LiveVirtualPairCursorBoundary
+import OAI.Computability.VPVNP.CompressorDetailedResident
+import OAI.Computability.VPVNP.CompressorScheduledExecution
+
+/-! # The selected virtual pair's descriptor execution and retained data
+
+The descriptor's actual initial memory is obtained after the eight linked
+startup calls and four fixed cursor visits. It is the memory used for the
+first shrinking pass of the virtual pair. The empty past carries its payload
+invariant, and the native execution retains every selected pass's data at
+the physical terminal boundary.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorRouting CursorBounds BurstRAM LiveProgram LiveProgram.CompressedPair Filter
+open CompressorRecords CompressorRecords.ScheduledTrace CompressorRecords.DescriptorSpace
+open PairSimulation.LocalHistory PairSimulation.TraversalRows PairSimulation.TraversalRoles
+open scoped Fin.CommRing
+
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {u : PairExponents B.growthConstant}
+variable {D : FixedProgramDiagonal.Program} {n C : ℕ} {hn : 2 ≤ n} (V : D.VirtualPairs B u hn C)
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+local notation "addr" => D.addressFactor
+local notation "ww" => wordBits D.addressFactor n
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "l" => reservedLanes B u n
+local notation "b" => virtualBits D.addressFactor n - reservedLanes B u n
+local notation "A" => BlockProgram.script B
+local notation "P" => initialPositions D.addressFactor n
+local notation "X" => VirtualPairs.scanState V
+local notation "E" => B.execute f hf T le_rfl (VirtualPairs.scanState V)
+local notation "small" => BlockClock.small B D.addressFactor n
+
+attribute [local irreducible] BlockProgram.script BlockProgram.layout CursorNetwork.cursorState
+
+/-- A common length threshold supplies graph and wire-width bounds on all
+partial branches before the scalar algebra and the virtual pair are chosen. -/
+theorem eventually_scan_prefix (D : FixedProgramDiagonal.Program) (B : S.Templates) (u : PairExponents B.growthConstant)
+ (C : ℕ) (haddr : max S.laneBits 5 ≤ D.addressFactor) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C) (R : Type*) [CommRing R]
+ (f : B.Entry → R) (hf : B.IsSolution f), PrefixLevelScale.Within (initialPositions D.addressFactor n) n
+ (B.execute f hf (blockCount (u.θ : ℝ) n) le_rfl V.scanState) := by
+ filter_upwards [PrefixLevelScale.eventually_execute B u D.addressFactor haddr] with n fits hn V R inst f hf
+ rw [V.scanState_pairInput]
+ exact fits _ V.dimension le_rfl R f hf
+
+/-- The resident descriptor data for the virtual pair's native execution, with its initial
+cursor layer, physical layout, cursor frame and selected payload history. -/
+noncomputable abbrev VirtualPairs.nativeResident (base : ℕ) (payload : SelectedPayloadHistory.Data (w := ww) B f hf) :
+ ScheduledTrace.Resident B f hf ww :=
+ let L := BlockProgram.layout B base P T
+ DetailedResident.resident B f hf ⟨leafLayer (siteOrder X),.cursor⟩ L (endAddress L) n
+ (cursorFrame L (S.degreeExponent 0) b l (initialWidth addr n)) payload
+
+theorem VirtualPairs.descriptor_execution (base clk rate : ℕ) (terminal : PairTable) (pub : Fin 11 → Word ww)
+ (incoming : Memory ww) (hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0))
+ (physical : InitialLive B f hf (blockRatio u).num (blockRatio u).den addr n base clk terminal pub incoming hd)
+ (payload : SelectedPayloadHistory.Data (w := ww) B f hf)
+ (smallBounds : Schedule.Online.Run.ControlBounds (A).plan small (w := ww))
+ (size : PrefixLevelScale.Within P n E)
+ (build : let L := BlockProgram.layout B base P T
+ LocatedRuns (V.nativeResident f hf base payload) pub (levelWords L : Word ww) (directoryRows L)
+ (sourceCap pub clk) small rate T P n) :
+ let boot := InitialTransferred.bootstrap B (blockRatio u).num (blockRatio u).den
+ let L := BlockProgram.layout B base P T
+ let mem := after incoming (eventLog (cursorStartupLogs boot pub addr n base incoming
+ (A).initial.length (A).block.length (A).size))
+ StartupResult boot (A).plan terminal pub addr n base incoming clk ∧
+ ∃ initial : InitialInterval B base P T (sourceCap pub clk) small b l (initialWidth addr n) pub mem,
+ RAMBuckets.cost Report.probes initial.interval.source.logs ≤ initialRate B*(P+1) ∧
+ small+3 ≤ sourceCap pub clk ∧ sourceCap pub clk+24 = clockAt pub clk Stage.online ∧
+ Nonempty (ScheduledTrace.Result (V.nativeResident f hf base payload) pub (levelWords L : Word ww) (directoryRows L)
+ (sourceCap pub clk) small (T*(S.steps+1)*rate+4) E (executeOrigins B f hf T le_rfl X) _
+ (nativeReaders (B := B) (f := f) (hf := hf) le_rfl X) [] (some 0) initial.interval.segment.memory) := by
+ let L := BlockProgram.layout B base P T
+ obtain ⟨setup,initial,ready,work,slack,hclock⟩ := V.initial_boundary f hf base clk terminal pub incoming hd physical
+ refine ⟨setup,initial,work,slack,hclock,?_⟩
+ have total := BlockProgram.directory_rows B base P T
+ have start := BlockProgram.initial_length B
+ have live : Boundary (V.nativeResident f hf base payload) pub (levelWords L : Word ww)
+ (directoryRows L) 4 [] X initial.interval.segment.memory :=
+ ⟨ready.bank,ready.tag,ready.ordinalValue,ready.totalValue,ready.stride,ready.stored,SelectedPayloadHistory.Past.empty⟩
+ have bounds : Schedule.Online.Run.ControlBounds (A).plan (sourceCap pub clk) (w := ww) :=
+ ⟨smallBounds.tags,smallBounds.calendar.trans (by omega),smallBounds.launch.trans (by omega)⟩
+ change directoryRows L = _ at total
+ dsimp only at build
+ change LocatedRuns _ pub _ (directoryRows L) _ _ _ _ _ _ at build
+ rw [total] at live build ⊢
+ rw [← start] at live
+ exact execute_of_local le_rfl X initial.interval.segment.memory bounds smallBounds build size live
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairHistograms.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairHistograms.lean
new file mode 100644
index 0000000000..85a84f6fbb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairHistograms.lean
@@ -0,0 +1,175 @@
+import OAI.Computability.VPVNP.LivePreparedPairCounters
+import OAI.Computability.VPVNP.LiveVirtualPairReadback
+import OAI.Computability.VPVNP.PairRAMCounterReadback
+
+/-! # Reading the canonical compressed-pair increments in the live counter array
+
+The grammar prefix in the actual post-copy memory already contains the nomination.
+The final-site histogram visits add the compressor exponents to the zero motif suffix.
+Both parts use the same dense order as the fixed program's exponent update.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression CursorNetwork LiveProgram PairStages PairStages.Group
+open ExponentTrace CutSchedule ChainAssignments LabelEvaluator JointLabelSystem PairSimulation
+
+universe v
+variable {D : FixedProgramDiagonal.Program} {n C : ℕ}
+ {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+ {K : Type v} [Field K] {S : BlockSchedule K} {B : S.Templates}
+
+theorem physicalGrammarCount (hC : D.constants.circuitExponent = C) :
+ Auxiliary.histLength (D.executionGroup n ht hf) = FixedRows.productionCount n C := by
+ change D.constants.grammarLabels.eval (D.geometry n) = _
+ rw [D.constants.grammarLabels_eq, hC]
+ rfl
+
+/-- Numbering of the compressor labels in the suffix of the actual counter array. -/
+noncomputable def physicalMotifOrder (hg : D.constants.motifLabels = Fintype.card B.Entry) :
+ Fin D.constants.motifLabels ≃ B.Entry :=
+ (finCongr hg).trans (Fintype.equivFin B.Entry).symm
+
+theorem physicalDenseSize (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry) :
+ Auxiliary.histLength (D.executionGroup n ht hf) + D.constants.motifLabels = B.denseCount n C :=
+ congrArg₂ Nat.add (physicalGrammarCount hC) hg
+
+/-- The index transport from the exponent stage to the mathematical array keeps
+the address ordinal of each counter. -/
+theorem physicalPairLabelCount (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry) :
+ Group.labelCount (D.executionGroup n ht hf) = B.denseCount n C :=
+ physicalDenseSize hC hg
+
+theorem physicalPairCounterAddr (hs : Auxiliary.shadowBase (D.executionGroup n ht hf) < 2^(D.executionGroup n ht hf).w) (j : Fin (Group.labelCount (D.executionGroup n ht hf))) :
+ (LiveExponent.counterAddr (D.executionGroup n ht hf).exponentPub j).val = Auxiliary.counterBase (D.executionGroup n ht hf) + j.val := by
+ have base : ((D.executionGroup n ht hf).exponentPub 2).val = Auxiliary.counterBase (D.executionGroup n ht hf) := (Auxiliary.address_values (D.executionGroup n ht hf) hs).2.2.1
+ have fit : ((D.executionGroup n ht hf).exponentPub 2).val + Group.labelCount (D.executionGroup n ht hf) ≤ 2^(D.executionGroup n ht hf).w := by
+ rw [base]
+ exact (Auxiliary.counter_end_le_shadow (D.executionGroup n ht hf)).trans hs.le
+ exact (LiveExponent.counterAddr_val _ _ fit).trans (congrArg (· + j.val) base)
+
+private theorem grammarEntry (hC : D.constants.circuitExponent = C) (μ : Nominations.Nom (D.executionGroup n ht hf))
+ (j : Fin (FixedRows.productionCount n C)) :
+ physicalNomination hC μ ((PrimedStackRAM.labelIndex n n _).symm j) =
+ μ (j.cast (physicalGrammarCount (ht := ht) (hf := hf) hC).symm) := by
+ subst C
+ change μ ((Auxiliary.order (D.executionGroup n ht hf)) ((PrimedStackRAM.labelIndex n n _).symm j)) = _
+ apply congrArg μ
+ apply Fin.ext
+ have h := congrArg (fun a : Fin (FixedRows.productionCount n D.constants.circuitExponent) => a.val)
+ ((PrimedStackRAM.labelIndex n n (n^(D.constants.circuitExponent+5))).apply_symm_apply j)
+ exact h
+
+theorem physicalDenseExponent (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (μ : Nominations.Nom (D.executionGroup n ht hf)) (ν : B.Entry → ℕ) (j : Fin (B.denseCount n C)) :
+ Fin.addCases (fun i => (μ i).val) (fun i => ν (physicalMotifOrder hg i))
+ (j.cast (physicalDenseSize (ht := ht) (hf := hf) hC hg).symm) =
+ B.denseExponent (fun p => (physicalNomination hC μ p).val) ν j := by
+ obtain ⟨(k | k), rfl⟩ := finSumFinEquiv.surjective j
+ · let k' := k.cast (physicalGrammarCount (ht := ht) (hf := hf) hC).symm
+ have index : (finSumFinEquiv (.inl k)).cast (physicalDenseSize (ht := ht) (hf := hf) hC hg).symm =
+ k'.castAdd D.constants.motifLabels := Fin.ext rfl
+ rw [index, Fin.addCases_left]
+ simp only [BlockSchedule.Templates.denseExponent, Equiv.symm_apply_apply, Sum.elim_inl, Function.comp_apply]
+ rw [grammarEntry]
+ · let k' := k.cast hg.symm
+ have index : (finSumFinEquiv (.inr k)).cast (physicalDenseSize (ht := ht) (hf := hf) hC hg).symm =
+ k'.natAdd (Auxiliary.histLength (D.executionGroup n ht hf)) := by
+ apply Fin.ext
+ change FixedRows.productionCount n C + k.val = Auxiliary.histLength (D.executionGroup n ht hf) + k.val
+ rw [physicalGrammarCount hC]
+ rw [index, Fin.addCases_right]
+ simp only [BlockSchedule.Templates.denseExponent, Equiv.symm_apply_apply, Sum.elim_inr, Function.comp_apply]
+ rfl
+
+private theorem stored_eq_of_readback {w b t : ℕ} (base : BurstRAM.Word w) (fit : base.val+t ≤ 2^w) (width : b ≤ w)
+ (μ : Fin t → BurstRAM.Word b) (m : Memory w) (read : ∀ j : Fin t, (m (base.val+j.val)).val = (μ j).val) :
+ LiveNominations.stored base fit μ m = m := by
+ funext a
+ by_cases h : base.val ≤ a ∧ a < base.val+t
+ · let j : Fin t := ⟨a-base.val, by omega⟩
+ have addr : a = base.val+j.val := by dsimp [j]; omega
+ rw [addr]
+ apply Fin.ext
+ exact (LiveNominations.stored_at_val width base fit μ m j).trans (read j).symm
+ · exact LiveNominations.stored_outside _ _ _ _ _ (by omega)
+
+variable {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M)
+ (processorFit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C)
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n)
+
+/-- Final-site histograms of this precise virtual machine occurrence, using its private fuel. -/
+noncomputable def VirtualPairs.histograms (μ : D.pairNom n C)
+ (q : (V.pairData data processorFit).Path ξ i μ) : List (B.Entry → ℕ) :=
+ let d := V.data data.advice ξ i μ
+ pairRAMHistogramsWithFuel B u V.dimension V.cap (laneLabels _ _ V.lanes) le_rfl
+ (B.compressorValues hn M) (B.compressorValues_solution hn M) d.machine d.fuel 0 d.initial q
+
+variable (hC : D.constants.circuitExponent = C)
+ (hg : D.constants.motifLabels = Fintype.card B.Entry) (μ : Nominations.Nom (D.executionGroup n ht hf))
+ {m : Memory (D.executionGroup n ht hf).w} {hw : 4 ≤ (D.executionGroup n ht hf).w} {advice : Bits (Auxiliary.sizes (D.executionGroup n ht hf)).advice}
+ {cuts : AllCuts (Auxiliary.sizes (D.executionGroup n ht hf)).h (Auxiliary.sizes (D.executionGroup n ht hf)).delta} {mode : LiveHeader.Mode.Tag}
+ (out : LiveHeaderProgram.Output (Auxiliary.sizes (D.executionGroup n ht hf)) (Auxiliary.headerBase (D.executionGroup n ht hf)) (D.executionGroup n ht hf).g.d hw advice cuts
+ (halves (Auxiliary.sizes (D.executionGroup n ht hf)).h (.inl (physicalPairIndex i))) mode m)
+ (F : Nominations.Fits (D.executionGroup n ht hf)) (tag : (D.executionGroup n ht hf).tagged Stage.nominations m)
+ {hdr : PrimedInputRAM.Header (Auxiliary.pairLengths (D.executionGroup n ht hf) (physicalPairIndex i)) → Bool}
+ (P : Auxiliary.PreparedBranch (D.executionGroup n ht hf) m (physicalPairIndex i) hdr (Nominations.indexed (D.executionGroup n ht hf) F m tag) μ)
+ (hs : Auxiliary.shadowBase (D.executionGroup n ht hf) < 2^(D.executionGroup n ht hf).w)
+ (q : (V.pairData data processorFit).Path ξ i (physicalNomination hC μ))
+
+include out hs
+
+set_option maxHeartbeats 1200000 in
+/-- The true post-copy memory followed by the canonical compressed-pair visits reads out
+the fixed program's joint increments, at every dense counter address. -/
+theorem VirtualPairs.counterVisits_readback (j : Fin (B.denseCount n C)) :
+ let hist := V.histograms data processorFit ξ i (physicalNomination hC μ) q
+ let final := Counters.visit (Auxiliary.counterBase (D.executionGroup n ht hf)) (Auxiliary.histLength (D.executionGroup n ht hf))
+ (fun (v : B.Entry → ℕ) k => v (physicalMotifOrder hg k)) hist (P.copy.memory ())
+ (final (Auxiliary.counterBase (D.executionGroup n ht hf)+j.val)).val = increments data processorFit V ξ i (physicalNomination hC μ) q j := by
+ dsimp only
+ let d := V.data data.advice ξ i (physicalNomination hC μ)
+ let base := Auxiliary.counter (D.executionGroup n ht hf)
+ have baseEq : base.val = Auxiliary.counterBase (D.executionGroup n ht hf) := (Auxiliary.address_values (D.executionGroup n ht hf) hs).2.2.1
+ obtain ⟨prefixRead, suffixRead⟩ := P.initialCounters out F tag μ hs
+ have pref (k : Fin (Auxiliary.histLength (D.executionGroup n ht hf))) : (P.copy.memory () (base.val+k.val)).val = (μ k).val := by
+ rw [baseEq]; exact prefixRead k
+ have suff (k : Fin D.constants.motifLabels) :
+ P.copy.memory () (base.val+Auxiliary.histLength (D.executionGroup n ht hf)+k.val) = 0 := by
+ rw [baseEq]; exact suffixRead k
+ have stored := stored_eq_of_readback base F.address F.width_le μ (P.copy.memory ()) pref
+ have degree := V.degree M.algebra (B.compressorValues hn M) (B.compressorValues_solution hn M)
+ i (PairedChain.headers data.advice ξ i) (physicalNomination hC μ) q
+ have read := pairRAMHistogramsWithFuel_readback B u V.dimension V.cap (laneLabels _ _ V.lanes) le_rfl
+ (B.compressorValues hn M) (B.compressorValues_solution hn M) d.machine d.fuel 0 d.initial q degree
+ (physicalMotifOrder hg) base F.address μ (P.copy.memory ()) suff
+ (j.cast (physicalDenseSize (ht := ht) (hf := hf) hC hg).symm)
+ dsimp only at read
+ rw [← baseEq, ← stored]
+ exact read.trans (physicalDenseExponent hC hg μ _ j)
+
+/-- The native exponent stage sees the same increments at its actual word addresses. -/
+theorem VirtualPairs.counterAddr_readback (a : Fin (Group.labelCount (D.executionGroup n ht hf))) :
+ let hist := V.histograms data processorFit ξ i (physicalNomination hC μ) q
+ let final := Counters.visit (Auxiliary.counterBase (D.executionGroup n ht hf)) (Auxiliary.histLength (D.executionGroup n ht hf))
+ (fun (v : B.Entry → ℕ) k => v (physicalMotifOrder hg k)) hist (P.copy.memory ())
+ (final (LiveExponent.counterAddr (D.executionGroup n ht hf).exponentPub a).val).val =
+ increments data processorFit V ξ i (physicalNomination hC μ) q
+ (a.cast (physicalPairLabelCount (ht := ht) (hf := hf) hC hg)) := by
+ dsimp only
+ rw [physicalPairCounterAddr hs a]
+ exact V.counterVisits_readback data processorFit ξ i hC hg μ out F tag P hs q
+ (a.cast (physicalPairLabelCount (ht := ht) (hf := hf) hC hg))
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairJobCounters.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairJobCounters.lean
new file mode 100644
index 0000000000..4c39523770
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairJobCounters.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.LiveVirtualPairHistograms
+
+/-! # Equating terminal job flushes with the canonical pair histogram
+
+The terminal interpreter may enumerate its local jobs in a different order from
+the compressed witness's histograms. The accumulated counters agree in every
+cell as soon as the integer increment sums agree for each motif label.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.Counters
+
+open BurstRAM
+
+theorem visit_eq_of_sums {A B : Type*} {g w : ℕ} (base grammar : ℕ) (f : A → Fin g → ℕ) (u : List A)
+ (h : B → Fin g → ℕ) (v : List B) (m : Memory w)
+ (sums : ∀ j : Fin g, (u.map (fun a => f a j)).sum = (v.map (fun b => h b j)).sum) :
+ visit base grammar f u m = visit base grammar h v m := by
+ funext a
+ by_cases inside : base+grammar ≤ a ∧ a < base+grammar+g
+ · let j : Fin g := ⟨a-(base+grammar),by omega⟩
+ have addr : a = base+grammar+j.val := by dsimp [j]; omega
+ rw [addr,visit_at,visit_at,sums j]
+ · have outside : a < base+grammar ∨ base+grammar+g ≤ a := by omega
+ rw [visit_outside _ _ _ _ _ _ outside, visit_outside _ _ _ _ _ _ outside]
+
+end PairSimulation.Counters
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork BurstRAM LabelEvaluator ExponentTrace PairSimulation
+
+universe v
+variable {D : FixedProgramDiagonal.Program} {n C : ℕ} {K : Type v} [Field K] {S : BlockSchedule K}
+ {B : S.Templates} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M)
+ (processorFit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C)
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n) (μ : D.pairNom n C)
+ (q : (V.pairData data processorFit).Path ξ i μ)
+
+/-- The ordered final-site histograms sum to the exponent of this very occurrence. -/
+theorem VirtualPairs.histograms_sum (l : B.Entry) :
+ ((V.histograms data processorFit ξ i μ q).map (fun h => h l)).sum =
+ (V.pairData data processorFit).ν ξ i μ q l := by
+ exact Counters.vertexHistograms_sum _ _ _ _ _ q l
+
+/-- A terminal visit in any physical site order flushes precisely the canonical
+counter memory when its local job increments sum to the witness exponents. -/
+theorem VirtualPairs.siteFlushes_eq {Site : Type*} [Fintype Site] {N g w : ℕ}
+ (sites : Fin N ≃ Site) (counts : Site → B.Entry → ℕ)
+ (powers : ∀ l, (∑ v, counts v l) = (V.pairData data processorFit).ν ξ i μ q l)
+ (base grammar : ℕ) (order : Fin g → B.Entry) (m : Memory w) :
+ Counters.visit base grammar (fun site j => counts site (order j)) (List.ofFn sites) m =
+ Counters.visit base grammar (fun (h : B.Entry → ℕ) j => h (order j))
+ (V.histograms data processorFit ξ i μ q) m := by
+ apply Counters.visit_eq_of_sums
+ intro j
+ rw [V.histograms_sum data processorFit ξ i μ q, ← powers]
+ simp only [List.map_ofFn, List.sum_ofFn, Function.comp_apply]
+ exact sites.sum_comp (fun v => counts v (order j))
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairNativeAssembly.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairNativeAssembly.lean
new file mode 100644
index 0000000000..1afe51afd9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairNativeAssembly.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.LiveVirtualPairSourceAssembly
+import OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+
+/-!
+# Instantiating the native source certificate for the chosen finite model
+
+The coefficient counter uses the exterior, pair index and nomination of
+this physical group. For each actual descriptor selection, the terminal
+vertex jobs update the dense counter bank. Their integer increments recover
+the exponents of exactly the canonical virtual occurrence decoded from
+the ordinal emission.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM LiveProgram LocalCount
+open PairStages PairStages.Group PairStages.Group.CompressedPaths CompressedPair
+open PairSimulation PairSimulation.LocalHistory NetworkKernel CompressorRecords CompressorRecords.Schedule
+
+attribute [local irreducible] CompressedPair.stages CompressedPair.regs CompressedPair.components TerminalProgram.workers
+
+universe v
+variable {D : FixedProgramDiagonal.Program} {n C : ℕ} {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+ {K : Type v} [Field K] {S : BlockSchedule K} {B : S.Templates} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M) (fit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C) [NeZero (virtualBits D.addressFactor n)]
+
+local notation "grp" => D.executionGroup n ht hf
+variable (W : Conditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (P : PairStageConditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (cut : 1+B.denseCount n C*D.counterWidth n ≤ n^D.constants.deltaPower)
+ (I : VirtualPairs.PhysicalInput data W P hC hg cut)
+local notation "ext" => VirtualPairs.exterior data W P hC hg cut I
+local notation "idx" => VirtualPairs.modelIndex data W P hC hg cut I
+local notation "nom" => physicalNomination hC I.μ
+local notation "mem" => I.branch.copy.memory ()
+local notation "sel" => V.selection (M := M)
+local notation "ws" => PublicExpr.eval (D.geometry n) (Layout.pairWorkspace D.constants)
+local notation "ports" => publicWords grp
+local notation "clk" => fuel grp
+
+variable (A : CanonicalScan data V (VirtualPairs.exterior data W P hC hg cut I)
+ (VirtualPairs.modelIndex data W P hC hg cut I) (physicalNomination hC I.μ))
+variable {d initial phases : ℕ} {catalog : Catalog d} {b : Bootstrap} {plan : Online.Config catalog initial phases}
+ {shape : DescriptorSpace.Shape} {limit : ℕ} {segments : VertexImage.Part → VertexImage.Segment}
+local notation "lastStage" => terminalBody shape limit segments
+local notation "entry" => after mem (eventLog (cursorStartupLogs b ports D.addressFactor n ws mem initial phases d))
+variable (physical : PhysicalStages b plan (terminalBody shape limit segments) (D.executionGroup n ht hf)
+ D.addressFactor n ((Layout.pairWorkspace D.constants).eval (D.geometry n)) (I.branch.copy.memory ()))
+variable (descriptor : (V.selection (M := M)).Choices ≃ StagePaths b plan (terminalBody shape limit segments)
+ (publicWords (D.executionGroup n ht hf)) (fuel (D.executionGroup n ht hf)) CompressedPair.Stage.online
+ (after (I.branch.copy.memory ()) (eventLog (cursorStartupLogs b (publicWords (D.executionGroup n ht hf)) D.addressFactor n
+ ((Layout.pairWorkspace D.constants).eval (D.geometry n)) (I.branch.copy.memory ()) initial phases d))))
+ (branches : ∀ z : (V.selection (M := M)).Choices, TerminalBranch (b := b) (plan := plan)
+ (shape := shape) (limit := limit) (segments := segments) (G := D.executionGroup n ht hf) (B := D.addressFactor) (n := n)
+ (base := (Layout.pairWorkspace D.constants).eval (D.geometry n)) (m := I.branch.copy.memory ()) descriptor (A.arc z) (A.sites z) z)
+
+set_option maxHeartbeats 1200000 in
+/-- A physical descriptor classification and the five actual terminal blocks
+supply the native-run certificate. The deposited counters here are the
+source's local job counts. The conversion to canonical algebraic exponents
+is proved by `CanonicalScan.flush`. -/
+noncomputable def VirtualPairs.nativeRunsOfTerminal
+ (setup : TransferredStartup.Runs (bootstrapRows b initial phases) d
+ (startupLayout b initial phases D.addressFactor n ws) D.addressFactor n b.degreeBits b.lanesPerBlock b.steps
+ ports (PairTag.address ports) mem) (workspaceFit : ws < 2^(D.geometry n).w)
+ (onlineFrame : ∀ a < Auxiliary.tableBase grp, physical.onlineFrame.word a)
+ (terminalFrame : ∀ a < Auxiliary.tableBase grp, ∀ path, (physical.terminalFrame path).word a)
+ (ptr : ∀ z : (sel).Choices, RowPointers (selectedChain (V := V) (M := M) z))
+ (leaf : (V.scanState).network.Site → ℕ × ℕ)
+ (deposited : ∀ z (x : TerminalData (A.arc z) (A.sites z)) (j : Fin (labelCount grp)),
+ ((branches z).vertexPaths x.arcs x.choices).val.memory (Auxiliary.counterBase grp+j.val) =
+ (Counters.visit (Auxiliary.counterBase grp) (Auxiliary.histLength grp)
+ (fun v k => A.siteTotals z x (ptr z) leaf v (physicalMotifOrder hg k))
+ (List.ofFn (siteOrder ((sel).finalState z)).entries) mem) (Auxiliary.counterBase grp+j.val))
+ (budget : ∀ z (x : TerminalData (A.arc z) (A.sites z)),
+ let rs := branchReports descriptor branches z x
+ (∀ r ∈ rs, r.events.length+4 ≤ clk) ∧ 4*RAMBuckets.cost Report.probes rs ≤ 2^(D.geometry n).d*(D.geometry n).H ∧
+ ∀ r ∈ rs, 3+r.probes ≤ (D.geometry n).H) : V.nativeRuns data fit W P hC hg cut I := by
+ apply PhysicalStages.sourceRuns physical (A.encoding fit) (A.emission fit) _ descriptor (terminal_tag_fits grp)
+ ((by decide : 26 ≤ 54).trans (terminal_clock_fits grp W.clock)) branches
+ (A.ordinals fit) setup rfl workspaceFit I.shadowFit onlineFrame terminalFrame _ budget
+ intro z x j
+ exact (deposited z x j).trans (congrFun (A.flush fit z x (ptr z) leaf
+ (Auxiliary.counterBase grp) (Auxiliary.histLength grp) (physicalMotifOrder hg) mem)
+ (Auxiliary.counterBase grp+j.val))
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairOccurrence.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairOccurrence.lean
new file mode 100644
index 0000000000..e78d5e47fd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairOccurrence.lean
@@ -0,0 +1,250 @@
+import OAI.Computability.VPVNP.LiveVirtualPairHistograms
+import OAI.Computability.VPVNP.LiveCompressedPairOccurrence
+
+/-! # From source tapes and histogram visits to the fixed program's compressed call
+
+A native schedule emits concrete per-call tapes from its selector, arc and final-site
+phases. The accepting-tape equivalence below uses the identity on those tapes.
+The only counter condition on the simulator concerns its actual writes. Their
+mathematical values follow from readback of the canonical virtual occurrence.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.CompressedPaths
+
+open BurstRAM BurstRAM.PrivateRAM PairSimulation.LocalHistory
+
+/-- Source-level obligations for one schedule on the actual prepared memory.
+The returned reports are the unrelocated reports of the pair instruction table. -/
+structure SourceRuns (G : Group) (input : Memory G.w) (X : Type) (visited : X → Memory G.w) (S H : ℕ) where
+ /-- Trace encoding that identifies the source schedule's semantic occurrences with their
+ selector, arc and vertex phases. -/
+ encoding : TraceEncoding X
+ /-- Injective translation from those encoded phases to native motif-ordinal term bursts and
+ the corresponding arc and vertex bursts. -/
+ emission : SelectorReindex encoding
+ /-- Per-call private tapes for each emitted ordinal phase list. Their range is exactly the
+ tapes on which the native pair program runs from the prepared memory to a halt. -/
+ tapes : Set.range emission.emit → List (List Bool)
+ tapes_injective : Function.Injective tapes
+ accepts : ∀ bs, bs ∈ Set.range tapes ↔ ∃ rs, runSegment (native G) (fuel G) (some 0) input bs = some rs ∧
+ endState (some 0) rs = none
+ tag : PreservesTag G input
+ effects : ∀ p rs, runSegment (native G) (fuel G) (some 0) input (tapes p) = some rs →
+ (∀ a, Auxiliary.headerBase G ≤ a → a < Auxiliary.tableBase G → after input (eventLog rs) a = input a) ∧
+ (∀ a : Fin (labelCount G), after input (eventLog rs) (Auxiliary.counterBase G+a.val) =
+ visited (emission.decode p) (Auxiliary.counterBase G+a.val)) ∧
+ 4*RAMBuckets.cost Report.probes rs ≤ S*H ∧
+ ∀ r ∈ rs, r.events.length+4 ≤ fuel G ∧ 3+r.probes ≤ H
+
+variable {G : Group} {input : Memory G.w} {X : Type} {visited : X → Memory G.w} {S H : ℕ}
+ (U : SourceRuns G input X visited S H)
+
+/-- The equivalence to raw accepted paths preserves the actual list of tapes. -/
+noncomputable def SourceRuns.paths : Set.range U.emission.emit ≃ Raw G input :=
+ (Equiv.ofInjective U.tapes U.tapes_injective).trans (Equiv.subtypeEquivRight fun bs => by
+ rw [U.accepts bs]
+ simp only [and_true])
+
+@[simp] theorem SourceRuns.paths_tapes (p : Set.range U.emission.emit) : (U.paths p).val = U.tapes p := rfl
+
+/-- Assemble the relocation contract using only the source classification, its
+execution facts, and counter readback of the selected mathematical occurrence. -/
+noncomputable def SourceRuns.execution (inc : X → Fin (labelCount G) → ℕ)
+ (read : ∀ x a, (visited x (Auxiliary.counterBase G+a.val)).val = inc x a) :
+ Execution G input X inc S H := by
+ have h (p : Set.range U.emission.emit) := U.effects p (reports (U.paths p)) (rawRun (U.paths p))
+ exact ⟨U.encoding, U.emission, U.paths, U.tag,
+ fun p r hr => ((h p).2.2.2 r hr).1, fun p => (h p).1,
+ fun p a => (congrArg Fin.val ((h p).2.1 a)).trans (read _ a),
+ fun p => (h p).2.2.1, fun p r hr => ((h p).2.2.2 r hr).2⟩
+
+end LiveProgram.PairStages.Group.CompressedPaths
+
+namespace LiveProgram.LocalCount
+
+open BurstRAM CutSchedule ChainAssignments ExponentTrace LiveHeader LiveHeaderProgram PairStages PairStages.Group
+
+variable {G : Group} {S H : ℕ}
+
+/-- The physical inputs at one nominated first-half group. -/
+structure CompressedInput (W : Conditions G S H) (P : PairStageConditions G S H)
+ (adv : Bits (profile G).advice) (fit : 1+labelCount G*expWidth G ≤ (profile G).delta) where
+ /-- Assignment of all physical cuts for the chain containing the selected first-half pair
+ group. -/
+ cuts : AllCuts (profile G).h (profile G).delta
+ /-- Zero-based index of the nominated pair group within the first half of the physical chain. -/
+ i : Fin (2^(profile G).h)
+ selected : physicalTag cuts (halves (profile G).h (.inl i)) = some .pair
+ padding : ∀ side, Fields.ValidPadding (profile G) cuts (halves (profile G).h (.inl i)) .pair side
+ /-- Prepared header-stage execution for this first-half group on its actual cuts and advice,
+ furnishing the memory from which nominations are read. -/
+ trace : Prepared W adv cuts (halves (profile G).h (.inl i)) .pair
+ out : Output (profile G) (Header.base G.g) G.g.d W.word adv cuts (halves (profile G).h (.inl i)) .pair (memory trace)
+ /-- Production-count nomination selected for this pair by the physical nomination stage. -/
+ μ : Nominations.Nom G
+ /-- Initialization and sparse-copy runs for the selected nomination, preparing the auxiliary
+ pair memory with the header from the actual exterior cuts. -/
+ branch : Auxiliary.PreparedBranch G (memory trace) i (PairedChain.headers adv (exteriorOf fit (fst cuts)) i)
+ (Nominations.indexed G (Auxiliary.nominationFits G i (P.room i) P.width.le P.nominations) (memory trace) trace.tag) μ
+
+variable {W : Conditions G S H} {P : PairStageConditions G S H} {adv : Bits (profile G).advice}
+ {fit : 1+labelCount G*expWidth G ≤ (profile G).delta} (I : CompressedInput W P adv fit)
+
+/-- Recover the primed exterior cut strings from the outgoing exterior fields of the first-half
+physical cuts, starting with the width-zero initial cut. -/
+abbrev CompressedInput.exterior := exteriorOf fit (fst I.cuts)
+/-- Certify the nomination stage's address, word-width and clock requirements for the selected
+group using the pair-stage conditions at its index. -/
+abbrev CompressedInput.nominationFits := Auxiliary.nominationFits G I.i (P.room I.i) P.width.le P.nominations
+
+include I in
+theorem CompressedInput.shadowFit : Auxiliary.shadowBase G < 2^G.w := by
+ have room := P.room I.i
+ have positive : 0 < LiveAuxiliaryHeaders.span (Auxiliary.pairLengths G I.i) (Auxiliary.histLength G) := by
+ simp [LiveAuxiliaryHeaders.span,PrimedInputRAM.Header.count]
+ omega
+
+variable {h Δ a t Z : ℕ} {Nom : Type}
+ {Path : Exterior h Δ → Fin (2^h) → Nom → Type} [∀ ξ i μ, Fintype (Path ξ i μ)]
+ (W : Conditions G S H) (P : PairStageConditions G S H)
+ (order : Nominations.Nom G ≃ Nom) (hh : h = (profile G).h) (hd : Δ = (profile G).delta)
+ (ha : a = (profile G).advice) (ht : t = labelCount G) (hz : Z = expWidth G)
+ (advice : Bits a) (cut : 1+t*Z ≤ Δ) (inc : ∀ ξ i μ, Path ξ i μ → Fin t → ℕ)
+
+theorem physicalFit (hd : Δ = (profile G).delta) (ht : t = labelCount G) (hz : Z = expWidth G)
+ (cut : 1+t*Z ≤ Δ) : 1+labelCount G*expWidth G ≤ (profile G).delta := by
+ simpa only [ht, hz, hd] using cut
+
+/-- Transport a physical exterior cut assignment to the model using the equalities of chain
+heights and cut widths. -/
+abbrev modelExterior (hh : h = (profile G).h) (hd : Δ = (profile G).delta)
+ (ξ : Exterior (profile G).h (profile G).delta) : Exterior h Δ :=
+ cast (congrArg₂ Exterior hh hd).symm ξ
+
+/-- Transport all model dimensions simultaneously, preserving the native index,
+input memory and selected physical nomination. -/
+theorem compressedObligation_of_inputExecution
+ (native : ∀ I : CompressedInput W P (cast (congrArg Bits ha) advice) (physicalFit hd ht hz cut),
+ let ξ := modelExterior hh hd I.exterior
+ let i := I.i.cast (congrArg (2^·) hh).symm
+ Nonempty (CompressedPaths.Execution G (I.branch.copy.memory ()) (Path ξ i (order I.μ))
+ (fun q j => inc ξ i (order I.μ) q (j.cast ht.symm)) S H)) :
+ compressedObligation W P order hh hd ha ht hz advice cut inc := by
+ subst h; subst Δ; subst a; subst t; subst Z
+ apply compressedCalls_of_execution W P order advice cut inc
+ intro cuts i j mode pad tr out ξ F N μ B
+ exact native ⟨cuts,i,mode,pad,tr,out,μ,B⟩
+
+end LiveProgram.LocalCount
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression CursorNetwork LiveProgram PairStages PairStages.Group LocalCount
+open ExponentTrace CutSchedule ChainAssignments LabelEvaluator PairSimulation
+
+universe v
+variable {D : FixedProgramDiagonal.Program} {n C : ℕ}
+ {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+ {K : Type v} [Field K] {S : BlockSchedule K} {B : S.Templates} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M)
+ (processorFit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C)
+
+variable (W : Conditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (P : PairStageConditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (cut : 1+B.denseCount n C * D.counterWidth n ≤ n^D.constants.deltaPower)
+
+private theorem width_eq : D.counterWidth n = expWidth (D.executionGroup n ht hf) := by
+ unfold expWidth executionGroup Constants.Z Constants.height
+ rw [eval_mul,PublicExpr.eval_natPow]
+ rfl
+
+/-- One checked physical branch for the fixed program's model. -/
+abbrev VirtualPairs.PhysicalInput := CompressedInput W P
+ (cast (congrArg Bits (adviceSizes (D := D) (n := n) (ht := ht) (hf := hf))) data.advice)
+ (physicalFit deltas (physicalPairLabelCount hC hg).symm width_eq cut)
+
+variable (I : VirtualPairs.PhysicalInput data W P hC hg cut)
+
+/-- Express the selected physical first-half index in the fixed model's index type using the
+equality of chain heights. -/
+noncomputable abbrev VirtualPairs.modelIndex := I.i.cast (congrArg (2^·) (heights (D := D) (n := n) (ht := ht) (hf := hf))).symm
+
+/-- First-half exterior cut data of the selected physical input, transported to the fixed
+program's model dimensions. -/
+noncomputable abbrev VirtualPairs.exterior := modelExterior heights deltas I.exterior
+
+private theorem headers_cast {h Δ a h' Δ' a' : ℕ} (hh : h=h') (hd : Δ=Δ') (ha : a=a')
+ (advice : Bits a) (ξ : Exterior h' Δ') (i : Fin (2^h'))
+ (lengths : PairedChain.lengths h' Δ' a' i = PairedChain.lengths h Δ a (i.cast (congrArg (2^·) hh).symm)) :
+ (lengths.symm ▸ PairedChain.headers advice (cast (congrArg₂ Exterior hh hd).symm ξ)
+ (i.cast (congrArg (2^·) hh).symm)) = PairedChain.headers (cast (congrArg Bits ha) advice) ξ i := by
+ subst h'; subst Δ'; subst a'
+ rfl
+
+/-- The compressed call reads the canonical virtual pair's own reset memory at
+each address in this actual physical input's shadow. -/
+theorem VirtualPairs.input_shadow (a : ℕ) :
+ I.branch.copy.memory () ((Auxiliary.shadow (D.executionGroup n ht hf)).val+a) =
+ (V.data data.advice (VirtualPairs.exterior data W P hC hg cut I)
+ (VirtualPairs.modelIndex data W P hC hg cut I) (physicalNomination hC I.μ)).initial a := by
+ let i := VirtualPairs.modelIndex data W P hC hg cut I
+ let ξ := VirtualPairs.exterior data W P hC hg cut I
+ have h := V.shadow_initial (ht := ht) (hf := hf) hC data.advice ξ i I.μ
+ (m := memory I.trace)
+ (N := Nominations.indexed (D.executionGroup n ht hf) I.nominationFits (memory I.trace) I.trace.tag)
+ have eq := headers_cast heights deltas adviceSizes data.advice I.exterior I.i (physicalPairLengths i)
+ let hdr : PrimedInputRAM.Header (D.pairLengths i) → Bool := PairedChain.headers data.advice ξ i
+ change ((physicalPairLengths (ht := ht) (hf := hf) i).symm ▸ hdr) =
+ PairedChain.headers (cast (congrArg Bits adviceSizes) data.advice) I.exterior I.i at eq
+ rw [eq] at h
+ exact h I.branch a
+
+/-- Native schedule facts on this particular canonical monomial witness.
+The expected motif flushes start with the actual memory of the copy stage. -/
+noncomputable abbrev VirtualPairs.nativeRuns :=
+ let ξ := VirtualPairs.exterior data W P hC hg cut I
+ let i := VirtualPairs.modelIndex data W P hC hg cut I
+ let μ := physicalNomination hC I.μ
+ let X := (V.pairData data processorFit).Path ξ i μ
+ CompressedPaths.SourceRuns (D.executionGroup n ht hf) (I.branch.copy.memory ()) X (fun q =>
+ Counters.visit (Auxiliary.counterBase (D.executionGroup n ht hf)) (Auxiliary.histLength (D.executionGroup n ht hf))
+ (fun (v : B.Entry → ℕ) k => v (physicalMotifOrder hg k)) (V.histograms data processorFit ξ i μ q)
+ (I.branch.copy.memory ())) (2^(D.geometry n).d) (D.geometry n).H
+
+set_option maxHeartbeats 1200000 in
+/-- Actual source tapes, their costs and their histogram writes give the canonical
+occurrences and increments expected by the compressed stage's linker. -/
+noncomputable def VirtualPairs.nativeExecution (U : V.nativeRuns data processorFit W P hC hg cut I) :
+ let ξ := VirtualPairs.exterior data W P hC hg cut I
+ let i := VirtualPairs.modelIndex data W P hC hg cut I
+ let μ := physicalNomination hC I.μ
+ CompressedPaths.Execution (D.executionGroup n ht hf) (I.branch.copy.memory ()) ((V.pairData data processorFit).Path ξ i μ)
+ (fun q j => increments data processorFit V ξ i μ q (j.cast (physicalPairLabelCount hC hg)))
+ (2^(D.geometry n).d) (D.geometry n).H :=
+ U.execution _ (fun q j => V.counterVisits_readback data processorFit (VirtualPairs.exterior data W P hC hg cut I)
+ (VirtualPairs.modelIndex data W P hC hg cut I) hC hg I.μ I.out
+ I.nominationFits I.trace.tag I.branch I.shadowFit q (j.cast (physicalPairLabelCount hC hg)))
+
+/-- Source executions at all valid prepared groups supply the complete first-half
+compressed-call obligation, with the model's exact occurrence type and field exponents. -/
+theorem VirtualPairs.compressedCalls_of_nativeRuns
+ (native : ∀ I : VirtualPairs.PhysicalInput data W P hC hg cut,
+ Nonempty (V.nativeRuns data processorFit W P hC hg cut I)) :
+ V.compressedCalls data processorFit W P hC hg cut := by
+ classical
+ apply compressedObligation_of_inputExecution
+ intro I
+ exact ⟨V.nativeExecution data processorFit W P hC hg cut I (native I).some⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairOrdinalData.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairOrdinalData.lean
new file mode 100644
index 0000000000..08eeaed5f2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairOrdinalData.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.PairSimulationNominationData
+import OAI.Computability.VPVNP.LiveVirtualPairs
+
+/-! # The actual virtual pair witness as descriptor, arc and DFS streams -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM BurstRAM.PrivateRAM
+open PairSimulation PairSimulation.LocalHistory NetworkKernel LiveProgram CutSchedule ExponentTrace
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+universe v
+variable {K : Type v} [Field K] {S : BlockSchedule K} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M)
+ (processorFit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C)
+ [NeZero (virtualBits D.addressFactor n)]
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n) (μ : D.pairNom n C)
+
+attribute [local irreducible] NominationClock
+
+/-- Initial padded cursor-network state for the virtual RAM scan, with its reserved lane
+labeling and wire widths determined by the virtual bucket and RAM word sizes. -/
+noncomputable abbrev VirtualPairs.scanState := scanInput (laneLabels _ _ V.lanes) V.dimension S (roundedUp 1 4 n) (CursorBounds.wordBits D.addressFactor n)
+/-- Compression execution on the virtual cursor state using the fixed model's label values and
+the chosen number of schedule blocks. -/
+noncomputable abbrev VirtualPairs.selection := B.execute (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl (V.scanState)
+
+variable (t : ℕ) (clock : NominationClock (d := virtualBits D.addressFactor n) (e := roundedUp 1 4 n) (Q := V.layout i) (V.data data.advice ξ i μ) V.cap.tags V.cap.capFits t)
+ {pp rr kk : ℕ} (N : Machine (CursorBounds.wordBits D.addressFactor n) pp rr kk) (pc : Fin 10 → Fin pp) (reg : Fin 2 ↪ Fin rr)
+ (base : Fin kk) (done : Fin pp) (hl : FinalBits.Linked N pc reg base done) (he : N.entry=pc 0)
+ (low : ℕ) (pub : N.publicData base=FinalBits.cursor (CursorBounds.wordBits D.addressFactor n) low 0) (extra : ℕ)
+ (memory : (V.selection (M := M)).Choices → Memory (CursorBounds.wordBits D.addressFactor n))
+ (fit : ∀ z, low+((V.selection (M := M)).finalState z).totalWidth < 2^(CursorBounds.wordBits D.addressFactor n))
+ (inputs : WorkerInputs (V.selection (M := M))
+ (CompressorRecords.executeOrigins B (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl (V.scanState))
+ (CursorBounds.wordBits D.addressFactor n))
+
+/-- All streams refer to the actual grammar coefficient machine and its
+exact private fuel, reset state and initialized nomination header. -/
+noncomputable abbrev VirtualPairs.phaseTrace : TraceEncoding ((V.pairData data processorFit).Path ξ i μ) :=
+ nominationTrace (d := virtualBits D.addressFactor n) (e := roundedUp 1 4 n) (Q := V.layout i)
+ (V.data data.advice ξ i μ) V.cap.tags V.cap.capFits (laneLabels _ _ V.lanes) V.dimension t clock
+ B (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl
+ N pc reg base done hl he low pub extra memory fit
+
+/-- Replace the semantic selector codes of the virtual occurrence by the corresponding worker
+tapes for each motif while retaining its arc and vertex choices. -/
+noncomputable abbrev VirtualPairs.phaseEmission :
+ SelectorReindex (V.phaseTrace data processorFit ξ i μ t clock N pc reg base done hl he low pub extra memory fit) :=
+ nominationReindex (d := virtualBits D.addressFactor n) (e := roundedUp 1 4 n) (Q := V.layout i)
+ (V.data data.advice ξ i μ) V.cap.tags V.cap.capFits (laneLabels _ _ V.lanes) V.dimension t clock
+ B (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl
+ N pc reg base done hl he low pub extra memory fit inputs
+
+/-- The chosen virtual branch determines both the terminal graph and the
+specific entry memory used by its physical final-arc scan. -/
+noncomputable abbrev VirtualPairs.finalData (z : (V.selection (M := M)).Choices) :=
+ NominationData (d := virtualBits D.addressFactor n) (e := roundedUp 1 4 n) (Q := V.layout i)
+ (V.data data.advice ξ i μ) V.cap.tags V.cap.capFits (laneLabels _ _ V.lanes) V.dimension t clock
+ B (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl
+ N pc reg base done hl he low pub extra memory fit z
+
+/-- The descriptor branch and all terminal choices classify the same
+monomial occurrence as the canonical `VirtualPairs.witness`. -/
+noncomputable def VirtualPairs.phaseDataEquiv :
+ ((z : (V.selection (M := M)).Choices) × V.finalData data ξ i μ t clock N pc reg base done hl he low pub extra memory fit z) ≃
+ Set.range (V.phaseEmission data processorFit ξ i μ t clock N pc reg base done hl he low pub extra memory fit inputs).emit :=
+ nominationDataEquiv (d := virtualBits D.addressFactor n) (e := roundedUp 1 4 n) (Q := V.layout i)
+ (V.data data.advice ξ i μ) V.cap.tags V.cap.capFits (laneLabels _ _ V.lanes) V.dimension t clock
+ B (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl
+ N pc reg base done hl he low pub extra memory fit inputs
+
+/-- Decode an actual descriptor and final-vertex datum to its precise
+algebraic occurrence in the fixed model. -/
+noncomputable def VirtualPairs.choiceDataEquiv :
+ ((z : (V.selection (M := M)).Choices) × V.finalData data ξ i μ t clock N pc reg base done hl he low pub extra memory fit z) ≃
+ (V.pairData data processorFit).Path ξ i μ :=
+ (V.phaseDataEquiv data processorFit ξ i μ t clock N pc reg base done hl he low pub extra memory fit inputs).trans
+ (V.phaseEmission data processorFit ξ i μ t clock N pc reg base done hl he low pub extra memory fit inputs).decode
+
+set_option maxHeartbeats 1500000 in
+/-- The chosen ordinal tapes, shared-arc calls and site jobs are those of
+the same decoded `V.pairData` occurrence. Their increment sums equal its
+canonical compressor histogram in every coordinate. -/
+theorem VirtualPairs.choiceData_jobs (z : (V.selection (M := M)).Choices)
+ (x : V.finalData data ξ i μ t clock N pc reg base done hl he low pub extra memory fit z) :
+ let E := V.selection (M := M)
+ let X := V.scanState
+ let Y := E.finalState z
+ let c := E.termChain (B.records (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl X) z
+ let r := selectedParsers B (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl X z
+ let P := nominationSites (V.data data.advice ξ i μ) V.cap.tags V.cap.capFits (laneLabels _ _ V.lanes) V.dimension
+ (Nat.add_sub_of_le S.degree_bounds.1) (B.compressorValues hn M) t clock
+ let p := V.phaseDataEquiv data processorFit ξ i μ t clock N pc reg base done hl he low pub extra memory fit inputs ⟨z,x⟩
+ let q := V.choiceDataEquiv data processorFit ξ i μ t clock N pc reg base done hl he low pub extra memory fit inputs ⟨z,x⟩
+ p.val.termCalls = ordinalTapes E (CompressorRecords.executeOrigins B (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl X) inputs z ∧ p.val.arcCalls = x.arcs.val ∧
+ ∀ (ptr : RowPointers c) (leaves : X.network.Site → ℕ × ℕ),
+ let jobs := vertexJobs c r ptr P leaves
+ p.val.vertices = List.ofFn (fun j => (x.jobs jobs ((siteOrder Y).entries j)).flatMap VertexJob.bits) ∧
+ ∀ l, (V.pairData data processorFit).ν ξ i μ q l = ∑ v, ((x.jobs jobs v).map (fun j => j.increment l)).sum :=
+ nominationData_jobs (d := virtualBits D.addressFactor n) (e := roundedUp 1 4 n) (Q := V.layout i)
+ (V.data data.advice ξ i μ) V.cap.tags V.cap.capFits (laneLabels _ _ V.lanes) V.dimension t clock
+ B (B.compressorValues hn M) (B.compressorValues_solution hn M) (blockCount (u.θ : ℝ) n) le_rfl
+ N pc reg base done hl he low pub extra memory fit inputs z x
+
+/-- The terminal site clock is chosen before the nomination and auxiliary
+header. Every selected canonical counter then meets its clock bound. -/
+theorem eventually_virtualNominationClock (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (C : ℕ) :
+ ∀ᶠ n : ℕ in Filter.atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C)
+ [NeZero (virtualBits D.addressFactor n)] (adv : Bits (n^D.constants.advicePower))
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n) (μ : D.pairNom n C),
+ NominationClock (V.data adv ξ i μ) V.cap.tags V.cap.capFits (n^39) := by
+ filter_upwards [eventually_nominationClock] with n all hn V inst adv ξ i μ
+ apply all _ _ _ V.cap _ _ _ _ (V.layout i) (V.data adv ξ i μ)
+ have h := (V.counts i (PairedChain.headers adv ξ i) μ).privateWork
+ change 6*(V.data adv ξ i μ).fuel ≤ n^10 at h
+ exact (Nat.le_mul_of_pos_left _ (by decide : 0 < 6)).trans h
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairPaperDescriptor.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairPaperDescriptor.lean
new file mode 100644
index 0000000000..212552d09b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairPaperDescriptor.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.LiveVirtualPairDescriptorExecution
+import OAI.Computability.VPVNP.CompressorCompiledResident
+import OAI.Computability.VPVNP.LiveCompressedPairDescriptorPaths
+import OAI.Computability.VPVNP.LiveCompressedPairPaperStartup
+
+/-! # The descriptor path of the fixed physical compressed pair
+
+The four cursor visits and the selected block visits are consecutive
+segments of the same RAM program. The selected terms retain the readback
+data for their terminal vertices. The path equivalence below uses the same
+choice, memory and report sequence as the chronological probe bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds BurstRAM LiveProgram LiveProgram.CompressedPair
+open CompressorRecords ScheduledTrace DescriptorSpace
+open scoped Fin.CommRing
+open PairSimulation PairSimulation.LocalHistory PairSimulation.TraversalRows PairSimulation.TraversalRoles
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {u : PairExponents B.growthConstant}
+ {D : FixedProgramDiagonal.Program} {C n : ℕ} {hn : 2 ≤ n} (V : D.VirtualPairs B u hn C)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry)
+ (base clk rate : ℕ) (pub : Fin 11 → Word (wordBits D.addressFactor n)) (m : Memory (wordBits D.addressFactor n))
+
+local notation "addr" => D.addressFactor
+local notation "ww" => wordBits D.addressFactor n
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "l" => reservedLanes B u n
+local notation "b" => virtualBits D.addressFactor n - reservedLanes B u n
+local notation "A" => BlockProgram.script B
+local notation "P" => initialPositions D.addressFactor n
+local notation "X" => VirtualPairs.scanState V
+local notation "E" => B.execute f hf T le_rfl (VirtualPairs.scanState V)
+local notation "small" => BlockClock.small B D.addressFactor n
+local notation "cap" => sourceCap pub clk
+local notation "L" => BlockProgram.layout B base P T
+local notation "boot" => paperBootstrap B u
+set_option quotPrecheck false in
+local notation "entry" => after m (eventLog (cursorStartupLogs boot pub addr n base m (A).initial.length (A).block.length (A).size))
+local notation "data" => CompiledResident.payload (w := ww) B f hf base P T n
+local notation "res" => V.nativeResident f hf base data
+set_option quotPrecheck false in
+local notation "lastStage" => TerminalProgram.table (BlockProgram.layout B base P T).shape B.recordLimit (paperSegments B u c labels)
+
+attribute [local irreducible] BlockProgram.script BlockProgram.layout CursorNetwork.cursorState
+ CompressedPair.stages CompressedPair.regs TerminalProgram.workers
+
+/-- A descriptor has a startup proof, a physical cursor interval, and a
+scheduled result whose input memory is the output of that interval. -/
+structure DescriptorData (Startup : Prop) (Cursor : Type*) (cost : Cursor → Prop)
+ (clockSlack clockValue : Prop) (Run : Cursor → Type*) where
+ init : Startup
+ /-- The four chronological cursor visits preceding the first compressor pass. -/
+ cursor : Cursor
+ cursorCost : cost cursor
+ slack : clockSlack
+ clock : clockValue
+ /-- The complete selected execution starting on the final cursor memory. -/
+ result : Run cursor
+
+/-- The actual selected calendar on the dynamic directory of this physical group. -/
+abbrev VirtualPairs.PaperDescriptor :=
+ DescriptorData (StartupResult boot (A).plan lastStage pub addr n base m clk)
+ (InitialInterval B base P T cap small b l (initialWidth addr n) pub entry)
+ (fun cursor => RAMBuckets.cost Report.probes cursor.interval.source.logs ≤ initialRate B*(P+1))
+ (small+3 ≤ cap) (cap+24 = clockAt pub clk CompressedPair.Stage.online)
+ (fun cursor => ScheduledTrace.Result res pub (levelWords L : Word ww) (directoryRows L) cap small
+ (T*(S.steps+1)*rate+4) E (executeOrigins B f hf T le_rfl X) _
+ (nativeReaders (B := B) (f := f) (hf := hf) le_rfl X) []
+ cursor.interval.segment.state cursor.interval.segment.memory)
+
+/-- Compile the chosen physical stages at the packed layout. Its shape differs
+from the template's allocation shape only in the runtime directory sizes. -/
+theorem VirtualPairs.paperDescriptor_of_runs
+ (hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0))
+ (start : InitialLive B f hf (blockRatio u).num (blockRatio u).den addr n base clk
+ (paperTerminal B u c labels) pub m hd)
+ (control : Schedule.Online.Run.ControlBounds (A).plan small (w := ww))
+ (sizes : PrefixLevelScale.Within P n E)
+ (passes : LocatedRuns res pub (levelWords L : Word ww) (directoryRows L) cap small rate T P n) :
+ Nonempty (V.PaperDescriptor f hf c labels base clk rate pub m) := by
+ have active : InitialLive B f hf (blockRatio u).num (blockRatio u).den addr n base clk lastStage pub m hd := by
+ rw [paper_terminal_rows]
+ exact start
+ obtain ⟨init,cursor,cost,slack,clock,⟨out⟩⟩ :=
+ V.descriptor_execution f hf base clk rate lastStage pub m hd active data control sizes passes
+ refine ⟨⟨init,cursor,cost,slack,clock,?_⟩⟩
+ exact cursor.interval.state.symm ▸ out
+
+variable {V f hf c labels base clk rate pub m}
+variable (Y : VirtualPairs.PaperDescriptor V f hf c labels base clk rate pub m)
+
+/-- Every descriptor term sequence is one genuine online path on the post-startup RAM. -/
+abbrev VirtualPairs.PaperDescriptor.paths : (E).Choices ≃
+ StagePaths boot (A).plan lastStage pub clk CompressedPair.Stage.online entry :=
+ DescriptorPaths.paths Y.cursor.interval Y.result boot lastStage clk Y.clock Y.slack
+
+theorem VirtualPairs.PaperDescriptor.post (z : (E).Choices) :
+ onlinePost (Y.paths z) = writeMemory (Y.result.trace.cut.part z).memory (PairTag.address pub)
+ (LiveStageLink.tagWord ww CompressedPair.Stage.terminal) :=
+ DescriptorPaths.paths_post Y.cursor.interval Y.result boot lastStage clk Y.clock Y.slack z
+
+/-- Online source-frame proof for reachable prefixes on the physical program. -/
+def VirtualPairs.PaperDescriptor.protectedOnline (below : (PairTag.address pub).val < (pub 2).val+6) :
+ Protected boot (A).plan lastStage pub clk CompressedPair.Stage.online entry :=
+ DescriptorPaths.protectedStage Y.cursor.interval Y.result boot lastStage clk Y.clock below
+
+theorem VirtualPairs.PaperDescriptor.online_word (below : (PairTag.address pub).val < (pub 2).val+6)
+ (x : ℕ) (low : x < (pub 2).val+6) : (Y.protectedOnline below).word x :=
+ DescriptorPaths.protectedStage_word Y.cursor.interval Y.result boot lastStage clk Y.clock below x low
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairPaperTerminal.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairPaperTerminal.lean
new file mode 100644
index 0000000000..1b458bbe3a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairPaperTerminal.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.LiveVirtualPairPaperDescriptor
+import OAI.Computability.VPVNP.LiveVirtualPairNativeAssembly
+import OAI.Computability.VPVNP.LiveTerminalReachableFrame
+
+/-! # The fixed pair's terminal execution on the selected descriptor
+
+Every selected branch runs against the post-memory of the actual online
+calendar. The terminal block must account for the sparse counter readback,
+the path caps, and preservation of both the pair tag and the live header
+even on branches whose next vertex rejects.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM LiveProgram LocalCount
+open PairStages PairStages.Group PairStages.Group.CompressedPaths CompressedPair
+open PairSimulation PairSimulation.LocalHistory NetworkKernel CompressorRecords CompressorRecords.Schedule
+
+set_option quotPrecheck false
+open scoped Fin.CommRing
+
+attribute [local irreducible] CompressedPair.stages CompressedPair.regs CompressedPair.components TerminalProgram.workers
+
+variable {D : FixedProgramDiagonal.Program} {n C : ℕ} {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+ {K : Type} [Field K] {S : BlockSchedule K} {B : S.Templates} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M) (fit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C) [NeZero (virtualBits D.addressFactor n)]
+
+local notation "grp" => D.executionGroup n ht hf
+variable (W : Conditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (P : PairStageConditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (cut : 1+B.denseCount n C*D.counterWidth n ≤ n^D.constants.deltaPower)
+ (I : VirtualPairs.PhysicalInput data W P hC hg cut)
+local notation "ext" => VirtualPairs.exterior data W P hC hg cut I
+local notation "idx" => VirtualPairs.modelIndex data W P hC hg cut I
+local notation "nom" => physicalNomination hC I.μ
+local notation "mem" => I.branch.copy.memory ()
+local notation "sel" => V.selection (M := M)
+local notation "ws" => PublicExpr.eval (D.geometry n) (Layout.pairWorkspace D.constants)
+local notation "ports" => publicWords grp
+local notation "clk" => fuel grp
+
+variable (A : CanonicalScan data V (VirtualPairs.exterior data W P hC hg cut I)
+ (VirtualPairs.modelIndex data W P hC hg cut I) (physicalNomination hC I.μ))
+local notation "f" => B.compressorValues hn M
+local notation "hf₀" => B.compressorValues_solution hn M
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "positions" => initialPositions D.addressFactor n
+local notation "L" => BlockProgram.layout B ws positions T
+local notation "boot" => paperBootstrap B u
+local notation "script" => BlockProgram.script B
+local notation "parts" => paperSegments B u D.constants hg
+local notation "lastStage" => TerminalProgram.table (L).shape B.recordLimit parts
+local notation "termProgram" => original boot (script).plan lastStage ports CompressedPair.Stage.terminal
+local notation "termClock" => clockAt ports clk CompressedPair.Stage.terminal
+
+variable (rate : ℕ)
+variable (Y : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M) D.constants hg
+ ((Layout.pairWorkspace D.constants).eval (D.geometry n)) (fuel (D.executionGroup n ht hf)) rate
+ (publicWords (D.executionGroup n ht hf)) (I.branch.copy.memory ()))
+
+/-- Five-block witnesses and the four physical assertions required of their
+native traces. Each component type is specialized to the selected descriptor. -/
+structure TerminalEvidence (Branches Pointers Leaves : Type*) (Tag Header : Prop)
+ (Deposits : Branches → Pointers → Leaves → Prop) (Caps : Branches → Prop) where
+ /-- The complete five-stage execution on each selected descriptor branch. -/
+ branches : Branches
+ /-- Addresses of the compressed placement tree at each visited level. -/
+ ptr : Pointers
+ /-- Addresses of the cursor vertices at the input level. -/
+ leaf : Leaves
+ tag : Tag
+ header : Header
+ deposits : Deposits branches ptr leaf
+ caps : Caps branches
+
+/-- The native five-block witness for the actual selected calendar, together
+with its site jobs and physical readbacks. -/
+abbrev VirtualPairs.PaperTerminal :=
+ TerminalEvidence
+ (∀ z : (sel).Choices, TerminalBranch (b := boot) (plan := (script).plan)
+ (shape := (L).shape) (limit := B.recordLimit) (segments := parts) (G := grp)
+ (B := D.addressFactor) (n := n) (base := ws) (m := mem) Y.paths (A.arc z) (A.sites z) z)
+ (∀ z : (sel).Choices, RowPointers (selectedChain (V := V) (M := M) z))
+ ((V.scanState).network.Site → ℕ × ℕ)
+ (∀ z, PreservesCell termProgram termClock 0 (onlinePost (Y.paths z)) (PairTag.address ports).val)
+ (∀ z a, a < Auxiliary.tableBase grp → PreservesCell termProgram termClock 0 (onlinePost (Y.paths z)) a)
+ (fun branches ptr leaf => ∀ z (x : TerminalData (A.arc z) (A.sites z)) (j : Fin (labelCount grp)),
+ ((branches z).vertexPaths x.arcs x.choices).val.memory (Auxiliary.counterBase grp+j.val) =
+ (Counters.visit (Auxiliary.counterBase grp) (Auxiliary.histLength grp)
+ (fun v k => A.siteTotals z x (ptr z) leaf v (physicalMotifOrder hg k))
+ (List.ofFn (siteOrder ((sel).finalState z)).entries) mem) (Auxiliary.counterBase grp+j.val))
+ (fun branches => ∀ z (x : TerminalData (A.arc z) (A.sites z)),
+ let rs := branchReports Y.paths branches z x
+ (∀ r ∈ rs, r.events.length+4 ≤ clk) ∧ 4*RAMBuckets.cost Report.probes rs ≤ 2^(D.geometry n).d*(D.geometry n).H ∧
+ ∀ r ∈ rs, 3+r.probes ≤ (D.geometry n).H)
+
+set_option maxHeartbeats 1200000 in
+/-- The concrete descriptor result and its selected native terminal blocks
+supply every premise of the prepared pair's execution certificate. -/
+noncomputable def VirtualPairs.nativeRunsOfPaperTerminal
+ (fixed : D.pair = paperTable B u D.constants hg)
+ (workspace : ws < 2^(D.geometry n).w)
+ (setup : TransferredStartup.Runs (bootstrapRows boot (script).initial.length (script).block.length) (script).size
+ (startupLayout boot (script).initial.length (script).block.length D.addressFactor n ws)
+ D.addressFactor n (S.degreeExponent 0) S.laneBits S.steps ports (PairTag.address ports) mem)
+ (Q : V.PaperTerminal data W P hC hg cut I A rate Y) : V.nativeRuns data fit W P hC hg cut I := by
+ have base : (ports 2).val = ws := Nat.mod_eq_of_lt workspace
+ have lt := tag_before_workspace D.constants (D.geometry n)
+ have tag : (PairTag.address ports).val < ws := by
+ rw [tag_address]
+ change (Layout.oldState D.constants).eval (D.geometry n) % 2^(D.geometry n).w < ws
+ rw [Nat.mod_eq_of_lt (lt.trans workspace)]
+ exact lt
+ have below : (PairTag.address ports).val < (ports 2).val+6 := by rw [base]; omega
+ have space (a : ℕ) (ha : a < Auxiliary.tableBase grp) : a < (ports 2).val+6 := by
+ have upper := (Auxiliary.geometry_order grp).2.2.1
+ have old : Auxiliary.tableBase grp ≤ (Layout.oldState D.constants).eval (D.geometry n) := by
+ change Auxiliary.tableBase grp ≤ Auxiliary.counterBase grp + D.constants.labels.eval (D.geometry n)
+ omega
+ rw [base]
+ omega
+ let tagFrame (p : StagePaths boot (script).plan lastStage ports clk CompressedPair.Stage.online
+ (after mem (eventLog (cursorStartupLogs boot ports D.addressFactor n ws mem (script).initial.length
+ (script).block.length (script).size)))) :=
+ Protected.ofPreservesCell (b := boot) (plan := (script).plan) (last := lastStage) (pub := ports)
+ (clock := clk) (s := CompressedPair.Stage.terminal) (m := onlinePost p) (by
+ obtain ⟨z,rfl⟩ := Y.paths.surjective p
+ exact Q.tag z)
+ let physical : PhysicalStages boot (script).plan lastStage grp D.addressFactor n ws mem :=
+ { body := by change D.pair = _; rw [fixed,paper_terminal_rows]; rfl
+ enough := by
+ have enough := terminal_clock_fits grp W.clock
+ unfold CompressedPair.clockAt at enough
+ omega
+ init := Y.init
+ onlineFrame := Y.protectedOnline below
+ terminalFrame := tagFrame }
+ apply V.nativeRunsOfTerminal data fit W P hC hg cut I A physical Y.paths Q.branches setup workspace
+ (fun a ha => Y.online_word below a (space a ha)) _ Q.ptr Q.leaf Q.deposits Q.caps
+ intro a ha p
+ obtain ⟨z,rfl⟩ := Y.paths.surjective p
+ exact Protected.ofPreservesCell_word (Q.tag z) (Q.header z a ha)
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairPreludeCharge.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairPreludeCharge.lean
new file mode 100644
index 0000000000..fb976b8c70
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairPreludeCharge.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PairTerminalSelectedStartCharges
+import OAI.Computability.VPVNP.LiveVirtualPairPaperDescriptor
+import OAI.Computability.VPVNP.LiveVirtualPairPreludeRoom
+
+/-! # Forced terminal charges on the selected finite-model descriptor -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorBounds CursorNetwork BurstRAM LiveProgram CompressedPair
+open PairStages.Group.CompressedPaths LabelEvaluator CompressorRecords ScheduledTrace DescriptorSpace
+open PairSimulation LocalHistory TerminalLink TraversalRows TraversalRoles TerminalPrefix Filter
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {u : PairExponents B.growthConstant}
+ {D : FixedProgramDiagonal.Program} {C n : ℕ} {hn : 2 ≤ n} (V : D.VirtualPairs B u hn C)
+ {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f}
+ {c : Constants} {labels : c.motifLabels = Fintype.card B.Entry}
+ {base clk rate : ℕ} {pub : Fin 11 → Word (wordBits D.addressFactor n)} {m : Memory (wordBits D.addressFactor n)}
+
+local notation "addr" => D.addressFactor
+local notation "ww" => wordBits D.addressFactor n
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "P" => initialPositions D.addressFactor n
+local notation "l" => reservedLanes B u n
+local notation "baseBits" => virtualBits D.addressFactor n - reservedLanes B u n
+local notation "E" => B.execute f hf T le_rfl V.scanState
+local notation "L" => BlockProgram.layout B base P T
+local notation "bound" => TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit + 1
+local notation "parts" => paperSegments B u c labels
+local notation "termClock" => clockAt pub clk CompressedPair.Stage.terminal
+
+attribute [local irreducible] BlockProgram.script CursorNetwork.cursorState TerminalProgram.workers
+ CompressedPair.stages CompressedPair.regs
+
+/-- Extract the full terminal prelude charge from the compiled payload and
+the physical RAM at the exit of this descriptor. -/
+private theorem prelude_of_room
+ (desc : V.PaperDescriptor f hf c labels base clk rate pub m)
+ (z : (E).Choices) (trace : FiveTrace (TerminalProgram.workers (L).shape B.recordLimit parts)
+ pub termClock (onlinePost (desc.paths z)))
+ (baseWord : (pub 2).val = base) (tag : (PairTag.address pub).val < (pub 2).val+6)
+ (exp : (pub 7).val = addressBits addr n) :
+ let r := addressBits addr n
+ let Y := (E).finalState z
+ let ls := selectedLayers B f hf T le_rfl V.scanState z
+ let tags := selected B f hf T le_rfl V.scanState z
+ r < ww → 32 ≤ (L).base+2^r*2^r → (L).base+2^r*2^r ≤ 2^ww →
+ endAddress L + 2*words B.recordLimit ls + Y.totalWidth ≤ TerminalBootstrap.address (L).base r →
+ 2*tags.length*(V.scanState.positions+1) < 2^ww →
+ arcCount Y ≤ slotCapacity L → arcCount Y ≤ tableWords L → Y.totalWidth < 2^ww →
+ TerminalBootstrap.cost (L).shape B.recordLimit+1+30 ≤ termClock → 60 ≤ termClock →
+ TraversalController.callFuel B.recordLimit+30 ≤ termClock →
+ Nonempty (PreludeCosts V.scanState Y pub trace S.steps B.recordLimit T bound) := by
+ subst base
+ intro r Y ls tags hr reserve room below ord slots cells totalFit clock₀ clock₁ clock₂
+ let payload := CompiledResident.payload (w := ww) B f hf ((pub 2).val : Word ww) P T n
+ have handoff := Linked.handoff_of_transfer pub (desc.post z) tag
+ exact TerminalProgram.packed_prefix_costs B f hf T le_rfl V.scanState z P (baseBits) l (initialWidth addr n) n pub
+ payload parts r termClock (desc.result.trace.cut.part z).memory (onlinePost (desc.paths z))
+ (desc.result.final z) handoff exp hr reserve room below ord slots cells totalFit clock₀ clock₁ clock₂ trace
+
+set_option exponentiation.threshold 10000 in
+/-- The actual finite model, source calendar, and accepted terminal trace all
+come after the length threshold. The bootstrap bound is the one charged by
+the fixed branch clock. -/
+theorem eventually_paperDescriptorPrelude (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (C : ℕ) (hb : max S.laneBits 5 ≤ D.addressFactor)
+ (num : D.numerator = (liveRatio u).num) (den : D.denominator = (liveRatio u).den)
+ (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C)
+ (ht : 21 ≤ 2^(D.geometry n).w) (hc : 44 ≤ n^10000) {p : Nat.Primes}
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn C)),
+ let G := D.executionGroup n ht hc
+ let pub := publicWords G
+ let clk := fuel G
+ let base := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ let alloc := BlockProgram.layout B base (initialPositions D.addressFactor n) (blockCount (u.θ : ℝ) n)
+ let bank := TerminalProgram.workers alloc.shape B.recordLimit (paperSegments B u c labels)
+ ∀ (rate : ℕ) (m : Memory (wordBits D.addressFactor n))
+ (desc : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M)
+ c labels base clk rate pub m) (z : (V.selection (M := M)).Choices)
+ (trace : FiveTrace bank pub (clockAt pub clk CompressedPair.Stage.terminal) (onlinePost (desc.paths z))),
+ Nonempty (PreludeCosts V.scanState ((V.selection (M := M)).finalState z) pub trace S.steps B.recordLimit
+ (blockCount (u.θ : ℝ) n) (TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit+1)) := by
+ filter_upwards [eventually_paperDescriptorRoom D B u C hb num den] with n room
+ intro hn V ht hc p M G pub clk base alloc bank rate m desc z trace
+ have h := room hn V ht hc M z
+ exact prelude_of_room V desc z trace h.workspace h.tag h.exponent h.exponentFit h.reserve h.room h.below
+ h.ordinal h.slots h.cells h.totalFit h.bootClock h.widthClock h.rowClock
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairPreludeRoom.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairPreludeRoom.lean
new file mode 100644
index 0000000000..7b9e496f76
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairPreludeRoom.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.PairTerminalPreludeBudget
+import OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+import OAI.Computability.VPVNP.LiveVirtualPairCursorBoundary
+import OAI.Computability.VPVNP.LiveCompressedPairPaperStartup
+import OAI.Computability.VPVNP.FixedProgramOperandFits
+
+/-! # Public words and room of the selected terminal prelude -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLayout
+
+open BurstRAM LiveProgram CompressorRecords DescriptorSpace
+
+/-- Bounds shared by the actual bootstrap, wire scan and traversal stages
+at one selected branch. The workspace and address exponent are the words
+the program reads. -/
+structure PreludeRoom {w : ℕ} (pub : Fin 11 → Word w) (L : Layout)
+ (r cap limit positions rows tags width arcs : ℕ) : Prop where
+ workspace : (pub 2).val = L.base
+ tag : (PairTag.address pub).val < (pub 2).val+6
+ exponent : (pub 7).val = r
+ exponentFit : r < w
+ reserve : 32 ≤ L.base+2^r*2^r
+ room : L.base+2^r*2^r ≤ 2^w
+ below : endAddress L+2*rows+width ≤ TerminalBootstrap.address L.base r
+ ordinal : 2*tags*(positions+1) < 2^w
+ slots : arcs ≤ slotCapacity L
+ cells : arcs ≤ tableWords L
+ totalFit : width < 2^w
+ bootClock : TerminalBootstrap.cost L.shape limit+1+30 ≤ cap
+ widthClock : 60 ≤ cap
+ rowClock : TraversalController.callFuel limit+30 ≤ cap
+
+end PairSimulation.TerminalLayout
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorBounds CursorNetwork BurstRAM LiveProgram CompressedPair LabelEvaluator CompressorRecords
+open PairStages.Group.CompressedPaths PairSimulation LocalHistory TraversalRows TraversalRoles TerminalPrefix Filter
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K}
+
+set_option exponentiation.threshold 10000 in
+/-- Uniform terminal room on the actual eleven words and finite-model
+selection. All stage witnesses use this same runtime layout and clock. -/
+theorem eventually_paperDescriptorRoom (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (C : ℕ) (hb : max S.laneBits 5 ≤ D.addressFactor)
+ (num : D.numerator = (liveRatio u).num) (den : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C)
+ (ht : 21 ≤ 2^(D.geometry n).w) (hc : 44 ≤ n^10000) {p : Nat.Primes}
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn C)) (z : (V.selection (M := M)).Choices),
+ let G := D.executionGroup n ht hc
+ let pub := publicWords G
+ let κ := B.compressorValues hn M
+ let ok := B.compressorValues_solution hn M
+ let T := blockCount (u.θ : ℝ) n
+ let base := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ let L := BlockProgram.layout B base (initialPositions D.addressFactor n) T
+ let Y := (V.selection (M := M)).finalState z
+ let ls := selectedLayers B κ ok T le_rfl V.scanState z
+ let tags := selected B κ ok T le_rfl V.scanState z
+ TerminalLayout.PreludeRoom pub L (addressBits D.addressFactor n) (clockAt pub (fuel G) Stage.terminal)
+ B.recordLimit V.scanState.positions (words B.recordLimit ls) tags.length Y.totalWidth (arcCount Y) := by
+ let start n := (LiveProgram.Layout.pairWorkspace D.constants).eval (paperGeometry D.addressFactor (liveCapacity u) n)
+ have poly : PolynomiallyBounded start := startup_workspace_polynomial D.constants D.address_pos (liveCapacity_polynomial u)
+ filter_upwards [TerminalLayout.eventually_preludeRoom B u D.addressFactor hb poly,
+ eventually_startup_inputs D.constants D.address_pos (liveCapacity_polynomial u)] with n fits inputs
+ intro hn V ht hc p M z G pub κ ok T base L Y ls tags
+ have geom := paperGeometry_eq D B u num den n
+ obtain ⟨baseWord,_,exp,tag⟩ := inputs G.lit
+ rw [← geom] at baseWord exp tag
+ change (pub 2).val = base at baseWord
+ change (pub 7).val = addressBits D.addressFactor n at exp
+ change (PairTag.address pub).val < (pub 2).val at tag
+ have cut := fits (laneLabels _ _ V.lanes) V.dimension le_rfl M.algebra κ ok
+ dsimp only at cut
+ rw [← V.scanState_pairInput] at cut
+ have positions : V.scanState.positions = initialPositions D.addressFactor n := by
+ rw [V.scanState_pairInput]; exact pairInput_positions S _ _
+ have offset : start n = base := by unfold start; rw [← geom]
+ have bounds := cut z G le_rfl
+ rw [offset] at bounds
+ obtain ⟨hr,reserve,room,below,ord,slots,cells,totalFit,clock₀,clock₁,clock₂⟩ := bounds
+ rw [positions] at reserve room below slots cells clock₀
+ exact ⟨baseWord,tag.trans_le (Nat.le_add_right _ _),exp,hr,reserve,room,below,ord,slots,cells,totalFit,
+ clock₀,clock₁,clock₂⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairQuietFrame.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairQuietFrame.lean
new file mode 100644
index 0000000000..85082e088e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairQuietFrame.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.LiveVirtualPairPreludeCharge
+import OAI.Computability.VPVNP.PairTerminalPackedReplay
+
+/-! # Preserving every low address on the actual terminal setup reports -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorBounds CursorNetwork BurstRAM LiveProgram CompressedPair
+open PairStages.Group.CompressedPaths LabelEvaluator CompressorRecords ScheduledTrace DescriptorSpace
+open PairSimulation LocalHistory TerminalLink TraversalRows TraversalRoles TerminalPrefix Filter
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {u : PairExponents B.growthConstant}
+ {D : FixedProgramDiagonal.Program} {C n : ℕ} {hn : 2 ≤ n} {V : D.VirtualPairs B u hn C}
+ {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f}
+ {c : Constants} {labels : c.motifLabels = Fintype.card B.Entry}
+ {base clk rate : ℕ} {pub : Fin 11 → Word (wordBits D.addressFactor n)} {m : Memory (wordBits D.addressFactor n)}
+
+local notation "ww" => wordBits D.addressFactor n
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "P" => initialPositions D.addressFactor n
+local notation "lanes₀" => reservedLanes B u n
+local notation "base₀" => virtualBits D.addressFactor n-reservedLanes B u n
+local notation "E" => B.execute f hf T le_rfl V.scanState
+local notation "L" => BlockProgram.layout B base P T
+local notation "tab" => (⟨0, by change 0 < 6; decide⟩ : Fin (L).shape.tables)
+local notation "parts" => paperSegments B u c labels
+local notation "bank₀" => TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit parts
+local notation "termClock" => clockAt pub clk CompressedPair.Stage.terminal
+local notation "payload₀" => CompiledResident.payload (w := ww) B f hf (base : Word ww) P T n
+
+/-- Every intermediate report of the quiet prefix preserves each cell
+below the workspace. This applies on the runtime bank and the equal fixed
+bank used by the vertex interpreter. -/
+private theorem frame_of_room
+ (desc : V.PaperDescriptor f hf c labels base clk rate pub m)
+ (z : (E).Choices) :
+ let r := addressBits D.addressFactor n
+ let Y := (E).finalState z
+ let ls := selectedLayers B f hf T le_rfl V.scanState z
+ let tags := selected B f hf T le_rfl V.scanState z
+ let phy := onlinePost (desc.paths z)
+ let Safe (W : TerminalLink.Stage → PairTable) :=
+ ∀ q : QuietPrefix W pub termClock phy, ∀ x < (pub 2).val, ReplayFrame x phy q.reportList
+ TerminalLayout.PreludeRoom pub L r termClock B.recordLimit V.scanState.positions
+ (words B.recordLimit ls) tags.length Y.totalWidth (arcCount Y) →
+ Safe (TerminalProgram.workers (L).shape B.recordLimit parts) ∧ Safe bank₀ := by
+ intro r Y ls tags phy Safe h
+ have baseWord : (pub 2).val = base := h.workspace
+ subst base
+ let payload := CompiledResident.payload (w := ww) B f hf ((pub 2).val : Word ww) P T n
+ have handoff := Linked.handoff_of_transfer pub (desc.post z) h.tag
+ have raw : Safe (TerminalProgram.workers (BlockProgram.layout B (pub 2).val P T).shape B.recordLimit parts) :=
+ TerminalProgram.packed_prefix_frame B f hf T le_rfl V.scanState z P base₀ lanes₀
+ (initialWidth D.addressFactor n) n pub payload parts r termClock (desc.result.trace.cut.part z).memory phy
+ (desc.result.final z) handoff h.exponent h.exponentFit h.reserve h.room h.below h.ordinal h.slots h.cells
+ h.totalFit h.bootClock h.widthClock h.rowClock
+ exact ⟨raw,(congrArg Safe (TerminalLayout.packed_workers B (pub 2).val P T parts)).mp raw⟩
+
+set_option exponentiation.threshold 10000 in
+theorem eventually_paperDescriptorQuietFrame (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (C : ℕ) (hb : max S.laneBits 5 ≤ D.addressFactor)
+ (num : D.numerator = (liveRatio u).num) (den : D.denominator = (liveRatio u).den)
+ (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C)
+ (ht : 21 ≤ 2^(D.geometry n).w) (hc : 44 ≤ n^10000) {p : Nat.Primes}
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn C)),
+ let G := D.executionGroup n ht hc
+ let pub := publicWords G
+ let clk := fuel G
+ let base := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ let alloc := BlockProgram.layout B base (initialPositions D.addressFactor n) (blockCount (u.θ : ℝ) n)
+ let bank (shape : DescriptorSpace.Shape) := TerminalProgram.workers shape B.recordLimit (paperSegments B u c labels)
+ ∀ (rate : ℕ) (m : Memory (wordBits D.addressFactor n))
+ (desc : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M)
+ c labels base clk rate pub m) (z : (V.selection (M := M)).Choices),
+ let phy := onlinePost (desc.paths z)
+ let Safe (W : TerminalLink.Stage → PairTable) :=
+ ∀ q : QuietPrefix W pub (clockAt pub clk CompressedPair.Stage.terminal) phy,
+ ∀ x < (pub 2).val, ReplayFrame x phy q.reportList
+ Safe (bank alloc.shape) ∧ Safe (bank (BlockProgram.allocationShape B)) := by
+ filter_upwards [eventually_paperDescriptorRoom D B u C hb num den] with n room
+ intro hn V ht hc p M G pub clk base alloc bank rate m desc z
+ exact frame_of_room desc z (room hn V ht hc M z)
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairQuietPrelude.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairQuietPrelude.lean
new file mode 100644
index 0000000000..9574bbd480
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairQuietPrelude.lean
@@ -0,0 +1,165 @@
+import OAI.Computability.VPVNP.LiveVirtualPairPreludeCharge
+import OAI.Computability.VPVNP.PairTerminalQuietHandoff
+import OAI.Computability.VPVNP.PairTerminalPreludeUnique
+
+/-! # Native terminal entry from the selected finite-model descriptor -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+namespace PairSimulation.TerminalLink
+
+open BurstRAM LiveProgram
+
+/-- The physical data exposed to the shared-bit and site interpreters by
+a deterministic prefix. Vertex readback is available on any fourth block
+with the indicated tape. -/
+structure QuietData {w cap : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w}
+ {input : Memory w} (q : QuietPrefix workers pub cap input)
+ (lo width prefixCount traversalCount : ℕ) (post : (Fin width → Bool) → Memory w → Prop) : Prop where
+ boot : q.boot.val.choices = [[]]
+ prefixRows : q.prefixRows.val.choices = List.replicate prefixCount []
+ traversal : q.traversalRows.val.choices = List.replicate traversalCount []
+ layout : FinalBits.Worker.Layout pub q.traversalRows.val.memory lo width
+ valid : (Entry.resume Stage.sharedBits (0 : Word w)).Valid (header pub) q.traversalRows.val.memory
+ clock : 54 ≤ cap
+ headerFit : (header pub).val+32 ≤ 2^w
+ low : (pub 2).val ≤ lo
+ below : lo+width ≤ (header pub).val
+ entry : ∀ bits (p : q.BitPaths), p.val.choices = FinalBits.calls bits ++ [[]] → post bits p.val.memory
+
+end PairSimulation.TerminalLink
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorBounds CursorNetwork BurstRAM LiveProgram CompressedPair
+open PairStages.Group.CompressedPaths LabelEvaluator CompressorRecords ScheduledTrace DescriptorSpace
+open PairSimulation LocalHistory TerminalLink TraversalRows TraversalRoles TerminalPrefix Filter
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {u : PairExponents B.growthConstant}
+ {D : FixedProgramDiagonal.Program} {C n : ℕ} {hn : 2 ≤ n} {V : D.VirtualPairs B u hn C}
+ {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f}
+ {c : Constants} {labels : c.motifLabels = Fintype.card B.Entry}
+ {base clk rate : ℕ} {pub : Fin 11 → Word (wordBits D.addressFactor n)} {m : Memory (wordBits D.addressFactor n)}
+
+local notation "ww" => wordBits D.addressFactor n
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "P" => initialPositions D.addressFactor n
+local notation "lanes₀" => reservedLanes B u n
+local notation "base₀" => virtualBits D.addressFactor n-reservedLanes B u n
+local notation "E" => B.execute f hf T le_rfl V.scanState
+local notation "L" => BlockProgram.layout B base P T
+local notation "tab" => (⟨0, by change 0 < 6; decide⟩ : Fin (L).shape.tables)
+local notation "parts" => paperSegments B u c labels
+local notation "bank₀" => TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit parts
+local notation "termClock" => clockAt pub clk CompressedPair.Stage.terminal
+local notation "payload₀" => CompiledResident.payload (w := ww) B f hf (base : Word ww) P T n
+
+/-- The checked vertex data, DFS history, wires and archived payloads on the
+same post-memory that the selected descriptor gives to the terminal program. -/
+abbrev VirtualPairs.PaperDescriptor.QuietData
+ (desc : V.PaperDescriptor f hf c labels base clk rate pub m) (z : (E).Choices)
+ (q : QuietPrefix bank₀ pub termClock (onlinePost (desc.paths z))) : Prop :=
+ let Y := (E).finalState z
+ let ls := selectedLayers B f hf T le_rfl V.scanState z
+ let tags := selected B f hf T le_rfl V.scanState z
+ TerminalLink.QuietData q (endAddress L+words B.recordLimit ls) Y.totalWidth (arcCount Y+1)
+ (2*(ls.map Layer.count).sum+2*tags.length+1) fun bits memory =>
+ TerminalProgram.VertexEntry B f hf T le_rfl V.scanState z L tab base₀ lanes₀ pub
+ (onlinePost (desc.paths z)) memory bits ∧
+ SelectedPayloadHistory.Past B f hf L payload₀ (executeLevels B f hf T le_rfl V.scanState z) memory
+
+private theorem quiet_of_room
+ (desc : V.PaperDescriptor f hf c labels base clk rate pub m)
+ (z : (E).Choices) (baseWord : (pub 2).val = base)
+ (tag : (PairTag.address pub).val < (pub 2).val+6) (exp : (pub 7).val = addressBits D.addressFactor n) :
+ let r := addressBits D.addressFactor n
+ let Y := (E).finalState z
+ let ls := selectedLayers B f hf T le_rfl V.scanState z
+ let tags := selected B f hf T le_rfl V.scanState z
+ r < ww → 32 ≤ (L).base+2^r*2^r → (L).base+2^r*2^r ≤ 2^ww →
+ endAddress L + 2*words B.recordLimit ls + Y.totalWidth ≤ TerminalBootstrap.address (L).base r →
+ 2*tags.length*(V.scanState.positions+1) < 2^ww →
+ arcCount Y ≤ slotCapacity L → arcCount Y ≤ tableWords L → Y.totalWidth < 2^ww →
+ TerminalBootstrap.cost (L).shape B.recordLimit+1+30 ≤ termClock → 60 ≤ termClock →
+ TraversalController.callFuel B.recordLimit+30 ≤ termClock →
+ ∃ q, desc.QuietData z q := by
+ subst base
+ intro r Y ls tags hr reserve room below ord slots cells totalFit clock₀ clock₁ clock₂
+ let alloc := BlockProgram.layout B (pub 2).val P T
+ let payload := CompiledResident.payload (w := ww) B f hf ((pub 2).val : Word ww) P T n
+ let phy := onlinePost (desc.paths z)
+ let rowWords := words B.recordLimit ls
+ let wireBase := endAddress alloc+rowWords
+ let post (bits : Fin Y.totalWidth → Bool) (mem : Memory ww) : Prop :=
+ TerminalProgram.VertexEntry B f hf T le_rfl V.scanState z alloc
+ (⟨0, by change 0 < 6; decide⟩ : Fin alloc.shape.tables) base₀ lanes₀ pub phy mem bits ∧
+ SelectedPayloadHistory.Past B f hf alloc payload (executeLevels B f hf T le_rfl V.scanState z) mem
+ let Good (W : TerminalLink.Stage → PairTable) : Prop :=
+ ∃ q : QuietPrefix W pub termClock phy, TerminalLink.QuietData q wireBase Y.totalWidth
+ (arcCount Y+1) (2*(ls.map Layer.count).sum+2*tags.length+1) post
+ change Good bank₀
+ apply (congrArg Good (TerminalLayout.packed_workers B (pub 2).val P T parts)).mp
+ have handoff := Linked.handoff_of_transfer pub (desc.post z) tag
+ obtain ⟨q,paths,boot,pref,rows,layout,each⟩ :=
+ TerminalProgram.packed_detailed_prefix B f hf T le_rfl V.scanState z P base₀ lanes₀
+ (initialWidth D.addressFactor n) n pub payload parts r termClock (desc.result.trace.cut.part z).memory phy
+ (desc.result.final z) handoff exp hr reserve room below ord slots cells totalFit clock₀ clock₁ clock₂
+ have head : (header pub).val = TerminalBootstrap.address alloc.base r :=
+ TerminalPrefix.header_val alloc pub r rfl exp hr reserve room
+ have lower : (pub 2).val ≤ endAddress alloc := by
+ apply le_trans _ (directoryBase_le_end alloc)
+ dsimp only [directoryBase,plannerTag,frameBase]
+ change (pub 2).val ≤ (pub 2).val+9+(_+1)+1; omega
+ have hHeader : (header pub).val+32 ≤ 2^ww := by
+ rw [head,TerminalBootstrap.address]
+ change 32 ≤ alloc.base+_ at reserve
+ change alloc.base+_ ≤ 2^ww at room
+ omega
+ have hWire : wireBase+Y.totalWidth ≤ (header pub).val := by
+ rw [head]
+ change endAddress alloc+2*rowWords+Y.totalWidth ≤ TerminalBootstrap.address alloc.base r at below
+ change endAddress alloc+rowWords+Y.totalWidth ≤ _
+ omega
+ refine ⟨q,boot,pref,rows,layout,q.valid_sharedBits (reserve.trans room),
+ (by omega : 54 ≤ termClock),hHeader,lower.trans (Nat.le_add_right ..),hWire,?_⟩
+ intro bits p tape
+ have eqn : p = paths bits := CompletedPhase.eq_of_choices _ _ (tape.trans (each bits).1.symm)
+ exact eqn ▸ (each bits).2
+
+set_option exponentiation.threshold 10000 in
+/-- Uniform selection of the actual fixed-bank prefix at the physical
+descriptor post-memory. Its vertex readback holds on each shared-bit path
+chosen by the canonical nomination. -/
+theorem eventually_paperDescriptorQuiet (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (C : ℕ) (hb : max S.laneBits 5 ≤ D.addressFactor)
+ (num : D.numerator = (liveRatio u).num) (den : D.denominator = (liveRatio u).den)
+ (c : Constants) (labels : c.motifLabels = Fintype.card B.Entry) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C)
+ (ht : 21 ≤ 2^(D.geometry n).w) (hc : 44 ≤ n^10000) {p : Nat.Primes}
+ (M : Model p (B.compressorDegree n) (B.compressorEquations hn C)),
+ let G := D.executionGroup n ht hc
+ let pub := publicWords G
+ let clk := fuel G
+ let base := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ ∀ (rate : ℕ) (m : Memory (wordBits D.addressFactor n))
+ (desc : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M)
+ c labels base clk rate pub m) (z : (V.selection (M := M)).Choices),
+ ∃ q, desc.QuietData z q := by
+ filter_upwards [eventually_paperDescriptorRoom D B u C hb num den] with n room
+ intro hn V ht hc p M G pub clk base rate m desc z
+ have h := room hn V ht hc M z
+ exact quiet_of_room desc z h.workspace h.tag h.exponent h.exponentFit h.reserve h.room h.below h.ordinal
+ h.slots h.cells h.totalFit h.bootClock h.widthClock h.rowClock
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairReadback.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairReadback.lean
new file mode 100644
index 0000000000..bdd232a153
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairReadback.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.LiveVirtualPairContinuation
+
+/-! # The canonical virtual pair's reset memory in the live shadow array -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression CursorNetwork LiveProgram PairStages PairStages.Group PrimedInputRAM
+open ExponentTrace CutSchedule
+
+private theorem lengths_cast {h h' Δ Δ' a a' : ℕ} (hh : h=h') (hd : Δ=Δ') (ha : a=a') (i : Fin (2^h)) :
+ PairedChain.lengths h' Δ' a' (i.cast (congrArg (2^·) hh)) = PairedChain.lengths h Δ a i := by
+ subst h'; subst Δ'; subst a'
+ rfl
+
+variable {D : FixedProgramDiagonal.Program} {n C : ℕ}
+ {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+
+/-- Transport a fixed-program pair index to the actual execution group's auxiliary index type
+using equality of the two chain heights. -/
+noncomputable abbrev physicalPairIndex (i : D.groupIndices n) : Fin (2^(Auxiliary.sizes (D.executionGroup n ht hf)).h) :=
+ i.cast (congrArg (2^·) heights)
+
+theorem physicalPairLengths (i : D.groupIndices n) :
+ Auxiliary.pairLengths (D.executionGroup n ht hf) (physicalPairIndex i) = D.pairLengths i :=
+ lengths_cast heights deltas adviceSizes i
+
+private theorem shadow_cast (G : Group) {i : Fin (2^(Auxiliary.sizes G).h)}
+ {L : PrimedInputRAM.Lengths} (hL : Auxiliary.pairLengths G i = L) (Q : Layout L G.g.n G.g.d G.g.H G.w)
+ (degree : Fin G.g.n) (root : Fin (Auxiliary.states G)) (hdr : Header L → Bool) (μ : Nominations.Nom G)
+ {m : Memory G.w} {N : Indexed G Stage.nominations m (Nominations.Nom G)}
+ (P : Auxiliary.PreparedBranch G m i (hL.symm ▸ hdr) N μ) (a : ℕ) :
+ P.copy.memory () ((Auxiliary.shadow G).val+a) =
+ (PrimedCounter.Data.ofNomination Q degree root hdr (Auxiliary.nominationEquiv G μ)).initial a := by
+ subst L
+ exact Auxiliary.shadow_initial Q degree root hdr μ P a
+
+universe v
+variable {K : Type v} [Field K] {S : BlockSchedule K} {B : S.Templates} {hn : 2 ≤ n}
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C)
+ (hC : D.constants.circuitExponent = C) (adv : Bits (n^D.constants.advicePower))
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n)
+ (μ : Nominations.Nom (D.executionGroup n ht hf))
+
+set_option maxHeartbeats 900000 in
+/-- The sparse-copy entry of the actual live machine agrees at every
+address with the reset memory of the canonical auxiliary pair. This
+includes the seven input arrays, unoccupied sparse slots and unused RAM. -/
+theorem VirtualPairs.shadow_initial {m : Memory (D.executionGroup n ht hf).w}
+ {N : Indexed (D.executionGroup n ht hf) Stage.nominations m (Nominations.Nom (D.executionGroup n ht hf))}
+ (P : Auxiliary.PreparedBranch (D.executionGroup n ht hf) m (physicalPairIndex i)
+ ((physicalPairLengths (ht := ht) (hf := hf) i).symm ▸ PairedChain.headers adv ξ i) N μ) (a : ℕ) :
+ P.copy.memory () ((Auxiliary.shadow (D.executionGroup n ht hf)).val+a) =
+ (V.data adv ξ i (physicalNomination hC μ)).initial a := by
+ subst C
+ exact shadow_cast (D.executionGroup n ht hf) (physicalPairLengths i) (V.layout i)
+ ⟨n-1,by change n-1 false) (fun _ => 0)).fits.headers
+ have eq : physicalPairIndex (ht := ht) (hf := hf) j = i := Fin.ext rfl
+ have size := physicalPairLengths (ht := ht) (hf := hf) j
+ rw [eq] at size
+ rw [LiveAuxiliaryHeaders.span,size,physicalGrammarCount hC,LiveProgram.Layout.virtualSiteBits_eq
+ _ (show 1 ≤ n by omega)]
+ rw [V.scratch] at counts
+ exact counts
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairSourceAssembly.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairSourceAssembly.lean
new file mode 100644
index 0000000000..0ac838de56
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairSourceAssembly.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.LiveCompressedPairTerminalAssembly
+import OAI.Computability.VPVNP.LiveCompressedPairHeaderMemory
+import OAI.Computability.VPVNP.LiveCompressedPairStageFrames
+import OAI.Computability.VPVNP.LiveVirtualPairOccurrence
+
+/-!
+# The source-run certificate of a concrete compressed pair
+
+Use the actual online path and the five terminal blocks to enumerate the
+accepted tapes of the fixed eleven-word program. The protected header and
+tag follow from the reachable-source frames. Counter readback concerns the
+memory of the last vertex block, and the burst bounds concern precisely
+the eight startup, online, and five terminal report lists.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM CompressorRecords CompressorRecords.Schedule PairSimulation LocalHistory NetworkKernel
+open LiveStageLink PairStages.Group PairStages.Group.CompressedPaths
+
+attribute [local irreducible] stages regs components TerminalProgram.workers
+
+variable {d initial phases : ℕ} {C : Catalog d} {b : Bootstrap} {plan : Online.Config C initial phases}
+ {shape : DescriptorSpace.Shape} {limit : ℕ} {segments : VertexImage.Part → VertexImage.Segment}
+ {G : PairStages.Group} {B n base : ℕ} {m : Memory G.w}
+variable (S : PhysicalStages b plan (terminalBody shape limit segments) G B n base m)
+
+local notation "ports" => publicWords G
+local notation "clk" => fuel G
+local notation "start" => cursorStartupLogs b ports B n base m initial phases d
+local notation "entry" => after m (eventLog start)
+local notation "lastStage" => terminalBody shape limit segments
+
+variable {X : Type} (enc : TraceEncoding X) (R : SelectorReindex enc) (visited : X → Memory G.w)
+ {Z : Type*} {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {net : Z → Network}
+ {scan : (z : Z) → ScanPhase (net z)} {sites : (z : Z) → SiteParsers κ (net z)}
+ (descriptor : Z ≃ StagePaths b plan (terminalBody shape limit segments) (publicWords G) (fuel G) Stage.online
+ (after m (eventLog (cursorStartupLogs b (publicWords G) B n base m initial phases d))))
+ (tags : 32 ≤ 2^G.w) (clock : 26 ≤ clockAt (publicWords G) (fuel G) Stage.terminal)
+ (branches : ∀ z : Z, TerminalBranch (G := G) (B := B) (n := n) (base := base) (m := m)
+ (b := b) (plan := plan) (shape := shape) (limit := limit) (segments := segments) descriptor (scan z) (sites z) z)
+ (emit : (Σ z : Z, TerminalData (scan z) (sites z)) ≃ Set.range R.emit)
+
+/-- Reports of one accepted compressed branch, from cursor startup through the selected online
+descriptor to the linked five terminal phases for its actual arc and vertex choices. -/
+noncomputable abbrev branchReports (z : Z) (x : TerminalData (scan z) (sites z)) :=
+ let t := branches z
+ let rows := t.setup.trace (t.bitPaths x.arcs) (t.vertexPaths x.arcs x.choices)
+ start ++ (onlineReports (descriptor z) ++
+ (TerminalLink.reports (TerminalLink.header ports) rows.logs).map (report ports Stage.terminal))
+
+private theorem range_tapes {J : Type*} (q : J ≃ Raw G m) (bits : List (List Bool)) :
+ bits ∈ Set.range (fun x : J => (q x).val) ↔
+ ∃ rs, runSegment (native G) clk (some 0) m bits = some rs ∧ endState (some 0) rs = none := by
+ constructor
+ · rintro ⟨x,rfl⟩
+ exact ⟨reports (q x),rawRun _,(q x).property.choose_spec.2.1⟩
+ · rintro ⟨rs,run,halt⟩
+ let path : Raw G m := ⟨bits,rs,run,halt,trivial⟩
+ exact ⟨q.symm path,congrArg Subtype.val (q.apply_symm_apply path)⟩
+
+
+/-- The canonical descriptor and terminal equivalences, the actual vertex
+counter effects and the stage-report budget construct all fields of
+`CompressedPaths.SourceRuns`. -/
+noncomputable def PhysicalStages.sourceRuns {S₀ H : ℕ}
+ (setup : TransferredStartup.Runs (bootstrapRows b initial phases) d (startupLayout b initial phases B n base)
+ B n b.degreeBits b.lanesPerBlock b.steps ports (PairTag.address ports) m)
+ (baseEq : base = (Layout.pairWorkspace G.constants).eval G.g) (baseFit : base < 2^G.w)
+ (shadow : Auxiliary.shadowBase G < 2^G.w)
+ (onlineFrame : ∀ a < Auxiliary.tableBase G, S.onlineFrame.word a)
+ (terminalFrame : ∀ a < Auxiliary.tableBase G, ∀ p, (S.terminalFrame p).word a)
+ (counter : ∀ z (x : TerminalData (scan z) (sites z)) (j : Fin (labelCount G)),
+ ((branches z).vertexPaths x.arcs x.choices).val.memory (Auxiliary.counterBase G+j.val) =
+ visited (R.decode (emit ⟨z,x⟩)) (Auxiliary.counterBase G+j.val))
+ (budget : ∀ z (x : TerminalData (scan z) (sites z)),
+ let rs := branchReports descriptor branches z x
+ (∀ r ∈ rs, r.events.length+4 ≤ clk) ∧ 4*RAMBuckets.cost Report.probes rs ≤ S₀*H ∧
+ ∀ r ∈ rs, 3+r.probes ≤ H) : SourceRuns G m X visited S₀ H := by
+ let paths := S.reindexTerminal descriptor tags clock branches emit
+ have before : G.addr.val < Auxiliary.tableBase G := by
+ rw [(Auxiliary.address_values G shadow).1]
+ exact (Auxiliary.geometry_order G).1.trans_le (Auxiliary.geometry_order G).2.1
+ have old := tag_before_workspace G.constants G.g
+ have upper : Auxiliary.tableBase G ≤ (Layout.oldState G.constants).eval G.g := by
+ have table := (Auxiliary.geometry_order G).2.2.1
+ change Auxiliary.tableBase G ≤ Auxiliary.counterBase G + G.constants.labels.eval G.g
+ omega
+ have beforeBase : G.addr.val < base := baseEq ▸ ((before.trans_le upper).trans old)
+ refine ⟨enc,R,fun y => (paths y).val,Subtype.val_injective.comp paths.injective,range_tapes paths,
+ S.preservesOuterTag shadow beforeBase setup (onlineFrame _ before) (terminalFrame _ before),?_⟩
+ intro y rs hr
+ obtain ⟨⟨z,x⟩,rfl⟩ := emit.surjective y
+ let path := paths (emit ⟨z,x⟩)
+ have logs : rs = reports path := Option.some.inj (hr.symm.trans (rawRun path))
+ subst rs
+ have cap := budget z x
+ have actualLogs := S.reindexTerminal_logs descriptor tags clock branches emit z x
+ change reports path = branchReports descriptor branches z x at actualLogs
+ rw [← actualLogs] at cap
+ refine ⟨fun a _ ha => S.headerReadback setup baseEq baseFit a ha (onlineFrame a ha)
+ (terminalFrame a ha) (rawRun path) path.property.choose_spec.2.1,?_,cap.2.1,?_⟩
+ · intro j
+ rw [show after m (eventLog (reports path)) = _ from S.reindexTerminal_after descriptor tags clock branches emit z x]
+ exact counter z x j
+ · exact fun r hr => ⟨cap.1 r hr,cap.2.2 r hr⟩
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairStartupBudget.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairStartupBudget.lean
new file mode 100644
index 0000000000..e7a78433ba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairStartupBudget.lean
@@ -0,0 +1,47 @@
+import OAI.Computability.VPVNP.LiveCompressedPairCursorStartup
+import OAI.Computability.VPVNP.LiveVirtualCompressedBudget
+import OAI.Computability.VPVNP.PaperPairParameters
+
+/-! # The eight native startup rows fit the compressed pair's burst budget -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM Compression CursorNetwork Filter
+
+theorem eventually_startup_burst {c : ℕ} (u : PairExponents c) (b : Bootstrap)
+ (initial phases margin : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ i : Fin 8, sourceFuel b initial phases n i + margin ≤ liveCapacity u n := by
+ obtain ⟨A,hA⟩ := sourceFuel_log b initial phases margin
+ have hδ : (u.δ : ℝ) < 1 := by
+ exact_mod_cast (show u.δ < 1 by linarith [u.theta_lt,u.delta_lt])
+ filter_upwards [eventually_absorb_polylog (A : ℝ) 1 (show (0 : ℝ) < 1-(u.δ : ℝ) by linarith)
+ (by norm_num : (0 : ℝ) < 1), eventually_ge_atTop 1] with n small hn i
+ simp only [Real.rpow_zero, mul_one, pow_one, one_mul] at small
+ have live := (liveBucket_bounds hδ.le hn).1
+ rw [liveCapacity_eq]
+ apply (hA n i).trans
+ exact_mod_cast small.trans live
+
+/-- The verified runs of the eight fixed bootstrap routines supply their own
+communication and private instruction bounds. -/
+theorem startup_rows_le {w : ℕ} (b : Bootstrap) (initial phases n H cap : ℕ)
+ (src : List (Stage × Report w))
+ (source : ∀ p ∈ src, ∃ i : Fin 8,
+ p.2.probes < sourceFuel b initial phases n i ∧ p.2.events.length < sourceFuel b initial phases n i)
+ (burst : ∀ i, sourceFuel b initial phases n i+5 ≤ H)
+ (fuel : ∀ i, sourceFuel b initial phases n i+77 ≤ cap) :
+ ∀ p ∈ src, p.2.probes+5 ≤ H ∧ p.2.events.length+77 ≤ cap := by
+ intro p hp
+ obtain ⟨i, probes, events⟩ := source p hp
+ exact ⟨(Nat.add_le_add_right probes.le 5).trans (burst i),
+ (Nat.add_le_add_right events.le 77).trans (fuel i)⟩
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairVertexCounters.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairVertexCounters.lean
new file mode 100644
index 0000000000..bfe4ab57c5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairVertexCounters.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.LiveVirtualPairPaperDescriptor
+import OAI.Computability.VPVNP.LiveVirtualPairNativeAssembly
+import OAI.Computability.VPVNP.LiveTerminalProtectedAddresses
+import OAI.Computability.VPVNP.LiveCompressedPairOnlineWord
+import OAI.Computability.VPVNP.PairTerminalLowCells
+import OAI.Computability.VPVNP.PairTerminalPackedPrefix
+
+/-! # The counter words presented to the selected terminal vertices -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM LiveProgram LocalCount
+open PairStages PairStages.Group PairStages.Group.CompressedPaths CompressedPair
+open PairSimulation PairSimulation.LocalHistory NetworkKernel CompressorRecords CompressorRecords.Schedule
+
+set_option quotPrecheck false
+open scoped Fin.CommRing
+
+attribute [local irreducible] CompressedPair.regs CompressedPair.components TerminalProgram.workers
+set_option maxHeartbeats 1200000
+
+variable {D : FixedProgramDiagonal.Program} {n C : ℕ} {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+ {K : Type} [Field K] {S : BlockSchedule K} {B : S.Templates} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M)
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn C)
+
+local notation "grp" => D.executionGroup n ht hf
+variable (W : Conditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (P : PairStageConditions (D.executionGroup n ht hf) (2^(D.geometry n).d) (D.geometry n).H)
+ (hC : D.constants.circuitExponent = C) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (cut : 1+B.denseCount n C*D.counterWidth n ≤ n^D.constants.deltaPower)
+ (I : VirtualPairs.PhysicalInput data W P hC hg cut)
+local notation "mem" => I.branch.copy.memory ()
+local notation "sel" => V.selection (M := M)
+local notation "ws" => PublicExpr.eval (D.geometry n) (Layout.pairWorkspace D.constants)
+local notation "ports" => publicWords grp
+
+local notation "f" => B.compressorValues hn M
+local notation "hf₀" => B.compressorValues_solution hn M
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "positions" => initialPositions D.addressFactor n
+local notation "L" => BlockProgram.layout B ws positions T
+local notation "boot" => paperBootstrap B u
+local notation "script" => BlockProgram.script B
+
+variable (rate : ℕ)
+variable (Y : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M) D.constants hg
+ ((Layout.pairWorkspace D.constants).eval (D.geometry n)) (fuel (D.executionGroup n ht hf)) rate
+ (publicWords (D.executionGroup n ht hf)) (I.branch.copy.memory ()))
+
+open TerminalLink SourceTransport
+open CompressorRecords.DescriptorSpace (endAddress levelStart levelsBase directoryBase plannerTag frameBase tableBase arrayBase incidenceStart)
+
+/-- Each selected shared-bit assignment reaches the vertex phase with the
+same grammar and motif counter words that the pair received on entry. -/
+theorem VirtualPairs.PaperDescriptor.vertex_counter_initial (z : (sel).Choices)
+ (setup : TransferredStartup.Runs (bootstrapRows boot (script).initial.length (script).block.length) (script).size
+ (startupLayout boot (script).initial.length (script).block.length D.addressFactor n ws)
+ D.addressFactor n (S.degreeExponent 0) S.laneBits S.steps ports (PairTag.address ports) mem)
+ (workspace : ws < 2^(D.geometry n).w)
+ {tab : Fin (L).shape.tables} {baseBits laneBits : ℕ} {bits : Fin ((sel).finalState z).totalWidth → Bool}
+ {vertex : Memory (grp).w}
+ (entry : TerminalProgram.VertexEntry B f hf₀ T le_rfl V.scanState z L tab baseBits laneBits
+ ports (onlinePost (Y.paths z)) vertex bits) (j : Fin (labelCount grp)) :
+ vertex (Auxiliary.counterBase grp+j.val) = mem (Auxiliary.counterBase grp+j.val) := by
+ let a := Auxiliary.counterBase grp+j.val
+ have tag := (terminal_protected_addresses grp (ports 2).val workspace le_rfl).1.1
+ have wsVal : (ports 2).val = ws := Nat.mod_eq_of_lt workspace
+ have sh : Auxiliary.shadowBase grp < ws := Nat.lt_add_of_pos_right (Nat.two_pow_pos _)
+ have apart : a < (PairTag.address ports).val := counter_before_pairTag grp (sh.trans workspace) j
+ have low : a < ws := (apart.trans tag).trans_eq wsVal
+ have base : (L).base = ws := rfl
+ have raw := entry.raw a (by
+ unfold endAddress levelStart levelsBase directoryBase plannerTag frameBase
+ omega) (.inl (by
+ unfold tableBase arrayBase incidenceStart levelStart levelsBase directoryBase plannerTag frameBase
+ omega))
+ have below : (PairTag.address ports).val < (ports 2).val+6 := by omega
+ exact raw.trans ((Y.protectedOnline below).after_startup_word D.addressFactor n ws mem setup Y.init
+ (Y.paths z) a low apart.ne (Y.online_word below a (by omega)))
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveVirtualPairs.lean b/lean/OAI/Computability/VPVNP/LiveVirtualPairs.lean
new file mode 100644
index 0000000000..0fbce50450
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveVirtualPairs.lean
@@ -0,0 +1,198 @@
+import OAI.Computability.VPVNP.FixedProgramModelData
+import OAI.Computability.VPVNP.PaperPairParameters
+import OAI.Computability.VPVNP.PairRAMDegreeBudget
+import OAI.Computability.VPVNP.PrimedCounterTranscriptCountParameters
+
+/-!
+# The concrete auxiliary pair data of the fixed diagonal program
+
+At each admissible length choose one uniform coefficient-counter layout
+for each pair index. All exterior bit strings and nominations use that same
+layout. Their compressed witnesses use the actual virtual machine, its
+actual reset word, private clock, and header. Thus the exponent histogram
+returned by the pair path and its algebraic weight belong to the same
+finite occurrence. The lane numbering reverses the coordinates within
+each address block, as in the physical cursor descriptor reader.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM BurstRAM.PrivateRAM LiveProgram CursorBounds CursorNetwork Compression
+open PrimedInputRAM PrimedStackRAM CutSchedule ExponentTrace Filter
+open scoped Classical
+
+universe v
+variable {K : Type v} [Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant) {n C : ℕ} (hn : 2 ≤ n)
+
+/-- Zero-based indices of the pairs at the fixed program's chain height, with one index for
+each first-half group. -/
+abbrev groupIndices (n : ℕ) := Fin (2^(D.chainHeight n))
+
+/-- Primed input lengths for one pair, including the two exterior cuts and the intervening cut,
+using the fixed program's chain height, cut width and advice length. -/
+abbrev pairLengths (i : D.groupIndices n) :=
+ PairedChain.lengths (D.chainHeight n) (n^D.constants.deltaPower) (n^D.constants.advicePower) i
+
+/-- Type of primed RAM input layouts for this pair's field lengths and the program's physical
+site exponent, bucket size and word width. -/
+abbrev pairLayout (i : D.groupIndices n) :=
+ PrimedInputRAM.Layout (D.pairLengths i) n (D.geometry n).d (D.geometry n).H (D.geometry n).w
+
+/-- Production histograms nominated at length n and circuit exponent C. Each production count
+is strictly less than `2^(2*d)`, where d is the physical site address width. -/
+abbrev pairNom (n C : ℕ) := BlockSchedule.Templates.PairNomination n C (D.geometry n).d
+
+/-- Degree, root and production histogram passed to the actual auxiliary program. -/
+noncomputable def auxData {i : D.groupIndices n} (Q : D.pairLayout i)
+ (hdr : Header (D.pairLengths i) → Bool) (μ : D.pairNom n C) :
+ PrimedCounter.Data Q (n^(C+5)) :=
+ PrimedCounter.Data.ofNomination Q ⟨n-1,by omega⟩ ⟨0,pow_pos (by omega) _⟩ hdr μ
+
+/-- Resource conditions on the virtual processor at length n, using the virtual site exponent,
+the rounded quarter-power bucket exponent and the fixed program's RAM word width. -/
+abbrev virtualCap (n : ℕ) := ProcessorBudget n (virtualBits D.addressFactor n)
+ (roundedUp 1 4 n) (CursorBounds.wordBits D.addressFactor n)
+
+/-- Number of lane coordinates used by all scheduled compression blocks, equal to the block
+count times the lanes per block. -/
+noncomputable def reservedLanes (n : ℕ) := blockCount (u.θ : ℝ) n * S.laneBits
+
+/-- Physical choices shared by all calls to the auxiliary pair program
+at this one length. The degree inequality precedes the choice of
+specialization, input, and path. -/
+structure VirtualPairs (C : ℕ) where
+ /-- Primed input layout for each pair index at this length, shared across all advice,
+ exterior bits and nominations for that index. -/
+ layout : (i : D.groupIndices n) → D.pairLayout i
+ literal : ∀ i, (layout i).program = D.literal
+ scratch : ∀ i, (layout i).scratchBase = 2^(virtualBits D.addressFactor n)
+ cap : D.virtualCap n
+ counts : ∀ i hdr (μ : D.pairNom n C), PrimedCounter.Resources.Counts (D.auxData hn (layout i) hdr μ) μ cap
+ dimension : 1 < virtualBits D.addressFactor n
+ lanes : reservedLanes B u n ≤ virtualBits D.addressFactor n
+ degree : ∀ (A : Type) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ (i : D.groupIndices n) (hdr : Header (D.pairLengths i) → Bool) (μ : D.pairNom n C),
+ let d := D.auxData hn (layout i) hdr μ
+ let W := pairRAMCountWithFuel B u dimension cap (laneLabels _ _ lanes) le_rfl
+ f hf d.machine d.fuel 0 d.initial
+ ∀ q : W.Choice, (∑ l, W.exponents q l) < 2^(2*(D.geometry n).d)
+
+variable {D B u hn}
+
+/-- Instantiate the auxiliary coefficient counter at this pair index with its layout, the
+header derived from advice and exterior cuts, and the nominated production counts. -/
+noncomputable def VirtualPairs.data (V : D.VirtualPairs B u hn C) (advice : Bits (n^D.constants.advicePower))
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n) (μ : D.pairNom n C) :=
+ D.auxData hn (V.layout i) (PairedChain.headers advice ξ i) μ
+
+/-- Compressed count witness for the nominated auxiliary machine under the given label
+solution, using its actual private fuel, zero starting state and initialized memory. -/
+noncomputable def VirtualPairs.witness (V : D.VirtualPairs B u hn C) {A : Type} [CommRing A]
+ (f : B.Entry → A) (hf : B.IsSolution f) (advice : Bits (n^D.constants.advicePower))
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n) (μ : D.pairNom n C) :=
+ let d := V.data advice ξ i μ
+ pairRAMCountWithFuel B u V.dimension V.cap (laneLabels _ _ V.lanes) le_rfl
+ f hf d.machine d.fuel 0 d.initial
+
+variable {p : Nat.Primes} {M : LabelEvaluator.Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ (data : D.ScalarData B hn M)
+ (fit : ProcessorInput.Fits D.literal n (D.geometry n).d (D.geometry n).H (D.geometry n).w)
+
+private theorem input_program_congr {n r bucket w : ℕ} {L : PrimedInputRAM.Lengths}
+ {p q : UniversalMachine.Program} (hp : ProcessorInput.Fits p n r bucket w)
+ (hq : ProcessorInput.Fits q n r bucket w) (eq : p = q) (header : Header L → Bool) :
+ PrimedInputRAM.input p hp header = PrimedInputRAM.input q hq header := by
+ cases eq
+ rfl
+
+/-- The finite paths, their exponents, and their joint coefficient identity
+for the literal processor and precisely the same advice used at the midpoint. -/
+noncomputable def VirtualPairs.pairData (V : D.VirtualPairs B u hn C) : PairData data fit where
+ Path ξ i μ := (V.witness (B.compressorValues hn M) (B.compressorValues_solution hn M) data.advice ξ i μ).Choice
+ pathFintype _ _ _ := inferInstance
+ ν ξ i μ := (V.witness (B.compressorValues hn M) (B.compressorValues_solution hn M) data.advice ξ i μ).exponents
+ bounded ξ i μ q l := by
+ have h := V.degree M.algebra (B.compressorValues hn M) (B.compressorValues_solution hn M)
+ i (PairedChain.headers data.advice ξ i) μ q
+ exact (Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ l)).trans_lt h
+ weight ξ i μ := by
+ let W := V.witness (B.compressorValues hn M) (B.compressorValues_solution hn M) data.advice ξ i μ
+ have hw := W.evaluates
+ have hc := (V.counts i (PairedChain.headers data.advice ξ i) μ).native
+ have eq := input_program_congr (V.layout i).fits fit (V.literal i) (PairedChain.headers data.advice ξ i)
+ rw [show (D.auxData hn (V.layout i) (PairedChain.headers data.advice ξ i) μ).header =
+ PairedChain.headers data.advice ξ i from rfl, eq] at hc
+ exact hw.trans (congrArg (fun x : ℕ => (x : M.algebra)) hc)
+
+/-- A fixed exponent covering all grammar labels before the address exponent
+is selected. It depends only on the hypothesized circuit exponent. -/
+def grammarCapacityPower (C : ℕ) := 3 + 3*(C+5)
+
+theorem grammar_count_le (n C : ℕ) (hn : 2 ≤ n) :
+ labelCount n n (n^(C+5)) ≤ n^grammarCapacityPower C := by
+ let H := n^(C+5)
+ have hH : 0 < H := Nat.pow_pos (by omega)
+ have hH' : H ≤ H^3 := by simpa only [pow_one] using Nat.pow_le_pow_right hH (by decide : 1 ≤ 3)
+ have hch : n.choose 2 ≤ n*n := by
+ rw [Nat.choose_two_right]
+ exact (Nat.div_le_self ..).trans (Nat.mul_le_mul_left _ (Nat.sub_le ..))
+ change H*n*2+n.choose 2*H*H*H ≤ _
+ have h1 : H*n*2 ≤ n*n*H^3 := calc
+ _ ≤ H*n*n := Nat.mul_le_mul_left _ hn
+ _ = n*n*H := by ring
+ _ ≤ _ := Nat.mul_le_mul_left _ hH'
+ have h2 : n.choose 2*H*H*H ≤ n*n*H^3 := calc
+ _ = n.choose 2*H^3 := by ring
+ _ ≤ _ := Nat.mul_le_mul_right _ hch
+ calc
+ _ ≤ 2*(n*n*H^3) := by omega
+ _ ≤ n*(n*n*H^3) := Nat.mul_le_mul_right _ hn
+ _ = n^grammarCapacityPower C := by
+ unfold grammarCapacityPower H
+ rw [pow_add n 3 (3*(C+5)), Nat.mul_comm 3 (C+5), pow_mul n (C+5) 3]
+ ring
+
+variable (D B u)
+
+/-- At sufficiently large lengths the auxiliary virtual layouts and their
+path identities exist simultaneously at every pair, before the advice,
+exterior cuts and nominations are selected. -/
+theorem eventually_virtualPairs (C : ℕ)
+ (hnumerator : D.numerator = (liveRatio u).num) (hdenominator : D.denominator = (liveRatio u).den)
+ (hb : max S.laneBits 5 ≤ D.addressFactor)
+ (hB : max (max (D.constants.chainPower+1) (D.constants.chainPower+D.constants.deltaPower))
+ (max D.constants.advicePower (grammarCapacityPower C)) + 2 ≤ D.addressFactor) :
+ ∀ᶠ n : ℕ in atTop, ∀ hn : 2 ≤ n, Nonempty (D.VirtualPairs B u hn C) := by
+ have hd : 0 < (u.δ : ℝ) := by exact_mod_cast u.delta_pos
+ have hd' : (u.δ : ℝ) ≤ 1 := by exact_mod_cast (show u.δ ≤ 1 by linarith [u.theta_lt,u.delta_lt])
+ filter_upwards [PrimedCounter.Resources.eventually_counts D.literal D.constants.chainPower
+ D.constants.advicePower D.constants.deltaPower (grammarCapacityPower C) D.addressFactor hB hd hd',
+ eventually_pairRAMCountWithFuel_degree.{v,0} B u D.addressFactor hb] with n counts degree hn
+ obtain ⟨hD,cap,hLane,hdeg⟩ := degree
+ have hbuck : liveBucket (u.δ : ℝ) n = (D.geometry n).H := by
+ change liveBucket (u.δ : ℝ) n = 2^(roundedUp D.numerator D.denominator n)
+ rw [hnumerator,hdenominator,← liveCapacity_eq u n]
+ rfl
+ have localLayouts (i : D.groupIndices n) :
+ ∃ Q : D.pairLayout i, Q.program = D.literal ∧ Q.scratchBase = 2^(virtualBits D.addressFactor n) ∧
+ ∀ hdr (μ : D.pairNom n C), PrimedCounter.Resources.Counts (D.auxData hn Q hdr μ) μ cap := by
+ have hh := counts i (n^(C+5)) (grammar_count_le n C hn)
+ dsimp only at hh
+ rw [hbuck] at hh
+ obtain ⟨Q,hp,hbase,cap',hc⟩ := hh
+ exact ⟨Q,hp,hbase,fun hdr μ => hc _ _ hdr μ (by change n-1+1=n; omega)⟩
+ choose Q hq hs hc using localLayouts
+ refine ⟨⟨Q,hq,hs,cap,hc,hD,hLane,?_⟩⟩
+ intro A inst f hf i hdr μ d W q
+ exact hdeg (laneLabels _ _ hLane) le_rfl A f hf d.machine d.fuel 0 d.initial q
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveWordCapacity.lean b/lean/OAI/Computability/VPVNP/LiveWordCapacity.lean
new file mode 100644
index 0000000000..6865072fde
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveWordCapacity.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.LiveProgramLayout
+import OAI.Computability.VPVNP.CursorBounds
+import OAI.Computability.VPVNP.LogBounds
+import OAI.Computability.VPVNP.RAMSiteBounds
+
+/-!
+# Word capacity for the live processor's public operand expressions
+
+Only two exponentials occur among the static operands: the physical site
+count and the virtual site count. For fixed address parameter both counts
+grow polynomially in the input length. This suffices for *every intermediate
+register* of an operand, including any multiplication before a division.
+The later choice of the address parameter does not impose an upper bound
+on the exponent of the permitted polynomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+open Filter CursorBounds
+
+/-- Live processor geometry at input length n, with site address width and RAM word width from
+the address parameter and bucket size H n. -/
+def paperGeometry (B : ℕ) (H : ℕ → ℕ) (n : ℕ) : Geometry :=
+ ⟨n, addressBits B n, H n, CursorBounds.wordBits B n⟩
+
+namespace PublicExpr
+
+/-- The syntax used by the complete fixed public bank. -/
+def SitePowers : PublicExpr → Prop
+ | .add a b | .sub a b | .mul a b => SitePowers a ∧ SitePowers b
+ | .divConst a _ | .log2 a | .clog2 a => SitePowers a
+ | .pow2 a => SitePowers a ∧ (a = .d ∨ a = Layout.virtualSiteBits)
+ | _ => True
+
+@[simp] theorem SitePowers.natPow {a : PublicExpr} (h : a.SitePowers) (k : ℕ) :
+ (a.natPow k).SitePowers := by
+ induction k with
+ | zero => trivial
+ | succ k ih => exact ⟨ih,h⟩
+
+private theorem siteCount_polynomial (B : ℕ) :
+ PolynomiallyBounded (fun n => 2^(B * Nat.clog 2 n)) := by
+ apply (((PolynomiallyBounded.const 2).mul PolynomiallyBounded.id).pow B).of_eventually_le 1
+ intro n hn
+ have hlog := Nat.pow_log_le_self 2 (show n ≠ 0 by omega)
+ have hclog : 2^(Nat.clog 2 n) ≤ 2*n := calc
+ _ ≤ 2^(n.log2+1) := Nat.pow_le_pow_right (by decide) (BurstRAM.clog_le_log2_succ n)
+ _ = 2*2^(n.log2) := pow_succ' ..
+ _ ≤ _ := Nat.mul_le_mul_left _ (by simpa [Nat.log2_eq_log_two] using hlog)
+ rw [Nat.mul_comm, pow_mul]
+ exact Nat.pow_le_pow_left hclog B
+
+private theorem virtualCount_polynomial (B : ℕ) (H : ℕ → ℕ) :
+ PolynomiallyBounded (fun n => 2^Layout.virtualSiteBits.eval (paperGeometry B H n)) := by
+ apply (siteCount_polynomial (B+2)).of_eventually_le 1
+ intro n hn
+ rw [Layout.virtualSiteBits_eq _ hn]
+ exact Nat.pow_le_pow_right (by decide) (virtualBits_le B n)
+
+private theorem d_polynomial (B : ℕ) : PolynomiallyBounded (addressBits B) :=
+ (PolynomiallyBounded.const B).mul PolynomiallyBounded.id.clog
+
+private theorem modulus_room (B : ℕ) (hB : 1 ≤ B) {f : ℕ → ℕ} (hf : PolynomiallyBounded f) :
+ ∀ᶠ n in atTop, f n < 2^CursorBounds.wordBits B n := by
+ obtain ⟨A,d,N,h⟩ := hf
+ filter_upwards [eventually_ge_atTop N, eventually_ge_atTop A,
+ BurstRAM.eventually_polynomial_lt_wordModulus (d+1)] with n hn hA hp
+ apply lt_of_le_of_lt ((h n hn).trans (Nat.mul_le_mul_right (n^d) hA))
+ rw [← pow_succ']
+ exact hp _ (BurstRAM.log2_le_addressWidth hB n)
+
+/-- Polynomial bounds and simultaneous intermediate word fit for one
+fixed operand. The live bucket size may be any polynomially bounded function. -/
+theorem SitePowers.fits {B : ℕ} (hB : 1 ≤ B) {H : ℕ → ℕ} (hH : PolynomiallyBounded H)
+ {e : PublicExpr} (h : e.SitePowers) :
+ PolynomiallyBounded (fun n => e.eval (paperGeometry B H n)) ∧
+ ∀ᶠ n in atTop, e.Fits (paperGeometry B H n) (2^CursorBounds.wordBits B n) := by
+ induction e with
+ | lit c =>
+ have hp : PolynomiallyBounded (fun n => (lit c).eval (paperGeometry B H n)) := .const _
+ exact ⟨hp, (modulus_room B hB hp).mono fun _ hi => ⟨hi,trivial⟩⟩
+ | n => exact ⟨PolynomiallyBounded.id, (modulus_room B hB PolynomiallyBounded.id).mono fun _ hi => ⟨hi,trivial⟩⟩
+ | d => exact ⟨d_polynomial B, (modulus_room B hB (d_polynomial B)).mono fun _ hi => ⟨hi,trivial⟩⟩
+ | H => exact ⟨hH, (modulus_room B hB hH).mono fun _ hi => ⟨hi,trivial⟩⟩
+ | w =>
+ have hp := ((d_polynomial B).add (.const 10)).pow 4
+ exact ⟨hp, (modulus_room B hB hp).mono fun _ hi => ⟨hi,trivial⟩⟩
+ | add a b ia ib | sub a b ia ib | mul a b ia ib =>
+ obtain ⟨ha,fa⟩ := ia h.1
+ obtain ⟨hb,fb⟩ := ib h.2
+ first | have hp := ha.add hb; refine ⟨hp,?_⟩
+ | have hp := ha.mul hb; refine ⟨hp,?_⟩
+ | have hp := ha.of_le (fun n => Nat.sub_le (a.eval (paperGeometry B H n)) (b.eval (paperGeometry B H n))); refine ⟨hp,?_⟩
+ filter_upwards [modulus_room B hB hp, fa, fb] with n hl hal hbl
+ exact ⟨hl,hal,hbl⟩
+ | divConst a b ih =>
+ obtain ⟨ha,fa⟩ := ih h
+ have hp := ha.of_le (fun n => Nat.div_le_self (a.eval (paperGeometry B H n)) b)
+ refine ⟨hp,?_⟩
+ filter_upwards [modulus_room B hB hp, fa, modulus_room B hB (PolynomiallyBounded.const b)] with n hl hal hb
+ exact ⟨hl,hal,hb⟩
+ | log2 a ih | clog2 a ih =>
+ obtain ⟨ha,fa⟩ := ih h
+ first | have hp := ha.clog; refine ⟨hp,?_⟩
+ | have hp := ha.of_le (fun n => Nat.log_le_self 2 (a.eval (paperGeometry B H n))); refine ⟨hp,?_⟩
+ filter_upwards [modulus_room B hB hp, fa] with n hl hal
+ exact ⟨hl,hal⟩
+ | pow2 a ih =>
+ obtain ⟨_,fa⟩ := ih h.1
+ have hp : PolynomiallyBounded (fun n => (pow2 a).eval (paperGeometry B H n)) := by
+ rcases h.2 with rfl | rfl
+ · exact siteCount_polynomial B
+ · exact virtualCount_polynomial B H
+ exact ⟨hp, (modulus_room B hB hp).and fa⟩
+
+/-- Uniform threshold for every operand in any finite table. -/
+theorem fits_bank {B : ℕ} (hB : 1 ≤ B) {H : ℕ → ℕ} (hH : PolynomiallyBounded H)
+ {ι : Type*} [Finite ι] (bank : ι → PublicExpr) (hs : ∀ i, (bank i).SitePowers) :
+ ∀ᶠ n in atTop, ∀ i, (bank i).Fits (paperGeometry B H n) (2^CursorBounds.wordBits B n) :=
+ (Filter.eventually_all).mpr fun i => ((hs i).fits hB hH).2
+
+end PublicExpr
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LiveWorkspaceCapacity.lean b/lean/OAI/Computability/VPVNP/LiveWorkspaceCapacity.lean
new file mode 100644
index 0000000000..c926f00c00
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LiveWorkspaceCapacity.lean
@@ -0,0 +1,47 @@
+import OAI.Computability.VPVNP.LiveLayoutWordFit
+
+/-!
+# Word space for the live buffers and the auxiliary workspace
+
+All live and auxiliary scratch addresses, including a final workspace of
+R² words after the virtual header, fit in one word for every sufficiently
+large length once B is fixed. The threshold works simultaneously for all
+groups, nominations and compressor term choices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+
+open Filter
+
+theorem eventually_workspace (c : Constants) {B : ℕ} (hB : 1 ≤ B)
+ {H : ℕ → ℕ} (hH : PolynomiallyBounded H) :
+ ∀ᶠ n in atTop, let g := paperGeometry B H n
+ (Layout.pairWorkspace c).eval g + (CursorBounds.processorCount B n)^2 < 2^g.w ∧
+ (Layout.shadow c).eval g < 2^g.w ∧ (Layout.oldState c).eval g < 2^g.w ∧
+ Layout.stageTag.eval g < 2^g.w := by
+ have safe : ((Layout.pairWorkspace c) + Layout.stageTag.natPow 2).SitePowers :=
+ ⟨Layout.pairWorkspace_sitePowers c, Layout.stageTag_sitePowers.natPow 2⟩
+ filter_upwards [(safe.fits hB hH).2, ((Layout.shadow_sitePowers c).fits hB hH).2,
+ ((Layout.oldState_sitePowers c).fits hB hH).2, (Layout.stageTag_sitePowers.fits hB hH).2]
+ with n hw hs ho ht
+ have hR : Layout.stageTag.eval (paperGeometry B H n) = CursorBounds.processorCount B n := rfl
+ change (Layout.pairWorkspace c).eval (paperGeometry B H n) + (CursorBounds.processorCount B n)^2 < 2^CursorBounds.wordBits B n ∧ _
+ exact ⟨by simpa only [eval_add, PublicExpr.eval_natPow, hR] using hw.1, hs.1,ho.1,ht.1⟩
+
+/-- The same heap bound applies to every descriptor offset below R². -/
+theorem eventually_offset_fits (c : Constants) {B : ℕ} (hB : 1 ≤ B)
+ {H : ℕ → ℕ} (hH : PolynomiallyBounded H) :
+ ∀ᶠ n in atTop, ∀ i ≤ (CursorBounds.processorCount B n)^2,
+ (Layout.pairWorkspace c).eval (paperGeometry B H n) + i < 2^CursorBounds.wordBits B n := by
+ filter_upwards [eventually_workspace c hB hH] with n h i hi
+ exact (Nat.add_le_add_left hi _).trans_lt h.1
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/LogBounds.lean b/lean/OAI/Computability/VPVNP/LogBounds.lean
new file mode 100644
index 0000000000..6ae255e7d7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/LogBounds.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.PolynomialBounds
+import Mathlib.Data.Nat.Log
+
+/-!
+# Polynomial bit-length bounds for natural arithmetic
+
+The binary logarithms of sizes are closed under sums, products, and raising
+a size to a polynomially bounded exponent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PolynomiallyBounded
+
+variable {f g : ℕ → ℕ}
+
+theorem clog (hf : PolynomiallyBounded f) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (f n)) :=
+ hf.of_le fun _ => Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le
+
+theorem clog_mul (hf : PolynomiallyBounded (fun n => Nat.clog 2 (f n)))
+ (hg : PolynomiallyBounded (fun n => Nat.clog 2 (g n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (f n * g n)) := by
+ refine (hf.add hg).of_le fun n => Nat.clog_le_of_le_pow ?_
+ change f n * g n ≤ 2 ^ (Nat.clog 2 (f n) + Nat.clog 2 (g n))
+ rw [pow_add]
+ exact Nat.mul_le_mul (Nat.le_pow_clog (by decide) _) (Nat.le_pow_clog (by decide) _)
+
+theorem clog_add (hf : PolynomiallyBounded (fun n => Nat.clog 2 (f n)))
+ (hg : PolynomiallyBounded (fun n => Nat.clog 2 (g n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (f n + g n)) := by
+ refine ((hf.add hg).add (PolynomiallyBounded.const 1)).of_le fun n => Nat.clog_le_of_le_pow ?_
+ let e := Nat.clog 2 (f n) + Nat.clog 2 (g n)
+ have h₁ : f n ≤ 2 ^ e := (Nat.le_pow_clog (by decide) _).trans
+ (Nat.pow_le_pow_right (by decide) (Nat.le_add_right _ _))
+ have h₂ : g n ≤ 2 ^ e := (Nat.le_pow_clog (by decide) _).trans
+ (Nat.pow_le_pow_right (by decide) (Nat.le_add_left _ _))
+ change f n + g n ≤ 2 ^ (e + 1)
+ rw [pow_succ, Nat.mul_two]
+ exact Nat.add_le_add h₁ h₂
+
+theorem clog_pow (hf : PolynomiallyBounded (fun n => Nat.clog 2 (f n)))
+ (hg : PolynomiallyBounded g) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (f n ^ g n)) := by
+ refine (hf.mul hg).of_le fun n => Nat.clog_le_of_le_pow ?_
+ change f n ^ g n ≤ 2 ^ (Nat.clog 2 (f n) * g n)
+ rw [pow_mul]
+ exact Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) _
+
+end PolynomiallyBounded
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayAdvicePreload.lean b/lean/OAI/Computability/VPVNP/MacaulayAdvicePreload.lean
new file mode 100644
index 0000000000..a0dc98b05d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayAdvicePreload.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.MacaulayLeafBudgets
+import OAI.Computability.VPVNP.MacaulaySignedCoefficient
+
+/-! # Capacity of the actual coefficient-reader advice banks
+
+The checker serialization and the selected mask and extension-field values
+are present in full. Both banks use finite port types. Each immutable stack
+fits the common live-space budget used by the row phases.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.Arms
+
+open RAMTape RadicalCertificate.MonomialIndex
+
+variable {p e t : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- Immutable pin mask, scalar table, width markers and arithmetic advice. -/
+theorem pin_preload_length (w v : ℕ) (pins : Finset (Fin t)) (a : Fin t → Scalar c)
+ (i : AffinePin.Query.Port) :
+ (AffinePin.Query.frame (AffinePin.Query.advice w v pins a) c v {} i).length ≤ AffinePin.Query.storage t e w v := by
+ rcases i with i|i
+ · cases i <;> simp [AffinePin.Query.frame, AffinePin.Stage.frame, AffinePin.Query.advice,
+ AffinePin.Query.mask_length, AffinePin.Query.values_length, AffinePin.Query.storage] <;> omega
+ · rcases i with i|i
+ · simp [AffinePin.Query.frame, SliceArithmetic.AddCall.clean]
+ · cases i <;> simp [AffinePin.Query.frame, SliceArithmetic.AddCall.clean, SliceArithmetic.MultiplyCall.external,
+ AffinePin.Query.storage] <;> omega
+
+/-- Disjoint ports for the signed equation-coefficient reader and the affine pin mask and value
+reader. -/
+abbrev CoefficientPort := JointScalar.Leaf.Port ⊕ AffinePin.Query.Port
+
+/-- The checker words and affine advice occupy disjoint physical banks. -/
+def coefficientAdvice (L : JointScalar.Leaf.Layout) (w v : ℕ) (pins : Finset (Fin t)) (a : Fin t → Scalar c) :
+ Stacks CoefficientPort :=
+ Sum.elim (JointScalar.Leaf.clean L [] [] []) (AffinePin.Query.frame (AffinePin.Query.advice w v pins a) c v {})
+
+theorem coefficientAdvice_loaded (L : JointScalar.Leaf.Layout) (w v : ℕ) (pins : Finset (Fin t))
+ (a : Fin t → Scalar c) :
+ SignedLeaf.Loaded L Sum.inl (coefficientAdvice L w v pins a) ∧
+ Pin.Preloaded (Function.Embedding.inr) (AffinePin.Query.advice w v pins a) c v (coefficientAdvice L w v pins a) :=
+ ⟨fun _ _ _ _ => rfl, fun _ => rfl⟩
+
+/-- The same prime-independent bound covers all immutable coefficient slots
+and the constant zero and one field encodings. -/
+theorem coefficientAdvice_preload {P : ReaderPlan} {w v signedSpace E V : ℕ} {L : JointScalar.Leaf.Layout}
+ (ht : P.arity=t) (he : e≤E) (hv : v≤V)
+ (hs : JointScalar.Leaf.bankSize L w (t*w) ≤ signedSpace)
+ (pins : Finset (Fin t)) (a : Fin t → Scalar c) (data : Bool → PairCall.Inputs) (harity : ∀ b, (data b).arity=t)
+ (constants : Bool → List Bool) (hconst : ∀ b, (constants b).length ≤ e*v) :
+ Preload (w := w) (P.live E V w signedSpace) data constants (coefficientAdvice L w v pins a) := by
+ have hsize := Nat.mul_le_mul he hv
+ have hpin : AffinePin.Query.storage t e w v ≤ AffinePin.Query.space t E w V :=
+ (Nat.le_add_right ..).trans (ReaderPlan.pin_space_mono t w he hv)
+ refine ⟨by dsimp [ReaderPlan.live]; omega, fun b => ?_, fun b => ?_, fun j => ?_⟩
+ · rw [harity b,← ht]
+ dsimp [ReaderPlan.live]; omega
+ · have h := (hconst b).trans hsize
+ dsimp [ReaderPlan.live]; omega
+ · cases j with
+ | inl i =>
+ have h := (JointScalar.Leaf.clean_length_le L w (t*w) i).trans hs
+ change (JointScalar.Leaf.clean L [] [] [] i).length ≤ _
+ dsimp only [ReaderPlan.live]; omega
+ | inr i =>
+ have h := (pin_preload_length w v pins a i).trans hpin
+ change (AffinePin.Query.frame (AffinePin.Query.advice w v pins a) c v {} i).length ≤ _
+ dsimp only [ReaderPlan.live]; rw [ht]; omega
+
+end RankQuery.Stack.MacaulayRead.Arms
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayAppendedPower.lean b/lean/OAI/Computability/VPVNP/MacaulayAppendedPower.lean
new file mode 100644
index 0000000000..fd0070ea3c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayAppendedPower.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.MacaulayEntryExecution
+import OAI.Computability.VPVNP.MacaulayBaseAdvice
+
+/-! # Native read of an appended powered-monomial matrix row
+
+The source and column ordinals have already been produced by the numeric
+row decoder. The complete powered phase compares both monomials, returns
+the field encoding of the formal coefficient, and restores all work ports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.Arms
+
+open RAMTape BurstRAM MacaulayRowDispatch RadicalCertificate.MonomialIndex
+
+variable {K : Type} [DecidableEq K] {p e w A S v : ℕ} [Fact p.Prime] {c : SliceArithmetic.Vector p e}
+
+/-- The suffix of the augmented matrix consists of monomials raised to the
+certificate power. This is the coefficient returned by its physical branch. -/
+theorem appended_power (rs : Reg → Word w) (data : Bool → PairCall.Inputs)
+ (constants : Bool → List Bool) (aux : Stacks K)
+ (pre : Preload (w := w) A data constants aux) (hw : 1≤w)
+ (source : Fin (size (data true).arity ((data true).degree false)))
+ (column : Fin (size (data true).arity ((data true).degree true)))
+ (hsource : (rs (outReg 2)).val=source.val) (hcolumn : (rs (outReg 3)).val=column.val)
+ (hm : (data true).mark=0) (hc : ∀ bit : Bool, constants bit = Engine.scalar v (if bit then (1 : Scalar c) else 0))
+ (hwidth : PairCall.requiredWidth (data true) ≤ w)
+ (hspace : PairCall.poweredSpace w A ≤ S) (htrans : transient A (data true).arity w ≤ S) :
+ ∃ n ≤ PairCall.scanClock w A (data true) + PairCall.powerClock (data true).arity w A +
+ PairCall.clearCost w + postTicks A (data true).arity w (5*A+2),
+ (phase true (emit true)).BoundedRun S n (frame rs [] (storage w data blank blank constants aux))
+ (frame rs (Engine.scalar v (powerEntry (K := Scalar c) (data true).scale (indexedDigits source) column))
+ (storage w data blank blank constants aux)) := by
+ let d := addressed rs (data true)
+ let ords : PairCall.Ordinals d := fun b => match b with
+ | false => source
+ | true => column
+ have hk (b : Bool) : d.ordinal b=(ords b).val := by cases b; exact hsource; exact hcolumn
+ obtain ⟨fit,efit⟩ := PairCall.fits_of_width d ords hwidth
+ obtain ⟨n,hn,run⟩ := powered_execution rs data constants aux pre hw ords hk fit efit hspace htrans
+ let flag := PairCall.powerMatch d (PairCall.monomial d ords false) (PairCall.monomial d ords true)
+ have hval : constants flag = Engine.scalar v
+ (powerEntry (K := Scalar c) (data true).scale (indexedDigits source) column) := by
+ rw [hc]
+ exact congrArg (Engine.scalar v) (PairCall.powerMatch_entry (K := Scalar c) d ords hm)
+ change (phase true (emit true)).BoundedRun S n _ (frame rs (constants flag) _) at run
+ exact ⟨n,hn,hval ▸ run⟩
+
+/-- Specialization to the actual ordinary-reader advice and its uniform
+budget. Only the two decoded ordinals depend on the selected matrix entry. -/
+theorem appended_power_plan {F : Type*} (P : ReaderPlan) (Q : QueryData P.arity (P.equations+P.pins) F)
+ (h : P.Covers Q) {E V : ℕ} (he : e ≤ E) (hv : v ≤ V) (sp ex : ℕ)
+ (hw : P.wordWidth ≤ w) (rs : Reg → Word w) (aux : Stacks K)
+ (pre : Preload (w := w) (P.live E V w sp) (BaseAdvice.inputs Q) (BaseAdvice.scalars c v) aux)
+ (source : Fin (size P.arity Q.pointBound)) (column : Fin (size P.arity Q.columnDegree))
+ (hsource : (rs (outReg 2)).val = source.val) (hcolumn : (rs (outReg 3)).val = column.val) :
+ ∃ n ≤ P.armTime E V w sp ex, (phase true (emit true)).BoundedRun (P.armSpace E V w sp) n
+ (frame rs [] (storage w (BaseAdvice.inputs Q) blank blank (BaseAdvice.scalars c v) aux))
+ (frame rs (Engine.scalar v (powerEntry (K := Scalar c) Q.power (indexedDigits source) column))
+ (storage w (BaseAdvice.inputs Q) blank blank (BaseAdvice.scalars c v) aux)) := by
+ let A := P.live E V w sp
+ let d := BaseAdvice.inputs Q true
+ have hL : d.degree false ≤ P.source := h.points_le.trans (le_max_left ..)
+ have hD : d.degree true ≤ P.column := h.degrees.2.2
+ have hscaled : Q.power ≤ Q.power*Q.fieldOrder := Nat.le_mul_of_pos_right _ ((by decide : 0 < 2).trans_le h.order_two)
+ have hw' := (P.pairWidth_le d rfl hL hD (hscaled.trans (h.targetParams .frobenius).1) (Nat.zero_le _)).trans hw
+ obtain ⟨_,hs,_⟩ := P.leaf_bounds w sp ex he hv d rfl hL hD
+ obtain ⟨steps,ht,run⟩ := appended_power rs (BaseAdvice.inputs Q) (BaseAdvice.scalars c v) aux pre
+ ((by decide : 1≤2).trans (P.dispatchWidth.2.2.trans hw)) source column hsource hcolumn rfl (fun _ => rfl)
+ hw' hs.2.1 hs.2.2.2.1
+ have hscan := (P.scan_bounds w A d rfl hL hD).2.1
+ have hpost : postTicks A P.arity w (5*A+2) ≤ postTicks A P.arity w (P.scalarTime E V w ex) := by
+ unfold postTicks
+ rw [max_self]
+ exact Nat.add_le_add_right (Nat.add_le_add_left (le_max_left ..) _) _
+ exact ⟨steps, ht.trans (Nat.add_le_add hscan hpost), run⟩
+
+end RankQuery.Stack.MacaulayRead.Arms
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayBaseAdvice.lean b/lean/OAI/Computability/VPVNP/MacaulayBaseAdvice.lean
new file mode 100644
index 0000000000..d7494b3b5f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayBaseAdvice.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.MacaulayAdvicePreload
+
+/-! # Initial advice of the augmented Macaulay matrix reader
+
+The private decoder words specify the number of original equations, affine
+pins and multiplier monomials. Its two scalar banks contain the signed grammar
+coefficient circuit and the actual pin mask and field values. Both are reusable
+across all row and column queries. Scratch decoder registers may change, but
+their widths and the exact leaf data are preserved by the ready predicate.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.BaseAdvice
+
+open RAMTape UniversalCountStack SliceArithmetic RadicalCertificate.MonomialIndex BurstRAM
+
+variable {F : Type*} {p e t eqs : ℕ}
+
+/-- The source radix is the multiplier degree for an equation, and the point
+bound for an appended powered monomial. The column radix is common. -/
+def inputs (S : QueryData t eqs F) (power : Bool) : PairCall.Inputs where
+ arity := t
+ degree := fun column ↦ if column then S.columnDegree else if power then S.pointBound else S.multiplierDegree
+ ordinal := fun _ ↦ 0
+ scale := if power then S.power else 1
+ mark := 0
+
+variable [Fact p.Prime]
+
+/-- Encode the extension-field element zero or one selected by the Boolean flag, using v bits
+per ground-field coordinate. -/
+def scalars (c : Vector p e) (v : ℕ) (bit : Bool) : List Bool :=
+ Engine.scalar v (if bit then (1 : Scalar c) else 0)
+
+/-- The immutable leaf bank for the integer, affine and powered-monomial arms. -/
+def leaf (S : QueryData t eqs F) (L : JointScalar.Leaf.Layout) (c : Vector p e) (w v : ℕ)
+ (pins : Finset (Fin t)) (values : Fin t → Scalar c) : Stacks (Arms.Leaf Arms.CoefficientPort) :=
+ Arms.storage w (inputs S) Arms.blank Arms.blank (scalars c v) (Arms.coefficientAdvice L w v pins values)
+
+/-- Canonical initial decoder registers. The two externally aliased addresses
+and all dispatch outputs start at zero. -/
+def registers (w originals pins multiples : ℕ) (j : MacaulayRowDispatch.Reg) : Word w :=
+ if h : j.val < 8 then Fin.ofNat _ (MacaulayRowDispatch.inputs 0 0 originals pins multiples ⟨j.val,h⟩) else 0
+
+theorem registers_params {w orig pins multiple : ℕ} (h₁ : orig < 2^w) (h₂ : pins < 2^w)
+ (h₃ : multiple < 2^w) : Params orig pins multiple (registers w orig pins multiple) := by
+ intro i _
+ have hi : (MacaulayRowDispatch.inReg i).val = i.val := rfl
+ have hv : (⟨(MacaulayRowDispatch.inReg i).val, hi ▸ i.isLt⟩ : Fin 8) = i := Fin.ext hi
+ rw [registers, dite_eq_left (hi ▸ i.isLt), hv, Fin.val_ofNat, Nat.mod_eq_of_lt]
+ fin_cases i <;> simp [MacaulayRowDispatch.inputs, h₁, h₂, h₃]
+
+/-- Physical working ports for the row decoder together with the coefficient-reader advice. -/
+abbrev RawPort := Work (Arms.Leaf Arms.CoefficientPort)
+
+/-- Initialize the row decoder with the equation, pin and multiplier counts and install the
+scalar advice used by all row queries. -/
+def initial (originals : ℕ) (S : QueryData t eqs F) (L : JointScalar.Leaf.Layout) (c : Vector p e) (w v : ℕ)
+ (pins : Finset (Fin t)) (values : Fin t → Scalar c) : Stacks RawPort :=
+ auxBank (registers w originals t (size t S.multiplierDegree)) (leaf S L c w v pins values)
+
+/-- The decoder has the required counts and bounded register widths, and its leaf bank still
+holds the specified coefficient and pin advice. -/
+def ready (originals : ℕ) (S : QueryData t eqs F) (L : JointScalar.Leaf.Layout) (c : Vector p e) (w v : ℕ)
+ (pins : Finset (Fin t)) (values : Fin t → Scalar c) : Stacks RawPort → Prop :=
+ Ready w originals t (size t S.multiplierDegree) (· = leaf S L c w v pins values)
+
+theorem initial_ready (originals : ℕ) (S : QueryData t eqs F) (L : JointScalar.Leaf.Layout) (c : Vector p e)
+ (w v : ℕ) (pins : Finset (Fin t)) (values : Fin t → Scalar c) (ho : originals < 2^w)
+ (ht : t < 2^w) (hm : size t S.multiplierDegree < 2^w) :
+ ready originals S L c w v pins values (initial originals S L c w v pins values) :=
+ ⟨_, _, registers_params ho ht hm, rfl, rfl⟩
+
+/-- Every state permitted at a repeated-query boundary satisfies the same height
+bound. The encoded matrix dimensions themselves may be exponential. -/
+theorem ready_length {originals w v A : ℕ} (S : QueryData t eqs F) (L : JointScalar.Leaf.Layout)
+ (c : Vector p e) (pins : Finset (Fin t)) (values : Fin t → Scalar c)
+ (pre : Arms.Preload (w := w) A (inputs S) (scalars c v) (Arms.coefficientAdvice L w v pins values))
+ (s : Stacks RawPort) (h : ready originals S L c w v pins values s) (k : RawPort) : (s k).length ≤ A := by
+ obtain ⟨rs, _, _, rfl, rfl⟩ := h
+ exact Arms.frame_bound rs [] (inputs S) Arms.blank Arms.blank (scalars c v) (Arms.coefficientAdvice L w v pins values)
+ pre.words (Nat.zero_le _) pre.arity (fun _ ↦ Nat.zero_le _) (fun _ ↦ Nat.zero_le _) pre.scalars pre.payload (.aux k)
+
+/-- The physical ready cap follows from the common reader plan before the
+particular field and its affine pins are chosen. -/
+theorem ready_length_uniform {originals w v E V signedSpace : ℕ} (P : ReaderPlan) (S : QueryData t eqs F)
+ (L : JointScalar.Leaf.Layout) (c : Vector p e) (pins : Finset (Fin t)) (values : Fin t → Scalar c)
+ (ht : P.arity = t) (he : e ≤ E) (hv : v ≤ V) (hs : JointScalar.Leaf.bankSize L w (t*w) ≤ signedSpace)
+ (s : Stacks RawPort) (h : ready originals S L c w v pins values s) (k : RawPort) :
+ (s k).length ≤ P.live E V w signedSpace :=
+ ready_length S L c pins values (Arms.coefficientAdvice_preload ht he hv hs pins values (inputs S)
+ (fun _ ↦ rfl) (scalars c v) (fun b ↦ (Engine.scalar_length v (if b then (1 : Scalar c) else 0)).le)) s h k
+
+end RankQuery.Stack.MacaulayRead.BaseAdvice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayCallBank.lean b/lean/OAI/Computability/VPVNP/MacaulayCallBank.lean
new file mode 100644
index 0000000000..8635711e21
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayCallBank.lean
@@ -0,0 +1,191 @@
+import OAI.Computability.VPVNP.RoutineSpace
+import OAI.Computability.VPVNP.SpaceRunMonotone
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+
+/-!
+# Staging and cleaning the fixed banks of coefficient-query subroutines
+
+A call copies selected read-only words into its private registers. On return
+it prepends selected output stacks to the caller's ports and erases its
+private bank. The time bound of the called routine and its space bound
+enter the resulting estimates separately.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.CallBank
+
+open RAMTape UniversalCountStack
+
+/-- Stack addresses for the caller's words, the callee's private registers and the scratch
+stack used during copying. -/
+inductive Port (X I : Type) where
+ | external (x : X)
+ | internal (i : I)
+ | scratch
+ deriving DecidableEq, Fintype
+
+variable {X I : Type} [DecidableEq X] [DecidableEq I]
+
+/-- Combine caller and callee stacks into a single call frame with an empty copy scratch stack. -/
+def frame (x : Stacks X) (u : Stacks I) : Stacks (Port X I)
+ | .external k => x k
+ | .internal k => u k
+ | .scratch => []
+
+/-- Initial or returned frame containing the caller's stacks and empty private and scratch
+banks. -/
+def clean (x : Stacks X) := frame (I := I) x fun _ => []
+
+private theorem update_internal (x : Stacks X) (u : Stacks I) (i : I) (v : List Bool) :
+ Function.update (frame x u) (.internal i) v = frame x (Function.update u i v) := by
+ funext j
+ cases j with
+ | internal j => by_cases h : i = j <;> simp [frame, h, eq_comm]
+ | _ => rfl
+
+private theorem update_external (x : Stacks X) (u : Stacks I) (i : X) (v : List Bool) :
+ Function.update (frame x u) (.external i) v = frame (Function.update x i v) u := by
+ funext j
+ cases j with
+ | external j => by_cases h : i = j <;> simp [frame, h, eq_comm]
+ | _ => rfl
+
+private def copyIn (source : I → X) (i : I) : FiniteRoutine (Port X I) :=
+ SuccessorFields.prependCopy (.external (source i)) (.internal i) .scratch
+
+private def fill (source : I → X) : List I → FiniteRoutine (Port X I)
+ | [] => .ret
+ | i :: is => (fill source is).followedBy (copyIn source i)
+
+/-- The private inputs after staging a call. Each selected register holds a copy of its
+designated caller stack. -/
+def filled (source : I → X) (is : List I) (x : Stacks X) (i : I) : List Bool :=
+ if i ∈ is then x (source i) else []
+
+private theorem fill_runs (source : I → X) (is : List I) (x : Stacks X) (B : ℕ) (hn : is.Nodup)
+ (hB : ∀ k, (x k).length ≤ B) :
+ ∃ t ≤ is.length*(5*B+2)+1, (fill source is).Runs t (clean x) (frame x (filled source is x)) := by
+ induction is with
+ | nil =>
+ have he : filled source [] x = fun _ => [] := funext fun _ => by simp [filled]
+ rw [he]
+ exact ⟨1,by simp,Routine.runs_ret _⟩
+ | cons i is ih =>
+ obtain ⟨hi,hn'⟩ := List.nodup_cons.mp hn
+ obtain ⟨t,ht,hr⟩ := ih hn'
+ let u := filled source is x
+ have hrun := SuccessorFields.prependCopy_runs (K := Port X I) (.external (source i)) (.internal i) .scratch
+ (by simp) (by simp) (by simp) (frame x u) rfl
+ change (copyIn source i).Runs (5*(x (source i)).length+2) (frame x u)
+ (Function.update (frame x u) (.internal i) (x (source i) ++ u i)) at hrun
+ have he : Function.update u i (x (source i) ++ u i) = filled source (i::is) x := by
+ funext j
+ by_cases h : j=i <;> simp [filled, u, h, hi]
+ rw [update_internal, he] at hrun
+ refine ⟨_, ?_, hr.followedBy hrun⟩
+ have := hB (source i); rw [List.length_cons, Nat.succ_mul is.length (5*B+2)]; omega
+
+private def copyOut (pair : I × X) : FiniteRoutine (Port X I) :=
+ SuccessorFields.prependCopy (.internal pair.1) (.external pair.2) .scratch
+
+private def save : List (I × X) → FiniteRoutine (Port X I)
+ | [] => .ret
+ | p :: ps => (copyOut p).followedBy (save ps)
+
+/-- Caller stacks after prepending the specified callee outputs, in order, to their destination
+stacks. -/
+def saved (u : Stacks I) : List (I × X) → Stacks X → Stacks X
+ | [], x => x
+ | (i,k) :: ps, x => saved u ps (Function.update x k (u i ++ x k))
+
+private theorem save_runs (ps : List (I × X)) (x : Stacks X) (u : Stacks I) (C : ℕ) (hC : ∀ i, (u i).length ≤ C) :
+ ∃ t ≤ ps.length*(5*C+2)+1, (save ps).Runs t (frame x u) (frame (saved u ps x) u) := by
+ induction ps generalizing x with
+ | nil => exact ⟨1,by simp,Routine.runs_ret _⟩
+ | cons pair ps ih =>
+ obtain ⟨i,k⟩ := pair
+ have hrun := SuccessorFields.prependCopy_runs (K := Port X I) (.internal i) (.external k) .scratch
+ (by simp) (by simp) (by simp) (frame x u) rfl
+ change (copyOut (i,k)).Runs (5*(u i).length+2) (frame x u)
+ (Function.update (frame x u) (.external k) (u i ++ x k)) at hrun
+ rw [update_external] at hrun
+ obtain ⟨t,ht,hr⟩ := ih (Function.update x k (u i ++ x k))
+ refine ⟨_, ?_, hrun.followedBy hr⟩
+ have := hC i; rw [List.length_cons, Nat.succ_mul ps.length (5*C+2)]; omega
+
+omit [DecidableEq X] [DecidableEq I] in
+private theorem frame_cap (x : Stacks X) (u : Stacks I) {B C : ℕ}
+ (hB : ∀ k, (x k).length ≤ B) (hC : ∀ k, (u k).length ≤ C) (k : Port X I) :
+ (frame x u k).length ≤ max B C := by
+ cases k with
+ | external j => exact (hB j).trans (le_max_left ..)
+ | internal j => exact (hC j).trans (le_max_right ..)
+ | scratch => exact Nat.zero_le _
+
+/-- Stage the selected input words, execute the private routine, copy its outputs back and
+erase the specified private registers. -/
+def machine (source : I → X) (ins : List I) (f : FiniteRoutine I) (outs : List (I × X)) (wipe : List I) :
+ FiniteRoutine (Port X I) :=
+ (((fill source ins).followedBy (f.onPorts Port.internal)).followedBy (save outs)).followedBy
+ (SliceArithmetic.CallClear.cleanup (wipe.map Port.internal))
+
+/-- Cost of all copies and clears around the called program. -/
+def overhead (inputs outputs cleared B C : ℕ) :=
+ (inputs*(5*B+2)+1) + (outputs*(5*C+2)+1) + (cleared*(C+1)+1)
+
+theorem machine_run (source : I → X) (ins : List I) (f : FiniteRoutine I) (outs : List (I × X)) (wipe : List I)
+ (x : Stacks X) (u v : Stacks I) {T B C : ℕ} (hn : ins.Nodup) (hB : ∀ k, (x k).length ≤ B)
+ (hin : filled source ins x = u) (hr : f.BoundedRun C T u v) (hz : ∀ i ∉ wipe, v i = []) :
+ let work := overhead ins.length outs.length wipe.length B C
+ ∃ t ≤ T+work, (machine source ins f outs wipe).BoundedRun (B+C+work) t
+ (clean x) (clean (saved v outs x)) := by
+ intro work
+ obtain ⟨a,ha,hfill⟩ := fill_runs source ins x B hn hB
+ rw [hin] at hfill
+ obtain ⟨b,hb,hsave⟩ := save_runs outs x v C hr.final_cap
+ let x' := saved v outs x
+ obtain ⟨d,hd,herase⟩ := SliceArithmetic.CallClear.cleanup_runs (wipe.map (Port.internal (X := X))) (frame x' v) C
+ (fun i hi => by obtain ⟨j,_,rfl⟩ := List.mem_map.mp hi; exact hr.final_cap j)
+ rw [List.length_map] at hd
+ have he : SliceArithmetic.CallClear.erased (wipe.map (Port.internal (X := X))) (frame x' v) = clean x' := by
+ funext i; cases i with
+ | external | scratch => simp [SliceArithmetic.CallClear.erased, clean, frame]
+ | internal i => by_cases hi : i ∈ wipe <;> simp [SliceArithmetic.CallClear.erased, clean, frame, hi, hz]
+ rw [he] at herase
+ have hcapC : C ≤ B+C+work := by omega
+ have hcore := FiniteRoutine.BoundedRun.onPorts (a := f) (ports := Port.internal)
+ (fun _ _ e => Port.internal.inj e) (frame x u) (hr.mono_cap hcapC)
+ (fun k outside => by
+ cases k with
+ | external j => exact (hB j).trans (by omega)
+ | internal i => exact (outside i rfl).elim
+ | scratch => exact Nat.zero_le _)
+ have install (s : Stacks I) : installStacks (Port.internal (X := X)) (frame x u) s = frame x s := by
+ apply installStacks_frame (ports := Port.internal) (base := frame x u) (small := s) (target := frame x s) (fun _ _ e => Port.internal.inj e) (fun _ => rfl)
+ rintro (j | j | _) outside <;> first | rfl | exact (outside j rfl).elim
+ rw [install, install] at hcore
+ have hfill' : (fill source ins).BoundedRun (B+C+work) a (clean x) (frame x u) :=
+ spaceRun_of_steps hfill fun k => by
+ have hx : (clean (I := I) x k).length ≤ B := by cases k <;> first | apply hB | exact Nat.zero_le _
+ dsimp [work, overhead]; omega
+ have hs' : (save outs).BoundedRun (B+C+work) b (frame x v) (frame x' v) :=
+ spaceRun_of_steps hsave fun k => by
+ have := frame_cap x v hB hr.final_cap k; dsimp [work, overhead]; omega
+ have hclear' : (SliceArithmetic.CallClear.cleanup (wipe.map (Port.internal (X := X)))).BoundedRun (B+C+work) d
+ (frame x' v) (clean x') := spaceRun_of_steps herase fun k => by
+ have htemp : SpaceRun (save outs).body.standalone (max B C + b) b (some (save outs).body.entry) (frame x v)
+ none (frame x' v) := spaceRun_of_steps hsave fun j => Nat.add_le_add_right (frame_cap x v hB hr.final_cap j) b
+ have := htemp.final_cap k
+ dsimp [work, overhead]; omega
+ refine ⟨_, ?_, ((hfill'.followedBy hcore).followedBy hs').followedBy hclear'⟩
+ dsimp [work, overhead]; omega
+
+end RadicalCertificate.MonomialIndex.CallBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayCoordinates.lean b/lean/OAI/Computability/VPVNP/MacaulayCoordinates.lean
new file mode 100644
index 0000000000..bcce9e9000
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayCoordinates.lean
@@ -0,0 +1,344 @@
+import OAI.Computability.VPVNP.CoordinateQueries
+import OAI.Computability.VPVNP.MacaulayRelations
+import OAI.Computability.VPVNP.FiniteSlice
+
+/-!
+# Coordinates from the augmented Macaulay matrix
+
+Appendix D puts the Macaulay rows first and then the powered monomial rows.
+A greedy coordinate query in this order returns a representation of the target.
+Discarding the coefficients of the Macaulay rows gives a representation in the
+quotient by their span, hence a representation of the original polynomial on
+the slice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+variable {K : Type*} {w n m : ℕ}
+
+/-- Concatenate two lists of rows, retaining their column indexing. -/
+def appendRows (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K) :
+ Matrix (Fin (w + n)) (Fin m) K := Fin.addCases W M
+
+@[simp] theorem appendRows_left (W : Matrix (Fin w) (Fin m) K)
+ (M : Matrix (Fin n) (Fin m) K) (i : Fin w) :
+ appendRows W M (i.castAdd n) = W i := Fin.addCases_left ..
+
+@[simp] theorem appendRows_right (W : Matrix (Fin w) (Fin m) K)
+ (M : Matrix (Fin n) (Fin m) K) (j : Fin n) :
+ appendRows W M (j.natAdd w) = M j := Fin.addCases_right ..
+
+variable [Field K]
+
+/-- A row in the appended block increases the prefix rank exactly when its
+class in the quotient increases the span of the preceding appended rows. -/
+theorem mem_appendRows_greedy_iff (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K)
+ (j : Fin n) :
+ j.natAdd w ∈ greedyIndices K (appendRows W M).row ↔
+ j ∈ greedyIndices K ((Submodule.span K (Set.range W.row)).mkQ ∘ M.row) := by
+ let S := Submodule.span K (Set.range W.row)
+ have himage : (appendRows W M).row '' Set.Iio (j.natAdd w) =
+ Set.range W.row ∪ M.row '' Set.Iio j := by
+ ext v
+ constructor
+ · rintro ⟨i, hi, rfl⟩
+ revert hi
+ refine Fin.addCases (fun i _ ↦ ?_) (fun i hi ↦ ?_) i
+ · exact Or.inl ⟨i, (appendRows_left W M i).symm⟩
+ · refine Or.inr ⟨i, ?_, (appendRows_right W M i).symm⟩
+ change w + i.val < w + j.val at hi
+ exact Nat.lt_of_add_lt_add_left hi
+ · rintro (⟨i, rfl⟩ | ⟨i, hi, rfl⟩)
+ · refine ⟨i.castAdd n, ?_, appendRows_left W M i⟩
+ exact lt_of_lt_of_le i.isLt (Nat.le_add_right _ _)
+ · exact ⟨i.natAdd w, Nat.add_lt_add_left hi w, appendRows_right W M i⟩
+ rw [mem_greedyIndices, mem_greedyIndices, himage, Submodule.span_union]
+ rw [show (appendRows W M).row (j.natAdd w) = M j from appendRows_right W M j]
+ change M j ∉ S ⊔ Submodule.span K (M.row '' Set.Iio j) ↔
+ S.mkQ (M j) ∉ Submodule.span K ((S.mkQ ∘ M.row) '' Set.Iio j)
+ rw [Set.image_comp, ← Submodule.map_span]
+ change M j ∉ S ⊔ Submodule.span K (M.row '' Set.Iio j) ↔
+ M j ∉ ((Submodule.span K (M.row '' Set.Iio j)).map S.mkQ).comap S.mkQ
+ rw [Submodule.comap_map_mkQ]
+
+variable [DecidableEq K]
+
+/-- Query the coefficient assigned to an original row. Only a selected row
+contributes a term to the sum over greedy basis indices. -/
+def originalRowCoordinate (A : Matrix (Fin n) (Fin m) K) (target : Fin m → K) (j : Fin n) : K :=
+ streamSum (rankQuery A) fun k ↦ if greedyRowIndex A k = j then greedyCoordinateQuery A target k else 0
+
+theorem originalRowCoordinate_eq_zero (A : Matrix (Fin n) (Fin m) K) (target : Fin m → K)
+ {j : Fin n} (hj : j ∉ greedyIndices K A.row) : originalRowCoordinate A target j = 0 := by
+ rw [originalRowCoordinate, streamSum_eq]
+ apply Finset.sum_eq_zero
+ intro k _
+ apply ite_eq_right_iff.mpr
+ intro he
+ exfalso
+ apply hj
+ rw [← he, greedyRowIndex_eq]
+ exact Finset.orderEmbOfFin_mem ..
+
+theorem originalRowCoordinate_reconstruct (A : Matrix (Fin n) (Fin m) K) (target : Fin m → K)
+ (hspan : target ∈ Submodule.span K (Set.range A.row)) :
+ ∑ j, originalRowCoordinate A target j • A j = target := by
+ simp only [originalRowCoordinate, streamSum_eq, Finset.sum_smul, ite_smul, zero_smul]
+ rw [Finset.sum_comm]
+ simpa using greedyCoordinateQuery_reconstruct A target hspan
+
+/-- The monomial coefficients, indexed by the second block of the augmented matrix. -/
+def quotientCoordinate (W : Matrix (Fin w) (Fin m) K) (M : Matrix (Fin n) (Fin m) K)
+ (target : Fin m → K) (j : Fin n) : K :=
+ originalRowCoordinate (appendRows W M) target (j.natAdd w)
+
+/-- The difference between the target and the combination of retained monomial
+rows belongs to the span of the original Macaulay rows. -/
+theorem quotientCoordinate_reconstruct (W : Matrix (Fin w) (Fin m) K)
+ (M : Matrix (Fin n) (Fin m) K) (target : Fin m → K)
+ (hspan : target ∈ Submodule.span K (Set.range (appendRows W M).row)) :
+ target - ∑ j, quotientCoordinate W M target j • M j ∈ Submodule.span K (Set.range W.row) := by
+ have he := originalRowCoordinate_reconstruct (appendRows W M) target hspan
+ rw [Fin.sum_univ_add] at he
+ simp only [appendRows_left, appendRows_right] at he
+ unfold quotientCoordinate
+ rw [sub_eq_iff_eq_add.mpr he.symm]
+ exact Submodule.sum_mem _ fun i _ ↦ Submodule.smul_mem _ _ (Submodule.subset_span ⟨i, rfl⟩)
+
+/-- Equality in the quotient by the Macaulay row space after discarding its coordinates. -/
+theorem quotientCoordinate_eq_mkQ (W : Matrix (Fin w) (Fin m) K)
+ (M : Matrix (Fin n) (Fin m) K) (target : Fin m → K)
+ (hspan : target ∈ Submodule.span K (Set.range (appendRows W M).row)) :
+ let π := (Submodule.span K (Set.range W.row)).mkQ
+ π target = ∑ j, quotientCoordinate W M target j • π (M j) := by
+ let S := Submodule.span K (Set.range W.row)
+ have h := quotientCoordinate_reconstruct W M target hspan
+ have hz : S.mkQ (target - ∑ j, quotientCoordinate W M target j • M j) = 0 :=
+ (Submodule.Quotient.mk_eq_zero _).mpr h
+ simpa only [map_sub, map_sum, map_smul, sub_eq_zero, S] using hz
+
+omit [DecidableEq K] in
+private theorem mem_append_of_difference (W : Matrix (Fin w) (Fin m) K)
+ (M : Matrix (Fin n) (Fin m) K) (target : Fin m → K) (c : Fin n → K)
+ (hc : target - ∑ j, c j • M j ∈ Submodule.span K (Set.range W.row)) :
+ target ∈ Submodule.span K (Set.range (appendRows W M).row) := by
+ let T := Submodule.span K (Set.range (appendRows W M).row)
+ have hleft : Submodule.span K (Set.range W.row) ≤ T := by
+ apply Submodule.span_le.mpr
+ rintro _ ⟨i, rfl⟩
+ exact Submodule.subset_span ⟨i.castAdd n, appendRows_left W M i⟩
+ have hright : ∑ j, c j • M j ∈ T := T.sum_mem fun j _ ↦
+ T.smul_mem _ (Submodule.subset_span ⟨j.natAdd w, appendRows_right W M j⟩)
+ simpa using T.add_mem (hleft hc) hright
+
+/-- Reindex the coefficient columns and the Macaulay rows for an indexed
+determinant query. The chosen order of the appended list is retained. -/
+def indexedQuotientCoordinate {I J : Type*} (W : Matrix I J K) (M : Matrix (Fin n) J K)
+ (rows : Fin w ≃ I) (cols : Fin m ≃ J) (target : J → K) : Fin n → K :=
+ quotientCoordinate (W.submatrix rows cols) (M.submatrix id cols) (target ∘ cols)
+
+omit [DecidableEq K] in
+theorem reindexed_difference_mem_iff {I J : Type*} (W : Matrix I J K) (M : Matrix (Fin n) J K)
+ (rows : Fin w ≃ I) (cols : Fin m ≃ J) (target : J → K) (c : Fin n → K) :
+ target ∘ cols - ∑ j, c j • (M.submatrix id cols) j ∈
+ Submodule.span K (Set.range (W.submatrix rows cols).row) ↔
+ target - ∑ j, c j • M j ∈ Submodule.span K (Set.range W.row) := by
+ let φ := (LinearEquiv.funCongrLeft K K cols).toLinearMap
+ let W' := W.submatrix rows cols
+ let M' := M.submatrix id cols
+ have hrows : Set.range W'.row = φ '' Set.range W.row := by
+ ext v
+ constructor
+ · rintro ⟨i, rfl⟩
+ exact ⟨W (rows i), ⟨rows i, rfl⟩, rfl⟩
+ · rintro ⟨_, ⟨i, rfl⟩, rfl⟩
+ refine ⟨rows.symm i, ?_⟩
+ funext j
+ change W (rows (rows.symm i)) (cols j) = W i (cols j)
+ rw [rows.apply_symm_apply]
+ have he : φ (target - ∑ j, c j • M j) = target ∘ cols - ∑ j, c j • M' j := by
+ rw [map_sub, map_sum]
+ simp only [map_smul]
+ rfl
+ rw [← he, hrows]
+ exact Submodule.apply_mem_span_image_iff_mem_span (LinearEquiv.funCongrLeft K K cols).injective
+
+theorem indexedQuotientCoordinate_reconstruct {I J : Type*} (W : Matrix I J K)
+ (M : Matrix (Fin n) J K) (rows : Fin w ≃ I) (cols : Fin m ≃ J) (target : J → K)
+ (hspan : ∃ c : Fin n → K, target - ∑ j, c j • M j ∈ Submodule.span K (Set.range W.row)) :
+ target - ∑ j, indexedQuotientCoordinate W M rows cols target j • M j ∈
+ Submodule.span K (Set.range W.row) := by
+ let W' := W.submatrix rows cols
+ let M' := M.submatrix id cols
+ have htransfer := reindexed_difference_mem_iff W M rows cols target
+ obtain ⟨c, hc⟩ := hspan
+ apply (htransfer _).mp
+ exact quotientCoordinate_reconstruct W' M' _ (mem_append_of_difference W' M' _ c ((htransfer c).mpr hc))
+
+omit [DecidableEq K] in
+theorem mem_greedyIndices_iff_no_prefix_coordinates {V : Type*} [AddCommGroup V] [Module K V]
+ (f : Fin n → V) (j : Fin n) :
+ j ∈ greedyIndices K f ↔ ¬∃ c : Fin j.val → K, f j = ∑ i, c i • f (Fin.castLE j.isLt.le i) := by
+ have hpre : Set.range (f ∘ Fin.castLE j.isLt.le) = f '' Set.Iio j := by
+ rw [Set.range_comp, Fin.range_castLE]
+ rfl
+ rw [mem_greedyIndices, ← hpre, Submodule.mem_span_range_iff_exists_fun K]
+ simp only [Function.comp_apply, eq_comm]
+
+end RankQuery
+
+namespace RadicalCertificate
+
+open MvPolynomial RankQuery
+
+variable {K E ι : Type*} [Field K] [Fintype K] [Field E] [Algebra K E] [Fintype ι]
+variable {t n : ℕ}
+
+/-- The D.1 row test for representing one polynomial by a linear combination of a list. -/
+theorem poweredDifference_relation_iff (F : ι → MvPolynomial (Fin t) K)
+ (p : Fin n → MvPolynomial (Fin t) K) (target : MvPolynomial (Fin t) K) (c : Fin n → K)
+ {H s R₀ d : ℕ} (hHP : H ≤ Fintype.card K ^ s) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (hp : ∀ j, (p j).totalDegree ≤ R₀) (ht : target.totalDegree ≤ R₀)
+ (bound : WeakCertificateBound E (Option ι) (t + 1) (max d (R₀ + 1)) H) :
+ let P := Fintype.card K ^ s
+ let L := H + P * R₀
+ (∀ x : Fin t → E, (∀ i, aeval x (F i) = 0) →
+ aeval x target = ∑ j, c j • aeval x (p j)) ↔
+ coefficientRow (L + d) (target ^ P) - ∑ j, c j • coefficientRow (L + d) (p j ^ P) ∈
+ Submodule.span K (Set.range (macaulayMatrix F L (L + d)).row) := by
+ let polys : Option (Fin n) → MvPolynomial (Fin t) K := Option.elim' target p
+ let scalars : Option (Fin n) → K := Option.elim' 1 (fun j ↦ -c j)
+ have hdeg : ∀ j, (polys j).totalDegree ≤ R₀ := by
+ rintro (_ | j)
+ · exact ht
+ · exact hp j
+ have h := poweredRows_relation_iff F polys scalars hHP hF hdeg bound
+ dsimp only at h ⊢
+ simpa only [polys, scalars, Fintype.sum_option, Option.elim'_none, Option.elim'_some,
+ one_smul, neg_smul, Finset.sum_neg_distrib, ← sub_eq_add_neg, sub_eq_zero] using h
+
+/-- The row criterion as an equality in the reduced coordinate algebra. -/
+theorem poweredDifference_class_iff (F : ι → MvPolynomial (Fin t) K)
+ (p : Fin n → MvPolynomial (Fin t) K) (target : MvPolynomial (Fin t) K) (c : Fin n → K)
+ {H s R₀ d : ℕ} (hHP : H ≤ Fintype.card K ^ s) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (hp : ∀ j, (p j).totalDegree ≤ R₀) (ht : target.totalDegree ≤ R₀)
+ (bound : WeakCertificateBound E (Option ι) (t + 1) (max d (R₀ + 1)) H) :
+ let V := {x : Fin t → E | ∀ i, aeval x (F i) = 0}
+ let π := Ideal.Quotient.mkₐ K (vanishingIdeal K V)
+ let P := Fintype.card K ^ s
+ let L := H + P * R₀
+ π target = ∑ j, c j • π (p j) ↔
+ coefficientRow (L + d) (target ^ P) - ∑ j, c j • coefficientRow (L + d) (p j ^ P) ∈
+ Submodule.span K (Set.range (macaulayMatrix F L (L + d)).row) := by
+ intro V π P L
+ refine Iff.trans ?_ (poweredDifference_relation_iff F p target c hHP hF hp ht bound)
+ have hpoint (x : V) :
+ FiniteSlice.sliceEvaluation V (∑ j, c j • π (p j)) x = ∑ j, c j • aeval x.val (p j) := by
+ rw [map_sum, Finset.sum_apply]
+ simp only [map_smul, Pi.smul_apply]
+ rfl
+ constructor
+ · intro he x hx
+ exact (congrArg (fun a ↦ FiniteSlice.sliceEvaluation V a ⟨x, hx⟩) he).trans (hpoint ⟨x, hx⟩)
+ · intro he
+ apply FiniteSlice.sliceEvaluation_injective V
+ funext x
+ exact (he x.val x.prop).trans (hpoint x).symm
+
+variable [DecidableEq K] {w m L D : ℕ}
+
+/-- Query the coordinates of a polynomial from the Macaulay rows followed by
+the powered rows of the supplied list. Both finite indexings of the Macaulay
+matrix are explicit, so the query can use the paper's monomial order. -/
+noncomputable def macaulayCoordinateQuery (F : ι → MvPolynomial (Fin t) K)
+ (p : Fin n → MvPolynomial (Fin t) K) (target : MvPolynomial (Fin t) K) (P : ℕ)
+ (rows : Fin w ≃ ι × BoundedMonomial t L) (cols : Fin m ≃ BoundedMonomial t D) : Fin n → K :=
+ indexedQuotientCoordinate (macaulayMatrix F L D) (fun j ↦ coefficientRow D (p j ^ P))
+ rows cols (coefficientRow D (target ^ P))
+
+/-- The determinant query on the actual Macaulay matrix reconstructs any target
+class in the span of the queried polynomials. The degree hypothesis is the
+effective weak Nullstellensatz bound used in D.1. -/
+theorem macaulayCoordinateQuery_reconstruct (F : ι → MvPolynomial (Fin t) K)
+ (p : Fin n → MvPolynomial (Fin t) K) (target : MvPolynomial (Fin t) K)
+ {H s R₀ d : ℕ} (hHP : H ≤ Fintype.card K ^ s) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (hp : ∀ j, (p j).totalDegree ≤ R₀) (ht : target.totalDegree ≤ R₀)
+ (bound : WeakCertificateBound E (Option ι) (t + 1) (max d (R₀ + 1)) H)
+ (rows : Fin w ≃ ι × BoundedMonomial t (H + Fintype.card K ^ s * R₀))
+ (cols : Fin m ≃ BoundedMonomial t (H + Fintype.card K ^ s * R₀ + d)) :
+ let V := {x : Fin t → E | ∀ i, aeval x (F i) = 0}
+ let π := Ideal.Quotient.mkₐ K (vanishingIdeal K V)
+ π target ∈ Submodule.span K (Set.range (fun j ↦ π (p j))) →
+ π target = ∑ j, macaulayCoordinateQuery F p target (Fintype.card K ^ s) rows cols j • π (p j) := by
+ intro V π hspan
+ let P := Fintype.card K ^ s
+ let L := H + P * R₀
+ let W := macaulayMatrix F L (L + d)
+ let M : Matrix (Fin n) (BoundedMonomial t (L + d)) K := fun j ↦ coefficientRow (L + d) (p j ^ P)
+ let v := coefficientRow (L + d) (target ^ P)
+ have hclass (c : Fin n → K) := poweredDifference_class_iff F p target c hHP hF hp ht bound
+ apply (hclass _).mpr
+ apply indexedQuotientCoordinate_reconstruct W M rows cols v
+ obtain ⟨c, hc⟩ := (Submodule.mem_span_range_iff_exists_fun K).mp hspan
+ exact ⟨c, (hclass c).mp hc.symm⟩
+
+omit [DecidableEq K] in
+/-- After the Macaulay prefix, exactly the greedy basis indices in the reduced
+coordinate algebra are selected, in the given order of the polynomial list. -/
+theorem macaulay_greedyIndex_iff (F : ι → MvPolynomial (Fin t) K)
+ (p : Fin n → MvPolynomial (Fin t) K)
+ {H s R₀ d : ℕ} (hHP : H ≤ Fintype.card K ^ s) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (hp : ∀ j, (p j).totalDegree ≤ R₀)
+ (bound : WeakCertificateBound E (Option ι) (t + 1) (max d (R₀ + 1)) H)
+ (rows : Fin w ≃ ι × BoundedMonomial t (H + Fintype.card K ^ s * R₀))
+ (cols : Fin m ≃ BoundedMonomial t (H + Fintype.card K ^ s * R₀ + d)) (j : Fin n) :
+ let V := {x : Fin t → E | ∀ i, aeval x (F i) = 0}
+ let π := Ideal.Quotient.mkₐ K (vanishingIdeal K V)
+ let P := Fintype.card K ^ s
+ let L := H + P * R₀
+ let W := macaulayMatrix F L (L + d)
+ let M : Matrix (Fin n) (BoundedMonomial t (L + d)) K := fun i ↦ coefficientRow (L + d) (p i ^ P)
+ j.natAdd w ∈ greedyIndices K (appendRows (W.submatrix rows cols) (M.submatrix id cols)).row ↔
+ j ∈ greedyIndices K (fun i ↦ π (p i)) := by
+ intro V π P L W M
+ rw [mem_appendRows_greedy_iff, mem_greedyIndices_iff_no_prefix_coordinates,
+ mem_greedyIndices_iff_no_prefix_coordinates]
+ apply not_congr
+ apply exists_congr
+ intro c
+ let inc := Fin.castLE j.isLt.le
+ let S := Submodule.span K (Set.range (W.submatrix rows cols).row)
+ let diff := M j ∘ cols - ∑ i, c i • (M (inc i) ∘ cols)
+ have hdiff : S.mkQ (M j ∘ cols) = ∑ i, c i • S.mkQ (M (inc i) ∘ cols) ↔ diff ∈ S := by
+ have hz : S.mkQ diff = 0 ↔ diff ∈ S := Submodule.Quotient.mk_eq_zero _
+ simpa only [diff, map_sub, map_sum, map_smul, sub_eq_zero] using hz
+ refine hdiff.trans ?_
+ apply (reindexed_difference_mem_iff W (M.submatrix inc id) rows cols (M j) c).trans
+ exact (poweredDifference_class_iff F (p ∘ inc) (p j) c hHP hF (fun i ↦ hp (inc i)) (hp j) bound).symm
+
+/-- The coordinate query returns zero off the selected polynomial basis in
+the reduced algebra, including for repeated or zero polynomial classes. -/
+theorem macaulayCoordinateQuery_eq_zero (F : ι → MvPolynomial (Fin t) K)
+ (p : Fin n → MvPolynomial (Fin t) K) (target : MvPolynomial (Fin t) K)
+ {H s R₀ d : ℕ} (hHP : H ≤ Fintype.card K ^ s) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (hp : ∀ j, (p j).totalDegree ≤ R₀)
+ (bound : WeakCertificateBound E (Option ι) (t + 1) (max d (R₀ + 1)) H)
+ (rows : Fin w ≃ ι × BoundedMonomial t (H + Fintype.card K ^ s * R₀))
+ (cols : Fin m ≃ BoundedMonomial t (H + Fintype.card K ^ s * R₀ + d)) (j : Fin n) :
+ let V := {x : Fin t → E | ∀ i, aeval x (F i) = 0}
+ let π := Ideal.Quotient.mkₐ K (vanishingIdeal K V)
+ j ∉ greedyIndices K (fun i ↦ π (p i)) →
+ macaulayCoordinateQuery F p target (Fintype.card K ^ s) rows cols j = 0 := by
+ intro V π hj
+ apply originalRowCoordinate_eq_zero
+ exact (macaulay_greedyIndex_iff F p hHP hF hp bound rows cols j).not.mpr hj
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayEntryExecution.lean b/lean/OAI/Computability/VPVNP/MacaulayEntryExecution.lean
new file mode 100644
index 0000000000..95aea09f96
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayEntryExecution.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.MacaulayEntryPhase
+
+/-! # Execution of the shifted and powered coefficient arms
+
+The two ordinal scans run on the source and column words issued by the row
+decoder. The divisibility and equality flags below come from the actual scans
+and determine the subsequent bit-stack computation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.Arms
+
+open BurstRAM RAMTape UniversalCountStack MacaulayRowDispatch RadicalCertificate.MonomialIndex
+
+variable {K : Type} [DecidableEq K] {w A S : ℕ}
+
+omit [DecidableEq K] in
+private theorem start_room (rs : Reg → Word w) (d : Bool → PairCall.Inputs) (v : Bool → List Bool)
+ (aux : Stacks K) (pre : Preload (w := w) A d v aux) :
+ ∀ z, (frame rs [] (storage w d blank blank v aux) z).length ≤ A :=
+ frame_bound rs [] d blank blank v aux pre.words (by simp) pre.arity (by simp [blank]) (by simp [blank]) pre.scalars pre.payload
+
+/-- Complete shifted-monomial matrix read. The chosen leaf receives exactly
+the coordinatewise difference and is skipped when the multiplier fails to
+divide the column. -/
+theorem equation_execution (rs : Reg → Word w) (data : Bool → PairCall.Inputs) (constants : Bool → List Bool)
+ (aux : Stacks K) (pre : Preload (w := w) A data constants aux) (hw : 1 ≤ w)
+ (leaf : FiniteRoutine (Ports K)) (ans : List Bool) (ha : ans.length ≤ A) (leafTicks : ℕ)
+ (k : PairCall.Ordinals (addressed rs (data false)))
+ (hk : ∀ b, (addressed rs (data false)).ordinal b = (k b).val)
+ (fit : ∀ b, RadicalCertificate.MonomialIndex.ISA.Fits
+ (RadicalCertificate.MonomialIndex.ISA.graded (data false).arity ((data false).degree b) (k b)) w)
+ (ss : PairCall.equationSpace w A (data false) ≤ S) (trans : transient A (data false).arity w ≤ S) :
+ let d := addressed rs (data false)
+ let a := PairCall.monomial d k false
+ let c := PairCall.monomial d k true
+ let pack := selected false (PairCall.difference w a c)
+ let flag := selected false (digits w (decide (a.val ≤ c.val)).toNat)
+ (a.val ≤ c.val → ∃ n ≤ leafTicks, ∃ rest : List Bool, rest.length ≤ d.arity*w ∧
+ leaf.BoundedRun S n (frame rs [] (storage w data pack flag constants aux))
+ (frame rs ans (storage w data (selected false rest) flag constants aux))) →
+ ∃ n ≤ PairCall.scanClock w A d + PairCall.packClock d.arity w A + PairCall.clearCost w + postTicks A d.arity w leafTicks,
+ (phase false leaf).BoundedRun S n (frame rs [] (storage w data blank blank constants aux))
+ (frame rs (if a.val ≤ c.val then ans else constants false) (storage w data blank blank constants aux)) := by
+ intro d a c pack flag yes
+ have hA : A ≤ S := by dsimp [transient] at trans; omega
+ obtain ⟨ns,hs,run⟩ := PairCall.equation_runs d k hk fit [] [] pre.words (pre.arity false) (by simp) (by simp)
+ have run' := scan_bounded PairCall.equation false rs [] data blank blank constants aux
+ (PairCall.difference w a c) (digits w (decide (a.val ≤ c.val)).toNat)
+ (by simpa only [List.append_nil] using run.mono_cap ss)
+ (fun z => (start_room rs data constants aux pre z).trans hA)
+ have out := complete_phase hw false (decide (a.val ≤ c.val)) rs data constants aux pre trans leaf
+ (PairCall.difference w a c) ans (by simp [a, c, d, addressed]) ha ⟨ns,hs,run'⟩
+ (fun h => yes (of_decide_eq_true h))
+ obtain ⟨v,hv,vr⟩ := out
+ refine ⟨v,hv,?_⟩
+ have same : (if decide (a.val ≤ c.val) then ans else constants false) =
+ (if a.val ≤ c.val then ans else constants false) := by
+ by_cases h : a.val ≤ c.val
+ · rw [ite_eq_left (decide_eq_true h), ite_eq_left h]
+ · rw [ite_eq_right (fun e => h (of_decide_eq_true e)), ite_eq_right h]
+ exact same ▸ vr
+
+/-- Complete powered-monomial read. The successful equality flag emits the
+stored unit scalar, and an unequal exponent emits zero. This code also
+handles marked or Frobenius targets via the scan's `scale` and `mark` words. -/
+theorem powered_execution (rs : Reg → Word w) (data : Bool → PairCall.Inputs) (constants : Bool → List Bool)
+ (aux : Stacks K) (pre : Preload (w := w) A data constants aux) (hw : 1 ≤ w)
+ (k : PairCall.Ordinals (addressed rs (data true)))
+ (hk : ∀ b, (addressed rs (data true)).ordinal b = (k b).val)
+ (fit : ∀ b, RadicalCertificate.MonomialIndex.ISA.Fits
+ (RadicalCertificate.MonomialIndex.ISA.graded (data true).arity ((data true).degree b) (k b)) w)
+ (hfit : ExponentISA.Fits (PairCall.powerParams (data true)) w)
+ (ss : PairCall.poweredSpace w A ≤ S) (trans : transient A (data true).arity w ≤ S) :
+ let d := addressed rs (data true)
+ let matched := PairCall.powerMatch d (PairCall.monomial d k false) (PairCall.monomial d k true)
+ ∃ n ≤ PairCall.scanClock w A d + PairCall.powerClock d.arity w A + PairCall.clearCost w + postTicks A d.arity w (5*A+2),
+ (phase true (emit true)).BoundedRun S n (frame rs [] (storage w data blank blank constants aux))
+ (frame rs (constants matched) (storage w data blank blank constants aux)) := by
+ intro d matched
+ have hA : A ≤ S := by dsimp [transient] at trans; omega
+ obtain ⟨ns,hs,run⟩ := PairCall.powered_runs d k hk fit hfit [] [] pre.words (pre.arity true) (by simp) (by simp)
+ have run' := scan_bounded PairCall.powered true rs [] data blank blank constants aux [] (digits w matched.toNat)
+ (by simpa only [List.append_nil] using run.mono_cap ss) (fun z => (start_room rs data constants aux pre z).trans hA)
+ have out := complete_phase hw true matched rs data constants aux pre trans (emit true) [] (constants true)
+ (by simp) (pre.scalars true) ⟨ns,hs,run'⟩ (leafTicks := 5*A+2) (fun _ => by
+ have len := pre.scalars true
+ refine ⟨_,by omega,[],by simp,spaceRun_of_steps (emit_runs rs true data (selected true [])
+ (selected true (digits w matched.toNat)) constants aux) ?_⟩
+ intro z
+ have cap := frame_bound rs [] data (selected true []) (selected true (digits w matched.toNat)) constants aux pre.words
+ (by simp) pre.arity (by intro b; cases b <;> simp [selected, blank])
+ (by intro b; cases b <;> simp [selected,blank,pre.words]) pre.scalars pre.payload z
+ exact (Nat.add_le_add cap (Nat.le_refl _)).trans (by dsimp [transient] at trans; omega))
+ have sel : (if matched then constants true else constants false) = constants matched := by cases matched <;> rfl
+ rwa [sel] at out
+
+end RankQuery.Stack.MacaulayRead.Arms
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayEntryPhase.lean b/lean/OAI/Computability/VPVNP/MacaulayEntryPhase.lean
new file mode 100644
index 0000000000..cc3a54a934
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayEntryPhase.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.MacaulayReadFinish
+
+/-! # Whole execution of a coefficient or powered-row arm
+
+Every call starts with empty exponent and flag buffers, and returns with both
+empty. An equation lookup is invoked only when all monomial coordinates can
+be subtracted. A powered row selects a constant encoding directly. The space
+budget accounts for a single live exponent buffer and a single scalar call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.Arms
+
+open BurstRAM RAMTape UniversalCountStack MacaulayRowDispatch RadicalCertificate.MonomialIndex
+
+variable {K : Type} [DecidableEq K]
+
+/-- Run the appropriate monomial scan for an equation or powered row, then use its flag to
+complete the scalar lookup. -/
+def phase (power : Bool) (leaf : FiniteRoutine (Ports K)) : FiniteRoutine (Ports K) :=
+ let scan := if power then PairCall.powered else PairCall.equation
+ (scan.onPorts (pairPorts power)).followedBy (finish power leaf)
+
+/-- Both of the Boolean-indexed temporary buffers contain empty bit stacks. -/
+abbrev blank : Bool → List Bool := fun _ => []
+
+/-- Place the given bits in the chosen buffer and leave the other buffer empty. -/
+def selected (b : Bool) (xs : List Bool) : Bool → List Bool := Function.update blank b xs
+
+private theorem erase_selected (b : Bool) (x : List Bool) : Function.update (selected b x) b [] = blank := by
+ rw [selected, Function.update_idem, show [] = blank b from rfl, Function.update_eq_self]
+
+/-- Common space for registers, immutable data, a dense residual vector and
+flag, and either a scalar copy or final buffer cleanup. -/
+def transient (A t w : ℕ) := (A + t*w+w) + (5*A + t*w+w+4)
+
+/-- Tick allowance after the monomial scan, including scalar selection or evaluation and
+cleanup of the exponent and flag buffers. -/
+def postTicks (A t w scalarTicks : ℕ) := 2 + max (5*A+2) scalarTicks + (t*w+1+(w+1))
+
+/-- A common stack bound for the register words, unary arity markers, scalar constants and
+auxiliary reader advice. -/
+structure Preload {w : ℕ} (A : ℕ) (data : Bool → PairCall.Inputs) (constants : Bool → List Bool)
+ (aux : Stacks K) : Prop where
+ words : w ≤ A
+ arity : ∀ b, (data b).arity ≤ A
+ scalars : ∀ b, (constants b).length ≤ A
+ payload : ∀ k, (aux k).length ≤ A
+
+omit [DecidableEq K] in
+private theorem phase_room {w A t : ℕ} {data : Bool → PairCall.Inputs} {constants : Bool → List Bool} {aux : Stacks K}
+ (pre : Preload (w := w) A data constants aux) (rs : Reg → Word w) (res : List Bool)
+ (hr : res.length ≤ A) (b : Bool) (buf flag : List Bool) (hp : buf.length ≤ t*w) (hf : flag.length ≤ w) :
+ ∀ z, (frame rs res (storage w data (selected b buf) (selected b flag) constants aux) z).length ≤ A+t*w+w := by
+ apply frame_bound
+ · omega
+ · omega
+ · intro j; exact (pre.arity j).trans (by omega)
+ · intro j; by_cases hj : j=b <;> simp [selected, blank, hj]; omega
+ · intro j; by_cases hj : j=b <;> simp [selected, blank, hj]; omega
+ · intro j; exact (pre.scalars j).trans (by omega)
+ · intro j; exact (pre.payload j).trans (by omega)
+
+/-- Append a flag-selected coefficient or constant call to a native scan,
+then reset both buffers. A coefficient routine may consume its exponent
+buffer or leave it for the common cleanup stage. -/
+theorem complete_phase {w A S t scanTicks leafTicks : ℕ} (hw : 1 ≤ w) (b matched : Bool)
+ (rs : Reg → Word w) (data : Bool → PairCall.Inputs) (constants : Bool → List Bool) (aux : Stacks K)
+ (pre : Preload (w := w) A data constants aux) (hs : transient A t w ≤ S)
+ (leaf : FiniteRoutine (Ports K)) (buf result : List Bool) (hp : buf.length ≤ t*w) (hv : result.length ≤ A)
+ (scan : ∃ cost ≤ scanTicks, ((if b then PairCall.powered else PairCall.equation).onPorts (pairPorts b)).BoundedRun S cost
+ (frame rs [] (storage w data blank blank constants aux))
+ (frame rs [] (storage w data (selected b buf) (selected b (digits w matched.toNat)) constants aux)))
+ (yes : matched = true → ∃ n ≤ leafTicks, ∃ rest : List Bool, rest.length ≤ t*w ∧
+ leaf.BoundedRun S n (frame rs [] (storage w data (selected b buf) (selected b (digits w matched.toNat)) constants aux))
+ (frame rs result (storage w data (selected b rest) (selected b (digits w matched.toNat)) constants aux))) :
+ ∃ n ≤ scanTicks + postTicks A t w leafTicks, (phase b leaf).BoundedRun S n
+ (frame rs [] (storage w data blank blank constants aux))
+ (frame rs (if matched then result else constants false) (storage w data blank blank constants aux)) := by
+ obtain ⟨u,hu,scanrun⟩ := scan
+ let flag := selected b (digits w matched.toNat)
+ have hflag : flag b = digits w matched.toNat := Function.update_self ..
+ have hf : (flag b).length = w := hflag ▸ length_digits ..
+ have work : ∃ n ≤ max (5*A+2) leafTicks, ∃ rest : List Bool, rest.length ≤ t*w ∧
+ (if matched then leaf else emit false).BoundedRun S n (frame rs [] (storage w data (selected b buf) flag constants aux))
+ (frame rs (if matched then result else constants false) (storage w data (selected b rest) flag constants aux)) := by
+ cases matched with
+ | true =>
+ obtain ⟨n,hn,rest,hr,h⟩ := yes rfl
+ exact ⟨n,hn.trans (le_max_right ..),rest,hr,h⟩
+ | false =>
+ have hl : 5*(constants false).length+2 ≤ 5*A+2 := by have := pre.scalars false; omega
+ refine ⟨_,hl.trans (le_max_left ..),buf,hp,spaceRun_of_steps (emit_runs rs false data (selected b buf) flag constants aux) ?_⟩
+ intro z
+ have hm := phase_room pre rs [] (by simp) b buf (digits w 0) hp (by simp) z
+ change _ + _ ≤ S
+ dsimp only [transient] at hs
+ exact (Nat.add_le_add hm hl).trans (by omega)
+ obtain ⟨n,hn,rest,hr,call⟩ := work
+ have hor : (if matched then result else constants false).length ≤ A := by cases matched; exact pre.scalars false; exact hv
+ have done := finish_bounded rs b matched data (selected b buf) flag constants aux leaf _ (selected b rest) hw hflag call (fun z => by
+ have cap := phase_room pre rs _ hor b rest (digits w matched.toNat) hr (by simp) z
+ have hlen : (selected b rest b).length = rest.length := by simp [selected]
+ dsimp only [transient] at hs
+ change _ + (_ + 1 + (_ + 1)) ≤ S
+ exact (Nat.add_le_add cap (show (selected b rest b).length + 1 + ((flag b).length+1) ≤ t*w+1+(w+1) by omega)).trans (by omega))
+ rw [erase_selected, show Function.update flag b [] = blank from erase_selected ..] at done
+ refine ⟨_, ?_, scanrun.followedBy done⟩
+ have hlen : (selected b rest b).length = rest.length := by simp [selected]
+ dsimp only [postTicks]; omega
+
+end RankQuery.Stack.MacaulayRead.Arms
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayExponentISA.lean b/lean/OAI/Computability/VPVNP/MacaulayExponentISA.lean
new file mode 100644
index 0000000000..58a95fd40f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayExponentISA.lean
@@ -0,0 +1,434 @@
+import OAI.Computability.VPVNP.MacaulayIndexISA
+import OAI.Computability.VPVNP.MacaulayRowIndex
+
+/-!
+# Fixed binary control for a shifted coefficient row
+
+The two input words hold the exponent blocks of the source monomial and
+the coefficient column. They can use different radices. The program checks
+every coordinate, reports equality and divisibility, and returns any requested
+digit of the residual. Marking one label before scaling covers multiplication
+by that label. A scalar multiplier also covers the Frobenius query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.ExponentISA
+
+open BurstRAM BurstRAM.PrivateRAM RAMTape.RegisterTable ISA
+
+/-- Input registers store the source radix, column radix, multiplier, marked
+coordinate and requested coordinate. Both coordinates use one-based numbers,
+with zero disabling the mark or the requested output. -/
+structure Parameters where
+ /-- Radix used to extract a variable exponent from the source monomial. -/
+ sourceBase : ℕ
+ /-- Radix used to extract a variable exponent from the column monomial. -/
+ columnBase : ℕ
+ /-- Factor applied to each source exponent after adding the possible one-variable shift. -/
+ scale : ℕ
+ /-- One-based coordinate at which to increase the source exponent by one before scaling. Zero
+ disables the shift. -/
+ mark : ℕ
+ /-- One-based coordinate of the exponent difference to retain. Zero requests no output digit. -/
+ request : ℕ
+
+/-- Register values maintained while comparing the shifted and scaled source exponents with the
+column exponents. -/
+structure Work where
+ /-- Number of exponent digits still to compare. It also gives the one-based coordinate of the
+ next low radix digit. -/
+ remaining : ℕ
+ /-- Unprocessed part of the source radix block after removing the low digits already visited. -/
+ source : ℕ
+ /-- Unprocessed part of the column radix block after removing the low digits already visited. -/
+ column : ℕ
+ /-- Stored column exponent minus the shifted source exponent at the requested coordinate,
+ truncated at zero. -/
+ residual : ℕ := 0
+ /-- Running conjunction of the coordinatewise inequalities needed for the shifted and scaled
+ source monomial to divide the column. -/
+ divides : Bool := true
+ /-- Running conjunction of the exponent equalities for the shifted and scaled source and the
+ column. -/
+ same : Bool := true
+ /-- Current source exponent after the optional one-coordinate shift and scaling. -/
+ sourceDigit : ℕ := 0
+ /-- Current exponent extracted from the low digit of the column block. -/
+ columnDigit : ℕ := 0
+
+/-- Registers 5--12 hold the work record, and the last two hold one and zero. -/
+def registers (w : ℕ) (p : Parameters) (s : Work) (j : Fin 15) : Word w :=
+ word w <| match j.val with
+ | 0 => p.sourceBase
+ | 1 => p.columnBase
+ | 2 => p.scale
+ | 3 => p.mark
+ | 4 => p.request
+ | 5 => s.remaining
+ | 6 => s.source
+ | 7 => s.column
+ | 8 => s.residual
+ | 9 => s.divides.toNat
+ | 10 => s.same.toNat
+ | 11 => s.sourceDigit
+ | 12 => s.columnDigit
+ | 13 => 1
+ | _ => 0
+
+/-- Fixed 18-instruction register table that compares the two exponent blocks and retains the
+requested residual digit. -/
+def table : Template 18 15 0 where
+ literalWidth := 1
+ entry := 0
+ code j := match j.val with
+ | 0 => .jumpEq 5 14 17 1
+ | 1 => .binary .mod 11 6 0 2
+ | 2 => .binary .mod 12 7 1 3
+ | 3 => .jumpEq 5 3 4 5
+ | 4 => .binary .add 11 11 13 5
+ | 5 => .binary .mul 11 2 11 6
+ | 6 => .jumpLt 12 11 7 8
+ | 7 => .constant 9 0 8
+ | 8 => .jumpEq 11 12 10 9
+ | 9 => .constant 10 0 10
+ | 10 => .jumpEq 5 4 11 14
+ | 11 => .jumpLt 12 11 12 13
+ | 12 => .constant 8 0 14
+ | 13 => .binary .sub 8 12 11 14
+ | 14 => .binary .div 6 6 0 15
+ | 15 => .binary .div 7 7 1 16
+ | 16 => .binary .sub 5 5 13 0
+ | _ => .accept
+
+/-- Constraints used at the physical arithmetic and comparison instructions. -/
+structure Fits (p : Parameters) (w : ℕ) : Prop where
+ one_lt : 1 < 2^w
+ source_pos : 0 < p.sourceBase
+ column_pos : 0 < p.columnBase
+ source_lt : p.sourceBase < 2^w
+ column_lt : p.columnBase < 2^w
+ scale_lt : p.scale < 2^w
+ product_lt : p.scale*p.sourceBase < 2^w
+ mark_lt : p.mark < 2^w
+ request_lt : p.request < 2^w
+
+/-- Execution of the exponent-comparison table for exactly n steps between the two indicated
+control locations and work records. -/
+abbrev Trace (w : ℕ) (p : Parameters) (n : ℕ) (pc : Fin 18) (s : Work) (pc' : Fin 18) (s' : Work) :=
+ Runs table (Fin.elim0 : Fin 0 → Word w) 0 n pc (registers w p s) pc' (registers w p s')
+
+private abbrev Block (w : ℕ) (p : Parameters) (n : ℕ) (pc : Fin 18) (s : Work) (pc' : Fin 18) (s' : Work) :=
+ ∃ k ≤ n, Trace w p k pc s pc' s'
+
+private theorem chain {w n m : ℕ} {p : Parameters} {pc pc' pc'' : Fin 18} {s t u : Work}
+ (a : Block w p n pc s pc' t) (b : Block w p m pc' t pc'' u) : Block w p (n+m) pc s pc'' u := by
+ obtain ⟨j,hj,hr⟩ := a
+ obtain ⟨k,hk,hs⟩ := b
+ exact ⟨_, Nat.add_le_add hj hk, hr.trans hs⟩
+
+private theorem word_lt {w a b : ℕ} (ha : a < 2^w) (hb : b < 2^w) :
+ word w a < word w b ↔ a < b := by simp [word, Fin.lt_def, Nat.mod_eq_of_lt, ha, hb]
+
+private theorem eval_mul (w a b : ℕ) :
+ BinaryOp.mul.eval (word w a) (word w b) = word w (a*b) := by
+ apply Fin.ext
+ simp only [BinaryOp.eval, word, Fin.val_mul, Fin.val_ofNat]
+ exact (Nat.mul_mod ..).symm
+
+private theorem eval_sub {w a b : ℕ} (ha : a < 2^w) (hb : b < 2^w) (hle : b ≤ a) :
+ BinaryOp.sub.eval (word w a) (word w b) = word w (a-b) := by
+ have hword : word w b ≤ word w a := le_of_not_gt (fun h => hle.not_gt ((word_lt ha hb).mp h))
+ apply Fin.ext
+ change (word w a - word w b).val = _
+ rw [Fin.sub_val_of_le hword]
+ simp [word, Nat.mod_eq_of_lt, ha, hb, (Nat.sub_le a b).trans_lt ha]
+
+private theorem write_eq {w : ℕ} (p : Parameters) (s s' : Work) (i : Fin 15) (v : Word w)
+ (hi : registers w p s' i = v) (hrest : ∀ j ≠ i, registers w p s j = registers w p s' j) :
+ Function.update (registers w p s) i v = registers w p s' := by
+ funext j
+ by_cases h : j = i
+ · subst j; simp [hi]
+ · simp [Function.update_of_ne h, hrest j h]
+
+local macro "writeReg" : tactic => `(tactic|
+ (simp only [Option.some.injEq, Prod.mk.injEq, true_and]
+ apply write_eq
+ · rfl
+ · intro j hj; fin_cases j <;> first | rfl | exact (hj rfl).elim))
+
+private abbrev wordStep (w : ℕ) (p : Parameters) (j : Fin 18) (s : Work) :=
+ step (table.code j) Fin.elim0 (0 : Word w) (registers w p s)
+
+/-- Extract the low source digit, add one when the coordinate is marked, then multiply by the
+query's scale. -/
+def scaledDigit (p : Parameters) (position source : ℕ) : ℕ :=
+ p.scale * (source % p.sourceBase + if position = p.mark then 1 else 0)
+
+private def readDigits (p : Parameters) (s : Work) : Work :=
+ {s with sourceDigit := scaledDigit p s.remaining s.source, columnDigit := s.column%p.columnBase}
+
+private theorem read_block {w : ℕ} (p : Parameters) (h : Fits p w) (s : Work)
+ (hr : 0 < s.remaining) (hrw : s.remaining < 2^w) (hs : s.source < 2^w) (hc : s.column < 2^w) :
+ Block w p 6 0 s 6 (readDigits p s) := by
+ let u := {s with sourceDigit := s.source%p.sourceBase}
+ let v := {u with columnDigit := s.column%p.columnBase}
+ have h₀ : wordStep w p 0 s = some (1, registers w p s) := by
+ change some (if word w s.remaining = word w 0 then _ else _, _) = _
+ simp [word_eq hrw (Nat.two_pow_pos _), hr.ne']
+ have h₁ : wordStep w p 1 s = some (2, registers w p u) := by
+ change some (2, Function.update (registers w p s) 11 (BinaryOp.mod.eval (word w s.source) (word w p.sourceBase))) = _
+ rw [eval_mod hs h.source_lt]; writeReg
+ have h₂ : wordStep w p 2 u = some (3, registers w p v) := by
+ change some (3, Function.update (registers w p u) 12 (BinaryOp.mod.eval (word w s.column) (word w p.columnBase))) = _
+ rw [eval_mod hc h.column_lt]; writeReg
+ have h₃ : wordStep w p 3 v = some (if s.remaining = p.mark then 4 else 5, registers w p v) := by
+ change some (if word w s.remaining = word w p.mark then _ else _, _) = _
+ simp [word_eq hrw h.mark_lt]
+ let marked := {v with sourceDigit := v.sourceDigit + (if s.remaining = p.mark then 1 else 0)}
+ have hm : Block w p 2 3 v 5 marked := by
+ by_cases he : s.remaining = p.mark
+ · rw [ite_eq_left he] at h₃
+ have h₄ : wordStep w p 4 v = some (5, registers w p marked) := by
+ change some (5, Function.update (registers w p v) 11 (BinaryOp.add.eval (word w v.sourceDigit) (word w 1))) = _
+ rw [eval_add]
+ simp only [marked, ite_eq_left he]; writeReg
+ exact ⟨2, le_rfl, .cons h₃ (.one h₄)⟩
+ · rw [ite_eq_right he] at h₃
+ have hh : marked = v := by simp [marked, he]
+ rw [hh]
+ exact ⟨1, by decide, Runs.one h₃⟩
+ have h₅ : wordStep w p 5 marked = some (6, registers w p (readDigits p s)) := by
+ change some (6, Function.update (registers w p marked) 11 (BinaryOp.mul.eval (word w p.scale) (word w marked.sourceDigit))) = _
+ rw [eval_mul]; writeReg
+ have hpre : Block w p 3 0 s 3 v := ⟨3, le_rfl, .cons h₀ (.cons h₁ (.one h₂))⟩
+ exact chain (chain hpre hm) ⟨1, le_rfl, .one h₅⟩
+
+
+private def compareDigits (s : Work) : Work :=
+ {s with
+ divides := s.divides && decide (s.sourceDigit ≤ s.columnDigit)
+ same := s.same && decide (s.sourceDigit = s.columnDigit)}
+
+private theorem compare_block {w : ℕ} (p : Parameters) (s : Work)
+ (ha : s.sourceDigit < 2^w) (hb : s.columnDigit < 2^w) :
+ Block w p 4 6 s 10 (compareDigits s) := by
+ let u := {s with divides := s.divides && decide (s.sourceDigit ≤ s.columnDigit)}
+ have h₆ : wordStep w p 6 s = some (if s.columnDigit < s.sourceDigit then 7 else 8, registers w p s) := by
+ change some (if word w s.columnDigit < word w s.sourceDigit then _ else _, _) = _
+ simp [word_lt hb ha]
+ have hdiv : Block w p 2 6 s 8 u := by
+ by_cases he : s.columnDigit < s.sourceDigit
+ · rw [ite_eq_left he] at h₆
+ have h₇ : wordStep w p 7 s = some (8, registers w p u) := by
+ change some (8, Function.update (registers w p s) 9 (word w 0)) = _
+ simp only [u, Nat.not_le_of_gt he, decide_false, Bool.and_false]
+ writeReg
+ exact ⟨2, le_rfl, .cons h₆ (.one h₇)⟩
+ · rw [ite_eq_right he] at h₆
+ have hu : u = s := by simp [u, Nat.le_of_not_gt he]
+ rw [hu]
+ exact ⟨1, by decide, .one h₆⟩
+ have h₈ : wordStep w p 8 u = some (if s.sourceDigit = s.columnDigit then 10 else 9, registers w p u) := by
+ change some (if word w s.sourceDigit = word w s.columnDigit then _ else _, _) = _
+ simp [word_eq ha hb]
+ have heq : Block w p 2 8 u 10 (compareDigits s) := by
+ by_cases he : s.sourceDigit = s.columnDigit
+ · rw [ite_eq_left he] at h₈
+ have hh : compareDigits s = u := by simp [compareDigits, u, he]
+ rw [hh]
+ exact ⟨1, by decide, .one h₈⟩
+ · rw [ite_eq_right he] at h₈
+ have h₉ : wordStep w p 9 u = some (10, registers w p (compareDigits s)) := by
+ change some (10, Function.update (registers w p u) 10 (word w 0)) = _
+ simp only [compareDigits, he, decide_false, Bool.and_false]
+ writeReg
+ exact ⟨2, le_rfl, .cons h₈ (.one h₉)⟩
+ exact chain hdiv heq
+
+private def saveDigit (p : Parameters) (s : Work) : Work :=
+ {s with residual := if s.remaining = p.request then s.columnDigit-s.sourceDigit else s.residual}
+
+private theorem save_block {w : ℕ} (p : Parameters) (fit : Fits p w) (s : Work)
+ (hr : s.remaining < 2^w) (ha : s.sourceDigit < 2^w) (hb : s.columnDigit < 2^w) :
+ Block w p 3 10 s 14 (saveDigit p s) := by
+ have h₁₀ : wordStep w p 10 s = some (if s.remaining = p.request then 11 else 14, registers w p s) := by
+ change some (if word w s.remaining = word w p.request then _ else _, _) = _
+ simp [word_eq hr fit.request_lt]
+ by_cases he : s.remaining = p.request
+ · rw [ite_eq_left he] at h₁₀
+ have h₁₁ : wordStep w p 11 s = some (if s.columnDigit < s.sourceDigit then 12 else 13, registers w p s) := by
+ change some (if word w s.columnDigit < word w s.sourceDigit then _ else _, _) = _
+ simp [word_lt hb ha]
+ by_cases hlt : s.columnDigit < s.sourceDigit
+ · rw [ite_eq_left hlt] at h₁₁
+ have h₁₂ : wordStep w p 12 s = some (14, registers w p (saveDigit p s)) := by
+ change some (14, Function.update (registers w p s) 8 (word w 0)) = _
+ simp only [saveDigit, ite_eq_left he, Nat.sub_eq_zero_of_le hlt.le]
+ writeReg
+ exact ⟨3, le_rfl, .cons h₁₀ (.cons h₁₁ (.one h₁₂))⟩
+ · rw [ite_eq_right hlt] at h₁₁
+ have h₁₃ : wordStep w p 13 s = some (14, registers w p (saveDigit p s)) := by
+ change some (14, Function.update (registers w p s) 8 (BinaryOp.sub.eval (word w s.columnDigit)
+ (word w s.sourceDigit))) = _
+ rw [eval_sub hb ha (Nat.le_of_not_gt hlt)]
+ simp only [saveDigit, ite_eq_left he]
+ writeReg
+ exact ⟨3, le_rfl, .cons h₁₀ (.cons h₁₁ (.one h₁₃))⟩
+ · rw [ite_eq_right he] at h₁₀
+ have hh : saveDigit p s = s := by simp [saveDigit, he]
+ rw [hh]
+ exact ⟨1, by decide, .one h₁₀⟩
+
+private def advance (p : Parameters) (s : Work) : Work :=
+ {s with
+ remaining := s.remaining-1, source := s.source/p.sourceBase, column := s.column/p.columnBase}
+
+private theorem advance_block {w : ℕ} (p : Parameters) (fit : Fits p w) (s : Work) {n : ℕ}
+ (hr : s.remaining = n+1) (hrw : s.remaining < 2^w) (hs : s.source < 2^w) (hc : s.column < 2^w) :
+ Trace w p 3 14 s 0 (advance p s) := by
+ let u := {s with source := s.source/p.sourceBase}
+ let v := {u with column := s.column/p.columnBase}
+ have h₁₄ : wordStep w p 14 s = some (15, registers w p u) := by
+ change some (15, Function.update (registers w p s) 6 (BinaryOp.div.eval (word w s.source) (word w p.sourceBase))) = _
+ rw [eval_div hs fit.source_lt]; writeReg
+ have h₁₅ : wordStep w p 15 u = some (16, registers w p v) := by
+ change some (16, Function.update (registers w p u) 7 (BinaryOp.div.eval (word w s.column) (word w p.columnBase))) = _
+ rw [eval_div hc fit.column_lt]; writeReg
+ have h₁₆ : wordStep w p 16 v = some (0, registers w p (advance p s)) := by
+ change some (0, Function.update (registers w p v) 5 (BinaryOp.sub.eval (word w s.remaining) (word w 1))) = _
+ rw [hr, eval_sub_one (hr ▸ hrw) fit.one_lt]
+ simp only [advance, hr, Nat.add_one_sub_one]
+ writeReg
+ exact .cons h₁₄ (.cons h₁₅ (.one h₁₆))
+
+private def round (p : Parameters) (s : Work) : Work :=
+ advance p (saveDigit p (compareDigits (readDigits p s)))
+
+private theorem round_run {w : ℕ} (p : Parameters) (fit : Fits p w) (s : Work) {n : ℕ}
+ (hr : s.remaining = n+1) (hrw : s.remaining < 2^w) (hs : s.source < 2^w) (hc : s.column < 2^w) :
+ Block w p 16 0 s 0 (round p s) := by
+ let u := readDigits p s
+ let v := compareDigits u
+ let z := saveDigit p v
+ have hpre := read_block p fit s (by omega) hrw hs hc
+ have hmod := Nat.mod_lt s.source fit.source_pos
+ have ha : u.sourceDigit < 2^w := by
+ apply lt_of_le_of_lt _ fit.product_lt
+ apply Nat.mul_le_mul_left
+ split <;> omega
+ have hb : u.columnDigit < 2^w := (Nat.mod_lt _ fit.column_pos).trans fit.column_lt
+ have hcmp := compare_block p u ha hb
+ have hsave := save_block p fit v hrw ha hb
+ have hnext := advance_block p fit z hr hrw hs hc
+ exact chain (chain (chain hpre hcmp) hsave) ⟨3, le_rfl, hnext⟩
+
+private def model (p : Parameters) : ℕ → Work → Work
+ | 0, s => s
+ | r+1, s => model p r (round p s)
+
+private theorem model_run {w : ℕ} (p : Parameters) (fit : Fits p w) (s : Work) {r : ℕ}
+ (hr : s.remaining = r) (hrw : s.remaining < 2^w) (hs : s.source < 2^w) (hc : s.column < 2^w) :
+ Block w p (16*r+1) 0 s 17 (model p r s) := by
+ induction r generalizing s with
+ | zero =>
+ refine ⟨1, by simp, .one ?_⟩
+ change some (if word w s.remaining = word w 0 then _ else _, _) = _
+ simp [hr, model]
+ | succ r ih =>
+ have hrr : (round p s).remaining = r := by change s.remaining-1 = r; omega
+ have ht := ih (round p s) hrr (by omega) ((Nat.div_le_self ..).trans_lt hs) ((Nat.div_le_self ..).trans_lt hc)
+ have hbody := round_run p fit s hr hrw hs hc
+ rw [model]
+ convert chain hbody ht using 1; omega
+
+
+private def sourceAt (p : Parameters) (r a i : ℕ) :=
+ scaledDigit p (r-i) (a / p.sourceBase^i)
+
+private def columnAt (p : Parameters) (b i : ℕ) :=
+ b / p.columnBase^i % p.columnBase
+
+private theorem source_succ (p : Parameters) (r a i : ℕ) :
+ sourceAt p (r+1) a (i+1) = sourceAt p r (a/p.sourceBase) i := by
+ simp [sourceAt, pow_succ', Nat.div_div_eq_div_mul]
+
+private theorem column_succ (p : Parameters) (b i : ℕ) :
+ columnAt p b (i+1) = columnAt p (b/p.columnBase) i := by
+ simp [columnAt, pow_succ', Nat.div_div_eq_div_mul]
+
+private theorem forall_succ (P : ℕ → Prop) (n : ℕ) :
+ (∀ i < n+1, P i) ↔ P 0 ∧ ∀ i < n, P (i+1) := by
+ constructor
+ · intro h; exact ⟨h 0 (by omega), fun i hi => h (i+1) (by omega)⟩
+ · rintro ⟨hz, hs⟩ (_ | i) hi
+ · exact hz
+ · exact hs i (by omega)
+
+private structure Answer (p : Parameters) (r : ℕ) (s out : Work) : Prop where
+ divides : out.divides = true ↔ s.divides = true ∧ ∀ i < r, sourceAt p r s.source i ≤ columnAt p s.column i
+ same : out.same = true ↔ s.same = true ∧ ∀ i < r, sourceAt p r s.source i = columnAt p s.column i
+ read : ∀ i < r, p.request = r-i → out.residual = columnAt p s.column i - sourceAt p r s.source i
+ keep : p.request = 0 ∨ r < p.request → out.residual = s.residual
+
+private theorem model_answer (p : Parameters) (s : Work) {r : ℕ} (hr : s.remaining = r) :
+ Answer p r s (model p r s) := by
+ induction r generalizing s with
+ | zero => exact ⟨by simp [model], by simp [model], by simp, fun _ => rfl⟩
+ | succ r ih =>
+ let z := round p s
+ have hz : z.remaining = r := by change s.remaining-1 = r; omega
+ have ans := ih z hz
+ have hs (i) : sourceAt p r z.source i = sourceAt p (r+1) s.source (i+1) := (source_succ ..).symm
+ have hc (i) : columnAt p z.column i = columnAt p s.column (i+1) := (column_succ ..).symm
+ have hread : z.residual = if r+1 = p.request then
+ columnAt p s.column 0 - sourceAt p (r+1) s.source 0 else s.residual := by
+ simp [z, round, advance, saveDigit, compareDigits, readDigits, hr, sourceAt, columnAt]
+ rw [model]
+ constructor
+ · rw [ans.divides, forall_succ]
+ simp only [hs, hc]
+ change ((s.divides && decide (scaledDigit p s.remaining s.source ≤ s.column % p.columnBase)) = true ∧ _) ↔ _
+ simp [hr, sourceAt, columnAt, and_assoc]
+ · rw [ans.same, forall_succ]
+ simp only [hs, hc]
+ change ((s.same && decide (scaledDigit p s.remaining s.source = s.column % p.columnBase)) = true ∧ _) ↔ _
+ simp [hr, sourceAt, columnAt, and_assoc]
+ · rintro (_ | i) hi hreq
+ · have he : p.request = r+1 := by simpa using hreq
+ rw [ans.keep (Or.inr (by omega)), hread, ite_eq_left he.symm]
+ · rw [← hs, ← hc]
+ exact ans.read i (by omega) (by omega)
+ · intro hreq
+ have hne : r+1 ≠ p.request := by omega
+ rw [ans.keep (by omega), hread, ite_eq_right hne]
+
+/-- The scalar row test, including the returned exponent at one arbitrary
+label, runs on a fixed binary stack machine. -/
+theorem run_digits {w t : ℕ} (p : Parameters) (fit : Fits p w) (source column : ℕ)
+ (ht : t < 2^w) (ha : source < 2^w) (hb : column < 2^w) :
+ let input : Work := ⟨t,source,column,0,true,true,0,0⟩
+ ∃ ticks ≤ (16*t+1)*(RAMTape.ISA.prepareBound w 0+3), ∃ out,
+ UniversalCountStack.SpaceRun (code table) (w+(RAMTape.ISA.prepareBound w 0+3)) ticks
+ (RAMTape.ISA.entry table 0) (bank Fin.elim0 0 (registers w p input))
+ (RAMTape.ISA.entry table 17) (bank Fin.elim0 0 (registers w p out)) ∧
+ (out.divides = true ↔ ∀ i < t, scaledDigit p (t-i) (source/p.sourceBase^i) ≤ column/p.columnBase^i%p.columnBase) ∧
+ (out.same = true ↔ ∀ i < t, scaledDigit p (t-i) (source/p.sourceBase^i) = column/p.columnBase^i%p.columnBase) ∧
+ ∀ i < t, p.request = t-i → out.residual =
+ column/p.columnBase^i%p.columnBase - scaledDigit p (t-i) (source/p.sourceBase^i) := by
+ intro input
+ obtain ⟨n,hn,hr⟩ := model_run p fit input rfl ht ha hb
+ obtain ⟨ticks,hticks,hphys⟩ := run hr
+ have ans := model_answer p input rfl
+ exact ⟨ticks,hticks.trans (Nat.mul_le_mul_right _ hn), _, hphys,
+ by simpa [input, sourceAt, columnAt] using ans.divides,
+ by simpa [input, sourceAt, columnAt] using ans.same, ans.read⟩
+
+end RadicalCertificate.MonomialIndex.ExponentISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayExponentPack.lean b/lean/OAI/Computability/VPVNP/MacaulayExponentPack.lean
new file mode 100644
index 0000000000..bc367c76c5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayExponentPack.lean
@@ -0,0 +1,258 @@
+import OAI.Computability.VPVNP.MacaulayExponentQuery
+import OAI.Computability.VPVNP.RoutineSpace
+import OAI.Computability.VPVNP.RankQueryStackRegister
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+import OAI.Computability.VPVNP.SliceArithmeticLoop
+
+/-!
+# Packing the exponent input of a scalar equation-coefficient query
+
+One step per variable extracts a pair of radix digits, checks the monomial
+divisibility condition, and prepends the little-endian word of their
+truncated difference. Processing the low radix digits first leaves the
+exponents on the output stack in the original variable order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.ExponentPack
+
+open RAMTape BurstRAM RankQuery.Stack.Dispatch
+
+/-- Stacks for the unary variable counter, the packed residual exponents and the temporary
+word-copy buffer. -/
+inductive Streams where
+ | marker | packed | scratch
+ deriving DecidableEq
+
+instance : Fintype Streams := ⟨{.marker, .packed, .scratch}, fun s => by cases s <;> decide⟩
+
+/-- Stack addresses of the ten-register subtraction routine and its three auxiliary streams. -/
+abbrev Port := RAMTape.ISA.Port 10 0 ⊕ Streams
+
+/-- Registers zero and one store the radices, two and three the residual
+source and column, four the divisibility flag, five through eight the
+arithmetic scratch, and nine a zero word. -/
+def arithmetic : RegCode 10 :=
+ .seq (.op 5 .mod 2 0) <| .seq (.op 6 .mod 3 1) <| .seq (.op 7 .sub 6 5) <|
+ .seq (.op 8 .sub 5 6) <| .seq (.test 8 9 .ret (.lit 4 0)) <|
+ .seq (.op 2 .div 2 0) (.op 3 .div 3 1)
+
+/-- Prepend a copy of the current residual exponent word from register seven to the packed
+output stack. -/
+def emit : FiniteRoutine Port := SuccessorFields.prependCopy (.inl (.reg 7)) (.inr .packed) (.inr .scratch)
+
+/-- Read one pair of radix digits, update the divisibility flag, and prepend their truncated
+difference to the output. -/
+def body : FiniteRoutine Port := (arithmetic.compile.onPorts Sum.inl).followedBy emit
+
+/-- Repeat the residual-exponent body once for each marker on the variable counter. -/
+def machine : FiniteRoutine Port := FiniteRoutine.repeatMarked (.inr .marker) body
+
+/-- Register stacks with n remaining variable markers, the current packed output and empty copy
+scratch. -/
+def frame {w : ℕ} (reg : Regs 10 w) (n : ℕ) (out : List Bool) : Stacks Port :=
+ Sum.elim (RAMTape.ISA.bank Fin.elim0 0 reg []) fun
+ | .marker => List.replicate n true
+ | .packed => out
+ | .scratch => []
+
+private theorem frame_pop {w : ℕ} (reg : Regs 10 w) (n : ℕ) (out : List Bool) :
+ Function.update (frame reg (n+1) out) (.inr .marker) (List.replicate n true) = frame reg n out := by
+ funext j; rcases j with j | j
+ · simp [frame]
+ · cases j <;> rfl
+
+private theorem frame_prepend {w : ℕ} (reg : Regs 10 w) (n : ℕ) (out : List Bool) :
+ Function.update (frame reg n out) (.inr .packed) (wordBits (reg 7) ++ out) =
+ frame reg n (wordBits (reg 7) ++ out) := by
+ funext j; rcases j with j | j
+ · simp [frame]
+ · cases j <;> rfl
+
+/-- Tick bound for one digit comparison and one residual-word copy at register width w. -/
+def bodyCost (w : ℕ) := arithmetic.length * (100*(w+1)^2) + (5*w+2)
+
+theorem body_run {w : ℕ} (reg : Regs 10 w) (n : ℕ) (out : List Bool) :
+ ∃ steps ≤ bodyCost w, body.Runs steps (frame reg n out)
+ (frame (arithmetic.exec reg) n (wordBits (arithmetic.exec reg 7) ++ out)) := by
+ obtain ⟨k,hk,hstep⟩ := arithmetic.compile_runs Fin.elim0 0 reg
+ have hreg : (arithmetic.compile.onPorts (Sum.inl : RAMTape.ISA.Port 10 0 → Port)).Runs k
+ (frame reg n out) (frame (arithmetic.exec reg) n out) := by
+ apply arithmetic.compile.runs_onPorts_framed Sum.inl_injective hstep (fun _ => rfl) (fun _ => rfl)
+ rintro (i | i) hi
+ · exact (hi i rfl).elim
+ · rfl
+ let R := arithmetic.exec reg
+ have hc := SuccessorFields.prependCopy_runs (K := Port) (.inl (.reg 7)) (.inr .packed) (.inr .scratch)
+ (by decide) (by decide) (by decide) (frame R n out) rfl
+ change emit.Runs (5*(wordBits (R 7)).length+2) (frame R n out)
+ (Function.update _ (.inr .packed) (wordBits (R 7) ++ out)) at hc
+ rw [length_wordBits, frame_prepend] at hc
+ exact ⟨_, Nat.add_le_add_right hk _, hreg.followedBy hc⟩
+
+/-- Representation of the live registers at a variable boundary. -/
+structure Holds {w : ℕ} (reg : Regs 10 w) (A B a b : ℕ) (good : Bool) : Prop where
+ srcBase : reg 0 = ISA.word w A
+ colBase : reg 1 = ISA.word w B
+ src : reg 2 = ISA.word w a
+ col : reg 3 = ISA.word w b
+ flag : reg 4 = ISA.word w good.toNat
+ zero : reg 9 = ISA.word w 0
+
+private theorem arith_word {w x y : ℕ} (op : Arith) (hx : x < 2^w) (hy : y < 2^w)
+ (hz : op.eval x y < 2^w) :
+ op.word (ISA.word w x) (ISA.word w y) = ISA.word w (op.eval x y) := by
+ have hxy (a : ℕ) (ha : a < 2^w) : (ISA.word w a).val = a := Nat.mod_eq_of_lt ha
+ apply Fin.ext
+ rw [hxy _ hz]
+ simpa only [hxy x hx, hxy y hy] using op.word_val (ISA.word w x) (ISA.word w y) (by
+ rwa [hxy x hx, hxy y hy])
+
+private theorem step_values {w A B a b : ℕ} {good : Bool} {reg : Regs 10 w} (h : Holds reg A B a b good)
+ (hA : A < 2^w) (hB : B < 2^w) (ha : a < 2^w) (hb : b < 2^w) :
+ let R := arithmetic.exec reg
+ Holds R A B (a/A) (b/B) (good && decide (a%A ≤ b%B)) ∧
+ R 7 = ISA.word w (b%B-a%A) := by
+ have h₁ : Arith.mod.word (reg 2) (reg 0) = ISA.word w (a%A) := by
+ rw [h.src, h.srcBase]; exact arith_word _ ha hA ((Nat.mod_le ..).trans_lt ha)
+ have h₂ : Arith.mod.word (reg 3) (reg 1) = ISA.word w (b%B) := by
+ rw [h.col, h.colBase]; exact arith_word _ hb hB ((Nat.mod_le ..).trans_lt hb)
+ have h₃ := arith_word .sub ((Nat.mod_le b B).trans_lt hb) ((Nat.mod_le a A).trans_lt ha)
+ ((Nat.sub_le (b%B) (a%A)).trans_lt ((Nat.mod_le ..).trans_lt hb))
+ have h₄ := arith_word .sub ((Nat.mod_le a A).trans_lt ha) ((Nat.mod_le b B).trans_lt hb)
+ ((Nat.sub_le (a%A) (b%B)).trans_lt ((Nat.mod_le ..).trans_lt ha))
+ have h₅ : Arith.div.word (reg 2) (reg 0) = ISA.word w (a/A) := by
+ rw [h.src, h.srcBase]; exact arith_word _ ha hA ((Nat.div_le_self ..).trans_lt ha)
+ have h₆ : Arith.div.word (reg 3) (reg 1) = ISA.word w (b/B) := by
+ rw [h.col, h.colBase]; exact arith_word _ hb hB ((Nat.div_le_self ..).trans_lt hb)
+ change Arith.sub.word _ _ = ISA.word w (b%B-a%A) at h₃
+ change Arith.sub.word _ _ = ISA.word w (a%A-b%B) at h₄
+ have hword := ISA.word_eq ((Nat.sub_le (a%A) (b%B)).trans_lt ((Nat.mod_le ..).trans_lt ha)) (Nat.two_pow_pos w)
+ by_cases he : a%A ≤ b%B
+ all_goals
+ simp [arithmetic, RegCode.exec, Function.update, h₁, h₂, h₃, h₄, h₅, h₆, h.zero, hword,
+ Nat.sub_eq_zero_iff_le, he]
+ constructor <;> first | exact h.srcBase | exact h.colBase | exact h.flag | exact h.zero | rfl
+
+
+/-- Concatenate fixed-width little-endian exponent words in the given variable order. -/
+def packed (w : ℕ) (xs : List ℕ) : List Bool := xs.flatMap (UniversalCountStack.digits w)
+
+private def residuals (A B : ℕ) : ℕ → ℕ → ℕ → List ℕ
+ | 0, _, _ => []
+ | n+1, a, b => residuals A B n (a/A) (b/B) ++ [b%B - a%A]
+
+private def allows (A B : ℕ) : ℕ → ℕ → ℕ → Bool
+ | 0, _, _ => true
+ | n+1, a, b => decide (a%A ≤ b%B) && allows A B n (a/A) (b/B)
+
+private theorem loop_run {w A B : ℕ} (hA : A < 2^w) (hB : B < 2^w) (n a b : ℕ)
+ (ha : a < 2^w) (hb : b < 2^w) (reg : Regs 10 w) (good : Bool) (out : List Bool)
+ (hr : Holds reg A B a b good) :
+ ∃ k ≤ n*(bodyCost w+1)+1, ∃ R : Regs 10 w, machine.Runs k (frame reg n out)
+ (frame R 0 (packed w (residuals A B n a b) ++ out)) ∧
+ Holds R A B (a/A^n) (b/B^n) (good && allows A B n a b) := by
+ induction n generalizing a b reg good out with
+ | zero =>
+ refine ⟨1, by simp, reg, ?_, by simpa [allows] using hr⟩
+ simp only [residuals, packed, List.flatMap_nil, List.nil_append]
+ exact Routine.Runs.popLoop_empty (Sum.inr Streams.marker : Port) (fun _ => true) (Routine.halt false) body.body (s := frame reg 0 out) rfl
+ | succ n ih =>
+ obtain ⟨s,hs,hbody⟩ := body_run reg n out
+ obtain ⟨hr',hval⟩ := step_values hr hA hB ha hb
+ rw [hval] at hbody
+ obtain ⟨t,ht,R,htail,hreg⟩ := ih (a/A) (b/B) ((Nat.div_le_self ..).trans_lt ha) ((Nat.div_le_self ..).trans_lt hb)
+ (arithmetic.exec reg) (good && decide (a%A ≤ b%B)) (wordBits (ISA.word w (b%B-a%A)) ++ out) hr'
+ refine ⟨1+s+t, by rw [Nat.succ_mul]; omega, R, ?_, ?_⟩
+ · have hsrc : frame reg (n+1) out (.inr .marker) = true :: List.replicate n true := by
+ simp [frame, List.replicate_succ]
+ have hruns := Routine.Runs.popLoop_true_continue (mid := frame (arithmetic.exec reg) n
+ (wordBits (ISA.word w (b%B-a%A)) ++ out)) (.inr .marker) (fun _ => true) (Routine.halt false) body.body
+ hsrc rfl (by rwa [frame_pop]) htail
+ simpa only [machine, FiniteRoutine.repeatMarked, FiniteRoutine.Runs, FiniteRoutine.ofRoutine, UniversalCountStack.digits, ISA.word, residuals, packed, List.flatMap_append,
+ List.flatMap_cons, List.flatMap_nil, List.append_nil, List.append_assoc] using hruns
+ · simpa only [Nat.div_div_eq_div_mul, pow_succ', allows, Bool.and_assoc] using hreg
+
+private theorem residuals_eq (A B n a b : ℕ) :
+ residuals A B n a b = List.ofFn (fun i : Fin n => b/B^i.rev.val%B - a/A^i.rev.val%A) := by
+ induction n generalizing a b with
+ | zero => simp [residuals]
+ | succ n ih =>
+ rw [residuals, ih, List.ofFn_succ']
+ simp only [Fin.rev_castSucc, Fin.val_succ, pow_succ', Nat.div_div_eq_div_mul,
+ Fin.rev_last, Fin.val_zero, pow_zero, Nat.div_one, List.concat_eq_append]
+
+private theorem allows_eq (A B n a b : ℕ) :
+ allows A B n a b = true ↔ ∀ i : Fin n, a/A^i.rev.val%A ≤ b/B^i.rev.val%B := by
+ induction n generalizing a b with
+ | zero => simp [allows]
+ | succ n ih =>
+ rw [allows, Bool.and_eq_true, decide_eq_true_eq, ih, Fin.forall_fin_succ']
+ simp only [Fin.rev_last, Fin.val_zero, pow_zero, Nat.div_one, Fin.rev_castSucc, Fin.val_succ,
+ pow_succ', Nat.div_div_eq_div_mul]
+ tauto
+
+theorem raw_digit {t D : ℕ} (a : BoundedMonomial t D) (i : Fin t) :
+ (rawCode a).val / (D+1)^i.rev.val % (D+1) = a.val i := by
+ have h : t = i.rev.val + ((t-i.rev.val-1)+1) := by have := i.rev.isLt; omega
+ have hpow : (D+1)^t = (D+1)^i.rev.val * ((D+1) * (D+1)^(t-i.rev.val-1)) := by
+ conv_lhs => rw [h, pow_add, pow_succ']
+ have hd := digit_rawCode a i
+ change (rawCode a).val % (D+1)^t / (D+1)^i.rev.val % (D+1) = a.val i at hd
+ rwa [hpow, Nat.mod_mul_right_div_self, Nat.mod_mul_right_mod] at hd
+
+/-- Set the source and column radices and raw keys, initialize divisibility to true and clear
+the scratch registers. -/
+def initial (w L D row col : ℕ) : Regs 10 w :=
+ ![ISA.word w (L+1), ISA.word w (D+1), ISA.word w row, ISA.word w col,
+ ISA.word w 1, 0, 0, 0, 0, 0]
+
+/-- A raw-key pair yields the actual ordered formal-polynomial exponent buffer
+and the exact divisibility flag consumed by the equation-row dispatcher. -/
+theorem pack_rows {w t L D : ℕ} (a : BoundedMonomial t L) (b : BoundedMonomial t D)
+ (hL : rawSize t L ≤ 2^w) (hD : rawSize t D ≤ 2^w) (hLA : L+1 < 2^w) (hDB : D+1 < 2^w)
+ (out : List Bool) :
+ let reg := initial w L D (rawCode a).val (rawCode b).val
+ let result := packed w (List.ofFn (fun i => b.val i - a.val i)) ++ out
+ ∃ k ≤ t*(bodyCost w+1)+1, ∃ R : Regs 10 w, machine.Runs k (frame reg t out) (frame R 0 result) ∧
+ R 4 = ISA.word w (decide (a.val ≤ b.val)).toNat := by
+ intro reg result
+ have hin : Holds reg (L+1) (D+1) (rawCode a).val (rawCode b).val true := by constructor <;> rfl
+ obtain ⟨k,hk,R,run,hreg⟩ := loop_run hLA hDB t (rawCode a).val (rawCode b).val
+ ((rawCode a).isLt.trans_le hL) ((rawCode b).isLt.trans_le hD) reg true out hin
+ refine ⟨k,hk,R,?_,?_⟩
+ · simpa only [residuals_eq, raw_digit, result] using run
+ · have htest := allows_eq (L+1) (D+1) t (rawCode a).val (rawCode b).val
+ simp only [raw_digit] at htest
+ have he : allows (L+1) (D+1) t (rawCode a).val (rawCode b).val = decide (a.val ≤ b.val) := by
+ apply Bool.eq_iff_iff.mpr
+ simpa only [decide_eq_true_eq, Finsupp.le_def] using htest
+ simpa only [Bool.true_and, he] using hreg.flag
+
+private theorem frame_length_le {w : ℕ} (R : Regs 10 w) (t : ℕ) (out : List Bool) (port : Port) :
+ (frame R t out port).length ≤ max (max w t) out.length := by
+ rcases port with j | j
+ · exact (RegisterTable.bank_length_le Fin.elim0 0 R j).trans
+ ((le_max_left w t).trans (le_max_left ..))
+ · cases j <;> simp [frame]
+
+theorem pack_rows_bounded {w t L D : ℕ} (a : BoundedMonomial t L) (b : BoundedMonomial t D)
+ (hL : rawSize t L ≤ 2^w) (hD : rawSize t D ≤ 2^w) (hLA : L+1 < 2^w) (hDB : D+1 < 2^w)
+ (out : List Bool) :
+ let reg := initial w L D (rawCode a).val (rawCode b).val
+ let result := packed w (List.ofFn (fun i => b.val i - a.val i)) ++ out
+ let ticks := t*(bodyCost w+1)+1
+ ∃ k ≤ ticks, ∃ R : Regs 10 w, machine.BoundedRun (max (max w t) out.length + ticks) k
+ (frame reg t out) (frame R 0 result) ∧ R 4 = ISA.word w (decide (a.val ≤ b.val)).toNat := by
+ obtain ⟨k,hk,R,hr,hgood⟩ := pack_rows a b hL hD hLA hDB out
+ exact ⟨k,hk,R, UniversalCountStack.spaceRun_of_steps hr
+ (fun j => Nat.add_le_add (frame_length_le _ _ _ j) hk),hgood⟩
+
+end RadicalCertificate.MonomialIndex.ExponentPack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayExponentQuery.lean b/lean/OAI/Computability/VPVNP/MacaulayExponentQuery.lean
new file mode 100644
index 0000000000..438ffabb14
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayExponentQuery.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.MacaulayExponentISA
+import OAI.Computability.VPVNP.MacaulayQueryBounds
+
+/-!
+# Bit-stack queries for the exponents in Macaulay entries
+
+After ordinal lookup, the low radix block of each raw key contains the
+actual exponents in variable order. The common word width accommodates both
+index scans, the shift by one label, and the scaled source digit. Division
+by the monomial, powered-row equality, and the requested exponent difference
+are recovered in the original label order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.ExponentISA
+
+open RAMTape.RegisterTable
+
+/-- Register width for the two index scans and the shifted exponent comparison. -/
+def entryWidth (t L D scale mark request : ℕ) :=
+ 1 + Nat.clog 2 (2 + rawSize t L + rawSize t D + t + t*L + t*D +
+ scale + scale*(L+1) + mark + request)
+
+/-- Set the source and column radices to their degree bounds plus one and install the scaling,
+marked coordinate and requested coordinate. -/
+def params (L D scale mark request : ℕ) : Parameters := ⟨L+1,D+1,scale,mark,request⟩
+
+private theorem width_bound (t L D scale mark request : ℕ) :
+ 2 + rawSize t L + rawSize t D + t + t*L + t*D + scale + scale*(L+1) + mark + request <
+ 2 ^ entryWidth t L D scale mark request := by
+ let B := 2 + rawSize t L + rawSize t D + t + t*L + t*D + scale + scale*(L+1) + mark + request
+ have h := Nat.le_pow_clog (b := 2) (by decide) B
+ change B < 2^(1+Nat.clog 2 B)
+ rw [pow_add]
+ have := Nat.two_pow_pos (Nat.clog 2 B)
+ omega
+
+theorem indexFits {t L D scale mark request k₁ k₂ : ℕ}
+ (h₁ : k₁ ≤ rawSize t L) (h₂ : k₂ ≤ rawSize t D) :
+ let w := entryWidth t L D scale mark request
+ ISA.Fits (ISA.graded t L k₁) w ∧ ISA.Fits (ISA.graded t D k₂) w ∧ Fits (params L D scale mark request) w := by
+ let w := entryWidth t L D scale mark request
+ have hw := width_bound t L D scale mark request
+ have hb (d : ℕ) : d+1 ≤ rawSize t d := Nat.le_mul_of_pos_right _ (Nat.pow_pos (Nat.succ_pos _))
+ have hbox (d : ℕ) : (d+1)^t ≤ rawSize t d := Nat.le_mul_of_pos_left _ (Nat.succ_pos _)
+ have hL := hb L
+ have hD := hb D
+ have hboxL := hbox L
+ have hboxD := hbox D
+ constructor
+ · constructor <;> (try dsimp [ISA.graded]) <;> omega
+ constructor
+ · constructor <;> (try dsimp [ISA.graded]) <;> omega
+ · constructor <;> (try dsimp [params]) <;> omega
+
+/-- Remove the degree digit of a raw graded monomial address. -/
+def exponentBlock {t D : ℕ} (a : BoundedMonomial t D) : ℕ := (rawCode a).val % (D+1)^t
+
+private theorem read_digit {t D : ℕ} (a : BoundedMonomial t D) (i : Fin t) :
+ exponentBlock a / (D+1)^i.rev.val % (D+1) = a.val i := digit_rawCode a i
+
+private theorem position {t : ℕ} (i : Fin t) : t - i.rev.val = i.val + 1 := by
+ rw [Fin.val_rev]; have := i.isLt; omega
+
+/-- The exponent at variable i after multiplying by the marked variable and raising the
+resulting monomial to the indicated power. -/
+def shifted {t : ℕ} (scale mark : ℕ) (source : Fin t → ℕ) (i : Fin t) :=
+ scale * (source i + if i.val+1 = mark then 1 else 0)
+
+/-- The fixed control returns the divisibility and equality tests in all
+labels, and the difference exponent of any single requested label. -/
+theorem row_run {t L D : ℕ} (a : BoundedMonomial t L) (b : BoundedMonomial t D)
+ (scale mark request : ℕ) :
+ let p := params L D scale mark request
+ let w := entryWidth t L D scale mark request
+ let input : Work := ⟨t,exponentBlock a,exponentBlock b,0,true,true,0,0⟩
+ ∃ ticks ≤ (16*t+1)*(RAMTape.ISA.prepareBound w 0+3), ∃ out,
+ UniversalCountStack.SpaceRun (code table) (w+(RAMTape.ISA.prepareBound w 0+3)) ticks
+ (RAMTape.ISA.entry table 0) (bank Fin.elim0 0 (registers w p input))
+ (RAMTape.ISA.entry table 17) (bank Fin.elim0 0 (registers w p out)) ∧
+ (out.divides = true ↔ ∀ i, shifted scale mark a.val i ≤ b.val i) ∧
+ (out.same = true ↔ ∀ i, shifted scale mark a.val i = b.val i) ∧
+ ∀ i : Fin t, request = i.val+1 → out.residual = b.val i - shifted scale mark a.val i := by
+ intro p w input
+ have fit : Fits p w := (indexFits (Nat.zero_le (rawSize t L)) (Nat.zero_le (rawSize t D))).2.2
+ have hw := width_bound t L D scale mark request
+ have ha : exponentBlock a < 2^w := (Nat.mod_le ..).trans_lt <| (rawCode a).isLt.trans_le (by dsimp [w]; omega)
+ have hb : exponentBlock b < 2^w := (Nat.mod_le ..).trans_lt <| (rawCode b).isLt.trans_le (by dsimp [w]; omega)
+ have hs (i : Fin t) : scaledDigit p (t-i.rev.val) (exponentBlock a / p.sourceBase^i.rev.val) =
+ shifted scale mark a.val i := by
+ change scale * (exponentBlock a / (L+1)^i.rev.val % (L+1) + if t-i.rev.val = mark then 1 else 0) = _
+ rw [position, read_digit]; rfl
+ have hc (i : Fin t) : exponentBlock b / p.columnBase^i.rev.val % p.columnBase = b.val i := read_digit b i
+ obtain ⟨ticks,ht,out,hphys,hdiv,heq,hread⟩ :=
+ run_digits p fit (exponentBlock a) (exponentBlock b) (by dsimp [w]; omega : t < 2^w) ha hb
+ have across (P : ℕ → Prop) : (∀ k < t, P k) ↔ ∀ i : Fin t, P i.rev.val := by
+ constructor
+ · exact fun h i => h _ i.rev.isLt
+ · intro h k hk
+ simpa using h (⟨k,hk⟩ : Fin t).rev
+ refine ⟨ticks,ht,out,hphys,?_,?_,?_⟩
+ · rw [hdiv, across]; simp only [hs, hc]
+ · rw [heq, across]; simp only [hs, hc]
+ · intro i hi
+ simpa only [hs, hc] using hread i.rev.val i.rev.isLt (show p.request = _ from (position i).symm ▸ hi)
+
+/-- The width of each register in the scalar entry tests is polynomially
+bounded for polynomially many labels and polynomial-bit degree and scale inputs. -/
+theorem entryWidth_polynomial {t L D scale mark request : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hL : PolynomiallyBounded (fun n => Nat.clog 2 (L n))) (hD : PolynomiallyBounded (fun n => Nat.clog 2 (D n)))
+ (hS : PolynomiallyBounded (fun n => Nat.clog 2 (scale n)))
+ (hM : PolynomiallyBounded (fun n => Nat.clog 2 (mark n)))
+ (hR : PolynomiallyBounded (fun n => Nat.clog 2 (request n))) :
+ PolynomiallyBounded (fun n => entryWidth (t n) (L n) (D n) (scale n) (mark n) (request n)) := by
+ open PolynomiallyBounded in
+ exact (PolynomiallyBounded.const 1).add <| clog_add (clog_add (clog_add (clog_add (clog_add
+ (clog_add (clog_add (clog_add (clog_add (clog (PolynomiallyBounded.const 2)) (bounded_rawSize ht hL))
+ (bounded_rawSize ht hD)) (clog ht)) (clog_mul (clog ht) hL)) (clog_mul (clog ht) hD)) hS)
+ (clog_mul hS (clog_add hL (clog (PolynomiallyBounded.const 1))))) hM) hR
+
+end RadicalCertificate.MonomialIndex.ExponentISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayFieldReadback.lean b/lean/OAI/Computability/VPVNP/MacaulayFieldReadback.lean
new file mode 100644
index 0000000000..c686beb416
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayFieldReadback.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.MacaulayReadBlocks
+import OAI.Computability.VPVNP.MacaulayPairEntries
+import OAI.Computability.VPVNP.AffinePinCoefficient
+import OAI.Computability.VPVNP.RankCoordinateSliceMinors
+
+/-! # Coefficients of the actual matrix requested by the rank machine
+
+The physical reader encodes elements of the advised finite field in a power
+basis. Each row in the augmented matrix has exactly the coefficient described
+by its shifted or powered branch, with the zero scalar on failed exponent
+tests. The Cramer query uses this same encoded matrix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead
+
+open RadicalCertificate.MonomialIndex Coordinate.SliceMinors SliceArithmetic
+
+variable {F : Type} [Field F] {p e t eqs : ℕ} [Fact p.Prime] [NeZero e]
+variable [Algebra (ZMod p) F] {c : Vector p e} (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F)
+
+private theorem encode_zero : AffinePin.Query.encode φ 0 = 0 := by
+ apply (φ.injective.comp (Scalar.interpret_injective c))
+ change φ (Scalar.interpretation c (AffinePin.Query.encode φ 0)) = φ (Scalar.interpretation c 0)
+ rw [AffinePin.Query.value_encode, map_zero, map_zero]
+
+private theorem encode_one : AffinePin.Query.encode φ 1 = 1 := by
+ apply (φ.injective.comp (Scalar.interpret_injective c))
+ change φ (Scalar.interpretation c (AffinePin.Query.encode φ 1)) = φ (Scalar.interpretation c 1)
+ rw [AffinePin.Query.value_encode, map_one, map_one]
+
+variable [Fact (Irreducible (modulus c))] (Q : QueryData t eqs F)
+
+/-- The original and affine rows differ only in their scalar coefficient
+reader. Both use the multiplier and column monomial in this exact order. -/
+theorem shifted_matrix_entry (row : Fin eqs) (o : Fin (size t Q.multiplierDegree)) (j : Fin (size t Q.columnDegree)) :
+ let a := enumeration t Q.multiplierDegree o
+ let b := enumeration t Q.columnDegree j
+ baseMatrix φ Q ((finProdFinEquiv (row,o)).castAdd (size t Q.pointBound)) j =
+ if a.val ≤ b.val then AffinePin.Query.encode φ (Q.getCoeff row (fun i => b.val i - a.val i)) else 0 := by
+ intro a b
+ change AffinePin.Query.encode φ (appendRows Q.equations Q.monomials ((finProdFinEquiv (row,o)).castAdd _) j) = _
+ simp only [appendRows, Fin.addCases_left, QueryData.equations, equationEntry, Equiv.symm_apply_apply,
+ indexedDigits_eq]
+ by_cases h : a.val ≤ b.val
+ · rw [ite_eq_left h]
+ have hc : ∀ i, (enumeration t Q.multiplierDegree o).val i ≤ (enumeration t Q.columnDegree j).val i := h
+ rw [ite_eq_left hc]
+ · rw [ite_eq_right h]
+ have hc : ¬∀ i, (enumeration t Q.multiplierDegree o).val i ≤ (enumeration t Q.columnDegree j).val i := h
+ rw [ite_eq_right hc, encode_zero]
+
+/-- Encoding a powered monomial row over the slice field yields the same
+zero/one coefficient as testing its exponents in the native scalar type. -/
+theorem power_matrix_entry (o : Fin (size t Q.pointBound)) (j : Fin (size t Q.columnDegree)) :
+ baseMatrix φ Q (o.natAdd (eqs*size t Q.multiplierDegree)) j =
+ powerEntry (K := Scalar c) Q.power (indexedDigits o) j := by
+ change AffinePin.Query.encode φ (appendRows Q.equations Q.monomials (o.natAdd _) j) = _
+ simp only [appendRows, Fin.addCases_right, powerEntry]
+ split_ifs
+ · exact encode_one φ
+ · exact encode_zero φ
+
+end RankQuery.Stack.MacaulayRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayIndexISA.lean b/lean/OAI/Computability/VPVNP/MacaulayIndexISA.lean
new file mode 100644
index 0000000000..03aae59212
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayIndexISA.lean
@@ -0,0 +1,449 @@
+import OAI.Computability.VPVNP.RegisterTable
+import OAI.Computability.VPVNP.GradedMonomialIndex
+
+/-!
+# Fixed register program for a dense monomial ordinal
+
+The program enumerates raw graded radix keys in increasing order. At a key it
+divides the exponent block by its radix exactly once per label and tests the
+digit sum against the outer degree. A selected ordinal returns the raw key.
+With the requested ordinal equal to the upper scan limit it returns the count
+instead. The instruction table and number of registers are independent of the
+degree bound and the number of variables.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.ISA
+
+open BurstRAM BurstRAM.PrivateRAM RAMTape.RegisterTable
+
+/-- The read-only registers, followed by cursor, count, remaining digits,
+residual value, digit sum, scratch, one and zero. -/
+def table : Template 15 13 0 where
+ literalWidth := 1
+ entry := 0
+ code pc := match pc.val with
+ | 0 => .jumpEq 5 3 14 1
+ | 1 => .binary .mod 8 5 2 2
+ | 2 => .copy 7 1 3
+ | 3 => .constant 9 0 4
+ | 4 => .jumpEq 7 12 9 5
+ | 5 => .binary .mod 10 8 0 6
+ | 6 => .binary .add 9 9 10 7
+ | 7 => .binary .div 8 8 0 8
+ | 8 => .binary .sub 7 7 11 4
+ | 9 => .binary .div 10 5 2 10
+ | 10 => .jumpEq 9 10 11 13
+ | 11 => .jumpEq 6 4 14 12
+ | 12 => .binary .add 6 6 11 13
+ | 13 => .binary .add 5 5 11 0
+ | _ => .accept
+
+/-- The lower and upper radix blocks fit in one register each. -/
+structure Parameters where
+ /-- Radix for the digits encoding individual variable exponents. -/
+ base : ℕ
+ /-- Number of variables and hence the number of digits inspected in each candidate key. -/
+ arity : ℕ
+ /-- Size of the low radix block. Division by this value recovers the total-degree tag. -/
+ box : ℕ
+ /-- Exclusive upper bound on the raw keys visited by the monomial scan. -/
+ limit : ℕ
+ /-- Zero-based rank of the valid monomial to return. Using the scan limit as the requested
+ rank makes the program count all valid keys. -/
+ ordinal : ℕ
+
+/-- Mutable register values of the scan through graded monomial keys. -/
+structure Work where
+ /-- Raw key currently under consideration, or the exclusive endpoint after exhausting the
+ scan. -/
+ cursor : ℕ := 0
+ /-- Number of valid keys strictly below the cursor. -/
+ count : ℕ := 0
+ /-- Number of variable digits still to examine for the current candidate. -/
+ remaining : ℕ := 0
+ /-- Unprocessed suffix of the candidate's low radix block, divided by the radix after each
+ digit. -/
+ value : ℕ := 0
+ /-- Sum of the variable exponent digits examined for the current candidate. -/
+ total : ℕ := 0
+ /-- Temporary register for an extracted digit or the total-degree tag used in the final
+ comparison. -/
+ scratch : ℕ := 0
+
+/-- Encode a natural number as a register word modulo two to the power w. -/
+def word (w a : ℕ) : Word w := Fin.ofNat _ a
+
+/-- Lay out the five scan parameters, six work values, one and zero in the thirteen hardware
+registers. -/
+def registers (w : ℕ) (p : Parameters) (s : Work) (j : Fin 13) : Word w :=
+ word w <| match j.val with
+ | 0 => p.base
+ | 1 => p.arity
+ | 2 => p.box
+ | 3 => p.limit
+ | 4 => p.ordinal
+ | 5 => s.cursor
+ | 6 => s.count
+ | 7 => s.remaining
+ | 8 => s.value
+ | 9 => s.total
+ | 10 => s.scratch
+ | 11 => 1
+ | _ => 0
+
+theorem word_eq {w a b : ℕ} (ha : a < 2^w) (hb : b < 2^w) :
+ word w a = word w b ↔ a = b := by simp [word, Fin.ext_iff, Nat.mod_eq_of_lt, ha, hb]
+
+theorem eval_add (w a b : ℕ) :
+ BinaryOp.add.eval (word w a) (word w b) = word w (a+b) := by
+ apply Fin.ext
+ simp only [BinaryOp.eval, word, Fin.val_add, Fin.val_ofNat]
+ exact (Nat.add_mod ..).symm
+
+theorem eval_mod {w a b : ℕ} (ha : a < 2^w) (hb : b < 2^w) :
+ BinaryOp.mod.eval (word w a) (word w b) = word w (a%b) := by
+ simp [BinaryOp.eval, word, Nat.mod_eq_of_lt, ha, hb]
+
+theorem eval_div {w a b : ℕ} (ha : a < 2^w) (hb : b < 2^w) :
+ BinaryOp.div.eval (word w a) (word w b) = word w (a/b) := by
+ simp [BinaryOp.eval, word, Nat.mod_eq_of_lt, ha, hb]
+
+theorem eval_sub_one {w a : ℕ} (ha : a+1 < 2^w) (hw : 1 < 2^w) :
+ BinaryOp.sub.eval (word w (a+1)) (word w 1) = word w a := by
+ apply Fin.ext
+ simp only [BinaryOp.eval, word, Fin.val_sub, Fin.val_ofNat, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hw]
+ have h : 2^w - 1 + (a+1) = a + 2^w := by omega
+ simp [h]
+
+/-- Execution of the graded-key scanner for exactly n instructions between the two indicated
+control locations and register configurations. -/
+abbrev Trace (w : ℕ) (p : Parameters) (n : ℕ) (pc : Fin 15) (s : Work) (pc' : Fin 15) (s' : Work) :=
+ Runs table (Fin.elim0 : Fin 0 → Word w) 0 n pc (registers w p s) pc' (registers w p s')
+
+private theorem write_eq {w : ℕ} (p : Parameters) (s s' : Work) (i : Fin 13) (v : Word w)
+ (hi : registers w p s' i = v)
+ (hrest : ∀ j ≠ i, registers w p s j = registers w p s' j) :
+ Function.update (registers w p s) i v = registers w p s' := by
+ funext j
+ by_cases h : j = i
+ · subst j; simp [hi]
+ · simp [Function.update_of_ne h, hrest j h]
+
+private abbrev wordStep (w : ℕ) (p : Parameters) (pc : Fin 15) (s : Work) :=
+ step (table.code pc) Fin.elim0 (0 : Word w) (registers w p s)
+
+private theorem digit_round {w : ℕ} (p : Parameters) (s : Work) {r : ℕ}
+ (hr : s.remaining = r+1) (hrem : r+1 < 2^w) (hbase : p.base < 2^w)
+ (hv : s.value < 2^w) (hw : 1 < 2^w) :
+ Trace w p 5 4 s 4 {s with
+ remaining := r, value := s.value/p.base
+ total := s.total + s.value%p.base, scratch := s.value%p.base} := by
+ let s₁ := {s with scratch := s.value % p.base}
+ let s₂ := {s₁ with total := s.total + s.value % p.base}
+ let s₃ := {s₂ with value := s.value / p.base}
+ let s₄ := {s₃ with remaining := r}
+ have h₀ : wordStep w p 4 s = some (5, registers w p s) := by
+ change some (if word w s.remaining = word w 0 then _ else _, _) = _
+ simp [hr, word_eq hrem (Nat.two_pow_pos _)]
+ have h₁ : wordStep w p 5 s = some (6, registers w p s₁) := by
+ change some (6, Function.update (registers w p s) 10 (BinaryOp.mod.eval (word w s.value) (word w p.base))) = _
+ rw [eval_mod hv hbase]
+ apply congrArg (fun R => some ((6 : Fin 15), R))
+ apply write_eq
+ · rfl
+ · intro j hj; fin_cases j <;> first | rfl | exact (hj rfl).elim
+ have h₂ : wordStep w p 6 s₁ = some (7, registers w p s₂) := by
+ change some (7, Function.update (registers w p s₁) 9 (BinaryOp.add.eval (word w s.total) (word w (s.value%p.base)))) = _
+ rw [eval_add]
+ apply congrArg (fun R => some ((7 : Fin 15), R))
+ apply write_eq
+ · rfl
+ · intro j hj; fin_cases j <;> first | rfl | exact (hj rfl).elim
+ have h₃ : wordStep w p 7 s₂ = some (8, registers w p s₃) := by
+ change some (8, Function.update (registers w p s₂) 8 (BinaryOp.div.eval (word w s.value) (word w p.base))) = _
+ rw [eval_div hv hbase]
+ apply congrArg (fun R => some ((8 : Fin 15), R))
+ apply write_eq
+ · rfl
+ · intro j hj; fin_cases j <;> first | rfl | exact (hj rfl).elim
+ have h₄ : wordStep w p 8 s₃ = some (4, registers w p s₄) := by
+ change some (4, Function.update (registers w p s₃) 7 (BinaryOp.sub.eval (word w s.remaining) (word w 1))) = _
+ rw [hr, eval_sub_one hrem hw]
+ apply congrArg (fun R => some ((4 : Fin 15), R))
+ apply write_eq
+ · rfl
+ · intro j hj; fin_cases j <;> first | rfl | exact (hj rfl).elim
+ exact .cons h₀ (.cons h₁ (.cons h₂ (.cons h₃ (.one h₄))))
+
+/-- Sum the indicated number of least significant base digits, counting leading zeros if
+necessary. -/
+def digitSum (base : ℕ) : ℕ → ℕ → ℕ
+ | 0, _ => 0
+ | n+1, v => v%base + digitSum base n (v/base)
+
+private theorem digitSum_eq (base n v : ℕ) :
+ digitSum base n v = ∑ i : Fin n, v / base^i.val % base := by
+ induction n generalizing v with
+ | zero => simp [digitSum]
+ | succ n ih =>
+ simp [digitSum, ih, Fin.sum_univ_succ, pow_succ', Nat.div_div_eq_div_mul]
+
+private theorem admissible_eq_digitSum (t D : ℕ) (c : Fin (rawSize t D)) :
+ admissible c = decide (digitSum (D+1) t (c.val % (D+1)^t) = c.val / (D+1)^t) := by
+ change decide ((∑ i : Fin t, c.val % (D+1)^t / (D+1)^i.rev.val % (D+1)) = _) = _
+ rw [digitSum_eq, ← Fin.revPerm.sum_comp]
+ simp only [Fin.revPerm_apply, Fin.rev_rev]
+ rfl
+ simp
+
+
+/-- Width conditions for the scalar scans and the digit-sum comparison. -/
+structure Fits (p : Parameters) (w : ℕ) : Prop where
+ one_lt : 1 < 2^w
+ base_pos : 0 < p.base
+ base_lt : p.base < 2^w
+ arity_lt : p.arity < 2^w
+ box_lt : p.box < 2^w
+ limit_lt : p.limit < 2^w
+ ordinal_lt : p.ordinal < 2^w
+ sum_lt : p.arity * (p.base-1) < 2^w
+
+private theorem digitSum_le (b n v : ℕ) (hb : 0 < b) : digitSum b n v ≤ n*(b-1) := by
+ induction n generalizing v with
+ | zero => simp [digitSum]
+ | succ n ih =>
+ have := ih (v/b)
+ have := Nat.mod_lt v hb
+ rw [digitSum, Nat.succ_mul]
+ omega
+
+private theorem digit_loop {w : ℕ} (p : Parameters) (fit : Fits p w) (s : Work) {r : ℕ}
+ (hr : s.remaining = r) (hrem : r < 2^w) (hv : s.value < 2^w) :
+ ∃ out, Trace w p (5*r+1) 4 s 9 out ∧ out.cursor = s.cursor ∧ out.count = s.count ∧
+ out.total = s.total + digitSum p.base r s.value := by
+ induction r generalizing s with
+ | zero =>
+ refine ⟨s, .one ?_, rfl, rfl, by simp [digitSum]⟩
+ change some (if word w s.remaining = word w 0 then _ else _, _) = _
+ simp [hr]
+ | succ r ih =>
+ let next := {s with
+ remaining := r, value := s.value/p.base
+ total := s.total + s.value%p.base, scratch := s.value%p.base}
+ have hround := digit_round p s hr hrem fit.base_lt hv fit.one_lt
+ obtain ⟨out, htail, hc, hn, he⟩ := ih next rfl (by omega) ((Nat.div_le_self ..).trans_lt hv)
+ refine ⟨out, ?_, hc, hn, ?_⟩
+ · convert hround.trans htail using 1; omega
+ · simpa [next, digitSum, Nat.add_assoc] using he
+
+local macro "writeReg" : tactic => `(tactic|
+ (simp only [Option.some.injEq, Prod.mk.injEq, true_and]
+ apply write_eq
+ · rfl
+ · intro j hj; fin_cases j <;> first | rfl | exact (hj rfl).elim))
+
+private theorem setup {w : ℕ} (p : Parameters) (fit : Fits p w) (s : Work) (hc : s.cursor < p.limit) :
+ Trace w p 4 0 s 4 {s with value := s.cursor%p.box, remaining := p.arity, total := 0} := by
+ let s₁ := {s with value := s.cursor%p.box}
+ let s₂ := {s₁ with remaining := p.arity}
+ let s₃ := {s₂ with total := 0}
+ have h₀ : wordStep w p 0 s = some (1, registers w p s) := by
+ change some (if word w s.cursor = word w p.limit then _ else _, _) = _
+ simp [word_eq (hc.trans fit.limit_lt) fit.limit_lt, hc.ne]
+ have h₁ : wordStep w p 1 s = some (2, registers w p s₁) := by
+ change some (2, Function.update (registers w p s) 8 (BinaryOp.mod.eval (word w s.cursor) (word w p.box))) = _
+ rw [eval_mod (hc.trans fit.limit_lt) fit.box_lt]
+ writeReg
+ have h₂ : wordStep w p 2 s₁ = some (3, registers w p s₂) := by
+ change some (3, Function.update (registers w p s₁) 7 (word w p.arity)) = _
+ writeReg
+ have h₃ : wordStep w p 3 s₂ = some (4, registers w p s₃) := by
+ change some (4, Function.update (registers w p s₂) 9 (word w 0)) = _
+ writeReg
+ exact .cons h₀ (.cons h₁ (.cons h₂ (.one h₃)))
+
+/-- A raw key is accepted precisely when the digit sum of its low block equals the total degree
+in its high block. -/
+def validKey (p : Parameters) (c : ℕ) : Bool :=
+ decide (digitSum p.base p.arity (c%p.box) = c/p.box)
+
+private theorem test_run {w : ℕ} (p : Parameters) (fit : Fits p w) (s : Work) (hc : s.cursor < p.limit) :
+ ∃ out, Trace w p (5*p.arity+7) 0 s (if validKey p s.cursor then 11 else 13) out ∧
+ out.cursor = s.cursor ∧ out.count = s.count := by
+ let initial := {s with value := s.cursor%p.box, remaining := p.arity, total := 0}
+ have hbegin := setup p fit s hc
+ obtain ⟨mid, hm, hmcur, hmcount, hmsum⟩ := digit_loop p fit initial rfl fit.arity_lt
+ ((Nat.mod_le _ _).trans_lt (hc.trans fit.limit_lt))
+ change mid.cursor = s.cursor at hmcur
+ change mid.total = 0 + digitSum p.base p.arity (s.cursor%p.box) at hmsum
+ rw [Nat.zero_add] at hmsum
+ let out := {mid with scratch := s.cursor/p.box}
+ have h₉ : wordStep w p 9 mid = some (10, registers w p out) := by
+ change some (10, Function.update (registers w p mid) 10 (BinaryOp.div.eval (word w mid.cursor) (word w p.box))) = _
+ rw [hmcur, eval_div (hc.trans fit.limit_lt) fit.box_lt]
+ writeReg
+ have h₁₀ : wordStep w p 10 out = some (if validKey p s.cursor then 11 else 13, registers w p out) := by
+ change some (if word w mid.total = word w (s.cursor/p.box) then _ else _, _) = _
+ simp [hmsum, validKey, word_eq ((digitSum_le p.base p.arity (s.cursor%p.box) fit.base_pos).trans_lt fit.sum_lt)
+ ((Nat.div_le_self ..).trans_lt (hc.trans fit.limit_lt))]
+ refine ⟨out, ?_, hmcur, hmcount⟩
+ have htail : Trace w p 2 9 mid (if validKey p s.cursor then 11 else 13) out := .cons h₉ (.one h₁₀)
+ change Trace w p (5*p.arity+1) 4 initial 9 mid at hm
+ convert (hbegin.trans hm).trans htail using 1; omega
+
+private theorem bump_cursor (w : ℕ) (p : Parameters) (s : Work) :
+ Trace w p 1 13 s 0 {s with cursor := s.cursor+1} := by
+ apply Runs.one
+ change some (0, Function.update (registers w p s) 5 (BinaryOp.add.eval (word w s.cursor) (word w 1))) = _
+ rw [eval_add]; writeReg
+
+private theorem bump_count (w : ℕ) (p : Parameters) (s : Work) :
+ Trace w p 1 12 s 13 {s with count := s.count+1} := by
+ apply Runs.one
+ change some (13, Function.update (registers w p s) 6 (BinaryOp.add.eval (word w s.count) (word w 1))) = _
+ rw [eval_add]; writeReg
+
+private theorem check_ordinal {w : ℕ} (p : Parameters) (fit : Fits p w) (s : Work) (hn : s.count < 2^w) :
+ Trace w p 1 11 s (if s.count = p.ordinal then 14 else 12) s := by
+ apply Runs.one
+ change some (if word w s.count = word w p.ordinal then _ else _, _) = _
+ simp [word_eq hn fit.ordinal_lt]
+
+
+/-- The return address is either the end of the range or the valid raw
+address whose exclusive prefix count equals the requested ordinal. -/
+structure Result (p : Parameters) (out : Work) : Prop where
+ cursor_le : out.cursor ≤ p.limit
+ count_eq : out.count = countCodes (validKey p) out.cursor
+ count_le : out.count ≤ p.ordinal
+ stopped : out.cursor = p.limit ∨ validKey p out.cursor = true ∧ out.count = p.ordinal
+
+private theorem scan {w : ℕ} (p : Parameters) (fit : Fits p w) (rem : ℕ) (s : Work)
+ (hc : s.cursor + rem = p.limit) (hn : s.count = countCodes (validKey p) s.cursor)
+ (hk : s.count ≤ p.ordinal) :
+ ∃ steps ≤ rem*(5*p.arity+10)+1, ∃ out, Trace w p steps 0 s 14 out ∧ Result p out := by
+ induction rem generalizing s with
+ | zero =>
+ simp only [Nat.add_zero] at hc
+ refine ⟨1, by simp, s, .one ?_, ⟨hc.le, hn, hk, Or.inl hc⟩⟩
+ change some (if word w s.cursor = word w p.limit then _ else _, _) = _
+ simp [hc]
+ | succ rem ih =>
+ obtain ⟨mid, htest, hmcur, hmcount⟩ := test_run p fit s (by omega)
+ have hstep : countCodes (validKey p) (s.cursor+1) = countCodes (validKey p) s.cursor +
+ if validKey p s.cursor then 1 else 0 := by rw [countCodes_eq, countCodes_eq, Nat.count_succ]
+ have clock {b : ℕ} (hb : b ≤ rem*(5*p.arity+10)+1) :
+ (5*p.arity+10)+b ≤ (rem+1)*(5*p.arity+10)+1 := by rw [Nat.succ_mul rem (5*p.arity+10)]; omega
+ by_cases hv : validKey p s.cursor = true
+ · simp only [ite_eq_left hv] at htest
+ have hcheck := check_ordinal p fit mid (hmcount.trans_le hk |>.trans_lt fit.ordinal_lt)
+ by_cases he : mid.count = p.ordinal
+ · simp only [ite_eq_left he] at hcheck
+ refine ⟨_, ?_, mid, htest.trans hcheck, ⟨by omega, hmcur ▸ hmcount.trans hn, he.le, Or.inr ?_⟩⟩
+ · have := clock (Nat.zero_le (rem*(5*p.arity+10)+1))
+ omega
+ · exact ⟨hmcur ▸ hv, he⟩
+ · simp only [ite_eq_right he] at hcheck
+ let counted := {mid with count := mid.count+1}
+ let next := {counted with cursor := counted.cursor+1}
+ have hcnt := bump_count w p mid
+ have hcur := bump_cursor w p counted
+ have hn' : next.count = countCodes (validKey p) next.cursor := by
+ change mid.count + 1 = countCodes _ (mid.cursor+1)
+ rw [hmcur, hmcount, hn, hstep, ite_eq_left hv]
+ obtain ⟨b,hb,out,ht,hr⟩ := ih next (by change mid.cursor+1+rem = _; omega) hn'
+ (by change mid.count+1 ≤ _; omega)
+ refine ⟨_, ?_, out, (((htest.trans hcheck).trans hcnt).trans hcur).trans ht, hr⟩
+ have := clock hb
+ omega
+ · simp only [ite_eq_right hv] at htest
+ let next := {mid with cursor := mid.cursor+1}
+ have hcur := bump_cursor w p mid
+ have hn' : next.count = countCodes (validKey p) next.cursor := by
+ change mid.count = countCodes _ (mid.cursor+1)
+ rw [hmcur, hmcount, hn, hstep, ite_eq_right hv, Nat.add_zero]
+ obtain ⟨b,hb,out,ht,hr⟩ := ih next (by change mid.cursor+1+rem = _; omega) hn'
+ (hmcount.trans_le hk)
+ refine ⟨_, ?_, out, (htest.trans hcur).trans ht, hr⟩
+ have := clock hb
+ omega
+
+/-- The actual bit-stack control has polynomial height even when the
+number of raw addresses scanned is exponential. -/
+theorem scan_physical {w : ℕ} (p : Parameters) (fit : Fits p w) :
+ ∃ ticks ≤ (p.limit*(5*p.arity+10)+1)*(RAMTape.ISA.prepareBound w 0+3), ∃ out, Result p out ∧
+ UniversalCountStack.SpaceRun (RAMTape.RegisterTable.code table) (w+(RAMTape.ISA.prepareBound w 0+3)) ticks
+ (RAMTape.ISA.entry table 0) (bank Fin.elim0 0 (registers w p {}))
+ (RAMTape.ISA.entry table 14) (bank Fin.elim0 0 (registers w p out)) := by
+ obtain ⟨n,hn,out,hr,hout⟩ := scan p fit p.limit {} (Nat.zero_add _) (by simp [countCodes_eq]) (Nat.zero_le _)
+ obtain ⟨ticks,ht,hphys⟩ := run hr
+ exact ⟨ticks, ht.trans (Nat.mul_le_mul_right _ hn), out, hout, hphys⟩
+
+/-- The concrete register input for a graded key scan. -/
+def graded (t D ordinal : ℕ) : Parameters := ⟨D+1, t, (D+1)^t, rawSize t D, ordinal⟩
+
+private theorem graded_test (t D ordinal : ℕ) (c : Fin (rawSize t D)) :
+ validKey (graded t D ordinal) c.val = admissible c := (admissible_eq_digitSum t D c).symm
+
+private theorem count_congr {p q : ℕ → Bool} (n : ℕ) (h : ∀ i < n, p i = q i) :
+ countCodes p n = countCodes q n := by
+ induction n with
+ | zero => simp [countCodes_eq]
+ | succ n ih =>
+ have he := ih (fun i hi => h i (hi.trans (Nat.lt_succ_self _)))
+ simp only [countCodes_eq] at he ⊢
+ rw [Nat.count_succ, Nat.count_succ, he, h n (Nat.lt_succ_self _)]
+
+private theorem graded_count (t D ordinal : ℕ) {n : ℕ} (hn : n ≤ rawSize t D) :
+ countCodes (validKey (graded t D ordinal)) n =
+ countCodes (fun c => if h : c < rawSize t D then admissible ⟨c,h⟩ else false) n := by
+ apply count_congr
+ intro i hi
+ have hr := hi.trans_le hn
+ simpa only [dite_eq_left hr] using graded_test t D ordinal ⟨i,hr⟩
+
+theorem count_result {t D : ℕ} {out : Work} (h : Result (graded t D (rawSize t D)) out) :
+ out.cursor = rawSize t D ∧ out.count = size t D := by
+ have he : out.cursor = rawSize t D := by
+ rcases h.stopped with he | ⟨_,he⟩
+ · exact he
+ · have hh := (Nat.count_le (p := fun i => validKey (graded t D (rawSize t D)) i = true) (n := out.cursor))
+ rw [← countCodes_eq, ← h.count_eq, he] at hh
+ exact h.cursor_le.antisymm hh
+ refine ⟨he, ?_⟩
+ rw [h.count_eq, he, graded_count _ _ _ le_rfl]
+ rfl
+
+theorem ordinal_result {t D : ℕ} {k : Fin (size t D)} {out : Work}
+ (h : Result (graded t D k) out) :
+ out.cursor = (rawCode (enumeration t D k)).val ∧ out.count = k.val := by
+ have hlen : countCodes (validKey (graded t D k)) (rawSize t D) = size t D := by
+ rw [graded_count _ _ _ le_rfl]; rfl
+ have hlt : out.cursor < rawSize t D := by
+ apply lt_of_le_of_ne h.cursor_le
+ intro he
+ have hn := h.count_eq
+ change out.cursor = rawSize t D at he
+ rw [he, hlen] at hn
+ exact (Nat.not_lt_of_ge (hn.symm.trans_le h.count_le)) k.isLt
+ obtain ⟨hv,hk⟩ := h.stopped.resolve_left (Nat.ne_of_lt hlt)
+ let m := enumeration t D k
+ let c := rawCode m
+ have hvalid : validKey (graded t D k) c.val = true := (graded_test t D k c).trans (admissible_rawCode m)
+ have hc : countCodes (validKey (graded t D k)) c.val = k.val := by
+ rw [graded_count _ _ _ c.isLt.le]
+ have he := congrArg Fin.val ((enumeration t D).symm_apply_apply k)
+ exact he
+ refine ⟨Nat.count_injective (p := fun i => validKey (graded t D k) i = true) hv hvalid ?_, hk⟩
+ rw [← countCodes_eq, ← countCodes_eq, ← h.count_eq, hk, hc]
+ rfl
+
+end RadicalCertificate.MonomialIndex.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayLeafBudgets.lean b/lean/OAI/Computability/VPVNP/MacaulayLeafBudgets.lean
new file mode 100644
index 0000000000..b71c993e35
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayLeafBudgets.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.MacaulayReaderScans
+import OAI.Computability.VPVNP.AffinePinResources
+import OAI.Computability.VPVNP.MacaulayEntryPhase
+import OAI.Computability.VPVNP.MacaulayPinArm
+
+/-! # Shared time and space budgets for the three Macaulay entry arms
+
+The live bank includes the signed counter, mask and value tables, two
+ordinal words, and a full residual exponent buffer. Exhaustive counting and
+ordinal scans contribute to the clock. Their exponent does not contribute
+to the stack-height bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.ReaderPlan
+
+open PolynomiallyBounded RankQuery.Stack
+
+/-- Includes the packed extension-field result and the residual buffer. -/
+def live (P : ReaderPlan) (e v w signedSpace : ℕ) :=
+ w + P.arity + P.arity*w + e*v + signedSpace + AffinePin.Query.space P.arity e w v
+
+/-- Common tick bound for signed equation evaluation, affine pin lookup and copying an encoded
+scalar constant. -/
+def scalarTime (P : ReaderPlan) (e v w signedExp : ℕ) :=
+ max (2^signedExp) (max (MacaulayRead.Arms.Pin.cost P.arity e w v) (5*(e*v)+2))
+
+/-- Tick bound for both ordinal scans and the post-scan scalar computation and buffer cleanup
+of a matrix-entry arm. -/
+def armTime (P : ReaderPlan) (e v w signedSpace signedExp : ℕ) :=
+ let b := P.live e v w signedSpace
+ P.scanTime w b + MacaulayRead.Arms.postTicks b P.arity w (P.scalarTime e v w signedExp)
+
+/-- Stack bound for the selected entry arm, including the ordinal scans, temporary exponent
+buffer and decoder allowance. -/
+def armSpace (P : ReaderPlan) (e v w signedSpace : ℕ) :=
+ let b := P.live e v w signedSpace
+ P.scanSpace w b + MacaulayRead.Arms.transient b P.arity w + MacaulayRowDispatch.ticks w
+
+/-- Time bound for decoding a row, routing it to the appropriate entry arm and returning the
+scalar. -/
+def readTime (P : ReaderPlan) (e v w signedSpace signedExp : ℕ) :=
+ MacaulayRowDispatch.ticks w + (4 + P.armTime e v w signedSpace signedExp)
+
+theorem pin_cost_mono (t w : ℕ) {e e' v v' : ℕ} (he : e ≤ e') (hv : v ≤ v') :
+ AffinePin.Query.cost t e w v ≤ AffinePin.Query.cost t e' w v' := by
+ unfold AffinePin.Query.cost AffinePin.Stage.cost AffinePin.Reader.cost EvaluatorDigitLookup.lookupTicks
+ AffinePin.Output.cost SliceArithmetic.AddCall.callCap
+ gcongr
+
+theorem pin_space_mono (t w : ℕ) {e e' v v' : ℕ} (he : e ≤ e') (hv : v ≤ v') :
+ AffinePin.Query.space t e w v ≤ AffinePin.Query.space t e' w v' := by
+ apply Nat.add_le_add _ (pin_cost_mono t w he hv)
+ unfold AffinePin.Query.storage
+ gcongr
+
+/-- All local clocks and stack heights are charged using their respective
+budgets. The signed-call time is the only exponential term besides the two
+ordinal scans. -/
+theorem leaf_bounds (P : ReaderPlan) (w signedSpace signedExp : ℕ) {e v E V : ℕ} (he : e ≤ E) (hv : v ≤ V)
+ (d : PairCall.Inputs) (ht : d.arity = P.arity) (hL : d.degree false ≤ P.source) (hD : d.degree true ≤ P.column) :
+ let live := P.live E V w signedSpace
+ let cap := P.armSpace E V w signedSpace
+ let clock := P.armTime E V w signedSpace signedExp
+ (w ≤ live ∧ P.arity ≤ live ∧ P.arity*w ≤ live ∧ e*v ≤ live ∧ signedSpace ≤ live ∧
+ AffinePin.Query.space P.arity e w v ≤ live) ∧
+ (PairCall.equationSpace w live d ≤ cap ∧ PairCall.poweredSpace w live ≤ cap ∧
+ live + MacaulayRowDispatch.ticks w ≤ cap ∧ MacaulayRead.Arms.transient live P.arity w ≤ cap ∧
+ max live (P.arity*w) + (5*w+2) ≤ cap) ∧
+ ∀ time, time ≤ 2^signedExp →
+ P.scanTime w live + MacaulayRead.Arms.postTicks live P.arity w
+ (max time (max (MacaulayRead.Arms.Pin.cost P.arity e w v) (5*(e*v)+2))) ≤ clock := by
+ intro b cap clock
+ obtain ⟨_,_,hs,hp⟩ := P.scan_bounds w b d ht hL hD
+ have h₁ := Nat.mul_le_mul he hv
+ have h₂ := pin_cost_mono P.arity w he hv
+ have h₃ := pin_space_mono P.arity w he hv
+ have hb : w ≤ b := by dsimp [b,live]; omega
+ have htbuf : P.arity*w ≤ b := by dsimp [b,live]; omega
+ constructor
+ · dsimp [b,live]; omega
+ constructor
+ · have eq : cap = P.scanSpace w b + MacaulayRead.Arms.transient b P.arity w + MacaulayRowDispatch.ticks w := rfl
+ rw [eq]
+ dsimp only [MacaulayRead.Arms.transient]
+ omega
+ · intro time htime
+ apply Nat.add_le_add_left
+ unfold MacaulayRead.Arms.postTicks scalarTime MacaulayRead.Arms.Pin.cost
+ gcongr
+
+private theorem clogMax {f g : ℕ → ℕ} (hf : PolynomiallyBounded (fun n => Nat.clog 2 (f n)))
+ (hg : PolynomiallyBounded (fun n => Nat.clog 2 (g n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (max (f n) (g n))) :=
+ (clog_add hf hg).of_le fun _ => Nat.clog_mono_right _ (max_le (Nat.le_add_right ..) (Nat.le_add_left ..))
+
+theorem leaf_resources (P : ℕ → ReaderPlan) {w e v signedSpace signedExp : ℕ → ℕ}
+ (hw : PolynomiallyBounded w) (he : PolynomiallyBounded e) (hv : PolynomiallyBounded v)
+ (hs : PolynomiallyBounded signedSpace) (hx : PolynomiallyBounded signedExp)
+ (ht : PolynomiallyBounded (fun n => (P n).arity)) (hd : PolynomiallyBounded (fun n => Nat.clog 2 (P n).degree))
+ (hn : PolynomiallyBounded (fun n => Nat.clog 2 (P n).points)) (hq : PolynomiallyBounded (fun n => Nat.clog 2 (P n).order)) :
+ PolynomiallyBounded (fun n => (P n).live (e n) (v n) (w n) (signedSpace n)) ∧
+ PolynomiallyBounded (fun n => (P n).armSpace (e n) (v n) (w n) (signedSpace n)) ∧
+ PolynomiallyBounded (fun n => Nat.clog 2 ((P n).readTime (e n) (v n) (w n) (signedSpace n) (signedExp n))) := by
+ obtain ⟨hpin,hpinSpace,_⟩ := AffinePin.Query.resources ht he hw hv
+ have hLive : PolynomiallyBounded (fun n => (P n).live (e n) (v n) (w n) (signedSpace n)) :=
+ ((((hw.add ht).add (ht.mul hw)).add (he.mul hv)).add hs).add hpinSpace
+ obtain ⟨hcap,hclock,hrouter⟩ := resources P hw hLive ht hd hn hq
+ have hpincost := ((((PolynomiallyBounded.const 5).mul hw).add (.const 2)).add hpin)
+ have hscalar := (((PolynomiallyBounded.const 5).mul (he.mul hv)).add (.const 2))
+ have hleaves := clogMax (clog_pow ((PolynomiallyBounded.const 2).clog) hx) (clogMax hpincost.clog hscalar.clog)
+ have hbuf := (ht.mul hw).add (.const 1)
+ have hticks := clog_add (clog_add ((PolynomiallyBounded.const 2).clog) (clogMax
+ ((((PolynomiallyBounded.const 5).mul hLive).add (.const 2)).clog) hleaves)) ((hbuf.add (hw.add (.const 1))).clog)
+ have htrans := ((hLive.add (ht.mul hw)).add hw).add
+ (((((PolynomiallyBounded.const 5).mul hLive).add (ht.mul hw)).add hw).add (.const 4))
+ exact ⟨hLive,(hcap.add htrans).add hrouter,clog_add hrouter.clog
+ (clog_add ((PolynomiallyBounded.const 4).clog) (clog_add hclock hticks))⟩
+
+end RadicalCertificate.MonomialIndex.ReaderPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayOrdinalCall.lean b/lean/OAI/Computability/VPVNP/MacaulayOrdinalCall.lean
new file mode 100644
index 0000000000..c32a9fa0ce
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayOrdinalCall.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.MacaulayPairPorts
+
+/-! # A returning raw-key lookup which preserves the caller's ordinal and advice -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.PairCall
+
+open RAMTape UniversalCountStack
+
+/-- Between register instructions only the register and persistent ports
+can be occupied. The instruction work ports and private log are empty. -/
+def wordPorts (r : ℕ) : List (RAMTape.ISA.Port r 0) :=
+ .persistent :: (List.finRange r).map .reg
+
+theorem wordPorts_nodup (r : ℕ) : (wordPorts r).Nodup := by
+ simp [wordPorts, List.Nodup.map (fun _ _ h => RAMTape.ISA.Port.reg.inj h) (List.nodup_finRange r)]
+
+theorem length_wordPorts (r : ℕ) : (wordPorts r).length = r+1 := by simp [wordPorts]
+
+theorem register_empty_else {r w : ℕ} (R : Fin r → BurstRAM.Word w) (i : RAMTape.ISA.Port r 0)
+ (hi : i ∉ wordPorts r) : RegisterTable.bank Fin.elim0 0 R i = [] := by
+ cases i with
+ | reg j => simp [wordPorts] at hi
+ | persistent => simp [wordPorts] at hi
+ | pub j => exact Fin.elim0 j
+ | work => rfl
+ | logPort j => cases j <;> rfl
+
+private def ordinalSource (column : Bool) : OrdBank → Field
+ | .reg i => match i.val with
+ | 0 => .base column
+ | 1 => .arity
+ | 2 => .box column
+ | 3 => .limit column
+ | 4 => .ordinal column
+ | 11 => .one
+ | _ => .zero
+ | _ => .zero
+
+private def singleOrdinal (c : Bool) : FiniteRoutine (CallBank.Port Field OrdBank) :=
+ CallBank.machine (ordinalSource c) (wordPorts 13) ordinalRoutine [(.reg 5,.raw c)] (wordPorts 13)
+
+/-- Return the raw key of the requested source or column monomial while preserving the caller's
+ordinal and parameter words. -/
+def ordinal (c : Bool) : FiniteRoutine Port := (singleOrdinal c).onPorts (embed Sum.inl)
+
+/-- Time allowance for copying the ordinal scan's input words, returning its raw key and
+clearing the private scan bank. -/
+def ordinalWork (w B : ℕ) := CallBank.overhead 14 1 14 B (w+(RAMTape.ISA.prepareBound w 0+3))
+
+/-- Stack allowance for staging and running one ordinal scan with register width w and caller
+stacks bounded by B. -/
+def ordinalSpace (w B : ℕ) := B+(w+(RAMTape.ISA.prepareBound w 0+3))+ordinalWork w B
+
+/-- Tick bound for a complete bounded-degree ordinal search, including the private call's input
+and output copies. -/
+def ordinalClock (w B t D : ℕ) :=
+ (rawSize t D*(5*t+10)+2)*(RAMTape.ISA.prepareBound w 0+3) + ordinalWork w B
+
+theorem ordinal_runs {w B : ℕ} (d : Inputs) (c : Bool) (k : Fin (size d.arity (d.degree c)))
+ (hk : d.ordinal c = k.val) (fit : ISA.Fits (ISA.graded d.arity (d.degree c) k) w)
+ (raw : Bool → List Bool) (packed flag : List Bool) (hB : ∀ i, (values w d raw packed flag i).length ≤ B) :
+ let key := (rawCode (enumeration d.arity (d.degree c) k)).val
+ ∃ n ≤ ordinalClock w B d.arity (d.degree c), (ordinal c).BoundedRun (ordinalSpace w B) n
+ (publicBank w d raw packed flag) (publicBank w d (Function.update raw c (digits w key ++ raw c)) packed flag) := by
+ intro key
+ let x := values w d raw packed flag
+ let p := ISA.graded d.arity (d.degree c) k
+ let R := ISA.registers w p {}
+ have hin : CallBank.filled (ordinalSource c) (wordPorts 13) x = RegisterTable.bank Fin.elim0 0 R := by
+ funext i
+ cases i with
+ | reg j =>
+ have hmem : (RAMTape.ISA.Port.reg j : OrdBank) ∈ wordPorts 13 := by simp [wordPorts]
+ simp only [CallBank.filled, ite_eq_left hmem]
+ fin_cases j <;> simp [ordinalSource, values, x, RegisterTable.bank, RAMTape.ISA.bank,
+ R, ISA.registers, p, ISA.graded, hk, digits, ISA.word]
+ | persistent => simp [CallBank.filled, wordPorts, x, ordinalSource, values, RegisterTable.bank, RAMTape.ISA.bank, digits]
+ | pub j => exact Fin.elim0 j
+ | work j => simp [CallBank.filled, wordPorts, RegisterTable.bank, RAMTape.ISA.bank]
+ | logPort j => cases j <;> simp [CallBank.filled, wordPorts, RegisterTable.bank, RAMTape.ISA.bank,
+ RAMTape.ISA.logStacks, AddressLog.keys, AddressLog.values]
+ obtain ⟨steps,ht,out,hr,hkey,_⟩ := ordinalRoutine_runs k fit
+ let post := RegisterTable.bank Fin.elim0 0 (ISA.registers w p out)
+ obtain ⟨n,hn,hcall⟩ := CallBank.machine_run (ordinalSource c) (wordPorts 13) ordinalRoutine
+ [(.reg 5,.raw c)] (wordPorts 13) x _ post (wordPorts_nodup _) hB hin hr (register_empty_else _)
+ have hsave : CallBank.saved post [(.reg 5,.raw c)] x =
+ values w d (Function.update raw c (digits w key ++ raw c)) packed flag := by
+ change Function.update (values w d raw packed flag) (.raw c) (digits w out.cursor ++ raw c) = _
+ rw [hkey]
+ exact update_raw ..
+ rw [hsave] at hcall
+ have hrun := lift_call Sum.inl Sum.inl_injective (singleOrdinal c) hcall
+ simp only [length_wordPorts, List.length_cons, List.length_nil] at hn hrun
+ refine ⟨n, ?_, hrun⟩
+ exact hn.trans (Nat.add_le_add_right ht _)
+
+end RadicalCertificate.MonomialIndex.PairCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayOrdinary.lean b/lean/OAI/Computability/VPVNP/MacaulayOrdinary.lean
new file mode 100644
index 0000000000..6807ef5d7b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayOrdinary.lean
@@ -0,0 +1,40 @@
+import OAI.Computability.VPVNP.MacaulayBaseAdvice
+import OAI.Computability.VPVNP.MacaulaySignedCoefficient
+import OAI.Computability.VPVNP.MacaulayPinArm
+import OAI.Computability.VPVNP.MacaulayEntryExecution
+
+/-! # The fixed scalar-entry program for the augmented Macaulay matrix
+
+All three arms run literal finite stack programs. The original row evaluates
+two signed counts, the affine row consults the pin table, and the appended
+row compares its powered source monomial with the column. Matrix dimensions,
+scalar field data, and coefficient circuits enter only through the caller's
+stack bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead
+
+open RAMTape MacaulayRowDispatch
+
+set_option synthInstance.maxSize 3000 in
+/-- The three scalar-entry routines. Equation rows use signed counts, affine rows use pin
+advice, and powered rows compare exponent vectors. -/
+def ordinaryArms : Kind → FiniteRoutine (Port BaseAdvice.RawPort)
+ | .equation => Arms.phase false (JointScalar.Leaf.machine.onPorts (SignedLeaf.ports Function.Embedding.inl))
+ | .affine => Arms.phase false (Arms.Pin.machine Function.Embedding.inr)
+ | .power => Arms.phase true (Arms.emit true)
+
+set_option synthInstance.maxSize 3000 in
+/-- Fixed row decoder and dispatch program with the equation, affine and powered scalar-entry
+arms installed. -/
+def ordinaryReader : FiniteRoutine (Port BaseAdvice.RawPort) := reader ordinaryArms
+
+end RankQuery.Stack.MacaulayRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayPairBounds.lean b/lean/OAI/Computability/VPVNP/MacaulayPairBounds.lean
new file mode 100644
index 0000000000..abc0207a9e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayPairBounds.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.MacaulayPairCall
+
+/-!
+# Uniform register widths and bounds for the physical Macaulay entry arms
+
+The actual physical clocks in the two returning routines are singly
+exponential. Their stack bounds are polynomial in the arity, register width
+and caller's live stack bound, independently of the size of the index scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.PairCall
+
+open PolynomiallyBounded
+
+/-- Common register width accommodating both graded-key scans, the optional coordinate shift
+and the scaled exponent comparisons. -/
+def requiredWidth (d : Inputs) := ExponentISA.entryWidth d.arity (d.degree false) (d.degree true) d.scale d.mark 0
+
+private theorem size_le_raw (t D : ℕ) : size t D ≤ rawSize t D := by
+ rw [size_eq_card]
+ exact (card_boundedMonomial_le t D).trans (Nat.le_mul_of_pos_left _ (Nat.succ_pos _))
+
+/-- One advised register width works for every pair of legal ordinals at
+these degrees, including the shifted power comparison. -/
+theorem fits_of_width (d : Inputs) (k : Ordinals d) {w : ℕ} (hw : requiredWidth d ≤ w) :
+ (∀ c, ISA.Fits (ISA.graded d.arity (d.degree c) (k c)) w) ∧ ExponentISA.Fits (powerParams d) w := by
+ have h₀ := ExponentISA.indexFits (scale := d.scale) (mark := d.mark) (request := 0)
+ ((k false).isLt.le.trans (size_le_raw ..)) ((k true).isLt.le.trans (size_le_raw ..))
+ have hpow := Nat.pow_le_pow_right (n := 2) (by decide) hw
+ have larger {p : ISA.Parameters} (h : ISA.Fits p (requiredWidth d)) : ISA.Fits p w :=
+ ⟨h.one_lt.trans_le hpow,h.base_pos,h.base_lt.trans_le hpow,h.arity_lt.trans_le hpow,h.box_lt.trans_le hpow,
+ h.limit_lt.trans_le hpow,h.ordinal_lt.trans_le hpow,h.sum_lt.trans_le hpow⟩
+ have h := h₀.2.2
+ exact ⟨fun c => by cases c; exact larger h₀.1; exact larger h₀.2.1,
+ ⟨h.one_lt.trans_le hpow,h.source_pos,h.column_pos,h.source_lt.trans_le hpow,h.column_lt.trans_le hpow,
+ h.scale_lt.trans_le hpow,h.product_lt.trans_le hpow,h.mark_lt.trans_le hpow,h.request_lt.trans_le hpow⟩⟩
+
+theorem requiredWidth_polynomial (d : ℕ → Inputs) (ht : PolynomiallyBounded (fun n => (d n).arity))
+ (hdeg : ∀ c, PolynomiallyBounded (fun n => Nat.clog 2 ((d n).degree c)))
+ (hscale : PolynomiallyBounded (fun n => Nat.clog 2 (d n).scale))
+ (hmark : PolynomiallyBounded (fun n => Nat.clog 2 (d n).mark)) :
+ PolynomiallyBounded (fun n => requiredWidth (d n)) :=
+ ExponentISA.entryWidth_polynomial ht (hdeg false) (hdeg true) hscale hmark (clog (const 0))
+
+private theorem boundMax {f g : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) :
+ PolynomiallyBounded (fun n => max (f n) (g n)) :=
+ (hf.add hg).of_le fun _ => max_le (Nat.le_add_right ..) (Nat.le_add_left ..)
+
+private theorem boundPrepare {w : ℕ → ℕ} (hw : PolynomiallyBounded w) :
+ PolynomiallyBounded (fun n => RAMTape.ISA.prepareBound (w n) 0+3) :=
+ (((const 100).mul ((hw.add (const 1)).pow 2)).mul (const (0+1))).add (const 3)
+
+private theorem boundOverhead (i o r : ℕ) {B C : ℕ → ℕ} (hB : PolynomiallyBounded B) (hC : PolynomiallyBounded C) :
+ PolynomiallyBounded (fun n => CallBank.overhead i o r (B n) (C n)) :=
+ ((((const i).mul (((const 5).mul hB).add (const 2))).add (const 1)).add
+ (((const o).mul (((const 5).mul hC).add (const 2))).add (const 1))).add
+ (((const r).mul (hC.add (const 1))).add (const 1))
+
+/-- The bounds of the actual two binary controls under the bit-size
+hypotheses of Lemma 8.2. Both include advice staging and final cleanup. -/
+theorem resources (d : ℕ → Inputs) {w B : ℕ → ℕ} (hw : PolynomiallyBounded w) (hB : PolynomiallyBounded B)
+ (ht : PolynomiallyBounded (fun n => (d n).arity))
+ (hdeg : ∀ c, PolynomiallyBounded (fun n => Nat.clog 2 ((d n).degree c))) :
+ PolynomiallyBounded (fun n => equationSpace (w n) (B n) (d n)) ∧
+ PolynomiallyBounded (fun n => poweredSpace (w n) (B n)) ∧
+ PolynomiallyBounded (fun n => Nat.clog 2 (scanClock (w n) (B n) (d n) +
+ packClock (d n).arity (w n) (B n) + clearCost (w n))) ∧
+ PolynomiallyBounded (fun n => Nat.clog 2 (scanClock (w n) (B n) (d n) +
+ powerClock (d n).arity (w n) (B n) + clearCost (w n))) := by
+ have hPrep := boundPrepare hw
+ have hScan := boundOverhead 14 1 14 hB (hw.add hPrep)
+ have hPwr := boundOverhead 16 1 16 hB (hw.add hPrep)
+ have hScanSpace : PolynomiallyBounded (fun n => ordinalSpace (w n) (B n)) := (hB.add (hw.add hPrep)).add hScan
+ have hPowSpace : PolynomiallyBounded (fun n => powerSpace (w n) (B n)) := (hB.add (hw.add hPrep)).add hPwr
+ have hBody : PolynomiallyBounded (fun n => ExponentPack.bodyCost (w n)) :=
+ ((const ExponentPack.arithmetic.length).mul ((const 100).mul ((hw.add (const 1)).pow 2))).add
+ (((const 5).mul hw).add (const 2))
+ have hTicks : PolynomiallyBounded (fun n => packTicks (d n).arity (w n)) :=
+ (ht.mul (hBody.add (const 1))).add (const 1)
+ have hInner := (boundMax hw ht).add hTicks
+ have hPack := boundOverhead 12 2 13 hB hInner
+ have hPackSpace : PolynomiallyBounded (fun n => packSpace (d n).arity (w n) (B n)) := (hB.add hInner).add hPack
+ have hClear : PolynomiallyBounded (fun n => clearCost (w n)) := ((const 2).mul (hw.add (const 1))).add (const 1)
+ have hOrd (c : Bool) : PolynomiallyBounded (fun n => Nat.clog 2
+ (ordinalClock (w n) (B n) (d n).arity ((d n).degree c))) :=
+ clog_add (clog_mul (clog_add (clog_mul (bounded_rawSize ht (hdeg c))
+ (clog (((const 5).mul ht).add (const 10)))) (clog (const 2))) (clog hPrep)) (clog hScan)
+ have hAll := clog_add (hOrd false) (hOrd true)
+ have hPackClock := hTicks.add hPack
+ have hPowClock := ((((const 16).mul ht).add (const 2)).mul hPrep).add hPwr
+ exact ⟨boundMax (boundMax hScanSpace hPackSpace) (((hB.add (ht.mul hw)).add hw).add hClear),
+ boundMax (boundMax hScanSpace hPowSpace) ((hB.add hw).add hClear),
+ clog_add (clog_add hAll (clog hPackClock)) (clog hClear),
+ clog_add (clog_add hAll (clog hPowClock)) (clog hClear)⟩
+
+end RadicalCertificate.MonomialIndex.PairCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayPairCall.lean b/lean/OAI/Computability/VPVNP/MacaulayPairCall.lean
new file mode 100644
index 0000000000..2b5d5f9bc4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayPairCall.lean
@@ -0,0 +1,180 @@
+import OAI.Computability.VPVNP.MacaulayPairPower
+
+/-! # Physical Macaulay entry arms with restored scratch banks
+
+Both arms preserve the two ordinal words, the degree and cardinality
+parameters, and the unary label counter. The equation arm prepends the
+ordered residual exponent words and a full-word divisibility flag. The
+powered-monomial arm prepends one full-word equality flag. Temporary raw
+keys are erased before returning to the matrix reader.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.PairCall
+
+open RAMTape UniversalCountStack
+
+/-- Perform the source ordinal lookup and then the column ordinal lookup, retaining both raw
+keys. -/
+def scans := (ordinal false).followedBy (ordinal true)
+
+/-- Erase the two temporary raw-key stacks before returning to the caller. -/
+def clearKeys : FiniteRoutine Port :=
+ SliceArithmetic.CallClear.cleanup [.external (.raw false), .external (.raw true)]
+
+/-- Return the packed column-minus-source exponents and a divisibility flag after looking up
+both monomials and clearing their keys. -/
+def equation := (scans.followedBy packRaw).followedBy clearKeys
+/-- Return the equality flag comparing the column with the shifted and scaled source monomial,
+then clear both temporary keys. -/
+def powered := (scans.followedBy powerRaw).followedBy clearKeys
+
+/-- A bounded-degree exponent vector on the input variables, with its degree bound taken from
+the source or column side. -/
+abbrev Monomial (d : Inputs) (c : Bool) := BoundedMonomial d.arity (d.degree c)
+/-- Valid indices into the bounded-monomial enumerations for the source and column. -/
+abbrev Ordinals (d : Inputs) := (c : Bool) → Fin (size d.arity (d.degree c))
+
+/-- The bounded monomial at the selected ordinal on the indicated side of the entry query. -/
+def monomial (d : Inputs) (k : Ordinals d) (c : Bool) : Monomial d c := enumeration d.arity (d.degree c) (k c)
+
+/-- Combined tick allowance for the source and column ordinal searches at their respective
+degree bounds. -/
+def scanClock (w B : ℕ) (d : Inputs) :=
+ ordinalClock w B d.arity (d.degree false) + ordinalClock w B d.arity (d.degree true)
+
+theorem scans_runs {w B : ℕ} (d : Inputs) (k : Ordinals d) (hk : ∀ c, d.ordinal c = (k c).val)
+ (fit : ∀ c, ISA.Fits (ISA.graded d.arity (d.degree c) (k c)) w) (packed flag : List Bool)
+ (hw : w ≤ B) (ht : d.arity ≤ B) (hp : packed.length ≤ B) (hf : flag.length ≤ B) :
+ let key := keys w (monomial d k false) (monomial d k true)
+ ∃ n ≤ scanClock w B d, scans.BoundedRun (ordinalSpace w B) n
+ (publicBank w d (fun _ => []) packed flag) (publicBank w d key packed flag) := by
+ intro key
+ let left : Bool → List Bool := fun c => if c then [] else digits w (rawCode (monomial d k false)).val
+ obtain ⟨n₁,hn₁,hr₁⟩ := ordinal_runs d false (k false) (hk false) (fit false) (fun _ => []) packed flag
+ (values_le d _ packed flag hw ht (fun _ => Nat.zero_le _) hp hf)
+ have h₁ : Function.update (fun _ : Bool => ([] : List Bool)) false
+ (digits w (rawCode (monomial d k false)).val ++ []) = left := by funext c; cases c <;> simp [left]
+ change (ordinal false).BoundedRun _ _ _ (publicBank w d (Function.update _ false
+ (digits w (rawCode (monomial d k false)).val ++ [])) packed flag) at hr₁
+ rw [h₁] at hr₁
+ have hlen (c : Bool) : (left c).length ≤ B := by cases c <;> simp [left,hw]
+ obtain ⟨n₂,hn₂,hr₂⟩ := ordinal_runs d true (k true) (hk true) (fit true) left packed flag
+ (values_le d _ packed flag hw ht hlen hp hf)
+ have h₂ : Function.update left true (digits w (rawCode (monomial d k true)).val ++ left true) = key := by
+ funext c; cases c <;> simp [left, key, keys]
+ change (ordinal true).BoundedRun _ _ _ (publicBank w d (Function.update left true
+ (digits w (rawCode (monomial d k true)).val ++ left true)) packed flag) at hr₂
+ rw [h₂] at hr₂
+ exact ⟨n₁+n₂, Nat.add_le_add hn₁ hn₂, hr₁.followedBy hr₂⟩
+
+/-- Tick allowance to clear two raw-key stacks of at most w bits each and return. -/
+def clearCost (w : ℕ) := 2*(w+1)+1
+
+private theorem clearKeys_runs {w B : ℕ} (d : Inputs) (raw : Bool → List Bool) (packed flag : List Bool)
+ (hr : ∀ c, (raw c).length ≤ w) (hB : ∀ i, (values w d raw packed flag i).length ≤ B) :
+ ∃ n ≤ clearCost w, clearKeys.BoundedRun (B+clearCost w) n (publicBank w d raw packed flag)
+ (publicBank w d (fun _ => []) packed flag) := by
+ let ports : List Port := [.external (.raw false), .external (.raw true)]
+ let s := publicBank w d raw packed flag
+ have h (i : Port) (hi : i ∈ ports) : (s i).length ≤ w := by
+ simp only [ports, List.mem_cons, List.not_mem_nil, or_false] at hi
+ rcases hi with rfl | rfl <;> exact hr _
+ obtain ⟨n,hn,hclear⟩ := SliceArithmetic.CallClear.cleanup_runs ports s w h
+ have he : SliceArithmetic.CallClear.erased ports s = publicBank w d (fun _ => []) packed flag := by
+ funext i
+ rcases i with i | i | _
+ · cases i with
+ | raw c => cases c <;> simp [SliceArithmetic.CallClear.erased, ports, publicBank, CallBank.clean, CallBank.frame, values]
+ | _ => simp [SliceArithmetic.CallClear.erased, ports, s, publicBank, CallBank.clean, CallBank.frame, values]
+ · simp [SliceArithmetic.CallClear.erased, ports, s, publicBank, CallBank.clean, CallBank.frame]
+ · simp [SliceArithmetic.CallClear.erased, ports, s, publicBank, CallBank.clean, CallBank.frame]
+ rw [he] at hclear
+ refine ⟨n,hn, spaceRun_of_steps hclear fun i => Nat.add_le_add ?_ hn⟩
+ rcases i with i | i | _ <;> first | exact hB _ | exact Nat.zero_le _
+
+@[simp] theorem length_difference {w t L D : ℕ} (a : BoundedMonomial t L) (b : BoundedMonomial t D) :
+ (difference w a b).length = t*w := by
+ have h (xs : List ℕ) : (ExponentPack.packed w xs).length = xs.length*w := by
+ induction xs with
+ | nil => simp [ExponentPack.packed]
+ | cons a xs ih =>
+ change ((UniversalCountStack.digits w a) ++ ExponentPack.packed w xs).length = (xs.length+1)*w
+ rw [List.length_append, length_digits, ih, Nat.add_one_mul, Nat.add_comm]
+ simp [difference,h]
+
+/-- Maximum stack allowance for ordinal lookup, residual packing and final cleanup in the
+equation arm. -/
+def equationSpace (w B : ℕ) (d : Inputs) :=
+ max (max (ordinalSpace w B) (packSpace d.arity w B)) (B + d.arity*w + w + clearCost w)
+
+/-- Maximum stack allowance for ordinal lookup, powered-exponent comparison and final cleanup
+in the powered arm. -/
+def poweredSpace (w B : ℕ) :=
+ max (max (ordinalSpace w B) (powerSpace w B)) (B+w+clearCost w)
+
+theorem equation_runs {w B : ℕ} (d : Inputs) (k : Ordinals d) (hk : ∀ c, d.ordinal c = (k c).val)
+ (fit : ∀ c, ISA.Fits (ISA.graded d.arity (d.degree c) (k c)) w) (packed flag : List Bool)
+ (hw : w ≤ B) (ht : d.arity ≤ B) (hp : packed.length ≤ B) (hf : flag.length ≤ B) :
+ let a := monomial d k false
+ let b := monomial d k true
+ ∃ n ≤ scanClock w B d + packClock d.arity w B + clearCost w,
+ equation.BoundedRun (equationSpace w B d) n (publicBank w d (fun _ => []) packed flag)
+ (publicBank w d (fun _ => []) (difference w a b ++ packed) (digits w (decide (a.val ≤ b.val)).toNat ++ flag)) := by
+ intro a b
+ let key := keys w a b
+ have hlen (c) : (key c).length = w := by cases c <;> simp [key,keys]
+ obtain ⟨n₁,h₁,r₁⟩ := scans_runs d k hk fit packed flag hw ht hp hf
+ have fs := fit false
+ have fc := fit true
+ rw [← hk] at fs fc
+ obtain ⟨n₂,h₂,r₂⟩ := packRaw_runs d a b fs fc packed flag
+ (values_le d key packed flag hw ht (fun c => (hlen c).trans_le hw) hp hf)
+ let msg := difference w a b ++ packed
+ let out := digits w (decide (a.val ≤ b.val)).toNat ++ flag
+ let bound := B+d.arity*w+w
+ have hmsg : msg.length ≤ bound := by simp [msg, bound]; omega
+ have hout : out.length ≤ bound := by simp [out, bound]; omega
+ obtain ⟨n₃,h₃,r₃⟩ := clearKeys_runs d key msg out (fun c => (hlen c).le)
+ (values_le d key msg out (by dsimp [bound]; omega) (by dsimp [bound]; omega)
+ (fun c => by rw [hlen]; dsimp [bound]; omega) hmsg hout)
+ let cap := equationSpace w B d
+ have t₁ : scans.BoundedRun cap n₁ _ _ := r₁.mono_cap ((le_max_left ..).trans (le_max_left ..))
+ have t₂ : packRaw.BoundedRun cap n₂ _ _ := r₂.mono_cap ((le_max_right ..).trans (le_max_left ..))
+ have t₃ : clearKeys.BoundedRun cap n₃ _ _ := r₃.mono_cap (le_max_right ..)
+ exact ⟨_, Nat.add_le_add (Nat.add_le_add h₁ h₂) h₃, (t₁.followedBy t₂).followedBy t₃⟩
+
+theorem powered_runs {w B : ℕ} (d : Inputs) (k : Ordinals d) (hk : ∀ c, d.ordinal c = (k c).val)
+ (fit : ∀ c, ISA.Fits (ISA.graded d.arity (d.degree c) (k c)) w) (hfit : ExponentISA.Fits (powerParams d) w)
+ (packed flag : List Bool) (hw : w ≤ B) (ht : d.arity ≤ B) (hp : packed.length ≤ B) (hf : flag.length ≤ B) :
+ let a := monomial d k false
+ let b := monomial d k true
+ ∃ n ≤ scanClock w B d + powerClock d.arity w B + clearCost w,
+ powered.BoundedRun (poweredSpace w B) n (publicBank w d (fun _ => []) packed flag)
+ (publicBank w d (fun _ => []) packed (digits w (powerMatch d a b).toNat ++ flag)) := by
+ intro a b
+ let key := keys w a b
+ have hlen (c) : (key c).length = w := by cases c <;> simp [key,keys]
+ obtain ⟨n₁,h₁,r₁⟩ := scans_runs d k hk fit packed flag hw ht hp hf
+ obtain ⟨n₂,h₂,r₂⟩ := powerRaw_runs d a b hfit (fit false).arity_lt
+ ((rawCode a).isLt.trans (fit false).limit_lt) ((rawCode b).isLt.trans (fit true).limit_lt) packed flag
+ (values_le d key packed flag hw ht (fun c => (hlen c).trans_le hw) hp hf)
+ let out := digits w (powerMatch d a b).toNat ++ flag
+ have hout : out.length ≤ B+w := by simp [out]; omega
+ obtain ⟨n₃,h₃,r₃⟩ := clearKeys_runs d key packed out (fun c => (hlen c).le)
+ (values_le d key packed out (by omega) (by omega)
+ (fun c => by rw [hlen]; omega) (by omega) hout)
+ let cap := poweredSpace w B
+ have t₁ : scans.BoundedRun cap n₁ _ _ := r₁.mono_cap ((le_max_left ..).trans (le_max_left ..))
+ have t₂ : powerRaw.BoundedRun cap n₂ _ _ := r₂.mono_cap ((le_max_right ..).trans (le_max_left ..))
+ have t₃ : clearKeys.BoundedRun cap n₃ _ _ := r₃.mono_cap (le_max_right ..)
+ exact ⟨_, Nat.add_le_add (Nat.add_le_add h₁ h₂) h₃, (t₁.followedBy t₂).followedBy t₃⟩
+
+end RadicalCertificate.MonomialIndex.PairCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayPairEntries.lean b/lean/OAI/Computability/VPVNP/MacaulayPairEntries.lean
new file mode 100644
index 0000000000..9f8048c75c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayPairEntries.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.MacaulayPairCall
+
+/-! # Reading matrix entries from the physical flags and exponents
+
+The equality word selects exactly the coefficient of the specified formal
+monomial, also when the target is obtained by label multiplication or
+Frobenius before taking the certificate power. The equation arm's flag
+and residual exponents give the shifted scalar coefficient directly.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.PairCall
+
+open MvPolynomial
+
+variable {K : Type*}
+
+/-- No marked coordinate is used for a source monomial in the appended matrix. -/
+theorem powerMatch_entry [Zero K] [One K] (d : Inputs) (k : Ordinals d) (hm : d.mark = 0) :
+ (if powerMatch d (monomial d k false) (monomial d k true) then (1 : K) else 0) =
+ powerEntry d.scale (indexedDigits (k false)) (k true) := by
+ simp [powerMatch, monomial, ExponentISA.shifted, hm, powerEntry, indexedDigits_eq]
+ split_ifs with he <;> simp [he]
+
+/-- The parameters used for a powered target row. -/
+def targetScale {t e : ℕ} (S : QueryData t e K) : QueryData.Operation t → ℕ
+ | .label _ => S.power
+ | .frobenius => S.power*S.fieldOrder
+
+/-- One-based variable index to increment for a label-multiplication query. Frobenius uses zero
+so every coordinate is left unmarked. -/
+def targetMark {t : ℕ} : QueryData.Operation t → ℕ
+ | .label i => i.val+1
+ | .frobenius => 0
+
+theorem powerMatch_target [Zero K] [One K] {e : ℕ} (d : Inputs) (k : Ordinals d)
+ (S : QueryData d.arity e K) (op : QueryData.Operation d.arity)
+ (hs : d.scale = targetScale S op) (hm : d.mark = targetMark op) :
+ (if powerMatch d (monomial d k false) (monomial d k true) then (1 : K) else 0) =
+ powerEntry S.power (S.target op (indexedDigits (k false))) (k true) := by
+ cases op with
+ | label i =>
+ simp only [powerMatch, decide_eq_true_eq, monomial, ExponentISA.shifted, hs, targetScale,
+ hm, targetMark, Nat.add_left_inj, Fin.val_inj, powerEntry, QueryData.target, indexedDigits_eq, Nat.add_comm]
+ split_ifs with he <;> simp [he]
+ | frobenius =>
+ simp [powerMatch, monomial, ExponentISA.shifted, hs, targetScale, hm, targetMark,
+ powerEntry, QueryData.target, indexedDigits_eq, Nat.mul_assoc]
+ split_ifs with he <;> simp [he]
+
+/-- Decode the integer/affine row block. The ordered buffer has exactly
+the difference exponents passed to the coefficient reader. -/
+theorem equationEntry_at [Zero K] {e : ℕ} (d : Inputs) (k : Ordinals d) (i : Fin e)
+ (getCoeff : Fin e → (Fin d.arity → ℕ) → K) :
+ let a := monomial d k false
+ let b := monomial d k true
+ equationEntry getCoeff (finProdFinEquiv (i,k false)) (k true) =
+ if a.val ≤ b.val then getCoeff i (fun j => b.val j-a.val j) else 0 := by
+ simp [equationEntry, indexedDigits_eq, monomial, Finsupp.le_def]
+
+end RadicalCertificate.MonomialIndex.PairCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayPairPack.lean b/lean/OAI/Computability/VPVNP/MacaulayPairPack.lean
new file mode 100644
index 0000000000..167e84b021
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayPairPack.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.MacaulayOrdinalCall
+
+/-! # Staging the residual packer with preserved caller inputs -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.PairCall
+
+open RAMTape UniversalCountStack
+
+private def packSource : ExponentPack.Port → Field
+ | .inl (.reg i) => match i.val with
+ | 0 => .base false
+ | 1 => .base true
+ | 2 => .raw false
+ | 3 => .raw true
+ | 4 => .one
+ | _ => .zero
+ | .inr .marker => .marker
+ | _ => .zero
+
+private def packInputs : List ExponentPack.Port := (wordPorts 10).map Sum.inl ++ [.inr .marker]
+
+private def packWipe : List ExponentPack.Port := .inr .packed :: packInputs
+
+private def packOutputs : List (ExponentPack.Port × Field) := [(.inr .packed,.packed), (.inl (.reg 4),.flag)]
+
+private def localPack : FiniteRoutine (CallBank.Port Field ExponentPack.Port) :=
+ CallBank.machine packSource packInputs ExponentPack.machine packOutputs packWipe
+
+/-- Run the staged residual-exponent routine on the two raw keys and return the packed
+differences and divisibility flag to their caller stacks. -/
+def packRaw : FiniteRoutine Port := localPack.onPorts (embed (Sum.inr ∘ Sum.inl))
+
+/-- Tick bound for one comparison and residual-word copy per variable, including the loop
+tests. -/
+def packTicks (t w : ℕ) := t*(ExponentPack.bodyCost w+1)+1
+
+/-- Private stack-height bound for the residual packer, accounting for register width, the
+unary marker and the work of all iterations. -/
+def packInnerSpace (t w : ℕ) := max w t + packTicks t w
+
+/-- Copying and cleanup allowance for the packer's twelve input stacks, two returned outputs
+and thirteen cleared private stacks. -/
+def packWork (t w B : ℕ) := CallBank.overhead 12 2 13 B (packInnerSpace t w)
+
+/-- Stack bound for the whole staged packer call, including the caller, private working space
+and copy overhead. -/
+def packSpace (t w B : ℕ) := B+packInnerSpace t w+packWork t w B
+
+/-- Tick bound for staging the packer, running all variable iterations and returning the two
+outputs. -/
+def packClock (t w B : ℕ) := packTicks t w+packWork t w B
+
+/-- The source and column raw graded monomial codes as fixed-width little-endian bit stacks. -/
+def keys {t L D : ℕ} (w : ℕ) (a : BoundedMonomial t L) (b : BoundedMonomial t D) : Bool → List Bool
+ | false => digits w (rawCode a).val
+ | true => digits w (rawCode b).val
+
+/-- Packed exponent vector obtained by coordinatewise truncated subtraction of the source
+monomial from the column monomial. -/
+def difference {t L D : ℕ} (w : ℕ) (a : BoundedMonomial t L) (b : BoundedMonomial t D) : List Bool :=
+ ExponentPack.packed w (List.ofFn (fun i => b.val i - a.val i))
+
+theorem packRaw_runs {w B : ℕ} (d : Inputs)
+ (a : BoundedMonomial d.arity (d.degree false)) (b : BoundedMonomial d.arity (d.degree true))
+ (fitS : ISA.Fits (ISA.graded d.arity (d.degree false) (d.ordinal false)) w)
+ (fitC : ISA.Fits (ISA.graded d.arity (d.degree true) (d.ordinal true)) w)
+ (packed flag : List Bool) (hB : ∀ i, (values w d (keys w a b) packed flag i).length ≤ B) :
+ ∃ n ≤ packClock d.arity w B, packRaw.BoundedRun (packSpace d.arity w B) n
+ (publicBank w d (keys w a b) packed flag)
+ (publicBank w d (keys w a b) (difference w a b ++ packed) (digits w (decide (a.val ≤ b.val)).toNat ++ flag)) := by
+ let x := values w d (keys w a b) packed flag
+ let R₀ := ExponentPack.initial w (d.degree false) (d.degree true) (rawCode a).val (rawCode b).val
+ have hin : CallBank.filled packSource packInputs x = ExponentPack.frame R₀ d.arity [] := by
+ funext i
+ rcases i with i | s
+ · cases i with
+ | reg j =>
+ have hm : (Sum.inl (.reg j) : ExponentPack.Port) ∈ packInputs := by simp [packInputs, wordPorts]
+ simp only [CallBank.filled, ite_eq_left hm]
+ fin_cases j <;> rfl
+ | persistent => simp [CallBank.filled, packInputs, wordPorts, packSource, x, values,
+ ExponentPack.frame, RAMTape.ISA.bank, digits]
+ | pub j => exact Fin.elim0 j
+ | work j => simp [CallBank.filled, packInputs, wordPorts, ExponentPack.frame, RAMTape.ISA.bank]
+ | logPort j => cases j <;> simp [CallBank.filled, packInputs, wordPorts, ExponentPack.frame,
+ RAMTape.ISA.bank, RAMTape.ISA.logStacks, AddressLog.keys, AddressLog.values]
+ · cases s <;> simp [CallBank.filled, packInputs, packSource, x, values, ExponentPack.frame]
+ obtain ⟨t,ht,R,hcore,hflag⟩ := ExponentPack.pack_rows_bounded a b fitS.limit_lt.le fitC.limit_lt.le
+ fitS.base_lt fitC.base_lt []
+ simp only [List.append_nil, List.length_nil, Nat.max_zero] at hcore
+ let v := ExponentPack.frame R 0 (difference w a b)
+ have hc : ExponentPack.machine.BoundedRun (packInnerSpace d.arity w) t
+ (ExponentPack.frame R₀ d.arity []) v := hcore
+ have hz (i : ExponentPack.Port) (hi : i ∉ packWipe) : v i = [] := by
+ rcases i with i | s
+ · apply register_empty_else R
+ exact fun he => hi (by simp [packWipe, packInputs, he])
+ · cases s <;> simp_all [packWipe, packInputs, v, ExponentPack.frame]
+ obtain ⟨n,hn,hr⟩ := CallBank.machine_run packSource packInputs ExponentPack.machine packOutputs packWipe
+ x _ v (by decide) hB hin hc hz
+ have hsave : CallBank.saved v packOutputs x = values w d (keys w a b) (difference w a b ++ packed)
+ (digits w (decide (a.val ≤ b.val)).toNat ++ flag) := by
+ change Function.update (Function.update (values w d (keys w a b) packed flag) .packed _) .flag _ = _
+ rw [update_packed]
+ change Function.update (values w d (keys w a b) (difference w a b ++ packed) flag)
+ .flag (BurstRAM.wordBits (R 4) ++ flag) = _
+ rw [hflag]
+ exact update_flag ..
+ rw [hsave] at hr
+ have lifted := lift_call (Sum.inr ∘ Sum.inl) (Sum.inr_injective.comp Sum.inl_injective) localPack hr
+ simp only [packInputs, packOutputs, packWipe, List.length_append, List.length_map, length_wordPorts,
+ List.length_cons, List.length_nil] at hn lifted
+ exact ⟨n,hn.trans (Nat.add_le_add_right ht _),lifted⟩
+
+end RadicalCertificate.MonomialIndex.PairCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayPairPorts.lean b/lean/OAI/Computability/VPVNP/MacaulayPairPorts.lean
new file mode 100644
index 0000000000..e3c6e668e8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayPairPorts.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.MacaulayCallBank
+import OAI.Computability.VPVNP.MacaulayExponentPack
+import OAI.Computability.VPVNP.MacaulayScalarRoutines
+
+/-! # Physical ports shared by the two ordinal scans and their entry routine -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.PairCall
+
+open RAMTape UniversalCountStack
+
+/-- `false` designates the source monomial and `true` the column. -/
+inductive Field where
+ | base (column : Bool) | box (column : Bool) | limit (column : Bool) | ordinal (column : Bool)
+ | raw (column : Bool)
+ | arity | marker | scale | mark | zero | one | packed | flag
+ deriving DecidableEq, Fintype
+
+/-- Private stack ports for the thirteen-register dense ordinal lookup with no public RAM
+operands. -/
+abbrev OrdBank := RAMTape.ISA.Port 13 0
+/-- Private stack ports for the fifteen-register powered-monomial comparison with no public RAM
+operands. -/
+abbrev PowerBank := RAMTape.ISA.Port 15 0
+/-- The disjoint private stacks used by ordinal lookup, residual-exponent packing and
+powered-exponent comparison. -/
+abbrev Private := OrdBank ⊕ (ExponentPack.Port ⊕ PowerBank)
+/-- Complete call frame containing the shared monomial fields, private routine stacks and copy
+scratch. -/
+abbrev Port := CallBank.Port Field Private
+
+/-- Query parameters for the two monomial scans and the optional shift and scale applied to the
+source. -/
+structure Inputs where
+ /-- Number of variables in both monomials and number of iterations in the exponent packer. -/
+ arity : ℕ
+ /-- Total-degree bound for the source when false and for the column when true. -/
+ degree : Bool → ℕ
+ /-- Zero-based position to look up in each of the two bounded-degree monomial enumerations. -/
+ ordinal : Bool → ℕ
+ /-- Power applied to the source monomial after its possible multiplication by a variable. -/
+ scale : ℕ
+ /-- One-based coordinate incremented before powering the source. Zero selects an unshifted
+ source. -/
+ mark : ℕ
+
+/-- Populate the public field stacks with scan parameters, unary markers, supplied raw keys,
+output buffers and the zero and one words. -/
+def values (w : ℕ) (d : Inputs) (raw : Bool → List Bool) (packed flag : List Bool) : Stacks Field
+ | .base c => digits w (d.degree c+1)
+ | .box c => digits w ((d.degree c+1)^d.arity)
+ | .limit c => digits w (rawSize d.arity (d.degree c))
+ | .ordinal c => digits w (d.ordinal c)
+ | .raw c => raw c
+ | .arity => digits w d.arity
+ | .marker => List.replicate d.arity true
+ | .scale => digits w d.scale
+ | .mark => digits w d.mark
+ | .zero => digits w 0
+ | .one => digits w 1
+ | .packed => packed
+ | .flag => flag
+
+/-- Install the public monomial query fields with all private stacks and copy scratch empty. -/
+def publicBank (w : ℕ) (d : Inputs) (raw : Bool → List Bool) (packed flag : List Bool) : Stacks Port :=
+ CallBank.clean (values w d raw packed flag)
+
+theorem values_le {w B : ℕ} (d : Inputs) (raw : Bool → List Bool) (packed flag : List Bool)
+ (hw : w ≤ B) (ht : d.arity ≤ B) (hr : ∀ c, (raw c).length ≤ B) (hp : packed.length ≤ B)
+ (hf : flag.length ≤ B) (i : Field) : (values w d raw packed flag i).length ≤ B := by
+ cases i <;> simp [values, hw, ht, hr, hp, hf]
+
+theorem update_raw (w : ℕ) (d : Inputs) (raw : Bool → List Bool) (packed flag v : List Bool) (c : Bool) :
+ Function.update (values w d raw packed flag) (.raw c) v =
+ values w d (Function.update raw c v) packed flag := by
+ funext i; cases i with
+ | raw j => by_cases h : j=c <;> simp [values, h]
+ | _ => rfl
+
+theorem update_packed (w : ℕ) (d : Inputs) (raw : Bool → List Bool) (packed flag v : List Bool) :
+ Function.update (values w d raw packed flag) .packed v = values w d raw v flag := by
+ funext i; cases i <;> rfl
+
+theorem update_flag (w : ℕ) (d : Inputs) (raw : Bool → List Bool) (packed flag v : List Bool) :
+ Function.update (values w d raw packed flag) .flag v = values w d raw packed v := by
+ funext i; cases i <;> rfl
+
+/-- Embed a routine's internal ports into the joint private bank while preserving its external
+fields and shared scratch port. -/
+def embed {I : Type} (f : I → Private) : CallBank.Port Field I → Port
+ | .internal i => .internal (f i)
+ | .external k => .external k
+ | .scratch => .scratch
+
+theorem embed_injective {I : Type} (f : I → Private) (hf : Function.Injective f) :
+ Function.Injective (embed f) := by
+ rintro (i | i | _) (j | j | _) h <;> simp_all [embed, hf.eq_iff]
+
+/-- Lift a cleaned private call into the shared bank. Ports outside the
+installed private block and caller slots are empty throughout the lift. -/
+theorem lift_call {I : Type} [DecidableEq I] (f : I → Private) (hf : Function.Injective f)
+ (r : FiniteRoutine (CallBank.Port Field I)) {C n : ℕ} {x y : Stacks Field}
+ (h : r.BoundedRun C n (CallBank.clean x) (CallBank.clean y)) :
+ (r.onPorts (embed f)).BoundedRun C n (CallBank.clean x) (CallBank.clean y) := by
+ let st : Stacks Port := CallBank.clean x
+ have installed (y : Stacks Field) :
+ installStacks (embed f) st (CallBank.clean y) = CallBank.clean y := by
+ apply installStacks_frame (ports := embed f) (base := st) (target := CallBank.clean y)
+ (small := CallBank.clean y) (embed_injective f hf)
+ · intro k; cases k <;> rfl
+ · rintro (k | i | _) hout <;> first | rfl | exact (hout (.external k) rfl).elim
+ have hh := FiniteRoutine.BoundedRun.onPorts (a := r) (embed_injective f hf) st h (by
+ rintro (k | i | _) hout <;> first | exact Nat.zero_le _ | exact (hout (.external k) rfl).elim)
+ rwa [installed, installed] at hh
+
+end RadicalCertificate.MonomialIndex.PairCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayPairPower.lean b/lean/OAI/Computability/VPVNP/MacaulayPairPower.lean
new file mode 100644
index 0000000000..eedf028e9f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayPairPower.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.MacaulayPairPack
+
+/-! # Returning the powered-row equality flag on the caller's physical ports -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.PairCall
+
+open RAMTape UniversalCountStack
+
+/-- Radices, scaling factor and marked coordinate for comparing a powered source monomial with
+a column monomial. The comparison requests no residual coordinate. -/
+def powerParams (d : Inputs) := ExponentISA.params (d.degree false) (d.degree true) d.scale d.mark 0
+
+private def powerSource : PowerBank → Field
+ | .reg i => match i.val with
+ | 0 => .base false
+ | 1 => .base true
+ | 2 => .scale
+ | 3 => .mark
+ | 5 => .arity
+ | 6 => .raw false
+ | 7 => .raw true
+ | 9 | 10 | 13 => .one
+ | _ => .zero
+ | _ => .zero
+
+private def localPower : FiniteRoutine (CallBank.Port Field PowerBank) :=
+ CallBank.machine powerSource (wordPorts 15) exponentRoutine [(.reg 10,.flag)] (wordPorts 15)
+
+/-- Run the exponent comparison on the caller's pair of raw monomial codes and push its
+equality flag onto the public flag stack. -/
+def powerRaw : FiniteRoutine Port := localPower.onPorts (embed (Sum.inr ∘ Sum.inr))
+
+/-- Instruction allowance for loading the exponent registers, returning the equality flag and
+clearing the call bank. -/
+def powerWork (w B : ℕ) := CallBank.overhead 16 1 16 B (w+(RAMTape.ISA.prepareBound w 0+3))
+
+/-- Bound on the length of any stack during a powered-row comparison, including the caller's
+stacks and the local exponent registers. -/
+def powerSpace (w B : ℕ) := B+(w+(RAMTape.ISA.prepareBound w 0+3))+powerWork w B
+
+/-- Tick bound for comparing all `t` coordinates of a powered row, including the transfers to
+and from the local call bank. -/
+def powerClock (t w B : ℕ) := (16*t+2)*(RAMTape.ISA.prepareBound w 0+3)+powerWork w B
+
+/-- Test whether the column exponents equal the source exponents after incrementing the marked
+coordinate, if present, and multiplying every exponent by the scale. -/
+def powerMatch (d : Inputs) (a : BoundedMonomial d.arity (d.degree false)) (b : BoundedMonomial d.arity (d.degree true)) :
+ Bool := decide (∀ i, ExponentISA.shifted d.scale d.mark a.val i = b.val i)
+
+theorem powerRaw_runs {w B : ℕ} (d : Inputs)
+ (a : BoundedMonomial d.arity (d.degree false)) (b : BoundedMonomial d.arity (d.degree true))
+ (hfit : ExponentISA.Fits (powerParams d) w) (ht : d.arity < 2^w)
+ (ha : (rawCode a).val < 2^w) (hb : (rawCode b).val < 2^w)
+ (packed flag : List Bool) (hB : ∀ i, (values w d (keys w a b) packed flag i).length ≤ B) :
+ ∃ n ≤ powerClock d.arity w B, powerRaw.BoundedRun (powerSpace w B) n
+ (publicBank w d (keys w a b) packed flag)
+ (publicBank w d (keys w a b) packed (digits w (powerMatch d a b).toNat ++ flag)) := by
+ let x := values w d (keys w a b) packed flag
+ let p := powerParams d
+ let input : ExponentISA.Work := ⟨d.arity, (rawCode a).val, (rawCode b).val,0,true,true,0,0⟩
+ have hin : CallBank.filled powerSource (wordPorts 15) x =
+ RegisterTable.bank Fin.elim0 0 (ExponentISA.registers w p input) := by
+ funext i
+ cases i with
+ | reg j =>
+ have hm : (RAMTape.ISA.Port.reg j : PowerBank) ∈ wordPorts 15 := by simp [wordPorts]
+ simp only [CallBank.filled, ite_eq_left hm]
+ fin_cases j <;> rfl
+ | persistent => simp [CallBank.filled, wordPorts, x, powerSource, values, RegisterTable.bank,
+ RAMTape.ISA.bank, digits]
+ | pub j => exact Fin.elim0 j
+ | work j => simp [CallBank.filled, wordPorts, RegisterTable.bank, RAMTape.ISA.bank]
+ | logPort j => cases j <;> simp [CallBank.filled, wordPorts, RegisterTable.bank, RAMTape.ISA.bank,
+ RAMTape.ISA.logStacks, AddressLog.keys, AddressLog.values]
+ obtain ⟨m,hm,out,hr,_,heq,_⟩ := exponentRoutine_runs p hfit (rawCode a).val (rawCode b).val ht ha hb
+ have pos (i : Fin d.arity) : d.arity-i.rev.val = i.val+1 := by
+ rw [Fin.val_rev]; have := i.isLt; omega
+ have hs (i : Fin d.arity) :
+ ExponentISA.scaledDigit p (d.arity-i.rev.val) ((rawCode a).val/p.sourceBase^i.rev.val) =
+ ExponentISA.shifted d.scale d.mark a.val i := by
+ change d.scale * ((rawCode a).val/(d.degree false+1)^i.rev.val%(d.degree false+1) +
+ if d.arity-i.rev.val = d.mark then 1 else 0) = _
+ rw [pos, ExponentPack.raw_digit]; rfl
+ have hc (i : Fin d.arity) : (rawCode b).val/p.columnBase^i.rev.val%p.columnBase = b.val i :=
+ ExponentPack.raw_digit b i
+ have hflag : out.same = powerMatch d a b := by
+ apply Bool.eq_iff_iff.mpr
+ rw [heq, powerMatch, decide_eq_true_eq]
+ constructor
+ · intro h i
+ simpa only [hs, hc] using h i.rev.val i.rev.isLt
+ · intro h k hk
+ let i : Fin d.arity := (⟨k,hk⟩ : Fin d.arity).rev
+ have h' := (hs i).trans ((h i).trans (hc i).symm)
+ simpa only [i, Fin.rev_rev] using h'
+ let v := RegisterTable.bank Fin.elim0 0 (ExponentISA.registers w p out)
+ obtain ⟨n,hn,hcall⟩ := CallBank.machine_run powerSource (wordPorts 15) exponentRoutine [(.reg 10,.flag)]
+ (wordPorts 15) x _ v (wordPorts_nodup _) hB hin hr (register_empty_else _)
+ have hsave : CallBank.saved v [(.reg 10,.flag)] x = values w d (keys w a b) packed (digits w (powerMatch d a b).toNat ++ flag) := by
+ change Function.update (values w d (keys w a b) packed flag) .flag (digits w out.same.toNat ++ flag) = _
+ rw [hflag]; exact update_flag ..
+ rw [hsave] at hcall
+ have lifted := lift_call (Sum.inr ∘ Sum.inr) (Sum.inr_injective.comp Sum.inr_injective) localPower hcall
+ simp only [length_wordPorts, List.length_cons, List.length_nil] at hn lifted
+ exact ⟨n,hn.trans (Nat.add_le_add_right hm _),lifted⟩
+
+end RadicalCertificate.MonomialIndex.PairCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayPinArm.lean b/lean/OAI/Computability/VPVNP/MacaulayPinArm.lean
new file mode 100644
index 0000000000..ac6e971389
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayPinArm.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.MacaulayReadArms
+import OAI.Computability.VPVNP.AffinePinCoefficient
+
+/-! # Calling the affine pin routine on the decoded Macaulay row
+
+The positive-divisibility branch takes its exponent buffer from the equation
+scan. It copies the decoded pin index, reads the pin table, and returns the
+field scalar directly on the matrix reader's result port.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.Arms.Pin
+
+open RAMTape BurstRAM SliceArithmetic MacaulayRowDispatch
+open RadicalCertificate.MonomialIndex
+
+set_option synthInstance.maxSize 2500
+
+variable {K : Type}
+
+private abbrev binary : AffinePin.Query.Port := .inl .binary
+private abbrev residual : AffinePin.Query.Port := .inl .exponents
+private abbrev result : AffinePin.Query.Port := .inl .value
+
+/-- Route the affine query's exponent input to the equation scan's packed residuals and its
+scalar output to the reader result. The other query ports use the embedded payload. -/
+def mount (inc : AffinePin.Query.Port ↪ K) (q : AffinePin.Query.Port) : Ports K :=
+ if q = residual then slot false (.external .packed)
+ else if q = result then .result else extra (.payload (inc q))
+
+theorem mount_injective (inc : AffinePin.Query.Port ↪ K) : Function.Injective (mount inc) := by
+ intro a b h
+ by_cases ha : a = residual <;> by_cases hb : b = residual <;>
+ by_cases ha' : a = result <;> by_cases hb' : b = result <;>
+ simp_all [mount, slot, extra]
+
+/-- Copy the decoded pin index to the affine query's binary input, then run the query on the
+reader's ports. -/
+def machine (inc : AffinePin.Query.Port ↪ K) : FiniteRoutine (Ports K) :=
+ (SuccessorFields.prependCopy (route (.reg (outReg 1))) (mount inc binary) (extra .temp)).followedBy
+ (AffinePin.Query.machine.onPorts (mount inc))
+
+/-- The embedded payload ports contain the initial affine query frame for the given pin advice,
+extension modulus and scalar word width. -/
+def Preloaded {p e : ℕ} (inc : AffinePin.Query.Port ↪ K) (A : AffinePin.Stage.Advice)
+ (c : Vector p e) (v : ℕ) (payload : Stacks K) : Prop :=
+ ∀ q, payload (inc q) = AffinePin.Query.frame A c v {} q
+
+/-- Install the initial affine query frame at the embedded payload ports of the given stack
+bank. -/
+noncomputable def preload {p e : ℕ} (inc : AffinePin.Query.Port ↪ K) (A : AffinePin.Stage.Advice)
+ (c : Vector p e) (v : ℕ) (base : Stacks K) : Stacks K :=
+ installStacks inc base (AffinePin.Query.frame A c v {})
+
+theorem preload_correct {p e : ℕ} (inc : AffinePin.Query.Port ↪ K) (A : AffinePin.Stage.Advice)
+ (c : Vector p e) (v : ℕ) (base : Stacks K) : Preloaded inc A c v (preload inc A c v base) :=
+ installStacks_at inc.injective base _
+
+private theorem unpack {p e w : ℕ} (inc : AffinePin.Query.Port ↪ K) (A : AffinePin.Stage.Advice)
+ (c : Vector p e) (v : ℕ) (aux : Stacks K) (h : Preloaded inc A c v aux)
+ (rs : Reg → Word w) (data : Bool → PairCall.Inputs) (packed flag constants : Bool → List Bool)
+ (res : List Bool) (q : AffinePin.Query.Port) :
+ frame rs res (storage w data packed flag constants aux) (mount inc q) =
+ AffinePin.Query.frame A c v {exponents := packed false, value := res} q := by
+ rcases q with q | q
+ · cases q <;> first | rfl | exact h _
+ · exact h _
+
+private theorem set_result [DecidableEq K] {w : ℕ} (rs : Reg → Word w) (s : Stacks (Leaf K))
+ (old new : List Bool) : Function.update (frame rs old s) .result new = frame rs new s := by
+ funext z; cases z <;> rfl
+
+private theorem set_residual [DecidableEq K] {w : ℕ} (rs : Reg → Word w) (res : List Bool)
+ (data : Bool → PairCall.Inputs) (pack flag constants : Bool → List Bool) (aux : Stacks K) :
+ Function.update (frame rs res (storage w data pack flag constants aux)) (slot false (.external .packed)) [] =
+ frame rs res (storage w data (Function.update pack false []) flag constants aux) := by
+ funext z
+ cases z with
+ | row | col | result => rfl
+ | aux z =>
+ rcases z with q | z
+ · cases q <;> rfl
+ rcases z with ⟨b,q⟩ | j
+ · cases b <;> cases q with
+ | external f => cases f <;> rfl
+ | internal | scratch => rfl
+ · cases j <;> rfl
+
+/-- Tick bound for copying a width-`w` pin index and looking up its affine coefficient. -/
+def cost (t e w v : ℕ) := 5*w+2 + AffinePin.Query.cost t e w v
+
+/-- One positive-divisibility affine call. The row decoder's register,
+the flag, the powered scan and the immutable advice survive the call. -/
+theorem bounded [DecidableEq K] {p e t w v S : ℕ} [Fact p.Prime] [NeZero e] {c : Vector p e}
+ (inc : AffinePin.Query.Port ↪ K) (hw : 0 d j)))
+ (hp : Preloaded inc (AffinePin.Query.advice w v pins a) c v aux)
+ (hS : AffinePin.Query.space t e w v ≤ S)
+ (room : ∀ z, ((frame rs [] (storage w data pack flag constants aux)) z).length + (5*w+2) ≤ S) :
+ let ans : Scalar c := if i∈pins then (if d=0 then -a i else if d=Finsupp.single i 1 then 1 else 0) else 0
+ ∃ steps ≤ cost t e w v, (machine inc).BoundedRun S steps (frame rs [] (storage w data pack flag constants aux))
+ (frame rs (Engine.scalar v ans) (storage w data (Function.update pack false []) flag constants aux)) := by
+ let A := AffinePin.Query.advice w v pins a
+ let start := frame rs [] (storage w data pack flag constants aux)
+ let digit := UniversalCountStack.digits w i.val
+ let mid := Function.update start (mount inc binary) digit
+ let ans : Scalar c := if i∈pins then (if d=0 then -a i else if d=Finsupp.single i 1 then 1 else 0) else 0
+ let finish := frame rs (Engine.scalar v ans) (storage w data (Function.update pack false []) flag constants aux)
+ have hwI : i.val < 2^w := hi ▸ (rs (outReg 1)).isLt
+ have hr : start (route (.reg (outReg 1))) = digit := by
+ rw [show start (route (.reg (outReg 1))) = wordBits (rs (outReg 1)) from frame_route ..]
+ apply congrArg wordBits
+ exact Fin.ext (hi.trans (Nat.mod_eq_of_lt hwI).symm)
+ have hsrc : (route (.reg (outReg 1)) : Ports K) = .aux (.inl (.reg (outReg 1))) := by
+ simp [route, inReg, outReg, Dispatch.Code.inReg, Dispatch.Code.outReg]
+ have hbin : start (mount inc binary) = [] := hp binary
+ have copy := SuccessorFields.prependCopy_runs (route (.reg (outReg 1))) (mount inc binary) (extra .temp)
+ (by rw [hsrc]; intro h; cases h) (by rw [hsrc]; intro h; cases h) (by intro h; cases h) start rfl
+ rw [hr, hbin, List.append_nil, UniversalCountStack.length_digits] at copy
+ have hb : (SuccessorFields.prependCopy (route (.reg (outReg 1))) (mount inc binary) (extra .temp)).BoundedRun S (5*w+2) start mid := UniversalCountStack.spaceRun_of_steps copy room
+ obtain ⟨n,hn,run⟩ := AffinePin.Query.bounded hw hv pins a i hwI d hd
+ have call : (AffinePin.Query.machine.onPorts (mount inc)).BoundedRun S n mid finish := by
+ apply (run.enlarge hS).framed (mount_injective inc) hb.final_cap
+ · intro q
+ by_cases h : q = binary
+ · subst q; exact Function.update_self ..
+ · rw [show mid (mount inc q) = start (mount inc q) from Function.update_of_ne (fun e => h (mount_injective inc e)) ..]
+ rw [show start = frame rs [] (storage w data pack flag constants aux) from rfl,
+ unpack inc A c v aux hp rs data pack flag constants [] q, hpack]
+ rcases q with q | q
+ · cases q <;> first | rfl | exact (h rfl).elim
+ · rfl
+ · intro q
+ have hu := unpack inc A c v aux hp rs data (Function.update pack false []) flag constants (Engine.scalar v ans) q
+ simpa only [Function.update_self] using hu
+ · intro z hz
+ have hh : finish = Function.update (Function.update start .result (Engine.scalar v ans))
+ (slot false (.external .packed)) [] := by rw [set_result, set_residual]
+ have hres : z ≠ slot false (.external .packed) := (hz residual).symm
+ have hout : z ≠ .result := (hz result).symm
+ rw [hh, Function.update_of_ne hres, Function.update_of_ne hout]
+ exact (Function.update_of_ne (fun e => hz binary e.symm) ..).symm
+ exact ⟨_, Nat.add_le_add_left hn _, hb.followedBy call⟩
+
+/-- The same bus call returns the coefficient of the field polynomial used
+in the Macaulay row, in the rank engine's power-basis representation. -/
+theorem coefficient [DecidableEq K] {p e t w v S : ℕ} [Fact p.Prime] [NeZero e] {c : Vector p e}
+ {F ι : Type*} [Field F] [Algebra (ZMod p) F] (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F)
+ (system : ι → MvPolynomial (Fin t) F) (inc : AffinePin.Query.Port ↪ K)
+ (hw : 0 d j)))
+ (hp : Preloaded inc (AffinePin.Query.advice w v pins (fun j => AffinePin.Query.encode φ (a j))) c v aux)
+ (hS : AffinePin.Query.space t e w v ≤ S)
+ (room : ∀ z, ((frame rs [] (storage w data pack flag constants aux)) z).length + (5*w+2) ≤ S) :
+ let ans := AffinePin.Query.encode φ ((SliceGeometry.pinnedEquations system pins a (.inr i)).coeff d)
+ ∃ steps ≤ cost t e w v, (machine inc).BoundedRun S steps (frame rs [] (storage w data pack flag constants aux))
+ (frame rs (Engine.scalar v ans) (storage w data (Function.update pack false []) flag constants aux)) := by
+ dsimp only
+ rw [← AffinePin.Query.encode_pin φ system pins a i d]
+ exact bounded inc hw hv pins (fun j => AffinePin.Query.encode φ (a j)) i d hd rs hi data pack flag constants
+ aux hpack hp hS room
+
+end RankQuery.Stack.MacaulayRead.Arms.Pin
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayPinRow.lean b/lean/OAI/Computability/VPVNP/MacaulayPinRow.lean
new file mode 100644
index 0000000000..80c6e66724
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayPinRow.lean
@@ -0,0 +1,111 @@
+import OAI.Computability.VPVNP.MacaulayAppendedPower
+
+/-! # Complete physical Macaulay read for a coordinate-pin row
+
+The ordinal scans produce the two monomials and their divisibility flag.
+On a divisible column the coefficient program reads the nominated affine
+pin and the residual exponent. Otherwise the phase emits its stored zero
+scalar. Cleanup restores the common reader bank in both cases.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.Arms
+
+open RAMTape BurstRAM MacaulayRowDispatch RadicalCertificate RadicalCertificate.MonomialIndex SliceArithmetic
+open UniversalCountStack (digits)
+
+set_option synthInstance.maxSize 3000
+
+variable {p e w v : ℕ} [Fact p.Prime] [NeZero e] {c : Vector p e}
+variable {F ι : Type*} [Field F] [Algebra (ZMod p) F]
+
+theorem pin_row_plan (P : ReaderPlan) (Q : QueryData P.arity (P.equations+P.pins) F)
+ (h : P.Covers Q) {E V : ℕ} (he : e ≤ E) (hv : v ≤ V) (sp ex : ℕ)
+ (hw : P.wordWidth ≤ w) (working : SliceArithmetic.Word.workingWidth p ≤ v)
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (system : ι → MvPolynomial (Fin P.arity) F)
+ (pins : Finset (Fin P.arity)) (values : Fin P.arity → F) (row : Fin P.arity)
+ (L : JointScalar.Leaf.Layout) (hlayout : JointScalar.Leaf.bankSize L w (P.arity*w) ≤ sp)
+ (rs : Reg → BurstRAM.Word w) (hrow : (rs (outReg 1)).val=row.val)
+ (source : Fin (size P.arity Q.multiplierDegree)) (column : Fin (size P.arity Q.columnDegree))
+ (hsource : (rs (outReg 2)).val=source.val) (hcolumn : (rs (outReg 3)).val=column.val) :
+ let data := BaseAdvice.inputs Q
+ let constants := BaseAdvice.scalars c v
+ let aux := coefficientAdvice L w v pins (fun j => AffinePin.Query.encode φ (values j))
+ let a := enumeration P.arity Q.multiplierDegree source
+ let b := enumeration P.arity Q.columnDegree column
+ let val := if a.val ≤ b.val then AffinePin.Query.encode φ
+ ((SliceGeometry.pinnedEquations system pins values (.inr row)).coeff (b.val-a.val)) else 0
+ ∃ n ≤ P.armTime E V w sp ex,
+ (phase false (Pin.machine (K := CoefficientPort) Function.Embedding.inr)).BoundedRun (P.armSpace E V w sp) n
+ (frame rs [] (storage w data blank blank constants aux))
+ (frame rs (Engine.scalar v val) (storage w data blank blank constants aux)) := by
+ intro data constants aux a b val
+ let A := P.live E V w sp
+ let S := P.armSpace E V w sp
+ let d := addressed rs (data false)
+ let ords : PairCall.Ordinals d := fun b => match b with
+ | false => source | true => column
+ have hk (j : Bool) : d.ordinal j = (ords j).val := by cases j; exact hsource; exact hcolumn
+ have hL : d.degree false ≤ P.source := h.degrees.2.1.trans (le_max_right ..)
+ have hD : d.degree true ≤ P.column := h.degrees.2.2
+ have hwidth := (P.pairWidth_le d rfl hL hD (le_max_left ..) (Nat.zero_le _)).trans hw
+ obtain ⟨fit,_⟩ := PairCall.fits_of_width d ords hwidth
+ obtain ⟨live,cap,_⟩ := P.leaf_bounds w sp ex he hv d rfl hL hD
+ have hpre : Preload (w := w) A data constants aux :=
+ coefficientAdvice_preload rfl he hv hlayout pins _ data (fun _ => rfl) constants
+ (fun bit => (Engine.scalar_length v (if bit then (1 : Scalar c) else 0)).le)
+ have pinReady := (coefficientAdvice_loaded L w v pins (fun j => AffinePin.Query.encode φ (values j))).2
+ have hw1 : 1 ≤ w := (by decide : 1≤2).trans (P.dispatchWidth.2.2.trans hw)
+ let delta := b.val-a.val
+ let scalar := AffinePin.Query.encode φ ((SliceGeometry.pinnedEquations system pins values (.inr row)).coeff delta)
+ let pack := selected false (PairCall.difference w a b)
+ let flag := selected false (digits w (decide (a.val ≤ b.val)).toNat)
+ let leaf := Pin.machine (K := CoefficientPort) Function.Embedding.inr
+ have dfit (j : Fin P.arity) : delta j < 2^w := by
+ have limit : Q.columnDegree+1 < 2^w := (fit true).base_lt
+ exact (Nat.sub_le ..).trans_lt ((b.encode j).isLt.trans limit)
+ have yes (_ : a.val ≤ b.val) : ∃ n ≤ Pin.cost P.arity e w v, ∃ rest : List Bool, rest.length ≤ P.arity*w ∧
+ leaf.BoundedRun S n (frame rs [] (storage w data pack flag constants aux))
+ (frame rs (Engine.scalar v scalar) (storage w data (selected false rest) flag constants aux)) := by
+ have hbuf (bit : Bool) : (pack bit).length ≤ A := by
+ cases bit <;> simp [pack,selected,blank]
+ exact live.2.2.1
+ have hflag (bit : Bool) : (flag bit).length ≤ A := by
+ cases bit <;> simp [flag,selected,blank]
+ exact live.1
+ have hf := frame_bound rs [] data pack flag constants aux hpre.words (by simp) hpre.arity hbuf hflag hpre.scalars hpre.payload
+ have room (z) : (frame rs [] (storage w data pack flag constants aux) z).length+(5*w+2) ≤ S :=
+ (Nat.add_le_add_right ((hf z).trans (le_max_left ..)) _).trans cap.2.2.2.2
+ have haS : AffinePin.Query.space P.arity e w v ≤ S := live.2.2.2.2.2.trans
+ ((Nat.le_add_right A _).trans cap.2.2.1)
+ obtain ⟨n,hn,hr⟩ := Pin.coefficient φ system (K := CoefficientPort) Function.Embedding.inr
+ hw1 working pins values row delta dfit rs hrow data pack flag constants aux
+ (by rw [show pack false=PairCall.difference w a b from Function.update_self ..]; rfl)
+ pinReady haS room
+ have eq : Function.update pack false [] = selected false [] := Function.update_idem ..
+ refine ⟨n,hn,[],by simp,?_⟩
+ rw [← eq]
+ exact hr
+ have hlen : (Engine.scalar v scalar).length ≤ A := (Engine.scalar_length v scalar).le.trans live.2.2.2.1
+ obtain ⟨n,hn,run⟩ := equation_execution rs data constants aux hpre hw1 leaf (Engine.scalar v scalar) hlen
+ (Pin.cost P.arity e w v) ords hk fit cap.1 cap.2.2.2.1 yes
+ have scan := (P.scan_bounds w A d rfl hL hD).1
+ have hp : Pin.cost P.arity e w v ≤ P.scalarTime E V w ex :=
+ (Nat.add_le_add_left (ReaderPlan.pin_cost_mono P.arity w he hv) _).trans ((le_max_left ..).trans (le_max_right ..))
+ have post : postTicks A P.arity w (Pin.cost P.arity e w v) ≤ postTicks A P.arity w (P.scalarTime E V w ex) := by
+ unfold postTicks; gcongr
+ refine ⟨n,hn.trans (Nat.add_le_add scan post),?_⟩
+ change (phase false leaf).BoundedRun S n _ (frame rs (if a.val ≤ b.val then Engine.scalar v scalar else constants false) _) at run
+ by_cases div : a.val ≤ b.val
+ · simpa only [val,div,ite_true,scalar] using run
+ · have hz : constants false = Engine.scalar v (0 : Scalar c) := by simp [constants,BaseAdvice.scalars]
+ simpa only [val,div,ite_false,hz] using run
+
+end RankQuery.Stack.MacaulayRead.Arms
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayQueryBounds.lean b/lean/OAI/Computability/VPVNP/MacaulayQueryBounds.lean
new file mode 100644
index 0000000000..325da7fc2d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayQueryBounds.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.MacaulaySliceBasis
+import OAI.Computability.VPVNP.MacaulayIndexISA
+
+/-!
+# Widths of the numerical Macaulay queries
+
+The binary logarithms of the certificate degree, powering exponent, raw
+graded keys, and augmented matrix dimensions are bounded using the input
+parameters of Lemma 8.2. The fixed radix-scan program uses a common register
+width that also covers its digit sum.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex
+
+open PolynomiallyBounded
+
+/-- An explicit common binary word width for every dense ordinal and for
+the counting mode. The extra bit accommodates equality with the upper limit. -/
+def scanWidth (t D : ℕ) :=
+ 1 + Nat.clog 2 (2 + rawSize t D + t + t*D)
+
+theorem graded_fits {t D k : ℕ} (hk : k ≤ rawSize t D) :
+ ISA.Fits (ISA.graded t D k) (scanWidth t D) := by
+ let B := 2 + rawSize t D + t + t*D
+ have hb : B < 2 ^ scanWidth t D := by
+ have h := Nat.le_pow_clog (b := 2) (by decide) B
+ change B < 2^(1 + Nat.clog 2 B)
+ rw [pow_add]
+ have := Nat.two_pow_pos (Nat.clog 2 B)
+ omega
+ have hbox : (D+1)^t ≤ rawSize t D := Nat.le_mul_of_pos_left _ (Nat.succ_pos _)
+ have hbase : D+1 ≤ rawSize t D := Nat.le_mul_of_pos_right _ (Nat.pow_pos (Nat.succ_pos _))
+ dsimp only [B] at hb
+ refine ⟨by omega, Nat.succ_pos _, ?_, ?_, ?_, ?_, ?_, ?_⟩ <;> dsimp [ISA.graded] <;> omega
+
+variable {t e : ℕ → ℕ} {K : ℕ → Type*} (S : (n : ℕ) → QueryData (t n) (e n) (K n))
+
+theorem bounded_rawSize {t D : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hD : PolynomiallyBounded (fun n => Nat.clog 2 (D n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (rawSize (t n) (D n))) := by
+ have hb := clog_add hD (clog (PolynomiallyBounded.const 1))
+ exact clog_mul hb (clog_pow hb ht)
+
+theorem bounded_scanWidth {t D : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hD : PolynomiallyBounded (fun n => Nat.clog 2 (D n))) :
+ PolynomiallyBounded (fun n => scanWidth (t n) (D n)) :=
+ (PolynomiallyBounded.const 1).add
+ (clog_add (clog_add (clog_add (clog (PolynomiallyBounded.const 2)) (bounded_rawSize ht hD)) (clog ht))
+ (clog_mul (clog ht) hD))
+
+/-- Row and column dimensions, and the word widths of each monomial lookup,
+are polynomial on a binary logarithmic scale for the exact QueryData parameters. -/
+theorem bounded_query_dimensions
+ (ht : PolynomiallyBounded t) (he : PolynomiallyBounded (fun n => Nat.clog 2 (e n)))
+ (hQ : PolynomiallyBounded (fun n => Nat.clog 2 (S n).fieldOrder))
+ (hd : PolynomiallyBounded (fun n => Nat.clog 2 (S n).degreeBound))
+ (hN : PolynomiallyBounded (fun n => Nat.clog 2 (S n).pointBound))
+ (hQpos : ∀ n, 2 ≤ (S n).fieldOrder) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (e n * size (t n) (S n).multiplierDegree + size (t n) (S n).pointBound)) ∧
+ PolynomiallyBounded (fun n => Nat.clog 2 (size (t n) (S n).columnDegree)) ∧
+ PolynomiallyBounded (fun n => scanWidth (t n) (S n).multiplierDegree) ∧
+ PolynomiallyBounded (fun n => scanWidth (t n) (S n).columnDegree) ∧
+ PolynomiallyBounded (fun n => scanWidth (t n) (S n).pointBound) := by
+ have one := clog (PolynomiallyBounded.const 1)
+ have hR : PolynomiallyBounded (fun n => Nat.clog 2 (S n).targetDegree) := clog_mul (clog_add hN one) hQ
+ have hmax : PolynomiallyBounded (fun n => Nat.clog 2 (max (S n).degreeBound ((S n).targetDegree+1))) :=
+ (clog_add hd (clog_add hR one)).of_le fun n => Nat.clog_mono_right _ (by omega)
+ have hH : PolynomiallyBounded (fun n => Nat.clog 2 (S n).certificateDegree) :=
+ clog_pow (clog_mul (clog (PolynomiallyBounded.const 2)) hmax)
+ ((PolynomiallyBounded.const 4).mul (ht.add (PolynomiallyBounded.const 3)))
+ have hs : PolynomiallyBounded (fun n => (S n).powerExponent) := hH.of_le fun n =>
+ Nat.clog_anti_left (by decide) (hQpos n)
+ have hP : PolynomiallyBounded (fun n => Nat.clog 2 (S n).power) := clog_pow hQ hs
+ have hL : PolynomiallyBounded (fun n => Nat.clog 2 (S n).multiplierDegree) := clog_add hH (clog_mul hP hR)
+ have hD : PolynomiallyBounded (fun n => Nat.clog 2 (S n).columnDegree) := clog_add hL hd
+ have hsize (D : ℕ → ℕ) (hb : PolynomiallyBounded (fun n => Nat.clog 2 (D n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (size (t n) (D n))) := by
+ simpa only [size_eq_card] using polynomiallyBounded_clog_boundedMonomial ht hb
+ exact ⟨clog_add (clog_mul he (hsize _ hL)) (hsize _ hN), hsize _ hD,
+ bounded_scanWidth ht hL, bounded_scanWidth ht hD, bounded_scanWidth ht hN⟩
+
+end RadicalCertificate.MonomialIndex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayReadArms.lean b/lean/OAI/Computability/VPVNP/MacaulayReadArms.lean
new file mode 100644
index 0000000000..8b312ee84f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayReadArms.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.MacaulayReadRouter
+import OAI.Computability.VPVNP.MacaulayPairCall
+
+/-! # Native exponent scans in the matrix reader
+
+The source and column ordinals are the third and fourth words returned by the
+row decoder. The equation and powered-row scans use separate advised radix
+bounds. Each scan preserves the decoded words, returning its flag and exponent
+buffer to the selected coefficient routine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.Arms
+
+open BurstRAM RAMTape UniversalCountStack MacaulayRowDispatch
+open RadicalCertificate.MonomialIndex
+
+/-- Auxiliary ports for the encodings of zero and one, a temporary copy stack and the
+coefficient routine's payload. -/
+inductive Extra (K : Type) where
+ | zeroScalar | oneScalar | temp | payload (k : K)
+ deriving DecidableEq, Fintype
+
+/-- Private ports of the matrix reader. Each of its two monomial scans has a pair-call bank
+alongside the shared auxiliary ports. -/
+abbrev Leaf (K : Type) := (Bool × PairCall.Port) ⊕ Extra K
+set_option synthInstance.maxSize 2500 in
+instance {K : Type} [DecidableEq K] : DecidableEq (Leaf K) :=
+ inferInstanceAs (DecidableEq ((Bool × PairCall.Port) ⊕ Extra K))
+
+/-- The matrix reader's row, column and result ports together with its decoder, monomial scans
+and coefficient payload. -/
+abbrev Ports (K : Type) := Bus (Leaf K)
+
+variable {K : Type}
+
+/-- Locate a pair-call stack in the private bank for the ordinary scan or the powered-row scan. -/
+def slot (power : Bool) (q : PairCall.Port) : Ports K := .aux (.inr (.inl (power,q)))
+/-- Locate a shared auxiliary stack of the coefficient routines on the matrix reader's bus. -/
+def extra (x : Extra K) : Ports K := .aux (.inr (.inr x))
+
+/-- Output-field index for a decoded monomial ordinal. The source uses field 2 and the column
+uses field 3. -/
+def ordinalField (b : Bool) : Fin 6 := if b then 3 else 2
+
+/-- Alias the two ordinal inputs to the decoded words on the physical bus. -/
+def pairPorts (power : Bool) : PairCall.Port → Ports K
+ | .external (.ordinal b) => route (.reg (outReg (ordinalField b)))
+ | q => slot power q
+
+theorem pairPorts_injective (power : Bool) : Function.Injective (pairPorts (K := K) power) := by
+ intro a b h
+ have left (b : Bool) : route (.reg (outReg (ordinalField b))) = (.aux (.inl (.reg (outReg (ordinalField b)))) : Ports K) := by
+ cases b <;> simp [route, ordinalField, inReg, outReg, Dispatch.Code.inReg, Dispatch.Code.outReg]
+ let ord (b : Bool) : PairCall.Port := .external (.ordinal b)
+ have other (q : PairCall.Port) (h₀ : q ≠ ord false) (h₁ : q ≠ ord true) :
+ pairPorts (K := K) power q = slot power q := by
+ cases q with
+ | external f => cases f with
+ | ordinal x => cases x <;> contradiction
+ | _ => rfl
+ | internal | scratch => rfl
+ have h₀ : pairPorts (K := K) power (ord false) = .aux (.inl (.reg (outReg 2))) := left false
+ have h₁ : pairPorts (K := K) power (ord true) = .aux (.inl (.reg (outReg 3))) := left true
+ have distinct : outReg 2 ≠ outReg 3 := by intro he; have := congrArg Fin.val he; contradiction
+ by_cases ha : a = ord false <;> by_cases ha' : a = ord true <;>
+ by_cases hb : b = ord false <;> by_cases hb' : b = ord true <;>
+ simp_all [slot, Ne.symm distinct]
+
+/-- Storage owned by the matrix reader. Aliased ordinal stacks have no
+private copy. The other bank remains intact when a scan updates its buffer. -/
+def storage (w : ℕ) (data : Bool → PairCall.Inputs) (packed flag : Bool → List Bool)
+ (constants : Bool → List Bool) (payload : Stacks K) : Stacks (Leaf K)
+ | .inl (_, .external (.ordinal _)) => []
+ | .inl (b,q) => PairCall.publicBank w (data b) (fun _ => []) (packed b) (flag b) q
+ | .inr .zeroScalar => constants false
+ | .inr .oneScalar => constants true
+ | .inr .temp => []
+ | .inr (.payload k) => payload k
+
+/-- Fill the pair scan's source and column ordinals from the row decoder's output registers. -/
+def addressed {w : ℕ} (rs : Reg → Word w) (d : PairCall.Inputs) : PairCall.Inputs :=
+ {d with ordinal := fun b => (rs (outReg (ordinalField b))).val}
+
+theorem pairFrame {w : ℕ} (rs : Reg → Word w) (res : List Bool) (d : Bool → PairCall.Inputs)
+ (pack flag : Bool → List Bool) (v : Bool → List Bool) (aux : Stacks K) (b : Bool) (q : PairCall.Port) :
+ frame rs res (storage w d pack flag v aux) (pairPorts b q) =
+ PairCall.publicBank w (addressed rs (d b)) (fun _ => []) (pack b) (flag b) q := by
+ cases q with
+ | external x =>
+ cases x <;> first | rfl | (rw [pairPorts, frame_route]; simp [addressed, PairCall.publicBank,
+ RadicalCertificate.MonomialIndex.CallBank.clean, RadicalCertificate.MonomialIndex.CallBank.frame,
+ PairCall.values, digits, ISA.bank])
+ | internal | scratch => rfl
+
+private theorem private_preserved {w : ℕ} (rs : Reg → Word w) (res : List Bool) (d : Bool → PairCall.Inputs)
+ (pack flag : Bool → List Bool) (v : Bool → List Bool) (aux : Stacks K) (b : Bool) (p' f' : List Bool)
+ (z : Ports K) (outside : ∀ q, pairPorts b q ≠ z) :
+ frame rs res (storage w d (Function.update pack b p') (Function.update flag b f') v aux) z =
+ frame rs res (storage w d pack flag v aux) z := by
+ cases z with
+ | row | col | result => rfl
+ | aux z =>
+ rcases z with q | x
+ · cases q <;> rfl
+ rcases x with ⟨a,q⟩ | y
+ · by_cases he : a = b
+ · subst a
+ cases q with
+ | external f => cases f with
+ | packed => exact (outside (.external .packed) rfl).elim
+ | flag => exact (outside (.external .flag) rfl).elim
+ | _ => rfl
+ | internal | scratch => rfl
+ · cases q with
+ | external f => cases f <;> first | rfl | simp [frame, bank, auxBank, storage, he,
+ PairCall.publicBank, RadicalCertificate.MonomialIndex.CallBank.clean, RadicalCertificate.MonomialIndex.CallBank.frame, PairCall.values]
+ | internal | scratch => rfl
+ · cases y <;> rfl
+
+/-- Run either physical pair scan in the full reader. Only its own output
+buffer and flag change. All other scratch is restored at the call boundary. -/
+theorem scan_bounded [DecidableEq K] {w S n : ℕ} (r : FiniteRoutine PairCall.Port) (b : Bool) (rs : Reg → Word w)
+ (res : List Bool) (d : Bool → PairCall.Inputs) (pack flag : Bool → List Bool) (v : Bool → List Bool)
+ (aux : Stacks K) (p' f' : List Bool)
+ (run : r.BoundedRun S n (PairCall.publicBank w (addressed rs (d b)) (fun _ => []) (pack b) (flag b))
+ (PairCall.publicBank w (addressed rs (d b)) (fun _ => []) p' f'))
+ (room : ∀ z, (frame rs res (storage w d pack flag v aux) z).length ≤ S) :
+ (r.onPorts (pairPorts b)).BoundedRun S n (frame rs res (storage w d pack flag v aux))
+ (frame rs res (storage w d (Function.update pack b p') (Function.update flag b f') v aux)) := by
+ apply run.framed (pairPorts_injective b) room (pairFrame rs res d pack flag v aux b)
+ · intro q
+ simpa only [Function.update_self] using pairFrame rs res d (Function.update pack b p') (Function.update flag b f') v aux b q
+ · exact private_preserved rs res d pack flag v aux b p' f'
+
+end RankQuery.Stack.MacaulayRead.Arms
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayReadBlocks.lean b/lean/OAI/Computability/VPVNP/MacaulayReadBlocks.lean
new file mode 100644
index 0000000000..af523067d4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayReadBlocks.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.MacaulayReadRouter
+import OAI.Computability.VPVNP.MacaulayRowIndex
+
+/-! # Joining the three physical row blocks on the determinant engine's ABI
+
+The first two blocks have product indices for an equation and its multiplier
+monomial. The appended monomials have one index each. This proof combines the
+three typed native reads without reconstructing a matrix or restricting its
+queried row or column.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead
+
+open RAMTape MacaulayRowDispatch BurstRAM Engine
+
+variable {K : Type} [DecidableEq K] {p e rows pins mult extra cols w v B S : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- Index the row for equation or affine pin `r` multiplied by monomial `o` in the augmented
+matrix. -/
+abbrev rowOf (r : Fin (rows+pins)) (o : Fin mult) : Fin ((rows+pins)*mult+extra) :=
+ (finProdFinEquiv (r,o)).castAdd extra
+/-- Index the powered monomial at suffix ordinal `o`, after all multiples of equations and
+pins. -/
+abbrev appended (o : Fin extra) : Fin ((rows+pins)*mult+extra) := o.natAdd ((rows+pins)*mult)
+
+variable (M : Matrix (Fin ((rows+pins)*mult+extra)) (Fin cols) (Scalar c))
+variable (leaf : Stacks K) (arms : Kind → FiniteRoutine (Bus K))
+
+/-- All three local reads preserve the decoder and its coefficient advice. -/
+abbrev BlockRun (kind : Kind) (rs : Reg → Word w) (i : Fin ((rows+pins)*mult+extra)) (j : Fin cols) :=
+ ∃ ticks ≤ B, (arms kind).BoundedRun S ticks (frame rs [] leaf) (frame rs (scalar v (M i j)) leaf)
+
+private theorem rowVal (r : Fin (rows+pins)) (o : Fin mult) : (rowOf (extra := extra) r o).val = r.val*mult+o.val := by
+ dsimp [rowOf,finProdFinEquiv]; ac_rfl
+
+/-- From one typed call for each row block, obtain the raw arm contract on
+all addresses, with one common immutable coefficient bank. -/
+theorem armCorrect_of_blocks
+ (eqn : ∀ (rs : Reg → Word w) (r : Fin rows) (o : Fin mult) (j : Fin cols),
+ (rs (outReg 1)).val = r.val → (rs (outReg 2)).val = o.val → (rs (outReg 3)).val = j.val →
+ BlockRun (B := B) (S := S) (v := v) M leaf arms .equation rs (rowOf (r.castAdd pins) o) j)
+ (affine : ∀ (rs : Reg → Word w) (r : Fin pins) (o : Fin mult) (j : Fin cols),
+ (rs (outReg 1)).val = r.val → (rs (outReg 2)).val = o.val → (rs (outReg 3)).val = j.val →
+ BlockRun (B := B) (S := S) (v := v) M leaf arms .affine rs (rowOf (r.natAdd rows) o) j)
+ (power : ∀ (rs : Reg → Word w) (o : Fin extra) (j : Fin cols),
+ (rs (outReg 2)).val = o.val → (rs (outReg 3)).val = j.val →
+ BlockRun (B := B) (S := S) (v := v) M leaf arms .power rs (appended o) j) :
+ ArmCorrect M w v rows pins mult B S (fun s => s = leaf) arms := by
+ intro i j rs state hin hout hs
+ subst state
+ have params : Params rows pins mult rs := by
+ intro a h
+ rw [hin]
+ fin_cases a <;> first | rfl | exact False.elim ((by decide : ¬ (2 ≤ (0 : Fin 8).val)) h) | exact False.elim ((by decide : ¬ (2 ≤ (1 : Fin 8).val)) h)
+ have hf (bits : List Bool) : frame rs bits leaf = bank w i j bits (auxBank rs leaf) := by
+ change bank w _ _ bits _ = _
+ rw [show (rs (inReg 0)).val = i.val from hin 0, show (rs (inReg 1)).val = j.val from hin 1]
+ have finish (u : Fin ((rows+pins)*mult+extra)) (k : Kind) (hk : (address u j rows pins mult).kind = k)
+ (run : BlockRun (B := B) (S := S) (v := v) M leaf arms k rs u j) (hu : u = i) :
+ ∃ z ≤ B, ∃ out, Ready w rows pins mult (fun s => s = leaf) out ∧
+ (arms (address i j rows pins mult).kind).BoundedRun S z (frame rs [] leaf)
+ (bank w i j (scalar v (M i j)) out) := by
+ subst u
+ obtain ⟨z,hz,run⟩ := run
+ exact ⟨z,hz,auxBank rs leaf,⟨rs,leaf,params,rfl,rfl⟩,hk.symm ▸ hf _ ▸ run⟩
+ cases i using Fin.addCases with
+ | left i =>
+ obtain ⟨⟨r,o⟩,rfl⟩ := finProdFinEquiv.surjective i
+ cases r using Fin.addCases with
+ | left r =>
+ have ha : address (rowOf (extra := extra) (r.castAdd pins) o) j rows pins mult = ⟨.equation,r.val,o.val,j.val⟩ := by
+ rw [rowVal]; exact original_address r o j
+ change ∀ a, (rs (outReg a)).val = (address (rowOf (extra := extra) (r.castAdd pins) o) j rows pins mult).fields a at hout
+ rw [ha] at hout
+ exact finish _ _ (congrArg Address.kind ha) (eqn rs r o j (hout 1) (hout 2) (hout 3)) rfl
+ | right r =>
+ have ha : address (rowOf (extra := extra) (r.natAdd rows) o) j rows pins mult = ⟨.affine,r.val,o.val,j.val⟩ := by
+ rw [rowVal]; exact affine_address r o j
+ change ∀ a, (rs (outReg a)).val = (address (rowOf (extra := extra) (r.natAdd rows) o) j rows pins mult).fields a at hout
+ rw [ha] at hout
+ exact finish _ _ (congrArg Address.kind ha) (affine rs r o j (hout 1) (hout 2) (hout 3)) rfl
+ | right o =>
+ have ha : address (appended (rows := rows) (pins := pins) (mult := mult) o) j rows pins mult = ⟨.power,0,o.val,j.val⟩ := power_address ..
+ change ∀ a, (rs (outReg a)).val = (address (appended (rows := rows) (pins := pins) (mult := mult) o) j rows pins mult).fields a at hout
+ rw [ha] at hout
+ exact finish _ _ (congrArg Address.kind ha) (power rs o j (hout 2) (hout 3)) rfl
+
+end RankQuery.Stack.MacaulayRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayReadFinish.lean b/lean/OAI/Computability/VPVNP/MacaulayReadFinish.lean
new file mode 100644
index 0000000000..9b436d1c63
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayReadFinish.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.MacaulayReadArms
+import OAI.Computability.VPVNP.MacaulayPairEntries
+
+/-! # Selecting a matrix entry and reclaiming its temporary buffers
+
+Divisibility selects either the coefficient routine or the zero scalar. On a
+powered row, equality selects an advised encoding of zero or one. The bit
+selection preserves its full flag word. Both the exponent buffer and flag
+are cleared before the next matrix read.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.Arms
+
+open BurstRAM RAMTape UniversalCountStack MacaulayRowDispatch RadicalCertificate.MonomialIndex
+
+variable {K : Type} [DecidableEq K]
+
+private def scalarPort (b : Bool) : Ports K := extra (if b then .oneScalar else .zeroScalar)
+
+/-- Prepend the stored field encoding of zero or one to the reader's result stack according to
+the given bit. -/
+def emit (bit : Bool) : FiniteRoutine (Ports K) :=
+ SuccessorFields.prependCopy (scalarPort bit) .result (extra .temp)
+
+/-- Clear the packed exponents and flag left by the selected monomial scan. -/
+def erase (power : Bool) : FiniteRoutine (Ports K) :=
+ (SliceArithmetic.CallClear.clear (slot power (.external .packed))).followedBy
+ (SliceArithmetic.CallClear.clear (slot power (.external .flag)))
+
+/-- Read the scan flag, emit zero on a failed match or run the supplied coefficient routine on
+a match, then clear the scan buffers. -/
+def finish (power : Bool) (leaf : FiniteRoutine (Ports K)) : FiniteRoutine (Ports K) :=
+ (TagRouter.select (slot power (.external .flag)) 1 (fun bit => if bit = 0 then emit false else leaf)).followedBy
+ (erase power)
+
+private theorem putResult {w : ℕ} (rs : Reg → Word w) (s : Stacks (Leaf K)) (old new : List Bool) :
+ Function.update (frame rs old s) .result new = frame rs new s := by
+ funext z; cases z <;> rfl
+
+private theorem putPacked {w : ℕ} (rs : Reg → Word w) (res : List Bool) (b : Bool) (data : Bool → PairCall.Inputs)
+ (pack flag constants : Bool → List Bool) (aux : Stacks K) (new : List Bool) :
+ Function.update (frame rs res (storage w data pack flag constants aux)) (slot b (.external .packed)) new =
+ frame rs res (storage w data (Function.update pack b new) flag constants aux) := by
+ funext z
+ cases z with
+ | row | col | result => rfl
+ | aux x =>
+ rcases x with q | x
+ · cases q <;> rfl
+ rcases x with ⟨a,q⟩ | x
+ · cases b <;> cases a <;> cases q with
+ | external f => cases f <;> rfl
+ | internal | scratch => rfl
+ · cases x <;> rfl
+
+private theorem putFlag {w : ℕ} (rs : Reg → Word w) (res : List Bool) (b : Bool) (data : Bool → PairCall.Inputs)
+ (pack flag constants : Bool → List Bool) (aux : Stacks K) (new : List Bool) :
+ Function.update (frame rs res (storage w data pack flag constants aux)) (slot b (.external .flag)) new =
+ frame rs res (storage w data pack (Function.update flag b new) constants aux) := by
+ funext z
+ cases z with
+ | row | col | result => rfl
+ | aux x =>
+ rcases x with q | x
+ · cases q <;> rfl
+ rcases x with ⟨a,q⟩ | x
+ · cases b <;> cases a <;> cases q with
+ | external f => cases f <;> rfl
+ | internal | scratch => rfl
+ · cases x <;> rfl
+
+omit [DecidableEq K] in
+/-- Bound every physical stack, including registers and the scalar result.
+The supplied word bound also covers the immutable degree/ordinal descriptors. -/
+theorem frame_bound {w A : ℕ} (rs : Reg → Word w) (res : List Bool) (data : Bool → PairCall.Inputs)
+ (pack flag constants : Bool → List Bool) (aux : Stacks K)
+ (hw : w ≤ A) (hres : res.length ≤ A) (ht : ∀ b, (data b).arity ≤ A)
+ (hp : ∀ b, (pack b).length ≤ A) (hf : ∀ b, (flag b).length ≤ A)
+ (hc : ∀ b, (constants b).length ≤ A) (haux : ∀ k, (aux k).length ≤ A) :
+ ∀ z, (frame rs res (storage w data pack flag constants aux) z).length ≤ A := by
+ intro z
+ cases z with
+ | row | col => simpa [frame, bank] using hw
+ | result => exact hres
+ | aux z =>
+ rcases z with q | z
+ · have hl := (RegisterTable.bank_length_le Fin.elim0 (0 : Word w) rs q).trans hw
+ cases q with
+ | reg i => simp [frame,bank,auxBank]; split_ifs <;> simp [hw]
+ | pub | persistent | work | logPort => exact hl
+ rcases z with ⟨b,q⟩ | x
+ · cases q with
+ | external f =>
+ have h := PairCall.values_le (data b) (fun _ => []) (pack b) (flag b) hw (ht b) (by simp) (hp b) (hf b) f
+ cases f <;> first | exact h | exact Nat.zero_le _
+ | internal | scratch => exact Nat.zero_le _
+ · cases x with
+ | zeroScalar => exact hc false
+ | oneScalar => exact hc true
+ | temp => exact Nat.zero_le _
+ | payload k => exact haux k
+
+theorem emit_runs {w : ℕ} (rs : Reg → Word w) (b : Bool) (data : Bool → PairCall.Inputs)
+ (pack flag constants : Bool → List Bool) (aux : Stacks K) :
+ (emit b).Runs (5*(constants b).length+2) (frame rs [] (storage w data pack flag constants aux))
+ (frame rs (constants b) (storage w data pack flag constants aux)) := by
+ let st := frame rs [] (storage w data pack flag constants aux)
+ have src : st (scalarPort b) = constants b := by cases b <;> rfl
+ have read := SuccessorFields.prependCopy_runs (scalarPort b) (.result : Ports K) (extra .temp)
+ (by cases b <;> simp [scalarPort, extra]) (by cases b <;> simp [scalarPort, extra]) (by simp [extra]) st rfl
+ rw [src, show st .result = [] from rfl, List.append_nil, putResult] at read
+ exact read
+
+theorem erase_runs {w : ℕ} (rs : Reg → Word w) (res : List Bool) (b : Bool) (data : Bool → PairCall.Inputs)
+ (pack flag constants : Bool → List Bool) (aux : Stacks K) :
+ (erase b).Runs ((pack b).length+1+((flag b).length+1)) (frame rs res (storage w data pack flag constants aux))
+ (frame rs res (storage w data (Function.update pack b []) (Function.update flag b []) constants aux)) := by
+ let st := frame rs res (storage w data pack flag constants aux)
+ have p := SliceArithmetic.CallClear.clear_runs (slot b (.external .packed)) st
+ have f := SliceArithmetic.CallClear.clear_runs (slot b (.external .flag))
+ (frame rs res (storage w data (Function.update pack b []) flag constants aux))
+ rw [putPacked] at p
+ rw [putFlag] at f
+ exact p.followedBy f
+
+/-- Run the flag router and reclaim the two buffers. The clock of the long
+scalar call is charged once, with its peak cap retained through the tag test. -/
+theorem finish_bounded {w S n : ℕ} (rs : Reg → Word w) (b matched : Bool) (data : Bool → PairCall.Inputs)
+ (pack flag constants : Bool → List Bool) (aux : Stacks K) (leaf : FiniteRoutine (Ports K))
+ (out : List Bool) (rem : Bool → List Bool)
+ (hw : 1 ≤ w) (hf : flag b = digits w matched.toNat)
+ (call : (if matched then leaf else emit false).BoundedRun S n
+ (frame rs [] (storage w data pack flag constants aux)) (frame rs out (storage w data rem flag constants aux)))
+ (room : ∀ z, (frame rs out (storage w data rem flag constants aux) z).length +
+ ((rem b).length+1+((flag b).length+1)) ≤ S) :
+ (finish b leaf).BoundedRun S (2+n+((rem b).length+1+((flag b).length+1)))
+ (frame rs [] (storage w data pack flag constants aux))
+ (frame rs out (storage w data (Function.update rem b []) (Function.update flag b []) constants aux)) := by
+ let start := frame rs [] (storage w data pack flag constants aux)
+ let next (i : ℕ) := if i = 0 then emit false else leaf
+ have hcall : (next matched.toNat).BoundedRun S n start (frame rs out (storage w data rem flag constants aux)) := by
+ cases matched <;> exact call
+ have hc := TagRouter.digits_bounded (slot b (.external .flag)) next hw (by cases matched <;> decide : matched.toNat < 2^1)
+ start _ hf hcall
+ have he := spaceRun_of_steps (erase_runs rs out b data rem flag constants aux) room
+ exact hc.followedBy he
+
+end RankQuery.Stack.MacaulayRead.Arms
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayReadPorts.lean b/lean/OAI/Computability/VPVNP/MacaulayReadPorts.lean
new file mode 100644
index 0000000000..bf0a7ef155
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayReadPorts.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.MacaulayRowDispatch
+import OAI.Computability.VPVNP.RankQueryGramRead
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-! # Row and column ports of the physical Macaulay reader
+
+The first two inputs of the row decoder refer directly to the caller's row
+and column stacks. All other registers use a private bank. The six decoded
+fields remain in that bank for the selected coefficient routine, while the
+caller's addresses and field result stack retain their separate names.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead
+
+open BurstRAM RAMTape MacaulayRowDispatch
+
+variable {K : Type}
+
+/-- Private ports for the row decoder and the coefficient routine embedded in the reader. -/
+abbrev Work (K : Type) := Small ⊕ K
+/-- Matrix-entry reader ports for the row address, column address, result and private
+workspace. -/
+abbrev Bus (K : Type) := Port (Work K)
+
+/-- Connect the decoder's first two input registers to the caller's row and column stacks. Its
+other ports use the private decoder bank. -/
+def route : Small → Bus K
+ | .reg r => if r = inReg 0 then .row else if r = inReg 1 then .col else .aux (.inl (.reg r))
+ | q => .aux (.inl q)
+
+theorem route_injective : Function.Injective (route (K := K)) := by
+ intro a b eq
+ cases a <;> cases b <;> simp only [route] at eq ⊢ <;> (try split_ifs at eq) <;> simp_all
+
+/-- The caller has separate stacks for the two addresses. The unused private
+aliases therefore carry empty strings. -/
+def auxBank {w : ℕ} (rs : Reg → Word w) (base : Stacks K) : Stacks (Work K)
+ | .inl (.reg r) => if r = inReg 0 ∨ r = inReg 1 then [] else wordBits (rs r)
+ | .inl q => ISA.bank Fin.elim0 (0 : Word w) rs [] q
+ | .inr k => base k
+
+/-- Full reader frame with the two incoming addresses installed. -/
+def frame {w : ℕ} (rs : Reg → Word w) (result : List Bool) (base : Stacks K) : Stacks (Bus K) :=
+ bank w (rs (inReg 0)).val (rs (inReg 1)).val result (auxBank rs base)
+
+private theorem first_ne_second : inReg 0 ≠ inReg 1 := by intro e; have := congrArg Fin.val e; contradiction
+
+theorem frame_route {w : ℕ} (rs : Reg → Word w) (res : List Bool) (s : Stacks K) (q : Small) :
+ frame rs res s (route q) = ISA.bank Fin.elim0 (0 : Word w) rs [] q := by
+ cases q with
+ | reg r =>
+ by_cases h : r = inReg 0
+ · subst r; simp [frame, bank, route, ISA.bank, UniversalCountStack.digits]
+ by_cases h' : r = inReg 1
+ · subst r; simp [frame, bank, route, ISA.bank, UniversalCountStack.digits, h]
+ · simp [frame, bank, route, auxBank, ISA.bank, h, h']
+ | pub | persistent | work | logPort => rfl
+
+private theorem outside {w : ℕ} (rs ss : Reg → Word w) (res : List Bool) (s : Stacks K)
+ (z : Bus K) (h : ∀ q, route q ≠ z) : frame rs res s z = frame ss res s z := by
+ cases z with
+ | row => exact (h (.reg (inReg 0)) (by simp [route])).elim
+ | col => exact (h (.reg (inReg 1)) (by simp [route, first_ne_second.symm])).elim
+ | result => rfl
+ | aux x =>
+ rcases x with q | k
+ · cases q with
+ | reg r =>
+ by_cases he : r = inReg 0 ∨ r = inReg 1
+ · simp [frame, bank, auxBank, he]
+ · exact (h (.reg r) (by simp [route, not_or.mp he])).elim
+ | pub a => exact a.elim0
+ | persistent => exact (h .persistent rfl).elim
+ | work i => exact (h (.work i) rfl).elim
+ | logPort i => exact (h (.logPort i) rfl).elim
+ · rfl
+
+/-- Physical row dispatch on the ordinary reader ABI. All other ports keep
+their actual caller state, including the field result stack. -/
+theorem dispatch_runs [DecidableEq K] {w : ℕ} (i j equations pins multiples p : ℕ)
+ (bound : ∀ a, inputs i j equations pins multiples a < 2^p) (hw : requiredWidth p ≤ w)
+ (rs : Reg → Word w) (hin : ∀ a, (rs (inReg a)).val = inputs i j equations pins multiples a)
+ (res : List Bool) (s : Stacks K) :
+ ∃ cost ≤ ticks w, ∃ out, (machine.onPorts route).Runs cost (frame rs res s) (frame out res s) ∧
+ (∀ a, out (inReg a) = rs (inReg a)) ∧
+ ∀ a, (out (outReg a)).val = (address i j equations pins multiples).fields a := by
+ obtain ⟨d,hd,out,hrun,hold,hnew⟩ := machine_runs i j equations pins multiples p w bound hw rs hin 0
+ exact ⟨d,hd,out,machine.runs_onPorts_framed route_injective hrun (frame_route rs res s)
+ (frame_route out res s) (outside out rs res s),hold,hnew⟩
+
+/-- A caller can reset its external addresses without clearing the private
+register bank. Only the two aliased registers are affected. -/
+def setAddresses {w : ℕ} (rs : Reg → Word w) (i j : ℕ) : Reg → Word w :=
+ Function.update (Function.update rs (inReg 0) (Fin.ofNat _ i)) (inReg 1) (Fin.ofNat _ j)
+
+theorem reframe {w : ℕ} (rs : Reg → Word w) (base : Stacks K) (i j : ℕ) (res : List Bool) :
+ bank w i j res (auxBank rs base) = frame (setAddresses rs i j) res base := by
+ funext z
+ cases z with
+ | row | col =>
+ simp [bank, frame, setAddresses, first_ne_second, UniversalCountStack.digits]
+ apply congrArg wordBits
+ exact Fin.ext (Nat.mod_mod ..).symm
+ | result => rfl
+ | aux x =>
+ rcases x with q | k
+ · cases q with
+ | reg r =>
+ by_cases e : r = inReg 0 ∨ r = inReg 1
+ · simp [frame, bank, auxBank, e]
+ · simp [frame, bank, auxBank, setAddresses, (not_or.mp e).1, (not_or.mp e).2]
+ | pub | persistent | work | logPort => rfl
+ · rfl
+
+end RankQuery.Stack.MacaulayRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayReadRouter.lean b/lean/OAI/Computability/VPVNP/MacaulayReadRouter.lean
new file mode 100644
index 0000000000..9b346ceaa7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayReadRouter.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.MacaulayReadPorts
+import OAI.Computability.VPVNP.RankQueryGramReadSpace
+import OAI.Computability.VPVNP.RankQueryTagSpace
+import OAI.Computability.VPVNP.RegisterTable
+
+/-! # Calling the three physical Macaulay entry routines
+
+The row descriptor selects an original coefficient, an affine pin coefficient,
+or a powered-monomial equality test. The dispatch and selection code preserves
+the caller's input addresses. Its running time is polynomial in the word
+width. The long selected routine uses its own independent live-space bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead
+
+open BurstRAM RAMTape MacaulayRowDispatch Engine
+
+variable {K : Type} [DecidableEq K]
+
+/-- Decode tag 0 as an original equation, tag 1 as an affine pin and any larger tag as a
+powered monomial. -/
+def ofTag (n : ℕ) : Kind := if n = 0 then .equation else if n = 1 then .affine else .power
+
+private theorem ofTag_tag (k : Kind) : ofTag k.tag = k := by cases k <;> rfl
+
+/-- One fixed instruction table, formed from the three coefficient routines. -/
+def reader (arms : Kind → FiniteRoutine (Bus K)) : FiniteRoutine (Bus K) :=
+ (MacaulayRowDispatch.machine.onPorts route).followedBy
+ (TagRouter.select (route (.reg (outReg 0))) 2 (arms ∘ ofTag))
+
+/-- Runtime size words occupy registers 2 through 7. Registers 0 and 1
+refer to the caller's two address ports, and may change between reads. -/
+def Params {w : ℕ} (equations pins multiples : ℕ) (rs : Reg → Word w) : Prop :=
+ ∀ a : Fin 8, 2 ≤ a.val → (rs (inReg a)).val = inputs 0 0 equations pins multiples a
+
+/-- The private workspace contains the advised row counts and a coefficient bank satisfying the
+caller's readiness predicate. -/
+def Ready (w equations pins multiples : ℕ) (leafReady : Stacks K → Prop) (aux : Stacks (Work K)) : Prop :=
+ ∃ (rs : Reg → Word w) (leaf : Stacks K), Params equations pins multiples rs ∧ leafReady leaf ∧ aux = auxBank rs leaf
+
+private theorem install_inputs {w equations pins multiples : ℕ} {rs : Reg → Word w}
+ (hp : Params equations pins multiples rs) {i j : ℕ} (hi : i < 2^w) (hj : j < 2^w) :
+ ∀ a, ((setAddresses rs i j) (inReg a)).val = inputs i j equations pins multiples a := by
+ intro a
+ fin_cases a
+ · simp [setAddresses, inputs, inReg, Dispatch.Code.inReg, Nat.mod_eq_of_lt hi]
+ · simp [setAddresses, inputs, inReg, Dispatch.Code.inReg, Nat.mod_eq_of_lt hj]
+ · simpa (config := { decide := true }) [setAddresses, inReg, Dispatch.Code.inReg, inputs] using hp 2 (by decide)
+ · simpa (config := { decide := true }) [setAddresses, inReg, Dispatch.Code.inReg, inputs] using hp 3 (by decide)
+ · simpa (config := { decide := true }) [setAddresses, inReg, Dispatch.Code.inReg, inputs] using hp 4 (by decide)
+ · simpa (config := { decide := true }) [setAddresses, inReg, Dispatch.Code.inReg, inputs] using hp 5 (by decide)
+ · simpa (config := { decide := true }) [setAddresses, inReg, Dispatch.Code.inReg, inputs] using hp 6 (by decide)
+ · simpa (config := { decide := true }) [setAddresses, inReg, Dispatch.Code.inReg, inputs] using hp 7 (by decide)
+
+omit [DecidableEq K] in
+private theorem frame_length {w A : ℕ} (rs : Reg → Word w) (leaf : Stacks K)
+ (h : ∀ k, (leaf k).length ≤ A) (z : Bus K) : (frame rs [] leaf z).length ≤ max w A := by
+ cases z with
+ | row | col => simp [frame, bank, UniversalCountStack.length_digits]
+ | result => simp [frame, bank]
+ | aux x =>
+ rcases x with q | k
+ · change (auxBank rs leaf (.inl q)).length ≤ max w A
+ have hl := RegisterTable.bank_length_le Fin.elim0 (0 : Word w) rs q
+ cases q with
+ | reg r => simp [auxBank]; split_ifs <;> simp
+ | pub | work | persistent | logPort => exact hl.trans (le_max_left ..)
+ · exact (h k).trans (le_max_right ..)
+
+/-- A run of one coefficient routine from a populated row descriptor. The
+three routines are called on disjoint classes of indices. Their bounds may
+be exponential in time while keeping polynomial space. -/
+def ArmCorrect {p e n m : ℕ} {c : SliceArithmetic.Vector p e}
+ (M : Matrix (Fin n) (Fin m) (Scalar c)) (w v equations pins multiples B S : ℕ)
+ (leafReady : Stacks K → Prop) (arms : Kind → FiniteRoutine (Bus K)) : Prop :=
+ ∀ (i : Fin n) (j : Fin m) (rs : Reg → Word w) (leaf : Stacks K),
+ (∀ a, (rs (inReg a)).val = inputs i j equations pins multiples a) →
+ (∀ a, (rs (outReg a)).val = (address i j equations pins multiples).fields a) → leafReady leaf →
+ ∃ t ≤ B, ∃ out, Ready w equations pins multiples leafReady out ∧
+ (arms (address i j equations pins multiples).kind).BoundedRun S t (frame rs [] leaf)
+ (bank w i j (scalar v (M i j)) out)
+
+/-- The call interface consumed by the Gram and Schur engine, with all
+routing and register framing accounted for. -/
+theorem correctSpace_of_arms {p e n m : ℕ} {c : SliceArithmetic.Vector p e}
+ (M : Matrix (Fin n) (Fin m) (Scalar c)) (w v equations pins multiples B S A b : ℕ)
+ (leafReady : Stacks K → Prop) (arms : Kind → FiniteRoutine (Bus K))
+ (bound : ∀ (i : Fin n) (j : Fin m) a, inputs i j equations pins multiples a < 2^b)
+ (hw : requiredWidth b ≤ w) (hbw : b ≤ w) (ht : 2 ≤ w)
+ (space : ∀ leaf, leafReady leaf → ∀ k, (leaf k).length ≤ A)
+ (room : max w A + ticks w ≤ S) (arm : ArmCorrect M w v equations pins multiples B S leafReady arms) :
+ CorrectSpace (reader arms) M w v (ticks w + (4+B)) S (Ready w equations pins multiples leafReady) := by
+ rintro i j _ ⟨rs,leaf,pars,ok,rfl⟩
+ have hi : i.val < 2^w := (bound i j 0).trans_le (Nat.pow_le_pow_right (by decide) hbw)
+ have hj : j.val < 2^w := (bound i j 1).trans_le (Nat.pow_le_pow_right (by decide) hbw)
+ let start := setAddresses rs i j
+ have hin := install_inputs pars hi hj
+ obtain ⟨td,hd,mid,disp,hkeep,hout⟩ := dispatch_runs _ _ _ _ _ b (bound i j) hw start hin [] leaf
+ have midIn a : (mid (inReg a)).val = inputs i j equations pins multiples a := (congrArg Fin.val (hkeep a)).trans (hin a)
+ obtain ⟨ta,ha,aux,hr,run⟩ := arm i j mid leaf midIn hout ok
+ let addr := address i.val j.val equations pins multiples
+ have hs : frame mid [] leaf (route (.reg (outReg 0))) = UniversalCountStack.digits w addr.kind.tag := by
+ rw [frame_route]
+ change wordBits (mid (outReg 0)) = wordBits (Fin.ofNat _ addr.kind.tag)
+ apply congrArg wordBits
+ apply Fin.ext
+ have hh : (mid (outReg 0)).val = addr.kind.tag := hout 0
+ exact hh.trans (Nat.mod_eq_of_lt (hh ▸ (mid (outReg 0)).isLt)).symm
+ have htag : addr.kind.tag < 2^2 := by cases addr.kind <;> decide
+ have sub : (arms ∘ ofTag) addr.kind.tag = arms addr.kind := congrArg arms (ofTag_tag _)
+ have select := TagRouter.digits_bounded (route (.reg (outReg 0))) (arms ∘ ofTag) ht htag _ _ hs (sub.symm ▸ run)
+ have dr : (MacaulayRowDispatch.machine.onPorts route).BoundedRun S td (frame start [] leaf) (frame mid [] leaf) :=
+ UniversalCountStack.spaceRun_of_steps disp fun z => (Nat.add_le_add (frame_length start leaf (space leaf ok) z) hd).trans room
+ refine ⟨td+(2*2+ta), by omega, aux, hr, ?_⟩
+ rw [reframe]
+ exact dr.followedBy select
+
+end RankQuery.Stack.MacaulayRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayReaderScans.lean b/lean/OAI/Computability/VPVNP/MacaulayReaderScans.lean
new file mode 100644
index 0000000000..0fd93202a7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayReaderScans.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.MacaulayReaderWidth
+
+/-! # Uniform budgets for both physical scans and all target operations -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.ReaderPlan
+
+open PolynomiallyBounded RankQuery.Stack
+
+/-- The two largest advised degrees, irrespective of the selected row or field. -/
+def envelope (P : ReaderPlan) : PairCall.Inputs :=
+ ⟨P.arity,fun b => if b then P.column else P.source,fun _ => 0,P.scale,P.arity⟩
+
+/-- A common tick bound for both monomial scans. It includes ordinal decoding, residual packing
+or powered comparison, and cleanup. -/
+def scanTime (P : ReaderPlan) (w B : ℕ) :=
+ (PairCall.scanClock w B P.envelope + PairCall.packClock P.arity w B + PairCall.clearCost w) +
+ (PairCall.scanClock w B P.envelope + PairCall.powerClock P.arity w B + PairCall.clearCost w)
+
+/-- A common bound on stack lengths for an equation scan and a powered-row scan at the plan's
+maximum degrees. -/
+def scanSpace (P : ReaderPlan) (w B : ℕ) :=
+ PairCall.equationSpace w B P.envelope + PairCall.poweredSpace w B
+
+private theorem ordinal_mono (w B t : ℕ) {a b : ℕ} (h : a ≤ b) :
+ PairCall.ordinalClock w B t a ≤ PairCall.ordinalClock w B t b := by
+ unfold PairCall.ordinalClock
+ gcongr
+ exact raw_mono t h
+
+/-- Applies to an equation or pin multiplier, an appended monomial and
+either a label multiplication or a Frobenius target row. -/
+theorem scan_bounds (P : ReaderPlan) (w B : ℕ) (d : PairCall.Inputs)
+ (ht : d.arity=P.arity) (hL : d.degree false ≤ P.source) (hD : d.degree true ≤ P.column) :
+ (PairCall.scanClock w B d + PairCall.packClock d.arity w B + PairCall.clearCost w ≤ P.scanTime w B) ∧
+ (PairCall.scanClock w B d + PairCall.powerClock d.arity w B + PairCall.clearCost w ≤ P.scanTime w B) ∧
+ PairCall.equationSpace w B d ≤ P.scanSpace w B ∧ PairCall.poweredSpace w B ≤ P.scanSpace w B := by
+ have hc : PairCall.scanClock w B d ≤ PairCall.scanClock w B P.envelope := by
+ unfold PairCall.scanClock
+ rw [ht]
+ exact Nat.add_le_add (ordinal_mono w B P.arity hL) (ordinal_mono w B P.arity hD)
+ have he : PairCall.equationSpace w B d = PairCall.equationSpace w B P.envelope := by
+ simp [PairCall.equationSpace, envelope, ht]
+ rw [ht,he]
+ unfold scanTime scanSpace
+ omega
+
+theorem resources (P : ℕ → ReaderPlan) {w B : ℕ → ℕ} (hw : PolynomiallyBounded w) (hB : PolynomiallyBounded B)
+ (ht : PolynomiallyBounded (fun n => (P n).arity)) (hd : PolynomiallyBounded (fun n => Nat.clog 2 (P n).degree))
+ (hn : PolynomiallyBounded (fun n => Nat.clog 2 (P n).points))
+ (hq : PolynomiallyBounded (fun n => Nat.clog 2 (P n).order)) :
+ PolynomiallyBounded (fun n => (P n).scanSpace (w n) (B n)) ∧
+ PolynomiallyBounded (fun n => Nat.clog 2 ((P n).scanTime (w n) (B n))) ∧
+ PolynomiallyBounded (fun n => MacaulayRowDispatch.ticks (w n)) := by
+ obtain ⟨_,hD,hL,_⟩ := degree_bounds P ht hd hn hq
+ obtain ⟨hs,hp,he,hq⟩ := PairCall.resources (fun n => (P n).envelope) hw hB ht (fun b => by
+ cases b <;> first | exact hD | exact hL)
+ exact ⟨hs.add hp,clog_add he hq,(PolynomiallyBounded.const _).mul
+ ((PolynomiallyBounded.const 100).mul ((hw.add (PolynomiallyBounded.const 1)).pow 2))⟩
+
+end RadicalCertificate.MonomialIndex.ReaderPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayReaderWidth.lean b/lean/OAI/Computability/VPVNP/MacaulayReaderWidth.lean
new file mode 100644
index 0000000000..78f5032d2b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayReaderWidth.lean
@@ -0,0 +1,203 @@
+import OAI.Computability.VPVNP.MacaulayPairBounds
+import OAI.Computability.VPVNP.MacaulayPairEntries
+import OAI.Computability.VPVNP.MacaulayRowDispatch
+
+/-! # A common word width for the physical matrix readers
+
+The input row counts include both original equations and pins. The field
+size can be bounded before the prime is chosen. The same width covers all
+legal rows and columns, label shifts and Frobenius target comparisons.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex
+
+open PolynomiallyBounded
+open RankQuery.Stack
+
+/-- Counts and upper bounds used to choose a single word width for Macaulay reads across the
+allowed fields, rows and target operations. -/
+structure ReaderPlan where
+ /-- Number of variables in the slice equations and their monomials. -/
+ arity : ℕ
+ /-- Number of original equations before the affine pin rows. -/
+ equations : ℕ
+ /-- Number of affine pin equations added to form the slice. -/
+ pins : ℕ
+ /-- Upper bound supplied for the degrees of the defining equations. -/
+ degree : ℕ
+ /-- Upper bound supplied for the number of geometric points in the slice. -/
+ points : ℕ
+ /-- Upper bound on the cardinality of the finite ground field. -/
+ order : ℕ
+
+namespace ReaderPlan
+
+/-- Degree bound for target monomials obtained by multiplying by a variable or applying
+Frobenius. -/
+def target (P : ReaderPlan) := (P.points+1)*P.order
+/-- Uniform effective Nullstellensatz degree bound using the plan's equation and target
+degrees. -/
+def certificate (P : ReaderPlan) := (2*max P.degree (P.target+1))^(4*(P.arity+3))
+/-- Upper bound on the Frobenius power used in radical membership queries. Its exponent is the
+ceiling binary logarithm of the certificate bound. -/
+def power (P : ReaderPlan) := P.order^(Nat.clog 2 P.certificate)
+/-- Degree allowance for monomials multiplying the equations, including the powered target
+degree. -/
+def multiplier (P : ReaderPlan) := P.certificate + P.power*P.target
+/-- Degree allowance for the coefficient columns of all products of a multiplier with a
+defining equation. -/
+def column (P : ReaderPlan) := P.multiplier + P.degree
+/-- Common degree bound for source monomials in both equation multiples and the appended
+monomial rows. -/
+def source (P : ReaderPlan) := max P.points P.multiplier
+/-- Common upper bound on exponent scaling for ordinary, powered and Frobenius-target reads. -/
+def scale (P : ReaderPlan) := max 1 (P.power*P.order)
+/-- Word width sufficient for the pair scan using the plan's largest source degree, column
+degree, scale and marked coordinate. -/
+def pairWidth (P : ReaderPlan) := ExponentISA.entryWidth P.arity P.source P.column P.scale P.arity 0
+
+/-- The dimensions can be bounded by the raw address ranges even though
+the physical caller uses dense ordinals. -/
+def addressLimit (P : ReaderPlan) :=
+ (P.equations+P.pins)*rawSize P.arity P.multiplier + rawSize P.arity P.points +
+ rawSize P.arity P.column + P.equations + P.pins + rawSize P.arity P.multiplier + 1
+
+/-- Bit width obtained by taking the ceiling binary logarithm of the plan's address limit. -/
+def addressBits (P : ReaderPlan) := Nat.clog 2 P.addressLimit
+
+/-- Common register width covering the input addresses, the row decoder's intermediate values
+and the exponent scan. -/
+def wordWidth (P : ReaderPlan) :=
+ 2 + P.addressBits + MacaulayRowDispatch.requiredWidth P.addressBits + P.pairWidth
+
+variable {K : Type*}
+
+/-- The slice query has field order at least two and fits the plan's bounds on field order,
+equation degree and number of points. -/
+structure Covers (P : ReaderPlan) (S : QueryData P.arity (P.equations+P.pins) K) : Prop where
+ order_two : 2 ≤ S.fieldOrder
+ order_le : S.fieldOrder ≤ P.order
+ degree_le : S.degreeBound ≤ P.degree
+ points_le : S.pointBound ≤ P.points
+
+theorem Covers.degrees {P : ReaderPlan} {S : QueryData P.arity (P.equations+P.pins) K} (h : P.Covers S) :
+ S.power ≤ P.power ∧ S.multiplierDegree ≤ P.multiplier ∧ S.columnDegree ≤ P.column := by
+ have hR : S.targetDegree ≤ P.target := Nat.mul_le_mul (Nat.add_le_add_right h.points_le 1) h.order_le
+ have hH : S.certificateDegree ≤ P.certificate :=
+ Nat.pow_le_pow_left (Nat.mul_le_mul_left 2 (max_le_max h.degree_le (Nat.add_le_add_right hR 1))) _
+ have hP : S.power ≤ P.power :=
+ (Nat.pow_le_pow_left h.order_le _).trans (Nat.pow_le_pow_right ((by decide : 0 < 2).trans_le (h.order_two.trans h.order_le))
+ ((Nat.clog_anti_left (by decide) h.order_two).trans (Nat.clog_mono_right _ hH)))
+ have hL : S.multiplierDegree ≤ P.multiplier := Nat.add_le_add hH (Nat.mul_le_mul hP hR)
+ exact ⟨hP,hL,Nat.add_le_add hL h.degree_le⟩
+
+theorem raw_mono (t : ℕ) {a b : ℕ} (h : a ≤ b) : rawSize t a ≤ rawSize t b :=
+ Nat.mul_le_mul (Nat.succ_le_succ h) (Nat.pow_le_pow_left (Nat.succ_le_succ h) t)
+
+private theorem size_le_raw_of_le (t : ℕ) {a b : ℕ} (h : a ≤ b) : size t a ≤ rawSize t b := by
+ rw [size_eq_card]
+ exact (card_boundedMonomial_le t a).trans ((Nat.le_mul_of_pos_left _ (Nat.succ_pos _)).trans (raw_mono t h))
+
+theorem Covers.dispatch {P : ReaderPlan} {S : QueryData P.arity (P.equations+P.pins) K} (h : P.Covers S)
+ (i : Fin ((P.equations+P.pins)*size P.arity S.multiplierDegree + size P.arity S.pointBound))
+ (j : Fin (size P.arity S.columnDegree)) (a : Fin 8) :
+ MacaulayRowDispatch.inputs i j P.equations P.pins (size P.arity S.multiplierDegree) a < 2^P.addressBits := by
+ have hm := size_le_raw_of_le P.arity h.degrees.2.1
+ have hc := size_le_raw_of_le P.arity h.degrees.2.2
+ have hn := size_le_raw_of_le P.arity h.points_le
+ have hi := i.isLt.trans_le (Nat.add_le_add (Nat.mul_le_mul_left _ hm) hn)
+ have hj := j.isLt.trans_le hc
+ apply Nat.lt_of_lt_of_le _ (Nat.le_pow_clog (by decide : 1<2) P.addressLimit)
+ fin_cases a <;> simp [MacaulayRowDispatch.inputs, addressLimit] <;> omega
+
+theorem dispatchWidth (P : ReaderPlan) :
+ MacaulayRowDispatch.requiredWidth P.addressBits ≤ P.wordWidth ∧ P.addressBits ≤ P.wordWidth ∧ 2 ≤ P.wordWidth := by
+ dsimp [wordWidth]; omega
+
+private theorem pairWidth_mono {t L L' D D' s s' m m' : ℕ} (hl : L ≤ L') (hd : D ≤ D')
+ (hs : s ≤ s') (hm : m ≤ m') :
+ ExponentISA.entryWidth t L D s m 0 ≤ ExponentISA.entryWidth t L' D' s' m' 0 := by
+ apply Nat.add_le_add_left
+ apply Nat.clog_mono_right
+ have r₁ := raw_mono t hl
+ have r₂ := raw_mono t hd
+ have l₁ := Nat.mul_le_mul_left t hl
+ have l₂ := Nat.mul_le_mul_left t hd
+ have l₃ := Nat.mul_le_mul hs (Nat.add_le_add_right hl 1)
+ omega
+
+theorem pairWidth_le (P : ReaderPlan) (d : PairCall.Inputs) (ht : d.arity = P.arity)
+ (hl : d.degree false ≤ P.source) (hd : d.degree true ≤ P.column) (hs : d.scale ≤ P.scale)
+ (hm : d.mark ≤ P.arity) : PairCall.requiredWidth d ≤ P.wordWidth := by
+ have h : PairCall.requiredWidth d ≤ P.pairWidth := by
+ unfold PairCall.requiredWidth pairWidth
+ rw [ht]
+ exact pairWidth_mono hl hd hs hm
+ dsimp only [wordWidth]; omega
+
+theorem Covers.targetParams {P : ReaderPlan} {S : QueryData P.arity (P.equations+P.pins) K}
+ (h : P.Covers S) (op : QueryData.Operation P.arity) :
+ PairCall.targetScale S op ≤ P.scale ∧ PairCall.targetMark op ≤ P.arity := by
+ have hp := h.degrees.1
+ have hq := h.order_le
+ have hpos := h.order_two
+ have hm := Nat.mul_le_mul hp hq
+ have hs : S.power ≤ S.power*S.fieldOrder := Nat.le_mul_of_pos_right _ (by omega)
+ cases op with
+ | label i => exact ⟨(hs.trans hm).trans (le_max_right ..), i.isLt⟩
+ | frobenius => exact ⟨hm.trans (le_max_right ..), Nat.zero_le _⟩
+
+private theorem polyClogMax {f g : ℕ → ℕ} (hf : PolynomiallyBounded (fun n => Nat.clog 2 (f n)))
+ (hg : PolynomiallyBounded (fun n => Nat.clog 2 (g n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (max (f n) (g n))) :=
+ (clog_add hf hg).of_le fun _ => Nat.clog_mono_right _ (max_le (Nat.le_add_right ..) (Nat.le_add_left ..))
+
+theorem degree_bounds (P : ℕ → ReaderPlan) (ht : PolynomiallyBounded (fun n => (P n).arity))
+ (hd : PolynomiallyBounded (fun n => Nat.clog 2 (P n).degree))
+ (hn : PolynomiallyBounded (fun n => Nat.clog 2 (P n).points))
+ (hq : PolynomiallyBounded (fun n => Nat.clog 2 (P n).order)) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (P n).multiplier) ∧
+ PolynomiallyBounded (fun n => Nat.clog 2 (P n).column) ∧
+ PolynomiallyBounded (fun n => Nat.clog 2 (P n).source) ∧
+ PolynomiallyBounded (fun n => Nat.clog 2 (P n).scale) := by
+ have h1 := clog (PolynomiallyBounded.const 1)
+ have hR := clog_mul (clog_add hn h1) hq
+ have hH := clog_pow (clog_mul (clog (PolynomiallyBounded.const 2)) (polyClogMax hd (clog_add hR h1)))
+ ((PolynomiallyBounded.const 4).mul (ht.add (PolynomiallyBounded.const 3)))
+ have hP := clog_pow hq hH
+ have hL := clog_add hH (clog_mul hP hR)
+ have hD := clog_add hL hd
+ have hsource := polyClogMax hn hL
+ have hscale := polyClogMax h1 (clog_mul hP hq)
+ exact ⟨hL,hD,hsource,hscale⟩
+
+/-- The physical word width is bounded independently of the varying row
+and column ordinals and the operation being queried. -/
+theorem width_polynomial (P : ℕ → ReaderPlan) (ht : PolynomiallyBounded (fun n => (P n).arity))
+ (he : PolynomiallyBounded (fun n => Nat.clog 2 (P n).equations))
+ (hi : PolynomiallyBounded (fun n => Nat.clog 2 (P n).pins))
+ (hd : PolynomiallyBounded (fun n => Nat.clog 2 (P n).degree))
+ (hn : PolynomiallyBounded (fun n => Nat.clog 2 (P n).points))
+ (hq : PolynomiallyBounded (fun n => Nat.clog 2 (P n).order)) :
+ PolynomiallyBounded (fun n => (P n).wordWidth) := by
+ have h1 := clog (PolynomiallyBounded.const 1)
+ obtain ⟨hL,hD,hsource,hscale⟩ := degree_bounds P ht hd hn hq
+ have hp : PolynomiallyBounded (fun n => (P n).pairWidth) :=
+ ExponentISA.entryWidth_polynomial ht hsource hD hscale (clog ht) (clog (PolynomiallyBounded.const 0))
+ have hl := bounded_rawSize ht hL
+ have hbits : PolynomiallyBounded (fun n => (P n).addressBits) :=
+ clog_add (clog_add (clog_add (clog_add (clog_add (clog_add (clog_mul (clog_add he hi) hl)
+ (bounded_rawSize ht hn)) (bounded_rawSize ht hD)) he) hi) hl) h1
+ exact (((PolynomiallyBounded.const 2).add hbits).add
+ ((hbits.add (PolynomiallyBounded.const 1)).mul (PolynomiallyBounded.const _))).add hp
+
+end ReaderPlan
+end RadicalCertificate.MonomialIndex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayReduction.lean b/lean/OAI/Computability/VPVNP/MacaulayReduction.lean
new file mode 100644
index 0000000000..ac6c769668
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayReduction.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.CertificateReduction
+import OAI.Computability.VPVNP.MacaulayRelations
+import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure
+
+/-!
+# Prime-characteristic descent of the label equations
+
+Section 8.2 applies prime reduction to the Macaulay matrix of all monomial
+multiples of the integer equations. A characteristic-zero solution excludes the
+row of one from its rational row space. The finite matrix argument supplies a
+prime of controlled bit length with the same exclusion. Given the uniform
+effective weak Nullstellensatz multiplier bound, the reduced equations then
+have a common zero over the algebraic closure of that prime field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CertificateReduction
+
+open MvPolynomial RadicalCertificate
+
+variable {t : ℕ} {ι : Type*} [Fintype ι]
+
+omit [Fintype ι] in
+/-- Base change commutes with the entire bounded Macaulay matrix. -/
+theorem macaulayMatrix_map {R S : Type*} [CommSemiring R] [CommSemiring S] (φ : R →+* S)
+ (F : ι → MvPolynomial (Fin t) R) (H D : ℕ) :
+ macaulayMatrix (fun i => map φ (F i)) H D = (macaulayMatrix F H D).map φ := by
+ ext ⟨i, a⟩ j
+ change (monomial a.val 1 * map φ (F i)).coeff j.val = φ ((monomial a.val 1 * F i).coeff j.val)
+ rw [← coeff_map, map_mul, map_monomial, φ.map_one]
+
+private theorem coefficientRow_one_map {R S : Type*} [CommSemiring R] [CommSemiring S]
+ (φ : R →+* S) (D : ℕ) : (fun j : BoundedMonomial t D =>
+ φ ((coefficientRow D (1 : MvPolynomial (Fin t) R)) j)) =
+ coefficientRow D (1 : MvPolynomial (Fin t) S) := by
+ funext j
+ change φ ((1 : MvPolynomial (Fin t) R).coeff j.val) = _
+ rw [← coeff_map, map_one]
+ rfl
+
+private theorem totalDegree_map_le {R S : Type*} [CommSemiring R] [CommSemiring S]
+ (φ : R →+* S) (f : MvPolynomial (Fin t) R) : (map φ f).totalDegree ≤ f.totalDegree :=
+ Finset.sup_mono (support_map_subset φ f)
+
+/-- At the selected prime the constant polynomial one has no certificate with
+multiplier degree at most `H`. This matrix statement needs no effective
+Nullstellensatz hypothesis. -/
+theorem exists_prime_one_notMem {K : Type*} [Field K] [CharZero K]
+ (F : ι → MvPolynomial (Fin t) ℤ) (H d b : ℕ)
+ (hdeg : ∀ i, (F i).totalDegree ≤ d) (hcoeff : ∀ i a, ((F i).coeff a).natAbs ≤ 2 ^ b)
+ (x : Fin t → K) (hx : ∀ i, eval₂ (Int.castRingHom K) x (F i) = 0) :
+ let a := Nat.clog 2 (H + d + 1) * t
+ ∃ p : ℕ, p.Prime ∧ p ≤ 2 ^ (2 * (a + Nat.clog 2 (a + b + 2)) + 1) ∧
+ coefficientRow (H + d) (1 : MvPolynomial (Fin t) (ZMod p)) ∉
+ Submodule.span (ZMod p) (Set.range (macaulayMatrix
+ (fun i => map (Int.castRingHom (ZMod p)) (F i)) H (H + d)).row) := by
+ let D := H + d
+ let a := Nat.clog 2 (D + 1) * t
+ let M := macaulayMatrix F H D
+ let v := coefficientRow D (1 : MvPolynomial (Fin t) ℤ)
+ have hQ : (fun j => (v j : ℚ)) ∉ Submodule.span ℚ (Set.range (M.map (Int.castRingHom ℚ)).row) := by
+ intro hmem
+ change (fun j => Int.castRingHom ℚ ((coefficientRow D (1 : MvPolynomial (Fin t) ℤ)) j))
+ ∈ Submodule.span ℚ (Set.range ((macaulayMatrix F H D).map (Int.castRingHom ℚ)).row) at hmem
+ rw [coefficientRow_one_map, ← macaulayMatrix_map] at hmem
+ have hx' (i : ι) : aeval x (map (Int.castRingHom ℚ) (F i)) = 0 := by
+ rw [aeval_def, eval₂_map]
+ exact (Subsingleton.elim ((algebraMap ℚ K).comp (Int.castRingHom ℚ)) (Int.castRingHom K)) ▸ hx i
+ have hzero := aeval_eq_zero_of_row_mem (fun i => map (Int.castRingHom ℚ) (F i))
+ (fun i => (totalDegree_map_le _ _).trans (hdeg i)) 1 (by simp) hmem x hx'
+ simp at hzero
+ have hcard : Fintype.card (BoundedMonomial t D) ≤ 2 ^ a := calc
+ _ ≤ (D + 1) ^ t := card_boundedMonomial_le t D
+ _ ≤ (2 ^ Nat.clog 2 (D + 1)) ^ t := Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) _
+ _ = _ := (pow_mul _ _ _).symm
+ obtain ⟨p, hp, hsize, hmem⟩ := exists_bounded_good_prime_of_notMem M v a b hcard
+ (macaulayMatrix_natAbs_le F hcoeff) (fun j => (coefficientRow_one_natAbs_le j).trans Nat.one_le_two_pow) hQ
+ refine ⟨p, hp, hsize, ?_⟩
+ change (fun j => Int.castRingHom (ZMod p) ((coefficientRow D (1 : MvPolynomial (Fin t) ℤ)) j))
+ ∉ Submodule.span (ZMod p) (Set.range ((macaulayMatrix F H D).map (Int.castRingHom (ZMod p))).row) at hmem
+ rwa [coefficientRow_one_map, ← macaulayMatrix_map] at hmem
+
+/-- A uniform weak certificate degree bound turns a failed Macaulay row test
+over the base field into a common zero in the extension where the bound holds. -/
+theorem commonZero_of_one_notMem {K E : Type*} [Field K] [Field E] [Algebra K E]
+ (F : ι → MvPolynomial (Fin t) K) (H d : ℕ) (hdeg : ∀ i, (F i).totalDegree ≤ d)
+ (hmem : coefficientRow (H + d) (1 : MvPolynomial (Fin t) K) ∉
+ Submodule.span K (Set.range (macaulayMatrix F H (H + d)).row))
+ (bound : WeakCertificateBound E ι t d H) : ∃ x : Fin t → E, ∀ i, aeval x (F i) = 0 := by
+ by_contra hno
+ let φ := algebraMap K E
+ let G (i : ι) := map φ (F i)
+ have hn : ¬ ∃ x : Fin t → E, ∀ i, eval x (G i) = 0 := by
+ simpa only [G, eval_map, φ, aeval_def] using hno
+ obtain ⟨A, hA, he⟩ := bound G (fun i => (totalDegree_map_le φ _).trans (hdeg i)) hn
+ have hrow := coefficientRow_sum_mul_mem G A (H + d) hA
+ rw [he, macaulayMatrix_map φ F, ← coefficientRow_one_map φ (H + d)] at hrow
+ exact hmem (rowSpan_descent _ _ hrow)
+
+local instance (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩
+
+/-- The characteristic-zero case of the choice-of-characteristic step in
+Theorem 8.1, conditional on the stated effective weak Nullstellensatz bound. -/
+theorem exists_prime_solution_of_weakCertificateBound {K : Type*} [Field K] [CharZero K]
+ (F : ι → MvPolynomial (Fin t) ℤ) (H d b : ℕ)
+ (hdeg : ∀ i, (F i).totalDegree ≤ d) (hcoeff : ∀ i a, ((F i).coeff a).natAbs ≤ 2 ^ b)
+ (x : Fin t → K) (hx : ∀ i, eval₂ (Int.castRingHom K) x (F i) = 0)
+ (bound : ∀ p : Nat.Primes, WeakCertificateBound (AlgebraicClosure (ZMod p.val)) ι t d H) :
+ let a := Nat.clog 2 (H + d + 1) * t
+ ∃ p : Nat.Primes, p.val ≤ 2 ^ (2 * (a + Nat.clog 2 (a + b + 2)) + 1) ∧
+ ∃ y : Fin t → AlgebraicClosure (ZMod p.val), ∀ i,
+ eval₂ (Int.castRingHom (AlgebraicClosure (ZMod p.val))) y (F i) = 0 := by
+ obtain ⟨p, hp, hsize, hmem⟩ := exists_prime_one_notMem F H d b hdeg hcoeff x hx
+ let p' : Nat.Primes := ⟨p, hp⟩
+ let : Fact p.Prime := ⟨hp⟩
+ let E := AlgebraicClosure (ZMod p)
+ obtain ⟨y, hy⟩ := commonZero_of_one_notMem (fun i => map (Int.castRingHom (ZMod p)) (F i))
+ H d (fun i => (totalDegree_map_le _ _).trans (hdeg i)) hmem (bound p')
+ refine ⟨p', hsize, y, fun i => ?_⟩
+ have hi := hy i
+ rw [aeval_def, eval₂_map] at hi
+ exact (Subsingleton.elim ((algebraMap (ZMod p) E).comp (Int.castRingHom (ZMod p))) (Int.castRingHom E)) ▸ hi
+
+end CertificateReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayRelations.lean b/lean/OAI/Computability/VPVNP/MacaulayRelations.lean
new file mode 100644
index 0000000000..764490199d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayRelations.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.MacaulayRows
+import Mathlib.FieldTheory.Finite.Basic
+import Mathlib.LinearAlgebra.Basis.VectorSpace
+
+/-!
+# Linear relations in the reduced slice algebra
+
+Appendix D.1 descends a bounded coefficient row test to the field of definition.
+A power of the cardinality of this finite field acts linearly on polynomials.
+Thus a relation among polynomial values on the slice becomes a relation among
+the powered coefficient rows modulo the Macaulay row space.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+open MvPolynomial
+
+variable {K E : Type*} [Field K] [Field E] [Algebra K E]
+
+/-- Membership of a row over the base field descends through any field extension.
+Apply a base-linear retraction of the scalar inclusion to the coefficient equations. -/
+theorem rowSpan_descent {I J : Type*} [Fintype I] (M : Matrix I J K) (v : J → K)
+ (hv : (fun j ↦ algebraMap K E (v j)) ∈
+ Submodule.span E (Set.range (M.map (algebraMap K E)).row)) :
+ v ∈ Submodule.span K (Set.range M.row) := by
+ let φ := Algebra.linearMap K E
+ obtain ⟨ψ, hψ⟩ := φ.exists_leftInverse_of_injective
+ (LinearMap.ker_eq_bot.mpr (algebraMap K E).injective)
+ have hfix (k : K) : ψ (algebraMap K E k) = k := DFunLike.congr_fun hψ k
+ obtain ⟨c, hc⟩ := (Submodule.mem_span_range_iff_exists_fun E).mp hv
+ refine (Submodule.mem_span_range_iff_exists_fun K).mpr ⟨fun i ↦ ψ (c i), ?_⟩
+ ext j
+ have hj : ∑ i, (M i j) • c i = algebraMap K E (v j) := by
+ simpa [Algebra.smul_def, mul_comm, Matrix.row, Matrix.map_apply,
+ Finset.sum_apply] using congrFun hc j
+ simpa [Finset.sum_apply, mul_comm, Matrix.row, hfix] using congrArg ψ hj
+
+variable {t : ℕ} {ι : Type*} [Fintype ι]
+
+/-- The bounded Rabinowitsch certificate may have coefficients in an extension field,
+even though the matrix and the tested row are over the base field. -/
+theorem coefficientRow_pow_mem_of_extension (F : ι → MvPolynomial (Fin t) K)
+ {f : MvPolynomial (Fin t) K} (A : ι → MvPolynomial (Fin (t + 1)) E)
+ (B : MvPolynomial (Fin (t + 1)) E) {H P R₀ d : ℕ} (hHP : H ≤ P) (hP : P ≠ 0)
+ (hA : ∀ i, (A i).totalDegree ≤ H) (hf : f.totalDegree ≤ R₀)
+ (hcert : let φ := algebraMap K E
+ (∑ i, A i * rename Fin.succ (map φ (F i))) + B * (1 - X 0 * rename Fin.succ (map φ f)) = 1) :
+ coefficientRow (H + P * R₀ + d) (f ^ P) ∈ Submodule.span K
+ (Set.range (macaulayMatrix F (H + P * R₀) (H + P * R₀ + d)).row) := by
+ let φ := algebraMap K E
+ have hf' : (map φ f).totalDegree ≤ R₀ := by
+ simpa only [totalDegree, support_map_of_injective f φ.injective] using hf
+ have he := coefficientRow_pow_mem (fun i ↦ map φ (F i)) A B hHP hP hA hf' hcert (d := d)
+ apply rowSpan_descent (E := E)
+ have hm (L D : ℕ) : macaulayMatrix (fun i ↦ map φ (F i)) L D = (macaulayMatrix F L D).map φ := by
+ ext ⟨i, a⟩ j
+ change (monomial a.val 1 * map φ (F i)).coeff j.val = φ ((monomial a.val 1 * F i).coeff j.val)
+ rw [← coeff_map, map_mul, map_monomial, φ.map_one]
+ rw [hm] at he
+ convert he using 1
+ ext j
+ change φ ((f ^ P).coeff j.val) = ((map φ f) ^ P).coeff j.val
+ rw [← map_pow, coeff_map]
+
+/-- A uniform weak Nullstellensatz certificate bound for systems of degree at most
+`D` in `n` variables. The extra equation in the Rabinowitsch system has index `none`. -/
+def WeakCertificateBound (E I : Type*) [Field E] [Fintype I] (n D H : ℕ) : Prop :=
+ ∀ G : I → MvPolynomial (Fin n) E, (∀ i, (G i).totalDegree ≤ D) →
+ (¬∃ x : Fin n → E, ∀ i, eval x (G i) = 0) →
+ ∃ A : I → MvPolynomial (Fin n) E, (∀ i, (A i).totalDegree ≤ H) ∧ ∑ i, A i * G i = 1
+
+/-- The two directions of the D.1 row-space criterion. The forward direction takes
+the uniform degree bound from the effective weak Nullstellensatz as a hypothesis. -/
+theorem row_test_of_weakCertificateBound (F : ι → MvPolynomial (Fin t) K)
+ (f : MvPolynomial (Fin t) K) {H P R₀ d : ℕ} (hHP : H ≤ P) (hP : P ≠ 0)
+ (hF : ∀ i, (F i).totalDegree ≤ d) (hf : f.totalDegree ≤ R₀)
+ (bound : WeakCertificateBound E (Option ι) (t + 1) (max d (R₀ + 1)) H) :
+ (∀ x : Fin t → E, (∀ i, aeval x (F i) = 0) → aeval x f = 0) ↔
+ coefficientRow (H + P * R₀ + d) (f ^ P) ∈ Submodule.span K
+ (Set.range (macaulayMatrix F (H + P * R₀) (H + P * R₀ + d)).row) := by
+ constructor
+ · intro hvan
+ let φ := algebraMap K E
+ let lift (p : MvPolynomial (Fin t) K) := rename Fin.succ (map φ p)
+ have hlift (p : MvPolynomial (Fin t) K) : (lift p).totalDegree ≤ p.totalDegree := by
+ simpa only [totalDegree, support_map_of_injective p φ.injective] using
+ totalDegree_rename_le Fin.succ (map φ p)
+ let G : Option ι → MvPolynomial (Fin (t + 1)) E
+ | some i => lift (F i)
+ | none => 1 - X 0 * lift f
+ have hdeg (i : Option ι) : (G i).totalDegree ≤ max d (R₀ + 1) := by
+ cases i with
+ | some i => exact ((hlift _).trans (hF i)).trans (le_max_left _ _)
+ | none =>
+ apply le_trans _ (le_max_right _ _)
+ apply (mem_restrictTotalDegree ..).mp
+ apply Submodule.sub_mem
+ · exact (mem_restrictTotalDegree ..).mpr (by simp)
+ · apply (mem_restrictTotalDegree ..).mpr
+ apply (totalDegree_mul _ _).trans
+ rw [totalDegree_X, add_comm]
+ exact Nat.add_le_add_right ((hlift _).trans hf) _
+ have hno : ¬∃ z : Fin (t + 1) → E, ∀ i, eval z (G i) = 0 := by
+ rintro ⟨z, hz⟩
+ have he (p : MvPolynomial (Fin t) K) : eval z (lift p) = aeval (z ∘ Fin.succ) p := by
+ simp only [lift, eval_rename, eval_map, aeval_def, φ]
+ have hzero := hvan (z ∘ Fin.succ) (fun i ↦ (he _).symm.trans (hz (some i)))
+ have hbad := hz none
+ change eval z (1 - X 0 * lift f) = 0 at hbad
+ simp [map_sub, map_mul, he, hzero] at hbad
+ obtain ⟨A, hA, ha⟩ := bound G hdeg hno
+ apply coefficientRow_pow_mem_of_extension F (fun i ↦ A (some i)) (A none)
+ hHP hP (fun i ↦ hA (some i)) hf
+ simpa only [Fintype.sum_option, G, lift, add_comm] using ha
+ · intro hrow x hx
+ have hdeg := (totalDegree_pow f P).trans (Nat.mul_le_mul_left _ hf)
+ have he := aeval_eq_zero_of_row_mem F hF (f ^ P) (by omega) hrow x hx
+ rw [map_pow] at he
+ exact (pow_eq_zero_iff hP).mp he
+
+/-- A power of the field cardinality distributes over linear combinations and fixes
+their coefficients. -/
+theorem linearCombination_pow_card [Fintype K] (s : ℕ) (c : ι → K)
+ (p : ι → MvPolynomial (Fin t) K) :
+ (∑ i, c i • p i) ^ (Fintype.card K ^ s) = ∑ i, c i • (p i ^ (Fintype.card K ^ s)) := by
+ induction s with
+ | zero => simp
+ | succ s ih =>
+ rw [pow_succ, pow_mul, ih]
+ let φ := FiniteField.frobeniusAlgHom K (MvPolynomial (Fin t) K)
+ change φ (∑ i, c i • _) = _
+ rw [map_sum]
+ refine Finset.sum_congr rfl fun i _ ↦ ?_
+ rw [map_smul]
+ exact congrArg (c i • ·) (pow_mul (p i) (Fintype.card K ^ s) (Fintype.card K)).symm
+
+/-- Coefficient rows commute with the base-linear Frobenius relation. -/
+theorem poweredRows_sum [Fintype K] (s D : ℕ) (c : ι → K)
+ (p : ι → MvPolynomial (Fin t) K) :
+ coefficientRow D ((∑ i, c i • p i) ^ (Fintype.card K ^ s)) =
+ ∑ i, c i • coefficientRow D (p i ^ (Fintype.card K ^ s)) := by
+ simp [linearCombination_pow_card, map_sum]
+
+/-- The value relation for a list of queried polynomials is exactly the corresponding
+linear relation on their powered rows modulo the Macaulay row space. In particular
+this applies to the monomial lists used in the prefix-rank and coordinate tests. -/
+theorem poweredRows_relation_iff [Fintype K] {J : Type*} [Fintype J]
+ (F : ι → MvPolynomial (Fin t) K) (p : J → MvPolynomial (Fin t) K) (c : J → K)
+ {H s R₀ d : ℕ} (hHP : H ≤ Fintype.card K ^ s) (hF : ∀ i, (F i).totalDegree ≤ d)
+ (hp : ∀ j, (p j).totalDegree ≤ R₀)
+ (bound : WeakCertificateBound E (Option ι) (t + 1) (max d (R₀ + 1)) H) :
+ let P := Fintype.card K ^ s
+ let L := H + P * R₀
+ (∀ x : Fin t → E, (∀ i, aeval x (F i) = 0) → ∑ j, c j • aeval x (p j) = 0) ↔
+ ∑ j, c j • coefficientRow (L + d) (p j ^ P) ∈ Submodule.span K
+ (Set.range (macaulayMatrix F L (L + d)).row) := by
+ dsimp only
+ have hdeg : (∑ j, c j • p j).totalDegree ≤ R₀ := totalDegree_finsetSum_le
+ fun j _ ↦ (totalDegree_smul_le _ _).trans (hp j)
+ simpa only [map_sum, map_smul, poweredRows_sum] using
+ row_test_of_weakCertificateBound F (∑ j, c j • p j) hHP
+ (pow_ne_zero _ Fintype.card_pos.ne') hF hdeg bound
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayRowDispatch.lean b/lean/OAI/Computability/VPVNP/MacaulayRowDispatch.lean
new file mode 100644
index 0000000000..aed1452465
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayRowDispatch.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.RankQueryStackCodegen
+import OAI.Computability.VPVNP.RankQueryTagRouter
+import OAI.Computability.VPVNP.MacaulayRowIndex
+
+/-! # Native dispatch of an augmented Macaulay row
+
+The first block contains the integer equations, followed by the affine slice
+rows, each paired with every multiplier monomial. The last block contains the
+powered monomials. One fixed register routine computes the kind of the row,
+the index of its equation or pin, the ordinal of its source monomial, and the
+unaltered column ordinal. All these numbers are runtime operands.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRowDispatch
+
+open Dispatch BurstRAM RAMTape
+
+/-- The row block determines which coefficient routine runs for an original equation, an affine
+pin or an appended powered monomial. -/
+inductive Kind | equation | affine | power deriving DecidableEq
+
+/-- Numeric dispatch tag for a row block, numbered 0 for equations, 1 for pins and 2 for
+powers. -/
+def Kind.tag : Kind → ℕ | .equation => 0 | .affine => 1 | .power => 2
+
+/-- Decoded address of a Macaulay entry, giving the row block, its local equation or pin index,
+and the source and column monomial ordinals. -/
+structure Address where
+ /-- Row block whose coefficient routine reads this entry. -/
+ kind : Kind
+ /-- Index within the original equations or affine pins. The decoder uses zero in this field
+ for appended powers. -/
+ row : ℕ
+ /-- Ordinal of the multiplier monomial for an equation or pin, or of the source monomial for
+ an appended power. -/
+ source : ℕ
+ /-- Ordinal of the requested column monomial. -/
+ column : ℕ
+ deriving DecidableEq
+
+/-- Encode the decoded address as six output words in the order tag, local row, source ordinal,
+column ordinal, zero, zero. -/
+def Address.fields (a : Address) : Fin 6 → ℕ := ![a.kind.tag, a.row, a.source, a.column, 0, 0]
+
+/-- These three cases use the same contiguous row ordering as `appendRows`
+and the two equation blocks of `slicedQueryData`. -/
+def address (i j equations pins multiples : ℕ) : Address :=
+ let all := (equations+pins)*multiples
+ if i < all then
+ let r := i/multiples
+ if r < equations then ⟨.equation, r, i%multiples, j⟩
+ else ⟨.affine, r-equations, i%multiples, j⟩
+ else ⟨.power, 0, i-all, j⟩
+
+/-- Form the eight input words from the row, column, equation count, pin count and multiplier
+count, followed by three zeros. -/
+def inputs (i j equations pins multiples : ℕ) : Fin 8 → ℕ := ![i,j,equations,pins,multiples,0,0,0]
+
+private def tree : Code :=
+ let i : Expr := .reg 0
+ let j : Expr := .reg 1
+ let eqns : Expr := .reg 2
+ let pins : Expr := .reg 3
+ let mult : Expr := .reg 4
+ let all := (eqns+pins)*mult
+ let r := i/mult
+ .test (all-i) 0 (.emit ![2,0,i-all,j,0,0])
+ (.test (eqns-r) 0 (.emit ![1,r-eqns,i%mult,j,0,0]) (.emit ![0,r,i%mult,j,0,0]))
+
+private theorem tree_eq (i j equations pins multiples : ℕ) :
+ tree.eval (inputs i j equations pins multiples) = (address i j equations pins multiples).fields := by
+ by_cases hl : i < (equations+pins)*multiples <;> by_cases hr : i/multiples < equations
+ all_goals funext a; fin_cases a <;>
+ simp [tree, inputs, Code.eval, eval_sub, eval_div, eval_mod, Expr.eval, Arith.eval, address, Address.fields,
+ Kind.tag, Nat.sub_eq_zero_iff_le, hl, hr, Nat.not_le.mpr, Nat.le_of_not_gt]
+
+/-- Number of scratch registers required by the compiled row decoder. -/
+abbrev cap := tree.scratch
+/-- Register indices for the decoder's eight inputs, six outputs and scratch space. -/
+abbrev Reg := Fin (14+cap)
+/-- Physical ISA ports for the decoder's register bank, with zero public memory ports. -/
+abbrev Small := RAMTape.ISA.Port (14+cap) 0
+
+/-- Fixed register routine that decodes an augmented row and returns its block and local
+indices. -/
+def machine : FiniteRoutine Small := tree.physical cap
+
+/-- Upper bound on decoder ticks from the emitted instruction count and the cost per
+instruction on width-`w` words. -/
+def ticks (w : ℕ) := (tree.emitFields cap (List.finRange 6)).length * (100*(w+1)^2)
+/-- Sufficient word width for intermediate computations when each decoder input fits in `bits`
+bits. -/
+def requiredWidth (bits : ℕ) := (bits+1)*tree.wordFactor
+
+/-- Locate one of the eight input words in the decoder's register bank. -/
+def inReg := Code.inReg cap
+/-- Locate one of the six decoded address words in the registers immediately following the
+inputs. -/
+def outReg := Code.outReg cap
+
+/-- The output ports are numbered by `Address.fields`. Input ports preserve
+both supplied ordinals and all advised row counts. -/
+theorem machine_runs (i j equations pins multiples p w : ℕ)
+ (bound : ∀ a, inputs i j equations pins multiples a < 2^p) (hw : requiredWidth p ≤ w)
+ (rs : Reg → Word w) (hin : ∀ a, (rs (inReg a)).val = inputs i j equations pins multiples a)
+ (persistent : Word w) :
+ ∃ cost ≤ ticks w, ∃ out, machine.Runs cost
+ (RAMTape.ISA.bank Fin.elim0 persistent rs []) (RAMTape.ISA.bank Fin.elim0 persistent out []) ∧
+ (∀ a, out (inReg a) = rs (inReg a)) ∧
+ ∀ a, (out (outReg a)).val = (address i j equations pins multiples).fields a := by
+ simpa only [ticks, machine, inReg, outReg, tree_eq] using tree.physical_runs cap p le_rfl _ rs hw bound hin Fin.elim0 persistent
+
+/-- Recover an equation row and the dense ordinal of its multiplier. -/
+theorem original_address {equations pins multiples : ℕ} (r : Fin equations) (k : Fin multiples) (j : ℕ) :
+ address (r.val*multiples+k.val) j equations pins multiples = ⟨.equation,r.val,k.val,j⟩ := by
+ have hm : 0 < multiples := Nat.zero_lt_of_lt k.isLt
+ have hv : r.val*multiples+k.val < (equations+pins)*multiples :=
+ (by have := Nat.mul_le_mul_right multiples (show r.val+1 ≤ equations+pins by omega); rw [Nat.succ_mul] at this; omega)
+ have hd : (r.val*multiples+k.val)/multiples = r.val := by
+ rw [Nat.mul_comm r.val, Nat.mul_add_div hm, Nat.div_eq_of_lt k.isLt, Nat.add_zero]
+ simp [address, hv, hd, r.isLt, Nat.mod_eq_of_lt k.isLt]
+
+/-- Affine rows retain their pin index when the prefix of integer equations
+is removed. -/
+theorem affine_address {equations pins multiples : ℕ} (r : Fin pins) (k : Fin multiples) (j : ℕ) :
+ address ((equations+r.val)*multiples+k.val) j equations pins multiples = ⟨.affine,r.val,k.val,j⟩ := by
+ have hm : 0 < multiples := Nat.zero_lt_of_lt k.isLt
+ have hv : (equations+r.val)*multiples+k.val < (equations+pins)*multiples :=
+ by have := Nat.mul_le_mul_right multiples (show (equations+r.val)+1 ≤ equations+pins by omega); rw [Nat.succ_mul] at this; omega
+ have hd : ((equations+r.val)*multiples+k.val)/multiples = equations+r.val := by
+ rw [Nat.mul_comm (equations+r.val), Nat.mul_add_div hm, Nat.div_eq_of_lt k.isLt, Nat.add_zero]
+ simp [address, hv, hd, Nat.mod_eq_of_lt k.isLt]
+
+/-- The appended row reads the source monomial ordinal in the suffix. -/
+theorem power_address (equations pins multiples k j : ℕ) :
+ address ((equations+pins)*multiples+k) j equations pins multiples = ⟨.power,0,k,j⟩ := by
+ simp [address]
+
+end RankQuery.Stack.MacaulayRowDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayRowIndex.lean b/lean/OAI/Computability/VPVNP/MacaulayRowIndex.lean
new file mode 100644
index 0000000000..3a3db32a6a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayRowIndex.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.GradedMonomialIndex
+import OAI.Computability.VPVNP.MacaulayCoordinates
+
+/-!
+# Entrywise queries in the finite-slice coefficient matrix
+
+The indexed matrix of Appendix D is given by a scalar equation-coefficient
+routine. A Macaulay entry needs at most one call to it. The appended rows and
+targets are powered monomials, so their entries require only exponent tests.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex
+
+open RankQuery MvPolynomial
+
+variable {t d e L D N : ℕ} {K : Type*}
+
+/-- Dense address of an equation and a multiplier monomial. -/
+def rowEquiv (t e L : ℕ) : Fin (e * size t L) ≃ Fin e × BoundedMonomial t L :=
+ finProdFinEquiv.symm.trans ((Equiv.refl _).prodCongr (enumeration t L))
+
+/-- Coefficient of a monomial multiple of an equation, read at a dense column index. -/
+def equationEntry [Zero K] (getCoeff : Fin e → (Fin t → ℕ) → K)
+ (r : Fin (e * size t L)) (c : Fin (size t D)) : K :=
+ let pair : Fin e × Fin (size t L) := finProdFinEquiv.symm r
+ let a := indexedDigits pair.2
+ let b := indexedDigits c
+ if ∀ i, a i ≤ b i then getCoeff pair.1 (fun i => b i - a i) else 0
+
+theorem equationEntry_eq [CommSemiring K] (F : Fin e → MvPolynomial (Fin t) K)
+ (getCoeff : Fin e → (Fin t → ℕ) → K)
+ (hget : ∀ i a, getCoeff i a = (F i).coeff (exponentVector a))
+ (r : Fin (e * size t L)) (c : Fin (size t D)) :
+ equationEntry getCoeff r c = macaulayMatrix F L D (rowEquiv t e L r) (enumeration t D c) := by
+ rw [macaulayMatrix_apply]
+ let pair : Fin e × Fin (size t L) := finProdFinEquiv.symm r
+ change (if ∀ i, indexedDigits pair.2 i ≤ indexedDigits c i then _ else 0) =
+ (if (enumeration t L pair.2).val ≤ (enumeration t D c).val then _ else 0)
+ simp only [indexedDigits_eq, Finsupp.le_def, hget]
+ split_ifs
+ · apply congrArg ((F pair.1).coeff)
+ exact Finsupp.ext fun _ => rfl
+ · rfl
+
+/-- An entry of a powered monomial row, computed without forming a polynomial. -/
+def powerEntry [Zero K] [One K] (P : ℕ) (a : Fin t → ℕ) (c : Fin (size t D)) : K :=
+ let b := indexedDigits c
+ if ∀ i, P * a i = b i then 1 else 0
+
+/-- A coefficient lookup agrees with taking the indicated power in the formal
+polynomial ring. This identity also covers power zero and the empty tuple. -/
+theorem powerEntry_eq [CommSemiring K] (P : ℕ) (a : Fin t → ℕ) (c : Fin (size t D)) :
+ powerEntry P a c = coefficientRow D ((monomial (exponentVector a) (1 : K)) ^ P)
+ (enumeration t D c) := by
+ change _ = ((monomial (exponentVector a) (1 : K)) ^ P).coeff _
+ rw [monomial_pow, one_pow, coeff_monomial]
+ have he : (∀ i, P * a i = indexedDigits c i) ↔
+ P • exponentVector a = (enumeration t D c).val := by
+ rw [DFunLike.ext_iff]
+ simp [exponentVector, indexedDigits_eq]
+ simp only [powerEntry, he]
+
+/-- The original (unpowered) monomial represented by a dense ordinal. -/
+noncomputable def monomialAt [CommSemiring K] (t N : ℕ) (i : Fin (size t N)) :
+ MvPolynomial (Fin t) K :=
+ monomial (enumeration t N i).val 1
+
+theorem powerEntry_indexed_eq [CommSemiring K] (P : ℕ) (j : Fin (size t N))
+ (c : Fin (size t D)) :
+ powerEntry P (indexedDigits j) c = coefficientRow D ((monomialAt t N j : MvPolynomial _ K) ^ P)
+ (enumeration t D c) := by
+ rw [powerEntry_eq]
+ have he : exponentVector (indexedDigits j) = (enumeration t N j).val :=
+ Finsupp.ext (indexedDigits_eq j)
+ rw [he]; rfl
+
+/-- A coordinate in the list of original monomial ordinals. Non-basis
+ordinals return zero. All matrix arguments are entry routines. -/
+def entryCoordinate [Field K] [DecidableEq K] (L D N P : ℕ)
+ (getCoeff : Fin e → (Fin t → ℕ) → K) (target : Fin t → ℕ) : Fin (size t N) → K :=
+ quotientCoordinate (m := size t D) (equationEntry (L := L) getCoeff)
+ (fun j => powerEntry P (indexedDigits j)) (powerEntry P target)
+
+theorem entryCoordinate_eq [Field K] [DecidableEq K] (L D N P : ℕ)
+ (F : Fin e → MvPolynomial (Fin t) K) (getCoeff : Fin e → (Fin t → ℕ) → K)
+ (hget : ∀ i a, getCoeff i a = (F i).coeff (exponentVector a)) (target : Fin t → ℕ) :
+ entryCoordinate L D N P getCoeff target =
+ macaulayCoordinateQuery F (monomialAt t N) (monomial (exponentVector target) 1) P
+ (rowEquiv t e L) (enumeration t D) := by
+ have heq : equationEntry (D := D) (L := L) getCoeff =
+ (macaulayMatrix F L D).submatrix (rowEquiv t e L) (enumeration t D) :=
+ funext fun r => funext fun c => equationEntry_eq F getCoeff hget r c
+ unfold entryCoordinate macaulayCoordinateQuery indexedQuotientCoordinate
+ rw [heq]
+ congr 1
+ · funext r c; exact powerEntry_indexed_eq P r c
+ · funext c; exact powerEntry_eq P target c
+
+end RadicalCertificate.MonomialIndex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayRows.lean b/lean/OAI/Computability/VPVNP/MacaulayRows.lean
new file mode 100644
index 0000000000..03eb3575e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayRows.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.RadicalCertificate
+import Mathlib.LinearAlgebra.Matrix.Defs
+import Mathlib.RingTheory.MvPolynomial.Basic
+
+/-!
+# The bounded coefficient matrix of the finite slice
+
+Appendix D.1 uses rows given by monomial multiples of the slicing equations.
+The bounded Rabinowitsch certificate puts the coefficient vector of the required
+power of a vanishing polynomial in this matrix's row space. Conversely, row-space
+membership implies vanishing at every geometric zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+open MvPolynomial
+
+variable {K : Type*} {t : ℕ} {ι : Type*}
+
+/-- Multi-indices of total degree at most `D` in the original `t` variables. -/
+def BoundedMonomial (t D : ℕ) := {a : Fin t →₀ ℕ // a.sum (fun _ e ↦ e) ≤ D}
+
+/-- The exponent of each variable is at most the total degree bound. -/
+def BoundedMonomial.encode {t D : ℕ} (a : BoundedMonomial t D) (i : Fin t) : Fin (D + 1) :=
+ ⟨a.val i, Nat.lt_succ_of_le (le_trans (by
+ by_cases hi : a.val i = 0
+ · exact hi ▸ Nat.zero_le _
+ · exact Finset.single_le_sum (fun _ _ ↦ Nat.zero_le _) (Finsupp.mem_support_iff.mpr hi)) a.prop)⟩
+
+theorem BoundedMonomial.encode_injective {t D : ℕ} :
+ Function.Injective (BoundedMonomial.encode (t := t) (D := D)) := by
+ intro a b hab
+ exact Subtype.ext <| Finsupp.ext fun i ↦ congrArg Fin.val (congrFun hab i)
+
+instance (t D : ℕ) : Finite (BoundedMonomial t D) :=
+ Finite.of_injective _ BoundedMonomial.encode_injective
+
+noncomputable instance (t D : ℕ) : Fintype (BoundedMonomial t D) := Fintype.ofFinite _
+
+/-- Each of the `t` exponents admits at most `D + 1` choices. -/
+theorem card_boundedMonomial_le (t D : ℕ) :
+ Fintype.card (BoundedMonomial t D) ≤ (D + 1) ^ t := by
+ simpa using Fintype.card_le_of_injective (BoundedMonomial.encode (t := t) (D := D))
+ BoundedMonomial.encode_injective
+
+section
+
+variable [CommSemiring K]
+
+/-- Coefficient row in the ordered matrix columns through degree `D`. -/
+noncomputable def coefficientRow (D : ℕ) :
+ MvPolynomial (Fin t) K →ₗ[K] (BoundedMonomial t D → K) :=
+ LinearMap.pi fun a ↦ lcoeff K a.val
+
+/-- The row indexed by `(i, a)` is the coefficient vector of `X^a Fᵢ`. -/
+noncomputable def macaulayMatrix (F : ι → MvPolynomial (Fin t) K) (L D : ℕ) :
+ Matrix (ι × BoundedMonomial t L) (BoundedMonomial t D) K :=
+ fun (i, a) ↦ coefficientRow D (monomial a.val 1 * F i)
+
+/-- The coefficient of a monomial multiple is the original coefficient with its
+exponent shifted, or zero if one of the exponents is too small. -/
+theorem macaulayMatrix_apply (F : ι → MvPolynomial (Fin t) K) {L D : ℕ}
+ (r : ι × BoundedMonomial t L) (j : BoundedMonomial t D) :
+ macaulayMatrix F L D r j =
+ if r.2.val ≤ j.val then (F r.1).coeff (j.val - r.2.val) else 0 := by
+ change (monomial r.2.val 1 * F r.1).coeff j.val = _
+ simp [coeff_monomial_mul']
+
+/-- For integer equations, the same absolute coefficient bound applies to every row. -/
+theorem macaulayMatrix_natAbs_le (F : ι → MvPolynomial (Fin t) ℤ) {L D B : ℕ}
+ (hB : ∀ i a, ((F i).coeff a).natAbs ≤ B) (r : ι × BoundedMonomial t L)
+ (j : BoundedMonomial t D) : (macaulayMatrix F L D r j).natAbs ≤ B := by
+ rw [macaulayMatrix_apply]
+ split_ifs <;> simp [hB]
+
+/-- The row augmenting the certificate matrix has a single nonzero coefficient, one. -/
+theorem coefficientRow_one_natAbs_le {D : ℕ} (j : BoundedMonomial t D) :
+ ((coefficientRow D (1 : MvPolynomial (Fin t) ℤ)) j).natAbs ≤ 1 := by
+ change ((1 : MvPolynomial (Fin t) ℤ).coeff j.val).natAbs ≤ 1
+ rw [coeff_one]
+ split_ifs <;> decide
+
+private noncomputable def polynomialRows (F : ι → MvPolynomial (Fin t) K) (L : ℕ) :
+ Submodule K (MvPolynomial (Fin t) K) :=
+ Submodule.span K (Set.range (fun p : ι × BoundedMonomial t L ↦ monomial p.2.val 1 * F p.1))
+
+private theorem rowSpan_eq (F : ι → MvPolynomial (Fin t) K) (L D : ℕ) :
+ Submodule.span K (Set.range (macaulayMatrix F L D).row) =
+ (polynomialRows F L).map (coefficientRow D) := by
+ rw [polynomialRows, Submodule.map_span, ← Set.range_comp]
+ rfl
+
+private theorem mul_mem_rows (F : ι → MvPolynomial (Fin t) K) {L : ℕ} (i : ι)
+ (g : MvPolynomial (Fin t) K) (hg : g.totalDegree ≤ L) : g * F i ∈ polynomialRows F L := by
+ have he : g * F i = ∑ a ∈ g.support, g.coeff a • (monomial a 1 * F i) := by
+ conv_lhs => rw [g.as_sum, Finset.sum_mul]
+ simp only [← smul_mul_assoc, smul_monomial, smul_eq_mul, mul_one]
+ rw [he]
+ exact Submodule.sum_mem _ fun a ha ↦ Submodule.smul_mem _ _ <|
+ Submodule.subset_span ⟨(i, ⟨a, (le_totalDegree ha).trans hg⟩), rfl⟩
+
+/-- Bounded multipliers express the coefficient row of a polynomial combination
+in the span of the Macaulay rows, over any commutative semiring. -/
+theorem coefficientRow_sum_mul_mem [Fintype ι] (F A : ι → MvPolynomial (Fin t) K)
+ {L : ℕ} (D : ℕ) (hA : ∀ i, (A i).totalDegree ≤ L) :
+ coefficientRow D (∑ i, A i * F i) ∈ Submodule.span K (Set.range (macaulayMatrix F L D).row) := by
+ rw [rowSpan_eq]
+ exact ⟨_, Submodule.sum_mem _ fun i _ ↦ mul_mem_rows F i _ (hA i), rfl⟩
+
+end
+
+variable [Field K]
+
+/-- The row space test resulting from the bounded inconsistency certificate, with the
+paper's multiplier bound `H + P * R₀` and column bound `H + P * R₀ + d`. -/
+theorem coefficientRow_pow_mem [Fintype ι] (F : ι → MvPolynomial (Fin t) K)
+ {f : MvPolynomial (Fin t) K} (A : ι → MvPolynomial (Fin (t + 1)) K)
+ (B : MvPolynomial (Fin (t + 1)) K) {H P R₀ d : ℕ} (hHP : H ≤ P) (hP : P ≠ 0)
+ (hA : ∀ i, (A i).totalDegree ≤ H) (hf : f.totalDegree ≤ R₀)
+ (hcert : (∑ i, A i * rename Fin.succ (F i)) + B * (1 - X 0 * rename Fin.succ f) = 1) :
+ coefficientRow (H + P * R₀ + d) (f ^ P) ∈ Submodule.span K
+ (Set.range (macaulayMatrix F (H + P * R₀) (H + P * R₀ + d)).row) := by
+ by_cases hz : f = 0
+ · simp [hz, zero_pow hP]
+ obtain ⟨he, hb⟩ := clear_certificate F hz A B hHP hA hcert
+ rw [← he]
+ exact coefficientRow_sum_mul_mem F _ _ fun i ↦
+ (hb i).trans (Nat.add_le_add_left (Nat.mul_le_mul_left _ hf) _)
+
+private theorem eq_of_coefficientRow_eq {D : ℕ} {p q : MvPolynomial (Fin t) K}
+ (hp : p.totalDegree ≤ D) (hq : q.totalDegree ≤ D)
+ (he : coefficientRow D p = coefficientRow D q) : p = q := by
+ ext a
+ by_cases ha : a.sum (fun _ e ↦ e) ≤ D
+ · exact congrFun he ⟨a, ha⟩
+ · have hp' : a ∉ p.support := fun h ↦ ha ((le_totalDegree h).trans hp)
+ have hq' : a ∉ q.support := fun h ↦ ha ((le_totalDegree h).trans hq)
+ simp_all [mem_support_iff]
+
+private theorem rows_degree_le (F : ι → MvPolynomial (Fin t) K) {d L : ℕ}
+ (hF : ∀ i, (F i).totalDegree ≤ d) :
+ polynomialRows F L ≤ restrictTotalDegree (Fin t) K (L + d) := by
+ refine Submodule.span_le.mpr ?_
+ rintro _ ⟨⟨i, a⟩, rfl⟩
+ apply (mem_restrictTotalDegree ..).mpr
+ exact (totalDegree_mul _ _).trans (Nat.add_le_add
+ ((totalDegree_monomial_le _ _).trans a.prop) (hF i))
+
+/-- A coefficient row in the Macaulay row space vanishes at all common zeros of the
+equations, including zeros in arbitrary extension fields. -/
+theorem aeval_eq_zero_of_row_mem {E : Type*} [Field E] [Algebra K E]
+ (F : ι → MvPolynomial (Fin t) K) {L d : ℕ} (hF : ∀ i, (F i).totalDegree ≤ d)
+ (p : MvPolynomial (Fin t) K) (hp : p.totalDegree ≤ L + d)
+ (hrow : coefficientRow (L + d) p ∈ Submodule.span K (Set.range (macaulayMatrix F L (L + d)).row))
+ (x : Fin t → E) (hx : ∀ i, aeval x (F i) = 0) : aeval x p = 0 := by
+ rw [rowSpan_eq] at hrow
+ obtain ⟨q, hq, he⟩ := hrow
+ have hdeg := (mem_restrictTotalDegree ..).mp (rows_degree_le F hF hq)
+ have heq := eq_of_coefficientRow_eq hdeg hp he
+ subst p
+ have hker : polynomialRows F L ≤ LinearMap.ker (aeval x).toLinearMap := by
+ refine Submodule.span_le.mpr ?_
+ rintro _ ⟨⟨i, a⟩, rfl⟩
+ change aeval x (monomial a.val 1 * F i) = 0
+ simp [hx i]
+ exact hker hq
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayScalarRoutines.lean b/lean/OAI/Computability/VPVNP/MacaulayScalarRoutines.lean
new file mode 100644
index 0000000000..de3f89d011
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayScalarRoutines.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.RegisterTableRoutine
+import OAI.Computability.VPVNP.MacaulayExponentQuery
+
+/-! # Returning monomial-index and powered-entry routines
+
+The caller supplies fixed-width registers and receives the raw index or
+comparison flags in the same bank. Both routines return with the private log
+and instruction scratch ports empty.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex
+
+open RAMTape.RegisterTable
+
+/-- Returning register routine that decodes a dense graded monomial ordinal to its raw code. -/
+def ordinalRoutine := routine ISA.table
+/-- Returning register routine that compares transformed source exponents with a column,
+reports divisibility and equality, and reads a requested residual exponent. -/
+def exponentRoutine := routine ExponentISA.table
+
+theorem ordinalRoutine_runs {w t D : ℕ} (k : Fin (size t D)) (fit : ISA.Fits (ISA.graded t D k) w) :
+ let p := ISA.graded t D k
+ let unit := RAMTape.ISA.prepareBound w 0+3
+ ∃ ticks ≤ (rawSize t D*(5*t+10)+2)*unit, ∃ out,
+ ordinalRoutine.BoundedRun (w+unit) ticks (bank Fin.elim0 0 (ISA.registers w p {}))
+ (bank Fin.elim0 0 (ISA.registers w p out)) ∧
+ out.cursor = (rawCode (enumeration t D k)).val ∧ out.count = k.val := by
+ intro p unit
+ obtain ⟨n,hn,out,hout,hr⟩ := ISA.scan_physical p fit
+ obtain ⟨ticks,ht,hret⟩ := return_run (T := ISA.table) (pc := 14) rfl hr
+ refine ⟨ticks, ?_, out, hret, ISA.ordinal_result hout⟩
+ change n ≤ (rawSize t D*(5*t+10)+1)*unit at hn
+ change ticks ≤ (rawSize t D*(5*t+10)+1+1)*unit
+ rw [Nat.add_one_mul]
+ dsimp [unit] at hn ⊢
+ omega
+
+theorem exponentRoutine_runs {w t : ℕ} (p : ExponentISA.Parameters) (fit : ExponentISA.Fits p w)
+ (source column : ℕ) (ht : t < 2^w) (ha : source < 2^w) (hb : column < 2^w) :
+ let input : ExponentISA.Work := ⟨t,source,column,0,true,true,0,0⟩
+ let unit := RAMTape.ISA.prepareBound w 0+3
+ ∃ ticks ≤ (16*t+2)*unit, ∃ out,
+ exponentRoutine.BoundedRun (w+unit) ticks (bank Fin.elim0 0 (ExponentISA.registers w p input))
+ (bank Fin.elim0 0 (ExponentISA.registers w p out)) ∧
+ (out.divides = true ↔ ∀ i < t, ExponentISA.scaledDigit p (t-i) (source/p.sourceBase^i) ≤ column/p.columnBase^i%p.columnBase) ∧
+ (out.same = true ↔ ∀ i < t, ExponentISA.scaledDigit p (t-i) (source/p.sourceBase^i) = column/p.columnBase^i%p.columnBase) ∧
+ ∀ i < t, p.request = t-i → out.residual =
+ column/p.columnBase^i%p.columnBase - ExponentISA.scaledDigit p (t-i) (source/p.sourceBase^i) := by
+ intro input unit
+ obtain ⟨n,hn,out,hr,hdiv,heq,hread⟩ := ExponentISA.run_digits p fit source column ht ha hb
+ obtain ⟨ticks,hb,hret⟩ := return_run (T := ExponentISA.table) (pc := 17) rfl hr
+ refine ⟨ticks, ?_, out, hret, hdiv,heq,hread⟩
+ change ticks ≤ (16*t+1+1)*unit
+ rw [Nat.add_one_mul]
+ dsimp [unit]; omega
+
+end RadicalCertificate.MonomialIndex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulaySignedCoefficient.lean b/lean/OAI/Computability/VPVNP/MacaulaySignedCoefficient.lean
new file mode 100644
index 0000000000..5f70f7449d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulaySignedCoefficient.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.MacaulaySignedLeaf
+import OAI.Computability.VPVNP.AffinePinCoefficient
+
+/-! # Original-equation coefficients on the native matrix-reader bus -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.SignedLeaf
+
+open RAMTape BurstRAM UniversalCountStack MacaulayRowDispatch JointLabelSystem
+open RadicalCertificate.MonomialIndex MvPolynomial
+
+variable {K : Type} (V I : Type*) [Fintype V] [Fintype I] (F : I → MvPolynomial V ℤ) {n : ℕ} (c : ℕ)
+variable {p e : ℕ} [Fact p.Prime] [NeZero e]
+
+/-- Install the signed coefficient routine's initial layout and empty input and output stacks
+at the embedded payload ports. -/
+noncomputable def preload (inc : JointScalar.Leaf.Port ↪ K) (L : JointScalar.Leaf.Layout)
+ (base : Stacks K) : Stacks K :=
+ installStacks inc base (JointScalar.Leaf.clean L [] [] [])
+
+theorem preload_correct (inc : JointScalar.Leaf.Port ↪ K) (L : JointScalar.Leaf.Layout) (base : Stacks K) :
+ Loaded L inc (preload inc L base) := fun i _ _ _ => installStacks_at inc.injective base _ i
+
+/-- Stack-length bound for one signed coefficient lookup, covering the Boolean checker,
+coefficient bank and local scalar operations. -/
+noncomputable abbrev callSpace (hn : 2 ≤ n) (w v : ℕ) (_modulus : SliceArithmetic.Vector p e) :=
+ let C := JointScalar.checker V I F c hn w
+ let L := JointScalar.Leaf.layout V I F c hn w p e v
+ let b := JointScalar.Leaf.bankSize L w (FixedRows.labelTotal V n c * w)
+ max (stackLimit C) b + JointScalar.Leaf.localCost L b
+
+/-- Tick bound for one signed coefficient lookup, including both witness counts and the local
+scalar operations. -/
+noncomputable abbrev callTime (hn : 2 ≤ n) (w v : ℕ) (_modulus : SliceArithmetic.Vector p e) :=
+ let C := JointScalar.checker V I F c hn w
+ let L := JointScalar.Leaf.layout V I F c hn w p e v
+ let b := JointScalar.Leaf.bankSize L w (FixedRows.labelTotal V n c * w)
+ 2*(2^L.witnessBits * perChoice C) + JointScalar.Leaf.localCost L b
+
+private theorem encode_cast {E : Type*} [Field E] [Algebra (ZMod p) E] {m : SliceArithmetic.Vector p e}
+ (φ : AdjoinRoot (SliceArithmetic.modulus m) ≃ₐ[ZMod p] E) (z : ℤ) :
+ (z : Scalar m) = AffinePin.Query.encode φ (z : E) := by
+ apply φ.injective.comp (Scalar.interpret_injective m)
+ change φ (Scalar.interpretation m _) = φ (Scalar.interpretation m _)
+ rw [AffinePin.Query.value_encode, map_intCast, map_intCast]
+
+set_option maxHeartbeats 1600000 in
+/-- On a divisible original row the decoded index and exponent buffer yield
+the encoded coefficient of the integer system after base change to the
+evaluation field. All scan buffers and the leaf advice survive the call. -/
+theorem coefficient [DecidableEq K] (hn : 2 ≤ n) {w v S : ℕ} {modulus : SliceArithmetic.Vector p e}
+ {E : Type*} [Field E] [Algebra (ZMod p) E] (φ : AdjoinRoot (SliceArithmetic.modulus modulus) ≃ₐ[ZMod p] E)
+ (inc : JointScalar.Leaf.Port ↪ K) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (row : Fin (2^n+Fintype.card I)) (d : Fin (FixedRows.labelTotal V n c) →₀ ℕ) (hd : ∀ i, d i < 2^w)
+ (rs : Reg → BurstRAM.Word w) (hi : (rs (outReg 1)).val = row.val)
+ (data : Bool → PairCall.Inputs) (pack flag constants : Bool → List Bool) (aux : Stacks K)
+ (hpack : pack false = ExponentPack.packed w (List.ofFn (fun i => d i)))
+ (hpre : Loaded (JointScalar.Leaf.layout V I F c hn w p e v) inc aux)
+ (hS : callSpace V I F c hn w v modulus ≤ S)
+ (room : ∀ i, (frame rs [] (Arms.storage w data pack flag constants aux) i).length ≤ S) :
+ let poly := unionEquations (grammarEquation hn c) F (FixedRows.rowIndex I n row)
+ let ans := AffinePin.Query.encode φ ((MvPolynomial.map (Int.castRingHom E) poly).coeff d)
+ ∃ steps ≤ callTime V I F c hn w v modulus,
+ (JointScalar.Leaf.machine.onPorts (ports inc)).BoundedRun S steps
+ (frame rs [] (Arms.storage w data pack flag constants aux))
+ (frame rs (Engine.scalar v ans) (Arms.storage w data pack flag constants aux)) := by
+ intro poly ans
+ let L := JointScalar.Leaf.layout V I F c hn w p e v
+ have fit : row.val < 2^w := hi ▸ (rs (outReg 1)).isLt
+ obtain ⟨steps,ht,hr⟩ := JointScalar.Leaf.coefficient_bounded V I F c hn w modulus hv w row fit
+ (fun i => d i) hd
+ have hvec : exponentVector (fun i => d i) = d := Finsupp.ext fun _ => rfl
+ rw [hvec] at hr
+ have hans : (poly.coeff d : Scalar modulus) = ans := by
+ dsimp only [ans]
+ rw [MvPolynomial.coeff_map]
+ exact encode_cast φ _
+ have hp : pack false = JointScalar.Leaf.packed w (fun i => d i) := hpack
+ refine ⟨steps,ht,bounded rs data pack flag constants aux inc inc.injective L hpre _ room ?_⟩
+ rw [hi,hp,← hans]
+ exact hr.enlarge hS
+
+end RankQuery.Stack.MacaulayRead.SignedLeaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulaySignedLeaf.lean b/lean/OAI/Computability/VPVNP/MacaulaySignedLeaf.lean
new file mode 100644
index 0000000000..507e0cd388
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulaySignedLeaf.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.MacaulayReadArms
+import OAI.Computability.VPVNP.JointScalarLeaf
+
+/-! # Installing the signed coefficient routine on the Macaulay reader bus -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.SignedLeaf
+
+open RAMTape BurstRAM UniversalCountStack MacaulayRowDispatch
+open RadicalCertificate.MonomialIndex
+
+variable {K : Type}
+
+/-- Row and exponent inputs refer directly to the caller's register and
+buffer. The result port belongs to the enclosing matrix reader. -/
+def ports (embed : JointScalar.Leaf.Port → K) (i : JointScalar.Leaf.Port) : Arms.Ports K :=
+ if i = .row then route (.reg (outReg 1))
+ else if i = .packed then Arms.slot false (.external .packed)
+ else if i = JointScalar.Leaf.resultPort then .result
+ else Arms.extra (.payload (embed i))
+
+private theorem row_address : route (.reg (outReg 1)) = (.aux (.inl (.reg (outReg 1))) : Arms.Ports K) := by
+ simp [route,outReg,inReg,Dispatch.Code.outReg,Dispatch.Code.inReg]
+
+theorem ports_injective {embed : JointScalar.Leaf.Port → K} (hinj : Function.Injective embed) : Function.Injective (ports embed) := by
+ intro i j h
+ simp only [ports,row_address,Arms.slot,Arms.extra] at h
+ split_ifs at h <;> first | contradiction | subst_vars; rfl | exact hinj (by simp at h <;> assumption)
+
+/-- Preloaded private stacks, including the checker advice, width words and
+field modulus. The three externally aliased ports require no payload. -/
+def Loaded (L : JointScalar.Leaf.Layout) (embed : JointScalar.Leaf.Port → K) (aux : Stacks K) :=
+ ∀ i, i ≠ .row → i ≠ .packed → i ≠ JointScalar.Leaf.resultPort → aux (embed i) = JointScalar.Leaf.clean L [] [] [] i
+
+private theorem leafFrame {w : ℕ} (rs : Reg → Word w) (res : List Bool)
+ (d : Bool → PairCall.Inputs) (pack flag constant : Bool → List Bool) (aux : Stacks K)
+ (embed : JointScalar.Leaf.Port → K) (L : JointScalar.Leaf.Layout) (loaded : Loaded L embed aux) (i : JointScalar.Leaf.Port) :
+ frame rs res (Arms.storage w d pack flag constant aux) (ports embed i) =
+ JointScalar.Leaf.clean L (digits w (rs (outReg 1)).val) (pack false) res i := by
+ by_cases hr : i = .row
+ · subst i
+ simp only [ports, ite_true, frame_route]
+ change wordBits (rs (outReg 1)) = wordBits (Fin.ofNat _ (rs (outReg 1)).val)
+ congr 1
+ exact Fin.ext (Nat.mod_eq_of_lt (rs (outReg 1)).isLt).symm
+ by_cases hp : i = .packed
+ · subst i; rfl
+ by_cases hs : i = JointScalar.Leaf.resultPort
+ · subst i; rfl
+ simp only [ports, hr, hp, hs, ite_false]
+ change aux (embed i) = _
+ rw [loaded i hr hp hs]
+ cases i with
+ | row => contradiction
+ | packed => contradiction
+ | arithmetic i =>
+ rcases i with i|i
+ · cases i with
+ | divide j => cases j <;> rfl
+ | _ => rfl
+ · cases i <;> first | rfl | exact (hs rfl).elim
+ | _ => rfl
+
+/-- A bounded run on the named coefficient bank lifts to a returning reader
+arm. The input registers, payload, flags, and both scan buffers are restored. -/
+theorem bounded [DecidableEq K] {w cap steps : ℕ} (rs : Reg → Word w) (d : Bool → PairCall.Inputs)
+ (pack flag constant : Bool → List Bool) (aux : Stacks K) (embed : JointScalar.Leaf.Port → K) (hinj : Function.Injective embed)
+ (L : JointScalar.Leaf.Layout) (loaded : Loaded L embed aux) (out : List Bool)
+ (room : ∀ i, (frame rs [] (Arms.storage w d pack flag constant aux) i).length ≤ cap)
+ (call : JointScalar.Leaf.machine.BoundedRun cap steps (JointScalar.Leaf.clean L (digits w (rs (outReg 1)).val) (pack false) [])
+ (JointScalar.Leaf.clean L (digits w (rs (outReg 1)).val) (pack false) out)) :
+ (JointScalar.Leaf.machine.onPorts (ports embed)).BoundedRun cap steps (frame rs [] (Arms.storage w d pack flag constant aux))
+ (frame rs out (Arms.storage w d pack flag constant aux)) := by
+ apply call.framed (ports_injective hinj) room (leafFrame rs [] d pack flag constant aux embed L loaded)
+ (leafFrame rs out d pack flag constant aux embed L loaded)
+ intro i hi
+ cases i <;> first | rfl | exact (hi JointScalar.Leaf.resultPort rfl).elim
+
+end RankQuery.Stack.MacaulayRead.SignedLeaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulaySignedRow.lean b/lean/OAI/Computability/VPVNP/MacaulaySignedRow.lean
new file mode 100644
index 0000000000..dede24cad7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulaySignedRow.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.MacaulayAppendedPower
+
+/-! # Native read of a shifted integer equation in the Macaulay matrix
+
+The reader decodes both monomials, checks divisibility, and, on its true
+branch, counts the signed coefficient at their coordinatewise difference.
+The reader restores its flag and residual buffer after returning the scalar.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead.Arms
+
+open BurstRAM RAMTape UniversalCountStack JointLabelSystem RadicalCertificate.MonomialIndex
+open MacaulayRowDispatch MvPolynomial
+
+variable {K : Type} [DecidableEq K] {p e w A S v : ℕ} [Fact p.Prime] [NeZero e]
+variable {modulus : SliceArithmetic.Vector p e}
+variable {E : Type*} [Field E] [Algebra (ZMod p) E]
+variable (V I : Type*) [Fintype V] [Fintype I] (F : I → MvPolynomial V ℤ) {n : ℕ} (c : ℕ)
+
+/-- The complete guarded original-row phase on the ordinary reader advice. -/
+theorem signed_row (hn : 2 ≤ n) (φ : AdjoinRoot (SliceArithmetic.modulus modulus) ≃ₐ[ZMod p] E)
+ (inc : JointScalar.Leaf.Port ↪ K) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ {eqs : ℕ} (Q : QueryData (FixedRows.labelTotal V n c) eqs E)
+ (rs : Reg → Word w) (aux : Stacks K)
+ (pre : Preload (w := w) A (BaseAdvice.inputs Q) (BaseAdvice.scalars modulus v) aux)
+ (hw : 1 ≤ w) (row : Fin (2^n+Fintype.card I))
+ (source : Fin (size (FixedRows.labelTotal V n c) Q.multiplierDegree))
+ (column : Fin (size (FixedRows.labelTotal V n c) Q.columnDegree))
+ (hrow : (rs (outReg 1)).val = row.val) (hsource : (rs (outReg 2)).val = source.val)
+ (hcolumn : (rs (outReg 3)).val = column.val) (hwidth : PairCall.requiredWidth (BaseAdvice.inputs Q false) ≤ w)
+ (loaded : SignedLeaf.Loaded (JointScalar.Leaf.layout V I F c hn w p e v) inc aux)
+ (hspace : PairCall.equationSpace w A (BaseAdvice.inputs Q false) ≤ S)
+ (htrans : transient A (FixedRows.labelTotal V n c) w ≤ S)
+ (hscalar : SignedLeaf.callSpace V I F c hn w v modulus ≤ S) :
+ let t := FixedRows.labelTotal V n c
+ let a := enumeration t Q.multiplierDegree source
+ let b := enumeration t Q.columnDegree column
+ let poly := MvPolynomial.map (Int.castRingHom E) (unionEquations (grammarEquation hn c) F (FixedRows.rowIndex I n row))
+ let ans : Scalar modulus := if a.val ≤ b.val then AffinePin.Query.encode φ (poly.coeff (b.val-a.val)) else 0
+ let ticks := SignedLeaf.callTime V I F c hn w v modulus
+ ∃ steps ≤ PairCall.scanClock w A (BaseAdvice.inputs Q false) + PairCall.packClock t w A +
+ PairCall.clearCost w + postTicks A t w ticks,
+ (phase false (JointScalar.Leaf.machine.onPorts (SignedLeaf.ports inc))).BoundedRun S steps
+ (frame rs [] (storage w (BaseAdvice.inputs Q) blank blank (BaseAdvice.scalars modulus v) aux))
+ (frame rs (Engine.scalar v ans) (storage w (BaseAdvice.inputs Q) blank blank (BaseAdvice.scalars modulus v) aux)) := by
+ intro t a b poly ans ticks
+ let data := BaseAdvice.inputs Q
+ let constants := BaseAdvice.scalars modulus v
+ let d := addressed rs (data false)
+ let ords : PairCall.Ordinals d := fun bit => match bit with
+ | false => source
+ | true => column
+ have hk (bit : Bool) : d.ordinal bit = (ords bit).val := by cases bit; exact hsource; exact hcolumn
+ obtain ⟨fit,_⟩ := PairCall.fits_of_width d ords hwidth
+ let residual := b.val-a.val
+ let yes := Engine.scalar v (AffinePin.Query.encode φ (poly.coeff residual))
+ let packed := PairCall.difference w a b
+ let pack := selected false packed
+ let flag := selected false (digits w (decide (a.val ≤ b.val)).toNat)
+ have hp : packed.length = t*w := PairCall.length_difference ..
+ have hflag : ∀ q, (flag q).length ≤ w := by intro q; cases q <;> simp [flag,selected,blank]
+ have hA : e*v ≤ A := by simpa only [BaseAdvice.scalars,Engine.scalar_length] using pre.scalars false
+ have hy : yes.length ≤ A := (Engine.scalar_length ..).le.trans hA
+ have hbig : A+t*w+w ≤ S := by change transient A t w ≤ S at htrans; unfold transient at htrans; omega
+ have room : ∀ z, (frame rs [] (storage w data pack flag constants aux) z).length ≤ S := by
+ apply frame_bound
+ · exact pre.words.trans (by omega)
+ · simp
+ · intro q; exact (pre.arity q).trans (by omega)
+ · intro q; cases q <;> simp [pack,selected,blank,hp]; omega
+ · intro q; exact (hflag q).trans (pre.words.trans (by omega))
+ · intro q; exact (pre.scalars q).trans (by omega)
+ · intro k; exact (pre.payload k).trans (by omega)
+ have hres (i : Fin t) : residual i < 2^w := by
+ have hb : b.val i < Q.columnDegree+1 := (b.encode i).isLt
+ have hdeg : Q.columnDegree+1 < 2^w := (fit true).base_lt
+ change b.val i - a.val i < 2^w
+ exact (Nat.sub_le ..).trans_lt (hb.trans hdeg)
+ have read := equation_execution rs data constants aux pre hw (JointScalar.Leaf.machine.onPorts (SignedLeaf.ports inc))
+ yes hy ticks ords hk fit hspace htrans
+ obtain ⟨steps,ht,run⟩ := read (fun _ => by
+ obtain ⟨steps,ht,call⟩ := SignedLeaf.coefficient V I F c hn φ inc hv row residual hres rs hrow data pack flag
+ constants aux (by rw [show pack false = packed from Function.update_self ..]; rfl) loaded hscalar room
+ exact ⟨steps,ht,packed,hp.le,call⟩)
+ have result : (if a.val ≤ b.val then yes else constants false) = Engine.scalar v ans := by
+ by_cases h : a.val ≤ b.val <;> simp only [ans,h,ite_true,ite_false] <;> rfl
+ change (phase false _).BoundedRun S steps _ (frame rs (if a.val ≤ b.val then yes else constants false) _) at run
+ exact ⟨steps,ht,result ▸ run⟩
+
+
+/-- A single reader plan supplies the scan, temporary-buffer and counted
+coefficient budgets before the matrix entry is selected. -/
+theorem signed_row_plan (hn : 2 ≤ n) (φ : AdjoinRoot (SliceArithmetic.modulus modulus) ≃ₐ[ZMod p] E)
+ (inc : JointScalar.Leaf.Port ↪ K) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (P : ReaderPlan) {eqs : ℕ} (Q : QueryData (FixedRows.labelTotal V n c) eqs E)
+ (ha : FixedRows.labelTotal V n c = P.arity)
+ (hl : Q.multiplierDegree ≤ P.source) (hd : Q.columnDegree ≤ P.column)
+ {Emax vmax : ℕ} (he : e ≤ Emax) (hvw : v ≤ vmax) (sp ex : ℕ)
+ (hsp : SignedLeaf.callSpace V I F c hn w v modulus ≤ sp)
+ (htime : SignedLeaf.callTime V I F c hn w v modulus ≤ 2^ex) (hw : P.wordWidth ≤ w)
+ (rs : Reg → Word w) (aux : Stacks K)
+ (pre : Preload (w := w) (P.live Emax vmax w sp) (BaseAdvice.inputs Q) (BaseAdvice.scalars modulus v) aux)
+ (loaded : SignedLeaf.Loaded (JointScalar.Leaf.layout V I F c hn w p e v) inc aux)
+ (row : Fin (2^n+Fintype.card I))
+ (source : Fin (size (FixedRows.labelTotal V n c) Q.multiplierDegree))
+ (column : Fin (size (FixedRows.labelTotal V n c) Q.columnDegree))
+ (hrow : (rs (outReg 1)).val = row.val) (hsource : (rs (outReg 2)).val = source.val)
+ (hcolumn : (rs (outReg 3)).val = column.val) :
+ let t := FixedRows.labelTotal V n c
+ let a := enumeration t Q.multiplierDegree source
+ let b := enumeration t Q.columnDegree column
+ let poly := MvPolynomial.map (Int.castRingHom E) (unionEquations (grammarEquation hn c) F (FixedRows.rowIndex I n row))
+ let ans : Scalar modulus := if a.val ≤ b.val then AffinePin.Query.encode φ (poly.coeff (b.val-a.val)) else 0
+ ∃ steps ≤ P.armTime Emax vmax w sp ex,
+ (phase false (JointScalar.Leaf.machine.onPorts (SignedLeaf.ports inc))).BoundedRun (P.armSpace Emax vmax w sp) steps
+ (frame rs [] (storage w (BaseAdvice.inputs Q) blank blank (BaseAdvice.scalars modulus v) aux))
+ (frame rs (Engine.scalar v ans) (storage w (BaseAdvice.inputs Q) blank blank (BaseAdvice.scalars modulus v) aux)) := by
+ intro t a b poly ans
+ let A := P.live Emax vmax w sp
+ let d := BaseAdvice.inputs Q false
+ let ticks := SignedLeaf.callTime V I F c hn w v modulus
+ have hwidth := (P.pairWidth_le d ha hl hd (le_max_left ..) (Nat.zero_le _)).trans hw
+ obtain ⟨live,space,time⟩ := P.leaf_bounds w sp ex he hvw d ha hl hd
+ have had : A + MacaulayRowDispatch.ticks w ≤ P.armSpace Emax vmax w sp := space.2.2.1
+ have hspA : sp ≤ A := live.2.2.2.2.1
+ have hs := hspA.trans ((Nat.le_add_right A (MacaulayRowDispatch.ticks w)).trans had)
+ have htrans : transient A t w ≤ P.armSpace Emax vmax w sp := by
+ rw [show t = P.arity from ha]
+ exact space.2.2.2.1
+ obtain ⟨steps,ht,run⟩ := signed_row V I F c hn φ inc hv Q rs aux pre
+ ((by decide : 1≤2).trans (P.dispatchWidth.2.2.trans hw)) row source column hrow hsource hcolumn
+ hwidth loaded space.1 htrans (hsp.trans hs)
+ have scan := (P.scan_bounds w A d ha hl hd).1
+ have hpost : postTicks A t w ticks ≤
+ postTicks A P.arity w (max ticks (max (Pin.cost P.arity e w v) (5*(e*v)+2))) := by
+ rw [show t = P.arity from ha]
+ unfold postTicks
+ gcongr
+ exact le_max_left ..
+ exact ⟨steps,ht.trans ((Nat.add_le_add scan hpost).trans (time ticks htime)),run⟩
+
+end RankQuery.Stack.MacaulayRead.Arms
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulaySliceBasis.lean b/lean/OAI/Computability/VPVNP/MacaulaySliceBasis.lean
new file mode 100644
index 0000000000..310e329a49
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulaySliceBasis.lean
@@ -0,0 +1,375 @@
+import OAI.Computability.VPVNP.MacaulayRowIndex
+import OAI.Computability.VPVNP.GreedySuffixIndex
+import OAI.Computability.VPVNP.EffectiveNullstellensatz
+import OAI.Computability.VPVNP.MonomialBasis
+
+/-!
+# Numeric basis queries for a finite reduced slice
+
+For an indexed system of equations and a known bound on the finite geometric
+zero set, these are the dimension, monomial basis ordinals and matrix entries
+from Lemma 8.2. The field cardinality is a numeric input. Correctness uses the
+proved effective weak Nullstellensatz and equality of the coefficient routine
+with the coefficients of the defining equations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex
+
+open RankQuery MvPolynomial FiniteSlice
+
+/-- Numeric input to the finite-slice queries. -/
+structure QueryData (t e : ℕ) (K : Type*) where
+ /-- Numeric cardinality of the finite ground field used in the Frobenius queries. -/
+ fieldOrder : ℕ
+ /-- Supplied upper bound on the total degrees of the indexed defining equations. -/
+ degreeBound : ℕ
+ /-- Supplied bound on the number of geometric points, also used to enumerate candidate basis
+ monomials. -/
+ pointBound : ℕ
+ /-- Look up the coefficient of an exponent tuple in an indexed defining equation. -/
+ getCoeff : Fin e → (Fin t → ℕ) → K
+
+variable {t e : ℕ} {K E : Type*}
+
+namespace QueryData
+
+variable (S : QueryData t e K)
+
+/-- Maximum degree of any target monomial in a multiplication or Frobenius query. -/
+def targetDegree := (S.pointBound + 1) * S.fieldOrder
+
+/-- Effective Nullstellensatz certificate degree used to bound the radical membership
+computation for the target monomials. -/
+def certificateDegree := (2 * max S.degreeBound (S.targetDegree + 1)) ^ (4 * (t + 3))
+
+/-- Ceiling logarithm of the certificate degree in base the ground-field order, giving the
+number of Frobenius iterations. -/
+def powerExponent := Nat.clog S.fieldOrder S.certificateDegree
+
+/-- Power to which the candidate monomials are raised for the radical membership test. -/
+def power := S.fieldOrder ^ S.powerExponent
+
+/-- Degree bound for multipliers in the Macaulay equation rows, obtained by adding the
+certificate degree to the powered target degree. -/
+def multiplierDegree := S.certificateDegree + S.power * S.targetDegree
+
+/-- Maximum total degree indexed by the columns, allowing a multiplier times any defining
+equation. -/
+def columnDegree := S.multiplierDegree + S.degreeBound
+
+/-- Coefficient matrix of all bounded monomial multiples of the defining equations, with
+entries read from the supplied coefficient lookup. -/
+abbrev equations [Zero K] := equationEntry (L := S.multiplierDegree) (D := S.columnDegree) S.getCoeff
+
+/-- Coefficient rows of the powered candidate monomials, indexed by their original ordinals up
+to the point bound. -/
+abbrev monomials [Zero K] [One K] : Matrix (Fin (size t S.pointBound)) (Fin (size t S.columnDegree)) K :=
+ fun j => powerEntry S.power (indexedDigits j)
+
+/-- Rank gained by appending the powered monomial rows to the equation matrix. For a presented
+finite slice this computes its reduced coordinate algebra dimension. -/
+def dimension [Field K] [DecidableEq K] := suffixDimension S.equations S.monomials
+
+/-- Return the original monomial ordinal for a given position among the rows selected greedily
+after the equation rows. -/
+def basisIndex [Field K] [DecidableEq K] : Fin S.dimension → Fin (size t S.pointBound) :=
+ suffixBasisIndex S.equations S.monomials
+
+/-- The two linear transformations queried in Lemma 8.2. -/
+inductive Operation (t : ℕ) where
+ | label (i : Fin t)
+ | frobenius
+
+/-- Exponent tuple after multiplying by the selected variable or raising the monomial to the
+ground-field order. -/
+def target (op : Operation t) (a : Fin t → ℕ) : Fin t → ℕ :=
+ match op with
+ | .label i => fun j => (if j = i then 1 else 0) + a j
+ | .frobenius => fun j => S.fieldOrder * a j
+
+/-- Matrix column `j`, row `i`, in dense basis coordinates. -/
+def matrixEntry [Field K] [DecidableEq K] (op : Operation t) (i j : Fin S.dimension) : K :=
+ entryCoordinate S.multiplierDegree S.columnDegree S.pointBound S.power S.getCoeff
+ (S.target op (indexedDigits (S.basisIndex j))) (S.basisIndex i)
+
+variable [Field K] [Fintype K] [DecidableEq K] [Field E] [Algebra K E] [IsAlgClosed E]
+
+/-- Agreement of the numerical field order, degree bound and entry oracle with the equations. -/
+structure Presents (F : Fin e → MvPolynomial (Fin t) K) : Prop where
+ fieldOrder_eq : S.fieldOrder = Fintype.card K
+ degree_ge_three : 3 ≤ S.degreeBound
+ degree_le : ∀ i, (F i).totalDegree ≤ S.degreeBound
+ coefficient_eq : ∀ i a, S.getCoeff i a = (F i).coeff (exponentVector a)
+
+variable (F : Fin e → MvPolynomial (Fin t) K)
+
+/-- Common zero set of the defining equations in the extension field. -/
+def points (E : Type*) [Field E] [Algebra K E] := {x : Fin t → E | ∀ i, aeval x (F i) = 0}
+
+/-- Send a polynomial over the ground field to its class modulo the vanishing ideal of the
+common zero set. -/
+noncomputable abbrev quotientMap (E : Type*) [Field E] [Algebra K E] :=
+ Ideal.Quotient.mkₐ K (vanishingIdeal K (points F E))
+
+/-- Enumerate the classes of candidate monomials in the reduced coordinate algebra using dense
+monomial ordinals. -/
+noncomputable abbrev listing (E : Type*) [Field E] [Algebra K E]
+ (j : Fin (size t S.pointBound)) : CoordinateAlgebra K (points F E) :=
+ quotientMap F E (monomialAt t S.pointBound j)
+
+omit [Fintype K] [DecidableEq K] [IsAlgClosed E] in
+theorem listing_range :
+ Set.range (S.listing F E) =
+ MonomialBasis.monomials (coordinateLabel (K := K) (points F E)) S.pointBound := by
+ let X := coordinateLabel (K := K) (points F E)
+ have value (a : Fin t →₀ ℕ) : quotientMap F E (monomial a 1) = ∏ i, X i ^ a i := by
+ unfold quotientMap
+ rw [← aeval_coordinateLabel]
+ simp [aeval_monomial, Finsupp.prod_fintype, X]
+ ext x
+ constructor
+ · rintro ⟨j, rfl⟩
+ let a := enumeration t S.pointBound j
+ exact ⟨a.val, by simpa [Finsupp.sum_fintype] using a.prop, (value a.val).symm⟩
+ · rintro ⟨f, hf, rfl⟩
+ let a : BoundedMonomial t S.pointBound := ⟨exponentVector f, by
+ rw [Finsupp.sum_fintype _ _ (fun _ => rfl)]; exact hf⟩
+ refine ⟨(enumeration t S.pointBound).symm a, ?_⟩
+ simp only [listing, monomialAt, Equiv.apply_symm_apply, value]
+ rfl
+
+omit [Fintype K] [DecidableEq K] [IsAlgClosed E] in
+theorem listing_first :
+ S.listing F E ⟨0, size_pos t S.pointBound⟩ = 1 := by
+ simp [listing, monomialAt, enumeration_first, constant]
+
+omit [DecidableEq K] in
+private theorem power_eq (h : S.Presents F) :
+ S.power = Fintype.card K ^ S.powerExponent := by rw [power, h.fieldOrder_eq]
+
+omit [DecidableEq K] in
+private theorem power_ge (h : S.Presents F) : S.certificateDegree ≤ Fintype.card K ^ S.powerExponent := by
+ rw [← S.power_eq F h, power, powerExponent]
+ apply Nat.le_pow_clog
+ rw [h.fieldOrder_eq]; exact Fintype.one_lt_card
+
+omit [DecidableEq K] [Algebra K E] in
+private theorem certificateBound (h : S.Presents F) :
+ WeakCertificateBound E (Option (Fin e)) (t+1) (max S.degreeBound (S.targetDegree+1)) S.certificateDegree :=
+ effective_weakCertificateBound E _ (h.degree_ge_three.trans (le_max_left ..))
+
+omit [DecidableEq K] in
+private theorem list_degree (h : S.Presents F) (j : Fin (size t S.pointBound)) :
+ (monomialAt t S.pointBound j : MvPolynomial _ K).totalDegree ≤ S.targetDegree := by
+ apply (totalDegree_monomial_le _ _).trans
+ apply (enumeration t S.pointBound j).prop.trans
+ unfold targetDegree
+ have hpos : 1 ≤ S.fieldOrder := by rw [h.fieldOrder_eq]; exact Fintype.card_pos
+ exact (Nat.le_succ _).trans (Nat.le_mul_of_pos_right _ hpos)
+
+theorem basisIndex_mem_iff (h : S.Presents F) (j : Fin (size t S.pointBound)) :
+ j ∈ Set.range S.basisIndex ↔ j ∈ greedyIndices K (S.listing F E) := by
+ have hM (i c) : S.monomials i c = coefficientRow S.columnDegree
+ ((monomialAt t S.pointBound i : MvPolynomial _ K) ^ S.power) (enumeration t S.columnDegree c) :=
+ powerEntry_indexed_eq _ _ _
+ have hW (r c) : S.equations r c = macaulayMatrix F S.multiplierDegree S.columnDegree
+ (rowEquiv t e S.multiplierDegree r) (enumeration t S.columnDegree c) :=
+ equationEntry_eq F _ h.coefficient_eq r c
+ have he := macaulay_greedyIndex_iff F (monomialAt t S.pointBound) (S.power_ge F h)
+ h.degree_le (S.list_degree F h) (S.certificateBound (E := E) F h)
+ (rowEquiv t e _) (enumeration t _) j
+ refine (mem_range_suffixBasisIndex S.equations S.monomials j).trans ?_
+ rw [show S.equations = _ from funext fun r => funext (hW r),
+ show S.monomials = _ from funext fun i => funext (hM i)]
+ dsimp only at he
+ rw [← S.power_eq F h] at he
+ exact he
+
+omit [Fintype K] [DecidableEq K] [IsAlgClosed E] in
+private theorem points_eq_zeroLocus : points F E = zeroLocus E (Ideal.span (Set.range F)) := by
+ ext x
+ simp [points, zeroLocus_span]
+
+omit [DecidableEq K] [IsAlgClosed E] in
+private theorem finiteRank (hfin : (points F E).Finite) (hN : (points F E).ncard ≤ S.pointBound) :
+ Module.Finite K (CoordinateAlgebra K (points F E)) ∧
+ Module.finrank K (CoordinateAlgebra K (points F E)) ≤ S.pointBound := by
+ rw [points_eq_zeroLocus] at hfin hN ⊢
+ let := hfin.fintype
+ obtain ⟨h, hdim⟩ := coordinateAlgebra_finite_finrank (E := E) (Ideal.span (Set.range F))
+ exact ⟨h, hdim.trans (by rwa [← Nat.card_eq_fintype_card])⟩
+
+/-- The matrix-rank algorithm actually indexes a basis of the reduced
+coordinate algebra. Its first vector is the unit for a nonempty slice. -/
+theorem exists_basis (h : S.Presents F) (hn : (points F E).Nonempty)
+ (hfin : (points F E).Finite) (hN : (points F E).ncard ≤ S.pointBound) :
+ ∃ b : Module.Basis (Fin S.dimension) K (CoordinateAlgebra K (points F E)),
+ (∀ i, b i = S.listing F E (S.basisIndex i)) ∧ ∃ u, u.val = 0 ∧ b u = 1 := by
+ let A := CoordinateAlgebra K (points F E)
+ let v := S.listing F E
+ obtain ⟨hfin', hdim⟩ := S.finiteRank F hfin hN
+ let : Module.Finite K A := hfin'
+ let : Nonempty (points F E) := hn.to_subtype
+ let : Nontrivial A := coordinateAlgebra_nontrivial _
+ have hind := suffixBasisIndex_injective S.equations S.monomials
+ have himage : Set.range S.basisIndex = (greedyIndices K v : Set _) := Set.ext (S.basisIndex_mem_iff F h)
+ let eqv := (Equiv.ofInjective S.basisIndex hind).trans (Set.equivOfEq himage)
+ have hi := (linearIndependent_equiv (R := K) (f := fun i : greedyIndices K v => v i.val) eqv).mpr
+ (greedyIndices_linearIndepOn K v)
+ have hspan : Submodule.span K (Set.range (v ∘ S.basisIndex)) = ⊤ := by
+ rw [Set.range_comp, himage]
+ have hall := greedyIndices_span_prefix K v (size t S.pointBound)
+ have huniv : {i : Fin (size t S.pointBound) | i.val < size t S.pointBound} = Set.univ :=
+ Set.eq_univ_of_forall (fun i => i.isLt)
+ rw [huniv, Set.inter_univ, Set.image_univ] at hall
+ rw [hall, S.listing_range F]
+ exact MonomialBasis.degreeSpan_eq_top _ _ (adjoin_coordinateLabel _) hdim
+ let b := Module.Basis.mk (v := v ∘ S.basisIndex) hi hspan.ge
+ have hb (i) : b i = v (S.basisIndex i) := Module.Basis.mk_apply ..
+ let z : Fin (size t S.pointBound) := ⟨0, size_pos ..⟩
+ have hz : z ∈ greedyIndices K v := by
+ have hempty : Set.Iio z = ∅ := by ext i; simp [z, Fin.le_def]
+ rw [mem_greedyIndices, hempty, show v z = 1 from S.listing_first F]
+ simp
+ obtain ⟨u, hu⟩ := (S.basisIndex_mem_iff F h z).mpr hz
+ refine ⟨b, hb, u, ?_, (hb u).trans (hu ▸ S.listing_first F)⟩
+ by_contra hne
+ let i : Fin S.dimension := ⟨0, u.pos⟩
+ have hlt : i < u := Nat.pos_of_ne_zero hne
+ have hlt' := suffixBasisIndex_strictMono S.equations S.monomials hlt
+ change S.basisIndex i < S.basisIndex u at hlt'
+ rw [hu] at hlt'
+ exact Nat.not_lt_zero _ hlt'
+
+/-- The size returned by the two rank queries is the reduced algebra dimension. -/
+theorem dimension_eq (h : S.Presents F) (hn : (points F E).Nonempty)
+ (hfin : (points F E).Finite) (hN : (points F E).ncard ≤ S.pointBound) :
+ S.dimension = Module.finrank K (CoordinateAlgebra K (points F E)) := by
+ obtain ⟨b, _, _⟩ := S.exists_basis F h hn hfin hN
+ simpa using (Module.finrank_eq_card_basis b).symm
+
+/-- Any monomial of degree at most the target-degree bound has the coordinates
+returned by the row algorithm, restricted to dense basis ordinals. -/
+theorem coordinate_eq_repr (h : S.Presents F)
+ (b : Module.Basis (Fin S.dimension) K (CoordinateAlgebra K (points F E)))
+ (hb : ∀ i, b i = S.listing F E (S.basisIndex i)) (a : Fin t → ℕ)
+ (ha : (monomial (exponentVector a) (1 : K)).totalDegree ≤ S.targetDegree)
+ (i : Fin S.dimension) :
+ entryCoordinate S.multiplierDegree S.columnDegree S.pointBound S.power S.getCoeff a (S.basisIndex i) =
+ b.repr (quotientMap F E (monomial (exponentVector a) 1)) i := by
+ let c := entryCoordinate S.multiplierDegree S.columnDegree S.pointBound S.power S.getCoeff a
+ let targetPoly : MvPolynomial (Fin t) K := monomial (exponentVector a) 1
+ let v := S.listing F E
+ have he := entryCoordinate_eq S.multiplierDegree S.columnDegree S.pointBound S.power F S.getCoeff
+ h.coefficient_eq a
+ have hspan : Submodule.span K (Set.range v) = ⊤ := by
+ apply eq_top_iff.mpr
+ rw [← b.span_eq]
+ apply Submodule.span_mono
+ rintro _ ⟨k,rfl⟩; exact ⟨S.basisIndex k, (hb k).symm⟩
+ have hr := macaulayCoordinateQuery_reconstruct F (monomialAt t S.pointBound) targetPoly
+ (S.power_ge F h) h.degree_le (S.list_degree F h) ha (S.certificateBound (E := E) F h)
+ (rowEquiv t e _) (enumeration t _)
+ dsimp only at hr
+ rw [← S.power_eq F h] at hr
+ have htarget : quotientMap F E targetPoly = ∑ j, c j • v j := by
+ dsimp only [c]
+ rw [he]
+ exact hr (by change _ ∈ Submodule.span K (Set.range v); rw [hspan]; trivial)
+ have hz (j : Fin (size t S.pointBound)) (hj : j ∉ Set.range S.basisIndex) : c j = 0 := by
+ have hj' := (S.basisIndex_mem_iff (E := E) F h j).not.mp hj
+ have hzero := macaulayCoordinateQuery_eq_zero F (monomialAt t S.pointBound) targetPoly
+ (S.power_ge F h) h.degree_le (S.list_degree F h) (S.certificateBound (E := E) F h)
+ (rowEquiv t e _) (enumeration t _) j hj'
+ rw [← S.power_eq F h] at hzero
+ dsimp only [c]
+ rw [he]
+ exact hzero
+ have hre : ∑ k, c (S.basisIndex k) • b k = ∑ j, c j • v j := by
+ simp only [hb]
+ change ∑ x, c (S.basisIndex x) • v (S.basisIndex x) = _
+ have hinj : Function.Injective S.basisIndex := suffixBasisIndex_injective S.equations S.monomials
+ rw [← Finset.sum_image (s := Finset.univ) (f := fun j => c j • v j) hinj.injOn]
+ apply Finset.sum_subset (Finset.subset_univ _)
+ intro j _ hj
+ have hnot : j ∉ Set.range S.basisIndex := fun ⟨k, hk⟩ => hj (Finset.mem_image.mpr ⟨k, Finset.mem_univ _, hk⟩)
+ rw [hz j hnot, zero_smul]
+ have hsum := htarget.trans hre.symm
+ have hh := congrArg (fun x => b.repr x i) hsum
+ simp only [Module.Basis.repr_sum_self] at hh
+ exact hh.symm
+
+/-- Multiply by one coordinate or apply the ground-field cardinality power. -/
+def Operation.apply {A : Type*} [CommRing A] (op : Operation t) (Q : ℕ) (X : Fin t → A) (v : A) : A :=
+ match op with
+ | .label i => X i * v
+ | .frobenius => v ^ Q
+
+omit [Fintype K] [DecidableEq K] in
+private theorem targetPolynomial (op : Operation t) (j : Fin (size t S.pointBound)) :
+ monomial (exponentVector (S.target op (indexedDigits j))) (1 : K) =
+ op.apply S.fieldOrder MvPolynomial.X (monomialAt t S.pointBound j) := by
+ cases op with
+ | label i =>
+ rw [Operation.apply, monomialAt, X, monomial_mul_monomial, one_mul]
+ apply congrArg (fun a : Fin t →₀ ℕ => monomial a (1 : K))
+ ext k
+ simp [target, exponentVector, indexedDigits_eq, Finsupp.single_apply, eq_comm]
+ | frobenius =>
+ rw [Operation.apply, monomialAt, monomial_pow, one_pow]
+ apply congrArg (fun a : Fin t →₀ ℕ => monomial a (1 : K))
+ ext k
+ simp [target, exponentVector, indexedDigits_eq]
+
+omit [DecidableEq K] in
+private theorem target_degree (h : S.Presents F) (op : Operation t) (j : Fin (size t S.pointBound)) :
+ (monomial (exponentVector (S.target op (indexedDigits j))) (1 : K)).totalDegree ≤ S.targetDegree := by
+ have hdeg : (monomialAt t S.pointBound j : MvPolynomial _ K).totalDegree ≤ S.pointBound :=
+ (totalDegree_monomial_le _ _).trans (enumeration t S.pointBound j).prop
+ rw [S.targetPolynomial op j]
+ cases op with
+ | label i =>
+ apply (totalDegree_mul ..).trans
+ rw [totalDegree_X]
+ have hpos : 1 ≤ S.fieldOrder := by rw [h.fieldOrder_eq]; exact Fintype.card_pos
+ exact (Nat.add_le_add_left hdeg 1).trans ((Nat.add_comm 1 _).trans_le (Nat.le_mul_of_pos_right _ hpos))
+ | frobenius =>
+ apply (totalDegree_pow ..).trans
+ unfold targetDegree
+ rw [Nat.mul_comm _ S.fieldOrder]
+ exact Nat.mul_le_mul_left _ (hdeg.trans (Nat.le_succ _))
+
+/-- The actual matrix-entry routine returns the coefficient of multiplying
+the `j`-th basis monomial by a label or raising it to the field cardinality. -/
+theorem matrixEntry_eq_repr (h : S.Presents F)
+ (b : Module.Basis (Fin S.dimension) K (CoordinateAlgebra K (points F E)))
+ (hb : ∀ i, b i = S.listing F E (S.basisIndex i)) (op : Operation t) (i j : Fin S.dimension) :
+ S.matrixEntry op i j =
+ b.repr (op.apply S.fieldOrder (coordinateLabel (points F E)) (b j)) i := by
+ rw [matrixEntry, S.coordinate_eq_repr F h b hb _ (S.target_degree F h op (S.basisIndex j)) i,
+ S.targetPolynomial, hb]
+ cases op <;> simp [Operation.apply, listing, quotientMap, coordinateLabel]
+
+/-- Lemma 8.2's basis, dimension and coordinate values for the indexed finite
+slice. The query functions take the scalar coefficient algorithm as input. -/
+theorem finite_slice_coordinate_queries (h : S.Presents F) (hn : (points F E).Nonempty)
+ (hfin : (points F E).Finite) (hN : (points F E).ncard ≤ S.pointBound) :
+ ∃ b : Module.Basis (Fin S.dimension) K (CoordinateAlgebra K (points F E)),
+ (∀ i, b i = S.listing F E (S.basisIndex i)) ∧ (∃ u, u.val = 0 ∧ b u = 1) ∧
+ S.dimension = Module.finrank K (CoordinateAlgebra K (points F E)) ∧
+ ∀ op i j, S.matrixEntry op i j =
+ b.repr (op.apply S.fieldOrder (coordinateLabel (points F E)) (b j)) i := by
+ obtain ⟨b, hb, hu⟩ := S.exists_basis F h hn hfin hN
+ exact ⟨b, hb, hu, S.dimension_eq F h hn hfin hN, S.matrixEntry_eq_repr F h b hb⟩
+
+end QueryData
+
+end RadicalCertificate.MonomialIndex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MacaulayTargetBudgets.lean b/lean/OAI/Computability/VPVNP/MacaulayTargetBudgets.lean
new file mode 100644
index 0000000000..e5c34b7b1c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MacaulayTargetBudgets.lean
@@ -0,0 +1,53 @@
+import OAI.Computability.VPVNP.MacaulayLeafBudgets
+import OAI.Computability.VPVNP.RankCoordinateTargetRead
+
+/-! # The staged target reader uses the common raw matrix-reader budgets -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.ReaderPlan
+
+open RankQuery.Stack Coordinate
+
+variable {F : Type*}
+
+/-- Both the prepared target row and the original matrix fit the same
+clock and space caps, including the target's native flag-selected copy. -/
+theorem target_bounds {P : ReaderPlan} {S : QueryData P.arity (P.equations+P.pins) F}
+ (h : P.Covers S) (op : QueryData.Operation P.arity) (d : PairCall.Inputs)
+ (ht : d.arity=P.arity) (hL : d.degree false=S.pointBound) (hD : d.degree true=S.columnDegree)
+ (hs : d.scale=PairCall.targetScale S op) (hm : d.mark=PairCall.targetMark op)
+ {E V e v w : ℕ} (he : e≤E) (hv : v≤V) (hw : P.wordWidth≤w) (signedSpace signedExp : ℕ) :
+ let b := P.live E V w signedSpace
+ PairCall.requiredWidth d ≤ w ∧ w ≤ b ∧ d.arity ≤ b ∧ max b (e*v) ≤ b ∧
+ TargetRead.clock w b e v d ≤ P.readTime E V w signedSpace signedExp ∧
+ TargetRead.space w b e v ≤ P.armSpace E V w signedSpace := by
+ intro b
+ have hl : d.degree false ≤ P.source := hL ▸ h.points_le.trans (le_max_left ..)
+ have hd : d.degree true ≤ P.column := hD ▸ h.degrees.2.2
+ have hfit := P.pairWidth_le d ht hl hd (hs ▸ (h.targetParams op).1) (hm ▸ (h.targetParams op).2)
+ have hab := P.leaf_bounds w signedSpace signedExp he hv d ht hl hd
+ have hword := hab.1.1
+ have har := hab.1.2.1
+ have hscalar : e*v ≤ b := hab.1.2.2.2.1
+ have hscan := (P.scan_bounds w b d ht hl hd).2.1
+ have hwork := (P.scan_bounds w b d ht hl hd).2.2.2
+ have hbank : w ≤ b := hword
+ have hbase : d.arity ≤ b := ht ▸ har
+ refine ⟨hfit.trans hw,hbank,hbase,max_le le_rfl hscalar,?_,?_⟩
+ · have copyBound : 5*(e*v)+2 ≤ max (5*b+2) (P.scalarTime E V w signedExp) :=
+ (Nat.add_le_add_right (Nat.mul_le_mul_left 5 hscalar) 2).trans (le_max_left ..)
+ change _ ≤ MacaulayRowDispatch.ticks w + (4 + (P.scanTime w b + MacaulayRead.Arms.postTicks b P.arity w _))
+ unfold TargetRead.clock MacaulayRead.Arms.postTicks
+ omega
+ · change _ ≤ P.scanSpace w b + MacaulayRead.Arms.transient b P.arity w + _
+ unfold TargetRead.space MacaulayRead.Arms.transient
+ omega
+
+end RadicalCertificate.MonomialIndex.ReaderPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MarkedEndpointOperation.lean b/lean/OAI/Computability/VPVNP/MarkedEndpointOperation.lean
new file mode 100644
index 0000000000..981af0201e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MarkedEndpointOperation.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.TwoMarkedSplit
+
+/-!
+# Acting at a single endpoint of a marked tensor
+
+Appendix A.3 places both exterior operators at the same endpoint of the first
+marked leg. One wire supplies the exterior index held by the other endpoint.
+The second marked leg and all background indices pass through unchanged.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+
+namespace WireTensor
+
+open scoped Classical
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J]
+
+private def markedPairEquiv (B : J → Type) (I K : Type) (p y : J) :
+ ((∀ j, B j) × I × K) ≃ ((j : J) → B j × (j = p → I) × (j = y → K)) where
+ toFun v j := (v.1 j, fun _ ↦ v.2.1, fun _ ↦ v.2.2)
+ invFun z := (fun j ↦ (z j).1, (z p).2.1 rfl, (z y).2.2 rfl)
+ left_inv _ := rfl
+ right_inv z := by
+ funext j
+ refine Prod.ext rfl (Prod.ext ?_ ?_)
+ all_goals funext h; subst j; rfl
+
+private def wirePairEquiv (H : Type) (s p : J) :
+ (H × H) ≃ ((j : J) → (j = s → H) × (j = p → H)) where
+ toFun v _ := (fun _ ↦ v.1, fun _ ↦ v.2)
+ invFun z := ((z s).1 rfl, (z p).2 rfl)
+ left_inv _ := rfl
+ right_inv z := by
+ funext j
+ apply Prod.ext <;> funext h <;> subst j <;> rfl
+
+namespace TwoMarkedNode
+
+variable {I K H : Type} [Fintype I] [Fintype K] [Fintype H]
+ (W : TwoMarkedNode k J I K) (op : H → H → I → I → k)
+
+/-- Apply the matrix to the old marked leg at the row endpoint, using a wire to
+supply the column index. Coincident endpoints are allowed. -/
+theorem child_same_right_restriction (s p y : J) :
+ Restricts (tensorProduct (W.place p y) (WireTensor.wire s p H))
+ ((W.child s p op).place p y) := by
+ let P := W.place p y
+ let U := tensorProduct P (WireTensor.wire s p H)
+ let V := (W.child s p op).place p y
+ let L (j : J) (o : V.Basis j) (z : U.Basis j) : k :=
+ (if o.1.1 = z.1.1 ∧ o.2.2 = z.1.2.2 ∧ o.1.2.1 = z.2.1 then 1 else 0) *
+ (if h : j = p then op (o.1.2.2 h) (z.2.2 h) (o.2.1 h) (z.1.2.1 h) else 1)
+ refine ⟨L, ?_⟩
+ funext o
+ let e : (((∀ j, W.Basis j) × I × K) × (H × H)) ≃ ((j : J) → U.Basis j) :=
+ ((markedPairEquiv W.Basis I K p y).prodCongr (wirePairEquiv H s p)).trans
+ (Equiv.arrowProdEquivProdArrow J P.Basis (WireTensor.wire (k := k) s p H).Basis).symm
+ let f (z : (j : J) → U.Basis j) := (∏ j, L j (o j) (z j)) * U.coeff z
+ let bg (j : J) := (o j).1.1
+ let idx := (o p).2.1 rfl
+ let second := (o y).2.2 rfl
+ let col := (o s).1.2.1 rfl
+ let row := (o p).1.2.2 rfl
+ have eval (b : ∀ j, W.Basis j) (old : I) (v : K) (r t : H) :
+ f (e ((b,old,v),(r,t))) =
+ (if bg = b ∧ second = v ∧ col = r then 1 else 0) *
+ op row t idx old * (W.coeff b old v * (if r = t then 1 else 0)) := by
+ change (∏ j, (if (o j).1.1 = b j ∧ (o j).2.2 = (fun _ ↦ v) ∧ (o j).1.2.1 = (fun _ ↦ r)
+ then (1 : k) else 0) *
+ (if h : j = p then op ((o j).1.2.2 h) t ((o j).2.1 h) old else 1)) *
+ (W.coeff b old v * (if r = t then 1 else 0)) = _
+ rw [Finset.prod_mul_distrib, Fintype.prod_boole]
+ have hp : (∀ j, (o j).1.1 = b j ∧ (o j).2.2 = (fun _ ↦ v) ∧ (o j).1.2.1 = (fun _ ↦ r)) ↔
+ bg = b ∧ second = v ∧ col = r := by
+ constructor
+ · intro h
+ exact ⟨funext (fun j ↦ (h j).1), congrFun (h y).2.1 rfl, congrFun (h s).2.2 rfl⟩
+ · rintro ⟨rfl,rfl,rfl⟩ j
+ refine ⟨rfl, ?_, ?_⟩
+ all_goals funext h; subst j; rfl
+ simp only [hp]
+ rw [Fintype.prod_dite_eq']
+ change (∑ z, f z) = V.coeff o
+ rw [← e.sum_comp f]
+ simp_rw [Fintype.sum_prod_type, eval]
+ simp [ite_mul, mul_ite, ite_and, V, place, twoMarked, child, bg, col, row, idx, second,
+ mul_comm]
+
+/-- At the column endpoint, swap the two exterior legs before applying the matrix. -/
+theorem child_same_left_restriction (s p y : J) :
+ Restricts (tensorProduct (W.place s y) (WireTensor.wire s p H))
+ ((W.child s p op).place s y) := by
+ have h := W.child_same_right_restriction (fun α β ↦ op β α) p s y
+ refine ((Restricts.refl _).tensorProduct (wire_swap s p H).1).trans (h.trans ?_)
+ let P := (W.child p s (fun α β ↦ op β α)).place s y
+ let V := (W.child s p op).place s y
+ let e (j : J) : V.Basis j ≃ P.Basis j :=
+ { toFun z := ((z.1.1, z.1.2.2, z.1.2.1), z.2)
+ invFun z := ((z.1.1, z.1.2.2, z.1.2.1), z.2)
+ left_inv _ := rfl
+ right_inv _ := rfl }
+ exact (restricts_of_reindex (T := P) (U := V) e (fun _ ↦ rfl)).1
+
+/-- Both operators can act at either endpoint. The single exterior wire costs
+its dimension raised to the distance between the two fixed endpoints. -/
+theorem value_child_same_le (F : SpectralPoint k J) (s p x y : J) (hx : x = s ∨ x = p)
+ (hH : 0 < Fintype.card H) :
+ (F.value ((W.child s p op).place x y) : ℝ) ≤
+ (F.value (W.place x y) : ℝ) * (Fintype.card H : ℝ) ^ F.wireDistance s p := by
+ have h : Restricts (tensorProduct (W.place x y) (WireTensor.wire s p H))
+ ((W.child s p op).place x y) := by
+ rcases hx with rfl | rfl
+ · exact W.child_same_left_restriction op _ _ _
+ · exact W.child_same_right_restriction op _ _ _
+ have hb := NNReal.coe_le_coe.mpr (F.monotone h)
+ rwa [F.value_tensorProduct, NNReal.coe_mul, F.value_wire_equiv _ _ (Fintype.equivFin H),
+ F.value_wire_eq_rpow _ _ hH] at hb
+
+end TwoMarkedNode
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MarkedExteriorBound.lean b/lean/OAI/Computability/VPVNP/MarkedExteriorBound.lean
new file mode 100644
index 0000000000..e24bfdf4b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MarkedExteriorBound.lean
@@ -0,0 +1,67 @@
+import OAI.Computability.VPVNP.ExteriorLevels
+import OAI.Computability.VPVNP.MarkedSplitBound
+
+/-! # Finite exterior bound for a marked tensor
+
+In Appendix A.2 the degree-`h` exterior identity gives two orders of the
+creation and contraction operators. Placing the old marked index at opposite
+endpoints bounds the two orders by wire costs through degrees `h+1` and `h-1`.
+The matrices are the same integral matrices over every field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor.SpectralPoint
+
+open ExteriorLevels Lemmata.FockCircuits
+
+/-- The finite, unpowered inequality underlying the relocation estimate in
+Lemma A.1. The parties `x`, `a`, and `b` may coincide. -/
+theorem value_marked_exterior_bound {k J : Type*} [Field k] [Fintype J]
+ (F : SpectralPoint k J) (B : J → Type) [∀ j, Fintype (B j)] {Q h : ℕ}
+ (hh : 1 ≤ h) (hQ : h < Q) (x a b : J) (T : ((j : J) → B j) → Fin Q → k) :
+ (F.value (marked B (Fin Q) x T) : ℝ) * (Q.choose h : ℝ) ^ F.wireDistance a b ≤
+ F.value (marked B (Fin Q) b T) * (Q.choose h : ℝ) ^ F.wireDistance a x *
+ (Q.choose (h + 1) : ℝ) ^ F.wireDistance x b +
+ F.value (marked B (Fin Q) a T) * (Q.choose (h - 1) : ℝ) ^ F.wireDistance a x *
+ (Q.choose h : ℝ) ^ F.wireDistance x b := by
+ classical
+ have : Nonempty (Fin Q) := ⟨⟨0, by omega⟩⟩
+ have level_nonempty (r : ℕ) (hr : r ≤ Q) : Nonempty (Level Q r) :=
+ Fintype.card_pos_iff.mp (by simpa only [card_level] using Nat.choose_pos hr)
+ have : Nonempty (Level Q h) := level_nonempty h hQ.le
+ have : Nonempty (Level Q (h + 1)) := level_nonempty _ hQ
+ have : Nonempty (Level Q (h - 1)) := level_nonempty _ (by omega)
+ let createUp (i : Fin Q) (α : Level Q h) (z : Level Q (h + 1)) : k :=
+ entry ℤ (Fock.create ℤ i) z α
+ let contractDown (j : Fin Q) (β : Level Q h) (z : Level Q (h + 1)) : k :=
+ entry ℤ (Fock.contract ℤ j) β z
+ let contractLow (j : Fin Q) (α : Level Q h) (z : Level Q (h - 1)) : k :=
+ entry ℤ (Fock.contract ℤ j) z α
+ let createBack (i : Fin Q) (β : Level Q h) (z : Level Q (h - 1)) : k :=
+ entry ℤ (Fock.create ℤ i) β z
+ let P i j β α := ∑ z, createUp i α z * contractDown j β z
+ let M i j β α := ∑ z, contractLow j α z * createBack i β z
+ have hcar (i j : Fin Q) (β α : Level Q h) : P i j β α + M i j β α =
+ if i = j ∧ β = α then 1 else 0 := by
+ simpa only [P, M, createUp, contractDown, contractLow, createBack, mul_comm] using
+ int_matrix_car k i j β α
+ have hsplit := NNReal.coe_le_coe.mpr
+ (value_marked_wire_le_split F B (Fin Q) (Level Q h) x a b T P M (fun i j β α ↦ by
+ by_cases he : i = j ∧ β = α <;> simpa only [he, ite_true, ite_false] using hcar i j β α))
+ rw [NNReal.coe_mul, NNReal.coe_add, F.value_wire_equiv a b (Fintype.equivFin (Level Q h)),
+ F.value_wire_eq_rpow a b Fintype.card_pos, card_level] at hsplit
+ have hp := F.value_splitMarkedTerm_le_plus B (Fin Q) (Level Q h) (Level Q (h + 1))
+ x a b b T P createUp contractDown (fun _ _ _ _ ↦ rfl)
+ have hm := F.value_splitMarkedTerm_le_minus B (Fin Q) (Level Q h) (Level Q (h - 1))
+ x a b a T M contractLow createBack (fun _ _ _ _ ↦ rfl)
+ simpa only [card_level, F.wireDistance_self, F.wireDistance_comm b x, Real.rpow_zero,
+ one_mul, mul_one, mul_assoc, mul_left_comm, mul_comm] using hsplit.trans (add_le_add hp hm)
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MarkedMove.lean b/lean/OAI/Computability/VPVNP/MarkedMove.lean
new file mode 100644
index 0000000000..f0f4958433
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MarkedMove.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.MarkedTensor
+
+/-!
+# Moving one marked tensor index along an identity wire
+
+Appendix A.2 of *VP and VNP differ over every field* bounds the cost of moving
+an index of dimension `q` by `q ^ d(a,b)`. The local maps copy the background
+indices, pass the wire endpoint at the destination to the output, and pair the
+other endpoint with the marked index at its original party. These operations
+also apply when both endpoints are at the same party.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+universe u v w
+
+variable {k : Type u} {J : Type v} [Fintype J]
+
+/-- An identity wire supplies a local restriction moving the marked index
+from `b` to `a`, over any commutative semiring. -/
+theorem marked_restricts_move [CommSemiring k] (B : J → Type*) [∀ j, Fintype (B j)]
+ (I : Type*) [Fintype I] (a b : J) (T : ((j : J) → B j) → I → k) :
+ Restricts (tensorProduct (marked B I b T) (wire a b I)) (marked B I a T) := by
+ classical
+ let L (j : J) (out : B j × (j = a → I))
+ (p : (B j × (j = b → I)) × ((j = a → I) × (j = b → I))) : k :=
+ if out.1 = p.1.1 ∧ (∀ h, out.2 h = p.2.1 h) ∧ (∀ h, p.1.2 h = p.2.2 h) then 1 else 0
+ refine ⟨L, ?_⟩
+ funext out
+ let i := (out a).2 rfl
+ let lift (j : J) : (B j × (j = b → I)) × ((j = a → I) × (j = b → I)) :=
+ (((out j).1, fun _ ↦ i), (fun _ ↦ i, fun _ ↦ i))
+ simp only [applyLocal, tensorProduct, marked, wire, L, Fintype.prod_boole]
+ rw [Finset.sum_eq_single lift]
+ · have h : ∀ j : J, (out j).1 = (lift j).1.1 ∧
+ (∀ h : j = a, (out j).2 h = (lift j).2.1 h) ∧
+ (∀ h : j = b, (lift j).1.2 h = (lift j).2.2 h) :=
+ fun _ ↦ ⟨rfl, by rintro rfl; rfl, fun _ ↦ rfl⟩
+ rw [ite_eq_left h, ite_eq_left (show (lift a).2.1 rfl = (lift b).2.2 rfl from rfl), mul_one, one_mul]
+ · intro x _ hx
+ split_ifs with hloc hw
+ · exfalso
+ apply hx
+ have ha : (x a).2.1 rfl = i := ((hloc a).2.1 rfl).symm
+ have hb : (x b).2.2 rfl = i := hw.symm.trans ha
+ funext j
+ refine Prod.ext (Prod.ext ((hloc j).1.symm) ?_) (Prod.ext ?_ ?_)
+ · funext h
+ subst j
+ exact ((hloc b).2.2 rfl).trans hb
+ · funext h
+ subst j
+ exact ha
+ · funext h
+ subst j
+ exact hb
+ all_goals simp
+ · exact fun h ↦ (h (Finset.mem_univ _)).elim
+
+namespace SpectralPoint
+
+variable [Field k] (F : SpectralPoint k J)
+variable (B : J → Type) [∀ j, Fintype (B j)] (I : Type) [Fintype I]
+variable (a b : J) (T : ((j : J) → B j) → I → k)
+
+/-- The wire's spectral value bounds the factor required to move a marked index. -/
+theorem value_marked_le_wire_mul :
+ F.value (marked B I a T) ≤ F.value (wire a b I) * F.value (marked B I b T) := by
+ simpa only [F.value_tensorProduct, mul_comm] using F.monotone (marked_restricts_move B I a b T)
+
+/-- The elementary index-moving bound of Appendix A.2. -/
+theorem value_marked_move_le [Nonempty I] :
+ (F.value (marked B I a T) : ℝ) ≤ (Fintype.card I : ℝ) ^ F.wireDistance a b *
+ (F.value (marked B I b T) : ℝ) := by
+ have h := NNReal.coe_le_coe.mpr (F.value_marked_le_wire_mul B I a b T)
+ rw [NNReal.coe_mul, F.value_wire_equiv a b (Fintype.equivFin I),
+ F.value_wire_eq_rpow a b Fintype.card_pos] at h
+ exact h
+
+/-- Vanishing of the marked tensor's spectral value is independent of the placement. -/
+theorem value_marked_eq_zero_iff :
+ F.value (marked B I a T) = 0 ↔ F.value (marked B I b T) = 0 := by
+ constructor
+ · intro h
+ have H := F.value_marked_le_wire_mul B I b a T
+ simpa [h] using H
+ · intro h
+ have H := F.value_marked_le_wire_mul B I a b T
+ simpa [h] using H
+
+/-- Moving a marked index between parties at zero wire distance preserves its value. -/
+theorem value_marked_eq_of_dist_zero (hab : F.wireDistance a b = 0) :
+ F.value (marked B I a T) = F.value (marked B I b T) := by
+ rcases isEmpty_or_nonempty I with hI | hI
+ · have hz (j : J) : F.value (marked B I j T) = 0 :=
+ F.value_zero _ (funext fun x ↦ isEmptyElim ((x j).2 rfl))
+ rw [hz, hz]
+ · have h₁ := F.value_marked_move_le B I a b T
+ have h₂ := F.value_marked_move_le B I b a T
+ rw [F.wireDistance_comm b a, hab, Real.rpow_zero, one_mul] at h₂
+ rw [hab, Real.rpow_zero, one_mul] at h₁
+ exact NNReal.coe_injective (le_antisymm h₁ h₂)
+
+/-- The placement of a one-dimensional marked index has no effect on its value. -/
+theorem value_marked_eq_of_card_one (hI : Fintype.card I = 1) :
+ F.value (marked B I a T) = F.value (marked B I b T) := by
+ have : Nonempty I := Fintype.card_pos_iff.mp (hI ▸ Nat.one_pos)
+ have h₁ := F.value_marked_move_le B I a b T
+ have h₂ := F.value_marked_move_le B I b a T
+ simp only [hI, Nat.cast_one, Real.one_rpow, one_mul] at h₁ h₂
+ exact NNReal.coe_injective (le_antisymm h₁ h₂)
+
+end SpectralPoint
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MarkedPowers.lean b/lean/OAI/Computability/VPVNP/MarkedPowers.lean
new file mode 100644
index 0000000000..12a00a1cfa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MarkedPowers.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.MarkedTensor
+import OAI.Computability.VPVNP.ExteriorLevelRates
+
+/-!
+# Tensor powers of a marked index
+
+In the proof of Lemma A.1, the same tensor power is placed at three different
+parties. Regrouping the marked indices of its copies gives a single index of
+dimension `q ^ n`, with the same coefficient table at each placement. The
+rounded exterior levels then bound both terms of the split by the same geometric
+mean to the power `n`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+universe u v
+variable {k : Type u} {J : Type v}
+
+/-- The product of `n` copies of the coefficient table, with their marked indices
+grouped separately from the background coordinates. -/
+def markedPowerTable [CommMonoid k] {B : J → Type} {I : Type} (n : ℕ)
+ (T : ((j : J) → B j) → I → k) (b : (j : J) → Fin n → B j) (i : Fin n → I) : k :=
+ ∏ t, T (fun j ↦ b j t) (i t)
+
+
+/-- Moving a marked index preserves whether the coefficient array is zero. -/
+theorem marked_coeff_eq_zero_iff [Zero k] (B : J → Type) [∀ j, Fintype (B j)]
+ (I : Type) [Fintype I] (a : J) (T : ((j : J) → B j) → I → k) :
+ (marked B I a T).coeff = 0 ↔ T = 0 := by
+ constructor
+ · intro h
+ funext b i
+ exact congrFun h (fun j ↦ (b j, fun _ ↦ i))
+ · rintro rfl
+ rfl
+
+variable [Field k] [Fintype J]
+
+/-- The regrouped marked array and the product of the original tensors have
+mutually invertible local changes of basis, including for the zeroth power. -/
+theorem marked_power_mutual (B : J → Type) [∀ j, Fintype (B j)] (I : Type) [Fintype I]
+ (a : J) (T : ((j : J) → B j) → I → k) (n : ℕ) :
+ let P := marked (fun j ↦ Fin n → B j) (Fin n → I) a (markedPowerTable n T)
+ let U := tensorFamilyProduct (fun _ : Fin n ↦ marked B I a T)
+ Restricts P U ∧ Restricts U P := by
+ let e (j : J) : (Fin n → B j × (j = a → I)) ≃ (Fin n → B j) × (j = a → Fin n → I) :=
+ { toFun := fun x ↦ (fun t ↦ (x t).1, fun h t ↦ (x t).2 h)
+ invFun := fun x t ↦ (x.1 t, fun h ↦ x.2 h t)
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+/-- Spectral values of the regrouped marked table are the powers of the values
+at the original placement. -/
+theorem SpectralPoint.value_markedPower (F : SpectralPoint k J) (B : J → Type)
+ [∀ j, Fintype (B j)] (I : Type) [Fintype I] (a : J) (T : ((j : J) → B j) → I → k)
+ (n : ℕ) :
+ F.value (marked (fun j ↦ Fin n → B j) (Fin n → I) a (markedPowerTable n T)) =
+ F.value (marked B I a T) ^ n := by
+ rw [F.value_eq_of_mutual (marked_power_mutual B I a T n), F.value_tensorFamilyProduct]
+ simp
+
+/-- Relabeling the marked index preserves the tensor up to invertible local
+changes of basis. The background coordinates are arbitrary. -/
+theorem marked_reindex_mutual (B : J → Type) [∀ j, Fintype (B j)] {I K : Type}
+ [Fintype I] [Fintype K] (e : I ≃ K) (a : J) (T : ((j : J) → B j) → I → k) :
+ Restricts (marked B I a T) (marked B K a (fun b i ↦ T b (e.symm i))) ∧
+ Restricts (marked B K a (fun b i ↦ T b (e.symm i))) (marked B I a T) := by
+ let f (j : J) : (B j × (j = a → K)) ≃ (B j × (j = a → I)) :=
+ { toFun := fun x ↦ (x.1, fun h ↦ e.symm (x.2 h))
+ invFun := fun x ↦ (x.1, fun h ↦ e (x.2 h))
+ left_inv := fun x ↦ by simp
+ right_inv := fun x ↦ by simp }
+ exact restricts_of_reindex f (fun _ ↦ rfl)
+
+/-- The index set used for the exterior operators on the powered tensor. -/
+noncomputable def markedPowerIndex (I : Type) [Fintype I] (n : ℕ) :
+ (Fin n → I) ≃ Fin (Fintype.card I ^ n) :=
+ Fintype.equivFinOfCardEq (by simp)
+
+/-- The coefficient table with the marked tuples numbered from zero to `q ^ n - 1`
+has the original spectral value to the `n`th power at every placement. -/
+theorem SpectralPoint.value_markedPower_fin (F : SpectralPoint k J) (B : J → Type)
+ [∀ j, Fintype (B j)] (I : Type) [Fintype I] (a : J) (T : ((j : J) → B j) → I → k)
+ (n : ℕ) :
+ F.value (marked (fun j ↦ Fin n → B j) (Fin (Fintype.card I ^ n)) a
+ (fun b i ↦ markedPowerTable n T b ((markedPowerIndex I n).symm i))) =
+ F.value (marked B I a T) ^ n := by
+ rw [← F.value_eq_of_mutual (marked_reindex_mutual _ (markedPowerIndex I n) a (markedPowerTable n T))]
+ exact F.value_markedPower B I a T n
+
+open VPVNP.ExteriorLevelRates
+
+/-- Moving the index in both directions puts the balancing exponent in the
+interval of exponents attainable by exterior powers. -/
+theorem relocation_log_bounds {q : ℕ} {y z t : ℝ} (hq : 2 ≤ q)
+ (hy : 0 < y) (hz : 0 < z) (ht : 0 < t)
+ (hzy : z ≤ (q : ℝ) ^ t * y) (hyz : y ≤ (q : ℝ) ^ t * z) :
+ -1 ≤ Real.logb q (z / y) / t ∧ Real.logb q (z / y) / t ≤ 1 := by
+ have hq' : (1 : ℝ) < q := by exact_mod_cast (show 1 < q from hq)
+ have upper := (Real.logb_le_iff_le_rpow hq' (div_pos hz hy)).2 ((div_le_iff₀ hy).2 hzy)
+ have lower := (Real.logb_le_iff_le_rpow hq' (div_pos hy hz)).2 ((div_le_iff₀ hz).2 hyz)
+ rw [Real.logb_div hz.ne' hy.ne'] at upper ⊢
+ rw [Real.logb_div hy.ne' hz.ne'] at lower
+ exact ⟨(le_div_iff₀ ht).2 (by linarith), (div_le_iff₀ ht).2 (by linarith)⟩
+
+/-- Compare a contribution from one endpoint to the target using its
+logarithmic dimension bound. -/
+private theorem exterior_term_le {q a d w e m : ℝ} {n : ℕ}
+ (hq : 1 < q) (ha : 0 < a) (hd : 0 < d) (hw : 0 < w) (he : 0 ≤ e)
+ (hlog : Real.logb q d ≤ m * n)
+ (hbal : Real.logb q a + e * m = Real.logb q w) :
+ a ^ n * d ^ e ≤ w ^ n := by
+ by_contra! h
+ have hstrict := (Real.logb_lt_logb_iff hq (pow_pos hw n)
+ (mul_pos (pow_pos ha n) (Real.rpow_pos_of_pos hd _))).2 h
+ rw [Real.logb_mul (pow_ne_zero _ ha.ne') (Real.rpow_pos_of_pos hd _).ne',
+ Real.logb_pow, Real.logb_pow, Real.logb_rpow_eq_mul_logb_of_pos hd, ← hbal] at hstrict
+ nlinarith only [hstrict, mul_le_mul_of_nonneg_left hlog he]
+
+/-- The positive powers and the two adjacent binomial ratios imply the
+geometric interpolation inequality for the marked tensor. -/
+theorem relocation_of_power_bounds {q : ℕ} {x y z u t : ℝ} (hq : 2 ≤ q)
+ (hy : 0 < y) (hz : 0 < z) (ht : 0 < t) (hu₀ : 0 ≤ u) (hu₁ : u ≤ 1)
+ (hs₀ : -1 ≤ Real.logb q (z / y) / t) (hs₁ : Real.logb q (z / y) / t ≤ 1)
+ (hpow : ∀ n : ℕ, 1 ≤ n → ∀ b : ℕ, 1 ≤ b → b < q ^ n →
+ x ^ n ≤ y ^ n * (((q ^ n).choose (b + 1) : ℝ) / (q ^ n).choose b) ^ ((1 - u) * t) +
+ z ^ n * (((q ^ n).choose (b - 1) : ℝ) / (q ^ n).choose b) ^ (u * t)) :
+ x ≤ z ^ (1 - u) * y ^ u := by
+ let w := z ^ (1 - u) * y ^ u
+ let s := Real.logb q (z / y) / t
+ have hw : 0 < w := mul_pos (Real.rpow_pos_of_pos hz _) (Real.rpow_pos_of_pos hy _)
+ have hq' : (1 : ℝ) < q := by exact_mod_cast (show 1 < q from hq)
+ have hst : t * s = Real.logb q z - Real.logb q y := by
+ dsimp [s]
+ rw [Real.logb_div hz.ne' hy.ne']
+ field_simp
+ have hwlog : Real.logb q w = (1 - u) * Real.logb q z + u * Real.logb q y := by
+ dsimp [w]
+ rw [Real.logb_mul (Real.rpow_pos_of_pos hz _).ne' (Real.rpow_pos_of_pos hy _).ne',
+ Real.logb_rpow_eq_mul_logb_of_pos hz, Real.logb_rpow_eq_mul_logb_of_pos hy]
+ by_contra! hx
+ obtain ⟨n, hn', hn⟩ := ((Filter.eventually_ge_atTop (1 : ℕ)).and
+ ((tendsto_pow_atTop_atTop_of_one_lt ((one_lt_div hw).2 hx)).eventually_gt_atTop 2)).exists
+ change 2 < (x / w) ^ n at hn
+ let b := powerLevel q s n
+ obtain ⟨hb, hbQ, ⟨_, hup⟩, ⟨_, hdown⟩⟩ := powerLevel_log_bounds hq hn' hs₀ hs₁
+ obtain ⟨hbpos, huppos, hdownpos⟩ := choose_adjacent_pos hb hbQ
+ have hden : (0 : ℝ) < (q ^ n).choose b := by exact_mod_cast hbpos
+ have hup_pos : (0 : ℝ) < (q ^ n).choose (b + 1) := by exact_mod_cast huppos
+ have hdown_pos : (0 : ℝ) < (q ^ n).choose (b - 1) := by exact_mod_cast hdownpos
+ have hup_term := exterior_term_le hq' hy (div_pos hup_pos hden) hw
+ (mul_nonneg (sub_nonneg.mpr hu₁) ht.le) hup (by rw [hwlog]; nlinarith [congrArg (· * u) hst])
+ have hdown_term := exterior_term_le hq' hz (div_pos hdown_pos hden) hw
+ (mul_nonneg hu₀ ht.le) hdown (by rw [hwlog]; nlinarith [congrArg (· * u) hst])
+ rw [div_pow, lt_div_iff₀ (pow_pos hw n)] at hn
+ linarith only [hn, hpow n hn' b hb hbQ, hup_term, hdown_term]
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MarkedRelocation.lean b/lean/OAI/Computability/VPVNP/MarkedRelocation.lean
new file mode 100644
index 0000000000..e82fa42375
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MarkedRelocation.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.MarkedExteriorBound
+import OAI.Computability.VPVNP.MarkedPowers
+import OAI.Computability.VPVNP.MarkedMove
+import OAI.Computability.VPVNP.WireGeodesic
+
+/-!
+# Relocation of one marked tensor index
+
+In Lemma A.1 of *VP and VNP differ over every field*, exterior multiplication
+and contraction on the marked index split its product with a wire. Dividing
+by the wire value leaves two ratios of adjacent exterior dimensions. Their
+bounds over tensor powers yield geometric interpolation of the endpoint
+values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor.SpectralPoint
+
+open WireGeometry
+open scoped NNReal
+
+universe u v
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J]
+
+private theorem divide_exterior_wire {x y z h p m u t : ℝ} (hh : 0 < h)
+ (hp : 0 ≤ p) (hm : 0 ≤ m)
+ (bound : x * h ^ t ≤ y * h ^ (u * t) * p ^ ((1 - u) * t) +
+ z * m ^ (u * t) * h ^ ((1 - u) * t)) :
+ x ≤ y * (p / h) ^ ((1 - u) * t) + z * (m / h) ^ (u * t) := by
+ apply (mul_le_mul_iff_left₀ (Real.rpow_pos_of_pos hh t)).mp
+ calc
+ x * h ^ t ≤ _ := bound
+ _ = (y * (p / h) ^ ((1 - u) * t) + z * (m / h) ^ (u * t)) * h ^ t := by
+ rw [show h ^ t = h ^ (u * t) * h ^ ((1 - u) * t) by rw [← Real.rpow_add hh]; congr 1; ring]
+ rw [Real.div_rpow hp hh.le, Real.div_rpow hm hh.le]
+ field_simp
+
+private theorem geometric_bound_of_equal_values {x y z u : ℝ} (hx : 0 < x)
+ (hy : x = y) (hz : x = z) : x ≤ y ^ (1 - u) * z ^ u := by
+ rw [← hy, ← hz, ← Real.rpow_add hx, sub_add_cancel, Real.rpow_one]
+
+/-- Lemma A.1. Placing a marked tensor index at a fractional point gives a
+spectral value bounded by the weighted geometric mean of the endpoint
+placements. The bound also holds for zero coefficient arrays. -/
+theorem value_marked_atFraction_le (F : SpectralPoint k J) (B : J → Type)
+ [∀ j, Fintype (B j)] (I : Type) [Fintype I] (a b c : J)
+ (T : ((j : J) → B j) → I → k) {u : ℝ} (hu₀ : 0 ≤ u) (hu₁ : u ≤ 1)
+ (hfrac : @AtFraction J F.wirePseudoMetric a b u c) :
+ (F.value (marked B I c T) : ℝ) ≤
+ (F.value (marked B I a T) : ℝ) ^ (1 - u) * (F.value (marked B I b T) : ℝ) ^ u := by
+ classical
+ let v (j : J) : ℝ := F.value (marked B I j T)
+ change v c ≤ v a ^ (1 - u) * v b ^ u
+ have hnonneg (j : J) : 0 ≤ v j := (F.value _).coe_nonneg
+ by_cases hz : F.value (marked B I c T) = 0
+ · have hc : v c = 0 := congrArg (fun x : ℝ≥0 ↦ (x : ℝ)) hz
+ rw [hc]
+ exact mul_nonneg (Real.rpow_nonneg (hnonneg a) _) (Real.rpow_nonneg (hnonneg b) _)
+ have hpos (j : J) : 0 < v j := by
+ apply lt_of_le_of_ne (hnonneg j)
+ intro h
+ exact hz ((F.value_marked_eq_zero_iff B I j c T).mp (NNReal.eq h.symm))
+ have hI : Nonempty I := by
+ rcases isEmpty_or_nonempty I with h | h
+ · exact False.elim <| hz <| F.value_zero _ (funext fun x ↦ isEmptyElim ((x c).2 rfl))
+ · exact h
+ have hIpos := Fintype.card_pos (α := I)
+ obtain ⟨hac, hcb⟩ := hfrac
+ change F.wireDistance a c = u * F.wireDistance a b at hac
+ change F.wireDistance c b = (1 - u) * F.wireDistance a b at hcb
+ by_cases ht : F.wireDistance a b = 0
+ · rw [ht, mul_zero] at hac hcb
+ exact geometric_bound_of_equal_values (hpos c)
+ (congrArg (fun x : ℝ≥0 ↦ (x : ℝ)) (F.value_marked_eq_of_dist_zero B I a c T hac).symm)
+ (congrArg (fun x : ℝ≥0 ↦ (x : ℝ)) (F.value_marked_eq_of_dist_zero B I c b T hcb))
+ by_cases hOne : Fintype.card I = 1
+ · exact geometric_bound_of_equal_values (hpos c)
+ (congrArg (fun x : ℝ≥0 ↦ (x : ℝ)) (F.value_marked_eq_of_card_one B I c a T hOne))
+ (congrArg (fun x : ℝ≥0 ↦ (x : ℝ)) (F.value_marked_eq_of_card_one B I c b T hOne))
+ have ht' : 0 < F.wireDistance a b := lt_of_le_of_ne (F.wireDistance_nonneg _ _) (Ne.symm ht)
+ have hq : 2 ≤ Fintype.card I := by omega
+ obtain ⟨hs₀, hs₁⟩ := relocation_log_bounds hq (hpos b) (hpos a) ht'
+ (F.value_marked_move_le B I a b T) (by
+ rw [F.wireDistance_comm a b]
+ exact F.value_marked_move_le B I b a T)
+ apply relocation_of_power_bounds hq (hpos b) (hpos a) ht' hu₀ hu₁ hs₀ hs₁
+ intro n _ h hh hQ
+ let Bn (j : J) := Fin n → B j
+ let Q := Fintype.card I ^ n
+ let Tn (x : (j : J) → Bn j) (i : Fin Q) := markedPowerTable n T x ((markedPowerIndex I n).symm i)
+ have hv (j : J) : (F.value (marked Bn (Fin Q) j Tn) : ℝ) = v j ^ n := by
+ simpa only [Bn, Q, Tn, v, NNReal.coe_pow] using
+ congrArg (fun x : ℝ≥0 ↦ (x : ℝ)) (F.value_markedPower_fin B I j T n)
+ have bound := F.value_marked_exterior_bound Bn hh hQ c a b Tn
+ rw [hv, hv, hv, hac, hcb] at bound
+ obtain ⟨hposH, _, _⟩ := VPVNP.ExteriorLevelRates.choose_adjacent_pos hh hQ
+ exact divide_exterior_wire (by exact_mod_cast hposH) (by positivity) (by positivity) bound
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MarkedSplitBound.lean b/lean/OAI/Computability/VPVNP/MarkedSplitBound.lean
new file mode 100644
index 0000000000..03400d13be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MarkedSplitBound.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.MarkedSplitIdentity
+
+/-!
+# Cost of the two orders of a marked-index operator
+
+Appendix A.2 places the exterior column and row at fixed endpoints, with an
+old index and a newly exposed index. The two matrix orders pair these four
+roles in opposite ways. Local restriction first realizes the factorization
+and then contracts the old index against the background tensor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor.SpectralPoint
+
+variable {k J : Type*} [Field k] [Fintype J]
+
+private def operatorSide (reverse : Bool) : Option (Option Bool) → Bool
+ | none => !reverse
+ | some none => reverse
+ | some (some side) => side
+
+private theorem value_wire_card (F : SpectralPoint k J) (a b : J)
+ (I : Type) [Fintype I] [Nonempty I] :
+ (F.value (wire a b I) : ℝ) = (Fintype.card I : ℝ) ^ F.wireDistance a b := by
+ rw [F.value_wire_equiv a b (Fintype.equivFin I)]
+ exact F.value_wire_eq_rpow a b Fintype.card_pos
+
+private theorem value_splitMarkedTerm_le_factor (F : SpectralPoint k J)
+ (B : J → Type) [∀ j, Fintype (B j)] (I H K : Type) [Fintype I] [Fintype H] [Fintype K]
+ (x a b old : J) (T : ((j : J) → B j) → I → k) (M : I → I → H → H → k)
+ (side : Option (Option Bool) → Bool) (center : Bool → J)
+ (L : ((r : Option (Option Bool)) → side r = false → cutBasis (tripleBasis I H) I r) → K → k)
+ (D : ((r : Option (Option Bool)) → side r = true → cutBasis (tripleBasis I H) I r) → K → k)
+ (h : ∀ t : (r : Option (Option Bool)) → cutBasis (tripleBasis I H) I r,
+ M (t (some none)) (t none) (t (some (some true))) (t (some (some false))) =
+ ∑ z, L (fun r _ ↦ t r) z * D (fun r _ ↦ t r) z) :
+ F.value (splitMarkedTerm B I H x a b T M) ≤
+ F.value (marked B I old T) * (F.value (wire (center false) (center true) K) *
+ ∏ r : Option (Option Bool), F.value (wire (r.elim old (triplePlace x a b))
+ (center (side r)) (cutBasis (tripleBasis I H) I r))) := by
+ let A (t : (r : Option Bool) → tripleBasis I H r) (j : I) :=
+ M (t none) j (t (some true)) (t (some false))
+ let op := placedTensor (fun r ↦ r.elim old (triplePlace x a b)) (cutBasis (tripleBasis I H) I)
+ (fun t ↦ A (fun r ↦ t (some r)) (t none))
+ have he : F.value (splitMarkedTerm B I H x a b T M) ≤ F.value (marked B I old T) * F.value op := by
+ rw [← F.value_tensorProduct]
+ exact F.monotone (contract_marked_operator B (tripleBasis I H) I old (triplePlace x a b) T A)
+ refine he.trans (mul_le_mul_of_nonneg_left ?_ zero_le)
+ have hh := F.value_cutFactorization_le (fun r ↦ r.elim old (triplePlace x a b)) side center
+ (cutBasis (tripleBasis I H) I) K L D
+ convert hh using 2
+ apply congrArg _
+ funext t
+ exact h _
+
+/-- The old index pairs with the row, and the new index pairs with the column. -/
+theorem value_splitMarkedTerm_le_plus (F : SpectralPoint k J) (B : J → Type) [∀ j, Fintype (B j)]
+ (I H K : Type) [Fintype I] [Fintype H] [Fintype K] [Nonempty I] [Nonempty H] [Nonempty K]
+ (x a b old : J) (T : ((j : J) → B j) → I → k) (M : I → I → H → H → k)
+ (L D : I → H → K → k) (h : ∀ i j β α, M i j β α = ∑ z, L i α z * D j β z) :
+ (F.value (splitMarkedTerm B I H x a b T M) : ℝ) ≤ F.value (marked B I old T) *
+ ((Fintype.card K : ℝ) ^ F.wireDistance x old * (Fintype.card H : ℝ) ^ F.wireDistance a x *
+ (Fintype.card H : ℝ) ^ F.wireDistance b old) := by
+ let center := fun s : Bool ↦ if s then old else x
+ have bound := value_splitMarkedTerm_le_factor F B I H K x a b old T M (operatorSide false) center
+ (fun t ↦ L (t (some none) rfl) (t (some (some false)) rfl))
+ (fun t ↦ D (t none rfl) (t (some (some true)) rfl))
+ (fun t ↦ h _ _ _ _)
+ rw [Fintype.prod_option, Fintype.prod_option, Fintype.prod_bool] at bound
+ change F.value _ ≤ F.value _ * (F.value (wire x old K) * (F.value (wire old old I) *
+ (F.value (wire x x I) * (F.value (wire b old H) * F.value (wire a x H))))) at bound
+ have bound' := NNReal.coe_le_coe.mpr bound
+ simpa only [NNReal.coe_mul, value_wire_card, F.wireDistance_self, Real.rpow_zero,
+ one_mul, mul_assoc, mul_left_comm, mul_comm] using bound'
+
+/-- The old index pairs with the column, and the new index pairs with the row. -/
+theorem value_splitMarkedTerm_le_minus (F : SpectralPoint k J) (B : J → Type) [∀ j, Fintype (B j)]
+ (I H K : Type) [Fintype I] [Fintype H] [Fintype K] [Nonempty I] [Nonempty H] [Nonempty K]
+ (x a b old : J) (T : ((j : J) → B j) → I → k) (M : I → I → H → H → k)
+ (L D : I → H → K → k) (h : ∀ i j β α, M i j β α = ∑ z, L j α z * D i β z) :
+ (F.value (splitMarkedTerm B I H x a b T M) : ℝ) ≤ F.value (marked B I old T) *
+ ((Fintype.card K : ℝ) ^ F.wireDistance old x * (Fintype.card H : ℝ) ^ F.wireDistance a old *
+ (Fintype.card H : ℝ) ^ F.wireDistance b x) := by
+ let center := fun s : Bool ↦ if s then x else old
+ have bound := value_splitMarkedTerm_le_factor F B I H K x a b old T M (operatorSide true) center
+ (fun t ↦ L (t none rfl) (t (some (some false)) rfl))
+ (fun t ↦ D (t (some none) rfl) (t (some (some true)) rfl))
+ (fun t ↦ h _ _ _ _)
+ rw [Fintype.prod_option, Fintype.prod_option, Fintype.prod_bool] at bound
+ change F.value _ ≤ F.value _ * (F.value (wire old x K) * (F.value (wire old old I) *
+ (F.value (wire x x I) * (F.value (wire b x H) * F.value (wire a old H))))) at bound
+ have bound' := NNReal.coe_le_coe.mpr bound
+ simpa only [NNReal.coe_mul, value_wire_card, F.wireDistance_self, Real.rpow_zero,
+ one_mul, mul_assoc, mul_left_comm, mul_comm] using bound'
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MarkedSplitIdentity.lean b/lean/OAI/Computability/VPVNP/MarkedSplitIdentity.lean
new file mode 100644
index 0000000000..e7dd4e2cd9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MarkedSplitIdentity.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.MarkedTensor
+
+/-!
+# Splitting a marked tensor times an identity wire
+
+In Appendix A.2 the new marked index is placed at the intermediate party. The
+column of the exterior operator stays at the first endpoint and its row at
+the second. These three roles retain their own local factors even when their
+parties coincide.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+universe w
+
+variable {J k : Type*}
+
+/-- The new marked index, the exterior column, and the exterior row. -/
+abbrev tripleBasis (I H : Type w) := cutBasis (fun _ : Bool ↦ H) I
+
+/-- Place the new index at `x`, the column at `a`, and the row at `b`. -/
+def triplePlace (x a b : J) : Option Bool → J
+ | none => x
+ | some false => a
+ | some true => b
+
+/-- Place the table indexed by the new index, row, and column, in that order. -/
+noncomputable abbrev threeMarked (B : J → Type*) [∀ j, Fintype (B j)]
+ (I H : Type w) [Fintype I] [Fintype H] (x a b : J)
+ (S : ((j : J) → B j) → I → H → H → k) : Tensor k J :=
+ placedWith B (tripleBasis I H) (triplePlace x a b)
+ (fun bg y ↦ S bg (y none) (y (some true)) (y (some false)))
+
+/-- Contract the old marked index against one of the two exterior-operator orders. -/
+noncomputable abbrev splitMarkedTerm [CommSemiring k] (B : J → Type*) [∀ j, Fintype (B j)]
+ (I H : Type w) [Fintype I] [Fintype H] (x a b : J)
+ (T : ((j : J) → B j) → I → k) (M : I → I → H → H → k) : Tensor k J :=
+ threeMarked B I H x a b (fun bg i β α ↦ ∑ j, T bg j * M i j β α)
+
+open scoped Classical in
+/-- Grouping the three indices of the marked tensor and the wire gives the
+coefficient of the marked tensor times the row-column Kronecker delta. -/
+theorem marked_wire_mutual [CommSemiring k] [Fintype J]
+ (B : J → Type*) [∀ j, Fintype (B j)] (I H : Type w) [Fintype I] [Fintype H]
+ (x a b : J) (T : ((j : J) → B j) → I → k) :
+ let X := tensorProduct (marked B I x T) (wire a b H)
+ let Y := threeMarked B I H x a b
+ (fun bg i β α ↦ T bg i * (if α = β then 1 else 0))
+ Restricts X Y ∧ Restricts Y X := by
+ let e (j : J) : (B j × ((r : Option Bool) → j = triplePlace x a b r → tripleBasis I H r)) ≃
+ (B j × (j = x → I)) × ((j = a → H) × (j = b → H)) :=
+ { toFun z := ((z.1, z.2 none), z.2 (some false), z.2 (some true))
+ invFun p := (p.1.1, fun r ↦ match r with
+ | none => p.1.2
+ | some false => p.2.1
+ | some true => p.2.2)
+ left_inv z := by
+ refine Prod.ext ?_ ?_
+ · rfl
+ funext r
+ rcases r with _ | (_ | _) <;> rfl
+ right_inv _ := rfl }
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+open scoped Classical in
+/-- The two contracted arrays dominate the product of the marked tensor and
+its identity wire under direct sum. -/
+theorem marked_split_restricts [CommSemiring k] [Fintype J]
+ (B : J → Type*) [∀ j, Fintype (B j)] (I H : Type w) [Fintype I] [Fintype H]
+ (x a b : J) (T : ((j : J) → B j) → I → k) (P M : I → I → H → H → k)
+ (h : ∀ i j β α, P i j β α + M i j β α = if i = j ∧ β = α then 1 else 0) :
+ Restricts (directSum (splitMarkedTerm B I H x a b T P) (splitMarkedTerm B I H x a b T M))
+ (tensorProduct (marked B I x T) (wire a b H)) := by
+ let L := splitMarkedTerm B I H x a b T P
+ let R := splitMarkedTerm B I H x a b T M
+ let Y := threeMarked B I H x a b (fun bg i β α ↦ T bg i * (if α = β then 1 else 0))
+ let LC : Array k L.Basis := L.coeff
+ let RC : Array k L.Basis := R.coeff
+ let YC : Array k L.Basis := Y.coeff
+ have hsum : LC + RC = YC := by
+ funext z
+ let bg := fun j ↦ (z j).1
+ let i : I := (z x).2 none rfl
+ let α : H := (z a).2 (some false) rfl
+ let β : H := (z b).2 (some true) rfl
+ change (∑ j, T bg j * P i j β α) + (∑ j, T bg j * M i j β α) =
+ T bg i * (if α = β then 1 else 0)
+ rw [← Finset.sum_add_distrib]
+ simp_rw [← mul_add, h]
+ by_cases he : β = α <;> simp [he, eq_comm (a := α) (b := β)]
+ refine (directSum_restricts_add LC RC).trans ?_
+ rw [hsum]
+ exact (marked_wire_mutual B I H x a b T).2
+
+open scoped Classical in
+/-- Applying the spectral point gives the subadditivity step of the relocation inequality. -/
+theorem value_marked_wire_le_split [Field k] [Fintype J] (F : SpectralPoint k J)
+ (B : J → Type) [∀ j, Fintype (B j)] (I H : Type) [Fintype I] [Fintype H]
+ (x a b : J) (T : ((j : J) → B j) → I → k) (P M : I → I → H → H → k)
+ (h : ∀ i j β α, P i j β α + M i j β α = if i = j ∧ β = α then 1 else 0) :
+ F.value (marked B I x T) * F.value (wire a b H) ≤
+ F.value (splitMarkedTerm B I H x a b T P) + F.value (splitMarkedTerm B I H x a b T M) := by
+ rw [← F.value_tensorProduct, ← F.value_directSum]
+ exact F.monotone (marked_split_restricts B I H x a b T P M h)
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MarkedTensor.lean b/lean/OAI/Computability/VPVNP/MarkedTensor.lean
new file mode 100644
index 0000000000..ae376fae3e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MarkedTensor.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.WireSpectrum
+
+/-!
+# Local operations on marked tensor indices
+
+In Appendix A, the same coefficient table can place its marked indices at
+different parties. Each party retains its background basis while receiving one
+factor for each marked role assigned to it. These local operations describe
+the arrays in the two orders of the exterior-algebra splitting identity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+universe u v w r
+
+variable {k : Type u} {J : Type v} {R : Type r}
+
+/-- A table on the background bases and additional marked indices. -/
+abbrev MarkedArray (k : Type*) (B : J → Type*) (I : R → Type*) :=
+ ((j : J) → B j) → ((r : R) → I r) → k
+
+/-- Place all marked indices while retaining the original background basis at
+ each party. This applies when multiple roles have the same party. -/
+noncomputable def placedWith [Fintype R] (B : J → Type*) [∀ j, Fintype (B j)]
+ (I : R → Type*) [∀ r, Fintype (I r)] (place : R → J) (T : MarkedArray k B I) : Tensor k J where
+ Basis j := B j × ((r : R) → j = place r → I r)
+ finiteBasis _ := by classical exact inferInstance
+ coeff x := T (fun j ↦ (x j).1) (fun r ↦ (x (place r)).2 r rfl)
+
+/-- One marked index, keeping the background bases unchanged. -/
+noncomputable def marked (B : J → Type*) [∀ j, Fintype (B j)]
+ (I : Type*) [Fintype I] (a : J) (T : ((j : J) → B j) → I → k) : Tensor k J where
+ Basis j := B j × (j = a → I)
+ finiteBasis _ := by classical exact inferInstance
+ coeff x := T (fun j ↦ (x j).1) ((x a).2 rfl)
+
+/-- A complete assignment of local indices to a placed tensor is equivalently
+an assignment of the background indices and one index per role. -/
+def placedWithEquiv (B : J → Type*) (I : R → Type*) (place : R → J) :
+ (((j : J) → B j) × ((r : R) → I r)) ≃ ((j : J) → B j × ((r : R) → j = place r → I r)) where
+ toFun xy j := (xy.1 j, fun r _ ↦ xy.2 r)
+ invFun x := (fun j ↦ (x j).1, fun r ↦ (x (place r)).2 r rfl)
+ left_inv _ := rfl
+ right_inv x := by
+ funext j
+ refine Prod.ext ?_ ?_
+ · rfl
+ funext r h
+ subst j
+ rfl
+
+/-- Move one extra factor into party `a`'s local basis, carrying it there as a function on the
+equality witness. -/
+def markedEquiv (B : J → Type*) (I : Type*) (a : J) :
+ (((j : J) → B j) × I) ≃ ((j : J) → B j × (j = a → I)) where
+ toFun xy j := (xy.1 j, fun _ ↦ xy.2)
+ invFun x := (fun j ↦ (x j).1, (x a).2 rfl)
+ left_inv _ := rfl
+ right_inv x := by
+ funext j
+ refine Prod.ext ?_ ?_
+ · rfl
+ funext h
+ subst j
+ rfl
+
+/-- Regroup role-indexed factors by their assigned parties, with one factor for each role
+placed at a given party. -/
+def placedEquiv (I : R → Type*) (place : R → J) :
+ ((r : R) → I r) ≃ ((j : J) → (r : R) → j = place r → I r) where
+ toFun x _ r _ := x r
+ invFun x r := x (place r) r rfl
+ left_inv _ := rfl
+ right_inv x := by
+ funext j r h
+ subst j
+ rfl
+
+/-- Identity matrix on the background and new marked indices, and a local
+pairing between the old marked index of the tensor and that of an operator. -/
+theorem contract_marked_operator [Fintype J] [Fintype R] [CommSemiring k]
+ (B : J → Type*) [∀ j, Fintype (B j)] (I : R → Type w) [∀ r, Fintype (I r)]
+ (K : Type w) [Fintype K] (a : J) (place : R → J)
+ (T : ((j : J) → B j) → K → k) (A : ((r : R) → I r) → K → k) :
+ Restricts (tensorProduct (marked B K a T)
+ (placedTensor (fun e ↦ e.elim a place) (cutBasis I K) (fun z ↦ A (fun r ↦ z (some r)) (z none))))
+ (placedWith B I place (fun b y ↦ ∑ i, T b i * A y i)) := by
+ classical
+ let L (j : J) (out : B j × ((r : R) → j = place r → I r))
+ (p : (B j × (j = a → K)) × ((e : Option R) → j = e.elim a place → cutBasis I K e)) : k :=
+ if out.1 = p.1.1 ∧ (∀ r (h : j = place r), out.2 r h = p.2 (some r) h) ∧
+ (∀ h : j = a, p.1.2 h = p.2 none h) then 1 else 0
+ refine ⟨L, ?_⟩
+ funext out
+ let e₁ := markedEquiv B K a
+ let e₂ := placedEquiv (cutBasis I K) (fun e ↦ e.elim a place)
+ let e₃ : (K × ((r : R) → I r)) ≃ ((e : Option R) → cutBasis I K e) :=
+ { toFun := fun xy e ↦ match e with | none => xy.1 | some r => xy.2 r
+ invFun := fun x ↦ (x none, fun r ↦ x (some r))
+ left_inv := fun _ ↦ rfl
+ right_inv := fun x ↦ by funext e; cases e <;> rfl }
+ let Y := tensorProduct (marked B K a T)
+ (placedTensor (fun e ↦ e.elim a place) (cutBasis I K)
+ (fun z ↦ A (fun r ↦ z (some r)) (z none)))
+ let ei : ((((j : J) → B j) × K) × (K × ((r : R) → I r))) ≃ ((j : J) → Y.Basis j) :=
+ (e₁.prodCongr (e₃.trans e₂)).trans (Equiv.arrowProdEquivProdArrow J _ _).symm
+ let f (x : (j : J) → Y.Basis j) := (∏ j, L j (out j) (x j)) * Y.coeff x
+ calc
+ _ = ∑ x : (j : J) → Y.Basis j, f x := rfl
+ _ = ∑ xy, f (ei xy) := (ei.sum_comp f).symm
+ _ = _ := ?_
+ let bg := fun j ↦ (out j).1
+ let vals := fun r ↦ (out (place r)).2 r rfl
+ have hh (b : (j : J) → B j) (k₁ k₂ : K) (y : (r : R) → I r) :
+ f (ei ((b,k₁),(k₂,y))) =
+ (if bg = b ∧ vals = y ∧ k₁ = k₂ then 1 else 0) * (T b k₁ * A y k₂) := by
+ dsimp only [f, Y, tensorProduct, marked, placedTensor, L, ei, e₁, e₂, e₃, Equiv.trans_apply, Equiv.prodCongr_apply,
+ Equiv.arrowProdEquivProdArrow, Equiv.symm, Equiv.coe_fn_mk, markedEquiv, placedEquiv]
+ rw [Fintype.prod_boole]
+ congr 2
+ apply propext
+ change (∀ j, (out j).1 = b j ∧ (∀ r (h : j = place r), (out j).2 r h = y r) ∧
+ (∀ _h : j = a, k₁ = k₂)) ↔ _
+ constructor
+ · intro h
+ exact ⟨funext (fun j ↦ (h j).1), funext (fun r ↦ (h (place r)).2.1 r rfl), (h a).2.2 rfl⟩
+ · rintro ⟨rfl, rfl, rfl⟩ j
+ refine ⟨rfl, ?_, fun _ ↦ rfl⟩
+ intro r h
+ subst j
+ rfl
+ simp_rw [Fintype.sum_prod_type]
+ simp_rw [hh]
+ simp [ite_mul, ite_and, bg, vals, placedWith]
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MatchClauses.lean b/lean/OAI/Computability/VPVNP/MatchClauses.lean
new file mode 100644
index 0000000000..d86d5c5235
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MatchClauses.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.HardnessCNF
+import Mathlib.Data.Fintype.EquivFin
+import Mathlib.Data.Fintype.BigOperators
+
+/-! # Boolean flags for matching finite words
+
+Each match flag is equivalent to a conjunction of prescribed bit values.
+There is one binary implication per bit and one clause for the converse.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace HardnessCNF
+
+open scoped Classical
+
+variable {k : ℕ} {I : Type*} [Fintype I]
+
+private noncomputable def indices (I : Type*) [Fintype I] : List I :=
+ (List.finRange _).map (Fintype.equivFin I).symm
+
+@[simp] private theorem mem_indices (i : I) : i ∈ indices I := by
+ simp [indices]
+ exact (Fintype.equivFin I).symm.surjective i
+
+@[simp] private theorem length_indices : (indices I).length = Fintype.card I := by
+ simp [indices]
+
+/-- Conjunction over a finite index type. -/
+noncomputable def meetCNF (c : I → CNF k) : CNF k := (indices I).flatMap c
+
+theorem satisfies_meetCNF (c : I → CNF k) (x : Fin k → Bool) :
+ Satisfies (meetCNF c) x ↔ ∀ i, Satisfies (c i) x := by
+ simp [Satisfies, meetCNF]
+ aesop
+
+theorem literalCount_meetCNF_const (c : I → CNF k) (n : ℕ) (hc : ∀ i, literalCount (c i) = n) :
+ literalCount (meetCNF c) = Fintype.card I * n := by
+ have h (s : List I) : literalCount (s.flatMap c) = s.length * n := by
+ induction s with
+ | nil => simp [literalCount]
+ | cons i s ih =>
+ change literalCount (c i ++ s.flatMap c) = (s.length + 1) * n
+ rw [Nat.add_mul, Nat.one_mul, ← ih, ← hc i]
+ simp [literalCount, Nat.add_comm]
+ simpa [meetCNF] using h (indices I)
+
+/-- A flag is set exactly when the payload bits match the specified word. -/
+noncomputable def matchClauses (flag : Fin k) (bit : I → Fin k) (target : I → Bool) : CNF k :=
+ ((flag, true) :: (indices I).map (fun i => (bit i, !(target i)))) ::
+ (indices I).map (fun i => [(flag, false), (bit i, target i)])
+
+theorem satisfies_matchClauses (flag : Fin k) (bit : I → Fin k) (target : I → Bool)
+ (x : Fin k → Bool) :
+ Satisfies (matchClauses flag bit target) x ↔ (x flag = true ↔ ∀ i, x (bit i) = target i) := by
+ have hneg (i : I) : (x (bit i) = !target i) ↔ x (bit i) ≠ target i := by
+ cases x (bit i) <;> cases target i <;> decide
+ simp only [Satisfies, matchClauses, List.forall_mem_cons, List.forall_mem_map,
+ List.exists_mem_cons_iff, mem_indices, forall_const, List.not_mem_nil, false_and,
+ exists_false, or_false]
+ have hreverse : (∃ l ∈ (indices I).map (fun i => (bit i, !target i)), x l.1 = l.2) ↔
+ ∃ i, x (bit i) ≠ target i := by
+ constructor
+ · rintro ⟨_, hm, hx⟩
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp hm
+ exact ⟨i, (hneg i).mp hx⟩
+ · rintro ⟨i, hi⟩
+ exact ⟨_, List.mem_map.mpr ⟨i, mem_indices _, rfl⟩, (hneg i).mpr hi⟩
+ rw [hreverse]
+ cases x flag <;> simp
+
+theorem literalCount_matchClauses (flag : Fin k) (bit : I → Fin k) (target : I → Bool) :
+ literalCount (matchClauses flag bit target) = 3 * Fintype.card I + 1 := by
+ simp [literalCount, matchClauses, Function.comp_def, Nat.mul_comm]
+ omega
+
+end HardnessCNF
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MatrixPowerQueries.lean b/lean/OAI/Computability/VPVNP/MatrixPowerQueries.lean
new file mode 100644
index 0000000000..1381989ff9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MatrixPowerQueries.lean
@@ -0,0 +1,138 @@
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Algebra.Polynomial.Coeff
+import Mathlib.Data.Matrix.Mul
+import Mathlib.Data.Nat.Log
+
+/-!
+# Streaming coefficient queries for matrix powers
+
+A query for one coefficient of a polynomial matrix power in Appendix D.2
+splits its exponent into two halves. The implementation scans intermediate
+indices and degree splits with scalar accumulators.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+open Polynomial
+
+/-- Splitting a nontrivial exponent into its lower and upper halves decreases
+the ceiling binary logarithm by at least one on both branches. -/
+theorem powerQuery_halves {h : ℕ} (hh : 1 < h) :
+ Nat.clog 2 (h / 2) < Nat.clog 2 h ∧ Nat.clog 2 (h - h / 2) < Nat.clog 2 h := by
+ have upper : h - h / 2 = (h + 2 - 1) / 2 := by omega
+ have order : h / 2 ≤ h - h / 2 := by omega
+ have step : Nat.clog 2 h = Nat.clog 2 (h - h / 2) + 1 := by
+ rw [upper]
+ exact Nat.clog_of_one_lt (by decide) hh
+ exact ⟨lt_of_le_of_lt (Nat.clog_mono_right 2 order) (by omega), by omega⟩
+
+variable {ι R : Type*} [Fintype ι] [DecidableEq ι] [Semiring R]
+
+/-- From an oracle for coefficients of individual entries, compute the
+coefficient of degree `z` in entry `(i,j)` of the `h`-th power. -/
+def powerEntryCoeff (entry : ι → ι → ℕ → R) (h : ℕ) (i j : ι) (z : ℕ) : R :=
+ if h = 0 then
+ if i = j ∧ z = 0 then 1 else 0
+ else if h = 1 then
+ entry i j z
+ else
+ ∑ k : ι, ∑ d ∈ Finset.antidiagonal z,
+ powerEntryCoeff entry (h / 2) i k d.1 *
+ powerEntryCoeff entry (h - h / 2) k j d.2
+termination_by Nat.clog 2 h
+decreasing_by
+ · exact (powerQuery_halves (by omega)).1
+ · exact (powerQuery_halves (by omega)).2
+
+/-- The entry query returns exactly the specified coefficient of the matrix
+power, using only the supplied entry oracle. -/
+theorem powerEntryCoeff_correct (M : Matrix ι ι R[X]) (entry : ι → ι → ℕ → R)
+ (hentry : ∀ i j z, entry i j z = (M i j).coeff z) (h : ℕ) (i j : ι) (z : ℕ) :
+ powerEntryCoeff entry h i j z = ((M ^ h) i j).coeff z := by
+ induction h using Nat.strong_induction_on generalizing i j z with
+ | h h ih =>
+ by_cases hz : h = 0
+ · subst h
+ by_cases hij : i = j <;> simp [powerEntryCoeff, hij, coeff_one]
+ by_cases ho : h = 1
+ · subst h
+ simpa [powerEntryCoeff] using hentry i j z
+ rw [powerEntryCoeff, ite_eq_right hz, ite_eq_right ho]
+ have splitPow : M ^ h = M ^ (h / 2) * M ^ (h - h / 2) := by
+ rw [← pow_add]
+ congr 1
+ omega
+ rw [splitPow, Matrix.mul_apply, finsetSum_coeff]
+ simp_rw [coeff_mul, ih (h / 2) (by omega), ih (h - h / 2) (by omega)]
+
+/-- A sequential scan over all indices uses a scalar accumulator. -/
+theorem foldl_add_eq_sum {A : Type*} [AddCommMonoid A]
+ (n : ℕ) (f : Fin n → A) :
+ Fin.foldl n (fun a i => a + f i) 0 = ∑ i, f i := by
+ induction n with
+ | zero => simp
+ | succ n ih =>
+ rw [Fin.foldl_succ_last, Fin.sum_univ_castSucc]
+ simp only [ih]
+
+/-- Sum over a consecutive block of indices with a tail-recursive scan. -/
+def streamSum {A : Type*} [AddCommMonoid A] (n : ℕ) (f : Fin n → A) : A :=
+ Fin.foldl n (fun acc i => acc + f i) 0
+
+theorem streamSum_eq {A : Type*} [AddCommMonoid A] (n : ℕ) (f : Fin n → A) :
+ streamSum n f = ∑ i, f i :=
+ foldl_add_eq_sum n f
+
+/-- Stream the ordered degree splits of `n` by keeping the first degree as
+the loop index and computing the second by subtraction. -/
+def streamAntiSum {A : Type*} [AddCommMonoid A] (n : ℕ) (f : ℕ → ℕ → A) : A :=
+ streamSum (n + 1) fun i => f i.val (n - i.val)
+
+theorem streamAntiSum_eq {A : Type*} [AddCommMonoid A] (n : ℕ) (f : ℕ → ℕ → A) :
+ streamAntiSum n f = ∑ p ∈ Finset.antidiagonal n, f p.1 p.2 := by
+ rw [streamAntiSum, streamSum_eq, Finset.Nat.sum_antidiagonal_eq_sum_range_succ f]
+ exact Fin.sum_univ_eq_sum_range (fun i => f i (n - i)) (n + 1)
+
+/-- Streaming implementation for matrices indexed by consecutive integers.
+The tail-recursive folds carry the two running sums for intermediate indices
+and for degree splits. Neither loop stores a list of all its indices. -/
+def streamedPowerEntryCoeff {n : ℕ} (entry : Fin n → Fin n → ℕ → R)
+ (h : ℕ) (i j : Fin n) (z : ℕ) : R :=
+ if h = 0 then
+ if i = j ∧ z = 0 then 1 else 0
+ else if h = 1 then
+ entry i j z
+ else
+ Fin.foldl n (fun acc k => acc +
+ Fin.foldl (z + 1) (fun acc' d => acc' +
+ streamedPowerEntryCoeff entry (h / 2) i k d.val *
+ streamedPowerEntryCoeff entry (h - h / 2) k j (z - d.val)) 0) 0
+termination_by Nat.clog 2 h
+decreasing_by
+ · exact (powerQuery_halves (by omega)).1
+ · exact (powerQuery_halves (by omega)).2
+
+/-- The streaming loops evaluate the matrix-power coefficient recurrence. -/
+theorem streamedPowerEntryCoeff_eq {n : ℕ} (entry : Fin n → Fin n → ℕ → R)
+ (h : ℕ) (i j : Fin n) (z : ℕ) :
+ streamedPowerEntryCoeff entry h i j z = powerEntryCoeff entry h i j z := by
+ induction h using Nat.strong_induction_on generalizing i j z with
+ | h h ih =>
+ rw [streamedPowerEntryCoeff, powerEntryCoeff]
+ split_ifs with hzero _ hone <;> try rfl
+ simp_rw [foldl_add_eq_sum, ih (h / 2) (by omega), ih (h - h / 2) (by omega)]
+ apply Finset.sum_congr rfl
+ intro k _
+ rw [Finset.Nat.sum_antidiagonal_eq_sum_range_succ_mk]
+ exact Fin.sum_univ_eq_sum_range (fun d => powerEntryCoeff entry (h / 2) i k d *
+ powerEntryCoeff entry (h - h / 2) k j (z - d)) (z + 1)
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MatrixWire.lean b/lean/OAI/Computability/VPVNP/MatrixWire.lean
new file mode 100644
index 0000000000..a622158665
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MatrixWire.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.WireTensor
+
+/-!
+# Matrix restrictions of a wire
+
+A wire carries the summation index of a matrix factorization between its two
+endpoints. Taking the rows or the columns as the factorization index bounds
+the wire dimension by either local dimension in the split-star construction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+variable {k J I K Z : Type*} [Fintype I] [Fintype K] [Fintype Z]
+
+/-- Place the row and column indices of a matrix at the indicated parties. -/
+noncomputable def matrixTensor (a b : J) (M : Matrix I K k) : Tensor k J where
+ Basis j := (j = a → I) × (j = b → K)
+ finiteBasis _ := by classical exact inferInstance
+ coeff x := M ((x a).1 rfl) ((x b).2 rfl)
+
+theorem matrixTensor_one [DecidableEq I] [Zero k] [One k] (a b : J) :
+ matrixTensor a b (1 : Matrix I I k) = wire a b I := by
+ unfold matrixTensor wire
+ congr 1
+ funext x
+ simp [Matrix.one_apply]
+
+private def wireEndpoints (a b : J) (Z : Type*) :
+ (Z × Z) ≃ ((j : J) → (j = a → Z) × (j = b → Z)) where
+ toFun p _ := (fun _ ↦ p.1, fun _ ↦ p.2)
+ invFun x := ((x a).1 rfl, (x b).2 rfl)
+ left_inv _ := rfl
+ right_inv x := by
+ funext j
+ apply Prod.ext <;> funext h <;> subst j <;> rfl
+
+variable [Fintype J] [CommSemiring k]
+
+/-- An exact factorization with inner index `Z` is obtained by acting with
+its two factors at the respective ends of a `Z`-dimensional wire. -/
+theorem wire_restricts_matrixTensor_of_factorization (a b : J) (M : Matrix I K k)
+ (A : Matrix I Z k) (B : Matrix Z K k) (h : ∀ i j, M i j = ∑ z, A i z * B z j) :
+ Restricts (wire (k := k) a b Z) (matrixTensor a b M) := by
+ classical
+ let L (j : J) (x : (j = a → I) × (j = b → K)) (y : (j = a → Z) × (j = b → Z)) :=
+ (if e : j = a then A (x.1 e) (y.1 e) else 1) *
+ (if e : j = b then B (y.2 e) (x.2 e) else 1)
+ refine ⟨L, ?_⟩
+ funext x
+ let f (y : ∀ j, (j = a → Z) × (j = b → Z)) :=
+ (∏ j, L j (x j) (y j)) * (wire (k := k) a b Z).coeff y
+ change (∑ y, f y) = M ((x a).1 rfl) ((x b).2 rfl)
+ rw [← (wireEndpoints a b Z).sum_comp f, Fintype.sum_prod_type, h]
+ apply Finset.sum_congr rfl
+ intro z _
+ dsimp only [f, L, wireEndpoints, wire, Equiv.coe_fn_mk]
+ simp only [Finset.prod_mul_distrib, Fintype.prod_dite_eq']
+ simp [mul_ite]
+
+/-- Use the row index as the wire index and put the whole matrix at the column endpoint. -/
+theorem wire_restricts_matrixTensor_left (a b : J) (M : Matrix I K k) :
+ Restricts (wire (k := k) a b I) (matrixTensor a b M) := by
+ classical
+ apply wire_restricts_matrixTensor_of_factorization a b M (1 : Matrix I I k) M
+ intro i j
+ simp [Matrix.one_apply, ite_mul]
+
+/-- Use the column index as the wire index and put the whole matrix at the row endpoint. -/
+theorem wire_restricts_matrixTensor_right (a b : J) (M : Matrix I K k) :
+ Restricts (wire (k := k) a b K) (matrixTensor a b M) := by
+ classical
+ apply wire_restricts_matrixTensor_of_factorization a b M M (1 : Matrix K K k)
+ intro i j
+ simp [Matrix.one_apply, mul_ite]
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MetricMidpoints.lean b/lean/OAI/Computability/VPVNP/MetricMidpoints.lean
new file mode 100644
index 0000000000..912cd58dba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MetricMidpoints.lean
@@ -0,0 +1,96 @@
+import Mathlib.Analysis.SpecificLimits.Basic
+import Mathlib.Tactic.Linarith
+import Mathlib.Tactic.NormNum
+
+/-! # From exact midpoints to fractional points
+
+In the geodesic-completion argument of Corollary 2.5, bisect a segment
+repeatedly, keeping the half that contains the prescribed distance from its
+left endpoint. The left endpoints are Cauchy and their limit has both
+prescribed endpoint distances.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+open Filter
+open scoped Topology
+
+variable {X : Type*} [MetricSpace X]
+
+/-- In a complete metric space with exact midpoints, every segment admits
+a point at each fraction of its length. -/
+theorem exists_fractionalPoint_of_midpoints [CompleteSpace X]
+ (hm : ∀ a b : X, ∃ m, dist a m = dist a b / 2 ∧ dist m b = dist a b / 2)
+ (a b : X) {t : ℝ} (ht₀ : 0 ≤ t) (ht₁ : t ≤ 1) :
+ ∃ z, dist a z = t * dist a b ∧ dist z b = (1 - t) * dist a b := by
+ classical
+ choose mid mid_left mid_right using hm
+ let step (p : X × X) : X × X :=
+ if dist a p.1 + dist p.1 p.2 / 2 ≤ t * dist a b then (mid p.1 p.2, p.2)
+ else (p.1, mid p.1 p.2)
+ let p : ℕ → X × X := Nat.rec (a, b) fun _ prev => step prev
+ have bracket (n : ℕ) :
+ dist a (p n).1 ≤ t * dist a b ∧
+ dist (p n).2 b ≤ (1 - t) * dist a b ∧
+ dist a (p n).1 + dist (p n).1 (p n).2 + dist (p n).2 b ≤ dist a b ∧
+ dist (p n).1 (p n).2 = dist a b * (1 / 2 : ℝ) ^ n := by
+ induction n with
+ | zero =>
+ change dist a a ≤ _ ∧ dist b b ≤ _ ∧ dist a a + dist a b + dist b b ≤ _ ∧ dist a b = _
+ simp only [dist_self, zero_add, add_zero, pow_zero, mul_one, le_refl, and_true]
+ exact ⟨mul_nonneg ht₀ dist_nonneg, mul_nonneg (sub_nonneg.mpr ht₁) dist_nonneg⟩
+ | succ n ih =>
+ obtain ⟨hl, hr, hpath, hlen⟩ := ih
+ let l := (p n).1
+ let r := (p n).2
+ have hL := dist_triangle a l (mid l r)
+ have hR := dist_triangle (mid l r) r b
+ rw [mid_left] at hL
+ rw [mid_right] at hR
+ change dist a (step (l, r)).1 ≤ _ ∧ dist (step (l, r)).2 b ≤ _ ∧
+ dist a (step (l, r)).1 + dist (step (l, r)).1 (step (l, r)).2 +
+ dist (step (l, r)).2 b ≤ _ ∧ dist (step (l, r)).1 (step (l, r)).2 = _
+ change dist a l + dist l r + dist r b ≤ _ at hpath
+ change dist l r = _ at hlen
+ by_cases hc : dist a l + dist l r / 2 ≤ t * dist a b
+ · simp only [step, ite_eq_left hc, mid_right, pow_succ]
+ exact ⟨hL.trans hc, hr, by linarith only [hL, hpath], by rw [hlen]; ring⟩
+ · simp only [step, ite_eq_right hc, mid_left, pow_succ]
+ exact ⟨hl, by linarith only [hc, hR, hpath], by linarith only [hR, hpath],
+ by rw [hlen]; ring⟩
+ have hstep (n : ℕ) : dist (p n).1 (p (n + 1)).1 ≤ dist a b * (1 / 2 : ℝ) ^ n := by
+ change dist (p n).1 (step (p n)).1 ≤ _
+ rw [← (bracket n).2.2.2]
+ unfold step
+ split
+ · rw [mid_left]
+ linarith only [dist_nonneg (x := (p n).1) (y := (p n).2)]
+ · simp
+ obtain ⟨z, hz⟩ := cauchySeq_tendsto_of_complete
+ (cauchySeq_of_le_geometric (1 / 2 : ℝ) (dist a b) (by norm_num) hstep)
+ have hleft : dist a z ≤ t * dist a b :=
+ le_of_tendsto_of_tendsto' (tendsto_const_nhds.dist hz) tendsto_const_nhds
+ (fun n => (bracket n).1)
+ have hpow := tendsto_pow_atTop_nhds_zero_of_lt_one (by norm_num : (0 : ℝ) ≤ 1 / 2)
+ (by norm_num : (1 / 2 : ℝ) < 1)
+ have hlen : Tendsto (fun n : ℕ => dist a b * (1 / 2 : ℝ) ^ n) atTop (𝓝 0) := by
+ simpa using hpow.const_mul (dist a b)
+ have hright : dist z b ≤ (1 - t) * dist a b := by
+ have bound := hlen.add_const ((1 - t) * dist a b)
+ rw [zero_add] at bound
+ refine le_of_tendsto_of_tendsto' (hz.dist tendsto_const_nhds) bound fun n => ?_
+ have tri := dist_triangle (p n).1 (p n).2 b
+ rw [(bracket n).2.2.2] at tri
+ exact tri.trans (add_le_add_right (bracket n).2.1 _)
+ exact ⟨z, by linarith only [hleft, hright, dist_triangle a z b],
+ by linarith only [hleft, hright, dist_triangle a z b]⟩
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MidpointUnion.lean b/lean/OAI/Computability/VPVNP/MidpointUnion.lean
new file mode 100644
index 0000000000..01ac52fdba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MidpointUnion.lean
@@ -0,0 +1,72 @@
+import Mathlib.Topology.MetricSpace.Pseudo.Defs
+import Mathlib.Data.Finset.Lattice.Fold
+
+/-!
+# Distances in the union of midpoint extensions
+
+The finite stages in Corollary 2.5 preserve distances between parties
+that have already appeared. The distance of two points in the union can
+therefore be read at their first common stage. A single later stage suffices
+to realize the entire distance matrix of a finite tuple.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {X : Type*}
+
+/-- Read a distance at the first stage containing both arguments. -/
+def unionDist (birth : X → ℕ) (d : ℕ → X → X → ℝ) (x y : X) : ℝ :=
+ d (max (birth x) (birth y)) x y
+
+/-- Each stage containing both points gives the distance in the union. -/
+theorem unionDist_eq_stage {birth : X → ℕ} {d : ℕ → X → X → ℝ}
+ (stable : ∀ n x y, birth x ≤ n → birth y ≤ n → d (n + 1) x y = d n x y)
+ {n : ℕ} {x y : X} (hx : birth x ≤ n) (hy : birth y ≤ n) :
+ unionDist birth d x y = d n x y := by
+ have hn := max_le hx hy
+ clear hx hy
+ obtain ⟨m, rfl⟩ := Nat.exists_eq_add_of_le hn
+ clear hn
+ induction m with
+ | zero => rfl
+ | succ m ih =>
+ exact ih.trans (stable _ x y (by omega) (by omega)).symm
+
+/-- The stage distances give a pseudometric on the union. The triangle
+inequality can be checked in any stage containing the three points. -/
+@[instance_reducible] noncomputable def unionPseudoMetric (birth : X → ℕ) (d : ℕ → X → X → ℝ)
+ (stable : ∀ n x y, birth x ≤ n → birth y ≤ n → d (n + 1) x y = d n x y)
+ (self : ∀ n x, d n x x = 0) (comm : ∀ n x y, d n x y = d n y x)
+ (triangle : ∀ n x y z, d n x z ≤ d n x y + d n y z) : PseudoMetricSpace X where
+ dist := unionDist birth d
+ dist_self x := self _ x
+ dist_comm x y := by
+ simp only [unionDist, max_comm (birth y) (birth x)]
+ exact comm _ _ _
+ dist_triangle x y z := by
+ let n := max (birth x) (max (birth y) (birth z))
+ have hx : birth x ≤ n := le_max_left _ _
+ have hy : birth y ≤ n := (le_max_left _ _).trans (le_max_right _ _)
+ have hz : birth z ≤ n := (le_max_right _ _).trans (le_max_right _ _)
+ rw [unionDist_eq_stage stable hx hz, unionDist_eq_stage stable hx hy, unionDist_eq_stage stable hy hz]
+ exact triangle n x y z
+
+/-- All distances of a finite configuration are read at one common stage,
+including for an empty tuple. -/
+theorem unionDist_finite_stage {birth : X → ℕ} {d : ℕ → X → X → ℝ}
+ (stable : ∀ n x y, birth x ≤ n → birth y ≤ n → d (n + 1) x y = d n x y)
+ {ι : Type*} [Fintype ι] (f : ι → X) :
+ ∃ n, (∀ i, birth (f i) ≤ n) ∧ ∀ i j, unionDist birth d (f i) (f j) = d n (f i) (f j) := by
+ let n := Finset.univ.sup (birth ∘ f)
+ have h (i : ι) : birth (f i) ≤ n := Finset.le_sup (f := birth ∘ f) (Finset.mem_univ i)
+ exact ⟨n, h, fun i j ↦ unionDist_eq_stage stable (h i) (h j)⟩
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MonicGraphRelation.lean b/lean/OAI/Computability/VPVNP/MonicGraphRelation.lean
new file mode 100644
index 0000000000..bb490eb0a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MonicGraphRelation.lean
@@ -0,0 +1,73 @@
+import Mathlib.Algebra.MvPolynomial.NoZeroDivisors
+import Mathlib.FieldTheory.Minpoly.IsIntegrallyClosed
+import Mathlib.RingTheory.Polynomial.RationalRoot
+import Mathlib.RingTheory.Polynomial.UniqueFactorization
+
+/-!
+# A bounded monic relation for the certificate graph
+
+In the effective Nullstellensatz argument used for Section 8.2, a generic
+linear normalization makes the distinguished coordinate integral over an
+embedded polynomial ring. A bounded nonzero relation in all the normalized
+coordinates is available by counting monomials. The minimal polynomial
+divides that relation over the polynomial ring, so replacing it by a monic
+relation does not increase its multivariate total degree.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+open MvPolynomial
+
+private theorem eval_split {E S : Type*} [Field E] [CommRing S] [Algebra E S] {m : ℕ}
+ (Q : Fin m → S) (T : S) (W : MvPolynomial (Fin (m + 1)) E) :
+ Polynomial.eval₂ (aeval Q).toRingHom T (finSuccEquiv E m W) = aeval (Fin.cons T Q) W := by
+ have he : (Polynomial.eval₂RingHom (aeval Q).toRingHom T).comp (finSuccEquiv E m).toRingHom =
+ (aeval (Fin.cons T Q)).toRingHom := by
+ apply ringHom_ext
+ · intro c
+ simp [finSuccEquiv_apply]
+ · intro i
+ refine Fin.cases ?_ (fun j => ?_) i
+ · simp [finSuccEquiv_X_zero]
+ · simp [finSuccEquiv_X_succ]
+ exact DFunLike.congr_fun he W
+
+/-- If `Q` are algebraically independent and `T` is integral over their image
+algebra, every nonzero relation in `(T,Q)` has a monic divisor which is itself a
+relation. The divisor has no larger total degree, including in positive characteristic. -/
+theorem monic_relation_of_relation {E S : Type*} [Field E] [CommRing S] [IsDomain S]
+ [Algebra E S] {m : ℕ} (Q : Fin m → S) (T : S)
+ (hinj : Function.Injective (aeval Q : MvPolynomial (Fin m) E →ₐ[E] S))
+ (hint : IsIntegral (aeval Q : MvPolynomial (Fin m) E →ₐ[E] S).range T)
+ (W : MvPolynomial (Fin (m + 1)) E) (hW : W ≠ 0) (hzero : aeval (Fin.cons T Q) W = 0) :
+ ∃ U : MvPolynomial (Fin (m + 1)) E, (finSuccEquiv E m U).Monic ∧
+ aeval (Fin.cons T Q) U = 0 ∧ U ∣ W ∧ U.totalDegree ≤ W.totalDegree := by
+ let B := MvPolynomial (Fin m) E
+ let φ : B →ₐ[E] S := aeval Q
+ let : Algebra B S := φ.toRingHom.toAlgebra
+ let : Module.IsTorsionFree B S := Module.isTorsionFree_iff_algebraMap_injective.mpr hinj
+ let e := AlgEquiv.ofInjective φ hinj
+ have hInt : IsIntegral B T := (e.toRingEquiv.isIntegral_iff (by rfl) T).mpr hint
+ let P := minpoly B T
+ let split := finSuccEquiv E m
+ have hroot : Polynomial.aeval T (split W) = 0 := (eval_split Q T W).trans hzero
+ have hdiv : P ∣ split W := minpoly.isIntegrallyClosed_dvd hInt hroot
+ have hmon : P.Monic := minpoly.monic hInt
+ have hdvd : split.symm P ∣ W := by simpa using (map_dvd split.symm hdiv)
+ refine ⟨split.symm P, ?_, ?_, hdvd, totalDegree_le_of_dvd_of_isDomain hdvd hW⟩
+ · change (split (split.symm P)).Monic
+ simpa using hmon
+ · rw [← eval_split]
+ change Polynomial.aeval T (split (split.symm P)) = 0
+ rw [split.apply_symm_apply]
+ exact minpoly.aeval B T
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MonomialBasis.lean b/lean/OAI/Computability/VPVNP/MonomialBasis.lean
new file mode 100644
index 0000000000..e9ef0cbaca
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MonomialBasis.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.GreedyBasis
+import Mathlib.Algebra.Algebra.Subalgebra.Lattice
+import Mathlib.Algebra.BigOperators.Ring.Finset
+import Mathlib.LinearAlgebra.Basis.VectorSpace
+import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas
+
+/-!
+# Bounded monomials in the reduced coordinate algebra
+
+Appendix D.1 enumerates monomials up to a dimension bound to select a basis
+of the finite slice algebra. Multiplying the span through degree `d` by
+one generator lands in the span through degree `d+1`. Equal consecutive
+spans contain every product of generators. Before that occurs, the dimension
+increases strictly.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MonomialBasis
+
+variable {K A Label : Type*} [Field K] [CommRing A] [Algebra K A] [Fintype Label]
+
+/-- Values of label monomials of total degree at most `d`. -/
+def monomials (X : Label → A) (d : ℕ) : Set A :=
+ {v | ∃ e : Label → ℕ, (∑ i, e i) ≤ d ∧ ∏ i, X i ^ e i = v}
+
+/-- The subspace generated by the bounded monomials. -/
+def degreeSpan (K : Type*) [Field K] [Algebra K A] (X : Label → A) (d : ℕ) : Submodule K A :=
+ Submodule.span K (monomials X d)
+
+private theorem one_mem_monomials (X : Label → A) (d : ℕ) : (1 : A) ∈ monomials X d :=
+ ⟨fun _ => 0, by simp, by simp⟩
+
+theorem degreeSpan_mono (X : Label → A) : Monotone (degreeSpan K X) := by
+ intro d d' h
+ apply Submodule.span_mono
+ rintro v ⟨e, hdeg, he⟩
+ exact ⟨e, hdeg.trans h, he⟩
+
+private theorem generator_mul_mem (X : Label → A) (i : Label) (d : ℕ) {v : A}
+ (hv : v ∈ degreeSpan K X d) : X i * v ∈ degreeSpan K X (d + 1) := by
+ classical
+ apply Submodule.span_induction (p := fun v _ => X i * v ∈ degreeSpan K X (d + 1)) _ _ _ _ hv
+ · rintro _ ⟨e, hdeg, rfl⟩
+ apply Submodule.subset_span
+ refine ⟨fun j => (if i = j then 1 else 0) + e j, ?_, ?_⟩
+ · simpa [Finset.sum_add_distrib, Nat.add_comm] using Nat.add_le_add_left hdeg 1
+ · simp_rw [pow_add]
+ rw [Finset.prod_mul_distrib]
+ simp [apply_ite]
+ · simp
+ · intro x y _ _ hx hy
+ simpa [mul_add] using (degreeSpan K X (d + 1)).add_mem hx hy
+ · intro k x _ hx
+ simpa [mul_smul_comm] using (degreeSpan K X (d + 1)).smul_mem k hx
+
+/-- Once successive spans agree, closure under each label forces them to
+contain the algebra generated by those labels. -/
+theorem stable_eq_top (X : Label → A) (d : ℕ) (hgen : Algebra.adjoin K (Set.range X) = ⊤)
+ (hstable : degreeSpan K X d = degreeSpan K X (d + 1)) : degreeSpan K X d = ⊤ := by
+ apply eq_top_iff.mpr
+ rw [← Algebra.top_toSubmodule, ← hgen, Algebra.adjoin_toSubmodule_le]
+ intro v hv
+ apply Submonoid.closure_induction_left (motive := fun v _ => v ∈ degreeSpan K X d) _ _ hv
+ · exact Submodule.subset_span (one_mem_monomials X d)
+ · rintro _ ⟨i, rfl⟩ y _ hy
+ exact hstable.symm ▸ generator_mul_mem X i d hy
+
+/-- Monomials through any upper bound on the dimension span the whole algebra. -/
+theorem degreeSpan_eq_top [FiniteDimensional K A] (X : Label → A) (N : ℕ)
+ (hgen : Algebra.adjoin K (Set.range X) = ⊤) (hdim : Module.finrank K A ≤ N) :
+ degreeSpan K X N = ⊤ := by
+ have hgrowth (d : ℕ) : d ≤ Module.finrank K (degreeSpan K X d) ∨ degreeSpan K X d = ⊤ := by
+ induction d with
+ | zero => exact Or.inl (Nat.zero_le _)
+ | succ d ih =>
+ have hle := degreeSpan_mono (K := K) X (Nat.le_succ d)
+ by_cases h : degreeSpan K X d = ⊤
+ · exact Or.inr (top_le_iff.mp (h ▸ hle))
+ · have hne : degreeSpan K X d ≠ degreeSpan K X (d + 1) :=
+ fun hs => h (stable_eq_top X d hgen hs)
+ exact Or.inl ((ih.resolve_right h).trans_lt
+ (Submodule.finrank_lt_finrank_of_lt (lt_of_le_of_ne hle hne)))
+ rcases hgrowth N with h | h
+ · exact Submodule.eq_top_of_finrank_eq ((degreeSpan K X N).finrank_le.antisymm (hdim.trans h))
+ · exact h
+
+/-- The dimension-bounded monomials admit a basis containing the constant
+monomial. The chosen indices themselves are values of bounded monomials. -/
+theorem exists_basis_containing_one [FiniteDimensional K A] [Nontrivial A]
+ (X : Label → A) (N : ℕ) (hgen : Algebra.adjoin K (Set.range X) = ⊤)
+ (hdim : Module.finrank K A ≤ N) :
+ ∃ S : Set A, ∃ b : Module.Basis S K A,
+ (∃ u : S, b u = 1) ∧ Set.range b ⊆ monomials X N := by
+ have hone : LinearIndepOn K id ({1} : Set A) := (linearIndepOn_singleton_iff K).mpr one_ne_zero
+ have hsub : ({1} : Set A) ⊆ monomials X N := Set.singleton_subset_iff.mpr (one_mem_monomials X N)
+ have hspan : ⊤ ≤ Submodule.span K (monomials X N) := (degreeSpan_eq_top X N hgen hdim).ge
+ let b := Module.Basis.extendLe hone hsub hspan
+ refine ⟨_, b, Module.Basis.subset_extendLe hone hsub hspan (Set.mem_singleton 1),
+ Module.Basis.extendLe_subset hone hsub hspan⟩
+
+/-- In any listing of the bounded monomials beginning with the constant,
+the basis selected by the prefix-rank tests in Appendix D.1 consists of the
+retained entries and begins with `1`. This applies also when distinct
+exponents give the same value in the slice algebra. -/
+theorem prefix_basis [FiniteDimensional K A] [Nontrivial A] {m : ℕ}
+ (X : Label → A) (N : ℕ) (hgen : Algebra.adjoin K (Set.range X) = ⊤)
+ (hdim : Module.finrank K A ≤ N) (listing : Fin (m + 1) → A)
+ (hlisting : Set.range listing = monomials X N) (hfirst : listing 0 = 1) :
+ ∃ b : Module.Basis (RankQuery.greedyIndices K listing) K A,
+ (∀ i, b i = listing i.val) ∧ ∃ u, u.val = 0 ∧ b u = 1 := by
+ have hwhole := RankQuery.greedyIndices_span_prefix K listing (m + 1)
+ have hspan : Submodule.span K (listing '' (RankQuery.greedyIndices K listing : Set _)) = ⊤ := by
+ have hall : {i : Fin (m + 1) | i.val < m + 1} = Set.univ :=
+ Set.eq_univ_of_forall (fun i => i.isLt)
+ rw [hall, Set.inter_univ, Set.image_univ, hlisting] at hwhole
+ exact hwhole.trans (degreeSpan_eq_top X N hgen hdim)
+ have heq : Set.range (fun i : RankQuery.greedyIndices K listing => listing i.val) =
+ listing '' (RankQuery.greedyIndices K listing : Set _) := by
+ ext a
+ constructor
+ · rintro ⟨i, rfl⟩
+ exact ⟨i.val, i.property, rfl⟩
+ · rintro ⟨i, hi, rfl⟩
+ exact ⟨⟨i, hi⟩, rfl⟩
+ have hzero : (0 : Fin (m + 1)) ∈ RankQuery.greedyIndices K listing := by
+ rw [RankQuery.mem_greedyIndices, hfirst, show Set.Iio (0 : Fin (m + 1)) = ∅ from Set.Iio_bot]
+ simp
+ let b := Module.Basis.mk (v := fun i : RankQuery.greedyIndices K listing => listing i.val)
+ (RankQuery.greedyIndices_linearIndepOn K listing) (by rw [heq, hspan])
+ exact ⟨b, fun _ => Module.Basis.mk_apply .., ⟨0, hzero⟩, rfl,
+ (Module.Basis.mk_apply ..).trans hfirst⟩
+
+end MonomialBasis
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifAdmission.lean b/lean/OAI/Computability/VPVNP/MotifAdmission.lean
new file mode 100644
index 0000000000..855a29aab7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifAdmission.lean
@@ -0,0 +1,334 @@
+import OAI.Computability.VPVNP.MotifWidths
+import Mathlib.Data.Nat.Sqrt
+import Mathlib.Data.Nat.Size
+
+/-!
+# Integer admission tests for a fixed rational wire motif
+
+Theorem 6.1 of *VP and VNP differ over every field* selects a demand grid
+point and a block repetition count from the input widths. The outer supply
+index is admitted by testing a rational quadratic bound. Clearing the fixed
+mass denominators gives integer algorithms for all three operations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifAdmission
+
+open MotifGrid
+
+variable {I : Type*} [Fintype I]
+
+/-- Common denominator of the reciprocal edge masses. -/
+def denominator (p : I → ℚ) : ℕ := ∏ i, (p i)⁻¹.den
+
+/-- The positive integer coefficient of one squared width after clearing denominators. -/
+def weight (p : I → ℚ) (i : I) : ℕ :=
+ (p i)⁻¹.num.natAbs * (denominator p / (p i)⁻¹.den)
+
+/-- Integral numerator of the squared width norm. -/
+def energy (p : I → ℚ) (b : I → ℕ) : ℕ := ∑ i, weight p i * b i ^ 2
+
+theorem denominator_pos (p : I → ℚ) : 0 < denominator p :=
+ Finset.prod_pos fun i _ => (p i)⁻¹.den_pos
+
+private theorem numerator_cast (r : ℚ) (hr : 0 ≤ r) :
+ (r.num.natAbs : ℝ) = (r.num : ℝ) := by
+ rw [Nat.cast_natAbs, abs_of_nonneg (Rat.num_nonneg.mpr hr)]
+
+private theorem rational_cast (r : ℚ) (hr : 0 ≤ r) :
+ (r : ℝ) = (r.num.natAbs : ℝ) / r.den := by
+ rw [Rat.cast_def, numerator_cast r hr]
+
+private theorem weight_cast (p : I → ℚ) (hp : ∀ i, 0 < p i) (i : I) :
+ (weight p i : ℝ) = (denominator p : ℝ) / (p i : ℝ) := by
+ let r := (p i)⁻¹
+ have hden : r.den ∣ denominator p :=
+ Finset.dvd_prod_of_mem (fun j => (p j)⁻¹.den) (Finset.mem_univ i)
+ have hclear : ((denominator p / r.den : ℕ) : ℝ) * r.den = denominator p := by
+ exact_mod_cast Nat.div_mul_cancel hden
+ have hr : 0 ≤ r := (inv_pos.mpr (hp i)).le
+ have hrpos : (0 : ℝ) < r.den := Nat.cast_pos.mpr r.den_pos
+ change (↑(r.num.natAbs * (denominator p / r.den)) : ℝ) = _
+ calc
+ _ = (r : ℝ) * denominator p := by
+ rw [rational_cast r hr, ← hclear, Nat.cast_mul]
+ field_simp
+ _ = _ := by simp [r, div_eq_mul_inv, mul_comm]
+
+/-- The integral energy with its fixed denominator recovers the real norm. -/
+theorem norm_sq_eq (p : I → ℚ) (hp : ∀ i, 0 < p i) (b : I → ℕ) :
+ widthNorm (realWidths p) (fun i => (b i : ℝ)) ^ 2 = (energy p b : ℝ) / denominator p := by
+ rw [norm_sq (realWidths p) _ (fun i => Rat.cast_pos.mpr (hp i))]
+ apply (eq_div_iff (Nat.cast_ne_zero.mpr (denominator_pos p).ne')).mpr
+ simp only [energy, Nat.cast_sum, Nat.cast_mul, Nat.cast_pow, Finset.sum_mul, realWidths]
+ exact Finset.sum_congr rfl fun i _ => by rw [weight_cast p hp i]; ring
+
+/-- Consume one base-four digit per recursive step. The result with enough
+digits is the binary integer square root. -/
+def sqrtDigits : ℕ → ℕ → ℕ
+ | 0, _ => 0
+ | k + 1, n =>
+ let a := 2 * sqrtDigits k (n / 4)
+ if (a + 1) ^ 2 ≤ n then a + 1 else a
+
+theorem sqrtDigits_eq (k n : ℕ) (hn : n < 4 ^ k) : sqrtDigits k n = n.sqrt := by
+ induction k generalizing n with
+ | zero =>
+ have h0 : n = 0 := Nat.lt_one_iff.mp hn
+ simp [h0, sqrtDigits]
+ | succ k ih =>
+ have hd : n / 4 < 4 ^ k :=
+ (Nat.div_lt_iff_lt_mul (by decide)).mpr (by simpa [pow_succ] using hn)
+ let r := (n / 4).sqrt
+ have hlo : (2 * r) ^ 2 ≤ n := by
+ have h := (Nat.le_div_iff_mul_le (by decide : 0 < 4)).mp (Nat.sqrt_le' (n / 4))
+ calc
+ (2 * r) ^ 2 = r ^ 2 * 4 := by ring
+ _ ≤ n := h
+ have hhi : n < (2 * r + 1 + 1) ^ 2 := by
+ have h := (Nat.div_lt_iff_lt_mul (by decide : 0 < 4)).mp (Nat.lt_succ_sqrt' (n / 4))
+ calc
+ n < (r + 1) ^ 2 * 4 := h
+ _ = (2 * r + 1 + 1) ^ 2 := by ring
+ simp only [sqrtDigits, ih _ hd]
+ change (if (2 * r + 1) ^ 2 ≤ n then 2 * r + 1 else 2 * r) = n.sqrt
+ split
+ · rename_i h
+ exact Nat.eq_sqrt'.mpr ⟨h, hhi⟩
+ · rename_i h
+ exact Nat.eq_sqrt'.mpr ⟨hlo, Nat.lt_of_not_ge h⟩
+
+/-- Executable floor square root of a rational energy. Binary input length
+bounds the number of recursive steps. -/
+def floorRoot (n d : ℕ) : ℕ :=
+ let m := n / d
+ sqrtDigits m.size m
+
+theorem floorRoot_eq (n d : ℕ) : floorRoot n d = (n / d).sqrt := by
+ apply sqrtDigits_eq
+ exact (Nat.lt_size_self _).trans_le (Nat.pow_le_pow_left (by decide : 2 ≤ 4) _)
+
+theorem sqrtDigit_operand_le (n : ℕ) : (2 * (n / 4).sqrt + 1) ^ 2 ≤ 4 * (n + 1) := by
+ let r := (n / 4).sqrt
+ have hlo : r ^ 2 * 4 ≤ n :=
+ (Nat.le_div_iff_mul_le (by decide : 0 < 4)).mp (Nat.sqrt_le' (n / 4))
+ have hr : r ≤ r ^ 2 := Nat.le_self_pow (by decide) r
+ change (2 * r + 1) ^ 2 ≤ 4 * (n + 1)
+ nlinarith only [hlo, hr, Nat.zero_le (r ^ 2)]
+
+/-- Ceiling of the square root of an unsigned fraction. At a perfect square
+the decrement prevents a spurious additional copy. -/
+def ceilRoot (n d : ℕ) : ℕ :=
+ if n = 0 then 0 else floorRoot (n - 1) d + 1
+
+theorem ceilRoot_le_iff (n d k : ℕ) (hd : 0 < d) :
+ ceilRoot n d ≤ k ↔ n ≤ k ^ 2 * d := by
+ by_cases hn : n = 0
+ · simp [hn, ceilRoot]
+ · rw [ceilRoot, ite_eq_right hn, floorRoot_eq, Nat.succ_le_iff, Nat.sqrt_lt',
+ Nat.div_lt_iff_lt_mul hd]
+ omega
+
+/-- Executable number of block repetitions. -/
+def copies (p : I → ℚ) (b : I → ℕ) (L : ℕ) : ℕ :=
+ ceilRoot (energy p b) (L ^ 2 * denominator p)
+
+/-- The integer calculation gives the ceiling used in the real width estimate. -/
+theorem copies_eq (p : I → ℚ) (hp : ∀ i, 0 < p i) (b : I → ℕ) (L : ℕ) (hL : 0 < L) :
+ copies p b L = MotifWidths.copies (widthNorm (realWidths p) (fun i => b i)) L := by
+ apply eq_of_forall_ge_iff
+ intro k
+ have hn : 0 ≤ widthNorm (realWidths p) (fun i => (b i : ℝ)) := Real.sqrt_nonneg _
+ rw [copies, ceilRoot_le_iff _ _ _ (Nat.mul_pos (pow_pos hL _) (denominator_pos p)),
+ MotifWidths.copies, Nat.ceil_le, div_le_iff₀ (Nat.cast_pos.mpr hL),
+ ← sq_le_sq₀ hn (mul_nonneg (Nat.cast_nonneg k) (Nat.cast_nonneg L)),
+ norm_sq_eq p hp b, div_le_iff₀ (Nat.cast_pos.mpr (denominator_pos p)), mul_pow, mul_assoc]
+ norm_cast
+
+/-- Test the two integer sides of the payload constraint. -/
+def admit (q : I → ℚ) (v : I → ℕ) (u L : ℕ) (R : ℚ) : Bool :=
+ decide (energy q v * R.den ^ 2 ≤ (u * L * R.num.natAbs) ^ 2 * denominator q)
+
+theorem admit_eq_true_iff (q : I → ℚ) (hq : ∀ i, 0 < q i) (v : I → ℕ)
+ (u L : ℕ) (R : ℚ) (hR : 0 ≤ R) :
+ admit q v u L R = true ↔
+ widthNorm (realWidths q) (fun i => v i) ≤ (u : ℝ) * L * (R : ℝ) := by
+ have hn : 0 ≤ widthNorm (realWidths q) (fun i => (v i : ℝ)) := Real.sqrt_nonneg _
+ have hRden : (0 : ℝ) < R.den := Nat.cast_pos.mpr R.den_pos
+ rw [admit, decide_eq_true_eq, rational_cast R hR, ← mul_div_assoc, le_div_iff₀ hRden,
+ ← sq_le_sq₀ (mul_nonneg hn hRden.le) (show 0 ≤ (u : ℝ) * L * R.num.natAbs by positivity),
+ mul_pow (widthNorm _ _), norm_sq_eq q hq v, div_mul_eq_mul_div,
+ div_le_iff₀ (Nat.cast_pos.mpr (denominator_pos q))]
+ norm_cast
+
+/-- Check that a nonnegative rational grid point dominates the normalized
+demand in one coordinate, without division by the demand norm. -/
+def coversCoordinate (p : I → ℚ) (b : I → ℕ) (i : I) (r : ℚ) : Bool :=
+ decide (0 ≤ r ∧
+ (b i * r.den) ^ 2 * denominator p ≤ energy p b * r.num.natAbs ^ 2)
+
+theorem coversCoordinate_eq_true_iff (p : I → ℚ) (hp : ∀ i, 0 < p i)
+ (b : I → ℕ) (i : I) (r : ℚ) :
+ coversCoordinate p b i r = true ↔ 0 ≤ r ∧
+ (b i : ℝ) ≤ widthNorm (realWidths p) (fun j => b j) * (r : ℝ) := by
+ rw [coversCoordinate, decide_eq_true_eq, and_congr_right_iff]
+ intro hr
+ have hrd : (0 : ℝ) < r.den := Nat.cast_pos.mpr r.den_pos
+ have hn : 0 ≤ widthNorm (realWidths p) (fun j => (b j : ℝ)) := Real.sqrt_nonneg _
+ rw [rational_cast r hr, ← mul_div_assoc, le_div_iff₀ hrd,
+ ← sq_le_sq₀ (mul_nonneg (Nat.cast_nonneg _) hrd.le) (mul_nonneg hn (Nat.cast_nonneg _)),
+ mul_pow (widthNorm _ _), norm_sq_eq p hp b, div_mul_eq_mul_div,
+ le_div_iff₀ (Nat.cast_pos.mpr (denominator_pos p))]
+ norm_cast
+
+/-- Choose the first covering point in a fixed ordering of the finite demand grid. -/
+def selectGrid (p : I → ℚ) (b : I → ℕ) (table : List (I → ℚ)) : Option (I → ℚ) :=
+ table.find? (fun z => decide (∀ i, coversCoordinate p b i (z i) = true))
+
+theorem selectGrid_spec (p : I → ℚ) (hp : ∀ i, 0 < p i) (b : I → ℕ)
+ {table : List (I → ℚ)} {z : I → ℚ} (h : selectGrid p b table = some z) :
+ z ∈ table ∧ ∀ i, 0 ≤ z i ∧
+ (b i : ℝ) ≤ widthNorm (realWidths p) (fun j => b j) * (z i : ℝ) := by
+ refine ⟨List.mem_of_find?_eq_some h, fun i => (coversCoordinate_eq_true_iff p hp b i _).mp ?_⟩
+ have hz := List.find?_some (p := fun w : I → ℚ =>
+ decide (∀ j, coversCoordinate p b j (w j) = true)) h
+ exact (of_decide_eq_true hz) i
+
+/-- The strict demand grids have a covering entry, including at zero demand
+where each coordinate of the demand vanishes. The choice depends only on the
+ordered table, masses, and input widths. -/
+theorem selectGrid_exists {S : Type*} [Fintype S] (p : I → ℚ) (hp : ∀ i, 0 < p i)
+ {q : S → ℝ} {H R : ℝ} (G : StrictGrids (realWidths p) q H R)
+ (b : I → ℕ) (table : List (I → ℚ)) (htable : ∀ z ∈ G.demands, z ∈ table) :
+ ∃ z, selectGrid p b table = some z := by
+ let N := widthNorm (realWidths p) (fun i => (b i : ℝ))
+ have hn : 0 ≤ N := Real.sqrt_nonneg _
+ let x := fun i => N⁻¹ * (b i : ℝ)
+ have hx i : 0 ≤ x i := mul_nonneg (inv_nonneg.mpr hn) (Nat.cast_nonneg _)
+ have hnorm : widthNorm (realWidths p) x ≤ 1 := by
+ rw [show x = (fun i => N⁻¹ * (b i : ℝ)) from rfl, widthNorm_scale _ _ (inv_nonneg.mpr hn)]
+ change N⁻¹ * N ≤ 1
+ rcases eq_or_ne N 0 with he | he <;> simp [he]
+ obtain ⟨z, hz, hcov⟩ := G.cover x hx hnorm
+ apply Option.isSome_iff_exists.mp
+ apply List.find?_isSome.mpr
+ refine ⟨z, htable z hz, decide_eq_true ?_⟩
+ intro i
+ refine (coversCoordinate_eq_true_iff p hp b i _).mpr
+ ⟨Rat.cast_nonneg.mp ((hx i).trans (hcov i).1), ?_⟩
+ change (b i : ℝ) ≤ N * (z i : ℝ)
+ rcases hn.eq_or_lt with h0 | hpos
+ · have h := coordinate_le (realWidths p) (fun j => (b j : ℝ))
+ (fun j => Rat.cast_pos.mpr (hp j)) i
+ change (b i : ℝ) ≤ _ * N at h
+ simpa [← h0] using h
+ · have h := mul_le_mul_of_nonneg_left (hcov i).1 hn
+ dsimp only [x] at h
+ rwa [← mul_assoc, mul_inv_cancel₀ hpos.ne', one_mul] at h
+
+/-- Every variable energy accumulator, including intermediate partial sums
+of its nonnegative summands, has a fixed quadratic magnitude bound. -/
+theorem energy_le (p : I → ℚ) (b : I → ℕ) (M : ℕ) (hb : ∀ i, b i ≤ M) :
+ energy p b ≤ (∑ i, weight p i) * M ^ 2 := by
+ rw [energy, Finset.sum_mul]
+ exact Finset.sum_le_sum fun i _ => Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (hb i) 2)
+
+/-- A fixed coefficient bounds the repetition count linearly in the input width. -/
+theorem copies_le (p : I → ℚ) (b : I → ℕ) (L M : ℕ) (hL : 0 < L)
+ (hb : ∀ i, b i ≤ M) : copies p b L ≤ ((∑ i, weight p i) + 1) * (M + 1) := by
+ let W := ∑ i, weight p i
+ apply (ceilRoot_le_iff _ _ _ (Nat.mul_pos (pow_pos hL _) (denominator_pos p))).mpr
+ have hW : W ≤ (W + 1) ^ 2 :=
+ (Nat.le_succ _).trans (Nat.le_self_pow (by decide) _)
+ calc
+ energy p b ≤ W * M ^ 2 := energy_le p b M hb
+ _ ≤ (W + 1) ^ 2 * (M + 1) ^ 2 :=
+ Nat.mul_le_mul hW (Nat.pow_le_pow_left (Nat.le_succ _) 2)
+ _ = ((W + 1) * (M + 1)) ^ 2 := (mul_pow _ _ _).symm
+ _ ≤ _ := Nat.le_mul_of_pos_right _ (Nat.mul_pos (pow_pos hL _) (denominator_pos p))
+
+/-- A finite search box containing every admitted outer payload. -/
+def payloadCap (q : I → ℚ) (u L : ℕ) (R : ℚ) : ℕ :=
+ u * L * R.num.natAbs * denominator q
+
+theorem payload_le_cap (q : I → ℚ) (hq : ∀ i, 0 < q i) (v : I → ℕ)
+ (u L : ℕ) (R : ℚ) (hv : admit q v u L R = true) (i : I) :
+ v i ≤ payloadCap q u L R := by
+ have hwreal : (0 : ℝ) < weight q i := by
+ rw [weight_cast q hq i]
+ exact div_pos (Nat.cast_pos.mpr (denominator_pos q)) (Rat.cast_pos.mpr (hq i))
+ have hw : 0 < weight q i := Nat.cast_pos.mp hwreal
+ have he : v i ^ 2 ≤ energy q v :=
+ (Nat.le_mul_of_pos_left _ hw).trans
+ (Finset.single_le_sum (f := fun j => weight q j * v j ^ 2) (fun j _ => Nat.zero_le _)
+ (Finset.mem_univ i))
+ apply (Nat.pow_le_pow_iff_left (n := 2) (by decide)).mp
+ rw [payloadCap, mul_pow]
+ exact (he.trans (Nat.le_mul_of_pos_right _ (pow_pos R.den_pos 2))).trans
+ ((of_decide_eq_true hv).trans (Nat.mul_le_mul_left _ (Nat.le_self_pow (by decide) _)))
+
+/-- Explicit quadratic bounds on both integers compared by the payload test
+on a linearly sized candidate box. -/
+theorem admit_operands_le (q : I → ℚ) (v : I → ℕ) (u L : ℕ) (R : ℚ) (K M : ℕ)
+ (hu : u ≤ K * (M + 1)) (hv : ∀ i, v i ≤ K * (M + 1)) :
+ energy q v * R.den ^ 2 ≤ ((∑ i, weight q i) * K ^ 2 * R.den ^ 2) * (M + 1) ^ 2 ∧
+ (u * L * R.num.natAbs) ^ 2 * denominator q ≤
+ ((K * L * R.num.natAbs) ^ 2 * denominator q) * (M + 1) ^ 2 := by
+ constructor
+ · apply (Nat.mul_le_mul_right (R.den ^ 2) (energy_le q v _ hv)).trans_eq
+ ring
+ · have h := Nat.mul_le_mul_right (denominator q) <|
+ Nat.pow_le_pow_left (Nat.mul_le_mul_right R.num.natAbs (Nat.mul_le_mul_right L hu)) 2
+ exact h.trans_eq (by ring)
+
+/-- Quadratic bounds for the integer comparisons used to select a grid point.
+Both coefficients are fixed for a fixed grid table. -/
+theorem grid_operands_le (p : I → ℚ) (b : I → ℕ) (M : ℕ) (hb : ∀ i, b i ≤ M)
+ (i : I) (r : ℚ) :
+ (b i * r.den) ^ 2 * denominator p ≤ (r.den ^ 2 * denominator p) * (M + 1) ^ 2 ∧
+ energy p b * r.num.natAbs ^ 2 ≤
+ ((∑ j, weight p j) * r.num.natAbs ^ 2) * (M + 1) ^ 2 := by
+ have hb' j : b j ≤ M + 1 := (hb j).trans (Nat.le_succ M)
+ constructor
+ · apply (Nat.mul_le_mul_right (denominator p) (Nat.pow_le_pow_left
+ (Nat.mul_le_mul_right r.den (hb' i)) 2)).trans_eq
+ ring
+ · apply (Nat.mul_le_mul_right (r.num.natAbs ^ 2) (energy_le p b _ hb')).trans_eq
+ ring
+
+/-- Quadratically bounded operands have bit length at most a constant plus
+twice the binary logarithm of the input width. -/
+theorem operand_bits_le (a K M : ℕ) (ha : a ≤ K * (M + 1) ^ 2) :
+ a.size ≤ K.size + 2 * Nat.clog 2 (M + 1) := by
+ apply Nat.size_le.mpr
+ rw [pow_add, Nat.mul_comm 2, pow_mul]
+ apply ha.trans_lt
+ exact mul_lt_mul_of_lt_of_le_of_pos_of_nonneg (Nat.lt_size_self K)
+ (Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) 2) (by positivity) (by positivity)
+
+/-- The finite payload search box is linear in the original maximum width. -/
+theorem payloadCap_le {J : Type*} [Fintype J] (p : I → ℚ) (q : J → ℚ)
+ (b : I → ℕ) (L M : ℕ) (R : ℚ) (hL : 0 < L) (hb : ∀ i, b i ≤ M) :
+ payloadCap q (copies p b L) L R ≤
+ (((∑ i, weight p i) + 1) * L * R.num.natAbs * denominator q) * (M + 1) := by
+ apply (Nat.mul_le_mul_right (denominator q) (Nat.mul_le_mul_right R.num.natAbs
+ (Nat.mul_le_mul_right L (copies_le p b L M hL hb)))).trans_eq
+ ring
+
+/-- The recursion depth in the executable ceiling test is bounded in terms
+of the original maximum width and the fixed mass coefficients. -/
+theorem copies_root_steps_le (p : I → ℚ) (b : I → ℕ) (L M : ℕ) (hb : ∀ i, b i ≤ M) :
+ ((energy p b - 1) / (L ^ 2 * denominator p)).size ≤
+ (∑ i, weight p i).size + 2 * Nat.clog 2 (M + 1) := by
+ apply operand_bits_le
+ exact (Nat.div_le_self _ _).trans <| (Nat.sub_le _ _).trans <|
+ energy_le p b (M + 1) (fun i => (hb i).trans (Nat.le_succ M))
+
+end MotifAdmission
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifBase.lean b/lean/OAI/Computability/VPVNP/MotifBase.lean
new file mode 100644
index 0000000000..0f3170e640
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifBase.lean
@@ -0,0 +1,178 @@
+import OAI.Computability.VPVNP.TensorSpectralComparison
+import OAI.Computability.VPVNP.MotifWirePowers
+import OAI.Computability.VPVNP.MotifOrdinarySum
+import OAI.Computability.VPVNP.MotifSupplyEnergy
+import OAI.Computability.VPVNP.MotifWidths
+
+/-!
+# Fixed base identities for wire motifs
+
+In Theorem 6.1, a finite supply grid beats each demand grid point at every
+spectral point. The supply witness may depend on the spectral point.
+Taking the direct sum of the supply grid and applying strict comparison
+yields one copy bound for all powers. Distributing the powers yields actual
+ordinary sums of local maps. Each summand is indexed by one copy and an
+ordered list of grid points, with widths added edge by edge.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifBase
+
+open WireTensor WireTensor.RestrictionClass
+
+universe u v
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nontrivial J]
+variable {D S : Type} [Fintype D] [Fintype S] {W Z : Type*} [Fintype W] [Finite Z]
+
+/-- The ordinary tensor of binary equality wires with a given integer width profile. -/
+noncomputable abbrev binaryWires {k : Type u} [CommSemiring k] {E : Type} [Fintype E]
+ (a b : E → J) (width : E → ℕ) :
+ Tensor.{u,v,0} k J := wireNetwork a b (fun e ↦ Fin (2 ^ width e))
+
+/-- The supply widths of a selector are the totals of the selected grid profiles. -/
+def payload {h : ℕ} (w : W → S → ℕ) (σ : Fin h → W) (e : S) : ℕ := ∑ i, w (σ i) e
+
+/-- The base identity (6.2) before grouping repeated copies by payload. -/
+def BaseIdentity (k : Type u) [CommSemiring k] {J : Type v} [Fintype J]
+ (a b : D → J) (c d : S → J) (z : D → ℕ) (w : W → S → ℕ) (K h : ℕ) : Prop :=
+ let X := binaryWires (k := k) a b (fun e ↦ h * z e)
+ let T (σ : Fin K × (Fin h → W)) := binaryWires (k := k) c d (payload w σ.2)
+ ∃ L : ∀ σ j, X.Basis j → (T σ).Basis j → k, X.coeff = ∑ σ, applyLocal (L σ) (T σ).coeff
+
+/-- The supply profile in the strict width comparison can vary with the spectral point. -/
+def StrictAtSpectrum (k : Type u) [Field k] {J : Type v} [Fintype J]
+ (a b : D → J) (c d : S → J) (z : D → ℕ) (w : W → S → ℕ) : Prop :=
+ ∀ F : SpectralPoint k J, ∃ i : W,
+ (∑ e, (z e : ℝ) * F.wireDistance (a e) (b e)) <
+ ∑ e, (w i e : ℝ) * F.wireDistance (c e) (d e)
+
+private theorem selector_expansion {A : Type*} [CommSemiring A] (y : W → A) (K h : ℕ) :
+ (K : A) * (∑ i, y i) ^ h =
+ ∑ σ : Fin K × (Fin h → W), ∏ j, y (σ.2 j) := by
+ rw [Fintype.sum_pow, Fintype.sum_prod_type]
+ simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul]
+
+private theorem copy_bound (a b : D → J) (c d : S → J) (z : D → ℕ) (w : W → S → ℕ)
+ (hs : StrictAtSpectrum k a b c d z w) :
+ ∃ K : ℕ, 1 ≤ K ∧ ∀ h : ℕ,
+ binaryNetworkClass (k := k) a b z ^ h ≤
+ (K : RestrictionClass k J) * (∑ i, binaryNetworkClass c d (w i)) ^ h := by
+ classical
+ let a₀ := Classical.choice (inferInstance : Nonempty J)
+ let rank := flatteningRankHom (k := k) a₀
+ let : CharZero (RestrictionClass k J) := rank.charZero
+ let X := binaryNetworkClass (k := k) a b z
+ let Y : RestrictionClass k J := ∑ i, binaryNetworkClass c d (w i)
+ have comp (f : RestrictionClass k J →+* ℝ) (hf : Monotone f) : f X < f Y := by
+ let F := toSpectralPoint f hf
+ obtain ⟨i, hi⟩ := hs F
+ have h₁ : f X < f (binaryNetworkClass c d (w i)) := by
+ change (F.value (binaryWires a b z) : ℝ) < (F.value (binaryWires c d (w i)) : ℝ)
+ rw [F.value_binary_wireNetwork, F.value_binary_wireNetwork]
+ exact Real.rpow_lt_rpow_of_exponent_lt (by norm_num) hi
+ change _ < f (∑ j, binaryNetworkClass c d (w j))
+ rw [map_sum]
+ exact h₁.trans_le (Finset.single_le_sum
+ (fun j _ ↦ by simpa using hf (orderBounds.zero_le (binaryNetworkClass c d (w j))))
+ (Finset.mem_univ i))
+ have hy : Y ≠ 0 := by
+ intro hY
+ let F := flatteningPoint (k := k) a₀
+ have hm := ofSpectralPoint_monotone F
+ have hx := comp (ofSpectralPoint F) hm
+ rw [hY, map_zero] at hx
+ exact hx.not_ge (by simpa using hm (orderBounds.zero_le X))
+ exact Spectral.strict_spectral_comparison orderBounds rank (flatteningRankHom_monotone a₀) hy comp
+
+private theorem baseIdentity_of_bound (a b : D → J) (c d : S → J) (z : D → ℕ) (w : W → S → ℕ)
+ {K h : ℕ} (bound : binaryNetworkClass (k := k) a b z ^ h ≤
+ (K : RestrictionClass k J) * (∑ i, binaryNetworkClass c d (w i)) ^ h) :
+ BaseIdentity k a b c d z w K h := by
+ classical
+ apply ordinary_sum_of_class_le
+ change binaryNetworkClass (k := k) a b (fun e ↦ h * z e) ≤
+ ∑ σ : Fin K × (Fin h → W), binaryNetworkClass c d (payload w σ.2)
+ rw [binaryNetworkClass_pow]
+ rw [selector_expansion] at bound
+ have term (σ : Fin K × (Fin h → W)) :
+ binaryNetworkClass (k := k) c d (payload w σ.2) =
+ ∏ j, binaryNetworkClass c d (w (σ.2 j)) :=
+ binaryNetworkClass_sum c d Finset.univ (fun j ↦ w (σ.2 j))
+ simp_rw [term]
+ exact bound
+
+private theorem cast_mono {n m : ℕ} (h : n ≤ m) :
+ (n : RestrictionClass k J) ≤ (m : RestrictionClass k J) := by
+ obtain ⟨r, rfl⟩ := Nat.exists_eq_add_of_le h
+ simpa only [Nat.cast_add, add_zero] using
+ orderBounds.add_mono (le_refl (n : RestrictionClass k J)) (orderBounds.zero_le (r : _))
+
+/-- A single copy count gives base identities for every demand profile in a
+finite grid and every power, over the specified field. -/
+theorem uniform_base_identity (a b : D → J) (c d : S → J) (z : Z → D → ℕ) (w : W → S → ℕ)
+ (hs : ∀ j, StrictAtSpectrum k a b c d (z j) w) :
+ ∃ K : ℕ, 1 ≤ K ∧ ∀ j h, BaseIdentity k a b c d (z j) w K h := by
+ classical
+ let := Fintype.ofFinite Z
+ choose K _ hbound using fun j ↦ copy_bound a b c d (z j) w (hs j)
+ let N := (∑ j, K j) + 1
+ refine ⟨N, Nat.le_add_left _ _, fun j h ↦ baseIdentity_of_bound _ _ _ _ _ _ ?_⟩
+ have hj : K j ≤ N := (Finset.single_le_sum (fun i _ ↦ Nat.zero_le (K i))
+ (Finset.mem_univ j)).trans (Nat.le_succ _)
+ apply (hbound j h).trans
+ simpa only [mul_comm] using
+ orderBounds.mul_mono ((∑ i, binaryNetworkClass (k := k) c d (w i)) ^ h) (cast_mono hj)
+
+open MotifGrid
+
+variable {p : D → ℝ} {q : S → ℝ} {H R : ℝ}
+
+/-- The weighted comparison (6.1) gives a simultaneous base identity on the
+integer width grid at every positive denominator multiple. -/
+theorem connected_grid_base_identity (G : StrictGrids p q H R) (a b : D → J)
+ (P : MotifSelector.Supply J S) (hq : ∀ e, 0 < q e)
+ (hcomp : ∀ F : SpectralPoint k J, distanceEnergy p (fun i ↦ F.wireDistance (a i) (b i)) ≤
+ H * distanceEnergy q (fun i ↦ F.wireDistance (P.src i) (P.dst i)))
+ {t : ℕ} (ht : 0 < t) :
+ ∃ K : ℕ, 1 ≤ K ∧ ∀ (z : G.demands) h, BaseIdentity k a b P.src P.dst
+ (G.demandWidths t z) (G.supplyWidths t) K h := by
+ apply uniform_base_identity
+ intro z F
+ exact G.integer_strict ht z _ _ (fun e ↦ F.wireDistance_nonneg _ _)
+ (F.connected_distanceEnergy_pos P.src P.dst P.color_eq_of_connected q hq) (hcomp F)
+
+/-- Choosing the denominator multiple before the tensor power makes the
+selector fraction as small as prescribed. The same base identity works for
+all rounded demand profiles and bounds the norm of every selector's payload. -/
+theorem exists_base_block (G : StrictGrids p q H R) (a b : D → J)
+ (P : MotifSelector.Supply J S) (hq : ∀ e, 0 < q e)
+ (hcomp : ∀ F : SpectralPoint k J, distanceEnergy p (fun i ↦ F.wireDistance (a i) (b i)) ≤
+ H * distanceEnergy q (fun i ↦ F.wireDistance (P.src i) (P.dst i)))
+ {δ : ℝ} (hδ : 0 < δ) :
+ ∃ (t h K : ℕ), 0 < t ∧ 0 < h ∧ 1 ≤ K ∧
+ (MotifWidths.selectorBits K G.supplies.card h : ℝ) / (h * (t * G.denominator) : ℝ) < δ ∧
+ (∀ z : G.demands, BaseIdentity k a b P.src P.dst
+ (G.demandWidths t z) (G.supplyWidths t) K h) ∧
+ ∀ σ : Fin h → G.supplies, widthNorm q (fun e ↦ (payload (G.supplyWidths t) σ e : ℝ)) ≤
+ (h * (t * G.denominator) : ℕ) * R := by
+ classical
+ have atScale (t : ℕ) : ∃ K : ℕ, 1 ≤ K ∧ (0 < t → ∀ (z : G.demands) h,
+ BaseIdentity k a b P.src P.dst (G.demandWidths t z) (G.supplyWidths t) K h) := by
+ by_cases ht : 0 < t
+ · obtain ⟨K, hK, hbase⟩ := connected_grid_base_identity G a b P hq hcomp ht
+ exact ⟨K, hK, fun _ ↦ hbase⟩
+ · exact ⟨1, le_rfl, fun h ↦ (ht h).elim⟩
+ choose K hK hbase using atScale
+ obtain ⟨t, h, ht, hh, hover⟩ := MotifWidths.exists_selector_block G.denominator
+ G.supplies.card G.denominator_pos K hδ
+ exact ⟨t, h, K t, ht, hh, hK t, hover, fun z ↦ hbase t ht z h,
+ MotifWidths.base_payload_bound G hq t h⟩
+
+end MotifBase
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifBlocks.lean b/lean/OAI/Computability/VPVNP/MotifBlocks.lean
new file mode 100644
index 0000000000..73df03a4c5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifBlocks.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.MotifBase
+
+/-!
+# Fixed block of wire identities for all demand widths
+
+Theorem 6.1 of *VP and VNP differ over every field* chooses its rational
+grids, common denominator multiple, tensor power, selector size and local
+maps before seeing the demand widths. Only the rounded grid point, number of
+repetitions and payload change with the widths. The energy error is uniform.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifBlocks
+
+open MotifGrid MotifBase WireTensor
+
+universe u v
+variable {k : Type u} [Field k] {J : Type v} [Fintype J]
+variable {D S : Type} [Fintype D] [Fintype S]
+
+/-- Data fixed before the demand widths are supplied, including the local
+base identities and the global additive error in the width energy. -/
+structure FixedBlock (k : Type u) [Field k] (a b : D → J) (P : MotifSelector.Supply J S)
+ (p : D → ℝ) (q : S → ℝ) (H H' : ℝ) where
+ /-- Positive rational radius bounding the supply-width grid. -/
+ radius : ℚ
+ radius_pos : 0 < radius
+ /-- Strict demand and supply grids for the chosen masses, spectral comparison, and radius. -/
+ grid : StrictGrids p q H (radius : ℝ)
+ /-- Common positive multiplier used with the grid denominator to obtain integer wire widths. -/
+ multiple : ℕ
+ /-- Positive tensor power used in the fixed base identities. -/
+ power : ℕ
+ /-- Number of summands indexed by the copy selector in each base identity. -/
+ copyCount : ℕ
+ multiple_pos : 0 < multiple
+ power_pos : 0 < power
+ copyCount_pos : 0 < copyCount
+ baseIdentity : ∀ z : grid.demands, BaseIdentity k a b P.src P.dst
+ (grid.demandWidths multiple z) (grid.supplyWidths multiple) copyCount power
+ base_payload_le : ∀ σ : Fin power → grid.supplies,
+ widthNorm q (fun i ↦ (payload (grid.supplyWidths multiple) σ i : ℝ)) ≤
+ (power * (multiple * grid.denominator) : ℕ) * radius
+ select : ∀ w : D → ℕ, ∃ z : grid.demands, ∀ i,
+ w i ≤ MotifWidths.copies (widthNorm p (fun j ↦ (w j : ℝ)))
+ (power * (multiple * grid.denominator)) *
+ (power * grid.demandWidths multiple z i)
+ /-- Uniform additive constant in the squared supply-energy bound after selector padding. -/
+ energyConstant : ℝ
+ padded_energy_le : ∀ (w : D → ℕ) (v : S → ℕ),
+ let L := power * (multiple * grid.denominator)
+ let s := MotifWidths.selectorBits copyCount grid.supplies.card power
+ let N := widthNorm p (fun i ↦ (w i : ℝ))
+ let u := MotifWidths.copies N L
+ widthNorm q (fun i ↦ (v i : ℝ)) ≤ (u : ℝ) * L * radius →
+ widthNorm q (fun i ↦ (v i + u * s : ℕ)) ^ 2 ≤ H' * N ^ 2 + energyConstant
+
+namespace FixedBlock
+
+variable {a b : D → J} {P : MotifSelector.Supply J S} {p : D → ℝ} {q : S → ℝ} {H H' : ℝ}
+variable (B : FixedBlock k a b P p q H H')
+
+/-- Width scale of one fixed base identity. -/
+def scale : ℕ := B.power * (B.multiple * B.grid.denominator)
+
+/-- Bits used to choose a direct-sum copy and the supply profile in each factor. -/
+def selectorBits : ℕ := MotifWidths.selectorBits B.copyCount B.grid.supplies.card B.power
+
+/-- Number of fixed blocks required by the integer demand. -/
+noncomputable def repetitions (w : D → ℕ) : ℕ :=
+ MotifWidths.copies (widthNorm p (fun i ↦ w i)) B.scale
+
+theorem scale_pos : 0 < B.scale :=
+ Nat.mul_pos B.power_pos (Nat.mul_pos B.multiple_pos B.grid.denominator_pos)
+
+/-- Every actual selector sequence is admitted by the numerical payload bound. -/
+theorem sequence_payload_le (hq : ∀ i, 0 < q i) (n : ℕ)
+ (σ : Fin n → Fin B.power → B.grid.supplies) :
+ widthNorm q (fun i ↦ ((∑ j, payload (B.grid.supplyWidths B.multiple) (σ j) i : ℕ) : ℝ)) ≤
+ (n : ℝ) * B.scale * B.radius := by
+ push_cast
+ calc
+ _ ≤ ∑ j, widthNorm q (fun i ↦ (payload (B.grid.supplyWidths B.multiple) (σ j) i : ℝ)) :=
+ MotifWidths.widthNorm_sum_le q hq _
+ _ ≤ ∑ _j : Fin n, (B.scale : ℝ) * (B.radius : ℝ) :=
+ Finset.sum_le_sum fun j _ ↦ B.base_payload_le (σ j)
+ _ = _ := by simp [mul_assoc]
+
+end FixedBlock
+
+/-- From the paper's spectral inequality obtain one block whose repetitions
+cover every nonnegative integer demand and obey the stated energy estimate. -/
+theorem exists_fixed_block [Nontrivial J] (a b : D → J) (P : MotifSelector.Supply J S)
+ (p : D → ℝ) (q : S → ℝ) (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) {H H' : ℝ}
+ (hH : 0 ≤ H) (hHH' : H < H')
+ (hcomp : ∀ F : SpectralPoint k J, distanceEnergy p (fun i ↦ F.wireDistance (a i) (b i)) ≤
+ H * distanceEnergy q (fun i ↦ F.wireDistance (P.src i) (P.dst i))) :
+ Nonempty (FixedBlock k a b P p q H H') := by
+ obtain ⟨R, hR₁, hR₂⟩ := exists_rat_btwn (Real.sqrt_lt_sqrt hH hHH')
+ have hR : 0 < (R : ℝ) := (Real.sqrt_nonneg H).trans_lt hR₁
+ obtain ⟨G⟩ := exists_strict_grids p q hp hq hH hR₁
+ obtain ⟨δ, hδ, htol⟩ := MotifWidths.exists_selector_tolerance (R : ℝ)
+ (widthNorm q (fun _ ↦ 1)) H' hR.le (Real.sqrt_nonneg _) hR₂
+ obtain ⟨t, h, K, ht, hh, hK, hfrac, hbase, hpayload⟩ :=
+ exists_base_block G a b P hq hcomp hδ
+ let s := MotifWidths.selectorBits K G.supplies.card h
+ let L := h * (t * G.denominator)
+ have hL : 0 < L := Nat.mul_pos hh (Nat.mul_pos ht G.denominator_pos)
+ have hfrac' : (s : ℝ) / L < δ := by simpa [s, L] using hfrac
+ have hbudget := htol ((s : ℝ) / L) (by positivity) hfrac'
+ obtain ⟨C, hbound⟩ := MotifWidths.padded_energy_le q hq hL hR.le hbudget
+ refine ⟨⟨R, Rat.cast_pos.mp hR, G, t, h, K, ht, hh, hK, hbase, hpayload,
+ MotifWidths.exists_padded_grid G hp t h ht hh, C, ?_⟩⟩
+ intro w v
+ exact hbound (widthNorm p (fun i ↦ (w i : ℝ))) v (Real.sqrt_nonneg _)
+
+end MotifBlocks
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifConversion.lean b/lean/OAI/Computability/VPVNP/MotifConversion.lean
new file mode 100644
index 0000000000..c7a3370f2b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifConversion.lean
@@ -0,0 +1,351 @@
+import OAI.Computability.VPVNP.MotifBlocks
+import OAI.Computability.VPVNP.MotifAdmission
+import OAI.Computability.VPVNP.MotifParameters
+import OAI.Computability.VPVNP.MotifPowerExpansion
+import OAI.Computability.VPVNP.MotifEntry
+
+/-!
+# Conversion of a fixed wire motif
+
+Theorem 6.1 of *VP and VNP differ over every field* converts the spectral
+inequality (6.1) into ordinary tensor identities. All scalar parameters and
+their integer equations are chosen before the input widths. A local matrix
+entry is represented independently of the coefficient ring by either failure
+or the list of parameter indices whose product is the entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifConversion
+
+open WireTensor MotifGrid MotifBlocks MotifSelector MotifDemandPadding
+
+universe u v
+variable {k : Type u} [Field k] {J : Type v} [Fintype J]
+variable {D S : Type} [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+
+/-- The integral demand and supply arrays used in the fixed polynomial equations. -/
+noncomputable abbrev parameterData := MotifParameters.wireData a b P.src P.dst
+ (B.grid.demandWidths B.multiple) (B.grid.supplyWidths B.multiple) B.copyCount B.power
+
+theorem exists_solution : ∃ κ : (parameterData B).Entry → k, (parameterData B).IsSolution κ :=
+ MotifParameters.exists_wire_solution _ _ _ _ _ _ _ _ B.baseIdentity
+
+/-- A base-identity selector, comprising a copy index and one supply-grid choice per
+tensor-power factor. -/
+abbrev Selector := Fin B.copyCount × (Fin B.power → B.grid.supplies)
+
+/-- Supply widths of one selected copy of the base identity. -/
+noncomputable def basePayload (σ : Selector B) : S → ℕ :=
+ MotifBase.payload (B.grid.supplyWidths B.multiple) σ.2
+
+/-- One fixed finite encoding of the base selectors, including invalid bit words. -/
+noncomputable def selectorCode : Selector B ↪ Word B.selectorBits := by
+ apply Classical.choice (Function.Embedding.nonempty_of_card_le ?_)
+ simp only [Selector, Word, Fintype.card_fin, Fintype.card_prod, Fintype.card_fun,
+ Fintype.card_coe]
+ exact
+ MotifWidths.selector_capacity B.copyCount B.grid.supplies.card B.power
+
+/-- Compute the block repetitions using integer arithmetic. -/
+def repetitions (w : D → ℕ) : ℕ := MotifAdmission.copies p w B.scale
+
+theorem repetitions_eq (hp : ∀ i, 0 < p i) (w : D → ℕ) :
+ repetitions B w = B.repetitions w := MotifAdmission.copies_eq _ hp w _ B.scale_pos
+
+/-- The set of admitted outer supply payloads. Testing one supplied index uses
+only the fixed integer mass coefficients, without enumerating this set. -/
+noncomputable def outerIndices (w : D → ℕ) : Finset (S → ℕ) := by
+ classical
+ let u := repetitions B w
+ let cap := MotifAdmission.payloadCap q u B.scale B.radius
+ exact (Finset.univ.image (fun f : S → Fin (cap + 1) => fun e => (f e).val)).filter
+ (fun v => MotifAdmission.admit q v u B.scale B.radius = true)
+
+theorem mem_outerIndices_iff (hq : ∀ i, 0 < q i) (w : D → ℕ) (v : S → ℕ) :
+ v ∈ outerIndices B w ↔ MotifAdmission.admit q v (repetitions B w) B.scale B.radius = true := by
+ classical
+ constructor
+ · exact fun hv => (Finset.mem_filter.mp hv).2
+ · intro hv
+ let cap := MotifAdmission.payloadCap q (repetitions B w) B.scale B.radius
+ let f : S → Fin (cap + 1) := fun i => ⟨v i, Nat.lt_succ_of_le
+ (MotifAdmission.payload_le_cap q hq v _ _ _ hv i)⟩
+ exact Finset.mem_filter.mpr ⟨Finset.mem_image_of_mem _ (Finset.mem_univ f), hv⟩
+
+theorem sequence_mem_outerIndices (hq : ∀ i, 0 < q i) (w : D → ℕ)
+ (θ : Fin (repetitions B w) → Selector B) :
+ totalWidth (basePayload B) θ ∈ outerIndices B w := by
+ rw [mem_outerIndices_iff B hq, MotifAdmission.admit_eq_true_iff q hq _ _ _ _ B.radius_pos.le]
+ exact B.sequence_payload_le (fun i => Rat.cast_pos.mpr (hq i)) _ (fun i => (θ i).2)
+
+/-- Total widths, including a complete selector list on each supply edge. -/
+def supplyWidths (w : D → ℕ) (v : S → ℕ) (i : S) : ℕ := v i + repetitions B w * B.selectorBits
+
+theorem energy_le (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) (w : D → ℕ)
+ (v : S → ℕ) (hv : v ∈ outerIndices B w) :
+ widthNorm (realWidths q) (fun e => (supplyWidths B w v e : ℝ)) ^ 2 ≤
+ H' * widthNorm (realWidths p) (fun e => (w e : ℝ)) ^ 2 + B.energyConstant := by
+ rw [mem_outerIndices_iff B hq, MotifAdmission.admit_eq_true_iff q hq _ _ _ _ B.radius_pos.le,
+ repetitions_eq B hp] at hv
+ unfold supplyWidths
+ rw [repetitions_eq B hp]
+ exact B.padded_energy_le w v hv
+
+/-- Rounded demand grid point found by scanning the fixed table of grid points. -/
+noncomputable def demandGrid (hp : ∀ i, 0 < p i) (w : D → ℕ) : B.grid.demands := by
+ let table := B.grid.demands.toList
+ let res := MotifAdmission.selectGrid p w table
+ have hex := MotifAdmission.selectGrid_exists p hp B.grid w table
+ (fun _ hz => Finset.mem_toList.mpr hz)
+ have hs : res.isSome := Option.isSome_iff_exists.mpr hex
+ have h := MotifAdmission.selectGrid_spec p hp w (Option.some_get hs).symm
+ exact ⟨res.get hs, Finset.mem_toList.mp h.1⟩
+
+theorem selectGrid_eq (hp : ∀ i, 0 < p i) (w : D → ℕ) :
+ MotifAdmission.selectGrid p w B.grid.demands.toList = some (demandGrid B hp w).val :=
+ (Option.some_get _).symm
+
+/-- Demand width for edge `e` at grid point `z`, scaled by the block multiplier and tensor
+power. -/
+noncomputable abbrev baseDemand (z : B.grid.demands) (e : D) :=
+ B.power * B.grid.demandWidths B.multiple z e
+
+theorem demand_le (hp : ∀ i, 0 < p i) (w : D → ℕ) (i : D) :
+ w i ≤ repetitions B w * baseDemand B (demandGrid B hp w) i := by
+ let z := demandGrid B hp w
+ have hz := (MotifAdmission.selectGrid_spec p hp w (selectGrid_eq B hp w)).2
+ rw [repetitions_eq B hp]
+ apply MotifWidths.copies_dominate (realWidths p) w _ B.scale_pos (realWidths z.val)
+ (fun j => Rat.cast_nonneg.mpr (hz j).1) (fun j => (hz j).2) _ i
+ intro j
+ simp [baseDemand, FixedBlock.scale, realWidths, mul_assoc, z]
+
+/-- A local entry description before substituting any scalar parameters. -/
+noncomputable def entry (hp : ∀ i, 0 < p i) (w : D → ℕ) (v : S → ℕ) (j : J)
+ (x : HalfBits a b w j) (y : Half P (fun e => Word (supplyWidths B w v e)) j) :
+ Option (Fin (repetitions B w) → (parameterData B).Entry) :=
+ (groupedIndices P (basePayload B) (selectorCode B) v j
+ (fun i => demandChunk a b (demand_le B hp w) i j x) y).map
+ (fun t i => ⟨demandGrid B hp w, (t i).1, j, (t i).2.1, (t i).2.2⟩)
+
+/-- An absent description evaluates to zero. A successful description evaluates
+to one parameter per copy. -/
+def evalEntry {Param A : Type*} [CommMonoidWithZero A] {n : ℕ} (κ : Param → A)
+ (idx : Option (Fin n → Param)) : A := idx.elim 0 fun t => ∏ i, κ (t i)
+
+private theorem evalEntry_grouped {A : Type*} [CommRing A] (κ : (parameterData B).Entry → A)
+ (hp : ∀ i, 0 < p i) (w : D → ℕ) (v : S → ℕ) (j : J)
+ (x : HalfBits a b w j) (y : Half P (fun e => Word (supplyWidths B w v e)) j) :
+ evalEntry κ (entry B hp w v j x y) =
+ groupedMap P (basePayload B) ((parameterData B).localMap κ (demandGrid B hp w))
+ (selectorCode B) v j (fun i => demandChunk a b (demand_le B hp w) i j x) y := by
+ let z := demandGrid B hp w
+ have aux (o : Option (EntryIndices P (HalfBits a b (baseDemand B z)) (basePayload B)
+ (repetitions B w) j)) :
+ evalEntry κ (o.map (fun t i => ⟨z, (t i).1, j, (t i).2.1, (t i).2.2⟩)) =
+ evalIndices ((parameterData B).localMap κ z) j o := by cases o <;> rfl
+ exact aux _
+
+/-- The local description specializes to zero or a single monomial of degree at
+most the number of base copies, including when that number is zero. -/
+theorem entry_monomial (hp : ∀ i, 0 < p i) (w : D → ℕ) (v : S → ℕ) (j : J)
+ (x : HalfBits a b w j) (y : Half P (fun e => Word (supplyWidths B w v e)) j) :
+ let poly := evalEntry (MvPolynomial.X (R := ℤ)) (entry B hp w v j x y)
+ (poly = 0 ∨ ∃ f, poly = MvPolynomial.monomial f 1) ∧ poly.totalDegree ≤ repetitions B w := by
+ cases h : entry B hp w v j x y with
+ | none => simp [evalEntry]
+ | some t =>
+ exact ⟨Or.inr ⟨_, MotifParameters.prod_entries_eq_monomial t⟩,
+ MotifParameters.prod_entries_degree_le t⟩
+
+/-- The ordinary sum identity in (6.2), over any commutative ring and every
+assignment satisfying the fixed integral equations. -/
+theorem identity [Nonempty J] {A : Type*} [CommRing A] (κ : (parameterData B).Entry → A)
+ (hκ : (parameterData B).IsSolution κ) (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i)
+ (w : D → ℕ) :
+ (wireNetwork (k := A) a b (fun e => Word (w e))).coeff =
+ ∑ v ∈ outerIndices B w, applyLocal
+ (B := (wireNetwork (k := A) P.src P.dst (fun e => Word (supplyWidths B w v e))).Basis)
+ (fun j x y => evalEntry κ (entry B hp w v j x y))
+ (wireNetwork P.src P.dst (fun e => Word (supplyWidths B w v e))).coeff := by
+ classical
+ funext x
+ erw [Finset.sum_apply]
+ let z := demandGrid B hp w
+ let c (j : J) (i : Fin (repetitions B w)) := demandChunk a b (demand_le B hp w) i j (x j)
+ let L := (parameterData B).localMap κ z
+ have base := (MotifParameters.wire_solution_iff _ _ _ _ _ _ _ _ κ).mp hκ z
+ have hcopy (i : Fin (repetitions B w)) :
+ (wireNetwork (k := A) a b (fun e => Word (baseDemand B z e))).coeff (fun j => c j i) =
+ ∑ σ, baseTerm P (basePayload B) L σ (fun j => c j i) := by
+ have h := congrFun base (fun j => c j i)
+ erw [Finset.sum_apply] at h
+ exact h.trans (Finset.sum_congr rfl fun σ _ =>
+ applyLocal_wireNetwork (k := A) P.src P.dst (fun e => Word (basePayload B σ e))
+ (C := HalfBits a b (baseDemand B z)) (L σ) (fun j => c j i))
+ calc
+ _ = ∏ i, (wireNetwork (k := A) a b (fun e => Word (baseDemand B z e))).coeff
+ (fun j => c j i) := coeff_eq_prod_chunks a b (demand_le B hp w) x
+ _ = ∏ i, ∑ σ, baseTerm P (basePayload B) L σ (fun j => c j i) :=
+ Finset.prod_congr rfl fun i _ => hcopy i
+ _ = _ := (power_expansion P (basePayload B) L (selectorCode B) (outerIndices B w)
+ (sequence_mem_outerIndices B hq w) c).trans <| Finset.sum_congr rfl fun v _ => by
+ unfold applyLocal
+ apply Finset.sum_congr rfl
+ intro y _
+ congr 1
+ apply Finset.prod_congr rfl
+ intro j _
+ exact (evalEntry_grouped B κ hp w v j (x j) (y j)).symm
+
+/-- The fixed number of outer coordinates, and the degree of every evaluated
+monomial, use at most linearly many bits of wire payload per input-width unit. -/
+theorem linear_index_bound (hq : ∀ i, 0 < q i) :
+ ∃ C : ℕ, ∀ (M : ℕ) (w : D → ℕ), (∀ i, w i ≤ M) →
+ repetitions B w ≤ C * (M + 1) ∧ ∀ v ∈ outerIndices B w, ∀ e, v e ≤ C * (M + 1) := by
+ let W := (∑ i, MotifAdmission.weight p i) + 1
+ let V := W * B.scale * B.radius.num.natAbs * MotifAdmission.denominator q
+ refine ⟨max W V, fun M w hw => ?_⟩
+ have hu := MotifAdmission.copies_le p w B.scale M B.scale_pos hw
+ constructor
+ · exact hu.trans (Nat.mul_le_mul_right _ (le_max_left _ _))
+ · intro v hv e
+ have hv' := (mem_outerIndices_iff B hq w v).mp hv
+ exact (MotifAdmission.payload_le_cap q hq _ _ _ _ hv' e).trans
+ ((MotifAdmission.payloadCap_le p q w _ M B.radius B.scale_pos hw).trans
+ (Nat.mul_le_mul_right _ (le_max_right _ _)))
+
+/-- The fixed finite selector table used in the local entry evaluator. -/
+noncomputable def selectorTable : List (Selector B) := Finset.univ.toList
+
+private theorem mem_selectorTable (s : Selector B) : s ∈ selectorTable B :=
+ Finset.mem_toList.mpr (Finset.mem_univ _)
+
+/-- A base matrix entry's index in the fixed parameter vector. -/
+noncomputable abbrev lookup (z : B.grid.demands) (σ : Selector B) (j : J)
+ (x : HalfBits a b (baseDemand B z) j) (y : Half P (fun e => Word (basePayload B σ e)) j) :
+ (parameterData B).Entry := ⟨z, σ, j, x, y⟩
+
+/-- The bit-string evaluator specialized to this block, with fixed finite table
+and code. The count records bit probes and word operations of the local scan. -/
+noncomputable def runEntry [DecidableEq J] (hp : ∀ i, 0 < p i) (w : D → ℕ) (v : S → ℕ) (j : J)
+ (d : MotifEntry.DemandBits a b w j)
+ (x : Half P (fun e => Fin (supplyWidths B w v e) → Bool) j) :
+ Option (List (parameterData B).Entry) × ℕ :=
+ let z := demandGrid B hp w
+ MotifEntry.run a b (baseDemand B z) w P (basePayload B) (lookup B z) (selectorTable B)
+ (selectorCode B) v j d x
+
+/-- The actual bit-string evaluator returns the matrix entry used in (6.2)
+after evaluating the reported parameter list. -/
+theorem runEntry_correct [DecidableEq J] {A : Type*} [CommRing A] (κ : (parameterData B).Entry → A)
+ (hp : ∀ i, 0 < p i) (w : D → ℕ) (v : S → ℕ) (j : J) (d : HalfBits a b w j)
+ (x : Half P (fun e => Word (supplyWidths B w v e)) j) :
+ (runEntry B hp w v j (MotifEntry.demandBits a b j d)
+ (mapHalf P (fun _ => MotifEntry.inputBits) x)).1.elim 0 (fun names => (names.map κ).prod) =
+ evalEntry κ (entry B hp w v j d x) := by
+ dsimp only [runEntry]
+ erw [MotifEntry.run_value, evalEntry_grouped]
+ exact MotifEntry.describe_correct a b (demand_le B hp w) P (basePayload B)
+ (lookup B (demandGrid B hp w)) κ (selectorTable B) (mem_selectorTable B)
+ (selectorCode B) v j d x
+
+/-- With the motif and its tables fixed, the number of bit probes and word
+operations has absolute exponent two in the largest demand width. -/
+theorem runEntry_cost [DecidableEq J] (hp : ∀ i, 0 < p i) :
+ ∃ K : ℕ, ∀ (M : ℕ) (w : D → ℕ), (∀ i, w i ≤ M) → ∀ v j d x,
+ (runEntry B hp w v j d x).2 ≤ K * (M + 1) ^ 2 := by
+ let Dmax := ∑ z : B.grid.demands, ∑ e, baseDemand B z e
+ let Smax := ∑ σ : Selector B, ∑ e, basePayload B σ e
+ let U := (∑ i, MotifAdmission.weight p i) + 1
+ let K := Fintype.card S * (12 * B.selectorBits + 12 * Smax + 48) +
+ Fintype.card D * (12 * Dmax + 7) + 2 * (selectorTable B).length + 18
+ have hD (z : B.grid.demands) (e : D) : baseDemand B z e ≤ Dmax :=
+ (Finset.single_le_sum (f := baseDemand B z) (fun _ _ => Nat.zero_le _)
+ (Finset.mem_univ e)).trans
+ (Finset.single_le_sum (f := fun z => ∑ i, baseDemand B z i) (fun _ _ => Nat.zero_le _)
+ (Finset.mem_univ z))
+ have hS (σ : Selector B) (e : S) : basePayload B σ e ≤ Smax :=
+ (Finset.single_le_sum (f := basePayload B σ) (fun _ _ => Nat.zero_le _)
+ (Finset.mem_univ e)).trans
+ (Finset.single_le_sum (f := fun σ => ∑ i, basePayload B σ i) (fun _ _ => Nat.zero_le _)
+ (Finset.mem_univ σ))
+ refine ⟨K * (U + 1) ^ 2, fun M w hw v j d x => ?_⟩
+ let z := demandGrid B hp w
+ have hu : repetitions B w ≤ U * (M + 1) := MotifAdmission.copies_le p w B.scale M B.scale_pos hw
+ have hu' : repetitions B w + 1 ≤ (U + 1) * (M + 1) := by
+ rw [add_mul, one_mul]
+ exact Nat.add_le_add hu (Nat.le_add_left _ _)
+ calc
+ _ ≤ K * (repetitions B w + 1) ^ 2 := MotifEntry.run_le a b (baseDemand B z) w P (basePayload B)
+ (lookup B z) (selectorTable B) (selectorCode B) v j d x (hD z) hS
+ _ ≤ K * ((U + 1) * (M + 1)) ^ 2 := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hu' _)
+ _ = _ := by ring
+
+/-- With sequential storage one can rescan a string from its beginning for
+every indexed bit probe. The resulting allowance is cubic in the maximum
+input width, with a coefficient fixed before seeing the input. -/
+theorem sequential_entry_cost [DecidableEq J] (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) :
+ ∃ K : ℕ, ∀ (M : ℕ) (w : D → ℕ), (∀ e, w e ≤ M) → ∀ v ∈ outerIndices B w, ∀ j d x,
+ let z := demandGrid B hp w
+ (MotifEntry.tapeRun (u := repetitions B w) a b (baseDemand B z) w P (basePayload B)
+ (lookup B z) (selectorTable B) (selectorCode B) v j d x).2 ≤ K * (M + 1) ^ 3 := by
+ obtain ⟨C, hC⟩ := linear_index_bound B hq
+ obtain ⟨A, hA⟩ := runEntry_cost B hp
+ let cap := Fintype.card D + Fintype.card S * (C + C * B.selectorBits)
+ refine ⟨(3 * cap + 2) * A, fun M w hw v hv j d x => ?_⟩
+ obtain ⟨hu, hvs⟩ := hC M w hw
+ have hlen (e : S) : supplyWidths B w v e ≤ (C + C * B.selectorBits) * (M + 1) := by
+ calc
+ _ ≤ C * (M + 1) + (C * (M + 1)) * B.selectorBits :=
+ Nat.add_le_add (hvs v hv e) (Nat.mul_le_mul_right _ hu)
+ _ = _ := by ring
+ let length := (∑ e, w e) + ∑ e, supplyWidths B w v e
+ have hs : length ≤ cap * (M + 1) := by
+ have hd := Finset.sum_le_sum (s := Finset.univ) (fun e _ => (hw e).trans (Nat.le_succ M))
+ have hv' := Finset.sum_le_sum (s := Finset.univ) (fun e _ => hlen e)
+ simpa [length, cap, Nat.add_mul, Nat.mul_assoc] using Nat.add_le_add hd hv'
+ have allowance : 3 * length + 2 ≤ (3 * cap + 2) * (M + 1) := by
+ calc
+ _ ≤ 3 * (cap * (M + 1)) + 2 * (M + 1) := Nat.add_le_add (Nat.mul_le_mul_left _ hs)
+ (Nat.le_mul_of_pos_right _ (Nat.succ_pos M))
+ _ = _ := by ring
+ have hrun := hA M w hw v j
+ (fun e h => MotifEntry.Tape.readBits (d.1 e h), fun e h => MotifEntry.Tape.readBits (d.2 e h))
+ (mapHalf P (fun _ => MotifEntry.Tape.readBits) x)
+ exact (Nat.mul_le_mul allowance hrun).trans_eq (by ring)
+
+/-- The spectral bound (6.1) yields fixed integral equations, a solution in
+the given field, and the identities (6.2) over every ring satisfying those
+equations. The block and its additive error are fixed before the input widths.
+The entry descriptions and outer indices are shared across all assignments. -/
+theorem exists_conversion [Nontrivial J] (a b : D → J) (P : Supply J S) (p : D → ℚ) (q : S → ℚ)
+ (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) {H H' : ℝ} (hH : 0 ≤ H) (hHH' : H < H')
+ (hcomp : ∀ F : SpectralPoint k J,
+ distanceEnergy (realWidths p) (fun i => F.wireDistance (a i) (b i)) ≤
+ H * distanceEnergy (realWidths q) (fun i => F.wireDistance (P.src i) (P.dst i))) :
+ ∃ B : FixedBlock k a b P (realWidths p) (realWidths q) H H',
+ (∃ κ : (parameterData B).Entry → k, (parameterData B).IsSolution κ) ∧
+ (∀ (w : D → ℕ) v, v ∈ outerIndices B w →
+ widthNorm (realWidths q) (fun e => (supplyWidths B w v e : ℝ)) ^ 2 ≤
+ H' * widthNorm (realWidths p) (fun e => (w e : ℝ)) ^ 2 + B.energyConstant) ∧
+ ∀ (A : Type*) [CommRing A] (κ : (parameterData B).Entry → A), (parameterData B).IsSolution κ →
+ ∀ w : D → ℕ, (wireNetwork (k := A) a b (fun e => Word (w e))).coeff =
+ ∑ v ∈ outerIndices B w, applyLocal
+ (B := (wireNetwork (k := A) P.src P.dst (fun e => Word (supplyWidths B w v e))).Basis)
+ (fun j x y => evalEntry κ (entry B hp w v j x y))
+ (wireNetwork P.src P.dst (fun e => Word (supplyWidths B w v e))).coeff := by
+ obtain ⟨B⟩ := exists_fixed_block a b P (realWidths p) (realWidths q)
+ (fun i => Rat.cast_pos.mpr (hp i)) (fun i => Rat.cast_pos.mpr (hq i)) hH hHH' hcomp
+ exact ⟨B, exists_solution B, energy_le B hp hq, fun _ _ κ hκ => identity B κ hκ hp hq⟩
+
+end MotifConversion
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifDemandPadding.lean b/lean/OAI/Computability/VPVNP/MotifDemandPadding.lean
new file mode 100644
index 0000000000..c30741ff22
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifDemandPadding.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.WireTensor
+import Mathlib.Algebra.BigOperators.Fin
+
+/-!
+# Demand padding in a repeated wire identity
+
+Theorem 6.1 fixes surplus bits to zero at both ends of each demand wire.
+A desired index is included as the same natural number in the larger range
+and read in consecutive fields of the base width. Equality at the two ends
+is then equivalent to equality in every field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifDemandPadding
+
+open WireTensor
+
+variable {J D R : Type*} [Fintype D]
+
+/-- Widen an index by leading zeros, then split it into `u` fields of width `a`. -/
+def padFields {b u a : ℕ} (h : b ≤ u * a) : Fin (2 ^ b) ↪ (Fin u → Fin (2 ^ a)) :=
+ (Fin.castLEEmb (show 2 ^ b ≤ (2 ^ a) ^ u by
+ rw [← pow_mul, Nat.mul_comm a u]
+ exact Nat.pow_le_pow_right (by decide) h)).trans finFunctionFinEquiv.symm.toEmbedding
+
+/-- Each field can be read directly from the original index by division and remainder. -/
+theorem padFields_digit {b u a : ℕ} (h : b ≤ u * a) (x : Fin (2 ^ b)) (i : Fin u) :
+ ((padFields h x i : Fin (2 ^ a)) : ℕ) = x.val / (2 ^ a) ^ i.val % (2 ^ a) := rfl
+
+/-- The half-wire coordinates of a binary network at a party. -/
+abbrev HalfBits (src dst : D → J) (w : D → ℕ) (j : J) :=
+ ((e : D) → j = src e → Fin (2 ^ w e)) × ((e : D) → j = dst e → Fin (2 ^ w e))
+
+/-- Read the fields of a single repeated base copy at all incident half-wires. -/
+def demandChunk (src dst : D → J) {b a : D → ℕ} {u : ℕ} (hab : ∀ e, b e ≤ u * a e)
+ (i : Fin u) (j : J) (x : HalfBits src dst b j) : HalfBits src dst a j :=
+ (fun e h ↦ padFields (hab e) (x.1 e h) i, fun e h ↦ padFields (hab e) (x.2 e h) i)
+
+/-- The product of the repeated base demands on the padded input is exactly
+the desired demand tensor. This is an entrywise identity over any coefficient
+semiring, also for zero copies or zero widths. -/
+theorem coeff_eq_prod_chunks [CommSemiring R] (src dst : D → J) {b a : D → ℕ} {u : ℕ}
+ (hab : ∀ e, b e ≤ u * a e) (x : ∀ j, HalfBits src dst b j) :
+ (wireNetwork (k := R) src dst (fun e ↦ Fin (2 ^ b e))).coeff x =
+ ∏ i : Fin u, (wireNetwork (k := R) src dst (fun e ↦ Fin (2 ^ a e))).coeff
+ (fun j ↦ demandChunk src dst hab i j (x j)) := by
+ classical
+ by_cases same : ∀ e, (x (src e)).1 e rfl = (x (dst e)).2 e rfl
+ · simp [wireNetwork, demandChunk, same]
+ · obtain ⟨e, he⟩ := not_forall.mp same
+ have mismatch : ¬ ∀ i, padFields (hab e) ((x (src e)).1 e rfl) i =
+ padFields (hab e) ((x (dst e)).2 e rfl) i :=
+ fun h ↦ he ((padFields (hab e)).injective (funext h))
+ obtain ⟨i, hi⟩ := not_forall.mp mismatch
+ have hX : (wireNetwork (k := R) src dst (fun e ↦ Fin (2 ^ b e))).coeff x = 0 :=
+ Finset.prod_eq_zero (Finset.mem_univ e) (ite_eq_right (fun h ↦ (he h).elim))
+ have hY : (wireNetwork (k := R) src dst (fun e ↦ Fin (2 ^ a e))).coeff
+ (fun j ↦ demandChunk src dst hab i j (x j)) = 0 :=
+ Finset.prod_eq_zero (Finset.mem_univ e) (ite_eq_right (fun h ↦ (hi h).elim))
+ exact hX.trans (Finset.prod_eq_zero (Finset.mem_univ i) hY).symm
+
+end MotifDemandPadding
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifEntry.lean b/lean/OAI/Computability/VPVNP/MotifEntry.lean
new file mode 100644
index 0000000000..a4538e16a7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifEntry.lean
@@ -0,0 +1,799 @@
+import OAI.Computability.VPVNP.MotifDemandPadding
+import OAI.Computability.VPVNP.MotifPayload
+import OAI.Computability.VPVNP.MotifParameters
+import Mathlib.Data.Nat.Bitwise
+
+/-!
+# Reading the entries of a grouped motif map
+
+For the construction on page 21, the input at a party is a collection of
+incident bit strings. Read their common selector sequence, check its full
+width vector, then use each copy's demand and supply fields to look up one
+parameter. The output list records multiplicities in the resulting monomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifEntry
+
+open MotifSelector
+
+/-- Binary digits are numbered from the least significant end. -/
+def inputBits {w : ℕ} (x : Fin (2 ^ w)) (i : Fin w) : Bool := x.val.testBit i.val
+
+/-- Probe one position, returning a zero bit outside the supplied string. -/
+def paddedBit {w : ℕ} (bits : Fin w → Bool) (pos : ℕ) : Bool :=
+ if h : pos < w then bits ⟨pos, h⟩ else false
+
+@[simp] theorem paddedBit_inputBits {w : ℕ} (x : Fin (2 ^ w)) (pos : ℕ) :
+ paddedBit (inputBits x) pos = x.val.testBit pos := by
+ by_cases h : pos < w
+ · simp [paddedBit, inputBits, h]
+ · have hx : x.val < 2 ^ pos := x.isLt.trans_le (Nat.pow_le_pow_right (by decide) (by omega))
+ simp [paddedBit, h, Nat.testBit_eq_false_of_lt hx]
+
+/-- Read consecutive bits by incrementing the probe position and combining
+each bit with the remaining high part by one shift and one addition. -/
+def readField {w : ℕ} (bits : Fin w → Bool) (off : ℕ) : ℕ → ℕ
+ | 0 => 0
+ | a + 1 => (paddedBit bits off).toNat + 2 * readField bits (off + 1) a
+
+/-- The input oracle is used only at the indicated little-endian positions. -/
+theorem readField_eq_sum {w : ℕ} (bits : Fin w → Bool) (off a : ℕ) :
+ readField bits off a = ∑ i : Fin a, (paddedBit bits (off + i.val)).toNat * 2 ^ i.val := by
+ induction a generalizing off with
+ | zero => simp [readField]
+ | succ a ih =>
+ rw [readField, ih, Fin.sum_univ_succ, Finset.mul_sum]
+ simp only [Fin.val_zero, Nat.add_zero, pow_zero, mul_one, Fin.val_succ, pow_succ]
+ congr 1
+ apply Finset.sum_congr rfl
+ intro i _
+ rw [show off + 1 + i.val = off + (i.val + 1) by omega]
+ ac_rfl
+
+private theorem testBit_toNat_eq (n pos : ℕ) :
+ (n.testBit pos).toNat = n / 2 ^ pos % 2 := by
+ rw [Nat.testBit_eq_decide_div_mod_eq]
+ by_cases h : n / 2 ^ pos % 2 = 1
+ · simp [h]
+ · have hz : n / 2 ^ pos % 2 = 0 := by omega
+ simp [hz]
+
+/-- Decoding from the bit oracle gives the same digit as division and
+remainder, even if the requested field is wholly or partly in the padding. -/
+theorem readField_inputBits {w : ℕ} (x : Fin (2 ^ w)) (off a : ℕ) :
+ readField (inputBits x) off a = (x.val / 2 ^ off) % 2 ^ a := by
+ induction a generalizing off with
+ | zero => simp [readField, Nat.mod_one]
+ | succ a ih =>
+ rw [readField, paddedBit_inputBits, testBit_toNat_eq, ih, pow_succ' 2 a,
+ Nat.mod_mul, Nat.div_div_eq_div_mul, pow_succ 2 off]
+
+/-- The decoded value of an arbitrary field fits in the field width. -/
+theorem readField_lt {w : ℕ} (bits : Fin w → Bool) (off a : ℕ) :
+ readField bits off a < 2 ^ a := by
+ induction a generalizing off with
+ | zero => simp [readField]
+ | succ a ih =>
+ have hh := ih (off + 1)
+ rw [readField, pow_succ]
+ cases paddedBit bits off <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega
+
+/-- A typed field, suitable for indexing the table of a fixed base motif. -/
+def fieldIndex {w : ℕ} (bits : Fin w → Bool) (off a : ℕ) : Fin (2 ^ a) :=
+ ⟨readField bits off a, readField_lt bits off a⟩
+
+/-- Reading the indicated demand chunk agrees with the padding injection. -/
+theorem fieldIndex_eq_padFields {w u a : ℕ} (h : w ≤ u * a) (x : Fin (2 ^ w)) (i : Fin u) :
+ fieldIndex (inputBits x) (a * i.val) a = MotifDemandPadding.padFields h x i := by
+ apply Fin.ext
+ rw [MotifDemandPadding.padFields_digit, ← pow_mul, ← readField_inputBits]
+ rfl
+
+/-- Record each probe and the fixed operations in the recursion.
+Each nonempty field iteration pays for the width test, one padded probe,
+the position increment, low-bit conversion, doubling, and addition. -/
+def meteredField {w : ℕ} (bits : Fin w → Bool) (off : ℕ) : ℕ → ℕ × ℕ
+ | 0 => (0, 1)
+ | a + 1 =>
+ let hi := meteredField bits (off + 1) a
+ ((paddedBit bits off).toNat + 2 * hi.1, 6 + hi.2)
+
+theorem meteredField_spec {w : ℕ} (bits : Fin w → Bool) (off a : ℕ) :
+ meteredField bits off a = (readField bits off a, 6 * a + 1) := by
+ induction a generalizing off with
+ | zero => simp [meteredField, readField]
+ | succ a ih =>
+ simp only [meteredField, ih, readField, Nat.mul_succ]
+ congr 1
+ omega
+
+
+/-- Locate one selector above the payload. -/
+def readTag {u bits v : ℕ} (x : Fin (v + u * bits) → Bool) (i : Fin u) : Word bits :=
+ fieldIndex x (v + bits * i.val) bits
+
+theorem readTag_inputBits {u bits v : ℕ} (x : Word (v + u * bits)) (i : Fin u) :
+ readTag (inputBits x) i = (wireFields u bits v x).1 i := by
+ apply Fin.ext
+ change readField (inputBits x) _ _ = x.val / 2 ^ v / (2 ^ bits) ^ i.val % 2 ^ bits
+ rw [readField_inputBits, Nat.div_div_eq_div_mul, pow_add 2 v (bits * i.val), pow_mul 2 bits i.val]
+
+/-- The low bits of a supply coordinate are its payload. -/
+def payloadBits {u bits v : ℕ} (x : Fin (v + u * bits) → Bool) : Fin v → Bool :=
+ fun i => x (Fin.castLE (Nat.le_add_right _ _) i)
+
+theorem payloadBits_inputBits {u bits v : ℕ} (x : Word (v + u * bits)) :
+ payloadBits (inputBits x) = inputBits (wireFields u bits v x).2 := by
+ funext i
+ change x.val.testBit i.val = (x.val % 2 ^ v).testBit i.val
+ simp [Nat.testBit_mod_two_pow, i.isLt]
+
+/-- Scan the widths preceding a copy to find the start of its payload field. -/
+def offset {u : ℕ} (w : Fin u → ℕ) (i : Fin u) : ℕ :=
+ ∑ t : Fin i.val, w (Fin.castLE i.isLt.le t)
+
+theorem fieldIndex_eq_unpack {u : ℕ} (w : Fin u → ℕ) (x : Word (∑ i, w i)) (i : Fin u) :
+ fieldIndex (inputBits x) (offset w i) (w i) = unpackFields w x i := by
+ apply Fin.ext
+ change readField (inputBits x) _ _ = (x.val / ∏ j : Fin i.val,
+ 2 ^ w (Fin.castLE i.isLt.le j)) % (2 ^ w i)
+ rw [readField_inputBits, Finset.prod_pow_eq_pow_sum]
+ rfl
+
+variable {J E S V : Type*} {C : J → Type*} {bits u : ℕ}
+
+/-- The code table can be searched even when some bit patterns are unused. -/
+def decode (table : List S) (code : S ↪ Word bits) (tag : Word bits) : Option S :=
+ table.find? (fun s => decide (code s = tag))
+
+theorem decode_eq_some (table : List S) (complete : ∀ s, s ∈ table)
+ (code : S ↪ Word bits) (tag : Word bits) (s : S) :
+ decode table code tag = some s ↔ code s = tag := by
+ constructor
+ · intro h
+ simpa using List.find?_some h
+ · intro hs
+ cases h : decode table code tag with
+ | none =>
+ have hn := List.find?_eq_none.mp h s (complete s)
+ simp [hs] at hn
+ | some t =>
+ have ht : code t = tag := by simpa using List.find?_some h
+ rw [code.injective (ht.trans hs.symm)]
+
+/-- Read the reference half-wire without using choice. -/
+def anchor [DecidableEq J] (G : Supply J E) {I : E → Type*} (j : J) (x : Half G I j) :
+ I (G.anchor j) :=
+ if h : j = G.src (G.anchor j) then x.1 _ h else
+ x.2 _ ((G.anchor_incident j).resolve_left fun he => h he.symm).symm
+
+theorem anchor_eq_readAnchor [DecidableEq J] (G : Supply J E) {I : E → Type*}
+ (j : J) (x : Half G I j) : anchor G j x = readAnchor G j x := by
+ unfold anchor readAnchor
+ split <;> simp_all
+
+variable [DecidableEq J] [Fintype E]
+
+/-- Check a party's source and target ports, testing one copy at a time. -/
+def consistent (G : Supply J E) (j : J) (tags : Half G (fun _ => Fin u → Word bits) j) :
+ Bool :=
+ let t := anchor G j tags
+ decide (∀ e, (if h : j = G.src e then ∀ i, tags.1 e h i = t i else True) ∧
+ (if h : j = G.dst e then ∀ i, tags.2 e h i = t i else True))
+
+private theorem consistent_iff {I : E → Type*} (G : Supply J E) (j : J)
+ (fields : Half G (fun e => (Fin u → Word bits) × I e) j) :
+ consistent G j (mapHalf G (fun _ => Prod.fst) fields) = true ↔ HalfAgrees G j fields := by
+ have ha : anchor G j (mapHalf G (fun _ => Prod.fst) fields) = (readAnchor G j fields).1 := by
+ rw [← anchor_eq_readAnchor]
+ unfold anchor
+ split <;> rfl
+ unfold consistent
+ dsimp only
+ rw [decide_eq_true_iff, ha]
+ unfold HalfAgrees
+ constructor
+ · intro h
+ constructor
+ · intro e he
+ exact funext (by simpa [he, mapHalf] using (h e).1)
+ · intro e he
+ exact funext (by simpa [he, mapHalf] using (h e).2)
+ · rintro ⟨hl, hr⟩ e
+ constructor
+ · split <;> rename_i he
+ · exact fun i => congrFun (hl e he) i
+ · trivial
+ · split <;> rename_i he
+ · exact fun i => congrFun (hr e he) i
+ · trivial
+
+/-- Decode the anchor sequence, checking each tag against the fixed selector
+table. Once decoded, the array can be indexed when computing payload offsets. -/
+def selectors? (table : List S) (code : S ↪ Word bits) (tags : Fin u → Word bits) :
+ Option (Fin u → S) :=
+ let a := Vector.ofFn (fun i => decode table code (tags i))
+ if h : ∀ i : Fin u, (a[i.val]).isSome then
+ some (fun i => (a[i.val]).get (h i)) else none
+
+private theorem selectors_spec (table : List S) (complete : ∀ s, s ∈ table)
+ (code : S ↪ Word bits) (tags : Fin u → Word bits) (θ : Fin u → S) :
+ selectors? table code tags = some θ ↔ sequenceCode code u θ = tags := by
+ simp only [selectors?, Vector.getElem_ofFn]
+ split
+ · rename_i h
+ rw [Option.some.injEq]
+ constructor
+ · rintro rfl
+ exact funext fun i => (decode_eq_some table complete code _ _).1 (Option.some_get (h i)).symm
+ · intro he
+ exact funext fun i => Option.get_of_eq_some _ ((decode_eq_some table complete code _ _).2
+ (congrFun he i))
+ · rename_i h
+ simp only [reduceCtorEq, false_iff]
+ exact fun he => h fun i => Option.isSome_iff_exists.mpr
+ ⟨θ i, (decode_eq_some table complete code _ _).2 (congrFun he i)⟩
+
+/-- Read the local supply fields in copy order and check the total vector on
+all edges. The last test also checks coordinates away from the current party. -/
+def extract (G : Supply J E) (w : S → E → ℕ) (v : E → ℕ) (θ : Fin u → S)
+ (j : J) (c : Fin u → C j) (x : Half G (fun e => Fin (v e) → Bool) j) :
+ Option (EntryIndices G C w u j) :=
+ if ∀ e, v e = totalWidth w θ e then
+ some (fun i => ⟨θ i, c i, mapHalf G (fun e y =>
+ fieldIndex y (offset (fun l => w (θ l) e) i) (w (θ i) e)) x⟩)
+ else none
+
+omit [DecidableEq J] in
+private theorem extract_inputBits (G : Supply J E) (w : S → E → ℕ) (v : E → ℕ)
+ (θ : Fin u → S) (j : J) (c : Fin u → C j) (x : Half G (fun e => Word (v e)) j) :
+ extract G w v θ j c (mapHalf G (fun _ => inputBits) x) = payloadIndices G w v θ j c x := by
+ unfold extract payloadIndices
+ by_cases h : v = totalWidth w θ
+ · subst v
+ rw [ite_eq_left (fun _ => rfl), dite_eq_left rfl]
+ apply congrArg some
+ funext i
+ congr 2
+ apply Prod.ext
+ · funext e he
+ exact fieldIndex_eq_unpack _ _ i
+ · funext e he
+ exact fieldIndex_eq_unpack _ _ i
+ · rw [ite_eq_right (fun he => h (funext he)), dite_eq_right h]
+
+/-- Execute all the entry checks on bit-string inputs. The argument `c`
+supplies the demand coordinate of each copy. -/
+def indices (G : Supply J E) (w : S → E → ℕ) (table : List S) (code : S ↪ Word bits)
+ (v : E → ℕ) (j : J) (c : Fin u → C j)
+ (x : Half G (fun e => Fin (v e + u * bits) → Bool) j) : Option (EntryIndices G C w u j) :=
+ let tags := mapHalf G (fun _ => readTag) x
+ if consistent G j tags then
+ (selectors? table code (anchor G j tags)).bind fun θ =>
+ extract G w v θ j c (mapHalf G (fun _ => payloadBits) x)
+ else none
+
+/-- Correctness of the executable local parser against the grouped wire map. -/
+theorem indices_eq_groupedIndices (G : Supply J E) (w : S → E → ℕ) (table : List S)
+ (complete : ∀ s, s ∈ table) (code : S ↪ Word bits) (v : E → ℕ) (j : J)
+ (c : Fin u → C j) (x : Half G (fun e => Word (v e + u * bits)) j) :
+ indices G w table code v j c (mapHalf G (fun _ => inputBits) x) =
+ groupedIndices G w code v j c x := by
+ classical
+ let fields := mapHalf G (fun e => wireFields u bits (v e)) x
+ let tags := mapHalf G (fun _ => Prod.fst) fields
+ let payload := mapHalf G (fun _ => Prod.snd) fields
+ let t := (readAnchor G j fields).1
+ have ht : mapHalf G (fun _ => readTag) (mapHalf G (fun _ => inputBits) x) = tags := by
+ apply Prod.ext <;> funext e he i <;> exact readTag_inputBits _ i
+ have hp : mapHalf G (fun _ => payloadBits) (mapHalf G (fun _ => inputBits) x) =
+ mapHalf G (fun _ => inputBits) payload := by
+ apply Prod.ext <;> funext e he <;> exact payloadBits_inputBits _
+ have ha : anchor G j tags = t := by
+ dsimp only [t]
+ rw [← anchor_eq_readAnchor]
+ unfold anchor
+ split <;> rfl
+ unfold indices groupedIndices
+ dsimp only
+ rw [ht, hp, ha]
+ change (if consistent G j tags then _ else _) =
+ (if HalfAgrees G j fields then tagIndices G w code v t j c payload else _)
+ by_cases hag : HalfAgrees G j fields
+ · rw [ite_eq_left hag, ite_eq_left ((consistent_iff G j fields).2 hag)]
+ unfold tagIndices
+ split
+ · rename_i hr
+ rw [(selectors_spec table complete code t hr.choose).2 hr.choose_spec]
+ exact extract_inputBits _ _ _ _ _ _ _
+ · rename_i hr
+ cases hx : selectors? table code t with
+ | none => rfl
+ | some θ => exact (hr ⟨θ, (selectors_spec table complete code t θ).1 hx⟩).elim
+ · rw [ite_eq_right hag, ite_eq_right (fun h => hag ((consistent_iff G j fields).1 h))]
+
+/-- Replace the indices by their fixed parameter-table names. Repeated names
+are retained once per occurrence. -/
+def labels {G : Supply J E} {w : S → E → ℕ}
+ (lookup : ∀ s j, C j → Half G (fun e => Word (w s e)) j → V) (j : J)
+ (out : Option (EntryIndices G C w u j)) : Option (List V) :=
+ out.map fun t => List.ofFn fun i => lookup (t i).1 j (t i).2.1 (t i).2.2
+
+omit [DecidableEq J] [Fintype E] in
+theorem labels_length {G : Supply J E} {w : S → E → ℕ}
+ (lookup : ∀ s j, C j → Half G (fun e => Word (w s e)) j → V) (j : J)
+ (out : Option (EntryIndices G C w u j)) {names : List V}
+ (h : labels lookup j out = some names) : names.length = u := by
+ cases out <;> simp [labels] at h
+ simp [← h]
+
+omit [DecidableEq J] [Fintype E] in
+theorem eval_labels {R : Type*} [CommMonoidWithZero R] {G : Supply J E} {w : S → E → ℕ}
+ (lookup : ∀ s j, C j → Half G (fun e => Word (w s e)) j → V) (κ : V → R) (j : J)
+ (out : Option (EntryIndices G C w u j)) :
+ (labels lookup j out).elim 0 (fun names => (names.map κ).prod) =
+ evalIndices (fun s j c x => κ (lookup s j c x)) j out := by
+ cases out <;> simp [labels, evalIndices, List.map_ofFn, List.prod_ofFn]
+
+/-- Local demand inputs with one bit string on each incident half-wire. -/
+abbrev DemandBits {D : Type*} (src dst : D → J) (b : D → ℕ) (j : J) :=
+ ((e : D) → j = src e → Fin (b e) → Bool) × ((e : D) → j = dst e → Fin (b e) → Bool)
+
+/-- Read a copy's fixed-size fields on the demand side, supplying zero bits
+above the width of the desired demand. -/
+def demandFields {D : Type*} (src dst : D → J) (a : D → ℕ) {b : D → ℕ}
+ (i : Fin u) (j : J) (d : DemandBits src dst b j) : MotifDemandPadding.HalfBits src dst a j :=
+ (fun e h => fieldIndex (d.1 e h) (a e * i.val) (a e),
+ fun e h => fieldIndex (d.2 e h) (a e * i.val) (a e))
+
+/-- Canonical bit strings for the two demand endpoints. -/
+def demandBits {D : Type*} (src dst : D → J) {b : D → ℕ} (j : J)
+ (d : MotifDemandPadding.HalfBits src dst b j) : DemandBits src dst b j :=
+ (fun e h => inputBits (d.1 e h), fun e h => inputBits (d.2 e h))
+
+omit [DecidableEq J] [Fintype E] in
+theorem demandFields_eq {D : Type*} (src dst : D → J) {a b : D → ℕ}
+ (hab : ∀ e, b e ≤ u * a e) (i : Fin u) (j : J)
+ (d : MotifDemandPadding.HalfBits src dst b j) :
+ demandFields src dst a i j (demandBits src dst j d) =
+ MotifDemandPadding.demandChunk src dst hab i j d := by
+ apply Prod.ext <;> funext e he <;> exact fieldIndex_eq_padFields (hab e) _ i
+
+/-- The entry algorithm for an entire local map, including demand padding.
+A failed check returns `none`; success returns the ordered parameter names. -/
+def describe {D : Type*} (src dst : D → J) (a b : D → ℕ) (G : Supply J E) (w : S → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (table : List S) (code : S ↪ Word bits) (v : E → ℕ)
+ (j : J) (d : DemandBits src dst b j) (x : Half G (fun e => Fin (v e + u * bits) → Bool) j) :
+ Option (List V) :=
+ labels lookup j (indices G w table code v j (fun i => demandFields src dst a i j d) x)
+
+/-- Specializing the output monomial gives exactly the paper's grouped
+local entry in every coefficient semiring. -/
+theorem describe_correct {D R : Type*} [CommMonoidWithZero R] (src dst : D → J) {a b : D → ℕ}
+ (hab : ∀ e, b e ≤ u * a e) (G : Supply J E) (w : S → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (κ : V → R) (table : List S)
+ (complete : ∀ s, s ∈ table) (code : S ↪ Word bits) (v : E → ℕ) (j : J)
+ (d : MotifDemandPadding.HalfBits src dst b j) (x : Half G (fun e => Word (v e + u * bits)) j) :
+ (describe src dst a b G w lookup table code v j (demandBits src dst j d)
+ (mapHalf G (fun _ => inputBits) x)).elim 0 (fun names => (names.map κ).prod) =
+ groupedMap G w (fun s j c y => κ (lookup s j c y)) code v j
+ (fun i => MotifDemandPadding.demandChunk src dst hab i j d) x := by
+ unfold describe groupedMap
+ rw [eval_labels, indices_eq_groupedIndices G w table complete]
+ simp_rw [demandFields_eq src dst hab]
+
+omit [DecidableEq J] [Fintype E] in
+/-- Every successful description denotes a single integral monomial of
+total degree at most the number of copies. -/
+theorem labels_monomial {G : Supply J E} {w : S → E → ℕ}
+ (lookup : ∀ s j, C j → Half G (fun e => Word (w s e)) j → V) (j : J)
+ (out : Option (EntryIndices G C w u j)) {names : List V}
+ (h : labels lookup j out = some names) :
+ ∃ m : V →₀ ℕ, (names.map (MvPolynomial.X (R := ℤ))).prod = MvPolynomial.monomial m 1 ∧
+ (names.map (MvPolynomial.X (R := ℤ))).prod.totalDegree ≤ u := by
+ cases out with
+ | none => simp [labels] at h
+ | some t =>
+ simp only [labels, Option.map_some, Option.some.injEq] at h
+ subst names
+ simp only [List.map_ofFn, List.prod_ofFn, Function.comp_apply]
+ exact ⟨_, MotifParameters.prod_entries_eq_monomial _, MotifParameters.prod_entries_degree_le _⟩
+
+section Work
+
+/-- Walk through the copies in order. A cons iteration charges the index step
+and the result-list cons in addition to the computed entry's own work. -/
+def scanCopies {A : Type*} : {u : ℕ} → (Fin u → A × ℕ) → List A × ℕ
+ | 0, _ => ([], 1)
+ | _ + 1, f =>
+ let head := f 0
+ let tail := scanCopies (fun i => f i.succ)
+ (head.1 :: tail.1, head.2 + tail.2 + 2)
+
+theorem scanCopies_spec {A : Type*} {u : ℕ} (f : Fin u → A × ℕ) :
+ (scanCopies f).1 = List.ofFn (fun i => (f i).1) ∧
+ (scanCopies f).2 = (∑ i, (f i).2) + 2 * u + 1 := by
+ induction u with
+ | zero => simp [scanCopies]
+ | succ u ih =>
+ obtain ⟨ho, hw⟩ := ih (fun i => f i.succ)
+ simp only [scanCopies, List.ofFn_succ, ho, hw, Fin.sum_univ_succ, Nat.mul_succ]
+ constructor
+ · trivial
+ · omega
+
+theorem scanCopies_le {A : Type*} {u B : ℕ} (f : Fin u → A × ℕ) (h : ∀ i, (f i).2 ≤ B) :
+ (scanCopies f).2 ≤ (B + 2) * u + 1 := by
+ rw [(scanCopies_spec f).2, Nat.add_mul]
+ have hs := Finset.sum_le_sum (s := Finset.univ) fun i _ => h i
+ simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] at hs
+ rw [Nat.mul_comm B u]
+ change (∑ i, (f i).2) ≤ u * B at hs
+ omega
+
+/-- Scan prior selector entries to find one payload offset. A width read and
+addition are charged at each iteration along with the index increment. -/
+def widthPrefix : {n : ℕ} → (Fin n → ℕ) → ℕ × ℕ
+ | 0, _ => (0, 1)
+ | _ + 1, w =>
+ let tail := widthPrefix (fun i => w i.succ)
+ (w 0 + tail.1, 3 + tail.2)
+
+theorem widthPrefix_spec {n : ℕ} (w : Fin n → ℕ) :
+ widthPrefix w = (∑ i, w i, 3 * n + 1) := by
+ induction n with
+ | zero => simp [widthPrefix]
+ | succ n ih =>
+ simp only [widthPrefix, ih, Fin.sum_univ_succ, Nat.mul_succ, Prod.mk.injEq, true_and]
+ omega
+
+/-- Count the code-table comparisons until the first match. -/
+def tableLookup {S : Type*} (p : S → Bool) : List S → Option S × ℕ
+ | [] => (none, 1)
+ | s :: ss =>
+ if p s then (some s, 2) else
+ let rest := tableLookup p ss
+ (rest.1, 2 + rest.2)
+
+theorem tableLookup_spec {S : Type*} (p : S → Bool) (ss : List S) :
+ (tableLookup p ss).1 = ss.find? p ∧ (tableLookup p ss).2 ≤ 2 * ss.length + 1 := by
+ induction ss with
+ | nil => simp [tableLookup]
+ | cons s ss ih =>
+ cases hs : p s <;>
+ simp only [tableLookup, hs, Bool.false_eq_true, ↓reduceIte, List.find?_cons,
+ List.length_cons, ih.1, true_and, Nat.mul_succ]
+ all_goals omega
+
+/-- A metered, typed field read. The counter uses indexed bit probes and
+word operations on positions, loop counters, and fixed-width base fields. -/
+def meteredIndex {n : ℕ} (x : Fin n → Bool) (off k : ℕ) : Word k × ℕ :=
+ let t := meteredField x off k
+ (⟨t.1, by rw [show t.1 = readField x off k from congrArg Prod.fst (meteredField_spec x off k)]
+ exact readField_lt _ _ _⟩, t.2)
+
+theorem meteredIndex_spec {n : ℕ} (x : Fin n → Bool) (off k : ℕ) :
+ meteredIndex x off k = (fieldIndex x off k, 6*k+1) := by
+ apply Prod.ext
+ · exact Fin.ext (congrArg Prod.fst (meteredField_spec _ _ _))
+ · change (meteredField x off k).2 = 6*k+1
+ rw [meteredField_spec]
+
+/-- Build a random-access array once. Count the indexed writes and the
+iterations of the construction loop, besides each cell's own operations. -/
+def arrayRun {A : Type*} {n : ℕ} (f : Fin n → A × ℕ) : (Fin n → A) × ℕ :=
+ let a := Vector.ofFn f
+ (fun i => a[i.val].1, (∑ i : Fin n, a[i.val].2) + 2*n+1)
+
+theorem arrayRun_spec {A : Type*} {n : ℕ} (f : Fin n → A × ℕ) :
+ arrayRun f = (fun i => (f i).1, (∑ i, (f i).2) + 2*n+1) := by simp [arrayRun]
+
+private theorem sum_le_card {I : Type*} [Fintype I] {B : ℕ} (f : I → ℕ) (h : ∀ i, f i ≤ B) :
+ ∑ i, f i ≤ Fintype.card I * B := by
+ simpa using Finset.sum_le_sum (s := Finset.univ) fun i _ => h i
+
+/-- Scan both ends of the fixed edge list. Each incident port supplies its
+input to the given field operation. Charge the loop, the endpoint tests, and
+writing the results to the party's local table. -/
+def portRun {I : Type*} [Fintype I] (src dst : I → J) {A B : I → Type*} (j : J)
+ (f : ∀ e, A e → B e × ℕ)
+ (x : ((e : I) → j = src e → A e) × ((e : I) → j = dst e → A e)) :
+ (((e : I) → j = src e → B e) × ((e : I) → j = dst e → B e)) × ℕ :=
+ ((fun e h => (f e (x.1 e h)).1, fun e h => (f e (x.2 e h)).1),
+ ∑ e, ((if h : j = src e then (f e (x.1 e h)).2 else 0) +
+ (if h : j = dst e then (f e (x.2 e h)).2 else 0) + 5))
+
+omit [Fintype E] in
+theorem portRun_le {I : Type*} [Fintype I] (src dst : I → J) {A B : I → Type*} (j : J)
+ (f : ∀ e, A e → B e × ℕ)
+ (x : ((e : I) → j = src e → A e) × ((e : I) → j = dst e → A e)) {n : ℕ}
+ (h : ∀ e y, (f e y).2 ≤ n) : (portRun src dst j f x).2 ≤ Fintype.card I * (2*n+5) := by
+ apply sum_le_card
+ intro e
+ split <;> split <;> grind
+
+/-- Stage one stores the selector words on all local ports, checks their
+agreement, and decodes the anchor's words into a random-access array. -/
+def selectorRun (G : Supply J E) (table : List S) (code : S ↪ Word bits)
+ (v : E → ℕ) (j : J) (x : Half G (fun e => Fin (v e + u * bits) → Bool) j) :
+ Option (Fin u → S) × ℕ :=
+ let batches := arrayRun fun i : Fin u => portRun G.src G.dst j (fun e y =>
+ let t := meteredIndex y (v e + bits*i.val) bits
+ (t.1, t.2+2)) x
+ let ports : Half G (fun _ => Fin u → Word bits) j :=
+ (fun e he i => (batches.1 i).1 e he, fun e he i => (batches.1 i).2 e he)
+ let t := anchor G j ports
+ let a := arrayRun fun i =>
+ let tag := t i
+ tableLookup (fun s => decide (code s = tag)) table
+ let decoded := if h : ∀ i : Fin u, (a.1 i).isSome then some fun i => (a.1 i).get (h i) else none
+ (if consistent G j ports then decoded else none,
+ batches.2 + 2*Fintype.card E*(3*u+3) + a.2 + 3*u+2)
+
+theorem selectorRun_value (G : Supply J E) (table : List S) (code : S ↪ Word bits)
+ (v : E → ℕ) (j : J) (x : Half G (fun e => Fin (v e + u * bits) → Bool) j) :
+ (selectorRun G table code v j x).1 =
+ let tags := mapHalf G (fun _ => readTag) x
+ if consistent G j tags then selectors? table code (anchor G j tags) else none := by
+ simp only [selectorRun, portRun, arrayRun_spec, meteredIndex_spec, mapHalf,
+ (tableLookup_spec _ _).1, selectors?, decode, Vector.getElem_ofFn]
+ rfl
+
+private theorem selectorRun_le (G : Supply J E) (table : List S) (code : S ↪ Word bits)
+ (v : E → ℕ) (j : J) (x : Half G (fun e => Fin (v e + u * bits) → Bool) j) :
+ (selectorRun G table code v j x).2 ≤
+ (Fintype.card E*(12*bits+25) + 2*table.length+10)*(u+1) := by
+ let f (i : Fin u) (e : E) (y : Fin (v e + u * bits) → Bool) :=
+ let t := meteredIndex y (v e + bits*i.val) bits
+ (t.1,t.2+2)
+ let batch (i : Fin u) := portRun G.src G.dst j (f i) x
+ have hf (i : Fin u) (e : E) (y : Fin (v e + u * bits) → Bool) : (f i e y).2 ≤ 6*bits+3 := by
+ simp only [f, meteredIndex_spec]
+ omega
+ have hp := sum_le_card (fun i => (batch i).2) (fun i => portRun_le G.src G.dst j (f i) x (hf i))
+ let a := (arrayRun batch).1
+ let t := anchor G j (I := fun _ => Fin u → Word bits)
+ (fun e h i => (a i).1 e h, fun e h i => (a i).2 e h)
+ let g (i : Fin u) := tableLookup (fun s => decide (code s = t i)) table
+ have hg := sum_le_card (fun i => (g i).2) (fun i => (tableLookup_spec _ table).2)
+ rw [Fintype.card_fin] at hg hp
+ change (arrayRun batch).2 + _ + (arrayRun g).2 + _ + 2 ≤ _
+ rw [arrayRun_spec, arrayRun_spec]
+ dsimp only
+ calc
+ _ ≤ (u*(Fintype.card E * (2*(6*bits+3)+5))+2*u+1) + 2*Fintype.card E*(3*u+3) +
+ (u*(2*table.length+1)+2*u+1)+3*u+2 := by omega
+ _ ≤ _ := by
+ ring_nf
+ omega
+
+/-- Compute and compare every edge's total width, including edges not
+incident to the party. -/
+def totalRun (w : S → E → ℕ) (v : E → ℕ) (θ : Fin u → S) : Bool × ℕ :=
+ let totals := fun e => widthPrefix (fun i => w (θ i) e)
+ (decide (∀ e, v e = (totals e).1), ∑ e, ((totals e).2+3))
+
+omit [DecidableEq J] in
+theorem totalRun_spec (w : S → E → ℕ) (v : E → ℕ) (θ : Fin u → S) :
+ totalRun w v θ = (decide (∀ e, v e = totalWidth w θ e), Fintype.card E*(3*u+4)) := by
+ simp [totalRun, widthPrefix_spec, totalWidth]
+ rfl
+
+/-- Once the selector array is known, collect both sets of incident fields
+for one base copy and return the corresponding parameter-table entry. -/
+def nameRun {D : Type*} [Fintype D] (src dst : D → J) (a b : D → ℕ)
+ (G : Supply J E) (w : S → E → ℕ) (θ : Fin u → S) (i : Fin u)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (v : E → ℕ) (j : J)
+ (d : DemandBits src dst b j) (x : Half G (fun e => Fin (v e + u * bits) → Bool) j) : V × ℕ :=
+ let ds := portRun src dst j (fun e y => meteredIndex y (a e * i.val) (a e)) d
+ let ps := portRun G.src G.dst j (fun e y =>
+ let off := widthPrefix (fun t : Fin i.val => w (θ (Fin.castLE i.isLt.le t)) e)
+ let field := meteredIndex (payloadBits y) off.1 (w (θ i) e)
+ (field.1, off.2 + field.2 + 2)) x
+ (lookup (θ i) j ds.1 ps.1, ds.2 + ps.2 + 3)
+
+private theorem nameRun_value {D : Type*} [Fintype D] (src dst : D → J) (a b : D → ℕ)
+ (G : Supply J E) (w : S → E → ℕ) (θ : Fin u → S) (i : Fin u)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (v : E → ℕ) (j : J)
+ (d : DemandBits src dst b j) (x : Half G (fun e => Fin (v e + u * bits) → Bool) j) :
+ (nameRun src dst a b G w θ i lookup v j d x).1 =
+ lookup (θ i) j (demandFields src dst a i j d)
+ (mapHalf G (fun e y => fieldIndex (payloadBits y) (offset (fun l => w (θ l) e) i)
+ (w (θ i) e)) x) := by
+ simp only [nameRun, portRun, meteredIndex_spec, widthPrefix_spec, demandFields, mapHalf, offset]
+
+private theorem nameRun_le {D : Type*} [Fintype D] (src dst : D → J) (a b : D → ℕ)
+ (G : Supply J E) (w : S → E → ℕ) (θ : Fin u → S) (i : Fin u)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (v : E → ℕ) (j : J)
+ (d : DemandBits src dst b j) (x : Half G (fun e => Fin (v e + u * bits) → Bool) j)
+ {A W : ℕ} (ha : ∀ e, a e ≤ A) (hw : ∀ s e, w s e ≤ W) :
+ (nameRun src dst a b G w θ i lookup v j d x).2 ≤
+ Fintype.card D*(12*A+7) + Fintype.card E*(6*u+12*W+13)+3 := by
+ let fd (e : D) (y : Fin (b e) → Bool) := meteredIndex y (a e * i.val) (a e)
+ have hd := portRun_le src dst j fd d (n := 6*A+1) (fun e y => by
+ simp only [fd, meteredIndex_spec]; have := ha e; omega)
+ let fs (e : E) (y : Fin (v e + u * bits) → Bool) :=
+ let off := widthPrefix (fun t : Fin i.val => w (θ (Fin.castLE i.isLt.le t)) e)
+ let field := meteredIndex (payloadBits y) off.1 (w (θ i) e)
+ (field.1, off.2 + field.2 + 2)
+ have hs := portRun_le G.src G.dst j fs x (n := 3*u+6*W+4) (fun e y => by
+ simp only [fs, widthPrefix_spec, meteredIndex_spec]; have := hw (θ i) e; have := i.isLt; omega)
+ change (portRun src dst j fd d).2 + (portRun G.src G.dst j fs x).2 + 3 ≤ _
+ convert Nat.add_le_add_right (Nat.add_le_add hd hs) 3 using 1
+ ring
+
+/-- Run the three stages on any input, including malformed selectors.
+The operation count includes the parameter lookup and each output-list cons. -/
+def run {D : Type*} [Fintype D] (src dst : D → J) (a b : D → ℕ)
+ (G : Supply J E) (w : S → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (table : List S) (code : S ↪ Word bits)
+ (v : E → ℕ) (j : J) (d : DemandBits src dst b j)
+ (x : Half G (fun e => Fin (v e + u * bits) → Bool) j) : Option (List V) × ℕ :=
+ let sel := selectorRun G table code v j x
+ match sel.1 with
+ | none => (none, sel.2+1)
+ | some θ =>
+ let total := totalRun w v θ
+ if total.1 then
+ let out := scanCopies (fun i => nameRun src dst a b G w θ i lookup v j d x)
+ (some out.1, sel.2+total.2+out.2+2)
+ else (none, sel.2+total.2+2)
+
+theorem run_value {D : Type*} [Fintype D] (src dst : D → J) (a b : D → ℕ)
+ (G : Supply J E) (w : S → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (table : List S) (code : S ↪ Word bits)
+ (v : E → ℕ) (j : J) (d : DemandBits src dst b j)
+ (x : Half G (fun e => Fin (v e + u * bits) → Bool) j) :
+ (run src dst a b G w lookup table code v j d x).1 =
+ describe src dst a b G w lookup table code v j d x := by
+ unfold run describe labels indices
+ dsimp only
+ rw [selectorRun_value]
+ let tags := mapHalf G (fun _ => readTag) x
+ by_cases hag : consistent G j tags = true
+ · simp only [tags] at hag
+ simp only [hag, ite_true]
+ cases selectors? table code _ with
+ | none => rfl
+ | some θ =>
+ dsimp only
+ rw [totalRun_spec]
+ simp only [decide_eq_true_eq, Option.bind_some, extract]
+ split
+ · simp only [Option.map_some, (scanCopies_spec _).1, nameRun_value, mapHalf]
+ · rfl
+ · simp only [tags] at hag
+ simp [hag]
+
+/-- The bit-probe and word-operation bound has an absolute quadratic
+exponent. Only the fixed motif tables enter the multiplicative constant. -/
+theorem run_le {D : Type*} [Fintype D] (src dst : D → J) (a b : D → ℕ)
+ (G : Supply J E) (w : S → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (table : List S) (code : S ↪ Word bits)
+ (v : E → ℕ) (j : J) (d : DemandBits src dst b j)
+ (x : Half G (fun e => Fin (v e + u * bits) → Bool) j)
+ {A W : ℕ} (ha : ∀ e, a e ≤ A) (hw : ∀ s e, w s e ≤ W) :
+ (run src dst a b G w lookup table code v j d x).2 ≤
+ (Fintype.card E*(12*bits+12*W+48) + Fintype.card D*(12*A+7) +
+ 2*table.length+18) * (u+1)^2 := by
+ have hsel := selectorRun_le G table code v j x
+ unfold run
+ dsimp only
+ split
+ · apply (Nat.add_le_add_right hsel 1).trans
+ ring_nf; omega
+ · rename_i θ _
+ rw [totalRun_spec]
+ split
+ · have hnames := scanCopies_le (fun i => nameRun src dst a b G w θ i lookup v j d x)
+ (fun i => nameRun_le src dst a b G w θ i lookup v j d x ha hw)
+ apply (Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add_right hsel _) hnames) 2).trans
+ ring_nf; omega
+ · apply (Nat.add_le_add_right (Nat.add_le_add_right hsel _) 2).trans
+ ring_nf; omega
+
+/-- Read one position by starting at the left end of a stored bit list.
+Out-of-range positions return zero. Every advance pays for inspecting the
+cell, decrementing the address, and moving to the next cell. -/
+def tapeProbe : List Bool → ℕ → Bool × ℕ
+ | [], _ => (false, 1)
+ | b :: _, 0 => (b, 2)
+ | _ :: bs, i+1 =>
+ let r := tapeProbe bs i
+ (r.1, r.2+3)
+
+theorem tapeProbe_spec (bs : List Bool) (i : ℕ) :
+ (tapeProbe bs i).1 = bs[i]?.getD false ∧ (tapeProbe bs i).2 ≤ 3*bs.length+2 := by
+ induction bs generalizing i with
+ | nil => simp [tapeProbe]
+ | cons b bs ih =>
+ cases i with
+ | zero => simp [tapeProbe]
+ | succ i =>
+ simp only [tapeProbe, List.getElem?_cons_succ, (ih i).1, true_and, List.length_cons]
+ have := (ih i).2
+ omega
+
+/-- Sequential storage for one input string of the specified width. -/
+abbrev Tape (n : ℕ) := {l : List Bool // l.length = n}
+
+/-- Read the bit at finite index `i` in a motif tape whose length is known. -/
+def Tape.readBits {n : ℕ} (t : Tape n) (i : Fin n) : Bool := (tapeProbe t.val i.val).1
+
+/-- Construct a motif tape by listing the bits of a function on `Fin n` in index order. -/
+def Tape.ofBits {n : ℕ} (b : Fin n → Bool) : Tape n := ⟨List.ofFn b, List.length_ofFn⟩
+
+theorem Tape.bits_ofBits {n : ℕ} (b : Fin n → Bool) : Tape.readBits (Tape.ofBits b) = b := by
+ funext i
+ simp [Tape.readBits, Tape.ofBits, (tapeProbe_spec _ _).1, i.isLt]
+
+theorem Tape.probe_le {n : ℕ} (t : Tape n) (i : ℕ) :
+ (tapeProbe t.val i).2 ≤ 3*n+2 := by simpa [t.property] using (tapeProbe_spec t.val i).2
+
+/-- A sequential-tape implementation with a conservative allowance for every
+indexed probe. The input length is the sum of the fixed motif's edge-string
+lengths. Ordinary control and word operations are charged the same allowance. -/
+def tapeRun {D : Type*} [Fintype D] (src dst : D → J) (a b : D → ℕ)
+ (G : Supply J E) (w : S → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (table : List S) (code : S ↪ Word bits)
+ (v : E → ℕ) (j : J)
+ (d : ((e : D) → j = src e → Tape (b e)) × ((e : D) → j = dst e → Tape (b e)))
+ (x : Half G (fun e => Tape (v e + u * bits)) j) : Option (List V) × ℕ :=
+ let result := run src dst a b G w lookup table code v j
+ (fun e h => Tape.readBits (d.1 e h), fun e h => Tape.readBits (d.2 e h))
+ (mapHalf G (fun _ => Tape.readBits) x)
+ let length := (∑ e, b e) + ∑ e, (v e + u*bits)
+ (result.1, (3*length+2)*result.2)
+
+/-- Each demand or supply probe in `tapeRun` fits in its reserved allowance. -/
+theorem tapeAllowance {D : Type*} [Fintype D] (b : D → ℕ) (v : E → ℕ) (u bits : ℕ) :
+ let L := (∑ e, b e) + ∑ e, (v e + u*bits)
+ (∀ (e : D) (t : Tape (b e)) i, (tapeProbe t.val i).2 ≤ 3*L+2) ∧
+ (∀ (e : E) (t : Tape (v e+u*bits)) i, (tapeProbe t.val i).2 ≤ 3*L+2) := by
+ constructor
+ · intro e t i
+ have h := Finset.single_le_sum (f := b) (fun _ _ => Nat.zero_le _) (Finset.mem_univ e)
+ have ht := t.probe_le i
+ omega
+ · intro e t i
+ have h := Finset.single_le_sum (f := fun e => v e+u*bits)
+ (fun _ _ => Nat.zero_le _) (Finset.mem_univ e)
+ have ht := t.probe_le i
+ omega
+
+/-- The rescan implementation has an absolute polynomial exponent even when
+the input tapes contain malformed data. -/
+theorem tapeRun_le {D : Type*} [Fintype D] (src dst : D → J) (a b : D → ℕ)
+ (G : Supply J E) (w : S → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e => Word (w s e)) j → V) (table : List S) (code : S ↪ Word bits)
+ (v : E → ℕ) (j : J)
+ (d : ((e : D) → j = src e → Tape (b e)) × ((e : D) → j = dst e → Tape (b e)))
+ (x : Half G (fun e => Tape (v e + u * bits)) j)
+ {A W : ℕ} (ha : ∀ e, a e ≤ A) (hw : ∀ s e, w s e ≤ W) :
+ let L := (∑ e, b e) + ∑ e, (v e + u*bits)
+ (tapeRun src dst a b G w lookup table code v j d x).2 ≤
+ (3*L+2) * ((Fintype.card E*(12*bits+12*W+48) + Fintype.card D*(12*A+7) +
+ 2*table.length+18)*(u+1)^2) :=
+ Nat.mul_le_mul_left _ (run_le src dst a b G w lookup table code v j _ _ ha hw)
+
+end Work
+
+end MotifEntry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifEntryWitness.lean b/lean/OAI/Computability/VPVNP/MotifEntryWitness.lean
new file mode 100644
index 0000000000..4ecbc378e7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifEntryWitness.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.MotifConversion
+import OAI.Computability.VPVNP.NetworkMonomials
+
+/-!
+# Monomial witnesses for fixed-motif entries
+
+The successful entry of a local conversion map reads one parameter label
+for every repeated base block. Its exponent vector counts these labels
+with multiplicity. A failed entry has an empty choice type.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifConversion
+
+open Diagonal NetworkKernel
+open scoped Classical
+
+variable {Label : Type} [Fintype Label] {A : Type*} [CommRing A] {u : ℕ}
+
+/-- Number of copies in which the entry reader returns a given parameter label. -/
+noncomputable def entryMultiplicity (t : Fin u → Label) (l : Label) : ℕ :=
+ ∑ i, if t i = l then 1 else 0
+
+theorem labelMonomial_entryMultiplicity (κ : Label → A) (t : Fin u → Label) :
+ labelMonomial κ (entryMultiplicity t) = ∏ i, κ (t i) := by
+ unfold entryMultiplicity
+ rw [labelMonomial_accumulate]
+ apply Finset.prod_congr rfl
+ intro i _
+ simp [labelMonomial, apply_ite]
+
+/-- A successful entry has one witness, including when its specialized
+coefficient is zero. All witness data are determined by the label list. -/
+noncomputable def entryWitness (κ : Label → A) (idx : Option (Fin u → Label)) :
+ MonomialWitness κ (evalEntry κ idx) :=
+ match idx with
+ | none => (MonomialWitness.paths κ Empty).changeValue (by simp [evalEntry])
+ | some t => (MonomialWitness.oneMonomial κ (entryMultiplicity t)).changeValue
+ (labelMonomial_entryMultiplicity κ t)
+
+@[simp] theorem entryWitness_some_exponents (κ : Label → A) (t : Fin u → Label)
+ (c : (entryWitness κ (some t)).Choice) (l : Label) :
+ (entryWitness κ (some t)).exponents c l = entryMultiplicity t l := rfl
+
+/-- Each accepted entry contributes exactly one label per base repetition. -/
+theorem entryWitness_totalExponent (κ : Label → A) (idx : Option (Fin u → Label))
+ (c : (entryWitness κ idx).Choice) : ∑ l, (entryWitness κ idx).exponents c l = u := by
+ cases idx with
+ | none => exact c.elim
+ | some t =>
+ simp only [entryWitness_some_exponents, entryMultiplicity]
+ rw [Finset.sum_comm]
+ simp
+
+end MotifConversion
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifGrid.lean b/lean/OAI/Computability/VPVNP/MotifGrid.lean
new file mode 100644
index 0000000000..c4e71ccd8b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifGrid.lean
@@ -0,0 +1,374 @@
+import Mathlib.Analysis.Real.Sqrt
+import Mathlib.Data.Rat.Floor
+import Mathlib.Data.Fintype.Pi
+import Mathlib.Tactic.FieldSimp
+import Mathlib.Tactic.Linarith
+import Mathlib.Tactic.Ring
+
+/-!
+# Rational width grids for a fixed wire motif
+
+In Theorem 6.1 of *VP and VNP differ over every field*, the spectral distances
+on the demand and supply edges obey a weighted quadratic inequality. The
+width grids below work simultaneously for every distance pattern satisfying
+that inequality. All entries have one common denominator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifGrid
+
+open scoped BigOperators
+
+variable {I : Type*} [Fintype I]
+
+/-- Width norm for edges with positive masses `p`. -/
+noncomputable def widthNorm (p x : I → ℝ) : ℝ := √(∑ i, x i ^ 2 / p i)
+
+/-- Squared distance in the dual weighted norm. -/
+noncomputable def distanceEnergy (p d : I → ℝ) : ℝ := ∑ i, p i * d i ^ 2
+
+/-- Logarithmic spectral value of a collection of wires. -/
+noncomputable def wireValue (x d : I → ℝ) : ℝ := ∑ i, x i * d i
+
+/-- Weighted Cauchy–Schwarz for the primal width norm and dual distance norm. -/
+theorem wireValue_le (p x d : I → ℝ) (hp : ∀ i, 0 < p i) :
+ wireValue x d ≤ widthNorm p x * √(distanceEnergy p d) := by
+ have hroot (i : I) : 0 < √(p i) := Real.sqrt_pos.mpr (hp i)
+ have cross (i : I) : x i / √(p i) * (√(p i) * d i) = x i * d i := by
+ field_simp [(hroot i).ne']
+ have left (i : I) : (x i / √(p i)) ^ 2 = x i ^ 2 / p i := by
+ rw [div_pow, Real.sq_sqrt (hp i).le]
+ have right (i : I) : (√(p i) * d i) ^ 2 = p i * d i ^ 2 := by
+ rw [mul_pow, Real.sq_sqrt (hp i).le]
+ simpa only [wireValue, widthNorm, distanceEnergy, cross, left, right] using
+ Real.sum_mul_le_sqrt_mul_sqrt Finset.univ (fun i ↦ x i / √(p i)) (fun i ↦ √(p i) * d i)
+
+/-- Squaring the width norm recovers its weighted energy. -/
+theorem norm_sq (p x : I → ℝ) (hp : ∀ i, 0 < p i) :
+ widthNorm p x ^ 2 = ∑ i, x i ^ 2 / p i :=
+ Real.sq_sqrt (Finset.sum_nonneg fun i _ ↦ div_nonneg (sq_nonneg _) (hp i).le)
+
+/-- A single edge contributes at most the full width norm. -/
+theorem coordinate_le (p x : I → ℝ) (hp : ∀ i, 0 < p i) (i : I) :
+ x i ≤ √(p i) * widthNorm p x := by
+ have h := Finset.single_le_sum (f := fun j ↦ x j ^ 2 / p j)
+ (fun j _ ↦ div_nonneg (sq_nonneg _) (hp j).le) (Finset.mem_univ i)
+ rw [← norm_sq _ _ hp] at h
+ have hle := (div_le_iff₀ (hp i)).mp h
+ have hsq : (√(p i) * widthNorm p x) ^ 2 = p i * widthNorm p x ^ 2 := by
+ rw [mul_pow, Real.sq_sqrt (hp i).le]
+ by_contra! hlt
+ have hpos : 0 ≤ √(p i) * widthNorm p x := mul_nonneg (Real.sqrt_nonneg (p i)) (Real.sqrt_nonneg _)
+ nlinarith only [hsq, hle, mul_self_lt_mul_self hpos hlt]
+
+private theorem wireValue_mono (x y d : I → ℝ) (hxy : ∀ i, x i ≤ y i)
+ (hd : ∀ i, 0 ≤ d i) : wireValue x d ≤ wireValue y d :=
+ Finset.sum_le_sum fun i _ ↦ mul_le_mul_of_nonneg_right (hxy i) (hd i)
+
+/-- The width norm is monotone on nonnegative widths. -/
+theorem norm_mono (p x y : I → ℝ) (hp : ∀ i, 0 < p i)
+ (hx : ∀ i, 0 ≤ x i) (hxy : ∀ i, x i ≤ y i) : widthNorm p x ≤ widthNorm p y :=
+ Real.sqrt_le_sqrt (Finset.sum_le_sum fun i _ ↦ div_le_div_of_nonneg_right
+ (pow_le_pow_left₀ (hx i) (hxy i) _) (hp i).le)
+
+private theorem add_error_value (x d : I → ℝ) (ε : ℝ) :
+ wireValue (fun i ↦ x i + ε) d = wireValue x d + ε * wireValue (fun _ ↦ 1) d := by
+ simp [wireValue, add_mul, Finset.sum_add_distrib, Finset.mul_sum]
+
+/-- Coordinatewise upward rounding by at most `ε` increases the norm by at most
+`ε` times the width norm of the all-ones vector. -/
+theorem widthNorm_round_le (p x z : I → ℝ) (hp : ∀ i, 0 < p i) {ε : ℝ} (hε : 0 ≤ ε)
+ (hz : ∀ i, 0 ≤ z i) (hxz : ∀ i, z i ≤ x i + ε) :
+ widthNorm p z ≤ widthNorm p x + ε * widthNorm p (fun _ ↦ 1) := by
+ let d := fun i ↦ z i / p i
+ have hd i : 0 ≤ d i := div_nonneg (hz i) (hp i).le
+ have henergy : √(distanceEnergy p d) = widthNorm p z := by
+ unfold distanceEnergy widthNorm
+ congr 1
+ apply Finset.sum_congr rfl
+ intro i _
+ dsimp [d]
+ field_simp [(hp i).ne']
+ have hval : wireValue z d = widthNorm p z ^ 2 := by
+ rw [norm_sq _ _ hp]
+ unfold wireValue
+ apply Finset.sum_congr rfl
+ intro i _
+ dsimp [d]
+ ring
+ have hr := wireValue_mono z (fun i ↦ x i + ε) d hxz hd
+ rw [hval, add_error_value] at hr
+ have hx := wireValue_le p x d hp
+ have h1 := wireValue_le p (fun _ ↦ 1) d hp
+ rw [henergy] at hx h1
+ by_cases hzero : widthNorm p z = 0
+ · rw [hzero]
+ exact add_nonneg (Real.sqrt_nonneg _) (mul_nonneg hε (Real.sqrt_nonneg _))
+ · have hpos : 0 < widthNorm p z := lt_of_le_of_ne (Real.sqrt_nonneg _) (Ne.symm hzero)
+ apply (le_of_mul_le_mul_right _ hpos)
+ nlinarith only [hr, hx, mul_le_mul_of_nonneg_left h1 hε]
+
+/-- One finite box of vectors on a common rational mesh. -/
+private noncomputable def boxGrid (B : ℕ) (K : I → ℝ) : Finset (I → ℚ) := by
+ classical
+ exact Finset.univ.image (fun f : (i : I) → Fin (⌈(B : ℝ) * K i⌉₊ + 1) ↦
+ fun i ↦ (f i).val / (B : ℚ))
+
+private theorem zero_mem_boxGrid (B : ℕ) (K : I → ℝ) : (fun _ ↦ 0) ∈ boxGrid B K := by
+ classical
+ refine Finset.mem_image.mpr ⟨fun _ ↦ 0, Finset.mem_univ _, ?_⟩
+ ext i
+ simp
+
+private theorem boxGrid_nonneg {B : ℕ} {K : I → ℝ} {r : I → ℚ} (hr : r ∈ boxGrid B K) :
+ ∀ i, 0 ≤ r i := by
+ classical
+ obtain ⟨f, _, rfl⟩ := Finset.mem_image.mp hr
+ intro i
+ dsimp
+ positivity
+
+private theorem boxGrid_integral {B : ℕ} {K : I → ℝ} {r : I → ℚ} (hr : r ∈ boxGrid B K) :
+ ∃ k : I → ℕ, ∀ i, r i = (k i : ℚ) / B := by
+ classical
+ obtain ⟨f, _, rfl⟩ := Finset.mem_image.mp hr
+ exact ⟨fun i ↦ (f i).val, fun _ ↦ rfl⟩
+
+private theorem round_box {B : ℕ} (hB : (0 : ℝ) < B) (K x : I → ℝ)
+ (hx : ∀ i, 0 ≤ x i) (hK : ∀ i, x i ≤ K i) :
+ ∃ u ∈ boxGrid B K, ∃ l ∈ boxGrid B K, ∀ i,
+ (x i ≤ (u i : ℝ) ∧ (u i : ℝ) ≤ x i + 1 / B) ∧
+ ((l i : ℝ) ≤ x i ∧ x i ≤ (l i : ℝ) + 1 / B) := by
+ classical
+ let k := fun i ↦ (B : ℝ) * x i
+ have hcap i : ⌈k i⌉₊ ≤ ⌈(B : ℝ) * K i⌉₊ := Nat.ceil_mono (mul_le_mul_of_nonneg_left (hK i) hB.le)
+ let u := fun i ↦ (⟨⌈k i⌉₊, Nat.lt_succ_of_le (hcap i)⟩ : Fin (⌈(B : ℝ) * K i⌉₊ + 1))
+ let l := fun i ↦ (⟨⌊k i⌋₊, Nat.lt_succ_of_le ((Nat.floor_le_ceil _).trans (hcap i))⟩ :
+ Fin (⌈(B : ℝ) * K i⌉₊ + 1))
+ refine ⟨_, Finset.mem_image_of_mem _ (Finset.mem_univ u),
+ _, Finset.mem_image_of_mem _ (Finset.mem_univ l), ?_⟩
+ intro i
+ have hk : 0 ≤ k i := mul_nonneg hB.le (hx i)
+ simp only [u, l, Rat.cast_div, Rat.cast_natCast, ← add_div]
+ constructor
+ · constructor
+ · exact (le_div_iff₀ hB).mpr (by simpa [k, mul_comm] using Nat.le_ceil (k i))
+ · apply (div_le_iff₀ hB).mpr
+ have := Nat.ceil_lt_add_one hk
+ dsimp [k] at this ⊢
+ rw [add_mul, div_mul_cancel₀ _ hB.ne']
+ linarith
+ · constructor
+ · exact (div_le_iff₀ hB).mpr (by simpa [k, mul_comm] using Nat.floor_le hk)
+ · exact (le_div_iff₀ hB).mpr (by simpa [k, mul_comm] using (Nat.lt_floor_add_one (k i)).le)
+
+/-- Optimal supply widths at dual distances `d`. -/
+private noncomputable def maximizer (q d : I → ℝ) (R : ℝ) : I → ℝ :=
+ fun i ↦ (R / √(distanceEnergy q d)) * (q i * d i)
+
+private theorem maximizer_value (q d : I → ℝ) (R : ℝ) (hE : 0 < distanceEnergy q d) :
+ wireValue (maximizer q d R) d = R * √(distanceEnergy q d) := by
+ have he := Real.sq_sqrt hE.le
+ have hs := (Real.sqrt_pos.mpr hE).ne'
+ calc
+ _ = R / √(distanceEnergy q d) * distanceEnergy q d := by
+ unfold wireValue maximizer distanceEnergy
+ rw [Finset.mul_sum]
+ exact Finset.sum_congr rfl fun _ _ ↦ by ring
+ _ = R / √(distanceEnergy q d) * (√(distanceEnergy q d)) ^ 2 := by rw [he]
+ _ = _ := by field_simp [hs]
+
+private theorem maximizer_norm (q d : I → ℝ) (hq : ∀ i, 0 < q i) {R : ℝ} (hR : 0 ≤ R)
+ (hE : 0 < distanceEnergy q d) : widthNorm q (maximizer q d R) = R := by
+ have hsq : widthNorm q (maximizer q d R) ^ 2 = R ^ 2 := by
+ rw [norm_sq _ _ hq]
+ calc
+ _ = (R / √(distanceEnergy q d)) ^ 2 * distanceEnergy q d := by
+ rw [show (R / √(distanceEnergy q d)) ^ 2 * distanceEnergy q d =
+ ∑ i, (R / √(distanceEnergy q d)) ^ 2 * (q i * d i ^ 2) by
+ unfold distanceEnergy; rw [Finset.mul_sum]]
+ apply Finset.sum_congr rfl
+ intro i _
+ unfold maximizer
+ rw [mul_pow, mul_pow]
+ field_simp [(hq i).ne']
+ _ = _ := by rw [div_pow, Real.sq_sqrt hE.le, div_mul_cancel₀ _ hE.ne']
+ rcases sq_eq_sq_iff_eq_or_eq_neg.mp hsq with heq | hneg
+ · exact heq
+ · have hnorm : 0 ≤ widthNorm q (maximizer q d R) := Real.sqrt_nonneg _
+ linarith
+
+/-- Cast a rational width vector into the real weighted space. -/
+def realWidths (z : I → ℚ) : I → ℝ := fun i ↦ z i
+
+private theorem zero_norm (m : I → ℝ) : widthNorm m (realWidths (fun _ ↦ 0)) = 0 :=
+ by simp [realWidths, widthNorm]
+
+variable {D S : Type*} [Fintype D] [Fintype S]
+
+/-- The two finite grids, their common denominator, and their approximation and
+comparison properties. The supply witness may depend on the spectral point. -/
+structure StrictGrids (p : D → ℝ) (q : S → ℝ) (H R : ℝ) where
+ /-- Positive integer giving the common mesh size through its reciprocal on both rational
+ grids. -/
+ denominator : ℕ
+ denominator_pos : 0 < denominator
+ /-- Finite rational demand-width vectors that cover every nonnegative demand of weighted norm
+ at most one by coordinatewise rounding up. -/
+ demands : Finset (D → ℚ)
+ /-- Finite rational supply-width vectors of weighted norm at most the supply radius, among
+ which strict domination is witnessed. -/
+ supplies : Finset (S → ℚ)
+ zero_mem_demands : (fun _ ↦ 0) ∈ demands
+ zero_mem_supplies : (fun _ ↦ 0) ∈ supplies
+ demand_integral : ∀ z ∈ demands, ∃ k : D → ℕ, ∀ i, z i = (k i : ℚ) / denominator
+ supply_integral : ∀ w ∈ supplies, ∃ k : S → ℕ, ∀ i, w i = (k i : ℚ) / denominator
+ slack : (1 + (1 / denominator : ℝ) * widthNorm p (fun _ ↦ 1)) * √H +
+ (1 / denominator : ℝ) * widthNorm q (fun _ ↦ 1) < R
+ demand_norm : ∀ z ∈ demands, widthNorm p (realWidths z) ≤
+ 1 + (1 / denominator : ℝ) * widthNorm p (fun _ ↦ 1)
+ supply_norm : ∀ w ∈ supplies, widthNorm q (realWidths w) ≤ R
+ cover : ∀ x : D → ℝ, (∀ i, 0 ≤ x i) → widthNorm p x ≤ 1 →
+ ∃ z ∈ demands, ∀ i, x i ≤ z i ∧ (z i : ℝ) ≤ x i + 1 / denominator
+ strict : ∀ z ∈ demands, ∀ (d : D → ℝ) (e : S → ℝ), (∀ i, 0 ≤ e i) →
+ 0 < distanceEnergy q e → distanceEnergy p d ≤ H * distanceEnergy q e →
+ ∃ w ∈ supplies, wireValue (realWidths z) d < wireValue (realWidths w) e
+
+/-- Uniform finite rational approximation in the first part of Theorem 6.1.
+The grid is independent of the demand widths and of the spectral point. -/
+theorem exists_strict_grids (p : D → ℝ) (q : S → ℝ) (hp : ∀ i, 0 < p i)
+ (hq : ∀ i, 0 < q i) {H R : ℝ} (hH : 0 ≤ H) (hR : √H < R) : Nonempty (StrictGrids p q H R) := by
+ classical
+ let P := widthNorm p (fun _ ↦ 1)
+ let Q := widthNorm q (fun _ ↦ 1)
+ have hP : 0 ≤ P := Real.sqrt_nonneg _
+ have hQ : 0 ≤ Q := Real.sqrt_nonneg _
+ have hgap : 0 < R - √H := sub_pos.mpr hR
+ obtain ⟨B, hB⟩ := exists_nat_gt ((√H * P + Q) / (R - √H))
+ have hpos : (0 : ℝ) < B := (div_nonneg (add_nonneg (mul_nonneg (Real.sqrt_nonneg _) hP) hQ)
+ hgap.le).trans_lt hB
+ let ε : ℝ := 1 / B
+ have hε : 0 ≤ ε := div_nonneg zero_le_one hpos.le
+ have hslack : (1 + ε * P) * √H + ε * Q < R := by
+ have ht : (√H * P + Q) / B < R - √H := (div_lt_iff₀ hpos).mpr (by
+ linarith only [(div_lt_iff₀ hgap).mp hB])
+ dsimp [ε]
+ rw [show (1 + 1 / (B : ℝ) * P) * √H + 1 / B * Q = √H + (√H * P + Q) / B by ring]
+ linarith
+ let Z := (boxGrid B (fun i ↦ √(p i))).filter fun z ↦ widthNorm p (realWidths z) ≤ 1 + ε * P
+ let W := (boxGrid B (fun i ↦ √(q i) * R)).filter fun w ↦ widthNorm q (realWidths w) ≤ R
+ refine ⟨⟨B, Nat.cast_pos.mp hpos, Z, W,
+ Finset.mem_filter.mpr ⟨zero_mem_boxGrid _ _, (zero_norm _).trans_le
+ (add_nonneg zero_le_one (mul_nonneg hε hP))⟩,
+ Finset.mem_filter.mpr ⟨zero_mem_boxGrid _ _,
+ (zero_norm _).trans_le ((Real.sqrt_nonneg H).trans hR.le)⟩,
+ fun _ hz ↦ boxGrid_integral (Finset.mem_filter.mp hz).1,
+ fun _ hw ↦ boxGrid_integral (Finset.mem_filter.mp hw).1, hslack,
+ fun _ hz ↦ (Finset.mem_filter.mp hz).2, fun _ hw ↦ (Finset.mem_filter.mp hw).2, ?_, ?_⟩⟩
+ · intro x hx hnorm
+ have hcap i : x i ≤ √(p i) := (coordinate_le p x hp i).trans <| by
+ simpa using mul_le_mul_of_nonneg_left hnorm (Real.sqrt_nonneg (p i))
+ obtain ⟨z, hz, _, _, happrox⟩ := round_box hpos _ x hx hcap
+ refine ⟨z, Finset.mem_filter.mpr ⟨hz, ?_⟩, fun i ↦ (happrox i).1⟩
+ have hz0 i : 0 ≤ realWidths z i := Rat.cast_nonneg.mpr (boxGrid_nonneg hz i)
+ exact (widthNorm_round_le p x _ hp hε hz0 (fun i ↦ (happrox i).1.2)).trans
+ (add_le_add_left hnorm _)
+ · intro z hz d e he hE hcomp
+ let wstar := maximizer q e R
+ have hR0 := (Real.sqrt_nonneg H).trans hR.le
+ have hw i : 0 ≤ wstar i := mul_nonneg (div_nonneg hR0 (Real.sqrt_nonneg _))
+ (mul_nonneg (hq i).le (he i))
+ have hnorm : widthNorm q wstar = R := maximizer_norm q e hq hR0 hE
+ have hcap i : wstar i ≤ √(q i) * R := by simpa [hnorm] using coordinate_le q wstar hq i
+ obtain ⟨_, _, w, hwmem, happrox⟩ := round_box hpos _ wstar hw hcap
+ have hw0 i : 0 ≤ realWidths w i := Rat.cast_nonneg.mpr (boxGrid_nonneg hwmem i)
+ refine ⟨w, Finset.mem_filter.mpr ⟨hwmem, (norm_mono q _ _ hq hw0
+ (fun i ↦ (happrox i).2.1)).trans hnorm.le⟩, ?_⟩
+ let L := √(distanceEnergy q e)
+ have hL : 0 < L := Real.sqrt_pos.mpr hE
+ have hdual : √(distanceEnergy p d) ≤ √H * L := by
+ rw [← Real.sqrt_mul hH]; exact Real.sqrt_le_sqrt hcomp
+ have hzbound : widthNorm p (realWidths z) ≤ 1 + ε * P := (Finset.mem_filter.mp hz).2
+ have hzvalue : wireValue (realWidths z) d ≤ (1 + ε * P) * (√H * L) :=
+ (wireValue_le _ _ _ hp).trans (mul_le_mul hzbound hdual (Real.sqrt_nonneg _)
+ (add_nonneg zero_le_one (mul_nonneg hε hP)))
+ have hwvalue := wireValue_mono wstar (fun i ↦ realWidths w i + ε) e
+ (fun i ↦ (happrox i).2.2) he
+ rw [add_error_value, show wireValue wstar e = R * L from maximizer_value q e R hE] at hwvalue
+ have hones := wireValue_le q (fun _ ↦ 1) e hq
+ change wireValue (fun _ ↦ 1) e ≤ Q * L at hones
+ nlinarith only [hzvalue, hwvalue, mul_le_mul_of_nonneg_left hones hε,
+ mul_lt_mul_of_pos_right hslack hL]
+
+/-- Scaling all widths by a nonnegative factor scales their norm by that factor. -/
+theorem widthNorm_scale (p x : I → ℝ) {a : ℝ} (ha : 0 ≤ a) :
+ widthNorm p (fun i ↦ a * x i) = a * widthNorm p x := by
+ unfold widthNorm
+ simp_rw [mul_pow, mul_div_assoc]
+ rw [← Finset.mul_sum, Real.sqrt_mul (sq_nonneg a), Real.sqrt_sq ha]
+
+/-- Scaling all widths scales the logarithmic wire value. -/
+theorem wireValue_scale (x d : I → ℝ) (a : ℝ) :
+ wireValue (fun i ↦ a * x i) d = a * wireValue x d := by
+ simp [wireValue, Finset.mul_sum, mul_assoc]
+
+namespace StrictGrids
+
+variable {p : D → ℝ} {q : S → ℝ} {H R : ℝ} (G : StrictGrids p q H R)
+
+/-- Demand bit widths when the base scale is `t * G.denominator`. -/
+noncomputable def demandWidths (t : ℕ) (z : G.demands) (i : D) : ℕ :=
+ t * (G.demand_integral _ z.property).choose i
+
+/-- Supply bit widths on the same base scale. -/
+noncomputable def supplyWidths (t : ℕ) (w : G.supplies) (i : S) : ℕ :=
+ t * (G.supply_integral _ w.property).choose i
+
+@[simp] theorem cast_demandWidths (t : ℕ) (z : G.demands) (i : D) :
+ (G.demandWidths t z i : ℝ) = ((t * G.denominator : ℕ) : ℝ) * (z.val i : ℝ) := by
+ rw [(G.demand_integral _ z.property).choose_spec i]
+ unfold demandWidths
+ push_cast
+ field_simp [show (G.denominator : ℝ) ≠ 0 from Nat.cast_ne_zero.mpr G.denominator_pos.ne']
+
+@[simp] theorem cast_supplyWidths (t : ℕ) (w : G.supplies) (i : S) :
+ (G.supplyWidths t w i : ℝ) = ((t * G.denominator : ℕ) : ℝ) * (w.val i : ℝ) := by
+ rw [(G.supply_integral _ w.property).choose_spec i]
+ unfold supplyWidths
+ push_cast
+ field_simp [show (G.denominator : ℝ) ≠ 0 from Nat.cast_ne_zero.mpr G.denominator_pos.ne']
+
+/-- The finite supply list has the required integral norm bound at every multiple. -/
+theorem supplyWidths_norm_le (t : ℕ) (w : G.supplies) :
+ widthNorm q (fun i ↦ (G.supplyWidths t w i : ℝ)) ≤ (t * G.denominator : ℕ) * R := by
+ simp_rw [cast_supplyWidths]
+ rw [widthNorm_scale _ _ (by positivity)]
+ exact mul_le_mul_of_nonneg_left (G.supply_norm _ w.property) (by positivity)
+
+/-- At any positive multiple of the mesh denominator the integer widths retain
+strict comparison. The supply index is chosen after the two distance patterns. -/
+theorem integer_strict {t : ℕ} (ht : 0 < t) (z : G.demands) (d : D → ℝ) (e : S → ℝ)
+ (he : ∀ i, 0 ≤ e i) (hE : 0 < distanceEnergy q e)
+ (hcomp : distanceEnergy p d ≤ H * distanceEnergy q e) :
+ ∃ w : G.supplies, wireValue (fun i ↦ (G.demandWidths t z i : ℝ)) d <
+ wireValue (fun i ↦ (G.supplyWidths t w i : ℝ)) e := by
+ obtain ⟨w, hw, hval⟩ := G.strict z z.property d e he hE hcomp
+ refine ⟨⟨w, hw⟩, ?_⟩
+ simp_rw [cast_demandWidths, cast_supplyWidths, wireValue_scale]
+ exact mul_lt_mul_of_pos_left hval (Nat.cast_pos.mpr (Nat.mul_pos ht G.denominator_pos))
+
+/-- Multiples of the common denominator can exceed any prescribed base size. -/
+theorem exists_large_scale (b : ℕ) : ∃ t : ℕ, 0 < t ∧ b < t * G.denominator := by
+ refine ⟨b + 1, Nat.succ_pos _, (Nat.lt_succ_self _).trans_le ?_⟩
+ simpa using Nat.mul_le_mul_left (b + 1) G.denominator_pos
+
+end StrictGrids
+
+end MotifGrid
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifIntegralWires.lean b/lean/OAI/Computability/VPVNP/MotifIntegralWires.lean
new file mode 100644
index 0000000000..8ad7d45654
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifIntegralWires.lean
@@ -0,0 +1,35 @@
+import OAI.Computability.VPVNP.WireTensor
+
+/-!
+# Integral coefficients of wire networks
+
+The supply and demand networks in the motif identities of Section 6 use the
+same bases over every field. Their coefficients are obtained from the integer
+network by the canonical ring homomorphism.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+variable (R : Type*) [CommRing R] {E J : Type*} [Fintype E]
+variable (a b : E → J) (I : E → Type*) [∀ e, Fintype (I e)]
+
+/-- The equality check at each edge has integral coefficients in every characteristic. -/
+theorem intCast_wireNetwork_coeff (x : ∀ j, (wireNetwork (k := ℤ) a b I).Basis j) :
+ ((wireNetwork (k := ℤ) a b I).coeff x : R) = (wireNetwork (k := R) a b I).coeff x := by
+ classical
+ simp [wireNetwork, apply_ite Int.cast]
+
+/-- Entrywise scalar extension of the integer network gives the network over the new ring. -/
+theorem intCast_wireNetwork_coeff_fun :
+ (fun x ↦ ((wireNetwork (k := ℤ) a b I).coeff x : R)) = (wireNetwork (k := R) a b I).coeff :=
+ funext (intCast_wireNetwork_coeff R a b I)
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifLocalSelectors.lean b/lean/OAI/Computability/VPVNP/MotifLocalSelectors.lean
new file mode 100644
index 0000000000..9b0a78e577
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifLocalSelectors.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.MotifSelector
+import OAI.Computability.VPVNP.WireTensor
+
+/-!
+# Local selector checks inside wire tensors
+
+The selector carried by each edge is read at its two incident parties. This
+realizes the global selector sum as a contraction of one wire network, and
+retains the payload on each individual edge.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifSelector
+
+open WireTensor
+
+variable {J E S R : Type*}
+
+/-- Half-wire coordinates local to one party. -/
+abbrev Half (G : Supply J E) (I : E → Type*) (j : J) :=
+ ((e : E) → j = G.src e → I e) × ((e : E) → j = G.dst e → I e)
+
+/-- Apply a separate coordinate transformation at each incident wire. -/
+def mapHalf {I I' : E → Type*} (G : Supply J E) {j : J} (f : ∀ e, I e → I' e)
+ (x : Half G I j) : Half G I' j :=
+ (fun e h => f e (x.1 e h), fun e h => f e (x.2 e h))
+
+theorem mapHalf_edgeAssignment {I I' : E → Type*} (G : Supply J E) (j : J)
+ (f : ∀ e, I e → I' e) (x : ∀ e, I e) :
+ mapHalf G f (edgeAssignment G.src G.dst x j) =
+ edgeAssignment G.src G.dst (fun e => f e (x e)) j := rfl
+
+/-- Read the chosen incident edge through its appropriate half-wire. -/
+noncomputable def readAnchor (G : Supply J E) {I : E → Type*} (j : J) (x : Half G I j) :
+ I (G.anchor j) := by
+ classical
+ exact if h : j = G.src (G.anchor j) then x.1 (G.anchor j) h else
+ x.2 (G.anchor j) ((G.anchor_incident j).resolve_left (fun he => h he.symm)).symm
+
+@[simp] theorem readAnchor_edgeAssignment (G : Supply J E) {I : E → Type*} (j : J)
+ (x : ∀ e, I e) : readAnchor G j (edgeAssignment G.src G.dst x j) = x (G.anchor j) := by
+ unfold readAnchor
+ split <;> rfl
+
+/-- A party checks that all of its incident edges carry its anchor selector. -/
+def HalfAgrees (G : Supply J E) {I : E → Type*} (j : J) (x : Half G (fun e => S × I e) j) :
+ Prop :=
+ (∀ e (h : j = G.src e), (x.1 e h).1 = (readAnchor G j x).1) ∧
+ (∀ e (h : j = G.dst e), (x.2 e h).1 = (readAnchor G j x).1)
+
+@[simp] theorem halfAgrees_edgeAssignment (G : Supply J E) {I : E → Type*} (j : J)
+ (x : ∀ e, S × I e) :
+ HalfAgrees G j (edgeAssignment G.src G.dst x j) ↔ Agrees G (fun e => (x e).1) j := by
+ unfold HalfAgrees Agrees
+ rw [readAnchor_edgeAssignment]
+ constructor
+ · rintro ⟨h₁, h₂⟩ e (he | he)
+ · exact h₁ e he.symm
+ · exact h₂ e he.symm
+ · intro h
+ exact ⟨fun e he => h e (Or.inl he.symm), fun e he => h e (Or.inr he.symm)⟩
+
+open scoped Classical in
+/-- Carry selector and payload on every supply edge and use only the payload
+in the original map after the selectors have been checked. -/
+noncomputable def selectedMap [Zero R] {I : E → Type*} {C : J → Type*} (G : Supply J E)
+ (L : ∀ (_ : S) (j : J), C j → Half G I j → R) (j : J)
+ (c : C j) (x : Half G (fun e => S × I e) j) : R :=
+ if HalfAgrees G j x then
+ L (readAnchor G j x).1 j c (mapHalf G (fun _ => Prod.snd) x) else 0
+
+open scoped Classical in
+/-- Exact local-map implementation of the selector sum in Theorem 6.1. -/
+theorem applyLocal_selectedMap [Nonempty J] [Fintype J] [Fintype E] [Fintype S]
+ [CommSemiring R] {I : E → Type*} [∀ e, Fintype (I e)] {C : J → Type*} (G : Supply J E)
+ (L : ∀ (_ : S) (j : J), C j → Half G I j → R) :
+ applyLocal (B := (wireNetwork (k := R) G.src G.dst (fun e => S × I e)).Basis)
+ (selectedMap G L) (wireNetwork G.src G.dst (fun e => S × I e)).coeff =
+ ∑ s, applyLocal (B := (wireNetwork (k := R) G.src G.dst I).Basis)
+ (L s) (wireNetwork G.src G.dst I).coeff := by
+ classical
+ funext c
+ rw [Finset.sum_apply]
+ erw [applyLocal_wireNetwork G.src G.dst (fun e => S × I e) (selectedMap G L) c]
+ have he (s : S) := applyLocal_wireNetwork G.src G.dst I (L s) c
+ simp_rw [he]
+ let eqv := Equiv.arrowProdEquivProdArrow E (fun _ => S) I
+ rw [← eqv.symm.sum_comp, Fintype.sum_prod_type]
+ simp only [selectedMap, halfAgrees_edgeAssignment, readAnchor_edgeAssignment,
+ mapHalf_edgeAssignment]
+ change (∑ x : E → S, ∑ y : ∀ e, I e,
+ ∏ j, if Agrees G x j then L (x (G.anchor j)) j (c j) (edgeAssignment G.src G.dst y j)
+ else 0) = _
+ rw [Finset.sum_comm, Finset.sum_comm (s := (Finset.univ : Finset S))]
+ exact Finset.sum_congr rfl fun y _ =>
+ sum_local_checks G (fun j s => L s j (c j) (edgeAssignment G.src G.dst y j))
+
+end MotifSelector
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifOrdinarySum.lean b/lean/OAI/Computability/VPVNP/MotifOrdinarySum.lean
new file mode 100644
index 0000000000..23c6940501
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifOrdinarySum.lean
@@ -0,0 +1,67 @@
+import OAI.Computability.VPVNP.TensorRestrictionSemiring
+
+/-!
+# From a restriction by a direct sum to an ordinary sum of images
+
+The base identities in Theorem 6.1 use one local linear map per party for
+each summand. A restriction from the direct sum supplies these maps by
+restricting the original matrices to each summand's coordinate block.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+
+namespace WireTensor
+
+open RestrictionClass
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nonempty J]
+
+/-- A finite direct sum dominating the demand yields an ordinary sum identity
+with exactly the same indices, in the demand's given coordinate spaces. -/
+theorem ordinary_sum_of_class_le_finset {ι : Type*} (s : Finset ι)
+ (X : Tensor.{u,v,0} k J) (Y : ι → Tensor.{u,v,0} k J)
+ (h : ofTensor X ≤ ∑ i ∈ s, ofTensor (Y i)) :
+ ∃ L : ∀ i j, X.Basis j → (Y i).Basis j → k, X.coeff = ∑ i ∈ s, applyLocal (L i) (Y i).coeff := by
+ classical
+ induction s using Finset.induction_on generalizing X with
+ | empty =>
+ simp only [Finset.sum_empty] at h ⊢
+ exact ⟨fun _ _ _ _ => 0, (zero_restricts_iff X).1 h⟩
+ | insert a s ha ih =>
+ obtain ⟨U, hU⟩ := ofTensor_surjective (∑ i ∈ s, ofTensor (Y i))
+ rw [Finset.sum_insert ha, ← hU, ← ofTensor_directSum] at h
+ obtain ⟨M, hM⟩ := (ofTensor_le_iff _ _).1 h
+ let left := fun j c b => M j c (Sum.inl b)
+ let right := fun j c b => M j c (Sum.inr b)
+ let R : Tensor.{u,v,0} k J := .mk X.Basis X.finiteBasis (applyLocal right U.coeff)
+ have hR : ofTensor R ≤ ∑ i ∈ s, ofTensor (Y i) := hU ▸ ⟨right, rfl⟩
+ obtain ⟨N, hN⟩ := ih R hR
+ let L := Function.update N a left
+ refine ⟨L, ?_⟩
+ calc
+ X.coeff = applyLocal left (Y a).coeff + R.coeff :=
+ hM.symm.trans (applyLocal_directSum (Y a) U M)
+ _ = applyLocal (L a) (Y a).coeff + ∑ i ∈ s, applyLocal (L i) (Y i).coeff := by
+ rw [hN]
+ congr 1
+ · simp [L]
+ · exact Finset.sum_congr rfl fun i hi => by simp [L, ne_of_mem_of_not_mem hi ha]
+ _ = _ := by rw [Finset.sum_insert ha]
+
+/-- The direct-sum restriction in the fixed-motif comparison gives one
+ordinary summand for each supply tensor. -/
+theorem ordinary_sum_of_class_le {ι : Type*} [Fintype ι]
+ (X : Tensor.{u,v,0} k J) (Y : ι → Tensor.{u,v,0} k J)
+ (h : ofTensor X ≤ ∑ i, ofTensor (Y i)) :
+ ∃ L : ∀ i j, X.Basis j → (Y i).Basis j → k, X.coeff = ∑ i, applyLocal (L i) (Y i).coeff :=
+ ordinary_sum_of_class_le_finset Finset.univ X Y h
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifParameters.lean b/lean/OAI/Computability/VPVNP/MotifParameters.lean
new file mode 100644
index 0000000000..b1413e576b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifParameters.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.MotifBase
+import OAI.Computability.VPVNP.MotifIntegralWires
+import Mathlib.Algebra.MvPolynomial.CommRing
+import Mathlib.Algebra.MvPolynomial.Degrees
+
+/-!
+# Integral equations for the fixed motif maps
+
+For each point of the demand grid in Theorem 6.1, impose its base tensor
+identity in every output coordinate. Distinct entries of the selected local
+maps are separate indeterminates. The equations can thus be specialized in
+any commutative ring, using the same integer tensors and the same bases.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifParameters
+
+open WireTensor MvPolynomial
+
+universe v w x y
+
+/-- Integral arrays and the selectors indexing their local images. -/
+structure Data (J : Type v) (Z : Type w) where
+ /-- Finite type of admissible supply selections for a given demand grid point. -/
+ Selector : Z → Type x
+ finiteSelector : ∀ z, Fintype (Selector z)
+ /-- Integer tensor to be expanded at the chosen demand grid point. -/
+ demand : Z → Tensor.{0,v,y} ℤ J
+ /-- Integer supply tensor used by one selector in the local-map expansion of the demand
+ tensor. -/
+ supply : (z : Z) → Selector z → Tensor.{0,v,y} ℤ J
+
+attribute [instance] Data.finiteSelector
+
+namespace Data
+
+variable {J Z : Type*} (G : Data J Z)
+
+/-- Each grid point, selector, party, row and column specifies one variable. -/
+abbrev Entry := (z : Z) × (t : G.Selector z) × (j : J) ×
+ (G.demand z).Basis j × (G.supply z t).Basis j
+
+/-- One equation for every joint output coordinate at every grid point. -/
+abbrev Output := (z : Z) × ((j : J) → (G.demand z).Basis j)
+
+instance [Finite Z] [Finite J] : Finite G.Entry := by
+ unfold Entry
+ infer_instance
+
+instance [Finite Z] [Finite J] : Finite G.Output := by
+ unfold Output
+ infer_instance
+
+/-- The local matrices read from a single parameter assignment. -/
+def localMap {R : Type*} (κ : G.Entry → R) (z : Z) (t : G.Selector z) (j : J)
+ (a : (G.demand z).Basis j) (b : (G.supply z t).Basis j) : R := κ ⟨z, t, j, a, b⟩
+
+variable [Fintype J]
+
+/-- Difference of the two sides of a base identity at one output coordinate. -/
+noncomputable def equation (o : G.Output) : MvPolynomial G.Entry ℤ :=
+ C ((G.demand o.1).coeff o.2) - ∑ t,
+ applyLocal (G.localMap X o.1 t) (fun b ↦ C ((G.supply o.1 t).coeff b)) o.2
+
+/-- Simultaneous vanishing of the integral equations. -/
+def IsSolution {R : Type*} [CommRing R] (κ : G.Entry → R) : Prop :=
+ ∀ o : G.Output, eval₂Hom (Int.castRingHom R) κ (G.equation o) = 0
+
+/-- Evaluating a base equation contracts the actual local matrices over the
+ring of the assignment. -/
+theorem eval_equation {R : Type*} [CommRing R] (κ : G.Entry → R) (o : G.Output) :
+ eval₂Hom (Int.castRingHom R) κ (G.equation o) =
+ ((G.demand o.1).coeff o.2 : R) - ∑ t, applyLocal (G.localMap κ o.1 t)
+ (fun b ↦ ((G.supply o.1 t).coeff b : R)) o.2 := by
+ classical
+ simp only [equation, applyLocal, localMap, map_sub, map_sum, map_mul, map_prod,
+ eval₂Hom_X', eval₂Hom_C]
+ rfl
+
+/-- Specialization of all the equations is equivalent to all the ordinary sum
+identities, as equalities of arrays in the original demand bases. -/
+theorem solution_iff {R : Type*} [CommRing R] (κ : G.Entry → R) :
+ G.IsSolution κ ↔ ∀ z, (fun a ↦ ((G.demand z).coeff a : R)) =
+ ∑ t, applyLocal (G.localMap κ z t) (fun b ↦ ((G.supply z t).coeff b : R)) := by
+ constructor
+ · intro h z
+ funext a
+ simpa only [eval_equation, sub_eq_zero, Finset.sum_apply] using h ⟨z, a⟩
+ · intro h o
+ simpa only [eval_equation, sub_eq_zero, Finset.sum_apply] using congrFun (h o.1) o.2
+
+/-- Base identities at individual grid points give a single simultaneous
+solution by assigning their matrix entries to their own variables. -/
+theorem exists_solution {R : Type*} [CommRing R]
+ (h : ∀ z, ∃ L : ∀ (t : G.Selector z) (j : J), (G.demand z).Basis j →
+ (G.supply z t).Basis j → R,
+ (fun a ↦ ((G.demand z).coeff a : R)) =
+ ∑ t, applyLocal (L t) (fun b ↦ ((G.supply z t).coeff b : R))) :
+ ∃ κ : G.Entry → R, G.IsSolution κ := by
+ choose L hL using h
+ let κ : G.Entry → R := fun ⟨z, t, j, a, b⟩ ↦ L z t j a b
+ exact ⟨κ, (G.solution_iff κ).2 hL⟩
+
+end Data
+
+section WireBases
+
+variable {J Z W : Type*} {D S : Type} [Fintype D] [Fintype S] [Fintype W]
+variable (a b : D → J) (c d : S → J) (z : Z → D → ℕ) (w : W → S → ℕ) (K h : ℕ)
+
+/-- The fixed integral tensors for the selectors in the spectral comparison. -/
+noncomputable def wireData : Data J Z where
+ Selector _ := Fin K × (Fin h → W)
+ finiteSelector _ := inferInstance
+ demand i := wireNetwork a b (fun e ↦ Fin (2 ^ (h * z i e)))
+ supply _ σ := wireNetwork c d (fun e ↦ Fin (2 ^ MotifBase.payload w σ.2 e))
+
+variable [Fintype J]
+
+/-- Specialization recovers the binary wire identities over the assignment's
+ring. All their matrix indices are taken in the original wire bases. -/
+theorem wire_solution_iff {R : Type*} [CommRing R]
+ (κ : (wireData a b c d z w K h).Entry → R) :
+ (wireData a b c d z w K h).IsSolution κ ↔ ∀ i,
+ (wireNetwork (k := R) a b (fun e ↦ Fin (2 ^ (h * z i e)))).coeff =
+ ∑ σ : Fin K × (Fin h → W), applyLocal
+ (B := ((wireData a b c d z w K h).supply i σ).Basis)
+ ((wireData a b c d z w K h).localMap κ i σ)
+ (wireNetwork (k := R) c d (fun e ↦ Fin (2 ^ MotifBase.payload w σ.2 e))).coeff := by
+ rw [Data.solution_iff]
+ apply forall_congr' fun i ↦ ?_
+ have hd := intCast_wireNetwork_coeff_fun R a b (fun e ↦ Fin (2 ^ (h * z i e)))
+ have hs (σ : Fin K × (Fin h → W)) := intCast_wireNetwork_coeff_fun R c d
+ (fun e ↦ Fin (2 ^ MotifBase.payload w σ.2 e))
+ simp_rw [← hd, ← hs]
+ rfl
+
+/-- Spectral base identities over the chosen field supply all the parameters
+of a single integral equation system at once. -/
+theorem exists_wire_solution {k : Type*} [Field k]
+ (base : ∀ i, MotifBase.BaseIdentity k a b c d (z i) w K h) :
+ ∃ κ : (wireData a b c d z w K h).Entry → k, (wireData a b c d z w K h).IsSolution κ := by
+ choose L hL using base
+ let κ : (wireData a b c d z w K h).Entry → k := fun ⟨i, σ, j, r, s⟩ ↦ L i σ j r s
+ exact ⟨κ, (wire_solution_iff a b c d z w K h κ).2 hL⟩
+
+end WireBases
+
+/-- Counting repeated parameter indices gives the exponent vector of one
+matrix entry in the repeated local map. -/
+noncomputable def entryExponents {V : Type*} {u : ℕ} (i : Fin u → V) : V →₀ ℕ :=
+ ∑ r, Finsupp.single (i r) 1
+
+/-- A product of base entries, including repetitions, is one monomial with
+coefficient one. The empty product also satisfies this formula. -/
+theorem prod_entries_eq_monomial {V : Type*} {u : ℕ} (i : Fin u → V) :
+ (∏ r, X (i r) : MvPolynomial V ℤ) = monomial (entryExponents i) 1 :=
+ (monomial_sum_one Finset.univ (fun r ↦ Finsupp.single (i r) 1)).symm
+
+/-- One selected base entry per copy contributes at most one degree per copy. -/
+theorem prod_entries_degree_le {V : Type*} {u : ℕ} (i : Fin u → V) :
+ (∏ r, X (i r) : MvPolynomial V ℤ).totalDegree ≤ u := by
+ simpa using totalDegree_finsetProd Finset.univ (fun r ↦ (X (i r) : MvPolynomial V ℤ))
+
+end MotifParameters
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifPayload.lean b/lean/OAI/Computability/VPVNP/MotifPayload.lean
new file mode 100644
index 0000000000..33eba840ff
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifPayload.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.MotifLocalSelectors
+import Mathlib.Algebra.BigOperators.Fin
+
+/-!
+# Grouping repeated motif maps by the total edge payload
+
+Theorem 6.1 uses one outer term for each total supply-width vector. The
+wire on an edge contains a selector list and the concatenated fields for
+the selected base maps. The coordinate arithmetic below is mixed-radix
+binary concatenation in the order of the copies.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifSelector
+
+open WireTensor
+
+variable {J E S C₀ : Type*} {C : J → Type*}
+
+/-- A width-`b` wire coordinate, numbered by its binary word. -/
+abbrev Word (b : ℕ) := Fin (2 ^ b)
+
+/-- Mixed-radix decomposition into the fields for consecutive copies. -/
+def unpackFields {u : ℕ} (w : Fin u → ℕ) : Word (∑ i, w i) ≃ ∀ i, Word (w i) :=
+ (finCongr (Finset.prod_pow_eq_pow_sum Finset.univ w 2).symm).trans finPiFinEquiv.symm
+
+/-- The payload occupies the low bits, with the list of selectors above it. -/
+def wireFields (u bits v : ℕ) : Word (v + u * bits) ≃ (Fin u → Word bits) × Word v :=
+ (((finFunctionFinEquiv.prodCongr (Equiv.refl (Word v))).trans finProdFinEquiv).trans
+ (finCongr (show (2 ^ bits) ^ u * 2 ^ v = 2 ^ (v + u * bits) by
+ rw [pow_add, Nat.mul_comm u bits, pow_mul, Nat.mul_comm]))).symm
+
+/-- Each edge's accumulated payload width. -/
+def totalWidth (w : S → E → ℕ) {u : ℕ} (θ : Fin u → S) (e : E) : ℕ := ∑ i, w (θ i) e
+
+/-- The complete list of table lookups for a single party. Each copy selects
+one base map and supplies its output and input coordinates. -/
+abbrev EntryIndices (G : Supply J E) (C : J → Type*) (w : S → E → ℕ) (u : ℕ) (j : J) :=
+ (i : Fin u) → Σ s : S, C j × Half G (fun e => Word (w s e)) j
+
+/-- Split the payload only if its total width agrees on every supply edge. -/
+noncomputable def payloadIndices (G : Supply J E) (w : S → E → ℕ) {u : ℕ} (v : E → ℕ)
+ (θ : Fin u → S) (j : J) (c : Fin u → C j) (x : Half G (fun e => Word (v e)) j) :
+ Option (EntryIndices G C w u j) := by
+ classical
+ exact if hv : v = totalWidth w θ then some (fun i =>
+ ⟨θ i, c i, mapHalf G (fun e y =>
+ unpackFields (fun l => w (θ l) e) (Fin.cast (congrArg (2 ^ ·) (congrFun hv e)) y) i) x⟩)
+ else none
+
+/-- Encode the selectors for all copies using the same fixed code table. -/
+def sequenceCode {T : Type*} (code : S ↪ T) (u : ℕ) : (Fin u → S) ↪ (Fin u → T) where
+ toFun θ := fun i => code (θ i)
+ inj' _ _ h := funext fun i => code.injective (congrFun h i)
+
+/-- Invalid tags reject the entry. Membership in the image can be checked
+copy by copy against the fixed finite table. -/
+noncomputable def tagIndices (G : Supply J E) (w : S → E → ℕ) {u bits : ℕ}
+ (code : S ↪ Word bits) (v : E → ℕ) (tags : Fin u → Word bits) (j : J)
+ (c : Fin u → C j) (x : Half G (fun e => Word (v e)) j) :
+ Option (EntryIndices G C w u j) := by
+ classical
+ exact if ht : tags ∈ Set.range (sequenceCode code u) then
+ payloadIndices G w v ht.choose j c x else none
+
+/-- The scalar-independent evaluator description at a party, including all
+checks on the selector copies, their validity and the supplied widths. -/
+noncomputable def groupedIndices (G : Supply J E) (w : S → E → ℕ) {u bits : ℕ}
+ (code : S ↪ Word bits) (v : E → ℕ) (j : J) (c : Fin u → C j)
+ (x : Half G (fun e => Word (v e + u * bits)) j) : Option (EntryIndices G C w u j) := by
+ classical
+ let fields := mapHalf G (fun e => wireFields u bits (v e)) x
+ exact if HalfAgrees G j fields then
+ tagIndices G w code v (readAnchor G j fields).1 j c (mapHalf G (fun _ => Prod.snd) fields)
+ else none
+
+/-- Evaluate a successful list of base entries multiplicatively. Failed checks
+produce the zero scalar in any commutative semiring. -/
+def evalIndices {R : Type*} [CommMonoidWithZero R] {G : Supply J E} {w : S → E → ℕ}
+ (L : ∀ s j, C j → Half G (fun e => Word (w s e)) j → R) (j : J) {u : ℕ}
+ (x : Option (EntryIndices G C w u j)) : R :=
+ x.elim 0 fun t => ∏ i, L (t i).1 j (t i).2.1 (t i).2.2
+
+/-- The map in one term of the grouped motif identity. -/
+noncomputable def groupedMap {R : Type*} [CommMonoidWithZero R] (G : Supply J E)
+ (w : S → E → ℕ) (L : ∀ s j, C j → Half G (fun e => Word (w s e)) j → R)
+ {u bits : ℕ} (code : S ↪ Word bits) (v : E → ℕ) (j : J) (c : Fin u → C j)
+ (x : Half G (fun e => Word (v e + u * bits)) j) : R :=
+ evalIndices L j (groupedIndices G w code v j c x)
+
+/-- The common code-table membership test is equivalent to testing each
+selector separately. Decoding requires no search over selector sequences. -/
+theorem mem_sequenceCode_range {T : Type*} {u : ℕ} (code : S ↪ T) (t : Fin u → T) :
+ t ∈ Set.range (sequenceCode code u) ↔ ∀ i, t i ∈ Set.range code := by
+ constructor
+ · rintro ⟨θ, rfl⟩ i
+ exact ⟨θ i, rfl⟩
+ · intro h
+ exact ⟨fun i => (h i).choose, funext fun i => (h i).choose_spec⟩
+
+end MotifSelector
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifPayloadIdentity.lean b/lean/OAI/Computability/VPVNP/MotifPayloadIdentity.lean
new file mode 100644
index 0000000000..1cb9ba8e4c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifPayloadIdentity.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.MotifPayload
+
+/-!
+# Contraction of a single grouped payload
+
+For a fixed global selector sequence, a matching payload width allows all
+wire values to be split into independent fields for the repeated copies.
+Summing over those fields factors into the product of the base contractions.
+A mismatched width makes the local entry vanish at every party.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifSelector
+
+open WireTensor
+
+variable {J E S R : Type*} {C : J → Type*}
+
+/-- Regroup the edgewise fields into one complete wire assignment per copy. -/
+private def assignmentEquiv (w : S → E → ℕ) {u : ℕ} (θ : Fin u → S) :
+ (∀ e, Word (totalWidth w θ e)) ≃ (∀ i, (e : E) → Word (w (θ i) e)) where
+ toFun x i e := unpackFields (fun j ↦ w (θ j) e) (x e) i
+ invFun y e := (unpackFields (fun j ↦ w (θ j) e)).symm (fun i ↦ y i e)
+ left_inv x := funext fun e ↦ (unpackFields (fun j ↦ w (θ j) e)).symm_apply_apply (x e)
+ right_inv y := funext fun i ↦ funext fun e ↦
+ congrFun ((unpackFields (fun j ↦ w (θ j) e)).apply_symm_apply (fun j ↦ y j e)) i
+
+open scoped Classical in
+/-- A fixed global sequence contributes precisely the product of its local
+base contractions to the one outer term indexed by its accumulated widths. -/
+theorem sum_payload_indices [Fintype J] [Nonempty J] [Fintype E] [CommSemiring R]
+ (G : Supply J E) (w : S → E → ℕ)
+ (L : ∀ s j, C j → Half G (fun e ↦ Word (w s e)) j → R) {u : ℕ}
+ (v : E → ℕ) (θ : Fin u → S) (c : ∀ j, Fin u → C j) :
+ (∑ x : ∀ e, Word (v e), ∏ j, evalIndices L j
+ (payloadIndices G w v θ j (c j) (edgeAssignment G.src G.dst x j))) =
+ if v = totalWidth w θ then
+ ∏ i, ∑ y : ∀ e, Word (w (θ i) e),
+ ∏ j, L (θ i) j (c j i) (edgeAssignment G.src G.dst y j)
+ else 0 := by
+ classical
+ by_cases hv : v = totalWidth w θ
+ · subst v
+ let f (i : Fin u) (y : ∀ e, Word (w (θ i) e)) (j : J) :=
+ L (θ i) j (c j i) (edgeAssignment G.src G.dst y j)
+ let e := assignmentEquiv w θ
+ have entry (x : ∀ d, Word (totalWidth w θ d)) (j : J) :
+ evalIndices L j (payloadIndices G w (totalWidth w θ) θ j (c j)
+ (edgeAssignment G.src G.dst x j)) = ∏ i, f i (e x i) j := by
+ simp [payloadIndices, evalIndices, f, e, assignmentEquiv, mapHalf_edgeAssignment]
+ rfl
+ simp only [ite_true, eq_self]
+ simp_rw [entry]
+ change (∑ x, ∏ j, ∏ i, f i (e x i) j) = ∏ i, ∑ y, ∏ j, f i y j
+ rw [Fintype.prod_sum]
+ calc
+ _ = ∑ x, ∏ i, ∏ j, f i (e x i) j := Finset.sum_congr rfl fun x _ ↦ Finset.prod_comm
+ _ = _ := e.sum_comp (fun y ↦ ∏ i, ∏ j, f i (y i) j)
+ · simp [payloadIndices, hv, evalIndices]
+
+end MotifSelector
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifPowerExpansion.lean b/lean/OAI/Computability/VPVNP/MotifPowerExpansion.lean
new file mode 100644
index 0000000000..aa058d6045
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifPowerExpansion.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.MotifPayloadIdentity
+
+/-!
+# The repeated motif identity as an ordinary sum over total widths
+
+After copying a fixed base identity, choices of its summands form selector
+lists. The supply edge payloads are grouped by their total width vector.
+The selector and validity checks in the local maps count each admissible
+list exactly once, as required by Theorem 6.1.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifSelector
+
+open WireTensor
+
+variable {J E S R : Type*} [Fintype J] [Nonempty J] [Fintype E] [Fintype S] [CommSemiring R]
+variable {C : J → Type*} (G : Supply J E) (w : S → E → ℕ)
+variable (L : ∀ s j, C j → Half G (fun e => Word (w s e)) j → R)
+variable {u bits : ℕ} (code : S ↪ Word bits)
+
+open scoped Classical in
+/-- The contribution of one selected base map after contracting its supply wires. -/
+noncomputable def baseTerm (s : S) (d : ∀ j, C j) : R :=
+ ∑ y : ∀ e, Word (w s e), ∏ j, L s j (d j) (edgeAssignment G.src G.dst y j)
+
+open scoped Classical in
+private theorem sum_decoded_tags (v : E → ℕ) (c : ∀ j, Fin u → C j) :
+ (∑ t : Fin u → Word bits, ∑ y : ∀ e, Word (v e),
+ ∏ j, evalIndices L j (tagIndices G w code v t j (c j) (edgeAssignment G.src G.dst y j))) =
+ ∑ θ : Fin u → S, ∑ y : ∀ e, Word (v e),
+ ∏ j, evalIndices L j (payloadIndices G w v θ j (c j) (edgeAssignment G.src G.dst y j)) := by
+ classical
+ let e := sequenceCode code u
+ let F (θ : Fin u → S) := ∑ y : ∀ i, Word (v i),
+ ∏ j, evalIndices L j (payloadIndices G w v θ j (c j) (edgeAssignment G.src G.dst y j))
+ let T (t : Fin u → Word bits) := ∑ y : ∀ i, Word (v i),
+ ∏ j, evalIndices L j (tagIndices G w code v t j (c j) (edgeAssignment G.src G.dst y j))
+ have valid (θ : Fin u → S) : T (e θ) = F θ := by
+ simp [T, F, tagIndices, e]
+ have invalid (t : Fin u → Word bits) (h : t ∉ Set.range e) : T t = 0 := by
+ change ¬ ∃ θ, sequenceCode code u θ = t at h
+ simp [T, tagIndices, h, evalIndices]
+ change ∑ t, T t = ∑ θ, F θ
+ symm
+ apply Finset.sum_bij_ne_zero (fun θ _ _ => e θ) (fun _ _ _ => Finset.mem_univ _)
+ (fun _ _ _ _ _ _ h => e.injective h) _ (fun θ _ _ => (valid θ).symm)
+ intro t _ ht
+ obtain ⟨θ, rfl⟩ : t ∈ Set.range e := by
+ by_contra h
+ exact ht (invalid t h)
+ exact ⟨θ, Finset.mem_univ _, (valid θ) ▸ ht, rfl⟩
+
+open scoped Classical in
+private theorem sum_grouped_fields (v : E → ℕ) (c : ∀ j, Fin u → C j) :
+ (∑ x : ∀ e, Word (v e + u * bits),
+ ∏ j, groupedMap G w L code v j (c j) (edgeAssignment G.src G.dst x j)) =
+ ∑ θ : Fin u → S, ∑ y : ∀ e, Word (v e),
+ ∏ j, evalIndices L j (payloadIndices G w v θ j (c j) (edgeAssignment G.src G.dst y j)) := by
+ classical
+ let F (t : Fin u → Word bits) (j : J) (d : Fin u → C j) (y : Half G (fun e => Word (v e)) j) :=
+ evalIndices L j (tagIndices G w code v t j d y)
+ let eqv := Equiv.piCongrRight (fun e => wireFields u bits (v e))
+ have eqterm (z : ∀ e, (Fin u → Word bits) × Word (v e)) (j : J) :
+ groupedMap G w L code v j (c j) (edgeAssignment G.src G.dst (eqv.symm z) j) =
+ selectedMap G F j (c j) (edgeAssignment G.src G.dst z j) := by
+ have he : (fun e => wireFields u bits (v e) (eqv.symm z e)) = z := eqv.apply_symm_apply z
+ simp only [groupedMap, groupedIndices, mapHalf_edgeAssignment, he, selectedMap]
+ split <;> rfl
+ rw [← eqv.symm.sum_comp,
+ Fintype.sum_congr _ _ (fun z => Finset.prod_congr rfl (fun j _ => eqterm z j))]
+ have h := congrFun (applyLocal_selectedMap G F) c
+ rw [Finset.sum_apply] at h
+ erw [applyLocal_wireNetwork G.src G.dst _ (selectedMap G F) c] at h
+ have he (t : Fin u → Word bits) := applyLocal_wireNetwork G.src G.dst _ (F t) c
+ simp_rw [he] at h
+ exact h.trans (sum_decoded_tags G w L code v c)
+
+open scoped Classical in
+/-- Each compressed term counts precisely the lists with its total width vector. -/
+theorem groupedMap_contraction (v : E → ℕ) (c : ∀ j, Fin u → C j) :
+ applyLocal (B := (wireNetwork (k := R) G.src G.dst (fun e => Word (v e + u*bits))).Basis)
+ (groupedMap G w L code v) (wireNetwork G.src G.dst (fun e => Word (v e + u*bits))).coeff c =
+ ∑ θ : Fin u → S, if v = totalWidth w θ then
+ ∏ i, baseTerm G w L (θ i) (fun j => c j i) else 0 := by
+ classical
+ erw [applyLocal_wireNetwork G.src G.dst _ (groupedMap G w L code v) c]
+ rw [sum_grouped_fields G w L code v c]
+ exact Finset.sum_congr rfl fun θ _ => sum_payload_indices G w L v θ c
+
+open scoped Classical in
+/-- The repeated ordinary sum, grouped by admitted total payload widths.
+Every successful selector list has exactly one outer index. -/
+theorem power_expansion (admitted : Finset (E → ℕ))
+ (cover : ∀ θ : Fin u → S, totalWidth w θ ∈ admitted)
+ (c : ∀ j, Fin u → C j) :
+ (∏ i, ∑ s, baseTerm G w L s (fun j => c j i)) =
+ ∑ v ∈ admitted, applyLocal
+ (B := (wireNetwork (k := R) G.src G.dst (fun e => Word (v e + u*bits))).Basis)
+ (groupedMap G w L code v)
+ (wireNetwork G.src G.dst (fun e => Word (v e + u*bits))).coeff c := by
+ classical
+ simp_rw [groupedMap_contraction G w L code _ c]
+ rw [Fintype.prod_sum, Finset.sum_comm]
+ exact Finset.sum_congr rfl fun θ _ => by simp [cover θ]
+
+end MotifSelector
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifSelector.lean b/lean/OAI/Computability/VPVNP/MotifSelector.lean
new file mode 100644
index 0000000000..e52162c74f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifSelector.lean
@@ -0,0 +1,94 @@
+import Mathlib.Algebra.BigOperators.Group.Finset.Sigma
+import Mathlib.Algebra.BigOperators.Ring.Finset
+import Mathlib.Logic.Relation
+
+/-!
+# Synchronizing selectors on a wire motif
+
+In Theorem 6.1 of *VP and VNP differ over every field* the same finite
+selector list is carried on every supply edge. Each party checks only
+its incident edges. Connectivity makes the surviving selector lists
+global, with each list contributing once.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifSelector
+
+open Relation
+
+variable {J E S R : Type*}
+
+/-- Endpoint data and connectedness of the supply wires, with an incident
+edge chosen at each party for reading its selector. -/
+structure Supply (J E : Type*) where
+ /-- Party at the source of each directed supply edge. -/
+ src : E → J
+ /-- Party at the destination of each directed supply edge. -/
+ dst : E → J
+ /-- Incident edge at each party whose selector is compared with the selectors on all other
+ incident edges. -/
+ anchor : J → E
+ anchor_incident : ∀ j, src (anchor j) = j ∨ dst (anchor j) = j
+ connected : ∀ j k, ReflTransGen
+ (fun u v => ∃ e, (src e = u ∧ dst e = v) ∨ (src e = v ∧ dst e = u)) j k
+
+/-- Each selector incident to the party agrees with the selector at its anchor edge. -/
+def Agrees (G : Supply J E) (x : E → S) (j : J) : Prop :=
+ ∀ e, (G.src e = j ∨ G.dst e = j) → x e = x (G.anchor j)
+
+/-- All local consistency checks succeed exactly on constant assignments. -/
+theorem agrees_iff_constant [Nonempty J] (G : Supply J E) (x : E → S) :
+ (∀ j, Agrees G x j) ↔ ∃ s, x = fun _ => s := by
+ constructor
+ · intro h
+ let j₀ := Classical.choice ‹Nonempty J›
+ have hloc (j k : J) : x (G.anchor j) = x (G.anchor k) := by
+ induction G.connected j k with
+ | refl => rfl
+ | @tail j' k _ step ih =>
+ obtain ⟨e, ⟨hs, hd⟩ | ⟨hs, hd⟩⟩ := step
+ · exact ih.trans ((h j' e (Or.inl hs)).symm.trans (h k e (Or.inr hd)))
+ · exact ih.trans ((h j' e (Or.inr hd)).symm.trans (h k e (Or.inl hs)))
+ exact ⟨x (G.anchor j₀), funext fun e => (h (G.src e) e (Or.inl rfl)).trans (hloc _ _)⟩
+ · rintro ⟨s, rfl⟩ j e _
+ rfl
+
+open scoped Classical in
+/-- Summing over all edge selectors with the local checks gives a single
+sum over global selectors. The factors may vanish or cancel in the ring. -/
+theorem sum_local_checks [Nonempty J] [Fintype J] [Fintype E] [Fintype S] [CommSemiring R]
+ (G : Supply J E) (L : J → S → R) :
+ (∑ x : E → S, ∏ j, if Agrees G x j then L j (x (G.anchor j)) else 0) =
+ ∑ s : S, ∏ j, L j s := by
+ classical
+ let e₀ := G.anchor (Classical.choice ‹Nonempty J›)
+ have hconst {s t : S} (h : (fun _ : E => s) = fun _ => t) : s = t := congrFun h e₀
+ have hf (x : E → S) :
+ (∏ j, if Agrees G x j then L j (x (G.anchor j)) else 0) =
+ ∑ s : S, if x = (fun _ => s) then ∏ j, L j s else 0 := by
+ by_cases h : ∀ j, Agrees G x j
+ · obtain ⟨t, rfl⟩ := (agrees_iff_constant G x).mp h
+ rw [Finset.sum_eq_single t]
+ · simp [h]
+ · intro s _ hs
+ exact ite_eq_right (fun he => hs (hconst he).symm)
+ · simp
+ · obtain ⟨j, hj⟩ := not_forall.mp h
+ have hleft : (∏ j, if Agrees G x j then L j (x (G.anchor j)) else 0) = 0 :=
+ Finset.prod_eq_zero (Finset.mem_univ j) (ite_eq_right hj)
+ rw [hleft]
+ apply Eq.symm (Finset.sum_eq_zero _)
+ intro s _
+ exact ite_eq_right (fun he => h ((agrees_iff_constant G x).mpr ⟨s, he⟩))
+ simp_rw [hf]
+ rw [Finset.sum_comm]
+ simp
+
+end MotifSelector
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifSupplyEnergy.lean b/lean/OAI/Computability/VPVNP/MotifSupplyEnergy.lean
new file mode 100644
index 0000000000..e9e3059ebf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifSupplyEnergy.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.MotifGrid
+import OAI.Computability.VPVNP.MotifSelector
+import OAI.Computability.VPVNP.WireSpectrum
+
+/-!
+# Positive spectral energy of a connected supply motif
+
+In Theorem 6.1 the binary supply network restricts to the two-entry diagonal:
+at each party the local map selects the same output color on every incident
+wire. The selected coefficient is one precisely when the coloring is
+constant along every edge. Connectivity therefore forces the sum of the
+supply wire distances to be at least one at each spectral point.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifSelector.Supply
+
+/-- Edgewise agreement of colors propagates along paths of the supply graph. -/
+theorem color_eq_of_connected {J E I : Type*} (G : MotifSelector.Supply J E) (color : J → I)
+ (h : ∀ e, color (G.src e) = color (G.dst e)) (j l : J) : color j = color l := by
+ induction G.connected j l with
+ | refl => rfl
+ | tail _ step ih =>
+ rcases step with ⟨e, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩⟩
+ · exact ih.trans (h e)
+ · exact ih.trans (h e).symm
+
+end MotifSelector.Supply
+
+namespace WireTensor
+
+variable {k J : Type*} [Fintype J] [Nonempty J]
+
+/-- A connected network of equality wires realizes the diagonal by selecting
+the output color on every incident half-wire. -/
+theorem connectedNetwork_restricts_diagonal [CommSemiring k] {E I : Type*}
+ [Fintype E] [Fintype I] (a b : E → J)
+ (hconn : ∀ x : J → I, (∀ e, x (a e) = x (b e)) → ∀ i j, x i = x j) :
+ Restricts (wireNetwork (k := k) a b (fun _ ↦ I)) (diagonal I) := by
+ classical
+ let W := wireNetwork (k := k) a b (fun _ ↦ I)
+ let select (j : J) (i : I) : W.Basis j := ⟨fun _ _ ↦ i, fun _ _ ↦ i⟩
+ refine ⟨_, (applyLocal_pullback select W.coeff).trans ?_⟩
+ funext x
+ simp only [W, select, wireNetwork, diagonal, Fintype.prod_boole]
+ congr 1
+ apply propext
+ constructor
+ · intro h
+ let j : J := Classical.ofNonempty
+ exact ⟨x j, fun i ↦ hconn x h i j⟩
+ · rintro ⟨c, hc⟩ e
+ exact (hc (a e)).trans (hc (b e)).symm
+
+namespace SpectralPoint
+
+variable [Field k] {E : Type} [Fintype E] (F : SpectralPoint k J) (a b : E → J)
+variable (hconn : ∀ x : J → Fin 2, (∀ e, x (a e) = x (b e)) → ∀ i j, x i = x j)
+include hconn
+
+/-- The binary supply network has value at least two, giving a logarithmic
+lower bound on the sum of the edge distances. -/
+theorem one_le_sum_connected_wireDistance : 1 ≤ ∑ e, F.wireDistance (a e) (b e) := by
+ have h := F.monotone (connectedNetwork_restricts_diagonal (k := k) a b hconn)
+ rw [F.value_diagonal_fin] at h
+ have hreal : (2 : ℝ) ≤ F.value (wireNetwork a b (fun _ ↦ Fin 2)) := by exact_mod_cast h
+ have hlog := Real.log_le_log (by norm_num : (0 : ℝ) < 2) hreal
+ have hsum := F.log2_value_binary_wireNetwork a b (fun _ ↦ 1)
+ simpa only [pow_one, Nat.cast_one, one_mul] using
+ ((one_le_div (Real.log_pos (by norm_num : (1 : ℝ) < 2))).2 hlog).trans_eq hsum
+
+/-- Some supply edge has positive spectral distance. -/
+theorem exists_pos_connected_wireDistance : ∃ e, 0 < F.wireDistance (a e) (b e) := by
+ by_contra! h
+ have hnonpos := Finset.sum_nonpos (s := Finset.univ) (fun e _ ↦ h e)
+ linarith [F.one_le_sum_connected_wireDistance a b hconn]
+
+/-- The weighted supply energy in Theorem 6.1 is positive for every
+spectral point when all edge masses are positive. -/
+theorem connected_distanceEnergy_pos (q : E → ℝ) (hq : ∀ e, 0 < q e) :
+ 0 < MotifGrid.distanceEnergy q (fun e ↦ F.wireDistance (a e) (b e)) := by
+ obtain ⟨e, he⟩ := F.exists_pos_connected_wireDistance a b hconn
+ apply (mul_pos (hq e) (sq_pos_of_pos he)).trans_le
+ exact Finset.single_le_sum (fun i _ ↦ mul_nonneg (hq i).le (sq_nonneg (F.wireDistance (a i) (b i))))
+ (Finset.mem_univ e)
+
+end SpectralPoint
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifWidths.lean b/lean/OAI/Computability/VPVNP/MotifWidths.lean
new file mode 100644
index 0000000000..2b6a88f80e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifWidths.lean
@@ -0,0 +1,247 @@
+import OAI.Computability.VPVNP.MotifGrid
+import Mathlib.Data.Nat.Log
+
+/-!
+# Selector and payload widths in a fixed motif
+
+Theorem 6.1 of *VP and VNP differ over every field* first fixes a denominator
+multiple and then a power of the base identity. This order matters because the
+number of direct-sum copies can depend on the chosen multiple. Every subsequent
+input uses repetitions of that single base block. Its selector overhead can
+be made arbitrarily small, and its padding costs a constant in squared width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace MotifWidths
+
+open MotifGrid
+
+/-- The least number of bits for a base selector, indexing a direct-sum
+copy and the `h` independent choices of supply grid point. -/
+def selectorBits (K n h : ℕ) : ℕ := Nat.clog 2 (K * n ^ h)
+
+theorem selector_capacity (K n h : ℕ) : K * n ^ h ≤ 2 ^ selectorBits K n h :=
+ Nat.le_pow_clog (by decide) _
+
+private theorem selectorBits_le (K n h : ℕ) :
+ selectorBits K n h ≤ Nat.clog 2 K + h * Nat.clog 2 n := by
+ apply (Nat.clog_le_iff_le_pow (by decide : 1 < 2)).mpr
+ rw [pow_add, Nat.mul_comm h, pow_mul]
+ exact Nat.mul_le_mul (Nat.le_pow_clog (by decide) _)
+ (Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) _)
+
+/-- Arbitrarily small selector fraction, with an arbitrary dependence of the
+number `K t` of direct-sum copies on the denominator multiple `t`. -/
+theorem exists_selector_block (den n : ℕ) (hd : 0 < den) (K : ℕ → ℕ) {δ : ℝ} (hδ : 0 < δ) :
+ ∃ t h : ℕ, 0 < t ∧ 0 < h ∧
+ (selectorBits (K t) n h : ℝ) / (h * (t * den) : ℝ) < δ := by
+ obtain ⟨t, ht⟩ := exists_nat_gt (2 * (Nat.clog 2 n : ℝ) / δ)
+ have ht0 : 0 < t := Nat.cast_pos.mp ((by positivity : 0 ≤ 2 * (Nat.clog 2 n : ℝ) / δ).trans_lt ht)
+ obtain ⟨h, hh⟩ := exists_nat_gt (2 * (Nat.clog 2 (K t) : ℝ) / δ)
+ have hh0 : 0 < h :=
+ Nat.cast_pos.mp ((by positivity : 0 ≤ 2 * (Nat.clog 2 (K t) : ℝ) / δ).trans_lt hh)
+ let B : ℝ := t * den
+ have htB : (t : ℝ) ≤ B := by
+ change (t : ℝ) ≤ t * den
+ exact le_mul_of_one_le_right (Nat.cast_nonneg _) (by exact_mod_cast hd)
+ have hB1 : 1 ≤ B := (show (1 : ℝ) ≤ t by exact_mod_cast ht0).trans htB
+ have hn : 2 * (Nat.clog 2 n : ℝ) < B * δ :=
+ ((div_lt_iff₀ hδ).mp ht).trans_le (mul_le_mul_of_nonneg_right htB hδ.le)
+ have hK := (div_lt_iff₀ hδ).mp hh
+ have hs : (selectorBits (K t) n h : ℝ) ≤ (Nat.clog 2 (K t) : ℝ) + h * (Nat.clog 2 n : ℝ) :=
+ by exact_mod_cast selectorBits_le (K t) n h
+ have hhB : 0 < (h : ℝ) * B := mul_pos (Nat.cast_pos.mpr hh0) (zero_lt_one.trans_le hB1)
+ refine ⟨t, h, ht0, hh0, (div_lt_iff₀ hhB).mpr ?_⟩
+ have hK' := hK.trans_le (le_mul_of_one_le_right (mul_nonneg (Nat.cast_nonneg h) hδ.le) hB1)
+ nlinarith only [hs, hK', mul_lt_mul_of_pos_left hn (Nat.cast_pos.mpr hh0)]
+
+/-- A single strictly positive tolerance leaves room for the selector bits
+inside the prescribed squared energy coefficient. -/
+theorem exists_selector_tolerance (R Q H' : ℝ) (hR : 0 ≤ R) (hQ : 0 ≤ Q)
+ (hR' : R < √H') : ∃ δ > 0, ∀ x : ℝ, 0 ≤ x → x < δ → (R + x * Q) ^ 2 < H' := by
+ have hq1 : 0 < Q + 1 := by linarith only [hQ]
+ refine ⟨(√H' - R) / (Q + 1), div_pos (sub_pos.mpr hR') hq1, fun x hx hxt => ?_⟩
+ have hlt := (lt_div_iff₀ hq1).mp hxt
+ have hsq := (sq_lt_sq₀ (add_nonneg hR (mul_nonneg hx hQ)) (Real.sqrt_nonneg H')).mpr
+ (show R + x * Q < √H' by linarith only [hx, hlt])
+ rwa [Real.sq_sqrt (Real.sqrt_pos.mp (hR.trans_lt hR')).le] at hsq
+
+variable {I : Type*} [Fintype I]
+
+/-- Triangle inequality for the aggregate payload over any finite selector list. -/
+theorem widthNorm_sum_le {T : Type*} [Fintype T] (p : I → ℝ) (hp : ∀ i, 0 < p i)
+ (x : T → I → ℝ) :
+ widthNorm p (fun i => ∑ t, x t i) ≤ ∑ t, widthNorm p (x t) := by
+ let y := fun i => ∑ t, x t i
+ let d := fun i => y i / p i
+ have he : √(distanceEnergy p d) = widthNorm p y := by
+ unfold distanceEnergy widthNorm
+ congr 1
+ apply Finset.sum_congr rfl
+ intro i _
+ dsimp only [d]
+ field_simp [(hp i).ne']
+ have hy : wireValue y d = widthNorm p y ^ 2 := by
+ rw [norm_sq _ _ hp]
+ unfold wireValue
+ apply Finset.sum_congr rfl
+ intro i _
+ dsimp only [d]
+ ring
+ have hval : wireValue y d = ∑ t, wireValue (x t) d := by
+ unfold wireValue y
+ simp only [Finset.sum_mul]
+ rw [Finset.sum_comm]
+ have hn := Finset.sum_le_sum (s := Finset.univ) (fun t _ => wireValue_le p (x t) d hp)
+ rw [he, ← Finset.sum_mul, ← hval, hy, sq] at hn
+ rcases (Real.sqrt_nonneg (∑ i, y i ^ 2 / p i)).eq_or_lt with h0 | hpos
+ · change widthNorm p y ≤ _
+ rw [show widthNorm p y = 0 from h0.symm]
+ exact Finset.sum_nonneg fun _ _ => Real.sqrt_nonneg _
+ · exact le_of_mul_le_mul_right hn hpos
+
+/-- Number of repetitions of a block of width scale `L`. -/
+noncomputable def copies (t : ℝ) (L : ℕ) : ℕ := ⌈t / L⌉₊
+
+theorem copies_spec {t : ℝ} (ht : 0 ≤ t) {L : ℕ} (hL : 0 < L) :
+ t ≤ (copies t L : ℝ) * L ∧ (copies t L : ℝ) * L ≤ t + L := by
+ have hL' : (0 : ℝ) < L := Nat.cast_pos.mpr hL
+ constructor
+ · exact (div_le_iff₀ hL').mp (Nat.le_ceil _)
+ · have h := mul_le_mul_of_nonneg_right (Nat.ceil_lt_add_one (div_nonneg ht hL'.le)).le hL'.le
+ rwa [add_mul, div_mul_cancel₀ _ hL'.ne', one_mul] at h
+
+/-- The surplus demand bits can be fixed at both endpoints. -/
+theorem copies_dominate (p : I → ℝ) (b base : I → ℕ) {L : ℕ} (hL : 0 < L)
+ (z : I → ℝ) (hz : ∀ i, 0 ≤ z i)
+ (hcover : ∀ i, (b i : ℝ) ≤ widthNorm p (fun j => b j) * z i)
+ (hbase : ∀ i, (base i : ℝ) = L * z i) :
+ ∀ i, b i ≤ copies (widthNorm p (fun j => b j)) L * base i := by
+ intro i
+ have hn : 0 ≤ widthNorm p (fun j => b j) := Real.sqrt_nonneg _
+ have h := mul_le_mul_of_nonneg_right (copies_spec hn hL).1 (hz i)
+ exact_mod_cast (show (b i : ℝ) ≤ (copies (widthNorm p (fun j => b j)) L : ℝ) * base i by
+ rw [hbase, ← mul_assoc]; exact (hcover i).trans h)
+
+/-- Given any admitted total payload vector, add the selector bits on every
+supply edge. The linear term from rounding the number of blocks is absorbed
+by the strict margin in the quadratic coefficient. -/
+theorem padded_energy_le (q : I → ℝ) (hq : ∀ i, 0 < q i) {L s : ℕ} (hL : 0 < L)
+ {R H' : ℝ} (hR : 0 ≤ R)
+ (hgap : (R + s / (L : ℝ) * widthNorm q (fun _ => 1)) ^ 2 < H') :
+ ∃ C : ℝ, ∀ (t : ℝ) (v : I → ℕ), 0 ≤ t →
+ widthNorm q (fun i => v i) ≤ (copies t L : ℝ) * L * R →
+ widthNorm q (fun i => (v i + copies t L * s : ℕ)) ^ 2 ≤ H' * t ^ 2 + C := by
+ let A := R + s / (L : ℝ) * widthNorm q (fun _ => 1)
+ have hA : 0 ≤ A := add_nonneg hR (mul_nonneg (by positivity) (Real.sqrt_nonneg _))
+ have hg : 0 < H' - A ^ 2 := sub_pos.mpr hgap
+ refine ⟨H' * A ^ 2 * L ^ 2 / (H' - A ^ 2), fun t v ht hv => ?_⟩
+ let u := copies t L
+ let c := fun i => ((v i + u * s : ℕ) : ℝ)
+ have hnorm : widthNorm q c ≤
+ widthNorm q (fun i => v i) + (u * s : ℝ) * widthNorm q (fun _ => 1) :=
+ widthNorm_round_le q _ c hq (by positivity) (fun i => Nat.cast_nonneg _) (fun i => by simp [c])
+ have hpad : widthNorm q c ≤ (t + L) * A := by
+ calc
+ _ ≤ (u : ℝ) * L * R + (u * s : ℝ) * widthNorm q (fun _ => 1) :=
+ hnorm.trans (add_le_add hv le_rfl)
+ _ = ((u : ℝ) * L) * A := by unfold A; field_simp [Nat.cast_ne_zero.mpr hL.ne']
+ _ ≤ _ := mul_le_mul_of_nonneg_right (copies_spec ht hL).2 hA
+ have hpadded : 0 ≤ (t + L) * A := mul_nonneg (add_nonneg ht (Nat.cast_nonneg L)) hA
+ apply ((sq_le_sq₀ (Real.sqrt_nonneg _) hpadded).mpr hpad).trans
+ rw [← sub_le_iff_le_add']
+ apply (le_div_iff₀ hg).mpr
+ nlinarith only [sq_nonneg ((H' - A ^ 2) * t - A ^ 2 * L)]
+
+variable {D S : Type*} [Fintype D] [Fintype S]
+variable {p : D → ℝ} {q : S → ℝ} {H R : ℝ}
+
+/-- Choosing the upper demand grid point makes the repeated integer base
+widths large enough at every edge, including when all demand widths vanish. -/
+theorem exists_padded_grid (G : StrictGrids p q H R) (hp : ∀ i, 0 < p i)
+ (t h : ℕ) (ht : 0 < t) (hh : 0 < h) (b : D → ℕ) :
+ ∃ z : G.demands, ∀ i,
+ b i ≤ copies (widthNorm p (fun j => b j)) (h * (t * G.denominator)) *
+ (h * G.demandWidths t z i) := by
+ let N := widthNorm p (fun j => (b j : ℝ))
+ have hn : 0 ≤ N := Real.sqrt_nonneg _
+ let x := fun i => N⁻¹ * (b i : ℝ)
+ have hx i : 0 ≤ x i := mul_nonneg (inv_nonneg.mpr hn) (Nat.cast_nonneg _)
+ have hnorm : widthNorm p x ≤ 1 := by
+ rw [show x = (fun i => N⁻¹ * (b i : ℝ)) from rfl, widthNorm_scale _ _ (inv_nonneg.mpr hn)]
+ change N⁻¹ * N ≤ 1
+ rcases eq_or_ne N 0 with he | he <;> simp [he]
+ obtain ⟨z, hz, hcover⟩ := G.cover x hx hnorm
+ refine ⟨⟨z, hz⟩, copies_dominate p b _ (Nat.mul_pos hh (Nat.mul_pos ht G.denominator_pos))
+ (realWidths z) (fun i => (hx i).trans (hcover i).1) ?_ ?_⟩
+ · intro i
+ rcases hn.eq_or_lt with hn0 | hn0
+ · have h := coordinate_le p (fun j => (b j : ℝ)) hp i
+ change (b i : ℝ) ≤ √(p i) * N at h
+ change (b i : ℝ) ≤ N * _
+ simpa [← hn0] using h
+ · have h := mul_le_mul_of_nonneg_left (hcover i).1 hn
+ dsimp only [x] at h
+ rwa [← mul_assoc, mul_inv_cancel₀ hn0.ne', one_mul] at h
+ · intro i
+ simp [realWidths, mul_assoc]
+
+/-- Adding the `h` supply grid points for a base selector costs at most `hBR`. -/
+theorem base_payload_bound (G : StrictGrids p q H R) (hq : ∀ i, 0 < q i)
+ (t h : ℕ) (w : Fin h → G.supplies) :
+ widthNorm q (fun i => ((∑ j, G.supplyWidths t (w j) i : ℕ) : ℝ)) ≤
+ (h * (t * G.denominator) : ℕ) * R := by
+ push_cast
+ calc
+ _ ≤ ∑ j, widthNorm q (fun i => (G.supplyWidths t (w j) i : ℝ)) := widthNorm_sum_le _ hq _
+ _ ≤ ∑ _j : Fin h, ((t * G.denominator : ℕ) : ℝ) * R :=
+ Finset.sum_le_sum fun j _ => G.supplyWidths_norm_le t (w j)
+ _ = _ := by simp [mul_assoc]
+
+/-- The number of base copies and every coordinate of every admitted outer
+payload are bounded linearly in the largest input width. -/
+theorem outer_indices_linear (p : D → ℝ) (q : S → ℝ) (hp : ∀ i, 0 < p i)
+ (hq : ∀ i, 0 < q i) {L : ℕ} (hL : 0 < L) {R : ℝ} (hR : 0 ≤ R) :
+ ∃ C : ℝ, ∀ (M : ℕ) (b : D → ℕ) (v : S → ℕ), (∀ i, b i ≤ M) →
+ widthNorm q (fun i => v i) ≤ (copies (widthNorm p (fun i => b i)) L : ℝ) * L * R →
+ (copies (widthNorm p (fun i => b i)) L : ℝ) ≤ C * (M + 1) ∧
+ ∀ i, (v i : ℝ) ≤ C * (M + 1) := by
+ let P := widthNorm p (fun _ => 1)
+ let Q := ∑ i, √(q i)
+ let C := max (P + L) (Q * R * (P + L))
+ refine ⟨C, fun M b v hb hv => ?_⟩
+ let N := widthNorm p (fun i => (b i : ℝ))
+ let u := copies N L
+ have hN : N ≤ M * P := by
+ calc
+ N ≤ widthNorm p (fun _ => (M : ℝ) * 1) := norm_mono p _ _ hp
+ (fun i => Nat.cast_nonneg _) (fun i => by simpa using hb i)
+ _ = M * P := widthNorm_scale _ _ (Nat.cast_nonneg _)
+ have hp0 : 0 ≤ P := Real.sqrt_nonneg _
+ have hu : (u : ℝ) * L ≤ (P + L) * (M + 1) := by
+ have h := (copies_spec (show 0 ≤ N from Real.sqrt_nonneg _) hL).2
+ change (u : ℝ) * L ≤ N + L at h
+ nlinarith only [h, hN, hp0, mul_nonneg (Nat.cast_nonneg M : (0 : ℝ) ≤ M) (Nat.cast_nonneg L)]
+ constructor
+ · have h1 : (1 : ℝ) ≤ L := by exact_mod_cast hL
+ exact (le_mul_of_one_le_right (Nat.cast_nonneg u) h1).trans
+ (hu.trans (mul_le_mul_of_nonneg_right (le_max_left _ _) (by positivity)))
+ · intro i
+ have hi : √(q i) ≤ Q := Finset.single_le_sum (fun j _ => Real.sqrt_nonneg (q j))
+ (Finset.mem_univ i)
+ have hq0 : 0 ≤ Q := Finset.sum_nonneg fun _ _ => Real.sqrt_nonneg _
+ calc
+ (v i : ℝ) ≤ √(q i) * widthNorm q (fun j => v j) := coordinate_le q (fun j => (v j : ℝ)) hq i
+ _ ≤ Q * ((u : ℝ) * L * R) := mul_le_mul hi hv (Real.sqrt_nonneg _) hq0
+ _ = Q * R * ((u : ℝ) * L) := by ring
+ _ ≤ Q * R * ((P + L) * (M + 1)) := mul_le_mul_of_nonneg_left hu (mul_nonneg hq0 hR)
+ _ ≤ C * (M + 1) := by rw [← mul_assoc]; gcongr; exact le_max_right _ _
+
+end MotifWidths
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/MotifWirePowers.lean b/lean/OAI/Computability/VPVNP/MotifWirePowers.lean
new file mode 100644
index 0000000000..67136523e5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/MotifWirePowers.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.TensorRestrictionSemiring
+
+/-!
+# Width arithmetic for binary wire networks
+
+A wire of width `w` has `2 ^ w` index values. Concatenating two indices at
+both endpoints multiplies the corresponding networks under tensor product.
+This realizes repetitions of a motif as ordinary powers of its restriction
+class, including for loops and repeated edges.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor.RestrictionClass
+
+universe u v
+
+variable {k : Type u} {J : Type v} {E : Type} [Field k] [Fintype J] [Fintype E]
+
+/-- The restriction class of a graph with an integer bit width at each edge. -/
+noncomputable def binaryNetworkClass (a b : E → J) (w : E → ℕ) : RestrictionClass k J :=
+ ofTensor (wireNetwork a b (fun e ↦ Fin (2 ^ w e)))
+
+private def joinBasis (a b : E → J) {I U R : E → Type}
+ [∀ e, Fintype (I e)] [∀ e, Fintype (U e)] [∀ e, Fintype (R e)]
+ (f : ∀ e, I e × U e ≃ R e) (j : J) :
+ (tensorProduct (wireNetwork (k := k) a b I) (wireNetwork a b U)).Basis j ≃
+ (wireNetwork (k := k) a b R).Basis j where
+ toFun x := ⟨fun e h ↦ f e (x.1.1 e h, x.2.1 e h), fun e h ↦ f e (x.1.2 e h, x.2.2 e h)⟩
+ invFun x :=
+ (⟨fun e h ↦ ((f e).symm (x.1 e h)).1, fun e h ↦ ((f e).symm (x.2 e h)).1⟩,
+ ⟨fun e h ↦ ((f e).symm (x.1 e h)).2, fun e h ↦ ((f e).symm (x.2 e h)).2⟩)
+ left_inv x := by
+ rcases x with ⟨⟨_, _⟩, ⟨_, _⟩⟩
+ simp
+ rfl
+ right_inv x := by
+ rcases x with ⟨_, _⟩
+ simp
+ rfl
+
+private theorem multiply_indicators {P Q R : Prop} [Decidable P] [Decidable Q] [Decidable R]
+ (h : R ↔ P ∧ Q) :
+ (if P then (1 : k) else 0) * (if Q then 1 else 0) = (if R then 1 else 0) := by
+ split_ifs <;> simp_all
+
+/-- Adding widths pointwise amounts to taking the tensor product. -/
+theorem binaryNetworkClass_add (a b : E → J) (w u : E → ℕ) :
+ binaryNetworkClass (k := k) a b (fun e ↦ w e + u e) =
+ binaryNetworkClass a b w * binaryNetworkClass a b u := by
+ classical
+ let f (e : E) : Fin (2 ^ w e) × Fin (2 ^ u e) ≃ Fin (2 ^ (w e + u e)) :=
+ finProdFinEquiv.trans (finCongr (pow_add 2 (w e) (u e)).symm)
+ apply (ofTensor_eq_iff _ _).2
+ apply restricts_of_reindex (joinBasis (k := k) a b f)
+ intro x
+ simp only [tensorProduct, wireNetwork, ← Finset.prod_mul_distrib]
+ apply Finset.prod_congr rfl
+ intro e _
+ have h : ((joinBasis (k := k) a b f (a e)) (x (a e))).1 e rfl =
+ ((joinBasis (k := k) a b f (b e)) (x (b e))).2 e rfl ↔
+ (x (a e)).1.1 e rfl = (x (b e)).1.2 e rfl ∧ (x (a e)).2.1 e rfl = (x (b e)).2.2 e rfl := by
+ change f e (_, _) = f e (_, _) ↔ _
+ rw [Equiv.apply_eq_iff_eq, Prod.mk.injEq]
+ exact @multiply_indicators k _ _ _ _ (Classical.propDecidable _) (Classical.propDecidable _)
+ (Classical.propDecidable _) h
+
+/-- Width zero gives the tensor unit. -/
+theorem binaryNetworkClass_zero (a b : E → J) :
+ binaryNetworkClass (k := k) a b (fun _ ↦ 0) = 1 := by
+ classical
+ change ofTensor (wireNetwork (k := k) a b (fun _ ↦ Fin 1)) = ofTensor unit
+ apply (ofTensor_eq_iff _ _).2
+ let f (j : J) : PUnit ≃ ((e : E) → j = a e → Fin 1) × ((e : E) → j = b e → Fin 1) :=
+ { toFun := fun _ ↦ edgeAssignment a b (I := fun _ ↦ Fin 1) (fun _ ↦ 0) j
+ invFun := fun _ ↦ PUnit.unit
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ Subsingleton.elim _ _ }
+ apply restricts_of_reindex f
+ intro x
+ symm
+ apply Finset.prod_eq_one
+ intro e _
+ exact ite_eq_left (Subsingleton.elim _ _)
+
+variable [Nonempty J]
+
+/-- Repeating all edge widths `n` times gives the `n`th power of the class. -/
+theorem binaryNetworkClass_pow (a b : E → J) (w : E → ℕ) (n : ℕ) :
+ binaryNetworkClass (k := k) a b (fun e ↦ n * w e) = binaryNetworkClass a b w ^ n := by
+ induction n with
+ | zero => simp [binaryNetworkClass_zero]
+ | succ n ih => simp only [Nat.succ_mul, binaryNetworkClass_add, ih, pow_succ]
+
+/-- The widths accumulated by a finite family of motifs give the product
+of the corresponding restriction classes. -/
+theorem binaryNetworkClass_sum {ι : Type*} (a b : E → J) (S : Finset ι) (ws : ι → E → ℕ) :
+ binaryNetworkClass (k := k) a b (fun e ↦ ∑ i ∈ S, ws i e) =
+ ∏ i ∈ S, binaryNetworkClass a b (ws i) := by
+ classical
+ induction S using Finset.induction_on with
+ | empty => simp [binaryNetworkClass_zero]
+ | insert i S hi ih =>
+ simp only [Finset.sum_insert hi, Finset.prod_insert hi, binaryNetworkClass_add, ih]
+
+end WireTensor.RestrictionClass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/NetworkFactorIso.lean b/lean/OAI/Computability/VPVNP/NetworkFactorIso.lean
new file mode 100644
index 0000000000..50093e203d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/NetworkFactorIso.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.NetworkHalfIso
+
+/-!
+# Local factors after relabelling a network
+
+Reindex each whole local factor by the new site and pull its incoming and
+outgoing arguments back along the alphabet bijections. This preserves the
+contraction, even for a network with parallel edges.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace NetworkKernel.Network.Iso
+
+open WireTensor
+
+variable {N M : NetworkKernel.Network}
+
+/-- Move an arbitrary local factor to its corresponding relabelled site. -/
+def pushFactors {k : Type*} (f : N.Iso M) (F : Factors k N) : Factors k M :=
+ Equiv.piCongrLeft (fun u ↦ M.Half u → k) f.site fun u z ↦ F u (f.pullHalf u z)
+
+@[simp] theorem pushFactors_at {k : Type*} (f : N.Iso M) (F : Factors k N) (u : N.Site)
+ (z : M.Half (f.site u)) : f.pushFactors F (f.site u) z = F u (f.pullHalf u z) := by
+ rw [pushFactors, Equiv.piCongrLeft_apply_apply]
+
+/-- One shared payload per relabelled edge corresponds to one per original
+edge. Every local factor then sees exactly its original incident arguments. -/
+theorem contract_pushFactors {k : Type*} [CommSemiring k] (f : N.Iso M) (F : Factors k N) :
+ contract M (f.pushFactors F) = contract N F := by
+ classical
+ rw [contract_edgeSum, contract_edgeSum]
+ symm
+ apply Fintype.sum_equiv (f.edge.piCongr f.payload)
+ intro z
+ apply Fintype.prod_equiv f.site
+ intro u
+ rw [pushFactors_at]
+ simp only [pullHalf, edgeAssignment, Equiv.piCongr_apply_apply, Equiv.symm_apply_apply]
+
+/-- Transport the finite family of individual choices counted by a local
+factor. At the image site, its elements are the choices on the pulled-back
+half-wire data. -/
+@[instance_reducible] def pushChoiceFintype (f : N.Iso M) (P : Factors Type N)
+ (fin : ∀ u z, Fintype (P u z)) : ∀ v z, Fintype (f.pushFactors P v z) :=
+ Equiv.piCongrLeft (fun v ↦ ∀ z, Fintype (f.pushFactors P v z)) f.site fun u z ↦
+ (f.pushFactors_at P u z).symm ▸ fin u (f.pullHalf u z)
+
+/-- The multiplicities of the transported local choice types have the same
+contraction as the original local choice counts. -/
+theorem contract_pushChoiceCount (f : N.Iso M) (P : Factors Type N)
+ (fin : ∀ u z, Fintype (P u z)) :
+ contract M (fun v z ↦ @Fintype.card _ (f.pushChoiceFintype P fin v z)) =
+ contract N (fun u z ↦ @Fintype.card _ (fin u z)) := by
+ rw [← f.contract_pushFactors (fun u z ↦ @Fintype.card _ (fin u z))]
+ congr 1
+ funext v z
+ obtain ⟨u, rfl⟩ := f.site.surjective v
+ rw [f.pushFactors_at (fun u z ↦ @Fintype.card _ (fin u z)) u z]
+ exact @Fintype.card_congr _ _ (f.pushChoiceFintype P fin _ z) (fin u (f.pullHalf u z))
+ (Equiv.cast (f.pushFactors_at P u z))
+
+end NetworkKernel.Network.Iso
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/NetworkHalfIso.lean b/lean/OAI/Computability/VPVNP/NetworkHalfIso.lean
new file mode 100644
index 0000000000..e158d53b83
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/NetworkHalfIso.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.NetworkIso
+
+/-!
+# Half-wire coordinates under network relabelling
+
+In a placed expansion, changing the coordinates of the input network gives
+a bijection on the independent half-wire assignments at each old site. The
+same expansion can then use the original output network for each choice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace NetworkKernel
+
+namespace Network.Iso
+
+variable {N M : Network}
+
+/-- Relabel each site, edge and payload by its identity map. -/
+def refl (N : Network) : N.Iso N where
+ site := Equiv.refl _
+ edge := Equiv.refl _
+ src _ := rfl
+ dst _ := rfl
+ payload _ := Equiv.refl _
+
+/-- Pulling the half-wire indices back to an original site is a bijection. -/
+def pullHalfEquiv (f : N.Iso M) (u : N.Site) : M.Half (f.site u) ≃ N.Half u where
+ toFun := f.pullHalf u
+ invFun a :=
+ ⟨Equiv.piCongrLeft (fun e ↦ f.site u = M.src e → M.Payload e) f.edge
+ (fun e h ↦ f.payload e (a.1 e (f.site.injective (h.trans (f.src e).symm)))),
+ Equiv.piCongrLeft (fun e ↦ f.site u = M.dst e → M.Payload e) f.edge
+ (fun e h ↦ f.payload e (a.2 e (f.site.injective (h.trans (f.dst e).symm))))⟩
+ left_inv a := by
+ apply Prod.ext <;> funext e h <;> obtain ⟨x, rfl⟩ := f.edge.surjective e <;>
+ simp only [pullHalf, Equiv.piCongrLeft_apply_apply, Equiv.apply_symm_apply]
+ right_inv a := by
+ apply Prod.ext <;> funext e h <;>
+ simp only [pullHalf, Equiv.piCongrLeft_apply_apply, Equiv.symm_apply_apply]
+
+end Network.Iso
+
+variable {k : Type*} [CommSemiring k] {N M : Network}
+
+/-- Reindex the input of an exact step, retaining its chosen output for every term. -/
+noncomputable def Step.reindexInput (s : Step k N) (input : N.Iso M) : Step k M :=
+ s.reindex input fun i ↦ Network.Iso.refl (s.term i).output
+
+/-- An input reindexing retains the output network at each choice. -/
+@[simp] theorem Step.reindexInput_term_output (s : Step k N) (input : N.Iso M) (i : s.Choice) :
+ ((s.reindexInput input).term i).output = (s.term i).output := rfl
+
+end NetworkKernel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/NetworkIso.lean b/lean/OAI/Computability/VPVNP/NetworkIso.lean
new file mode 100644
index 0000000000..120e2b7d1c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/NetworkIso.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.NetworkKernel
+
+/-!
+# Relabelling a placed wire-network expansion
+
+Bijections on sites, edges and individual payload alphabets preserve each
+wire equality. Transporting both the input and a choice-dependent output
+therefore preserves the exact identity for a substep.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace NetworkKernel
+
+/-- A relabelling of sites and edges, with a bijection on the alphabet of each wire. -/
+structure Network.Iso (N M : Network) where
+ /-- Bijection carrying sites of the original network to sites of the relabelled network. -/
+ site : N.Site ≃ M.Site
+ /-- Bijection carrying individual wires to the relabelled wires, including parallel wires. -/
+ edge : N.Edge ≃ M.Edge
+ src : ∀ e, site (N.src e) = M.src (edge e)
+ dst : ∀ e, site (N.dst e) = M.dst (edge e)
+ /-- For each original wire, a bijection from its payload alphabet to the alphabet of its
+ image wire. -/
+ payload : ∀ e, N.Payload e ≃ M.Payload (edge e)
+
+
+namespace Network.Iso
+
+variable {N M : Network}
+
+/-- Pull a half-wire assignment at an image site back to its original site. -/
+def pullHalf (f : N.Iso M) (u : N.Site) (a : M.Half (f.site u)) : N.Half u :=
+ ⟨fun e h ↦ (f.payload e).symm (a.1 (f.edge e) ((congrArg f.site h).trans (f.src e))),
+ fun e h ↦ (f.payload e).symm (a.2 (f.edge e) ((congrArg f.site h).trans (f.dst e)))⟩
+
+/-- Pull every site's independent half-wire assignment back along the isomorphism. -/
+def pull (f : N.Iso M) (a : ∀ u, M.Half u) (u : N.Site) : N.Half u :=
+ f.pullHalf u (a (f.site u))
+
+private theorem src_at {v : M.Site} {e : M.Edge} (a : ∀ u, M.Half u) (h : v = M.src e) :
+ (a v).1 e h = (a (M.src e)).1 e rfl := by cases h; rfl
+
+private theorem dst_at {v : M.Site} {e : M.Edge} (a : ∀ u, M.Half u) (h : v = M.dst e) :
+ (a v).2 e h = (a (M.dst e)).2 e rfl := by cases h; rfl
+
+/-- The network equality tensor is invariant under the relabelling. -/
+theorem coeff_pull {k : Type*} [CommSemiring k] (f : N.Iso M) (a : ∀ u, M.Half u) :
+ N.coeff (k := k) (f.pull a) = M.coeff a := by
+ classical
+ unfold Network.coeff Network.tensor WireTensor.wireNetwork
+ apply Fintype.prod_equiv f.edge
+ intro e
+ simp only [pull, pullHalf, src_at a, dst_at a, Equiv.apply_eq_iff_eq]
+
+end Network.Iso
+
+variable {N M : Network} {k : Type*}
+
+/-- Transport the placements and local kernels of one term along input and output
+network isomorphisms. -/
+noncomputable def Term.reindex (t : Term k N) (input : N.Iso M) {P : Network}
+ (output : t.output.Iso P) : Term k M where
+ output := P
+ place u := output.site (t.place (input.site.symm u))
+ kernel := Equiv.piCongrLeft _ output.site fun v a z ↦
+ t.kernel v (fun u h ↦ input.pullHalf u (a (input.site u) (by simpa using congrArg output.site h)))
+ (output.pullHalf v z)
+
+/-- Transport preserves a term's value on the corresponding half-wire assignment. -/
+theorem Term.value_reindex [CommSemiring k] (t : Term k N) (input : N.Iso M)
+ {P : Network} (output : t.output.Iso P) (a : ∀ u, M.Half u) :
+ (t.reindex input output).value a = t.value (input.pull a) := by
+ classical
+ rw [Term.value_eq_edgeSum, Term.value_eq_edgeSum]
+ symm
+ let labels := output.edge.piCongr output.payload
+ apply Fintype.sum_equiv labels
+ intro z
+ apply Fintype.prod_equiv output.site
+ intro v
+ simp only [reindex, Equiv.piCongrLeft_apply_apply, Network.Iso.pull,
+ Network.Iso.pullHalf, WireTensor.edgeAssignment, labels, Equiv.piCongr_apply_apply,
+ Equiv.symm_apply_apply]
+
+/-- Transport an exact step along an input network isomorphism and one output
+network isomorphism for each choice. -/
+noncomputable def Step.reindex [CommSemiring k] (s : Step k N) (input : N.Iso M)
+ {out : s.Choice → Network} (output : ∀ i, (s.term i).output.Iso (out i)) : Step k M where
+ Choice := s.Choice
+ choiceFintype := s.choiceFintype
+ term i := (s.term i).reindex input (output i)
+ exact_eq a := by
+ rw [← input.coeff_pull a, s.exact_eq]
+ simp only [Term.value_reindex]
+
+end NetworkKernel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/NetworkKernel.lean b/lean/OAI/Computability/VPVNP/NetworkKernel.lean
new file mode 100644
index 0000000000..d57121514e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/NetworkKernel.lean
@@ -0,0 +1,321 @@
+import OAI.Computability.VPVNP.PlacedTensor
+
+/-!
+# Placed local kernels of a wire network
+
+Equation (7.1) of *VP and VNP differ over every field* sums over motif choices
+and then over one shared assignment per edge of the chosen output network.
+A choice determines the topology, the widths, and the placement of whole old
+vertex factors. Contracting the expansion against arbitrary factors only
+requires independent old half-wire indices inside each new site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace NetworkKernel
+
+open WireTensor
+
+/-- An indexed wire network. The payload alphabet can vary from edge to edge. -/
+structure Network where
+ /-- Finite type of sites where the network's half-wire payloads are assigned. -/
+ Site : Type
+ siteFintype : Fintype Site
+ /-- Finite type of individual directed wires whose endpoint payloads are equated by the
+ network tensor. -/
+ Edge : Type
+ edgeFintype : Fintype Edge
+ /-- Source site of a directed wire, where its outgoing half-wire payload is assigned. -/
+ src : Edge → Site
+ /-- Destination site of a directed wire, where its incoming half-wire payload is assigned. -/
+ dst : Edge → Site
+ /-- Finite alphabet of possible payloads shared by the two ends of each wire. -/
+ Payload : Edge → Type
+ payloadFintype : ∀ e, Fintype (Payload e)
+
+attribute [instance] Network.siteFintype Network.edgeFintype Network.payloadFintype
+
+/-- Independent assignments to all incoming and outgoing half-wires at a site. -/
+abbrev Network.Half (N : Network) (v : N.Site) :=
+ ((e : N.Edge) → v = N.src e → N.Payload e) × ((e : N.Edge) → v = N.dst e → N.Payload e)
+
+variable {k : Type*} [CommSemiring k]
+
+/-- The equality of the two half-wire indices on each edge. -/
+noncomputable abbrev Network.tensor (N : Network) (k : Type*) [CommSemiring k] :=
+ wireNetwork (k := k) N.src N.dst N.Payload
+
+/-- Product of wire equality indicators on a global half-wire assignment. -/
+noncomputable def Network.coeff (N : Network) (a : ∀ u, N.Half u) : k :=
+ (N.tensor k).coeff a
+
+/-- Local old indices assigned to a single new site by the placement. -/
+abbrev Placed {U V : Type} (p : U → V) (B : U → Type) (v : V) :=
+ (u : U) → v = p u → B u
+
+/-- One admitted term of a substep. Its network and placement can depend on
+the entire list of selected motif terms. -/
+structure Term (k : Type*) (old : Network) where
+ /-- New network used in this summand of the compression step. -/
+ output : Network
+ /-- Assigns each old site to the new site that receives its half-wire data. -/
+ place : old.Site → output.Site
+ /-- Local coefficient at a new site, depending on the old half-wire data placed there and on
+ the new half-wire assignment. -/
+ kernel : ∀ v, Placed place old.Half v → output.Half v → k
+
+open scoped Classical in
+/-- Wire expansion in one term, read as a local map on the output wire tensor. -/
+noncomputable def Term.value {N : Network} (t : Term k N) (a : ∀ u, N.Half u) : k :=
+ applyLocal t.kernel (t.output.tensor k).coeff (placedAssignmentEquiv t.place N.Half a)
+
+open scoped Classical in
+/-- Each term of (7.1) uses exactly one sum per new edge, including parallel
+edges. Both ends of the edge use the same payload. -/
+theorem Term.value_eq_edgeSum {N : Network} (t : Term k N) (a : ∀ u, N.Half u) :
+ t.value a = ∑ z : (e : t.output.Edge) → t.output.Payload e,
+ ∏ v, t.kernel v (fun u _ ↦ a u) (edgeAssignment t.output.src t.output.dst z v) :=
+ applyLocal_wireNetwork t.output.src t.output.dst t.output.Payload t.kernel
+ (placedAssignmentEquiv t.place N.Half a)
+
+/-- A substep specifies its finite term list and the coefficient identity. -/
+structure Step (k : Type*) [CommSemiring k] (old : Network) where
+ /-- Finite index type of terms in the exact expansion of the old network's coefficient. -/
+ Choice : Type
+ choiceFintype : Fintype Choice
+ /-- Output network, placement and local kernels chosen by a term index. -/
+ term : Choice → Term k old
+ exact_eq : ∀ a, old.coeff a = ∑ i, (term i).value a
+
+attribute [instance] Step.choiceFintype
+
+open scoped Classical in
+/-- Equation (7.1), with both sums and the dependence of all incidence data on
+the chosen term displayed. -/
+theorem Step.edgeExpansion {N : Network} (s : Step k N) (a : ∀ u, N.Half u) :
+ N.coeff a = ∑ i, ∑ z : (e : (s.term i).output.Edge) → (s.term i).output.Payload e,
+ ∏ v, (s.term i).kernel v (fun u _ ↦ a u)
+ (edgeAssignment (s.term i).output.src (s.term i).output.dst z v) := by
+ simp only [s.exact_eq, Term.value_eq_edgeSum]
+
+/-- Whole local factors, evaluated at a fixed choice of any external indices. -/
+abbrev Factors (k : Type*) (N : Network) := ∀ u, N.Half u → k
+
+open scoped Classical in
+/-- Contract the wire equalities with arbitrary local factors. -/
+noncomputable def contract (N : Network) (F : Factors k N) : k :=
+ ∑ a : (u : N.Site) → N.Half u, (∏ u, F u (a u)) * N.coeff a
+
+open scoped Classical in
+/-- In a contraction against wire equalities, one common value per edge
+suffices. -/
+theorem contract_edgeSum (N : Network) (F : Factors k N) :
+ contract N F = ∑ z : (e : N.Edge) → N.Payload e, ∏ u, F u (edgeAssignment N.src N.dst z u) :=
+ applyLocal_wireNetwork N.src N.dst N.Payload (fun u (_ : Unit) z ↦ F u z) (fun _ ↦ ())
+
+open scoped Classical in
+/-- Only the original factors placed at this site enter its local product. -/
+noncomputable def Term.placedProduct {N : Network} (t : Term k N) (F : Factors k N)
+ (v : t.output.Site) (a : Placed t.place N.Half v) : k :=
+ ∏ u, if h : v = t.place u then F u (a u h) else 1
+
+private theorem Term.prod_placedProduct {N : Network} (t : Term k N) (F : Factors k N)
+ (a : ∀ u, N.Half u) :
+ (∏ v, t.placedProduct F v (fun u _ ↦ a u)) = ∏ u, F u (a u) := by
+ classical
+ simp only [Term.placedProduct]
+ rw [Finset.prod_comm]
+ simp
+
+open scoped Classical in
+/-- The new local vertex factor obtained by summing the old half-wire indices
+at this site. The same kernel applies when the old factors carry free indices. -/
+noncomputable def Term.push {N : Network} (t : Term k N) (F : Factors k N) :
+ Factors k t.output := fun v z ↦
+ ∑ a : Placed t.place N.Half v, t.placedProduct F v a * t.kernel v a z
+
+open scoped Classical in
+/-- A single placed kernel contracts locally against the complete old factors. -/
+theorem Term.contract_value {N : Network} (t : Term k N) (F : Factors k N) :
+ (∑ a : (u : N.Site) → N.Half u, (∏ u, F u (a u)) * t.value a) =
+ contract t.output (t.push F) := by
+ simp only [Term.value_eq_edgeSum, Finset.mul_sum, contract_edgeSum]
+ rw [Finset.sum_comm]
+ apply Finset.sum_congr rfl
+ intro z _
+ simp only [Term.push, Fintype.prod_sum]
+ apply Fintype.sum_equiv (placedAssignmentEquiv t.place N.Half)
+ intro a
+ simp only [Finset.prod_mul_distrib, placedAssignmentEquiv, Equiv.coe_fn_mk,
+ Term.prod_placedProduct]
+
+open scoped Classical in
+/-- Substitution of a kernel expansion preserves the contraction of an
+arbitrary old network over the coefficient semiring. -/
+theorem Step.contract_eq_sum {N : Network} (s : Step k N) (F : Factors k N) :
+ contract N F = ∑ i, contract (s.term i).output ((s.term i).push F) := by
+ simp only [contract, s.exact_eq, Finset.mul_sum]
+ rw [Finset.sum_comm]
+ exact Finset.sum_congr rfl fun i _ ↦ (s.term i).contract_value F
+
+
+open scoped Classical in
+/-- Push an old factor with external indices, carrying all of those indices
+to its designated new site. The local map only reads the external indices
+in that site's placement fiber. -/
+noncomputable def Term.pushOpen {N : Network} (t : Term k N) {External : N.Site → Type}
+ (F : ∀ u, External u → N.Half u → k) (v : t.output.Site) (c : Placed t.place External v)
+ (z : t.output.Half v) : k :=
+ ∑ a : Placed t.place N.Half v,
+ (∏ u, if h : v = t.place u then F u (c u h) (a u h) else 1) * t.kernel v a z
+
+open scoped Classical in
+/-- Substep substitution with uncontracted indices. At each new site the
+external input consists exactly of the old external inputs placed there. -/
+theorem Step.contract_open {N : Network} (s : Step k N) {External : N.Site → Type}
+ (F : ∀ u, External u → N.Half u → k) (c : (u : N.Site) → External u) :
+ contract N (fun u a ↦ F u (c u) a) =
+ ∑ i, contract (s.term i).output (fun v ↦ (s.term i).pushOpen F v (fun u _ ↦ c u)) :=
+ s.contract_eq_sum _
+
+/-- A layout before contraction of wires whose two endpoints land at the
+same output site. Each of these wires has one payload, owned by that site. -/
+structure Layout (k : Type*) (old : Network) where
+ /-- Network of exposed wires remaining after internal labels are summed. -/
+ output : Network
+ /-- Assigns each old site to the output site at which its data enter the local coefficient. -/
+ place : old.Site → output.Site
+ /-- Finite type of absorbed wires or other internal summation indices. -/
+ Internal : Type
+ internalFintype : Fintype Internal
+ /-- Finite alphabet summed over at each internal index. -/
+ Label : Internal → Type
+ labelFintype : ∀ e, Fintype (Label e)
+ /-- Output site responsible for summing the label at each internal index. -/
+ owner : Internal → output.Site
+ /-- Local coefficient before summation, depending on the old data placed at the site, its
+ internal labels and its exposed half-wires. -/
+ entry : ∀ v, Placed place old.Half v → Placed owner Label v → output.Half v → k
+
+attribute [instance] Layout.internalFintype Layout.labelFintype
+
+open scoped Classical in
+/-- Summing each absorbed edge once, inside the kernel at its owner. -/
+noncomputable def Layout.term {N : Network} (L : Layout k N) : Term k N where
+ output := L.output
+ place := L.place
+ kernel v a z := ∑ h : Placed L.owner L.Label v, L.entry v a h z
+
+open scoped Classical in
+/-- Local sums over internal wires are equal to one global assignment to the
+internal wires. The shared edge indices of the output are summed separately. -/
+theorem Layout.term_value {N : Network} (L : Layout k N) (a : ∀ u, N.Half u) :
+ L.term.value a = ∑ z : (e : L.output.Edge) → L.output.Payload e,
+ ∑ h : (e : L.Internal) → L.Label e,
+ ∏ v, L.entry v (fun u _ ↦ a u) (fun e _ ↦ h e)
+ (edgeAssignment L.output.src L.output.dst z v) := by
+ rw [Term.value_eq_edgeSum]
+ apply Finset.sum_congr rfl
+ intro z _
+ change (∏ v, ∑ h : Placed L.owner L.Label v,
+ L.entry v (fun u _ ↦ a u) h (edgeAssignment L.output.src L.output.dst z v)) = _
+ rw [Fintype.prod_sum]
+ symm
+ exact Fintype.sum_equiv (placedAssignmentEquiv L.owner L.Label) _ _ (fun _ ↦ rfl)
+
+open scoped Classical in
+/-- Assemble exact motif expansions into a step of (7.1). The hypotheses
+describe the original demand factorization, the individual motif identities,
+and the two properties of the selected layout: its payload bijection and
+the regrouping of its map entries. The layout may depend on the whole list
+of selectors. -/
+noncomputable def Step.ofMotifProduct {N : Network} {M : Type} [Fintype M]
+ (C : M → Type) [∀ m, Fintype (C m)] (X : (m : M) → C m → Type)
+ [∀ m i, Fintype (X m i)]
+ (demand : M → ((u : N.Site) → N.Half u) → k)
+ (contribution : (m : M) → (i : C m) → X m i → ((u : N.Site) → N.Half u) → k)
+ (old_eq : ∀ a, N.coeff a = ∏ m, demand m a)
+ (motif_eq : ∀ m a, demand m a = ∑ i, ∑ x, contribution m i x a)
+ (L : ((m : M) → C m) → Layout k N)
+ (split : ∀ s, ((m : M) → X m (s m)) ≃
+ ((e : (L s).output.Edge) → (L s).output.Payload e) × ((e : (L s).Internal) → (L s).Label e))
+ (group : ∀ s x a, (∏ m, contribution m (s m) (x m) a) =
+ ∏ v, (L s).entry v (fun u _ ↦ a u) (fun e _ ↦ (split s x).2 e)
+ (edgeAssignment (L s).output.src (L s).output.dst (split s x).1 v)) : Step k N where
+ Choice := (m : M) → C m
+ choiceFintype := inferInstance
+ term s := (L s).term
+ exact_eq a := by
+ simp only [old_eq, motif_eq, Fintype.prod_sum, Layout.term_value]
+ apply Finset.sum_congr rfl
+ intro s _
+ let f (z : ((e : (L s).output.Edge) → (L s).output.Payload e) ×
+ ((e : (L s).Internal) → (L s).Label e)) :=
+ ∏ v, (L s).entry v (fun u _ ↦ a u) (fun e _ ↦ z.2 e)
+ (edgeAssignment (L s).output.src (L s).output.dst z.1 v)
+ exact (Fintype.sum_equiv (split s) _ f (fun x ↦ group s x a)).trans
+ (Fintype.sum_prod_type f)
+
+open scoped Classical in
+/-- Fixing the old half-wire indices turns a term into a contraction of the
+new network against the rows of its local kernels. -/
+theorem Term.value_eq_contract {N : Network} (t : Term k N) (a : ∀ u, N.Half u) :
+ t.value a = contract t.output (fun v z ↦ t.kernel v (fun u _ ↦ a u) z) :=
+ (t.value_eq_edgeSum a).trans (contract_edgeSum _ _).symm
+
+/-- Finite branch-dependent iteration of substeps. A branch can use a
+different continuation for each selected term. -/
+inductive History (k : Type*) [CommSemiring k] : Network → Type _
+ | stop {N} : History k N
+ | branch {N} (step : Step k N) (tail : ∀ i, History k (step.term i).output) : History k N
+
+namespace History
+
+/-- Fully enumerated paths carry every term choice, each old half-wire
+assignment separately, and the one shared final payload on each final edge. -/
+def Path {N : Network} : History k N → Type
+ | .stop => (e : N.Edge) → N.Payload e
+ | .branch s tail => (i : s.Choice) × ((u : N.Site) → N.Half u) × (tail i).Path
+
+open scoped Classical in
+noncomputable instance pathFintype {N : Network} (H : History k N) : Fintype H.Path := by
+ induction H with
+ | @stop N => exact inferInstanceAs (Fintype ((e : N.Edge) → N.Payload e))
+ | @branch N s tail ih =>
+ letI := ih
+ exact inferInstanceAs (Fintype ((i : s.Choice) × ((u : N.Site) → N.Half u) × (tail i).Path))
+
+/-- Product of original factor entries and the kernel entries selected by the
+path. Every intermediate assignment is explicitly part of the path. -/
+noncomputable def weight {N : Network} (H : History k N) (F : Factors k N) : H.Path → k :=
+ match H with
+ | .stop => fun z ↦ ∏ u, F u (edgeAssignment N.src N.dst z u)
+ | .branch s tail => fun ⟨i, a, path⟩ ↦
+ (∏ u, F u (a u)) *
+ (tail i).weight (fun v z ↦ (s.term i).kernel v (fun u _ ↦ a u) z) path
+
+/-- Iterated substitution as a single finite sum over fully expanded paths.
+This is the exact algebra used before weighting paths in Section 12. -/
+theorem contract_eq_sum_paths {N : Network} (H : History k N) (F : Factors k N) :
+ contract N F = ∑ p : H.Path, H.weight F p := by
+ classical
+ induction H with
+ | stop => exact contract_edgeSum _ _
+ | @branch N s tail ih =>
+ change contract N F =
+ ∑ p : (i : s.Choice) × ((u : N.Site) → N.Half u) × (tail i).Path,
+ (∏ u, F u (p.2.1 u)) *
+ (tail p.1).weight (fun v z ↦ (s.term p.1).kernel v (fun u _ ↦ p.2.1 u) z) p.2.2
+ simp only [Fintype.sum_sigma, Fintype.sum_prod_type, ← Finset.mul_sum, ← ih,
+ ← Term.value_eq_contract]
+ simp only [contract, s.exact_eq, Finset.mul_sum]
+ exact Finset.sum_comm
+
+end History
+end NetworkKernel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/NetworkMonomialIso.lean b/lean/OAI/Computability/VPVNP/NetworkMonomialIso.lean
new file mode 100644
index 0000000000..53d12810d1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/NetworkMonomialIso.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.NetworkMonomials
+import OAI.Computability.VPVNP.NetworkHalfIso
+
+/-!
+# Reindexing local kernel witnesses
+
+The coordinate change on the input and output of a tensor substitution
+transports the arguments of each local map. Its successful checks, choices
+and parameter exponents remain the ones attached to the original map.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace NetworkKernel
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+variable {N M P : Network}
+
+/-- Transport witnesses for every local kernel entry of one placed term. -/
+noncomputable def Term.reindexWitness (t : Term A N)
+ (W : ∀ v a z, MonomialWitness κ (t.kernel v a z))
+ (input : N.Iso M) (output : t.output.Iso P) :
+ ∀ v a z, MonomialWitness κ ((t.reindex input output).kernel v a z) := by
+ dsimp only [Term.reindex]
+ refine (Equiv.piCongrLeft _ output.site) ?_
+ intro v a z
+ rw [Equiv.piCongrLeft_apply_apply]
+ exact W v _ _
+
+/-- A step written in new input coordinates carries the same finite
+witnesses for every selected output term and local kernel. -/
+noncomputable def Step.reindexInputWitness (s : Step A N) (input : N.Iso M)
+ (W : ∀ i v a z, MonomialWitness κ ((s.term i).kernel v a z)) :
+ ∀ i v a z, MonomialWitness κ (((s.reindexInput input).term i).kernel v a z) :=
+ fun i ↦ (s.term i).reindexWitness (W i) input (Network.Iso.refl _)
+
+end NetworkKernel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/NetworkMonomials.lean b/lean/OAI/Computability/VPVNP/NetworkMonomials.lean
new file mode 100644
index 0000000000..fa6e2f3779
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/NetworkMonomials.lean
@@ -0,0 +1,235 @@
+import OAI.Computability.VPVNP.NetworkKernel
+import OAI.Computability.VPVNP.Diagonal
+
+/-!
+# The monomials of an expanded contraction
+
+In equation (12.2) of *VP and VNP differ over every field*, each path records
+the old half-wire indices, a local witness for each kernel entry, and an
+accepting path at each original site. Products add parameter exponents.
+The choice sets are specified independently of the parameter values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace NetworkKernel
+
+open Diagonal
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+
+/-- An entry specified by finite witnesses, each contributing a parameter
+monomial. The empty witness set represents a failed local check. -/
+structure MonomialWitness (κ : Label → A) (value : A) where
+ /-- Finite index type of the monomials in the witnessed sum, retaining repeated summands as
+ separate choices. -/
+ Choice : Type
+ choiceFintype : Fintype Choice
+ /-- Exponent of each label in the monomial selected by a given witness choice. -/
+ exponents : Choice → Label → ℕ
+ evaluates : ∑ p, labelMonomial κ (exponents p) = value
+
+attribute [instance] MonomialWitness.choiceFintype
+
+namespace MonomialWitness
+
+/-- Change only the proved value of an expansion, preserving the choice
+type and exponent function by definition. -/
+def changeValue {x y : A} (w : MonomialWitness κ x) (h : x = y) : MonomialWitness κ y where
+ Choice := w.Choice
+ choiceFintype := w.choiceFintype
+ exponents := w.exponents
+ evaluates := w.evaluates.trans h
+
+/-- All accepting local paths have unit weight before kernel substitution. -/
+def paths (κ : Label → A) (P : Type) [Fintype P] :
+ MonomialWitness κ (Fintype.card P : A) where
+ Choice := P
+ choiceFintype := inferInstance
+ exponents _ _ := 0
+ evaluates := by simp [labelMonomial]
+
+/-- A single successful local monomial. Its witness persists under every
+parameter specialization, including one sending the monomial to zero. -/
+def oneMonomial (κ : Label → A) (e : Label → ℕ) : MonomialWitness κ (labelMonomial κ e) where
+ Choice := Unit
+ choiceFintype := inferInstance
+ exponents _ := e
+ evaluates := by simp
+
+/-- A map entry that fails its syntactic checks has no witnesses. Passing
+the checks contributes its monomial even if that monomial evaluates to zero. -/
+def checked (κ : Label → A) (ok : Bool) (e : Label → ℕ) :
+ MonomialWitness κ (if ok then labelMonomial κ e else 0) := by
+ cases ok with
+ | false => simpa using paths κ Empty
+ | true => exact oneMonomial κ e
+
+/-- Disjointly enumerate a finite sum of local choices. -/
+noncomputable def sum {I : Type} [Fintype I] {f : I → A}
+ (w : ∀ i, MonomialWitness κ (f i)) : MonomialWitness κ (∑ i, f i) where
+ Choice := (i : I) × (w i).Choice
+ choiceFintype := inferInstance
+ exponents p := (w p.1).exponents p.2
+ evaluates := by simp only [Fintype.sum_sigma, MonomialWitness.evaluates]
+
+open scoped Classical in
+/-- Independent local choices multiply. Exponents accumulate coordinatewise. -/
+noncomputable def prod {I : Type} [Fintype I] {f : I → A}
+ (w : ∀ i, MonomialWitness κ (f i)) : MonomialWitness κ (∏ i, f i) where
+ Choice := (i : I) → (w i).Choice
+ choiceFintype := inferInstance
+ exponents p l := ∑ i, (w i).exponents (p i) l
+ evaluates := by
+ simp_rw [labelMonomial_accumulate κ]
+ rw [← Fintype.prod_sum (fun i p ↦ labelMonomial κ ((w i).exponents p))]
+ simp only [MonomialWitness.evaluates]
+
+/-- Combine witnesses of two successive factors of the path weight. -/
+noncomputable def mul {x y : A} (v : MonomialWitness κ x) (w : MonomialWitness κ y) :
+ MonomialWitness κ (x * y) where
+ Choice := v.Choice × w.Choice
+ choiceFintype := inferInstance
+ exponents p l := v.exponents p.1 l + w.exponents p.2 l
+ evaluates := by
+ rw [Fintype.sum_prod_type]
+ simp only [labelMonomial, pow_add, Finset.prod_mul_distrib]
+ simp only [← Finset.mul_sum, ← Finset.sum_mul]
+ exact congrArg₂ (· * ·) v.evaluates w.evaluates
+
+end MonomialWitness
+
+open scoped Classical in
+/-- Expand the hidden sums over absorbed fields in the local layout kernel.
+The local entry witnesses include the syntactic map-entry checks and their
+monomials. -/
+noncomputable def Layout.kernelWitness {N : Network} (L : Layout A N)
+ (W : ∀ v a h z, MonomialWitness κ (L.entry v a h z))
+ (v : L.output.Site) (a : Placed L.place N.Half v) (z : L.output.Half v) :
+ MonomialWitness κ (L.term.kernel v a z) :=
+ MonomialWitness.sum (fun h ↦ W v a h z)
+
+open scoped Classical in
+/-- Expand a single new vertex factor. Its choice records the old half-wires
+and witnesses only at old sites assigned to this vertex, together with the
+chosen witness for the new local kernel. -/
+noncomputable def Term.pushWitness {N : Network} (t : Term A N) (F : Factors A N)
+ (W : ∀ u b, MonomialWitness κ (F u b))
+ (K : ∀ v a z, MonomialWitness κ (t.kernel v a z)) (v : t.output.Site) (z : t.output.Half v) :
+ MonomialWitness κ (t.push F v z) := by
+ refine MonomialWitness.sum (fun a ↦ MonomialWitness.mul ?_ (K v a z))
+ have eqn : t.placedProduct F v a =
+ ∏ u : {u // v = t.place u}, F u.val (a u.val u.prop) :=
+ Finset.prod_congr_set {u | v = t.place u} _ _
+ (fun u h ↦ dite_eq_left h) (fun u h ↦ dite_eq_right h)
+ exact (MonomialWitness.prod
+ (fun (u : {u // v = t.place u}) ↦ W u.val (a u.val u.prop))).changeValue eqn.symm
+
+open scoped Classical in
+/-- Unpack a local history node into its hidden old indices, the independent
+children assigned to this vertex, and its own kernel witness. -/
+def Term.pushChoice {N : Network} (t : Term A N) (F : Factors A N)
+ (W : ∀ u b, MonomialWitness κ (F u b)) (K : ∀ v a z, MonomialWitness κ (t.kernel v a z))
+ (v : t.output.Site) (z : t.output.Half v) :
+ (t.pushWitness F W K v z).Choice ≃
+ (a : Placed t.place N.Half v) ×
+ ((u : {u // v = t.place u}) → (W u.val (a u.val u.prop)).Choice) × (K v a z).Choice :=
+ Equiv.refl _
+
+open scoped Classical in
+/-- Exponents at a local history node accumulate over precisely its own
+children and its kernel entry. -/
+@[simp] theorem Term.pushChoice_exponents {N : Network} (t : Term A N) (F : Factors A N)
+ (W : ∀ u b, MonomialWitness κ (F u b)) (K : ∀ v a z, MonomialWitness κ (t.kernel v a z))
+ (v : t.output.Site) (z : t.output.Half v) (a : Placed t.place N.Half v)
+ (children : (u : {u // v = t.place u}) → (W u.val (a u.val u.prop)).Choice)
+ (own : (K v a z).Choice) (l : Label) :
+ (t.pushWitness F W K v z).exponents ((t.pushChoice F W K v z).symm ⟨a, children, own⟩) l =
+ (∑ u, (W u.val (a u.val u.prop)).exponents (children u) l) + (K v a z).exponents own l := rfl
+
+namespace History
+
+/-- Finite local witnesses for every kernel that occurs in this history.
+A branch can have different sites, hidden fields and templates. -/
+def KernelWitnesses {N : Network} (κ : Label → A) : History A N → Type 1
+ | .stop => PUnit
+ | .branch s tail =>
+ (∀ i v a z, MonomialWitness κ ((s.term i).kernel v a z)) ×
+ ((i : s.Choice) → (tail i).KernelWitnesses κ)
+
+/-- Complete finite witnesses for a network contraction. First select all
+terms along the branch. After choosing one common value for each final edge,
+each final site expands its own local history independently. -/
+noncomputable def expandedWitness {N : Network} (H : History A N) (K : H.KernelWitnesses κ)
+ (F : Factors A N) (W : ∀ u b, MonomialWitness κ (F u b)) :
+ MonomialWitness κ (contract N F) := by
+ classical
+ induction H with
+ | @stop N =>
+ exact (MonomialWitness.sum (fun z ↦ MonomialWitness.prod
+ (fun u ↦ W u (WireTensor.edgeAssignment N.src N.dst z u)))).changeValue
+ (contract_edgeSum N F).symm
+ | @branch N s tail ih =>
+ exact (MonomialWitness.sum (fun i ↦ ih i (K.2 i) ((s.term i).push F)
+ ((s.term i).pushWitness F W (K.1 i)))).changeValue (s.contract_eq_sum F).symm
+
+open scoped Classical in
+/-- At a terminal branch choose the final edge payloads once, and one local
+history at each final vertex. -/
+def stopChoice {N : Network} (K : (stop (k := A) (N := N)).KernelWitnesses κ)
+ (F : Factors A N) (W : ∀ u b, MonomialWitness κ (F u b)) :
+ (stop.expandedWitness K F W).Choice ≃ (z : (e : N.Edge) → N.Payload e) ×
+ ((v : N.Site) → (W v (WireTensor.edgeAssignment N.src N.dst z v)).Choice) :=
+ Equiv.refl _
+
+open scoped Classical in
+@[simp] theorem stopChoice_exponents {N : Network} (K : (stop (k := A) (N := N)).KernelWitnesses κ)
+ (F : Factors A N) (W : ∀ u b, MonomialWitness κ (F u b)) (z : (e : N.Edge) → N.Payload e)
+ (p : (v : N.Site) → (W v (WireTensor.edgeAssignment N.src N.dst z v)).Choice) (l : Label) :
+ (stop.expandedWitness K F W).exponents ((stopChoice K F W).symm ⟨z, p⟩) l =
+ ∑ v, (W v (WireTensor.edgeAssignment N.src N.dst z v)).exponents (p v) l := rfl
+
+/-- At a branch, the selector chooses the new network and the rest of the
+choice belongs to that network's continuation. -/
+def branchChoice {N : Network} (s : Step A N) (tail : ∀ i, History A (s.term i).output)
+ (K : (branch s tail).KernelWitnesses κ) (F : Factors A N)
+ (W : ∀ u b, MonomialWitness κ (F u b)) :
+ ((branch s tail).expandedWitness K F W).Choice ≃
+ (i : s.Choice) × ((tail i).expandedWitness (K.2 i) ((s.term i).push F)
+ ((s.term i).pushWitness F W (K.1 i))).Choice :=
+ Equiv.refl _
+
+@[simp] theorem branchChoice_exponents {N : Network} (s : Step A N)
+ (tail : ∀ i, History A (s.term i).output)
+ (K : (branch s tail).KernelWitnesses κ) (F : Factors A N) (W : ∀ u b, MonomialWitness κ (F u b))
+ (i : s.Choice) (p : ((tail i).expandedWitness (K.2 i) ((s.term i).push F)
+ ((s.term i).pushWitness F W (K.1 i))).Choice) (l : Label) :
+ ((branch s tail).expandedWitness K F W).exponents ((branchChoice s tail K F W).symm ⟨i, p⟩) l =
+ ((tail i).expandedWitness (K.2 i) ((s.term i).push F)
+ ((s.term i).pushWitness F W (K.1 i))).exponents p l :=
+ rfl
+
+end History
+
+/-- Natural path counts can be transported to any commutative coefficient
+ring before expanding the kernels. -/
+theorem natCast_contract (N : Network) (F : Factors ℕ N) :
+ ((contract N F : ℕ) : A) = contract N (fun u a ↦ (F u a : A)) := by
+ simp only [contract_edgeSum, Nat.cast_sum, Nat.cast_prod]
+
+/-- Equation (12.2) for a compressed network of local path counts. Its left
+side enumerates local paths explicitly, including distinct paths that have
+the same exponent vector. -/
+noncomputable def History.expandedCount {N : Network} (H : History A N)
+ (K : H.KernelWitnesses κ) (P : ∀ u, N.Half u → Type) [∀ u b, Fintype (P u b)] :
+ MonomialWitness κ ((contract N (fun u b ↦ Fintype.card (P u b)) : ℕ) : A) :=
+ (H.expandedWitness K _ (fun u b ↦ MonomialWitness.paths κ (P u b))).changeValue
+ (natCast_contract (A := A) N _).symm
+
+end NetworkKernel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/NormRigidity.lean b/lean/OAI/Computability/VPVNP/NormRigidity.lean
new file mode 100644
index 0000000000..04ef22b2f7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/NormRigidity.lean
@@ -0,0 +1,475 @@
+import OAI.Computability.VPVNP.CrossingSpectralBound
+import OAI.Computability.VPVNP.SpectralRealizable
+import Mathlib.Analysis.Calculus.Deriv.Slope
+import Mathlib.Analysis.Calculus.FDeriv.Norm
+import Mathlib.Analysis.Calculus.Rademacher
+import Mathlib.Analysis.InnerProductSpace.OfNorm
+import Mathlib.Tactic.Linarith
+
+/-!
+# Norm rigidity from the shifted crossing
+
+The two flattening bounds in Theorem 3.1 give a geometric inequality on the
+cost of placing the auxiliary wire endpoints. This file derives Lemma 3.2's
+inner-product conclusion from that inequality. If the dual quadratic bound
+fails at smooth points, both costs strictly decrease along suitable directions.
+Dense differentiability of the norm supplies supporting functionals and extends
+the estimate to arbitrary vectors.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace NormRigidity
+
+open Filter
+open scoped Topology
+
+variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E]
+
+/-- The norm's derivative at the opposite vector is the opposite functional. -/
+theorem norm_deriv_neg {y : E} {g : E →L[ℝ] ℝ} (hg : HasFDerivAt (‖·‖) g y) :
+ HasFDerivAt (‖·‖) (-g) (-y) := by
+ simpa using hg.hasFDerivAt_norm_smul_neg (show (-1 : ℝ) < 0 by norm_num)
+
+private theorem normAlongMotion {x z : E} {f : E →L[ℝ] ℝ}
+ (hf : HasFDerivAt (‖·‖) f x) :
+ HasDerivAt (fun ε : ℝ => ‖x - ε • z‖) (-f z) 0 := by
+ have hl : HasDerivAt (fun ε : ℝ => x - ε • z) (-z) 0 := by
+ simpa using ((hasDerivAt_id' (0 : ℝ)).smul_const z).const_sub x
+ simpa [Function.comp_def] using hf.comp_hasDerivAt_of_eq (0 : ℝ) hl (by simp)
+
+/-- A negative derivative at zero forces a decrease for every sufficiently
+small positive step, without any derivative assumptions away from zero. -/
+theorem eventually_lt_of_deriv_neg {F : ℝ → ℝ} {d : ℝ}
+ (hF : HasDerivAt F d 0) (hd : d < 0) :
+ ∀ᶠ ε in 𝓝[>] (0 : ℝ), F ε < F 0 := by
+ filter_upwards [hF.tendsto_slope_zero_right.eventually (eventually_lt_nhds hd),
+ self_mem_nhdsWithin] with ε hε hpos
+ have hpos' : 0 < ε := hpos
+ simp only [zero_add, smul_eq_mul] at hε
+ by_contra! hle
+ exact hε.not_ge (mul_nonneg (inv_nonneg.mpr hpos'.le) (sub_nonneg.mpr hle))
+
+/-- A common movement of two endpoints decreases their weighted lengths even
+after paying the linear cost for the new segment. -/
+theorem weighted_norm_motion {x y : E} {f g : E →L[ℝ] ℝ}
+ (hf : HasFDerivAt (‖·‖) f x) (hg : HasFDerivAt (‖·‖) g y)
+ {t u b : ℝ} {z : E} (hlt : b * ‖z‖ < (t • f + u • g) z) :
+ ∀ᶠ ε in 𝓝[>] (0 : ℝ),
+ t * ‖x - ε • z‖ + u * ‖y - ε • z‖ + ε * b * ‖z‖ < t * ‖x‖ + u * ‖y‖ := by
+ have hF := (((normAlongMotion (z := z) hf).const_mul t).add
+ ((normAlongMotion (z := z) hg).const_mul u)).add
+ (((hasDerivAt_id' (0 : ℝ)).mul_const b).mul_const ‖z‖)
+ have hd : t * (-f z) + u * (-g z) + 1 * b * ‖z‖ < 0 := by
+ simp only [add_apply, smul_apply, smul_eq_mul] at hlt
+ linarith
+ simpa using eventually_lt_of_deriv_neg hF hd
+
+section
+
+variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [FiniteDimensional ℝ E]
+
+/-- Norm derivatives approximate the norm from below in every direction. -/
+theorem exists_norm_derivative_approx (x : E) {ε : ℝ} (hε : 0 < ε) :
+ ∃ (z : E) (f : E →L[ℝ] ℝ), HasFDerivAt (‖·‖) f z ∧
+ f z = ‖z‖ ∧ ‖f‖ ≤ 1 ∧ ‖x‖ - ε ≤ f x := by
+ obtain ⟨z, hz, hxz⟩ := (dense_differentiableAt_norm (E := E)).exists_dist_lt x (half_pos hε)
+ change DifferentiableAt ℝ (‖·‖) z at hz
+ let f := fderiv ℝ (fun v : E => ‖v‖) z
+ have hf : ‖f‖ ≤ 1 := NNReal.coe_one ▸
+ norm_fderiv_le_of_lipschitz ℝ (x₀ := z) lipschitzWith_one_norm
+ refine ⟨z, f, hz.hasFDerivAt, hz.fderiv_norm_self, hf, ?_⟩
+ have hfxz : f z - f x ≤ ‖z - x‖ := calc
+ f z - f x = f (z - x) := (map_sub f z x).symm
+ _ ≤ ‖f (z - x)‖ := _root_.le_abs_self _
+ _ ≤ ‖f‖ * ‖z - x‖ := f.le_opNorm _
+ _ ≤ 1 * ‖z - x‖ := mul_le_mul_of_nonneg_right hf (norm_nonneg _)
+ _ = _ := one_mul _
+ have hnxz : ‖x‖ - ‖z‖ ≤ ‖x - z‖ := norm_sub_norm_le x z
+ rw [norm_sub_rev] at hfxz
+ have hfz : f z = ‖z‖ := hz.fderiv_norm_self
+ rw [dist_eq_norm] at hxz
+ linarith
+
+end
+
+/-- The two crossing cuts use opposite partners at the terminal marked by `y`.
+The central-wire costs are the two square roots in Theorem 3.1. -/
+def CrossingPlacement (E : Type*) [NormedAddCommGroup E] : Prop :=
+ ∀ (x y zp zm : E) (t u δ : ℝ), 0 < t → 0 < u →
+ -(t^2 + u^2) < δ → δ < t^2 + u^2 →
+ t * ‖x‖ + u * ‖y‖ ≤ max
+ (t * ‖x - zp‖ + u * ‖y - zp‖ + Real.sqrt (t^2 + u^2 + δ) * ‖zp‖)
+ (t * ‖x - zm‖ + u * ‖-y - zm‖ + Real.sqrt (t^2 + u^2 - δ) * ‖zm‖)
+
+private theorem witness_of_lt_norm (F : E →L[ℝ] ℝ) (c : ℝ) (hc : 0 ≤ c) (hF : c < ‖F‖) :
+ ∃ z : E, c * ‖z‖ < F z := by
+ by_contra! hall
+ apply (not_lt_of_ge (F.opNorm_le_bound hc ?_)) hF
+ intro z
+ rw [Real.norm_eq_abs, abs_le]
+ have hn := hall (-z)
+ rw [map_neg, norm_neg] at hn
+ exact ⟨by linarith, hall z⟩
+
+private theorem choose_displacement {S A B : ℝ} (hA : 0 ≤ A)
+ (hB : 0 ≤ B) (hA₂ : A^2 ≤ 2*S) (hB₂ : B^2 ≤ 2*S)
+ (hbad : 2*S < A^2 + B^2) :
+ ∃ δ : ℝ, -S < δ ∧ δ < S ∧ Real.sqrt (S+δ) < A ∧ Real.sqrt (S-δ) < B := by
+ let δ := (A^2 - B^2) / 2
+ have h₁ : -S < δ := by dsimp [δ]; linarith
+ have h₂ : δ < S := by dsimp [δ]; linarith
+ refine ⟨δ, h₁, h₂, ?_, ?_⟩
+ · apply (Real.sqrt_lt' (by nlinarith : 0 < A)).mpr
+ dsimp [δ]
+ linarith
+ · apply (Real.sqrt_lt' (by nlinarith : 0 < B)).mpr
+ dsimp [δ]
+ linarith
+
+private theorem norm_smul_le_scalar (f : E →L[ℝ] ℝ) {t : ℝ} (ht : 0 ≤ t) (hf : ‖f‖ ≤ 1) :
+ ‖t • f‖ ≤ t := by
+ rw [norm_smul, Real.norm_eq_abs, abs_of_nonneg ht]
+ simpa using (mul_le_mul_of_nonneg_left hf ht)
+
+/-- A strict failure of the dual norm inequality yields simultaneous strict descent
+directions for the two crossing costs. -/
+theorem crossing_descent_directions (f g : E →L[ℝ] ℝ) {t u : ℝ} (ht : 0 < t) (hu : 0 < u)
+ (hf : ‖f‖ ≤ 1) (hg : ‖g‖ ≤ 1)
+ (hbad : 2 * (t^2 + u^2) < ‖t • f + u • g‖^2 + ‖t • f - u • g‖^2) :
+ ∃ (δ : ℝ) (zp zm : E), -(t^2+u^2) < δ ∧ δ < t^2+u^2 ∧
+ Real.sqrt (t^2+u^2+δ)*‖zp‖ < (t • f + u • g) zp ∧
+ Real.sqrt (t^2+u^2-δ)*‖zm‖ < (t • f - u • g) zm := by
+ have hn := add_le_add (norm_smul_le_scalar f ht.le hf) (norm_smul_le_scalar g hu.le hg)
+ have hquad : (t+u)^2 ≤ 2*(t^2+u^2) := by nlinarith only [sq_nonneg (t-u)]
+ have hplus : ‖t • f + u • g‖ ≤ t+u := (norm_add_le _ _).trans hn
+ have hminus : ‖t • f - u • g‖ ≤ t+u := (norm_sub_le _ _).trans hn
+ obtain ⟨δ, hδl, hδr, hp, hm⟩ := choose_displacement (norm_nonneg _) (norm_nonneg _)
+ ((pow_le_pow_left₀ (norm_nonneg _) hplus 2).trans hquad)
+ ((pow_le_pow_left₀ (norm_nonneg _) hminus 2).trans hquad) hbad
+ obtain ⟨zp, hzp⟩ := witness_of_lt_norm _ _ (Real.sqrt_nonneg _) hp
+ obtain ⟨zm, hzm⟩ := witness_of_lt_norm _ _ (Real.sqrt_nonneg _) hm
+ exact ⟨δ, zp, zm, hδl, hδr, hzp, hzm⟩
+
+/-- A placement satisfying the crossing inequality forces the dual quadratic
+estimate on any two derivatives of the norm, as in equation (3.1). -/
+theorem dual_bound_of_placement (hp : CrossingPlacement E) (x y : E)
+ (f g : E →L[ℝ] ℝ) (hf : HasFDerivAt (‖·‖) f x) (hg : HasFDerivAt (‖·‖) g y)
+ (hf' : ‖f‖ ≤ 1) (hg' : ‖g‖ ≤ 1) {t u : ℝ} (ht : 0 ≤ t) (hu : 0 ≤ u) :
+ ‖t • f + u • g‖^2 + ‖t • f - u • g‖^2 ≤ 2 * (t^2 + u^2) := by
+ rcases ht.eq_or_lt with h | ht
+ · subst t
+ have hle := pow_le_pow_left₀ (norm_nonneg _) (norm_smul_le_scalar g hu hg') 2
+ simpa only [zero_smul, zero_add, zero_sub, norm_neg, zero_pow (by decide : 2 ≠ 0), two_mul]
+ using add_le_add hle hle
+ rcases hu.eq_or_lt with h | hu
+ · subst u
+ have hle := pow_le_pow_left₀ (norm_nonneg _) (norm_smul_le_scalar f ht.le hf') 2
+ simpa only [zero_smul, add_zero, sub_zero, zero_pow (by decide : 2 ≠ 0), two_mul]
+ using add_le_add hle hle
+ by_contra! hbad
+ obtain ⟨δ, zp, zm, hδl, hδr, hz, hw⟩ := crossing_descent_directions f g ht hu hf' hg' hbad
+ have hw' : √(t^2 + u^2 - δ) * ‖zm‖ < (t • f + u • (-g)) zm := by
+ simpa [sub_eq_add_neg] using hw
+ have hnear : ∀ᶠ ε in 𝓝[>] (0 : ℝ), 0 < ε := self_mem_nhdsWithin
+ obtain ⟨ε, hε, hplus, hminus⟩ :=
+ (hnear.and ((weighted_norm_motion hf hg hz).and
+ (weighted_norm_motion hf (norm_deriv_neg hg) hw'))).exists
+ have hpos : 0 < ε := hε
+ have hplacement := hp x y (ε • zp) (ε • zm) t u δ ht hu hδl hδr
+ simp only [norm_smul, Real.norm_eq_abs, abs_of_pos hpos] at hplacement
+ rw [norm_neg] at hminus
+ rw [le_max_iff] at hplacement
+ rcases hplacement with h | h <;> linarith
+
+section
+
+private theorem eval_le_squares (f : E →L[ℝ] ℝ) (x : E) :
+ f x ≤ ‖f‖ ^ 2 / 4 + ‖x‖ ^ 2 := by
+ have h := (le_abs_self (f x)).trans (f.le_opNorm x)
+ nlinarith only [h, sq_nonneg (‖f‖ - 2 * ‖x‖)]
+
+variable (D : Set (E →L[ℝ] ℝ))
+ (hD : ∀ x : E, ∀ ε : ℝ, 0 < ε → ∃ f ∈ D, ‖f‖ ≤ 1 ∧ ‖x‖ - ε ≤ f x)
+ (hdual : ∀ f ∈ D, ∀ g ∈ D, ∀ t u : ℝ, 0 ≤ t → 0 ≤ u →
+ ‖t • f + u • g‖ ^ 2 + ‖t • f - u • g‖ ^ 2 ≤ 2 * (t ^ 2 + u ^ 2))
+
+include hD hdual in
+/-- The two dual combinations bound the weighted evaluations at `a + b` and `a - b`.
+Approximate support functionals then give the upper half of the parallelogram law. -/
+theorem parallelogram_le_of_dual_bound (a b : E) :
+ ‖a + b‖ ^ 2 + ‖a - b‖ ^ 2 ≤ 2 * (‖a‖ ^ 2 + ‖b‖ ^ 2) := by
+ let t := ‖a + b‖
+ let u := ‖a - b‖
+ have ht : 0 ≤ t := norm_nonneg _
+ have hu : 0 ≤ u := norm_nonneg _
+ change t ^ 2 + u ^ 2 ≤ _
+ refine le_of_forall_pos_le_add fun ε hε ↦ ?_
+ let δ := ε / (2 * (t + u) + 1)
+ have hpos : 0 < 2 * (t + u) + 1 := by linarith
+ have hδ : 0 < δ := div_pos hε hpos
+ have hscale : δ * (2 * (t + u) + 1) = ε := div_mul_cancel₀ ε hpos.ne'
+ obtain ⟨f, hf, _, hfx⟩ := hD (a + b) δ hδ
+ obtain ⟨g, hg, _, hgy⟩ := hD (a - b) δ hδ
+ change t - δ ≤ f (a + b) at hfx
+ change u - δ ≤ g (a - b) at hgy
+ have happrox := add_le_add (mul_le_mul_of_nonneg_left hfx ht)
+ (mul_le_mul_of_nonneg_left hgy hu)
+ have heval := add_le_add (eval_le_squares (t • f + u • g) a)
+ (eval_le_squares (t • f - u • g) b)
+ simp only [map_add, map_sub] at happrox
+ simp only [add_apply, sub_apply,
+ smul_apply, smul_eq_mul] at heval
+ linarith only [happrox, heval, hdual f hf g hg t u ht hu, hscale, hδ]
+
+include hD hdual in
+/-- Applying the upper parallelogram estimate to the sum and difference gives equality. -/
+theorem parallelogram_of_dual_bound (a b : E) :
+ ‖a + b‖ ^ 2 + ‖a - b‖ ^ 2 = 2 * (‖a‖ ^ 2 + ‖b‖ ^ 2) := by
+ apply le_antisymm (parallelogram_le_of_dual_bound D hD hdual a b)
+ have h := parallelogram_le_of_dual_bound D hD hdual (a + b) (a - b)
+ have ha : a + b + (a - b) = (2 : ℝ) • a := by rw [two_smul]; abel
+ have hb : a + b - (a - b) = (2 : ℝ) • b := by rw [two_smul]; abel
+ rw [ha, hb, norm_smul, norm_smul] at h
+ norm_num at h
+ linarith only [h]
+
+include hD hdual in
+/-- The real norm comes from an inner product whenever its approximate support
+functionals satisfy the dual estimate (3.1). -/
+theorem innerProduct_of_dual_bound : Nonempty (InnerProductSpace ℝ E) := by
+ exact ⟨InnerProductSpace.ofNorm ℝ fun a b ↦ by
+ simpa only [sq] using parallelogram_of_dual_bound D hD hdual a b⟩
+
+end
+
+/-- The geometric implication of Lemma 3.2. In a finite-dimensional real
+space the two crossing placement costs force the given norm to be Euclidean. -/
+theorem innerProduct_of_placement [FiniteDimensional ℝ E] (hp : CrossingPlacement E) :
+ Nonempty (InnerProductSpace ℝ E) := by
+ let D : Set (E →L[ℝ] ℝ) := {f | ‖f‖ ≤ 1 ∧ ∃ x, HasFDerivAt (‖·‖) f x}
+ apply innerProduct_of_dual_bound D
+ · intro v ε hε
+ obtain ⟨z, f, hz, _, hf, hv⟩ := exists_norm_derivative_approx v hε
+ exact ⟨f, ⟨hf, z, hz⟩, hf, hv⟩
+ · rintro f ⟨hf, x, hx⟩ g ⟨hg, y, hy⟩ t u ht hu
+ exact dual_bound_of_placement hp x y f g hx hy hf hg ht hu
+
+/-- The cost of adding two tensor summands contributes at most one bit beyond
+the larger base-two exponent. -/
+theorem exponent_le_max_add_one {A P Q : ℝ}
+ (h : (2 : ℝ)^A ≤ (2 : ℝ)^P + (2 : ℝ)^Q) : A ≤ max P Q + 1 := by
+ apply (Real.rpow_le_rpow_left_iff (show (1 : ℝ) < 2 by norm_num)).mp
+ calc
+ (2 : ℝ)^A ≤ (2 : ℝ)^P + (2 : ℝ)^Q := h
+ _ ≤ (2 : ℝ)^(max P Q) + (2 : ℝ)^(max P Q) := add_le_add
+ ((Real.rpow_le_rpow_left_iff (by norm_num)).mpr (le_max_left P Q))
+ ((Real.rpow_le_rpow_left_iff (by norm_num)).mpr (le_max_right P Q))
+ _ = (2 : ℝ)^(max P Q + 1) := by rw [Real.rpow_add_one (by norm_num)]; ring
+
+/-- For two exponentially scaled wire costs, subadditivity implies that the
+target rate is bounded by the larger limiting cost. -/
+theorem limit_le_max_of_two_powers {A P Q : ℕ → ℝ} {a p q : ℝ}
+ (hA : Tendsto A atTop (𝓝 a)) (hP : Tendsto P atTop (𝓝 p)) (hQ : Tendsto Q atTop (𝓝 q))
+ (h : ∀ᶠ n : ℕ in atTop, (2 : ℝ)^((n : ℝ) * A n) ≤
+ (2 : ℝ)^((n : ℝ) * P n) + (2 : ℝ)^((n : ℝ) * Q n)) : a ≤ max p q := by
+ have hlim : Tendsto (fun n : ℕ => max (P n) (Q n) + 1 / n) atTop (𝓝 (max p q)) := by
+ simpa using (hP.max hQ).add (tendsto_const_div_atTop_nhds_zero_nat (1 : ℝ))
+ apply le_of_tendsto_of_tendsto hA hlim
+ filter_upwards [h, eventually_gt_atTop (0 : ℕ)] with n hn hnpos
+ have hn' : 0 < (n : ℝ) := by exact_mod_cast hnpos
+ have hbound := exponent_le_max_add_one hn
+ rw [← mul_max_of_nonneg _ _ hn'.le] at hbound
+ apply (mul_le_mul_iff_right₀ hn').mp
+ rwa [mul_add, mul_one_div_cancel hn'.ne']
+
+private theorem pow_scaled_log_rate {n : ℕ} {d : ℝ} (hn : 0 < n) (hd : 0 < d) (c : ℝ) :
+ (2 : ℝ)^((n : ℝ) * (c * (Real.logb 2 d / n))) = d^c := by
+ have hn' : (n : ℝ) ≠ 0 := by exact_mod_cast hn.ne'
+ rw [show (n : ℝ) * (c * (Real.logb 2 d / n)) = Real.logb 2 d * c by field_simp]
+ rw [Real.rpow_mul (by norm_num), Real.rpow_logb (by norm_num) (by norm_num) hd]
+
+/-- The four-terminal wire inequality at a common realization scale. The
+two original wires have terminal-to-terminal lengths `2*x0` and `2*y0`. In each placement
+the terminal links have lengths `xp,yp` or `xm,ym` and the two centers have
+distances `2*ep` and `2*em`. The two crossing ranks may have different exponential rates. -/
+theorem crossingPlacement_cost_limit {X Y Rplus Rminus : ℕ → ℕ}
+ {t u rp rm σ x0 y0 ep em xp yp xm ym : ℝ} (hσ : 0 < σ)
+ (hX : Tendsto (fun n : ℕ => Real.logb 2 (X n) / n) atTop (𝓝 t))
+ (hY : Tendsto (fun n : ℕ => Real.logb 2 (Y n) / n) atTop (𝓝 u))
+ (hp : Tendsto (fun n : ℕ => Real.logb 2 (Rplus n) / n) atTop (𝓝 rp))
+ (hm : Tendsto (fun n : ℕ => Real.logb 2 (Rminus n) / n) atTop (𝓝 rm))
+ (hpos : ∀ᶠ n in atTop, 0 < X n ∧ 0 < Y n ∧ 0 < Rplus n ∧ 0 < Rminus n)
+ (hcost : ∀ᶠ n in atTop,
+ (X n : ℝ)^(2*σ*x0) * (Y n : ℝ)^(2*σ*y0) ≤
+ (X n : ℝ)^(2*σ*xp) * (Y n : ℝ)^(2*σ*yp) * (Rplus n : ℝ)^(2*σ*ep) +
+ (X n : ℝ)^(2*σ*xm) * (Y n : ℝ)^(2*σ*ym) * (Rminus n : ℝ)^(2*σ*em)) :
+ t * x0 + u * y0 ≤ max (t * xp + u * yp + ep * rp) (t * xm + u * ym + em * rm) := by
+ have bound := limit_le_max_of_two_powers
+ ((hX.const_mul (2*σ*x0)).add (hY.const_mul (2*σ*y0)))
+ (((hX.const_mul (2*σ*xp)).add (hY.const_mul (2*σ*yp))).add (hp.const_mul (2*σ*ep)))
+ (((hX.const_mul (2*σ*xm)).add (hY.const_mul (2*σ*ym))).add (hm.const_mul (2*σ*em))) (by
+ filter_upwards [hpos, hcost, eventually_gt_atTop (0 : ℕ)] with n hn hc hnpos
+ obtain ⟨hx, hy, hplus, hminus⟩ := hn
+ have hx' : 0 < (X n : ℝ) := by exact_mod_cast hx
+ have hy' : 0 < (Y n : ℝ) := by exact_mod_cast hy
+ have hp' : 0 < (Rplus n : ℝ) := by exact_mod_cast hplus
+ have hm' : 0 < (Rminus n : ℝ) := by exact_mod_cast hminus
+ simpa only [Pi.add_apply, Pi.mul_apply, Function.comp_apply, mul_add,
+ Real.rpow_add (show (0 : ℝ) < 2 by norm_num), pow_scaled_log_rate hnpos hx',
+ pow_scaled_log_rate hnpos hy', pow_scaled_log_rate hnpos hp', pow_scaled_log_rate hnpos hm']
+ using hc)
+ apply (mul_le_mul_iff_right₀ (show 0 < 2*σ by positivity)).mp
+ rw [mul_max_of_nonneg _ _ (show 0 ≤ 2*σ by positivity)]
+ ring_nf at bound ⊢
+ exact bound
+
+/-- The spectral inequality for the two placements of a finite, integer crossing.
+The shared scale belongs to the realization of the eight points. -/
+def FiniteCrossingCost (x y zp zm : E) (σ : ℝ) : Prop :=
+ ∀ {X Y P M : ℕ}, 0 < X → 0 < Y → 0 < P → 0 < M →
+ Crossing.IntegralCrossing X Y P M →
+ (X : ℝ)^(2*σ*‖x‖) * (Y : ℝ)^(2*σ*‖y‖) ≤
+ (X : ℝ)^(2*σ*‖x-zp‖) * (Y : ℝ)^(2*σ*‖y-zp‖) * (P : ℝ)^(2*σ*‖zp‖) +
+ (X : ℝ)^(2*σ*‖x-zm‖) * (Y : ℝ)^(2*σ*‖-y-zm‖) * (M : ℝ)^(2*σ*‖zm‖)
+
+private theorem eventually_pos_of_log_rate {D : ℕ → ℕ} {d : ℝ} (hd : 0 < d)
+ (hD : Tendsto (fun n : ℕ => Real.logb 2 (D n) / n) atTop (𝓝 d)) :
+ ∀ᶠ n in atTop, 0 < D n := by
+ filter_upwards [hD.eventually_const_lt hd] with n hn
+ by_contra! h
+ rw [Nat.le_zero.mp h] at hn
+ simp at hn
+
+omit [NormedSpace ℝ E] in
+/-- Theorem 3.1 turns the finite wire-cost inequality at one common realization
+scale into the two geometric placement costs of Lemma 3.2. -/
+theorem crossingPlacement_of_finiteCosts
+ (hcost : ∀ x y zp zm : E, ∃ σ : ℝ, 0 < σ ∧ FiniteCrossingCost x y zp zm σ) :
+ CrossingPlacement E := by
+ intro x y zp zm t u δ ht hu hδl hδr
+ obtain ⟨σ, hσ, hwire⟩ := hcost x y zp zm
+ obtain ⟨X, Y, P, M, hX, hY, hP, hM, hfactors⟩ := Crossing.shiftedCrossing t u δ ht hu hδl hδr
+ have hpos := (eventually_pos_of_log_rate ht hX).and ((eventually_pos_of_log_rate hu hY).and
+ ((eventually_pos_of_log_rate (Real.sqrt_pos.mpr (by linarith)) hP).and
+ (eventually_pos_of_log_rate (Real.sqrt_pos.mpr (by linarith)) hM)))
+ have h := crossingPlacement_cost_limit (x0 := ‖x‖) (y0 := ‖y‖) (ep := ‖zp‖) (em := ‖zm‖)
+ (xp := ‖x-zp‖) (yp := ‖y-zp‖) (xm := ‖x-zm‖) (ym := ‖-y-zm‖) hσ hX hY hP hM hpos (by
+ filter_upwards [hpos] with n ⟨hx, hy, hp, hm⟩
+ exact hwire hx hy hp hm (hfactors n).some)
+ simpa only [mul_comm ‖zp‖, mul_comm ‖zm‖] using h
+
+/-- A translate of one positive rescaling of a finite configuration lies
+entirely in any prescribed nonempty open set. -/
+theorem exists_homothety_mem {ι : Type*} [Finite ι] (p : ι → E) {U : Set E}
+ (hU : IsOpen U) (hU' : U.Nonempty) :
+ ∃ c : E, ∃ r : ℝ, 0 < r ∧ ∀ i, c + r • p i ∈ U := by
+ obtain ⟨c, hc⟩ := hU'
+ have hi (i : ι) : ∀ᶠ r in 𝓝[>] (0 : ℝ), c + r • p i ∈ U := by
+ have hcont : Continuous (fun r : ℝ => c + r • p i) :=
+ continuous_const.add (continuous_id.smul continuous_const)
+ have hlim : Tendsto (fun r : ℝ => c + r • p i) (𝓝[>] (0 : ℝ)) (𝓝 c) := by
+ simpa [ContinuousWithinAt] using hcont.continuousWithinAt (s := Set.Ioi (0 : ℝ)) (x := 0)
+ exact hlim.eventually (hU.mem_nhds hc)
+ have hpos : ∀ᶠ r in 𝓝[>] (0 : ℝ), 0 < r := self_mem_nhdsWithin
+ obtain ⟨r, hr, hp⟩ := (hpos.and (eventually_all.mpr hi)).exists
+ exact ⟨c, r, hr, hp⟩
+
+/-- A translated positive rescaling multiplies every pair distance by its scale. -/
+theorem dist_homothety (c x y : E) {r : ℝ} (hr : 0 ≤ r) :
+ dist (c + r • x) (c + r • y) = r * dist x y := by
+ simp [dist_smul₀, Real.norm_of_nonneg hr]
+
+/-- The two possible placements use eight roles. Roles 0 and 1 are the endpoints
+of the first wire, 2 and 3 those of the second wire, and the last four are the
+two pairs of auxiliary centers. The distances may vanish between distinct roles. -/
+def EightPointCrossingCost (d : Fin 8 → Fin 8 → ℝ) : Prop :=
+ ∀ {X Y P M : ℕ}, 0 < X → 0 < Y → 0 < P → 0 < M → Crossing.IntegralCrossing X Y P M →
+ (X : ℝ)^(d 0 1) * (Y : ℝ)^(d 2 3) ≤
+ (X : ℝ)^(d 0 4 + d 1 5) * (Y : ℝ)^(d 2 4 + d 3 5) * (P : ℝ)^(d 4 5) +
+ (X : ℝ)^(d 0 6 + d 1 7) * (Y : ℝ)^(d 3 6 + d 2 7) * (M : ℝ)^(d 6 7)
+
+private theorem dist_to_neg (x : E) : dist x (-x) = 2 * ‖x‖ := by
+ rw [dist_eq_norm, sub_neg_eq_add, ← two_smul ℝ x, norm_smul]
+ norm_num
+
+/-- From scaled spectral costs on every finite configuration in an open set,
+obtain the two placement inequalities on the whole normed space. -/
+theorem placement_of_local_costs {U : Set E} (hU : IsOpen U) (hne : U.Nonempty)
+ (hcost : ∀ p : Fin 8 → E, (∀ i, p i ∈ U) →
+ ∃ σ : ℝ, 0 < σ ∧ EightPointCrossingCost (fun i j => σ * dist (p i) (p j))) :
+ CrossingPlacement E := by
+ apply crossingPlacement_of_finiteCosts
+ intro x y zp zm
+ let p : Fin 8 → E := ![x, -x, y, -y, zp, -zp, zm, -zm]
+ obtain ⟨c, r, hr, hc⟩ := exists_homothety_mem p hU hne
+ obtain ⟨σ, hσ, hp⟩ := hcost (fun i => c + r • p i) hc
+ refine ⟨σ*r, mul_pos hσ hr, ?_⟩
+ intro X Y P M hx hy hP hM factor
+ have hh := hp hx hy hP hM factor
+ simp only [dist_homothety c _ _ hr.le] at hh
+ change (X : ℝ)^(σ*(r*dist x (-x))) * (Y : ℝ)^(σ*(r*dist y (-y))) ≤
+ (X : ℝ)^(σ*(r*dist x zp)+σ*(r*dist (-x) (-zp))) *
+ (Y : ℝ)^(σ*(r*dist y zp)+σ*(r*dist (-y) (-zp))) * (P : ℝ)^(σ*(r*dist zp (-zp))) +
+ (X : ℝ)^(σ*(r*dist x zm)+σ*(r*dist (-x) (-zm))) *
+ (Y : ℝ)^(σ*(r*dist (-y) zm)+σ*(r*dist y (-zm))) * (M : ℝ)^(σ*(r*dist zm (-zm))) at hh
+ have hflip : dist y (-zm) = dist (-y) zm := by simpa using (dist_neg_neg y (-zm)).symm
+ simp only [dist_to_neg, dist_neg_neg, hflip] at hh
+ simp only [dist_eq_norm] at hh
+ convert hh using 1 <;> ring_nf
+
+/-- A finite-dimensional norm is Euclidean if some nonempty open set satisfies
+the two finite crossing costs at a common scale for every eight-point configuration. -/
+theorem innerProduct_of_local_costs [FiniteDimensional ℝ E] {U : Set E}
+ (hU : IsOpen U) (hne : U.Nonempty)
+ (hcost : ∀ p : Fin 8 → E, (∀ i, p i ∈ U) →
+ ∃ σ : ℝ, 0 < σ ∧ EightPointCrossingCost (fun i j => σ * dist (p i) (p j))) :
+ Nonempty (InnerProductSpace ℝ E) :=
+ innerProduct_of_placement (placement_of_local_costs hU hne hcost)
+
+/-- A spectral point bounds the finite cost at any eight labelled tensor parties. -/
+theorem eightPointCost_of_spectrum {k J : Type*} [Field k] [Fintype J]
+ (F : WireTensor.SpectralPoint k J) (label : Fin 8 → J) :
+ EightPointCrossingCost (fun i j => F.wireDistance (label i) (label j)) := by
+ intro X Y P M hx hy hp hm f
+ let term : Crossing.Terminal → J :=
+ Sum.elim (fun b => if b then label 1 else label 0) (fun b => if b then label 3 else label 2)
+ let cp := fun b : Bool => if b then label 5 else label 4
+ let cm := fun b : Bool => if b then label 7 else label 6
+ exact Crossing.crossing_spectral_inequality F term cp cm hx hy hp hm f
+
+/-- Lemma 3.2. If each finite subset of a nonempty open set in a real normed
+space is realized up to scale by spectral wires over the fixed field, the
+space's norm comes from an inner product. The proof works in every finite
+dimension, including the real normed planes of the lemma. -/
+theorem norm_rigidity (k : Type*) [Field k] [FiniteDimensional ℝ E]
+ {U : Set E} (hU : IsOpen U) (hUn : U.Nonempty)
+ (h : ∀ S : Finset E, (↑S : Set E) ⊆ U →
+ WireTensor.RealizableUpToScale k (fun i j : S => dist i.val j.val)) :
+ Nonempty (InnerProductSpace ℝ E) := by
+ classical
+ apply innerProduct_of_local_costs hU hUn
+ intro p hp
+ let S : Finset E := Finset.univ.image p
+ have hSU : (↑S : Set E) ⊆ U := by
+ intro x hx
+ obtain ⟨i, _, rfl⟩ := Finset.mem_image.mp hx
+ exact hp i
+ let l : Fin 8 → S := fun i => ⟨p i, Finset.mem_image_of_mem p (Finset.mem_univ _)⟩
+ obtain ⟨w⟩ := (h S hSU).relabel l
+ refine ⟨w.scale⁻¹, inv_pos.mpr w.scale_pos, ?_⟩
+ have hd (i j : Fin 8) : w.scale⁻¹ * dist (p i) (p j) = w.spectrum.wireDistance (w.label i) (w.label j) := by
+ have hd' : dist (p i) (p j) = w.scale * w.spectrum.wireDistance (w.label i) (w.label j) :=
+ w.distances i j
+ rw [hd', inv_mul_cancel_left₀ w.scale_pos.ne']
+ simp only [hd]
+ intro X Y P M hx hy hp hm f
+ exact eightPointCost_of_spectrum w.spectrum w.label hx hy hp hm f
+
+end NormRigidity
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Normalization.lean b/lean/OAI/Computability/VPVNP/Normalization.lean
new file mode 100644
index 0000000000..4f8d497f60
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Normalization.lean
@@ -0,0 +1,132 @@
+import Mathlib.Analysis.SpecialFunctions.Pow.Asymptotics
+import Mathlib.Data.Nat.Choose.Sum
+
+/-!
+# Additivity under subparty normalization
+
+The direct-sum expansion on a subset of parties in Lemma 2.3 of *VP and VNP
+differ over every field* has `m + 1` binomial groups. Bounding each group by
+the whole expansion and the whole expansion by the sum of group values
+suffices to recover exact additivity after normalizing by the diagonal
+exponent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+open Filter Topology
+
+/-- The number of binomial groups has exponential growth rate one. -/
+private theorem tendsto_binomialGroupCount_root :
+ Tendsto (fun n : ℕ ↦ ((n : ℝ) + 1) ^ (n : ℝ)⁻¹) atTop (𝓝 1) := by
+ have lim := (tendsto_rpow_div_mul_add 1 1 (-1) zero_ne_one).comp
+ (tendsto_atTop_add_const_right (atTop : Filter ℕ) (1 : ℝ) tendsto_natCast_atTop_atTop)
+ simpa only [Function.comp_def, one_mul, add_neg_cancel_right, one_div] using lim
+
+/-- A factor `m + 1` in a comparison of all powers disappears in the growth rate. -/
+private theorem le_of_binomialGroupCount_pow_le {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y)
+ (h : ∀ m : ℕ, 0 < m → x ^ m ≤ ((m : ℝ) + 1) * y ^ m) : x ≤ y := by
+ have lim : Tendsto (fun n : ℕ ↦ ((n : ℝ) + 1) ^ (n : ℝ)⁻¹ * y) atTop (𝓝 y) := by
+ simpa only [one_mul] using tendsto_binomialGroupCount_root.mul_const y
+ apply ge_of_tendsto lim
+ filter_upwards [eventually_gt_atTop (0 : ℕ)] with m hm
+ have := Real.rpow_le_rpow (pow_nonneg hx m) (h m hm) (show 0 ≤ (m : ℝ)⁻¹ by positivity)
+ simpa only [Real.mul_rpow (show 0 ≤ (m : ℝ) + 1 by positivity) (pow_nonneg hy m),
+ Real.pow_rpow_inv_natCast hx hm.ne', Real.pow_rpow_inv_natCast hy hm.ne'] using this
+
+/-- Lemma 2.3's binomial-group bounds imply additivity of the normalized
+value. `h` is the positive exponent of the embedded local diagonal, `a` and
+`b` are the normalized values of two tensors, and `z` is the normalized
+value of their direct sum. -/
+theorem normalizedAdditivity_of_binomialBounds {a b z h : ℝ}
+ (ha : 0 ≤ a) (hb : 0 ≤ b) (hz : 0 ≤ z) (hh : 0 < h)
+ (group_le : ∀ m j : ℕ, 0 < m → j ≤ m →
+ (a ^ j * b ^ (m - j) * m.choose j) ^ h ≤ (z ^ m) ^ h)
+ (expansion_le : ∀ m : ℕ, 0 < m → (z ^ m) ^ h ≤
+ ∑ j ∈ Finset.range (m + 1), (a ^ j * b ^ (m - j) * m.choose j) ^ h) :
+ z = a + b := by
+ let A (m j : ℕ) := a ^ j * b ^ (m - j) * m.choose j
+ have hA (m j : ℕ) : 0 ≤ A m j := by dsimp [A]; positivity
+ have sumA (m : ℕ) : ∑ j ∈ Finset.range (m + 1), A m j = (a + b)^m := (add_pow a b m).symm
+ have constSum (m : ℕ) (c : ℝ) :
+ ∑ _j ∈ Finset.range (m + 1), c = ((m : ℝ) + 1) * c := by simp
+ apply le_antisymm
+ · apply (Real.rpow_le_rpow_iff hz (add_nonneg ha hb) hh).mp
+ apply le_of_binomialGroupCount_pow_le (Real.rpow_nonneg hz _)
+ (Real.rpow_nonneg (add_nonneg ha hb) _)
+ intro m hm
+ calc
+ (z ^ h) ^ m = (z ^ m) ^ h := by
+ rw [← Real.rpow_natCast_mul hz, mul_comm (m : ℝ), Real.rpow_mul_natCast hz]
+ _ ≤ ∑ j ∈ Finset.range (m + 1), A m j ^ h := expansion_le m hm
+ _ ≤ ∑ _j ∈ Finset.range (m + 1), ((a + b)^m) ^ h := by
+ apply Finset.sum_le_sum
+ intro j hj
+ apply Real.rpow_le_rpow (hA m j) _ hh.le
+ rw [← sumA m]
+ exact Finset.single_le_sum (fun k _ ↦ hA m k) hj
+ _ = ((m : ℝ) + 1) * ((a + b) ^ h) ^ m := by
+ rw [constSum, ← Real.rpow_natCast_mul (add_nonneg ha hb), mul_comm (m : ℝ),
+ Real.rpow_mul_natCast (add_nonneg ha hb)]
+ · apply le_of_binomialGroupCount_pow_le (add_nonneg ha hb) hz
+ intro m hm
+ rw [← sumA, ← constSum]
+ apply Finset.sum_le_sum
+ intro j hj
+ exact (Real.rpow_le_rpow_iff (hA m j) (pow_nonneg hz _) hh).mp
+ (group_le m j hm (Nat.le_of_lt_succ (Finset.mem_range.mp hj)))
+
+private theorem subadditive_sum_le {S : Type*} [CommSemiring S] (f : S →*₀ ℝ)
+ (hadd : ∀ x y, f (x + y) ≤ f x + f y) {ι : Type*} (s : Finset ι) (t : ι → S) :
+ f (∑ i ∈ s, t i) ≤ ∑ i ∈ s, f (t i) := by
+ classical
+ induction s using Finset.induction_on with
+ | empty => simp
+ | insert i s hi ih =>
+ rw [Finset.sum_insert hi, Finset.sum_insert hi]
+ exact (hadd _ _).trans (add_le_add_right ih _)
+
+/-- The numerical bounds of Lemma 2.3 follow from the semiring binomial
+expansion. The embedded tensor value is multiplicative, subadditive on
+direct sums, and monotone under projection onto either direct summand. -/
+theorem normalized_multiplicative_value_add {S : Type*} [CommSemiring S] (f : S →*₀ ℝ)
+ (hf : ∀ x, 0 ≤ f x) (hsummand : ∀ x y, f x ≤ f (x + y))
+ (hadd : ∀ x y, f (x + y) ≤ f x + f y) {h : ℝ} (hh : 0 < h)
+ (hdiag : ∀ n : ℕ, f n = (n : ℝ) ^ h) (x y : S) :
+ f (x + y) ^ h⁻¹ = f x ^ h⁻¹ + f y ^ h⁻¹ := by
+ let term (m j : ℕ) := x ^ j * y ^ (m - j) * m.choose j
+ have hx := hf x
+ have hy := hf y
+ have groupValue (m j : ℕ) :
+ ((f x ^ h⁻¹) ^ j * (f y ^ h⁻¹) ^ (m - j) * m.choose j) ^ h = f (term m j) := by
+ dsimp only [term]
+ rw [map_mul, map_mul, map_pow, map_pow, hdiag]
+ rw [Real.mul_rpow (by positivity) (by positivity),
+ Real.mul_rpow (by positivity) (by positivity),
+ ← Real.rpow_natCast_mul (Real.rpow_nonneg (hf _) _),
+ ← Real.rpow_natCast_mul (Real.rpow_nonneg (hf _) _),
+ ← Real.rpow_mul (hf x), ← Real.rpow_mul (hf y)]
+ have cancel (n : ℕ) : h⁻¹ * ((n : ℝ) * h) = n := by field_simp
+ rw [cancel, cancel, Real.rpow_natCast, Real.rpow_natCast]
+ have totalValue (m : ℕ) : ((f (x + y) ^ h⁻¹) ^ m) ^ h = f ((x + y) ^ m) := by
+ rw [map_pow, ← Real.rpow_natCast_mul (Real.rpow_nonneg (hf _) _), ← Real.rpow_mul (hf _),
+ show h⁻¹ * ((m : ℝ) * h) = m by field_simp, Real.rpow_natCast]
+ apply normalizedAdditivity_of_binomialBounds (Real.rpow_nonneg (hf x) _)
+ (Real.rpow_nonneg (hf y) _) (Real.rpow_nonneg (hf _) _) hh
+ · intro m j _ hj
+ rw [groupValue, totalValue, add_pow]
+ change f (term m j) ≤ f (∑ i ∈ Finset.range (m + 1), term m i)
+ rw [← Finset.add_sum_erase _ _ (Finset.mem_range.mpr (Nat.lt_succ_of_le hj))]
+ exact hsummand _ _
+ · intro m _
+ simp only [groupValue, totalValue, add_pow]
+ exact subadditive_sum_le f hadd _ _
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/NullstellensatzGraph.lean b/lean/OAI/Computability/VPVNP/NullstellensatzGraph.lean
new file mode 100644
index 0000000000..302e5a116e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/NullstellensatzGraph.lean
@@ -0,0 +1,107 @@
+import Mathlib.RingTheory.Nullstellensatz
+import Mathlib.RingTheory.Ideal.Operations
+import Mathlib.RingTheory.MvPolynomial.Basic
+import Mathlib.Algebra.MvPolynomial.Degrees
+
+/-! # The graph used for effective Nullstellensatz certificates
+
+When the equations `F i` have no common zero, the functions `x_j` and
+`t * F i` generate the polynomial algebra in `x,t`. A linear Noether
+normalization of this generating system keeps each normalized coordinate
+linear in `t` and of bounded total degree. This is the graph construction
+of Jelonek's proof of the effective Nullstellensatz, specialized to affine
+space.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+open MvPolynomial
+
+variable {E I : Type*} [Field E] {n : ℕ}
+
+/-- The original coordinates and the equation values multiplied by an extra variable. -/
+noncomputable def graphGenerator (F : I → MvPolynomial (Fin n) E) :
+ Fin n ⊕ I → MvPolynomial (Fin (n+1)) E
+ | .inl j => X j.succ
+ | .inr i => X 0 * rename Fin.succ (F i)
+
+/-- Qualitative Nullstellensatz gives a certificate before any degree bound is imposed. -/
+theorem exists_certificate_of_inconsistent [IsAlgClosed E] [Fintype I]
+ (F : I → MvPolynomial (Fin n) E) (hno : ¬ ∃ x : Fin n → E, ∀ i, eval x (F i) = 0) :
+ ∃ A : I → MvPolynomial (Fin n) E, ∑ i, A i * F i = 1 := by
+ let J := Ideal.span (Set.range F)
+ have hzero : zeroLocus E J = ∅ := by
+ rw [zeroLocus_span]
+ apply Set.eq_empty_iff_forall_notMem.mpr
+ intro x hx
+ apply hno
+ exact ⟨x, fun i => by simpa only [aeval_eq_eval] using hx (F i) ⟨i, rfl⟩⟩
+ have hrad : (1 : MvPolynomial (Fin n) E) ∈ J.radical := by
+ rw [← vanishingIdeal_zeroLocus_eq_radical (K := E), hzero]
+ intro x hx
+ exact False.elim hx
+ obtain ⟨m, hm⟩ := Ideal.mem_radical_iff.mp hrad
+ exact Ideal.mem_span_range_iff_exists_fun.mp (by simpa using hm : 1 ∈ J)
+
+/-- The graph functions generate the full polynomial algebra if the system is inconsistent. -/
+theorem graphGenerator_adjoin [IsAlgClosed E] [Fintype I] (F : I → MvPolynomial (Fin n) E)
+ (hno : ¬ ∃ x : Fin n → E, ∀ i, eval x (F i) = 0) :
+ Algebra.adjoin E (Set.range (graphGenerator F)) = ⊤ := by
+ let S := Algebra.adjoin E (Set.range (graphGenerator F))
+ have gen (i : Fin n ⊕ I) : graphGenerator F i ∈ S :=
+ Algebra.subset_adjoin ⟨i, rfl⟩
+ have hrename (p : MvPolynomial (Fin n) E) : rename Fin.succ p ∈ S := by
+ induction p using MvPolynomial.induction_on with
+ | C c => simpa using S.algebraMap_mem c
+ | add p q hp hq => simpa using S.add_mem hp hq
+ | mul_X p j hp => simpa [graphGenerator] using S.mul_mem hp (gen (.inl j))
+ obtain ⟨u, hu⟩ := exists_certificate_of_inconsistent F hno
+ have ht : X (0 : Fin (n+1)) ∈ S := by
+ have h := congrArg (fun p => X (0 : Fin (n+1)) * rename Fin.succ p) hu
+ simp only [map_sum, map_mul, map_one, mul_one, Finset.mul_sum] at h
+ rw [← h]
+ apply S.sum_mem
+ intro i _
+ simpa only [graphGenerator, mul_left_comm] using S.mul_mem (hrename (u i)) (gen (.inr i))
+ apply top_unique
+ rw [← adjoin_range_X (σ := Fin (n+1)) (R := E)]
+ apply Algebra.adjoin_le
+ rintro _ ⟨j, rfl⟩
+ exact Fin.cases ht (fun i => gen (.inl i)) j
+
+/-- Every linear combination of the graph functions has the displayed affine-in-`t` form. -/
+theorem graphGenerator_span_decompose [Fintype I] (F : I → MvPolynomial (Fin n) E)
+ {q : MvPolynomial (Fin (n+1)) E} (hq : q ∈ Submodule.span E (Set.range (graphGenerator F))) :
+ ∃ (l : Fin n → E) (c : I → E), q = (∑ j, C (l j) * X j.succ) +
+ X 0 * ∑ i, C (c i) * rename Fin.succ (F i) := by
+ obtain ⟨v, hv⟩ := (Submodule.mem_span_range_iff_exists_fun E).mp hq
+ refine ⟨fun j => v (.inl j), fun i => v (.inr i), ?_⟩
+ rw [← hv, Fintype.sum_sum_type, Finset.mul_sum]
+ simp only [graphGenerator, smul_eq_C_mul, mul_left_comm]
+
+/-- Normalization by linear combinations increases the equation degree by at most one. -/
+theorem graphGenerator_span_degree [Fintype I] (F : I → MvPolynomial (Fin n) E) {D : ℕ}
+ (hF : ∀ i, (F i).totalDegree ≤ D) {q : MvPolynomial (Fin (n+1)) E}
+ (hq : q ∈ Submodule.span E (Set.range (graphGenerator F))) : q.totalDegree ≤ D + 1 := by
+ obtain ⟨v, hv⟩ := (Submodule.mem_span_range_iff_exists_fun E).mp hq
+ rw [← hv]
+ apply totalDegree_finsetSum_le
+ intro i _
+ apply (totalDegree_smul_le ..).trans
+ cases i with
+ | inl j => simp [graphGenerator]
+ | inr i =>
+ apply (totalDegree_mul ..).trans
+ have h := (totalDegree_rename_le Fin.succ (F i)).trans (hF i)
+ rw [totalDegree_X]
+ omega
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/OracleBinaryTarget.lean b/lean/OAI/Computability/VPVNP/OracleBinaryTarget.lean
new file mode 100644
index 0000000000..e974408f34
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/OracleBinaryTarget.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.VerifierMachineNetwork
+import Mathlib.Data.Nat.Bitwise
+
+/-!
+# Comparing a queried exponent against a count register
+
+One static Boolean expression per possible count compares the query's binary
+digits with the fixed count. Values exceeding the number of available flags
+therefore produce a zero target row and are rejected by the row-count circuit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace OracleBinaryTarget
+
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+
+variable {V : Type*} {w : ℕ}
+
+private def mismatch (wire : Fin w → V) (j : ℕ) (i : Fin w) : Expr V :=
+ if j.testBit i.val then .not (.input (wire i)) else .input (wire i)
+
+/-- Boolean equality test between the wired binary word and the natural-number target,
+returning false when the target exceeds the word's range. -/
+def expr (wire : Fin w → V) (j : ℕ) : Expr V :=
+ if j < 2 ^ w then .not (Expr.disjoin ((List.finRange w).map (mismatch wire j)))
+ else .const false
+
+private theorem mismatch_eval (wire : Fin w → V) (j : ℕ) (i : Fin w) (x : V → Bool) :
+ (mismatch wire j i).eval x = true ↔ x (wire i) ≠ j.testBit i.val := by
+ cases h : j.testBit i.val <;> cases h' : x (wire i) <;> simp [mismatch, Expr.eval, h, h']
+
+theorem expr_eval (wire : Fin w → V) (j z : ℕ) (hz : z < 2 ^ w) (x : V → Bool)
+ (hx : ∀ i, x (wire i) = z.testBit i.val) : (expr wire j).eval x = decide (z = j) := by
+ apply Bool.eq_iff_iff.mpr
+ by_cases hj : j < 2 ^ w
+ · simp only [expr, hj, ite_true, Expr.eval, Bool.not_eq_true', decide_eq_true_eq]
+ rw [Bool.eq_false_iff]
+ simp only [ne_eq, Expr.eval_disjoin_true, List.mem_map, List.mem_finRange, true_and,
+ exists_exists_eq_and, mismatch_eval, not_exists, not_not, hx]
+ constructor
+ · intro h
+ apply Nat.eq_of_testBit_eq
+ intro t
+ by_cases ht : t < w
+ · exact h ⟨t, ht⟩
+ · have hp := Nat.pow_le_pow_right (by decide : 0 < 2) (le_of_not_gt ht)
+ rw [Nat.testBit_eq_false_of_lt (hz.trans_le hp), Nat.testBit_eq_false_of_lt (hj.trans_le hp)]
+ · rintro rfl
+ exact fun _ ↦ rfl
+ · have hne : z ≠ j := by omega
+ simp [expr, hj, hne, Expr.eval]
+
+theorem expr_size_le (wire : Fin w → V) (j : ℕ) : (expr wire j).size ≤ w * 3 + 2 := by
+ unfold expr
+ split
+ · have h := Expr.size_disjoin_le ((List.finRange w).map (mismatch wire j)) 2 (by
+ intro e he
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp he
+ unfold mismatch
+ split <;> simp [Expr.size])
+ simp only [List.length_map, List.length_finRange] at h
+ change _ + 1 ≤ _
+ omega
+ · change 1 ≤ _
+ omega
+
+end OracleBinaryTarget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/OracleCNFExpr.lean b/lean/OAI/Computability/VPVNP/OracleCNFExpr.lean
new file mode 100644
index 0000000000..cff9552c20
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/OracleCNFExpr.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.VerifierMachineNetwork
+import OAI.Computability.VPVNP.HardnessCNF
+
+/-! # Boolean expressions for the coefficient oracle's CNF
+
+Each clause becomes a disjunction of its signed input flags. Negating the
+disjunction of failed clauses enforces their conjunction, including the empty
+formula and formulas containing empty clauses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace OracleCNFExpr
+
+open HardnessCNF
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+
+variable {W : Type*} {k : ℕ}
+
+private def lit (wire : Fin k → W) (l : Literal k) : Expr W :=
+ if l.2 then .input (wire l.1) else .not (.input (wire l.1))
+
+private def clause (wire : Fin k → W) (c : List (Literal k)) : Expr W :=
+ Expr.disjoin (c.map (lit wire))
+
+/-- Expression testing the CNF on the indicated wires of a larger Boolean frame. -/
+def formula (wire : Fin k → W) (φ : CNF k) : VerifierNetwork.Expr W :=
+ .not (Expr.disjoin (φ.map (fun c => .not (clause wire c))))
+
+private theorem eval_lit (wire : Fin k → W) (x : W → Bool) (l : Literal k) :
+ (lit wire l).eval x = true ↔ x (wire l.1) = l.2 := by
+ rcases l with ⟨i, b⟩
+ cases b <;> simp [lit, Expr.eval]
+
+private theorem eval_clause (wire : Fin k → W) (x : W → Bool) (c : List (Literal k)) :
+ (clause wire c).eval x = true ↔ ∃ l ∈ c, x (wire l.1) = l.2 := by
+ rw [clause, Expr.eval_disjoin_true]
+ constructor
+ · rintro ⟨e, he, hv⟩
+ obtain ⟨l, hl, rfl⟩ := List.mem_map.mp he
+ exact ⟨l, hl, (eval_lit wire x l).mp hv⟩
+ · rintro ⟨l, hl, hv⟩
+ exact ⟨lit wire l, List.mem_map.mpr ⟨l, hl, rfl⟩, (eval_lit wire x l).mpr hv⟩
+
+private theorem eval_not_true (x : W → Bool) (e : Expr W) :
+ (Expr.not e).eval x = true ↔ ¬ e.eval x = true := by
+ cases h : e.eval x <;> simp [Expr.eval, h]
+
+theorem formula_eval_iff (wire : Fin k → W) (φ : CNF k) (x : W → Bool) :
+ (formula wire φ).eval x = true ↔ Satisfies φ (x ∘ wire) := by
+ simp [formula, eval_not_true, Expr.eval_disjoin_true, eval_clause, Satisfies]
+
+private theorem clause_size_le (wire : Fin k → W) (c : List (Literal k)) :
+ (clause wire c).size ≤ 3 * c.length + 1 := by
+ have h := Expr.size_disjoin_le (c.map (lit wire)) 2 (by
+ rintro e he
+ obtain ⟨⟨i,b⟩, _, rfl⟩ := List.mem_map.mp he
+ cases b <;> simp [lit, Expr.size])
+ simpa [clause, Nat.mul_comm] using h
+
+/-- The expression has linear size in the number of literals and clauses. -/
+theorem formula_size_le (wire : Fin k → W) (φ : CNF k) :
+ (formula wire φ).size ≤ 3 * literalCount φ + 3 * φ.length + 2 := by
+ induction φ with
+ | nil => simp [formula, Expr.disjoin, Expr.size, literalCount]
+ | cons c φ ih =>
+ have h := clause_size_le wire c
+ simp only [formula, List.map_cons, Expr.disjoin, Expr.size, literalCount, List.sum_cons,
+ List.length_cons] at ih ⊢
+ omega
+
+end OracleCNFExpr
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/OracleTallyCircuit.lean b/lean/OAI/Computability/VPVNP/OracleTallyCircuit.lean
new file mode 100644
index 0000000000..d8464463c5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/OracleTallyCircuit.lean
@@ -0,0 +1,222 @@
+import OAI.Computability.VPVNP.VerifierMachineNetwork
+import Mathlib.Algebra.BigOperators.Fin
+
+/-!
+# Boolean circuit checking row counts
+
+The coefficient oracle of §8.1 counts the selected terminal and production events.
+Each event flag may increment the counts of any fixed set of rows. At each stage this
+circuit maintains one bit for every row and every count from zero through the number
+of flags. Its final layer compares those bits with the supplied one-hot target table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace OracleTally
+
+open VerifierNetwork (Frame)
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+
+/-- Flag wires followed by the row and count coordinates of the one-hot table. -/
+abbrev Input (Rows : Type*) (k : ℕ) := Fin k ⊕ Rows × Fin (k + 1)
+
+variable {Rows : Type*} {k : ℕ}
+
+/-- Number of selected flags that are set in this row. -/
+def rowCount (selected : Rows → Fin k → Bool) (x : Fin k → Bool) (r : Rows) : ℕ :=
+ ∑ i, if selected r i && x i then 1 else 0
+
+/-- The target marks exactly the attained count in each row. -/
+def RowCountsOK (selected : Rows → Fin k → Bool) (x : Fin k → Bool)
+ (target : Rows → Fin (k+1) → Bool) : Prop :=
+ ∀ r j, target r j = decide (rowCount selected x r = j.val)
+
+theorem rowCount_le (selected : Rows → Fin k → Bool) (x : Fin k → Bool) (r : Rows) :
+ rowCount selected x r ≤ k := by
+ calc
+ rowCount selected x r ≤ ∑ _ : Fin k, 1 := by
+ unfold rowCount
+ apply Finset.sum_le_sum
+ intro i _
+ split <;> decide
+ _ = k := by simp
+
+/-- An all-zero target row for a count greater than `k` is rejected as well. -/
+theorem rowCountsOK_oneHot_iff (selected : Rows → Fin k → Bool) (x : Fin k → Bool)
+ (wanted : Rows → ℕ) :
+ RowCountsOK selected x (fun r j ↦ decide (wanted r = j.val)) ↔
+ ∀ r, rowCount selected x r = wanted r := by
+ constructor
+ · intro h r
+ let j : Fin (k+1) := ⟨rowCount selected x r, Nat.lt_succ_of_le (rowCount_le _ _ _)⟩
+ have hj := h r j
+ simpa [j, eq_comm] using hj
+ · intro h r j
+ rw [h]
+
+private def prefixCount (selected : Rows → Fin k → Bool) (x : Fin k → Bool)
+ (r : Rows) (t : ℕ) : ℕ :=
+ ∑ a ∈ Finset.range t, if h : a < k then
+ (if selected r ⟨a,h⟩ && x ⟨a,h⟩ then 1 else 0) else 0
+
+private theorem prefixCount_full (selected : Rows → Fin k → Bool) (x : Fin k → Bool)
+ (r : Rows) : prefixCount selected x r k = rowCount selected x r :=
+ (Finset.sum_fin_eq_sum_range (fun i ↦ if selected r i && x i then 1 else 0)).symm
+
+private def initialExpr : Input Rows k → Expr (Input Rows k)
+ | .inl i => .input (.inl i)
+ | .inr (_, j) => .const (decide (0 = j.val))
+
+private def previousExpr (r : Rows) (j : Fin (k+1)) : Expr (Input Rows k) :=
+ if j.val = 0 then .const false
+ else .input (.inr (r, ⟨j.val - 1, by have := j.isLt; omega⟩))
+
+private def layerExpr (selected : Rows → Fin k → Bool) (t : ℕ) :
+ Input Rows k → Expr (Input Rows k)
+ | .inl i => .input (.inl i)
+ | .inr (r, j) =>
+ if ht : t < k then
+ if selected r ⟨t, ht⟩ then
+ Expr.mux (.input (.inl ⟨t, ht⟩)) (previousExpr r j) (.input (.inr (r, j)))
+ else .input (.inr (r, j))
+ else .input (.inr (r, j))
+
+variable [Fintype Rows]
+
+private noncomputable def scan (selected : Rows → Fin k → Bool) (t : ℕ) :
+ Frame (Input Rows k) (Input Rows k) :=
+ ((Frame.initial id).step initialExpr).steps (layerExpr selected) t
+
+private theorem scan_eval (selected : Rows → Fin k → Bool) (x : Input Rows k → Bool) (t : ℕ) :
+ (∀ i, (scan selected t).eval x (.inl i) = x (.inl i)) ∧
+ (∀ r j, (scan selected t).eval x (.inr (r,j)) =
+ decide (prefixCount selected (x ∘ Sum.inl) r t = j.val)) := by
+ induction t with
+ | zero =>
+ constructor <;> intros <;> simp [scan, initialExpr, Expr.eval, prefixCount]
+ | succ t ih =>
+ have hs : scan selected (t+1) = (scan selected t).step (layerExpr selected t) := rfl
+ constructor
+ · intro i
+ simpa [hs, layerExpr, Expr.eval] using ih.1 i
+ · intro r j
+ rw [hs, Frame.step_eval]
+ have hc : prefixCount selected (x ∘ Sum.inl) r (t+1) =
+ prefixCount selected (x ∘ Sum.inl) r t +
+ (if ht : t < k then (if selected r ⟨t,ht⟩ && x (.inl ⟨t,ht⟩) then 1 else 0)
+ else 0) := Finset.sum_range_succ _ _
+ rw [hc]
+ by_cases ht : t < k
+ · cases hr : selected r ⟨t, ht⟩ <;> cases hx : x (.inl ⟨t,ht⟩) <;>
+ simp [layerExpr, ht, hr, hx, ih.1, ih.2, Expr.eval]
+ by_cases hj : j.val = 0
+ · simp [previousExpr, hj, Expr.eval]
+ · simp only [previousExpr, ite_eq_right hj, Expr.eval, ih.2]
+ apply Bool.eq_iff_iff.mpr
+ simp
+ omega
+ · simp [layerExpr, ht, Expr.eval, ih.2]
+
+/-- The completed table of attained counts, before checking the supplied target. -/
+noncomputable def counters (selected : Rows → Fin k → Bool) :
+ Frame (Input Rows k) (Rows × Fin (k+1)) :=
+ (scan selected k).select Sum.inr
+
+theorem counters_eval (selected : Rows → Fin k → Bool) (input : Input Rows k → Bool)
+ (r : Rows) (j : Fin (k+1)) :
+ (counters selected).eval input (r,j) = decide (rowCount selected (input ∘ Sum.inl) r = j.val) := by
+ simp only [counters, Frame.select_eval, (scan_eval selected input k).2, prefixCount_full]
+
+private def mismatch (a : Rows × Fin (k+1)) : Expr (Input Rows k ⊕ Input Rows k) :=
+ let target := Expr.input (.inl (.inr a))
+ let attained := Expr.input (.inr (.inr a))
+ Expr.mux target (.not attained) attained
+
+omit [Fintype Rows] in
+private theorem mismatch_eval (v : Input Rows k ⊕ Input Rows k → Bool) (a : Rows × Fin (k+1)) :
+ (mismatch a).eval v = true ↔ v (.inl (.inr a)) ≠ v (.inr (.inr a)) := by
+ cases ht : v (.inl (.inr a)) <;> cases hc : v (.inr (.inr a)) <;>
+ simp [mismatch, Expr.eval, ht, hc]
+
+private noncomputable def outputExpr (_ : Unit) : Expr (Input Rows k ⊕ Input Rows k) :=
+ .not (Expr.disjoin (Finset.univ.toList.map mismatch))
+
+/-- Finished network over both the flag bits and the queried target table. -/
+noncomputable def frame (selected : Rows → Fin k → Bool) : Frame (Input Rows k) Unit :=
+ (scan selected k).withInput.step outputExpr
+
+/-- The output rejects every differing entry, including extra marks in a target row. -/
+theorem frame_eval_iff (selected : Rows → Fin k → Bool) (x : Fin k → Bool)
+ (target : Rows → Fin (k+1) → Bool) :
+ (frame selected).eval (Sum.elim x (Function.uncurry target)) () = true ↔
+ RowCountsOK selected x target := by
+ simp only [frame, Frame.step_eval, outputExpr, Expr.eval, Bool.not_eq_true']
+ rw [Bool.eq_false_iff]
+ simp only [ne_eq, Expr.eval_disjoin_true, List.mem_map, Finset.mem_toList, Finset.mem_univ, true_and,
+ exists_exists_eq_and, mismatch_eval, not_exists, not_not, Frame.withInput_eval_inl,
+ Frame.withInput_eval_inr, Sum.elim_inr]
+ simp only [Prod.forall, (scan_eval selected _ k).2, prefixCount_full]
+ rfl
+
+/-- Deterministic transcript verifier for the row counts. -/
+noncomputable def verifier (selected : Rows → Fin k → Bool) :=
+ (frame selected).circuit ()
+
+theorem verifier_eval_iff (selected : Rows → Fin k → Bool) (x : Fin k → Bool)
+ (target : Rows → Fin (k+1) → Bool) :
+ (verifier selected).eval (Sum.elim x (Function.uncurry target)) = true ↔
+ RowCountsOK selected x target := by
+ rw [verifier, Frame.circuit_eval, frame_eval_iff]
+
+omit [Fintype Rows] in
+private theorem layerExpr_size (selected : Rows → Fin k → Bool) (t : ℕ) (i : Input Rows k) :
+ (layerExpr selected t i).size ≤ 8 := by
+ rcases i with i | ⟨r,j⟩
+ · change 1 ≤ 8
+ decide
+ · by_cases ht : t < k
+ · cases hr : selected r ⟨t,ht⟩ <;> by_cases hj : j.val = 0 <;>
+ simp [layerExpr, ht, hr, hj, Expr.mux, Expr.size, previousExpr]
+ · simp [layerExpr, ht, Expr.size]
+
+private theorem outputExpr_size (u : Unit) :
+ (outputExpr (Rows := Rows) (k := k) u).size ≤ Fintype.card Rows * (k+1) * 10 + 2 := by
+ have hs := Expr.size_disjoin_le (Finset.univ.toList.map (mismatch (Rows := Rows) (k := k))) 9
+ (fun e he ↦ by obtain ⟨a, _, rfl⟩ := List.mem_map.mp he; rfl)
+ simp only [List.length_map, Finset.length_toList, Finset.card_univ, Fintype.card_prod,
+ Fintype.card_fin] at hs
+ exact Nat.add_le_add_right hs 1
+
+/-- One constant-size local expression per live wire at every clock tick, followed by
+one constant-size mismatch check per table entry and a disjunction. -/
+theorem frame_size_le (selected : Rows → Fin k → Bool) :
+ (frame selected).size ≤
+ (k + Fintype.card Rows * (k+1)) + k * ((k + Fintype.card Rows * (k+1)) * 8) +
+ (Fintype.card Rows * (k+1) * 10 + 2) := by
+ let first : Frame (Input Rows k) (Input Rows k) := (Frame.initial id).step initialExpr
+ have hi : first.size ≤ Fintype.card (Input Rows k) := by
+ have h := Frame.step_size_le (Frame.initial id) (initialExpr (Rows := Rows) (k := k)) 1
+ (by rintro (i | ⟨r,j⟩) <;> rfl)
+ simpa [first] using h
+ have hs := Frame.steps_size_le first (layerExpr selected) k 8 (fun t _ i ↦ layerExpr_size _ t i)
+ have hf := Frame.step_size_le (scan selected k).withInput outputExpr
+ (Fintype.card Rows * (k+1) * 10 + 2) outputExpr_size
+ simp only [Frame.withInput_size, Fintype.card_unit, one_mul] at hf
+ change (frame selected).size ≤ (first.steps (layerExpr selected) k).size + _ at hf
+ simp only [Input, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] at hi hs
+ omega
+
+/-- Size bound in the AND/NOT gate model used by the transcript verifier. -/
+theorem verifier_size_le (selected : Rows → Fin k → Bool) :
+ (frame selected).circuitSize () ≤ 4 *
+ ((k + Fintype.card Rows * (k+1)) + k * ((k + Fintype.card Rows * (k+1)) * 8) +
+ (Fintype.card Rows * (k+1) * 10 + 2)) :=
+ ((frame selected).circuitSize_le ()).trans (Nat.mul_le_mul_left _ (frame_size_le selected))
+
+end OracleTally
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/OrbitAverage.lean b/lean/OAI/Computability/VPVNP/OrbitAverage.lean
new file mode 100644
index 0000000000..dd72d27343
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/OrbitAverage.lean
@@ -0,0 +1,44 @@
+import Mathlib.Algebra.Group.Action.Pretransitive
+import Mathlib.GroupTheory.GroupAction.Basic
+import Mathlib.Algebra.BigOperators.Ring.Finset
+import Mathlib.Basic.Real.Basic
+import Mathlib.Algebra.BigOperators.Group.Finset.Sigma
+
+/-!
+# Uniform averaging on transitive finite group actions
+
+Section 5 compares Grassmann pair energies by lifting them to the general
+linear group. A uniformly chosen group element takes a fixed point of any
+transitive finite action to a uniformly chosen point.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+/-- A finite group average of an observable agrees with its uniform average on a
+transitive finite set. -/
+theorem orbitAverage_eq_uniformAverage (G : Type*) {S : Type*} [Group G] [Fintype G]
+ [Fintype S] [MulAction G S] [MulAction.IsPretransitive G S] (s : S) (E : S → ℝ) :
+ (∑ g : G, E (g • s)) / Fintype.card G = (∑ x : S, E x) / Fintype.card S := by
+ let : Nonempty S := ⟨s⟩
+ have hx (x : S) : (∑ g : G, E (g • x)) = ∑ g : G, E (g • s) := by
+ obtain ⟨h, rfl⟩ := MulAction.exists_smul_eq G s x
+ simp_rw [smul_smul]
+ exact Equiv.sum_comp (Equiv.mulRight h) (fun g : G ↦ E (g • s))
+ have hg (g : G) : (∑ x : S, E (g • x)) = ∑ x : S, E x :=
+ Equiv.sum_comp (MulAction.toPerm g) E
+ apply (div_eq_div_iff (Nat.cast_ne_zero.mpr Fintype.card_ne_zero)
+ (Nat.cast_ne_zero.mpr Fintype.card_ne_zero)).2
+ calc
+ _ = ∑ x : S, ∑ g : G, E (g • x) := by simp_rw [hx]; simp [mul_comm]
+ _ = ∑ g : G, ∑ x : S, E (g • x) := Finset.sum_comm
+ _ = _ := by simp_rw [hg]; simp [mul_comm]
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/OrderedParse.lean b/lean/OAI/Computability/VPVNP/OrderedParse.lean
new file mode 100644
index 0000000000..fb47063088
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/OrderedParse.lean
@@ -0,0 +1,76 @@
+import Mathlib.Data.Fintype.Prod
+import Mathlib.Data.Fintype.Sigma
+
+/-!
+# Finite ordered parses
+
+A parse of layer `d` has `d + 1` terminal occurrences. At a binary production, the
+split records the layer of the left child, and the two state labels specify the roots
+of the child parses. The root state of the entire parse is supplied by the grammar.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+universe u v
+
+/-- Ordered binary parse with terminal variables, child states and fixed leaf count. -/
+inductive OrderedParse (V : Type u) (H : Type v) : ℕ → Type (max u v) where
+ | leaf (v : V) : OrderedParse V H 0
+ | node {d : ℕ} (b : Fin (d + 1)) (i j : H)
+ (left : OrderedParse V H b.val) (right : OrderedParse V H (d - b.val)) :
+ OrderedParse V H (d + 1)
+
+namespace OrderedParse
+
+variable {V : Type u} {H : Type v}
+
+/-- A parse in degree one is determined by its sole terminal. -/
+def leafEquiv : OrderedParse V H 0 ≃ V where
+ toFun | leaf v => v
+ invFun := leaf
+ left_inv t := by cases t; rfl
+ right_inv _ := rfl
+
+/-- Decompose a binary parse into its split, child states and ordered subtrees. -/
+def nodeEquiv (d : ℕ) : OrderedParse V H (d + 1) ≃
+ Σ b : Fin (d + 1), H × H × OrderedParse V H b.val × OrderedParse V H (d - b.val) where
+ toFun | node b i j left right => ⟨b, i, j, left, right⟩
+ invFun | ⟨b, i, j, left, right⟩ => node b i j left right
+ left_inv t := by cases t; rfl
+ right_inv _ := rfl
+
+instance instFintype [Fintype V] [Fintype H] : (d : ℕ) → Fintype (OrderedParse V H d)
+ | 0 => Fintype.ofEquiv _ leafEquiv.symm
+ | d + 1 => by
+ letI (b : Fin (d + 1)) : Fintype (OrderedParse V H b.val) := instFintype b.val
+ letI (b : Fin (d + 1)) : Fintype (OrderedParse V H (d - b.val)) := instFintype (d - b.val)
+ exact Fintype.ofEquiv _ (nodeEquiv d).symm
+termination_by d => d
+decreasing_by
+ · exact b.isLt
+ · exact Nat.lt_succ_of_le (Nat.sub_le _ _)
+
+/-- Terminal word, read from left to right with multiplicity. -/
+def leaves {d : ℕ} : OrderedParse V H d → List V
+ | leaf v => [v]
+ | node _ _ _ left right => leaves left ++ leaves right
+
+@[simp] theorem length_leaves {d : ℕ} (t : OrderedParse V H d) :
+ t.leaves.length = d + 1 := by
+ induction t with
+ | leaf => rfl
+ | node b _ _ _ _ ih₁ ih₂ =>
+ rw [leaves, List.length_append, ih₁, ih₂]
+ have := b.isLt
+ omega
+
+end OrderedParse
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PackedShrinkStep.lean b/lean/OAI/Computability/VPVNP/PackedShrinkStep.lean
new file mode 100644
index 0000000000..fe62fa6701
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PackedShrinkStep.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PackedSubdivision
+import OAI.Computability.VPVNP.ShrinkMotif
+import OAI.Computability.VPVNP.ShrinkPayload
+
+/-!
+# Quadratic energy bound for the actual shrinking step
+
+The degree threshold in Section 7.2 works for every packed graph with the
+same old degree and number of color bits. Each list of admitted six-party
+terms determines a single layout. With the paper's floor subdivisions, the
+energy of its numbered outgoing arcs (including the zero-width dummies)
+satisfies equation (7.2), with a constant independent of the old widths and
+of the number of positions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.ShrinkMotif
+
+/-- Parallel slots assigned to each of the four surviving supply types. -/
+noncomputable def subdivisions (d c d' : ℕ) (e : Fin 4) : ℕ :=
+ SlotSubdivision.count (2 ^ c * d) d d' (relativeMass e)
+
+/-- The same integral subdivision profile is used on all motifs and all lanes. -/
+structure Ready (d c d' : ℕ) (δ : ℝ) : Prop where
+ degree_pos : 0 < d'
+ count_pos : ∀ e, 0 < subdivisions d c d' e
+ degree_budget : d * PackingData.pieceCount d c * ∑ e, subdivisions d c d' e ≤ d'
+ mass : ∀ {p p' : ℝ}, 0 < p → p' = p * ((2 ^ c * d : ℕ) * (d : ℝ)) / d' →
+ ∀ e, (1 - δ) * p * relativeMass e ≤ (subdivisions d c d' e : ℝ) * p'
+
+/-- In particular, all sufficiently large power-of-two degrees can be used. -/
+theorem eventually_ready (d c : ℕ) (hd : 0 < d) (hc : 2 ≤ c) {δ : ℝ}
+ (hδ : 0 < δ) (hδ' : δ < 1) : ∃ N : ℕ, ∀ d' ≥ N, Ready d c d' δ := by
+ let q := fun e ↦ (relativeMass e : ℝ)
+ have hq e : 0 < q e := Rat.cast_pos.mpr (relativeMass_pos e)
+ obtain ⟨N, hN⟩ := SlotSubdivision.eventually_represented q hq
+ (Nat.mul_pos (pow_pos (by decide : 0 < 2) c) hd) hd hδ hδ'
+ refine ⟨N, fun d' hd' ↦ ?_⟩
+ obtain ⟨hdegree, hm⟩ := hN d' hd'
+ refine ⟨hdegree, fun e ↦ (hm 1 _ zero_lt_one rfl e).1,
+ PackingData.packed_degree_budget q (fun e ↦ (hq e).le) sum_relativeMass hc hd d', ?_⟩
+ exact fun hp hmass e ↦ (hm _ _ hp hmass e).2
+
+/-- Strict contraction of the leading term under the chosen loss allowance. -/
+theorem shrinkFactor_lt_one {δ H' : ℝ} (hδ : δ < 1) (hgap : H' < 2 * (1 - δ)) :
+ H' / (2 * (1 - δ)) < 1 := by
+ rwa [div_lt_one (mul_pos (by norm_num) (sub_pos.mpr hδ))]
+
+end Compression.ShrinkMotif
+
+namespace Compression.PackingData
+
+open MotifGrid MotifBlocks MotifConversion ShrinkMotif ShrinkEnergy SurvivingSlots
+
+variable {V H Tag L : Type} {d c d' : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable {k : Type*} [Field k] {factor δ : ℝ}
+variable (P : PackingData V H Tag L d c)
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (number : P.BundleNumbering) (old : Arc V H Tag L d c → ℕ)
+variable (choice : ∀ m : P.Motif,
+ ↥(outerIndices B (demandWidths (P.abWidth number old m) (old m.val))))
+
+/-- All eight supply widths at each occurrence, for the selected term list. -/
+noncomputable def termWidths (m : P.Motif) (l : Bool) (e : Fin 4) : ℕ :=
+ supplyWidths B (demandWidths (P.abWidth number old m) (old m.val)) (choice m).val (l,e)
+
+/-- The energy of the genuine, subdivided arc identifiers before reindexing. -/
+theorem packed_energy_from_terms [Nonempty V] (hc : 2 ≤ c) (hd : 0 < d)
+ (ready : Ready d c d' δ) (hδ : δ < 1) (hfactor : 0 ≤ factor) :
+ let p := equalArcMass (Position V H Tag L c) d
+ let p' := equalArcMass (Site V Tag L) d'
+ let w := P.termWidths B number old choice
+ let l := chosenLayout p (fun e ↦ (relativeMass e : ℝ)) w
+ let m := subdivisions d c d'
+ (∑ i : Id P.Motif m, (slotWidth m w l i : ℝ) ^ 2 / p') ≤
+ factor / (2 * (1 - δ)) * (∑ a, (old a : ℝ) ^ 2 / p) +
+ roundingConstant d d' (pieceCount d c) factor B.energyConstant (1 - δ) m *
+ (Fintype.card (Position V H Tag L c) : ℝ) ^ 2 := by
+ apply P.packed_energy_le hc hd ready.degree_pos number old _ _ _ (sub_pos.mpr hδ) hfactor
+ (fun e ↦ Rat.cast_pos.mpr (relativeMass_pos e)) ready.count_pos
+ · apply ready.mass _ (P.equalArcMass_packed hd d')
+ exact one_div_pos.mpr (mul_pos (Nat.cast_pos.mpr Fintype.card_pos) (Nat.cast_pos.mpr hd))
+ · exact fun m ↦ term_energy_le B _ _ (choice m).property
+
+/-- Equation (7.2) on the numbered outgoing arcs of the graph passed to the
+next compressor step. Dummy arcs carry zero payload at every remaining lane. -/
+theorem shrinkSlotWidth_energy_le [Nonempty V] (hc : 2 ≤ c) (hd : 0 < d)
+ (ready : Ready d c d' δ) (hδ : δ < 1) (hfactor : 0 ≤ factor)
+ {pad : ℕ} (outgoing : PaddedId (V × Tag) (Id P.BaseMotif (subdivisions d c d')) pad ≃
+ (V × Tag) × Fin d') :
+ let p := equalArcMass (Position V H Tag L c) d
+ let p' := equalArcMass (Site V Tag L) d'
+ let w := P.termWidths B number old choice
+ let l := chosenLayout p (fun e ↦ (relativeMass e : ℝ)) w
+ let m := subdivisions d c d'
+ let width := P.shrinkSlotWidth l m (fun a t ↦ w a l t) outgoing
+ (∑ a : ((V × Tag) × L) × Fin d', (width ((a.1.1,a.2),a.1.2) : ℝ) ^ 2 / p') ≤
+ factor / (2 * (1 - δ)) * (∑ a, (old a : ℝ) ^ 2 / p) +
+ roundingConstant d d' (pieceCount d c) factor B.energyConstant (1 - δ) m *
+ (Fintype.card (Position V H Tag L c) : ℝ) ^ 2 := by
+ intro p p' w l m width
+ exact (P.sum_shrinkSlotWidth l m (fun a t ↦ w a l t) outgoing
+ (fun n ↦ (n : ℝ) ^ 2 / p') (by simp)).trans_le
+ (P.packed_energy_from_terms B number old choice hc hd ready hδ hfactor)
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PackedSubdivision.lean b/lean/OAI/Computability/VPVNP/PackedSubdivision.lean
new file mode 100644
index 0000000000..1b4bbdf7ac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PackedSubdivision.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.ShrinkEnergy
+import OAI.Computability.VPVNP.SlotSubdivision
+
+/-!
+# Masses and subdivision counts of an actual packed graph
+
+The color bits and old slot label give exactly `K = 2^c*d` old positions
+per packed site. Section 7.2 consequently computes the new arc mass from
+the old arc mass and the two degrees alone.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+open ShrinkEnergy SlotSubdivision
+
+variable {V H Tag L : Type*} {d c : ℕ}
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+
+/-- The number of old positions per packed site is the number of choices
+of color word times the number of choices of the old slot label. -/
+theorem card_positions (P : PackingData V H Tag L d c) :
+ Fintype.card (Position V H Tag L c) = Fintype.card (Site V Tag L) * (2 ^ c * d) := by
+ have hH : Fintype.card H = d := (Fintype.card_congr P.slotLabel).trans (Fintype.card_fin _)
+ simp only [Position, BitWord, Fintype.card_prod, Fintype.card_fun, Fintype.card_fin,
+ ZMod.card, hH]
+
+/-- Actual masses satisfy `p' = pKd/d'`. -/
+theorem equalArcMass_packed (P : PackingData V H Tag L d c) (hd : 0 < d) (d' : ℕ) :
+ equalArcMass (Site V Tag L) d' =
+ equalArcMass (Position V H Tag L c) d * ((2 ^ c * d : ℕ) * (d : ℝ)) / d' := by
+ let S : ℝ := (2 ^ c * d : ℕ) * (d : ℝ)
+ have hS : S ≠ 0 := by dsimp only [S]; positivity
+ rw [equalArcMass, equalArcMass, P.card_positions, Nat.cast_mul, mul_assoc]
+ change 1 / (_ * (d' : ℝ)) = 1 / (_ * S) * S / d'
+ simp only [div_eq_mul_inv, mul_inv_rev]
+ calc
+ _ = (Fintype.card (Site V Tag L) : ℝ)⁻¹ * (S⁻¹ * S) * (d' : ℝ)⁻¹ := by
+ rw [inv_mul_cancel₀ hS]
+ ring
+ _ = _ := by ring
+
+/-- The exact packed role counts and the actual floor choice fit inside
+the output degree, so the regularization's common deficit exists. -/
+theorem packed_degree_budget {T : Type*} [Fintype T] (q : T → ℝ) (hq : ∀ t, 0 ≤ q t)
+ (htotal : ∑ t, q t = 4 / 3) (hc : 2 ≤ c) (hd : 0 < d) (d' : ℕ) :
+ d * pieceCount d c * ∑ t, count (2 ^ c * d) d d' (q t) ≤ d' := by
+ apply degree_budget q hq htotal (Nat.mul_pos (by positivity) hd) hd
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_add_of_le hc
+ have h : 2 ^ (2 + n) * d = 4 * (2 ^ n * d) := by rw [pow_add]; ring
+ simp only [pieceCount, h]
+ omega
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PackingLanes.lean b/lean/OAI/Computability/VPVNP/PackingLanes.lean
new file mode 100644
index 0000000000..57696e890d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PackingLanes.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.BitSlotIndex
+import OAI.Computability.VPVNP.SlotOtherEnd
+import OAI.Computability.VPVNP.SlotSeparation
+import Mathlib.Data.Nat.Log
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# Choosing and consuming binary lane coordinates
+
+Appendix C uses one bit per base color, enough bits to index an outgoing
+slot, and a tag large enough for the greedy exclusions. All three block
+lengths depend only on the degree. The remaining coordinates are arbitrary.
+The input may have any displacement on any directed base arc.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+/-- Split a binary vector into two coordinate blocks. Addition splits in the
+same way, so both blocks retain constant displacements on each base arc. -/
+def splitBitWord (a b : ℕ) : BitWord (a + b) ≃+ BitWord a × BitWord b where
+ toEquiv := (finSumFinEquiv.symm.arrowCongr (Equiv.refl (ZMod 2))).trans
+ (Equiv.sumArrowEquivProdArrow _ _ _)
+ map_add' _ _ := rfl
+
+/-- Logarithmic tag length sufficient to avoid all forbidden choices. -/
+def packingTagBits (d : ℕ) : ℕ := Nat.log 2 (2 * d * ((d + 1) + (d + 1) ^ 2)) + 1
+
+theorem packingTagBits_sufficient (d : ℕ) :
+ 2 * d * ((d + 1) + (d + 1) ^ 2) < 2 ^ packingTagBits d :=
+ Nat.lt_pow_succ_log_self (by decide) _
+
+/-- For degree `2^a` and `g` unused coordinates, this is the whole original
+lane length. Only the color and slot fields reduce the position count. -/
+abbrev packingLaneBits (a g : ℕ) :=
+ (2 * 2 ^ a + 1) + (a + (packingTagBits (2 ^ a) + g))
+
+/-- Separate the color, slot, tag, and remaining-lane fields. -/
+def packingFields (a g : ℕ) : BitWord (packingLaneBits a g) ≃+
+ BitWord (2 * 2 ^ a + 1) × (BitWord a × (BitWord (packingTagBits (2 ^ a)) × BitWord g)) :=
+ (splitBitWord _ _).trans ((AddEquiv.refl _).prodCongr
+ ((splitBitWord _ _).trans ((AddEquiv.refl _).prodCongr (splitBitWord _ _))))
+
+/-- Packing data for bit-word slots, tag shifts and residual lanes, with dyadic degree and the
+corresponding finite color bound. -/
+abbrev DyadicPackingData (V : Type*) (a g : ℕ) :=
+ PackingData V (BitWord a) (BitWord (packingTagBits (2 ^ a))) (BitWord g)
+ (2 ^ a) (2 * 2 ^ a + 1)
+
+variable {V : Type*} {a g : ℕ}
+
+/-- Reorder the actual arc coordinates after splitting its lane. -/
+def packingArcEquiv (V : Type*) (a g : ℕ) :
+ (V × Fin (2 ^ a)) × BitWord (packingLaneBits a g) ≃
+ Arc V (BitWord a) (BitWord (packingTagBits (2 ^ a))) (BitWord g) (2 ^ a) (2 * 2 ^ a + 1) where
+ toFun p :=
+ let f := packingFields a g p.2
+ (((p.1.1,f.2.2),p.1.2),f.1,f.2.1)
+ invFun p := ((p.1.1.1,p.1.2),(packingFields a g).symm (p.2.1,p.2.2,p.1.1.2))
+ left_inv := by rintro ⟨⟨x,i⟩, w⟩; simp
+ right_inv := by rintro ⟨⟨⟨x,t,h⟩,i⟩,u,k⟩; simp
+
+section Ordered
+
+variable (G : LiftedSlots V (2 ^ a) (BitWord (packingLaneBits a g)))
+
+/-- Construct the packing data by scanning the supplied base order. Candidate
+tags are enumerated by their binary integers, independently of the unused lanes. -/
+def orderedDyadicPacking {N : ℕ} (order : V ≃ Fin N) : DyadicPackingData V a g where
+ slots := G.base
+ color := G.base.orderedColor order
+ proper := G.base.orderedColor_proper order
+ slotLabel := bitWordFinEquiv a
+ offset := G.base.orderedTagOffsets order (bitWordFinEquiv (packingTagBits (2 ^ a)))
+ (fun p ↦ (packingFields a g (G.displacement p)).2.2.1) (packingTagBits_sufficient (2 ^ a))
+ bitShift p := (packingFields a g (G.displacement p)).1
+ slotShift p := (packingFields a g (G.displacement p)).2.1
+ siteShift p := (packingFields a g (G.displacement p)).2.2
+
+theorem orderedDyadicPacking_validTags {N : ℕ} (order : V ≃ Fin N) :
+ G.base.ValidTagOffsets (orderedDyadicPacking G order).tagShift
+ (orderedDyadicPacking G order).offset :=
+ G.base.orderedTagOffsets_valid order (bitWordFinEquiv (packingTagBits (2 ^ a)))
+ (fun p ↦ (packingFields a g (G.displacement p)).2.2.1) (packingTagBits_sufficient (2 ^ a))
+
+/-- The relabeling respects the directed endpoints, slot numbers, and all
+translated fields of the actual input for every choice of base order. -/
+theorem orderedDyadicPacking_actual {N : ℕ} (order : V ≃ Fin N)
+ (p : (V × Fin (2 ^ a)) × BitWord (packingLaneBits a g)) :
+ (orderedDyadicPacking G order).actual (packingArcEquiv V a g p) =
+ packingArcEquiv V a g (G.actualTarget p) := by
+ rcases p with ⟨e,w⟩
+ simp only [LiftedSlots.actualTarget_apply, packingArcEquiv, Equiv.coe_fn_mk, map_add]
+ rfl
+
+end Ordered
+
+variable [Finite V] (G : LiftedSlots V (2 ^ a) (BitWord (packingLaneBits a g)))
+
+/-- Apply the ordered construction using a chosen enumeration of a finite base. -/
+noncomputable def dyadicPacking : DyadicPackingData V a g := by
+ letI := Fintype.ofFinite V
+ exact orderedDyadicPacking G (Fintype.equivFin V)
+
+theorem dyadicPacking_validTags : G.base.ValidTagOffsets (dyadicPacking G).tagShift
+ (dyadicPacking G).offset := by
+ unfold dyadicPacking
+ exact orderedDyadicPacking_validTags G _
+
+theorem dyadicPacking_actual (p : (V × Fin (2 ^ a)) × BitWord (packingLaneBits a g)) :
+ (dyadicPacking G).actual (packingArcEquiv V a g p) =
+ packingArcEquiv V a g (G.actualTarget p) := by
+ unfold dyadicPacking
+ exact orderedDyadicPacking_actual G _ p
+
+/-- Position count before packing is `K` times the new count. The tag moves
+into the base, while the color and slot fields are removed. -/
+theorem packing_position_count (V : Type*) [Fintype V] (a g : ℕ) :
+ Fintype.card (V × BitWord (packingLaneBits a g)) =
+ (2 ^ (2 * 2 ^ a + 1) * 2 ^ a) * Fintype.card (Site V (BitWord (packingTagBits (2 ^ a)))
+ (BitWord g)) := by
+ simp only [packingLaneBits, Site, BitWord, Fintype.card_prod, Fintype.card_fun, Fintype.card_fin,
+ ZMod.card, pow_add]
+ ring
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PackingPreimages.lean b/lean/OAI/Computability/VPVNP/PackingPreimages.lean
new file mode 100644
index 0000000000..3dfc8919c3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PackingPreimages.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.SlotOtherEnd
+
+/-!
+# Old positions at each packed site
+
+In either layout of §7.2 each new site receives exactly `K = 2^c d` old
+positions. Half are thick and stay at their site. For thin positions the tag
+offset and the chosen side of the bundle permute the ports. Each of the new
+site's ports therefore receives the thin half of one old color-word fiber.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+variable {V H Tag L : Type*} {d c : ℕ}
+variable (P : PackingData V H Tag L d c)
+
+/-- Recover the old site and slot from a routed port. The only free field
+at that port is the bit word with its prescribed old color bit. -/
+private def positionBitFiber
+ (e : Site V Tag L × H ≃ Site V Tag L × Fin d) (s : Site V Tag L) (b : ZMod 2) :
+ {x : Position V H Tag L c // x.2.1 (P.color x.1.1) = b ∧ (e (x.1,x.2.2)).1 = s} ≃
+ Σ i : Fin d, {w : BitWord c // w (P.color (e.symm (s,i)).1.1) = b} := by
+ have recover (p : Site V Tag L × H) (hp : (e p).1 = s) : e.symm (s,(e p).2) = p := by
+ rw [← hp]
+ exact e.symm_apply_apply p
+ exact {
+ toFun := fun x ↦ ⟨(e (x.1.1,x.1.2.2)).2, x.1.2.1, by
+ rw [recover _ x.2.2]; exact x.2.1⟩
+ invFun := fun z ↦ ⟨((e.symm (s,z.1)).1,z.2.1,(e.symm (s,z.1)).2), z.2.2, by simp⟩
+ left_inv := fun x ↦ Subtype.ext (by simp [recover _ x.2.2])
+ right_inv := fun z ↦ by
+ obtain ⟨i,w,hw⟩ := z
+ apply Sigma.ext
+ · simp
+ · exact (Subtype.heq_iff_coe_eq (by simp)).mpr rfl }
+
+variable [Fintype V] [Fintype Tag] [Fintype L] [Fintype H]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+private theorem card_positionBitFiber
+ (e : Site V Tag L × H ≃ Site V Tag L × Fin d) (s : Site V Tag L) (b : ZMod 2) :
+ Fintype.card {x : Position V H Tag L c //
+ x.2.1 (P.color x.1.1) = b ∧ (e (x.1,x.2.2)).1 = s} = d * 2 ^ (c - 1) := by
+ rw [Fintype.card_congr (P.positionBitFiber e s b), Fintype.card_sigma]
+ simp [SlotPacking.card_oneBit]
+
+variable [AddCommGroup Tag] [AddCommGroup L]
+
+/-- Every new position has exactly `K` immediate old positions in its history,
+for either common layout. -/
+theorem card_placement (hc : 0 < c) (layout : Bool) (s : Site V Tag L) :
+ Fintype.card {x : Position V H Tag L c // P.placement layout x = s} = 2 ^ c * d := by
+ let keep := (Equiv.refl (Site V Tag L)).prodCongr P.slotLabel
+ let route := (P.offsetSite.prodCongr P.slotLabel).trans (P.layoutPorts layout)
+ let kept := fun x : Position V H Tag L c ↦ x.2.1 (P.color x.1.1) = 1 ∧ (keep (x.1,x.2.2)).1 = s
+ let moved := fun x : Position V H Tag L c ↦ x.2.1 (P.color x.1.1) = 0 ∧ (route (x.1,x.2.2)).1 = s
+ have hcases (x : Position V H Tag L c) : P.placement layout x = s ↔ kept x ∨ moved x := by
+ have hbit : x.2.1 (P.color x.1.1) = 0 ∨ x.2.1 (P.color x.1.1) = 1 :=
+ (by decide : ∀ b : ZMod 2, b = 0 ∨ b = 1) _
+ rcases hbit with h | h <;> cases layout <;>
+ simp [placement, thick, keep, kept, moved, route, layoutPorts, assignedBundle, h]
+ have hdisj : Disjoint kept moved := fun _ h₁ h₂ x hx ↦ by
+ exact one_ne_zero ((h₁ x hx).1.symm.trans (h₂ x hx).1)
+ rw [Fintype.card_congr (Equiv.subtypeEquivRight hcases),
+ Fintype.card_subtype_or_disjoint kept moved hdisj,
+ P.card_positionBitFiber keep s 1, P.card_positionBitFiber route s 0]
+ obtain ⟨n,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (Nat.ne_of_gt hc)
+ simp only [Nat.succ_sub_one, pow_succ]
+ ring
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PaddedQuery.lean b/lean/OAI/Computability/VPVNP/PaddedQuery.lean
new file mode 100644
index 0000000000..35ec6ca102
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PaddedQuery.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.HardnessQuery
+
+/-! # Projections at every length above the table size
+
+The query interpreter addresses the payload from the right end of its input.
+A pinned run of zero bits between its self-delimiting table and the payload
+therefore leaves all its queries unchanged. This gives the projection at a
+specified source length, as needed for tensor powers along an infinite set of
+lengths with small circuits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open UniversalMachine
+
+theorem weightedQuery_projection_at_length {R V Q : Type*} [CommRing R] [Fintype Q]
+ {k : ℕ} (p : QueryProgram k Q) (t : ℕ) (weight : Projection R (Fin k) V)
+ (n : ℕ) (hsize : (programPrefix (QueryMachine.machine p t)).length + k ≤ n) :
+ ∃ φ : Projection R (Fin n × Bool) V,
+ φ.hom (MvPolynomial.map (Int.castRingHom R) (P n)) =
+ weightedPredicate (fun x => p.eval x t p.start) weight := by
+ let q := QueryMachine.machine p t
+ let pre := programPrefix q
+ let padded := pre ++ List.replicate (n - (pre.length + k)) false
+ have hn : n = padded.length + k := by
+ have hs : pre.length + k ≤ n := hsize
+ simp [padded]
+ omega
+ have hc : q.extra = (t + 1) * Fintype.card Q * (k + 1) := by
+ simp [q, QueryMachine.machine, TableCompiler.compile, QueryMachine.Control, Nat.mul_assoc]
+ have hstates : t + 1 ≤ q.extra := by
+ have hQ : 0 < Fintype.card Q := Fintype.card_pos_iff.mpr ⟨p.start⟩
+ rw [hc]
+ exact (Nat.le_mul_of_pos_right _ hQ).trans (Nat.le_mul_of_pos_right _ (by omega))
+ have hpre : t + 2 ≤ padded.length := by
+ have h := queryPrefix_lower hstates
+ simpa only [padded, List.length_append] using h.trans (Nat.le_add_right _ _)
+ have hp : (pinVariables (R := R) padded.get (Equiv.refl (Fin k))).hom
+ (MvPolynomial.map (Int.castRingHom R) (P (padded.length+k))) =
+ booleanPolynomial fun x => ((p.eval x t p.start).toNat : R) := by
+ rw [map_P]
+ apply pairedPolynomial_pin
+ intro x
+ have hd : decode (padded ++ List.ofFn x) = some q := by
+ simp [padded, pre, List.append_assoc, decode_programPrefix]
+ apply congrArg (fun j : ℕ => (j : R))
+ change acceptingCount (Fin.append padded.get x) = _
+ simp only [acceptingCount, List.ofFn_fin_append, List.ofFn_get, hd]
+ exact QueryMachine.correct p t padded x _ (querySteps_le_clock rfl hpre)
+ rw [hn]
+ refine ⟨weight.comp (pinVariables padded.get (Equiv.refl (Fin k))), ?_⟩
+ rw [Projection.hom_comp, RingHom.comp_apply, hp, weightedPredicate_eq_projection]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairArenaBudget.lean b/lean/OAI/Computability/VPVNP/PairArenaBudget.lean
new file mode 100644
index 0000000000..9675476183
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairArenaBudget.lean
@@ -0,0 +1,202 @@
+import OAI.Computability.VPVNP.PairTraversalArena
+import OAI.Computability.VPVNP.CompressorDescriptorSquare
+import OAI.Computability.VPVNP.PairLinkSlack
+import OAI.Computability.VPVNP.CursorBranchCommunication
+import OAI.Computability.VPVNP.RAMFinite
+
+/-!
+# Native construction of the selected pair's DFS arena
+
+Place the ordered argument rows and their dispatch tags after the
+Appendix E directory. The final shared-bit array occupies the interval
+between them. The real worker traces use a vanishing fraction of the
+live group's budget, including the two probes and forty-seven
+instructions allowed for an enclosing transfer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRoles
+
+open Compression CursorBounds CursorNetwork Filter BurstRAM BurstRAM.PrivateRAM
+open CompressorRecords TraversalRows DirectoryRun LocalHistory NetworkKernel
+
+variable {w : ℕ}
+
+private def Worker.clock : Worker w → ℕ
+ | .leaf .. => 14
+ | .fiber _ cap .. => 7*cap+25
+
+private theorem worker_clock {W : Worker w} {m : Memory w} {rs : List (Report w)} (h : W.Run m rs) :
+ ∀ r ∈ rs, r.events.length < Worker.clock W := by
+ cases W <;> exact localSegment_event_bound ((runSegment_iff ..).mp h).1
+
+private theorem segments_clock {ws : List (Worker w)} {m : Memory w} {rs : List (Report w)} {K : ℕ}
+ (h : Segments ws m rs) (hk : ∀ W ∈ ws, Worker.clock W ≤ K) :
+ ∀ r ∈ rs, r.events.length < K := by
+ induction h with
+ | nil => simp
+ | @cons head tail m rs ss run rest ih =>
+ intro r hr
+ rcases List.mem_append.mp hr with pre | post
+ · exact (worker_clock run r pre).trans_le (hk head List.mem_cons_self)
+ · exact ih (fun W hW => hk W (List.mem_cons_of_mem _ hW)) r post
+
+private theorem role_clock {offset cap base : ℕ} {ls : List TaggedLayer} {m : Memory w}
+ {rs : List (Report w)} (h : RolePasses offset cap base ls m rs) :
+ ∀ r ∈ rs, r.events.length < 12 := by
+ induction h with
+ | nil => simp
+ | cons run rest ih =>
+ intro r hr
+ exact (List.mem_append.mp hr).elim (localSegment_event_bound ((runSegment_iff ..).mp run).1 r)
+ (ih r)
+
+private theorem workers_clock {A : Type*} {N Y : Network} {raw : Memory w}
+ {limit : ℕ} (c : TermChain A N Y) (ords : ChainOrders c) (old : Order N.Site)
+ (dirs : Directories raw limit c ords old) (cap previous base : ℕ) :
+ ∀ W ∈ workers c ords old dirs cap previous base, Worker.clock W ≤ 7*cap+25 := by
+ induction c generalizing previous base with
+ | done => simp [workers]
+ | more t rec tail ih =>
+ intro W hW
+ rcases List.mem_cons.mp hW with rfl | h
+ · rfl
+ · exact ih ords.2 ords.1 dirs.2 base _ _ h
+
+private theorem probes_le (es : List (Event w)) : countProbes es ≤ es.length := by
+ induction es with
+ | nil => rfl
+ | cons e es ih => cases e <;> simp [countProbes] <;> omega
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+/-- Native role and row reports on each selected branch, given the actual
+per-level preimage directories produced by the shrink and refresh passes.
+The array and report budgets are derived from the cursor parameters. -/
+theorem eventually_nativeArena (B : S.Templates) (u : PairExponents B.growthConstant)
+ (F : DescriptorSpace.Shape) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {start : ℕ → ℕ} (hstart : PolynomiallyBounded start) {ε : ℝ} (hε : 0 < ε)
+ (probeMargin : ℕ := 2) (tickMargin : ℕ := 47) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let w := wordBits b n
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let baseAddr := DescriptorSpace.endAddress
+ (DescriptorSpace.cursorLayout F b S.steps u.θ (start n) n)
+ ∀ (z : E.Choices) (m : Memory w),
+ let Y := E.finalState z
+ let ls := selectedLayers B f hf T hT X z
+ let rowWords := words B.recordLimit ls
+ let offset := rowWords + Y.totalWidth
+ let vs := executeLevels B f hf T hT X z
+ let c := E.termChain data z
+ let ords := branchOrders E data z
+ let old := siteOrder X
+ baseAddr + 2*rowWords + Y.totalWidth < min (2^w) (start n + (processorCount b n)^2) ∧
+ ∀ ds : (i : Fin vs.length) → LevelDirectory vs[i] m baseAddr,
+ let dirs := selectedDirectories B f hf T hT X z m baseAddr ds
+ let ws := Worker.leaf B.recordLimit baseAddr old.length ::
+ workers c ords old dirs B.recordLimit baseAddr
+ (address B.recordLimit baseAddr old.length)
+ ∃ ts rs, RolePasses offset B.recordLimit baseAddr (selected B f hf T hT X z) m ts ∧
+ Segments ws (after m (eventLog ts)) rs ∧
+ let out := after m (eventLog (ts++rs))
+ Reads w out offset B.recordLimit baseAddr (selected B f hf T hT X z) ∧
+ AllRows w out B.recordLimit baseAddr baseAddr ls ∧
+ (∀ r ∈ ts++rs, 1+r.probes+probeMargin ≤ liveBucket u.δ n ∧
+ r.events.length+tickMargin ≤ n) ∧
+ ((ts.length + rs.length + countProbes (eventLog (ts++rs)) : ℕ) : ℝ) <
+ ε * (processorCount b n : ℝ) * liveBucket u.δ n := by
+ let K := 2*(B.recordLimit+2)
+ let C := (2*B.recordLimit+6)*(S.steps+2)
+ let clock := 7*B.recordLimit+25
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ have hp := CursorRAM.bounded_positions b
+ have hword := CursorRAM.eventual_word_room b hb' (hstart.add (hp.pow 2))
+ have hd : (u.θ : ℝ) ≤ 1 := by
+ have h := (Rat.cast_lt (K := ℝ)).mpr u.theta_lt
+ norm_num at h
+ linarith only [h]
+ filter_upwards [DescriptorSpace.eventually_selected_square F B u b hb K, hword,
+ eventually_pairAccesses B u b hb C 1 hε, eventually_pairBurstSlack u probeMargin,
+ eventually_ge_atTop ((clock+tickMargin+3)^2), eventually_ge_atTop 3]
+ with n hs hw hbudget hslack hn hn₃
+ intro base lanes labels hD hT A _ f hf w X T E data baseAddr z m Y ls size off vs c ords old
+ have hh := hs (start n) labels hD hT A f hf z
+ have foot := selected_words_le B f hf T hT X z
+ change size ≤ (B.recordLimit+2)*Y.positions*B.growthConstant^T at foot
+ have room : baseAddr + 2*size + Y.totalWidth < start n + (processorCount b n)^2 := by
+ apply lt_of_le_of_lt _ hh
+ change baseAddr+2*size+Y.totalWidth ≤ baseAddr +
+ K*(X.positions+processorCount b n+Y.positions*B.growthConstant^T+Y.totalWidth)+1
+ dsimp only [K]
+ nlinarith only [foot,Nat.zero_le (B.recordLimit*(X.positions+processorCount b n+Y.totalWidth))]
+ have hR : processorCount b n ≤ initialPositions b n :=
+ (Nat.pow_le_pow_right Nat.zero_lt_two (addressBits_le_virtualBits b n hn₃)).trans
+ (Nat.le_mul_of_pos_right _ (by omega : 0 < virtualBits b n))
+ have fit := room.trans_le (Nat.add_le_add_left (Nat.pow_le_pow_left hR 2) _)
+ have hfit := fit.trans hw
+ refine ⟨lt_min hfit room, ?_⟩
+ intro ds dirs ws
+ obtain ⟨ts,rs,hrole,hrows,_,tags,rows,_,len,probes⟩ :=
+ native_arena B f hf T hT X z baseAddr Y.totalWidth m ds hfit
+ have hclock : ∀ r ∈ ts++rs, r.events.length < clock := by
+ intro r hr
+ rcases List.mem_append.mp hr with tag | row
+ · exact (role_clock hrole r tag).trans_le (by dsimp [clock]; omega)
+ · apply segments_clock hrows _ r row
+ intro worker hW
+ rcases List.mem_cons.mp hW with rfl | h
+ · dsimp [Worker.clock,clock]; omega
+ · exact workers_clock c ords old dirs B.recordLimit baseAddr _ _ h
+ have clock' : clock+tickMargin ≤ n := by
+ have := Nat.le_self_pow (by decide : 2 ≠ 0) (clock+tickMargin+3)
+ omega
+ have burst : clock+1+probeMargin ≤ liveBucket u.δ n := by
+ have hc : (clock+tickMargin+3 : ℝ)^2 ≤ n := by exact_mod_cast hn
+ have hsqrt : (clock+tickMargin+3 : ℝ) ≤ (n : ℝ)^(1/2 : ℝ) := by
+ rw [← Real.sqrt_eq_rpow]
+ exact Real.le_sqrt_of_sq_le hc
+ exact_mod_cast (by linarith only [hsqrt,hslack, Nat.cast_nonneg (α := ℝ) tickMargin] :
+ (clock : ℝ)+1+probeMargin ≤ (liveBucket u.δ n : ℝ))
+ refine ⟨ts,rs,hrole,hrows,tags,rows,fun r hr => ?_,?_⟩
+ · have he := hclock r hr
+ have hp : r.probes ≤ r.events.length := probes_le _
+ omega
+ · let l := n.log2+1
+ have ht : T ≤ l := by
+ apply le_trans _ (BurstRAM.clog_le_log2_succ n)
+ change ⌊(u.θ : ℝ)*Real.logb 2 n⌋₊ ≤ Nat.clog 2 n
+ rw [← Real.natCeil_logb_natCast 2 n]
+ apply (Nat.floor_le_floor (mul_le_of_le_one_left _ hd)).trans (Nat.floor_le_ceil _)
+ exact Real.logb_nonneg (by norm_num) (by exact_mod_cast (show 1 ≤ n by omega))
+ have ht' : (S.steps+1)*T+1 ≤ (S.steps+2)*l := by
+ have hmul := Nat.mul_le_mul_left (S.steps+1) ht
+ have hl : 1 ≤ l := Nat.succ_pos _
+ exact (Nat.add_le_add hmul hl).trans_eq (by ring)
+ have hcost : ts.length+rs.length+countProbes (eventLog (ts++rs)) ≤ C*X.positions*l := by
+ have h := Nat.add_le_add len probes
+ calc _ ≤ (2*B.recordLimit+6)*(((S.steps+1)*T+1)*X.positions) := h.trans_eq (by ring)
+ _ ≤ (2*B.recordLimit+6)*(((S.steps+2)*l)*X.positions) := by gcongr
+ _ = _ := by dsimp [C]; ring
+ have he : C*X.positions*l ≤ branchAccesses X Y c C 1 n := by
+ unfold branchAccesses
+ apply le_trans _ (Nat.le_add_right _ _)
+ rw [pow_one]
+ exact (Nat.mul_assoc C X.positions l).le.trans
+ (Nat.mul_le_mul_left C (Nat.le_add_right _ _))
+ exact (Nat.cast_le.mpr (hcost.trans he)).trans_lt (hbudget labels hD hT A f hf z).1
+
+end PairSimulation.TraversalRoles
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairCoefficient.lean b/lean/OAI/Computability/VPVNP/PairCoefficient.lean
new file mode 100644
index 0000000000..56967a39a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairCoefficient.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.ParseHistogram
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+import Mathlib.Data.Fintype.Pi
+
+/-!
+# The histogram coefficient of a primed pair
+
+For fixed exterior cut bits, `input s v` is the primed bit string at site `v`
+when the internal shared bits have assignment `s`. No machine-transcript
+validation is imposed on that assignment. Section 9.3 expands the product
+of all these sites' label queries over the integers. Its coefficient counts
+joint choices of internal bits, ordered parses, and leaf bijections with the
+prescribed histogram of terminal and binary productions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairCoefficient
+
+open MvPolynomial ParseGrammar
+open scoped Classical
+
+variable {Internal Site H : Type*} {n m : ℕ} [Fintype Internal] [Fintype Site] [Fintype H]
+
+/-- Each site makes its own ordered parse and its own assignment of its
+terminal occurrences to the distinct queried positions. -/
+abbrev Choices (H : Type*) (d : Fin n) (input : Internal → Site → Fin m → Bool) :=
+ (s : Internal) × ((v : Site) → ParseChoice H d (input s v))
+
+/-- All occurrences of one grammar label at all sites of the pair share one counter. -/
+noncomputable def jointHistogram (d : Fin n) (h : H) (input : Internal → Site → Fin m → Bool)
+ (c : Choices H d input) : GrammarLabel (Fin m × Bool) H n →₀ ℕ :=
+ ∑ v, histogram d h (c.2 v).1
+
+/-- The polynomial `F` in equation (9.4), before assigning scalars to any labels. -/
+noncomputable def jointPolynomial (d : Fin n) (h : H) (input : Internal → Site → Fin m → Bool) :
+ MvPolynomial (GrammarLabel (Fin m × Bool) H n) ℤ :=
+ ∑ s, ∏ v, labelQuery d h (input s v)
+
+/-- Fully expand the product over all sites before grouping equal label monomials. -/
+theorem jointPolynomial_eq_sum (d : Fin n) (h : H) (input : Internal → Site → Fin m → Bool) :
+ jointPolynomial d h input =
+ ∑ c : Choices H d input, monomial (jointHistogram d h input c) 1 := by
+ rw [jointPolynomial, Fintype.sum_sigma]
+ apply Finset.sum_congr rfl
+ intro s _
+ simp_rw [labelQuery_eq_sum_histogram]
+ rw [Fintype.prod_sum]
+ apply Finset.sum_congr rfl
+ intro choices _
+ exact (monomial_sum_one _ _).symm
+
+/-- Exact multiplicity of each histogram. The integer coefficient includes
+every choice of internal bits and every tuple of local parses with this histogram. -/
+theorem coeff_eq_count (d : Fin n) (h : H) (input : Internal → Site → Fin m → Bool)
+ (μ : GrammarLabel (Fin m × Bool) H n →₀ ℕ) :
+ (jointPolynomial d h input).coeff μ =
+ (Fintype.card {c : Choices H d input // jointHistogram d h input c = μ} : ℤ) := by
+ rw [jointPolynomial_eq_sum, coeff_sum]
+ simp only [coeff_monomial, Fintype.card_subtype]
+ convert! Finset.sum_boole (R := ℤ) (fun c : Choices H d input => jointHistogram d h input c = μ) Finset.univ using 2
+ split_ifs <;> rfl
+
+omit [Fintype Internal] in
+/-- A parse uses one label at each terminal and one at each binary node.
+This gives the component bound used for the `2r`-bit nominations in (9.4). -/
+theorem histogram_component_le (d : Fin n) (h : H) (input : Internal → Site → Fin m → Bool)
+ (c : Choices H d input) (a : GrammarLabel (Fin m × Bool) H n) :
+ jointHistogram d h input c a ≤ Fintype.card Site * (2 * d.val + 1) := by
+ rw [jointHistogram, Finsupp.finsetSum_apply]
+ calc
+ _ ≤ ∑ _v : Site, (2 * d.val + 1) := by
+ apply Finset.sum_le_sum
+ intro v _
+ rw [← histogram_sum d h (c.2 v).1]
+ exact Finset.single_le_sum (fun i _ => Nat.zero_le (histogram d h (c.2 v).1 i))
+ (Finset.mem_univ a)
+ _ = _ := by simp
+
+/-- For two groups of `R = 2^r` sites, the paper's `2r`-bit counters cover
+all histograms whenever `4n ≤ R` and the layer has degree `n`. -/
+theorem pair_counter_capacity (r n : ℕ) (hn : 0 < n) (hR : 4 * n ≤ 2 ^ r) :
+ (2 * 2 ^ r) * (2 * (n - 1) + 1) < 2 ^ (2 * r) := by
+ have h : 2 * (2 * (n - 1) + 1) < 2 ^ r := by omega
+ calc
+ _ = 2 ^ r * (2 * (2 * (n - 1) + 1)) := by ac_rfl
+ _ < 2 ^ r * 2 ^ r := Nat.mul_lt_mul_of_pos_left h (Nat.two_pow_pos r)
+ _ = _ := by rw [two_mul, pow_add]
+
+/-- Nominate every histogram whose individual counters fit in the chosen
+fixed width. Evaluating the primed pair polynomial over any field or
+commutative ring sums its monomials with the number of matching parses. -/
+theorem evaluate_by_nominations {A : Type*} [CommRing A]
+ [DecidableEq (GrammarLabel (Fin m × Bool) H n)]
+ (d : Fin n) (h : H) (input : Internal → Site → Fin m → Bool)
+ (value : GrammarLabel (Fin m × Bool) H n → A) (w : ℕ)
+ (hfit : Fintype.card Site * (2 * d.val + 1) < 2 ^ w) :
+ eval₂Hom (Int.castRingHom A) value (jointPolynomial d h input) =
+ ∑ μ : GrammarLabel (Fin m × Bool) H n → Fin (2 ^ w), (∏ a, value a ^ (μ a).val) *
+ (Fintype.card {c : Choices H d input // ∀ a, jointHistogram d h input c a = (μ a).val} : A) := by
+ let nominate (c : Choices H d input) (a : GrammarLabel (Fin m × Bool) H n) : Fin (2 ^ w) :=
+ ⟨jointHistogram d h input c a, (histogram_component_le d h input c a).trans_lt hfit⟩
+ let weight (μ : GrammarLabel (Fin m × Bool) H n → Fin (2 ^ w)) := ∏ a, value a ^ (μ a).val
+ rw [jointPolynomial_eq_sum, map_sum]
+ calc
+ _ = ∑ c : Choices H d input, weight (nominate c) := by
+ apply Finset.sum_congr rfl
+ intro c _
+ rw [eval₂Hom_monomial, map_one, one_mul, Finsupp.prod_fintype]
+ simp
+ _ = ∑ μ, ∑ _c : {c : Choices H d input // nominate c = μ}, weight μ :=
+ (Fintype.sum_fiberwise' nominate weight).symm
+ _ = _ := by
+ apply Finset.sum_congr rfl
+ intro μ _
+ have heq (c : Choices H d input) : nominate c = μ ↔
+ ∀ a, jointHistogram d h input c a = (μ a).val := by
+ constructor
+ · intro hnom a
+ exact congrArg Fin.val (congrFun hnom a)
+ · intro hnom
+ exact funext (fun a => Fin.ext (hnom a))
+ simp [weight, Fintype.card_subtype, heq, nsmul_eq_mul, mul_comm]
+
+end PairCoefficient
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairCounterReadFootprint.lean b/lean/OAI/Computability/VPVNP/PairCounterReadFootprint.lean
new file mode 100644
index 0000000000..f06929599a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairCounterReadFootprint.lean
@@ -0,0 +1,39 @@
+import OAI.Computability.VPVNP.PairSimulationCounters
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-! # The external reads of the native histogram flush -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.Counters
+
+open BurstRAM CompressorRecords.SourceTransport
+open private componentEvents word val_word from OAI.Computability.VPVNP.PairSimulationCounters
+
+/-- The flush reads each external component of the designated histogram suffix. -/
+theorem events_reads {w : ℕ} (priv : Word w → Word w) (m : Memory w) (src dst n : ℕ)
+ (fit : dst+n < 2^w) (allow : ℕ → Prop) (cells : ∀ i : Fin n, allow (dst+i.val)) :
+ Reads allow (events priv m src dst n) := by
+ induction n generalizing src dst m with
+ | zero =>
+ intro a v read
+ simp [events] at read
+ | succ n ih =>
+ intro a v read
+ rcases List.mem_append.mp read with head | rest
+ · simp only [componentEvents, List.mem_cons, List.not_mem_nil, reduceCtorEq,
+ Event.read.injEq, false_or, or_false] at head
+ rw [head.1, val_word (by omega)]
+ exact cells 0
+ · apply ih _ (src+1) (dst+1) (by omega) _ a v rest
+ intro i
+ have h := cells ⟨i.val+1, by omega⟩
+ simpa only [Nat.add_assoc, Nat.add_comm 1] using h
+
+end PairSimulation.Counters
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairDispatchedRowEffects.lean b/lean/OAI/Computability/VPVNP/PairDispatchedRowEffects.lean
new file mode 100644
index 0000000000..4d456ab43d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairDispatchedRowEffects.lean
@@ -0,0 +1,219 @@
+import OAI.Computability.VPVNP.PairVertexDispatch
+import OAI.Computability.VPVNP.PairVertexSelectedReport
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+
+/-!
+# Local row effects under the physical vertex dispatcher
+
+Each term pass and each cursor leaf selects its role by a tag lookup.
+The router adds this lookup to the role trace and preserves the returned
+suffix, the role's scratch update and its histogram increment. This lifts
+the role-specific decoder and emission proofs to the common DFS entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM DFS LocalHistory NetworkKernel NodeArguments TreeDecode CompressorRecords
+open CompressorRecords.SourceTransport (Reads)
+open scoped Fin.CommRing
+
+variable {W endAddr : ℕ} {m : Memory W} {offset node : Word W}
+ {saved : Scratch W endAddr} {role : NodeDispatch.Role}
+ {handlers : NodeDispatch.Role → HookParser W endAddr}
+
+/-- Inverting a successful dispatch recovers the selected role's job and
+the very same suffix. Conversely, each role success gives this wrapped job. -/
+theorem dispatcher_read_iff (tag : NodeDispatch.role (m (offset + node).val) = role)
+ {bits tail : List Bool} {job : VisitPath W endAddr} :
+ (dispatcher handlers m offset).read node saved bits = some (job, tail) ↔
+ ∃ body, (handlers role).read node saved bits = some (body, tail) ∧
+ job = dispatchJob m offset node saved body := by
+ simp only [dispatcher, tag, Option.map_eq_some_iff]
+ constructor
+ · rintro ⟨⟨body, rest⟩, hit, h⟩
+ cases h
+ exact ⟨body, hit, rfl⟩
+ · rintro ⟨body, hit, rfl⟩
+ exact ⟨(body, tail), hit, rfl⟩
+
+/-- All role tags use one probe at the tag address. The branches differ
+only in their number of ticks. -/
+theorem dispatchEvents_footprint (allow : ℕ → Prop) (tagCell : allow (offset + node).val) :
+ after m (dispatchEvents m offset node) = m ∧ Reads allow (dispatchEvents m offset node) := by
+ by_cases tag : m (offset + node).val = 0
+ all_goals
+ constructor
+ · simp only [dispatchEvents, NodeDispatch.events, tag, ite_true, ite_false]
+ rfl
+ · intro a v h
+ simp only [dispatchEvents, NodeDispatch.events, tag, ite_true, ite_false, List.mem_append,
+ List.mem_replicate, List.mem_cons, List.not_mem_nil, reduceCtorEq, and_false,
+ false_or, or_false, Event.read.injEq] at h
+ exact h.1 ▸ tagCell
+
+theorem dispatchJob_cost (body : VisitPath W endAddr) :
+ countProbes (dispatchJob m offset node saved body).trace = countProbes body.trace + 1 ∧
+ (dispatchJob m offset node saved body).trace.length ≤ body.trace.length + 9 := by
+ obtain ⟨p, t, _⟩ := dispatchEvents_cost m offset node
+ simp only [dispatchJob, countProbes_append, List.length_append, p]
+ omega
+
+theorem dispatchJob_realizes {L : Type} {hist : Scratch W endAddr → L → ℕ}
+ {semantic : VertexJob L} {body : VisitPath W endAddr} (real : RealizesJob hist semantic body) :
+ RealizesJob hist semantic (dispatchJob m offset node saved body) := by
+ refine ⟨real.address, ?_, fun s h => real.counts s h.2⟩
+ simp only [dispatchJob, PrimedInputRAM.Flow.choiceBits_append,
+ (dispatchEvents_cost m offset node).2.2,
+ List.nil_append, real.bits]
+
+variable {geometry rootFields leaf shrink refresh : Segment} {p regs : ℕ}
+ {A : Placement (segments geometry rootFields leaf shrink refresh) p regs}
+ {M : Machine W p regs 11}
+
+/-- The role body starts at its own entry and returns to the common DFS
+header. Its cost may use a different allowance from the full job's cost. -/
+def RoleJobGuard (A : Placement (segments geometry rootFields leaf shrink refresh) p regs)
+ (M : Machine W p regs 11) (m : Memory W) (role : NodeDispatch.Role) (allow : ℕ → Prop)
+ (cost : VisitPath W endAddr → Prop) (body : VisitPath W endAddr) : Prop :=
+ body.Linked M (A.entry (rolePart role)) (A.dfsPC 3) A.dfs m ∧ after m body.trace = m ∧
+ Reads allow body.trace ∧ cost body
+
+theorem dispatchJob_guard (linked : Contains A M) {G histBase : Word W}
+ {allow : ℕ → Prop} {rawCost cost : VisitPath W endAddr → Prop}
+ {body : VisitPath W endAddr} (resident : ResidentGeometry saved G offset histBase)
+ (tag : NodeDispatch.role (m (offset + node).val) = role) (tagCell : allow (offset + node).val)
+ (addr : body.node = node) (raw : RoleJobGuard A M m role allow rawCost body)
+ (charge : rawCost body → cost (dispatchJob m offset node saved body)) :
+ JobGuard A M m allow cost (dispatchJob m offset node saved body) := by
+ obtain ⟨noWrite, reads⟩ := dispatchEvents_footprint (m := m) allow tagCell
+ refine ⟨dispatchJob_linked linked resident tag addr raw.1, ?_, ?_, charge raw.2.2.2⟩
+ · change after m (dispatchEvents m offset node ++ body.trace) = m
+ simp only [after, List.foldl_append] at noWrite ⊢
+ rw [noWrite]
+ exact raw.2.1
+ · intro a v h
+ exact (List.mem_append.mp h).elim (reads a v) (raw.2.2.1 a v)
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R} {N : Network}
+ {valid : List Packet → Scratch W endAddr → Prop} {hist : Scratch W endAddr → L → ℕ}
+
+section Term
+
+variable {t : Term R N} {r : TermParsers f t} {ptr : t.output.Site → ℕ × ℕ}
+ {before : Packets N} {next : Packets t.output}
+ (tag : ∀ v, NodeDispatch.role (m (offset + ((ptr v).1 : Word W)).val) = role)
+
+include tag
+
+theorem dispatcher_nodeStep (raw : NodeStep (handlers role) valid r ptr before next) :
+ NodeStep (dispatcher handlers m offset) valid r ptr before next := by
+ constructor
+ · intro v z pending s bits job tail ready hit
+ obtain ⟨body, read, rfl⟩ := (dispatcher_read_iff (tag v)).mp hit
+ exact raw.sound v z pending s bits body tail ready read
+ · intro v z pending s a k tail ready
+ obtain ⟨body, read, frame⟩ := raw.complete v z pending s a k tail ready
+ exact ⟨_, (dispatcher_read_iff (tag v)).mpr ⟨body, read, rfl⟩, frame⟩
+
+/-- At a known role row, only the body must be matched against the term
+reader, and only its writes have to be checked against the child packets. -/
+theorem dispatcher_nodeStep_of_suffix
+ (suffix : ∀ v z pending s bits, valid (next v z :: pending) s →
+ ((handlers role).read ((ptr v).1 : Word W) s bits).map Prod.snd =
+ ((nodeReader r v z).read bits).map Prod.snd)
+ (write : ∀ v z pending s bits job tail a k, valid (next v z :: pending) s →
+ (handlers role).read ((ptr v).1 : Word W) s bits = some (job, tail) →
+ bits = r.nodeBits v a z k ++ tail → valid (children r before v a ++ pending) (job.update s)) :
+ NodeStep (dispatcher handlers m offset) valid r ptr before next :=
+ dispatcher_nodeStep tag (nodeStep_of_suffix (handlers role) valid r ptr before next suffix write)
+
+variable {G histBase : Word W} {allow : ℕ → Prop} {rawCost cost : VisitPath W endAddr → Prop}
+ (linked : Contains A M) (tagCell : ∀ v, allow (offset + ((ptr v).1 : Word W)).val)
+ (resident : ∀ v z pending s, valid (next v z :: pending) s →
+ ResidentGeometry s G offset histBase)
+ (charge : ∀ v s body, rawCost body → cost (dispatchJob m offset ((ptr v).1 : Word W) s body))
+
+include linked tagCell resident charge
+
+theorem dispatcher_emitsNode
+ (raw : EmitsNode valid hist (RoleJobGuard A M m role allow rawCost) r ptr before next) :
+ EmitsNode valid hist (JobGuard A M m allow cost) r ptr before next := by
+ intro v z a k pending s ready
+ obtain ⟨body, real, en, guard, frame⟩ := raw v z a k pending s ready
+ exact ⟨_, dispatchJob_realizes real, ⟨rfl, en⟩,
+ dispatchJob_guard linked (resident v z pending s ready) (tag v) (tagCell v) real.address guard
+ (charge v s body), frame⟩
+
+theorem dispatcher_emitsNode_of_read (steps : NodeStep (handlers role) valid r ptr before next)
+ (effect : ∀ v z a k pending s body, valid (next v z :: pending) s →
+ (handlers role).read ((ptr v).1 : Word W) s (r.nodeBits v a z k) = some (body, []) →
+ RealizesJob hist ⟨(ptr v).1, r.nodeBits v a z k, (r.witness v a z).exponents k⟩ body ∧
+ body.enabled s ∧ RoleJobGuard A M m role allow rawCost body) :
+ EmitsNode valid hist (JobGuard A M m allow cost) r ptr before next :=
+ dispatcher_emitsNode tag linked tagCell resident charge
+ (emitsNode_of_read valid hist _ (handlers role) r ptr before next steps effect)
+
+end Term
+
+section Leaf
+
+variable {P : SiteParsers f N} {ptr : N.Site → ℕ × ℕ} {input : Packets N}
+ (tag : ∀ v, NodeDispatch.role (m (offset + ((ptr v).1 : Word W)).val) = .leaf)
+
+include tag
+
+/-- The singleton cursor subtree returns exactly the body's scratch and
+suffix, for successful and rejected input streams alike. -/
+theorem dispatcher_leaf_subtrees
+ (raw : Subtrees (handlers .leaf) valid P (fun v => leafTree (ptr v)) input) :
+ Subtrees (dispatcher handlers m offset) valid P (fun v => leafTree (ptr v)) input := by
+ have same (v : N.Site) (s : Scratch W endAddr) (bits : List Bool) :
+ (dispatcher handlers m offset).decode [((ptr v).1 : Word W)] s bits =
+ (handlers .leaf).decode [((ptr v).1 : Word W)] s bits := by
+ simp only [HookParser.decode, dispatcher, tag v]
+ cases hit : (handlers .leaf).read ((ptr v).1 : Word W) s bits <;> rfl
+ intro v z
+ have old := raw v z
+ constructor
+ · intro pending s bits out tail ready hit
+ apply old.sound pending s bits out tail ready
+ exact (same v s bits).symm.trans hit
+ · intro pending s x tail ready
+ obtain ⟨out, hit⟩ := old.complete pending s x tail ready
+ exact ⟨out, (same v s _).trans hit⟩
+
+variable {G histBase : Word W} {allow : ℕ → Prop} {rawCost cost : VisitPath W endAddr → Prop}
+ (linked : Contains A M) (tagCell : ∀ v, allow (offset + ((ptr v).1 : Word W)).val)
+ (resident : ∀ v z pending s, valid (input v z :: pending) s →
+ ResidentGeometry s G offset histBase)
+ (charge : ∀ v s body, rawCost body → cost (dispatchJob m offset ((ptr v).1 : Word W) s body))
+
+include linked tagCell resident charge
+
+/-- A leaf emits one occurrence. Adding the tag lookup preserves that
+occurrence's bit code and increments, and links its path at the DFS entry. -/
+theorem dispatcher_leaf_emits
+ (raw : Emits valid hist (RoleJobGuard A M m .leaf allow rawCost) P input (leafJobs P ptr)) :
+ Emits valid hist (JobGuard A M m allow cost) P input (leafJobs P ptr) := by
+ apply leaf_emits valid hist _ P input ptr
+ intro v z x pending s ready
+ obtain ⟨jobs, paths⟩ := raw v z x pending s ready
+ have hs := paths.realized
+ simp only [leafJobs, List.forall₂_cons_left_iff, List.forall₂_nil_left_iff] at hs
+ obtain ⟨body, rest, real, rfl, rfl⟩ := hs
+ have guard := paths.framed body List.mem_cons_self
+ exact ⟨_, dispatchJob_realizes real, ⟨rfl, paths.ready.1⟩,
+ dispatchJob_guard linked (resident v z pending s ready) (tag v) (tagCell v) real.address guard
+ (charge v s body), paths.remaining⟩
+
+end Leaf
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairIndexedLevelChecks.lean b/lean/OAI/Computability/VPVNP/PairIndexedLevelChecks.lean
new file mode 100644
index 0000000000..e905f69ae3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairIndexedLevelChecks.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.PairSelectedLevelChecks
+import OAI.Computability.VPVNP.PairTraversalRoles
+
+/-!
+# Numerical layer bases in the selected worker contracts
+
+The physical header of an output layer follows the preceding layer's rows.
+Its count is the input size of the next selected pass. Thus local proofs can
+use the two consecutive indices of the published directory directly.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NetworkKernel CompressorRecords LocalHistory
+open NodeArguments Compression TraversalRows
+open TraversalRoles
+open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels
+
+variable {W endAddr : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+
+private noncomputable def mark (v : SelectedLevel B f hf) : TaggedLayer :=
+ ⟨levelLayer B f hf v, tagLevel B f hf v⟩
+
+private theorem mark_count (v : SelectedLevel B f hf) :
+ (mark B f hf v).layer.count = (siteOrder (v.pass.next v.term)).length := by
+ rw [mark,levelLayer_count]
+ change Fintype.card (v.pass.next v.term).network.Site = _
+ simpa only [Fintype.card_fin] using
+ (Fintype.card_congr (siteOrder (v.pass.next v.term)).entries).symm
+
+private theorem indexed_bases {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (K : E.MapWitnesses f) (r : ExecutionReaders E K) (o : PassOrigins B f hf E)
+ (z : E.Choices) (cap base : ℕ) (prev : TaggedLayer)
+ (hprev : prev.layer.count = (siteOrder X).length) :
+ let vs := collectLevels B f hf E K r o z
+ let tags := prev :: vs.map (mark B f hf)
+ ∀ i : Fin vs.length, layerBase cap base tags (i.val + 1) =
+ address cap (layerBase cap base tags i.val) (siteOrder vs[i].input).length := by
+ induction E generalizing base prev with
+ | done => exact fun i => Fin.elim0 i
+ | @more a g a' g' X p tail ih =>
+ let current : SelectedLevel B f hf := ⟨a,g,a',g',X,p,o.1,z.1,r.1.select.encode z.1⟩
+ let vs := collectLevels B f hf (tail z.1) (K.2 z.1) (r.2 z.1) (o.2 z.1) z.2
+ let tags := mark B f hf current :: vs.map (mark B f hf)
+ change ∀ i : Fin (current::vs).length, layerBase cap base (prev::tags) (i.val + 1) =
+ address cap (layerBase cap base (prev::tags) i.val) (siteOrder (current::vs)[i].input).length
+ intro i
+ cases i using Fin.cases with
+ | zero =>
+ simp only [Fin.val_zero,Fin.getElem_fin,layerBase_cons,layerBase_zero]
+ exact congrArg (address cap base) hprev
+ | succ j =>
+ simp only [Fin.val_succ,Fin.getElem_fin,List.getElem_cons_succ,layerBase_cons]
+ exact ih z.1 (K.2 z.1) (r.2 z.1) (o.2 z.1) z.2 (endPos cap base prev.layer)
+ (mark B f hf current) (mark_count B f hf current) j
+
+variable (hook : HookParser W endAddr) (valid : List Packet → Scratch W endAddr → Prop)
+ (hist : Scratch W endAddr → B.Entry → ℕ) (guard : VisitPath W endAddr → Prop)
+
+attribute [local irreducible] LevelChecks
+
+private theorem indexed_checks (cap : ℕ) (passes : List (SelectedLevel B f hf)) (pos : ℕ → ℕ)
+ (baseStep : ∀ i : Fin passes.length, pos (i.val + 1) =
+ address cap (pos i.val) (siteOrder passes[i].input).length)
+ (row : ∀ i : Fin passes.length,
+ LevelChecks B f hf hook valid hist guard cap (pos i.val) passes[i]) :
+ AllLevelChecks B f hf hook valid hist guard cap (pos 0) passes := by
+ induction passes generalizing pos with
+ | nil => trivial
+ | cons v vs ih =>
+ constructor
+ · exact row 0
+ · have next : pos 1 = address cap (pos 0) (siteOrder v.input).length := baseStep 0
+ rw [← next]
+ exact ih (fun j => pos (j+1)) (fun i => baseStep i.succ) (fun i => row i.succ)
+
+variable {n : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T hT X).Choices) (base : ℕ)
+
+/-- The consecutive input and output bases are the actual two physical
+positions of this indexed selected level in the frozen directory. -/
+theorem selected_level_bases :
+ let vs := executeLevels B f hf T hT X z
+ let tags := selected B f hf T hT X z
+ ∀ i : Fin vs.length, layerBase B.recordLimit base tags (i.val + 1) =
+ address B.recordLimit (layerBase B.recordLimit base tags i.val)
+ (siteOrder vs[i].input).length :=
+ indexed_bases B f hf _ _ _ _ z B.recordLimit base ⟨leafLayer (siteOrder X),.cursor⟩ rfl
+
+/-- A check for every physical level index supplies the recursive row
+checks used by the accepting-path and malformed-tape inductions. -/
+theorem selected_indexed
+ (check : let vs := executeLevels B f hf T hT X z
+ let tags := selected B f hf T hT X z
+ ∀ i : Fin vs.length, LevelChecks B f hf hook valid hist guard B.recordLimit
+ (layerBase B.recordLimit base tags i.val) vs[i]) :
+ AllLevelChecks B f hf hook valid hist guard B.recordLimit base
+ (executeLevels B f hf T hT X z) :=
+ by
+ let tags := selected B f hf T hT X z
+ rw [← layerBase_zero B.recordLimit base tags]
+ exact indexed_checks B f hf hook valid hist guard B.recordLimit (executeLevels B f hf T hT X z)
+ (layerBase B.recordLimit base tags) (selected_level_bases B f hf T hT X z base) check
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairLinkSlack.lean b/lean/OAI/Computability/VPVNP/PairLinkSlack.lean
new file mode 100644
index 0000000000..a55f88bce0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairLinkSlack.lean
@@ -0,0 +1,49 @@
+import OAI.Computability.VPVNP.CursorBranchBudget
+
+/-!
+# Slack for linking a pair stage inside the live call
+
+The enclosing control transfers add at most two external probes and
+forty-seven instructions. The compression exponents leave room for those
+fixed costs before the native cutoffs are applied.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open Compression Filter
+
+theorem eventually_pairBurstSlack {C₂ : ℕ} (u : PairExponents C₂) (margin : ℕ := 2) :
+ ∀ᶠ n : ℕ in atTop, (n : ℝ)^(1/2 : ℝ) + margin ≤ (liveBucket u.δ n : ℝ) := by
+ have ht : (u.θ : ℝ) < 1/100 := by simpa using (Rat.cast_lt (K := ℝ)).mpr u.theta_lt
+ have hd : (u.δ : ℝ) < (u.θ : ℝ)/10 := by simpa using (Rat.cast_lt (K := ℝ)).mpr u.delta_lt
+ have h := eventually_absorb_polylog ((margin : ℝ) + 1) 0 (show 1/2 < 1-(u.δ : ℝ) by linarith)
+ (show (0 : ℝ) < 1 by norm_num)
+ filter_upwards [h, eventually_ge_atTop 1] with n h hn
+ have h₁ := Real.one_le_rpow (show 1 ≤ (n : ℝ) by exact_mod_cast hn) (by norm_num : (0 : ℝ) ≤ 1/2)
+ simp only [pow_zero,mul_one,one_mul] at h
+ exact (by nlinarith only [h,mul_le_mul_of_nonneg_left h₁ (Nat.cast_nonneg (α := ℝ) margin)] :
+ (n : ℝ)^(1/2 : ℝ)+margin ≤ (n : ℝ)^(1-(u.δ : ℝ))).trans
+ (liveBucket_bounds (by linarith) hn).1
+
+set_option exponentiation.threshold 10000 in
+/-- Combine the metered map and cursor computation with the native setup,
+slicing and traversal costs and the enclosing control transfer. -/
+theorem pairTickSlack {n : ℕ} (hn : 4 ≤ n) :
+ n^132 + n^500 + 47 ≤ n^9999 := by
+ have h₁ := Nat.pow_le_pow_right (by omega : 0 < n) (by decide : 132 ≤ 500)
+ have h₃ := (by decide : 47 ≤ 4^3).trans (Nat.pow_le_pow_left hn 3)
+ have h₄ := Nat.pow_le_pow_right (by omega : 0 < n) (by decide : 3 ≤ 500)
+ calc _ ≤ n^501 := by
+ rw [pow_succ]
+ nlinarith only [h₁,h₃.trans h₄,Nat.mul_le_mul_left (n^500) hn]
+ _ ≤ n^9999 := Nat.pow_le_pow_right (by omega) (by decide)
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairMapSuccessBudget.lean b/lean/OAI/Computability/VPVNP/PairMapSuccessBudget.lean
new file mode 100644
index 0000000000..73653d4951
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairMapSuccessBudget.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.PairSimulationMapHandlerAction
+import OAI.Computability.VPVNP.PairSimulationMapHandlerClock
+import OAI.Computability.VPVNP.PairSimulationMapEntryExact
+
+/-! # Counting an actual finite matrix action from its trace
+
+The register-writer trace contributes its fixed loads. The remaining
+instructions are private ticks for the selector, the repeated rows and
+the histogram update. This bound applies at the scratch snapshot used
+by the surrounding resident loop.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapHandlerImage.Family
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry
+open BurstRAM PrivateRAM CompressorRecords MapConstants
+open private eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe
+open private lines_probes from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'} {t shared w : ℕ}
+
+private theorem dispatch_le {α : Type*} (ss : List α) (s : α) :
+ MapDriver.Program.dispatchSteps ss s ≤ 2*ss.length := by
+ induction ss with
+ | nil => exact le_rfl
+ | cons a as ih =>
+ rw [MapDriver.Program.dispatchSteps,List.length_cons,Nat.mul_succ]
+ split <;> omega
+
+private theorem tick_probes (n : ℕ) : countProbes (List.replicate n (.tick : Event w))=0 := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa only [List.replicate_succ,countProbes] using ih
+
+set_option maxHeartbeats 650000 in
+-- Unfold the physical selector and row clocks for this dependent matrix layout.
+theorem successEvents_cost (F : Family B t shared) (hp : ∀ e, 0 < p₀ e)
+ (I : LocalHistory.EntryInput B)
+ (hw : widthThreshold B ≤ w) (pub : Fin 5 → BurstRAM.Word w)
+ (state : BurstRAM.Word w) (m : Memory w) :
+ let key := (demandGrid B hp I.demand,I.party)
+ let es := F.successEvents hp I hw pub state m
+ es.length ≤ F.clock key (repetitions B I.demand) ∧ countProbes es = F.probes key := by
+ intro key es
+ let L := F.layout key
+ let P := MapInline.callProgram L
+ let u := repetitions B I.demand
+ let d := demandBits src dst I.party I.demandBits
+ let x := mapHalf G (fun _ ↦ inputBits) I.supplyBits
+ let fd := (fits_of_threshold B hw).2.1 key.1
+ let fs := (fits_of_threshold B hw).2.2.1
+ let words := (MapConstants.source (w:=w) L F.ordinal).publicData
+ let ports := (MapPortAgreement.ports G I.party L.core.edgeOrder).length
+ have bounded (θ : Fin u → Selector B) :
+ entryTicks hp I L F.ordinal hw θ ≤
+ L.lines.length+(1+3*ports)+MapNativeClock.cap B key.1 key.2 u := by
+ let rc := MapRowLoop.rowCap B key.1 key.2
+ let ticks :=
+ MapRowLoop.rowSteps B key.1 key.2 I.demand I.payload d x θ fd fs P.bank.keyPort words
+ have rows (i : Fin u) : ticks i ≤ rc :=
+ (MapRow.exactSteps_le_cap B key.1 (θ i) i key.2 I.demand I.payload d x
+ (fun e => MotifEntry.offset (fun l => basePayload B (θ l) e) i) fd (fs _)
+ (P.bank.keyPort _) words).trans
+ (Finset.single_le_sum (fun s _ => Nat.zero_le (MapRow.cap B key.1 s key.2))
+ (Finset.mem_univ (θ i)))
+ have body : P.driverTicks d x θ fd fs words ≤ (5+2*(selectorTable B).length+rc)*u+1 := by
+ unfold MapEntry.Program.driverTicks MapDriver.Program.exactSteps
+ apply Nat.add_le_add_right
+ calc
+ _ ≤ ∑ _ : Fin u, (5+2*(selectorTable B).length+rc) := by
+ apply Finset.sum_le_sum
+ intro i _
+ exact Nat.add_le_add (Nat.add_le_add_left (dispatch_le _ _) 5) (rows i)
+ _ = _ := by simp [Nat.mul_comm]
+ have guard := P.selector.successTicks_le (selectorCode B) θ ports
+ have numPorts := MapPortAgreement.ports_length_le G I.party L.core.edgeOrder
+ change ports ≤ 2*Fintype.card E at numPorts
+ have selector : P.selector.successTicks (selectorCode B) θ ports ≤
+ (7*(u*B.selectorBits)+6)*(2*Fintype.card E)+3+
+ ((6*B.selectorBits+1+(2*(selectorTable B).length+1)+5)*u+1) :=
+ guard.trans (Nat.add_le_add_right (Nat.add_le_add_right (Nat.mul_le_mul_left _ numPorts) _) _)
+ change L.lines.length+(1+3*ports)+P.successTicks d x θ fd fs words ≤ _
+ apply Nat.add_le_add_left
+ unfold MapEntry.Program.successTicks MapNativeClock.cap
+ change P.selector.successTicks (selectorCode B) θ ports + P.driverTicks d x θ fd fs words +
+ ((Fintype.card E+1)+(7*u+1)) ≤
+ (7*(u*B.selectorBits)+6)*(2*Fintype.card E)+3+
+ ((6*B.selectorBits+1+(2*(selectorTable B).length+1)+5)*u+1)+
+ ((5+2*(selectorTable B).length+rc)*u+1)+(Fintype.card E+1)+(7*u+1)
+ omega
+ let recipe := MapArgumentWriter.recipes (F.base key) (F.fields key)
+ have writer := eval_cost pub state m (RegisterSetup.lines recipe) (fun _ => 0)
+ have probes := lines_probes recipe pub state m (fun _ => 0)
+ have wrLen : (MapArgumentWriter.events (F.base key) (F.fields key) pub state m).length=
+ MapArgumentWriter.clock (F.base key) (F.fields key) := by
+ simp only [MapArgumentWriter.events,List.length_append,List.length_replicate,
+ MapArgumentWriter.clock]
+ exact congrArg (·+_) writer.1
+ have wrPr : countProbes (MapArgumentWriter.events (F.base key) (F.fields key) pub state m) =
+ F.probes key := by
+ simp only [MapArgumentWriter.events,countProbes_append,tick_probes,Nat.add_zero]
+ exact probes
+ change (F.successEvents hp I hw pub state m).length ≤ _ ∧
+ countProbes (F.successEvents hp I hw pub state m)=_
+ simp only [successEvents,List.length_append,List.length_replicate,
+ countProbes_append,tick_probes,Nat.add_zero]
+ refine ⟨?_,wrPr⟩
+ rw [wrLen]
+ apply Nat.add_le_add_left
+ apply Nat.mul_le_mul_left
+ change ((selectorRun G (selectorTable B) (selectorCode B) I.payload I.party x).1.elim
+ 0 (entryTicks hp I L F.ordinal hw)) ≤
+ L.lines.length+(1+3*ports)+MapNativeClock.cap B key.1 key.2 u
+ cases (selectorRun G (selectorTable B) (selectorCode B) I.payload I.party x).1 with
+ | none => exact Nat.zero_le _
+ | some θ => exact bounded θ
+
+end PairSimulation.MapHandlerImage.Family
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeCacheClock.lean b/lean/OAI/Computability/VPVNP/PairNativeCacheClock.lean
new file mode 100644
index 0000000000..e30c0596be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeCacheClock.lean
@@ -0,0 +1,46 @@
+import OAI.Computability.VPVNP.PairNativeCacheProgram
+import OAI.Computability.VPVNP.CursorDescriptorWords
+
+/-!
+# Clock for the native operand-cache initialization
+
+The arithmetic prelude and all 38 store/increment pairs together use at most
+one input length in native ticks at every sufficiently large length. The
+threshold is uniform in the live bucket size.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeCache
+
+open Filter LiveProgram NativeOperands
+
+theorem eventually_work_le (c : Constants) (a b B : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ H : ℕ,
+ work (args c) a b (AssemblerPublic.geometry B n H) + 76 ≤ n := by
+ let K := Finset.univ.sup (fun i => fieldCost 0 (args c i))
+ let A := 4*a + (a+b+109) + 38*(K*((B+10)^4+2))
+ filter_upwards [BurstRAM.eventually_polylog_le A 4] with n hn
+ let L := n.log2+1
+ have h1 : 1 ≤ L := Nat.succ_pos _
+ have hl : L ≤ L^4 := Nat.le_self_pow (by decide) _
+ have hwidth : CursorBounds.wordBits B n + 1 ≤ ((B+10)^4+2)*L^4 := by
+ simpa only [Nat.zero_add,Nat.clog_one_right,Nat.add_zero] using
+ CompressorRecords.word_plus_clog_le B n 0 (Nat.zero_le n)
+ intro H
+ apply (work_le c a b (AssemblerPublic.geometry B n H)).trans
+ change 4*a*L + (a+b+109) + 38*(K*(CursorBounds.wordBits B n+1)) ≤ n
+ refine le_trans ?_ hn
+ calc
+ _ ≤ 4*a*L^4 + (a+b+109)*L^4 + 38*(K*(((B+10)^4+2)*L^4)) :=
+ Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ hl)
+ (Nat.le_mul_of_pos_right _ (h1.trans hl))) (Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ hwidth))
+ _ = A*L^4 := by dsimp only [A]; ring
+
+end PairSimulation.NativeCache
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeCachePaper.lean b/lean/OAI/Computability/VPVNP/PairNativeCachePaper.lean
new file mode 100644
index 0000000000..385490c374
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeCachePaper.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.PairNativeCacheRun
+import OAI.Computability.VPVNP.LiveProgram
+
+/-! # The native cache initializes the prescribed auxiliary leaf sources -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeCache
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter.GuessWord
+open LiveProgram LeafSourceLoad LeafRegisterBank LeafStartup NativeOperands
+open CursorRouting CursorNetwork
+open scoped Fin.CommRing
+
+variable (c : Constants) {p : UniversalMachine.Program} {B n H : ℕ}
+ {i : Fin (2^(n^c.chainPower-1))}
+ (Q : Layout (CounterPublic.spec p c |>.lengths n i) n (addressWidth B n) H (CursorBounds.wordBits B n))
+ (D : PrimedCounter.Data Q (n^(c.circuitExponent+5)))
+
+/-- Cache preparation in the paper's actual eleven-operand row, using only
+the runtime cache-base register, the fixed exponents, and the parsed prefix.
+Each of the 38 private cells is exactly the scalar the virtual leaf reads. -/
+theorem paper_run (a b : ℕ) (hb : 0 < b) (hB : 1 ≤ B) (hn : 2 ≤ n)
+ (hH : H = 2^roundedUp a b n) (fit : PairNativeGeometry.Fits a b n (CursorBounds.wordBits B n))
+ (hp : Q.program = p) (hbase : Q.scratchBase = 2^CursorBounds.virtualBits B n) (hf : D.Fits)
+ (hroot : D.root.val = 0) (hw : 2 ≤ CursorBounds.wordBits B n)
+ (hc : 2^CursorBounds.virtualBits B n*2^roundedUp 1 4 n < 2^CursorBounds.wordBits B n)
+ {R pcs : ℕ} (reg : Fin (bankSize c) ↪ Fin R) (M : Machine (CursorBounds.wordBits B n) pcs R 11)
+ (hpub : M.publicData = Pieces.word (AssemblerPublic.geometry B n H) (CounterPublic.actualPrefix p) ∘
+ StageOperands.pair c)
+ (embed : Fin (NativeCacheTable.size (code c a b reg)) → Fin pcs) (finish : Instr 2 pcs R 11)
+ (rows : ∀ j, M.code (embed j) = (NativeCacheTable.row (code c a b reg) (storeSrc c reg)
+ (ptr c reg) (one c reg) embed finish j).resize (CursorBounds.wordBits B n))
+ (base : ℕ) (room : base+38 ≤ 2^(CursorBounds.wordBits B n)) (st : Config (CursorBounds.wordBits B n) pcs R)
+ (entry : st.pc = embed (NativeCacheTable.label (code c a b reg) (code c a b reg).entry))
+ (baseWord : st.reg (reg (saved (args c))) = (base : Word (CursorBounds.wordBits B n)))
+ (v : Position (CursorBounds.virtualBits B n))
+ (buf : Buffers (CursorBounds.virtualBits B n) (2^roundedUp 1 4 n) (CursorBounds.wordBits B n)) :
+ let g := AssemblerPublic.geometry B n H
+ let x := auxiliary D hw hc v buf
+ ∃ t ≤ work (args c) a b g+76, ∃ out,
+ Prefix M st (List.replicate t .tick) out ∧ out.pc = embed (NativeCacheTable.done (code c a b reg)) ∧
+ Cached base out.privateMem (fun j : Static 34 => sourceWord x D.pub j.dest) ∧
+ (∀ key : Word g.w, key.val < base ∨ base+38 ≤ key.val → out.privateMem key = st.privateMem key) ∧
+ out.persistent = st.persistent ∧ ∀ j, j ∉ Set.range reg → out.reg j = st.reg j := by
+ let g := AssemblerPublic.geometry B n H
+ let lit := CounterPublic.actualPrefix p
+ have h := paper_operands c Q D hB hn hp hbase hf hroot hw hc v buf
+ have hfits j : FieldFits g (expr c j) := by
+ have this := (h j).2
+ cases he : expr c j with
+ | geometry e => rwa [he] at this
+ | prefixLength | prefixWord => trivial
+ have h6 : (M.publicData 6).val = n := by
+ rw [hpub]; exact Nat.mod_eq_of_lt (PrimedInputRAM.Opcodes.pubNat_lt Q hf.assembler 1)
+ have h7 : (M.publicData 7).val = addressWidth B n := by
+ rw [hpub]; exact Nat.mod_eq_of_lt (PrimedInputRAM.Opcodes.pubNat_lt Q hf.assembler 3)
+ obtain ⟨t,ht,out,pre,stop,cache,rest,persistent,unchanged⟩ := run c g lit a b reg M hb (show 0 < n by omega) rfl
+ hH fit hfits h6 h7 (by rw [hpub]; rfl) (by rw [hpub]; rfl) embed finish rows base room st entry baseWord
+ exact ⟨t,ht,out,pre,stop,fun j => (cache j).trans (h j).1,rest,persistent,unchanged⟩
+
+end PairSimulation.NativeCache
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeCacheProgram.lean b/lean/OAI/Computability/VPVNP/PairNativeCacheProgram.lean
new file mode 100644
index 0000000000..9b29302041
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeCacheProgram.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairNativeOperandVector
+import OAI.Computability.VPVNP.PairNativeCacheTable
+import OAI.Computability.VPVNP.PairSimulationLeafCachedSources
+import OAI.Computability.VPVNP.PairSimulationLeafSourceOperands
+
+/-! # The private operand-cache program embedded in a final-vertex pair burst
+
+The native arithmetic reads only the eleven public operands and the runtime
+cache-base word. The store tail writes each result at its designated offset.
+All labels and registers can be relocated in the surrounding vertex table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeCache
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM LiveProgram NativeOperands LeafSourceLoad
+open scoped Fin.CommRing
+
+/-- Expression for the cache word at index `i`, in the order of the four virtual-machine
+parameters followed by the 34 auxiliary public operands. -/
+abbrev args (c : Constants) (i : Fin 38) : InputOperand := expr c ((slots 34)[i.val]'i.isLt)
+/-- Number of native registers allocated to evaluate all 38 expressions and retain their
+results for the cache stores. -/
+abbrev bankSize (c : Constants) := NativeOperands.registerCount (capacity (args c))
+
+/-- Index of a fixed leaf source in the cache vector, given by its offset from the private
+cache base. -/
+def number (j : Static 34) : Fin 38 := ⟨j.offset, by cases j <;> simp [Static.offset]; omega⟩
+/-- Register holding the evaluated word for leaf source `j` when the native arithmetic prelude
+finishes. -/
+def resultReg (c : Constants) (j : Static 34) : Fin (bankSize c) := src (args c) (number j)
+
+theorem args_number (c : Constants) (j : Static 34) : args c (number j) = expr c j := by
+ obtain ⟨i,hi,h⟩ := List.mem_iff_getElem.mp (mem_slots j)
+ have hn : j.offset = i := h ▸ slot_offset (k := 34) ⟨i,hi⟩
+ unfold args number
+ simp only [hn,h]
+
+/-- Native operand-vector program that derives the pair geometry and evaluates the 38 cache
+expressions using bucket parameters `a` and `b`. -/
+abbrev block (c : Constants) (a b : ℕ) := vector (args c) a b
+
+/-- Place the cache arithmetic in the caller's register bank through `reg`, keeping its eleven
+public operand indices. -/
+abbrev relocated {R : ℕ} (c : Constants) (a b : ℕ) (reg : Fin (bankSize c) ↪ Fin R) :=
+ PrimedCounter.renameFlow reg id (block c a b)
+
+/-- Standalone initializer that runs the pair's 38 operand expressions in their native bank,
+stores them at successive private addresses, and accepts. -/
+def template (c : Constants) (a b : ℕ) :=
+ NativeCacheTable.template (relocated c a b (Function.Embedding.refl _))
+ (resultReg c) (cursor (args c)) (unit (args c))
+
+theorem template_rows (c : Constants) (a b w : ℕ) (pub : Fin 11 → Word w) (i) :
+ ((template c a b).instantiate w pub).code i =
+ (NativeCacheTable.row (relocated c a b (Function.Embedding.refl _)) (resultReg c)
+ (cursor (args c)) (unit (args c)) id .accept i).resize w := rfl
+
+theorem work_le (c : Constants) (a b : ℕ) (g : Geometry) :
+ work (args c) a b g + 76 ≤ 4*a*(g.n.log2+1) + (a+b+109) +
+ 38*(Finset.univ.sup (fun i => fieldCost 0 (args c i)) * (g.w+1)) := by
+ have h := PairNativeGeometry.ticks_le a b g.n
+ change PairNativeGeometry.ticks a b g.n + 38*((Finset.univ.sup fun i => fieldCost 0 (args c i))*(g.w+1)) + 3 + 76 ≤ _
+ omega
+
+/-- Arithmetic prepares every store source in its actual native register,
+leaving registers outside the chosen embedding available to the caller. -/
+theorem prelude {R : ℕ} (c : Constants) (g : Geometry) (lit : LiteralPrefix)
+ (a b : ℕ) (reg : Fin (bankSize c) ↪ Fin R)
+ (hb : 0 < b) (hn : 0 < g.n) (hwidth : g.w = (g.d+10)^4) (hbucket : g.H = 2^roundedUp a b g.n)
+ (fit : PairNativeGeometry.Fits a b g.n g.w) (hf : ∀ j, FieldFits g (expr c j))
+ (pub : Fin 11 → Word g.w) (h6 : (pub 6).val = g.n) (h7 : (pub 7).val = g.d)
+ (h1 : pub 1 = Fin.ofNat _ lit.length) (h0 : pub 0 = Fin.ofNat _ lit.value)
+ (st : Word g.w) (m : Memory g.w) (rs : Regs g.w R) :
+ ∃ t ≤ work (args c) a b g, ∃ out,
+ Flow.Exec pub st (relocated c a b reg) rs m (List.replicate t .tick) out m ∧
+ (∀ j : Static 34, out (reg (resultReg c j)) = Pieces.word g lit (expr c j)) ∧
+ out (reg (cursor (args c))) = rs (reg (saved (args c))) ∧ out (reg (unit (args c))) = 1 ∧
+ ∀ j, j ∉ Set.range reg → out j = rs j := by
+ obtain ⟨t,ht,small,run,done⟩ := vector_run (args c) g lit a b hb hn hwidth hbucket fit
+ (fun i => hf _) pub h6 h7 h1 h0 st m (rs ∘ reg)
+ obtain ⟨out,large,restrict,other⟩ := PrimedCounter.liftExec reg id pub run rs rfl
+ refine ⟨t,ht,out,large,?_,(congrFun restrict _).trans done.pointer,(congrFun restrict _).trans done.one,other⟩
+ intro j
+ exact (congrFun restrict _).trans ((done.value (number j)).trans (congrArg (Pieces.word g lit) (args_number c j)))
+
+end PairSimulation.NativeCache
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeCacheRun.lean b/lean/OAI/Computability/VPVNP/PairNativeCacheRun.lean
new file mode 100644
index 0000000000..90b29128d4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeCacheRun.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairNativeCacheProgram
+import OAI.Computability.VPVNP.PairNativeFlowPrefix
+
+/-! # Executing the native 38-word private cache initializer
+
+The prefix ends at the continuation supplied by the surrounding vertex
+burst. The private cache holds every fixed virtual parameter and every
+auxiliary public word. External memory and binary choices are untouched.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeCache
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter.GuessWord
+open LiveProgram LeafSourceLoad NativeOperands
+open scoped Fin.CommRing
+
+variable {R pcs : ℕ} (c : Constants) (g : Geometry) (lit : LiteralPrefix) (a b : ℕ)
+ (reg : Fin (bankSize c) ↪ Fin R) (M : Machine g.w pcs R 11)
+
+/-- Arithmetic flow whose labels form the first part of the cache table in the enclosing
+machine. -/
+abbrev code := relocated c a b reg
+/-- Map each fixed leaf source to the enclosing machine register read by its private store
+instruction. -/
+abbrev storeSrc := reg ∘ resultReg c
+/-- Enclosing machine register that points to the private cell for the next cache store. -/
+abbrev ptr := reg (cursor (args c))
+/-- Enclosing machine register containing the unit increment used to advance the cache cursor. -/
+abbrev one := reg (unit (args c))
+
+/-- Native evidence for the one private computation that prepares the leaf
+cache, including the caller's register and private-memory frame. -/
+theorem run (hb : 0 < b) (hn : 0 < g.n) (hwidth : g.w = (g.d+10)^4)
+ (hbucket : g.H = 2^roundedUp a b g.n) (fit : PairNativeGeometry.Fits a b g.n g.w)
+ (hf : ∀ j, FieldFits g (expr c j)) (h6 : (M.publicData 6).val = g.n) (h7 : (M.publicData 7).val = g.d)
+ (h1 : M.publicData 1 = Fin.ofNat _ lit.length) (h0 : M.publicData 0 = Fin.ofNat _ lit.value)
+ (embed : Fin (NativeCacheTable.size (code c a b reg)) → Fin pcs) (finish : Instr 2 pcs R 11)
+ (rows : ∀ i, M.code (embed i) =
+ (NativeCacheTable.row (code c a b reg) (storeSrc c reg) (ptr c reg) (one c reg) embed finish i).resize g.w)
+ (base : ℕ) (room : base+38 ≤ 2^g.w) (st : Config g.w pcs R)
+ (entry : st.pc = embed (NativeCacheTable.label (code c a b reg) (code c a b reg).entry))
+ (baseWord : st.reg (reg (saved (args c))) = (base : Word g.w)) :
+ ∃ t ≤ work (args c) a b g+76, ∃ out,
+ Prefix M st (List.replicate t .tick) out ∧
+ out.pc = embed (NativeCacheTable.done (code c a b reg)) ∧
+ Cached base out.privateMem (fun j => Pieces.word g lit (expr c j)) ∧
+ (∀ x : Word g.w, x.val < base ∨ base+38 ≤ x.val → out.privateMem x = st.privateMem x) ∧
+ out.persistent = st.persistent ∧
+ ∀ j, j ∉ Set.range reg → out.reg j = st.reg j := by
+ let A := code c a b reg
+ let sreg := storeSrc c reg
+ let cur := ptr c reg
+ let un := one c reg
+ let pc := embed ∘ NativeCacheTable.pc A
+ let inc := embed ∘ NativeCacheTable.inc A
+ let vals := fun j => Pieces.word g lit (expr c j)
+ let ext : Memory g.w := fun _ => 0
+ obtain ⟨t,ht,out,arith,ready,hcur,hu,frame⟩ := prelude c g lit a b reg hb hn hwidth hbucket fit hf
+ M.publicData h6 h7 h1 h0 st.persistent ext st.reg
+ have linked := NativeCacheTable.linked_of_rows A sreg cur un M embed finish rows
+ let mid : Config g.w pcs R := ⟨pc 0,st.persistent,out,st.privateMem⟩
+ have head : Prefix M st (List.replicate t .tick) mid := by
+ have h := arith.toPrefix linked st.privateMem
+ have hst : (⟨embed (NativeCacheTable.label A A.entry),st.persistent,st.reg,st.privateMem⟩ : Config g.w pcs R) = st := by
+ change st.pc = embed (NativeCacheTable.label A A.entry) at entry
+ rw [← entry]
+ exact hst ▸ h
+ have stores (j : Fin (slots 34).length) : M.code (pc j.castSucc) = storeInstr sreg cur (inc j) (slots 34)[j] := by
+ rw [show pc j.castSucc = embed (NativeCacheTable.pc A j.castSucc) from rfl,rows,NativeCacheTable.row_store]
+ rfl
+ have advances (j : Fin (slots 34).length) : M.code (inc j) = incInstr cur un (pc j.succ) := by
+ rw [show inc j = embed (NativeCacheTable.inc A j) from rfl,rows,NativeCacheTable.row_advance]
+ rfl
+ have hsrc (j : Static 34) : sreg j ≠ cur := reg.injective.ne (temp_ne_fixed ((number j).val+1) 10)
+ have huc : un ≠ cur := reg.injective.ne (by
+ intro h; have := congrArg Fin.val h; change 11 = 10 at this; contradiction)
+ obtain ⟨final,tail,atEnd,mem⟩ := write_rows M sreg cur un hsrc huc (slots 34) vals pc inc
+ stores advances base mid rfl (hcur.trans baseWord) hu ready (by simpa using room)
+ have run := head.append tail
+ rw [← List.replicate_add,length_slots] at run
+ refine ⟨_,by omega,final,run,atEnd,mem.cached,?_,mem.persistent,?_⟩
+ · intro x hx; apply mem.outside; simpa using hx
+ · intro j hj; exact (mem.frame j (fun eq => hj ⟨cursor (args c),eq.symm⟩)).trans (frame _ hj)
+
+end PairSimulation.NativeCache
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeCacheTable.lean b/lean/OAI/Computability/VPVNP/PairNativeCacheTable.lean
new file mode 100644
index 0000000000..c338f4a9b8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeCacheTable.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PairSimulationLeafCacheWrite
+import OAI.Computability.VPVNP.PrimedInputRAMFlow
+
+/-!
+# A native arithmetic prelude followed by the pair's private cache stores
+
+The first addresses are the labels of the arithmetic flow. Its normal exit
+enters a chain of 38 private stores, each followed by one cursor increment.
+The standalone table accepts at the end. The same row emitter allows a
+larger scheduler to place these labels and supply the final continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeCacheTable
+
+open BurstRAM PrivateRAM PrimedInputRAM LeafSourceLoad
+variable {R p w : ℕ}
+
+/-- Number of private stores needed for the four fixed leaf parameters and 34 auxiliary
+operands. -/
+abbrev count := (slots 34).length
+/-- Instruction count for the arithmetic flow, two rows per cache word, and the continuation
+and rejection rows. -/
+def size (a : Flow R 11) := a.length + 2*count + 2
+
+/-- Address of a label from the arithmetic flow in the prefix of the cache instruction table. -/
+def label (a : Flow R 11) (l : a.Label) : Fin (size a) :=
+ ⟨(a.labels l).val,by have := (a.labels l).isLt; unfold size; omega⟩
+
+/-- The last even address is the final continuation. -/
+def pc (a : Flow R 11) (i : Fin (count+1)) : Fin (size a) :=
+ ⟨a.length + 2*i.val,by have := i.isLt; unfold size; omega⟩
+
+/-- Address of the cursor increment immediately following the private store for cache slot `i`. -/
+def inc (a : Flow R 11) (i : Fin count) : Fin (size a) :=
+ ⟨a.length + (2*i.val+1),by have := i.isLt; unfold size; omega⟩
+
+/-- Address reached after incrementing past the last cache word, where the enclosing program
+supplies its continuation. -/
+def done (a : Flow R 11) := pc a (Fin.last count)
+/-- Rejecting row targeted by a failed branch of the cache arithmetic. -/
+def bad (a : Flow R 11) : Fin (size a) := ⟨a.length+2*count+1,by unfold size; omega⟩
+
+/-- Emit one row with targets in an ambient scheduler's program-counter type. -/
+def row (a : Flow R 11) (src : Static 34 → Fin R) (cursor unit : Fin R)
+ (embed : Fin (size a) → Fin p) (finish : Instr 2 p R 11) (i : Fin (size a)) : Instr 2 p R 11 :=
+ if h : i.val < a.length then
+ ((a.code (a.labels.symm ⟨i.val,h⟩)).map (fun t => (t.map (embed ∘ label a)).getD (embed (pc a 0)))).emit
+ (embed (bad a))
+ else
+ let j := i.val - a.length
+ if h : j/2 < count then
+ let slot : Fin count := ⟨j/2,h⟩
+ if j%2 = 0 then storeInstr src cursor (embed (inc a slot)) (slots 34)[slot]
+ else incInstr cursor unit (embed (pc a slot.succ))
+ else if j = 2*count then finish else .reject
+
+variable (a : Flow R 11) (src : Static 34 → Fin R) (cursor unit : Fin R)
+
+theorem row_flow (embed : Fin (size a) → Fin p) (finish : Instr 2 p R 11) (i : a.Label) :
+ row a src cursor unit embed finish (label a i) =
+ ((a.code i).map (fun t => (t.map (embed ∘ label a)).getD (embed (pc a 0)))).emit (embed (bad a)) := by
+ simp [row,label,(a.labels i).isLt]
+
+theorem row_store (embed : Fin (size a) → Fin p) (finish : Instr 2 p R 11) (i : Fin count) :
+ row a src cursor unit embed finish (pc a i.castSucc) = storeInstr src cursor (embed (inc a i)) (slots 34)[i] := by
+ have hi : i.val < 38 := i.isLt
+ simp [row,pc,hi]
+
+theorem row_advance (embed : Fin (size a) → Fin p) (finish : Instr 2 p R 11) (i : Fin count) :
+ row a src cursor unit embed finish (inc a i) = incInstr cursor unit (embed (pc a i.succ)) := by
+ have hi : i.val < 38 := i.isLt
+ have half : (2*i.val+1)/2 = i.val := by omega
+ simp [row,inc,half,hi]
+
+theorem row_done (embed : Fin (size a) → Fin p) (finish : Instr 2 p R 11) :
+ row a src cursor unit embed finish (done a) = finish := by simp [row,done,pc]
+
+theorem row_bad (embed : Fin (size a) → Fin p) (finish : Instr 2 p R 11) :
+ row a src cursor unit embed finish (bad a) = .reject := by
+ simp [row,bad,Nat.add_assoc]
+
+/-- Assemble a two-bit-literal program with the supplied arithmetic entry, 38
+store-and-increment pairs, and an accepting continuation. -/
+def template : Template (size a) R 11 where
+ literalWidth := 2
+ entry := label a a.entry
+ code := row a src cursor unit id .accept
+
+/-- Installing these rows anywhere in a machine links the arithmetic flow
+to the first cache store. -/
+theorem linked_of_rows (M : Machine w p R 11) (embed : Fin (size a) → Fin p) (finish : Instr 2 p R 11)
+ (h : ∀ i, M.code (embed i) = (row a src cursor unit embed finish i).resize w) :
+ Flow.Linked M a (embed ∘ label a) (embed (pc a 0)) (embed (bad a)) := by
+ constructor
+ intro i
+ rw [Function.comp_apply,h,row_flow]
+
+variable (pub : Fin 11 → Word w)
+
+theorem linked :
+ Flow.Linked ((template a src cursor unit).instantiate w pub) a (label a) (pc a 0) (bad a) :=
+ linked_of_rows a src cursor unit _ id .accept (fun _ => rfl)
+
+theorem store_row (i : Fin count) :
+ ((template a src cursor unit).instantiate w pub).code (pc a i.castSucc) =
+ storeInstr src cursor (inc a i) (slots 34)[i] := by
+ change (row a src cursor unit id .accept (pc a i.castSucc)).resize w = _
+ rw [row_store]; rfl
+
+theorem advance_row (i : Fin count) :
+ ((template a src cursor unit).instantiate w pub).code (inc a i) = incInstr cursor unit (pc a i.succ) := by
+ change (row a src cursor unit id .accept (inc a i)).resize w = _
+ rw [row_advance]; rfl
+
+theorem done_row :
+ ((template a src cursor unit).instantiate w pub).code (done a) = .accept := by
+ change (row a src cursor unit id .accept (done a)).resize w = _
+ rw [row_done]; rfl
+
+theorem bad_row :
+ ((template a src cursor unit).instantiate w pub).code (bad a) = .reject := by
+ change (row a src cursor unit id .accept (bad a)).resize w = _
+ rw [row_bad]; rfl
+
+end PairSimulation.NativeCacheTable
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFlowPrefix.lean b/lean/OAI/Computability/VPVNP/PairNativeFlowPrefix.lean
new file mode 100644
index 0000000000..427c97f22a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFlowPrefix.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# From a tick-only structured flow to a native configuration prefix
+
+The linked guards execute a single local step. An elementary instruction
+whose event is a tick also has a local native successor and preserves both
+memories. Composing those successors yields the concrete endpoint and the
+exact instruction count independently of the behavior at the exit label.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Flow
+open BurstRAM PrivateRAM PrimedStackRAM PrimedCounter.GuessWord
+
+variable {w p r k : ℕ} {M : Machine w p r k} {st : Word w}
+ {op : Op r k} {a : PrimedInputRAM.Flow r k} {rs out : Regs w r} {m m' : Memory w}
+ {stop bad : Fin p} {es : List (Event w)}
+
+private theorem line_tick {label : (Flow.line op).Label → Fin p}
+ (h : op.effect M.publicData st rs m = some (.tick,out,m'))
+ (hl : Linked M (.line op) label stop bad) (priv : Word w → Word w) :
+ m' = m ∧ M.program.step ⟨label (Flow.line op).entry,st,rs,priv⟩ =
+ .localStep ⟨stop,st,out,priv⟩ := by
+ have hc := hl.atLabel (Flow.line op).entry
+ change M.code (label (Flow.line op).entry) = (op.emit stop bad).resize w at hc
+ change m' = m ∧ (M.code (label (Flow.line op).entry)).run M.publicData _ = _
+ rw [hc]
+ cases op <;> simp only [Op.effect, Option.some.injEq, Prod.mk.injEq, reduceCtorEq, false_and, true_and] at h
+ all_goals try (split at h <;> simp only [Option.some.injEq,Prod.mk.injEq,true_and,reduceCtorEq] at h)
+ all_goals first | contradiction | exact ⟨h.2.symm,by rw [← h.1]; rfl⟩ |
+ exact ⟨h.2.symm,by rw [← h.1]; simp_all [Op.emit,Instr.resize,Instr.run]⟩
+
+private theorem stepEq {l q : Fin r} {a b : PrimedInputRAM.Flow r k}
+ {label : (Flow.ifEq l q a b).Label → Fin p} (hl : Linked M (.ifEq l q a b) label stop bad)
+ (priv : Word w → Word w) :
+ M.program.step ⟨label (.inl ()),st,rs,priv⟩ = .localStep
+ ⟨if rs l = rs q then label (.inr (.inl a.entry)) else label (.inr (.inr b.entry)),st,rs,priv⟩ := by
+ change (M.code (label (.inl ()))).run M.publicData _ = _
+ erw [hl.atLabel (.inl ())]
+ rfl
+
+private theorem stepLt {l q : Fin r} {a b : PrimedInputRAM.Flow r k}
+ {label : (Flow.ifLt l q a b).Label → Fin p} (hl : Linked M (.ifLt l q a b) label stop bad)
+ (priv : Word w → Word w) :
+ M.program.step ⟨label (.inl ()),st,rs,priv⟩ = .localStep
+ ⟨if rs l < rs q then label (.inr (.inl a.entry)) else label (.inr (.inr b.entry)),st,rs,priv⟩ := by
+ change (M.code (label (.inl ()))).run M.publicData _ = _
+ erw [hl.atLabel (.inl ())]
+ rfl
+
+/-- Local steps in the structured derivation give a genuine native prefix
+from the entry registers to the exit registers. -/
+theorem Exec.toPrefix_of_ticks (h : Exec M.publicData st a rs m es out m')
+ (ht : ∀ e ∈ es, e = .tick) {label : a.Label → Fin p}
+ (hl : Linked M a label stop bad) (priv : Word w → Word w) :
+ m' = m ∧ Prefix M ⟨label a.entry,st,rs,priv⟩ es ⟨stop,st,out,priv⟩ := by
+ induction h generalizing stop with
+ | line he =>
+ have hz := ht _ (List.mem_cons_self ..)
+ subst hz
+ obtain ⟨hm,step⟩ := line_tick he hl priv
+ exact ⟨hm,.tick step (.nil _)⟩
+ | seq _ _ left right =>
+ obtain ⟨hm,pre⟩ := left (fun e he => ht e (List.mem_append_left _ he)) hl.seqLeft
+ obtain ⟨hm',suf⟩ := right (fun e he => ht e (List.mem_append_right _ he)) hl.seqRight
+ exact ⟨hm'.trans hm,pre.append suf⟩
+ | @ifEqYes _ _ _ _ input _ _ _ _ test _ ih =>
+ obtain ⟨hm,body⟩ := ih (fun e he => ht e (List.mem_cons_of_mem _ he)) hl.ifEqYes
+ refine ⟨hm,.tick ?_ body⟩
+ have step := stepEq (st := st) (rs := input) hl priv
+ rw [ite_eq_left test] at step
+ exact step
+ | @ifEqNo _ _ _ _ input _ _ _ _ test _ ih =>
+ obtain ⟨hm,body⟩ := ih (fun e he => ht e (List.mem_cons_of_mem _ he)) hl.ifEqNo
+ refine ⟨hm,.tick ?_ body⟩
+ have step := stepEq (st := st) (rs := input) hl priv
+ rw [ite_eq_right test] at step
+ exact step
+ | @ifLtYes _ _ _ _ input _ _ _ _ test _ ih =>
+ obtain ⟨hm,body⟩ := ih (fun e he => ht e (List.mem_cons_of_mem _ he)) hl.ifLtYes
+ refine ⟨hm,.tick ?_ body⟩
+ have step := stepLt (st := st) (rs := input) hl priv
+ rw [ite_eq_left test] at step
+ exact step
+ | @ifLtNo _ _ _ _ input _ _ _ _ test _ ih =>
+ obtain ⟨hm,body⟩ := ih (fun e he => ht e (List.mem_cons_of_mem _ he)) hl.ifLtNo
+ refine ⟨hm,.tick ?_ body⟩
+ have step := stepLt (st := st) (rs := input) hl priv
+ rw [ite_eq_right test] at step
+ exact step
+ | branchYes _ _ | branchNo _ _ => cases ht _ (List.mem_cons_self ..)
+ | whileDone test =>
+ refine ⟨rfl,.tick ?_ (.nil _)⟩
+ change (M.code (label (.inl ()))).run M.publicData _ = _
+ erw [hl.atLabel (.inl ())]
+ simp [code,Jump.map,Jump.emit,Instr.resize,Instr.run,test]
+ | whileStep test _ _ body rest =>
+ obtain ⟨hm,hbody⟩ := body (fun e he => ht e (List.mem_cons_of_mem _ (List.mem_append_left _ he))) hl.loopBody
+ obtain ⟨hm',hrest⟩ := rest (fun e he => ht e (List.mem_cons_of_mem _ (List.mem_append_right _ he))) hl
+ refine ⟨hm'.trans hm,.tick ?_ (hbody.append hrest)⟩
+ change (M.code (label (.inl ()))).run M.publicData _ = _
+ erw [hl.atLabel (.inl ())]
+ simp [code,Jump.map,Jump.emit,Instr.resize,Instr.run,test]; rfl
+
+/-- Specialization used by the operand and cache arithmetic, which supply
+their tick count directly. -/
+theorem Exec.toPrefix {ticks : ℕ}
+ (h : Exec M.publicData st a rs m (List.replicate ticks .tick) out m')
+ {label : a.Label → Fin p} (hl : Linked M a label stop bad) (priv : Word w → Word w) :
+ Prefix M ⟨label a.entry,st,rs,priv⟩ (List.replicate ticks .tick) ⟨stop,st,out,priv⟩ :=
+ (h.toPrefix_of_ticks (fun _ he => (List.mem_replicate.mp he).2) hl priv).2
+
+end PrimedInputRAM.Flow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameArithmetic.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameArithmetic.lean
new file mode 100644
index 0000000000..f64a2c6cd5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameArithmetic.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PairNativeFrameReads
+import OAI.Computability.VPVNP.PrimedStackRAMNodeTable
+
+/-!
+# Word arithmetic for the terminal vertex's pair frame
+
+After the six descriptor reads, the native program computes the histogram
+base, graph arena, cache base and remaining frame fields. Each equality is
+in the machine's word ring, so the code equations also hold when an
+intermediate wraps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+open BurstRAM PrivateRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private def degreeCode : ℕ → Code
+ | 0 => .line (.constant 16 0)
+ | d+1 => .seq (degreeCode d) (.line (.binary .add 16 16 15))
+
+private theorem degree_run (pub : Fin 11 → Word w) (st : Word w) (m : Memory w) (rs : Regs w 24)
+ (one : rs 15 = 1) (d : ℕ) :
+ Flow.Exec pub st (degreeCode d) rs m (List.replicate (d+1) .tick) (Function.update rs 16 (d : Word w)) m := by
+ induction d with
+ | zero => exact .line rfl
+ | succ d ih =>
+ let t := Function.update rs (16 : R) (d : Word w)
+ have h : Flow.Exec pub st (.line (.binary .add 16 16 15)) t m [.tick]
+ (Function.update rs 16 ((d+1 : ℕ) : Word w)) m := by
+ apply Flow.Exec.line
+ simp [Op.effect,BinaryOp.eval,t,one]
+ simpa only [degreeCode,List.replicate_succ',List.replicate_one] using ih.seq h
+
+private def tailCode : Code := straight (.publicWord 7 3) [
+ .publicWord 9 6, .publicWord 19 9, .copy 12 9, .copy 13 1,
+ .binary .add 10 16 16, .binary .mul 10 10 9, .binary .add 10 10 15,
+ .binary .add 14 3 17, .binary .mul 14 10 14, .binary .add 14 9 14,
+ .binary .add 2 14 19, .copy 18 2,
+ .binary .mul 11 9 9, .binary .mul 11 11 11, .binary .mul 11 11 9, .binary .add 11 2 11]
+
+/-- Native program that constructs the fixed degree in register 16 and uses the loaded header
+words to compute the private frame addresses. -/
+def arithmetic (degree : ℕ) : Code := .seq (degreeCode degree) tailCode
+
+/-- Word distance between consecutive node argument packets, equal to twice the degree times
+the public input length plus one. -/
+def argumentStride (pub : Fin 11 → Word w) (degree : ℕ) : Word w :=
+ 2*(degree : Word w)*pub 6+1
+
+/-- Histogram base as a machine word, obtained by skipping one argument packet per address
+below the exclusive end of the node rows. -/
+def histWord (pub : Fin 11 → Word w) (rs : Regs w 24) (degree : ℕ) : Word w :=
+ pub 6 + argumentStride pub degree * (rs 3 + rs 17)
+
+/-- Base word of the graph arena and its geometry frame, immediately after the histogram's
+public number of label slots. -/
+def graphWord (pub : Fin 11 → Word w) (rs : Regs w 24) (degree : ℕ) : Word w :=
+ histWord pub rs degree + pub 9
+
+private def tailBank (pub : Fin 11 → Word w) (s : Regs w 24) : Regs w 24 :=
+ let n := pub 6
+ let square := n*n
+ let degree2 := s 16+s 16
+ let stride := degree2*n+s 15
+ let rows := s 3+s 17
+ let hist := n+stride*rows
+ let G := hist+pub 9
+ let fields : List (R × Word w) := [(7,pub 3),(9,n),(19,pub 9),(12,n),(13,s 1),
+ (10,degree2),(10,degree2*n),(10,stride),
+ (14,rows),(14,stride*rows),(14,hist),(2,G),(18,G),
+ (11,square),(11,square*square),(11,square*square*n),(11,G+square*square*n)]
+ fields.foldl (fun rs j => Function.update rs j.1 j.2) s
+
+/-- Register bank obtained by installing the degree in register 16 and carrying out the frame
+arithmetic updates in instruction order. -/
+def arithmeticBank (pub : Fin 11 → Word w) (rs : Regs w 24) (degree : ℕ) :=
+ tailBank pub (Function.update rs 16 (degree : Word w))
+
+/-- The fixed post-read program emits only ticks, for an exact cost of the
+degree plus eighteen native instructions. -/
+theorem arithmetic_run (pub : Fin 11 → Word w) (st : Word w) (m : Memory w)
+ (rs : Regs w 24) (degree : ℕ) (one : rs 15 = 1) :
+ Flow.Exec pub st (arithmetic degree) rs m (List.replicate (degree+18) .tick)
+ (arithmeticBank pub rs degree) m := by
+ let s := Function.update rs (16 : R) (degree : Word w)
+ have tail : Flow.Exec pub st tailCode s m (List.replicate 17 .tick) (tailBank pub s) m :=
+ (Flow.once_sound pub st false _ s m rfl).1
+ rw [show degree+18 = (degree+1)+17 by omega,List.replicate_add]
+ exact (degree_run pub st m rs one degree).seq tail
+
+/-- Register equations after address computation, including the graph, histogram and cache
+bases, the frame fields, and preservation of the loaded descriptor registers. -/
+structure ArithmeticValues (pub : Fin 11 → Word w) (rs : Regs w 24) (degree : ℕ) (out : Regs w 24) : Prop where
+ graph : out 2 = graphWord pub rs degree
+ shadow : out 7 = pub 3
+ length : out 9 = pub 6
+ iterations : out 10 = 2*(degree : Word w)*(pub 6)+1
+ cache : out 11 = graphWord pub rs degree + (pub 6)^5
+ copyLength : out 12 = pub 6
+ role : out 13 = rs 1
+ histogram : out 14 = histWord pub rs degree
+ cursor : out 18 = graphWord pub rs degree
+ preserved : ∀ i ∈ ([0,1,3,4,5,6,8,15,17] : List R), out i = rs i
+
+theorem arithmetic_values (pub : Fin 11 → Word w) (rs : Regs w 24) (degree : ℕ) (one : rs 15 = 1) :
+ ArithmeticValues pub rs degree (arithmeticBank pub rs degree) := by
+ let stride := ((degree : Word w)+degree)*pub 6+rs 15
+ let histogram := pub 6 + stride*(rs 3+rs 17)
+ let graph := histogram+pub 9
+ have hs : stride = argumentStride pub degree := by simp only [stride,argumentStride,one,two_mul]
+ have hh : histogram = histWord pub rs degree := by simp only [histogram,histWord,hs]
+ have hg : graph = graphWord pub rs degree := by simp only [graph,graphWord,hh]
+ refine ⟨hg,rfl,rfl,hs,?_,rfl,rfl,hh,hg,?_⟩
+ · change graph + (pub 6*pub 6)*(pub 6*pub 6)*pub 6 = _
+ rw [hg]; ring
+ · intro i hi
+ simp only [List.mem_cons,List.not_mem_nil,or_false] at hi
+ rcases hi with rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl|rfl <;> rfl
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameDescriptor.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameDescriptor.lean
new file mode 100644
index 0000000000..ce8e2db452
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameDescriptor.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.PairNativeFrameLeaf
+import OAI.Computability.VPVNP.PairTerminalLayout
+import OAI.Computability.VPVNP.PairTerminalPrefixLayout
+import OAI.Computability.VPVNP.PairSimulationCounters
+
+/-! # Geometry fields of the native terminal bootstrap and prefix scan
+
+Six header cells survive the width-prefix scan. The separately computed
+role offset is passed in a saved register. Together these seven values
+determine the geometry installed by each final vertex.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords DescriptorSpace Compression TerminalPrefix
+open scoped Fin.CommRing
+
+variable {w a g : ℕ}
+
+theorem regions_eq (degree n firstRow rowWords labels : ℕ) :
+ regions degree n firstRow rowWords labels =
+ TerminalLayout.privateRegions degree n (firstRow+rowWords) labels := rfl
+
+/-- Agreement of six terminal-header cells with the supplied row interval, row stride, two
+radices and auxiliary shadow span. -/
+structure Readback (m : Memory w) (header : Word w) (firstRow rowWords stride baseRadix laneRadix : ℕ)
+ (shadowSpan : Word w) : Prop where
+ row : m (header+4).val = (firstRow : Word w)
+ words : m (header+5).val = (rowWords : Word w)
+ pitch : m (header+15).val = (stride : Word w)
+ base : m (header+18).val = (baseRadix : Word w)
+ lane : m (header+19).val = (laneRadix : Word w)
+ span : m (header+20).val = shadowSpan
+
+private theorem offset_val (header : Word w) {j : ℕ} (fit : header.val+32 ≤ 2^w) (hj : j < 32) :
+ (header + (j : Word w)).val = header.val+j := by
+ rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j < 2^w),Nat.mod_eq_of_lt (by omega)]
+
+theorem bootstrap_readback (L : Layout) (last : ℕ) (A : TerminalBootstrap.Header L last) (cap r : ℕ)
+ (pub : Fin 11 → Word w) (m : Memory w) (state : Word w) (ready : TerminalBootstrap.Ready L last A pub m)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ L.base+2^r*2^r)
+ (room : L.base+2^r*2^r ≤ 2^w) :
+ Readback (after m (TerminalBootstrap.report L.shape cap pub state m).events) (Worker.header pub)
+ (endAddress L) (A.rowWords cap) (cap+2) A.baseRadix A.laneRadix (TerminalBootstrap.shadowSpan pub m) := by
+ have hb := header_val L pub r ready.workspace exp hr reserve room
+ have fit : (Worker.header pub).val+32 ≤ 2^w := by rw [hb,TerminalBootstrap.address]; omega
+ have actual := (TerminalBootstrap.native L last A cap pub m state ready r exp hr reserve room).2.2.1
+ have field (j : Fin 21) :
+ after m (TerminalBootstrap.report L.shape cap pub state m).events (Worker.header pub + (j.val : Word w)).val =
+ TerminalBootstrap.values L last A cap pub m j := by
+ rw [offset_val _ fit (by have := j.isLt; omega),hb]; exact actual j
+ exact ⟨field 4,field 5,field 15,field 18,field 19,field 20⟩
+
+variable {header span : Word w} {m : Memory w} {firstRow rowWords stride baseRadix laneRadix : ℕ}
+
+theorem Readback.transfer (h : Readback m header firstRow rowWords stride baseRadix laneRadix span)
+ {later : Memory w} (stable : ∀ j ∈ ([4,5,15,18,19,20] : List ℕ),
+ later (header+(j : Word w)).val = m (header+(j : Word w)).val) :
+ Readback later header firstRow rowWords stride baseRadix laneRadix span :=
+ ⟨(stable 4 (by decide)).trans h.row,(stable 5 (by decide)).trans h.words,
+ (stable 15 (by decide)).trans h.pitch,(stable 18 (by decide)).trans h.base,
+ (stable 19 (by decide)).trans h.lane,(stable 20 (by decide)).trans h.span⟩
+
+theorem Readback.after_scan {pub : Fin 11 → Word w} (h : Readback m (Worker.header pub)
+ firstRow rowWords stride baseRadix laneRadix span) {X : State a g} {T : IncidenceDirectory w}
+ {prefixBase : Word w} {rs : List (Report w)} (run : Segment.Run pub X T prefixBase m rs)
+ (fit : (Worker.header pub).val+32 ≤ 2^w) (below : prefixBase.val+arcCount X ≤ (Worker.header pub).val) :
+ Readback (after m (eventLog rs)) (Worker.header pub) firstRow rowWords stride baseRadix laneRadix span := by
+ apply h.transfer
+ intro j hj
+ have options : j = 4 ∨ j = 5 ∨ j = 15 ∨ j = 18 ∨ j = 19 ∨ j = 20 := by simpa using hj
+ have addr := offset_val (Worker.header pub) fit (by omega : j < 32)
+ have a12 : (Worker.header pub+12).val = (Worker.header pub).val+12 := offset_val _ fit (by decide : 12<32)
+ have a14 : (Worker.header pub+14).val = (Worker.header pub).val+14 := offset_val _ fit (by decide : 14<32)
+ have fresh := run.stored.outside (Worker.header pub+(j : Word w)).val (by rw [addr,a12]; omega)
+ (.inr (by rw [addr]; omega))
+ rw [fresh]
+ apply ite_eq_right
+ rw [addr,a14]; omega
+
+/-- A completed vertex adds its histogram strictly below the terminal
+header. Every following vertex therefore reads the same six operands. -/
+theorem Readback.addHistogram (h : Readback m header firstRow rowWords stride baseRadix laneRadix span)
+ {t : ℕ} (base grammar : ℕ) (hist : Fin t → ℕ) (below : base+grammar+t ≤ header.val)
+ (fit : header.val+32 ≤ 2^w) :
+ Readback (Counters.addHistogram base grammar hist m) header firstRow rowWords stride baseRadix laneRadix span := by
+ apply h.transfer
+ intro j hj
+ have opts : j = 4 ∨ j = 5 ∨ j = 15 ∨ j = 18 ∨ j = 19 ∨ j = 20 := by simpa using hj
+ apply Counters.addHistogram_outside
+ right
+ rw [offset_val header fit (by omega : j < 32)]
+ omega
+
+theorem Readback.regions_eq (h : Readback m header firstRow rowWords stride baseRadix laneRadix span)
+ (degree : ℕ) (pub : Fin 11 → Word w) (n labels : ℕ) (hn : (pub 6).val=n) (hl : (pub 9).val=labels)
+ (fit : firstRow+rowWords < 2^w) :
+ fromHeader degree pub header m = TerminalLayout.privateRegions degree n (firstRow+rowWords) labels := by
+ rw [fromHeader,h.row,h.words,Fin.val_natCast,Fin.val_natCast,
+ Nat.mod_eq_of_lt (by omega : firstRow < 2^w),Nat.mod_eq_of_lt (by omega : rowWords < 2^w),hn,hl]
+ exact NativeFrame.regions_eq ..
+
+/-- Pointwise coincidence of all twelve stored words with the terminal
+layout, including the histogram, live role displacement and cache base. -/
+theorem Readback.fields_eq (h : Readback m header firstRow rowWords stride baseRadix laneRadix span)
+ (degree : ℕ) (pub : Fin 11 → Word w) (role : Word w) (n labels : ℕ) (hn : (pub 6).val=n)
+ (hl : (pub 9).val=labels) (fit : firstRow+rowWords < 2^w) (j : Fin 12) :
+ fields degree pub header role m j =
+ (TerminalLayout.geometry (TerminalLayout.privateRegions degree n (firstRow+rowWords) labels)
+ firstRow stride baseRadix laneRadix (pub 3).val span.val role.val n j : Word w) := by
+ have hword : pub 6 = (n : Word w) := hn ▸ (Fin.cast_val_eq_self _).symm
+ have eqn := h.regions_eq degree pub n labels hn hl fit
+ unfold fields; rw [eqn]
+ fin_cases j <;> first | exact h.row | exact h.words | exact h.pitch | exact h.base | exact h.lane |
+ exact h.span.trans (Fin.cast_val_eq_self _).symm | exact (Fin.cast_val_eq_self _).symm | exact hword | rfl
+
+/-- The pointer at live length lies below the geometry, since the private
+layout contains an argument interval for each absolute node address up to
+the exclusive row end. -/
+theorem Readback.pointer_before (h : Readback m header firstRow rowWords stride baseRadix laneRadix span)
+ (degree : ℕ) (pub : Fin 11 → Word w) (positive : 0 < firstRow) (fit : firstRow+rowWords < 2^w) :
+ (pub 6).val < frameBase (fromHeader degree pub header m) := by
+ rw [h.regions_eq degree pub _ _ rfl rfl fit]
+ change (pub 6).val < (pub 6).val + (firstRow+rowWords)*(2*degree*(pub 6).val+1) + (pub 9).val
+ have hp : 0 < (firstRow+rowWords)*(2*degree*(pub 6).val+1) :=
+ Nat.mul_pos (by omega) (Nat.succ_pos _)
+ exact (Nat.lt_add_of_pos_right hp).trans_le (Nat.le_add_right _ _)
+
+/-- The genuine decoder's address, radix and span data from the same
+selected bootstrap and the prepared auxiliary shadow. -/
+theorem Readback.leaf_operands {p r k n a' H s : ℕ} {L : PrimedInputRAM.Lengths} {Q : PrimedInputRAM.Layout L n a' H w}
+ (h : Readback m header firstRow rowWords stride baseRadix laneRadix span) (degree : ℕ)
+ (pub : Fin 11 → Word w) (role : Word w) (pc : LeafImage.Label → Fin p) (reg : LeafImage.Reg ↪ Fin r)
+ (operand : LeafImage.Pub → Fin k) (ret : Fin p) (M : Machine w p r k)
+ (assigned : M.publicData ∘ operand = leafWords degree pub header role m ∘ LeafGeometryLoad.slot)
+ (data : PrimedCounter.Data Q s) (b l cap : ℕ) (pitch : stride=cap+2) (rb : baseRadix=2^b)
+ (rl : laneRadix=2^l) (fits : max stride (max baseRadix laneRadix) < 2^w)
+ (spanVal : span.val = LiveAuxiliaryHeaders.span L data.hist.length)
+ (range : (pub 3).val+span.val ≤ 2^w)
+ (shadow : ∀ i < span.val, (m ((pub 3).val+i)).val = (data.initial i).val)
+ (hn : (pub 6).val=n) :
+ LeafFront.Operands (LeafImage.front pc reg operand ret) M m data (fromHeader degree pub header m) b l cap ∧
+ M.publicData (operand .size) = (n : Word w) := by
+ apply NativeFrame.leaf_operands degree pub header role m pc reg operand ret M assigned data b l cap
+ · rw [h.pitch,Fin.val_natCast,Nat.mod_eq_of_lt (by omega)]; exact pitch
+ · rw [h.base,Fin.val_natCast,Nat.mod_eq_of_lt (by omega)]; exact rb
+ · rw [h.lane,Fin.val_natCast,Nat.mod_eq_of_lt (by omega)]; exact rl
+ · rw [h.span]; exact spanVal
+ · rw [h.span]; exact range
+ · rw [h.span]; exact shadow
+ · exact hn
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameFootprint.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameFootprint.lean
new file mode 100644
index 0000000000..b43a59bce3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameFootprint.lean
@@ -0,0 +1,42 @@
+import OAI.Computability.VPVNP.PairNativeFrameRun
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-! # External-memory footprint of the terminal vertex's geometry setup -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+open BurstRAM CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+theorem events_writes (degree : ℕ) (header : Word w) (m : Memory w) :
+ Writes (fun _ => False) (events degree header m) := by
+ intro a v h
+ simp [events,preludeEvents,readEvents,fieldEvents,List.mem_replicate] at h
+
+theorem events_after (degree : ℕ) (header : Word w) (m initial : Memory w) :
+ after initial (events degree header m) = initial := by
+ funext j; exact after_outside initial (events_writes degree header m) (fun hf => hf)
+
+theorem events_reads (degree : ℕ) (header : Word w) (m : Memory w) :
+ Reads (fun x => ∃ j : Fin 6, x = (header + (offsets j : Word w)).val) (events degree header m) := by
+ intro a v h
+ simp only [events,preludeEvents,readEvents,fieldEvents,List.mem_cons,List.mem_append,List.mem_replicate,
+ List.not_mem_nil,or_false,reduceCtorEq,and_false,or_self,false_or,Event.read.injEq] at h
+ rcases h with h|h|h|h|h|h
+ · exact ⟨0,congrArg Fin.val h.1⟩
+ · exact ⟨1,congrArg Fin.val h.1⟩
+ · exact ⟨2,congrArg Fin.val h.1⟩
+ · exact ⟨3,congrArg Fin.val h.1⟩
+ · exact ⟨4,congrArg Fin.val h.1⟩
+ · exact ⟨5,congrArg Fin.val h.1⟩
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameGeometry.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameGeometry.lean
new file mode 100644
index 0000000000..d49fa81e33
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameGeometry.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.PairNativeFrameArithmetic
+import OAI.Computability.VPVNP.PairNativeFrameTable
+import OAI.Computability.VPVNP.PairSimulationLeafArena
+
+/-! # Terminal header words and the private address layout of the leaf verifier -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The exclusive node bound uses the entire address interval, including
+the cells below the first absolute descriptor address. -/
+def regions (degree n firstRow rowWords labels : ℕ) : LeafArena.Regions :=
+ ⟨⟨n,2*degree*n+1⟩,firstRow+rowWords,labels,n^5⟩
+
+/-- Private leaf layout reconstructed from the terminal row base and row word count, the public
+input length and label count, and the fixed degree. -/
+def fromHeader (degree : ℕ) (pub : Fin 11 → Word w) (header : Word w) (m : Memory w) :=
+ regions degree (pub 6).val (m (header+4).val).val (m (header+5).val).val (pub 9).val
+
+/-- First address after the private histogram, where the terminal vertex installs its geometry
+fields. -/
+def frameBase (A : LeafArena.Regions) := A.histBase+A.histWords
+
+/-- Offsets 0 through 5 serve the leaf decoder. Offsets 6 through 8
+supply the argument and cache addresses for leaf preparation. -/
+def fields (degree : ℕ) (pub : Fin 11 → Word w) (header role : Word w) (m : Memory w) :
+ Fin 12 → Word w :=
+ let A := fromHeader degree pub header m
+ ![m (header+4).val, m (header+15).val, m (header+18).val, m (header+19).val,
+ pub 3, m (header+20).val, pub 6, (A.arguments.stride : Word w), (A.cacheBase : Word w),
+ pub 6, role, (A.histBase : Word w)]
+
+private theorem nat_word (x : Word w) : (x.val : Word w) = x := Fin.ext (Nat.mod_eq_of_lt x.isLt)
+
+private theorem stride_cast (degree : ℕ) (pub : Fin 11 → Word w) (header : Word w) (m : Memory w) :
+ ((fromHeader degree pub header m).arguments.stride : Word w) = argumentStride pub degree := by
+ simp only [fromHeader,regions,argumentStride,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_one,nat_word]
+
+private theorem hist_cast (degree : ℕ) (pub : Fin 11 → Word w) (header : Word w) (m : Memory w) (rs : Regs w 24) :
+ ((fromHeader degree pub header m).histBase : Word w) = histWord pub (loaded header m rs) degree := by
+ change (((pub 6).val + ((m (header+4).val).val + (m (header+5).val).val) *
+ (fromHeader degree pub header m).arguments.stride : ℕ) : Word w) =
+ pub 6 + argumentStride pub degree * (m (header+4).val + m (header+5).val)
+ simp only [Nat.cast_add,Nat.cast_mul,nat_word,stride_cast,mul_comm]
+
+private theorem graph_cast (degree : ℕ) (pub : Fin 11 → Word w) (header : Word w) (m : Memory w) (rs : Regs w 24) :
+ (frameBase (fromHeader degree pub header m) : Word w) = graphWord pub (loaded header m rs) degree := by
+ simp only [frameBase,Nat.cast_add,hist_cast degree pub header m rs,graphWord]
+ rw [show (fromHeader degree pub header m).histWords = (pub 9).val from rfl,nat_word]
+
+private theorem cache_cast (degree : ℕ) (pub : Fin 11 → Word w) (header : Word w) (m : Memory w) (rs : Regs w 24) :
+ ((fromHeader degree pub header m).cacheBase : Word w) = graphWord pub (loaded header m rs) degree + (pub 6)^5 := by
+ change ((frameBase (fromHeader degree pub header m)+(pub 6).val^5 : ℕ) : Word w) = _
+ simp only [Nat.cast_add,Nat.cast_pow,graph_cast degree pub header m rs,nat_word]
+
+/-- Values required by the thirteen private stores. The frame starts
+immediately after the histogram and ends before the scalar operand cache. -/
+structure Ready {r : ℕ} (reg : R ↪ Fin r) (pub : Fin 11 → Word w)
+ (degree : ℕ) (header role : Word w) (m : Memory w) (out : Regs w r) : Prop where
+ graph : out (reg 2) = (frameBase (fromHeader degree pub header m) : Word w)
+ cursor : out (reg 18) = (frameBase (fromHeader degree pub header m) : Word w)
+ unit : out (reg 15) = 1
+ field : ∀ i, out (reg (fieldReg i)) = fields degree pub header role m i
+
+theorem arithmetic_ready (degree : ℕ) (pub : Fin 11 → Word w) (header : Word w) (m : Memory w) (rs : Regs w 24) :
+ Ready (Function.Embedding.refl _) pub degree header (rs 1) m
+ (arithmeticBank pub (loaded header m rs) degree) := by
+ have h := arithmetic_values pub (loaded header m rs) degree (show loaded header m rs 15 = 1 from rfl)
+ have hg := (graph_cast degree pub header m rs).symm
+ refine ⟨h.graph.trans hg,h.cursor.trans hg,h.preserved 15 (by decide),?_⟩
+ intro i
+ fin_cases i
+ · exact h.preserved 3 (by decide)
+ · exact h.preserved 4 (by decide)
+ · exact h.preserved 5 (by decide)
+ · exact h.preserved 6 (by decide)
+ · exact h.shadow
+ · exact h.preserved 8 (by decide)
+ · exact h.length
+ · exact h.iterations.trans (stride_cast degree pub header m).symm
+ · exact h.cache.trans (cache_cast degree pub header m rs).symm
+ · exact h.copyLength
+ · exact h.role
+ · exact h.histogram.trans (hist_cast degree pub header m rs).symm
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameGroup.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameGroup.lean
new file mode 100644
index 0000000000..51df9e750d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameGroup.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.PairNativeFrameDescriptor
+import OAI.Computability.VPVNP.PairTerminalShadowSpan
+
+/-! # Preservation of terminal geometry and auxiliary shadow through vertex calls -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+open BurstRAM PairSimulation NativeFrame
+open scoped Fin.CommRing
+
+variable (G : Group)
+
+private theorem shadow_le_workspace : shadowBase G ≤ (Layout.pairWorkspace G.constants).eval G.g := by
+ change shadowBase G ≤ shadowBase G + _
+ exact Nat.le_add_right _ _
+
+/-- The three physical public operands describing the counter bank cannot
+reach the auxiliary shadow, hence cannot reach the high terminal header. -/
+theorem physical_counter_end (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w) :
+ let pub := terminalOperands G
+ (pub 4).val + (pub 5).val + G.constants.motifLabels ≤ (pub 3).val ∧
+ (pub 3).val ≤ (pub 2).val ∧ (pub 9).val = G.constants.motifLabels := by
+ intro pub
+ have endLe := counter_end_le_shadow G
+ change counterBase G + (histLength G + G.constants.motifLabels) ≤ shadowBase G at endLe
+ have sw := shadow_le_workspace G
+ have shadowFit : shadowBase G < 2^G.w := sw.trans_lt fit
+ have h3 : (pub 3).val = shadowBase G := Nat.mod_eq_of_lt shadowFit
+ have h4 : (pub 4).val = counterBase G := Nat.mod_eq_of_lt (show counterBase G < 2^G.w by omega)
+ have h5 : (pub 5).val = histLength G := Nat.mod_eq_of_lt (show histLength G < 2^G.w by omega)
+ have h9 : (pub 9).val = G.constants.motifLabels := Nat.mod_eq_of_lt (show G.constants.motifLabels < 2^G.w by omega)
+ have h2 : (pub 2).val = (Layout.pairWorkspace G.constants).eval G.g := Nat.mod_eq_of_lt fit
+ rw [h2,h3,h4,h5,h9]; exact ⟨by omega,sw,rfl⟩
+
+variable {G} {m : Memory G.w} {header span : Word G.w} {row rowWords stride baseRadix laneRadix : ℕ}
+
+/-- Readback of the same six native header fields after the actual motif
+counter update, using the physical counter allocation of the live program. -/
+theorem readback_after_histogram (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w)
+ (below : (terminalOperands G 2).val ≤ header.val) (room : header.val+32 ≤ 2^G.w)
+ (h : Readback m header row rowWords stride baseRadix laneRadix span) (hist : Fin G.constants.motifLabels → ℕ) :
+ Readback (Counters.addHistogram (terminalOperands G 4).val (terminalOperands G 5).val hist m)
+ header row rowWords stride baseRadix laneRadix span :=
+ h.addHistogram _ _ hist (((physical_counter_end G fit).1.trans (physical_counter_end G fit).2.1).trans below) room
+
+/-- Every address in the auxiliary shadow survives a site's native
+counter flush, including reset addresses whose value is zero. -/
+theorem shadow_after_histogram (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w)
+ (hist : Fin G.constants.motifLabels → ℕ) (a : ℕ) :
+ Counters.addHistogram (terminalOperands G 4).val (terminalOperands G 5).val hist m
+ ((terminalOperands G 3).val + a) = m ((terminalOperands G 3).val + a) :=
+ Counters.addHistogram_outside _ _ hist m _ (.inr ((physical_counter_end G fit).1.trans (Nat.le_add_right _ _)))
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameLeaf.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameLeaf.lean
new file mode 100644
index 0000000000..4a982d8bcb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameLeaf.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairNativeFrameRun
+import OAI.Computability.VPVNP.PairSimulationLeafGeometryLoad
+
+/-! # Reading the leaf's fixed operands from the installed geometry
+
+The native vertex uses twelve fields. Each visit reloads the first ten,
+in the order required by the leaf decoder and route test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- First ten words of the installed frame, in the order used to reload the leaf decoder and
+route-test operands. -/
+def leafWords (degree : ℕ) (pub : Fin 11 → Word w) (header role : Word w) (m : Memory w) :
+ Fin 10 → Word w := fun j => fields degree pub header role m (j.castLE (by decide))
+
+theorem Result.stored {P : Ports r} {degree : ℕ} {pub : Fin 11 → Word w} {m : Memory w} {c out : Config w p r}
+ (h : Result P degree pub m c out) :
+ LeafGeometryLoad.Stored (pub 6).val (frameBase (fromHeader degree pub (c.reg P.header) m)) out.privateMem
+ (leafWords degree pub (c.reg P.header) (c.reg P.role) m) := by
+ refine ⟨?_,fun i => h.values (i.castLE (by decide))⟩
+ rw [Fin.cast_val_eq_self]; exact h.pointer
+
+/-- Any subsequent writes restricted to the operand cache or above it
+preserve the actual geometry record. The role and histogram words are
+also protected by the same two address inequalities. -/
+theorem Result.stored_after {P : Ports r} {degree : ℕ} {pub : Fin 11 → Word w} {m : Memory w}
+ {c out : Config w p r} (h : Result P degree pub m c out) (priv : Word w → Word w)
+ (head : (pub 6).val < (fromHeader degree pub (c.reg P.header) m).cacheBase)
+ (bank : frameBase (fromHeader degree pub (c.reg P.header) m)+12 ≤ (fromHeader degree pub (c.reg P.header) m).cacheBase)
+ (fit : (fromHeader degree pub (c.reg P.header) m).cacheBase ≤ 2^w)
+ (same : ∀ j : Word w, j.val < (fromHeader degree pub (c.reg P.header) m).cacheBase → priv j = out.privateMem j) :
+ LeafGeometryLoad.Stored (pub 6).val (frameBase (fromHeader degree pub (c.reg P.header) m)) priv
+ (leafWords degree pub (c.reg P.header) (c.reg P.role) m) ∧
+ ∀ i : Fin 12, priv ((frameBase (fromHeader degree pub (c.reg P.header) m)+i.val : ℕ) : Word w) =
+ fields degree pub (c.reg P.header) (c.reg P.role) m i := by
+ have full (i : Fin 12) := h.values i
+ have field (i : Fin 12) : priv ((frameBase (fromHeader degree pub (c.reg P.header) m)+i.val : ℕ) : Word w) =
+ fields degree pub (c.reg P.header) (c.reg P.role) m i := by
+ rw [same,full]
+ rw [Fin.val_natCast,Nat.mod_eq_of_lt (by have := i.isLt; omega)]
+ have := i.isLt; omega
+ refine ⟨⟨?_,fun i => field (i.castLE (by decide))⟩,field⟩
+ rw [Fin.cast_val_eq_self,same _ head]; exact h.pointer
+
+variable {L : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout L n a H w}
+
+/-- The terminal descriptor's preserved geometry and the concrete shadow
+contents supply the nine obligations of the executable leaf front. -/
+theorem leaf_operands (degree : ℕ) (pub : Fin 11 → Word w) (header role : Word w) (m : Memory w)
+ (pc : LeafImage.Label → Fin p) (reg : LeafImage.Reg ↪ Fin r) (operand : LeafImage.Pub → Fin k)
+ (ret : Fin p) (M : Machine w p r k)
+ (assigned : M.publicData ∘ operand = leafWords degree pub header role m ∘ LeafGeometryLoad.slot)
+ (data : PrimedCounter.Data Q s) (b l cap : ℕ)
+ (rowStride : (m (header+15).val).val = cap+2)
+ (radixB : (m (header+18).val).val = 2^b) (radixL : (m (header+19).val).val = 2^l)
+ (span : (m (header+20).val).val = LiveAuxiliaryHeaders.span L data.hist.length)
+ (fits : (pub 3).val+(m (header+20).val).val ≤ 2^w)
+ (shadow : ∀ i < (m (header+20).val).val, (m ((pub 3).val+i)).val = (data.initial i).val)
+ (length : (pub 6).val = n) :
+ LeafFront.Operands (LeafImage.front pc reg operand ret) M m data (fromHeader degree pub header m) b l cap ∧
+ M.publicData (operand .size) = (n : Word w) := by
+ let val := leafWords degree pub header role m
+ have address (j : LeafAddress.Field) : M.publicData (operand (.address j)) = val (LeafGeometryLoad.slot (.address j)) :=
+ congrFun assigned (.address j)
+ have arena (j : RoutePrepare.Field) : M.publicData (operand (.arena j)) = val (LeafGeometryLoad.slot (.arena j)) :=
+ congrFun assigned (.arena j)
+ have hn : (pub 6).val = (fromHeader degree pub header m).arguments.start := rfl
+ refine ⟨⟨?_,?_,?_,?_,?_,?_,?_,arena .stride,arena .cache⟩,?_⟩
+ · exact (congrArg Fin.val (address .stride)).trans rowStride
+ · exact (congrArg Fin.val (address .radixB)).trans radixB
+ · exact (congrArg Fin.val (address .radixL)).trans radixL
+ · exact (congrArg Fin.val (address .span)).trans span
+ · change (M.publicData (operand (.address .shadow))).val+(M.publicData (operand (.address .span))).val ≤ _
+ rw [address .shadow,address .span]; exact fits
+ · change ∀ i < (M.publicData (operand (.address .span))).val, (m ((M.publicData (operand (.address .shadow))).val+i)).val = _
+ rw [address .shadow,address .span]; exact shadow
+ · exact (arena .start).trans ((Fin.cast_val_eq_self (pub 6)).symm.trans (congrArg (fun x : ℕ => (x : Word w)) hn))
+ · exact (congrFun assigned .size).trans ((Fin.cast_val_eq_self (pub 6)).symm.trans (congrArg (fun x : ℕ => (x : Word w)) length))
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFramePrelude.lean b/lean/OAI/Computability/VPVNP/PairNativeFramePrelude.lean
new file mode 100644
index 0000000000..87e2002e7d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFramePrelude.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.PairNativeFrameGeometry
+import OAI.Computability.VPVNP.PrimedCounterRenameRun
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+
+/-! # Relocating the terminal frame's header reads and address computation -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+
+variable {r w : ℕ}
+
+/-- Copy the caller's header address and role offset into the work bank, then execute the six
+header reads and compute the frame geometry. -/
+def prelude (degree : ℕ) (reg : R ↪ Fin r) (savedHeader savedRole : Fin r) : Flow r 11 :=
+ .seq (.seq (.line (.copy (reg 0) savedHeader)) (.line (.copy (reg 1) savedRole)))
+ (PrimedCounter.renameFlow reg id (.seq reads (arithmetic degree)))
+
+/-- Event trace of frame preparation through the arithmetic exit, including both entry copies
+and the six external header probes. -/
+def preludeEvents (degree : ℕ) (header : Word w) (m : Memory w) : List (Event w) :=
+ [.tick,.tick] ++ (readEvents header m ++ List.replicate (degree+18) .tick)
+
+theorem tick_cost (n : ℕ) :
+ countProbes (List.replicate n (.tick : Event w)) = 0 ∧ choiceBits (List.replicate n (.tick : Event w)) = [] := by
+ induction n with
+ | zero => exact ⟨rfl,rfl⟩
+ | succ n ih => simpa only [List.replicate_succ,countProbes,choiceBits] using ih
+
+theorem prelude_cost (degree : ℕ) (header : Word w) (m : Memory w) :
+ (preludeEvents degree header m).length = degree+114 ∧
+ countProbes (preludeEvents degree header m) = 6 ∧ choiceBits (preludeEvents degree header m) = [] := by
+ obtain ⟨l,p,b⟩ := reads_cost header m
+ obtain ⟨tp,tb⟩ := tick_cost (w := w) (degree+18)
+ refine ⟨?_,?_,?_⟩
+ · simp [preludeEvents,l]; omega
+ · change countProbes (readEvents header m ++ List.replicate (degree+18) .tick) = _
+ rw [countProbes_append,p,tp]
+ · change choiceBits (readEvents header m ++ List.replicate (degree+18) .tick) = _
+ rw [Flow.choiceBits_append,b,tb]; rfl
+
+theorem prelude_run (degree : ℕ) (reg : R ↪ Fin r) (savedHeader savedRole : Fin r)
+ (free : savedRole ≠ reg 0) (pub : Fin 11 → Word w) (st : Word w) (m : Memory w) (rs : Regs w r) :
+ ∃ out, Flow.Exec pub st (prelude degree reg savedHeader savedRole) rs m
+ (preludeEvents degree (rs savedHeader) m) out m ∧
+ Ready reg pub degree (rs savedHeader) (rs savedRole) m out ∧
+ ∀ j, j ∉ Set.range reg → out j = rs j := by
+ let t := Function.update rs (reg 0) (rs savedHeader)
+ let u := Function.update t (reg 1) (rs savedRole)
+ have ht : t savedRole = rs savedRole := Function.update_of_ne free ..
+ have copy0 : Flow.Exec pub st (.line (.copy (reg 0) savedHeader)) rs m [.tick] t m := .line rfl
+ have copy1 : Flow.Exec pub st (.line (.copy (reg 1) savedRole)) t m [.tick] u m := by
+ apply Flow.Exec.line; simp only [Op.effect,ht,u]
+ let small := u ∘ reg
+ have h0 : small 0 = rs savedHeader := by simp [small,u,t]
+ have h1 : small 1 = rs savedRole := Function.update_self ..
+ let s := loaded (small 0) m small
+ have run := (reads_run pub st m small).seq (arithmetic_run pub st m s degree rfl)
+ obtain ⟨out,body,ins,outside⟩ := PrimedCounter.liftExec reg id pub run u rfl
+ have head := (copy0.seq copy1).seq body
+ refine ⟨out,?_,?_,?_⟩
+ · simpa only [prelude,preludeEvents,List.cons_append,List.nil_append,h0] using head
+ · have q := arithmetic_ready degree pub (small 0) m small
+ rw [←h0,←h1]
+ exact ⟨(congrFun ins 2).trans q.graph,(congrFun ins 18).trans q.cursor,
+ (congrFun ins 15).trans q.unit,fun i => (congrFun ins (fieldReg i)).trans (q.field i)⟩
+ · intro j hj
+ have hn (i : R) : j ≠ reg i := fun eq => hj ⟨i,eq.symm⟩
+ rw [outside j hj]
+ simp only [u,t,Function.update_of_ne (hn 0),Function.update_of_ne (hn 1)]
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFramePrepared.lean b/lean/OAI/Computability/VPVNP/PairNativeFramePrepared.lean
new file mode 100644
index 0000000000..d6022ec94d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFramePrepared.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.PairNativeFrameGroup
+import OAI.Computability.VPVNP.PairTerminalShadowTransfer
+import OAI.Computability.VPVNP.LiveProgramPairNominationOrder
+
+/-! # Typed leaf operands for a native auxiliary-counter preparation -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedCounter LiveAuxiliaryHeaders PairSimulation NativeFrame
+open scoped Fin.CommRing
+
+variable {G : Group} {i : Fin (2^(sizes G).h)} {before : Memory G.w}
+ {N : Indexed G Stage.nominations before (Nominations.Nom G)} {μ : Nominations.Nom G}
+ {hdr : Header (pairLengths G i) → Bool} (B : PreparedBranch G before i hdr N μ)
+ (Q : PrimedInputRAM.Layout (pairLengths G i) G.g.n G.g.d G.g.H G.w) (degree : Fin G.g.n) (root : Fin (states G))
+
+/-- The source public table receives the real auxiliary reset words,
+including arbitrary nomination and two-sided exterior choices. The
+histogram-target frame is needed only at the single descriptor cell,
+and shadow stability is needed only inside the reserved header. -/
+theorem PreparedBranch.leafOperands {p r k : ℕ} (slotDegree : ℕ) (header role : Word G.w)
+ (bootMem curr : Memory G.w) {row rowWords b l cap : ℕ}
+ (read : Readback curr header row rowWords (cap+2) (2^b) (2^l) (TerminalBootstrap.shadowSpan (terminalOperands G) bootMem))
+ (descriptor : bootMem (histogramCell G) = B.copy.memory () (histogramCell G))
+ (shadowFrame : ∀ a < span (pairLengths G i) (histLength G),
+ curr ((shadow G).val+a) = B.copy.memory () ((shadow G).val+a))
+ (pc : LeafImage.Label → Fin p) (reg : LeafImage.Reg ↪ Fin r) (operand : LeafImage.Pub → Fin k) (ret : Fin p)
+ (M : Machine G.w p r k) (assigned : M.publicData ∘ operand =
+ leafWords slotDegree (terminalOperands G) header role curr ∘ LeafGeometryLoad.slot)
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w)
+ (sizeFits : G.g.n < 2^G.w) (shapeFits : max (cap+2) (max (2^b) (2^l)) < 2^G.w)
+ (room : shadowBase G + span (pairLengths G i) (histLength G) ≤ 2^G.w) :
+ LeafFront.Operands (LeafImage.front pc reg operand ret) M curr
+ (Data.ofNomination Q degree root hdr (nominationEquiv G μ)) (fromHeader slotDegree (terminalOperands G) header curr) b l cap ∧
+ M.publicData (operand .size) = (G.g.n : Word G.w) := by
+ let D := Data.ofNomination Q degree root hdr (nominationEquiv G μ)
+ let pub := terminalOperands G
+ have heq : D.hist.length = histLength G := by
+ rw [show D.hist = histogram G μ from histogram_eq Q degree root hdr μ]
+ simp [histogram]
+ have hs : shadowBase G < 2^G.w := by
+ have hw : shadowBase G ≤ (Layout.pairWorkspace G.constants).eval G.g := by
+ change shadowBase G ≤ shadowBase G+_; exact Nat.le_add_right _ _
+ exact hw.trans_lt fit
+ have shadowVal : (pub 3).val = shadowBase G := Nat.mod_eq_of_lt hs
+ have pos : 0 < shadowBase G := by
+ obtain ⟨ht,hd,hh,hg⟩ := geometry_order G; omega
+ have spanVal : (TerminalBootstrap.shadowSpan pub bootMem).val = span (pairLengths G i) (histLength G) := by
+ rw [B.shadowSpan_of_cell descriptor,Fin.val_natCast,Nat.mod_eq_of_lt (show span (pairLengths G i) (histLength G) < 2^G.w by omega)]
+ apply read.leaf_operands slotDegree pub role pc reg operand ret M assigned D b l cap rfl rfl rfl shapeFits
+ · rw [heq]; exact spanVal
+ · rw [spanVal,shadowVal]; exact room
+ · intro a ha
+ have h := shadowFrame a (spanVal ▸ ha)
+ exact congrArg Fin.val (h.trans (shadow_initial Q degree root hdr μ B a))
+ · exact Nat.mod_eq_of_lt sizeFits
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameReads.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameReads.lean
new file mode 100644
index 0000000000..11b04a4da7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameReads.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import OAI.Computability.VPVNP.RAMSuccessor
+import Mathlib.Data.ZMod.Defs
+
+/-! # Reading the terminal vertex's six descriptor words
+
+The surrounding ordinal dispatch passes the address of the terminal header
+in register zero and the role offset in register one. Only the six named
+descriptor offsets cause external probes. The addresses are computed with
+the two-bit literals available to the fixed pair program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+/-- Register indices for the 24-word work bank shared by the header reader and frame
+arithmetic. -/
+abbrev R := Fin 24
+/-- Native instruction flows for the terminal frame, with 24 work registers and eleven public
+operands. -/
+abbrev Code := Flow 24 11
+
+variable {w : ℕ}
+
+/-- Header registers 3, 17, 4, 5, 6 and 8 receive the absolute row base,
+row words, row stride, base radix, lane radix and auxiliary shadow span. -/
+def destinations : Fin 6 → R := ![3,17,4,5,6,8]
+/-- Header offsets for the absolute row base, row word count, row stride, base radix, lane
+radix and shadow span, in read order. -/
+def offsets : Fin 6 → ℕ := ![4,5,15,18,19,20]
+
+private def advance (dst src : R) : ℕ → Code
+ | 0 => .line (.copy dst src)
+ | n+1 => .seq (advance dst src n) (.line (.binary .add dst dst 15))
+
+private theorem advance_run (pub : Fin 11 → Word w) (st : Word w) (m : Memory w) (rs : Regs w 24)
+ (dst src : R) (hd : dst ≠ 15) (one : rs 15 = 1) (n : ℕ) :
+ Flow.Exec pub st (advance dst src n) rs m (List.replicate (n+1) .tick)
+ (Function.update rs dst (rs src + (n : Word w))) m := by
+ induction n with
+ | zero => simpa [advance] using (show Flow.Exec pub st (.line (.copy dst src)) rs m [.tick]
+ (Function.update rs dst (rs src)) m from .line rfl)
+ | succ n ih =>
+ let mid := Function.update rs dst (rs src+(n : Word w))
+ have h : Flow.Exec pub st (.line (.binary .add dst dst 15)) mid m [.tick]
+ (Function.update rs dst (rs src+((n+1 : ℕ) : Word w))) m := by
+ apply Flow.Exec.line
+ simp only [Op.effect,BinaryOp.eval,mid,Function.update_self,Function.update_of_ne hd.symm,
+ Function.update_idem,one,Nat.cast_add,Nat.cast_one,add_assoc]
+ simpa only [advance,List.replicate_succ',List.replicate_one] using ih.seq h
+
+/-- Copy the header pointer from register zero, advance it by `off` unit steps, and load the
+addressed external word into `dst`. -/
+def readField (dst : R) (off : ℕ) : Code := .seq (advance dst 0 off) (.line (.read dst dst))
+
+/-- Trace for reading one header field, with one pointer-copy tick, `off` increment ticks, and
+a read carrying the value from memory. -/
+def fieldEvents (header : Word w) (m : Memory w) (off : ℕ) : List (Event w) :=
+ List.replicate (off+1) .tick ++ [.read (header+off) (m (header+off).val)]
+
+private theorem read_run (pub : Fin 11 → Word w) (st : Word w) (m : Memory w) (rs : Regs w 24)
+ (dst : R) (hd : dst ≠ 15) (one : rs 15 = 1) (off : ℕ) :
+ Flow.Exec pub st (readField dst off) rs m (fieldEvents (rs 0) m off)
+ (Function.update rs dst (m (rs 0+off).val)) m := by
+ let mid := Function.update rs dst (rs 0+(off : Word w))
+ have h : Flow.Exec pub st (.line (.read dst dst)) mid m
+ [.read (rs 0+off) (m (rs 0+off).val)] (Function.update rs dst (m (rs 0+off).val)) m := by
+ apply Flow.Exec.line; simp [Op.effect,mid,Function.update_idem]
+ exact (advance_run pub st m rs dst 0 hd one off).seq h
+
+/-- Initialize the unit register and load all six terminal descriptor words into their assigned
+work registers. -/
+def reads : Code :=
+ .seq (.line (.constant 15 1)) (.seq (readField 3 4) (.seq (readField 17 5) (.seq (readField 4 15)
+ (.seq (readField 5 18) (.seq (readField 6 19) (readField 8 20))))))
+
+/-- Ordered event trace for the complete header reader, starting with the unit initialization
+and ending with the shadow-span read. -/
+def readEvents (header : Word w) (m : Memory w) :=
+ .tick :: (fieldEvents header m 4 ++ (fieldEvents header m 5 ++ (fieldEvents header m 15 ++
+ (fieldEvents header m 18 ++ (fieldEvents header m 19 ++ fieldEvents header m 20)))))
+
+private def withField (header : Word w) (m : Memory w) (dst : R) (off : ℕ) (rs : Regs w 24) :=
+ Function.update rs dst (m (header+off).val)
+
+/-- Work bank after the header reader sets register 15 to one and installs the six external
+field values in their destinations. -/
+def loaded (header : Word w) (m : Memory w) (rs : Regs w 24) :=
+ let set := withField header m
+ set 8 20 (set 6 19 (set 5 18 (set 4 15 (set 17 5 (set 3 4 (Function.update rs 15 1))))))
+
+theorem reads_run (pub : Fin 11 → Word w) (st : Word w) (m : Memory w) (rs : Regs w 24) :
+ Flow.Exec pub st reads rs m (readEvents (rs 0) m) (loaded (rs 0) m rs) m := by
+ let set := withField (rs 0) m
+ let z := Function.update rs (15 : R) 1
+ let a := set 3 4 z
+ let b := set 17 5 a
+ let c := set 4 15 b
+ let d := set 5 18 c
+ let e := set 6 19 d
+ have load : Flow.Exec pub st (.line (.constant 15 1)) rs m [.tick] z m := .line rfl
+ have read (u : Regs w 24) (dst : R) (off : ℕ) (hd : dst ≠ 15) (h : u 15 = 1) (hdr : u 0 = rs 0) :
+ Flow.Exec pub st (readField dst off) u m (fieldEvents (rs 0) m off) (set dst off u) m := by
+ simpa only [set,withField,hdr] using read_run pub st m u dst hd h off
+ refine load.seq ((read z 3 4 (by decide) rfl rfl).seq ((read a 17 5 (by decide) rfl rfl).seq
+ ((read b 4 15 (by decide) rfl rfl).seq ((read c 5 18 (by decide) rfl rfl).seq
+ ((read d 6 19 (by decide) rfl rfl).seq (read e 8 20 (by decide) rfl rfl))))))
+
+theorem reads_cost (header : Word w) (m : Memory w) :
+ (readEvents header m).length = 94 ∧ countProbes (readEvents header m) = 6 ∧ choiceBits (readEvents header m) = [] := by
+ exact ⟨rfl,rfl,rfl⟩
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameRun.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameRun.lean
new file mode 100644
index 0000000000..4b3a43999c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameRun.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.PairNativeFramePrelude
+import OAI.Computability.VPVNP.PairNativeFrameStore
+
+/-! # Executing the terminal vertex's private geometry installation
+
+The caller supplies two live registers holding the terminal header and its
+role offset. The program consumes six external reads, computes all addresses,
+and publishes the histogram and scalar-cache pointers in the designated
+registers of the enclosing vertex burst.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r : ℕ}
+
+/-- Register allocation for the terminal frame installer, with input and output separation
+conditions that protect the role and cache values during handoff. -/
+structure Ports (r : ℕ) where
+ /-- Embedding of the installer's 24 local work registers into the enclosing machine's
+ register bank. -/
+ work : R ↪ Fin r
+ /-- Caller register supplying the terminal header's external address to the first entry copy. -/
+ header : Fin r
+ /-- Caller register supplying the role offset to the second entry copy, distinct from the
+ destination of the first copy. -/
+ role : Fin r
+ /-- Caller register receiving the private histogram base before the cache pointer is copied
+ out. -/
+ hist : Fin r
+ /-- Caller register receiving the scalar-cache base for the next phase of leaf preparation. -/
+ cache : Fin r
+ role_free : role ≠ work 0
+ hist_free : hist ≠ work 11
+ outputs : hist ≠ cache
+
+/-- Frame prelude specialized to the work-register embedding and the caller's two input
+registers. -/
+abbrev Ports.code (P : Ports r) (degree : ℕ) := prelude degree P.work P.header P.role
+/-- Instruction-row emitter that uses these ports for the prelude, private frame stores and
+pointer handoff to the caller. -/
+abbrev Ports.row (P : Ports r) (degree : ℕ) := Table.row (P.code degree) P.work P.hist P.cache (p := p)
+
+/-- Trace of the entire frame installation, extending the prelude by 27 local ticks for private
+stores, cursor advances and the two output copies. -/
+def events (degree : ℕ) (header : Word w) (m : Memory w) :=
+ preludeEvents degree header m ++ List.replicate 27 .tick
+
+theorem events_cost (degree : ℕ) (header : Word w) (m : Memory w) :
+ (events degree header m).length = degree+141 ∧
+ countProbes (events degree header m) = 6 ∧ choiceBits (events degree header m) = [] := by
+ obtain ⟨l,p,b⟩ := prelude_cost degree header m
+ obtain ⟨tp,tb⟩ := tick_cost (w := w) 27
+ refine ⟨?_,?_,?_⟩
+ · rw [events,List.length_append,l,List.length_replicate]
+ · rw [events,countProbes_append,p,tp]
+ · rw [events,Flow.choiceBits_append,b,tb]; rfl
+
+/-- The private memory and register ABI seen by all subsequent visits in
+this burst, including visits that fail the route or cursor-zero verifier. -/
+structure Result (P : Ports r) (degree : ℕ) (pub : Fin 11 → Word w) (m : Memory w)
+ (c out : Config w p r) : Prop where
+ pointer : out.privateMem (pub 6) = (frameBase (fromHeader degree pub (c.reg P.header) m) : Word w)
+ values : ∀ i : Fin 12, out.privateMem ((frameBase (fromHeader degree pub (c.reg P.header) m)+i.val : ℕ) : Word w) =
+ fields degree pub (c.reg P.header) (c.reg P.role) m i
+ outside : ∀ a : Word w, a ≠ pub 6 → a.val < frameBase (fromHeader degree pub (c.reg P.header) m) ∨
+ frameBase (fromHeader degree pub (c.reg P.header) m)+12 ≤ a.val → out.privateMem a = c.privateMem a
+ hist : out.reg P.hist = ((fromHeader degree pub (c.reg P.header) m).histBase : Word w)
+ cache : out.reg P.cache = ((fromHeader degree pub (c.reg P.header) m).cacheBase : Word w)
+ persistent : out.persistent = c.persistent
+ registers : ∀ j, j ∉ Set.range P.work → j ≠ P.hist → j ≠ P.cache → out.reg j = c.reg j
+
+theorem run (P : Ports r) (degree : ℕ) (M : Machine w p r 11)
+ (emb : Fin (Table.size (P.code degree)) → Fin p) (finish : Instr 2 p r 11)
+ (rows : ∀ j, M.code (emb j) = (P.row degree emb finish j).resize w) (m : Memory w)
+ (c : Config w p r) (entry : c.pc = emb (Table.label (P.code degree) (P.code degree).entry))
+ (before : (M.publicData 6).val < frameBase (fromHeader degree M.publicData (c.reg P.header) m))
+ (fit : frameBase (fromHeader degree M.publicData (c.reg P.header) m)+12 ≤ 2^w) :
+ ∃ out, out.pc = emb (Table.tail (P.code degree) 27) ∧ Result P degree M.publicData m c out ∧
+ ∀ fuel bits, execute M.program (fuel + degree+141) c m bits =
+ (execute M.program fuel out m bits).map (Flow.prependEvents (events degree (c.reg P.header) m)) := by
+ let flow := P.code degree
+ change ∀ j, M.code (emb j) = (Table.row flow P.work P.hist P.cache emb finish j).resize w at rows
+ let header := c.reg P.header
+ let n := (M.publicData 6).val
+ let G := frameBase (fromHeader degree M.publicData header m)
+ let hd := preludeEvents degree header m
+ have hw : (n : Word w) = M.publicData 6 := Fin.ext (Nat.mod_eq_of_lt (M.publicData 6).isLt)
+ obtain ⟨bank,deriv,ready,frame⟩ := prelude_run degree P.work P.header P.role P.role_free M.publicData
+ c.persistent m c.reg
+ let mid : Config w p r := ⟨emb (Table.tail flow 0),c.persistent,bank,c.privateMem⟩
+ have hn : mid.reg (P.work 9) = (n : Word w) := (ready.field 6).trans hw.symm
+ obtain ⟨s,runStores,pcS,installed⟩ := store_run flow P.work P.hist P.cache emb finish M rows
+ n G before fit mid rfl hn ready.graph ready.cursor ready.unit
+ let h := s.put (emb (Table.tail flow 26)) P.hist (s.reg (P.work 14))
+ let out := h.put (emb (Table.tail flow 27)) P.cache (h.reg (P.work 11))
+ have histStep : M.program.step s = .localStep h := by
+ change (M.code s.pc).run M.publicData s = _
+ rw [pcS,rows,Table.at_hist]; rfl
+ have cacheStep : M.program.step h = .localStep out := by
+ change (M.code (emb (Table.tail flow 26))).run M.publicData h = _
+ rw [rows,Table.at_cache]; rfl
+ have handoff : Prefix M s [.tick,.tick] out := .tick histStep (.tick cacheStep (.nil _))
+ have tail : Prefix M mid (List.replicate 27 .tick) out := runStores.append handoff
+ refine ⟨out,rfl,?_,?_⟩
+ · refine ⟨?_,?_,?_,?_,?_,installed.persistent,?_⟩
+ · exact hw ▸ installed.pointer
+ · intro i; exact (installed.fields i).trans (ready.field i)
+ · intro a hne outside
+ exact installed.outside a (fun eq => hne (Fin.ext eq)) outside
+ · change Function.update h.reg P.cache _ P.hist = _
+ rw [Function.update_of_ne P.outputs]
+ change Function.update s.reg P.hist _ P.hist = _
+ rw [Function.update_self,installed.registers _ (P.work.injective.ne (by decide))]
+ exact ready.field 11
+ · change Function.update h.reg P.cache _ P.cache = _
+ rw [Function.update_self]
+ change Function.update s.reg P.hist _ (P.work 11) = _
+ rw [Function.update_of_ne P.hist_free.symm,installed.registers _ (P.work.injective.ne (by decide))]
+ exact ready.field 8
+ · intro j outside histFree cacheFree
+ have hcur : j ≠ P.work 18 := fun eq => outside ⟨18,eq.symm⟩
+ change Function.update h.reg P.cache _ j = _
+ rw [Function.update_of_ne cacheFree]
+ change Function.update s.reg P.hist _ j = _
+ rw [Function.update_of_ne histFree,installed.registers j hcur]; exact frame j outside
+ · intro fuel bits
+ have linked := Table.linked flow P.work P.hist P.cache emb finish M rows
+ have reject : M.code (emb (Table.tail flow 28)) = .reject := by rw [rows,Table.at_bad]; rfl
+ have front := deriv.execute linked reject c.privateMem (fuel+27) bits
+ have initial : (⟨emb (Table.label flow flow.entry),c.persistent,c.reg,c.privateMem⟩ : Config w p r) = c := by
+ rw [←entry]
+ change execute M.program (hd.length+(fuel+27)) ⟨emb (Table.label flow flow.entry),c.persistent,c.reg,c.privateMem⟩ m (choiceBits hd ++ bits) =
+ (execute M.program (fuel+27) mid m bits).map (Flow.prependEvents hd) at front
+ obtain ⟨len,_,ch⟩ := prelude_cost degree header m
+ change hd.length = degree+114 at len
+ change choiceBits hd = [] at ch
+ rw [len,ch,List.nil_append,initial] at front
+ have last := tail.execute fuel m bits
+ rw [List.length_replicate,(tick_cost (w := w) 27).2,List.nil_append] at last
+ rw [show fuel+degree+141 = (degree+114)+(fuel+27) by omega,front,last,Option.map_map]
+ congr 1
+ funext rep; simp only [Function.comp_apply,Flow.prependEvents,events,hd,List.append_assoc,header]
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameStore.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameStore.lean
new file mode 100644
index 0000000000..47cfd72818
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameStore.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.PairNativeFrameTable
+import OAI.Computability.VPVNP.PairSimulationLeafCacheWrite
+
+/-! # Installing the terminal geometry in actual private memory
+
+A vertex's call stores its frame pointer in private cell n and the twelve
+header operands at consecutive addresses starting at G. The cursor is the
+only register changed. The source register for field six also supplies n.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+
+open BurstRAM PrivateRAM PrimedInputRAM PrimedCounter.GuessWord LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {w p r : ℕ}
+
+/-- Private geometry pointer and twelve header fields after the store loop. -/
+structure Installed (c out : Config w p r) (reg : Fin 24 ↪ Fin r) (n G : ℕ) : Prop where
+ persistent : out.persistent = c.persistent
+ cursor : out.reg (reg 18) = ((G+12 : ℕ) : Word w)
+ registers : ∀ j, j ≠ reg 18 → out.reg j = c.reg j
+ pointer : out.privateMem (n : Word w) = (G : Word w)
+ fields : ∀ i : Fin 12, out.privateMem ((G+i.val : ℕ) : Word w) = c.reg (reg (fieldReg i))
+ outside : ∀ a : Word w, a.val ≠ n → a.val < G ∨ G+12 ≤ a.val → out.privateMem a = c.privateMem a
+
+private def ids := (List.finRange 12).map (Static.operand (k := 12))
+private theorem ids_get (i : Fin ids.length) : ids[i] = .operand (i.cast (by simp [ids])) := by
+ have get (j : Fin 12) :
+ ((List.finRange 12).map (Static.operand (k := 12)))[j.val]'(by simp) = .operand j := by
+ rw [List.getElem_map, List.getElem_finRange]
+ rfl
+ exact get (i.cast (by simp [ids]))
+
+private def port (reg : Fin 24 ↪ Fin r) : Static 12 → Fin r
+ | .operand i => reg (fieldReg i)
+ | _ => reg 3
+
+/-- Prefix of the literal fixed table from the pointer store up to the
+histogram handoff. All twenty-five events are private ticks. -/
+theorem store_run (flow : Flow r 11) (reg : Fin 24 ↪ Fin r) (savedHist cacheDst : Fin r)
+ (emb : Fin (Table.size flow) → Fin p) (finish : Instr 2 p r 11) (M : Machine w p r 11)
+ (rows : ∀ j, M.code (emb j) = (Table.row flow reg savedHist cacheDst emb finish j).resize w)
+ (n G : ℕ) (before : n < G) (fit : G+12 ≤ 2^w) (c : Config w p r)
+ (entry : c.pc = emb (Table.tail flow 0)) (hn : c.reg (reg 9) = (n : Word w))
+ (hg : c.reg (reg 2) = (G : Word w)) (hc : c.reg (reg 18) = (G : Word w))
+ (one : c.reg (reg 15) = 1) :
+ ∃ out, Prefix M c (List.replicate 25 .tick) out ∧
+ out.pc = emb (Table.store flow (Fin.last 12)) ∧ Installed c out reg n G := by
+ let b := c.store (emb (Table.store flow 0)) (n : Word w) (G : Word w)
+ have first : M.program.step c = .localStep b := by
+ change (M.code c.pc).run M.publicData c = _
+ rw [entry, rows, Table.at_pointer]
+ simp only [Instr.resize, Instr.run, hn, hg, b]
+ have len : ids.length = 12 := by simp [ids]
+ have hs (j : Static 12) : port reg j ≠ reg 18 := by
+ cases j <;> apply reg.injective.ne
+ all_goals first | decide | (intro he; have hh := congrArg Fin.val he; change 3 + _ = 18 at hh; omega)
+ let pc (j : Fin (ids.length+1)) := emb (Table.store flow (j.cast (by omega)))
+ let inc (j : Fin ids.length) := emb (Table.advance flow (j.cast len))
+ have storeRow (i : Fin ids.length) :
+ M.code (pc i.castSucc) = storeInstr (port reg) (reg 18) (inc i) ids[i] := by
+ rw [ids_get]
+ change M.code (emb (Table.store flow (i.cast len).castSucc)) = _
+ rw [rows, Table.at_store]
+ rfl
+ have incRow (i : Fin ids.length) :
+ M.code (inc i) = incInstr (reg 18) (reg 15) (pc i.succ) := by
+ dsimp only [inc]
+ rw [rows, Table.at_advance]
+ rfl
+ obtain ⟨out, run, done, S⟩ := write_rows M (port reg) (reg 18) (reg 15) hs
+ (reg.injective.ne (by decide)) ids (c.reg ∘ port reg) pc inc storeRow incRow G b rfl hc one
+ (fun _ => rfl) (by simpa only [len] using fit)
+ have memLen : (ids.map (c.reg ∘ port reg)).length = 12 := by simpa only [List.length_map] using len
+ refine ⟨out,?_,done,S.persistent,memLen ▸ S.cursor_end,S.frame,?_,?_,?_⟩
+ · change Prefix M c (.tick :: List.replicate 24 .tick) out
+ exact .tick first (by simpa only [len] using run)
+ · rw [S.outside _ (.inl (by change n % _ < G; rw [Nat.mod_eq_of_lt (by omega)]; exact before))]
+ exact Function.update_self ..
+ · intro i
+ have hi := S.values (i.cast memLen.symm)
+ change out.privateMem ((G+i.val : ℕ) : Word w) = (ids.map (c.reg ∘ port reg))[i.val]'_ at hi
+ rw [List.getElem_map] at hi
+ have eqn : ids[i.val]'(by omega) = .operand i := ids_get (i.cast len.symm)
+ rw [eqn] at hi
+ exact hi
+ · intro a hn ha
+ rw [S.outside _ (by simpa only [memLen] using ha)]
+ apply Function.update_of_ne
+ exact fun eqn => hn ((congrArg Fin.val eqn).trans (Nat.mod_eq_of_lt (by omega)))
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeFrameTable.lean b/lean/OAI/Computability/VPVNP/PairNativeFrameTable.lean
new file mode 100644
index 0000000000..97e5a35fbb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeFrameTable.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlow
+import OAI.Computability.VPVNP.PairNativeFrameReads
+
+/-! # Relocatable instruction rows for installing the terminal geometry frame
+
+The arithmetic and its six external reads enter a chain of thirteen private
+stores. The last two instructions hand the histogram base to the caller and
+the cache base to the leaf's operand initializer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+
+variable {r p : ℕ}
+
+/-- Local source register for frame field `i`, with the twelve words occupying consecutive
+registers 3 through 14. -/
+def fieldReg (i : Fin 12) : Fin 24 := (i.natAdd 3).castLE (by decide)
+
+namespace Table
+
+variable (a : Flow r 11)
+/-- Number of instruction rows for a frame prelude and its 29-row installation tail. -/
+def size := a.length+29
+
+/-- Program counter in the installation table corresponding to a label of the frame prelude. -/
+def label (j : a.Label) : Fin (size a) := ⟨(a.labels j).val,by have := (a.labels j).isLt; unfold size; omega⟩
+
+/-- Offset zero stores the frame pointer. Offsets 1 through 24 write the
+twelve fields and advance the cursor. -/
+def tail (j : Fin 29) : Fin (size a) := ⟨a.length+j.val,by have := j.isLt; unfold size; omega⟩
+/-- Address of the next field-store row, with index twelve denoting the histogram-pointer
+handoff after all fields have been written. -/
+def store (i : Fin 13) : Fin (size a) := tail a ⟨1+2*i.val,by have := i.isLt; omega⟩
+/-- Address of the unit cursor advance following frame field `i`, which transfers control to
+the next store position. -/
+def advance (i : Fin 12) : Fin (size a) := tail a ⟨2+2*i.val,by have := i.isLt; omega⟩
+
+/-- The caller supplies the continuation instruction at `tail 27`; the
+rejecting flow exit is at `tail 28`. -/
+def row (reg : Fin 24 ↪ Fin r) (savedHist cacheDst : Fin r) (emb : Fin (size a) → Fin p)
+ (finish : Instr 2 p r 11) (pc : Fin (size a)) : Instr 2 p r 11 :=
+ if h : pc.val < a.length then
+ ((a.code (a.labels.symm ⟨pc.val,h⟩)).map (fun t => (t.map (emb ∘ label a)).getD (emb (tail a 0)))).emit
+ (emb (tail a 28))
+ else
+ let j := pc.val - a.length
+ if j = 0 then .storePrivate (reg 9) (reg 2) (emb (store a 0))
+ else if h : (j-1)/2 < 12 then
+ let i : Fin 12 := ⟨(j-1)/2,h⟩
+ if (j-1)%2 = 0 then .storePrivate (reg 18) (reg (fieldReg i)) (emb (advance a i))
+ else .binary .add (reg 18) (reg 18) (reg 15) (emb (store a i.succ))
+ else if j = 25 then .copy savedHist (reg 14) (emb (tail a 26))
+ else if j = 26 then .copy cacheDst (reg 11) (emb (tail a 27))
+ else if j = 27 then finish else .reject
+
+variable (reg : Fin 24 ↪ Fin r) (savedHist cacheDst : Fin r) (emb : Fin (size a) → Fin p)
+ (finish : Instr 2 p r 11)
+
+theorem at_label (j : a.Label) :
+ row a reg savedHist cacheDst emb finish (label a j) =
+ ((a.code j).map (fun t => (t.map (emb ∘ label a)).getD (emb (tail a 0)))).emit (emb (tail a 28)) := by
+ simp [row,label,(a.labels j).isLt]
+
+theorem at_pointer : row a reg savedHist cacheDst emb finish (tail a 0) =
+ .storePrivate (reg 9) (reg 2) (emb (store a 0)) := by simp [row,tail]
+
+theorem at_store (i : Fin 12) : row a reg savedHist cacheDst emb finish (store a i.castSucc) =
+ .storePrivate (reg 18) (reg (fieldReg i)) (emb (advance a i)) := by
+ have hi : i.val < 12 := i.isLt
+ simp [row,store,tail,hi]
+
+theorem at_advance (i : Fin 12) : row a reg savedHist cacheDst emb finish (advance a i) =
+ .binary .add (reg 18) (reg 18) (reg 15) (emb (store a i.succ)) := by
+ have hi : i.val < 12 := i.isLt
+ have sub : 2+2*i.val-1 = 2*i.val+1 := by omega
+ have div : (2*i.val+1)/2 = i.val := by omega
+ simp [row,advance,tail,hi,sub,div]
+
+theorem at_hist : row a reg savedHist cacheDst emb finish (store a (Fin.last 12)) =
+ .copy savedHist (reg 14) (emb (tail a 26)) := by simp [row,store,tail]
+
+theorem at_cache : row a reg savedHist cacheDst emb finish (tail a 26) =
+ .copy cacheDst (reg 11) (emb (tail a 27)) := by simp [row,tail]
+
+theorem at_done : row a reg savedHist cacheDst emb finish (tail a 27) = finish := by simp [row,tail]
+theorem at_bad : row a reg savedHist cacheDst emb finish (tail a 28) = .reject := by simp [row,tail]
+
+theorem linked {w : ℕ} (M : Machine w p r 11)
+ (rows : ∀ j, M.code (emb j) = (row a reg savedHist cacheDst emb finish j).resize w) :
+ Flow.Linked M a (emb ∘ label a) (emb (tail a 0)) (emb (tail a 28)) := by
+ constructor
+ intro j; rw [Function.comp_apply,rows,at_label]
+
+end Table
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeGeometry.lean b/lean/OAI/Computability/VPVNP/PairNativeGeometry.lean
new file mode 100644
index 0000000000..e7fe8c00cb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeGeometry.lean
@@ -0,0 +1,161 @@
+import OAI.Computability.VPVNP.PairNativeGeometryFields
+import OAI.Computability.VPVNP.RAMSiteBounds
+
+/-!
+# Loading live geometry inside a pair simulation burst
+
+The eleven public words of the pair include the live length and address width
+at slots six and seven, and the literal prefix and its length at slots zero
+and one. The remaining geometry comes from bounded register arithmetic with
+the fixed numerator and denominator chosen for this live evaluator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairNativeGeometry
+open BurstRAM PrivateRAM PrimedInputRAM PrimedStackRAM Filter
+
+variable {w : ℕ}
+
+private def setup : Code := straight (.constant 0 1) [.constant 1 2,.publicWord 4 6,.publicWord 5 7,
+ .constant 3 0,.publicWord 8 1,.publicWord 9 0]
+
+private def load (pub : Fin 11 → Word w) (rs : Regs w 12) :=
+ ([(0,Fin.ofNat (2^w) 1),(1,Fin.ofNat (2^w) 2),(4,pub 6),(5,pub 7),(3,Fin.ofNat (2^w) 0),
+ (8,pub 1),(9,pub 0)] : List (Register × Word w)).foldl (fun x j => Function.update x j.1 j.2) rs
+
+/-- Load the live length, address width and literal prefix from the pair's public words, then
+compute the word width and rounded bucket size in registers. -/
+def program (a b : ℕ) : Code := .seq setup (.seq widthCode
+ (.seq (power 2 4 a) (.seq VirtualParameters.clogLoop (bucketCode b))))
+
+/-- Exact tick count for loading the geometry, including the power computation and the
+ceiling-logarithm loop on `n^a`. -/
+def ticks (a b n : ℕ) := 7 + (17 + ((a+1) + ((4*Nat.clog 2 (n^a)+1)+(b+4))))
+
+theorem clog_power_le (a n : ℕ) : Nat.clog 2 (n^a) ≤ a * Nat.clog 2 n := by
+ apply Nat.clog_le_of_le_pow
+ rw [Nat.mul_comm, pow_mul]
+ exact Nat.pow_le_pow_left (Nat.le_pow_clog Nat.one_lt_two n) a
+
+/-- For fixed ratio the arithmetic takes at most linearly many instructions
+in the bit length, including the final loop test. -/
+theorem ticks_le (a b n : ℕ) : ticks a b n ≤ 4*a*(n.log2+1) + a+b+30 := by
+ have h := (clog_power_le a n).trans (Nat.mul_le_mul_left a (clog_le_log2_succ n))
+ have := Nat.mul_le_mul_left 4 h
+ unfold ticks
+ rw [Nat.mul_assoc]
+ omega
+
+/-- Bounds on the power, denominator, rounded numerator and shift count that make the bucket
+computation exact in `w`-bit registers. -/
+structure Fits (a b n w : ℕ) : Prop where
+ power : n^a+1 < 2^w
+ denominator : b < 2^w
+ numerator : Nat.clog 2 (n^a)+(b-1) < 2^w
+ shift : roundedUp a b n < w
+
+/-- All register bounds hold uniformly at every sufficiently large length
+for each fixed choice of the two exponents and address multiplier. -/
+theorem eventually_fits (a b B : ℕ) (hB : 1 ≤ B) :
+ ∀ᶠ n : ℕ in atTop, Fits a b n ((addressWidth B n + 10)^4) := by
+ filter_upwards [eventually_polynomial_lt_wordModulus (a+1), eventually_ge_atTop (2^(a+b+2))] with n hp hn
+ let r := addressWidth B n
+ let w := (r+10)^4
+ have htwo : 2 ≤ n := (Nat.pow_le_pow_right (by decide : 0 < 2) (show 1 ≤ a+b+2 by omega)).trans hn
+ have hr : n.log2 ≤ r := log2_le_addressWidth hB n
+ have hbig := ((Nat.le_log2 (by omega : n ≠ 0)).mpr hn).trans hr
+ have hcr : Nat.clog 2 n ≤ r := Nat.le_mul_of_pos_left _ hB
+ have hlog := (clog_power_le a n).trans (Nat.mul_le_mul_left a hcr)
+ have htop : a*r+b+1 ≤ w := by
+ calc
+ _ ≤ (r+10)^2 := by nlinarith [Nat.mul_le_mul_right r (show a ≤ r by omega)]
+ _ ≤ _ := Nat.pow_le_pow_right (by omega : 0 < r+10) (by decide : 2 ≤ 4)
+ have hmod : w < 2^w := Nat.lt_two_pow_self
+ have hpow := hp r hr
+ have hmono := Nat.mul_le_mul_left (n^a) htwo
+ have hpos := Nat.pow_pos (by omega : 0 < n) (n := a)
+ change Fits a b n w
+ refine ⟨?_,by omega,by omega,?_⟩
+ · change n^(a+1) < 2^w at hpow
+ rw [pow_succ] at hpow; omega
+ · rw [roundedUp,Nat.clog_pow_left]
+ exact (Nat.div_le_self _ _).trans_lt (by omega)
+
+/-- Postcondition for the geometry loader. Registers 4 through 7 hold the length, address
+width, word width and bucket size, and registers 8 and 9 hold the public prefix length and
+word. -/
+structure Result (pub : Fin 11 → Word w) (a b n r : ℕ) (out : Regs w 12) : Prop where
+ length : (out 4).val = n
+ address : (out 5).val = r
+ width : (out 6).val = w
+ bucket : (out 7).val = 2^roundedUp a b n
+ prefixLength : out 8 = pub 1
+ prefixWord : out 9 = pub 0
+
+theorem program_run (pub : Fin 11 → Word w) (state : Word w) (m : Memory w) (rs : Regs w 12)
+ (a b n r : ℕ) (hb : 0 < b) (hn : 0 < n) (hw : w = (r+10)^4) (hf : Fits a b n w)
+ (h6 : (pub 6).val = n) (h7 : (pub 7).val = r) :
+ ∃ out, Flow.Exec pub state (program a b) rs m (List.replicate (ticks a b n) .tick) out m ∧
+ Result pub a b n r out := by
+ let s := load pub rs
+ have hstart : Flow.Exec pub state setup rs m (List.replicate 7 .tick) s m :=
+ (Flow.once_sound pub state false _ rs m rfl).1
+ have hlarge : 10 ≤ w := by
+ rw [hw]; exact (show 10 ≤ r+10 by omega).trans (Nat.le_self_pow (by decide) _)
+ have hmod : w < 2^w := Nat.lt_two_pow_self
+ have hsOne : (s 0).val = 1 := Nat.mod_eq_of_lt (by omega)
+ have hsTwo : (s 1).val = 2 := Nat.mod_eq_of_lt (by omega)
+ obtain ⟨t,width,hwval,keepT⟩ := width_run pub state m s r h7 hw hsOne
+ have htN : (t 4).val = n := (congrArg Fin.val (keepT 4 (by decide) (by decide))).trans h6
+ have hp : n^a < 2^w := Nat.lt_trans (Nat.lt_succ_self _) hf.power
+ let u := Function.update t (2 : Register) (⟨n^a,hp⟩ : Word w)
+ have hpow := power_run pub state m t 2 4 (by decide) n htN hn a hp
+ have keepU (j : Register) (h2 : j ≠ 2) : u j = t j := Function.update_of_ne h2 ..
+ have uone : (u 0).val = 1 := (congrArg Fin.val ((keepU 0 (by decide)).trans (keepT _ (by decide) (by decide)))).trans hsOne
+ have utwo : (u 1).val = 2 := (congrArg Fin.val ((keepU 1 (by decide)).trans (keepT _ (by decide) (by decide)))).trans hsTwo
+ have uzero : (u 3).val = 0 := by rw [keepU 3 (by decide),keepT 3 (by decide) (by decide)]; exact Nat.zero_mod _
+ have hlog : Nat.clog 2 (n^a) < 2^w := (Nat.le_add_right ..).trans_lt hf.numerator
+ obtain ⟨v,run,_,clog,keepV⟩ := VirtualParameters.clogRun pub state m (n^a) u uone utwo
+ (by simp [u]) uzero hf.power hlog
+ obtain ⟨out,finish,bucket,keep⟩ := bucket_run pub state m v a b n hb
+ ((congrArg Fin.val (keepV 0 (by decide) (by decide))).trans uone) clog hf.denominator hf.numerator hf.shift
+ have preserved (j : Register) (h2 : j ≠ 2) (h3 : j ≠ 3) (h7 : j ≠ 7) (h10 : j ≠ 10) (h11 : j ≠ 11) :
+ out j = t j := ((keep j h7 h10 h11).trans (keepV j h2 h3)).trans (keepU j h2)
+ refine ⟨out,seqTicks hstart (seqTicks width (seqTicks hpow (seqTicks run finish))),?_⟩
+ constructor
+ · exact (congrArg Fin.val (preserved 4 (by decide) (by decide) (by decide) (by decide) (by decide))).trans htN
+ · rw [preserved 5 (by decide) (by decide) (by decide) (by decide) (by decide),keepT 5 (by decide) (by decide)]
+ exact h7
+ · rw [preserved 6 (by decide) (by decide) (by decide) (by decide) (by decide)]; exact hwval
+ · exact bucket
+ · rw [preserved 8 (by decide) (by decide) (by decide) (by decide) (by decide),keepT 8 (by decide) (by decide)]; rfl
+ · rw [preserved 9 (by decide) (by decide) (by decide) (by decide) (by decide),keepT 9 (by decide) (by decide)]; rfl
+
+/-- In any linked occurrence, loading the pair geometry consumes only ticks.
+The continuation receives the original memories and choice stream. -/
+theorem program_execute {p : ℕ} (M : Machine w p 12 11) (state : Word w)
+ (priv : Word w → Word w) (m : Memory w) (rs : Regs w 12) (a b n r : ℕ)
+ (hb : 0 < b) (hn : 0 < n) (hw : w = (r+10)^4) (hf : Fits a b n w)
+ (h6 : (M.publicData 6).val = n) (h7 : (M.publicData 7).val = r)
+ (label : (program a b).Label → Fin p) (stop bad : Fin p)
+ (hl : Flow.Linked M (program a b) label stop bad) (hbad : M.code bad = .reject) :
+ ∃ out, Result M.publicData a b n r out ∧ ∀ fuel bits,
+ execute M.program (ticks a b n + fuel) ⟨label (program a b).entry,state,rs,priv⟩ m bits =
+ (execute M.program fuel ⟨stop,state,out,priv⟩ m bits).map
+ (Flow.prependEvents (List.replicate (ticks a b n) .tick)) := by
+ obtain ⟨out,run,done⟩ := program_run M.publicData state m rs a b n r hb hn hw hf h6 h7
+ have choices (t : ℕ) : choiceBits (List.replicate t (.tick : Event w)) = [] := by
+ induction t with
+ | zero => rfl
+ | succ t ih => simp [List.replicate_succ,choiceBits,ih]
+ refine ⟨out,done,fun fuel bits => ?_⟩
+ simpa only [List.length_replicate,choices,List.nil_append] using run.execute hl hbad priv fuel bits
+
+end PairNativeGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeGeometryArithmetic.lean b/lean/OAI/Computability/VPVNP/PairNativeGeometryArithmetic.lean
new file mode 100644
index 0000000000..fd155d0801
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeGeometryArithmetic.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.RAMVirtualParametersCode
+
+/-!
+# Fixed powers and literals in the live pair's native registers
+
+Both pieces are finite instruction text. Their lengths depend only on a
+fixed integer from the program. They preserve every register except their
+destination and produce one tick per instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairNativeGeometry
+open BurstRAM PrivateRAM PrimedInputRAM PrimedStackRAM
+
+/-- Instruction flows for computing the pair geometry in twelve registers with access to the
+eleven public words. -/
+abbrev Code := Flow 12 11
+/-- An index in the twelve-register bank used by the fixed-power and literal-loading routines. -/
+abbrev Register := Fin 12
+
+variable {w : ℕ} {pub : Fin 11 → Word w} {state : Word w} {m : Memory w}
+
+theorem seqTicks {a b : Code} {rs s t : Regs w 12} {i j : ℕ}
+ (h : Flow.Exec pub state a rs m (List.replicate i .tick) s m)
+ (k : Flow.Exec pub state b s m (List.replicate j .tick) t m) :
+ Flow.Exec pub state (.seq a b) rs m (List.replicate (i+j) .tick) t m := by
+ rw [List.replicate_add]; exact h.seq k
+
+/-- Raise the source register to a fixed natural power, starting from one. -/
+def power (dst src : Register) : ℕ → Code
+ | 0 => .line (.constant dst 1)
+ | j+1 => .seq (power dst src j) (.line (.binary .mul dst dst src))
+
+theorem power_run (pub : Fin 11 → Word w) (state : Word w) (m : Memory w)
+ (rs : Regs w 12) (dst src : Register) (hne : src ≠ dst) (n : ℕ) (hx : (rs src).val = n)
+ (hn : 0 < n) (a : ℕ) (hfit : n^a < 2^w) :
+ Flow.Exec pub state (power dst src a) rs m (List.replicate (a+1) .tick)
+ (Function.update rs dst ⟨n^a,hfit⟩) m := by
+ induction a with
+ | zero =>
+ apply Flow.Exec.line
+ have he : (Fin.ofNat (2^w) 1 : Word w) = ⟨n^0,hfit⟩ :=
+ Fin.ext (by simpa using Nat.mod_eq_of_lt (show 1 < 2^w by simpa using hfit))
+ change some ((Event.tick : Event w), Function.update rs dst (Fin.ofNat (2^w) 1), m) = _
+ rw [he]
+ | succ a ih =>
+ let hprev : n^a < 2^w := (Nat.pow_le_pow_right hn (Nat.le_succ a)).trans_lt hfit
+ let mid := Function.update rs dst (⟨n^a,hprev⟩ : Word w)
+ have hlast : Flow.Exec pub state (.line (.binary .mul dst dst src)) mid m
+ (List.replicate 1 .tick) (Function.update rs dst ⟨n^(a+1),hfit⟩) m := by
+ apply Flow.Exec.line
+ change some ((Event.tick : Event w), Function.update mid dst (BinaryOp.mul.eval (mid dst) (mid src)),m) = _
+ have hval : BinaryOp.mul.eval (mid dst) (mid src) = (⟨n^(a+1),hfit⟩ : Word w) := by
+ apply Fin.ext
+ change (mid dst).val * (mid src).val % (2^w) = n^(a+1)
+ rw [show (mid dst).val = n^a by simp [mid],
+ show (mid src).val = n by simpa [mid,hne] using hx, ← pow_succ, Nat.mod_eq_of_lt hfit]
+ rw [hval]; simp [mid]
+ exact seqTicks (ih hprev) hlast
+
+/-- Produce a fixed natural literal using only two-bit literal text. -/
+def literal (dst one : Register) : ℕ → Code
+ | 0 => .line (.constant dst 0)
+ | j+1 => .seq (literal dst one j) (.line (.binary .add dst dst one))
+
+theorem literal_run (pub : Fin 11 → Word w) (state : Word w) (m : Memory w)
+ (rs : Regs w 12) (dst one : Register) (hne : one ≠ dst) (h1 : (rs one).val = 1)
+ (b : ℕ) (hfit : b < 2^w) :
+ Flow.Exec pub state (literal dst one b) rs m (List.replicate (b+1) .tick)
+ (Function.update rs dst ⟨b,hfit⟩) m := by
+ induction b with
+ | zero => exact .line rfl
+ | succ b ih =>
+ let hprev : b < 2^w := (Nat.lt_succ_self _).trans hfit
+ let mid := Function.update rs dst (⟨b,hprev⟩ : Word w)
+ have hlast : Flow.Exec pub state (.line (.binary .add dst dst one)) mid m
+ (List.replicate 1 .tick) (Function.update rs dst ⟨b+1,hfit⟩) m := by
+ apply Flow.Exec.line
+ change some ((Event.tick : Event w), Function.update mid dst (BinaryOp.add.eval (mid dst) (mid one)),m) = _
+ have hval : BinaryOp.add.eval (mid dst) (mid one) = (⟨b+1,hfit⟩ : Word w) := by
+ apply Fin.ext
+ change ((mid dst).val + (mid one).val) % (2^w) = b+1
+ rw [show (mid dst).val = b by simp [mid],
+ show (mid one).val = 1 by simpa [mid,hne] using h1, Nat.mod_eq_of_lt hfit]
+ rw [hval]; simp [mid]
+ exact seqTicks (ih hprev) hlast
+
+end PairNativeGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeGeometryFields.lean b/lean/OAI/Computability/VPVNP/PairNativeGeometryFields.lean
new file mode 100644
index 0000000000..fe839dc610
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeGeometryFields.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairNativeGeometryArithmetic
+
+/-!
+# Native word width and rounded bucket for a live pair
+
+The width is the fourth power of the address width plus ten. The rounded
+bucket exponent is computed by integer ceiling division after the power
+and ceiling-logarithm instructions have completed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairNativeGeometry
+open BurstRAM PrivateRAM PrimedInputRAM PrimedStackRAM
+
+variable {w : ℕ}
+
+/-- Compute the machine word width by adding ten to the address width in register 5 and raising
+the sum to the fourth power in register 6. -/
+def widthCode : Code := .seq (literal 11 0 10) (.seq (.line (.binary .add 11 5 11)) (power 6 11 4))
+
+theorem width_run (pub : Fin 11 → Word w) (state : Word w) (m : Memory w) (rs : Regs w 12)
+ (r : ℕ) (hr : (rs 5).val = r) (hw : w = (r+10)^4) (h1 : (rs 0).val = 1) :
+ ∃ out, Flow.Exec pub state widthCode rs m (List.replicate 17 .tick) out m ∧
+ (out 6).val = w ∧ ∀ j : Register, j ≠ 6 → j ≠ 11 → out j = rs j := by
+ have hlarge : w < 2^w := Nat.lt_two_pow_self
+ have hr10 : r+10 ≤ w := hw ▸ Nat.le_self_pow (by decide) _
+ have h10 : 10 < 2^w := by omega
+ let s := Function.update rs (11 : Register) (⟨10,h10⟩ : Word w)
+ let t := Function.update s (11 : Register) (BinaryOp.add.eval (s 5) (s 11))
+ have ha := literal_run pub state m rs 11 0 (by decide) h1 10 h10
+ have hb : Flow.Exec pub state (.line (.binary .add 11 5 11)) s m (List.replicate 1 .tick) t m := .line rfl
+ have ht : (t 11).val = r+10 := by
+ change ((s 5).val+(s 11).val) % (2^w) = r+10
+ rw [show (s 5).val = r by simpa [s,Function.update_apply] using hr, show (s 11).val = 10 by simp [s],
+ Nat.mod_eq_of_lt (by omega)]
+ have hh : (r+10)^4 < 2^w := hw ▸ hlarge
+ have hc := power_run pub state m t 6 11 (by decide) (r+10) ht (by omega) 4 hh
+ refine ⟨_,seqTicks ha (seqTicks hb hc),by simp [hw],?_⟩
+ intro j hj h11
+ simp [t,s,Function.update_of_ne hj,Function.update_of_ne h11]
+
+/-- Round the logarithm in register 3 up by ceiling division by positive `b`, then shift one
+left by that quotient to obtain the bucket size in register 7. -/
+def bucketCode (b : ℕ) : Code :=
+ .seq (literal 10 0 (b-1)) (straight (.binary .add 11 3 10)
+ [.binary .add 10 10 0, .binary .div 11 11 10, .binary .shiftLeft 7 0 11])
+
+private theorem shifted_value {one x : Word w} (h1 : one.val = 1) (hx : x.val < w) :
+ (BinaryOp.shiftLeft.eval one x).val = 2^x.val := by
+ have hfit := Nat.pow_lt_pow_right Nat.one_lt_two hx
+ simp [BinaryOp.eval,hx,Nat.shiftLeft_eq,h1,Nat.mod_eq_of_lt hfit]
+
+theorem bucket_run (pub : Fin 11 → Word w) (state : Word w) (m : Memory w) (rs : Regs w 12)
+ (a b n : ℕ) (hb : 0 < b) (h1 : (rs 0).val = 1) (hlog : (rs 3).val = Nat.clog 2 (n^a))
+ (hbfit : b < 2^w) (hsum : Nat.clog 2 (n^a)+(b-1) < 2^w) (hshift : roundedUp a b n < w) :
+ ∃ out, Flow.Exec pub state (bucketCode b) rs m (List.replicate (b+4) .tick) out m ∧
+ (out 7).val = 2^roundedUp a b n ∧ ∀ j : Register, j ≠ 7 → j ≠ 10 → j ≠ 11 → out j = rs j := by
+ let s := Function.update rs (10 : Register) (⟨b-1, by omega⟩ : Word w)
+ let num := BinaryOp.add.eval (s 3) (s 10)
+ let den := BinaryOp.add.eval (s 10) (s 0)
+ let exp := BinaryOp.div.eval num den
+ let result := BinaryOp.shiftLeft.eval (s 0) exp
+ let out := ([(11,num),(10,den),(11,exp),(7,result)] : List (Register × Word w)).foldl
+ (fun x j => Function.update x j.1 j.2) s
+ have hlit := literal_run pub state m rs 10 0 (by decide) h1 (b-1) (show b-1 < 2^w by omega)
+ have hrest : Flow.Exec pub state
+ (straight (.binary .add 11 3 10) [.binary .add 10 10 0,.binary .div 11 11 10,.binary .shiftLeft 7 0 11])
+ s m (List.replicate 4 .tick) out m := (Flow.once_sound pub state false _ s m rfl).1
+ have ho : (s 0).val = 1 := by simpa [s,Function.update_apply] using h1
+ have hx : (s 3).val = Nat.clog 2 (n^a) := by simpa [s,Function.update_apply] using hlog
+ have hp : (s 10).val = b-1 := by simp [s]
+ have hn : num.val = Nat.clog 2 (n^a)+(b-1) := by
+ change ((s 3).val+(s 10).val) % (2^w) = _; rw [hx,hp,Nat.mod_eq_of_lt hsum]
+ have hd : den.val = b := by
+ change ((s 10).val+(s 0).val) % (2^w) = _; rw [hp,ho,show b-1+1 = b by omega,Nat.mod_eq_of_lt hbfit]
+ have he : exp.val = roundedUp a b n := by
+ change (num.val / den.val) % (2^w) = roundedUp a b n
+ rw [Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt num.isLt),hn,hd,roundedUp,Nat.clog_pow_left]
+ refine ⟨out,?_,?_,?_⟩
+ · rw [show b+4 = ((b-1)+1)+4 by omega]; exact seqTicks hlit hrest
+ · change result.val = _
+ rw [shifted_value ho (he ▸ hshift),he]
+ · intro j hj h10 h11
+ simp [out,s,Function.update_of_ne hj,Function.update_of_ne h10,Function.update_of_ne h11]
+
+end PairNativeGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeLeafSetupRun.lean b/lean/OAI/Computability/VPVNP/PairNativeLeafSetupRun.lean
new file mode 100644
index 0000000000..c1ad09f4dc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeLeafSetupRun.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.PairNativeLeafSetupTable
+import OAI.Computability.VPVNP.PairNativeCachePaper
+import OAI.Computability.VPVNP.PairNativeFrameLeaf
+import OAI.Computability.VPVNP.PairSimulationLeafImagePreparation
+
+/-! # Native geometry and auxiliary-counter cache in the same vertex burst
+
+The true eleven pair operands and the six terminal header reads determine
+both regions. The geometry pointer and all twelve fields survive the cache
+writes. Every path then continues from the same private configuration and
+with the entire supplied choice tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeLeafSetup
+
+open BurstRAM PrivateRAM LiveProgram PrimedInputRAM PrimedStackRAM PrimedCounter.GuessWord NativeOperands
+open CursorNetwork CursorRouting LeafSourceLoad LeafRegisterBank
+open scoped Fin.CommRing
+
+attribute [local irreducible] NativeOperands.capacity NativeOperands.saved
+
+variable {c : Constants} {r pcs : ℕ} (K : Block c r)
+ {p : UniversalMachine.Program} {B n H : ℕ} {i : Fin (2^(n^c.chainPower-1))}
+ (Q : Layout (CounterPublic.spec p c |>.lengths n i) n (addressWidth B n) H (CursorBounds.wordBits B n))
+ (D : PrimedCounter.Data Q (n^(c.circuitExponent+5)))
+
+local notation "w" => CursorBounds.wordBits B n
+local notation "d" => CursorBounds.virtualBits B n
+local notation "e" => roundedUp 1 4 n
+local notation "geom" => AssemblerPublic.geometry B n H
+
+theorem paper_run (hb : 0 < K.denominator) (hB : 1 ≤ B) (hn : 3 ≤ n)
+ (hH : H = 2^roundedUp K.numerator K.denominator n)
+ (fit : PairNativeGeometry.Fits K.numerator K.denominator n w)
+ (hp : Q.program = p) (hbase : Q.scratchBase = 2^d) (hf : D.Fits) (hroot : D.root.val = 0)
+ (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (M : Machine w pcs r 11)
+ (hpub : M.publicData = Pieces.word geom (CounterPublic.actualPrefix p) ∘ StageOperands.pair c)
+ (pc : Fin (size K) → Fin pcs) (ret : Instr 2 pcs r 11)
+ (rows : ∀ j, M.code (pc j) = (row K pc ret j).resize w)
+ (m : Memory w) (st : Config w pcs r) (start : st.pc = pc (entry K))
+ (before : (M.publicData 6).val < NativeFrame.frameBase
+ (NativeFrame.fromHeader K.degree M.publicData (st.reg K.frame.header) m))
+ (room : (NativeFrame.fromHeader K.degree M.publicData (st.reg K.frame.header) m).cacheBase+38 ≤ 2^w) :
+ let A := NativeFrame.fromHeader K.degree M.publicData (st.reg K.frame.header) m
+ let G := NativeFrame.frameBase A
+ let header := st.reg K.frame.header
+ let role := st.reg K.frame.role
+ ∃ ticks ≤ work (NativeCache.args c) K.numerator K.denominator geom+76, ∃ out : Config w pcs r,
+ out.pc = pc (done K) ∧ out.persistent = st.persistent ∧ out.reg K.frame.hist = (A.histBase : Word w) ∧
+ LeafGeometryLoad.Stored (M.publicData 6).val G out.privateMem (NativeFrame.leafWords K.degree M.publicData header role m) ∧
+ (∀ j : Fin 12, out.privateMem ((G+j.val : ℕ) : Word w) = NativeFrame.fields K.degree M.publicData header role m j) ∧
+ Cached A.cacheBase out.privateMem (LeafVisit.cacheWords D d e) ∧
+ (∀ a : Word w, a ≠ M.publicData 6 → (a.val < G ∨ G+12 ≤ a.val) →
+ (a.val < A.cacheBase ∨ A.cacheBase+38 ≤ a.val) → out.privateMem a = st.privateMem a) ∧
+ (∀ j, j ∉ Set.range K.frame.work → j ≠ K.frame.hist → j ∉ Set.range K.cache → out.reg j = st.reg j) ∧
+ ∀ fuel bits, execute M.program (fuel+ticks+K.degree+142) st m bits =
+ (execute M.program fuel out m bits).map
+ (Flow.prependEvents (NativeFrame.events K.degree header m ++ List.replicate (ticks+1) .tick)) := by
+ intro A G header role
+ have pubN : (M.publicData 6).val = n := by
+ rw [hpub]
+ exact Nat.mod_eq_of_lt (PrimedInputRAM.Opcodes.pubNat_lt Q hf.assembler 1)
+ have cacheEq : A.cacheBase = G + n^5 := by
+ change G + (M.publicData 6).val^5 = _
+ rw [pubN]
+ have sep : G+12 ≤ A.cacheBase := by
+ have pos : 3^5 ≤ n^5 := Nat.pow_le_pow_left hn _
+ omega
+ have frows j : M.code ((pc ∘ framePC K) j) =
+ (K.frame.row K.degree (pc ∘ framePC K) (handoff K pc) j).resize w := by
+ rw [Function.comp_apply,rows,frame_row]
+ obtain ⟨mid, stop, installed, run⟩ := NativeFrame.run K.frame K.degree M (pc ∘ framePC K)
+ (handoff K pc) frows m st start before (by change G+12 ≤ _; change A.cacheBase+38 ≤ _ at room; omega)
+ let next : Config w pcs r := {mid with pc := pc (cacheEntry K)}
+ have jump : M.program.step mid = .localStep next := by
+ change (M.code mid.pc).run M.publicData mid = _
+ rw [stop, frows]
+ change ((NativeFrame.Table.row (frameFlow K) _ _ _ _ _ _).resize w).run M.publicData mid = _
+ rw [NativeFrame.Table.at_done]
+ simp only [handoff,Instr.resize,Instr.run,ite_self,next]
+ have crows j : M.code ((pc ∘ cachePC K) j) =
+ (NativeCacheTable.row (cacheFlow K) (NativeCache.storeSrc c K.cache) (NativeCache.ptr c K.cache)
+ (NativeCache.one c K.cache) (pc ∘ cachePC K) ret j).resize w := by
+ rw [Function.comp_apply,rows,cache_row]
+ have vd : 0 < d := (Nat.mul_pos (show 0 < B by omega)
+ (Nat.clog_pos (by decide : 1 < 2) (show 1 < n by omega))).trans_le (CursorBounds.addressBits_le_virtualBits B n hn)
+ let v : Position d := (⟨0,vd⟩,0)
+ let buf : Buffers d (2^e) w := fun _ _ => false
+ have cachePort : next.reg (K.cache (saved (NativeCache.args c))) = (A.cacheBase : Word w) := by
+ change mid.reg _ = _
+ rw [← K.basePort]
+ exact installed.cache
+ obtain ⟨t,ht,out,cacheSteps,pcOut,cached,rest,persist,regs⟩ := NativeCache.paper_run c Q D K.numerator K.denominator
+ hb hB (by omega) hH fit hp hbase hf hroot hw hc K.cache M hpub (pc ∘ cachePC K) ret crows
+ A.cacheBase room next rfl cachePort v buf
+ have saved := installed.stored_after out.privateMem (before.trans_le (by change G ≤ A.cacheBase; omega))
+ sep (by change A.cacheBase ≤ _; change A.cacheBase+38 ≤ _ at room; omega)
+ (fun j h => rest j (.inl h))
+ have cacheVals j : sourceWord (LeafStartup.auxiliary D hw hc v buf) D.pub (Static.dest j) =
+ LeafVisit.cacheWords D d e j := by cases j <;> rfl
+ refine ⟨t,ht,out,pcOut,persist.trans installed.persistent,(regs _ K.histogramPort).trans installed.hist,
+ saved.1,saved.2,fun j => (cached j).trans (cacheVals j),?_,?_,?_⟩
+ · intro a ha hg hc'
+ exact (rest a hc').trans (installed.outside a ha hg)
+ · intro j hf' hh hcache
+ apply (regs _ hcache).trans
+ exact installed.registers j hf' hh (fun eq => hcache ⟨_,K.basePort.symm.trans eq.symm⟩)
+ · intro fuel bits
+ have steps := (Prefix.tick jump cacheSteps).execute fuel m bits
+ change execute M.program (fuel+(.tick :: List.replicate t .tick : List (Event w)).length) mid m
+ (choiceBits (.tick :: List.replicate t .tick) ++ bits) = _ at steps
+ have ch : choiceBits (.tick :: List.replicate t (.tick : Event w)) = [] :=
+ (@NativeFrame.tick_cost (CursorBounds.wordBits B n) t).2
+ rw [List.length_cons,List.length_replicate,ch,List.nil_append] at steps
+ rw [show fuel+t+K.degree+142 = (fuel+(t+1))+K.degree+141 by omega,run,steps,Option.map_map]
+ congr 1
+ funext rep
+ simp only [Function.comp_apply,Flow.prependEvents,List.replicate_succ,List.append_assoc,header]
+
+end PairSimulation.NativeLeafSetup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeLeafSetupTable.lean b/lean/OAI/Computability/VPVNP/PairNativeLeafSetupTable.lean
new file mode 100644
index 0000000000..af13fe1153
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeLeafSetupTable.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PairNativeFrameRun
+import OAI.Computability.VPVNP.PairNativeCacheRun
+
+/-! # One native instruction block for initializing a vertex's leaf verifier
+
+The first part installs the descriptor geometry and supplies the cache base
+to the operand compiler. One deterministic jump enters the compiler, which
+writes the 38 auxiliary-counter operands before returning to the vertex body.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeLeafSetup
+
+open BurstRAM PrivateRAM LiveProgram PrimedInputRAM NativeOperands
+open scoped Fin.CommRing
+
+variable {r p : ℕ}
+
+attribute [local irreducible] NativeOperands.capacity NativeOperands.saved
+
+/-- Register assignment for the terminal geometry and the auxiliary operand cache. -/
+structure Placement (count : ℕ) (slot : Fin count) (r : ℕ) where
+ /-- Fixed port degree of the final layer. -/
+ degree : ℕ
+ /-- Numerator of the live bucket exponent. -/
+ numerator : ℕ
+ /-- Denominator of the live bucket exponent. -/
+ denominator : ℕ
+ /-- Registers used by the geometry reader and private store loop. -/
+ frame : NativeFrame.Ports r
+ /-- Registers used by the auxiliary operand compiler. -/
+ cache : Fin count ↪ Fin r
+ basePort : frame.cache = cache slot
+ histogramPort : frame.hist ∉ Set.range cache
+
+/-- The geometry and cache components with the compiler's saved base register. -/
+abbrev Block (c : Constants) (r : ℕ) := Placement (NativeCache.bankSize c) (saved (NativeCache.args c)) r
+
+variable {c : Constants} (K : Block c r)
+
+/-- Native geometry calculation preceding the private stores. -/
+abbrev frameFlow := K.frame.code K.degree
+/-- Native expression evaluator that precedes the cache writes. -/
+abbrev cacheFlow := NativeCache.code c K.numerator K.denominator K.cache
+/-- Number of program-counter locations reserved for geometry installation. -/
+abbrev frameSize := NativeFrame.Table.size (frameFlow K)
+/-- Number of program-counter locations reserved for the operand cache. -/
+abbrev cacheSize := NativeCacheTable.size (cacheFlow K)
+/-- Number of locations in the concatenated instruction table. -/
+abbrev size := frameSize K + cacheSize K
+
+/-- Include a geometry instruction address in the combined table. -/
+def framePC (j : Fin (frameSize K)) : Fin (size K) := j.castAdd (cacheSize K)
+/-- Include a cache instruction address after the geometry block. -/
+def cachePC (j : Fin (cacheSize K)) : Fin (size K) := j.natAdd (frameSize K)
+/-- First instruction executed by the geometry reader. -/
+def entry := framePC K (NativeFrame.Table.label (frameFlow K) (frameFlow K).entry)
+/-- Destination of the jump from geometry installation to cache computation. -/
+def cacheEntry := cachePC K (NativeCacheTable.label (cacheFlow K) (cacheFlow K).entry)
+/-- Location where the caller's continuation replaces the cache return. -/
+def done := cachePC K (NativeCacheTable.done (cacheFlow K))
+
+/-- Unconditional native jump to the cache initializer. -/
+def handoff (pc : Fin (size K) → Fin p) : Instr 2 p r 11 :=
+ .jumpEq K.frame.cache K.frame.cache (pc (cacheEntry K)) (pc (cacheEntry K))
+
+/-- Opcode of the combined table with all program counters relocated. -/
+def row (pc : Fin (size K) → Fin p) (ret : Instr 2 p r 11) : Fin (size K) → Instr 2 p r 11 :=
+ Fin.addCases (K.frame.row K.degree (pc ∘ framePC K) (handoff K pc))
+ (NativeCacheTable.row (cacheFlow K) (NativeCache.storeSrc c K.cache) (NativeCache.ptr c K.cache)
+ (NativeCache.one c K.cache) (pc ∘ cachePC K) ret)
+
+theorem frame_row (pc : Fin (size K) → Fin p) (ret : Instr 2 p r 11) (j : Fin (frameSize K)) :
+ row K pc ret (framePC K j) = K.frame.row K.degree (pc ∘ framePC K) (handoff K pc) j :=
+ Fin.addCases_left ..
+
+theorem cache_row (pc : Fin (size K) → Fin p) (ret : Instr 2 p r 11) (j : Fin (cacheSize K)) :
+ row K pc ret (cachePC K j) = NativeCacheTable.row (cacheFlow K)
+ (NativeCache.storeSrc c K.cache) (NativeCache.ptr c K.cache) (NativeCache.one c K.cache)
+ (pc ∘ cachePC K) ret j := Fin.addCases_right ..
+
+/-- Standalone eleven-operand table with an accepting continuation. -/
+def template : Template (size K) r 11 := ⟨2, entry K, row K id .accept⟩
+
+end PairSimulation.NativeLeafSetup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeOperandArithmetic.lean b/lean/OAI/Computability/VPVNP/PairNativeOperandArithmetic.lean
new file mode 100644
index 0000000000..bacdf03248
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeOperandArithmetic.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.PairNativeOperandBase
+
+/-! # Native word arithmetic for the pair's private operand bank -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeOperands
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM LiveProgram
+open scoped Fin.CommRing
+
+/-- The four binary operations available when combining two native operand values. -/
+inductive Arithmetic where | add | sub | mul | div
+
+/-- Natural-number interpretation of the binary operand operations, using truncated subtraction
+and integer division. -/
+def Arithmetic.value : Arithmetic → ℕ → ℕ → ℕ
+ | .add => (·+·) | .sub => (·-·) | .mul => (·*·) | .div => (·/·)
+
+/-- Instruction flow that combines `dst` with `rhs` in place. The subtraction branch writes
+zero when the right operand exceeds the left. -/
+def Arithmetic.op {r : ℕ} (dst rhs : Fin (registerCount r)) : Arithmetic → Code r
+ | .add => .line (.binary .add dst dst rhs)
+ | .sub => .ifLt dst rhs (.line (.constant dst 0)) (.line (.binary .sub dst dst rhs))
+ | .mul => .line (.binary .mul dst dst rhs)
+ | .div => .line (.binary .div dst dst rhs)
+
+private theorem op_run {r w : ℕ} (pub : Fin 11 → Word w) (st : Word w) (m : Memory w)
+ (rs : Regs w (registerCount r)) (dst rhs : Fin (registerCount r)) (op : Arithmetic)
+ {x y : ℕ} (hx : rs dst = Fin.ofNat _ x) (hy : rs rhs = Fin.ofNat _ y) (fx : x < 2^w) (fy : y < 2^w) :
+ ∃ t ≤ 2, Flow.Exec pub st (op.op dst rhs) rs m (List.replicate t .tick)
+ (Function.update rs dst (Fin.ofNat _ (op.value x y))) m := by
+ have vx : (rs dst).val = x := hx ▸ Nat.mod_eq_of_lt fx
+ have vy : (rs rhs).val = y := hy ▸ Nat.mod_eq_of_lt fy
+ cases op with
+ | add =>
+ refine ⟨1,by decide,Flow.Exec.line ?_⟩
+ simp only [Op.effect,BinaryOp.eval,hx,hy,Arithmetic.value]
+ rw [show Fin.ofNat (2^w) x + Fin.ofNat (2^w) y = Fin.ofNat _ (x+y) from (Nat.cast_add (R := Word w) ..).symm]
+ | mul =>
+ refine ⟨1,by decide,Flow.Exec.line ?_⟩
+ simp only [Op.effect,BinaryOp.eval,hx,hy,Arithmetic.value]
+ rw [show Fin.ofNat (2^w) x * Fin.ofNat (2^w) y = Fin.ofNat _ (x*y) from (Nat.cast_mul (α := Word w) x y).symm]
+ | div =>
+ refine ⟨1,by decide,Flow.Exec.line ?_⟩
+ simp only [Op.effect,BinaryOp.eval,vx,vy,Arithmetic.value]
+ | sub =>
+ by_cases h : x < y
+ · refine ⟨2,le_rfl,.ifLtYes (by change (rs dst).val < (rs rhs).val; omega) (.line ?_)⟩
+ simp [Op.effect,Arithmetic.value,Nat.sub_eq_zero_of_le h.le]
+ · refine ⟨2,le_rfl,.ifLtNo (by change ¬(rs dst).val < (rs rhs).val; omega) (.line ?_)⟩
+ simp only [Op.effect,BinaryOp.eval,hx,hy,Arithmetic.value]
+ rw [show Fin.ofNat (2^w) x - Fin.ofNat (2^w) y = Fin.ofNat _ (x-y) from
+ (Nat.cast_sub (R := Word w) (Nat.le_of_not_gt h)).symm]
+
+/-- Run the two operand flows in order, then combine the values in temporary slots `base` and
+`base+1` and leave the result in `base`. -/
+def combine {r : ℕ} (op : Arithmetic) (base : ℕ) (a b : Code r) : Code r :=
+ .seq (.seq a b) (op.op (temp r base) (temp r (base+1)))
+
+theorem combine_eval (g : Geometry) (lit : LiteralPrefix) {r base x y u v : ℕ} (hroom : base+1 ≤ r)
+ (op : Arithmetic) {a b : Code r} (ha : Eval g lit r base x u a) (hb : Eval g lit r (base+1) y v b)
+ (fx : x < 2^g.w) (fy : y < 2^g.w) : Eval g lit r base (op.value x y) (u+v+2) (combine op base a b) := by
+ intro pub st m rs ready
+ obtain ⟨t,ht,mid,first,hx,keep⟩ := ha pub st m rs ready
+ obtain ⟨s,hs,z,second,hy,preserve⟩ := hb pub st m mid (keep.ready ready)
+ have hx' : z (temp r base) = Fin.ofNat _ x := by
+ apply Eq.trans (preserve _ ?_ ?_) hx
+ all_goals rw [temp_val (by omega)]; omega
+ obtain ⟨k,hk,run⟩ := op_run pub st m z _ _ op hx' hy fx fy
+ exact ⟨_,by omega,_,seqTicks (seqTicks first second) run,Function.update_self ..,
+ (keep.trans (preserve.mono (by omega))).trans (update_keep (by omega) z _)⟩
+
+/-- Evaluate the exponent at `base` and replace it with a left shift of one by that exponent. -/
+def pow2 {r : ℕ} (base : ℕ) (a : Code r) : Code r :=
+ .seq (.seq a (.line (.constant (fixed r 0) 1)))
+ (.line (.binary .shiftLeft (temp r base) (fixed r 0) (temp r base)))
+
+theorem pow2_eval (g : Geometry) (lit : LiteralPrefix) {r base x u : ℕ} (hroom : base ≤ r)
+ {a : Code r} (ha : Eval g lit r base x u a) (hx : x < 2^g.w) (hf : 2^x < 2^g.w) :
+ Eval g lit r base (2^x) (u+2) (pow2 base a) := by
+ intro pub st m rs ready
+ obtain ⟨t,ht,mid,run,hval,keep⟩ := ha pub st m rs ready
+ let z := Function.update mid (fixed r 0) (Fin.ofNat (2^g.w) 1)
+ have h1 : Flow.Exec pub st (.line (.constant (fixed r 0) 1)) mid m (List.replicate 1 .tick) z m := .line rfl
+ have hval' : (z (temp r base)).val = x := by
+ rw [show z (temp r base) = mid (temp r base) from Function.update_of_ne (temp_ne_fixed (r := r) base 0) _ _,hval]
+ exact Nat.mod_eq_of_lt hx
+ have he : x < g.w := (Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp hf
+ have hone : (z (fixed r 0)).val = 1 := by
+ rw [show z (fixed r 0) = Fin.ofNat _ 1 from Function.update_self ..]
+ exact Nat.mod_eq_of_lt ((Nat.one_le_two_pow (n := x)).trans_lt hf)
+ have h2 : Flow.Exec pub st (.line (.binary .shiftLeft (temp r base) (fixed r 0) (temp r base)))
+ z m (List.replicate 1 .tick) (Function.update z (temp r base) (Fin.ofNat _ (2^x))) m := by
+ apply Flow.Exec.line
+ simp [Op.effect,BinaryOp.eval,hval',hone,he,Nat.shiftLeft_eq]
+ exact ⟨_,by omega,_,seqTicks (seqTicks run h1) h2,Function.update_self ..,
+ (keep.trans (scratch_keep mid 0 (by decide) _)).trans (update_keep hroom z _)⟩
+
+end PairSimulation.NativeOperands
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeOperandBase.lean b/lean/OAI/Computability/VPVNP/PairNativeOperandBase.lean
new file mode 100644
index 0000000000..dda8d83bf8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeOperandBase.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.LiveProgramPieces
+import Mathlib.Data.ZMod.Defs
+import OAI.Computability.VPVNP.PrimedCounterRenameRun
+import OAI.Computability.VPVNP.RAMTapePublicInputOperands
+
+/-!
+# Native register computation of the compressed pair's static operands
+
+The first twelve registers belong to the geometry and logarithm kernels.
+Expression registers follow those registers in increasing order. Computing
+a right operand one register higher leaves the left operand available for
+the arithmetic instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeOperands
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM LiveProgram
+open scoped Fin.CommRing
+
+/-- Size of the operand register bank, with twelve fixed registers followed by temporary slots
+numbered from zero through `r`. -/
+abbrev registerCount (r : ℕ) := 12+(r+1)
+/-- Native operand flows with temporary slots up to `r` and access to the eleven public
+pair-stage words. -/
+abbrev Code (r : ℕ) := Flow (registerCount r) 11
+
+/-- Locate a geometry or logarithm register at the same index in the enlarged operand bank. -/
+def fixed (r : ℕ) (i : Fin 12) : Fin (registerCount r) := i.castAdd (r+1)
+
+/-- The injective register map used to lift executions of twelve-register routines into the
+native operand bank. -/
+def fixedEmbedding (r : ℕ) : Fin 12 ↪ Fin (registerCount r) :=
+ ⟨fixed r,fun _ _ h => Fin.ext (congrArg (fun j : Fin (registerCount r) => j.val) h)⟩
+
+/-- Locate a temporary operand register after the twelve fixed registers, reducing the slot
+index modulo `r+1`. -/
+def temp (r base : ℕ) : Fin (registerCount r) := (Fin.ofNat (r+1) base).natAdd 12
+
+theorem temp_val {r base : ℕ} (h : base ≤ r) : (temp r base).val = 12+base := by
+ change 12+base%(r+1) = _
+ rw [Nat.mod_eq_of_lt (by omega)]
+
+/-- The six input words shared with the tape operand evaluator, encoding length, address width,
+bucket size, word width, prefix length and packed prefix value. -/
+def words (g : Geometry) (lit : LiteralPrefix) : Fin 6 → Word g.w :=
+ RAMTape.InputOperandMachine.input g lit
+
+/-- Register assignment for the six operand inputs in logical order. The bucket precedes the
+word width in that order and occupies register 7. -/
+def inputSlot : Fin 6 → Fin 12 := ![4,5,7,6,8,9]
+
+/-- Locate the fixed register holding logical input `i` in an operand bank with temporary slots
+up to `r`. -/
+abbrev inputReg (r : ℕ) (i : Fin 6) := fixed r (inputSlot i)
+
+/-- The six designated registers already contain the encoded geometry and prefix words required
+by operand evaluation. -/
+def Ready (g : Geometry) (lit : LiteralPrefix) {r : ℕ} (rs : Regs g.w (registerCount r)) : Prop :=
+ ∀ i : Fin 6, rs (inputReg r i) = words g lit i
+
+/-- The output agrees with the input on registers from 4 up to but excluding `12+base`,
+protecting the fixed inputs and all earlier temporary results. -/
+def Keeps {r w : ℕ} (base : ℕ) (rs out : Regs w (registerCount r)) : Prop :=
+ ∀ i, 4 ≤ i.val → i.val < 12+base → out i = rs i
+
+theorem Keeps.ready {g : Geometry} {lit : LiteralPrefix} {r base : ℕ}
+ {rs out : Regs g.w (registerCount r)} (h : Keeps base rs out) (hr : Ready g lit rs) :
+ Ready g lit out := by
+ intro i
+ have hi : 4 ≤ (inputSlot i).val := by fin_cases i <;> decide
+ have hlt := (inputSlot i).isLt
+ exact (h _ hi (show (inputSlot i).val < 12+base by omega)).trans (hr i)
+
+/-- From any ready bank the code produces the word for `v` in temporary slot `base` within the
+tick budget, preserves the protected registers and returns the original memory. -/
+def Eval (g : Geometry) (lit : LiteralPrefix) (r base v steps : ℕ) (code : Code r) : Prop :=
+ ∀ (pub : Fin 11 → Word g.w) (state : Word g.w) (m : Memory g.w) (rs : Regs g.w (registerCount r)),
+ Ready g lit rs → ∃ t ≤ steps, ∃ out : Regs g.w (registerCount r),
+ Flow.Exec pub state code rs m (List.replicate t .tick) out m ∧
+ out (temp r base) = Fin.ofNat _ v ∧ Keeps base rs out
+
+theorem seqTicks {w r k : ℕ} {pub : Fin k → Word w} {state : Word w} {m : Memory w}
+ {a b : Flow r k} {rs mid out : Regs w r} {j t : ℕ}
+ (ha : Flow.Exec pub state a rs m (List.replicate j .tick) mid m)
+ (hb : Flow.Exec pub state b mid m (List.replicate t .tick) out m) :
+ Flow.Exec pub state (.seq a b) rs m (List.replicate (j+t) .tick) out m := by
+ simpa only [List.replicate_add] using ha.seq hb
+
+theorem update_keep {r w base : ℕ} (hb : base ≤ r) (rs : Regs w (registerCount r))
+ (v : Word w) : Keeps base rs (Function.update rs (temp r base) v) := by
+ intro i _ hi
+ exact Function.update_of_ne (fun h => by rw [h,temp_val hb] at hi; omega) ..
+
+theorem scratch_keep {r w base : ℕ} (rs : Regs w (registerCount r)) (j : Fin 12)
+ (hj : j.val < 4) (v : Word w) : Keeps base rs (Function.update rs (fixed r j) v) := by
+ intro i hi _
+ have he : (fixed r j).val = j.val := rfl
+ exact Function.update_of_ne (fun h => by rw [h,he] at hi; omega) ..
+
+theorem Keeps.trans {r w b : ℕ} {rs mid out : Regs w (registerCount r)}
+ (h : Keeps b rs mid) (k : Keeps b mid out) : Keeps b rs out :=
+ fun i lo hi => (k i lo hi).trans (h i lo hi)
+
+theorem Keeps.mono {r w a b : ℕ} {rs out : Regs w (registerCount r)} (h : Keeps b rs out) (hab : a ≤ b) :
+ Keeps a rs out := fun i lo hi => h i lo (by omega)
+
+private def addUnits {r : ℕ} (dst : Fin (registerCount r)) : ℕ → Code r
+ | 0 => .line (.constant dst 0)
+ | n+1 => .seq (addUnits dst n) (.line (.binary .add dst dst (fixed r 0)))
+
+/-- Build the literal `n` in the destination register by loading one into scratch register 0
+and adding that unit `n` times from zero. -/
+def literal {r : ℕ} (dst : Fin (registerCount r)) (n : ℕ) : Code r :=
+ .seq (.line (.constant (fixed r 0) 1)) (addUnits dst n)
+
+private theorem addUnits_run {w r : ℕ} (pub : Fin 11 → Word w) (state : Word w) (m : Memory w)
+ (rs : Regs w (registerCount r)) (dst : Fin (registerCount r)) (hd : dst ≠ fixed r 0)
+ (h1 : rs (fixed r 0) = 1) (n : ℕ) :
+ Flow.Exec pub state (addUnits dst n) rs m (List.replicate (n+1) .tick)
+ (Function.update rs dst (Fin.ofNat _ n)) m := by
+ induction n with
+ | zero => exact Flow.Exec.line rfl
+ | succ n ih =>
+ let mid := Function.update rs dst (Fin.ofNat (2^w) n)
+ have hv : mid (fixed r 0) = 1 := (Function.update_of_ne hd.symm ..).trans h1
+ have hop : Flow.Exec pub state (.line (.binary .add dst dst (fixed r 0))) mid m [.tick]
+ (Function.update rs dst (Fin.ofNat _ (n+1))) m := by
+ apply Flow.Exec.line
+ simp only [Op.effect,BinaryOp.eval,hv,mid,Function.update_self,Function.update_idem]
+ rw [show Fin.ofNat (2^w) n + 1 = Fin.ofNat (2^w) (n+1) from (Nat.cast_succ (R := Word w) n).symm]
+ exact seqTicks (t := 1) ih hop
+
+theorem literal_run {w r : ℕ} (pub : Fin 11 → Word w) (state : Word w) (m : Memory w)
+ (rs : Regs w (registerCount r)) (dst : Fin (registerCount r)) (hd : dst ≠ fixed r 0) (n : ℕ) :
+ let mid := Function.update rs (fixed r 0) (Fin.ofNat (2^w) 1)
+ Flow.Exec pub state (literal dst n) rs m (List.replicate (n+2) .tick)
+ (Function.update mid dst (Fin.ofNat _ n)) m := by
+ let mid := Function.update rs (fixed r 0) (Fin.ofNat (2^w) 1)
+ have one : Flow.Exec pub state (.line (.constant (fixed r 0) 1)) rs m [.tick] mid m := .line rfl
+ have h := addUnits_run pub state m mid dst hd (Function.update_self ..) n
+ simpa only [literal, show 1+(n+1)=n+2 by omega] using seqTicks (j := 1) one h
+
+theorem temp_ne_fixed {r : ℕ} (base : ℕ) (i : Fin 12) : temp r base ≠ fixed r i := by
+ intro h
+ have e := congrArg Fin.val h
+ change 12+(base%(r+1)) = i.val at e
+ omega
+
+theorem literal_eval (g : Geometry) (lit : LiteralPrefix) {r base : ℕ} (hb : base ≤ r) (v : ℕ) :
+ Eval g lit r base v (v+2) (literal (temp r base) v) := by
+ intro pub st m rs _
+ let mid := Function.update rs (fixed r 0) (Fin.ofNat (2^g.w) 1)
+ exact ⟨_,le_rfl,_,literal_run pub st m rs (temp r base) (temp_ne_fixed base 0) v,Function.update_self ..,
+ (scratch_keep rs 0 (by decide) _).trans (update_keep hb mid _)⟩
+
+theorem input_eval (g : Geometry) (lit : LiteralPrefix) {r base : ℕ} (hb : base ≤ r) (i : Fin 6)
+ (v : ℕ) (hv : words g lit i = Fin.ofNat _ v) :
+ Eval g lit r base v 1 (.line (.copy (temp r base) (inputReg r i))) := by
+ intro pub st m rs hr
+ let out := Function.update rs (temp r base) (rs (inputReg r i))
+ exact ⟨1,le_rfl,out,.line rfl,(Function.update_self ..).trans ((hr i).trans hv),update_keep hb rs _⟩
+
+end PairSimulation.NativeOperands
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeOperandCompiler.lean b/lean/OAI/Computability/VPVNP/PairNativeOperandCompiler.lean
new file mode 100644
index 0000000000..51ad144977
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeOperandCompiler.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.PairNativeOperandArithmetic
+import OAI.Computability.VPVNP.PairNativeOperandLog
+
+/-! # Compiling public expressions to native instructions within a pair burst -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeOperands
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM LiveProgram
+open scoped Fin.CommRing
+
+/-- Evaluate an operand, pass it through the floor or ceiling binary-logarithm routine in fixed
+registers 2 and 3, then copy the result back to its temporary slot. -/
+def logarithm {r : ℕ} (ceil : Bool) (base : ℕ) (a : Code r) : Code r :=
+ .seq (.seq (.seq a (.line (.copy (fixed r 2) (temp r base))))
+ (PrimedCounter.renameFlow (fixed r) id (Log.program ceil))) (.line (.copy (temp r base) (fixed r 3)))
+
+theorem logarithm_eval (g : Geometry) (lit : LiteralPrefix) {r base x u : ℕ} (hroom : base ≤ r)
+ (ceil : Bool) {a : Code r} (ha : Eval g lit r base x u a) (hx : x < 2^g.w) (hw : 2 ≤ g.w) :
+ Eval g lit r base (if ceil then Nat.clog 2 x else Nat.log 2 x) (u+(10*(g.w+1)+12)) (logarithm ceil base a) := by
+ intro pub st m rs ready
+ obtain ⟨t,ht,mid,run,hvalue,keep⟩ := ha pub st m rs ready
+ let z := Function.update mid (fixed r 2) (mid (temp r base))
+ have hcopy : Flow.Exec pub st (.line (.copy (fixed r 2) (temp r base))) mid m (List.replicate 1 .tick) z m := .line rfl
+ obtain ⟨k,hk,localOut,small,hlog,houtside⟩ := Log.run ceil pub st m (z ∘ fixed r) hw
+ obtain ⟨big,loop,restrict,others⟩ := PrimedCounter.liftExec (fixedEmbedding r) id pub small z rfl
+ have hx' : ((z ∘ fixed r) 2).val = x := by
+ change (z (fixed r 2)).val = _
+ rw [show z (fixed r 2) = mid (temp r base) from Function.update_self ..,hvalue]
+ exact Nat.mod_eq_of_lt hx
+ have hout : big (fixed r 3) = Fin.ofNat _ (if ceil then Nat.clog 2 x else Nat.log 2 x) := by
+ have h := congrFun restrict 3
+ change big (fixed r 3) = localOut 3 at h
+ rw [h,← hx',← hlog]; exact (Fin.ofNat_val_eq_self _).symm
+ have hback : Flow.Exec pub st (.line (.copy (temp r base) (fixed r 3))) big m (List.replicate 1 .tick)
+ (Function.update big (temp r base) (big (fixed r 3))) m := .line rfl
+ have loopKeep : Keeps base z big := by
+ intro i lo _
+ by_cases hi : i ∈ Set.range (fixedEmbedding r)
+ · obtain ⟨j,rfl⟩ := hi
+ exact (congrFun restrict j).trans (houtside j lo)
+ · exact others i hi
+ exact ⟨_,by omega,_,seqTicks (seqTicks (seqTicks run hcopy) loop) hback,(Function.update_self ..).trans hout,
+ (((keep.trans (scratch_keep mid 2 (by decide) _)).trans loopKeep).trans (update_keep hroom big _))⟩
+
+/-- Compile a public geometry expression into native instructions writing temporary slot
+`base`. A binary operation evaluates its right operand one slot higher to retain the left
+value. -/
+def compile (r base : ℕ) : PublicExpr → Code r
+ | .lit n => literal (temp r base) n
+ | .n => .line (.copy (temp r base) (inputReg r 0))
+ | .d => .line (.copy (temp r base) (inputReg r 1))
+ | .H => .line (.copy (temp r base) (inputReg r 2))
+ | .w => .line (.copy (temp r base) (inputReg r 3))
+ | .add a b => combine .add base (compile r base a) (compile r (base+1) b)
+ | .sub a b => combine .sub base (compile r base a) (compile r (base+1) b)
+ | .mul a b => combine .mul base (compile r base a) (compile r (base+1) b)
+ | .divConst a n => combine .div base (compile r base a) (literal (temp r (base+1)) n)
+ | .pow2 a => pow2 base (compile r base a)
+ | .log2 a => logarithm false base (compile r base a)
+ | .clog2 a => logarithm true base (compile r base a)
+
+/-- Recursive tick bound for a compiled public expression. Literal costs grow with the literal
+and logarithm costs grow with the machine word width. -/
+def cost (w : ℕ) : PublicExpr → ℕ
+ | .lit n => n+2
+ | .add a b | .sub a b | .mul a b => cost w a + cost w b + 2
+ | .divConst a n => cost w a + (n+2) + 2
+ | .pow2 a => cost w a + 2
+ | .log2 a | .clog2 a => cost w a + (10*(w+1)+12)
+ | _ => 1
+
+theorem cost_le (e : PublicExpr) (w : ℕ) : cost w e ≤ cost 0 e*(w+1) := by
+ induction e <;> simp only [cost,Nat.zero_add,Nat.mul_one,Nat.add_mul] at *
+ all_goals (simp only [Nat.mul_succ] at *; omega)
+
+private theorem value_lt {e : PublicExpr} {g : Geometry} (h : e.Fits g (2^g.w)) : e.eval g < 2^g.w := by
+ cases e <;> exact h.1
+
+theorem compile_eval (g : Geometry) (lit : LiteralPrefix) (hw : 2 ≤ g.w) (r base : ℕ) (e : PublicExpr)
+ (hr : base + RAMTape.PublicExprMachine.extra e ≤ r) (hf : e.Fits g (2^g.w)) :
+ Eval g lit r base (e.eval g) (cost g.w e) (compile r base e) := by
+ induction e generalizing base with
+ | lit n => exact literal_eval g lit (by simpa [RAMTape.PublicExprMachine.extra] using hr) n
+ | n => exact input_eval g lit (by simpa [RAMTape.PublicExprMachine.extra] using hr) 0 _ rfl
+ | d => exact input_eval g lit (by simpa [RAMTape.PublicExprMachine.extra] using hr) 1 _ rfl
+ | H => exact input_eval g lit (by simpa [RAMTape.PublicExprMachine.extra] using hr) 2 _ rfl
+ | w => exact input_eval g lit (by simpa [RAMTape.PublicExprMachine.extra] using hr) 3 _ rfl
+ | add a b ha hb | sub a b ha hb | mul a b ha hb =>
+ simp only [RAMTape.PublicExprMachine.extra] at hr
+ obtain ⟨_,fa,fb⟩ := hf
+ exact combine_eval g lit (by omega) _ (ha _ (by omega) fa) (hb _ (by omega) fb) (value_lt fa) (value_lt fb)
+ | divConst a n ha =>
+ simp only [RAMTape.PublicExprMachine.extra] at hr
+ obtain ⟨_,fa,fn⟩ := hf
+ exact combine_eval g lit (by omega) .div (ha _ (by omega) fa) (literal_eval g lit (by omega) n) (value_lt fa) fn
+ | pow2 a ha =>
+ simp only [RAMTape.PublicExprMachine.extra] at hr
+ exact pow2_eval g lit (by omega) (ha _ (by omega) hf.2) (value_lt hf.2) hf.1
+ | log2 a ha =>
+ exact logarithm_eval g lit (by simp only [RAMTape.PublicExprMachine.extra] at hr; omega)
+ false (ha _ hr hf.2) (value_lt hf.2) hw
+ | clog2 a ha =>
+ exact logarithm_eval g lit (by simp only [RAMTape.PublicExprMachine.extra] at hr; omega)
+ true (ha _ hr hf.2) (value_lt hf.2) hw
+
+end PairSimulation.NativeOperands
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeOperandLog.lean b/lean/OAI/Computability/VPVNP/PairNativeOperandLog.lean
new file mode 100644
index 0000000000..43daef2246
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeOperandLog.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.PairNativeGeometryArithmetic
+
+/-!
+# Logarithmic operands inside the native pair burst
+
+Repeated floor division by two needs no increment of the operand. For a
+ceiling logarithm at `x > 1`, the same loop starts at `x-1` with counter
+one. This covers the largest word as well as zero and powers of two.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeOperands.Log
+
+open BurstRAM PrivateRAM PrimedInputRAM PrimedStackRAM
+
+variable {w : ℕ}
+/-- The twelve-register instruction flows used to evaluate binary logarithms inside a native
+operand computation. -/
+abbrev Code := Flow 12 11
+
+private def step : Code := .seq (.line (.binary .div 2 2 1)) (.line (.binary .add 3 3 0))
+private def loop : Code := .whileLt 0 2 step
+
+private theorem loop_run (pub : Fin 11 → Word w) (state : Word w) (m : Memory w)
+ (x c : ℕ) (rs : Regs w 12) (h1 : (rs 0).val = 1) (h2 : (rs 1).val = 2)
+ (hx : (rs 2).val = x) (hc : (rs 3).val = c) (hfit : c+Nat.log 2 x < 2^w) :
+ ∃ out, Flow.Exec pub state loop rs m (List.replicate (3*Nat.log 2 x+1) .tick) out m ∧
+ (out 3).val = c+Nat.log 2 x ∧ ∀ i : Fin 12, i ≠ 2 → i ≠ 3 → out i = rs i := by
+ induction x using Nat.strong_induction_on generalizing c rs with
+ | h x ih =>
+ by_cases small : x < 2
+ · rw [Nat.log_of_lt small, Nat.mul_zero, Nat.zero_add,Nat.add_zero]
+ exact ⟨rs,.whileDone (by change ¬ (rs 0).val < (rs 2).val; omega),hc,fun _ _ _ => rfl⟩
+ · have hlog := Nat.log_of_one_lt_of_le Nat.one_lt_two (show 2 ≤ x by omega)
+ let a := Function.update rs (2 : Fin 12) (BinaryOp.div.eval (rs 2) (rs 1))
+ let b := Function.update a (3 : Fin 12) (BinaryOp.add.eval (a 3) (a 0))
+ have keep (i : Fin 12) (h₂ : i ≠ 2) (h₃ : i ≠ 3) : b i = rs i := by
+ simp [b,a,Function.update_of_ne h₂,Function.update_of_ne h₃]
+ have hbx : (b 2).val = x/2 := by
+ change ((rs 2).val/(rs 1).val) % (2^w) = x/2
+ rw [Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt (rs 2).isLt),hx,h2]
+ have hbc : (b 3).val = c+1 := by
+ change ((a 3).val+(a 0).val) % (2^w) = c+1
+ rw [show (a 3).val = c by simpa [a,Function.update_apply] using hc,
+ show (a 0).val = 1 by simpa [a,Function.update_apply] using h1,Nat.mod_eq_of_lt (by omega)]
+ have body : Flow.Exec pub state step rs m [.tick,.tick] b m :=
+ Flow.Exec.seq (.line (rs' := a) rfl) (.line (rs' := b) rfl)
+ obtain ⟨out,rest,value,frame⟩ := ih (x/2) (by omega) (c+1) b
+ ((congrArg Fin.val (keep _ (by decide) (by decide))).trans h1)
+ ((congrArg Fin.val (keep _ (by decide) (by decide))).trans h2) hbx hbc (by omega)
+ refine ⟨out,?_,by omega,fun i h₂ h₃ => (frame i h₂ h₃).trans (keep i h₂ h₃)⟩
+ rw [show 3*Nat.log 2 x+1 = (2+(3*Nat.log 2 (x/2)+1))+1 by omega,
+ List.replicate_succ,List.replicate_add]
+ exact .whileStep (by change (rs 0).val < (rs 2).val; omega) body rest
+
+private theorem ceiling_eq (x : ℕ) (hx : 1 < x) : Nat.clog 2 x = 1+Nat.log 2 (x-1) := by
+ apply Nat.le_antisymm
+ · apply Nat.clog_le_of_le_pow
+ rw [Nat.add_comm 1]
+ have h := Nat.lt_pow_succ_log_self Nat.one_lt_two (x-1)
+ omega
+ · have h := Nat.pow_log_le_self 2 (by omega : x-1 ≠ 0)
+ have hlt : Nat.log 2 (x-1) < Nat.clog 2 x := (Nat.lt_clog_iff_pow_lt Nat.one_lt_two).2 (by omega)
+ omega
+
+private def init : Code := straight (.constant 0 1) [.constant 1 2,.constant 3 0]
+
+private def preCeil : Code := .seq (.line (.binary .sub 2 2 0)) (.line (.copy 3 0))
+
+/-- Compute the floor or ceiling binary logarithm of register 2 in register 3 by repeated
+halving. For a ceiling logarithm above one the loop starts from one less than the operand
+and counts from one. -/
+def program (ceil : Bool) : Code := .seq init (if ceil then
+ .ifLt 0 2 (.seq preCeil loop) (.line (.constant 3 0)) else loop)
+
+/-- The result occupies register three. Registers four and above, including
+the word-width register, keep their original contents. -/
+theorem run (ceil : Bool) (pub : Fin 11 → Word w) (state : Word w) (m : Memory w)
+ (rs : Regs w 12) (hw : 2 ≤ w) :
+ ∃ ticks ≤ 10*(w+1)+10, ∃ out,
+ Flow.Exec pub state (program ceil) rs m (List.replicate ticks .tick) out m ∧
+ (out 3).val = (if ceil then Nat.clog 2 (rs 2).val else Nat.log 2 (rs 2).val) ∧
+ ∀ i : Fin 12, 4 ≤ i.val → out i = rs i := by
+ let x := (rs 2).val
+ let s := Function.update (Function.update (Function.update rs (0 : Fin 12) (Fin.ofNat (2^w) 1))
+ (1 : Fin 12) (Fin.ofNat (2^w) 2)) (3 : Fin 12) (Fin.ofNat (2^w) 0)
+ have hinit : Flow.Exec pub state init rs m (List.replicate 3 .tick) s m :=
+ (Flow.once_sound pub state false _ rs m rfl).1
+ have hfour : 4 ≤ 2^w := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ have h1 : (s 0).val = 1 := Nat.mod_eq_of_lt (by omega)
+ have h2 : (s 1).val = 2 := Nat.mod_eq_of_lt (by omega)
+ have hx : (s 2).val = x := rfl
+ have h0 : (s 3).val = 0 := rfl
+ have hxlt : x < 2^w := (rs 2).isLt
+ have hclog : Nat.clog 2 x ≤ w := Nat.clog_le_of_le_pow hxlt.le
+ have hlog := (Nat.log_le_clog 2 x).trans hclog
+ have hfit : w < 2^w := Nat.lt_two_pow_self
+ have frame (i : Fin 12) (hi : 4 ≤ i.val) : s i = rs i := by
+ have h₀ : i ≠ 0 := fun h => by subst i; contradiction
+ have h₁ : i ≠ 1 := fun h => by subst i; contradiction
+ have h₃ : i ≠ 3 := fun h => by subst i; contradiction
+ simp [s,Function.update_of_ne h₀,Function.update_of_ne h₁,Function.update_of_ne h₃]
+ have hne (i : Fin 12) (hi : 4 ≤ i.val) : i ≠ 2 ∧ i ≠ 3 := by
+ constructor <;> intro he <;> subst i <;> contradiction
+ cases ceil with
+ | false =>
+ obtain ⟨out,body,hv,hk⟩ := loop_run pub state m x 0 s h1 h2 hx h0 (by omega)
+ exact ⟨_,by omega,out,PairNativeGeometry.seqTicks hinit body,by simpa using hv,
+ fun i hi => (hk i (hne i hi).1 (hne i hi).2).trans (frame i hi)⟩
+ | true =>
+ by_cases small : x ≤ 1
+ · let out := Function.update s (3 : Fin 12) (Fin.ofNat (2^w) 0)
+ have branch : Flow.Exec pub state (.ifLt 0 2 (.seq preCeil loop) (.line (.constant 3 0)))
+ s m (List.replicate 2 .tick) out m :=
+ .ifLtNo (by change ¬ (s 0).val < (s 2).val; omega) (.line rfl)
+ exact ⟨_,by omega,out,PairNativeGeometry.seqTicks hinit branch,
+ by change 0 = Nat.clog 2 x; rw [Nat.clog_of_right_le_one small],
+ fun i hi => (Function.update_of_ne (hne i hi).2 ..).trans (frame i hi)⟩
+ · let t := Function.update s (2 : Fin 12) (BinaryOp.sub.eval (s 2) (s 0))
+ let u := Function.update t (3 : Fin 12) (t 0)
+ have adjust : Flow.Exec pub state preCeil s m (List.replicate 2 .tick) u m :=
+ Flow.Exec.seq (.line (rs' := t) rfl) (.line (rs' := u) rfl)
+ have hu (i : Fin 12) (h₂ : i ≠ 2) (h₃ : i ≠ 3) : u i = s i := by
+ simp [u,t,Function.update_of_ne h₂,Function.update_of_ne h₃]
+ have hux : (u 2).val = x-1 := by
+ change (s 2 - s 0).val = x-1
+ rw [Fin.sub_val_of_le (by change (s 0).val ≤ (s 2).val; omega),h1,hx]
+ have hceil := ceiling_eq x (by omega)
+ obtain ⟨out,body,hv,hk⟩ := loop_run pub state m (x-1) 1 u
+ ((congrArg Fin.val (hu _ (by decide) (by decide))).trans h1)
+ ((congrArg Fin.val (hu _ (by decide) (by decide))).trans h2) hux h1 (by omega)
+ have branch := Flow.Exec.ifLtYes (b := (Flow.line (.constant 3 0) : Code))
+ (show s 0 < s 2 by change (s 0).val < (s 2).val; omega) (PairNativeGeometry.seqTicks adjust body)
+ change Flow.Exec pub state _ s m (List.replicate ((2+(3*Nat.log 2 (x-1)+1))+1) .tick) out m at branch
+ exact ⟨_,by omega,out,PairNativeGeometry.seqTicks hinit branch,hv.trans hceil.symm,
+ fun i hi => ((hk i (hne i hi).1 (hne i hi).2).trans (hu i (hne i hi).1 (hne i hi).2)).trans (frame i hi)⟩
+
+end PairSimulation.NativeOperands.Log
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNativeOperandVector.lean b/lean/OAI/Computability/VPVNP/PairNativeOperandVector.lean
new file mode 100644
index 0000000000..0d3862c51e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNativeOperandVector.lean
@@ -0,0 +1,180 @@
+import OAI.Computability.VPVNP.PairNativeOperandCompiler
+import OAI.Computability.VPVNP.PairNativeGeometry
+
+/-! # Native evaluation of a fixed vector from the eleven pair-stage operands
+
+Register twelve retains the caller's private cache base. Results start at
+register thirteen, in vector order. The final two instructions set the cache
+write pointer and unit register for the consecutive private stores.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeOperands
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM LiveProgram
+open scoped Fin.CommRing
+
+variable {k : ℕ}
+
+/-- Number of extra temporary slots above an operand's result slot. A geometry expression uses
+its compiler's space bound and a prefix field uses zero. -/
+def need : InputOperand → ℕ
+ | .geometry e => RAMTape.PublicExprMachine.extra e
+ | _ => 0
+
+/-- Tick allowance for one vector entry, using the expression cost for a geometry operand and
+one copy for either prefix operand. -/
+def fieldCost (w : ℕ) : InputOperand → ℕ
+ | .geometry e => cost w e
+ | _ => 1
+
+/-- Produce one vector field in temporary slot `base` by compiling a geometry expression or
+copying the selected prefix word or length. -/
+def field (r base : ℕ) : InputOperand → Code r
+ | .geometry e => compile r base e
+ | .prefixLength => .line (.copy (temp r base) (inputReg r 4))
+ | .prefixWord => .line (.copy (temp r base) (inputReg r 5))
+
+/-- For a geometry operand, all bounds required by the public-expression evaluator hold at
+modulus `2^g.w`. The two prefix operands are already word-valued. -/
+def FieldFits (g : Geometry) : InputOperand → Prop
+ | .geometry e => e.Fits g (2^g.w)
+ | _ => True
+
+theorem field_eval (g : Geometry) (lit : LiteralPrefix) (hw : 2 ≤ g.w) (r base : ℕ) (e : InputOperand)
+ (hr : base+need e ≤ r) (hf : FieldFits g e) :
+ Eval g lit r base (e.eval g lit) (fieldCost g.w e) (field r base e) := by
+ cases e with
+ | geometry e => exact compile_eval g lit hw _ _ e hr hf
+ | prefixLength => exact input_eval g lit (by simpa [need] using hr) 4 _ rfl
+ | prefixWord => exact input_eval g lit (by simpa [need] using hr) 5 _ rfl
+
+/-- Largest temporary index reserved for the vector, allowing one result slot per entry and
+enough extra slots for its most demanding expression. -/
+def capacity (args : Fin k → InputOperand) := k + Finset.univ.sup (fun i => need (args i))
+
+/-- Register `13+i` holds vector entry `i` for the subsequent private cache store. -/
+def src (args : Fin k → InputOperand) (i : Fin k) := temp (capacity args) (i.val+1)
+/-- Temporary slot zero, register 12, holds the caller's cache base throughout geometry and
+field evaluation. -/
+def saved (args : Fin k → InputOperand) := temp (capacity args) 0
+/-- Fixed register 10 carries the write pointer for the sequence of private cache stores. -/
+def cursor (args : Fin k → InputOperand) := fixed (capacity args) 10
+/-- Fixed register 11 holds the unit increment used to advance from one cache entry to the
+next. -/
+def unit (args : Fin k → InputOperand) := fixed (capacity args) 11
+
+theorem src_val (args : Fin k → InputOperand) (i : Fin k) : (src args i).val = 13+i.val := by
+ rw [src,temp_val (by unfold capacity; omega)]
+ omega
+
+private def initialFields (args : Fin k → InputOperand) : (n : ℕ) → n ≤ k → Code (capacity args)
+ | 0, _ => .line (.copy (fixed _ 0) (fixed _ 0))
+ | n+1, h => .seq (initialFields args n (by omega)) (field _ (n+1) (args ⟨n,h⟩))
+
+private def maxCost (args : Fin k → InputOperand) := Finset.univ.sup (fun i => fieldCost 0 (args i))
+
+private theorem prefix_run (args : Fin k → InputOperand) (g : Geometry) (lit : LiteralPrefix)
+ (hw : 2 ≤ g.w) (hf : ∀ i, FieldFits g (args i)) (pub : Fin 11 → Word g.w) (st : Word g.w)
+ (m : Memory g.w) (rs : Regs g.w (registerCount (capacity args))) (ready : Ready g lit rs)
+ (n : ℕ) (hn : n ≤ k) :
+ ∃ t ≤ n*(maxCost args*(g.w+1))+1, ∃ out,
+ Flow.Exec pub st (initialFields args n hn) rs m (List.replicate t .tick) out m ∧ Ready g lit out ∧
+ out (saved args) = rs (saved args) ∧
+ ∀ i : Fin k, i.val < n → out (src args i) = Pieces.word g lit (args i) := by
+ induction n with
+ | zero =>
+ have h : Flow.Exec pub st (.line (.copy (fixed (capacity args) 0) (fixed _ 0))) rs m [Event.tick] rs m := by
+ apply Flow.Exec.line; simp only [Op.effect,Function.update_eq_self]
+ exact ⟨1,by simp,rs,h,ready,rfl,fun _ h => (Nat.not_lt_zero _ h).elim⟩
+ | succ n ih =>
+ obtain ⟨t,ht,mid,first,hr,hsaved,hprev⟩ := ih (by omega)
+ let i : Fin k := ⟨n,hn⟩
+ have room : n+1+need (args i) ≤ capacity args :=
+ Nat.add_le_add hn (Finset.le_sup (f := fun j => need (args j)) (Finset.mem_univ i))
+ obtain ⟨u,hu,out,second,hout,keep⟩ := field_eval g lit hw _ (n+1) (args i) room (hf i) pub st m mid hr
+ have hcost : fieldCost g.w (args i) ≤ fieldCost 0 (args i)*(g.w+1) := by
+ cases h : args i with
+ | geometry e => exact cost_le e _
+ | prefixLength | prefixWord => simp [fieldCost]
+ have hmax : fieldCost 0 (args i) ≤ maxCost args := Finset.le_sup (f := fun j => fieldCost 0 (args j)) (Finset.mem_univ i)
+ have bound := hu.trans (hcost.trans (Nat.mul_le_mul_right _ hmax))
+ have hs : (saved args).val = 12 := by rw [saved,temp_val (Nat.zero_le _)]
+ refine ⟨_,by rw [Nat.succ_mul]; omega,out,seqTicks first second,keep.ready hr,
+ (keep _ (by omega) (by omega)).trans hsaved,?_⟩
+ intro j hj
+ by_cases hji : j.val = n
+ · have eq : j = i := Fin.ext hji
+ subst j; exact hout
+ · exact (keep _ (by rw [src_val]; omega) (by rw [src_val]; omega)).trans (hprev _ (by omega))
+
+/-- Load the geometry, compute the vector fields in index order, and initialize the cache write
+pointer and its unit increment. -/
+def vector (args : Fin k → InputOperand) (a b : ℕ) : Code (capacity args) :=
+ .seq (.seq (PrimedCounter.renameFlow (fixed (capacity args)) id (PairNativeGeometry.program a b))
+ (initialFields args k le_rfl)) (.seq (.line (.copy (cursor args) (saved args))) (.line (.constant (unit args) 1)))
+
+/-- Tick bound for evaluating the entire operand vector, combining geometry setup with a
+uniform per-entry bound and three bookkeeping instructions. -/
+def work (args : Fin k → InputOperand) (a b : ℕ) (g : Geometry) :=
+ PairNativeGeometry.ticks a b g.n + k*(maxCost args*(g.w+1)) + 3
+
+/-- Postcondition for native vector evaluation. Each source register holds its encoded operand,
+the cursor holds the supplied base and the increment register holds one. -/
+structure Result (args : Fin k → InputOperand) (g : Geometry) (lit : LiteralPrefix)
+ (base : Word g.w) (rs : Regs g.w (registerCount (capacity args))) : Prop where
+ value (i : Fin k) : rs (src args i) = Pieces.word g lit (args i)
+ pointer : rs (cursor args) = base
+ one : rs (unit args) = 1
+
+theorem vector_run (args : Fin k → InputOperand) (g : Geometry) (lit : LiteralPrefix) (a b : ℕ)
+ (hb : 0 < b) (hn : 0 < g.n) (hwidth : g.w = (g.d+10)^4) (hbucket : g.H = 2^roundedUp a b g.n)
+ (fit : PairNativeGeometry.Fits a b g.n g.w) (hf : ∀ i, FieldFits g (args i))
+ (pub : Fin 11 → Word g.w) (h6 : (pub 6).val = g.n) (h7 : (pub 7).val = g.d)
+ (h1 : pub 1 = Fin.ofNat _ lit.length) (h0 : pub 0 = Fin.ofNat _ lit.value)
+ (st : Word g.w) (m : Memory g.w) (rs : Regs g.w (registerCount (capacity args))) :
+ ∃ t ≤ work args a b g, ∃ out, Flow.Exec pub st (vector args a b) rs m (List.replicate t .tick) out m ∧
+ Result args g lit (rs (saved args)) out := by
+ let r := capacity args
+ obtain ⟨small,geo,values⟩ := PairNativeGeometry.program_run pub st m (rs ∘ fixed r) a b g.n g.d hb hn hwidth fit h6 h7
+ obtain ⟨mid,load,keep,other⟩ := PrimedCounter.liftExec (fixedEmbedding r) id pub geo rs rfl
+ have wordEq (x : Word g.w) : x = Fin.ofNat _ x.val := (Fin.ofNat_val_eq_self x).symm
+ have ready : Ready g lit mid := by
+ intro i
+ have eq := congrFun keep (inputSlot i)
+ change mid (inputReg r i) = small _ at eq
+ apply eq.trans
+ fin_cases i
+ · exact (wordEq (small 4)).trans (congrArg (Fin.ofNat _) values.length)
+ · exact (wordEq (small 5)).trans (congrArg (Fin.ofNat _) values.address)
+ · exact (wordEq (small 7)).trans (congrArg (Fin.ofNat _) (values.bucket.trans hbucket.symm))
+ · exact (wordEq (small 6)).trans (congrArg (Fin.ofNat _) values.width)
+ · exact values.prefixLength.trans h1
+ · exact values.prefixWord.trans h0
+ have hs : mid (saved args) = rs (saved args) :=
+ other _ (by rintro ⟨j,hj⟩; exact temp_ne_fixed (r := r) 0 j hj.symm)
+ have hw : 2 ≤ g.w := by rw [hwidth]; exact (show 2 ≤ g.d+10 by omega).trans (Nat.le_self_pow (by decide) _)
+ obtain ⟨t,ht,z,body,_,hz,hout⟩ := prefix_run args g lit hw hf pub st m mid ready k le_rfl
+ let u := Function.update z (cursor args) (z (saved args))
+ let out := Function.update u (unit args) (Fin.ofNat (2^g.w) 1)
+ have cp : Flow.Exec pub st (.line (.copy (cursor args) (saved args))) z m (List.replicate 1 .tick) u m := .line rfl
+ have un : Flow.Exec pub st (.line (.constant (unit args) 1)) u m (List.replicate 1 .tick) out m := .line rfl
+ refine ⟨_,by unfold work; omega,out,seqTicks (seqTicks load body) (seqTicks cp un),?_⟩
+ constructor
+ · intro i
+ rw [show out (src args i) = u (src args i) from Function.update_of_ne (temp_ne_fixed (i.val+1) 11) ..,
+ show u (src args i) = z (src args i) from Function.update_of_ne (temp_ne_fixed (i.val+1) 10) ..]
+ exact hout i i.isLt
+ · change Function.update u (unit args) _ (cursor args) = _
+ rw [Function.update_of_ne (show cursor args ≠ unit args from by
+ intro h; have := congrArg Fin.val h; change 10 = 11 at this; contradiction)]
+ exact (Function.update_self ..).trans (hz.trans hs)
+ · exact Function.update_self ..
+
+end PairSimulation.NativeOperands
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeArguments.lean b/lean/OAI/Computability/VPVNP/PairNodeArguments.lean
new file mode 100644
index 0000000000..eb7c892443
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeArguments.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.PairSimulationPrivateFields
+import OAI.Computability.VPVNP.PairSimulationHistoryBounds
+import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout
+
+/-!
+# The private argument buffer for a descriptor node
+
+One contiguous interval per node holds its outgoing half-wire bits followed
+by its incoming half-wire bits. An incoming slot looks up the width of the
+matched outgoing arc. The two half-wires are independent in a child guess,
+including when the graph has parallel arcs or loops. A child later reads
+exactly the private words that its parent filled.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments
+
+open BurstRAM BurstRAM.PrivateRAM Compression LocalHistory CompressorRecords
+open scoped Fin.CommRing
+
+/-- The private argument interval of a node is indexed by its absolute DFS address. -/
+structure Arena where
+ /-- Private memory address from which the per-node half-wire argument intervals are
+ allocated. -/
+ start : ℕ
+ /-- Distance in private words between the starts of argument intervals for consecutive
+ descriptor addresses. -/
+ stride : ℕ
+
+/-- Starting address of the private argument interval for an absolute descriptor address,
+obtained by scaling the address by the arena stride. -/
+def Arena.base (A : Arena) (node : ℕ) : ℕ := A.start + node * A.stride
+
+theorem Arena.before (A : Arena) {n m : ℕ} (h : n < m) : A.base n + A.stride ≤ A.base m := by
+ unfold base
+ have hmul := Nat.mul_le_mul_right A.stride h
+ rw [Nat.succ_mul] at hmul
+ omega
+
+theorem Arena.disjoint (A : Arena) {n m : ℕ} (h : n ≠ m) :
+ A.base n + A.stride ≤ A.base m ∨ A.base m + A.stride ≤ A.base n :=
+ (lt_or_gt_of_ne h).imp A.before A.before
+
+variable {a g : ℕ} (X : State a g) (u : X.network.Site)
+
+/-- The actual slot field as seen by the old vertex, independently at each end. -/
+noncomputable def fieldBits (h : X.network.Half u) (dir : Bool) (j : Fin (2 ^ a)) :
+ Fin (X.halfWidth u dir j) → Bool :=
+ match dir with
+ | false => let e := (outgoingOrder X u).entries j; h.1 e.val e.property
+ | true => let e := (incomingOrder X u).entries j; h.2 e.val e.property
+
+/-- The half-wire bit strings at site `u` in numbered slot order, using outgoing arcs for
+`false` and incoming arcs for `true`. -/
+noncomputable def fields (h : X.network.Half u) (dir : Bool) : List (List Bool) :=
+ List.ofFn fun j ↦ List.ofFn (fieldBits X u h dir j)
+
+/-- Concatenation used both when a parent guesses a child and at its later visit. -/
+noncomputable def packed (h : X.network.Half u) : List Bool :=
+ (fields X u h false).flatten ++ (fields X u h true).flatten
+
+private theorem fiber_encode {I V : Type} {B : I → Type} (p : I → V) (v : V)
+ (o : Order {i // v = p i}) (r : ∀ i, ChoiceReader (B i)) (h : NetworkKernel.Placed p B v) :
+ ((fiber p v o r).encode h) =
+ (List.ofFn fun j ↦ (r (o.entries j).val).encode
+ (h (o.entries j).val (o.entries j).prop)).flatten := by
+ unfold fiber Order.reader ChoiceReader.reindex
+ dsimp only
+ rw [ChoiceReader.vector_encode]
+ rfl
+
+/-- The concrete RAM byte order agrees with the abstract traversal's old-half parser. -/
+theorem packed_eq_encode (h : X.network.Half u) : packed X u h =
+ ((half X.network u (outgoingOrder X u) (incomingOrder X u) (statePayload X)).encode h) := by
+ change _ = _ ++ _
+ rw [fiber_encode, fiber_encode]
+ unfold packed fields
+ congr 2 <;> congr 1 <;> funext j <;> exact (PrivateFields.bitField_encode _).symm
+
+theorem packed_length (h : X.network.Half u) :
+ (packed X u h).length = ∑ dir : Bool, ∑ j, X.halfWidth u dir j := by
+ rw [packed_eq_encode, stateHalf_length]
+
+/-- Slot offset uses widths only and has no dependence on the guessed values. -/
+noncomputable def offset (dir : Bool) (j : Fin (2 ^ a)) : ℕ :=
+ (if dir then ∑ t, X.halfWidth u false t else 0) +
+ ((List.ofFn (X.halfWidth u dir)).take j.val).sum
+
+/-- Start of a numbered half-wire field within a node's private interval. Incoming fields
+follow the entire outgoing block, and earlier fields contribute their widths. -/
+noncomputable def Arena.fieldAddress (A : Arena) (node : ℕ) (dir : Bool) (j : Fin (2 ^ a)) : ℕ :=
+ A.base node + offset X u dir j
+
+private theorem fields_offset (h : X.network.Half u) (dir : Bool) (j : Fin (2 ^ a)) :
+ ((fields X u h dir).take j.val).flatten.length =
+ ((List.ofFn (X.halfWidth u dir)).take j.val).sum := by
+ simp [fields, Function.comp_def]
+
+private theorem fields_size (h : X.network.Half u) (dir : Bool) :
+ (fields X u h dir).flatten.length = ∑ j, X.halfWidth u dir j := by
+ simp [fields, List.length_flatten, List.sum_ofFn]
+
+/-- Each endpoint's declared slot is precisely its slice of the private buffer. -/
+theorem packed_member (h : X.network.Half u) (dir : Bool) (j : Fin (2 ^ a)) :
+ ∃ before after : List Bool, packed X u h = before ++
+ List.ofFn (fieldBits X u h dir j) ++ after ∧
+ before.length = offset X u dir j := by
+ let rows := fields X u h dir
+ let start := (rows.take j.val).flatten
+ let stop := (rows.drop (j.val+1)).flatten
+ have hj : j.val < rows.length := by simp [rows,fields]
+ have hr : rows.flatten = start ++ List.ofFn (fieldBits X u h dir j) ++ stop := by
+ have he := (List.take_append_drop j.val rows).symm
+ rw [List.drop_eq_getElem_cons hj] at he
+ have hf := congrArg List.flatten he
+ simpa [rows, fields, start, stop, List.append_assoc] using hf
+ cases dir with
+ | false =>
+ exact ⟨start, stop ++ (fields X u h true).flatten, by
+ change _ ++ _ = _; rw [hr]; simp [List.append_assoc], by
+ simpa [offset,start,rows] using fields_offset X u h false j⟩
+ | true =>
+ exact ⟨(fields X u h false).flatten ++ start, stop, by
+ change _ ++ _ = _; rw [hr]; simp [List.append_assoc], by
+ rw [List.length_append, fields_size, show start.length = _ from fields_offset X u h true j]
+ simp [offset]⟩
+
+/-- Guessing the whole child buffer supplies each individual native slot at its
+calculated private address and preserves private words outside the interval. -/
+theorem stored_member {w : ℕ} (A : Arena) (node : ℕ) (h : X.network.Half u)
+ (mem : Word w → Word w) (fit : A.base node + (packed X u h).length ≤ 2 ^ w)
+ (dir : Bool) (j : Fin (2 ^ a)) (i : Fin (X.halfWidth u dir j)) :
+ PrivateFields.storeBits (A.base node) (packed X u h) mem
+ ((A.fieldAddress X u node dir j + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (fieldBits X u h dir j i) := by
+ obtain ⟨pre,post,he,hoff⟩ := packed_member X u h dir j
+ have hlen : pre.length + i.val < (packed X u h).length := by rw [he]; simp; omega
+ have hb := PrivateFields.storeBits_read (A.base node) _ mem fit ⟨pre.length+i.val, hlen⟩
+ rw [Arena.fieldAddress, ← hoff, Nat.add_assoc]
+ refine hb.trans ?_
+ change PrivateFields.bitValue w (packed X u h)[pre.length+i.val] = _
+ simp [he, i.isLt]
+
+namespace WidthRead
+
+/-- External address of the selected width. Incoming fields use the inverse slot
+column before addressing the old width array. -/
+def value {w : ℕ} (T : IncidenceDirectory w) (m : Memory w) (dir : Bool) (port : Word w) :=
+ let id := if dir then m (T.actualIn + port).val else port
+ m (T.width + id).val
+
+/-- A concrete field header reads the old forward width or the width at the
+original source of the incoming half, retaining all slot multiplicities. -/
+theorem value_actual {w : ℕ} (T : IncidenceDirectory w) (mem : Memory w)
+ (rep : T.ActualColumns X mem) (dir : Bool) (j : Fin (2 ^ a)) :
+ value T mem dir (IncidenceDirectory.actualPort X (u,j)) =
+ CursorRAM.encode w (X.halfWidth u dir j) := by
+ cases dir with
+ | false => exact rep.width _
+ | true => simp only [value, ite_true, rep.actualIn]; exact rep.width _
+
+end WidthRead
+end PairSimulation.NodeArguments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildAddress.lean b/lean/OAI/Computability/VPVNP/PairNodeChildAddress.lean
new file mode 100644
index 0000000000..f4440aeb9b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildAddress.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.PairNodeArguments
+import OAI.Computability.VPVNP.PairSimulationAssembly
+import OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+/-!
+# Reading an old site's descriptor address for a child visit
+
+The next word in a placement row names an old descriptor. Its ordinal within the
+old layer identifies the first outgoing port. Its absolute address identifies
+the private interval for this child's half-wire guesses. The seven instructions
+read one external word and preserve the unconsumed choice bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildAddress
+
+open BurstRAM BurstRAM.PrivateRAM Compression LocalHistory CompressorRecords
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.read ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r k a g : ℕ}
+
+/-- Seven instructions that read the next child descriptor, advance the placement-row pointer,
+and compute both the child's first outgoing port and its private argument base. -/
+def instruction (pc : Fin 7 → Fin p) (reg : Fin 16 ↪ Fin r) (done : Fin p) :
+ Fin 7 → Instr w p r k :=
+ ![.readExternal (reg 2) (reg 9) (pc 1),
+ .binary .add (reg 9) (reg 9) (reg 3) (pc 2),
+ .binary .sub (reg 8) (reg 2) (reg 11) (pc 3),
+ .binary .div (reg 8) (reg 8) (reg 12) (pc 4),
+ .binary .mul (reg 8) (reg 8) (reg 13) (pc 5),
+ .binary .mul (reg 2) (reg 2) (reg 15) (pc 6),
+ .binary .add (reg 2) (reg 14) (reg 2) done]
+
+theorem resize_instruction (pc : Fin 7 → Fin p) (reg : Fin 16 ↪ Fin r) (done : Fin p)
+ (i : Fin 7) : (instruction (w := 1) (k := k) pc reg done i).resize w =
+ instruction pc reg done i := by fin_cases i <;> rfl
+
+/-- The seven supplied machine labels contain the child-address instructions with the specified
+register embedding and continuation. -/
+def Linked (M : Machine w p r k) (pc : Fin 7 → Fin p) (reg : Fin 16 ↪ Fin r) (done : Fin p) :
+ Prop := ∀ i, M.code (pc i) = instruction pc reg done i
+
+/-- Trace of a child-address lookup, consisting of the external read of the descriptor at `ptr`
+followed by six arithmetic ticks. -/
+def events (m : Memory w) (ptr : Word w) : List (Event w) :=
+ [.read ptr (m ptr.val), .tick, .tick, .tick, .tick, .tick, .tick]
+
+theorem cost (m : Memory w) (ptr : Word w) :
+ countProbes (events m ptr) = 1 ∧ (events m ptr).length = 7 ∧ choiceBits (events m ptr) = [] :=
+ ⟨rfl, rfl, rfl⟩
+
+variable {M : Machine w p r k} {pc : Fin 7 → Fin p} {reg : Fin 16 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (hl : Linked M pc reg done) (i : Fin 7) {c : Config w p r}
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg done i).run M.publicData c := by
+ change (M.code c.pc).run _ _ = _
+ rw [hc, hl]
+
+/-- The child setup preserves the parent's count, the incidence tables, the other
+configuration registers, all private words, and the external memory. -/
+theorem native (hl : Linked M pc reg done) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc 0) (hone : c.reg (reg 3) = 1) :
+ let ptr := c.reg (reg 9)
+ let node := m ptr.val
+ ∃ d, d.pc = done ∧ d.reg (reg 2) = c.reg (reg 14) + node * c.reg (reg 15) ∧
+ d.reg (reg 8) = BinaryOp.div.eval (node - c.reg (reg 11)) (c.reg (reg 12)) *
+ c.reg (reg 13) ∧ d.reg (reg 9) = ptr + 1 ∧
+ (∀ j, j ≠ reg 2 → j ≠ reg 8 → j ≠ reg 9 → d.reg j = c.reg j) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ fuel bs, execute M.program (fuel + 7) c m bs =
+ (execute M.program fuel d m bs).map
+ (fun rep => ⟨events m ptr ++ rep.events, rep.result⟩) := by
+ intro ptr node
+ have path := ReadPrefix.read (M := M) (m := m) (c := c) ptr (step_at hl 0 hc)
+ (ReadPrefix.tick (step_at hl 1 rfl) (ReadPrefix.tick (step_at hl 2 rfl)
+ (ReadPrefix.tick (step_at hl 3 rfl) (ReadPrefix.tick (step_at hl 4 rfl)
+ (ReadPrefix.tick (step_at hl 5 rfl) (ReadPrefix.tick (step_at hl 6 rfl)
+ (ReadPrefix.nil _)))))))
+ refine ⟨_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ReadPrefix.execute path⟩
+ · rfl
+ · simp (config := { decide := true })
+ [Config.put, reg.injective.eq_iff, BinaryOp.eval, node, ptr]
+ · simp (config := { decide := true })
+ [Config.put, reg.injective.eq_iff, BinaryOp.eval, node, ptr]
+ · simp (config := { decide := true })
+ [Config.put, reg.injective.eq_iff, BinaryOp.eval, hone, ptr]
+ · intro j h₂ h₈ h₉
+ simp [Config.put, Function.update_of_ne h₂, Function.update_of_ne h₈, Function.update_of_ne h₉]
+ · rfl
+ · rfl
+
+/-- Dividing the descriptor offset by its positive stride recovers the old site
+ordinal. Multiplying by the old degree gives the port used by the incidence reader. -/
+theorem firstPort_eq (X : State a g) (u : X.network.Site) (node olderBase stride : Word w)
+ (hnode : node.val = olderBase.val + stride.val * ((siteOrder X).entries.symm u).val)
+ (hstride : 0 < stride.val) :
+ BinaryOp.div.eval (node - olderBase) stride * ((2 ^ a : ℕ) : Word w) =
+ IncidenceDirectory.actualPort X (u, 0) := by
+ have lower : olderBase ≤ node := show olderBase.val ≤ node.val by omega
+ have quotient : (node - olderBase).val / stride.val = ((siteOrder X).entries.symm u).val := by
+ rw [Fin.sub_val_of_le lower, hnode, Nat.add_sub_cancel_left, Nat.mul_div_cancel_left _ hstride]
+ have word : BinaryOp.div.eval (node - olderBase) stride =
+ (((siteOrder X).entries.symm u).val : Word w) := by
+ change Fin.ofNat _ ((node - olderBase).val / stride.val) = _
+ rw [quotient]
+ rfl
+ rw [word, ← Nat.cast_mul]
+ apply congrArg (fun n : ℕ => (n : Word w))
+ change ((bitWordFinEquiv g u.2).val + 2 ^ g * (X.baseIndex u.1).val) * 2 ^ a =
+ ((X.baseIndex u.1).val * 2 ^ g + (bitWordFinEquiv g u.2).val) * 2 ^ a + 0
+ ring
+
+end PairSimulation.NodeArguments.ChildAddress
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildBankInit.lean b/lean/OAI/Computability/VPVNP/PairNodeChildBankInit.lean
new file mode 100644
index 0000000000..48bd5ec82a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildBankInit.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.PairNodeChildLoop
+
+/-!
+# Initializing the register bank of child slot ordinals
+
+The first slot receives zero. When a second slot exists it receives one.
+Every subsequent instruction adds this stored unit to the preceding slot.
+The fixed program uses one private instruction per slot at every word width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildBankInit
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {a w p r k : ℕ}
+
+/-- Select the label for child slot `n` while it is in range and transfer to the return label
+once the ordinal bank is full. -/
+def next (pc : Fin (2 ^ a) → Fin p) (ret : Fin p) (n : ℕ) : Fin p :=
+ if h : n < 2 ^ a then pc ⟨n, h⟩ else ret
+
+/-- The label of each slot contains its entire initialization instruction. -/
+def instruction (pc : Fin (2 ^ a) → Fin p) (bank : Fin (2 ^ a) ↪ Fin r) (ret : Fin p)
+ (j : Fin (2 ^ a)) : Instr w p r k :=
+ let target := next pc ret (j.val + 1)
+ if hz : j.val = 0 then .constant (bank j) 0 target
+ else if ho : j.val = 1 then .constant (bank j) 1 target
+ else .binary .add (bank j) (bank ⟨j.val - 1, by have := j.isLt; omega⟩)
+ (bank ⟨1, by have := j.isLt; omega⟩) target
+
+theorem resize_instruction (pc : Fin (2 ^ a) → Fin p) (bank : Fin (2 ^ a) ↪ Fin r)
+ (ret : Fin p) (j : Fin (2 ^ a)) :
+ (instruction (w := 5) (k := k) pc bank ret j).resize w = instruction pc bank ret j := by
+ unfold instruction
+ split <;> first | rfl | split <;> rfl
+
+/-- Every supplied slot label contains the instruction that initializes its ordinal register
+and continues to the next slot or the return label. -/
+def Linked (M : Machine w p r k) (pc : Fin (2 ^ a) → Fin p) (bank : Fin (2 ^ a) ↪ Fin r)
+ (ret : Fin p) : Prop := ∀ j, M.code (pc j) = instruction pc bank ret j
+
+variable {M : Machine w p r k} {pc : Fin (2 ^ a) → Fin p} {bank : Fin (2 ^ a) ↪ Fin r}
+variable {ret : Fin p}
+
+private theorem step (link : Linked M pc bank ret) (j : Fin (2 ^ a)) (c : Config w p r)
+ (hc : c.pc = pc j)
+ (ready : ∀ i : Fin (2 ^ a), i.val < j.val → c.reg (bank i) = (i.val : Word w)) :
+ M.program.step c = .localStep (c.put (next pc ret (j.val + 1)) (bank j) (j.val : Word w)) := by
+ change (M.code c.pc).run M.publicData c = _
+ rw [hc, link]
+ unfold instruction
+ split
+ · rename_i hz
+ simp only [Instr.run, hz, Nat.cast_zero]
+ · rename_i hz
+ split
+ · rename_i ho
+ simp only [Instr.run, ho, Nat.cast_one]
+ · rename_i ho
+ let prev : Fin (2 ^ a) := ⟨j.val - 1, by have := j.isLt; omega⟩
+ let unit : Fin (2 ^ a) := ⟨1, by have := j.isLt; omega⟩
+ change CallAction.localStep (c.put _ _ (c.reg (bank prev) + c.reg (bank unit))) = _
+ have pred : prev.val + 1 = j.val := by dsimp [prev]; omega
+ rw [ready prev (by omega), ready unit (by dsimp [unit]; omega)]
+ change CallAction.localStep (c.put _ _ ((prev.val : Word w) + ((1 : ℕ) : Word w))) = _
+ rw [← Nat.cast_add, pred]
+
+private theorem one_tick (m : Memory w) {c d : Config w p r}
+ (h : M.program.step c = .localStep d) : ChildScan.Prefix M m c d [] [.tick] := by
+ intro fuel tail
+ simp only [List.nil_append, List.length_cons, List.length_nil, execute, h]
+ rfl
+
+/-- Execute the initializer from arbitrary registers. The argument suffix and
+external memory are passed directly to the continuation. -/
+theorem native (link : Linked M pc bank ret) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc 0) :
+ ∃ d, d.pc = ret ∧ d.persistent = c.persistent ∧ d.privateMem = c.privateMem ∧
+ (∀ j, d.reg (bank j) = (j.val : Word w)) ∧
+ (∀ x, x ∉ Set.range bank → d.reg x = c.reg x) ∧
+ ChildScan.Prefix M m c d [] (List.replicate (2 ^ a) .tick) := by
+ have upto (n : ℕ) (hn : n ≤ 2 ^ a) :
+ ∃ d, d.pc = next pc ret n ∧ d.persistent = c.persistent ∧ d.privateMem = c.privateMem ∧
+ (∀ j : Fin (2 ^ a), j.val < n → d.reg (bank j) = (j.val : Word w)) ∧
+ (∀ x, x ∉ Set.range bank → d.reg x = c.reg x) ∧
+ ChildScan.Prefix M m c d [] (List.replicate n .tick) := by
+ induction n with
+ | zero =>
+ have pos : 0 < 2 ^ a := pow_pos (by decide) _
+ refine ⟨c, ?_, rfl, rfl, fun j hj => (Nat.not_lt_zero _ hj).elim, fun _ _ => rfl, ?_⟩
+ · rw [next, dite_eq_left pos, hc]
+ congr 1
+ · intro fuel tail
+ simp
+ | succ n ih =>
+ have room : n < 2 ^ a := hn
+ let j : Fin (2 ^ a) := ⟨n, room⟩
+ obtain ⟨d, atPC, state, priv, ready, frame, run⟩ := ih room.le
+ let z := d.put (next pc ret (n + 1)) (bank j) (n : Word w)
+ have hj : d.pc = pc j := by simpa only [next, dite_eq_left room, j] using atPC
+ have single : ChildScan.Prefix M m d z [] [.tick] := one_tick m (step link j d hj ready)
+ refine ⟨z, rfl, state, priv, ?_, ?_, ?_⟩
+ · intro i hi
+ by_cases e : i = j
+ · subst i
+ exact Config.put_same ..
+ · have ne : i.val ≠ n := fun he => e (Fin.ext he)
+ exact (Function.update_of_ne (bank.injective.ne e) ..).trans (ready i (by omega))
+ · intro x hx
+ have ne : x ≠ bank j := fun e => hx ⟨j, e.symm⟩
+ exact (Function.update_of_ne ne ..).trans (frame x hx)
+ · simpa only [List.nil_append, List.replicate_succ'] using run.trans single
+ obtain ⟨d, atPC, state, priv, ready, frame, run⟩ := upto (2 ^ a) le_rfl
+ exact ⟨d, by simpa only [next, lt_self_iff_false, ↓reduceDIte] using atPC, state, priv,
+ fun j => ready j j.isLt, frame, run⟩
+
+end PairSimulation.NodeArguments.ChildBankInit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildCode.lean b/lean/OAI/Computability/VPVNP/PairNodeChildCode.lean
new file mode 100644
index 0000000000..012f0eec52
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildCode.lean
@@ -0,0 +1,184 @@
+import OAI.Computability.VPVNP.PairNodeChildHeader
+import OAI.Computability.VPVNP.PairNodeChildScan
+
+/-!
+# A finite instruction table for a parent's child scan
+
+For a fixed old degree, the table contains the parent header, the shared
+child loop, and the setup, width lookup, and guess code of every outgoing
+and incoming slot. All destinations refer to its finite label set except
+the supplied return address. The same region can be embedded in a larger
+vertex handler.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildCode
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+/-- One incidence slot of an old site. The Boolean selects outgoing (false) or incoming (true),
+and the ordinal selects one of the 2^a ports in that direction. -/
+abbrev Slot (a : ℕ) := Bool × Fin (2 ^ a)
+/-- Instruction labels within a single slot, divided into two for port setup, six for the width
+lookup and seven for guessing and storing field bits. -/
+abbrev SlotLabel := Fin 2 ⊕ (Fin 6 ⊕ Fin 7)
+/-- Labels for the entire child scan. The alternatives distinguish the parent header, loop
+guard, child address calculation and instructions specific to each incidence slot. -/
+abbrev Label (a : ℕ) := Fin 17 ⊕ (Fin 3 ⊕ (Fin 7 ⊕ (Slot a × SlotLabel)))
+
+/-- Number of child-scan instructions before the return destination. The shared blocks use 27
+instructions, and each of the 2 · 2^a slots contributes 15. -/
+def size (a : ℕ) := 17 + (3 + (7 + (2 * 2 ^ a) * (2 + (6 + 7))))
+
+/-- Arithmetic numbering of all parent and slot instructions. -/
+def number (a : ℕ) : Label a ≃ Fin (size a) :=
+ let slots := (finTwoEquiv.symm.prodCongr (Equiv.refl (Fin (2 ^ a)))).trans finProdFinEquiv
+ let part := ((Equiv.refl (Fin 2)).sumCongr finSumFinEquiv).trans finSumFinEquiv
+ let bodies := (slots.prodCongr part).trans finProdFinEquiv
+ let child := ((Equiv.refl (Fin 7)).sumCongr bodies).trans finSumFinEquiv
+ let loop := ((Equiv.refl (Fin 3)).sumCongr child).trans finSumFinEquiv
+ ((Equiv.refl (Fin 17)).sumCongr loop).trans finSumFinEquiv
+
+variable {w p r k a : ℕ}
+
+/-- Program counter of the j-th parent-header instruction in the supplied placement of
+child-scan labels. -/
+def headerPC (loc : Label a → Fin p) (j : Fin 17) := loc (.inl j)
+
+/-- Restricts the label placement to the loop guard, address calculation and three blocks for
+each slot, giving the destinations needed to link the child loop. -/
+def sites (loc : Label a → Fin p) : ChildScan.Sites a p where
+ guard i := loc (.inr (.inl i))
+ address i := loc (.inr (.inr (.inl i)))
+ slots :=
+ { setup := fun i j => loc (.inr (.inr (.inr (i, .inl j))))
+ header := fun i j => loc (.inr (.inr (.inr (i, .inr (.inl j)))))
+ guess := fun i j => loc (.inr (.inr (.inr (i, .inr (.inr j))))) }
+
+private def afterSlot (i : Slot a) : List (Slot a) → List (Slot a)
+ | [] => []
+ | j :: js => if i = j then js else afterSlot i js
+
+private theorem slots_nodup (n : ℕ) : (ChildSlots.slots n).Nodup := by
+ apply List.nodup_append'.mpr
+ refine ⟨List.nodup_ofFn_ofInjective (fun _ _ h => congrArg Prod.snd h),
+ List.nodup_ofFn_ofInjective (fun _ _ h => congrArg Prod.snd h), ?_⟩
+ intro x h₁ h₂
+ obtain ⟨j, rfl⟩ := List.mem_ofFn.mp h₁
+ obtain ⟨l, eq⟩ := List.mem_ofFn.mp h₂
+ exact Bool.noConfusion (congrArg Prod.fst eq)
+
+/-- Emit the relative instruction at a body label. The slot loader may read
+a public operand or a private ordinal register. -/
+def instructionWith (loc : Label a → Fin p) (reg : Fin 16 ↪ Fin r)
+ (source : ChildSlots.Names (2 ^ a) r k)
+ (ret : Fin p) : Label a → Instr w p r k
+ | .inl j => ChildHeader.instruction (headerPC loc) reg ((sites loc).guard 0) j
+ | .inr (.inl j) => ChildScan.guard (sites loc).guard reg ((sites loc).address 0) ret j
+ | .inr (.inr (.inl j)) => ChildAddress.instruction (sites loc).address reg
+ (ChildSlots.first (sites loc).slots ((sites loc).guard 0) (ChildSlots.slots (2 ^ a))) j
+ | .inr (.inr (.inr (i, .inl j))) =>
+ ChildSlots.setupWith (sites loc).slots (ChildScan.slotRegs reg) source i j
+ | .inr (.inr (.inr (i, .inr (.inl j)))) =>
+ FieldGuess.instruction ((sites loc).slots.header i)
+ (ChildSlots.guessRegs (ChildScan.slotRegs reg)) ((sites loc).slots.guess i 0) j
+ | .inr (.inr (.inr (i, .inr (.inr j)))) =>
+ PrivateFields.instruction .guess ((sites loc).slots.guess i)
+ (FieldGuess.fieldRegs (ChildSlots.guessRegs (ChildScan.slotRegs reg)))
+ (ChildSlots.first (sites loc).slots ((sites loc).guard 0)
+ (afterSlot i (ChildSlots.slots (2 ^ a)))) j
+
+theorem resize_instructionWith (loc : Label a → Fin p) (reg : Fin 16 ↪ Fin r)
+ (source : ChildSlots.Names (2 ^ a) r k) (ret : Fin p) (j : Label a) :
+ (instructionWith (w := 1) loc reg source ret j).resize w =
+ instructionWith loc reg source ret j := by
+ rcases j with j | j | j | ⟨i, j | j | j⟩
+ · fin_cases j <;> rfl
+ · exact ChildScan.resize_guard ..
+ · exact ChildAddress.resize_instruction ..
+ · exact ChildSlots.resize_setupWith ..
+ · exact FieldGuess.resize_instruction ..
+ · exact PrivateFields.resize_instruction .guess _ _ _ j
+
+/-- A machine containing this code satisfies every linkage condition, including
+the return from the last slot to the original parent guard. -/
+theorem linkedWith (M : Machine w p r k) (loc : Label a → Fin p) (reg : Fin 16 ↪ Fin r)
+ (source : ChildSlots.Names (2 ^ a) r k) (ret : Fin p)
+ (code : ∀ j, M.code (loc j) = instructionWith loc reg source ret j) :
+ ChildHeader.Linked M (headerPC loc) reg ((sites loc).guard 0) ∧
+ ChildScan.LinkedWith M (sites loc) reg source ret := by
+ refine ⟨fun j => code (.inl j), ⟨fun j => code (.inr (.inl j)),
+ fun j => code (.inr (.inr (.inl j))), ?_⟩⟩
+ let allSlots := ChildSlots.slots (2 ^ a)
+ have aux (xs : List (Slot a)) (hs : xs.Nodup)
+ (suffix : ∀ i ∈ xs, afterSlot i allSlots = afterSlot i xs) :
+ ChildSlots.LinkedWith M (sites loc).slots (ChildScan.slotRegs reg) source
+ ((sites loc).guard 0) xs := by
+ induction xs with
+ | nil => trivial
+ | cons i xs ih =>
+ have hi := List.nodup_cons.mp hs
+ have jump : afterSlot i allSlots = xs :=
+ (suffix i List.mem_cons_self).trans (by simp [afterSlot])
+ refine ⟨fun j => code (.inr (.inr (.inr (i, .inl j)))),
+ fun j => code (.inr (.inr (.inr (i, .inr (.inl j))))), ?_, ih hi.2 ?_⟩
+ · intro j
+ have hit := code (.inr (.inr (.inr (i, .inr (.inr j)))))
+ change M.code ((sites loc).slots.guess i j) = PrivateFields.instruction .guess _ _
+ (ChildSlots.first (sites loc).slots ((sites loc).guard 0) (afterSlot i allSlots)) j at hit
+ rwa [jump] at hit
+ · intro j hj
+ have ne : j ≠ i := fun eq => hi.1 (eq ▸ hj)
+ simpa only [afterSlot, ite_eq_right ne] using suffix j (List.mem_cons_of_mem _ hj)
+ exact aux allSlots (slots_nodup _) (fun _ _ => rfl)
+
+/-- The original table obtains its slot names from public operands. -/
+abbrev instruction (loc : Label a → Fin p) (reg : Fin 16 ↪ Fin r) (port : Fin (2 ^ a) → Fin k)
+ (ret : Fin p) : Label a → Instr w p r k := instructionWith loc reg (.operand port) ret
+
+theorem resize_instruction (loc : Label a → Fin p) (reg : Fin 16 ↪ Fin r)
+ (port : Fin (2 ^ a) → Fin k) (ret : Fin p) (j : Label a) :
+ (instruction (w := 1) loc reg port ret j).resize w = instruction loc reg port ret j :=
+ resize_instructionWith ..
+
+theorem linked (M : Machine w p r k) (loc : Label a → Fin p) (reg : Fin 16 ↪ Fin r)
+ (port : Fin (2 ^ a) → Fin k) (ret : Fin p)
+ (code : ∀ j, M.code (loc j) = instruction loc reg port ret j) :
+ ChildHeader.Linked M (headerPC loc) reg ((sites loc).guard 0) ∧
+ ChildScan.Linked M (sites loc) reg port ret := by
+ obtain ⟨hh, hl⟩ := linkedWith M loc reg (.operand port) ret code
+ exact ⟨hh, hl.guard, hl.address, hl.slots⟩
+
+/-- A standalone parent handler has one terminal instruction in addition to
+its child scan. Slot ordinals use the corresponding public parameter number. -/
+def localPC (a : ℕ) (j : Label a) : Fin (size a + 1) := (number a j).castSucc
+
+/-- Standalone 16-register machine template for a parent scan. It starts at the first header
+instruction, loads slot ordinals from public operands and returns to a final accept
+instruction. -/
+def table (a : ℕ) : Template (size a + 1) 16 (2 ^ a) where
+ literalWidth := 1
+ entry := headerPC (localPC a) 0
+ code := Fin.lastCases .accept fun j =>
+ instruction (localPC a) (Function.Embedding.refl _) id (Fin.last (size a)) ((number a).symm j)
+
+theorem table_linked (a w : ℕ) (pub : Fin (2 ^ a) → Word w) :
+ let M := (table a).instantiate w pub
+ let loc := localPC a
+ let reg := Function.Embedding.refl (Fin 16)
+ ChildHeader.Linked M (headerPC loc) reg ((sites loc).guard 0) ∧
+ ChildScan.Linked M (sites loc) reg id (Fin.last (size a)) := by
+ apply linked
+ intro j
+ simp only [Template.instantiate, table, localPC, Fin.lastCases_castSucc,
+ Equiv.symm_apply_apply, resize_instruction]
+
+end PairSimulation.NodeArguments.ChildCode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildHeader.lean b/lean/OAI/Computability/VPVNP/PairNodeChildHeader.lean
new file mode 100644
index 0000000000..4fd007aac7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildHeader.lean
@@ -0,0 +1,204 @@
+import OAI.Computability.VPVNP.PairNodeChildAddress
+import OAI.Computability.VPVNP.PairSimulationDFS
+
+/-!
+# Loading a placement row and the old layer's parameter directory
+
+The popped descriptor supplies a child-list pointer and count. A seven-word
+directory supplies the geometry of the old descriptors, the private argument
+arena, and the inverse-incidence and width columns. These words are read
+once before the child scan enters its loop.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildHeader
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.read ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r k : ℕ}
+
+/-- The directory words, in their stored order. -/
+structure Fields (w : ℕ) where
+ /-- External address of the first descriptor row in the older layer. The child scan subtracts
+ this address from the child's row address to recover its offset. -/
+ olderBase : Word w
+ /-- Distance in words between successive older-layer descriptor rows. Dividing a row offset
+ by this stride gives the child's site ordinal. -/
+ stride : Word w
+ /-- Number of outgoing slots per older-layer site. Multiplying the site ordinal by this
+ degree gives the index of its first port. -/
+ degree : Word w
+ /-- Base address of the private arena where the child scan stores guessed half-wire
+ arguments. -/
+ argumentStart : Word w
+ /-- Distance in private words between argument buffers indexed by consecutive node addresses.
+ A child at address `node` uses the buffer at `argumentStart + node * argumentStride`. -/
+ argumentStride : Word w
+ /-- Base address of the inverse-incidence table. At an incoming port, this table gives the
+ source port whose wire width the scan needs. -/
+ actualIn : Word w
+ /-- Base address of the wire-width table indexed by actual outgoing ports. Each width tells
+ the scan how many argument bits to guess for that wire. -/
+ width : Word w
+
+/-- Seven words in the order read by the child scan. They contain the descriptor base and
+stride, degree, private argument base and stride, inverse-incidence base, and width-table
+base. -/
+def Fields.words (f : Fields w) : Fin 7 → Word w :=
+ ![f.olderBase, f.stride, f.degree, f.argumentStart, f.argumentStride, f.actualIn, f.width]
+
+/-- The seven directory words occupy consecutive external memory cells beginning at `base`,
+using word-address arithmetic. -/
+def Fields.Stored (f : Fields w) (m : Memory w) (base : Word w) : Prop :=
+ ∀ j : Fin 7, m (base + (j.val : Word w)).val = f.words j
+
+/-- The 17 instructions that load the child-list pointer and count from the popped row, read
+the seven older-layer directory words, and pass control to `done`. -/
+def instruction (pc : Fin 17 → Fin p) (reg : Fin 16 ↪ Fin r) (done : Fin p) :
+ Fin 17 → Instr w p r k :=
+ ![.constant (reg 3) 1 (pc 1), .readExternal (reg 9) (reg 7) (pc 2),
+ .binary .add (reg 10) (reg 7) (reg 3) (pc 3), .readExternal (reg 10) (reg 10) (pc 4),
+ .readExternal (reg 11) (reg 8) (pc 5), .binary .add (reg 7) (reg 8) (reg 3) (pc 6),
+ .readExternal (reg 12) (reg 7) (pc 7), .binary .add (reg 7) (reg 7) (reg 3) (pc 8),
+ .readExternal (reg 13) (reg 7) (pc 9), .binary .add (reg 7) (reg 7) (reg 3) (pc 10),
+ .readExternal (reg 14) (reg 7) (pc 11), .binary .add (reg 7) (reg 7) (reg 3) (pc 12),
+ .readExternal (reg 15) (reg 7) (pc 13), .binary .add (reg 7) (reg 7) (reg 3) (pc 14),
+ .readExternal (reg 6) (reg 7) (pc 15), .binary .add (reg 7) (reg 7) (reg 3) (pc 16),
+ .readExternal (reg 7) (reg 7) done]
+
+theorem resize_instruction (pc : Fin 17 → Fin p) (reg : Fin 16 ↪ Fin r) (done : Fin p)
+ (i : Fin 17) : (instruction (w := 2) (k := k) pc reg done i).resize w =
+ instruction pc reg done i := by fin_cases i <;> rfl
+
+/-- The machine contains the header's 17 instructions at the specified program counters, with
+the supplied register assignment and continuation. -/
+def Linked (M : Machine w p r k) (pc : Fin 17 → Fin p) (reg : Fin 16 ↪ Fin r) (done : Fin p) :
+ Prop := ∀ i, M.code (pc i) = instruction pc reg done i
+
+private def offset (base : Word w) : ℕ → Word w
+ | 0 => base
+ | n + 1 => offset base n + 1
+
+private theorem offset_eq (base : Word w) (n : ℕ) : offset base n = base + (n : Word w) := by
+ induction n with
+ | zero => simp [offset]
+ | succ n ih => simp [offset, ih, add_assoc]
+
+/-- Trace of the header load. The machine reads the child-list pointer and count at `node` and
+`node + 1`, then reads the seven directory words beginning at `base`. -/
+def events (m : Memory w) (node base : Word w) : List (Event w) :=
+ let fetch := fun addr : Word w => Event.read addr (m addr.val)
+ [.tick, fetch node, .tick, fetch (node + 1), fetch base, .tick, fetch (offset base 1),
+ .tick, fetch (offset base 2), .tick, fetch (offset base 3), .tick, fetch (offset base 4),
+ .tick, fetch (offset base 5), .tick, fetch (offset base 6)]
+
+theorem cost (m : Memory w) (node base : Word w) :
+ countProbes (events m node base) = 9 ∧ (events m node base).length = 17 ∧
+ choiceBits (events m node base) = [] := ⟨rfl, rfl, rfl⟩
+
+/-- The header writes only the child scan's input registers. -/
+def Preserved (reg : Fin 16 ↪ Fin r) (j : Fin r) : Prop :=
+ ∀ z : Fin 16, z = 3 ∨ z = 6 ∨ z = 7 ∨ 9 ≤ z → j ≠ reg z
+
+/-- State at the header continuation. The scan registers hold one, the child-list pointer and
+count, and the seven directory words. All other registers, private memory, and persistent
+state retain their entry values. -/
+structure Ready (reg : Fin 16 ↪ Fin r) (done : Fin p) (c d : Config w p r)
+ (f : Fields w) (src countValue : ℕ) : Prop where
+ pc : d.pc = done
+ one : d.reg (reg 3) = 1
+ source : d.reg (reg 9) = (src : Word w)
+ count : d.reg (reg 10) = (countValue : Word w)
+ olderBase : d.reg (reg 11) = f.olderBase
+ stride : d.reg (reg 12) = f.stride
+ degree : d.reg (reg 13) = f.degree
+ argumentStart : d.reg (reg 14) = f.argumentStart
+ argumentStride : d.reg (reg 15) = f.argumentStride
+ actualIn : d.reg (reg 6) = f.actualIn
+ width : d.reg (reg 7) = f.width
+ frame : ∀ j, Preserved reg j → d.reg j = c.reg j
+ privateMem : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+variable {M : Machine w p r k} {pc : Fin 17 → Fin p} {reg : Fin 16 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (hl : Linked M pc reg done) (i : Fin 17) {c : Config w p r}
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg done i).run M.publicData c := by
+ change (M.code c.pc).run _ _ = _
+ rw [hc, hl]
+
+/-- Load the child scan's actual source, count and layer parameters. The prefix
+preserves the bit stream and reaches the linked loop on the same external memory. -/
+theorem native (hl : Linked M pc reg done) (m : Memory w) (c : Config w p r) (hc : c.pc = pc 0)
+ (f : Fields w) (stored : f.Stored m (c.reg (reg 8))) (src : ℕ) (kids : List (Word w))
+ (row : DFS.Row m (c.reg (reg 7)).val src kids) :
+ ∃ d, Ready reg done c d f src kids.length ∧ ∀ fuel bs,
+ execute M.program (fuel + 17) c m bs = (execute M.program fuel d m bs).map
+ (fun rep => ⟨events m (c.reg (reg 7)) (c.reg (reg 8)) ++ rep.events, rep.result⟩) := by
+ let node := c.reg (reg 7)
+ let base := c.reg (reg 8)
+ have srcWord : m node.val = (src : Word w) := row.2.2.1
+ have countWord : m (node + 1).val = (kids.length : Word w) := by
+ have hn : node.val + 1 < 2 ^ w := row.1
+ have oneVal : (1 : Word w).val = 1 := by
+ rw [Fin.val_one', Nat.mod_eq_of_lt (by omega : 1 < 2 ^ w)]
+ rw [Fin.val_add, oneVal, Nat.mod_eq_of_lt hn]
+ exact row.2.2.2.1
+ have read (j : Fin 7) : m (offset base j.val).val = f.words j := by
+ rw [offset_eq]
+ exact stored j
+ have path := ReadPrefix.tick (step_at hl 0 hc)
+ (ReadPrefix.read (m := m) _ (step_at hl 1 rfl)
+ (ReadPrefix.tick (step_at hl 2 rfl)
+ (ReadPrefix.read _ (step_at hl 3 rfl)
+ (ReadPrefix.read _ (step_at hl 4 rfl)
+ (ReadPrefix.tick (step_at hl 5 rfl)
+ (ReadPrefix.read _ (step_at hl 6 rfl)
+ (ReadPrefix.tick (step_at hl 7 rfl)
+ (ReadPrefix.read _ (step_at hl 8 rfl)
+ (ReadPrefix.tick (step_at hl 9 rfl)
+ (ReadPrefix.read _ (step_at hl 10 rfl)
+ (ReadPrefix.tick (step_at hl 11 rfl)
+ (ReadPrefix.read _ (step_at hl 12 rfl)
+ (ReadPrefix.tick (step_at hl 13 rfl)
+ (ReadPrefix.read _ (step_at hl 14 rfl)
+ (ReadPrefix.tick (step_at hl 15 rfl)
+ (ReadPrefix.read _ (step_at hl 16 rfl) (ReadPrefix.nil _)))))))))))))))))
+ let final {d : Config w p r} {es : List (Event w)} (_ : ReadPrefix M m c es d) := d
+ refine ⟨final path, ?_, ?_⟩
+ · refine ⟨rfl, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, rfl, rfl⟩
+ all_goals simp only [final]
+ all_goals simp (config := { decide := true }) only [Config.put, Fin.isValue, ne_eq,
+ reg.injective.eq_iff, not_false_eq_true, Function.update_of_ne, BinaryOp.eval,
+ Function.update_self, Function.update_idem]
+ · exact srcWord
+ · exact countWord
+ · exact read 0
+ · exact read 1
+ · exact read 2
+ · exact read 3
+ · exact read 4
+ · exact read 5
+ · exact read 6
+ · intro j keep
+ simp [Function.update_of_ne (keep 3 (by decide)), Function.update_of_ne (keep 6 (by decide)),
+ Function.update_of_ne (keep 7 (by decide)), Function.update_of_ne (keep 9 (by decide)),
+ Function.update_of_ne (keep 10 (by decide)), Function.update_of_ne (keep 11 (by decide)),
+ Function.update_of_ne (keep 12 (by decide)), Function.update_of_ne (keep 13 (by decide)),
+ Function.update_of_ne (keep 14 (by decide)), Function.update_of_ne (keep 15 (by decide))]
+ · intro fuel bs
+ simpa (config := { decide := true }) [events, offset, Config.put, reg.injective.eq_iff,
+ BinaryOp.eval, final] using ReadPrefix.execute path fuel bs
+
+end PairSimulation.NodeArguments.ChildHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildImmediate.lean b/lean/OAI/Computability/VPVNP/PairNodeChildImmediate.lean
new file mode 100644
index 0000000000..01e65a462a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildImmediate.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.PairNodeChildBankInit
+import OAI.Computability.VPVNP.PairNodeChildCode
+import OAI.Computability.VPVNP.PairNodeChildStage
+
+/-!
+# Child-argument scans on the eleven-operand vertex machine
+
+A fixed register bank supplies every slot number. The initializer writes zero
+and one as instruction literals and derives each following ordinal by addition.
+The body uses a register copy in the slot's existing setup instruction. The
+number of setup instructions and the field, packet and probe traces of the
+child scan are therefore independent of the source of the slot numbers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildCode.RegisterBank
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords Compression DFS ChildScan
+open scoped Fin.CommRing
+
+variable {a g w p r k : ℕ}
+
+/-- Body instruction embedded at the existing parent, child and slot labels. -/
+abbrev instruction (loc : Label a → Fin p) (reg : Fin 16 ↪ Fin r)
+ (bank : Fin (2 ^ a) ↪ Fin r) (ret : Fin p) (j : Label a) : Instr w p r k :=
+ instructionWith loc reg (.bank bank) ret j
+
+private theorem resize_five (op : Instr 1 p r k) : (op.resize 5).resize w = op.resize w := by
+ cases op <;> try rfl
+ case constant dst v pc =>
+ simp [Instr.resize, Nat.mod_eq_of_lt (v.isLt.trans (by decide : 2 ^ 1 < 32))]
+
+/-- The body can be emitted at the five-bit literal width of the actual vertex
+image even when the slot exponent is greater than five. -/
+theorem resize_instruction (loc : Label a → Fin p) (reg : Fin 16 ↪ Fin r)
+ (bank : Fin (2 ^ a) ↪ Fin r) (ret : Fin p) (j : Label a) :
+ (instruction (w := 5) (k := k) loc reg bank ret j).resize w =
+ instruction loc reg bank ret j := by
+ have h := resize_instructionWith (w := 5) loc reg (ChildSlots.Names.bank (k := k) bank) ret j
+ change (instructionWith (w := 5) loc reg (.bank bank) ret j).resize w = _
+ rw [← h, resize_five]
+ exact resize_instructionWith ..
+
+variable {M : Machine w p r k} {loc : Label a → Fin p} {reg : Fin 16 ↪ Fin r}
+variable {bank : Fin (2 ^ a) ↪ Fin r} {ret : Fin p} {initPC : Fin (2 ^ a) → Fin p}
+variable {X : State a g} {T : IncidenceDirectory w} {A : Arena} {older cap : ℕ} {m : Memory w}
+
+/-- Execute the parent header and argument scan with initialized ordinal
+registers. Every supplied public word remains available to other vertex code. -/
+theorem native_ready (code : ∀ j, M.code (loc j) = instruction loc reg bank ret j)
+ (apart : ∀ i j, bank i ≠ reg j) (rep : T.ActualColumns X m)
+ (xs : List (Child X)) (src : ℕ) (c : Config w p r)
+ (names : ∀ j, c.reg (bank j) = (j.val : Word w)) (hc : c.pc = headerPC loc 0)
+ (stored : (directory a older cap A T).Stored m (c.reg (reg 8)))
+ (row : Row m (c.reg (reg 7)).val src (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w) :
+ let qs := xs.map (Child.packet X older cap)
+ let es := ChildHeader.events m (c.reg (reg 7)) (c.reg (reg 8)) ++ events X T m src xs
+ ∃ d, d.pc = ret ∧ d.persistent = c.persistent ∧ d.privateMem = storePackets A qs c.privateMem ∧
+ (∀ endAddr, scratch endAddr d.privateMem = writePackets A qs (scratch endAddr c.privateMem)) ∧
+ (∀ i, ChildHeader.Preserved reg i → i ∉ mutableRegs reg → d.reg i = c.reg i) ∧
+ ChildScan.Prefix M m c d (qs.flatMap Packet.bits) es := by
+ obtain ⟨hh, hl⟩ := linkedWith M loc reg (.bank bank) ret code
+ exact native_stageWith hh hl apart rep xs src c names hc stored row strideFit nodes packets
+
+/-- A short argument tape cannot return through the register-based body. -/
+theorem reject_ready (code : ∀ j, M.code (loc j) = instruction loc reg bank ret j)
+ (apart : ∀ i j, bank i ≠ reg j) (rep : T.ActualColumns X m)
+ (xs : List (Child X)) (src : ℕ) (c : Config w p r)
+ (names : ∀ j, c.reg (bank j) = (j.val : Word w)) (hc : c.pc = headerPC loc 0)
+ (stored : (directory a older cap A T).Stored m (c.reg (reg 8)))
+ (row : Row m (c.reg (reg 7)).val src (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w)
+ (bs : List Bool) (short : bs.length < (xs.flatMap (Child.payload X)).length) :
+ ¬ Returns M c m bs := by
+ obtain ⟨hh, hl⟩ := linkedWith M loc reg (.bank bank) ret code
+ exact reject_stageWith hh hl apart rep xs src c names hc stored row
+ strideFit nodes packets bs short
+
+private theorem reg_outside (apart : ∀ i j, bank i ≠ reg j) (j : Fin 16) :
+ reg j ∉ Set.range bank := fun ⟨i, hi⟩ => apart i j hi
+
+/-- The complete hosted stage starts with arbitrary ordinal-register contents.
+It fills the bank, reads the actual descriptor and consumes the placed child
+arguments. The only added events are the bank's private initialization ticks. -/
+theorem native_stage (init : ChildBankInit.Linked M initPC bank (headerPC loc 0))
+ (code : ∀ j, M.code (loc j) = instruction loc reg bank ret j)
+ (apart : ∀ i j, bank i ≠ reg j) (rep : T.ActualColumns X m)
+ (xs : List (Child X)) (src : ℕ) (c : Config w p r) (hc : c.pc = initPC 0)
+ (stored : (directory a older cap A T).Stored m (c.reg (reg 8)))
+ (row : Row m (c.reg (reg 7)).val src (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w) :
+ let qs := xs.map (Child.packet X older cap)
+ let es := List.replicate (2 ^ a) .tick ++
+ (ChildHeader.events m (c.reg (reg 7)) (c.reg (reg 8)) ++ events X T m src xs)
+ ∃ d, d.pc = ret ∧ d.persistent = c.persistent ∧ d.privateMem = storePackets A qs c.privateMem ∧
+ (∀ endAddr, scratch endAddr d.privateMem = writePackets A qs (scratch endAddr c.privateMem)) ∧
+ (∀ i, i ∉ Set.range bank → ChildHeader.Preserved reg i → i ∉ mutableRegs reg →
+ d.reg i = c.reg i) ∧ ChildScan.Prefix M m c d (qs.flatMap Packet.bits) es := by
+ obtain ⟨mid, entry, state, priv, names, frame, before⟩ := ChildBankInit.native init m c hc
+ have keep (j : Fin 16) := frame (reg j) (reg_outside apart j)
+ obtain ⟨d, pc, persistent, memory, scratchEq, unchanged, body⟩ :=
+ native_ready code apart rep xs src mid names entry (keep 8 ▸ stored) (keep 7 ▸ row)
+ strideFit nodes packets
+ rw [keep 7, keep 8] at body
+ rw [priv] at memory scratchEq
+ exact ⟨d, pc, persistent.trans state, memory, scratchEq,
+ fun i hi h₁ h₂ => (unchanged i h₁ h₂).trans (frame i hi), before.trans body⟩
+
+/-- Short-tape rejection holds already at the first bank instruction. -/
+theorem reject_stage (init : ChildBankInit.Linked M initPC bank (headerPC loc 0))
+ (code : ∀ j, M.code (loc j) = instruction loc reg bank ret j)
+ (apart : ∀ i j, bank i ≠ reg j) (rep : T.ActualColumns X m)
+ (xs : List (Child X)) (src : ℕ) (c : Config w p r) (hc : c.pc = initPC 0)
+ (stored : (directory a older cap A T).Stored m (c.reg (reg 8)))
+ (row : Row m (c.reg (reg 7)).val src (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w)
+ (bs : List Bool) (short : bs.length < (xs.flatMap (Child.payload X)).length) :
+ ¬ Returns M c m bs := by
+ obtain ⟨mid, entry, _, _, names, frame, before⟩ := ChildBankInit.native init m c hc
+ have keep (j : Fin 16) := frame (reg j) (reg_outside apart j)
+ exact fun accepted => reject_ready code apart rep xs src mid names entry (keep 8 ▸ stored)
+ (keep 7 ▸ row) strideFit nodes packets bs short ((before.returns bs).mp accepted)
+
+end PairSimulation.NodeArguments.ChildCode.RegisterBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildLoop.lean b/lean/OAI/Computability/VPVNP/PairNodeChildLoop.lean
new file mode 100644
index 0000000000..15ffdb0c21
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildLoop.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.PairNodeChildSlots
+import OAI.Computability.VPVNP.PairPendingArguments
+
+/-!
+# Native loop control for a placement-fiber argument scan
+
+A three-instruction test exits on an empty row. On a nonempty row it removes
+one unit from the child counter and enters the descriptor-address block.
+The scan consumes only the supplied argument bits and returns with the
+unconsumed suffix and the remaining private memory available.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildScan
+
+open BurstRAM BurstRAM.PrivateRAM Compression LocalHistory CompressorRecords
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+open private returns_prefix from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+variable {w p r k a g : ℕ} {M : Machine w p r k} {m : Memory w}
+
+/-- A linked prefix that consumes exactly its own list of choices. -/
+def Prefix (M : Machine w p r k) (m : Memory w) (c d : Config w p r)
+ (bits : List Bool) (es : List (Event w)) : Prop := ∀ fuel tail,
+ execute M.program (fuel + es.length) c m (bits ++ tail) =
+ (execute M.program fuel d m tail).map (fun q => ⟨es ++ q.events, q.result⟩)
+
+theorem Prefix.trans {c d z : Config w p r} {xs ys : List Bool} {es fs : List (Event w)}
+ (first : Prefix M m c d xs es) (next : Prefix M m d z ys fs) :
+ Prefix M m c z (xs ++ ys) (es ++ fs) := by
+ intro fuel tail
+ rw [List.append_assoc, List.length_append, show fuel + (es.length + fs.length) =
+ (fuel + fs.length) + es.length by omega, first _ _, next fuel tail]
+ simp [Option.map_map, Function.comp_def, List.append_assoc]
+
+theorem Prefix.returns {c d : Config w p r} {xs : List Bool} {es : List (Event w)}
+ (h : Prefix M m c d xs es) (tail : List Bool) :
+ DFS.Returns M c m (xs ++ tail) ↔ DFS.Returns M d m tail := returns_prefix (fun f => h f tail)
+
+/-- Slot routines use the first nine registers of the enclosing loop. -/
+def slotRegs (reg : Fin 16 ↪ Fin r) : Fin 9 ↪ Fin r := (Fin.castAddEmb 7).trans reg
+
+/-- The loop branches to the address calculation or to its continuation. -/
+def guard (pc : Fin 3 → Fin p) (reg : Fin 16 ↪ Fin r) (body ret : Fin p) :
+ Fin 3 → Instr w p r k :=
+ ![.constant (reg 0) 0 (pc 1), .jumpEq (reg 10) (reg 0) ret (pc 2),
+ .binary .sub (reg 10) (reg 10) (reg 3) body]
+
+theorem resize_guard (pc : Fin 3 → Fin p) (reg : Fin 16 ↪ Fin r) (body ret : Fin p) (j : Fin 3) :
+ (guard (w := 1) (k := k) pc reg body ret j).resize w = guard pc reg body ret j := by
+ fin_cases j <;> rfl
+
+/-- The machine contains the three child-loop guard instructions at the specified counters.
+With its unit register set, the guard returns on a zero count or decrements the count and
+enters the child body. -/
+def GuardLinked (M : Machine w p r k) (pc : Fin 3 → Fin p) (reg : Fin 16 ↪ Fin r)
+ (body ret : Fin p) : Prop := ∀ j, M.code (pc j) = guard pc reg body ret j
+
+variable {pc : Fin 3 → Fin p} {reg : Fin 16 ↪ Fin r} {body ret : Fin p}
+
+private theorem step_at (hl : GuardLinked M pc reg body ret) (c : Config w p r) (j : Fin 3)
+ (hc : c.pc = pc j) : M.program.step c = (guard pc reg body ret j).run M.publicData c := by
+ simp [Machine.program, hc, hl j]
+
+/-- The empty loop exits without consuming a choice or changing the argument buffers. -/
+theorem guard_empty (hl : GuardLinked M pc reg body ret) (c : Config w p r) (hc : c.pc = pc 0)
+ (hzero : c.reg (reg 10) = 0) (m : Memory w) :
+ ∃ d, d.pc = ret ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ (∀ i, i ≠ reg 0 → d.reg i = c.reg i) ∧ Prefix M m c d [] [.tick, .tick] := by
+ let c₁ := c.put (pc 1) (reg 0) 0
+ let d := {c₁ with pc := ret}
+ have h₀ : M.program.step c = .localStep c₁ := step_at hl c 0 hc
+ have h₁ : M.program.step c₁ = .localStep d := by
+ rw [step_at hl c₁ 1 rfl]
+ change CallAction.localStep {c₁ with
+ pc := (if c₁.reg (reg 10) = c₁.reg (reg 0) then ret else pc 2)} = _
+ simp [c₁, Config.put, hzero, d]
+ refine ⟨d, rfl, rfl, rfl, fun i hi => by simp [d, c₁, Config.put, Function.update_of_ne hi], ?_⟩
+ exact fun fuel tail => ReadPrefix.execute
+ (ReadPrefix.tick h₀ (ReadPrefix.tick h₁ (ReadPrefix.nil _))) fuel tail
+
+/-- For a nonempty child row the guard subtracts one in the word register,
+retains the source pointer and enters the single common child body. -/
+theorem guard_cons (hl : GuardLinked M pc reg body ret) (c : Config w p r) (hc : c.pc = pc 0)
+ (n : ℕ) (hn : n + 1 < 2 ^ w) (hcount : c.reg (reg 10) = ((n + 1 : ℕ) : Word w))
+ (hone : c.reg (reg 3) = 1) (m : Memory w) :
+ ∃ d, d.pc = body ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ d.reg (reg 10) = (n : Word w) ∧ (∀ i, i ≠ reg 0 → i ≠ reg 10 → d.reg i = c.reg i) ∧
+ Prefix M m c d [] [.tick, .tick, .tick] := by
+ let c₁ := c.put (pc 1) (reg 0) 0
+ let c₂ := {c₁ with pc := pc 2}
+ let d := c₂.put body (reg 10) (n : Word w)
+ have nz : ((n + 1 : ℕ) : Word w) ≠ 0 := by
+ intro eqn
+ have h := congrArg Fin.val eqn
+ change (n + 1) % (2 ^ w) = 0 at h
+ rw [Nat.mod_eq_of_lt hn] at h
+ omega
+ have h₀ : M.program.step c = .localStep c₁ := step_at hl c 0 hc
+ have h₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at hl c₁ 1 rfl]
+ change CallAction.localStep {c₁ with
+ pc := (if c₁.reg (reg 10) = c₁.reg (reg 0) then ret else pc 2)} = _
+ have nz' : (n : Word w) + 1 ≠ 0 := by simpa using nz
+ simp [c₁, c₂, Config.put, hcount, nz']
+ have h₂ : M.program.step c₂ = .localStep d := by
+ rw [step_at hl c₂ 2 rfl]
+ change CallAction.localStep (c₂.put body (reg 10) (c₂.reg (reg 10) - c₂.reg (reg 3))) = _
+ simp [c₂, c₁, Config.put, hcount, hone, d]
+ refine ⟨d, rfl, rfl, rfl, Config.put_same .., fun i h₀ h₁ => by
+ simp [d, c₂, c₁, Config.put, Function.update_of_ne h₀, Function.update_of_ne h₁], ?_⟩
+ exact fun fuel tail => ReadPrefix.execute
+ (ReadPrefix.tick h₀ (ReadPrefix.tick h₁ (ReadPrefix.tick h₂ (ReadPrefix.nil _)))) fuel tail
+
+end PairSimulation.NodeArguments.ChildScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildPackets.lean b/lean/OAI/Computability/VPVNP/PairNodeChildPackets.lean
new file mode 100644
index 0000000000..9864e88737
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildPackets.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.PairNodeChildSlots
+import OAI.Computability.VPVNP.PairPendingArguments
+import OAI.Computability.VPVNP.PairTraversalRows
+
+/-!
+# Ordered arguments at the child addresses in a descriptor row
+
+Each child keeps its old site number, its actual outgoing and incoming
+half-wire coordinates, and its absolute DFS node. Machine writes to these
+addresses give the same scratch update as the logical list of packets.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildScan
+
+open BurstRAM BurstRAM.PrivateRAM LocalHistory Compression TraversalRows DFS
+open scoped Fin.CommRing
+
+variable {w a g endAddr : ℕ} (X : State a g)
+
+/-- An old site and all independent field values guessed there. -/
+structure Child where
+ /-- Site in the older network whose descriptor row and incidence widths determine this
+ child’s argument buffer and field lengths. -/
+ site : X.network.Site
+ /-- Independent bit values for every outgoing and incoming slot at the child site, indexed
+ within the actual half-wire width of that slot. -/
+ data : (i : Bool × Fin (2 ^ a)) → Fin (X.halfWidth site i.1 i.2) → Bool
+
+/-- Forms a child record from a network half-wire assignment by reading its coordinates in the
+outgoing and incoming incidence orders of the site. -/
+noncomputable def Child.ofHalf (u : X.network.Site) (h : X.network.Half u) : Child X :=
+ ⟨u, fun i => fieldBits X u h i.1 i.2⟩
+
+/-- Absolute DFS descriptor address of the old site, obtained from its ordinal in site order
+and the row layout with base older and capacity cap. -/
+def childNode (older cap : ℕ) (u : X.network.Site) : ℕ := (sitePointers cap older (siteOrder X) u).1
+
+/-- Serializes the child’s fields in port order, first for outgoing ports and then for incoming
+ports. Each field contributes exactly its own bits. -/
+noncomputable def Child.payload (v : Child X) : List Bool :=
+ ChildSlots.bits X v.site v.data (ChildSlots.slots (2 ^ a))
+
+/-- Pairs the child’s absolute descriptor address with its serialized half-wire bits so the
+pending-argument arena can store the payload at the corresponding node. -/
+noncomputable def Child.packet (older cap : ℕ) (v : Child X) : Packet :=
+ ⟨childNode X older cap v.site, v.payload X⟩
+
+theorem Child.payload_ofHalf (u : X.network.Site) (h : X.network.Half u) :
+ (Child.ofHalf X u h).payload X = packed X u h := ChildSlots.bits_all h
+
+private theorem field_lengths (u : X.network.Site)
+ (data : (i : Bool × Fin (2 ^ a)) → Fin (X.halfWidth u i.1 i.2) → Bool)
+ (slots : List (Bool × Fin (2 ^ a))) :
+ (ChildSlots.bits X u data slots).length = ChildSlots.length X u slots := by
+ simp [ChildSlots.bits, ChildSlots.length, List.flatMap_def, Function.comp_def]
+
+theorem Child.payload_length (v : Child X) :
+ (v.payload X).length = ChildSlots.length X v.site (ChildSlots.slots (2 ^ a)) :=
+ field_lengths X v.site v.data _
+
+/-- Any complete prefix is a possible independent assignment to the half-wire
+fields. Width-zero fields contribute an empty segment. -/
+private theorem choose_slots (u : X.network.Site) (slots : List (Bool × Fin (2 ^ a)))
+ (nd : slots.Nodup) (bs : List Bool) (h : ChildSlots.length X u slots ≤ bs.length) :
+ ∃ data, ChildSlots.bits X u data slots ++ bs.drop (ChildSlots.length X u slots) = bs := by
+ classical
+ induction slots generalizing bs with
+ | nil => exact ⟨fun _ _ => false, rfl⟩
+ | cons i rest ih =>
+ let n := X.halfWidth u i.1 i.2
+ have hl : ChildSlots.length X u (i :: rest) = n + ChildSlots.length X u rest := by
+ simp [ChildSlots.length, n]
+ obtain ⟨tail, ht⟩ := ih (List.nodup_cons.mp nd).2 (bs.drop n) (by rw [hl] at h; simp; omega)
+ have hn : n ≤ bs.length := (Nat.le_add_right _ _).trans (hl ▸ h)
+ let head : Fin n → Bool := fun j => bs[j.val]'(j.isLt.trans_le hn)
+ let d := Function.update tail i head
+ have he : List.ofFn head = bs.take n := by
+ apply List.ext_getElem (by simp [hn])
+ intros
+ simp [head]
+ have same : ChildSlots.bits X u d rest = ChildSlots.bits X u tail rest := by
+ unfold ChildSlots.bits
+ simp only [List.flatMap_def]
+ apply congrArg List.flatten
+ apply List.map_congr_left
+ intro j hj
+ rw [show d j = tail j from Function.update_of_ne
+ (fun (eqn : j = i) => (List.nodup_cons.mp nd).1 (eqn ▸ hj)) ..]
+ refine ⟨d, ?_⟩
+ change (List.ofFn (d i) ++ ChildSlots.bits X u d rest) ++ _ = _
+ rw [show d i = head from Function.update_self .., he, same, hl, List.append_assoc,
+ ← List.drop_drop, ht, List.take_append_drop]
+
+/-- Split off precisely one full child's half-wire packet from an arbitrary tape. -/
+theorem choose_payload (u : X.network.Site) (bs : List Bool)
+ (h : ChildSlots.length X u (ChildSlots.slots (2 ^ a)) ≤ bs.length) :
+ ∃ d : Child X, d.site = u ∧ d.payload X ++ bs.drop (d.payload X).length = bs := by
+ have nd : (ChildSlots.slots (2 ^ a)).Nodup := by
+ rw [ChildSlots.slots, List.nodup_append]
+ refine ⟨List.nodup_ofFn.mpr (fun _ _ e => congrArg Prod.snd e),
+ List.nodup_ofFn.mpr (fun _ _ e => congrArg Prod.snd e), ?_⟩
+ intro x hx y hy he
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hx
+ obtain ⟨j, rfl⟩ := List.mem_ofFn.mp hy
+ cases he
+ obtain ⟨data, hd⟩ := choose_slots X u _ nd bs h
+ let child : Child X := ⟨u, data⟩
+ exact ⟨child, rfl, by rw [Child.payload_length]; exact hd⟩
+
+/-- Actual ordered old-site arguments of a parent term. -/
+noncomputable def children {A : Type*} {t : NetworkKernel.Term A X.network}
+ (v : t.output.Site) (ord : Order (t.Preimage v))
+ (h : NetworkKernel.Placed t.place X.network.Half v) :
+ List (Child X) := List.ofFn fun j => Child.ofHalf X (ord.entries j).val
+ (h (ord.entries j).val (ord.entries j).prop)
+
+variable {X}
+
+/-- Applying native stores for a list of complete child packets. -/
+def storePackets (A : Arena) (qs : List Packet) (priv : Word w → Word w) : Word w → Word w :=
+ qs.foldl (fun prev q => PrivateFields.storeBits (A.base q.node) q.bits prev) priv
+
+private theorem store_congr (dst : ℕ) (bs : List Bool) (f g : Word w → Word w) (x : Word w)
+ (hx : f x = g x) : PrivateFields.storeBits dst bs f x = PrivateFields.storeBits dst bs g x := by
+ induction bs generalizing dst f g with
+ | nil => exact hx
+ | cons b rest ih =>
+ apply ih
+ by_cases he : x = (dst : Word w)
+ · subst x
+ simp
+ · simpa [Function.update_of_ne he] using hx
+
+/-- Projection of the native private memory after all writes is exactly the
+logical scratch update for the list of packets. -/
+theorem scratch_storePackets (A : Arena) (qs : List Packet) (priv : Word w → Word w) :
+ scratch endAddr (storePackets A qs priv) = writePackets A qs (scratch endAddr priv) := by
+ induction qs generalizing priv with
+ | nil => rfl
+ | cons q rest ih =>
+ change scratch endAddr
+ (storePackets A rest (PrivateFields.storeBits (A.base q.node) q.bits priv)) =
+ writePackets A rest (q.write A (scratch endAddr priv))
+ rw [ih]
+ congr 1
+ funext x
+ apply store_congr
+ simp [rawScratch, scratch, x.prop]
+
+end PairSimulation.NodeArguments.ChildScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildPublishedDirectory.lean b/lean/OAI/Computability/VPVNP/PairNodeChildPublishedDirectory.lean
new file mode 100644
index 0000000000..da408d0d63
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildPublishedDirectory.lean
@@ -0,0 +1,192 @@
+import OAI.Computability.VPVNP.CompressorBlockMetadataShrinkReadback
+import OAI.Computability.VPVNP.CompressorRefreshPlacementPacket
+import OAI.Computability.VPVNP.PairNodeChildStage
+import OAI.Computability.VPVNP.PairTraversalControllerInputs
+
+/-!
+# The child decoder's directory in the published DFS level
+
+The retained row base occupies scalar 14. The metadata writer publishes the
+row stride, old degree, argument arena and stride, inverse-incidence pointer
+and width pointer in scalars 15 through 20. These seven consecutive words
+are the operand bank read by the native child header.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildScan
+
+open BurstRAM CompressorRecords BlockMetadata
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem field_address (head : ℕ) (fit : head + 20 < 2 ^ w) (j : Fin 7) :
+ (((head : Word w) + 14) + (j.val : Word w)).val = head + 14 + j.val := by
+ have hj := j.isLt
+ rw [show (14 : Word w) = ((14 : ℕ) : Word w) from rfl, ← Nat.cast_add, ← Nat.cast_add,
+ Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+
+/-- The first six metadata operands after the retained row pointer are the
+six remaining words consumed by the child decoder. -/
+theorem directory_of_payload (m : Memory w) (a older cap slots n oldSites head : ℕ)
+ (T : IncidenceDirectory w) (placement : Placement) (fit : head + 20 < 2 ^ w)
+ (start : m (head + 14) = (older : Word w))
+ (published : ∀ j : Fin 12, m (head + 15 + j.val) =
+ (payload cap slots (2 ^ a) n T.actualIn.val T.width.val oldSites placement j : Word w)) :
+ (directory a older cap ⟨n, frameStride slots n⟩ T).Stored m ((head : Word w) + 14) := by
+ intro j
+ rw [field_address head fit j]
+ cases j using Fin.cases with
+ | zero => exact start
+ | succ j =>
+ have h := published (j.castAdd 6)
+ change m (head + 15 + j.val) = _ at h
+ rw [show head + 14 + j.succ.val = head + 15 + j.val by simp only [Fin.val_succ]; omega, h]
+ fin_cases j <;> simp [payload, directory, ChildHeader.Fields.words]
+
+/-- Later planner and traversal reports may change memory anywhere outside
+these seven words while preserving the decoder's operand bank. -/
+theorem directory_retain {f : ChildHeader.Fields w} {m m' : Memory w} {head : ℕ}
+ (old : f.Stored m ((head : Word w) + 14)) (fit : head + 20 < 2 ^ w)
+ (frame : ∀ i, head + 14 ≤ i → i ≤ head + 20 → m' i = m i) :
+ f.Stored m' ((head : Word w) + 14) := by
+ intro j
+ have addr := field_address head fit j
+ have hj := j.isLt
+ exact (frame _ (by rw [addr]; omega) (by rw [addr]; omega)).trans (old j)
+
+open DescriptorSpace TraversalControllerInputs TraversalRoles
+
+/-- The child handoff's old-level pointer names the retained seven fields in
+the actual traversal memory. The bootstrap supplies the first header and the
+level pitch, and the traversal frame preserves every cell before its rows. -/
+theorem directory_at_locator (L : Layout) (level : Fin L.levels) {pub : Fin 11 → Word w}
+ {src mem : Memory w} {H offset cap : ℕ} {initial : TaggedLayer} {ls : List (Fiber w)}
+ (d : Resident pub mem H (levelStart L 0) (levelWords L) offset cap (endAddress L) initial ls)
+ {f : ChildHeader.Fields w} (old : f.Stored src ((levelStart L level : Word w) + 14))
+ (wide : 21 ≤ levelHeaderWords L) (fit : endAddress L ≤ 2 ^ w)
+ (frame : ∀ i < endAddress L, mem i = src i) :
+ f.Stored mem (levelHead pub mem level + 14) := by
+ have ptr : levelHead pub mem level = (levelStart L level : Word w) := by
+ rw [levelHead, terminal_read d 16 (by decide), terminal_read d 17 (by decide),
+ d.firstHead, d.levelPitch]
+ simp [levelStart]
+ have next := levelStart_mono L level.isLt
+ change levelStart L (level.val + 1) ≤ endAddress L at next
+ have width : levelHeaderWords L ≤ levelWords L := by unfold levelWords; omega
+ have bound : levelStart L level + 20 < endAddress L := by
+ have adv : levelStart L (level.val + 1) = levelStart L level + levelWords L := by
+ simp only [levelStart, Nat.succ_mul, Nat.add_assoc]
+ omega
+ rw [ptr]
+ exact directory_retain old (bound.trans_le fit) fun i _ hi => frame i (hi.trans_lt bound)
+
+end PairSimulation.NodeArguments.ChildScan
+
+namespace CompressorRecords.BlockMetadata
+
+open BurstRAM Compression DescriptorSpace BlockPlanner Schedule ShrinkBlockInputs
+open PairSimulation.NodeArguments PairSimulation.NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+ {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ)
+ (base : Word w) (positions blocks t : ℕ)
+
+local notation "scr" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base
+local notation "pub" => Ports.data pt
+local notation "first" => Script.levelsPerBlock scr * t
+local notation "st" => (levelStart L first : Word w)
+local notation "head" => levelStart L (first + i.val)
+
+private theorem Published.keeps_row_base {step oldSites : ℕ} {role : Role} {fields : Fields}
+ {m : Memory w} {rs : List (Report w)}
+ (P : Published B base positions blocks t step role fields m oldSites rs) :
+ after m (eventLog rs) (levelStart L (first + step) + 14) =
+ m (levelStart L (first + step) + 14) := by
+ have next : levelStart L (first + (step + 1)) = levelStart L (first + step) + levelWords L := by
+ unfold levelStart
+ ring
+ have wide : 66 ≤ levelWords L := by
+ have h : levelHeaderWords L = 66 := rfl
+ simp only [levelWords, h]
+ omega
+ exact P.outside _ (Or.inl (by omega)) (by rw [next]; omega) (by rw [next]; omega)
+
+/-- The actual three selected metadata publications give the child directory
+in their post-memory. Scalar 14 is inherited from the preceding publication. -/
+theorem Published.shrink_child_directory {m : Memory w} {rs : List (Report w)}
+ (P : Published B base positions blocks t i.val .shrink (shrinkFields B i) m
+ (ShrinkPreimages.oldCount X) rs)
+ (header : ShrinkHeaderReads.Header i X T start L first m)
+ (entry : LevelFields.Entry L first pub st m) (termFits : ShrinkInput.termEnd X start 10 < 2 ^ w)
+ (rows : m (pt).rows.val = (directoryRows L : Word w))
+ (n older : ℕ) (nCell : m (levelStart L 0 + 29) = (n : Word w))
+ (rowBase : m (head + 14) = (older : Word w)) :
+ (directory (a i) older B.recordLimit ⟨n, frameStride (slotDegree S) n⟩ T).Stored
+ (after m (eventLog rs)) ((head : Word w) + 14) := by
+ apply directory_of_payload _ _ _ _ _ _ (ShrinkPreimages.oldCount X) _ _
+ (shrinkPlacement i X start) (by have := header.room; omega)
+ · exact (P.keeps_row_base B base positions blocks t).trans rowBase
+ · exact P.shrink_payload B i X T start base positions blocks t header entry termFits rows n nCell
+
+section Refresh
+
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ (Y : State S.portExponent (S.portExponent + g))
+ (c : Compression.Refresh.DyadicRefreshChoice Y S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool)
+
+local notation "lev" => RefreshPlacement.selectedLevel B f hf Y c sel
+local notation "cur" => first + S.steps
+local notation "here" => levelStart L cur
+local notation "U" => packedIncidence L w cur (SelectedLevel.oldSlots lev)
+
+/-- At a refresh the same seven words describe the unique older child. The
+degree comes from the selected refresh scalar, and the two incidence bases
+come from its packed old-level head bank. -/
+theorem Published.refresh_child_directory {m : Memory w} {rs : List (Report w)} {dH : ℕ}
+ (P : Published B base positions blocks t S.steps .refresh (refreshFields B) m Y.positions rs)
+ (entry : LevelFields.Entry L first pub st m)
+ (scalars : LevelFields.Published L cur lev dH m)
+ (pointers : PortRefresh.TraversalHeaders.HeadBank L cur (lev).oldSlots m)
+ (room : here + 66 ≤ 2 ^ w) (rows : m (pt).rows.val = (directoryRows L : Word w))
+ (n older : ℕ) (nCell : m (levelStart L 0 + 29) = (n : Word w))
+ (rowBase : m (here + 14) = (older : Word w)) :
+ (directory S.portExponent older B.recordLimit ⟨n, frameStride (slotDegree S) n⟩ U).Stored
+ (after m (eventLog rs)) ((here : Word w) + 14) := by
+ let table := tableBase L cur (4 : Fin 6)
+ let place : Placement := ⟨Y.positions, table, table + Y.positions, table + 2 * Y.positions, 1⟩
+ obtain ⟨_, count, owner, counts, ids, cap⟩ :=
+ RefreshPlacement.metadata_values B base positions blocks t f hf Y c sel m dH
+ entry scalars pointers room
+ have placed : place.reads (refreshFields B) pub st m := ⟨count, owner, counts, ids, cap⟩
+ have firstHead := BlockHeaderPlan.firstHeader_eval L base m st (Fin.cast_val_eq_self _).symm rows
+ have early := levelStart_mono L (Nat.zero_le (cur))
+ have degree := (LevelFields.eval_scalar entry S.steps 1 (by omega)).trans scalars.degree
+ have col (q : Fin 6) : (LevelFields.incidence (L).shape S.steps q).eval pub st m =
+ ((U).column q).val := by
+ rw [LevelFields.eval_incidence entry, packed_column]
+ · exact (pointers.incidence q).trans (Fin.cast_val_eq_self _).symm
+ · change here + 54 + q.val < 2 ^ w
+ have := q.isLt
+ omega
+ apply directory_of_payload _ _ _ _ _ _ Y.positions _ _ place (by omega)
+ · exact (P.keeps_row_base B base positions blocks t).trans rowBase
+ · intro j
+ exact (P.payload j).trans (field_values B.recordLimit (slotDegree S) (refreshFields B)
+ place firstHead (by omega) nCell degree (LevelFields.eval_dimensions entry scalars).1
+ (col 4) (col 5) placed j)
+
+end Refresh
+
+end CompressorRecords.BlockMetadata
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildScan.lean b/lean/OAI/Computability/VPVNP/PairNodeChildScan.lean
new file mode 100644
index 0000000000..38ad302857
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildScan.lean
@@ -0,0 +1,330 @@
+import OAI.Computability.VPVNP.PairNodeChildLoop
+import OAI.Computability.VPVNP.PairNodeChildPackets
+import OAI.Computability.VPVNP.PairNodeChildAddress
+
+/-!
+# Scanning a parent's actual descriptor children
+
+The same guard, address calculation and slot routine run once per child,
+independent of the row length. The pointer comes from external memory and
+determines both the child's old incidence ordinal and its private buffer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildScan
+
+open BurstRAM BurstRAM.PrivateRAM Compression LocalHistory CompressorRecords DFS
+open scoped Fin.CommRing
+
+variable {w p r k a g : ℕ}
+
+/-- Program counters shared across iterations of a parent’s child scan, together with the
+setup, width lookup and guess counters for each directed slot. -/
+structure Sites (a p : ℕ) where
+ /-- Locations of the three child-count instructions that either exit the scan or decrement
+ the count and enter the address block. -/
+ guard : Fin 3 → Fin p
+ /-- Locations of the seven instructions that fetch the child descriptor pointer, advance the
+ source and calculate the first port and private argument address. -/
+ address : Fin 7 → Fin p
+ /-- Instruction locations for processing each of the 2^a outgoing and 2^a incoming half-wire
+ fields once the child address is known. -/
+ slots : ChildSlots.Sites (2 ^ a) p
+
+/-- The entire body links back to the same guard after all slots of one child. -/
+structure LinkedWith (M : Machine w p r k) (s : Sites a p) (reg : Fin 16 ↪ Fin r)
+ (source : ChildSlots.Names (2 ^ a) r k) (ret : Fin p) : Prop where
+ guard : GuardLinked M s.guard reg (s.address 0) ret
+ address : ChildAddress.Linked M s.address reg
+ (ChildSlots.first s.slots (s.guard 0) (ChildSlots.slots (2 ^ a)))
+ slots : ChildSlots.LinkedWith M s.slots (slotRegs reg) source (s.guard 0)
+ (ChildSlots.slots (2 ^ a))
+
+/-- The linkage interface for public slot-ordinal operands. -/
+structure Linked (M : Machine w p r k) (s : Sites a p) (reg : Fin 16 ↪ Fin r)
+ (port : Fin (2 ^ a) → Fin k) (ret : Fin p) : Prop where
+ guard : GuardLinked M s.guard reg (s.address 0) ret
+ address : ChildAddress.Linked M s.address reg
+ (ChildSlots.first s.slots (s.guard 0) (ChildSlots.slots (2 ^ a)))
+ slots : ChildSlots.Linked M s.slots (slotRegs reg) port (s.guard 0) (ChildSlots.slots (2 ^ a))
+
+theorem Linked.toLinkedWith {M : Machine w p r k} {s : Sites a p} {reg : Fin 16 ↪ Fin r}
+ {port : Fin (2 ^ a) → Fin k} {ret : Fin p} (h : Linked M s reg port ret) :
+ LinkedWith M s reg (.operand port) ret := ⟨h.guard, h.address, h.slots⟩
+
+/-- Register contents common to all children of the parent. -/
+structure Params (reg : Fin 16 ↪ Fin r) (a older cap : ℕ) (A : Arena) (T : IncidenceDirectory w)
+ (c : Config w p r) : Prop where
+ one : c.reg (reg 3) = 1
+ incoming : c.reg (reg 6) = T.actualIn
+ widths : c.reg (reg 7) = T.width
+ olderBase : c.reg (reg 11) = (older : Word w)
+ rowStride : c.reg (reg 12) = ((cap + 2 : ℕ) : Word w)
+ degree : c.reg (reg 13) = ((2 ^ a : ℕ) : Word w)
+ start : c.reg (reg 14) = (A.start : Word w)
+ stride : c.reg (reg 15) = (A.stride : Word w)
+
+/-- Only the slot temporaries, child address operands and loop counters may change. -/
+def mutableRegs (reg : Fin 16 ↪ Fin r) : Finset (Fin r) :=
+ {reg 0, reg 1, reg 2, reg 4, reg 5, reg 8, reg 9, reg 10}
+
+/-- Register preservation across a child scan outside its eight mutable registers. In
+particular the common incidence, row-layout and argument-arena parameters carry into the
+next iteration. -/
+def Frame (reg : Fin 16 ↪ Fin r) (c d : Config w p r) : Prop :=
+ ∀ i, i ∉ mutableRegs reg → d.reg i = c.reg i
+
+private theorem Params.transfer {reg : Fin 16 ↪ Fin r} {a older cap : ℕ} {A : Arena}
+ {T : IncidenceDirectory w} {c d : Config w p r} (h : Params reg a older cap A T c)
+ (frame : Frame reg c d) : Params reg a older cap A T d := by
+ constructor <;> first
+ | exact (frame _ (by simp [mutableRegs])).trans h.one
+ | exact (frame _ (by simp [mutableRegs])).trans h.incoming
+ | exact (frame _ (by simp [mutableRegs])).trans h.widths
+ | exact (frame _ (by simp [mutableRegs])).trans h.olderBase
+ | exact (frame _ (by simp [mutableRegs])).trans h.rowStride
+ | exact (frame _ (by simp [mutableRegs])).trans h.degree
+ | exact (frame _ (by simp [mutableRegs])).trans h.start
+ | exact (frame _ (by simp [mutableRegs])).trans h.stride
+
+variable {M : Machine w p r k} {s : Sites a p} {reg : Fin 16 ↪ Fin r}
+variable {source : ChildSlots.Names (2 ^ a) r k} {port : Fin (2 ^ a) → Fin k}
+variable {ret : Fin p} {m : Memory w}
+variable {X : State a g} {T : IncidenceDirectory w} {A : Arena} {older cap : ℕ}
+
+/-- The source row, all old node pointers, and all destination fields fit in the word arena. -/
+structure Ready (m : Memory w) (X : State a g) (A : Arena) (older cap src : ℕ)
+ (xs : List (Child X)) : Prop where
+ endFit : src + xs.length < 2 ^ w
+ strideFit : cap + 2 < 2 ^ w
+ cells : ∀ i : Fin xs.length, m (src + i.val) = (childNode X older cap xs[i].site : Word w)
+ nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w
+ packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w
+
+private theorem Ready.tail {x : Child X} {xs : List (Child X)} {src : ℕ}
+ (h : Ready m X A older cap src (x :: xs)) : Ready m X A older cap (src + 1) xs := by
+ refine ⟨by simpa [Nat.add_assoc, Nat.add_comm 1] using h.endFit, h.strideFit, fun i => ?_,
+ fun v hv => h.nodes v (List.mem_cons_of_mem _ hv),
+ fun v hv => h.packets v (List.mem_cons_of_mem _ hv)⟩
+ simpa only [Fin.getElem_fin, Fin.val_succ, List.getElem_cons_succ, Nat.add_assoc, Nat.add_comm 1]
+ using h.cells i.succ
+
+/-- Specialize the bounds to the actual DFS row read by the parent. -/
+theorem ready_of_row {xs : List (Child X)} {node src : ℕ}
+ (hr : Row m node src (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w) :
+ Ready m X A older cap src xs := by
+ refine ⟨by simpa using hr.2.1, strideFit, fun i => ?_, nodes, packets⟩
+ simpa using hr.2.2.2.2 ⟨i.val, by simp⟩
+
+/-- Trace before the first slot of a live child. Three guard ticks precede the external read at
+src and the six ticks of address arithmetic. -/
+def setupEvents (m : Memory w) (src : ℕ) : List (Event w) :=
+ [.tick, .tick, .tick] ++ ChildAddress.events m (src : Word w)
+
+/-- Execute the guard and actual directory-pointer calculation for one live child. -/
+private theorem enter {x : Child X} {xs : List (Child X)} {src : ℕ}
+ (hl : LinkedWith M s reg source ret)
+ (h : Ready m X A older cap src (x :: xs)) (c : Config w p r) (hc : c.pc = s.guard 0)
+ (hp : c.reg (reg 9) = (src : Word w)) (hn : c.reg (reg 10) = ((xs.length + 1 : ℕ) : Word w))
+ (par : Params reg a older cap A T c) :
+ let node := childNode X older cap x.site
+ ∃ d, d.pc = ChildSlots.first s.slots (s.guard 0) (ChildSlots.slots (2 ^ a)) ∧
+ d.reg (reg 2) = (A.base node : Word w) ∧
+ d.reg (reg 8) = IncidenceDirectory.actualPort X (x.site, 0) ∧
+ d.reg (reg 9) = ((src + 1 : ℕ) : Word w) ∧ d.reg (reg 10) = (xs.length : Word w) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧ Frame reg c d ∧
+ Prefix M m c d [] (setupEvents m src) := by
+ intro node
+ have srcFit : src < 2 ^ w := (Nat.le_add_right _ _).trans_lt h.endFit
+ have countFit : xs.length + 1 < 2 ^ w := (Nat.le_add_left _ _).trans_lt h.endFit
+ obtain ⟨c₁, pc₁, mem₁, state₁, n₁, keep₁, pre₁⟩ := guard_cons hl.guard c hc xs.length
+ countFit hn par.one m
+ have frame₁ : Frame reg c c₁ := by
+ intro i hi
+ simp only [mutableRegs, Finset.mem_insert, Finset.mem_singleton, not_or] at hi
+ exact keep₁ i hi.1 hi.2.2.2.2.2.2.2
+ have par₁ := par.transfer frame₁
+ have ptr₁ : c₁.reg (reg 9) = (src : Word w) :=
+ (keep₁ _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans hp
+ obtain ⟨d, pc₂, dst, first, ptr₂, keep₂, mem₂, state₂, pre₂⟩ := ChildAddress.native hl.address m
+ c₁ pc₁ par₁.one
+ have stored : m (c₁.reg (reg 9)).val = (node : Word w) := by
+ rw [ptr₁, Fin.val_natCast, Nat.mod_eq_of_lt srcFit]
+ simpa [node] using h.cells ⟨0, Nat.zero_lt_succ _⟩
+ have nodeFit := h.nodes x List.mem_cons_self
+ have olderFit : older < 2 ^ w := (Nat.le_add_right older _).trans_lt nodeFit
+ have numeric : (node : Word w).val = (older : Word w).val +
+ ((cap + 2 : ℕ) : Word w).val * ((siteOrder X).entries.symm x.site).val := by
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt nodeFit, Fin.val_natCast, Nat.mod_eq_of_lt olderFit,
+ Fin.val_natCast, Nat.mod_eq_of_lt h.strideFit]
+ rfl
+ have rowPos : 0 < ((cap + 2 : ℕ) : Word w).val := by
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt h.strideFit]
+ omega
+ refine ⟨d, pc₂, ?_, ?_, ?_, (keep₂ _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))
+ (reg.injective.ne (by decide))).trans n₁, mem₂.trans mem₁, state₂.trans state₁, ?_, ?_⟩
+ · rw [dst, stored, par₁.start, par₁.stride]
+ simp only [Arena.base, Nat.cast_add, Nat.cast_mul]
+ · rw [first, stored, par₁.olderBase, par₁.rowStride, par₁.degree]
+ exact ChildAddress.firstPort_eq X x.site _ _ _ numeric rowPos
+ · rw [ptr₂, ptr₁, Nat.cast_add, Nat.cast_one]
+ · intro i hi
+ have notMem := hi
+ simp only [mutableRegs, Finset.mem_insert, Finset.mem_singleton, not_or] at notMem
+ exact (keep₂ i notMem.2.2.1 notMem.2.2.2.2.2.1 notMem.2.2.2.2.2.2.1).trans (frame₁ i hi)
+ · have h₂ : Prefix M m c₁ d [] (ChildAddress.events m (src : Word w)) := by
+ intro fuel bs
+ simpa only [ptr₁, List.nil_append, ChildAddress.events, List.length_cons, List.length_nil]
+ using pre₂ fuel bs
+ exact pre₁.trans h₂
+
+private theorem names_frame {c d : Config w p r} (valid : source.Valid M c)
+ (apart : source.Apart reg) (frame : Frame reg c d) : source.Valid M d :=
+ valid.transfer apart fun i hi => frame i (by
+ simp only [mutableRegs, Finset.mem_insert, Finset.mem_singleton, not_or]
+ exact ⟨hi 0, hi 1, hi 2, hi 4, hi 5, hi 8, hi 9, hi 10⟩)
+
+private theorem slots_apart (h : source.Apart reg) : source.Apart (slotRegs reg) := by
+ cases source with
+ | operand => trivial
+ | bank b => exact fun i j => h i (j.castAdd 7)
+
+/-- One complete child, with its outgoing slots followed by its incoming slots. -/
+noncomputable def childEvents (X : State a g) (T : IncidenceDirectory w) (m : Memory w)
+ (src : ℕ) (x : Child X) : List (Event w) :=
+ setupEvents m src ++ ChildSlots.events X x.site T m x.data (ChildSlots.slots (2 ^ a))
+
+private theorem step {x : Child X} {xs : List (Child X)} {src : ℕ}
+ (hl : LinkedWith M s reg source ret)
+ (apart : source.Apart reg) (rep : T.ActualColumns X m)
+ (h : Ready m X A older cap src (x :: xs)) (c : Config w p r) (names : source.Valid M c)
+ (hc : c.pc = s.guard 0)
+ (hp : c.reg (reg 9) = (src : Word w)) (hn : c.reg (reg 10) = ((xs.length + 1 : ℕ) : Word w))
+ (par : Params reg a older cap A T c) :
+ ∃ d, d.pc = s.guard 0 ∧ d.reg (reg 9) = ((src + 1 : ℕ) : Word w) ∧
+ d.reg (reg 10) = (xs.length : Word w) ∧
+ d.privateMem = PrivateFields.storeBits (A.base (childNode X older cap x.site))
+ (x.payload X) c.privateMem ∧ d.persistent = c.persistent ∧ Frame reg c d ∧
+ Prefix M m c d (x.payload X) (childEvents X T m src x) := by
+ obtain ⟨d, hd, dst, first, ptr, count, mem, state, keep, pre⟩ := enter hl h c hc hp hn par
+ have par' := par.transfer keep
+ have fit := h.packets x List.mem_cons_self
+ rw [Child.payload_length] at fit
+ obtain ⟨out, ho, memory, persistent, _, frame, run⟩ := ChildSlots.scanWith _ hl.slots
+ (slots_apart apart) rep x.data _ fit d (names_frame names apart keep) hd dst par'.one
+ par'.incoming par'.widths first
+ have keeps (i : Fin 16) (h₀ : i ≠ 0) (h₁ : i ≠ 1) (h₂ : i ≠ 2) (h₄ : i ≠ 4) (h₅ : i ≠ 5) :
+ out.reg (reg i) = d.reg (reg i) :=
+ frame _ (reg.injective.ne h₀) (reg.injective.ne h₁) (reg.injective.ne h₂)
+ (reg.injective.ne h₄) (reg.injective.ne h₅)
+ refine ⟨out, ho, (keeps 9 (by decide) (by decide) (by decide) (by decide) (by decide)).trans ptr,
+ (keeps 10 (by decide) (by decide) (by decide) (by decide) (by decide)).trans count,
+ memory.trans (congrArg _ mem), persistent.trans state, ?_, pre.trans run⟩
+ intro i hi
+ have hnot := hi
+ simp only [mutableRegs, Finset.mem_insert, Finset.mem_singleton, not_or] at hnot
+ exact (frame i hnot.1 hnot.2.1 hnot.2.2.1 hnot.2.2.2.1 hnot.2.2.2.2.1).trans (keep i hi)
+
+/-- The chosen local instruction trace includes one empty-row exit. -/
+noncomputable def events (X : State a g) (T : IncidenceDirectory w) (m : Memory w) :
+ ℕ → List (Child X) → List (Event w)
+ | _, [] => [.tick, .tick]
+ | src, x :: xs => childEvents X T m src x ++ events X T m (src + 1) xs
+
+/-- Execute the full native row, preserving the continuation's entire choice
+suffix and preparing precisely the logical ordered list of argument packets. -/
+theorem scanWith (hl : LinkedWith M s reg source ret) (apart : source.Apart reg)
+ (rep : T.ActualColumns X m) (src : ℕ) (xs : List (Child X)) (h : Ready m X A older cap src xs)
+ (c : Config w p r) (names : source.Valid M c)
+ (hc : c.pc = s.guard 0) (hp : c.reg (reg 9) = (src : Word w))
+ (hn : c.reg (reg 10) = (xs.length : Word w)) (par : Params reg a older cap A T c) :
+ let qs := xs.map (Child.packet X older cap)
+ ∃ d, d.pc = ret ∧ d.privateMem = storePackets A qs c.privateMem ∧ d.persistent = c.persistent ∧
+ Frame reg c d ∧ Prefix M m c d (qs.flatMap Packet.bits) (events X T m src xs) := by
+ induction xs generalizing c src with
+ | nil =>
+ obtain ⟨d, hd, mem, state, keep, pre⟩ := guard_empty hl.guard c hc (by simpa using hn) m
+ exact ⟨d, hd, mem, state, fun i hi => keep i (fun eqn => hi (by simp [mutableRegs, eqn])), pre⟩
+ | cons x xs ih =>
+ obtain ⟨mid, hm, ptr, count, mem, state, keep, pre⟩ := step hl apart rep h c names hc hp hn par
+ obtain ⟨d, hd, mem', state', keep', more⟩ := ih (src + 1) h.tail mid
+ (names_frame names apart keep) hm ptr count (par.transfer keep)
+ refine ⟨d, hd, mem'.trans (congrArg _ mem), state'.trans state, fun i hi =>
+ (keep' i hi).trans (keep i hi), pre.trans more⟩
+
+theorem scan (hl : Linked M s reg port ret) (names : ∀ j, M.publicData (port j) = (j.val : Word w))
+ (rep : T.ActualColumns X m) (src : ℕ) (xs : List (Child X)) (h : Ready m X A older cap src xs)
+ (c : Config w p r) (hc : c.pc = s.guard 0) (hp : c.reg (reg 9) = (src : Word w))
+ (hn : c.reg (reg 10) = (xs.length : Word w)) (par : Params reg a older cap A T c) :
+ let qs := xs.map (Child.packet X older cap)
+ ∃ d, d.pc = ret ∧ d.privateMem = storePackets A qs c.privateMem ∧ d.persistent = c.persistent ∧
+ Frame reg c d ∧ Prefix M m c d (qs.flatMap Packet.bits) (events X T m src xs) :=
+ scanWith hl.toLinkedWith trivial rep src xs h c names hc hp hn par
+
+private theorem Ready.replace {x z : Child X} {xs : List (Child X)} {src : ℕ}
+ (h : Ready m X A older cap src (x :: xs)) (hz : z.site = x.site) :
+ Ready m X A older cap src (z :: xs) := by
+ refine ⟨h.endFit, h.strideFit, fun i => ?_, fun j hj => ?_, fun j hj => ?_⟩
+ · cases i using Fin.cases with
+ | zero => simpa [hz] using h.cells ⟨0, Nat.zero_lt_succ _⟩
+ | succ j => exact h.cells j.succ
+ · rcases List.mem_cons.mp hj with rfl | hm
+ · simpa [hz] using h.nodes x List.mem_cons_self
+ · exact h.nodes j (List.mem_cons_of_mem _ hm)
+ · rcases List.mem_cons.mp hj with rfl | hm
+ · simpa only [Child.payload_length, hz] using h.packets x List.mem_cons_self
+ · exact h.packets j (List.mem_cons_of_mem _ hm)
+
+/-- An incomplete argument tape cannot return. This includes a short field
+in a later child after all earlier guessed packets have been written. -/
+theorem reject_shortWith (hl : LinkedWith M s reg source ret)
+ (apart : source.Apart reg) (rep : T.ActualColumns X m)
+ (src : ℕ) (xs : List (Child X)) (h : Ready m X A older cap src xs)
+ (c : Config w p r) (names : source.Valid M c)
+ (hc : c.pc = s.guard 0) (hp : c.reg (reg 9) = (src : Word w))
+ (hn : c.reg (reg 10) = (xs.length : Word w)) (par : Params reg a older cap A T c)
+ (bs : List Bool) (short : bs.length < (xs.flatMap (Child.payload X)).length) :
+ ¬ Returns M c m bs := by
+ induction xs generalizing c src bs with
+ | nil => simp at short
+ | cons x xs ih =>
+ let n := (x.payload X).length
+ have hl' : bs.length < n + (xs.flatMap (Child.payload X)).length := by simpa [n] using short
+ by_cases full : n ≤ bs.length
+ · obtain ⟨v, hv, tape⟩ := choose_payload X x.site bs ((Child.payload_length X x) ▸ full)
+ obtain ⟨mid, hm, ptr, count, _, _, keep, run⟩ :=
+ step hl apart rep (h.replace hv) c names hc hp hn par
+ have len : (v.payload X).length = n := by simp [n, Child.payload_length, hv]
+ have later := ih (src + 1) h.tail mid (names_frame names apart keep) hm ptr count
+ (par.transfer keep) (bs.drop n) (by simp only [List.length_drop]; omega)
+ intro accepted
+ rw [← tape] at accepted
+ exact later (len ▸ (run.returns _).mp accepted)
+ · obtain ⟨mid, hm, dst, first, _, _, _, _, keep, run⟩ := enter hl h c hc hp hn par
+ have par' := par.transfer keep
+ have fit := h.packets x List.mem_cons_self
+ rw [Child.payload_length] at fit
+ have short' := (Nat.lt_of_not_ge full).trans_eq (Child.payload_length X x)
+ exact fun accept => ChildSlots.reject_shortWith _ hl.slots (slots_apart apart) rep _ fit
+ mid (names_frame names apart keep) hm dst par'.one par'.incoming par'.widths first
+ bs short' ((run.returns bs).mp accept)
+
+theorem reject_short (hl : Linked M s reg port ret)
+ (names : ∀ j, M.publicData (port j) = (j.val : Word w)) (rep : T.ActualColumns X m)
+ (src : ℕ) (xs : List (Child X)) (h : Ready m X A older cap src xs)
+ (c : Config w p r) (hc : c.pc = s.guard 0) (hp : c.reg (reg 9) = (src : Word w))
+ (hn : c.reg (reg 10) = (xs.length : Word w)) (par : Params reg a older cap A T c)
+ (bs : List Bool) (short : bs.length < (xs.flatMap (Child.payload X)).length) :
+ ¬ Returns M c m bs :=
+ reject_shortWith hl.toLinkedWith trivial rep src xs h c names hc hp hn par bs short
+
+end PairSimulation.NodeArguments.ChildScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildScanCost.lean b/lean/OAI/Computability/VPVNP/PairNodeChildScanCost.lean
new file mode 100644
index 0000000000..4625fa5d48
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildScanCost.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.PairNodeChildScan
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-!
+# Work of the child argument scan
+
+Every old port requires one width probe. Each incoming port also requires
+one inverse-incidence probe. Each guessed bit uses six local instructions.
+The row scan adds one descriptor probe and ten instructions per child and
+two final exit instructions, including for an empty row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildScan
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords
+open PrimedInputRAM.Flow (choiceBits_append)
+
+variable {w a g : ℕ} (X : State a g) (T : IncidenceDirectory w) (m : Memory w)
+
+private def slotProbes {n : ℕ} (i : Bool × Fin n) : ℕ := if i.1 then 2 else 1
+private def slotWork {n : ℕ} (i : Bool × Fin n) : ℕ := if i.1 then 8 else 7
+
+private theorem slots_cost (x : Child X) (slots : List (Bool × Fin (2 ^ a))) :
+ let es := ChildSlots.events X x.site T m x.data slots
+ let bs := ChildSlots.bits X x.site x.data slots
+ choiceBits es = bs ∧ countProbes es = (slots.map slotProbes).sum ∧
+ es.length = (slots.map slotWork).sum + 6 * bs.length := by
+ induction slots with
+ | nil => exact ⟨rfl, rfl, rfl⟩
+ | cons i slots ih =>
+ have hdr := FieldGuess.header_cost T m i.1 (IncidenceDirectory.actualPort X (x.site, i.2))
+ have guess := PrivateFields.events_work (w := w) .guess (List.ofFn (x.data i))
+ have bits := PrivateFields.events_bits (w := w) .guess (List.ofFn (x.data i))
+ simp only [ChildSlots.events, ChildSlots.bits, List.flatMap_cons, choiceBits_append,
+ BurstRAM.countProbes_append, List.length_append, List.map_cons, List.sum_cons,
+ hdr.2.2, hdr.1, hdr.2.1, guess.2, guess.1, bits, List.length_cons,
+ List.length_nil] at *
+ change _ = _ ∧ _ = _ ∧ _ = _
+ obtain ⟨ihb, ihp, ihw⟩ := ih
+ rw [ihb, ihp, ihw]
+ by_cases hi : i.1 = true <;> simp [choiceBits, countProbes, slotProbes, slotWork, hi] <;> omega
+
+private theorem one_cost (src : ℕ) (x : Child X) :
+ let es := childEvents X T m src x
+ choiceBits es = x.payload X ∧ countProbes es = 1 + 3 * 2 ^ a ∧
+ es.length = 10 + 15 * 2 ^ a + 6 * (x.payload X).length := by
+ have h := slots_cost X T m x (ChildSlots.slots (2 ^ a))
+ have p : ((ChildSlots.slots (2 ^ a)).map slotProbes).sum = 3 * 2 ^ a := by
+ simp [ChildSlots.slots, List.map_ofFn, Function.comp_def, slotProbes]
+ omega
+ have v : ((ChildSlots.slots (2 ^ a)).map slotWork).sum = 15 * 2 ^ a := by
+ simp [ChildSlots.slots, List.map_ofFn, Function.comp_def, slotWork]
+ omega
+ have setup : choiceBits (setupEvents m src) = [] ∧ countProbes (setupEvents m src) = 1 ∧
+ (setupEvents m src).length = 10 := ⟨rfl, rfl, rfl⟩
+ simp only [childEvents, choiceBits_append, BurstRAM.countProbes_append, List.length_append,
+ setup.1, setup.2.1, setup.2.2, List.nil_append, h.1, h.2.1, h.2.2, p, v, Child.payload,
+ Nat.add_assoc, and_self]
+
+/-- Exact guessed bits, probes, and instructions of the native scan. These
+counts include the exit after the last child. -/
+theorem events_cost (src : ℕ) (xs : List (Child X)) :
+ let es := events X T m src xs
+ let bs := xs.flatMap (Child.payload X)
+ choiceBits es = bs ∧ countProbes es = (1 + 3 * 2 ^ a) * xs.length ∧
+ es.length = (10 + 15 * 2 ^ a) * xs.length + 6 * bs.length + 2 := by
+ induction xs generalizing src with
+ | nil => exact ⟨rfl, by simp [events, countProbes], by simp [events]⟩
+ | cons x xs ih =>
+ have h := one_cost X T m src x
+ obtain ⟨hb, hp, hw⟩ := ih (src + 1)
+ simp only [events, List.flatMap_cons, choiceBits_append, BurstRAM.countProbes_append,
+ List.length_append, List.length_cons, h.1, h.2.1, h.2.2, hb, hp, hw, Nat.mul_add, Nat.mul_one]
+ exact ⟨trivial, by omega, by omega⟩
+
+end PairSimulation.NodeArguments.ChildScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildSegment.lean b/lean/OAI/Computability/VPVNP/PairNodeChildSegment.lean
new file mode 100644
index 0000000000..6cb3e2d582
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildSegment.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.PairNodeChildImmediate
+import OAI.Computability.VPVNP.PairVertexImage
+
+/-!
+# The child-argument block in the final vertex image
+
+A single finite label space contains the slot initializer followed by the
+parent header and the complete child loop. Its first sixteen private registers
+serve the argument scan. The remaining registers form its private ordinal bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildCode.RegisterBank
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {a p r w : ℕ}
+
+/-- First interval of the combined labels. -/
+def initPC (pc : Fin (2 ^ a + size a) → Fin p) (i : Fin (2 ^ a)) : Fin p :=
+ pc (i.castAdd (size a))
+
+/-- Second interval, using the child code's established label order. -/
+def loc (pc : Fin (2 ^ a + size a) → Fin p) (j : Label a) : Fin p :=
+ pc ((number a j).natAdd (2 ^ a))
+
+/-- The first sixteen private registers of the child-argument segment, used to scan the
+children and assemble their arguments. -/
+def regs (prv : Fin (16 + 2 ^ a) ↪ Fin r) : Fin 16 ↪ Fin r := (Fin.castAddEmb (2 ^ a)).trans prv
+
+/-- The final `2 ^ a` private registers of the child-argument segment, one for the ordinal of
+each port slot. -/
+def bank (prv : Fin (16 + 2 ^ a) ↪ Fin r) : Fin (2 ^ a) ↪ Fin r := (Fin.natAddEmb 16).trans prv
+
+theorem bank_apart (prv : Fin (16 + 2 ^ a) ↪ Fin r) (i : Fin (2 ^ a)) (j : Fin 16) :
+ bank prv i ≠ regs prv j := by
+ apply prv.injective.ne
+ intro eqn
+ have hv := congrArg Fin.val eqn
+ change 16 + i.val = j.val at hv
+ have hj := j.isLt
+ omega
+
+/-- An eleven-operand segment with five-bit literals, ready to embed in a
+shrink or refresh handler at an arbitrary supplied continuation. -/
+def segment (a : ℕ) : VertexImage.Segment where
+ count := 2 ^ a + size a
+ privateRegs := 16 + 2 ^ a
+ entry := (0 : Fin (2 ^ a)).castAdd (size a)
+ row pc _ _ prv done := Fin.addCases
+ (ChildBankInit.instruction (initPC pc) (bank prv) (headerPC (loc pc) 0))
+ (fun i => instruction (loc pc) (regs prv) (bank prv) done ((number a).symm i))
+
+/-- A host containing the segment satisfies the two code hypotheses of the
+complete success and short-tape rejection theorems. -/
+theorem segment_linked (M : Machine w p r 11) (pc : Fin (segment a).count → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (prv : Fin (segment a).privateRegs ↪ Fin r) (done : Fin p)
+ (code : ∀ i, M.code (pc i) = ((segment a).row pc dfs saved prv done i).resize w) :
+ ChildBankInit.Linked M (initPC pc) (bank prv) (headerPC (loc pc) 0) ∧
+ ∀ j, M.code (loc pc j) = instruction (loc pc) (regs prv) (bank prv) done j := by
+ constructor
+ · intro i
+ apply (code (i.castAdd (size a))).trans
+ simp only [segment, Fin.addCases_left, ChildBankInit.resize_instruction]
+ · intro j
+ apply (code ((number a j).natAdd (2 ^ a))).trans
+ simp only [segment, Fin.addCases_right, Equiv.symm_apply_apply, resize_instruction]
+
+end PairSimulation.NodeArguments.ChildCode.RegisterBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildSlots.lean b/lean/OAI/Computability/VPVNP/PairNodeChildSlots.lean
new file mode 100644
index 0000000000..1c96a96406
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildSlots.lean
@@ -0,0 +1,342 @@
+import OAI.Computability.VPVNP.PairNodeFieldGuess
+
+/-!
+# Filling all half-wire arguments of a child
+
+A finite scan enters the width and guess block at each of the old site's
+outgoing slots, then its incoming slots. The fixed slot ordinal is added
+to the first physical port. The destination cursor advances by the width
+actually read at that port. The scan consumes exactly the semantic child
+payload and leaves it in one private interval.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildSlots
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords LocalHistory
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+open private returns_prefix from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+variable {w p r k a g : ℕ}
+
+/-- The first physical port of an old site is kept in register 8. -/
+def guessRegs (reg : Fin 9 ↪ Fin r) : Fin 8 ↪ Fin r := (Fin.castAddEmb 1).trans reg
+
+/-- Addresses of the instructions that compute the physical port, look up the field width, and
+guess the field bits for each directed child slot. -/
+structure Sites (n p : ℕ) where
+ /-- The two instruction addresses that load the slot ordinal and add it to the site's first
+ physical port. -/
+ setup : Bool × Fin n → Fin 2 → Fin p
+ /-- The six instruction addresses for the width lookup, including the inverse-incidence
+ lookup on incoming slots. -/
+ header : Bool × Fin n → Fin 6 → Fin p
+ /-- The seven instruction addresses for guessing the slot's field and writing its bits to
+ consecutive private cells. -/
+ guess : Bool × Fin n → Fin 7 → Fin p
+
+/-- Entry address of the first slot's setup block, or the supplied return address for an empty
+slot list. -/
+def first {n : ℕ} (s : Sites n p) (ret : Fin p) : List (Bool × Fin n) → Fin p
+ | [] => ret
+ | i :: _ => s.setup i 0
+
+/-- Slot names can be read from a public operand or from a previously
+initialized bank of private registers. Both reads take one local instruction. -/
+inductive Names (n r k : ℕ) where
+ | operand (port : Fin n → Fin k)
+ | bank (register : Fin n → Fin r)
+
+/-- The instruction that loads slot `j`'s ordinal into `dst` from its public operand or private
+register and continues at `next`. -/
+def Names.load {n : ℕ} (source : Names n r k) (j : Fin n) (dst : Fin r)
+ (next : Fin p) : Instr w p r k :=
+ match source with
+ | .operand port => .publicWord dst (port j) next
+ | .bank register => .copy dst (register j) next
+
+/-- Every slot-name source holds its slot ordinal as a machine word in the public data or the
+current register file. -/
+def Names.Valid {n : ℕ} (source : Names n r k) (M : Machine w p r k)
+ (c : Config w p r) : Prop :=
+ match source with
+ | .operand port => ∀ j, M.publicData (port j) = (j.val : Word w)
+ | .bank register => ∀ j, c.reg (register j) = (j.val : Word w)
+
+/-- The private slot-name bank is disjoint from the working registers. Public slot names impose
+no register condition. -/
+def Names.Apart {n d : ℕ} (source : Names n r k) (reg : Fin d ↪ Fin r) : Prop :=
+ match source with
+ | .operand _ => True
+ | .bank register => ∀ i j, register i ≠ reg j
+
+theorem Names.Valid.transfer {n d : ℕ} {source : Names n r k} {reg : Fin d ↪ Fin r}
+ {M : Machine w p r k} {c z : Config w p r} (h : source.Valid M c)
+ (apart : source.Apart reg) (frame : ∀ i, (∀ j, i ≠ reg j) → z.reg i = c.reg i) :
+ source.Valid M z := by
+ cases source with
+ | operand => exact h
+ | bank b => exact fun j => (frame (b j) (apart j)).trans (h j)
+
+/-- Load the slot ordinal, add the site's first physical port, then enter the outgoing or
+incoming width lookup according to the slot direction. -/
+def setupWith {n : ℕ} (s : Sites n p) (reg : Fin 9 ↪ Fin r) (source : Names n r k)
+ (i : Bool × Fin n) : Fin 2 → Instr w p r k :=
+ ![source.load i.2 (reg 5) (s.setup i 1),
+ .binary .add (reg 5) (reg 8) (reg 5) (FieldGuess.entry (s.header i) i.1)]
+
+/-- The public-operand version of the two slot setup instructions. -/
+abbrev setup {n : ℕ} (s : Sites n p) (reg : Fin 9 ↪ Fin r) (port : Fin n → Fin k)
+ (i : Bool × Fin n) : Fin 2 → Instr w p r k := setupWith s reg (.operand port) i
+
+theorem resize_setupWith {n : ℕ} (s : Sites n p) (reg : Fin 9 ↪ Fin r) (source : Names n r k)
+ (i : Bool × Fin n) (j : Fin 2) : (setupWith (w := 1) s reg source i j).resize w =
+ setupWith s reg source i j := by cases source <;> fin_cases j <;> rfl
+
+theorem resize_setup {n : ℕ} (s : Sites n p) (reg : Fin 9 ↪ Fin r) (port : Fin n → Fin k)
+ (i : Bool × Fin n) (j : Fin 2) : (setup (w := 1) s reg port i j).resize w =
+ setup s reg port i j := resize_setupWith ..
+
+/-- The machine links each listed slot's address setup, width lookup, and field guess in
+sequence and passes control to `ret` after the last slot. -/
+def LinkedWith {n : ℕ} (M : Machine w p r k) (s : Sites n p) (reg : Fin 9 ↪ Fin r)
+ (source : Names n r k) (ret : Fin p) : List (Bool × Fin n) → Prop
+ | [] => True
+ | i :: rest => (∀ j, M.code (s.setup i j) = setupWith s reg source i j) ∧
+ FieldGuess.Linked M (s.header i) (guessRegs reg) (s.guess i 0) ∧
+ PrivateFields.Linked M .guess (s.guess i) (FieldGuess.fieldRegs (guessRegs reg))
+ (first s ret rest) ∧ LinkedWith M s reg source ret rest
+
+/-- The slot scan is linked through its return address with slot ordinals supplied by public
+operands. -/
+abbrev Linked {n : ℕ} (M : Machine w p r k) (s : Sites n p) (reg : Fin 9 ↪ Fin r)
+ (port : Fin n → Fin k) (ret : Fin p) := LinkedWith M s reg (.operand port) ret
+
+/-- Total semantic field length in the specified part of the scan. -/
+noncomputable def length (X : State a g) (u : X.network.Site)
+ (slots : List (Bool × Fin (2 ^ a))) : ℕ :=
+ (slots.map fun i ↦ X.halfWidth u i.1 i.2).sum
+
+/-- The guessed half-wire bits concatenated in the given slot order, with each field listed in
+increasing bit index. -/
+noncomputable def bits (X : State a g) (u : X.network.Site)
+ (data : (i : Bool × Fin (2 ^ a)) → Fin (X.halfWidth u i.1 i.2) → Bool)
+ (slots : List (Bool × Fin (2 ^ a))) : List Bool := slots.flatMap fun i ↦ List.ofFn (data i)
+
+/-- The scan trace in slot order, recording two address-setup ticks, the incidence and width
+lookup events for the slot direction, and the private field guess. -/
+noncomputable def events (X : State a g) (u : X.network.Site) (T : IncidenceDirectory w)
+ (m : Memory w) (data : (i : Bool × Fin (2 ^ a)) → Fin (X.halfWidth u i.1 i.2) → Bool)
+ (slots : List (Bool × Fin (2 ^ a))) : List (Event w) := slots.flatMap fun i ↦
+ [.tick,.tick] ++ FieldGuess.headerEvents T m i.1 (IncidenceDirectory.actualPort X (u, i.2)) ++
+ PrivateFields.events .guess (List.ofFn (data i))
+
+private theorem append_store (dst : ℕ) (xs ys : List Bool) (mem : Word w → Word w) :
+ PrivateFields.storeBits dst (xs ++ ys) mem =
+ PrivateFields.storeBits (dst+xs.length) ys (PrivateFields.storeBits dst xs mem) := by
+ induction xs generalizing dst mem with
+ | nil => simp [PrivateFields.storeBits]
+ | cons x xs ih => simp [PrivateFields.storeBits, ih, Nat.add_assoc, Nat.add_comm 1]
+
+private theorem physical_port (X : State a g) (u : X.network.Site) (j : Fin (2 ^ a)) :
+ IncidenceDirectory.actualPort (w := w) X (u, 0) + (j.val : Word w) =
+ IncidenceDirectory.actualPort X (u,j) := by
+ change ((_:ℕ) : Word w) + _ = ((_:ℕ) : Word w)
+ simp
+
+variable {X : State a g} {u : X.network.Site} {T : IncidenceDirectory w} {m : Memory w}
+variable {M : Machine w p r k} {s : Sites (2 ^ a) p} {reg : Fin 9 ↪ Fin r}
+variable {port : Fin (2 ^ a) → Fin k} {source : Names (2 ^ a) r k} {ret : Fin p}
+
+private theorem address_prefix (i : Bool × Fin (2 ^ a))
+ (code : ∀ j, M.code (s.setup i j) = setupWith s reg source i j)
+ (c : Config w p r) (names : source.Valid M c) (hc : c.pc = s.setup i 0)
+ (hp : c.reg (reg 8) = IncidenceDirectory.actualPort X (u, 0)) :
+ ∃ d, d.pc = FieldGuess.entry (s.header i) i.1 ∧
+ d.reg (reg 5) = IncidenceDirectory.actualPort X (u, i.2) ∧
+ (∀ j, j ≠ reg 5 → d.reg j = c.reg j) ∧ d.privateMem = c.privateMem ∧
+ d.persistent = c.persistent ∧ ReadPrefix M m c [.tick,.tick] d := by
+ let c₁ := c.put (s.setup i 1) (reg 5) (i.2.val : Word w)
+ let d := c₁.put (FieldGuess.entry (s.header i) i.1) (reg 5)
+ (IncidenceDirectory.actualPort X (u, i.2))
+ have h₀ : M.program.step c = .localStep c₁ := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl,hc,code]
+ cases source with
+ | operand pt =>
+ change CallAction.localStep (c.put _ _ (M.publicData (pt i.2))) = _
+ rw [names]
+ | bank b =>
+ change CallAction.localStep (c.put _ _ (c.reg (b i.2))) = _
+ rw [names]
+ have h₁ : M.program.step c₁ = .localStep d := by
+ rw [show M.program.step c₁ = (M.code c₁.pc).run M.publicData c₁ from rfl,
+ show c₁.pc = s.setup i 1 from rfl,code]
+ change CallAction.localStep (c₁.put _ _ (c₁.reg (reg 8)+c₁.reg (reg 5))) = _
+ simp [d,c₁,Config.put,hp,physical_port]
+ exact ⟨d,rfl,Config.put_same ..,fun j hj ↦ by
+ simp [d,c₁,Config.put,Function.update_of_ne hj],rfl,rfl,
+ ReadPrefix.tick h₀ (ReadPrefix.tick h₁ (ReadPrefix.nil _))⟩
+
+/-- Ordered success and exact suffix. Every child slot, including an incoming
+slot at a self-loop, consumes a separate segment of the stream. -/
+theorem scanWith (slots : List (Bool × Fin (2 ^ a))) (hl : LinkedWith M s reg source ret slots)
+ (apart : source.Apart reg) (rep : T.ActualColumns X m)
+ (data : (i : Bool × Fin (2 ^ a)) → Fin (X.halfWidth u i.1 i.2) → Bool)
+ (dst : ℕ) (fit : dst + length X u slots < 2 ^ w)
+ (c : Config w p r) (names : source.Valid M c) (hc : c.pc = first s ret slots)
+ (hd : c.reg (reg 2) = (dst : Word w))
+ (hone : c.reg (reg 3) = 1) (hi : c.reg (reg 6) = T.actualIn) (hw : c.reg (reg 7) = T.width)
+ (hp : c.reg (reg 8) = IncidenceDirectory.actualPort X (u, 0)) :
+ ∃ d, d.pc = ret ∧
+ d.privateMem = PrivateFields.storeBits dst (bits X u data slots) c.privateMem ∧
+ d.persistent = c.persistent ∧ d.reg (reg 2) = ((dst + length X u slots : ℕ) : Word w) ∧
+ (∀ i, i ≠ reg 0 → i ≠ reg 1 → i ≠ reg 2 → i ≠ reg 4 → i ≠ reg 5 → d.reg i = c.reg i) ∧
+ ∀ fuel tail, execute M.program (fuel + (events X u T m data slots).length) c m
+ (bits X u data slots ++ tail) = (execute M.program fuel d m tail).map
+ (fun q ↦ ⟨events X u T m data slots ++ q.events,q.result⟩) := by
+ induction slots generalizing dst c with
+ | nil => exact ⟨c,hc,rfl,rfl,by simpa [length] using hd,fun _ _ _ _ _ _ ↦ rfl,
+ fun fuel tail ↦ by simp [bits,events]⟩
+ | cons i rest ih =>
+ obtain ⟨setupCode, header, guess, more⟩ := hl
+ obtain ⟨mid,hm,midPort,midReg,midMem,midState,pre⟩ :=
+ address_prefix (m := m) i setupCode c names hc hp
+ let n := X.halfWidth u i.1 i.2
+ have fit' : dst+n+length X u rest < 2 ^ w := by simpa [n,length,Nat.add_assoc] using fit
+ have keeps (j : Fin 9) (hj : j ≠ 5) := midReg (reg j) (reg.injective.ne hj)
+ obtain ⟨back,hback,backMem,backState,hnext,frame,run⟩ := FieldGuess.guess_slot X u dst
+ i.1 i.2 (data i) T m rep header guess mid hm ((keeps 6 (by decide)).trans hi)
+ ((keeps 7 (by decide)).trans hw) midPort ((keeps 2 (by decide)).trans hd)
+ ((keeps 3 (by decide)).trans hone) (by omega)
+ have kept (j : Fin 9) (h₀ : j ≠ 0) (h₁ : j ≠ 1) (h₂ : j ≠ 2) (h₄ : j ≠ 4) (h₅ : j ≠ 5) :=
+ (frame (reg j) (reg.injective.ne h₀) (reg.injective.ne h₁) (reg.injective.ne h₂)
+ (reg.injective.ne h₄)).trans (keeps j h₅)
+ obtain ⟨d,hpc,hmem,hstate,hdst,hreg,hret⟩ := ih more (dst+n) fit' back
+ (names.transfer apart (fun j hn => (frame j (hn 0) (hn 1) (hn 2) (hn 4)).trans
+ (midReg j (hn 5)))) hback hnext
+ ((kept 3 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hone)
+ ((kept 6 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hi)
+ ((kept 7 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hw)
+ ((kept 8 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hp)
+ refine ⟨d,hpc,?_,hstate.trans (backState.trans midState),?_,?_,?_⟩
+ · rw [hmem,backMem,midMem]
+ simp [bits,append_store,n]
+ · simpa [n,length,Nat.add_assoc] using hdst
+ · intro j h₀ h₁ h₂ h₄ h₅
+ exact (hreg j h₀ h₁ h₂ h₄ h₅).trans ((frame _ h₀ h₁ h₂ h₄).trans (midReg _ h₅))
+ · intro fuel tail
+ change mid.reg (guessRegs reg 5) = _ at midPort
+ rw [midPort] at run
+ let es := FieldGuess.headerEvents T m i.1 (IncidenceDirectory.actualPort X (u, i.2)) ++
+ PrivateFields.events (w := w) .guess (List.ofFn (data i))
+ let fs := events X u T m data rest
+ change execute _ (fuel + (([.tick,.tick] : List (Event w)) ++ es ++ fs).length) c m
+ ((List.ofFn (data i) ++ bits X u data rest) ++ tail) = _
+ have enter := ReadPrefix.execute pre ((fuel+fs.length)+es.length)
+ ((List.ofFn (data i) ++ bits X u data rest) ++ tail)
+ change execute _ (_+2) _ _ _ = _ at enter
+ have body := run (fuel+fs.length) (bits X u data rest ++ tail)
+ change execute _ (_+es.length) _ _ _ = _ at body
+ have more := hret fuel tail
+ change execute _ (fuel+fs.length) _ _ _ = _ at more
+ rw [show fuel+(([.tick,.tick] : List (Event w)) ++ es ++ fs).length =
+ ((fuel+fs.length)+es.length)+2 by simp; omega, enter, List.append_assoc, body, more]
+ simp [events, Option.map_map, Function.comp_def, List.append_assoc]
+
+theorem scan (slots : List (Bool × Fin (2 ^ a))) (hl : Linked M s reg port ret slots)
+ (names : ∀ j, M.publicData (port j) = (j.val : Word w)) (rep : T.ActualColumns X m)
+ (data : (i : Bool × Fin (2 ^ a)) → Fin (X.halfWidth u i.1 i.2) → Bool)
+ (dst : ℕ) (fit : dst + length X u slots < 2 ^ w)
+ (c : Config w p r) (hc : c.pc = first s ret slots) (hd : c.reg (reg 2) = (dst : Word w))
+ (hone : c.reg (reg 3) = 1) (hi : c.reg (reg 6) = T.actualIn) (hw : c.reg (reg 7) = T.width)
+ (hp : c.reg (reg 8) = IncidenceDirectory.actualPort X (u, 0)) :
+ ∃ d, d.pc = ret ∧
+ d.privateMem = PrivateFields.storeBits dst (bits X u data slots) c.privateMem ∧
+ d.persistent = c.persistent ∧ d.reg (reg 2) = ((dst + length X u slots : ℕ) : Word w) ∧
+ (∀ i, i ≠ reg 0 → i ≠ reg 1 → i ≠ reg 2 → i ≠ reg 4 → i ≠ reg 5 → d.reg i = c.reg i) ∧
+ ∀ fuel tail, execute M.program (fuel + (events X u T m data slots).length) c m
+ (bits X u data slots ++ tail) = (execute M.program fuel d m tail).map
+ (fun q ↦ ⟨events X u T m data slots ++ q.events,q.result⟩) :=
+ scanWith slots hl trivial rep data dst fit c names hc hd hone hi hw hp
+
+/-- All outgoing and then all incoming slots, including slots of width zero. -/
+def slots (n : ℕ) : List (Bool × Fin n) :=
+ List.ofFn (fun i ↦ (false,i)) ++ List.ofFn (fun i ↦ (true,i))
+
+theorem bits_all (h : X.network.Half u) :
+ bits X u (fun i ↦ fieldBits X u h i.1 i.2) (slots (2 ^ a)) = packed X u h := by
+ simp [bits,slots,packed,fields,List.flatMap_def,Function.comp_def]
+
+/-- The complete old site buffer exactly fills the cursor range. -/
+theorem length_all : length X u (slots (2 ^ a)) = ∑ dir : Bool, ∑ j, X.halfWidth u dir j := by
+ simp [length,slots,Function.comp_def,List.sum_ofFn,Nat.add_comm]
+
+/-- With too few bits some header eventually reaches an incomplete field. No
+native suffix returns, regardless of the accepted bits in all earlier slots. -/
+theorem reject_shortWith (slots : List (Bool × Fin (2 ^ a)))
+ (hl : LinkedWith M s reg source ret slots)
+ (apart : source.Apart reg) (rep : T.ActualColumns X m)
+ (dst : ℕ) (fit : dst + length X u slots < 2 ^ w) (c : Config w p r) (names : source.Valid M c)
+ (hc : c.pc = first s ret slots) (hd : c.reg (reg 2) = (dst : Word w))
+ (hone : c.reg (reg 3) = 1) (hi : c.reg (reg 6) = T.actualIn) (hw : c.reg (reg 7) = T.width)
+ (hp : c.reg (reg 8) = IncidenceDirectory.actualPort X (u, 0)) (bs : List Bool)
+ (short : bs.length < length X u slots) : ¬ DFS.Returns M c m bs := by
+ induction slots generalizing c dst bs with
+ | nil => simp [length] at short
+ | cons i rest ih =>
+ obtain ⟨setupCode, header, guess, more⟩ := hl
+ obtain ⟨mid,hm,midPort,midReg,_,_,pre⟩ := address_prefix (m := m) i setupCode c names hc hp
+ let n := X.halfWidth u i.1 i.2
+ have fit' : dst+n+length X u rest < 2 ^ w := by simpa [n,length,Nat.add_assoc] using fit
+ have short' : bs.length < n+length X u rest := by simpa [n,length] using short
+ have keeps (j : Fin 9) (hj : j ≠ 5) := midReg (reg j) (reg.injective.ne hj)
+ intro accept
+ have reach := (returns_prefix (fun f ↦ ReadPrefix.execute pre f bs)).mp accept
+ by_cases full : n ≤ bs.length
+ · let f (j : Fin n) := bs[j.val]'(j.isLt.trans_le full)
+ have read : List.ofFn f ++ bs.drop n = bs := by
+ have take : List.ofFn f = bs.take n := by
+ apply List.ext_getElem (by simp [full])
+ intros; simp [f]
+ rw [take,List.take_append_drop]
+ obtain ⟨back,hback,_,_,hnext,frame,run⟩ := FieldGuess.guess_slot X u dst
+ i.1 i.2 f T m rep header guess mid hm ((keeps 6 (by decide)).trans hi)
+ ((keeps 7 (by decide)).trans hw) midPort ((keeps 2 (by decide)).trans hd)
+ ((keeps 3 (by decide)).trans hone) (by omega)
+ have kept (j : Fin 9) (h₀ : j ≠ 0) (h₁ : j ≠ 1) (h₂ : j ≠ 2) (h₄ : j ≠ 4) (h₅ : j ≠ 5) :=
+ (frame (reg j) (reg.injective.ne h₀) (reg.injective.ne h₁) (reg.injective.ne h₂)
+ (reg.injective.ne h₄)).trans (keeps j h₅)
+ apply ih more (dst+n) fit' back
+ (names.transfer apart (fun j hn => (frame j (hn 0) (hn 1) (hn 2) (hn 4)).trans
+ (midReg j (hn 5)))) hback hnext
+ ((kept 3 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hone)
+ ((kept 6 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hi)
+ ((kept 7 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hw)
+ ((kept 8 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hp)
+ (bs.drop n) (by simp; omega)
+ rw [← read] at reach
+ exact (returns_prefix (fun fuel ↦ run fuel (bs.drop n))).mp reach
+ · exact FieldGuess.reject_short X u dst i.1 i.2 T m rep header guess mid hm
+ ((keeps 6 (by decide)).trans hi) ((keeps 7 (by decide)).trans hw) midPort
+ ((keeps 2 (by decide)).trans hd) ((keeps 3 (by decide)).trans hone)
+ (by omega) bs (Nat.lt_of_not_ge full) reach
+
+theorem reject_short (slots : List (Bool × Fin (2 ^ a))) (hl : Linked M s reg port ret slots)
+ (names : ∀ j, M.publicData (port j) = (j.val : Word w)) (rep : T.ActualColumns X m)
+ (dst : ℕ) (fit : dst + length X u slots < 2 ^ w) (c : Config w p r)
+ (hc : c.pc = first s ret slots) (hd : c.reg (reg 2) = (dst : Word w))
+ (hone : c.reg (reg 3) = 1) (hi : c.reg (reg 6) = T.actualIn) (hw : c.reg (reg 7) = T.width)
+ (hp : c.reg (reg 8) = IncidenceDirectory.actualPort X (u, 0)) (bs : List Bool)
+ (short : bs.length < length X u slots) : ¬ DFS.Returns M c m bs :=
+ reject_shortWith slots hl trivial rep dst fit c names hc hd hone hi hw hp bs short
+
+end PairSimulation.NodeArguments.ChildSlots
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeChildStage.lean b/lean/OAI/Computability/VPVNP/PairNodeChildStage.lean
new file mode 100644
index 0000000000..22fb97b122
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeChildStage.lean
@@ -0,0 +1,174 @@
+import OAI.Computability.VPVNP.PairNodeChildScanCost
+import OAI.Computability.VPVNP.PairNodeChildHeader
+import OAI.Computability.VPVNP.PairTypedVertexJobs
+
+/-!
+# The complete child argument stage of a native parent visit
+
+The header loads the actual list and the old layer's incidence directory. The
+fixed child loop consumes precisely the placed old halves before entering the
+local kernel routine. The same computation preserves the remaining tape,
+stack cells, and packets already prepared for other pending sites.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildScan
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DFS LocalHistory NetworkKernel
+open TraversalRows
+open scoped Fin.CommRing
+
+variable {w p r k a g : ℕ} {M : Machine w p r k} {s : Sites a p} {reg : Fin 16 ↪ Fin r}
+variable {source : ChildSlots.Names (2 ^ a) r k} {port : Fin (2 ^ a) → Fin k}
+variable {ret : Fin p} {m : Memory w} {X : State a g}
+variable {T : IncidenceDirectory w} {A : Arena} {older cap : ℕ} {header : Fin 17 → Fin p}
+
+/-- Runtime layout data read from the chosen physical level. -/
+def directory (a older cap : ℕ) (A : Arena) (T : IncidenceDirectory w) : ChildHeader.Fields w :=
+ ⟨(older : Word w), ((cap + 2 : ℕ) : Word w), ((2 ^ a : ℕ) : Word w), (A.start : Word w),
+ (A.stride : Word w), T.actualIn, T.width⟩
+
+private theorem header_params {c d : Config w p r} {src count : ℕ}
+ (h : ChildHeader.Ready reg (s.guard 0) c d (directory a older cap A T) src count) :
+ Params reg a older cap A T d :=
+ ⟨h.one, h.actualIn, h.width, h.olderBase, h.stride, h.degree, h.argumentStart, h.argumentStride⟩
+
+/-- The ordered packets passed to the old-argument kernel reader are exactly
+the child coordinates produced by the native scan of the same fiber. -/
+theorem children_packets {R L : Type} [CommRing R] [Fintype L] {κ : L → R} {t : Term R X.network}
+ (r : TermParsers κ t) (hp : ∀ u h, r.halfBits u h = packed X u h) (older cap : ℕ)
+ (v : t.output.Site) (h : Placed t.place X.network.Half v) :
+ (children X v (r.order.children v) h).map (Child.packet X older cap) =
+ r.childPackets (childNode X older cap) v h := by
+ simp only [children, List.map_ofFn, Function.comp_def, TermParsers.childPackets, Child.packet,
+ Child.payload_ofHalf, hp]
+ rfl
+
+/-- The pointer at each old-argument position is the precise absolute node
+stored in the selected traversal layer, in the parser's child order. -/
+theorem children_words {R L : Type} [CommRing R] [Fintype L] {κ : L → R} {t : Term R X.network}
+ (r : TermParsers κ t) (next : Order t.output.Site) (older cap : ℕ) (v : t.output.Site)
+ (h : Placed t.place X.network.Half v) :
+ (children X v (r.order.children v) h).map (fun x => (childNode X older cap x.site : Word w)) =
+ childWords w cap older (stepLayer (siteOrder X) next r) (next.entries.symm v) := by
+ obtain ⟨j, rfl⟩ := next.entries.surjective v
+ rw [Equiv.symm_apply_apply]
+ simp only [children, childWords, stepLayer, Child.ofHalf, childNode, sitePointers, List.map_ofFn,
+ Function.comp_def]
+
+private theorem header_entry (hh : ChildHeader.Linked M header reg (s.guard 0))
+ (c : Config w p r) (hc : c.pc = header 0)
+ (stored : (directory a older cap A T).Stored m (c.reg (reg 8)))
+ (xs : List (Child X)) (src : ℕ)
+ (row : Row m (c.reg (reg 7)).val src
+ (xs.map fun x => (childNode X older cap x.site : Word w))) :
+ ∃ d, ChildHeader.Ready reg (s.guard 0) c d (directory a older cap A T) src xs.length ∧
+ Prefix M m c d [] (ChildHeader.events m (c.reg (reg 7)) (c.reg (reg 8))) := by
+ obtain ⟨d, ready, prefixRun⟩ := ChildHeader.native hh m c hc _ stored src _ row
+ refine ⟨d, by simpa using ready, fun fuel tail => ?_⟩
+ simpa only [List.nil_append, (ChildHeader.cost m (c.reg (reg 7)) (c.reg (reg 8))).2.1] using
+ prefixRun fuel tail
+
+private theorem names_after_header {c d : Config w p r} (valid : source.Valid M c)
+ (apart : source.Apart reg) {src count : ℕ}
+ (h : ChildHeader.Ready reg (s.guard 0) c d (directory a older cap A T) src count) :
+ source.Valid M d :=
+ valid.transfer apart fun i hi => h.frame i fun j _ => hi j
+
+/-- The whole stage consumes the old argument bits and executes the kernel
+continuation on the suffix with the logical packets stored in scratch. -/
+theorem native_stageWith (hh : ChildHeader.Linked M header reg (s.guard 0))
+ (hl : LinkedWith M s reg source ret)
+ (apart : source.Apart reg) (rep : T.ActualColumns X m)
+ (xs : List (Child X)) (src : ℕ) (c : Config w p r) (names : source.Valid M c)
+ (hc : c.pc = header 0)
+ (stored : (directory a older cap A T).Stored m (c.reg (reg 8)))
+ (row : Row m (c.reg (reg 7)).val src (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w) :
+ let qs := xs.map (Child.packet X older cap)
+ let es := ChildHeader.events m (c.reg (reg 7)) (c.reg (reg 8)) ++ events X T m src xs
+ ∃ d, d.pc = ret ∧ d.persistent = c.persistent ∧ d.privateMem = storePackets A qs c.privateMem ∧
+ (∀ endAddr, scratch endAddr d.privateMem = writePackets A qs (scratch endAddr c.privateMem)) ∧
+ (∀ i, ChildHeader.Preserved reg i → i ∉ mutableRegs reg → d.reg i = c.reg i) ∧
+ Prefix M m c d (qs.flatMap Packet.bits) es := by
+ intro qs es
+ obtain ⟨mid, init, pre⟩ := header_entry hh c hc stored xs src row
+ have h := ready_of_row row strideFit nodes packets
+ obtain ⟨d, hd, memory, state, frame, body⟩ := scanWith hl apart rep src xs h mid
+ (names_after_header names apart init) init.pc init.source
+ init.count (header_params init)
+ have mem : d.privateMem = storePackets A qs c.privateMem :=
+ memory.trans (congrArg _ init.privateMem)
+ exact ⟨d, hd, state.trans init.persistent, mem, fun n => mem ▸ scratch_storePackets A qs _,
+ fun i hi hmut => (frame i hmut).trans (init.frame i hi), pre.trans body⟩
+
+theorem native_stage (hh : ChildHeader.Linked M header reg (s.guard 0))
+ (hl : Linked M s reg port ret)
+ (names : ∀ j, M.publicData (port j) = (j.val : Word w)) (rep : T.ActualColumns X m)
+ (xs : List (Child X)) (src : ℕ) (c : Config w p r) (hc : c.pc = header 0)
+ (stored : (directory a older cap A T).Stored m (c.reg (reg 8)))
+ (row : Row m (c.reg (reg 7)).val src (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w) :
+ let qs := xs.map (Child.packet X older cap)
+ let es := ChildHeader.events m (c.reg (reg 7)) (c.reg (reg 8)) ++ events X T m src xs
+ ∃ d, d.pc = ret ∧ d.persistent = c.persistent ∧ d.privateMem = storePackets A qs c.privateMem ∧
+ (∀ endAddr, scratch endAddr d.privateMem = writePackets A qs (scratch endAddr c.privateMem)) ∧
+ (∀ i, ChildHeader.Preserved reg i → i ∉ mutableRegs reg → d.reg i = c.reg i) ∧
+ Prefix M m c d (qs.flatMap Packet.bits) es :=
+ native_stageWith hh hl.toLinkedWith trivial rep xs src c names hc stored row
+ strideFit nodes packets
+
+/-- Rejection from the same full entry, including reads of the actual parent
+header and directory. No accepting suffix exists for a short argument stream. -/
+theorem reject_stageWith (hh : ChildHeader.Linked M header reg (s.guard 0))
+ (hl : LinkedWith M s reg source ret)
+ (apart : source.Apart reg) (rep : T.ActualColumns X m)
+ (xs : List (Child X)) (src : ℕ) (c : Config w p r) (names : source.Valid M c)
+ (hc : c.pc = header 0)
+ (stored : (directory a older cap A T).Stored m (c.reg (reg 8)))
+ (row : Row m (c.reg (reg 7)).val src (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w)
+ (bs : List Bool) (short : bs.length < (xs.flatMap (Child.payload X)).length) :
+ ¬ Returns M c m bs := by
+ obtain ⟨mid, init, pre⟩ := header_entry hh c hc stored xs src row
+ have h := ready_of_row row strideFit nodes packets
+ exact fun accepted => reject_shortWith hl apart rep src xs h mid
+ (names_after_header names apart init) init.pc init.source init.count
+ (header_params init) bs short ((pre.returns bs).mp accepted)
+
+theorem reject_stage (hh : ChildHeader.Linked M header reg (s.guard 0))
+ (hl : Linked M s reg port ret)
+ (names : ∀ j, M.publicData (port j) = (j.val : Word w)) (rep : T.ActualColumns X m)
+ (xs : List (Child X)) (src : ℕ) (c : Config w p r) (hc : c.pc = header 0)
+ (stored : (directory a older cap A T).Stored m (c.reg (reg 8)))
+ (row : Row m (c.reg (reg 7)).val src (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w)
+ (bs : List Bool) (short : bs.length < (xs.flatMap (Child.payload X)).length) :
+ ¬ Returns M c m bs :=
+ reject_stageWith hh hl.toLinkedWith trivial rep xs src c names hc stored row
+ strideFit nodes packets bs short
+
+/-- All native stores remain above the protected stack boundary, including
+when the remaining stack contains pending siblings. -/
+theorem storePackets_below (A : Arena) (qs : List Packet) (priv : Word w → Word w)
+ (endAddr : ℕ) (fits : ∀ q ∈ qs, q.Fits A w endAddr) (x : Word w) (hx : x.val < endAddr) :
+ storePackets A qs priv x = priv x := by
+ induction qs generalizing priv with
+ | nil => rfl
+ | cons q qs ih =>
+ have hf := fits q List.mem_cons_self
+ apply (ih _ (fun z hz => fits z (List.mem_cons_of_mem _ hz))).trans
+ exact PrivateFields.storeBits_outside _ _ _ x hf.2.2 (Or.inl (hx.trans_le hf.1))
+
+end PairSimulation.NodeArguments.ChildScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeDispatch.lean b/lean/OAI/Computability/VPVNP/PairNodeDispatch.lean
new file mode 100644
index 0000000000..7312e3ef37
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeDispatch.lean
@@ -0,0 +1,241 @@
+import OAI.Computability.VPVNP.PairSimulationDFSDecode
+import OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+/-!
+# Dispatching an ordered history visit by its recorded role
+
+The common DFS pop leaves the absolute descriptor address in register 7.
+A single external word lookup selects the cursor leaf, six-party shrinking,
+or degree-refresh entry routine. The six instructions preserve the
+private stack, histogram, pending suffix and the node address itself.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeDispatch
+
+open BurstRAM BurstRAM.PrivateRAM DFS
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.read ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+open private returns_prefix from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+variable {w p r k : ℕ}
+
+/-- The three handlers for a visited DFS node are the cursor leaf, the six-party shrink step
+and the degree refresh step. -/
+inductive Role
+ | leaf | shrink | refresh
+ deriving DecidableEq
+
+/-- Decodes the stored role word. Zero selects the leaf handler, one selects shrink, and every
+other value selects refresh. -/
+def role (tag : Word w) : Role :=
+ if tag = 0 then .leaf else if tag = 1 then .shrink else .refresh
+
+/-- Fetch the role word from the side table indexed by the absolute
+descriptor address. Only two temporary registers are modified. -/
+def instruction (pc : Fin 6 → Fin p) (reg : Fin 9 ↪ Fin r) (field : Fin k)
+ (entry : Role → Fin p) : Fin 6 → Instr w p r k :=
+ ![.publicWord (reg 0) field (pc 1), .binary .add (reg 0) (reg 0) (reg 7) (pc 2),
+ .readExternal (reg 0) (reg 0) (pc 3), .constant (reg 1) 0 (pc 4),
+ .jumpEq (reg 0) (reg 1) (entry .leaf) (pc 5),
+ .jumpEq (reg 0) (reg 3) (entry .shrink) (entry .refresh)]
+
+theorem resize_instruction (pc : Fin 6 → Fin p) (reg : Fin 9 ↪ Fin r) (field : Fin k)
+ (entry : Role → Fin p) (i : Fin 6) :
+ (instruction (w := 1) pc reg field entry i).resize w = instruction pc reg field entry i := by
+ fin_cases i <;> rfl
+
+/-- Requires the machine to contain all six dispatcher instructions at the specified program
+counters, with the supplied register placement, role-table offset operand and handler entry
+points. -/
+def Linked (M : Machine w p r k) (pc : Fin 6 → Fin p) (reg : Fin 9 ↪ Fin r) (field : Fin k)
+ (entry : Role → Fin p) : Prop := ∀ i, M.code (pc i) = instruction pc reg field entry i
+
+/-- Trace for dispatching one node. The external read is at offset + node, and a nonzero tag
+takes one further tick to distinguish shrink from refresh. -/
+def events (m : Memory w) (offset node : Word w) : List (Event w) :=
+ let a := offset + node
+ let tag := m a.val
+ [.tick, .tick, .read a tag, .tick, .tick] ++ if tag = 0 then [] else [.tick]
+
+theorem events_cost (m : Memory w) (offset node : Word w) :
+ countProbes (events m offset node) = 1 ∧ (events m offset node).length ≤ 6 ∧
+ choiceBits (events m offset node) = [] := by
+ by_cases hz : m (offset+node).val = 0 <;> simp [events, hz, countProbes, choiceBits]
+
+variable {M : Machine w p r k} {pc : Fin 6 → Fin p} {reg : Fin 9 ↪ Fin r} {field : Fin k}
+ {entry : Role → Fin p}
+
+private theorem step_at (hl : Linked M pc reg field entry) (i : Fin 6) (c : Config w p r)
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg field entry i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+/-- The common five rows after the offset load work for either a public
+word or a base obtained from the terminal geometry record. -/
+theorem enter_loaded (offset : Word w) (c : Config w p r)
+ (first : M.program.step c = .localStep (c.put (pc 1) (reg 0) offset))
+ (later : ∀ i : Fin 6, i ≠ 0 → M.code (pc i) = instruction pc reg field entry i)
+ (h1 : c.reg (reg 3) = 1) (m : Memory w) :
+ let node := c.reg (reg 7)
+ let tag := m (offset+node).val
+ ∃ out, out.pc = entry (role tag) ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent ∧ (∀ j, j ≠ reg 0 → j ≠ reg 1 → out.reg j = c.reg j) ∧
+ ∀ fuel bs, execute M.program (fuel+(events m offset node).length) c m bs =
+ (execute M.program fuel out m bs).map
+ (fun rep => ⟨events m offset node ++ rep.events,rep.result⟩) := by
+ intro node tag
+ have step (i : Fin 6) (hi : i ≠ 0) (d : Config w p r) (hd : d.pc = pc i) :
+ M.program.step d = (instruction pc reg field entry i).run M.publicData d := by
+ change (M.code d.pc).run _ _ = _
+ rw [hd, later i hi]
+ let a := offset+node
+ let c₁ := c.put (pc 1) (reg 0) offset
+ let c₂ := c₁.put (pc 2) (reg 0) a
+ let c₃ := c₂.put (pc 3) (reg 0) tag
+ let c₄ := c₃.put (pc 4) (reg 1) 0
+ let leave (j : Fin p) := {c₄ with pc := j}
+ let pre : List (Event w) := [.tick,.tick,.read a tag,.tick,.tick]
+ have s₀ : M.program.step c = .localStep c₁ := first
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step 1 (by decide) c₁ rfl]
+ change CallAction.localStep (c₁.put (pc 2) (reg 0) (c₁.reg (reg 0)+c₁.reg (reg 7))) = _
+ simp [c₁,c₂,a,node,Config.put]
+ have s₂ : M.program.step c₂ = .read a (fun v => c₂.put (pc 3) (reg 0) v) := by
+ rw [step 2 (by decide) c₂ rfl]
+ change CallAction.read (c₂.reg (reg 0)) _ = _
+ exact congrArg (fun t => CallAction.read t _) (Config.put_same ..)
+ have s₃ : M.program.step c₃ = .localStep c₄ := step 3 (by decide) c₃ rfl
+ have s₄ : M.program.step c₄ = .localStep (leave (if tag=0 then entry .leaf else pc 5)) := by
+ rw [step 4 (by decide) c₄ rfl]
+ change CallAction.localStep {c₄ with pc := if c₄.reg (reg 0) = c₄.reg (reg 1) then _ else _} = _
+ simp [c₄,c₃,leave,Config.put]
+ have finish {q : Fin p} {es : List (Event w)}
+ (h : ReadPrefix M m (leave (if tag=0 then entry .leaf else pc 5)) es (leave q)) :
+ ReadPrefix M m c (pre++es) (leave q) :=
+ ReadPrefix.tick s₀ (ReadPrefix.tick s₁ (ReadPrefix.read a s₂
+ (ReadPrefix.tick s₃ (ReadPrefix.tick s₄ h))))
+ let q := entry (role tag)
+ have h : ReadPrefix M m c (events m offset node) (leave q) := by
+ by_cases hz : tag = 0
+ · have hq : (if tag=0 then entry .leaf else pc 5) = q := by simp [hz,q,role]
+ have he : events m offset node = pre++[] := by
+ change pre ++ (if tag = 0 then [] else [.tick]) = _
+ rw [ite_eq_left hz]
+ rw [he]
+ apply finish
+ rw [hq]
+ exact ReadPrefix.nil _
+ · have s₅ : M.program.step (leave (pc 5)) = .localStep (leave q) := by
+ rw [step 5 (by decide) (leave (pc 5)) rfl]
+ change CallAction.localStep {leave (pc 5) with pc :=
+ (if (leave (pc 5)).reg (reg 0) = (leave (pc 5)).reg (reg 3) then entry .shrink
+ else entry .refresh)} = _
+ dsimp only [leave, c₄, c₃, c₂, c₁, Config.put, q, role]
+ simp [hz,h1]
+ split <;> rfl
+ have he : events m offset node = pre++[.tick] := by
+ change pre ++ (if tag = 0 then [] else [.tick]) = _
+ rw [ite_eq_right hz]
+ rw [he]
+ apply finish
+ rw [ite_eq_right hz]
+ exact ReadPrefix.tick s₅ (ReadPrefix.nil _)
+ refine ⟨leave q, rfl, rfl, rfl, ?_, ReadPrefix.execute h⟩
+ intro j hj₀ hj₁
+ simp [leave,c₄,c₃,c₂,c₁,Config.put,Function.update_of_ne hj₀,Function.update_of_ne hj₁]
+
+/-- The fetched word selects the corresponding native continuation without
+consuming any of the remaining private choices. -/
+theorem enter (hl : Linked M pc reg field entry) (c : Config w p r) (hc : c.pc = pc 0)
+ (h1 : c.reg (reg 3) = 1) (m : Memory w) :
+ let offset := M.publicData field
+ let node := c.reg (reg 7)
+ let tag := m (offset+node).val
+ ∃ out, out.pc = entry (role tag) ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent ∧ (∀ j, j ≠ reg 0 → j ≠ reg 1 → out.reg j = c.reg j) ∧
+ ∀ fuel bs, execute M.program (fuel+(events m offset node).length) c m bs =
+ (execute M.program fuel out m bs).map
+ (fun rep => ⟨events m offset node ++ rep.events,rep.result⟩) :=
+ enter_loaded (M.publicData field) c (step_at hl 0 c hc) (fun i _ => hl i) h1 m
+
+/-- Parser of the actual dispatch opcode, retaining its deterministic
+prefix in the visit path. -/
+def parser {endAddr : ℕ} (handlers : Role → HookParser w endAddr) (m : Memory w)
+ (offset : Word w) : HookParser w endAddr where
+ read node s bs := ((handlers (role (m (offset+node).val))).read node s bs).map fun (job,tail) =>
+ ({job with trace := events m offset node ++ job.trace},tail)
+
+/-- Exact leaf, shrink and refresh handlers at their native entry labels
+compose with the fixed role router, on successful reads and rejection. -/
+theorem parser_exactOn {endAddr : ℕ} {domain : Word w → Scratch w endAddr → Prop}
+ (hl : Linked M pc reg field entry) (ret : Fin p)
+ (m : Memory w) (handlers : Role → HookParser w endAddr)
+ (h : ∀ i, (handlers i).ExactOn
+ (fun node s => domain node s ∧ role (m (M.publicData field + node).val) = i)
+ M (entry i) ret reg m) :
+ (parser handlers m (M.publicData field)).ExactOn domain M (pc 0) ret reg m := by
+ let offset := M.publicData field
+ constructor
+ · intro node s hd bs job tail result
+ let i := role (m (offset+node).val)
+ obtain ⟨⟨j, rest⟩, read, eq⟩ := Option.map_eq_some_iff.mp result
+ cases eq
+ obtain ⟨hnode, hen, hbs, body⟩ := (h i).success node s ⟨hd, rfl⟩ bs j tail read
+ refine ⟨hnode, hen, ?_, ?_⟩
+ · simpa only [PrimedInputRAM.Flow.choiceBits_append,
+ (events_cost m (M.publicData field) node).2.2,
+ List.nil_append] using hbs
+ · intro c top pending enabled hc hn hs hend ht he h1
+ obtain ⟨mid, hm, mem, persist, regs, run⟩ := enter hl c hc h1 m
+ rw [hn, hnode] at hm run
+ have kept (i : Fin 9) (hi : i ≠ 0) (hi' : i ≠ 1) :=
+ regs (reg i) (reg.injective.ne hi) (reg.injective.ne hi')
+ obtain ⟨out, hp, hn', ht', he', h1', pst, st, upd, work⟩ := body mid top pending
+ (mem ▸ enabled) hm ((kept 7 (by decide) (by decide)).trans hn) (mem ▸ hs) hend
+ ((kept 5 (by decide) (by decide)).trans ht) ((kept 6 (by decide) (by decide)).trans he)
+ ((kept 3 (by decide) (by decide)).trans h1)
+ refine ⟨out,hp,hn',ht',he',h1',pst.trans persist,st,mem ▸ upd,?_⟩
+ intro fuel suffix
+ simp only [PrimedInputRAM.Flow.choiceBits_append,
+ (events_cost m (M.publicData field) node).2.2, List.nil_append,
+ List.length_append]
+ rw [show fuel + ((events m offset node).length+j.trace.length) =
+ (fuel+j.trace.length)+(events m offset node).length by omega, run, work]
+ simp only [Option.map_map, Function.comp_def, List.append_assoc]
+ · intro node bs c top pending hd hc hn hs hend ht he h1 fail
+ let i := role (m (offset+node).val)
+ have read : (handlers i).read node (scratch endAddr c.privateMem) bs = none :=
+ Option.map_eq_none_iff.mp fail
+ obtain ⟨mid, hm, mem, _, regs, run⟩ := enter hl c hc h1 m
+ rw [hn] at hm run
+ have kept (i : Fin 9) (hi : i ≠ 0) (hi' : i ≠ 1) :=
+ regs (reg i) (reg.injective.ne hi) (reg.injective.ne hi')
+ have reject := (h i).reject node bs mid top pending ⟨mem ▸ hd, rfl⟩ hm
+ ((kept 7 (by decide) (by decide)).trans hn) (mem ▸ hs) hend
+ ((kept 5 (by decide) (by decide)).trans ht) ((kept 6 (by decide) (by decide)).trans he)
+ ((kept 3 (by decide) (by decide)).trans h1) (mem ▸ read)
+ exact fun ok => reject ((returns_prefix (fun fuel => run fuel bs)).mp ok)
+
+/-- Exact leaf, shrink and refresh handlers at their native entry labels
+compose with the fixed role router, on successful reads and rejection. -/
+theorem parser_exact {endAddr : ℕ}
+ (hl : Linked M pc reg field entry) (ret : Fin p)
+ (m : Memory w) (handlers : Role → HookParser w endAddr)
+ (h : ∀ i, (handlers i).Exact M (entry i) ret reg m) :
+ (parser handlers m (M.publicData field)).Exact M (pc 0) ret reg m := by
+ have h' := parser_exactOn (domain := fun _ _ => True) hl ret m handlers
+ (fun i => ⟨fun node s _ => (h i).success node s,
+ fun node bs c top pending _ => (h i).reject node bs c top pending⟩)
+ exact ⟨fun node s => h'.success node s trivial,
+ fun node bs c top pending => h'.reject node bs c top pending trivial⟩
+
+end PairSimulation.NodeDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairNodeFieldGuess.lean b/lean/OAI/Computability/VPVNP/PairNodeFieldGuess.lean
new file mode 100644
index 0000000000..2d0fbb1613
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairNodeFieldGuess.lean
@@ -0,0 +1,212 @@
+import OAI.Computability.VPVNP.PairNodeArguments
+import OAI.Computability.VPVNP.PairSimulationPrivateSlices
+import OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+/-!
+# Native width lookup and independent child-slot guesses
+
+The outgoing and incoming branches enter the same width-reading and bit-guess
+instructions. An incoming slot first reads the inverse arc directory. The
+guessed bits are written consecutively to the child's argument interval.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.FieldGuess
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords Compression
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.read ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+open private returns_prefix from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+variable {w p r k : ℕ}
+
+/-- Registers 0--4 form the native private-field ABI. Registers 5--7 hold
+physical port ID, inverse incidence base, and source width base. -/
+def instruction (pc : Fin 6 → Fin p) (reg : Fin 8 ↪ Fin r) (guess : Fin p) :
+ Fin 6 → Instr w p r k :=
+ ![.binary .add (reg 4) (reg 6) (reg 5) (pc 1), .readExternal (reg 4) (reg 4) (pc 3),
+ .copy (reg 4) (reg 5) (pc 3), .binary .add (reg 4) (reg 7) (reg 4) (pc 4),
+ .readExternal (reg 1) (reg 4) (pc 5), .binary .add (reg 1) (reg 2) (reg 1) guess]
+
+/-- Selects the width-lookup entry instruction for a slot. Incoming slots enter at instruction
+zero to read the inverse incidence table, and outgoing slots enter at instruction two with
+their port already known. -/
+def entry (pc : Fin 6 → Fin p) (dir : Bool) : Fin p := pc (if dir then 0 else 2)
+
+/-- The first five registers of the eight-register width routine, passed to the private
+bit-guessing loop after the field end address has been computed. -/
+def fieldRegs (reg : Fin 8 ↪ Fin r) : Fin 5 ↪ Fin r := (Fin.castAddEmb 3).trans reg
+
+theorem resize_instruction (pc : Fin 6 → Fin p) (reg : Fin 8 ↪ Fin r) (guess : Fin p)
+ (i : Fin 6) : (instruction (w := 1) (k := k) pc reg guess i).resize w =
+ instruction pc reg guess i := by fin_cases i <;> rfl
+
+/-- Requires the six installed width-lookup instructions to use the specified register
+placement and transfer control to the bit-guessing entry. -/
+def Linked (M : Machine w p r k) (pc : Fin 6 → Fin p) (reg : Fin 8 ↪ Fin r) (guess : Fin p) :=
+ ∀ i, M.code (pc i) = instruction pc reg guess i
+
+/-- Trace that determines the width of one port before any bit choices. An incoming port first
+reads its arc ID from the inverse incidence table, then both directions read the width at
+the resulting ID. -/
+def headerEvents (T : IncidenceDirectory w) (m : Memory w) (dir : Bool) (port : Word w) :
+ List (Event w) :=
+ let id := if dir then m (T.actualIn + port).val else port
+ (if dir then [.tick, .read (T.actualIn+port) id] else [.tick]) ++
+ [.tick, .read (T.width+id) (m (T.width+id).val), .tick]
+
+theorem header_cost (T : IncidenceDirectory w) (m : Memory w) (dir : Bool) (port : Word w) :
+ countProbes (headerEvents T m dir port) = (if dir then 2 else 1) ∧
+ (headerEvents T m dir port).length = (if dir then 5 else 4) ∧
+ choiceBits (headerEvents T m dir port) = [] := by
+ cases dir <;> exact ⟨rfl,rfl,rfl⟩
+
+variable {M : Machine w p r k} {pc : Fin 6 → Fin p} {reg : Fin 8 ↪ Fin r} {guess : Fin p}
+
+private theorem step_at (hl : Linked M pc reg guess) (i : Fin 6) (c : Config w p r)
+ (hc : c.pc = pc i) : M.program.step c = (instruction pc reg guess i).run M.publicData c := by
+ simp [Machine.program,hc,hl i]
+
+/-- Exact header continuation. No private field, histogram cell, or branch bit
+is touched while following the two real incidence columns. -/
+theorem header (hl : Linked M pc reg guess) (T : IncidenceDirectory w) (m : Memory w)
+ (dir : Bool) (c : Config w p r) (hc : c.pc = entry pc dir)
+ (hi : c.reg (reg 6) = T.actualIn) (hw : c.reg (reg 7) = T.width) :
+ let port := c.reg (reg 5)
+ ∃ out, out.pc = guess ∧ out.reg (reg 1) = c.reg (reg 2) + WidthRead.value T m dir port ∧
+ (∀ j, j ≠ reg 1 → j ≠ reg 4 → out.reg j = c.reg j) ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent ∧ ∀ fuel bs,
+ execute M.program (fuel + (headerEvents T m dir port).length) c m bs =
+ (execute M.program fuel out m bs).map
+ (fun rep ↦ ⟨headerEvents T m dir port ++ rep.events,rep.result⟩) := by
+ intro port
+ let id := if dir then m (T.actualIn+port).val else port
+ let addr := T.width+id
+ let middle := c.put (pc 3) (reg 4) id
+ let atWidth := middle.put (pc 4) (reg 4) addr
+ let loaded := atWidth.put (pc 5) (reg 1) (m addr.val)
+ let out := loaded.put guess (reg 1) (c.reg (reg 2) + m addr.val)
+ let first : List (Event w) := if dir then [.tick,.read (T.actualIn+port) id] else [.tick]
+ have enter : ReadPrefix M m c first middle := by
+ cases dir with
+ | false => exact ReadPrefix.tick (step_at hl 2 c hc) (ReadPrefix.nil _)
+ | true =>
+ let x := c.put (pc 1) (reg 4) (T.actualIn+port)
+ have h₀ : M.program.step c = .localStep x := by
+ rw [step_at hl 0 c hc]
+ change CallAction.localStep (c.put _ _ (c.reg (reg 6) + port)) = _
+ rw [hi]
+ have h₁ : M.program.step x = .read (T.actualIn+port) (fun n ↦ x.put (pc 3) (reg 4) n) := by
+ rw [step_at hl 1 x rfl]
+ change CallAction.read (x.reg (reg 4)) _ = _
+ rw [Config.put_same]
+ refine ReadPrefix.tick h₀ (ReadPrefix.read _ h₁ ?_)
+ have he : x.put (pc 3) (reg 4) (m (T.actualIn+port).val) = middle := by
+ simp [middle, x, id, Config.put, Function.update_idem]
+ rw [he]
+ exact ReadPrefix.nil _
+ have h₃ : M.program.step middle = .localStep atWidth := by
+ rw [step_at hl 3 middle rfl]
+ change CallAction.localStep (middle.put _ _ (middle.reg (reg 7) + middle.reg (reg 4))) = _
+ simp [middle, atWidth, addr, Config.put, hw]
+ have h₄ : M.program.step atWidth = .read addr (fun n ↦ atWidth.put (pc 5) (reg 1) n) := by
+ rw [step_at hl 4 atWidth rfl]
+ change CallAction.read (atWidth.reg (reg 4)) _ = _
+ rw [Config.put_same]
+ have h₅ : M.program.step loaded = .localStep out := by
+ rw [step_at hl 5 loaded rfl]
+ change CallAction.localStep (loaded.put _ _ (loaded.reg (reg 2) + loaded.reg (reg 1))) = _
+ simp [out, loaded, atWidth, middle, Config.put]
+ let last : List (Event w) := [.tick,.read addr (m addr.val),.tick]
+ have leave : ReadPrefix M m middle last out :=
+ ReadPrefix.tick h₃ (ReadPrefix.read _ h₄ (ReadPrefix.tick h₅ (ReadPrefix.nil _)))
+ refine ⟨out, rfl, Config.put_same .., ?_, rfl, rfl, ?_⟩
+ · intro j hj₁ hj₄
+ simp [out,loaded,atWidth,middle,Config.put,Function.update_of_ne hj₁,Function.update_of_ne hj₄]
+ · intro fuel bs
+ change execute M.program (fuel+(first++last).length) c m bs = _
+ rw [List.length_append, show fuel+(first.length+last.length) =
+ (fuel+last.length)+first.length by omega,
+ ReadPrefix.execute enter, ReadPrefix.execute leave]
+ simp [headerEvents, first, last, addr, id, Option.map_map, Function.comp_def, List.append_assoc]
+
+/-- The concrete slot of a child is read from the packed incidence table, then
+its independently guessed payload is written at the declared private address. -/
+theorem guess_slot {a g : ℕ} (X : State a g) (u : X.network.Site)
+ (dst : ℕ) (dir : Bool) (j : Fin (2 ^ a)) (f : Fin (X.halfWidth u dir j) → Bool)
+ (T : IncidenceDirectory w) (m : Memory w)
+ (rep : T.ActualColumns X m) {bitsPC : Fin 7 → Fin p} {ret : Fin p}
+ (hl : Linked M pc reg (bitsPC 0))
+ (hb : PrivateFields.Linked M .guess bitsPC (fieldRegs reg) ret)
+ (c : Config w p r) (hc : c.pc = entry pc dir) (hi : c.reg (reg 6) = T.actualIn)
+ (hw : c.reg (reg 7) = T.width) (hport : c.reg (reg 5) = IncidenceDirectory.actualPort X (u, j))
+ (hd : c.reg (reg 2) = (dst : Word w)) (h1 : c.reg (reg 3) = 1)
+ (fit : dst + X.halfWidth u dir j < 2 ^ w) :
+ let bits := List.ofFn f
+ let es := headerEvents T m dir (c.reg (reg 5)) ++ PrivateFields.events (w := w) .guess bits
+ ∃ out, out.pc = ret ∧ out.privateMem = PrivateFields.storeBits (dst)
+ bits c.privateMem ∧ out.persistent = c.persistent ∧
+ out.reg (reg 2) = ((dst + X.halfWidth u dir j : ℕ) : Word w) ∧
+ (∀ i, i ≠ reg 0 → i ≠ reg 1 → i ≠ reg 2 → i ≠ reg 4 → out.reg i = c.reg i) ∧
+ ∀ fuel tail, execute M.program (fuel + es.length) c m (bits ++ tail) =
+ (execute M.program fuel out m tail).map (fun q ↦ ⟨es ++ q.events,q.result⟩) := by
+ intro bits es
+ obtain ⟨d, hp, he, keep, hm, hs, head⟩ := header hl T m dir c hc hi hw
+ rw [hport, WidthRead.value_actual X u T m rep, hd] at he
+ have hdst : d.reg (fieldRegs reg 2) = (dst : Word w) :=
+ (keep _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans hd
+ have hone : d.reg (fieldRegs reg 3) = 1 :=
+ (keep _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans h1
+ obtain ⟨out, pref, hr⟩ := PrivateFields.guess_prefix hb d hp (dst)
+ bits hdst (by change d.reg (reg 1) = _; simpa [bits,CursorRAM.encode] using he) hone
+ (by simpa [bits] using fit)
+ refine ⟨out, hr.pc, hr.privateMem.trans (congrArg _ hm), hr.persistent.trans hs, ?_, ?_, ?_⟩
+ · change out.reg (fieldRegs reg 2) = _
+ simpa [bits] using hr.destination
+ · intro i h₀ h₁ h₂ h₄
+ exact (hr.frame _ h₀ h₂ h₄).trans (keep _ h₁ h₄)
+ · intro fuel tail
+ dsimp only [es]
+ rw [List.length_append, show fuel+(_+_) =
+ (fuel+(PrivateFields.events (w := w) .guess bits).length)+
+ (headerEvents T m dir (c.reg (reg 5))).length by omega, head]
+ have run := pref.execute fuel m tail
+ rw [PrivateFields.events_bits] at run
+ simpa [es, Option.map_map, Function.comp_def, List.append_assoc] using congrArg
+ (Option.map (fun q : Report w ↦
+ (⟨headerEvents T m dir (c.reg (reg 5)) ++ q.events,q.result⟩ : Report w))) run
+
+/-- A truncated choice stream cannot return through a field, regardless of the
+machine's continuation. This also applies after an arbitrary prefix of old slots. -/
+theorem reject_short {a g : ℕ} (X : State a g) (u : X.network.Site) (dst : ℕ)
+ (dir : Bool) (j : Fin (2 ^ a)) (T : IncidenceDirectory w) (m : Memory w)
+ (rep : T.ActualColumns X m) {bitsPC : Fin 7 → Fin p} {ret : Fin p}
+ (hl : Linked M pc reg (bitsPC 0))
+ (hb : PrivateFields.Linked M .guess bitsPC (fieldRegs reg) ret)
+ (c : Config w p r) (hc : c.pc = entry pc dir) (hi : c.reg (reg 6) = T.actualIn)
+ (hw : c.reg (reg 7) = T.width) (hport : c.reg (reg 5) = IncidenceDirectory.actualPort X (u, j))
+ (hd : c.reg (reg 2) = (dst : Word w)) (h1 : c.reg (reg 3) = 1)
+ (fit : dst + X.halfWidth u dir j < 2 ^ w) (bs : List Bool)
+ (short : bs.length < X.halfWidth u dir j) : ¬ DFS.Returns M c m bs := by
+ obtain ⟨d, hp, he, keep, _, _, head⟩ := header hl T m dir c hc hi hw
+ rw [hport, WidthRead.value_actual X u T m rep, hd] at he
+ intro accept
+ obtain ⟨fuel,out,run⟩ := (returns_prefix (fun f ↦ head f bs)).mp accept
+ have bad := PrivateFields.guess_short hb d hp (dst)
+ (X.halfWidth u dir j)
+ ((keep _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans hd)
+ (by change d.reg (reg 1) = _; simpa [CursorRAM.encode] using he)
+ ((keep _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans h1)
+ fit bs short fuel m
+ rw [bad] at run
+ cases run
+
+end PairSimulation.NodeArguments.FieldGuess
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairOnlineLiveBudget.lean b/lean/OAI/Computability/VPVNP/PairOnlineLiveBudget.lean
new file mode 100644
index 0000000000..5755fa66cf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairOnlineLiveBudget.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.CompressorOnlineBudget
+import OAI.Computability.VPVNP.CursorBranchCommunication
+import OAI.Computability.VPVNP.PairLinkSlack
+
+/-!
+# Live caps of the online descriptor program
+
+The calendar, recipe, and data-worker calls are the reports of the
+fixed online table. Its local clock is chosen from fixed catalog
+parameters, and the global bound holds before the input assignment,
+term choices and online memory are selected.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PhaseVisits
+
+open BurstRAM Compression Schedule CursorNetwork CursorBounds Filter
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+/-- Choose a local clock covering the finite controller and worker link.
+At large input lengths all reports fit the physical burst and private
+clock, with any fixed margins for the enclosing live instruction table. -/
+theorem eventually_selectedOnline (B : S.Templates) (u : PairExponents B.growthConstant)
+ (P : Plan S) (H I q b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {d i j : ℕ} {C : Catalog d} (Q : Online.Config C i j)
+ (probeMargin tickMargin : ℕ) {ε : ℝ} (hε : 0 < ε) :
+ let K := H + 30 + 2*(i+j) + 20 + 6*(arity C+1) + 2*Online.N d (i+j) + 5
+ ∀ᶠ n : ℕ in atTop,
+ let cap := K*(n.log2+1)^q
+ let w := wordBits b n
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ ∀ (z : (B.execute f hf T hT X).Choices) (p : Ports w) (initial : List (Directory.Row d w))
+ (groups : ∀ v : SelectedLevel B f hf, LevelRows (d := d) (w := w) X.positions v)
+ (steps : List (Online.Run.Step d (i+j) w)) (m : Memory w) (state : Word w),
+ calls initial ≤ I*X.positions → Online.Run.Valid Q p cap m steps →
+ m p.tag.val = LiveStageLink.tagWord w (Online.calendarIndex d (i+j)) →
+ steps.map Online.Run.Step.row = branchRows P X.positions
+ (executeLevels B f hf T hT X z) initial groups →
+ let rs := Online.Run.reports Q p m steps
+ runSegment (Online.program Q p) cap (some state) m (Online.Run.choices steps) = some rs ∧
+ after m (eventLog rs) = Online.Run.finalMemory (C := C) p m steps ∧
+ endState (some state) rs = none ∧
+ (∀ r ∈ rs, 1+r.probes+probeMargin ≤ liveBucket u.δ n ∧ r.events.length+tickMargin ≤ n) ∧
+ (RAMBuckets.cost Report.probes rs : ℝ) < ε * processorCount b n * liveBucket u.δ n := by
+ intro K
+ let rate := (2*(I + (S.steps+1)*max 1 (slotDegree S)*P.levelRate)+1)*K
+ have hlocal := eventually_absorb_polylog (K : ℝ) q
+ (show (0 : ℝ) < 1/2 by norm_num) (show (0 : ℝ) < 1 by norm_num)
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ filter_upwards [hlocal, eventually_pairBurstSlack u (probeMargin+1),
+ BurstRAM.eventually_polylog_le (K+tickMargin) q, eventually_ge_atTop 1,
+ CursorRAM.eventual_word_room b hb' (PolynomiallyBounded.const (Online.N d (i+j))),
+ eventually_pairAccesses B u b hb rate (q+1) hε]
+ with n hlocal hburst hticks hn hfit hbudget
+ intro cap w base lanes labels hD hT A _ f hf X T z p initial groups
+ steps m state hinit valid tag rows rs
+ have hL : 1 ≤ (n.log2+1)^q := Nat.one_le_pow _ _ (Nat.succ_pos _)
+ have hcap : K ≤ cap := Nat.le_mul_of_pos_right _ hL
+ have hc := selected_online_budget B u P K I q b n hn labels hD hT f hf z Q p initial groups hinit
+ steps m state cap valid tag hfit.le (by dsimp only [K] at hcap; omega)
+ (by dsimp only [K] at hcap; omega) le_rfl rows
+ have hsmall : (cap : ℝ) ≤ (n : ℝ)^(1/2 : ℝ) := by
+ dsimp only [cap]
+ push_cast
+ simpa only [Real.rpow_zero, mul_one, one_mul] using hlocal
+ have htime : cap + tickMargin ≤ n := by
+ apply le_trans _ hticks
+ exact (Nat.add_le_add_left (Nat.le_mul_of_pos_right tickMargin hL)
+ (K*(n.log2+1)^q)).trans_eq (Nat.add_mul ..).symm
+ refine ⟨hc.1,hc.2.1,hc.2.2.1,fun r hr => ?_,?_⟩
+ · obtain ⟨he, hp⟩ := hc.2.2.2.1 r hr
+ have h : (cap : ℝ)+(probeMargin+1 : ℕ) ≤ liveBucket u.δ n :=
+ (add_le_add_left hsmall ((probeMargin+1 : ℕ) : ℝ)).trans hburst
+ have hh : cap+(probeMargin+1) ≤ liveBucket u.δ n := by exact_mod_cast h
+ omega
+ · let Y := (B.execute f hf T hT X).finalState z
+ let c := (B.execute f hf T hT X).termChain (B.records f hf T hT X) z
+ have he : rate*initialPositions b n*(n.log2+1)^(q+1) ≤ branchAccesses X Y c rate (q+1) n := by
+ rw [← pairInput_positions S labels hD]
+ unfold branchAccesses
+ apply le_trans _ (Nat.le_add_right _ _)
+ exact (Nat.mul_assoc ..).le.trans (Nat.mul_le_mul_left rate (Nat.le_add_right _ _))
+ exact (Nat.cast_le.mpr (hc.2.2.2.2.trans he)).trans_lt (hbudget labels hD hT A f hf z).1
+
+end CompressorRecords.PhaseVisits
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairOutputRowDirectory.lean b/lean/OAI/Computability/VPVNP/PairOutputRowDirectory.lean
new file mode 100644
index 0000000000..4b1b661dc4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairOutputRowDirectory.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.PairVertexLevelBounds
+
+/-!
+# Decoding the output rows of a traversal
+
+The leaf layer precedes the selected output layers. A popped word identifies
+an output row precisely when it is the header of a site of one of these
+layers. Empty layers contribute no candidates to the finite directory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.OutputRowDirectory
+
+open BurstRAM TraversalRoles TraversalRows VertexLevelBounds
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- An output row identified by a tagged output layer and a site ordinal bounded by that
+layer’s count. The traversal uses the pair to recover the absolute descriptor address. -/
+abbrev Row (outputs : List TaggedLayer) :=
+ Σ j : Fin outputs.length, Fin outputs[j].layer.count
+
+variable (cap base : ℕ) (leaf : TaggedLayer) (outputs : List TaggedLayer)
+
+/-- The site number is relative to its output layer. Layer zero of the
+physical layout holds the leaves. -/
+def rowAddress (row : Row outputs) : ℕ :=
+ address cap (layerBase cap base (leaf :: outputs) (row.1.val + 1)) row.2.val
+
+theorem rowAddress_injective : Function.Injective (rowAddress cap base leaf outputs) := by
+ rintro ⟨j, x⟩ ⟨k, y⟩ eqn
+ let start := endPos cap base leaf.layer
+ change address cap (layerBase cap base (leaf :: outputs) (j.val + 1)) x.val =
+ address cap (layerBase cap base (leaf :: outputs) (k.val + 1)) y.val at eqn
+ rw [layerBase_cons, layerBase_cons] at eqn
+ obtain ⟨lo, _, _, later, _⟩ := node_interval cap start outputs j x
+ obtain ⟨lo', _, _, later', _⟩ := node_interval cap start outputs k y
+ have same : j = k := by
+ apply Fin.ext
+ rcases lt_trichotomy j.val k.val with h | h | h
+ · exact False.elim ((later k.val h).not_ge (eqn.symm ▸ lo'))
+ · exact h
+ · exact False.elim ((later' j.val h).not_ge (eqn ▸ lo))
+ subst k
+ have sameSite : x = y :=
+ Fin.ext (Nat.eq_of_mul_eq_mul_left (by omega : 0 < cap + 2) (Nat.add_left_cancel eqn))
+ cases sameSite
+ rfl
+
+theorem rowAddress_lt_end (row : Row outputs) :
+ rowAddress cap base leaf outputs row <
+ layerBase cap base (leaf :: outputs) (outputs.length + 1) := by
+ rw [rowAddress, layerBase_cons, layerBase_cons]
+ exact (node_interval cap (endPos cap base leaf.layer) outputs row.1 row.2).2.1.trans_le
+ (layerBase_mono cap (endPos cap base leaf.layer) outputs row.1.isLt)
+
+private def rows (outputs : List TaggedLayer) : List (Row outputs) :=
+ (List.finRange outputs.length).flatMap fun j =>
+ (List.finRange outputs[j].layer.count).map (Sigma.mk j)
+
+private theorem mem_rows (row : Row outputs) : row ∈ rows outputs :=
+ List.mem_flatMap.mpr ⟨row.1, List.mem_finRange _,
+ List.mem_map.mpr ⟨row.2, List.mem_finRange _, rfl⟩⟩
+
+/-- Search the fixed row headers in level and site order using machine-word equality. -/
+def decode (node : Word w) : Option (Row outputs) :=
+ (rows outputs).find? fun row => decide (node = (rowAddress cap base leaf outputs row : Word w))
+
+variable (fit : layerBase cap base (leaf :: outputs) (outputs.length + 1) ≤ 2 ^ w)
+
+include fit
+
+/-- Each valid output header selects its unique level and site. -/
+theorem decode_eq_some_iff (node : Word w) (row : Row outputs) :
+ decode cap base leaf outputs node = some row ↔
+ node.val = rowAddress cap base leaf outputs row := by
+ have match_word (x : Row outputs) :
+ node = (rowAddress cap base leaf outputs x : Word w) ↔
+ node.val = rowAddress cap base leaf outputs x := by
+ rw [Fin.ext_iff, Fin.val_natCast,
+ Nat.mod_eq_of_lt ((rowAddress_lt_end cap base leaf outputs x).trans_le fit)]
+ constructor
+ · intro found
+ unfold decode at found
+ have hit := List.find?_some found
+ exact (match_word row).mp (of_decide_eq_true hit)
+ · intro addr
+ unfold decode
+ cases found : (rows outputs).find?
+ (fun x => decide (node = (rowAddress cap base leaf outputs x : Word w))) with
+ | none =>
+ exact False.elim ((List.find?_eq_none.mp found row (mem_rows outputs row))
+ (decide_eq_true ((match_word row).mpr addr)))
+ | some x =>
+ have hit := List.find?_some found
+ have hx := (match_word x).mp (of_decide_eq_true hit)
+ exact congrArg some (rowAddress_injective cap base leaf outputs (hx.symm.trans addr))
+
+/-- Words in the leaf region, row interiors, or beyond the directory have no output row. -/
+theorem decode_eq_none_iff (node : Word w) :
+ decode cap base leaf outputs node = none ↔
+ ∀ row, node.val ≠ rowAddress cap base leaf outputs row := by
+ constructor
+ · intro noneFound row addr
+ have found := (decode_eq_some_iff cap base leaf outputs fit node row).mpr addr
+ simp [noneFound] at found
+ · intro miss
+ cases found : decode cap base leaf outputs node with
+ | none => rfl
+ | some row =>
+ exact False.elim (miss row ((decode_eq_some_iff cap base leaf outputs fit node row).mp found))
+
+end PairSimulation.OutputRowDirectory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairPendingArguments.lean b/lean/OAI/Computability/VPVNP/PairPendingArguments.lean
new file mode 100644
index 0000000000..e4f12279e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairPendingArguments.lean
@@ -0,0 +1,212 @@
+import OAI.Computability.VPVNP.PairNodeArguments
+import OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+/-!
+# Pending arguments of the depth-first native hook
+
+The node address indexes a private argument interval. Writing a batch of
+child half-wires establishes their exact bit values, preserves distinct
+pending siblings, and leaves the DFS stack below the scratch boundary.
+The row traversal then propagates the local hook's input invariant through
+all visited addresses, including prefixes that reject.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments
+
+open BurstRAM BurstRAM.PrivateRAM DFS
+open scoped Fin.CommRing
+
+variable {w endAddr : ℕ}
+
+/-- A genuinely supplied local half-wire argument, named by its node address. -/
+structure Packet where
+ /-- Absolute DFS node address used as the index of this packet’s interval in the private
+ argument arena. -/
+ node : ℕ
+ /-- Ordered half-wire bits supplied to the node’s handler, stored one bit per word in its
+ argument interval. -/
+ bits : List Bool
+
+/-- Bounds ensuring the packet starts at or above the DFS stack boundary, occupies at most one
+arena stride and ends within the machine-word address space. -/
+def Packet.Fits (q : Packet) (A : Arena) (w endAddr : ℕ) : Prop :=
+ endAddr ≤ A.base q.node ∧ q.bits.length ≤ A.stride ∧ A.base q.node + q.bits.length ≤ 2^w
+
+/-- Extend the typed scratch to the full private word space solely for
+expressing native stores above the stack boundary. -/
+def rawScratch (s : Scratch w endAddr) (a : Word w) : Word w :=
+ if h : endAddr ≤ a.val then s ⟨a,h⟩ else 0
+
+/-- States that each addressed scratch word of the packet equals the machine-word encoding of
+the corresponding bit, beginning at the node’s arena base. -/
+def Packet.Stored (q : Packet) (A : Arena) (s : Scratch w endAddr) : Prop :=
+ ∀ i : Fin q.bits.length, rawScratch s ((A.base q.node + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w q.bits[i.val]
+
+/-- Updates scratch by storing the packet bits consecutively from its node’s arena base and
+restricting the resulting private memory to addresses at or above the stack boundary. -/
+def Packet.write (q : Packet) (A : Arena) (s : Scratch w endAddr) : Scratch w endAddr :=
+ scratch endAddr (PrivateFields.storeBits (A.base q.node) q.bits (rawScratch s))
+
+private theorem raw_write_at (q : Packet) (A : Arena) (s : Scratch w endAddr) {a : Word w}
+ (ha : endAddr ≤ a.val) : rawScratch (q.write A s) a =
+ PrivateFields.storeBits (A.base q.node) q.bits (rawScratch s) a := by
+ simp [rawScratch, Packet.write, scratch, ha]
+
+private theorem address_val (q : Packet) (A : Arena) (hq : q.Fits A w endAddr)
+ (i : Fin q.bits.length) : (((A.base q.node + i.val : ℕ) : Word w)).val = A.base q.node+i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans_le hq.2.2)
+
+theorem Packet.stored_write (q : Packet) (A : Arena) (s : Scratch w endAddr)
+ (hq : q.Fits A w endAddr) : q.Stored A (q.write A s) := by
+ intro i
+ rw [raw_write_at _ _ _ (by rw [address_val q A hq i]; exact hq.1.trans (Nat.le_add_right _ _))]
+ exact PrivateFields.storeBits_read _ _ _ hq.2.2 i
+
+theorem Packet.stored_other (q p : Packet) (A : Arena) (s : Scratch w endAddr)
+ (hq : q.Fits A w endAddr) (hp : p.Fits A w endAddr) (hne : q.node ≠ p.node)
+ (stored : p.Stored A s) : p.Stored A (q.write A s) := by
+ intro i
+ let addr := ((A.base p.node + i.val : ℕ) : Word w)
+ have hi : addr.val = A.base p.node + i.val := address_val p A hp i
+ have ha := hp.1.trans (Nat.le_add_right (A.base p.node) i.val)
+ change rawScratch (q.write A s) addr = _
+ rw [raw_write_at q A s (hi ▸ ha)]
+ have ho : addr.val < A.base q.node ∨ A.base q.node+q.bits.length ≤ addr.val := by
+ rw [hi]
+ rcases A.disjoint hne with left | right
+ · exact Or.inr ((Nat.add_le_add_left hq.2.1 _).trans (left.trans (Nat.le_add_right _ _)))
+ · exact Or.inl ((Nat.add_lt_add_left (i.isLt.trans_le hp.2.1) _).trans_le right)
+ rw [PrivateFields.storeBits_outside _ _ _ _ hq.2.2 ho]
+ exact stored i
+
+/-- The physical child writes occur in their listed order. -/
+def writePackets (A : Arena) (xs : List Packet) (s : Scratch w endAddr) : Scratch w endAddr :=
+ xs.foldl (fun old p => p.write A old) s
+
+theorem writePackets_preserves (A : Arena) (xs : List Packet) (p : Packet) (s : Scratch w endAddr)
+ (hf : ∀ q ∈ xs, q.Fits A w endAddr) (hp : p.Fits A w endAddr)
+ (hne : ∀ q ∈ xs, q.node ≠ p.node) (h : p.Stored A s) :
+ p.Stored A (writePackets A xs s) := by
+ induction xs generalizing s with
+ | nil => exact h
+ | cons q qs ih =>
+ exact ih _ (fun j hj => hf j (List.mem_cons_of_mem _ hj))
+ (fun j hj => hne j (List.mem_cons_of_mem _ hj))
+ (q.stored_other p A s (hf q List.mem_cons_self) hp (hne q List.mem_cons_self) h)
+
+/-- Distinct child records retain every bit value assigned to them. -/
+theorem writePackets_children (A : Arena) (xs : List Packet) (s : Scratch w endAddr)
+ (hf : ∀ q ∈ xs, q.Fits A w endAddr) (hn : (xs.map Packet.node).Nodup) :
+ ∀ q ∈ xs, q.Stored A (writePackets A xs s) := by
+ induction xs generalizing s with
+ | nil => simp
+ | cons q qs ih =>
+ rw [List.map_cons, List.nodup_cons] at hn
+ intro p hp
+ rcases List.mem_cons.mp hp with rfl | mem
+ · exact writePackets_preserves A qs p _ (fun j hj => hf j (List.mem_cons_of_mem _ hj))
+ (hf p List.mem_cons_self) (fun j hj he => hn.1 (he ▸ List.mem_map_of_mem hj))
+ (p.stored_write A s (hf p List.mem_cons_self))
+ · exact ih _ (fun j hj => hf j (List.mem_cons_of_mem _ hj)) hn.2 p mem
+
+/-- Other private work may change the histogram or scratch tables. Matching
+the packet's own addressed words is sufficient to retain its arguments. -/
+theorem Packet.Stored.congr {q : Packet} {A : Arena} {s t : Scratch w endAddr}
+ (h : q.Stored A s) (eqn : ∀ i : Fin q.bits.length,
+ rawScratch t ((A.base q.node + i.val : ℕ) : Word w) =
+ rawScratch s ((A.base q.node + i.val : ℕ) : Word w)) : q.Stored A t :=
+ fun i => (eqn i).trans (h i)
+
+/-- Ghost values of all current argument frames. The predicate on packets
+specifies the node's actual half-wire format while retaining all its bit values. -/
+def PreparedPackets (A : Arena) (format : Packet → Prop) (xs : List Packet)
+ (s : Scratch w endAddr) : Prop :=
+ (xs.map Packet.node).Nodup ∧ ∀ q ∈ xs, format q ∧ q.Fits A w endAddr ∧ q.Stored A s
+
+/-- Replace the popped argument by its ordered children. The physical
+argument cells of every child and every older pending sibling agree with
+the corresponding logical half-wire packet after the native update. -/
+theorem preparedPackets_push (A : Arena) (format : Packet → Prop) (head : Packet)
+ (children pending : List Packet) (s out : Scratch w endAddr)
+ (before : PreparedPackets A format (head::pending) s)
+ (valid : ∀ q ∈ children, format q ∧ q.Fits A w endAddr)
+ (nodup : ((children ++ pending).map Packet.node).Nodup)
+ (agree : ∀ q ∈ children ++ pending, ∀ i : Fin q.bits.length,
+ rawScratch out ((A.base q.node + i.val : ℕ) : Word w) =
+ rawScratch (writePackets A children s) ((A.base q.node + i.val : ℕ) : Word w)) :
+ PreparedPackets A format (children ++ pending) out := by
+ rw [List.map_append, List.nodup_append] at nodup
+ refine ⟨by simpa only [List.map_append, List.nodup_append] using nodup, ?_⟩
+ intro q hq
+ have hwrite := fun p hp => (valid p hp).2
+ rcases List.mem_append.mp hq with child | sibling
+ · obtain ⟨hf,hfit⟩ := valid q child
+ exact ⟨hf,hfit,(writePackets_children A children s hwrite nodup.1 q child).congr (agree q hq)⟩
+ · obtain ⟨hf,hfit,hs⟩ := before.2 q (List.mem_cons_of_mem _ sibling)
+ have sep : ∀ p ∈ children, p.node ≠ q.node := fun p hp eqn =>
+ nodup.2.2 p.node (List.mem_map_of_mem hp) q.node (List.mem_map_of_mem sibling) eqn
+ exact ⟨hf,hfit,(writePackets_preserves A children q s hwrite hfit sep hs).congr (agree q hq)⟩
+
+end PairSimulation.NodeArguments
+
+namespace PairSimulation.DFS
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+/-- A node's completed local hook establishes the invariant on the recorded
+children and preserves it on the existing stack suffix. No reachability
+requirement is imposed on unrelated scratch cells. -/
+def HookParser.PreparesChildren {w endAddr : ℕ} (P : HookParser w endAddr)
+ (domain : Word w → Scratch w endAddr → Prop) (m : Memory w) : Prop :=
+ ∀ (node : Word w) src kids pending (s : Scratch w endAddr) bs job tail,
+ Row m node.val src kids → (∀ j ∈ node :: pending, domain j s) →
+ P.read node s bs = some (job,tail) → ∀ j ∈ kids ++ pending, domain j (job.update s)
+
+/-- A prepared frontier may contain node-specific argument values, stack
+separation and histogram information shared by its pending vertices. -/
+def HookParser.PreparesFrontier {w endAddr : ℕ} (P : HookParser w endAddr)
+ (domain : Word w → Scratch w endAddr → Prop)
+ (valid : List (Word w) → Scratch w endAddr → Prop) (m : Memory w) : Prop :=
+ ∀ node pending s, valid (node :: pending) s → domain node s ∧
+ ∀ src kids bs job tail, Row m node.val src kids → P.read node s bs = some (job,tail) →
+ valid (kids ++ pending) (job.update s)
+
+/-- The admissibility of actual hook calls can use the whole current
+frontier, including the distinctness of unprocessed sibling buffers. -/
+theorem HookParser.validAlong_of_frontier {w endAddr : ℕ} (P : HookParser w endAddr)
+ {domain : Word w → Scratch w endAddr → Prop}
+ {valid : List (Word w) → Scratch w endAddr → Prop} {m : Memory w}
+ {pending nodes : List (Word w)} {es : List (Event w)}
+ (visits : Visits m endAddr pending nodes es) (prep : P.PreparesFrontier domain valid m)
+ (s : Scratch w endAddr) (bs : List Bool) (hs : valid pending s) :
+ P.ValidAlong domain nodes s bs := by
+ induction visits generalizing s bs with
+ | nil => trivial
+ | @cons node pending kids nodes src es row fits rest ih =>
+ obtain ⟨head, tail⟩ := prep node pending s hs
+ exact ⟨head, fun job suffix hread => ih _ _ (tail src kids bs job suffix row hread)⟩
+
+/-- Follow the concrete chronological DFS. Every hook is entered on its
+prepared argument cells, for every possible remaining binary stream. -/
+theorem HookParser.validAlong_of_visits {w endAddr : ℕ} (P : HookParser w endAddr)
+ {domain : Word w → Scratch w endAddr → Prop} {m : Memory w}
+ {pending nodes : List (Word w)} {es : List (Event w)}
+ (visits : Visits m endAddr pending nodes es)
+ (hchild : P.PreparesChildren domain m) (s : Scratch w endAddr) (bs : List Bool)
+ (hroot : ∀ j ∈ pending, domain j s) : P.ValidAlong domain nodes s bs := by
+ exact P.validAlong_of_frontier visits
+ (valid := fun pending s => ∀ j ∈ pending, domain j s)
+ (fun node pending s h => ⟨h node List.mem_cons_self, fun src kids bs job tail row hread =>
+ hchild node src kids pending s bs job tail row h hread⟩) s bs hroot
+
+end PairSimulation.DFS
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRAMCounterReadback.lean b/lean/OAI/Computability/VPVNP/PairRAMCounterReadback.lean
new file mode 100644
index 0000000000..a22070bd81
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRAMCounterReadback.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.PairRAMDegreeBudget
+import OAI.Computability.VPVNP.PairSimulationAssembly
+import OAI.Computability.VPVNP.PairSimulationCounters
+
+/-!
+# Reading the complete compressed pair's exponent array
+
+The final vertex histograms use the descriptor order of the actual repeated
+compressor. Adding them to the shared suffix gives the monomial exponents
+in its template alphabet. The prefix holds the nominated production counts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open Compression CursorRouting NetworkKernel BurstRAM BurstRAM.PrivateRAM CursorBounds Filter
+open PairSimulation PairSimulation.LocalHistory
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+variable (u : PairExponents B.growthConstant) {b n : ℕ} (hD : 1 < virtualBits b n)
+variable (cap : ProcessorBudget n (virtualBits b n) (roundedUp 1 4 n) (wordBits b n))
+variable {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+variable (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+variable {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+variable {p r k' : ℕ} (M : Machine (wordBits b n) p r k')
+variable (fuel : ℕ) (initial : Word (wordBits b n))
+variable (header : ℕ → Word (wordBits b n))
+
+/-- Per-vertex template histograms for the chosen virtual fuel, in final-site order. -/
+noncomputable def pairRAMHistogramsWithFuel
+ (c : (pairRAMCountWithFuel B u hD cap labels hT f hf M fuel initial header).Choice) :
+ List (B.Entry → ℕ) := by
+ letI : NeZero (virtualBits b n) := ⟨by omega⟩
+ let pad := Nat.add_sub_of_le S.degree_bounds.1
+ let X := cursorState labels hD pad (ramFieldBits (2 ^ roundedUp 1 4 n) (wordBits b n) :
+ RAMSystem (virtualBits b n) → ℕ)
+ let P := cursorSiteParsers M fuel initial header cap.tags cap.capFits labels hD pad f
+ exact Counters.vertexHistograms _ _ (executeReaders B f hf _ hT X) P.factors P.witnesses c
+
+/-- Per-vertex template histograms, ordered by the actual final-site descriptors. -/
+noncomputable abbrev pairRAMHistograms
+ (c : (pairRAMCount B u hD cap labels hT f hf M initial header).Choice) :
+ List (B.Entry → ℕ) :=
+ pairRAMHistogramsWithFuel B u hD cap labels hT f hf M (n^10) initial header c
+
+private theorem twoAddressBits_le_wordBits (b n : ℕ) : 2 * addressBits b n ≤ wordBits b n := by
+ change 2 * addressBits b n ≤ (addressBits b n + 10)^4
+ calc
+ _ ≤ (addressBits b n + 10)^2 := by nlinarith [Nat.zero_le (addressBits b n * addressBits b n)]
+ _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide)
+
+/-- At arbitrary fuel, the ordered visits recover both parts of the live exponent array. -/
+theorem pairRAMHistogramsWithFuel_readback
+ (c : (pairRAMCountWithFuel B u hD cap labels hT f hf M fuel initial header).Choice)
+ (degree : (∑ l, (pairRAMCountWithFuel B u hD cap labels hT f hf M fuel initial header).exponents
+ c l) < 2 ^ (2 * addressBits b n))
+ {g grammar : ℕ} (order : Fin g ≃ B.Entry) (addr : Word (wordBits b n))
+ (fit : addr.val + grammar ≤ 2 ^ wordBits b n) (μ : Fin grammar → Word (2 * addressBits b n))
+ (m : Memory (wordBits b n)) (hz : ∀ i : Fin g, m (addr.val + grammar + i) = 0)
+ (j : Fin (grammar + g)) :
+ let W := pairRAMCountWithFuel B u hD cap labels hT f hf M fuel initial header
+ let hist := pairRAMHistogramsWithFuel B u hD cap labels hT f hf M fuel initial header c
+ let final := Counters.visit addr.val grammar (fun (h : B.Entry → ℕ) i => h (order i)) hist
+ (LiveNominations.stored addr fit μ m)
+ (final (addr.val + j)).val =
+ Fin.addCases (fun i => (μ i).val) (fun i => W.exponents c (order i)) j := by
+ let inst : NeZero (virtualBits b n) := ⟨by omega⟩
+ let pad := Nat.add_sub_of_le S.degree_bounds.1
+ let X := cursorState labels hD pad (ramFieldBits (2 ^ roundedUp 1 4 n) (wordBits b n) :
+ RAMSystem (virtualBits b n) → ℕ)
+ let P := cursorSiteParsers M fuel initial header cap.tags cap.capFits labels hD pad f
+ apply Counters.live_array_readback _ _ (executeReaders B f hf _ hT X) P.factors P.witnesses
+ c order addr fit μ m hz (twoAddressBits_le_wordBits b n) _ j
+ rw [← pow_mul, Nat.mul_comm (addressBits b n) 2]
+ exact degree
+
+/-- The actual ordered visits recover both parts of the live exponent array. -/
+theorem pairRAMHistograms_readback
+ (c : (pairRAMCount B u hD cap labels hT f hf M initial header).Choice)
+ (degree : (∑ l, (pairRAMCount B u hD cap labels hT f hf M initial header).exponents c l) <
+ 2 ^ (2 * addressBits b n))
+ {g grammar : ℕ} (order : Fin g ≃ B.Entry) (addr : Word (wordBits b n))
+ (fit : addr.val + grammar ≤ 2 ^ wordBits b n) (μ : Fin grammar → Word (2 * addressBits b n))
+ (m : Memory (wordBits b n)) (hz : ∀ i : Fin g, m (addr.val + grammar + i) = 0)
+ (j : Fin (grammar + g)) :
+ let W := pairRAMCount B u hD cap labels hT f hf M initial header
+ let hist := pairRAMHistograms B u hD cap labels hT f hf M initial header c
+ let final := Counters.visit addr.val grammar (fun (h : B.Entry → ℕ) i => h (order i)) hist
+ (LiveNominations.stored addr fit μ m)
+ (final (addr.val + j)).val =
+ Fin.addCases (fun i => (μ i).val) (fun i => W.exponents c (order i)) j :=
+ pairRAMHistogramsWithFuel_readback B u hD cap labels hT f hf M (n^10) initial header
+ c degree order addr fit μ m hz j
+
+/-- For the paper's virtual dimensions, the final counter array
+recovers the two histograms simultaneously for all programs, fuel choices, headers and paths. -/
+theorem eventually_pairRAMHistogramsWithFuel_readback (b : ℕ) (hb : max S.laneBits 5 ≤ b) :
+ ∀ᶠ n : ℕ in atTop, ∃ hD : 1 < virtualBits b n,
+ ∃ cap : ProcessorBudget n (virtualBits b n) (roundedUp 1 4 n) (wordBits b n),
+ blockCount (u.θ : ℝ) n * S.laneBits ≤ virtualBits b n ∧
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {p r k' : ℕ} (M : Machine (wordBits b n) p r k') (fuel : ℕ)
+ (initial : Word (wordBits b n))
+ (header : ℕ → Word (wordBits b n)),
+ let W := pairRAMCountWithFuel B u hD cap labels hT f hf M fuel initial header
+ ∀ (c : W.Choice) {g grammar : ℕ} (order : Fin g ≃ B.Entry) (addr : Word (wordBits b n))
+ (fit : addr.val + grammar ≤ 2 ^ wordBits b n)
+ (μ : Fin grammar → Word (2 * addressBits b n)) (m : Memory (wordBits b n)),
+ (∀ i : Fin g, m (addr.val + grammar + i) = 0) → ∀ j : Fin (grammar + g),
+ let hist := pairRAMHistogramsWithFuel B u hD cap labels hT f hf M fuel initial header c
+ let final := Counters.visit addr.val grammar (fun (h : B.Entry → ℕ) i => h (order i))
+ hist (LiveNominations.stored addr fit μ m)
+ (final (addr.val + j)).val =
+ Fin.addCases (fun i => (μ i).val) (fun i => W.exponents c (order i)) j := by
+ filter_upwards [eventually_pairRAMCountWithFuel_degree B u b hb] with n h
+ obtain ⟨hD, cap, hl, h⟩ := h
+ refine ⟨hD, cap, hl, ?_⟩
+ intro base lanes labels hT A _ f hf p r k' M fuel initial header W c
+ g grammar order addr fit μ m hz j
+ exact pairRAMHistogramsWithFuel_readback B u hD cap labels hT f hf M fuel initial header c
+ (h labels hT A f hf M fuel initial header c) order addr fit μ m hz j
+
+/-- For the paper's virtual dimensions and clock, the final counter array
+recovers the two histograms simultaneously for all programs, headers and paths. -/
+theorem eventually_pairRAMHistograms_readback (b : ℕ) (hb : max S.laneBits 5 ≤ b) :
+ ∀ᶠ n : ℕ in atTop, ∃ hD : 1 < virtualBits b n,
+ ∃ cap : ProcessorBudget n (virtualBits b n) (roundedUp 1 4 n) (wordBits b n),
+ blockCount (u.θ : ℝ) n * S.laneBits ≤ virtualBits b n ∧
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {p r k' : ℕ} (M : Machine (wordBits b n) p r k') (initial : Word (wordBits b n))
+ (header : ℕ → Word (wordBits b n)),
+ let W := pairRAMCount B u hD cap labels hT f hf M initial header
+ ∀ (c : W.Choice) {g grammar : ℕ} (order : Fin g ≃ B.Entry) (addr : Word (wordBits b n))
+ (fit : addr.val + grammar ≤ 2 ^ wordBits b n)
+ (μ : Fin grammar → Word (2 * addressBits b n)) (m : Memory (wordBits b n)),
+ (∀ i : Fin g, m (addr.val + grammar + i) = 0) → ∀ j : Fin (grammar + g),
+ let hist := pairRAMHistograms B u hD cap labels hT f hf M initial header c
+ let final := Counters.visit addr.val grammar (fun (h : B.Entry → ℕ) i => h (order i))
+ hist (LiveNominations.stored addr fit μ m)
+ (final (addr.val + j)).val =
+ Fin.addCases (fun i => (μ i).val) (fun i => W.exponents c (order i)) j := by
+ filter_upwards [eventually_pairRAMHistogramsWithFuel_readback B u b hb] with n h
+ obtain ⟨hD, cap, hl, h⟩ := h
+ refine ⟨hD, cap, hl, ?_⟩
+ intro base lanes labels hT A _ f hf p r k' M initial header
+ exact h labels hT A f hf M (n^10) initial header
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRAMDegreeBudget.lean b/lean/OAI/Computability/VPVNP/PairRAMDegreeBudget.lean
new file mode 100644
index 0000000000..96b1b8db3f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRAMDegreeBudget.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.CompressedRAMDegree
+import OAI.Computability.VPVNP.CursorBranchBudget
+import OAI.Computability.VPVNP.RAMApplications
+
+/-!
+# The exponent-field bound for the virtual RAM
+
+For all sufficiently large input lengths, every witness of the compressed
+virtual path count has total parameter degree below the capacity of a
+two-address-width word. The threshold precedes the choice of ring, parameter
+assignment, virtual program, fuel, header, and path.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open Compression CursorRouting NetworkKernel BurstRAM BurstRAM.PrivateRAM CursorBounds Filter
+
+variable {k : Type*} [Field k] {S : BlockSchedule k}
+
+section Count
+
+variable (B : S.Templates) (u : PairExponents B.growthConstant) {b n : ℕ}
+variable (hD : 1 < virtualBits b n)
+variable (cap : ProcessorBudget n (virtualBits b n) (roundedUp 1 4 n) (wordBits b n))
+variable {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+variable (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+variable {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+variable {p r k' : ℕ} (M : Machine (wordBits b n) p r k') (fuel : ℕ)
+variable (initial : Word (wordBits b n)) (header : ℕ → Word (wordBits b n))
+
+/-- Equation (12.2) at the virtual site count and quarter-power bucket,
+with a specified virtual private fuel. -/
+noncomputable def pairRAMCountWithFuel :
+ MonomialWitness f (Nat.card (ActualPaths M.program fuel initial
+ (RAMMemory.initialMemory (2 ^ virtualBits b n) header)
+ (withinCaps (2 ^ virtualBits b n) (2 ^ roundedUp 1 4 n))) : A) := by
+ letI : NeZero (virtualBits b n) := ⟨by omega⟩
+ exact compressedRAMCount B f hf M fuel initial header cap.tags cap.capFits labels hD _ hT
+
+/-- Equation (12.2) at the paper's virtual private fuel. -/
+noncomputable abbrev pairRAMCount :=
+ pairRAMCountWithFuel B u hD cap labels hT f hf M (n^10) initial header
+
+end Count
+
+/-- One eventual threshold gives the virtual address and bucket capacities
+and the strict exponent bound for every branch, simultaneously over all fuel choices. -/
+theorem eventually_pairRAMCountWithFuel_degree (B : S.Templates)
+ (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) :
+ ∀ᶠ n : ℕ in atTop, ∃ hD : 1 < virtualBits b n,
+ ∃ cap : ProcessorBudget n (virtualBits b n) (roundedUp 1 4 n) (wordBits b n),
+ blockCount (u.θ : ℝ) n * S.laneBits ≤ virtualBits b n ∧
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {p r k' : ℕ} (M : Machine (wordBits b n) p r k') (fuel : ℕ)
+ (initial : Word (wordBits b n))
+ (header : ℕ → Word (wordBits b n)),
+ let W := pairRAMCountWithFuel B u hD cap labels hT f hf M fuel initial header
+ ∀ c : W.Choice, (∑ l, W.exponents c l) < 2 ^ (2 * addressBits b n) := by
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ filter_upwards [eventually_pairBranchBounds B u b hb,
+ eventually_bothProcessorBudgets hb' (show (0 : ℝ) ≤ 0 from le_rfl) zero_le_one] with n h caps
+ obtain ⟨hD, hl, h⟩ := h
+ refine ⟨hD, caps.2, hl, ?_⟩
+ intro base lanes labels hT A _ f hf p r k' M fuel initial header W c
+ let inst : NeZero (virtualBits b n) := ⟨by omega⟩
+ obtain ⟨z, hz⟩ := compressedRAMCount_degree B f hf M fuel initial header
+ caps.2.tags caps.2.capFits labels hD _ hT c
+ have hbranch := h labels hD hT A f hf
+ have hbucket : virtualBucket n = 2 ^ roundedUp 1 4 n := by
+ simp only [virtualBucket, roundedUp_eq, Nat.cast_one, Nat.cast_ofNat]
+ unfold pairInput at hbranch
+ rw [hbucket] at hbranch
+ exact hz.trans_lt (hbranch z).2.2.2.2.2.2.2
+
+/-- One eventual threshold gives the virtual address and bucket capacities
+and the strict exponent bound for every branch, at fuel (n^{10}). -/
+theorem eventually_pairRAMCount_degree (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) :
+ ∀ᶠ n : ℕ in atTop, ∃ hD : 1 < virtualBits b n,
+ ∃ cap : ProcessorBudget n (virtualBits b n) (roundedUp 1 4 n) (wordBits b n),
+ blockCount (u.θ : ℝ) n * S.laneBits ≤ virtualBits b n ∧
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {p r k' : ℕ} (M : Machine (wordBits b n) p r k') (initial : Word (wordBits b n))
+ (header : ℕ → Word (wordBits b n)),
+ let W := pairRAMCount B u hD cap labels hT f hf M initial header
+ ∀ c : W.Choice, (∑ l, W.exponents c l) < 2 ^ (2 * addressBits b n) := by
+ filter_upwards [eventually_pairRAMCountWithFuel_degree B u b hb] with n h
+ obtain ⟨hD, cap, hl, h⟩ := h
+ refine ⟨hD, cap, hl, ?_⟩
+ intro base lanes labels hT A _ f hf p r k' M initial header
+ exact h labels hT A f hf M (n^10) initial header
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshDiagonal.lean b/lean/OAI/Computability/VPVNP/PairRefreshDiagonal.lean
new file mode 100644
index 0000000000..6439e76c31
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshDiagonal.lean
@@ -0,0 +1,244 @@
+import OAI.Computability.VPVNP.PairSimulationMapConsistency
+import OAI.Computability.VPVNP.PairSimulationPrivateFields
+import OAI.Computability.VPVNP.DegreeRefreshMotif
+
+/-!
+# Testing the two diagonal ties in a refresh kernel
+
+At a port the outgoing old half is compared to its outgoing external
+segment, and the incoming external segment to the incoming old half. The
+widths of these two comparisons can differ. Both use the same discrepancy
+mask, so success means every bit of both ties agrees.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshDiagonal
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Embed the seven bit-comparison loop registers into the ten registers of the two-sided
+diagonal test. -/
+def loopRegs (reg : Fin 10 ↪ Fin r) : Fin 7 ↪ Fin r := (Fin.castLEEmb (by decide)).trans reg
+
+/-- Registers 0,1,2 give the first left cursor, exclusive left end and
+right cursor. Registers 7,8,9 give the second triple. -/
+def control (pc first second : Fin 7 → Fin p) (reg : Fin 10 ↪ Fin r) (yes no : Fin p) :
+ Fin 7 → Instr w p r k :=
+ ![.constant (reg 3) 1 (pc 1), .constant (reg 4) 0 (first 0),
+ .copy (reg 0) (reg 7) (pc 3), .copy (reg 1) (reg 8) (pc 4),
+ .copy (reg 2) (reg 9) (second 0), .constant (reg 5) 0 (pc 6),
+ .jumpEq (reg 4) (reg 5) yes no]
+
+/-- The installed control code links the two comparison scans to their return labels before
+branching on the accumulated mismatch flag. -/
+structure Linked (M : Machine w p r k) (pc first second : Fin 7 → Fin p)
+ (reg : Fin 10 ↪ Fin r) (yes no : Fin p) : Prop where
+ head : ∀ j, M.code (pc j) = control pc first second reg yes no j
+ firstScan : MapConsistency.Linked M first (loopRegs reg) (pc 2)
+ secondScan : MapConsistency.Linked M second (loopRegs reg) (pc 5)
+
+variable {M : Machine w p r k} {pc first second : Fin 7 → Fin p} {reg : Fin 10 ↪ Fin r}
+variable {yes no : Fin p}
+
+private theorem step_at (h : Linked M pc first second reg yes no) (j : Fin 7) (c : Config w p r)
+ (hc : c.pc = pc j) :
+ M.program.step c = (control pc first second reg yes no j).run M.publicData c := by
+ simp [Machine.program, hc, h.head j]
+
+/-- Private starts of the two old halves and their corresponding external
+segments. The lengths belong to the original, independent half-wires. -/
+structure Pointers (w : ℕ) where
+ /-- Private start address of the old outgoing half-word. -/
+ oldOut : Word w
+ /-- Private start address of the outgoing segment against which the old outgoing half is
+ checked. -/
+ externalOut : Word w
+ /-- Private start address of the old incoming half-word. -/
+ oldIn : Word w
+ /-- Private start address of the incoming segment against which the old incoming half is
+ checked. -/
+ externalIn : Word w
+
+/-- Register layout at entry to the two diagonal scans. -/
+def Pointers.Ready (a : Pointers w) (reg : Fin 10 ↪ Fin r) (c : Config w p r)
+ (outWidth inWidth : ℕ) : Prop :=
+ (c.reg (reg 0) = a.oldOut ∧ c.reg (reg 1) = a.oldOut + (outWidth : Word w) ∧
+ c.reg (reg 2) = a.externalOut) ∧
+ (c.reg (reg 7) = a.oldIn ∧ c.reg (reg 8) = a.oldIn + (inWidth : Word w) ∧
+ c.reg (reg 9) = a.externalIn)
+
+/-- A pair of equally long bit fields in private memory. -/
+structure Tie (w n : ℕ) where
+ /-- Private read cursor for the original half-word in this diagonal tie. -/
+ left : Word w
+ /-- Private read cursor for the segment paired with that half-word. -/
+ right : Word w
+ /-- The independent bits of the original half-word that the comparison must read. -/
+ oldBits : Fin n → Bool
+ /-- Bits of the selected segment that are compared with the corresponding old half-word. -/
+ segmentBits : Fin n → Bool
+
+/-- Both private ranges contain the encoded bits specified for this tie, in increasing bit
+order. -/
+def Tie.resident {n : ℕ} (b : Tie w n) (mem : Word w → Word w) : Prop :=
+ (∀ j, mem (b.left + (j.val : Word w)) = PrivateFields.bitValue w (b.oldBits j)) ∧
+ ∀ j, mem (b.right + (j.val : Word w)) = PrivateFields.bitValue w (b.segmentBits j)
+
+private theorem bit_agrees {n : ℕ} (x y : Fin n → Bool) (hn : n < 2^w) :
+ (∀ j, PrivateFields.bitValue w (x j) = PrivateFields.bitValue w (y j)) ↔ x = y := by
+ constructor
+ · intro h
+ funext j
+ have hw : 1 < 2^w := by have := j.isLt; omega
+ have hone : (1 : Word w) ≠ 0 := by
+ intro e
+ have hv := congrArg Fin.val e
+ change 1 % (2^w) = 0 at hv
+ rw [Nat.mod_eq_of_lt hw] at hv
+ omega
+ have he := h j
+ cases hx : x j <;> cases hy : y j <;> simp_all [PrivateFields.bitValue]
+ · rintro rfl; exact fun _ ↦ rfl
+
+/-- Execute both comparisons, even if the first one fails. The input may
+contain any independent old and new halves, including empty fields. -/
+theorem compare (h : Linked M pc first second reg yes no)
+ {n₁ n₂ : ℕ} (a : Tie w n₁) (b : Tie w n₂) (c : Config w p r) (hc : c.pc = pc 0)
+ (ha : c.reg (reg 0) = a.left ∧ c.reg (reg 1) = a.left + (n₁ : Word w) ∧ c.reg (reg 2) = a.right)
+ (hb : c.reg (reg 7) = b.left ∧ c.reg (reg 8) = b.left + (n₂ : Word w) ∧ c.reg (reg 9) = b.right)
+ (hm₁ : a.resident c.privateMem) (hm₂ : b.resident c.privateMem)
+ (hn₁ : n₁ < 2^w) (hn₂ : n₂ < 2^w) :
+ ∃ out, Prefix M c (List.replicate (7*(n₁+n₂)+9) .tick) out ∧
+ out.pc = (if a.oldBits = a.segmentBits ∧ b.oldBits = b.segmentBits then yes else no) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ ∀ j, j ∉ Set.range reg → out.reg j = c.reg j := by
+ classical
+ let c₁ := c.put (pc 1) (reg 3) 1
+ let a₀ := c₁.put (first 0) (reg 4) 0
+ have e₀ : M.program.step c = .localStep c₁ := step_at h 0 c hc
+ have e₁ : M.program.step c₁ = .localStep a₀ := step_at h 1 c₁ rfl
+ have start : Prefix M c (List.replicate 2 .tick) a₀ := .tick e₀ (.tick e₁ (.nil _))
+ obtain ⟨mid, sa, pm, _, _, maskA, keepA, memA, stateA⟩ := MapConsistency.compareArrays h.firstScan
+ (fun j ↦ PrivateFields.bitValue w (a.oldBits j)) (fun j ↦ PrivateFields.bitValue w (a.segmentBits j))
+ a.left a.right a₀ rfl
+ (by simpa [a₀,c₁,Config.put,loopRegs] using ha.1)
+ (by simpa [a₀,c₁,Config.put,loopRegs] using ha.2.1)
+ (by simpa [a₀,c₁,Config.put,loopRegs] using ha.2.2)
+ (by simp [a₀,c₁,Config.put,loopRegs]) hn₁ hm₁.1 hm₁.2
+ have hm : mid.reg (reg 4) = 0 ↔ a.oldBits = a.segmentBits := by
+ simpa [a₀,c₁,Config.put,loopRegs,bit_agrees a.oldBits a.segmentBits hn₁] using maskA
+ have keep (j : Fin 10) (hj : j = 3 ∨ 7 ≤ j.val) : mid.reg (reg j) = a₀.reg (reg j) := by
+ apply keepA
+ all_goals
+ intro he
+ have hv := congrArg Fin.val (reg.injective he)
+ norm_num [Fin.castLEEmb] at hv
+ rcases hj with rfl | hj <;> omega
+ have h7 : mid.reg (reg 7) = b.left := by rw [keep 7 (by decide)]; simpa [a₀,c₁,Config.put] using hb.1
+ have h8 : mid.reg (reg 8) = b.left + (n₂ : Word w) := by rw [keep 8 (by decide)]; simpa [a₀,c₁,Config.put] using hb.2.1
+ have h9 : mid.reg (reg 9) = b.right := by rw [keep 9 (by decide)]; simpa [a₀,c₁,Config.put] using hb.2.2
+ let c₂ := mid.put (pc 3) (reg 0) (mid.reg (reg 7))
+ let c₃ := c₂.put (pc 4) (reg 1) (c₂.reg (reg 8))
+ let b₀ := c₃.put (second 0) (reg 2) (c₃.reg (reg 9))
+ have e₂ : M.program.step mid = .localStep c₂ := step_at h 2 mid pm
+ have e₃ : M.program.step c₂ = .localStep c₃ := step_at h 3 c₂ rfl
+ have e₄ : M.program.step c₃ = .localStep b₀ := step_at h 4 c₃ rfl
+ have reload : Prefix M mid (List.replicate 3 .tick) b₀ := .tick e₂ (.tick e₃ (.tick e₄ (.nil _)))
+ have hm₂' : b.resident b₀.privateMem := by
+ change b.resident mid.privateMem
+ rw [memA]
+ exact hm₂
+ obtain ⟨fin, sb, pf, _, _, maskB, keepB, memB, stateB⟩ := MapConsistency.compareArrays h.secondScan
+ (fun j ↦ PrivateFields.bitValue w (b.oldBits j)) (fun j ↦ PrivateFields.bitValue w (b.segmentBits j))
+ b.left b.right b₀ rfl (by simp [b₀,c₃,c₂,Config.put,loopRegs,h7])
+ (by simp [b₀,c₃,c₂,Config.put,loopRegs,h8]) (by simp [b₀,c₃,c₂,Config.put,loopRegs,h9])
+ (by simp [b₀,c₃,c₂,a₀,c₁,Config.put,loopRegs,keep 3 (by decide)]) hn₂ hm₂'.1 hm₂'.2
+ have hm' : fin.reg (reg 4) = 0 ↔ a.oldBits = a.segmentBits ∧ b.oldBits = b.segmentBits := by
+ simpa [b₀,c₃,c₂,Config.put,loopRegs,hm,bit_agrees b.oldBits b.segmentBits hn₂] using maskB
+ let t := fin.put (pc 6) (reg 5) 0
+ let out := {t with pc := if a.oldBits = a.segmentBits ∧ b.oldBits = b.segmentBits then yes else no}
+ have e₅ : M.program.step fin = .localStep t := step_at h 5 fin pf
+ have e₆ : M.program.step t = .localStep out := by
+ rw [step_at h 6 t rfl]
+ simp [control, Instr.run, t, Config.put, out, hm']
+ have finish : Prefix M fin (List.replicate 2 .tick) out := .tick e₅ (.tick e₆ (.nil _))
+ refine ⟨out, ?_, rfl, memB.trans memA, stateB.trans stateA, ?_⟩
+ · convert (((start.append sa).append reload).append sb).append finish using 1
+ simp only [← List.replicate_add]
+ congr 1
+ omega
+ · intro j hj
+ have hn (k : Fin 10) : j ≠ reg k := fun he ↦ hj ⟨k, he.symm⟩
+ have hb' := keepB j (hn 0) (hn 2) (hn 4) (hn 5) (hn 6)
+ have ha' := keepA j (hn 0) (hn 2) (hn 4) (hn 5) (hn 6)
+ simpa [out,t,b₀,c₃,c₂,a₀,c₁,Config.put,hn] using hb'.trans
+ ((by simp [b₀,c₃,c₂,Config.put,hn] : b₀.reg j = mid.reg j).trans ha')
+
+/-- The concrete instruction layout. The first two labels are the accepting
+and rejecting exits. The three seven-instruction blocks are control and the
+two private array comparisons. -/
+def label (block : Fin 3) (j : Fin 7) : Fin 23 := (finProdFinEquiv (block, j)).natAdd 2
+
+/-- Resizable 23-instruction diagonal test with two seven-instruction bit scans and distinct
+accept and reject exits. -/
+def table : Template 23 10 0 where
+ literalWidth := 1
+ entry := label 0 0
+ code := Fin.addCases (m := 2) (n := 21) (fun i ↦ if i.val = 0 then .accept else .reject)
+ fun q ↦
+ let z : Fin 3 × Fin 7 := finProdFinEquiv.symm q
+ let reg := Function.Embedding.refl (Fin 10)
+ if z.1 = 0 then control (label 0) (label 1) (label 2) reg 0 1 z.2
+ else if z.1 = 1 then MapConsistency.instruction (label 1) (loopRegs reg) (label 0 2) z.2
+ else MapConsistency.instruction (label 2) (loopRegs reg) (label 0 5) z.2
+
+theorem table_linked (w : ℕ) : Linked (table.instantiate w Fin.elim0)
+ (label 0) (label 1) (label 2) (Function.Embedding.refl (Fin 10)) 0 1 := by
+ constructor
+ · intro j
+ fin_cases j <;> rfl
+ · intro j
+ fin_cases j <;> rfl
+ · intro j
+ fin_cases j <;> rfl
+
+open Compression.Refresh in
+/-- Specialize the physical comparison to the two actual diagonal demand
+coordinates of the refresh kernel. The ordinary port map is entered exactly
+when the integer diagonal multiplier is one. -/
+theorem compare_portDiagonal {B : Type*} [Fintype B] {d : ℕ}
+ (t : Equiv.Perm (Arc B d)) (width : Arc B d → ℕ) (v : B) (i : Fin d)
+ (x : (oldNetwork ℤ t width).Basis (v, i)) (z : PortSegments t width v i)
+ (outOld outExternal inOld inExternal : BurstRAM.Word w)
+ (h : Linked M pc first second reg yes no) (c : Config w p r) (hc : c.pc = pc 0)
+ (hout : c.reg (reg 0) = outOld ∧ c.reg (reg 1) = outOld + (width ((v,i),i) : BurstRAM.Word w) ∧
+ c.reg (reg 2) = outExternal)
+ (hin : c.reg (reg 7) = inOld ∧ c.reg (reg 8) = inOld + (width (t.symm ((v,i),i)) : BurstRAM.Word w) ∧
+ c.reg (reg 9) = inExternal)
+ (ho : (Tie.mk outOld outExternal (x.1 ((v,i),i) rfl) (z.1 i)).resident c.privateMem)
+ (hi : (Tie.mk inOld inExternal (incomingHalf t width v i i x) (z.2 i)).resident c.privateMem)
+ (h₁ : width ((v,i),i) < 2^w) (h₂ : width (t.symm ((v,i),i)) < 2^w) :
+ ∃ out, Prefix M c (List.replicate (7*(width ((v,i),i)+width (t.symm ((v,i),i)))+9) .tick) out ∧
+ out.pc = (if portDiagonal t width v i x z = (1 : ℤ) then yes else no) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ ∀ j, j ∉ Set.range reg → out.reg j = c.reg j := by
+ obtain ⟨out, path, dest, keep⟩ := compare h _ _ c hc hout hin ho hi h₁ h₂
+ refine ⟨out, path, ?_, keep⟩
+ have hd : portDiagonal t width v i x z = (1 : ℤ) ↔ x.1 ((v,i),i) rfl = z.1 i ∧
+ incomingHalf t width v i i x = z.2 i := by
+ unfold portDiagonal segmentTest
+ rw [eq_comm (a := z.2 i) (b := incomingHalf t width v i i x)]
+ split_ifs <;> simp_all
+ simpa only [hd] using dest
+
+end PairSimulation.RefreshDiagonal
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshDiagonalArguments.lean b/lean/OAI/Computability/VPVNP/PairRefreshDiagonalArguments.lean
new file mode 100644
index 0000000000..699001725c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshDiagonalArguments.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.PairRefreshDiagonal
+import OAI.Computability.VPVNP.CompressorRefreshMapOperands
+
+/-!
+# The refresh diagonal checker on the actual node buffers
+
+For each direction the child contributes its original slot at the promoted
+port. The parent contributes the segment at the recorded offset in its
+external slot. The checked bits are exactly the diagonal arguments of the
+degree-refresh local kernel. Independent parent and child arguments suffice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshDiagonal
+
+open Compression Compression.Refresh Compression.DegreeRefresh CompressorRecords
+open NodeArguments RefreshMapOperands NetworkKernel
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {a b l dH w pcs regs params : ℕ}
+variable (X : State a (a+l)) (v : (X.Base × BitWord l) × Fin (2^a))
+variable (P : SlotGraph (Fin (2^a)) dH) (hD : 1 < 2^a) (hd : dH+1 ≤ 2^b)
+variable (internal : X.Base × BitWord l → Fin (2^a) × Fin dH → ℕ)
+
+local notation "G" => splitSlots X
+local notation "widths" => groupedWidths (bitWordFinEquiv a) (splitWidths X)
+local notation "matching" => oldPortMatching G (bitWordFinEquiv a)
+local notation "Y" => newState X P hD hd internal
+
+/-- Natural operand addresses reduced to native private RAM words. The
+incoming segment uses the offset of its actual source in the old bundle. -/
+noncomputable def argumentPointers (A : Arena) (child parent : ℕ) : Pointers w where
+ oldOut := (A.fieldAddress X (oldSite X v) child false v.2 : ℕ)
+ externalOut := (A.fieldAddress Y (promotedSites v) parent false (refreshSlots hd (.inl 0)) +
+ (PortRefresh.outgoingRecord G (bitWordFinEquiv a) (splitWidths X) (v,v.2)).offset : ℕ)
+ oldIn := (A.fieldAddress X (oldSite X v) child true v.2 : ℕ)
+ externalIn := (A.fieldAddress Y (promotedSites v) parent true (refreshSlots hd (.inl 0)) +
+ (PortRefresh.incomingRecord G (bitWordFinEquiv a) (splitWidths X) (v,v.2)).offset : ℕ)
+
+private theorem encode_bit (u : Bool) : PrimedInputRAM.encodeBit w u = PrivateFields.bitValue w u := rfl
+
+/-- Native execution on a selected refresh node's actual private half-buffers.
+The branch taken agrees with the integer diagonal multiplier of the kernel. -/
+theorem compare_arguments {M : Machine w pcs regs params} {pc first second : Fin 7 → Fin pcs}
+ {reg : Fin 10 ↪ Fin regs} {yes no : Fin pcs} (link : Linked M pc first second reg yes no)
+ (A : Arena) (child parent : ℕ) (x : X.network.Half (oldSite X v))
+ (z : (Y).network.Half (promotedSites v)) (c : Config w pcs regs) (hc : c.pc = pc 0)
+ (hx : NodeFields A child X _ x c.privateMem) (hz : NodeFields A parent Y _ z c.privateMem)
+ (ready : (argumentPointers X v P hD hd internal A child parent).Ready reg c
+ (widths (v,v.2)) (widths ((matching).symm (v,v.2))))
+ (h₁ : widths (v,v.2) < 2^w) (h₂ : widths ((matching).symm (v,v.2)) < 2^w) :
+ ∃ out, Prefix M c (List.replicate (7*(widths (v,v.2)+widths ((matching).symm (v,v.2)))+9)
+ .tick) out ∧ out.pc = (if portDiagonal matching widths v.1 v.2 (oldHalf X v x)
+ (segments X v P hD hd internal z) = (1 : ℤ) then yes else no) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ ∀ j, j ∉ Set.range reg → out.reg j = c.reg j := by
+ let q := argumentPointers X v P hD hd internal A child parent (w := w)
+ apply compare_portDiagonal matching widths v.1 v.2 (oldHalf X v x) (segments X v P hD hd internal z)
+ q.oldOut q.externalOut q.oldIn q.externalIn link c hc ready.1 ready.2 _ _ h₁ h₂
+ · constructor
+ · intro j
+ simpa only [q, argumentPointers, Nat.cast_add, encode_bit] using old_out_read X v A child x c.privateMem hx v.2 j
+ · intro j
+ simpa only [q, argumentPointers, Nat.cast_add, encode_bit] using
+ external_out_read X v P hD hd internal A parent z c.privateMem hz v.2 j
+ · constructor
+ · intro j
+ simpa only [q, argumentPointers, Nat.cast_add, encode_bit] using old_in_read X v A child x c.privateMem hx v.2 j
+ · intro j
+ simpa only [q, argumentPointers, Nat.cast_add, encode_bit] using
+ external_in_read X v P hD hd internal A parent z c.privateMem hz v.2 j
+
+end PairSimulation.RefreshDiagonal
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshGeometryReload.lean b/lean/OAI/Computability/VPVNP/PairRefreshGeometryReload.lean
new file mode 100644
index 0000000000..782f607b84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshGeometryReload.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.PairVertexControl
+import OAI.Computability.VPVNP.PairVertexSegmentChain
+import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe
+import OAI.Computability.VPVNP.PairTerminalLayout
+
+/-!
+# Refresh map workspace at the actual DFS call boundary
+
+The role reloads the histogram base from private geometry after the child scan. Four
+instructions use two dead locator temporaries and preserve the popped node, site ordinal,
+current and old level heads. Its map directory is beyond the argument frames, histogram
+and twelve immutable geometry cells. All staging finishes below the persistent scalar
+cache for sufficiently large input size.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalGeometry
+
+open BurstRAM BurstRAM.PrivateRAM PairSimulation VertexImage PrimedCounter.GuessWord PhaseRecipe
+open scoped Fin.CommRing
+open private resident_read from OAI.Computability.VPVNP.PairVertexControl
+
+variable {w p r : ℕ}
+
+/-- The two temporaries belong to the fourteen-word level locator. -/
+def reload : VertexImage.Segment where
+ count := 4
+ privateRegs := 14
+ entry := 0
+ row loc dfs _saved common done := ![
+ .loadPrivate (common 9) (dfs 6) (loc 1),
+ .constant (common 10) 11 (loc 2),
+ .binary .add (common 9) (common 9) (common 10) (loc 3),
+ .loadPrivate (common 10) (common 9) done]
+
+/-- Select the six locator registers that supply the refresh computation's five public operands
+and its state word. -/
+def source : Fin 6 → (Fin 9 ⊕ VertexImage.Saved ⊕ Fin 14) := ![
+ .inr (.inr 7), .inr (.inr 0), .inr (.inr 4), .inr (.inr 9), .inr (.inr 10), .inr (.inr 11)]
+
+/-- The freshly reloaded private histogram address, passed as public recipe operand four. -/
+def histogram : Expr := .publicWord 4
+
+/-- Compute the map directory above the histogram, its counters, twelve geometry cells, and two
+live-size buffers. -/
+def directory (histCount : ℕ) : Expr := ((histogram.add (.lit histCount)).add (.lit 12)).add
+ ((Expr.lit 2).mul (.header 17))
+
+/-- Actual terminal private memory supplies the histogram. No initial value of its saved
+bootstrap register enters this execution. -/
+theorem reload_native_address (M : Machine w p r 11) (loc : Fin 4 → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (common : Fin 14 ↪ Fin r) (done : Fin p)
+ (linked : ∀ i, M.code (loc i) = (reload.row loc dfs saved common done i).resize w)
+ (c : Config w p r) (entry : c.pc = loc 0) {endAddr : ℕ} {G offset hist : Word w}
+ (endWord : c.reg (dfs 6) = (endAddr : Word w))
+ (resident : ResidentGeometry (DFS.scratch endAddr c.privateMem) G offset hist) :
+ ∃ d, Prefix M c (List.replicate 4 .tick) d ∧ d.pc = done ∧ d.reg (common 10) = hist ∧
+ d.reg (common 9) = G + 11 ∧
+ (∀ j, j ≠ common 9 → j ≠ common 10 → d.reg j = c.reg j) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ have rows (i : Fin 3) : M.code (loc (i.castAdd 1)) =
+ geometryRows (fun j => loc (j.castAdd 1)) (dfs 6) (common 9) (common 10)
+ (11 : Word w) (loc 3) i := by
+ rw [linked]; fin_cases i <;> rfl
+ obtain ⟨mid, pre, pc, ptr, frame, mem, pers⟩ :=
+ geometry_run rows (common.injective.ne (by decide)) c entry
+ obtain ⟨hg, _, hh⟩ := resident_read _ _ _ _ resident
+ let d := mid.put done (common 10) (mid.privateMem (mid.reg (common 9)))
+ have step : M.program.step mid = .localStep d := by
+ change (M.code mid.pc).run M.publicData mid = _
+ rw [pc, linked]; rfl
+ have tail : Prefix M mid [.tick] d := .tick step (.nil _)
+ refine ⟨d, pre.append tail, rfl, ?_, ?_, fun j h₉ h₁₀ =>
+ (Function.update_of_ne h₁₀ ..).trans (frame _ h₉ h₁₀), mem, pers⟩
+ · rw [show d.reg (common 10) = _ from Config.put_same .., ptr, endWord, hg, mem, hh]
+ · have keep : d.reg (common 9) = mid.reg (common 9) :=
+ Function.update_of_ne (common.injective.ne (by decide : (9 : Fin 14) ≠ 10)) ..
+ rw [keep, ptr, endWord, hg]
+
+theorem reload_native (M : Machine w p r 11) (loc : Fin 4 → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (common : Fin 14 ↪ Fin r) (done : Fin p)
+ (linked : ∀ i, M.code (loc i) = (reload.row loc dfs saved common done i).resize w)
+ (c : Config w p r) (entry : c.pc = loc 0) {endAddr : ℕ} {G offset hist : Word w}
+ (endWord : c.reg (dfs 6) = (endAddr : Word w))
+ (resident : ResidentGeometry (DFS.scratch endAddr c.privateMem) G offset hist) :
+ ∃ d, Prefix M c (List.replicate 4 .tick) d ∧ d.pc = done ∧ d.reg (common 10) = hist ∧
+ (∀ j, j ≠ common 9 → j ≠ common 10 → d.reg j = c.reg j) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨out, pre, pc, histogram, _, frame, mem, per⟩ :=
+ reload_native_address M loc dfs saved common done linked c entry endWord resident
+ exact ⟨out, pre, pc, histogram, frame, mem, per⟩
+
+/-- Computing the private directory and histogram requires only the freshly loaded
+histogram base and the old level's published argument-arena start, which equals `n`. -/
+theorem heads_eval (histCount n hist : ℕ) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w)
+ (hh : pub 4 = (hist : Word w)) (hn : (Expr.header 17).eval pub state m = (n : Word w)) :
+ histogram.eval pub state m = (hist : Word w) ∧
+ (directory histCount).eval pub state m = ((hist + histCount + 12 + 2 * n : ℕ) : Word w) := by
+ refine ⟨hh, ?_⟩
+ change pub 4 + (histCount : Word w) + 12 + 2 * (Expr.header 17).eval pub state m = _
+ rw [hh, hn]; push_cast; rfl
+
+/-- The node's private argument frame precedes the common histogram. -/
+theorem argument_end {a g : ℕ} (degree n nodes labels : ℕ) (X : Compression.State a g)
+ (v : X.network.Site) (h : X.network.Half v) (node : ℕ) (hn : node < nodes)
+ (degreeBound : 2 ^ a ≤ degree) (widthBound : X.maxWireWidth ≤ n) :
+ let R := TerminalLayout.privateRegions degree n nodes labels
+ R.arguments.base node + (NodeArguments.packed X v h).length ≤ R.histBase := by
+ let R := TerminalLayout.privateRegions degree n nodes labels
+ apply (Nat.add_le_add_left _ _).trans (R.node_before hn)
+ have a := NodeArguments.packed_length_le X v h
+ have b := Nat.mul_le_mul (Nat.mul_le_mul_left 2 degreeBound) widthBound
+ change (NodeArguments.packed X v h).length ≤ 2 * degree * n + 1
+ omega
+
+/-- The private space reserved between histogram and scalar cache covers both the
+raw descriptor and all map copies. Its lower bound includes the immutable geometry. -/
+theorem workspace_before_cache (degree n nodes labels headCapacity copies : ℕ)
+ (large : headCapacity + 12 ≤ n) (five : 5 ≤ n) (copyBound : copies ≤ n) :
+ let R := TerminalLayout.privateRegions degree n nodes labels
+ let start := R.histBase + labels + 12 + 2 * n
+ R.histBase + R.histWords + 12 ≤ start ∧ start + headCapacity + 2 * copies ≤ R.cacheBase := by
+ have square : 5 * n ≤ n ^ 2 := (Nat.mul_le_mul_right n five).trans_eq (pow_two n).symm
+ have power : n ^ 2 ≤ n ^ 5 := Nat.pow_le_pow_right (by omega) (by decide)
+ dsimp only [TerminalLayout.privateRegions, LeafArena.Regions.cacheBase]
+ constructor <;> omega
+
+end CompressorRecords.PortRefresh.TraversalGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshGuardLayout.lean b/lean/OAI/Computability/VPVNP/PairRefreshGuardLayout.lean
new file mode 100644
index 0000000000..97f66de997
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshGuardLayout.lean
@@ -0,0 +1,45 @@
+import OAI.Computability.VPVNP.PairRefreshHookReadSupport
+
+/-! # Source ranges for a selected refresh job at the dispatcher -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM Compression CompressorRecords DescriptorSpace PortRefresh NewSlots
+open TraversalControllerInputs
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {hist : ℕ}
+
+/-- Published row ranges in the live block layout. The dispatched tag is read
+below the terminal header, like the two node cells and the level directory. -/
+structure GuardLayout {n w : ℕ} (R : Site B n hist w) (pub : Fin 11 → Word w) (m : Memory w)
+ (start positions blocks : ℕ)
+ (prev next : Fin (BlockProgram.layout B start positions blocks).levels)
+ : Prop where
+ size : R.state.positions ≤ positions
+ below : endAddress (BlockProgram.layout B start positions blocks) ≤ (TerminalLink.header pub).val
+ headerFit : (TerminalLink.header pub).val + 32 ≤ 2 ^ w
+ oldHead : (levelHead pub m R.level).val =
+ levelStart (BlockProgram.layout B start positions blocks) prev
+ newHead : (levelHead pub m (R.level + 1)).val =
+ levelStart (BlockProgram.layout B start positions blocks) next
+ scratch : R.start = arrayBase (BlockProgram.layout B start positions blocks) prev
+ oldCols : R.prev = packedIncidence (BlockProgram.layout B start positions blocks) w prev
+ (R.state.positions * 2 ^ S.portExponent)
+ newCols : R.next = packedIncidence (BlockProgram.layout B start positions blocks) w next
+ (R.nextState.positions * 2 ^ S.degreeExponent 0)
+ levels : ∀ i, R.level + 1 ≤ i → i ≤ R.level + 1 + R.later →
+ (levelHead pub m i + 14).val < (TerminalLink.header pub).val
+ parentBefore : R.parent + 1 < (TerminalLink.header pub).val
+ listBefore : R.listHead < (TerminalLink.header pub).val
+ tagBefore : (R.roleOffset + word R.parent).val < (TerminalLink.header pub).val
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHalfDecoder.lean b/lean/OAI/Computability/VPVNP/PairRefreshHalfDecoder.lean
new file mode 100644
index 0000000000..95170a7dd6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHalfDecoder.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.PairShrinkRoleChildTyped
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+
+/-!
+# Reading the two independent arguments of a refresh node
+
+The parent packet is read at its absolute DFS arena address. The unique old
+half is parsed from the remaining choice tape in outgoing-then-incoming slot
+order. Both operations use the state network's actual variable slot widths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHalfDecoder
+
+open BurstRAM Compression LocalHistory NodeArguments NodeArguments.ChildScan DFS
+open scoped Fin.CommRing
+
+variable {w a g endAddr : ℕ} (X : State a g) (u : X.network.Site)
+
+/-- Decode a half-wire assignment in outgoing slot order followed by incoming slot order, using
+the state's payload widths. -/
+noncomputable def reader := LocalHistory.half X.network u (outgoingOrder X u) (incomingOrder X u) (statePayload X)
+/-- Total number of bits in the site's outgoing and incoming half-wire fields. -/
+noncomputable def width := ∑ dir : Bool, ∑ j, X.halfWidth u dir j
+
+theorem read_iff (bs : List Bool) (x : X.network.Half u) (tail : List Bool) :
+ (reader X u).read bs = some (x,tail) ↔ bs = packed X u x ++ tail := by
+ rw [packed_eq_encode]
+ exact (reader X u).read_iff bs x tail
+
+theorem none_iff (bs : List Bool) :
+ (reader X u).read bs = none ↔ bs.length < width X u := by
+ constructor
+ · intro h
+ by_contra! room
+ let bits : X.network.Half u := (fun _ _ _ => false,fun _ _ _ => false)
+ have eqn : ChildSlots.length X u (ChildSlots.slots (2^a)) = width X u := by
+ exact (Child.payload_length X (Child.ofHalf X u bits)).symm.trans
+ ((congrArg List.length (Child.payload_ofHalf X u bits)).trans (packed_length X u bits))
+ obtain ⟨q,atSite,split⟩ := choose_payload X u bs (eqn ▸ room)
+ rcases q with ⟨v,data⟩
+ change v = u at atSite
+ subst v
+ let q : Child X := ⟨u,data⟩
+ have eq := (read_iff X u bs (q.half X) (bs.drop (q.payload X).length)).mpr
+ ((q.payload_eq_packed X) ▸ split.symm)
+ rw [h] at eq; contradiction
+ · intro short
+ cases h : (reader X u).read bs with
+ | none => rfl
+ | some pair =>
+ obtain ⟨x,tail⟩ := pair
+ have len := congrArg List.length ((read_iff X u bs x tail).mp h)
+ rw [List.length_append,packed_length] at len
+ change bs.length < ∑ dir : Bool, ∑ j, X.halfWidth u dir j at short
+ omega
+
+variable (A : Arena) (node : ℕ) (s : Scratch w endAddr)
+
+/-- Read the parent's packed argument from private scratch as bits, interpreting a stored word
+equal to one as true. -/
+noncomputable def packetBits : List Bool := List.ofFn fun i : Fin (width X u) =>
+ decide (rawScratch s ((A.base node+i.val : ℕ) : Word w) = 1)
+
+/-- Read the parent packet from its DFS arena and decode its local half-wire assignment. The
+packet supplies exactly the required number of bits. -/
+noncomputable def parent : Option (X.network.Half u) :=
+ ((reader X u).read (packetBits X u A node s)).map Prod.fst
+
+theorem packetBits_eq (x : X.network.Half u) (stored : (Packet.mk node (packed X u x)).Stored A s)
+ (hw : 0 < w) : packetBits X u A node s = packed X u x := by
+ apply List.ext_getElem
+ · simp [packetBits,width,packed_length]
+ · intro j hj hi
+ have field := stored ⟨j,hi⟩
+ simp only [packetBits,List.getElem_ofFn]
+ rw [field]
+ change decide (PrimedInputRAM.encodeBit w (packed X u x)[j] = 1) = _
+ simp [PrimedInputRAM.encodeBit_eq_one hw]
+
+theorem parent_eq (x : X.network.Half u) (stored : (Packet.mk node (packed X u x)).Stored A s)
+ (hw : 0 < w) : parent X u A node s = some x := by
+ unfold parent
+ rw [packetBits_eq X u A node s x stored hw,
+ (read_iff X u _ x []).mpr (List.append_nil _).symm]
+ rfl
+
+end PairSimulation.RefreshHalfDecoder
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookBudget.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookBudget.lean
new file mode 100644
index 0000000000..3312cb62ec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookBudget.lean
@@ -0,0 +1,195 @@
+import OAI.Computability.VPVNP.PairRefreshHookSite
+import OAI.Computability.VPVNP.PairRefreshTraversalQuiet
+import OAI.Computability.VPVNP.PairMapSuccessBudget
+import OAI.Computability.VPVNP.PairVertexOrdinalRoleCost
+
+/-! # The cost of the selected refresh reader
+
+The canonical trace includes every public load, guessed old wire bit and
+private motif instruction. One fixed scan coefficient bounds the probes of
+the dispatched job on every selected branch. The work threshold is independent
+of the row, field specialization and branch choices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords CompressorRecords.PortRefresh
+open RefreshMapOperands MotifConversion NewSlots LocalHistory NodeArguments
+open TraversalControllerInputs VertexImage DFS PhaseRecipe
+open private eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe
+open private lines_probes from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {w n hist t : ℕ}
+ (R : Site B n hist w) (ties : Fin t ≃ Tie (2 ^ S.portExponent))
+ (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (pub : Fin 11 → BurstRAM.Word w) (m : Memory w)
+
+local notation "D" => 2 ^ S.portExponent
+local notation "T" => TraversalPlan.plan B ties stride order
+local notation "K₀" => TraversalPlan.budget B ties stride order
+local notation "X" => Site.state R
+local notation "v" => Site.port R
+local notation "ws" => groupedWidths (bitWordFinEquiv _) (splitWidths X)
+local notation "perm" => oldPortMatching (splitSlots X) (bitWordFinEquiv _)
+local notation "wo" => ws (v, Prod.snd v)
+local notation "wi" => ws (Equiv.symm perm (v, Prod.snd v))
+local notation "copies" =>
+ repetitions B.refresh (blockDemandWidths (splitSlots X) (bitWordFinEquiv _)
+ (splitWidths X) (Prod.fst v))
+
+private theorem ticks (a : ℕ) : countProbes (List.replicate a (.tick : Event w)) = 0 := by
+ induction a with
+ | zero => rfl
+ | succ a h => simpa only [List.replicate_succ, countProbes] using h
+
+private theorem setup_cost {a : ℕ} (f : Fin a → Expr) (heads : Fin 5 → BurstRAM.Word w)
+ (st : BurstRAM.Word w) (mem : Memory w) :
+ let es := RefreshResidentImage.Plan.setupEvents f heads st mem
+ es.length = (RegisterSetup.lines f).length ∧ countProbes es = ∑ i, (f i).loads :=
+ ⟨(eval_cost heads st mem (RegisterSetup.lines f) (fun _ => 0)).1,
+ lines_probes f heads st mem (fun _ => 0)⟩
+
+set_option maxHeartbeats 1100000 in
+-- The trace uses the same dependent finite map index in three instruction banks.
+/-- Count the actual map trace, including both diagonal widths and each
+repetition, independently of the other resident registers. -/
+theorem action_cost {old : R.state.network.Half R.olderSite}
+ {new : R.nextState.network.Half R.newerSite}
+ {s updated : Scratch w n} {es : List (Event w)}
+ (hit : R.action ties stride order pub m old new s = some (es, updated)) :
+ countProbes es ≤ K₀ ∧ es.length ≤ K₀ * (wo + wi + copies + 1) := by
+ rw [TraversalPlan.canonicalAction_events B ties stride order R.state R.choice R.port R.degree n
+ R.rowEnd R.oldNode R.parent R.room old new m (levelHead pub m R.level).val
+ (levelHead pub m (R.level + 1)).val R.geometry hit]
+ let I := entryInput B R.state R.choice R.port old new
+ let z := demandGrid B.refresh (fun _ => zero_lt_one) I.demand
+ let heads := TraversalPlan.operands
+ ((sites R.state.baseIndex (bitWordFinEquiv R.lanes)) R.port).val
+ R.parent (levelHead pub m (R.level + 1)).val R.regions.histBase R.geometry
+ let st : BurstRAM.Word w := word (levelHead pub m R.level).val
+ have mapCost := (T).family.successEvents_cost (fun _ => zero_lt_one) I R.room.tableWidth
+ heads st m
+ have diag := setup_cost (T).diagonal heads st m
+ have route := setup_cost (T).route heads st m
+ obtain ⟨probe, work⟩ := (T).uniform.choose_spec z R.port.2 wo wi copies
+ let clk := RefreshResidentDispatch.chainTicks
+ ((RefreshResidentDispatch.gridOrder B).symm z).val R.port.2.val
+ let map := (T).family.successEvents (fun _ => zero_lt_one) I R.room.tableWidth heads st m
+ let d := RefreshResidentImage.Plan.setupEvents (T).diagonal heads st m
+ let r := RefreshResidentImage.Plan.setupEvents (T).route heads st m
+ let es' := List.replicate 4 (.tick : Event w) ++
+ (((d ++ List.replicate (7 * (wo + wi) + 9) .tick) ++
+ (r ++ List.replicate clk .tick)) ++ map)
+ change countProbes es' ≤ (T).uniform.choose + 4 ∧
+ es'.length ≤ ((T).uniform.choose + 4) * (wo + wi + copies + 1)
+ let fields := (T).family.fields (z, R.port.2)
+ have mapProbe : countProbes map =
+ ∑ i, ((MapArgumentWriter.recipes (T).directory fields) i).loads := mapCost.2
+ have mapWork : map.length ≤ MapArgumentWriter.clock (T).directory fields +
+ MapInline.cap B.refresh (T).ordinal z R.port.2 copies := mapCost.1
+ change d.length = _ ∧ countProbes d = _ at diag
+ change r.length = _ ∧ countProbes r = _ at route
+ change (RegisterSetup.lines (T).diagonal).length + (7 * (wo + wi) + 9) +
+ ((RegisterSetup.lines (T).route).length + clk) + _ ≤ _ at work
+ simp only [es', List.length_append, List.length_replicate, countProbes_append, ticks,
+ diag.1, diag.2, route.1, route.2, mapProbe, Nat.add_zero, Nat.zero_add, Nat.add_mul]
+ have four : 4 ≤ 4 * (wo + wi + copies + 1) := Nat.le_mul_of_pos_right _ (Nat.succ_pos _)
+ dsimp only [fields] at *
+ constructor <;> omega
+
+/-- The successful parser trace includes the locator, the singleton input
+packet and the selected map. -/
+theorem read_cost {node : BurstRAM.Word w} {s : Scratch w n} {bs out tail}
+ (hit : R.read ties stride order pub m node s bs = some (out, tail)) :
+ countProbes out.trace ≤ 15 + R.later + 3 * D + K₀ ∧
+ out.trace.length ≤ 63 + 6 * R.later + 16 * D +
+ 6 * (packed R.state R.olderSite out.value.1).length + K₀ * (wo + wi + copies + 1) := by
+ obtain ⟨_, _, es, hit', traceEq⟩ := (RefreshHook.read_some_iff R.state R.olderSite R.nextState
+ R.newerSite R.arena R.oldNode R.parent (R.front pub m) (R.action ties stride order pub m)
+ node s bs out tail).mp hit
+ obtain ⟨probes, len⟩ := R.action_cost ties stride order pub m hit'
+ have front := RefreshVertexAssembly.inputTrace_cost S.portExponent R.state R.olderSite out.value.1
+ R.prev m R.listHead pub node R.level R.later
+ rw [traceEq, List.length_append, countProbes_append]
+ exact ⟨Nat.add_le_add front.2.1.le probes, Nat.add_le_add front.1.le len⟩
+
+variable (B)
+
+/-- The external probe coefficient, including the single role dispatch. -/
+noncomputable def scan := 16 + 3 * D + K₀ + (S.steps + 1)
+
+open Filter
+
+/-- A single length threshold works for every represented site of every
+branch. The dispatch trace is charged as part of this same visit. -/
+theorem eventually_ordinal_cost :
+ ∀ᶠ n : ℕ in atTop, ∀ {w : ℕ} (R : Site B n hist w) (pub : Fin 11 → BurstRAM.Word w)
+ (m : Memory w) (offset node : BurstRAM.Word w) (s : Scratch w n) (bs out tail)
+ (j : VisitPath w n),
+ R.later ≤ (S.steps + 1) * (n.log2 + 1) →
+ R.read ties stride order pub m node s bs = some (out, tail) →
+ j.trace = dispatchEvents m offset node ++ out.trace →
+ ordinalJobCost n 1 (scan B ties stride order) j := by
+ let C := 72 + 16 * D + 6 * (S.steps + 1) + 12 * D + 3 * K₀
+ filter_upwards [eventually_ge_atTop (2 * C), eventually_ge_atTop 2] with n hn two
+ intro w R pub m offset node s bs out tail j later hit path
+ obtain ⟨probe, time⟩ := R.read_cost ties stride order pub m hit
+ obtain ⟨dispatchProbe, dispatchTime, _⟩ := dispatchEvents_cost m offset node
+ have oldBits := (packed_length_le R.state R.olderSite out.value.1).trans
+ (Nat.mul_le_mul_left _ R.room.oldWidth)
+ have width (e) : groupedWidths (bitWordFinEquiv _) (splitWidths R.state) e ≤ n :=
+ (R.state.width_le_maxWireWidth _).trans R.room.oldWidth
+ have outWidth := width (R.port, R.port.2)
+ have inWidth := width
+ ((oldPortMatching (splitSlots R.state) (bitWordFinEquiv _)).symm (R.port, R.port.2))
+ have copyBound := R.room.copyBound
+ have log_le : n.log2 ≤ n := by simpa only [Nat.log2_eq_log_two] using Nat.log_le_self 2 n
+ have visit := Nat.mul_le_mul_left K₀
+ (Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add outWidth inWidth) copyBound) 1)
+ have stepBound := Nat.mul_le_mul_left 6
+ (later.trans (Nat.mul_le_mul_left _ (Nat.add_le_add_right log_le 1)))
+ have bitsBound := Nat.mul_le_mul_left 6 oldBits
+ constructor
+ · rw [path, countProbes_append, dispatchProbe, pow_one]
+ have fixed := Nat.le_mul_of_pos_right (16 + 3 * D + K₀) (Nat.succ_pos n.log2)
+ change _ ≤ (16 + 3 * D + K₀ + (S.steps + 1)) * (n.log2 + 1)
+ rw [Nat.add_mul]
+ exact (show 1 + countProbes out.trace ≤ (16 + 3 * D + K₀) + R.later by omega).trans
+ (Nat.add_le_add fixed later)
+ · rw [path, List.length_append]
+ have constant := Nat.le_mul_of_pos_right (72 + 16 * D) (Nat.succ_pos n)
+ have bits : 6 * (2 * D * n) ≤ 12 * D * (n + 1) := by
+ calc
+ _ = 12 * D * n := by ring
+ _ ≤ _ := Nat.mul_le_mul_left _ (Nat.le_succ n)
+ have reps : K₀ * (n + n + n + 1) ≤ 3 * K₀ * (n + 1) := by
+ rw [Nat.mul_comm 3 K₀, Nat.mul_assoc]
+ exact Nat.mul_le_mul_left _ (by omega)
+ have linear : (dispatchEvents m offset node).length + out.trace.length ≤ C * (n + 1) := by
+ calc
+ _ ≤ 72 + 16 * D + 6 * R.later +
+ 6 * (packed R.state R.olderSite out.value.1).length + _ := by
+ exact (Nat.add_le_add dispatchTime time).trans_eq (by omega)
+ _ ≤ (72 + 16 * D) * (n + 1) + 6 * ((S.steps + 1) * (n + 1)) +
+ 12 * D * (n + 1) + 3 * K₀ * (n + 1) :=
+ Nat.add_le_add
+ (Nat.add_le_add (Nat.add_le_add constant stepBound) (bitsBound.trans bits))
+ (visit.trans reps)
+ _ = C * (n + 1) := by dsimp [C]; ring
+ calc
+ _ ≤ C * (n + 1) := linear
+ _ ≤ C * (2 * n) := Nat.mul_le_mul_left C (by omega)
+ _ = (2 * C) * n := by ring
+ _ ≤ n ^ 2 := (Nat.mul_le_mul_right n hn).trans_eq (pow_two n).symm
+ _ ≤ n ^ 43 := Nat.pow_le_pow_right (by omega) (by decide)
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookEffect.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookEffect.lean
new file mode 100644
index 0000000000..8d6bbd987a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookEffect.lean
@@ -0,0 +1,222 @@
+import OAI.Computability.VPVNP.PairRefreshHookSite
+import OAI.Computability.VPVNP.PairRefreshTraversalFrames
+import OAI.Computability.VPVNP.PairRefreshTraversalHistogram
+import OAI.Computability.VPVNP.PairRefreshTraversalValue
+import OAI.Computability.VPVNP.PairVertexFrameData
+
+/-!
+# Scratch effects of a refresh on the pending DFS frontier
+
+The unique child write fills one argument slot below the histogram. The
+selected map then increments the label words and uses a private workspace
+between the vertex geometry and the cache. All pending arguments, geometry
+fields and cached operands can still be read at their original addresses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM PrivateRAM Compression CompressorRecords CompressorRecords.PortRefresh
+open NodeArguments TreeDecode VertexImage DFS LeafSourceLoad Compression.DegreeRefresh Compression.Refresh
+open CompressorRecords.RefreshMapOperands MotifConversion
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {w n hist t : ℕ}
+variable (R : Site B n hist w) (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ)
+ (order : B.Entry ≃ Fin hist) (pub : Fin 11 → BurstRAM.Word w) (m : Memory w)
+ (old : R.state.network.Half R.olderSite) (new : R.nextState.network.Half R.newerSite)
+local notation "child" => packet R.state R.olderSite R.oldNode old
+local notation "base" => LeafArena.Regions.histBase R.regions
+local notation "directory" => LeafArena.Regions.histBase R.regions + hist + 12 + 2*n
+local notation "upper" => TraversalPlan.canonicalUpper B ties stride order R.state R.choice R.port
+ R.degree n R.rowEnd R.oldNode R.parent R.room old new
+local notation "names" => TraversalPlan.emitted B order R.state R.choice R.port old new
+
+variable {s out : Scratch w n} {es : List (Event w)}
+variable (result : R.action ties stride order pub m old new
+ ((RefreshHook.packet R.state R.olderSite R.oldNode old).write R.arena s) = some (es,out))
+
+private theorem option_fields {α β : Type*} (condition : Bool) (e : α) (v : β) (es : α) (out : β)
+ (result : (if condition then some (e,v) else none) = some (es,out)) :
+ condition = true ∧ out = v := by
+ cases condition <;> simp_all
+
+set_option maxHeartbeats 1800000 in
+-- The concrete refresh action has dependent slot and workspace indices.
+include result in
+/-- A successful parser selects the actual map update applied after its unique
+old-half packet has been written. -/
+theorem action_scratch : (names).isSome = true ∧ out = upper ((child).write R.arena s) := by
+ exact option_fields (names).isSome _ (upper ((child).write R.arena s)) es out result
+
+private theorem hist_room : base+hist ≤ 2^w :=
+ R.regions.hist_before.trans R.room.capacity.room.le
+
+private theorem wordBelow (i : Fin hist) :
+ (((base+i.val : ℕ) : BurstRAM.Word w)).val = base+i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans_le (hist_room R))
+
+include result in
+/-- The map preserves each raw scratch word in the indicated regions, excluding
+its histogram interval. This includes arbitrary old values in unused cells. -/
+theorem action_frame (a : BurstRAM.Word w)
+ (far : a.val < directory ∨ R.regions.cacheBase ≤ a.val)
+ (apart : a.val < base ∨ base+hist ≤ a.val) :
+ rawScratch out a = rawScratch ((child).write R.arena s) a := by
+ rw [(R.action_scratch ties stride order pub m old new result).2]
+ by_cases ha : n ≤ a.val
+ · simp only [rawScratch,dite_eq_left ha]
+ apply TraversalPlan.upper_frame B ties stride order R.state R.choice R.port R.degree n
+ R.rowEnd R.oldNode R.parent R.room old new _ _ ha far
+ intro i eqn
+ have value := (congrArg Fin.val eqn).trans (wordBelow R i)
+ have ix := i.isLt
+ omega
+ · simp only [rawScratch,dite_eq_right ha]
+
+private theorem child_outside (a : BurstRAM.Word w)
+ (apart : a.val < R.arena.base R.oldNode ∨ R.arena.base R.oldNode + (child).bits.length ≤ a.val) :
+ rawScratch ((child).write R.arena s) a = rawScratch s a := by
+ by_cases ha : n ≤ a.val
+ · simp only [rawScratch,dite_eq_left ha,Packet.write,scratch]
+ exact (PrivateFields.storeBits_outside _ _ (rawScratch s) a (R.oldFit old).2.2 apart).trans
+ (dite_eq_left ha)
+ · simp only [rawScratch,dite_eq_right ha]
+
+private theorem childEnd : R.arena.base R.oldNode + (child).bits.length ≤ base :=
+ (Nat.add_le_add_left (R.oldFit old).2.1 _).trans (R.regions.node_before R.room.childBound)
+
+include result in
+/-- Any fitted pending node, including the newly written child, retains its
+packet words after the map has run. -/
+theorem action_packet (q : Packet) (node : q.node < R.rowEnd) (fit : q.Fits R.arena w n)
+ (i : Fin q.bits.length) :
+ rawScratch out ((R.arena.base q.node+i.val : ℕ) : BurstRAM.Word w) =
+ rawScratch ((child).write R.arena s) ((R.arena.base q.node+i.val : ℕ) : BurstRAM.Word w) := by
+ have ix := (Nat.add_lt_add_left (i.isLt.trans_le fit.2.1) _).trans_le (R.regions.node_before node)
+ have room : R.arena.base q.node+i.val < 2^w := (Nat.add_lt_add_left i.isLt _).trans_le fit.2.2
+ have bound : (((R.arena.base q.node+i.val : ℕ) : BurstRAM.Word w)).val < base :=
+ (Nat.mod_eq_of_lt room).trans_lt ix
+ apply R.action_frame ties stride order pub m old new result _ (Or.inl ?_) (Or.inl bound)
+ omega
+
+include result in
+/-- The ten record words, the role and histogram pointers, and all 38 cached
+operands survive the child write and the map. -/
+theorem action_vertexFrame {data : Fin 10 → BurstRAM.Word w} {offset : BurstRAM.Word w} {vals : Static 34 → BurstRAM.Word w}
+ (before : VertexFrameData R.regions data offset vals s) (positive : 0 < R.oldNode)
+ (cacheFit : R.regions.cacheBase+38 ≤ 2^w) :
+ VertexFrameData R.regions data offset vals out := by
+ have lowChild : n < R.arena.base R.oldNode := by
+ change n < n + R.oldNode*(2*R.degree*n+1)
+ exact Nat.lt_add_of_pos_right (Nat.mul_pos positive (Nat.succ_pos _))
+ have endBefore := childEnd R old
+ have cache : base+hist ≤ R.regions.cacheBase := R.regions.hist_before
+ have frameBase : NativeFrame.frameBase R.regions = base+hist := rfl
+ have geomRoom : base+hist+12 ≤ R.regions.cacheBase := by
+ change base+hist+12 ≤ base+hist+n^5
+ exact Nat.add_le_add_left ((by decide : 12 ≤ 5^5).trans (Nat.pow_le_pow_left R.room.five 5)) _
+ apply before.transfer
+ · have val : (n : BurstRAM.Word w).val = n := Nat.mod_eq_of_lt before.resident.endFit
+ apply (R.action_frame ties stride order pub m old new result _ (Or.inl (by rw [val]; omega))
+ (Or.inl (by rw [val]; omega))).trans
+ exact child_outside R old _ (Or.inl (val.trans_lt lowChild))
+ · intro i
+ have ix := i.isLt
+ have fit : NativeFrame.frameBase R.regions+i.val < 2^w := by rw [frameBase]; omega
+ have val : (((NativeFrame.frameBase R.regions+i.val : ℕ) : BurstRAM.Word w)).val = base+hist+i.val :=
+ (Nat.mod_eq_of_lt fit).trans (congrArg (·+i.val) frameBase)
+ apply (R.action_frame ties stride order pub m old new result _ (Or.inl (by rw [val]; omega))
+ (Or.inr (by rw [val]; omega))).trans
+ exact child_outside R old _ (Or.inr (by rw [val]; omega))
+ · intro j
+ have hj : j.offset < 38 := by cases j <;> simp [Static.offset]; omega
+ have fit : R.regions.cacheBase + j.offset < 2^w := by omega
+ have val : (((R.regions.cacheBase+j.offset : ℕ) : BurstRAM.Word w)).val = R.regions.cacheBase+j.offset :=
+ Nat.mod_eq_of_lt fit
+ apply (R.action_frame ties stride order pub m old new result _ (Or.inr (by rw [val]; omega))
+ (Or.inr (by rw [val]; omega))).trans
+ exact child_outside R old _ (Or.inr (by rw [val]; omega))
+
+private theorem index_length {u : ℕ} {α β : Type*} (indices : Option (Fin u → α)) (toLabel : α → β) :
+ (((indices.map List.ofFn).map (List.map toLabel)).getD []).length ≤ u := by
+ cases indices <;> simp
+
+/-- A refresh emits at most one label for each allocated copy. This bound
+applies to every independent old half and every parent packet. -/
+theorem action_count_le (i : Fin hist) : ((names).getD []).count i ≤ n := by
+ let placed := TraversalPlan.splitPlaced R.state R.port (TraversalPlan.placedHalf R.state R.port old)
+ have half := TraversalPlan.splitPlaced_child R.state R.port (TraversalPlan.placedHalf R.state R.port old)
+ have eqn := TraversalPlan.emitted_eq_indices B order R.state R.choice R.port old new placed half
+ refine (List.count_le_length ..).trans ?_
+ rw [eqn]
+ exact (index_length ..).trans R.room.copyBound
+
+include result in
+/-- Word-level readback for the complete action. The preceding child store
+is disjoint from each histogram word, including words previously incremented. -/
+theorem action_histogram (i : Fin hist) :
+ rawScratch out ((base+i.val : ℕ) : BurstRAM.Word w) =
+ rawScratch s ((base+i.val : ℕ) : BurstRAM.Word w) + (((names).getD []).count i : BurstRAM.Word w) := by
+ let a : BurstRAM.Word w := ((base+i.val : ℕ) : BurstRAM.Word w)
+ have va : a.val = base+i.val := wordBelow R i
+ have low : n ≤ base := Nat.le_add_right ..
+ have hi : n ≤ a.val := va ▸ low.trans (Nat.le_add_right _ _)
+ have ⟨good,next⟩ := R.action_scratch ties stride order pub m old new result
+ have keep := child_outside (s := s) R old a (Or.inr ((childEnd R old).trans ((Nat.le_add_right _ _).trans_eq va.symm)))
+ have update := TraversalPlan.upper_histogram B ties stride order R.state R.choice R.port R.degree n
+ R.rowEnd R.oldNode R.parent R.room old new ((child).write R.arena s) good i hi
+ rw [next]
+ change rawScratch (upper ((child).write R.arena s)) a = rawScratch s a + _
+ rw [← keep]
+ simp only [rawScratch,dite_eq_left hi]
+ exact update
+
+include result in
+/-- The accepted action advances the pending forest by exactly one visit and
+increments every natural label exponent by its true emitted multiplicity. -/
+theorem action_budgeted {data : Fin 10 → BurstRAM.Word w} {offset : BurstRAM.Word w} {vals : Static 34 → BurstRAM.Word w}
+ (format : Packet → Prop) (desc : ℕ → List ℕ) (nodeCap limit : ℕ) (head : Packet) (pending : List Packet)
+ (before : Budgeted R.arena format (VertexFrameData R.regions data offset vals) desc
+ (privateHistogram order.symm base) nodeCap limit (head::pending) s)
+ (shape : desc head.node = subtreeAddresses desc child) (typed : format child)
+ (nodeBound : ∀ q, format q → q.node < R.rowEnd) (positive : 0 < R.oldNode)
+ (cacheFit : R.regions.cacheBase+38 ≤ 2^w) (limitFit : limit < 2^w) (capFit : n ≤ nodeCap) :
+ Budgeted R.arena format (VertexFrameData R.regions data offset vals) desc
+ (privateHistogram order.symm base) nodeCap limit (child::pending) out ∧
+ ∀ label, privateHistogram order.symm base out label = privateHistogram order.symm base s label +
+ ((names).getD []).count (order label) := by
+ have hit (label) : privateHistogram order.symm base out label =
+ privateHistogram order.symm base s label + ((names).getD []).count (order label) := by
+ let i := order label
+ have small := (R.action_count_le order old new i).trans capFit
+ have nat := before.word_add limitFit label small
+ have word := R.action_histogram ties stride order pub m old new result i
+ change (rawScratch out ((base+i.val : ℕ) : BurstRAM.Word w)).val =
+ (rawScratch s ((base+i.val : ℕ) : BurstRAM.Word w)).val + _
+ rw [word]
+ simpa only [privateHistogram,Equiv.symm_symm,Fin.cast_val_eq_self] using nat
+ refine ⟨before.push (children := [child]) (by simpa using shape)
+ (R.action_vertexFrame ties stride order pub m old new result before.frontier.frame positive cacheFit)
+ ?_ ?_ (fun label => (hit label).le.trans (Nat.add_le_add_left
+ ((R.action_count_le order old new (order label)).trans capFit) _)),hit⟩
+ · intro q hq
+ obtain rfl := List.mem_singleton.mp hq
+ exact ⟨typed,R.oldFit old⟩
+ · intro q hq i
+ have facts : format q ∧ q.Fits R.arena w n := by
+ rcases List.mem_append.mp hq with childEq | sibling
+ · obtain rfl := List.mem_singleton.mp childEq
+ exact ⟨typed,R.oldFit old⟩
+ · have ready := before.frontier.prepared.2 q (List.mem_cons_of_mem _ sibling)
+ exact ⟨ready.1,ready.2.1⟩
+ exact R.action_packet ties stride order pub m old new result q (nodeBound q facts.1) facts.2 i
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookEmission.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookEmission.lean
new file mode 100644
index 0000000000..cd7b53dad3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookEmission.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.PairRefreshHookOrigin
+import OAI.Computability.VPVNP.PairRefreshHookRecover
+import OAI.Computability.VPVNP.PairRefreshHookEffect
+import OAI.Computability.VPVNP.PairRefreshTraversalQuiet
+import OAI.Computability.VPVNP.PairTreeEmissions
+
+/-!
+# The physical refresh job and its selected term
+
+A prepared parent supplies the same newer argument to the physical and
+semantic readers. For the emitted job the natural counter increments are
+the exponents of the selected kernel witness. The unique child packet and
+the pending siblings satisfy the budgeted frontier after that job.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords CompressorRecords.PortRefresh NewSlots NodeArguments NodeArguments.ChildScan
+open LocalHistory TreeDecode VertexImage DFS NetworkKernel LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {bits n hist t : ℕ}
+ (R : Site B n hist bits) (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (pub : Fin 11 → BurstRAM.Word bits) (m : Memory bits)
+variable {K : Type*} [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f)
+local notation "reader" => originReader B f hf (PassOrigin.refresh R.state) R.choice
+local notation "site" => R.newerSite
+local notation "parent" => R.parent
+local notation "base" => R.regions.histBase
+local notation "H" => privateHistogram order.symm base
+local notation "hook" => R.hook ties stride order pub m
+
+variable (new : R.nextState.network.Half R.newerSite)
+ (data : Fin 10 → BurstRAM.Word bits) (offset : BurstRAM.Word bits) (vals : Static 34 → BurstRAM.Word bits)
+ (format : Packet → Prop) (desc : ℕ → List ℕ) (nodeCap limit : ℕ)
+ (pending : List Packet) (s : Scratch bits n)
+local notation "head" => Packet.mk parent (packed R.nextState site new)
+local notation "valid" => Budgeted R.arena format (VertexFrameData R.regions data offset vals) desc H nodeCap limit
+local notation "assignment" => Placed (TraversalPlan.place R.state) R.state.network.Half site
+local notation "oldAt" => (fun before : assignment =>
+ before R.olderSite (TraversalPlan.old_place R.state R.port))
+local notation "child" => (fun before : assignment => packet R.state R.olderSite R.oldNode (oldAt before))
+local notation "bitsOf" => TermParsers.nodeBits (reader) site
+local notation "seen" => TermParsers.witness (reader) site
+
+variable (ready : Budgeted R.arena format (VertexFrameData R.regions data offset vals) desc
+ (privateHistogram order.symm R.regions.histBase) nodeCap limit
+ (Packet.mk R.parent (packed R.nextState R.newerSite new)::pending) s)
+ (hw : 0 < bits)
+ (shape : ∀ before : Placed (TraversalPlan.place R.state) R.state.network.Half R.newerSite,
+ desc R.parent = subtreeAddresses desc (packet R.state R.olderSite R.oldNode
+ (before R.olderSite (TraversalPlan.old_place R.state R.port))))
+ (typed : ∀ before : Placed (TraversalPlan.place R.state) R.state.network.Half R.newerSite,
+ format (packet R.state R.olderSite R.oldNode (before R.olderSite (TraversalPlan.old_place R.state R.port))))
+ (nodeBound : ∀ q, format q → q.node < R.rowEnd) (positive : 0 < R.oldNode)
+ (cacheFit : R.regions.cacheBase+38 ≤ 2^bits) (limitFit : limit < 2^bits) (capFit : n ≤ nodeCap)
+
+include ready hw shape typed nodeBound positive cacheFit limitFit capFit in
+set_option maxHeartbeats 1500000 in
+theorem origin_effect (before : Placed (TraversalPlan.place R.state) R.state.network.Half site)
+ (w : (seen before new).Choice) (tail : List Bool) (job : VisitPath bits n)
+ (read : (hook).read (parent : BurstRAM.Word bits) s (bitsOf before new w ++ tail) = some (job,tail)) :
+ RealizesJob H ⟨parent,bitsOf before new w,(seen before new).exponents w⟩ job ∧
+ job.enabled s ∧ valid (child before::pending) (job.update s) := by
+ have hp := RefreshHalfDecoder.parent_eq R.nextState site R.arena parent s new ready.frontier.head.2.2.2 hw
+ have bitsEq := TraversalPlan.origin_nodeBits B f hf R.state R.choice R.port before new w
+ rw [bitsEq] at read
+ let old := oldAt before
+ obtain ⟨es,out,ha,hjob⟩ := R.recover_job ties stride order pub m (parent : BurstRAM.Word bits) s old new hp job tail read
+ clear read
+ subst job
+ obtain ⟨budgeted,counts⟩ := R.action_budgeted ties stride order pub m old new ha format desc nodeCap limit
+ head pending ready (shape before) (typed before) nodeBound positive cacheFit limitFit capFit
+ refine ⟨⟨rfl,?_,?_⟩,rfl,budgeted⟩
+ · change choiceBits (R.front pub m parent old ++ es) = _
+ rw [PrimedInputRAM.Flow.choiceBits_append,R.front_choices pub m]
+ have quiet := TraversalPlan.canonicalAction_noChoices B ties stride order R.state R.choice R.port R.degree n
+ R.rowEnd R.oldNode parent R.room old new m (TraversalControllerInputs.levelHead pub m R.level).val
+ (TraversalControllerInputs.levelHead pub m (R.level+1)).val R.geometry ha
+ rw [quiet,List.append_nil]
+ exact bitsEq.symm
+ · intro current enabled label
+ change current = s at enabled
+ subst current
+ exact (counts label).trans (congrArg (H s label + ·)
+ (TraversalPlan.origin_emitted_count B order R.state R.choice R.port new before f hf w label))
+
+include ready hw shape typed nodeBound positive cacheFit limitFit capFit in
+set_option maxHeartbeats 1500000 in
+/-- Both directions of the single selected term row. The returned job has
+the exact address, choice word and natural exponents on its enabled scratch,
+and prepares the singleton child and every pending sibling. -/
+theorem origin_steps :
+ (∀ bs job tail, (hook).read (parent : BurstRAM.Word bits) s bs = some (job,tail) →
+ ∃ before : assignment, ∃ w : (seen before new).Choice, bs = bitsOf before new w ++ tail ∧
+ RealizesJob H ⟨parent,bitsOf before new w,(seen before new).exponents w⟩ job ∧
+ job.enabled s ∧ valid (child before::pending) (job.update s)) ∧
+ (∀ before : assignment, ∀ w : (seen before new).Choice, ∀ tail, ∃ job,
+ (hook).read (parent : BurstRAM.Word bits) s (bitsOf before new w ++ tail) = some (job,tail) ∧
+ RealizesJob H ⟨parent,bitsOf before new w,(seen before new).exponents w⟩ job ∧
+ job.enabled s ∧ valid (child before::pending) (job.update s)) := by
+ have hp := RefreshHalfDecoder.parent_eq R.nextState site R.arena parent s new ready.frontier.head.2.2.2 hw
+ have choice bs tail := R.origin_tape_iff ties stride order pub m f hf (parent : BurstRAM.Word bits) s bs tail new hp
+ have effect := origin_effect (R := R) (ties := ties) (stride := stride) (order := order) (pub := pub) (m := m)
+ (f := f) (hf := hf) (new := new) (data := data) (offset := offset) (vals := vals) (format := format)
+ (desc := desc) (nodeCap := nodeCap) (limit := limit) (pending := pending) (s := s) ready hw shape typed
+ nodeBound positive cacheFit limitFit capFit
+ constructor
+ · intro bs job tail hit
+ obtain ⟨before,w,tape⟩ := (choice bs tail).mp ⟨job,hit⟩
+ rw [tape] at hit
+ exact ⟨before,w,tape,effect before w tail job hit⟩
+ · intro before w tail
+ obtain ⟨job,hit⟩ := (choice (bitsOf before new w ++ tail) tail).mpr ⟨before,w,rfl⟩
+ exact ⟨job,hit,effect before w tail job hit⟩
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookExact.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookExact.lean
new file mode 100644
index 0000000000..0016ae8a9e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookExact.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.PairRefreshHookPath
+import OAI.Computability.VPVNP.PairRefreshTraversalQuiet
+
+/-!
+# Exact hook at a selected native refresh row
+
+The popped node identifies the resident row. Its typed newer half is already
+in private memory. The role consumes exactly the bits of its independent older
+half, then executes the selected diagonal and motif. A short half rejects in
+the field loader. An incompatible complete pair rejects in the map body, even
+with additional choices available to the continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh CompressorRecords CompressorRecords.PortRefresh
+open NodeArguments NodeArguments.ChildScan VertexImage DFS
+open CompressorRecords.PortRefresh.NewSlots
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {bits n hist t pcs regs : ℕ}
+ (R : Site B n hist bits) (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (loc : Fin (RefreshVertex.refreshSegment B ties stride order).count → Fin pcs)
+ (dfs : Fin 9 ↪ Fin regs) (saved : Saved ↪ Fin regs)
+ (reg : Fin (RefreshVertex.refreshSegment B ties stride order).privateRegs ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11) (m : Memory bits)
+
+local notation "segment" => RefreshVertex.refreshSegment B ties stride order
+local notation "act" => R.action ties stride order M.publicData m
+local notation "read" => R.read ties stride order M.publicData m
+
+/-- The fields used by the refresh row at entry to the DFS role. -/
+def At (node : BurstRAM.Word bits) (c : Config bits pcs regs) : Prop :=
+ c.pc = loc (segment).entry ∧ c.reg (dfs 7) = node ∧ c.reg (dfs 6) = word n ∧ R.Prepared node (scratch n c.privateMem)
+
+private theorem quiet (x z s es next) (h : act x z s = some (es,next)) : choiceBits es = [] :=
+ TraversalPlan.canonicalAction_noChoices B ties stride order R.state R.choice R.port R.degree n R.rowEnd
+ R.oldNode R.parent R.room x z m (TraversalControllerInputs.levelHead M.publicData m R.level).val
+ (TraversalControllerInputs.levelHead M.publicData m (R.level+1)).val R.geometry h
+
+variable (installed : ∀ i, M.code (loc i) = ((RefreshVertex.refreshSegment B ties stride order).row loc dfs saved reg done i).resize bits)
+ (apartD : ∀ i j, reg i ≠ dfs j) (apartS : ∀ i j, reg i ≠ saved j)
+ (facts : R.Published ties stride M.publicData m)
+
+include installed apartD apartS facts in
+set_option maxHeartbeats 1500000 in
+theorem site_realizes :
+ ShrinkRole.Realizes read M m dfs (R.At ties stride order loc dfs) (fun _ _ out => out.pc = done) := by
+ apply RefreshHook.realizes R.state R.olderSite R.nextState R.newerSite R.arena R.oldNode R.parent
+ (R.front M.publicData m) act (R.front_choices M.publicData m) (R.quiet ties stride order M m)
+ M m dfs (R.At ties stride order loc dfs) done
+ · intro node c hc
+ obtain ⟨new,stored⟩ := hc.2.2.2.2.2
+ have pos : 0 < bits := by
+ have hw := facts.wide
+ have positive := Nat.two_pow_pos S.portExponent
+ by_contra! hn
+ have hz : bits=0 := by omega
+ rw [hz,pow_zero] at hw
+ omega
+ exact ⟨new,RefreshHalfDecoder.parent_eq R.nextState R.newerSite R.arena R.parent _ new stored pos⟩
+ · intro node c bs hc hs
+ exact R.short_path ties stride order loc dfs saved reg done M m installed facts c hc.1
+ ((congrArg Fin.val hc.2.1).trans hc.2.2.2.1) bs hs
+ · intro node c x z tail hc hp ha
+ have path := R.action_path ties stride order loc dfs saved reg done M m installed apartD apartS facts
+ node c hc.1 hc.2.1 hc.2.2.1 hc.2.2.2 x z hp
+ dsimp only at path
+ rw [ha] at path
+ exact path tail
+ · intro node c x z es next hc hp ha
+ have path := R.action_path ties stride order loc dfs saved reg done M m installed apartD apartS facts
+ node c hc.1 hc.2.1 hc.2.2.1 hc.2.2.2 x z hp
+ dsimp only at path
+ rw [ha] at path
+ obtain ⟨out,hpc,frame,upper,pathToExit,_⟩ := path
+ exact ⟨out,hpc,frame,upper,pathToExit⟩
+
+include installed apartD apartS facts in
+/-- The actual instruction table realizes the local parser for every
+private tape on the selected refresh row, including failure on short and
+incompatible inputs. A successful parse returns its untouched suffix. -/
+theorem site_exact :
+ (R.hook ties stride order M.publicData m).ExactOn R.Prepared M (loc (segment).entry) done dfs m := by
+ apply (R.site_realizes ties stride order loc dfs saved reg done M m installed apartD apartS facts).exactOn
+ · intro node s bs out rest _ parsed
+ exact RefreshHook.splits R.state R.olderSite R.nextState R.newerSite R.arena R.oldNode R.parent
+ (R.front M.publicData m) act (R.front_choices M.publicData m) (R.quiet ties stride order M m)
+ node s bs out rest parsed
+ · intro node c top pending dom entry
+ exact ⟨entry.pc,entry.nodeWord,entry.endWord,dom⟩
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookFrozenSite.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookFrozenSite.lean
new file mode 100644
index 0000000000..8889e91268
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookFrozenSite.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairRefreshHookVertexPublished
+import OAI.Computability.VPVNP.PairTerminalSiteDirectories
+
+/-!
+# The refresh hook after preceding physical site calls
+
+The linked site's external memory preserves the selected history, placement
+pointers and DFS rows from the completed vertex entry. These facts recover
+the published refresh hook after earlier sites have flushed their motif counts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.RefreshHook.SelectedPublished
+
+open BurstRAM Compression Compression.Refresh CompressorRecords PortRefresh NewSlots
+open LocalHistory TraversalRoles TraversalRows DescriptorSpace TerminalProgram
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {n l g hist : ℕ} (G : LiveProgram.PairStages.Group) (workspace : BurstRAM.Word G.w)
+ (positions blocks : ℕ)
+ (budget : blocks * S.laneBits ≤ l) (initial : State (S.degreeExponent 0) l)
+ (branch : (B.execute f hf blocks budget initial).Choices)
+ (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (record : List Bool) (port : (X.Base × BitWord g) × Fin (2 ^ S.portExponent))
+ (stage : Fin (executeLevels B f hf blocks budget initial branch).length)
+ (occurrence : (executeLevels B f hf blocks budget initial branch)[stage] =
+ RefreshPlacement.traversalLevel f hf X choice record)
+
+local notation "layout" => BlockProgram.layout B workspace.val positions blocks
+local notation "levels" => executeLevels B f hf blocks budget initial branch
+local notation "tags" => TraversalRoles.selected B f hf blocks budget initial branch
+local notation "cap" => BlockSchedule.Templates.recordLimit B
+local notation "first" => endAddress layout
+local notation "rowEnd" => first + tagWords cap tags
+local notation "ord" => Fin.val (sites X.baseIndex (bitWordFinEquiv g) port)
+local notation "child" => address cap (layerBase cap first tags stage.val) ord
+local notation "parent" => address cap (layerBase cap first tags (stage.val + 1)) ord
+local notation "width" =>
+ State.totalWidth (StateExecution.finalState (B.execute f hf blocks budget initial) branch)
+
+include occurrence in
+theorem at_site {tab : Fin (layout).shape.tables} {baseBits laneBits ordinal : ℕ}
+ {calendar vertex current : Memory G.w} {wireBits : Fin width → Bool}
+ (entry : VertexEntry B f hf blocks budget initial branch layout tab baseBits laneBits
+ (terminalOperands G) calendar vertex wireBits)
+ (history : SelectedPayloadHistory.Past B f hf layout
+ (CompiledResident.payload B f hf workspace positions blocks n) levels calendar)
+ (packed : VertexPacked G layout cap tags width)
+ (frame : LinkedVertexMemory G vertex ordinal current)
+ (fits : TraversalPlan.Room B X choice port (slotDegree S) n rowEnd child parent hist G.w) :
+ let R := ofSelected B n hist G.w workspace.val positions blocks X choice port stage.val
+ tags width fits
+ R.Published (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride
+ (terminalOperands G) current := by
+ have lastLive : (selectedLayers B f hf blocks budget initial branch).dropLast.length <
+ (layout).levels := by
+ rw [TerminalBootstrap.selected_prior_length, BlockProgram.actual_level_count,
+ Nat.mul_comm blocks]
+ omega
+ have allLive : (levels).length < (layout).levels :=
+ (executeLevels_length B f hf blocks budget initial branch).trans_lt (by
+ rw [BlockProgram.actual_level_count]
+ omega)
+ have prior := entry.payload B f hf blocks budget initial branch lastLive history
+ obtain ⟨⟨ds, resident⟩, past⟩ := packed.site_operands frame entry allLive
+ (by change 28 ≤ 54; decide) prior
+ have data := RefreshHookRetained.ofPast B f hf workspace positions blocks n X choice past
+ stage record occurrence
+ have layerEq := selected_layers B f hf blocks budget initial branch
+ have rowMem := packed.rows frame (layerEq ▸ selected_capacity B f hf blocks budget initial branch)
+ (layerEq ▸ entry.rows)
+ rw [layerEq] at rowMem
+ exact from_resident B f hf blocks budget initial branch X choice record port stage occurrence
+ workspace.val positions blocks fits data.size data.live ds resident rowMem data.sources
+ data.child
+
+end PairSimulation.RefreshHook.SelectedPublished
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookGuard.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookGuard.lean
new file mode 100644
index 0000000000..b92f287db1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookGuard.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairRefreshHookNative
+import OAI.Computability.VPVNP.PairRefreshGuardLayout
+import OAI.Computability.VPVNP.PairRefreshHookWrites
+import OAI.Computability.VPVNP.PairRefreshHookBudget
+import OAI.Computability.VPVNP.PairDispatchedRowEffects
+
+/-!
+# The guarded refresh visit at the physical role dispatcher
+
+The role tag, the placed node's source ranges and its accepted native parser
+determine one DFS job. The linked execution of that job preserves external
+memory, avoids both scheduler control cells, and satisfies the ordinal work
+and probe bounds at all sufficiently large lengths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace
+open PortRefresh NewSlots NodeArguments TreeDecode VertexImage DFS
+open TraversalControllerInputs LiveProgram Filter
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {hist : ℕ} (order : B.Entry ≃ Fin hist)
+
+local notation "ties" => RefreshBlockPlan.order B
+local notation "stride" => LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)
+
+variable (constants : Constants) (p q : ℕ)
+local notation "segments" => TerminalProgram.nativeSegments B constants p q order
+
+/-- All parts of the guard refer to the same role job recovered by this
+successful parse, including its exact read support and its enclosing dispatch. -/
+theorem eventually_dispatched_guard :
+ ∀ᶠ n : ℕ in atTop, ∀ {w pcs regs : ℕ} (R : Site B n hist w)
+ (V : Placement segments pcs regs) (M : Machine w pcs regs 11) (m : Memory w)
+ (start positions blocks : ℕ)
+ (prev next : Fin (BlockProgram.layout B start positions blocks).levels),
+ Contains V M → R.Published ties stride M.publicData m →
+ GuardLayout B R M.publicData m start positions blocks prev next →
+ NodeDispatch.role (m (R.roleOffset + word R.parent).val) = .refresh →
+ R.later ≤ (S.steps + 1) * (n.log2 + 1) →
+ ∀ (power scanCap : ℕ), 1 ≤ power → scan B ties stride order ≤ scanCap →
+ ∀ (s : Scratch w n) (bs tail : List Bool) (body : VisitPath w n),
+ R.Prepared (word R.parent) s →
+ (R.hook ties stride order M.publicData m).read (word R.parent) s bs = some (body, tail) →
+ let job := dispatchJob m R.roleOffset (word R.parent) s body
+ job.enabled s ∧ JobGuard V M m (TerminalLink.workerCell (TerminalLink.header M.publicData))
+ (ordinalJobCost n power scanCap) job := by
+ filter_upwards [eventually_ordinal_cost B ties stride order] with n clock
+ intro w pcs regs R V M m start positions blocks prev next installed facts layout tag later
+ power scanCap hp hs s bs tail body prepared hit
+ let pub := M.publicData
+ let node : Word w := word R.parent
+ let job := dispatchJob m R.roleOffset node s body
+ have native := (R.site_exact_installed constants p q order V M m installed facts).success
+ node s prepared bs body tail hit
+ obtain ⟨⟨out, rest⟩, found, equal⟩ := Option.map_eq_some_iff.mp hit
+ have eqBody : body.trace = out.trace := by
+ exact (congrArg VisitPath.trace (Prod.mk.inj equal).1).symm
+ have eqRest := (Prod.mk.inj equal).2
+ subst rest
+ have rawMem : after m body.trace = m :=
+ eqBody ▸ R.read_after ties stride order pub m found
+ have rawRead := R.read_worker_layout order pub m start positions blocks prev next facts
+ layout.size layout.below layout.headerFit layout.oldHead layout.newHead layout.scratch
+ layout.oldCols layout.newCols layout.levels layout.parentBefore layout.listBefore
+ prepared.1 found
+ let allowed := TerminalLink.workerCell (TerminalLink.header pub)
+ have rawGuard : RoleJobGuard V M m .refresh allowed (fun _ => True) body :=
+ ⟨native.2.2.2, rawMem, eqBody ▸ rawRead, trivial⟩
+ have tagCell : allowed (R.roleOffset + node).val :=
+ TerminalLink.workerCell_of_lt (by
+ change (TerminalLink.header M.publicData).val + 31 < 2 ^ w
+ have := layout.headerFit
+ omega) layout.tagBefore
+ have small := clock R pub m R.roleOffset node s bs out tail job later found
+ (congrArg (dispatchEvents m R.roleOffset node ++ ·) eqBody)
+ have bound : ordinalJobCost n power scanCap job := by
+ refine ⟨small.1.trans (Nat.mul_le_mul hs ?_), small.2⟩
+ exact Nat.pow_le_pow_right (Nat.succ_pos _) hp
+ exact ⟨⟨rfl, native.2.1⟩, dispatchJob_guard installed prepared.2.1 tag tagCell native.1 rawGuard
+ (fun _ => bound)⟩
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookNative.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookNative.lean
new file mode 100644
index 0000000000..59b098d5ac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookNative.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.PairRefreshHookExact
+import OAI.Computability.VPVNP.PairTerminalNativeTable
+
+/-! # The selected refresh parser in the compressed pair's physical table
+
+The full eleven-operand vertex image supplies the refresh rows, their register
+separation and their return address. A published selected site can therefore
+be interpreted using the canonical numerical template itself.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM PrivateRAM Compression CompressorRecords VertexImage LiveProgram
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {n hist bits pcs regs : ℕ}
+ (R : Site B n hist bits) (constants : Constants) (p q : ℕ) (order : B.Entry ≃ Fin hist)
+local notation "segments" => TerminalProgram.nativeSegments B constants p q order
+local notation "ties" => RefreshBlockPlan.order B
+local notation "stride" => PortRefresh.LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)
+
+/-- The exact hook at the refresh entry of the actual linked vertex image. -/
+theorem site_exact_installed (V : Placement segments pcs regs) (M : Machine bits pcs regs 11) (m : Memory bits)
+ (contains : Contains V M) (facts : R.Published ties stride M.publicData m) :
+ (R.hook ties stride order M.publicData m).ExactOn R.Prepared M (V.entry .refresh) (V.dfsPC 3) V.dfs m := by
+ apply R.site_exact ties stride order (V.stage .refresh) V.dfs V.saved (V.localRegs .refresh) (V.dfsPC 3) M m
+ · exact stage_linked V M contains .refresh
+ · intro i j
+ exact V.reg.injective.ne (by simp)
+ · intro i j
+ exact V.reg.injective.ne (by simp)
+ · exact facts
+
+set_option maxHeartbeats 1500000 in
+/-- The canonical instruction and register numbering meets the same exact
+hook specification for every resident selected site. -/
+theorem site_exact_native (pub : Fin 11 → Word bits) (m : Memory bits) (facts : R.Published ties stride pub m) :
+ let V := placement segments
+ let M := (template segments).instantiate bits pub
+ (R.hook ties stride order pub m).ExactOn R.Prepared M (V.entry .refresh) (V.dfsPC 3) V.dfs m := by
+ intro V M
+ exact R.site_exact_installed constants p q order V M m (template_contains segments pub) facts
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookOrigin.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookOrigin.lean
new file mode 100644
index 0000000000..ce6858387b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookOrigin.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairRefreshHookWitness
+import OAI.Computability.VPVNP.PairRefreshTraversalOriginBits
+import OAI.Computability.VPVNP.PairTreeNodeReaders
+
+/-! # Equality of the refresh hook and the selected term reader on suffixes
+
+The physical row and the mathematical term both consume the sole placed
+child's half. The successful kernel witness consumes the empty word. These
+equalities characterize every accepted suffix, including an empty child.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords CompressorRecords.PortRefresh NewSlots NodeArguments NodeArguments.ChildScan
+open LocalHistory VertexImage DFS NetworkKernel
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {bits n hist t : ℕ}
+ (R : Site B n hist bits) (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (pub : Fin 11 → BurstRAM.Word bits) (m : Memory bits)
+variable {K : Type*} [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f)
+local notation "reader" => originReader B f hf (PassOrigin.refresh R.state) R.choice
+local notation "site" => R.newerSite
+
+set_option maxHeartbeats 1200000 in
+/-- Every complete physical local prefix is the corresponding term
+reader's own word, and every such term word is consumed on the real row. -/
+theorem origin_tape_iff (node : BurstRAM.Word bits) (s : Scratch bits n) (bs tail : List Bool)
+ (new : R.nextState.network.Half site)
+ (hp : RefreshHalfDecoder.parent R.nextState site R.arena R.parent s = some new) :
+ (∃ job, (R.hook ties stride order pub m).read node s bs = some (job,tail)) ↔
+ ∃ before, ∃ w : ((reader).witness site before new).Choice, bs = (reader).nodeBits site before new w ++ tail := by
+ rw [R.hook_witness_iff ties stride order pub m f hf node s bs tail new hp]
+ constructor
+ · rintro ⟨before,tape,⟨w⟩⟩
+ refine ⟨before,w,?_⟩
+ rw [TraversalPlan.origin_nodeBits B f hf R.state R.choice R.port before new w]
+ exact tape
+ · rintro ⟨before,w,tape⟩
+ refine ⟨before,?_,⟨w⟩⟩
+ rwa [TraversalPlan.origin_nodeBits B f hf R.state R.choice R.port before new w] at tape
+
+private theorem map_snd_eq {α : Type*} (value : Option (α × List Bool)) (tail : List Bool) :
+ value.map Prod.snd = some tail ↔ ∃ x, value = some (x,tail) := by
+ cases value with
+ | none => simp
+ | some pair => cases pair; simp
+
+set_option maxHeartbeats 1200000 in
+/-- Equality of the actual and semantic unconsumed streams. A rejection
+by either parser excludes every returned suffix. -/
+theorem origin_suffix (node : BurstRAM.Word bits) (s : Scratch bits n) (bs : List Bool)
+ (new : R.nextState.network.Half site)
+ (hp : RefreshHalfDecoder.parent R.nextState site R.arena R.parent s = some new) :
+ ((R.hook ties stride order pub m).read node s bs).map Prod.snd =
+ ((TreeDecode.nodeReader (reader) site new).read bs).map Prod.snd := by
+ let native := (R.hook ties stride order pub m).read node s bs
+ let C := TreeDecode.nodeReader (reader) site new
+ have test (tail : List Bool) : native.map Prod.snd = some tail ↔ (C.read bs).map Prod.snd = some tail := by
+ rw [map_snd_eq native tail,map_snd_eq (C.read bs) tail]
+ rw [R.origin_tape_iff ties stride order pub m f hf node s bs tail new hp]
+ constructor
+ · rintro ⟨before,w,tape⟩
+ exact ⟨⟨before,w⟩,(C.read_iff bs ⟨before,w⟩ tail).mpr tape⟩
+ · rintro ⟨⟨before,w⟩,hit⟩
+ exact ⟨before,w,(C.read_iff bs ⟨before,w⟩ tail).mp hit⟩
+ change native.map Prod.snd = (C.read bs).map Prod.snd
+ cases h : (C.read bs).map Prod.snd with
+ | some tail => exact (test tail).mpr h
+ | none =>
+ cases p : native.map Prod.snd with
+ | none => rfl
+ | some tail =>
+ have impossible := (test tail).mp p
+ rw [h] at impossible
+ cases impossible
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookPacketFrame.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookPacketFrame.lean
new file mode 100644
index 0000000000..8b9c82661f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookPacketFrame.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairRefreshHookReader
+import OAI.Computability.VPVNP.PairRefreshVertexPacket
+import OAI.Computability.VPVNP.PairShrinkOldHalfAddresses
+
+/-!
+# Physical packets and the DFS stack across a refresh hook
+
+The scratch projection of a stored parent supplies all independent native
+slot operands. Loading the unique refresh child performs exactly the packet
+write in the hook reader. The load and the selected map preserve the DFS
+registers and every stack word below the scratch boundary.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook
+
+open BurstRAM PrivateRAM Compression CompressorRecords.RefreshMapOperands DFS
+open NodeArguments NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {w a g n p r : ℕ}
+
+/-- Decode each field from the popped packet in the native private memory. -/
+theorem stored_nodeFields (X : State a g) (v : X.network.Site) (new : X.network.Half v)
+ (A : Arena) (node : ℕ) (priv : Word w → Word w)
+ (fit : (Packet.mk node (packed X v new)).Fits A w n)
+ (stored : (Packet.mk node (packed X v new)).Stored A (scratch n priv)) :
+ NodeFields A node X v new priv :=
+ Packet.read_field X v new A node priv fit stored
+
+variable (X : State a g) (v : X.network.Site) (old : X.network.Half v) (A : Arena) (older cap : ℕ)
+local notation "child" => childNode X older cap v
+local notation "data" => Child.ofHalf X v old
+local notation "loaded" => Child.packet X older cap (Child.ofHalf X v old)
+
+/-- The unique packet assembled by the native half reader is the packet
+whose logical update precedes the canonical refresh action. -/
+theorem child_packet : loaded = packet X v child old := by
+ change Packet.mk child ((data).payload X) = Packet.mk child (packed X v old)
+ rw [Child.payload_ofHalf]
+
+theorem child_scratch {priv next : Word w → Word w}
+ (load : next = storePackets A [loaded] priv) :
+ scratch n next = (packet X v child old).write A (scratch n priv) := by
+ rw [load,scratch_storePackets,child_packet]
+ rfl
+
+/-- The load writes the child's argument interval, entirely above the stack.
+Its ordinary registers are in a private bank disjoint from every DFS register. -/
+theorem child_frame {front : ℕ} (dfs : Fin 9 ↪ Fin r) (bank : Fin front ↪ Fin r)
+ (apart : ∀ i j, bank i ≠ dfs j) (c mid : Config w p r)
+ (load : mid.privateMem = storePackets A [loaded] c.privateMem)
+ (per : mid.persistent = c.persistent)
+ (regs : ∀ i, i ∉ Set.range bank → mid.reg i = c.reg i)
+ (fit : (packet X v child old).Fits A w n) : ShrinkRole.Frame dfs n c mid := by
+ refine ⟨fun i _ => regs _ (fun ⟨j,hj⟩ => apart j i hj), ?_, per⟩
+ intro q hq
+ exact (congrFun load q).trans (RefreshVertexPacket.outside X v old A older cap c.privateMem
+ fit.2.2 q (.inl (hq.trans_le fit.1)))
+
+/-- The map can change the histogram and its work area. Every stack address
+is below both, and each histogram address has its genuine natural value. -/
+theorem body_frame {h bankSize histBase dir : ℕ} (dfs : Fin 9 ↪ Fin r) (bank : Fin bankSize ↪ Fin r)
+ (apart : ∀ i j, bank i ≠ dfs j) (mid out : Config w p r)
+ (per : out.persistent = mid.persistent)
+ (regs : ∀ j, (∀ i, j ≠ bank i) → out.reg j = mid.reg j)
+ (mem : ∀ q : Word w, q.val < dir →
+ (∀ i : Fin h, q ≠ ((histBase+i.val : ℕ) : Word w)) → out.privateMem q = mid.privateMem q)
+ (low : n ≤ histBase) (work : n ≤ dir) (histFit : histBase+h ≤ 2^w) :
+ ShrinkRole.Frame dfs n mid out := by
+ refine ⟨fun i _ => regs _ (fun j eqn => apart j i eqn.symm), ?_, per⟩
+ intro q hq
+ apply mem q (hq.trans_le work)
+ intro i eqn
+ have index : (((histBase+i.val : ℕ) : Word w)).val = histBase+i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans_le histFit)
+ exact (hq.trans_le (low.trans (Nat.le_add_right _ _))).ne ((congrArg Fin.val eqn).trans index)
+
+end PairSimulation.RefreshHook
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookPath.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookPath.lean
new file mode 100644
index 0000000000..fb60b7fa00
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookPath.lean
@@ -0,0 +1,183 @@
+import OAI.Computability.VPVNP.PairRefreshHookSite
+import OAI.Computability.VPVNP.PairRefreshTraversalExact
+import OAI.Computability.VPVNP.PairRefreshHookPacketFrame
+
+/-!
+# Exact native action of one selected refresh row
+
+The successful action is fixed by the frozen level, the parsed old half and
+the incoming upper scratch. The proof follows the physical role from its entry
+to the common DFS continuation. A failed local action excludes a return for
+every continuation and fuel.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords CompressorRecords.PortRefresh RefreshMapOperands NewSlots
+open NodeArguments NodeArguments.ChildScan
+open TraversalControllerInputs VertexImage DFS
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+ {bits n hist t pcs regs : ℕ} (R : Site B n hist bits)
+ (ties : Fin t ≃ Tie (2 ^ S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (loc : Fin (RefreshVertex.refreshSegment B ties stride order).count → Fin pcs)
+ (dfs : Fin 9 ↪ Fin regs) (saved : Saved ↪ Fin regs)
+ (reg : Fin (RefreshVertex.refreshSegment B ties stride order).privateRegs ↪ Fin regs)
+ (done : Fin pcs)
+ (M : Machine bits pcs regs 11) (m : Memory bits)
+
+local notation "body" => TraversalPlan.body B ties stride order
+local notation "locator" => TraversalPlan.locatorBank B ties stride order
+local notation "bodyLoc" => RefreshVertexAssembly.bodyPC S.portExponent body locator loc
+local notation "bodyBank" => RefreshVertexAssembly.bodyRegs S.portExponent body locator reg
+local notation "segment" => RefreshVertex.refreshSegment B ties stride order
+local notation "H₀" => LeafArena.Regions.histBase (regions R)
+local notation "A" => arena R
+local notation "P" => parent R
+local notation "W" => BurstRAM.Word bits
+local notation "O" => NewSlots.sites (State.baseIndex (state R)) (bitWordFinEquiv (lanes R))
+local notation "oldSite" => olderSite R
+local notation "newSite" => newerSite R
+local notation "X" => state R
+local notation "Y" => nextState R
+local notation "child" => oldNode R
+
+variable (installed : ∀ i, M.code (loc i) =
+ ((RefreshVertex.refreshSegment B ties stride order).row loc dfs saved reg done i).resize bits)
+ (apartD : ∀ i j, reg i ≠ dfs j) (apartS : ∀ i j, reg i ≠ saved j)
+ (facts : R.Published ties stride M.publicData m)
+
+include facts in
+private theorem wordPos : 0 < bits := by
+ have upper := facts.wide
+ have pos := Nat.two_pow_pos S.portExponent
+ by_contra! no
+ have zero : bits=0 := Nat.eq_zero_of_le_zero no
+ rw [zero,pow_zero] at upper
+ omega
+
+include installed facts in
+/-- At this frozen row, a missing child half rejects before the map starts. -/
+theorem short_path (c : Config bits pcs regs) (entry : c.pc = loc (segment).entry)
+ (node : (c.reg (dfs 7)).val = P) (bs : List Bool)
+ (short : bs.length < RefreshHalfDecoder.width X oldSite) :
+ ¬ Returns M c m bs := by
+ obtain ⟨h,f,pit,off,base,initial,ls,j,id,heads,hj,_,_,pos,last⟩ := facts.location
+ let z : (X).network.Half oldSite := (fun _ _ _ => false,fun _ _ _ => false)
+ have e := TraversalGeometry.argument_end R.degree n R.rowEnd hist X oldSite z child
+ R.room.childBound R.room.oldDegree R.room.oldWidth
+ have histFit : H₀ < 2^bits :=
+ ((Nat.le_add_right ..).trans (Nat.le_add_right ..)).trans_lt R.room.capacity.room
+ exact RefreshVertexAssembly.reject_short S.portExponent body locator loc dfs saved reg done M
+ installed X oldSite z R.prev m A R.older B.recordLimit R.listHead heads j R.level hj id c entry
+ (node.trans pos) last facts.fields (node.symm ▸ facts.children) facts.oldCols facts.strideFit
+ (facts.before.trans (node ▸ (c.reg (dfs 7)).isLt)) (e.trans_lt histFit) bs
+ (by rwa [packed_length])
+
+set_option maxHeartbeats 1400000 in
+-- Joining the dependent child and map executions requires matching their register banks and frames.
+include installed facts apartD apartS in
+theorem action_path (node : W) (c : Config bits pcs regs) (entry : c.pc = loc (segment).entry)
+ (popped : c.reg (dfs 7) = node) (endWord : c.reg (dfs 6) = word n)
+ (ready : R.Prepared node (scratch n c.privateMem))
+ (old : (X).network.Half oldSite) (new : (Y).network.Half newSite)
+ (readParent : RefreshHalfDecoder.parent Y newSite A P (scratch n c.privateMem) = some new) :
+ let packet := RefreshHook.packet X oldSite child old
+ let front := R.front M.publicData m node old
+ match R.action ties stride order M.publicData m old new
+ (packet.write A (scratch n c.privateMem)) with
+ | none => ∀ tail, ¬ Returns M c m (packed X oldSite old ++ tail)
+ | some (es,next) =>
+ ∃ out, out.pc = done ∧ ShrinkRole.Frame dfs n c out ∧ scratch n out.privateMem = next ∧
+ ChildScan.Prefix M m c out (packed X oldSite old) (front++es) ∧
+ ∀ i : Fin hist, out.privateMem (word (H₀+i.val)) = c.privateMem (word (H₀+i.val)) +
+ (((TraversalPlan.emitted B order X R.choice R.port old new).getD []).count i : W) := by
+ intro packet front
+ obtain ⟨atNode,resident,typed,typedStored⟩ := ready
+ have decoded := RefreshHalfDecoder.parent_eq Y newSite A P (scratch n c.privateMem)
+ typed typedStored (wordPos R ties stride M m facts)
+ obtain rfl := Option.some.inj (readParent.symm.trans decoded)
+ have parentData : NodeFields A P Y newSite new c.privateMem := fun dir j i =>
+ Packet.read_field Y newSite new A P c.privateMem (R.newFit new) typedStored dir j i
+ obtain ⟨h,f,pit,off,base,initial,ls,j,id,heads,hj,siteEq,later,pos,last⟩ := facts.location
+ have nodeVal := (congrArg Fin.val popped).trans atNode
+ have histLimit : H₀+hist ≤ R.regions.cacheBase := Nat.le_add_right ..
+ have histFits := histLimit.trans_lt R.room.capacity.room
+ have oldEnd := TraversalGeometry.argument_end R.degree n R.rowEnd hist X oldSite old child
+ R.room.childBound R.room.oldDegree R.room.oldWidth
+ have oldFit := oldEnd.trans_lt ((Nat.le_add_right ..).trans_lt histFits)
+ have early : n < (A).base child :=
+ Nat.lt_add_of_pos_right (Nat.mul_pos facts.positive (Nat.succ_pos _))
+ have row' : Row m (c.reg (dfs 7)).val R.listHead [word child] := nodeVal.symm ▸ facts.children
+ obtain ⟨mid,first,atBody,located,mem,per,keep⟩ :=
+ RefreshVertexAssembly.load_child S.portExponent body locator loc dfs saved reg done M installed
+ X oldSite old R.prev m A R.older B.recordLimit R.listHead heads j R.level hj id c entry
+ (nodeVal.trans pos) last facts.fields row' facts.oldCols facts.strideFit
+ (facts.before.trans (atNode ▸ node.isLt)) oldFit
+ have locRun : ChildScan.Prefix M m c mid (packed X oldSite old) front := by
+ unfold front Site.front
+ rw [later,← popped]; exact first
+ have geom' := RefreshVertexPacket.geometry X oldSite old A R.older B.recordLimit c.privateMem
+ R.geometry R.roleOffset (word H₀) resident early (oldEnd.trans facts.roleAfter)
+ (oldEnd.trans facts.histAfter)
+ have old' := RefreshVertexPacket.fields X oldSite old A R.older B.recordLimit c.privateMem
+ oldFit.le
+ have new' := RefreshVertexPacket.parent_fields X oldSite old A R.older B.recordLimit c.privateMem
+ Y newSite new P facts.before (R.oldFit old).2.1 (R.newFit new).2.2 parentData
+ have stack' := (keep (dfs 6) (fun ⟨i,e⟩ => apartD i 6 e)).trans endWord
+ have fitId : id.val < 2^bits := by
+ have small : id.val ≤ TraversalRows.address B.recordLimit
+ (TraversalRoles.layerBase B.recordLimit base (initial::ls.map Prod.fst) j) id :=
+ (Nat.le_mul_of_pos_left _ (by omega : 0 apartD _ i) (fun _ i => apartS _ i) mid atBody stack' (mem ▸ geom')
+ (congrArg Fin.val located.oldHead) (congrArg Fin.val located.state.current) site'
+ ((congrArg Fin.val located.state.node).trans nodeVal) facts.headers facts.children
+ facts.lanesFit facts.terms facts.oldCols facts.newCols (mem ▸ old') (mem ▸ new') facts.wide _ sc
+ unfold action
+ cases eqn : TraversalPlan.canonicalAction B ties stride order X R.choice R.port R.degree n
+ R.rowEnd child P R.room old new m (levelHead M.publicData m R.level).val
+ (levelHead M.publicData m (R.level+1)).val R.geometry
+ (packet.write A (scratch n c.privateMem)) with
+ | none =>
+ rw [eqn] at res
+ exact fun tail => mt (locRun.returns tail).mp (res tail)
+ | some value =>
+ obtain ⟨es,next⟩ := value
+ rw [eqn] at res
+ obtain ⟨out,bodyRun,_,_,_,stop,persist,regs',external,hits,updated⟩ := res
+ have cf := RefreshHook.child_frame X oldSite old A R.older B.recordLimit dfs reg apartD
+ c mid mem per keep (R.oldFit old)
+ have low : n ≤ H₀ := Nat.le_add_right ..
+ have bf := RefreshHook.body_frame dfs bodyBank (fun _ j => apartD _ j) mid out persist regs'
+ external low (by omega) histFits.le
+ have frame := cf.trans bf
+ refine ⟨out,stop,frame,updated,by simpa only [List.append_nil] using locRun.trans bodyRun,?_⟩
+ intro i
+ have histVal : (word (bits := bits) (H₀+i.val)).val = H₀+i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans histFits)
+ have histMem := RefreshVertexPacket.outside X oldSite old A R.older B.recordLimit c.privateMem
+ oldFit.le (word (H₀+i.val))
+ (Or.inr ((oldEnd.trans (Nat.le_add_right H₀ i.val)).trans histVal.symm.le))
+ exact (hits i).trans (congrArg (fun x => x+_) ((congrFun mem _).trans histMem))
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookReadSupport.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookReadSupport.lean
new file mode 100644
index 0000000000..a306b97f90
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookReadSupport.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.PairRefreshHookSite
+import OAI.Computability.VPVNP.PairRefreshVertexReads
+import OAI.Computability.VPVNP.PairRefreshTraversalBounds
+import OAI.Computability.VPVNP.PairRefreshTraversalQuiet
+
+/-!
+# External reads of an accepted refresh hook
+
+The locator may read the terminal scalars at offsets 1, 15, 16 and 17.
+All other reads precede the terminal header. The concrete old and new
+incidence regions and refresh scratch allocation supply their address bounds.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM Compression CompressorRecords CompressorRecords.PortRefresh NewSlots
+open NodeArguments NodeArguments.ChildScan
+open TraversalControllerInputs ShrinkRole.ChildArguments DescriptorSpace
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {w n hist : ℕ}
+ (R : Site B n hist w) (order : B.Entry ≃ Fin hist) (pub : Fin 11 → Word w) (m : Memory w)
+ (start positions blocks : ℕ)
+ (prev next : Fin (BlockProgram.layout B start positions blocks).levels)
+local notation "L" => BlockProgram.layout B start positions blocks
+local notation "T" => RefreshBlockPlan.order B
+local notation "stride" => LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)
+local notation "H" => TerminalLink.header pub
+local notation "cells" => TerminalLink.workerCell H
+
+private theorem header_scalar (i : ℕ) (nonzero : 0 < i) (short : i < 31)
+ (fit : (H).val + 32 ≤ 2 ^ w) :
+ cells (terminalHead pub + (i : Word w)).val := by
+ have hw : i < 2 ^ w := by omega
+ have hi : (terminalHead pub + (i : Word w)).val = (H).val + i := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt hw,
+ Nat.mod_eq_of_lt (by change (H).val + i < 2 ^ w; omega)]
+ rfl
+ have last : (H + 31).val = (H).val + 31 := by
+ rw [show (31 : Word w) = ((31 : ℕ) : Word w) from rfl, Fin.val_add, Fin.val_natCast,
+ Nat.mod_eq_of_lt (by omega : 31 < 2 ^ w), Nat.mod_eq_of_lt (by omega)]
+ change _ ≠ (H).val ∧ _ ≠ (H + 31).val
+ rw [hi, last]; omega
+
+/-- A successful parse only probes the allowed words of the enclosing terminal
+worker. Both packed column sizes come from the selected old position count. -/
+theorem read_worker_layout (facts : R.Published T stride pub m)
+ (size : R.state.positions ≤ positions)
+ (below : endAddress L ≤ (H).val) (fit : (H).val + 32 ≤ 2 ^ w)
+ (oldHead : (levelHead pub m R.level).val = levelStart L prev)
+ (newHead : (levelHead pub m (R.level + 1)).val = levelStart L next)
+ (scratch : R.start = arrayBase L prev)
+ (oldCols : R.prev = packedIncidence L w prev (R.state.positions * 2 ^ S.portExponent))
+ (newCols : R.next = packedIncidence L w next (R.nextState.positions * 2 ^ (S.degreeExponent 0)))
+ (levelReads : ∀ i, R.level + 1 ≤ i → i ≤ R.level + 1 + R.later →
+ (levelHead pub m i + 14).val < (H).val)
+ (parentBefore : R.parent + 1 < (H).val) (rowBefore : R.listHead < (H).val)
+ {node : Word w} {s : DFS.Scratch w n} {bs out tail}
+ (atNode : node.val = R.parent)
+ (hit : R.read T stride order pub m node s bs = some (out, tail)) :
+ SourceTransport.Reads cells out.trace := by
+ obtain ⟨_, _, es, actionEq, path⟩ := (RefreshHook.read_some_iff R.state R.olderSite R.nextState
+ R.newerSite R.arena R.oldNode R.parent (R.front pub m) (R.action T stride order pub m)
+ node s bs out tail).mp hit
+ have limits := TraversalPlan.layout_limits (bits := w) B R.state R.choice start positions blocks
+ prev next size (below.trans_lt (H).isLt) below
+ obtain ⟨oldBefore, _, _, beforeCols, _, _⟩ := limits
+ have col : ColumnsBelow R.prev R.state (H).val := by
+ rw [oldCols]
+ exact ⟨beforeCols 4, beforeCols 5⟩
+ have baseBound : (levelHead pub m R.level + 14).val + 6 < (H).val := by
+ rw [Fin.val_add, oldHead]
+ have h14 : (14 : Word w).val = 14 := Nat.mod_eq_of_lt (by change 14 < 2 ^ w; omega)
+ rw [h14, Nat.mod_eq_of_lt (by have := (H).isLt; omega)]; omega
+ have child := worker_reads_of_below H fit (trace_reads_below facts.oldCols col node
+ (levelHead pub m R.level + 14) R.listHead [Child.ofHalf R.state R.olderSite out.value.1]
+ (atNode ▸ parentBefore) baseBound rowBefore)
+ have locate : SourceTransport.Reads cells (VertexLevel.trace pub m (R.level + 1) R.later) :=
+ VertexLevel.trace_reads _ _ (fun i hi => by
+ simp only [Finset.mem_insert, Finset.mem_singleton] at hi
+ rcases hi with rfl | rfl | rfl | rfl <;>
+ exact header_scalar pub _ (by decide) (by decide) fit)
+ (fun i lo hi => TerminalLink.workerCell_of_lt (by omega) (levelReads i lo hi))
+ have bodyReads := TraversalPlan.layout_worker_reads B R.state R.choice start positions blocks
+ prev next order R.port m R.parent R.oldNode R.listHead R.geometry R.degree n R.rowEnd R.room
+ out.value.1 out.value.2 H (by omega) size below
+ (oldHead ▸ newHead ▸ scratch ▸ oldCols ▸ newCols ▸ facts.headers) facts.children (by omega)
+ rowBefore (oldCols ▸ facts.oldCols) (newCols ▸ facts.newCols)
+ have eventEq := TraversalPlan.canonicalAction_events B T stride order R.state R.choice R.port
+ R.degree n R.rowEnd R.oldNode R.parent R.room out.value.1 out.value.2 m
+ (levelHead pub m R.level).val (levelHead pub m (R.level + 1)).val R.geometry actionEq
+ rw [oldHead, newHead] at eventEq
+ intro q v has
+ rw [path] at has
+ rcases List.mem_append.mp has with front | body
+ · rcases List.mem_append.mp front with start | next
+ · exact locate q v start
+ · rcases List.mem_append.mp next with tick | next
+ · cases List.eq_of_mem_replicate tick
+ · rcases List.mem_append.mp next with tick | actual
+ · cases List.eq_of_mem_replicate tick
+ · exact child q v actual
+ · exact bodyReads q v (eventEq ▸ body)
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookReader.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookReader.lean
new file mode 100644
index 0000000000..695e745707
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookReader.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.PairRefreshHalfDecoder
+import OAI.Computability.VPVNP.PairShrinkRoleStages
+
+/-!
+# A typed parser for the refresh hook
+
+The parent is reconstructed from its private packet, and the old half is the
+single prefix consumed from the branch tape. The local map receives the scratch
+after the packet write. A success records both halves, the exact chronological
+trace and the complete resulting scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook
+
+open NetworkKernel BurstRAM BurstRAM.PrivateRAM DFS Compression NodeArguments NodeArguments.ChildScan ShrinkRole
+open scoped Fin.CommRing
+
+variable {bits endAddr a b g l pcs regs : ℕ}
+ (X : State a g) (oldSite : X.network.Site) (Y : State b l) (newSite : Y.network.Site)
+ (A : Arena) (child parent : ℕ)
+
+local notation "Old" => Network.Half (State.network X) oldSite
+local notation "New" => Network.Half (State.network Y) newSite
+local notation "S₀" => Scratch bits endAddr
+
+variable (front : Word bits → X.network.Half oldSite → List (Event bits))
+ (action : X.network.Half oldSite → Y.network.Half newSite → Scratch bits endAddr → Option (List (Event bits) × Scratch bits endAddr))
+
+/-- Form the old child's argument packet from its DFS row address and its packed half-wire
+bits. -/
+noncomputable def packet (x : Old) : Packet := ⟨child,packed X oldSite x⟩
+
+/-- Decode the resident parent and the guessed old child, store the child packet, and invoke
+the refresh action on the two assignments. -/
+noncomputable def reader : Reader bits endAddr (Old × New) := fun node s bs =>
+ match RefreshHalfDecoder.parent Y newSite A parent s, (RefreshHalfDecoder.reader X oldSite).read bs with
+ | some newer, some (older,tail) =>
+ match action older newer ((packet X oldSite child older).write A s) with
+ | some (es,out) => some (⟨(older,newer),front node older ++ es,out⟩,tail)
+ | none => none
+ | _, _ => none
+
+
+local notation "read" => reader X oldSite Y newSite A child parent front action
+
+theorem read_some_iff (node : Word bits) (s : S₀) (bs : List Bool)
+ (out : Outcome bits endAddr (Old × New)) (tail : List Bool) :
+ read node s bs = some (out,tail) ↔
+ RefreshHalfDecoder.parent Y newSite A parent s = some out.value.2 ∧
+ bs = packed X oldSite out.value.1 ++ tail ∧
+ ∃ es, action out.value.1 out.value.2 ((packet X oldSite child out.value.1).write A s) =
+ some (es,out.updated) ∧ out.trace = front node out.value.1 ++ es := by
+ constructor
+ · intro h
+ cases hp : RefreshHalfDecoder.parent Y newSite A parent s with
+ | none => simp [reader,hp] at h
+ | some z =>
+ cases hx : (RefreshHalfDecoder.reader X oldSite).read bs with
+ | none => simp [reader,hp,hx] at h
+ | some pair =>
+ obtain ⟨x,rest⟩ := pair
+ cases ha : action x z ((packet X oldSite child x).write A s) with
+ | none => simp [reader,hp,hx,ha] at h
+ | some value =>
+ obtain ⟨es,next⟩ := value
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj (by simpa only [reader,hp,hx,ha] using h))
+ exact ⟨rfl,(RefreshHalfDecoder.read_iff X oldSite bs x rest).mp hx,es,ha,rfl⟩
+ · rintro ⟨hp,bsEq,es,ha,trace⟩
+ have hx := (RefreshHalfDecoder.read_iff X oldSite bs out.value.1 tail).mpr bsEq
+ cases out with | mk pair tr updated =>
+ cases pair with | mk x z =>
+ change tr = front node x ++ es at trace
+ subst tr
+ simp only [reader,hp,hx,ha]
+
+variable (frontChoices : ∀ node x, choiceBits (front node x) = packed X oldSite x)
+ (quiet : ∀ x z s es next, action x z s = some (es,next) → choiceBits es = [])
+
+include frontChoices quiet in
+theorem splits : Splits read := by
+ intro node s bs out tail h
+ obtain ⟨_,tape,es,ha,path⟩ := (read_some_iff X oldSite Y newSite A child parent front action node s bs out tail).mp h
+ rw [path,PrimedInputRAM.Flow.choiceBits_append,frontChoices,quiet _ _ _ _ _ ha,List.append_nil]
+ exact tape
+
+variable (M : Machine bits pcs regs 11) (m : Memory bits) (dfs : Fin 9 ↪ Fin regs)
+ (pre : Word bits → Config bits pcs regs → Prop) (done : Fin pcs)
+
+include frontChoices quiet in
+/-- A packet parser with a genuine successful native prefix and both native
+rejection cases realizes the DFS hook on all complete and truncated tapes. -/
+theorem realizes
+ (parentReady : ∀ node c, pre node c → ∃ z, RefreshHalfDecoder.parent Y newSite A parent (scratch endAddr c.privateMem) = some z)
+ (short : ∀ node c bs, pre node c → bs.length < RefreshHalfDecoder.width X oldSite → ¬ Returns M c m bs)
+ (reject : ∀ node c x z tail, pre node c →
+ RefreshHalfDecoder.parent Y newSite A parent (scratch endAddr c.privateMem) = some z →
+ action x z ((packet X oldSite child x).write A (scratch endAddr c.privateMem)) = none →
+ ¬ Returns M c m (packed X oldSite x ++ tail))
+ (success : ∀ node c x z es next, pre node c →
+ RefreshHalfDecoder.parent Y newSite A parent (scratch endAddr c.privateMem) = some z →
+ action x z ((packet X oldSite child x).write A (scratch endAddr c.privateMem)) = some (es,next) →
+ ∃ out, out.pc = done ∧ ShrinkRole.Frame dfs endAddr c out ∧ scratch endAddr out.privateMem = next ∧
+ ChildScan.Prefix M m c out (packed X oldSite x) (front node x ++ es)) :
+ Realizes read M m dfs pre (fun _ _ d => d.pc = done) := by
+ constructor
+ · intro node c bs out tail hc got
+ obtain ⟨hp,tape,es,actionEq,trace⟩ := (read_some_iff X oldSite Y newSite A child parent front action _ _ _ _ _).mp got
+ obtain ⟨endState,pc,frame,updated,path⟩ := success _ _ _ _ _ _ hc hp actionEq
+ have bitsEq : choiceBits out.trace = packed X oldSite out.value.1 := by
+ rw [trace,PrimedInputRAM.Flow.choiceBits_append,frontChoices,quiet _ _ _ _ _ actionEq,List.append_nil]
+ exact ⟨bitsEq ▸ tape,endState,pc,frame,updated,by rwa [bitsEq,trace]⟩
+ · intro node c bs hc refused
+ obtain ⟨z,hz⟩ := parentReady _ _ hc
+ cases parsed : (RefreshHalfDecoder.reader X oldSite).read bs with
+ | none => exact short _ _ _ hc ((RefreshHalfDecoder.none_iff X oldSite bs).mp parsed)
+ | some pair =>
+ obtain ⟨x,tail⟩ := pair
+ have bsEq := (RefreshHalfDecoder.read_iff X oldSite bs x tail).mp parsed
+ have ha : action x z ((packet X oldSite child x).write A (scratch endAddr c.privateMem)) = none := by
+ cases h : action x z ((packet X oldSite child x).write A (scratch endAddr c.privateMem)) with
+ | none => rfl
+ | some pair =>
+ obtain ⟨es,next⟩ := pair
+ simp [reader,hz,parsed,h] at refused
+ exact bsEq ▸ reject _ _ _ _ _ hc hz ha
+
+end PairSimulation.RefreshHook
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookRecover.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookRecover.lean
new file mode 100644
index 0000000000..c74994d471
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookRecover.lean
@@ -0,0 +1,44 @@
+import OAI.Computability.VPVNP.PairRefreshHookSite
+
+/-! # Recovering the native job of a specified pair of refresh halves -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords CompressorRecords.PortRefresh NewSlots NodeArguments NodeArguments.ChildScan DFS
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {bits n hist t : ℕ}
+ (R : Site B n hist bits) (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (pub : Fin 11 → BurstRAM.Word bits) (m : Memory bits)
+
+theorem recover_job (node : BurstRAM.Word bits) (s : Scratch bits n) (old : R.state.network.Half R.olderSite)
+ (new : R.nextState.network.Half R.newerSite)
+ (parent : RefreshHalfDecoder.parent R.nextState R.newerSite R.arena R.parent s = some new)
+ (job : VisitPath bits n) (tail : List Bool)
+ (hit : (R.hook ties stride order pub m).read node s (packed R.state R.olderSite old ++ tail) = some (job,tail)) :
+ ∃ es updated, R.action ties stride order pub m old new
+ ((packet R.state R.olderSite R.oldNode old).write R.arena s) = some (es,updated) ∧
+ job = ⟨node,R.front pub m node old ++ es,(·=s),fun _ => updated⟩ := by
+ obtain ⟨⟨out,rest⟩,hr,hj⟩ := Option.map_eq_some_iff.mp hit
+ have jobEq : (⟨node,out.trace,(·=s),fun _ => out.updated⟩ : VisitPath bits n) = job := congrArg Prod.fst hj
+ have tailEq : rest = tail := congrArg Prod.snd hj
+ subst tail
+ obtain ⟨parsed,tape,es,selected,trace⟩ := (RefreshHook.read_some_iff R.state R.olderSite R.nextState R.newerSite
+ R.arena R.oldNode R.parent (R.front pub m) (R.action ties stride order pub m) _ _ _ _ _).mp hr
+ have newer := Option.some.inj (parsed.symm.trans parent)
+ have h₁ := (RefreshHalfDecoder.read_iff R.state R.olderSite _ out.value.1 rest).mpr tape
+ have h₂ := (RefreshHalfDecoder.read_iff R.state R.olderSite (packed R.state R.olderSite old ++ rest) old rest).mpr rfl
+ have older := (Prod.mk.inj (Option.some.inj (h₁.symm.trans h₂))).1
+ rw [older,newer] at selected
+ rw [older] at trace
+ exact ⟨es,out.updated,selected,jobEq.symm.trans (congrArg (fun tr => (⟨node,tr,(·=s),fun _ => out.updated⟩ : VisitPath bits n)) trace)⟩
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookSelectedGuardLayout.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookSelectedGuardLayout.lean
new file mode 100644
index 0000000000..0364a88176
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookSelectedGuardLayout.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.PairRefreshHookFrozenSite
+import OAI.Computability.VPVNP.PairRefreshGuardLayout
+
+/-!
+# Guard addresses of a selected refresh job
+
+At each linked site, the old and new level pointers still locate the two
+packed graphs. The parent row and its tagged copy lie in the reserved
+traversal arena below the controller's terminal header.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.RefreshHook.SelectedPublished
+
+open BurstRAM Compression Compression.Refresh CompressorRecords PortRefresh NewSlots
+open LocalHistory TraversalRoles TraversalRows DescriptorSpace TerminalProgram
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary
+open TraversalControllerInputs
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {n l g hist : ℕ} (G : LiveProgram.PairStages.Group) (workspace : BurstRAM.Word G.w)
+ (positions blocks : ℕ)
+ (budget : blocks * S.laneBits ≤ l) (initial : State (S.degreeExponent 0) l)
+ (branch : (B.execute f hf blocks budget initial).Choices)
+ (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (record : List Bool) (port : (X.Base × BitWord g) × Fin (2 ^ S.portExponent))
+ (stage : Fin (executeLevels B f hf blocks budget initial branch).length)
+ (occurrence : (executeLevels B f hf blocks budget initial branch)[stage] =
+ RefreshPlacement.traversalLevel f hf X choice record)
+
+local notation "layout" => BlockProgram.layout B workspace.val positions blocks
+local notation "levels" => executeLevels B f hf blocks budget initial branch
+local notation "tags" => TraversalRoles.selected B f hf blocks budget initial branch
+local notation "cap" => BlockSchedule.Templates.recordLimit B
+local notation "first" => endAddress layout
+local notation "rowEnd" => first + tagWords cap tags
+local notation "ord" => Fin.val (sites X.baseIndex (bitWordFinEquiv g) port)
+local notation "child" => address cap (layerBase cap first tags stage.val) ord
+local notation "parent" => address cap (layerBase cap first tags (stage.val + 1)) ord
+local notation "width" =>
+ State.totalWidth (StateExecution.finalState (B.execute f hf blocks budget initial) branch)
+
+local notation "pub" => terminalOperands G
+local notation "H" => Fin.val (TerminalLink.header pub)
+local notation "size" => tagWords cap tags
+
+include occurrence in
+/-- The real selected calendar and the physical linked memory provide all source
+address ranges required by the refresh dispatcher. -/
+theorem guard_at_site {tab : Fin (layout).shape.tables} {baseBits laneBits ordinal : ℕ}
+ {calendar vertex current : Memory G.w} {wireBits : Fin width → Bool}
+ (entry : VertexEntry B f hf blocks budget initial branch layout tab baseBits laneBits
+ pub calendar vertex wireBits)
+ (history : SelectedPayloadHistory.Past B f hf layout
+ (CompiledResident.payload B f hf workspace positions blocks n) levels calendar)
+ (packed : VertexPacked G layout cap tags width)
+ (frame : LinkedVertexMemory G vertex ordinal current)
+ (fits : TraversalPlan.Room B X choice port (slotDegree S) n rowEnd child parent hist G.w)
+ (prev next : Fin (layout).levels) (prevIndex : prev.val = stage.val)
+ (nextIndex : next.val = stage.val + 1) :
+ let R := ofSelected B n hist G.w workspace.val positions blocks X choice port stage.val
+ tags width fits
+ Site.GuardLayout B R pub current workspace.val positions blocks prev next := by
+ let R := ofSelected B n hist G.w workspace.val positions blocks X choice port stage.val
+ tags width fits
+ change Site.GuardLayout B R pub current workspace.val positions blocks prev next
+ have live : (levels).length < (layout).levels :=
+ (executeLevels_length B f hf blocks budget initial branch).trans_lt (by
+ rw [BlockProgram.actual_level_count]
+ omega)
+ obtain ⟨kept, high⟩ := packed.traversal_frames frame
+ have heads (i : ℕ) (hi : i ≤ (levels).length) :=
+ entry.site_level_head live (by change 28 ≤ 54; decide) kept high i hi
+ have data := RefreshHookRetained.ofPast B f hf workspace positions blocks n X choice history
+ stage record occurrence
+ have arena : first + 2 * size + width ≤ H := packed.arena
+ have below : first ≤ H := by omega
+ have top : first ≤ parent := (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ have inside : parent < first + size := fits.parentBound
+ have minSize : 2 ≤ size := by
+ have pos : 0 < size := by omega
+ change 0 < (cap + 2) * (((tags).map TaggedLayer.layer).map Layer.count).sum at pos
+ have nonempty := (mul_pos_iff_of_pos_left (by omega : 0 < cap + 2)).mp pos
+ exact (by omega : 2 ≤ cap + 2).trans (Nat.le_mul_of_pos_right _ nonempty)
+ have tagsLength : (tags).length = (levels).length + 1 := by simp [TraversalRoles.selected]
+ refine ⟨data.size, below, packed.room, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩
+ · rw [prevIndex]
+ exact (heads stage.val stage.isLt.le).2
+ · rw [nextIndex]
+ exact (heads (stage.val + 1) stage.isLt).2
+ · rw [prevIndex]; rfl
+ · rw [prevIndex]; rfl
+ · rw [nextIndex]; rfl
+ · intro i _ hi
+ change i ≤ stage.val + 1 + ((tags).length - 1 - (stage.val + 1)) at hi
+ have inLevels : i ≤ (levels).length := by rw [tagsLength] at hi; omega
+ have nextFits := levelStart_mono layout (inLevels.trans_lt live)
+ have stride : 14 < levelWords layout := by
+ change 14 < 66 + _ + _
+ omega
+ have fieldBefore : levelStart layout i + 14 < endAddress layout := by
+ change levelStart layout (i + 1) ≤ endAddress layout at nextFits
+ have shift : levelStart layout (i + 1) = levelStart layout i + levelWords layout := by
+ simp only [levelStart, Nat.succ_mul, Nat.add_assoc]
+ rw [shift] at nextFits
+ omega
+ rw [Fin.val_add, (heads i inLevels).2]
+ have small : (14 : BurstRAM.Word G.w).val ≤ 14 := Nat.mod_le ..
+ exact (Nat.mod_le ..).trans_lt
+ ((Nat.add_le_add_left small _).trans_lt (fieldBefore.trans_le below))
+ · change parent + 1 < H
+ omega
+ · change parent + 2 < H
+ omega
+ · change (Fin.ofNat (2 ^ G.w) (size + width) + Fin.ofNat (2 ^ G.w) parent).val < H
+ rw [Fin.val_add, Fin.val_ofNat, Fin.val_ofNat]
+ exact (Nat.mod_le ..).trans_lt ((Nat.add_le_add (Nat.mod_le ..) (Nat.mod_le ..)).trans_lt
+ (by omega))
+
+end PairSimulation.RefreshHook.SelectedPublished
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookSelectedLocation.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookSelectedLocation.lean
new file mode 100644
index 0000000000..98977af933
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookSelectedLocation.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.CompressorRefreshTraversalChild
+import OAI.Computability.VPVNP.CompressorRecordRefreshArgumentSite
+import OAI.Computability.VPVNP.CompressorRefreshCopyGeometry
+import OAI.Computability.VPVNP.PairTraversalControllerInputs
+import OAI.Computability.VPVNP.PairTraversalRoleExecution
+
+/-!
+# Locating a selected refresh port in the physical DFS table
+
+The typed level directories have exactly the tagged layers of the chosen
+compressor branch. At an occurrence of a degree refresh the port ordinal
+therefore names a live output row. Its unique child has the same ordinal
+at the preceding layer base.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.RefreshHook.SelectedLocation
+
+open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh CompressorRecords
+open PortRefresh NewSlots LocalHistory TraversalRoles TraversalRows TraversalControllerInputs
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {g n w : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n) (initial : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T hT initial).Choices) (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) (encoded : List Bool)
+ (port : (X.Base × BitWord g) × Fin (2 ^ S.portExponent))
+
+local notation "levels" => executeLevels B f hf T hT initial z
+local notation "tags" => TraversalRoles.selected B f hf T hT initial z
+local notation "v" => RefreshPlacement.traversalLevel f hf X choice encoded
+local notation "site" => (sites (D := 2 ^ S.portExponent) X.baseIndex (bitWordFinEquiv g) port)
+local notation "leaf" => TaggedLayer.mk (leafLayer (siteOrder initial)) Role.cursor
+local notation "cap" => B.recordLimit
+
+theorem live_port : (site).val < (levelLayer B f hf v).count := by
+ rw [levelLayer_count]
+ change (site).val < Fintype.card (((v).pass.next (v).term).Base × BitWord g)
+ rw [Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv g), Fintype.card_fin]
+ have card := CopyGeometry.base_count X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2 choice
+ change Fintype.card ((v).pass.next (v).term).Base =
+ Fintype.card X.Base * 2 ^ S.portExponent at card
+ rw [card]
+ exact (site).isLt
+
+variable (stage : Fin (executeLevels B f hf T hT initial z).length)
+ (occurrence : (executeLevels B f hf T hT initial z)[stage] =
+ RefreshPlacement.traversalLevel f hf X choice encoded)
+ {pub : Fin 11 → BurstRAM.Word w} {mem : Memory w} {H first pitch offset base : ℕ}
+
+include occurrence in
+/-- The actual directory bank locates this selected output identifier in the same
+layer sequence and at the same absolute row address as the vertex controller. -/
+theorem locate (ds : (i : Fin (levels).length) → LevelDirectory levels[i] mem base)
+ (resident : Resident pub mem H first pitch offset cap base leaf (levelFibers levels ds))
+ (fits : base + tagWords cap tags < 2 ^ w) :
+ let fibers := levelFibers levels ds
+ let table := leaf :: fibers.map Prod.fst
+ ∃ j : Fin table.length, ∃ id : Fin table[j].layer.count,
+ Resident pub mem H first pitch offset cap base leaf fibers ∧
+ j.val = stage.val + 1 ∧ id.val = (site).val ∧
+ ((tags).length - 1) - (stage.val + 1) = fibers.length - (stage.val + 1) ∧
+ address cap (layerBase cap base tags (stage.val + 1)) (site).val =
+ address cap (layerBase cap base table j.val) id.val ∧
+ layerBase cap base table (fibers.length + 1) < 2 ^ w := by
+ let fibers := levelFibers levels ds
+ let table := leaf :: fibers.map Prod.fst
+ have tagEq : table = tags := by
+ change leaf :: (levelFibers levels ds).map Prod.fst = _
+ rw [levelFibers_tags]
+ rfl
+ have lengthEq : fibers.length = (levels).length := by simp [fibers, levelFibers]
+ have tagLength : (tags).length = fibers.length + 1 := by simp [← tagEq, table]
+ let j : Fin table.length := ⟨stage.val + 1, by
+ have hs := stage.isLt
+ simp only [table, List.length_cons, List.length_map, lengthEq]
+ omega⟩
+ have layerEq : table[j].layer = levelLayer B f hf v := by
+ change (table[stage.val + 1]'j.isLt).layer = _
+ simp only [table, List.getElem_cons_succ, List.getElem_map, fibers, levelFibers,
+ List.getElem_ofFn]
+ exact congrArg (levelLayer B f hf) occurrence
+ let id : Fin table[j].layer.count := ⟨(site).val, by
+ rw [layerEq]
+ exact live_port B f hf X choice encoded port⟩
+ refine ⟨j, id, resident, rfl, rfl, ?_, ?_, ?_⟩
+ · change (tags).length - 1 - (stage.val + 1) = fibers.length - (stage.val + 1)
+ rw [tagLength, Nat.add_sub_cancel]
+ · change address cap (layerBase cap base tags (stage.val + 1)) (site).val =
+ address cap (layerBase cap base table (stage.val + 1)) (site).val
+ rw [tagEq]
+ · change layerBase cap base table (fibers.length + 1) < 2 ^ w
+ rw [tagEq, ← tagLength]
+ simpa only [layerBase, List.take_length, tagWords] using fits
+
+include occurrence in
+theorem child_row (rows : AllRows w mem cap base base (selectedLayers B f hf T hT initial z)) :
+ let parent := address cap (layerBase cap base tags (stage.val + 1)) (site).val
+ let child := address cap (layerBase cap base tags stage.val) (site).val
+ DFS.Row mem parent (parent + 2) [(child : BurstRAM.Word w)] :=
+ RefreshPlacement.selected_row f hf X choice encoded T hT initial z rows stage occurrence
+ ⟨(site).val, live_port B f hf X choice encoded port⟩
+
+end PairSimulation.RefreshHook.SelectedLocation
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookSelectedPublished.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookSelectedPublished.lean
new file mode 100644
index 0000000000..6f66cde78d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookSelectedPublished.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.PairRefreshHookSelectedLocation
+import OAI.Computability.VPVNP.PairRefreshSelectedSite
+import OAI.Computability.VPVNP.CompressorRefreshPayloadHistory
+import OAI.Computability.VPVNP.CompressorSelectedChildDirectory
+
+/-!
+# Physical publication of the selected refresh hook
+
+The completed compressor supplies the chosen term, both packed incidence
+directories and the child decoder's fields. The selected DFS arena supplies
+the actual singleton row and the level locator. Their combination describes
+the native hook at the popped port.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.RefreshHook.SelectedPublished
+
+open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh CompressorRecords
+open PortRefresh NewSlots LocalHistory TraversalRoles TraversalRows TraversalControllerInputs
+open DescriptorSpace NodeArguments NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f) {g n w hist l : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ l) (initial : State (S.degreeExponent 0) l)
+ (z : (B.execute f hf T hT initial).Choices) (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) (encoded : List Bool)
+ (port : (X.Base × BitWord g) × Fin (2 ^ S.portExponent))
+ (stage : Fin (executeLevels B f hf T hT initial z).length)
+ (occurrence : (executeLevels B f hf T hT initial z)[stage] =
+ RefreshPlacement.traversalLevel f hf X choice encoded)
+ (workspace positions blocks : ℕ)
+
+local notation "layout" => BlockProgram.layout B workspace positions blocks
+local notation "levels" => executeLevels B f hf T hT initial z
+local notation "tags" => TraversalRoles.selected B f hf T hT initial z
+local notation "cap" => BlockSchedule.Templates.recordLimit B
+local notation "first" => endAddress layout
+local notation "rowEnd" => first + tagWords cap tags
+local notation "ord" => Fin.val (sites X.baseIndex (bitWordFinEquiv g) port)
+local notation "older" => layerBase cap first tags stage.val
+local notation "child" => address cap older ord
+local notation "parent" => address cap (layerBase cap first tags (stage.val + 1)) ord
+local notation "width" =>
+ State.totalWidth (StateExecution.finalState (B.execute f hf T hT initial) z)
+local notation "leaf" => TaggedLayer.mk (leafLayer (siteOrder initial)) Role.cursor
+local notation "shape" => RefreshBlockPlan.shape B
+local notation "ties" => RefreshBlockPlan.order B
+local notation "stride" => LevelRecipe.Shape.stride shape
+
+include occurrence in
+/-- Recover the selected row's complete hook data in the memory in which it will
+execute. All packed operands come from the producing refresh's physical records. -/
+theorem from_resident
+ (fits : TraversalPlan.Room B X choice port (slotDegree S) n rowEnd child parent hist w)
+ (size : X.positions ≤ positions) (live : stage.val + 1 < (layout).levels)
+ {pub : Fin 11 → BurstRAM.Word w} {mem : Memory w} {H offset : ℕ}
+ (ds : (i : Fin (levels).length) → LevelDirectory levels[i] mem first)
+ (resident : Resident pub mem H (levelStart layout 0) (levelWords layout) offset cap first leaf
+ (levelFibers levels ds))
+ (rows : AllRows w mem cap first first (selectedLayers B f hf T hT initial z))
+ (records : RefreshPayloadHistory.Data B layout stage.val n X choice mem)
+ (directory : SelectedChildDirectory.Stored B layout stage.val n X mem) :
+ let R := ofSelected B n hist w workspace positions blocks X choice port stage.val
+ tags width fits
+ R.Published ties stride pub mem := by
+ let R := ofSelected B n hist w workspace positions blocks X choice port stage.val tags width fits
+ change R.Published ties stride pub mem
+ let fibers := levelFibers levels ds
+ have len : fibers.length = (levels).length := by simp [fibers, levelFibers]
+ have tagEq : leaf :: fibers.map Prod.fst = tags := by
+ change leaf :: (levelFibers levels ds).map Prod.fst = _
+ rw [levelFibers_tags]
+ rfl
+ have start_eq (i : ℕ) : levelStart layout 0 + i * levelWords layout = levelStart layout i := by
+ simp only [levelStart, Nat.zero_mul, Nat.add_zero]
+ have heads (i : ℕ) : levelHead pub mem i = (levelStart layout i : BurstRAM.Word w) := by
+ rw [levelHead, terminal_read resident 16 (by decide), terminal_read resident 17 (by decide),
+ resident.firstHead, resident.levelPitch, ← Nat.cast_mul, ← Nat.cast_add, start_eq]
+ have headVal (i : ℕ) (hi : i ≤ fibers.length) :
+ (levelHead pub mem i).val = levelStart layout i := by
+ have room := resident.levelFits i hi
+ rw [start_eq] at room
+ rw [heads, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ have oldLive : stage.val ≤ fibers.length := stage.isLt.le.trans_eq len.symm
+ have newLive : stage.val + 1 ≤ fibers.length := stage.isLt.trans_eq len.symm
+ have oldBase := resident.currentBase stage.val oldLive
+ rw [start_eq, show leaf :: (levelFibers levels ds).map Prod.fst = tags from tagEq] at oldBase
+ let regs := TerminalLayout.privateRegions (slotDegree S) n rowEnd hist
+ have bound : rowEnd ≤ regs.histBase := by
+ change rowEnd ≤ n + rowEnd * (2 * slotDegree S * n + 1)
+ exact (Nat.le_mul_of_pos_right _ (Nat.succ_pos _)).trans (Nat.le_add_left ..)
+ have cache : regs.histBase ≤ regs.cacheBase := (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ have arenaFit : rowEnd < 2 ^ w := (bound.trans cache).trans_lt fits.capacity.room
+ have tagLive : stage.val < (tags).length := by
+ simpa only [TraversalRoles.selected, List.length_cons, List.length_map] using
+ stage.isLt.trans (Nat.lt_succ_self _)
+ obtain ⟨pos, before, role, histAfter, strideFit, lanesFit, wide, _⟩ := numeric B n hist w
+ workspace positions blocks X choice port stage.val tags width fits ⟨stage.val, by omega⟩
+ ⟨stage.val + 1, live⟩ size tagLive
+ (selected_positive B f hf T hT initial z _ (List.getElem_mem (l := tags) tagLive))
+ obtain ⟨j, id, loc, hj, hid, later, addr, endFit⟩ :=
+ SelectedLocation.locate B f hf T hT initial z X choice encoded port stage occurrence
+ ds resident arenaFit
+ have childRow := SelectedLocation.child_row B f hf T hT initial z X choice encoded port
+ stage occurrence rows
+ refine ⟨⟨H, levelStart layout 0, levelWords layout, offset, first, leaf, fibers, j, id,
+ loc, hj, hid, later, addr, endFit⟩, ?_, ?_, ?_, records.fits, records.stored,
+ records.old.actual, records.new.actual, pos, before, role, histAfter, strideFit, lanesFit, wide⟩
+ · change (ChildScan.directory S.portExponent older cap R.arena R.prev).Stored mem
+ (levelHead pub mem stage.val + 14)
+ rw [heads]
+ exact directory.bank older oldBase
+ · change DFS.Row mem parent (parent + 2) [word R.oldNode]
+ rw [show R.oldNode = child from oldNode_eq B n hist w workspace positions blocks X choice port
+ stage.val tags width fits]
+ exact childRow
+ · change TraversalHeaders.Geometry (Fintype.card X.Base) g (levelHead pub mem stage.val).val
+ (levelHead pub mem (stage.val + 1)).val (arrayBase layout stage.val) R.arena R.prev R.next mem
+ rw [headVal _ oldLive, headVal _ newLive]
+ exact records.geometry
+
+end PairSimulation.RefreshHook.SelectedPublished
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookSite.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookSite.lean
new file mode 100644
index 0000000000..3bc1305f74
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookSite.lean
@@ -0,0 +1,166 @@
+import OAI.Computability.VPVNP.PairRefreshHookReader
+import OAI.Computability.VPVNP.PairRefreshVertexRun
+import OAI.Computability.VPVNP.PairRefreshTraversalAction
+import OAI.Computability.VPVNP.PairShrinkOldHalfAddresses
+
+/-!
+# Frozen row data and the refresh role parser
+
+A selected row supplies its two graph states, site, stored term choice and
+physical workspace. The reader reconstructs the newer half from the popped
+packet in scratch. Its one nondeterministic input is the independently chosen
+older half.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords CompressorRecords.PortRefresh CompressorRecords.PortRefresh.NewSlots RefreshMapOperands NodeArguments NodeArguments.ChildScan
+open TraversalControllerInputs TraversalRoles TraversalRows VertexImage DFS
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {bits n hist t : ℕ}
+
+/-- Input state, selected refresh term, and physical row and workspace addresses used by the
+refresh hook. -/
+structure Site (n hist bits : ℕ) where
+ /-- Number of lane bits left after moving the port bits into the base. -/
+ lanes : ℕ
+ /-- Network state entering the selected refresh, with the port bits still in the lane. -/
+ state : State S.portExponent (S.portExponent+lanes)
+ /-- Dyadic refresh choice recorded for this input state. -/
+ choice : DyadicRefreshChoice state S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh
+ /-- Input base, residual lane, and promoted port identifying the output row. -/
+ port : (state.Base × BitWord lanes) × Fin (2^S.portExponent)
+ /-- Slot degree used to size the private argument arena. -/
+ degree : ℕ
+ /-- Address immediately following the traversal rows. -/
+ rowEnd : ℕ
+ /-- Starting address of the input layer, used to locate the child row. -/
+ older : ℕ
+ /-- Address of the promoted output row whose packet supplies the newer half. -/
+ parent : ℕ
+ /-- Address of the first entry in the parent row’s child list. -/
+ listHead : ℕ
+ /-- Chronological index of the input layer of this refresh. -/
+ level : ℕ
+ /-- Number of traversal layers following this refresh’s output layer. -/
+ later : ℕ
+ /-- Starting address of the stored refresh terms for this level. -/
+ start : ℕ
+ /-- Incidence directory for the input state. -/
+ prev : IncidenceDirectory bits
+ /-- Incidence directory for the state produced by the refresh. -/
+ next : IncidenceDirectory bits
+ /-- Private address of the geometry words used by the traversal. -/
+ geometry : BurstRAM.Word bits
+ /-- Offset stored in the traversal geometry for locating the role data. -/
+ roleOffset : BurstRAM.Word bits
+ room : TraversalPlan.Room B state choice port degree n rowEnd
+ (childNode state older B.recordLimit (oldSite state port)) parent hist bits
+
+namespace Site
+
+variable {B} (R : Site B n hist bits)
+ (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (pub : Fin 11 → BurstRAM.Word bits) (m : Memory bits)
+
+/-- State produced by applying the selected dyadic refresh to the input state. -/
+noncomputable abbrev nextState := dyadicRefreshNext R.state S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order S.degree_bounds.2 R.choice
+/-- Input site obtained by putting the promoted port back into the lane. -/
+noncomputable abbrev olderSite := oldSite R.state R.port
+/-- Output site with the promoted port in its base and the residual lane unchanged. -/
+noncomputable abbrev newerSite := promotedSites R.port
+/-- Child row address computed from the input layer start and the input site ordinal. -/
+noncomputable abbrev oldNode := childNode R.state R.older B.recordLimit R.olderSite
+/-- Private memory layout for the row arguments, histogram, and cache. -/
+def regions := TerminalLayout.privateRegions R.degree n R.rowEnd hist
+/-- Private argument arena holding the packed child and parent half-wire assignments. -/
+def arena := R.regions.arguments
+
+/-- Event prefix for locating the parent layer and reading the child’s half-wire assignment. -/
+noncomputable def front (node : BurstRAM.Word bits) (old : R.state.network.Half R.olderSite) :=
+ RefreshVertexAssembly.inputTrace S.portExponent R.state R.olderSite old R.prev m R.listHead pub node R.level R.later
+
+/-- Local refresh action on the two half-wire assignments, returning the event trace and
+updated scratch on success. -/
+noncomputable def action (old : R.state.network.Half R.olderSite) (new : R.nextState.network.Half R.newerSite)
+ (s : Scratch bits n) :=
+ TraversalPlan.canonicalAction B ties stride order R.state R.choice R.port R.degree n R.rowEnd R.oldNode R.parent
+ R.room old new m (levelHead pub m R.level).val (levelHead pub m (R.level+1)).val R.geometry s
+
+/-- Refresh reader that decodes the parent packet, consumes the old half from the tape, and
+runs the local action. -/
+noncomputable def read := RefreshHook.reader R.state R.olderSite R.nextState R.newerSite R.arena R.oldNode R.parent
+ (R.front pub m) (R.action ties stride order pub m)
+
+/-- DFS visit parser built from the refresh reader at this row. -/
+noncomputable def hook := ShrinkRole.hook (R.read ties stride order pub m)
+
+/-- The popped packet contains a typed parent argument and the three geometry
+words used by the native role. The node number ties it to this selected row. -/
+def Prepared (node : BurstRAM.Word bits) (s : Scratch bits n) : Prop :=
+ node.val = R.parent ∧ ResidentGeometry s R.geometry R.roleOffset (word R.regions.histBase) ∧
+ ∃ new : R.nextState.network.Half R.newerSite, (Packet.mk R.parent (packed R.nextState R.newerSite new)).Stored R.arena s
+
+/-- Published memory, scalar fits, and the selected row in the completed
+traversal layers. The register and memory semantics of the role are proved
+separately from these source data. -/
+structure Published : Prop where
+ location : ∃ (header first pitch offset base : ℕ) (initial : TaggedLayer) (ls : List (Fiber bits))
+ (j : Fin (initial :: ls.map Prod.fst).length) (id : Fin (initial :: ls.map Prod.fst)[j].layer.count),
+ Resident pub m header first pitch offset B.recordLimit base initial ls ∧ j.val = R.level+1 ∧
+ id.val = (NewSlots.sites R.state.baseIndex (bitWordFinEquiv R.lanes) R.port).val ∧
+ R.later = ls.length-(R.level+1) ∧ R.parent = address B.recordLimit
+ (layerBase B.recordLimit base (initial :: ls.map Prod.fst) j) id ∧
+ layerBase B.recordLimit base (initial :: ls.map Prod.fst) (ls.length+1) < 2^bits
+ fields : (directory S.portExponent R.older B.recordLimit R.arena R.prev).Stored m (levelHead pub m R.level+14)
+ children : Row m R.parent R.listHead [word R.oldNode]
+ headers : TraversalHeaders.Geometry (Fintype.card R.state.Base) R.lanes (levelHead pub m R.level).val
+ (levelHead pub m (R.level+1)).val R.start R.arena R.prev R.next m
+ fit : Fintype.card R.state.Base * 2^S.portExponent * 2^R.lanes * 2^S.portExponent ≤ 2^bits
+ terms : Build.Stored R.state S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh R.choice ties R.start stride fit m
+ oldCols : R.prev.ActualColumns R.state m
+ newCols : R.next.ActualColumns R.nextState m
+ positive : 0 < R.oldNode
+ before : R.oldNode < R.parent
+ roleAfter : R.regions.histBase ≤ (R.geometry+10).val
+ histAfter : R.regions.histBase ≤ (R.geometry+11).val
+ strideFit : B.recordLimit+2 < 2^bits
+ lanesFit : 2^R.lanes < 2^bits
+ wide : 2^S.portExponent < 2^bits
+
+theorem oldFit (old : R.state.network.Half R.olderSite) :
+ (Packet.mk R.oldNode (packed R.state R.olderSite old)).Fits R.arena bits n := by
+ have width := (packed_length_le R.state R.olderSite old).trans
+ (Nat.mul_le_mul (Nat.mul_le_mul_left 2 R.room.oldDegree) R.room.oldWidth)
+ have bound := TraversalGeometry.argument_end R.degree n R.rowEnd hist R.state R.olderSite old R.oldNode
+ R.room.childBound R.room.oldDegree R.room.oldWidth
+ have hh : R.regions.histBase ≤ R.regions.cacheBase := (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ exact ⟨Nat.le_add_right ..,width.trans (Nat.le_succ _),bound.trans (hh.trans R.room.capacity.room.le)⟩
+
+theorem newFit (new : R.nextState.network.Half R.newerSite) :
+ (Packet.mk R.parent (packed R.nextState R.newerSite new)).Fits R.arena bits n := by
+ have width := (packed_length_le R.nextState R.newerSite new).trans
+ (Nat.mul_le_mul (Nat.mul_le_mul_left 2 R.room.newDegree) R.room.newWidth)
+ have bound := TraversalGeometry.argument_end R.degree n R.rowEnd hist R.nextState R.newerSite new R.parent
+ R.room.parentBound R.room.newDegree R.room.newWidth
+ have hh : R.regions.histBase ≤ R.regions.cacheBase := (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ exact ⟨Nat.le_add_right ..,width.trans (Nat.le_succ _),bound.trans (hh.trans R.room.capacity.room.le)⟩
+
+theorem front_choices (node : BurstRAM.Word bits) (old : R.state.network.Half R.olderSite) :
+ choiceBits (R.front pub m node old) = packed R.state R.olderSite old :=
+ (RefreshVertexAssembly.inputTrace_cost S.portExponent R.state R.olderSite old R.prev m R.listHead pub node R.level R.later).2.2
+
+end Site
+end PairSimulation.RefreshHook
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookVertexPublished.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookVertexPublished.lean
new file mode 100644
index 0000000000..fe7c1b5e81
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookVertexPublished.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.PairRefreshHookSelectedPublished
+import OAI.Computability.VPVNP.CompressorRefreshHookRetained
+
+/-!
+# The selected refresh hook at entry into the physical vertex traversal
+
+Each selected occurrence recovers its actual compressor payload from the
+calendar history. The linked traversal and shared-bit stages have already
+constructed the directory words and DFS rows in the vertex-entry memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.RefreshHook.SelectedPublished
+
+open BurstRAM Compression Compression.Refresh CompressorRecords PortRefresh NewSlots
+open LocalHistory TraversalRoles TraversalRows DescriptorSpace TerminalProgram
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {n l w g hist : ℕ} (workspace : BurstRAM.Word w) (positions blocks : ℕ)
+ (budget : blocks * S.laneBits ≤ l) (initial : State (S.degreeExponent 0) l)
+ (branch : (B.execute f hf blocks budget initial).Choices)
+ (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (record : List Bool) (port : (X.Base × BitWord g) × Fin (2 ^ S.portExponent))
+ (stage : Fin (executeLevels B f hf blocks budget initial branch).length)
+ (occurrence : (executeLevels B f hf blocks budget initial branch)[stage] =
+ RefreshPlacement.traversalLevel f hf X choice record)
+
+local notation "layout" => BlockProgram.layout B workspace.val positions blocks
+local notation "levels" => executeLevels B f hf blocks budget initial branch
+local notation "tags" => TraversalRoles.selected B f hf blocks budget initial branch
+local notation "cap" => BlockSchedule.Templates.recordLimit B
+local notation "first" => endAddress layout
+local notation "rowEnd" => first + tagWords cap tags
+local notation "ord" => Fin.val (sites X.baseIndex (bitWordFinEquiv g) port)
+local notation "child" => address cap (layerBase cap first tags stage.val) ord
+local notation "parent" => address cap (layerBase cap first tags (stage.val + 1)) ord
+local notation "width" =>
+ State.totalWidth (StateExecution.finalState (B.execute f hf blocks budget initial) branch)
+
+include occurrence in
+/-- The four linked terminal stages and the actual selected calendar suffice for the
+whole publication invariant, with no individually assumed graph or directory cells. -/
+theorem of_vertex_entry {tab : Fin (layout).shape.tables} {baseBits laneBits : ℕ}
+ {pub : Fin 11 → BurstRAM.Word w} {calendar vertex : Memory w}
+ {wireBits : Fin width → Bool}
+ (entry : VertexEntry B f hf blocks budget initial branch layout tab baseBits laneBits
+ pub calendar vertex wireBits)
+ (history : SelectedPayloadHistory.Past B f hf layout
+ (CompiledResident.payload B f hf workspace positions blocks n) levels calendar)
+ (fits : TraversalPlan.Room B X choice port (slotDegree S) n rowEnd child parent hist w) :
+ let R := ofSelected B n hist w workspace.val positions blocks X choice port stage.val
+ tags width fits
+ R.Published (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride pub vertex := by
+ have data := RefreshHookRetained.atVertex B f hf workspace positions blocks n X choice budget
+ initial branch entry history stage record occurrence
+ obtain ⟨ds, resident⟩ := entry.directories
+ exact from_resident B f hf blocks budget initial branch X choice record port stage occurrence
+ workspace.val positions blocks fits data.size data.live ds resident entry.rows data.sources
+ data.child
+
+end PairSimulation.RefreshHook.SelectedPublished
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookWitness.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookWitness.lean
new file mode 100644
index 0000000000..3f91544d0d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookWitness.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairRefreshHookSite
+import OAI.Computability.VPVNP.PairRefreshTraversalWitness
+
+/-!
+# Accepted physical refresh tapes and scheduled kernel witnesses
+
+At a fixed prepared node the newer argument is determined by the resident
+packet. The old half occurs once on the private choice tape. Every accepted
+suffix corresponds to a placed old argument with a genuine dyadic kernel
+witness, including when a selected scalar vanishes in the coefficient field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords CompressorRecords.PortRefresh NewSlots NodeArguments NodeArguments.ChildScan
+open VertexImage DFS NetworkKernel
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {bits n hist t : ℕ}
+ (R : Site B n hist bits) (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (pub : Fin 11 → BurstRAM.Word bits) (m : Memory bits)
+
+local notation "X" => R.state
+local notation "Y" => R.nextState
+local notation "oldSite" => R.olderSite
+local notation "newSite" => R.newerSite
+
+/-- Recover the independently guessed half and the acceptance bit of the
+actual finite refresh map from the physical parser. -/
+theorem hook_choice_iff (node : BurstRAM.Word bits) (s : Scratch bits n) (bs tail : List Bool)
+ (new : (Y).network.Half newSite)
+ (hp : RefreshHalfDecoder.parent Y newSite R.arena R.parent s = some new) :
+ (∃ job, (R.hook ties stride order pub m).read node s bs = some (job,tail)) ↔
+ ∃ old : (X).network.Half oldSite, bs = packed X oldSite old ++ tail ∧
+ (TraversalPlan.emitted B order X R.choice R.port old new).isSome = true := by
+ constructor
+ · rintro ⟨job,h⟩
+ obtain ⟨⟨out,rest⟩,hr,hj⟩ := Option.map_eq_some_iff.mp h
+ obtain ⟨_,rfl⟩ := Prod.mk.inj hj
+ obtain ⟨parent,tape,es,action,_⟩ := (RefreshHook.read_some_iff X oldSite Y newSite R.arena R.oldNode R.parent
+ (R.front pub m) (R.action ties stride order pub m) node s bs out rest).mp hr
+ obtain rfl := Option.some.inj (hp.symm.trans parent)
+ refine ⟨out.value.1,tape,?_⟩
+ unfold Site.action TraversalPlan.canonicalAction at action
+ split at action
+ · assumption
+ · contradiction
+ · rintro ⟨old,tape,accepted⟩
+ have hh := (RefreshHalfDecoder.read_iff X oldSite bs old tail).mpr tape
+ simp [Site.hook,ShrinkRole.hook,Site.read,RefreshHook.reader,hp,hh,Site.action,TraversalPlan.canonicalAction,accepted]
+
+variable {K : Type*} [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f)
+local notation "place₀" => TraversalPlan.place X
+local notation "v" => R.port
+local notation "conn" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hsol" => And.right (Iff.mp (B.solution_iff f) hf)
+
+/-- The physical accepted old-half prefixes are precisely the assigned inputs
+of the selected dyadic kernel that have a monomial witness. -/
+theorem hook_witness_iff (node : BurstRAM.Word bits) (s : Scratch bits n) (bs tail : List Bool)
+ (new : (Y).network.Half newSite)
+ (hp : RefreshHalfDecoder.parent Y newSite R.arena R.parent s = some new) :
+ (∃ job, (R.hook ties stride order pub m).read node s bs = some (job,tail)) ↔
+ ∃ before : Placed place₀ (X).network.Half newSite,
+ bs = packed X oldSite (before oldSite (TraversalPlan.old_place X v)) ++ tail ∧
+ Nonempty (dyadicRefreshKernelWitness X S.graph (Nat.two_pow_pos _) conn B.refresh
+ S.port_order S.degree_bounds.2 (f ∘ Sum.inr) hsol R.choice newSite before new).Choice := by
+ rw [R.hook_choice_iff ties stride order pub m node s bs tail new hp]
+ constructor
+ · rintro ⟨old,tape,accept⟩
+ let before := TraversalPlan.placedHalf X v old
+ have same : before oldSite (TraversalPlan.old_place X v) = old := rfl
+ refine ⟨before,same ▸ tape,?_⟩
+ exact (TraversalPlan.emitted_iff_witness B order X R.choice v new before f hf).mp (same ▸ accept)
+ · rintro ⟨before,tape,witness⟩
+ exact ⟨_,tape,(TraversalPlan.emitted_iff_witness B order X R.choice v new before f hf).mpr witness⟩
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshHookWrites.lean b/lean/OAI/Computability/VPVNP/PairRefreshHookWrites.lean
new file mode 100644
index 0000000000..ba3f25491f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshHookWrites.lean
@@ -0,0 +1,49 @@
+import OAI.Computability.VPVNP.PairRefreshHookSite
+import OAI.Computability.VPVNP.PairRefreshTraversalQuiet
+import OAI.Computability.VPVNP.PairRefreshVertexInputWrites
+
+/-! # The accepted refresh hook leaves external RAM intact
+
+The row locator and older-half reader change only private state. The selected
+action updates private scratch and the label histogram. Their complete
+chronological trace therefore replays on the same external memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.Site
+
+open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh CompressorRecords CompressorRecords.PortRefresh
+open NodeArguments TraversalControllerInputs
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {bits n hist t : ℕ}
+ (R : Site B n hist bits) (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (pub : Fin 11 → BurstRAM.Word bits) (m : Memory bits)
+
+variable {node : BurstRAM.Word bits} {s : DFS.Scratch bits n} {bs tail : List Bool}
+ {out : ShrinkRole.Outcome bits n (R.state.network.Half R.olderSite × R.nextState.network.Half R.newerSite)}
+
+theorem read_noWrites (h : R.read ties stride order pub m node s bs = some (out,tail)) :
+ SourceTransport.Writes (fun _ => False) out.trace := by
+ obtain ⟨_,_,es,selected,trace⟩ := (RefreshHook.read_some_iff R.state R.olderSite R.nextState R.newerSite
+ R.arena R.oldNode R.parent (R.front pub m) (R.action ties stride order pub m) node s bs out tail).mp h
+ rw [trace]
+ intro a value ha
+ rcases List.mem_append.mp ha with setup | visit
+ · exact RefreshVertexAssembly.inputTrace_noWrites R.state R.olderSite out.value.1 R.prev m R.listHead
+ pub node R.level R.later a value setup
+ · exact TraversalPlan.canonicalAction_noWrites B ties stride order R.state R.choice R.port R.degree n R.rowEnd
+ R.oldNode R.parent R.room out.value.1 out.value.2 m (levelHead pub m R.level).val
+ (levelHead pub m (R.level+1)).val R.geometry selected a value visit
+
+theorem read_after (h : R.read ties stride order pub m node s bs = some (out,tail)) :
+ after m out.trace = m :=
+ funext fun _ => SourceTransport.after_outside m (R.read_noWrites ties stride order pub m h) id
+
+end PairSimulation.RefreshHook.Site
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshOriginLevel.lean b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevel.lean
new file mode 100644
index 0000000000..3258b795c4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevel.lean
@@ -0,0 +1,227 @@
+import OAI.Computability.VPVNP.PairRefreshOriginLevelEffect
+import OAI.Computability.VPVNP.PairRefreshOriginLevelDispatch
+import OAI.Computability.VPVNP.PairRefreshOriginLevelMemory
+
+/-! # Level checks for the installed refresh worker
+
+The completed selected directory determines the row, its tag, and both
+levels of incidence data. A positive read realizes the chosen local factor
+and prepares its single old packet. An arbitrary successful read recovers
+that same kind of occurrence and preserves all pending siblings.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace PortRefresh
+open PortRefresh.NewSlots
+open TraversalRows TraversalRoles LocalHistory NetworkKernel NodeArguments TreeDecode
+open VertexImage DFS
+open LiveProgram Filter
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+attribute [local irreducible] executeLevels originReader selectedDesc siteOrder packed children
+ layerBase choiceEquiv placedEquiv halfEquiv
+
+section IndexedRow
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f) {hist : ℕ} (order : B.Entry ≃
+ Fin hist)
+ {lanes : ℕ} (blocks : ℕ) (budget : blocks * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (branch : (B.execute f hf blocks budget X).Choices)
+ (n w start positions width : ℕ)
+local notation "passes" => executeLevels B f hf blocks budget X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "first" => endAddress (BlockProgram.layout B start positions blocks)
+local notation "tags₀" => selected B f hf blocks budget X branch
+local notation "rows" => tagWords B.recordLimit (tags₀)
+local notation "offset" => (word (rows + width) : Word w)
+local notation "region" => TerminalLayout.privateRegions (slotDegree S) n (first + rows) hist
+local notation "pos" => layerBase B.recordLimit first (tags₀)
+local notation "format₀" => SelectedPacketFormat B f hf blocks budget X branch first
+local notation "desc₀" => selectedDesc B f hf blocks budget X branch first
+local notation "counts" => privateHistogram order.symm (region).histBase
+variable (room : Rooms n hist w start positions blocks ⟨leafLayer (siteOrder X), .cursor⟩
+ (executeLevels B f hf blocks budget X branch))
+local notation "site" => rowSite n hist w start positions blocks width (leaf₀) passes room
+local notation "ties₀" => RefreshBlockPlan.order B
+local notation "stride₀" => LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)
+
+variable (constants : Constants) (p q : ℕ)
+variable {pcs regs : ℕ} (V : Placement (TerminalProgram.nativeSegments B constants p q order)
+ pcs regs) (M : Machine w pcs regs 11) (m : Memory w)
+ (memory : LevelMemory B f hf blocks budget X branch n w start positions width room M.publicData m)
+ (data : Fin 10 → Word w) (vals : LeafSourceLoad.Static 34 → Word w)
+ (nodeCap limit power scanCap : ℕ)
+ (handlers : NodeDispatch.Role → HookParser w n)
+variable (refresh : handlers .refresh = SelectedRows.parser n hist w start positions blocks width
+ ⟨leafLayer (siteOrder X), .cursor⟩ (executeLevels B f hf blocks budget X branch) room order
+ M.publicData m)
+local notation "valid" => Budgeted (region).arguments (format₀) (VertexFrameData region data
+ offset vals)
+ (desc₀) counts nodeCap limit
+local notation "hook" => dispatcher handlers m offset
+local notation "guard" => JobGuard V M m (TerminalLink.workerCell (TerminalLink.header
+ M.publicData))
+ (ordinalJobCost n power scanCap)
+
+set_option maxHeartbeats 2000000 in
+-- Resolve the row address in both the selected parser and the installed worker.
+include memory refresh in
+private theorem assemble
+ (capFit : n ≤ nodeCap) (limitFit : limit < 2 ^ w)
+ (protect : ∀ (x : Row passes) s bs tail body, (site x).Prepared (word (site x).parent) s →
+ ((site x).hook (ties₀) (stride₀) order M.publicData m).read (word (site x).parent) s bs
+ = some (body, tail) →
+ guard (dispatchJob m offset (word (site x).parent) s body))
+ (i : Fin (passes).length) (tag : tagLevel B f hf passes[i] = .refresh) :
+ LevelChecks B f hf hook valid counts guard B.recordLimit ((pos) i.val) passes[i] := by
+ let v := passes[i]
+ let r := originReader B f hf v.origin v.term
+ let afterBase := TraversalRows.address B.recordLimit ((pos) i.val) (siteOrder v.input).length
+ let ptr := sitePointers B.recordLimit afterBase (ShrinkRoleDirectory.outputOrder v)
+ let src := fun u z => Packet.mk (sitePointers B.recordLimit ((pos) i.val) (siteOrder v.input) u).1
+ (packed v.input u z)
+ let dst := fun u z => Packet.mk (ptr u).1
+ (pullBits (v.pass.output_eq v.term) (packed (v.pass.next v.term)) u z)
+ let row := fun u => (⟨⟨i, u⟩, tag⟩ : Row passes)
+ have ptrEq u : (ptr u).1 = (site (row u)).parent :=
+ level_parent B f hf blocks budget X branch n hist w start positions width room (row u)
+ have tags u : NodeDispatch.role (m (offset + ((ptr u).1 : Word w)).val) = .refresh :=
+ (level_dispatch B f hf blocks budget X branch n hist w start positions width room (row u)
+ (rows + width) (TerminalLink.header M.publicData) m memory.tags memory.codes
+ memory.tagEnd memory.headerFit).1
+ have fit : (pos) ((passes).length + 1) ≤ 2 ^ w := by
+ rw [selected_endBase]
+ have he : rows = words B.recordLimit (selectedLayers B f hf blocks budget X branch) := by
+ rw [tagWords, selected_layers]
+ have h := memory.tagEnd.trans (TerminalLink.header M.publicData).isLt.le
+ omega
+ have hw : 0 < w := Nat.pos_of_ne_zero fun hz => (by decide : ¬2 < 2 ^ 0)
+ ((congrArg (fun j : ℕ => 2 < 2 ^ j) hz).mp memory.codes)
+ have readAt u z pending s (ready : valid (dst u z :: pending) s) bs :
+ (handlers .refresh).read ((ptr u).1 : Word w) s bs =
+ ((site (row u)).hook (ties₀) (stride₀) order M.publicData m).read (word (site (row
+ u)).parent) s bs := by
+ rw [refresh]
+ have pr := level_prepared B f hf blocks budget X branch n hist w start positions width
+ room (row u) z ready
+ exact (read_at n hist w start positions blocks width (leaf₀) passes room order
+ M.publicData m fit (row u)
+ _ s pr bs).trans (congrArg (fun b : ℕ => ((site (row u)).hook (ties₀) (stride₀) order
+ M.publicData m).read
+ (word b) s bs) (ptrEq u))
+ have tape u z pending s (ready : valid (dst u z :: pending) s) bs tail :
+ (∃ body, (handlers .refresh).read ((ptr u).1 : Word w) s bs = some (body, tail)) ↔
+ ∃ a c, bs = r.nodeBits u a z c ++ tail := by
+ rw [readAt u z pending s ready bs]
+ have packetEq := level_packet B f hf blocks budget X branch n hist w start positions width
+ room (row u) z
+ have stored := (congrArg (fun q : Packet => q.Stored (region).arguments s) packetEq).mp
+ ready.frontier.head.2.2.2
+ exact local_tape_iff n hist w start positions blocks width (leaf₀) passes room order
+ M.publicData m
+ (row u) z s bs tail hw stored
+ have effects u z a c pending s (ready : valid (dst u z :: pending) s) tail body
+ (hit : (handlers .refresh).read ((ptr u).1 : Word w) s (r.nodeBits u a z c ++ tail) =
+ some (body, tail)) :=
+ selected_effect B f hf blocks budget X branch n hist w start positions width room order
+ M.publicData m
+ (row u) data vals nodeCap limit z a c pending s ready hw (memory.published (row u)).positive
+ memory.cacheFit limitFit capFit tail body ((readAt u z pending s ready _).symm.trans hit)
+ have raw : NodeStep (handlers .refresh) valid r ptr src dst := by
+ constructor
+ · intro u z pending s bs body tail ready hit
+ obtain ⟨a, c, eqn⟩ := (tape u z pending s ready bs tail).mp ⟨body, hit⟩
+ subst bs
+ exact ⟨a, c, rfl, (effects u z a c pending s ready tail body hit).2.2⟩
+ · intro u z pending s a c tail ready
+ obtain ⟨body, hit⟩ := (tape u z pending s ready _ tail).mpr ⟨a, c, rfl⟩
+ exact ⟨body, hit, (effects u z a c pending s ready tail body hit).2.2⟩
+ refine ⟨dispatcher_nodeStep tags raw, ?_⟩
+ intro u z a c pending s ready
+ obtain ⟨body, hit, frame⟩ := raw.complete u z pending s a c [] ready
+ have eff := effects u z a c pending s ready [] body hit
+ have prep := level_prepared B f hf blocks budget X branch n hist w start positions width
+ room (row u) z ready
+ have prepared := (congrArg (fun j : ℕ => (site (row u)).Prepared (word j) s) (ptrEq u)).mp prep
+ have safe := protect (row u) s _ [] body prepared ((readAt u z pending s ready _).symm.trans hit)
+ exact ⟨_, dispatchJob_realizes eff.1, ⟨rfl, eff.2.1⟩,
+ (congrArg (fun j : ℕ => guard (dispatchJob m offset (word j) s body)) (ptrEq u)).mpr safe,
+ frame⟩
+
+end IndexedRow
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {hist : ℕ} (order : B.Entry ≃ Fin hist) (constants : Constants) (p q : ℕ)
+
+set_option maxHeartbeats 2000000 in
+-- Combine the native read bound with each indexed role check.
+/-- A uniform threshold for all fields, selected branches and physical
+refresh rows using these fixed map tables. -/
+theorem eventually_levelChecks :
+ ∀ᶠ n : ℕ in atTop, ∀ {K : Type} [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes : ℕ} (blocks : ℕ) (budget : blocks * S.laneBits ≤ lanes) (X : State
+ (S.degreeExponent 0) lanes)
+ (branch : (B.execute f hf blocks budget X).Choices) (w start positions width : ℕ),
+ let vs := executeLevels B f hf blocks budget X branch
+ let leafTag := TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+ let rowBase := endAddress (BlockProgram.layout B start positions blocks)
+ let tags := selected B f hf blocks budget X branch
+ let rowWords := tagWords B.recordLimit tags
+ let roleWord : Word w := word (rowWords + width)
+ let area := TerminalLayout.privateRegions (slotDegree S) n (rowBase + rowWords) hist
+ let packetFormat := SelectedPacketFormat B f hf blocks budget X branch rowBase
+ let treeDesc := selectedDesc B f hf blocks budget X branch rowBase
+ let histogram := privateHistogram order.symm area.histBase
+ ∀ (room : Rooms n hist w start positions blocks leafTag vs) {pcs regs : ℕ}
+ (V : Placement (TerminalProgram.nativeSegments B constants p q order) pcs regs)
+ (M : Machine w pcs regs 11) (m : Memory w),
+ Contains V M → LevelMemory B f hf blocks budget X branch n w start positions width
+ room M.publicData m →
+ ∀ (data : Fin 10 → Word w) (vals : LeafSourceLoad.Static 34 → Word w) (nodeCap limit
+ power scanCap : ℕ),
+ n ≤ nodeCap → limit < 2 ^ w → 1 ≤ power →
+ Site.scan B (RefreshBlockPlan.order B)
+ (LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)) order ≤ scanCap →
+ ∀ (handlers : NodeDispatch.Role → HookParser w n), handlers .refresh =
+ SelectedRows.parser n hist w start positions blocks width leafTag vs room order
+ M.publicData m →
+ let prepared := Budgeted area.arguments packetFormat (VertexFrameData area data
+ roleWord vals) treeDesc histogram nodeCap limit
+ let checkJob := JobGuard V M m (TerminalLink.workerCell (TerminalLink.header M.publicData))
+ (ordinalJobCost n power scanCap)
+ ∀ i : Fin vs.length, tagLevel B f hf vs[i] = .refresh →
+ LevelChecks B f hf (dispatcher handlers m roleWord) prepared histogram checkJob
+ B.recordLimit
+ (layerBase B.recordLimit rowBase tags i.val) vs[i] := by
+ filter_upwards [Site.eventually_dispatched_guard B order constants p q] with n bound
+ intro K _ f hf lanes blocks budget X branch w start positions width vs leafTag rowBase tags
+ rowWords roleWord area
+ packetFormat treeDesc histogram room pcs regs V M m link memory data vals nodeCap limit
+ power scanCap capFit limitFit hp hs
+ handlers refresh prepared checkJob i tag
+ apply assemble B f hf order blocks budget X branch n w start positions width room constants
+ p q V M m memory
+ data vals nodeCap limit power scanCap handlers refresh capFit limitFit _ i tag
+ intro x s bs tail body prep hit
+ let R := rowSite n hist w start positions blocks width leafTag vs room x
+ obtain ⟨prev, next, layout⟩ := memory.layout x
+ have dispatch := (level_dispatch B f hf blocks budget X branch n hist w start positions
+ width room x
+ (rowWords + width) (TerminalLink.header M.publicData) m memory.tags memory.codes
+ memory.tagEnd memory.headerFit).1
+ rw [level_parent B f hf blocks budget X branch n hist w start positions width room x] at dispatch
+ exact (bound R V M m start positions blocks prev next link (memory.published x) layout dispatch
+ (memory.later x) power scanCap hp hs s bs tail body prep hit).2
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelDispatch.lean b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelDispatch.lean
new file mode 100644
index 0000000000..33fa331843
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelDispatch.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairRefreshOriginLevelGeometry
+
+/-! # Preparing and dispatching a selected refresh head -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles LocalHistory NetworkKernel NodeArguments TreeDecode
+open VertexImage DFS
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes : ℕ} (blocks : ℕ) (budget : blocks * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (branch : (B.execute f hf blocks budget X).Choices)
+ (n hist w start positions width : ℕ)
+
+local notation "passes" => executeLevels B f hf blocks budget X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "first" => endAddress (BlockProgram.layout B start positions blocks)
+local notation "tags₀" => selected B f hf blocks budget X branch
+local notation "rows" => tagWords B.recordLimit (tags₀)
+local notation "pos" => layerBase B.recordLimit first (tags₀)
+local notation "format₀" => SelectedPacketFormat B f hf blocks budget X branch first
+local notation "desc₀" => selectedDesc B f hf blocks budget X branch first
+variable (room : Rooms n hist w start positions blocks ⟨leafLayer (siteOrder X), .cursor⟩
+ (executeLevels B f hf blocks budget X branch))
+ (x : Row (executeLevels B f hf blocks budget X branch))
+local notation "i₀" => x.val.1
+local notation "u₀" => x.val.2
+local notation "v₀" => (passes)[i₀]
+local notation "R₀" => rowSite n hist w start positions blocks width (leaf₀) passes room x
+local notation "nextBase" => TraversalRows.address B.recordLimit
+ ((pos) (i₀).val) (siteOrder (v₀).input).length
+local notation "ptr" => sitePointers B.recordLimit nextBase (ShrinkRoleDirectory.outputOrder (v₀))
+local notation "head₀" => (fun z => Packet.mk ((ptr) u₀).1
+ (pullBits ((v₀).pass.output_eq (v₀).term) (packed ((v₀).pass.next (v₀).term)) u₀ z))
+
+private theorem preparedHead {bits len labels : ℕ} (R : RefreshHook.Site B len labels bits)
+ {q : Packet} {new : R.nextState.network.Half R.newerSite} {node : Word bits}
+ {fmt : Packet → Prop} {desc : ℕ → List ℕ} {counts : Scratch bits len → B.Entry → ℕ}
+ {cap limit : ℕ} {pending : List Packet} {s : Scratch bits len}
+ {data : Fin 10 → Word bits} {vals : LeafSourceLoad.Static 34 → Word bits}
+ (addr : node.val = R.parent)
+ (frame : R.geometry = (NativeFrame.frameBase R.regions : Word bits))
+ (eqn : q = ⟨R.parent, packed R.nextState R.newerSite new⟩)
+ (ready : Budgeted R.arena fmt (VertexFrameData R.regions data R.roleOffset vals)
+ desc counts cap limit (q :: pending) s) : R.Prepared node s := by
+ have stored := ready.frontier.head.2.2.2
+ rw [eqn] at stored
+ have resident := ready.frontier.frame.resident
+ rw [← frame] at resident
+ exact ⟨addr, resident, new, stored⟩
+
+set_option maxHeartbeats 1500000 in
+-- The selected term carries dependent input and output networks.
+/-- A genuine budgeted head gives the resident geometry and stored newer
+half used by the local parser at its physical entry. -/
+theorem level_prepared {data : Fin 10 → Word w} {vals : LeafSourceLoad.Static 34 → Word w}
+ {counts : Scratch w n → B.Entry → ℕ} {nodeCap limit : ℕ}
+ {pending : List Packet} {s : Scratch w n}
+ (z : ((v₀).pass.step.term (v₀).term).output.Half u₀)
+ (ready : Budgeted (R₀).arena (format₀) (VertexFrameData (R₀).regions data (R₀).roleOffset vals)
+ (desc₀) counts nodeCap limit ((head₀) z :: pending) s) :
+ (R₀).Prepared (((ptr) u₀).1 : Word w) s := by
+ have addr := level_parent B f hf blocks budget X branch n hist w start positions width room x
+ have fit := level_parent_val B f hf blocks budget X branch n hist w start positions width room x
+ have node := (congrArg (fun j : ℕ => (j : Word w).val) addr).trans fit
+ have packetEq :=
+ level_packet B f hf blocks budget X branch n hist w start positions width room x z
+ exact preparedHead B (R₀) node rfl packetEq ready
+
+set_option maxHeartbeats 1500000 in
+-- The site address and its packed representation use the selected execution.
+include room width in
+/-- The physical dispatch probe reads the published refresh role and avoids
+both terminal-controller cells. The exclusive tag end can equal the header. -/
+theorem level_dispatch (offset : ℕ) (terminal : Word w) (m : Memory w)
+ (published : TraversalRoles.Reads w m offset B.recordLimit first (tags₀))
+ (codes : 2 < 2 ^ w) (below : offset + first + rows ≤ terminal.val)
+ (headerFit : terminal.val + 31 < 2 ^ w) :
+ let cell := ((offset : Word w) + (((ptr) u₀).1 : Word w)).val
+ NodeDispatch.role (m cell) = .refresh ∧ TerminalLink.workerCell terminal cell := by
+ intro cell
+ have ptrEq := level_parent B f hf blocks budget X branch n hist w start positions width room x
+ have parentEq := parent_eq n hist w start positions blocks width (leaf₀) passes room x
+ have fits := level_parent_val B f hf blocks budget X branch n hist w start positions width room x
+ have atRow : (((ptr) u₀).1 : Word w).val = ShrinkRoleDirectory.address B.recordLimit first
+ (leaf₀) passes x.val :=
+ (congrArg (fun j : ℕ => (j : Word w).val) ptrEq).trans (fits.trans parentEq)
+ have hit := ShrinkRoleDirectory.dispatch_at_site B.recordLimit first (leaf₀) passes
+ published codes (below.trans terminal.isLt.le) _ x.val atRow
+ refine ⟨hit.trans (congrArg Role.dispatch x.property),TerminalLink.workerCell_of_lt headerFit ?_⟩
+ have parentBound : (R₀).parent < first + rows := (R₀).room.parentBound
+ have addressBound : offset + (R₀).parent < terminal.val := by omega
+ change ((offset : Word w) + (((ptr) u₀).1 : Word w)).val < _
+ rw [ptrEq, ← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt (addressBound.trans terminal.isLt)]
+ exact addressBound
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelEffect.lean b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelEffect.lean
new file mode 100644
index 0000000000..20ed8ce35d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelEffect.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairRefreshOriginLevelRead
+import OAI.Computability.VPVNP.PairRefreshOriginLevelGeometry
+import OAI.Computability.VPVNP.PairRefreshHookEmission
+
+/-! # Histogram and frontier effects of the selected refresh occurrence -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace PortRefresh
+open PortRefresh.NewSlots
+open TraversalRows TraversalRoles LocalHistory NetworkKernel NodeArguments TreeDecode
+open VertexImage DFS
+open scoped Fin.CommRing
+
+set_option quotPrecheck false
+
+attribute [local irreducible] executeLevels originReader selectedDesc siteOrder packed children
+ layerBase choiceEquiv placedEquiv halfEquiv
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes : ℕ} (blocks : ℕ) (budget : blocks * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (branch : (B.execute f hf blocks budget X).Choices)
+ (n hist w start positions width : ℕ)
+
+local notation "passes" => executeLevels B f hf blocks budget X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "first" => endAddress (BlockProgram.layout B start positions blocks)
+local notation "tags₀" => selected B f hf blocks budget X branch
+local notation "pos" => layerBase B.recordLimit first (tags₀)
+local notation "format₀" => SelectedPacketFormat B f hf blocks budget X branch first
+local notation "desc₀" => selectedDesc B f hf blocks budget X branch first
+variable (room : Rooms n hist w start positions blocks ⟨leafLayer (siteOrder X), .cursor⟩
+ (executeLevels B f hf blocks budget X branch))
+ (order : B.Entry ≃ Fin hist) (pub : Fin 11 → Word w) (m : Memory w) (x : Row
+ (executeLevels B f hf blocks budget X branch))
+local notation "u₀" => x.val.2
+local notation "v₀" => (passes).get x.val.1
+local notation "R₀" => rowSite n hist w start positions blocks width (leaf₀) passes room x
+local notation "r₀" => originReader B f hf (v₀).origin (v₀).term
+local notation "ties₀" => RefreshBlockPlan.order B
+local notation "stride₀" => LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)
+local notation "nextBase" => TraversalRows.address B.recordLimit ((pos) x.val.1.val)
+ (siteOrder (v₀).input).length
+local notation "ptr" => sitePointers B.recordLimit nextBase (ShrinkRoleDirectory.outputOrder (v₀))
+local notation "src" => (fun u z => Packet.mk (sitePointers B.recordLimit ((pos) x.val.1.val)
+ (siteOrder (v₀).input) u).1 (packed (v₀).input u z))
+local notation "head₀" => (fun z => Packet.mk ((ptr) u₀).1
+ (pullBits ((v₀).pass.output_eq (v₀).term) (packed ((v₀).pass.next (v₀).term)) u₀ z))
+local notation "newHalf" => halfEquiv (v₀) u₀ x.property
+local notation "counts" => privateHistogram order.symm (R₀).regions.histBase
+variable (data : Fin 10 → Word w) (vals : LeafSourceLoad.Static 34 → Word w) (nodeCap limit : ℕ)
+local notation "valid" => Budgeted (R₀).arena (format₀) (VertexFrameData (R₀).regions data
+ (R₀).roleOffset vals)
+ (desc₀) (counts) nodeCap limit
+
+set_option maxHeartbeats 2000000 in
+-- Transport the dependent occurrence and its ordered packet through the port equivalence.
+/-- The exact selected term supplies the code and every exponent increment
+of this body. Its update prepares the ordered old packets for DFS. -/
+theorem selected_effect (z : ((v₀).pass.step.term (v₀).term).output.Half u₀)
+ (a : Placed ((v₀).pass.step.term (v₀).term).place (v₀).input.network.Half u₀)
+ (c : ((r₀).witness u₀ a z).Choice) (pending : List Packet) (s : Scratch w n)
+ (ready : valid ((head₀) z :: pending) s) (hw : 0 < w)
+ (positive : 0 < (R₀).oldNode) (cacheFit : (R₀).regions.cacheBase + 38 ≤ 2 ^ w)
+ (limitFit : limit < 2 ^ w) (capFit : n ≤ nodeCap) (tail : List Bool) (body : VisitPath w n)
+ (read : ((R₀).hook (ties₀) (stride₀) order pub m).read (word (R₀).parent) s
+ ((r₀).nodeBits u₀ a z c ++ tail) = some (body, tail)) :
+ RealizesJob (counts) ⟨((ptr) u₀).1, (r₀).nodeBits u₀ a z c, ((r₀).witness u₀ a
+ z).exponents c⟩ body ∧
+ body.enabled s ∧ valid (children (r₀) (src) u₀ a ++ pending) (body.update s) := by
+ let R := R₀
+ let pe := placedEquiv (v₀) u₀ x.property
+ let new := (newHalf) z
+ let occ := choiceEquiv (v₀) u₀ x.property z ⟨a, c⟩
+ let child := fun old : Placed (TraversalPlan.place R.state) R.state.network.Half R.newerSite =>
+ RefreshHook.packet R.state R.olderSite R.oldNode
+ (old R.olderSite (TraversalPlan.old_place R.state R.port))
+ have onlyChild old : children (r₀) (src) u₀ old = [child (pe old)] :=
+ children_eq (v₀) u₀ x.property old ((pos) x.val.1.val)
+ have single old : children (r₀) (src) u₀ (pe.symm old) = [child old] :=
+ (onlyChild (pe.symm old)).trans (congrArg (fun b => [child b]) (pe.apply_symm_apply old))
+ have shape old : (desc₀) R.parent = subtreeAddresses (desc₀) (child old) := by
+ have h := level_children_shape B f hf blocks budget X branch n hist w start positions
+ width room x (pe.symm old)
+ exact h.trans ((congrArg (List.flatMap (subtreeAddresses desc₀)) (single old)).trans
+ (List.append_nil _))
+ have typed old : (format₀) (child old) :=
+ level_children_format B f hf blocks budget X branch start positions x (pe.symm old)
+ ((congrArg (fun ls => child old ∈ ls) (single old)).mpr List.mem_cons_self)
+ have eqn := choice_fields (v₀) u₀ x.property z a c
+ have hp := level_parent B f hf blocks budget X branch n hist w start positions width room x
+ have packetEq := level_packet B f hf blocks budget X branch n hist w start positions width
+ room x z
+ have prepared := (congrArg (fun q : Packet => valid (q :: pending) s) packetEq).mp ready
+ have nativeRead := (congrArg (fun bs => (R.hook (ties₀) (stride₀) order pub m).read (word
+ R.parent) s
+ (bs ++ tail) = some (body, tail)) eqn.2.1).mp read
+ have eff := R.origin_effect (ties₀) (stride₀) order pub m f hf new data R.roleOffset vals
+ (format₀) (desc₀) nodeCap limit pending s prepared hw shape typed
+ (level_node_lt B f hf blocks budget X branch n hist w start positions width room x)
+ positive cacheFit limitFit capFit occ.1 occ.2 tail body nativeRead
+ have after := (onlyChild a).trans (congrArg (fun b => [child b]) eqn.1.symm)
+ refine ⟨⟨eff.1.address.trans (congrArg (fun j : ℕ => (j : Word w)) hp.symm),
+ eff.1.bits.trans eqn.2.1.symm, ?_⟩, eff.2.1, ?_⟩
+ · intro q h label
+ exact (eff.1.counts q h label).trans (congrArg (counts q label + ·) (congrFun eqn.2.2.symm
+ label))
+ · exact (congrArg (fun children => valid (children ++ pending) (body.update s)) after).mpr eff.2.2
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelGeometry.lean b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelGeometry.lean
new file mode 100644
index 0000000000..4c6454996c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelGeometry.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedPackets
+import OAI.Computability.VPVNP.PairVertexSelectedDesc
+import OAI.Computability.VPVNP.PairVertexFrameData
+
+/-!
+# Physical packet geometry at a selected refresh level
+
+The pointer following the old rows is the parent used by the native refresh
+reader. Its output packet carries the same independent half-wire assignment.
+The selected descendant list and packet format apply to every placed input.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles LocalHistory NetworkKernel NodeArguments TreeDecode
+open VertexImage DFS
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes : ℕ} (blocks : ℕ) (budget : blocks * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (branch : (B.execute f hf blocks budget X).Choices)
+ (n hist w start positions width : ℕ)
+
+local notation "passes" => executeLevels B f hf blocks budget X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "first" => endAddress (BlockProgram.layout B start positions blocks)
+local notation "tags₀" => selected B f hf blocks budget X branch
+local notation "rows" => tagWords B.recordLimit (tags₀)
+local notation "pos" => layerBase B.recordLimit first (tags₀)
+local notation "format₀" => SelectedPacketFormat B f hf blocks budget X branch first
+local notation "desc₀" => selectedDesc B f hf blocks budget X branch first
+variable (room : Rooms n hist w start positions blocks ⟨leafLayer (siteOrder X), .cursor⟩
+ (executeLevels B f hf blocks budget X branch))
+ (x : Row (executeLevels B f hf blocks budget X branch))
+local notation "i₀" => x.val.1
+local notation "u₀" => x.val.2
+local notation "v₀" => (passes)[i₀]
+local notation "R₀" => rowSite n hist w start positions blocks width (leaf₀) passes room x
+local notation "reader₀" => originReader B f hf (v₀).origin (v₀).term
+local notation "nextBase" => TraversalRows.address B.recordLimit
+ ((pos) (i₀).val) (siteOrder (v₀).input).length
+local notation "ptr" => sitePointers B.recordLimit nextBase (ShrinkRoleDirectory.outputOrder (v₀))
+local notation "src" => (fun u z => Packet.mk (sitePointers B.recordLimit ((pos) (i₀).val)
+ (siteOrder (v₀).input) u).1 (packed (v₀).input u z))
+local notation "head₀" => (fun z => Packet.mk ((ptr) u₀).1
+ (pullBits ((v₀).pass.output_eq (v₀).term) (packed ((v₀).pass.next (v₀).term)) u₀ z))
+local notation "newHalf" => halfEquiv (v₀) u₀ x.property
+
+/-- The target pointer calculated by the selected level checker. -/
+theorem level_parent : ((ptr) u₀).1 = (R₀).parent := by
+ have after := selected_level_bases B f hf blocks budget X branch first i₀
+ have ptrEq := congrArg (fun b => (sitePointers B.recordLimit b
+ (ShrinkRoleDirectory.outputOrder (v₀)) u₀).1) after.symm
+ exact ptrEq.trans (parent_eq n hist w start positions blocks width (leaf₀) passes room x).symm
+
+set_option maxHeartbeats 1500000 in
+-- The selected term carries dependent input and output networks.
+/-- The packet consumed at the selected row has the exact address and packed
+output-half order of the local refresh hook. -/
+theorem level_packet (z : ((v₀).pass.step.term (v₀).term).output.Half u₀) :
+ (head₀) z = ⟨(R₀).parent,packed (R₀).nextState (R₀).newerSite ((newHalf) z)⟩ := by
+ exact congrArg₂ Packet.mk
+ (level_parent B f hf blocks budget X branch n hist w start positions width room x)
+ (halfEquiv_packed (v₀) u₀ x.property z)
+
+set_option maxHeartbeats 1500000 in
+-- The selected term carries dependent input and output networks.
+/-- The descendant list is the concatenation of the ordered child subtrees,
+for any independent placed old halves in the selected term. -/
+theorem level_children_shape
+ (a : Placed ((v₀).pass.step.term (v₀).term).place (v₀).input.network.Half u₀) :
+ (desc₀) (R₀).parent =
+ (TreeDecode.children (reader₀) (src) u₀ a).flatMap (subtreeAddresses desc₀) := by
+ have atRow := parent_eq n hist w start positions blocks width (leaf₀) passes room x
+ have shape := selectedDesc_level B f hf blocks budget X branch first i₀ u₀
+ have addresses := children_addresses (reader₀) (src) (fun u =>
+ (sitePointers B.recordLimit ((pos) (i₀).val) (siteOrder (v₀).input) u).1)
+ (fun _ _ => rfl) (desc₀) u₀ a
+ exact (congrArg (desc₀) atRow).trans (shape.trans addresses.symm)
+
+set_option maxHeartbeats 1500000 in
+-- The selected term carries dependent input and output networks.
+/-- Each placed child has the packet format of its actual selected input row. -/
+theorem level_children_format
+ (a : Placed ((v₀).pass.step.term (v₀).term).place (v₀).input.network.Half u₀)
+ {q : Packet} (mem : q ∈ TreeDecode.children (reader₀) (src) u₀ a) : (format₀) q := by
+ obtain ⟨j,rfl⟩ := List.mem_ofFn.mp mem
+ exact (selected_format B f hf blocks budget X branch first).1 i₀ _ ⟨_,_,rfl⟩
+
+/-- All selected packets, including unrelated pending siblings, lie in the
+same physical row interval as the selected hook. -/
+theorem level_node_lt (q : Packet) (format : (format₀) q) : q.node < (R₀).rowEnd := by
+ change q.node < first + rows
+ rw [tagWords,selected_layers]
+ exact selected_packet_node B f hf blocks budget X branch first format
+
+/-- Converting the physical parent address to a machine word loses no bits.
+The selected refresh room places the entire argument arena below the cache. -/
+theorem level_parent_val : ((R₀).parent : Word w).val = (R₀).parent := by
+ have bound := (R₀).room.parentBound
+ have rowBefore : (R₀).rowEnd ≤ (R₀).regions.histBase :=
+ (Nat.le_mul_of_pos_right _ (Nat.succ_pos _)).trans (Nat.le_add_left ..)
+ have histBefore : (R₀).regions.histBase ≤ (R₀).regions.cacheBase :=
+ (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ have endFit := (rowBefore.trans histBefore).trans_lt (R₀).room.capacity.room
+ exact Nat.mod_eq_of_lt (bound.trans endFit)
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelMemory.lean b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelMemory.lean
new file mode 100644
index 0000000000..95a28cd1dc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelMemory.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedParser
+import OAI.Computability.VPVNP.PairRefreshHookGuard
+
+/-! # Resident data for a selected refresh level -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace PortRefresh
+open PortRefresh.NewSlots TraversalRows TraversalRoles LocalHistory NetworkKernel NodeArguments
+open TreeDecode VertexImage DFS
+open LiveProgram Filter
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f) {hist : ℕ}
+ {lanes : ℕ} (blocks : ℕ) (budget : blocks * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (branch : (B.execute f hf blocks budget X).Choices)
+ (n w start positions width : ℕ)
+local notation "passes" => executeLevels B f hf blocks budget X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "first" => endAddress (BlockProgram.layout B start positions blocks)
+local notation "tags₀" => selected B f hf blocks budget X branch
+local notation "rows" => tagWords B.recordLimit (tags₀)
+local notation "region" => TerminalLayout.privateRegions (slotDegree S) n (first + rows) hist
+variable (room : Rooms n hist w start positions blocks ⟨leafLayer (siteOrder X), .cursor⟩
+ (executeLevels B f hf blocks budget X branch))
+local notation "site" => rowSite n hist w start positions blocks width (leaf₀) passes room
+local notation "ties₀" => RefreshBlockPlan.order B
+local notation "stride₀" => LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)
+
+/-- Memory and capacity facts at the start of the selected vertex.
+The physical head bounds include the saved traversal directory and role tags. -/
+structure LevelMemory (pub : Fin 11 → Word w) (m : Memory w) : Prop where
+ tags : TraversalRoles.Reads w m (rows + width) B.recordLimit first (tags₀)
+ tagEnd : (rows + width) + first + rows ≤ (TerminalLink.header pub).val
+ headerFit : (TerminalLink.header pub).val + 31 < 2 ^ w
+ codes : 2 < 2 ^ w
+ cacheFit : (region).cacheBase + 38 ≤ 2 ^ w
+ published : ∀ x, (site x).Published (ties₀) (stride₀) pub m
+ layout : ∀ x, ∃ prev next, Site.GuardLayout B (site x) pub m start positions blocks prev next
+ later : ∀ x, (site x).later ≤ (S.steps + 1) * (n.log2 + 1)
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelRead.lean b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelRead.lean
new file mode 100644
index 0000000000..15cc720d76
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelRead.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.PairRefreshOriginLevelView
+import OAI.Computability.VPVNP.PairRefreshHookOrigin
+
+/-! # Successful local tapes at a chronological refresh output
+
+Reindexing the genuine port's placed argument and local occurrence identifies
+the accepted suffixes with the term at the indexed output, including for
+arbitrary independent half values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM PrivateRAM Compression CompressorRecords PortRefresh LocalHistory NodeArguments
+open TraversalRows TraversalRoles ShrinkRoleDirectory NetworkKernel DFS TreeDecode
+open PortRefresh.NewSlots
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f}
+ (n hist w start positions blocks width : ℕ) (leaf : TaggedLayer)
+ (passes : List (SelectedLevel B f hf))
+ (room : Rooms n hist w start positions blocks leaf passes)
+ (order : B.Entry ≃ Fin hist) (pub : Fin 11 → Word w) (m : Memory w)
+ (x : Row passes)
+
+local notation "v₀" => passes.get x.val.1
+local notation "u₀" => Sigma.snd (Subtype.val x)
+local notation "r₀" => originReader B f hf (SelectedLevel.origin (v₀)) (SelectedLevel.term (v₀))
+local notation "R₀" => rowSite n hist w start positions blocks width leaf passes room x
+local notation "ties₀" => RefreshBlockPlan.order B
+local notation "stride₀" => LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)
+
+set_option maxHeartbeats 2000000 in
+-- Reindexing dependent witnesses unfolds the selected term and its native port.
+theorem local_tape_iff
+ (z : (passes[x.val.1].pass.step.term passes[x.val.1].term).output.Half x.val.2)
+ (s : Scratch w n) (bits tail : List Bool) (hw : 0 < w)
+ (stored : (Packet.mk (R₀).parent (packed (R₀).nextState (R₀).newerSite
+ (halfEquiv (v₀) (u₀) x.property z))).Stored (R₀).arena s) :
+ (∃ body, ((R₀).hook (ties₀) (stride₀) order pub m).read (word (R₀).parent) s bits =
+ some (body, tail)) ↔
+ ∃ a : Placed ((v₀).pass.step.term (v₀).term).place (v₀).input.network.Half (u₀),
+ ∃ c : ((r₀).witness (u₀) a z).Choice, bits = (r₀).nodeBits (u₀) a z c ++ tail := by
+ let native := choiceEquiv (v₀) (u₀) x.property z
+ let new := halfEquiv (v₀) (u₀) x.property z
+ have hp := RefreshHalfDecoder.parent_eq (R₀).nextState (R₀).newerSite (R₀).arena
+ (R₀).parent s new stored hw
+ rw [(R₀).origin_tape_iff (ties₀) (stride₀) order pub m f hf _ s bits tail new hp]
+ constructor
+ · rintro ⟨a, c, eqn⟩
+ let occ := native.symm ⟨a, c⟩
+ refine ⟨occ.1, occ.2, ?_⟩
+ have same := (choice_fields (v₀) (u₀) x.property z occ.1 occ.2).2.1
+ change (r₀).nodeBits (u₀) occ.1 z occ.2 =
+ (originReader B f hf (PassOrigin.refresh (R₀).state) (R₀).choice).nodeBits (R₀).newerSite
+ (native occ).1 new (native occ).2 at same
+ rw [show native occ = ⟨a, c⟩ from native.apply_symm_apply _] at same
+ exact eqn.trans (congrArg (· ++ tail) same.symm)
+ · rintro ⟨a, c, eqn⟩
+ let occ := native ⟨a, c⟩
+ exact ⟨occ.1, occ.2,
+ eqn.trans (congrArg (· ++ tail) (choice_fields (v₀) (u₀) x.property z a c).2.1)⟩
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelView.lean b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelView.lean
new file mode 100644
index 0000000000..aa2d5e29dd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshOriginLevelView.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedPackets
+import OAI.Computability.VPVNP.PairRefreshTraversalOriginBits
+
+/-! # Reindexing a selected refresh kernel at its physical port
+
+The selected level keeps the output site of its term. The native reader
+undoes the promotion of that site. Both views have the same placed half,
+the same local occurrence, and the same singleton child packet.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM Compression Compression.DegreeRefresh Compression.Refresh CompressorRecords
+open CompressorRecords.PortRefresh NodeArguments NodeArguments.ChildScan LocalHistory
+open TreeDecode NetworkKernel
+open TraversalRows TraversalRoles
+set_option quotPrecheck false
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f}
+ (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site)
+ (h : tagLevel B f hf v = .refresh)
+
+local notation "t₀" => StatePass.step v.pass |>.term v.term
+local notation "o₀" => occurrence v u h
+local notation "x₀" => Occurrence.state (o₀)
+local notation "port₀" => Occurrence.port (o₀)
+local notation "u₀" => promotedSites (port₀)
+local notation "r₀" => originReader B f hf v.origin v.term
+local notation "r₁" => originReader B f hf (PassOrigin.refresh (x₀)) (Occurrence.choice (o₀))
+local notation "source₀" => Placed (Term.place (t₀)) v.input.network.Half u
+local notation "source₁" =>
+ Placed (TraversalPlan.place (x₀)) (Network.Half (State.network (x₀))) (u₀)
+
+/-- Placed arguments of the selected term and of its native port. -/
+noncomputable def placedEquiv : source₀ ≃ source₁ := by
+ rcases v with ⟨a, g, a', g', X, p, origin, term, tape⟩
+ cases origin with
+ | shrink => cases h
+ | refresh X =>
+ rcases u with ⟨⟨base, port⟩, lane⟩
+ exact Equiv.refl _
+
+variable (z : (v.pass.step.term v.term).output.Half u)
+local notation "new₀" => halfEquiv v u h z
+
+/-- This equivalence includes the actual local occurrence, also at a zero
+coefficient in the specialization. -/
+noncomputable def choiceEquiv :
+ ((a : source₀) × ((r₀).witness u a z).Choice) ≃
+ ((a : source₁) × ((r₁).witness (u₀) a (new₀)).Choice) := by
+ rcases v with ⟨a, g, a', g', X, p, origin, term, tape⟩
+ cases origin with
+ | shrink => cases h
+ | refresh X =>
+ rcases u with ⟨⟨base, port⟩, lane⟩
+ exact Equiv.refl _
+
+variable (a : Placed (v.pass.step.term v.term).place v.input.network.Half u)
+ (c : ((originReader B f hf v.origin v.term).witness u a z).Choice)
+local notation "native₀" => choiceEquiv v u h z ⟨a, c⟩
+
+theorem choice_fields :
+ (native₀).1 = placedEquiv v u h a ∧
+ (r₀).nodeBits u a z c = (r₁).nodeBits (u₀) (native₀).1 (new₀) (native₀).2 ∧
+ ((r₀).witness u a z).exponents c =
+ ((r₁).witness (u₀) (native₀).1 (new₀)).exponents (native₀).2 := by
+ rcases v with ⟨a, g, a', g', X, p, origin, term, tape⟩
+ cases origin with
+ | shrink => cases h
+ | refresh X =>
+ rcases u with ⟨⟨base, port⟩, lane⟩
+ exact ⟨rfl, rfl, rfl⟩
+
+/-- The site's placed fiber contains the one old site at its true
+address in the previous physical layer. -/
+theorem children_eq (base : ℕ) :
+ children (r₀) (fun t y => ⟨(sitePointers B.recordLimit base (siteOrder v.input) t).1,
+ packed v.input t y⟩) u a =
+ [RefreshHook.packet (x₀) (RefreshMapOperands.oldSite (x₀) (port₀))
+ (childNode (x₀) base B.recordLimit (RefreshMapOperands.oldSite (x₀) (port₀)))
+ ((placedEquiv v u h a) _ (TraversalPlan.old_place (x₀) (port₀)))] := by
+ rcases v with ⟨a, g, a', g', X, p, origin, term, tape⟩
+ cases origin with
+ | shrink => cases h
+ | refresh X =>
+ rcases u with ⟨⟨b, port⟩, lane⟩
+ let v' := ((b, lane), port)
+ let r := originReader B f hf (PassOrigin.refresh X) term
+ let addr := fun t => (sitePointers B.recordLimit base (siteOrder X) t).1
+ exact (TermParsers.childPackets_state X r rfl (fun _ => rfl) (fun _ => rfl) addr
+ (promotedSites v') a).symm.trans (TraversalPlan.origin_childPackets B f hf X term v' a addr)
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshResidentDiagonal.lean b/lean/OAI/Computability/VPVNP/PairRefreshResidentDiagonal.lean
new file mode 100644
index 0000000000..642c9c8f7b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshResidentDiagonal.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.PairRefreshResidentImage
+
+/-!
+# Running both diagonal tests inside the installed refresh image
+
+The register recipes read the actual width and offset columns. The comparison
+loops read both resident node halves, testing the precise integer multiplier
+of the refresh kernel before any histogram update.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe OperandInputs PairSimulation NodeArguments MotifConversion NewSlots RefreshMapOperands NetworkKernel
+open scoped Fin.CommRing
+
+variable {bits g t hist shared pcs regs : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+ (T : Plan B t hist shared)
+ (pc : T.Address → Fin pcs) (dfs : Fin 9 ↪ Fin regs) (saved : VertexImage.Saved ↪ Fin regs)
+ (common : Fin shared ↪ Fin regs) (own : T.Local ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11) (installed : T.Installed pc dfs saved common own done M)
+
+local notation "D" => 2^S.portExponent
+local notation "H" => 2^S.expanderExponent
+local notation "P" => S.graph.toSlotGraph
+local notation "hD" => S.port_order
+local notation "hd" => And.right S.degree_bounds
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+
+variable (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ)
+ (oldDir newDir : IncidenceDirectory bits) (start : ℕ) (m : Memory bits)
+local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice
+local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t (Plan.stride T) start
+local notation "Q" => Allocation.Plan.scratch Pₗ bits
+local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ)
+local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ)
+local notation "N" => Fintype.card X.Base*D*2^g*D
+local notation "ws" => groupedWidths (bitWordFinEquiv _) (splitWidths X)
+local notation "perm" => oldPortMatching (splitSlots X) (bitWordFinEquiv _)
+local notation "inp" => T.inputs dfs saved common
+local notation "vout" => ws (v,Prod.snd v)
+local notation "vin" => ws (Equiv.symm perm (v,Prod.snd v))
+
+variable (old : X.network.Half (oldSite X v)) (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+local notation "diagonalValue" => portDiagonal perm ws (Prod.fst v) (Prod.snd v) (oldHalf X v old) (segments X v P hD hd internal new)
+
+private theorem tick_log (n : ℕ) :
+ choiceBits (List.replicate n (.tick : Event bits)) = [] ∧ countProbes (List.replicate n (.tick : Event bits)) = 0 := by
+ induction n with
+ | zero => exact ⟨rfl,rfl⟩
+ | succ n ih => simpa only [List.replicate_succ,choiceBits,countProbes] using ih
+
+include installed in
+/-- The diagonal loader and both comparisons form one linked prefix, including
+the rejecting branch and the frame on every other live operand. -/
+theorem diagonal_native {fit : N ≤ 2^bits} (c : Config bits pcs regs) (entry : c.pc = T.diagSetup pc 0)
+ (safe : ∀ i j, own i ≠ inp j)
+ (args : Describes T.input (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m
+ X v P hD hd internal A child parent oldDir newDir Q src term)
+ (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice T.ties start T.stride fit m)
+ (oldCols : oldDir.ActualColumns X m) (newCols : newDir.ActualColumns Y m)
+ (oldData : NodeFields A child X (oldSite X v) old c.privateMem)
+ (newData : NodeFields A parent Y (promotedSites v) new c.privateMem)
+ (wide : D < 2^bits) (wo : vout < 2^bits) (wi : vin < 2^bits) :
+ ∃ d es, ChildScan.Prefix M m c d [] es ∧
+ es.length = (RegisterSetup.lines T.diagonal).length + (7*(vout+vin)+9) ∧
+ countProbes es = ∑ i, (T.diagonal i).loads ∧ choiceBits es = [] ∧
+ d.pc = (if diagonalValue = (1 : ℤ) then T.routeSetup pc 0 else T.bad pc) ∧
+ (∀ j, (∀ i, j ≠ own i) → d.reg j = c.reg j) ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨es,mid,len,probes,path,pc',mem,per,ready,frame,run⟩ := DiagonalFrame.setup_trace X v P hD hd internal
+ A child parent oldDir newDir Q src term T.input m M c inp (T.diagVM own) (T.diagReg own) (T.diagSetup pc)
+ (T.diag_link pc dfs saved common own done M installed) (fun i j => safe _ j) (T.outputs own) entry args oldCols
+ newCols stored.segments wide
+ have next : mid.pc = T.comparePC pc 0 0 := pc'.trans (dite_eq_right (Nat.lt_irrefl _))
+ have old' : NodeFields A child X _ old mid.privateMem := mem ▸ oldData
+ have new' : NodeFields A parent Y _ new mid.privateMem := mem ▸ newData
+ obtain ⟨d,tail,final,mem',per',regs'⟩ := RefreshDiagonal.compare_arguments X v P hD hd internal
+ (T.compare_link pc dfs saved common own done M installed) A child parent old new mid next old' new' ready wo wi
+ let n := 7*(vout+vin)+9
+ have first : ChildScan.Prefix M m c mid [] es := run
+ change PrimedCounter.GuessWord.Prefix M mid (List.replicate n .tick) d at tail
+ have counts := tick_log (bits := bits) n
+ have second : ChildScan.Prefix M m mid d [] (List.replicate n .tick) := by
+ intro fuel more
+ simpa only [counts.1] using tail.execute fuel m more
+ refine Exists.intro d ?_
+ refine Exists.intro (es ++ List.replicate n (.tick : Event bits)) ?_
+ constructor
+ · exact first.trans second
+ refine And.intro ?_ (And.intro ?_ (And.intro ?_ (And.intro ?_ (And.intro ?_ (And.intro ?_ ?_)))))
+
+ · rw [List.length_append,len,List.length_replicate]
+ rfl
+ · rw [countProbes_append,probes,counts.2,Nat.add_zero]
+ rfl
+ · rw [PrimedInputRAM.Flow.choiceBits_append,path,counts.1,List.nil_append]
+ · exact final
+ · intro j hj
+ exact (regs' j (fun ⟨i,e⟩ => hj _ e.symm)).trans (frame j (fun i => hj _))
+ · exact mem'.trans mem
+ · exact per'.trans per
+
+end CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshResidentDispatch.lean b/lean/OAI/Computability/VPVNP/PairRefreshResidentDispatch.lean
new file mode 100644
index 0000000000..372eab4441
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshResidentDispatch.lean
@@ -0,0 +1,153 @@
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+import OAI.Computability.VPVNP.CompressorRefreshMapRoute
+import OAI.Computability.VPVNP.PairSimulationResidentDispatchImage
+import OAI.Computability.VPVNP.PairNodeChildLoop
+import Mathlib.Data.List.NodupEquivFin
+
+/-!
+# Native dispatch on the refresh term header and promoted port
+
+The ordinal comparison chains use the finite order of the stored demand grid.
+The port chain uses the promoted port's numerical order. Together the operand
+loader and the two chains reach the corresponding motif interpreter in the host
+RAM, with an exact instruction count and external probe count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentDispatch
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open NewSlots PhaseRecipe OperandInputs PairSimulation NodeArguments MotifConversion
+open scoped Fin.CommRing
+
+variable {bits g t pcs regs params : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+
+/-- Bijection between finite dispatch ordinals and the admissible refresh demand profiles in
+the route's grid-case order. -/
+noncomputable def gridOrder : Fin (MapRoute.gridCases B).length ≃ B.refresh.grid.demands :=
+ (finCongr (List.length_ofFn (f := _))).trans
+ ((List.Nodup.getEquiv _ B.refresh.grid.demands.nodup_toList).trans
+ (Equiv.subtypeEquivRight fun _ => Finset.mem_toList))
+
+theorem gridOrder_apply (i : Fin (MapRoute.gridCases B).length) :
+ gridOrder B i = (MapRoute.gridCases B)[i.val] := by
+ apply Subtype.ext
+ simp only [MapRoute.gridCases,List.getElem_ofFn]
+ rfl
+
+local notation "D" => 2^S.portExponent
+local notation "H" => 2^S.expanderExponent
+local notation "P" => S.graph.toSlotGraph
+local notation "hD" => S.port_order
+local notation "hd" => And.right S.degree_bounds
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+
+variable (I : Input) (stride : ℕ)
+local notation "f" => MapRoute.fields D stride I
+variable (vm : Fin (RegisterSetup.regCount (MapRoute.fields (2^S.portExponent) stride I)) ↪ Fin regs)
+ (place : ResidentDispatchImage.Address B.refresh.grid.demands (Fin (2^S.portExponent)) → Fin pcs)
+ (target : B.refresh.grid.demands → Fin (2^S.portExponent) → Fin pcs) (bad : Fin pcs)
+
+include place target vm in
+/-- Install the demand and party dispatch chains with their setup registers, successful handler
+targets, and rejection target. -/
+noncomputable def image : ResidentDispatchImage.Image B.refresh.grid.demands (Fin D)
+ (MapRoute.gridCases B).length D pcs regs where
+ grids := gridOrder B
+ parties := Equiv.refl _
+ place := place
+ target := target
+ bad := bad
+ grid := vm (RegisterSetup.output f 0)
+ party := vm (RegisterSetup.output f 1)
+ zero := vm (RegisterSetup.output f 2)
+ one := vm (RegisterSetup.output f 3)
+
+local notation "R" => image B I stride vm place target bad
+
+theorem distinct : (R).Distinct := by
+ constructor <;> intro eqn <;> have h := congrArg Fin.val (vm.injective eqn) <;> norm_num [RegisterSetup.output] at h
+
+variable (X : State S.portExponent (S.portExponent+g))
+ (p : (X.Base × BitWord g) × Fin (2^S.portExponent))
+local notation "dem" => blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X)
+local notation "selected" => demandGrid B.refresh (fun _ => zero_lt_one) (dem (Prod.fst p))
+
+/-- Native ticks used to select a grid ordinal and port along the two consecutive comparison
+chains. -/
+def chainTicks (grid port : ℕ) := 1 + ((2 * grid + 1) + (2 * port + 1))
+
+theorem keys_hit (M : Machine bits pcs regs params) (linked : (R).Linked M)
+ (c : Config bits pcs regs) (entry : c.pc = place (.inl ()))
+ (keys : MapRoute.Keys B X p (fun i => c.reg (vm (RegisterSetup.output f i))))
+ (wide : D < 2^bits) :
+ ∃ d, PrimedCounter.GuessWord.Prefix M c
+ (List.replicate (chainTicks ((gridOrder B).symm selected).val p.2.val) .tick) d ∧
+ d.pc = target selected p.2 ∧
+ (∀ q, (∀ i, q ≠ vm i) → d.reg q = c.reg q) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨j, key, fit, get⟩ := keys.grid
+ have select : gridOrder B j = selected := (gridOrder_apply B j).trans get
+ obtain ⟨d, path, pc, frame, mem, per⟩ := (R).native M linked (distinct B I stride vm place target bad)
+ j p.2 fit (p.2.isLt.trans wide) c entry key keys.party keys.one
+ refine ⟨d, ?_, ?_, fun q hq => frame q (hq _) (hq _) (hq _), mem, per⟩
+ · rwa [← select, Equiv.symm_apply_apply]
+ · exact pc.trans (congrArg (fun z => target z p.2) select)
+
+private theorem tick_counts (n : ℕ) :
+ choiceBits (List.replicate n (.tick : Event bits)) = [] ∧ countProbes (List.replicate n (.tick : Event bits)) = 0 := by
+ induction n with
+ | zero => exact ⟨rfl,rfl⟩
+ | succ n ih => simpa only [List.replicate_succ, choiceBits, countProbes] using ih
+
+variable (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (A : Arena) (child parent : ℕ) (oldDir newDir : IncidenceDirectory bits)
+ (ties : Fin t ≃ Tie (2^S.portExponent)) (start : ℕ) (m : Memory bits)
+local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice
+local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t stride start
+local notation "Q" => Allocation.Plan.scratch Pₗ bits
+local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ)
+local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ)
+local notation "N" => Fintype.card X.Base*D*2^g*D
+
+/-- The concrete field loader followed by both ordinal chains. The instruction
+bound depends on the finite template and the chosen ordinal, independently of
+the sizes of the bitstrings consumed by the motif. -/
+theorem load_and_dispatch {fit : N ≤ 2^bits} (M : Machine bits pcs regs params) (c : Config bits pcs regs)
+ (inputs : Fin 6 → Fin regs) (pc : ℕ → Fin pcs)
+ (link : RegisterSetup.Linked vm inputs M pc (RegisterSetup.lines f)) (safe : ∀ i j, vm i ≠ inputs j)
+ (entry : c.pc = pc 0) (next : pc (RegisterSetup.lines f).length = place (.inl ()))
+ (linked : (R).Linked M)
+ (args : Describes I (fun i => c.reg (inputs i.castSucc)) (c.reg (inputs (Fin.last 5))) m
+ X p P hD hd internal A child parent oldDir newDir Q src term)
+ (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m)
+ (wide : D < 2^bits) :
+ ∃ d es, ChildScan.Prefix M m c d [] es ∧
+ es.length = (RegisterSetup.lines f).length + chainTicks ((gridOrder B).symm selected).val p.2.val ∧
+ countProbes es = ∑ i, (f i).loads ∧ choiceBits es = [] ∧ d.pc = target selected p.2 ∧
+ (∀ q, (∀ i, q ≠ vm i) → d.reg q = c.reg q) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨es,mid,len,probes,path,pc',mem,per,keys,frame,run⟩ :=
+ MapRoute.setup B X choice p A child parent oldDir newDir ties start stride m I M c inputs vm pc link safe entry args stored wide
+ obtain ⟨d,tail,done,frame',mem',per'⟩ := keys_hit B I stride vm place target bad X p M linked mid (pc'.trans next) keys wide
+ let n := chainTicks ((gridOrder B).symm selected).val p.2.val
+ have first : ChildScan.Prefix M m c mid [] es := run
+ change PrimedCounter.GuessWord.Prefix M mid (List.replicate n .tick) d at tail
+ have counts := tick_counts (bits := bits) n
+ have second : ChildScan.Prefix M m mid d [] (List.replicate n .tick) := by
+ intro fuel more
+ simpa only [counts.1] using tail.execute fuel m more
+ refine ⟨d,es ++ List.replicate n .tick,first.trans second,?_,?_,?_,done,fun q hq => (frame' q hq).trans (frame q hq),
+ mem'.trans mem,per'.trans per⟩
+ · rw [List.length_append,len,List.length_replicate]
+ · rw [countProbes_append,probes,counts.2,Nat.add_zero]
+ · rw [PrimedInputRAM.Flow.choiceBits_append,path,counts.1,List.nil_append]
+
+end CompressorRecords.PortRefresh.RefreshResidentDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshResidentExact.lean b/lean/OAI/Computability/VPVNP/PairRefreshResidentExact.lean
new file mode 100644
index 0000000000..e55670e65a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshResidentExact.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.PairRefreshResidentReads
+import OAI.Computability.VPVNP.PairRefreshResidentMapExact
+
+/-! # A successful refresh kernel has a fixed trace and upper scratch
+
+The chronological diagonal and dispatch prefix preserves the actual inputs
+of the selected handler. The resulting trace and upper-scratch update are
+determined by these input words, the two node halves and the incoming scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe OperandInputs PairSimulation NodeArguments MotifConversion NewSlots RefreshMapOperands NetworkKernel
+open scoped Fin.CommRing
+
+variable {bits g t hist shared pcs regs : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+ (T : Plan B t hist shared)
+ (pc : T.Address → Fin pcs) (dfs : Fin 9 ↪ Fin regs) (saved : VertexImage.Saved ↪ Fin regs)
+ (common : Fin shared ↪ Fin regs) (own : T.Local ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11) (installed : T.Installed pc dfs saved common own done M)
+
+local notation "D" => 2^S.portExponent
+local notation "H" => 2^S.expanderExponent
+local notation "P" => S.graph.toSlotGraph
+local notation "hD" => S.port_order
+local notation "hd" => And.right S.degree_bounds
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+
+variable (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ)
+ (oldDir newDir : IncidenceDirectory bits) (start : ℕ) (m : Memory bits)
+local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice
+local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t (Plan.stride T) start
+local notation "Q" => Allocation.Plan.scratch Pₗ bits
+local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ)
+local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ)
+local notation "N" => Fintype.card X.Base*D*2^g*D
+local notation "ws" => groupedWidths (bitWordFinEquiv _) (splitWidths X)
+local notation "perm" => oldPortMatching (splitSlots X) (bitWordFinEquiv _)
+local notation "inp" => T.inputs dfs saved common
+local notation "vout" => ws (v,Prod.snd v)
+local notation "vin" => ws (Equiv.symm perm (v,Prod.snd v))
+
+variable (old : X.network.Half (oldSite X v)) (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+local notation "diagonalValue" => portDiagonal perm ws (Prod.fst v) (Prod.snd v) (oldHalf X v old) (segments X v P hD hd internal new)
+
+
+open MotifEntry MotifDemandPadding MotifSelector LocalHistory
+local notation "E₀" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀)
+local notation "idx" => (z,Prod.snd v)
+local notation "L" => MapInline.layout B.refresh z (Prod.snd v)
+local notation "u" => repetitions B.refresh (EntryInput.demand E₀)
+local notation "d" => demandBits tieSource tieTarget (Prod.snd v) (EntryInput.demandBits E₀)
+local notation "x" => mapHalf S.portSupply (fun _ => inputBits) (EntryInput.supplyBits E₀)
+local notation "names" => Option.map (List.map (Plan.ordinal T))
+ (Prod.fst (runEntry B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀) (EntryInput.payload E₀) (Prod.snd v) d x))
+local notation "Wfields" => MapHandlerImage.Family.fields (Plan.family T) idx
+
+
+local notation "dx" => List.length (RegisterSetup.lines (Plan.diagonal T)) + (7*(vout+vin)+9)
+local notation "rx" => List.length (RegisterSetup.lines (Plan.route T)) +
+ RefreshResidentDispatch.chainTicks (Fin.val (Equiv.symm (RefreshResidentDispatch.gridOrder B) z)) (Fin.val (Prod.snd v))
+local notation "mx" => MapArgumentWriter.clock (Plan.directory T) Wfields + MapInline.cap B.refresh (Plan.ordinal T) z (Prod.snd v) u
+local notation "dp" => ∑ i, Expr.loads ((Plan.diagonal T) i)
+local notation "rp" => ∑ i, Expr.loads ((Plan.route T) i)
+local notation "mp" => ∑ i, Expr.loads ((MapArgumentWriter.recipes (Plan.directory T) Wfields) i)
+
+include installed in
+set_option maxHeartbeats 2000000 in
+theorem native_success_exact {fit : N ≤ 2^bits} {n limit : ℕ} (c : Config bits pcs regs) (entry : c.pc = T.diagSetup pc 0)
+ (banks : Banks T dfs saved common own)
+ (args : Describes T.input (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m
+ X v P hD hd internal A child parent oldDir newDir Q src term)
+ (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice T.ties start T.stride fit m)
+ (oldCols : oldDir.ActualColumns X m) (newCols : newDir.ActualColumns Y m)
+ (oldData : NodeFields A child X (oldSite X v) old c.privateMem)
+ (newData : NodeFields A parent Y (promotedSites v) new c.privateMem)
+ (top maxWidth directory histBase : ℕ)
+ (hdir : T.directory.eval (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m = word directory)
+ (hhist : T.histogram.eval (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m = word histBase)
+ (oldEnd : A.base child + (packed X (oldSite X v) old).length ≤ top)
+ (newEnd : A.base parent + (packed Y (promotedSites v) new).length ≤ top)
+ (oldWidth : X.maxWireWidth ≤ maxWidth) (newWidth : (Y).maxWireWidth ≤ maxWidth)
+ (inputsEnd : top+2*maxWidth ≤ directory) (histEnd : histBase+hist ≤ directory)
+ (workEnd : directory+MapCallWords.headCapacity D H+2*u ≤ limit)
+ (capacity : MapWorkspace.Capacity B.refresh bits n limit) (copyBound : u ≤ n)
+ (wide : D < 2^bits) (wo : vout < 2^bits) (wi : vin < 2^bits)
+ (tableWidth : MapConstants.widthThreshold B.refresh ≤ bits) (endAddr : ℕ) (savedScratch : DFS.Scratch bits endAddr)
+ (incoming : DFS.scratch endAddr c.privateMem = savedScratch)
+ (diagonalOK : diagonalValue = (1 : ℤ)) (namesOK : (names).isSome = true) :
+ let pub := fun i : Fin 5 => c.reg (inp i.castSucc)
+ let state := c.reg (inp (Fin.last 5))
+ let es := T.successEvents X choice v m old new tableWidth pub state
+ ∃ out, ChildScan.Prefix M m c out [] es ∧ es.length ≤ dx + rx + mx ∧
+ countProbes es = dp + (rp + mp) ∧ choiceBits es = [] ∧ out.pc = done ∧ out.persistent = c.persistent ∧
+ (∀ j, (∀ i, j ≠ own i) → out.reg j = c.reg j) ∧
+ (∀ q : W bits, q.val < directory → (∀ l : Fin hist, q ≠ word (histBase+l.val)) →
+ out.privateMem q = c.privateMem q) ∧
+ (∀ l : Fin hist, out.privateMem (word (histBase+l.val)) = c.privateMem (word (histBase+l.val)) +
+ (((names).getD []).count l : W bits)) ∧
+ DFS.scratch endAddr out.privateMem = T.mapUpper X choice v A child parent old new
+ top maxWidth directory histBase oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd
+ capacity copyBound tableWidth endAddr savedScratch := by
+ intro pub state es
+ obtain ⟨mid,front,flen,fprobes,fpath,midPC,frame,mem,pers⟩ :=
+ T.front_exact pc dfs saved common own done M installed X choice v A child parent oldDir newDir start m old new
+ c entry banks args stored oldCols newCols oldData newData wide wo wi diagonalOK
+ have inputs (i) : mid.reg (inp i) = c.reg (inp i) := frame _ (fun j => (banks.inputs j i).symm)
+ have midPub : (fun i : Fin 5 => mid.reg (inp i.castSucc)) = pub := funext fun i => inputs i.castSucc
+ have midState : mid.reg (inp (Fin.last 5)) = state := inputs (Fin.last 5)
+ obtain ⟨out,call,clen,cprobes,cpath,exit,per,regs',memory,counts,updated⟩ :=
+ T.map_native_exact pc dfs saved common own done M installed X choice v A child parent oldDir newDir start m old new
+ mid midPC banks.handler (midPub.symm ▸ midState.symm ▸ args) stored oldCols newCols (mem ▸ oldData)
+ (mem ▸ newData) top maxWidth directory histBase (midPub.symm ▸ midState.symm ▸ hdir)
+ (midPub.symm ▸ midState.symm ▸ hhist) oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd capacity
+ copyBound wide tableWidth endAddr savedScratch (mem ▸ incoming) namesOK
+ rw [midPub,midState] at call clen cprobes cpath
+ let pre := T.frontEvents X choice v m old new pub state
+ let tail := T.family.successEvents (fun _ => zero_lt_one) E₀ tableWidth pub state m
+ change pre.length = _ at flen
+ change countProbes pre = _ at fprobes
+ change choiceBits pre = [] at fpath
+ change tail.length ≤ _ at clen
+ change countProbes tail = _ at cprobes
+ change choiceBits tail = [] at cpath
+ refine ⟨out,front.trans call,?_,?_,?_,exit,per.trans pers,fun j hj => (regs' j hj).trans (frame j hj),
+ fun q hq hn => (memory q hq hn).trans (congrFun mem q),?_,updated⟩
+ · change (pre++tail).length ≤ _
+ rw [List.length_append,flen]
+ exact Nat.add_le_add_left clen _
+ · change countProbes (pre++tail) = _
+ rw [countProbes_append,fprobes,cprobes,Nat.add_assoc]
+ · change choiceBits (pre++tail) = []
+ rw [PrimedInputRAM.Flow.choiceBits_append,fpath,cpath,List.nil_append]
+ · intro l
+ rw [counts,mem]
+
+end CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshResidentFrontExact.lean b/lean/OAI/Computability/VPVNP/PairRefreshResidentFrontExact.lean
new file mode 100644
index 0000000000..2dbfad5d22
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshResidentFrontExact.lean
@@ -0,0 +1,169 @@
+import OAI.Computability.VPVNP.PairRefreshResidentKernel
+import OAI.Computability.VPVNP.CompressorRegisterSetupClock
+import OAI.Computability.VPVNP.CompressorRegisterSetupTrace
+
+/-! # Exact traces of the refresh diagonal and grid/port dispatcher
+
+The operand setup depends only on the six inputs and external memory. The
+comparison and dispatch loops add fixed runs of private ticks, so arbitrary
+caller registers have no effect on the chronological external reads.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe OperandInputs PairSimulation NodeArguments MotifConversion NewSlots RefreshMapOperands NetworkKernel
+open scoped Fin.CommRing
+
+variable {bits g t hist shared pcs regs : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+ (T : Plan B t hist shared)
+ (pc : T.Address → Fin pcs) (dfs : Fin 9 ↪ Fin regs) (saved : VertexImage.Saved ↪ Fin regs)
+ (common : Fin shared ↪ Fin regs) (own : T.Local ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11) (installed : T.Installed pc dfs saved common own done M)
+
+local notation "D" => 2^S.portExponent
+local notation "H" => 2^S.expanderExponent
+local notation "P" => S.graph.toSlotGraph
+local notation "hD" => S.port_order
+local notation "hd" => And.right S.degree_bounds
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+
+variable (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ)
+ (oldDir newDir : IncidenceDirectory bits) (start : ℕ) (m : Memory bits)
+local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice
+local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t (Plan.stride T) start
+local notation "Q" => Allocation.Plan.scratch Pₗ bits
+local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ)
+local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ)
+local notation "N" => Fintype.card X.Base*D*2^g*D
+local notation "ws" => groupedWidths (bitWordFinEquiv _) (splitWidths X)
+local notation "perm" => oldPortMatching (splitSlots X) (bitWordFinEquiv _)
+local notation "inp" => T.inputs dfs saved common
+local notation "vout" => ws (v,Prod.snd v)
+local notation "vin" => ws (Equiv.symm perm (v,Prod.snd v))
+
+variable (old : X.network.Half (oldSite X v)) (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+local notation "diagonalValue" => portDiagonal perm ws (Prod.fst v) (Prod.snd v) (oldHalf X v old) (segments X v P hD hd internal new)
+
+
+open MotifEntry MotifDemandPadding MotifSelector LocalHistory
+local notation "E₀" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀)
+local notation "idx" => (z,Prod.snd v)
+local notation "dx" => List.length (RegisterSetup.lines (Plan.diagonal T)) + (7*(vout+vin)+9)
+local notation "rx" => List.length (RegisterSetup.lines (Plan.route T)) +
+ RefreshResidentDispatch.chainTicks (Fin.val (Equiv.symm (RefreshResidentDispatch.gridOrder B) z)) (Fin.val (Prod.snd v))
+local notation "dp" => ∑ i, Expr.loads ((Plan.diagonal T) i)
+local notation "rp" => ∑ i, Expr.loads ((Plan.route T) i)
+
+/-- Chronological register-setup events obtained by evaluating the compiled operand expressions
+in the supplied external memory. -/
+def setupEvents {n : ℕ} (f : Fin n → Expr) (pub : Fin 5 → W bits) (state : W bits)
+ (m : Memory bits) : List (Event bits) :=
+ (RowRecipe.evaluate pub state m (RegisterSetup.lines f) (fun _ => 0)).1
+
+/-- Trace through diagonal setup, outgoing and incoming bit comparisons, route setup, and
+selection of the grid and party handler. -/
+noncomputable def frontEvents (pub : Fin 5 → W bits) (state : W bits) : List (Event bits) :=
+ (setupEvents T.diagonal pub state m ++ List.replicate (7*(vout+vin)+9) .tick) ++
+ (setupEvents T.route pub state m ++ List.replicate
+ (RefreshResidentDispatch.chainTicks ((RefreshResidentDispatch.gridOrder B).symm z).val v.2.val) .tick)
+
+private theorem ticks {n : ℕ} :
+ choiceBits (List.replicate n (.tick : Event bits)) = [] ∧ countProbes (List.replicate n (.tick : Event bits)) = 0 := by
+ induction n with
+ | zero => exact ⟨rfl,rfl⟩
+ | succ n ih => simpa only [List.replicate_succ,choiceBits,countProbes] using ih
+
+private theorem tickPrefix {a b : Config bits pcs regs} {n : ℕ}
+ (run : PrimedCounter.GuessWord.Prefix M a (List.replicate n .tick) b) :
+ ChildScan.Prefix M m a b [] (List.replicate n .tick) := by
+ intro fuel more
+ simpa only [(ticks (bits := bits) (n := n)).1] using run.execute fuel m more
+
+private theorem setup_exact {n : ℕ} (f : Fin n → Expr) (inputs : Fin 6 → Fin regs)
+ (vm : Fin (RegisterSetup.regCount f) ↪ Fin regs) (loc : ℕ → Fin pcs)
+ (link : RegisterSetup.Linked vm inputs M loc (RegisterSetup.lines f)) (safe : ∀ i j, vm i ≠ inputs j)
+ (c : Config bits pcs regs) (entry : c.pc = loc 0) :
+ let pub := fun i : Fin 5 => c.reg (inputs i.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let es := setupEvents f pub state m
+ ∃ d, ChildScan.Prefix M m c d [] es ∧ es.length = (RegisterSetup.lines f).length ∧
+ countProbes es = ∑ i, (f i).loads ∧ choiceBits es = [] ∧ d.pc = loc (RegisterSetup.lines f).length ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ (∀ i, d.reg (vm (RegisterSetup.output f i)) = (f i).eval pub state m) ∧
+ ∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j := by
+ intro pub state es
+ have raw := RegisterSetup.execute_setup_raw f inputs vm M m loc link safe c entry
+ dsimp only at raw
+ rw [RegisterSetup.events_eq] at raw
+ obtain ⟨d,len,probes,choices,exit,mem,pers,vals,frame,run⟩ := raw
+ exact ⟨d,run,len,probes,choices,exit,mem,pers,vals,frame⟩
+
+include installed in
+set_option maxHeartbeats 1600000 in
+theorem front_exact {fit : N ≤ 2^bits} (c : Config bits pcs regs) (entry : c.pc = T.diagSetup pc 0)
+ (banks : Banks T dfs saved common own)
+ (args : Describes T.input (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m
+ X v P hD hd internal A child parent oldDir newDir Q src term)
+ (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice T.ties start T.stride fit m)
+ (oldCols : oldDir.ActualColumns X m) (newCols : newDir.ActualColumns Y m)
+ (oldData : NodeFields A child X (oldSite X v) old c.privateMem)
+ (newData : NodeFields A parent Y (promotedSites v) new c.privateMem)
+ (wide : D < 2^bits) (wo : vout < 2^bits) (wi : vin < 2^bits) (ok : diagonalValue = (1 : ℤ)) :
+ let pub := fun i : Fin 5 => c.reg (inp i.castSucc)
+ let state := c.reg (inp (Fin.last 5))
+ let es := T.frontEvents X choice v m old new pub state
+ ∃ out, ChildScan.Prefix M m c out [] es ∧ es.length = dx + rx ∧ countProbes es = dp + rp ∧
+ choiceBits es = [] ∧ out.pc = T.family.target (T.handlerPC pc) idx ∧
+ (∀ j, (∀ i, j ≠ own i) → out.reg j = c.reg j) ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ intro pub state es
+ obtain ⟨a,first,alen,ap,ab,apc,amem,aper,aval,aframe⟩ := setup_exact M m T.diagonal inp (T.diagVM own)
+ (T.diagSetup pc) (T.diag_link pc dfs saved common own done M installed) (fun _ j => banks.inputs _ j) c entry
+ have val (i) := (aval i).trans (DiagonalFrame.values X v P hD hd internal A child parent oldDir newDir Q src term
+ T.input pub state m args oldCols newCols stored.segments wide i)
+ simp only [T.outputs own] at val
+ obtain ⟨b,scan,bpc,bmem,bper,bframe⟩ := RefreshDiagonal.compare_arguments X v P hD hd internal
+ (T.compare_link pc dfs saved common own done M installed) A child parent old new a
+ (apc.trans (dite_eq_right (Nat.lt_irrefl _))) (amem ▸ oldData) (amem ▸ newData)
+ ⟨⟨val 0,val 1,val 2⟩,⟨val 3,val 4,val 5⟩⟩ wo wi
+ rw [ite_eq_left ok] at bpc
+ have bReg (j) (hj : ∀ i, j ≠ own i) : b.reg j = c.reg j :=
+ (bframe j (fun ⟨i,e⟩ => hj _ e.symm)).trans (aframe j (fun _ => hj _))
+ have bInputs (i) : b.reg (inp i) = c.reg (inp i) := bReg _ (fun j => (banks.inputs j i).symm)
+ have bPub : (fun i : Fin 5 => b.reg (inp i.castSucc)) = pub := funext fun i => bInputs i.castSucc
+ obtain ⟨d,third,dlen,dp',db,dpc,dmem,dper,dvals,dframe⟩ := setup_exact M m T.route inp (T.routeVM own)
+ (T.routeSetup pc) (T.route_link pc dfs saved common own done M installed) (fun _ j => banks.inputs _ j) b bpc
+ rw [bPub,bInputs (Fin.last 5)] at third dlen dp' db dvals
+ have keys := MapRoute.values B X choice v A child parent oldDir newDir T.ties start T.stride m T.input pub state
+ args stored wide
+ obtain ⟨out,dispatch,exit,frame,mem,pers⟩ := RefreshResidentDispatch.keys_hit B T.input T.stride (T.routeVM own)
+ (T.routePC pc) (fun q j => T.family.target (T.handlerPC pc) (q,j)) (T.bad pc) X v M
+ (T.dispatch_link pc dfs saved common own done M installed) d (dpc.trans (dite_eq_right (Nat.lt_irrefl _)))
+ ((funext dvals).symm ▸ keys) wide
+ change (setupEvents T.diagonal pub state m).length = _ at alen
+ change (setupEvents T.route pub state m).length = _ at dlen
+ change countProbes (setupEvents T.diagonal pub state m) = _ at ap
+ change countProbes (setupEvents T.route pub state m) = _ at dp'
+ change choiceBits (setupEvents T.diagonal pub state m) = _ at ab
+ change choiceBits (setupEvents T.route pub state m) = _ at db
+ refine ⟨out,(first.trans (tickPrefix M m scan)).trans (third.trans (tickPrefix M m dispatch)),?_,?_,?_,exit,?_,
+ mem.trans (dmem.trans (bmem.trans amem)),pers.trans (dper.trans (bper.trans aper))⟩
+ · simp only [es,frontEvents,List.length_append,List.length_replicate,alen,dlen]
+ · simp only [es,frontEvents,countProbes_append,ap,dp',ticks.2,Nat.add_zero]
+ · simp only [es,frontEvents,PrimedInputRAM.Flow.choiceBits_append,ab,db,ticks.1,List.nil_append]
+ · intro j hj
+ exact (frame j (fun _ => hj _)).trans ((dframe j (fun _ => hj _)).trans (bReg j hj))
+
+end CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshResidentImage.lean b/lean/OAI/Computability/VPVNP/PairRefreshResidentImage.lean
new file mode 100644
index 0000000000..aff7872b0e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshResidentImage.lean
@@ -0,0 +1,235 @@
+import OAI.Computability.VPVNP.PairRefreshResidentDispatch
+import OAI.Computability.VPVNP.PairSimulationMapHandlerImage
+import OAI.Computability.VPVNP.PairSimulationMapInvocationClock
+import OAI.Computability.VPVNP.CompressorRefreshDiagonalFrame
+import OAI.Computability.VPVNP.CompressorRefreshMapWorkspace
+
+/-!
+# The diagonal, dispatch and motif rows of a refresh vertex
+
+The two diagonal tests enter the grid/party loader on success and a local
+reject instruction on failure. Every target of the ordinal chains is the
+argument writer of the corresponding inlined map. All operands are evaluated
+from the six registers selected by the enclosing role.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentImage
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe OperandInputs PairSimulation NodeArguments MotifConversion MotifSelector
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist shared : ℕ}
+local notation "D" => 2^S.portExponent
+local notation "H" => 2^S.expanderExponent
+local notation "hd" => And.right S.degree_bounds
+
+/-- Fixed resident refresh plan giving the tie ordering, physical operand recipes, histogram
+ordinals, and source register assignments. -/
+structure Plan (t hist shared : ℕ) where
+ /-- Enumeration of the graph's refresh ties used by the operand and handler tables. -/
+ ties : Fin t ≃ Tie D
+ /-- Stride supplied to the refresh term and route address recipes. -/
+ stride : ℕ
+ /-- Runtime address expressions for the old and new refresh argument packets and published
+ level tables. -/
+ input : OperandInputs.Input
+ /-- Recipe expression locating the private map-call directory. -/
+ directory : Expr
+ /-- Recipe expression locating the persistent private histogram counters. -/
+ histogram : Expr
+ /-- Map each refresh parameter entry to its counter ordinal in the common histogram. -/
+ ordinal : (parameterData B.refresh).Entry → Fin hist
+ /-- Identify the six recipe inputs among the DFS, saved, and shared registers. -/
+ source : Fin 6 → MapHandlerImage.Source shared
+
+namespace Plan
+
+variable {B} (A : Plan B t hist shared)
+
+/-- Compute the planned map-call field heads from the tie geometry, argument inputs, directory,
+and histogram. -/
+noncomputable def heads := MapCallWords.plannedHeads D H A.stride A.input A.directory A.histogram
+
+/-- Assemble the refresh map handler for each demand and party, with inline table layout,
+operand recipes, and global histogram ordinals. -/
+noncomputable def family : MapHandlerImage.Family B.refresh hist shared where
+ regCount i := RegisterSetup.regCount (MapCallTable.formulas (MapEntryTable.allocation B.refresh i.1 i.2)
+ (Fintype.equivFin _) (Fintype.equivFin _)) + 3
+ portCount i := Nat.card (MapEntryTable.PublicPort B.refresh i.1 i.2)
+ layout i := MapInline.layout B.refresh i.1 i.2
+ ordinal := A.ordinal
+ base _ := A.directory
+ field _ := MapCallWords.fields S.graph.toSlotGraph hd A.ties A.stride A.input A.heads
+ source _ := A.source
+
+/-- Register expressions for checking the diagonal tie at the designated external refresh slot. -/
+def diagonal := DiagonalFrame.fields D (refreshSlots hd (Sum.inl 0)) A.input
+/-- Register expressions that select the demand profile and party of the refresh map call. -/
+def route := MapRoute.fields D A.stride A.input
+
+/-- Instruction addresses for diagonal setup, the comparisons, route setup and dispatch, the
+map handler, and the rejection exit. -/
+noncomputable abbrev Address := Fin (RegisterSetup.lines A.diagonal).length ⊕ (Fin 3 × Fin 7) ⊕
+ Fin (RegisterSetup.lines A.route).length ⊕ ResidentDispatchImage.Address B.refresh.grid.demands (Fin D) ⊕
+ A.family.Address ⊕ Unit
+
+/-- Local register banks reserved for diagonal setup and scanning, route evaluation, and the
+selected map handler. -/
+noncomputable abbrev Local := (Fin (RegisterSetup.regCount A.diagonal) ⊕ Fin 4) ⊕
+ Fin (RegisterSetup.regCount A.route) ⊕ A.family.PrivateReg
+
+variable {p r w : ℕ} (pc : A.Address → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r) (own : A.Local ↪ Fin r) (done : Fin p)
+
+/-- Resolve each recipe input to its host register using its designated DFS, saved, or shared
+source. -/
+def inputs (i : Fin 6) := (A.source i).elim dfs (Sum.elim saved common)
+
+/-- Register embedding for the compiled diagonal-setup expressions. -/
+noncomputable def diagVM : Fin (RegisterSetup.regCount A.diagonal) ↪ Fin r :=
+ (Function.Embedding.inl.trans Function.Embedding.inl).trans own
+
+private def diagSlots : Fin 10 ↪ (Fin 6 ⊕ Fin 4) :=
+ ⟨![.inl 0,.inl 1,.inl 2,.inr 0,.inr 1,.inr 2,.inr 3,.inl 3,.inl 4,.inl 5], by decide⟩
+
+/-- Select the ten registers for the two diagonal bit scans from the setup outputs and the
+additional scratch registers. -/
+noncomputable def diagReg : Fin 10 ↪ Fin r :=
+ (diagSlots.trans <| (Function.Embedding.sumMap
+ (⟨RegisterSetup.output A.diagonal,fun _ _ eqn => Fin.ext (congrArg (Fin.val : Fin (RegisterSetup.regCount A.diagonal) → ℕ) eqn)⟩ : Fin 6 ↪ _)
+ (Function.Embedding.refl _)).trans Function.Embedding.inl).trans own
+
+theorem outputs (i : Fin 6) :
+ A.diagVM own (RegisterSetup.output A.diagonal i) = A.diagReg own (DiagonalFrame.register i) := by
+ fin_cases i <;> rfl
+
+/-- Register embedding for the compiled route-setup expressions. -/
+noncomputable def routeVM : Fin (RegisterSetup.regCount A.route) ↪ Fin r :=
+ (Function.Embedding.inl.trans Function.Embedding.inr).trans own
+
+/-- Place the refresh handler family's private registers in the resident plan's local bank. -/
+noncomputable def handlerReg : A.family.PrivateReg ↪ Fin r :=
+ (Function.Embedding.inr.trans Function.Embedding.inr).trans own
+
+/-- Program counter of the chosen control or bit-scan instruction in the diagonal comparison
+block. -/
+def comparePC (scan : Fin 3) (i : Fin 7) := pc (.inr (.inl (scan,i)))
+/-- Program counter of a refresh grid or party dispatch instruction. -/
+def routePC (a : ResidentDispatchImage.Address B.refresh.grid.demands (Fin D)) := pc (.inr (.inr (.inr (.inl a))))
+/-- Translate a local map-family instruction address into its resident program counter. -/
+def handlerPC (a : A.family.Address) := pc (.inr (.inr (.inr (.inr (.inl a)))))
+/-- Rejection address reached when the resident refresh selection fails. -/
+def bad := pc (.inr (.inr (.inr (.inr (.inr ())))))
+
+/-- Program counter for a diagonal setup line, with fallthrough to the first comparison once
+all operands are evaluated. -/
+noncomputable def diagSetup (i : ℕ) : Fin p := if hi : i < (RegisterSetup.lines A.diagonal).length then
+ pc (.inl ⟨i,hi⟩) else A.comparePC pc 0 0
+/-- Program counter for a route setup line, with fallthrough to the dispatch entry after its
+last line. -/
+noncomputable def routeSetup (i : ℕ) : Fin p := if hi : i < (RegisterSetup.lines A.route).length then
+ pc (.inr (.inr (.inl ⟨i,hi⟩))) else A.routePC pc (.inl ())
+
+/-- The installed grid-and-party dispatcher using the evaluated route registers and the
+family's handler entries. -/
+noncomputable def dispatcher := RefreshResidentDispatch.image B A.input A.stride (A.routeVM own)
+ (A.routePC pc) (fun z j => A.family.target (A.handlerPC pc) (z,j)) (A.bad pc)
+
+/-- The host rows. The caller supplies the already loaded common registers and
+the continuation for a successful motif. The diagonal and map failures halt. -/
+noncomputable def text : A.Address → Instr 5 p r 11
+ | .inl i => (RegisterSetup.instruction (w := 2) (A.diagVM own) (A.inputs dfs saved common)
+ (RegisterSetup.lines A.diagonal)[i.val] (A.diagSetup pc (i.val+1))).resize 5
+ | .inr (.inl (s,i)) => match s.val with
+ | 0 => RefreshDiagonal.control (A.comparePC pc 0) (A.comparePC pc 1) (A.comparePC pc 2)
+ (A.diagReg own) (A.routeSetup pc 0) (A.bad pc) i
+ | 1 => MapConsistency.instruction (A.comparePC pc 1) (RefreshDiagonal.loopRegs (A.diagReg own)) (A.comparePC pc 0 2) i
+ | _ => MapConsistency.instruction (A.comparePC pc 2) (RefreshDiagonal.loopRegs (A.diagReg own)) (A.comparePC pc 0 5) i
+ | .inr (.inr (.inl i)) => (RegisterSetup.instruction (w := 2) (A.routeVM own) (A.inputs dfs saved common)
+ (RegisterSetup.lines A.route)[i.val] (A.routeSetup pc (i.val+1))).resize 5
+ | .inr (.inr (.inr (.inl a))) => (A.dispatcher pc own).text a
+ | .inr (.inr (.inr (.inr (.inl a)))) =>
+ A.family.text (A.handlerPC pc) dfs saved common (A.handlerReg own) done a
+ | .inr (.inr (.inr (.inr (.inr _)))) => .reject
+
+private noncomputable def number (Z : Type*) [Finite Z] : Z ≃ Fin (Nat.card Z) := by
+ letI := Fintype.ofFinite Z
+ exact Fintype.equivFinOfCardEq Nat.card_eq_fintype_card.symm
+
+/-- Finite numbering of all addresses in the resident refresh instruction image. -/
+noncomputable def locations : A.Address ≃ Fin (Nat.card A.Address) := number _
+/-- Finite numbering of the shared and local registers used to install the resident image. -/
+noncomputable def registers : (Fin shared ⊕ A.Local) ≃ Fin (Nat.card (Fin shared ⊕ A.Local)) := number _
+
+/-- The vertex segment obtained by numbering the plan's instructions and registers, entered at
+the first diagonal-setup instruction. -/
+noncomputable def segment : VertexImage.Segment where
+ count := Nat.card A.Address
+ privateRegs := Nat.card (Fin shared ⊕ A.Local)
+ entry := A.diagSetup A.locations 0
+ row loc dfs saved localRegs done i := A.text (loc ∘ A.locations) dfs saved
+ ((Function.Embedding.inl.trans A.registers.toEmbedding).trans localRegs)
+ ((Function.Embedding.inr.trans A.registers.toEmbedding).trans localRegs) done (A.locations.symm i)
+
+variable (M : Machine w p r 11)
+/-- Each physical instruction at a plan address is the plan's instruction resized to the
+machine word width. -/
+def Installed : Prop := ∀ a, M.code (pc a) = (A.text pc dfs saved common own done a).resize w
+
+private theorem resize5 (op : Instr 2 p r 11) : (op.resize 5).resize w = op.resize w := by
+ cases op <;> try rfl
+ case constant dst val next => simp only [Instr.resize, resize_literal (by decide : 2 ≤ 5)]
+
+variable (installed : A.Installed pc dfs saved common own done M)
+
+include installed in
+theorem diag_link : RegisterSetup.Linked (A.diagVM own) (A.inputs dfs saved common) M (A.diagSetup pc)
+ (RegisterSetup.lines A.diagonal) := by
+ intro i
+ rw [diagSetup,dite_eq_left i.isLt,installed]
+ exact (resize5 _).trans (RegisterSetup.resize_instruction ..)
+
+include installed in
+theorem compare_link : RefreshDiagonal.Linked M (A.comparePC pc 0) (A.comparePC pc 1) (A.comparePC pc 2)
+ (A.diagReg own) (A.routeSetup pc 0) (A.bad pc) := by
+ constructor <;> intro i <;> apply (installed (.inr (.inl (_,i)))).trans <;> fin_cases i <;> rfl
+
+include installed in
+theorem route_link : RegisterSetup.Linked (A.routeVM own) (A.inputs dfs saved common) M (A.routeSetup pc)
+ (RegisterSetup.lines A.route) := by
+ intro i
+ rw [routeSetup,dite_eq_left i.isLt,installed]
+ exact (resize5 _).trans (RegisterSetup.resize_instruction ..)
+
+include installed in
+theorem dispatch_link : (A.dispatcher pc own).Linked M := fun a => installed (.inr (.inr (.inr (.inl a))))
+
+include installed in
+theorem handler_rows (a) : M.code (A.handlerPC pc a) =
+ (A.family.text (A.handlerPC pc) dfs saved common (A.handlerReg own) done a).resize w :=
+ installed (.inr (.inr (.inr (.inr (.inl a)))))
+
+include installed in
+theorem rejection : M.code (A.bad pc) = .reject := installed (.inr (.inr (.inr (.inr (.inr ())))))
+
+theorem segment_installed (loc : Fin A.segment.count → Fin p)
+ (localRegs : Fin A.segment.privateRegs ↪ Fin r)
+ (installed : ∀ i, M.code (loc i) = (A.segment.row loc dfs saved localRegs done i).resize w) :
+ A.Installed (loc ∘ A.locations) dfs saved
+ ((Function.Embedding.inl.trans A.registers.toEmbedding).trans localRegs)
+ ((Function.Embedding.inr.trans A.registers.toEmbedding).trans localRegs) done M := by
+ intro a
+ change M.code (loc (A.locations a)) = _
+ exact (installed (A.locations a)).trans (by simp only [segment,Equiv.symm_apply_apply])
+
+end Plan
+end CompressorRecords.PortRefresh.RefreshResidentImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshResidentKernel.lean b/lean/OAI/Computability/VPVNP/PairRefreshResidentKernel.lean
new file mode 100644
index 0000000000..2d162cf4aa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshResidentKernel.lean
@@ -0,0 +1,216 @@
+import OAI.Computability.VPVNP.PairRefreshResidentDiagonal
+import OAI.Computability.VPVNP.PairRefreshResidentMap
+
+/-!
+# The complete resident refresh kernel on the host RAM
+
+The diagonal multiplier and the selected interpreter execute in one native
+segment. A failing diagonal reaches its own reject instruction. Otherwise
+the actual grid/party handler determines the return or rejection and the
+histogram updates.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe OperandInputs PairSimulation NodeArguments MotifConversion NewSlots RefreshMapOperands NetworkKernel
+open scoped Fin.CommRing
+
+variable {bits g t hist shared pcs regs : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+ (T : Plan B t hist shared)
+ (pc : T.Address → Fin pcs) (dfs : Fin 9 ↪ Fin regs) (saved : VertexImage.Saved ↪ Fin regs)
+ (common : Fin shared ↪ Fin regs) (own : T.Local ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11) (installed : T.Installed pc dfs saved common own done M)
+
+local notation "D" => 2^S.portExponent
+local notation "H" => 2^S.expanderExponent
+local notation "P" => S.graph.toSlotGraph
+local notation "hD" => S.port_order
+local notation "hd" => And.right S.degree_bounds
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+
+variable (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ)
+ (oldDir newDir : IncidenceDirectory bits) (start : ℕ) (m : Memory bits)
+local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice
+local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t (Plan.stride T) start
+local notation "Q" => Allocation.Plan.scratch Pₗ bits
+local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ)
+local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ)
+local notation "N" => Fintype.card X.Base*D*2^g*D
+local notation "ws" => groupedWidths (bitWordFinEquiv _) (splitWidths X)
+local notation "perm" => oldPortMatching (splitSlots X) (bitWordFinEquiv _)
+local notation "inp" => T.inputs dfs saved common
+local notation "vout" => ws (v,Prod.snd v)
+local notation "vin" => ws (Equiv.symm perm (v,Prod.snd v))
+
+variable (old : X.network.Half (oldSite X v)) (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+local notation "diagonalValue" => portDiagonal perm ws (Prod.fst v) (Prod.snd v) (oldHalf X v old) (segments X v P hD hd internal new)
+
+
+open MotifEntry MotifDemandPadding MotifSelector LocalHistory
+local notation "E₀" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀)
+local notation "idx" => (z,Prod.snd v)
+local notation "L" => MapInline.layout B.refresh z (Prod.snd v)
+local notation "u" => repetitions B.refresh (EntryInput.demand E₀)
+local notation "d" => demandBits tieSource tieTarget (Prod.snd v) (EntryInput.demandBits E₀)
+local notation "x" => mapHalf S.portSupply (fun _ => inputBits) (EntryInput.supplyBits E₀)
+local notation "names" => Option.map (List.map (Plan.ordinal T))
+ (Prod.fst (runEntry B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀) (EntryInput.payload E₀) (Prod.snd v) d x))
+local notation "Wfields" => MapHandlerImage.Family.fields (Plan.family T) idx
+
+
+local notation "dx" => List.length (RegisterSetup.lines (Plan.diagonal T)) + (7*(vout+vin)+9)
+local notation "rx" => List.length (RegisterSetup.lines (Plan.route T)) +
+ RefreshResidentDispatch.chainTicks (Fin.val (Equiv.symm (RefreshResidentDispatch.gridOrder B) z)) (Fin.val (Prod.snd v))
+local notation "mx" => MapArgumentWriter.clock (Plan.directory T) Wfields + MapInline.cap B.refresh (Plan.ordinal T) z (Prod.snd v) u
+local notation "dp" => ∑ i, Expr.loads ((Plan.diagonal T) i)
+local notation "rp" => ∑ i, Expr.loads ((Plan.route T) i)
+local notation "mp" => ∑ i, Expr.loads ((MapArgumentWriter.recipes (Plan.directory T) Wfields) i)
+
+/-- The refresh image's local registers are disjoint from each DFS, saved, and shared register
+bank. -/
+structure Banks : Prop where
+ dfs : ∀ a b, own a ≠ dfs b
+ saved : ∀ a b, own a ≠ saved b
+ common : ∀ a b, own a ≠ common b
+
+variable {T dfs saved common own} in
+theorem Banks.inputs (h : Banks T dfs saved common own) (a j) : own a ≠ inp j := by
+ change own a ≠ (T.source j).elim dfs (Sum.elim saved common)
+ cases T.source j with
+ | inl i => exact h.dfs a i
+ | inr s => cases s with
+ | inl i => exact h.saved a i
+ | inr i => exact h.common a i
+
+variable {T dfs saved common own} in
+theorem Banks.handler (h : Banks T dfs saved common own) : T.family.Apart dfs saved common (T.handlerReg own) :=
+ ⟨fun _ j => h.dfs _ j,fun _ j => h.saved _ j,fun _ j => h.common _ j⟩
+
+include installed in
+set_option maxHeartbeats 2000000 in
+/-- Execute the full resident refresh kernel. The branch choice is exactly
+the mathematical diagonal test followed by the map on the two node halves. -/
+theorem native {fit : N ≤ 2^bits} {n limit : ℕ} (c : Config bits pcs regs) (entry : c.pc = T.diagSetup pc 0)
+ (banks : Banks T dfs saved common own)
+ (args : Describes T.input (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m
+ X v P hD hd internal A child parent oldDir newDir Q src term)
+ (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice T.ties start T.stride fit m)
+ (oldCols : oldDir.ActualColumns X m) (newCols : newDir.ActualColumns Y m)
+ (oldData : NodeFields A child X (oldSite X v) old c.privateMem)
+ (newData : NodeFields A parent Y (promotedSites v) new c.privateMem)
+ (top maxWidth directory histBase : ℕ)
+ (hdir : T.directory.eval (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m = word directory)
+ (hhist : T.histogram.eval (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m = word histBase)
+ (oldEnd : A.base child + (packed X (oldSite X v) old).length ≤ top)
+ (newEnd : A.base parent + (packed Y (promotedSites v) new).length ≤ top)
+ (oldWidth : X.maxWireWidth ≤ maxWidth) (newWidth : (Y).maxWireWidth ≤ maxWidth)
+ (inputsEnd : top+2*maxWidth ≤ directory) (histEnd : histBase+hist ≤ directory)
+ (workEnd : directory+MapCallWords.headCapacity D H+2*u ≤ limit)
+ (capacity : MapWorkspace.Capacity B.refresh bits n limit) (copyBound : u ≤ n)
+ (wide : D < 2^bits) (wo : vout < 2^bits) (wi : vin < 2^bits)
+ (tableWidth : MapConstants.widthThreshold B.refresh ≤ bits) :
+ let emitted := if diagonalValue = (1 : ℤ) then names else none
+ ∃ out es, ChildScan.Prefix M m c out [] es ∧ es.length ≤ dx + rx + mx ∧
+ countProbes es = dp + (if diagonalValue = (1 : ℤ) then rp + mp else 0) ∧ choiceBits es = [] ∧
+ (if emitted.isSome then out.pc = done else M.code out.pc = .reject) ∧ out.persistent = c.persistent ∧
+ (∀ j, (∀ i, j ≠ own i) → out.reg j = c.reg j) ∧
+ (∀ q : W bits, q.val < directory → (∀ l : Fin hist, q ≠ word (histBase+l.val)) → out.privateMem q = c.privateMem q) ∧
+ ∀ l : Fin hist, out.privateMem (word (histBase+l.val)) = c.privateMem (word (histBase+l.val)) +
+ ((emitted.getD []).count l : W bits) := by
+ dsimp only
+ obtain ⟨mid,es,first,len,probes,path,pc',frame,mem,per⟩ := T.diagonal_native pc dfs saved common own done M
+ installed X choice v A child parent oldDir newDir start m old new c entry banks.inputs args stored oldCols newCols
+ oldData newData wide wo wi
+ by_cases ok : diagonalValue = (1 : ℤ)
+ · simp only [ite_eq_left ok] at pc' ⊢
+ have inputEq (j) : mid.reg (inp j) = c.reg (inp j) := frame _ (fun i => (banks.inputs i j).symm)
+ have pubEq : (fun i : Fin 5 => mid.reg (inp i.castSucc)) = (fun i : Fin 5 => c.reg (inp i.castSucc)) :=
+ funext fun i => inputEq i.castSucc
+ have args' := pubEq.symm ▸ (inputEq (Fin.last 5)).symm ▸ args
+ obtain ⟨next,rs,second,rlen,rprobes,rpath,rpc,rframe,rmem,rper⟩ :=
+ RefreshResidentDispatch.load_and_dispatch B T.input T.stride (T.routeVM own) (T.routePC pc)
+ (fun z' j => T.family.target (T.handlerPC pc) (z',j)) (T.bad pc) X v choice A child parent oldDir newDir
+ T.ties start m M mid inp (T.routeSetup pc) (T.route_link pc dfs saved common own done M installed)
+ (fun _ j => banks.inputs _ j) pc' (dite_eq_right (Nat.lt_irrefl _))
+ (T.dispatch_link pc dfs saved common own done M installed) args' stored wide
+ have allregs (j) (hj : ∀ i, j ≠ own i) : next.reg j = c.reg j :=
+ (rframe j (fun _ => hj _)).trans (frame j hj)
+ have eqr (j) : next.reg (inp j) = c.reg (inp j) := allregs _ (fun i => (banks.inputs i j).symm)
+ have pub' : (fun i : Fin 5 => next.reg (inp i.castSucc)) = (fun i : Fin 5 => c.reg (inp i.castSucc)) :=
+ funext fun i => eqr i.castSucc
+ have mem' := rmem.trans mem
+ obtain ⟨out,ms,third,mlen,mprobes,mpath,mpc,mper,mframe,mmem,histogram⟩ :=
+ T.map_native pc dfs saved common own done M installed X choice v A child parent oldDir newDir start m old new next
+ rpc banks.handler (pub'.symm ▸ (eqr (Fin.last 5)).symm ▸ args) stored oldCols newCols (mem' ▸ oldData)
+ (mem' ▸ newData) top maxWidth directory histBase (pub'.symm ▸ (eqr (Fin.last 5)).symm ▸ hdir)
+ (pub'.symm ▸ (eqr (Fin.last 5)).symm ▸ hhist) oldEnd newEnd oldWidth newWidth inputsEnd histEnd
+ workEnd capacity copyBound wide tableWidth
+ refine ⟨out,(es++rs)++ms,(first.trans second).trans third,?_,?_,?_,mpc,mper.trans (rper.trans per),
+ fun j hj => (mframe j hj).trans (allregs j hj),fun q hq hn => (mmem q hq hn).trans (congrFun mem' q),?_⟩
+ · rw [List.length_append,List.length_append,len,rlen]
+ exact Nat.add_le_add_left mlen _
+ · rw [countProbes_append,countProbes_append,probes,rprobes,mprobes,Nat.add_assoc]
+ rfl
+ · rw [PrimedInputRAM.Flow.choiceBits_append,PrimedInputRAM.Flow.choiceBits_append,path,rpath,mpath]; rfl
+ · intro l
+ rw [histogram,mem']
+ · simp only [ite_eq_right ok] at pc' ⊢
+ refine ⟨mid,es,first,?_,?_,path,?_,per,frame,fun q _ _ => congrFun mem q,?_⟩
+ · rw [len]; omega
+ · simpa using probes
+ · rw [pc']; exact T.rejection pc dfs saved common own done M installed
+ · intro l
+ simp [mem]
+
+/-- The external probe bound depends only on the fixed motif and the recipes
+of the enclosing role. Internal instructions additionally scale with the two
+diagonal widths and the number of motif copies. -/
+theorem uniform : ∃ C : ℕ, ∀ (grid : B.refresh.grid.demands) (port : Fin D) (outWidth inWidth copies : ℕ),
+ let fields := T.family.fields (grid,port)
+ let cost := (RegisterSetup.lines T.diagonal).length + (7*(outWidth+inWidth)+9) +
+ ((RegisterSetup.lines T.route).length + RefreshResidentDispatch.chainTicks
+ ((RefreshResidentDispatch.gridOrder B).symm grid).val port.val) +
+ (MapArgumentWriter.clock T.directory fields + MapInline.cap B.refresh T.ordinal grid port copies)
+ (∑ i, (T.diagonal i).loads) + ((∑ i, (T.route i).loads) +
+ ∑ i, ((MapArgumentWriter.recipes T.directory fields) i).loads) ≤ C ∧
+ cost ≤ C * (outWidth+inWidth+copies+1) := by
+ obtain ⟨K,bound⟩ := T.family.uniform
+ let fixed := (RegisterSetup.lines T.diagonal).length + (RegisterSetup.lines T.route).length + 9 +
+ RefreshResidentDispatch.chainTicks (MapRoute.gridCases B).length D
+ let reads := (∑ i, (T.diagonal i).loads) + ∑ i, (T.route i).loads
+ refine ⟨fixed+7+K+reads,fun grid port wo wi copies => ?_⟩
+ obtain ⟨probe,work⟩ := bound (grid,port) copies
+ change (∑ i, ((MapArgumentWriter.recipes T.directory (T.family.fields (grid,port))) i).loads) ≤ K at probe
+ change MapArgumentWriter.clock T.directory (T.family.fields (grid,port)) +
+ MapInline.cap B.refresh T.ordinal grid port copies ≤ K*(copies+1) at work
+ dsimp only
+ constructor
+ · dsimp [reads]; omega
+ · let n := wo+wi+copies+1
+ have gfit := ((RefreshResidentDispatch.gridOrder B).symm grid).isLt
+ have pfit := port.isLt
+ have fixedBound : (RegisterSetup.lines T.diagonal).length + (7*(wo+wi)+9) +
+ ((RegisterSetup.lines T.route).length + RefreshResidentDispatch.chainTicks
+ ((RefreshResidentDispatch.gridOrder B).symm grid).val port.val) ≤ fixed + 7*(wo+wi) := by
+ dsimp [fixed,RefreshResidentDispatch.chainTicks]; omega
+ have h1 : fixed ≤ fixed*n := Nat.le_mul_of_pos_right _ (by dsimp [n]; omega)
+ have h2 : 7*(wo+wi) ≤ 7*n := Nat.mul_le_mul_left _ (by dsimp [n]; omega)
+ have h3 : K*(copies+1) ≤ K*n := Nat.mul_le_mul_left _ (by dsimp [n]; omega)
+ change _ ≤ (fixed+7+K+reads)*n
+ rw [Nat.add_mul,Nat.add_mul,Nat.add_mul]
+ omega
+
+end CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshResidentMap.lean b/lean/OAI/Computability/VPVNP/PairRefreshResidentMap.lean
new file mode 100644
index 0000000000..9862c9f4ef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshResidentMap.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.PairRefreshResidentImage
+import OAI.Computability.VPVNP.PairSimulationMapHandlerRun
+import OAI.Computability.VPVNP.CompressorRefreshMapCallData
+
+/-!
+# Executing the selected resident refresh map
+
+The selected interpreter receives descriptor words computed from the level
+arrays and resident bits from the two node buffers. Its raw operand, selector,
+and histogram ranges are supplied by the concrete packed workspace.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe OperandInputs PairSimulation NodeArguments MotifConversion NewSlots RefreshMapOperands NetworkKernel
+open scoped Fin.CommRing
+
+variable {bits g t hist shared pcs regs : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+ (T : Plan B t hist shared)
+ (pc : T.Address → Fin pcs) (dfs : Fin 9 ↪ Fin regs) (saved : VertexImage.Saved ↪ Fin regs)
+ (common : Fin shared ↪ Fin regs) (own : T.Local ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11) (installed : T.Installed pc dfs saved common own done M)
+
+local notation "D" => 2^S.portExponent
+local notation "H" => 2^S.expanderExponent
+local notation "P" => S.graph.toSlotGraph
+local notation "hD" => S.port_order
+local notation "hd" => And.right S.degree_bounds
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+
+variable (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ)
+ (oldDir newDir : IncidenceDirectory bits) (start : ℕ) (m : Memory bits)
+local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice
+local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t (Plan.stride T) start
+local notation "Q" => Allocation.Plan.scratch Pₗ bits
+local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ)
+local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ)
+local notation "N" => Fintype.card X.Base*D*2^g*D
+local notation "ws" => groupedWidths (bitWordFinEquiv _) (splitWidths X)
+local notation "perm" => oldPortMatching (splitSlots X) (bitWordFinEquiv _)
+local notation "inp" => T.inputs dfs saved common
+local notation "vout" => ws (v,Prod.snd v)
+local notation "vin" => ws (Equiv.symm perm (v,Prod.snd v))
+
+variable (old : X.network.Half (oldSite X v)) (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+local notation "diagonalValue" => portDiagonal perm ws (Prod.fst v) (Prod.snd v) (oldHalf X v old) (segments X v P hD hd internal new)
+
+
+open MotifEntry MotifDemandPadding MotifSelector LocalHistory
+local notation "E₀" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀)
+local notation "idx" => (z,Prod.snd v)
+local notation "L" => MapInline.layout B.refresh z (Prod.snd v)
+local notation "u" => repetitions B.refresh (EntryInput.demand E₀)
+local notation "d" => demandBits tieSource tieTarget (Prod.snd v) (EntryInput.demandBits E₀)
+local notation "x" => mapHalf S.portSupply (fun _ => inputBits) (EntryInput.supplyBits E₀)
+local notation "names" => Option.map (List.map (Plan.ordinal T))
+ (Prod.fst (runEntry B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀) (EntryInput.payload E₀) (Prod.snd v) d x))
+local notation "Wfields" => MapHandlerImage.Family.fields (Plan.family T) idx
+
+include installed in
+set_option maxHeartbeats 1600000 in
+/-- The actual selected map exits at the caller's continuation or at a rejecting
+opcode. Its histogram additions are the multiplicities of its emitted labels.
+Words preceding the scratch directory and outside the histogram are preserved. -/
+theorem map_native {fit : N ≤ 2^bits} {n limit : ℕ} (c : Config bits pcs regs)
+ (entry : c.pc = T.family.target (T.handlerPC pc) idx)
+ (banks : T.family.Apart dfs saved common (T.handlerReg own))
+ (args : Describes T.input (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m
+ X v P hD hd internal A child parent oldDir newDir Q src term)
+ (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice T.ties start T.stride fit m)
+ (oldCols : oldDir.ActualColumns X m) (newCols : newDir.ActualColumns Y m)
+ (oldData : NodeFields A child X (oldSite X v) old c.privateMem)
+ (newData : NodeFields A parent Y (promotedSites v) new c.privateMem)
+ (top maxWidth directory histBase : ℕ)
+ (hdir : T.directory.eval (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m = word directory)
+ (hhist : T.histogram.eval (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m = word histBase)
+ (oldEnd : A.base child + (packed X (oldSite X v) old).length ≤ top)
+ (newEnd : A.base parent + (packed Y (promotedSites v) new).length ≤ top)
+ (oldWidth : X.maxWireWidth ≤ maxWidth) (newWidth : (Y).maxWireWidth ≤ maxWidth)
+ (inputsEnd : top+2*maxWidth ≤ directory) (histEnd : histBase+hist ≤ directory)
+ (workEnd : directory+MapCallWords.headCapacity D H+2*u ≤ limit)
+ (capacity : MapWorkspace.Capacity B.refresh bits n limit) (copyBound : u ≤ n)
+ (wide : D < 2^bits) (tableWidth : MapConstants.widthThreshold B.refresh ≤ bits) :
+ ∃ out es, ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ MapArgumentWriter.clock T.directory Wfields + MapInline.cap B.refresh T.ordinal z v.2 u ∧
+ countProbes es = ∑ i, ((MapArgumentWriter.recipes T.directory Wfields) i).loads ∧ choiceBits es = [] ∧
+ (if (names).isSome then out.pc = done else M.code out.pc = .reject) ∧ out.persistent = c.persistent ∧
+ (∀ j, (∀ i, j ≠ own i) → out.reg j = c.reg j) ∧
+ (∀ q : W bits, q.val < directory → (∀ l : Fin hist, q ≠ word (histBase+l.val)) → out.privateMem q = c.privateMem q) ∧
+ ∀ l : Fin hist, out.privateMem (word (histBase+l.val)) = c.privateMem (word (histBase+l.val)) +
+ (((names).getD []).count l : W bits) := by
+ let R := MapCallWords.regions B X choice v A child parent old new directory histBase
+ let loc := (L).corePC (L).locations
+ let ord := MapCallWords.regions_ordered B X choice v A child parent old new z (L).core loc top maxWidth directory
+ histBase limit oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd
+ let Wk := MapWorkspace.workspace (MapInline.callProgram L) R d x capacity copyBound ord
+ let pub := fun i : Fin 5 => c.reg (inp i.castSucc)
+ let state := c.reg (inp (Fin.last 5))
+ let addr := T.directory.eval pub state m
+ have dirFit : directory < 2^bits := by have := capacity.room; omega
+ have addrVal : addr.val = directory := (congrArg Fin.val hdir).trans (Nat.mod_eq_of_lt dirFit)
+ have hhead := MapCallWords.plannedHeads_eval B X choice v A child parent old new oldDir newDir T.ties start T.stride
+ pub state m T.input T.directory T.histogram directory histBase hdir hhist args stored wide
+ have vals := MapCallWords.values_eq B X choice v A child parent oldDir newDir T.ties start T.stride pub state m
+ T.input T.heads old new z (L).core loc Wk args oldCols newCols stored wide rfl hhead.1 hhead.2.1 hhead.2.2.1 hhead.2.2.2
+ have resident := MapCallData.resident_packed B X choice v A child parent old new z (L).core loc T.ties start T.stride m
+ c.privateMem R capacity copyBound ord addr addrVal.ge stored oldData newData rfl
+ have argc : Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H)) ≤ MapCallWords.headCapacity D H := le_max_right _ _
+ have room : addr.val+Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H)) ≤ 2^bits := by have := capacity.room; omega
+ have histVal (l : Fin hist) : (word (bits := bits) (histBase+l.val)).val = histBase+l.val :=
+ Nat.mod_eq_of_lt (by have := l.isLt; omega)
+ have dirCell (j : MapDirectoryInit.Row (L).core) :
+ (Wk.directory+(j.val : W bits)).val = directory+j.val := by
+ change ((directory : W bits)+(j.val : W bits)).val = _
+ rw [← Nat.cast_add]
+ apply Nat.mod_eq_of_lt
+ have bound := ord.directoryEnd
+ change directory + (MapPortAgreement.ports S.portSupply v.2 (L).core.edgeOrder).length ≤ directory + MapCallWords.headCapacity D H at bound
+ have := j.isLt
+ have := capacity.room
+ omega
+ have histBefore (l : Fin hist) : (word (bits := bits) (histBase+l.val)).val < addr.val := by
+ rw [histVal,addrVal]; exact (Nat.add_lt_add_left l.isLt _).trans_le histEnd
+ obtain ⟨out,es,run,len,probes,choices,branch,per,regs',mem',counts⟩ :=
+ T.family.native (T.handlerPC pc) dfs saved common (T.handlerReg own) done M
+ (T.handler_rows pc dfs saved common own done M installed) banks (fun _ => zero_lt_one) E₀ tableWidth c m Wk
+ entry room vals resident (fun l => Or.inl (histBefore l))
+ (fun l j eqn => by
+ have h : histBase+l.val = directory+j.val := (histVal l).symm.trans ((congrArg Fin.val eqn).trans (dirCell j))
+ have := l.isLt; omega)
+ refine ⟨out,es,run,len,probes,choices,branch,per,fun q hq => regs' q (fun _ => hq _),?_,counts⟩
+ intro q hq notHist
+ apply mem' q (Or.inl (hq.trans_le addrVal.ge))
+ refine ⟨⟨Or.inl ?_,Or.inl ?_,notHist⟩,fun j eqn => ?_⟩
+ · change q.val < directory + MapCallWords.headCapacity D H
+ omega
+ · change q.val < directory + MapCallWords.headCapacity D H + u
+ omega
+ · have eqv := (congrArg Fin.val eqn).trans (dirCell j)
+ omega
+
+end CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshResidentMapExact.lean b/lean/OAI/Computability/VPVNP/PairRefreshResidentMapExact.lean
new file mode 100644
index 0000000000..d519b3664c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshResidentMapExact.lean
@@ -0,0 +1,248 @@
+import OAI.Computability.VPVNP.PairRefreshResidentMap
+import OAI.Computability.VPVNP.PairSimulationMapHandlerExact
+
+/-!
+# The chronological trace and upper scratch of a successful refresh map
+
+The selected handler publishes a descriptor obtained from the two resident node
+frames and the external incidence tables. The same execution realizes the fixed
+event list and the scratch update of this physical workspace.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe OperandInputs PairSimulation NodeArguments MotifConversion NewSlots RefreshMapOperands
+open scoped Fin.CommRing
+
+variable {bits g t hist shared pcs regs : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+ (T : Plan B t hist shared)
+ (pc : T.Address → Fin pcs) (dfs : Fin 9 ↪ Fin regs) (saved : VertexImage.Saved ↪ Fin regs)
+ (common : Fin shared ↪ Fin regs) (own : T.Local ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11) (installed : T.Installed pc dfs saved common own done M)
+
+local notation "D" => 2^S.portExponent
+local notation "H" => 2^S.expanderExponent
+local notation "P" => S.graph.toSlotGraph
+local notation "hD" => S.port_order
+local notation "hd" => And.right S.degree_bounds
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+
+variable (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ)
+ (oldDir newDir : IncidenceDirectory bits) (start : ℕ) (m : Memory bits)
+local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice
+local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t (Plan.stride T) start
+local notation "Q" => Allocation.Plan.scratch Pₗ bits
+local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ)
+local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ)
+local notation "N" => Fintype.card X.Base*D*2^g*D
+local notation "inp" => T.inputs dfs saved common
+
+variable (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order S.degree_bounds.2 choice).network.Half
+ (promotedSites v))
+
+open MotifEntry MotifDemandPadding MotifSelector LocalHistory
+local notation "E₀" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀)
+local notation "idx" => (z,Prod.snd v)
+local notation "L" => MapInline.layout B.refresh z (Prod.snd v)
+local notation "u" => repetitions B.refresh (EntryInput.demand E₀)
+local notation "d" => demandBits tieSource tieTarget (Prod.snd v) (EntryInput.demandBits E₀)
+local notation "x" => mapHalf S.portSupply (fun _ => inputBits) (EntryInput.supplyBits E₀)
+local notation "names" => Option.map (List.map (Plan.ordinal T))
+ (Prod.fst (runEntry B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀) (EntryInput.payload E₀) (Prod.snd v) d x))
+local notation "Wfields" => MapHandlerImage.Family.fields (Plan.family T) idx
+
+/-- The prescribed upper-scratch update for a refresh entry. The four workspace
+heads and the descriptor address come from the concrete numeric allocation. -/
+noncomputable def mapUpper {n limit : ℕ} (top maxWidth directory histBase : ℕ)
+ (oldEnd : A.base child + (packed X (oldSite X v) old).length ≤ top)
+ (newEnd : A.base parent + (packed Y (promotedSites v) new).length ≤ top)
+ (oldWidth : X.maxWireWidth ≤ maxWidth) (newWidth : (Y).maxWireWidth ≤ maxWidth)
+ (inputsEnd : top+2*maxWidth ≤ directory) (histEnd : histBase+hist ≤ directory)
+ (workEnd : directory+MapCallWords.headCapacity D H+2*u ≤ limit)
+ (capacity : MapWorkspace.Capacity B.refresh bits n limit) (copyBound : u ≤ n)
+ (tableWidth : MapConstants.widthThreshold B.refresh ≤ bits)
+ (endAddr : ℕ) (savedScratch : DFS.Scratch bits endAddr) : DFS.Scratch bits endAddr :=
+ let R := MapCallWords.regions B X choice v A child parent old new directory histBase
+ let loc := (L).corePC (L).locations
+ let ord := MapCallWords.regions_ordered B X choice v A child parent old new z (L).core loc top maxWidth
+ directory histBase limit oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd
+ let Wk := MapWorkspace.workspace (MapInline.callProgram L) R d x capacity copyBound ord
+ MapScratch.upper (L).core (L).args loc Wk (word directory)
+ (MapConstants.selectorWord B.refresh (MapConstants.fits_of_threshold B.refresh tableWidth).2.2.2)
+ T.ordinal endAddr savedScratch
+
+set_option maxHeartbeats 1200000 in
+/-- Both the saved node-buffer prefix outside the histogram and the cache at or
+above the scratch limit retain their incoming words. -/
+theorem mapUpper_frame {n limit : ℕ} (top maxWidth directory histBase : ℕ)
+ (oldEnd : A.base child + (packed X (oldSite X v) old).length ≤ top)
+ (newEnd : A.base parent + (packed Y (promotedSites v) new).length ≤ top)
+ (oldWidth : X.maxWireWidth ≤ maxWidth) (newWidth : (Y).maxWireWidth ≤ maxWidth)
+ (inputsEnd : top+2*maxWidth ≤ directory) (histEnd : histBase+hist ≤ directory)
+ (workEnd : directory+MapCallWords.headCapacity D H+2*u ≤ limit)
+ (capacity : MapWorkspace.Capacity B.refresh bits n limit) (copyBound : u ≤ n)
+ (tableWidth : MapConstants.widthThreshold B.refresh ≤ bits)
+ (endAddr : ℕ) (savedScratch : DFS.Scratch bits endAddr)
+ (a : W bits) (upper : endAddr ≤ a.val) (far : a.val < directory ∨ limit ≤ a.val)
+ (notHist : ∀ l : Fin hist, a ≠ word (histBase+l.val)) :
+ T.mapUpper X choice v A child parent old new top maxWidth directory histBase
+ oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd capacity copyBound
+ tableWidth endAddr savedScratch ⟨a, upper⟩ = savedScratch ⟨a, upper⟩ := by
+ let R := MapCallWords.regions B X choice v A child parent old new directory histBase
+ let loc := (L).corePC (L).locations
+ let ord := MapCallWords.regions_ordered B X choice v A child parent old new z (L).core loc top maxWidth
+ directory histBase limit oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd
+ let Wk := MapWorkspace.workspace (MapInline.callProgram L) R d x capacity copyBound ord
+ let mem : PrivateScratch.Memory bits := fun q =>
+ if h : endAddr ≤ q.val then savedScratch ⟨q,h⟩ else 0
+ let sel := MapConstants.selectorWord B.refresh (MapConstants.fits_of_threshold B.refresh tableWidth).2.2.2
+ have array (base len : ℕ) (lo : directory ≤ base) (hi : base+len ≤ limit)
+ (values : Fin len → W bits) (before : PrivateScratch.Memory bits) :
+ PrivateScratch.write (base : W bits) values before a = before a := by
+ apply dite_eq_right
+ rintro ⟨i,hit⟩
+ have bound := (Nat.add_lt_add_left i.isLt base).trans_le hi
+ rw [← Nat.cast_add] at hit
+ have val : base+i.val = a.val :=
+ (Nat.mod_eq_of_lt (bound.trans capacity.room)).symm.trans (congrArg Fin.val hit)
+ omega
+ have argc : Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H)) ≤
+ MapCallWords.headCapacity D H := le_max_right _ _
+ have published : MapScratch.published (L).core (L).args loc Wk (word directory) mem a = mem a :=
+ array directory (Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H))) le_rfl (by omega) _ mem
+ have portsEnd := ord.directoryEnd
+ change directory + (MapPortAgreement.ports S.portSupply v.2 (L).core.edgeOrder).length ≤
+ directory + MapCallWords.headCapacity D H at portsEnd
+ have directoryMem (before : PrivateScratch.Memory bits) :
+ MapCallSetup.directoryMemory (L).core loc Wk before a = before a :=
+ array directory (MapPortAgreement.ports S.portSupply v.2 (L).core.edgeOrder).length le_rfl (by omega) _ before
+ have sourceLo : directory ≤ Wk.source := Nat.le_add_right ..
+ have targetLo : directory ≤ Wk.target := sourceLo.trans (Nat.le_add_right ..)
+ have sourceEnd : Wk.source+u ≤ limit := by
+ change directory + MapCallWords.headCapacity D H + u ≤ limit; omega
+ have targetEnd : Wk.target+u ≤ limit := by
+ change directory + MapCallWords.headCapacity D H + u + u ≤ limit; omega
+ have finish (θ : Fin u → MotifConversion.Selector B.refresh) (before : PrivateScratch.Memory bits) :
+ ((L).core.program loc).successMemory Wk sel T.ordinal θ before a = before a := by
+ rw [MapEntry.Program.successMemory,PrivateLabels.accumulate_outside Wk.hist _ _ a notHist,
+ array Wk.target u targetLo targetEnd, array Wk.source u sourceLo sourceEnd]
+ change MapScratch.successMemory (L).core (L).args loc Wk (word directory) sel T.ordinal mem a = _
+ unfold MapScratch.successMemory
+ cases pick : (selectorRun S.portSupply (selectorTable B.refresh) (selectorCode B.refresh)
+ (E₀).payload v.2 x).1 with
+ | none =>
+ rw [Option.elim_none,directoryMem,published]
+ exact dite_eq_left upper
+ | some θ =>
+ rw [Option.elim_some,finish,directoryMem,published]
+ exact dite_eq_left upper
+
+include installed in
+set_option maxHeartbeats 1600000 in
+/-- Execute the successful selected map on its resident operands. The descriptor
+writer fixes the external reads and the map updates all upper scratch words. -/
+theorem map_native_exact {fit : N ≤ 2^bits} {n limit : ℕ} (c : Config bits pcs regs)
+ (entry : c.pc = T.family.target (T.handlerPC pc) idx)
+ (banks : T.family.Apart dfs saved common (T.handlerReg own))
+ (args : Describes T.input (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m
+ X v P hD hd internal A child parent oldDir newDir Q src term)
+ (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice T.ties start T.stride fit m)
+ (oldCols : oldDir.ActualColumns X m) (newCols : newDir.ActualColumns Y m)
+ (oldData : NodeFields A child X (oldSite X v) old c.privateMem)
+ (newData : NodeFields A parent Y (promotedSites v) new c.privateMem)
+ (top maxWidth directory histBase : ℕ)
+ (hdir : T.directory.eval (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m = word directory)
+ (hhist : T.histogram.eval (fun i => c.reg (inp i.castSucc)) (c.reg (inp (Fin.last 5))) m = word histBase)
+ (oldEnd : A.base child + (packed X (oldSite X v) old).length ≤ top)
+ (newEnd : A.base parent + (packed Y (promotedSites v) new).length ≤ top)
+ (oldWidth : X.maxWireWidth ≤ maxWidth) (newWidth : (Y).maxWireWidth ≤ maxWidth)
+ (inputsEnd : top+2*maxWidth ≤ directory) (histEnd : histBase+hist ≤ directory)
+ (workEnd : directory+MapCallWords.headCapacity D H+2*u ≤ limit)
+ (capacity : MapWorkspace.Capacity B.refresh bits n limit) (copyBound : u ≤ n)
+ (wide : D < 2^bits) (tableWidth : MapConstants.widthThreshold B.refresh ≤ bits) (endAddr : ℕ)
+ (savedScratch : DFS.Scratch bits endAddr) (incoming : DFS.scratch endAddr c.privateMem = savedScratch)
+ (good : (names).isSome = true) :
+ let pub := fun i : Fin 5 => c.reg (inp i.castSucc)
+ let state := c.reg (inp (Fin.last 5))
+ let es := T.family.successEvents (fun _ => zero_lt_one) E₀ tableWidth pub state m
+ ∃ out, ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ MapArgumentWriter.clock T.directory Wfields + MapInline.cap B.refresh T.ordinal z v.2 u ∧
+ countProbes es = ∑ i, ((MapArgumentWriter.recipes T.directory Wfields) i).loads ∧ choiceBits es = [] ∧
+ out.pc = done ∧ out.persistent = c.persistent ∧
+ (∀ j, (∀ i, j ≠ own i) → out.reg j = c.reg j) ∧
+ (∀ q : W bits, q.val < directory → (∀ l : Fin hist, q ≠ word (histBase+l.val)) →
+ out.privateMem q = c.privateMem q) ∧
+ (∀ l : Fin hist, out.privateMem (word (histBase+l.val)) = c.privateMem (word (histBase+l.val)) +
+ (((names).getD []).count l : W bits)) ∧
+ DFS.scratch endAddr out.privateMem = T.mapUpper X choice v A child parent old new
+ top maxWidth directory histBase oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd
+ capacity copyBound tableWidth endAddr savedScratch := by
+ intro pub state es
+ let R := MapCallWords.regions B X choice v A child parent old new directory histBase
+ let loc := (L).corePC (L).locations
+ let ord := MapCallWords.regions_ordered B X choice v A child parent old new z (L).core loc top maxWidth directory
+ histBase limit oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd
+ let Wk := MapWorkspace.workspace (MapInline.callProgram L) R d x capacity copyBound ord
+ let addr := T.directory.eval pub state m
+ have dirFit : directory < 2^bits := by have := capacity.room; omega
+ have addrVal : addr.val = directory := (congrArg Fin.val hdir).trans (Nat.mod_eq_of_lt dirFit)
+ have hhead := MapCallWords.plannedHeads_eval B X choice v A child parent old new oldDir newDir T.ties start T.stride
+ pub state m T.input T.directory T.histogram directory histBase hdir hhist args stored wide
+ have vals := MapCallWords.values_eq B X choice v A child parent oldDir newDir T.ties start T.stride pub state m
+ T.input T.heads old new z (L).core loc Wk args oldCols newCols stored wide rfl hhead.1 hhead.2.1 hhead.2.2.1 hhead.2.2.2
+ have resident := MapCallData.resident_packed B X choice v A child parent old new z (L).core loc T.ties start T.stride m
+ c.privateMem R capacity copyBound ord addr addrVal.ge stored oldData newData rfl
+ have argc : Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H)) ≤ MapCallWords.headCapacity D H := le_max_right _ _
+ have room : addr.val+Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H)) ≤ 2^bits := by have := capacity.room; omega
+ have histVal (l : Fin hist) : (word (bits := bits) (histBase+l.val)).val = histBase+l.val :=
+ Nat.mod_eq_of_lt (by have := l.isLt; omega)
+ have dirCell (j : MapDirectoryInit.Row (L).core) :
+ (Wk.directory+(j.val : W bits)).val = directory+j.val := by
+ change ((directory : W bits)+(j.val : W bits)).val = _
+ rw [← Nat.cast_add]
+ apply Nat.mod_eq_of_lt
+ have bound := ord.directoryEnd
+ change directory + (MapPortAgreement.ports S.portSupply v.2 (L).core.edgeOrder).length ≤ directory + MapCallWords.headCapacity D H at bound
+ have := j.isLt
+ have := capacity.room
+ omega
+ have histBefore (l : Fin hist) : (word (bits := bits) (histBase+l.val)).val < addr.val := by
+ rw [histVal,addrVal]; exact (Nat.add_lt_add_left l.isLt _).trans_le histEnd
+ obtain ⟨out,run,len,probes,choices,exit,per,regs',mem',counts,post⟩ :=
+ T.family.native_success_exact (T.handlerPC pc) dfs saved common (T.handlerReg own) done M
+ (T.handler_rows pc dfs saved common own done M installed) banks (fun _ => zero_lt_one) E₀ tableWidth c m Wk
+ endAddr savedScratch incoming good entry room vals resident (fun l => Or.inl (histBefore l))
+ (fun l j eqn => by
+ have h : histBase+l.val = directory+j.val := (histVal l).symm.trans ((congrArg Fin.val eqn).trans (dirCell j))
+ have := l.isLt; omega)
+ refine ⟨out,run,len,probes,choices,exit,per,fun q hq => regs' q (fun _ => hq _),?_,counts,?_⟩
+ · intro q hq notHist
+ apply mem' q (Or.inl (hq.trans_le addrVal.ge))
+ refine ⟨⟨Or.inl ?_,Or.inl ?_,notHist⟩,fun j eqn => ?_⟩
+ · change q.val < directory + MapCallWords.headCapacity D H
+ omega
+ · change q.val < directory + MapCallWords.headCapacity D H + u
+ omega
+ · have eqv := (congrArg Fin.val eqn).trans (dirCell j)
+ omega
+ · change DFS.scratch endAddr out.privateMem =
+ MapScratch.upper (L).core (L).args loc Wk addr _ T.ordinal endAddr savedScratch at post
+ rw [show addr = word directory from hdir] at post
+ exact post
+
+end CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshResidentReads.lean b/lean/OAI/Computability/VPVNP/PairRefreshResidentReads.lean
new file mode 100644
index 0000000000..026185155c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshResidentReads.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.PairRefreshResidentFrontExact
+import OAI.Computability.VPVNP.PairSimulationMapHandlerAction
+
+/-! # The chronological reads of a successful resident refresh visit
+
+A fixed list of setup events and private ticks precedes the selected map.
+Each external read, including a nested load used to compute another address,
+belongs to a diagonal, route or argument-writer expression.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe PairSimulation MotifConversion NewSlots RefreshMapOperands MotifEntry LocalHistory
+open private no_choices from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+open private eval_no_writes from OAI.Computability.VPVNP.CompressorFormulaFootprint
+
+variable {bits g t hist shared : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+ (T : Plan B t hist shared) (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (m : Memory bits)
+ (old : X.network.Half (oldSite X v)) (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order S.degree_bounds.2 choice
+ ).network.Half (promotedSites v))
+
+local notation "E₀" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀)
+local notation "idx" => (z,Prod.snd v)
+local notation "Wfields" => MapHandlerImage.Family.fields (Plan.family T) idx
+
+/-- Chronological trace on a successful diagonal and motif selection. -/
+noncomputable def successEvents (hw : MapConstants.widthThreshold B.refresh ≤ bits)
+ (pub : Fin 5 → W bits) (state : W bits) : List (Event bits) :=
+ T.frontEvents X choice v m old new pub state ++
+ T.family.successEvents (fun _ => zero_lt_one) E₀ hw pub state m
+
+private theorem append_reads {data : ℕ → Prop} {a b : List (Event bits)}
+ (ha : SourceTransport.Reads data a) (hb : SourceTransport.Reads data b) :
+ SourceTransport.Reads data (a++b) :=
+ fun q w h => (List.mem_append.mp h).elim (ha q w) (hb q w)
+
+private theorem tick_reads (data : ℕ → Prop) (n : ℕ) :
+ SourceTransport.Reads data (List.replicate n (.tick : Event bits)) := by
+ intro q value h
+ cases List.eq_of_mem_replicate h
+
+theorem successEvents_readsFrom (hw : MapConstants.widthThreshold B.refresh ≤ bits)
+ (pub : Fin 5 → W bits) (state : W bits) (data : ℕ → Prop)
+ (diagSafe : ∀ j, (T.diagonal j).ReadsFrom data pub state m)
+ (routeSafe : ∀ j, (T.route j).ReadsFrom data pub state m)
+ (writerSafe : ∀ j, ((MapArgumentWriter.recipes T.directory Wfields) j).ReadsFrom data pub state m) :
+ SourceTransport.Reads data (T.successEvents X choice v m old new hw pub state) := by
+ apply append_reads
+ · exact append_reads (append_reads (RegisterSetup.lines_reads T.diagonal data pub state m diagSafe _) (tick_reads _ _))
+ (append_reads (RegisterSetup.lines_reads T.route data pub state m routeSafe _) (tick_reads _ _))
+ · apply T.family.successEvents_readsFrom (fun _ => zero_lt_one) E₀ hw pub state m data
+ · change T.directory.ReadsFrom data pub state m
+ simpa only [MapArgumentWriter.recipes,Fin.snoc_last] using writerSafe (Fin.last _)
+ · intro a
+ change (T.family.field idx a).ReadsFrom data pub state m
+ have h := writerSafe (((T.family.layout idx).args a).castSucc)
+ simpa only [MapArgumentWriter.recipes,Fin.snoc_castSucc,MapHandlerImage.Family.fields,
+ Function.comp_apply,Equiv.symm_apply_apply] using h
+
+private theorem tick_choices (n : ℕ) : choiceBits (List.replicate n (.tick : Event bits)) = [] := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa only [List.replicate_succ,choiceBits] using ih
+
+theorem successEvents_noChoices (hw : MapConstants.widthThreshold B.refresh ≤ bits)
+ (pub : Fin 5 → W bits) (state : W bits) :
+ choiceBits (T.successEvents X choice v m old new hw pub state) = [] := by
+ simp only [successEvents,frontEvents,PrimedInputRAM.Flow.choiceBits_append,setupEvents,no_choices,tick_choices,
+ List.nil_append]
+ exact T.family.successEvents_noChoices (fun _ => zero_lt_one) E₀ hw pub state m
+
+/-- The setup instructions and private loops leave every external memory cell intact. -/
+theorem successEvents_noWrites (hw : MapConstants.widthThreshold B.refresh ≤ bits)
+ (pub : Fin 5 → W bits) (state : W bits) :
+ SourceTransport.Writes (fun _ => False) (T.successEvents X choice v m old new hw pub state) := by
+ intro a value h
+ rcases List.mem_append.mp h with front | selected
+ · rcases List.mem_append.mp front with diagonal | route
+ · rcases List.mem_append.mp diagonal with setup | ticks
+ · exact eval_no_writes (fun _ => False) pub state m (RegisterSetup.lines T.diagonal) _ a value setup
+ · cases List.eq_of_mem_replicate ticks
+ · rcases List.mem_append.mp route with setup | ticks
+ · exact eval_no_writes (fun _ => False) pub state m (RegisterSetup.lines T.route) _ a value setup
+ · cases List.eq_of_mem_replicate ticks
+ · exact T.family.successEvents_noWrites (fun _ => zero_lt_one) E₀ hw pub state m a value selected
+
+theorem after_successEvents (hw : MapConstants.widthThreshold B.refresh ≤ bits)
+ (pub : Fin 5 → W bits) (state : W bits) :
+ after m (T.successEvents X choice v m old new hw pub state) = m :=
+ funext fun _ => SourceTransport.after_outside m (T.successEvents_noWrites X choice v m old new hw pub state) id
+
+end CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedDomain.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedDomain.lean
new file mode 100644
index 0000000000..044088d4f9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedDomain.lean
@@ -0,0 +1,48 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedPackets
+import OAI.Computability.VPVNP.PairVertexRoleDomains
+
+/-! # Preparing the refresh reader from a popped vertex packet -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM Compression CompressorRecords DescriptorSpace TraversalRows TraversalRoles
+open DFS VertexImage LocalHistory
+open scoped Fin.CommRing
+
+variable {k : Type} {K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes : ℕ} (blocks : ℕ) (budget : blocks * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (branch : (B.execute f hf blocks budget X).Choices)
+ (n hist w start positions : ℕ)
+
+local notation "passes" => executeLevels B f hf blocks budget X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "first" => endAddress (BlockProgram.layout B start positions blocks)
+local notation "rows" => tagWords B.recordLimit (selected B f hf blocks budget X branch)
+local notation "width" => State.totalWidth (StateExecution.finalState (B.execute f hf blocks budget X) branch)
+local notation "region" => TerminalLayout.privateRegions (slotDegree S) n (first + rows) hist
+
+/-- On the selected execution, the vertex frame supplies the geometry pointer
+and role offset of the refresh reader. Its stored packet supplies the typed
+half at the promoted port of the same chronological row. -/
+theorem prepared_of_domain (room : Rooms n hist w start positions blocks (leaf₀) passes)
+ {data : Fin 10 → Word w} {vals : LeafSourceLoad.Static 34 → Word w}
+ {counts : Scratch w n → B.Entry → ℕ} {nodeCap limit : ℕ} {node : Word w} {s : Scratch w n}
+ (domain : RoleDomains.Domain X B.recordLimit first passes region data
+ ((rows + width : ℕ) : Word w) vals counts nodeCap limit .refresh node s) :
+ Prepared n hist w start positions blocks width (leaf₀) passes room node s := by
+ obtain ⟨site, tag, address, out⟩ := domain
+ obtain ⟨z, _, stored⟩ := out.packet
+ let x : Row passes := ⟨site, tag⟩
+ exact ⟨x, prepared_at n hist w start positions blocks width (leaf₀) passes room x node s z
+ address out.frame.resident stored⟩
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedGuardRows.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedGuardRows.lean
new file mode 100644
index 0000000000..8b779d8a59
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedGuardRows.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedParser
+import OAI.Computability.VPVNP.PairRefreshHookSelectedGuardLayout
+
+/-! # Published guard layouts of chronological refresh rows -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory TraversalRows TraversalRoles
+open TerminalProgram LiveProgram PairStages.Group.Auxiliary
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+ (G : PairStages.Group) (n hist : ℕ) {l : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ l)
+ (X : State (S.degreeExponent 0) l) (z : (B.execute f hf T hT X).Choices)
+
+local notation "pub" => terminalOperands G
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "L" => BlockProgram.layout B (Fin.val (pub 2)) X.positions T
+local notation "first" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "tags" => selected B f hf T hT X z
+local notation "width" => State.totalWidth (StateExecution.finalState (B.execute f hf T hT X) z)
+local notation "size" => tagWords B.recordLimit (tags)
+
+variable (room : Rooms n hist G.w (terminalOperands G 2).val X.positions T
+ ⟨leafLayer (siteOrder X), .cursor⟩ (executeLevels B f hf T hT X z))
+local notation "site" => rowSite n hist G.w (Fin.val (pub 2)) X.positions T (width)
+ (first) (passes) room
+
+/-- Each actual selected refresh reads the two consecutive packed levels,
+including at the last pass of a branch. -/
+theorem guardLayout_at {baseBits laneBits ord : ℕ} {tab : Fin (L).shape.tables}
+ {calendar reference m : Memory G.w} {bits : Fin (width) → Bool}
+ (entry : VertexEntry B f hf T hT X z (L) tab baseBits laneBits pub calendar reference bits)
+ (history : SelectedPayloadHistory.Past B f hf (L)
+ (CompiledResident.payload B f hf (pub 2) X.positions T n) (passes) calendar)
+ (packed : VertexPacked G (L) B.recordLimit (tags) (width))
+ (frame : LinkedVertexMemory G reference ord m) (x : Row (passes)) :
+ ∃ prev next, Site.GuardLayout B ((site) x) pub m (pub 2).val X.positions T prev next := by
+ have stage := x.val.1.isLt
+ have length := executeLevels_length B f hf T hT X z
+ have live : (passes).length < (L).levels :=
+ length.trans_lt (by rw [BlockProgram.actual_level_count]; omega)
+ let prev : Fin (L).levels := ⟨x.val.1.val, stage.trans live⟩
+ let next : Fin (L).levels := ⟨x.val.1.val + 1, (Nat.succ_le_of_lt stage).trans_lt live⟩
+ refine ⟨prev, next, ?_⟩
+ exact SelectedPublished.guard_at_site B f hf G (pub 2) X.positions T hT X z
+ x.occurrence.state x.occurrence.choice (passes)[x.val.1].selector
+ x.occurrence.port x.val.1 x.occurrence.selected entry history packed frame (room x)
+ prev next rfl rfl
+
+/-- The level locator's remaining scan only includes later physical levels. -/
+theorem later_le (blocks : T ≤ n.log2 + 1) (x : Row (passes)) :
+ ((site) x).later ≤ (S.steps + 1) * (n.log2 + 1) := by
+ change (tags).length - 1 - (x.val.1.val + 1) ≤ _
+ have count : (tags).length = (passes).length + 1 := by simp [selected]
+ rw [count, Nat.add_sub_cancel]
+ exact (Nat.sub_le ..).trans ((executeLevels_length B f hf T hT X z).trans
+ (Nat.mul_le_mul_left _ blocks))
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedLevelMemory.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedLevelMemory.lean
new file mode 100644
index 0000000000..142509015e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedLevelMemory.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.PairRefreshOriginLevelMemory
+import OAI.Computability.VPVNP.PairRefreshSelectedGuardRows
+import OAI.Computability.VPVNP.PairRefreshSelectedPublished
+
+/-!
+# All refresh level operands at the actual terminal vertex
+
+The selected calendar's retained payload and the first four terminal phases
+supply the memory for every refresh row. The two controller words and the
+motif histogram may change between vertices. The physical memory frame
+transfers the level rows, tags and map read bounds across those writes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TerminalProgram LiveProgram PairStages.Group.Auxiliary
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+ (G : PairStages.Group) (n hist : ℕ) {l : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ l)
+ (X : State (S.degreeExponent 0) l) (z : (B.execute f hf T hT X).Choices)
+
+local notation "pub" => terminalOperands G
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "L" => BlockProgram.layout B (Fin.val (pub 2)) X.positions T
+local notation "tags" => selected B f hf T hT X z
+local notation "width" => State.totalWidth (StateExecution.finalState (B.execute f hf T hT X) z)
+local notation "size" => tagWords B.recordLimit (tags)
+
+set_option maxHeartbeats 1500000 in
+/-- The genuine live workspace realizes the complete refresh level memory
+predicate at every reachable terminal site, independently of its ordinal. -/
+theorem levelMemory_at (room : Rooms n hist G.w (terminalOperands G 2).val X.positions T
+ ⟨leafLayer (siteOrder X),.cursor⟩ (executeLevels B f hf T hT X z))
+ {baseBits laneBits ord : ℕ} {tab : Fin (L).shape.tables} {calendar vertex m : Memory G.w} {wire : Fin (width) → Bool}
+ (entry : VertexEntry B f hf T hT X z (L) tab baseBits laneBits pub calendar vertex wire)
+ (history : SelectedPayloadHistory.Past B f hf (L) (CompiledResident.payload B f hf (pub 2) X.positions T n)
+ (passes) calendar)
+ (packed : VertexPacked G (L) B.recordLimit (tags) (width)) (frame : LinkedVertexMemory G vertex ord m)
+ (stack : (TerminalLayout.privateRegions (slotDegree S) n (endAddress (L)+size) hist).stackBase ≤ 2^G.w)
+ (blocks : T ≤ n.log2+1) :
+ LevelMemory B f hf T hT X z n G.w (pub 2).val X.positions width room pub m := by
+ have arena := packed.arena
+ have header := packed.room
+ refine ⟨packed.roleWords frame ?_,?_,?_,?_,stack,?_,?_,?_⟩
+ · rw [tagWords,selected_layers]
+ exact entry.roles
+ · change (size+width)+endAddress (L)+size ≤ (vertexHeader G).val
+ omega
+ · change (vertexHeader G).val+31 < 2^G.w
+ omega
+ · omega
+ · exact published_at_site B f hf G (pub 2) X.positions T hT X z entry history packed frame room
+ · exact guardLayout_at B f hf G n hist T hT X z room entry history packed frame
+ · exact later_le B f hf G n hist T hT X z room blocks
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedOccurrence.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedOccurrence.lean
new file mode 100644
index 0000000000..b41e372a34
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedOccurrence.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PairShrinkRoleDirectory
+import OAI.Computability.VPVNP.CompressorRecordRefreshArgumentSite
+
+/-! # Refresh rows of a selected execution
+
+The native site order identifies a refresh output with a base, residual lane
+and promoted port. Unpacking the origin of the chosen pass recovers the input
+state and term that produced this row. The numerical directory uses the same
+ordinal and distinguishes repeated occurrences of a term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh CompressorRecords
+open TraversalRoles TraversalRows PortRefresh ShrinkRoleDirectory
+
+variable {k K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ {B : S.Templates} {f : B.Entry → K} {hf : B.IsSolution f}
+
+/-- Output sites whose selected pass is a refresh, indexed by their chronological level. -/
+abbrev Row (passes : List (SelectedLevel B f hf)) :=
+ {x : ShrinkRoleDirectory.Site passes // tagLevel B f hf passes[x.1] = .refresh}
+
+/-- The literal selected-level record determined by a refresh origin. -/
+noncomputable def level {g : ℕ} (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (bits : List Bool) :
+ SelectedLevel B f hf :=
+ ⟨_, _, _, _, X, _, .refresh X, choice, bits⟩
+
+/-- Typed input state, branch choice, and physical port of an output row. -/
+structure Occurrence (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site) where
+ /-- Number of lanes remaining after port promotion. -/
+ lanes : ℕ
+ /-- Input state recorded at this occurrence. -/
+ state : State S.portExponent (S.portExponent + lanes)
+ /-- Refresh term selected by the branch. -/
+ choice : DyadicRefreshChoice state S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh
+ /-- Base, residual lane and promoted port of the output site. -/
+ port : (state.Base × BitWord lanes) × Fin (2 ^ S.portExponent)
+ selected : v = level state choice v.selector
+ ordinal : (NewSlots.sites state.baseIndex (bitWordFinEquiv lanes) port).val =
+ ((outputOrder v).entries.symm u).val
+
+/-- Decompose the recorded origin and undo the port promotion on the actual
+output site. The shrink branch is ruled out by the stored role. -/
+noncomputable def occurrence (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site)
+ (h : tagLevel B f hf v = .refresh) : Occurrence v u := by
+ rcases v with ⟨a, g, a', g', X, p, origin, term, tape⟩
+ cases origin with
+ | shrink => cases h
+ | refresh X =>
+ refine ⟨_, X, term, promotedSites.symm u, rfl, ?_⟩
+ rcases u with ⟨⟨base, port⟩, lane⟩
+ rfl
+
+/-- The typed refresh data at this chronological output row. -/
+noncomputable abbrev Row.occurrence {passes : List (SelectedLevel B f hf)} (x : Row passes) :=
+ SelectedRows.occurrence passes[x.val.1] x.val.2 x.property
+
+private def asRefresh (passes : List (SelectedLevel B f hf)) (x : ShrinkRoleDirectory.Site passes) :
+ Option (Row passes) :=
+ if h : tagLevel B f hf passes[x.1] = .refresh then some ⟨x, h⟩ else none
+
+private theorem asRefresh_eq_some (passes : List (SelectedLevel B f hf))
+ (x : ShrinkRoleDirectory.Site passes) (y : Row passes) :
+ asRefresh passes x = some y ↔ x = y.val := by
+ unfold asRefresh
+ split
+ · rw [Option.some.injEq, Subtype.ext_iff]
+ · rename_i h
+ simp only [reduceCtorEq, false_iff]
+ exact fun e => h (e ▸ y.property)
+
+variable (base : ℕ) (leaf : TaggedLayer) (passes : List (SelectedLevel B f hf)) {w : ℕ}
+
+/-- The typed row returned by matching a popped word to a physical output
+header and checking the chosen pass's role. -/
+noncomputable def decode (node : BurstRAM.Word w) : Option (Row passes) :=
+ (OutputRowDirectory.decode B.recordLimit base leaf (outputTags passes) node).bind fun x =>
+ asRefresh passes ((siteRows passes).symm x)
+
+theorem decode_eq_some_iff
+ (fit : layerBase B.recordLimit base (leaf :: outputTags passes) (passes.length + 1) ≤ 2 ^ w)
+ (node : BurstRAM.Word w) (x : Row passes) :
+ decode base leaf passes node = some x ↔
+ node.val = ShrinkRoleDirectory.address B.recordLimit base leaf passes x.val := by
+ have room : layerBase B.recordLimit base (leaf :: outputTags passes)
+ ((outputTags passes).length + 1) ≤ 2 ^ w := by simpa only [outputTags, List.length_map] using fit
+ rw [decode, Option.bind_eq_some_iff]
+ constructor
+ · rintro ⟨row, found, tagged⟩
+ have he := (asRefresh_eq_some passes _ x).mp tagged
+ have same : row = siteRows passes x.val := by rw [← he, Equiv.apply_symm_apply]
+ exact (OutputRowDirectory.decode_eq_some_iff B.recordLimit base leaf (outputTags passes) room
+ node _).mp (same ▸ found)
+ · intro addr
+ refine ⟨siteRows passes x.val, ?_, ?_⟩
+ · exact (OutputRowDirectory.decode_eq_some_iff B.recordLimit base leaf (outputTags passes) room node _).mpr addr
+ · exact (asRefresh_eq_some passes _ x).mpr (Equiv.symm_apply_apply _ _)
+
+/-- A parent address selects a unique chronological refresh occurrence. -/
+theorem unique_row {x y : Row passes}
+ (same : ShrinkRoleDirectory.address B.recordLimit base leaf passes x.val =
+ ShrinkRoleDirectory.address B.recordLimit base leaf passes y.val) : x = y :=
+ Subtype.ext (address_injective B.recordLimit base leaf passes same)
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedPackets.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedPackets.lean
new file mode 100644
index 0000000000..5abcc9ef06
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedPackets.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedParser
+import OAI.Computability.VPVNP.PairSelectedPacketOrders
+
+/-! # Typed half-wire packets at selected refresh rows
+
+At a refresh origin the output network of the chosen term is the promoted
+state. Reindexing the output half along this equality preserves all packed
+bits in their physical order, including independently chosen endpoint values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+set_option maxHeartbeats 1500000
+open scoped Fin.CommRing
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords DescriptorSpace TraversalRows TraversalRoles ShrinkRoleDirectory
+open DFS NodeArguments VertexImage TreeDecode
+open PortRefresh.NewSlots
+
+variable {k : Type} {K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f}
+
+private noncomputable abbrev promotedState {v : SelectedLevel B f hf} {u : (v.pass.step.term v.term).output.Site}
+ (x : Occurrence v u) :=
+ dyadicRefreshNext x.state S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1
+ B.refresh S.port_order S.degree_bounds.2 x.choice
+
+/-- The selected output half and the native reader's promoted half carry the
+same ordered payload. The equivalence also recovers the original term half. -/
+noncomputable def halfEquiv (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site)
+ (h : tagLevel B f hf v = .refresh) :
+ (v.pass.step.term v.term).output.Half u ≃
+ (promotedState (occurrence v u h)).network.Half (promotedSites (occurrence v u h).port) := by
+ rcases v with ⟨a, g, a', g', X, p, origin, term, tape⟩
+ cases origin with
+ | shrink => cases h
+ | refresh X =>
+ rcases u with ⟨⟨base, port⟩, lane⟩
+ exact Equiv.refl _
+
+theorem halfEquiv_packed (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site)
+ (h : tagLevel B f hf v = .refresh) (z : (v.pass.step.term v.term).output.Half u) :
+ pullBits (v.pass.output_eq v.term) (packed (v.pass.next v.term)) u z =
+ packed (promotedState (occurrence v u h)) (promotedSites (occurrence v u h).port) (halfEquiv v u h z) := by
+ rcases v with ⟨a, g, a', g', X, p, origin, term, tape⟩
+ cases origin with
+ | shrink => cases h
+ | refresh X =>
+ rcases u with ⟨⟨base, port⟩, lane⟩
+ rfl
+
+variable (n hist w start positions blocks width : ℕ) (leaf : TaggedLayer) (passes : List (SelectedLevel B f hf))
+ (room : Rooms n hist w start positions blocks leaf passes)
+local notation "base₀" => endAddress (BlockProgram.layout B start positions blocks)
+local notation "tags₀" => leaf :: outputTags passes
+local notation "R₀" => TerminalLayout.privateRegions (slotDegree S) n ((base₀) + tagWords B.recordLimit (tags₀)) hist
+local notation "site₀" => rowSite n hist w start positions blocks width leaf passes room
+
+/-- A stored term-output packet prepares the actual row parser, with its
+physical parent and the three private geometry words loaded by the vertex. -/
+theorem prepared_at (x : Row passes) (node : BurstRAM.Word w) (s : Scratch w n)
+ (z : (passes[x.val.1].pass.step.term passes[x.val.1].term).output.Half x.val.2)
+ (atRow : node.val = ShrinkRoleDirectory.address B.recordLimit (base₀) leaf passes x.val)
+ (frame : ResidentGeometry s (word ((R₀).histBase + hist)) (word (tagWords B.recordLimit (tags₀) + width))
+ (word (R₀).histBase))
+ (stored : (Packet.mk (ShrinkRoleDirectory.address B.recordLimit (base₀) leaf passes x.val)
+ (pullBits (passes[x.val.1].pass.output_eq passes[x.val.1].term) (packed (passes[x.val.1].pass.next passes[x.val.1].term))
+ x.val.2 z)).Stored (R₀).arguments s) : ((site₀) x).Prepared node s := by
+ have parent := parent_eq n hist w start positions blocks width leaf passes room x
+ have bits := halfEquiv_packed passes[x.val.1] x.val.2 x.property z
+ refine ⟨atRow.trans parent.symm, frame, halfEquiv passes[x.val.1] x.val.2 x.property z, ?_⟩
+ rw [parent]
+ exact bits ▸ stored
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedParser.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedParser.lean
new file mode 100644
index 0000000000..9450d5d9ef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedParser.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedOccurrence
+import OAI.Computability.VPVNP.PairRefreshSelectedSite
+
+/-! # Native refresh parser on the complete selected branch
+
+The popped address determines both the chronological term and its output site.
+Its local reader uses the input state and the term stored in that occurrence,
+together with the physical arenas of the block. All rows use the same native
+refresh entry and return address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+set_option maxHeartbeats 1500000
+open scoped Fin.CommRing
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles ShrinkRoleDirectory DFS LiveProgram VertexImage
+
+variable {k : Type} {K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f}
+ (n hist w start positions blocks width : ℕ) (leaf : TaggedLayer) (passes : List (SelectedLevel B f hf))
+
+local notation "tags₀" => leaf :: outputTags passes
+local notation "base₀" => endAddress (BlockProgram.layout B start positions blocks)
+
+/-- Space required by the real selected state, term and port on each refresh
+row. The prefix supplies this bound before the terminal visit starts. -/
+def Rooms : Prop := ∀ x : Row passes, RowRoom B n hist w start positions blocks x.occurrence.state
+ x.occurrence.choice x.occurrence.port x.val.1.val (tags₀)
+
+variable (room : Rooms n hist w start positions blocks leaf passes)
+
+/-- Freeze the physical row addresses, incidence directories and geometry
+using the selected origin of this site. -/
+noncomputable def rowSite (x : Row passes) : RefreshHook.Site B n hist w :=
+ ofSelected B n hist w start positions blocks x.occurrence.state x.occurrence.choice
+ x.occurrence.port x.val.1.val (tags₀) width (room x)
+
+local notation "site₀" => rowSite n hist w start positions blocks width leaf passes room
+local notation "ties₀" => RefreshBlockPlan.order B
+local notation "stride₀" => PortRefresh.LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)
+
+theorem parent_eq (x : Row passes) : ((site₀) x).parent =
+ ShrinkRoleDirectory.address B.recordLimit (base₀) leaf passes x.val := by
+ change TraversalRows.address B.recordLimit (layerBase B.recordLimit (base₀) (tags₀) (x.val.1.val + 1))
+ (PortRefresh.NewSlots.sites x.occurrence.state.baseIndex (bitWordFinEquiv _) x.occurrence.port).val = _
+ rw [x.occurrence.ordinal]
+ rfl
+
+variable (order : B.Entry ≃ Fin hist) (pub : Fin 11 → Word w) (m : Memory w)
+
+/-- The global hook accepts only a decoded refresh parent and runs exactly
+the reader of that physical row. -/
+noncomputable def parser : HookParser w n where
+ read node s bits := (decode (base₀) leaf passes node).bind fun x =>
+ (((site₀) x).hook (ties₀) (stride₀) order pub m).read node s bits
+
+local notation "reader₀" => SelectedRows.parser n hist w start positions blocks width leaf passes room order
+
+/-- The exact union of prepared refresh rows of this branch. -/
+def Prepared (node : Word w) (s : Scratch w n) : Prop := ∃ x : Row passes, ((site₀) x).Prepared node s
+
+local notation "ready₀" => Prepared n hist w start positions blocks width leaf passes room
+
+variable (fit : layerBase B.recordLimit (endAddress (BlockProgram.layout B start positions blocks))
+ (leaf :: outputTags passes) (passes.length + 1) ≤ 2 ^ w)
+
+include fit in
+theorem read_at (x : Row passes) (node : Word w) (s : Scratch w n) (atRow : ((site₀) x).Prepared node s)
+ (bits : List Bool) :
+ ((reader₀) pub m).read node s bits = (((site₀) x).hook (ties₀) (stride₀) order pub m).read node s bits := by
+ have ptr : node.val = ((site₀) x).parent := atRow.1
+ have addr : node.val = ShrinkRoleDirectory.address B.recordLimit (base₀) leaf passes x.val :=
+ ptr.trans (parent_eq n hist w start positions blocks width leaf passes room x)
+ have located : SelectedRows.decode (base₀) leaf passes node = some x :=
+ (SelectedRows.decode_eq_some_iff (B := B) (f := f) (hf := hf) (w := w) (base₀) leaf passes fit node x).2 addr
+ exact congrArg (fun y : Option (Row passes) => y.bind fun i =>
+ (((site₀) i).hook (ties₀) (stride₀) order pub m).read node s bits) located
+
+/-- Prepared scratch at a popped parent identifies a unique selected refresh
+site even when two levels chose identical terms. -/
+theorem prepared_unique (node : Word w) (s : Scratch w n) (prepared : (ready₀) node s) :
+ ∃! x : Row passes, ((site₀) x).Prepared node s := by
+ obtain ⟨x, hx⟩ := prepared
+ refine ⟨x, hx, fun y hy => unique_row (base₀) leaf passes ?_⟩
+ rw [← parent_eq n hist w start positions blocks width leaf passes room y,
+ ← parent_eq n hist w start positions blocks width leaf passes room x, ← hy.1, ← hx.1]
+
+/-- The physical dispatch probe on this domain reads the refresh tag. -/
+theorem dispatch_prepared {offset : ℕ}
+ (tags : TraversalRoles.Reads w m offset B.recordLimit (base₀) (tags₀))
+ (codes : 2 < 2 ^ w) (tagFit : offset + (base₀) + tagWords B.recordLimit (tags₀) ≤ 2 ^ w)
+ (node : Word w) (s : Scratch w n) (prepared : (ready₀) node s) :
+ NodeDispatch.role (m ((offset : Word w) + node).val) = .refresh := by
+ obtain ⟨x, hx⟩ := prepared
+ have addressEq := hx.1.trans (parent_eq n hist w start positions blocks width leaf passes room x)
+ rw [dispatch_at_site B.recordLimit (base₀) leaf passes tags codes tagFit node x.val addressEq, x.property]
+ rfl
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedPublished.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedPublished.lean
new file mode 100644
index 0000000000..e93c6ce622
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedPublished.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedRows
+import OAI.Computability.VPVNP.PairRefreshHookFrozenSite
+
+/-! # Native refresh execution at every physical terminal vertex
+
+The calendar payload and the linked memory of the current vertex provide the
+published fields of each row decoded by the chronological parser. This also
+covers vertices reached after earlier calls have flushed their motif counts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles ShrinkRoleDirectory LocalHistory TerminalProgram VertexImage DFS
+open LiveProgram LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary
+open scoped Fin.CommRing
+set_option maxHeartbeats 1500000
+
+variable {k : Type} {K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k} (B : S.Templates)
+ (f : B.Entry → K) (hf : B.IsSolution f) {n l hist : ℕ} (G : LiveProgram.PairStages.Group)
+ (workspace : Word G.w) (positions blocks : ℕ) (budget : blocks * S.laneBits ≤ l)
+ (initial : State (S.degreeExponent 0) l) (branch : (B.execute f hf blocks budget initial).Choices)
+local notation "L₀" => BlockProgram.layout B workspace.val positions blocks
+local notation "passes₀" => executeLevels B f hf blocks budget initial branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder initial)) Role.cursor
+local notation "tags₀" => TraversalRoles.selected B f hf blocks budget initial branch
+local notation "width₀" => State.totalWidth (StateExecution.finalState (B.execute f hf blocks budget initial) branch)
+local notation "pub₀" => terminalOperands G
+variable {tab : Fin (BlockProgram.layout B workspace.val positions blocks).shape.tables}
+ {baseBits laneBits ordinal : ℕ} {calendar vertex current : Memory G.w}
+ {wireBits : Fin ((StateExecution.finalState (B.execute f hf blocks budget initial) branch).totalWidth) → Bool}
+ (entry : VertexEntry B f hf blocks budget initial branch
+ (BlockProgram.layout B workspace.val positions blocks) tab baseBits laneBits (terminalOperands G) calendar vertex wireBits)
+ (history : SelectedPayloadHistory.Past B f hf (BlockProgram.layout B workspace.val positions blocks)
+ (CompiledResident.payload B f hf workspace positions blocks n) (executeLevels B f hf blocks budget initial branch) calendar)
+ (packed : VertexPacked G (BlockProgram.layout B workspace.val positions blocks) B.recordLimit
+ (TraversalRoles.selected B f hf blocks budget initial branch)
+ (State.totalWidth (StateExecution.finalState (B.execute f hf blocks budget initial) branch)))
+ (frame : LinkedVertexMemory G vertex ordinal current)
+ (room : Rooms n hist G.w workspace.val positions blocks (TaggedLayer.mk (leafLayer (siteOrder initial)) Role.cursor)
+ (executeLevels B f hf blocks budget initial branch))
+local notation "site₀" => rowSite n hist G.w workspace.val positions blocks (width₀) (leaf₀) (passes₀) room
+
+include entry history packed frame in
+/-- Readback for all rows of this selected branch, directly at the site's
+external memory. -/
+theorem published_at_site (x : Row (passes₀)) : ((site₀) x).Published (RefreshBlockPlan.order B)
+ (PortRefresh.LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)) (pub₀) current :=
+ SelectedPublished.at_site B f hf G workspace positions blocks budget initial branch
+ x.occurrence.state x.occurrence.choice passes₀[x.val.1].selector x.occurrence.port x.val.1
+ x.occurrence.selected entry history packed frame (room x)
+
+variable (p q : ℕ) (order : B.Entry ≃ Fin hist)
+local notation "segments₀" => TerminalProgram.nativeSegments B G.constants p q order
+local notation "reader₀" => SelectedRows.parser n hist G.w workspace.val positions blocks (width₀) (leaf₀) (passes₀) room order (pub₀) current
+local notation "domain₀" => Prepared n hist G.w workspace.val positions blocks (width₀) (leaf₀) (passes₀) room
+
+include entry history packed frame in
+/-- At an arbitrary site of the completed calendar, the full fixed numerical
+table realizes the refresh reader for every prepared chronological row. -/
+theorem exact_at_site :
+ let V := placement (segments₀)
+ let M := (template (segments₀)).instantiate G.w (pub₀)
+ (reader₀).ExactOn (domain₀) M (V.entry .refresh) (V.dfsPC 3) V.dfs current := by
+ intro V M
+ have len : (passes₀).length + 1 = (tags₀).length := by
+ simp [TraversalRoles.selected]
+ have fit : layerBase B.recordLimit (endAddress (L₀)) (tags₀) ((passes₀).length + 1) ≤ 2^G.w := by
+ rw [len, layerBase, List.take_length]
+ change endAddress (L₀) + tagWords B.recordLimit (tags₀) ≤ _
+ have bound := packed.arena
+ have headerRoom := packed.room
+ omega
+ apply exactOn n hist G.w workspace.val positions blocks (width₀) (leaf₀) (passes₀) room order
+ current fit G.constants p q V M (template_contains (segments₀) (pub₀))
+ exact published_at_site B f hf G workspace positions blocks budget initial branch entry history packed frame room
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedRoom.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedRoom.lean
new file mode 100644
index 0000000000..b0b6a4c035
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedRoom.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedParser
+
+/-! # Uniform capacity for all refresh rows of the actual selected execution -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+open Compression CompressorRecords DescriptorSpace TraversalRows TraversalRoles ShrinkRoleDirectory
+open LocalHistory CursorBounds CursorNetwork Filter
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+
+/-- Every refresh row on every true branch meets the packet and private map
+capacity. The threshold is chosen before the coefficient specialization,
+selector tape, selected level and output port. -/
+theorem eventually_rooms (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {workspace : ℕ → ℕ} (bounded : PolynomiallyBounded workspace) (hist : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (split : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (K : Type*) [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f),
+ let Z := pairInput S split hD
+ let count := blockCount (u.θ : ℝ) n
+ ∀ z : (B.execute f hf count hT Z).Choices,
+ let passes := executeLevels B f hf count hT Z z
+ Rooms n hist (wordBits b n) (workspace n) (initialPositions b n) count
+ ⟨leafLayer (siteOrder Z), .cursor⟩ passes := by
+ filter_upwards [PortRefresh.TraversalPlan.eventually_selected_room B u b hb bounded hist] with n cap
+ intro base lanes split hD hT K _ f hf Z count z passes x
+ let O := x.occurrence
+ let tags := selected B f hf count hT Z z
+ let row := siteRows passes x.val
+ let j : Fin tags.length := row.1.succ
+ let id : Fin tags[j].layer.count := row.2
+ have parentLayer : j.val = x.val.1.val + 1 := rfl
+ have sameId : id.val = (PortRefresh.NewSlots.sites O.state.baseIndex (bitWordFinEquiv O.lanes) O.port).val :=
+ O.ordinal.symm
+ have rowEnd : tagWords B.recordLimit tags = words B.recordLimit (selectedLayers B f hf count hT Z z) := by
+ rw [tagWords, selected_layers]
+ have fits := (cap split hD hT K f hf z O.state O.choice passes[x.val.1].selector
+ x.val.1 O.selected j parentLayer id O.port).2.2
+ rw [← rowEnd, sameId] at fits
+ exact fits
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedRows.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedRows.lean
new file mode 100644
index 0000000000..909f93df03
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedRows.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedParser
+import OAI.Computability.VPVNP.PairRefreshHookNative
+
+/-! # Exact execution of the chronological refresh parser on the native table -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook.SelectedRows
+
+set_option maxHeartbeats 1500000
+open scoped Fin.CommRing
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles ShrinkRoleDirectory DFS LiveProgram VertexImage
+
+variable {k : Type} {K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f}
+ (n hist w start positions blocks width : ℕ) (leaf : TaggedLayer) (passes : List (SelectedLevel B f hf))
+ (room : Rooms n hist w start positions blocks leaf passes) (order : B.Entry ≃ Fin hist) (m : Memory w)
+local notation "site₀" => rowSite n hist w start positions blocks width leaf passes room
+local notation "reader₀" => SelectedRows.parser n hist w start positions blocks width leaf passes room order
+local notation "ready₀" => Prepared n hist w start positions blocks width leaf passes room
+local notation "ties₀" => RefreshBlockPlan.order B
+local notation "stride₀" => PortRefresh.LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)
+variable (fit : layerBase B.recordLimit (endAddress (BlockProgram.layout B start positions blocks))
+ (leaf :: outputTags passes) (passes.length + 1) ≤ 2 ^ w)
+
+variable (constants : Constants) (p q : ℕ) {pcs regs : ℕ}
+local notation "segments₀" => TerminalProgram.nativeSegments B constants p q order
+variable (V : Placement (TerminalProgram.nativeSegments B constants p q order) pcs regs) (M : Machine w pcs regs 11)
+
+include fit in
+/-- At any prepared node, success and rejection of the chronological parser
+are those of the fixed instruction table on the supplied choice tape. -/
+theorem exactOn (contains : Contains V M)
+ (published : ∀ x : Row passes, ((site₀) x).Published (ties₀) (stride₀) M.publicData m) :
+ ((reader₀) M.publicData m).ExactOn (ready₀) M (V.entry .refresh) (V.dfsPC 3) V.dfs m := by
+ have read := read_at n hist w start positions blocks width leaf passes room order M.publicData m fit
+ have exactLocal (x : Row passes) := ((site₀) x).site_exact_installed constants p q order V M m contains (published x)
+ constructor
+ · intro node s ready bits job tail result
+ obtain ⟨x, hx⟩ := ready
+ rw [read x node s hx bits] at result
+ exact (exactLocal x).success node s hx bits job tail result
+ · intro node bits c top pending ready pc nodeEq stack ptr h5 h6 one failed
+ obtain ⟨x, hx⟩ := ready
+ rw [read x node _ hx bits] at failed
+ exact (exactLocal x).reject node bits c top pending hx pc nodeEq stack ptr h5 h6 one failed
+
+end PairSimulation.RefreshHook.SelectedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshSelectedSite.lean b/lean/OAI/Computability/VPVNP/PairRefreshSelectedSite.lean
new file mode 100644
index 0000000000..550d96395f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshSelectedSite.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.PairRefreshHookSite
+import OAI.Computability.VPVNP.PairRefreshTraversalBounds
+
+/-!
+# A refresh hook at its selected physical row
+
+The site uses the layer starts, term arena, incidence directories and role offset
+of the chronological block. Its two adjacent packet addresses have the same
+physical ordinal under promotion. The two geometry cells read by the child
+scanner follow the histogram and fit below the cache.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshHook
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords CompressorRecords.PortRefresh CompressorRecords.PortRefresh.NewSlots
+open RefreshMapOperands DescriptorSpace NodeArguments NodeArguments.ChildScan
+open TraversalRoles TraversalRows LocalHistory
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+variable (n hist bits start positions blocks : ℕ) {g : ℕ} (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1 B.refresh)
+ (port : (X.Base × BitWord g) × Fin (2^S.portExponent)) (stage : ℕ) (tags : List TaggedLayer) (width : ℕ)
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order (And.right S.degree_bounds) choice
+local notation "layout₀" => BlockProgram.layout B start positions blocks
+local notation "first" => endAddress layout₀
+local notation "cap" => BlockSchedule.Templates.recordLimit B
+local notation "rows" => tagWords cap tags
+local notation "rowEnd₀" => first + rows
+local notation "id₀" => Fin.val (NewSlots.sites X.baseIndex (bitWordFinEquiv g) port)
+local notation "older₀" => layerBase cap first tags stage
+local notation "parent₀" => address cap (layerBase cap first tags (stage+1)) id₀
+local notation "child₀" => address cap older₀ id₀
+local notation "region" => TerminalLayout.privateRegions (slotDegree S) n rowEnd₀ hist
+
+/-- The packed child node uses exactly the site's port/lane ordinal. -/
+theorem child_address (origin cap₀ : ℕ) :
+ childNode X origin cap₀ (oldSite X port) = address cap₀ origin id₀ := by
+ have h := ArgumentSite.oldSite_number X port
+ change origin + (cap₀+2)*((bitWordFinEquiv _ (oldSite X port).2).val + 2^_*(X.baseIndex (oldSite X port).1).val) =
+ origin + (cap₀+2)*id₀
+ rw [← h]
+ ring
+
+/-- Bounds ensuring the child and parent rows, both wire assignments, and the refresh workspace
+fit the selected physical layout. -/
+def RowRoom : Prop := TraversalPlan.Room B X choice port (slotDegree S) n rowEnd₀ child₀ parent₀ hist bits
+
+variable (fits : RowRoom B n hist bits start positions blocks X choice port stage tags)
+
+/-- Freeze the descriptor and the histogram geometry of a selected refresh site. -/
+noncomputable def ofSelected : Site B n hist bits where
+ lanes := g
+ state := X
+ choice := choice
+ port := port
+ degree := slotDegree S
+ rowEnd := rowEnd₀
+ older := older₀
+ parent := parent₀
+ listHead := parent₀+2
+ level := stage
+ later := tags.length-1-(stage+1)
+ start := arrayBase layout₀ stage
+ prev := packedIncidence layout₀ bits stage (X.positions*2^S.portExponent)
+ next := packedIncidence layout₀ bits (stage+1) ((Y).positions*2^(S.degreeExponent 0))
+ geometry := word ((region).histBase+hist)
+ roleOffset := word (rows+width)
+ room := (child_address X port older₀ cap).symm ▸ fits
+
+local notation "site" => ofSelected B n hist bits start positions blocks X choice port stage tags width fits
+
+theorem oldNode_eq : (site).oldNode = child₀ := child_address X port older₀ cap
+
+private theorem end_pos (D : Layout) : 0 < endAddress D := by
+ have h : 0 < frameBase D := Nat.add_pos_right _ (by decide)
+ exact h.trans_le (((((Nat.le_add_right ..).trans (Nat.le_add_right ..)).trans (Nat.le_add_right ..)).trans
+ (Nat.le_add_right ..)) : frameBase D ≤ endAddress D)
+
+/-- Each actual layer, including the cursor layer, contains at least one site. -/
+theorem selected_positive {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ {l : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ l) (Z : State (S.degreeExponent 0) l)
+ (z : (B.execute f hf T hT Z).Choices) (layer : TaggedLayer) (member : layer ∈ selected B f hf T hT Z z) :
+ 0 < layer.layer.count := by
+ rcases List.mem_cons.mp member with rfl | member
+ · change 0 < (siteOrder Z).length
+ exact (show 0 < Fintype.card Z.network.Site from Z.positions_pos).trans_eq
+ ((Fintype.card_congr (siteOrder Z).entries).symm.trans (Fintype.card_fin _))
+ · obtain ⟨level,_,rfl⟩ := List.mem_map.mp member
+ rw [levelLayer_count]
+ exact (level.pass.next level.term).positions_pos
+
+set_option maxHeartbeats 600000 in
+/-- Positive, ordered row addresses and nonwrapping geometry cells used by the
+native child input. The source column limits and lane width follow from the
+same current and successor allocations as the map expression reads. -/
+theorem numeric (oldLevel nextLevel : Fin (layout₀).levels) (size : X.positions ≤ positions)
+ (oldTag : stage < tags.length) (oldCount : 0 < tags[stage].layer.count) :
+ 0 < (site).oldNode ∧ (site).oldNode < (site).parent ∧
+ (site).regions.histBase ≤ ((site).geometry+10).val ∧
+ (site).regions.histBase ≤ ((site).geometry+11).val ∧
+ cap+2 < 2^bits ∧ 2^g < 2^bits ∧ 2^S.portExponent < 2^bits ∧
+ Fintype.card X.Base*2^S.portExponent*2^g*2^S.portExponent ≤ 2^bits := by
+ have childEq := oldNode_eq B n hist bits start positions blocks X choice port stage tags width fits
+ have h₀ : first ≤ older₀ := Nat.le_add_right ..
+ have positive : 0 < child₀ := (end_pos layout₀).trans_le (h₀.trans (Nat.le_add_right ..))
+ have nextBase : layerBase cap first tags (stage+1) = endPos cap older₀ tags[stage].layer :=
+ VertexLevelBounds.layerBase_succ cap first tags ⟨stage,oldTag⟩
+ have growth : older₀ < layerBase cap first tags (stage+1) := by
+ rw [nextBase]
+ exact Nat.lt_add_of_pos_right (Nat.mul_pos (by omega) oldCount)
+ have before : child₀ < parent₀ := Nat.add_lt_add_right growth _
+ have histFit := fits.capacity.room
+ have spare : 12 ≤ n^5 := (by decide : 12 ≤ 5^5).trans (Nat.pow_le_pow_left fits.five 5)
+ have fitsWord : (region).histBase + hist + 11 < 2^bits := by
+ change (region).histBase + hist + n^5 < 2^bits at histFit
+ omega
+ have geometry (i : ℕ) (hi : i ≤ 11) :
+ ((site).geometry + (i : BurstRAM.Word bits)).val = (region).histBase+hist+i := by
+ change (Fin.ofNat (2^bits) ((region).histBase+hist)+(i : BurstRAM.Word bits)).val = _
+ rw [Fin.val_add,Fin.val_ofNat,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : (region).histBase+hist < 2^bits),
+ Nat.mod_eq_of_lt (by omega : i < 2^bits),Nat.mod_eq_of_lt (by omega)]
+ have rowBound : rowEnd₀ ≤ (region).histBase := by
+ change rowEnd₀ ≤ n + rowEnd₀*(2*slotDegree S*n+1)
+ exact (Nat.le_mul_of_pos_right _ (Nat.succ_pos _)).trans (Nat.le_add_left ..)
+ have rowFits := rowBound.trans_lt (by omega : (region).histBase < 2^bits)
+ have widthFit : cap+2 < 2^bits := by
+ have top : layerBase cap first tags (stage+1) ≤ parent₀ := Nat.le_add_right ..
+ have countFit : cap+2 ≤ layerBase cap first tags (stage+1) := by
+ rw [nextBase]
+ exact (Nat.le_mul_of_pos_right (cap+2) oldCount).trans (Nat.le_add_left ..)
+ exact (countFit.trans top).trans_lt (fits.parentBound.trans_le rowFits.le)
+ have layoutFits := (Nat.le_add_right .. : first ≤ rowEnd₀).trans_lt rowFits
+ obtain ⟨_,_,_,_,_,count,lanes,ports⟩ := TraversalPlan.layout_limits B X choice start positions blocks oldLevel nextLevel size
+ layoutFits (le_rfl : first ≤ first)
+ rw [childEq]
+ refine ⟨positive,before,?_,?_,widthFit,lanes,ports,count⟩
+ · change (region).histBase ≤ ((site).geometry+10).val
+ have cell : ((site).geometry+10).val = (region).histBase+hist+10 := by
+ simpa only [Nat.cast_ofNat] using geometry 10 (by decide)
+ rw [cell]; exact (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ · change (region).histBase ≤ ((site).geometry+11).val
+ have cell : ((site).geometry+11).val = (region).histBase+hist+11 := by
+ simpa only [Nat.cast_ofNat] using geometry 11 le_rfl
+ rw [cell]; exact (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+
+end PairSimulation.RefreshHook
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalAction.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalAction.lean
new file mode 100644
index 0000000000..e3cad47cc7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalAction.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalCanonical
+import OAI.Computability.VPVNP.PairRefreshResidentReads
+import OAI.Computability.VPVNP.PairRefreshResidentMapExact
+import OAI.Computability.VPVNP.PairSimulationFieldReadSafety
+
+/-!
+# The chronological refresh action and its upper scratch state
+
+The event list of a successful local visit depends on the actual node halves, the
+selected term, the published level headers and the four-word geometry reload.
+Its private scratch update acts on the incoming scratch independently of unrelated
+host registers or private memory below the DFS boundary.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe PairSimulation VertexImage NodeArguments NewSlots RefreshMapOperands NetworkKernel
+open MotifConversion MotifEntry MotifDemandPadding MotifSelector LocalHistory
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist bits g : ℕ}
+ (ties : Fin t ≃ Tie (2 ^ S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent)) (degree n rowEnd child parent : ℕ)
+
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hd" => And.right S.degree_bounds
+local notation "T" => plan B ties stride order
+local notation "Y" =>
+ dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice
+local notation "R" => TerminalLayout.privateRegions degree n rowEnd hist
+local notation "A" => LeafArena.Regions.arguments R
+local notation "hb" => LeafArena.Regions.histBase R
+local notation "dir" => hb + hist + 12 + 2 * n
+local notation "K" => MapCallWords.headCapacity (2 ^ S.portExponent) (2 ^ S.expanderExponent)
+local notation "demand" =>
+ blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) (Prod.fst v)
+local notation "copies" => repetitions B.refresh demand
+local notation "O" => sites (D := 2 ^ S.portExponent) X.baseIndex (bitWordFinEquiv g)
+
+/-- The selected physical fit conditions needed by the terminal private arena.
+All conditions hold or fail independently of the particular guessed old half. -/
+structure Room (hist bits : ℕ) : Prop where
+ childBound : child < rowEnd
+ parentBound : parent < rowEnd
+ oldDegree : 2 ^ S.portExponent ≤ degree
+ newDegree : 2 ^ (S.degreeExponent 0) ≤ degree
+ oldWidth : X.maxWireWidth ≤ n
+ newWidth : (Y).maxWireWidth ≤ n
+ copyBound : copies ≤ n
+ large : K + 12 ≤ n
+ five : 5 ≤ n
+ capacity : MapWorkspace.Capacity B.refresh bits n
+ (TerminalLayout.privateRegions degree n rowEnd hist).cacheBase
+ tableWidth : MapConstants.widthThreshold B.refresh ≤ bits
+
+variable (room : Room B X choice v degree n rowEnd child parent hist bits)
+ (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+ (m : Memory bits) (oldHead newHead : ℕ) (G : W bits)
+
+/-- Canonical successful traversal trace consisting of four geometry-reload ticks and the
+resident plan's selected refresh events. -/
+noncomputable def canonicalEvents : List (Event bits) :=
+ List.replicate 4 .tick ++ (T).successEvents X choice v m old new room.tableWidth
+ (operands (O v).val parent newHead hb G) (word oldHead)
+
+set_option maxHeartbeats 1200000 in
+-- Constructing the scratch update elaborates the size witnesses for both node frames.
+/-- Private scratch image after the selected refresh map executes with the bounded child and
+parent frames, copy buffers, and histogram. -/
+noncomputable def canonicalUpper {endAddr : ℕ}
+ (s : DFS.Scratch bits endAddr) : DFS.Scratch bits endAddr :=
+ (T).mapUpper X choice v A child parent old new hb n dir hb
+ (TraversalGeometry.argument_end degree n rowEnd hist X (oldSite X v) old child room.childBound
+ room.oldDegree room.oldWidth)
+ (TraversalGeometry.argument_end degree n rowEnd hist Y (promotedSites v) new parent
+ room.parentBound room.newDegree room.newWidth)
+ room.oldWidth room.newWidth (by omega) (by omega)
+ (TraversalGeometry.workspace_before_cache degree n rowEnd hist K copies room.large room.five
+ room.copyBound).2
+ room.capacity room.copyBound room.tableWidth endAddr s
+
+local notation "events" =>
+ canonicalEvents B ties stride order X choice v degree n rowEnd child parent room old new
+ m oldHead newHead G
+local notation "upper" =>
+ canonicalUpper B ties stride order X choice v degree n rowEnd child parent room old new
+
+/-- The traversal action combines the diagonal and map result with its canonical successful
+events and private scratch update. -/
+noncomputable def canonicalAction {endAddr : ℕ} (s : DFS.Scratch bits endAddr) :
+ Option (List (Event bits) × DFS.Scratch bits endAddr) :=
+ if (emitted B order X choice v old new).isSome then some (events, upper s) else none
+
+variable (U V : IncidenceDirectory bits) (start listHead : ℕ)
+
+local notation "Pl" =>
+ Allocation.plan X (S.degreeExponent 0) (2 ^ S.expanderExponent) t stride start
+local notation "pub" => operands (Fin.val (O v)) parent newHead hb G
+local notation "st" => word (bits := bits) oldHead
+local notation "I" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand I)
+
+set_option maxHeartbeats 1400000 in
+-- The trace bound instantiates the three dependent field-read families at the terminal.
+/-- All external reads of the exact event list avoid the scheduler's two control
+cells in the fitting terminal header. -/
+theorem canonical_worker_reads {fit :
+ Fintype.card X.Base * 2 ^ S.portExponent * 2 ^ g * 2 ^ S.portExponent ≤ 2 ^ bits}
+ (header : TraversalHeaders.Geometry (Fintype.card X.Base) g oldHead newHead start A U V m)
+ (row : DFS.Row m parent listHead [word child]) (lanes : 2 ^ g < 2 ^ bits)
+ (oldCols : U.ActualColumns X m) (newCols : V.ActualColumns Y m)
+ (terminal : W bits) (terminalFit : terminal.val + 31 < 2 ^ bits)
+ (oldBefore : oldHead + 60 < terminal.val) (newBefore : newHead + 59 < terminal.val)
+ (parentBefore : parent < terminal.val) (listBefore : listHead < terminal.val)
+ (area : (Pl).supply ≤ terminal.val)
+ (oldIn : U.actualIn.val + Fintype.card X.Base * 2 ^ (S.portExponent + g) * 2 ^ S.portExponent ≤
+ terminal.val)
+ (oldWidth : U.width.val + Fintype.card X.Base * 2 ^ (S.portExponent + g) * 2 ^ S.portExponent ≤
+ terminal.val)
+ (newIn : V.actualIn.val + Fintype.card (State.Base Y) * 2 ^ g * 2 ^ (S.degreeExponent 0) ≤
+ terminal.val)
+ (newWidth : V.width.val + Fintype.card (State.Base Y) * 2 ^ g * 2 ^ (S.degreeExponent 0) ≤
+ terminal.val)
+ (wide : 2 ^ S.portExponent < 2 ^ bits)
+ (enough : 2 + 2 ^ S.portExponent * 2 ^ S.expanderExponent ≤ stride) :
+ SourceTransport.Reads (TerminalLink.workerCell terminal) events := by
+ obtain ⟨dia, route, directory, fields⟩ :=
+ canonical_reads B ties stride order X choice v A U V m start parent child listHead oldHead
+ newHead hb G (fit := fit) header row lanes oldCols newCols terminal.val terminal.isLt.le
+ oldBefore newBefore parentBefore listBefore area oldIn oldWidth newIn newWidth wide enough
+ have allowed : SourceTransport.Reads (· < terminal.val)
+ ((T).successEvents X choice v m old new room.tableWidth pub st) := by
+ apply (T).successEvents_readsFrom X choice v m old new room.tableWidth pub st _ dia route
+ intro i
+ refine Fin.lastCases ?_ (fun j => ?_) i
+ · simpa only [MapArgumentWriter.recipes, Fin.snoc_last] using directory
+ · simpa only [MapArgumentWriter.recipes, Fin.snoc_castSucc] using fields (z, v.2) j
+ intro a value ha
+ rcases List.mem_append.mp ha with tick | cell
+ · cases List.eq_of_mem_replicate tick
+ · exact TerminalLink.workerCell_of_lt terminalFit (allowed a value cell)
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalBounds.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalBounds.lean
new file mode 100644
index 0000000000..667caf370e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalBounds.lean
@@ -0,0 +1,299 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalAction
+import OAI.Computability.VPVNP.PairVertexLevelBounds
+import OAI.Computability.VPVNP.CompressorBlockLevelFit
+import OAI.Computability.VPVNP.CompressorBlockShrinkPrefixFits
+import OAI.Computability.VPVNP.CompressorRefreshTraversalChild
+import OAI.Computability.VPVNP.PairShrinkCallCapacity
+import OAI.Computability.VPVNP.PairShrinkGeometryLimit
+
+/-!
+# Bounds for the selected degree-refresh traversal
+
+The old and new incidence heads use the actual row counts in the scheduled block
+layout. The packed table of terms and segment widths also ends in that allocation.
+The private map capacity uses the end of the selected DFS rows in the chronological
+directory. The threshold is uniform in the coefficient specialization and branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe PairSimulation NodeArguments NewSlots RefreshMapOperands DescriptorSpace
+open MotifConversion NetworkKernel LocalHistory CursorBounds CursorNetwork TraversalRows Filter
+open private refreshNext_width_bound from OAI.Computability.VPVNP.RefreshHistory
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+
+private theorem positions_formula {a g : ℕ} (Z : State a g) :
+ Fintype.card Z.Base * 2^g = Z.positions := by
+ simp only [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv _),Fintype.card_fin]
+
+private theorem block_column {a l bits start positions blocks : ℕ} (Z : State a l)
+ (level : Fin (BlockProgram.layout B start positions blocks).levels)
+ (size : Z.positions ≤ positions) (degree : 2^a ≤ slotDegree S) (c : Fin 6) :
+ let L := BlockProgram.layout B start positions blocks
+ let rows := Z.positions * 2^a
+ ((packedIncidence L bits level rows).column c).val + Fintype.card Z.Base * 2^l * 2^a ≤
+ endAddress L := by
+ intro L rows
+ rw [positions_formula]
+ have cap : rows ≤ slotCapacity L := Nat.mul_le_mul size degree
+ have before := ShrinkBranch.incidence_before L bits level rows (0 : Fin 6) cap c
+ exact before.trans ((Nat.le_add_right ..).trans
+ ((tableEnd_le_nextLevel L level (0 : Fin 6)).trans (levelStart_mono L level.isLt)))
+
+variable {g bits : ℕ} (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh)
+ (start positions blocks : ℕ)
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order (And.right S.degree_bounds) choice
+local notation "space₀" => BlockProgram.layout B start positions blocks
+variable (prev next : Fin (BlockProgram.layout B start positions blocks).levels)
+local notation "oldRows" => X.positions*2^S.portExponent
+local notation "newRows" => State.positions Y*2^(S.degreeExponent 0)
+local notation "U" => packedIncidence space₀ bits prev oldRows
+local notation "V" => packedIncidence space₀ bits next newRows
+local notation "s" => RefreshBlockPlan.shape B
+local notation "P" => Allocation.plan X (S.degreeExponent 0) (LevelRecipe.Shape.dH s) (LevelRecipe.Shape.ties s) (LevelRecipe.Shape.stride s) (arrayBase space₀ prev)
+
+set_option maxHeartbeats 1800000 in
+/-- Bounds used by the canonical probe proof, including both distinct incoming
+and width columns. Every endpoint follows from the actual old position count. -/
+theorem layout_limits (size : X.positions ≤ positions) {limit : ℕ}
+ (fit : endAddress space₀ < 2^bits) (below : endAddress space₀ ≤ limit) :
+ levelStart space₀ prev+60 < limit ∧ levelStart space₀ next+59 < limit ∧ (P).supply ≤ limit ∧
+ (∀ c : Fin 6, ((U).column c).val + Fintype.card X.Base*2^(S.portExponent+g)*2^S.portExponent ≤ limit) ∧
+ (∀ c : Fin 6, ((V).column c).val + Fintype.card (State.Base Y)*2^g*2^(S.degreeExponent 0) ≤ limit) ∧
+ Fintype.card X.Base*2^S.portExponent*2^g*2^S.portExponent ≤ 2^bits ∧
+ 2^g < 2^bits ∧ 2^S.portExponent < 2^bits := by
+ have stop := (BlockLevelFit.refresh (L := space₀) (w := bits) (g := g) B start positions blocks prev rfl X size fit).1.next
+ simp only [BlockLevelFit.tableStart,Nat.zero_mul,Nat.add_zero] at stop
+ have supply : (P).supply ≤ (P).stop :=
+ (((Nat.le_add_right ..).trans (Nat.le_add_right ..)).trans (Nat.le_add_right ..)).trans (Nat.le_add_right ..)
+ have header (i : Fin (space₀).levels) : levelStart space₀ i+60 < endAddress space₀ := by
+ have hlen : 60 < levelWords space₀ :=
+ (by decide : 60 < 66).trans_le ((Nat.le_add_right ..).trans (Nat.le_add_right ..))
+ have hnext : levelStart space₀ i + levelWords space₀ = levelStart space₀ (i.val+1) := by
+ simp only [levelStart,Nat.succ_mul,Nat.add_assoc]
+ exact ((Nat.add_lt_add_left hlen _).trans_eq hnext).trans_le (levelStart_mono space₀ i.isLt)
+ have oldDegree : 2^S.portExponent ≤ slotDegree S := le_max_left ..
+ have newDegree : 2^S.degreeExponent 0 ≤ slotDegree S :=
+ (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ 0)).trans
+ (le_max_right ..)
+ have newSize := (dyadicRefreshNext_positions X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2 choice).le.trans size
+ have cols (c : Fin 6) := block_column (bits := bits) (start := start) (positions := positions) (blocks := blocks) B X prev size oldDegree c
+ have count : Fintype.card X.Base*2^(S.portExponent+g)*2^S.portExponent < 2^bits :=
+ (Nat.le_add_left ..).trans_lt ((cols 0).trans_lt fit)
+ have count' := count
+ rw [pow_add,← Nat.mul_assoc] at count'
+ have pos : 0 < Fintype.card X.Base := Fintype.card_pos
+ have lanes : 2^g ≤ Fintype.card X.Base * 2^S.portExponent * 2^g :=
+ Nat.le_mul_of_pos_left _ (Nat.mul_pos pos (Nat.two_pow_pos _))
+ have left : 0 < Fintype.card X.Base * 2^S.portExponent * 2^g :=
+ Nat.mul_pos (Nat.mul_pos pos (Nat.two_pow_pos _)) (Nat.two_pow_pos _)
+ exact ⟨(header prev).trans_le below,(Nat.add_lt_add_left (by decide : 59 < 60) _).trans ((header next).trans_le below),
+ supply.trans (stop.trans ((levelStart_mono space₀ prev.isLt).trans below)),fun c => (cols c).trans below,
+ fun c => (block_column (bits := bits) (start := start) (positions := positions) (blocks := blocks) B Y next newSize newDegree c).trans below,count'.le,
+ (lanes.trans (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _))).trans_lt count',
+ (Nat.le_mul_of_pos_left _ left).trans_lt count'⟩
+
+variable {hist : ℕ} (order : B.Entry ≃ Fin hist)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (m : Memory bits)
+ (parent child listHead histBase : ℕ) (G : W bits)
+local notation "T" => plan B (RefreshBlockPlan.order B) (LevelRecipe.Shape.stride s) order
+local notation "pub" => operands (Fin.val (sites (D := 2^S.portExponent) X.baseIndex (bitWordFinEquiv g) v))
+ parent (levelStart space₀ next) histBase G
+local notation "st" => word (bits := bits) (levelStart space₀ prev)
+
+set_option maxHeartbeats 1800000 in
+/-- Physical header and singleton row reads suffice for the entire fixed
+expression family on a selected refresh stage of the chronological block. -/
+theorem layout_reads (size : X.positions ≤ positions) {limit : ℕ} (fit : endAddress space₀ < 2^bits)
+ (below : endAddress space₀ ≤ limit) (fits : limit ≤ 2^bits)
+ (header : TraversalHeaders.Geometry (Fintype.card X.Base) g (levelStart space₀ prev) (levelStart space₀ next)
+ (arrayBase space₀ prev) A U V m)
+ (row : DFS.Row m parent listHead [word child]) (hp : parent < limit) (hl : listHead < limit)
+ (old : (U).ActualColumns X m) (new : (V).ActualColumns Y m) :
+ let ok := Expr.ReadsFrom (· < limit) pub st m
+ (∀ i, ok ((T).diagonal i)) ∧ (∀ i, ok ((T).route i)) ∧ ok (T).directory ∧
+ ∀ idx j, ok ((T).family.fields idx j) := by
+ obtain ⟨prevHead,nextHead,area,oldCols,newCols,rows,lanes,ports⟩ :=
+ layout_limits B X choice start positions blocks prev next size fit below
+ exact canonical_reads B (RefreshBlockPlan.order B) (s).stride order X choice v A U V m (arrayBase space₀ prev)
+ parent child listHead (levelStart space₀ prev) (levelStart space₀ next) histBase G (fit := rows)
+ header row lanes old new limit fits prevHead nextHead hp hl area (oldCols 4) (oldCols 5)
+ (newCols 4) (newCols 5) ports le_rfl
+
+set_option maxHeartbeats 1800000 in
+/-- Every read of the actual local action, including the selected map call,
+avoids the terminal controller cells in the compiled block layout. -/
+theorem layout_worker_reads (degree n rowEnd : ℕ)
+ (room : Room B X choice v degree n rowEnd child parent hist bits)
+ (old : X.network.Half (oldSite X v)) (new : (Y).network.Half (promotedSites v))
+ (terminal : W bits) (terminalFit : terminal.val+31 < 2^bits)
+ (size : X.positions ≤ positions) (below : endAddress space₀ ≤ terminal.val)
+ (header : TraversalHeaders.Geometry (Fintype.card X.Base) g (levelStart space₀ prev) (levelStart space₀ next)
+ (arrayBase space₀ prev) (TerminalLayout.privateRegions degree n rowEnd hist).arguments U V m)
+ (row : DFS.Row m parent listHead [word child]) (hp : parent < terminal.val) (hl : listHead < terminal.val)
+ (oldCols : (U).ActualColumns X m) (newCols : (V).ActualColumns Y m) :
+ SourceTransport.Reads (TerminalLink.workerCell terminal)
+ (canonicalEvents B (RefreshBlockPlan.order B) (s).stride order X choice v degree n rowEnd child parent
+ room old new m (levelStart space₀ prev) (levelStart space₀ next) G) := by
+ obtain ⟨prevHead,nextHead,area,oldEnds,newEnds,rows,lanes,ports⟩ :=
+ layout_limits B X choice start positions blocks prev next size (below.trans_lt terminal.isLt) below
+ exact canonical_worker_reads B (RefreshBlockPlan.order B) (s).stride order X choice v degree n rowEnd child parent
+ room old new m (levelStart space₀ prev) (levelStart space₀ next) G U V (arrayBase space₀ prev) listHead (fit := rows)
+ header row lanes oldCols newCols terminal terminalFit prevHead nextHead hp hl area (oldEnds 4) (oldEnds 5)
+ (newEnds 4) (newEnds 5) ports le_rfl
+
+/-- Map capacity up to the cache of the actual chronological layout. The row
+count comes from the same selected execution as the graph and node operands. -/
+theorem eventually_selected_capacity (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {workspace : ℕ → ℕ} (bounded : PolynomiallyBounded workspace) (degree labels : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (split : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ let Z := pairInput S split hD
+ let count := blockCount (u.θ : ℝ) n
+ let space := BlockProgram.layout B (workspace n) (initialPositions b n) count
+ ∀ z : (B.execute f hf count hT Z).Choices,
+ let rows := words B.recordLimit (selectedLayers B f hf count hT Z z)
+ MapWorkspace.Capacity B.refresh (wordBits b n) n
+ (TerminalLayout.privateRegions degree n (endAddress space+rows) labels).cacheBase := by
+ let bound n := NativeFrame.histLimit degree b workspace n + labels + n^5
+ have hBound : PolynomiallyBounded bound :=
+ ((NativeFrame.histLimit_bounded degree b bounded).add (.const labels)).add (PolynomiallyBounded.id.pow 5)
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ filter_upwards [NativeFrame.eventually_selected_histBase B u (BlockProgram.allocationShape B) b hb bounded,
+ MapWorkspace.eventually_capacity (B := B.refresh) b hb' bound hBound] with n selected cap
+ intro base lanes split hD hT R _ f hf Z count space z rows
+ let full := cursorLayout (BlockProgram.allocationShape B) b S.steps u.θ (workspace n) n
+ have prior : endAddress space ≤ endAddress full := BlockProgram.allocation_end B _ _ count
+ have upper := selected split hD hT R f hf z degree labels
+ let actual := TerminalLayout.privateRegions degree n (endAddress space+rows) labels
+ have actualLe : actual.cacheBase ≤ bound n := by
+ refine Nat.add_le_add_right (Nat.add_le_add_right (le_trans ?_ upper) labels) _
+ exact Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.add_le_add_right prior rows)) n
+ exact ⟨cap.selectorBits,cap.demandBits,cap.payloadBits,actualLe.trans_lt cap.room,
+ fun a ha => cap.fields a (ha.trans actualLe)⟩
+
+/-- Every selected refresh stage fits its old and new half-wire widths and the
+motif repetition count at the same length threshold. -/
+theorem eventually_selected_sizes (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (split : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ let Z := pairInput S split hD
+ let count := blockCount (u.θ : ℝ) n
+ ∀ (z : (B.execute f hf count hT Z).Choices) {g : ℕ}
+ (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (record : List Bool),
+ RefreshPlacement.traversalLevel f hf X choice record ∈ executeLevels B f hf count hT Z z →
+ X.positions ≤ initialPositions b n ∧ X.maxWireWidth ≤ n ∧
+ (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1
+ B.refresh S.port_order S.degree_bounds.2 choice).maxWireWidth ≤ n ∧
+ ∀ p : X.Base × BitWord g, repetitions B.refresh
+ (blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) p) ≤ n := by
+ let K := refreshLengthConstant S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh
+ filter_upwards [ShrinkCallCapacity.eventually_levels B u b hb K] with n bounds
+ intro base lanes split hD hT R _ f hf Z count z g X choice record member
+ obtain ⟨pos,width⟩ := bounds split hD hT R f hf z (RefreshPlacement.traversalLevel f hf X choice record) member
+ change K * (X.maxWireWidth + 1) ≤ n at width
+ have kpos : 1 ≤ K := le_max_left ..
+ refine ⟨pos,((Nat.le_succ _).trans (Nat.le_mul_of_pos_left _ kpos)).trans width,?_,?_⟩
+ · apply Finset.sup_le
+ intro e _
+ exact (refreshNext_width_bound X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1
+ B.refresh S.port_order S.degree_bounds.2 (by linarith [S.portComparison_pos]) choice e).trans width
+ · intro p
+ apply le_trans (term_repetitions_le B.refresh _ (W := X.maxWireWidth) ?_) ((Nat.mul_le_mul ?_ (Nat.le_succ _)).trans width)
+ · intro e
+ unfold blockDemandWidths internalWidth
+ split <;> exact X.width_le_maxWireWidth _
+ · exact (le_max_left ..).trans (le_max_right ..)
+
+open TraversalRoles
+
+/-- A refresh uses the same ordinal in the preceding layer. Its parent header,
+unique child pointer and child header are all inside the actual row interval. -/
+theorem refresh_row_bounds {cap first stage : ℕ} (positive : 1 ≤ cap) (tags : List TaggedLayer)
+ (j : Fin tags.length) (hj : j.val = stage+1) (i : Fin tags[j].layer.count) :
+ let parent := address cap (layerBase cap first tags j.val) i.val
+ let child := address cap (layerBase cap first tags stage) i.val
+ let rowEnd := first + tagWords cap tags
+ child ≤ parent ∧ parent+2 < rowEnd := by
+ intro parent child rowEnd
+ have before := VertexLevelBounds.layerBase_mono cap first tags (by omega : stage ≤ j.val)
+ have after := VertexLevelBounds.layerBase_mono cap first tags j.isLt
+ have endEq : layerBase cap first tags tags.length = rowEnd := by simp [layerBase,rowEnd,tagWords]
+ rw [endEq,VertexLevelBounds.layerBase_succ cap first tags j] at after
+ have inside := Nat.mul_le_mul_left (cap+2) i.isLt
+ rw [Nat.mul_succ] at inside
+ exact ⟨Nat.add_le_add_right before _,by
+ change layerBase cap first tags j.val + (cap+2)*i.val + 2 < rowEnd
+ change layerBase cap first tags j.val + (cap+2)*tags[j].layer.count ≤ rowEnd at after
+ omega⟩
+
+/-- The complete private and physical bounds for the selected map role. The
+child and parent row addresses use the actual site ordinal in adjacent layers. -/
+theorem eventually_selected_room (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {workspace : ℕ → ℕ} (bounded : PolynomiallyBounded workspace) (hist : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (split : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ let Z := pairInput S split hD
+ let count := blockCount (u.θ : ℝ) n
+ let space := BlockProgram.layout B (workspace n) (initialPositions b n) count
+ ∀ (z : (B.execute f hf count hT Z).Choices) {g : ℕ}
+ (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (record : List Bool)
+ (stage : Fin (executeLevels B f hf count hT Z z).length),
+ (executeLevels B f hf count hT Z z)[stage] = RefreshPlacement.traversalLevel f hf X choice record →
+ let tags := selected B f hf count hT Z z
+ let first := endAddress space
+ let rowEnd := first + words B.recordLimit (selectedLayers B f hf count hT Z z)
+ ∀ (j : Fin tags.length) (_ : j.val = stage.val+1) (i : Fin tags[j].layer.count)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)),
+ let child := address B.recordLimit (layerBase B.recordLimit first tags stage.val) i.val
+ let parent := address B.recordLimit (layerBase B.recordLimit first tags j.val) i.val
+ X.positions ≤ initialPositions b n ∧ parent+2 < rowEnd ∧
+ Room B X choice v (slotDegree S) n rowEnd child parent hist (wordBits b n) := by
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ let K := MapCallWords.headCapacity (2^S.portExponent) (2^S.expanderExponent)
+ filter_upwards [eventually_selected_capacity B u b hb bounded (slotDegree S) hist,
+ eventually_selected_sizes B u b hb, MapConstants.eventually_width B.refresh b hb',
+ eventually_ge_atTop (K+12), eventually_ge_atTop 5] with n capacity sizes table large five
+ intro base lanes split hD hT R _ f hf Z count space z g X choice record stage step tags first rowEnd j hj i v child parent
+ have member : RefreshPlacement.traversalLevel f hf X choice record ∈ executeLevels B f hf count hT Z z := by
+ rw [← step]; exact List.getElem_mem stage.isLt
+ obtain ⟨pos,oldWidth,newWidth,copies⟩ := sizes split hD hT R f hf z X choice record member
+ have cap := capacity split hD hT R f hf z
+ have eqn : first+tagWords B.recordLimit tags = rowEnd := by
+ rw [tagWords,show tags.map TaggedLayer.layer = _ from selected_layers B f hf count hT Z z]
+ have ⟨childBefore,parentEnd⟩ := refresh_row_bounds (first := first) (le_max_left 1 _ : 1 ≤ B.recordLimit) tags j hj i
+ change child ≤ parent at childBefore
+ change parent+2 < first+tagWords B.recordLimit tags at parentEnd
+ rw [eqn] at parentEnd
+ exact ⟨pos,parentEnd,by
+ refine ⟨by omega,by omega,le_max_left ..,?_,oldWidth,newWidth,copies v.1,large,five,cap,table⟩
+ exact (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ 0)).trans
+ (le_max_right ..)⟩
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalCanonical.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalCanonical.lean
new file mode 100644
index 0000000000..e8418e845c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalCanonical.lean
@@ -0,0 +1,175 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalMapBody
+import OAI.Computability.VPVNP.CompressorRefreshTraversalRecipeReads
+
+/-!
+# Configuration-independent operands of the refresh traversal
+
+The parent descriptor, promoted-site ordinal and level heads survive the child scan.
+Reloading the histogram fixes both remaining temporary words. Thus the complete
+external event sequence of the diagonal and selected map is evaluated on the same
+operand bank for every initial configuration in the packet domain.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe PairSimulation VertexImage NodeArguments NewSlots RefreshMapOperands NetworkKernel
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist : ℕ}
+ (ties : Fin t ≃ Tie (2 ^ S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+
+local notation "T" => plan B ties stride order
+
+/-- Public words for the live refresh body, including the site, parent node, new-level header,
+histogram-pointer cell, and histogram base. -/
+def operands {bits : ℕ} (site parent newHead histBase : ℕ) (G : W bits) : Fin 5 → W bits :=
+ ![word site, word parent, word newHead, G + 11, word histBase]
+
+variable {pcs regs bits g : ℕ} (loc : Fin (body B ties stride order).count → Fin pcs)
+ (dfs : Fin 9 ↪ Fin regs) (saved : Saved ↪ Fin regs)
+ (bank : Fin (body B ties stride order).privateRegs ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11)
+local notation "left" =>
+ Segment.leftPC TraversalGeometry.reload (RefreshResidentImage.Plan.segment T) loc
+local notation "right" =>
+ Segment.rightPC TraversalGeometry.reload (RefreshResidentImage.Plan.segment T) loc
+local notation "commonBank" => Function.Embedding.trans (locatorBank B ties stride order) bank
+
+private theorem word_val {w : ℕ} {x : W w} {n : ℕ} (h : x.val = n) : x = word n :=
+ Fin.ext (h.trans (Nat.mod_eq_of_lt (h ▸ x.isLt)).symm)
+
+/-- The four native instructions establish the canonical five public words and state. -/
+theorem enter_canonical
+ (rows : ∀ j, M.code (loc j) =
+ ((body B ties stride order).row loc dfs saved bank done j).resize bits)
+ (c : Config bits pcs regs) (entry : c.pc = left TraversalGeometry.reload.entry)
+ {site parent oldHead newHead histBase endAddr : ℕ} {G offset : W bits}
+ (endWord : c.reg (dfs 6) = (endAddr : W bits))
+ (resident : ResidentGeometry (DFS.scratch endAddr c.privateMem) G offset (word histBase))
+ (oldWord : (c.reg (commonBank 11)).val = oldHead)
+ (newWord : (c.reg (commonBank 4)).val = newHead)
+ (siteWord : (c.reg (commonBank 7)).val = site)
+ (parentWord : (c.reg (commonBank 0)).val = parent) :
+ ∃ mid, PrimedCounter.GuessWord.Prefix M c (List.replicate 4 .tick) mid ∧
+ mid.pc = (T).diagSetup (right ∘ (T).locations) 0 ∧
+ mid.privateMem = c.privateMem ∧ mid.persistent = c.persistent ∧
+ (∀ j, j ≠ commonBank 9 → j ≠ commonBank 10 → mid.reg j = c.reg j) ∧
+ (fun i : Fin 5 => mid.reg ((T).inputs dfs saved commonBank i.castSucc)) =
+ operands site parent newHead histBase G ∧
+ mid.reg ((T).inputs dfs saved commonBank (Fin.last 5)) = word oldHead := by
+ have linked := (body_links B ties stride order loc dfs saved bank done M rows).1
+ obtain ⟨mid, pre, ep, histogram, cell, frame, priv, per⟩ :=
+ TraversalGeometry.reload_native_address M left dfs saved
+ commonBank (right (T).segment.entry) linked c entry endWord resident
+ have keep (i : Fin 14) (ha : i ≠ 9)
+ (hb : i ≠ 10) : mid.reg (commonBank i) = c.reg (commonBank i) :=
+ frame _ ((commonBank).injective.ne ha) ((commonBank).injective.ne hb)
+ refine ⟨mid, pre, ?_, priv, per, frame, ?_, (keep 11 (by decide)
+ (by decide)).trans (word_val oldWord)⟩
+ · rw [ep]
+ change right ((T).diagSetup (T).locations 0) = (T).diagSetup (right ∘ (T).locations) 0
+ by_cases h : 0 < (RegisterSetup.lines (T).diagonal).length
+ · refine (congrArg right (dite_eq_left h)).trans ?_
+ rw [RefreshResidentImage.Plan.diagSetup, dite_eq_left h]; rfl
+ · refine (congrArg right (dite_eq_right h)).trans ?_
+ rw [RefreshResidentImage.Plan.diagSetup, dite_eq_right h]; rfl
+ · funext i; fin_cases i
+ · exact (keep 7 (by decide) (by decide)).trans (word_val siteWord)
+ · exact (keep 0 (by decide) (by decide)).trans (word_val parentWord)
+ · exact (keep 4 (by decide) (by decide)).trans (word_val newWord)
+ · exact cell
+ · exact histogram
+
+variable (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent)) (A : Arena) (U V : IncidenceDirectory bits)
+ (m : Memory bits)
+ (start parent child listHead oldHead newHead histBase : ℕ) (G : W bits)
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hd" => And.right S.degree_bounds
+local notation "supply" =>
+ blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph
+ (Nat.two_pow_pos _) hc B.refresh choice
+local notation "Y" =>
+ dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice
+local notation "O" => sites (D := 2 ^ S.portExponent) X.baseIndex (bitWordFinEquiv g)
+local notation "Pl" =>
+ Allocation.plan X (S.degreeExponent 0) (2 ^ S.expanderExponent) t stride start
+local notation "pub" => operands (Fin.val (O v)) parent newHead histBase G
+local notation "state" => word (bits := bits) oldHead
+
+/-- Typed data for the selected local role on its canonical operand bank. -/
+theorem canonical_data {fit :
+ Fintype.card X.Base * 2 ^ S.portExponent * 2 ^ g * 2 ^ S.portExponent ≤ 2 ^ bits}
+ (header : TraversalHeaders.Geometry (Fintype.card X.Base) g oldHead newHead start A U V m)
+ (row : DFS.Row m parent listHead [word child]) (lanes : 2 ^ g < 2 ^ bits) :
+ OperandInputs.Describes (T).input pub state m X v S.graph.toSlotGraph S.port_order hd supply A
+ child parent U V
+ ((Pl).scratch bits) (word (Pl).demand) (word (Pl).term) ∧
+ (T).directory.eval pub state m = word (histBase + hist + 12 + 2 * A.start) ∧
+ (T).histogram.eval pub state m = word histBase := by
+ let C : LevelRecipe.Context bits := ⟨pub, state, m⟩
+ have siteRoom := (Nat.le_mul_of_pos_right (Fintype.card X.Base * 2 ^ S.portExponent * 2 ^ g)
+ (Nat.two_pow_pos S.portExponent)).trans fit
+ have oldFit : C.state.val = oldHead := Nat.mod_eq_of_lt (by have := header.oldRoom; omega)
+ have newFit : (C.pub 2).val = newHead := Nat.mod_eq_of_lt (by have := header.newRoom; omega)
+ have siteFit : (C.pub 0).val = (O v).val := Nat.mod_eq_of_lt ((O v).isLt.trans_le siteRoom)
+ have parentFit : (C.pub 1).val = parent := Nat.mod_eq_of_lt (by have := row.1; omega)
+ have args := TraversalHeaders.describes (shape B t stride) X v S.graph.toSlotGraph S.port_order hd
+ supply A U V C
+ header oldFit newFit siteFit parentFit row lanes
+ have heads := TraversalGeometry.heads_eval hist A.start histBase C.pub C.state m rfl
+ args.childRep.arena
+ exact ⟨args, heads.2, heads.1⟩
+
+/-- All physical expression probes of a selected refresh stay below the terminal
+header if its two level regions and its placed node row do. -/
+theorem canonical_reads {fit :
+ Fintype.card X.Base * 2 ^ S.portExponent * 2 ^ g * 2 ^ S.portExponent ≤ 2 ^ bits}
+ (header : TraversalHeaders.Geometry (Fintype.card X.Base) g oldHead newHead start A U V m)
+ (row : DFS.Row m parent listHead [word child]) (lanes : 2 ^ g < 2 ^ bits)
+ (old : U.ActualColumns X m) (new : V.ActualColumns Y m) (limit : ℕ) (fits : limit ≤ 2 ^ bits)
+ (oldBefore : oldHead + 60 < limit) (newBefore : newHead + 59 < limit)
+ (parentBefore : parent < limit)
+ (listBefore : listHead < limit) (area : (Pl).supply ≤ limit)
+ (oldIn : U.actualIn.val + Fintype.card X.Base * 2 ^ (S.portExponent + g) * 2 ^ S.portExponent ≤
+ limit)
+ (oldWidth : U.width.val + Fintype.card X.Base * 2 ^ (S.portExponent + g) * 2 ^ S.portExponent ≤
+ limit)
+ (newIn : V.actualIn.val + Fintype.card (State.Base Y) * 2 ^ g * 2 ^ (S.degreeExponent 0) ≤
+ limit)
+ (newWidth : V.width.val + Fintype.card (State.Base Y) * 2 ^ g * 2 ^ (S.degreeExponent 0) ≤
+ limit)
+ (wide : 2 ^ S.portExponent < 2 ^ bits)
+ (enough : 2 + 2 ^ S.portExponent * 2 ^ S.expanderExponent ≤ stride) :
+ let ok := Expr.ReadsFrom (· < limit) pub state m
+ (∀ i, ok ((T).diagonal i)) ∧ (∀ i, ok ((T).route i)) ∧ ok (T).directory ∧
+ ∀ idx j, ok ((T).family.fields idx j) := by
+ intro ok
+ have oldFit : (state).val = oldHead := Nat.mod_eq_of_lt (by omega)
+ have newFit : (pub 2).val = newHead := Nat.mod_eq_of_lt (by omega)
+ have parentFit : (pub 1).val = parent := Nat.mod_eq_of_lt (parentBefore.trans_le fits)
+ have heads := TraversalHeaders.input_reads pub state m limit (shape B t stride) oldFit newFit
+ parentFit row
+ oldBefore newBefore parentBefore listBefore
+ have dir : ok (T).directory := ⟨⟨⟨trivial, trivial⟩, trivial⟩, trivial, heads.child.arena⟩
+ have args := (canonical_data B ties stride order X choice v A U V m start parent child listHead
+ oldHead newHead histBase G
+ (fit := fit) header row lanes).1
+ obtain ⟨dia, route, field⟩ :=
+ TraversalRecipeReads.fields B X choice v A child parent U V ties start stride limit pub state
+ m (T).input (fit := fit) (T).directory (T).histogram args heads old new oldIn oldWidth
+ newIn newWidth area fits wide enough dir trivial
+ exact ⟨dia, route, dir, fun idx j => field _⟩
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalExact.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalExact.lean
new file mode 100644
index 0000000000..90d679b375
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalExact.lean
@@ -0,0 +1,211 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalAction
+import OAI.Computability.VPVNP.PairRefreshResidentExact
+
+/-!
+# Exact execution of the chronological terminal refresh action
+
+The accepted action fixes both the trace and the entire upper scratch update. A failed
+diagonal or local map forces rejection for every continuation and every unused tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe PairSimulation VertexImage NodeArguments NewSlots RefreshMapOperands NetworkKernel
+open MotifConversion MotifEntry MotifDemandPadding MotifSelector LocalHistory
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist bits g : ℕ}
+ (ties : Fin t ≃ Tie (2 ^ S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent)) (degree n rowEnd child parent : ℕ)
+
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hd" => And.right S.degree_bounds
+local notation "T" => plan B ties stride order
+local notation "Y" =>
+ dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice
+local notation "R" => TerminalLayout.privateRegions degree n rowEnd hist
+local notation "A" => LeafArena.Regions.arguments R
+local notation "hb" => LeafArena.Regions.histBase R
+local notation "dir" => hb + hist + 12 + 2 * n
+local notation "K" => MapCallWords.headCapacity (2 ^ S.portExponent) (2 ^ S.expanderExponent)
+local notation "demand" =>
+ blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) (Prod.fst v)
+local notation "copies" => repetitions B.refresh demand
+local notation "O" => sites (D := 2 ^ S.portExponent) X.baseIndex (bitWordFinEquiv g)
+
+variable (room : Room B X choice v degree n rowEnd child parent hist bits)
+ (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+ (m : Memory bits) (oldHead newHead : ℕ) (G : W bits)
+
+local notation "events" =>
+ canonicalEvents B ties stride order X choice v degree n rowEnd child parent room old new
+ m oldHead newHead G
+local notation "upper" =>
+ canonicalUpper B ties stride order X choice v degree n rowEnd child parent room old new
+
+variable (U V : IncidenceDirectory bits) (start listHead : ℕ)
+
+local notation "Pl" =>
+ Allocation.plan X (S.degreeExponent 0) (2 ^ S.expanderExponent) t stride start
+local notation "pub" => operands (Fin.val (O v)) parent newHead hb G
+local notation "st" => word (bits := bits) oldHead
+local notation "I" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand I)
+
+variable {pcs regs : ℕ} (loc : Fin (body B ties stride order).count → Fin pcs)
+ (dfs : Fin 9 ↪ Fin regs) (saved : Saved ↪ Fin regs)
+ (bank : Fin (body B ties stride order).privateRegs ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11)
+
+local notation "left" =>
+ Segment.leftPC TraversalGeometry.reload (RefreshResidentImage.Plan.segment T) loc
+local notation "right" =>
+ Segment.rightPC TraversalGeometry.reload (RefreshResidentImage.Plan.segment T) loc
+local notation "commonBank" => Function.Embedding.trans (locatorBank B ties stride order) bank
+local notation "own" => Function.Embedding.trans (Function.Embedding.trans Function.Embedding.inr
+ (Equiv.toEmbedding (RefreshResidentImage.Plan.registers T))) bank
+local notation "ws" => groupedWidths (bitWordFinEquiv _) (splitWidths X)
+local notation "perm" => oldPortMatching (splitSlots X) (bitWordFinEquiv _)
+local notation "wo" => ws (v, Prod.snd v)
+local notation "wi" => ws (Equiv.symm perm (v, Prod.snd v))
+local notation "supply" =>
+ blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph
+ (Nat.two_pow_pos _) hc B.refresh choice
+local notation "dia" => portDiagonal perm ws (Prod.fst v) (Prod.snd v) (oldHalf X v old)
+ (segments X v S.graph.toSlotGraph S.port_order hd supply new)
+local notation "named" => Option.map (List.map (RefreshResidentImage.Plan.ordinal T))
+ (Prod.fst (runEntry B.refresh (fun _ => zero_lt_one) (EntryInput.demand I)
+ (EntryInput.payload I) (Prod.snd v)
+ (demandBits tieSource tieTarget (Prod.snd v) (EntryInput.demandBits I))
+ (mapHalf S.portSupply (fun _ => inputBits) (EntryInput.supplyBits I))))
+
+set_option maxHeartbeats 2500000 in
+-- The exact trace specializes both native branches to the canonical dependent scratch update.
+theorem canonical_body {fit :
+ Fintype.card X.Base * 2 ^ S.portExponent * 2 ^ g * 2 ^ S.portExponent ≤ 2 ^ bits}
+ (rows : ∀ j, M.code (loc j) =
+ ((body B ties stride order).row loc dfs saved bank done j).resize bits)
+ (apartD : ∀ i j, bank i ≠ dfs j) (apartS : ∀ i j, bank i ≠ saved j)
+ (c : Config bits pcs regs) (entry : c.pc = left TraversalGeometry.reload.entry)
+ {endAddr : ℕ} {offset : W bits} (endWord : c.reg (dfs 6) = (endAddr : W bits))
+ (resident : ResidentGeometry (DFS.scratch endAddr c.privateMem) G offset (word hb))
+ (oldWord : (c.reg (commonBank 11)).val = oldHead)
+ (newWord : (c.reg (commonBank 4)).val = newHead)
+ (siteWord : (c.reg (commonBank 7)).val = (O v).val)
+ (parentWord : (c.reg (commonBank 0)).val = parent)
+ (header : TraversalHeaders.Geometry (Fintype.card X.Base) g oldHead newHead start A U V m)
+ (row : DFS.Row m parent listHead [word child]) (lanes : 2 ^ g < 2 ^ bits)
+ (stored : Build.Stored X S.graph
+ (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m)
+ (oldCols : U.ActualColumns X m) (newCols : V.ActualColumns Y m)
+ (oldData : NodeFields A child X (oldSite X v) old c.privateMem)
+ (newData : NodeFields A parent Y (promotedSites v) new c.privateMem)
+ (wide : 2 ^ S.portExponent < 2 ^ bits) (s : DFS.Scratch bits endAddr)
+ (incoming : DFS.scratch endAddr c.privateMem = s) :
+ let names := emitted B order X choice v old new
+ match canonicalAction B ties stride order X choice v degree n rowEnd child parent room old new m
+ oldHead newHead G s with
+ | none => ∀ bs, ¬ DFS.Returns M c m bs
+ | some (es, updated) =>
+ ∃ out, ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ budget B ties stride order * (wo + wi + copies + 1) ∧
+ countProbes es ≤ budget B ties stride order ∧ choiceBits es = [] ∧ out.pc = done ∧
+ out.persistent = c.persistent ∧ (∀ j, (∀ i, j ≠ bank i) → out.reg j = c.reg j) ∧
+ (∀ q : W bits, q.val < dir →
+ (∀ l : Fin hist, q ≠ word (hb + l.val)) → out.privateMem q = c.privateMem q) ∧
+ (∀ l : Fin hist, out.privateMem (word (hb + l.val)) = c.privateMem (word (hb + l.val)) +
+ ((names.getD []).count l : W bits)) ∧ DFS.scratch endAddr out.privateMem = updated := by
+ dsimp only
+ unfold canonicalAction
+ by_cases good : (emitted B order X choice v old new).isSome = true
+ · rw [ite_eq_left good]
+ have diagonal : dia = (1 : ℤ) := by
+ by_contra bad
+ simp only [emitted, ite_eq_right bad, Option.isSome_none, Bool.false_eq_true] at good
+ have names : (named).isSome = true := by
+ simp only [emitted, ite_eq_left diagonal] at good
+ exact good
+ obtain ⟨mid, pre, ep, priv, per, frame, pubEq, stEq⟩ :=
+ enter_canonical B ties stride order loc dfs saved bank done M
+ rows c entry endWord resident oldWord newWord siteWord parentWord
+ obtain ⟨args, hdir, hhist⟩ :=
+ canonical_data B ties stride order X choice v A U V m start parent child listHead
+ oldHead newHead hb G (fit := fit) header row lanes
+ have first : ChildScan.Prefix M m c mid [] (List.replicate 4 .tick) := fun fuel bs =>
+ pre.execute fuel m bs
+ have banks : RefreshResidentImage.Plan.Banks T dfs saved commonBank own := by
+ refine ⟨fun _ j => apartD _ j, fun _ j => apartS _ j, ?_⟩
+ intro a b eq
+ have h : (Sum.inr a : Fin 14 ⊕ (T).Local) = Sum.inl b :=
+ (T).registers.injective (bank.injective eq)
+ contradiction
+ have installed := (body_links B ties stride order loc dfs saved bank done M rows).2
+ have oldEnd := TraversalGeometry.argument_end degree n rowEnd hist X (oldSite X v) old child
+ room.childBound room.oldDegree room.oldWidth
+ have newEnd := TraversalGeometry.argument_end degree n rowEnd hist Y (promotedSites v) new
+ parent room.parentBound room.newDegree room.newWidth
+ have space := TraversalGeometry.workspace_before_cache degree n rowEnd hist K copies room.large
+ room.five room.copyBound
+ have nfit : n < 2 ^ bits := by
+ apply Nat.lt_of_le_of_lt _ room.capacity.room
+ change n ≤ n + rowEnd * (2 * degree * n + 1) + hist + n ^ 5
+ omega
+ have wf (e) : ws e < 2 ^ bits := ((X.width_le_maxWireWidth _).trans room.oldWidth).trans_lt nfit
+ obtain ⟨out, run, len, reads, tape, exit, per', keep, mem, hits, scratch⟩ :=
+ (T).native_success_exact (right ∘ (T).locations) dfs saved commonBank own done M installed
+ X choice v A child parent U V start m old new mid ep banks (pubEq.symm ▸ stEq.symm ▸ args)
+ stored oldCols newCols (priv ▸ oldData) (priv ▸ newData) hb n dir hb
+ (pubEq.symm ▸ stEq.symm ▸ hdir) (pubEq.symm ▸ stEq.symm ▸ hhist) oldEnd newEnd
+ room.oldWidth room.newWidth (by omega) (by omega) space.2 room.capacity room.copyBound wide
+ (wf _) (wf _) room.tableWidth endAddr s (priv ▸ incoming) diagonal names
+ rw [pubEq, stEq] at run len reads tape
+ obtain ⟨readBound, workBound⟩ := (T).uniform.choose_spec z v.2 wo wi copies
+ refine ⟨out, first.trans run, ?_, ?_, ?_, exit, per'.trans per,
+ fun j hj => (keep j (fun _ => hj _)).trans (frame j (hj _) (hj _)),
+ fun q hq hn => (mem q hq hn).trans (congrFun priv q), ?_, scratch⟩
+ · change (List.replicate 4 (.tick : Event bits) ++ _).length ≤
+ ((T).uniform.choose + 4) * (wo + wi + copies + 1)
+ rw [List.length_append, List.length_replicate, Nat.add_mul]
+ have h := len.trans workBound
+ have four : 4 ≤ 4 * (wo + wi + copies + 1) := Nat.le_mul_of_pos_right _ (by omega)
+ omega
+ · change countProbes (List.replicate 4 (.tick : Event bits) ++ _) ≤ (T).uniform.choose + 4
+ rw [countProbes_append, reads]
+ change 0 + _ ≤ _
+ omega
+ · change choiceBits (List.replicate 4 (.tick : Event bits) ++ _) = []
+ rw [PrimedInputRAM.Flow.choiceBits_append, tape]; rfl
+ · intro l
+ rw [hits, priv, emitted, ite_eq_left diagonal]
+ rfl
+ · rw [ite_eq_right good]
+ obtain ⟨out, es, path, _, _, _, branch, _⟩ :=
+ map_body B ties stride order loc dfs saved bank done M X choice v degree n rowEnd U V m
+ start parent child listHead oldHead newHead old new rows apartD apartS c entry endWord
+ resident oldWord newWord siteWord parentWord header row lanes stored oldCols newCols oldData
+ newData room.childBound room.parentBound room.oldDegree room.newDegree room.oldWidth
+ room.newWidth room.copyBound room.large room.five room.capacity wide room.tableWidth
+ rw [ite_eq_right good] at branch
+ have stop : M.program.step out = .reject := by
+ change (M.code out.pc).run M.publicData out = _
+ rw [branch]; rfl
+ intro bs returned
+ obtain ⟨fuel, rep, ran⟩ := (path.returns bs).mp returned
+ cases fuel <;> simp only [execute, stop, reduceCtorEq] at ran
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalFrames.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalFrames.lean
new file mode 100644
index 0000000000..bdc4deae34
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalFrames.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalAction
+
+/-!
+# Private geometry and cache through the refresh map
+
+At the terminal layout's actual geometry address, the pointer cell and both dispatch
+words survive the canonical upper scratch update. The scalar cache lies after the
+complete map workspace and all its cells are preserved as well.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe PairSimulation VertexImage NodeArguments NewSlots RefreshMapOperands NetworkKernel
+open MotifConversion MotifEntry MotifDemandPadding MotifSelector LocalHistory
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist bits g : ℕ}
+ (ties : Fin t ≃ Tie (2 ^ S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent)) (degree n rowEnd child parent : ℕ)
+
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hd" => And.right S.degree_bounds
+local notation "T" => plan B ties stride order
+local notation "Y" =>
+ dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice
+local notation "R" => TerminalLayout.privateRegions degree n rowEnd hist
+local notation "A" => LeafArena.Regions.arguments R
+local notation "hb" => LeafArena.Regions.histBase R
+local notation "dir" => hb + hist + 12 + 2 * n
+local notation "K" => MapCallWords.headCapacity (2 ^ S.portExponent) (2 ^ S.expanderExponent)
+local notation "demand" =>
+ blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) (Prod.fst v)
+local notation "copies" => repetitions B.refresh demand
+local notation "O" => sites (D := 2 ^ S.portExponent) X.baseIndex (bitWordFinEquiv g)
+
+variable (room : Room B X choice v degree n rowEnd child parent hist bits)
+ (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+ (m : Memory bits) (oldHead newHead : ℕ) (G : W bits)
+
+local notation "out" =>
+ canonicalUpper B ties stride order X choice v degree n rowEnd child parent room old new
+
+set_option maxHeartbeats 1600000 in
+-- Specializing the frame theorem reduces the layout-dependent map and histogram addresses.
+theorem upper_frame {endAddr : ℕ} (s : DFS.Scratch bits endAddr) (a : W bits) (ha : endAddr ≤ a.val)
+ (far : a.val < dir ∨ (R).cacheBase ≤ a.val) (apart : ∀ l : Fin hist, a ≠ word (hb + l.val)) :
+ out s ⟨a, ha⟩ = s ⟨a, ha⟩ := by
+ unfold canonicalUpper
+ apply RefreshResidentImage.Plan.mapUpper_frame <;> assumption
+
+/-- Every scalar cache word lies above every address written by this visit. -/
+theorem cache_preserved {endAddr : ℕ} (s : DFS.Scratch bits endAddr) (a : W bits)
+ (ha : endAddr ≤ a.val)
+ (far : (R).cacheBase ≤ a.val) : out s ⟨a, ha⟩ = s ⟨a, ha⟩ := by
+ apply upper_frame B ties stride order X choice v degree n rowEnd child parent room old new s a ha
+ (Or.inr far)
+ intro l eq
+ have below : (word (bits := bits) (hb + l.val)).val < (R).cacheBase := by
+ apply (Nat.mod_le ..).trans_lt
+ change hb + l.val < hb + hist + n ^ 5
+ have := l.isLt; omega
+ rw [← eq] at below; omega
+
+/-- The actual geometry pointer, role offset and histogram base are unchanged. -/
+theorem geometry_preserved (s : DFS.Scratch bits n) (role : W bits)
+ (resident : ResidentGeometry s (word (hb + hist)) role (word hb)) :
+ ResidentGeometry (out s) (word (hb + hist)) role (word hb) := by
+ let geometry : W bits := word (hb + hist)
+ have space := (TraversalGeometry.workspace_before_cache degree n rowEnd hist K copies room.large
+ room.five room.copyBound).1
+ have fits : hb + hist + 12 < 2 ^ bits := by
+ have last := (TraversalGeometry.workspace_before_cache degree n rowEnd hist K copies room.large
+ room.five room.copyBound).2
+ have hi := room.capacity.room
+ omega
+ have hn : n < hb := by
+ have pos : 0 < rowEnd := Nat.zero_lt_of_lt room.childBound
+ change n < n + rowEnd * (2 * degree * n + 1)
+ exact Nat.lt_add_of_pos_right (Nat.mul_pos pos (Nat.succ_pos _))
+ have address (j : ℕ) (hj : j < 12) : (geometry + word j).val = hb + hist + j := by
+ change ((↑(hb + hist) : W bits) + (↑j : W bits)).val = _
+ rw [← Nat.cast_add]
+ exact Nat.mod_eq_of_lt (by omega)
+ have keep (a : W bits) (ha : n ≤ a.val) (before : a.val < dir)
+ (away : a.val < hb ∨ hb + hist ≤ a.val) :
+ rawScratch (out s) a = rawScratch s a := by
+ simp only [rawScratch, dite_eq_left ha]
+ apply upper_frame B ties stride order X choice v degree n rowEnd child parent room old new s a
+ ha (Or.inl before)
+ intro l eq
+ have hl : (word (bits := bits) (hb + l.val)).val = hb + l.val := Nat.mod_eq_of_lt
+ (by have := l.isLt; omega)
+ have eqv : a.val = hb + l.val := (congrArg Fin.val eq).trans hl
+ have := l.isLt; omega
+ have nptr : (word (bits := bits) n).val = n := Nat.mod_eq_of_lt resident.endFit
+ have gr (j : ℕ) (hj : j < 12) :
+ rawScratch (out s) (geometry + word j) = rawScratch s (geometry + word j) := by
+ have pos := address j hj
+ apply keep <;> omega
+ exact ⟨resident.endFit, resident.roleAbove, resident.histAbove,
+ (keep (word n) nptr.ge (by omega) (Or.inl (nptr.trans_lt hn))).trans resident.pointer,
+ (gr 10 (by decide)).trans resident.role, (gr 11 (by decide)).trans resident.histogram⟩
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalHistogram.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalHistogram.lean
new file mode 100644
index 0000000000..0d889f30c9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalHistogram.lean
@@ -0,0 +1,171 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalAction
+
+/-!
+# Histogram of a successful terminal refresh
+
+A successful refresh changes each private histogram cell by the number of
+occurrences of its parameter in the emitted list. The statement applies to
+arbitrary incoming DFS scratch, including the counters accumulated by earlier visits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe OperandInputs PairSimulation NodeArguments MotifConversion NewSlots RefreshMapOperands
+open MotifEntry MotifDemandPadding MotifSelector LocalHistory
+open scoped Fin.CommRing
+
+variable {bits g t hist shared : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k}
+ {B : S.Templates} (T : Plan B t hist shared)
+ (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent)) (A : Arena) (child parent : ℕ)
+
+local notation "D" => 2 ^ S.portExponent
+local notation "H" => 2 ^ S.expanderExponent
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order
+ (And.right S.degree_bounds) choice
+
+variable (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order
+ S.degree_bounds.2 choice).network.Half (promotedSites v))
+
+local notation "I" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand I)
+local notation "L" => MapInline.layout B.refresh z (Prod.snd v)
+local notation "u" => repetitions B.refresh (EntryInput.demand I)
+local notation "d" => demandBits tieSource tieTarget (Prod.snd v) (EntryInput.demandBits I)
+local notation "x" => mapHalf S.portSupply (fun _ => inputBits) (EntryInput.supplyBits I)
+local notation "entry" => runEntry B.refresh (fun _ => zero_lt_one) (EntryInput.demand I)
+ (EntryInput.payload I) (Prod.snd v) d x
+local notation "names" => Option.map (List.map (Plan.ordinal T)) (Prod.fst entry)
+
+set_option maxHeartbeats 1800000 in
+-- The label array and the row evaluator use the same dependent field buffers.
+theorem mapUpper_histogram {n limit : ℕ} (top maxWidth directory histBase : ℕ)
+ (oldEnd : A.base child + (packed X (oldSite X v) old).length ≤ top)
+ (newEnd : A.base parent + (packed Y (promotedSites v) new).length ≤ top)
+ (oldWidth : X.maxWireWidth ≤ maxWidth) (newWidth : (Y).maxWireWidth ≤ maxWidth)
+ (inputsEnd : top + 2 * maxWidth ≤ directory) (histEnd : histBase + hist ≤ directory)
+ (workEnd : directory + MapCallWords.headCapacity D H + 2 * u ≤ limit)
+ (capacity : MapWorkspace.Capacity B.refresh bits n limit) (copyBound : u ≤ n)
+ (tableWidth : MapConstants.widthThreshold B.refresh ≤ bits)
+ {endAddr : ℕ} (saved : DFS.Scratch bits endAddr) (good : (names).isSome = true)
+ (l : Fin hist) (above : endAddr ≤ (word (bits := bits) (histBase + l.val)).val) :
+ T.mapUpper X choice v A child parent old new top maxWidth directory histBase
+ oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd capacity copyBound
+ tableWidth endAddr saved ⟨word (histBase + l.val), above⟩ =
+ saved ⟨word (histBase + l.val), above⟩ + (((names).getD []).count l : W bits) := by
+ let R := MapCallWords.regions B X choice v A child parent old new directory histBase
+ let loc := (L).corePC (L).locations
+ let ord := MapCallWords.regions_ordered B X choice v A child parent old new z (L).core loc
+ top maxWidth directory histBase limit oldEnd newEnd oldWidth newWidth inputsEnd histEnd workEnd
+ let Wk := MapWorkspace.workspace (MapInline.callProgram L) R d x capacity copyBound ord
+ let mem : PrivateScratch.Memory bits := fun q => if h : endAddr ≤ q.val then saved ⟨q,h⟩ else 0
+ let sel := MapConstants.selectorWord B.refresh
+ (MapConstants.fits_of_threshold B.refresh tableWidth).2.2.2
+ let a : W bits := word (histBase + l.val)
+ have aVal : a.val = histBase + l.val := Nat.mod_eq_of_lt (by
+ have := l.isLt
+ have := capacity.room
+ omega)
+ have array (base len : ℕ) (lo : directory ≤ base) (hi : base + len ≤ limit)
+ (values : Fin len → W bits) (before : PrivateScratch.Memory bits) :
+ PrivateScratch.write (base : W bits) values before a = before a := by
+ apply dite_eq_right
+ rintro ⟨i, hit⟩
+ rw [← Nat.cast_add] at hit
+ have inRange := (Nat.add_lt_add_left i.isLt base).trans_le hi
+ have eq := (Nat.mod_eq_of_lt (inRange.trans capacity.room)).symm.trans
+ ((congrArg Fin.val hit).trans aVal)
+ have := l.isLt
+ omega
+ have argc : Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H)) ≤
+ MapCallWords.headCapacity D H := le_max_right _ _
+ have published : MapScratch.published (L).core (L).args loc Wk (word directory) mem a = mem a :=
+ array directory (Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H))) le_rfl (by omega) _ mem
+ have portsEnd := ord.directoryEnd
+ change directory + (MapPortAgreement.ports S.portSupply v.2 (L).core.edgeOrder).length ≤
+ directory + MapCallWords.headCapacity D H at portsEnd
+ have directoryMem (before : PrivateScratch.Memory bits) :
+ MapCallSetup.directoryMemory (L).core loc Wk before a = before a :=
+ array directory _ le_rfl (by omega) _ before
+ have sourceLo : directory ≤ Wk.source := Nat.le_add_right ..
+ have targetLo : directory ≤ Wk.target := sourceLo.trans (Nat.le_add_right ..)
+ have sourceEnd : Wk.source + u ≤ limit := by
+ change directory + MapCallWords.headCapacity D H + u ≤ limit
+ omega
+ have targetEnd : Wk.target + u ≤ limit := by
+ change directory + MapCallWords.headCapacity D H + u + u ≤ limit
+ omega
+ have run : (MotifEntry.run tieSource tieTarget (baseDemand B.refresh z) (EntryInput.demand I)
+ S.portSupply (basePayload B.refresh) (lookup B.refresh z) (selectorTable B.refresh)
+ (selectorCode B.refresh) (EntryInput.payload I) v.2 d x).1.isSome = true := by
+ change (entry).1.isSome = true
+ simpa only [Option.isSome_map] using good
+ obtain ⟨θ, pick, valid⟩ := MapScratch.sequence_of_success run
+ change MapScratch.successMemory (L).core (L).args loc Wk (word directory) sel T.ordinal mem a = _
+ rw [MapScratch.successMemory, pick, Option.elim_some, MapEntry.Program.successMemory]
+ change PrivateLabels.accumulate Wk.hist _ _ (word (Wk.hist + l.val)) = _
+ erw [PrivateLabels.accumulate_at Wk.hist _ _ Wk.histogramFit l,
+ array Wk.target u targetLo targetEnd, array Wk.source u sourceLo sourceEnd,
+ directoryMem, published]
+ have start : mem a = saved ⟨a, above⟩ := dite_eq_left above
+ erw [start]
+ congr 1
+ unfold runEntry
+ erw [MapFinish.entry_value, pick, Option.bind_some, ite_eq_left valid, Option.map_some,
+ Option.getD_some, List.map_ofFn]
+ rfl
+
+end CompressorRecords.PortRefresh.RefreshResidentImage.Plan
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PhaseRecipe PairSimulation NewSlots
+open RefreshMapOperands LocalHistory NetworkKernel
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist bits g : ℕ}
+ (ties : Fin t ≃ Tie (2 ^ S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent)) (degree n rowEnd child parent : ℕ)
+ (room : Room B X choice v degree n rowEnd child parent hist bits)
+ (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+
+local notation "hb" => LeafArena.Regions.histBase (TerminalLayout.privateRegions degree n rowEnd hist)
+local notation "names" => emitted B order X choice v old new
+
+set_option maxHeartbeats 1400000 in
+-- Specialize the two dependent node buffers and the terminal scratch layout.
+theorem upper_histogram {endAddr : ℕ} (s : DFS.Scratch bits endAddr) (good : (names).isSome = true)
+ (l : Fin hist) (above : endAddr ≤ (word (bits := bits) (hb + l.val)).val) :
+ canonicalUpper B ties stride order X choice v degree n rowEnd child parent room old new
+ s ⟨word (hb + l.val), above⟩ =
+ s ⟨word (hb + l.val), above⟩ + (((names).getD []).count l : W bits) := by
+ unfold emitted at good ⊢
+ split at good
+ · rename_i diagonal
+ rw [ite_eq_left diagonal]
+ unfold canonicalUpper
+ apply RefreshResidentImage.Plan.mapUpper_histogram
+ exact good
+ · contradiction
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalLabels.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalLabels.lean
new file mode 100644
index 0000000000..feb3259931
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalLabels.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalMapBody
+
+/-!
+# Labels of the resident refresh role
+
+The two stored node arguments select the same diagonal tests and scalar list as the
+dyadic refresh kernel. The physical parent may receive its old half through any
+placement with the prescribed singleton child.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open Compression Compression.Refresh Compression.DegreeRefresh NetworkKernel PairSimulation
+open MotifConversion MotifEntry MotifDemandPadding MotifSelector LocalHistory RefreshMapOperands
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {hist g : ℕ} (order : B.Entry ≃ Fin hist) (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent))
+ (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+
+local notation "G" => splitSlots X
+local notation "port" => bitWordFinEquiv (S.portExponent)
+local notation "widths" => splitWidths X
+local notation "t" => oldPortMatching G port
+local notation "ws" => groupedWidths port widths
+local notation "P" => S.graph.toSlotGraph
+local notation "hd" => And.right S.degree_bounds
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "supply" =>
+ blockSupplyWidths G port widths S.graph (Nat.two_pow_pos _) hc B.refresh choice
+local notation "oldArg" => oldHalf X v old
+local notation "seg" => segments X v P S.port_order hd supply new
+local notation "I" => entryInput B X choice v old new
+local notation "splitIso" => relaneIso X.slots (splitBitWord S.portExponent g) X.width
+
+set_option maxHeartbeats 1800000 in
+-- Matching the two label formulas unfolds the complete dependent refresh entry.
+/-- The addressable labels, including repetitions, are the exact common scalar
+indices of the refresh kernel for these arguments. -/
+theorem emitted_eq_indices
+ (before : Placed (refreshPositions port) (actualWireGraph G widths).Half (promotedSites v))
+ (child : before (originalSites port v)
+ (by simp [promotedSites, originalSites, refreshPositions]) =
+ (splitIso).pullHalf (originalSites port v) old) :
+ emitted B order X choice v old new =
+ ((refreshEntryIndices G port widths S.graph
+ (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice
+ v before new).map List.ofFn).map (List.map (fun e => order (.inr e))) := by
+ classical
+ let good := (oldArg).1 ((v.1, v.2), v.2) rfl = (seg).1 v.2 ∧
+ (seg).2 v.2 = incomingHalf (R := ℤ) t ws v.1 v.2 v.2 oldArg
+ have diag : portDiagonal t ws v.1 v.2 oldArg seg = (1 : ℤ) ↔ good := by
+ unfold portDiagonal segmentTest
+ dsimp only [good]
+ split <;> split <;> rename_i h₁ h₂
+ · exact ⟨fun _ => ⟨h₁, h₂⟩, fun _ => rfl⟩
+ · exact ⟨by norm_num, fun h => (h₂ h.2).elim⟩
+ · exact ⟨by norm_num, fun h => (h₁ h.1).elim⟩
+ · exact ⟨by norm_num, fun h => (h₁ h.1).elim⟩
+ unfold emitted refreshEntryIndices
+ dsimp only
+ rw [child]
+ let ids := entry B.refresh (fun _ => zero_lt_one) (EntryInput.demand I) (EntryInput.payload I) v.2
+ (EntryInput.demandBits I) (EntryInput.supplyBits I)
+ change (if portDiagonal t ws v.1 v.2 oldArg seg = (1 : ℤ) then _ else none) =
+ ((if good then ids else none).map List.ofFn).map (List.map (fun e => order (.inr e)))
+ by_cases eqn : good
+ · rw [ite_eq_left (diag.mpr eqn), ite_eq_left eqn]
+ exact congrArg (Option.map (List.map (fun e => order (.inr e))))
+ (runEntry_list B.refresh (fun _ => zero_lt_one) (EntryInput.demand I) (EntryInput.payload I)
+ v.2 (EntryInput.demandBits I) (EntryInput.supplyBits I))
+ · rw [ite_eq_right (mt diag.mp eqn), ite_eq_right eqn]
+ rfl
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalMapBody.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalMapBody.lean
new file mode 100644
index 0000000000..aa7b8bce61
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalMapBody.lean
@@ -0,0 +1,214 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalPlan
+import OAI.Computability.VPVNP.PairRefreshResidentKernel
+
+/-!
+# Executing the selected refresh body in the terminal DFS layout
+
+The four geometry instructions and the resident map image run in one host program.
+The old and new argument intervals are below the shared histogram. The actual map
+workspace lies beyond the immutable geometry and finishes before the scalar cache.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe PairSimulation VertexImage NodeArguments NewSlots RefreshMapOperands NetworkKernel
+open MotifConversion MotifEntry MotifDemandPadding MotifSelector LocalHistory
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist : ℕ}
+ (ties : Fin t ≃ Tie (2 ^ S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+local notation "T" => plan B ties stride order
+private abbrev siteOrder {a g : ℕ}
+(X : State a (a + g)) := sites (D := 2 ^ a) X.baseIndex (bitWordFinEquiv g)
+local notation "D" => 2 ^ S.portExponent
+local notation "H" => 2 ^ S.expanderExponent
+local notation "P" => S.graph.toSlotGraph
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hd" => And.right S.degree_bounds
+
+/-- One constant for every node, level and input size of the fixed refresh role. -/
+noncomputable def budget : ℕ := (T).uniform.choose + 4
+
+variable {pcs regs bits g : ℕ} (loc : Fin (body B ties stride order).count → Fin pcs)
+ (dfs : Fin 9 ↪ Fin regs) (saved : Saved ↪ Fin regs)
+ (bank : Fin (body B ties stride order).privateRegs ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11)
+ (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent)) (degree n rowEnd : ℕ)
+ (U V : IncidenceDirectory bits) (m : Memory bits)
+ (start parent child listHead oldHead newHead : ℕ)
+
+local notation "left" =>
+ Segment.leftPC TraversalGeometry.reload (RefreshResidentImage.Plan.segment T) loc
+local notation "right" =>
+ Segment.rightPC TraversalGeometry.reload (RefreshResidentImage.Plan.segment T) loc
+local notation "commonBank" => Function.Embedding.trans (locatorBank B ties stride order) bank
+local notation "own" => Function.Embedding.trans (Function.Embedding.trans Function.Embedding.inr
+ (Equiv.toEmbedding (RefreshResidentImage.Plan.registers T))) bank
+local notation "Y" =>
+ dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice
+local notation "supply" =>
+ blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph
+ (Nat.two_pow_pos _) hc B.refresh choice
+local notation "O" => siteOrder X
+local notation "R" => TerminalLayout.privateRegions degree n rowEnd hist
+local notation "A" => LeafArena.Regions.arguments R
+local notation "histBase" => LeafArena.Regions.histBase R
+local notation "directory" => histBase + hist + 12 + 2 * n
+local notation "ws" => groupedWidths (bitWordFinEquiv _) (splitWidths X)
+local notation "perm" => oldPortMatching (splitSlots X) (bitWordFinEquiv _)
+local notation "wo" => ws (v, Prod.snd v)
+local notation "wi" => ws (Equiv.symm perm (v, Prod.snd v))
+
+variable (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+local notation "diagonalValue" => portDiagonal perm ws (Prod.fst v) (Prod.snd v) (oldHalf X v old)
+ (segments X v P S.port_order hd supply new)
+local notation "E₀" => entryInput B X choice v old new
+local notation "z" => demandGrid B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀)
+local notation "u" => repetitions B.refresh (EntryInput.demand E₀)
+local notation "d" => demandBits tieSource tieTarget (Prod.snd v) (EntryInput.demandBits E₀)
+local notation "x" => mapHalf S.portSupply (fun _ => inputBits) (EntryInput.supplyBits E₀)
+
+/-- Histogram ordinals emitted by the selected refresh entry after its diagonal tie check
+succeeds. -/
+noncomputable def emitted : Option (List (Fin hist)) :=
+ if diagonalValue = (1 : ℤ) then
+ ((runEntry B.refresh (fun _ => zero_lt_one) (EntryInput.demand E₀)
+ (EntryInput.payload E₀) v.2 d x).1.map (List.map (fun e => order (.inr e))))
+ else none
+
+set_option maxHeartbeats 2200000 in
+-- Elaborating the native call specializes every register and both dependent node frames.
+/-- The selected refresh role executes from the actual located parent and singleton
+preimage row. Its successful labels and its rejection branch agree with the local
+refresh map, with constant external probes and linear local work. -/
+theorem map_body
+ (rows : ∀ j, M.code (loc j) =
+ ((body B ties stride order).row loc dfs saved bank done j).resize bits)
+ (apartD : ∀ i j, bank i ≠ dfs j) (apartS : ∀ i j, bank i ≠ saved j)
+ (c : Config bits pcs regs) (entry : c.pc = left TraversalGeometry.reload.entry)
+ {endAddr : ℕ} {G offset : W bits} (endWord : c.reg (dfs 6) = (endAddr : W bits))
+ (resident : ResidentGeometry (DFS.scratch endAddr c.privateMem) G offset (word histBase))
+ (oldWord : (c.reg (commonBank 11)).val = oldHead)
+ (newWord : (c.reg (commonBank 4)).val = newHead)
+ (siteWord : (c.reg (commonBank 7)).val = (O v).val)
+ (parentWord : (c.reg (commonBank 0)).val = parent)
+ (header : TraversalHeaders.Geometry (Fintype.card X.Base) g oldHead newHead start A U V m)
+ (row : DFS.Row m parent listHead [word child]) (lanes : 2 ^ g < 2 ^ bits)
+ {fit : Fintype.card X.Base * D * 2 ^ g * D ≤ 2 ^ bits}
+ (stored : Build.Stored X S.graph
+ (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m)
+ (oldCols : U.ActualColumns X m) (newCols : V.ActualColumns Y m)
+ (oldData : NodeFields A child X (oldSite X v) old c.privateMem)
+ (newData : NodeFields A parent Y (promotedSites v) new c.privateMem)
+ (childBound : child < rowEnd) (parentBound : parent < rowEnd) (oldDegree : D ≤ degree)
+ (newDegree : 2 ^ (S.degreeExponent 0) ≤ degree) (oldWidth : X.maxWireWidth ≤ n)
+ (newWidth : (Y).maxWireWidth ≤ n)
+ (copyBound : u ≤ n) (large : MapCallWords.headCapacity D H + 12 ≤ n) (five : 5 ≤ n)
+ (capacity : MapWorkspace.Capacity B.refresh bits n (R).cacheBase) (wide : D < 2 ^ bits)
+ (tableWidth : MapConstants.widthThreshold B.refresh ≤ bits) :
+ let names := emitted B order X choice v old new
+ ∃ out es, ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ budget B ties stride order * (wo + wi + u + 1) ∧
+ countProbes es ≤ budget B ties stride order ∧
+ choiceBits es = [] ∧ (if names.isSome then out.pc = done else M.code out.pc = .reject) ∧
+ out.persistent = c.persistent ∧ (∀ j, (∀ i, j ≠ bank i) → out.reg j = c.reg j) ∧
+ (∀ q : W bits, q.val < directory →
+ (∀ l : Fin hist, q ≠ word (histBase + l.val)) → out.privateMem q = c.privateMem q) ∧
+ ∀ l : Fin hist,
+ out.privateMem (word (histBase + l.val)) = c.privateMem (word (histBase + l.val)) +
+ ((names.getD []).count l : W bits) := by
+ dsimp only
+ obtain ⟨mid, pre, entry', priv, pers, frame, args, hdir, hhist⟩ :=
+ enter B ties stride order loc dfs saved bank done M X choice v A U V m start parent child
+ listHead oldHead newHead
+ histBase rows c entry endWord resident oldWord newWord siteWord parentWord header row lanes
+ have first : ChildScan.Prefix M m c mid [] (List.replicate 4 .tick) := by
+ intro fuel bs
+ exact pre.execute fuel m bs
+ have ready : mid.pc = (T).diagSetup (right ∘ (T).locations) 0 := by
+ rw [entry']
+ change right ((T).diagSetup (T).locations 0) = (T).diagSetup (right ∘ (T).locations) 0
+ by_cases h : 0 < (RegisterSetup.lines (T).diagonal).length
+ · refine (congrArg right (dite_eq_left h)).trans ?_
+ rw [RefreshResidentImage.Plan.diagSetup, dite_eq_left h]
+ rfl
+ · refine (congrArg right (dite_eq_right h)).trans ?_
+ rw [RefreshResidentImage.Plan.diagSetup, dite_eq_right h]
+ rfl
+ have banks : RefreshResidentImage.Plan.Banks T dfs saved commonBank own := by
+ refine ⟨fun _ j => apartD _ j, fun _ j => apartS _ j, ?_⟩
+ intro a b eq
+ have h : (Sum.inr a : Fin 14 ⊕ (T).Local) = Sum.inl b :=
+ (T).registers.injective (bank.injective eq)
+ contradiction
+ have installed := (body_links B ties stride order loc dfs saved bank done M rows).2
+ have oldEnd := TraversalGeometry.argument_end degree n rowEnd hist X (oldSite X v) old child
+ childBound oldDegree oldWidth
+ have newEnd := TraversalGeometry.argument_end degree n rowEnd hist Y (promotedSites v) new parent
+ parentBound newDegree newWidth
+ have endSpace :=
+ TraversalGeometry.workspace_before_cache degree n rowEnd hist (MapCallWords.headCapacity D H) u
+ large five copyBound
+ have nfits : n < 2 ^ bits := by
+ apply Nat.lt_of_le_of_lt _ capacity.room
+ change n ≤ n + rowEnd * (2 * degree * n + 1) + hist + n ^ 5
+ omega
+ have fields (e) : ws e < 2 ^ bits := ((X.width_le_maxWireWidth _).trans oldWidth).trans_lt nfits
+ obtain ⟨out, es, run, len, probes, path, pc', pers', frame', mem, hits⟩ :=
+ (T).native (right ∘ (T).locations) dfs saved commonBank own done M installed
+ X choice v A child parent U V start m old new mid ready banks args stored oldCols newCols
+ (priv ▸ oldData) (priv ▸ newData) histBase n directory histBase hdir hhist oldEnd newEnd
+ oldWidth newWidth (by omega) (by omega) endSpace.2 capacity copyBound wide
+ (fields _) (fields _) tableWidth
+ obtain ⟨readBound, workBound⟩ := (T).uniform.choose_spec z v.2 wo wi u
+ refine ⟨out, List.replicate 4 (.tick : Event bits) ++ es, first.trans run, ?_, ?_, ?_, pc',
+ pers'.trans pers,
+ fun j hj => (frame' j (fun _ => hj _)).trans (frame j (hj _) (hj _)),
+ fun q hq hn => (mem q hq hn).trans (congrFun priv q), ?_⟩
+ · rw [List.length_append, List.length_replicate]
+ have h := len.trans workBound
+ change 4 + es.length ≤ ((T).uniform.choose + 4) * (wo + wi + u + 1)
+ rw [Nat.add_mul]
+ have four : 4 ≤ 4 * (wo + wi + u + 1) := Nat.le_mul_of_pos_right _ (by omega)
+ omega
+ · rw [countProbes_append, probes]
+ change 0 + _ ≤ (T).uniform.choose + 4
+ dsimp only at readBound
+ split <;> omega
+ · rw [PrimedInputRAM.Flow.choiceBits_append, path]; rfl
+ · intro l
+ rw [hits, priv]; rfl
+
+/-- The fixed capacity requirements hold simultaneously up to the scalar cache in
+any polynomial bound on the number of absolute descriptor addresses. -/
+theorem eventually_body_capacity (degree labels b : ℕ) (hb : 1 ≤ b) (nodes : ℕ → ℕ)
+ (bound : PolynomiallyBounded nodes) :
+ ∀ᶠ n : ℕ in Filter.atTop, MapWorkspace.Capacity B.refresh (CursorBounds.wordBits b n) n
+ (TerminalLayout.privateRegions degree n (nodes n) labels).cacheBase :=
+ MapWorkspace.eventually_capacity (B := B.refresh) b hb _ <|
+ ((PolynomiallyBounded.id.add (bound.mul (NodeArguments.frameStride_bounded degree))).add
+ (.const labels)).add (PolynomiallyBounded.id.pow 5)
+
+theorem copies_le : u ≤ Fintype.card (Tie D) * X.maxWireWidth := by
+ apply term_repetitions_le B.refresh
+ intro e
+ change blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) v.1 e ≤ _
+ unfold blockDemandWidths internalWidth
+ split <;> exact X.width_le_maxWireWidth _
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalOriginBits.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalOriginBits.lean
new file mode 100644
index 0000000000..edf089d2aa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalOriginBits.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalValue
+import OAI.Computability.VPVNP.PairSelectedKernelReaders
+import OAI.Computability.VPVNP.PairTypedVertexJobs
+
+/-!
+# Bits consumed by the selected refresh origin reader
+
+The promoted site's placement fiber has one member. Its actual parser reads the
+old outgoing and incoming slots in physical order. The successful local map
+contributes an empty choice word, so the node consumes exactly that child packet.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open Compression Compression.Refresh Compression.DegreeRefresh NetworkKernel
+open PairSimulation PairSimulation.NodeArguments PairSimulation.LocalHistory RefreshMapOperands
+
+private theorem ofFn_unique {I : Type} {α : Type*} (o : Order I) (one : I) (unique : ∀ i, i = one)
+ (f : I → α) : List.ofFn (fun j => f (o.entries j)) = [f one] := by
+ let singleton : I ≃ Fin 1 :=
+ ⟨fun _ => 0, fun _ => one, fun i => (unique i).symm, fun _ => Subsingleton.elim ..⟩
+ have size : o.length = 1 := by
+ simpa only [Fintype.card_fin] using Fintype.card_congr (o.entries.trans singleton)
+ have same : (fun j => f (o.entries j)) = fun _ => f one := funext fun j => congrArg f (unique _)
+ rw [same, List.ofFn_const, size]
+ rfl
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {K : Type*} [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f)
+ {g : ℕ} (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent))
+ (before : Placed (place X) X.network.Half (promotedSites v))
+
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hd" => And.right S.degree_bounds
+local notation "site" => promotedSites v
+local notation "older" => before (oldSite X v) (old_place X v)
+local notation "reader" => originReader B f hf (PassOrigin.refresh X) choice
+
+set_option maxHeartbeats 1800000 in
+/-- The actual origin's ordered child list contains the single old-site packet. -/
+theorem origin_childPackets (previous : X.network.Site → ℕ) :
+ (reader).childPackets previous site before =
+ [⟨previous (oldSite X v), packed X (oldSite X v) older⟩] := by
+ refine (TermParsers.childPackets_state X reader rfl (fun _ => rfl) (fun _ => rfl) previous site before).trans ?_
+ let one : {u : X.network.Site // site = place X u} := ⟨oldSite X v, old_place X v⟩
+ have unique (i : {u : X.network.Site // site = place X u}) : i = one :=
+ Subtype.ext ((place X).injective (i.property.symm.trans (old_place X v)))
+ exact ofFn_unique ((reader).order.children site) one unique
+ (fun i => Packet.mk (previous i.val) (packed X i.val (before i.val i.property)))
+
+variable (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh
+ S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+ (witness : ((originReader B f hf (PassOrigin.refresh X) choice).witness (promotedSites v) before new).Choice)
+
+set_option maxHeartbeats 1800000 in
+/-- Once a local refresh witness exists, its map requires no additional bits. -/
+theorem origin_kernelBits : ((reader).read site before new).encode witness = [] := by
+ apply List.length_eq_zero_iff.mp
+ exact listedEntryReader_length (f ∘ Sum.inr) _ _
+ (refreshNames_spec (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc
+ B.refresh S.port_order hd choice site (splitPlaced X v before) new) witness
+
+/-- The exact bit word consumed by a successful visit to the selected origin. -/
+theorem origin_nodeBits : (reader).nodeBits site before new witness = packed X (oldSite X v) older := by
+ refine (TermParsers.nodeBits_eq_childPackets (reader) (fun _ => 0) site before new witness).trans ?_
+ have bits := congrArg (List.flatMap Packet.bits) (origin_childPackets B f hf X choice v before (fun _ => 0))
+ have last := origin_kernelBits B f hf X choice v before new witness
+ exact (congrArg₂ List.append bits last).trans (by simp)
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalPlan.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalPlan.lean
new file mode 100644
index 0000000000..d97c555979
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalPlan.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.PairRefreshGeometryReload
+import OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders
+import OAI.Computability.VPVNP.PairRefreshResidentImage
+
+/-!
+# The refresh body in the terminal DFS register bank
+
+The first fourteen shared words are the level locator's bank. The body reloads the
+private histogram head, then uses the popped node, the site ordinal and the two genuine
+level heads for its diagonal checks, dispatch and map call. The child's descriptor address
+is read through the unique preimage row. The global parameter numbering sends each
+refresh scalar to its right-summand histogram bin.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe
+open PairSimulation PairSimulation.VertexImage NewSlots RefreshMapOperands NodeArguments
+open PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist : ℕ}
+ (ties : Fin t ≃ Tie (2 ^ S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+
+/-- The refresh level's static geometry, giving input and output degrees, expander size, tie
+count, record stride, and selector width. -/
+noncomputable def shape (t stride : ℕ) : LevelRecipe.Shape :=
+ ⟨S.portExponent, S.degreeExponent 0, 2 ^ S.expanderExponent, t, stride, B.refresh.selectorBits⟩
+
+/-- Construct the resident refresh plan from the traversal header operands, shared locator
+sources, tie enumeration, and common histogram numbering. -/
+noncomputable def plan : RefreshResidentImage.Plan B t hist 14 where
+ ties := ties
+ stride := stride
+ input := TraversalHeaders.input (shape B t stride)
+ directory := TraversalGeometry.directory hist
+ histogram := TraversalGeometry.histogram
+ ordinal e := order (.inr e)
+ source := TraversalGeometry.source
+
+local notation "T" => plan B ties stride order
+
+/-- Embedding for the handoff from the locator and child scan into the local body. -/
+noncomputable def locatorBank : Fin 14 ↪ Fin (T).segment.privateRegs :=
+ Function.Embedding.inl.trans (T).registers.toEmbedding
+
+/-- The native histogram reload and the exact refresh map image share the locator bank. -/
+noncomputable def body : VertexImage.Segment :=
+ TraversalGeometry.reload.thenWith (T).segment (locatorBank B ties stride order)
+ (Equiv.refl _).toEmbedding
+
+variable {pcs regs bits : ℕ} (loc : Fin (body B ties stride order).count → Fin pcs)
+ (dfs : Fin 9 ↪ Fin regs) (saved : Saved ↪ Fin regs)
+ (bank : Fin (body B ties stride order).privateRegs ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11)
+
+local notation "left" =>
+ Segment.leftPC TraversalGeometry.reload (RefreshResidentImage.Plan.segment T) loc
+local notation "right" =>
+ Segment.rightPC TraversalGeometry.reload (RefreshResidentImage.Plan.segment T) loc
+local notation "commonBank" => Function.Embedding.trans (locatorBank B ties stride order) bank
+
+/-- Installation of the single segment yields the precise geometry and local-body
+links, including their common entry PC and shared registers. -/
+theorem body_links
+ (rows : ∀ j, M.code (loc j) =
+ ((body B ties stride order).row loc dfs saved bank done j).resize bits) :
+ (∀ j, M.code (left j) =
+ (TraversalGeometry.reload.row left dfs saved commonBank
+ (right (T).segment.entry) j).resize bits) ∧
+ (T).Installed (right ∘ (T).locations) dfs saved commonBank
+ ((Function.Embedding.inr.trans (T).registers.toEmbedding).trans bank) done M := by
+ obtain ⟨a, b⟩ :=
+ Segment.split_link TraversalGeometry.reload (T).segment (locatorBank B ties stride order)
+ (Equiv.refl _).toEmbedding loc dfs saved bank done M rows
+ exact ⟨a, (T).segment_installed dfs saved done M right bank b⟩
+
+/-- The live expression operands are the four surviving locator values and the
+histogram just reloaded. Operand three contains the private histogram-cell address. -/
+theorem input_registers (common : Fin 14 ↪ Fin regs) :
+ (T).inputs dfs saved common =
+ ![common 7, common 0, common 4, common 9, common 10, common 11] := by
+ funext i; fin_cases i <;> rfl
+
+section Entry
+
+variable {g : ℕ} (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent)) (A : Arena) (U V : IncidenceDirectory bits)
+ (m : Memory bits) (start parent child listHead oldHead newHead histBase : ℕ)
+
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hd" => And.right S.degree_bounds
+local notation "supply" =>
+ blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph
+ (Nat.two_pow_pos _) hc B.refresh choice
+local notation "Pₗ" =>
+ Allocation.plan X (S.degreeExponent 0) (2 ^ S.expanderExponent) t stride start
+local notation "O" => sites (D := 2 ^ S.portExponent) X.baseIndex (bitWordFinEquiv g)
+
+/-- Actual entry into the local computation from the preserved locator and child-scan
+state. Only the header contents and the actual child row are used to recover the level
+and its two argument frames. -/
+theorem enter (rows : ∀ j,
+ M.code (loc j) = ((body B ties stride order).row loc dfs saved bank done j).resize bits)
+ (c : Config bits pcs regs)
+ (entry : c.pc = left TraversalGeometry.reload.entry) {endAddr : ℕ} {G offset : W bits}
+ (endWord : c.reg (dfs 6) = (endAddr : W bits))
+ (resident : ResidentGeometry (DFS.scratch endAddr c.privateMem) G offset (word histBase))
+ (oldWord : (c.reg (commonBank 11)).val = oldHead)
+ (newWord : (c.reg (commonBank 4)).val = newHead)
+ (siteWord : (c.reg (commonBank 7)).val = (O v).val)
+ (parentWord : (c.reg (commonBank 0)).val = parent)
+ (header : TraversalHeaders.Geometry (Fintype.card X.Base) g oldHead newHead start A U V m)
+ (row : DFS.Row m parent listHead [word child]) (lanes : 2 ^ g < 2 ^ bits) :
+ ∃ out, Prefix M c (List.replicate 4 .tick) out ∧ out.pc = right (T).segment.entry ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ (∀ j, j ≠ commonBank 9 → j ≠ commonBank 10 → out.reg j = c.reg j) ∧
+ let inp := (T).inputs dfs saved commonBank
+ let pub := fun i : Fin 5 => out.reg (inp i.castSucc)
+ let state := out.reg (inp (Fin.last 5))
+ OperandInputs.Describes (T).input pub state m X v S.graph.toSlotGraph S.port_order hd supply A
+ child parent U V
+ ((Pₗ).scratch bits) (word (Pₗ).demand) (word (Pₗ).term) ∧
+ (T).directory.eval pub state m = word (histBase + hist + 12 + 2 * A.start) ∧
+ (T).histogram.eval pub state m = word histBase := by
+ have links := body_links B ties stride order loc dfs saved bank done M rows
+ obtain ⟨out, pre, ep, histEq, frame, priv, pers⟩ :=
+ TraversalGeometry.reload_native M left dfs saved commonBank
+ (right (T).segment.entry) links.1 c entry endWord resident
+ let C : LevelRecipe.Context bits :=
+ ⟨fun i => out.reg ((T).inputs dfs saved commonBank i.castSucc),
+ out.reg ((T).inputs dfs saved commonBank (Fin.last 5)), m⟩
+ have keep (i : Fin 14) (hn₉ : i ≠ 9)
+ (hn₁₀ : i ≠ 10) : out.reg (commonBank i) = c.reg (commonBank i) :=
+ frame _ ((commonBank).injective.ne hn₉) ((commonBank).injective.ne hn₁₀)
+ have oh : C.state.val = oldHead :=
+ (congrArg Fin.val (keep 11 (by decide) (by decide))).trans oldWord
+ have nh : (C.pub 2).val = newHead :=
+ (congrArg Fin.val (keep 4 (by decide) (by decide))).trans newWord
+ have site : (C.pub 0).val = (O v).val :=
+ (congrArg Fin.val (keep 7 (by decide) (by decide))).trans siteWord
+ have pw : (C.pub 1).val = parent :=
+ (congrArg Fin.val (keep 0 (by decide) (by decide))).trans parentWord
+ have args := TraversalHeaders.describes (shape B t stride) X v S.graph.toSlotGraph S.port_order hd
+ supply A U V C
+ header oh nh site pw row lanes
+ have heads := TraversalGeometry.heads_eval hist A.start histBase C.pub C.state m histEq
+ args.childRep.arena
+ exact ⟨out, pre, ep, priv, pers, frame, args, heads.2, heads.1⟩
+
+end Entry
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalQuiet.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalQuiet.lean
new file mode 100644
index 0000000000..3276dc77da
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalQuiet.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalAction
+
+/-! # Choice and external-memory frames of the canonical refresh action
+
+Only the preceding child reader consumes the guessed half-wire bits. The
+selected local action consumes no further choices and only reads external RAM.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open PhaseRecipe PairSimulation VertexImage NodeArguments NewSlots RefreshMapOperands NetworkKernel
+open MotifConversion MotifEntry MotifDemandPadding MotifSelector LocalHistory
+open scoped Fin.CommRing
+open private guessed_addFuel from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist bits g : ℕ}
+ (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+ (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (degree n rowEnd child parent : ℕ)
+
+variable (room : Room B X choice v degree n rowEnd child parent hist bits)
+ (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+ (m : Memory bits) (oldHead newHead : ℕ) (G : W bits)
+
+local notation "events" => canonicalEvents B ties stride order X choice v degree n rowEnd child parent room old new m oldHead newHead G
+local notation "T" => plan B ties stride order
+local notation "action" => canonicalAction B ties stride order X choice v degree n rowEnd child parent room old new m oldHead newHead G
+
+theorem canonicalEvents_noChoices : choiceBits events = [] := by
+ rw [canonicalEvents,PrimedInputRAM.Flow.choiceBits_append,(T).successEvents_noChoices]
+ rfl
+
+theorem canonicalEvents_noWrites : SourceTransport.Writes (fun _ => False) events := by
+ intro a value h
+ rcases List.mem_append.mp h with tick | visit
+ · cases List.eq_of_mem_replicate tick
+ · exact (T).successEvents_noWrites X choice v m old new room.tableWidth _ _ a value visit
+
+variable {endAddr : ℕ} {s updated : DFS.Scratch bits endAddr} {es : List (Event bits)}
+
+theorem canonicalAction_events (h : action s = some (es,updated)) : es = events := by
+ unfold canonicalAction at h
+ split at h
+ · exact (Prod.mk.inj (Option.some.inj h)).1.symm
+ · contradiction
+
+theorem canonicalAction_noChoices (h : action s = some (es,updated)) : choiceBits es = [] := by
+ rw [canonicalAction_events B ties stride order X choice v degree n rowEnd child parent room old new m oldHead newHead G h]
+ exact canonicalEvents_noChoices B ties stride order X choice v degree n rowEnd child parent room old new m oldHead newHead G
+
+theorem canonicalAction_noWrites (h : action s = some (es,updated)) :
+ SourceTransport.Writes (fun _ => False) es := by
+ rw [canonicalAction_events B ties stride order X choice v degree n rowEnd child parent room old new m oldHead newHead G h]
+ exact canonicalEvents_noWrites B ties stride order X choice v degree n rowEnd child parent room old new m oldHead newHead G
+
+theorem after_canonicalAction (h : action s = some (es,updated)) : after m es = m :=
+ funext fun _ => SourceTransport.after_outside m
+ (canonicalAction_noWrites B ties stride order X choice v degree n rowEnd child parent room old new m oldHead newHead G h) id
+
+/-- Every successful complete report factors at the certified local prefix, including
+reports obtained at an arbitrary fuel bound. All its external updates occur in the suffix. -/
+theorem canonicalAction_report {pcs regs params fuel : ℕ} {M : Machine bits pcs regs params}
+ {c out : Config bits pcs regs} {tape : List Bool} {report : Report bits}
+ (h : action s = some (es,updated)) (pre : ChildScan.Prefix M m c out [] es)
+ (returned : execute M.program fuel c m tape = some report) :
+ ∃ rest, execute M.program fuel out m tape = some rest ∧ report.events = es ++ rest.events ∧
+ report.result = rest.result ∧ after m report.events = after m rest.events := by
+ obtain ⟨guessed,correct,choices⟩ := execute_iff.mp returned
+ have more := execute_iff.mpr ⟨guessed_addFuel guessed es.length,correct,choices⟩
+ have tail := pre fuel tape
+ rw [List.nil_append] at tail
+ rw [Nat.add_comm es.length fuel,tail] at more
+ obtain ⟨rest,run,eq⟩ := Option.map_eq_some_iff.mp more
+ have eventsEq := congrArg Report.events eq.symm
+ have resultEq := congrArg Report.result eq.symm
+ have unchanged := after_canonicalAction B ties stride order X choice v degree n rowEnd child parent room old new m
+ oldHead newHead G h
+ refine ⟨rest,run,eventsEq,resultEq,?_⟩
+ rw [eventsEq]
+ exact (show after m (es++rest.events) = after (after m es) rest.events from List.foldl_append).trans
+ (congrArg (fun mem => after mem rest.events) unchanged)
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalValue.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalValue.lean
new file mode 100644
index 0000000000..8c5cd0c881
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalValue.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalLabels
+import OAI.Computability.VPVNP.RefreshProcedureWitness
+import OAI.Computability.VPVNP.PairSimulationPrivateLabels
+
+/-!
+# Evaluation of the local refresh action
+
+The old physical node is the unique preimage of the promoted site. The product
+of the scalar labels emitted by the native local visit is the selected dyadic
+refresh kernel over every specialization of the common parameter equations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open Compression Compression.Refresh Compression.DegreeRefresh NetworkKernel
+open PairSimulation MotifConversion RefreshMapOperands
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {hist g : ℕ} (order : B.Entry ≃ Fin hist) (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent))
+
+local notation "port" => bitWordFinEquiv S.portExponent
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hd" => And.right S.degree_bounds
+local notation "splitIso" => relaneIso X.slots (splitBitWord S.portExponent g) X.width
+
+/-- The numerical refresh placement is the lane split followed by port promotion. -/
+noncomputable def place : X.network.Site ≃ (X.Base × Fin (2 ^ S.portExponent)) × BitWord g :=
+ ((Equiv.refl X.Base).prodCongr (splitBitWord S.portExponent g).toEquiv).trans
+ (refreshPositions (bitWordFinEquiv _))
+
+theorem old_place : promotedSites v = place X (oldSite X v) := by
+ change ((v.1.1, v.2), v.1.2) = refreshPositions port (v.1.1,
+ splitBitWord S.portExponent g ((splitBitWord S.portExponent g).symm ((port).symm v.2, v.1.2)))
+ rw [AddEquiv.apply_symm_apply, refreshPositions_apply, Equiv.apply_symm_apply]
+
+variable (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh
+ S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+
+/-- Fill the kernel's placed argument with the sole old half-wire assignment. -/
+def placedHalf : Placed (place X) X.network.Half (promotedSites v) :=
+ fun u hu => (show oldSite X v = u from (place X).injective ((old_place X v).symm.trans hu)) ▸ old
+
+theorem placedHalf_unique (before : Placed (place X) X.network.Half (promotedSites v)) :
+ placedHalf X v (before (oldSite X v) (old_place X v)) = before := by
+ funext u hu
+ obtain rfl := (place X).injective ((old_place X v).symm.trans hu)
+ rfl
+
+variable (before : Placed (place X) X.network.Half (promotedSites v))
+local notation "older" => before (oldSite X v) (old_place X v)
+
+/-- Pull the placed old half-wire assignment through the lane-splitting isomorphism for use by
+the refresh kernel. -/
+noncomputable def splitPlaced :
+ Placed (refreshPositions port) (actualWireGraph (splitSlots X) (splitWidths X)).Half
+ (promotedSites v) :=
+ fun u hu => (splitIso).pullHalf u (before ((splitIso).site u) (by
+ change promotedSites v = refreshPositions port (u.1,
+ splitBitWord S.portExponent g ((splitBitWord S.portExponent g).symm u.2))
+ rwa [AddEquiv.apply_symm_apply]))
+
+theorem splitPlaced_child :
+ splitPlaced X v before (originalSites port v)
+ (by simp [promotedSites, originalSites, refreshPositions]) =
+ (splitIso).pullHalf (originalSites port v) older := rfl
+
+local notation "indices" => refreshEntryIndices (splitSlots X) port (splitWidths X)
+ S.graph (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice v (splitPlaced X v before) new
+
+/-- Decode the finite histogram labels back into the common parameter alphabet. -/
+def evalLabels {K : Type*} [CommMonoidWithZero K] (f : B.Entry → K)
+ (labels : Option (List (Fin hist))) : K :=
+ labels.elim 0 fun ls => (ls.map (f ∘ order.symm)).prod
+
+theorem eval_emitted_indices {K : Type*} [CommMonoidWithZero K] (f : B.Entry → K) :
+ evalLabels B order f (emitted B order X choice v older new) =
+ evalEntry (f ∘ Sum.inr) indices := by
+ rw [emitted_eq_indices B order X choice v older new (splitPlaced X v before)
+ (splitPlaced_child X v before)]
+ cases indices with
+ | none => rfl
+ | some labels =>
+ simp only [Option.map_some, evalLabels, Option.elim_some, evalEntry,
+ List.map_ofFn, List.prod_ofFn, Function.comp_apply, Equiv.symm_apply_apply]
+
+variable {K : Type*} [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f)
+
+local notation "hsol" => And.right (Iff.mp (B.solution_iff f) hf)
+local notation "step" => expanderRefreshStep (splitSlots X) port (splitWidths X) S.graph
+ (Nat.two_pow_pos _) hc B.refresh (f ∘ Sum.inr) hsol S.port_order hd
+local notation "pass" => dyadicRefreshPass X S.graph (Nat.two_pow_pos _) hc B.refresh
+ S.port_order hd (f ∘ Sum.inr) hsol
+
+set_option maxHeartbeats 1500000 in
+-- Reduce the reindexed kernel on the singleton placed half.
+/-- The physical action evaluates to the exact coefficient of the scheduled dyadic
+refresh. Its value is zero on either failed local test. -/
+theorem eval_emitted_kernel :
+ evalLabels B order f (emitted B order X choice v older new) =
+ (((pass).step.term choice).kernel (promotedSites v) before new) := by
+ rw [eval_emitted_indices]
+ have raw := refreshEntryIndices_spec (splitSlots X) port (splitWidths X) S.graph
+ (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice v (splitPlaced X v before)
+ new (f ∘ Sum.inr) hsol
+ apply raw.symm.trans
+ change ((step).term choice).kernel (promotedSites v) (splitPlaced X v before) new =
+ ((((step).term choice).reindex splitIso (Network.Iso.refl _)).kernel (promotedSites v)
+ before new)
+ unfold Term.reindex
+ erw [Equiv.piCongrLeft_refl]
+ rfl
+
+/-- The same identity directly on the independently stored child and parent halves. -/
+theorem eval_emitted_singleton :
+ evalLabels B order f (emitted B order X choice v old new) =
+ (((pass).step.term choice).kernel (promotedSites v) (placedHalf X v old) new) :=
+ eval_emitted_kernel B order X choice v new (placedHalf X v old) f hf
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshTraversalWitness.lean b/lean/OAI/Computability/VPVNP/PairRefreshTraversalWitness.lean
new file mode 100644
index 0000000000..7c8be210be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshTraversalWitness.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.PairRefreshTraversalValue
+import OAI.Computability.VPVNP.PairSelectedKernelReaders
+
+/-!
+# Witnesses and histogram exponents at the selected refresh node
+
+An emitted list corresponds to one local witness, even when a selected scalar is
+zero in the field. Each histogram bin records exactly the exponent of the matching
+parameter in that witness.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open Compression Compression.Refresh Compression.DegreeRefresh NetworkKernel
+open PairSimulation MotifConversion RefreshMapOperands
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {hist g : ℕ} (order : B.Entry ≃ Fin hist) (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh
+ S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+ (before : Placed (place X) X.network.Half (promotedSites v))
+ {K : Type*} [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f)
+
+local notation "port" => bitWordFinEquiv S.portExponent
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "hd" => And.right S.degree_bounds
+local notation "hsol" => And.right (Iff.mp (B.solution_iff f) hf)
+local notation "older" => before (oldSite X v) (old_place X v)
+local notation "idx" => refreshEntryIndices (splitSlots X) port (splitWidths X)
+ S.graph (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice v (splitPlaced X v before) new
+local notation "W" => dyadicRefreshKernelWitness X S.graph (Nat.two_pow_pos _) hc B.refresh
+ S.port_order hd (f ∘ Sum.inr) hsol choice (promotedSites v) before new
+
+private theorem count_right {L M : Type} {u : ℕ}
+ (ord : L ⊕ M ≃ Fin hist) (labels : Fin u → M) (a : L ⊕ M) :
+ ((List.ofFn labels).map (fun e => ord (.inr e))).count (ord a) =
+ Sum.elim (fun _ => 0) (entryMultiplicity labels) a := by
+ classical
+ have h := PrivateLabels.count_entry (fun i => (Sum.inr (labels i) : L ⊕ M)) ord a
+ rw [List.map_ofFn] at h ⊢
+ refine h.trans ?_
+ cases a with
+ | inl l => simp [entryMultiplicity]
+ | inr l => simp [entryMultiplicity]
+
+private theorem choices_of_indices {Label : Type} [Fintype Label] {u : ℕ}
+ (scalar : Label → K) (indices : Option (Fin u → Label)) :
+ Nonempty (entryWitness scalar indices).Choice ↔ indices.isSome = true := by
+ cases indices with
+ | none => exact ⟨fun ⟨c⟩ => c.elim, fun h => by cases h⟩
+ | some _ => exact ⟨fun _ => rfl, fun _ => ⟨()⟩⟩
+
+set_option maxHeartbeats 1600000 in
+-- Identify the reindexed witness with its finite entry choice.
+/-- The branch is admissible exactly when the native role emits a list. -/
+theorem emitted_iff_witness :
+ (emitted B order X choice v older new).isSome = true ↔ Nonempty (W).Choice := by
+ rw [emitted_eq_indices B order X choice v older new (splitPlaced X v before)
+ (splitPlaced_child X v before)]
+ simp only [Option.isSome_map]
+ exact (choices_of_indices (f ∘ Sum.inr) idx).symm
+
+private theorem indexed_counts {L M : Type} [Fintype M] {u : ℕ}
+ (ord : L ⊕ M ≃ Fin hist) (scalar : M → K) (ids : Option (Fin u → M))
+ (w : (entryWitness scalar ids).Choice) (label : L ⊕ M) :
+ ((ids.map List.ofFn |>.map (List.map (fun e => ord (.inr e)))).getD []).count (ord label) =
+ Sum.elim (fun _ => 0) ((entryWitness scalar ids).exponents w) label := by
+ cases ids with
+ | none => exact w.elim
+ | some labels => exact count_right ord labels label
+
+set_option maxHeartbeats 1800000 in
+-- Compare the reindexed exponent with the count in the selected label list.
+/-- Histogram multiplicity of every global parameter equals the exponent of the
+scheduled refresh witness, including the zero exponents on shrinking parameters. -/
+theorem emitted_count (w : (W).Choice) (label : B.Entry) :
+ ((emitted B order X choice v older new).getD []).count (order label) =
+ (MonomialWitness.right f W).exponents w label := by
+ rw [emitted_eq_indices B order X choice v older new (splitPlaced X v before)
+ (splitPlaced_child X v before)]
+ change (((idx).map List.ofFn |>.map (List.map (fun e => order (.inr e)))).getD []).count
+ (order label) = Sum.elim (fun _ => 0) ((entryWitness (f ∘ Sum.inr) idx).exponents w) label
+ exact indexed_counts order (f ∘ Sum.inr) idx w label
+
+local notation "reader" => LocalHistory.originReader B f hf
+ (VPVNP.CompressorRecords.PassOrigin.refresh X) choice
+
+/-- The scheduled term reader has a kernel witness exactly on the accepted
+branch, for every physical specialization of the common equations. -/
+theorem origin_emitted_iff :
+ (emitted B order X choice v older new).isSome = true ↔
+ Nonempty ((reader).witness (promotedSites v) before new).Choice :=
+ emitted_iff_witness B order X choice v new before f hf
+
+private theorem subsingleton_indices {Label : Type} [Fintype Label] {u : ℕ}
+ (scalar : Label → K) (indices : Option (Fin u → Label)) :
+ Subsingleton (entryWitness scalar indices).Choice := by
+ cases indices with
+ | none => exact inferInstanceAs (Subsingleton Empty)
+ | some _ => exact inferInstanceAs (Subsingleton Unit)
+
+/-- An accepted port has exactly one local kernel witness even after a parameter
+specialization sending its monomial to zero. -/
+theorem origin_witness_unique
+ (accepted : (emitted B order X choice v older new).isSome = true) :
+ ∃! _w : ((reader).witness (promotedSites v) before new).Choice, True := by
+ obtain ⟨w⟩ := (origin_emitted_iff B order X choice v new before f hf).mp accepted
+ have subs : Subsingleton ((reader).witness (promotedSites v) before new).Choice :=
+ subsingleton_indices (f ∘ Sum.inr) idx
+ exact ⟨w, trivial, fun y _ => subs.elim y w⟩
+
+/-- Per-bin effect in the exact exponent ABI of the selected term reader. -/
+theorem origin_emitted_count (w : ((reader).witness (promotedSites v) before new).Choice)
+ (label : B.Entry) :
+ ((emitted B order X choice v older new).getD []).count (order label) =
+ ((reader).witness (promotedSites v) before new).exponents w label :=
+ emitted_count B order X choice v new before f hf w label
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshVertexAssembly.lean b/lean/OAI/Computability/VPVNP/PairRefreshVertexAssembly.lean
new file mode 100644
index 0000000000..af7a6a8266
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshVertexAssembly.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.PairVertexLevelLocator
+import OAI.Computability.VPVNP.PairVertexStagePrefix
+import OAI.Computability.VPVNP.PairVertexSegmentChain
+
+/-!
+# The refresh role's complete vertex image
+
+The level locator runs first, using the fourteen registers retained by the
+refresh body. The handoff and child scan then fill the private child argument
+buffer. The remainder of the body reuses the saved locator values and returns
+to the DFS continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshVertexAssembly
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage VertexStagePrefix NodeArguments
+open TraversalControllerInputs TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+variable (a : ℕ) (body : Segment) (locator : Fin 14 ↪ Fin body.privateRegs)
+
+/-- The refresh child-argument preparation and its continuation into the resident kernel body. -/
+abbrev childBody := withChildren a body locator
+
+/-- The locator register bank as embedded in the complete refresh vertex segment. -/
+def locatorBank : Fin 14 ↪ Fin (childBody a body locator).privateRegs :=
+ locator.trans (Fin.castAddEmb (ChildCode.RegisterBank.segment a).privateRegs)
+
+/-- One role entry for the locator, argument scan and the kernel body. -/
+def segment := Segment.thenWith VertexLevel.segment (childBody a body locator)
+ (locatorBank a body locator) (Function.Embedding.refl _)
+
+variable {w p r : ℕ} (loc : Fin (segment a body locator).count → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r) (reg : Fin (segment a body locator).privateRegs ↪ Fin r)
+ (done : Fin p) (M : Machine w p r 11)
+
+/-- Program counters of the level-location phase preceding child preparation. -/
+def levelPC := Segment.leftPC VertexLevel.segment (childBody a body locator) loc
+/-- Program counters in the combined child-preparation and resident-body segment following the
+level scan. -/
+def childPC := Segment.rightPC VertexLevel.segment (childBody a body locator) loc
+/-- Program counters of the resident refresh body after the child argument has been installed. -/
+def bodyPC := (childPreparation a body locator).bodyPC (childPC a body locator loc)
+/-- Embedding of the resident refresh body's private registers inside the child-preparation
+segment. -/
+def bodyRegs := Preparation.bodyRegs (ChildCode.RegisterBank.segment a) body reg
+/-- The level locator's registers transported through the resident body's embedding. -/
+def levelRegs := locator.trans (bodyRegs a body locator reg)
+
+/-- Agreement of the installed refresh vertex instructions with the width-resized assembly at
+each placed address. -/
+def Installed : Prop := ∀ i, M.code (loc i) = ((segment a body locator).row loc dfs saved reg done i).resize w
+
+variable (installed : Installed a body locator loc dfs saved reg done M)
+
+include installed in
+theorem linked :
+ (∀ i, M.code (levelPC a body locator loc i) = (VertexLevel.segment.row (levelPC a body locator loc)
+ dfs saved (levelRegs a body locator reg) (childPC a body locator loc (childBody a body locator).entry) i).resize w) ∧
+ (∀ i, M.code (childPC a body locator loc i) = ((childBody a body locator).row (childPC a body locator loc)
+ dfs saved reg done i).resize w) := by
+ exact Segment.split_link VertexLevel.segment (childBody a body locator) (locatorBank a body locator)
+ (Function.Embedding.refl _) loc dfs saved reg done M installed
+
+include installed in
+theorem body_linked (i) : M.code (bodyPC a body locator loc i) = (body.row (bodyPC a body locator loc)
+ dfs saved (bodyRegs a body locator reg) done i).resize w :=
+ (child_rows a body locator M (childPC a body locator loc) dfs saved reg done
+ (linked a body locator loc dfs saved reg done M installed).2).2.2.2 i
+
+include installed in
+/-- Locate the actual noninitial node before reading its children. The locator
+writes only its assigned registers and reaches the first handoff instruction. -/
+theorem locate {m : Memory w} {header first pitch offset cap base : ℕ} {old : TaggedLayer} {ls : List (Fiber w)}
+ (resident : TraversalControllerInputs.Resident M.publicData m header first pitch offset cap base old ls)
+ (j : Fin (old :: ls.map Prod.fst).length) (level : ℕ) (hj : j.val = level+1)
+ (id : Fin (old :: ls.map Prod.fst)[j].layer.count) (c : Config w p r)
+ (entry : c.pc = loc (segment a body locator).entry)
+ (node : (c.reg (dfs 7)).val = address cap (layerBase cap base (old :: ls.map Prod.fst) j) id)
+ (fit : layerBase cap base (old :: ls.map Prod.fst) (ls.length+1) < 2^w) :
+ ∃ out, ChildScan.Prefix M m c out [] (VertexLevel.trace M.publicData m (level+1) (ls.length-(level+1))) ∧
+ out.pc = childPC a body locator loc (childBody a body locator).entry ∧
+ VertexLevel.Located M.publicData m (levelRegs a body locator reg) (c.reg (dfs 7)) level (id.val : Word w) out ∧
+ VertexLevel.Frame (levelRegs a body locator reg) c out :=
+ VertexLevel.run M (levelPC a body locator loc) dfs saved (levelRegs a body locator reg) _
+ (linked a body locator loc dfs saved reg done M installed).1 resident j level hj id c entry node fit
+
+end PairSimulation.RefreshVertexAssembly
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshVertexInputWrites.lean b/lean/OAI/Computability/VPVNP/PairRefreshVertexInputWrites.lean
new file mode 100644
index 0000000000..864d715941
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshVertexInputWrites.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.PairRefreshVertexPrefix
+import OAI.Computability.VPVNP.CompressorFlowFootprint
+
+/-!
+# External write footprint of the refresh vertex inputs
+
+The level locator and each child header probe external memory. The child scan
+stores the guessed half-wire bits in private memory. Its chronological trace,
+including each choice, contains no external write.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open BurstRAM Compression CompressorRecords NodeArguments
+
+variable {w a g : ℕ}
+
+theorem VertexLevel.trace_noWrites (pub : Fin 11 → Word w) (m : Memory w) (level later : ℕ) :
+ SourceTransport.Writes (fun _ => False) (VertexLevel.trace pub m level later) := by
+ intro p v h
+ have scan (n : ℕ) : Event.write p v ∉ VertexLevel.scanEvents pub m level n := by
+ induction n with
+ | zero => simp [VertexLevel.scanEvents, VertexLevel.testEvents]
+ | succ n ih => simp [VertexLevel.scanEvents, VertexLevel.testEvents, ih]
+ simp [VertexLevel.trace, VertexLevel.bootEvents, scan] at h
+
+theorem NodeArguments.ChildHeader.events_noWrites (m : Memory w) (node base : Word w) :
+ SourceTransport.Writes (fun _ => False) (ChildHeader.events m node base) := by
+ intro p v h
+ simp [ChildHeader.events] at h
+
+/-- Every ordered child row only reads the external descriptor and columns.
+The bit payloads may be chosen arbitrarily. -/
+theorem NodeArguments.ChildScan.events_noWrites (X : State a g) (U : IncidenceDirectory w)
+ (m : Memory w) (src : ℕ) (xs : List (ChildScan.Child X)) :
+ SourceTransport.Writes (fun _ => False) (ChildScan.events X U m src xs) := by
+ intro p v
+ induction xs generalizing src with
+ | nil => simp [ChildScan.events]
+ | cons x xs ih =>
+ intro h
+ simp only [ChildScan.events, ChildScan.childEvents, ChildScan.setupEvents, ChildAddress.events,
+ List.mem_append, List.mem_cons, List.not_mem_nil, reduceCtorEq, false_or] at h
+ rcases h with h | tail
+ · obtain ⟨i, _, slot⟩ := List.mem_flatMap.mp h
+ simp only [List.mem_append, List.mem_cons, List.not_mem_nil, reduceCtorEq, false_or] at slot
+ rcases slot with header | bits
+ · cases dir : i.1 <;> simp [FieldGuess.headerEvents, dir] at header
+ · exact (FlowFootprint.bounds_of_noProbes (fun _ => False) (fun _ => False)
+ (PrivateFields.events_work (w := w) .guess (List.ofFn (x.data i))).2).2 p v bits
+ · exact ih (src+1) tail
+
+/-- The complete input trace for a typed old half leaves all external words
+untouched, independently of the values returned by its probes. -/
+theorem RefreshVertexAssembly.inputTrace_noWrites (X : State a g) (site : X.network.Site)
+ (old : X.network.Half site) (U : IncidenceDirectory w) (m : Memory w) (listHead : ℕ)
+ (pub : Fin 11 → Word w) (node : Word w) (level later : ℕ) :
+ SourceTransport.Writes (fun _ => False) (inputTrace a X site old U m listHead pub node level later) := by
+ intro p v h
+ simp only [inputTrace, List.mem_append] at h
+ rcases h with levelRead | handoff | bank | header | scan
+ · exact VertexLevel.trace_noWrites pub m (level+1) later p v levelRead
+ · simp at handoff
+ · simp [List.mem_replicate] at bank
+ · exact ChildHeader.events_noWrites m _ _ p v header
+ · exact ChildScan.events_noWrites X U m listHead _ p v scan
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshVertexPacket.lean b/lean/OAI/Computability/VPVNP/PairRefreshVertexPacket.lean
new file mode 100644
index 0000000000..765733cb45
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshVertexPacket.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.CompressorRefreshMapOperands
+import OAI.Computability.VPVNP.PairSimulationNodeFieldSpace
+import OAI.Computability.VPVNP.PairNodeChildPackets
+import OAI.Computability.VPVNP.PairVertexControl
+
+/-!
+# Resident refresh arguments after guessing the unique child
+
+The one packet of the refresh placement is stored in its old-node frame.
+The newer parent frame and the DFS geometry cells retain their values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshVertexPacket
+
+open BurstRAM BurstRAM.PrivateRAM Compression NodeArguments LocalHistory CompressorRecords.RefreshMapOperands
+open NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {bits a g b l : ℕ} (X : State a g) (site : X.network.Site) (old : X.network.Half site)
+ (A : Arena) (older cap : ℕ) (priv : Word bits → Word bits)
+
+local notation "child" => childNode X older cap site
+local notation "bitsList" => packed X site old
+local notation "afterChild" => storePackets A [Child.packet X older cap (Child.ofHalf X site old)] priv
+
+theorem stored : afterChild = PrivateFields.storeBits (A.base child) bitsList priv := by
+ change PrivateFields.storeBits (A.base child) ((Child.ofHalf X site old).payload X) priv = _
+ rw [Child.payload_ofHalf]
+
+theorem fields (fit : A.base child+(bitsList).length ≤ 2^bits) :
+ NodeFields A child X site old afterChild := by
+ rw [stored]
+ exact nodeFields_store A child X site old priv fit
+
+theorem outside (fit : A.base child+(bitsList).length ≤ 2^bits) (q : Word bits)
+ (sep : q.val < A.base child ∨ A.base child+(bitsList).length ≤ q.val) : afterChild q = priv q := by
+ rw [stored]
+ exact PrivateFields.storeBits_outside _ _ _ q fit sep
+
+/-- A child preceding its parent cannot overwrite any of the parent's bits. -/
+theorem parent_fields (Y : State b l) (u : Y.network.Site) (new : Y.network.Half u) (parent : ℕ)
+ (before : child < parent) (width : (bitsList).length ≤ A.stride)
+ (fit : A.base parent + (packed Y u new).length ≤ 2^bits)
+ (held : NodeFields A parent Y u new priv) : NodeFields A parent Y u new afterChild := by
+ have endBefore := (Nat.add_le_add_left width _).trans (A.before before)
+ have childFit := endBefore.trans ((Nat.le_add_right ..).trans fit)
+ intro dir j i
+ let pos := A.fieldAddress Y u parent dir j + i.val
+ have within : pos < 2^bits := (Nat.add_lt_add_left i.isLt _).trans_le ((field_end_le Y u new A parent dir j).trans fit)
+ have starts : A.base parent ≤ pos := (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ have word : (pos : Word bits).val = pos := Nat.mod_eq_of_lt within
+ exact (outside X site old A older cap priv childFit _ (Or.inr (word ▸ endBefore.trans starts))).trans (held dir j i)
+
+/-- The retained stack-end pointer lies below the packet; both geometry slots
+lie above it. The predicate therefore holds after the native child stores. -/
+theorem geometry {endAddr : ℕ} (G offset hist : Word bits)
+ (resident : VertexImage.ResidentGeometry (DFS.scratch endAddr priv) G offset hist)
+ (early : endAddr < A.base child) (role : A.base child+(bitsList).length ≤ (G+10).val)
+ (histogram : A.base child+(bitsList).length ≤ (G+11).val) :
+ VertexImage.ResidentGeometry (DFS.scratch endAddr afterChild) G offset hist := by
+ have fit := role.trans (G+10).isLt.le
+ have endVal : (endAddr : Word bits).val = endAddr := Nat.mod_eq_of_lt resident.endFit
+ have keep (q : Word bits) (atEnd : endAddr ≤ q.val) (sep : q.val < A.base child ∨ A.base child+(bitsList).length ≤ q.val) :
+ rawScratch (DFS.scratch endAddr afterChild) q = rawScratch (DFS.scratch endAddr priv) q := by
+ simpa only [rawScratch,dite_eq_left atEnd,DFS.scratch] using outside X site old A older cap priv fit q sep
+ exact ⟨resident.endFit,resident.roleAbove,resident.histAbove,
+ (keep _ endVal.ge (Or.inl (endVal.trans_lt early))).trans resident.pointer,
+ (keep _ resident.roleAbove (Or.inr role)).trans resident.role,
+ (keep _ resident.histAbove (Or.inr histogram)).trans resident.histogram⟩
+
+end PairSimulation.RefreshVertexPacket
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshVertexPrefix.lean b/lean/OAI/Computability/VPVNP/PairRefreshVertexPrefix.lean
new file mode 100644
index 0000000000..a8a581a085
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshVertexPrefix.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.PairRefreshVertexAssembly
+import OAI.Computability.VPVNP.PairRefreshVertexPacket
+import OAI.Computability.VPVNP.PairVertexStageRun
+import OAI.Computability.VPVNP.PairVertexStageChildren
+
+/-!
+# Locating and decoding the unique child at a refresh visit
+
+The raw DFS node selects a level header. The actual child directory and singleton
+preimage row supply the address of the older node. A complete guess stores its
+half-wire values in that node's frame and reaches the refresh kernel.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshVertexAssembly
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage VertexStagePrefix NodeArguments NodeArguments.ChildScan
+open TraversalControllerInputs TraversalRoles TraversalRows Compression CompressorRecords
+open scoped Fin.CommRing
+
+variable {w p r g : ℕ} (a : ℕ) (body : Segment) (locator : Fin 14 ↪ Fin body.privateRegs)
+ (loc : Fin (segment a body locator).count → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (segment a body locator).privateRegs ↪ Fin r) (done : Fin p) (M : Machine w p r 11)
+ (installed : Installed a body locator loc dfs saved reg done M)
+ (X : State a g) (site : X.network.Site) (old : X.network.Half site)
+ (U : IncidenceDirectory w) (m : Memory w) (A : Arena) (older cap listHead : ℕ)
+
+local notation "child" => childNode X older cap site
+local notation "half" => Child.ofHalf X site old
+local notation "packet" => Child.packet X older cap half
+local notation "args" => packed X site old
+local notation "bank" => levelRegs a body locator reg
+local notation "P₀" => childPreparation a body locator
+local notation "cp" => childPC a body locator loc
+
+/-- Input-stage trace through level location, register handoff, child-header reads, and the
+scan of the single old half-wire packet. -/
+noncomputable def inputTrace (pub : Fin 11 → Word w) (node : Word w) (level later : ℕ) :=
+ VertexLevel.trace pub m (level+1) later ++
+ (List.replicate 2 (.tick : Event w) ++
+ (List.replicate (2^a) (.tick : Event w) ++
+ (ChildHeader.events m node (levelHead pub m level+14) ++ ChildScan.events X U m listHead [half])))
+
+/-- Exact work and external probes before entry to the resident map. Only the
+older half-wire packet is taken from the branch bitstream. -/
+theorem inputTrace_cost (pub : Fin 11 → Word w) (node : Word w) (level later : ℕ) :
+ let es := inputTrace a X site old U m listHead pub node level later
+ es.length = 63 + 6*later + 16*2^a + 6*(args).length ∧
+ countProbes es = 15 + later + 3*2^a ∧ choiceBits es = args := by
+ intro es
+ obtain ⟨ll,lp,lc⟩ := VertexLevel.trace_cost pub m (level+1) later
+ obtain ⟨hp,hl,hc⟩ := ChildHeader.cost m node (levelHead pub m level+14)
+ obtain ⟨cc,cp',cl⟩ := events_cost X U m listHead [half]
+ simp only [List.length_cons,List.length_nil,List.flatMap_cons,List.flatMap_nil,List.append_nil,
+ Child.payload_ofHalf] at cc cp' cl
+ have tick (n : ℕ) : countProbes (List.replicate n (.tick : Event w)) = 0 ∧
+ choiceBits (List.replicate n (.tick : Event w)) = [] := by
+ induction n with
+ | zero => exact ⟨rfl,rfl⟩
+ | succ n ih => simpa only [List.replicate_succ,countProbes,choiceBits] using ih
+ simp only [es,inputTrace,List.length_append,List.length_replicate,countProbes_append,
+ PrimedInputRAM.Flow.choiceBits_append,(tick _).1,(tick _).2,lc,hc,cc,cp',lp,hp,hl,ll,cl,List.nil_append]
+ constructor
+ · omega
+ · exact ⟨by omega, trivial⟩
+
+include installed in
+/-- Reach the selected refresh body with its locator intact and with all of the
+guessed child fields installed in the older node's own private memory. -/
+theorem load_child {header first pitch offset base : ℕ} {initial : TaggedLayer} {ls : List (Fiber w)}
+ (heads : Resident M.publicData m header first pitch offset cap base initial ls)
+ (j : Fin (initial :: ls.map Prod.fst).length) (level : ℕ) (hj : j.val = level+1)
+ (id : Fin (initial :: ls.map Prod.fst)[j].layer.count) (c : Config w p r)
+ (entry : c.pc = loc (segment a body locator).entry)
+ (node : (c.reg (dfs 7)).val = address cap (layerBase cap base (initial :: ls.map Prod.fst) j) id)
+ (endFit : layerBase cap base (initial :: ls.map Prod.fst) (ls.length+1) < 2^w)
+ (fields : (directory a older cap A U).Stored m (levelHead M.publicData m level + 14))
+ (row : DFS.Row m (c.reg (dfs 7)).val listHead [(child : Word w)])
+ (rep : U.ActualColumns X m) (strideFit : cap+2 < 2^w)
+ (nodeFit : child < 2^w) (packetFit : A.base child+(args).length < 2^w) :
+ ∃ out, ChildScan.Prefix M m c out args
+ (inputTrace a X site old U m listHead M.publicData (c.reg (dfs 7)) level (ls.length-(level+1))) ∧
+ out.pc = bodyPC a body locator loc body.entry ∧
+ VertexLevel.Located M.publicData m bank (c.reg (dfs 7)) level (id.val : Word w) out ∧
+ out.privateMem = storePackets A [packet] c.privateMem ∧ out.persistent = c.persistent ∧
+ ∀ q, q ∉ Set.range reg → out.reg q = c.reg q := by
+ obtain ⟨mid,first,atChild,located,frame⟩ := locate a body locator loc dfs saved reg done M installed
+ heads j level hj id c entry node endFit
+ have row' : DFS.Row m (mid.reg (bank 0)).val listHead
+ ([half].map fun q => (childNode X older cap q.site : Word w)) := located.state.node.symm ▸ row
+ have node' : ∀ q ∈ [half], childNode X older cap q.site < 2^w := by
+ intro q h; exact List.mem_singleton.mp h ▸ nodeFit
+ have fit' : ∀ q ∈ [half], A.base (childNode X older cap q.site) + (q.payload X).length < 2^w := by
+ intro q h; rw [List.mem_singleton.mp h,Child.payload_ofHalf]; exact packetFit
+ obtain ⟨out,ep,pers,mem,_,kept,scan⟩ := VertexStagePrefix.child_run body locator M cp dfs saved reg done
+ (linked a body locator loc dfs saved reg done M installed).2 rep [half] listHead mid atChild
+ (located.oldFields.symm ▸ fields) row' strideFit node' fit'
+ have nodeWord : mid.reg (locatorRegs body locator reg 0) = c.reg (dfs 7) := located.state.node
+ have dirWord : mid.reg (locatorRegs body locator reg 12) = levelHead M.publicData m level+14 := located.oldFields
+ have bodyPath : ChildScan.Prefix M m mid out args (List.replicate 2 .tick ++ (List.replicate (2^a) .tick ++
+ (ChildHeader.events m (c.reg (dfs 7)) (levelHead M.publicData m level+14) ++ ChildScan.events X U m listHead [half]))) := by
+ simpa only [List.map_cons,List.map_nil,List.flatMap_cons,List.flatMap_nil,List.append_nil,Child.packet,
+ Child.payload_ofHalf,nodeWord,dirWord] using scan
+ refine ⟨out,first.trans bodyPath,ep,?_,?_,pers.trans frame.persistent,?_⟩
+ · apply VertexStageDispatch.retainLocated located
+ intro i
+ exact kept _ (fun ⟨j,eqn⟩ => Preparation.disjoint reg j (locator i) eqn)
+ · rw [mem,frame.privateMem]; rfl
+ · intro q hq
+ exact (kept q (fun ⟨_,eqn⟩ => hq ⟨_,eqn⟩)).trans (frame.outside q (fun ⟨_,eqn⟩ => hq ⟨_,eqn⟩))
+
+
+include installed in
+/-- A truncated packet rejects in the actual child stage, independently of the continuation. -/
+theorem reject_short {header first pitch offset base : ℕ} {initial : TaggedLayer} {ls : List (Fiber w)}
+ (heads : Resident M.publicData m header first pitch offset cap base initial ls)
+ (j : Fin (initial :: ls.map Prod.fst).length) (level : ℕ) (hj : j.val = level+1)
+ (id : Fin (initial :: ls.map Prod.fst)[j].layer.count) (c : Config w p r)
+ (entry : c.pc = loc (segment a body locator).entry)
+ (node : (c.reg (dfs 7)).val = address cap (layerBase cap base (initial :: ls.map Prod.fst) j) id)
+ (endFit : layerBase cap base (initial :: ls.map Prod.fst) (ls.length+1) < 2^w)
+ (fields : (directory a older cap A U).Stored m (levelHead M.publicData m level + 14))
+ (row : DFS.Row m (c.reg (dfs 7)).val listHead [(child : Word w)])
+ (rep : U.ActualColumns X m) (strideFit : cap+2 < 2^w)
+ (nodeFit : child < 2^w) (packetFit : A.base child+(args).length < 2^w)
+ (bs : List Bool) (short : bs.length < (args).length) : ¬ DFS.Returns M c m bs := by
+ obtain ⟨mid,first,atChild,located,_⟩ := locate a body locator loc dfs saved reg done M installed
+ heads j level hj id c entry node endFit
+ have row' : DFS.Row m (mid.reg (bank 0)).val listHead
+ ([half].map fun q => (childNode X older cap q.site : Word w)) := located.state.node.symm ▸ row
+ have node' : ∀ q ∈ [half], childNode X older cap q.site < 2^w := by
+ intro q h; exact List.mem_singleton.mp h ▸ nodeFit
+ have fit' : ∀ q ∈ [half], A.base (childNode X older cap q.site) + (q.payload X).length < 2^w := by
+ intro q h; rw [List.mem_singleton.mp h,Child.payload_ofHalf]; exact packetFit
+ have tooShort : bs.length < ([half].flatMap (Child.payload X)).length := by
+ simpa only [List.flatMap_cons,List.flatMap_nil,List.append_nil,Child.payload_ofHalf] using short
+ have fail := VertexStagePrefix.child_reject body locator M cp dfs saved reg done
+ (linked a body locator loc dfs saved reg done M installed).2 rep [half] listHead mid atChild
+ (located.oldFields.symm ▸ fields) row' strideFit node' fit' bs tooShort
+ exact fun accept => fail ((first.returns bs).mp accept)
+
+end PairSimulation.RefreshVertexAssembly
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshVertexReads.lean b/lean/OAI/Computability/VPVNP/PairRefreshVertexReads.lean
new file mode 100644
index 0000000000..4804d50bd8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshVertexReads.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.PairRefreshVertexPrefix
+import OAI.Computability.VPVNP.PairShrinkRoleChildReads
+import OAI.Computability.VPVNP.PairVertexLevelReads
+
+/-!
+# External read footprint of the refresh locator and singleton child reader
+
+The locator reads the header and level scalars. The child reads its descriptor,
+the old directory, and the incoming and width arrays. The two handoff copies
+and the ordinal-bank initializer use only private registers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshVertexAssembly
+
+open BurstRAM Compression CompressorRecords NodeArguments NodeArguments.ChildScan
+open TraversalControllerInputs TraversalRoles ShrinkRole.ChildArguments
+open scoped Fin.CommRing
+
+variable {w a g : ℕ} {pub : Fin 11 → Word w} {m : Memory w}
+ {head first pitch offset cap base : ℕ} {initial : TaggedLayer} {ls : List (Fiber w)}
+
+theorem inputTrace_reads (heads : Resident pub m head first pitch offset cap base initial ls)
+ (beforeH : ∀ i ≤ ls.length, first+i*pitch+28 ≤ head)
+ (X : State a g) (site : X.network.Site) (old : X.network.Half site) (U : IncidenceDirectory w)
+ (listHead : ℕ) (node : Word w) (level later : ℕ) (live : level+1+later ≤ ls.length)
+ (rep : U.ActualColumns X m) (col : ColumnsBelow U X head)
+ (parent : node.val+1 < head) (row : listHead+1 ≤ head) :
+ SourceTransport.Reads (TerminalLink.workerCell (TerminalLink.header pub))
+ (inputTrace a X site old U m listHead pub node level later) := by
+ let H := TerminalLink.header pub
+ have hval : H.val = head := (congrArg Fin.val heads.header).trans (Nat.mod_eq_of_lt (by have := heads.headerFits; omega))
+ have room : H.val + 32 ≤ 2^w := hval ▸ heads.headerFits
+ have lfit := heads.levelFits level (by omega)
+ have oldBase : (levelHead pub m level+14).val = first+level*pitch+14 := by
+ rw [levelHead, terminal_read heads 16 (by decide), terminal_read heads 17 (by decide),
+ heads.firstHead,heads.levelPitch,show (14 : Word w) = ((14 : ℕ) : Word w) from rfl,
+ ← Nat.cast_mul,← Nat.cast_add,← Nat.cast_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega)]
+ have headerBound : (levelHead pub m level+14).val + 6 < head := by
+ rw [oldBase]; have := beforeH level (by omega); omega
+ have childReads := trace_reads_below rep col node (levelHead pub m level+14) listHead
+ [Child.ofHalf X site old] parent headerBound row
+ have childWorker := worker_reads_of_below H room (hval ▸ childReads)
+ have locate := VertexLevel.trace_worker_reads heads beforeH (level+1) later live
+ intro q v hq
+ rcases List.mem_append.mp hq with h | h
+ · exact locate q v h
+ · rcases List.mem_append.mp h with h | h
+ · simp at h
+ · rcases List.mem_append.mp h with h | h
+ · simp [List.mem_replicate] at h
+ · exact childWorker q v h
+
+end PairSimulation.RefreshVertexAssembly
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairRefreshVertexRun.lean b/lean/OAI/Computability/VPVNP/PairRefreshVertexRun.lean
new file mode 100644
index 0000000000..d1af9ad0cb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairRefreshVertexRun.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.PairRefreshVertexPrefix
+import OAI.Computability.VPVNP.PairRefreshTraversalMapBody
+
+/-!
+# Executing a complete refresh role from the popped DFS node
+
+The installed finite role locates the selected level, guesses the unique older
+half-wire packet, and runs the resident kernel on it and the independent newer
+half. The role either returns to the DFS or reaches a rejecting opcode. All
+histogram additions use the fixed global ordering of refresh scalar entries.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshVertex
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh
+open CompressorRecords CompressorRecords.PortRefresh CompressorRecords.RefreshMapOperands
+open VertexImage NodeArguments NodeArguments.ChildScan TraversalControllerInputs TraversalRoles TraversalRows
+open NewSlots MotifConversion LocalHistory
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {t hist : ℕ}
+ (ties : Fin t ≃ Tie (2^S.portExponent)) (stride : ℕ) (order : B.Entry ≃ Fin hist)
+local notation "body" => TraversalPlan.body B ties stride order
+local notation "locator" => TraversalPlan.locatorBank B ties stride order
+
+/-- The complete native refresh vertex segment at the schedule's port exponent, with the chosen
+resident body and locator registers. -/
+noncomputable def refreshSegment := RefreshVertexAssembly.segment S.portExponent body locator
+
+variable {bits pcs regs g : ℕ} (loc : Fin (refreshSegment B ties stride order).count → Fin pcs)
+ (dfs : Fin 9 ↪ Fin regs) (saved : Saved ↪ Fin regs)
+ (reg : Fin (refreshSegment B ties stride order).privateRegs ↪ Fin regs) (done : Fin pcs)
+ (M : Machine bits pcs regs 11) (X : State S.portExponent (S.portExponent+g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2^S.portExponent)) (degree n rowEnd : ℕ)
+ (U V : IncidenceDirectory bits) (m : Memory bits) (start older listHead : ℕ)
+ (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order))
+ B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites v))
+
+local notation "D" => 2^S.portExponent
+local notation "H" => 2^S.expanderExponent
+local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order)
+local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh S.port_order (And.right S.degree_bounds) choice
+local notation "O" => NewSlots.sites X.baseIndex (bitWordFinEquiv g)
+local notation "R" => TerminalLayout.privateRegions degree n rowEnd hist
+local notation "A" => LeafArena.Regions.arguments R
+local notation "histBase" => LeafArena.Regions.histBase R
+local notation "cap" => BlockSchedule.Templates.recordLimit B
+local notation "child" => childNode X older cap (oldSite X v)
+local notation "oldBits" => packed X (oldSite X v) old
+local notation "childHalf" => Child.ofHalf X (oldSite X v) old
+local notation "pkt" => Child.packet X older cap childHalf
+local notation "E₀" => entryInput B X choice v old new
+local notation "copies" => repetitions B.refresh (EntryInput.demand E₀)
+local notation "ws" => groupedWidths (bitWordFinEquiv _) (splitWidths X)
+local notation "perm" => oldPortMatching (splitSlots X) (bitWordFinEquiv _)
+local notation "wo" => ws (v,Prod.snd v)
+local notation "wi" => ws (Equiv.symm perm (v,Prod.snd v))
+local notation "bodyLoc" => RefreshVertexAssembly.bodyPC S.portExponent body locator loc
+local notation "bodyBank" => RefreshVertexAssembly.bodyRegs S.portExponent body locator reg
+local notation "K₀" => TraversalPlan.budget B ties stride order
+
+set_option maxHeartbeats 1200000 in
+/-- The actual branch path and private updates of a refresh vertex. The fixed
+cost includes one header scan and one input packet before the motif. -/
+theorem run {header first pitch offset base : ℕ} {initial : TaggedLayer} {ls : List (Fiber bits)}
+ (installed : ∀ i, M.code (loc i) = ((refreshSegment B ties stride order).row loc dfs saved reg done i).resize bits)
+ (apartD : ∀ i j, reg i ≠ dfs j) (apartS : ∀ i j, reg i ≠ saved j)
+ (heads : Resident M.publicData m header first pitch offset cap base initial ls)
+ (j : Fin (initial :: ls.map Prod.fst).length) (level : ℕ) (hj : j.val = level+1)
+ (id : Fin (initial :: ls.map Prod.fst)[j].layer.count) (selected : id.val = (O v).val)
+ (c : Config bits pcs regs) (entry : c.pc = loc (refreshSegment B ties stride order).entry)
+ (node : (c.reg (dfs 7)).val = address cap (layerBase cap base (initial :: ls.map Prod.fst) j) id)
+ (fitRows : layerBase cap base (initial :: ls.map Prod.fst) (ls.length+1) < 2^bits)
+ (fields : (directory S.portExponent older cap A U).Stored m (levelHead M.publicData m level+14))
+ (row : DFS.Row m (c.reg (dfs 7)).val listHead [word child])
+ (levelData : TraversalHeaders.Geometry (Fintype.card X.Base) g (levelHead M.publicData m level).val
+ (levelHead M.publicData m (level+1)).val start A U V m)
+ {fit : Fintype.card X.Base*D*2^g*D ≤ 2^bits}
+ (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m)
+ (oldCols : U.ActualColumns X m) (newCols : V.ActualColumns Y m)
+ (newData : NodeFields A (c.reg (dfs 7)).val Y (promotedSites v) new c.privateMem)
+ {G role : W bits} (stack : c.reg (dfs 6) = word n)
+ (geometry : ResidentGeometry (DFS.scratch n c.privateMem) G role (word histBase))
+ (roleAfter : histBase ≤ (G+10).val) (histAfter : histBase ≤ (G+11).val)
+ (positive : 0 < child) (before : child < (c.reg (dfs 7)).val) (parentBound : (c.reg (dfs 7)).val < rowEnd)
+ (oldDegree : D ≤ degree) (newDegree : 2^(S.degreeExponent 0) ≤ degree)
+ (oldWidth : X.maxWireWidth ≤ n) (newWidth : (Y).maxWireWidth ≤ n)
+ (copyBound : copies ≤ n) (large : MapCallWords.headCapacity D H+12 ≤ n) (five : 5 ≤ n)
+ (capacity : MapWorkspace.Capacity B.refresh bits n (R).cacheBase)
+ (strideFit : cap+2 < 2^bits) (lanes : 2^g < 2^bits) (wide : D < 2^bits)
+ (tableWidth : MapConstants.widthThreshold B.refresh ≤ bits) :
+ let labels := TraversalPlan.emitted B order X choice v old new
+ let later := ls.length-(level+1)
+ ∃ out es, ChildScan.Prefix M m c out oldBits es ∧ choiceBits es = oldBits ∧
+ es.length ≤ 63+6*later+16*D+6*(oldBits).length+K₀*(wo+wi+copies+1) ∧
+ countProbes es ≤ 15+later+3*D+K₀ ∧
+ (if labels.isSome then out.pc = done else M.code out.pc = .reject) ∧
+ out.persistent = c.persistent ∧ (∀ q, q ∉ Set.range reg → out.reg q = c.reg q) ∧
+ (∀ q : W bits, q.val < histBase+hist+12+2*n → (∀ l : Fin hist, q ≠ word (histBase+l.val)) →
+ out.privateMem q = storePackets A [pkt] c.privateMem q) ∧
+ ∀ l : Fin hist, out.privateMem (word (histBase+l.val)) = c.privateMem (word (histBase+l.val)) +
+ ((labels.getD []).count l : W bits) := by
+ intro labels later
+ let parent := (c.reg (dfs 7)).val
+ have childBound := before.trans parentBound
+ have oldEnd := TraversalGeometry.argument_end degree n rowEnd hist X (oldSite X v) old child childBound oldDegree oldWidth
+ have newEnd := TraversalGeometry.argument_end degree n rowEnd hist Y (promotedSites v) new parent parentBound newDegree newWidth
+ have hhist : histBase + hist ≤ (R).cacheBase := Nat.le_add_right ..
+ have histFits := hhist.trans_lt capacity.room
+ have childFit : (A).base child+(oldBits).length < 2^bits := oldEnd.trans_lt ((Nat.le_add_right ..).trans_lt histFits)
+ have parentFit := newEnd.trans ((Nat.le_add_right ..).trans histFits.le)
+ have strideBound : (oldBits).length ≤ (A).stride :=
+ (packed_length_le X (oldSite X v) old).trans ((Nat.mul_le_mul (Nat.mul_le_mul_left 2 oldDegree) oldWidth).trans (Nat.le_succ _))
+ have early : n < (A).base child := by
+ change n < n+child*(2*degree*n+1)
+ exact Nat.lt_add_of_pos_right (Nat.mul_pos positive (Nat.succ_pos _))
+ obtain ⟨mid,front,atBody,located,mem,per,regs'⟩ := RefreshVertexAssembly.load_child S.portExponent body locator loc dfs saved
+ reg done M installed X (oldSite X v) old U m A older cap listHead heads j level hj id c entry node fitRows fields row
+ oldCols strideFit (before.trans (c.reg (dfs 7)).isLt) childFit
+ have geom' := RefreshVertexPacket.geometry X (oldSite X v) old A older cap c.privateMem G role (word histBase)
+ geometry early (oldEnd.trans roleAfter) (oldEnd.trans histAfter)
+ have old' := RefreshVertexPacket.fields X (oldSite X v) old A older cap c.privateMem childFit.le
+ have new' := RefreshVertexPacket.parent_fields X (oldSite X v) old A older cap c.privateMem Y (promotedSites v)
+ new parent before strideBound parentFit newData
+ have stack' := (regs' (dfs 6) (fun ⟨i,e⟩ => apartD i 6 e)).trans stack
+ have siteFit : id.val < 2^bits := by
+ have startBefore : id.val ≤ address cap (layerBase cap base (initial :: ls.map Prod.fst) j) id :=
+ (Nat.le_mul_of_pos_left _ (by omega : 0 < cap+2)).trans (Nat.le_add_left ..)
+ exact startBefore.trans_lt (node ▸ (c.reg (dfs 7)).isLt)
+ have site' := (congrArg Fin.val located.owner).trans ((Nat.mod_eq_of_lt siteFit).trans selected)
+ obtain ⟨out,es,bodyRun,len,probes,choices,branch,pers,frame,kept,hits⟩ :=
+ TraversalPlan.map_body B ties stride order bodyLoc dfs saved bodyBank done M X choice v degree n rowEnd U V m
+ start parent child listHead (levelHead M.publicData m level).val (levelHead M.publicData m (level+1)).val old new
+ (RefreshVertexAssembly.body_linked S.portExponent body locator loc dfs saved reg done M installed)
+ (fun _ i => apartD _ i) (fun _ i => apartS _ i) mid atBody stack' (mem ▸ geom')
+ (congrArg Fin.val located.oldHead) (congrArg Fin.val located.state.current) site' (congrArg Fin.val located.state.node)
+ levelData row lanes stored oldCols newCols (mem ▸ old') (mem ▸ new') childBound parentBound oldDegree newDegree
+ oldWidth newWidth copyBound large five capacity wide tableWidth
+ let events := RefreshVertexAssembly.inputTrace S.portExponent X (oldSite X v) old U m listHead M.publicData
+ (c.reg (dfs 7)) level later
+ obtain ⟨time,cost,bs⟩ := RefreshVertexAssembly.inputTrace_cost S.portExponent X (oldSite X v) old U m listHead
+ M.publicData (c.reg (dfs 7)) level later
+ have join : ChildScan.Prefix M m c out oldBits (events++es) := by simpa only [List.append_nil] using front.trans bodyRun
+ refine ⟨out,events++es,join,?_,?_,?_,branch,pers.trans per,?_,?_,?_⟩
+ ·
+ rw [PrimedInputRAM.Flow.choiceBits_append,choices,List.append_nil]; exact bs
+ · rw [List.length_append]; exact Nat.add_le_add time.le len
+ · rw [countProbes_append]; exact Nat.add_le_add cost.le probes
+ · intro q hq
+ exact (frame q (fun _ eqn => hq ⟨_,eqn.symm⟩)).trans (regs' q hq)
+ · intro q hq hn
+ exact (kept q hq hn).trans (congrFun mem q)
+ · intro l
+ have hval : (word (bits := bits) (histBase+l.val)).val = histBase+l.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left l.isLt _).trans histFits)
+ have oldAt := RefreshVertexPacket.outside X (oldSite X v) old A older cap c.privateMem childFit.le
+ (word (histBase+l.val)) (Or.inr ((oldEnd.trans (Nat.le_add_right histBase l.val)).trans hval.symm.le))
+ exact (hits l).trans (congrArg (fun q => q+_) ((congrFun mem _).trans oldAt))
+
+end PairSimulation.RefreshVertex
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairResidentFrameColumn.lean b/lean/OAI/Computability/VPVNP/PairResidentFrameColumn.lean
new file mode 100644
index 0000000000..66eef89871
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairResidentFrameColumn.lean
@@ -0,0 +1,429 @@
+import OAI.Computability.VPVNP.CompressorRegisterSetupClock
+import OAI.Computability.VPVNP.PairSimulationReverseSlices
+import OAI.Computability.VPVNP.PairSimulationSliceReads
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+
+/-!
+# Native copying of all intervals of a resident operand
+
+Each fixed local interval has a read-only pointer calculation, the three-word
+slice header and a private copy loop. The direction selects which of the two
+stored offsets belongs to the input. The instruction table is fixed before
+the widths, descriptor addresses, or branch bits are supplied.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentColumn
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe
+open scoped Fin.CommRing
+open private reads_append from OAI.Computability.VPVNP.CompressorFormulaFootprint
+
+/-- A physical copy uses three dynamic pointers and a statically known orientation. -/
+structure Setup where
+ /-- Expression that computes the base address of the source interval in private memory. -/
+ source : Expr
+ /-- Expression that computes the destination buffer's base address before the header supplies
+ its offset. -/
+ destination : Expr
+ /-- Expression that locates the first word of the external three-word slice header. -/
+ frame : Expr
+ /-- When true, apply the first stored offset to the destination and the second to the source.
+ When false, apply them in source–destination order. -/
+ reverse : Bool
+
+/-- Initialize the six header registers in order with the source base, zero, destination base,
+unit increment, zero and frame address. -/
+def Setup.operands (s : Setup) : Fin 6 → Expr :=
+ ![s.source, .lit 0, s.destination, .lit 1, .lit 0, s.frame]
+
+/-- One resident copy interval, described by its two private buffer bases, its external header
+address, the offset in each buffer and the bits to transfer. -/
+structure Row where
+ /-- Private buffer base to which the source offset is added before reading the first bit. -/
+ source : ℕ
+ /-- Base of the private buffer into which the row's bits are copied. -/
+ destination : ℕ
+ /-- External address of this row's offset pair, followed by its length word at `frame + 2`. -/
+ frame : ℕ
+ /-- Number of private cells from the source base to the first bit of this slice. -/
+ sourceOffset : ℕ
+ /-- Number of private cells from the destination base to the start of the copied slice. -/
+ targetOffset : ℕ
+ /-- Payload in increasing address order. Its length is the number of private cells to copy. -/
+ bits : List Bool
+
+/-- Store the row's payload one bit per private cell, starting at `destination + targetOffset`. -/
+def Row.write {w : ℕ} (row : Row) (priv : Word w → Word w) :=
+ PrivateFields.storeBits (row.destination + row.targetOffset) row.bits priv
+
+/-- The private source cells starting at `source + sourceOffset` contain the word encodings of
+the row's bits in order. -/
+def Row.reads {w : ℕ} (row : Row) (priv : Word w → Word w) : Prop :=
+ ∀ i : Fin row.bits.length, priv ((row.source + row.sourceOffset + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w row.bits[i.val]
+
+variable {N w p r k : ℕ}
+
+/-- The setup expressions evaluate to the row's three pointers and the external header fits the
+address space and records the payload length. For a nonempty slice, its two offset words
+agree with the setup's orientation. -/
+structure Row.Recorded (row : Row) (s : Setup) (pub : Fin 5 → Word w)
+ (state : Word w) (mem : Memory w) : Prop where
+ source : s.source.eval pub state mem = (row.source : Word w)
+ destination : s.destination.eval pub state mem = (row.destination : Word w)
+ frame : s.frame.eval pub state mem = (row.frame : Word w)
+ frameFit : row.frame + 2 < 2 ^ w
+ length : (mem (row.frame + 2)).val = row.bits.length
+ offsets : 0 < row.bits.length → (mem row.frame).val =
+ (if s.reverse then row.targetOffset else row.sourceOffset) ∧
+ (mem (row.frame + 1)).val = (if s.reverse then row.sourceOffset else row.targetOffset)
+
+/-- The physical read addresses needed by one compiled setup and its slice header. -/
+structure Row.ReadSafe (row : Row) (setup : Setup) (allowed : ℕ → Prop)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w) : Prop where
+ loads : ∀ j, (setup.operands j).ReadsFrom allowed pub state mem
+ frame : ∀ j : Fin 3, allowed (row.frame + j.val)
+
+private theorem readSafe_true (row : Row) (setup : Setup)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w) :
+ row.ReadSafe setup (fun _ ↦ True) pub state mem := by
+ have all (e : Expr) : e.ReadsFrom (fun _ ↦ True) pub state mem := by
+ induction e with
+ | lit | publicWord | state => trivial
+ | load _ h => exact ⟨h, trivial⟩
+ | binary _ _ _ h₁ h₂ => exact ⟨h₁, h₂⟩
+ exact ⟨fun j ↦ all _, fun _ ↦ trivial⟩
+
+private theorem frame_reads (row : Row) (setup : Setup) (allowed : ℕ → Prop)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+ (safe : row.ReadSafe setup allowed pub state mem) (fit : row.frame + 2 < 2 ^ w) :
+ SourceTransport.Reads allowed (PrivateSlices.frameEvents mem row.frame row.bits) := by
+ apply PrivateSlices.frameEvents_reads
+ · rw [show (row.frame : Word w).val = row.frame from Nat.mod_eq_of_lt (by omega)]
+ exact safe.frame 0
+ · rw [← Nat.cast_add_one, show ((row.frame + 1 : ℕ) : Word w).val = row.frame + 1 from
+ Nat.mod_eq_of_lt (by omega)]
+ exact safe.frame 1
+ · rw [← Nat.cast_add_one, ← Nat.cast_add_one,
+ show ((row.frame + 1 + 1 : ℕ) : Word w).val = row.frame + 1 + 1 from Nat.mod_eq_of_lt fit]
+ exact safe.frame 2
+
+/-- The pivot separates source and destination buffers. Each nonempty source interval ends at
+or before the pivot, the destination starts at or above it, and each nonempty destination
+interval ends strictly below the word modulus. -/
+structure Row.Fits (row : Row) (w pivot : ℕ) : Prop where
+ old : 0 < row.bits.length → row.source + row.sourceOffset + row.bits.length ≤ pivot
+ new : pivot ≤ row.destination
+ room : 0 < row.bits.length → row.destination + row.targetOffset + row.bits.length < 2 ^ w
+
+private theorem reads_write (x y : Row) (pivot : ℕ) (hx : x.Fits w pivot)
+ (hy : y.Fits w pivot) (priv : Word w → Word w) (read : y.reads priv) :
+ y.reads (x.write priv) := by
+ intro j
+ by_cases h : x.bits.length = 0
+ · have nil := List.length_eq_zero_iff.mp h
+ simpa [Row.write, nil, PrivateFields.storeBits] using read j
+ have fit := hx.room (Nat.pos_of_ne_zero h)
+ have old := hy.old (Nat.zero_lt_of_lt j.isLt)
+ have addr := hx.new
+ have hv : ((y.source + y.sourceOffset + j.val : ℕ) : Word w).val =
+ y.source + y.sourceOffset + j.val := Nat.mod_eq_of_lt (by have := j.isLt; omega)
+ rw [Row.write, PrivateFields.storeBits_outside _ _ _ _ fit.le (Or.inl (by rw [hv]; omega))]
+ exact read j
+
+variable (S : Fin N → Setup)
+
+/-- Number of compiled instructions that evaluate the six setup operands for row `i`. -/
+def setCount (i : Fin N) := (RegisterSetup.lines (S i).operands).length
+
+/-- Instruction labels indexed by row, with separate ranges for its variable-length setup,
+eleven header instructions and seven private copy instructions. -/
+abbrev Label := (i : Fin N) × (Fin (setCount S i) ⊕ Fin 11 ⊕ Fin 7)
+
+/-- Program counter for setup line `j` of row `i`, falling through to the first header
+instruction once the setup lines are exhausted. -/
+def setPC (loc : Label S → Fin p) (i : Fin N) (j : ℕ) : Fin p :=
+ if h : j < setCount S i then loc ⟨i, .inl ⟨j, h⟩⟩ else loc ⟨i, .inr (.inl 0)⟩
+
+/-- Relocate an index in row `i`'s eleven-instruction slice header to its machine program
+counter. -/
+def headPC (loc : Label S → Fin p) (i : Fin N) (j : Fin 11) := loc ⟨i, .inr (.inl j)⟩
+/-- Locate one of the seven instructions of the private bit-copy loop for row `i`. -/
+def copyPC (loc : Label S → Fin p) (i : Fin N) (j : Fin 7) := loc ⟨i, .inr (.inr j)⟩
+
+/-- Entry counter for the row with ordinal `n`, or the supplied return counter once all rows
+have been visited. -/
+def start (loc : Label S → Fin p) (ret : Fin p) (n : ℕ) :=
+ if h : n < N then setPC S loc ⟨n, h⟩ 0 else ret
+
+variable (vm : ∀ i, Fin (RegisterSetup.regCount (S i).operands) ↪ Fin r) (inputs : Fin 6 → Fin r)
+
+/-- Embed the six output registers of row `i`'s compiled setup into the enclosing machine
+register file for use by the header and copy loop. -/
+def reg (i : Fin N) : Fin 6 ↪ Fin r :=
+ (⟨RegisterSetup.output (S i).operands, fun _ _ h ↦
+ Fin.ext (congrArg (Fin.val (n := RegisterSetup.regCount (S i).operands)) h)⟩ :
+ Fin 6 ↪ Fin _).trans (vm i)
+
+/-- Decode a column label into a setup, oriented header or copy-loop instruction. Finishing a
+slice transfers control to the following row or to the return counter. -/
+def instruction (loc : Label S → Fin p) (ret : Fin p) : Label S → Instr w p r k
+ | ⟨i, .inl j⟩ => RegisterSetup.instruction (vm i) inputs
+ (RegisterSetup.lines (S i).operands)[j.val] (setPC S loc i (j.val + 1))
+ | ⟨i, .inr (.inl j)⟩ => if (S i).reverse then
+ ReverseSlices.instruction (headPC S loc i) (reg S vm i) (copyPC S loc i 0)
+ (start S loc ret (i.val + 1)) j
+ else PrivateSlices.instruction (headPC S loc i) (reg S vm i) (copyPC S loc i 0)
+ (start S loc ret (i.val + 1)) j
+ | ⟨i, .inr (.inr j)⟩ => PrivateFields.instruction .copy (copyPC S loc i)
+ (PrivateSlices.copyRegs (reg S vm i)) (start S loc ret (i.val + 1)) j
+
+theorem resize_instruction (loc : Label S → Fin p) (ret : Fin p) (l : Label S) :
+ (instruction (w := 2) (k := k) S vm inputs loc ret l).resize w =
+ instruction S vm inputs loc ret l := by
+ rcases l with ⟨i, j | j | j⟩
+ · exact RegisterSetup.resize_instruction ..
+ · cases h : (S i).reverse <;> fin_cases j <;> simp [instruction, h, ReverseSlices.instruction,
+ PrivateSlices.instruction, Instr.resize]
+ · fin_cases j <;> rfl
+
+variable {S vm inputs} (M : Machine w p r k) (loc : Label S → Fin p) (ret : Fin p)
+variable (code : ∀ l, M.code (loc l) = instruction S vm inputs loc ret l)
+variable (safe : ∀ i u j, vm i u ≠ inputs j)
+
+/-- The complete trace of one gather frame, with arbitrary compiler registers normalized to zero. -/
+def frameTrace (s : Setup) (row : Row) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) :=
+ (RowRecipe.evaluate pub state m (RegisterSetup.lines s.operands) (fun _ ↦ 0)).1 ++
+ PrivateSlices.frameEvents m row.frame row.bits
+
+/-- The trace of a fixed row list in numerical visit order. -/
+def trace (S : Fin N → Setup) (row : Fin N → Row) (is : List (Fin N))
+ (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) :=
+ is.flatMap fun i ↦ frameTrace (S i) (row i) pub state m
+
+include code safe in
+private theorem one (row : Row) (i : Fin N) (cfg : Config w p r) (m : Memory w)
+ (pub : Fin 5 → Word w) (state : Word w)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state) (entry : cfg.pc = setPC S loc i 0)
+ (recorded : row.Recorded (S i) pub state m) (pivot : ℕ) (fits : row.Fits w pivot)
+ (read : row.reads cfg.privateMem) (allowed : ℕ → Prop)
+ (sites : row.ReadSafe (S i) allowed pub state m) :
+ ∃ events out, out.pc = start S loc ret (i.val + 1) ∧ out.privateMem = row.write cfg.privateMem ∧
+ out.persistent = cfg.persistent ∧ (∀ j, out.reg (inputs j) = cfg.reg (inputs j)) ∧
+ (∀ j, (∀ u, j ≠ vm i u) → out.reg j = cfg.reg j) ∧
+ events.length ≤ setCount S i + 12 + 5 * row.bits.length ∧
+ countProbes events ≤ (∑ j, ((S i).operands j).loads) + 3 ∧ choiceBits events = [] ∧
+ SourceTransport.Reads allowed events ∧ events = frameTrace (S i) row pub state m ∧
+ ∀ fuel more, execute M.program (fuel + events.length) cfg m more =
+ (execute M.program fuel out m more).map (fun rep ↦ ⟨events ++ rep.events, rep.result⟩) := by
+ let f := (S i).operands
+ have link : RegisterSetup.Linked (vm i) inputs M (setPC S loc i) (RegisterSetup.lines f) := by
+ intro j
+ have hj : j.val < setCount S i := j.isLt
+ rw [show setPC S loc i j.val = loc ⟨i, .inl j⟩ by rw [setPC, dite_eq_left hj]; rfl]
+ exact code ⟨i, .inl j⟩
+ let rs := fun j ↦ cfg.reg (vm i j)
+ let ev := (RowRecipe.evaluate pub state m (RegisterSetup.lines f) rs).1
+ have raw := RegisterSetup.execute_setup_raw f inputs (vm i) M m _ link (safe i) cfg entry
+ dsimp only at raw
+ rw [show (fun j : Fin 5 ↦ cfg.reg (inputs j.castSucc)) = pub from funext hp, hs] at raw
+ obtain ⟨d, len, count, det, atHead, mem, pers, vals, unchanged, run⟩ := raw
+ have loads := RegisterSetup.lines_reads f allowed pub state m sites.loads rs
+ have startHead : d.pc = headPC S loc i 0 := by
+ change d.pc = setPC S loc i (setCount S i) at atHead
+ rw [atHead, setPC, dite_eq_right (Nat.lt_irrefl _)]
+ rfl
+ have h₀ : d.reg (reg S vm i 0) = (row.source : Word w) := (vals 0).trans recorded.source
+ have h₂ : d.reg (reg S vm i 2) = (row.destination : Word w) := (vals 2).trans recorded.destination
+ have h₃ : d.reg (reg S vm i 3) = 1 := vals 3
+ have h₅ : d.reg (reg S vm i 5) = (row.frame : Word w) := (vals 5).trans recorded.frame
+ have header : if (S i).reverse then ReverseSlices.Linked M (headPC S loc i) (reg S vm i)
+ (copyPC S loc i 0) (start S loc ret (i.val + 1))
+ else PrivateSlices.Linked M (headPC S loc i) (reg S vm i)
+ (copyPC S loc i 0) (start S loc ret (i.val + 1)) := by
+ split <;> rename_i h <;> intro j <;>
+ simpa only [headPC, instruction, h, Bool.false_eq_true, ite_true, ite_false] using
+ code ⟨i, .inr (.inl j)⟩
+ have copy : PrivateFields.Linked M .copy (copyPC S loc i) (PrivateSlices.copyRegs (reg S vm i))
+ (start S loc ret (i.val + 1)) := fun j ↦ code ⟨i, .inr (.inr j)⟩
+ obtain ⟨hlen, offs⟩ := ReverseSlices.oriented_frame_words (S i).reverse m (row.frame : Word w)
+ row.frame _ _ row.bits.length rfl recorded.frameFit recorded.length recorded.offsets
+ have offsets : 0 < row.bits.length →
+ (if (S i).reverse then m ((row.frame : Word w) + 1).val else m (row.frame : Word w).val).val =
+ row.sourceOffset ∧ (if (S i).reverse then m (row.frame : Word w).val
+ else m ((row.frame : Word w) + 1).val).val = row.targetOffset := by
+ cases rev : (S i).reverse <;>
+ simpa only [rev, Bool.false_eq_true, ite_false, ite_true] using offs
+ obtain ⟨out, stop, persistent, memory, kept, step, work, probes⟩ :=
+ ReverseSlices.execute_stored_frame (S i).reverse header copy d startHead h₃ m _ h₅
+ row.source row.destination row.sourceOffset row.targetOffset h₀ h₂ row.bits hlen offsets
+ (fun h ↦ ⟨by have := fits.old h; have := fits.new; have := fits.room h; omega, fits.room h⟩)
+ (fun h ↦ Or.inr (by have := fits.old h; have := fits.new; omega)) (mem ▸ read)
+ let fe := PrivateSlices.frameEvents m row.frame row.bits
+ have keep (j : Fin r) (h : ∀ u, j ≠ vm i u) : out.reg j = cfg.reg j :=
+ (kept j (h _) (h _) (h _) (h _)).trans (unchanged j h)
+ refine ⟨ev ++ fe, out, stop, ?_, persistent.trans pers,
+ fun j ↦ keep _ (fun u ↦ (safe i u j).symm), keep, ?_, ?_, ?_, ?_, ?_, ?_⟩
+ · rw [memory, mem, Row.write]
+ · rw [List.length_append, len]
+ change setCount S i + fe.length ≤ _
+ change fe.length = _ at work
+ split at work <;> omega
+ · rw [countProbes_append, count]
+ change countProbes fe = _ at probes
+ apply Nat.add_le_add_left (m := 3)
+ split at probes <;> omega
+ · rw [PrimedInputRAM.Flow.choiceBits_append, det, List.nil_append]
+ unfold fe PrivateSlices.frameEvents
+ rw [PrimedInputRAM.Flow.choiceBits_append]
+ have hh : choiceBits (PrivateSlices.headerEvents m (row.frame : Word w)) = [] := by
+ by_cases hz : m ((row.frame : Word w) + 1 + 1).val = 0 <;>
+ simp [PrivateSlices.headerEvents, hz, choiceBits]
+ rw [hh, List.nil_append]
+ split <;> simp [choiceBits, PrivateFields.events_bits]
+ · exact reads_append loads (frame_reads row (S i) allowed pub state m sites recorded.frameFit)
+ · exact congrArg (· ++ fe) (RegisterSetup.events_eq f pub state m rs)
+ · intro fuel more
+ rw [List.length_append, show fuel + (ev.length + fe.length) =
+ (fuel + fe.length) + ev.length by omega, run, step]
+ simp only [Option.map_map, Function.comp_def, List.append_assoc]
+ rfl
+
+/-- Bounds of the generated setup and copy instructions for one visit. -/
+def work (S : Fin N → Setup) (row : Fin N → Row) (i : Fin N) :=
+ setCount S i + 12 + 5 * (row i).bits.length
+
+/-- Per-row upper bound on external probes, counting all loads in the setup expressions and up
+to three reads of the slice header. -/
+def probes (S : Fin N → Setup) (i : Fin N) := (∑ j, ((S i).operands j).loads) + 3
+
+/-- The actual private-memory result of a sequence of slice copies. -/
+def writes (row : Fin N → Row) (is : List (Fin N)) (mem : Word w → Word w) :=
+ is.foldl (fun old i ↦ (row i).write old) mem
+
+/-- Execution contract for a row list. The trace reaches the return counter with the prescribed
+private writes, preserves persistent state and registers outside the visited scratch banks,
+consumes no choices, and satisfies the summed time and probe bounds. -/
+structure Result (S : Fin N → Setup)
+ (vm : ∀ i, Fin (RegisterSetup.regCount (S i).operands) ↪ Fin r)
+ (M : Machine w p r k) (ret : Fin p) (row : Fin N → Row) (is : List (Fin N))
+ (m : Memory w) (cfg out : Config w p r) (events : List (Event w)) : Prop where
+ pc : out.pc = ret
+ memory : out.privateMem = writes row is cfg.privateMem
+ persistent : out.persistent = cfg.persistent
+ regs : ∀ j, (∀ i ∈ is, ∀ u, j ≠ vm i u) → out.reg j = cfg.reg j
+ ticks : events.length ≤ (is.map (work S row)).sum
+ reads : countProbes events ≤ (is.map (probes S)).sum
+ choices : choiceBits events = []
+ execute : ∀ fuel more, BurstRAM.execute M.program (fuel + events.length) cfg m more =
+ (BurstRAM.execute M.program fuel out m more).map (fun rep ↦ ⟨events ++ rep.events, rep.result⟩)
+
+variable (row : Fin N → Row) (m : Memory w) (pub : Fin 5 → Word w) (state : Word w)
+variable (recorded : ∀ i, (row i).Recorded (S i) pub state m)
+variable (pivot : ℕ) (fits : ∀ i, (row i).Fits w pivot)
+
+variable (allowed : ℕ → Prop)
+variable (sites : ∀ i, (row i).ReadSafe (S i) allowed pub state m)
+
+include code safe recorded fits sites in
+private theorem scan_list (is : List (Fin N)) (off : ℕ) (endEq : off + is.length = N)
+ (order : ∀ j : Fin is.length, is[j.val].val = off + j.val)
+ (cfg : Config w p r) (entry : cfg.pc = start S loc ret off)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state)
+ (source : ∀ i, (row i).reads cfg.privateMem) :
+ ∃ events out, Result S vm M ret row is m cfg out events ∧
+ SourceTransport.Reads allowed events ∧ events = trace S row is pub state m := by
+ induction is generalizing cfg off with
+ | nil =>
+ have endAt : off = N := by simpa only [List.length_nil, Nat.add_zero] using endEq
+ refine ⟨[], cfg, ?_, by simp [SourceTransport.Reads], rfl⟩
+ exact ⟨by simpa [start, endAt] using entry, rfl, rfl, fun _ _ ↦ rfl, le_rfl, le_rfl, rfl,
+ by simp⟩
+ | cons i is ih =>
+ have hi : i.val = off := by simpa using order ⟨0, by simp⟩
+ subst off
+ have startAt : cfg.pc = setPC S loc i 0 := by
+ rw [entry, start, dite_eq_left i.isLt]
+ obtain ⟨es, d, pc, mem, keep, args, regs, time, count, det, esReads, esEq, step⟩ :=
+ one M loc ret code safe (row i) i cfg m pub state hp hs startAt (recorded i) pivot
+ (fits i) (source i) allowed (sites i)
+ have next (j : Fin is.length) : is[j.val].val = i.val + 1 + j.val := by
+ have h := order ⟨j.val + 1, Nat.succ_lt_succ j.isLt⟩
+ change is[j.val].val = i.val + (j.val + 1) at h
+ omega
+ have safeReads (j : Fin N) : (row j).reads d.privateMem := by
+ rw [mem]
+ exact reads_write _ _ pivot (fits i) (fits j) cfg.privateMem (source j)
+ obtain ⟨tail, out, done, tailReads, tailEq⟩ := ih (i.val + 1)
+ (by simp only [List.length_cons] at endEq; omega) next d pc
+ (fun j ↦ (args _).trans (hp j)) ((args _).trans hs) safeReads
+ refine ⟨es ++ tail, out, ⟨done.pc, ?_, done.persistent.trans keep, ?_, ?_, ?_, ?_, ?_⟩,
+ reads_append esReads tailReads, congrArg₂ List.append esEq tailEq⟩
+ · rw [done.memory, mem]
+ rfl
+ · intro j h
+ exact (done.regs j (fun v hv ↦ h v (List.mem_cons_of_mem _ hv))).trans
+ (regs j (h i List.mem_cons_self))
+ · simp only [List.length_append, List.map_cons, List.sum_cons]
+ exact Nat.add_le_add time done.ticks
+ · rw [countProbes_append, List.map_cons, List.sum_cons]
+ exact Nat.add_le_add count done.reads
+ · rw [PrimedInputRAM.Flow.choiceBits_append, det, done.choices, List.nil_append]
+ · intro fuel more
+ rw [List.length_append, show fuel + (es.length + tail.length) =
+ (fuel + tail.length) + es.length by omega, step, done.execute]
+ simp [Option.map_map, Function.comp_def, List.append_assoc]
+
+include code safe recorded fits sites in
+/-- Every successful execution of the column realizes the prescribed trace. -/
+theorem native_exact (cfg : Config w p r) (entry : cfg.pc = start S loc ret 0)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state)
+ (source : ∀ i, (row i).reads cfg.privateMem) :
+ let es := trace S row (List.finRange N) pub state m
+ ∃ out, Result S vm M ret row (List.finRange N) m cfg out es ∧
+ SourceTransport.Reads allowed es := by
+ intro es
+ obtain ⟨events, out, run, reads, eqv⟩ := scan_list M loc ret code safe row m pub state
+ recorded pivot fits allowed sites
+ (List.finRange N) 0 (by simp) (fun j ↦ by simp) cfg entry hp hs source
+ rw [eqv] at run reads
+ exact ⟨out, run, reads⟩
+
+include code safe recorded fits sites in
+/-- The finite column code copies every recorded interval in physical row order,
+consumes no branch choices and preserves every register outside its scratch bank. -/
+theorem native_reads (cfg : Config w p r) (entry : cfg.pc = start S loc ret 0)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state)
+ (source : ∀ i, (row i).reads cfg.privateMem) :
+ ∃ events out, Result S vm M ret row (List.finRange N) m cfg out events ∧
+ SourceTransport.Reads allowed events := by
+ obtain ⟨out, run, reads⟩ := native_exact M loc ret code safe row m pub state recorded pivot
+ fits allowed sites cfg entry hp hs source
+ exact ⟨_, out, run, reads⟩
+
+include code safe recorded fits in
+/-- The finite column code copies every recorded interval in physical row order,
+consumes no branch choices and preserves every register outside its scratch bank. -/
+theorem native (cfg : Config w p r) (entry : cfg.pc = start S loc ret 0)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state)
+ (source : ∀ i, (row i).reads cfg.privateMem) :
+ ∃ events out, Result S vm M ret row (List.finRange N) m cfg out events := by
+ obtain ⟨events, out, result, _⟩ := native_reads M loc ret code safe row m pub state recorded
+ pivot fits (fun _ ↦ True) (fun i ↦ readSafe_true _ _ _ _ _) cfg entry hp hs source
+ exact ⟨events, out, result⟩
+
+end PairSimulation.ResidentColumn
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedCursorLeaf.lean b/lean/OAI/Computability/VPVNP/PairSelectedCursorLeaf.lean
new file mode 100644
index 0000000000..98634824d8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedCursorLeaf.lean
@@ -0,0 +1,474 @@
+import OAI.Computability.VPVNP.PairVertexFrameWrites
+import OAI.Computability.VPVNP.PairSelectedPacketOrders
+import OAI.Computability.VPVNP.PairVertexSelectedReport
+import OAI.Computability.VPVNP.PairSimulationLeafReads
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+
+/-! # The native cursor leaves of the selected terminal history -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.SelectedCursorLeaf
+
+open BurstRAM PrivateRAM DFS VertexImage CursorRouting CursorNetwork LeafStartup
+open TreeDecode LocalHistory LeafHandler NodeArguments NetworkKernel CompressorRecords
+open CompressorRecords.SourceTransport NativeFrame
+open scoped Fin.CommRing
+
+set_option maxRecDepth 12000
+set_option maxHeartbeats 1600000
+set_option synthInstance.maxSize 10000
+attribute [local irreducible] LeafRole.labelCount LeafRole.privateCount
+
+private theorem leafDispatch {W n p r : ℕ} {S : Part → Segment} {V : Placement S p r}
+ {M : Machine W p r 11} (link : Contains V M) (G offset hist : Word W) (m : Memory W)
+ (handlers : NodeDispatch.Role → HookParser W n) (domain : Word W → Scratch W n → Prop)
+ (body : (handlers .leaf).ExactOn domain M (V.entry .leaf) (V.dfsPC 3) V.dfs m) :
+ (dispatcher handlers m offset).ExactOn
+ (fun node s => ResidentGeometry s G offset hist ∧ domain node s ∧ NodeDispatch.role (m (offset+node).val) = .leaf)
+ M (V.core (.roleBase 0)) (V.dfsPC 3) V.dfs m := by
+ apply dispatch_exactOn link G offset hist m _ (fun _ _ h => h.1) handlers
+ intro role
+ constructor
+ · intro node saved h bits job tail hit
+ have eqn := h.2.symm.trans h.1.2.2
+ subst role
+ exact body.success node saved h.1.2.1 bits job tail hit
+ · intro node bits c top pending h pc nodeReg stack endPos topReg endReg one fail
+ have eqn := h.2.symm.trans h.1.2.2
+ subst role
+ exact body.reject node bits c top pending h.1.2.1 pc nodeReg stack endPos topReg endReg one fail
+
+private theorem dispatch_footprint {w : ℕ} (allow : ℕ → Prop) (m : Memory w) (offset node : Word w)
+ (tag : m (offset+node).val = 0) (addr : allow (offset+node).val) :
+ Reads allow (dispatchEvents m offset node) ∧ after m (dispatchEvents m offset node) = m := by
+ simp only [dispatchEvents,NodeDispatch.events,tag,ite_true,List.append_nil]
+ refine ⟨TerminalFootprint.reads_append (TerminalFootprint.reads_ticks _ _) ?_,rfl⟩
+ intro a v ha
+ simp only [List.mem_cons,List.not_mem_nil,reduceCtorEq,or_false,false_or,Event.read.injEq] at ha
+ exact ha.1 ▸ addr
+
+private theorem pop {w n : ℕ} {R : LeafArena.Regions} {format : Packet → Prop}
+ {stable : Scratch w n → Prop} {desc : ℕ → List ℕ} {head : Packet} {pending : List Packet} {s out : Scratch w n}
+ (h : Frontier R.arguments format stable desc (head::pending) s) (outFrame : stable out)
+ (typed : ∀ q, format q → q.node < R.nodes)
+ (keep : ∀ i : {a : Word w // n ≤ a.val}, i.val.val < R.stackBase → out i = s i) :
+ Frontier R.arguments format stable desc pending out := by
+ apply h.pop outFrame
+ intro q member fits stored
+ apply stored.congr
+ intro i
+ let a : Word w := ((R.arguments.base q.node+i.val : ℕ) : Word w)
+ have hv : a.val = R.arguments.base q.node+i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans_le fits.2.2)
+ have above : n ≤ a.val := hv ▸ fits.1.trans (Nat.le_add_right _ _)
+ have endRoom := R.node_before (typed q (h.prepared.2 q (List.mem_cons_of_mem _ member)).1)
+ have tailRoom := R.hist_before
+ have low : a.val < R.stackBase := by
+ rw [hv,LeafArena.Regions.stackBase]
+ have := i.isLt
+ have := fits.2.1
+ omega
+ change rawScratch out a = rawScratch s a
+ simpa only [rawScratch,dite_eq_left above] using keep ⟨a,above⟩ low
+
+open private realized_counts from OAI.Computability.VPVNP.PairSimulationVertexJobs
+
+/-- A successful leaf consumes one outstanding subtree without increasing
+any histogram coordinate. The same effects therefore preserve its headroom. -/
+private theorem budgetLeaf {W n : ℕ} {A : Type*} [CommRing A] {J : Type} [Fintype J]
+ {κ : J → A} {N : Network} (P : SiteParsers κ N) (ptr : N.Site → ℕ × ℕ) (input : Packets N)
+ (hook : HookParser W n) (arena : Arena) (format : Packet → Prop) (stable : Scratch W n → Prop)
+ (desc : ℕ → List ℕ) (hist : Scratch W n → J → ℕ) (guard : VisitPath W n → Prop)
+ (nodeCap limit : ℕ) (shape : ∀ u z, desc (input u z).node = [])
+ (unchanged : ∀ u s bits job tail, hook.read ((ptr u).1 : Word W) s bits = some (job,tail) →
+ ∀ l, hist (job.update s) l = hist s l) (zero : ∀ u z i l, (P.witnesses u z).exponents i l = 0)
+ (basic : Subtrees hook (Frontier arena format stable desc) P (fun u => leafTree (ptr u)) input ∧
+ Emits (Frontier arena format stable desc) hist guard P input (leafJobs P ptr)) :
+ let valid := Budgeted arena format stable desc hist nodeCap limit
+ Subtrees hook valid P (fun u => leafTree (ptr u)) input ∧ Emits valid hist guard P input (leafJobs P ptr) := by
+ intro valid
+ constructor
+ · intro u z
+ constructor
+ · intro pending s bits out tail h read
+ obtain ⟨selected,front⟩ := (basic.1 u z).sound pending s bits out tail h.frontier read
+ change hook.decode [((ptr u).1 : Word W)] s bits = some (out,tail) at read
+ rw [HookParser.decode] at read
+ obtain ⟨⟨job,rest⟩,hit,done⟩ := Option.bind_eq_some_iff.mp read
+ change some (job.update s,rest) = some (out,tail) at done
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj done).symm
+ exact ⟨selected,h.advance (children := []) (shape u z) front (fun l =>
+ (unchanged u s bits job tail hit l).le.trans (Nat.le_add_right _ _))⟩
+ · intro pending s x tail h
+ exact (basic.1 u z).complete pending s x tail h.frontier
+ · intro u z x pending s h
+ obtain ⟨jobs,eff⟩ := basic.2 u z x pending s h.frontier
+ refine ⟨jobs,eff.realized,eff.ready,eff.framed,h.advance (children := []) (shape u z) eff.remaining ?_⟩
+ intro l
+ have hc := realized_counts eff.realized s eff.ready l
+ simp only [leafJobs,List.map_cons,List.map_nil,List.sum_cons,List.sum_nil,zero,Nat.add_zero] at hc
+ exact hc.le.trans (Nat.le_add_right _ _)
+
+variable {geometry rootFields shrink refresh : Segment} {p r w : ℕ}
+ (V : Placement (segments geometry rootFields LeafRole.segment shrink refresh) p r)
+ (M : Machine w p r 11)
+ {L : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout L n a H w}
+ (D : PrimedCounter.Data Q s) {b l e degree pad : ℕ} [NeZero (b+l)]
+ (hD : 1 < b+l) (hd : 2+pad = 2^degree) (budget : ProcessorBudget n (b+l) e w)
+ {K : Type*} [CommRing K] {Label : Type} [Fintype Label] (f : Label → K)
+ (bound : NominationClock D budget.tags budget.capFits (n^39))
+ (m : Memory w) (header offset : Word w) (arity cap : ℕ)
+
+local notation "regions" => fromHeader arity M.publicData header m
+local notation "data" => leafWords arity M.publicData header offset m
+local notation "fields" => LeafRole.addressFields data
+local notation "X" => LeafArguments.state hD hd (2^e) w
+local notation "leaves" => TraversalRows.sitePointers cap (Fin.val (fields LeafAddress.Field.base)) (siteOrder X)
+local notation "sites" => nominationSites D budget.tags budget.capFits (cursorCoordinateLabels b l) hD hd f (n^39) bound
+
+/-- Prepared cursor packets supply both the exact leaf reader and its native
+zero-increment job. The concrete dispatch and role reader preserve every
+pending argument below the verifier stacks, on every returned suffix. -/
+theorem checks (link : Contains V M) (fit : (regions).stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ (hn : 2048 ≤ n) (hwidth : b+l ≤ w)
+ (stride : (m (header+15).val).val = cap+2) (rb : (m (header+18).val).val = 2^b)
+ (rl : (m (header+19).val).val = 2^l) (span : (m (header+20).val).val = LiveAuxiliaryHeaders.span L D.hist.length)
+ (shadowFit : (M.publicData 3).val + (m (header+20).val).val ≤ 2^w)
+ (headers : ∀ i < (m (header+20).val).val, (m ((M.publicData 3).val+i)).val = (D.initial i).val)
+ (size : (M.publicData 6).val = n)
+ (time : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w),
+ LeafStartup.steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ n^39)
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length+n^39 ≤ n^40)
+ (boot : ∀ (v : Site (b+l)) (buf : Buffers (b+l) (2^e) w), LeafBoot.ticks D budget.tags budget.capFits v buf ≤ n^15)
+ (handlers : NodeDispatch.Role → HookParser w n)
+ (leaf : handlers .leaf = LeafRole.parser data D budget regions fit m (n^39))
+ (allow : ℕ → Prop) (shadow : ∀ site : Word w, site < fields .span → allow (fields .shadow+site).val)
+ (tag : ∀ u, m (offset+((leaves u).1 : Word w)).val = 0)
+ (tagRead : ∀ u, allow (offset+((leaves u).1 : Word w)).val)
+ (format : Packet → Prop) (stable : Scratch w n → Prop) (desc : ℕ → List ℕ)
+ (typed : ∀ q, format q → q.node < (regions).nodes ∧ q.node < 2^w)
+ (cached : ∀ s, stable s → LeafSourceLoad.Cached (regions).cacheBase (rawScratch s) (LeafVisit.cacheWords D (b+l) e))
+ (record : ∀ s, stable s → LeafGeometryLoad.Stored n (frameBase regions) (rawScratch s) data)
+ (resident : ∀ s, stable s → ResidentGeometry s (frameBase regions : Word w) offset ((regions).histBase : Word w))
+ (preserve : ∀ s out, stable s →
+ (∀ i : {a : Word w // n ≤ a.val}, i.val.val < (regions).stackBase → out i = s i) → stable out)
+ {g : ℕ} (order : Fin g ≃ Label) (hcount : g ≤ (regions).histWords) :
+ let input := fun v z => Packet.mk (leaves v).1 (packed X v z)
+ let valid := Frontier (regions).arguments format stable desc
+ let hook := dispatcher handlers m offset
+ let guard := JobGuard V M m allow (fun j : VisitPath w n => countProbes j.trace ≤ 2 ∧ j.trace.length+17 ≤ n^40)
+ Subtrees hook valid sites (fun v => leafTree (leaves v)) input ∧
+ Emits valid (privateHistogram order (regions).histBase) guard sites input (leafJobs sites leaves) := by
+ intro input valid hook guard
+ let roleParser := LeafRole.parser (endAddr := n) data D budget regions fit m (n^39)
+ let domain := LeafRole.Domain (endAddr := n) (e := e) data D hD hd regions cap (frameBase regions)
+ have body := LeafRole.site_exact V M D hD hd budget m header offset arity cap (n^39) fit link
+ stride rb rl span shadowFit headers size time room
+ have exactDispatch := leafDispatch link (frameBase regions : Word w) offset ((regions).histBase : Word w) m
+ handlers domain (leaf.symm ▸ body)
+ have roleAt (u : (X).network.Site) : NodeDispatch.role (m (offset+((leaves u).1 : Word w)).val) = .leaf := by
+ rw [tag]; rfl
+ have ready (v : Position (b+l)) (z : (X).network.Half (lanePositions (cursorCoordinateLabels b l) v))
+ (pending : List Packet) (s : Scratch w n) (h : valid (input (lanePositions (cursorCoordinateLabels b l) v) z::pending) s) :
+ let node : Word w := (leaves (lanePositions (cursorCoordinateLabels b l) v)).1
+ StoredCursorRow hD hd fields (regions).arguments node s cap v z ∧ domain node s := by
+ intro node
+ have ⟨hs,type,fits,stored⟩ := h.head
+ have ⟨hl,hv⟩ := typed _ type
+ have addr : node.val = (leaves (lanePositions (cursorCoordinateLabels b l) v)).1 := Nat.mod_eq_of_lt hv
+ have fit' : (cursorPacket hD hd node.val v z).Fits (regions).arguments w n := by rw [addr]; exact fits
+ have stored' : (cursorPacket hD hd node.val v z).Stored (regions).arguments s := by rw [addr]; exact stored
+ exact ⟨⟨hwidth,stride,rb,rl,addr,fit',stored'⟩,⟨⟨addr ▸ hl,cached s hs,v,z,addr,fit',stored'⟩,record s hs⟩⟩
+ have pops (u : (X).network.Site) (z : (X).network.Half u) (pending : List Packet) (s : Scratch w n)
+ (bits tail : List Bool) (j : VisitPath w n) (h : valid (input u z::pending) s)
+ (hit : roleParser.read ((leaves u).1 : Word w) s bits = some (j,tail)) : valid pending (j.update s) := by
+ have keep := LeafRole.below_stack D budget (n^39) data regions fit m _ s bits tail j hit room
+ exact pop h (preserve s _ h.frame keep) (fun q hq => (typed q hq).1) keep
+ constructor
+ · apply leaf_subtrees hook valid sites leaves input
+ · intro u z pending s bits h
+ obtain ⟨v,rfl⟩ := (lanePositions (cursorCoordinateLabels b l)).surjective u
+ let node : Word w := (leaves (lanePositions (cursorCoordinateLabels b l) v)).1
+ have row := (ready v z pending s h).1
+ change ((dispatcher handlers m offset).read node s bits).map Prod.snd = _
+ have hn : NodeDispatch.role (m (offset+node).val) = .leaf := roleAt _
+ rw [dispatcher_suffix,hn,leaf]
+ let load := LeafVisit.loaded (endAddr := n) D budget regions fit fields m
+ have suffix := cursorHook_suffix hD hd D budget.tags budget.capFits f (n^39) bound (LeafVisit.storage regions fit)
+ fields (regions).arguments (fun node s => (load node s).trace) (fun node s => (load node s).prepared) node s cap v z row bits
+ have same : physicalInput (b+l) e w fields (regions).arguments (fun n s => (load n s).trace)
+ (fun n s => (load n s).prepared) = load := rfl
+ unfold cursorHook at suffix
+ rw [same] at suffix
+ simp only [LeafRole.parser,LeafRole.withReload,Option.map_map,Function.comp_def]
+ exact suffix
+ · intro u z pending s bits j tail h hit
+ change (dispatcher handlers m offset).read _ _ _ = _ at hit
+ simp only [dispatcher,roleAt,leaf,Option.map_eq_some_iff] at hit
+ obtain ⟨⟨body,rest⟩,hb,eqn⟩ := hit
+ cases eqn
+ exact pops u z pending s bits rest body h hb
+ · apply leaf_emits valid (privateHistogram order (regions).histBase) guard sites input leaves
+ intro u z x pending s h
+ obtain ⟨v,rfl⟩ := (lanePositions (cursorCoordinateLabels b l)).surjective u
+ let u := lanePositions (cursorCoordinateLabels b l) v
+ let node : Word w := (leaves u).1
+ have ⟨row,hdomain⟩ := ready v z pending s h
+ let code := ((sites).read u z).encode x
+ let src := (regions).histBase
+ have low : n ≤ src := by
+ change n ≤ (regions).arguments.start + (regions).nodes*(regions).arguments.stride
+ have hs : (regions).arguments.start = n := size
+ omega
+ have top : src+g ≤ (regions).stackBase := le_trans (Nat.add_le_add_left hcount _) ((regions).hist_before.trans (Nat.le_add_right ..))
+ have topFit : (regions).stackBase < 2^w := (Nat.le_add_right _ _).trans_lt fit
+ let addr (label : Label) : Word w := ((src+(order.symm label).val : ℕ) : Word w)
+ have val (label : Label) : (addr label).val = src+(order.symm label).val :=
+ Nat.mod_eq_of_lt (((Nat.add_lt_add_left (order.symm label).isLt _).trans_le top).trans topFit)
+ let cell (label : Label) : {a : Word w // n ≤ a.val} := ⟨addr label,(val label).symm ▸ low.trans (Nat.le_add_right _ _)⟩
+ have away (label : Label) : (cell label).val.val < (regions).stackBase := (val label).symm ▸
+ (Nat.add_lt_add_left (order.symm label).isLt _).trans_le top
+ obtain ⟨j,hread,enabled,real⟩ := LeafRole.selected_job D hD hd budget f (n^39) bound data regions cap fit m
+ node s v z row cell away (room v _) code [] ⟨x,rfl⟩
+ rw [List.append_nil] at hread
+ let actual := dispatchJob m offset node s j
+ have hit : hook.read node s code = some (actual,[]) := by
+ have hn : NodeDispatch.role (m (offset+node).val) = .leaf := roleAt u
+ change (dispatcher handlers m offset).read node s code = _
+ simp only [dispatcher,hn,leaf,hread,Option.map_some,actual]
+ have good := exactDispatch.success node s ⟨resident _ h.frame,hdomain,roleAt u⟩ code actual [] hit
+ obtain ⟨reads,mem⟩ := LeafRole.site_footprint D budget regions fit m data node s (n^39) code [] j allow shadow hread
+ obtain ⟨probe,len⟩ := LeafRole.site_work M D budget m header offset arity fit hn boot node s code [] j hread
+ obtain ⟨dr,dm⟩ := dispatch_footprint allow m offset node (tag u) (tagRead u)
+ have dc := dispatchEvents_cost m offset node
+ refine ⟨actual,⟨good.1,?_,?_⟩,⟨rfl,enabled⟩,⟨good.2.2.2,?_,TerminalFootprint.reads_append dr reads,?_,?_⟩,
+ pops u z pending s code [] j h hread⟩
+ · exact (List.append_nil _ ▸ good.2.2.1).symm
+ · intro old en label
+ have hist (old : Scratch w n) : privateHistogram order src old label = (old (cell label)).val := by
+ change (rawScratch old (addr label)).val = _
+ simp only [rawScratch,dite_eq_left (cell label).property,cell]
+ change privateHistogram order src (j.update old) label = privateHistogram order src old label + 0
+ rw [hist,hist]
+ exact real.counts old en.2 label
+ · change after m (dispatchEvents m offset node ++ j.trace) = m
+ simp only [after,List.foldl_append] at dm mem ⊢
+ rw [dm,mem]
+ · change countProbes (dispatchEvents m offset node ++ j.trace) ≤ 2
+ rw [countProbes_append,dc.1]; omega
+ · change (dispatchEvents m offset node ++ j.trace).length+17 ≤ n^40
+ rw [List.length_append]; omega
+
+open Compression
+
+/-- Apply the physical leaf checks at every selected branch of an ordered
+execution. In the block program the canonical ordering is
+`execute_readerOrders`, giving the initial packet of `selected_inputPacked`. -/
+theorem selected (link : Contains V M) (fit : (regions).stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ (hn : 2048 ≤ n) (hwidth : b+l ≤ w)
+ (stride : (m (header+15).val).val = cap+2) (rb : (m (header+18).val).val = 2^b)
+ (rl : (m (header+19).val).val = 2^l) (span : (m (header+20).val).val = LiveAuxiliaryHeaders.span L D.hist.length)
+ (shadowFit : (M.publicData 3).val + (m (header+20).val).val ≤ 2^w)
+ (headers : ∀ i < (m (header+20).val).val, (m ((M.publicData 3).val+i)).val = (D.initial i).val)
+ (size : (M.publicData 6).val = n)
+ (time : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w),
+ LeafStartup.steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ n^39)
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length+n^39 ≤ n^40)
+ (boot : ∀ (v : Site (b+l)) (buf : Buffers (b+l) (2^e) w), LeafBoot.ticks D budget.tags budget.capFits v buf ≤ n^15)
+ (handlers : NodeDispatch.Role → HookParser w n)
+ (leaf : handlers .leaf = LeafRole.parser data D budget regions fit m (n^39))
+ (allow : ℕ → Prop) (shadow : ∀ site : Word w, site < fields .span → allow (fields .shadow+site).val)
+ (tag : ∀ u, m (offset+((leaves u).1 : Word w)).val = 0)
+ (tagRead : ∀ u, allow (offset+((leaves u).1 : Word w)).val)
+ (format : Packet → Prop) (stable : Scratch w n → Prop) (desc : ℕ → List ℕ)
+ (typed : ∀ q, format q → q.node < (regions).nodes ∧ q.node < 2^w)
+ (cached : ∀ s, stable s → LeafSourceLoad.Cached (regions).cacheBase (rawScratch s) (LeafVisit.cacheWords D (b+l) e))
+ (record : ∀ s, stable s → LeafGeometryLoad.Stored n (frameBase regions) (rawScratch s) data)
+ (resident : ∀ s, stable s → ResidentGeometry s (frameBase regions : Word w) offset ((regions).histBase : Word w))
+ (preserve : ∀ s out, stable s →
+ (∀ i : {a : Word w // n ≤ a.val}, i.val.val < (regions).stackBase → out i = s i) → stable out)
+ {g : ℕ} (order : Fin g ≃ Label) (hcount : g ≤ (regions).histWords) :
+ ∀ {lastDegree lastLanes : ℕ} (E : StateExecution K lastDegree lastLanes X) (W : E.MapWitnesses f)
+ (readers : ExecutionReaders E W) (rec : E.Records) (z : E.Choices),
+ ExecutionOrders E W readers → ∀ ptr : RowPointers (E.termChain rec z),
+ let input := (fromRows (E.termChain rec z) (branchParsers E W readers rec z) ptr
+ (fun u => (leaves u).1) (packed (E.finalState z))).1
+ let valid := Frontier (regions).arguments format stable desc
+ let hook := dispatcher handlers m offset
+ let guard := JobGuard V M m allow (fun j : VisitPath w n => countProbes j.trace ≤ 2 ∧ j.trace.length+17 ≤ n^40)
+ Subtrees hook valid sites (fun v => leafTree (leaves v)) input ∧
+ Emits valid (privateHistogram order (regions).histBase) guard sites input (leafJobs sites leaves) := by
+ intro lastDegree lastLanes E W readers rec z orders ptr input valid hook guard
+ have same : input = fun u q => Packet.mk (leaves u).1 (packed X u q) := by
+ funext u q
+ exact execution_inputPacked E W readers rec z orders ptr (fun i => (leaves i).1) u q
+ rw [same]
+ exact checks V M D hD hd budget f bound m header offset arity cap link fit hn hwidth stride rb rl span
+ shadowFit headers size time room boot handlers leaf allow shadow tag tagRead format stable desc typed
+ cached record resident preserve order hcount
+
+/-- The same physical leaf consumes its root from the budgeted frontier.
+Its private histogram remains equal to the one on entry, even on arbitrary
+successfully decoded leaf tapes. -/
+theorem checksBudgeted (link : Contains V M) (fit : (regions).stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ (hn : 2048 ≤ n) (hwidth : b+l ≤ w)
+ (stride : (m (header+15).val).val = cap+2) (rb : (m (header+18).val).val = 2^b)
+ (rl : (m (header+19).val).val = 2^l) (span : (m (header+20).val).val = LiveAuxiliaryHeaders.span L D.hist.length)
+ (shadowFit : (M.publicData 3).val + (m (header+20).val).val ≤ 2^w)
+ (headers : ∀ i < (m (header+20).val).val, (m ((M.publicData 3).val+i)).val = (D.initial i).val)
+ (size : (M.publicData 6).val = n)
+ (time : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w),
+ LeafStartup.steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ n^39)
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length+n^39 ≤ n^40)
+ (boot : ∀ (v : Site (b+l)) (buf : Buffers (b+l) (2^e) w), LeafBoot.ticks D budget.tags budget.capFits v buf ≤ n^15)
+ (handlers : NodeDispatch.Role → HookParser w n)
+ (leaf : handlers .leaf = LeafRole.parser data D budget regions fit m (n^39))
+ (allow : ℕ → Prop) (shadow : ∀ site : Word w, site < fields .span → allow (fields .shadow+site).val)
+ (tag : ∀ u, m (offset+((leaves u).1 : Word w)).val = 0)
+ (tagRead : ∀ u, allow (offset+((leaves u).1 : Word w)).val)
+ (format : Packet → Prop) (stable : Scratch w n → Prop) (desc : ℕ → List ℕ)
+ (typed : ∀ q, format q → q.node < (regions).nodes ∧ q.node < 2^w)
+ (cached : ∀ s, stable s → LeafSourceLoad.Cached (regions).cacheBase (rawScratch s) (LeafVisit.cacheWords D (b+l) e))
+ (record : ∀ s, stable s → LeafGeometryLoad.Stored n (frameBase regions) (rawScratch s) data)
+ (resident : ∀ s, stable s → ResidentGeometry s (frameBase regions : Word w) offset ((regions).histBase : Word w))
+ (preserve : ∀ s out, stable s →
+ (∀ i : {a : Word w // n ≤ a.val}, i.val.val < (regions).stackBase → out i = s i) → stable out)
+ {g : ℕ} (order : Fin g ≃ Label) (hcount : g ≤ (regions).histWords)
+ (nodeCap limit : ℕ) (shape : ∀ u, desc (leaves u).1 = []) :
+ let input := fun v z => Packet.mk (leaves v).1 (packed X v z)
+ let valid := Budgeted (regions).arguments format stable desc (privateHistogram order (regions).histBase) nodeCap limit
+ let hook := dispatcher handlers m offset
+ let guard := JobGuard V M m allow (fun j : VisitPath w n => countProbes j.trace ≤ 2 ∧ j.trace.length+17 ≤ n^40)
+ Subtrees hook valid sites (fun u => leafTree (leaves u)) input ∧
+ Emits valid (privateHistogram order (regions).histBase) guard sites input (leafJobs sites leaves) := by
+ intro input valid hook guard
+ have basic := checks V M D hD hd budget f bound m header offset arity cap link fit hn hwidth stride rb rl span
+ shadowFit headers size time room boot handlers leaf allow shadow tag tagRead format stable desc typed
+ cached record resident preserve order hcount
+ apply budgetLeaf sites leaves input hook (regions).arguments format stable desc
+ (privateHistogram order (regions).histBase) guard nodeCap limit (fun u _ => shape u) _ (fun _ _ _ _ => rfl) basic
+ intro u s bits job tail hit l
+ let node : Word w := (leaves u).1
+ have role : NodeDispatch.role (m (offset+node).val) = .leaf := by rw [tag u]; rfl
+ change (dispatcher handlers m offset).read node s bits = some (job,tail) at hit
+ simp only [dispatcher,role,leaf,Option.map_eq_some_iff] at hit
+ obtain ⟨⟨body,rest⟩,read,eqn⟩ := hit
+ cases eqn
+ let addr : Word w := (((regions).histBase+(order.symm l).val : ℕ) : Word w)
+ change (rawScratch (body.update s) addr).val = (rawScratch s addr).val
+ by_cases hi : n ≤ addr.val
+ · have hv : addr.val ≤ (regions).histBase+(order.symm l).val := Nat.mod_le _ _
+ have htop := (regions).hist_before
+ have hbelow : addr.val < (regions).stackBase := by
+ unfold LeafArena.Regions.stackBase
+ have := (order.symm l).isLt
+ omega
+ have kept := LeafRole.below_stack D budget (n^39) data regions fit m node s bits rest body read room ⟨addr,hi⟩ hbelow
+ simp only [rawScratch,dite_eq_left hi]
+ exact congrArg Fin.val kept
+ · simp only [rawScratch,dite_eq_right hi]
+
+/-- The selected mathematical branch starts at the very same budgeted
+cursor packets used in the native vertex execution. -/
+theorem selectedBudgeted (link : Contains V M) (fit : (regions).stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ (hn : 2048 ≤ n) (hwidth : b+l ≤ w)
+ (stride : (m (header+15).val).val = cap+2) (rb : (m (header+18).val).val = 2^b)
+ (rl : (m (header+19).val).val = 2^l) (span : (m (header+20).val).val = LiveAuxiliaryHeaders.span L D.hist.length)
+ (shadowFit : (M.publicData 3).val + (m (header+20).val).val ≤ 2^w)
+ (headers : ∀ i < (m (header+20).val).val, (m ((M.publicData 3).val+i)).val = (D.initial i).val)
+ (size : (M.publicData 6).val = n)
+ (time : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w),
+ LeafStartup.steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ n^39)
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length+n^39 ≤ n^40)
+ (boot : ∀ (v : Site (b+l)) (buf : Buffers (b+l) (2^e) w), LeafBoot.ticks D budget.tags budget.capFits v buf ≤ n^15)
+ (handlers : NodeDispatch.Role → HookParser w n)
+ (leaf : handlers .leaf = LeafRole.parser data D budget regions fit m (n^39))
+ (allow : ℕ → Prop) (shadow : ∀ site : Word w, site < fields .span → allow (fields .shadow+site).val)
+ (tag : ∀ u, m (offset+((leaves u).1 : Word w)).val = 0)
+ (tagRead : ∀ u, allow (offset+((leaves u).1 : Word w)).val)
+ (format : Packet → Prop) (stable : Scratch w n → Prop) (desc : ℕ → List ℕ)
+ (typed : ∀ q, format q → q.node < (regions).nodes ∧ q.node < 2^w)
+ (cached : ∀ s, stable s → LeafSourceLoad.Cached (regions).cacheBase (rawScratch s) (LeafVisit.cacheWords D (b+l) e))
+ (record : ∀ s, stable s → LeafGeometryLoad.Stored n (frameBase regions) (rawScratch s) data)
+ (resident : ∀ s, stable s → ResidentGeometry s (frameBase regions : Word w) offset ((regions).histBase : Word w))
+ (preserve : ∀ s out, stable s →
+ (∀ i : {a : Word w // n ≤ a.val}, i.val.val < (regions).stackBase → out i = s i) → stable out)
+ {g : ℕ} (order : Fin g ≃ Label) (hcount : g ≤ (regions).histWords)
+ (nodeCap limit : ℕ) (shape : ∀ u, desc (leaves u).1 = []) :
+ ∀ {lastDegree lastLanes : ℕ} (E : StateExecution K lastDegree lastLanes X) (W : E.MapWitnesses f)
+ (readers : ExecutionReaders E W) (rec : E.Records) (z : E.Choices),
+ ExecutionOrders E W readers → ∀ ptr : RowPointers (E.termChain rec z),
+ let input := (fromRows (E.termChain rec z) (branchParsers E W readers rec z) ptr
+ (fun u => (leaves u).1) (packed (E.finalState z))).1
+ let valid := Budgeted (regions).arguments format stable desc (privateHistogram order (regions).histBase) nodeCap limit
+ let hook := dispatcher handlers m offset
+ let guard := JobGuard V M m allow (fun j : VisitPath w n => countProbes j.trace ≤ 2 ∧ j.trace.length+17 ≤ n^40)
+ Subtrees hook valid sites (fun v => leafTree (leaves v)) input ∧
+ Emits valid (privateHistogram order (regions).histBase) guard sites input (leafJobs sites leaves) := by
+ intro lastDegree lastLanes E W readers rec z orders ptr input valid hook guard
+ have same : input = fun u q => Packet.mk (leaves u).1 (packed X u q) := by
+ funext u q
+ exact execution_inputPacked E W readers rec z orders ptr (fun i => (leaves i).1) u q
+ rw [same]
+ exact checksBudgeted V M D hD hd budget f bound m header offset arity cap link fit hn hwidth stride rb rl span
+ shadowFit headers size time room boot handlers leaf allow shadow tag tagRead format stable desc typed
+ cached record resident preserve order hcount nodeCap limit shape
+
+/-- The common vertex frame supplies the resident cache and geometry for the
+native leaf reader and persists after every returned leaf. -/
+theorem selectedFramed (link : Contains V M) (fit : (regions).stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ (hn : 2048 ≤ n) (hwidth : b+l ≤ w)
+ (stride : (m (header+15).val).val = cap+2) (rb : (m (header+18).val).val = 2^b)
+ (rl : (m (header+19).val).val = 2^l) (span : (m (header+20).val).val = LiveAuxiliaryHeaders.span L D.hist.length)
+ (shadowFit : (M.publicData 3).val + (m (header+20).val).val ≤ 2^w)
+ (headers : ∀ i < (m (header+20).val).val, (m ((M.publicData 3).val+i)).val = (D.initial i).val)
+ (size : (M.publicData 6).val = n)
+ (time : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w),
+ LeafStartup.steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ n^39)
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length+n^39 ≤ n^40)
+ (boot : ∀ (v : Site (b+l)) (buf : Buffers (b+l) (2^e) w), LeafBoot.ticks D budget.tags budget.capFits v buf ≤ n^15)
+ (handlers : NodeDispatch.Role → HookParser w n)
+ (leaf : handlers .leaf = LeafRole.parser data D budget regions fit m (n^39))
+ (allow : ℕ → Prop) (shadow : ∀ site : Word w, site < fields .span → allow (fields .shadow+site).val)
+ (tag : ∀ u, m (offset+((leaves u).1 : Word w)).val = 0)
+ (tagRead : ∀ u, allow (offset+((leaves u).1 : Word w)).val)
+ (format : Packet → Prop) (desc : ℕ → List ℕ)
+ (typed : ∀ q, format q → q.node < (regions).nodes ∧ q.node < 2^w)
+ {g : ℕ} (order : Fin g ≃ Label) (hcount : g ≤ (regions).histWords)
+ (nodeCap limit : ℕ) (shape : ∀ u, desc (leaves u).1 = []) :
+ ∀ {lastDegree lastLanes : ℕ} (E : StateExecution K lastDegree lastLanes X) (W : E.MapWitnesses f)
+ (readers : ExecutionReaders E W) (rec : E.Records) (z : E.Choices),
+ ExecutionOrders E W readers → ∀ ptr : RowPointers (E.termChain rec z),
+ let input := (fromRows (E.termChain rec z) (branchParsers E W readers rec z) ptr
+ (fun u => (leaves u).1) (packed (E.finalState z))).1
+ let valid := Budgeted (regions).arguments format
+ (VertexFrameData regions data offset (LeafVisit.cacheWords D (b+l) e)) desc
+ (privateHistogram order (regions).histBase) nodeCap limit
+ let hook := dispatcher handlers m offset
+ let guard := JobGuard V M m allow (fun j : VisitPath w n => countProbes j.trace ≤ 2 ∧ j.trace.length+17 ≤ n^40)
+ Subtrees hook valid sites (fun v => leafTree (leaves v)) input ∧
+ Emits valid (privateHistogram order (regions).histBase) guard sites input (leafJobs sites leaves) := by
+ have low : n ≤ (regions).arguments.start := size.ge
+ have endBefore : n < (regions).stackBase := by
+ unfold LeafArena.Regions.stackBase LeafArena.Regions.cacheBase LeafArena.Regions.histBase Arena.base
+ omega
+ intro lastDegree lastLanes E W readers rec z orders ptr
+ exact selectedBudgeted V M D hD hd budget f bound m header offset arity cap link fit hn hwidth stride rb rl span
+ shadowFit headers size time room boot handlers leaf allow shadow tag tagRead format
+ (VertexFrameData regions data offset (LeafVisit.cacheWords D (b+l) e)) desc typed
+ (fun _ h => h.cached) (fun _ h => h.record) (fun _ h => h.resident)
+ (fun _ _ h => h.of_below_stack endBefore) order hcount nodeCap limit shape E W readers rec z orders ptr
+
+end PairSimulation.SelectedCursorLeaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedKernelReaders.lean b/lean/OAI/Computability/VPVNP/PairSelectedKernelReaders.lean
new file mode 100644
index 0000000000..fb102dfcba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedKernelReaders.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.CompressorExecutionLevels
+import OAI.Computability.VPVNP.PairSimulationAssemblyBounds
+
+/-!
+# Identifying the actual local kernel reader at every recorded pass
+
+The origin recorded by the online descriptor selects the very same shrink
+or refresh term parser as the repeated monomial history, including its
+kernel witnesses and all private choice words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression NetworkKernel CompressorRecords
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ {a g b n : ℕ} {X : State a g}
+
+/-- Recover the concrete local term parser indicated by the recorded
+pass constructor, before any surrounding bind or repeat operation. -/
+noncomputable def originReader {p : StatePass R X b n} (origin : PassOrigin B f hf p) :
+ ∀ i, TermParsers f (p.step.term i) :=
+ match origin with
+ | .shrink j h Y => (shrinkPassReaders B f hf j h Y).termParsers
+ | .refresh Y => ((refreshProcedureReaders B f hf _ _ rfl Y).1).termParsers
+
+/-- Agreement holds for all choices of the local profile, including the
+next pass selected by each possible continuation. -/
+def ReaderOrigins {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (K : E.MapWitnesses f) (r : ExecutionReaders E K) (origins : PassOrigins B f hf E) : Prop :=
+ match E with
+ | .done _ => True
+ | .more _ tail => (∀ i, r.1.termParsers i = originReader B f hf origins.1 i) ∧
+ ∀ i, ReaderOrigins (tail i) (K.2 i) (r.2 i) (origins.2 i)
+
+open private bindOrigins ProcedureOrigins idOrigins ProcedureOrigins.seq ProcedureOrigins.reindex
+ shrinkOrigins refreshOrigins prefixOrigins blockOrigins repeatOrigins from OAI.Computability.VPVNP.CompressorExecutionLevels
+open private prefixReaders from OAI.Computability.VPVNP.PairSimulationAssembly
+open private prefixWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+
+private theorem bindMatch {b' n' : ℕ} (E : StateExecution R b n X)
+ (next : (z : E.Choices) → StateExecution R b' n' (E.finalState z))
+ (K : E.MapWitnesses f) (V : ∀ z, (next z).MapWitnesses f)
+ (r : ExecutionReaders E K) (s : ∀ z, ExecutionReaders (next z) (V z))
+ (o : PassOrigins B f hf E) (t : ∀ z, PassOrigins B f hf (next z))
+ (first : ReaderOrigins B f hf E K r o) (rest : ∀ z, ReaderOrigins B f hf (next z) (V z) (s z) (t z)) :
+ ReaderOrigins B f hf (E.bind next) _ (bindReaders E next K V r s) (bindOrigins B f hf E next o t) := by
+ induction E with
+ | done => exact rest ()
+ | more _ _ ih =>
+ exact ⟨first.1,fun i => ih i _ (K.2 i) _ (r.2 i) _ (o.2 i) _ (first.2 i) (fun z => rest ⟨i,z⟩)⟩
+
+variable {l d : ℕ} {μ : ℝ}
+
+private abbrev ProcedureMatch {P : Procedure R a b l d μ} {K : P.MapWitnesses f}
+ (r : ProcedureReaders P K) (o : ProcedureOrigins B f hf P) :=
+ ∀ g n h X, ReaderOrigins B f hf (P.run g n h X) _ (r g n h X) (o g n h X)
+
+private theorem matchId (a : ℕ) : ProcedureMatch B f hf (ProcedureReaders.id a f) (idOrigins B f hf a) := by
+ intro g n h X
+ have eqn := h.trans (Nat.zero_add g)
+ subst g
+ trivial
+
+private theorem matchSeq {c l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} {Q : Procedure R b c l' d' ν}
+ {K : P.MapWitnesses f} {V : Q.MapWitnesses f}
+ {r : ProcedureReaders P K} {s : ProcedureReaders Q V}
+ {o : ProcedureOrigins B f hf P} {t : ProcedureOrigins B f hf Q}
+ (first : ProcedureMatch B f hf r o) (rest : ProcedureMatch B f hf s t) :
+ ProcedureMatch B f hf (r.seq s) (ProcedureOrigins.seq B f hf o t) :=
+ fun g n eqn X =>
+ let E := P.run (l'+g) n (eqn.trans (Nat.add_assoc l l' g)) X
+ bindMatch B f hf E _ _ _ _ _ _ _ (first _ _ _ X) (fun z => rest _ _ _ (E.finalState z))
+
+private theorem matchReindex {a' b' l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ}
+ {K : P.MapWitnesses f} {r : ProcedureReaders P K} {o : ProcedureOrigins B f hf P}
+ (h : ProcedureMatch B f hf r o) {ha : a = a'} {hb : b = b'} {hl : l = l'} {hd : d = d'} {hm : μ = ν} :
+ ProcedureMatch B f hf (r.reindex (ha := ha) (hb := hb) (hl := hl) (hd := hd) (hμ := hm))
+ (ProcedureOrigins.reindex B f hf o) := by subst a' b' l' d' ν; exact h
+
+private theorem shrinkMatch (j : Fin S.steps) :
+ ProcedureMatch B f hf (shrinkProcedureReaders B f hf j) (shrinkOrigins B f hf j) := by
+ intro g n h X
+ subst n
+ exact ⟨fun _ => rfl,fun _ => trivial⟩
+
+private theorem refreshMatch :
+ ProcedureMatch B f hf (refreshProcedureReaders B f hf) (refreshOrigins B f hf) := by
+ intro g n h X
+ subst n
+ exact ⟨fun _ => rfl,fun _ => trivial⟩
+
+private theorem prefixMatch (j : ℕ) (hj : j ≤ S.steps) :
+ ProcedureMatch B f hf (prefixReaders S (B.shrinkProcedure f hf) (B.shrinkProcedureWitnesses f hf)
+ (shrinkProcedureReaders B f hf) j hj) (prefixOrigins B f hf j hj) := by
+ induction j with
+ | zero =>
+ simp only [prefixReaders,prefixOrigins,prefixWitnesses,BlockSchedule.shrinkPrefix]
+ exact matchReindex B f hf (matchId B f hf _)
+ | succ j ih =>
+ simp only [prefixReaders,prefixOrigins,prefixWitnesses,BlockSchedule.shrinkPrefix]
+ exact matchReindex B f hf (matchSeq B f hf (ih (Nat.le_of_succ_le hj))
+ (matchReindex B f hf (shrinkMatch B f hf ⟨j,hj⟩)))
+
+private theorem blockMatch :
+ ProcedureMatch B f hf (blockReaders B f hf) (blockOrigins B f hf) := by
+ unfold blockReaders blockOrigins assembleReaders
+ exact matchReindex B f hf (matchSeq B f hf (matchReindex B f hf (prefixMatch B f hf S.steps le_rfl))
+ (refreshMatch B f hf))
+
+private theorem repeatMatch (g T n : ℕ) (h : n = T*S.laneBits+g) (X : State (S.degreeExponent 0) n) :
+ ReaderOrigins B f hf ((B.procedure f hf).repeatExecution g T n h X) _
+ (repeatReaders (blockReaders B f hf) g T n h X) (repeatOrigins B f hf g T n h X) := by
+ induction T generalizing n with
+ | zero =>
+ have eqn : n = g := by simpa using h
+ subst g
+ trivial
+ | succ T ih =>
+ let E := (B.procedure f hf).run (T*S.laneBits+g) n (by rw [h,Nat.succ_mul]; omega) X
+ exact bindMatch B f hf E _ _ _ _ _ _ _ (blockMatch B f hf _ _ _ X) (fun z => ih _ rfl (E.finalState z))
+
+/-- Matching the physical origin now rewrites the whole selected term parser
+to the shrink or refresh implementation proved at that origin. -/
+theorem execute_originReaders {n : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) :
+ ReaderOrigins B f hf (B.execute f hf T hT X) _
+ (repeatReaders (blockReaders B f hf) _ T n (Nat.add_sub_of_le hT).symm X)
+ (executeOrigins B f hf T hT X) :=
+ repeatMatch B f hf _ T n (Nat.add_sub_of_le hT).symm X
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedLevelChecks.lean b/lean/OAI/Computability/VPVNP/PairSelectedLevelChecks.lean
new file mode 100644
index 0000000000..376d387580
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedLevelChecks.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.PairSelectedRowChecks
+import OAI.Computability.VPVNP.PairSelectedKernelReaders
+
+/-!
+# Checking native row roles at their chronological physical level
+
+The selected-level list stores exactly the origins and profiles used by
+the term chain. Its running row base advances by the size of each real
+input layer. Checking the two native row contracts at these concrete levels
+therefore supplies the whole worker with the corresponding packed records.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NetworkKernel CompressorRecords LocalHistory NodeArguments Compression TraversalRows
+open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels
+open scoped Fin.CommRing
+
+variable {W endAddr : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ (hook : HookParser W endAddr) (valid : List Packet → Scratch W endAddr → Prop)
+ (hist : Scratch W endAddr → B.Entry → ℕ) (guard : VisitPath W endAddr → Prop)
+
+/-- The true outgoing state of this level determines the next numerical
+header row. The kernel is the concrete shrink or refresh reader named by
+the physical origin. -/
+def LevelChecks (cap base : ℕ) (v : SelectedLevel B f hf) : Prop :=
+ let ptr := sitePointers cap (address cap base (siteOrder v.input).length)
+ ((v.pass.output_eq v.term).symm ▸ siteOrder (v.pass.next v.term))
+ let source := fun u z => Packet.mk (sitePointers cap base (siteOrder v.input) u).1 (packed v.input u z)
+ let target := fun u z => Packet.mk (ptr u).1 (pullBits (v.pass.output_eq v.term) (packed (v.pass.next v.term)) u z)
+ let r := originReader B f hf v.origin v.term
+ NodeStep hook valid r ptr source target ∧ EmitsNode valid hist guard r ptr source target
+
+/-- Require both the node-step and emission contracts at each selected level in order,
+advancing the row base past that level's input sites before checking the next level. -/
+def AllLevelChecks (cap : ℕ) : ℕ → List (SelectedLevel B f hf) → Prop
+ | _, [] => True
+ | base, v::vs => LevelChecks B f hf hook valid hist guard cap base v ∧
+ AllLevelChecks cap (address cap base (siteOrder v.input).length) vs
+
+private theorem pushRowAddress {N Z : Network} (e : N = Z) (o : Order Z.Site) (cap base : ℕ) :
+ pushAddress e (fun u => (sitePointers cap base (e.symm ▸ o) u).1) =
+ fun u => (sitePointers cap base o u).1 := by cases e; rfl
+
+omit [CommRing R] in
+private theorem uncastRows {N Z Y : Network} (e : N = Z) (c : TermChain R Z Y) (o : ChainOrders c) (cap base : ℕ) :
+ uncastPointers e c (chainPointers cap (e.symm ▸ c : TermChain R N Y)
+ (show ChainOrders (e.symm ▸ c : TermChain R N Y) from by cases e; exact o) base) =
+ chainPointers cap c o base := by cases e; rfl
+
+private theorem order_length {N Z : Network} (e : N = Z) (o : Order Z.Site) :
+ ((e.symm ▸ o : Order N.Site)).length = o.length := by cases e; rfl
+
+private theorem collected_checks {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (K : E.MapWitnesses f) (r : ExecutionReaders E K) (o : PassOrigins B f hf E)
+ (records : E.Records) (z : E.Choices) (cap base : ℕ) (origins : ReaderOrigins B f hf E K r o)
+ (checked : AllLevelChecks B f hf hook valid hist guard cap base (collectLevels B f hf E K r o z)) :
+ let c := E.termChain records z
+ let ptr := chainPointers cap c (branchOrders E records z) (address cap base (siteOrder X).length)
+ ExecutionChecks hook valid hist guard E K r records z ptr (fun u => (sitePointers cap base (siteOrder X) u).1) := by
+ induction E generalizing base with
+ | done => trivial
+ | @more a g a' g' X p tail ih =>
+ let e := p.output_eq z.1
+ let nextBase := address cap base (siteOrder X).length
+ let ord := siteOrder (p.next z.1)
+ let d := (tail z.1).termChain (records.2 z.1) z.2
+ let ords := branchOrders (tail z.1) (records.2 z.1) z.2
+ let idx := z.1
+ let current : SelectedLevel B f hf := ⟨a,g,a',g',X,p,o.1,idx,r.1.select.encode idx⟩
+ have first : LevelChecks B f hf hook valid hist guard cap base current := checked.1
+ have next := ih idx (K.2 idx) (r.2 idx) (o.2 idx) (records.2 idx) z.2 nextBase (origins.2 idx) checked.2
+ constructor
+ · unfold PassChecks
+ rw [origins.1 idx]
+ exact first
+ · have casted : uncastPointers e d
+ (chainPointers cap (e.symm ▸ d : TermChain R (p.step.term idx).output _)
+ (show ChainOrders (e.symm ▸ d : TermChain R (p.step.term idx).output _) from by
+ exact (branchOrders (.more p tail) records z).2)
+ (address cap nextBase ((e.symm ▸ ord : Order (p.step.term idx).output.Site)).length)) =
+ chainPointers cap d ords (address cap nextBase ord.length) := by
+ rw [order_length e ord]
+ exact uncastRows e d ords cap _
+ exact Eq.mpr (congrArg₂ (fun pp aa => ExecutionChecks hook valid hist guard (tail idx) (K.2 idx)
+ (r.2 idx) (records.2 idx) z.2 pp aa) casted (pushRowAddress e ord cap nextBase)) next
+
+/-- Each row proof now ranges over the concrete chronological level list,
+with its published profile and genuine source/target numerical row bases. -/
+theorem selected_checks {n : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T hT X).Choices) (base : ℕ)
+ (check : AllLevelChecks B f hf hook valid hist guard B.recordLimit base (executeLevels B f hf T hT X z)) :
+ let E := B.execute f hf T hT X
+ let records := B.records f hf T hT X
+ let c := E.termChain records z
+ let r := selectedParsers B f hf T hT X z
+ let ptr := chainPointers B.recordLimit c (branchOrders E records z)
+ (address B.recordLimit base (siteOrder X).length)
+ let addr := fun u => (sitePointers B.recordLimit base (siteOrder X) u).1
+ let frames := fromRows c r ptr addr (packed (E.finalState z))
+ StepLayers hook valid c r ptr frames.2 frames.1 ∧ EmissionLayers valid hist guard c r ptr frames.2 frames.1 := by
+ intro E records c r ptr addr frames
+ let readers := repeatReaders (blockReaders B f hf) _ T n (Nat.add_sub_of_le hT).symm X
+ let origins := executeOrigins B f hf T hT X
+ exact execution_checks hook valid hist guard E _ readers records z ptr addr (execute_readerOrders B f hf T hT X)
+ (collected_checks B f hf hook valid hist guard E _ readers origins records z B.recordLimit base
+ (execute_originReaders B f hf T hT X) check)
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedNativeRoles.lean b/lean/OAI/Computability/VPVNP/PairSelectedNativeRoles.lean
new file mode 100644
index 0000000000..52129881b3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedNativeRoles.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.PairVertexRoleHandlers
+import OAI.Computability.VPVNP.PairVertexRoleDomains
+import OAI.Computability.VPVNP.PairVertexSelectedRoles
+import OAI.Computability.VPVNP.PairVertexSelectedDesc
+import OAI.Computability.VPVNP.PairVertexSelectedRoleLayout
+import OAI.Computability.VPVNP.PairVertexOrdinalRoleCost
+import OAI.Computability.VPVNP.PairTerminalNativeTable
+
+/-!
+# Selecting the actual vertex role at each chronological pass
+
+The frozen descriptor chooses either a shrinking or refresh kernel at each
+output layer. The three physical readers share a finite instruction table,
+a private histogram and the same budgeted packet frontier. Header fields
+and stored role words are read in the current site memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM LiveProgram LiveProgram.PairStages.Group.Auxiliary
+open Compression CompressorRecords LocalHistory NodeArguments TraversalRows TraversalRoles
+open DFS TreeDecode VertexImage NetworkKernel
+open scoped Fin.CommRing
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+ (G : PairStages.Group) (p q n labels : ℕ) (order : B.Entry ≃ Fin labels)
+ (baseBits laneBits : ℕ) (ord : ℕ) (power scan : ℕ)
+
+local notation "pub" => terminalOperands G
+local notation "hdr" => vertexHeader G
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "first" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "tags" => selected B f hf T hT X z
+local notation "L" => BlockProgram.layout B (Fin.val (pub 2)) X.positions T
+local notation "base" => DescriptorSpace.endAddress (L)
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "width" => State.totalWidth (Y)
+local notation "size" => tagWords B.recordLimit (tags)
+local notation "offset" => (((size) + (width) : ℕ) : Word G.w)
+local notation "area" => TerminalLayout.privateRegions (slotDegree S) n ((base) + (size)) labels
+local notation "segments" => nativeSegments B G.constants p q order
+local notation "V" => VertexImage.placement (segments)
+local notation "M" => PrivateRAM.Template.instantiate (VertexImage.template (segments)) G.w pub
+
+variable {calendar reference : Memory G.w} (m : Memory G.w)
+ {bits : Fin ((B.execute f hf T hT X).finalState z).totalWidth → Bool}
+ {tab : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ (pack : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (selected B f hf T hT X z) ((B.execute f hf T hT X).finalState z).totalWidth)
+ (entry : VertexEntry B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ tab baseBits laneBits (terminalOperands G) calendar reference bits)
+ (later : LinkedVertexMemory G reference ord m)
+
+local notation "data" => NativeFrame.leafWords (slotDegree S) pub hdr (offset) m
+
+variable (vals : LeafSourceLoad.Static 34 → Word G.w) (leaf : HookParser G.w n)
+ (shrinkSites : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z)
+ → HookParser G.w n)
+ (refreshReader : HookParser G.w n) (sites : SiteParsers f X.network)
+
+local notation "shrink" => ShrinkRoleDirectory.parser B.recordLimit (base)
+ (first) (passes) shrinkSites
+local notation "readers" => RoleDomains.handlers leaf (shrink) refreshReader
+local notation "source" => privateHistogram order.symm (LeafArena.Regions.histBase (area))
+local notation "doms" => RoleDomains.Domain X B.recordLimit (base) (passes) (area) (data) (offset)
+ vals (source) (n ^ 9000) (n * n ^ 9000)
+local notation "shape" => selectedDesc B f hf T hT X z (base)
+local notation "valid" => Budgeted (W := G.w) (endAddr := n) (LeafArena.Regions.arguments (area))
+ (SelectedPacketFormat B f hf T hT X z (base))
+ (VertexFrameData (area) (data) (offset) vals) (shape) (source) (n ^ 9000) (n * n ^ 9000)
+local notation "hook" => dispatcher (readers) m (offset)
+local notation "guard" => JobGuard (V) (M) m (TerminalLink.workerCell hdr)
+ (ordinalJobCost n power scan)
+local notation "leaves" => sitePointers B.recordLimit (base) (siteOrder X)
+local notation "inputs" => (fun u h => Packet.mk (Prod.fst ((leaves) u)) (packed X u h))
+local notation "atLevel" => (fun i : Fin (passes).length => LevelChecks B f hf (hook) (valid)
+ (source) (guard) B.recordLimit (layerBase B.recordLimit (base) (tags) (Fin.val i)) (passes)[i])
+
+attribute [local irreducible] VertexImage.placement VertexImage.template
+ ShrinkRoleDirectory.parser LevelChecks
+ ordinalJobCost selectedDesc
+
+include pack entry later in
+/-- Role selection and the input domain are fixed by the installed
+eleven-operand table and its frozen rows. Only local role-specific
+execution contracts are required. -/
+theorem VertexEntry.native_checks
+ (length : (pub 6).val = n) (count : (pub 9).val = labels)
+ (native : ∀ r, ((readers) r).ExactOn ((doms) r) (M) ((V).entry (rolePart r))
+ ((V).dfsPC 3) (V).dfs m)
+ (cursor : Subtrees (hook) (valid) sites (fun u => leafTree ((leaves) u)) (inputs) ∧
+ Emits (valid) (source) (guard) sites (inputs) (leafJobs sites (leaves)))
+ (shrinkRows : ∀ i : Fin (passes).length, tagLevel B f hf (passes)[i] = .shrink → (atLevel) i)
+ (refreshRows : ∀ i : Fin (passes).length,
+ tagLevel B f hf (passes)[i] = .refresh → (atLevel) i) :
+ SelectedChecks B f hf T hT X z (base) (V) (M) m
+ ((NativeFrame.frameBase (area) : ℕ) : Word G.w) (offset) (area).histBase
+ order.symm sites (valid) (roleDomain (area) (data) (offset) vals (doms) m)
+ (readers) (ordinalJobCost n power scan) := by
+ obtain ⟨_, _, stored⟩ := entry.role_layout B f hf T hT X z G n labels
+ baseBits laneBits ord m pack later length count
+ have room := pack.room
+ have span := pack.arena
+ have fit : (offset).val + (base) + (size) ≤ 2 ^ G.w := by
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt (by omega : (size) + (width) < 2 ^ G.w)]
+ omega
+ apply SelectedChecks.ofRoleRows B f hf T hT X z (base) (V) (M) m (area) (offset) (data) vals
+ order.symm sites (shape) (n ^ 9000) (n * n ^ 9000) (readers) (doms)
+ (ordinalJobCost n power scan)
+ · have codes : 2 < 2 ^ G.w := by omega
+ exact RoleDomains.domainsReady X B.recordLimit (base) (passes) (area) (data) (offset) vals
+ (source) (n ^ 9000) (n * n ^ 9000) m stored codes fit le_rfl
+ · exact native
+ · exact cursor
+ · intro vs layers i
+ let v := vs[i]
+ have role : tagLevel B f hf v = .shrink ∨ tagLevel B f hf v = .refresh := by
+ rcases v with ⟨_, _, _, _, _, _, origin, _, _⟩
+ cases origin <;> simp [tagLevel, ofOrigin]
+ exact role.elim (shrinkRows i) (refreshRows i)
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedPacketFormat.lean b/lean/OAI/Computability/VPVNP/PairSelectedPacketFormat.lean
new file mode 100644
index 0000000000..57f969c6ab
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedPacketFormat.lean
@@ -0,0 +1,194 @@
+import OAI.Computability.VPVNP.PairIndexedLevelChecks
+import OAI.Computability.VPVNP.PairShrinkRoleDirectory
+
+/-!
+# Typed packets at all rows of a selected traversal
+
+A genuine packet consists of an actual row header and a half-wire value
+encoded in that row's state. This remains a finite union of genuine row
+formats when the tape after the current vertex is arbitrary.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open NetworkKernel CompressorRecords LocalHistory NodeArguments
+open Compression TraversalRows TraversalRoles
+open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels
+open private row_address from OAI.Computability.VPVNP.PairShrinkRoleDirectory
+open private ptr_bounds from OAI.Computability.VPVNP.PairTraversalDisjoint
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k}
+ {B : S.Templates} {f : B.Entry → R} {hf : B.IsSolution f}
+
+/-- The packet pairs a site's row-header address in the supplied order with the encoded bits of
+a half-wire assignment at that same site. -/
+def AtRow {N : Network} (cap base : ℕ) (o : Order N.Site) (bits : ∀ v, N.Half v → List Bool)
+ (q : Packet) : Prop := ∃ u z, q = ⟨(sitePointers cap base o u).1, bits u z⟩
+
+private theorem atRow_cast {N Y : Network} (e : N = Y) (cap base : ℕ) (o : Order Y.Site)
+ (bits : ∀ v, Y.Half v → List Bool) (q : Packet) :
+ AtRow cap base (e.symm ▸ o : Order N.Site) (pullBits e bits) q ↔ AtRow cap base o bits q := by
+ cases e; rfl
+
+/-- Each packet witnesses a concrete site and half assignment in the
+initial state or the true output state of one selected pass. -/
+def PacketFormat {a g : ℕ} (X : State a g) (cap base : ℕ) (leaf : TaggedLayer)
+ (passes : List (SelectedLevel B f hf)) (q : Packet) : Prop :=
+ AtRow cap base (siteOrder X) (packed X) q ∨
+ ∃ i : Fin passes.length, let v := passes[i]
+ let p := v.pass.next v.term
+ AtRow cap (layerBase cap base (leaf :: ShrinkRoleDirectory.outputTags passes) (i.val + 1))
+ (siteOrder p) (packed p) q
+
+theorem PacketFormat.output {a g : ℕ} (X : State a g) (cap base : ℕ) (leaf : TaggedLayer)
+ (passes : List (SelectedLevel B f hf)) (i : Fin passes.length) :
+ let v := passes[i]
+ let pos := layerBase cap base (leaf :: ShrinkRoleDirectory.outputTags passes) (i.val + 1)
+ ∀ u z, PacketFormat X cap base leaf passes
+ ⟨(sitePointers cap pos (ShrinkRoleDirectory.outputOrder v) u).1,
+ pullBits (v.pass.output_eq v.term) (packed (v.pass.next v.term)) u z⟩ := by
+ intro v pos u z
+ exact Or.inr ⟨i,(atRow_cast (v.pass.output_eq v.term) cap pos _ _ _).mp ⟨u,z,rfl⟩⟩
+
+/-- The format provides the exact typed input of a heterogeneous physical
+row parser. In the second case the dependent pair identifies both the pass
+occurrence and its site, using the shared directory's native address. -/
+theorem PacketFormat.cases {a g : ℕ} {X : State a g} {cap base : ℕ} {leaf : TaggedLayer}
+ {passes : List (SelectedLevel B f hf)} {q : Packet}
+ (h : PacketFormat X cap base leaf passes q) :
+ AtRow cap base (siteOrder X) (packed X) q ∨
+ ∃ x : ShrinkRoleDirectory.Site passes,
+ ∃ z : (passes[x.1].pass.step.term passes[x.1].term).output.Half x.2,
+ q = ⟨ShrinkRoleDirectory.address cap base leaf passes x,
+ pullBits (passes[x.1].pass.output_eq passes[x.1].term)
+ (packed (passes[x.1].pass.next passes[x.1].term)) x.2 z⟩ := by
+ rcases h with h | ⟨i,h⟩
+ · exact Or.inl h
+ · let v := passes[i]
+ obtain ⟨u,z,e⟩ := (atRow_cast (v.pass.output_eq v.term) cap _ _ _ q).mpr h
+ exact Or.inr ⟨⟨i,u⟩,z,e⟩
+
+/-- All formatted packets fit in the published row region. This is an
+address bound before converting the natural header to a machine word. -/
+theorem PacketFormat.node_lt {a g : ℕ} {X : State a g} {cap base : ℕ} {leaf : TaggedLayer}
+ {passes : List (SelectedLevel B f hf)} {q : Packet} (h : PacketFormat X cap base leaf passes q)
+ (count : leaf.layer.count = (siteOrder X).length) :
+ q.node < layerBase cap base (leaf :: ShrinkRoleDirectory.outputTags passes)
+ (passes.length + 1) := by
+ let outs := ShrinkRoleDirectory.outputTags passes
+ rcases h.cases with ⟨u,z,rfl⟩ | ⟨x,z,rfl⟩
+ · have low := (ptr_bounds (siteOrder X) cap base u).2
+ have eqn : layerBase cap base (leaf::outs) 1 = address cap base (siteOrder X).length := by
+ rw [layerBase_cons,layerBase_zero,endPos,count]
+ exact low.trans_le (eqn ▸ VertexLevelBounds.layerBase_mono cap base (leaf::outs)
+ (Nat.le_add_left 1 passes.length))
+ · have below := OutputRowDirectory.rowAddress_lt_end cap base leaf outs
+ (ShrinkRoleDirectory.siteRows passes x)
+ rw [row_address] at below
+ simpa only [outs,ShrinkRoleDirectory.outputTags,List.length_map] using below
+
+private theorem extendFormat {a g : ℕ} {X : State a g} (cap base : ℕ) (leaf : TaggedLayer)
+ (cur : SelectedLevel B f hf) (rest : List (SelectedLevel B f hf)) {q : Packet}
+ (h : PacketFormat (cur.pass.next cur.term) cap (endPos cap base leaf.layer)
+ ⟨levelLayer B f hf cur, tagLevel B f hf cur⟩ rest q) :
+ PacketFormat X cap base leaf (cur::rest) q := by
+ rcases h with h | ⟨i,h⟩
+ · refine Or.inr ⟨0,?_⟩
+ change AtRow cap (layerBase cap base
+ (leaf :: ShrinkRoleDirectory.outputTags (cur::rest)) (0+1)) _ _ q
+ rw [layerBase_cons,layerBase_zero]
+ exact h
+ · refine Or.inr ⟨i.succ,?_⟩
+ simpa only [Fin.getElem_fin,Fin.val_succ,List.getElem_cons_succ,layerBase_cons,
+ ShrinkRoleDirectory.outputTags,List.map_cons] using h
+
+private def stateRow {a g : ℕ} (X : State a g) (cap base : ℕ) (q : Packet) : Prop :=
+ AtRow (N := X.network) cap base (siteOrder X) (packed X) q
+
+private def formatInputs {a g b n : ℕ} (X : State a g) (Y : State b n) (cap base : ℕ)
+ (leaf : TaggedLayer)
+ (passes : List (SelectedLevel B f hf)) : Prop :=
+ let pos := layerBase cap base (leaf :: ShrinkRoleDirectory.outputTags passes)
+ (∀ i : Fin passes.length, ∀ q, stateRow passes[i].input cap (pos i.val) q →
+ PacketFormat X cap base leaf passes q) ∧
+ ∀ q, stateRow Y cap (pos passes.length) q → PacketFormat X cap base leaf passes q
+
+section
+
+attribute [local irreducible] stateRow
+
+private theorem prependInputs {b n : ℕ} (Y : State b n) (cap base : ℕ) (leaf : TaggedLayer)
+ (cur : SelectedLevel B f hf) (vs : List (SelectedLevel B f hf))
+ (later : formatInputs (cur.pass.next cur.term) Y cap (endPos cap base leaf.layer)
+ ⟨levelLayer B f hf cur, tagLevel B f hf cur⟩ vs) :
+ formatInputs cur.input Y cap base leaf (cur::vs) := by
+ constructor
+ · intro i
+ cases i using Fin.cases with
+ | zero =>
+ intro q h
+ rw [Fin.val_zero,layerBase_zero] at h
+ exact Or.inl (by unfold stateRow at h; exact h)
+ | succ i =>
+ intro q h
+ apply extendFormat cap base leaf cur vs
+ apply later.1 i q
+ simpa only [Fin.val_succ,Fin.getElem_fin,List.getElem_cons_succ,layerBase_cons,
+ ShrinkRoleDirectory.outputTags,List.map_cons] using h
+ · intro q h
+ apply extendFormat cap base leaf cur vs
+ apply later.2 q
+ simpa only [List.length_cons,layerBase_cons,ShrinkRoleDirectory.outputTags,
+ List.map_cons] using h
+
+private theorem collect_format {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (K : E.MapWitnesses f) (r : ExecutionReaders E K) (o : PassOrigins B f hf E) (z : E.Choices)
+ (cap base : ℕ) (leaf : TaggedLayer) :
+ formatInputs X (E.finalState z) cap base leaf (collectLevels B f hf E K r o z) := by
+ induction E generalizing leaf base with
+ | done =>
+ cases z
+ refine ⟨fun i => Fin.elim0 i,fun q h => Or.inl ?_⟩
+ simp only [collectLevels,List.length_nil,layerBase_zero,StateExecution.finalState] at h
+ unfold stateRow at h
+ exact h
+ | @more a g a' g' X p tail ih =>
+ let cur : SelectedLevel B f hf := ⟨a,g,a',g',X,p,o.1,z.1,r.1.select.encode z.1⟩
+ exact prependInputs ((tail z.1).finalState z.2) cap base leaf cur _
+ (ih z.1 (K.2 z.1) (r.2 z.1) (o.2 z.1) z.2 (endPos cap base leaf.layer) _)
+
+end
+
+variable (B f hf) {n : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T hT X).Choices) (base : ℕ)
+
+/-- Packet format for the chosen execution branch at the template's record limit. Its row and
+payload come from either the initial cursor layer or an output layer of a selected pass. -/
+abbrev SelectedPacketFormat := PacketFormat X B.recordLimit base ⟨leafLayer (siteOrder X),.cursor⟩
+ (executeLevels B f hf T hT X z)
+
+/-- Both the old half packets guessed at a physical level and the real
+terminal root packet at the final layer have the selected format. -/
+theorem selected_format :
+ let passes := executeLevels B f hf T hT X z
+ let tags := selected B f hf T hT X z
+ let Y := (B.execute f hf T hT X).finalState z
+ (∀ i : Fin passes.length, ∀ q, AtRow B.recordLimit (layerBase B.recordLimit base tags i.val)
+ (siteOrder passes[i].input) (packed passes[i].input) q →
+ SelectedPacketFormat B f hf T hT X z base q) ∧
+ ∀ q, AtRow B.recordLimit (layerBase B.recordLimit base tags passes.length)
+ (siteOrder Y) (packed Y) q →
+ SelectedPacketFormat B f hf T hT X z base q :=
+ collect_format (B := B) (f := f) (hf := hf) (B.execute f hf T hT X) _
+ (repeatReaders (blockReaders B f hf) _ T n (Nat.add_sub_of_le hT).symm X)
+ (executeOrigins B f hf T hT X) z B.recordLimit base ⟨leafLayer (siteOrder X),.cursor⟩
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedPacketGeometry.lean b/lean/OAI/Computability/VPVNP/PairSelectedPacketGeometry.lean
new file mode 100644
index 0000000000..d90e5c8106
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedPacketGeometry.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PairSelectedPacketFormat
+import OAI.Computability.VPVNP.PairTraversalRootAddress
+import OAI.Computability.VPVNP.PairSimulationNodeFieldSpace
+
+/-!
+# Root and child argument frames of a selected physical vertex
+
+The terminal site's actual packed half assignment belongs to the selected
+packet format at its root address. Every newly guessed child packet has this
+format and fits the fixed argument stride and the live private word space.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open NetworkKernel CompressorRecords LocalHistory NodeArguments
+open Compression TraversalRows TraversalRoles
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) {lanes : ℕ} (T : ℕ)
+ (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) (base : ℕ)
+
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => selected B f hf T hT X z
+local notation "rows" => selectedLayers B f hf T hT X z
+local notation "pos" => layerBase B.recordLimit base (tags)
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+
+theorem selected_lastBase : (pos) (passes).length = base + words B.recordLimit (rows).dropLast := by
+ have count : (tags).length = (passes).length+1 := by simp [selected]
+ rw [← selected_layers, List.dropLast_eq_take, List.length_map,count,
+ Nat.add_sub_cancel,← List.map_take]
+ rfl
+
+theorem selected_endBase : (pos) ((passes).length+1) = base + words B.recordLimit (rows) := by
+ have count : (tags).length = (passes).length+1 := by simp [selected]
+ rw [layerBase,← count,List.take_length,selected_layers]
+
+/-- The physical packet passed from the final endpoint gather into DFS. -/
+theorem selected_root_format (v : (Y).network.Site) (h : (Y).network.Half v) :
+ SelectedPacketFormat B f hf T hT X z base
+ ⟨(selectedTrees B f hf T hT X z base v).address,packed (Y) v h⟩ := by
+ apply (selected_format B f hf T hT X z base).2
+ refine ⟨v,h,?_⟩
+ rw [selectedTrees_address,selected_lastBase]
+ rfl
+
+theorem selected_packet_node {q : Packet} (format : SelectedPacketFormat B f hf T hT X z base q) :
+ q.node < base + words B.recordLimit (rows) := by
+ rw [← selected_endBase]
+ exact format.node_lt rfl
+
+/-- The whole placed child list, including an empty fiber, meets the
+format and fit premises of the histogram-budgeted frontier transition. -/
+theorem selected_children_fit {n w : ℕ} (regions : LeafArena.Regions)
+ (start : n ≤ regions.arguments.start)
+ (stride : frameStride (slotDegree S) n ≤ regions.arguments.stride)
+ (wordFit : regions.histBase ≤ 2 ^ w)
+ (nodes : base + words B.recordLimit (rows) ≤ regions.nodes)
+ (width : B.growthConstant ^ T * (X.maxWireWidth + 1) ≤ n) (i : Fin (passes).length) :
+ let v := (passes)[i]
+ let reader := originReader B f hf v.origin v.term
+ let input := fun u h => Packet.mk
+ (sitePointers B.recordLimit ((pos) i.val) (siteOrder v.input) u).1
+ (packed v.input u h)
+ ∀ u a q, q ∈ children reader input u a →
+ SelectedPacketFormat B f hf T hT X z base q ∧ q.Fits regions.arguments w n := by
+ intro v reader input u a q h
+ obtain ⟨j,rfl⟩ := List.mem_ofFn.mp h
+ let child := (reader.order.children u).entries j
+ let packet := input child.val (a child.val child.prop)
+ have fmt : SelectedPacketFormat B f hf T hT X z base packet :=
+ (selected_format B f hf T hT X z base).1 i packet ⟨child.val,_,rfl⟩
+ have below := (selected_packet_node B f hf T hT X z base fmt).trans_le nodes
+ have fit := regions.node_before below
+ have width' := ((executeLevels_limits B f hf T hT X z v (List.getElem_mem ..)).2).trans width
+ have size : packet.bits.length ≤ regions.arguments.stride :=
+ (packed_length_le v.input child.val _).trans
+ (((Nat.mul_le_mul (Nat.mul_le_mul_left 2 v.oldDegree_le)
+ width').trans (Nat.le_succ _)).trans stride)
+ exact ⟨fmt,start.trans (Nat.le_add_right _ _),size,
+ (Nat.add_le_add_left size _).trans (fit.trans wordFit)⟩
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedPacketOrders.lean b/lean/OAI/Computability/VPVNP/PairSelectedPacketOrders.lean
new file mode 100644
index 0000000000..e662d0c8ee
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedPacketOrders.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairTreePacketLayers
+import OAI.Computability.VPVNP.PairTraversalSelectedOrder
+
+/-!
+# The actual ordered half-wire packet at every selected pass
+
+The next term's numerical slot order agrees with the state's argument
+arena, also across the output network identification between two stages.
+At the initial cursor site this recovers the four independently supplied
+port buffers used by the physical leaf.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NetworkKernel CompressorRecords LocalHistory NodeArguments Compression
+open scoped Fin.CommRing
+open private castParsers from OAI.Computability.VPVNP.PairSimulationAssemblyBounds
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R}
+ {a g a' g' b n : ℕ} {X : State a g}
+
+/-- Numerical packets at the input to any suffix of the actual schedule. -/
+theorem execution_inputPacked (E : StateExecution R b n X) (W : E.MapWitnesses f)
+ (r : ExecutionReaders E W) (rec : E.Records) (z : E.Choices) (ordered : ExecutionOrders E W r)
+ (ptr : RowPointers (E.termChain rec z)) (addr : X.network.Site → ℕ) (v : X.network.Site)
+ (h : X.network.Half v) :
+ (fromRows (E.termChain rec z) (branchParsers E W r rec z) ptr addr (packed (E.finalState z))).1 v h =
+ ⟨addr v,packed X v h⟩ := by
+ cases E with
+ | done => rfl
+ | more p tail =>
+ change Packet.mk (addr v) ((r.1.termParsers z.1).halfBits v h) = _
+ have out := ordered.1.2.1 z.1 v
+ have inc := ordered.1.2.2 z.1 v
+ change (r.1.termParsers z.1).order.outgoing v = outgoingOrder _ v at out
+ change (r.1.termParsers z.1).order.incoming v = incomingOrder _ v at inc
+ rw [TermParsers.halfBits,out,inc,packed_eq_encode]
+ rfl
+
+/-- Pull a site's half-wire encoder back across a network equality so that the output term can
+use the next state's packed bits. -/
+def pullBits {N Y : Network} (eqn : N = Y) (bits : ∀ v, Y.Half v → List Bool) :
+ ∀ v, N.Half v → List Bool := by cases eqn; exact bits
+
+private theorem castInputPacked {N Z Y : Network} (eqn : N = Z) (c : TermChain R Z Y)
+ (r : ChainParsers f c) (finalBits : ∀ v, Y.Half v → List Bool)
+ (before : ∀ v, Z.Half v → List Bool)
+ (input : ∀ ptr addr v h, (fromRows c r ptr addr finalBits).1 v h = ⟨addr v,before v h⟩)
+ (ptr : RowPointers (eqn.symm ▸ c : TermChain R N Y)) (addr : N.Site → ℕ) (v : N.Site) (h : N.Half v) :
+ (fromRows (eqn.symm ▸ c : TermChain R N Y) (castParsers eqn.symm c r) ptr addr finalBits).1 v h =
+ ⟨addr v,pullBits eqn before v h⟩ := by cases eqn; exact input ptr addr v h
+
+/-- The output arguments consumed by the shrink/refresh kernel at this
+level are precisely the actual packed half-wires of its selected next state. -/
+theorem execution_outputPacked (p : StatePass R X a' g') (tail : ∀ i, StateExecution R b n (p.next i))
+ (W : (StateExecution.more p tail).MapWitnesses f) (r : ExecutionReaders (.more p tail) W)
+ (rec : (StateExecution.more p tail).Records) (z : (StateExecution.more p tail).Choices)
+ (ordered : ExecutionOrders (.more p tail) W r)
+ (ptr : RowPointers ((StateExecution.more p tail).termChain rec z)) (addr : X.network.Site → ℕ)
+ (v : (p.step.term z.1).output.Site) (h : (p.step.term z.1).output.Half v) :
+ (fromRows ((StateExecution.more p tail).termChain rec z) (branchParsers (.more p tail) W r rec z)
+ ptr addr (packed ((StateExecution.more p tail).finalState z))).2.1 v h =
+ ⟨(ptr.1 v).1,pullBits (p.output_eq z.1) (packed (p.next z.1)) v h⟩ := by
+ let E := tail z.1
+ let rr := r.2 z.1
+ let records := rec.2 z.1
+ exact castInputPacked (p.output_eq z.1) (E.termChain records z.2) (branchParsers E (W.2 z.1) rr records z.2)
+ (packed (E.finalState z.2)) (packed (p.next z.1))
+ (execution_inputPacked E (W.2 z.1) rr records z.2 (ordered.2 z.1)) ptr.2 (fun u => (ptr.1 u).1) v h
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+ (κ : B.Entry → R) (hκ : B.IsSolution κ)
+
+/-- In particular the very first packet for the routed RAM cursor has the
+actual cursor state's packed bits and its actual leaf-row pointer. -/
+theorem selected_inputPacked {n : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute κ hκ T hT X).Choices) :
+ let E := B.execute κ hκ T hT X
+ let c := E.termChain (B.records κ hκ T hT X) z
+ let r := selectedParsers B κ hκ T hT X z
+ ∀ ptr addr v h, (fromRows c r ptr addr (packed (E.finalState z))).1 v h = ⟨addr v,packed X v h⟩ := by
+ intro E c r
+ exact execution_inputPacked E _ _ _ z (execute_readerOrders B κ hκ T hT X)
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedRefreshRows.lean b/lean/OAI/Computability/VPVNP/PairSelectedRefreshRows.lean
new file mode 100644
index 0000000000..bab5122a46
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedRefreshRows.lean
@@ -0,0 +1,63 @@
+import OAI.Computability.VPVNP.PairSelectedNativeRoles
+import OAI.Computability.VPVNP.PairVertexRatedRoles
+
+/-! # Complete local refresh contracts on one selected branch -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary
+open Compression CompressorRecords DescriptorSpace DFS TreeDecode LocalHistory TraversalRows
+open TraversalRoles VertexImage NodeArguments
+open scoped Fin.CommRing
+
+variable {k A : Type} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ (G : PairStages.Group) (n p q : ℕ) {labels : ℕ} (order : B.Entry ≃ Fin labels)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+ (m : Memory G.w)
+
+local notation "pub" => terminalOperands G
+local notation "hdr" => vertexHeader G
+local notation "L" => BlockProgram.layout B (Fin.val (pub 2)) X.positions T
+local notation "base" => endAddress (L)
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => selected B f hf T hT X z
+local notation "size" => tagWords B.recordLimit (tags)
+local notation "width" => State.totalWidth (StateExecution.finalState (B.execute f hf T hT X) z)
+local notation "offset" => (((size) + (width) : ℕ) : Word G.w)
+local notation "area" => TerminalLayout.privateRegions (slotDegree S) n ((base) + (size)) labels
+local notation "data" => NativeFrame.leafWords (slotDegree S) pub hdr (offset) m
+local notation "hist" => privateHistogram (W := G.w) (endAddr := n) order.symm
+ (LeafArena.Regions.histBase (area))
+local notation "image" => nativeSegments B G.constants p q order
+local notation "V" => placement (image)
+local notation "M" => PrivateRAM.Template.instantiate (template (image)) G.w pub
+local notation "rate" => RatedRoles.scan B order
+
+/-- One reader proves both acceptance on every prepared refresh row and
+the exact local monomial update of every selected refresh occurrence. -/
+def RefreshRows : Prop :=
+ ∃ refresh : HookParser G.w n, ∀ vals : LeafSourceLoad.Static 34 → Word G.w,
+ let dom := RoleDomains.Domain X B.recordLimit (base) (passes) (area) (data) (offset)
+ vals (hist) (n ^ 9000) (n * n ^ 9000)
+ let valid := Budgeted (W := G.w) (endAddr := n) (area).arguments
+ (SelectedPacketFormat B f hf T hT X z (base)) (VertexFrameData (area) (data) (offset) vals)
+ (selectedDesc B f hf T hT X z (base)) (hist) (n ^ 9000) (n * n ^ 9000)
+ refresh.ExactOn (dom .refresh) (M) ((V).entry .refresh) ((V).dfsPC 3) (V).dfs m ∧
+ ∀ leaf shrink : HookParser G.w n, ∀ i : Fin (passes).length,
+ tagLevel B f hf (passes)[i] = .refresh →
+ LevelChecks B f hf (dispatcher (RoleDomains.handlers leaf shrink refresh) m (offset))
+ valid (hist) (JobGuard (V) (M) m (TerminalLink.workerCell hdr)
+ (ordinalJobCost n 1 (rate))) B.recordLimit
+ (layerBase B.recordLimit (base) (tags) i.val) (passes)[i]
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedRowChecks.lean b/lean/OAI/Computability/VPVNP/PairSelectedRowChecks.lean
new file mode 100644
index 0000000000..3295e8d4c5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedRowChecks.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.PairSelectedPacketOrders
+import OAI.Computability.VPVNP.PairTreeEmissions
+
+/-!
+# Joining the native shrink and refresh row checks along a selected branch
+
+Each local implementation sees the two actual compressor states on either
+side of its own pass, in their numerical slot order. Transport across the
+output-network equality and recursion through the selected passes provide
+both the decoder and emission contracts for the final term chain.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NetworkKernel CompressorRecords LocalHistory NodeArguments Compression
+open scoped Fin.CommRing
+open private castParsers from OAI.Computability.VPVNP.PairSimulationAssemblyBounds
+
+variable {W endAddr : ℕ} {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R}
+ (hook : HookParser W endAddr) (valid : List Packet → Scratch W endAddr → Prop)
+ (hist : Scratch W endAddr → L → ℕ) (guard : VisitPath W endAddr → Prop)
+
+/-- Return a row-pointer family for the original term chain by undoing the transport of its
+input network. -/
+def uncastPointers {N Z Y : Network} (e : N = Z) (c : TermChain R Z Y)
+ (ptr : RowPointers (e.symm ▸ c : TermChain R N Y)) : RowPointers c := by cases e; exact ptr
+
+/-- Transport a numerical site-address function from the term's output network to the equal
+network of the following state. -/
+def pushAddress {N Z : Network} (e : N = Z) (addr : N.Site → ℕ) : Z.Site → ℕ := by cases e; exact addr
+
+private def Claims {N Y : Network} (c : TermChain R N Y) (r : ChainParsers f c)
+ (ptr : RowPointers c) (addr : N.Site → ℕ) (bits : ∀ v, Y.Half v → List Bool) : Prop :=
+ let frames := fromRows c r ptr addr bits
+ StepLayers hook valid c r ptr frames.2 frames.1 ∧ EmissionLayers valid hist guard c r ptr frames.2 frames.1
+
+private theorem castClaims {N Z Y : Network} (e : N = Z) (c : TermChain R Z Y) (r : ChainParsers f c)
+ (ptr : RowPointers (e.symm ▸ c : TermChain R N Y)) (addr : N.Site → ℕ) (bits : ∀ v, Y.Half v → List Bool)
+ (h : Claims hook valid hist guard c r (uncastPointers e c ptr) (pushAddress e addr) bits) :
+ Claims hook valid hist guard (e.symm ▸ c : TermChain R N Y) (castParsers e.symm c r) ptr addr bits := by
+ cases e; exact h
+
+/-- Both local obligations at a state pass, with the actual half-wire
+packets in its source and successor states. -/
+def PassChecks {a g b n : ℕ} {X : State a g} (p : StatePass R X b n) {K : p.MapWitnesses f}
+ (r : PassReaders p K) (i : p.step.Choice) (ptr : (p.step.term i).output.Site → ℕ × ℕ)
+ (addr : X.network.Site → ℕ) : Prop :=
+ let before := fun v z => Packet.mk (addr v) (packed X v z)
+ let next := fun v z => Packet.mk (ptr v).1 (pullBits (p.output_eq i) (packed (p.next i)) v z)
+ NodeStep hook valid (r.termParsers i) ptr before next ∧ EmitsNode valid hist guard (r.termParsers i) ptr before next
+
+/-- A sequence of checks for the individually selected native shrinking
+and degree-refresh rows. -/
+def ExecutionChecks {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (K : E.MapWitnesses f) (r : ExecutionReaders E K) (rec : E.Records) (z : E.Choices)
+ (ptr : RowPointers (E.termChain rec z)) (addr : X.network.Site → ℕ) : Prop :=
+ match E with
+ | .done _ => True
+ | .more p tail =>
+ PassChecks hook valid hist guard p r.1 z.1 ptr.1 addr ∧
+ ExecutionChecks (tail z.1) (K.2 z.1) (r.2 z.1) (rec.2 z.1) z.2
+ (uncastPointers (p.output_eq z.1) _ ptr.2) (pushAddress (p.output_eq z.1) (fun v => (ptr.1 v).1))
+
+/-- A local proof over the actual state records of each pass supplies the
+complete selected-branch hypotheses used by the terminal vertex worker. -/
+theorem execution_checks {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (K : E.MapWitnesses f) (r : ExecutionReaders E K) (rec : E.Records) (z : E.Choices)
+ (ptr : RowPointers (E.termChain rec z)) (addr : X.network.Site → ℕ) (orders : ExecutionOrders E K r)
+ (checked : ExecutionChecks hook valid hist guard E K r rec z ptr addr) :
+ let c := E.termChain rec z
+ let readers := branchParsers E K r rec z
+ let frames := fromRows c readers ptr addr (packed (E.finalState z))
+ StepLayers hook valid c readers ptr frames.2 frames.1 ∧ EmissionLayers valid hist guard c readers ptr frames.2 frames.1 := by
+ change Claims hook valid hist guard _ _ _ _ _
+ induction E with
+ | done => exact ⟨trivial,trivial⟩
+ | @more a g a' g' X p tail ih =>
+ let exec := StateExecution.more p tail
+ let d := (tail z.1).termChain (rec.2 z.1) z.2
+ let pars := branchParsers (tail z.1) (K.2 z.1) (r.2 z.1) (rec.2 z.1) z.2
+ let frames := fromRows (exec.termChain rec z) (branchParsers exec K r rec z) ptr addr (packed (exec.finalState z))
+ let before := fun v z => Packet.mk (addr v) (packed X v z)
+ let next := fun v y => Packet.mk (ptr.1 v).1 (pullBits (p.output_eq z.1) (packed (p.next z.1)) v y)
+ have oldEq : frames.1 = before := by
+ funext v y
+ exact execution_inputPacked exec K r rec z orders ptr addr v y
+ have newEq : frames.2.1 = next := by
+ funext v y
+ exact execution_outputPacked p tail K r rec z orders ptr addr v y
+ have first : NodeStep hook valid (r.1.termParsers z.1) ptr.1 frames.1 frames.2.1 ∧
+ EmitsNode valid hist guard (r.1.termParsers z.1) ptr.1 frames.1 frames.2.1 := by
+ rw [oldEq,newEq]; exact checked.1
+ have tailProof := ih z.1 (K.2 z.1) (r.2 z.1) (rec.2 z.1) z.2
+ (uncastPointers (p.output_eq z.1) d ptr.2) (pushAddress (p.output_eq z.1) (fun v => (ptr.1 v).1))
+ (orders.2 z.1) checked.2
+ have later := castClaims hook valid hist guard (p.output_eq z.1) d pars ptr.2 (fun v => (ptr.1 v).1)
+ (packed (exec.finalState z)) tailProof
+ exact ⟨⟨first.1,later.1⟩,⟨first.2,later.2⟩⟩
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedRowShape.lean b/lean/OAI/Computability/VPVNP/PairSelectedRowShape.lean
new file mode 100644
index 0000000000..caae0e6c59
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedRowShape.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.PairTreeSelectedFrontier
+import OAI.Computability.VPVNP.PairIndexedLevelChecks
+import OAI.Computability.VPVNP.PairShrinkRoleDirectory
+
+/-!
+# Subtree headroom at each physical shrink and refresh row
+
+The descendant list supplied by the selected traversal agrees at each
+chronological output row with the actual child packet order. Replacing
+that row by the child packets therefore consumes exactly one unit of
+the remaining-vertex allowance.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open NetworkKernel CompressorRecords LocalHistory NodeArguments
+open Compression TraversalRows TraversalRoles
+open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels
+open private castParsers from OAI.Computability.VPVNP.PairSimulationAssemblyBounds
+open private pushRowAddress uncastRows order_length from OAI.Computability.VPVNP.PairSelectedLevelChecks
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates)
+ (f : B.Entry → R) (hf : B.IsSolution f) (desc : ℕ → List ℕ)
+
+/-- At every selected output site, the descriptor's descendant list is the concatenation, in
+reader order, of each input child's row address followed by that child's descendants. -/
+def LevelShape (cap before after : ℕ) (v : SelectedLevel B f hf) : Prop :=
+ ∀ u, desc (sitePointers cap after (ShrinkRoleDirectory.outputOrder v) u).1 =
+ childAddresses (originReader B f hf v.origin v.term)
+ (fun t => (sitePointers cap before (siteOrder v.input) t).1) desc u
+
+private def Shapes (cap : ℕ) : ℕ → List (SelectedLevel B f hf) → Prop
+ | _, [] => True
+ | base, v::vs => let next := address cap base (siteOrder v.input).length
+ LevelShape B f hf desc cap base next v ∧ Shapes cap next vs
+
+private theorem uncastDesc {N Z Y : Network} (e : N = Z) (c : TermChain R Z Y)
+ (r : ChainParsers f c) (ptr : RowPointers (e.symm ▸ c : TermChain R N Y)) (addr : N.Site → ℕ)
+ (h : DescLayers (e.symm ▸ c : TermChain R N Y) (castParsers e.symm c r) ptr addr desc) :
+ DescLayers c r (uncastPointers e c ptr) (pushAddress e addr) desc := by cases e; exact h
+
+private theorem collected_shape {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (K : E.MapWitnesses f) (r : ExecutionReaders E K) (o : PassOrigins B f hf E)
+ (records : E.Records) (z : E.Choices) (cap base : ℕ) (origins : ReaderOrigins B f hf E K r o)
+ (rows : let c := E.termChain records z
+ DescLayers c (branchParsers E K r records z)
+ (chainPointers cap c (branchOrders E records z) (address cap base (siteOrder X).length))
+ (fun u => (sitePointers cap base (siteOrder X) u).1) desc) :
+ Shapes B f hf desc cap base (collectLevels B f hf E K r o z) := by
+ induction E generalizing base with
+ | done => trivial
+ | @more a g a' g' X p tail ih =>
+ let e := p.output_eq z.1
+ let nextBase := address cap base (siteOrder X).length
+ let ord := siteOrder (p.next z.1)
+ let d := (tail z.1).termChain (records.2 z.1) z.2
+ let ords := branchOrders (tail z.1) (records.2 z.1) z.2
+ let rr := branchParsers (tail z.1) (K.2 z.1) (r.2 z.1) (records.2 z.1) z.2
+ let idx := z.1
+ let current : SelectedLevel B f hf := ⟨a,g,a',g',X,p,o.1,idx,r.1.select.encode idx⟩
+ constructor
+ · change LevelShape B f hf desc cap base nextBase current
+ unfold LevelShape
+ rw [← origins.1 idx]
+ exact rows.1
+ · apply ih idx (K.2 idx) (r.2 idx) (o.2 idx) (records.2 idx) z.2 nextBase (origins.2 idx)
+ have tailDesc := uncastDesc B f desc e d rr _ (fun v => (sitePointers cap nextBase
+ (e.symm ▸ ord : Order (p.step.term idx).output.Site) v).1) rows.2
+ have ptrEq : uncastPointers e d
+ (chainPointers cap (e.symm ▸ d : TermChain R (p.step.term idx).output _)
+ (show ChainOrders (e.symm ▸ d : TermChain R (p.step.term idx).output _) from by
+ exact (branchOrders (.more p tail) records z).2)
+ (address cap nextBase ((e.symm ▸ ord : Order (p.step.term idx).output.Site)).length)) =
+ chainPointers cap d ords (address cap nextBase ord.length) := by
+ rw [order_length e ord]
+ exact uncastRows e d ords cap _
+ exact Eq.mp (congrArg₂ (fun pp aa => DescLayers d rr pp aa desc) ptrEq
+ (pushRowAddress e ord cap nextBase)) tailDesc
+
+private theorem indexShape (cap : ℕ) (vs : List (SelectedLevel B f hf)) (pos : ℕ → ℕ)
+ (step : ∀ i : Fin vs.length, pos (i.val + 1) =
+ address cap (pos i.val) (siteOrder vs[i].input).length)
+ (h : Shapes B f hf desc cap (pos 0) vs) (i : Fin vs.length) :
+ LevelShape B f hf desc cap (pos i.val) (pos (i.val + 1)) vs[i] := by
+ induction vs generalizing pos with
+ | nil => exact Fin.elim0 i
+ | cons v vs ih =>
+ cases i using Fin.cases with
+ | zero => rw [step 0]; exact h.1
+ | succ i =>
+ apply ih (fun j => pos (j+1)) (fun j => step j.succ) _ i
+ have first : pos (0+1) = address cap (pos 0) (siteOrder v.input).length := step 0
+ rw [first]
+ exact h.2
+
+/-- The full headroom transition at the genuinely indexed native row,
+independently of the selected or malformed private suffix. -/
+theorem selected_rowShape {n : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n)
+ (X : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T hT X).Choices) (base : ℕ)
+ (rows : let E := B.execute f hf T hT X
+ let records := B.records f hf T hT X
+ let c := E.termChain records z
+ DescLayers c (selectedParsers B f hf T hT X z)
+ (chainPointers B.recordLimit c (branchOrders E records z)
+ (address B.recordLimit base (siteOrder X).length))
+ (fun u => (sitePointers B.recordLimit base (siteOrder X) u).1) desc) :
+ let passes := executeLevels B f hf T hT X z
+ let pos := layerBase B.recordLimit base (selected B f hf T hT X z)
+ ∀ i : Fin passes.length, LevelShape B f hf desc B.recordLimit
+ (pos i.val) (pos (i.val + 1)) passes[i] := by
+ intro passes pos
+ apply indexShape B f hf desc B.recordLimit passes pos (selected_level_bases B f hf T hT X z base)
+ change Shapes B f hf desc B.recordLimit
+ (layerBase B.recordLimit base (selected B f hf T hT X z) 0) passes
+ rw [layerBase_zero]
+ exact collected_shape B f hf desc _ _ _ _ _ z B.recordLimit base
+ (execute_originReaders B f hf T hT X) rows
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSelectedShrinkRows.lean b/lean/OAI/Computability/VPVNP/PairSelectedShrinkRows.lean
new file mode 100644
index 0000000000..8da2e3c8ee
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSelectedShrinkRows.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.PairSelectedNativeRoles
+import OAI.Computability.VPVNP.PairVertexRatedRoles
+
+/-! # Native shrinking-role contracts at a selected physical vertex -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary
+open Compression CompressorRecords DescriptorSpace DFS TreeDecode LocalHistory TraversalRows
+open TraversalRoles VertexImage NodeArguments
+open scoped Fin.CommRing
+
+variable {k A : Type} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ (G : PairStages.Group) (n p q : ℕ) {labels : ℕ} (order : B.Entry ≃ Fin labels)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+ (m : Memory G.w)
+
+local notation "pub" => terminalOperands G
+local notation "hdr" => vertexHeader G
+local notation "L" => BlockProgram.layout B (Fin.val (pub 2)) X.positions T
+local notation "base" => endAddress (L)
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => selected B f hf T hT X z
+local notation "size" => tagWords B.recordLimit (tags)
+local notation "width" => State.totalWidth (StateExecution.finalState (B.execute f hf T hT X) z)
+local notation "offset" => (((size) + (width) : ℕ) : Word G.w)
+local notation "area" => TerminalLayout.privateRegions (slotDegree S) n ((base) + (size)) labels
+local notation "data" => NativeFrame.leafWords (slotDegree S) pub hdr (offset) m
+local notation "hist" => privateHistogram (W := G.w) (endAddr := n) order.symm
+ (LeafArena.Regions.histBase (area))
+local notation "image" => nativeSegments B G.constants p q order
+local notation "V" => placement (image)
+local notation "M" => PrivateRAM.Template.instantiate (template (image)) G.w pub
+local notation "rate" => RatedRoles.scan B order
+
+/-- The same physical site readers give the accepted native shrinking tapes and
+the monomial of every shrinking occurrence in the chronological history. -/
+def ShrinkRows : Prop :=
+ ∃ readers : ShrinkRoleDirectory.ShrinkSite (passes) → HookParser G.w n,
+ let first : TaggedLayer := ⟨leafLayer (siteOrder X), .cursor⟩
+ let shrink := ShrinkRoleDirectory.parser B.recordLimit (base) first (passes) readers
+ ∀ vals : LeafSourceLoad.Static 34 → Word G.w,
+ let dom := RoleDomains.Domain X B.recordLimit (base) (passes) (area) (data) (offset)
+ vals (hist) (n ^ 9000) (n * n ^ 9000)
+ let valid := Budgeted (W := G.w) (endAddr := n) (area).arguments
+ (SelectedPacketFormat B f hf T hT X z (base)) (VertexFrameData (area) (data) (offset) vals)
+ (selectedDesc B f hf T hT X z (base)) (hist) (n ^ 9000) (n * n ^ 9000)
+ shrink.ExactOn (dom .shrink) (M) ((V).entry .shrink) ((V).dfsPC 3) (V).dfs m ∧
+ ∀ leaf refresh : HookParser G.w n, ∀ i : Fin (passes).length,
+ tagLevel B f hf (passes)[i] = .shrink →
+ LevelChecks B f hf (dispatcher (RoleDomains.handlers leaf shrink refresh) m (offset))
+ valid (hist) (JobGuard (V) (M) m (TerminalLink.workerCell hdr)
+ (ordinalJobCost n 1 (rate))) B.recordLimit
+ (layerBase B.recordLimit (base) (tags) i.val) (passes)[i]
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkABBuffers.lean b/lean/OAI/Computability/VPVNP/PairShrinkABBuffers.lean
new file mode 100644
index 0000000000..3a70e74bc4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkABBuffers.lean
@@ -0,0 +1,207 @@
+import OAI.Computability.VPVNP.CompressorShrinkABSliceTable
+import OAI.Computability.VPVNP.PairNodeArguments
+
+/-!
+# AB demand buffers of a resident shrinking map
+
+The packed descriptor stores a three-word interval for each pair consisting
+of a thick old arc and an assigned motif. Its source and target offsets are
+relative to the old half-word and the selected AB operand. Each frame copies
+a slice from one old half. Taken in old-field order these writes reconstruct
+the precise row argument of the matrix at either A or B, even when the two
+old halves were guessed independently.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkAB
+
+open BurstRAM Compression Compression.PackingData CompressorRecords
+open ShrinkSliceArrays SliceSchedule
+open scoped Fin.CommRing
+
+variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (P : PackingData V H Tag L d c) (number : P.BundleNumbering) (order : P.ThickNumbering)
+variable (width : Arc V H Tag L d c → ℕ) {b : Site V Tag L × Fin d} (m : P.MotifFiber b)
+
+/-- Physical start of the three words in the completed indexed-starts bank. -/
+def frame {w : ℕ} (B : Word w) (a : P.ThickFiber b) : ℕ :=
+ B.val + (2 ^ c * d / 4) + pieceCount d c +
+ 3 * ((order b a).val * pieceCount d c + (number b m).val)
+
+/-- The physical word loads from the final AB bank yield the exact typed slice. -/
+theorem frame_words {w : ℕ} {B : Word w} {mem : Memory w}
+ (stored : IndexedStarts.Stored B (thickWidths P order width b) (abWidths P number width b) mem)
+ (a : P.ThickFiber b) :
+ let f := frame P number order m B a
+ let s := P.demandSlice number order width b a m
+ (mem (f+2)).val = s.length ∧
+ (0 < s.length → (mem f).val = s.sourceOffset ∧ (mem (f+1)).val = s.targetOffset) := by
+ intro f s
+ let i := (order b a).val * pieceCount d c + (number b m).val
+ have ho : (thickWidths P order width b).length = 2 ^ c * d / 4 := List.length_ofFn
+ have hn : (abWidths P number width b).length = pieceCount d c := List.length_ofFn
+ have hi : i < (thickWidths P order width b).length * (abWidths P number width b).length := by
+ rw [ho,hn]
+ calc
+ _ < (order b a).val * pieceCount d c + pieceCount d c :=
+ Nat.add_lt_add_left (number b m).isLt _
+ _ = ((order b a).val + 1) * pieceCount d c := (Nat.succ_mul _ _).symm
+ _ ≤ _ := Nat.mul_le_mul_right _ (order b a).isLt
+ have hs := ab_sliceAt P number order width b a m
+ have len := stored.lengths i hi
+ rw [ho,hn,hs] at len
+ refine ⟨len, fun hp ↦ ?_⟩
+ have off := stored.offsets i hi (hs ▸ hp)
+ rw [ho, hn, hs] at off
+ exact off
+
+theorem source_bound (a : P.ThickFiber b) :
+ let s := P.demandSlice number order width b a m
+ ∀ k : Fin s.length, s.sourceOffset + k.val < width a.1.1 := by
+ intro s k
+ have hk := k.isLt
+ dsimp [s,demandSlice,copySlice] at hk ⊢
+ omega
+
+theorem target_bound (a : P.ThickFiber b) :
+ let s := P.demandSlice number order width b a m
+ 0 < s.length → s.targetOffset + s.length ≤ P.abWidth number width m.val := by
+ intro s h
+ dsimp [s,demandSlice,copySlice] at h ⊢
+ omega
+
+/-- Bits copied by a single actual AB frame at either packed endpoint. -/
+def copyBits (data : (a : P.ThickFiber b) → Fin (width a.1.1) → Bool) (a : P.ThickFiber b) :
+ List Bool :=
+ let s := P.demandSlice number order width b a m
+ List.ofFn fun k : Fin s.length ↦
+ data a ⟨s.sourceOffset+k.val, source_bound P number order width m a k⟩
+
+/-- Read the AB operand of the typed demand-bit bijection from a collection of
+old half-wires. The field data can be different at the two packed endpoints. -/
+def operand (hc : 2 ≤ c) (hd : 0 < d) (data : (a : P.ThickFiber b) → Fin (width a.1.1) → Bool)
+ (j : Fin (P.abWidth number width m.val)) : Bool :=
+ let a := P.demandBitEquiv hc hd number order width b ⟨m, j⟩
+ data a.1 a.2
+
+/-- Each copied bit already has its eventual value in the assembled AB word. -/
+theorem copyBits_operand (hc : 2 ≤ c) (hd : 0 < d)
+ (data : (a : P.ThickFiber b) → Fin (width a.1.1) → Bool) (a : P.ThickFiber b) :
+ let s := P.demandSlice number order width b a m
+ ∀ k : Fin s.length, (copyBits P number order width m data a)[k.val]? =
+ some (operand P number order width m hc hd data
+ ⟨s.targetOffset+k.val, lt_of_lt_of_le (Nat.add_lt_add_left k.isLt _)
+ (target_bound P number order width m a (Nat.zero_lt_of_lt k.isLt))⟩) := by
+ intro s k
+ let src : Fin (width a.1.1) := ⟨s.sourceOffset+k.val, source_bound P number order width m a k⟩
+ let dst : Fin (P.abWidth number width m.val) := ⟨s.targetOffset+k.val,
+ lt_of_lt_of_le (Nat.add_lt_add_left k.isLt _) (target_bound P number order width m a
+ (Nat.zero_lt_of_lt k.isLt))⟩
+ have he := (P.demandBitEquiv_eq_iff_slice number order width b hc hd a m src dst).2
+ ⟨k.val,k.isLt,rfl,rfl⟩
+ change _ = some (let z := P.demandBitEquiv hc hd number order width b ⟨m,dst⟩; data z.1 z.2)
+ rw [he]
+ simp only [copyBits, List.getElem?_ofFn, src]
+ split <;> simp_all [s]
+
+/-- Private-memory effect of the source-major copies into one AB destination. -/
+def fill {w : ℕ} (base : ℕ) (data : (a : P.ThickFiber b) → Fin (width a.1.1) → Bool)
+ (as : List (P.ThickFiber b)) (mem : Word w → Word w) : Word w → Word w :=
+ as.foldl (fun old a ↦ PrivateFields.storeBits
+ (base + (P.demandSlice number order width b a m).targetOffset)
+ (copyBits P number order width m data a) old) mem
+
+private theorem store_bit {w : ℕ} (dst : ℕ) (bits : List Bool) (mem : Word w → Word w)
+ (k : ℕ) (bit : Bool) (get : bits[k]? = some bit) (fit : dst + bits.length ≤ 2 ^ w) :
+ PrivateFields.storeBits dst bits mem ((dst+k : ℕ) : Word w) = PrivateFields.bitValue w bit := by
+ have hk : k < bits.length := by
+ by_contra! h
+ rw [List.getElem?_eq_none h] at get
+ contradiction
+ rw [List.getElem?_eq_getElem hk, Option.some.injEq] at get
+ exact (PrivateFields.storeBits_read dst bits mem fit ⟨k,hk⟩).trans (congrArg _ get)
+
+/-- A positive slice writes its own target coordinates and leaves every other
+coordinate of the AB word unchanged. Zero-length frames have no memory effect. -/
+private theorem store_at_target {w : ℕ} (hc : 2 ≤ c) (hd : 0 < d) (base : ℕ)
+ (fit : base + P.abWidth number width m.val ≤ 2 ^ w)
+ (data : (a : P.ThickFiber b) → Fin (width a.1.1) → Bool) (a : P.ThickFiber b)
+ (j : Fin (P.abWidth number width m.val)) (mem : Word w → Word w) :
+ let s := P.demandSlice number order width b a m
+ let f := (base+j.val : ℕ)
+ PrivateFields.storeBits (base+s.targetOffset) (copyBits P number order width m data a) mem
+ (f : Word w) = if s.targetOffset ≤ j.val ∧ j.val < s.targetOffset+s.length then
+ PrivateFields.bitValue w (operand P number order width m hc hd data j) else mem f := by
+ intro s f
+ let bs := copyBits P number order width m data a
+ have len : bs.length = s.length := List.length_ofFn
+ by_cases hz : s.length = 0
+ · have nil : bs = [] := List.length_eq_zero_iff.mp (len.trans hz)
+ change PrivateFields.storeBits _ bs _ _ = _
+ simp [nil, hz, PrivateFields.storeBits]
+ have range := target_bound P number order width m a (Nat.pos_of_ne_zero hz)
+ change s.targetOffset + s.length ≤ _ at range
+ have cap : base+s.targetOffset+bs.length ≤ 2 ^ w := by omega
+ by_cases h : s.targetOffset ≤ j.val ∧ j.val < s.targetOffset+s.length
+ · rw [ite_eq_left h]
+ let k : Fin s.length := ⟨j.val-s.targetOffset, by omega⟩
+ have hval : s.targetOffset+k.val = j.val := Nat.add_sub_of_le h.1
+ have he := copyBits_operand P number order width m hc hd data a k
+ have hdj : (⟨s.targetOffset+k.val, by omega⟩ : Fin (P.abWidth number width m.val)) = j :=
+ Fin.ext hval
+ rw [hdj] at he
+ change PrivateFields.storeBits _ bs _ _ = _
+ rw [show f = (base+s.targetOffset)+k.val by dsimp [f]; omega]
+ exact store_bit _ _ _ _ _ he cap
+ · rw [ite_eq_right h]
+ apply PrivateFields.storeBits_outside _ _ _ _ cap
+ have hf : (f : Word w).val = f := Nat.mod_eq_of_lt (by dsimp [f]; omega)
+ rw [hf]
+ dsimp only [f]
+ omega
+
+/-- Visiting every thick arc in the bundle reconstructs the exact AB buffer.
+The physical readout works for arbitrary prior destination memory. -/
+theorem fill_operand {w : ℕ} (hc : 2 ≤ c) (hd : 0 < d) (base : ℕ)
+ (fit : base + P.abWidth number width m.val ≤ 2 ^ w)
+ (data : (a : P.ThickFiber b) → Fin (width a.1.1) → Bool)
+ (as : List (P.ThickFiber b)) (mem : Word w → Word w) (j : Fin (P.abWidth number width m.val))
+ (covered : (P.demandBitEquiv hc hd number order width b ⟨m, j⟩).1 ∈ as ∨
+ mem ((base + j.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (operand P number order width m hc hd data j)) :
+ fill P number order width m base data as mem ((base + j.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (operand P number order width m hc hd data j) := by
+ induction as generalizing mem with
+ | nil => exact covered.resolve_left (by simp)
+ | cons a as ih =>
+ apply ih
+ have hs := store_at_target P number order width m hc hd base fit data a j mem
+ dsimp only at hs
+ by_cases inside : (P.demandSlice number order width b a m).targetOffset ≤ j.val ∧
+ j.val < (P.demandSlice number order width b a m).targetOffset +
+ (P.demandSlice number order width b a m).length
+ · exact Or.inr (hs.trans (ite_eq_left inside))
+ · rw [ite_eq_right inside] at hs
+ refine covered.elim (fun ha ↦ Or.inl ?_) (fun val ↦ Or.inr (hs.trans val))
+ rw [List.mem_cons] at ha
+ apply ha.resolve_left
+ intro he
+ cases hraw : P.demandBitEquiv hc hd number order width b ⟨m, j⟩ with
+ | mk src idx =>
+ rw [hraw] at he
+ change src = a at he
+ subst a
+ obtain ⟨k,hk,_,hj⟩ :=
+ (P.demandBitEquiv_eq_iff_slice number order width b hc hd src m idx j).mp hraw
+ exact inside ⟨by omega, by omega⟩
+
+end PairSimulation.ShrinkAB
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkABFrameAddress.lean b/lean/OAI/Computability/VPVNP/PairShrinkABFrameAddress.lean
new file mode 100644
index 0000000000..36d241a467
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkABFrameAddress.lean
@@ -0,0 +1,366 @@
+import OAI.Computability.VPVNP.PairResidentFrameColumn
+import OAI.Computability.VPVNP.PairSimulationNodeFieldSpace
+import OAI.Computability.VPVNP.PairShrinkABNative
+import OAI.Computability.VPVNP.PairShrinkOldHalfAddresses
+import OAI.Computability.VPVNP.CompressorBundleRankedInput
+import OAI.Computability.VPVNP.CompressorShrinkMotifOrder
+
+/-!
+# Physical pointers for the AB operand copies
+
+The resident map supplies its dense motif ordinal. Dividing this by the
+number of AB pieces selects a thick-wire list, in the order actually written
+by the preimage scan. Its old arc ID locates the independent child half. The
+rank at that same ID selects the source-major slice frame in the bundle bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkAB.Physical
+
+open Compression Compression.PackingData CompressorRecords CompressorRecords.PhaseRecipe
+open BurstRAM BurstRAM.PrivateRAM BundleLists ShrinkSliceArrays
+open scoped Fin.CommRing
+
+/-- Operands available at the entry of a resident AB copy. -/
+structure Header where
+ /-- Private argument-arena parameters and incidence heads for recovering an old endpoint's
+ half-wire address. -/
+ oldHalf : ShrinkOldHalves.Physical.Header
+ /-- Dense ordinal of the selected CD motif. Division by the piece count gives its bundle
+ number. -/
+ motif : Expr
+ /-- Start of the classified bundle rows containing original arc IDs in append order. -/
+ lists : Expr
+ /-- Distance in words between consecutive classified bundle rows. -/
+ listStride : Expr
+ /-- Head of the array mapping each old arc ID to its rank within its bundle. -/
+ rankBase : Expr
+ /-- Base of the consecutive AB frame banks, one bank per bundle. -/
+ banks : Expr
+ /-- Private staging address where this party gathers its AB demand word. -/
+ destination : Expr
+
+/-- Quotient of the dense motif ordinal by the fixed number of pieces in each bundle. -/
+def Header.bundle (h : Header) (pieces : ℕ) := h.motif.div (.lit pieces)
+
+/-- Remainder of the dense motif ordinal modulo the bundle's piece count, used to select the
+frame column. -/
+def Header.piece (h : Header) (pieces : ℕ) := h.motif.mod (.lit pieces)
+
+/-- The row contains original old arc IDs in append order. -/
+def Header.arc (h : Header) (pieces index : ℕ) : Expr :=
+ .load ((h.lists.add ((h.bundle pieces).mul h.listStride)).add (.lit index))
+
+/-- Address the three-word AB frame at the old arc's stored rank and the motif's piece number,
+after the bundle's two width arrays. -/
+def Header.frame (h : Header) (count pieces index : ℕ) : Expr :=
+ let rank := Expr.load (h.rankBase.add (h.arc pieces index))
+ let bank := h.banks.add ((h.bundle pieces).mul (.lit (IndexedStarts.capacity count pieces)))
+ (bank.add (.lit (count + pieces))).add
+ ((Expr.lit 3).mul ((rank.mul (.lit pieces)).add (h.piece pieces)))
+
+variable {w a g : ℕ} (X : State a (packingLaneBits a g))
+local notation "P" => X.packingData
+local notation "d" => 2 ^ a
+local notation "c" => Shrink.colors a
+local notation "arcs" => BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex
+local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex
+local notation "arcCount" => Fintype.card X.Base * 2 ^ (packingLaneBits a g) * d
+local notation "bundleCount" => (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * d
+local notation "count" => 2 ^ c * d / 4
+local notation "pieces" => pieceCount d c
+
+/-- Classical equality on old base vertices for the thick-arc fiber and its ordinal
+enumeration. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Convert a fixed loop ordinal to the old thick arc encountered by the
+original ID list. This is a bijection even if the key ordering differs. -/
+noncomputable def members (arcFit : arcCount ≤ 2 ^ w)
+ (bucketFit : bundleCount + bundleCount ≤ 2 ^ w)
+ (b : Port X.Base (BitWord (Shrink.J a)) (BitWord g) d) :
+ Fin count ≃ (P).ThickFiber b :=
+ let size := arcList_length (P) arcs sites (State.two_le_packingColors a) arcFit bucketFit (.inl b)
+ ((finCongr size.symm).trans (ordinalEquiv (P) arcs sites arcFit bucketFit (.inl b))).trans
+ (thickEquiv (P) b)
+
+variable (h : Header) (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+variable (q : Fin 6 → Word w) (s : Fin 5 → Word w) (first dest : ℕ)
+
+/-- Agreement of the evaluated AB header with the selected motif ordinal, classified lists,
+rank array, frame bank, and private destination. -/
+structure Header.Stored (m : (P).Motif) : Prop where
+ motif : (h.motif.eval pub state mem).val = (ShrinkMotifOrder.stateNumber X m).val
+ lists : h.lists.eval pub state mem = q 5
+ listStride : h.listStride.eval pub state mem = q 4
+ rankBase : h.rankBase.eval pub state mem = s 1
+ banks : h.banks.eval pub state mem = CursorRAM.encode w first
+ destination : h.destination.eval pub state mem = CursorRAM.encode w dest
+
+private theorem of_val {x : Word w} {n : ℕ} (h : x.val = n) : x = CursorRAM.encode w n := by
+ subst n
+ exact Fin.ext (Nat.mod_eq_of_lt x.isLt).symm
+
+private theorem unpack {x y : Word w} {u v : ℕ} (eqn : x.val = u * y.val + v) (lo : v < y.val) :
+ (BinaryOp.div.eval x y).val = u ∧ (BinaryOp.mod.eval x y).val = v := by
+ have q : x.val / y.val = u := by
+ rw [eqn, Nat.mul_comm u, Nat.mul_add_div (Nat.zero_lt_of_lt lo),
+ Nat.div_eq_of_lt lo, Nat.add_zero]
+ exact ⟨(Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)).trans q,
+ (Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt)).trans (eqn ▸ Nat.mul_add_mod_of_lt lo)⟩
+
+variable {q s first dest}
+variable (m : X.packingData.Motif) (stored : h.Stored X pub state mem q s first dest m)
+variable (arcFit : Fintype.card X.Base * 2 ^ (packingLaneBits a g) * 2 ^ a ≤ 2 ^ w)
+variable (bucketFit : (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a +
+ (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a ≤ 2 ^ w)
+variable (pieceFit : pieceCount (2 ^ a) (Shrink.colors a) < 2 ^ w)
+local notation "b" => X.packingData.bundle m
+local notation "port" => portIndex sites b
+local notation "fiber" => Subtype.mk m (Eq.refl b)
+local notation "piece" => X.shrinkNumber b fiber
+
+include stored pieceFit in
+theorem coordinates :
+ (h.bundle pieces).eval pub state mem = CursorRAM.encode w (port).val ∧
+ (h.piece pieces).eval pub state mem = CursorRAM.encode w (piece).val := by
+ have dy : (CursorRAM.encode w pieces).val = pieces := Nat.mod_eq_of_lt pieceFit
+ have hm := stored.motif.trans (ShrinkMotifOrder.number_val (P) X.shrinkNumber sites m)
+ have v := unpack (x := h.motif.eval pub state mem) (y := CursorRAM.encode w pieces)
+ (u := (port).val) (v := (piece).val) (by rw [dy]; exact hm)
+ (by rw [dy]; exact (piece).isLt)
+ exact ⟨of_val v.1, of_val v.2⟩
+
+variable (i : Fin (2 ^ (Shrink.colors a) * 2 ^ a / 4))
+local notation "t" => members X arcFit bucketFit b i
+
+private theorem actual_id (e : BundleKeys.OldArc X.Base a g) :
+ Fin.ofNat (2 ^ w) (arcs e).val =
+ IncidenceDirectory.actualPort X (packingInputEdges X.Base a g e) := by
+ rw [BundleKeys.oldArcOrder_val, Shrink.oldNumber_original]
+ rfl
+
+open private row_fits from OAI.Computability.VPVNP.CompressorRecordPreimageScan
+
+include stored pieceFit in
+theorem old_id (reg : RowRegions q) (nrows : (q 2).val = bundleCount + bundleCount)
+ (cap : count ≤ (q 4).val) (filled : PreimagesAt q (wordOwner (P) arcs sites) mem arcCount) :
+ (h.arc pieces i.val).eval pub state mem = IncidenceDirectory.actualPort X
+ (packingInputEdges X.Base a g (t).1.1) := by
+ let v : Word w := Fin.ofNat _ (bucketIndex sites (.inl b)).val
+ have vw : v.val = (bucketIndex sites (.inl b)).val :=
+ Nat.mod_eq_of_lt ((bucketIndex sites (.inl b)).isLt.trans_le bucketFit)
+ have below : v < q 2 := by
+ change v.val < (q 2).val
+ rw [vw, nrows]
+ exact (bucketIndex sites (.inl b)).isLt
+ have vport : CursorRAM.encode w (port).val = v := rfl
+ have coord := (coordinates X h pub state mem m stored pieceFit).1.trans vport
+ change mem ((h.lists.eval pub state mem + (h.bundle pieces).eval pub state mem *
+ h.listStride.eval pub state mem) + (i.val : Word w)).val = _
+ rw [stored.lists, stored.listStride, coord]
+ change mem ((rowAt q v) + (i.val : Word w)).val = _
+ have endRow := row_fits reg below
+ have valid : (rowAt q v).val + i.val < 2 ^ w := by have := i.isLt; omega
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt valid]
+ have size := arcList_length (P) arcs sites (State.two_le_packingColors a)
+ arcFit bucketFit (.inl b)
+ let j := Fin.cast size.symm i
+ have read := (filled.rows v below).2 j
+ have he := ordinalEquiv_id (P) arcs sites arcFit bucketFit (.inl b) j
+ exact read.trans (he.trans (actual_id X (t).1.1))
+
+include stored pieceFit in
+theorem old_rank (reg : RowRegions q) (nrows : (q 2).val = bundleCount + bundleCount)
+ (cap : count ≤ (q 4).val) (filled : PreimagesAt q (wordOwner (P) arcs sites) mem arcCount)
+ (ranked : BundleWidthScatter.RankedInput (P) X.shrinkNumber X.shrinkOrder arcs sites s mem
+ X.packingWidth) :
+ (Expr.load (h.rankBase.add (h.arc pieces i.val))).eval pub state mem =
+ CursorRAM.encode w (X.shrinkOrder b (t)).val := by
+ have arc := old_id X h pub state mem m stored arcFit bucketFit pieceFit i reg nrows cap filled
+ change mem (h.rankBase.eval pub state mem + (h.arc pieces i.val).eval pub state mem).val = _
+ rw [stored.rankBase, arc, ← actual_id]
+ have rank := ranked.ranks (t).1.1
+ rw [BundleWidthScatter.rank_thick (P) X.shrinkNumber X.shrinkOrder (t)] at rank
+ exact rank
+
+
+variable {thick ab : Fin 5 → Word w}
+
+private theorem enc_add (x y : ℕ) : CursorRAM.encode w x + CursorRAM.encode w y =
+ CursorRAM.encode w (x + y) := Fin.ext (Nat.add_mod x y _).symm
+
+private theorem enc_mul (x y : ℕ) : CursorRAM.encode w x * CursorRAM.encode w y =
+ CursorRAM.encode w (x * y) := Fin.ext (Nat.mul_mod x y _).symm
+
+local notation "bank" => ShrinkABSliceTable.bank (w := w) first count pieces (Fin.val port)
+
+include stored pieceFit in
+theorem frame_address (reg : RowRegions q) (nrows : (q 2).val = bundleCount + bundleCount)
+ (cap : count ≤ (q 4).val) (filled : PreimagesAt q (wordOwner (P) arcs sites) mem arcCount)
+ (ranked : BundleWidthScatter.RankedInput (P) X.shrinkNumber X.shrinkOrder arcs sites s mem
+ X.packingWidth)
+ (alloc : ShrinkABSliceTable.Layout thick ab bundleCount count pieces first) :
+ (h.frame count pieces i.val).eval pub state mem =
+ CursorRAM.encode w (ShrinkAB.frame (P) X.shrinkNumber X.shrinkOrder fiber bank (t)) := by
+ obtain ⟨bundle, part⟩ := coordinates X h pub state mem m stored pieceFit
+ have r := old_rank X h pub state mem m stored arcFit bucketFit pieceFit i
+ reg nrows cap filled ranked
+ change (h.banks.eval pub state mem + (h.bundle pieces).eval pub state mem *
+ CursorRAM.encode w (IndexedStarts.capacity count pieces) +
+ CursorRAM.encode w (count + pieces)) +
+ CursorRAM.encode w 3 * ((Expr.load (h.rankBase.add (h.arc pieces i.val))).eval pub state mem *
+ CursorRAM.encode w pieces + (h.piece pieces).eval pub state mem) = _
+ rw [stored.banks, bundle, part, r]
+ simp only [enc_mul, enc_add, ShrinkAB.frame, ShrinkABSliceTable.bank_val alloc, Nat.add_assoc]
+
+
+/-- The static pointer program for one frame in the thick-wire row. -/
+def Header.setup (H : Header) (degree oldCount pieceCount : ℕ) (dir : Bool) (idx : ℕ) :
+ ResidentColumn.Setup :=
+ ⟨H.oldHalf.field degree (H.arc pieceCount idx) dir, H.destination,
+ H.frame oldCount pieceCount idx, false⟩
+
+variable (arena : NodeArguments.Arena) (nodes : X.network.Site → ℕ) (layout dir : Bool)
+local notation "abSite" => ShrinkOldHalves.abSite X m dir
+variable (x : X.packingData.PlacedHalf X.packingWidth layout (ShrinkOldHalves.abSite X m dir))
+local notation "data" => ShrinkOldHalves.abData X layout m dir x
+local notation "slice" =>
+ X.packingData.demandSlice X.shrinkNumber X.shrinkOrder X.packingWidth b t fiber
+
+/-- Logical copy at the actual old-ID row index. Its source and target offsets
+refer to the same thick-rank / motif-rank frame as the pointer calculation. -/
+noncomputable def row : ResidentColumn.Row :=
+ ⟨ShrinkOldHalves.address X arena nodes (t).1.1 dir, dest,
+ ShrinkAB.frame (P) X.shrinkNumber X.shrinkOrder fiber bank (t),
+ (slice).sourceOffset, (slice).targetOffset,
+ ShrinkAB.copyBits (P) X.shrinkNumber X.shrinkOrder X.packingWidth fiber data (t)⟩
+
+open private frame_fit from OAI.Computability.VPVNP.PairShrinkABNative
+
+set_option maxHeartbeats 1200000 in
+-- Reconcile the concrete state numbering with both dependent bank arrays.
+include stored pieceFit in
+theorem recorded (T : IncidenceDirectory w) (older stride : ℕ)
+ (hs : h.oldHalf.Stored T arena older stride pub state mem)
+ (cols : T.ActualColumns X mem) (degreeFits : d < 2 ^ w)
+ (reg : RowRegions q) (nrows : (q 2).val = bundleCount + bundleCount)
+ (cap : count ≤ (q 4).val) (filled : PreimagesAt q (wordOwner (P) arcs sites) mem arcCount)
+ (ranked : BundleWidthScatter.RankedInput (P) X.shrinkNumber X.shrinkOrder arcs sites s mem
+ X.packingWidth)
+ (alloc : ShrinkABSliceTable.Layout thick ab bundleCount count pieces first)
+ (image : ShrinkABSliceTable.Image bank (thickWidths (P) X.shrinkOrder X.packingWidth b)
+ (abWidths (P) X.shrinkNumber X.packingWidth b) mem) :
+ let ptr := fun u ↦ older + stride * PortRefresh.ArgumentAddress.siteOrdinal X u
+ (row X m arcFit bucketFit i arena ptr layout dir x (first := first) (dest := dest)).Recorded
+ (h.setup d count pieces dir i.val) pub state mem := by
+ intro ptr
+ have aid := old_id X h pub state mem m stored arcFit bucketFit pieceFit i reg nrows cap filled
+ have word := ShrinkOldHalves.Physical.field_eq X h.oldHalf T arena older stride pub state mem
+ hs cols arcFit degreeFits (t).1.1 (h.arc pieces i.val) aid dir
+ have sp := ShrinkABSliceTable.space alloc port
+ have oldSize : (thickWidths (P) X.shrinkOrder X.packingWidth b).length = count := List.length_ofFn
+ have newSize : (abWidths (P) X.shrinkNumber X.packingWidth b).length = pieces := List.length_ofFn
+ have sd := image.stored (input := ShrinkABSliceTable.columns thick ab (port).val)
+ (by rw [oldSize, newSize]; exact sp)
+ have words := frame_words (P) X.shrinkNumber X.shrinkOrder X.packingWidth fiber sd (t)
+ have len : (ShrinkAB.copyBits (P) X.shrinkNumber X.shrinkOrder X.packingWidth
+ fiber data (t)).length =
+ (slice).length := List.length_ofFn
+ exact ⟨word, stored.destination, frame_address X h pub state mem m stored arcFit bucketFit
+ pieceFit i reg nrows cap filled ranked alloc,
+ frame_fit (P) X.shrinkNumber X.shrinkOrder fiber bank (t) sp.fits,
+ words.1.trans len.symm, fun pos ↦ words.2 (len ▸ pos)⟩
+
+set_option maxHeartbeats 800000 in
+-- Reduce the typed slice coordinate through the numbered old arc and field widths.
+theorem reads {endAddr : ℕ} (priv : Word w → Word w)
+ (ready : ShrinkOldHalves.PlacedPackets X layout arena nodes priv abSite x endAddr) :
+ (row X m arcFit bucketFit i arena nodes layout dir x (first := first) (dest := dest)).reads
+ priv := by
+ intro j
+ have len : (row X m arcFit bucketFit i arena nodes layout dir x
+ (first := first) (dest := dest)).bits.length = (slice).length := List.length_ofFn
+ let k : Fin (slice).length := ⟨j.val, len ▸ j.isLt⟩
+ have bit := ShrinkOldHalves.read_ab X layout m dir ready (t)
+ ⟨(slice).sourceOffset + j.val,
+ ShrinkAB.source_bound (P) X.shrinkNumber X.shrinkOrder X.packingWidth fiber (t) k⟩
+ simpa only [row, ShrinkAB.copyBits, List.getElem_ofFn, Nat.add_assoc] using bit
+
+theorem fits (pivot : ℕ) (old : ∀ u, arena.base (nodes u) + arena.stride ≤ pivot)
+ (start : pivot ≤ dest) (room : dest + (P).abWidth X.shrinkNumber X.packingWidth m < 2 ^ w)
+ {endAddr : ℕ} {priv : Word w → Word w}
+ (ready : ShrinkOldHalves.PlacedPackets X layout arena nodes priv abSite x endAddr) :
+ (row X m arcFit bucketFit i arena nodes layout dir x (first := first) (dest := dest)).Fits w
+ pivot := by
+ let e := (t).1.1
+ let u := ShrinkOldHalves.position X e dir
+ have placed : abSite = (P).placement layout u := by
+ cases dir with
+ | false =>
+ exact (congrArg Prod.fst (t).2.symm).trans ((P).place_thick_source layout (t).1).symm
+ | true =>
+ exact (congrArg (fun z ↦ ((P).siteGraph.target z).1) (t).2.symm).trans
+ ((P).place_thick_target layout (t).1).symm
+ let z := (X.packingHalfEquiv u).symm (x u placed)
+ let v := X.packingInputIso.site u
+ let j := ShrinkOldHalves.slot X e dir
+ have endField := NodeArguments.field_end_le X v z arena (nodes v) dir j
+ have width : X.halfWidth v dir j = X.packingWidth e := by
+ simpa only [List.length_ofFn] using congrArg List.length (ShrinkOldHalves.slot_bits X e dir z)
+ have frameWidth : (NodeArguments.packed X v z).length ≤ arena.stride := (ready u placed).1.2.1
+ have ends := old v
+ rw [width] at endField
+ let r := row X m arcFit bucketFit i arena nodes layout dir x (first := first) (dest := dest)
+ have len : r.bits.length = (slice).length := List.length_ofFn
+ constructor
+ · intro pos
+ have last : (slice).length - 1 < (slice).length := by
+ change 0 < r.bits.length at pos
+ omega
+ have edge := ShrinkAB.source_bound (P) X.shrinkNumber X.shrinkOrder X.packingWidth fiber
+ (t) ⟨_, last⟩
+ change (slice).sourceOffset + ((slice).length - 1) < X.packingWidth e at edge
+ change arena.fieldAddress X v (nodes v) dir j + (slice).sourceOffset + r.bits.length ≤ pivot
+ omega
+ · exact start
+ · intro pos
+ change 0 < r.bits.length at pos
+ have bound := ShrinkAB.target_bound (P) X.shrinkNumber X.shrinkOrder X.packingWidth fiber
+ (t) (len ▸ pos)
+ change (slice).targetOffset + (slice).length ≤
+ (P).abWidth X.shrinkNumber X.packingWidth m at bound
+ change dest + (slice).targetOffset + r.bits.length < 2 ^ w
+ omega
+
+
+set_option maxHeartbeats 1200000 in
+-- The physical and logical folds carry different dependent presentations of each wire.
+/-- The final native column writes every coordinate of the selected resident
+AB operand, although the original append order may differ from thick rank. -/
+theorem writes_operand (priv : Word w → Word w)
+ (room : dest + (P).abWidth X.shrinkNumber X.packingWidth m ≤ 2 ^ w)
+ (j : Fin ((P).abWidth X.shrinkNumber X.packingWidth m)) :
+ let rs := fun i ↦ row X m arcFit bucketFit i arena nodes layout dir x
+ (first := first) (dest := dest)
+ ResidentColumn.writes rs (List.finRange count) priv ((dest + j.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (ShrinkAB.operand (P) X.shrinkNumber X.shrinkOrder
+ X.packingWidth fiber (State.two_le_packingColors a) (Nat.two_pow_pos a) data j) := by
+ intro rs
+ let o := members X arcFit bucketFit b
+ have all (z : (P).ThickFiber b) : z ∈ (List.finRange count).map o := by
+ exact List.mem_map.mpr ⟨o.symm z, List.mem_finRange _, o.apply_symm_apply z⟩
+ have fill := ShrinkAB.fill_operand (P) X.shrinkNumber X.shrinkOrder X.packingWidth fiber
+ (State.two_le_packingColors a) (Nat.two_pow_pos a) dest room data
+ ((List.finRange count).map o) priv j (Or.inl (all _))
+ rw [ShrinkAB.fill, List.foldl_map] at fill
+ exact fill
+
+end PairSimulation.ShrinkAB.Physical
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkABNative.lean b/lean/OAI/Computability/VPVNP/PairShrinkABNative.lean
new file mode 100644
index 0000000000..40fdbcb762
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkABNative.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.PairShrinkABBuffers
+import OAI.Computability.VPVNP.PairSimulationReverseSlices
+
+/-!
+# Native AB copies from the independent old half-wire buffers
+
+The indexed-starts scan records intersections of thick wires with AB fields in
+source-major order. A resident map visits one column of the resulting bank.
+The slice loop reads its length and, for a positive intersection, both offsets.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkAB
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData CompressorRecords
+open ShrinkSliceArrays SliceSchedule
+open scoped Fin.CommRing
+
+variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (P : PackingData V H Tag L d c) (number : P.BundleNumbering) (order : P.ThickNumbering)
+variable (width : Arc V H Tag L d c → ℕ) {b : Site V Tag L × Fin d} (m : P.MotifFiber b)
+variable {w p r k : ℕ}
+
+omit [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] [DecidableEq V] [DecidableEq Tag]
+ [DecidableEq L] in
+private theorem frame_fit (B : Word w) (a : P.ThickFiber b)
+ (space : B.val + IndexedStarts.capacity (2 ^ c * d / 4) (pieceCount d c) < 2 ^ w) :
+ frame P number order m B a + 2 < 2 ^ w := by
+ have h : (order b a).val * pieceCount d c + (number b m).val <
+ (2 ^ c * d / 4) * pieceCount d c := calc
+ _ < (order b a).val * pieceCount d c + pieceCount d c := Nat.add_lt_add_left (number b m).isLt _
+ _ = ((order b a).val + 1) * pieceCount d c := (Nat.succ_mul _ _).symm
+ _ ≤ _ := Nat.mul_le_mul_right _ (order b a).isLt
+ unfold frame
+ unfold IndexedStarts.capacity at space
+ omega
+
+/-- Execute a complete source-major interval at an actual old endpoint. The old
+field remains intact. The destination can subsequently be filled by the other
+thick arcs of the bundle. -/
+theorem execute_piece {M : Machine w p r k} {pc : Fin 11 → Fin p}
+ {reg : Fin 6 ↪ Fin r} {arcPC : Fin 7 → Fin p} {done : Fin p}
+ (linked : PrivateSlices.Linked M pc reg (arcPC 0) done)
+ (copy : PrivateFields.Linked M .copy arcPC (PrivateSlices.copyRegs reg) done)
+ (cfg : Config w p r) (entry : cfg.pc = pc 0) (one : cfg.reg (reg 3) = 1)
+ {mem : Memory w} {B : Word w}
+ (stored : IndexedStarts.Stored B (thickWidths P order width b) (abWidths P number width b) mem)
+ (space : B.val + IndexedStarts.capacity (2 ^ c * d / 4) (pieceCount d c) < 2 ^ w)
+ (a : P.ThickFiber b) (src dst : ℕ)
+ (hf : cfg.reg (reg 5) = (frame P number order m B a : Word w))
+ (source : cfg.reg (reg 0) = (src : Word w)) (dest : cfg.reg (reg 2) = (dst : Word w))
+ (apart : src + width a.1.1 ≤ dst) (room : dst + P.abWidth number width m.val < 2 ^ w)
+ (data : (a : P.ThickFiber b) → Fin (width a.1.1) → Bool)
+ (old : ∀ i, cfg.privateMem ((src + i.val : ℕ) : Word w) = PrivateFields.bitValue w (data a i)) :
+ ReverseSlices.FrameResult M reg done cfg mem (frame P number order m B a : Word w)
+ (dst + (P.demandSlice number order width b a m).targetOffset)
+ (copyBits P number order width m data a) := by
+ let s := P.demandSlice number order width b a m
+ let bs := copyBits P number order width m data a
+ have len : bs.length = s.length := List.length_ofFn
+ obtain ⟨h₁, h₂⟩ := frame_words P number order width m stored a
+ obtain ⟨h₃, h₄⟩ := ReverseSlices.oriented_frame_words false mem
+ (frame P number order m B a) (frame P number order m B a)
+ s.sourceOffset s.targetOffset bs.length rfl (frame_fit P number order m B a space)
+ (h₁.trans len.symm) (fun hp ↦ h₂ (len ▸ hp))
+ have sourceEnd (hp : 0 < bs.length) : s.sourceOffset + bs.length ≤ width a.1.1 := by
+ let last : Fin s.length := ⟨bs.length - 1, by omega⟩
+ have h := source_bound P number order width m a last
+ change s.sourceOffset + (bs.length - 1) < width a.1.1 at h
+ omega
+ apply ReverseSlices.execute_stored_frame false linked copy cfg entry one mem _ hf src dst
+ s.sourceOffset s.targetOffset source dest bs h₃ h₄
+ · intro hp
+ have hs := sourceEnd hp
+ have ht := target_bound P number order width m a (len ▸ hp)
+ change s.targetOffset + s.length ≤ _ at ht
+ omega
+ · intro hp
+ exact Or.inr (by have hs := sourceEnd hp; omega)
+ · intro i
+ let ix : Fin s.length := ⟨i.val, len ▸ i.isLt⟩
+ have h := old ⟨s.sourceOffset + i.val, source_bound P number order width m a ix⟩
+ simpa only [bs, copyBits, List.getElem_ofFn, Nat.add_assoc] using h
+
+end PairSimulation.ShrinkAB
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkAbstractFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkAbstractFootprint.lean
new file mode 100644
index 0000000000..7b432194fe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkAbstractFootprint.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairShrinkRoleMapActions
+import OAI.Computability.VPVNP.PairSimulationShrinkRowFootprint
+
+/-! # External memory of a scheduled shrinking action
+
+The row selector enumerates exactly the resident actions. Each accepting
+action concatenates its route, interval gather and matrix events. The
+three read bounds therefore apply to the action at every scratch state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots ShrinkMapImage.Registers
+open ResidentMapLoop.Exact MapResidentRows SourceTransport
+
+variable {g : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t w endAddr : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+
+private noncomputable local instance actionFootBase : DecidableEq X.Base := Classical.decEq _
+
+local notation "side" => selectedLayout X B.shrink sel
+local notation "F" => ShrinkVertexImage.matrixFamily B ord i
+local notation "G" => ShrinkVertexImage.gatherFamily B ord i
+
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+ (jobs : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ ShrinkPartyNative.Job X B.shrink (S.shrink i) sel q.1.1 q.1.2 w)
+
+variable (m : Memory w) (level term : Word w)
+ (R : MapRowSource X sel (selectedLayout X B.shrink sel) m level term)
+ (hw : MapConstants.widthThreshold B.shrink ≤ w)
+ (pub : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v → Fin 5 → Word w)
+ (workspace : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ MapHandlerOperand.Workspace (w := w) (ShrinkVertexImage.matrixFamily B ord i)
+ demandMass_pos (jobInput B i X sel v hidden jobs q))
+
+local notation "row" j => rowEquiv X side v j
+local notation "input" j => jobInput B i X sel v hidden jobs (row j)
+local notation "key" j => MapHandlerOperand.index demandMass_pos (input j)
+local notation "state" j => rowOrdinalWord (w := w) X side v j
+
+set_option maxHeartbeats 1600000 in
+-- Instantiate the native traces with the resident's dependent party index and workspace.
+/-- All external writes are absent. Three bounds on the actual read traces
+suffice for any member of the scheduled shrinking action list. -/
+theorem actionFootprint (allow : ℕ → Prop)
+ (routes : ∀ j, Reads allow (routeEvents X sel side v m level term R j))
+ (gathers : ∀ j, Reads allow ((jobs (row j)).trace ((G).operands (key j)) ((G).node (key j))
+ (pub (row j)) (state j) m))
+ (matrices : ∀ j, Reads allow ((F).successEvents demandMass_pos (input j) hw
+ (pub (row j)) (state j) m))
+ (act : Action w endAddr)
+ (member : act ∈ actions B ord i X sel v hidden jobs m level term R hw pub workspace)
+ (node : Word w) (saved : Scratch w endAddr) (es : List (Event w)) (updated : Scratch w endAddr)
+ (got : act node saved = some (es, updated)) : Reads allow es ∧ Writes (fun _ ↦ False) es := by
+ unfold actions at member
+ obtain ⟨j, rfl⟩ := List.mem_ofFn.mp member
+ let q := rowEquiv X side v j
+ let I := jobInput B i X sel v hidden jobs q
+ have eqn := rowAction_trace (g := g) (w := w) (endAddr := endAddr) (ready := S.shrink i)
+ (jobMotif := q.1.1) (F) (G) X sel v m level term R j I (jobs q) hw (pub q)
+ (workspace q) saved got
+ rw [eqn]
+ refine ⟨TerminalFootprint.reads_append (routes j)
+ (TerminalFootprint.reads_append (gathers j) (matrices j)), ?_⟩
+ intro a b hit
+ obtain h | h := List.mem_append.mp hit
+ · exact routeEvents_noWrites X sel side v m level term R j a b h
+ obtain h | h := List.mem_append.mp h
+ · exact (jobs q).trace_noWrites ((G).operands (key j)) ((G).node (key j))
+ (pub q) (state j) m a b h
+ · exact (F).successEvents_noWrites demandMass_pos I hw (pub q) (state j) m a b h
+
+end PairSimulation.ShrinkRole.MapWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkAdjacentRows.lean b/lean/OAI/Computability/VPVNP/PairShrinkAdjacentRows.lean
new file mode 100644
index 0000000000..ec2fe21b1b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkAdjacentRows.lean
@@ -0,0 +1,67 @@
+import OAI.Computability.VPVNP.PairShrinkPackedParent
+
+/-!
+# Disjoint child and parent rows at a selected shrinking occurrence
+
+The old site ordinal belongs to the input layer at the physical pass index.
+The next selected prefix begins after every row of that layer. This separates
+every child packet address from the output address used by a resident party.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPackedRows
+
+open Compression CompressorRecords DescriptorSpace TraversalRows TraversalRoles
+open PortRefresh.ArgumentAddress
+open private tag_count from OAI.Computability.VPVNP.CompressorSelectedDirectoryHistory
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+variable (workspace : ℕ) (cur : Fin (executeLevels B f hf T hT X z).length)
+variable (j : Fin S.steps) {g : ℕ}
+variable (Z : State (S.degreeExponent j.castSucc) (packingLaneBits (S.degreeExponent j.castSucc) g))
+variable (sel : SelectedScore.Selection B Z) (bits : List Bool)
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => selected B f hf T hT X z
+local notation "firstRow" => endAddress (BlockProgram.layout B workspace X.positions T)
+local notation "older" => layerBase B.recordLimit firstRow tags cur.val
+local notation "later" => layerBase B.recordLimit firstRow tags (cur.val + 1)
+local notation "pitch" => B.recordLimit + 2
+local notation "Y" => Z.shrinkNext B.shrink (S.shrink j) sel
+
+/-- Every old site starts strictly before the selected successor layer. -/
+theorem packed_child_before_successor (occurrence : passes[cur] = shrinkLevel B f hf j Z sel bits)
+ (child : Z.network.Site) : older + (pitch) * siteOrdinal Z child < later := by
+ have hi : cur.val < (tags).length := by
+ simp only [selected, List.length_cons, List.length_map]
+ exact Nat.lt_succ_of_lt cur.isLt
+ let current := (tags)[cur.val].layer
+ let before := ((tags).take cur.val).map TaggedLayer.layer
+ have count : current.count = Z.positions := by
+ have h := tag_count (B := B) (f := f) (hf := hf) (z := z) cur
+ rw [occurrence] at h
+ exact h
+ have bounds := ShrinkCallCapacity.layer_addresses Z B.recordLimit firstRow before [] current
+ count child
+ simpa only [layerBase, List.take_succ_eq_append_getElem hi, List.map_append, List.map_cons,
+ List.map_nil, before, current] using bounds
+
+/-- In particular, updating any old child packet cannot address the parent's
+row, even when that parent is the last output site of the branch. -/
+theorem packed_child_before_parent (occurrence : passes[cur] = shrinkLevel B f hf j Z sel bits)
+ (child : Z.network.Site) (parent : (Y).network.Site) :
+ older + (pitch) * siteOrdinal Z child < later + (pitch) * siteOrdinal (Y) parent :=
+ lt_of_lt_of_le
+ (packed_child_before_successor B f hf T hT X z workspace cur j Z sel bits occurrence child)
+ (Nat.le_add_right _ _)
+
+end PairSimulation.ShrinkPackedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkArgumentReadBounds.lean b/lean/OAI/Computability/VPVNP/PairShrinkArgumentReadBounds.lean
new file mode 100644
index 0000000000..3f5726fe3f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkArgumentReadBounds.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.PairShrinkSurvivingAddress
+import OAI.Computability.VPVNP.CompressorFormulaFootprint
+
+/-!
+# Read bounds for the private argument address calculation
+
+A width prefix uses the actual slot directory of the chosen endpoint.
+An incoming slot first indexes the inverse incidence column and then the
+width column by the outgoing arc returned there. Both numerical indices
+belong to the same finite actual port range.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ArgumentReadBounds
+
+open BurstRAM BurstRAM.PrivateRAM Compression NodeArguments CompressorRecords
+open CompressorRecords.PortRefresh.ArgumentAddress CompressorRecords.PhaseRecipe
+open ShrinkOldHalves.Physical
+open private unpack word_of_val from OAI.Computability.VPVNP.PairShrinkOldHalfAddresses
+open private eval_port from OAI.Computability.VPVNP.CompressorRecordRefreshArgumentAddress
+open scoped Fin.CommRing
+
+variable {a g w : ℕ} {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w}
+variable (X : State a g) (u : X.network.Site) (k : Fin (2 ^ a))
+variable (Hdr : Header) (T : IncidenceDirectory w) (A : Arena) {layer pitch : ℕ}
+local notation "N" => Fintype.card X.Base * 2 ^ g * 2 ^ a
+local notation "ev" => Expr.eval pub state mem
+
+/-- The four scalar input expressions common to old and new private argument field lookups. -/
+structure FieldsReadable (Hdr : Header) (H : ℕ) (pub : Fin 5 → Word w) (state : Word w)
+ (mem : Memory w) : Prop where
+ arena : Hdr.arenaBase.ReadsFrom (· < H) pub state mem
+ stride : Hdr.arenaStride.ReadsFrom (· < H) pub state mem
+ actualIn : Hdr.actualIn.ReadsFrom (· < H) pub state mem
+ width : Hdr.width.ReadsFrom (· < H) pub state mem
+
+private theorem column_lt (col : Word w) (e : (X.Base × BitWord g) × Fin (2 ^ a)) (H : ℕ)
+ (room : col.val + N ≤ H) : (col + IncidenceDirectory.actualPort X e).val < H := by
+ have bound := (IncidenceDirectory.actualOrder X e).isLt
+ rw [IncidenceDirectory.actualPort_number]
+ change (col.val + (IncidenceDirectory.actualOrder X e).val % 2 ^ w) % 2 ^ w < H
+ exact (Nat.mod_le ..).trans_lt <| lt_of_lt_of_le
+ (Nat.add_lt_add_left ((Nat.mod_le ..).trans_lt bound) _) room
+
+private theorem sum_safe {α : Type*} (xs : List α) (f : α → Expr) (H : ℕ)
+ (h : ∀ x, (f x).ReadsFrom (· < H) pub state mem) :
+ (sum (xs.map f)).ReadsFrom (· < H) pub state mem := by
+ induction xs with
+ | nil => trivial
+ | cons i is ih => exact ⟨h i, ih⟩
+
+/-- Every nested load of the complete private address lies in the allowed prefix.
+The endpoint port already includes the incoming or outgoing orientation. -/
+theorem field (stored : Hdr.Stored T A layer pitch pub state mem)
+ (cols : T.ActualColumns X mem) (capacity : N ≤ 2 ^ w) (degreeFits : 2 ^ a < 2 ^ w)
+ (node port : Expr) (dir : Bool)
+ (portEq : ev port = IncidenceDirectory.actualPort X (u, k)) (H : ℕ)
+ (ins : FieldsReadable Hdr H pub state mem)
+ (nodeSafe : node.ReadsFrom (· < H) pub state mem)
+ (portSafe : port.ReadsFrom (· < H) pub state mem)
+ (inRoom : T.actualIn.val + N ≤ H) (widthRoom : T.width.val + N ≤ H) :
+ (ShrinkSurvivingAddress.field (2 ^ a) Hdr node dir port).ReadsFrom (· < H) pub state mem := by
+ let E := { Hdr.input (2 ^ a) port with node := node }
+ let site := siteOrdinal X u
+ have portVal : (ev port).val = site * 2 ^ a + k.val := by
+ rw [portEq, IncidenceDirectory.actualPort_number]
+ exact (Nat.mod_eq_of_lt ((IncidenceDirectory.actualOrder X (u, k)).isLt.trans_le capacity)).trans
+ (IncidenceDirectory.actualOrder_val X (u, k))
+ have dval : (CursorRAM.encode w (2 ^ a)).val = 2 ^ a := Nat.mod_eq_of_lt degreeFits
+ have parts := unpack (ev port) (CursorRAM.encode w (2 ^ a)) site k.val
+ (by rw [dval]; exact portVal) (by rw [dval]; exact k.isLt)
+ have rep : Represents pub state mem E X u T A (ev node).val :=
+ ⟨stored.arenaBase, stored.arenaStride, word_of_val rfl, word_of_val parts.1,
+ stored.actualIn,
+ stored.width⟩
+ let safe := Expr.ReadsFrom (· < H) pub state mem
+ have halfSafe (incoming : Bool) (i : Fin (2 ^ a)) : safe (E.half incoming i) := by
+ have pi : safe (E.port i) := ⟨⟨⟨portSafe, trivial⟩, trivial⟩, trivial⟩
+ have value := eval_port rep i
+ have inAt : (ev E.actualIn + ev (E.port i)).val < H := by
+ rw [rep.actualIn, value]
+ exact column_lt X _ _ H inRoom
+ cases incoming with
+ | false =>
+ refine ⟨⟨ins.width, pi⟩, ?_⟩
+ change (ev E.width + ev (E.port i)).val < H
+ rw [rep.width, value]
+ exact column_lt X _ _ H widthRoom
+ | true =>
+ refine ⟨⟨ins.width, ⟨⟨ins.actualIn, pi⟩, inAt⟩⟩, ?_⟩
+ change (ev E.width + mem (ev E.actualIn + ev (E.port i)).val).val < H
+ rw [rep.width, rep.actualIn, value, cols.actualIn]
+ exact column_lt X _ _ H widthRoom
+ have side : safe (outgoing (2 ^ a) E dir) := by
+ cases dir with
+ | false => trivial
+ | true => exact sum_safe _ _ H (halfSafe false)
+ let j := port.mod (.lit (2 ^ a))
+ have selector (i : Fin (2 ^ a)) : safe (before j i) :=
+ ⟨trivial, ⟨trivial, ⟨⟨⟨portSafe, trivial⟩, trivial⟩, trivial⟩⟩⟩
+ exact ⟨⟨ins.arena, nodeSafe, ins.stride⟩, side,
+ sum_safe _ _ H (fun i ↦ ⟨selector i, halfSafe dir i⟩)⟩
+
+/-- The old half lookup also reads the forward incidence column at the source arc
+when the desired endpoint is incoming. Its node comes from the old layer's site ordinal. -/
+theorem old_field (stored : Hdr.Stored T A layer pitch pub state mem)
+ (cols : T.ActualColumns X mem) (capacity : N ≤ 2 ^ w) (degreeFits : 2 ^ a < 2 ^ w)
+ (arc : Expr) (e : (X.Base × BitWord g) × Fin (2 ^ a)) (dir : Bool)
+ (arcEq : ev arc = IncidenceDirectory.actualPort X e)
+ (portEq : ev (Hdr.port arc dir) = IncidenceDirectory.actualPort X (u, k)) (H : ℕ)
+ (ins : FieldsReadable Hdr H pub state mem)
+ (arcSafe : arc.ReadsFrom (· < H) pub state mem)
+ (outSafe : Hdr.actualOut.ReadsFrom (· < H) pub state mem)
+ (layerSafe : Hdr.layerBase.ReadsFrom (· < H) pub state mem)
+ (pitchSafe : Hdr.layerStride.ReadsFrom (· < H) pub state mem)
+ (outRoom : T.actualOut.val + N ≤ H) (inRoom : T.actualIn.val + N ≤ H)
+ (widthRoom : T.width.val + N ≤ H) :
+ (Hdr.field (2 ^ a) arc dir).ReadsFrom (· < H) pub state mem := by
+ let p := Hdr.port arc dir
+ have portSafe : p.ReadsFrom (· < H) pub state mem := by
+ cases dir with
+ | false => exact arcSafe
+ | true =>
+ refine ⟨⟨outSafe, arcSafe⟩, ?_⟩
+ change (ev Hdr.actualOut + ev arc).val < H
+ rw [stored.actualOut, arcEq]
+ exact column_lt X _ _ H outRoom
+ let node := (Hdr.input (2 ^ a) p).node
+ have nodeSafe : node.ReadsFrom (· < H) pub state mem :=
+ ⟨layerSafe, pitchSafe, portSafe, trivial⟩
+ exact field X u k Hdr T A stored cols capacity degreeFits node p dir portEq H ins nodeSafe
+ portSafe inRoom widthRoom
+
+end PairSimulation.ArgumentReadBounds
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCDFieldAddress.lean b/lean/OAI/Computability/VPVNP/PairShrinkCDFieldAddress.lean
new file mode 100644
index 0000000000..406f380f94
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCDFieldAddress.lean
@@ -0,0 +1,382 @@
+import OAI.Computability.VPVNP.PairShrinkABFrameAddress
+import OAI.Computability.VPVNP.CompressorShrinkBundlePlan
+
+/-!
+# Direct pointers to the two unsplit CD operands
+
+The motif's rank is relative to its bundle. Its classified row contains old
+arc IDs in append order. A fixed-size rank comparison retrieves the matching
+original ID. The thickness column at its source chooses which of the two
+private child halves belongs to C and which belongs to D.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCD
+
+open Compression Compression.PackingData CompressorRecords CompressorRecords.PhaseRecipe
+open BurstRAM BurstRAM.PrivateRAM BundleLists
+open scoped Fin.CommRing
+
+/-- Runtime operands for finding the CD demand's old arc and choosing the correct private half
+at C or D. -/
+structure Header where
+ /-- The shared bundle lists, ranks, motif ordinal, and old half-wire geometry used by the CD
+ lookup. -/
+ fields : ShrinkAB.Physical.Header
+ /-- Number of classified owner rows. Half this count is the displacement to the CD half of
+ the row rectangle. -/
+ owners : Expr
+ /-- Head of the array of old-site thickness flags used to orient the two CD endpoints. -/
+ thickness : Expr
+
+/-- CD rows occupy the second half of the classified row rectangle. -/
+def Header.row (H : Header) (pieces : ℕ) : Expr :=
+ let b := (H.owners.div (.lit 2)).add (H.fields.bundle pieces)
+ H.fields.lists.add (b.mul H.fields.listStride)
+
+/-- Read an old arc ID at a fixed column of the selected bundle's CD row. -/
+def Header.candidate (H : Header) (pieces index : ℕ) : Expr :=
+ .load ((H.row pieces).add (.lit index))
+
+/-- A nonzero modular difference divided by itself is one. A zero
+difference divided by itself is zero, including at the largest word. -/
+def equal (x y : Expr) : Expr :=
+ let z := x.sub y
+ (Expr.lit 1).sub (z.div z)
+
+/-- Keep the candidate's arc ID exactly when its stored rank equals the motif's piece number,
+and return zero otherwise. -/
+def Header.select (H : Header) (pieces index : ℕ) : Expr :=
+ let id := H.candidate pieces index
+ let rank := Expr.load (H.fields.rankBase.add id)
+ (equal rank (H.fields.piece pieces)).mul id
+
+/-- Sum the rank-filtered CD row entries to recover the old arc ID at the selected piece. -/
+def Header.arc (H : Header) (pieces : ℕ) : Expr :=
+ PortRefresh.ArgumentAddress.sum ((List.finRange pieces).map fun i ↦ H.select pieces i.val)
+
+/-- Read the thickness flag of the old source site, whose ordinal is the selected CD arc ID
+divided by the old degree. -/
+def Header.flag (H : Header) (degree pieces : ℕ) : Expr :=
+ .load (H.thickness.add ((H.arc pieces).div (.lit degree)))
+
+/-- C follows the incoming half when its old source is thick. D follows
+the complementary half. Each source address uses the numbered child arena. -/
+def Header.field (H : Header) (degree pieces : ℕ) (atD : Bool) : Expr :=
+ let arc := H.arc pieces
+ let flag := H.flag degree pieces
+ let incoming := if atD then (Expr.lit 1).sub flag else flag
+ let out := H.fields.oldHalf.field degree arc false
+ let inc := H.fields.oldHalf.field degree arc true
+ (incoming.mul inc).add (((Expr.lit 1).sub incoming).mul out)
+
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+local notation "P" => X.packingData
+local notation "d" => 2 ^ a
+local notation "c" => Shrink.colors a
+local notation "arcs" => BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex
+local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex
+local notation "arcCount" => Fintype.card X.Base * 2 ^ (packingLaneBits a g) * d
+local notation "bundles" => (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * d
+local notation "pieces" => pieceCount d c
+
+/-- Classical equality of base vertices used in the classified CD fiber lookup. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Each row index decodes to a different motif, and every motif in the
+bundle occurs at one index. -/
+noncomputable def members (arcFit : arcCount ≤ 2 ^ w) (bucketFit : bundles + bundles ≤ 2 ^ w)
+ (b : Port X.Base (BitWord (Shrink.J a)) (BitWord g) d) : Fin pieces ≃ (P).MotifFiber b :=
+ let size := arcList_length (P) arcs sites (State.two_le_packingColors a) arcFit bucketFit (.inr b)
+ ((finCongr size.symm).trans (ordinalEquiv (P) arcs sites arcFit bucketFit (.inr b))).trans
+ (motifEquiv (P) b)
+
+variable (H : Header) (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+variable {q : Fin 6 → Word w} {s : Fin 5 → Word w} {first dest : ℕ}
+variable (m : X.packingData.Motif) (stored : H.fields.Stored X pub state mem q s first dest m)
+variable (arcFit : Fintype.card X.Base * 2 ^ (packingLaneBits a g) * 2 ^ a ≤ 2 ^ w)
+variable (bucketFit : (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a +
+ (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a ≤ 2 ^ w)
+variable (pieceFit : pieceCount (2 ^ a) (Shrink.colors a) < 2 ^ w)
+variable (twoFits : 2 < 2 ^ w)
+variable (owners : H.owners.eval pub state mem = q 2)
+variable (reg : RowRegions q) (nrows : (q 2).val =
+ (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a +
+ (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a)
+variable (cap : pieceCount (2 ^ a) (Shrink.colors a) ≤ (q 4).val)
+local notation "b" => X.packingData.bundle m
+local notation "port" => portIndex sites b
+local notation "fiber" => Subtype.mk m (Eq.refl b)
+local notation "piece" => X.shrinkNumber b fiber
+local notation "member" => members X arcFit bucketFit b
+
+open private row_fits from OAI.Computability.VPVNP.CompressorRecordPreimageScan
+open private actual_id from OAI.Computability.VPVNP.PairShrinkABFrameAddress
+
+include owners nrows twoFits in
+private theorem half_count :
+ (H.owners.div (.lit 2)).eval pub state mem = CursorRAM.encode w bundles := by
+ change Fin.ofNat _ ((H.owners.eval pub state mem).val / ((2 : Word w).val)) = _
+ rw [owners, nrows, show (2 : Word w).val = 2 from Nat.mod_eq_of_lt twoFits]
+ rw [← Nat.mul_two, Nat.mul_div_cancel _ (by decide : 0 < 2)]
+
+include arcFit bucketFit owners nrows twoFits stored pieceFit reg cap in
+theorem candidate_eq (filled : PreimagesAt q (wordOwner (P) arcs sites) mem arcCount)
+ (i : Fin pieces) :
+ (H.candidate pieces i.val).eval pub state mem =
+ IncidenceDirectory.actualPort X (packingInputEdges X.Base a g (member i).1.1) := by
+ let v : Word w := Fin.ofNat _ (bucketIndex sites (.inr b)).val
+ have vw : v.val = (bucketIndex sites (.inr b)).val :=
+ Nat.mod_eq_of_lt ((bucketIndex sites (.inr b)).isLt.trans_le bucketFit)
+ have below : v < q 2 := by
+ change v.val < (q 2).val
+ rw [vw, nrows]; exact (bucketIndex sites (.inr b)).isLt
+ have bundle := (ShrinkAB.Physical.coordinates X H.fields pub state mem m stored pieceFit).1
+ have base := half_count X H pub state mem twoFits owners nrows
+ have index : CursorRAM.encode w bundles + CursorRAM.encode w (port).val = v := by
+ exact Fin.ext (Nat.add_mod ..).symm
+ change mem ((H.fields.lists.eval pub state mem + ((H.owners.div (.lit 2)).eval pub state mem +
+ (H.fields.bundle pieces).eval pub state mem) * H.fields.listStride.eval pub state mem) +
+ (i.val : Word w)).val = _
+ rw [stored.lists, stored.listStride, base, bundle, index]
+ change mem ((rowAt q v) + (i.val : Word w)).val = _
+ have endRow := row_fits reg below
+ have valid : (rowAt q v).val + i.val < 2 ^ w := by have := i.isLt; omega
+ rw [Fin.val_add, Fin.val_natCast, Nat.add_mod_mod, Nat.mod_eq_of_lt valid]
+ have size := arcList_length (P) arcs sites (State.two_le_packingColors a)
+ arcFit bucketFit (.inr b)
+ let j := Fin.cast size.symm i
+ have read := (filled.rows v below).2 j
+ have he := ordinalEquiv_id (P) arcs sites arcFit bucketFit (.inr b) j
+ exact read.trans (he.trans (actual_id X (member i).1.1))
+
+private theorem equal_eval (x y : Expr) :
+ (equal x y).eval pub state mem =
+ if x.eval pub state mem = y.eval pub state mem then 1 else 0 := by
+ let z := x.eval pub state mem - y.eval pub state mem
+ change 1 - (Fin.ofNat _ (z.val / z.val) : Word w) = _
+ by_cases eqn : x.eval pub state mem = y.eval pub state mem
+ · have hz : z = 0 := sub_eq_zero.mpr eqn
+ simp [hz, eqn]
+ · have hz : z ≠ 0 := fun h ↦ eqn (sub_eq_zero.mp h)
+ have pos : 0 < z.val := Nat.pos_of_ne_zero (fun h ↦ hz (Fin.ext h))
+ simp only [ite_eq_right eqn, Nat.div_self pos]
+ exact sub_self _
+
+private theorem sum_eval (xs : List Expr) :
+ (PortRefresh.ArgumentAddress.sum xs).eval pub state mem =
+ (xs.map fun e ↦ e.eval pub state mem).sum := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih =>
+ change x.eval pub state mem + (PortRefresh.ArgumentAddress.sum xs).eval pub state mem = _
+ rw [ih]; rfl
+
+include arcFit bucketFit owners nrows twoFits stored pieceFit reg cap in
+theorem arc_eq (filled : PreimagesAt q (wordOwner (P) arcs sites) mem arcCount)
+ (ranked : BundleWidthScatter.RankedInput (P) X.shrinkNumber X.shrinkOrder arcs sites s mem
+ X.packingWidth) :
+ (H.arc pieces).eval pub state mem =
+ IncidenceDirectory.actualPort X (packingInputEdges X.Base a g m.1) := by
+ let matchIndex := (member).symm fiber
+ have candidate := candidate_eq X H pub state mem m stored arcFit bucketFit pieceFit
+ twoFits owners reg nrows cap filled
+ have rank (i : Fin pieces) :
+ (Expr.load (H.fields.rankBase.add (H.candidate pieces i.val))).eval pub state mem =
+ CursorRAM.encode w (X.shrinkNumber b (member i)).val := by
+ change mem (H.fields.rankBase.eval pub state mem +
+ (H.candidate pieces i.val).eval pub state mem).val = _
+ rw [stored.rankBase, candidate, ← actual_id]
+ have r := ranked.ranks (member i).1.1
+ rw [BundleWidthScatter.rank_motif (P) X.shrinkNumber X.shrinkOrder (member i)] at r
+ exact r
+ have pieceWord := (ShrinkAB.Physical.coordinates X H.fields pub state mem m stored pieceFit).2
+ have eqRank (i : Fin pieces) :
+ CursorRAM.encode w (X.shrinkNumber b (member i)).val = CursorRAM.encode w (piece).val ↔
+ i = matchIndex := by
+ constructor
+ · intro eqn
+ have r := congrArg Fin.val eqn
+ change (X.shrinkNumber b (member i)).val % _ = (piece).val % _ at r
+ rw [Nat.mod_eq_of_lt ((X.shrinkNumber b (member i)).isLt.trans pieceFit),
+ Nat.mod_eq_of_lt ((piece).isLt.trans pieceFit)] at r
+ exact (member).injective (((X.shrinkNumber b).injective (Fin.ext r)).trans
+ ((member).apply_symm_apply fiber).symm)
+ · rintro rfl
+ rw [Equiv.apply_symm_apply]
+ have each (i : Fin pieces) : (H.select pieces i.val).eval pub state mem =
+ if i = matchIndex then IncidenceDirectory.actualPort X (packingInputEdges X.Base a g m.1)
+ else 0 := by
+ change (equal _ _).eval pub state mem * (H.candidate pieces i.val).eval pub state mem = _
+ rw [equal_eval, rank, pieceWord]
+ by_cases hm : i = matchIndex
+ · rw [ite_eq_left ((eqRank i).2 hm), one_mul, ite_eq_left hm, candidate, hm]
+ simp only [matchIndex, Equiv.apply_symm_apply]
+ · rw [ite_eq_right (fun h ↦ hm ((eqRank i).1 h)), zero_mul, ite_eq_right hm]
+ rw [Header.arc, sum_eval, List.map_map, ← List.ofFn_id, List.map_ofFn]
+ simp only [List.sum_ofFn, Function.comp_apply, id_eq, each, Finset.sum_ite_eq',
+ Finset.mem_univ, ite_true]
+
+
+include arcFit bucketFit owners nrows twoFits stored pieceFit reg cap in
+theorem flag_eq (filled : PreimagesAt q (wordOwner (P) arcs sites) mem arcCount)
+ (ranked : BundleWidthScatter.RankedInput (P) X.shrinkNumber X.shrinkOrder arcs sites s mem
+ X.packingWidth) (degreeFits : d < 2 ^ w) (p : Fin 14 → Word w) (layout : Bool)
+ (column : ShrinkRAM.PlacementColumns X.slots X.baseIndex p layout mem)
+ (thick : H.thickness.eval pub state mem = p 11) :
+ (H.flag d pieces).eval pub state mem =
+ CursorRAM.encode w (ShrinkOldHalves.cDirection X m).toNat := by
+ have arc := arc_eq X H pub state mem m stored arcFit bucketFit pieceFit twoFits
+ owners reg nrows cap filled ranked
+ have num : ((H.arc pieces).eval pub state mem).val = (arcs m.1).val := by
+ rw [arc, ← actual_id, Fin.val_ofNat, Nat.mod_eq_of_lt ((arcs m.1).isLt.trans_le arcFit)]
+ have site := BundleRAM.site_quotient X (CursorRAM.encode w d)
+ (Nat.mod_eq_of_lt degreeFits) m.1 _ num
+ change mem (H.thickness.eval pub state mem +
+ ShrinkRAM.div ((H.arc pieces).eval pub state mem) (CursorRAM.encode w d)).val = _
+ rw [thick, site]
+ apply Fin.ext
+ have bits := congrArg (Prod.fst ∘ Prod.snd) (column.atSite (sourcePosition m.1))
+ change (mem (p 11 + ShrinkRAM.word w
+ (Shrink.oldNumber X.baseIndex (sourcePosition m.1))).val).val =
+ (ShrinkOldHalves.cDirection X m).toNat at bits
+ have small : (ShrinkOldHalves.cDirection X m).toNat < 2 ^ w := by
+ have bound : ∀ bit : Bool, bit.toNat ≤ 1 := by decide
+ exact (bound _).trans_lt (lt_trans (by decide : 1 < 2) twoFits)
+ exact bits.trans (Nat.mod_eq_of_lt small).symm
+
+include arcFit bucketFit owners nrows twoFits stored pieceFit reg cap in
+theorem field_eq (filled : PreimagesAt q (wordOwner (P) arcs sites) mem arcCount)
+ (ranked : BundleWidthScatter.RankedInput (P) X.shrinkNumber X.shrinkOrder arcs sites s mem
+ X.packingWidth) (degreeFits : d < 2 ^ w) (p : Fin 14 → Word w) (layout : Bool)
+ (column : ShrinkRAM.PlacementColumns X.slots X.baseIndex p layout mem)
+ (thick : H.thickness.eval pub state mem = p 11)
+ (T : IncidenceDirectory w) (A : NodeArguments.Arena) (older stride : ℕ)
+ (hs : H.fields.oldHalf.Stored T A older stride pub state mem) (cols : T.ActualColumns X mem)
+ (atD : Bool) :
+ let nodes := fun u ↦ older + stride * PortRefresh.ArgumentAddress.siteOrdinal X u
+ (H.field d pieces atD).eval pub state mem = CursorRAM.encode w
+ (ShrinkOldHalves.address X A nodes m.1
+ (if atD then !(ShrinkOldHalves.cDirection X m) else ShrinkOldHalves.cDirection X m)) := by
+ intro nodes
+ have arc := arc_eq X H pub state mem m stored arcFit bucketFit pieceFit twoFits
+ owners reg nrows cap filled ranked
+ have bit := flag_eq X H pub state mem m stored arcFit bucketFit pieceFit twoFits
+ owners reg nrows cap filled ranked degreeFits p layout column thick
+ have field (dir : Bool) := ShrinkOldHalves.Physical.field_eq X H.fields.oldHalf T A older stride
+ pub state mem hs cols arcFit degreeFits m.1 (H.arc pieces) arc dir
+ let dir := ShrinkOldHalves.cDirection X m
+ have flagValue : (H.flag d pieces).eval pub state mem = if dir then 1 else 0 := by
+ rw [bit]
+ change CursorRAM.encode w dir.toNat = if dir then 1 else 0
+ cases dir <;> rfl
+ have f (d' : Bool) : (H.fields.oldHalf.field d (H.arc pieces) d').eval pub state mem =
+ CursorRAM.encode w (ShrinkOldHalves.address X A nodes m.1 d') := field d'
+ cases atD with
+ | false =>
+ change (H.flag d pieces).eval pub state mem * _ + (1 - (H.flag d pieces).eval pub state mem) *
+ (H.fields.oldHalf.field d (H.arc pieces) false).eval pub state mem = _
+ rw [flagValue, f false, f true]
+ cases hv : ShrinkOldHalves.cDirection X m <;> simp [dir, hv]
+ | true =>
+ change (1 - (H.flag d pieces).eval pub state mem) * _ +
+ (1 - (1 - (H.flag d pieces).eval pub state mem)) *
+ (H.fields.oldHalf.field d (H.arc pieces) false).eval pub state mem = _
+ rw [flagValue, f false, f true]
+ cases hv : ShrinkOldHalves.cDirection X m <;> simp [dir, hv]
+
+
+namespace Published
+
+/-- Read the external word at a fixed scalar offset from the runtime old-level header address. -/
+def load (old : Expr) (offset : ℕ) : Expr := .load (old.add (.lit offset))
+
+/-- Level header offsets 0, 1 and 2 give the old base, degree and lane counts.
+The original bucket owner and appended-ID rectangles determine the count of
+classified buckets and the preceding thickness column. -/
+def header (a : ℕ) (old motif arenaBase arenaStride destination : Expr) : Header :=
+ let oldSites := (load old 0).mul (load old 2)
+ let oldSlots := oldSites.mul (load old 1)
+ let owner := load old 44
+ let ids := load old 46
+ let child : ShrinkOldHalves.Physical.Header :=
+ ⟨arenaBase, arenaStride, load old 14, load old 15, load old 57, load old 58, load old 59⟩
+ let ab : ShrinkAB.Physical.Header :=
+ ⟨child, motif, ids, .lit (ShrinkRankSpace.cap a), load old 45, load old 43, destination⟩
+ ⟨ab, ids.sub (owner.add ((Expr.lit 2).mul oldSlots)), owner.sub ((Expr.lit 3).mul oldSites)⟩
+
+variable (old motif arenaBase arenaStride destination : Expr)
+local notation "hdr" => header a old motif arenaBase arenaStride destination
+variable (start : ℕ) (T : IncidenceDirectory w)
+local notation "plan" => ShrinkInput.plan X start
+local notation "collect" => ShrinkRankSpace.Shape.collectBank plan w
+local notation "placement" => ShrinkInput.placementBank X T start
+
+/-- Resolve both calculated heads to the values that the shrinking scan
+actually published into its bucket and preliminary placement operand banks. -/
+theorem geometry
+ (vertices : (load old 0).eval pub state mem = (Fintype.card X.Base : Word w))
+ (degree : (load old 1).eval pub state mem = ((2 ^ a : ℕ) : Word w))
+ (lanes : (load old 2).eval pub state mem = ((2 ^ (packingLaneBits a g) : ℕ) : Word w))
+ (owner : (load old 44).eval pub state mem = ((plan).owner : Word w))
+ (ids : (load old 46).eval pub state mem = ((plan).ids : Word w)) :
+ (hdr).owners.eval pub state mem = (collect) 2 ∧
+ (hdr).thickness.eval pub state mem = (placement) 11 := by
+ constructor
+ · change (load old 46).eval pub state mem - ((load old 44).eval pub state mem +
+ 2 * ((load old 0).eval pub state mem * (load old 2).eval pub state mem *
+ (load old 1).eval pub state mem)) = _
+ rw [ids, owner, vertices, degree, lanes]
+ change (((plan).owner + 2 * (plan).A + 2 * (plan).B : ℕ) : Word w) -
+ ((plan).owner + 2 * ((Fintype.card X.Base : Word w) * ↑(2 ^ packingLaneBits a g : ℕ) *
+ ↑(2 ^ a : ℕ))) = ↑(2 * (plan).B : ℕ)
+ simp only [Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, ShrinkRankSpace.Shape.A,
+ ShrinkRankSpace.slots, ShrinkInput.plan, ShrinkRankArena.shape]
+ ring
+ · change (load old 44).eval pub state mem - 3 *
+ ((load old 0).eval pub state mem * (load old 2).eval pub state mem) = _
+ rw [owner, vertices, lanes]
+ change ((ShrinkInput.placementBase X start + 4 *
+ (Fintype.card X.Base * 2 ^ (packingLaneBits a g)) : ℕ) : Word w) - 3 *
+ ((Fintype.card X.Base : Word w) * ↑(2 ^ packingLaneBits a g : ℕ)) =
+ ↑(ShrinkInput.placementBase X start + 1 * (Fintype.card X.Base *
+ 2 ^ packingLaneBits a g) : ℕ)
+ simp only [Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, Nat.cast_one]
+ ring
+
+/-- The physical child field expressions use the published old DFS geometry
+and the incidence heads following the 54-word scalar header. -/
+theorem child (A : NodeArguments.Arena) (layer stride : ℕ)
+ (baseWord : arenaBase.eval pub state mem = CursorRAM.encode w A.start)
+ (strideWord : arenaStride.eval pub state mem = CursorRAM.encode w A.stride)
+ (layerWord : (load old 14).eval pub state mem = CursorRAM.encode w layer)
+ (rowStride : (load old 15).eval pub state mem = CursorRAM.encode w stride)
+ (outgoing : (load old 57).eval pub state mem = T.actualOut)
+ (incoming : (load old 58).eval pub state mem = T.actualIn)
+ (width : (load old 59).eval pub state mem = T.width) :
+ (hdr).fields.oldHalf.Stored T A layer stride pub state mem :=
+ ⟨baseWord, strideWord, layerWord, rowStride, outgoing, incoming, width⟩
+
+/-- The raw rank, ID and AB bank heads in the old header select the
+corresponding ranked input and physical copy setup. -/
+theorem abHeader (bankBase target : ℕ)
+ (motifWord : (motif.eval pub state mem).val = (ShrinkMotifOrder.stateNumber X m).val)
+ (listWord : (load old 46).eval pub state mem = ((plan).ids : Word w))
+ (rankWord : (load old 45).eval pub state mem = ((plan).ranks : Word w))
+ (banks : (load old 43).eval pub state mem = CursorRAM.encode w bankBase)
+ (targetWord : destination.eval pub state mem = CursorRAM.encode w target) :
+ let ranks := ShrinkWidthArena.scatterBank T collect ((plan).ranks : Word w)
+ (ShrinkInput.widthBase X start)
+ (hdr).fields.Stored X pub state mem collect ranks bankBase target m :=
+ ⟨motifWord, listWord, rfl, rankWord, banks, targetWord⟩
+
+end Published
+
+end PairSimulation.ShrinkCD
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCDReadBounds.lean b/lean/OAI/Computability/VPVNP/PairShrinkCDReadBounds.lean
new file mode 100644
index 0000000000..caf0184f32
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCDReadBounds.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.PairShrinkCallHeader
+import OAI.Computability.VPVNP.PairShrinkArgumentReadBounds
+
+/-!
+# Addresses read by the CD rank scan
+
+The native expression tests every old arc in the second classified row for
+the selected bundle. Each candidate read stays in the ID rectangle, each
+rank read stays in the old-arc rank column, and the thickness test stays in
+the old-site column. Both possible child addresses use the original
+incidence columns and the full fixed-degree width prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCDReadBounds
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData CompressorRecords
+open CompressorRecords.PhaseRecipe CompressorRecords.BundleLists
+open scoped Fin.CommRing
+
+open private half_count from OAI.Computability.VPVNP.PairShrinkCDFieldAddress
+open private actual_id from OAI.Computability.VPVNP.PairShrinkABFrameAddress
+open private rowAt_val from OAI.Computability.VPVNP.CompressorRecordPreimageScan
+
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+variable (m : X.packingData.Motif) (C : ShrinkCD.Header)
+variable {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w}
+variable (H : ℕ) (T : IncidenceDirectory w) (origin : ℕ)
+local notation "P" => X.packingData
+local notation "d" => 2 ^ a
+local notation "Q" => pieceCount d (Shrink.colors a)
+local notation "sites" => Fintype.card X.Base * 2 ^ (packingLaneBits a g)
+local notation "N" => sites * d
+local notation "B" => (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * d
+local notation "Z" => ShrinkInput.plan X origin
+local notation "q" => ShrinkRankSpace.Shape.collectBank Z w
+local notation "rank" => ShrinkWidthArena.scatterBank T q
+ (CursorRAM.encode w (ShrinkRankSpace.Shape.ranks Z)) (ShrinkInput.widthBase X origin)
+local notation "pre" => ShrinkInput.placementBank X T origin
+local notation "ev" => Expr.eval pub state mem
+local notation "rd" => Expr.ReadsFrom (· < H) pub state mem
+/-- Classical equality on the input base vertices for tracing the CD row and incidence reads. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Readable source expressions for the row classifier and rank scan. -/
+structure ScanInputs (C : ShrinkCD.Header) (H : ℕ) (pub : Fin 5 → Word w) (state : Word w)
+ (mem : Memory w) : Prop where
+ owners : C.owners.ReadsFrom (· < H) pub state mem
+ lists : C.fields.lists.ReadsFrom (· < H) pub state mem
+ motif : C.fields.motif.ReadsFrom (· < H) pub state mem
+ stride : C.fields.listStride.ReadsFrom (· < H) pub state mem
+ ranks : C.fields.rankBase.ReadsFrom (· < H) pub state mem
+ thickness : C.thickness.ReadsFrom (· < H) pub state mem
+
+private theorem add_lt (x y : Word w) (h : x.val + y.val < H) : (x + y).val < H :=
+ (Nat.mod_le ..).trans_lt h
+
+private theorem sum_reads (xs : List Expr) (each : ∀ x ∈ xs, rd x) :
+ rd (PortRefresh.ArgumentAddress.sum xs) := by
+ induction xs with
+ | nil => trivial
+ | cons x xs ih => exact ⟨each x List.mem_cons_self,
+ ih (fun e he ↦ each e (List.mem_cons_of_mem _ he))⟩
+
+/-- Confinement of all candidate and rank probes, including the candidates
+whose ranks fail the test. -/
+theorem scan {first dest : ℕ} (safe : ScanInputs C H pub state mem)
+ (stored : C.fields.Stored X pub state mem q rank first dest m)
+ (geometry : ShrinkCallHeader.Geometry (w := w) X origin)
+ (owners : ev C.owners = q 2) (thick : ev C.thickness = pre 11)
+ (old : ShrinkCallHeader.OldTables X mem T origin) (twoFits : 2 < 2 ^ w)
+ (space : (Z).stop < 2 ^ w) (endBefore : (Z).stop ≤ H) :
+ rd (C.arc Q) ∧ rd (C.flag d Q) := by
+ let port := portIndex (Shrink.packedIndex (a := a) (g := g) X.baseIndex) ((P).bundle m)
+ let v := CursorRAM.encode w (B + port.val)
+ have portLt : port.val < B := port.isLt
+ have vw : v.val = B + port.val := Nat.mod_eq_of_lt (by have := geometry.bucketFit; omega)
+ have below : v < q 2 := by change v.val < (q 2).val; rw [vw, geometry.nrows]; omega
+ have bundle := (ShrinkAB.Physical.coordinates X C.fields pub state mem m stored
+ geometry.piecesFit).1
+ have half := half_count X C pub state mem twoFits owners geometry.nrows
+ have values := (Z).values T pre Fintype.card_pos space
+ have rowRoom : (q 5).val + (q 2).val * (q 4).val ≤ H := by
+ rw [values.ids, values.buckets, values.stride]
+ change (Z).gathered ≤ H
+ have h₁ : (Z).gathered ≤ (Z).ranks := Nat.le_add_right _ _
+ have h₂ : (Z).ranks ≤ (Z).stop := Nat.le_add_right _ _
+ exact h₁.trans (h₂.trans endBefore)
+ have candidate (i : Fin Q) : rd (C.candidate Q i.val) := by
+ refine ⟨⟨⟨safe.lists, ⟨⟨safe.owners, trivial⟩, safe.motif, trivial⟩, safe.stride⟩,
+ trivial⟩, ?_⟩
+ change ((ev C.fields.lists + ((ev (C.owners.div (.lit 2))) +
+ ev (C.fields.bundle Q)) * ev C.fields.listStride) + (i.val : Word w)).val < H
+ rw [stored.lists, half, bundle, stored.listStride]
+ have index : CursorRAM.encode w B + CursorRAM.encode w port.val = v :=
+ Fin.ext (Nat.add_mod ..).symm
+ rw [index]
+ change (rowAt q v + (i.val : Word w)).val < H
+ apply add_lt H
+ rw [rowAt_val geometry.regions below]
+ have indexFits := (Nat.mod_le i.val (2 ^ w)).trans_lt (i.isLt.trans_le geometry.cap)
+ have step := Nat.mul_le_mul_right (q 4).val (show v.val + 1 ≤ (q 2).val from below)
+ rw [Nat.succ_mul] at step
+ change (q 5).val + v.val * (q 4).val + i.val % (2 ^ w) < H
+ omega
+ have id (i : Fin Q) := ShrinkCD.candidate_eq X C pub state mem m stored geometry.arcFit
+ geometry.bucketFit geometry.piecesFit twoFits owners geometry.regions geometry.nrows
+ geometry.cap old.preimages i
+ have rankRead (i : Fin Q) : rd (.load (C.fields.rankBase.add (C.candidate Q i.val))) := by
+ refine ⟨⟨safe.ranks, candidate i⟩, ?_⟩
+ change (ev C.fields.rankBase + ev (C.candidate Q i.val)).val < H
+ rw [stored.rankBase, id, ← actual_id]
+ apply add_lt H
+ change (Fin.ofNat (2 ^ w) (Z).ranks).val + _ < H
+ rw [values.ranks]
+ let ord := BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex
+ have atRank (e : BundleKeys.OldArc X.Base a g) :
+ (Z).ranks + (Fin.ofNat (2 ^ w) (ord e).val).val < H :=
+ (Nat.add_lt_add_left ((Nat.mod_le ..).trans_lt (ord e).isLt) _).trans_le endBefore
+ exact atRank ((ShrinkCD.members X geometry.arcFit geometry.bucketFit ((P).bundle m) i).1.1)
+ have select (i : Fin Q) : rd (C.select Q i.val) := by
+ let diff := (Expr.load (C.fields.rankBase.add (C.candidate Q i.val))).sub (C.fields.piece Q)
+ have diffRead : rd diff := ⟨rankRead i, safe.motif, trivial⟩
+ exact ⟨⟨trivial, diffRead, diffRead⟩, candidate i⟩
+ have arcRead : rd (C.arc Q) := by
+ apply sum_reads H
+ intro e he
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp he
+ exact select i
+ refine ⟨arcRead, ⟨⟨safe.thickness, arcRead, trivial⟩, ?_⟩⟩
+ change (ev C.thickness + BinaryOp.div.eval (ev (C.arc Q)) ((2 ^ a : ℕ) : Word w)).val < H
+ rw [thick, ShrinkCD.arc_eq X C pub state mem m stored geometry.arcFit geometry.bucketFit
+ geometry.piecesFit twoFits owners geometry.regions geometry.nrows geometry.cap
+ old.preimages old.ranked, ← actual_id]
+ apply add_lt H
+ let ord := BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex
+ have small : (ord m.1).val % (2 ^ w) / d < sites :=
+ (Nat.div_lt_iff_lt_mul (Nat.two_pow_pos a)).2 ((Nat.mod_le ..).trans_lt (ord m.1).isLt)
+ have base : (pre 11).val ≤ ShrinkInput.placementBase X origin + sites := by
+ change (_ + 1 * sites) % (2 ^ w) ≤ _
+ simpa only [one_mul] using Nat.mod_le (ShrinkInput.placementBase X origin + sites) (2 ^ w)
+ have ready : (pre 11).val + sites ≤ H := by
+ have h := (ShrinkInput.range_bounds X origin).2.2.1
+ change ShrinkInput.placementBase X origin + 4 * sites ≤ (Z).stop at h
+ omega
+ change (pre 11).val + ((ord m.1).val % (2 ^ w) / (d % (2 ^ w))) % (2 ^ w) < H
+ rw [Nat.mod_eq_of_lt geometry.degreeFit]
+ exact (Nat.add_lt_add_left ((Nat.mod_le ..).trans_lt small) _).trans_le ready
+
+end PairSimulation.ShrinkCDReadBounds
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallABI.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallABI.lean
new file mode 100644
index 0000000000..112b36809a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallABI.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.CompressorBlockMetadataPackets
+import OAI.Computability.VPVNP.CompressorPublishedHeadsRun
+import OAI.Computability.VPVNP.PairShrinkPartyNative
+import OAI.Computability.VPVNP.PairShrinkCallFamily
+import OAI.Computability.VPVNP.PairSimulationLeafScalarStartup
+import OAI.Computability.VPVNP.PairTerminalLayout
+
+/-!
+# Register operands of a selected shrinking map
+
+The locator keeps the old header and the popped node. After the hidden pass
+the shared registers also hold the geometry pointer, histogram and the start
+of the scratch beyond the leaf verifier stacks. The resident scan supplies
+the selected motif ordinal. All descriptor expressions use these six live
+words and the external level metadata.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallABI
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe
+open Compression Compression.ShrinkMotif MotifConversion
+open scoped Fin.CommRing
+
+variable {w p r : ℕ} (c : Config w p r) (common : Fin 24 ↪ Fin r)
+
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g)) (m : X.packingData.Motif)
+ (degree n rowEnd labels : ℕ) (level : Word w) (mem : Memory w)
+local notation "R" => TerminalLayout.privateRegions degree n rowEnd labels
+
+/-- First private address after all stacks of capacity `n^40`. -/
+noncomputable def hiddenBase (regions : LeafArena.Regions) (n : ℕ) : ℕ :=
+ regions.stackBase + Fintype.card LeafStartup.ScalarPort * n ^ 40
+
+/-- Register readback for the descriptor and both kinds of gather. The node
+arena stride and the hidden slot stride are computed from metadata cell 17. -/
+theorem live (old : c.reg (common 11) = level)
+ (lengthWord : mem (level + 17).val = (n : Word w))
+ (motif : (c.reg (common 18)).val = (ShrinkMotifOrder.stateNumber X m).val)
+ (hidden : c.reg (common 8) = (hiddenBase R n : Word w))
+ (hist : c.reg (common 10) = ((R).histBase : Word w)) :
+ ShrinkCallHeader.Live X m (operands degree) (pub c common) (state c common) level mem
+ (R).arguments (hiddenBase R n) (n^2) (R).histBase := by
+ have len : mem (c.reg (common 11) + 17).val = (n : Word w) := by rw [old, lengthWord]
+ refine ⟨old, motif, len, ?_, hidden, ?_, hist⟩
+ · change ((2 * degree : ℕ) : Word w) * mem (c.reg (common 11) + 17).val + 1 =
+ ((2 * degree * n + 1 : ℕ) : Word w)
+ simp only [len, Nat.cast_add, Nat.cast_mul, Nat.cast_one]
+ · change mem (c.reg (common 11) + 17).val * mem (c.reg (common 11) + 17).val =
+ ((n ^ 2 : ℕ) : Word w)
+ rw [len, pow_two, Nat.cast_mul]
+
+/-- The surviving half-address expression indexes the popped node from the
+locator. Its destination is the same surviving interval used by the map. -/
+theorem supply_readback (dir : Bool) (slot : Fin 4) :
+ let I := ShrinkPartyNative.supplyInputs (operands degree) node a dir slot
+ I.node.eval (pub c common) (state c common) mem = c.reg (common 0) ∧
+ I.destination = ((operands degree).inputs a).surviving dir slot := ⟨rfl, rfl⟩
+
+/-- The only external probe in the six live register operands is the
+published length at offset 17. -/
+theorem operand_reads (D : ℕ → Prop) (inRange : D (c.reg (common 11) + 17).val) :
+ let O := operands degree
+ let rd := Expr.ReadsFrom D (pub c common) (state c common) mem
+ rd O.level ∧ rd O.motif ∧ rd O.arguments ∧ rd O.argumentStride ∧
+ rd O.hidden ∧ rd O.slotStride ∧ rd O.hist ∧ rd node := by
+ have lengthRead : Expr.ReadsFrom D (pub c common) (state c common) mem
+ (operands degree).arguments := ⟨⟨trivial, trivial⟩, inRange⟩
+ exact ⟨trivial, trivial, lengthRead, ⟨⟨trivial, lengthRead⟩, trivial⟩, trivial,
+ ⟨lengthRead, lengthRead⟩, trivial, trivial⟩
+
+section Metadata
+
+open DescriptorSpace BlockPlanner Schedule
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (base : Word w) (positions blocks t step : ℕ) (role : BlockMetadata.Role)
+ (fields : BlockMetadata.Fields)
+local notation "scr" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base
+local notation "first" => Script.levelsPerBlock scr * t
+local notation "head" => levelStart L (first + step)
+
+/-- The third DFS payload word copies the original problem length into
+the old-level header actually selected by the locator. -/
+theorem length_published {before : Memory w} {oldSites : ℕ} {rs : List (Report w)}
+ (installed : BlockMetadata.Published B base positions blocks t step role fields before
+ oldSites rs)
+ (rows : before (pt).rows.val = (directoryRows L : Word w))
+ (firstRoom : levelStart L 0 + 29 < 2 ^ w)
+ (initial : before (levelStart L 0 + 29) = (n : Word w)) :
+ after before (eventLog rs) (head + 17) = (n : Word w) := by
+ have ptr : BlockHeaderPlan.firstHeader.eval (pt).data (levelStart L first : Word w) before =
+ (levelStart L 0 : Word w) :=
+ BlockHeaderPlan.firstHeader_eval L base before _ (Fin.cast_val_eq_self _).symm rows
+ have h := installed.payload 2
+ change after before (eventLog rs) (head + 15 + 2) =
+ before ((BlockHeaderPlan.firstHeader.eval (pt).data (levelStart L first : Word w) before) +
+ (29 : Word w)).val at h
+ rw [ptr, ← show ((levelStart L 0 + 29 : ℕ) : Word w) = (levelStart L 0 : Word w) + 29 by simp,
+ Fin.val_natCast, Nat.mod_eq_of_lt firstRoom, initial] at h
+ simpa only [Nat.add_assoc] using h
+
+end Metadata
+
+/-- The four term and fourteen data-head stores preserve the metadata length
+used on entry to the map. -/
+theorem length_after_heads (L : DescriptorSpace.Layout) (P : Fin 5 → Word w) (st : Word w)
+ (before : Memory w) (head : ℕ) (termDest termValue : Fin 4 → Expr)
+ (dataDest dataValue : Fin 14 → Expr)
+ (lengthWord : before (head + 17) = (n : Word w))
+ (fit : head + 17 < 2 ^ w)
+ (term : PublishedHeads.Published L P st before (head + 36) termDest termValue)
+ (data : PublishedHeads.Published L P st
+ (PublishedHeads.image P st before (head + 36) termValue) (head + 40) dataDest dataValue) :
+ PublishedHeads.image P st (PublishedHeads.image P st before (head + 36) termValue)
+ (head + 40) dataValue ((head : Word w) + 17).val = (n : Word w) := by
+ rw [← show ((head + 17 : ℕ) : Word w) = (head : Word w) + 17 by simp, Fin.val_natCast,
+ Nat.mod_eq_of_lt fit]
+ exact (data.outside _ (.inl (by omega))).trans
+ ((term.outside _ (.inl (by omega))).trans lengthWord)
+
+end PairSimulation.ShrinkCallABI
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallABIReads.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallABIReads.lean
new file mode 100644
index 0000000000..8a09a7741b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallABIReads.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairShrinkCDReadBounds
+import OAI.Computability.VPVNP.PairShrinkDescriptorReads
+import OAI.Computability.VPVNP.PairShrinkPartyABReads
+import OAI.Computability.VPVNP.PairSimulationMapHandlerAction
+
+/-!
+# External reads of the six-register shrink map writer
+
+Each emitted operand expression reads from the selected old header, its
+incidence and classification tables, or the dense demand and term records
+in the completed shrink arena. The same header and arena bounds used by the
+native AB gather suffice for the CD lookup and the raw descriptor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData CompressorRecords
+open CompressorRecords.PhaseRecipe Compression.ShrinkMotif MotifGrid MotifBlocks MotifConversion
+open scoped Fin.CommRing
+open private cell_reads from OAI.Computability.VPVNP.PairShrinkPartyABReads
+
+variable {w a b g : ℕ} {K : Type*} [_root_.Field K] {δ factor : ℝ}
+variable {X : State a (packingLaneBits a g)}
+variable {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+variable {m : X.packingData.Motif} {party : Fin 6}
+variable (J : Job X F ready sel m party w) (degree : ℕ)
+variable {pub : Fin 5 → Word w} {state level H : Word w} {mem : Memory w}
+variable {T : IncidenceDirectory w} {origin : ℕ}
+local notation "O" => ShrinkCallABI.operands degree
+local notation "C" => ShrinkCallHeader.Operands.cdHeader (ShrinkCallABI.operands degree) a
+local notation "rd" => Expr.ReadsFrom (· < H.val) pub state mem
+local notation "ev" => Expr.eval pub state mem
+local notation "d" => 2 ^ a
+local notation "Q" => pieceCount d (Shrink.colors a)
+local notation "term" => ShrinkInput.termHead (w := w) X origin
+local notation "dense" => ShrinkInput.demandHead (w := w) X origin
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Every external load, including the full scan used to recover the CD
+source ID, lies below the terminal controller header. -/
+theorem Job.abi_descriptor_reads
+ (old : J.OldPublished O pub state mem level T origin)
+ (areas : J.ABAreas level T origin H.val)
+ (termsEnd : ShrinkInput.termEnd X origin 10 ≤ H.val) :
+ rd ((O).inputs a).descriptor ∧ ∀ j arg, rd (((O).inputs a).fields j arg) := by
+ have ins := J.abi_inputs_readable degree old areas
+ have cell := cell_reads old.live.header ins.level areas.levelEnd
+ have twoFits : 2 < 2 ^ w := by have := areas.levelEnd; have := H.isLt; omega
+ have G := ShrinkCallHeader.geometry X T origin old.space
+ have heads := ShrinkCallHeader.heads X F sel m O pub state level mem J.arena T origin
+ J.older J.pitch J.first J.scratch.hidden J.scratch.stride J.scratch.hist old.levelData old.live
+ have inputs : ShrinkCDReadBounds.ScanInputs C H.val pub state mem := by
+ have oldSites : rd (((O).cell 0).mul ((O).cell 2)) := ⟨cell 0 (by decide), cell 2 (by decide)⟩
+ have oldSlots : rd ((((O).cell 0).mul ((O).cell 2)).mul ((O).cell 1)) :=
+ ⟨oldSites, cell 1 (by decide)⟩
+ exact ⟨⟨cell 46 (by decide), cell 44 (by decide), trivial, oldSlots⟩, cell 46 (by decide),
+ ins.motif, trivial, cell 45 (by decide), ⟨cell 44 (by decide), trivial, oldSites⟩⟩
+ obtain ⟨arcRead, flagRead⟩ := ShrinkCDReadBounds.scan X m C H.val T origin inputs heads.ab G
+ heads.owners heads.thickness old.tables twoFits old.space areas.classifier
+ have arc := ShrinkCD.arc_eq X C pub state mem m heads.ab G.arcFit G.bucketFit G.piecesFit
+ twoFits heads.owners G.regions G.nrows G.cap old.tables.preimages old.tables.ranked
+ have endpoint (dir : Bool) := J.old_field_reads O old ins areas m.1 ((C).arc Q) dir arc arcRead
+ have cdReads (atD : Bool) : rd (((O).inputs a).cd atD) := by
+ cases atD
+ · exact ⟨⟨flagRead, endpoint true⟩, ⟨trivial, flagRead⟩, endpoint false⟩
+ · exact ⟨⟨⟨trivial, flagRead⟩, endpoint true⟩, ⟨trivial, trivial, flagRead⟩, endpoint false⟩
+ have stored := ShrinkCallHeader.stored X F sel m O pub state level mem J.arena T origin
+ J.older J.pitch J.first J.scratch.hidden J.scratch.stride J.scratch.hist old.levelData old.live
+ old.tables old.space twoFits
+ have count : rd ((O).count a) :=
+ ⟨⟨⟨cell 0 (by decide), trivial, cell 3 (by decide)⟩, trivial⟩, trivial⟩
+ have ord : idx < ShrinkTermInputs.motifCount X := ((ShrinkMotifOrder.entries X).symm m).isLt
+ have termRoom : (term).val + ShrinkTermInputs.motifCount X * 10 ≤ H.val := by
+ rw [ShrinkTermSelection.motifCount_eq X]
+ apply le_trans (Nat.add_le_add_right (Nat.mod_le ..) _) termsEnd
+ have pairRoom := (ShrinkInput.termLayout X T origin 10 (termsEnd.trans_lt H.isLt)).2.2.1
+ apply ShrinkDescriptorReads.fields stored H.val ins.level _ ins.motif ins.hidden ins.slot count
+ (show rd (O).hist from trivial) cdReads
+ · omega
+ · omega
+ · change (ev (O).level).val + 59 < H.val
+ rw [old.live.header]
+ have := areas.levelEnd
+ omega
+
+section Handler
+
+variable {k₀ : Type} [_root_.Field k₀] {S : BlockSchedule k₀} (B : S.Templates)
+variable {sel₀ : X.ShrinkSelection B.shrink} (job : Job X B.shrink ready sel₀ m party w)
+variable {t : ℕ} (ordinal : B.Entry → Fin t)
+
+/-- The selected handler's entire successful event list reads below the terminal
+controller header, including the external setup of its private descriptor. -/
+theorem Job.abi_success_reads
+ (old : job.OldPublished O pub state mem level T origin)
+ (areas : job.ABAreas level T origin H.val)
+ (termsEnd : ShrinkInput.termEnd X origin 10 ≤ H.val)
+ (I : LocalHistory.EntryInput B.shrink) (width : MapConstants.widthThreshold B.shrink ≤ w) :
+ SourceTransport.Reads (· < H.val) ((ShrinkCallABI.family B degree a ordinal).successEvents
+ demandMass_pos I width pub state mem) := by
+ obtain ⟨ptr, fields⟩ := job.abi_descriptor_reads degree old areas termsEnd
+ exact (ShrinkCallABI.family B degree a ordinal).successEvents_readsFrom demandMass_pos I width
+ pub state mem (· < H.val) ptr (fields I.party)
+
+end Handler
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallCapacity.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallCapacity.lean
new file mode 100644
index 0000000000..088c8c8614
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallCapacity.lean
@@ -0,0 +1,248 @@
+import OAI.Computability.VPVNP.PairNativeFrameGeometry
+import OAI.Computability.VPVNP.PairShrinkCallHeader
+import OAI.Computability.VPVNP.PairShrinkCallWorkspace
+import OAI.Computability.VPVNP.ShrinkFieldBounds
+
+/-!
+# Private capacity of all selected shrinking map calls
+
+The cursor branch bounds every intermediate width by an envelope of order
+`n ^ (3/10)`. The fixed block factor multiplying that envelope still gives
+at most `n` for all large inputs. Hence a whole admitted supply field,
+including its selectors, fits the square stride read by the native handoff.
+The map workspace follows the persistent leaf cache and its scalar stacks.
+All shared fields, nine staging fields and both selector buffers have a single
+polynomial upper address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallCapacity
+
+open Compression Compression.PackingData Compression.ShrinkMotif CompressorRecords
+open CursorBounds CursorNetwork MotifBlocks MotifGrid MotifConversion Filter
+open NodeArguments ShrinkCallFields
+open private shrinkMotif_count from OAI.Computability.VPVNP.PairSimulationSelectorBounds
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {factor : ℝ}
+
+/-- Uniform in the branch and its levels. Absorb a fixed linear width factor
+into the live input length before selecting a level or motif. -/
+theorem eventually_levels (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) (K : ℕ) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ ∀ z : (B.execute f hf T hT X).Choices, ∀ v ∈ executeLevels B f hf T hT X z,
+ v.input.positions ≤ initialPositions b n ∧ K * (v.input.maxWireWidth + 1) ≤ n := by
+ filter_upwards [eventually_pairBranchBounds B u b hb, eventually_ge_atTop (2 * K * K + 1)]
+ with n branch large
+ intro base lanes labels hD hT R _ f hf X T z v hv
+ obtain ⟨positions, width⟩ := executeLevels_limits B f hf T hT X z v hv
+ refine ⟨positions.trans_eq (pairInput_positions S labels hD), ?_⟩
+ let L := B.growthConstant ^ T * (X.maxWireWidth + 1)
+ have small : (L : ℝ) ≤ (n : ℝ) ^ (3 / 10 : ℝ) := (branch.2.2 labels hD hT R f hf z).2.2.2.2.2.1
+ have hn : 1 ≤ (n : ℝ) := by exact_mod_cast (by omega : 1 ≤ n)
+ have hs : (L : ℝ) ≤ Real.sqrt n := small.trans (by
+ rw [Real.sqrt_eq_rpow]
+ apply Real.rpow_le_rpow_of_exponent_le hn
+ norm_num)
+ have sq : L * L ≤ n := by
+ exact_mod_cast (mul_le_mul hs hs (Nat.cast_nonneg L) (Real.sqrt_nonneg _)).trans_eq
+ (Real.mul_self_sqrt (Nat.cast_nonneg n))
+ change v.input.maxWireWidth ≤ L at width
+ apply (Nat.mul_le_mul_left K (Nat.succ_le_succ width)).trans
+ by_cases h : 2 * K ≤ L
+ · by_cases hzero : L = 0
+ · rw [hzero] at h ⊢
+ have hk : K = 0 := by omega
+ simp [hk]
+ · have hsuc : L + 1 ≤ 2 * L := by omega
+ calc
+ K * (L + 1) ≤ K * (2 * L) := Nat.mul_le_mul_left _ hsuc
+ _ = (2 * K) * L := by ring
+ _ ≤ L * L := Nat.mul_le_mul_right _ h
+ _ ≤ n := sq
+ · calc
+ K * (L + 1) ≤ K * (2 * K) := Nat.mul_le_mul_left _ (by omega)
+ _ = 2 * K * K := by ring
+ _ ≤ n := by omega
+
+/-- Reserve four shared words per global motif, nine staging words, the port
+directory, the argument descriptor and both selector buffers. -/
+def extent (motifs n : ℕ) : ℕ :=
+ 4 * motifs * n ^ 2 + 9 * n ^ 2 + 16 + Fintype.card Arg + 2 * n
+
+theorem extent_bounded {motifs : ℕ → ℕ} (hM : PolynomiallyBounded motifs) :
+ PolynomiallyBounded (fun n ↦ extent (motifs n) n) := by
+ have shared := ((PolynomiallyBounded.const 4).mul hM).mul (PolynomiallyBounded.id.pow 2)
+ have staged := (PolynomiallyBounded.const 9).mul (PolynomiallyBounded.id.pow 2)
+ exact (((shared.add staged).add (.const 16)).add (.const (Fintype.card Arg))).add
+ ((PolynomiallyBounded.const 2).mul .id)
+
+/-- Map temporaries start immediately after the persistent cache and all
+scalar verifier stacks. The histogram stays in its original interval. -/
+def mapBase (R : LeafArena.Regions) (ports n : ℕ) : ℕ := R.stackBase + ports * n ^ 40
+
+theorem histogram_before (R : LeafArena.Regions) (ports n : ℕ) :
+ R.histBase + R.histWords ≤ mapBase R ports n :=
+ R.hist_before.trans ((Nat.le_add_right R.cacheBase 38).trans (Nat.le_add_right _ _))
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g))
+variable (F : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+variable (sel : X.ShrinkSelection F) (m : X.packingData.Motif)
+local notation "demand" => X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m
+local notation "payload" => Subtype.val (sel m)
+local notation "copies" => repetitions F (demand)
+local notation "ord" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+
+/-- The square stride also suffices using only the coarse input width bound
+`X.maxWireWidth ≤ n`. The finer cursor estimate in `eventually_levels`
+puts the copy count below `n` itself. -/
+theorem square_widths {n : ℕ} (hn : 1 ≤ n) (wide : 2 * fieldFactor F ≤ n)
+ (hw : X.maxWireWidth ≤ n) :
+ (∀ e, (demand) e ≤ n ^ 2) ∧ copies ≤ 2 * fieldFactor F * n ∧
+ copies ≤ n ^ 2 ∧ ∀ e, (payload) e + copies * F.selectorBits ≤ n ^ 2 := by
+ have bound := X.packingData.shrinkTerm_bounds (State.two_le_packingColors _)
+ (Nat.two_pow_pos _) X.shrinkNumber X.packingWidth (fun _ ↦ X.width_le_maxWireWidth _)
+ F m (sel m)
+ have field : fieldFactor F * (X.maxWireWidth + 1) ≤ 2 * fieldFactor F * n := by
+ calc
+ _ ≤ fieldFactor F * (2 * n) := Nat.mul_le_mul_left _ (by omega)
+ _ = _ := by ring
+ have sq : 2 * fieldFactor F * n ≤ n ^ 2 := by
+ rw [pow_two]
+ exact Nat.mul_le_mul_right _ wide
+ have lo : n ≤ n ^ 2 := by rw [pow_two]; exact Nat.le_mul_of_pos_right n hn
+ refine ⟨fun e ↦ ?_, bound.1.trans field, bound.1.trans (field.trans sq),
+ fun e ↦ ((bound.2 e).2.trans field).trans sq⟩
+ exact (X.packingData.shrinkDemandWidths_le (State.two_le_packingColors _)
+ (Nat.two_pow_pos _) X.shrinkNumber X.packingWidth (fun _ ↦ X.width_le_maxWireWidth _) m e).trans
+ (hw.trans lo)
+
+/-- The CD base at C or D points to the complete genuine input half-field.
+Its end remains below hidden storage whenever the child packet does. -/
+theorem cd_end (A : Arena) (older pitch hidden : ℕ)
+ (below : ∀ v (z : X.network.Half v),
+ A.base (older + pitch * PortRefresh.ArgumentAddress.siteOrdinal X v) +
+ (packed X v z).length ≤ hidden) (dir : Bool) :
+ ShrinkCallHeader.cdBase X m A older pitch dir + (demand) true ≤ hidden := by
+ let d := if dir then !(ShrinkOldHalves.cDirection X m) else ShrinkOldHalves.cDirection X m
+ let v := X.packingInputIso.site (ShrinkOldHalves.position X m.val d)
+ let j := ShrinkOldHalves.slot X m.val d
+ let z : X.network.Half v := ⟨fun _ _ _ ↦ false, fun _ _ _ ↦ false⟩
+ have len := congrArg List.length (ShrinkOldHalves.slot_bits X m.val d z)
+ have hw : X.halfWidth v d j = X.packingWidth m.val := by simpa only [List.length_ofFn] using len
+ change A.fieldAddress X v (older + pitch * PortRefresh.ArgumentAddress.siteOrdinal X v) d j +
+ X.packingWidth m.val ≤ hidden
+ rw [← hw]
+ exact (field_end_le X v z A _ d j).trans (below v z)
+
+/-- Numerical sufficiency for the actual native square stride. Both halves
+of the demand and every admitted selector-augmented supply field are bounded
+uniformly before the row ordinal is supplied. -/
+theorem fits {b n labels hist work bound motifs : ℕ} (hn : 1 ≤ n) (histLe : hist + labels ≤ work)
+ (workLe : work ≤ bound)
+ (motifLe : ShrinkTermInputs.motifCount X ≤ motifs)
+ (width : (fieldFactor F + 1) * (X.maxWireWidth + 1) ≤ n)
+ (cap : MapWorkspace.Capacity F (wordBits b n) n (bound + extent motifs n))
+ (A : Arena) (older pitch : ℕ)
+ (below : ∀ v (z : X.network.Half v),
+ A.base (older + pitch * PortRefresh.ArgumentAddress.siteOrdinal X v) +
+ (packed X v z).length ≤ work) :
+ let scratch := ShrinkCallHeader.scratch X work (n ^ 2) hist
+ Fits (w := wordBits b n) (n := n) (limit := bound + extent motifs n)
+ (u := copies) (t := labels) F (demand) (payload) scratch ord
+ (ShrinkCallHeader.cdBase X m A older pitch) := by
+ intro s
+ have term := X.packingData.shrinkTerm_bounds (State.two_le_packingColors _)
+ (Nat.two_pow_pos _) X.shrinkNumber X.packingWidth (fun _ ↦ X.width_le_maxWireWidth _)
+ F m (sel m)
+ have ab := X.packingData.shrinkDemandWidths_le (State.two_le_packingColors _)
+ (Nat.two_pow_pos _) X.shrinkNumber X.packingWidth (fun _ ↦ X.width_le_maxWireWidth _) m false
+ rw [Nat.add_mul, Nat.one_mul] at width
+ have all : fieldFactor F * (X.maxWireWidth + 1) ≤ n := by omega
+ have hcopy : copies ≤ n := term.1.trans all
+ have sq : n ≤ n ^ 2 := by rw [pow_two]; exact Nat.le_mul_of_pos_right _ hn
+ have card := Fintype.card_congr (ShrinkMotifOrder.stateNumber X)
+ rw [Fintype.card_fin] at card
+ have idx : ord < s.motifs := by
+ change ord < Fintype.card X.packingData.Motif
+ rw [card]
+ exact (ShrinkMotifOrder.stateNumber X m).isLt
+ refine ⟨cap, hcopy, idx, ab.trans (by change _ ≤ n ^ 2; omega),
+ cd_end X m A older pitch _ below, fun e ↦ ((term.2 e).2.trans all).trans sq, ?_, ?_⟩
+ · dsimp [s, ShrinkCallHeader.scratch, Scratch.directory, Scratch.staging]
+ omega
+ · have hM : 4 * ShrinkTermInputs.motifCount X * n ^ 2 ≤ 4 * motifs * n ^ 2 :=
+ Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ motifLe)
+ dsimp [s, ShrinkCallHeader.scratch, Scratch.target, Scratch.source, Scratch.descriptor,
+ Scratch.directory, Scratch.staging, extent]
+ omega
+
+/-- The threshold precedes every selection and every workspace address.
+An arbitrary polynomial upper bound on the end of the leaf stacks suffices. -/
+theorem eventually_capacity (b : ℕ) (hb : 1 ≤ b) (degree : ℕ) {work : ℕ → ℕ}
+ (hW : PolynomiallyBounded work) :
+ ∀ᶠ n : ℕ in atTop, MapWorkspace.Capacity F (wordBits b n) n
+ (work n + extent (initialPositions b n * degree) n) :=
+ MapWorkspace.eventually_capacity (B := F) b hb _
+ (hW.add (extent_bounded ((CursorRAM.bounded_positions b).mul (.const degree))))
+
+/-- All admitted motif IDs fit the global reservation, including those in
+subsequent shrinks whose base and remaining lane counts have changed. -/
+theorem motif_count {b n degree : ℕ} (positions : X.positions ≤ initialPositions b n)
+ (slots : 2 ^ a ≤ degree) : ShrinkTermInputs.motifCount X ≤ initialPositions b n * degree :=
+ (shrinkMotif_count X).trans (Nat.mul_le_mul positions slots)
+
+open Classical in
+/-- On the actual terminal layout the child row-number bound puts its entire
+packet below the histogram. Hidden and staged supply fields use the square
+stride in their dedicated region above the scalar stacks. -/
+theorem eventually_terminal_fits (b degree labels ports : ℕ) (hb : 1 ≤ b) {workLimit : ℕ → ℕ}
+ (hW : PolynomiallyBounded workLimit) :
+ ∀ᶠ n : ℕ in atTop, ∀ {a g : ℕ} (X : State a (packingLaneBits a g))
+ (sel : X.ShrinkSelection F) (m : X.packingData.Motif)
+ (firstRow rowWords older pitch : ℕ),
+ let G := NativeFrame.regions degree n firstRow rowWords labels
+ let scratch := ShrinkCallHeader.scratch X (mapBase G ports n) (n * n) G.histBase
+ let sizes := X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m
+ mapBase G ports n ≤ workLimit n → 2 ^ a ≤ degree → X.positions ≤ initialPositions b n →
+ (fieldFactor F + 1) * (X.maxWireWidth + 1) ≤ n →
+ (∀ v : X.network.Site,
+ older + pitch * PortRefresh.ArgumentAddress.siteOrdinal X v < G.nodes) →
+ Fits (w := wordBits b n) (n := n) (u := repetitions F sizes) (t := labels)
+ (limit := workLimit n + extent (initialPositions b n * degree) n)
+ F sizes (sel m).val scratch (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallHeader.cdBase X m G.arguments older pitch) := by
+ filter_upwards [eventually_capacity F b hb degree hW, eventually_ge_atTop 1]
+ with n cap hn
+ intro a g X sel m firstRow rowWords older pitch G scratch sizes workFit hd pos width nodes
+ have hw : X.maxWireWidth ≤ n := by
+ rw [Nat.add_mul, Nat.one_mul] at width
+ omega
+ have hist : G.histBase + labels ≤ mapBase G ports n := histogram_before G ports n
+ have packet (v : X.network.Site) (z : X.network.Half v) :
+ G.arguments.base (older + pitch * PortRefresh.ArgumentAddress.siteOrdinal X v) +
+ (packed X v z).length ≤ mapBase G ports n := by
+ have len : (packed X v z).length ≤ G.arguments.stride :=
+ (packed_length_le X v z).trans ((Nat.mul_le_mul (Nat.mul_le_mul_left 2 hd) hw).trans
+ (Nat.le_succ _))
+ have before := G.node_before (nodes v)
+ exact (Nat.add_le_add_left len _).trans (before.trans (by omega))
+ simpa only [scratch, sizes, pow_two] using
+ fits X F sel m hn hist workFit (motif_count X pos hd) width cap G.arguments older pitch packet
+
+end PairSimulation.ShrinkCallCapacity
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallDemandCells.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallDemandCells.lean
new file mode 100644
index 0000000000..ae03d63395
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallDemandCells.lean
@@ -0,0 +1,205 @@
+import OAI.Computability.VPVNP.PairShrinkABFrameAddress
+import OAI.Computability.VPVNP.PairShrinkCallFields
+import OAI.Computability.VPVNP.ShrinkLocalMaps
+import OAI.Computability.VPVNP.PairSimulationMapRow
+import OAI.Computability.VPVNP.LiveHeaderBits
+
+/-!
+# The four demand endpoints of a resident shrinking map
+
+The assembled AB word uses the demand-bit repartition of the old thick arcs.
+The two unsplit CD endpoints remain in their old child packets. Reading these
+four bit strings supplies exactly the local demand argument of the six-party
+matrix; an endpoint absent at the chosen party has width zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallDemandCells
+
+open Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel BurstRAM MotifEntry CompressorRecords
+open scoped Fin.CommRing
+
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+/-- Classical equality of base vertices for identifying the old sites assigned to each demand
+endpoint. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "P" => X.packingData
+local notation "BW" => X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth
+local notation "hc" => State.two_le_packingColors a
+local notation "hd" => Nat.two_pow_pos a
+
+variable (layout : Bool) (m : X.packingData.Motif) (party : Fin 6)
+
+/-- Independent old half-wire assignments for all sites placed at this motif party's resident
+site in the chosen layout. -/
+abbrev Old (j : Fin 6) := Placed ((P).shrinkPlace layout) ((P).oldWireNetwork X.packingWidth).Half
+ ((P).shrinkPartySite layout m j)
+
+/-- The length and bit string of the indicated demand endpoint at this party, extracted from
+its placed old half-wire assignments. -/
+noncomputable def endpoint (x : Old X layout m party) :=
+ MapRow.endpoint demandSource demandTarget party (BW m)
+ (demandBits demandSource demandTarget party
+ ((P).shrinkLocalDemandArg hc hd X.shrinkNumber X.shrinkOrder X.packingWidth layout m party x))
+
+private theorem input_bits {n : ℕ} (bits : Fin n → Bool) (i : Fin n) :
+ inputBits ((RAMSerialization.wordBits n).symm bits) i = bits i := by
+ rw [inputBits, LiveHeader.testBit_wordBits, Equiv.apply_symm_apply]
+
+/-- Convert the two old network arguments to the AB copy program's input coordinates. -/
+noncomputable def abHalf (dir : Bool) (x : Old X layout m (if dir then 1 else 0)) :
+ (P).PlacedHalf X.packingWidth layout (ShrinkOldHalves.abSite X m dir) := by
+ cases dir <;> exact (P).shrinkPlacedHalf X.packingWidth layout _ rfl x
+
+/-- The bit value produced by the AB column program at each of its two endpoints. -/
+noncomputable def abBit (dir : Bool) (x : Old X layout m (if dir then 1 else 0))
+ (i : Fin ((P).abWidth X.shrinkNumber X.packingWidth m)) : Bool :=
+ ShrinkAB.operand (P) X.shrinkNumber X.shrinkOrder X.packingWidth ⟨m, rfl⟩ hc hd
+ (ShrinkOldHalves.abData X layout m dir (abHalf X layout m dir x)) i
+
+variable (A : NodeArguments.Arena) (nodes : X.network.Site → ℕ)
+
+/-- Native AB slice writes supply the staged word required by the local demand reader. -/
+theorem ab_written (dir : Bool) (x : Old X layout m (if dir then 1 else 0))
+ (arcFit : Fintype.card X.Base * 2 ^ packingLaneBits a g * 2 ^ a ≤ 2 ^ w)
+ (bucketFit : let count := Fintype.card X.Base * (2 ^ Shrink.J a * 2 ^ g) * 2 ^ a
+ count + count ≤ 2 ^ w)
+ (first dest : ℕ) (old : Word w → Word w)
+ (room : dest + (P).abWidth X.shrinkNumber X.packingWidth m ≤ 2 ^ w)
+ (i : Fin ((P).abWidth X.shrinkNumber X.packingWidth m)) :
+ let rows := fun j ↦ ShrinkAB.Physical.row X m arcFit bucketFit j A nodes layout dir
+ (abHalf X layout m dir x) (first := first) (dest := dest)
+ ResidentColumn.writes rows (List.finRange (2 ^ Shrink.colors a * 2 ^ a / 4)) old
+ ((dest + i.val : ℕ) : Word w) = PrivateFields.bitValue w (abBit X layout m dir x i) :=
+ ShrinkAB.Physical.writes_operand X m arcFit bucketFit A nodes layout dir
+ (abHalf X layout m dir x) old room i
+
+/-- Directly addressed fields at parties C and D. -/
+noncomputable def cdBase (dir : Bool) := ShrinkOldHalves.address X A nodes m.1
+ (if dir then !(ShrinkOldHalves.cDirection X m) else ShrinkOldHalves.cDirection X m)
+
+/-- The original child packets survive a gather that changes only private
+cells at or beyond the staging pivot. This applies to either unsplit CD end. -/
+theorem placedPackets_frame {endAddr pivot : ℕ} {site}
+ {x : (P).PlacedHalf X.packingWidth layout site} {old new : Word w → Word w}
+ (read : ShrinkOldHalves.PlacedPackets X layout A nodes old site x endAddr)
+ (ends : ∀ u, A.base (nodes u) + A.stride ≤ pivot)
+ (frame : ∀ q : Word w, q.val < pivot → new q = old q) :
+ ShrinkOldHalves.PlacedPackets X layout A nodes new site x endAddr := by
+ intro u hu
+ let v := X.packingInputIso.site u
+ let z := (X.packingHalfEquiv u).symm (x u hu)
+ let q : NodeArguments.Packet := ⟨nodes v, NodeArguments.packed X v z⟩
+ obtain ⟨fits, stored⟩ : q.Fits A w endAddr ∧ q.Stored A (DFS.scratch endAddr old) := read u hu
+ refine ⟨fits, stored.congr ?_⟩
+ intro i
+ let a : Word w := ((A.base q.node + i.val : ℕ) : Word w)
+ have ha : a.val = A.base q.node + i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans_le fits.2.2)
+ have below : a.val < pivot := by
+ rw [ha]
+ exact (Nat.add_lt_add_left (i.isLt.trans_le fits.2.1) _).trans_le (ends v)
+ have above : endAddr ≤ a.val := by rw [ha]; exact fits.1.trans (Nat.le_add_right ..)
+ change NodeArguments.rawScratch (DFS.scratch endAddr new) a =
+ NodeArguments.rawScratch (DFS.scratch endAddr old) a
+ simpa only [NodeArguments.rawScratch, dite_eq_left above, DFS.scratch] using frame a below
+
+/-- Required AB output and the independent child packets selected at C and D. -/
+structure Readback (x : Old X layout m party) (priv : Word w → Word w)
+ (dest endAddr : ℕ) : Prop where
+ ab : ∀ (dir : Bool) (h : party = if dir then 1 else 0)
+ (i : Fin ((P).abWidth X.shrinkNumber X.packingWidth m)),
+ priv ((dest + i.val : ℕ) : Word w) = PrivateFields.bitValue w (abBit X layout m dir (h ▸ x) i)
+ c : ∀ h : party = 2, ShrinkOldHalves.PlacedPackets X layout A nodes priv _
+ ((P).shrinkPlacedHalf X.packingWidth layout _ ((P).shrinkPartySite_C layout m) (h ▸ x)) endAddr
+ d : ∀ h : party = 3, ShrinkOldHalves.PlacedPackets X layout A nodes priv _
+ ((P).shrinkPlacedHalf X.packingWidth layout ((P).roleD layout m) rfl
+ (h ▸ x : Old X layout m 3)) endAddr
+
+set_option maxHeartbeats 1600000 in
+-- Reducing all four dependent half-wire widths uses the packing and word equivalences.
+/-- Arbitrary, independently supplied old half-wires give the native demand
+bits at every endpoint of the actual selected map. -/
+theorem demandCells (x : Old X layout m party) (priv : Word w → Word w) (dest endAddr : ℕ)
+ (h : Readback X layout m party A nodes x priv dest endAddr)
+ (base : Bool × Bool → ℕ)
+ (bases : ∀ dir e, party = (if dir then demandTarget e else demandSource e) →
+ base (dir, e) = if e then cdBase X m A nodes dir else dest)
+ (q : Bool × Bool) (i : Fin (endpoint X layout m party x q).1) :
+ priv ((base q + i.val : ℕ) : Word w) =
+ PrimedInputRAM.encodeBit w ((endpoint X layout m party x q).2 i) := by
+ rcases q with ⟨dir, e⟩
+ revert i
+ cases dir <;> cases e
+ · by_cases hit : party = demandSource false
+ · subst party
+ rw [bases false false rfl]
+ change ∀ i : Fin (BW m false), _ =
+ PrimedInputRAM.encodeBit w (inputBits ((RAMSerialization.wordBits _).symm _) i)
+ intro i
+ erw [input_bits]
+ exact h.ab false rfl i
+ · have empty : endpoint X layout m party x (false, false) = ⟨0, Fin.elim0⟩ := by
+ simp [endpoint, MapRow.endpoint, hit]
+ rw [empty]
+ exact fun i ↦ i.elim0
+ · by_cases hit : party = demandSource true
+ · subst party
+ rw [bases false true rfl]
+ change ∀ i : Fin (BW m true), _ =
+ PrimedInputRAM.encodeBit w (inputBits ((RAMSerialization.wordBits _).symm _) i)
+ intro i
+ erw [input_bits]
+ exact ShrinkOldHalves.read_C X layout m (h.c rfl) i
+ · have empty : endpoint X layout m party x (false, true) = ⟨0, Fin.elim0⟩ := by
+ simp [endpoint, MapRow.endpoint, hit]
+ rw [empty]
+ exact fun i ↦ i.elim0
+ · by_cases hit : party = demandTarget false
+ · subst party
+ rw [bases true false rfl]
+ change ∀ i : Fin (BW m false), _ =
+ PrimedInputRAM.encodeBit w (inputBits ((RAMSerialization.wordBits _).symm _) i)
+ intro i
+ erw [input_bits]
+ exact h.ab true rfl i
+ · have empty : endpoint X layout m party x (true, false) = ⟨0, Fin.elim0⟩ := by
+ simp [endpoint, MapRow.endpoint, hit]
+ rw [empty]
+ exact fun i ↦ i.elim0
+ · by_cases hit : party = demandTarget true
+ · subst party
+ rw [bases true true rfl]
+ change ∀ i : Fin (BW m true), _ =
+ PrimedInputRAM.encodeBit w (inputBits ((RAMSerialization.wordBits _).symm _) i)
+ intro i
+ erw [input_bits]
+ exact ShrinkOldHalves.read_D X layout m (h.d rfl) i
+ · have empty : endpoint X layout m party x (true, true) = ⟨0, Fin.elim0⟩ := by
+ simp [endpoint, MapRow.endpoint, hit]
+ rw [empty]
+ exact fun i ↦ i.elim0
+
+/-- Read all demand cells at the actual descriptor's field bases. Only A, B, C
+and D have a nonempty demand endpoint. -/
+theorem scratch_demandCells (s : ShrinkCallFields.Scratch) (ord : ℕ)
+ (x : Old X layout m party) (priv : Word w → Word w) (endAddr : ℕ)
+ (h : Readback X layout m party A nodes x priv s.staging endAddr)
+ (q : Bool × Bool) (i : Fin (endpoint X layout m party x q).1) :
+ let f := s.fieldBase ord party layout (cdBase X m A nodes) (.inl q)
+ priv ((f + i.val : ℕ) : Word w) =
+ PrimedInputRAM.encodeBit w ((endpoint X layout m party x q).2 i) := by
+ apply demandCells X layout m party A nodes x priv s.staging endAddr h
+ (fun q ↦ s.fieldBase ord party layout (cdBase X m A nodes) (.inl q)) _ q i
+ intro dir e eq
+ simp only [ShrinkCallFields.Scratch.fieldBase, ShrinkCallFields.demandParty, eq, ite_true]
+
+end PairSimulation.ShrinkCallDemandCells
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallFamily.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallFamily.lean
new file mode 100644
index 0000000000..32fc3b1715
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallFamily.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PairShrinkCallHeader
+import OAI.Computability.VPVNP.PairSimulationMapHandlerImage
+import OAI.Computability.VPVNP.PairSimulationMapInvocationClock
+
+/-!
+# Fixed map handlers at one shrinking substep
+
+The grid point and party select an inlined handler with a fixed old degree.
+Every handler evaluates its descriptor from the old header, popped node,
+geometry, histogram, shrink scratch and selected motif ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallABI
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe
+open Compression Compression.ShrinkMotif MotifConversion
+open scoped Fin.CommRing
+
+/-- Old header, popped node, geometry pointer, histogram, shrink scratch,
+then the motif ordinal for the writer's state register. -/
+def sourceSlot : Fin 6 → Fin 24 := ![11, 0, 9, 10, 8, 18]
+
+/-- Identify each of the six recipe inputs with its register in the shared 24-register locator
+bank. -/
+def source (j : Fin 6) : MapHandlerImage.Source 24 := .inr (.inr (sourceSlot j))
+
+/-- The popped DFS node address, supplied in public operand one of the shrinking map recipe. -/
+def node : Expr := .publicWord 1
+
+/-- Build the call's address expressions from the old header, dense motif, private scratch
+base, and histogram. Header cell 17 supplies the live size used in both strides. -/
+def operands (degree : ℕ) : ShrinkCallHeader.Operands :=
+ let level := Expr.publicWord 0
+ let n := Expr.load (level.add (.lit 17))
+ ⟨level, .state, n, ((Expr.lit (2 * degree)).mul n).add (.lit 1),
+ .publicWord 4, n.mul n, .publicWord 3⟩
+
+/-- The shrink part of the common parameter-entry numbering, and the raw
+descriptor and field expressions consumed by the installed map writer. -/
+noncomputable def family {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (degree a : ℕ) {t : ℕ} (ordinal : B.Entry → Fin t) : MapHandlerImage.Family B.shrink t 24 where
+ regCount i := RegisterSetup.regCount (MapCallTable.formulas
+ (MapEntryTable.allocation B.shrink i.1 i.2) (Fintype.equivFin _) (Fintype.equivFin _)) + 3
+ portCount i := Nat.card (MapEntryTable.PublicPort B.shrink i.1 i.2)
+ layout i := MapInline.layout B.shrink i.1 i.2
+ ordinal := ordinal ∘ Sum.inl
+ base _ := ((operands degree).inputs a).descriptor
+ field i := ((operands degree).inputs a).fields i.2
+ source _ := source
+
+variable {w p r : ℕ} (c : Config w p r) (common : Fin 24 ↪ Fin r)
+
+/-- Read the five public recipe operands from the common registers selected by the shrink call
+interface. -/
+def pub (j : Fin 5) : Word w := c.reg (common (sourceSlot j.castSucc))
+
+/-- Read the sixth recipe input, the dense motif ordinal passed as the formula writer's state. -/
+def state : Word w := c.reg (common (sourceSlot 5))
+
+section Family
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (degree a : ℕ) {t : ℕ} (ordinal : B.Entry → Fin t)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (i : MapHandlerImage.Index B.shrink)
+
+theorem input_reg (j : Fin 6) :
+ (family B degree a ordinal).inputs dfs saved common i j = common (sourceSlot j) := rfl
+
+/-- The writer and the gather programs evaluate their recipes on this same
+five-word bank and state. -/
+theorem inputs_readback :
+ (fun j : Fin 5 ↦ c.reg ((family B degree a ordinal).inputs dfs saved common i j.castSucc)) =
+ pub c common ∧
+ c.reg ((family B degree a ordinal).inputs dfs saved common i 5) = state c common :=
+ ⟨rfl, rfl⟩
+
+end Family
+
+end PairSimulation.ShrinkCallABI
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallFields.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallFields.lean
new file mode 100644
index 0000000000..8e5ed803e2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallFields.lean
@@ -0,0 +1,308 @@
+import OAI.Computability.VPVNP.PairSimulationMapCallArg
+import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe
+import OAI.Computability.VPVNP.CompressorShrinkTermSelection
+
+/-!
+# The descriptor words of a resident six-party map
+
+The selected term supplies its copy count and the eight payload widths.
+The dense two-column demand array supplies AB and CD. Each absorbed role
+reads its single shared private slot. The surviving roles read the buffers
+assembled from subdivision frames. The CD endpoints read the stored old
+half-wire directly, and AB reads its assembled bundle slice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallFields
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe
+open Compression Compression.PackingData Compression.ShrinkMotif
+open MotifGrid MotifBlocks MotifConversion
+open scoped Fin.CommRing
+
+/-- One descriptor slot of the map evaluator, indexed by a demand edge or one of the eight
+supply roles where needed. -/
+abbrev Arg := MapCallSetup.Arg Bool (Bool × Fin 4)
+/-- A source or target half of a demand edge or supply role whose field buffer the six-party
+map can read. -/
+abbrev Endpoint := MapLookup.LabelField Bool (Bool × Fin 4)
+
+/-- The eight surviving endpoint staging intervals follow the single AB interval.
+Every absolute absorbed role has its own earlier interval, shared by its ends. -/
+structure Scratch where
+ /-- First private word reserved for absorbed supply labels shared by their two endpoints. -/
+ hidden : ℕ
+ /-- Number of private words reserved for each shared or staged field. -/
+ stride : ℕ
+ /-- Number of motifs for which the hidden pass reserves four shared field intervals apiece. -/
+ motifs : ℕ
+ /-- Private base address of the label histogram updated by the map evaluator. -/
+ hist : ℕ
+
+/-- Base of the AB buffer, immediately after the four shared intervals for each motif. -/
+def Scratch.staging (s : Scratch) := s.hidden + 4 * s.motifs * s.stride
+
+/-- Base of absorbed role `t`'s shared label in the four-field block for motif `ordinal`. -/
+def Scratch.shared (s : Scratch) (ordinal : ℕ) (t : Fin 4) :=
+ s.hidden + (ordinal * 4 + t.val) * s.stride
+
+/-- Base of role `t`'s staged surviving field at the chosen source or target end. -/
+def Scratch.surviving (s : Scratch) (dir : Bool) (t : Fin 4) :=
+ s.staging + (1 + dir.toNat * 4 + t.val) * s.stride
+
+/-- Base of the lookup directory after the AB interval and the eight surviving endpoint
+intervals. -/
+def Scratch.directory (s : Scratch) := s.staging + 9 * s.stride
+/-- Base of the map descriptor following the sixteen directory words. -/
+def Scratch.descriptor (s : Scratch) := s.directory + 16
+/-- Start of the source-copy indices immediately after the complete descriptor. -/
+def Scratch.source (s : Scratch) := s.descriptor + Fintype.card Arg
+/-- Start of the target-copy indices after all source-copy indices. -/
+def Scratch.target (s : Scratch) (copies : ℕ) := s.source + copies
+
+/-- The source party of a demand edge for an outgoing field and its target party for an
+incoming field. -/
+def demandParty (dir e : Bool) := if dir then demandTarget e else demandSource e
+
+/-- The party incident to the specified supply role at its outgoing or incoming end. -/
+def supplyParty (dir : Bool) (e : Bool × Fin 4) := if dir then supply.dst e else supply.src e
+
+/-- Locate the endpoint at party `j` in its old CD, staged AB, surviving, or shared buffer. An
+absent endpoint uses address zero. -/
+def Scratch.fieldBase (s : Scratch) (ordinal : ℕ) (j : Fin 6) (layout : Bool)
+ (cd : Bool → ℕ) : Endpoint → ℕ
+ | .inl (dir, e) => if j = demandParty dir e then (if e then cd dir else s.staging) else 0
+ | .inr (dir, e) => if j = supplyParty dir e then
+ (if e.1 = layout then s.surviving dir e.2 else s.shared ordinal e.2) else 0
+
+/-- Live operands: the canonical level header, the dense motif ordinal, the
+private arena and the old CD source or target computed from its physical row. -/
+structure Inputs where
+ /-- Register expression for the producing level header from which the map loads its published
+ addresses. -/
+ level : Expr
+ /-- Register expression for the selected motif number in the dense ordering. -/
+ ordinal : Expr
+ /-- Expression for the base of the shared absorbed-role buffers. -/
+ hidden : Expr
+ /-- Expression for the allocated width of each shared or staged buffer. -/
+ stride : Expr
+ /-- Expression for the number of motifs represented in the shared buffers. -/
+ motifs : Expr
+ /-- Expression for the private histogram base used to count selected map labels. -/
+ hist : Expr
+ /-- Expressions for the old CD half-wire buffers at the source and target of the demand edge. -/
+ cd : Bool → Expr
+
+namespace Inputs
+
+/-- Load the word at a fixed offset from the producing level header. -/
+def loadHead (I : Inputs) (offset : ℕ) : Expr := .load (I.level.add (.lit offset))
+
+/-- Compute this motif’s term-row address using the published term base, row stride and dense
+ordinal. -/
+def term (I : Inputs) := (I.loadHead 36).add (I.ordinal.mul (I.loadHead 37))
+/-- Read the copy count from the second word of the selected term row. -/
+def copies (I : Inputs) := Expr.load ((I.term).add (.lit 1))
+/-- Read the selected shrinking layout bit from offset 38 of the level header. -/
+def layout (I : Inputs) := I.loadHead 38
+/-- Load the AB or CD demand width in the two-word row for this motif. -/
+def demand (I : Inputs) (e : Bool) :=
+ Expr.load (((I.loadHead 47).add ((Expr.lit 2).mul I.ordinal)).add (.lit e.toNat))
+
+/-- Load the selected payload width at the recorded role index after the two leading term
+words. -/
+def payload (I : Inputs) (e : Bool × Fin 4) :=
+ Expr.load (((I.term).add (.lit 2)).add (.lit (ShrinkSliceArrays.supplyRoles.symm e).val))
+
+/-- Compute the start of the AB staging interval beyond the four shared buffers for every
+motif. -/
+def staging (I : Inputs) := I.hidden.add (((Expr.lit 4).mul I.motifs).mul I.stride)
+/-- Compute the shared buffer address for absorbed role `t` of the current motif. -/
+def shared (I : Inputs) (t : Fin 4) :=
+ I.hidden.add (((I.ordinal.mul (.lit 4)).add (.lit t.val)).mul I.stride)
+/-- Compute the staged buffer address for one of four surviving roles at the selected source or
+target end. -/
+def surviving (I : Inputs) (dir : Bool) (t : Fin 4) :=
+ I.staging.add ((Expr.lit (1 + dir.toNat * 4 + t.val)).mul I.stride)
+/-- Compute the lookup directory address after the nine staging intervals. -/
+def directory (I : Inputs) := I.staging.add ((Expr.lit 9).mul I.stride)
+/-- Compute the descriptor address immediately after the sixteen directory words. -/
+def descriptor (I : Inputs) := I.directory.add (.lit 16)
+/-- Compute the start of the source-copy indices after the descriptor slots. -/
+def source (I : Inputs) := I.descriptor.add (.lit (Fintype.card Arg))
+
+/-- Selecting between the two field addresses works in the machine-word ring. -/
+def select (bit yes no : Expr) := no.add ((yes.sub no).mul bit)
+
+/-- Build the register expression selecting the actual input buffer for an incident endpoint,
+using the recorded layout for supply roles. -/
+def base (I : Inputs) (j : Fin 6) : Endpoint → Expr
+ | .inl (dir, e) => if j = demandParty dir e then (if e then I.cd dir else I.staging) else .lit 0
+ | .inr (dir, e) => if j = supplyParty dir e then
+ if e.1 then select I.layout (I.surviving dir e.2) (I.shared e.2)
+ else select I.layout (I.shared e.2) (I.surviving dir e.2)
+ else .lit 0
+
+/-- Supply each descriptor slot of the selected party with its buffer address, size, copy count
+or histogram pointer. -/
+def fields (I : Inputs) (j : Fin 6) : Arg → Expr
+ | .base f => I.base j f
+ | .demand e => I.demand e
+ | .payload e => I.payload e
+ | .copies => I.copies
+ | .directory => I.directory
+ | .source => I.source
+ | .target => I.source.add I.copies
+ | .hist => I.hist
+
+end Inputs
+
+variable {w a g : ℕ} (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+variable (X : State a (packingLaneBits a g))
+variable {k : Type*} [_root_.Field k] {factor : ℝ}
+variable (F : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (selection : X.ShrinkSelection F) (m : X.packingData.Motif)
+local notation "MIdx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+local notation "BW" => X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m
+local notation "ev" => Expr.eval pub state mem
+
+/-- Readback equations identifying the live register expressions and published header cells
+with the selected motif, layout, term row and scratch allocation. -/
+structure Stored (I : Inputs) (s : Scratch) (term dense : Word w) (step : ℕ)
+ (layout : Bool) (cd : Bool → ℕ) : Prop where
+ ordinal : ev I.ordinal = (MIdx : Word w)
+ hidden : ev I.hidden = (s.hidden : Word w)
+ stride : ev I.stride = (s.stride : Word w)
+ motifs : ev I.motifs = (s.motifs : Word w)
+ hist : ev I.hist = (s.hist : Word w)
+ termBase : ev (I.loadHead 36) = term
+ termStride : ev (I.loadHead 37) = (step : Word w)
+ layout : ev I.layout = (layout.toNat : Word w)
+ denseBase : ev (I.loadHead 47) = dense
+ cd : ∀ dir, ev (I.cd dir) = (cd dir : Word w)
+
+open scoped Classical in
+/-- The descriptor word at each argument slot for a given motif and party, using the selected
+payload widths and fixed block repetition count. -/
+noncomputable def values (s : Scratch) (j : Fin 6) (layout : Bool) (cd : Bool → ℕ) : Arg → Word w
+ | .base f => s.fieldBase MIdx j layout cd f
+ | .demand e => BW e
+ | .payload e => (selection m).val e
+ | .copies => repetitions F BW
+ | .directory => s.directory
+ | .source => s.source
+ | .target => s.target (repetitions F BW)
+ | .hist => s.hist
+
+private theorem cast_val (v : Word w) : (v.val : Word w) = v := Fin.ext (Nat.mod_eq_of_lt v.isLt)
+
+private theorem word_of_val {v : Word w} {n : ℕ} (h : v.val = n) : v = (n : Word w) :=
+ h ▸ (cast_val v).symm
+
+variable {pub state mem X F selection m}
+variable (I : Inputs) (s : Scratch) (term dense : Word w) (step : ℕ) (layout : Bool) (cd : Bool → ℕ)
+variable (h : Stored pub state mem X m I s term dense step layout cd)
+
+include h in
+private theorem staging_eval : ev I.staging = (s.staging : Word w) := by
+ simp only [Inputs.staging, Scratch.staging, Expr.add, Expr.mul, Expr.eval, BinaryOp.eval,
+ h.hidden, h.motifs, h.stride, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+
+include h in
+private theorem base_eval (j : Fin 6) (f : Endpoint) :
+ ev (I.base j f) = (s.fieldBase MIdx j layout cd f : Word w) := by
+ have stage := staging_eval I s term dense step layout cd h
+ have shared (t : Fin 4) : ev (I.shared t) = (s.shared MIdx t : Word w) := by
+ simp only [Inputs.shared, Scratch.shared, Expr.add, Expr.mul, Expr.eval, BinaryOp.eval,
+ h.ordinal, h.hidden, h.stride, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+ have surv (dir : Bool) (t : Fin 4) : ev (I.surviving dir t) = (s.surviving dir t : Word w) := by
+ change ev I.staging + ((1 + dir.toNat * 4 + t.val : ℕ) : Word w) * ev I.stride = _
+ rw [stage, h.stride, ← Nat.cast_mul, ← Nat.cast_add]
+ rfl
+ rcases f with ⟨dir, e⟩ | ⟨dir, side, t⟩
+ · by_cases party : j = demandParty dir e
+ · cases e <;> simp [Inputs.base, Scratch.fieldBase, party, stage, h.cd]
+ · simp [Inputs.base, Scratch.fieldBase, party, Expr.eval]
+ · by_cases party : j = supplyParty dir (side, t)
+ · cases side <;> cases layout <;> simp [Inputs.base, Scratch.fieldBase, party, Inputs.select,
+ Expr.add, Expr.sub, Expr.mul, Expr.eval, BinaryOp.eval, h.layout, shared, surv]
+ · simp [Inputs.base, Scratch.fieldBase, party, Expr.eval]
+
+include h in
+open scoped Classical in
+/-- Every word to be written into the native call descriptor is read from the
+chosen term, the true CD/AB demand record, or its designated private region. -/
+theorem fields_eval
+ (pair : ShrinkTermInputs.statePairs X dense mem)
+ (fields : TermRecordScan.Fields F ShrinkSliceArrays.supplyRoles demandMass_pos BW
+ (selection m).val (ShrinkTermSelection.rowBase X term step m) mem)
+ (dfit : dense.val + 2 * MIdx + 1 < 2 ^ w)
+ (tfit : term.val + MIdx * step + 9 < 2 ^ w)
+ (j : Fin 6) (arg : Arg) :
+ ev (I.fields j arg) = values X F selection m s j layout cd arg := by
+ let n := term.val + MIdx * step
+ let row := ShrinkTermSelection.rowBase X term step m
+ have hr : row.val = n := Nat.mod_eq_of_lt (by omega)
+ have tr : ev I.term = (n : Word w) := by
+ change ev (I.loadHead 36) + ev I.ordinal * ev (I.loadHead 37) = _
+ rw [h.termBase, h.ordinal, h.termStride, ← cast_val term, ← Nat.cast_mul, ← Nat.cast_add]
+ have copies : ev I.copies = ((repetitions F BW : ℕ) : Word w) := by
+ change mem (ev I.term + 1).val = _
+ rw [tr, ← Nat.cast_add_one, show ((n + 1 : ℕ) : Word w).val = n + 1 from
+ Nat.mod_eq_of_lt (by omega)]
+ exact word_of_val (hr ▸ fields.2.1)
+ have dir : ev I.directory = (s.directory : Word w) := by
+ change ev I.staging + 9 * ev I.stride = _
+ rw [staging_eval I s term dense step layout cd h, h.stride]
+ simp [Scratch.directory]
+ have src : ev I.source = (s.source : Word w) := by
+ change (ev I.directory + 16) + (Fintype.card Arg : Word w) = _
+ rw [dir]
+ simp [Scratch.source, Scratch.descriptor]
+ cases arg with
+ | base f => exact base_eval I s term dense step layout cd h j f
+ | copies => exact copies
+ | directory => exact dir
+ | source => exact src
+ | hist => exact h.hist
+ | target =>
+ change ev I.source + ev I.copies = _
+ rw [src, copies, ← Nat.cast_add]
+ rfl
+ | payload e =>
+ let i := ShrinkSliceArrays.supplyRoles.symm e
+ have data := fields.2.2 i
+ rw [Equiv.apply_symm_apply] at data
+ change mem ((ev I.term + 2) + (i.val : Word w)).val = _
+ have fit : n + 2 + i.val < 2 ^ w := by have := i.isLt; dsimp [n]; omega
+ have cell : ((n : Word w) + 2 + (i.val : Word w)).val = n + 2 + i.val := by
+ change ((n : Word w) + ((2 : ℕ) : Word w) + (i.val : Word w)).val = _
+ rw [← Nat.cast_add, ← Nat.cast_add]
+ exact Nat.mod_eq_of_lt fit
+ rw [tr, cell]
+ exact word_of_val (hr ▸ data)
+ | demand e =>
+ have pp := pair m
+ change mem ((ev (I.loadHead 47) + 2 * ev I.ordinal) + (e.toNat : Word w)).val =
+ ((BW e : ℕ) : Word w)
+ rw [h.denseBase, h.ordinal, ← cast_val dense]
+ change mem (((dense.val : Word w) + ((2 : ℕ) : Word w) * (MIdx : Word w)) +
+ (e.toNat : Word w)).val = _
+ rw [← Nat.cast_mul, ← Nat.cast_add, ← Nat.cast_add]
+ cases e
+ · rw [Bool.toNat_false, Nat.add_zero, Fin.val_natCast,
+ Nat.mod_eq_of_lt (show dense.val + 2 * MIdx < 2 ^ w by omega)]
+ exact word_of_val pp.1
+ · rw [Bool.toNat_true, Fin.val_natCast, Nat.mod_eq_of_lt dfit]
+ exact word_of_val pp.2
+
+end PairSimulation.ShrinkCallFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallFrameLive.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallFrameLive.lean
new file mode 100644
index 0000000000..be58e300ba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallFrameLive.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.PairNativeFrameDescriptor
+import OAI.Computability.VPVNP.PairNativeFrameRun
+import OAI.Computability.VPVNP.PairShrinkCallABI
+import OAI.Computability.VPVNP.PairShrinkRoleHandoff
+
+/-!
+# Shrink-map operands from the native private geometry
+
+The terminal startup stores the pointer at the live length and the cache,
+length and histogram at offsets 8, 9 and 11. The hidden handoff and the map
+reload use these four cells, possibly at different points of the traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallFrameLive
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {w p r : ℕ}
+
+/-- Private geometry read by the two native handoffs. -/
+structure Stored (R : LeafArena.Regions) (n : ℕ) (mem : Word w → Word w) : Prop where
+ pointer : mem (n : Word w) = (NativeFrame.frameBase R : Word w)
+ cache : mem ((NativeFrame.frameBase R : Word w) + 8) = (R.cacheBase : Word w)
+ length : mem ((NativeFrame.frameBase R : Word w) + 9) = (n : Word w)
+ histogram : mem ((NativeFrame.frameBase R : Word w) + 11) = (R.histBase : Word w)
+
+variable (degree : ℕ) (pub : Fin 11 → Word w) (m : Memory w)
+
+/-- Both the startup `Result` and the geometry segment's `Ready` expose
+this pointer and the twelve fields in its actual outgoing private memory. -/
+theorem of_fields (header role : Word w) (priv : Word w → Word w)
+ (pointer : priv (pub 6) = (NativeFrame.frameBase
+ (NativeFrame.fromHeader degree pub header m) : Word w))
+ (fields : ∀ j : Fin 12, priv ((NativeFrame.frameBase
+ (NativeFrame.fromHeader degree pub header m) + j.val : ℕ) : Word w) =
+ NativeFrame.fields degree pub header role m j) :
+ Stored (NativeFrame.fromHeader degree pub header m) (pub 6).val priv := by
+ have atField (j : Fin 12) : priv ((NativeFrame.frameBase
+ (NativeFrame.fromHeader degree pub header m) : Word w) + (j.val : Word w)) =
+ NativeFrame.fields degree pub header role m j := by
+ rw [← Nat.cast_add]
+ exact fields j
+ refine ⟨?_, atField 8, ?_, atField 11⟩
+ · rw [Fin.cast_val_eq_self]; exact pointer
+ · exact (atField 9).trans (Fin.cast_val_eq_self _).symm
+
+/-- Concrete initial private geometry of a completed frame program. -/
+theorem of_run (P : NativeFrame.Ports r) (c out : Config w p r)
+ (run : NativeFrame.Result P degree pub m c out) :
+ Stored (NativeFrame.fromHeader degree pub (c.reg P.header) m) (pub 6).val out.privateMem :=
+ of_fields degree pub m (c.reg P.header) (c.reg P.role) out.privateMem run.pointer run.values
+
+/-- Rewrite the runtime region to the selected terminal row layout. -/
+theorem of_readback {first rows stride baseRadix laneRadix n labels : ℕ} {header span : Word w}
+ {priv : Word w → Word w}
+ (read : NativeFrame.Readback m header first rows stride baseRadix laneRadix span)
+ (source : Stored (NativeFrame.fromHeader degree pub header m) (pub 6).val priv)
+ (length : (pub 6).val = n) (labelCount : (pub 9).val = labels)
+ (room : first + rows < 2 ^ w) :
+ Stored (TerminalLayout.privateRegions degree n (first + rows) labels) n priv := by
+ rw [read.regions_eq degree pub n labels length labelCount room, length] at source
+ exact source
+
+variable {R : LeafArena.Regions} {n : ℕ} {before after : Word w → Word w}
+
+/-- Only the geometry pointer and its three live fields need to survive the
+private packet writes between startup and the handoffs. -/
+theorem Stored.transfer (h : Stored R n before)
+ (ptr : after (n : Word w) = before (n : Word w))
+ (cells : ∀ j ∈ ([8, 9, 11] : List ℕ), after ((NativeFrame.frameBase R + j : ℕ) : Word w) =
+ before ((NativeFrame.frameBase R + j : ℕ) : Word w)) : Stored R n after := by
+ have field (j : ℕ) (mem : j ∈ ([8, 9, 11] : List ℕ)) :
+ after ((NativeFrame.frameBase R : Word w) + (j : Word w)) =
+ before ((NativeFrame.frameBase R : Word w) + (j : Word w)) := by
+ rw [← Nat.cast_add]
+ exact cells j mem
+ exact ⟨ptr.trans h.pointer, (field 8 (by decide)).trans h.cache,
+ (field 9 (by decide)).trans h.length, (field 11 (by decide)).trans h.histogram⟩
+
+/-- Reading the geometry in the hidden handoff and then in the map reload
+sets the two concrete registers required by the party publication theorem. -/
+theorem handoff (hiddenFrame : Stored R n before) (mapFrame : Stored R n after)
+ (cfg : Config w p r) (common : Fin 24 ↪ Fin r)
+ (hidden : cfg.reg (common 8) = VertexLevel.hiddenBaseWord
+ (before (before (n : Word w) + 8)) (before (before (n : Word w) + 9)))
+ (hist : cfg.reg (common 10) = after (after (n : Word w) + 11)) :
+ cfg.reg (common 8) = (ShrinkCallABI.hiddenBase R n : Word w) ∧
+ cfg.reg (common 10) = (R.histBase : Word w) := by
+ rw [hiddenFrame.pointer, hiddenFrame.cache, hiddenFrame.length, VertexLevel.hiddenBaseWord_cast]
+ at hidden
+ rw [mapFrame.pointer, mapFrame.histogram] at hist
+ exact ⟨hidden, hist⟩
+
+end PairSimulation.ShrinkCallFrameLive
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallFrameStores.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallFrameStores.lean
new file mode 100644
index 0000000000..8a45b6fd2f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallFrameStores.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.PairShrinkCallFrameLive
+import OAI.Computability.VPVNP.PairVertexFrameData
+import OAI.Computability.VPVNP.PairShrinkHiddenStep
+import OAI.Computability.VPVNP.PairNodeChildPackets
+
+/-!
+# Private geometry through the two shrinking stores
+
+The vertex invariant gives the geometry pointer and the cache, length and
+histogram words. Child packets occupy argument slots below the geometry.
+Absorbed-wire stores occupy private slots beyond the leaf stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallFrameLive
+
+open BurstRAM DFS NodeArguments LeafSourceLoad TreeDecode
+open scoped Fin.CommRing
+open private resident_read from OAI.Computability.VPVNP.PairVertexControl
+
+variable {w n : ℕ} {R : LeafArena.Regions} {priv : Word w → Word w}
+local notation "G" => NativeFrame.frameBase R
+
+/-- Read the four live private cells directly from the scratch invariant
+carried at each pending vertex. -/
+theorem of_vertex {data : Fin 10 → Word w} {offset : Word w} {vals : Static 34 → Word w}
+ (frame : VertexFrameData R data offset vals (scratch n priv))
+ (cache : data 8 = (R.cacheBase : Word w)) (length : data 9 = (n : Word w))
+ (above : n ≤ G) (room : G + 12 ≤ 2 ^ w) : Stored R n priv := by
+ have resident := resident_read priv (G : Word w) offset (R.histBase : Word w) frame.resident
+ have value (j : Fin 10) : priv ((G : Word w) + (j.val : Word w)) = data j := by
+ have hj := j.isLt
+ have live : n ≤ ((G + j.val : ℕ) : Word w).val := by
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt (by omega : G + j.val < 2 ^ w)]
+ omega
+ have v := frame.record.values_at j
+ rw [rawScratch, dite_eq_left live] at v
+ rw [← Nat.cast_add]
+ exact v
+ exact ⟨resident.1, (value 8).trans cache, (value 9).trans length, resident.2.2⟩
+
+private theorem child_outside (A : Arena) (qs : List Packet) (x : Word w)
+ (fit : ∀ q ∈ qs, A.base q.node + q.bits.length ≤ 2 ^ w)
+ (outside : ∀ q ∈ qs, x.val < A.base q.node ∨ A.base q.node + q.bits.length ≤ x.val) :
+ ChildScan.storePackets A qs priv x = priv x := by
+ induction qs generalizing priv with
+ | nil => rfl
+ | cons q qs ih =>
+ exact (ih (fit := fun z hz ↦ fit z (List.mem_cons_of_mem _ hz))
+ (outside := fun z hz ↦ outside z (List.mem_cons_of_mem _ hz))).trans
+ (PrivateFields.storeBits_outside _ _ _ x (fit q List.mem_cons_self)
+ (outside q List.mem_cons_self))
+
+/-- The old children use real nodes below the region's exclusive node
+bound, and all of their packet intervals begin above the geometry pointer cell. -/
+theorem Stored.children (h : Stored R n priv) (qs : List Packet)
+ (fits : ∀ q ∈ qs, q.Fits R.arguments w n)
+ (nodes : ∀ q ∈ qs, q.node < R.nodes)
+ (abovePointer : ∀ q ∈ qs, n < R.arguments.base q.node)
+ (room : G + 12 ≤ 2 ^ w) :
+ Stored R n (ChildScan.storePackets R.arguments qs priv) := by
+ have kept (x : Word w) := child_outside (priv := priv) R.arguments qs x
+ (fun q hq ↦ (fits q hq).2.2)
+ apply h.transfer
+ · exact kept _ (fun q hq ↦ .inl ((Nat.mod_le ..).trans_lt (abovePointer q hq)))
+ · intro j hj
+ have small : j < 12 := by
+ simp only [List.mem_cons, List.not_mem_nil, or_false] at hj
+ omega
+ apply kept _
+ intro q hq
+ right
+ have before := R.node_before (nodes q hq)
+ have length := (fits q hq).2.1
+ have next : R.histBase ≤ G := Nat.le_add_right ..
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt (by omega : G + j < 2 ^ w)]
+ omega
+
+theorem hidden_below (base stride : ℕ) (rows : List ShrinkHiddenGuess.Row) (x : Word w)
+ (room : ∀ row ∈ rows, base + row.1 * stride + row.2.length ≤ 2 ^ w)
+ (below : x.val < base) : ShrinkHiddenGuess.storeRows base stride rows priv x = priv x := by
+ induction rows generalizing priv with
+ | nil => rfl
+ | cons row rows ih =>
+ exact (ih (room := fun z hz ↦ room z (List.mem_cons_of_mem _ hz))).trans
+ (PrivateFields.storeBits_outside _ _ _ x (room row List.mem_cons_self)
+ (.inl (below.trans_le (Nat.le_add_right _ _))))
+
+/-- The hidden store starts beyond the entire geometry directory. Its
+computed interval fits also cover zero-width absorbed rows. -/
+theorem Stored.hidden (h : Stored R n priv) (stride : ℕ) (rows : List ShrinkHiddenGuess.Row)
+ (above : n ≤ G) (fits : ∀ row ∈ rows,
+ ShrinkCallABI.hiddenBase R n + row.1 * stride + row.2.length ≤ 2 ^ w) :
+ Stored R n (ShrinkHiddenGuess.storeRows (ShrinkCallABI.hiddenBase R n) stride rows priv) := by
+ have room : G + 12 ≤ ShrinkCallABI.hiddenBase R n := by
+ unfold NativeFrame.frameBase ShrinkCallABI.hiddenBase LeafArena.Regions.stackBase
+ LeafArena.Regions.cacheBase
+ omega
+ have kept (x : Word w) := hidden_below (priv := priv) (ShrinkCallABI.hiddenBase R n) stride
+ rows x fits
+ apply h.transfer
+ · exact kept _ ((Nat.mod_le ..).trans_lt (by omega))
+ · intro j hj
+ have small : j < 12 := by
+ simp only [List.mem_cons, List.not_mem_nil, or_false] at hj
+ omega
+ exact kept _ ((Nat.mod_le ..).trans_lt ((Nat.add_lt_add_left small _).trans_le room))
+
+end PairSimulation.ShrinkCallFrameLive
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallHeader.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallHeader.lean
new file mode 100644
index 0000000000..e48e2503a2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallHeader.lean
@@ -0,0 +1,339 @@
+import OAI.Computability.VPVNP.PairShrinkCallFields
+import OAI.Computability.VPVNP.PairShrinkCDFieldAddress
+import OAI.Computability.VPVNP.CompressorShrinkInputTerms
+
+/-!
+# Reading the selected shrink map header
+
+The physical level contains a term head, a ten-word row stride, the selected
+layout and the dense AB/CD pair head. The number of private hidden slots
+comes from the actual base and residual lane counts of this level. Reading
+the classified CD row and its source-thickness flag supplies the direct
+pointers at C and D, including when the independent half-words disagree.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallHeader
+
+open Compression Compression.PackingData Compression.ShrinkMotif CompressorRecords
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords.PhaseRecipe
+open MotifGrid MotifBlocks MotifConversion
+open scoped Fin.CommRing
+
+/-- Live register expressions on entry to one resident map. -/
+structure Operands where
+ /-- External address of the selected old-level header. -/
+ level : Expr
+ /-- Dense ordinal selecting this motif's term and row in the shrinking tables. -/
+ motif : Expr
+ /-- Private start address of the argument frames indexed by absolute DFS node. -/
+ arguments : Expr
+ /-- Number of private words reserved between consecutive node argument frames. -/
+ argumentStride : Expr
+ /-- Start of the private shared supply-field slots, indexed by motif and role. -/
+ hidden : Expr
+ /-- Distance in private words between adjacent shared or staged supply fields. -/
+ slotStride : Expr
+ /-- Private address of the histogram to which the evaluated map contributes. -/
+ hist : Expr
+
+/-- Read a scalar or table pointer at the specified offset from the old-level header. -/
+def Operands.cell (O : Operands) (i : ℕ) := ShrinkCD.Published.load O.level i
+
+/-- The dense motif count is the product of absolute bundle count and piece count. -/
+def Operands.count (O : Operands) (a : ℕ) : Expr :=
+ (((O.cell 0).mul ((Expr.lit (2 ^ (Shrink.J a))).mul (O.cell 3))).mul (.lit (2 ^ a))).mul
+ (.lit (pieceCount (2 ^ a) (Shrink.colors a)))
+
+/-- First private staging word after the four shared slots reserved for each motif. -/
+def Operands.staging (O : Operands) (a : ℕ) : Expr :=
+ O.hidden.add (((Expr.lit 4).mul (O.count a)).mul O.slotStride)
+
+/-- Assemble the published CD lookup expressions from the selected level, motif ordinal, old
+argument geometry, and staging address. -/
+def Operands.cdHeader (O : Operands) (a : ℕ) : ShrinkCD.Header :=
+ ShrinkCD.Published.header a O.level O.motif O.arguments O.argumentStride (O.staging a)
+
+/-- Build the map-field recipe, including the dynamic motif count and the oriented CD source
+addresses at the old degree. -/
+def Operands.inputs (O : Operands) (a : ℕ) : ShrinkCallFields.Inputs :=
+ ⟨O.level, O.motif, O.hidden, O.slotStride, O.count a, O.hist,
+ (O.cdHeader a).field (2 ^ a) (pieceCount (2 ^ a) (Shrink.colors a))⟩
+
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+variable {k : Type*} [_root_.Field k] {factor : ℝ}
+variable (F : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (sel : X.ShrinkSelection F) (m : X.packingData.Motif)
+/-- Classical equality on old base vertices for interpreting the selected motif's native field
+and bundle pointers. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "P" => X.packingData
+local notation "d" => 2 ^ a
+local notation "c" => Shrink.colors a
+local notation "Q" => pieceCount d c
+local notation "arcs" => BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex
+local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex
+local notation "arcCount" => Fintype.card X.Base * 2 ^ (packingLaneBits a g) * d
+local notation "bundleCount" => (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * d
+local notation "side" => X.packingData.shrinkTermLayout F X.shrinkNumber X.packingWidth sel
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+
+variable (O : Operands) (pub : Fin 5 → Word w) (state level : Word w) (mem : Memory w)
+local notation "ev" => Expr.eval pub state mem
+
+/-- The private frame reserves four shared words per motif before the staged
+AB and surviving endpoints. -/
+def scratch (hidden stride hist : ℕ) : ShrinkCallFields.Scratch :=
+ ⟨hidden, stride, ShrinkTermInputs.motifCount X, hist⟩
+
+variable (A : NodeArguments.Arena) (T : IncidenceDirectory w) (origin older stride bankBase : ℕ)
+variable (hidden slotStride hist : ℕ)
+local notation "plan" => ShrinkInput.plan X origin
+local notation "q" => ShrinkRankSpace.Shape.collectBank plan w
+local notation "rank" => ShrinkWidthArena.scatterBank T q
+ (CursorRAM.encode w (ShrinkRankSpace.Shape.ranks plan)) (ShrinkInput.widthBase X origin)
+local notation "pre" => ShrinkInput.placementBank X T origin
+local notation "term" => ShrinkInput.termHead (w := w) X origin
+local notation "dense" => ShrinkInput.demandHead (w := w) X origin
+local notation "heap" => scratch X hidden slotStride hist
+
+/-- The scalar slots and graph-array heads of the actual old level, read as
+machine words at their offsets in the published header. -/
+structure Level : Prop where
+ vertices : mem (level + 0).val = (Fintype.card X.Base : Word w)
+ degree : mem (level + 1).val = ((2 ^ a : ℕ) : Word w)
+ lanes : mem (level + 2).val = ((2 ^ packingLaneBits a g : ℕ) : Word w)
+ residual : mem (level + 3).val = ((2 ^ g : ℕ) : Word w)
+ oldLayer : mem (level + 14).val = (older : Word w)
+ rowStride : mem (level + 15).val = (stride : Word w)
+ termHead : mem (level + 36).val = term
+ termStride : mem (level + 37).val = 10
+ layout : mem (level + 38).val = ((side).toNat : Word w)
+ abBank : mem (level + 43).val = (bankBase : Word w)
+ owner : mem (level + 44).val = ((plan).owner : Word w)
+ rankHead : mem (level + 45).val = ((plan).ranks : Word w)
+ ids : mem (level + 46).val = ((plan).ids : Word w)
+ demandHead : mem (level + 47).val = dense
+ actualOut : mem (level + 57).val = T.actualOut
+ actualIn : mem (level + 58).val = T.actualIn
+ width : mem (level + 59).val = T.width
+
+/-- The incoming recipe expressions evaluate to the selected level, motif ordinal, argument
+arena, scratch geometry, and histogram address. -/
+structure Live : Prop where
+ header : ev O.level = level
+ motif : (ev O.motif).val = idx
+ arguments : ev O.arguments = (A.start : Word w)
+ argumentStride : ev O.argumentStride = (A.stride : Word w)
+ hiddenBase : ev O.hidden = (hidden : Word w)
+ stride : ev O.slotStride = (slotStride : Word w)
+ histogram : ev O.hist = (hist : Word w)
+
+/-- Retained source data from the original port classifier, ranker, and
+preliminary placement pass in the memory on which this resident executes. -/
+structure OldTables : Prop where
+ preimages : PreimagesAt q (BundleLists.wordOwner (P) arcs sites) mem arcCount
+ ranked : BundleWidthScatter.RankedInput (P) X.shrinkNumber X.shrinkOrder arcs sites rank mem
+ X.packingWidth
+ incidence : T.ActualColumns X mem
+ thickness : ShrinkRAM.PlacementColumns X.slots X.baseIndex pre false mem
+
+private theorem word_of_val {v : Word w} {n : ℕ} (h : v.val = n) : v = (n : Word w) := by
+ subst n
+ exact Fin.ext (Nat.mod_eq_of_lt v.isLt).symm
+
+private theorem cell_eq (head : ev O.level = level) (i : ℕ) :
+ ev (O.cell i) = mem (level + (i : Word w)).val := by
+ change mem (ev O.level + (i : Word w)).val = _
+ rw [head]
+
+theorem count_eq (base : ev (O.cell 0) = (Fintype.card X.Base : Word w))
+ (lanes : ev (O.cell 3) = ((2 ^ g : ℕ) : Word w)) :
+ ev (O.count a) = (ShrinkTermInputs.motifCount X : Word w) := by
+ rw [ShrinkTermSelection.motifCount_eq X]
+ change ev (O.cell 0) * (((2 ^ (Shrink.J a) : ℕ) : Word w) * ev (O.cell 3)) *
+ ((2 ^ a : ℕ) : Word w) * (Q : Word w) = _
+ rw [base, lanes, ← Nat.cast_mul, ← Nat.cast_mul, ← Nat.cast_mul, ← Nat.cast_mul]
+
+/-- Natural address of the old CD half used at C or D, with orientation determined by the
+motif's old source thickness. -/
+noncomputable def cdBase (atD : Bool) : ℕ :=
+ ShrinkOldHalves.address X A (fun u ↦ older + stride * PortRefresh.ArgumentAddress.siteOrdinal X u)
+ m.1 (if atD then !(ShrinkOldHalves.cDirection X m) else ShrinkOldHalves.cDirection X m)
+
+variable (levelData : Level X F sel level mem T origin older stride bankBase)
+variable (live : Live X m O pub state level mem A hidden slotStride hist)
+variable (old : OldTables X mem T origin)
+
+/-- Pointer expressions shared by the unsplit CD read and the AB frame scan. -/
+structure Heads : Prop where
+ ab : (O.cdHeader a).fields.Stored X pub state mem q rank bankBase (heap).staging m
+ child : (O.cdHeader a).fields.oldHalf.Stored T A older stride pub state mem
+ owners : ev (O.cdHeader a).owners = q 2
+ thickness : ev (O.cdHeader a).thickness = pre 11
+ motifs : ev (O.count a) = (ShrinkTermInputs.motifCount X : Word w)
+
+include levelData live in
+theorem heads :
+ Heads X m O pub state mem A T origin older stride bankBase hidden slotStride hist := by
+ have cell := cell_eq O pub state level mem live.header
+ have vertices := (cell 0).trans levelData.vertices
+ have deg := (cell 1).trans levelData.degree
+ have lanes := (cell 2).trans levelData.lanes
+ have motifs := count_eq X O pub state mem vertices ((cell 3).trans levelData.residual)
+ have stage : ev (O.staging a) = ((heap).staging : Word w) := by
+ change ev O.hidden + 4 * ev (O.count a) * ev O.slotStride = _
+ rw [live.hiddenBase, motifs, live.stride]
+ simp [scratch, ShrinkCallFields.Scratch.staging]
+ have ab := ShrinkCD.Published.abHeader X pub state mem m O.level O.motif O.arguments
+ O.argumentStride (O.staging a) origin T bankBase (heap).staging live.motif
+ ((cell 46).trans levelData.ids) ((cell 45).trans levelData.rankHead)
+ ((cell 43).trans levelData.abBank) stage
+ have child := ShrinkCD.Published.child (a := a) pub state mem O.level O.motif O.arguments
+ O.argumentStride (O.staging a) T A older stride live.arguments live.argumentStride
+ ((cell 14).trans levelData.oldLayer) ((cell 15).trans levelData.rowStride)
+ ((cell 57).trans levelData.actualOut) ((cell 58).trans levelData.actualIn)
+ ((cell 59).trans levelData.width)
+ obtain ⟨owners, thick⟩ := ShrinkCD.Published.geometry X pub state mem O.level O.motif O.arguments
+ O.argumentStride (O.staging a) origin T vertices deg lanes ((cell 44).trans levelData.owner)
+ ((cell 46).trans levelData.ids)
+ exact ⟨ab, child, owners, thick, motifs⟩
+
+/-- Representability of the ranker's old ID and bucket arrays follows from
+the allocated end of the ranking stage. -/
+structure Geometry : Prop where
+ arcFit : arcCount ≤ 2 ^ w
+ bucketFit : bundleCount + bundleCount ≤ 2 ^ w
+ piecesFit : Q < 2 ^ w
+ degreeFit : d < 2 ^ w
+ regions : RowRegions q
+ nrows : (q 2).val = bundleCount + bundleCount
+ cap : Q ≤ (q 4).val
+
+include T in
+theorem geometry (space : (plan).stop < 2 ^ w) : Geometry (w := w) X origin := by
+ have ⟨arcFits, bucketsFit, piecesFit, degreeFits, _⟩ := (plan).scalarFits Fintype.card_pos space
+ have bounded := (plan).values T pre Fintype.card_pos space
+ have rowRegions : RowRegions q := by
+ have own : (q 1).val = (plan).owner := bounded.owner
+ constructor
+ · rw [own, bounded.count, bounded.counts]
+ change (plan).origin + (plan).A ≤ (plan).origin + 2 * (plan).A
+ omega
+ · rw [bounded.counts, bounded.buckets, bounded.ids]
+ exact le_rfl
+ · rw [bounded.ids, bounded.buckets, bounded.stride]
+ change (plan).gathered ≤ 2 ^ w
+ exact le_trans (Nat.le_add_right _ _) (le_trans (Nat.le_add_right _ _) space.le)
+ have bucketFits : bundleCount + bundleCount ≤ 2 ^ w := by
+ change 2 * bundleCount < _ at bucketsFit
+ omega
+ have nr : (q 2).val = bundleCount + bundleCount := by
+ change (2 * bundleCount) % (2 ^ w) = bundleCount + bundleCount
+ rw [Nat.mod_eq_of_lt (show 2 * bundleCount < 2 ^ w from bucketsFit), two_mul]
+ exact ⟨arcFits.le, bucketFits, piecesFit, degreeFits, rowRegions, nr, bounded.stride.ge⟩
+
+include levelData live old in
+theorem stored (space : (plan).stop < 2 ^ w) (twoFits : 2 < 2 ^ w) :
+ ShrinkCallFields.Stored pub state mem X m (O.inputs a) heap term dense 10 side
+ (cdBase X m A older stride) := by
+ have h := heads X F sel m O pub state level mem A T origin older stride bankBase
+ hidden slotStride hist levelData live
+ have G := geometry X T origin space
+ have cell := cell_eq O pub state level mem live.header
+ refine ⟨word_of_val live.motif, live.hiddenBase, live.stride, h.motifs, live.histogram,
+ (cell 36).trans levelData.termHead, (cell 37).trans levelData.termStride,
+ (cell 38).trans levelData.layout, (cell 47).trans levelData.demandHead, fun dir ↦ ?_⟩
+ exact ShrinkCD.field_eq X (O.cdHeader a) pub state mem m h.ab G.arcFit G.bucketFit G.piecesFit
+ twoFits h.owners G.regions G.nrows G.cap old.preimages old.ranked G.degreeFit pre false
+ old.thickness h.thickness T A older stride h.child old.incidence dir
+
+
+include levelData live old in
+/-- The exact descriptor value for every field of the selected resident map. -/
+theorem fields_eval (space : (plan).stop < 2 ^ w) (twoFits : 2 < 2 ^ w)
+ (room : ShrinkInput.termEnd X origin 10 < 2 ^ w)
+ (pair : ShrinkTermInputs.statePairs X dense mem)
+ (record : TermRecordScan.Fields F ShrinkSliceArrays.supplyRoles demandMass_pos
+ ((P).shrinkDemandWidths X.shrinkNumber X.packingWidth m) (sel m).val
+ (ShrinkTermSelection.rowBase X term 10 m) mem) (j : Fin 6) (arg : ShrinkCallFields.Arg) :
+ ev ((O.inputs a).fields j arg) = ShrinkCallFields.values X F sel m heap j side
+ (cdBase X m A older stride) arg := by
+ have h := stored X F sel m O pub state level mem A T origin older stride bankBase
+ hidden slotStride hist levelData live old space twoFits
+ have bounds := ShrinkInput.termLayout X T origin 10 room
+ have maxI : idx < ShrinkTermInputs.motifCount X := (ShrinkMotifOrder.entries X).symm m |>.isLt
+ apply ShrinkCallFields.fields_eval (O.inputs a) heap term dense 10 side
+ (cdBase X m A older stride) h pair record _ _ j arg
+ · have := bounds.2.2.1
+ have := (term).isLt
+ omega
+ · have := bounds.2.2.2
+ omega
+
+
+local notation "ord" => BundleLists.portIndex sites (X.packingData.bundle m)
+local notation "count" => 2 ^ c * d / 4
+local notation "bank" => ShrinkABSliceTable.bank (w := w) bankBase count Q (Fin.val ord)
+
+include levelData live old in
+/-- At every genuine thick-wire row index, the canonical header and the final
+bank recorded by the selected level meet the native column's operand contract. -/
+theorem ab_recorded (space : (plan).stop < 2 ^ w)
+ (alloc : ShrinkABSliceTable.Layout (ShrinkInput.thickBank X T origin)
+ (ShrinkInput.piecesBank X T origin) bundleCount count Q bankBase)
+ (bankWords : IndexedStarts.Stored bank
+ (ShrinkSliceArrays.thickWidths (P) X.shrinkOrder X.packingWidth ((P).bundle m))
+ (ShrinkSliceArrays.abWidths (P) X.shrinkNumber X.packingWidth ((P).bundle m)) mem)
+ (dir : Bool) (x : (P).PlacedHalf X.packingWidth side (ShrinkOldHalves.abSite X m dir))
+ (i : Fin count) :
+ let G := geometry X T origin space
+ let nodes := fun u ↦ older + stride * PortRefresh.ArgumentAddress.siteOrdinal X u
+ let row := ShrinkAB.Physical.row X m G.arcFit G.bucketFit i A nodes side dir x
+ (first := bankBase) (dest := (heap).staging)
+ row.Recorded ((O.cdHeader a).fields.setup d count Q dir i.val) pub state mem := by
+ intro G nodes row
+ have h := heads X F sel m O pub state level mem A T origin older stride bankBase
+ hidden slotStride hist levelData live
+ have countBound : count ≤ Q := by unfold pieceCount; omega
+ exact ShrinkAB.Physical.recorded X (O.cdHeader a).fields pub state mem m h.ab G.arcFit
+ G.bucketFit G.piecesFit i A side dir x T older stride h.child old.incidence G.degreeFit
+ G.regions G.nrows (countBound.trans G.cap) old.preimages old.ranked alloc
+ ⟨mem, bankWords, fun _ _ _ ↦ rfl⟩
+
+/-- The descriptor's computed C operand points to the stored bit of the
+selected old half-assignment. -/
+theorem read_C (header : ShrinkCallFields.Stored pub state mem X m (O.inputs a) heap term dense 10
+ side (cdBase X m A older stride)) {endAddr : ℕ} (priv : Word w → Word w)
+ (x : (P).PlacedHalf X.packingWidth side ((P).placement side ((P).C m)))
+ (prepared : ShrinkOldHalves.PlacedPackets X side A
+ (fun u ↦ older + stride * PortRefresh.ArgumentAddress.siteOrdinal X u) priv _ x endAddr)
+ (i : Fin (X.packingWidth m.1)) :
+ priv (ev ((O.inputs a).cd false) + (i.val : Word w)) =
+ PrivateFields.bitValue w ((P).localCWord X.packingWidth side m x i) := by
+ rw [header.cd, ← Nat.cast_add]
+ exact ShrinkOldHalves.read_C X side m prepared i
+
+/-- The descriptor's D operand selects the opposite physical end, using its
+independent child packet even when source and target coincide. -/
+theorem read_D (header : ShrinkCallFields.Stored pub state mem X m (O.inputs a) heap term dense 10
+ side (cdBase X m A older stride)) {endAddr : ℕ} (priv : Word w → Word w)
+ (x : (P).PlacedHalf X.packingWidth side ((P).roleD side m))
+ (prepared : ShrinkOldHalves.PlacedPackets X side A
+ (fun u ↦ older + stride * PortRefresh.ArgumentAddress.siteOrdinal X u) priv _ x endAddr)
+ (i : Fin (X.packingWidth m.1)) :
+ priv (ev ((O.inputs a).cd true) + (i.val : Word w)) =
+ PrivateFields.bitValue w ((P).localDWord X.packingWidth side m x i) := by
+ rw [header.cd, ← Nat.cast_add]
+ exact ShrinkOldHalves.read_D X side m prepared i
+
+end PairSimulation.ShrinkCallHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallPublished.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallPublished.lean
new file mode 100644
index 0000000000..6516254299
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallPublished.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.PairShrinkCallHeader
+import OAI.Computability.VPVNP.CompressorShrinkHeaderReads
+import OAI.Computability.VPVNP.CompressorBlockHeadStability
+
+/-!
+# A resident map's header after the native level publications
+
+Four term words are written first, followed by fourteen data heads. Their
+reports keep the old incidence and DFS metadata outside those intervals.
+The bundle ranker and term recipe identify the addresses stored at the
+actual offsets for AB slices and the selected term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallHeader
+
+open Compression Compression.PackingData CompressorRecords BurstRAM CompressorRecords.PhaseRecipe
+open CompressorRecords.DescriptorSpace
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ}
+local notation "a" => ShrinkBlockInputs.a i
+variable (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g))
+variable (sel : X.ShrinkSelection B.shrink) (T : IncidenceDirectory w) (origin : ℕ)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "term" => ShrinkInput.termHead (w := w) X origin
+local notation "dense" => ShrinkInput.demandHead (w := w) X origin
+local notation "side" => X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth sel
+local notation "Z" => ShrinkInput.plan X origin
+local notation "q" => ShrinkRankSpace.Shape.collectBank Z w
+local notation "wb" => ShrinkInput.widthBase X origin
+local notation "abStart" => ShrinkWidthArena.abBase X q wb
+local notation "F" => BlockProgram.geometry B
+local notation "initial" => BlockProgram.arena B i.val 0
+local notation "tr" => BlockHeadStability.shrinkTerms B i
+local notation "dr" => BlockDataHeads.values B F i initial (BlockProgram.arena B i.val 1)
+ (BlockProgram.arena B i.val 2) (BlockProgram.arena B i.val 3)
+
+variable (L : Layout) (first : ℕ) (pub : Fin 5 → Word w) (state : Word w) (before : Memory w)
+local notation "here" => levelStart L (first + i.val)
+local notation "mid" => PublishedHeads.image pub state before (here + 36) tr
+local notation "out" => PublishedHeads.image pub state mid (here + 40) dr
+
+private theorem recipe_heads {mem : Memory w}
+ (h : ShrinkBundlePlan.Reads X F i.val initial pub state mem origin T)
+ (space : (Z).stop < 2 ^ w) :
+ (ShrinkTermRecipe.term a (ShrinkBundlePlan.termInputs i.val a initial)).eval pub state mem =
+ term ∧
+ (ShrinkTermRecipe.dense a (ShrinkBundlePlan.termInputs i.val a initial)).eval pub state mem =
+ dense := by
+ let pars := ShrinkBundlePlan.termInputs i.val a initial
+ have described := ShrinkBundlePlan.term_input X h space
+ have dt := ShrinkTermRecipe.eval_term pars X pub state mem described
+ have dd := ShrinkTermRecipe.eval_dense pars X pub state mem described
+ have size := (Z).values T (ShrinkInput.placementBank X T origin) Fintype.card_pos space
+ have stride : (q 4).val = (Z).Q := size.stride
+ have startEq : abStart + 2 * ShrinkTermRecipe.M X = ShrinkInput.stop X origin := by
+ change (wb + 2 * ((Z).B * (q 4).val) + 2 * ((Z).B * (q 4).val) + 2 * (Z).B) +
+ 2 * ((Z).B * (Z).Q) = wb + 6 * ((Z).B * (Z).Q) + 2 * (Z).B
+ rw [stride]; ring
+ rw [startEq] at dt dd
+ exact ⟨dt, dd⟩
+
+set_option maxHeartbeats 1200000 in
+-- Identify every selected field in the two dependent publication walks.
+/-- The two chronological publication walks give the canonical resident
+header. The chosen score cell and the two DFS pointers are read at their
+own actual locations in the preceding memory. -/
+theorem Level.of_publications (older stride bankBase : ℕ)
+ (header : ShrinkHeaderReads.Header i X T origin L first before)
+ (entry : LevelFields.Entry L first pub state before)
+ (pitch : (pub 1 - 1).val < here + 36)
+ (dfs : before (here + 14) = (older : Word w) ∧ before (here + 15) = (stride : Word w))
+ (scoreWord : before (((ShrinkInput.termEnd X origin 10 + 2 : ℕ) : Word w)).val =
+ ((side).toNat : Word w))
+ (tableFit : here + 61 < 2 ^ w) (tableWord : before (here + 61) = (bankBase : Word w))
+ (space : (Z).stop < 2 ^ w)
+ (terms : PublishedHeads.Published L pub state before (here + 36)
+ (fun j : Fin 4 ↦ LevelFields.address i.val (36 + j.val)) tr)
+ (data : PublishedHeads.Published L pub state mid (here + 40)
+ (fun j : Fin 14 ↦ LevelFields.address i.val (40 + j.val)) dr) :
+ Level X B.shrink sel (here : Word w) out T origin older stride bankBase := by
+ have unchanged (n : ℕ) (hn : n < 36 ∨ 54 ≤ n) : out (here + n) = before (here + n) := by
+ exact (data.outside _ (by unfold PublishedHeads.Outside; omega)).trans
+ (terms.outside _ (by unfold PublishedHeads.Outside; omega))
+ have atTerm (j : Fin 4) : out (here + (36 + j.val)) = (tr j).eval pub state before := by
+ rw [← Nat.add_assoc]
+ exact (data.outside _ (.inl (by have := j.isLt; omega))).trans (terms.stored j)
+ have atData (j : Fin 14) : out (here + (40 + j.val)) = (dr j).eval pub state mid := by
+ rw [← Nat.add_assoc]; exact data.stored j
+ have middle (n : ℕ) (hn : n < 36 ∨ 40 ≤ n) : mid (here + n) = before (here + n) :=
+ terms.outside _ (by unfold PublishedHeads.Outside; omega)
+ have readMid : ShrinkHeaderReads.Header i X T origin L first mid :=
+ ⟨header.room, (middle _ (by decide)).trans header.vertices, (middle _ (by decide)).trans
+ header.degree, (middle _ (by decide)).trans header.lanes,
+ (middle _ (by decide)).trans header.residual, fun j ↦ (middle _ (Or.inr (by omega))).trans
+ (header.incidence j), (middle _ (by decide)).trans header.scratch⟩
+ have entered : LevelFields.Entry L first pub state mid :=
+ ⟨entry.pointer, (terms.outside _ (.inl pitch)).trans entry.pitch⟩
+ have read := header.reads B entry
+ have read' := readMid.reads B entered
+ have th := (recipe_heads B i X T origin pub state read space).1
+ have dh := (recipe_heads B i X T origin pub state read' space).2
+ have ranks := ShrinkBundlePlan.head_values X read'
+ let pars := ShrinkBundlePlan.termInputs i.val a initial
+ have n := ShrinkTermRecipe.eval_count pars X pub state before
+ (ShrinkBundlePlan.term_input X read space)
+ have score : (SelectedPlan.layout (ShrinkBlockInputs.selectedInputs B F i initial)).eval
+ pub state before = ((side).toNat : Word w) := by
+ change before (((ShrinkTermRecipe.term a pars).eval pub state before +
+ (ShrinkTermRecipe.count a pars).eval pub state before * ((10 : ℕ) : Word w)) + 2).val = _
+ rw [th, n]
+ have address : (term + (ShrinkTermRecipe.M X : Word w) * ((10 : ℕ) : Word w)) + 2 =
+ ((ShrinkInput.termEnd X origin 10 + 2 : ℕ) : Word w) := by
+ change ((((ShrinkInput.stop X origin + 2 * ShrinkTermRecipe.M X : ℕ) : Word w) +
+ (ShrinkTermRecipe.M X : Word w) * ((10 : ℕ) : Word w)) + 2) =
+ ((ShrinkInput.stop X origin + 2 * ShrinkTermRecipe.M X + ShrinkTermRecipe.M X * 10 + 2 :
+ ℕ) : Word w)
+ simp only [Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+ rw [address]
+ exact scoreWord
+ have abHead : (BlockProgram.arena B i.val 1).eval pub state mid = (bankBase : Word w) :=
+ (LevelFields.eval_scalar entered i.val 61 tableFit).trans
+ ((middle _ (by decide)).trans tableWord)
+ have addr (n : ℕ) (hn : n ≤ 59) : (((here : Word w) + (n : Word w))).val = here + n := by
+ rw [← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt (by have := header.room; omega)]
+ have ten : (tr 1).eval pub state before = ((10 : ℕ) : Word w) := rfl
+ have co : T.column 3 = T.actualOut := rfl
+ have ci : T.column 4 = T.actualIn := rfl
+ have cw : T.column 5 = T.width := rfl
+ constructor
+ · simpa only [Nat.cast_zero] using (congrArg out (addr 0 (by decide))).trans
+ ((unchanged _ (by decide)).trans header.vertices)
+ · simpa only [Nat.cast_one] using (congrArg out (addr 1 (by decide))).trans
+ ((unchanged _ (by decide)).trans header.degree)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 2 (by decide))).trans
+ ((unchanged _ (by decide)).trans header.lanes)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 3 (by decide))).trans
+ ((unchanged _ (by decide)).trans header.residual)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 14 (by decide))).trans
+ ((unchanged _ (by decide)).trans dfs.1)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 15 (by decide))).trans
+ ((unchanged _ (by decide)).trans dfs.2)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 36 (by decide))).trans
+ ((atTerm 0).trans th)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 37 (by decide))).trans
+ ((atTerm 1).trans ten)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 38 (by decide))).trans
+ ((atTerm 2).trans score)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 43 (by decide))).trans
+ ((atData 3).trans abHead)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 44 (by decide))).trans
+ ((atData 4).trans ranks.owner)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 45 (by decide))).trans
+ ((atData 5).trans ranks.ranks)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 46 (by decide))).trans
+ ((atData 6).trans ranks.ids)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 47 (by decide))).trans
+ ((atData 7).trans dh)
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 57 (by decide))).trans
+ ((unchanged _ (by decide)).trans ((header.incidence 3).trans co))
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 58 (by decide))).trans
+ ((unchanged _ (by decide)).trans ((header.incidence 4).trans ci))
+ · simpa only [Nat.cast_ofNat] using (congrArg out (addr 59 (by decide))).trans
+ ((unchanged _ (by decide)).trans ((header.incidence 5).trans cw))
+
+end PairSimulation.ShrinkCallHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallSupplyCells.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallSupplyCells.lean
new file mode 100644
index 0000000000..9114aa561b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallSupplyCells.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.PairShrinkCallFields
+import OAI.Computability.VPVNP.PairShrinkSurvivingOperands
+import OAI.Computability.VPVNP.PairShrinkHiddenSlots
+import OAI.Computability.VPVNP.LiveHeaderBits
+
+/-!
+# Supply bits of a shrinking map in the caller's private memory
+
+An incident port is either an absorbed wire shared between its two resident
+maps or a surviving wire assembled from the independently stored half-wire
+of the current output vertex. Reading its own physical field yields the
+payload bits followed by the selector bits of the selected matrix column.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallSupplyCells
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel MotifEntry ShrinkCallFields
+open scoped Fin.CommRing
+open private readSupplyEnd layoutCases_absorbed from OAI.Computability.VPVNP.ShrinkSupplyLocal
+
+variable {a b g w pad : ℕ} (X : State a (packingLaneBits a g))
+variable (layout : Bool) (subdiv : Fin 4 → ℕ)
+variable (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+variable {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+variable (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad) (hpos : ∀ t, 0 < subdiv t)
+variable (m : X.packingData.Motif) (j : Fin 6)
+local notation "W" => fun m t ↦ widths m (layout, t)
+local notation "Idx" => Fin.val (CompressorRecords.ShrinkMotifOrder.stateNumber X m)
+
+variable (s : Scratch)
+variable (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel widths layout)
+ (X.packingData.shrinkPartySite layout m j))
+variable (z : (X.shrinkOutputState layout subdiv (fun m t ↦ widths m (layout, t)) I).network.Half
+ (X.packingData.shrinkPartySite layout m j))
+
+/-- The assembled private field agrees pointwise with the reverse copies from
+the new vertex. Each right-hand side uses its own actual source or target half. -/
+def Retained (before after : Word w → Word w) : Prop :=
+ ∀ dir t (party : j = ShrinkSurvivingOperands.party layout t dir),
+ let site := (congrArg (X.packingData.shrinkPartySite layout m) party).trans
+ (ShrinkSurvivingOperands.party_site X layout m t dir)
+ let halves : (X.shrinkOutputState layout subdiv (fun m t ↦ widths m (layout, t)) I).network.Half
+ (ShrinkSurvivingOperands.site X layout m t dir) :=
+ ⟨fun e he ↦ z.1 e (site.trans he), fun e he ↦ z.2 e (site.trans he)⟩
+ let dst := s.surviving dir t
+ ∀ i : Fin (widths m (layout, t)), after ((dst + i.val : ℕ) : Word w) =
+ ShrinkSurvivingOperands.nativeFill X layout subdiv (W) I m t dir halves dst before
+ ((dst + i.val : ℕ) : Word w)
+
+/-- The once-guessed field at its absolute ID survives every assembly copy. -/
+def Absorbed (after : Word w → Word w) : Prop :=
+ ∀ t (owned : X.packingData.shrinkPartySite layout m j =
+ X.packingData.shrinkInternalOwner layout (m, t))
+ (i : Fin (widths m (!layout, t))),
+ after ((s.shared Idx t + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (RAMSerialization.wordBits _ (h (m, t) owned) i)
+
+private theorem input_bit {n : ℕ} (x : Fin (2 ^ n)) (i : Fin n) :
+ inputBits x i = RAMSerialization.wordBits n x i := LiveHeader.testBit_wordBits _ _
+
+variable (before after : Word w → Word w)
+variable (hidden : Absorbed X layout widths m j s h after)
+variable (retained : Retained X layout subdiv widths I m j s z before after)
+variable (room : ∀ dir t, s.surviving dir t + widths m (layout, t) ≤ 2 ^ w)
+
+include retained room in
+private theorem retained_cell (t : Fin 4) (dir : Bool)
+ (party : j = ShrinkSurvivingOperands.party layout t dir) (i : Fin (widths m (layout, t))) :
+ after ((s.surviving dir t + i.val : ℕ) : Word w) = PrivateFields.bitValue w
+ (inputBits (ShrinkSurvivingOperands.mapColumn X layout subdiv I hpos m t widths dir
+ (party ▸ h) (party ▸ z)) i) := by
+ subst j
+ rw [input_bit]
+ exact (retained dir t rfl i).trans
+ (ShrinkSurvivingOperands.nativeFill_mapColumn X layout subdiv I hpos m t widths dir h z
+ (s.surviving dir t) before (room dir t) i)
+
+/-- Select one actual source or target coordinate from the six-party matrix column. -/
+noncomputable def word (dir : Bool) (e : Bool × Fin 4) (p : j = supplyParty dir e) :
+ Fin (2 ^ widths m e) :=
+ match dir with
+ | false => (X.packingData.shrinkLocalSupplyArg layout subdiv widths I hpos m j h z).1 e p
+ | true => (X.packingData.shrinkLocalSupplyArg layout subdiv widths I hpos m j h z).2 e p
+
+include hidden retained room in
+theorem read (cd : Bool → ℕ) (dir : Bool) (e : Bool × Fin 4) (party : j = supplyParty dir e)
+ (i : Fin (widths m e)) :
+ after ((s.fieldBase Idx j layout cd (.inr (dir, e)) + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w
+ (inputBits (word X layout subdiv widths I hpos m j h z dir e party) i) := by
+ rcases e with ⟨l,t⟩
+ by_cases active : l = layout
+ · subst l
+ rw [Scratch.fieldBase, ite_eq_left party, ite_eq_left rfl]
+ have hp : j = ShrinkSurvivingOperands.party layout t dir := by cases dir <;> exact party
+ have hh := retained_cell X layout subdiv widths I hpos m j s h z before after retained room
+ t dir hp i
+ subst j
+ cases dir <;> exact hh
+ · have he : l = !layout := Bool.eq_not_of_ne active
+ subst l
+ rw [Scratch.fieldBase, ite_eq_left party, ite_eq_right active]
+ subst j
+ rw [input_bit]
+ cases dir <;> simp only [word, supplyParty,
+ shrinkLocalSupplyArg, readSupplyEnd, layoutCases_absorbed] <;> apply hidden
+
+
+end PairSimulation.ShrinkCallSupplyCells
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCallWorkspace.lean b/lean/OAI/Computability/VPVNP/PairShrinkCallWorkspace.lean
new file mode 100644
index 0000000000..4abdf8238b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCallWorkspace.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.PairShrinkCallFields
+import OAI.Computability.VPVNP.PairSimulationMapWorkspaceLayout
+import OAI.Computability.VPVNP.PairSimulationMapArgumentInput
+
+/-!
+# Workspace and argument separation of the six-party map
+
+The private input addresses may lie on either side of the histogram. All
+inputs end before the map's port directory, then come its argument record,
+selector ordinals and decoded labels. The nine staging intervals comprise
+AB and the source and target of each of the four surviving wire types.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallFields
+
+open BurstRAM Compression Compression.ShrinkMotif MotifEntry
+open MotifGrid MotifBlocks MotifConversion MapWorkspace
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+theorem Scratch.shared_end (s : Scratch) {n : ℕ} (hm : n < s.motifs) (t : Fin 4) :
+ s.shared n t + s.stride ≤ s.staging := by
+ have k : n * 4 + t.val + 1 ≤ 4 * s.motifs := by have := t.isLt; omega
+ have hk := Nat.mul_le_mul_right s.stride k
+ rw [Nat.succ_mul] at hk
+ unfold Scratch.shared Scratch.staging
+ omega
+
+theorem Scratch.surviving_end (s : Scratch) (dir : Bool) (t : Fin 4) :
+ s.surviving dir t + s.stride ≤ s.directory := by
+ have k : 1 + dir.toNat * 4 + t.val + 1 ≤ 9 := by cases dir <;> have := t.isLt <;> simp <;> omega
+ have hk := Nat.mul_le_mul_right s.stride k
+ rw [Nat.succ_mul] at hk
+ unfold Scratch.surviving Scratch.directory
+ omega
+
+theorem Scratch.rawEnd (s : Scratch) (n : ℕ) (hn : n < s.motifs) (j : Fin 6) (layout : Bool)
+ (cd : Bool → ℕ) (demand : Bool → ℕ) (payload : Bool × Fin 4 → ℕ) (tags copies : ℕ)
+ (ab : demand false ≤ s.stride) (old : ∀ dir, cd dir + demand true ≤ s.hidden)
+ (wire : ∀ e, payload e + copies * tags ≤ s.stride) (f : Endpoint) :
+ s.fieldBase n j layout cd f + rawWidth demand payload tags copies f ≤ s.directory := by
+ have before : s.hidden ≤ s.staging := Nat.le_add_right ..
+ have after : s.staging + s.stride ≤ s.directory := by unfold Scratch.directory; omega
+ rcases f with ⟨dir, e⟩ | ⟨dir, e⟩
+ · cases e
+ · change (if j = demandParty dir false then s.staging else 0) + demand false ≤ _
+ split <;> omega
+ · change (if j = demandParty dir true then cd dir else 0) + demand true ≤ _
+ have bound := old dir
+ split <;> omega
+ · change (if j = supplyParty dir e then
+ (if e.1 = layout then s.surviving dir e.2 else s.shared n e.2) else 0) +
+ (payload e + copies * tags) ≤ _
+ have endActive := s.surviving_end dir e.2
+ have endHidden := s.shared_end hn e.2
+ have len := wire e
+ split
+ · split <;> omega
+ · omega
+
+private theorem descriptorBase_eq (s : Scratch) :
+ descriptorBase (Bool × Fin 4) s.directory = s.descriptor := by
+ change s.directory + 2 * Fintype.card (Bool × Fin 4) = s.directory + 16
+ simp
+
+private theorem source_eq (s : Scratch) :
+ ordinalBase Bool (Bool × Fin 4) s.directory = s.source := by
+ rw [ordinalBase, descriptorBase_eq]
+ rfl
+
+variable {K : Type} [_root_.Field K] {factor : ℝ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable {grid : F.grid.demands} {j : Fin 6} {p r k u t n limit : ℕ}
+variable (P : MapEntry.Program F grid j p r k)
+variable (demand : Bool → ℕ) (payload : Bool × Fin 4 → ℕ)
+variable (d : DemandBits demandSource demandTarget demand j)
+variable (x : MotifSelector.Half supply (fun e ↦ Fin (payload e + u * F.selectorBits) → Bool) j)
+variable (s : Scratch) (ord : ℕ) (layout : Bool) (cd : Bool → ℕ)
+
+/-- All numerical premises concern physical interval endpoints and the fixed
+word capacity. None refers to the map accepting or to its selector sequence. -/
+structure Fits : Prop where
+ capacity : Capacity F w n limit
+ copies : u ≤ n
+ ordinal : ord < s.motifs
+ ab : demand false ≤ s.stride
+ cd : ∀ dir, cd dir + demand true ≤ s.hidden
+ supply : ∀ e, payload e + u * F.selectorBits ≤ s.stride
+ histogram : s.hist + t ≤ s.directory
+ room : s.target u + u ≤ limit
+
+variable (ok : Fits (w := w) (n := n) (limit := limit) (u := u) (t := t)
+ F demand payload s ord cd)
+
+/-- The workspace handed to the fixed map-call program on the selected term. -/
+noncomputable def workspace : MapEntry.Program.Workspace P demand payload d x t w :=
+ scratchWorkspace P demand payload (s.fieldBase ord j layout cd) d x ok.capacity ok.copies
+ (fun f ↦ s.rawEnd ord ok.ordinal j layout cd demand payload F.selectorBits u
+ ok.ab ok.cd ok.supply f) ok.histogram (copies := u) le_rfl
+ (by simpa only [scratchEnd, source_eq, Scratch.target] using ok.room)
+
+local notation "XW" => workspace F P demand payload d x s ord layout cd ok
+
+theorem workspace_cells (f : Endpoint) : (XW).base f = s.fieldBase ord j layout cd f := rfl
+
+theorem workspace_source : (XW).source = s.source := source_eq s
+
+theorem workspace_target : (XW).target = s.target u :=
+ congrArg (· + u) (source_eq s)
+
+include ok in
+theorem workspace_descriptor_fit : s.descriptor + Fintype.card Arg ≤ 2 ^ w := by
+ have room := ok.room.trans_lt ok.capacity.room
+ unfold Scratch.target Scratch.source at room
+ omega
+
+variable {F}
+variable {z : F.grid.demands} (A : MapEntryTable.Allocation F z j r k)
+variable (loc : A.Address → Fin p)
+local notation "HW" => workspace F (A.program loc) demand payload d x s ord layout cd ok
+
+/-- Any positive input bit precedes every private descriptor and port-directory
+cell, including on maps with no demand at the given party. -/
+theorem separated (f : Endpoint) (i : Fin (rawWidth demand payload F.selectorBits u f)) :
+ MapArgumentWriter.separated A loc (HW) (s.descriptor : Word w)
+ ((s.fieldBase ord j layout cd f + i.val : ℕ) : Word w) := by
+ have h := s.rawEnd ord ok.ordinal j layout cd demand payload F.selectorBits u
+ ok.ab ok.cd ok.supply f
+ have small : s.fieldBase ord j layout cd f + i.val < s.directory := by have := i.isLt; omega
+ have space := ok.room.trans_lt ok.capacity.room
+ unfold Scratch.target Scratch.source Scratch.descriptor at space
+ have raw : ((s.fieldBase ord j layout cd f + i.val : ℕ) : Word w).val =
+ s.fieldBase ord j layout cd f + i.val := Nat.mod_eq_of_lt (by omega)
+ have desc : (s.descriptor : Word w).val = s.descriptor := Nat.mod_eq_of_lt (by
+ unfold Scratch.descriptor; omega)
+ refine ⟨Or.inl (by rw [raw, desc]; unfold Scratch.descriptor; omega), ?_⟩
+ intro a eqn
+ have len := MapPortAgreement.ports_length_le supply j A.edgeOrder
+ have card : 2 * Fintype.card (Bool × Fin 4) = 16 := by simp
+ rw [card] at len
+ have fit : s.directory + a.val < 2 ^ w := by have := a.isLt.trans_le len; omega
+ have val := congrArg Fin.val eqn
+ change _ = ((s.directory : Word w) + (a.val : Word w)).val at val
+ rw [← Nat.cast_add, show ((s.directory + a.val : ℕ) : Word w).val = _ from
+ Nat.mod_eq_of_lt fit, raw] at val
+ omega
+
+end PairSimulation.ShrinkCallFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCanonicalFieldSupport.lean b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalFieldSupport.lean
new file mode 100644
index 0000000000..fc6f7f6e2c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalFieldSupport.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.PairShrinkVisitFootprint
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+import OAI.Computability.VPVNP.PairShrinkSiteRouteBounds
+import OAI.Computability.VPVNP.PairShrinkSiteHiddenFootprint
+import OAI.Computability.VPVNP.PairShrinkHiddenNoWrites
+import OAI.Computability.VPVNP.PairShrinkHiddenSetupNoWrites
+
+/-!
+# External memory of a canonical shrinking visit
+
+The locator and child reader enter the packed row. All remaining reads come
+from that row's old level, stored term directory, hidden fields, and selected
+matrix operands. The parent decoder and the scratch and histogram updates
+take place in private memory. A returned visit therefore preserves external
+memory on its entire choice stream, independently of later visits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM DFS Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots SourceTransport
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows ResidentMapLoop.Exact
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g w n t : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : MapResidentRows.Site X}
+ (site : CanonicalSite B i X sel v w n t) (ord : B.Entry → Fin t)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+
+set_option quotPrecheck false
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "D" => BlockProgram.layout B site.workspace.val site.positions site.blocks
+local notation "childLoad" => selectedChildSetup site.publicData site.mem site.levels site.passIndex
+ S.steps i.val (a i)
+local notation "hiddenLoad" => physicalHiddenSetup B.shrink.selectorBits (hiddenStride i)
+ site.level.val site.mem
+local notation "mapLoad" => mapStartSetup site.mem site.level (Fin.val (siteIndex X v) : Word w)
+local notation "seed" => ShrinkHiddenSlots.rows X side widths v site.seed
+
+variable (H node : Word w) (saved : Scratch w n) (bits : List Bool)
+ (job : VisitPath w n) (tail : List Bool) (room : H.val + 31 < 2 ^ w)
+ (beforeHeader : endAddress (BlockProgram.layout B site.workspace.val site.positions
+ site.blocks) ≤ H.val)
+ (levelEq : site.level = (levelStart (BlockProgram.layout B site.workspace.val site.positions
+ site.blocks) site.cur : Word w))
+ (payload : CompiledResident.ShrinkPayload B site.workspace site.positions site.blocks n
+ site.cur i X sel site.mem)
+ (args : site.hiddenArgs = PackedHidden.arguments B i X sel site.workspace site.positions
+ site.blocks site.cur n (TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)) v)
+ (area : site.source.InLevel (BlockProgram.layout B site.workspace.val site.positions
+ site.blocks) site.cur)
+ (beforeNext : levelStart (BlockProgram.layout B site.workspace.val site.positions site.blocks)
+ (site.cur + 1) ≤ H.val)
+ (published : MapResidentInputs.Published site.mem site.level
+ ((ShrinkResidentLayout.layout X site.source.first).params (a i) true w 3)
+ ((ShrinkResidentLayout.layout X site.source.first).params (a i) true w 5) site.term 10)
+
+local notation "domain" => TerminalLink.workerCell H
+variable (locator : TraceSupport (TerminalLink.workerCell H)
+ ((selectedChildSetup site.publicData site.mem site.levels site.passIndex S.steps i.val
+ (a i)).trace node saved))
+ (child : ∀ out rest, ChildArguments.reader
+ (TerminalLayout.privateRegions (slotDegree S) n site.rowEnd (Fintype.card B.Entry)).arguments
+ site.incidence site.mem site.older B.recordLimit site.descriptor node
+ ((selectedChildSetup site.publicData site.mem site.levels site.passIndex S.steps i.val
+ (a i)).updated node saved) bits = some (out, rest) →
+ TraceSupport (TerminalLink.workerCell H) out.trace)
+
+/-- A successful hidden-field parse emits only reads and private events. -/
+theorem hiddenRead_noWrites {n w : ℕ} {a : Args w} {m : Memory w} {shape : List Row}
+ {node : Word w} {s : Scratch w n} {tape rest : List Bool} {out : Outcome w n (List Row)}
+ (hit : hiddenReader a m shape node s tape = some (out, rest)) :
+ Writes (fun _ ↦ False) out.trace := by
+ rw [(ShrinkNodeCost.hidden_trace a m shape node s tape rest out hit).1]
+ exact ShrinkHiddenGuess.events_noWrites a m out.value
+
+attribute [local irreducible] BlockProgram.layout Compression.ShrinkEnergy.chosenLayout
+ TerminalLayout.privateRegions
+ ResidentMapLoop.Exact.scan canonicalActions canonicalBank hiddenReader ShrinkHiddenSlots.rows
+
+set_option maxHeartbeats 1600000 in
+-- Identify the typed old and absorbed fields used by the actual selected row bank.
+include room beforeHeader levelEq payload args area beforeNext published locator child in
+/-- Read and write footprints of a returned raw visit with its parent fixed. -/
+theorem canonicalFamily_support_of_maps (parent : (Y).network.Half v)
+ (bank : ∀ xs hs s trace final, ResidentMapLoop.Exact.scan node
+ (canonicalActions site ord f hf parent xs hs) s = some (trace, final) →
+ TraceSupport (domain) trace)
+ (hit : (canonicalFamily site ord f hf parent).read node saved bits = some (job, tail)) :
+ TraceSupport (domain) job.trace := by
+ unfold canonicalFamily at hit
+ refine visit_footprint (n := n) (X := X) (regions).arguments site.incidence site.mem site.older
+ B.recordLimit site.descriptor (fun _ ↦ site.hiddenArgs) (fun _ ↦ (seed))
+ (canonicalActions site ord f hf parent) (childLoad) (fun _ ↦ (hiddenLoad))
+ (fun _ _ ↦ (mapLoad)) node (domain) saved bits tail job locator child
+ (fun _ s ↦ ⟨site.hiddenSetup_reads H room beforeHeader levelEq node s,
+ physicalHiddenSetup_noWrites B.shrink.selectorBits (hiddenStride i) site.level.val
+ site.mem node s⟩) ?_ ?_ bank hit
+ · intro _ s b out rest read
+ have hidden := CanonicalSite.hiddenReader_reads (g := g) (X := X) (sel := sel) site H
+ room beforeHeader payload args (node := node) (saved := s) (bs := b) (tail := rest)
+ (out := out) read
+ exact ⟨hidden, hiddenRead_noWrites (a := site.hiddenArgs) (m := site.mem) (shape := (seed))
+ (node := node) (s := s) (tape := b) (rest := rest) (out := out) read⟩
+ · intro _ _ s
+ exact ⟨ShrinkSiteBank.mapStart_worker (g := g) (X := X) (L := D) (cur := site.cur)
+ B i site.source v H area beforeNext room published,
+ mapStartSetup_noWrites site.mem site.level ((siteIndex X v).val : Word w) node s⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCanonicalFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalFootprint.lean
new file mode 100644
index 0000000000..845c58501f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalFootprint.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalFieldSupport
+import OAI.Computability.VPVNP.PairShrinkSiteFootprint
+
+/-!
+# External reads of the shrinking vertex interpreter
+
+For each parent assignment, the canonical parser reads the physical resident
+matrix rows in their stored order. Decoding the parent preserves the same
+worker read domain and external memory for every successful visit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM DFS Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots SourceTransport
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows ResidentMapLoop.Exact
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g w n t : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : MapResidentRows.Site X}
+ (site : CanonicalSite B i X sel v w n t) (ord : B.Entry → Fin t)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+
+private noncomputable local instance canonicalFootBase : DecidableEq X.Base := Classical.decEq _
+set_option quotPrecheck false
+local notation "side" => selectedLayout X B.shrink sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "Old" => Placed (X.packingData.shrinkPlace side ∘ X.packingInputIso.site.symm)
+ X.network.Half v
+
+variable (H node : Word w) (saved : Scratch w n) (bits : List Bool)
+ (job : VisitPath w n) (tail : List Bool) (room : H.val + 31 < 2 ^ w)
+ (beforeHeader : endAddress (BlockProgram.layout B site.workspace.val site.positions
+ site.blocks) ≤ H.val)
+ (levelEq : site.level = (levelStart (BlockProgram.layout B site.workspace.val site.positions
+ site.blocks) site.cur : Word w))
+ (payload : CompiledResident.ShrinkPayload B site.workspace site.positions site.blocks n
+ site.cur i X sel site.mem)
+ (args : site.hiddenArgs = PackedHidden.arguments B i X sel site.workspace site.positions
+ site.blocks site.cur n (TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)) v)
+ (area : site.source.InLevel (BlockProgram.layout B site.workspace.val site.positions
+ site.blocks) site.cur)
+ (beforeNext : levelStart (BlockProgram.layout B site.workspace.val site.positions site.blocks)
+ (site.cur + 1) ≤ H.val)
+ (published : MapResidentInputs.Published site.mem site.level
+ ((ShrinkResidentLayout.layout X site.source.first).params (a i) true w 3)
+ ((ShrinkResidentLayout.layout X site.source.first).params (a i) true w 5) site.term 10)
+
+local notation "domain" => TerminalLink.workerCell H
+variable (locator : TraceSupport (TerminalLink.workerCell H)
+ ((selectedChildSetup site.publicData site.mem site.levels site.passIndex S.steps i.val
+ (a i)).trace node saved))
+ (child : ∀ out rest, ChildArguments.reader
+ (TerminalLayout.privateRegions (slotDegree S) n site.rowEnd (Fintype.card B.Entry)).arguments
+ site.incidence site.mem site.older B.recordLimit site.descriptor node
+ ((selectedChildSetup site.publicData site.mem site.levels site.passIndex S.steps i.val
+ (a i)).updated node saved) bits = some (out, rest) →
+ TraceSupport (TerminalLink.workerCell H) out.trace)
+
+attribute [local irreducible] BlockProgram.layout Compression.ShrinkEnergy.chosenLayout
+ TerminalLayout.privateRegions ResidentMapLoop.Exact.scan canonicalBank MapWitness.actions
+
+set_option maxHeartbeats 1600000 in
+-- Identify the typed old and absorbed fields used by the actual selected row bank.
+include room beforeHeader levelEq payload args area beforeNext published locator child in
+/-- Read and write footprints of a returned raw visit with its parent fixed. -/
+theorem canonicalFamily_support (parent : (Y).network.Half v)
+ (sources : ∀ (old : Old) q, ShrinkSiteBank.RowSources B i X sel site.workspace site.positions
+ site.blocks site.cur site.bounds n site.rowEnd site.older site.later v old parent
+ site.mem H q)
+ (hit : (canonicalFamily site ord f hf parent).read node saved bits = some (job, tail)) :
+ TraceSupport (domain) job.trace := by
+ refine canonicalFamily_support_of_maps site ord f hf H node saved bits job tail room beforeHeader
+ levelEq payload args area beforeNext published locator child parent ?_ hit
+ intro xs hs s trace final scan
+ dsimp only [canonicalActions, typedActions] at scan
+ exact ShrinkSiteBank.scan_footprint site ord parent _ _ H room levelEq area beforeNext
+ (sources _) node s scan
+
+set_option maxHeartbeats 1300000 in
+-- Recover the stored parent and specialize the fixed-parent parser without altering its trace.
+include room beforeHeader levelEq payload args area beforeNext published locator child in
+/-- Every successful shrinking visit reads only the worker's cells and returns the
+same external memory, before examining any future choice bits. -/
+theorem canonicalParent_worker
+ (sources : ∀ (parent : (Y).network.Half v) (old : Old) q,
+ ShrinkSiteBank.RowSources B i X sel site.workspace site.positions site.blocks site.cur
+ site.bounds n site.rowEnd site.older site.later v old parent site.mem H q)
+ (hit : (canonicalParent site ord f hf).read node saved bits = some (job, tail)) :
+ Reads (domain) job.trace ∧ after site.mem job.trace = site.mem := by
+ unfold canonicalParent parentParser at hit
+ obtain ⟨parent, _, family⟩ := Option.bind_eq_some_iff.mp hit
+ have support := canonicalFamily_support site ord f hf H node saved bits job tail room
+ beforeHeader levelEq payload args area beforeNext published locator child parent
+ (sources parent) family
+ exact ⟨support.1, support.memory site.mem⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCanonicalJob.lean b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalJob.lean
new file mode 100644
index 0000000000..09f22a2762
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalJob.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.PairShrinkPhysicalSourceBounds
+import OAI.Computability.VPVNP.PairShrinkCallABI
+import OAI.Computability.VPVNP.PairShrinkPartyOutputHeader
+
+/-!
+# The resident job at a physical shrinking substep
+
+The old and new DFS layers determine the actual child and parent nodes.
+The private arena and hidden scratch come from the terminal geometry. The
+producing substep determines the three external table bases for term records,
+AB intervals and surviving intervals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCanonicalJob
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords
+open CompressorRecords.DescriptorSpace CompressorRecords.ShrinkBlockInputs
+open CompressorRecords.ShrinkSlots CompressorRecords.ShrinkSliceSweep
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} {δ : ℝ} (X : State (a i) (packingLaneBits (a i) g))
+variable (ready : Ready (2 ^ a i) (Shrink.colors (a i)) (2 ^ b i) δ)
+variable (sel : SelectedScore.Selection B X) (m : X.packingData.Motif) (party : Fin 6)
+variable (base : Word w) (positions blocks cur : ℕ)
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "cut" => tableBase L cur (0 : Fin 6)
+local notation "first" => tableBase L cur (1 : Fin 6)
+local notation "width" => tableBase L cur (2 : Fin 6)
+local notation "slots" => tableBase L cur (3 : Fin 6)
+local notation "term" => ShrinkInput.termHead (w := w) X cut
+local notation "stride" => (10 : Word w)
+local notation "shape" => levelShape (b := b i) X
+local notation "role" => SelectedArena.roleBase X term stride
+local notation "heads" => ShrinkOutput.heads shape role slots
+local notation "Z" => ShrinkInput.plan X cut
+local notation "absHead" => ShrinkBundlePlan.absoluteHead Z w
+local notation "T" => packedIncidence L w cur (DemandRAM.oldCount X)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "Y" => X.shrinkNext B.shrink ready sel
+local notation "site" => X.packingData.shrinkPartySite side m party
+local notation "ns" => ShrinkBundlePlan.thickCount (a i)
+local notation "nt" => ShrinkBundlePlan.cap (a i)
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+local notation "split" => ShrinkOutput.splitBank (b := b i) X B.shrink sel term
+ (Fin.val stride) role width
+local notation "bank" => selectedAllocation B.shrink X sel term 10 width
+ (SlotLevel.Shape.subdivisions shape)
+
+variable (sp : ShrinkResidentSources.Bounds B i X base positions blocks cur)
+/-- Classical equality on input base vertices for the selected party's canonical allocation and
+old-site ordinals. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+include sp in
+private theorem rank_room : (Z).stop < 2 ^ w := by
+ have h := (ShrinkInput.range_bounds X cut).2.2.2
+ exact h.trans_lt ((Nat.le_add_right ..).trans_lt
+ ((Nat.le_add_right ..).trans_lt sp.termRoom))
+
+/-- The popped parent address is the row of this exact party in the new layer. -/
+noncomputable def job (n rowEnd older later : ℕ) (old : ShrinkCallDemandCells.Old X side m party)
+ (parent : (Y).network.Half site) : ShrinkPartyNative.Job X B.shrink ready sel m party w :=
+ let G := TerminalLayout.privateRegions (slotDegree S) n rowEnd (Fintype.card B.Entry)
+ let geom := ShrinkCallHeader.geometry X T cut (rank_room B i X base positions blocks cur sp)
+ ⟨old, parent, G.arguments,
+ later + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal (Y) site,
+ ShrinkCallHeader.scratch X (ShrinkCallABI.hiddenBase G n) (n ^ 2) G.histBase,
+ older, B.recordLimit + 2, first, term, 10, width, geom.arcFit, geom.bucketFit⟩
+
+/-- Runtime fit and the identity of the physical interval bank recorded by
+the producing slot sweep. -/
+structure Geometry : Prop where
+ rank : (Z).stop < 2 ^ w
+ ab : ShrinkABSliceTable.Layout (ShrinkInput.thickBank X T cut) (ShrinkInput.piecesBank X T cut)
+ (Z).B ns nt first
+ split_eq : split = bank
+ allocation : (bank).Fits
+ absolute : (absHead).val + idx < 2 ^ w
+ slot : finish shape heads < 2 ^ w
+ degree : 2 ^ b i < 2 ^ w
+ two : 2 < 2 ^ w
+ lanes : 2 ^ g < 2 ^ w
+ capacity : Fintype.card (Y).Base * 2 ^ g * 2 ^ b i ≤ 2 ^ w
+ termBefore : ShrinkInput.termEnd X cut 10 ≤ endAddress L
+ absoluteBefore : (absHead).val + ShrinkTermInputs.motifCount X ≤ endAddress L
+ intervalsBefore : (bank).last ≤ endAddress L
+
+include sp in
+/-- Derive every fit from the physical source extents. In particular the
+`max` in the producing sweep's allocator equals the address in table two. -/
+theorem geometry : Geometry B i X ready sel m base positions blocks cur := by
+ have nextEnd : levelStart L (cur + 1) ≤ endAddress L := levelStart_mono L sp.nextLive.le
+ have table (j : Fin 6) : tableBase L cur j ≤ endAddress L :=
+ (Nat.le_add_right ..).trans ((tableEnd_le_nextLevel L cur j).trans nextEnd)
+ have headerEnd : levelStart L cur + 66 ≤ endAddress L := by
+ apply le_trans _ nextEnd
+ change levelStart L cur + levelHeaderWords L ≤ levelStart L (cur + 1)
+ simp only [levelStart, Nat.succ_mul, levelWords]
+ omega
+ have ten : 10 < 2 ^ w := by have := sp.room; omega
+ have stepVal : (10 : Word w).val = 10 := Nat.mod_eq_of_lt ten
+ have termBefore := sp.termBefore.trans (table 1)
+ have ab := BlockSlices.ab_layout i X T cut sp.termRoom sp.fresh
+ (sp.widthAfter.trans_lt ((table 2).trans_lt sp.room))
+ have widthAfter := (Nat.le_add_right first _).trans sp.widthAfter
+ have low := sp.selectedBefore.trans widthAfter
+ have weq := ShrinkOutput.width_at_eq i X term stride width low
+ have bankEq : split = bank := by
+ unfold ShrinkOutput.splitBank
+ rw [weq, stepVal]
+ have alloc := ShrinkOutput.fits (b := b i) X B.shrink sel term (Fin.val stride) role width
+ ready stepVal.ge sp.packedRoom
+ have last : (bank).last ≤ endAddress L := by
+ rw [← bankEq, ShrinkOutput.splitBank_last]
+ exact sp.slotAfter.trans (table 3)
+ have rank := rank_room B i X base positions blocks cur sp
+ have lane := (Z).scalarFits Fintype.card_pos rank
+ have absEarly : (absHead).val + ShrinkTermInputs.motifCount X ≤ (Z).ranks := by
+ rw [ShrinkTermSelection.motifCount_eq X]
+ change ((Z).gathered + (Z).B * (Z).Q) % 2 ^ w + (Z).B * (Z).Q ≤ (Z).gathered + _
+ have h := Nat.add_le_add_right (Nat.mod_le ((Z).gathered + (Z).B * (Z).Q) (2 ^ w))
+ ((Z).B * (Z).Q)
+ exact h.trans_eq (by change _ = (Z).gathered + (2 * (Z).B) * (Z).Q; ring)
+ have rankBefore : (Z).ranks ≤ endAddress L :=
+ (Nat.le_add_right ..).trans ((ShrinkInput.range_bounds X cut).2.2.2.trans
+ (sp.fresh.trans (table 1)))
+ have absBefore := absEarly.trans rankBefore
+ have ordinal : idx < ShrinkTermInputs.motifCount X := ((ShrinkMotifOrder.entries X).symm m).isLt
+ let next : Fin (L).levels := ⟨cur + 1, sp.nextLive⟩
+ have nextFit := packed_incidence_room L sp.room next sp.nextCapacity
+ have cap : Fintype.card (Y).Base * 2 ^ g * 2 ^ b i < 2 ^ w := by
+ rw [(next_counts X B.shrink ready sel).2]
+ omega
+ have degreeFit := (Nat.le_mul_of_pos_left (2 ^ b i)
+ (Nat.mul_pos (Fintype.card_pos (α := (Y).Base)) (Nat.two_pow_pos g))).trans_lt cap
+ exact ⟨rank, ab, bankEq, bankEq ▸ alloc, (Nat.add_lt_add_left ordinal _).trans
+ (absBefore.trans_lt sp.room), sp.slotRoom, degreeFit, by omega, lane.2.2.2.2.1, cap.le,
+ termBefore, absBefore, last⟩
+
+end PairSimulation.ShrinkCanonicalJob
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCanonicalPacketBounds.lean b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalPacketBounds.lean
new file mode 100644
index 0000000000..0662c8b02d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalPacketBounds.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalJob
+import OAI.Computability.VPVNP.PairShrinkSelectedCapacity
+
+/-!
+# Child and parent packet intervals of a canonical resident shrinking job
+
+Every selected old or new node before the row end has a private argument
+interval ending before the histogram. Its packed half-wire bits fit the
+argument stride. The histogram, cache and stacks all precede staging.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCanonicalJob
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords NodeArguments
+open ShrinkCallCapacity ShrinkCallFields
+
+variable {a g w endAddr n : ℕ} {U : Type*}
+variable (Z : State a g) (site : Z.network.Site) (parent : Z.network.Half site)
+variable (oldNode : U → ℕ) (node degree rowEnd labels : ℕ) (s : Scratch)
+local notation "G" => TerminalLayout.privateRegions degree n rowEnd labels
+local notation "ports" => Fintype.card LeafStartup.ScalarPort
+local notation "parentPacket" => Packet.mk node (packed Z site parent)
+
+/-- Numerical packet premises of the gather at its published node addresses.
+The stack boundary may be any address up to the live length. -/
+theorem packet_bounds (stack : endAddr ≤ n) (children : ∀ u, oldNode u < rowEnd)
+ (newNode : node < rowEnd) (degreeBound : 2 ^ a ≤ degree) (width : Z.maxWireWidth ≤ n)
+ (wordFit : mapBase G ports n < 2 ^ w) (hidden : mapBase G ports n = s.hidden) :
+ (∀ u, (G).arguments.base (oldNode u) + (G).arguments.stride ≤ s.staging) ∧
+ (parentPacket).Fits (G).arguments w endAddr ∧
+ (G).arguments.base node + (parentPacket).bits.length ≤ s.staging := by
+ have hist : (G).histBase ≤ mapBase G ports n :=
+ (Nat.le_add_right ..).trans (histogram_before G ports n)
+ have staging : mapBase G ports n ≤ s.staging := hidden ▸ Nat.le_add_right ..
+ have parentSize : (parentPacket).bits.length ≤ (G).arguments.stride :=
+ (packed_length_le Z site parent).trans
+ ((Nat.mul_le_mul (Nat.mul_le_mul_left 2 degreeBound) width).trans (Nat.le_succ _))
+ have parentBefore : (G).arguments.base node + (parentPacket).bits.length ≤ mapBase G ports n :=
+ (Nat.add_le_add_left parentSize _).trans (((G).node_before newNode).trans hist)
+ exact ⟨fun u ↦ ((G).node_before (children u)).trans (hist.trans staging),
+ ⟨stack.trans (Nat.le_add_right ..), parentSize, parentBefore.trans wordFit.le⟩,
+ parentBefore.trans staging⟩
+
+end PairSimulation.ShrinkCanonicalJob
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCanonicalReadAreas.lean b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalReadAreas.lean
new file mode 100644
index 0000000000..84083e572d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalReadAreas.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalJob
+import OAI.Computability.VPVNP.PairShrinkPartyReadAreas
+import OAI.Computability.VPVNP.PairShrinkPartyReadBounds
+import OAI.Computability.VPVNP.PairShrinkCallABIReads
+
+/-!
+# Read bounds of the canonical shrinking job
+
+The old level and its successor lie below the end of the descriptor. Both
+native gathers and the selected map writer therefore read below the terminal
+controller header. The old header's successor word identifies the next
+incidence bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCanonicalJob
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords
+open CompressorRecords.DescriptorSpace CompressorRecords.ShrinkBlockInputs
+open CompressorRecords.ShrinkSlots CompressorRecords.ShrinkSliceSweep
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} {δ : ℝ} (X : State (a i) (packingLaneBits (a i) g))
+variable (ready : Ready (2 ^ a i) (Shrink.colors (a i)) (2 ^ b i) δ)
+variable (sel : SelectedScore.Selection B X) (m : X.packingData.Motif) (party : Fin 6)
+variable (base : Word w) (positions blocks cur : ℕ)
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "cut" => tableBase L cur (0 : Fin 6)
+local notation "term" => ShrinkInput.termHead (w := w) X cut
+local notation "shape" => levelShape (b := b i) X
+local notation "role" => SelectedArena.roleBase X term (10 : Word w)
+local notation "heads" => ShrinkOutput.heads shape role (tableBase L cur (3 : Fin 6))
+local notation "Z" => ShrinkInput.plan X cut
+local notation "absHead" => ShrinkBundlePlan.absoluteHead Z w
+local notation "T" => packedIncidence L w cur (DemandRAM.oldCount X)
+local notation "U" => packedIncidence L w (cur + 1) (actualCount shape)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "Y" => X.shrinkNext B.shrink ready sel
+local notation "site" => X.packingData.shrinkPartySite side m party
+local notation "level" => levelStart L cur
+local notation "next" => levelStart L (cur + 1)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+variable (sp : ShrinkResidentSources.Bounds B i X base positions blocks cur)
+variable (J : ShrinkPartyNative.Job X B.shrink ready sel m party w)
+local notation "allocated" => selectedAllocation B.shrink X sel term 10
+ (tableBase L cur (2 : Fin 6))
+ (SlotLevel.Shape.subdivisions shape)
+
+include sp in
+/-- All concrete array ends required by the AB and surviving scans and the
+map's term descriptors, expressed at the actual terminal header. -/
+theorem read_areas (firstBank : J.first = tableBase L cur (1 : Fin 6))
+ (intervalBank : J.allocation = allocated) (H : Word w) (mem : Memory w)
+ (beforeHeader : endAddress L ≤ H.val)
+ (successor : mem (level + 40) = (next : Word w)) :
+ J.ABAreas (level : Word w) T cut H.val ∧
+ J.SupplyAreas (level : Word w) absHead heads U next H.val mem ∧
+ ShrinkInput.termEnd X cut 10 ≤ H.val := by
+ have geo := geometry B i X ready sel m base positions blocks cur sp
+ have nextLe := (levelStart_mono L sp.nextLive.le).trans beforeHeader
+ have oldLe := (levelStart_mono L (Nat.le_succ cur)).trans nextLe
+ have oldWord : (level : Word w).val = level := Nat.mod_eq_of_lt (oldLe.trans_lt H.isLt)
+ have beyond : levelStart L ((cur + 1) + 1) ≤ H.val :=
+ (levelStart_mono L sp.nextLive).trans beforeHeader
+ have newInc : incidenceStart L (cur + 1) + 6 * slotCapacity L ≤ H.val := by
+ have h := tableEnd_le_nextLevel L (cur + 1) (0 : Fin 6)
+ change (incidenceStart L (cur + 1) + 6 * slotCapacity L + 0 * tableWords L) +
+ tableWords L ≤ _ at h
+ omega
+ have head : next + 66 = incidenceStart L (cur + 1) := rfl
+ have count := (next_counts X B.shrink ready sel).2
+ have col (j : Fin 6) : ((U).column j).val + Fintype.card (Y).Base *
+ 2 ^ g * 2 ^ b i ≤ H.val := by
+ rw [count, packed_column]
+ change (incidenceStart L (cur + 1) + j.val * actualCount shape) % 2 ^ w + _ ≤ _
+ have bound := Nat.mul_le_mul_right (actualCount shape) j.isLt
+ rw [Nat.succ_mul] at bound
+ have capacity := Nat.mul_le_mul_left 6 sp.nextCapacity
+ exact (Nat.add_le_add_right (Nat.mod_le ..) _).trans (by omega)
+ have inv : SlotLevel.targetsHead shape heads ≤ finish shape heads := by
+ unfold finish widthHead inHead outHead inverseBaseHead SlotLevel.stopAddress
+ SlotLevel.shiftsHead
+ omega
+ refine ⟨sp.party_abAreas J firstBank nextLe, ?_, geo.termBefore.trans beforeHeader⟩
+ exact ⟨by simpa only [oldWord] using successor, by omega, geo.absoluteBefore.trans beforeHeader,
+ inv.trans (sp.slotEnd.trans nextLe), col 4, col 5,
+ intervalBank.symm ▸ geo.intervalsBefore.trans beforeHeader⟩
+
+end PairSimulation.ShrinkCanonicalJob
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCanonicalSite.lean b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalSite.lean
new file mode 100644
index 0000000000..3dbd7b9217
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalSite.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalWorkspaceFit
+import OAI.Computability.VPVNP.PairShrinkRoleChild
+import OAI.Computability.VPVNP.PairShrinkSiteBank
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherSource
+
+/-! # Physical directories and workspace bounds at a selected shrinking site -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+open ShrinkMapImage.Registers MapResidentRows
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (i : Fin S.steps) {g : ℕ} (X : State (a i) (packingLaneBits (a i) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "Hidden" => Placed (X.packingData.shrinkInternalOwner side)
+ (internalLabel widths side) v
+
+/-- Addresses, field directories and workspace bounds for one selected site. -/
+structure CanonicalSite (w n t : ℕ) where
+ /-- Base word address of the compressor's descriptor workspace. -/
+ workspace : Word w
+ /-- Number of processor positions used when laying out the compressor's workspace. -/
+ positions : ℕ
+ /-- Number of complete scheduled blocks in the compressor's workspace layout. -/
+ blocks : ℕ
+ /-- Chronological pass index used to locate the producing level and its tables. -/
+ cur : ℕ
+ bounds : ShrinkResidentSources.Bounds B i X workspace positions blocks cur
+ /-- Exclusive end address of the selected traversal's node rows. -/
+ rowEnd : ℕ
+ /-- Base address of the input layer's node rows. -/
+ older : ℕ
+ /-- Base address of the output layer's node rows. -/
+ later : ℕ
+ /-- Upper address bound on the canonical jobs' private workspaces. -/
+ limit : ℕ
+ fits : ∀ m, canonicalFits B i X sel (w := w) t n rowEnd older limit m
+ /-- Physical memory read by the vertex handler at this site. -/
+ mem : Memory w
+ /-- Word address of the header for the producing compressor level. -/
+ level : Word w
+ /-- Word address of the shrinking term records for the producing level. -/
+ term : Word w
+ /-- Published map directory and term data read at this site from the specified memory. -/
+ source : MapRowSource X sel side mem level term
+ width : MapConstants.widthThreshold B.shrink ≤ w
+ /-- The eleven public operand words of the terminal vertex program. -/
+ publicData : Fin 11 → Word w
+ /-- Number of passes in the selected chronological execution. -/
+ levels : ℕ
+ /-- Pass ordinal supplied to the vertex handler for this row. -/
+ passIndex : ℕ
+ /-- Directory of the packed incidence columns used to recover the old wire endpoints. -/
+ incidence : IncidenceDirectory w
+ /-- Child-argument descriptor selected by the popped node address. -/
+ descriptor : Word w → ChildArguments.Descriptor w X
+ /-- Addresses and row parameters for guessing the hidden fields at this site. -/
+ hiddenArgs : Args w
+ /-- Initial assignment of the hidden fields placed at this site. -/
+ seed : Hidden
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkCanonicalWorkspaceFit.lean b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalWorkspaceFit.lean
new file mode 100644
index 0000000000..5aee921897
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkCanonicalWorkspaceFit.lean
@@ -0,0 +1,55 @@
+import OAI.Computability.VPVNP.PairShrinkCallABI
+import OAI.Computability.VPVNP.PairShrinkSelectedCapacity
+
+/-!
+# Workspace capacity at a scheduled shrinking motif
+
+The terminal row end determines the private argument arena and histogram.
+The hidden fields begin after the scalar stacks and use the square stride
+computed by the handoff. These are the addresses used by the canonical job
+for every party of the motif.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open Compression Compression.ShrinkMotif CompressorRecords CursorBounds MotifConversion
+open ShrinkCallCapacity ShrinkCallFields
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (i : Fin S.steps)
+variable {g : ℕ} (X : State (S.degreeExponent i.castSucc)
+ (packingLaneBits (S.degreeExponent i.castSucc) g)) (sel : X.ShrinkSelection B.shrink)
+
+open Classical in
+/-- Workspace capacity for the motif at the old level's published row base. -/
+noncomputable abbrev canonicalFits {w : ℕ} (t n rowEnd older limit : ℕ)
+ (m : X.packingData.Motif) : Prop :=
+ let R := TerminalLayout.privateRegions (slotDegree S) n rowEnd (Fintype.card B.Entry)
+ let demand := X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m
+ Fits (w := w) (n := n) (limit := limit) (u := repetitions B.shrink demand) (t := t)
+ B.shrink demand (sel m).val
+ (ShrinkCallHeader.scratch X (ShrinkCallABI.hiddenBase R n) (n ^ 2) R.histBase)
+ (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallHeader.cdBase X m R.arguments older (B.recordLimit + 2))
+
+/-- The selected level's capacity applies at the canonical row end. In
+particular this specializes the capacity supplied by
+`ShrinkCallCapacity.eventually_packed_occurrence` for the physical level. -/
+theorem canonicalFits_of_selected {b n firstRow rowWords older limit : ℕ}
+ (m : X.packingData.Motif)
+ (fit : SelectedFits X B sel m
+ (NativeFrame.regions (slotDegree S) n firstRow rowWords (Fintype.card B.Entry))
+ b n limit older (B.recordLimit + 2)) :
+ canonicalFits B i X sel (w := wordBits b n) (Fintype.card B.Entry) n
+ (firstRow + rowWords) older limit m := by
+ simpa only [canonicalFits, SelectedFits, pow_two, ShrinkCallABI.hiddenBase, mapBase,
+ TerminalLayout.privateRegions, NativeFrame.regions, NodeArguments.frameStride] using fit
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkChildDemandBudget.lean b/lean/OAI/Computability/VPVNP/PairShrinkChildDemandBudget.lean
new file mode 100644
index 0000000000..4bc0e459b3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkChildDemandBudget.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.CursorBranchCommunication
+import OAI.Computability.VPVNP.PairShrinkRoleChild
+import OAI.Computability.VPVNP.PairSimulationAssembly
+
+/-! # Bounds on the selected shrinking child arguments
+
+The shrinking reader enumerates the placement fiber at its output site.
+The pass's record bound limits the length of that enumeration, and each
+old site's two sets of half-wires contribute at most twice the old degree
+times the maximum wire width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.ChildArguments
+
+open Compression LocalHistory NodeArguments
+
+theorem demand_le {a g : ℕ} (X : State a g) (sites : List X.network.Site) :
+ demand X sites ≤ sites.length * (2 * 2 ^ a * X.maxWireWidth) := by
+ induction sites with
+ | nil => simp [demand]
+ | cons u us ih =>
+ have first : width X u ≤ 2 * 2 ^ a * X.maxWireWidth := by
+ rw [width, ChildSlots.length_all]
+ exact CursorNetwork.incidentBits_le X u
+ change width X u + demand X us ≤ (us.length + 1) * _
+ rw [Nat.add_mul, Nat.one_mul, Nat.add_comm (us.length * _)]
+ exact Nat.add_le_add first ih
+
+variable {K R : Type*} [Field K] [CommRing R] {S : BlockSchedule K}
+
+/-- The descriptor of the actual scheduled term fits the fixed record limit.
+Its input bit demand grows linearly with the current state's maximum wire width. -/
+theorem selected_budget (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+ (i : Fin S.steps) {g w : ℕ}
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink)
+ (v : (X.Base × BitWord (packingTagBits (2 ^ S.degreeExponent i.castSucc))) × BitWord g)
+ (desc : Descriptor w X)
+ (order : desc.sites = List.ofFn fun j =>
+ ((((shrinkPassReaders B f hf i rfl X).order sel).children v).entries j).val) :
+ desc.sites.length ≤ B.recordLimit ∧
+ demand X desc.sites ≤
+ (2 * 2 ^ S.degreeExponent i.castSucc * B.recordLimit) * X.maxWireWidth := by
+ classical
+ have card := Fintype.card_congr
+ (((shrinkPassReaders B f hf i rfl X).order sel).children v).entries
+ rw [Fintype.card_fin] at card
+ have records := (X.shrinkStatePass_bounded B.shrink (f ∘ Sum.inl)
+ ((B.solution_iff f).mp hf).1 (S.shrink i) sel).1 v
+ have factor := Finset.le_sup (f := fun j : Fin S.steps =>
+ State.shrinkHistoryFactor B.shrink (S.degreeExponent j.castSucc) (S.degreeExponent j.succ))
+ (Finset.mem_univ i)
+ have count : desc.sites.length ≤ B.recordLimit := by
+ rw [order, List.length_ofFn, card]
+ exact (Nat.le_add_left _ _).trans (records.trans (factor.trans
+ ((le_max_left ..).trans (le_max_right ..))))
+ refine ⟨count, (demand_le X desc.sites).trans ?_⟩
+ calc
+ _ ≤ B.recordLimit * (2 * 2 ^ S.degreeExponent i.castSucc * X.maxWireWidth) :=
+ Nat.mul_le_mul_right _ count
+ _ = _ := by ac_rfl
+
+end PairSimulation.ShrinkRole.ChildArguments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkChildWords.lean b/lean/OAI/Computability/VPVNP/PairShrinkChildWords.lean
new file mode 100644
index 0000000000..30055f8765
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkChildWords.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.PairShrinkJobOperands
+import OAI.Computability.VPVNP.PairShrinkRoleMapWitness
+
+/-!
+# Initializing the first resident map from the actual child scan
+
+The scanned child list is the fiber of the selected shrinking term. Its
+argument packets contain the independent outgoing and incoming bits of
+each old site, pulled into packing coordinates at their owning vertex.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel LocalHistory
+open BurstRAM NodeArguments DFS CompressorRecords CompressorRecords.ShrinkSlots
+
+variable {K : Type} {R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps)
+variable {g w endAddr : ℕ} (X : State (S.degreeExponent i.castSucc)
+ (packingLaneBits (S.degreeExponent i.castSucc) g)) (sel : X.ShrinkSelection B.shrink)
+private noncomputable local instance childBase : DecidableEq X.Base := Classical.decEq _
+local notation "l" => selectedLayout X B.shrink sel
+private noncomputable abbrev selectedTerm := NetworkKernel.Step.term (StatePass.step
+ (X.shrinkStatePass B.shrink (f ∘ Sum.inl) ((B.solution_iff f).mp hf).1 (S.shrink i))) sel
+
+variable (v : (X.Base × BitWord (packingTagBits (2 ^ S.degreeExponent i.castSucc))) × BitWord g)
+variable (x : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v)
+variable (J : Job X B.shrink (S.shrink i) sel q.1.1 q.1.2 w)
+
+set_option maxHeartbeats 1000000 in
+-- Pulling half-wire indices from the term's fiber reduces the selected placement.
+theorem Job.childWords_of_packets {L : Type} [Fintype L] {κ : L → R}
+ (r : TermParsers κ (selectedTerm B f hf i X sel))
+ (oldEq : J.old = Eq.rec (motive := fun u _ ↦ Placed (X.packingData.shrinkPlace l)
+ (X.packingData.oldWireNetwork X.packingWidth).Half u)
+ (ShrinkRole.MapWitness.placedOld B i X sel v x) q.2.symm)
+ (halfOrder : ∀ (u : X.network.Site) (z : X.network.Half u), r.halfBits u z = packed X u z)
+ (before : DFS.Scratch w endAddr) (priv : Word w → Word w)
+ (fit : ∀ packet ∈ r.childPackets J.nodes v x, packet.Fits J.arena w endAddr)
+ (nd : ((r.childPackets J.nodes v x).map Packet.node).Nodup)
+ (written : DFS.scratch endAddr priv =
+ writePackets J.arena (r.childPackets J.nodes v x) before) :
+ J.ChildWords priv endAddr := by
+ rcases q with ⟨⟨motif, party⟩, place⟩
+ change X.packingData.shrinkPartySite l motif party = v at place
+ subst v
+ intro site eqn u hu
+ let actual := X.packingInputIso.site u
+ have atChild : X.packingData.shrinkPartySite l motif party =
+ (selectedTerm B f hf i X sel).place actual := by
+ change _ = packedSiteEquiv ((X.packingData.placement l) (X.packingInputIso.site.symm
+ (X.packingInputIso.site u)))
+ rw [Equiv.symm_apply_apply, ← hu, eqn]
+ let packet := Packet.mk (J.nodes actual) (packed X actual (x actual atChild))
+ have present : packet ∈ r.childPackets J.nodes _ x := by
+ let ord := (r.order.children (X.packingData.shrinkPartySite l motif party)).entries
+ obtain ⟨j, hj⟩ := ord.surjective ⟨actual, atChild⟩
+ apply List.mem_ofFn.mpr
+ refine ⟨j, ?_⟩
+ change Packet.mk (J.nodes (ord j).val) (r.halfBits (ord j).val (x (ord j).val (ord j).prop))
+ = packet
+ rw [hj, halfOrder]
+ have stored := written ▸ writePackets_children J.arena _ before fit nd packet present
+ change (Packet.mk _ (packed X _ ((X.packingHalfEquiv u).symm
+ (J.old u _)))).Fits _ _ _ ∧ (Packet.mk _ (packed X _ ((X.packingHalfEquiv u).symm
+ (J.old u _)))).Stored _ _
+ rw [oldEq]
+ change (Packet.mk _ (packed X _ ((X.packingHalfEquiv u).symm
+ (X.packingHalfEquiv u (x actual atChild))))).Fits _ _ _ ∧
+ (Packet.mk _ (packed X _ ((X.packingHalfEquiv u).symm
+ (X.packingHalfEquiv u (x actual atChild))))).Stored _ _
+ rw [Equiv.symm_apply_apply]
+ exact ⟨fit packet present, stored⟩
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkDescriptorReads.lean b/lean/OAI/Computability/VPVNP/PairShrinkDescriptorReads.lean
new file mode 100644
index 0000000000..6f37694e4d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkDescriptorReads.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PairShrinkCallFields
+import OAI.Computability.VPVNP.CompressorFormulaFootprint
+
+/-!
+# External cells used to form a shrinking map descriptor
+
+The selected motif ordinal addresses two demand cells and ten term cells. At each
+party the remaining descriptor entries compute private workspace pointers or use the
+direct CD pointer for an incident endpoint. This proof checks the nested external
+loads in those expressions before the descriptor is written.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkDescriptorReads
+
+open BurstRAM CompressorRecords CompressorRecords.PhaseRecipe Compression ShrinkCallFields
+open scoped Fin.CommRing
+
+variable {w a g : ℕ}
+
+private theorem add_val_le (base : Word w) (n : ℕ) :
+ (base + (n : Word w)).val ≤ base.val + n := by
+ change (base.val + n % 2 ^ w) % 2 ^ w ≤ base.val + n
+ exact (Nat.mod_le ..).trans (Nat.add_le_add_left (Nat.mod_le ..) _)
+
+variable {X : State a (packingLaneBits a g)} {m : X.packingData.Motif}
+ {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w}
+ {I : ShrinkCallFields.Inputs} {s : Scratch} {term dense : Word w}
+ {step : ℕ} {layout : Bool} {cd : Bool → ℕ}
+
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+local notation "ev" => Expr.eval pub state mem
+
+/-- Bounds on the actual level, demand pair and term row suffice for all descriptor
+loads. The two CD endpoints can have independently computed addresses. -/
+theorem fields (stored : Stored pub state mem X m I s term dense step layout cd) (H : ℕ)
+ (levelRead : I.level.ReadsFrom (· < H) pub state mem)
+ (levelRoom : (ev I.level).val + 59 < H)
+ (ordinalRead : I.ordinal.ReadsFrom (· < H) pub state mem)
+ (hiddenRead : I.hidden.ReadsFrom (· < H) pub state mem)
+ (strideRead : I.stride.ReadsFrom (· < H) pub state mem)
+ (motifsRead : I.motifs.ReadsFrom (· < H) pub state mem)
+ (histRead : I.hist.ReadsFrom (· < H) pub state mem)
+ (cdRead : ∀ dir, (I.cd dir).ReadsFrom (· < H) pub state mem)
+ (termRoom : term.val + idx * step + 9 < H) (denseRoom : dense.val + 2 * idx + 1 < H) :
+ I.descriptor.ReadsFrom (· < H) pub state mem ∧
+ ∀ party arg, (I.fields party arg).ReadsFrom (· < H) pub state mem := by
+ let safe := Expr.ReadsFrom (· < H) pub state mem
+ have head (n : ℕ) (hn : n ≤ 59) : safe (I.loadHead n) := by
+ refine ⟨⟨levelRead, trivial⟩, ?_⟩
+ exact (add_val_le (ev I.level) n).trans_lt (by omega)
+ have tr : safe I.term := ⟨head 36 (by decide), ordinalRead, head 37 (by decide)⟩
+ let start := term.val + idx * step
+ have tv : ev I.term = (start : Word w) := by
+ change ev (I.loadHead 36) + ev I.ordinal * ev (I.loadHead 37) = _
+ rw [stored.termBase, stored.ordinal, stored.termStride]
+ simp only [start, Nat.cast_add, Nat.cast_mul, Fin.cast_val_eq_self]
+ have bound : (ev I.term).val ≤ start := tv ▸ Nat.mod_le ..
+ have copies : safe I.copies := by
+ refine ⟨⟨tr, trivial⟩, ?_⟩
+ exact (add_val_le (ev I.term) 1).trans_lt (by change start + 9 < H at termRoom; omega)
+ have payload (e : Bool × Fin 4) : safe (I.payload e) := by
+ let i := ShrinkSliceArrays.supplyRoles.symm e
+ refine ⟨⟨⟨tr, trivial⟩, trivial⟩, ?_⟩
+ have first : ((ev I.term) + 2).val ≤ (ev I.term).val + 2 := add_val_le _ 2
+ have hi : i.val < 8 := i.isLt
+ apply ((add_val_le ((ev I.term) + 2) i.val).trans (Nat.add_le_add_right first i.val)).trans_lt
+ change start + 9 < H at termRoom
+ omega
+ have demand (e : Bool) : safe (I.demand e) := by
+ refine ⟨⟨⟨head 47 (by decide), trivial, ordinalRead⟩, trivial⟩, ?_⟩
+ change ((ev (I.loadHead 47) + 2 * ev I.ordinal) + (e.toNat : Word w)).val < H
+ rw [stored.denseBase, stored.ordinal]
+ have pair : dense + 2 * (idx : Word w) = ((dense.val + 2 * idx : ℕ) : Word w) := by
+ simp only [Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, Fin.cast_val_eq_self]
+ rw [pair, ← Nat.cast_add]
+ apply (Nat.mod_le ..).trans_lt
+ have he : e.toNat ≤ 1 := by cases e <;> decide
+ omega
+ have staging : safe I.staging := ⟨hiddenRead, ⟨trivial, motifsRead⟩, strideRead⟩
+ have shared (t : Fin 4) : safe (I.shared t) :=
+ ⟨hiddenRead, ⟨⟨ordinalRead, trivial⟩, trivial⟩, strideRead⟩
+ have surviving (dir : Bool) (t : Fin 4) : safe (I.surviving dir t) :=
+ ⟨staging, trivial, strideRead⟩
+ have directory : safe I.directory := ⟨staging, trivial, strideRead⟩
+ have descriptor : safe I.descriptor := ⟨directory, trivial⟩
+ have source : safe I.source := ⟨descriptor, trivial⟩
+ have select {x y : Expr} (hx : safe x) (hy : safe y) : safe (Inputs.select I.layout x y) :=
+ ⟨hy, ⟨hx, hy⟩, head 38 (by decide)⟩
+ refine ⟨descriptor, fun j arg => ?_⟩
+ cases arg with
+ | copies => exact copies
+ | hist => exact histRead
+ | source => exact source
+ | target => exact ⟨source, copies⟩
+ | directory => exact directory
+ | demand e => exact demand e
+ | payload e => exact payload e
+ | base f =>
+ change safe (I.base j f)
+ rcases f with ⟨dir, e⟩ | ⟨dir, side, t⟩
+ · rw [Inputs.base]
+ split
+ · cases e
+ · exact staging
+ · exact cdRead dir
+ · trivial
+ · rw [Inputs.base]
+ split
+ · cases side
+ · exact select (shared t) (surviving dir t)
+ · exact select (surviving dir t) (shared t)
+ · trivial
+
+end PairSimulation.ShrinkDescriptorReads
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkFirstMapMemory.lean b/lean/OAI/Computability/VPVNP/PairShrinkFirstMapMemory.lean
new file mode 100644
index 0000000000..a1dddea424
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkFirstMapMemory.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.PairShrinkChildWords
+import OAI.Computability.VPVNP.PairShrinkCallFrameStores
+
+/-!
+# Resident inputs immediately after the shrinking hidden scan
+
+The child scan stores one packet per preceding site. The hidden scan writes
+above all of those packets and above the popped parent's own arguments.
+It supplies the single shared value used at both ends of an absorbed edge.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel LocalHistory
+open MotifBlocks MotifConversion MotifGrid CompressorRecords CompressorRecords.ShrinkSlots
+open NodeArguments DFS
+open scoped Fin.CommRing
+
+variable {a b g w endAddr : ℕ} {factor δ : ℝ} {K : Type} [_root_.Field K]
+variable {X : State a (packingLaneBits a g)}
+variable {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+private noncomputable local instance firstMapBase : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X F sel
+local notation "widths" => ShrinkPreparedCall.width F X sel
+variable (v : (X.Base × BitWord (packingTagBits (2 ^ a))) × BitWord g)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X F sel))
+ (internalLabel (ShrinkPreparedCall.width F X sel) (selectedLayout X F sel)) v)
+variable (q : X.packingData.ResidentMap (selectedLayout X F sel) v)
+variable (J : Job X F ready sel q.1.1 q.1.2 w)
+local notation "rows" => ShrinkHiddenSlots.rows X side widths v hidden
+local notation "upper" => J.scratch.hidden
+local notation "pitch" => J.scratch.stride
+variable (childMem : Word w → Word w)
+local notation "after" => ShrinkHiddenGuess.storeRows upper pitch rows childMem
+
+include q in
+/-- Both families of inputs used by the first resident come from the same
+concrete memory after the once-per-field guess. -/
+theorem Job.firstMapFields (children : J.ChildWords childMem endAddr)
+ (oldEnd : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ upper)
+ (size : ∀ m t, widths m (!side, t) ≤ pitch)
+ (cap : upper + (ShrinkHistoryRows.hiddenOrder X).length * pitch ≤ 2 ^ w) :
+ J.ChildWords after endAddr ∧
+ ShrinkCallSupplyCells.Absorbed X side widths q.1.1 q.1.2 J.scratch (q.2.symm ▸ hidden)
+ after := by
+ have fit := ShrinkHiddenSlots.rows_fit X upper pitch side widths v hidden size cap
+ constructor
+ · intro site h
+ apply ShrinkCallDemandCells.placedPackets_frame X side J.arena J.nodes (children site h) oldEnd
+ intro cell low
+ exact ShrinkCallFrameLive.hidden_below upper pitch rows cell (fun r hr ↦ (fit r hr).2) low
+ · rcases q with ⟨⟨m, j⟩, owner⟩
+ change X.packingData.shrinkPartySite side m j = v at owner
+ subst v
+ apply Job.hiddenFields J hidden
+ intro t owned i
+ exact ShrinkHiddenSlots.resident_read X J.scratch.hidden J.scratch.stride side widths _
+ hidden childMem fit (m, t) owned i
+
+/-- The popped parent argument survives the older-child writes and the
+upper-region hidden writes before the surviving-interval gather reads it. -/
+theorem Job.parentStored_after_fields (parent : Packet) (original : Scratch w endAddr)
+ (childPackets : List Packet) (childFit : ∀ z ∈ childPackets, z.Fits J.arena w endAddr)
+ (distinct : ∀ z ∈ childPackets, z.node ≠ parent.node)
+ (written : DFS.scratch endAddr childMem = writePackets J.arena childPackets original)
+ (pfit : parent.Fits J.arena w endAddr) (present : parent.Stored J.arena original)
+ (oldEnd : J.arena.base parent.node + parent.bits.length ≤ upper)
+ (size : ∀ m t, widths m (!side, t) ≤ pitch)
+ (cap : upper + (ShrinkHistoryRows.hiddenOrder X).length * pitch ≤ 2 ^ w) :
+ parent.Stored J.arena (DFS.scratch endAddr after) := by
+ have kept : parent.Stored J.arena (DFS.scratch endAddr childMem) := written ▸
+ writePackets_preserves J.arena childPackets parent original childFit pfit distinct present
+ have fit := ShrinkHiddenSlots.rows_fit X upper pitch side widths v hidden size cap
+ apply kept.congr
+ intro i
+ let addr : Word w := ((J.arena.base parent.node + i.val : ℕ) : Word w)
+ have val : addr.val = J.arena.base parent.node + i.val := Nat.mod_eq_of_lt
+ ((Nat.add_lt_add_left i.isLt _).trans_le pfit.2.2)
+ have lo : endAddr ≤ addr.val := val ▸ pfit.1.trans (Nat.le_add_right ..)
+ have hi : addr.val < upper := val ▸ (Nat.add_lt_add_left i.isLt _).trans_le oldEnd
+ change rawScratch (DFS.scratch endAddr after) addr =
+ rawScratch (DFS.scratch endAddr childMem) addr
+ simpa only [rawScratch, dite_eq_left lo, DFS.scratch] using
+ ShrinkCallFrameLive.hidden_below upper pitch rows addr (fun r hr ↦ (fit r hr).2) hi
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkGatherClock.lean b/lean/OAI/Computability/VPVNP/PairShrinkGatherClock.lean
new file mode 100644
index 0000000000..e281577f1a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkGatherClock.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherBank
+import OAI.Computability.VPVNP.PairShrinkGatherWidth
+
+/-!
+# Uniform work of the shrinking-party gather
+
+The register-setup text and the list of frames are fixed by the stage, grid
+point, party and layout. Each frame reads at most three additional external
+words. Only the private bit-copy instructions depend on the row's bit length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentColumn
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe
+open private eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe
+open private lines_probes from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+open scoped Fin.CommRing
+
+variable {n w : ℕ} (S : Fin n → Setup) (row : Fin n → Row)
+
+private theorem slice_work (m : Memory w) (frame : Word w) (bs : List Bool) :
+ (PrivateSlices.frameEvents m frame bs).length ≤ 12 + 5 * bs.length ∧
+ countProbes (PrivateSlices.frameEvents m frame bs) ≤ 3 := by
+ have h := PrivateFields.events_work (w := w) .copy bs
+ by_cases z : m (frame + 1 + 1).val = 0 <;> cases bs <;>
+ simp_all [PrivateSlices.frameEvents, PrivateSlices.headerEvents, countProbes]
+ all_goals omega
+
+/-- Fixed allowance per visited frame, given a coefficient for its payload length. -/
+def allowance (scale : ℕ) (i : Fin n) : ℕ := setCount S i + 12 + 5 * scale + probes S i
+
+theorem trace_work (is : List (Fin n)) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w)
+ (scale peak : ℕ) (bits : ∀ i, (row i).bits.length ≤ scale * (peak + 1)) :
+ (trace S row is pub state m).length ≤ (is.map (allowance S scale)).sum * (peak + 1) ∧
+ countProbes (trace S row is pub state m) ≤ (is.map (allowance S scale)).sum := by
+ have each (i : Fin n) :
+ (frameTrace (S i) (row i) pub state m).length ≤ allowance S scale i * (peak + 1) ∧
+ countProbes (frameTrace (S i) (row i) pub state m) ≤ allowance S scale i := by
+ let f := (S i).operands
+ let setup := (RowRecipe.evaluate pub state m (RegisterSetup.lines f) (fun _ ↦ 0)).1
+ let frame := PrivateSlices.frameEvents m ((row i).frame : Word w) (row i).bits
+ have st : setup.length = setCount S i := (eval_cost pub state m _ _).1
+ have sp : countProbes setup = ∑ j, (f j).loads := lines_probes f pub state m _
+ have cost := slice_work m ((row i).frame : Word w) (row i).bits
+ change frame.length ≤ _ ∧ countProbes frame ≤ _ at cost
+ change (setup ++ frame).length ≤ _ ∧ countProbes (setup ++ frame) ≤ _
+ rw [List.length_append, countProbes_append, st, sp]
+ constructor
+ · calc
+ _ ≤ setCount S i + 12 + 5 * (scale * (peak + 1)) := by
+ have := Nat.mul_le_mul_left 5 (bits i)
+ omega
+ _ ≤ (setCount S i + 12) * (peak + 1) + (5 * scale) * (peak + 1) := by
+ rw [Nat.mul_assoc]
+ exact Nat.add_le_add_right (Nat.le_mul_of_pos_right _ (Nat.succ_pos _)) _
+ _ ≤ allowance S scale i * (peak + 1) := by
+ rw [← Nat.add_mul]
+ exact Nat.mul_le_mul_right _ (Nat.le_add_right ..)
+ · unfold allowance probes
+ dsimp only [f] at *
+ omega
+ induction is with
+ | nil => simp [trace, countProbes]
+ | cons i is ih =>
+ change ((frameTrace (S i) (row i) pub state m) ++ (trace S row is pub state m)).length ≤ _ ∧
+ countProbes ((frameTrace (S i) (row i) pub state m) ++ (trace S row is pub state m)) ≤ _
+ rw [List.length_append, countProbes_append, List.map_cons, List.sum_cons, Nat.add_mul]
+ exact ⟨Nat.add_le_add (each i).1 ih.1, Nat.add_le_add (each i).2 ih.2⟩
+
+end PairSimulation.ResidentColumn
+
+namespace PairSimulation.ShrinkGatherBank.Family
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open CompressorRecords CompressorRecords.ShrinkSlots MotifBlocks MotifGrid MotifConversion
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+variable {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {t shared : ℕ} {F : MapHandlerImage.Family B t shared} (G : ShrinkGatherBank.Family F)
+
+/-- This finite sum depends only on the fixed stage text and the chosen width coefficient. -/
+noncomputable def clockConstant (scale : ℕ) : ℕ :=
+ ∑ k : Key B, ((List.finRange _).map (ResidentColumn.allowance (G.setup k) scale)).sum
+
+theorem trace_bound_of_width {g w : ℕ} {δ : ℝ} {X : State G.a (packingLaneBits G.a g)}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} {sel : X.ShrinkSelection B}
+ {m : X.packingData.Motif} {party : Fin 6} (z : B.grid.demands)
+ (J : ShrinkPartyNative.Job X B ready sel m party w)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w) (scale peak : ℕ)
+ (bits : ∀ c i, (J.row c i).bits.length ≤ scale * (peak + 1)) :
+ let es := J.trace (G.operands (z, party)) (G.node (z, party)) pub state mem
+ es.length ≤ G.clockConstant scale * (peak + 1) ∧ countProbes es ≤ G.clockConstant scale := by
+ let side := selectedLayout X B sel
+ let k : Key B := (z, party, side)
+ let rs := ShrinkPartyColumns.gather party side G.thickCount G.profile J.row
+ let cost (key : Key B) :=
+ ((List.finRange _).map (ResidentColumn.allowance (G.setup key) scale)).sum
+ have h := ResidentColumn.trace_work (G.setup k) rs (List.finRange _) pub state mem scale peak
+ (fun _ ↦ bits _ _)
+ have bound : cost k ≤ G.clockConstant scale := Finset.single_le_sum
+ (f := cost) (fun _ _ ↦ Nat.zero_le _) (Finset.mem_univ k)
+ exact ⟨h.1.trans (Nat.mul_le_mul_right _ bound), h.2.trans bound⟩
+
+/-- The bound uses the old state's maximum wire width even on surviving subdivisions. -/
+theorem trace_bound {g w : ℕ} {δ : ℝ} {X : State G.a (packingLaneBits G.a g)}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} {sel : X.ShrinkSelection B}
+ {m : X.packingData.Motif} {party : Fin 6} (z : B.grid.demands)
+ (J : ShrinkPartyNative.Job X B ready sel m party w)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w) :
+ let es := J.trace (G.operands (z, party)) (G.node (z, party)) pub state mem
+ let C := G.clockConstant (fieldFactor B + 1)
+ es.length ≤ C * (X.maxWireWidth + 1) ∧ countProbes es ≤ C :=
+ G.trace_bound_of_width z J pub state mem (fieldFactor B + 1) X.maxWireWidth J.row_bits_le
+
+/-- One constant bounds all selected jobs from the entire finite family of stage images. -/
+theorem uniform_clock {I : Type*} [Finite I] {t₀ shared₀ : I → ℕ}
+ {writer : ∀ i, MapHandlerImage.Family B (t₀ i) (shared₀ i)}
+ (banks : ∀ i, ShrinkGatherBank.Family (writer i)) :
+ ∃ C : ℕ, ∀ (i : I) {g w : ℕ} {δ : ℝ}
+ {X : State (banks i).a (packingLaneBits (banks i).a g)}
+ {ready : Ready (2 ^ (banks i).a) (2 * 2 ^ (banks i).a + 1) (2 ^ (banks i).b) δ}
+ {sel : X.ShrinkSelection B} {m : X.packingData.Motif} {party : Fin 6}
+ (z : B.grid.demands) (J : ShrinkPartyNative.Job X B ready sel m party w)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w),
+ let es := J.trace ((banks i).operands (z, party)) ((banks i).node (z, party)) pub state mem
+ es.length ≤ C * (X.maxWireWidth + 1) ∧ countProbes es ≤ C := by
+ let := Fintype.ofFinite I
+ let c (i : I) := (banks i).clockConstant (fieldFactor B + 1)
+ refine ⟨∑ i, c i, ?_⟩
+ intro i g w δ X ready sel m party z J pub state mem
+ have bound := (banks i).trace_bound z J pub state mem
+ have hi : c i ≤ ∑ j, c j :=
+ Finset.single_le_sum (f := c) (fun _ _ ↦ Nat.zero_le _) (Finset.mem_univ i)
+ exact ⟨bound.1.trans (Nat.mul_le_mul_right _ hi), bound.2.trans hi⟩
+
+end PairSimulation.ShrinkGatherBank.Family
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkGatherExterior.lean b/lean/OAI/Computability/VPVNP/PairShrinkGatherExterior.lean
new file mode 100644
index 0000000000..9b69efa4ab
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkGatherExterior.lean
@@ -0,0 +1,63 @@
+import OAI.Computability.VPVNP.PairSimulationMapScratchOutside
+import OAI.Computability.VPVNP.PairShrinkUpdatedBelow
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherMatrix
+
+/-!
+# Exterior cells in the pure gather and grouped map
+
+A packet witness fixes the gather intervals for every incoming scratch.
+The grouped map's pure update subsequently preserves every word outside
+its descriptor, directory, selector, label and histogram arrays.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.ShrinkSlots
+open Compression Compression.PackingData Compression.ShrinkMotif
+open MotifGrid MotifBlocks MotifConversion MapHandlerOperand
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {t shared w g endAddr packetEnd : ℕ} (F : MapHandlerImage.Family B t shared)
+ (G : ShrinkGatherBank.Family F) {X : State G.a (packingLaneBits G.a g)} {δ : ℝ}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} {selection : X.ShrinkSelection B}
+ {motif : X.packingData.Motif} (I : LocalHistory.EntryInput B)
+ (J : ShrinkPartyNative.Job X B ready selection motif I.party w)
+ (hw : MapConstants.widthThreshold B ≤ w) (P : Fin 5 → Word w) (st : Word w) (mem : Memory w)
+ (W : Workspace F demandMass_pos I) (saved : DFS.Scratch w endAddr)
+local notation "key" => Prod.mk (demandGrid B demandMass_pos I.demand) I.party
+local notation "L" => F.layout key
+local notation "ptr" => PhaseRecipe.Expr.eval P st mem (F.base key)
+
+/-- Every successful pure gathered action has the same exterior frame as its
+installed interpreter, even for a scratch that has never been materialized
+as a full private-memory configuration. -/
+theorem gathered_exterior {baseline : Word w → Word w} (packets : J.Packets packetEnd baseline)
+ (fit : (ptr).val + Fintype.card ShrinkCallFields.Arg ≤ 2 ^ w)
+ {events : List (Event w)} {out : DFS.Scratch w endAddr}
+ (got : gatheredAction F G I J hw P st mem W saved = some (events, out)) :
+ ∀ q : Word w, q.val < J.scratch.staging →
+ q.val < (ptr).val ∨ (ptr).val + Fintype.card ShrinkCallFields.Arg ≤ q.val →
+ MapCallSetup.Outside (L).core ((L).corePC (L).locations) W q →
+ NodeArguments.rawScratch out q = NodeArguments.rawScratch saved q := by
+ obtain ⟨⟨es, s⟩, raw, eqn⟩ := Option.map_eq_some_iff.mp got
+ have upper := (F.action_some_iff demandMass_pos I hw P st mem W endAddr
+ (J.updated endAddr saved)).mp raw |>.2.2
+ have same : s = out := (Prod.mk.inj eqn).2
+ intro q below descriptor outside
+ rw [← same, upper]
+ exact (MapScratch.upper_outside (L).core (L).args ((L).corePC (L).locations) W ptr _
+ F.ordinal endAddr (J.updated endAddr saved) q fit descriptor outside).trans
+ (J.updated_below packets saved q below)
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkGatherQuiet.lean b/lean/OAI/Computability/VPVNP/PairShrinkGatherQuiet.lean
new file mode 100644
index 0000000000..db5aef1c81
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkGatherQuiet.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.PairShrinkPartyNative
+
+/-!
+# Choices and external writes of a shrinking-party gather
+
+Operand setup and slice headers only read external memory. Each subsequent
+bit copy takes private steps. These trace properties hold for arbitrary
+packet contents and values returned by the header probes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentColumn
+
+open BurstRAM CompressorRecords
+open scoped Fin.CommRing
+open private no_choices from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+open private eval_no_writes from OAI.Computability.VPVNP.CompressorFormulaFootprint
+
+variable {N w : ℕ} (pub : Fin 5 → Word w) (state : Word w) (m : Memory w)
+
+private theorem frameTrace_noChoices (s : Setup) (row : Row) :
+ choiceBits (frameTrace s row pub state m) = [] := by
+ have head : choiceBits (PrivateSlices.headerEvents m (row.frame : Word w)) = [] := by
+ by_cases h : m ((row.frame : Word w) + 1 + 1).val = 0 <;>
+ simp [PrivateSlices.headerEvents, h, choiceBits]
+ simp only [frameTrace, PrivateSlices.frameEvents, PrimedInputRAM.Flow.choiceBits_append,
+ no_choices, head, List.nil_append]
+ split <;> simp [choiceBits, PrivateFields.events_bits]
+
+private theorem frameTrace_noWrites (s : Setup) (row : Row) :
+ SourceTransport.Writes (fun _ ↦ False) (frameTrace s row pub state m) := by
+ intro a v h
+ rcases List.mem_append.mp h with setup | frame
+ · exact eval_no_writes (fun _ ↦ False) pub state m _ _ a v setup
+ rcases List.mem_append.mp frame with head | copy
+ · by_cases h : m ((row.frame : Word w) + 1 + 1).val = 0 <;>
+ simp [PrivateSlices.headerEvents, h] at head
+ · split at copy
+ · exact List.not_mem_nil copy
+ · exact (FlowFootprint.bounds_of_noProbes (fun _ ↦ False) (fun _ ↦ False)
+ (PrivateFields.events_work (w := w) .copy row.bits).2).2 a v copy
+
+variable (S : Fin N → Setup) (row : Fin N → Row) (is : List (Fin N))
+
+theorem trace_noChoices : choiceBits (trace S row is pub state m) = [] := by
+ induction is with
+ | nil => rfl
+ | cons i is ih =>
+ rw [trace, List.flatMap_cons, PrimedInputRAM.Flow.choiceBits_append,
+ frameTrace_noChoices, List.nil_append]
+ exact ih
+
+theorem trace_noWrites : SourceTransport.Writes (fun _ ↦ False) (trace S row is pub state m) := by
+ intro a v h
+ obtain ⟨i, _, frame⟩ := List.mem_flatMap.mp h
+ exact frameTrace_noWrites pub state m (S i) (row i) a v frame
+
+end PairSimulation.ResidentColumn
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM CompressorRecords Compression Compression.State Compression.ShrinkMotif
+open MotifBlocks MotifConversion MotifGrid
+
+variable {a b g w : ℕ} {δ factor : ℝ} {K : Type*} [_root_.Field K]
+ {X : State a (packingLaneBits a g)}
+ {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+ {m : X.packingData.Motif} {party : Fin 6}
+ (J : Job (a := a) (b := b) (g := g) X F ready sel m party w)
+ (O : ShrinkCallHeader.Operands) (nodeExpr : PhaseRecipe.Expr) (pub : Fin 5 → Word w)
+ (state : Word w) (mem : Memory w)
+
+theorem Job.trace_noChoices : choiceBits (J.trace O nodeExpr pub state mem) = [] :=
+ ResidentColumn.trace_noChoices pub state mem _ _ _
+
+theorem Job.trace_noWrites :
+ SourceTransport.Writes (fun _ ↦ False) (J.trace O nodeExpr pub state mem) :=
+ ResidentColumn.trace_noWrites pub state mem _ _ _
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkGatherTraceReads.lean b/lean/OAI/Computability/VPVNP/PairShrinkGatherTraceReads.lean
new file mode 100644
index 0000000000..f7a220b65d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkGatherTraceReads.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.PairShrinkPartyNative
+
+/-!
+# External reads of the selected shrinking-party gather
+
+Each visited frame contributes its compiled pointer loads and the three
+possible slice-header reads. The published interval banks identify the
+header addresses and prove that they fit in the native word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentColumn
+
+open BurstRAM CompressorRecords
+open private frame_reads from OAI.Computability.VPVNP.PairResidentFrameColumn
+open private reads_append from OAI.Computability.VPVNP.CompressorFormulaFootprint
+
+/-- The allowed pointer and header addresses of the rows cover every external
+read in their chronological trace. -/
+theorem trace_reads {N w : ℕ} (S : Fin N → Setup) (row : Fin N → Row) (is : List (Fin N))
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w) (allowed : ℕ → Prop)
+ (safe : ∀ i, (row i).ReadSafe (S i) allowed pub state mem)
+ (fit : ∀ i, (row i).frame + 2 < 2 ^ w) :
+ SourceTransport.Reads allowed (trace S row is pub state mem) := by
+ intro addr value read
+ obtain ⟨i, _, hit⟩ := List.mem_flatMap.mp read
+ have loads := RegisterSetup.lines_reads (S i).operands allowed pub state mem (safe i).loads
+ (fun _ ↦ 0)
+ exact reads_append loads (frame_reads (row i) (S i) allowed pub state mem (safe i) (fit i))
+ addr value hit
+
+end PairSimulation.ResidentColumn
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM CompressorRecords CompressorRecords.ShrinkSlots Compression Compression.ShrinkMotif
+open MotifBlocks MotifConversion MotifGrid ShrinkPartyColumns
+open private Job.recorded from OAI.Computability.VPVNP.PairShrinkPartyNative
+
+variable {a b g w : ℕ} {δ factor : ℝ} {K : Type*} [_root_.Field K]
+ {X : State a (packingLaneBits a g)}
+ {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+ {m : X.packingData.Motif} {party : Fin 6}
+ (J : Job X F ready sel m party w) (O : ShrinkCallHeader.Operands) (nodeExpr : PhaseRecipe.Expr)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w) (allowed : ℕ → Prop)
+ {level absolute : Word w} {T U : IncidenceDirectory w} {origin layer pitch : ℕ}
+ {heads : SlotLevel.Heads}
+
+local notation "side" => selectedLayout X F sel
+
+/-- The public trace of the actual resident job reads only the addresses
+allowed for its AB and surviving rows. -/
+theorem Job.trace_reads (old : J.OldPublished O pub state mem level T origin)
+ (next : J.SupplyPublished O nodeExpr pub state mem heads absolute U layer pitch)
+ (safe : ∀ c i, (J.row c i).ReadSafe (setups O nodeExpr a b party side c i)
+ allowed pub state mem) :
+ SourceTransport.Reads allowed (J.trace O nodeExpr pub state mem) :=
+ ResidentColumn.trace_reads _ _ _ pub state mem allowed (fun _ ↦ safe _ _)
+ (fun _ ↦ (Job.recorded J O nodeExpr pub state mem old next _ _).frameFit)
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkGatherWidth.lean b/lean/OAI/Computability/VPVNP/PairShrinkGatherWidth.lean
new file mode 100644
index 0000000000..0d9ba10925
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkGatherWidth.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.PairShrinkPartyNative
+import OAI.Computability.VPVNP.ShrinkFieldBounds
+
+/-!
+# Width of each row copied by the shrinking-party gather
+
+An AB interval fits its demand, whose width is at most the largest old wire.
+A surviving subdivision fits its selected supply field, including all the
+selector bits. The resulting bound is uniform over the physical packet
+addresses, the selected layout, and the subdivision index.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifBlocks MotifGrid MotifConversion CompressorRecords CompressorRecords.ShrinkSlots
+open ShrinkPartyColumns
+open scoped Fin.CommRing
+
+variable {a b g w : ℕ} {δ factor : ℝ} {K : Type*} [_root_.Field K]
+ {X : State a (packingLaneBits a g)}
+ {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+ {m : X.packingData.Motif} {party : Fin 6} (J : Job X F ready sel m party w)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X F sel
+local notation "sub" => SlotLevel.Shape.subdivisions (levelShape (b := b) X)
+local notation "count" => 2 ^ (Shrink.colors a) * 2 ^ a / 4
+
+private theorem Job.abRow_bits_le (dir : Bool) (hit : party = if dir then 1 else 0)
+ (i : Fin count) :
+ (J.abRow dir hit i).bits.length ≤ X.maxWireWidth := by
+ by_cases pos : 0 < (J.abRow dir hit i).bits.length
+ · have bound := ab_bound X m J.arcFit J.bucketFit i J.arena J.nodes side dir (J.abHalf dir hit)
+ J.first J.scratch.staging pos
+ have old := X.packingData.abWidth_le (State.two_le_packingColors a) (Nat.two_pow_pos a)
+ X.shrinkNumber X.packingWidth (fun _ ↦ X.width_le_maxWireWidth _) m
+ exact (Nat.le_add_left ..).trans (bound.trans old)
+ · omega
+
+private theorem Job.supplyRow_bits_le (dir : Bool) (t : Fin 4)
+ (hit : party = ShrinkSurvivingOperands.party side t dir) (i : Fin (sub t)) :
+ (J.supplyRow dir t hit i).bits.length ≤ fieldFactor F * (X.maxWireWidth + 1) := by
+ have bound := surviving_bound X side sub (branchWidth X F sel) (X.shrinkStateIndex ready side)
+ m t dir (J.half dir t hit) J.arena J.node (J.scratch.surviving dir t)
+ (J.allocation.row (ShrinkMotifOrder.stateNumber X m, t)) ready.count_pos i
+ have term := X.packingData.shrinkTerm_bounds (State.two_le_packingColors a) (Nat.two_pow_pos a)
+ X.shrinkNumber X.packingWidth (fun _ ↦ X.width_le_maxWireWidth _) F m (sel m)
+ exact (Nat.le_add_left ..).trans (bound.trans (term.2 (side, t)).2)
+
+/-- Each physical gather row copies at most a fixed block factor times the
+largest old wire width plus one. This includes empty AB intervals. -/
+theorem Job.row_bits_le (c : At party side) (i : Fin (frames count sub c.val)) :
+ (J.row c i).bits.length ≤ (fieldFactor F + 1) * (X.maxWireWidth + 1) := by
+ rw [Nat.add_mul, Nat.one_mul]
+ rcases c with ⟨_ | ⟨dir, t⟩, h⟩
+ · apply (J.abRow_bits_le (decide (party = 1)) _ i).trans
+ omega
+ · exact (J.supplyRow_bits_le dir t _ i).trans (Nat.le_add_right ..)
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkGeometryLimit.lean b/lean/OAI/Computability/VPVNP/PairShrinkGeometryLimit.lean
new file mode 100644
index 0000000000..bb4e635dd9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkGeometryLimit.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairNativeFrameDescriptor
+
+/-!
+# Uniform bound for the native terminal histogram address
+
+The terminal header counts all selected DFS rows, including the final layer. The
+private histogram starts after the argument frame for the last possible absolute
+row address. A fixed polynomial bounds this address before any branch is chosen.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NativeFrame
+
+open Compression CursorBounds CursorNetwork CompressorRecords Filter TraversalRows
+
+/-- Reserve one argument frame for each absolute address up to the selected
+descriptor space bound. The histogram length does not enter its base address. -/
+noncomputable def histLimit (degree b : ℕ) (start : ℕ → ℕ) (n : ℕ) : ℕ :=
+ n + (start n + (initialPositions b n)^2) * NodeArguments.frameStride degree n
+
+theorem histLimit_bounded (degree b : ℕ) {start : ℕ → ℕ} (hs : PolynomiallyBounded start) :
+ PolynomiallyBounded (histLimit degree b start) :=
+ PolynomiallyBounded.id.add ((hs.add ((CursorRAM.bounded_positions b).pow 2)).mul
+ (NodeArguments.frameStride_bounded degree))
+
+/-- The polynomial bound holds for every coefficient specialization and all
+branches, including at zero compression depth. -/
+theorem eventually_selected_histBase {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (F : DescriptorSpace.Shape)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hs : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let L := DescriptorSpace.cursorLayout F b S.steps u.θ (start n) n
+ ∀ z : (B.execute f hf T hT X).Choices,
+ let rows := words B.recordLimit (selectedLayers B f hf T hT X z)
+ ∀ degree count, (regions degree n (DescriptorSpace.endAddress L) rows count).histBase ≤
+ histLimit degree b start n := by
+ filter_upwards [TerminalLayout.eventually_fit B u F b hb hs 0,
+ eventually_ge_atTop 3] with n selected hn
+ intro base lanes labels hD hT A _ f hf X T L z rows degree count
+ have below := (selected labels hD hT A f hf z).1
+ change DescriptorSpace.endAddress L + 2 * rows + _ <
+ start n + (processorCount b n)^2 - 32 at below
+ have rowEnd : DescriptorSpace.endAddress L + rows ≤ start n + (processorCount b n)^2 := by omega
+ have proc : processorCount b n ≤ initialPositions b n :=
+ (Nat.pow_le_pow_right Nat.zero_lt_two (addressBits_le_virtualBits b n hn)).trans
+ (Nat.le_mul_of_pos_right _ (by omega : 0 < virtualBits b n))
+ exact Nat.add_le_add_left (Nat.mul_le_mul_right _
+ (rowEnd.trans (Nat.add_le_add_left (Nat.pow_le_pow_left proc 2) _))) _
+
+/-- Reading the two native header words also respects the bound. Each natural
+address encoded in a word can only decrease when reduced modulo the word size. -/
+theorem Readback.histBase_le {w firstRow rowWords stride baseRadix laneRadix : ℕ}
+ {m : BurstRAM.Memory w} {header span : BurstRAM.Word w}
+ (h : Readback m header firstRow rowWords stride baseRadix laneRadix span)
+ (degree : ℕ) (pub : Fin 11 → BurstRAM.Word w) :
+ (fromHeader degree pub header m).histBase ≤
+ (regions degree (pub 6).val firstRow rowWords (pub 9).val).histBase := by
+ unfold fromHeader
+ rw [h.row, h.words, Fin.val_natCast, Fin.val_natCast]
+ exact Nat.add_le_add_left (Nat.mul_le_mul_right _
+ (Nat.add_le_add (Nat.mod_le _ _) (Nat.mod_le _ _))) _
+
+/-- Uniform upper bound on the first map workspace cell above all native
+leaf stacks. Each of the named stack ports reserves `n^40` words. -/
+noncomputable def postStackLimit (degree b : ℕ) (start : ℕ → ℕ) (labels ports n : ℕ) :=
+ histLimit degree b start n + labels + n^5 + 38 + ports * n^40
+
+theorem postStackLimit_bounded (degree b : ℕ) {start : ℕ → ℕ} (hs : PolynomiallyBounded start)
+ (labels ports : ℕ) : PolynomiallyBounded (postStackLimit degree b start labels ports) :=
+ let hc := ((histLimit_bounded degree b hs).add (.const labels)).add (PolynomiallyBounded.id.pow 5)
+ (hc.add (.const 38)).add ((PolynomiallyBounded.const ports).mul (PolynomiallyBounded.id.pow 40))
+
+theorem postStack_le {degree b n firstRow rowWords labels : ℕ} {start : ℕ → ℕ}
+ (ports : ℕ) (hh : (regions degree n firstRow rowWords labels).histBase ≤
+ histLimit degree b start n) :
+ (regions degree n firstRow rowWords labels).stackBase + ports * n^40 ≤
+ postStackLimit degree b start labels ports n :=
+ Nat.add_le_add_right (Nat.add_le_add_right (Nat.add_le_add_right (Nat.add_le_add_right hh _) _) _)
+ _
+
+end PairSimulation.NativeFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHandlerPrepared.lean b/lean/OAI/Computability/VPVNP/PairShrinkHandlerPrepared.lean
new file mode 100644
index 0000000000..6de97c2dd4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHandlerPrepared.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.PairShrinkPreparedCall
+import OAI.Computability.VPVNP.PairShrinkCallFamily
+import OAI.Computability.VPVNP.PairSimulationMapHandlerOperand
+
+/-!
+# Preparing the selected shrink handler's fixed map image
+
+The stage and the party determine the descriptor recipe. The live register
+bank and the completed argument gathers supply its true addresses and bits.
+Its histogram is disjoint from both the private descriptor and the local
+port directory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPreparedCall
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open CompressorRecords MotifGrid MotifBlocks MotifConversion MotifEntry NetworkKernel
+open scoped Fin.CommRing
+
+variable {a g b pad w p r t n limit endAddr : ℕ} {K : Type} [_root_.Field K]
+variable {S : BlockSchedule K} (B : S.Templates)
+variable (degree : ℕ) (ord : B.Entry → Fin t)
+variable (X : State a (packingLaneBits a g))
+/-- Classical decidable equality on the compression state’s base vertices for preparing the
+shrink handler’s map descriptor. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+variable (selection : X.ShrinkSelection B.shrink) (layout : Bool) (subdiv : Fin 4 → ℕ)
+variable {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+variable (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad) (hpos : ∀ t, 0 < subdiv t)
+variable (m : X.packingData.Motif) (j : Fin 6)
+variable (old : ShrinkCallDemandCells.Old X layout m j)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner layout)
+ (internalLabel (width B.shrink X selection) layout) (X.packingData.shrinkPartySite layout m j))
+variable (z : (X.shrinkOutputState layout subdiv
+ (fun m t ↦ width B.shrink X selection m (layout, t)) I).network.Half
+ (X.packingData.shrinkPartySite layout m j))
+variable (s : ShrinkCallFields.Scratch) (arena : NodeArguments.Arena) (nodes : X.network.Site → ℕ)
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (widthsDemand X m)) B.shrink (widthsDemand X m) (selection m).val
+ s (ShrinkMotifOrder.stateNumber X m).val (ShrinkCallDemandCells.cdBase X m arena nodes))
+
+local notation "Call" => input B.shrink X selection layout subdiv I hpos m j old hidden z
+local notation "Family" => ShrinkCallABI.family B degree a ord
+local notation "Grid" => MapHandlerOperand.index demandMass_pos (Call)
+local notation "L" => MapHandlerOperand.layout (Family) demandMass_pos (Call)
+local notation "Prog" => MapInline.callProgram (L)
+local notation "Ds" => demandBits demandSource demandTarget j
+ (LocalHistory.EntryInput.demandBits (Call))
+local notation "Ws" => MotifSelector.mapHalf supply (fun _ ↦ inputBits)
+ (LocalHistory.EntryInput.supplyBits (Call))
+local notation "cds" => ShrinkCallDemandCells.cdBase X m arena nodes
+local notation "Workspace" => ShrinkCallFields.workspace B.shrink (Prog) (widthsDemand X m)
+ (Subtype.val (selection m)) (Ds) (Ws) s
+ (Fin.val (ShrinkMotifOrder.stateNumber X m)) layout (cds) ok
+
+variable (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin 24 ↪ Fin r)
+variable (cfg : Config w p r) (mem : Memory w)
+local notation "pub" => MapHandlerOperand.pub (Family) demandMass_pos (Call) dfs saved common cfg
+local notation "st" => MapHandlerOperand.state (Family) demandMass_pos (Call) dfs saved common cfg
+local notation "O" => ShrinkCallABI.operands degree
+local notation "Addr" => MapHandlerOperand.addr (Family) demandMass_pos (Call)
+ dfs saved common cfg mem
+
+set_option maxHeartbeats 1200000 in
+-- The handler, typed old packet and selected map layout use dependent coordinate types.
+/-- The hosted handler can run the selected entry, on the actual private words
+and the descriptor expressions compiled for the current stage. -/
+theorem prepared (before : Word w → Word w)
+ (oldFields : ShrinkCallDemandCells.Readback X layout m j arena nodes old cfg.privateMem
+ s.staging endAddr)
+ (hiddenFields : ShrinkCallSupplyCells.Absorbed X layout (width B.shrink X selection) m j
+ s hidden cfg.privateMem)
+ (supplyFields : ShrinkCallSupplyCells.Retained X layout subdiv (width B.shrink X selection)
+ I m j s z before cfg.privateMem)
+ (words : ∀ arg, (((O).inputs a).fields j arg).eval pub st mem =
+ ShrinkCallFields.values (w := w) X B.shrink selection m s j layout (cds) arg) :
+ MapHandlerOperand.Prepared (Family) demandMass_pos (Call) dfs saved common cfg mem
+ (Workspace) := by
+ have hdir := words .directory
+ change ((O).inputs a).directory.eval pub st mem = (s.directory : Word w) at hdir
+ have address : Addr = (s.descriptor : Word w) := by
+ change ((O).inputs a).directory.eval pub st mem + 16 = _
+ rw [hdir]
+ simp [ShrinkCallFields.Scratch.descriptor]
+ have limit := ok.room.trans_lt ok.capacity.room
+ have hroom := ShrinkCallFields.workspace_descriptor_fit B.shrink (widthsDemand X m)
+ (selection m).val s _ (cds) ok
+ have hdesc : (s.descriptor : Word w).val = s.descriptor := Nat.mod_eq_of_lt (by
+ unfold ShrinkCallFields.Scratch.target ShrinkCallFields.Scratch.source at limit
+ omega)
+ have hhist (l : Fin t) : s.hist + l.val < s.directory :=
+ (Nat.add_lt_add_left l.isLt s.hist).trans_le ok.histogram
+ have endDir : s.directory + 16 < 2 ^ w := by
+ unfold ShrinkCallFields.Scratch.target ShrinkCallFields.Scratch.source
+ ShrinkCallFields.Scratch.descriptor at limit
+ omega
+ refine ⟨?_, ?_, ?_, ?_, ?_⟩
+ · rwa [address, hdesc]
+ · intro arg
+ exact (words arg).trans (values_eq B.shrink X selection layout subdiv I hpos m j old hidden z
+ s arena nodes (L).core ((L).corePC (L).locations) ok arg)
+ · rw [address]
+ exact resident B.shrink X selection layout subdiv I hpos m j old hidden z s arena nodes
+ (L).core ((L).corePC (L).locations) ok before cfg.privateMem oldFields hiddenFields
+ supplyFields
+ · intro l
+ left
+ change ((s.hist + l.val : ℕ) : Word w).val < (Addr).val
+ rw [address, hdesc, show ((s.hist + l.val : ℕ) : Word w).val = _ from
+ Nat.mod_eq_of_lt (by have := hhist l; omega)]
+ exact (hhist l).trans_le (Nat.le_add_right ..)
+ · intro l i eqn
+ have hi := i.isLt.trans_le (MapPortAgreement.ports_length_le supply j (L).core.edgeOrder)
+ change i.val < 2 * Fintype.card (Bool × Fin 4) at hi
+ have card : 2 * Fintype.card (Bool × Fin 4) = 16 := by simp
+ rw [card] at hi
+ have hv := congrArg Fin.val eqn
+ change ((s.hist + l.val : ℕ) : Word w).val =
+ ((s.directory : Word w) + (i.val : Word w)).val at hv
+ rw [← Nat.cast_add, Fin.val_natCast, Fin.val_natCast,
+ Nat.mod_eq_of_lt (by have := hhist l; omega : s.hist + l.val < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega : s.directory + i.val < 2 ^ w)] at hv
+ have := hhist l
+ omega
+
+end PairSimulation.ShrinkPreparedCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenCode.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenCode.lean
new file mode 100644
index 0000000000..67e6a23e97
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenCode.lean
@@ -0,0 +1,153 @@
+import OAI.Computability.VPVNP.PairNodeChildLoop
+
+/-!
+# Native loop control for absorbed shrinking fields
+
+The public row count and ordered ID array are read from external memory.
+Each ID selects one fixed-stride private slot; only the term's actual bit
+width is guessed and written. Registers 0–4 are the private field mover.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess
+
+open BurstRAM PrivateRAM NodeArguments
+open scoped Fin.CommRing
+
+variable {W p r k : ℕ}
+
+/-- Instruction labels for initializing the owner's scan, testing its remaining count,
+addressing the current private slot, and advancing to the next dense ID. -/
+inductive Control where
+ | one | zero | countAddr | readCount | rowOffset | rowStart | test
+ | slotOffset | slotStart | slotEnd | decrement | advance
+ deriving DecidableEq
+
+instance : Fintype Control := derive_fintype% _
+
+/-- The term width reader's input pointer, term parameters, and outputs.
+Its register six retains the actual dense hidden ID on completion. -/
+def widthRegs (reg : Fin 22 ↪ Fin r) : Fin 10 ↪ Fin r :=
+ (⟨![5,6,7,8,9,1,10,11,12,13], by decide⟩ : Fin 10 ↪ Fin 22).trans reg
+
+/-- Embed the five registers of the private bit-guessing loop as registers 0 through 4 of the
+absorbed-field scan. -/
+def guessRegs (reg : Fin 22 ↪ Fin r) : Fin 5 ↪ Fin r := (Fin.castAddEmb 17).trans reg
+
+/-- Emit the scan instruction at a control label, with supplied entry addresses for reading the
+width, guessing the bits, and leaving the scan. -/
+def control (pc : Control → Fin p) (reg : Fin 22 ↪ Fin r) (width guess done : Fin p) :
+ Control → Instr W p r k
+ | .one => .constant (reg 3) 1 (pc .zero)
+ | .zero => .constant (reg 21) 0 (pc .countAddr)
+ | .countAddr => .binary .add (reg 14) (reg 17) (reg 18) (pc .readCount)
+ | .readCount => .readExternal (reg 14) (reg 14) (pc .rowOffset)
+ | .rowOffset => .binary .mul (reg 5) (reg 18) (reg 20) (pc .rowStart)
+ | .rowStart => .binary .add (reg 5) (reg 19) (reg 5) (pc .test)
+ | .test => .jumpEq (reg 14) (reg 21) done width
+ | .slotOffset => .binary .mul (reg 2) (reg 10) (reg 16) (pc .slotStart)
+ | .slotStart => .binary .add (reg 2) (reg 15) (reg 2) (pc .slotEnd)
+ | .slotEnd => .binary .add (reg 1) (reg 2) (reg 1) guess
+ | .decrement => .binary .sub (reg 14) (reg 14) (reg 3) (pc .advance)
+ | .advance => .binary .add (reg 5) (reg 5) (reg 3) (pc .test)
+
+theorem resize_control (pc : Control → Fin p) (reg : Fin 22 ↪ Fin r) (width guess done : Fin p) (j : Control) :
+ (control (W := 1) (k := k) pc reg width guess done j).resize W = control pc reg width guess done j := by
+ cases j <;> rfl
+
+/-- The machine contains each scan control instruction at its assigned program counter with the
+given registers and jump targets. -/
+def ControlLinked (M : Machine W p r k) (pc : Control → Fin p) (reg : Fin 22 ↪ Fin r) (width guess done : Fin p) :=
+ ∀ j, M.code (pc j) = control pc reg width guess done j
+
+/-- Addresses and layout choices for one packed owner. The caller can
+place the private slots at any base separated from its other scratch. -/
+structure Args (W : ℕ) where
+ /-- External word address of the first selected motif term record. -/
+ termBase : Word W
+ /-- Distance in external words between the starts of consecutive motif term records. -/
+ termStride : Word W
+ /-- The surviving layout of the selected terms. The width reader uses the opposite layout for
+ absorbed fields. -/
+ layout : Bool
+ /-- Number of selector bits contributed to a hidden field by each repetition of its term. -/
+ selectorBits : Word W
+ /-- First private word address in the array of slots for guessed hidden fields. -/
+ scratchBase : ℕ
+ /-- Distance in private words between slots for consecutive dense hidden-field IDs. -/
+ slotStride : ℕ
+ /-- External base address of the table giving the number of hidden fields for each packed
+ owner. -/
+ countBase : ℕ
+ /-- Ordinal of the packed site whose count and ordered row of hidden-field IDs the scan
+ reads. -/
+ owner : ℕ
+ /-- External address where the array of owners' ordered hidden-field ID rows begins. -/
+ rowBase : ℕ
+ /-- Distance in external words from one packed owner's ID row to the next. -/
+ rowStride : ℕ
+
+/-- Start address of this owner's external ID row, computed as the row base plus the owner
+ordinal times the row stride. -/
+def Args.row (g : Args W) := g.rowBase + g.owner*g.rowStride
+
+/-- Start address of the private bit slot for a dense hidden-field ID, computed as the scratch
+base plus the ID times the slot stride. -/
+def Args.slot (g : Args W) (id : ℕ) := g.scratchBase + id*g.slotStride
+
+/-- The ten designated input registers hold the term parameters, private slot geometry, owner
+ordinal, and external count and row addresses required by the scan. -/
+structure Inputs (g : Args W) (reg : Fin 22 ↪ Fin r) (c : Config W p r) : Prop where
+ term : c.reg (reg 6) = g.termBase
+ termStride : c.reg (reg 7) = g.termStride
+ layout : c.reg (reg 8) = (g.layout.toNat : Word W)
+ selectors : c.reg (reg 9) = g.selectorBits
+ scratch : c.reg (reg 15) = (g.scratchBase : Word W)
+ stride : c.reg (reg 16) = (g.slotStride : Word W)
+ counts : c.reg (reg 17) = (g.countBase : Word W)
+ owner : c.reg (reg 18) = (g.owner : Word W)
+ rows : c.reg (reg 19) = (g.rowBase : Word W)
+ rowStride : c.reg (reg 20) = (g.rowStride : Word W)
+
+/-- The scan inputs are loaded, and registers 3 and 21 hold the constants one and zero for the
+loop counter and guard. -/
+structure Ready (g : Args W) (reg : Fin 22 ↪ Fin r) (c : Config W p r) : Prop extends Inputs g reg c where
+ one : c.reg (reg 3) = 1
+ zero : c.reg (reg 21) = 0
+
+/-- All modifications after the initial constant rows. -/
+def scratch : List (Fin 22) := [0,1,2,4,5,10,11,12,13,14]
+
+/-- The two configurations agree on every register outside the scan's embedded scratch
+registers. -/
+def Frame (reg : Fin 22 ↪ Fin r) (c d : Config W p r) :=
+ ∀ i, (∀ j ∈ scratch, i ≠ reg j) → d.reg i = c.reg i
+
+theorem Frame.trans {reg : Fin 22 ↪ Fin r} {a b c : Config W p r} (h : Frame reg a b) (h' : Frame reg b c) :
+ Frame reg a c := fun i hi => (h' i hi).trans (h i hi)
+
+theorem Frame.atReg {reg : Fin 22 ↪ Fin r} {c d : Config W p r} (h : Frame reg c d)
+ (j : Fin 22) (hj : j ∉ scratch) : d.reg (reg j) = c.reg (reg j) :=
+ h _ (fun _ ht => reg.injective.ne (fun eq => hj (eq ▸ ht)))
+
+theorem Ready.frame {reg : Fin 22 ↪ Fin r} {g : Args W} {c d : Config W p r}
+ (ready : Ready g reg c) (h : Frame reg c d) : Ready g reg d :=
+ ⟨⟨(h.atReg _ (by decide)).trans ready.term, (h.atReg _ (by decide)).trans ready.termStride,
+ (h.atReg _ (by decide)).trans ready.layout, (h.atReg _ (by decide)).trans ready.selectors,
+ (h.atReg _ (by decide)).trans ready.scratch, (h.atReg _ (by decide)).trans ready.stride,
+ (h.atReg _ (by decide)).trans ready.counts, (h.atReg _ (by decide)).trans ready.owner,
+ (h.atReg _ (by decide)).trans ready.rows, (h.atReg _ (by decide)).trans ready.rowStride⟩,
+ (h.atReg _ (by decide)).trans ready.one, (h.atReg _ (by decide)).trans ready.zero⟩
+
+theorem frame_put {reg : Fin 22 ↪ Fin r} (c : Config W p r) (next : Fin p) (j : Fin 22)
+ (v : Word W) (hj : j ∈ scratch) : Frame reg c (c.put next (reg j) v) :=
+ fun _ hi => Function.update_of_ne (hi j hj) _ _
+
+end PairSimulation.ShrinkHiddenGuess
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenControl.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenControl.lean
new file mode 100644
index 0000000000..292d031d78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenControl.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenCode
+
+/-!
+# Executing the shrinking hidden-array row control
+
+One count probe initializes the row. The guard uses the remaining number of
+entries, and the back edge advances the dense-ID pointer by one word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess
+
+open BurstRAM PrivateRAM NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.read ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {W p r k : ℕ} {M : Machine W p r k} {pc : Control → Fin p} {reg : Fin 22 ↪ Fin r}
+variable {width guess done : Fin p}
+
+private theorem control_step (link : ControlLinked M pc reg width guess done)
+ (j : Control) {c : Config W p r} (h : c.pc = pc j) :
+ M.program.step c = (control pc reg width guess done j).run M.publicData c := by
+ simp [Machine.program, h, link j]
+
+/-- The six events before the first loop test. They include one external read of the selected
+owner's count and five local steps. -/
+def setupEvents (m : Memory W) (g : Args W) : List (Event W) :=
+ [.tick, .tick, .tick, .read ((g.countBase + g.owner : ℕ) : Word W) (m (g.countBase + g.owner)),
+ .tick, .tick]
+
+/-- Load the count and the start of this owner's row, and establish the two
+constant registers used by the guard and back edge. -/
+theorem setup_run (link : ControlLinked M pc reg width guess done) (m : Memory W) (g : Args W)
+ (c : Config W p r) (hc : c.pc = pc .one) (inputs : Inputs g reg c)
+ (fit : g.countBase + g.owner < 2 ^ W) :
+ ∃ d, Prefix M m c d [] (setupEvents m g) ∧ d.pc = pc .test ∧
+ d.reg (reg 14) = m (g.countBase + g.owner) ∧ d.reg (reg 5) = (g.row : Word W) ∧
+ Ready g reg d ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ i, i ≠ reg 3 → i ≠ reg 5 → i ≠ reg 14 → i ≠ reg 21 → d.reg i = c.reg i := by
+ let addr := ((g.countBase + g.owner : ℕ) : Word W)
+ have val : addr.val = g.countBase + g.owner := by
+ exact Nat.mod_eq_of_lt fit
+ let one := c.put (pc .zero) (reg 3) 1
+ let zero := one.put (pc .countAddr) (reg 21) 0
+ let load := zero.put (pc .readCount) (reg 14) addr
+ let offset := load.put (pc .rowOffset) (reg 14) (m addr.val)
+ let start := offset.put (pc .rowStart) (reg 5) ((g.owner * g.rowStride : ℕ) : Word W)
+ let d := start.put (pc .test) (reg 5) (g.row : Word W)
+ have s₀ : M.program.step c = .localStep one := control_step link .one hc
+ have s₁ : M.program.step one = .localStep zero := control_step link .zero rfl
+ have s₂ : M.program.step zero = .localStep load := by
+ rw [control_step link .countAddr rfl]
+ change CallAction.localStep (zero.put _ _ (zero.reg (reg 17) + zero.reg (reg 18))) = _
+ simp [load, zero, one, Config.put, inputs.counts, inputs.owner, addr]
+ have s₃ : M.program.step load = .read addr (fun v => load.put (pc .rowOffset) (reg 14) v) := by
+ rw [control_step link .readCount rfl]
+ change CallAction.read (load.reg (reg 14)) _ = _
+ rw [Config.put_same]
+ have s₄ : M.program.step offset = .localStep start := by
+ rw [control_step link .rowOffset rfl]
+ change CallAction.localStep (offset.put _ _ (offset.reg (reg 18) * offset.reg (reg 20))) = _
+ simp [start, offset, load, zero, one, Config.put, inputs.owner, inputs.rowStride]
+ have s₅ : M.program.step start = .localStep d := by
+ rw [control_step link .rowStart rfl]
+ change CallAction.localStep (start.put _ _ (start.reg (reg 19) + start.reg (reg 5))) = _
+ simp [d, start, offset, load, zero, one, Config.put, inputs.rows, Args.row]
+ have path := ReadPrefix.tick (m := m) s₀ (ReadPrefix.tick s₁ (ReadPrefix.tick s₂
+ (ReadPrefix.read addr s₃ (ReadPrefix.tick s₄ (ReadPrefix.tick s₅ (ReadPrefix.nil _))))))
+ have keep (i : Fin r) (h₃ : i ≠ reg 3) (h₅ : i ≠ reg 5) (h₁₄ : i ≠ reg 14) (h₂₁ : i ≠ reg 21) :
+ d.reg i = c.reg i := by
+ simp [d, start, offset, load, zero, one, Config.put, Function.update_of_ne, h₃, h₅, h₁₄, h₂₁]
+ have same (j : Fin 22) (h₃ : j ≠ 3) (h₅ : j ≠ 5) (h₁₄ : j ≠ 14) (h₂₁ : j ≠ 21) :
+ d.reg (reg j) = c.reg (reg j) :=
+ keep _ (reg.injective.ne h₃) (reg.injective.ne h₅) (reg.injective.ne h₁₄) (reg.injective.ne h₂₁)
+ have params : Inputs g reg d := by
+ constructor <;> rw [same _ (by decide) (by decide) (by decide) (by decide)]
+ exacts
+ [inputs.term, inputs.termStride, inputs.layout, inputs.selectors, inputs.scratch,
+ inputs.stride, inputs.counts, inputs.owner, inputs.rows, inputs.rowStride]
+ refine ⟨d, ?_, rfl, ?_, Config.put_same .., ⟨params, ?_, ?_⟩, rfl, rfl, keep⟩
+ · intro fuel bs
+ simpa only [setupEvents, List.nil_append, val] using ReadPrefix.execute path fuel bs
+ · simp [d, start, offset, Config.put, val]
+ · simp [d, start, offset, load, zero, one, Config.put]
+ · simp [d, start, offset, load, zero, Config.put]
+
+/-- One local branch tests the remaining count, including a zero-length row. -/
+theorem test_run (link : ControlLinked M pc reg width guess done) (m : Memory W) (g : Args W)
+ (c : Config W p r) (hc : c.pc = pc .test) (ready : Ready g reg c)
+ (n : ℕ) (count : c.reg (reg 14) = (n : Word W)) (fit : n < 2 ^ W) :
+ ∃ d, Prefix M m c d [] [.tick] ∧ d.pc = (if n = 0 then done else width) ∧
+ d.reg = c.reg ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ let d := {c with pc := if n = 0 then done else width}
+ have eqzero : (n : Word W) = 0 ↔ n = 0 := by
+ constructor
+ · intro hz
+ have h := congrArg Fin.val hz
+ change n % (2 ^ W) = 0 at h
+ rwa [Nat.mod_eq_of_lt fit] at h
+ · rintro rfl
+ rfl
+ have step : M.program.step c = .localStep d := by
+ rw [control_step link .test hc]
+ change CallAction.localStep {c with pc := if c.reg (reg 14) = c.reg (reg 21) then done else width} = _
+ simp only [d, count, ready.zero, eqzero]
+ exact ⟨d, fun fuel bs => ReadPrefix.execute (ReadPrefix.tick step (ReadPrefix.nil _)) fuel bs,
+ rfl, rfl, rfl, rfl⟩
+
+/-- The two local back-edge instructions consume one row entry and advance
+the ID pointer, preserving the field buffers and the loop's stable registers. -/
+theorem advance_run (link : ControlLinked M pc reg width guess done) (m : Memory W) (g : Args W)
+ (c : Config W p r) (hc : c.pc = pc .decrement) (ready : Ready g reg c) (rem ptr : ℕ)
+ (count : c.reg (reg 14) = ((rem + 1 : ℕ) : Word W)) (pointer : c.reg (reg 5) = (ptr : Word W)) :
+ ∃ d, Prefix M m c d [] [.tick, .tick] ∧ d.pc = pc .test ∧
+ d.reg (reg 14) = (rem : Word W) ∧ d.reg (reg 5) = ((ptr + 1 : ℕ) : Word W) ∧
+ Frame reg c d ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ let next := c.put (pc .advance) (reg 14) (rem : Word W)
+ let d := next.put (pc .test) (reg 5) ((ptr + 1 : ℕ) : Word W)
+ have s₀ : M.program.step c = .localStep next := by
+ rw [control_step link .decrement hc]
+ change CallAction.localStep (c.put _ _ (c.reg (reg 14) - c.reg (reg 3))) = _
+ simp [next, count, ready.one]
+ have s₁ : M.program.step next = .localStep d := by
+ rw [control_step link .advance rfl]
+ change CallAction.localStep (next.put _ _ (next.reg (reg 5) + next.reg (reg 3))) = _
+ simp [d, next, Config.put, pointer, ready.one]
+ exact ⟨d, fun fuel bs => ReadPrefix.execute
+ (ReadPrefix.tick s₀ (ReadPrefix.tick s₁ (ReadPrefix.nil _))) fuel bs, rfl,
+ by simp [d, next, Config.put], Config.put_same ..,
+ (frame_put c _ 14 _ (by decide)).trans (frame_put next _ 5 _ (by decide)), rfl, rfl⟩
+
+end PairSimulation.ShrinkHiddenGuess
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenCost.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenCost.lean
new file mode 100644
index 0000000000..f065a96c63
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenCost.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenGuess
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-! # Exact branch stream, reads and clock for a native hidden-field scan -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+variable {W : ℕ}
+
+private theorem field_cost (g : Args W) (m : Memory W) (ptr : ℕ) (e : Row) :
+ (fieldEvents g m ptr e).length = 22+6*e.2.length ∧
+ countProbes (fieldEvents g m ptr e) = 3 ∧ choiceBits (fieldEvents g m ptr e) = e.2 := by
+ let id := m (ptr : Word W).val
+ have hdr := ShrinkHiddenWidth.cost m (ptr : Word W)
+ (ShrinkHiddenWidth.rowBase g.termBase g.termStride id)
+ (ShrinkHiddenWidth.coordinate (g.layout.toNat : Word W) id)
+ change (g.header m (ptr : Word W)).length = 18 ∧ countProbes (g.header m (ptr : Word W)) = 3 ∧
+ choiceBits (g.header m (ptr : Word W)) = [] at hdr
+ obtain ⟨len, probes, bits⟩ := hdr
+ have hf := PrivateFields.events_work (w := W) .guess e.2
+ simp [fieldEvents, len, countProbes_append, probes, hf, countProbes, choiceBits,
+ PrimedInputRAM.Flow.choiceBits_append, bits, PrivateFields.events_bits]
+ omega
+
+private theorem loop_cost (g : Args W) (m : Memory W) (ptr : ℕ) (es : List Row) :
+ (loopEvents g m ptr es).length = 1+25*es.length+6*(stream es).length ∧
+ countProbes (loopEvents g m ptr es) = 3*es.length ∧ choiceBits (loopEvents g m ptr es) = stream es := by
+ induction es generalizing ptr with
+ | nil => simp [loopEvents, countProbes, choiceBits, stream]
+ | cons e es ih =>
+ obtain ⟨hlen, hpr, hbs⟩ := ih (ptr+1)
+ obtain ⟨len, probes, bits⟩ := field_cost g m ptr e
+ simp only [stream] at hlen hbs
+ simp only [loopEvents, List.length_append, List.length_cons, List.length_nil, hlen, len,
+ countProbes_append, countProbes, probes, hpr, PrimedInputRAM.Flow.choiceBits_append, choiceBits,
+ bits, hbs, stream, List.flatMap_cons, List.append_nil, Nat.mul_add]
+ exact ⟨by omega, by omega, trivial⟩
+
+/-- The only external probes are one count word and three words per field.
+Each independently guessed bit is present exactly once in the native trace. -/
+theorem cost (g : Args W) (m : Memory W) (es : List Row) :
+ (events g m es).length = 7+25*es.length+6*(stream es).length ∧
+ countProbes (events g m es) = 1+3*es.length ∧ choiceBits (events g m es) = stream es := by
+ obtain ⟨hlen,hpr,hbs⟩ := loop_cost g m g.row es
+ simp only [events, List.length_append, countProbes_append, PrimedInputRAM.Flow.choiceBits_append, hlen,hpr,hbs]
+ simp [setupEvents, countProbes, choiceBits]
+ omega
+
+end PairSimulation.ShrinkHiddenGuess
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenDecode.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenDecode.lean
new file mode 100644
index 0000000000..e1de6c5bd4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenDecode.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenGuess
+
+/-!
+# Decoding an arbitrary complete native hidden-field stream
+
+The same field widths that the native loop reads determine a partition of
+any sufficiently long bit list. This includes empty fields and preserves
+the remaining bits for the next node operation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess
+
+open BurstRAM PrivateRAM NodeArguments.ChildScan
+
+variable {W p r k : ℕ}
+
+/-- Replace each field's bits, retaining its ID and consuming its recorded width. -/
+def decode : List Row → List Bool → List Row × List Bool
+ | [], bs => ([],bs)
+ | e::es, bs =>
+ let next := decode es (bs.drop e.2.length)
+ ((e.1,bs.take e.2.length)::next.1,next.2)
+
+private theorem decode_at (g : Args W) (m : Memory W) (es : List Row) (ptr : ℕ)
+ (ok : ∀ i : Fin es.length, ValidAt g m (ptr+i.val) es[i.val]) (bs : List Bool)
+ (enough : (stream es).length ≤ bs.length) :
+ let d := decode es bs
+ d.1.length = es.length ∧ stream d.1 ++ d.2 = bs ∧
+ ∀ i : Fin d.1.length, ValidAt g m (ptr+i.val) d.1[i.val] := by
+ induction es generalizing ptr bs with
+ | nil => exact ⟨rfl,rfl,fun i => Fin.elim0 i⟩
+ | cons e es ih =>
+ have len : e.2.length + (stream es).length ≤ bs.length := by simpa only [stream,List.flatMap_cons,List.length_append] using enough
+ have eqLen : (bs.take e.2.length).length = e.2.length := by simp [Nat.min_eq_left (by omega : e.2.length ≤ bs.length)]
+ have vs (i : Fin es.length) : ValidAt g m (ptr+1+i.val) es[i.val] := by
+ simpa only [Fin.val_succ,List.getElem_cons_succ,← Nat.add_assoc,Nat.add_right_comm] using ok i.succ
+ have ve : ValidAt g m ptr e := by simpa using ok 0
+ obtain ⟨size, part, tail⟩ := ih (ptr+1) vs (bs.drop e.2.length) (by simp; omega)
+ refine ⟨congrArg Nat.succ size,?_,?_⟩
+ · change bs.take e.2.length ++ stream (decode es (bs.drop e.2.length)).1 ++ (decode es (bs.drop e.2.length)).2 = bs
+ rw [List.append_assoc,part,List.take_append_drop]
+ · intro i
+ refine Fin.cases ?_ (fun j => ?_) i
+ · simpa only [Fin.val_zero,Nat.add_zero,List.getElem_cons_zero,decode,ValidAt,eqLen] using ve
+ · simpa only [Fin.val_succ,List.getElem_cons_succ,decode,← Nat.add_assoc,Nat.add_right_comm] using tail j
+
+/-- The decoder drops exactly the total number of requested field bits. -/
+theorem decode_tail (es : List Row) (bs : List Bool) :
+ (decode es bs).2 = bs.drop (stream es).length := by
+ induction es generalizing bs with
+ | nil => rfl
+ | cons e es ih =>
+ change (decode es (bs.drop e.2.length)).2 = _
+ rw [ih,List.drop_drop]
+ simp only [stream,List.flatMap_cons,List.length_append]
+
+/-- Sufficient input determines both the actual accepted prefix and its tail. -/
+theorem decode_valid (g : Args W) (m : Memory W) (es : List Row) (ok : ValidRows g m es)
+ (bs : List Bool) (enough : (stream es).length ≤ bs.length) :
+ let d := decode es bs
+ d.1.length = es.length ∧ stream d.1 ++ d.2 = bs ∧ ValidRows g m d.1 :=
+ decode_at g m es g.row ok bs enough
+
+/-- The actual native run from a raw stream writes the decoded fields and
+passes the exact remaining suffix to its continuation. -/
+theorem native_decode {M : Machine W p r k} {pc : Stage → Fin p} {reg : Fin 22 ↪ Fin r} {done : Fin p}
+ (link : Linked M pc reg done) (g : Args W) (m : Memory W) (es : List Row)
+ (c : Config W p r) (entry : c.pc = pc (.inl .one)) (inputs : Inputs g reg c)
+ (fit : g.countBase+g.owner < 2^W) (count : (m (g.countBase+g.owner)).val = es.length)
+ (ok : ValidRows g m es) (bs : List Bool) (enough : (stream es).length ≤ bs.length) :
+ let parsed := decode es bs
+ ∃ d, d.pc = done ∧ d.privateMem = storeRows g.scratchBase g.slotStride parsed.1 c.privateMem ∧
+ d.persistent = c.persistent ∧ ∀ fuel, execute M.program (fuel+(events g m parsed.1).length) c m bs =
+ (execute M.program fuel d m parsed.2).map (fun q => ⟨events g m parsed.1 ++ q.events,q.result⟩) := by
+ obtain ⟨len,part,valid⟩ := decode_valid g m es ok bs enough
+ obtain ⟨d,pref,endPC,_,priv,pers⟩ := native link g m (decode es bs).1 c entry inputs fit (count.trans len.symm) valid
+ refine ⟨d,endPC,priv,pers,fun fuel => ?_⟩
+ have path := pref fuel (decode es bs).2
+ rwa [part] at path
+
+end PairSimulation.ShrinkHiddenGuess
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenFootprint.lean
new file mode 100644
index 0000000000..751c7535bc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenFootprint.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenInputs
+import OAI.Computability.VPVNP.CompressorRegisterSetupTrace
+
+/-!
+# External addresses read by the absorbed-field scan
+
+The setup reads five cells in the old-level header. The loop reads the
+owner count, one dense ID per field, and the repetition and payload cells
+of the selected term. The private guesses perform no external accesses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess
+
+open BurstRAM PrivateRAM CompressorRecords PhaseRecipe SourceTransport
+open scoped Fin.CommRing
+open private headEvents from OAI.Computability.VPVNP.PairSimulationPrivateFields
+open private reads_append from OAI.Computability.VPVNP.CompressorFormulaFootprint
+
+variable {W p r : ℕ}
+
+/-- All chronological header probes belong to the five selected cells. -/
+theorem Header.trace_reads (D : ℕ → Prop) (s t : ℕ) (inputs : Fin 6 → Fin r)
+ (vm : Fin (RegisterSetup.regCount (Header.recipe s t)) ↪ Fin r)
+ (c : Config W p r) (m : Memory W) (oldLevel : ℕ)
+ (level : c.reg (inputs 5) = (oldLevel : Word W)) (fit : oldLevel+38 < 2^W)
+ (allowed : ∀ j ∈ ([31,32,36,37,38] : List ℕ), D (oldLevel+j)) :
+ Reads D (Header.trace s t inputs vm c m) := by
+ apply RegisterSetup.lines_reads
+ intro i
+ let pub := fun j : Fin 5 => c.reg (inputs j.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ have head (j : ℕ) (hj : j ∈ ([31,32,36,37,38] : List ℕ)) :
+ (Expr.header j).ReadsFrom D pub state m := by
+ have lim : j ≤ 38 := by simp only [List.mem_cons,List.not_mem_nil,or_false] at hj; omega
+ refine ⟨⟨trivial,trivial⟩,?_⟩
+ change D ((c.reg (inputs 5))+(j : Word W)).val
+ rw [level,← Nat.cast_add,Fin.val_cast_of_lt (by omega : oldLevel+j < 2^W)]
+ exact allowed j hj
+ fin_cases i <;> first | exact head _ (by decide) | trivial
+
+private theorem private_reads (D : ℕ → Prop) (bs : List Bool) : Reads D (PrivateFields.events (w := W) .guess bs) := by
+ induction bs with
+ | nil => simp [PrivateFields.events,Reads]
+ | cons b bs ih =>
+ apply reads_append _ ih
+ simp [headEvents,Reads]
+
+/-- The three addresses of one field's actual external reads. -/
+def FieldCells (D : ℕ → Prop) (g : Args W) (m : Memory W) (ptr : ℕ) :=
+ let a : Word W := ptr
+ let id := m a.val
+ let base := ShrinkHiddenWidth.rowBase g.termBase g.termStride id
+ let coord := ShrinkHiddenWidth.coordinate (g.layout.toNat : Word W) id
+ D a.val ∧ D (base+1).val ∧ D (base+2+coord).val
+
+theorem field_reads (D : ℕ → Prop) (g : Args W) (m : Memory W) (ptr : ℕ) (e : Row)
+ (cells : FieldCells D g m ptr) : Reads D (fieldEvents g m ptr e) := by
+ apply reads_append _ (private_reads D e.2)
+ refine reads_append ?_ ?_
+ swap
+ · intro a v h; simp at h
+ intro a v h
+ simp only [Args.header,ShrinkHiddenWidth.events,List.mem_cons,List.not_mem_nil,Event.read.injEq,
+ reduceCtorEq,false_or,or_false] at h
+ obtain (⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩) := h
+ exacts [cells.1,cells.2.1,cells.2.2]
+
+private theorem loop_reads (D : ℕ → Prop) (g : Args W) (m : Memory W) (es : List Row) (ptr : ℕ)
+ (cells : ∀ i : Fin es.length, FieldCells D g m (ptr+i.val)) : Reads D (loopEvents g m ptr es) := by
+ induction es generalizing ptr with
+ | nil => simp [loopEvents,Reads]
+ | cons e es ih =>
+ apply reads_append _ (ih (ptr+1) fun j => by
+ simpa only [Fin.val_succ,← Nat.add_assoc,Nat.add_right_comm] using cells j.succ)
+ intro a v h
+ simp only [List.mem_cons,List.mem_append,List.not_mem_nil,reduceCtorEq,false_or,or_false] at h
+ exact field_reads D g m ptr e (by simpa using cells 0) a v h
+
+theorem events_reads (D : ℕ → Prop) (g : Args W) (m : Memory W) (es : List Row)
+ (count : D ((g.countBase+g.owner : ℕ) : Word W).val)
+ (cells : ∀ i : Fin es.length, FieldCells D g m (g.row+i.val)) : Reads D (events g m es) := by
+ apply reads_append _ (loop_reads D g m es g.row cells)
+ intro a v h
+ simp only [setupEvents,List.mem_cons,List.not_mem_nil,Event.read.injEq,reduceCtorEq,false_or,or_false] at h
+ exact h.1 ▸ count
+
+end PairSimulation.ShrinkHiddenGuess
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenGuess.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenGuess.lean
new file mode 100644
index 0000000000..1d88b52bb4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenGuess.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenStep
+import OAI.Computability.VPVNP.PairShrinkHiddenControl
+
+/-!
+# Executing the complete absorbed-field row
+
+The native count probe controls a forward scan of the selected owner's ID
+directory. Each iteration reads its actual term cells and consumes one
+independent field in the restricted order. The private storage is indexed
+by dense ID, so both motif incidences refer to the same guessed bit word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess
+
+open BurstRAM PrivateRAM NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {W p r k : ℕ} {M : Machine W p r k} {pc : Stage → Fin p} {reg : Fin 22 ↪ Fin r} {done : Fin p}
+
+/-- Trace of the forward scan from the current ID pointer. Each field contributes a guard test,
+its field trace, and two steps to decrement and advance. The final event tests the empty
+remainder. -/
+def loopEvents (g : Args W) (m : Memory W) : ℕ → List Row → List (Event W)
+ | _, [] => [.tick]
+ | ptr, e :: es => (.tick :: fieldEvents g m ptr e ++ [.tick,.tick]) ++ loopEvents g m (ptr+1) es
+
+/-- Trace from initialization through the final loop test, scanning the supplied fields in
+order from the owner's row start. -/
+def events (g : Args W) (m : Memory W) (es : List Row) :=
+ setupEvents m g ++ loopEvents g m g.row es
+
+/-- The choice stream for an ordered row of hidden fields, formed by concatenating their bit
+lists in scan order. -/
+def stream (rows : List Row) := rows.flatMap Prod.snd
+
+private theorem suffixValid (g : Args W) (m : Memory W) (ptr : ℕ) (e : Row) (es : List Row)
+ (h : ∀ i : Fin (e::es).length, ValidAt g m (ptr+i.val) (e::es)[i.val]) :
+ ValidAt g m ptr e ∧ ∀ i : Fin es.length, ValidAt g m (ptr+1+i.val) es[i.val] := by
+ refine ⟨by simpa using h 0, fun i => ?_⟩
+ simpa only [Fin.val_succ, List.getElem_cons_succ, ← Nat.add_assoc, Nat.add_right_comm] using h i.succ
+
+private theorem tested {g : Args W} {m : Memory W} {c : Config W p r} (link : Linked M pc reg done)
+ (entry : c.pc = pc (.inl .test)) (ready : Ready g reg c) (n : ℕ)
+ (count : c.reg (reg 14) = (n : Word W)) (fit : n < 2^W) :
+ ∃ d, Prefix M m c d [] [.tick] ∧ d.pc = (if n=0 then done else pc (.inr (.inl 0))) ∧
+ d.reg = c.reg ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent :=
+ test_run (controls link) m g c entry ready n count fit
+
+private theorem iteration_run (link : Linked M pc reg done) (g : Args W) (m : Memory W) (c : Config W p r)
+ (ptr rem : ℕ) (e : Row) (entry : c.pc = pc (.inl .test)) (ready : Ready g reg c)
+ (count : c.reg (reg 14) = ((rem+1 : ℕ) : Word W)) (pointer : c.reg (reg 5) = (ptr : Word W))
+ (countFit : rem+1 < 2^W) (valid : ValidAt g m ptr e) :
+ ∃ d, Prefix M m c d e.2 (.tick :: fieldEvents g m ptr e ++ [.tick,.tick]) ∧
+ d.pc = pc (.inl .test) ∧ d.reg (reg 14) = (rem : Word W) ∧ d.reg (reg 5) = ((ptr+1 : ℕ) : Word W) ∧
+ Frame reg c d ∧ d.privateMem = PrivateFields.storeBits (g.slot e.1) e.2 c.privateMem ∧
+ d.persistent = c.persistent := by
+ obtain ⟨a, guard, hpc, hreg, hmem, hper⟩ := tested (m := m) link entry ready (rem+1) count countFit
+ have fa : Frame reg c a := fun i _ => congrFun hreg i
+ have ra := ready.frame fa
+ obtain ⟨b, body, hb, h5, h14, fb, bm, bp⟩ := field_run link g m a ptr e
+ (by simpa using hpc) ra (hreg ▸ pointer) valid
+ obtain ⟨d, tail, hd, dc, dp, fd, dm, ds⟩ := advance_run (controls link) m g b hb
+ (ra.frame fb) rem ptr (h14.trans ((congrFun hreg _).trans count)) (h5.trans ((congrFun hreg _).trans pointer))
+ refine ⟨d, ?_, hd, dc, dp, (fa.trans fb).trans fd, ?_, ds.trans (bp.trans hper)⟩
+ · simpa only [List.nil_append, List.append_nil, List.singleton_append, List.cons_append] using
+ (guard.trans body).trans tail
+ · rw [dm, bm, hmem]
+
+private theorem loop_run (link : Linked M pc reg done) (g : Args W) (m : Memory W) (es : List Row)
+ (c : Config W p r) (ptr : ℕ) (entry : c.pc = pc (.inl .test)) (ready : Ready g reg c)
+ (count : c.reg (reg 14) = (es.length : Word W)) (pointer : c.reg (reg 5) = (ptr : Word W))
+ (countFit : es.length < 2^W) (valid : ∀ i : Fin es.length, ValidAt g m (ptr+i.val) es[i.val]) :
+ ∃ d, Prefix M m c d (stream es) (loopEvents g m ptr es) ∧ d.pc = done ∧ Frame reg c d ∧
+ d.privateMem = storeRows g.scratchBase g.slotStride es c.privateMem ∧ d.persistent = c.persistent := by
+ induction es generalizing ptr c with
+ | nil =>
+ obtain ⟨d, pref, hpc, hreg, hm, hp⟩ := tested (m := m) link entry ready 0 count countFit
+ exact ⟨d,pref,hpc,fun i _ => congrFun hreg i,hm,hp⟩
+ | cons e es ih =>
+ obtain ⟨ve, vs⟩ := suffixValid g m ptr e es valid
+ obtain ⟨a, step, hep, hcount, hptr, fa, hm, hp⟩ :=
+ iteration_run link g m c ptr es.length e entry ready count pointer countFit ve
+ obtain ⟨d, tail, hd, fd, dm, ds⟩ := ih a (ptr+1) hep (ready.frame fa) hcount hptr
+ (by simpa using Nat.lt_trans (Nat.lt_succ_self es.length) countFit) vs
+ refine ⟨d, step.trans tail, hd, fa.trans fd, ?_, ds.trans hp⟩
+ rw [dm,hm]
+ rfl
+
+/-- Exact native prefix, including the public count probe, all field bits,
+and the final empty test. The continuation receives the unconsumed suffix. -/
+theorem native (link : Linked M pc reg done) (g : Args W) (m : Memory W) (es : List Row)
+ (c : Config W p r) (entry : c.pc = pc (.inl .one)) (inputs : Inputs g reg c)
+ (fit : g.countBase+g.owner < 2^W) (count : (m (g.countBase+g.owner)).val = es.length)
+ (valid : ValidRows g m es) :
+ ∃ d, Prefix M m c d (stream es) (events g m es) ∧ d.pc = done ∧
+ (∀ i, i ≠ reg 3 → i ≠ reg 21 → (∀ j ∈ scratch, i ≠ reg j) → d.reg i = c.reg i) ∧
+ d.privateMem = storeRows g.scratchBase g.slotStride es c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨a, init, ep, hc, hp, ready, hm, hs, keep⟩ := setup_run (controls link) m g c entry inputs fit
+ have cf : es.length < 2^W := count ▸ (m (g.countBase+g.owner)).isLt
+ have hcount : a.reg (reg 14) = (es.length : Word W) := by
+ apply Fin.ext
+ rw [hc, count, Fin.val_natCast, Nat.mod_eq_of_lt cf]
+ obtain ⟨d, tail, hd, frame, dm, ds⟩ := loop_run link g m es a g.row ep ready hcount hp cf valid
+ exact ⟨d, init.trans tail, hd, fun i h3 h21 hi => (frame i hi).trans (keep i h3
+ (hi 5 (by decide)) (hi 14 (by decide)) h21), dm.trans (congrArg _ hm), ds.trans hs⟩
+
+/-- With any shorter stream, all complete leading fields still run once.
+The first incomplete field prevents the burst from returning. -/
+private theorem loop_short (link : Linked M pc reg done) (g : Args W) (m : Memory W) (es : List Row)
+ (c : Config W p r) (ptr : ℕ) (entry : c.pc = pc (.inl .test)) (ready : Ready g reg c)
+ (count : c.reg (reg 14) = (es.length : Word W)) (pointer : c.reg (reg 5) = (ptr : Word W))
+ (countFit : es.length < 2^W) (valid : ∀ i : Fin es.length, ValidAt g m (ptr+i.val) es[i.val])
+ (bs : List Bool) (short : bs.length < (stream es).length) : ¬ DFS.Returns M c m bs := by
+ induction es generalizing ptr c bs with
+ | nil => simp [stream] at short
+ | cons e es ih =>
+ obtain ⟨ve, vs⟩ := suffixValid g m ptr e es valid
+ by_cases h : bs.length < e.2.length
+ · obtain ⟨d, test, hpc, hr, _, _⟩ := tested (m := m) link entry ready (es.length+1) count countFit
+ apply mt (test.returns bs).mp
+ exact field_short link g m d ptr e (by simpa using hpc)
+ (ready.frame (fun i _ => congrFun hr i)) (hr ▸ pointer) ve bs h
+ · let first : Row := (e.1, bs.take e.2.length)
+ have eqLen : first.2.length = e.2.length := by simpa [first] using Nat.min_eq_left (by omega : e.2.length ≤ bs.length)
+ have vf : ValidAt g m ptr first := ⟨ve.1, ve.2.1.trans eqLen.symm, eqLen ▸ ve.2.2⟩
+ obtain ⟨a, step, ep, hc, hp, fr, _, _⟩ :=
+ iteration_run link g m c ptr es.length first entry ready count pointer countFit vf
+ have reject := ih a (ptr+1) ep (ready.frame fr) hc hp
+ (by simpa using Nat.lt_trans (Nat.lt_succ_self es.length) countFit) vs (bs.drop e.2.length) (by
+ simp only [stream, List.flatMap_cons, List.length_append] at short
+ simp only [stream, List.length_drop]; omega)
+ have back := mt (step.returns (bs.drop e.2.length)).mp reject
+ simpa only [first, List.take_append_drop] using back
+
+theorem native_short (link : Linked M pc reg done) (g : Args W) (m : Memory W) (es : List Row)
+ (c : Config W p r) (entry : c.pc = pc (.inl .one)) (inputs : Inputs g reg c)
+ (fit : g.countBase+g.owner < 2^W) (count : (m (g.countBase+g.owner)).val = es.length)
+ (valid : ValidRows g m es) (bs : List Bool) (short : bs.length < (stream es).length) :
+ ¬ DFS.Returns M c m bs := by
+ obtain ⟨a, init, ep, hc, hp, ready, _, _, _⟩ := setup_run (controls link) m g c entry inputs fit
+ have cf : es.length < 2^W := count ▸ (m (g.countBase+g.owner)).isLt
+ have hcount : a.reg (reg 14) = (es.length : Word W) := by
+ apply Fin.ext
+ rw [hc, count, Fin.val_natCast, Nat.mod_eq_of_lt cf]
+ exact mt (init.returns bs).mp (loop_short link g m es a g.row ep ready hcount hp cf valid bs short)
+
+end PairSimulation.ShrinkHiddenGuess
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenHeaderTrace.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenHeaderTrace.lean
new file mode 100644
index 0000000000..a029952c33
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenHeaderTrace.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenInputs
+import OAI.Computability.VPVNP.CompressorRegisterSetupTrace
+import OAI.Computability.VPVNP.PairShrinkRoleStages
+
+/-!
+# Canonical trace of the hidden-field header
+
+The five external probes in the hidden-field header read offsets of the same
+old-level pointer. The compiled address calculation overwrites its temporaries
+before each probe. Its trace is therefore independent of the previous register
+contents, including the registers used for the owner and private slot geometry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess.Header
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords PrimedStackRAM PhaseRecipe RowRecipe
+open scoped Fin.CommRing
+open private compile_value from OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe
+open private log_append from OAI.Computability.VPVNP.CompressorFormulaFootprint
+open private room scratch_val from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+
+variable {w r : ℕ}
+
+/-- Each non-read assignment takes one local step, for every initial register file. -/
+private theorem allTicks (pub : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (ls : List (Assign r 5)) (rs : Regs w r) (zero : (ls.map fun l => l.rhs.reads).sum = 0) :
+ (evaluate pub s m ls rs).1 = List.replicate ls.length .tick := by
+ induction ls generalizing rs with
+ | nil => rfl
+ | cons a ls ih =>
+ simp only [List.map_cons, List.sum_cons, Nat.add_eq_zero_iff] at zero
+ have event : a.rhs.event m rs = .tick := by
+ cases ha : a.rhs with
+ | read i => simp [ha, RHS.reads] at zero
+ | _ => rfl
+ simp only [evaluate, event, ih _ zero.2, List.length_cons, List.replicate_succ]
+
+private theorem compile_noReads (pub pub' : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (slot : ℕ → Fin r) (rs rs' : Regs w r) (e : Expr) (quiet : e.loads = 0) :
+ (evaluate pub s m (e.compile slot 0) rs).1 = (evaluate pub' s m (e.compile slot 0) rs').1 :=
+ let zero := (Expr.compile_reads e slot 0).trans quiet
+ (allTicks pub s m _ rs zero).trans (allTicks pub' s m _ rs' zero).symm
+
+private theorem compile_header (pub pub' : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (slot : ℕ → Fin r) (rs rs' : Regs w r) (i cap : ℕ)
+ (fit : (Expr.header i).slots ≤ cap)
+ (inj : ∀ x < cap, ∀ y < cap, slot x = slot y → x = y) :
+ (evaluate pub s m ((Expr.header i).compile slot 0) rs).1 =
+ (evaluate pub' s m ((Expr.header i).compile slot 0) rs').1 := by
+ let e := Expr.headerAddress i
+ have hf : 0 + e.slots ≤ cap := by rw [Nat.zero_add]; exact fit
+ have addr (b : Fin 5 → Word w) (v : Regs w r) :
+ (evaluate b s m (e.compile slot 0) v).2 (slot 0) = s + (i : Word w) :=
+ compile_value b s m e slot cap 0 v hf inj
+ simp only [Expr.header, Expr.compile, log_append, evaluate, RHS.event]
+ rw [compile_noReads pub pub' s m slot rs rs' (Expr.headerAddress i) rfl, addr, addr]
+
+private theorem emit_congr (n t : ℕ) (pub pub' : Fin 5 → Word w) (s : Word w) (m : Memory w)
+ (i : Fin 10) (rs rs' : Regs w (RegisterSetup.regCount (recipe n t))) :
+ (evaluate pub s m (RegisterSetup.emit (recipe n t) i) rs).1 =
+ (evaluate pub' s m (RegisterSetup.emit (recipe n t) i) rs').1 := by
+ let f := recipe n t
+ let slot := RegisterSetup.scratch f
+ have inj : ∀ x < RegisterSetup.scratchCount f, ∀ y < RegisterSetup.scratchCount f,
+ slot x = slot y → x = y := by
+ intro x hx y hy h
+ have h' := congrArg Fin.val h
+ rw [show (slot x).val = _ from scratch_val f hx,
+ show (slot y).val = _ from scratch_val f hy] at h'
+ omega
+ simp only [RegisterSetup.emit, log_append, evaluate, RHS.event]
+ congr 1
+ have fit := room f i
+ have kinds : (f i).loads = 0 ∨ ∃ j, f i = Expr.header j := by
+ fin_cases i <;> simp [f, recipe, Expr.loads, Expr.header]
+ rcases kinds with quiet | ⟨j, he⟩
+ · exact compile_noReads pub pub' s m slot rs rs' _ quiet
+ · change (evaluate pub s m ((f i).compile slot 0) rs).1 =
+ (evaluate pub' s m ((f i).compile slot 0) rs').1
+ rw [he] at fit ⊢
+ exact compile_header pub pub' s m slot rs rs' j _ fit inj
+
+/-- Fixing the old level pointer determines the complete chronological log.
+The word size and the selected stage constants may vary. -/
+theorem headerTrace_congr (selectors stride : ℕ) (pub pub' : Fin 5 → Word w) (s : Word w)
+ (m : Memory w) (rs rs' : Regs w (RegisterSetup.regCount (recipe selectors stride))) :
+ (evaluate pub s m (RegisterSetup.lines (recipe selectors stride)) rs).1 =
+ (evaluate pub' s m (RegisterSetup.lines (recipe selectors stride)) rs').1 := by
+ let f := recipe selectors stride
+ suffices h : ∀ (is : List (Fin 10)) (a b : Regs w (RegisterSetup.regCount f)),
+ (evaluate pub s m (is.flatMap (RegisterSetup.emit f)) a).1 =
+ (evaluate pub' s m (is.flatMap (RegisterSetup.emit f)) b).1 from h _ rs rs'
+ intro is
+ induction is with
+ | nil => intros; rfl
+ | cons i is ih =>
+ intro a b
+ simp only [List.flatMap_cons, log_append]
+ exact congrArg₂ List.append (emit_congr selectors stride pub pub' s m i a b) (ih _ _)
+
+/-- Canonical header trace from its external pointer and memory. -/
+def canonicalTrace (selectors stride : ℕ) (s : Word w) (m : Memory w) : List (Event w) :=
+ (evaluate (fun _ => 0) s m (RegisterSetup.lines (recipe selectors stride)) (fun _ => 0)).1
+
+theorem trace_canonical {p : ℕ} (selectors stride : ℕ) (inputs : Fin 6 → Fin r)
+ (vm : Fin (RegisterSetup.regCount (recipe selectors stride)) ↪ Fin r)
+ (c : Config w p r) (m : Memory w) (s : Word w) (level : c.reg (inputs 5) = s) :
+ trace selectors stride inputs vm c m = canonicalTrace selectors stride s m := by
+ unfold trace canonicalTrace
+ rw [show c.reg (inputs (Fin.last 5)) = s from level]
+ exact headerTrace_congr selectors stride _ _ _ _ _ _
+
+end PairSimulation.ShrinkHiddenGuess.Header
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenInputs.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenInputs.lean
new file mode 100644
index 0000000000..0d30e1e781
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenInputs.lean
@@ -0,0 +1,111 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenGuess
+import OAI.Computability.VPVNP.CompressorRegisterSetupTrace
+
+/-!
+# Loading the published addresses used by the absorbed-field scan
+
+The live old-level header contains the owner-count and ordered-row heads, the
+term array's base and stride, and the selected layout. Stage constants use
+the native binary literal compiler. The owner and private slot geometry come
+from the enclosing node visit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess.Header
+
+open BurstRAM PrivateRAM CompressorRecords PhaseRecipe NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+/-- The ten expressions that initialize the scan from five old-level header cells, the owner's
+three live operands, and the selector-width and row-stride literals. -/
+def recipe (selectorBits rowStride : ℕ) : Fin 10 → Expr :=
+ ![.header 36, .header 37, .header 38, .lit selectorBits, .publicWord 1, .publicWord 2,
+ .header 31, .publicWord 0, .header 32, .lit rowStride]
+
+/-- Map each of the ten header recipe outputs to its destination in the scan's 22-register
+bank. -/
+def target : Fin 10 → Fin 22 := ![6,7,8,9,15,16,17,18,19,20]
+
+variable {W p r k : ℕ}
+
+/-- Absolute old-level header cells in the completed external directory. -/
+structure Published (g : Args W) (oldLevel : ℕ) (m : Memory W) : Prop where
+ counts : m (oldLevel+31) = (g.countBase : Word W)
+ rows : m (oldLevel+32) = (g.rowBase : Word W)
+ term : m (oldLevel+36) = g.termBase
+ stride : m (oldLevel+37) = g.termStride
+ layout : m (oldLevel+38) = (g.layout.toNat : Word W)
+
+/-- The chronological instruction trace of the header compiler. -/
+def trace (selectors rowStride : ℕ) (inputs : Fin 6 → Fin r)
+ (vm : Fin (RegisterSetup.regCount (recipe selectors rowStride)) ↪ Fin r)
+ (c : Config W p r) (m : Memory W) : List (Event W) :=
+ (RowRecipe.evaluate (fun i : Fin 5 => c.reg (inputs i.castSucc)) (c.reg (inputs (Fin.last 5)))
+ m (RegisterSetup.lines (recipe selectors rowStride)) (fun i => c.reg (vm i))).1
+
+/-- Each of the five external values is read once. No guesses are consumed
+and the private memory remains available to the actual hidden loop. -/
+theorem raw_run (M : Machine W p r k) (g : Args W) (m : Memory W) (oldLevel : ℕ)
+ (selectors rowStride : ℕ) (sel : g.selectorBits = (selectors : Word W)) (stride : g.rowStride = rowStride)
+ (inputs : Fin 6 → Fin r) (pc : ℕ → Fin p) (reg : Fin 22 ↪ Fin r)
+ (vm : Fin (RegisterSetup.regCount (recipe selectors rowStride)) ↪ Fin r)
+ (link : RegisterSetup.Linked vm inputs M pc (RegisterSetup.lines (recipe selectors rowStride)))
+ (safe : ∀ i j, vm i ≠ inputs j)
+ (outputs : ∀ i, vm (RegisterSetup.output (recipe selectors rowStride) i) = reg (target i))
+ (c : Config W p r) (atStart : c.pc = pc 0) (hL : c.reg (inputs 5) = (oldLevel : Word W))
+ (ho : c.reg (inputs 0) = (g.owner : Word W)) (hs : c.reg (inputs 1) = (g.scratchBase : Word W))
+ (hz : c.reg (inputs 2) = (g.slotStride : Word W))
+ (fits : oldLevel+38 < 2^W) (headers : Published g oldLevel m) :
+ let es := trace selectors rowStride inputs vm c m
+ ∃ d, Prefix M m c d [] es ∧ es.length = (RegisterSetup.lines (recipe selectors rowStride)).length ∧
+ countProbes es = 5 ∧ choiceBits es = [] ∧ d.pc = pc (RegisterSetup.lines (recipe selectors rowStride)).length ∧
+ Inputs g reg d ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j := by
+ obtain ⟨d,len,probes,choices,ep,priv,pers,vals,frame,pref⟩ :=
+ RegisterSetup.execute_setup_raw (recipe selectors rowStride) inputs vm M m pc link safe c atStart
+ let pub := fun i : Fin 5 => c.reg (inputs i.castSucc)
+ have eqAt (i : Fin 10) : d.reg (reg (target i)) = (recipe selectors rowStride i).eval pub
+ (c.reg (inputs (Fin.last 5))) m := (outputs i) ▸ vals i
+ have head (j : ℕ) (hj : j ≤ 38) :
+ (Expr.header j).eval pub (c.reg (inputs (Fin.last 5))) m = m (oldLevel+j) := by
+ change m ((c.reg (inputs 5))+(j : Word W)).val = _
+ rw [hL, ← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ have loadCount : ∑ i, (recipe selectors rowStride i).loads = 5 := by
+ simp only [Fin.sum_univ_succ, Fin.sum_univ_zero, recipe, Expr.header, Expr.headerAddress, Expr.add]
+ rfl
+ refine ⟨d,pref,len,probes.trans loadCount,choices,ep,?_,priv,pers,frame⟩
+ exact ⟨(eqAt 0).trans ((head 36 (by decide)).trans headers.term),
+ (eqAt 1).trans ((head 37 (by decide)).trans headers.stride),
+ (eqAt 2).trans ((head 38 (by decide)).trans headers.layout), (eqAt 3).trans sel.symm,
+ (eqAt 4).trans hs, (eqAt 5).trans hz, (eqAt 6).trans ((head 31 (by decide)).trans headers.counts),
+ (eqAt 7).trans ho, (eqAt 8).trans ((head 32 (by decide)).trans headers.rows),
+ (eqAt 9).trans (congrArg (fun n : ℕ => (n : Word W)) stride.symm)⟩
+
+/-- Each of the five external values is read once. No guesses are consumed
+and the private memory remains available to the actual hidden loop. -/
+theorem run (M : Machine W p r k) (g : Args W) (m : Memory W) (oldLevel : ℕ)
+ (selectors rowStride : ℕ) (sel : g.selectorBits = (selectors : Word W)) (stride : g.rowStride = rowStride)
+ (inputs : Fin 6 → Fin r) (pc : ℕ → Fin p) (reg : Fin 22 ↪ Fin r)
+ (vm : Fin (RegisterSetup.regCount (recipe selectors rowStride)) ↪ Fin r)
+ (link : RegisterSetup.Linked vm inputs M pc (RegisterSetup.lines (recipe selectors rowStride)))
+ (safe : ∀ i j, vm i ≠ inputs j)
+ (outputs : ∀ i, vm (RegisterSetup.output (recipe selectors rowStride) i) = reg (target i))
+ (c : Config W p r) (atStart : c.pc = pc 0) (hL : c.reg (inputs 5) = (oldLevel : Word W))
+ (ho : c.reg (inputs 0) = (g.owner : Word W)) (hs : c.reg (inputs 1) = (g.scratchBase : Word W))
+ (hz : c.reg (inputs 2) = (g.slotStride : Word W))
+ (fits : oldLevel+38 < 2^W) (headers : Published g oldLevel m) :
+ ∃ es d, Prefix M m c d [] es ∧ es.length = (RegisterSetup.lines (recipe selectors rowStride)).length ∧
+ countProbes es = 5 ∧ choiceBits es = [] ∧ d.pc = pc (RegisterSetup.lines (recipe selectors rowStride)).length ∧
+ Inputs g reg d ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j := by
+ obtain ⟨d,result⟩ := raw_run M g m oldLevel selectors rowStride sel stride inputs pc reg vm link safe outputs c atStart hL ho hs hz fits headers
+ exact ⟨_,d,result⟩
+
+end PairSimulation.ShrinkHiddenGuess.Header
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenNoWrites.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenNoWrites.lean
new file mode 100644
index 0000000000..11beefcf41
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenNoWrites.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenGuess
+import OAI.Computability.VPVNP.PairShrinkHiddenSetupNoWrites
+import OAI.Computability.VPVNP.CompressorFlowFootprint
+
+/-!
+# External memory through a shrinking hidden-field scan
+
+The scan reads the count, resident IDs, and selected term cells. It consumes
+the field guesses and stores them privately. Every event sequence preserves
+external memory, including an empty scan and arbitrary guessed field values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess
+
+open BurstRAM CompressorRecords SourceTransport
+
+variable {w : ℕ}
+
+/-- One row reads its external headers and writes its guessed bits in the
+private bit bank. -/
+theorem fieldEvents_noWrites (g : Args w) (m : Memory w) (ptr : ℕ) (e : Row) :
+ Writes (fun _ ↦ False) (fieldEvents g m ptr e) := by
+ intro a v h
+ simp only [fieldEvents, List.mem_append] at h
+ rcases h with (head | ticks) | guess
+ · simp [Args.header, ShrinkHiddenWidth.events] at head
+ · cases List.eq_of_mem_replicate ticks
+ · exact (FlowFootprint.bounds_of_noProbes (fun _ ↦ False) (fun _ ↦ False)
+ (PrivateFields.events_work (w := w) .guess e.2).2).2 a v guess
+
+/-- Arbitrary guessed fields leave every external word untouched throughout
+the count probe, per-field loop and terminating test. -/
+theorem events_noWrites (g : Args w) (m : Memory w) (es : List Row) :
+ Writes (fun _ ↦ False) (events g m es) := by
+ intro a v h
+ have scan (ptr : ℕ) (rows : List Row) : Event.write a v ∉ loopEvents g m ptr rows := by
+ induction rows generalizing ptr with
+ | nil => simp [loopEvents]
+ | cons e tail ih =>
+ simpa [loopEvents, ih] using
+ (show Event.write a v ∉ fieldEvents g m ptr e from fieldEvents_noWrites g m ptr e a v)
+ rcases List.mem_append.mp h with setup | loop
+ · simp [setupEvents] at setup
+ · exact scan _ _ loop
+
+/-- The post-trace external memory agrees at every address with the supplied
+memory, regardless of the owner or the encoded field values. -/
+theorem after_events (g : Args w) (m : Memory w) (es : List Row) (before : Memory w) :
+ after before (events g m es) = before :=
+ funext fun _ ↦ after_outside before (events_noWrites g m es) id
+
+end PairSimulation.ShrinkHiddenGuess
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenParser.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenParser.lean
new file mode 100644
index 0000000000..de2af70f4d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenParser.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenSlots
+
+/-!
+# The private hidden rows consumed by the selected shrinking kernel
+
+At each site the hidden rows occur in the order of the native directory.
+Their concatenated bit fields are the entire branch string consumed by the
+kernel. The subsequent resident matrix checks contribute no choice bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkHiddenSlots
+
+open Compression Compression.ShrinkMotif CompressorRecords ShrinkHistoryRows LocalHistory NetworkKernel
+open scoped Classical
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g))
+
+/-- Dense identifiers and little-endian bit fields in the site's scan order. -/
+def rows (layout : Bool) (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord g)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel widths layout) v) :
+ List (ℕ × List Bool) :=
+ let o := residents (hiddenOrder X) (X.packingData.shrinkInternalOwner layout) v
+ List.ofFn fun j =>
+ let e := o.entries j
+ (id X e.val, List.ofFn (RAMSerialization.wordBits _ (h e.val e.prop)))
+
+private theorem order_member {U V : Type} (o : Order U) (f : U → V) (e : U) :
+ f e ∈ List.ofFn (fun j => f (o.entries j)) :=
+ List.mem_ofFn.mpr ⟨o.entries.symm e, congrArg f (o.entries.apply_symm_apply e)⟩
+
+set_option maxHeartbeats 1500000 in
+/-- The row for every absorbed edge at this site occurs in the scan. -/
+theorem mem_rows (layout : Bool) (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord g)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel widths layout) v)
+ (e : X.packingData.Motif × Fin 4) (hv : v = X.packingData.shrinkInternalOwner layout e) :
+ (id X e, List.ofFn (RAMSerialization.wordBits _ (h e hv))) ∈ rows X layout widths v h := by
+ exact order_member (residents (hiddenOrder X) (X.packingData.shrinkInternalOwner layout) v)
+ (fun u => (id X u.val, List.ofFn (RAMSerialization.wordBits _ (h u.val u.prop)))) ⟨e,hv⟩
+
+theorem rows_nodup (layout : Bool) (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord g)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel widths layout) v) :
+ ((rows X layout widths v h).map Prod.fst).Nodup := by
+ rw [rows, List.map_ofFn, List.nodup_ofFn]
+ let o := residents (hiddenOrder X) (X.packingData.shrinkInternalOwner layout) v
+ exact (id_injective X).comp (Subtype.val_injective.comp o.entries.injective)
+
+open private fiber_encode from OAI.Computability.VPVNP.PairNodeArguments
+
+private theorem bounded_encode {width : ℕ} (x : Fin (2 ^ width)) :
+ (ChoiceReader.bounded width (2 ^ width) le_rfl).encode x = List.ofFn (RAMSerialization.wordBits _ x) := by
+ change BurstRAM.wordBits (Fin.ofNat (2 ^ width) x.val) = BurstRAM.wordBits x
+ congr 1
+ exact Fin.ext (Nat.mod_eq_of_lt x.isLt)
+
+private theorem fiber_rows (layout : Bool) (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord g)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel widths layout) v) :
+ let owner := X.packingData.shrinkInternalOwner layout
+ (fiber owner v (residents (hiddenOrder X) owner v)
+ (fun e => ChoiceReader.bounded (widths e.1 (!layout,e.2)) _ le_rfl)).encode h =
+ ((rows X layout widths v h).map Prod.snd).flatten := by
+ intro owner
+ erw [fiber_encode]
+ rw [rows, List.map_ofFn]
+ apply congrArg List.flatten
+ apply congrArg List.ofFn
+ funext j
+ exact bounded_encode _
+
+private theorem skip_empty (a b c : List Bool) (ha : a = c) (hb : b.length = 0) :
+ a ++ b = c := by simp [ha, List.length_eq_zero_iff.mp hb]
+
+variable {K R : Type*} [Field K] [CommRing R] {S : BlockSchedule K}
+variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps)
+
+set_option maxHeartbeats 4000000 in
+/-- Exact word-for-word agreement with the kernel of the scheduled pass. -/
+theorem kernel_encode {g : ℕ} (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (s : X.ShrinkSelection B.shrink) (v old new)
+ (x : (B.shrinkPassWitnesses f hf i rfl X s v old new).Choice) :
+ let layout := X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s
+ let widths := fun m => X.packingData.shrinkSupplyWidths X.shrinkNumber X.packingWidth B.shrink m (s m)
+ ((shrinkPassReaders B f hf i rfl X).kernel s v old new).encode x =
+ ((rows X layout widths v x.1).map Prod.snd).flatten := by
+ intro layout widths
+ let owner := X.packingData.shrinkInternalOwner layout
+ let o := residents (hiddenOrder X) owner v
+ change (fiber owner v o (fun e => ChoiceReader.bounded (widths e.1 (!layout,e.2)) _ le_rfl)).encode x.1 ++ _ = _
+ apply skip_empty
+ · exact fiber_rows X layout widths v x.1
+ · erw [Order.reader_length]
+ simp only [motifEntryReader, listedEntryReader_length, Finset.sum_const_zero]
+
+end PairSimulation.ShrinkHiddenSlots
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenReadback.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenReadback.lean
new file mode 100644
index 0000000000..261e6202d1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenReadback.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenParser
+import OAI.Computability.VPVNP.PairShrinkHiddenStep
+import OAI.Computability.VPVNP.PairNodeChildPackets
+
+/-!
+# Reading both map columns after the complete hidden-field scan
+
+The final private memory of the native shrinking guess worker is a fold of
+field stores. Distinct dense identifiers keep all of these fields resident
+through the end of the scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkHiddenSlots
+
+open BurstRAM ShrinkHiddenGuess NodeArguments Compression Compression.ShrinkMotif NetworkKernel
+open scoped Fin.CommRing Classical
+
+variable {w : ℕ}
+
+/-- Read one member of the complete native scan's private-memory update. -/
+theorem storeRows_read (base stride : ℕ) (es : List Row) (old : Word w → Word w)
+ (fits : ∀ r ∈ es, r.2.length ≤ stride ∧ base + r.1 * stride + r.2.length ≤ 2 ^ w)
+ (distinct : (es.map Prod.fst).Nodup) (r : Row) (hr : r ∈ es) (i : Fin r.2.length) :
+ storeRows base stride es old ((base + r.1 * stride + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w r.2[i.val] := by
+ let arena : Arena := ⟨base,stride⟩
+ let packet : Row → Packet := fun e => ⟨e.1,e.2⟩
+ have packetFit : ∀ q ∈ es.map packet, q.Fits arena w 0 := by
+ intro q hq
+ obtain ⟨e,he,rfl⟩ := List.mem_map.mp hq
+ exact ⟨Nat.zero_le _, fits e he⟩
+ have packetDistinct : ((es.map packet).map Packet.node).Nodup := by
+ simpa only [List.map_map, Function.comp_def, packet] using distinct
+ have stored := writePackets_children arena _ (DFS.scratch 0 old) packetFit packetDistinct (packet r)
+ (List.mem_map_of_mem hr) i
+ rw [← ChildScan.scratch_storePackets] at stored
+ change rawScratch (DFS.scratch 0 (ChildScan.storePackets arena (es.map packet) old))
+ ((base + r.1 * stride + i.val : ℕ) : Word w) = PrivateFields.bitValue w r.2[i.val] at stored
+ simpa only [rawScratch, dite_true, Nat.zero_le, DFS.scratch, ChildScan.storePackets, storeRows, List.foldl_map, packet, arena, Arena.base]
+ using stored
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g)) (base stride : ℕ)
+variable (layout : Bool) (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+
+/-- The allocation of one private slot per dense identifier bounds every
+field store in each site's restricted row. -/
+theorem rows_fit (v : (X.Base × BitWord (packingTagBits (2 ^ a))) × BitWord g)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel widths layout) v)
+ (size : ∀ m t, widths m (!layout,t) ≤ stride)
+ (cap : base + (CompressorRecords.ShrinkHistoryRows.hiddenOrder X).length * stride ≤ 2 ^ w) :
+ ∀ r ∈ rows X layout widths v h, r.2.length ≤ stride ∧ base + r.1 * stride + r.2.length ≤ 2 ^ w := by
+ intro r hr
+ obtain ⟨j,rfl⟩ := List.mem_ofFn.mp hr
+ let o := CompressorRecords.ShrinkHistoryRows.residents (CompressorRecords.ShrinkHistoryRows.hiddenOrder X)
+ (X.packingData.shrinkInternalOwner layout) v
+ let e := (o.entries j).val
+ change (List.ofFn (RAMSerialization.wordBits _ (h e _))).length ≤ stride ∧
+ base + id X e * stride + (List.ofFn (RAMSerialization.wordBits _ (h e _))).length ≤ 2 ^ w
+ rw [List.length_ofFn]
+ have hs := size e.1 e.2
+ have hi : id X e < (CompressorRecords.ShrinkHistoryRows.hiddenOrder X).length :=
+ ((CompressorRecords.ShrinkHistoryRows.hiddenOrder X).entries.symm e).isLt
+ have step := Nat.mul_le_mul_right stride hi
+ rw [Nat.succ_mul] at step
+ exact ⟨hs, by omega⟩
+
+/-- Every owned coordinate remains available after all rows have been written. -/
+theorem resident_read (v : (X.Base × BitWord (packingTagBits (2 ^ a))) × BitWord g)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel widths layout) v)
+ (old : Word w → Word w)
+ (fits : ∀ r ∈ rows X layout widths v h, r.2.length ≤ stride ∧
+ base + r.1 * stride + r.2.length ≤ 2 ^ w)
+ (e : X.packingData.Motif × Fin 4) (hv : v = X.packingData.shrinkInternalOwner layout e)
+ (i : Fin (widths e.1 (!layout,e.2))) :
+ storeRows base stride (rows X layout widths v h) old
+ ((address X base stride e + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (RAMSerialization.wordBits _ (h e hv) i) := by
+ let bits := RAMSerialization.wordBits _ (h e hv)
+ have stored := storeRows_read base stride _ old fits (rows_nodup X layout widths v h)
+ (id X e, List.ofFn bits) (mem_rows X layout widths v h e hv) ⟨i.val, by simp [bits]⟩
+ simpa only [address, List.getElem_ofFn, bits] using stored
+
+variable {b pad : ℕ} (subdiv : Fin 4 → ℕ)
+variable {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+variable (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad) (hpos : ∀ t, 0 < subdiv t)
+local notation "Y" => X.packingData.shrinkOutput layout subdiv (fun m t ↦ widths m (layout,t)) I
+
+/-- The same native store scan supplies the bit to either endpoint of the
+absorbed edge, evaluated on the local party's independent half-wires. -/
+theorem storeRows_mapColumn (m : X.packingData.Motif) (t : Fin 4) (dir : Bool)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel widths layout)
+ (X.packingData.shrinkInternalOwner layout (m,t)))
+ (z : (Y).Half (X.packingData.shrinkInternalOwner layout (m,t))) (old : Word w → Word w)
+ (fits : ∀ r ∈ rows X layout widths _ h, r.2.length ≤ stride ∧ base + r.1 * stride + r.2.length ≤ 2 ^ w)
+ (i : Fin (widths m (!layout,t))) :
+ storeRows base stride (rows X layout widths _ h) old
+ ((address X base stride (m,t) + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (RAMSerialization.wordBits _
+ (mapColumn X layout subdiv widths I hpos m t dir h z) i) := by
+ rw [mapColumn_eq]
+ exact resident_read X base stride layout widths _ h old fits (m,t) rfl i
+
+end PairSimulation.ShrinkHiddenSlots
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenResidentFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenResidentFootprint.lean
new file mode 100644
index 0000000000..db78c34f59
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenResidentFootprint.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenFootprint
+import OAI.Computability.VPVNP.PairShrinkHiddenRows
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-!
+# The selected hidden pass reads below the terminal controller
+
+The count and ID addresses lie in the resident directory. The dense ID
+selects a ten-word term row entirely below the width-array head. These two
+upper bounds cover every external read, independently of the private bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkHiddenRows
+
+open BurstRAM PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open CompressorRecords ShrinkHistoryRows ShrinkSliceSweep NetworkKernel
+open MotifBlocks MotifGrid MotifConversion ShrinkHiddenGuess SourceTransport LocalHistory
+open scoped Classical Fin.CommRing
+
+variable {a l W n A : ℕ} (X : State a (packingLaneBits a l))
+
+private theorem row_term_cells (T : Allocation W n A) (fit : T.Fits) (bound : ℕ)
+ (termBound : T.widthBase ≤ bound) (id : Word W) (ordinal : Fin n) (role : Fin 4)
+ (key : id.val = ordinal.val*4+role.val) :
+ let base := ShrinkHiddenWidth.rowBase (T.termBase : Word W) (T.termStride : Word W) id
+ let coord := ShrinkHiddenWidth.coordinate (T.layout.toNat : Word W) id
+ (base+1).val < bound ∧ (base+2+coord).val < bound := by
+ intro base coord
+ have room := T.term_stop fit ordinal
+ have widthLe : T.widthBase ≤ T.widthEnd := Nat.le_add_right ..
+ have endLe : T.widthEnd ≤ T.last := Nat.le_add_right ..
+ have fits := fit.room
+ unfold Allocation.termStart at room
+ have h4 : 4 < 2^W := by omega
+ have hi : (!T.layout).toNat*4+role.val < 8 := by have := Bool.toNat_le (!T.layout); have := role.isLt; omega
+ dsimp only [base,coord]
+ rw [ShrinkHiddenWidth.rowBase_eq _ _ _ _ _ key h4,ShrinkHiddenWidth.coordinate_eq _ _ _ _ key h4]
+ let rb : ℕ := T.termBase+ordinal.val*T.termStride
+ change (((rb : Word W)+((1 : ℕ) : Word W)).val < bound) ∧
+ (((rb : Word W)+((2 : ℕ) : Word W)+(((!T.layout).toNat*4+role.val : ℕ) : Word W)).val < bound)
+ rw [← Nat.cast_add,← Nat.cast_add,← Nat.cast_add]
+ exact ⟨(Nat.mod_le ..).trans_lt (by dsimp [rb]; omega),(Nat.mod_le ..).trans_lt (by dsimp [rb]; omega)⟩
+
+/-- Actual trace support on the count, row, and term allocations. -/
+theorem reads_below (T : TermAllocation (W := W) X) (m : Memory W) (first cutoff : ℕ)
+ (allocation : T.Fits) (residentFit : (ShrinkResidentLayout.layout X first).endAddr < 2^W)
+ (residentBound : (ShrinkResidentLayout.layout X first).endAddr ≤ cutoff) (termBound : T.widthBase ≤ cutoff)
+ (dir : Directory (hiddenOrder X) (packedOrder X) (X.packingData.shrinkInternalOwner T.layout)
+ ((ShrinkResidentLayout.layout X first).params a false W) m)
+ (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord l)
+ (h : Placed (X.packingData.shrinkInternalOwner T.layout) (internalLabel widths T.layout) v)
+ (scratchBase slotStride : ℕ) :
+ let L := ShrinkResidentLayout.layout X first
+ let G := args X T (L.params a false W) v scratchBase slotStride
+ let es := ShrinkHiddenSlots.rows X T.layout widths v h
+ Reads (fun i => i < cutoff) (events G m es) := by
+ intro L G es
+ let ord := residents (hiddenOrder X) (X.packingData.shrinkInternalOwner T.layout) v
+ let own := ((packedOrder X).entries.symm v).val
+ let cap := ShrinkResidentLayout.rowCapacity a false
+ have ownLt : own < L.sites := ((packedOrder X).entries.symm v).isLt
+ obtain ⟨_,_,_,_,hc,hcap,hr⟩ := ShrinkResidentLayout.frame X first false residentFit
+ change (L.params a false W 3).val = L.counts false at hc
+ change (L.params a false W 4).val = cap at hcap
+ change (L.params a false W 5).val = L.rows false at hr
+ change L.endAddr ≤ cutoff at residentBound
+ change L.endAddr < 2^W at residentFit
+ obtain ⟨_,_,countEnd,rowsEnd⟩ := L.ranges false
+ have size : L.size false = L.sites*cap := ShrinkResidentLayout.size_eq_rows X first false
+ have countCell : G.countBase+G.owner < cutoff := by
+ change (L.params a false W 3).val+own < cutoff
+ rw [hc]
+ calc
+ _ < L.counts false+L.sites := Nat.add_lt_add_left ownLt _
+ _ = L.rows false := countEnd
+ _ ≤ L.rows false+L.size false := Nat.le_add_right ..
+ _ ≤ _ := rowsEnd.trans residentBound
+ have len : es.length = ord.length := List.length_ofFn
+ have lengthCap : ord.length = cap :=
+ (Fintype.card_congr (Equiv.subtypeEquivRight (fun _ => eq_comm))).trans (hidden_count X T.layout v)
+ have rowCell (i : Fin es.length) : G.row+i.val < L.endAddr := by
+ have offset := Nat.mul_le_mul_right cap ownLt
+ rw [Nat.succ_mul] at offset
+ have il : i.val < cap := i.isLt.trans_eq (len.trans lengthCap)
+ change (L.params a false W 5).val+own*(L.params a false W 4).val+i.val < L.endAddr
+ rw [hr,hcap,Nat.add_assoc]
+ calc
+ _ < L.rows false+(own*cap+cap) := Nat.add_lt_add_left (Nat.add_lt_add_left il _) _
+ _ ≤ L.rows false+L.sites*cap := Nat.add_le_add_left offset _
+ _ ≤ _ := size ▸ rowsEnd
+ apply events_reads
+ · exact (Nat.mod_le ..).trans_lt countCell
+ · intro i
+ let j : Fin ord.length := ⟨i.val,len ▸ i.isLt⟩
+ let e := (ord.entries j).val
+ let dense := ShrinkMotifOrder.stateNumber X e.1
+ let ptr := G.row+i.val
+ have ptrEq : (ptr : Word W).val = ptr := Fin.val_cast_of_lt ((rowCell i).trans residentFit)
+ have stored : m ptr = (ShrinkHiddenSlots.id X e : Word W) :=
+ ShrinkHiddenSlots.directory_id X T.layout (L.params a false W) m dir v j
+ have hkey := ShrinkHiddenSlots.id_eq X e.1 e.2
+ have idLe : (m ptr).val ≤ dense.val*4+e.2.val := by
+ rw [stored, Fin.val_natCast, hkey]; exact Nat.mod_le ..
+ let ix := (m ptr).val / 4
+ let role : Fin 4 := ⟨(m ptr).val % 4,Nat.mod_lt _ (by decide)⟩
+ have le : ix ≤ dense.val := by dsimp only [ix]; have := e.2.isLt; omega
+ let index := (⟨ix,le.trans_lt dense.isLt⟩ : Fin _)
+ have key : (m ptr).val = index.val*4+role.val := by dsimp [index,ix,role]; omega
+ have pair := row_term_cells T allocation cutoff termBound (m ptr) index role key
+ change (ptr : Word W).val < cutoff ∧ _
+ rw [ptrEq]
+ exact ⟨(rowCell i).trans_le residentBound,pair⟩
+
+/-- The header and resident scan have a common footprint below the terminal
+control region. The two protected control cells are excluded from the
+entire chronological trace. -/
+theorem hosted_reads {p r : ℕ} (T : TermAllocation (W := W) X) (m : Memory W) (first oldLevel : ℕ)
+ (H : Word W) (terminalFit : H.val+31 < 2^W) (levelBound : oldLevel+38 < H.val)
+ (allocation : T.Fits) (residentBound : (ShrinkResidentLayout.layout X first).endAddr ≤ H.val)
+ (termBound : T.widthBase ≤ H.val)
+ (dir : Directory (hiddenOrder X) (packedOrder X) (X.packingData.shrinkInternalOwner T.layout)
+ ((ShrinkResidentLayout.layout X first).params a false W) m)
+ (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord l)
+ (h : Placed (X.packingData.shrinkInternalOwner T.layout) (internalLabel widths T.layout) v)
+ (scratchBase slotStride s t : ℕ) (inputs : Fin 6 → Fin r)
+ (vm : Fin (RegisterSetup.regCount (Header.recipe s t)) ↪ Fin r) (c : Config W p r)
+ (level : c.reg (inputs 5) = (oldLevel : Word W)) :
+ let L := ShrinkResidentLayout.layout X first
+ let G := args X T (L.params a false W) v scratchBase slotStride
+ let es := ShrinkHiddenSlots.rows X T.layout widths v h
+ let ev := Header.trace s t inputs vm c m ++ events G m es
+ Reads (fun i => i < H.val) ev ∧ Reads (TerminalLink.workerCell H) ev := by
+ intro L G es ev
+ have head := Header.trace_reads (fun i => i < H.val) s t inputs vm c m oldLevel level
+ (levelBound.trans H.isLt) (by
+ intro j hj
+ simp only [List.mem_cons,List.not_mem_nil,or_false] at hj
+ omega)
+ have body := reads_below X T m first H.val allocation (residentBound.trans_lt H.isLt)
+ residentBound termBound dir widths v h scratchBase slotStride
+ have below : Reads (fun i => i < H.val) ev := by
+ intro addr value read
+ exact (List.mem_append.mp read).elim (head addr value) (body addr value)
+ exact ⟨below,fun addr value read => TerminalFootprint.below H terminalFit (below addr value read)⟩
+
+end PairSimulation.ShrinkHiddenRows
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenRows.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenRows.lean
new file mode 100644
index 0000000000..e63375124a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenRows.lean
@@ -0,0 +1,195 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenParser
+import OAI.Computability.VPVNP.PairShrinkHiddenGuess
+import OAI.Computability.VPVNP.CompressorShrinkResidentLayout
+
+/-!
+# The native absorbed-field loop on a shrinking history
+
+The owner's external count and ID row enumerate its hidden fields in the
+kernel reader's order. Each ID addresses the actual chosen motif term and
+the private interval reserved for that field. The loop consumes the bits
+of each hidden word in little-endian order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkHiddenRows
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif
+open CompressorRecords ShrinkHistoryRows ShrinkSliceSweep LocalHistory NetworkKernel
+open MotifBlocks MotifGrid MotifConversion
+open scoped Classical Fin.CommRing
+
+variable {a l W n A : ℕ} (X : State a (packingLaneBits a l))
+
+/-- Stage inputs read from the physical term allocation and preimage directory. -/
+def args (T : Allocation W n A) (p : Fin 6 → Word W) (v : (X.Base × BitWord (Shrink.J a)) × BitWord l)
+ (scratchBase slotStride : ℕ) : ShrinkHiddenGuess.Args W where
+ termBase := (T.termBase : Word W)
+ termStride := (T.termStride : Word W)
+ layout := T.layout
+ selectorBits := T.selectors
+ scratchBase := scratchBase
+ slotStride := slotStride
+ countBase := (p 3).val
+ owner := ((packedOrder X).entries.symm v).val
+ rowBase := (p 5).val
+ rowStride := (p 4).val
+
+/-- The stored count is the number of complete word fields in this row. -/
+theorem count (T : Allocation W n A) (p : Fin 6 → Word W) (m : Memory W)
+ (dir : Directory (hiddenOrder X) (packedOrder X) (X.packingData.shrinkInternalOwner T.layout) p m)
+ (widths : X.packingData.Motif → Bool × Fin 4 → ℕ) (v : (X.Base × BitWord (Shrink.J a)) × BitWord l)
+ (h : Placed (X.packingData.shrinkInternalOwner T.layout) (internalLabel widths T.layout) v)
+ (scratchBase slotStride : ℕ) :
+ let g := args X T p v scratchBase slotStride
+ (m (g.countBase+g.owner)).val = (ShrinkHiddenSlots.rows X T.layout widths v h).length := by
+ simpa only [args, ShrinkHiddenSlots.rows, List.length_ofFn] using dir.count v
+
+/-- The resident directory allocation fits both the count probe and the full
+exclusive row end, even at the last owner. -/
+theorem directory_fit (T : Allocation W n A) (first : ℕ) (v : (X.Base × BitWord (Shrink.J a)) × BitWord l)
+ (fit : (ShrinkResidentLayout.layout X first).endAddr < 2^W) (scratchBase slotStride : ℕ)
+ (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (h : Placed (X.packingData.shrinkInternalOwner T.layout) (internalLabel widths T.layout) v) :
+ let p := (ShrinkResidentLayout.layout X first).params a false W
+ let g := args X T p v scratchBase slotStride
+ g.countBase+g.owner < 2^W ∧ g.row+(ShrinkHiddenSlots.rows X T.layout widths v h).length < 2^W := by
+ let L := ShrinkResidentLayout.layout X first
+ let idx := ((packedOrder X).entries.symm v).val
+ let cap := ShrinkResidentLayout.rowCapacity a false
+ have hi : idx < L.sites := ((packedOrder X).entries.symm v).isLt
+ have sz : L.size false = L.sites * cap := ShrinkResidentLayout.size_eq_rows X first false
+ obtain ⟨_,_,_,_,hc,hs,hr⟩ := ShrinkResidentLayout.frame X first false fit
+ have len : (ShrinkHiddenSlots.rows X T.layout widths v h).length = cap := by
+ rw [ShrinkHiddenSlots.rows, List.length_ofFn]
+ change Fintype.card {e : X.packingData.Motif × Fin 4 // v = X.packingData.shrinkInternalOwner T.layout e} = _
+ exact (Fintype.card_congr (Equiv.subtypeEquivRight (fun _ => eq_comm))).trans (hidden_count X T.layout v)
+ change (L.params a false W 3).val+idx < 2^W ∧
+ (L.params a false W 5).val+idx*(L.params a false W 4).val+(ShrinkHiddenSlots.rows X T.layout widths v h).length < 2^W
+ rw [hc,hs,hr,len]
+ have rend := (L.ranges false).2.2.2
+ have cend := (L.ranges false).2.2.1
+ have bound := Nat.mul_le_mul_right cap hi
+ rw [Nat.succ_mul] at bound
+ change L.endAddr < 2^W at fit
+ change L.counts false+idx < 2^W ∧ L.rows false+idx*cap+cap < 2^W
+ omega
+
+section Term
+
+set_option maxHeartbeats 2000000
+
+variable {K : Type*} [_root_.Field K] {factor : ℝ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable (sel : X.ShrinkSelection F)
+
+/-- The physical row uses the supply widths of the chosen motif terms. -/
+abbrev widths (motif : X.packingData.Motif) :=
+ X.packingData.shrinkSupplyWidths X.shrinkNumber X.packingWidth F motif (sel motif)
+
+/-- The shrinking slice-table allocation specialized to the state's dense motif count and
+absolute old-arc count, including the selected term records used for width lookup. -/
+abbrev TermAllocation :=
+ Allocation W (((Fintype.card X.Base*(2^(Shrink.J a)*2^l))*2^a)*pieceCount (2^a) (Shrink.colors a))
+ (Slots.oldBaseArcCount (Fintype.card X.Base) (2^(Shrink.J a)) (2^a) (Shrink.colors a)*2^l)
+
+variable (T : TermAllocation (W := W) X) (p : Fin 6 → Word W) (m : Memory W)
+
+/-- Every stored dense ID and native width agree with the chosen hidden
+word, and each word fits its private slot. -/
+theorem valid_rows (term : Terms X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) T F X.packingWidth sel m)
+ (allocation : T.Fits) (selectors : T.selectors.val = F.selectorBits)
+ (dir : Directory (hiddenOrder X) (packedOrder X) (X.packingData.shrinkInternalOwner T.layout) p m)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord l)
+ (h : Placed (X.packingData.shrinkInternalOwner T.layout) (internalLabel (widths X F sel) T.layout) v)
+ (scratchBase slotStride : ℕ)
+ (slots : ∀ motif t, widths X F sel motif (!T.layout,t) ≤ slotStride)
+ (space : scratchBase+(hiddenOrder X).length*slotStride < 2^W)
+ (rowFit : (args X T p v scratchBase slotStride).row + (ShrinkHiddenSlots.rows X T.layout (widths X F sel) v h).length ≤ 2^W) :
+ ShrinkHiddenGuess.ValidRows (args X T p v scratchBase slotStride) m (ShrinkHiddenSlots.rows X T.layout (widths X F sel) v h) := by
+ let G := args X T p v scratchBase slotStride
+ let row := ShrinkHiddenSlots.rows X T.layout (widths X F sel) v h
+ let ord := residents (hiddenOrder X) (X.packingData.shrinkInternalOwner T.layout) v
+ have hlen : row.length = ord.length := List.length_ofFn
+ intro i
+ let j : Fin ord.length := ⟨i.val, hlen ▸ i.isLt⟩
+ let e := (ord.entries j).val
+ let dense := ShrinkMotifOrder.stateNumber X e.1
+ let fieldWidth := widths X F sel e.1 (!T.layout,e.2)
+ let key := ShrinkHiddenSlots.id X e
+ have hkey : key = dense.val*4+e.2.val := ShrinkHiddenSlots.id_eq X e.1 e.2
+ have hslot := slots e.1 e.2
+ have hkeyBound : key < (hiddenOrder X).length := ((hiddenOrder X).entries.symm e).isLt
+ have slotBound : G.slot key + fieldWidth < 2^W := by
+ have le := Nat.mul_le_mul_right slotStride hkeyBound
+ rw [Nat.succ_mul] at le
+ change scratchBase+key*slotStride+fieldWidth < 2^W
+ omega
+ have hwidth : fieldWidth < 2^W := by omega
+ have hfitID : key < 2^W := by
+ have room := T.term_stop allocation dense
+ have hmul := Nat.mul_le_mul_left dense.val (show 4 ≤ T.termStride by have := allocation.termStride; omega)
+ have hbase : T.widthBase ≤ T.widthEnd := Nat.le_add_right ..
+ have hend : T.widthEnd ≤ T.last := Nat.le_add_right ..
+ have fit := allocation.room
+ have ht := e.2.isLt
+ rw [hkey]
+ unfold Allocation.termStart at room
+ omega
+ have pos : ((G.row+i.val : ℕ) : Word W).val = G.row+i.val := Fin.val_cast_of_lt ((Nat.add_lt_add_left i.isLt G.row).trans_le rowFit)
+ have stored : m (G.row+i.val) = (key : Word W) := ShrinkHiddenSlots.directory_id X T.layout p m dir v j
+ have ident : (m (G.row+i.val)).val = key := by rw [stored, Fin.val_cast_of_lt hfitID]
+ have width : (G.width m (m (G.row+i.val))).val = fieldWidth := by
+ have hdense : (ShrinkMotifOrder.stateNumber X).symm dense = e.1 := Equiv.symm_apply_apply ..
+ have got := ShrinkHiddenWidth.term_value_eq X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex)
+ T F X.packingWidth sel m term allocation selectors dense e.2 (m (G.row+i.val)) (ident.trans hkey)
+ (by change X.packingData.termWidths F X.shrinkNumber X.packingWidth sel
+ ((ShrinkMotifOrder.stateNumber X).symm dense) (!T.layout) e.2 < 2^W
+ rw [hdense]; exact hwidth)
+ change _ = X.packingData.termWidths F X.shrinkNumber X.packingWidth sel
+ ((ShrinkMotifOrder.stateNumber X).symm dense) (!T.layout) e.2 at got
+ rw [hdense] at got
+ exact got
+ have rowKey : row[i.val].1 = key := by simp only [row, ShrinkHiddenSlots.rows, List.getElem_ofFn]; rfl
+ have rowWidth : row[i.val].2.length = fieldWidth := by
+ simp only [row, ShrinkHiddenSlots.rows, List.getElem_ofFn, List.length_ofFn]
+ rfl
+ change ShrinkHiddenGuess.ValidAt G m (G.row+i.val) row[i.val]
+ unfold ShrinkHiddenGuess.ValidAt
+ rw [pos, rowKey, rowWidth]
+ exact ⟨ident, width, slotBound⟩
+
+end Term
+
+section Kernel
+
+variable {K R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps)
+
+/-- The native loop consumes the scheduled kernel's exact encoding of
+the hidden assignment. -/
+theorem kernel_stream {l : ℕ} (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) l))
+ (s : X.ShrinkSelection B.shrink) (v old new)
+ (x : (B.shrinkPassWitnesses f hf i rfl X s v old new).Choice) :
+ let layout := X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s
+ let widths := fun m => X.packingData.shrinkSupplyWidths X.shrinkNumber X.packingWidth B.shrink m (s m)
+ ShrinkHiddenGuess.stream (ShrinkHiddenSlots.rows X layout widths v x.1) =
+ ((shrinkPassReaders B f hf i rfl X).kernel s v old new).encode x := by
+ intro layout widths
+ rw [ShrinkHiddenGuess.stream, List.flatMap_def]
+ exact (ShrinkHiddenSlots.kernel_encode B f hf i X s v old new x).symm
+
+end Kernel
+end PairSimulation.ShrinkHiddenRows
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenSeedBudget.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSeedBudget.lean
new file mode 100644
index 0000000000..5cc9705bac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSeedBudget.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenRows
+
+/-!
+# Sizes of the selected shrinking hidden rows
+
+The native guess stream concatenates one little-endian word for each absorbed
+edge at its owner. Its length is the sum of the selected field widths there.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenRows
+
+open Compression Compression.ShrinkMotif CompressorRecords ShrinkHistoryRows NetworkKernel
+open MotifBlocks MotifGrid MotifConversion
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g)) (side : Bool)
+ (ws : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord g)
+ (h : Placed (X.packingData.shrinkInternalOwner side) (internalLabel ws side) v)
+
+/-- The physical row contains exactly four absorbed roles per resident motif count. -/
+theorem rows_length :
+ (ShrinkHiddenSlots.rows X side ws v h).length = ShrinkResidentLayout.rowCapacity a false := by
+ classical
+ rw [ShrinkHiddenSlots.rows, List.length_ofFn]
+ change Fintype.card {e : X.packingData.Motif × Fin 4 //
+ v = X.packingData.shrinkInternalOwner side e} = _
+ exact (Fintype.card_congr (Equiv.subtypeEquivRight (fun _ => eq_comm))).trans
+ (hidden_count X side v)
+
+open scoped Classical in
+/-- Reindex the physical scan by the absorbed edges owned at this vertex. -/
+theorem stream_length :
+ (ShrinkHiddenGuess.stream (ShrinkHiddenSlots.rows X side ws v h)).length =
+ ∑ e : {e : X.packingData.Motif × Fin 4 // X.packingData.shrinkInternalOwner side e = v},
+ ws e.val.1 (!side, e.val.2) := by
+ let o := residents (hiddenOrder X) (X.packingData.shrinkInternalOwner side) v
+ let index := o.entries.trans (Equiv.subtypeEquivRight (fun _ => eq_comm))
+ simp only [ShrinkHiddenGuess.stream, ShrinkHiddenSlots.rows, List.length_flatMap,
+ List.map_ofFn, Function.comp_def, List.length_ofFn, List.sum_ofFn]
+ exact index.sum_comp (fun e => ws e.val.1 (!side, e.val.2))
+
+variable {K : Type*} [_root_.Field K] {factor : ℝ}
+ (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+ (sel : X.ShrinkSelection F)
+ (seed : Placed (X.packingData.shrinkInternalOwner side) (internalLabel (widths X F sel) side) v)
+
+/-- The actual selected stream length is linear in the state's maximum wire width. -/
+theorem selected_stream_le :
+ (ShrinkHiddenGuess.stream (ShrinkHiddenSlots.rows X side (widths X F sel) v seed)).length ≤
+ ShrinkResidentLayout.rowCapacity a false * fieldFactor F * (X.maxWireWidth + 1) := by
+ classical
+ rw [stream_length]
+ exact X.packingData.shrinkSite_internalWidth_le (State.two_le_packingColors a) (Nat.two_pow_pos a)
+ X.shrinkNumber X.packingWidth (fun _ => X.width_le_maxWireWidth _) F sel side v
+
+variable {S : BlockSchedule K} (B : S.Templates)
+
+/-- One row capacity works for every degree in the finite shrinking schedule. -/
+def stageCapacity (S : BlockSchedule K) : ℕ :=
+ Finset.univ.sup fun i : Fin S.steps =>
+ ShrinkResidentLayout.rowCapacity (S.degreeExponent i.castSucc) false
+
+theorem rowCapacity_le_stageCapacity (i : Fin S.steps) :
+ ShrinkResidentLayout.rowCapacity (S.degreeExponent i.castSucc) false ≤ stageCapacity S :=
+ Finset.le_sup (f := fun j : Fin S.steps =>
+ ShrinkResidentLayout.rowCapacity (S.degreeExponent j.castSucc) false)
+ (Finset.mem_univ i)
+
+/-- Uniform bounds for both the field count and the guessed bits, for any site and branch. -/
+theorem scheduled_seed_bounds (i : Fin S.steps)
+ (Y : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (choice : Y.ShrinkSelection B.shrink) (site : (Y.Base × BitWord (Shrink.J _)) × BitWord g)
+ (hidden : Placed (Y.packingData.shrinkInternalOwner side)
+ (internalLabel (widths Y B.shrink choice) side) site) :
+ let rows := ShrinkHiddenSlots.rows Y side (widths Y B.shrink choice) site hidden
+ rows.length ≤ stageCapacity S ∧
+ (ShrinkHiddenGuess.stream rows).length ≤
+ stageCapacity S * fieldFactor B.shrink * (Y.maxWireWidth + 1) := by
+ intro rows
+ have cap := rowCapacity_le_stageCapacity (S := S) i
+ exact ⟨(rows_length Y side _ site hidden).le.trans cap,
+ (selected_stream_le Y side site B.shrink choice hidden).trans
+ (Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ cap))⟩
+
+end PairSimulation.ShrinkHiddenRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenSegment.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSegment.lean
new file mode 100644
index 0000000000..432796cd7e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSegment.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenTable
+import OAI.Computability.VPVNP.PairVertexImage
+
+/-!
+# Hosting the absorbed-field scan inside the vertex image
+
+The segment enters the header reader on the caller's live operands and
+returns to the supplied continuation after the last owned field. It uses
+the same register layout as the reset-entry program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkHiddenGuess.Table
+
+open BurstRAM PrivateRAM CompressorRecords NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable (s t : ℕ) {p r W : ℕ}
+
+/-- Number of instructions in the hosted scan segment, comprising the compiled header rows
+followed by one row for each scan stage. -/
+abbrev segmentCount := (lines s t).length + Fintype.card Stage
+
+/-- Host program counter for a scan stage, indexed in the segment after all compiled header
+rows. -/
+def segmentLoop (pc : Fin (segmentCount s t) → Fin p) (j : Stage) :=
+ pc (((Fintype.equivFin Stage) j).natAdd (lines s t).length)
+
+/-- Host program counter for a compiled header row, with indices at or beyond the header length
+directed to the scan's initialization. -/
+def segmentHeader (pc : Fin (segmentCount s t) → Fin p) (i : ℕ) :=
+ if h : i < (lines s t).length then pc ((⟨i,h⟩ : Fin (lines s t).length).castAdd (Fintype.card Stage))
+ else segmentLoop s t pc (.inl .one)
+
+/-- The live source bank in the same layout as the four-operand preamble. -/
+def segmentInputs : Fin 6 ↪ Fin (R s t) :=
+ ⟨inputs s t,fun _ _ eq => Sum.inr.inj (Sum.inr.inj ((Fintype.equivFin _).injective eq))⟩
+
+/-- Vertex-image segment that prepares the scan from the caller's live operands, guesses the
+owner's absorbed fields, and jumps to the supplied continuation. -/
+def segment : VertexImage.Segment where
+ count := segmentCount s t
+ privateRegs := R s t
+ entry := segmentHeader s t id 0
+ row pc _ _ prv ret := Fin.addCases
+ (fun i => RegisterSetup.instruction ((vm s t).trans prv) ((segmentInputs s t).trans prv)
+ ((lines s t)[i.val]) (segmentHeader s t pc (i.val+1)))
+ (fun j => instruction (segmentLoop s t pc) ((regs s t).trans prv) ret ((Fintype.equivFin Stage).symm j))
+
+theorem segment_entry (pc : Fin (segment s t).count → Fin p) :
+ pc (segment s t).entry = segmentHeader s t pc 0 := by
+ simp only [segment,segmentHeader,segmentLoop]
+ split <;> rfl
+
+theorem segment_after_header (pc : Fin (segment s t).count → Fin p) :
+ segmentHeader s t pc (lines s t).length = segmentLoop s t pc (.inl .one) := by
+ simp [segmentHeader]
+
+private theorem resize_twice {b : ℕ} (op : Instr b p r 11) (hb : b ≤ 5) :
+ (op.resize 5).resize W = op.resize W := by
+ cases op <;> first | rfl | simp only [Instr.resize,resize_literal hb]
+
+theorem segment_linked (M : Machine W p r 11) (pc : Fin (segment s t).count → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (prv : Fin (segment s t).privateRegs ↪ Fin r) (ret : Fin p)
+ (rows : ∀ i, M.code (pc i) = ((segment s t).row pc dfs saved prv ret i).resize W) :
+ RegisterSetup.Linked ((vm s t).trans prv) ((segmentInputs s t).trans prv) M (segmentHeader s t pc) (lines s t) ∧
+ Linked M (segmentLoop s t pc) ((regs s t).trans prv) ret := by
+ constructor
+ · intro i
+ unfold segmentHeader
+ rw [dite_eq_left i.isLt]
+ apply (rows (i.castAdd (Fintype.card Stage))).trans
+ simp only [segment,Fin.addCases_left]
+ rw [← RegisterSetup.resize_instruction (w := 5), resize_twice _ (by decide), RegisterSetup.resize_instruction]
+ rfl
+ · intro j
+ apply (rows (((Fintype.equivFin Stage) j).natAdd (lines s t).length)).trans
+ simp only [segment,Fin.addCases_right,Equiv.symm_apply_apply]
+ rw [← resize_instruction (W := 5),resize_twice _ (by decide),resize_instruction]
+
+/-- The host supplies four live operands in the protected six-register bank. -/
+structure SegmentOperands (prv : Fin (segment s t).privateRegs ↪ Fin r)
+ (g : Args W) (oldLevel : ℕ) (c : Config W p r) : Prop where
+ level : c.reg (prv (segmentInputs s t 5)) = (oldLevel : Word W)
+ owner : c.reg (prv (segmentInputs s t 0)) = (g.owner : Word W)
+ base : c.reg (prv (segmentInputs s t 1)) = (g.scratchBase : Word W)
+ stride : c.reg (prv (segmentInputs s t 2)) = (g.slotStride : Word W)
+
+end PairSimulation.ShrinkHiddenGuess.Table
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenSegmentRun.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSegmentRun.lean
new file mode 100644
index 0000000000..faf6414c42
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSegmentRun.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenSegment
+
+/-! # Header and field execution in the hosted hidden segment -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess.Table
+
+open BurstRAM PrivateRAM CompressorRecords NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {s t p r W : ℕ}
+
+set_option maxHeartbeats 600000 in
+/-- The live header sets up the hidden loop without changing any private
+memory cell or register outside the installed header bank. -/
+theorem segment_prepare_raw (M : Machine W p r 11) (pc : Fin (segmentCount s t) → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (prv : Fin (R s t) ↪ Fin r) (ret : Fin p)
+ (rows : ∀ i, M.code (pc i) = ((segment s t).row pc dfs saved prv ret i).resize W)
+ (g : Args W) (m : Memory W) (oldLevel : ℕ) (c : Config W p r)
+ (entry : c.pc = pc (segment s t).entry) (op : SegmentOperands s t prv g oldLevel c)
+ (selectors : g.selectorBits = (s : Word W)) (stride : g.rowStride = t)
+ (fits : oldLevel+38 < 2^W) (published : Header.Published g oldLevel m) :
+ let ev := Header.trace s t ((segmentInputs s t).trans prv) ((vm s t).trans prv) c m
+ ∃ d, Prefix M m c d [] ev ∧ d.pc = segmentLoop s t pc (.inl .one) ∧
+ Inputs g ((regs s t).trans prv) d ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ (∀ i, i ∉ Set.range ((vm s t).trans prv) → d.reg i = c.reg i) ∧
+ ev.length = (lines s t).length ∧ countProbes ev = 5 ∧ choiceBits ev = [] := by
+ obtain ⟨header,_⟩ : RegisterSetup.Linked ((vm s t).trans prv) ((segmentInputs s t).trans prv) M
+ (segmentHeader s t pc) (lines s t) ∧ _ := segment_linked s t M pc dfs saved prv ret rows
+ let H := segmentHeader s t pc
+ let I := (segmentInputs s t).trans prv
+ let V := (vm s t).trans prv
+ let G := (regs s t).trans prv
+ have free (i : Fin (aux s t)) (j : Fin 6) : V i ≠ I j := prv.injective.ne (safe s t i j)
+ have out (i : Fin 10) : V (RegisterSetup.output (Header.recipe s t) i) = G (Header.target i) :=
+ by simp only [V,G,Function.Embedding.trans_apply,outputs s t i]
+ have atStart : c.pc = H 0 := entry.trans (segment_entry s t pc)
+ have lev : c.reg (I 5) = (oldLevel : Word W) := op.level
+ have own : c.reg (I 0) = (g.owner : Word W) := op.owner
+ have base : c.reg (I 1) = (g.scratchBase : Word W) := op.base
+ have size : c.reg (I 2) = (g.slotStride : Word W) := op.stride
+ have run := @Header.raw_run W p r 11 M g m oldLevel s t selectors stride I H G V
+ header free out c atStart lev own base size fits published
+ obtain ⟨d,path,len,probes,bits,ep,ready,priv,pers,keep⟩ := run
+ exact ⟨d,path,ep.trans (segment_after_header s t pc),ready,priv,pers,
+ fun i f => keep i (fun j eq => f ⟨j,eq.symm⟩),len,probes,bits⟩
+
+/-- A full hosted scan on a valid row, returning to the caller's exact PC.
+Registers outside its private bank remain available to the next segment. -/
+theorem segment_run (M : Machine W p r 11) (pc : Fin (segmentCount s t) → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (prv : Fin (R s t) ↪ Fin r) (ret : Fin p)
+ (code : ∀ i, M.code (pc i) = ((segment s t).row pc dfs saved prv ret i).resize W)
+ (g : Args W) (m : Memory W) (oldLevel : ℕ) (c : Config W p r) (es : List Row)
+ (entry : c.pc = pc (segment s t).entry) (op : SegmentOperands s t prv g oldLevel c)
+ (selectors : g.selectorBits = (s : Word W)) (stride : g.rowStride = t)
+ (fits : oldLevel+38 < 2^W) (published : Header.Published g oldLevel m)
+ (fit : g.countBase+g.owner < 2^W) (count : (m (g.countBase+g.owner)).val = es.length)
+ (valid : ValidRows g m es) :
+ let head := Header.trace s t ((segmentInputs s t).trans prv) ((vm s t).trans prv) c m
+ let ev := head ++ events g m es
+ ∃ d, Prefix M m c d (stream es) ev ∧ d.pc = ret ∧
+ d.privateMem = storeRows g.scratchBase g.slotStride es c.privateMem ∧ d.persistent = c.persistent ∧
+ (∀ i, i ∉ Set.range prv → d.reg i = c.reg i) ∧
+ ev.length = (lines s t).length+7+25*es.length+6*(stream es).length ∧
+ countProbes ev = 6+3*es.length ∧ choiceBits ev = stream es ∧
+ ∀ bs, bs.length < (stream es).length → ¬ DFS.Returns M c m bs := by
+ intro head ev
+ obtain ⟨a,pref,ep,ready,pm,ps,frame,len,probes,choices⟩ :=
+ segment_prepare_raw M pc dfs saved prv ret code g m oldLevel c entry op selectors stride fits published
+ have link := (segment_linked s t M pc dfs saved prv ret code).2
+ obtain ⟨d,path,endPC,keep,priv,pers⟩ := native link g m es a ep ready fit count valid
+ obtain ⟨work,reads,bits⟩ := cost g m es
+ refine ⟨d,pref.trans path,endPC,priv.trans (congrArg _ pm),pers.trans ps,?_,?_,?_,?_,?_⟩
+ · intro i free
+ have sep (j : Fin 22) : i ≠ prv (regs s t j) := fun eq => free ⟨_,eq.symm⟩
+ exact (keep i (sep 3) (sep 21) (fun j _ => sep j)).trans (frame i fun ⟨j,eq⟩ => free ⟨_,eq⟩)
+ · simp only [ev,List.length_append]
+ change head.length = _ at len
+ omega
+ · simp only [ev,countProbes_append]
+ change countProbes head = 5 at probes
+ omega
+ · simp only [ev,PrimedInputRAM.Flow.choiceBits_append]
+ change choiceBits head = [] at choices
+ rw [choices,bits,List.nil_append]
+ · intro bs short
+ exact mt (pref.returns bs).mp (native_short link g m es a ep ready fit count valid bs short)
+
+end PairSimulation.ShrinkHiddenGuess.Table
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenSetupNoWrites.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSetupNoWrites.lean
new file mode 100644
index 0000000000..6b0824ab05
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSetupNoWrites.lean
@@ -0,0 +1,55 @@
+import OAI.Computability.VPVNP.PairShrinkRolePhysicalHidden
+import OAI.Computability.VPVNP.PairShrinkRoleMapStart
+import OAI.Computability.VPVNP.CompressorFormulaFootprint
+
+/-!
+# External memory during shrinking setup
+
+The hidden-field handoff runs locally and its compiled header only reads
+external memory. Map entry likewise runs its four reload steps locally
+and reads the four level fields and the packed site's count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open BurstRAM CompressorRecords
+open scoped Fin.CommRing
+open private eval_no_writes from OAI.Computability.VPVNP.CompressorFormulaFootprint
+open private fetch from OAI.Computability.VPVNP.PairSimulationMapResidentInputs
+
+variable {w endAddr : ℕ} (s t oldHead : ℕ) (m : Memory w) (level owner node : Word w)
+ (saved : DFS.Scratch w endAddr)
+
+theorem ShrinkRole.physicalHiddenSetup_noWrites :
+ SourceTransport.Writes (fun _ ↦ False)
+ ((ShrinkRole.physicalHiddenSetup s t oldHead m).trace node saved) := by
+ intro a v h
+ rcases List.mem_append.mp h with handoff | header
+ · cases (List.mem_replicate.mp handoff).2
+ · exact eval_no_writes (fun _ ↦ False) _ _ _ _ _ a v header
+
+theorem ShrinkRole.after_physicalHiddenSetup :
+ after m ((ShrinkRole.physicalHiddenSetup s t oldHead m).trace node saved) = m :=
+ funext fun _ ↦ SourceTransport.after_outside m
+ (physicalHiddenSetup_noWrites s t oldHead m node saved) id
+
+theorem ShrinkVertexImage.mapStartSetup_noWrites :
+ SourceTransport.Writes (fun _ ↦ False)
+ ((ShrinkVertexImage.mapStartSetup m level owner).trace node saved) := by
+ intro a v h
+ change Event.write a v ∈ List.replicate 4 .tick ++ MapResidentInputs.headerEvents m level owner at h
+ simp [MapResidentInputs.headerEvents, fetch] at h
+
+theorem ShrinkVertexImage.after_mapStartSetup :
+ after m ((ShrinkVertexImage.mapStartSetup m level owner).trace node saved) = m :=
+ funext fun _ ↦ SourceTransport.after_outside m (mapStartSetup_noWrites m level owner node saved) id
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenSlots.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSlots.lean
new file mode 100644
index 0000000000..2b5f0ddd82
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenSlots.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.CompressorRecordsShrinkHistory
+import OAI.Computability.VPVNP.PairNodeArguments
+
+/-!
+# Private fields for absorbed edges in a shrinking pass
+
+Each absorbed edge receives one slot indexed by its dense motif and role
+ordinal. The local history scans the restricted list of owners. The source
+and target maps at that owner use the same private field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkHiddenSlots
+
+open BurstRAM CompressorRecords ShrinkHistoryRows Compression LocalHistory
+open scoped Classical Fin.CommRing
+
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+
+/-- The identifier carried by a row of the hidden owner directory. -/
+def id (e : X.packingData.Motif × Fin 4) : ℕ := ((hiddenOrder X).entries.symm e).val
+
+theorem id_eq (m : X.packingData.Motif) (t : Fin 4) :
+ id X (m,t) = (ShrinkMotifOrder.stateNumber X m).val * 4 + t.val := by
+ change t.val + 4 * (ShrinkMotifOrder.stateNumber X m).val = _
+ omega
+
+theorem id_injective : Function.Injective (id X) :=
+ Fin.val_injective.comp (hiddenOrder X).entries.symm.injective
+
+/-- The base of a private bit field, shared between its two map incidences. -/
+def address (base stride : ℕ) (e : X.packingData.Motif × Fin 4) : ℕ := base + id X e * stride
+
+set_option maxHeartbeats 1500000 in
+/-- Each entry in the native local row contains its full dense identifier. -/
+theorem directory_id (layout : Bool) (p : Fin 6 → Word w) (mem : Memory w)
+ (dir : Directory (hiddenOrder X) (packedOrder X) (X.packingData.shrinkInternalOwner layout) p mem)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord g)
+ (j : Fin (residents (hiddenOrder X) (X.packingData.shrinkInternalOwner layout) v).length) :
+ let e := ((residents (hiddenOrder X) (X.packingData.shrinkInternalOwner layout) v).entries j).val
+ mem ((p 5).val + ((packedOrder X).entries.symm v).val * (p 4).val + j.val) = (id X e : Word w) :=
+ dir.idAt v j
+
+variable (base stride : ℕ) {e e' : X.packingData.Motif × Fin 4}
+
+theorem addresses_disjoint (hne : e ≠ e') :
+ address X base stride e + stride ≤ address X base stride e' ∨
+ address X base stride e' + stride ≤ address X base stride e :=
+ NodeArguments.Arena.disjoint ⟨base, stride⟩ (fun h => hne (id_injective X h))
+
+theorem store_read (bits : List Bool) (old : Word w → Word w)
+ (fit : address X base stride e + bits.length ≤ 2 ^ w) (i : Fin bits.length) :
+ PrivateFields.storeBits (address X base stride e) bits old
+ ((address X base stride e + i.val : ℕ) : Word w) = PrivateFields.bitValue w bits[i.val] :=
+ PrivateFields.storeBits_read _ _ _ fit i
+
+/-- Writing a resident field preserves every bit of any other slot. -/
+theorem store_other (hne : e ≠ e') (bits : List Bool) (old : Word w → Word w)
+ (size : bits.length ≤ stride) (i : Fin stride)
+ (fit : address X base stride e + bits.length ≤ 2 ^ w)
+ (readFit : address X base stride e' + i.val < 2 ^ w) :
+ let cell : Word w := (address X base stride e' + i.val : ℕ)
+ PrivateFields.storeBits (address X base stride e) bits old cell = old cell := by
+ intro cell
+ apply PrivateFields.storeBits_outside _ _ _ cell fit
+ have val : cell.val = address X base stride e' + i.val := Nat.mod_eq_of_lt readFit
+ rw [val]
+ rcases addresses_disjoint X base stride hne with before | after <;> omega
+
+section Incidences
+
+open NetworkKernel PackingData ShrinkMotif
+open private readSupplyEnd layoutCases_absorbed from OAI.Computability.VPVNP.ShrinkSupplyLocal
+
+variable {b pad : ℕ} (layout : Bool) (subdiv : Fin 4 → ℕ)
+variable (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+variable {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+variable (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad) (hpos : ∀ t, 0 < subdiv t)
+local notation "Y" => X.packingData.shrinkOutput layout subdiv (fun m t ↦ widths m (layout,t)) I
+
+/-- The party reading an absorbed edge at the indicated end. -/
+def party (layout : Bool) (t : Fin 4) : Bool → Fin 6
+ | false => supply.src (!layout,t)
+ | true => supply.dst (!layout,t)
+
+theorem party_owner (m : X.packingData.Motif) (t : Fin 4) (dir : Bool) :
+ X.packingData.shrinkPartySite layout m (party layout t dir) =
+ X.packingData.shrinkInternalOwner layout (m,t) := by
+ cases dir <;> simp only [shrinkPartySite, party, shrinkInternalOwner, role_src_absorbed, role_dst_absorbed]
+
+variable (m : X.packingData.Motif) (t : Fin 4)
+local notation "owner" => X.packingData.shrinkInternalOwner layout (m,t)
+local notation "Labels" => internalLabel widths layout
+
+/-- Select the absorbed column from the actual local supply argument.
+Both ends use the hidden assignment at their common packed site. -/
+def mapColumn (dir : Bool) (h : Placed (X.packingData.shrinkInternalOwner layout) Labels owner)
+ (z : (Y).Half owner) : Labels (m,t) :=
+ match dir with
+ | false => (X.packingData.shrinkLocalSupplyArg layout subdiv widths I hpos m _
+ ((party_owner X layout m t false).symm ▸ h) ((party_owner X layout m t false).symm ▸ z)).1 (!layout,t) rfl
+ | true => (X.packingData.shrinkLocalSupplyArg layout subdiv widths I hpos m _
+ ((party_owner X layout m t true).symm ▸ h) ((party_owner X layout m t true).symm ▸ z)).2 (!layout,t) rfl
+
+private theorem placed_cast {U V : Type} {P : U → V} {F : U → Type} {v v' : V}
+ (eqn : v = v') (h : Placed P F v') (e : U) (he : v = P e) :
+ (eqn.symm ▸ h : Placed P F v) e he = h e (eqn.symm.trans he) := by
+ cases eqn
+ rfl
+
+theorem mapColumn_eq (dir : Bool) (h : Placed (X.packingData.shrinkInternalOwner layout) Labels owner)
+ (z : (Y).Half owner) : mapColumn X layout subdiv widths I hpos m t dir h z = h (m,t) rfl := by
+ cases dir <;> simp only [mapColumn, shrinkLocalSupplyArg, readSupplyEnd, layoutCases_absorbed]
+ exact placed_cast (party_owner X layout m t true) h (m,t) _
+
+/-- A shared private slot gives the coordinate of either incident map column.
+The half-wire argument is arbitrary, including unrelated assignments to the
+source and target party's surviving fields. -/
+theorem mapColumn_read (dir : Bool) (h : Placed (X.packingData.shrinkInternalOwner layout) Labels owner)
+ (z : (Y).Half owner) (priv : Word w → Word w)
+ (stored : ∀ j, priv ((address X base stride (m,t) + j.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (RAMSerialization.wordBits _ (h (m,t) rfl) j))
+ (i : Fin (widths m (!layout,t))) :
+ priv ((address X base stride (m,t) + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (RAMSerialization.wordBits _
+ (mapColumn X layout subdiv widths I hpos m t dir h z) i) := by
+ rw [mapColumn_eq]
+ exact stored i
+
+end Incidences
+
+end PairSimulation.ShrinkHiddenSlots
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenStep.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenStep.lean
new file mode 100644
index 0000000000..03d80c7218
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenStep.lean
@@ -0,0 +1,191 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenCode
+import OAI.Computability.VPVNP.PairShrinkHiddenWidth
+
+/-!
+# Reading and guessing one stored absorbed-field row
+
+The width reader follows the dense ID to the selected term's repetition and
+role payload cells. The private destination is computed from that same ID.
+The finite guess loop consumes precisely the indicated number of bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenGuess
+
+open BurstRAM PrivateRAM CompressorRecords ShrinkSliceArrays NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {W p r k : ℕ}
+
+/-- Labels of the complete field scan, partitioned into its outer controls, 18 width-reader
+instructions, and seven private guess instructions. -/
+abbrev Stage := Control ⊕ (Fin 18 ⊕ Fin 7)
+
+/-- Emit one row of the field scan, linking the width reader to the slot address calculation
+and the private guess loop to the remaining-count decrement. -/
+def instruction (pc : Stage → Fin p) (reg : Fin 22 ↪ Fin r) (done : Fin p) : Stage → Instr W p r k
+ | .inl j => control (pc ∘ Sum.inl) reg (pc (.inr (.inl 0))) (pc (.inr (.inr 0))) done j
+ | .inr (.inl j) => ShrinkHiddenWidth.instruction (pc ∘ Sum.inr ∘ Sum.inl) (widthRegs reg) (pc (.inl .slotOffset)) j
+ | .inr (.inr j) => PrivateFields.instruction .guess (pc ∘ Sum.inr ∘ Sum.inr) (guessRegs reg) (pc (.inl .decrement)) j
+
+theorem resize_instruction (pc : Stage → Fin p) (reg : Fin 22 ↪ Fin r) (done : Fin p) (j : Stage) :
+ (instruction (W := 3) (k := k) pc reg done j).resize W = instruction pc reg done j := by
+ rcases j with j | j | j
+ · cases j <;> rfl
+ · exact ShrinkHiddenWidth.resize_instruction ..
+ · fin_cases j <;> rfl
+
+/-- Every scan stage has its specified instruction in the machine at the supplied program
+counter, using the given registers and exit address. -/
+def Linked (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 22 ↪ Fin r) (done : Fin p) :=
+ ∀ j, M.code (pc j) = instruction pc reg done j
+
+/-- Width word for the given dense hidden ID, obtained from the opposite-layout role's payload
+plus the term repetition count times the selector width. -/
+def Args.width (g : Args W) (m : Memory W) (id : Word W) :=
+ supplyValue (supplyData (ShrinkHiddenWidth.coordinate (g.layout.toNat : Word W) id) g.selectorBits 0)
+ (ShrinkHiddenWidth.rowBase g.termBase g.termStride id) m
+
+/-- Width-reader trace for the field whose dense ID is stored at the supplied pointer. The ID
+determines the term row and hidden role to probe. -/
+def Args.header (g : Args W) (m : Memory W) (ptr : Word W) :=
+ let id := m ptr.val
+ ShrinkHiddenWidth.events m ptr (ShrinkHiddenWidth.rowBase g.termBase g.termStride id)
+ (ShrinkHiddenWidth.coordinate (g.layout.toNat : Word W) id)
+
+/-- Each pair consists of a dense hidden ID and the actual independent
+bits to consume. Address and width conditions are checked against memory. -/
+abbrev Row := ℕ × List Bool
+
+/-- The external directory entry matches the field's dense ID, the term gives exactly its bit
+length, and its private slot's exclusive bit end fits in a machine word. -/
+def ValidAt (g : Args W) (m : Memory W) (ptr : ℕ) (e : Row) : Prop :=
+ let id := m ((ptr : Word W).val)
+ id.val = e.1 ∧ (g.width m id).val = e.2.length ∧ g.slot e.1+e.2.length < 2^W
+
+/-- Each field in the list satisfies the ID, width, and slot-end checks at its successive
+position in the owner's external row. -/
+def ValidRows (g : Args W) (m : Memory W) (es : List Row) : Prop :=
+ ∀ i : Fin es.length, ValidAt g m (g.row+i.val) es[i.val]
+
+/-- Update private memory in row order by storing each field's bit list at the slot selected by
+its dense ID. -/
+def storeRows (base stride : ℕ) (rows : List Row) (old : Word W → Word W) :=
+ rows.foldl (fun m e => PrivateFields.storeBits (base+e.1*stride) e.2 m) old
+
+variable {M : Machine W p r k} {pc : Stage → Fin p} {reg : Fin 22 ↪ Fin r} {done : Fin p}
+
+theorem controls (link : Linked M pc reg done) :
+ ControlLinked M (pc ∘ Sum.inl) reg (pc (.inr (.inl 0))) (pc (.inr (.inr 0))) done := fun j => link (.inl j)
+
+private theorem guesses (link : Linked M pc reg done) :
+ PrivateFields.Linked M .guess (pc ∘ Sum.inr ∘ Sum.inr) (guessRegs reg) (pc (.inl .decrement)) :=
+ fun j => link (.inr (.inr j))
+
+theorem slot_run (link : Linked M pc reg done) (g : Args W) (m : Memory W) (c : Config W p r)
+ (entry : c.pc = pc (.inl .slotOffset)) (ready : Ready g reg c) (id n : ℕ)
+ (hid : (c.reg (reg 10)).val = id) (hw : (c.reg (reg 1)).val = n) :
+ ∃ d, Prefix M m c d [] (List.replicate 3 .tick) ∧ d.pc = pc (.inr (.inr 0)) ∧
+ d.reg (reg 2) = (g.slot id : Word W) ∧ d.reg (reg 1) = ((g.slot id+n : ℕ) : Word W) ∧
+ (∀ i, i ≠ reg 1 → i ≠ reg 2 → d.reg i = c.reg i) ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ let a := c.put (pc (.inl .slotStart)) (reg 2) (c.reg (reg 10)*c.reg (reg 16))
+ let b := a.put (pc (.inl .slotEnd)) (reg 2) (a.reg (reg 15)+a.reg (reg 2))
+ let d := b.put (pc (.inr (.inr 0))) (reg 1) (b.reg (reg 2)+b.reg (reg 1))
+ have s₁ : M.program.step c = .localStep a := by
+ change (M.code c.pc).run M.publicData c = _
+ rw [entry, link]; rfl
+ have s₂ : M.program.step a = .localStep b := by
+ change (M.code (pc (.inl .slotStart))).run M.publicData a = _
+ rw [link]; rfl
+ have s₃ : M.program.step b = .localStep d := by
+ change (M.code (pc (.inl .slotEnd))).run M.publicData b = _
+ rw [link]; rfl
+ have pre : PrimedCounter.GuessWord.Prefix M c (List.replicate 3 .tick) d := .tick s₁ (.tick s₂ (.tick s₃ (.nil _)))
+ have val {a : Word W} {n : ℕ} (h : a.val = n) : a = (n : Word W) := by
+ subst n
+ exact Fin.ext (Nat.mod_eq_of_lt a.isLt).symm
+ refine ⟨d, fun fuel tail => pre.execute fuel m tail, rfl, ?_, ?_, ?_, rfl, rfl⟩
+ · simp [a,b,d,Config.put, Args.slot,ready.scratch,ready.stride,val hid]
+ · simp [a,b,d,Config.put, Args.slot,ready.scratch,ready.stride,val hid,val hw]
+ · intro i h1 h2; simp [a,b,d,Config.put,Function.update_of_ne h1,Function.update_of_ne h2]
+
+private theorem stage_run (link : Linked M pc reg done) (g : Args W) (m : Memory W) (c : Config W p r)
+ (ptr : ℕ) (e : Row) (entry : c.pc = pc (.inr (.inl 0))) (ready : Ready g reg c)
+ (hp : c.reg (reg 5) = (ptr : Word W)) (hv : ValidAt g m ptr e) :
+ ∃ d, Prefix M m c d [] (g.header m (ptr : Word W) ++ List.replicate 3 .tick) ∧
+ d.pc = pc (.inr (.inr 0)) ∧ d.reg (reg 2) = (g.slot e.1 : Word W) ∧
+ d.reg (reg 1) = ((g.slot e.1+e.2.length : ℕ) : Word W) ∧
+ d.reg (reg 5) = c.reg (reg 5) ∧ d.reg (reg 14) = c.reg (reg 14) ∧ Frame reg c d ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨u, header, atSlot, width, ident, keep, mem, persist⟩ := ShrinkHiddenWidth.native
+ (M := M) (pc := pc ∘ Sum.inr ∘ Sum.inl) (reg := widthRegs reg) (done := pc (.inl .slotOffset))
+ (fun j => link (.inr (.inl j))) m c entry
+ have k' (i : Fin r) (h1 : i ≠ reg 1) (h10 : i ≠ reg 10) (h11 : i ≠ reg 11)
+ (h12 : i ≠ reg 12) (h13 : i ≠ reg 13) : u.reg i = c.reg i := keep i h1 h10 h11 h12 h13
+ have fu : Frame reg c u := fun i h => k' i (h 1 (by decide)) (h 10 (by decide))
+ (h 11 (by decide)) (h 12 (by decide)) (h 13 (by decide))
+ change u.reg (reg 10) = m (c.reg (reg 5)).val at ident
+ change u.reg (reg 1) = supplyValue (supplyData
+ (ShrinkHiddenWidth.coordinate (c.reg (reg 8)) (m (c.reg (reg 5)).val)) (c.reg (reg 9)) 0)
+ (ShrinkHiddenWidth.rowBase (c.reg (reg 6)) (c.reg (reg 7)) (m (c.reg (reg 5)).val)) m at width
+ rw [hp] at ident
+ rw [hp, ready.layout, ready.selectors, ready.term, ready.termStride] at width
+ change u.reg (reg 1) = g.width m (m (ptr : Word W).val) at width
+ have header' : Prefix M m c u [] (g.header m (ptr : Word W)) := by
+ change Prefix M m c u [] (ShrinkHiddenWidth.events m (c.reg (reg 5))
+ (ShrinkHiddenWidth.rowBase (c.reg (reg 6)) (c.reg (reg 7)) (m (c.reg (reg 5)).val))
+ (ShrinkHiddenWidth.coordinate (c.reg (reg 8)) (m (c.reg (reg 5)).val))) at header
+ simpa only [Args.header, hp, ready.term, ready.termStride, ready.layout] using header
+ obtain ⟨d, slot, dest, out, limit, k₂, hm, hs⟩ := slot_run link g m u atSlot (ready.frame fu) e.1 e.2.length
+ ((congrArg Fin.val ident).trans hv.1) ((congrArg Fin.val width).trans hv.2.1)
+ refine ⟨d, header'.trans slot, dest, out, limit, ?_, ?_, fu.trans ?_, hm.trans mem, hs.trans persist⟩
+ · exact (k₂ _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans
+ (k' _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))
+ (reg.injective.ne (by decide)) (reg.injective.ne (by decide)))
+ · exact (k₂ _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans
+ (k' _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))
+ (reg.injective.ne (by decide)) (reg.injective.ne (by decide)))
+ · exact fun i hi => k₂ _ (hi 1 (by decide)) (hi 2 (by decide))
+
+/-- Trace for one field through the width lookup, the three slot-address instructions, and the
+private guesses of its bit list. -/
+def fieldEvents (g : Args W) (m : Memory W) (ptr : ℕ) (e : Row) :=
+ (g.header m (ptr : Word W) ++ List.replicate 3 .tick) ++ PrivateFields.events .guess e.2
+
+theorem field_run (link : Linked M pc reg done) (g : Args W) (m : Memory W) (c : Config W p r)
+ (ptr : ℕ) (e : Row) (entry : c.pc = pc (.inr (.inl 0))) (ready : Ready g reg c)
+ (hp : c.reg (reg 5) = (ptr : Word W)) (hv : ValidAt g m ptr e) :
+ ∃ d, Prefix M m c d e.2 (fieldEvents g m ptr e) ∧ d.pc = pc (.inl .decrement) ∧
+ d.reg (reg 5) = c.reg (reg 5) ∧ d.reg (reg 14) = c.reg (reg 14) ∧ Frame reg c d ∧
+ d.privateMem = PrivateFields.storeBits (g.slot e.1) e.2 c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨u, stage, ep, dst, limit, h5, h14, fu, hm, hs⟩ := stage_run link g m c ptr e entry ready hp hv
+ obtain ⟨d, guess, out⟩ := PrivateFields.guess_prefix (guesses link) u ep (g.slot e.1) e.2 dst limit
+ ((ready.frame fu).one) hv.2.2
+ have bits : Prefix M m u d e.2 (PrivateFields.events .guess e.2) := fun fuel tail => by
+ simpa only [PrivateFields.events_bits, ite_true] using guess.execute fuel m tail
+ have rest (i : Fin r) (h0 : i ≠ reg 0) (h2 : i ≠ reg 2) (h4 : i ≠ reg 4) : d.reg i = u.reg i :=
+ out.frame _ h0 h2 h4
+ refine ⟨d, stage.trans bits, out.pc, ?_, ?_, fu.trans ?_, ?_, out.persistent.trans hs⟩
+ · exact (rest _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans h5
+ · exact (rest _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans h14
+ · exact fun i hi => rest i (hi 0 (by decide)) (hi 2 (by decide)) (hi 4 (by decide))
+ · rw [out.privateMem, hm]
+
+theorem field_short (link : Linked M pc reg done) (g : Args W) (m : Memory W) (c : Config W p r)
+ (ptr : ℕ) (e : Row) (entry : c.pc = pc (.inr (.inl 0))) (ready : Ready g reg c)
+ (hp : c.reg (reg 5) = (ptr : Word W)) (hv : ValidAt g m ptr e)
+ (bits : List Bool) (short : bits.length < e.2.length) : ¬ DFS.Returns M c m bits := by
+ obtain ⟨u, stage, ep, dst, limit, _, _, fu, _, _⟩ := stage_run link g m c ptr e entry ready hp hv
+ intro accepts
+ obtain ⟨fuel, report, ran⟩ := (stage.returns bits).mp accepts
+ rw [PrivateFields.guess_short (guesses link) u ep _ _ dst limit (ready.frame fu).one hv.2.2 bits short fuel m] at ran
+ contradiction
+
+end PairSimulation.ShrinkHiddenGuess
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenTable.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenTable.lean
new file mode 100644
index 0000000000..dac88329e7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenTable.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenInputs
+import OAI.Computability.VPVNP.PairShrinkHiddenCost
+
+/-!
+# A native instruction table for the shrinking hidden-field pass
+
+Four public operands identify the packed owner, private slot base and stride,
+and old-level header. The finite table first loads these operands, reads the
+live published header, scans the owner's fields and enters an accepting halt.
+Only the binary compiler for the two stage constants depends on the stage.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkHiddenGuess.Table
+
+open BurstRAM PrivateRAM CompressorRecords NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable (s t : ℕ)
+
+/-- The compiled register-setup rows for the hidden scan's header recipe at selector width `s`
+and owner row stride `t`. -/
+abbrev lines := RegisterSetup.lines (Header.recipe s t)
+/-- Register count of the compiled header recipe, including its ten output registers and its
+expression-evaluation workspace. -/
+abbrev aux := RegisterSetup.regCount (Header.recipe s t)
+/-- Labels for the four public operand loads, the compiled header rows, the field-scan stages,
+and the accepting halt. -/
+abbrev Label := (Fin 4 ⊕ Fin (lines s t).length) ⊕ (Stage ⊕ Unit)
+/-- Physical register indices for the scan's 22 registers, the header compiler's auxiliary
+bank, and the six source registers. -/
+abbrev Reg := Fin 22 ⊕ (Fin (aux s t) ⊕ Fin 6)
+/-- Number of program counters in the reset-entry hidden-field instruction table. -/
+abbrev P := Fintype.card (Label s t)
+/-- Number of physical registers allocated to the reset-entry hidden-field program. -/
+abbrev R := Fintype.card (Reg s t)
+
+/-- Encode a symbolic instruction label as a program counter using the finite enumeration of
+table labels. -/
+def label (x : Label s t) : Fin (P s t) := Fintype.equivFin _ x
+/-- Program counter for the initial load of the indexed public operand. -/
+def boot (i : Fin 4) := label s t (.inl (.inl i))
+/-- Program counter of a field-scan stage inside the reset-entry table. -/
+def loop (j : Stage) := label s t (.inr (.inl j))
+/-- Program counter of the accepting instruction reached when the owner's remaining field count
+is zero. -/
+def done := label s t (.inr (.inr ()))
+/-- Program counter for header instruction number `i`. An index past the last header
+instruction enters the first scan control. -/
+def setup (i : ℕ) := if h : i < (lines s t).length then label s t (.inl (.inr ⟨i,h⟩))
+ else loop s t (.inl .one)
+
+/-- Embed the scan's 22 logical registers in the physical register bank of the table. -/
+def regs : Fin 22 ↪ Fin (R s t) := Function.Embedding.inl.trans (Fintype.equivFin _).toEmbedding
+/-- Physical register for each of the header recipe's six protected source positions. -/
+def inputs (i : Fin 6) : Fin (R s t) := Fintype.equivFin _ (Sum.inr (Sum.inr i))
+
+private def place {v : ℕ} (i : Fin v) : Fin 22 ⊕ (Fin v ⊕ Fin 6) :=
+ if h : i.val < 10 then .inl (Header.target ⟨i.val,h⟩) else .inr (.inl i)
+
+private theorem place_injective {v : ℕ} : Function.Injective (place (v := v)) := by
+ intro i j eq
+ have target : Function.Injective Header.target := by decide
+ by_cases hi : i.val < 10 <;> by_cases hj : j.val < 10 <;>
+ simp only [place,hi,hj, dite_true,dite_false,Sum.inl.injEq,Sum.inr.injEq,
+ reduceCtorEq] at eq
+ · exact Fin.ext (congrArg (fun k : Fin 10 => k.val) (target eq))
+ · exact eq
+
+/-- Embed the header compiler's registers so its ten outputs land in their designated scan
+registers and its other registers use the auxiliary bank. -/
+def vm : Fin (aux s t) ↪ Fin (R s t) := (⟨place,place_injective⟩ : _ ↪ _).trans
+ (Fintype.equivFin _).toEmbedding
+
+theorem safe (i : Fin (aux s t)) (j : Fin 6) : vm s t i ≠ inputs s t j := by
+ intro eq
+ have h : place i = .inr (.inr j) := (Fintype.equivFin _).injective eq
+ unfold place at h
+ split at h <;> simp at h
+
+theorem outputs (i : Fin 10) : vm s t (RegisterSetup.output (Header.recipe s t) i) =
+ regs s t (Header.target i) := by
+ change Fintype.equivFin _ (place _) = Fintype.equivFin _ _
+ simp [place,RegisterSetup.output,i.isLt]
+
+/-- Assign the four public operand loads to source positions 0, 1, 2, and 5, with the old-level
+header address in position 5. -/
+def source : Fin 4 → Fin 6 := ![0,1,2,5]
+/-- Successor of a public operand load. The first three loads advance to the next load, and the
+fourth enters header setup. -/
+def afterBoot (i : Fin 4) : Fin (P s t) :=
+ if h : i.val+1 < 4 then boot s t ⟨i.val+1,h⟩ else setup s t 0
+
+/-- Reset-entry instruction template that loads four public operands, executes the compiled
+header recipe, scans the owner's fields, and accepts at the end. -/
+def template : Template (P s t) (R s t) 4 where
+ literalWidth := 3
+ entry := boot s t 0
+ code j := match (Fintype.equivFin (Label s t)).symm j with
+ | .inl (.inl i) => .publicWord (inputs s t (source i)) i (afterBoot s t i)
+ | .inl (.inr i) => RegisterSetup.instruction (vm s t) (inputs s t) ((lines s t)[i.val]) (setup s t (i.val+1))
+ | .inr (.inl j) => instruction (loop s t) (regs s t) (done s t) j
+ | .inr (.inr ()) => .accept
+
+variable {W : ℕ} (pub : Fin 4 → Word W)
+
+theorem linked : Linked ((template s t).instantiate W pub) (loop s t) (regs s t) (done s t) := by
+ intro j
+ simpa only [Template.instantiate,template,loop,label,Equiv.symm_apply_apply] using
+ resize_instruction (k := 4) (W := W) (loop s t) (regs s t) (done s t) j
+
+private theorem resize_setup (i : Instr 2 (P s t) (R s t) 4) : (i.resize 3).resize W = i.resize W := by
+ cases i with
+ | constant r v pc =>
+ have fit : v.val < 8 := v.isLt.trans_le (by decide : 2^2 ≤ 2^3)
+ simp [Instr.resize,Nat.mod_eq_of_lt fit]
+ | _ => rfl
+
+theorem header_linked : RegisterSetup.Linked (vm s t) (inputs s t) ((template s t).instantiate W pub)
+ (setup s t) (lines s t) := by
+ intro i
+ simp only [Template.instantiate,template,setup,dite_eq_left i.isLt,label,Equiv.symm_apply_apply]
+ rw [← RegisterSetup.resize_instruction (w := 3),resize_setup, RegisterSetup.resize_instruction]
+
+theorem boot_code (i : Fin 4) : ((template s t).instantiate W pub).code (boot s t i) =
+ .publicWord (inputs s t (source i)) i (afterBoot s t i) := by
+ simp [Template.instantiate,template,boot,label,Instr.resize]
+
+theorem done_code : ((template s t).instantiate W pub).code (done s t) = .accept := by
+ simp [Template.instantiate,template,done,label,Instr.resize]
+
+end PairSimulation.ShrinkHiddenGuess.Table
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenTypedDecode.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenTypedDecode.lean
new file mode 100644
index 0000000000..725ba29dc7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenTypedDecode.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenParser
+import OAI.Computability.VPVNP.PairShrinkHiddenDecode
+
+/-!
+# Typed assignments for arbitrary hidden-field streams
+
+Splitting a complete raw stream at the recorded widths gives exactly one
+assignment to the absorbed edges resident at the site. The native decoder
+produces those fields with the original IDs and the exact remaining suffix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkHiddenSlots
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords ShrinkHistoryRows
+open LocalHistory NetworkKernel ShrinkHiddenGuess
+open scoped Classical
+
+private def fieldRows {n : ℕ} (key width : Fin n → ℕ) (x : (j : Fin n) → Word (width j)) :=
+ List.ofFn fun j => (key j, List.ofFn (RAMSerialization.wordBits _ (x j)))
+
+private theorem fieldRows_cons {n : ℕ} (key width : Fin (n+1) → ℕ) (x : (j : Fin (n+1)) → Word (width j)) :
+ fieldRows key width x = (key 0, List.ofFn (RAMSerialization.wordBits _ (x 0))) ::
+ fieldRows (fun j => key j.succ) (fun j => width j.succ) (fun j => x j.succ) :=
+ List.ofFn_succ
+
+/-- Split a stream into an ordered vector of full-width words. -/
+private theorem decode_fields (n : ℕ) (key width : Fin n → ℕ) (x : (j : Fin n) → Word (width j))
+ (bs : List Bool) (enough : (stream (fieldRows key width x)).length ≤ bs.length) :
+ ∃ y : (j : Fin n) → Word (width j),
+ decode (fieldRows key width x) bs =
+ (fieldRows key width y, bs.drop (stream (fieldRows key width x)).length) ∧
+ bs = stream (fieldRows key width y) ++ bs.drop (stream (fieldRows key width x)).length := by
+ induction n generalizing bs with
+ | zero => exact ⟨x,rfl,rfl⟩
+ | succ n ih =>
+ let rest := fieldRows (fun j : Fin n => key j.succ) (fun j => width j.succ) (fun j => x j.succ)
+ have len : (stream (fieldRows key width x)).length = width 0 + (stream rest).length := by
+ rw [fieldRows_cons]
+ simp only [stream, List.flatMap_cons, List.length_append, List.length_ofFn, rest]
+ have hw : width 0 ≤ bs.length := (Nat.le_add_right _ _).trans (len ▸ enough)
+ obtain ⟨ys, decoded, part⟩ := ih (fun j => key j.succ) (fun j => width j.succ) (fun j => x j.succ)
+ (bs.drop (width 0)) (by rw [len] at enough; simp [rest] at enough ⊢; omega)
+ let bits : Fin (width 0) → Bool := fun j => bs[j.val]'(j.isLt.trans_le hw)
+ have head : List.ofFn bits = bs.take (width 0) := by
+ apply List.ext_getElem (by simp [hw])
+ intros
+ simp [bits]
+ let y (j : Fin (n+1)) : Word (width j) := Fin.cases ((RAMSerialization.wordBits _).symm bits) ys j
+ have newHead : List.ofFn (RAMSerialization.wordBits _ (y 0)) = bs.take (width 0) :=
+ (congrArg List.ofFn ((RAMSerialization.wordBits _).apply_symm_apply bits)).trans head
+ refine ⟨y, ?_, ?_⟩
+ · rw [len, fieldRows_cons key width x, fieldRows_cons key width y, decode, List.length_ofFn, decoded, newHead]
+ simp only [List.drop_drop]
+ rfl
+ · rw [len, fieldRows_cons key width y]
+ change bs = List.ofFn (RAMSerialization.wordBits _ (y 0)) ++
+ stream (fieldRows (fun j => key j.succ) (fun j => width j.succ) ys) ++ _
+ rw [newHead, List.append_assoc, ← List.drop_drop, ← part, List.take_append_drop]
+
+private theorem decode_order {U : Type} (o : Order U) (key width : U → ℕ)
+ (x : (e : U) → Word (width e)) (bs : List Bool) :
+ let fields := fun (z : (e : U) → Word (width e)) =>
+ fieldRows (fun j => key (o.entries j)) (fun j => width (o.entries j)) (fun j => z (o.entries j))
+ (stream (fields x)).length ≤ bs.length →
+ ∃ z, decode (fields x) bs = (fields z, bs.drop (stream (fields x)).length) ∧
+ bs = stream (fields z) ++ bs.drop (stream (fields x)).length := by
+ intro fields enough
+ obtain ⟨y,decoded,part⟩ := decode_fields o.length (fun j => key (o.entries j))
+ (fun j => width (o.entries j)) (fun j => x (o.entries j)) bs enough
+ let F := fun e => Word (width e)
+ let z := Equiv.piCongrLeft F o.entries y
+ have write : fields z = fieldRows (fun j => key (o.entries j)) (fun j => width (o.entries j)) y := by
+ apply congrArg List.ofFn
+ funext j
+ exact congrArg (fun t => (key (o.entries j), List.ofFn (RAMSerialization.wordBits _ t)))
+ (Equiv.piCongrLeft_apply_apply F o.entries y j)
+ exact ⟨z, write.symm ▸ decoded, write.symm ▸ part⟩
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g)) (layout : Bool)
+variable (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+variable (v : (X.Base × BitWord (Shrink.J a)) × BitWord g)
+local notation "owner" => X.packingData.shrinkInternalOwner layout
+local notation "Labels" => internalLabel widths layout
+
+set_option maxHeartbeats 2500000 in
+/-- The native decoder can start with any placeholders of the right widths.
+Its output is precisely the rows of a typed local assignment. -/
+theorem decode_rows (placeholder : Placed owner Labels v) (bs : List Bool)
+ (enough : (stream (rows X layout widths v placeholder)).length ≤ bs.length) :
+ ∃ h : Placed owner Labels v,
+ decode (rows X layout widths v placeholder) bs =
+ (rows X layout widths v h, bs.drop (stream (rows X layout widths v placeholder)).length) ∧
+ bs = stream (rows X layout widths v h) ++ bs.drop (stream (rows X layout widths v placeholder)).length := by
+ let o := residents (hiddenOrder X) owner v
+ let width := fun e : {e // v = owner e} => widths e.val.1 (!layout,e.val.2)
+ obtain ⟨z,decoded,part⟩ := decode_order o (fun e => id X e.val) width
+ (fun e => placeholder e.val e.prop) bs enough
+ exact ⟨fun e he => z ⟨e,he⟩, decoded, part⟩
+
+open private fiber_rows from OAI.Computability.VPVNP.PairShrinkHiddenParser
+
+/-- Equality of two complete prefixes, allowing arbitrary suffixes, forces
+both the typed assignment and the suffix to agree. -/
+theorem rows_prefix_unique (h h' : Placed owner Labels v) (tail tail' : List Bool)
+ (eqn : stream (rows X layout widths v h) ++ tail = stream (rows X layout widths v h') ++ tail') :
+ h = h' ∧ tail = tail' := by
+ let r := fiber owner v (residents (hiddenOrder X) owner v)
+ (fun e => ChoiceReader.bounded (widths e.1 (!layout,e.2)) _ le_rfl)
+ have encode (q : Placed owner Labels v) : r.encode q = stream (rows X layout widths v q) := by
+ simpa only [stream, List.flatMap_def] using fiber_rows X layout widths v q
+ let bs := stream (rows X layout widths v h) ++ tail
+ have one := (r.read_iff bs h tail).mpr (by rw [encode])
+ have two := (r.read_iff bs h' tail').mpr (by rw [encode]; exact eqn)
+ exact Prod.mk.inj (Option.some.inj (one.symm.trans two))
+
+section Native
+
+open BurstRAM.PrivateRAM
+
+variable {w p r k : ℕ} {M : Machine w p r k} {pc : Stage → Fin p} {reg : Fin 22 ↪ Fin r} {done : Fin p}
+
+/-- Execute the entire hidden-field loop on an arbitrary complete input.
+Its continuation sees precisely the suffix after the decoded typed assignment. -/
+theorem native_complete (placeholder : Placed owner Labels v)
+ (link : Linked M pc reg done) (arg : Args w) (mem : Memory w)
+ (c : Config w p r) (entry : c.pc = pc (.inl .one)) (inputs : Inputs arg reg c)
+ (fit : arg.countBase + arg.owner < 2 ^ w)
+ (count : (mem (arg.countBase + arg.owner)).val = (rows X layout widths v placeholder).length)
+ (valid : ValidRows arg mem (rows X layout widths v placeholder)) (bs : List Bool)
+ (enough : (stream (rows X layout widths v placeholder)).length ≤ bs.length) :
+ let tail := bs.drop (stream (rows X layout widths v placeholder)).length
+ ∃ h : Placed owner Labels v, ∃ d : Config w p r,
+ bs = stream (rows X layout widths v h) ++ tail ∧ d.pc = done ∧
+ d.privateMem = storeRows arg.scratchBase arg.slotStride (rows X layout widths v h) c.privateMem ∧
+ d.persistent = c.persistent ∧
+ ∀ fuel, execute M.program (fuel + (events arg mem (rows X layout widths v h)).length) c mem bs =
+ (execute M.program fuel d mem tail).map
+ (fun q => ⟨events arg mem (rows X layout widths v h) ++ q.events, q.result⟩) := by
+ intro tail
+ obtain ⟨h, parsed, split⟩ := decode_rows X layout widths v placeholder bs enough
+ obtain ⟨d,hd,store,per,run⟩ := native_decode link arg mem _ c entry inputs fit count valid bs enough
+ rw [parsed] at store run
+ exact ⟨h,d,split,hd,store,per,run⟩
+
+end Native
+
+end PairSimulation.ShrinkHiddenSlots
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHiddenWidth.lean b/lean/OAI/Computability/VPVNP/PairShrinkHiddenWidth.lean
new file mode 100644
index 0000000000..75172b8ab9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHiddenWidth.lean
@@ -0,0 +1,233 @@
+import OAI.Computability.VPVNP.PairNodeChildLoop
+import OAI.Computability.VPVNP.CompressorShrinkSliceTable
+
+/-!
+# Reading the width of a hidden shrinking field
+
+A dense field identifier encodes a motif ordinal and one of four roles.
+The reader looks up the motif's repetition count and the role's payload in
+the layout opposite the surviving one. The resulting bit width is their
+payload plus the selector bits for all repetitions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkHiddenWidth
+
+open BurstRAM PrivateRAM CompressorRecords ShrinkSliceArrays NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.read ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r k : ℕ}
+
+/-- Registers zero through four hold the ID pointer, term base, term stride,
+layout bit, and selector width. Register five receives the width, six keeps
+the ID, and registers seven through nine are temporary. -/
+def instruction (pc : Fin 18 → Fin p) (reg : Fin 10 ↪ Fin r) (done : Fin p) : Fin 18 → Instr w p r k :=
+ ![.readExternal (reg 6) (reg 0) (pc 1),
+ .constant (reg 8) 4 (pc 2),
+ .binary .div (reg 7) (reg 6) (reg 8) (pc 3),
+ .binary .mul (reg 7) (reg 7) (reg 2) (pc 4),
+ .binary .add (reg 7) (reg 1) (reg 7) (pc 5),
+ .constant (reg 9) 1 (pc 6),
+ .binary .add (reg 5) (reg 7) (reg 9) (pc 7),
+ .readExternal (reg 5) (reg 5) (pc 8),
+ .binary .mul (reg 5) (reg 5) (reg 4) (pc 9),
+ .binary .sub (reg 9) (reg 9) (reg 3) (pc 10),
+ .binary .mul (reg 9) (reg 9) (reg 8) (pc 11),
+ .binary .mod (reg 8) (reg 6) (reg 8) (pc 12),
+ .binary .add (reg 9) (reg 9) (reg 8) (pc 13),
+ .constant (reg 8) 2 (pc 14),
+ .binary .add (reg 8) (reg 7) (reg 8) (pc 15),
+ .binary .add (reg 8) (reg 8) (reg 9) (pc 16),
+ .readExternal (reg 8) (reg 8) (pc 17),
+ .binary .add (reg 5) (reg 8) (reg 5) done]
+
+theorem resize_instruction (pc : Fin 18 → Fin p) (reg : Fin 10 ↪ Fin r) (done : Fin p) (i : Fin 18) :
+ (instruction (w := 3) (k := k) pc reg done i).resize w = instruction pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- The machine implements all 18 width-reader instructions at their assigned addresses with
+the specified register bank and continuation. -/
+def Linked (M : Machine w p r k) (pc : Fin 18 → Fin p) (reg : Fin 10 ↪ Fin r) (done : Fin p) :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+/-- Word address of the selected term record. The quotient of the dense hidden ID by four
+selects the motif ordinal in the strided term array. -/
+def rowBase (termBase termStride id : Word w) : Word w :=
+ termBase + BinaryOp.div.eval id 4 * termStride
+
+/-- Payload offset among the eight role coordinates of a term. It takes the role from the ID
+modulo four and chooses the four-role half opposite the surviving layout. -/
+def coordinate (layout id : Word w) : Word w :=
+ (1-layout) * 4 + BinaryOp.mod.eval id 4
+
+/-- The 18 events of a width lookup, including the dense ID read at `ptr`, the repetition count
+at `base + 1`, and the payload at `base + 2 + coord`. -/
+def events (m : Memory w) (ptr base coord : Word w) : List (Event w) :=
+ let read := fun addr : Word w => Event.read addr (m addr.val)
+ [read ptr,.tick,.tick,.tick,.tick,.tick,.tick,read (base+1),
+ .tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,read (base+2+coord),.tick]
+
+theorem cost (m : Memory w) (ptr base coord : Word w) :
+ (events m ptr base coord).length = 18 ∧ countProbes (events m ptr base coord) = 3 ∧
+ choiceBits (events m ptr base coord) = [] := ⟨rfl, rfl, rfl⟩
+
+variable {M : Machine w p r k} {pc : Fin 18 → Fin p} {reg : Fin 10 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (link : Linked M pc reg done) (i : Fin 18) {c : Config w p r}
+ (h : c.pc = pc i) : M.program.step c = (instruction pc reg done i).run M.publicData c := by
+ simp [Machine.program, h, link i]
+
+/-- Exact native execution, including the retained ID and the complete
+frame on the caller's configuration. -/
+theorem native (link : Linked M pc reg done) (m : Memory w) (c : Config w p r) (hc : c.pc = pc 0) :
+ let ptr := c.reg (reg 0)
+ let id := m ptr.val
+ let base := rowBase (c.reg (reg 1)) (c.reg (reg 2)) id
+ let coord := coordinate (c.reg (reg 3)) id
+ ∃ d, Prefix M m c d [] (events m ptr base coord) ∧ d.pc = done ∧
+ d.reg (reg 5) = supplyValue (supplyData coord (c.reg (reg 4)) 0) base m ∧
+ d.reg (reg 6) = id ∧
+ (∀ j, j ≠ reg 5 → j ≠ reg 6 → j ≠ reg 7 → j ≠ reg 8 → j ≠ reg 9 → d.reg j = c.reg j) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ intro ptr id base coord
+ have path := ReadPrefix.read (m := m) ptr (step_at link 0 hc)
+ (ReadPrefix.tick (step_at link 1 rfl)
+ (ReadPrefix.tick (step_at link 2 rfl)
+ (ReadPrefix.tick (step_at link 3 rfl)
+ (ReadPrefix.tick (step_at link 4 rfl)
+ (ReadPrefix.tick (step_at link 5 rfl)
+ (ReadPrefix.tick (step_at link 6 rfl)
+ (ReadPrefix.read _ (step_at link 7 rfl)
+ (ReadPrefix.tick (step_at link 8 rfl)
+ (ReadPrefix.tick (step_at link 9 rfl)
+ (ReadPrefix.tick (step_at link 10 rfl)
+ (ReadPrefix.tick (step_at link 11 rfl)
+ (ReadPrefix.tick (step_at link 12 rfl)
+ (ReadPrefix.tick (step_at link 13 rfl)
+ (ReadPrefix.tick (step_at link 14 rfl)
+ (ReadPrefix.tick (step_at link 15 rfl)
+ (ReadPrefix.read _ (step_at link 16 rfl)
+ (ReadPrefix.tick (step_at link 17 rfl) (ReadPrefix.nil _))))))))))))))))))
+ let final {d : Config w p r} {es : List (Event w)} (_ : ReadPrefix M m c es d) := d
+ refine ⟨final path, ?_, rfl, ?_, ?_, ?_, rfl, rfl⟩
+ · intro fuel tail
+ simpa (config := { decide := true }) [events, ptr, id, base, coord, rowBase, coordinate,
+ Config.put, reg.injective.eq_iff, BinaryOp.eval, final] using ReadPrefix.execute path fuel tail
+ · simp (config := { decide := true }) [final, Config.put, reg.injective.eq_iff, BinaryOp.eval,
+ supplyValue, supplyData, base, coord, rowBase, coordinate, id, ptr]
+ · simp (config := { decide := true }) [final, Config.put, reg.injective.eq_iff, id, ptr]
+ · intro j h5 h6 h7 h8 h9
+ simp [final, Config.put, Function.update_of_ne h5, Function.update_of_ne h6,
+ Function.update_of_ne h7, Function.update_of_ne h8, Function.update_of_ne h9]
+
+/-- Decode the motif ordinal in the dense field ID. -/
+theorem rowBase_eq (id : Word w) (termBase stride ordinal : ℕ) (t : Fin 4)
+ (hid : id.val = ordinal*4+t.val) (h4 : 4 < 2^w) :
+ rowBase (termBase : Word w) (stride : Word w) id = ((termBase+ordinal*stride : ℕ) : Word w) := by
+ have div : BinaryOp.div.eval id 4 = (ordinal : Word w) := by
+ change Fin.ofNat _ (id.val/(4 : Word w).val) = _
+ rw [show (4 : Word w).val = 4 from Nat.mod_eq_of_lt h4, hid,
+ show (ordinal*4+t.val)/4 = ordinal by have := t.isLt; omega]
+ rfl
+ simp only [rowBase, div, Nat.cast_add, Nat.cast_mul]
+
+/-- Decode the role and switch to the hidden half of the eight payload words. -/
+theorem coordinate_eq (id : Word w) (layout : Bool) (ordinal : ℕ) (t : Fin 4)
+ (hid : id.val = ordinal*4+t.val) (h4 : 4 < 2^w) :
+ coordinate (layout.toNat : Word w) id = (((!layout).toNat*4+t.val : ℕ) : Word w) := by
+ have role : BinaryOp.mod.eval id 4 = (t.val : Word w) := by
+ change Fin.ofNat _ (id.val%(4 : Word w).val) = _
+ rw [show (4 : Word w).val = 4 from Nat.mod_eq_of_lt h4, hid,
+ show (ordinal*4+t.val)%4 = t.val by have := t.isLt; omega]
+ rfl
+ simp only [coordinate, role, Nat.cast_add, Nat.cast_mul]
+ cases layout <;> simp
+
+/-- Numeric readback of the native width register for an arbitrary fitted
+row. Both the payload and the repetition factor are read from memory. -/
+theorem value_eq (m : Memory w) (id selectors : Word w) (termBase stride ordinal : ℕ) (layout : Bool)
+ (t : Fin 4) (width : ℕ) (hid : id.val = ordinal*4+t.val)
+ (room : termBase+ordinal*stride+10 ≤ 2^w)
+ (read : (m (termBase+ordinal*stride+2+((!layout).toNat*4+t.val))).val +
+ (m (termBase+ordinal*stride+1)).val * selectors.val = width) (fit : width < 2^w) :
+ (supplyValue (supplyData (coordinate (layout.toNat : Word w) id) selectors 0)
+ (rowBase (termBase : Word w) (stride : Word w) id) m).val = width := by
+ let base := termBase+ordinal*stride
+ let index := (!layout).toNat*4+t.val
+ have h4 : 4 < 2^w := by omega
+ have hi : index < 8 := by
+ have h := Bool.toNat_le (!layout)
+ have ht := t.isLt
+ dsimp only [index]
+ omega
+ rw [rowBase_eq _ _ _ _ _ hid h4, coordinate_eq _ _ _ _ hid h4]
+ have hb : (base : Word w).val = base := Fin.val_cast_of_lt (by dsimp [base]; omega)
+ have hc : (index : Word w).val = index := Fin.val_cast_of_lt (by omega)
+ apply supplyValue_eq _ _ _ _ _ fit
+ · change (base : Word w).val+2+(index : Word w).val < 2^w
+ rw [hb, hc]
+ dsimp [base]
+ omega
+ · change (m ((base : Word w).val+2+(index : Word w).val)).val +
+ (m ((base : Word w).val+1)).val * selectors.val = _
+ rwa [hb, hc]
+
+section Term
+
+open Compression Compression.PackingData ShrinkSliceSweep Allocation SliceSchedule
+open MotifBlocks MotifGrid MotifConversion MotifDemandPadding ShrinkMotif
+
+variable {d c n N J nL : ℕ} {V H Tag L : Type}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (cd : P.BundleNumbering) (site : Site V Tag L ≃ Fin n)
+
+local notation "count" => (n*d)*pieceCount d c
+local notation "order" => ShrinkMotifOrder.number P cd site
+
+variable (T : Allocation w ((n*d)*pieceCount d c) (Slots.oldBaseArcCount N J d c * nL))
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable {K : Type*} [_root_.Field K] {factor : ℝ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (old : Arc V H Tag L d c → ℕ) (choice : ∀ q : P.Motif, P.ShrinkChoice cd old F q)
+
+/-- The term directory's chosen hidden width is precisely the native
+readback for its corresponding dense ID. -/
+theorem term_value_eq (m : Memory w) (terms : Terms P cd site T F old choice m)
+ (allocation : T.Fits) (sel : T.selectors.val = F.selectorBits)
+ (j : Fin count) (t : Fin 4) (id : Word w) (hid : id.val = j.val*4+t.val)
+ (fit : P.termWidths F cd old choice ((order).symm j) (!T.layout) t < 2^w) :
+ (supplyValue (supplyData (coordinate (T.layout.toNat : Word w) id) T.selectors 0)
+ (rowBase (T.termBase : Word w) (T.termStride : Word w) id) m).val =
+ P.termWidths F cd old choice ((order).symm j) (!T.layout) t := by
+ have limit := T.term_stop allocation j
+ have room : T.termStart j+10 ≤ 2^w :=
+ limit.trans ((Nat.le_add_right .. : T.widthBase ≤ T.widthEnd).trans
+ ((Nat.le_add_right .. : T.widthEnd ≤ T.last).trans allocation.room.le))
+ apply value_eq m id T.selectors T.termBase T.termStride j.val T.layout t _ hid room _ fit
+ have fields := terms j
+ let i := supplyRoles.symm (!T.layout, t)
+ have val := fields.2.2 i
+ have rep := fields.2.1
+ have hb : (Fin.ofNat (2^w) (T.termStart j)).val = T.termStart j :=
+ (Fin.val_ofNat ..).trans (Nat.mod_eq_of_lt (by omega))
+ rw [hb, show i.val = (!T.layout).toNat*4+t.val from supplyRoles_index ..,
+ show supplyRoles i = (!T.layout,t) from supplyRoles.apply_symm_apply _] at val
+ rw [hb] at rep
+ change (m (T.termStart j+2+((!T.layout).toNat*4+t.val))).val +
+ (m (T.termStart j+1)).val * T.selectors.val = _
+ rw [val,rep,sel]
+ rfl
+
+end Term
+end PairSimulation.ShrinkHiddenWidth
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHookActionRates.lean b/lean/OAI/Computability/VPVNP/PairShrinkHookActionRates.lean
new file mode 100644
index 0000000000..ca1e4f74d3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHookActionRates.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+import OAI.Computability.VPVNP.PairShrinkHookRates
+import OAI.Computability.VPVNP.PairShrinkResidentBudget
+
+/-!
+# Ordinal cost of the canonical shrinking parser
+
+The parent packet and the parsed child and hidden fields select the physical
+resident jobs. Their actual gather and matrix actions determine the cost
+bound on every successful tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression CompressorRecords CompressorRecords.ShrinkBlockInputs
+open LocalHistory ShrinkNodeCost VertexImage
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : MapResidentRows.Site X}
+ {w n t : ℕ} (site : CanonicalSite B i X sel v w n t) (ord : B.Entry → Fin t)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+
+variable (node : Word w)
+ (order : (site.descriptor node).sites = List.ofFn fun j =>
+ ((((shrinkPassReaders B f hf i rfl X).order sel).children v).entries j).val)
+ (saved : Scratch w n) (bits tail : List Bool) (body : VisitPath w n)
+ (room : RateRoom S (selectedHeaderLength B) (MapWitness.scanCoefficient B ord)
+ (prologueCoefficient B) n)
+ (level : site.levels - (site.passIndex + 1) ≤ (S.steps + 1) * (n.log2 + 1))
+ (wire : X.maxWireWidth ≤ n)
+ (hit : (canonicalParent site ord f hf).read node saved bits = some (body, tail))
+
+include order room level wire hit in
+/-- The selected parent parser leaves room for the dispatcher's probe and instructions. -/
+theorem canonicalParent_rates :
+ countProbes body.trace + 1 ≤
+ probeRate S (MapWitness.scanCoefficient B ord) (prologueCoefficient B) * (n.log2 + 1) ∧
+ body.trace.length + 9 ≤ n ^ 43 := by
+ simp only [canonicalParent, parentParser] at hit
+ obtain ⟨parent, _, read⟩ := Option.bind_eq_some_iff.mp hit
+ let regions := TerminalLayout.privateRegions (slotDegree S) n site.rowEnd (Fintype.card B.Entry)
+ refine selected_hook_rates B f hf i X sel v site.descriptor node order site.seed
+ regions.arguments site.incidence site.mem site.older site.hiddenArgs
+ (canonicalActions site ord f hf parent) site.publicData site.levels site.passIndex
+ site.level ((MapResidentRows.siteIndex X v).val : Word w) saved bits tail body
+ (MapWitness.scanCoefficient B ord) n room level wire ?_ read
+ intro child _ hidden out es _ _ scan
+ dsimp only [canonicalActions, typedActions, canonicalBank] at scan
+ exact MapWitness.scan_bound B ord i X sel v _ _ site.mem site.level site.term site.source
+ site.width _ _ node _ out es scan
+
+include order room level wire hit in
+/-- Every successful tape of the canonical parser gives an ordinal job with the
+uniform scan coefficient of the installed resident maps. -/
+theorem canonicalParent_ordinal_cost (offset : Word w) :
+ ordinalJobCost n 1 (probeRate S (MapWitness.scanCoefficient B ord) (prologueCoefficient B))
+ (dispatchJob site.mem offset node saved body) := by
+ obtain ⟨probes, ticks⟩ :=
+ canonicalParent_rates site ord f hf node order saved bits tail body room level wire hit
+ exact dispatched_ordinal_cost site.mem offset node saved body probes ticks
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHookBudget.lean b/lean/OAI/Computability/VPVNP/PairShrinkHookBudget.lean
new file mode 100644
index 0000000000..1bfab5a1f7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHookBudget.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairShrinkNodeClock
+import OAI.Computability.VPVNP.PairShrinkRoleSelectedChildren
+import OAI.Computability.VPVNP.PairShrinkRolePhysicalHidden
+import OAI.Computability.VPVNP.PairShrinkRoleMapStart
+
+/-! # Native costs at the entry of a physical shrinking hook
+
+The successful hook determines the actual stored child arguments, hidden
+bits and resident scan on the outgoing private scratch. The three setup
+traces are the linked level selector, cached hidden header, and map reload.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkNodeCost
+
+open BurstRAM PrivateRAM DFS Compression CompressorRecords NodeArguments NodeArguments.ChildScan
+open ShrinkRole ShrinkHiddenGuess
+open scoped Fin.CommRing
+
+variable {w endAddr a g : ℕ} {X : State a g}
+
+variable (A : Arena) (T : IncidenceDirectory w) (m : Memory w) (older cap : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w X) (args : Args w) (seed : List Row)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w endAddr))
+ (pub : Fin 11 → Word w) (levels old stages stage selectors stride : ℕ) (head owner : Word w)
+ (node : Word w) (saved : Scratch w endAddr) (bs tail : List Bool) (job : VisitPath w endAddr)
+ (hit : (hook (visitReader A T m older cap desc (fun _ => args) (fun _ => seed) maps
+ (selectedChildSetup pub m levels old stages stage a)
+ (fun _ => physicalHiddenSetup selectors stride head.val m)
+ (fun _ _ => ShrinkVertexImage.mapStartSetup m head owner))).read node saved bs =
+ some (job, tail))
+
+include hit
+
+set_option maxHeartbeats 600000 in
+-- The setup equations unfold the composed selector and physical header traces.
+theorem hook_counts :
+ ∃ xs hs mapIn mapOut ms, xs.map Child.site = (desc node).sites ∧ hs.length = seed.length ∧
+ (stream hs).length = (stream seed).length ∧
+ ResidentMapLoop.Exact.scan node (maps xs hs) mapIn = some (ms, mapOut) ∧
+ job.trace.length = 88 + 6 * (levels - (old + 1)) + stages + 2 * stage + 2 ^ a +
+ VertexLevel.hiddenCount +
+ (RegisterSetup.lines (Header.recipe selectors stride)).length +
+ (10 + 15 * 2 ^ a) * (desc node).sites.length +
+ 6 * ChildArguments.demand X (desc node).sites + 25 * seed.length +
+ 6 * (stream seed).length + ms.length ∧
+ countProbes job.trace = 25 + (levels - (old + 1)) +
+ (1 + 3 * 2 ^ a) * (desc node).sites.length + 3 * seed.length + countProbes ms := by
+ obtain ⟨⟨out, rest⟩, found, hj⟩ := Option.map_eq_some_iff.mp hit
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj hj
+ exact native_cost A T m older cap desc (fun _ => args) (fun _ => seed) maps pub (old + 1)
+ (levels - (old + 1)) stages stage selectors stride head.val owner _ _ _ node saved bs rest out
+ rfl (fun _ _ => rfl) (fun _ _ _ => by rw [Fin.cast_val_eq_self]; rfl) found
+
+set_option maxHeartbeats 600000 in
+-- The setup equations unfold the composed selector and physical header traces.
+/-- The map trace in the hook counts starts at the scratch reached by the
+successful child and hidden reads, with the hidden read returning the hook's suffix. -/
+theorem hook_counts_reached :
+ ∃ child mid hidden mapOut ms,
+ ChildArguments.reader A T m older cap desc node
+ ((selectedChildSetup pub m levels old stages stage a).updated node saved) bs =
+ some (child, mid) ∧
+ hiddenReader args m seed node
+ ((physicalHiddenSetup selectors stride head.val m).updated node child.updated) mid =
+ some (hidden, tail) ∧
+ ResidentMapLoop.Exact.scan node (maps child.value hidden.value)
+ ((ShrinkVertexImage.mapStartSetup m head owner).updated node hidden.updated) =
+ some (ms, mapOut) ∧
+ job.trace.length = 88 + 6 * (levels - (old + 1)) + stages + 2 * stage + 2 ^ a +
+ VertexLevel.hiddenCount +
+ (RegisterSetup.lines (Header.recipe selectors stride)).length +
+ (10 + 15 * 2 ^ a) * (desc node).sites.length +
+ 6 * ChildArguments.demand X (desc node).sites + 25 * seed.length +
+ 6 * (stream seed).length + ms.length ∧
+ countProbes job.trace = 25 + (levels - (old + 1)) +
+ (1 + 3 * 2 ^ a) * (desc node).sites.length + 3 * seed.length + countProbes ms := by
+ obtain ⟨⟨out, rest⟩, found, hj⟩ := Option.map_eq_some_iff.mp hit
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj hj
+ obtain ⟨child, mid, hidden, mapOut, ms, readChild, readHidden, scan, _, _, _, ticks, probes⟩ :=
+ native_cost_reached A T m older cap desc (fun _ => args) (fun _ => seed) maps pub (old + 1)
+ (levels - (old + 1)) stages stage selectors stride head.val owner _ _ _ node saved bs rest out
+ rfl (fun _ _ => rfl) (fun _ _ _ => by rw [Fin.cast_val_eq_self]; rfl) found
+ exact ⟨child, mid, hidden, mapOut, ms, readChild, readHidden, scan, ticks, probes⟩
+
+end PairSimulation.ShrinkNodeCost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkHookRates.lean b/lean/OAI/Computability/VPVNP/PairShrinkHookRates.lean
new file mode 100644
index 0000000000..d8af859d58
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkHookRates.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.PairShrinkHookBudget
+import OAI.Computability.VPVNP.PairShrinkNodeRates
+import OAI.Computability.VPVNP.PairShrinkPrologueBudget
+
+/-!
+# Ordinal cost of a selected shrinking hook
+
+The selected child and hidden directories bound the two scans before the
+resident maps. A map estimate on the scratch reached by these scans bounds
+the whole accepted job, including the dispatch from its ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkNodeCost
+
+open BurstRAM BurstRAM.PrivateRAM DFS Compression Compression.ShrinkMotif CompressorRecords
+open CompressorRecords.ShrinkSlots NodeArguments NodeArguments.ChildScan LocalHistory NetworkKernel
+open ShrinkRole ShrinkHiddenGuess ShrinkVertexImage VertexImage
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+
+/-- Instruction length of the installed hidden header at each stage. -/
+noncomputable def selectedHeaderLength (i : Fin S.steps) : ℕ :=
+ (RegisterSetup.lines (Header.recipe B.shrink.selectorBits (hiddenStride i))).length
+
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps)
+ {g w endAddr : ℕ}
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink)
+ (v : (X.Base × BitWord (packingTagBits (2 ^ S.degreeExponent i.castSucc))) × BitWord g)
+ (desc : Word w → ChildArguments.Descriptor w X) (node : Word w)
+ (order : (desc node).sites = List.ofFn fun j =>
+ ((((shrinkPassReaders B f hf i rfl X).order sel).children v).entries j).val)
+
+variable (placeholder : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkHiddenRows.widths X B.shrink sel) (selectedLayout X B.shrink sel)) v)
+ (A : Arena) (inc : IncidenceDirectory w) (m : Memory w) (older : ℕ) (arg : Args w)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w endAddr))
+ (pub : Fin 11 → Word w) (levels old : ℕ) (head owner : Word w)
+
+/-- The physical hidden row directory at this site of the chosen layout. -/
+noncomputable abbrev selectedSeed :=
+ ShrinkHiddenSlots.rows X (selectedLayout X B.shrink sel) (ShrinkHiddenRows.widths X B.shrink sel)
+ v placeholder
+
+variable (saved : Scratch w endAddr) (bits tail : List Bool) (body : VisitPath w endAddr)
+ (mapC n : ℕ) (room : RateRoom S (selectedHeaderLength B) mapC (prologueCoefficient B) n)
+ (level : levels - (old + 1) ≤ (S.steps + 1) * (n.log2 + 1)) (wire : X.maxWireWidth ≤ n)
+ (mapRates : ∀ (child : Outcome w endAddr (List (Child X))) (mid : List Bool)
+ (hidden : Outcome w endAddr (List Row)) (mapOut : Scratch w endAddr) (trace : List (Event w)),
+ ChildArguments.reader A inc m older B.recordLimit desc node
+ ((selectedChildSetup pub m levels old S.steps i.val (oldExponent i)).updated node saved)
+ bits = some (child, mid) →
+ hiddenReader arg m (selectedSeed B i X sel v placeholder) node
+ ((physicalHiddenSetup B.shrink.selectorBits (hiddenStride i) head.val m).updated node
+ child.updated) mid = some (hidden, tail) →
+ ResidentMapLoop.Exact.scan node (maps child.value hidden.value)
+ ((mapStartSetup m head owner).updated node hidden.updated) = some (trace, mapOut) →
+ trace.length ≤ mapC * (X.maxWireWidth + 1) ∧ countProbes trace ≤ mapC)
+ (hit : (hook (visitReader A inc m older B.recordLimit desc (fun _ => arg)
+ (fun _ => selectedSeed B i X sel v placeholder) maps
+ (selectedChildSetup pub m levels old S.steps i.val (oldExponent i))
+ (fun _ => physicalHiddenSetup B.shrink.selectorBits (hiddenStride i) head.val m)
+ (fun _ _ => mapStartSetup m head owner))).read node saved bits = some (body, tail))
+
+include order room level wire mapRates hit
+
+/-- The successful hook leaves room for the dispatcher in both resource bounds.
+The map estimate applies to the exact scratch produced by its two parsers. -/
+theorem selected_hook_rates :
+ countProbes body.trace + 1 ≤ probeRate S mapC (prologueCoefficient B) * (n.log2 + 1) ∧
+ body.trace.length + 9 ≤ n ^ 43 := by
+ obtain ⟨child, mid, hidden, mapOut, trace, childRead, hiddenRead, scan, ticks, probes⟩ :=
+ hook_counts_reached A inc m older B.recordLimit desc arg (selectedSeed B i X sel v placeholder)
+ maps pub levels old S.steps i.val
+ B.shrink.selectorBits (hiddenStride i) head owner node saved bits tail body hit
+ obtain ⟨mapTime, mapReads⟩ := mapRates child mid hidden mapOut trace childRead hiddenRead scan
+ obtain ⟨children, demand, fields, payload⟩ :=
+ selected_prologue_bounds B f hf i X sel v (desc node) order placeholder
+ exact job_rates S i (selectedHeaderLength B) mapC (prologueCoefficient B) n room level wire
+ children demand fields payload mapTime mapReads ticks probes
+
+/-- The actual dispatched job at this ordinal satisfies the common traversal allowance. -/
+theorem selected_hook_cost (offset : Word w) :
+ ordinalJobCost n 1 (probeRate S mapC (prologueCoefficient B))
+ (dispatchJob m offset node saved body) := by
+ have bounds := selected_hook_rates B f hf i X sel v desc node order placeholder A inc m older
+ arg maps pub levels old head owner saved bits tail body mapC n room level wire mapRates hit
+ exact dispatched_ordinal_cost m offset node saved body bounds.1 bounds.2
+
+end PairSimulation.ShrinkNodeCost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkInputRetention.lean b/lean/OAI/Computability/VPVNP/PairShrinkInputRetention.lean
new file mode 100644
index 0000000000..287d887f08
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkInputRetention.lean
@@ -0,0 +1,274 @@
+import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables
+import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch
+import OAI.Computability.VPVNP.CompressorShrinkResidentRun
+import OAI.Computability.VPVNP.PairShrinkCallHeader
+
+/-!
+# Reading original arc lists and ranks during a shrinking simulation
+
+The append pass lists old outgoing identifiers in scan order. The gather pass
+writes its keys above these lists, and the rank pass writes above the keys.
+The absolute-identifier scatter reuses the gathered-key rectangle. The list
+rows, counters and owners lie below that rectangle, and the ranks lie above
+it. Consequently the simulation can combine the original scan-order lists
+with the ranks in the selected ordering in the same memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkInput.Run
+
+open BurstRAM Compression Compression.PackingData BundleLists BundleKeys
+open ShrinkRankSpace BundleGather
+open private rowAt_val from OAI.Computability.VPVNP.CompressorRecordPreimageScan
+
+variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w}
+variable {start : ℕ} {m : Memory w} (r : Run X T start m)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "Z" => plan X start
+local notation "A" => Shape.A (plan X start)
+local notation "B" => Shape.B (plan X start)
+local notation "P" => X.packingData
+local notation "arcs" => oldArcOrder (a := a) (g := g) X.baseIndex
+local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex
+local notation "q" => Shape.collectBank (plan X start) w
+local notation "rankHead" => Fin.ofNat (2 ^ w) (Shape.ranks (plan X start))
+local notation "s" => ShrinkWidthArena.scatterBank T q rankHead (widthBase X start)
+local notation "ms" => after r.greedy.post (eventLog r.sites)
+local notation "ml" => after (after (after ms (eventLog r.clear)) (eventLog r.classify))
+ (eventLog r.append)
+local notation "mg" => after ml (eventLog r.gather)
+
+/-- Below the gathered-key rectangle the width, rank, and gather scans all
+preserve the memory left by the original list builder. -/
+theorem post_eq_append (room : stop X start < 2 ^ w) {z : ℕ} (hz : z < (Z).gathered) :
+ r.post z = ml z := by
+ have ranges := range_bounds X start
+ have fit := ranges.2.2.2.trans_lt room
+ have v := (Z).values T (placementBank X T start) Fintype.card_pos fit
+ have layout := ((Z).regions T (placementBank X T start) Fintype.card_pos
+ ((r.greedy.old 5).trans (ranges.1.trans ranges.2.1)) fit).2.1
+ have hn : B + B ≤ 2 ^ w := by rw [← two_mul, ← v.buckets]; exact (q 2).isLt.le
+ have stored : BundleGather.Stored P arcs sites q ml := by
+ intro b
+ apply r.ranking.ranked.lists.rows
+ change (bucketIndex sites b).val % (2 ^ w) < (q 2).val
+ rw [Nat.mod_eq_of_lt ((bucketIndex sites b).isLt.trans_le hn), v.buckets, two_mul]
+ exact (bucketIndex sites b).isLt
+ have ha : A < 2 ^ w := (Z).scalarFits Fintype.card_pos fit |>.1
+ let K := (Z).gatheredTable w T
+ obtain ⟨rs, run, done, _, _⟩ := fixed_gather_table P arcs sites q
+ (Fin.ofNat _ (Z).key) (Fin.ofNat _ (Z).gathered) T.width
+ (State.two_le_packingColors a) ha hn layout ml stored
+ have count : Fixed.entryCount K = A := by
+ change B * (2 ^ (Shrink.colors a) * 2 ^ a / 4 + (Z).Q) = A
+ rw [Nat.mul_add]; exact bundle_rows_total ..
+ have execute := run.executed
+ change runSegment _ _ _ _ (List.replicate (Fixed.entryCount K) []) = some rs at execute
+ rw [count] at execute
+ have eqn : rs = r.gather := Option.some.inj (execute.symm.trans r.ranking.ranked.gather)
+ subst rs
+ have gather : mg z = ml z := done.outside K layout le_rfl z (.inl (v.gathered ▸ hz))
+ have hr := hz.trans_le (Nat.le_add_right (Z).gathered (Z).rectangleSize)
+ have zrank : z < (rankHead).val := by rw [v.ranks]; exact hr
+ have ranks : r.rankPost z = mg z := r.ranking.ranked.rank.frame z (.inl zrank)
+ exact (r.afterRank z (hr.trans_le (Nat.le_add_right (Z).ranks A))).trans (ranks.trans gather)
+
+/-- The complete old-port lists in any later snapshot that preserves the
+part of the shrinking directory preceding the gathered keys. -/
+theorem original_preimages {out : Memory w} (room : stop X start < 2 ^ w)
+ (low : ∀ z < (Z).gathered, out z = r.post z) :
+ PreimagesAt q (wordOwner P arcs sites) out A := by
+ let place := wordOwner (w := w) P arcs sites
+ have before := range_bounds X start
+ have fit := before.2.2.2.trans_lt room
+ have v := (Z).values T (placementBank X T start) Fintype.card_pos fit
+ have reg := ((Z).regions T (placementBank X T start) Fintype.card_pos
+ ((r.greedy.old 5).trans (before.1.trans before.2.1)) fit).1
+ have read (z : ℕ) (hz : z < (Z).gathered) : out z = ml z :=
+ (low z hz).trans (r.post_eq_append room hz)
+ have top : (q 5).val + (q 2).val * (q 4).val = (Z).gathered := by
+ rw [v.ids, v.buckets, v.stride]; rfl
+ have scalars := (Z).scalarFits Fintype.card_pos fit
+ have bucketCount : (q 2).val = B + B := v.buckets.trans (two_mul _)
+ have capacity (u : Word w) (hu : u < q 2) : (preimagePrefix place u A).length ≤ (q 4).val := by
+ let j : Fin (B + B) := ⟨u.val, bucketCount ▸ hu⟩
+ let b := (bucketIndex sites (d := 2 ^ a)).symm j
+ have idx : (bucketIndex sites b).val = u.val :=
+ congrArg Fin.val ((bucketIndex sites).apply_symm_apply j)
+ have idWord : Fin.ofNat (2 ^ w) (bucketIndex sites b).val = u := by
+ rw [idx]; exact Fin.ext (Nat.mod_eq_of_lt u.isLt)
+ rw [← idWord]
+ change (arcList P arcs sites b).length ≤ _
+ rw [arcList_length P arcs sites (State.two_le_packingColors a)
+ scalars.1.le (by rw [← two_mul]; exact scalars.2.1.le), v.stride]
+ cases b with
+ | inl b => exact Nat.div_le_div_right (by omega : 2 ^ (Shrink.colors a) * 2 ^ a ≤
+ 3 * (2 ^ (Shrink.colors a) * 2 ^ a))
+ | inr b => exact le_rfl
+ have filled : PreimagesAt q place ml A := r.ranking.ranked.lists
+ constructor
+ · intro i hi
+ have hi' : i.val < (q 0).val := hi
+ have bound := ((Nat.add_lt_add_left hi' (q 1).val).trans_le reg.ownersBeforeCounts).trans_le
+ ((Nat.le_add_right ..).trans reg.countsBeforeRows)
+ unfold ownerAt
+ rw [read _ (by rw [Fin.val_add]; exact (Nat.mod_le ..).trans_lt (by omega))]
+ exact filled.owners i hi
+ · intro u hu
+ have cap := capacity u hu
+ have hcount := (Nat.add_lt_add_left (show u.val < (q 2).val from hu) (q 3).val).trans_le
+ reg.countsBeforeRows
+ have hlen := Nat.mul_le_mul_right (q 4).val (show u.val + 1 ≤ (q 2).val from hu)
+ rw [Nat.succ_mul] at hlen
+ obtain ⟨length, data⟩ := filled.rows u hu
+ constructor
+ · rw [read _ (by rw [countAt, Fin.val_add]; exact (Nat.mod_le ..).trans_lt (by omega))]
+ exact length
+ · intro i
+ have hi := i.isLt.trans_le cap
+ rw [read _ (by rw [rowAt_val reg hu]; omega)]
+ exact data i
+
+include r in
+private theorem packing_width_fits (e : OldArc X.Base a g) : X.packingWidth e < 2 ^ w := by
+ by_cases h : (P).thick (sourcePosition e) ∧ (P).thick (sourcePosition ((P).actual e))
+ · let x : (P).ThickFiber e.1 := ⟨⟨e, h⟩, rfl⟩
+ have width := r.stored.thickWidths e.1 (X.shrinkOrder e.1 x)
+ rw [Equiv.symm_apply_apply] at width
+ change _ = X.packingWidth e at width
+ rw [← width]
+ exact Fin.isLt _
+ · let y : (P).Motif := ⟨e, h⟩
+ let x : (P).MotifFiber ((P).bundle y) := ⟨y, rfl⟩
+ have width := r.stored.cdWidths ((P).bundle y) (X.shrinkNumber ((P).bundle y) x)
+ rw [Equiv.symm_apply_apply] at width
+ change _ = X.packingWidth e at width
+ rw [← width]
+ exact Fin.isLt _
+
+/-- Original ranks, owners and exact widths. The later snapshot need only
+agree on the lower directory and the rank column. The gathered keys may
+have already been reused for absolute motif IDs. -/
+theorem original_ranked {out : Memory w} (room : stop X start < 2 ^ w)
+ (low : ∀ z < (Z).gathered, out z = r.post z)
+ (rank : ∀ z, (Z).ranks ≤ z → z < widthBase X start → out z = r.post z) :
+ BundleWidthScatter.RankedInput P X.shrinkNumber X.shrinkOrder arcs sites s out
+ X.packingWidth := by
+ have before := range_bounds X start
+ have fit := before.2.2.2.trans_lt room
+ have v := (Z).values T (placementBank X T start) Fintype.card_pos fit
+ have ai := ShrinkBundlePlan.absolute_inputs r fit
+ have old : T.width.val + A ≤ start := r.greedy.old 5
+ have owner : (q 1).val = (Z).owner := v.owner
+ have og : (Z).owner + A ≤ (Z).gathered := by
+ change (Z).owner + A ≤ (Z).owner + 2 * A + 2 * B + (Z).rectangleSize
+ omega
+ have wg : T.width.val + A ≤ (Z).gathered := old.trans ((before.1.trans before.2.1).trans
+ ((Nat.le_add_right (Z).owner A).trans og))
+ constructor
+ · intro e
+ have he := (arcs e).isLt
+ change out (q 1 + Fin.ofNat _ (arcs e).val).val = _
+ rw [low _ (by
+ rw [Fin.val_add, Fin.val_ofNat, owner]
+ exact (Nat.mod_le ..).trans_lt
+ ((Nat.add_lt_add_left ((Nat.mod_le ..).trans_lt he) _).trans_le og))]
+ exact ai.owners e
+ · intro e
+ have he : (arcs e).val < A := (arcs e).isLt
+ have top : (Z).ranks + A < 2 ^ w := fit
+ have addr : (rankHead + Fin.ofNat _ (arcs e).val).val = (Z).ranks + (arcs e).val := by
+ rw [Fin.val_add, v.ranks, Fin.val_ofNat, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)]
+ change out (rankHead + Fin.ofNat _ (arcs e).val).val = _
+ rw [rank _ (addr ▸ Nat.le_add_right ..)
+ (addr ▸ Nat.add_lt_add_left he (Z).ranks)]
+ exact ai.ranks e
+ · intro e
+ have he : (arcs e).val < A := (arcs e).isLt
+ have hz := (Nat.add_lt_add_left he T.width.val).trans_le wg
+ have hbelow : (Z).gathered ≤ widthBase X start :=
+ (Nat.le_add_right (Z).gathered _).trans (Nat.le_add_right (Z).ranks A)
+ change (out (T.width + Fin.ofNat _ (arcs e).val).val).val = _
+ rw [Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod, Nat.mod_eq_of_lt (hz.trans_le
+ (hbelow.trans fit.le)), low _ hz, r.afterRank _ (hz.trans_le hbelow)]
+ exact (congrArg Fin.val (r.ranking.widths e)).trans (Nat.mod_eq_of_lt (r.packing_width_fits e))
+
+/-- Read both tables after the native absolute scatter and subsequent stages
+which preserve the shrinking input area. -/
+theorem original_after_absolute {rs : List (Report w)}
+ (last : ShrinkBundlePlan.AbsoluteRun r rs) {out : Memory w} (room : stop X start < 2 ^ w)
+ (keep : ∀ z < widthBase X start, out z = after r.post (eventLog rs) z) :
+ PreimagesAt q (wordOwner P arcs sites) out A ∧
+ BundleWidthScatter.RankedInput P X.shrinkNumber X.shrinkOrder arcs sites s out
+ X.packingWidth := by
+ have bound : (Z).gathered ≤ widthBase X start :=
+ (Nat.le_add_right (Z).gathered _).trans (Nat.le_add_right (Z).ranks A)
+ have low (z) (hz : z < (Z).gathered) :=
+ (keep z (hz.trans_le bound)).trans (last.frame z (.inl hz))
+ exact ⟨r.original_preimages room low, r.original_ranked room low
+ (fun z hr hw ↦ (keep z hw).trans (last.frame z (.inr hr)))⟩
+
+end CompressorRecords.ShrinkInput.Run
+
+namespace CompressorRecords.ShrinkOutput
+
+open Compression BurstRAM ShrinkBlockInputs BundleLists BundleKeys ShrinkResidentRun
+open Compression.ShrinkMotif
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {i : Fin S.steps}
+variable {g w : ℕ} {δ : ℝ} {X : State (a i) (packingLaneBits (a i) g)}
+variable {ready : Ready (2 ^ a i) (Shrink.colors (a i)) (2 ^ b i) δ}
+variable {T : IncidenceDirectory w} {start cap : ℕ} {stride selectors : Word w}
+variable {sel : SelectedScore.Selection B X} {m : Memory w}
+variable {p : ShrinkBranch.Prefix X T start cap m}
+variable (v : ShrinkBranch.Selected B X T start stride selectors cap m p sel)
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "absHead" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Read all original inputs of a resident map in the final snapshot produced
+by the hidden and map directories, the AB intersections, and the surviving
+and ordered-slot scans. Later stages may reuse the gathered-key rectangle. -/
+theorem CompleteTables.old_call_tables
+ {resident first width slotStart : ℕ} {role : Word w} {side : Bool}
+ {h u : ShrinkResidentRun.Passes w}
+ (hiddenRun : Built X resident absHead role side false v.beforeOutput h)
+ (mapRun : Built X resident absHead role side true (h.final v.beforeOutput) u)
+ {I : ShrinkABSliceRecipe.Inputs} {pub : Fin 5 → Word w} {state : Word w} {ref : Memory w}
+ {r : TablesRun w} (tables : CompleteTables B i X ready sel term stride absHead start
+ I pub state ref first width slotStart cap (u.final (h.final v.beforeOutput)) r)
+ (room : ShrinkInput.termEnd X start stride.val < 2 ^ w)
+ (residentFresh : ShrinkInput.stop X start ≤ resident)
+ (abFresh : ShrinkInput.stop X start ≤ first) (order : first ≤ width) :
+ PairSimulation.ShrinkCallHeader.OldTables X r.final T start := by
+ have frame (x : ℕ) (hx : x < ShrinkInput.stop X start) :
+ r.final x = after p.input.post (eventLog p.absolute) x := by
+ have beforeHidden := (hx.trans_le residentFresh).trans_le
+ ((ShrinkResidentLayout.layout X resident).ranges false).1
+ have beforeMaps := (hx.trans_le residentFresh).trans_le
+ ((ShrinkResidentLayout.layout X resident).ranges true).1
+ have beforeAB := hx.trans_le abFresh
+ have beforeSlots := (beforeAB.trans_le order).trans_le
+ (retained_room X term stride.val (SelectedArena.roleBase X term stride) width)
+ exact (tables.remainder.construction.frame x (.inl beforeSlots)).trans
+ ((tables.abFrame x (.inl beforeAB)).trans ((mapRun.frame x (.inl beforeMaps)).trans
+ ((hiddenRun.frame x (.inl beforeHidden)).trans (v.lowerFrame x hx))))
+ have stopRoom : ShrinkInput.stop X start < 2 ^ w := by
+ unfold ShrinkInput.termEnd at room
+ omega
+ obtain ⟨rows, ranked⟩ := p.input.original_after_absolute p.absoluteRun stopRoom
+ (fun x hx ↦ frame x (hx.trans_le (ShrinkInput.range_bounds X start).2.2.2))
+ have geometry := p.input.keepAbsoluteThenTerms p.absoluteRun.frame stride.val room frame
+ exact ⟨rows, ranked, geometry.incidence.actual, geometry.placement⟩
+
+end CompressorRecords.ShrinkOutput
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkInstalledItem.lean b/lean/OAI/Computability/VPVNP/PairShrinkInstalledItem.lean
new file mode 100644
index 0000000000..c8f6699d3a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkInstalledItem.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.PairShrinkRouteABI
+import OAI.Computability.VPVNP.PairShrinkReadyAfterGather
+import OAI.Computability.VPVNP.PairSimulationShrinkScheduledItem
+import OAI.Computability.VPVNP.PairShrinkLiveOperands
+
+/-! # A scheduled matrix item at the site of an individual party -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open MotifGrid MotifBlocks MotifConversion NetworkKernel CompressorRecords
+open ShrinkBlockInputs ShrinkSlots ShrinkVertexImage ShrinkMapImage.Registers
+open MapHandlerOperand MapResidentRows
+open scoped Fin.CommRing
+
+variable {w p r t n limit endAddr g : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (ord : B.Entry → Fin t) (stage : Fin S.steps)
+variable {X : State (a stage) (packingLaneBits (a stage) g)}
+variable (sel : X.ShrinkSelection B.shrink) {motif : X.packingData.Motif} {party : Fin 6}
+variable (J : Job X B.shrink (S.shrink stage) sel motif party w)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "Fam" => matrixFamily B ord stage
+local notation "Gather" => gatherFamily B ord stage
+local notation "degree" => slotDegree S
+
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel))
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) motif party))
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (ShrinkPreparedCall.widthsDemand X motif)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X motif) (sel motif).val J.scratch
+ (ShrinkMotifOrder.stateNumber X motif).val (ShrinkCallDemandCells.cdBase X motif J.arena J.nodes))
+local notation "call" => Job.entryInput B X (S.shrink stage) sel motif party J hidden
+local notation "work" =>
+ Job.mapWorkspace B degree ord X (S.shrink stage) sel motif party J hidden ok
+
+variable (pc : GatherAddress (matrixFamily B ord stage) (gatherFamily B ord stage) → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (locals : Fin (maps B ord stage).code.privateRegs ↪ Fin r) (ret : Fin p)
+ (M : Machine w p r 11)
+local notation "cm" => Function.Embedding.trans (gatherShared Fam Gather) locals
+local notation "own" => Function.Embedding.trans (gatherMatrix Fam Gather) locals
+local notation "gr" => Function.Embedding.trans (gatherLocal Fam Gather) locals
+local notation "tmp" => locals (layoutTemp Fam Gather)
+local notation "key" => MapHandlerOperand.index demandMass_pos call
+local notation "lp" => loop Fam mapRegisters (corePC Fam Gather pc) cm ret
+
+variable (v : MapResidentRows.Site X) (mem : Memory w) (level term : Word w)
+variable (source : MapRowSource X sel (selectedLayout X B.shrink sel) mem level term)
+ (i : Fin (order X (selectedLayout X B.shrink sel) v).length) (P : Fin 5 → Word w)
+ (hw : MapConstants.widthThreshold B.shrink ≤ w) (inv : Word w → Config w p r → Prop)
+local notation "st" => rowOrdinalWord (w := w) (a := a stage) (g := g) X side v i
+local notation "src" => rowCursor X sel side v mem level term source i
+local notation "action" => rowAction (endAddr := endAddr) Fam Gather X sel v mem level term
+ source i call J hw P work
+attribute [local irreducible] Compression.ShrinkEnergy.chosenLayout rowOrdinalWord
+
+set_option maxHeartbeats 3000000 in
+-- The fixed matrix input and the gathered workspace carry the same stage and party.
+/-- The concrete job supplies its exact matrix action, including the external
+row dispatch and the native memory frame on both branches. -/
+theorem Job.installedItem
+ (link : GatherLinked Fam Gather mapRegisters pc dfs saved cm own gr tmp ret M)
+ (ds : ∀ j k, locals j ≠ dfs k) (ss : ∀ j k, locals j ≠ saved k)
+ (positive : 0 < w) (atRow : (MapResidentRows.entry X side v i) = (motif, party))
+ (allowed : ℕ → Prop)
+ (safe : ∀ c k, (J.row c k).ReadSafe
+ (setups (ShrinkCallABI.operands degree) ShrinkCallABI.node (a stage) (b stage)
+ party side c k) allowed P st mem)
+ {T U : IncidenceDirectory w} {origin layer pitch : ℕ} {heads : SlotLevel.Heads}
+ {absolute : Word w}
+ (old : J.OldPublished (ShrinkCallABI.operands degree) P st mem level T origin)
+ (next : J.SupplyPublished (ShrinkCallABI.operands degree) ShrinkCallABI.node P st mem
+ heads absolute U layer pitch)
+ (stack : endAddr ≤ J.scratch.hist) (hist : J.scratch.hist + t ≤ J.scratch.hidden)
+ (live : ∀ node c, inv node c → LiveOperands (endAddr := endAddr)
+ Fam mapRegisters dfs saved cm tmp call J P st mem level term work inv node c) :
+ ResidentMapLoop.Exact.Item (endAddr := endAddr) lp M mem dfs inv src
+ (fun _ s => action s) := by
+ have banks := hosted_banks Fam Gather dfs saved locals ds ss
+ have abi := route_abi B ord stage dfs saved locals ds ss key
+ have atParty : (MapResidentRows.entry X side v i).2 = (call).party := congrArg Prod.snd atRow
+ have grid : rowGrid (B := B.shrink) X side v i =
+ demandGrid B.shrink demandMass_pos (call).demand :=
+ congrArg (fun m => demandGrid B.shrink demandMass_pos (ShrinkPreparedCall.widthsDemand X m))
+ (congrArg Prod.fst atRow)
+ have room := J.call_bounds B degree ord X (S.shrink stage) sel motif party hidden ok
+ mem P st level T origin old stack
+ have histEnd := J.histogram_before_staging B degree ord X (S.shrink stage) sel motif party
+ hidden ok hist
+ exact exact_item (B := B.shrink) (g := g) (ready := S.shrink stage) (endAddr := endAddr)
+ (jobMotif := motif) (absolute := absolute) (T := T) (U := U) (origin := origin)
+ (layer := layer) (pitch := pitch) (heads := heads) («side» := side)
+ Fam Gather mapRegisters pc dfs saved cm own gr tmp ret M link banks.1 banks.2.1
+ X sel v mem level term source i call J hw P work inv positive banks.2.2 abi.1 abi.2.1 abi.2.2
+ rfl atParty grid allowed safe old next room histEnd live
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkItemsOfFn.lean b/lean/OAI/Computability/VPVNP/PairShrinkItemsOfFn.lean
new file mode 100644
index 0000000000..98067478c7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkItemsOfFn.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoopExact
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherSource
+
+/-!
+# Exact items in a finite resident map row
+
+The native map loop advances one word after each occurrence. The actions
+at the finite row ordinals therefore form an exact list starting at the
+published row base, including the empty row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentMapLoop.Exact
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {w endAddr p r k n src : ℕ} {P : Program p r} {M : Machine w p r k}
+variable {m : Memory w} {dfs : Fin 9 ↪ Fin r} {inv : Word w → Config w p r → Prop}
+
+/-- Consecutive source words turn the indexed occurrence proofs into the exact loop list. -/
+theorem Items.ofFn {f : Fin n → Action w endAddr}
+ (each : ∀ i, Item P M m dfs inv (src + i.val) (f i)) :
+ Items P M m dfs inv src (List.ofFn f) := by
+ induction n generalizing src with
+ | zero => simp [Items]
+ | succ n ih =>
+ rw [List.ofFn_succ]
+ constructor
+ · simpa only [Fin.val_zero, Nat.add_zero] using each 0
+ · apply ih
+ intro i
+ simpa only [Fin.val_succ, Nat.add_assoc, Nat.add_comm i.val 1] using each i.succ
+
+end PairSimulation.ResidentMapLoop.Exact
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM CompressorRecords Compression Compression.ShrinkMotif MotifGrid MotifBlocks
+open MotifConversion MapResidentRows
+
+variable {K : Type} [Field K] {factor : ℝ}
+variable {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {selection : X.ShrinkSelection B}
+variable {side : Bool} {m : Memory w} {level term : Word w}
+
+/-- Address of the first resident-map slot of a site, including sites with no entries. -/
+noncomputable def MapRowSource.rowStart (R : MapRowSource X selection side m level term)
+ (site : Site X) : ℕ :=
+ ((ShrinkResidentLayout.layout X R.first).params a true w 5).val +
+ (siteIndex X site).val * capacity a
+
+theorem MapRowSource.rowCursor_eq (R : MapRowSource X selection side m level term)
+ (site : Site X) (i : Fin (order X side site).length) :
+ rowCursor X selection side site m level term R i = R.rowStart site + i.val := rfl
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkJobExterior.lean b/lean/OAI/Computability/VPVNP/PairShrinkJobExterior.lean
new file mode 100644
index 0000000000..81071d88d6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkJobExterior.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.PairShrinkGatherExterior
+import OAI.Computability.VPVNP.PairShrinkResidentMemory
+import OAI.Computability.VPVNP.PairShrinkVertexImage
+
+/-!
+# Exterior scratch of a scheduled shrinking job
+
+The actual descriptor pointer comes from the retained level. The selected
+workspace fixes the histogram and all private write intervals. The pure
+gathered action preserves each exterior word for every incoming scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif MotifEntry
+open MotifBlocks MotifGrid MotifConversion NetworkKernel CompressorRecords
+open CompressorRecords.ShrinkSlots NodeArguments ShrinkMapImage.Registers
+
+variable {w g packetEnd endAddr t n limit : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (ord : B.Entry → Fin t) (i : Fin S.steps)
+local notation "degree" => slotDegree S
+local notation "family" => ShrinkVertexImage.matrixFamily B ord i
+local notation "gathers" => ShrinkVertexImage.gatherFamily B ord i
+variable (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+variable (sel : X.ShrinkSelection B.shrink)
+variable (m : X.packingData.Motif) (party : Fin 6)
+variable (J : Job X B.shrink (S.shrink i) sel m party w)
+/-- Classical decidable equality on the compression state’s base vertices for the
+exterior-memory bounds of a scheduled shrink job. -/
+noncomputable local instance stepBaseDecidable : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+local notation "BW" => ShrinkPreparedCall.widthsDemand X m
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+local notation "cd" => ShrinkCallDemandCells.cdBase X m J.arena J.nodes
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel))
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m party))
+local notation "call" => Job.entryInput B X (S.shrink i) sel m party J hidden
+local notation "L" => MapHandlerOperand.layout family demandMass_pos call
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (ShrinkPreparedCall.widthsDemand X m)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X m) (sel m).val J.scratch (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallDemandCells.cdBase X m J.arena J.nodes))
+local notation "W" => Job.mapWorkspace B degree ord X (S.shrink i) sel m party J hidden ok
+variable (hw : MapConstants.widthThreshold B.shrink ≤ w)
+variable (P : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+local notation "ptr" => PhaseRecipe.Expr.eval P state mem (ShrinkCallFields.Inputs.descriptor
+ (ShrinkCallHeader.Operands.inputs (ShrinkCallABI.operands degree) (S.degreeExponent i.castSucc)))
+
+set_option maxHeartbeats 1400000 in
+-- Align the selected job input, workspace and gathered action at the same schedule index.
+/-- A genuine map at this substep preserves every word below staging that
+lies outside the histogram, on an arbitrary incoming logical scratch. -/
+theorem Job.gathered_preserves (saved : DFS.Scratch w endAddr)
+ {baseline : Word w → Word w} (packets : J.Packets packetEnd baseline)
+ (histEnd : J.scratch.hist + t ≤ J.scratch.hidden)
+ {level : Word w} {T : IncidenceDirectory w} {origin : ℕ}
+ (old : J.OldPublished (ShrinkCallABI.operands degree) P state mem level T origin)
+ {events : List (Event w)} {out : DFS.Scratch w endAddr}
+ (got : gatheredAction family gathers call J hw P state mem W saved = some (events, out)) :
+ ∀ q : Word w, q.val < J.scratch.staging →
+ (q.val < J.scratch.hist ∨ J.scratch.hist + t ≤ q.val) →
+ rawScratch out q = rawScratch saved q := by
+ have address := Job.descriptor_address B degree X (S.shrink i) sel m party J P state mem old
+ have descFit : (ptr).val + Fintype.card ShrinkCallFields.Arg ≤ 2 ^ w := by
+ rw [address]
+ have h := ok.room.trans_lt ok.capacity.room
+ unfold ShrinkCallFields.Scratch.target ShrinkCallFields.Scratch.source at h
+ exact (Nat.add_le_add_right (Nat.mod_le ..) _).trans (by omega)
+ have outside := gathered_exterior family gathers call J hw P state mem W saved packets descFit got
+ exact ShrinkCallFields.resident_exterior B.shrink (L).core ((L).corePC (L).locations)
+ BW (sel m).val
+ (demandBits demandSource demandTarget party (LocalHistory.EntryInput.demandBits call))
+ (MotifSelector.mapHalf supply (fun _ ↦ inputBits) (LocalHistory.EntryInput.supplyBits call))
+ J.scratch idx side cd ok histEnd address outside
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkJobHistogram.lean b/lean/OAI/Computability/VPVNP/PairShrinkJobHistogram.lean
new file mode 100644
index 0000000000..02f907bb4a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkJobHistogram.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkRowHistogram
+import OAI.Computability.VPVNP.PairShrinkResidentMemory
+import OAI.Computability.VPVNP.PairShrinkVertexImage
+
+/-!
+# Histogram effect of a scheduled shrinking job
+
+The old level header locates the descriptor. The concrete job places the histogram
+before staging and the directory after it, so every bin counts the occurrences of
+its parameter in the selected entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif MotifEntry
+open MotifBlocks MotifGrid MotifConversion NetworkKernel CompressorRecords
+open CompressorRecords.ShrinkSlots NodeArguments ShrinkMapImage.Registers
+open scoped Fin.CommRing
+
+variable {w g packetEnd endAddr t n limit : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (ord : B.Entry → Fin t) (i : Fin S.steps)
+local notation "degree" => slotDegree S
+local notation "family" => ShrinkVertexImage.matrixFamily B ord i
+local notation "gathers" => ShrinkVertexImage.gatherFamily B ord i
+variable (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+variable (sel : X.ShrinkSelection B.shrink)
+variable (m : X.packingData.Motif) (party : Fin 6)
+variable (J : Job X B.shrink (S.shrink i) sel m party w)
+private noncomputable local instance histogramJobBase : DecidableEq X.Base := Classical.decEq _
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel))
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m party))
+local notation "call" => Job.entryInput B X (S.shrink i) sel m party J hidden
+local notation "L" => MapHandlerOperand.layout family demandMass_pos call
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (ShrinkPreparedCall.widthsDemand X m)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X m) (sel m).val J.scratch (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallDemandCells.cdBase X m J.arena J.nodes))
+local notation "W" => Job.mapWorkspace B degree ord X (S.shrink i) sel m party J hidden ok
+variable (hw : MapConstants.widthThreshold B.shrink ≤ w)
+variable (P : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+local notation "ptr" => PhaseRecipe.Expr.eval P state mem (ShrinkCallFields.Inputs.descriptor
+ (ShrinkCallHeader.Operands.inputs (ShrinkCallABI.operands degree) (S.degreeExponent i.castSucc)))
+local notation:max "bin" l:max => ((J.scratch.hist + Fin.val (l : Fin t) : ℕ) : Word w)
+
+set_option maxHeartbeats 1800000 in
+-- Align the dependent schedule, party and workspace indices for the gathered action.
+/-- A successful gathered map of the selected job adds its entry's multiplicity at every bin. -/
+theorem Job.gathered_histogram (saved : DFS.Scratch w endAddr)
+ {baseline : Word w → Word w} (packets : J.Packets packetEnd baseline)
+ (floor : endAddr ≤ J.scratch.hist) (histEnd : J.scratch.hist + t ≤ J.scratch.hidden)
+ {level : Word w} {T : IncidenceDirectory w} {origin : ℕ}
+ (old : J.OldPublished (ShrinkCallABI.operands degree) P state mem level T origin)
+ {events : List (Event w)} {out : DFS.Scratch w endAddr}
+ (got : gatheredAction family gathers call J hw P state mem W saved = some (events, out)) :
+ ∀ l : Fin t, rawScratch out (bin l) = rawScratch saved (bin l) +
+ (((MapHandlerOperand.names family demandMass_pos call).getD []).count l : Word w) := by
+ have room := ok.room.trans_lt ok.capacity.room
+ unfold ShrinkCallFields.Scratch.target ShrinkCallFields.Scratch.source at room
+ have descRoom : J.scratch.descriptor < 2 ^ w := by omega
+ have ptrVal : (ptr).val = J.scratch.descriptor := by
+ rw [Job.descriptor_address B degree X (S.shrink i) sel m party J P state mem old]
+ exact Nat.mod_eq_of_lt descRoom
+ have below : J.scratch.hist + t ≤ J.scratch.staging := histEnd.trans (Nat.le_add_right ..)
+ have beforeDir : J.scratch.hist + t ≤ J.scratch.directory := below.trans (Nat.le_add_right ..)
+ have binVal (l : Fin t) : (bin l).val = J.scratch.hist + l.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left l.isLt _).trans_le (W).histogramFit)
+ apply ShrinkMapImage.Registers.gathered_histogram family gathers X sel mem call J hw P W saved
+ state packets floor _ below _ _ got
+ · change (ptr).val + Fintype.card ShrinkCallFields.Arg ≤ 2 ^ w
+ rw [ptrVal]
+ omega
+ · intro l
+ left
+ change (bin l).val < (ptr).val
+ rw [binVal, ptrVal]
+ exact (Nat.add_lt_add_left l.isLt _).trans_le (beforeDir.trans (Nat.le_add_right ..))
+ · intro l k eqn
+ have len := MapPortAgreement.ports_length_le supply party (L).core.edgeOrder
+ have card : 2 * Fintype.card (Bool × Fin 4) = 16 := by simp
+ rw [card] at len
+ have dirFit : J.scratch.directory + k.val < 2 ^ w :=
+ (Nat.add_lt_add_left (k.isLt.trans_le len) _).trans descRoom
+ have val := congrArg Fin.val eqn
+ change (bin l).val = ((J.scratch.directory : Word w) + (k.val : Word w)).val at val
+ rw [binVal, ← Nat.cast_add, show ((J.scratch.directory + k.val : ℕ) : Word w).val =
+ J.scratch.directory + k.val from Nat.mod_eq_of_lt dirFit] at val
+ have := l.isLt
+ omega
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkJobOperands.lean b/lean/OAI/Computability/VPVNP/PairShrinkJobOperands.lean
new file mode 100644
index 0000000000..50eed5e320
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkJobOperands.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.PairShrinkHandlerPrepared
+import OAI.Computability.VPVNP.PairShrinkPartyNative
+import OAI.Computability.VPVNP.PairShrinkHiddenReadback
+
+/-!
+# Resident map arguments after the party gather
+
+The placed child packets supply C and D. The party gather writes the AB and
+surviving words and preserves both the child argument arena and the earlier
+absorbed slots. These facts identify the private words passed to the
+selected grouped map for any local tensor argument.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open Compression.ShrinkEnergy MotifBlocks MotifGrid MotifConversion NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots CompressorRecords.ShrinkSliceSweep
+open NodeArguments
+open scoped Fin.CommRing
+
+variable {a b g w endAddr : ℕ} {δ factor : ℝ} {K : Type} [_root_.Field K]
+variable {X : State a (packingLaneBits a g)}
+variable {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+variable {m : X.packingData.Motif} {party : Fin 6}
+variable (J : Job X F ready sel m party w)
+/-- Classical decidable equality on the compression state’s base vertices for the resident map
+operands assembled by the party gather. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X F sel
+local notation "widths" => ShrinkPreparedCall.width F X sel
+local notation "owner" => X.packingData.shrinkPartySite side m party
+local notation "Idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+
+/-- All independent child half-wires stored at this parent. This is the
+pointwise packet conclusion of the child scan, reindexed by the old layout. -/
+def Job.ChildWords (priv : Word w → Word w) (endAddr : ℕ) : Prop :=
+ ∀ site (eqn : X.packingData.shrinkPartySite side m party = packedSiteEquiv site),
+ ShrinkOldHalves.PlacedPackets X side J.arena J.nodes priv site
+ (X.packingData.shrinkPlacedHalf X.packingWidth side site eqn J.old) endAddr
+
+variable {before after : Word w → Word w}
+
+/-- After all interval copies the two old CD endpoints retain their original
+child bits, and the assembled AB endpoint has its computed value. -/
+theorem Job.Assembled.demandFields (staged : J.Assembled before after)
+ (child : J.ChildWords before endAddr)
+ (endBefore : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ J.scratch.staging) :
+ ShrinkCallDemandCells.Readback X side m party J.arena J.nodes J.old after
+ J.scratch.staging endAddr := by
+ refine ⟨staged.ab, ?_, ?_⟩
+ · intro hp
+ subst party
+ apply ShrinkCallDemandCells.placedPackets_frame X side J.arena J.nodes _ endBefore staged.below
+ exact child _ (X.packingData.shrinkPartySite_C side m)
+ · intro hp
+ subst party
+ apply ShrinkCallDemandCells.placedPackets_frame X side J.arena J.nodes _ endBefore staged.below
+ exact child _ rfl
+
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X F sel))
+ (internalLabel (ShrinkPreparedCall.width F X sel) (selectedLayout X F sel))
+ (X.packingData.shrinkPartySite (selectedLayout X F sel) m party))
+
+set_option maxHeartbeats 1200000 in
+-- Unfolding the selected layout identifies the hidden coordinate and its dependent bit width.
+/-- Turn the completed native hidden-word readback at the current owner into
+the caller's physical private field predicate. -/
+theorem Job.hiddenFields (raw : ∀ t (owned : owner = X.packingData.shrinkInternalOwner side (m, t))
+ (i : Fin ((widths) m (!side, t))),
+ before ((ShrinkHiddenSlots.address X J.scratch.hidden J.scratch.stride (m, t) + i.val : ℕ) :
+ Word w) = PrivateFields.bitValue w (RAMSerialization.wordBits _ (hidden (m, t) owned) i)) :
+ ShrinkCallSupplyCells.Absorbed X side (widths) m party J.scratch hidden before := by
+ intro t own i
+ simpa only [ShrinkHiddenSlots.address, ShrinkHiddenSlots.id_eq, ShrinkCallFields.Scratch.shared]
+ using raw t own i
+
+set_option maxHeartbeats 1200000 in
+-- The private readback uses the selected layout at the dependent old and new fiber types.
+/-- The independent input of an absorbed edge is still available at both
+ends after the subsequent copies. -/
+theorem Job.Assembled.hiddenFields (staged : J.Assembled before after)
+ (prior : ShrinkCallSupplyCells.Absorbed X side (widths) m party J.scratch hidden before)
+ (count : Idx < J.scratch.motifs) (fit : ∀ t, (widths) m (!side, t) ≤ J.scratch.stride) :
+ ShrinkCallSupplyCells.Absorbed X side (widths) m party J.scratch hidden after := by
+ intro t own i
+ have hi := i.isLt.trans_le (fit t)
+ have upper := J.scratch.shared_end count t
+ have lt : J.scratch.shared Idx t + i.val < J.scratch.staging := by omega
+ rw [staged.below _ ((Nat.mod_le ..).trans_lt lt)]
+ exact prior t own i
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkJobPrepared.lean b/lean/OAI/Computability/VPVNP/PairShrinkJobPrepared.lean
new file mode 100644
index 0000000000..bcb642f163
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkJobPrepared.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairShrinkJobOperands
+import OAI.Computability.VPVNP.PairShrinkCallABI
+
+/-!
+# Starting the installed map writer after a concrete party gather
+
+The selected local record determines the grouped entry. The parent node
+provides its independent output half, and its child packets and absorbed
+guesses provide the other input indices. The old external term and demand
+tables supply the published word widths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.State Compression.PackingData
+open Compression.ShrinkMotif Compression.ShrinkEnergy MotifBlocks MotifGrid MotifConversion
+open MotifEntry NetworkKernel CompressorRecords CompressorRecords.ShrinkSlots
+open CompressorRecords.ShrinkSliceSweep
+
+variable {a b g w p r t n limit endAddr : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (degree : ℕ) (ord : B.Entry → Fin t)
+variable {δ : ℝ} (X : State a (packingLaneBits a g))
+variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) (sel : X.ShrinkSelection B.shrink)
+variable (m : X.packingData.Motif) (j : Fin 6) (J : Job X B.shrink ready sel m j w)
+/-- Classical equality on old base vertices used to identify this party's selected map inputs. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+local notation "sub" => SlotLevel.Shape.subdivisions (levelShape (b := b) X)
+local notation "slots" => X.shrinkStateIndex ready (side)
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "BW" => ShrinkPreparedCall.widthsDemand X m
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+local notation "cd" => ShrinkCallDemandCells.cdBase X m J.arena J.nodes
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel))
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m j))
+
+/-- The selected map row is the actual entry of the resident's local polynomial. -/
+noncomputable def Job.entryInput : LocalHistory.EntryInput B.shrink :=
+ ShrinkPreparedCall.input B.shrink X sel (side) (sub) (slots) ready.count_pos
+ m j J.old hidden J.parent
+
+local notation "call" => Job.entryInput B X ready sel m j J hidden
+local notation "family" => ShrinkCallABI.family B degree a ord
+local notation "L" => MapHandlerOperand.layout (family) demandMass_pos (call)
+local notation "D" => demandBits demandSource demandTarget j
+ (LocalHistory.EntryInput.demandBits (call))
+local notation "W" => MotifSelector.mapHalf supply (fun _ ↦ inputBits)
+ (LocalHistory.EntryInput.supplyBits (call))
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (ShrinkPreparedCall.widthsDemand X m)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X m) (sel m).val J.scratch (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallDemandCells.cdBase X m J.arena J.nodes))
+
+/-- The map-handler workspace built from this party's demand and supply bits, selected term,
+and fitted scratch addresses. -/
+noncomputable abbrev Job.mapWorkspace :
+ MapHandlerOperand.Workspace (w := w) (family) demandMass_pos (call) :=
+ ShrinkCallFields.workspace B.shrink (MapInline.callProgram (L)) (BW) (sel m).val
+ (D) (W) J.scratch idx (side) (cd) ok
+
+variable (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin 24 ↪ Fin r)
+variable (cfg : Config w p r) (mem : Memory w)
+
+set_option maxHeartbeats 1400000 in
+-- The typed entry and the branch-selected shrink index appear at several fiber coordinates.
+/-- The actual interval gather, original packet arena and selected term record
+establish every input obligation of the installed private map interpreter. -/
+theorem Job.prepared_after_gather (before : Word w → Word w)
+ (stage : J.Assembled before cfg.privateMem)
+ (children : J.ChildWords before endAddr)
+ (ends : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ J.scratch.staging)
+ (guessed : ShrinkCallSupplyCells.Absorbed X (side) (widths) m j J.scratch hidden before)
+ (T : IncidenceDirectory w) (origin : ℕ) (level : Word w)
+ (tables : J.OldPublished (ShrinkCallABI.operands degree) (ShrinkCallABI.pub cfg common)
+ (ShrinkCallABI.state cfg common) mem level T origin)
+ (two : 2 < 2 ^ w) (termRoom : ShrinkInput.termEnd X origin 10 < 2 ^ w)
+ (pairs : ShrinkTermInputs.statePairs X (ShrinkInput.demandHead X origin) mem)
+ (terms : TermRecordScan.Fields B.shrink ShrinkSliceArrays.supplyRoles demandMass_pos
+ (BW) (sel m).val (ShrinkTermSelection.rowBase X (ShrinkInput.termHead X origin) 10 m) mem) :
+ MapHandlerOperand.Prepared (family) demandMass_pos (call) dfs saved common cfg mem
+ (Job.mapWorkspace B degree ord X ready sel m j J hidden ok) := by
+ apply ShrinkPreparedCall.prepared B degree ord X sel (side) (sub) (slots) ready.count_pos
+ m j J.old hidden J.parent J.scratch J.arena J.nodes ok dfs saved common cfg mem before
+ · exact Job.Assembled.demandFields J stage children ends
+ · exact Job.Assembled.hiddenFields J hidden stage guessed ok.ordinal
+ (fun t ↦ ok.supply (!side, t))
+ · exact stage.retained
+ · intro arg
+ have h := ShrinkCallHeader.fields_eval X B.shrink sel m (ShrinkCallABI.operands degree)
+ (ShrinkCallABI.pub cfg common) (ShrinkCallABI.state cfg common) level mem J.arena T
+ origin J.older J.pitch J.first J.scratch.hidden J.scratch.stride J.scratch.hist
+ tables.levelData tables.live tables.tables tables.space two termRoom pairs terms j arg
+ have heap : ShrinkCallHeader.scratch X J.scratch.hidden J.scratch.stride J.scratch.hist =
+ J.scratch := by
+ unfold ShrinkCallHeader.scratch
+ rw [← tables.motifCount]
+ rw [heap] at h
+ exact h
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkLiveMapItems.lean b/lean/OAI/Computability/VPVNP/PairShrinkLiveMapItems.lean
new file mode 100644
index 0000000000..f4de7b7407
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkLiveMapItems.lean
@@ -0,0 +1,178 @@
+import OAI.Computability.VPVNP.PairShrinkSiteActions
+import OAI.Computability.VPVNP.PairShrinkRoleSiteOperands
+import OAI.Computability.VPVNP.PairShrinkOrdinalSources
+import OAI.Computability.VPVNP.PairShrinkItemsOfFn
+import OAI.Computability.VPVNP.PairShrinkInstalledItem
+
+/-!
+# The installed map loop at a selected shrinking site
+
+The row cursor ranges over the site's true ordered resident occurrences. Each
+occurrence reads the selected level's physical tables, gathers from the
+caller’s retained packets and evaluates the grouped matrix at its own ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows ShrinkRole ShrinkRole.MapWitness
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {i : Fin S.steps}
+variable {g w n : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+variable {sel : SelectedScore.Selection B X} {v : Site X}
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+variable (site : CanonicalSite B i X sel v w n (Fintype.card B.Entry))
+variable (ord : B.Entry → Fin (Fintype.card B.Entry))
+variable (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "J" => jobs B i X sel site.workspace site.positions site.blocks site.cur site.bounds
+ n site.rowEnd site.older site.later v old parent
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "L" => BlockProgram.layout B site.workspace.val site.positions site.blocks
+local notation "here" => Nat.cast (R := Word w) (levelStart L site.cur)
+local notation "cut" => tableBase L site.cur (0 : Fin 6)
+local notation "node" => site.later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal (X.shrinkNext B.shrink (S.shrink i) sel) v
+
+/-- The canonical fit uses the old row base and pitch of this job's packet arena. -/
+private theorem job_fit (q : X.packingData.ResidentMap side v) :
+ let job := J q
+ let d := ShrinkPreparedCall.widthsDemand X q.1.1
+ ShrinkCallFields.Fits (w := w) (n := n) (limit := site.limit)
+ (t := Fintype.card B.Entry) (u := MotifConversion.repetitions B.shrink d) B.shrink
+ d (sel q.1.1).val job.scratch (ShrinkMotifOrder.stateNumber X q.1.1).val
+ (ShrinkCallDemandCells.cdBase X q.1.1 job.arena job.nodes) := site.fits q.1.1
+
+variable {p r : ℕ} (M : Machine w p r 11) (pc : Fin (shrinkSegment B ord).count → Fin p)
+variable (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+variable (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r) (done : Fin p)
+local notation "common" => shared B ord i reg
+local notation "P" => mapLoop B ord i pc reg done
+
+-- The loaded party and motif identify the row without reevaluating its energy comparison.
+open private jobPublic from OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+attribute [local irreducible] Compression.ShrinkEnergy.chosenLayout MapWitness.rowEquiv
+ rowOrdinalWord rowAction ShrinkCallFields.workspace
+
+private theorem item_change {p r k w endAddr src₀ src₁ : ℕ}
+ {p₀ p₁ : ResidentMapLoop.Program p r} {machine : Machine w p r k} {mem : Memory w}
+ {d : Fin 9 ↪ Fin r} {inv : Word w → Config w p r → Prop}
+ {f₀ f₁ : ResidentMapLoop.Exact.Action w endAddr}
+ (h : ResidentMapLoop.Exact.Item p₀ machine mem d inv src₀ f₀)
+ (program : p₀ = p₁) (src : src₀ = src₁) (act : f₀ = f₁) :
+ ResidentMapLoop.Exact.Item p₁ machine mem d inv src₁ f₁ := by
+ subst p₁ src₁ f₁
+ exact h
+
+set_option maxHeartbeats 1200000 in
+-- Instantiate the dependent stage and resident index in the host's gather and matrix banks.
+/-- Execute every canonical map action with the actual installed role and live row sources. -/
+theorem exact_items
+ (installed : ∀ j, M.code (pc j) = ((shrinkSegment B ord).row pc dfs saved reg done j).resize w)
+ (ds : ∀ j k, reg j ≠ dfs k) (ss : ∀ j k, reg j ≠ saved k)
+ (H : Word w) (terminalRoom : H.val + 31 < 2 ^ w)
+ (levelEq : site.level = here)
+ (sources : ∀ q, RowSources B i X sel site.workspace site.positions site.blocks site.cur
+ site.bounds n site.rowEnd site.older site.later v old parent site.mem H q)
+ (entry : Config w p r) (expected : Word w → Word w)
+ (start : SiteMapInput common dfs regions n ((node : ℕ) : Word w) site.level site.term
+ expected entry)
+ (fields : ∀ q : X.packingData.ResidentMap side v,
+ (J q).Packets n entry.privateMem ∧ (J q).ChildWords entry.privateMem n ∧
+ ShrinkCallSupplyCells.Absorbed X side (ShrinkPreparedCall.width B.shrink X sel) q.1.1
+ q.1.2 (J q).scratch (q.2.symm ▸ hidden) entry.privateMem ∧
+ (∀ u, (J q).arena.base ((J q).nodes u) + (J q).arena.stride ≤ (J q).scratch.hist) ∧
+ (J q).arena.base (J q).node + (J q).arena.stride ≤ (J q).scratch.hist) :
+ ResidentMapLoop.Exact.Items P M site.mem dfs (siteInvariant site common entry)
+ (firstMap B i site.source v) (canonicalBank site ord parent old hidden) := by
+ let F := matrixFamily B ord i
+ let G := gatherFamily B ord i
+ let locals := reloadRegs B ord i reg
+ let tmp := locals (layoutTemp F G)
+ have localD : ∀ j k, locals j ≠ dfs k := fun _ _ ↦ ds _ _
+ have localS : ∀ j k, locals j ≠ saved k := fun _ _ ↦ ss _ _
+ have banks := hosted_banks F G dfs saved locals localD localS
+ have link := map_linked B ord i M (matrixPC B ord i pc) dfs saved locals done
+ (selected_map_rows B ord i M pc dfs saved reg done installed)
+ unfold canonicalBank MapWitness.actions
+ apply ResidentMapLoop.Exact.Items.ofFn
+ intro j
+ let q := rowEquiv (a := a i) (g := g) X side v j
+ let job := J q
+ let atParty : Placed (X.packingData.shrinkInternalOwner side)
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) side)
+ (X.packingData.shrinkPartySite side q.1.1 q.1.2) :=
+ Eq.rec (motive := fun y _ ↦ Placed (X.packingData.shrinkInternalOwner side)
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) side) y) hidden q.2.symm
+ have fit := job_fit site parent old q
+ let pp := pub site.level (job.node : Word w) regions n
+ let st := rowOrdinalWord (w := w) X side v j
+ have pubEq : ShrinkCallABI.pub entry common = pp := by
+ dsimp only [pp]
+ rw [node_eq]
+ exact start.pub_eq
+ have hst := row_ordinal (g := g) (w := w) (B := B) (i := i) (X := X) (sel := sel) (v := v) j
+ have data := source_at (g := g) (w := w) site parent old q H st levelEq hst (sources q)
+ have heads := data.1
+ have next := data.2
+ have abArea := (sources q).abArea
+ have supplyArea := (sources q).supplyArea
+ rw [← levelEq] at abArea supplyArea
+ have sites := job.abi_readSafe (slotDegree S) H terminalRoom heads next abArea supplyArea
+ have hist := ShrinkResidentMemory.histogram_before_hidden regions n (Fintype.card B.Entry) le_rfl
+ have stack : n ≤ job.scratch.hist := Nat.le_add_right ..
+ have positive : 0 < w := by
+ by_contra! zero
+ have two := (sources q).two
+ simp [Nat.eq_zero_of_le_zero zero] at two
+ have pair := row_pair (g := g) (B := B) (i := i) (X := X) (sel := sel) (v := v) j
+ have oldLive : job.OldPublished (ShrinkCallABI.operands (slotDegree S))
+ (ShrinkCallABI.pub entry common) st site.mem site.level
+ (packedIncidence L w site.cur (DemandRAM.oldCount X)) cut := by
+ rw [pubEq]
+ exact heads
+ have args := fields q
+ have live (u : Word w) (c : Config w p r) (valid : siteInvariant site common entry u c) :=
+ ShrinkPartyNative.Job.liveOperands (w := w) (p := p) (r := r) (g := g)
+ (endAddr := n) (n := n) (limit := site.limit) B ord i sel job atParty fit dfs saved
+ common tmp entry st site.mem site.level site.term banks.2.2 start.level start.term
+ start.stride start.one args.1 args.2.1 args.2.2.1 args.2.2.2.1 args.2.2.2.2 hist
+ oldLive (sources q).two (sources q).termRoom (sources q).pairs (sources q).fields u c valid
+ have run := ShrinkPartyNative.Job.installedItem (X := X) (w := w) (g := g)
+ (endAddr := n) (n := n) (limit := site.limit) (motif := q.1.1) (party := q.1.2)
+ (origin := cut) (layer := site.later) (pitch := B.recordLimit + 2)
+ (T := packedIncidence L w site.cur (DemandRAM.oldCount X))
+ (U := packedIncidence L w (site.cur + 1) (actualCount (levelShape (b := b i) X)))
+ (absolute := ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X cut) w)
+ (heads := ShrinkOutput.heads (levelShape (b := b i) X)
+ (SelectedArena.roleBase X (ShrinkInput.termHead (w := w) X cut) 10)
+ (tableBase L site.cur (3 : Fin 6)))
+ B ord i sel job atParty fit (gatheredPC B ord i pc) dfs saved locals done M v site.mem
+ site.level site.term site.source j pp site.width (siteInvariant site common entry) link
+ localD localS positive pair.symm (TerminalLink.workerCell H) sites heads next stack hist (by
+ intro u c valid
+ have ev := live u c valid
+ rw [pubEq] at ev
+ exact ev)
+ refine item_change run ?_ ?_ ?_
+ · rfl
+ · rfl
+ · funext u scratch
+ dsimp only [q, job, atParty, pp, MapWitness.jobInput, jobPublic, id]
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkLiveOperands.lean b/lean/OAI/Computability/VPVNP/PairShrinkLiveOperands.lean
new file mode 100644
index 0000000000..bc737779a4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkLiveOperands.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.PairShrinkResidentMemory
+import OAI.Computability.VPVNP.PairSimulationShrinkLiveOperands
+import OAI.Computability.VPVNP.PairShrinkVertexImage
+
+/-!
+# Live resident operands for one physical shrinking map
+
+The resident loop carries the old header, term pointer, constant stride,
+one word and the writer's five public inputs in the same eight shared
+registers throughout. Packet and shared-field readbacks are those of the
+loop-entry private memory. The fixed map row runs against its own selected
+motif, while its exterior frame maintains these inputs for the next row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkVertexImage
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords
+open ShrinkMapImage ShrinkMapImage.Registers ShrinkResidentMemory
+open scoped Fin.CommRing
+
+/-- Live registers at a map-row entrance. Header registers 0, 4, 5 and
+10 and the five public operands share the old-level register 11. -/
+def residentSlot : Fin 8 → Fin 24 := ![11, 16, 17, 22, 0, 9, 10, 8]
+
+/-- A host register is live at a resident map entrance when it is the image of one of the eight
+operand slots. -/
+def residentLive {r : ℕ} (common : Fin 24 ↪ Fin r) (q : Fin r) :=
+ ∃ j : Fin 8, common (residentSlot j) = q
+
+theorem live_protected {r : ℕ} (common : Fin 24 ↪ Fin r) (tmp : Fin r)
+ (apart : ∀ j, common j ≠ tmp) (j : Fin 8) :
+ Protected mapRegisters common tmp (common (residentSlot j)) := by
+ have disjoint : ∀ i : Fin 8, residentSlot i ≠ mapRegisters.zero ∧
+ ∀ k : Fin 11, 6 ≤ k.val → k.val ≤ 9 → residentSlot i ≠ mapRegisters.header k := by decide
+ exact ⟨apart _, common.injective.ne (disjoint j).1,
+ fun k lo hi ↦ common.injective.ne ((disjoint j).2 k lo hi)⟩
+
+/-- The resident loop's cursor can advance without changing any live map
+operand register. -/
+theorem residentLive_cursor {r : ℕ} (common : Fin 24 ↪ Fin r) (q : Fin r)
+ (live : residentLive common q) : q ≠ (mapRegisters.headerReg common) 2 := by
+ obtain ⟨j, rfl⟩ := live
+ apply common.injective.ne
+ exact (by decide : ∀ i : Fin 8, residentSlot i ≠ mapRegisters.header 2) j
+
+end PairSimulation.ShrinkVertexImage
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open MotifGrid MotifBlocks MotifConversion MotifEntry NetworkKernel CompressorRecords
+open CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open ShrinkVertexImage ShrinkMapImage.Registers ShrinkResidentMemory
+
+variable {w p r t n limit endAddr g : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (ord : B.Entry → Fin t) (stage : Fin S.steps)
+variable {X : State (a stage) (packingLaneBits (a stage) g)}
+variable (sel : X.ShrinkSelection B.shrink) {motif : X.packingData.Motif} {party : Fin 6}
+variable (J : Job X B.shrink (S.shrink stage) sel motif party w)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "Fam" => matrixFamily B ord stage
+local notation "degree" => slotDegree S
+local notation "BW" => ShrinkPreparedCall.widthsDemand X motif
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X motif)
+local notation "cd" => ShrinkCallDemandCells.cdBase X motif J.arena J.nodes
+
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel))
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) motif party))
+local notation "call" => Job.entryInput B X (S.shrink stage) sel motif party J hidden
+
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (ShrinkPreparedCall.widthsDemand X motif)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X motif) (sel motif).val J.scratch
+ (ShrinkMotifOrder.stateNumber X motif).val (ShrinkCallDemandCells.cdBase X motif J.arena J.nodes))
+
+variable (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin 24 ↪ Fin r)
+variable (tmp : Fin r) (entry : Config w p r) (st : Word w) (mem : Memory w) (level term : Word w)
+local notation "P" => ShrinkCallABI.pub entry common
+local notation "work" =>
+ Job.mapWorkspace B degree ord X (S.shrink stage) sel motif party J hidden ok
+local notation "guard" => residentLive common
+local notation "inv" => fun (_ : Word w) (c : Config w p r) ↦
+ Invariant J.scratch entry.privateMem guard entry.reg c
+
+set_option maxHeartbeats 1300000 in
+-- The grouped entry and the selected stage's gather share dependent map registers and field widths.
+/-- Supply the non-static inputs of the exact row interpreter from the
+loop-entry configuration and the chronological source readbacks. -/
+theorem Job.liveOperands {T : IncidenceDirectory w} {origin : ℕ}
+ (apart : ∀ j, common j ≠ tmp) (head : entry.reg (common 11) = level)
+ (termAt : entry.reg (common 16) = term) (strideAt : entry.reg (common 17) = 10)
+ (oneAt : entry.reg (common 22) = 1)
+ (packets : J.Packets endAddr entry.privateMem)
+ (children : J.ChildWords entry.privateMem endAddr)
+ (hiddenAt : ShrinkCallSupplyCells.Absorbed X side widths motif party J.scratch hidden
+ entry.privateMem)
+ (childrenLow : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ J.scratch.hist)
+ (parentLow : J.arena.base J.node + J.arena.stride ≤ J.scratch.hist)
+ (histEnd : J.scratch.hist + t ≤ J.scratch.hidden)
+ (old : J.OldPublished (ShrinkCallABI.operands degree) P st mem level T origin)
+ (two : 2 < 2 ^ w) (termRoom : ShrinkInput.termEnd X origin 10 < 2 ^ w)
+ (pairs : ShrinkTermInputs.statePairs X (ShrinkInput.demandHead X origin) mem)
+ (terms : TermRecordScan.Fields B.shrink ShrinkSliceArrays.supplyRoles demandMass_pos
+ BW (sel motif).val (ShrinkTermSelection.rowBase X (ShrinkInput.termHead X origin) 10 motif)
+ mem)
+ (node : Word w) (c : Config w p r) (valid : inv node c) :
+ LiveOperands (endAddr := endAddr) Fam mapRegisters dfs saved common tmp call J P st mem
+ level term work inv node c := by
+ have reg (l : Fin 8) := valid.registers (common (residentSlot l)) ⟨l, rfl⟩
+ have hiddenFit (t : Fin 4) : widths motif (!side, t) ≤ J.scratch.stride := ok.supply (!side, t)
+ have stageRoom : J.scratch.staging ≤ 2 ^ w := by
+ have room := ok.room.trans_lt ok.capacity.room
+ unfold ShrinkCallFields.Scratch.target ShrinkCallFields.Scratch.source
+ ShrinkCallFields.Scratch.descriptor ShrinkCallFields.Scratch.directory at room
+ omega
+ have histStage : J.scratch.hist ≤ J.scratch.staging :=
+ (Nat.le_add_right ..).trans (histEnd.trans (Nat.le_add_right ..))
+ refine ⟨(reg 0).trans head, (reg 1).trans termAt, (reg 2).trans strideAt, (reg 3).trans oneAt,
+ ?_, J.packets_preserved valid.memory packets childrenLow parentLow, ?_, ?_⟩
+ · intro j
+ have publicSlots : ∀ j : Fin 5, ∃ l : Fin 8,
+ residentSlot l = ShrinkCallABI.sourceSlot j.castSucc := by decide
+ obtain ⟨l, hl⟩ := publicSlots j
+ change c.reg (common (ShrinkCallABI.sourceSlot j.castSucc)) =
+ entry.reg (common (ShrinkCallABI.sourceSlot j.castSucc))
+ rw [← hl]
+ exact reg l
+ · intro out staged pubEq stateEq
+ have table : J.OldPublished (ShrinkCallABI.operands degree) (ShrinkCallABI.pub out common)
+ (ShrinkCallABI.state out common) mem level T origin := by
+ change ShrinkCallABI.pub out common = P at pubEq
+ change ShrinkCallABI.state out common = st at stateEq
+ rw [pubEq, stateEq]
+ exact old
+ exact Job.prepared_after_gather B degree ord X (S.shrink stage) sel motif party J hidden ok dfs
+ saved common out mem c.privateMem staged
+ (J.childWords_preserved valid.memory children childrenLow)
+ (fun u ↦ (childrenLow u).trans histStage)
+ (J.absorbed_preserved hidden valid.memory hiddenAt ok.ordinal hiddenFit stageRoom)
+ T origin level table two termRoom pairs terms
+ · intro out kept frame
+ apply Job.keepsInputs B degree ord X (S.shrink stage) sel motif party J hidden ok valid
+ _ histEnd P st mem old frame
+ intro q ⟨l, hq⟩
+ rw [← hq]
+ exact kept _ (live_protected common tmp apart l)
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkMapExterior.lean b/lean/OAI/Computability/VPVNP/PairShrinkMapExterior.lean
new file mode 100644
index 0000000000..be6b664e9f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkMapExterior.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.PairShrinkRoleMapActions
+import OAI.Computability.VPVNP.PairSimulationMapScanAcceptance
+import OAI.Computability.VPVNP.PairShrinkRoutedExterior
+
+/-!
+# Exterior scratch after the scheduled shrinking map scan
+
+The scan runs the actions in the actual resident row order. The selected
+job's fitted workspace and published operands protect every word below the
+hidden storage that is outside the histogram, including all child arguments.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots ShrinkMapImage.Registers
+open ResidentMapLoop.Exact MapResidentRows NodeArguments
+open scoped Fin.CommRing
+
+variable {g w n t limit packetEnd : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (ord : B.Entry → Fin t) (i : Fin S.steps)
+variable (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+variable (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+open private acceptanceBase from OAI.Computability.VPVNP.PairShrinkRoleMapActions
+private noncomputable local instance exteriorBaseDecidable : DecidableEq X.Base :=
+ acceptanceBase i X
+set_option allowUnsafeReducibility true in
+attribute [local reducible] exteriorBaseDecidable
+set_option allowUnsafeReducibility true in
+attribute [local irreducible] selectedLayout
+
+local notation "side" => selectedLayout X B.shrink sel
+local notation "F" => ShrinkVertexImage.matrixFamily B ord i
+local notation "G" => ShrinkVertexImage.gatherFamily B ord i
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+variable (jobs : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ ShrinkPartyNative.Job X B.shrink (S.shrink i) sel q.1.1 q.1.2 w)
+
+local notation "entry" => jobInput (g := g) (w := w) B i X sel v hidden jobs
+local notation "atRow" => rowEquiv (a := S.degreeExponent i.castSucc) (g := g) X side v
+variable (mem : Memory w) (level term : Word w)
+variable (src : MapRowSource X sel (selectedLayout X B.shrink sel) mem level term)
+variable (hw : MapConstants.widthThreshold B.shrink ≤ w)
+variable (pub : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v → Fin 5 → Word w)
+variable (ok : ∀ q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v,
+ ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := MotifConversion.repetitions B.shrink (ShrinkPreparedCall.widthsDemand X q.1.1)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X q.1.1) (sel q.1.1).val (jobs q).scratch
+ (ShrinkMotifOrder.stateNumber X q.1.1).val
+ (ShrinkCallDemandCells.cdBase X q.1.1 (jobs q).arena (jobs q).nodes))
+
+set_option maxHeartbeats 1500000 in
+-- Align each resident's dependent workspace with the input indexed by its party and motif.
+/-- The genuine schedule workspace of each selected job in the row. -/
+noncomputable def mapWorkspaces (q : X.packingData.ResidentMap side v) :
+ MapHandlerOperand.Workspace (w := w) F demandMass_pos (entry q) :=
+ ShrinkPartyNative.Job.mapWorkspace (a := S.degreeExponent i.castSucc)
+ (b := S.degreeExponent i.succ) (g := g) (w := w) (n := n) (limit := limit)
+ B (slotDegree S) ord X (S.shrink i) sel
+ q.1.1 q.1.2 (jobs q) (q.2.symm ▸ hidden) (ok q)
+
+set_option allowUnsafeReducibility true in
+attribute [local irreducible] MapHandlerOperand.Workspace ShrinkVertexImage.matrixFamily
+
+set_option maxHeartbeats 1800000 in
+-- Instantiate the workspace at each selected row before it enters the scratch-dependent scan.
+/-- The scheduled row with the fitted workspace at every resident occurrence. -/
+noncomputable def fittedActions : List (Action w n) :=
+ actions (g := g) (w := w) (endAddr := n) B ord i X sel v hidden jobs mem level term src hw pub
+ fun q ↦ mapWorkspaces (g := g) (w := w) (n := n) (limit := limit) B ord i X sel v hidden
+ jobs ok q
+
+local notation "scheduled" => fittedActions (g := g) (w := w) (n := n) (limit := limit)
+ B ord i X sel v hidden jobs mem level term src hw pub ok
+
+set_option allowUnsafeReducibility true in
+attribute [local irreducible] rowAction ShrinkPartyNative.Job.entryInput
+ ShrinkPartyNative.Job.mapWorkspace
+
+set_option maxHeartbeats 3000000 in
+-- The action and workspace depend on the same physical row and its resident party.
+/-- Every successful scheduled resident scan preserves the words below the hidden
+storage outside the histogram. This applies to every incoming scratch value. -/
+theorem scan_exterior (R : LeafArena.Regions) (node : Word w) (saved : Scratch w n)
+ (labels : t ≤ R.histWords)
+ (scratchHist : ∀ q, (jobs q).scratch.hist = R.histBase)
+ (scratchBase : ∀ q, (jobs q).scratch.hidden = ShrinkCallABI.hiddenBase R n)
+ (baseline : Word w → Word w) (packets : ∀ q, (jobs q).Packets packetEnd baseline)
+ {T : IncidenceDirectory w} {origin : ℕ}
+ (old : ∀ j : Fin (order X side v).length, let q := atRow j
+ (jobs q).OldPublished (ShrinkCallABI.operands (slotDegree S)) (pub q)
+ (rowOrdinalWord (a := S.degreeExponent i.castSucc) (g := g) (w := w) X side v j)
+ mem level T origin)
+ {events : List (Event w)} {out : Scratch w n}
+ (run : scan (w := w) (endAddr := n) node scheduled saved = some (events, out))
+ (address : Word w)
+ (low : address.val < ShrinkCallABI.hiddenBase R n)
+ (outside : address.val < R.histBase ∨ R.histBase + t ≤ address.val) :
+ rawScratch out address = rawScratch saved address := by
+ unfold fittedActions actions at run
+ suffices h : rawScratch out address = rawScratch saved address +
+ ∑ _j : Fin (order X side v).length, (0 : Word w) by simpa only [Finset.sum_const_zero,
+ add_zero] using h
+ refine scan_ofFn_add (endAddr := n) (n := (order X side v).length) node _
+ (fun s ↦ rawScratch s address) (fun _ ↦ (0 : Word w)) ?_ run
+ intro j initial trace next got
+ let q := atRow j
+ unfold mapWorkspaces jobInput at got
+ have endHist : (jobs q).scratch.hist + t ≤ (jobs q).scratch.hidden := by
+ rw [scratchHist q, scratchBase q]
+ exact ShrinkResidentMemory.histogram_before_hidden R n t labels
+ have under : address.val < (jobs q).scratch.staging :=
+ (low.trans_le (scratchBase q).ge).trans_le (Nat.le_add_right ..)
+ have away : address.val < (jobs q).scratch.hist ∨ (jobs q).scratch.hist + t ≤ address.val := by
+ rwa [scratchHist q]
+ exact (ShrinkPartyNative.Job.routed_preserves (g := g) (w := w) (endAddr := n)
+ (n := n) (t := t) (limit := limit) (packetEnd := packetEnd) («side» := side)
+ (T := T) (origin := origin) (baseline := baseline) (events := trace) (out := next)
+ B ord i X sel q.1.1 q.1.2 (jobs q) (q.2.symm ▸ hidden) (ok q) hw (pub q) mem
+ v level term src j initial (packets q) endHist (old j) got address under away).trans
+ (add_zero _).symm
+
+end PairSimulation.ShrinkRole.MapWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkMapJobInput.lean b/lean/OAI/Computability/VPVNP/PairShrinkMapJobInput.lean
new file mode 100644
index 0000000000..554f226839
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkMapJobInput.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.PairShrinkJobPrepared
+import OAI.Computability.VPVNP.PairShrinkRoleMapWitness
+
+/-!
+# The native shrinking party and its selected kernel witness
+
+The same placed old factors, independently supplied new halves and once-guessed
+absorbed labels give the same entry input in the executable map and in the
+local polynomial witness.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (S.degreeExponent i.castSucc)
+ (packingLaneBits (S.degreeExponent i.castSucc) g))
+variable (sel : X.ShrinkSelection B.shrink)
+/-- Classical decidable equality on the compression state’s base vertices for identifying the
+native map input with the selected kernel input. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+
+variable (v : (X.Base × BitWord (packingTagBits (2 ^ S.degreeExponent i.castSucc))) × BitWord g)
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+variable (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v)
+variable (J : Job X B.shrink (S.shrink i) sel q.1.1 q.1.2 w)
+
+set_option maxHeartbeats 1000000 in
+-- Reindexing the local arguments unfolds the dependent half-wire type of the chosen layout.
+/-- Reading the stored parent and its placed child packets gives the input
+whose accepted name list appears in the shrinking kernel's monomial witness. -/
+theorem Job.entryInput_eq_witness
+ (children : J.old = Eq.rec (motive := fun y _ ↦ Placed (X.packingData.shrinkPlace side)
+ (X.packingData.oldWireNetwork X.packingWidth).Half y)
+ (ShrinkRole.MapWitness.placedOld B i X sel v old) q.2.symm)
+ (newHalf : J.parent = Eq.rec (motive := fun y _ ↦
+ (X.shrinkNext B.shrink (S.shrink i) sel).network.Half y) parent q.2.symm) :
+ Job.entryInput B X (S.shrink i) sel q.1.1 q.1.2 J (q.2.symm ▸ hidden) =
+ ShrinkRole.MapWitness.input B i X sel v old parent hidden q := by
+ unfold Job.entryInput ShrinkPreparedCall.input
+ rw [children, newHalf]
+ rfl
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkMapReload.lean b/lean/OAI/Computability/VPVNP/PairShrinkMapReload.lean
new file mode 100644
index 0000000000..f2ea1e7d82
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkMapReload.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.PairVertexLocatedBody
+import OAI.Computability.VPVNP.PairVertexSegmentChain
+
+/-!
+# Reloading the geometry and histogram heads before the shrinking maps
+
+The DFS end register points to a private word containing the geometry head. The
+histogram head is its eleventh field. This fixed prefix reads those two words from
+the actual configuration before entering the grid and party map loop.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapReload
+
+open BurstRAM BurstRAM.PrivateRAM NodeArguments.ChildScan VertexImage
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {p r w : ℕ}
+
+/-- Four native instructions follow the private geometry pointer at the stack end and load
+geometry word 11, the histogram base, into locator register 10. -/
+def instruction (pc : Fin 4 → Fin p) (reg : Fin 14 ↪ Fin r) (stack : Fin r) (done : Fin p) :
+ Fin 4 → Instr w p r 11 :=
+ ![.loadPrivate (reg 9) stack (pc 1), .constant (reg 10) 11 (pc 2),
+ .binary .add (reg 10) (reg 9) (reg 10) (pc 3), .loadPrivate (reg 10) (reg 10) done]
+
+theorem resize_instruction (pc : Fin 4 → Fin p) (reg : Fin 14 ↪ Fin r)
+ (stack : Fin r) (done : Fin p) (i : Fin 4) :
+ (instruction (w := 5) pc reg stack done i).resize w = instruction pc reg stack done i := by
+ fin_cases i <;> rfl
+
+/-- The private reload leaves the packed owner and the cached hidden-field head intact. -/
+theorem run {M : Machine w p r 11} {pc : Fin 4 → Fin p} {reg : Fin 14 ↪ Fin r}
+ {stack : Fin r} {done : Fin p} (linked : ∀ i, M.code (pc i) = instruction pc reg stack done i)
+ (c : Config w p r) (hc : c.pc = pc 0) (m : Memory w) :
+ let G := c.privateMem (c.reg stack)
+ ∃ out, Prefix M m c out [] (List.replicate 4 .tick) ∧ out.pc = done ∧
+ out.reg (reg 9) = G ∧ out.reg (reg 10) = c.privateMem (G + 11) ∧
+ (∀ j, j ≠ reg 9 → j ≠ reg 10 → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ intro G
+ let a := c.put (pc 1) (reg 9) G
+ let b := a.put (pc 2) (reg 10) 11
+ let d := b.put (pc 3) (reg 10) (G + 11)
+ let out := d.put done (reg 10) (c.privateMem (G + 11))
+ have atRow (i : Fin 4) (q : Config w p r) (hp : q.pc = pc i) :
+ M.program.step q = (instruction pc reg stack done i).run M.publicData q := by
+ simp only [Machine.program, hp, linked]
+ have s₀ : M.program.step c = .localStep a := atRow 0 c hc
+ have s₁ : M.program.step a = .localStep b := atRow 1 a rfl
+ have s₂ : M.program.step b = .localStep d := by
+ rw [atRow 2 b rfl]
+ change CallAction.localStep (b.put _ _ (b.reg (reg 9) + b.reg (reg 10))) = _
+ simp [a, b, d, Config.put]
+ have s₃ : M.program.step d = .localStep out := by
+ rw [atRow 3 d rfl]
+ change CallAction.localStep (d.put _ _ (d.privateMem (d.reg (reg 10)))) = _
+ simp [a, b, d, out, Config.put]
+ have pre : ReadPrefix M m c (List.replicate 4 .tick) out :=
+ ReadPrefix.tick s₀ (ReadPrefix.tick s₁ (ReadPrefix.tick s₂
+ (ReadPrefix.tick s₃ (ReadPrefix.nil _))))
+ refine ⟨out, ReadPrefix.execute pre, rfl, ?_, ?_, ?_, rfl, rfl⟩
+ · simp [out, d, b, a, Config.put]
+ · simp [out]
+ · intro j h₉ h₁₀
+ simp [out, d, b, a, Config.put, Function.update_of_ne h₉, Function.update_of_ne h₁₀]
+
+/-- Install the four histogram-reload instructions ahead of a located resident map body, using
+its locator registers and DFS stack-end register. -/
+def setup (B : LocatedBody) : Segment where
+ count := 4
+ privateRegs := B.code.privateRegs
+ entry := 0
+ row pc dfs _ regs done := instruction pc (B.locator.trans regs) (dfs 6) done
+
+/-- Geometry preparation and the installed map share their full register bank. -/
+def body (B : LocatedBody) : LocatedBody where
+ code := Segment.thenWith (setup B) B.code (Function.Embedding.refl _) (Function.Embedding.refl _)
+ locator := B.locator
+
+theorem links (B : LocatedBody) (M : Machine w p r 11)
+ (pc : Fin (body B).code.count → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (regs : Fin B.code.privateRegs ↪ Fin r) (done : Fin p)
+ (installed : ∀ i, M.code (pc i) = ((body B).code.row pc dfs saved regs done i).resize w) :
+ (∀ i, M.code (Segment.leftPC (setup B) B.code pc i) =
+ instruction (Segment.leftPC (setup B) B.code pc) (B.locator.trans regs) (dfs 6)
+ (Segment.rightPC (setup B) B.code pc B.code.entry) i) ∧
+ (∀ i, M.code (Segment.rightPC (setup B) B.code pc i) =
+ (B.code.row (Segment.rightPC (setup B) B.code pc) dfs saved regs done i).resize w) := by
+ obtain ⟨l, r⟩ := Segment.split_link (setup B) B.code (Function.Embedding.refl _)
+ (Function.Embedding.refl _) pc dfs saved regs done M installed
+ exact ⟨fun i => (l i).trans (resize_instruction ..), r⟩
+
+end PairSimulation.ShrinkMapReload
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkMapRowJobCount.lean b/lean/OAI/Computability/VPVNP/PairShrinkMapRowJobCount.lean
new file mode 100644
index 0000000000..38627d939d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkMapRowJobCount.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.PairShrinkJobHistogram
+
+/-! # Histogram counts of a complete shrinking resident occurrence -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif MotifEntry
+open MotifBlocks MotifGrid MotifConversion NetworkKernel CompressorRecords
+open CompressorRecords.ShrinkSlots NodeArguments ShrinkMapImage.Registers MapResidentRows
+open scoped Fin.CommRing
+
+variable {w g packetEnd endAddr t n limit : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (ord : B.Entry → Fin t) (i : Fin S.steps)
+local notation "degree" => slotDegree S
+local notation "family" => ShrinkVertexImage.matrixFamily B ord i
+local notation "gathers" => ShrinkVertexImage.gatherFamily B ord i
+variable (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+variable (sel : X.ShrinkSelection B.shrink)
+variable (m : X.packingData.Motif) (party : Fin 6)
+variable (J : Job X B.shrink (S.shrink i) sel m party w)
+private noncomputable local instance routedHistogramBase : DecidableEq X.Base := Classical.decEq _
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel))
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m party))
+local notation "call" => Job.entryInput B X (S.shrink i) sel m party J hidden
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (ShrinkPreparedCall.widthsDemand X m)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X m) (sel m).val J.scratch (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallDemandCells.cdBase X m J.arena J.nodes))
+local notation "W" => Job.mapWorkspace B degree ord X (S.shrink i) sel m party J hidden ok
+variable (hw : MapConstants.widthThreshold B.shrink ≤ w)
+variable (P : Fin 5 → Word w) (mem : Memory w) (site : Site X) (level term : Word w)
+variable {side : Bool} (src : MapRowSource X sel side mem level term)
+variable (row : Fin (order X side site).length)
+local notation "st" => rowOrdinalWord (w := w) (a := S.degreeExponent i.castSucc) (g := g)
+ X side site row
+
+local notation:max "bin" l:max => ((J.scratch.hist + Fin.val (l : Fin t) : ℕ) : Word w)
+
+set_option maxHeartbeats 2000000 in
+-- The scheduled row, party input and gathered output share a dependent job index.
+/-- Routing the selected resident preserves the gathered map's exact histogram update. -/
+theorem Job.routed_histogram (saved : DFS.Scratch w endAddr)
+ {baseline : Word w → Word w} (packets : J.Packets packetEnd baseline)
+ (floor : endAddr ≤ J.scratch.hist) (histEnd : J.scratch.hist + t ≤ J.scratch.hidden)
+ {T : IncidenceDirectory w} {origin : ℕ}
+ (old : J.OldPublished (ShrinkCallABI.operands degree) P st mem level T origin)
+ {events : List (Event w)} {out : DFS.Scratch w endAddr}
+ (got : rowAction (g := g) (ready := S.shrink i) (side := side) (jobMotif := m)
+ family gathers X sel site mem level term src row call J hw P W saved =
+ some (events, out)) :
+ ∀ l : Fin t, rawScratch out (bin l) = rawScratch saved (bin l) +
+ (((MapHandlerOperand.names family demandMass_pos call).getD []).count l : Word w) := by
+ unfold rowAction at got
+ obtain ⟨⟨trace, last⟩, raw, pair⟩ := Option.map_eq_some_iff.mp got
+ have same : last = out := (Prod.mk.inj pair).2
+ rw [← same]
+ exact Job.gathered_histogram B ord i X sel m party J hidden ok hw P st mem saved
+ packets floor histEnd old raw
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkNodeClock.lean b/lean/OAI/Computability/VPVNP/PairShrinkNodeClock.lean
new file mode 100644
index 0000000000..47ac6e9a94
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkNodeClock.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.PairShrinkNodeStageCost
+import OAI.Computability.VPVNP.PairShrinkRoleSetup
+import OAI.Computability.VPVNP.PairShrinkRoleHeaderSetup
+import OAI.Computability.VPVNP.PairShrinkRoleHandoff
+import OAI.Computability.VPVNP.PairSimulationMapResidentInputs
+
+/-! # Counts for a complete shrinking visit
+
+All terms outside the selected map list are explicit native instruction
+or probe counts. A resident map list contributes its test and increment
+per item, its final exit test, and the traces of its actually executed items.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkNodeCost
+
+open BurstRAM PrivateRAM DFS Compression CompressorRecords NodeArguments NodeArguments.ChildScan
+open ShrinkRole ShrinkHiddenGuess
+open scoped Fin.CommRing
+
+variable {w endAddr a g : ℕ} {X : State a g}
+
+private theorem noProbes (n : ℕ) : countProbes (List.replicate n (.tick : Event w)) = 0 := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa only [List.replicate_succ, countProbes] using ih
+
+/-- Counts for a map list that actually succeeded, parameterized by the
+concrete resource bounds for each selected row. -/
+theorem scan_cost {ι : Type*} (jobs : List ι) (action : ι → ResidentMapLoop.Exact.Action w endAddr)
+ (ticks reads : ι → ℕ) (node : Word w) (saved out : Scratch w endAddr) (es : List (Event w))
+ (row : ∀ i ∈ jobs, ∀ s e t, action i node s = some (e, t) →
+ e.length ≤ ticks i ∧ countProbes e ≤ reads i)
+ (got : ResidentMapLoop.Exact.scan node (jobs.map action) saved = some (es, out)) :
+ es.length ≤ 1 + 2 * jobs.length + (jobs.map ticks).sum ∧
+ countProbes es ≤ (jobs.map reads).sum := by
+ induction jobs generalizing saved es out with
+ | nil =>
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj got)
+ exact ⟨le_rfl, le_rfl⟩
+ | cons j js ih =>
+ cases hx : action j node saved with
+ | none => simp [ResidentMapLoop.Exact.scan, hx] at got
+ | some pair =>
+ obtain ⟨h, mid⟩ := pair
+ cases hy : ResidentMapLoop.Exact.scan node (js.map action) mid with
+ | none => simp [ResidentMapLoop.Exact.scan, hx, hy] at got
+ | some pair =>
+ obtain ⟨t, last⟩ := pair
+ simp only [List.map_cons, ResidentMapLoop.Exact.scan, hx, hy, Option.some.injEq,
+ Prod.mk.injEq] at got
+ obtain ⟨rfl, rfl⟩ := got
+ have first := row j List.mem_cons_self _ _ _ hx
+ have rest := ih mid last t (fun i hi => row i (List.mem_cons_of_mem _ hi)) hy
+ simp only [List.length_append, List.length_cons, List.length_nil, List.map_cons,
+ List.sum_cons, countProbes_append, countProbes]
+ omega
+
+variable (A : Arena) (T : IncidenceDirectory w) (m : Memory w) (older cap : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w X)
+ (args : List (Child X) → Args w) (seed : List (Child X) → List Row)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w endAddr))
+ (pub : Fin 11 → Word w) (level later stages stage selectors stride oldHead : ℕ) (owner : Word w)
+ (s₁ : Setup w endAddr) (s₂ : List (Child X) → Setup w endAddr)
+ (s₃ : List (Child X) → List Row → Setup w endAddr)
+ (node : Word w) (saved : Scratch w endAddr) (bs tail : List Bool) (out : Outcome w endAddr Unit)
+ (childSetup : s₁.trace node saved = VertexLevel.trace pub m level later ++
+ List.replicate (stages + 7 + 2 * stage) .tick ++ List.replicate 2 .tick ++
+ List.replicate (2 ^ a) .tick)
+ (hiddenSetup : ∀ xs s, (s₂ xs).trace node s =
+ List.replicate (VertexLevel.hiddenCount + 1) .tick ++
+ Header.canonicalTrace selectors stride (oldHead : Word w) m)
+ (mapSetup : ∀ xs h s, (s₃ xs h).trace node s = List.replicate 4 .tick ++
+ MapResidentInputs.headerEvents m (oldHead : Word w) owner)
+ (got : visitReader A T m older cap desc args seed maps s₁ s₂ s₃ node saved bs =
+ some (out, tail))
+
+include childSetup hiddenSetup mapSetup got
+
+/-- Instruction and probe counts for the child and hidden reads reached by the visit
+and the resident map scan starting on their prepared scratch. -/
+theorem native_cost_reached :
+ ∃ child mid hidden mapOut ms,
+ ChildArguments.reader A T m older cap desc node (s₁.updated node saved) bs =
+ some (child, mid) ∧
+ hiddenReader (args child.value) m (seed child.value) node
+ ((s₂ child.value).updated node child.updated) mid = some (hidden, tail) ∧
+ ResidentMapLoop.Exact.scan node (maps child.value hidden.value)
+ ((s₃ child.value hidden.value).updated node hidden.updated) = some (ms, mapOut) ∧
+ child.value.map Child.site = (desc node).sites ∧
+ hidden.value.length = (seed child.value).length ∧
+ (stream hidden.value).length = (stream (seed child.value)).length ∧
+ out.trace.length = 88 + 6 * later + stages + 2 * stage + 2 ^ a + VertexLevel.hiddenCount +
+ (RegisterSetup.lines (Header.recipe selectors stride)).length +
+ (10 + 15 * 2 ^ a) * (desc node).sites.length +
+ 6 * ChildArguments.demand X (desc node).sites +
+ 25 * (seed child.value).length + 6 * (stream (seed child.value)).length + ms.length ∧
+ countProbes out.trace = 25 + later + (1 + 3 * 2 ^ a) * (desc node).sites.length +
+ 3 * (seed child.value).length + countProbes ms := by
+ obtain ⟨child, mid, hidden, mapOut, ms, hchild, hhidden, hscan, sites, hnum, hbits, trace⟩ :=
+ visit_trace_reached A T m older cap desc args seed maps s₁ s₂ s₃ node saved bs tail out got
+ refine ⟨child, mid, hidden, mapOut, ms, hchild, hhidden, hscan, sites, hnum, hbits, ?_⟩
+ rw [trace, childSetup, hiddenSetup, mapSetup]
+ obtain ⟨locT, locP, _⟩ := VertexLevel.trace_cost pub m level later
+ obtain ⟨chP, chT, _⟩ := ChildHeader.cost m node (desc node).directoryBase
+ obtain ⟨_, oldP, oldT⟩ := ChildScan.events_cost X T m (desc node).source child.value
+ obtain ⟨hdrT, hdrP⟩ := hidden_header_cost selectors stride (oldHead : Word w) m
+ obtain ⟨hidT, hidP, _⟩ := ShrinkHiddenGuess.cost (args child.value) m hidden.value
+ obtain ⟨mapT, mapP, _⟩ := MapResidentInputs.headerCost m (oldHead : Word w) owner
+ have nxs : child.value.length = (desc node).sites.length := by
+ simpa only [List.length_map] using congrArg List.length sites
+ have demand := (ChildArguments.payload_length X child.value).trans
+ (congrArg (ChildArguments.demand X) sites)
+ simp only [List.length_append, List.length_replicate, countProbes_append, noProbes,
+ locT, locP, chT, chP, oldT, oldP, hdrT, hdrP, hidT, hidP, mapT, mapP, nxs, demand, hnum, hbits]
+ constructor <;> omega
+
+/-- Combined length of the level search, stage selection, child handoff,
+child directory, hidden handoff, hidden header and loop, and map reload
+and header. The list of per-item map events includes its own loop control. -/
+theorem native_cost :
+ ∃ xs hs mapIn mapOut ms, xs.map Child.site = (desc node).sites ∧ hs.length = (seed xs).length ∧
+ (stream hs).length = (stream (seed xs)).length ∧
+ ResidentMapLoop.Exact.scan node (maps xs hs) mapIn = some (ms, mapOut) ∧
+ out.trace.length = 88 + 6 * later + stages + 2 * stage + 2 ^ a + VertexLevel.hiddenCount +
+ (RegisterSetup.lines (Header.recipe selectors stride)).length +
+ (10 + 15 * 2 ^ a) * (desc node).sites.length +
+ 6 * ChildArguments.demand X (desc node).sites +
+ 25 * (seed xs).length + 6 * (stream (seed xs)).length + ms.length ∧
+ countProbes out.trace = 25 + later + (1 + 3 * 2 ^ a) * (desc node).sites.length +
+ 3 * (seed xs).length + countProbes ms := by
+ obtain ⟨child, mid, hidden, mapOut, ms, _, _, hscan, sites, hnum, hbits, ticks, probes⟩ :=
+ native_cost_reached A T m older cap desc args seed maps pub level later stages stage selectors
+ stride oldHead owner s₁ s₂ s₃ node saved bs tail out childSetup hiddenSetup mapSetup got
+ exact ⟨child.value, hidden.value, _, mapOut, ms, sites, hnum, hbits, hscan, ticks, probes⟩
+
+end PairSimulation.ShrinkNodeCost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkNodeLabelBudget.lean b/lean/OAI/Computability/VPVNP/PairShrinkNodeLabelBudget.lean
new file mode 100644
index 0000000000..8639798f57
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkNodeLabelBudget.lean
@@ -0,0 +1,319 @@
+import OAI.Computability.VPVNP.PairSimulationMapResidentRows
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoop
+import OAI.Computability.VPVNP.PairShrinkRoleMapLabels
+import OAI.Computability.VPVNP.PairRefreshTraversalMapBody
+import OAI.Computability.VPVNP.PairShrinkJobPrepared
+
+/-!
+# Label counts of native shrinking and refresh rows
+
+A successful motif invocation emits one label for each repetition, including
+repeated labels. A shrinking row enumerates the six-party occurrences in its
+published order. Its output on every input is bounded by the row capacity
+times the repetition bound of the input state. A refresh has one invocation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open MotifGrid MotifBlocks MotifConversion MotifDemandPadding MotifSelector
+
+variable {K : Type*} [Field K] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+ {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+ (B : FixedBlock K a b P (realWidths p) (realWidths q) H H')
+
+/-- A successful run on arbitrary bit inputs emits one base-matrix label
+per copy, even if several copies select the same label. -/
+theorem runEntry_length [DecidableEq J] (hp : ∀ i, 0 < p i) (width : D → ℕ)
+ (payload : S → ℕ) (j : J) (d : MotifEntry.DemandBits a b width j)
+ (x : Half P (fun e => Fin (supplyWidths B width payload e) → Bool) j)
+ {ls : List (parameterData B).Entry} (hit : (runEntry B hp width payload j d x).1 = some ls) :
+ ls.length = repetitions B width := by
+ unfold runEntry at hit
+ erw [MotifEntry.run_value] at hit
+ unfold MotifEntry.describe MotifEntry.labels at hit
+ obtain ⟨idx, _, rfl⟩ := Option.map_eq_some_iff.mp hit
+ exact List.length_ofFn
+
+end PairSimulation.LocalHistory
+
+namespace PairSimulation.ResidentMapLoop
+
+/-- On a successful loop the list has exactly the sum of the copy counts.
+A failing loop keeps the prefix already emitted, bounded by the same sum. -/
+theorem labels_length_ofFn {t n : ℕ} (jobs : Fin n → Job t) (copies : Fin n → ℕ)
+ (lengths : ∀ i ls, (jobs i).names = some ls → ls.length = copies i) :
+ (labels (List.ofFn jobs)).length ≤ ∑ i, copies i ∧
+ (passed (List.ofFn jobs) = true → (labels (List.ofFn jobs)).length = ∑ i, copies i) := by
+ induction n with
+ | zero => simp [labels, passed]
+ | succ n ih =>
+ obtain ⟨leTail, eqTail⟩ := ih (fun i => jobs i.succ) (fun i => copies i.succ)
+ (fun i => lengths i.succ)
+ rw [List.ofFn_succ, Fin.sum_univ_succ]
+ cases first : (jobs 0).names with
+ | none => simp [labels, passed, first]
+ | some ls =>
+ have head := lengths 0 ls first
+ simp only [labels, first, Option.elim_some, List.length_append, head]
+ constructor
+ · exact Nat.add_le_add_left leTail _
+ · intro pass
+ have later : passed (List.ofFn fun i => jobs i.succ) = true := by
+ simpa [passed, first] using pass
+ rw [eqTail later]
+
+end PairSimulation.ResidentMapLoop
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel LocalHistory
+open MotifBlocks MotifConversion MotifGrid MotifDemandPadding MotifSelector
+open CompressorRecords
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (B : S.Templates)
+
+theorem names_length (arg : EntryInput B.shrink) {ls : List (parameterData B.shrink).Entry}
+ (hit : names B arg = some ls) : ls.length = repetitions B.shrink arg.demand :=
+ runEntry_length B.shrink demandMass_pos arg.demand arg.payload arg.party _ _ hit
+
+section Entries
+
+variable {n t : ℕ} (args : Fin n → EntryInput B.shrink)
+ (index : (parameterData B.shrink).Entry → Fin t) (jobs : Fin n → ResidentMapLoop.Job t)
+ (correct : ∀ j, (jobs j).names = (names B (args j)).map (List.map index))
+
+include correct in
+/-- On a passed row the degree equals the sum of the repetitions of its
+actual entry calls. Every prefix of a rejecting row satisfies the upper bound. -/
+theorem row_label_lengths :
+ (ResidentMapLoop.labels (List.ofFn jobs)).length ≤ ∑ j, repetitions B.shrink (args j).demand ∧
+ (ResidentMapLoop.passed (List.ofFn jobs) = true →
+ (ResidentMapLoop.labels (List.ofFn jobs)).length =
+ ∑ j, repetitions B.shrink (args j).demand) := by
+ apply ResidentMapLoop.labels_length_ofFn jobs
+ intro j ls hit
+ rw [correct] at hit
+ obtain ⟨body, success, rfl⟩ := Option.map_eq_some_iff.mp hit
+ rw [List.length_map]
+ exact names_length B _ success
+
+include correct in
+theorem row_label_max (bound : ℕ) (copyBound : ∀ j, repetitions B.shrink (args j).demand ≤ bound) :
+ (ResidentMapLoop.labels (List.ofFn jobs)).length ≤ n * bound := by
+ apply (row_label_lengths B args index jobs correct).1.trans
+ calc
+ _ ≤ ∑ _ : Fin n, bound := Finset.sum_le_sum fun j _ => copyBound j
+ _ = _ := by simp
+
+end Entries
+
+section Ordered
+
+variable {a l t : ℕ} (Y : State a (packingLaneBits a l)) (layoutSide : Bool)
+ (v : MapResidentRows.Site Y)
+/-- Classical decidable equality on the compression state’s base vertices for counting labels
+in the ordered resident row. -/
+noncomputable local instance : DecidableEq Y.Base := Classical.decEq _
+variable (args : Fin (MapResidentRows.order Y layoutSide v).length → EntryInput B.shrink)
+ (widths : ∀ j : Fin (MapResidentRows.order Y layoutSide v).length,
+ (args j).demand = Y.packingData.shrinkDemandWidths Y.shrinkNumber Y.packingWidth
+ (MapResidentRows.entry Y layoutSide v j).1)
+ (index : (parameterData B.shrink).Entry → Fin t)
+ (jobs : Fin (MapResidentRows.order Y layoutSide v).length → ResidentMapLoop.Job t)
+ (correct : ∀ j : Fin (MapResidentRows.order Y layoutSide v).length,
+ (jobs j).names = (names B (args j)).map (List.map index))
+
+include Y layoutSide v args widths index jobs correct
+
+set_option maxHeartbeats 1000000 in
+-- The demand vector uses a dependent projection from the enumerated resident.
+/-- The resident row in the published directory has a linear label budget
+in the input width, including inputs that fail at a later occurrence. -/
+theorem row_label_budget :
+ (ResidentMapLoop.labels (List.ofFn jobs)).length ≤
+ MapResidentRows.capacity a * fieldFactor B.shrink * (Y.maxWireWidth + 1) := by
+ rw [Nat.mul_assoc, ← MapResidentRows.length_eq Y layoutSide v]
+ apply row_label_max B args index jobs correct
+ intro j
+ rw [widths]
+ exact (linear_field_bounds B.shrink _ _ (Y.packingData.shrinkDemandWidths_le
+ (State.two_le_packingColors _) (Nat.two_pow_pos _) Y.shrinkNumber Y.packingWidth
+ (fun _ => Y.width_le_maxWireWidth _) _)).1
+
+theorem row_label_count_le_square (n : ℕ) (hn : 1 ≤ n) (width : Y.maxWireWidth ≤ n)
+ (large : 2 * (MapResidentRows.capacity a * fieldFactor B.shrink) ≤ n)
+ (label : Fin t) : (ResidentMapLoop.labels (List.ofFn jobs)).count label ≤ n ^ 2 := by
+ let c := MapResidentRows.capacity a * fieldFactor B.shrink
+ have bound := row_label_budget B Y layoutSide v args widths index jobs correct
+ refine (List.count_le_length (a := label)).trans (bound.trans ?_)
+ calc
+ c * (Y.maxWireWidth + 1) ≤ c * (2 * n) := Nat.mul_le_mul_left _ (by omega)
+ _ = (2 * c) * n := by ring
+ _ ≤ n ^ 2 := by rw [pow_two]; exact Nat.mul_le_mul_right _ large
+
+end Ordered
+
+section Selected
+
+open CompressorRecords.ShrinkSlots
+
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g : ℕ}
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+/-- Classical decidable equality on the compression state’s base vertices for bounding the
+exponents of the selected shrink witness. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm)
+ X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+local notation "W" => B.shrinkPassWitnesses f hf i rfl X sel v old parent
+local notation "side" => selectedLayout X B.shrink sel
+
+set_option maxHeartbeats 2000000 in
+-- The kernel witness and the six-party resident subtype use dependent reindexings.
+/-- Bound the increment of the actual selected kernel witness in the common
+parameter alphabet, at the point where the frontier checks word headroom. -/
+theorem selected_exponent_bound (x : (W).Choice) (label : B.Entry) :
+ (W).exponents x label ≤ MapResidentRows.capacity (S.degreeExponent i.castSucc) *
+ fieldFactor B.shrink * (X.maxWireWidth + 1) := by
+ classical
+ cases label with
+ | inr l => rw [refresh_exponent B f hf i X sel v old parent x l]; exact Nat.zero_le _
+ | inl l =>
+ rw [exponent_count B f hf i X sel v old parent x l]
+ have cardinal : Fintype.card (X.packingData.ResidentMap side v) =
+ MapResidentRows.capacity (S.degreeExponent i.castSucc) := by
+ rw [Fintype.card_congr (rowEquiv X side v).symm, Fintype.card_fin, MapResidentRows.length_eq]
+ calc
+ _ ≤ ∑ _ : X.packingData.ResidentMap side v, fieldFactor B.shrink * (X.maxWireWidth + 1) := by
+ apply Finset.sum_le_sum
+ intro q _
+ let I := input B i X sel v old parent x.1 q
+ have limit : repetitions B.shrink I.demand ≤ fieldFactor B.shrink * (X.maxWireWidth + 1) :=
+ (linear_field_bounds B.shrink _ _ (X.packingData.shrinkDemandWidths_le
+ (State.two_le_packingColors _) (Nat.two_pow_pos _) X.shrinkNumber X.packingWidth
+ (fun _ => X.width_le_maxWireWidth _) q.val.1)).1
+ change ((names B I).getD []).count l ≤ _
+ cases got : names B I with
+ | none => simp
+ | some ls =>
+ exact (List.count_le_length (a := l) (l := ls)).trans
+ ((names_length B I got).le.trans limit)
+ _ = _ := by simp [cardinal, Nat.mul_assoc]
+
+theorem exponent_le_square (x : (W).Choice) (label : B.Entry) {n : ℕ} (hn : 1 ≤ n)
+ (width : X.maxWireWidth ≤ n)
+ (large : 2 * (MapResidentRows.capacity (S.degreeExponent i.castSucc) *
+ fieldFactor B.shrink) ≤ n) :
+ (W).exponents x label ≤ n ^ 2 := by
+ let c := MapResidentRows.capacity (S.degreeExponent i.castSucc) * fieldFactor B.shrink
+ apply (selected_exponent_bound B f hf i X sel v old parent x label).trans
+ calc
+ c * (X.maxWireWidth + 1) ≤ c * (2 * n) := Nat.mul_le_mul_left _ (by omega)
+ _ = (2 * c) * n := by ring
+ _ ≤ n ^ 2 := by rw [pow_two]; exact Nat.mul_le_mul_right _ large
+
+end Selected
+
+open Filter in
+/-- The input-length threshold for all shrinking stages is fixed before
+choosing any state, layout, site or branch of the schedule. -/
+theorem eventually_row_constants :
+ ∀ᶠ n : ℕ in atTop, 1 ≤ n ∧ ∀ j : Fin S.steps,
+ 2 * (MapResidentRows.capacity (S.degreeExponent j.castSucc) * fieldFactor B.shrink) ≤ n := by
+ let coeff (j : Fin S.steps) :=
+ 2 * (MapResidentRows.capacity (S.degreeExponent j.castSucc) * fieldFactor B.shrink)
+ filter_upwards [eventually_ge_atTop (max 1 (Finset.univ.sup coeff))] with n hn
+ exact ⟨(le_max_left ..).trans hn, fun j =>
+ (Finset.le_sup (f := coeff) (Finset.mem_univ j)).trans ((le_max_right ..).trans hn)⟩
+
+end PairSimulation.ShrinkRole.MapWitness
+
+namespace PairSimulation.ShrinkPartyNative
+
+open Compression Compression.PackingData Compression.ShrinkMotif CompressorRecords
+open CompressorRecords.ShrinkSlots NetworkKernel
+
+attribute [local irreducible] LocalHistory.Order.restrict LocalHistory.shrinkMotifOrder
+ LocalHistory.Order.prod ShrinkCallABI.family
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {a b g w t : ℕ} {δ : ℝ} (X : State a (packingLaneBits a g))
+ (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) (sel : X.ShrinkSelection B.shrink)
+ (v : MapResidentRows.Site X)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+local notation "row" => Fin (LocalHistory.Order.length (MapResidentRows.order X side v))
+local notation "motif" => fun j => Prod.fst (MapResidentRows.entry X side v j)
+local notation "party" => fun j => Prod.snd (MapResidentRows.entry X side v j)
+
+set_option maxHeartbeats 1500000 in
+-- The real party job specializes both halves of the indexed handler family.
+/-- Apply the width bound directly to the selected handler family on the
+physical party jobs. Work and probe charges do not affect its emitted labels. -/
+theorem native_row_label_budget (degree : ℕ) (index : B.Entry → Fin t)
+ (calls : ∀ j : row, Job X B.shrink ready sel (motif j) (party j) w)
+ (hidden : ∀ j : row, Placed (X.packingData.shrinkInternalOwner side)
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) side)
+ (X.packingData.shrinkPartySite side (motif j) (party j)))
+ (work probes : row → ℕ) :
+ let inputs := fun j => Job.entryInput B X ready sel (motif j) (party j) (calls j) (hidden j)
+ let family := ShrinkCallABI.family B degree a index
+ let jobs := List.ofFn fun j => ResidentMapLoop.Job.mk
+ (MapHandlerOperand.names family demandMass_pos (inputs j)) (work j) (probes j)
+ (ResidentMapLoop.labels jobs).length ≤
+ MapResidentRows.capacity a * fieldFactor B.shrink * (X.maxWireWidth + 1) := by
+ intro inputs family jobs
+ exact ShrinkRole.MapWitness.row_label_budget B X side v inputs (fun _ => rfl) family.ordinal
+ (fun j => ⟨MapHandlerOperand.names family demandMass_pos (inputs j), work j, probes j⟩)
+ (fun _ => rfl)
+
+end PairSimulation.ShrinkPartyNative
+
+namespace CompressorRecords.PortRefresh.TraversalPlan
+
+open Compression Compression.Refresh Compression.DegreeRefresh NetworkKernel PairSimulation
+open MotifConversion MotifDemandPadding MotifSelector LocalHistory RefreshMapOperands
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {hist g : ℕ} (order : B.Entry ≃ Fin hist) (X : State S.portExponent (S.portExponent + g))
+ (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh)
+ (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent))
+ (old : X.network.Half (oldSite X v))
+ (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order
+ S.degree_bounds.2 choice).network.Half
+ (promotedSites v))
+
+/-- The native refresh has one motif call after its diagonal checks. -/
+theorem emitted_length {ls : List (Fin hist)} (hit : emitted B order X choice v old new = some ls) :
+ ls.length = repetitions B.refresh
+ (blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) v.1) := by
+ unfold emitted at hit
+ split at hit
+ · obtain ⟨names, success, rfl⟩ := Option.map_eq_some_iff.mp hit
+ rw [List.length_map]
+ exact runEntry_length B.refresh _ _ _ _ _ _ success
+ · contradiction
+
+theorem emitted_length_bound {ls : List (Fin hist)}
+ (hit : emitted B order X choice v old new = some ls) :
+ ls.length ≤ Fintype.card (Tie (2 ^ S.portExponent)) * X.maxWireWidth := by
+ rw [emitted_length B order X choice v old new hit]
+ apply term_repetitions_le
+ intro e
+ unfold blockDemandWidths internalWidth
+ split <;> exact X.width_le_maxWireWidth _
+
+end CompressorRecords.PortRefresh.TraversalPlan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkNodeRates.lean b/lean/OAI/Computability/VPVNP/PairShrinkNodeRates.lean
new file mode 100644
index 0000000000..c89a4e27e9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkNodeRates.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PairShrinkNodeClock
+import OAI.Computability.VPVNP.PairVertexLevelSchedule
+import OAI.Computability.VPVNP.PairVertexOrdinalRoleCost
+import OAI.Computability.VPVNP.PairDispatchedRowEffects
+
+/-! # Uniform resources of a shrinking node in the ordinal traversal
+
+The level locator is the only source of length-dependent external probes.
+The old and hidden bit streams contribute private instructions linear in
+the current maximum width. The dispatch costs one probe and nine instructions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkNodeCost
+
+open Compression CompressorRecords BurstRAM DFS Filter
+
+variable {k : Type*} [_root_.Field k] (S : BlockSchedule k)
+
+private def fixedProbes (i : Fin S.steps) (mapC fieldC : ℕ) :=
+ 26 + (1+3*2^(S.degreeExponent i.castSucc))*fieldC + 3*fieldC + mapC
+
+/-- One common coefficient for all shrinking passes in the installed schedule. -/
+def probeRate (mapC fieldC : ℕ) :=
+ Finset.univ.sup (fun i : Fin S.steps => fixedProbes S i mapC fieldC + (S.steps+1))
+
+private noncomputable def fixedTicks (i : Fin S.steps) (header fieldC : ℕ) :=
+ let degree := 2^(S.degreeExponent i.castSucc)
+ 97 + S.steps + 2*i.val + degree + VertexLevel.hiddenCount + header +
+ (10+15*degree)*fieldC + 25*fieldC
+
+private noncomputable def tickRate (i : Fin S.steps) (header mapC fieldC : ℕ) :=
+ fixedTicks S i header fieldC + 6*(S.steps+1) + 12*fieldC + mapC
+
+/-- At a single eventual threshold every stage's instruction coefficient
+fits. Header lengths can differ between stages. -/
+def RateRoom (header : Fin S.steps → ℕ) (mapC fieldC n : ℕ) : Prop :=
+ 1 ≤ n ∧ ∀ i, 2*tickRate S i (header i) mapC fieldC ≤ n
+
+theorem eventually_job_rate_room (header : Fin S.steps → ℕ) (mapC fieldC : ℕ) :
+ ∀ᶠ n : ℕ in atTop, RateRoom S header mapC fieldC n := by
+ let rates := fun i : Fin S.steps => 2*tickRate S i (header i) mapC fieldC
+ filter_upwards [eventually_ge_atTop (max 1 (Finset.univ.sup rates))] with n hn
+ exact ⟨(le_max_left ..).trans hn,fun i =>
+ (Finset.le_sup (f := rates) (Finset.mem_univ i)).trans ((le_max_right ..).trans hn)⟩
+
+/-- The two count identities are the output of `native_cost` for a single
+successful shrinking reader. The map-loop charges include its final exit
+test and every selected row, including the case of an empty loop. -/
+theorem job_rates (i : Fin S.steps) (header : Fin S.steps → ℕ) (mapC fieldC n : ℕ)
+ (room : RateRoom S header mapC fieldC n)
+ {later width sites oldBits hiddenRows hiddenBits mapTicks mapProbes ticks probes : ℕ}
+ (level : later ≤ (S.steps+1)*(n.log2+1)) (wire : width ≤ n)
+ (children : sites ≤ fieldC) (demand : oldBits ≤ fieldC*(width+1))
+ (hidden : hiddenRows ≤ fieldC) (payload : hiddenBits ≤ fieldC*(width+1))
+ (mapTime : mapTicks ≤ mapC*(width+1)) (mapReads : mapProbes ≤ mapC)
+ (time : ticks = 88+6*later+S.steps+2*i.val+2^(S.degreeExponent i.castSucc)+VertexLevel.hiddenCount+
+ header i+(10+15*2^(S.degreeExponent i.castSucc))*sites+6*oldBits+
+ 25*hiddenRows+6*hiddenBits+mapTicks)
+ (reads : probes = 25+later+(1+3*2^(S.degreeExponent i.castSucc))*sites+3*hiddenRows+mapProbes) :
+ probes+1 ≤ probeRate S mapC fieldC*(n.log2+1) ∧ ticks+9 ≤ n^43 := by
+ let fixed := fixedProbes S i mapC fieldC
+ let t := tickRate S i (header i) mapC fieldC
+ have degree := Nat.mul_le_mul_left (1+3*2^(S.degreeExponent i.castSucc)) children
+ have hs := Nat.mul_le_mul_left 3 hidden
+ have work := Nat.mul_le_mul_left (10+15*2^(S.degreeExponent i.castSucc)) children
+ have hh := Nat.mul_le_mul_left 25 hidden
+ have loc := Nat.mul_le_mul_left 6 (level.trans (Nat.mul_le_mul_left _ (Nat.succ_le_succ (Nat.log2_le_self n))))
+ have enlarge (c : ℕ) := Nat.mul_le_mul_left c (Nat.succ_le_succ wire)
+ have old := Nat.mul_le_mul_left 6 (demand.trans (enlarge fieldC))
+ have bits := Nat.mul_le_mul_left 6 (payload.trans (enlarge fieldC))
+ have maps := mapTime.trans (enlarge mapC)
+ constructor
+ · have sup : fixed+(S.steps+1) ≤ probeRate S mapC fieldC :=
+ Finset.le_sup (f := fun j => fixedProbes S j mapC fieldC + (S.steps+1)) (Finset.mem_univ i)
+ refine le_trans ?_ (Nat.mul_le_mul_right (n.log2+1) sup)
+ have pad : fixed ≤ fixed*(n.log2+1) := Nat.le_mul_of_pos_right fixed (Nat.succ_pos _)
+ rw [Nat.add_mul]
+ dsimp only [fixed,fixedProbes] at pad ⊢
+ omega
+ · have scaled : ticks+9 ≤ t*(n+1) := by
+ have pad := Nat.le_mul_of_pos_right (fixedTicks S i (header i) fieldC) (Nat.succ_pos n)
+ dsimp only [t,tickRate,fixedTicks] at pad ⊢
+ rw [time]
+ linarith only [pad,loc,work,hh,old,bits,maps]
+ have fit : 2*t ≤ n := room.2 i
+ have hn := room.1
+ calc
+ ticks+9 ≤ t*(n+1) := scaled
+ _ ≤ t*(2*n) := Nat.mul_le_mul_left t (by omega)
+ _ = 2*t*n := by ring
+ _ ≤ n^2 := by rw [pow_two]; exact Nat.mul_le_mul_right n fit
+ _ ≤ n^43 := Nat.pow_le_pow_right hn (by decide : 2 ≤ 43)
+
+/-- The real tag lookup adds exactly the one probe and at most the nine
+instructions already allowed in the two bounds on the underlying role. -/
+theorem dispatched_ordinal_cost {w endAddr n rate : ℕ} (m : Memory w) (offset node : Word w)
+ (saved : DFS.Scratch w endAddr) (body : DFS.VisitPath w endAddr)
+ (probes : countProbes body.trace+1 ≤ rate*(n.log2+1)) (ticks : body.trace.length+9 ≤ n^43) :
+ VertexImage.ordinalJobCost n 1 rate (VertexImage.dispatchJob m offset node saved body) := by
+ obtain ⟨p,t⟩ := VertexImage.dispatchJob_cost (m := m) (offset := offset) (node := node) (saved := saved) body
+ exact ⟨by simpa only [p,pow_one] using probes,t.trans ticks⟩
+
+variable {S} {R : Type*} [CommRing R] (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+variable {lanes : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+
+/-- The pass list appearing in the actual level search gives the logarithmic
+number of later headers for every popped ordinal. -/
+theorem selected_later_le_log {n : ℕ} (blocks : T ≤ n.log2+1) (level : ℕ) :
+ (executeLevels B f hf T hT X z).length - (level+1) ≤ (S.steps+1)*(n.log2+1) := by
+ rw [VertexLevel.selected_pass_count B f hf T hT X z]
+ exact (Nat.sub_le ..).trans ((Nat.mul_le_mul_right _ blocks).trans_eq (Nat.mul_comm ..))
+
+end PairSimulation.ShrinkNodeCost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkNodeStageCost.lean b/lean/OAI/Computability/VPVNP/PairShrinkNodeStageCost.lean
new file mode 100644
index 0000000000..0328ce49a3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkNodeStageCost.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.PairShrinkRoleExact
+import OAI.Computability.VPVNP.PairShrinkHiddenHeaderTrace
+import OAI.Computability.VPVNP.PairNodeChildScanCost
+
+/-! # Trace charges of the selected shrinking role
+
+The child and hidden readers derive field widths from their respective
+directories. The private bit loops spend six instructions per bit. Their
+external probes depend on the number of fields and children. The locator,
+the four handoffs, and both headers are charged at their native instruction
+counts, including at a site with an empty child or map list.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkNodeCost
+
+open BurstRAM PrivateRAM DFS Compression CompressorRecords NodeArguments NodeArguments.ChildScan
+open ShrinkRole ShrinkHiddenGuess
+open scoped Fin.CommRing
+
+variable {w endAddr a g : ℕ} {X : State a g}
+
+private theorem bind_trace {α β : Type*} (a : Reader w endAddr α) (b : α → Reader w endAddr β)
+ (node : Word w) (s : Scratch w endAddr) (bs : List Bool) {out : Outcome w endAddr β}
+ {rest : List Bool}
+ (h : ShrinkRole.bind a b node s bs = some (out, rest)) :
+ ∃ first mid last, a node s bs = some (first,mid) ∧
+ b first.value node first.updated mid = some (last,rest) ∧
+ out.trace = first.trace ++ last.trace := by
+ cases h₁ : a node s bs with
+ | none => simp [ShrinkRole.bind,h₁] at h
+ | some pair =>
+ obtain ⟨first,mid⟩ := pair
+ obtain ⟨⟨last,tail⟩,h₂,eqn⟩ :=
+ Option.map_eq_some_iff.mp (by simpa only [ShrinkRole.bind,h₁] using h)
+ cases eqn
+ exact ⟨first,mid,last,rfl,h₂,rfl⟩
+
+private theorem decode_shape (seed : List Row) (bs : List Bool)
+ (h : (stream seed).length ≤ bs.length) :
+ (decode seed bs).1.length=seed.length ∧
+ (stream (decode seed bs).1).length=(stream seed).length := by
+ induction seed generalizing bs with
+ | nil => exact ⟨rfl,rfl⟩
+ | cons e es ih =>
+ have enough : e.2.length+(stream es).length ≤ bs.length := by
+ simpa only [stream,List.flatMap_cons,List.length_append] using h
+ obtain ⟨hn,hw⟩ := ih (bs.drop e.2.length) (by simp only [List.length_drop]; omega)
+ exact ⟨congrArg Nat.succ hn,by
+ simp only [decode,stream,List.flatMap_cons,List.length_append,List.length_take]
+ rw [Nat.min_eq_left (by omega : e.2.length ≤ bs.length)]
+ exact congrArg (e.2.length+·) hw⟩
+
+theorem hidden_trace (args : Args w) (m : Memory w) (seed : List Row) (node : Word w)
+ (s : Scratch w endAddr) (bs tail : List Bool) (out : Outcome w endAddr (List Row))
+ (h : hiddenReader args m seed node s bs = some (out, tail)) :
+ out.trace=events args m out.value ∧ out.value.length=seed.length ∧
+ (stream out.value).length=(stream seed).length := by
+ unfold hiddenReader at h
+ split at h
+ · rename_i enough
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj h)
+ exact ⟨rfl,decode_shape seed bs enough⟩
+ · contradiction
+
+section
+
+variable (A : Arena) (T : IncidenceDirectory w) (m : Memory w) (older cap : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w X)
+ (args : List (Child X) → Args w) (seed : List (Child X) → List Row)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w endAddr))
+ (s₁ : Setup w endAddr) (s₂ : List (Child X) → Setup w endAddr)
+ (s₃ : List (Child X) → List Row → Setup w endAddr)
+ (node : Word w) (s : Scratch w endAddr) (bs tail : List Bool) (out : Outcome w endAddr Unit)
+ (run : visitReader A T m older cap desc args seed maps s₁ s₂ s₃ node s bs = some (out, tail))
+
+include run
+
+/-- The two successful reads pass their returned scratch and tape suffix to the
+next setup and reader. The map scan runs on the scratch prepared from the
+hidden outcome and contributes the final segment of the trace. -/
+theorem visit_trace_reached :
+ ∃ child mid hidden mapOut ms,
+ ChildArguments.reader A T m older cap desc node (s₁.updated node s) bs = some (child,mid) ∧
+ hiddenReader (args child.value) m (seed child.value) node
+ ((s₂ child.value).updated node child.updated) mid = some (hidden,tail) ∧
+ ResidentMapLoop.Exact.scan node (maps child.value hidden.value)
+ ((s₃ child.value hidden.value).updated node hidden.updated) = some (ms,mapOut) ∧
+ child.value.map Child.site = (desc node).sites ∧
+ hidden.value.length = (seed child.value).length ∧
+ (stream hidden.value).length = (stream (seed child.value)).length ∧
+ out.trace = s₁.trace node s ++
+ (ChildHeader.events m node (desc node).directoryBase ++
+ ChildScan.events X T m (desc node).source child.value) ++
+ (s₂ child.value).trace node child.updated ++
+ ShrinkHiddenGuess.events (args child.value) m hidden.value ++
+ (s₃ child.value hidden.value).trace node hidden.updated ++ ms := by
+ obtain ⟨b₁,bs₁,r₁,h₁,hnext,e₁⟩ := bind_trace _ _ node s bs run
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj h₁)
+ obtain ⟨child,bs₂,r₂,hc,hnext,e₂⟩ := bind_trace _ _ _ _ _ hnext
+ have hChild := ChildArguments.reader_some A T m older cap desc hc
+ obtain ⟨b₂,bs₃,r₃,h₂,hnext,e₃⟩ := bind_trace _ _ _ _ _ hnext
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj h₂)
+ obtain ⟨hidden,bs₄,r₄,hh,hnext,e₄⟩ := bind_trace _ _ _ _ _ hnext
+ obtain ⟨trace,hlen,hbits⟩ := hidden_trace _ _ _ _ _ _ _ _ hh
+ obtain ⟨b₃,bs₅,r₅,h₃,hnext,e₅⟩ := bind_trace _ _ _ _ _ hnext
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj h₃)
+ obtain ⟨⟨mapTrace,mapOut⟩,hmap,eqn⟩ := Option.map_eq_some_iff.mp hnext
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj eqn
+ refine ⟨child,bs₂,hidden,mapOut,mapTrace,hc,hh,hmap,hChild.1,hlen,hbits,?_⟩
+ rw [e₁,e₂,e₃,e₄,e₅,trace]
+ have hct := congrArg Outcome.trace hChild.2.1
+ simp only [ChildArguments.outcome] at hct
+ simp only [hct,List.append_assoc]
+
+/-- Split the emitted trace of an accepted node into the very child, hidden
+and resident-map traces read on this path. The map list and its input scratch
+are those produced by the preceding two scans. -/
+theorem visit_trace :
+ ∃ xs hs t₂ t₃ mapInput mapOut mapTrace,
+ xs.map Child.site=(desc node).sites ∧ hs.length=(seed xs).length ∧
+ (stream hs).length=(stream (seed xs)).length ∧
+ ResidentMapLoop.Exact.scan node (maps xs hs) mapInput = some (mapTrace,mapOut) ∧
+ out.trace = s₁.trace node s ++
+ (ChildHeader.events m node (desc node).directoryBase ++
+ ChildScan.events X T m (desc node).source xs) ++
+ (s₂ xs).trace node t₂ ++ ShrinkHiddenGuess.events (args xs) m hs ++
+ (s₃ xs hs).trace node t₃ ++ mapTrace := by
+ obtain ⟨child,_,hidden,mapOut,mapTrace,_,_,hmap,sites,hlen,hbits,trace⟩ :=
+ visit_trace_reached A T m older cap desc args seed maps s₁ s₂ s₃ node s bs tail out run
+ exact ⟨child.value,hidden.value,child.updated,hidden.updated,_,mapOut,mapTrace,
+ sites,hlen,hbits,hmap,trace⟩
+
+end
+
+open private lines_probes from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+open private eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe
+
+theorem hidden_header_cost (selectors stride : ℕ) (ptr : Word w) (m : Memory w) :
+ (Header.canonicalTrace selectors stride ptr m).length =
+ (RegisterSetup.lines (Header.recipe selectors stride)).length ∧
+ countProbes (Header.canonicalTrace selectors stride ptr m)=5 := by
+ refine ⟨(eval_cost ..).1,(lines_probes ..).trans ?_⟩
+ simp only [Fin.sum_univ_succ,Fin.sum_univ_zero,Header.recipe,PhaseRecipe.Expr.header,
+ PhaseRecipe.Expr.headerAddress,PhaseRecipe.Expr.add]
+ rfl
+
+end PairSimulation.ShrinkNodeCost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkOldHalfAddresses.lean b/lean/OAI/Computability/VPVNP/PairShrinkOldHalfAddresses.lean
new file mode 100644
index 0000000000..0f9f5f9c59
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkOldHalfAddresses.lean
@@ -0,0 +1,443 @@
+import OAI.Computability.VPVNP.PairTypedVertexJobs
+import OAI.Computability.VPVNP.PairNodeChildPackets
+import OAI.Computability.VPVNP.ShrinkStateInput
+import OAI.Computability.VPVNP.ShrinkLocalMaps
+import OAI.Computability.VPVNP.CompressorRecordRefreshArgumentAddress
+
+/-!
+# Stored old half-wires at the four shrink demand endpoints
+
+At A and B each demand coordinate uses the old wire and bit selected by
+the common bundle ordering. At C and D it uses the original unsplit wire.
+The incoming pointer is at the actual target and its incoming slot. All
+four reads allow arbitrary independent child half-wire assignments.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments
+
+open BurstRAM DFS
+open scoped Fin.CommRing
+
+/-- A child packet already present in scratch supplies each of its slot fields. -/
+theorem Packet.read_field {a g w endAddr : ℕ} (X : Compression.State a g) (u : X.network.Site)
+ (h : X.network.Half u) (A : Arena) (node : ℕ) (priv : Word w → Word w)
+ (fit : (Packet.mk node (packed X u h)).Fits A w endAddr)
+ (stored : (Packet.mk node (packed X u h)).Stored A
+ (scratch endAddr priv))
+ (dir : Bool) (j : Fin (2 ^ a)) (i : Fin (X.halfWidth u dir j)) :
+ priv ((A.fieldAddress X u node dir j + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (fieldBits X u h dir j i) := by
+ obtain ⟨pre, post, he, hpre⟩ := packed_member X u h dir j
+ have hi : pre.length + i.val < (packed X u h).length := by rw [he]; simp; omega
+ have hb := stored ⟨pre.length + i.val, hi⟩
+ change rawScratch (scratch endAddr priv) ((A.base node + (pre.length + i.val) : ℕ) : Word w) =
+ PrivateFields.bitValue w (packed X u h)[pre.length + i.val] at hb
+ have le : endAddr ≤ A.base node := fit.1
+ have cap : A.base node + (packed X u h).length ≤ 2 ^ w := fit.2.2
+ have addr : (((A.base node + (pre.length + i.val) : ℕ) : Word w)).val =
+ A.base node + (pre.length + i.val) := Nat.mod_eq_of_lt (by omega)
+ rw [Arena.fieldAddress, ← hpre, Nat.add_assoc]
+ have valid : endAddr ≤ (((A.base node + (pre.length + i.val) : ℕ) : Word w)).val := by
+ rw [addr]; omega
+ rw [rawScratch, dite_eq_left valid] at hb
+ simpa [scratch, he, i.isLt] using hb
+
+end PairSimulation.NodeArguments
+
+namespace PairSimulation.ShrinkOldHalves
+
+open Compression Compression.PackingData LocalHistory NodeArguments BurstRAM DFS
+open scoped Fin.CommRing
+
+variable {a g w endAddr : ℕ} (X : State a (packingLaneBits a g))
+local notation "P" => X.packingData
+local notation "old" => X.packingData.oldWireNetwork X.packingWidth
+local notation "I" => X.packingInputIso
+
+/-- Packed position at the chosen end of the old directed arc. -/
+noncomputable def position (e : (old).Edge) : Bool → (old).Site
+ | false => sourcePosition e
+ | true => sourcePosition ((P).actual e)
+
+/-- The slot of this directed arc at the original child. At the incoming
+end the forward incidence column gives the destination slot. -/
+noncomputable def slot (e : (old).Edge) : Bool → Fin (2 ^ a)
+ | false => ((I).edge e).2
+ | true => (X.slots.actualGraph.target ((I).edge e)).2
+
+/-- Private address of an old directed arc's chosen half, obtained from the corresponding old
+site, its DFS node, and its oriented slot. -/
+noncomputable def address (A : Arena) (nodes : X.network.Site → ℕ)
+ (e : (old).Edge) (dir : Bool) : ℕ :=
+ let u := (I).site (position X e dir)
+ A.fieldAddress X u (nodes u) dir (slot X e dir)
+
+/-- Independent word of the packed half-assignment. -/
+noncomputable def halfWord (e : (old).Edge) : (dir : Bool) → (old).Half (position X e dir) →
+ Fin (X.packingWidth e) → Bool
+ | false, z => z.1 e rfl
+ | true, z => z.2 e rfl
+
+private theorem incoming_congr {u : X.network.Site} (z : X.network.Half u)
+ {e f : X.network.Edge} (he : e = f) (h : u = X.network.dst e) (h' : u = X.network.dst f) :
+ List.ofFn (z.2 e h) = List.ofFn (z.2 f h') := by cases he; rfl
+
+/-- Reindexing from the old numbered state to packed coordinates reads the
+actual outgoing or incoming slot of that arc. -/
+theorem slot_bits (e : (old).Edge) (dir : Bool) (z : X.network.Half ((I).site (position X e dir))) :
+ List.ofFn (fieldBits X _ z dir (slot X e dir)) =
+ List.ofFn (halfWord X e dir (X.packingHalfEquiv _ z)) := by
+ cases dir with
+ | false => rfl
+ | true =>
+ let t := X.slots.actualGraph.target
+ let u := (I).site (position X e true)
+ have hdst : u = (t ((I).edge e)).1 := (I).dst e
+ have he : ((incomingOrder X u).entries (slot X e true)).val = (I).edge e := by
+ change t.symm (u,(t ((I).edge e)).2) = (I).edge e
+ rw [hdst]
+ exact t.symm_apply_apply _
+ exact incoming_congr X z he _ _
+
+/-- Native memory at the numbered pointer contains the word used by the packed
+kernel at this endpoint. -/
+theorem read (A : Arena) (nodes : X.network.Site → ℕ) (priv : Word w → Word w)
+ (e : (old).Edge) (dir : Bool) (z : X.network.Half ((I).site (position X e dir)))
+ (fit : (Packet.mk (nodes ((I).site (position X e dir))) (packed X _ z)).Fits A w endAddr)
+ (stored : (Packet.mk (nodes ((I).site (position X e dir))) (packed X _ z)).Stored A
+ (scratch endAddr priv))
+ (i : Fin (X.packingWidth e)) :
+ priv ((address X A nodes e dir + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (halfWord X e dir (X.packingHalfEquiv _ z) i) := by
+ let u := (I).site (position X e dir)
+ let j := slot X e dir
+ let f := fieldBits X u z dir j
+ let h := halfWord X e dir (X.packingHalfEquiv _ z)
+ have eqs : List.ofFn f = List.ofFn h := slot_bits X e dir z
+ have widths : X.halfWidth u dir j = X.packingWidth e := by
+ simpa only [List.length_ofFn] using congrArg List.length eqs
+ have bit {p q : ℕ} {f : Fin p → Bool} {h : Fin q → Bool} (he : p = q)
+ (hs : List.ofFn f = List.ofFn h) (i : Fin q) : f (Fin.cast he.symm i) = h i := by
+ subst q
+ exact congrFun (List.ofFn_injective hs) i
+ exact (Packet.read_field X u z A _ priv fit stored dir j (Fin.cast widths.symm i)).trans
+ (congrArg _ (bit widths eqs i))
+
+
+variable (layout : Bool)
+local notation "Site" => Compression.Site X.Base (BitWord (packingTagBits (2 ^ a))) (BitWord g)
+
+/-- Scratch contains the child packets for precisely the old sites placed
+at the given new site, with the packing isomorphism reversed on their values. -/
+def PlacedPackets (A : Arena) (nodes : X.network.Site → ℕ) (priv : Word w → Word w)
+ (site : Site) (x : (P).PlacedHalf X.packingWidth layout site) (endAddr : ℕ) : Prop :=
+ ∀ u h, let z := (X.packingHalfEquiv u).symm (x u h)
+ let q := Packet.mk (nodes ((I).site u)) (packed X _ z)
+ q.Fits A w endAddr ∧ q.Stored A (scratch endAddr priv)
+
+variable {A : Arena} {nodes : X.network.Site → ℕ} {priv : Word w → Word w}
+
+theorem read_placed {site : Site} {x : (P).PlacedHalf X.packingWidth layout site}
+ (h : PlacedPackets X layout A nodes priv site x endAddr)
+ (e : (old).Edge) (dir : Bool) (atSite : site = (P).placement layout (position X e dir))
+ (i : Fin (X.packingWidth e)) :
+ priv ((address X A nodes e dir + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (halfWord X e dir (x _ atSite) i) := by
+ let u := position X e dir
+ have data := h u atSite
+ have r := read X A nodes priv e dir ((X.packingHalfEquiv u).symm (x u atSite)) data.1 data.2 i
+ rw [Equiv.apply_symm_apply] at r
+ exact r
+
+/-- Select the A site at the source end of the AB demand and the B site at its target end. -/
+noncomputable def abSite (m : (P).Motif) : Bool → Site
+ | false => (P).roleA m
+ | true => (P).roleB m
+
+private theorem abPlaced (m : (P).Motif) (dir : Bool) (t : (P).ThickFiber ((P).bundle m)) :
+ abSite X m dir = (P).placement layout (position X t.1.1 dir) := by
+ cases dir with
+ | false => exact (congrArg Prod.fst t.2.symm).trans ((P).place_thick_source layout t.1).symm
+ | true =>
+ exact (congrArg (fun b ↦ ((P).siteGraph.target b).1) t.2.symm).trans
+ ((P).place_thick_target layout t.1).symm
+
+/-- Source or target bits to be copied by the AB slice loop, in original
+thick-wire coordinates. -/
+noncomputable def abData (m : (P).Motif) (dir : Bool)
+ (x : (P).PlacedHalf X.packingWidth layout (abSite X m dir))
+ (t : (P).ThickFiber ((P).bundle m)) : Fin (X.packingWidth t.1.1) → Bool :=
+ halfWord X t.1.1 dir (x _ (abPlaced X layout m dir t))
+
+theorem read_ab (m : (P).Motif) (dir : Bool)
+ {x : (P).PlacedHalf X.packingWidth layout (abSite X m dir)}
+ (h : PlacedPackets X layout A nodes priv _ x endAddr)
+ (t : (P).ThickFiber ((P).bundle m)) (i : Fin (X.packingWidth t.1.1)) :
+ priv ((address X A nodes t.1.1 dir + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (abData X layout m dir x t i) :=
+ read_placed X layout h t.1.1 dir (abPlaced X layout m dir t) i
+
+section AB
+
+variable [DecidableEq X.Base]
+variable (hc : 2 ≤ 2 * 2 ^ a + 1) (hd : 0 < 2 ^ a)
+
+
+/-- Repartitioning the stored outgoing AB bits yields the A row. -/
+theorem abData_A (number : X.packingData.BundleNumbering) (order : X.packingData.ThickNumbering)
+ (m : (P).Motif) (x : (P).PlacedHalf X.packingWidth layout ((P).roleA m))
+ (i : Fin ((P).abWidth number X.packingWidth m)) :
+ let z := (P).demandBitEquiv hc hd number order X.packingWidth ((P).bundle m)
+ ⟨⟨m, rfl⟩, i⟩
+ abData X layout m false x z.1 z.2 =
+ (P).localAWord hc hd number order X.packingWidth layout m x i :=
+ rfl
+
+/-- Repartitioning the stored incoming AB bits yields the B row. -/
+theorem abData_B (number : X.packingData.BundleNumbering) (order : X.packingData.ThickNumbering)
+ (m : (P).Motif) (x : (P).PlacedHalf X.packingWidth layout ((P).roleB m))
+ (i : Fin ((P).abWidth number X.packingWidth m)) :
+ let z := (P).demandBitEquiv hc hd number order X.packingWidth ((P).bundle m)
+ ⟨⟨m, rfl⟩, i⟩
+ abData X layout m true x z.1 z.2 =
+ (P).localBWord hc hd number order X.packingWidth layout m x i :=
+ rfl
+
+end AB
+
+/-- The unsplit C endpoint is incoming precisely when the old source is thick. -/
+noncomputable def cDirection (m : (P).Motif) : Bool :=
+ decide ((P).thick (sourcePosition m.1))
+
+theorem read_C (m : (P).Motif)
+ {x : (P).PlacedHalf X.packingWidth layout ((P).placement layout ((P).C m))}
+ (h : PlacedPackets X layout A nodes priv _ x endAddr) (i : Fin (X.packingWidth m.1)) :
+ priv ((address X A nodes m.1 (cDirection X m) + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w ((P).localCWord X.packingWidth layout m x i) := by
+ by_cases thick : (P).thick (sourcePosition m.1)
+ · simp [cDirection, localCWord, thick]
+ simpa only [Nat.cast_add, halfWord, position] using
+ read_placed X layout h m.1 true (by simp [C,thick,position]) i
+ · simp [cDirection, localCWord, thick]
+ simpa only [Nat.cast_add, halfWord, position] using
+ read_placed X layout h m.1 false (by simp [C,thick,position]) i
+
+theorem read_D (m : (P).Motif)
+ {x : (P).PlacedHalf X.packingWidth layout ((P).roleD layout m)}
+ (h : PlacedPackets X layout A nodes priv _ x endAddr) (i : Fin (X.packingWidth m.1)) :
+ priv ((address X A nodes m.1 (!(cDirection X m)) + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w ((P).localDWord X.packingWidth layout m x i) := by
+ by_cases thick : (P).thick (sourcePosition m.1)
+ · simp [cDirection, localDWord, thick]
+ simpa only [Nat.cast_add, halfWord, position] using
+ read_placed X layout h m.1 false (by simp [roleD,D,thick,position]) i
+ · simp [cDirection, localDWord, thick]
+ simpa only [Nat.cast_add, halfWord, position] using
+ read_placed X layout h m.1 true (by simp [roleD,D,thick,position]) i
+
+
+section Selected
+
+open NetworkKernel MotifBlocks MotifConversion MotifGrid ShrinkMotif
+
+variable {b : ℕ} {δ factor : ℝ} {k R : Type*} [Field k] [CommRing R]
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (κ : (parameterData B).Entry → R) (hκ : (parameterData B).IsSolution κ)
+variable (ready : ShrinkMotif.Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ)
+variable (s : X.ShrinkSelection B)
+/-- Classical equality of old base vertices for resolving the sites and slots of placed demand
+halves. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "term" => NetworkKernel.Step.term (StatePass.step (X.shrinkStatePass B κ hκ ready)) s
+local notation "lay" => X.packingData.shrinkTermLayout B X.shrinkNumber X.packingWidth s
+
+private theorem placed_at (site : Site) (u : (old).Site) (h : site = (P).placement lay u) :
+ packedSiteEquiv site = (term).place ((I).site u) := by
+ change packedSiteEquiv site = packedSiteEquiv ((P).placement lay ((I).site.symm ((I).site u)))
+ rw [Equiv.symm_apply_apply, h]
+
+/-- The placed old halves that the reindexed shrinking kernel reads from the
+selected child assignment, in the packing coordinates of the demand rows. -/
+noncomputable def placedInput (site : Site)
+ (x : Placed (term).place X.network.Half (packedSiteEquiv site)) :
+ (P).PlacedHalf X.packingWidth lay site :=
+ fun u h ↦ X.packingHalfEquiv u (x ((I).site u) (placed_at X B κ hκ ready s site u h))
+
+/-- The native child batch supplies all and only the old sites at this
+resident's placement. A child packet is found by its genuine fiber index. -/
+theorem placedPackets_after_children (A : Arena) (nodes : X.network.Site → ℕ)
+ (r : TermParsers κ (term)) (hp : ∀ u z, r.halfBits u z = packed X u z) (site : Site)
+ (x : Placed (term).place X.network.Half (packedSiteEquiv site))
+ (before : Scratch w endAddr) (priv : Word w → Word w)
+ (fit : ∀ q ∈ r.childPackets nodes (packedSiteEquiv site) x, q.Fits A w endAddr)
+ (nd : ((r.childPackets nodes (packedSiteEquiv site) x).map Packet.node).Nodup)
+ (written : scratch endAddr priv =
+ writePackets A (r.childPackets nodes (packedSiteEquiv site) x) before) :
+ PlacedPackets X lay A nodes priv site (placedInput X B κ hκ ready s site x) endAddr := by
+ intro u h
+ let z := x ((I).site u) (placed_at X B κ hκ ready s site u h)
+ let q := Packet.mk (nodes ((I).site u)) (packed X _ z)
+ have present : q ∈ r.childPackets nodes (packedSiteEquiv site) x := by
+ let o := (r.order.children (packedSiteEquiv site)).entries
+ let t : (term).Preimage (packedSiteEquiv site) :=
+ ⟨(I).site u, placed_at X B κ hκ ready s site u h⟩
+ obtain ⟨j, hj⟩ := o.surjective t
+ apply List.mem_ofFn.mpr
+ refine ⟨j, ?_⟩
+ change Packet.mk (nodes (o j).val) (r.halfBits (o j).val (x (o j).val (o j).prop)) = q
+ rw [hj, hp]
+ simp only [placedInput, Equiv.symm_apply_apply]
+ exact ⟨fit q present, written ▸ writePackets_children A _ before fit nd q present⟩
+
+end Selected
+
+namespace Physical
+
+open CompressorRecords CompressorRecords.PhaseRecipe BurstRAM.PrivateRAM
+open CompressorRecords.PortRefresh.ArgumentAddress
+
+/-- Runtime addresses of the preceding descriptor layer and its old state
+columns, together with the private argument arena parameters. -/
+structure Header where
+ /-- First private address of the argument arena in which the old node's packet is stored. -/
+ arenaBase : Expr
+ /-- Word stride between private argument frames for consecutive node addresses. -/
+ arenaStride : Expr
+ /-- External DFS row base of the old layer supplying the child packets. -/
+ layerBase : Expr
+ /-- Distance in external words between adjacent site rows in the old DFS layer. -/
+ layerStride : Expr
+ /-- Head of the forward incidence column mapping an old outgoing slot to its actual target
+ slot. -/
+ actualOut : Expr
+ /-- Head of the inverse incidence column used to identify the outgoing arc of an incoming
+ slot. -/
+ actualIn : Expr
+ /-- Head of the numbered old-arc widths used to locate a slot inside a packed half-wire
+ argument. -/
+ width : Expr
+
+/-- Resolve the endpoint's own numerical port, using the forward incidence
+column when the operand is at the destination. -/
+def Header.port (H : Header) (arc : Expr) (dir : Bool) : Expr :=
+ if dir then .load (H.actualOut.add arc) else arc
+
+/-- Divide an oriented port by the degree to recover its site ordinal, then assemble the node
+address, arena, and width-prefix inputs for the field reader. -/
+def Header.input (H : Header) (degree : ℕ) (port : Expr) : Input :=
+ let ord := port.div (.lit degree)
+ ⟨H.arenaBase, H.arenaStride, H.layerBase.add (H.layerStride.mul ord),
+ ord, H.actualIn, H.width⟩
+
+/-- Compute the pointer using only the row's old arc ID, stage pointers and
+the fixed-degree prefix of actual widths. -/
+def Header.field (H : Header) (degree : ℕ) (arc : Expr) (dir : Bool) : Expr :=
+ let p := H.port arc dir
+ PortRefresh.ArgumentAddress.field degree (H.input degree p) dir (p.mod (.lit degree))
+
+variable (H : Header) (T : IncidenceDirectory w) (A : Arena)
+variable (layer stride : ℕ) (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+
+/-- The evaluated header supplies the designated arena start and stride, old layer start and
+pitch, and the actual outgoing, incoming, and width column heads. -/
+structure Header.Stored : Prop where
+ arenaBase : H.arenaBase.eval pub state mem = CursorRAM.encode w A.start
+ arenaStride : H.arenaStride.eval pub state mem = CursorRAM.encode w A.stride
+ layerBase : H.layerBase.eval pub state mem = CursorRAM.encode w layer
+ layerStride : H.layerStride.eval pub state mem = CursorRAM.encode w stride
+ actualOut : H.actualOut.eval pub state mem = T.actualOut
+ actualIn : H.actualIn.eval pub state mem = T.actualIn
+ width : H.width.eval pub state mem = T.width
+
+private theorem target_port (e : (old).Edge) :
+ (((I).site (position X e true)), slot X e true) =
+ X.slots.actualGraph.target ((I).edge e) := Prod.ext ((I).dst e) rfl
+
+theorem port_eq (stored : H.Stored T A layer stride pub state mem) (cols : T.ActualColumns X mem)
+ (e : (old).Edge) (arc : Expr)
+ (ha : arc.eval pub state mem = IncidenceDirectory.actualPort X ((I).edge e)) (dir : Bool) :
+ (H.port arc dir).eval pub state mem =
+ IncidenceDirectory.actualPort X ((I).site (position X e dir), slot X e dir) := by
+ cases dir with
+ | false => exact ha
+ | true =>
+ change mem (H.actualOut.eval pub state mem + arc.eval pub state mem).val = _
+ rw [stored.actualOut, ha]
+ exact (cols.actualOut ((I).edge e)).trans
+ (congrArg (IncidenceDirectory.actualPort X) (target_port X e).symm)
+
+private theorem unpack (x d : Word w) (hi lo : ℕ)
+ (h : x.val = hi * d.val + lo) (hl : lo < d.val) :
+ (BinaryOp.div.eval x d).val = hi ∧ (BinaryOp.mod.eval x d).val = lo := by
+ have q : x.val / d.val = hi := by
+ rw [h, Nat.mul_comm hi, Nat.mul_add_div (Nat.zero_lt_of_lt hl),
+ Nat.div_eq_of_lt hl, Nat.add_zero]
+ exact ⟨(Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)).trans q,
+ (Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt)).trans (h ▸ Nat.mul_add_mod_of_lt hl)⟩
+
+private theorem word_of_val {x : Word w} {n : ℕ} (h : x.val = n) : x = CursorRAM.encode w n := by
+ subst n
+ exact Fin.ext (Nat.mod_eq_of_lt x.isLt).symm
+
+/-- Evaluation of the physical expression yields the old half-wire pointer
+at the real descriptor address of this endpoint's child. -/
+theorem field_eq (stored : H.Stored T A layer stride pub state mem) (cols : T.ActualColumns X mem)
+ (capacity : Fintype.card X.Base * 2 ^ (packingLaneBits a g) * 2 ^ a ≤ 2 ^ w)
+ (degreeFits : 2 ^ a < 2 ^ w) (e : (old).Edge) (arc : Expr)
+ (ha : arc.eval pub state mem = IncidenceDirectory.actualPort X ((I).edge e)) (dir : Bool) :
+ (H.field (2 ^ a) arc dir).eval pub state mem = CursorRAM.encode w
+ (address X A (fun u ↦ layer + stride * siteOrdinal X u) e dir) := by
+ let u := (I).site (position X e dir)
+ let j := slot X e dir
+ let p := H.port arc dir
+ let E := H.input (2 ^ a) p
+ let n := siteOrdinal X u
+ have word := port_eq X H T A layer stride pub state mem stored cols e arc ha dir
+ rw [IncidenceDirectory.actualPort_number] at word
+ have idFit := (IncidenceDirectory.actualOrder X (u,j)).isLt.trans_le capacity
+ have val : (p.eval pub state mem).val = n * 2 ^ a + j.val := by
+ rw [show p.eval pub state mem = _ from word]
+ exact (Nat.mod_eq_of_lt idFit).trans (IncidenceDirectory.actualOrder_val X (u,j))
+ have dval : ((CursorRAM.encode w (2 ^ a))).val = 2 ^ a := Nat.mod_eq_of_lt degreeFits
+ have split := unpack (p.eval pub state mem) (CursorRAM.encode w (2 ^ a)) n j.val
+ (by rw [dval]; exact val) (by rw [dval]; exact j.isLt)
+ have quotient : (p.div (.lit (2 ^ a))).eval pub state mem = CursorRAM.encode w n :=
+ word_of_val split.1
+ have remainder : (p.mod (.lit (2 ^ a))).eval pub state mem = CursorRAM.encode w j.val :=
+ word_of_val split.2
+ have rep : Represents pub state mem E X u T A (layer + stride * n) := {
+ arena := stored.arenaBase
+ stride := stored.arenaStride
+ node := by
+ change H.layerBase.eval pub state mem +
+ H.layerStride.eval pub state mem * (p.div (.lit (2 ^ a))).eval pub state mem = _
+ rw [stored.layerBase, stored.layerStride, quotient]
+ apply Fin.ext
+ change (_ + _ * _ : Word w).val = (layer + stride * n) % _
+ simp only [CursorRAM.encode, Fin.val_add, Fin.val_mul, Fin.val_ofNat, Nat.mod_add_mod,
+ Nat.add_mod_mod, Nat.mod_mul_mod, Nat.mul_mod_mod]
+ site := quotient
+ actualIn := stored.actualIn
+ width := stored.width }
+ exact eval_field rep cols dir _ j degreeFits remainder
+
+/-- The physical layer ordinal here is the one used by the native child
+scan when it assigned the argument packet. -/
+theorem childNode_eq (older cap : ℕ) (u : X.network.Site) :
+ ChildScan.childNode X older cap u = older + (cap + 2) * siteOrdinal X u := by
+ change older + (cap + 2) * ((bitWordFinEquiv _ u.2).val + 2 ^ _ * (X.baseIndex u.1).val) =
+ older + (cap + 2) * ((X.baseIndex u.1).val * 2 ^ _ + (bitWordFinEquiv _ u.2).val)
+ ring
+
+end Physical
+
+end PairSimulation.ShrinkOldHalves
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkOldTableTransfer.lean b/lean/OAI/Computability/VPVNP/PairShrinkOldTableTransfer.lean
new file mode 100644
index 0000000000..d769ec3c9a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkOldTableTransfer.lean
@@ -0,0 +1,165 @@
+import OAI.Computability.VPVNP.PairShrinkCallHeader
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-!
+# Retaining the old tables used by shrink map calls
+
+An old level supplies three incidence columns, four preliminary placement
+columns and the classifier's lists and ranks. Agreement on these allocated
+regions transports all typed readbacks into the online scheduler's memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallHeader
+
+open Compression Compression.PackingData CompressorRecords BurstRAM BundleLists
+open ShrinkRankSpace
+open private rowAt_val countAt_val from OAI.Computability.VPVNP.CompressorRecordPreimageScan
+
+variable {a g w : ℕ} {X : State a (packingLaneBits a g)}
+variable {mem out : Memory w} {origin : ℕ} {T : IncidenceDirectory w}
+variable {D : ℕ → Prop}
+
+local notation "Z" => ShrinkInput.plan X origin
+local notation "q" => Shape.collectBank (ShrinkInput.plan X origin) w
+local notation "pre" => ShrinkInput.placementBank X T origin
+local notation "arcs" => BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex
+local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex
+local notation "place" => wordOwner (w := w) X.packingData arcs sites
+local notation "A" => IncidenceDirectory.slotCount X
+local notation "S" => Fintype.card X.Base * 2 ^ packingLaneBits a g
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+private theorem row_capacity (geo : Geometry (w := w) X origin) (u : Word w) (hu : u < q 2) :
+ (preimagePrefix place u A).length ≤ (q 4).val := by
+ let j : Fin ((Z).B + (Z).B) := ⟨u.val, geo.nrows ▸ hu⟩
+ obtain ⟨b, eqn⟩ := (bucketIndex sites (d := 2 ^ a)).surjective j
+ have eu : Fin.ofNat (2 ^ w) (bucketIndex sites b).val = u := by
+ rw [eqn]
+ exact Fin.ext (Nat.mod_eq_of_lt u.isLt)
+ rw [← eu]
+ change (arcList X.packingData arcs sites b).length ≤ _
+ rw [arcList_length X.packingData arcs sites (State.two_le_packingColors a)
+ geo.arcFit geo.bucketFit]
+ cases b with
+ | inl b => exact (Nat.div_le_div_right (by omega :
+ 2 ^ (Shrink.colors a) * 2 ^ a ≤ 3 * (2 ^ (Shrink.colors a) * 2 ^ a))).trans geo.cap
+ | inr b => exact geo.cap
+
+private theorem column_agree {base i : Word w} {length : ℕ}
+ (fit : base.val + length ≤ 2 ^ w) (index : i.val < length)
+ (agree : SourceTransport.Agree D mem out)
+ (cells : ∀ z, base.val ≤ z → z < base.val + length → D z) :
+ out (base + i).val = mem (base + i).val := by
+ apply (agree _ _).symm
+ rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ exact cells _ (Nat.le_add_right ..) (Nat.add_lt_add_left index _)
+
+/-- Carry the old level's typed port, rank, list and placement tables to any
+memory which agrees on their physical regions. -/
+theorem OldTables.transfer (h : OldTables X mem T origin)
+ (room : (Z).stop < 2 ^ w)
+ (oldFit : ∀ c : Fin 3, (T.column (c.natAdd 3)).val + A ≤ 2 ^ w)
+ (agree : SourceTransport.Agree D mem out)
+ (columns : ∀ (c : Fin 3) z, (T.column (c.natAdd 3)).val ≤ z →
+ z < (T.column (c.natAdd 3)).val + A → D z)
+ (classify : ∀ z, (Z).owner ≤ z → z < (Z).stop → D z)
+ (preliminary : ∀ z, ShrinkInput.placementBase X origin ≤ z →
+ z < ShrinkInput.rankBase X origin → D z) :
+ OldTables X out T origin := by
+ have geo := geometry X T origin room
+ have v := (Z).values T pre Fintype.card_pos room
+ have own : (q 1).val = (Z).owner := v.owner
+ have ownersCounts := geo.regions.ownersBeforeCounts
+ have countsRows := geo.regions.countsBeforeRows
+ have rowTop : (q 5).val + (q 2).val * (q 4).val = (Z).gathered := by
+ rw [v.ids, v.buckets, v.stride]
+ rfl
+ have gatheredRank : (Z).gathered ≤ (Z).ranks := Nat.le_add_right ..
+ have rankStop : (Z).ranks + A = (Z).stop := rfl
+ have ownerCells (i : Word w) (hi : i.val < A) :
+ out (q 1 + i).val = mem (q 1 + i).val := by
+ have size : (q 0).val = A := v.count
+ refine column_agree (length := A) (by omega) hi agree ?_
+ intro z lo lt
+ exact classify z (own ▸ lo) (by omega)
+ have column (c : Fin 3) (i : Word w) (hi : i.val < A) :
+ out (T.column (c.natAdd 3) + i).val = mem (T.column (c.natAdd 3) + i).val :=
+ column_agree (oldFit c) hi agree (columns c)
+ constructor
+ · constructor
+ · intro i hi
+ exact (ownerCells i ((show i.val < (q 0).val from hi).trans_eq v.count)).trans
+ (h.preimages.owners i hi)
+ · intro u hu
+ obtain ⟨count, entries⟩ := h.preimages.rows u hu
+ constructor
+ · rw [(agree _ _).symm]
+ · exact count
+ · rw [countAt_val geo.regions hu]
+ have index : u.val < (q 2).val := hu
+ apply classify <;> omega
+ · intro i
+ rw [(agree _ _).symm]
+ · exact entries i
+ · rw [rowAt_val geo.regions hu]
+ have hi := i.isLt.trans_le (row_capacity geo u hu)
+ have next := Nat.mul_le_mul_right (q 4).val (show u.val + 1 ≤ (q 2).val from hu)
+ rw [Nat.succ_mul] at next
+ apply classify <;> omega
+ · have index (e : BundleKeys.OldArc X.Base a g) :
+ (BundleWidthScatter.arcWord (w := w) arcs e).val < A :=
+ (Nat.mod_le ..).trans_lt (arcs e).isLt
+ constructor
+ · intro e
+ exact (ownerCells _ (index e)).trans (h.ranked.owners e)
+ · intro e
+ apply Eq.trans _ (h.ranked.ranks e)
+ refine column_agree (base := Fin.ofNat (2 ^ w) (Z).ranks) (length := A)
+ (by rw [v.ranks, rankStop]; exact room.le) (index e) agree ?_
+ intro z lo hi
+ rw [v.ranks] at lo hi
+ exact classify z (by omega) (rankStop ▸ hi)
+ · intro e
+ exact (congrArg Fin.val (column 2 _ (index e))).trans (h.ranked.widths e)
+ · constructor
+ · intro e
+ exact (column 0 _ (IncidenceDirectory.actualPort_lt X e)).trans (h.incidence.actualOut e)
+ · intro e
+ exact (column 1 _ (IncidenceDirectory.actualPort_lt X e)).trans (h.incidence.actualIn e)
+ · intro e
+ exact (column 2 _ (IncidenceDirectory.actualPort_lt X e)).trans (h.incidence.width e)
+ · constructor
+ intro x P i
+ have hi : i.val < S := by
+ change (Shrink.oldNumber X.baseIndex x) % (2 ^ w) < _
+ rw [← Shrink.oldIndex_val]
+ exact (Nat.mod_le ..).trans_lt (Fin.isLt _)
+ have rankRoom : ShrinkInput.rankBase X origin < 2 ^ w :=
+ (ShrinkInput.range_bounds X origin).2.2.1.trans_lt room
+ have keep (c : Fin 4) : out (ShrinkRAM.outAddr pre c i) = mem (ShrinkRAM.outAddr pre c i) := by
+ have start : (pre (c.natAdd 10)).val = ShrinkInput.placementBase X origin + c.val * S :=
+ ShrinkPlacement.starts X T _ _ _ false rankRoom c
+ have stop : (pre (c.natAdd 10)).val + S ≤ ShrinkInput.rankBase X origin := by
+ rw [start]
+ change _ ≤ ShrinkInput.placementBase X origin + 4 * S
+ have hc := Nat.mul_le_mul_right S c.isLt
+ rw [Nat.succ_mul] at hc
+ omega
+ apply column_agree (length := S) (stop.trans rankRoom.le) hi agree
+ intro z lo lt
+ apply preliminary z _ (lt.trans_le stop)
+ rw [start] at lo
+ omega
+ rw [keep 0, keep 1, keep 2, keep 3]
+ exact h.thickness.atSite x
+
+end PairSimulation.ShrinkCallHeader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkOrdinalSources.lean b/lean/OAI/Computability/VPVNP/PairShrinkOrdinalSources.lean
new file mode 100644
index 0000000000..6e023cbecd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkOrdinalSources.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PairShrinkSiteSources
+import OAI.Computability.VPVNP.PairShrinkCanonicalSite
+import OAI.Computability.VPVNP.PairShrinkRoleMapActions
+
+/-!
+# The published source at a shrinking row ordinal
+
+The route's public ordinal and its motif-party pair agree with the packed
+source directory. The old and successor tables can therefore be read with
+the state word computed by that route.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots
+open ShrinkMapImage.Registers MapResidentRows ShrinkRole ShrinkRole.MapWitness
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {i : Fin S.steps}
+variable {g w n : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+variable {sel : SelectedScore.Selection B X} {v : Site X}
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+variable (site : CanonicalSite B i X sel v w n (Fintype.card B.Entry))
+variable (ord : B.Entry → Fin (Fintype.card B.Entry))
+variable (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "J" => jobs B i X sel site.workspace site.positions site.blocks site.cur site.bounds
+ n site.rowEnd site.older site.later v old parent
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "L" => BlockProgram.layout B site.workspace.val site.positions site.blocks
+local notation "here" => Nat.cast (R := Word w) (levelStart L site.cur)
+local notation "cut" => tableBase L site.cur (0 : Fin 6)
+local notation "node" => site.later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal (X.shrinkNext B.shrink (S.shrink i) sel) v
+
+/-- The public row ID and the dense term table use the same motif numbering. -/
+theorem row_ordinal (j : Fin (order (a := a i) (g := g) X side v).length) :
+ rowOrdinalWord (w := w) (a := a i) (g := g) X side v j =
+ ((ShrinkMotifOrder.stateNumber (a := a i) (g := g) X
+ (rowEquiv (a := a i) (g := g) X side v j).1.1).val : Word w) := by
+ have pair : (rowEquiv X side v j).1 = MapResidentRows.entry X side v j := rfl
+ rw [pair]
+ exact congrArg (fun k : ℕ ↦ (k : Word w)) (ShrinkMotifOrder.entries_ordinal X _)
+
+theorem row_pair (j : Fin (order (a := a i) (g := g) X side v).length) :
+ (rowEquiv (a := a i) (g := g) X side v j).1 = MapResidentRows.entry X side v j := rfl
+
+local notation "O" => ShrinkCallABI.operands (slotDegree S)
+local notation "T" => packedIncidence L w site.cur (DemandRAM.oldCount X)
+local notation "shape" => levelShape (b := b i) X
+local notation "U" => packedIncidence L w (site.cur + 1) (actualCount shape)
+local notation "records" => ShrinkInput.termHead (w := w) X cut
+local notation "slots" => ShrinkOutput.heads shape (SelectedArena.roleBase X records 10)
+ (tableBase L site.cur (3 : Fin 6))
+local notation "absolute" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X cut) w
+
+/-- Read the old and successor tables with the public words of this particular
+resident and the motif ordinal loaded by the route. -/
+theorem source_at (q : X.packingData.ResidentMap side v) (H st : Word w)
+ (levelEq : site.level = here)
+ (ordEq : st = ((ShrinkMotifOrder.stateNumber X q.1.1).val : Word w))
+ (src : RowSources B i X sel site.workspace site.positions site.blocks site.cur site.bounds
+ n site.rowEnd site.older site.later v old parent site.mem H q) :
+ let pp := pub site.level ((J q).node : Word w) regions n
+ (J q).OldPublished O pp st site.mem site.level T cut ∧
+ (J q).SupplyPublished O ShrinkCallABI.node pp st site.mem slots absolute U site.later
+ (B.recordLimit + 2) := by
+ subst st
+ dsimp only
+ rw [levelEq, node_eq]
+ exact ⟨src.old, src.next⟩
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPackedCapacity.lean b/lean/OAI/Computability/VPVNP/PairShrinkPackedCapacity.lean
new file mode 100644
index 0000000000..5e8f6054c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPackedCapacity.lean
@@ -0,0 +1,221 @@
+import OAI.Computability.VPVNP.PairShrinkSelectedCapacity
+import OAI.Computability.VPVNP.PairTerminalPackedBudget
+import OAI.Computability.VPVNP.PairShrinkPackedRows
+
+/-!
+# Shrinking map capacity at the packed directory's physical row end
+
+The compressor publishes exactly its live calendar rows. The first DFS row
+follows this tight directory. Its end fixes the terminal argument frames,
+histogram, cache and stacks, and thus the natural base of the shrinking
+worker's private maps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallCapacity
+
+open BurstRAM Compression CursorBounds CursorNetwork CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles Filter ShrinkCallFields Compression.ShrinkMotif
+open private reindex_bounds from OAI.Computability.VPVNP.PairShrinkSelectedCapacity
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k}
+variable (B : S.Templates) (u : PairExponents B.growthConstant)
+variable (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hs : PolynomiallyBounded start)
+
+local notation "P" => initialPositions b
+local notation "T" => blockCount (u.θ : ℝ)
+local notation "degree" => slotDegree S
+local notation "ports" => Fintype.card LeafStartup.ScalarPort
+local notation "labelCount" => Fintype.card B.Entry
+local notation "work" => NativeFrame.postStackLimit degree b start labelCount ports
+local notation "extra" => fun n ↦ extent (P n * degree) n
+
+include hb hs in
+/-- The runtime cache word and live length produce the exact private map
+base and square stride. All map storage then ends before the word modulus. -/
+theorem eventually_packed_handoff :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : T n * S.laneBits ≤ lanes) (R : Type*) [CommRing R] (f : B.Entry → R)
+ (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let L := BlockProgram.layout B (start n) (P n) (T n)
+ ∀ z : (B.execute f hf (T n) hT X).Choices,
+ let rows := words B.recordLimit (selectedLayers B f hf (T n) hT X z)
+ let G := NativeFrame.regions degree n (endAddress L) rows labelCount
+ let w := wordBits b n
+ mapBase G ports n + extra n < 2 ^ w ∧
+ (VertexLevel.hiddenBaseWord (G.cacheBase : Word w) (n : Word w)).val = mapBase G ports n ∧
+ ((n : Word w) * (n : Word w)).val = n * n := by
+ have hsize := extent_bounded ((CursorRAM.bounded_positions b).mul (.const degree))
+ filter_upwards [TerminalLayout.eventually_packedFit B u b hb hs ports extra hsize]
+ with n room
+ intro base lanes labels hD hT R _ f hf X L z rows G w
+ have bound : mapBase G ports n + extra n < 2 ^ w := (room labels hD hT R f hf z).2.2.2.1
+ exact ⟨bound, handoff_words G bound⟩
+
+/-- Read the two input words of the map handoff from the terminal geometry
+written for the packed directory and recover the histogram pointer as well. -/
+theorem packed_private_words {w n : ℕ} (positions blocks rows pitch baseRadix laneRadix : ℕ)
+ (mem : Memory w) (header role span : Word w) (pub : Fin 11 → Word w)
+ (priv : Word w → Word w) (geometry : Word w)
+ (live : (pub 6).val = n) (labels : (pub 9).val = labelCount) :
+ let L := BlockProgram.layout B (start n) positions blocks
+ let G := NativeFrame.regions degree n (endAddress L) rows labelCount
+ NativeFrame.Readback mem header (endAddress L) rows pitch baseRadix laneRadix span →
+ endAddress L + rows < 2 ^ w →
+ mapBase G ports n + extent (positions * degree) n < 2 ^ w →
+ (∀ i : Fin 12, priv (geometry + (i.val : Word w)) =
+ NativeFrame.fields degree pub header role mem i) →
+ (VertexLevel.hiddenBaseWord (priv (geometry + 8)) (priv (geometry + 9))).val =
+ mapBase G ports n ∧
+ (priv (geometry + 9) * priv (geometry + 9)).val = n * n ∧
+ priv (geometry + 11) = (G.histBase : Word w) := by
+ intro L G read rowFit room fields
+ have eqn := read.regions_eq degree pub n labelCount live labels rowFit
+ have hc := fields 8
+ change priv (geometry + 8) = ((NativeFrame.fromHeader degree pub header mem).cacheBase : Word w)
+ at hc
+ rw [eqn] at hc
+ have hn : priv (geometry + 9) = (n : Word w) := (fields 9).trans
+ (live ▸ (Fin.cast_val_eq_self _).symm)
+ have hh := fields 11
+ change priv (geometry + 11) = ((NativeFrame.fromHeader degree pub header mem).histBase : Word w)
+ at hh
+ rw [eqn] at hh
+ rw [hc, hn]
+ obtain ⟨base, stride⟩ := handoff_words G room
+ exact ⟨base, stride, hh⟩
+
+include hb hs in
+/-- The packed first-row address is at most the rectangular allocation end.
+Both layouts use the same selected DFS words, so the previously bounded
+histogram also bounds the actual post-stack start. -/
+theorem eventually_packed_workBase :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : T n * S.laneBits ≤ lanes) (R : Type*) [CommRing R] (f : B.Entry → R)
+ (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let L := BlockProgram.layout B (start n) (P n) (T n)
+ ∀ z : (B.execute f hf (T n) hT X).Choices,
+ let rows := words B.recordLimit (selectedLayers B f hf (T n) hT X z)
+ let G := NativeFrame.regions degree n (endAddress L) rows labelCount
+ mapBase G ports n ≤ work n := by
+ filter_upwards [NativeFrame.eventually_selected_histBase B u (BlockProgram.allocationShape B)
+ b hb hs] with n bounds
+ intro base lanes labels hD hT R _ f hf X L z rows G
+ let upper := cursorLayout (BlockProgram.allocationShape B) b S.steps u.θ (start n) n
+ have end_le : endAddress L ≤ endAddress upper := BlockProgram.allocation_end B _ _ _
+ apply NativeFrame.postStack_le
+ have hist := bounds labels hD hT R f hf z degree labelCount
+ refine le_trans ?_ hist
+ change n + (endAddress L + rows) * (2 * degree * n + 1) ≤
+ n + (endAddress upper + rows) * (2 * degree * n + 1)
+ exact Nat.add_le_add_left (Nat.mul_le_mul_right _ (Nat.add_le_add_right end_le rows)) n
+
+open Classical in
+/-- Fitted maps indexed by the transported input of a selected level. -/
+structure SelectedAt {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f}
+ (v : SelectedLevel B f hf) (G : LeafArena.Regions) (b n limit older pitch : ℕ) : Prop where
+ fits : ∀ {g : ℕ} (eqn : v.inputLanes = packingLaneBits v.inputExponent g),
+ let X : State v.inputExponent (packingLaneBits v.inputExponent g) := eqn ▸ v.input
+ ∀ (sel : X.ShrinkSelection B.shrink) (m : X.packingData.Motif),
+ SelectedFits X B sel m G b n limit older pitch
+
+open Classical in
+include hb hs in
+/-- All child addresses and the scratch base are the ones stored for this
+selected level of the packed calendar. The capacity limit is the exclusive
+end of the dedicated post-stack reserve on this very branch. -/
+theorem eventually_packed_selected :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : T n * S.laneBits ≤ lanes) (R : Type*) [CommRing R] (f : B.Entry → R)
+ (hf : B.IsSolution f),
+ let initial := pairInput S labels hD
+ let firstRow := endAddress (BlockProgram.layout B (start n) (P n) (T n))
+ ∀ z : (B.execute f hf (T n) hT initial).Choices,
+ let vs := executeLevels B f hf (T n) hT initial z
+ let tags := selected B f hf (T n) hT initial z
+ let rows := words B.recordLimit (selectedLayers B f hf (T n) hT initial z)
+ let G := NativeFrame.regions degree n firstRow rows labelCount
+ let limit := mapBase G ports n + extra n
+ ∀ i : Fin vs.length, SelectedAt B vs[i] G b n limit
+ (layerBase B.recordLimit firstRow tags i.val) (B.recordLimit + 2) := by
+ have hb₁ : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ have capacity := eventually_capacity B.shrink b hb₁ degree
+ (NativeFrame.postStackLimit_bounded degree b hs labelCount ports)
+ filter_upwards [capacity, eventually_levels B u b hb (fieldFactor B.shrink + 1),
+ eventually_packed_workBase B u b hb hs, eventually_packed_handoff B u b hb hs,
+ eventually_ge_atTop 1] with n cap levels bases handoff hn
+ intro base lanes labels hD hT R _ f hf initial firstRow z vs tags rows G limit i
+ let v := vs[i]
+ let older := layerBase B.recordLimit firstRow tags i.val
+ constructor
+ intro g eqn X sel m
+ obtain ⟨hp, hw⟩ := reindex_bounds v.input eqn
+ have live := levels labels hD hT R f hf z v (List.getElem_mem i.isLt)
+ have hWidth : (fieldFactor B.shrink + 1) * (X.maxWireWidth + 1) ≤ n := hw ▸ live.2
+ have hPos : X.positions ≤ P n := hp ▸ live.1
+ have small : limit ≤ work n + extra n :=
+ Nat.add_le_add_right (bases labels hD hT R f hf z) _
+ have actual : MapWorkspace.Capacity B.shrink (wordBits b n) n limit :=
+ ⟨cap.selectorBits, cap.demandBits, cap.payloadBits,
+ (handoff labels hD hT R f hf z).1, fun a ha ↦ cap.fields a (ha.trans small)⟩
+ have hist : G.histBase + labelCount ≤ mapBase G ports n := histogram_before G ports n
+ have hx : X.maxWireWidth ≤ n := by rw [Nat.add_mul, Nat.one_mul] at hWidth; omega
+ have below (site : X.network.Site) (zhalf : X.network.Half site) :
+ G.arguments.base (older + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal X site) +
+ (NodeArguments.packed X site zhalf).length ≤ mapBase G ports n := by
+ have row := ShrinkPackedRows.packed_layer_address B f hf (T n) hT initial z
+ (start n) i eqn site
+ rw [show initial.positions = P n from pairInput_positions S labels hD] at row
+ have len : (NodeArguments.packed X site zhalf).length ≤ G.arguments.stride :=
+ (NodeArguments.packed_length_le X site zhalf).trans
+ ((Nat.mul_le_mul (Nat.mul_le_mul_left 2 v.oldDegree_le) hx).trans (Nat.le_succ _))
+ exact (Nat.add_le_add_left len _).trans ((G.node_before row).trans
+ ((Nat.le_add_right _ _).trans hist))
+ simpa only [SelectedFits, pow_two, limit] using fits X B.shrink sel m hn hist le_rfl
+ (motif_count X hPos v.oldDegree_le) hWidth actual G.arguments older (B.recordLimit + 2) below
+
+open Classical in
+include hb hs in
+/-- At a concrete native shrinking occurrence the selected motif supplies
+its admitted term and the old layer base and pitch are the published ones. -/
+theorem eventually_packed_occurrence :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : T n * S.laneBits ≤ lanes) (R : Type*) [CommRing R] (f : B.Entry → R)
+ (hf : B.IsSolution f),
+ let initial := pairInput S labels hD
+ let firstRow := endAddress (BlockProgram.layout B (start n) (P n) (T n))
+ ∀ z : (B.execute f hf (T n) hT initial).Choices,
+ let vs := executeLevels B f hf (T n) hT initial z
+ let tags := selected B f hf (T n) hT initial z
+ let rows := words B.recordLimit (selectedLayers B f hf (T n) hT initial z)
+ let G := NativeFrame.regions degree n firstRow rows labelCount
+ ∀ (i : Fin vs.length) (j : Fin S.steps) {g : ℕ}
+ (X : State (S.degreeExponent j.castSucc)
+ (packingLaneBits (S.degreeExponent j.castSucc) g))
+ (sel : SelectedScore.Selection B X) (bits : List Bool),
+ vs[i] = shrinkLevel B f hf j X sel bits →
+ ∀ m : X.packingData.Motif, SelectedFits X B sel m G b n (mapBase G ports n + extra n)
+ (layerBase B.recordLimit firstRow tags i.val) (B.recordLimit + 2) := by
+ filter_upwards [eventually_packed_selected B u b hb hs] with n fits
+ intro base lanes labels hD hT R _ f hf initial firstRow z vs tags rows G i j g X sel bits atPass m
+ have h := fits labels hD hT R f hf z i
+ change SelectedAt B vs[i] G b n _ _ _ at h
+ rw [atPass] at h
+ exact h.fits rfl sel m
+
+end PairSimulation.ShrinkCallCapacity
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPackedPackets.lean b/lean/OAI/Computability/VPVNP/PairShrinkPackedPackets.lean
new file mode 100644
index 0000000000..486bbaaeba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPackedPackets.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalPacketBounds
+import OAI.Computability.VPVNP.PairShrinkPacketData
+import OAI.Computability.VPVNP.PairShrinkPackedCapacity
+import OAI.Computability.VPVNP.PairShrinkPackedParent
+
+/-!
+# Fitted packet gathers on every selected packed shrinking level
+
+The old and new row addresses come from the selected level and its successor.
+The terminal arguments occupy a separate private interval before the map
+scratch. Only the child and parent bit readbacks depend on the private memory
+at entry to an individual resident job.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCanonicalJob
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords NodeArguments
+open DescriptorSpace ShrinkBlockInputs ShrinkSlots ShrinkCallCapacity ShrinkCallFields
+open CursorNetwork CursorBounds TraversalRoles TraversalRows Filter MotifConversion
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+
+section Job
+
+variable (j : Fin S.steps) {g w : ℕ} (X : State (a j) (packingLaneBits (a j) g))
+variable (sel : SelectedScore.Selection B X) (m : X.packingData.Motif) (party : Fin 6)
+/-- The packet structure uses the selected layout's equality on the old sites. -/
+private noncomputable local instance packedJobBase : DecidableEq X.Base := Classical.decEq _
+variable (J : ShrinkPartyNative.Job X B.shrink (S.shrink j) sel m party w)
+local notation "Y" => X.shrinkNext B.shrink (S.shrink j) sel
+local notation "owner" => X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m party
+local notation "packet" => Packet.mk J.node (packed Y owner J.parent)
+local notation "demand" => X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m
+
+/-- Concrete address fits and the memory-dependent packet constructor needed
+by the selected resident map stage. -/
+structure PacketSpace (n limit : ℕ) : Prop where
+ fields : Fits (w := w) (n := n) (limit := limit) (u := repetitions B.shrink demand)
+ (t := Fintype.card B.Entry) B.shrink demand (sel m).val J.scratch
+ (ShrinkMotifOrder.stateNumber X m).val (ShrinkCallHeader.cdBase X m J.arena J.older J.pitch)
+ oldEnd : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ J.scratch.staging
+ parentFit : (packet).Fits J.arena w n
+ parentEnd : J.arena.base J.node + (packet).bits.length ≤ J.scratch.staging
+ packets : ∀ priv, J.ChildWords priv n → (packet).Stored J.arena (DFS.scratch n priv) →
+ J.Packets n priv
+
+end Job
+
+variable (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+variable {start : ℕ → ℕ} (hs : PolynomiallyBounded start)
+local notation "P" => initialPositions b
+local notation "T" => blockCount (u.θ : ℝ)
+local notation "degree" => slotDegree S
+local notation "ports" => Fintype.card LeafStartup.ScalarPort
+
+open Classical in
+include hb hs in
+/-- The packet bounds and constructor use the job's real old and new layer
+bases and the worker's actual post-stack reserve. -/
+theorem eventually_packets :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : T n * S.laneBits ≤ lanes) (R : Type*) [CommRing R] (f : B.Entry → R)
+ (hf : B.IsSolution f),
+ let initial := pairInput S labels hD
+ let firstRow := endAddress (BlockProgram.layout B (start n) (P n) (T n))
+ ∀ z : (B.execute f hf (T n) hT initial).Choices,
+ let vs := executeLevels B f hf (T n) hT initial z
+ let tags := selected B f hf (T n) hT initial z
+ let rows := words B.recordLimit (selectedLayers B f hf (T n) hT initial z)
+ let G := NativeFrame.regions degree n firstRow rows (Fintype.card B.Entry)
+ let limit := mapBase G ports n + extent (P n * degree) n
+ let w := wordBits b n
+ ∀ (i : Fin vs.length) (j : Fin S.steps) {g : ℕ}
+ (X : State (a j) (packingLaneBits (a j) g)) (sel : SelectedScore.Selection B X)
+ (bits : List Bool), vs[i] = shrinkLevel B f hf j X sel bits →
+ ∀ (m : X.packingData.Motif) (party : Fin 6) (startWord : Word w)
+ (sp : ShrinkResidentSources.Bounds B j X startWord (P n) (T n) i.val)
+ (old : ShrinkCallDemandCells.Old X (selectedLayout X B.shrink sel) m party)
+ (parent : (X.shrinkNext B.shrink (S.shrink j) sel).network.Half
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m party)),
+ startWord.val = start n →
+ let J := job B j X (S.shrink j) sel m party startWord (P n) (T n) i.val sp
+ n (firstRow + rows) (layerBase B.recordLimit firstRow tags i.val)
+ (layerBase B.recordLimit firstRow tags (i.val + 1)) old parent
+ PacketSpace B j X sel m party J n limit := by
+ filter_upwards [eventually_packed_occurrence B u b hb hs,
+ ShrinkPackedRows.eventually_parent_width B u b hb] with n fits wide
+ intro base lanes labels hD hT R _ f hf initial firstRow z vs tags rows G limit w i j g
+ X sel bits atPass m party startWord sp old parent _ J
+ let older := layerBase B.recordLimit firstRow tags i.val
+ let later := layerBase B.recordLimit firstRow tags (i.val + 1)
+ have size := wide labels hD hT R f hf z i j X sel bits atPass
+ have fields := fits labels hD hT R f hf z i j X sel bits atPass m
+ change SelectedFits X B sel m G b n limit older (B.recordLimit + 2) at fields
+ have native : Fits (w := w) (n := n) (limit := limit)
+ (u := repetitions B.shrink (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m))
+ (t := Fintype.card B.Entry) B.shrink
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m) (sel m).val J.scratch
+ (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallHeader.cdBase X m J.arena J.older J.pitch) := by
+ change Fits (w := w) (n := n) (limit := limit) (t := Fintype.card B.Entry)
+ (u := repetitions B.shrink (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m))
+ B.shrink _ (sel m).val (ShrinkCallHeader.scratch X (mapBase G ports n) (n ^ 2) G.histBase)
+ _ (ShrinkCallHeader.cdBase X m G.arguments older (B.recordLimit + 2))
+ rw [pow_two]
+ exact fields
+ have fit : mapBase G ports n < 2 ^ w := (Nat.le_add_right ..).trans_lt native.capacity.room
+ have same : initial.positions = P n := pairInput_positions S labels hD
+ have bounds := packet_bounds (X.shrinkNext B.shrink (S.shrink j) sel)
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m party) parent
+ J.nodes J.node degree (firstRow + rows) (Fintype.card B.Entry) J.scratch le_rfl (fun v ↦ by
+ have row := ShrinkPackedRows.packed_shrink_address B f hf (T n) hT initial z
+ (start n) i j X sel bits atPass v
+ rw [same] at row
+ exact row) (by
+ have row := ShrinkPackedRows.packed_parent_address B f hf (T n) hT initial z
+ (start n) i j X sel bits atPass
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m party)
+ rw [same] at row
+ exact row) size.2 size.1 fit rfl
+ refine ⟨native, bounds.1, bounds.2.1, bounds.2.2, ?_⟩
+ intro priv children stored
+ exact J.packets_of children bounds.1 bounds.2.1 stored bounds.2.2 native
+
+end PairSimulation.ShrinkCanonicalJob
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPackedParent.lean b/lean/OAI/Computability/VPVNP/PairShrinkPackedParent.lean
new file mode 100644
index 0000000000..583b7b5224
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPackedParent.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.PairShrinkPackedRows
+
+/-!
+# The output packet of a selected shrink in the packed terminal arena
+
+The output sites of a pass occupy its successor layer, including when that
+layer is terminal. Their slot widths are the subdivided supply widths of the
+admitted motif terms or the zero widths on cyclic padding arcs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPackedRows
+
+open BurstRAM Compression CompressorRecords CursorBounds CursorNetwork DescriptorSpace Filter
+open TraversalRows TraversalRoles MotifConversion ShrinkMotif
+
+section Rows
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+variable (workspace : ℕ) (cur : Fin (executeLevels B f hf T hT X z).length)
+variable (j : Fin S.steps) {g : ℕ}
+variable (Z : State (S.degreeExponent j.castSucc) (packingLaneBits (S.degreeExponent j.castSucc) g))
+variable (sel : SelectedScore.Selection B Z) (bits : List Bool)
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => selected B f hf T hT X z
+local notation "rows" => selectedLayers B f hf T hT X z
+local notation "Y" => Z.shrinkNext B.shrink (S.shrink j) sel
+local notation "firstRow" => endAddress (BlockProgram.layout B workspace X.positions T)
+
+/-- Each output site's argument address is in the selected row reservation,
+at the prefix immediately after the input layer of this shrink. -/
+theorem packed_parent_address (occurrence : passes[cur] = shrinkLevel B f hf j Z sel bits)
+ (site : (Y).network.Site) :
+ layerBase B.recordLimit firstRow tags (cur.val + 1) +
+ (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal (Y) site <
+ firstRow + words B.recordLimit rows := by
+ have hi : cur.val + 1 < (tags).length := by
+ simp only [selected, List.length_cons, List.length_map]
+ exact Nat.succ_lt_succ cur.isLt
+ let current := (tags)[cur.val + 1].layer
+ let before := ((tags).take (cur.val + 1)).map TaggedLayer.layer
+ let later := ((tags).drop (cur.val + 1 + 1)).map TaggedLayer.layer
+ have count : current.count = (Y).positions := by
+ simp only [current, selected, List.getElem_cons_succ, List.getElem_map, levelLayer_count]
+ rw [show passes[cur.val] = shrinkLevel B f hf j Z sel bits from occurrence]
+ rfl
+ have split := List.take_append_drop (cur.val + 1 + 1) (tags)
+ rw [List.take_succ_eq_append_getElem hi, List.append_assoc, List.singleton_append] at split
+ have exactRows : before ++ current :: later = rows := by
+ simpa only [before, current, later, List.map_append, List.map_cons] using
+ (congrArg (List.map TaggedLayer.layer) split).trans (selected_layers B f hf T hT X z)
+ rw [← exactRows]
+ exact ShrinkCallCapacity.layer_addresses (Y) B.recordLimit firstRow before later current
+ count site
+
+end Rows
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+
+/-- Maximum width of the selected outgoing slots. The local conversion block
+bounds the whole supply word before the layout subdivides it. -/
+theorem shrinkNext_width_le (j : Fin S.steps) {g : ℕ}
+ (Z : State (S.degreeExponent j.castSucc) (packingLaneBits (S.degreeExponent j.castSucc) g))
+ (sel : SelectedScore.Selection B Z) :
+ (Z.shrinkNext B.shrink (S.shrink j) sel).maxWireWidth ≤
+ fieldFactor B.shrink * (Z.maxWireWidth + 1) := by
+ classical
+ let d := 2 ^ S.degreeExponent j.castSucc
+ let c := 2 * d + 1
+ let layout := Z.packingData.shrinkTermLayout B.shrink Z.shrinkNumber Z.packingWidth sel
+ apply Finset.sup_le
+ intro e _
+ exact Z.packingData.shrinkSlotWidth_le (State.two_le_packingColors _) (Nat.two_pow_pos _)
+ Z.shrinkNumber Z.packingWidth (fun _ ↦ Z.width_le_maxWireWidth _) B.shrink sel layout
+ (subdivisions d c (2 ^ S.degreeExponent j.succ))
+ (Z.shrinkStateIndex (S.shrink j) layout).outgoing e
+
+/-- The same length threshold covers every output site, including the sites
+of the final shrink, before any coefficient assignment or branch choice. -/
+theorem eventually_parent_width (u : PairExponents B.growthConstant) (b : ℕ)
+ (hb : max S.laneBits 5 ≤ b) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ ∀ z : (B.execute f hf T hT X).Choices,
+ ∀ (cur : Fin (executeLevels B f hf T hT X z).length) (j : Fin S.steps) {g : ℕ}
+ (Z : State (S.degreeExponent j.castSucc)
+ (packingLaneBits (S.degreeExponent j.castSucc) g))
+ (sel : SelectedScore.Selection B Z) (bits : List Bool),
+ (executeLevels B f hf T hT X z)[cur] = shrinkLevel B f hf j Z sel bits →
+ (Z.shrinkNext B.shrink (S.shrink j) sel).maxWireWidth ≤ n ∧
+ 2 ^ S.degreeExponent j.succ ≤ slotDegree S := by
+ filter_upwards [ShrinkCallCapacity.eventually_levels B u b hb (fieldFactor B.shrink)]
+ with n bounds
+ intro base lanes labels hD hT R _ f hf X T z cur j g Z sel bits occurrence
+ let vs := executeLevels B f hf T hT X z
+ have input := (bounds labels hD hT R f hf z vs[cur] (List.getElem_mem cur.isLt)).2
+ have atLevel : vs[cur] = shrinkLevel B f hf j Z sel bits := occurrence
+ rw [atLevel] at input
+ exact ⟨(shrinkNext_width_le B j Z sel).trans input,
+ (shrinkLevel B f hf j Z sel bits).outputDegree_le⟩
+
+end PairSimulation.ShrinkPackedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPackedRows.lean b/lean/OAI/Computability/VPVNP/PairShrinkPackedRows.lean
new file mode 100644
index 0000000000..c16bcbe512
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPackedRows.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.PairShrinkSelectedCapacity
+import OAI.Computability.VPVNP.CompressorSelectedDirectoryHistory
+import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory
+import OAI.Computability.VPVNP.PairTerminalPackedBudget
+import OAI.Computability.VPVNP.PairTraversalPreorderBounds
+
+/-!
+# Child addresses in the selected packed DFS rows
+
+The level ordinal counts the chronological compression passes. The prefix at
+this ordinal ends immediately before the rows of its input state. The packed
+layout uses the actual calendar size to locate the first DFS row. Its exclusive
+row end also bounds every word-encoded preorder visit and its child references.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPackedRows
+
+open BurstRAM Compression CompressorRecords CursorBounds CursorNetwork DescriptorSpace Filter
+open TraversalRows TraversalRoles
+open scoped Fin.CommRing
+open private tag_count from OAI.Computability.VPVNP.CompressorSelectedDirectoryHistory
+
+section Selected
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+local notation "levels" => executeLevels B f hf T hT X z
+local notation "tags" => selected B f hf T hT X z
+local notation "rows" => selectedLayers B f hf T hT X z
+variable (workspace : ℕ) (i : Fin (executeLevels B f hf T hT X z).length)
+local notation "L" => BlockProgram.layout B workspace X.positions T
+local notation "firstRow" => endAddress L
+local notation "older" => layerBase B.recordLimit firstRow tags i.val
+
+private theorem child_address {a g : ℕ} (Z : State a g)
+ (count : Z.positions = levels[i].input.positions)
+ (site : Z.network.Site) :
+ older + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal Z site <
+ firstRow + words B.recordLimit rows := by
+ have hi : i.val < (tags).length := by
+ simp only [selected, List.length_cons, List.length_map]
+ exact Nat.lt_succ_of_lt i.isLt
+ let current := (tags)[i.val].layer
+ let before := ((tags).take i.val).map TaggedLayer.layer
+ let later := ((tags).drop (i.val + 1)).map TaggedLayer.layer
+ have atLevel : current.count = Z.positions :=
+ (tag_count (B := B) (f := f) (hf := hf) (z := z) i).trans count.symm
+ have split := List.take_append_drop (i.val + 1) (tags)
+ rw [List.take_succ_eq_append_getElem hi, List.append_assoc, List.singleton_append] at split
+ have exactRows : before ++ current :: later = rows := by
+ simpa only [before, current, later, List.map_append, List.map_cons] using
+ (congrArg (List.map TaggedLayer.layer) split).trans (selected_layers B f hf T hT X z)
+ rw [← exactRows]
+ exact ShrinkCallCapacity.layer_addresses Z B.recordLimit firstRow before later current
+ atLevel site
+
+/-- A selected input reindexed to its packing lane count uses the row prefix
+of that same level, at every site in the old network. -/
+theorem packed_layer_address {g : ℕ}
+ (eqn : levels[i].inputLanes = packingLaneBits levels[i].inputExponent g) :
+ let Z : State levels[i].inputExponent (packingLaneBits levels[i].inputExponent g) :=
+ eqn ▸ levels[i].input
+ ∀ site : Z.network.Site,
+ older + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal Z site <
+ firstRow + words B.recordLimit rows := by
+ intro Z site
+ apply child_address B f hf T hT X z workspace i Z _ site
+ have transported {a l l' : ℕ} (Y : State a l) (e : l = l') :
+ (e ▸ Y : State a l').positions = Y.positions := by subst l'; rfl
+ exact transported _ eqn
+
+/-- The old node at a concrete shrinking occurrence is inside the packed
+row allocation. Its address uses the selected occurrence and its true row pitch. -/
+theorem packed_shrink_address (j : Fin S.steps) {g : ℕ}
+ (Z : State (S.degreeExponent j.castSucc) (packingLaneBits (S.degreeExponent j.castSucc) g))
+ (sel : SelectedScore.Selection B Z) (bits : List Bool)
+ (atPass : levels[i] = shrinkLevel B f hf j Z sel bits) (site : Z.network.Site) :
+ older + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal Z site <
+ firstRow + words B.recordLimit rows :=
+ child_address B f hf T hT X z workspace i Z (by rw [atPass]; rfl) site
+
+/-- In the final directory image the native input-header cell contains the
+selected row prefix itself. The word bound gives its exact natural address. -/
+theorem retained_row_base {w : ℕ} (mem : Memory w)
+ (dirs : SelectedDirectoryHistory.Retained B f hf T hT X z L firstRow mem)
+ (fit : firstRow + words B.recordLimit rows ≤ 2 ^ w) :
+ (mem (levelStart L i.val + 14)).val = older := by
+ have p := dirs.current i.val i.isLt.le
+ change mem (levelStart L i.val + 14) = (older : Word w) at p
+ obtain ⟨site⟩ := levels[i].input.baseNonempty
+ have bound := child_address B f hf T hT X z workspace i levels[i].input rfl (site, 0)
+ rw [p, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : older < 2 ^ w)]
+
+end Selected
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+
+/-- For every field specialization and selected branch, all encoded visits
+and their child intervals are bounded by the end of the actual packed rows. -/
+theorem eventually_preorder (u : PairExponents B.growthConstant) (b : ℕ)
+ (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hstart : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ let w := wordBits b n
+ let T := blockCount (u.θ : ℝ) n
+ let X := pairInput S labels hD
+ let L := BlockProgram.layout B (start n) X.positions T
+ ∀ (z : (B.execute f hf T hT X).Choices) (mem : Memory w),
+ let layers := selectedLayers B f hf T hT X z
+ let limit := endAddress L + words B.recordLimit layers
+ AllRows w mem B.recordLimit (endAddress L) (endAddress L) layers →
+ ∀ v, ∀ node ∈ (selectedTrees B f hf T hT X z (endAddress L) v).preorder.map
+ (fun m : ℕ ↦ (m : Word w)),
+ node.val + 2 ≤ limit ∧ (mem node.val).val + (mem (node.val + 1)).val ≤ limit := by
+ filter_upwards [TerminalLayout.eventually_packedFit B u b hb hstart 0 (fun _ ↦ 0)
+ (PolynomiallyBounded.const 0)] with n room
+ intro base l labels hD hT R _ f hf w T X L z mem layers limit stored
+ have packed := room labels hD hT R f hf z
+ have positions : X.positions = initialPositions b n := pairInput_positions S labels hD
+ have le : limit ≤ 2 ^ w := by
+ change endAddress (BlockProgram.layout B (start n) X.positions T) +
+ words B.recordLimit layers ≤ 2 ^ w
+ rw [positions]
+ have external := packed.1
+ have high := packed.2.1
+ let final := (B.execute f hf T hT X).finalState z
+ let header := TerminalLayout.headerBase (start n) (addressBits b n)
+ change endAddress (BlockProgram.layout B (start n) (initialPositions b n) T) +
+ 2 * words B.recordLimit layers + final.totalWidth < header at external
+ change header + 32 ≤ 2 ^ w at high
+ omega
+ exact selected_preorder_word_bounds B f hf T hT X z (endAddress L) limit mem stored le_rfl le
+
+end PairSimulation.ShrinkPackedRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPacketData.lean b/lean/OAI/Computability/VPVNP/PairShrinkPacketData.lean
new file mode 100644
index 0000000000..f4fd13765f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPacketData.lean
@@ -0,0 +1,67 @@
+import OAI.Computability.VPVNP.PairShrinkJobOperands
+
+/-!
+# Packet premises of the resident shrinking-party gather
+
+The child scan supplies the old half-wires at the AB endpoints. The stored
+parent supplies the surviving half-wires. The selected map's workspace fit
+bounds all nine staging intervals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif
+open MotifGrid MotifBlocks MotifConversion CompressorRecords CompressorRecords.ShrinkSlots
+open NodeArguments
+
+variable {a b g w n limit t endAddr : ℕ} {δ factor : ℝ} {K : Type} [_root_.Field K]
+variable {X : State a (packingLaneBits a g)}
+variable {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+variable {m : X.packingData.Motif} {party : Fin 6}
+variable (J : Job X F ready sel m party w) {priv : Word w → Word w}
+/-- Use the same classical equality as the selected old half-wire layout. -/
+private noncomputable local instance packetBase : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X F sel
+local notation "site" => X.packingData.shrinkPartySite side m party
+local notation "parentPacket" => Packet.mk J.node (packed (X.shrinkNext F ready sel) site J.parent)
+local notation "demand" => ShrinkPreparedCall.widthsDemand X m
+
+/-- The gather's input and staging requirements follow from the actual packet
+readbacks and the workspace fit for this motif. -/
+theorem Job.packets_of (child : J.ChildWords priv endAddr)
+ (oldEnd : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ J.scratch.staging)
+ (parentFit : (parentPacket).Fits J.arena w endAddr)
+ (parentStored : (parentPacket).Stored J.arena (DFS.scratch endAddr priv))
+ (parentEnd : J.arena.base J.node + (parentPacket).bits.length ≤ J.scratch.staging)
+ (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions F (demand)) F (demand) (sel m).val J.scratch
+ (ShrinkMotifOrder.stateNumber X m).val (ShrinkCallDemandCells.cdBase X m J.arena J.nodes)) :
+ J.Packets endAddr priv := by
+ have room := ok.room.trans_lt ok.capacity.room
+ unfold ShrinkCallFields.Scratch.target ShrinkCallFields.Scratch.source
+ ShrinkCallFields.Scratch.descriptor at room
+ have directory : J.scratch.directory < 2 ^ w := by omega
+ have abEnd : J.scratch.staging + J.scratch.stride ≤ J.scratch.directory := by
+ unfold ShrinkCallFields.Scratch.directory
+ omega
+ have supplyStride (k : Fin 4) : branchWidth X F sel m k ≤ J.scratch.stride :=
+ ok.supply (side, k)
+ refine ⟨?_, oldEnd, parentFit, parentStored, parentEnd, ok.ab, ?_, supplyStride, ?_⟩
+ · intro dir hit
+ cases dir <;> subst party <;> exact child _ rfl
+ · exact (Nat.add_le_add_left ok.ab _).trans_lt (abEnd.trans_lt directory)
+ · intro dir k
+ exact (Nat.add_le_add_left (supplyStride k) _).trans_lt
+ ((J.scratch.surviving_end dir k).trans_lt directory)
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPartyABReads.lean b/lean/OAI/Computability/VPVNP/PairShrinkPartyABReads.lean
new file mode 100644
index 0000000000..9855b9caec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPartyABReads.lean
@@ -0,0 +1,270 @@
+import OAI.Computability.VPVNP.PairShrinkABFrameAddress
+import OAI.Computability.VPVNP.CompressorFormulaFootprint
+import OAI.Computability.VPVNP.PairShrinkArgumentReadBounds
+import OAI.Computability.VPVNP.PairShrinkCallABI
+
+/-!
+# External reads of a shrinking AB copy
+
+The copy visits the old-port list in append order, resolves the selected
+arc's thick rank, and follows the frame at that rank. Its source payload
+lives in a private child packet. Only the published old level, incidence
+columns, append list, rank column and slice bank are read externally.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkAB.Physical
+
+open Compression Compression.PackingData CompressorRecords CompressorRecords.PhaseRecipe
+open BurstRAM BundleLists
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem add_le (x y : Word w) : (x + y).val ≤ x.val + y.val := Nat.mod_le ..
+
+private theorem mul_le (x y : Word w) : (x * y).val ≤ x.val * y.val := Nat.mod_le ..
+
+/-- Access the identifier at the chosen position of the thick row. -/
+theorem Header.arc_reads (hdr : Header) (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+ (H pieces bucket buckets idx cap : ℕ) (list : Word w)
+ (readsMotif : hdr.motif.ReadsFrom (· < H) pub state mem)
+ (readsList : hdr.lists.ReadsFrom (· < H) pub state mem)
+ (readsStride : hdr.listStride.ReadsFrom (· < H) pub state mem)
+ (listEq : hdr.lists.eval pub state mem = list)
+ (strideEq : (hdr.listStride.eval pub state mem).val = cap)
+ (coord : (hdr.bundle pieces).eval pub state mem = (bucket : Word w))
+ (inBucket : bucket < buckets) (inSlot : idx < cap)
+ (room : list.val + buckets * cap ≤ H) :
+ (hdr.arc pieces idx).ReadsFrom (· < H) pub state mem := by
+ refine ⟨⟨⟨readsList, ⟨⟨readsMotif, trivial⟩, readsStride⟩⟩, trivial⟩, ?_⟩
+ change ((hdr.lists.eval pub state mem + (hdr.bundle pieces).eval pub state mem *
+ hdr.listStride.eval pub state mem) + (idx : Word w)).val < H
+ rw [listEq, coord]
+ let width := hdr.listStride.eval pub state mem
+ change ((list + (bucket : Word w) * width) + (idx : Word w)).val < H
+ have pos : ((bucket : Word w) * width).val ≤ bucket * cap :=
+ (mul_le _ _).trans (strideEq ▸ Nat.mul_le_mul_right width.val (Nat.mod_le ..))
+ have bound := Nat.mul_le_mul_right cap inBucket
+ rw [Nat.succ_mul] at bound
+ have cell := add_le (list + (bucket : Word w) * width) (idx : Word w)
+ have row := add_le list ((bucket : Word w) * width)
+ have offset : (idx : Word w).val ≤ idx := Nat.mod_le ..
+ omega
+
+/-- The only additional indirect read in the frame expression is the rank
+at the actual outgoing ID obtained from the old list. -/
+theorem Header.frame_reads (hdr : Header) (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+ (H count pieces idx slots : ℕ)
+ (motif : hdr.motif.ReadsFrom (· < H) pub state mem)
+ (banks : hdr.banks.ReadsFrom (· < H) pub state mem)
+ (rank : hdr.rankBase.ReadsFrom (· < H) pub state mem)
+ (arc : (hdr.arc pieces idx).ReadsFrom (· < H) pub state mem)
+ (arcBound : ((hdr.arc pieces idx).eval pub state mem).val < slots)
+ (room : (hdr.rankBase.eval pub state mem).val + slots ≤ H) :
+ (hdr.frame count pieces idx).ReadsFrom (· < H) pub state mem := by
+ have rankRead : (Expr.load (hdr.rankBase.add (hdr.arc pieces idx))).ReadsFrom
+ (· < H) pub state mem :=
+ ⟨⟨rank, arc⟩, (add_le _ _).trans_lt ((Nat.add_lt_add_left arcBound _).trans_le room)⟩
+ exact ⟨⟨⟨banks, ⟨⟨motif, trivial⟩, trivial⟩⟩, trivial⟩,
+ ⟨trivial, ⟨⟨rankRead, trivial⟩, ⟨motif, trivial⟩⟩⟩⟩
+
+variable {V G Tag L : Type} {d c : ℕ}
+variable [AddCommGroup G] [AddCommGroup Tag] [AddCommGroup L]
+
+/-- All three external reads of an indexed frame lie within its own AB bank. -/
+theorem frame_lt_end (P : PackingData V G Tag L d c)
+ (number : P.BundleNumbering) (order : P.ThickNumbering)
+ {b : Site V Tag L × Fin d} (m : P.MotifFiber b) (B : Word w) (a : P.ThickFiber b)
+ (j : Fin 3) :
+ ShrinkAB.frame P number order m B a + j.val <
+ B.val + IndexedStarts.capacity (2 ^ c * d / 4) (pieceCount d c) := by
+ have h : (order b a).val * pieceCount d c + (number b m).val <
+ (2 ^ c * d / 4) * pieceCount d c :=
+ (Nat.add_lt_add_left (number b m).isLt _).trans_le
+ ((Nat.succ_mul _ _).symm ▸ Nat.mul_le_mul_right _ (order b a).isLt)
+ have hj := j.isLt
+ unfold ShrinkAB.frame IndexedStarts.capacity
+ omega
+
+end PairSimulation.ShrinkAB.Physical
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.PackingData CompressorRecords CompressorRecords.PhaseRecipe
+open Compression.ShrinkMotif MotifGrid MotifBlocks MotifConversion
+open ShrinkPartyColumns ShrinkOldHalves.Physical CompressorRecords.ShrinkSlots
+open scoped Fin.CommRing
+
+variable {w a b g : ℕ} {K : Type*} [_root_.Field K] {δ factor : ℝ}
+variable {X : State a (packingLaneBits a g)}
+variable {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+variable {m : X.packingData.Motif} {party : Fin 6}
+variable (J : Job X F ready sel m party w)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "count" => 2 ^ (Shrink.colors a) * 2 ^ a / 4
+local notation "pieces" => pieceCount (2 ^ a) (Shrink.colors a)
+local notation "arcs" => Fintype.card X.Base * 2 ^ packingLaneBits a g * 2 ^ a
+local notation "buckets" => (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a
+local notation "bundle" => X.packingData.bundle m
+local notation "siteOrd" => Shrink.packedIndex (a := a) (g := g) X.baseIndex
+local notation "port" => BundleLists.portIndex siteOrd bundle
+local notation "side" => selectedLayout X F sel
+
+/-- External extents of the selected old-level data used by a native AB copy. -/
+structure Job.ABAreas (level : Word w) (T : IncidenceDirectory w) (origin H : ℕ) : Prop where
+ levelEnd : level.val + 60 ≤ H
+ classifier : (ShrinkInput.plan X origin).stop ≤ H
+ outgoing : T.actualOut.val + arcs ≤ H
+ incoming : T.actualIn.val + arcs ≤ H
+ widths : T.width.val + arcs ≤ H
+ intersections : J.first + buckets * IndexedStarts.capacity count pieces ≤ H
+
+variable {pub : Fin 5 → Word w} {state level : Word w} {mem : Memory w} {T : IncidenceDirectory w}
+variable {origin H : ℕ}
+
+/-- The enclosing shrink role provides these entry expressions. Its concrete
+register ABI only reads the old level's degree-independent length word. -/
+structure InputsReadable (O : ShrinkCallHeader.Operands) (H : ℕ) (pub : Fin 5 → Word w)
+ (state : Word w) (mem : Memory w) : Prop where
+ level : O.level.ReadsFrom (· < H) pub state mem
+ motif : O.motif.ReadsFrom (· < H) pub state mem
+ arguments : O.arguments.ReadsFrom (· < H) pub state mem
+ stride : O.argumentStride.ReadsFrom (· < H) pub state mem
+ hidden : O.hidden.ReadsFrom (· < H) pub state mem
+ slot : O.slotStride.ReadsFrom (· < H) pub state mem
+
+private theorem cell_reads {O : ShrinkCallHeader.Operands}
+ (entry : O.level.eval pub state mem = level) (read : O.level.ReadsFrom (· < H) pub state mem)
+ (room : level.val + 60 ≤ H) (i : ℕ) (hi : i < 60) :
+ (ShrinkCD.Published.load O.level i).ReadsFrom (· < H) pub state mem := by
+ refine ⟨⟨read, trivial⟩, ?_⟩
+ change (O.level.eval pub state mem + (i : Word w)).val < H
+ rw [entry, Fin.val_add]
+ exact (Nat.mod_le ..).trans_lt
+ ((Nat.add_lt_add_left ((Nat.mod_le ..).trans_lt hi) _).trans_le room)
+
+/-- A caller may supply any bounded old outgoing-ID expression, including
+the CD rank-selection expression or one cell of the thick AB list. -/
+theorem Job.old_field_reads (O : ShrinkCallHeader.Operands)
+ (old : J.OldPublished O pub state mem level T origin)
+ (ins : InputsReadable O H pub state mem) (areas : J.ABAreas level T origin H)
+ (e : BundleKeys.OldArc X.Base a g) (arc : Expr) (dir : Bool)
+ (arcEq : arc.eval pub state mem =
+ IncidenceDirectory.actualPort X (packingInputEdges X.Base a g e))
+ (arcRead : arc.ReadsFrom (· < H) pub state mem) :
+ ((O.cdHeader a).fields.oldHalf.field (2 ^ a) arc dir).ReadsFrom (· < H) pub state mem := by
+ let hdr := (O.cdHeader a).fields.oldHalf
+ have heads := ShrinkCallHeader.heads X F sel m O pub state level mem J.arena T origin
+ J.older J.pitch J.first J.scratch.hidden J.scratch.stride J.scratch.hist old.levelData old.live
+ have geometry := ShrinkCallHeader.geometry X T origin old.space
+ have read := cell_reads old.live.header ins.level areas.levelEnd
+ let u := X.packingInputIso.site (ShrinkOldHalves.position X e dir)
+ let j := ShrinkOldHalves.slot X e dir
+ have oriented := ShrinkOldHalves.Physical.port_eq X hdr T J.arena J.older J.pitch pub state mem
+ heads.child old.tables.incidence e arc arcEq dir
+ exact ArgumentReadBounds.old_field X u j hdr T J.arena heads.child old.tables.incidence
+ J.arcFit geometry.degreeFit arc (packingInputEdges X.Base a g e) dir arcEq oriented H
+ ⟨ins.arguments, ins.stride, read 58 (by decide), read 59 (by decide)⟩ arcRead
+ (read 57 (by decide)) (read 14 (by decide)) (read 15 (by decide))
+ areas.outgoing areas.incoming areas.widths
+
+/-- External bounds for all six pointer-program operands and all three
+direct frame reads at a genuine thick-wire visit of an active AB party. -/
+theorem Job.ab_readBounds (O : ShrinkCallHeader.Operands) (nodeExpr : Expr)
+ (old : J.OldPublished O pub state mem level T origin)
+ (ins : InputsReadable O H pub state mem) (areas : J.ABAreas level T origin H)
+ (hc : none ∈ columns party side) (i : Fin count) :
+ let c : At party side := ⟨none, hc⟩
+ (∀ f : Fin 6, ((setups O nodeExpr a b party side c i).operands f).ReadsFrom
+ (· < H) pub state mem) ∧ ∀ k : Fin 3, (J.row c i).frame + k.val < H := by
+ intro c
+ let hdr := (O.cdHeader a).fields
+ let Z := ShrinkInput.plan X origin
+ let q := Z.collectBank w
+ let t := ShrinkAB.Physical.members X J.arcFit J.bucketFit bundle i
+ let e := t.1.1
+ let dir := decide (party = 1)
+ have heads := ShrinkCallHeader.heads X F sel m O pub state level mem J.arena T origin
+ J.older J.pitch J.first J.scratch.hidden J.scratch.stride J.scratch.hist old.levelData old.live
+ have G := ShrinkCallHeader.geometry X T origin old.space
+ have countBound : count ≤ pieces := by unfold pieceCount; omega
+ have idxBound := i.isLt.trans_le (countBound.trans G.cap)
+ have coord := (ShrinkAB.Physical.coordinates X hdr pub state mem m heads.ab G.piecesFit).1
+ have aid := ShrinkAB.Physical.old_id X hdr pub state mem m heads.ab J.arcFit J.bucketFit
+ G.piecesFit i G.regions G.nrows (countBound.trans G.cap) old.tables.preimages
+ have v := Z.values T (ShrinkInput.placementBank X T origin) Fintype.card_pos old.space
+ have cells := cell_reads old.live.header ins.level areas.levelEnd
+ have listRoom : (q 5).val + buckets * (q 4).val ≤ H := by
+ rw [v.ids, v.stride]
+ have half : buckets * Z.Q ≤ (2 * buckets) * Z.Q := Nat.mul_le_mul_right _ (by omega)
+ have last : Z.ids + (2 * buckets) * Z.Q ≤ Z.stop := by
+ change Z.gathered ≤ Z.gathered + Z.rectangleSize + Z.A
+ omega
+ exact ((Nat.add_le_add_left half _).trans last).trans areas.classifier
+ have arcRead := hdr.arc_reads pub state mem H pieces (port).val buckets i.val (q 4).val (q 5)
+ ins.motif (cells 46 (by decide)) trivial heads.ab.lists
+ (congrArg Fin.val heads.ab.listStride) coord (port).isLt idxBound listRoom
+ have arcBound : ((hdr.arc pieces i.val).eval pub state mem).val < arcs := by
+ rw [aid, IncidenceDirectory.actualPort_number]
+ exact (Nat.mod_le ..).trans_lt (IncidenceDirectory.actualOrder X _).isLt
+ have rankRoom : (hdr.rankBase.eval pub state mem).val + arcs ≤ H := by
+ rw [heads.ab.rankBase]
+ change (Fin.ofNat (2 ^ w) Z.ranks).val + arcs ≤ H
+ rw [v.ranks]
+ exact areas.classifier
+ have frameRead := hdr.frame_reads pub state mem H count pieces i.val arcs ins.motif
+ (cells 43 (by decide)) (cells 45 (by decide)) arcRead arcBound rankRoom
+ have sourceRead := J.old_field_reads O old ins areas e (hdr.arc pieces i.val) dir aid arcRead
+ have destRead : (O.staging a).ReadsFrom (· < H) pub state mem :=
+ ⟨ins.hidden, ⟨⟨trivial, ⟨⟨⟨cells 0 (by decide), ⟨trivial, cells 3 (by decide)⟩⟩, trivial⟩,
+ trivial⟩⟩, ins.slot⟩⟩
+ constructor
+ · intro f
+ fin_cases f <;> first | exact sourceRead | exact destRead | exact frameRead | trivial
+ · intro k
+ let B := ShrinkABSliceTable.bank (w := w) J.first count pieces (port).val
+ have lower := ShrinkAB.Physical.frame_lt_end X.packingData X.shrinkNumber X.shrinkOrder
+ (b := bundle) ⟨m, rfl⟩ B t k
+ have bank : B.val = J.first + (port).val * IndexedStarts.capacity count pieces :=
+ ShrinkABSliceTable.bank_val old.allocation port
+ have rowBound := Nat.mul_le_mul_right (IndexedStarts.capacity count pieces) (port).isLt
+ rw [Nat.succ_mul] at rowBound
+ change (ShrinkAB.frame X.packingData X.shrinkNumber X.shrinkOrder ⟨m, rfl⟩ B t) + k.val < H
+ exact lower.trans_le (by rw [bank, Nat.add_assoc]
+ exact (Nat.add_le_add_left rowBound _).trans areas.intersections)
+
+/-- The canonical six-register ABI satisfies the expression bounds from the
+published level header alone. Its only external operand load is cell 17. -/
+theorem Job.abi_inputs_readable (degree : ℕ)
+ (old : J.OldPublished (ShrinkCallABI.operands degree) pub state mem level T origin)
+ (areas : J.ABAreas level T origin H) :
+ InputsReadable (ShrinkCallABI.operands degree) H pub state mem := by
+ have lengthRead := cell_reads old.live.header (show
+ (ShrinkCallABI.operands degree).level.ReadsFrom (· < H) pub state mem from trivial)
+ areas.levelEnd 17 (by decide)
+ exact ⟨trivial, trivial, lengthRead, ⟨⟨trivial, lengthRead⟩, trivial⟩, trivial,
+ ⟨lengthRead, lengthRead⟩⟩
+
+/-- Bound every AB setup and frame load for the register ABI installed in
+the shrinking party evaluator. -/
+theorem Job.abi_ab_readBounds (degree : ℕ)
+ (old : J.OldPublished (ShrinkCallABI.operands degree) pub state mem level T origin)
+ (areas : J.ABAreas level T origin H) (hc : none ∈ columns party side) (i : Fin count) :
+ let c : At party side := ⟨none, hc⟩
+ let S := setups (ShrinkCallABI.operands degree) ShrinkCallABI.node a b party side c i
+ (∀ f : Fin 6, (S.operands f).ReadsFrom (· < H) pub state mem) ∧
+ ∀ k : Fin 3, (J.row c i).frame + k.val < H :=
+ J.ab_readBounds (ShrinkCallABI.operands degree) ShrinkCallABI.node old
+ (J.abi_inputs_readable degree old areas) areas hc i
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPartyColumns.lean b/lean/OAI/Computability/VPVNP/PairShrinkPartyColumns.lean
new file mode 100644
index 0000000000..5e6ad0008d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPartyColumns.lean
@@ -0,0 +1,325 @@
+import OAI.Computability.VPVNP.PairResidentFrameColumn
+import OAI.Computability.VPVNP.PairShrinkCallFields
+import OAI.Computability.VPVNP.PairShrinkABFrameAddress
+import OAI.Computability.VPVNP.PairShrinkSurvivingColumn
+
+/-!
+# Native frame schedule for one party of a shrinking motif
+
+The AB interval, when present, is followed by the incident surviving
+subdivisions in source and then target order. Each assembled operand
+occupies its own stride in scratch. This permits all frames to run in
+one program while every operand has the value it would have in isolation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyColumns
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords ShrinkCallFields ResidentColumn
+open scoped Fin.CommRing
+
+/-- AB has one staging region. Each surviving type has a region at each end. -/
+abbrev Column := Option (Bool × Fin 4)
+
+/-- Test whether the selected party gathers the AB demand or the given oriented surviving
+supply field in the chosen layout. -/
+def active (party : Fin 6) (layout : Bool) : Column → Bool
+ | none => decide (party = 0 ∨ party = 1)
+ | some (dir, t) => decide (party = supplyParty dir (layout, t))
+
+private def all : List Column :=
+ none :: (List.ofFn (fun t : Fin 4 ↦ some (false, t)) ++
+ List.ofFn (fun t : Fin 4 ↦ some (true, t)))
+
+/-- The fixed list of candidate gather columns filtered to the ones incident to this party. -/
+def columns (party : Fin 6) (layout : Bool) := all.filter (active party layout)
+
+theorem mem_columns (party : Fin 6) (layout : Bool) (c : Column) :
+ c ∈ columns party layout ↔ active party layout c := by
+ have present : c ∈ all := by
+ rcases c with _ | ⟨dir, t⟩
+ · exact List.mem_cons_self
+ · cases dir <;> fin_cases t <;> simp [all]
+ simp [columns, present]
+
+/-- An active gather column together with its membership in this party's filtered list. -/
+abbrev At (party : Fin 6) (layout : Bool) := {c // c ∈ columns party layout}
+
+/-- The number of frame copies in a column, given by the AB arc count or the selected supply
+role's subdivision count. -/
+def frames (abCount : ℕ) (subdiv : Fin 4 → ℕ) : Column → ℕ
+ | none => abCount
+ | some (_, t) => subdiv t
+
+/-- Private staging destination for the AB demand or the oriented surviving supply word of this
+column. -/
+def base (s : Scratch) : Column → ℕ
+ | none => s.staging
+ | some (dir, t) => s.surviving dir t
+
+variable (party : Fin 6) (layout : Bool) (abCount : ℕ) (subdiv : Fin 4 → ℕ)
+
+/-- A copy visit consisting of an incident column and a valid frame ordinal within that column. -/
+abbrev Visit := (c : At party layout) × Fin (frames abCount subdiv c.val)
+
+/-- Enumerate the active columns in party order and every frame within each column in
+increasing ordinal order. -/
+def visits : List (Visit party layout abCount subdiv) :=
+ (columns party layout).attach.flatMap fun c ↦
+ (List.finRange (frames abCount subdiv c.val)).map (Sigma.mk c)
+
+/-- The finite instruction table visits every frame of every incident column. -/
+def gather {α : Type*}
+ (f : ∀ c : At party layout, Fin (frames abCount subdiv c.val) → α)
+ (i : Fin (visits party layout abCount subdiv).length) : α :=
+ let v := (visits party layout abCount subdiv).get i
+ f v.1 v.2
+
+/-- Use the thick-wire worker on AB and the reverse subdivision worker on each supply field. -/
+def setup (oldDegree newDegree pieces : ℕ) (ab : ShrinkAB.Physical.Header)
+ (surv : Bool → Fin 4 → ShrinkSurvivingColumn.Inputs) :
+ (c : At party layout) → Fin (frames abCount subdiv c.val) → Setup
+ | ⟨none, _⟩, i => ab.setup oldDegree abCount pieces (decide (party = 1)) i.val
+ | ⟨some (dir, t), _⟩, i => (surv dir t).setup newDegree subdiv t dir i
+
+variable {party layout abCount subdiv} {w : ℕ}
+
+private theorem writes_eq
+ (row : ∀ c : At party layout, Fin (frames abCount subdiv c.val) → Row)
+ (priv : Word w → Word w) :
+ writes (gather party layout abCount subdiv row) (List.finRange _) priv =
+ (columns party layout).attach.foldl
+ (fun old c ↦ writes (row c) (List.finRange _) old) priv := by
+ let vs := visits party layout abCount subdiv
+ let write (old : Word w → Word w) (v : Visit party layout abCount subdiv) :=
+ (row v.1 v.2).write old
+ change (List.finRange vs.length).foldl (fun old i ↦ write old (vs.get i)) priv = _
+ rw [← List.foldl_map, List.map_get_finRange]
+ change ((columns party layout).attach.flatMap _).foldl write priv = _
+ simp only [List.foldl_flatMap, List.foldl_map, writes]
+ rfl
+
+private theorem keep_fold {α : Type*} (ls : List α)
+ (step : (Word w → Word w) → α → Word w → Word w) (addr : Word w)
+ (keeps : ∀ i ∈ ls, ∀ old, step old i addr = old addr) (old : Word w → Word w) :
+ ls.foldl step old addr = old addr := by
+ induction ls generalizing old with
+ | nil => rfl
+ | cons i rest ih =>
+ exact (ih (fun j hj ↦ keeps j (List.mem_cons_of_mem i hj)) (step old i)).trans
+ (keeps i List.mem_cons_self old)
+
+private theorem store_congr (dst : ℕ) (bits : List Bool) (addr : Word w)
+ {m n : Word w → Word w} (eqv : m addr = n addr) :
+ PrivateFields.storeBits dst bits m addr = PrivateFields.storeBits dst bits n addr := by
+ induction bits generalizing dst m n with
+ | nil => exact eqv
+ | cons bit rest ih =>
+ apply ih
+ by_cases same : addr = (dst : Word w)
+ · subst addr; simp
+ · simp [Function.update_of_ne same, eqv]
+
+private theorem writes_congr {n : ℕ} (row : Fin n → Row) (ls : List (Fin n)) (addr : Word w)
+ {m n' : Word w → Word w} (eqv : m addr = n' addr) :
+ writes row ls m addr = writes row ls n' addr := by
+ induction ls generalizing m n' with
+ | nil => exact eqv
+ | cons i rest ih => exact ih (store_congr _ _ addr eqv)
+
+private def number : Column → ℕ
+ | none => 0
+ | some (dir, t) => 1 + dir.toNat * 4 + t.val
+
+private theorem number_injective : Function.Injective number := by
+ rintro (_ | ⟨d, i⟩) (_ | ⟨e, j⟩) h
+ · rfl
+ · simp [number] at h
+ omega
+ · simp [number] at h
+ · cases d <;> cases e <;> simp [number] at h ⊢ <;> omega
+
+private theorem base_eq (s : Scratch) (c : Column) :
+ base s c = s.staging + number c * s.stride := by
+ cases c <;> simp [base, number, Scratch.surviving]
+
+private theorem separate (s : Scratch) {c d : Column} (ne : c ≠ d) :
+ base s c + s.stride ≤ base s d ∨ base s d + s.stride ≤ base s c := by
+ have step (x y : Column) (h : number x < number y) : base s x + s.stride ≤ base s y := by
+ rw [base_eq, base_eq, Nat.add_assoc, ← Nat.succ_mul]
+ exact Nat.add_le_add_left (Nat.mul_le_mul_right _ h) _
+ exact (lt_or_gt_of_ne (number_injective.ne ne)).imp (step c d) (step d c)
+
+variable (scratch : Scratch)
+variable (row : ∀ c : At party layout, Fin (frames abCount subdiv c.val) → Row)
+
+/-- Every nonempty slice stays within the stride reserved for its column. -/
+def InBuffer (c : At party layout) (i : Fin (frames abCount subdiv c.val)) : Prop :=
+ 0 < (row c i).bits.length → base scratch c.val ≤ (row c i).destination + (row c i).targetOffset ∧
+ (row c i).destination + (row c i).targetOffset + (row c i).bits.length ≤
+ base scratch c.val + scratch.stride
+
+/-- A frame written at its assigned base is confined whenever its last bit is within the stride. -/
+theorem inBuffer_of (c : At party layout) (i : Fin (frames abCount subdiv c.val))
+ (dest : (row c i).destination = base scratch c.val)
+ (bound : 0 < (row c i).bits.length →
+ (row c i).targetOffset + (row c i).bits.length ≤ scratch.stride) :
+ InBuffer scratch row c i := by
+ intro pos
+ rw [dest]
+ have := bound pos
+ omega
+
+variable (pivot : ℕ) (fits : ∀ c i, (row c i).Fits w pivot)
+variable (inside : ∀ c i, InBuffer scratch row c i)
+
+include fits inside in
+private theorem keep_column (c : At party layout) (addr : Word w)
+ (outside : addr.val < base scratch c.val ∨ base scratch c.val + scratch.stride ≤ addr.val)
+ (old : Word w → Word w) :
+ writes (row c) (List.finRange _) old addr = old addr := by
+ apply keep_fold
+ intro i _ priv
+ by_cases zero : (row c i).bits.length = 0
+ · simp [Row.write, List.length_eq_zero_iff.mp zero, PrivateFields.storeBits]
+ have hp := Nat.pos_of_ne_zero zero
+ have bounds := inside c i hp
+ exact PrivateFields.storeBits_outside _ _ priv addr ((fits c i).room hp).le (by omega)
+
+include fits inside in
+/-- The final memory at each operand agrees with running that column alone.
+All addresses below staging retain the child packets and shared hidden fields. -/
+theorem memory (old : Word w → Word w) :
+ let final := writes (gather party layout abCount subdiv row) (List.finRange _) old
+ (∀ c : At party layout, ∀ addr : Word w,
+ base scratch c.val ≤ addr.val → addr.val < base scratch c.val + scratch.stride →
+ final addr = writes (row c) (List.finRange _) old addr) ∧
+ (∀ addr : Word w, addr.val < scratch.staging → final addr = old addr) := by
+ intro final
+ have joined := writes_eq row old
+ change final = _ at joined
+ rw [joined]
+ let cs := (columns party layout).attach
+ let step (m : Word w → Word w) (c : At party layout) := writes (row c) (List.finRange _) m
+ constructor
+ · intro c addr lo hi
+ have other (d : At party layout) (hd : d ≠ c) (m : Word w → Word w) :
+ step m d addr = m addr := by
+ have sep := separate scratch (Subtype.val_injective.ne hd)
+ apply keep_column scratch row pivot fits inside
+ omega
+ have nd : cs.Nodup := by
+ have allNd : all.Nodup := by decide
+ exact List.Nodup.attach (allNd.filter _)
+ obtain ⟨pre, post, hs⟩ := List.append_of_mem (List.mem_attach _ c)
+ change cs = pre ++ c :: post at hs
+ rw [hs, List.nodup_append] at nd
+ change cs.foldl step old addr = step old c addr
+ rw [hs, List.foldl_append, List.foldl_cons]
+ have after := keep_fold post step addr
+ (fun d hd ↦ other d (fun eqv ↦ (List.nodup_cons.mp nd.2.1).1 (eqv ▸ hd)))
+ (step (pre.foldl step old) c)
+ apply after.trans
+ apply writes_congr
+ exact keep_fold pre step addr (fun d hd ↦ other d (nd.2.2 d hd c List.mem_cons_self)) old
+ · intro addr below
+ apply keep_fold
+ intro d _ m
+ apply keep_column scratch row pivot fits inside d addr _ m
+ rw [base_eq]
+ exact Or.inl (below.trans_le (Nat.le_add_right _ _))
+
+variable {p r k : ℕ}
+variable (S : ∀ c : At party layout, Fin (frames abCount subdiv c.val) → Setup)
+local notation "flatSetup" => gather party layout abCount subdiv S
+local notation "flatRow" => gather party layout abCount subdiv row
+local notation "order" => List.finRange (List.length (visits party layout abCount subdiv))
+
+include fits inside in
+/-- Run the fixed concatenated frame code at this party. Each target contains the same
+operand as in its own column run, and all previously supplied inputs below staging survive. -/
+theorem native (M : Machine w p r k)
+ (vm : ∀ i, Fin (RegisterSetup.regCount ((flatSetup i).operands)) ↪ Fin r)
+ (inputs : Fin 6 → Fin r) (loc : Label flatSetup → Fin p) (ret : Fin p)
+ (code : ∀ l, M.code (loc l) = instruction flatSetup vm inputs loc ret l)
+ (safe : ∀ i v j, vm i v ≠ inputs j)
+ (mem : Memory w) (pub : Fin 5 → Word w) (state : Word w)
+ (recorded : ∀ c i, (row c i).Recorded (S c i) pub state mem)
+ (cfg : Config w p r) (entry : cfg.pc = start flatSetup loc ret 0)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state)
+ (read : ∀ c i, (row c i).reads cfg.privateMem) :
+ ∃ events out, Result flatSetup vm M ret flatRow order mem cfg out events ∧
+ (∀ c : At party layout, ∀ addr : Word w,
+ base scratch c.val ≤ addr.val → addr.val < base scratch c.val + scratch.stride →
+ out.privateMem addr = writes (row c) (List.finRange _) cfg.privateMem addr) ∧
+ (∀ addr : Word w, addr.val < scratch.staging →
+ out.privateMem addr = cfg.privateMem addr) := by
+ obtain ⟨events, out, res⟩ := ResidentColumn.native M loc ret code safe flatRow mem pub state
+ (fun _ ↦ recorded _ _) pivot (fun _ ↦ fits _ _) cfg entry hp hs (fun _ ↦ read _ _)
+ refine ⟨events, out, res, ?_⟩
+ rw [res.memory]
+ exact memory scratch row pivot fits inside cfg.privateMem
+
+section Bounds
+
+open Compression Compression.PackingData NodeArguments
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g))
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+set_option maxHeartbeats 800000 in
+-- Compare the worker’s old-arc index and the matching dependent thick-fiber coordinate.
+/-- Every nonempty frame from the AB worker fits the logical demand word. -/
+theorem ab_bound (m : X.packingData.Motif)
+ (arcFit : Fintype.card X.Base * 2 ^ (packingLaneBits a g) * 2 ^ a ≤ 2 ^ w)
+ (bucketFit : (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a +
+ (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a ≤ 2 ^ w)
+ (i : Fin (2 ^ (Shrink.colors a) * 2 ^ a / 4)) (arena : Arena)
+ (nodes : X.network.Site → ℕ) (layout dir : Bool)
+ (x : X.packingData.PlacedHalf X.packingWidth layout (ShrinkOldHalves.abSite X m dir))
+ (first dst : ℕ) :
+ let r := ShrinkAB.Physical.row X m arcFit bucketFit i arena nodes layout dir x
+ (first := first) (dest := dst)
+ 0 < r.bits.length →
+ r.targetOffset + r.bits.length ≤ X.packingData.abWidth X.shrinkNumber X.packingWidth m := by
+ intro r pos
+ let b := X.packingData.bundle m
+ let z := ShrinkAB.Physical.members X arcFit bucketFit b i
+ let cut := X.packingData.demandSlice X.shrinkNumber X.shrinkOrder X.packingWidth b z ⟨m, rfl⟩
+ have len : r.bits.length = cut.length := List.length_ofFn
+ change cut.targetOffset + r.bits.length ≤ _
+ rw [len]
+ exact ShrinkAB.target_bound X.packingData X.shrinkNumber X.shrinkOrder X.packingWidth
+ ⟨m, rfl⟩ z (len ▸ pos)
+
+/-- A surviving reverse frame has precisely the endpoint's subdivision width. -/
+theorem surviving_bound {b pad : ℕ} (layout : Bool) (subdiv : Fin 4 → ℕ)
+ (width : X.packingData.Motif → Fin 4 → ℕ)
+ {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+ (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad)
+ (m : X.packingData.Motif) (t : Fin 4) (dir : Bool)
+ (z : (X.shrinkOutputState layout subdiv width I).network.Half
+ (ShrinkSurvivingOperands.site X layout m t dir))
+ (arena : Arena) (node dst : ℕ) (bank : ShrinkSliceSweep.Row w)
+ (hpos : ∀ t, 0 < subdiv t) (j : Fin (subdiv t)) :
+ let r := ShrinkSurvivingColumn.row X layout subdiv width I m t dir z arena node dst bank j
+ r.targetOffset + r.bits.length ≤ width m t := by
+ intro r
+ have len := ShrinkSurvivingColumn.row_length X layout subdiv width I m t dir z arena
+ node dst bank hpos j
+ change r.bits.length = _ at len
+ rw [len]
+ exact ShrinkSurvivingFrames.end_le _ _ (hpos t) j
+
+end Bounds
+
+end PairSimulation.ShrinkPartyColumns
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPartyNative.lean b/lean/OAI/Computability/VPVNP/PairShrinkPartyNative.lean
new file mode 100644
index 0000000000..d9821a4f0a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPartyNative.lean
@@ -0,0 +1,415 @@
+import OAI.Computability.VPVNP.PairSimulationDFSHooks
+import OAI.Computability.VPVNP.PairShrinkPartyColumns
+import OAI.Computability.VPVNP.PairShrinkCallHeader
+import OAI.Computability.VPVNP.PairShrinkCallDemandCells
+import OAI.Computability.VPVNP.PairShrinkCallSupplyCells
+import OAI.Computability.VPVNP.PairShrinkSurvivingSelected
+
+/-!
+# Executing the selected resident shrinking-party columns
+
+The packed old assignments determine each AB source bit, and one stored
+parent packet supplies every incident surviving column. The selected row
+allocation and ordered-slot table determine the pointer computations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.State Compression.PackingData
+open Compression.ShrinkMotif Compression.ShrinkEnergy MotifBlocks MotifGrid MotifConversion
+open CompressorRecords CompressorRecords.ShrinkSlots CompressorRecords.ShrinkSliceSweep
+open CompressorRecords.PortRefresh.ArgumentAddress NodeArguments ShrinkPartyColumns
+open scoped Fin.CommRing
+
+variable {a b g w : ℕ} {δ factor : ℝ} {K : Type*} [_root_.Field K]
+variable (X : State a (packingLaneBits a g))
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) (sel : X.ShrinkSelection F)
+variable (m : X.packingData.Motif) (party : Fin 6)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X F sel
+local notation "sub" => SlotLevel.Shape.subdivisions (levelShape (b := b) X)
+local notation "slots" => X.shrinkStateIndex ready side
+local notation "outState" => X.shrinkNext F ready sel
+local notation "width" => branchWidth X F sel
+local notation "atSite" => X.packingData.shrinkPartySite side m party
+local notation "count" => 2 ^ (Shrink.colors a) * 2 ^ a / 4
+local notation "pieces" => pieceCount (2 ^ a) (Shrink.colors a)
+local notation "abWidth" => X.packingData.abWidth X.shrinkNumber X.packingWidth m
+local notation "idx" => ShrinkMotifOrder.stateNumber X m
+local notation "buckets" => (Fintype.card X.Base * (2 ^ (Shrink.J a) * 2 ^ g)) * 2 ^ a
+
+/-- The current map job uses the selected branch and the same arena for its old
+child packets and its new half-wire packet. The three slice bases are public. -/
+structure Job (w : ℕ) where
+ /-- Placed old half-wire assignments at the resident party site, used to recover the demand
+ operands. -/
+ old : ShrinkCallDemandCells.Old X side m party
+ /-- The selected output site's independent half-wire assignment supplying the subdivided
+ surviving fields in its packet. -/
+ parent : (outState).network.Half atSite
+ /-- Private argument arena shared by this parent packet and the old child packets. -/
+ arena : Arena
+ /-- Absolute DFS row address indexing the parent argument packet. -/
+ node : ℕ
+ /-- Private shared-field, staging, directory, and histogram addresses of this party's shrink
+ map. -/
+ scratch : ShrinkCallFields.Scratch
+ /-- Start of the input layer's DFS rows, from which the old-site node addresses are computed. -/
+ older : ℕ
+ /-- Number of words per old DFS site row. -/
+ pitch : ℕ
+ /-- Start of the external AB frame-bank rectangle, with one indexed bank per bundle. -/
+ first : ℕ
+ /-- External base word for the selected shrinking term records. -/
+ term : Word w
+ /-- Word stride between successive dense motif term records. -/
+ stride : ℕ
+ /-- External base address of the surviving slice-width arrays in the selected allocation. -/
+ widthBase : ℕ
+ arcFit : Fintype.card X.Base * 2 ^ packingLaneBits a g * 2 ^ a ≤ 2 ^ w
+ bucketFit : buckets + buckets ≤ 2 ^ w
+
+variable {X F ready sel m party} (J : Job X F ready sel m party w)
+
+/-- Locate an old site's child row using its site ordinal and the old layer's base and pitch. -/
+noncomputable def Job.nodes (u : X.network.Site) := J.older + J.pitch * siteOrdinal X u
+
+private theorem ab_hit (h : none ∈ columns party side) : party = if party = 1 then 1 else 0 := by
+ have hs := (mem_columns party side none).mp h
+ simp only [active, decide_eq_true_eq] at hs
+ rcases hs with rfl | rfl <;> decide
+
+private theorem supply_hit (dir : Bool) (t : Fin 4) (h : some (dir, t) ∈ columns party side) :
+ party = ShrinkSurvivingOperands.party side t dir := by
+ have hs := (mem_columns party side _).mp h
+ change decide (party = ShrinkCallFields.supplyParty dir (side, t)) = true at hs
+ cases dir <;> exact of_decide_eq_true hs
+
+/-- At A or B, extract the placed old half-wire assignment used by the indicated end of the AB
+demand. -/
+noncomputable def Job.abHalf (dir : Bool) (hit : party = if dir then 1 else 0) :=
+ ShrinkCallDemandCells.abHalf X side m dir (hit ▸ J.old)
+
+private def movedHalf {N : NetworkKernel.Network} {u v : N.Site} (h : u = v) (z : N.Half u) :
+ N.Half v := ⟨fun e he ↦ z.1 e (h.trans he), fun e he ↦ z.2 e (h.trans he)⟩
+
+/-- Transport the resident parent's half-wire assignment to the equal site at the chosen end of
+a surviving supply wire. -/
+noncomputable def Job.half (dir : Bool) (t : Fin 4)
+ (hit : party = ShrinkSurvivingOperands.party side t dir) :=
+ movedHalf ((congrArg (X.packingData.shrinkPartySite side m) hit).trans
+ (ShrinkSurvivingOperands.party_site X side m t dir)) J.parent
+
+private theorem moved_packed {u v : (outState).network.Site} (e : u = v)
+ (z : (outState).network.Half u) :
+ packed (outState) v (movedHalf e z) = packed (outState) u z := by
+ cases e
+ rfl
+
+theorem Job.packed_half (dir : Bool) (t : Fin 4)
+ (hit : party = ShrinkSurvivingOperands.party side t dir) :
+ packed (outState) _ (J.half dir t hit) = packed (outState) _ J.parent := moved_packed _ _
+
+/-- The selected slice allocation determined by the term records, width base, and subdivision
+profile for this shrink. -/
+noncomputable def Job.allocation := selectedAllocation F X sel J.term J.stride J.widthBase sub
+
+/-- Copy row for one old AB arc, with its child packet as source and the party's AB staging
+word as destination. -/
+noncomputable def Job.abRow (dir : Bool) (hit : party = if dir then 1 else 0) (i : Fin count) :=
+ ShrinkAB.Physical.row X m J.arcFit J.bucketFit i J.arena J.nodes side dir (J.abHalf dir hit)
+ (first := J.first) (dest := J.scratch.staging)
+
+/-- Reverse-copy row for one subdivision of an incident surviving supply field, read from the
+parent packet and placed in its unsplit staging word. -/
+noncomputable def Job.supplyRow (dir : Bool) (t : Fin 4)
+ (hit : party = ShrinkSurvivingOperands.party side t dir) (i : Fin (sub t)) :=
+ ShrinkSurvivingColumn.row X side sub (width) slots m t dir (J.half dir t hit) J.arena
+ J.node (J.scratch.surviving dir t) (J.allocation.row (idx, t)) i
+
+/-- Concrete field, address, offsets and bits at every visit of the party scan. -/
+noncomputable def Job.row : (c : At party side) → Fin (frames count sub c.val) → ResidentColumn.Row
+ | ⟨none, h⟩, i => J.abRow (decide (party = 1)) (by simpa using ab_hit h) i
+ | ⟨some (dir, t), h⟩, i => J.supplyRow dir t (supply_hit dir t h) i
+
+/-- All input packet cells lie before staging and all staged widths fit their designated strides. -/
+structure Job.Packets (endAddr : ℕ) (priv : Word w → Word w) : Prop where
+ old : ∀ dir hit, ShrinkOldHalves.PlacedPackets X side J.arena J.nodes priv
+ (ShrinkOldHalves.abSite X m dir) (J.abHalf dir hit) endAddr
+ oldEnd : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ J.scratch.staging
+ parentFit : (Packet.mk J.node (packed (outState) atSite J.parent)).Fits J.arena w endAddr
+ parentStored : (Packet.mk J.node (packed (outState) atSite J.parent)).Stored J.arena
+ (DFS.scratch endAddr priv)
+ parentEnd : J.arena.base J.node + (packed (outState) atSite J.parent).length ≤ J.scratch.staging
+ abStride : abWidth ≤ J.scratch.stride
+ abRoom : J.scratch.staging + abWidth < 2 ^ w
+ supplyStride : ∀ t, (width) m t ≤ J.scratch.stride
+ supplyRoom : ∀ dir t, J.scratch.surviving dir t + (width) m t < 2 ^ w
+
+set_option maxHeartbeats 800000 in
+-- Check the selected graph against the dependent site and half-word coordinates.
+private theorem Job.conditions {endAddr : ℕ} {priv : Word w → Word w}
+ (ps : J.Packets endAddr priv) (c : At party side) (i : Fin (frames count sub c.val)) :
+ (J.row c i).reads priv ∧ (J.row c i).Fits w J.scratch.staging ∧
+ InBuffer J.scratch J.row c i := by
+ rcases c with ⟨_ | ⟨dir, t⟩, h⟩
+ · let dir := decide (party = 1)
+ have hit : party = if dir then 1 else 0 := by simpa [dir] using ab_hit h
+ let x := J.abHalf dir hit
+ have stored := ps.old dir hit
+ refine ⟨ShrinkAB.Physical.reads X m J.arcFit J.bucketFit i J.arena J.nodes side dir x
+ priv stored, ShrinkAB.Physical.fits X m J.arcFit J.bucketFit i J.arena J.nodes side dir x
+ J.scratch.staging ps.oldEnd le_rfl ps.abRoom stored, ?_⟩
+ apply inBuffer_of J.scratch J.row _ i rfl
+ intro hp
+ exact (ab_bound X m J.arcFit J.bucketFit i J.arena J.nodes side dir x J.first
+ J.scratch.staging hp).trans ps.abStride
+ · let hit := supply_hit dir t h
+ let z := J.half dir t hit
+ let bank := J.allocation.row (idx, t)
+ let dst := J.scratch.surviving dir t
+ have same := J.packed_half dir t hit
+ refine ⟨ShrinkSurvivingColumn.reads X side sub (width) slots m t dir z J.arena J.node dst bank
+ priv (same.symm ▸ ps.parentFit) (same.symm ▸ ps.parentStored) i,
+ ShrinkSurvivingColumn.fits X side sub (width) slots m t dir z J.arena J.node dst bank
+ ready.count_pos J.scratch.staging (same.symm ▸ ps.parentEnd) (Nat.le_add_right _ _)
+ (ps.supplyRoom dir t) i, ?_⟩
+ apply inBuffer_of J.scratch J.row _ i rfl
+ exact fun _ ↦ (surviving_bound X side sub (width) slots m t dir z J.arena J.node dst bank
+ ready.count_pos i).trans (ps.supplyStride t)
+
+variable (O : ShrinkCallHeader.Operands) (nodeExpr : PhaseRecipe.Expr)
+variable (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+
+/-- Construct the surviving gather operands for one orientation and role using the old level,
+motif, parent node, and the role's staging destination. -/
+def supplyInputs (a : ℕ) (dir : Bool) (t : Fin 4) :=
+ ShrinkSurvivingSelected.inputs a O.level O.motif O.arguments O.argumentStride nodeExpr
+ ((O.inputs a).surviving dir t)
+
+/-- Generate the native register setup for each active AB or surviving copy at this party,
+using the old and new degree exponents. -/
+noncomputable def setups (a b : ℕ) (party : Fin 6) (layout : Bool) :=
+ let d := 2 ^ a
+ let c := Shrink.colors a
+ let profile := subdivisions d c (2 ^ b)
+ ShrinkPartyColumns.setup party layout (2 ^ c * d / 4) profile d (2 ^ b) (pieceCount d c)
+ (O.cdHeader a).fields (supplyInputs O nodeExpr a)
+
+/-- Old-level columns, ranked original ID lists and the selected AB interval bank. -/
+structure Job.OldPublished (level : Word w) (T : IncidenceDirectory w) (origin : ℕ) : Prop where
+ levelData : ShrinkCallHeader.Level X F sel level mem T origin J.older J.pitch J.first
+ live : ShrinkCallHeader.Live X m O pub state level mem J.arena J.scratch.hidden J.scratch.stride
+ J.scratch.hist
+ motifCount : J.scratch.motifs = ShrinkTermInputs.motifCount X
+ tables : ShrinkCallHeader.OldTables X mem T origin
+ space : (ShrinkInput.plan X origin).stop < 2 ^ w
+ allocation : ShrinkABSliceTable.Layout (ShrinkInput.thickBank X T origin)
+ (ShrinkInput.piecesBank X T origin) buckets count pieces J.first
+ bankWords : IndexedStarts.Stored (ShrinkABSliceTable.bank (w := w) J.first count pieces
+ (BundleLists.portIndex (Shrink.packedIndex (a := a) (g := g) X.baseIndex)
+ (X.packingData.bundle m)).val)
+ (ShrinkSliceArrays.thickWidths X.packingData X.shrinkOrder X.packingWidth
+ (X.packingData.bundle m))
+ (ShrinkSliceArrays.abWidths X.packingData X.shrinkNumber X.packingWidth
+ (X.packingData.bundle m)) mem
+
+/-- The common selected slot and interval images. The per-endpoint destinations are the
+staging expressions in the very same six-party call header. -/
+structure Job.SupplyPublished (heads : SlotLevel.Heads) (absolute : Word w)
+ (U : IncidenceDirectory w) (layer pitch : ℕ) : Prop where
+ tableHeads : ∀ dir t, ShrinkSurvivingSelected.Published X (supplyInputs O nodeExpr a dir t).tables
+ m heads absolute (b := b) (pub := pub) (state := state) (mem := mem)
+ directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absolute mem
+ sorted : Build.OrderedTables X ready side heads mem
+ absFit : absolute.val + (idx).val < 2 ^ w
+ slotFit : finish (levelShape (b := b) X) heads < 2 ^ w
+ degreeFit : 2 ^ b < 2 ^ w
+ twoFit : 2 < 2 ^ w
+ allocation : J.allocation.Fits
+ images : ∀ i, Image (J.allocation.row i)
+ (selected X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) J.allocation
+ F X.packingWidth sel i) mem
+ half : ∀ dir t, (supplyInputs O nodeExpr a dir t).half.Stored U J.arena layer pitch pub state mem
+ incidence : U.ActualColumns (outState) mem
+ capacity : Fintype.card (outState).Base * 2 ^ g * 2 ^ b ≤ 2 ^ w
+ nodeWord : nodeExpr.eval pub state mem = (J.node : Word w)
+ destination : ∀ dir t, ((O.inputs a).surviving dir t).eval pub state mem =
+ (J.scratch.surviving dir t : Word w)
+ interval : ∀ dir t, (supplyInputs O nodeExpr a dir t).tables.intervalHead.eval pub state mem =
+ (J.allocation.widthEnd : Word w)
+
+variable {level absolute : Word w} {T U : IncidenceDirectory w} {origin layer pitch : ℕ}
+variable {heads : SlotLevel.Heads}
+variable (old : J.OldPublished O pub state mem level T origin)
+variable (next : J.SupplyPublished O nodeExpr pub state mem heads absolute U layer pitch)
+
+set_option maxHeartbeats 1000000 in
+-- Reduce the packed site, actual endpoint row and the level's stored numbering together.
+include old next in
+private theorem Job.recorded (c : At party side) (i : Fin (frames count sub c.val)) :
+ (J.row c i).Recorded (setups O nodeExpr a b party side c i) pub state mem := by
+ rcases c with ⟨_ | ⟨dir, t⟩, hc⟩
+ · let dir := decide (party = 1)
+ have hit : party = if dir then 1 else 0 := by simpa [dir] using ab_hit hc
+ have scratchEq : ShrinkCallHeader.scratch X J.scratch.hidden J.scratch.stride J.scratch.hist =
+ J.scratch := by
+ unfold ShrinkCallHeader.scratch
+ rw [← old.motifCount]
+ have h := ShrinkCallHeader.ab_recorded X F sel m O pub state level mem J.arena T origin
+ J.older J.pitch J.first J.scratch.hidden J.scratch.stride J.scratch.hist
+ old.levelData old.live old.tables old.space old.allocation old.bankWords dir
+ (J.abHalf dir hit) i
+ dsimp only at h
+ rw [scratchEq] at h
+ exact h
+ · exact ShrinkSurvivingSelected.recorded X ready m t dir i F sel J.term J.stride J.widthBase
+ (supplyInputs O nodeExpr a dir t) heads absolute U J.arena J.node (J.scratch.surviving dir t)
+ layer pitch (J.half dir t (supply_hit dir t hc)) (next.tableHeads dir t) next.directory
+ next.sorted next.absFit next.slotFit next.degreeFit next.twoFit next.allocation next.images
+ (next.half dir t) next.incidence next.capacity next.nodeWord (next.destination dir t)
+ (next.interval dir t)
+
+private noncomputable def widths (m' : X.packingData.Motif) (e : Bool × Fin 4) : ℕ :=
+ X.packingData.termWidths F X.shrinkNumber X.packingWidth sel m' e.1 e.2
+
+/-- Values consumed by the demand and supply map readers after all frames execute. -/
+structure Job.Assembled (before after : Word w → Word w) : Prop where
+ retained : ShrinkCallSupplyCells.Retained X side sub (widths (F := F) (sel := sel)) slots
+ m party J.scratch J.parent before after
+ ab : ∀ (dir : Bool) (hit : party = if dir then 1 else 0) (i : Fin abWidth),
+ after ((J.scratch.staging + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (ShrinkCallDemandCells.abBit X side m dir (hit ▸ J.old) i)
+ below : ∀ x : Word w, x.val < J.scratch.staging → after x = before x
+
+set_option maxHeartbeats 800000 in
+-- Identify both orientations of the selected new half with the typed map's local arguments.
+private theorem Job.assembled {before after : Word w → Word w} {endAddr : ℕ}
+ (ps : J.Packets endAddr before)
+ (staged : ∀ c : At party side, ∀ addr : Word w, base J.scratch c.val ≤ addr.val →
+ addr.val < base J.scratch c.val + J.scratch.stride →
+ after addr = ResidentColumn.writes (J.row c) (List.finRange _) before addr)
+ (below : ∀ x : Word w, x.val < J.scratch.staging → after x = before x) :
+ J.Assembled before after := by
+ refine ⟨?_, ?_, below⟩
+ · intro dir t hit site halves dst i
+ have active : some (dir, t) ∈ columns party side := by
+ apply (mem_columns ..).mpr
+ change decide (party = ShrinkCallFields.supplyParty dir (side, t)) = true
+ apply decide_eq_true
+ cases dir <;> exact hit
+ let c : At party side := ⟨some (dir, t), active⟩
+ let addr : Word w := ((dst + i.val : ℕ) : Word w)
+ have hlt : i.val < (width) m t := i.isLt
+ have val : addr.val = dst + i.val := Nat.mod_eq_of_lt (by
+ have room := ps.supplyRoom dir t
+ change dst + (width) m t < 2 ^ w at room
+ omega)
+ apply staged c addr (by rw [val]; exact Nat.le_add_right _ _) ?_
+ change addr.val < dst + J.scratch.stride
+ rw [val]
+ exact Nat.add_lt_add_left (hlt.trans_le (ps.supplyStride t)) _
+ · intro dir hit i
+ have active : none ∈ columns party side := by
+ apply (mem_columns ..).mpr
+ change decide (party = 0 ∨ party = 1) = true
+ cases dir <;> simp_all
+ let c : At party side := ⟨none, active⟩
+ let addr : Word w := ((J.scratch.staging + i.val : ℕ) : Word w)
+ have val : addr.val = J.scratch.staging + i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans ps.abRoom)
+ refine (staged c addr (by rw [val]; exact Nat.le_add_right _ _)
+ (by rw [val]; exact Nat.add_lt_add_left (i.isLt.trans_le ps.abStride) _)).trans ?_
+ have wd := ShrinkCallDemandCells.ab_written X side m J.arena J.nodes dir (hit ▸ J.old)
+ J.arcFit J.bucketFit J.first J.scratch.staging before ps.abRoom.le i
+ cases dir <;> subst party <;> exact wd
+
+local notation "setupAt" => setups O nodeExpr a b party side
+local notation "flatSetup" => gather party side count sub setupAt
+local notation "flatRow" => gather party side count sub (Job.row J)
+
+open private writes_congr from OAI.Computability.VPVNP.PairShrinkPartyColumns
+
+/-- The native update restricted to the upper private scratch. -/
+noncomputable def Job.updated (endAddr : ℕ) (before : DFS.Scratch w endAddr) :
+ DFS.Scratch w endAddr :=
+ DFS.scratch endAddr (ResidentColumn.writes flatRow (List.finRange _) (rawScratch before))
+
+/-- The public trace of a fixed resident job. -/
+noncomputable def Job.trace :=
+ ResidentColumn.trace flatSetup flatRow (List.finRange _) pub state mem
+
+include old next in
+/-- The installed rows return the typed map fields, the exact chronological trace and the
+upper-scratch update. Private cells below the stack boundary are preserved. -/
+theorem native_party_reads {p r k : ℕ} (M : Machine w p r k)
+ (vm : ∀ i, Fin (RegisterSetup.regCount ((flatSetup i).operands)) ↪ Fin r)
+ (inputs : Fin 6 → Fin r) (loc : ResidentColumn.Label flatSetup → Fin p) (ret : Fin p)
+ (code : ∀ l, M.code (loc l) = ResidentColumn.instruction flatSetup vm inputs loc ret l)
+ (safe : ∀ i v j, vm i v ≠ inputs j)
+ (allowed : ℕ → Prop) (sites : ∀ c i, (J.row c i).ReadSafe (setupAt c i) allowed pub state mem)
+ (cfg : Config w p r) (entry : cfg.pc = ResidentColumn.start flatSetup loc ret 0)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state)
+ {endAddr : ℕ} (ps : J.Packets endAddr cfg.privateMem) :
+ let es := J.trace O nodeExpr pub state mem
+ ∃ out, ResidentColumn.Result flatSetup vm M ret flatRow
+ (List.finRange (visits party side count sub).length) mem cfg out es ∧
+ J.Assembled cfg.privateMem out.privateMem ∧ SourceTransport.Reads allowed es ∧
+ DFS.scratch endAddr out.privateMem = J.updated endAddr (DFS.scratch endAddr cfg.privateMem) ∧
+ (∀ a : Word w, a.val < endAddr → out.privateMem a = cfg.privateMem a) := by
+ intro es
+ obtain ⟨out, res, reads⟩ := ResidentColumn.native_exact M loc ret code safe flatRow mem pub state
+ (fun _ ↦ J.recorded O nodeExpr pub state mem old next _ _) J.scratch.staging
+ (fun _ ↦ (J.conditions ps _ _).2.1) allowed (fun _ ↦ sites _ _) cfg entry hp hs
+ (fun _ ↦ (J.conditions ps _ _).1)
+ have eqMem := res.memory
+ have staged := ShrinkPartyColumns.memory J.scratch J.row J.scratch.staging
+ (fun c i ↦ (J.conditions ps c i).2.1) (fun c i ↦ (J.conditions ps c i).2.2) cfg.privateMem
+ have assm := J.assembled (after := out.privateMem) ps
+ (fun c a lo hi ↦ (congrFun eqMem a).trans (staged.1 c a lo hi))
+ (fun a below ↦ (congrFun eqMem a).trans (staged.2 a below))
+ refine ⟨out, res, assm, reads, ?_, ?_⟩
+ · funext a
+ change out.privateMem a.val = ResidentColumn.writes flatRow (List.finRange _) _ a.val
+ rw [eqMem]
+ exact writes_congr _ _ a.val (by simp [rawScratch, a.property, DFS.scratch])
+ · intro a ha
+ apply assm.below
+ have first : endAddr ≤ J.arena.base J.node := ps.parentFit.1
+ have last := ps.parentEnd
+ omega
+
+include old next in
+/-- Run every real AB and surviving frame of the selected resident map, in one linked program.
+The resulting private state supplies the bits of its typed matrix call. -/
+theorem native_party {p r k : ℕ} (M : Machine w p r k)
+ (vm : ∀ i, Fin (RegisterSetup.regCount ((flatSetup i).operands)) ↪ Fin r)
+ (inputs : Fin 6 → Fin r) (loc : ResidentColumn.Label flatSetup → Fin p) (ret : Fin p)
+ (code : ∀ l, M.code (loc l) = ResidentColumn.instruction flatSetup vm inputs loc ret l)
+ (safe : ∀ i v j, vm i v ≠ inputs j)
+ (cfg : Config w p r) (entry : cfg.pc = ResidentColumn.start flatSetup loc ret 0)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state)
+ {endAddr : ℕ} (ps : J.Packets endAddr cfg.privateMem) :
+ ∃ events out, ResidentColumn.Result flatSetup vm M ret flatRow
+ (List.finRange (visits party side count sub).length) mem cfg out events ∧
+ J.Assembled cfg.privateMem out.privateMem := by
+ obtain ⟨ev, out, run, staged, below⟩ := ShrinkPartyColumns.native J.scratch J.row
+ J.scratch.staging (fun c i ↦ (J.conditions ps c i).2.1)
+ (fun c i ↦ (J.conditions ps c i).2.2) setupAt M vm inputs loc ret code safe
+ mem pub state (J.recorded O nodeExpr pub state mem old next) cfg entry hp hs
+ (fun c i ↦ (J.conditions ps c i).1)
+ exact ⟨ev, out, run, J.assembled ps staged below⟩
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPartyOutputHeader.lean b/lean/OAI/Computability/VPVNP/PairShrinkPartyOutputHeader.lean
new file mode 100644
index 0000000000..366649605f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPartyOutputHeader.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.PairShrinkPartyNative
+
+/-!
+# Publishing the surviving-column inputs of a resident shrinking party
+
+The eight endpoint programs share the same incidence, motif, inverse-slot
+and interval bases. Only their private destinations differ. Reading the
+two level headers therefore supplies the recorded setup for every incident
+subdivision of the resident map.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.State Compression.PackingData
+open Compression.ShrinkMotif Compression.ShrinkEnergy MotifBlocks MotifGrid MotifConversion
+open CompressorRecords CompressorRecords.PhaseRecipe CompressorRecords.ShrinkSlots
+open CompressorRecords.ShrinkSliceSweep
+open scoped Fin.CommRing
+
+variable {a b g w : ℕ} {δ factor : ℝ} {K : Type*} [_root_.Field K]
+variable {X : State a (packingLaneBits a g)}
+variable {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+variable {m : X.packingData.Motif} {party : Fin 6} (J : Job X F ready sel m party w)
+variable (O : ShrinkCallHeader.Operands) (node : Expr) {pub : Fin 5 → Word w}
+variable {state level absolute : Word w} {mem : Memory w} {origin : ℕ} {T : IncidenceDirectory w}
+variable (old : J.OldPublished O pub state mem level T origin)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+private theorem cast_val (v : Word w) : (v.val : Word w) = v := by simp
+
+private theorem cell_at (i : ℕ) (fit : level.val + i < 2 ^ w) :
+ (level + (i : Word w)).val = level.val + i := by
+ calc
+ _ = (((level.val + i : ℕ) : Word w)).val := by rw [Nat.cast_add, cast_val]
+ _ = _ := Nat.mod_eq_of_lt fit
+
+local notation "idx" => ShrinkMotifOrder.stateNumber X m
+local notation "s" => levelShape (b := b) X
+local notation "side" => selectedLayout X F sel
+local notation "Y" => X.shrinkNext F ready sel
+
+include old in
+/-- From the two physical level headers and selected array images, recover all the
+publication hypotheses for the compiled party without separate endpoint assumptions. -/
+theorem Job.SupplyPublished.of_header (heads : SlotLevel.Heads) (U : IncidenceDirectory w)
+ (next layer pitch : ℕ)
+ (oldRoom : level.val + 42 < 2 ^ w) (newRoom : next + 59 < 2 ^ w)
+ (absoluteAt : mem (level.val + 39) = absolute)
+ (nextAt : mem (level.val + 40) = (next : Word w))
+ (inverseAt : mem (level.val + 41) = (SlotLevel.inverseHead s heads : Word w))
+ (intervalAt : mem (level.val + 42) = (J.allocation.widthEnd : Word w))
+ (layerAt : mem (next + 14) = (layer : Word w)) (pitchAt : mem (next + 15) = (pitch : Word w))
+ (outAt : mem (next + 57) = U.actualOut) (inAt : mem (next + 58) = U.actualIn)
+ (widthAt : mem (next + 59) = U.width)
+ (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absolute mem)
+ (sorted : Build.OrderedTables X ready side heads mem)
+ (absFit : absolute.val + (idx).val < 2 ^ w) (slotFit : finish s heads < 2 ^ w)
+ (degreeFit : 2 ^ b < 2 ^ w) (twoFit : 2 < 2 ^ w) (lanesFit : 2 ^ g < 2 ^ w)
+ (allocation : J.allocation.Fits)
+ (images : ∀ i, Image (J.allocation.row i)
+ (selected X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) J.allocation
+ F X.packingWidth sel i) mem)
+ (incidence : U.ActualColumns (Y) mem)
+ (capacity : Fintype.card (Y).Base * 2 ^ g * 2 ^ b ≤ 2 ^ w)
+ (nodeWord : node.eval pub state mem = (J.node : Word w)) :
+ J.SupplyPublished O node pub state mem heads absolute U layer pitch := by
+ have motif : O.motif.eval pub state mem = ((idx).val : Word w) := by
+ rw [← old.live.motif]
+ exact (cast_val _).symm
+ have vertices : mem (level.val + 0) = (Fintype.card X.Base : Word w) := by
+ rw [← cell_at 0 (by omega : level.val + 0 < 2 ^ w)]
+ exact old.levelData.vertices
+ have lane : mem (level.val + 3) = ((2 ^ g : ℕ) : Word w) := by
+ rw [← cell_at 3 (by omega : level.val + 3 < 2 ^ w)]
+ exact old.levelData.residual
+ have laneVal : (mem (level.val + 3)).val = 2 ^ g := by rw [lane]; exact Nat.mod_eq_of_lt lanesFit
+ have read (d : Bool) (t : Fin 4) := ShrinkSurvivingSelected.inputs_readback X m heads absolute
+ level.val next J.allocation.widthEnd U J.arena layer pitch O.level O.motif O.arguments
+ O.argumentStride node ((O.inputs a).surviving d t) (old.live.header.trans (cast_val level).symm)
+ motif old.live.arguments old.live.argumentStride oldRoom newRoom vertices laneVal
+ absoluteAt nextAt inverseAt intervalAt layerAt pitchAt outAt inAt widthAt
+ refine ⟨fun d t ↦ (read d t).1, directory, sorted, absFit, slotFit, degreeFit, twoFit,
+ allocation, images, fun d t ↦ (read d t).2.1, incidence, capacity, nodeWord, ?_,
+ fun d t ↦ (read d t).2.2⟩
+ intro dir t
+ have vertexExpr : (O.cell 0).eval pub state mem = (Fintype.card X.Base : Word w) := by
+ change mem (O.level.eval pub state mem + 0).val = _
+ rw [old.live.header]
+ exact old.levelData.vertices
+ have laneExpr : (O.cell 3).eval pub state mem = ((2 ^ g : ℕ) : Word w) := by
+ change mem (O.level.eval pub state mem + 3).val = _
+ rw [old.live.header]
+ exact old.levelData.residual
+ have count := ShrinkCallHeader.count_eq X O pub state mem vertexExpr laneExpr
+ have stage : (O.staging a).eval pub state mem = (J.scratch.staging : Word w) := by
+ change O.hidden.eval pub state mem + 4 * (O.count a).eval pub state mem *
+ O.slotStride.eval pub state mem = _
+ rw [old.live.hiddenBase, old.live.stride, count, ← old.motifCount]
+ simp [ShrinkCallFields.Scratch.staging]
+ change (O.staging a).eval pub state mem + ((1 + dir.toNat * 4 + t.val : ℕ) : Word w) *
+ O.slotStride.eval pub state mem = _
+ rw [stage, old.live.stride, ← Nat.cast_mul, ← Nat.cast_add]
+ rfl
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPartyReadAreas.lean b/lean/OAI/Computability/VPVNP/PairShrinkPartyReadAreas.lean
new file mode 100644
index 0000000000..c41c64bcb9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPartyReadAreas.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.PairShrinkPartyABReads
+import OAI.Computability.VPVNP.PairShrinkPhysicalSourceBounds
+
+/-! # Public AB read areas of a physical shrinking party
+
+The old incidence columns use the actual number of outgoing arcs. The
+classification and AB intersection tables fit their successive allocations
+before the next level header.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkResidentSources
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords
+open CompressorRecords.DescriptorSpace CompressorRecords.ShrinkBlockInputs
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {i : Fin S.steps}
+variable {w g : ℕ} {δ : ℝ} {X : State (a i) (packingLaneBits (a i) g)}
+variable {ready : Ready (2 ^ a i) (Shrink.colors (a i)) (2 ^ b i) δ}
+variable {sel : SelectedScore.Selection B X} {m : X.packingData.Motif} {party : Fin 6}
+variable {base : Word w} {positions blocks cur H : ℕ}
+
+local notation "lay" => BlockProgram.layout B base.val positions blocks
+local notation "cut" => tableBase lay cur (0 : Fin 6)
+local notation "first" => tableBase lay cur (1 : Fin 6)
+local notation "source" => packedIncidence lay w cur (DemandRAM.oldCount X)
+
+/-- The live shrinking level supplies all external bounds required by a
+genuine AB job, including the last indexed three-word frame. -/
+theorem Bounds.party_abAreas (bounds : Bounds B i X base positions blocks cur)
+ (J : ShrinkPartyNative.Job X B.shrink ready sel m party w)
+ (firstEq : J.first = first) (nextLe : levelStart lay (cur + 1) ≤ H) :
+ J.ABAreas (levelStart lay cur : Word w) source cut H := by
+ have tab (j : Fin 6) : tableBase lay cur j ≤ H :=
+ (Nat.le_add_right _ _).trans ((tableEnd_le_nextLevel lay cur j).trans nextLe)
+ have cutEq : cut = incidenceStart lay cur + 6 * slotCapacity lay := by
+ simp only [tableBase, arrayBase, Fin.val_zero, Nat.zero_mul, Nat.add_zero]
+ have column (j : Fin 6) : ((source).column j).val + DemandRAM.oldCount X ≤ H := by
+ rw [packed_column]
+ have within := Nat.mul_le_mul_right (DemandRAM.oldCount X) j.isLt
+ rw [Nat.succ_mul] at within
+ have cap := Nat.mul_le_mul_left 6 bounds.oldCapacity
+ change 6 * DemandRAM.oldCount X ≤ 6 * slotCapacity lay at cap
+ change (incidenceStart lay cur + j.val * DemandRAM.oldCount X) % 2^w + _ ≤ _
+ exact (Nat.add_le_add_right (Nat.mod_le ..) _).trans
+ (by have h := tab 0; rw [cutEq] at h; omega)
+ have head : levelStart lay cur + 66 = incidenceStart lay cur := rfl
+ have classEnd : (ShrinkInput.plan X cut).stop ≤ ShrinkInput.stop X cut :=
+ (ShrinkInput.range_bounds X cut).2.2.2
+ refine ⟨?_, classEnd.trans (bounds.fresh.trans (tab 1)), column 3, column 4, column 5, ?_⟩
+ · have before := tab 0
+ rw [cutEq, ← head] at before
+ exact (Nat.add_le_add_right (Nat.mod_le ..) _).trans (by omega)
+ · rw [firstEq]
+ exact bounds.widthAfter.trans (tab 2)
+
+end PairSimulation.ShrinkResidentSources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPartyReadBounds.lean b/lean/OAI/Computability/VPVNP/PairShrinkPartyReadBounds.lean
new file mode 100644
index 0000000000..1000289acf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPartyReadBounds.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.PairShrinkPartyABReads
+import OAI.Computability.VPVNP.PairShrinkSurvivingReadBounds
+import OAI.Computability.VPVNP.PairSimulationFieldReadSafety
+
+/-!
+# External read region of the selected shrinking-party gather
+
+All runtime reads of the emitted gather come from the two level headers,
+the old sorted-bundle tables, the output incidence and width columns, the
+absolute motif and inverse-slot tables, or the assigned slice banks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open Compression.ShrinkEnergy MotifBlocks MotifGrid MotifConversion CompressorRecords
+open CompressorRecords.ShrinkSlots CompressorRecords.ShrinkSliceSweep
+open CompressorRecords.PhaseRecipe ShrinkPartyColumns
+open scoped Fin.CommRing
+
+variable {a b g w : ℕ} {δ factor : ℝ} {K : Type*} [_root_.Field K]
+variable {X : State a (packingLaneBits a g)}
+variable {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {ready : ShrinkMotif.Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+variable {m : X.packingData.Motif} {party : Fin 6} (J : Job X F ready sel m party w)
+local notation "shape" => levelShape (b := b) X
+local notation "sub" => SlotLevel.Shape.subdivisions (levelShape (b := b) X)
+local notation "side" => selectedLayout X F sel
+local notation "idx" => ShrinkMotifOrder.stateNumber X m
+local notation "count" => 2 ^ (Shrink.colors a) * 2 ^ a / 4
+local notation "N" => Fintype.card (State.Base (X.shrinkNext F ready sel)) * 2 ^ g * 2 ^ b
+
+/-- The selected next-state arrays and the interval bank lie below the terminal header.
+The pointer in old header cell 40 is the same next header used to look up the incidence heads. -/
+structure Job.SupplyAreas (level absolute : Word w) (heads : SlotLevel.Heads)
+ (U : IncidenceDirectory w) (nextHead H : ℕ) (mem : Memory w) : Prop where
+ pointer : mem (level.val + 40) = (nextHead : Word w)
+ header : nextHead + 60 ≤ H
+ motifs : absolute.val + ShrinkTermInputs.motifCount X ≤ H
+ inverse : SlotLevel.targetsHead shape heads ≤ H
+ incoming : U.actualIn.val + N ≤ H
+ widths : U.width.val + N ≤ H
+ intervals : J.allocation.last ≤ H
+
+variable {pub : Fin 5 → Word w} {state level absolute : Word w} {mem : Memory w}
+variable {origin nextHead layer pitch : ℕ} {T U : IncidenceDirectory w} {heads : SlotLevel.Heads}
+
+theorem Job.readSafe (O : ShrinkCallHeader.Operands) (node : Expr) (H : Word w)
+ (terminalRoom : H.val + 31 < 2 ^ w)
+ (old : J.OldPublished O pub state mem level T origin)
+ (next : J.SupplyPublished O node pub state mem heads absolute U layer pitch)
+ (ins : InputsReadable O H.val pub state mem)
+ (nodeSafe : node.ReadsFrom (· < H.val) pub state mem)
+ (oldSpace : J.ABAreas level T origin H.val)
+ (space : J.SupplyAreas level absolute heads U nextHead H.val mem)
+ (c : At party side) (i : Fin (frames count sub c.val)) :
+ (J.row c i).ReadSafe (setups O node a b party side c i) (TerminalLink.workerCell H)
+ pub state mem := by
+ have below : (J.row c i).ReadSafe (setups O node a b party side c i) (· < H.val)
+ pub state mem := by
+ rcases c with ⟨_ | ⟨dir, t⟩, hc⟩
+ · obtain ⟨loads, cells⟩ := J.ab_readBounds O node old ins oldSpace hc i
+ exact ⟨loads, cells⟩
+ · let P := supplyInputs O node a dir t
+ have oldRoom : (O.level.eval pub state mem).val + 42 < H.val := by
+ rw [old.live.header]; have := oldSpace.levelEnd; omega
+ have nextRoom : ((ShrinkSurvivingSelected.cell O.level 40).eval pub state mem).val + 59 <
+ H.val := by
+ change (mem (O.level.eval pub state mem + (40 : Word w)).val).val + 59 < _
+ rw [old.live.header, Fin.val_add]
+ have len : (40 : Word w).val = 40 := by
+ change 40 % (2 ^ w) = 40
+ exact Nat.mod_eq_of_lt (by omega)
+ have nextFit : nextHead < 2 ^ w := by have := space.header; omega
+ rw [len, Nat.mod_eq_of_lt (by have := oldSpace.levelEnd; omega),
+ space.pointer, Fin.val_natCast, Nat.mod_eq_of_lt nextFit]
+ have := space.header
+ omega
+ obtain ⟨table, fields⟩ := ShrinkSurvivingReadBounds.inputs_reads a O.level O.motif O.arguments
+ O.argumentStride node ((O.inputs a).surviving dir t) ins.level ins.motif ins.arguments
+ ins.stride oldRoom nextRoom
+ have dst := ShrinkSurvivingReadBounds.destination_reads O a dir t ins.level ins.hidden
+ ins.slot (by omega)
+ have denseLt : (idx).val < ShrinkTermInputs.motifCount X :=
+ ((ShrinkMotifOrder.entries X).symm m).isLt
+ have absRoom := (Nat.add_lt_add_left denseLt absolute.val).trans_le space.motifs
+ refine ⟨ShrinkSurvivingReadBounds.setup_reads X P m t dir i ready side (branchWidth X F sel)
+ heads absolute (next.tableHeads dir t) table next.directory next.sorted next.absFit
+ absRoom space.inverse next.slotFit next.degreeFit next.twoFit U J.arena
+ (next.half dir t) fields nodeSafe dst next.incidence next.capacity space.incoming
+ space.widths, ?_⟩
+ intro k
+ have frame := (ShrinkSurvivingReadBounds.frame_end J.allocation next.allocation idx t i)
+ |>.trans_le space.intervals
+ change ShrinkSurvivingFrames.head (J.allocation.row (idx, t)) (sub t) i + k.val < _
+ exact (Nat.add_le_add_left (show k.val ≤ 2 from Nat.le_of_lt_succ k.isLt) _).trans_lt frame
+ exact ⟨fun j ↦ TerminalLink.expr_worker_reads terminalRoom (below.loads j),
+ fun k ↦ TerminalLink.workerCell_of_lt terminalRoom (below.frame k)⟩
+
+/-- The six concrete register operands satisfy the whole-program read condition using
+only the assigned table extents and the published level pointers. -/
+theorem Job.abi_readSafe (degree : ℕ) (H : Word w) (terminalRoom : H.val + 31 < 2 ^ w)
+ (old : J.OldPublished (ShrinkCallABI.operands degree) pub state mem level T origin)
+ (next : J.SupplyPublished (ShrinkCallABI.operands degree) ShrinkCallABI.node pub state mem heads
+ absolute U layer pitch)
+ (oldSpace : J.ABAreas level T origin H.val)
+ (space : J.SupplyAreas level absolute heads U nextHead H.val mem)
+ (c : At party side) (i : Fin (frames count sub c.val)) :
+ (J.row c i).ReadSafe
+ (setups (ShrinkCallABI.operands degree) ShrinkCallABI.node a b party side c i)
+ (TerminalLink.workerCell H) pub state mem :=
+ J.readSafe _ _ H terminalRoom old next (J.abi_inputs_readable degree old oldSpace) trivial
+ oldSpace space c i
+
+variable (degree : ℕ) (H : Word w)
+local notation "operands" => ShrinkCallABI.operands degree
+local notation "flatSetup" =>
+ gather party side count sub (setups operands ShrinkCallABI.node a b party side)
+local notation "flatRow" => gather party side count sub (Job.row J)
+
+/-- The concrete ABI run excludes the terminal control cells. Both the returning upper
+scratch and the successful trace are explicit functions of the decoded resident inputs. -/
+theorem native_party_worker {p r k : ℕ}
+ (terminalRoom : H.val + 31 < 2 ^ w)
+ (old : J.OldPublished operands pub state mem level T origin)
+ (next : J.SupplyPublished operands ShrinkCallABI.node pub state mem heads absolute U
+ layer pitch)
+ (oldSpace : J.ABAreas level T origin H.val)
+ (space : J.SupplyAreas level absolute heads U nextHead H.val mem)
+ (M : Machine w p r k) (vm : ∀ i, Fin (RegisterSetup.regCount ((flatSetup i).operands)) ↪ Fin r)
+ (inputs : Fin 6 → Fin r) (loc : ResidentColumn.Label flatSetup → Fin p) (ret : Fin p)
+ (code : ∀ l, M.code (loc l) = ResidentColumn.instruction flatSetup vm inputs loc ret l)
+ (safe : ∀ i v j, vm i v ≠ inputs j)
+ (cfg : Config w p r) (entry : cfg.pc = ResidentColumn.start flatSetup loc ret 0)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state)
+ {endAddr : ℕ} (packets : J.Packets endAddr cfg.privateMem) :
+ let es := J.trace operands ShrinkCallABI.node pub state mem
+ ∃ out, ResidentColumn.Result flatSetup vm M ret flatRow
+ (List.finRange (visits party side count sub).length) mem cfg out es ∧
+ J.Assembled cfg.privateMem out.privateMem ∧
+ SourceTransport.Reads (TerminalLink.workerCell H) es ∧
+ DFS.scratch endAddr out.privateMem = J.updated endAddr (DFS.scratch endAddr cfg.privateMem) ∧
+ (∀ a : Word w, a.val < endAddr → out.privateMem a = cfg.privateMem a) :=
+ native_party_reads J operands ShrinkCallABI.node pub state mem old next M vm inputs loc ret code
+ safe (TerminalLink.workerCell H) (J.abi_readSafe degree H terminalRoom old next oldSpace space)
+ cfg entry hp hs packets
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPhysicalMapData.lean b/lean/OAI/Computability/VPVNP/PairShrinkPhysicalMapData.lean
new file mode 100644
index 0000000000..de4e810a5a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPhysicalMapData.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.PairShrinkPhysicalSiteBank
+import OAI.Computability.VPVNP.PairShrinkSitePhysical
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalData
+
+/-!
+# Published map operands at the physical shrinking site
+
+The actual chronological occurrence determines the parser's row and both
+layer bases. Its retained sources cover every resident map of the site.
+The numeric packet bounds use exactly the same selected job, including the
+transport of the old and parent half-wires to the map's resident party.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TraversalRows TraversalRoles
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices) {G : Group} {n limit : ℕ}
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence BlockProgram.layout
+ BlockSchedule.Templates.execute StateExecution.finalState executeLevels
+set_option quotPrecheck false
+local notation "pub" => terminalOperands G
+set_option quotPrecheck false in
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val X.positions T
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "rowEnd" => endAddress D + words B.recordLimit (selectedLayers B f hf T hT X z)
+local notation "before" j => layerBase B.recordLimit (endAddress D) tags j
+local notation "sites" => ShrinkRoleDirectory.ShrinkSite passes
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ {baseBits laneBits ord : ℕ} {calendar reference phy : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n)
+ (executeLevels B f hf T hT X z) calendar)
+ (entry : TerminalProgram.VertexEntry (w := G.w) B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+ (packed : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ord phy)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+
+/-- Every motif and party at the selected site has room for its canonical job's packets
+at the published level addresses, for each old and successor half-wire input. -/
+def PhysicalSitePackets (x : sites) : Prop :=
+ ∀ (m : x.occurrence.state.packingData.Motif) (party : Fin 6)
+ (bounds : ShrinkResidentSources.Bounds B x.occurrence.i x.occurrence.state (pub 2)
+ X.positions T x.val.1.val)
+ (old : ShrinkCallDemandCells.Old x.occurrence.state
+ (ShrinkSlots.selectedLayout x.occurrence.state B.shrink x.occurrence.selection) m party)
+ (parent : x.occurrence.nextState.network.Half (x.occurrence.state.packingData.shrinkPartySite
+ (ShrinkSlots.selectedLayout x.occurrence.state B.shrink x.occurrence.selection) m party)),
+ let J := ShrinkCanonicalJob.job B x.occurrence.i x.occurrence.state
+ (S.shrink x.occurrence.i) x.occurrence.selection m party
+ (pub 2) X.positions T x.val.1.val bounds n rowEnd (before x.val.1.val)
+ (before (x.val.1.val + 1)) old parent
+ ShrinkCanonicalJob.PacketSpace B x.occurrence.i x.occurrence.state x.occurrence.selection
+ m party J n limit
+
+set_option maxHeartbeats 1800000 in
+-- Match the selected resident and both dependent half-wire indices in the concrete job.
+/-- At every physical shrink site the selected old and successor rows and the
+fitted canonical job give all three fields of the native map's operand contract. -/
+theorem physicalSiteMapData
+ (fits : ∀ x : sites, ∀ m, canonicalFits B x.occurrence.i x.occurrence.state
+ x.occurrence.selection (w := G.w) (Fintype.card B.Entry) n rowEnd (before x.val.1.val)
+ limit m)
+ (x : sites)
+ (packets : PhysicalSitePackets (G := G) (n := n) (limit := limit) B f hf hT X z x)
+ (parent : (x.occurrence.state.shrinkNext B.shrink (S.shrink x.occurrence.i)
+ x.occurrence.selection).network.Half x.occurrence.site) :
+ CanonicalMapData (physicalSiteBank B f hf hT X z history entry packed frame width fits x)
+ (vertexHeader G) parent := by
+ let o := x.occurrence
+ obtain ⟨bounds, sources⟩ := ShrinkSiteBank.rowSources_vertex (G := G) B f hf hT X z X.positions n
+ x.val.1 o.i o.state o.selection _ o.selected history entry packed frame
+ refine ⟨?_, fun old q ↦ sources o.site old parent q, ?_⟩
+ · exact (Nat.lt_succ_self _).trans_le packed.room
+ · intro old q
+ exact packets q.1.1 q.1.2 bounds _ _
+
+end PairSimulation.ShrinkRole
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPhysicalSiteBank.lean b/lean/OAI/Computability/VPVNP/PairShrinkPhysicalSiteBank.lean
new file mode 100644
index 0000000000..7a49757eeb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPhysicalSiteBank.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCompiledSite
+import OAI.Computability.VPVNP.PairShrinkSelectedOccurrence
+import OAI.Computability.VPVNP.PairVertexCompiledPayload
+
+/-!
+# Physical shrinking sites for the terminal traversal
+
+The row's chronological origin selects the actual compressor payload and its
+output site. The address, owner, stage number, hidden fields and matrix row
+in each parser therefore belong to the branch traversed by this terminal call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TraversalRows TraversalRoles
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) {G : Group} {n limit : ℕ}
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence BlockProgram.layout
+ BlockSchedule.Templates.execute StateExecution.finalState executeLevels
+set_option quotPrecheck false
+local notation "pub" => terminalOperands G
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val X.positions T
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "rowBase" => endAddress D
+local notation "rowEnd" => rowBase + words B.recordLimit (selectedLayers B f hf T hT X z)
+local notation "labelCount" => Fintype.card B.Entry
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ {baseBits laneBits ord : ℕ} {calendar reference phy : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n)
+ (executeLevels B f hf T hT X z) calendar)
+ (entry : TerminalProgram.VertexEntry (w := G.w) B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+ (packed : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ord phy)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+
+local notation "sites" => ShrinkRoleDirectory.ShrinkSite passes
+local notation "before" j => layerBase B.recordLimit rowBase tags j
+
+/-- The operand record at every genuine shrinking row. Its source certificate
+comes from the prefix actually executed by the compressor and the protected
+memory window at this vertex. -/
+def physicalSiteBank
+ (fits : ∀ x : sites, ∀ m, canonicalFits B x.occurrence.i x.occurrence.state
+ x.occurrence.selection (w := G.w) labelCount n rowEnd (before x.val.1.val) limit m)
+ (x : sites) : CanonicalSite B x.occurrence.i x.occurrence.state x.occurrence.selection
+ x.occurrence.site G.w n labelCount := by
+ let o := x.occurrence
+ have payload := CompiledResident.shrink_vertex (G := G) history entry packed frame
+ x.val.1 o.selected
+ exact compiledSite B f hf o.i o.state o.selection o.site pub (pub 2) X.positions T x.val.1.val
+ n rowEnd (before x.val.1.val) (before (x.val.1.val + 1)) limit (passes).length
+ phy payload width (fits x)
+
+end PairSimulation.ShrinkRole
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPhysicalSiteData.lean b/lean/OAI/Computability/VPVNP/PairShrinkPhysicalSiteData.lean
new file mode 100644
index 0000000000..ea829b816c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPhysicalSiteData.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.PairShrinkPhysicalSiteBank
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalData
+import OAI.Computability.VPVNP.PairShrinkRolePackedChildren
+import OAI.Computability.VPVNP.PairShrinkSiteOrdinal
+import OAI.Computability.VPVNP.PairShrinkPackedParent
+
+/-!
+# The published operands of a shrinking site at a physical vertex call
+
+Each operand is identified in the chronological level selected by the popped
+row. The child reader, hidden reader and resident maps use the same parent
+ordinal and the same retained compressor memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TraversalRows TraversalRoles
+open NodeArguments NodeArguments.ChildScan TraversalControllerInputs ShrinkBlockInputs
+open scoped Fin.CommRing
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) {G : Group} {n limit : ℕ}
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence BlockProgram.layout
+ BlockSchedule.Templates.execute StateExecution.finalState executeLevels
+
+set_option quotPrecheck false
+local notation "pub" => terminalOperands G
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val X.positions T
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "rowsEnd" => endAddress D + words B.recordLimit (selectedLayers B f hf T hT X z)
+local notation "before" j => layerBase B.recordLimit (endAddress D) tags j
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n rowsEnd
+ (Fintype.card B.Entry)
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ {baseBits laneBits ord : ℕ} {calendar reference phy : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n)
+ (executeLevels B f hf T hT X z) calendar)
+ (entry : TerminalProgram.VertexEntry (w := G.w) B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+ (packed : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ord phy)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+ (fits : ∀ x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z), ∀ m,
+ canonicalFits B x.occurrence.i x.occurrence.state x.occurrence.selection (w := G.w)
+ (Fintype.card B.Entry) n
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T) +
+ words B.recordLimit (selectedLayers B f hf T hT X z))
+ (layerBase B.recordLimit (endAddress (BlockProgram.layout B (terminalOperands G 2).val
+ X.positions T)) (TraversalRoles.selected B f hf T hT X z) x.val.1.val) limit m)
+ (x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z))
+
+local notation "o" => x.occurrence
+local notation "site" => physicalSiteBank B f hf hT X z history entry packed frame width fits x
+local notation "id" => VertexImage.RoleDomains.siteId B f hf T hT X z x
+local notation "side" => SelectedFinish.chosen B (o).state (o).selection
+local notation "widths" => ShrinkHiddenRows.widths (o).state B.shrink (o).selection
+local notation "old" => before x.val.1.val
+local notation "new" => before (x.val.1.val + 1)
+local notation "target" => address B.recordLimit new
+ (MapResidentRows.siteIndex (o).state (o).site).val
+
+set_option maxHeartbeats 4000000 in
+-- Align the site chosen by the actual term history with the shared physical operand bank.
+/-- The complete site data, for the role image instantiated with the terminal
+worker's public words and the packed bounds of its genuine branch. -/
+theorem physicalSiteData {p r : ℕ} (M : Machine G.w p r 11) (publicWords : M.publicData = pub)
+ (wire : (o).state.maxWireWidth ≤ n)
+ (frameRoom : NativeFrame.frameBase regions + 12 ≤ 2 ^ G.w)
+ (earlier : ∀ u, childNode (o).state old B.recordLimit u < target)
+ (slots : ∀ m t, widths m (!side, t) ≤ n ^ 2)
+ (space : ShrinkCallABI.hiddenBase regions n + (ShrinkHistoryRows.hiddenOrder (o).state).length *
+ n ^ 2 ≤ 2 ^ G.w)
+ (hidden : PackedHidden.Facts B (o).i (o).state (o).selection (pub 2) X.positions T
+ x.val.1.val n regions (o).site phy) :
+ CanonicalSiteData site M f hf T hT X z x.val.1 id (endAddress D) := by
+ let j := x.val.1
+ let h := levelStart D j.val
+ have atPass := (o).selected
+ have payload := CompiledResident.shrink_vertex (G := G) history entry packed frame j atPass
+ have children := PackedChildren.of_payload B f hf T hT X z j (o).i (o).state
+ (o).selection _ atPass entry packed frame payload (o).site wire frameRoom
+ have everyChild := PackedChildren.child_geometry (G := G) B f hf T hT X z j (o).i
+ (o).state (o).selection _ atPass wire frameRoom
+ have parent := ShrinkPackedRows.packed_parent_address B f hf T hT X z (pub 2).val j (o).i
+ (o).state (o).selection _ atPass (o).site
+ have rowRoom := PackedChildren.row_fit B f hf T hT X z packed
+ have live : (vs).length < (D).levels :=
+ (executeLevels_length B f hf T hT X z).trans_lt (by rw [BlockProgram.actual_level_count]; omega)
+ obtain ⟨low, high⟩ := packed.traversal_frames frame
+ have wide : 28 ≤ (D).shape.scalarFields := by
+ unfold BlockProgram.layout
+ change 28 ≤ 54
+ decide
+ have head := entry.site_level_head live wide low high j.val j.isLt.le
+ have numeral := shrinkSiteOrdinal_eq B (o).i (o).state (o).selection (o).site
+ have idVal := VertexImage.RoleDomains.siteId_val B f hf T hT X z x
+ have hv : (h : Word G.w).val = h := Nat.mod_eq_of_lt (by
+ have bound := payload.words.oldRoom
+ change h + 65 < 2 ^ G.w at bound
+ omega)
+ refine ⟨publicWords.symm, rfl, rfl, ?_, ?_, idVal.symm, x.property, (o).index, rowRoom.2,
+ children.columns, children.strideFit, children.above, frameRoom, ?_, ?_,
+ fun u => (everyChild u).2.1,
+ fun u => (everyChild u).1, parent, ?_, wire, slots, space, hidden.selectors,
+ hidden.rowStride, ?_, ?_, hidden.countFit, hidden.count, hidden.valid,
+ hidden.scratch, hidden.pitch.trans (pow_two n).symm, hidden.owner, ?_, ?_, rfl⟩
+ · rw [publicWords]
+ exact head.1.symm
+ · change new + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal (o).nextState
+ (o).site = new + (B.recordLimit + 2) * (id).val
+ rw [numeral, idVal]
+ · intro node eqn
+ change node.val = new + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal (o).nextState (o).site at eqn
+ rw [numeral] at eqn
+ have got := children.directory node eqn
+ rw [head.1] at got
+ exact got
+ · intro _ _
+ rfl
+ · intro u
+ change childNode (o).state old B.recordLimit u < new + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal (o).nextState (o).site
+ rw [numeral]
+ exact earlier u
+ · change (h : Word G.w).val + 38 < 2 ^ G.w
+ rw [hv]
+ exact hidden.headRoom
+ · change ShrinkHiddenGuess.Header.Published _ (h : Word G.w).val phy
+ rw [hv]
+ exact hidden.headers
+ · exact compiledSite_published B f hf (o).i (o).state (o).selection (o).site pub (pub 2)
+ X.positions T j.val n rowsEnd old new limit (vs).length phy payload width (fits x)
+ · exact compiledSite_mapRoom B f hf (o).i (o).state (o).selection (o).site pub (pub 2)
+ X.positions T j.val n rowsEnd old new limit (vs).length phy payload width (fits x)
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPhysicalSourceBounds.lean b/lean/OAI/Computability/VPVNP/PairShrinkPhysicalSourceBounds.lean
new file mode 100644
index 0000000000..6ad8b3b809
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPhysicalSourceBounds.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.CompressorShrinkSlotPhysicalSpace
+import OAI.Computability.VPVNP.CompressorShrinkTablesPhysical
+import OAI.Computability.VPVNP.PairShrinkOldTableTransfer
+
+/-!
+# Physical extents of a shrinking level's resident sources
+
+Both the input and successor incidence banks fit the descriptor's slot
+capacity. The selected term rows end before the AB table. The surviving
+and ordered slot tables, and both resident directories, lie before the next
+level header.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkResidentSources
+
+open BurstRAM Compression CompressorRecords CompressorRecords.DescriptorSpace
+open CompressorRecords.ShrinkBlockInputs ShrinkSlots
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g))
+variable (base : Word w) (positions blocks cur : ℕ)
+
+local notation "lay" => BlockProgram.layout B base.val positions blocks
+local notation "cut" => tableBase lay cur (0 : Fin 6)
+local notation "first" => tableBase lay cur (1 : Fin 6)
+local notation "width" => tableBase lay cur (2 : Fin 6)
+local notation "slots" => tableBase lay cur (3 : Fin 6)
+local notation "resident" => tableBase lay cur (5 : Fin 6)
+local notation "term" => ShrinkInput.termHead (w := w) X cut
+local notation "step" => (10 : Word w)
+local notation "role" => SelectedArena.roleBase X term step
+local notation "shape" => levelShape (b := b i) X
+local notation "heads" => ShrinkOutput.heads shape role slots
+local notation "ns" => ShrinkBundlePlan.thickCount (a i)
+local notation "nt" => ShrinkBundlePlan.cap (a i)
+
+/-- Address bounds for one physical source level and its copied successor. -/
+structure Bounds : Prop where
+ nextLive : cur + 1 < (lay).levels
+ room : endAddress lay < 2 ^ w
+ oldCapacity : IncidenceDirectory.slotCount X ≤ slotCapacity lay
+ nextCapacity : actualCount shape ≤ slotCapacity lay
+ termBefore : ShrinkInput.termEnd X cut 10 ≤ first
+ termRoom : ShrinkInput.termEnd X cut 10 < 2 ^ w
+ selectedBefore : SelectedFinish.stop X term step ≤ first
+ fresh : ShrinkInput.stop X cut ≤ first
+ widthAfter : first + (ShrinkInput.plan X cut).B * IndexedStarts.capacity ns nt ≤ width
+ slotAfter : ShrinkOutput.slotsBase X (ShrinkOutput.widthBase X (term).val (step).val role width)
+ shape ≤ slots
+ packedRoom : ShrinkOutput.stop (b := b i) X (term).val (step).val role width < 2 ^ w
+ slotRoom : finish shape heads < 2 ^ w
+ residentEnd : (ShrinkResidentLayout.layout X resident).endAddr ≤ levelStart lay (cur + 1)
+ slotEnd : finish shape heads ≤ levelStart lay (cur + 1)
+
+variable (round : ℕ)
+local notation "here" => (S.steps + 1) * round + i.val
+
+/-- Derive the resident-source bounds from a live block in the actual schedule. -/
+theorem bounds (live : round < blocks) (size : X.positions ≤ positions)
+ (room : endAddress lay < 2 ^ w) : Bounds B i X base positions blocks here := by
+ have next : here + 1 < (lay).levels := by
+ change here + 1 < 1 + (S.steps + 1) * blocks
+ have rounds := Nat.mul_le_mul_left (S.steps + 1) live
+ rw [Nat.mul_succ] at rounds
+ have stepBound := i.isLt
+ omega
+ let level : Fin (lay).levels := ⟨here, by omega⟩
+ have oldSize : IncidenceDirectory.slotCount X ≤ slotCapacity lay := by
+ have positionsEq : Fintype.card X.Base * 2 ^ packingLaneBits (a i) g = X.positions := by
+ simp only [State.positions, Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv _),
+ Fintype.card_fin]
+ have degree : 2 ^ (a i) ≤ slotDegree S :=
+ (Finset.le_sup (f := fun j : Fin (S.steps + 1) ↦ 2 ^ S.degreeExponent j)
+ (Finset.mem_univ i.castSucc)).trans (le_max_right ..)
+ change Fintype.card X.Base * 2 ^ packingLaneBits (a i) g * 2 ^ (a i) ≤ positions * slotDegree S
+ rw [positionsEq]
+ exact Nat.mul_le_mul size degree
+ have space := ShrinkOutput.table_space B i X base positions blocks round live size room
+ obtain ⟨_, newSize, _, _⟩ :=
+ ShrinkSlotCalendar.physical_space B i X base.val positions blocks level rfl size room
+ obtain ⟨_, termEnd, _, _, _, _, slotEnd, _, residentEnd⟩ :=
+ BlockLevelFit.shrink B base.val positions blocks level rfl i X size room
+ exact ⟨next, room, oldSize, newSize,
+ termEnd.within.trans (tableEnd_le_tableBase lay here (show (0 : Fin 6) < 1 by decide)),
+ space.termRoom, space.abAfter, space.fresh, space.widthAfter, space.slotAfter, space.packedRoom,
+ space.slotRoom, residentEnd.next, slotEnd.next⟩
+
+variable {B i X base positions blocks cur}
+local notation "T" => packedIncidence lay w cur (DemandRAM.oldCount X)
+local notation "Z" => ShrinkInput.plan X cut
+
+/-- The three occupied incidence columns, the preliminary placement and the
+classifier's rows and ranks all precede table one. A frame from the end of the
+level header through that table boundary retains the old map-call inputs. -/
+theorem Bounds.oldTables (h : Bounds B i X base positions blocks cur)
+ {before out : Memory w} (old : ShrinkCallHeader.OldTables X before T cut)
+ (frame : ∀ x, incidenceStart lay cur ≤ x → x < first → out x = before x) :
+ ShrinkCallHeader.OldTables X out T cut := by
+ let level : Fin (lay).levels := ⟨cur, (Nat.lt_succ_self _).trans h.nextLive⟩
+ let n := DemandRAM.oldCount X
+ have incRoom : incidenceStart lay cur + 6 * n < 2 ^ w :=
+ packed_incidence_room lay h.room level h.oldCapacity
+ have incEnd : incidenceStart lay cur + 6 * n ≤ cut := by
+ have size := Nat.mul_le_mul_left 6 h.oldCapacity
+ change incidenceStart lay cur + 6 * n ≤
+ incidenceStart lay cur + 6 * slotCapacity lay + 0 * tableWords lay
+ simpa only [Nat.zero_mul, Nat.add_zero] using Nat.add_le_add_left size _
+ have range (c : Fin 6) :
+ incidenceStart lay cur ≤ ((T).column c).val ∧
+ ((T).column c).val + n ≤ incidenceStart lay cur + 6 * n := by
+ rw [packed_column]
+ have bound := Nat.mul_le_mul_right n c.isLt
+ rw [Nat.succ_mul] at bound
+ have fit : incidenceStart lay cur + c.val * n < 2 ^ w := by omega
+ change incidenceStart lay cur ≤ (incidenceStart lay cur + c.val * n) % (2 ^ w) ∧
+ (incidenceStart lay cur + c.val * n) % (2 ^ w) + n ≤ _
+ rw [Nat.mod_eq_of_lt fit]
+ exact ⟨Nat.le_add_right .., by omega⟩
+ obtain ⟨placement, rank, widthEnd, inputEnd⟩ := ShrinkInput.range_bounds X cut
+ have rankRoom : (Z).stop < 2 ^ w := by
+ have room := h.termRoom
+ unfold ShrinkInput.termEnd at room
+ exact inputEnd.trans_lt (by omega)
+ have start : incidenceStart lay cur ≤ cut := (Nat.le_add_right ..).trans incEnd
+ have last : cut ≤ first := (placement.trans (rank.trans (widthEnd.trans inputEnd))).trans h.fresh
+ apply old.transfer rankRoom (fun c ↦ ((range (c.natAdd 3)).2.trans_lt incRoom).le)
+ (D := fun x ↦ incidenceStart lay cur ≤ x ∧ x < first) (fun x hx ↦ (frame x hx.1 hx.2).symm)
+ · intro c z lo hi
+ exact ⟨(range (c.natAdd 3)).1.trans lo, hi.trans_le ((range (c.natAdd 3)).2.trans
+ (incEnd.trans last))⟩
+ · intro z lo hi
+ exact ⟨start.trans (placement.trans (rank.trans lo)), hi.trans_le (inputEnd.trans h.fresh)⟩
+ · intro z lo hi
+ exact ⟨start.trans (placement.trans lo), hi.trans_le (widthEnd.trans (inputEnd.trans h.fresh))⟩
+
+end PairSimulation.ShrinkResidentSources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPreparedCall.lean b/lean/OAI/Computability/VPVNP/PairShrinkPreparedCall.lean
new file mode 100644
index 0000000000..5d05d72b44
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPreparedCall.lean
@@ -0,0 +1,173 @@
+import OAI.Computability.VPVNP.PairShrinkCallWorkspace
+import OAI.Computability.VPVNP.PairShrinkCallDemandCells
+import OAI.Computability.VPVNP.PairShrinkCallSupplyCells
+import OAI.Computability.VPVNP.PairSimulationRecordedMapCalls
+
+/-!
+# A native map-call descriptor from a selected shrinking term
+
+The real demand and supply readbacks, the recorded branch widths and the
+private workspace intervals supply every input of the compiled descriptor
+writer. These facts hold for arbitrary choices of the local half-wires and
+absorbed words, including data on which the grouped entry test rejects.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPreparedCall
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open MotifGrid MotifBlocks MotifConversion MotifEntry NetworkKernel
+open MapPortAgreement MapResidentAgreement
+open scoped Fin.CommRing
+
+variable {a g b pad w p r k t n limit endAddr : ℕ} {K : Type} [_root_.Field K] {factor : ℝ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (X : State a (packingLaneBits a g))
+/-- Classical decidable equality on the compression state’s base vertices for the native
+map-call descriptor of a selected shrink term. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+variable (selection : X.ShrinkSelection F) (layout : Bool) (subdiv : Fin 4 → ℕ)
+variable {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+variable (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad) (hpos : ∀ t, 0 < subdiv t)
+variable (m : X.packingData.Motif) (j : Fin 6)
+/-- Demand widths of a motif computed from the numbering and wire widths of the input state. -/
+noncomputable abbrev widthsDemand (motif : X.packingData.Motif) :=
+ X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth motif
+
+local notation "BW" => widthsDemand X m
+/-- Supply widths of a motif for the term chosen by the shrinking selection. -/
+noncomputable abbrev width (e : X.packingData.Motif) :=
+ X.packingData.shrinkSupplyWidths X.shrinkNumber X.packingWidth F e (selection e)
+
+local notation "Widths" => width F X selection
+local notation "Idx" => Fin.val (CompressorRecords.ShrinkMotifOrder.stateNumber X m)
+local notation "U" => repetitions F (BW)
+
+variable (old : ShrinkCallDemandCells.Old X layout m j)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner layout)
+ (internalLabel (width F X selection) layout)
+ (X.packingData.shrinkPartySite layout m j))
+variable (z : (X.shrinkOutputState layout subdiv
+ (fun m t ↦ width F X selection m (layout, t)) I).network.Half
+ (X.packingData.shrinkPartySite layout m j))
+
+/-- The full selected input, with the original matrix coordinates at this party. -/
+noncomputable def input : LocalHistory.EntryInput F :=
+ ⟨BW, (selection m).val, j, X.packingData.shrinkLocalDemandArg (State.two_le_packingColors a)
+ (Nat.two_pow_pos a) X.shrinkNumber X.shrinkOrder X.packingWidth layout m j old,
+ X.packingData.shrinkLocalSupplyArg layout subdiv (Widths) I hpos m j hidden z⟩
+
+local notation "C" => input F X selection layout subdiv I hpos m j old hidden z
+local notation "D" => demandBits demandSource demandTarget j
+ (LocalHistory.EntryInput.demandBits (C))
+local notation "S" => MotifSelector.mapHalf supply (fun _ ↦ inputBits)
+ (LocalHistory.EntryInput.supplyBits (C))
+
+variable (s : ShrinkCallFields.Scratch) (arena : NodeArguments.Arena) (nodes : X.network.Site → ℕ)
+local notation "cd" => ShrinkCallDemandCells.cdBase X m arena nodes
+
+variable (A : MapEntryTable.Allocation F (demandGrid F demandMass_pos (widthsDemand X m)) j r k)
+variable (loc : A.Address → Fin p)
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit)
+ (u := repetitions F (widthsDemand X m)) (t := t) F (widthsDemand X m) (selection m).val
+ s (CompressorRecords.ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallDemandCells.cdBase X m arena nodes))
+local notation "HW" => ShrinkCallFields.workspace F (A.program loc)
+ (BW) (Subtype.val (selection m))
+ (D) (S)
+ s Idx layout (cd) ok
+
+private theorem endpoint_le (q : Bool × Bool) : (MapRow.endpoint demandSource demandTarget j
+ (BW) (D) q).1 ≤ BW q.2 := by
+ rcases q with ⟨dir, e⟩
+ cases dir with
+ | false =>
+ by_cases eqn : j = demandSource e <;>
+ simp [MapRow.endpoint, eqn]
+ | true =>
+ by_cases eqn : j = demandTarget e <;>
+ simp [MapRow.endpoint, eqn]
+
+/-- The descriptor's scalar and address words agree with the map initializer's
+precise ABI, including its separate directory, ordinal and label addresses. -/
+theorem values_eq (arg : ShrinkCallFields.Arg) :
+ ShrinkCallFields.values (w := w) X F selection m s j layout (cd) arg =
+ MapCallSetup.values A loc (HW) arg := by
+ cases arg with
+ | base f => rfl
+ | demand e => rfl
+ | payload e => rfl
+ | copies => rfl
+ | hist => rfl
+ | directory => rfl
+ | source => exact congrArg (fun n : ℕ ↦ (n : Word w)) (ShrinkCallFields.workspace_source ..).symm
+ | target => exact congrArg (fun n : ℕ ↦ (n : Word w)) (ShrinkCallFields.workspace_target ..).symm
+
+/-- Every incident bit is the local matrix's actual coordinate. Descriptor
+writes and the directory fill are disjoint from all these reads. -/
+theorem resident (before after : Word w → Word w)
+ (demand : ShrinkCallDemandCells.Readback X layout m j arena nodes old after s.staging endAddr)
+ (shared : ShrinkCallSupplyCells.Absorbed X layout (Widths) m j s hidden after)
+ (visible : ShrinkCallSupplyCells.Retained X layout subdiv (Widths) I m j s z before after) :
+ MapArgumentWriter.ResidentFields A loc (HW) (s.descriptor : Word w) after := by
+ let bases := s.fieldBase Idx j layout (cd)
+ have endStaging : s.directory < 2 ^ w := by
+ have room := ok.room.trans_lt ok.capacity.room
+ unfold ShrinkCallFields.Scratch.target ShrinkCallFields.Scratch.source
+ ShrinkCallFields.Scratch.descriptor at room
+ omega
+ have survFit (dir : Bool) (e : Fin 4) : s.surviving dir e + (Widths) m (layout, e) ≤ 2 ^ w :=
+ (Nat.add_le_add_left (ok.supply _) _).trans ((s.surviving_end dir e).trans endStaging.le)
+ constructor
+ · intro e
+ have small := ok.supply e
+ have all := s.surviving_end false 0
+ omega
+ · intro q
+ rfl
+ · intro q i
+ cases q with
+ | inl q =>
+ obtain ⟨e, party⟩ := q
+ have bit := ShrinkCallSupplyCells.read X layout subdiv (Widths) I hpos m j s hidden z
+ before after shared visible survFit (cd) false e party i
+ have sep := ShrinkCallFields.separated (BW) (selection m).val (D) (S) s Idx layout
+ (cd) ok A loc (.inr (false, e)) i
+ change after ((bases (.inr (false, e)) : Word w) + (i.val : Word w)) = _ ∧ _
+ constructor
+ · rw [← Nat.cast_add]
+ exact bit
+ · change MapArgumentWriter.separated A loc (HW) _
+ ((bases (.inr (false, e)) : Word w) + (i.val : Word w))
+ rw [← Nat.cast_add]
+ exact sep
+ | inr q =>
+ obtain ⟨e, party⟩ := q
+ have bit := ShrinkCallSupplyCells.read X layout subdiv (Widths) I hpos m j s hidden z
+ before after shared visible survFit (cd) true e party i
+ have sep := ShrinkCallFields.separated (BW) (selection m).val (D) (S) s Idx layout
+ (cd) ok A loc (.inr (true, e)) i
+ change after ((bases (.inr (true, e)) : Word w) + (i.val : Word w)) = _ ∧ _
+ constructor
+ · rw [← Nat.cast_add]
+ exact bit
+ · change MapArgumentWriter.separated A loc (HW) _
+ ((bases (.inr (true, e)) : Word w) + (i.val : Word w))
+ rw [← Nat.cast_add]
+ exact sep
+ · intro q i
+ have bit := ShrinkCallDemandCells.scratch_demandCells X layout m j arena nodes s Idx old
+ after endAddr demand q i
+ exact ⟨bit, ShrinkCallFields.separated (BW) (selection m).val (D) (S) s Idx layout
+ (cd) ok A loc (.inl q) ⟨i.val, i.isLt.trans_le
+ (endpoint_le F X selection layout subdiv I hpos m j old hidden z q)⟩⟩
+
+end PairSimulation.ShrinkPreparedCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPrologueBudget.lean b/lean/OAI/Computability/VPVNP/PairShrinkPrologueBudget.lean
new file mode 100644
index 0000000000..3f8162299a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPrologueBudget.lean
@@ -0,0 +1,67 @@
+import OAI.Computability.VPVNP.PairShrinkChildDemandBudget
+import OAI.Computability.VPVNP.PairShrinkHiddenSeedBudget
+import OAI.Computability.VPVNP.CompressorSlotState
+import OAI.Computability.VPVNP.CompressorLevelCounts
+
+/-!
+# Child and hidden arguments of the selected shrinking prologue
+
+One coefficient fixed by the schedule and its templates bounds the two
+directory counts and the number of bits consumed by each native scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkNodeCost
+
+open Compression Compression.ShrinkMotif CompressorRecords CompressorRecords.ShrinkSlots
+open LocalHistory NetworkKernel ShrinkRole
+
+variable {K R : Type*} [Field K] [CommRing R] {S : BlockSchedule K}
+
+/-- Cover both directory counts and both coefficients for the payload widths. -/
+noncomputable def prologueCoefficient (B : S.Templates) : ℕ :=
+ max (max B.recordLimit (2 * slotDegree S * B.recordLimit))
+ (max (ShrinkHiddenRows.stageCapacity S)
+ (ShrinkHiddenRows.stageCapacity S * fieldFactor B.shrink))
+
+/-- Bound the child arguments of the actual placement fiber and the absorbed
+words of its selected layout, for every choice of the initial hidden values. -/
+theorem selected_prologue_bounds (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+ (i : Fin S.steps) {g w : ℕ}
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink)
+ (v : (X.Base × BitWord (packingTagBits (2 ^ S.degreeExponent i.castSucc))) × BitWord g)
+ (desc : ChildArguments.Descriptor w X)
+ (order : desc.sites = List.ofFn fun j =>
+ ((((shrinkPassReaders B f hf i rfl X).order sel).children v).entries j).val)
+ (placeholder : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkHiddenRows.widths X B.shrink sel) (selectedLayout X B.shrink sel)) v) :
+ let C := prologueCoefficient B
+ let seed := ShrinkHiddenSlots.rows X (selectedLayout X B.shrink sel)
+ (ShrinkHiddenRows.widths X B.shrink sel) v placeholder
+ desc.sites.length ≤ C ∧ ChildArguments.demand X desc.sites ≤ C * (X.maxWireWidth + 1) ∧
+ seed.length ≤ C ∧ (ShrinkHiddenGuess.stream seed).length ≤ C * (X.maxWireWidth + 1) := by
+ intro C seed
+ obtain ⟨children, demand⟩ := ChildArguments.selected_budget B f hf i X sel v desc order
+ obtain ⟨fields, bits⟩ :=
+ ShrinkHiddenRows.scheduled_seed_bounds (selectedLayout X B.shrink sel) B i X sel v placeholder
+ have degree : 2 ^ S.degreeExponent i.castSucc ≤ slotDegree S :=
+ (Finset.le_sup (f := fun j : Fin (S.steps + 1) => 2 ^ S.degreeExponent j)
+ (Finset.mem_univ i.castSucc)).trans
+ (le_max_right ..)
+ have childBits : 2 * 2 ^ S.degreeExponent i.castSucc * B.recordLimit ≤ C :=
+ (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left 2 degree)).trans
+ ((le_max_right ..).trans (le_max_left ..))
+ exact ⟨children.trans ((le_max_left ..).trans (le_max_left ..)),
+ demand.trans (Nat.mul_le_mul childBits (Nat.le_succ _)),
+ fields.trans ((le_max_left ..).trans (le_max_right ..)),
+ bits.trans (Nat.mul_le_mul_right _ ((le_max_right ..).trans (le_max_right ..)))⟩
+
+end PairSimulation.ShrinkNodeCost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkPublishedSupplyWords.lean b/lean/OAI/Computability/VPVNP/PairShrinkPublishedSupplyWords.lean
new file mode 100644
index 0000000000..ad5e362fe2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkPublishedSupplyWords.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.CompressorShrinkScheduledTail
+import OAI.Computability.VPVNP.CompressorShrinkSlotFrame
+import OAI.Computability.VPVNP.CompressorShrinkSelectedReadback
+import OAI.Computability.VPVNP.CompressorShrinkTablesPhysical
+
+/-!
+# The four published addresses used to read surviving shrink operands
+
+The absolute motif directory is the last word of the term publication.
+The next level, inverse-slot table and interval bank are the first three
+words of the following data publication. The latter reads the memory
+left by the term publisher.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkPublishedSupplyWords
+
+open BurstRAM Compression CompressorRecords CompressorRecords.DescriptorSpace
+open CompressorRecords.BlockPlanner CompressorRecords.PhaseRecipe CompressorRecords.Schedule
+open CompressorRecords.ShrinkBlockInputs CompressorRecords.SourceOnline
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+variable (base : Word w) (positions blocks t : ℕ)
+
+local notation "prog" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "pub" => Ports.data (Workspace.ports (arity (Script.catalog prog)) base)
+local notation "first" => Script.levelsPerBlock prog * t
+local notation "cur" => first + i.val
+local notation "old" => levelStart L cur
+local notation "next" => levelStart L (first + (i.val + 1))
+local notation "st" => (levelStart L first : Word w)
+local notation "tab" => (fun j : Fin 6 ↦ tableBase L cur j)
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "sh" => ShrinkSlots.levelShape (b := b i) X
+local notation "role" => SelectedArena.roleBase X term (10 : Word w)
+local notation "heads" => ShrinkOutput.heads sh role (tab 3)
+local notation "alloc" => ShrinkSliceSweep.selectedAllocation B.shrink X sel term 10 (tab 2)
+ (SlotLevel.Shape.subdivisions sh)
+local notation "geometry" => BlockProgram.geometry B
+local notation "arena" => BlockProgram.arena B i.val
+
+section Words
+
+variable (level : ℕ)
+local notation "levelTab" => (fun j : Fin 6 ↦ tableBase L level j)
+local notation "levelTerm" => ShrinkInput.termHead (w := w) X (levelTab 0)
+local notation "levelHeads" => ShrinkOutput.heads sh (SelectedArena.roleBase X levelTerm 10)
+ (levelTab 3)
+local notation "levelAlloc" => ShrinkSliceSweep.selectedAllocation B.shrink X sel levelTerm 10
+ (levelTab 2) (SlotLevel.Shape.subdivisions sh)
+
+/-- Supply pointers in an absolute chronological level header. -/
+structure Stored (mem : Memory w) : Prop where
+ absolute : mem (levelStart L level + 39) =
+ ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X (levelTab 0)) w
+ successor : mem (levelStart L level + 40) = (levelStart L (level + 1) : Word w)
+ inverse : mem (levelStart L level + 41) = (SlotLevel.inverseHead sh levelHeads : Word w)
+ interval : mem (levelStart L level + 42) = ((levelAlloc).widthEnd : Word w)
+
+end Words
+
+private theorem gap : old + 66 ≤ next := by
+ have size : levelHeaderWords L = 66 := rfl
+ rw [show first + (i.val + 1) = cur + 1 by omega]
+ simp only [levelStart, Nat.succ_mul, levelWords, size]
+ omega
+
+set_option maxHeartbeats 1500000 in
+-- Reducing the three packet images unfolds the installed block and its fourteen data expressions.
+/-- Recover the four published words from the three chronological packet groups
+and the physical header and table pointers present at their entry. -/
+theorem of_tail {cap : ℕ} {mem : Memory w} {ms ps : List (Packet prog w)}
+ (T : IncidenceDirectory w) (header : ShrinkHeaderReads.Header i X T (tab 0) L first mem)
+ (tables : ∀ j : Fin 6, mem (old + (60 + j.val)) = (tab j : Word w))
+ (pitch : mem (pub 1 - 1).val = (levelWords L : Word w))
+ (live : t < blocks) (sites : X.positions ≤ positions) (fit : endAddress L < 2 ^ w)
+ (run : ShrinkScheduledTail.Result B base positions blocks t cap i X mem ms ps) :
+ Stored B i X sel base positions blocks cur (post mem ps) := by
+ let afterMeta := post mem ms
+ have sep := gap B i base positions blocks t
+ have room := PublishedHeads.level_room B base positions blocks t i.val live i.isLt.le fit
+ have controls := Window.lowCells (A := prog) L base rfl rfl
+ ((levelStart_mono L (Nat.zero_le _)).trans_lt fit)
+ have early : (pub 1 - 1).val < old := controls.2.trans_le (levelStart_mono L (Nat.zero_le _))
+ have entry : LevelFields.Entry L first pub st afterMeta :=
+ ⟨rfl, (run.baseFields.outside _ (.inl (by omega)) (by omega) (by omega)).trans pitch⟩
+ have saved (n : ℕ) (hn : n ≤ 65) (free : n < 15 ∨ 27 ≤ n) :
+ afterMeta (old + n) = mem (old + n) :=
+ run.baseFields.outside _ (by omega) (by omega) (by omega)
+ have hdr : ShrinkHeaderReads.Header i X T (tab 0) L first afterMeta :=
+ ⟨header.room, (saved 0 (by decide) (by decide)).trans header.vertices,
+ (saved 1 (by decide) (by decide)).trans header.degree,
+ (saved 2 (by decide) (by decide)).trans header.lanes,
+ (saved 3 (by decide) (by decide)).trans header.residual,
+ fun c ↦ (saved _ (by have := c.isLt; omega) (Or.inr (by omega))).trans (header.incidence c),
+ (saved 60 (by decide) (by decide)).trans header.scratch⟩
+ have table (j : Fin 6) : (arena j).eval pub st afterMeta = (tab j : Word w) := by
+ have hj := j.isLt
+ exact (LevelFields.eval_scalar entry i.val (60 + j.val) (by omega)).trans
+ ((saved _ (by omega) (Or.inr (by omega))).trans (tables j))
+ let chosen := selectedInputs B geometry i (arena 0)
+ have space := ShrinkOutput.table_space B i X base positions blocks t live sites fit
+ have vals := (SelectedTailPackets.header_values B i X T (tab 0) pub st afterMeta hdr entry
+ space.termRoom (by omega) (fun _ ↦ True) trivial (fun _ _ ↦ trivial)).1
+ have rd := hdr.reads B entry
+ have roleAt := SelectedPlan.roles_head chosen X _ T term pub st afterMeta vals
+ have slotAt := slotInputs_reads B geometry i X (arena 0) (arena 3) pub st afterMeta role (tab 3)
+ rd.vertices rd.residual roleAt (table 3)
+ have inv := (endpoint_heads B geometry i X (arena 0) (arena 3) pub st afterMeta role (tab 3)
+ slotAt).2
+ have intervals : (BlockSlices.intervals i (arena 2)).eval pub st afterMeta =
+ ((alloc).widthEnd : Word w) := by
+ change (arena 2).eval pub st afterMeta + (4 * chosen.oldSlots.eval pub st afterMeta) *
+ (BlockSlices.subdivisionSum i : Word w) =
+ ((tab 2 + (DemandRAM.absoluteCount X * 4) * BlockSlices.subdivisionSum i : ℕ) : Word w)
+ rw [table, vals.slots, DemandRAM.count_eq X]
+ push_cast
+ ring
+ have termRead := run.published.termGroup.source.stored (3 : Fin 4)
+ have dataRead (j : Fin 14) : post mem ps (old + 40 + j.val) =
+ (PublishedHeads.dataValues B i j).eval pub st afterMeta := by
+ rw [run.image]
+ apply (run.published.dataGroup.source.stored j).trans
+ exact BlockHeadStability.shrink_data_stable B i entry room (by omega) (offset := 36) (N := 4)
+ le_rfl (by decide) run.published.termGroup.source.outside j
+ constructor
+ · rw [run.image]
+ apply (run.published.dataGroup.source.outside _ (.inl (by omega))).trans
+ exact termRead.trans (ShrinkBundlePlan.head_values X rd).absoluteCD
+ · rw [Nat.add_assoc first i.val 1]
+ exact (dataRead 0).trans (LevelFields.eval_atLevel entry (i.val + 1))
+ · exact (dataRead 1).trans inv
+ · exact (dataRead 2).trans intervals
+
+end PairSimulation.ShrinkPublishedSupplyWords
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkReadyAfterGather.lean b/lean/OAI/Computability/VPVNP/PairShrinkReadyAfterGather.lean
new file mode 100644
index 0000000000..84ad41cf00
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkReadyAfterGather.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.PairShrinkJobPrepared
+import OAI.Computability.VPVNP.PairSimulationMapHandlerFrame
+
+/-!
+# The ready continuation of the scheduled shrink row
+
+The interval copier leaves the five shared operand registers and the state
+register intact. The native grouped map can therefore start from every
+actual exit of the gather, including calls with invalid selector payloads.
+The descriptor and all mutable map ranges lie above the pending DFS stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.State Compression.PackingData
+open Compression.ShrinkMotif Compression.ShrinkEnergy NetworkKernel MotifBlocks MotifGrid
+open MotifConversion CompressorRecords CompressorRecords.PhaseRecipe CompressorRecords.ShrinkSlots
+open scoped Fin.CommRing
+
+variable {a b g w p r t n limit endAddr : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (degree : ℕ) (ord : B.Entry → Fin t)
+variable {δ : ℝ} (X : State a (packingLaneBits a g))
+variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) (sel : X.ShrinkSelection B.shrink)
+variable (m : X.packingData.Motif) (j : Fin 6) (J : Job X B.shrink ready sel m j w)
+private noncomputable local instance readyBase : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "BW" => ShrinkPreparedCall.widthsDemand X m
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel))
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m j))
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (ShrinkPreparedCall.widthsDemand X m)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X m) (sel m).val J.scratch (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallDemandCells.cdBase X m J.arena J.nodes))
+local notation "call" => Job.entryInput B X ready sel m j J hidden
+local notation "family" => ShrinkCallABI.family B degree a ord
+local notation "work" => Job.mapWorkspace B degree ord X ready sel m j J hidden ok
+local notation "O" => ShrinkCallABI.operands degree
+
+variable (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin 24 ↪ Fin r)
+variable (mem : Memory w) (pub : Fin 5 → Word w) (st level : Word w)
+variable (T : IncidenceDirectory w) (origin : ℕ)
+variable (tables : J.OldPublished (ShrinkCallABI.operands degree) pub st mem level T origin)
+
+include tables in
+/-- The callback required by the scheduled resident loop, with all six operands
+taken from the actual post-gather registers. -/
+theorem Job.ready_after_gather (c : Config w p r)
+ (children : J.ChildWords c.privateMem endAddr)
+ (ends : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ J.scratch.staging)
+ (guessed : ShrinkCallSupplyCells.Absorbed X (side) (widths) m j J.scratch hidden c.privateMem)
+ (two : 2 < 2 ^ w) (termRoom : ShrinkInput.termEnd X origin 10 < 2 ^ w)
+ (pairs : ShrinkTermInputs.statePairs X (ShrinkInput.demandHead X origin) mem)
+ (terms : TermRecordScan.Fields B.shrink ShrinkSliceArrays.supplyRoles demandMass_pos
+ (BW) (sel m).val (ShrinkTermSelection.rowBase X (ShrinkInput.termHead X origin) 10 m) mem) :
+ ∀ out : Config w p r, J.Assembled c.privateMem out.privateMem →
+ MapHandlerOperand.pub (family) demandMass_pos (call) dfs saved common out = pub →
+ MapHandlerOperand.state (family) demandMass_pos (call) dfs saved common out = st →
+ MapHandlerOperand.Prepared (family) demandMass_pos (call) dfs saved common out mem
+ (work) := by
+ intro out result hpub hst
+ change ShrinkCallABI.pub out common = pub at hpub
+ change ShrinkCallABI.state out common = st at hst
+ apply Job.prepared_after_gather B degree ord X ready sel m j J hidden ok dfs saved common out mem
+ c.privateMem result children ends guessed T origin level _ two termRoom pairs terms
+ rwa [hpub, hst]
+
+include tables in
+private theorem descriptor_read :
+ ((O).inputs a).descriptor.eval pub st mem = (J.scratch.descriptor : Word w) := by
+ have vertex : ((O).cell 0).eval pub st mem = (Fintype.card X.Base : Word w) := by
+ change mem ((O).level.eval pub st mem + 0).val = _
+ rw [tables.live.header]
+ exact tables.levelData.vertices
+ have lane : ((O).cell 3).eval pub st mem = ((2 ^ g : ℕ) : Word w) := by
+ change mem ((O).level.eval pub st mem + 3).val = _
+ rw [tables.live.header]
+ exact tables.levelData.residual
+ have count := ShrinkCallHeader.count_eq X (O) pub st mem vertex lane
+ change (((O).hidden.eval pub st mem +
+ (4 * ((O).count a).eval pub st mem) * (O).slotStride.eval pub st mem) +
+ 9 * (O).slotStride.eval pub st mem) + 16 = _
+ rw [count, ← tables.motifCount, tables.live.hiddenBase, tables.live.stride]
+ simp only [ShrinkCallFields.Scratch.descriptor, ShrinkCallFields.Scratch.directory,
+ ShrinkCallFields.Scratch.staging, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+
+include tables in
+/-- The descriptor writer and the four mutable map arrays preserve the DFS
+stack, including for unsuccessful resident entries. -/
+theorem Job.call_bounds (stack : endAddr ≤ J.scratch.hist) :
+ MapHandlerOperand.Bounds (family) demandMass_pos (call) (work) endAddr
+ (((family).base (MapHandlerOperand.index demandMass_pos (call))).eval pub st mem) := by
+ have dptr := descriptor_read B degree X ready sel m j J mem pub st level T origin tables
+ change ((O).inputs a).descriptor.eval pub st mem = _ at dptr
+ have extent := ok.room.trans_lt ok.capacity.room
+ unfold ShrinkCallFields.Scratch.target ShrinkCallFields.Scratch.source
+ ShrinkCallFields.Scratch.descriptor at extent
+ have cap : J.scratch.directory + 16 < 2 ^ w := by omega
+ have dcap : (J.scratch.directory : Word w).val = J.scratch.directory :=
+ Nat.mod_eq_of_lt (by omega)
+ have bound := ok.histogram
+ constructor
+ · change endAddr ≤ (((O).inputs a).descriptor.eval pub st mem).val
+ rw [dptr]
+ change endAddr ≤ (J.scratch.directory + 16) % (2 ^ w)
+ rw [Nat.mod_eq_of_lt cap]
+ omega
+ · change endAddr ≤ MapWorkspace.ordinalBase Bool (Bool × Fin 4) J.scratch.directory
+ unfold MapWorkspace.ordinalBase MapWorkspace.descriptorBase
+ omega
+ · change endAddr ≤ MapWorkspace.ordinalBase Bool (Bool × Fin 4) J.scratch.directory + _
+ unfold MapWorkspace.ordinalBase MapWorkspace.descriptorBase
+ omega
+ · exact stack
+ · change endAddr ≤ (J.scratch.directory : Word w).val
+ rw [dcap]
+ omega
+ · change (J.scratch.directory : Word w).val + _ ≤ _
+ rw [dcap]
+ have len := MapPortAgreement.ports_length_le supply j
+ (MapHandlerOperand.layout (family) demandMass_pos (call)).core.edgeOrder
+ have card : 2 * Fintype.card (Bool × Fin 4) = 16 := by simp
+ rw [card] at len
+ exact (Nat.add_le_add_left len _).trans cap.le
+
+/-- Counter words lie below the upper private region overwritten by interval copies. -/
+theorem Job.histogram_before_staging (hist : J.scratch.hist + t ≤ J.scratch.hidden) (l : Fin t) :
+ (((work).hist + l.val : ℕ) : Word w).val < J.scratch.staging :=
+ (Nat.mod_le ..).trans_lt (((Nat.add_lt_add_left l.isLt _).trans_le hist).trans_le
+ (Nat.le_add_right ..))
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkResidentBudget.lean b/lean/OAI/Computability/VPVNP/PairShrinkResidentBudget.lean
new file mode 100644
index 0000000000..647e93df26
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkResidentBudget.lean
@@ -0,0 +1,165 @@
+import OAI.Computability.VPVNP.PairShrinkScanCoefficient
+import OAI.Computability.VPVNP.PairShrinkRowBudget
+import OAI.Computability.VPVNP.PairShrinkNodeClock
+import OAI.Computability.VPVNP.PairShrinkRoleMapActions
+import OAI.Computability.VPVNP.ShrinkFieldBounds
+
+/-! # Cost of the shrinking vertex's real resident map scan
+
+Each row uses the demand sizes of its selected motif. The native clock
+therefore depends linearly on the maximum input width. The probe count
+is independent of that width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots ShrinkMapImage.Registers
+open ResidentMapLoop.Exact MapResidentRows MotifGrid MotifConversion MotifBlocks
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t w endAddr : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps) {g : ℕ}
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "side" => selectedLayout X B.shrink sel
+local notation "F" => ShrinkVertexImage.matrixFamily B ord i
+local notation "G" => ShrinkVertexImage.gatherFamily B ord i
+local notation "idx" => Fin (LocalHistory.Order.length (order X side v))
+
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+ (jobs : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ ShrinkPartyNative.Job X B.shrink (S.shrink i) sel q.1.1 q.1.2 w)
+ (m : Memory w) (level term : Word w)
+ (R : MapRowSource X sel (selectedLayout X B.shrink sel) m level term)
+ (hw : MapConstants.widthThreshold B.shrink ≤ w)
+ (pub : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v → Fin 5 → Word w)
+ (workspace : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ MapHandlerOperand.Workspace (w := w) (ShrinkVertexImage.matrixFamily B ord i)
+ demandMass_pos (jobInput B i X sel v hidden jobs q))
+
+/-- The sizes here are the demand sizes used by the concrete matrix call. -/
+theorem job_repetitions (q : X.packingData.ResidentMap side v) :
+ repetitions B.shrink (jobInput B i X sel v hidden jobs q).demand ≤
+ fieldFactor B.shrink * (X.maxWireWidth+1) :=
+ (linear_field_bounds B.shrink _ _ (X.packingData.shrinkDemandWidths_le
+ (State.two_le_packingColors _) (Nat.two_pow_pos _) X.shrinkNumber X.packingWidth
+ (fun _ => X.width_le_maxWireWidth _) q.1.1)).1
+
+local notation "cap" => MapResidentRows.capacity (S.degreeExponent i.castSucc)
+local notation "call" => jobInput B i X sel v hidden jobs
+local notation "qAt" => rowEquiv X side v
+private noncomputable def gatherEvents (j : idx) : List (Event w) :=
+ let q := (qAt) j
+ let key := (demandGrid B.shrink demandMass_pos ((call) q).demand, ((call) q).party)
+ (jobs q).trace ((G).operands key) ((G).node key) (pub q)
+ (rowOrdinalWord (a := S.degreeExponent i.castSucc) (g := g) X side v j) m
+
+local notation "gTrace" => gatherEvents B ord i X sel v hidden jobs m pub
+
+set_option maxHeartbeats 2000000 in
+-- Identify the party-indexed workspace and the selected row at each resident iteration.
+theorem scan_cost (gTicks gProbes : ℕ)
+ (gather : ∀ j : idx, ((gTrace) j).length ≤ gTicks ∧
+ countProbes ((gTrace) j) ≤ gProbes)
+ (node : Word w) (saved updated : Scratch w endAddr) (es : List (Event w))
+ (hit : scan node (actions B ord i X sel v hidden jobs m level term R hw pub workspace) saved =
+ some (es, updated)) :
+ es.length ≤ 1 + 2*cap + cap*(27+2*Fintype.card B.shrink.grid.demands + gTicks +
+ matrixFactor B ord i * (X.maxWireWidth+1)) ∧
+ countProbes es ≤ cap*(3+gProbes+(F).probeBound) := by
+ let action (j : idx) : Action w endAddr := fun _ s =>
+ let q := (qAt) j
+ rowAction (g := g) («side» := side) (ready := S.shrink i) (F) (G) X sel v m level term R j
+ ((call) q) (jobs q) hw (pub q) (workspace q) s
+ let rows := List.finRange (order X side v).length
+ have actual : (rows.map action) = actions B ord i X sel v hidden jobs m level term R hw pub
+ workspace := by
+ exact List.ofFn_eq_map.symm
+ let ticks := 27+2*Fintype.card B.shrink.grid.demands + gTicks +
+ matrixFactor B ord i * (X.maxWireWidth+1)
+ let loads := 3+gProbes+(F).probeBound
+ have row (j : idx) (s : Scratch w endAddr) (log : List (Event w)) (out : Scratch w endAddr)
+ (got : action j node s=some (log,out)) : log.length≤ticks ∧ countProbes log≤loads := by
+ let q := (qAt) j
+ let I := (call) q
+ let key := (demandGrid B.shrink demandMass_pos I.demand, I.party)
+ let u := repetitions B.shrink I.demand
+ let C := (MapNativeClock.uniform B.shrink).choose
+ obtain ⟨time,probe⟩ :=
+ rowAction_cost (g := g) («side» := side) (ready := S.shrink i) (F) (G) X sel v m level term
+ R j I
+ (jobs q) hw (pub q) (workspace q) s got
+ obtain ⟨gt,gp⟩ := gather j
+ have rep := job_repetitions B i X sel v hidden jobs q
+ change u ≤ fieldFactor B.shrink * (X.maxWireWidth+1) at rep
+ have clock : (F).clock key u ≤ matrixFactor B ord i * (X.maxWireWidth+1) := by
+ refine ((F).clock_le key u).trans ?_
+ have hC : MapNativeClock.cap B.shrink key.1 key.2 u ≤ C*(u+1) :=
+ (MapNativeClock.uniform B.shrink).choose_spec key.1 key.2 u
+ calc
+ _ ≤ (F).clockFactor * ((C+1)*(u+1)) := Nat.mul_le_mul_left _ (by rw [Nat.add_mul]; omega)
+ _ ≤ (F).clockFactor * ((C+1)*((fieldFactor B.shrink+1)*(X.maxWireWidth+1))) :=
+ Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ (by rw [Nat.add_mul]; omega))
+ _ = _ := by unfold matrixFactor; dsimp only [C]; ring
+ change log.length ≤ 15+2*Fintype.card B.shrink.grid.demands+12+
+ ((gTrace) j).length+(F).clock key u at time
+ change countProbes log=3+countProbes ((gTrace) j)+(F).probes key at probe
+ have base (k : ℕ) : 15+2*k+12=27+2*k := by omega
+ rw [base] at time
+ refine ⟨time.trans (Nat.add_le_add (Nat.add_le_add_left gt _) clock), ?_⟩
+ rw [probe]
+ exact Nat.add_le_add (Nat.add_le_add_left gp _) ((F).probes_le key)
+ have result :=
+ ShrinkNodeCost.scan_cost rows action (fun _ => ticks) (fun _ => loads) node saved updated es
+ (fun j _ => row j) (by rwa [actual])
+ have size : rows.length=cap := (List.length_finRange ..).trans (MapResidentRows.length_eq ..)
+ simpa only [List.map_const',List.sum_replicate_nat,size,ticks,loads] using result
+
+set_option maxHeartbeats 2000000 in
+-- The dependent jobs project the same indexed layout and packed operand width.
+/-- An accepted real row list at any shrinking stage, for every incoming
+upper scratch. The coefficient only depends on the original templates
+and the chosen finite entry numbering. -/
+theorem scan_bound (node : Word w) (saved updated : Scratch w endAddr) (es : List (Event w))
+ (hit : scan node (actions B ord i X sel v hidden jobs m level term R hw pub workspace) saved =
+ some (es, updated)) :
+ es.length ≤ scanCoefficient B ord * (X.maxWireWidth+1) ∧
+ countProbes es ≤ scanCoefficient B ord := by
+ let Q := (G).clockConstant (fieldFactor B.shrink+1)
+ let W := X.maxWireWidth+1
+ have each (j : idx) : ((gTrace) j).length ≤ Q*W ∧ countProbes ((gTrace) j)≤Q :=
+ (G).trace_bound (g := g) (X := X) (ready := S.shrink i) (sel := sel)
+ (demandGrid B.shrink demandMass_pos ((call) ((qAt) j)).demand)
+ (jobs ((qAt) j)) (pub ((qAt) j))
+ (rowOrdinalWord (a := S.degreeExponent i.castSucc) (g := g) X side v j) m
+ obtain ⟨clock,probe⟩ := scan_cost B ord i X sel v hidden jobs m level term R hw pub workspace
+ (Q*W) Q each node saved updated es hit
+ have stage : stageCoefficient B ord i ≤ scanCoefficient B ord :=
+ Finset.single_le_sum (fun j _ => Nat.zero_le (stageCoefficient B ord j)) (Finset.mem_univ i)
+ let fixed := 27+2*Fintype.card B.shrink.grid.demands
+ let factor := matrixFactor B ord i
+ have first : 1+2*cap ≤ (1+2*cap)*W := Nat.le_mul_of_pos_right _ (Nat.succ_pos _)
+ have second : fixed ≤ fixed*W := Nat.le_mul_of_pos_right _ (Nat.succ_pos _)
+ have localClock : es.length ≤ stageCoefficient B ord i * W := by
+ refine clock.trans ?_
+ change 1+2*cap + cap*(fixed+Q*W+factor*W) ≤
+ (1+2*cap+cap*(fixed+Q+factor)+cap*(3+Q+(F).probeBound))*W
+ rw [Nat.add_mul,Nat.add_mul, Nat.mul_assoc, Nat.add_mul (fixed+Q), Nat.add_mul fixed]
+ exact (Nat.add_le_add first (Nat.mul_le_mul_left _
+ (Nat.add_le_add_right (Nat.add_le_add_right second _) _))).trans
+ (Nat.le_add_right ..)
+ exact ⟨localClock.trans (Nat.mul_le_mul_right _ stage),
+ probe.trans ((Nat.le_add_left ..).trans stage)⟩
+
+end PairSimulation.ShrinkRole.MapWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkResidentHeaderWords.lean b/lean/OAI/Computability/VPVNP/PairShrinkResidentHeaderWords.lean
new file mode 100644
index 0000000000..7c43916419
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkResidentHeaderWords.lean
@@ -0,0 +1,166 @@
+import OAI.Computability.VPVNP.PairShrinkResidentHeaders
+import OAI.Computability.VPVNP.PairShrinkPublishedSupplyWords
+
+/-! # Chronological retention of a shrinking level's resident header -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkResidentHeaders
+
+open BurstRAM Compression CompressorRecords DescriptorSpace BlockPlanner SourceOnline ShrinkSlots
+open SourceTransport ShrinkBlockInputs Schedule
+open scoped Fin.CommRing
+
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+variable (i : Fin S.steps) {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g))
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+variable (sel : SelectedScore.Selection B X) (base : Word w) (positions blocks cur n : ℕ)
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "here" => levelStart L cur
+local notation "next" => levelStart L (cur + 1)
+local notation "tab" => (fun j : Fin 6 ↦ tableBase L cur j)
+local notation "T" => packedIncidence L w cur (DemandRAM.oldCount X)
+local notation "sh" => levelShape (b := b i) X
+local notation "H" => ShrinkResidentLayout.layout X (tab 5)
+
+/-- Header values retained in the selected pass history. The successor's layer base
+and descriptor pitch come from the DFS directory history and the next pass. -/
+structure Words (mem : Memory w) : Prop where
+ level : ShrinkCallHeader.Level X B.shrink sel (here : Word w) mem T (tab 0)
+ (mem (here + 14)).val (B.recordLimit + 2) (tab 1)
+ length : mem (here + 17) = (n : Word w)
+ residentHeads : ∀ j : Fin 6, mem (here + (30 + j.val)) =
+ (ShrinkResidentsPlan.headValues H j : Word w)
+ supply : ShrinkPublishedSupplyWords.Stored B i X sel base positions blocks cur mem
+ successor : PortRefresh.TraversalHeaders.HeadBank L (cur + 1) (actualCount sh) mem
+ oldRoom : here + 65 < 2 ^ w
+ nextRoom : next + 65 < 2 ^ w
+
+variable {B i X sel base positions blocks cur n}
+variable {m out : Memory w}
+
+private theorem head_cast (h j : ℕ) (fit : h + j < 2 ^ w) :
+ (((h : Word w) + (j : Word w))).val = h + j := by
+ rw [← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt fit]
+
+theorem Words.strideWord (p : Words B i X sel base positions blocks cur n m) :
+ m (here + 15) = ((B.recordLimit + 2 : ℕ) : Word w) := by
+ have room := p.oldRoom
+ have h := head_cast (w := w) (here) 15 (by omega)
+ exact (congrArg m h).symm.trans p.level.rowStride
+
+private theorem before_next : here + 66 ≤ next := by
+ have sz : levelHeaderWords L = 66 := rfl
+ simp only [levelStart, Nat.succ_mul, levelWords, sz]
+ omega
+
+open private HeadBank.keep_pointers from OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders
+
+/-- Transport the parser's old-header readbacks and all successor pointer
+words from the producer snapshot along the actual selected history frame. -/
+theorem Words.transfer (p : Words B i X sel base positions blocks cur n m)
+ (same : Agree (SelectedPayloadHistory.Cells L cur) m out) :
+ Words B i X sel base positions blocks cur n out := by
+ have gap : here + 66 ≤ next := before_next
+ have natAt (j : ℕ) (small : j < 66) : out (here + j) = m (here + j) :=
+ (same _ (.inl ⟨Nat.le_add_right .., by omega⟩)).symm
+ have takeWord (j : ℕ) (small : j < 66) (v : Word w)
+ (word : m ((here : Word w) + (j : Word w)).val = v) :
+ out ((here : Word w) + (j : Word w)).val = v := by
+ have room := p.oldRoom
+ rw [head_cast (here) j (by omega)] at *
+ exact (natAt j small).trans word
+ have kept := p.level
+ refine ⟨?_, (natAt 17 (by decide)).trans p.length,
+ fun j ↦ (natAt _ (by have := j.isLt; omega)).trans (p.residentHeads j), ?_, ?_,
+ p.oldRoom, p.nextRoom⟩
+ · rw [natAt 14 (by decide)]
+ exact ⟨takeWord 0 (by decide) _ kept.vertices, takeWord 1 (by decide) _ kept.degree,
+ takeWord 2 (by decide) _ kept.lanes, takeWord 3 (by decide) _ kept.residual,
+ takeWord 14 (by decide) _ kept.oldLayer, takeWord 15 (by decide) _ kept.rowStride,
+ takeWord 36 (by decide) _ kept.termHead, takeWord 37 (by decide) _ kept.termStride,
+ takeWord 38 (by decide) _ kept.layout, takeWord 43 (by decide) _ kept.abBank,
+ takeWord 44 (by decide) _ kept.owner, takeWord 45 (by decide) _ kept.rankHead,
+ takeWord 46 (by decide) _ kept.ids, takeWord 47 (by decide) _ kept.demandHead,
+ takeWord 57 (by decide) _ kept.actualOut, takeWord 58 (by decide) _ kept.actualIn,
+ takeWord 59 (by decide) _ kept.width⟩
+ · exact ⟨(natAt 39 (by decide)).trans p.supply.absolute,
+ (natAt 40 (by decide)).trans p.supply.successor,
+ (natAt 41 (by decide)).trans p.supply.inverse,
+ (natAt 42 (by decide)).trans p.supply.interval⟩
+ · apply HeadBank.keep_pointers p.successor
+ intro j lo hi
+ apply (same _ (.inr ?_)).symm
+ exact ⟨Nat.add_le_add_left lo _, (Nat.add_lt_add_left hi _).trans_le (Nat.le_add_right ..)⟩
+
+section Production
+
+variable {t cap : ℕ}
+local notation "prog" => BlockProgram.script B
+local notation "start" => Script.levelsPerBlock prog * t
+local notation "atOld" => start + i.val
+local notation "oldHead" => levelStart L atOld
+local notation "newHead" => levelStart L (atOld + 1)
+local notation "tableAt" => (fun j : Fin 6 ↦ tableBase L atOld j)
+local notation "oldInc" => packedIncidence L w atOld (DemandRAM.oldCount X)
+local notation "pt" => Workspace.ports (arity (Script.catalog prog)) base
+local notation "pub" => Ports.data pt
+variable {ms ps : List (SourceOnline.Packet (BlockProgram.script B) w)}
+
+/-- Capture the old and successor pointer words from the actual three terminal
+publication groups. The successor pitch is supplied by the next selected pass. -/
+theorem Words.of_tail (tail : ShrinkScheduledTail.Result B base positions blocks t cap i X m ms ps)
+ (header : ShrinkHeaderReads.Header i X oldInc (tableAt 0) L start m)
+ (oldBank : PortRefresh.TraversalHeaders.HeadBank L atOld (DemandRAM.oldCount X) m)
+ (nextBank : PortRefresh.TraversalHeaders.HeadBank L (atOld + 1) (actualCount sh) m)
+ (read : ShrinkOutput.ScheduledReadbacks B i X sel base positions blocks t oldInc m)
+ (rows : m (pt).rows.val = (directoryRows L : Word w))
+ (pitch : m (pub 1 - 1).val = (levelWords L : Word w))
+ (initial : m (levelStart L 0 + 29) = (n : Word w))
+ (live : t < blocks) (size : X.positions ≤ positions) (fit : endAddress L < 2 ^ w) :
+ Words B i X sel base positions blocks atOld n (post m ps) := by
+ have room := PublishedHeads.level_room B base positions blocks t i.val live i.isLt.le fit
+ have newRoom := PublishedHeads.level_room B base positions blocks t (i.val + 1) live i.isLt fit
+ have gap : oldHead + 66 ≤ newHead := before_next
+ have low := levelStart_mono L (Nat.zero_le atOld)
+ have eqn : start + (i.val + 1) = atOld + 1 := (Nat.add_assoc ..).symm
+ rw [eqn] at newRoom
+ have stable (j : ℕ) (small : j < 66) (metadata : j < 15 ∨ 27 ≤ j)
+ (published : j < 36 ∨ 54 ≤ j) : post m ps (oldHead + j) = m (oldHead + j) := by
+ apply tail.outside
+ · omega
+ · omega
+ · rw [eqn]; omega
+ · rw [eqn]; omega
+ refine ⟨?_, lengthWord tail n rows (by omega) initial,
+ fun j ↦ (stable _ (by have := j.isLt; omega) (.inr (by omega))
+ (.inl (by have := j.isLt; omega))).trans (read.hidden.heads j),
+ ShrinkPublishedSupplyWords.of_tail B i X sel base positions blocks t oldInc header
+ (fun j ↦ by
+ have h := oldBank.tables j
+ change m (oldHead + 60 + j.val) = _ at h
+ rw [← Nat.add_assoc]
+ exact h)
+ pitch live size fit tail, ?_, by omega, by omega⟩
+ · rw [stable 14 (by decide) (by decide) (by decide)]
+ exact oldLevel tail live size fit header oldBank pitch read
+ · apply HeadBank.keep_pointers nextBank
+ intro j lo _
+ apply tail.next_data
+ rw [eqn]
+ change 54 ≤ j at lo
+ omega
+
+end Production
+
+end PairSimulation.ShrinkResidentHeaders
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkResidentHeaders.lean b/lean/OAI/Computability/VPVNP/PairShrinkResidentHeaders.lean
new file mode 100644
index 0000000000..0db647ac9f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkResidentHeaders.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.PairShrinkCallABI
+import OAI.Computability.VPVNP.PairShrinkCallPublished
+import OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders
+import OAI.Computability.VPVNP.CompressorShrinkScheduledRetention
+import OAI.Computability.VPVNP.CompressorShrinkTailReadback
+import OAI.Computability.VPVNP.CompressorSelectedPayloadHistory
+
+/-!
+# Resident shrinking headers from the native publication groups
+
+The old level's descriptor and term words are read in the memory reached
+after the three terminal groups. The length word and directory pointers
+are retained with that level through the subsequent selected passes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkResidentHeaders
+
+open BurstRAM Compression CompressorRecords DescriptorSpace BlockPlanner PhaseRecipe Schedule
+open ShrinkBlockInputs ShrinkScheduledTail SourceOnline SourceTransport
+open scoped Fin.CommRing
+
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+variable {w g : ℕ} {base : Word w} {positions blocks t cap : ℕ} {i : Fin S.steps}
+variable {X : State (a i) (packingLaneBits (a i) g)} {sel : SelectedScore.Selection B X}
+variable {m : Memory w} {T : IncidenceDirectory w}
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "prog" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "first" => Script.levelsPerBlock prog * t
+local notation "cur" => first + i.val
+local notation "head" => levelStart L cur
+local notation "nxt" => levelStart L (first + (i.val + 1))
+local notation "tab" => (fun j : Fin 6 ↦ tableBase L cur j)
+local notation "pt" => Workspace.ports (arity (Script.catalog prog)) base
+local notation "pub" => Ports.data pt
+local notation "st" => (levelStart L first : Word w)
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "step" => (10 : Word w)
+local notation "score" => SelectedArena.origin X term step + 2
+local notation "layer" => Fin.val (m (head + 14))
+
+variable {ms ps : List (SourceOnline.Packet (BlockProgram.script B) w)}
+variable (tail : Result B base positions blocks t cap i X m ms ps)
+
+private theorem header_gap : head + 66 ≤ nxt := by
+ have sz : levelHeaderWords L = 66 := rfl
+ rw [← Nat.add_assoc]
+ simp only [levelStart, Nat.succ_mul, levelWords, sz]
+ omega
+
+include tail in
+/-- All the old fields consumed by a party are recovered from the actual
+metadata and head publications, including the selected score cell. -/
+theorem oldLevel (live : t < blocks) (size : X.positions ≤ positions) (fit : endAddress L < 2 ^ w)
+ (header : ShrinkHeaderReads.Header i X T (tab 0) L first m)
+ (bank : PortRefresh.TraversalHeaders.HeadBank L cur (DemandRAM.oldCount X) m)
+ (pitch : m (pub 1 - 1).val = (levelWords L : Word w))
+ (read : ShrinkOutput.ScheduledReadbacks B i X sel base positions blocks t T m) :
+ ShrinkCallHeader.Level X B.shrink sel (head : Word w) (post m ps) T (tab 0) layer
+ (B.recordLimit + 2) (tab 1) := by
+ have gap : head + 66 ≤ nxt := header_gap
+ have hc : head + 66 ≤ 2 ^ w := PublishedHeads.level_room B base positions blocks t i.val live
+ i.isLt.le fit
+ have keep (j : ℕ) (hj : j ≤ 65) (outside : j < 15 ∨ 27 ≤ j) :
+ post m ms (head + j) = m (head + j) :=
+ tail.baseFields.outside _ (by omega) (by omega) (by omega)
+ have hdr : ShrinkHeaderReads.Header i X T (tab 0) L first (post m ms) :=
+ ⟨header.room, (keep 0 (by decide) (by decide)).trans header.vertices,
+ (keep 1 (by decide) (by decide)).trans header.degree,
+ (keep 2 (by decide) (by decide)).trans header.lanes,
+ (keep 3 (by decide) (by decide)).trans header.residual,
+ fun j ↦ (keep _ (by have := j.isLt; omega) (.inr (by omega))).trans (header.incidence j),
+ (keep 60 (by decide) (by decide)).trans header.scratch⟩
+ have firstRoom := (levelStart_mono L (Nat.zero_le cur)).trans_lt (by omega : head < 2 ^ w)
+ have low := Window.lowCells (A := prog) L base rfl rfl firstRoom
+ have prior : (pub 1 - 1).val < head :=
+ low.2.trans_le (levelStart_mono L (Nat.zero_le cur))
+ have entry : LevelFields.Entry L first pub st (post m ms) :=
+ ⟨rfl, (tail.baseFields.outside _ (by omega) (by omega) (by omega)).trans pitch⟩
+ have sp := ShrinkOutput.table_space B i X base positions blocks t live size fit
+ have termRoom := sp.termRoom
+ let N := ShrinkTermSelection.bundles X * ShrinkTermSelection.ranks (a i)
+ change ShrinkInput.stop X (tab 0) + 2 * N + N * 10 < 2 ^ w at termRoom
+ have word : (term).val = ShrinkInput.stop X (tab 0) + 2 * N := Nat.mod_eq_of_lt (by omega)
+ have ten : (step).val = 10 := Nat.mod_eq_of_lt (by omega : (10 : ℕ) < 2 ^ w)
+ have matchScore : score = ShrinkInput.termEnd X (tab 0) 10 + 2 := by
+ change (term).val + ShrinkTermInputs.motifCount X * (step).val + 2 = _
+ rw [word, ten, ShrinkTermSelection.motifCount_eq]
+ rfl
+ have afterHead : head + 66 ≤ tab 0 := by
+ change head + 66 ≤ head + 66 + 6 * slotCapacity L + 0 * tableWords L
+ omega
+ have pastHead : head + 66 ≤ score := by
+ have h := afterHead.trans (ScorePackets.start_le_term i X (tab 0) sp.termRoom)
+ unfold SelectedArena.origin
+ omega
+ have beforeNext : score < nxt := by
+ have bound := (ShrinkOutput.old_bounds i X term step).2.2.trans_le sp.selectedWithin
+ have hi := tableEnd_le_nextLevel L cur (0 : Fin 6)
+ rw [Nat.add_assoc] at hi
+ exact bound.trans_le hi
+ have sfit : score < 2 ^ w := by
+ have h := PublishedHeads.level_room B base positions blocks t (i.val+1) live i.isLt fit
+ omega
+ have recorded : post m ms (((ShrinkInput.termEnd X (tab 0) 10 + 2 : ℕ) : Word w)).val =
+ ((X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth sel).toNat :
+ Word w) := by
+ rw [← matchScore, Fin.val_natCast, Nat.mod_eq_of_lt sfit]
+ exact (tail.baseFields.outside _ (by omega) (by omega) (by omega)).trans read.resident.chosen
+ have stride : post m ms (head + 15) = ((B.recordLimit + 2 : ℕ) : Word w) :=
+ tail.baseFields.payload 0
+ have oldBase : post m ms (head + 14) = (layer : Word w) :=
+ (keep 14 (by decide) (by decide)).trans (by simp)
+ have table : post m ms (head + 61) = (tab 1 : Word w) :=
+ (keep 61 (by decide) (by decide)).trans (bank.tables (1 : Fin 6))
+ have planRoom : (ShrinkInput.plan X (tab 0)).stop < 2 ^ w := by
+ change ShrinkInput.widthBase X (tab 0) + _ + _ + _ + _ < 2 ^ w at termRoom
+ change ShrinkInput.widthBase X (tab 0) < _
+ omega
+ rw [tail.image]
+ exact ShrinkCallHeader.Level.of_publications B i X sel T (tab 0) L first pub st (post m ms)
+ layer (B.recordLimit + 2) (tab 1) hdr entry (by omega) ⟨oldBase, stride⟩ recorded (by omega)
+ table planRoom tail.published.termGroup.source tail.published.dataGroup.source
+
+include tail in
+/-- The original length, copied into metadata cell 17, survives the term
+and data publishers which follow that copy. -/
+theorem lengthWord (n : ℕ) (rows : m (pt).rows.val = (directoryRows L : Word w))
+ (firstRoom : levelStart L 0 + 29 < 2 ^ w) (initial : m (levelStart L 0 + 29) = (n : Word w)) :
+ post m ps (head + 17) = (n : Word w) :=
+ (tail.metaCell _ (.inl (by omega))).trans
+ (ShrinkCallABI.length_published n B base positions blocks t i.val .shrink
+ (BlockMetadata.shrinkFields B i) tail.baseFields rows firstRoom initial)
+
+end PairSimulation.ShrinkResidentHeaders
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkResidentMemory.lean b/lean/OAI/Computability/VPVNP/PairShrinkResidentMemory.lean
new file mode 100644
index 0000000000..26c218b3c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkResidentMemory.lean
@@ -0,0 +1,320 @@
+import OAI.Computability.VPVNP.PairShrinkJobPrepared
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoop
+
+/-!
+# Child and hidden operands across the resident map loop
+
+Every selected map reads its input packets below the histogram and its
+shared hidden fields above it. Its writes affect the histogram, its own
+operand staging and its grouped-map workspace. The two input regions thus
+agree with the memory at the start of the loop after every successful map.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkResidentMemory
+
+open BurstRAM BurstRAM.PrivateRAM ShrinkCallFields
+open scoped Fin.CommRing
+
+variable {w p r : ℕ}
+
+/-- The two scratch memories agree below the histogram base and from the hidden base up to the
+staging base. -/
+structure Preserved (s : Scratch) (initial current : Word w → Word w) : Prop where
+ low : ∀ q : Word w, q.val < s.hist → current q = initial q
+ shared : ∀ q : Word w, s.hidden ≤ q.val → q.val < s.staging → current q = initial q
+
+theorem Preserved.refl (s : Scratch) (m : Word w → Word w) : Preserved s m m :=
+ ⟨fun _ _ ↦ rfl, fun _ _ _ ↦ rfl⟩
+
+theorem Preserved.trans {s : Scratch} {a b c : Word w → Word w}
+ (ab : Preserved s a b) (bc : Preserved s b c) : Preserved s a c :=
+ ⟨fun q h ↦ (bc.low q h).trans (ab.low q h),
+ fun q lo hi ↦ (bc.shared q lo hi).trans (ab.shared q lo hi)⟩
+
+theorem Preserved.stable (P : ResidentMapLoop.Program p r) (s : Scratch)
+ (initial : Word w → Word w) : P.Stable (fun c ↦ Preserved s initial c.privateMem) := by
+ intro c d old _ mem _
+ rw [mem]
+ exact old
+
+/-- Loop inputs include the live register words supplied by the locator and
+the resident operand cells carried across previous calls. -/
+structure Invariant (s : Scratch) (initial : Word w → Word w)
+ (live : Fin r → Prop) (expected : Fin r → Word w) (c : Config w p r) : Prop where
+ registers : ∀ j, live j → c.reg j = expected j
+ memory : Preserved s initial c.privateMem
+
+theorem Invariant.start (s : Scratch) (c : Config w p r) (live : Fin r → Prop) :
+ Invariant s c.privateMem live c.reg c :=
+ ⟨fun _ _ ↦ rfl, Preserved.refl s c.privateMem⟩
+
+theorem Invariant.stable (P : ResidentMapLoop.Program p r) (s : Scratch)
+ (initial : Word w → Word w) (live : Fin r → Prop) (expected : Fin r → Word w)
+ (away : ∀ j, live j → j ≠ P.cursor) : P.Stable (Invariant s initial live expected) := by
+ intro c d old frozen mem _
+ refine ⟨fun j hj ↦ (frozen j (away j hj)).trans (old.registers j hj), ?_⟩
+ rw [mem]
+ exact old.memory
+
+theorem Invariant.next {s : Scratch} {initial : Word w → Word w}
+ {live : Fin r → Prop} {expected : Fin r → Word w} {c d : Config w p r}
+ (old : Invariant s initial live expected c)
+ (frozen : ∀ j, live j → d.reg j = c.reg j) (mem : Preserved s initial d.privateMem) :
+ Invariant s initial live expected d :=
+ ⟨fun j hj ↦ (frozen j hj).trans (old.registers j hj), mem⟩
+
+/-- The histogram block of the terminal allocation precedes the first
+shared shrinking word. -/
+theorem histogram_before_hidden (R : LeafArena.Regions) (n t : ℕ) (ht : t ≤ R.histWords) :
+ R.histBase + t ≤ ShrinkCallABI.hiddenBase R n := by
+ change R.histBase + t ≤ R.cacheBase + 38 + _
+ exact ((Nat.add_le_add_left ht _).trans R.hist_before).trans
+ ((Nat.le_add_right ..).trans (Nat.le_add_right ..))
+
+end PairSimulation.ShrinkResidentMemory
+
+namespace PairSimulation.ShrinkCallFields
+
+open BurstRAM Compression Compression.ShrinkMotif MotifEntry MotifGrid MotifBlocks MotifConversion
+open ShrinkResidentMemory
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {factor : ℝ} {w p r k t u n limit : ℕ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable {grid : F.grid.demands} {j : Fin 6} (A : MapEntryTable.Allocation F grid j r k)
+variable (loc : A.Address → Fin p) (demand : Bool → ℕ) (payload : Bool × Fin 4 → ℕ)
+variable (d : DemandBits demandSource demandTarget demand j)
+variable (x : MotifSelector.Half supply (fun e ↦ Fin (payload e + u * F.selectorBits) → Bool) j)
+variable (s : Scratch) (ord : ℕ) (side : Bool) (cd : Bool → ℕ)
+variable (ok : Fits (w := w) (n := n) (limit := limit) (u := u) (t := t) F demand payload s ord cd)
+local notation "W" => workspace F (A.program loc) demand payload d x s ord side cd ok
+
+/-- Every word preceding operand staging and outside the actual histogram
+survives a successful resident gather and grouped-map execution. -/
+theorem resident_exterior {before after : Word w → Word w}
+ (histEnd : s.hist + t ≤ s.hidden)
+ {ptr : Word w} (address : ptr = (s.descriptor : Word w))
+ (memory : ∀ q : Word w, q.val < s.staging →
+ q.val < ptr.val ∨ ptr.val + Fintype.card Arg ≤ q.val →
+ MapCallSetup.Outside A loc W q → after q = before q) :
+ ∀ q : Word w, q.val < s.staging →
+ (q.val < s.hist ∨ s.hist + t ≤ q.val) → after q = before q := by
+ have room := ok.room.trans_lt ok.capacity.room
+ have dirFit : s.directory + 16 < 2 ^ w := by
+ unfold Scratch.target Scratch.source Scratch.descriptor at room
+ omega
+ have ptrVal : ptr.val = s.descriptor := by
+ rw [address]
+ exact Nat.mod_eq_of_lt dirFit
+ have stageDir : s.staging ≤ s.directory := Nat.le_add_right ..
+ have hiddenStage : s.hidden ≤ s.staging := Nat.le_add_right ..
+ have histRoom : s.hist + t < 2 ^ w :=
+ ((histEnd.trans hiddenStage).trans stageDir).trans_lt (by omega)
+ have sc := workspace_source F (A.program loc) demand payload d x s ord side cd ok
+ have ta := workspace_target F (A.program loc) demand payload d x s ord side cd ok
+ have srcStart : s.directory ≤ s.source := (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ have tgtStart : s.source ≤ s.target u := Nat.le_add_right ..
+ have keep (q : Word w) (hq : q.val < s.staging) (hh : q.val < s.hist ∨ s.hist + t ≤ q.val) :
+ after q = before q := by
+ apply memory q hq (.inl (ptrVal ▸ (hq.trans_le (stageDir.trans (Nat.le_add_right ..)))))
+ constructor
+ · refine ⟨.inl (sc ▸ hq.trans_le (stageDir.trans srcStart)),
+ .inl (ta ▸ hq.trans_le (stageDir.trans (srcStart.trans tgtStart))), ?_⟩
+ intro l eqn
+ have hv := congrArg Fin.val eqn
+ change q.val = ((s.hist + l.val : ℕ) : Word w).val at hv
+ rw [show ((s.hist + l.val : ℕ) : Word w).val = s.hist + l.val from
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left l.isLt _).trans histRoom)] at hv
+ rcases hh with lo | hi <;> have := l.isLt <;> omega
+ · intro a eqn
+ have len := MapPortAgreement.ports_length_le supply j A.edgeOrder
+ have card : 2 * Fintype.card (Bool × Fin 4) = 16 := by simp
+ rw [card] at len
+ have valid : s.directory + a.val < 2 ^ w :=
+ ((Nat.add_lt_add_left (a.isLt.trans_le len) _).trans dirFit)
+ have hv := congrArg Fin.val eqn
+ change q.val = ((s.directory : Word w) + (a.val : Word w)).val at hv
+ rw [← Nat.cast_add, show ((s.directory + a.val : ℕ) : Word w).val = s.directory + a.val
+ from Nat.mod_eq_of_lt valid] at hv
+ omega
+ exact keep
+
+/-- Apply the exterior frame returned by the installed gather and grouped
+matrix to both resident input regions. Each valid call preserves every
+other resident's child and shared words, regardless of its own motif or
+party. -/
+theorem resident_preserved {initial before after : Word w → Word w}
+ (previous : Preserved s initial before) (histEnd : s.hist + t ≤ s.hidden)
+ {ptr : Word w} (address : ptr = (s.descriptor : Word w))
+ (memory : ∀ q : Word w, q.val < s.staging →
+ q.val < ptr.val ∨ ptr.val + Fintype.card Arg ≤ q.val →
+ MapCallSetup.Outside A loc W q → after q = before q) :
+ Preserved s initial after := by
+ have keep := resident_exterior F A loc demand payload d x s ord side cd ok histEnd address memory
+ have hiddenStage : s.hidden ≤ s.staging := Nat.le_add_right ..
+ exact previous.trans ⟨fun q lo ↦ keep q (lo.trans_le
+ ((Nat.le_add_right s.hist t).trans (histEnd.trans hiddenStage))) (.inl lo),
+ fun q lo hi ↦ keep q hi (.inr (histEnd.trans lo))⟩
+
+end PairSimulation.ShrinkCallFields
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif
+open MotifBlocks MotifGrid MotifConversion NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots NodeArguments ShrinkResidentMemory
+open scoped Fin.CommRing
+
+variable {a b g w endAddr : ℕ} {K : Type} [_root_.Field K] {factor δ : ℝ}
+variable {X : State a (packingLaneBits a g)}
+variable {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+variable {m : X.packingData.Motif} {party : Fin 6} (J : Job X F ready sel m party w)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+variable {before after : Word w → Word w}
+local notation "side" => selectedLayout X F sel
+local notation "widths" => ShrinkPreparedCall.width F X sel
+local notation "Idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+
+/-- The lower arena still holds every independently chosen old half after a
+previous map has updated its own selector, labels and histogram. -/
+theorem Job.childWords_preserved (frame : Preserved J.scratch before after)
+ (child : J.ChildWords before endAddr)
+ (low : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ J.scratch.hist) :
+ J.ChildWords after endAddr := by
+ intro site atSite
+ exact ShrinkCallDemandCells.placedPackets_frame X side J.arena J.nodes
+ (child site atSite) low frame.low
+
+/-- All child and parent packet premises used by the actual party gather
+survive in the common input region. -/
+theorem Job.packets_preserved (frame : Preserved J.scratch before after)
+ (p : J.Packets endAddr before)
+ (childLow : ∀ u, J.arena.base (J.nodes u) + J.arena.stride ≤ J.scratch.hist)
+ (parentLow : J.arena.base J.node + J.arena.stride ≤ J.scratch.hist) :
+ J.Packets endAddr after := by
+ refine ⟨fun dir hit ↦ ShrinkCallDemandCells.placedPackets_frame X side J.arena J.nodes
+ (p.old dir hit) childLow frame.low, p.oldEnd, p.parentFit, ?_, p.parentEnd,
+ p.abStride, p.abRoom, p.supplyStride, p.supplyRoom⟩
+ apply p.parentStored.congr
+ intro i
+ let a : Word w := ((J.arena.base J.node + i.val : ℕ) : Word w)
+ have val : a.val = J.arena.base J.node + i.val := Nat.mod_eq_of_lt
+ ((Nat.add_lt_add_left i.isLt _).trans_le p.parentFit.2.2)
+ have lo : endAddr ≤ a.val := val ▸ p.parentFit.1.trans (Nat.le_add_right ..)
+ have hi : a.val < J.scratch.hist := val ▸
+ (Nat.add_lt_add_left (i.isLt.trans_le p.parentFit.2.1) _).trans_le parentLow
+ change rawScratch (DFS.scratch endAddr after) a = rawScratch (DFS.scratch endAddr before) a
+ simpa only [rawScratch, dite_eq_left lo, DFS.scratch] using frame.low a hi
+
+/-- Hidden fields belonging to the current motif survive calls for any
+earlier resident, including a different party at the same packed site. -/
+theorem Job.absorbed_preserved
+ (hidden : Placed (X.packingData.shrinkInternalOwner side) (internalLabel widths side)
+ (X.packingData.shrinkPartySite side m party))
+ (frame : Preserved J.scratch before after)
+ (h : ShrinkCallSupplyCells.Absorbed X side widths m party J.scratch hidden before)
+ (ordinal : Idx < J.scratch.motifs)
+ (bound : ∀ t, widths m (!side, t) ≤ J.scratch.stride) (room : J.scratch.staging ≤ 2 ^ w) :
+ ShrinkCallSupplyCells.Absorbed X side widths m party J.scratch hidden after := by
+ intro t own i
+ let a := J.scratch.shared Idx t + i.val
+ have hi : a < J.scratch.staging :=
+ (Nat.add_lt_add_left (i.isLt.trans_le (bound t)) _).trans_le (J.scratch.shared_end ordinal t)
+ have low : J.scratch.hidden ≤ a := (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ have val : (a : Word w).val = a := Nat.mod_eq_of_lt (hi.trans_le room)
+ exact (frame.shared (a : Word w) (by rw [val]; exact low) (by rw [val]; exact hi)).trans
+ (h t own i)
+
+end PairSimulation.ShrinkPartyNative
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open MotifBlocks MotifGrid MotifConversion MotifEntry NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots ShrinkResidentMemory
+open scoped Fin.CommRing
+
+variable {a b g w t n limit : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (degree : ℕ) (ord : B.Entry → Fin t) {δ : ℝ}
+variable (X : State a (packingLaneBits a g))
+variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) (sel : X.ShrinkSelection B.shrink)
+variable (m : X.packingData.Motif) (j : Fin 6) (J : Job X B.shrink ready sel m j w)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+local notation "BW" => ShrinkPreparedCall.widthsDemand X m
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+local notation "cd" => ShrinkCallDemandCells.cdBase X m J.arena J.nodes
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel))
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m j))
+local notation "call" => Job.entryInput B X ready sel m j J hidden
+local notation "L" =>
+ MapHandlerOperand.layout (ShrinkCallABI.family B degree a ord) demandMass_pos call
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (ShrinkPreparedCall.widthsDemand X m)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X m) (sel m).val J.scratch (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallDemandCells.cdBase X m J.arena J.nodes))
+local notation "W" => Job.mapWorkspace B degree ord X ready sel m j J hidden ok
+
+/-- The private-memory conclusion of the scheduled row interpreter maintains
+the resident loop's invariant for the actual selected map workspace. -/
+theorem Job.resident_preserved {initial before after : Word w → Word w}
+ (prior : Preserved J.scratch initial before) (histEnd : J.scratch.hist + t ≤ J.scratch.hidden)
+ {ptr : Word w} (address : ptr = (J.scratch.descriptor : Word w))
+ (frame : ∀ q : Word w, q.val < J.scratch.staging →
+ q.val < ptr.val ∨ ptr.val + Fintype.card ShrinkCallFields.Arg ≤ q.val →
+ MapCallSetup.Outside (L).core ((L).corePC (L).locations) W q → after q = before q) :
+ Preserved J.scratch initial after :=
+ ShrinkCallFields.resident_preserved B.shrink (L).core ((L).corePC (L).locations) BW (sel m).val
+ (demandBits demandSource demandTarget j (LocalHistory.EntryInput.demandBits call))
+ (MotifSelector.mapHalf supply (fun _ ↦ inputBits) (LocalHistory.EntryInput.supplyBits call))
+ J.scratch idx side cd ok prior histEnd address frame
+
+/-- The job header places the map descriptor sixteen words after its
+private pointer directory. This recovers the pointer in the exterior frame
+from the actual level fields and the live register bank. -/
+theorem Job.descriptor_address (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w)
+ {level : Word w} {T : IncidenceDirectory w} {origin : ℕ}
+ (old : J.OldPublished (ShrinkCallABI.operands degree) pub st mem level T origin) :
+ (((ShrinkCallABI.operands degree).inputs a).descriptor).eval pub st mem =
+ (J.scratch.descriptor : Word w) := by
+ let O := ShrinkCallABI.operands degree
+ have h := ShrinkCallHeader.heads X B.shrink sel m O pub st level mem J.arena T origin
+ J.older J.pitch J.first J.scratch.hidden J.scratch.stride J.scratch.hist old.levelData old.live
+ change O.hidden.eval pub st mem + 4 * (O.count a).eval pub st mem * O.slotStride.eval pub st mem
+ + 9 * O.slotStride.eval pub st mem + 16 = _
+ rw [old.live.hiddenBase, old.live.stride, h.motifs, ← old.motifCount]
+ simp only [ShrinkCallFields.Scratch.descriptor, ShrinkCallFields.Scratch.directory,
+ ShrinkCallFields.Scratch.staging, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+
+/-- Maintain the full loop invariant using the frozen live registers and
+the exterior memory clause of a successful selected resident map. -/
+theorem Job.keepsInputs {p r : ℕ} {initial : Word w → Word w}
+ {live : Fin r → Prop} {expected : Fin r → Word w} {c out : Config w p r}
+ (prior : Invariant J.scratch initial live expected c)
+ (frozen : ∀ a, live a → out.reg a = c.reg a)
+ (histEnd : J.scratch.hist + t ≤ J.scratch.hidden)
+ (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w)
+ {level : Word w} {T : IncidenceDirectory w} {origin : ℕ}
+ (old : J.OldPublished (ShrinkCallABI.operands degree) pub st mem level T origin)
+ (frame : let ptr := (((ShrinkCallABI.operands degree).inputs a).descriptor).eval pub st mem
+ ∀ q : Word w, q.val < J.scratch.staging →
+ q.val < ptr.val ∨ ptr.val + Fintype.card ShrinkCallFields.Arg ≤ q.val →
+ MapCallSetup.Outside (L).core ((L).corePC (L).locations) W q →
+ out.privateMem q = c.privateMem q) :
+ Invariant J.scratch initial live expected out :=
+ prior.next frozen (Job.resident_preserved B degree ord X ready sel m j J hidden ok prior.memory
+ histEnd (Job.descriptor_address B degree X ready sel m j J pub st mem old) frame)
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkResidentPublication.lean b/lean/OAI/Computability/VPVNP/PairShrinkResidentPublication.lean
new file mode 100644
index 0000000000..e5d5db76bb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkResidentPublication.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.PairShrinkResidentHeaderWords
+import OAI.Computability.VPVNP.PairShrinkSiteBank
+import OAI.Computability.VPVNP.PairShrinkResidentSources
+
+/-!
+# Recovering both native party contracts in the retained memory
+
+The old and new DFS layer words select the actual node addresses. The
+two contracts use the same party, selected term, private arena and
+register bank. The surviving endpoints use the next pass's pitch word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkResidentPublication
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.ShrinkMotif CompressorRecords
+open DescriptorSpace ShrinkBlockInputs ShrinkSlots ShrinkPartyNative
+open scoped Fin.CommRing
+
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} {δ : ℝ} (X : State (a i) (packingLaneBits (a i) g))
+variable (ready : Ready (2 ^ a i) (Shrink.colors (a i)) (2 ^ b i) δ)
+variable (sel : SelectedScore.Selection B X) (m : X.packingData.Motif) (party : Fin 6)
+variable (base : Word w) (positions blocks cur : ℕ)
+variable (bounds : ShrinkResidentSources.Bounds B i X base positions blocks cur)
+variable (n rowEnd older later : ℕ)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "here" => levelStart L cur
+local notation "next" => levelStart L (cur + 1)
+local notation "cut" => tableBase L cur (0 : Fin 6)
+local notation "term" => ShrinkInput.termHead (w := w) X cut
+local notation "sh" => levelShape (b := b i) X
+local notation "heads" => ShrinkOutput.heads sh (SelectedArena.roleBase X term 10)
+ (tableBase L cur (3 : Fin 6))
+local notation "absolute" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X cut) w
+local notation "T" => packedIncidence L w cur (DemandRAM.oldCount X)
+local notation "U" => packedIncidence L w (cur + 1) (actualCount sh)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "Y" => X.shrinkNext B.shrink ready sel
+local notation "site" => X.packingData.shrinkPartySite side m party
+local notation "degree" => slotDegree S
+local notation "R" => TerminalLayout.privateRegions degree n rowEnd (Fintype.card B.Entry)
+
+variable (child : ShrinkCallDemandCells.Old X (selectedLayout X B.shrink sel) m party)
+variable (parent : (X.shrinkNext B.shrink ready sel).network.Half
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m party))
+local notation "J" => ShrinkCanonicalJob.job B i X ready sel m party base positions blocks cur
+ bounds n rowEnd older later child parent
+variable (mem : Memory w)
+local notation "O" => ShrinkCallABI.operands degree
+
+section Bank
+variable (P : Fin 5 → Word w) (state : Word w)
+
+set_option maxHeartbeats 1500000 in
+-- The old and successor graph types reduce through the canonical job and both slot directories.
+/-- Decode the old and successor party headers from the selected payload and
+the DFS locator's live inputs. All table and field capacity bounds come
+from the shrinking level allocation. -/
+private theorem bank (words : ShrinkResidentHeaders.Words B i X sel base positions blocks cur n mem)
+ (data : ShrinkResidentSources.Data B i X ready sel base positions blocks cur mem)
+ (oldLayer : mem (here + 14) = (older : Word w))
+ (newLayer : mem (next + 14) = (later : Word w))
+ (newStride : mem (next + 15) = ((B.recordLimit + 2 : ℕ) : Word w))
+ (locator : P 0 = (here : Word w))
+ (motif : state.val = (ShrinkMotifOrder.stateNumber X m).val)
+ (hidden : P 4 = (ShrinkCallABI.hiddenBase R n : Word w))
+ (hist : P 3 = ((R).histBase : Word w))
+ (node : P 1 = ((J).node : Word w)) :
+ (J).OldPublished O P state mem (here : Word w) T cut ∧
+ (J).SupplyPublished O ShrinkCallABI.node P state mem heads absolute U later
+ (B.recordLimit + 2) := by
+ have geom := ShrinkCanonicalJob.geometry B i X ready sel m base positions blocks cur bounds
+ have word (k : ℕ) (small : k ≤ 65) : (((here : Word w) + (k : Word w))).val = here + k := by
+ have room := words.oldRoom
+ rw [← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ have baseVal : (here : Word w).val = here := Nat.mod_eq_of_lt (by have := words.oldRoom; omega)
+ have layer : mem ((here : Word w) + 14).val = (older : Word w) := by
+ rw [show (14 : Word w) = ((14 : ℕ) : Word w) from rfl, word 14 (by decide)]
+ exact oldLayer
+ have len : mem ((here : Word w) + 17).val = (n : Word w) := by
+ rw [show (17 : Word w) = ((17 : ℕ) : Word w) from rfl, word 17 (by decide)]
+ exact words.length
+ have lengthAt : mem (P 0 + 17).val = (n : Word w) := by rw [locator, len]
+ have live : ShrinkCallHeader.Live X m O P state (here : Word w) mem (R).arguments
+ (ShrinkCallABI.hiddenBase R n) (n ^ 2) (R).histBase := by
+ refine ⟨locator, motif, lengthAt, ?_, hidden, ?_, hist⟩
+ · change ((2 * degree : ℕ) : Word w) * mem (P 0 + 17).val + 1 =
+ ((2 * degree * n + 1 : ℕ) : Word w)
+ simp only [lengthAt, Nat.cast_add, Nat.cast_mul, Nat.cast_one]
+ · change mem (P 0 + 17).val * mem (P 0 + 17).val = ((n ^ 2 : ℕ) : Word w)
+ rw [lengthAt, pow_two, Nat.cast_mul]
+ have old : (J).OldPublished O P state mem (here : Word w) T cut :=
+ ⟨{words.level with oldLayer := layer},
+ live,
+ rfl, data.old, geom.rank, geom.ab, data.slices.abFields _⟩
+ refine ⟨old, Job.SupplyPublished.of_header (J) O ShrinkCallABI.node old heads U next later
+ (B.recordLimit + 2) ?_ ?_ ?_ ?_ ?_ ?_ newLayer newStride ?_ ?_ ?_ data.absolute data.sorted
+ geom.absolute geom.slot geom.degree geom.two geom.lanes geom.allocation ?_ data.successor
+ geom.capacity node⟩
+ · rw [baseVal]; have := words.oldRoom; omega
+ · have := words.nextRoom; omega
+ · rw [baseVal]; exact words.supply.absolute
+ · rw [baseVal]; exact words.supply.successor
+ · rw [baseVal]; exact words.supply.inverse
+ · rw [baseVal]; exact words.supply.interval
+ · exact words.successor.incidence (3 : Fin 6)
+ · exact words.successor.incidence (4 : Fin 6)
+ · exact words.successor.incidence (5 : Fin 6)
+ · intro j
+ have h := data.slices.intervals j
+ rw [geom.split_eq] at h
+ exact h
+
+end Bank
+
+local notation "P" => ShrinkSiteBank.pub (here : Word w) (Job.node J : Word w) R n
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+local notation "stateWord" => (idx : Word w)
+
+/-- The static five-word bank gives the same two native contracts for each
+resident party, whether its map is reached during a scan or read as a row. -/
+theorem published_words
+ (words : ShrinkResidentHeaders.Words B i X sel base positions blocks cur n mem)
+ (data : ShrinkResidentSources.Data B i X ready sel base positions blocks cur mem)
+ (oldLayer : mem (here + 14) = (older : Word w))
+ (newLayer : mem (next + 14) = (later : Word w))
+ (newStride : mem (next + 15) = ((B.recordLimit + 2 : ℕ) : Word w)) :
+ (J).OldPublished O P stateWord mem (here : Word w) T cut ∧
+ (J).SupplyPublished O ShrinkCallABI.node P stateWord mem heads absolute U later
+ (B.recordLimit + 2) := by
+ have fit := (ShrinkCanonicalJob.geometry B i X ready sel m base positions blocks cur
+ bounds).absolute
+ apply bank B i X ready sel m party base positions blocks cur bounds n rowEnd older later child
+ parent mem P stateWord words data oldLayer newLayer newStride rfl _ rfl rfl rfl
+ exact Nat.mod_eq_of_lt (by omega : idx < 2 ^ w)
+
+variable {p r : ℕ} (cfg : Config w p r) (common : Fin 24 ↪ Fin r)
+local notation "regPub" => ShrinkCallABI.pub cfg common
+local notation "regState" => ShrinkCallABI.state cfg common
+
+/-- The locator and map-loop registers instantiate the same resident operands. -/
+theorem published
+ (words : ShrinkResidentHeaders.Words B i X sel base positions blocks cur n mem)
+ (data : ShrinkResidentSources.Data B i X ready sel base positions blocks cur mem)
+ (oldLayer : mem (here + 14) = (older : Word w))
+ (newLayer : mem (next + 14) = (later : Word w))
+ (newStride : mem (next + 15) = ((B.recordLimit + 2 : ℕ) : Word w))
+ (locator : cfg.reg (common 11) = (here : Word w))
+ (motif : (cfg.reg (common 18)).val = idx)
+ (hidden : cfg.reg (common 8) = (ShrinkCallABI.hiddenBase R n : Word w))
+ (hist : cfg.reg (common 10) = ((R).histBase : Word w))
+ (node : cfg.reg (common 0) = ((J).node : Word w)) :
+ (J).OldPublished O regPub regState mem (here : Word w) T cut ∧
+ (J).SupplyPublished O ShrinkCallABI.node regPub regState mem heads absolute U later
+ (B.recordLimit + 2) :=
+ bank B i X ready sel m party base positions blocks cur bounds n rowEnd older later child parent
+ mem regPub regState words data oldLayer newLayer newStride locator motif hidden hist node
+
+end PairSimulation.ShrinkResidentPublication
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkResidentSourceCapture.lean b/lean/OAI/Computability/VPVNP/PairShrinkResidentSourceCapture.lean
new file mode 100644
index 0000000000..ae84ffd7d7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkResidentSourceCapture.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.PairShrinkResidentSources
+import OAI.Computability.VPVNP.PairShrinkPhysicalSourceBounds
+import OAI.Computability.VPVNP.PairShrinkResidentTermCapture
+import OAI.Computability.VPVNP.CompressorShrinkScheduledOutput
+import OAI.Computability.VPVNP.CompressorShrinkTailRetention
+
+/-!
+# Capturing the resident sources from the selected shrink execution
+
+Parts 5 through 11 preserve the old incidence words and table zero. The
+resident publications lie in the old header or table five, the three scans
+begin at table one, and the incidence copy writes at the successor. Thus the
+old ports, ranks, dense demand pairs and selected term rows can be read in
+the same snapshot as the computed slices and ordered endpoint rectangles.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkResidentSources
+
+open BurstRAM Compression CompressorRecords CompressorRecords.DescriptorSpace
+open CompressorRecords.ShrinkBlockInputs BlockPlanner SourceOnline
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {i : Fin S.steps}
+variable {g w : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+variable {sel : SelectedScore.Selection B X} {base : Word w} {positions blocks t fuel cap : ℕ}
+
+local notation "prog" => BlockProgram.script B
+local notation "lay" => BlockProgram.layout B base.val positions blocks
+local notation "cur" => Script.levelsPerBlock prog * t + i.val
+local notation "nxt" => Script.levelsPerBlock prog * t + (i.val + 1)
+local notation "tab" => (fun j : Fin 6 => tableBase lay cur j)
+local notation "T" => packedIncidence lay w cur (DemandRAM.oldCount X)
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "dense" => ShrinkInput.demandHead (w := w) X (tab 0)
+local notation "step" => (10 : Word w)
+local notation "origin" => SelectedArena.origin X term step
+local notation "args" => BlockSlices.abInputs i (BlockProgram.arena B i.val 0)
+ (BlockProgram.arena B i.val 1)
+
+variable {ps₅ ps₆ ps₇ ps₈ ms ps : List (SourceOnline.Packet (BlockProgram.script B) w)}
+variable {r : ShrinkOutput.TablesRun w}
+local notation "allParts" => (((ps₅ ++ ps₆) ++ ps₇) ++ ps₈)
+
+set_option maxHeartbeats 1600000 in
+-- Comparing the four physical windows expands their layouts at the current and successor levels.
+/-- The old incidence area and all of table zero survive the resident passes,
+three output scans, successor copy, and terminal header publications. -/
+theorem source_frame {m : Memory w}
+ (run : ScheduledShrink.Output B i X sel base positions blocks t cap m ps₅ ps₆ ps₇ ps₈ r)
+ (tail : ShrinkScheduledTail.Result B base positions blocks t cap i X (post m allParts) ms ps)
+ (live : t < blocks) (size : X.positions ≤ positions) (room : endAddress lay < 2 ^ w)
+ (x : ℕ) (lo : incidenceStart lay cur ≤ x) (hi : x < tab 1) :
+ post (post m allParts) ps x = m x := by
+ have headLo : levelStart lay cur + 66 ≤ x := lo
+ have beforeNext : tab 1 ≤ levelStart lay nxt := by
+ rw [show nxt = cur + 1 by omega]
+ exact (Nat.le_add_right ..).trans (tableEnd_le_nextLevel lay cur (1 : Fin 6))
+ have earlier := hi.trans_le beforeNext
+ have firstResident : tab 1 ≤ tab 5 := (Nat.le_add_right ..).trans
+ (tableEnd_le_tableBase lay cur (show (1 : Fin 6) < 5 by decide))
+ have residents := run.residents.preserved x (by
+ rintro (data | header)
+ · exact (hi.trans_le firstResident).not_ge data.1
+ · change _ ∧ x < levelStart lay cur + 36 at header
+ omega)
+ have scan := ShrinkOutput.scheduled_frame B i X sel base positions blocks t args
+ (post m ps₅) (post m ps₅) cap r ps₈ live size room run.tables
+ run.slotReports x (.inl hi) (.inl (earlier.trans_le (Nat.le_add_right ..)))
+ apply (tail.old_data x (by omega) earlier).trans
+ rw [post_append, run.postWidth]
+ exact scan.trans residents
+
+set_option maxHeartbeats 1600000 in
+-- The dependent row types include the selected degree, numbering, and physical table heads.
+/-- The actual completed shrink pass and its terminal publications establish
+all resident operands in one chronological snapshot. -/
+theorem Data.capture {initial : Memory w}
+ {p : ShrinkBranch.Prefix X T (tab 0) fuel initial}
+ (v : ShrinkBranch.Selected B X T (tab 0) step (B.shrink.selectorBits : Word w)
+ fuel initial p sel)
+ (run : ScheduledShrink.Output B i X sel base positions blocks t cap
+ v.beforeOutput ps₅ ps₆ ps₇ ps₈ r)
+ (tail : ShrinkScheduledTail.Result B base positions blocks t cap i X
+ (post v.beforeOutput allParts) ms ps)
+ (live : t < blocks) (size : X.positions ≤ positions) (room : endAddress lay < 2 ^ w) :
+ Data B i X (S.shrink i) sel base positions blocks cur
+ (post (post v.beforeOutput allParts) ps) := by
+ have fits := bounds B i X base positions blocks t live size room
+ have wide : (step).val = 10 := by
+ have startRoom := ScorePackets.start_le_term i X (tab 0) fits.termRoom
+ have lo : levelStart lay cur + 66 ≤ tab 0 := by
+ change levelStart lay cur + 66 ≤ levelStart lay cur + 66 + 6 * slotCapacity lay + 0 * _
+ omega
+ exact Nat.mod_eq_of_lt (show 10 < 2 ^ w from by have := (term).isLt; omega)
+ have termRoom : ShrinkInput.termEnd X (tab 0) (step).val < 2 ^ w := wide ▸ fits.termRoom
+ have stopRoom : ShrinkInput.stop X (tab 0) < 2 ^ w := by
+ unfold ShrinkInput.termEnd at termRoom
+ omega
+ obtain ⟨preimages, ranked⟩ := p.input.original_after_absolute p.absoluteRun stopRoom
+ (fun x hx => v.lowerFrame x (hx.trans_le (ShrinkInput.range_bounds X (tab 0)).2.2.2))
+ have geometry := p.input.keepAbsoluteThenTerms p.absoluteRun.frame (step).val termRoom
+ v.lowerFrame
+ have old : ShrinkCallHeader.OldTables X v.beforeOutput T (tab 0) :=
+ ⟨preimages, ranked, geometry.incidence.actual, geometry.placement⟩
+ have frame := source_frame run tail live size room
+ have startLo : incidenceStart lay cur ≤ tab 0 :=
+ (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ have ranges := ShrinkInput.range_bounds X (tab 0)
+ have denseAddr : (dense).val = ShrinkInput.stop X (tab 0) := Nat.mod_eq_of_lt stopRoom
+ have sourceLo : incidenceStart lay cur ≤ (dense).val := denseAddr ▸
+ startLo.trans (ranges.1.trans (ranges.2.1.trans (ranges.2.2.1.trans ranges.2.2.2)))
+ have originEnd : origin ≤ tab 1 := by
+ have selected := (ShrinkOutput.old_bounds i X term step).2.2
+ exact (Nat.le_add_right ..).trans (selected.le.trans
+ (ShrinkOutput.table_space B i X base positions blocks t live size room).abAfter)
+ obtain ⟨pairs, fields⟩ := v.term_capture termRoom wide.ge
+ (fun x low high => frame x (sourceLo.trans low) (high.trans_le originEnd))
+ have read := tail.readbacks sel T run.readbacks live size room
+ refine ⟨fits.oldTables old frame, pairs, ?_, read.hidden.directories, read.resident.directory,
+ read.slices, read.ordered, ?_⟩
+ · simpa only [wide] using fields
+ · rw [show cur + 1 = nxt by omega]
+ exact read.incidence.actual
+
+end PairSimulation.ShrinkResidentSources
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkResidentSources.lean b/lean/OAI/Computability/VPVNP/PairShrinkResidentSources.lean
new file mode 100644
index 0000000000..a82f15e0b3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkResidentSources.lean
@@ -0,0 +1,184 @@
+import OAI.Computability.VPVNP.PairShrinkInputRetention
+import OAI.Computability.VPVNP.CompressorShrinkResidentFinal
+import OAI.Computability.VPVNP.CompressorShrinkReadbackTransfer
+import OAI.Computability.VPVNP.CompressorShrinkSlotRetention
+import OAI.Computability.VPVNP.CompressorSelectedPayloadHistory
+import OAI.Computability.VPVNP.CompressorBlockProgram
+import OAI.Computability.VPVNP.CompressorCurrentGraph
+import OAI.Computability.VPVNP.PairShrinkPhysicalSourceBounds
+import OAI.Computability.VPVNP.PairShrinkResidentTermCapture
+import OAI.Computability.VPVNP.CompressorShrinkSliceInterval
+
+/-!
+# Source records of a selected shrinking level
+
+The input incidence, old-port lists, sorted ranks, dense demand pairs, term
+words, resident directories, slice banks and ordered-slot rectangles occupy
+the producing level. The copied successor incidence occupies its own
+canonical bank. All components here describe one selected branch at one
+chronological level and one memory snapshot.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkResidentSources
+
+open BurstRAM Compression CompressorRecords CompressorRecords.DescriptorSpace
+open CompressorRecords.ShrinkBlockInputs Compression.ShrinkMotif ShrinkSlots
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} {δ : ℝ} (X : State (a i) (packingLaneBits (a i) g))
+variable (ready : Ready (2 ^ a i) (Shrink.colors (a i)) (2 ^ b i) δ)
+variable (sel : SelectedScore.Selection B X) (base : Word w) (positions blocks cur : ℕ)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "lay" => BlockProgram.layout B base.val positions blocks
+local notation "cut" => tableBase lay cur (0 : Fin 6)
+local notation "first" => tableBase lay cur (1 : Fin 6)
+local notation "width" => tableBase lay cur (2 : Fin 6)
+local notation "slots" => tableBase lay cur (3 : Fin 6)
+local notation "resident" => tableBase lay cur (5 : Fin 6)
+local notation "term" => ShrinkInput.termHead (w := w) X cut
+local notation "dense" => ShrinkInput.demandHead (w := w) X cut
+local notation "absHead" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X cut) w
+local notation "side" => SelectedFinish.chosen B X sel
+local notation "shape" => levelShape (b := b i) X
+local notation "heads" => ShrinkOutput.heads shape (SelectedArena.roleBase X term 10) slots
+local notation "sourceInc" => packedIncidence lay w cur (DemandRAM.oldCount X)
+local notation "nextInc" => packedIncidence lay w (cur + 1) (actualCount shape)
+
+/-- Typed data consumed by resident-party handlers after the native
+shrinking pass and its successor-incidence copy. -/
+structure Data (mem : Memory w) : Prop where
+ old : ShrinkCallHeader.OldTables X mem sourceInc cut
+ pairs : ShrinkTermInputs.statePairs X dense mem
+ terms : ∀ m, TermRecordScan.Fields B.shrink ShrinkSliceArrays.supplyRoles
+ demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m) (sel m).val
+ (ShrinkTermSelection.rowBase X term 10 m) mem
+ residents : ∀ maps, ShrinkHistoryRows.Directory (ShrinkResidentDirectory.oldOrder X maps)
+ (ShrinkHistoryRows.packedOrder X) (ShrinkResidentDirectory.place X maps side)
+ (ShrinkResidentRun.outputBank X resident maps) mem
+ absolute : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absHead mem
+ slices : ShrinkOutput.SliceReadbacks B i X sel term 10 first width mem
+ sorted : Build.OrderedTables X ready side heads mem
+ successor : (nextInc).ActualColumns (X.shrinkNext B.shrink ready sel) mem
+
+variable {B i X ready sel base positions blocks cur}
+variable {before out : Memory w}
+
+private theorem table_range (L : Layout) (level : ℕ) (t : Fin L.shape.tables) :
+ levelStart L level ≤ tableBase L level t ∧ tableBase L level t ≤ levelStart L (level + 1) :=
+ ⟨((Nat.le_add_right ..).trans (Nat.le_add_right ..)).trans (Nat.le_add_right ..),
+ (Nat.le_add_right ..).trans (tableEnd_le_nextLevel L level t)⟩
+
+private theorem successor_actual
+ (bounds : Bounds B i X base positions blocks cur)
+ (data : (nextInc).ActualColumns (X.shrinkNext B.shrink ready sel) before)
+ (agree : SourceTransport.Agree (SelectedPayloadHistory.Cells lay cur) before out) :
+ (nextInc).ActualColumns (X.shrinkNext B.shrink ready sel) out := by
+ let Y := X.shrinkNext B.shrink ready sel
+ let j : Fin (lay).levels := ⟨cur + 1, bounds.nextLive⟩
+ have total : IncidenceDirectory.slotCount Y = actualCount shape :=
+ (next_counts X B.shrink ready sel).2
+ have read (c : Fin 6) (e : (Y.Base × BitWord g) × Fin (2 ^ b i)) :
+ out ((nextInc).column c + IncidenceDirectory.actualPort Y e).val =
+ before ((nextInc).column c + IncidenceDirectory.actualPort Y e).val := by
+ have hi := (IncidenceDirectory.actualPort_lt Y e (w := w)).trans_eq total
+ have range := CurrentGraph.column_range lay j _ bounds.nextCapacity bounds.room c _ hi
+ apply (agree _ (.inr ⟨?_, range.2⟩)).symm
+ apply le_trans _ range.1
+ change levelStart lay (cur + 1) + 54 ≤ levelStart lay (cur + 1) + 66
+ omega
+ exact ⟨fun e ↦ (read 3 e).trans (data.actualOut e),
+ fun e ↦ (read 4 e).trans (data.actualIn e), fun e ↦ (read 5 e).trans (data.width e)⟩
+
+private theorem absolute_transfer (bounds : Bounds B i X base positions blocks cur)
+ (stored : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absHead before)
+ (keep : ∀ x, cut ≤ x → x < first → out x = before x) :
+ MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absHead out := by
+ let Z := ShrinkInput.plan X cut
+ have ranges := ShrinkInput.range_bounds X cut
+ have room : ShrinkInput.stop X cut < 2 ^ w := by
+ have tr := bounds.termRoom
+ unfold ShrinkInput.termEnd at tr
+ omega
+ have fit := ranges.2.2.2.trans_lt room
+ have rankBefore : Z.ranks ≤ ShrinkInput.widthBase X cut := Nat.le_add_right ..
+ have eqn : Z.gathered + Z.B * Z.Q + Z.B * Z.Q = Z.ranks := by
+ change _ = Z.gathered + (2 * Z.B) * Z.Q
+ ring
+ have raw : (absHead).val = Z.gathered + Z.B * Z.Q :=
+ Nat.mod_eq_of_lt (show Z.gathered + Z.B * Z.Q < 2 ^ w by omega)
+ have below : cut ≤ Z.gathered := by
+ have lower := ranges.1.trans ranges.2.1
+ change cut ≤ ShrinkInput.rankBase X cut + 2 * Z.A + 2 * Z.B + Z.rectangleSize
+ omega
+ intro j
+ have hj : j.val < Z.B * Z.Q := j.isLt
+ have upper := ranges.2.2.2.trans bounds.fresh
+ rw [keep _ (by rw [raw]; omega) (by rw [raw]; omega)]
+ exact stored j
+
+/-- Transfer all typed inputs to the memory of a later parser call. Only
+the producing level and the successor's pointer and incidence bank are
+used, so writes to its scalar header and workspace are allowed. -/
+theorem Data.transfer (d : Data B i X ready sel base positions blocks cur before)
+ (bounds : Bounds B i X base positions blocks cur)
+ (agree : SourceTransport.Agree (SelectedPayloadHistory.Cells lay cur) before out) :
+ Data B i X ready sel base positions blocks cur out := by
+ let next := levelStart lay (cur + 1)
+ have keep (x : ℕ) (low : levelStart lay cur ≤ x) (high : x < next) : out x = before x :=
+ (agree x (.inl ⟨low, high⟩)).symm
+ have fit : next < 2 ^ w := (levelStart_mono lay bounds.nextLive.le).trans_lt bounds.room
+ have header : levelStart lay cur + 66 ≤ next := by
+ change levelsBase lay + cur * levelWords lay + 66 ≤ levelsBase lay + (cur + 1) * levelWords lay
+ rw [Nat.succ_mul]
+ have hw : 66 ≤ levelWords lay := by
+ change 66 ≤ 66 + 6 * slotCapacity lay + 6 * tableWords lay
+ omega
+ omega
+ have step : (10 : Word w).val = 10 := Nat.mod_eq_of_lt (show 10 < 2 ^ w by omega)
+ have interval (x : ℕ) (lo : cut ≤ x) (hi : x < first) : out x = before x :=
+ keep x ((table_range lay cur (0 : Fin 6)).1.trans lo)
+ (hi.trans_le (table_range lay cur (1 : Fin 6)).2)
+ have src := bounds.oldTables d.old fun x lo hi ↦
+ keep x ((Nat.le_add_right ..).trans lo) (hi.trans_le (table_range lay cur (1 : Fin 6)).2)
+ have denseRoom : ShrinkInput.stop X cut < 2 ^ w := by
+ have tr := bounds.termRoom
+ unfold ShrinkInput.termEnd at tr
+ omega
+ have cutBefore := ShrinkInput.range_bounds X cut
+ have low : cut ≤ (dense).val := by
+ change cut ≤ ShrinkInput.stop X cut % 2 ^ w
+ rw [Nat.mod_eq_of_lt denseRoom]
+ exact cutBefore.1.trans (cutBefore.2.1.trans (cutBefore.2.2.1.trans cutBefore.2.2.2))
+ obtain ⟨pairs, terms⟩ := ShrinkTermInputs.capture_transfer B X cut 10 bounds.termRoom le_rfl
+ d.pairs d.terms (fun x lo hi ↦ interval x (low.trans lo) (hi.trans_le bounds.termBefore))
+ constructor
+ · exact src
+ · exact pairs
+ · exact terms
+ · intro maps
+ exact ShrinkResidentRun.transfer X resident side maps (d.residents maps)
+ (bounds.residentEnd.trans_lt fit) (fun x lo hi ↦
+ keep x ((table_range lay cur (5 : Fin 6)).1.trans lo) (hi.trans_le bounds.residentEnd))
+ · exact absolute_transfer bounds d.absolute interval
+ · exact d.slices.transfer_interval (T := sourceInc) ready (step.symm ▸ bounds.termRoom)
+ bounds.fresh bounds.widthAfter bounds.slotAfter
+ ((table_range lay cur (3 : Fin 6)).2.trans_lt fit) step.ge bounds.packedRoom
+ (fun x lo hi ↦ keep x ((table_range lay cur (1 : Fin 6)).1.trans lo)
+ (hi.trans_le (table_range lay cur (3 : Fin 6)).2))
+ · exact d.sorted.transfer_interval fun x lo hi ↦
+ keep x ((table_range lay cur (3 : Fin 6)).1.trans lo) (hi.trans_le bounds.slotEnd)
+ · exact successor_actual bounds d.successor agree
+
+end PairSimulation.ShrinkResidentSources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkResidentTermCapture.lean b/lean/OAI/Computability/VPVNP/PairShrinkResidentTermCapture.lean
new file mode 100644
index 0000000000..9f96f418d3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkResidentTermCapture.lean
@@ -0,0 +1,243 @@
+import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch
+import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables
+import OAI.Computability.VPVNP.CompressorShrinkResidentFinal
+
+/-! # Selected demand pairs and term rows in the final shrinking memory
+
+The paired gather writes one AB and one CD width per motif. The term worker
+writes each admitted term at the same motif ordinal in a second table. The
+selected geometry, resident directories and subsequent slice tables preserve
+both sets of cells for the six local map calls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ShrinkTermInputs
+
+open BurstRAM Compression Compression.ShrinkMotif
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+variable {w a g : ℕ} (X : State a (packingLaneBits a g)) (start stride : ℕ)
+variable {sel : SelectedScore.Selection B X} {before out : Memory w}
+
+private noncomputable local instance captureBaseDecidable : DecidableEq X.Base := Classical.decEq _
+
+local notation "dense" => ShrinkInput.demandHead (w := w) X start
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "stop" => ShrinkInput.termEnd X start stride
+
+/-- Exact exclusive ends of the paired gather and the term worker. -/
+theorem capture_ends (room : stop < 2 ^ w) :
+ (dense).val + 2 * motifCount X = (term).val ∧ (term).val + motifCount X * stride = stop := by
+ let n := ShrinkTermSelection.bundles X * ShrinkTermSelection.ranks a
+ change ShrinkInput.stop X start + 2*n + n*stride < 2 ^ w at room
+ rw [ShrinkTermSelection.motifCount_eq]
+ change ShrinkInput.stop X start % (2 ^ w) + 2*n = (ShrinkInput.stop X start + 2*n) % (2^w) ∧
+ (ShrinkInput.stop X start + 2*n) % (2^w) + n*stride = ShrinkInput.stop X start + 2*n + n*stride
+ rw [Nat.mod_eq_of_lt (by omega : ShrinkInput.stop X start < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega : ShrinkInput.stop X start + 2*n < 2 ^ w)]
+ exact ⟨rfl, rfl⟩
+
+/-- Transfer exactly the two cells per motif lying before the term table. -/
+theorem pairs_transfer (room : stop < 2 ^ w) (pairs : statePairs X dense before)
+ (keep : ∀ x, (dense).val ≤ x → x < (term).val → out x = before x) :
+ statePairs X dense out := by
+ have endPairs := (capture_ends X start stride room).1
+ intro u
+ let j := (ShrinkMotifOrder.stateNumber X u).val
+ have hj : j < motifCount X := ((ShrinkMotifOrder.entries X).symm u).isLt
+ change (out ((dense).val + 2*j)).val = _ ∧ (out ((dense).val + 2*j + 1)).val = _
+ rw [keep _ (by omega) (by omega), keep _ (by omega) (by omega)]
+ exact pairs u
+
+/-- Reading the two demand cells and the ten selected term cells is stable
+under later writes outside the actual dense-through-term interval. -/
+theorem capture_transfer (room : stop < 2 ^ w) (wide : 10 ≤ stride)
+ (pairs : statePairs X dense before)
+ (fields : ∀ u, TermRecordScan.Fields B.shrink ShrinkSliceArrays.supplyRoles demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth u) (sel u).val
+ (ShrinkTermSelection.rowBase X term stride u) before)
+ (keep : ∀ x, (dense).val ≤ x → x < stop → out x = before x) :
+ statePairs X dense out ∧ ∀ u, TermRecordScan.Fields B.shrink
+ ShrinkSliceArrays.supplyRoles demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth u) (sel u).val
+ (ShrinkTermSelection.rowBase X term stride u) out := by
+ obtain ⟨endPairs, endTerms⟩ := capture_ends X start stride room
+ refine ⟨pairs_transfer X start stride room pairs (fun x lo hi ↦ keep x lo (by omega)), ?_⟩
+ intro u
+ let row := ShrinkTermSelection.rowBase X term stride u
+ let j := (ShrinkMotifOrder.stateNumber X u).val
+ have hj : j < motifCount X := ((ShrinkMotifOrder.entries X).symm u).isLt
+ have last := Nat.mul_le_mul_right stride hj
+ rw [Nat.succ_mul] at last
+ have addr : row.val = (term).val + j * stride := Nat.mod_eq_of_lt (by
+ change (term).val + j * stride < 2 ^ w
+ omega)
+ have same (n : ℕ) (hn : n < 10) : out (row.val + n) = before (row.val + n) := by
+ apply keep <;> rw [addr] <;> omega
+ obtain ⟨grid, copies, payload⟩ := fields u
+ change TermRecordScan.Fields _ _ _ _ _ row out
+ refine ⟨?_, ?_, ?_⟩
+ · rw [show out row.val = _ from by simpa only [Nat.add_zero] using same 0 (by decide)]
+ exact grid
+ · rw [same 1 (by decide)]
+ exact copies
+ · intro e
+ have he : 2 + e.val < 10 := by have := e.isLt; omega
+ rw [Nat.add_assoc, same _ he, ← Nat.add_assoc]
+ exact payload e
+
+end CompressorRecords.ShrinkTermInputs
+
+namespace CompressorRecords.ShrinkBranch
+
+open BurstRAM Compression Compression.ShrinkMotif
+
+variable {w a g start cap : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w}
+variable {m : Memory w} (p : Prefix X T start cap m)
+private noncomputable local instance captureBaseDecidable : DecidableEq X.Base := Classical.decEq _
+
+local notation "dense" => ShrinkInput.demandHead (w := w) X start
+local notation "term" => ShrinkInput.termHead (w := w) X start
+
+/-- The reports in this prefix gather the two widths for each actual CD motif. -/
+theorem Prefix.statePairs_beforeTerm (room : ShrinkInput.stop X start < 2 ^ w) :
+ ShrinkTermInputs.statePairs X dense p.beforeTerm := by
+ have stored := (p.input.keepAbsoluteFrame room p.absoluteRun.frame).stored
+ intro u
+ let b := X.packingData.bundle u
+ let x : X.packingData.MotifFiber b := ⟨u, rfl⟩
+ let r := X.shrinkNumber b x
+ let j := BundleLists.portIndex (Shrink.packedIndex X.baseIndex) b
+ have ab := (congrArg Fin.val (p.gatherRun.readAB j.val j.isLt r.val r.isLt)).trans
+ (stored.ab.widths b r)
+ have cd := (congrArg Fin.val (p.gatherRun.readCD j.val j.isLt r.val r.isLt)).trans
+ (stored.cdWidths b r)
+ rw [show (X.shrinkNumber b).symm r = x from (X.shrinkNumber b).symm_apply_apply x] at ab cd
+ change (p.beforeTerm ((dense).val + 2 * (ShrinkMotifOrder.stateNumber X u).val)).val = _ ∧
+ (p.beforeTerm ((dense).val + 2 * (ShrinkMotifOrder.stateNumber X u).val + 1)).val = _
+ rw [ShrinkMotifOrder.number_val]
+ exact ⟨ab, cd⟩
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+variable {stride selectors : Word w} {sel : SelectedScore.Selection B X} {p}
+variable (v : Selected B X T start stride selectors cap m p sel)
+local notation "origin" => SelectedArena.origin X term stride
+
+/-- The selected geometry and a later interval frame retain the two gathered
+widths, the grid index, the repetitions and the eight chosen payload widths. -/
+theorem Selected.term_capture {out : Memory w}
+ (room : ShrinkInput.termEnd X start stride.val < 2 ^ w) (wide : 10 ≤ stride.val)
+ (keep : ∀ x, (dense).val ≤ x → x < origin → out x = v.beforeOutput x) :
+ ShrinkTermInputs.statePairs X dense out ∧ ∀ u, TermRecordScan.Fields B.shrink
+ ShrinkSliceArrays.supplyRoles demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth u) (sel u).val
+ (ShrinkTermSelection.rowBase X term stride.val u) out := by
+ have stopRoom : ShrinkInput.stop X start < 2 ^ w := by
+ unfold ShrinkInput.termEnd at room
+ omega
+ let afterTerm := after p.beforeTerm (eventLog v.terms)
+ have pairs : ShrinkTermInputs.statePairs X dense afterTerm :=
+ ShrinkTermInputs.pairs_transfer X start stride.val room (p.statePairs_beforeTerm stopRoom)
+ (fun x _ hi ↦ v.termRun.frame x (.inl hi))
+ have endTerms : origin = ShrinkInput.termEnd X start stride.val :=
+ (ShrinkTermInputs.capture_ends X start stride.val room).2
+ exact ShrinkTermInputs.capture_transfer B X start stride.val room wide pairs v.termRun.fields
+ (fun x lo hi ↦ (keep x lo (hi.trans_eq endTerms.symm)).trans
+ (v.postTerm.geometry.frame x (.inl (hi.trans_eq endTerms.symm))))
+
+end CompressorRecords.ShrinkBranch
+
+namespace CompressorRecords.ShrinkOutput
+
+open BurstRAM Compression Compression.ShrinkMotif ShrinkBlockInputs ShrinkResidentRun
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {i : Fin S.steps}
+variable {w g start cap : ℕ} {δ : ℝ} {X : State (a i) (packingLaneBits (a i) g)}
+variable {ready : Ready (2 ^ a i) (Shrink.colors (a i)) (2 ^ b i) δ}
+variable {m : Memory w} {T : IncidenceDirectory w} {stride selectors : Word w}
+variable {sel : SelectedScore.Selection B X} {p : ShrinkBranch.Prefix X T start cap m}
+variable (v : ShrinkBranch.Selected B X T start stride selectors cap m p sel)
+private noncomputable local instance captureBaseDecidable : DecidableEq X.Base := Classical.decEq _
+
+local notation "dense" => ShrinkInput.demandHead (w := w) X start
+local notation "term" => ShrinkInput.termHead (w := w) X start
+local notation "absHead" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w
+local notation "origin" => SelectedArena.origin X term stride
+
+variable {I : ShrinkABSliceRecipe.Inputs} {pub : Fin 5 → Word w} {state : Word w} {ref : Memory w}
+variable {first width slotStart : ℕ} {r : TablesRun w}
+
+/-- Capture after the AB and ordered-slot scans. The input interval frame
+also permits intervening publication of the six resident heads. -/
+theorem CompleteTables.term_capture_after {input : Memory w}
+ (tables : CompleteTables B i X ready sel term stride absHead start I pub state ref
+ first width slotStart cap input r)
+ (room : ShrinkInput.termEnd X start stride.val < 2 ^ w) (wide : 10 ≤ stride.val)
+ (resident : ∀ x, (dense).val ≤ x → x < origin → input x = v.beforeOutput x)
+ (abFresh : origin ≤ first) (order : first ≤ width) :
+ ShrinkTermInputs.statePairs X dense r.final ∧ ∀ u, TermRecordScan.Fields B.shrink
+ ShrinkSliceArrays.supplyRoles demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth u) (sel u).val
+ (ShrinkTermSelection.rowBase X term stride.val u) r.final := by
+ apply v.term_capture room wide
+ intro x lo hi
+ have beforeAB := hi.trans_le abFresh
+ have beforeSlots := (beforeAB.trans_le order).trans_le
+ (retained_room X term stride.val (SelectedArena.roleBase X term stride) width)
+ exact (tables.remainder.construction.frame x (.inl beforeSlots)).trans
+ ((tables.abFrame x (.inl beforeAB)).trans (resident x lo hi))
+
+/-- Read the dense demands and selected term in the common final snapshot
+of both resident-directory scans and all three output tables. -/
+theorem CompleteTables.term_capture {resident : ℕ} {role : Word w} {side : Bool}
+ {h u : ShrinkResidentRun.Passes w}
+ (hiddenRun : Built X resident absHead role side false v.beforeOutput h)
+ (mapRun : Built X resident absHead role side true (h.final v.beforeOutput) u)
+ (tables : CompleteTables B i X ready sel term stride absHead start I pub state ref
+ first width slotStart cap (u.final (h.final v.beforeOutput)) r)
+ (room : ShrinkInput.termEnd X start stride.val < 2 ^ w) (wide : 10 ≤ stride.val)
+ (residentFresh : origin ≤ resident) (abFresh : origin ≤ first) (order : first ≤ width) :
+ ShrinkTermInputs.statePairs X dense r.final ∧ ∀ u, TermRecordScan.Fields B.shrink
+ ShrinkSliceArrays.supplyRoles demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth u) (sel u).val
+ (ShrinkTermSelection.rowBase X term stride.val u) r.final := by
+ apply tables.term_capture_after v room wide _ abFresh order
+ intro x _ hi
+ have early := hi.trans_le residentFresh
+ exact (mapRun.frame x (.inl (early.trans_le ((ShrinkResidentLayout.layout X resident).ranges
+ true).1))).trans (hiddenRun.frame x (.inl (early.trans_le
+ ((ShrinkResidentLayout.layout X resident).ranges false).1)))
+
+/-- The six header publishers lie below the demand pairs. After their writes,
+the actual AB and slot passes still expose every map operand from the same branch. -/
+theorem CompleteTables.published_term_capture {resident level : ℕ} {role : Word w} {side : Bool}
+ {h u : ShrinkResidentRun.Passes w}
+ (hiddenRun : Built X resident absHead role side false v.beforeOutput h)
+ (mapRun : Built X resident absHead role side true (h.final v.beforeOutput) u)
+ (tables : CompleteTables B i X ready sel term stride absHead start I pub state ref
+ first width slotStart cap (endMemory X resident level v.beforeOutput h u) r)
+ (room : ShrinkInput.termEnd X start stride.val < 2 ^ w) (wide : 10 ≤ stride.val)
+ (headerBefore : level + 36 ≤ (dense).val) (residentFresh : origin ≤ resident)
+ (abFresh : origin ≤ first) (order : first ≤ width) :
+ ShrinkTermInputs.statePairs X dense r.final ∧ ∀ u, TermRecordScan.Fields B.shrink
+ ShrinkSliceArrays.supplyRoles demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth u) (sel u).val
+ (ShrinkTermSelection.rowBase X term stride.val u) r.final := by
+ apply tables.term_capture_after v room wide _ abFresh order
+ have publish := (ShrinkResidentsPlan.published level (ShrinkResidentLayout.layout X resident)
+ (headerBefore.trans (dense).isLt.le) (u.final (h.final v.beforeOutput))).2
+ intro x lo hi
+ have early := hi.trans_le residentFresh
+ exact (publish x (.inr (headerBefore.trans lo))).trans
+ ((mapRun.frame x (.inl (early.trans_le ((ShrinkResidentLayout.layout X resident).ranges
+ true).1))).trans (hiddenRun.frame x (.inl (early.trans_le
+ ((ShrinkResidentLayout.layout X resident).ranges false).1))))
+
+end CompressorRecords.ShrinkOutput
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleBankChild.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleBankChild.lean
new file mode 100644
index 0000000000..f8f7bdc6e4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleBankChild.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairShrinkRoleChild
+import OAI.Computability.VPVNP.PairNodeChildSegment
+
+/-!
+# The child decoder in the hosted shrinking segment
+
+Before the descriptor header, the hosted program fills its slot-ordinal bank.
+The initializer contributes one tick per ordinal and carries all argument
+buffers, the protected DFS stack and the full remaining tape into the scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.BankChild
+
+open BurstRAM BurstRAM.PrivateRAM DFS Compression CompressorRecords NodeArguments
+open NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {a g w p r k endAddr : ℕ} {X : State a g}
+ {M : Machine w p r k} {m : Memory w} {dfs : Fin 9 ↪ Fin r}
+
+theorem initializer_realizes {pc : Fin (2 ^ a) → Fin p} {bank : Fin (2 ^ a) ↪ Fin r}
+ {done : Fin p} (init : ChildBankInit.Linked M pc bank done)
+ (apart : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → dfs i ∉ Set.range bank)
+ {pre post : Word w → Config w p r → Prop}
+ (start : ∀ node c, pre node c → c.pc = pc 0)
+ (finish : ∀ node c d, pre node c → d.pc = done →
+ (ChildSlots.Names.bank bank).Valid M d → d.persistent = c.persistent →
+ d.privateMem = c.privateMem → (∀ i, i ∉ Set.range bank → d.reg i = c.reg i) → post node d) :
+ Realizes (endAddr := endAddr) (Setup.ticks (2 ^ a)).reader M m dfs pre (fun _ => post) := by
+ apply Setup.realizes
+ intro node c h
+ obtain ⟨d, pc, state, mem, ready, keep, run⟩ := ChildBankInit.native init m c (start node c h)
+ exact ⟨d, finish node c d h pc ready state mem keep,
+ ⟨fun i hi => keep _ (apart i hi), fun i _ => congrFun mem i, state⟩, congrArg _ mem, run⟩
+
+variable (A : Arena) (T : IncidenceDirectory w) (m : Memory w) (older cap : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w X)
+
+/-- Run the fixed child-register setup ticks, then decode the placed old-site arguments from
+the selected child directory and choice tape. -/
+noncomputable def reader : Reader w endAddr (List (Child X)) :=
+ ShrinkRole.bind (Setup.ticks (2 ^ a)).reader fun _ => ChildArguments.reader A T m older cap desc
+
+theorem splitBits : Splits (endAddr := endAddr) (reader A T m older cap desc) :=
+ (Setup.ticks (2 ^ a)).splits.bind fun _ _ _ _ _ _ h =>
+ ChildArguments.splitBits A T m older cap desc h
+
+open ChildCode.RegisterBank (segment initPC bank loc regs)
+
+variable {A T m older cap desc}
+
+/-- Native realization from the first instruction of the installed eleven-operand
+segment. A successful scan stores the decoded packets in order and preserves every
+register outside the segment's local allocation. -/
+theorem realizes {M : Machine w p r 11} {dfs : Fin 9 ↪ Fin r}
+ (pc : Fin (segment a).count → Fin p) (saved : VertexImage.Saved ↪ Fin r)
+ (prv : Fin (segment a).privateRegs ↪ Fin r) (ret : Fin p)
+ (rows : ∀ j, M.code (pc j) = ((segment a).row pc dfs saved prv ret j).resize w)
+ (apart : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → ∀ j, dfs i ≠ prv j)
+ (rep : T.ActualColumns X m) (strideFit : cap + 2 < 2 ^ w)
+ {pre : Word w → Config w p r → Prop} {post : List (Child X) → Word w → Config w p r → Prop}
+ (start : ∀ node c, pre node c →
+ c.pc = pc (segment a).entry ∧ c.reg (regs prv 7) = node ∧
+ c.reg (regs prv 8) = (desc node).directoryBase ∧
+ ChildArguments.Resident A T m older cap endAddr node (desc node))
+ (finish : ∀ node c d xs, pre node c → xs.map Child.site = (desc node).sites → d.pc = ret →
+ d.persistent = c.persistent →
+ d.privateMem = storePackets A (xs.map (Child.packet X older cap)) c.privateMem →
+ (∀ i, i ∉ Set.range prv → d.reg i = c.reg i) → post xs node d) :
+ Realizes (endAddr := endAddr) (reader A T m older cap desc) M m dfs pre post := by
+ obtain ⟨init, code⟩ := ChildCode.RegisterBank.segment_linked M pc dfs saved prv ret rows
+ obtain ⟨hh, hl⟩ := ChildCode.linkedWith M (loc pc) (regs prv) (.bank (bank prv)) ret code
+ let header := ChildCode.headerPC (loc pc)
+ let input := ChildArguments.Entry A T m older cap desc header (regs prv) M
+ (.bank (bank prv)) endAddr
+ let mid (node : Word w) (d : Config w p r) : Prop := input node d ∧
+ ∃ c, pre node c ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ i, i ∉ Set.range (bank prv) → d.reg i = c.reg i
+ have sep (j : Fin 16) : regs prv j ∉ Set.range (bank prv) := fun ⟨i, he⟩ =>
+ ChildCode.RegisterBank.bank_apart prv i j he
+ have boot : Realizes (endAddr := endAddr) (Setup.ticks (2 ^ a)).reader M m dfs pre
+ (fun _ => mid) := by
+ apply initializer_realizes init (fun i hi ⟨j, eqn⟩ => apart i hi _ eqn.symm)
+ (fun node c hc => (start node c hc).1)
+ intro node c d hc hd names state mem keep
+ obtain ⟨_, parent, directory, resident⟩ := start node c hc
+ exact ⟨⟨hd, (keep _ (sep 7)).trans parent, (keep _ (sep 8)).trans directory, names, resident⟩,
+ c, hc, mem, state, keep⟩
+ apply boot.bind
+ intro _
+ apply ChildArguments.realizesWith hh hl (ChildCode.RegisterBank.bank_apart prv) rep strideFit
+ (fun i hi j => apart i hi _) (fun _ _ h => h.1)
+ intro node d z xs h sites done state mem keep
+ obtain ⟨_, c, hc, dm, ds, before⟩ := h
+ refine finish node c z xs hc sites done (state.trans ds) (dm ▸ mem) ?_
+ intro i hi
+ have free (j : Fin 16) : i ≠ regs prv j := fun e => hi ⟨_, e.symm⟩
+ exact (keep _ (fun j _ => free j) (by simp [mutableRegs, free])).trans
+ (before i fun ⟨j, eqn⟩ => hi ⟨_, eqn⟩)
+
+end PairSimulation.ShrinkRole.BankChild
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleBankHistogramStep.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleBankHistogramStep.lean
new file mode 100644
index 0000000000..44be772027
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleBankHistogramStep.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+import OAI.Computability.VPVNP.PairShrinkMapRowJobCount
+
+/-!
+# Histogram increment at one physical resident of a shrinking site
+
+An old assignment, a parent half-wire and the hidden fields determine the row
+independently of its later use in a local kernel witness.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open ShrinkMapImage.Registers ResidentMapLoop.Exact MapResidentRows NodeArguments
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g n w t packetEnd : ℕ}
+ {X : State (a i) (packingLaneBits (a i) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : Site X}
+
+open private acceptanceBase from OAI.Computability.VPVNP.PairShrinkRoleMapActions
+private noncomputable local instance rowBase : DecidableEq X.Base := acceptanceBase i X
+set_option allowUnsafeReducibility true in
+attribute [local reducible] rowBase
+set_option allowUnsafeReducibility true in
+attribute [local reducible] Compression.PackingData.shrinkTermLayout ShrinkVertexImage.gatherFamily
+set_option allowUnsafeReducibility true in
+attribute [local irreducible] Compression.ShrinkEnergy.chosenLayout
+
+local notation "side" => selectedLayout X B.shrink sel
+variable (site : CanonicalSite B i X sel v w n t) (ord : B.Entry ≃ Fin t)
+ (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+ (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+
+local notation "bank" => canonicalBank site ord parent old hidden
+local notation "residents" => order (a := a i) (g := g) X side v
+
+/-- The selected resident's action in the actual physical row order. -/
+noncomputable def canonicalRow (j : Fin (residents).length) : Action w n :=
+ (bank)[j.val]'(by simpa only [canonicalBank, MapWitness.actions, List.length_ofFn] using j.isLt)
+
+/-- Collecting all indexed actions recovers the whole resident bank. -/
+theorem canonicalRows_eq : List.ofFn (canonicalRow site ord old parent hidden) = bank := by
+ apply List.ext_getElem
+ · simp only [List.length_ofFn, canonicalBank, MapWitness.actions]
+ · intro k h₁ h₂
+ rw [List.getElem_ofFn]
+ rfl
+
+
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "jobs" => ShrinkSiteBank.jobs (g := g) (w := w) B i X sel site.workspace
+ site.positions site.blocks site.cur site.bounds n site.rowEnd site.older site.later v old parent
+local notation "row" => MapWitness.rowEquiv (a := a i) (g := g) X side v
+open private jobPublic from OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+local notation:max "pubAt" q:max => jobPublic site old parent q
+set_option quotPrecheck false in
+local notation:max "bin" l:max => (((regions).histBase + (ord l).val : ℕ) : Word w)
+
+set_option allowUnsafeReducibility true in
+attribute [local irreducible] rowAction ShrinkPartyNative.Job.entryInput
+ ShrinkPartyNative.Job.mapWorkspace MapWitness.input
+
+private theorem ordinal_names (I : LocalHistory.EntryInput B.shrink) :
+ MapHandlerOperand.names (ShrinkVertexImage.matrixFamily B ord i) demandMass_pos I =
+ (MapWitness.names B I).map (List.map (ord ∘ Sum.inl)) := rfl
+
+set_option maxHeartbeats 2200000 in
+-- Identify the actual row's dependent job, resident input and fitted workspace.
+/-- One successful resident action adds the multiplicity of its scheduled local names. -/
+theorem canonicalRow_count (j : Fin (residents).length) (baseline : Word w → Word w)
+ (packets : (jobs (row j)).Packets packetEnd baseline)
+ {T : IncidenceDirectory w} {origin : ℕ}
+ (header : (jobs (row j)).OldPublished (ShrinkCallABI.operands (slotDegree S))
+ (jobPublic site old parent (row j)) (rowOrdinalWord (w := w) (a := a i) (g := g) X side v j)
+ site.mem site.level T origin)
+ (node : Word w) {saved out : Scratch w n} {es : List (Event w)}
+ (got : canonicalRow site ord old parent hidden j node saved = some (es, out)) (l : B.Entry) :
+ rawScratch out (bin l) = rawScratch saved (bin l) +
+ ((((MapWitness.names B (MapWitness.input (g := g) B i X sel v old parent hidden
+ (row j))).map (List.map (ord ∘ Sum.inl))).getD []).count (ord l) : Word w) := by
+ let q := row j
+ have labels : t ≤ (regions).histWords := by
+ change t ≤ Fintype.card B.Entry
+ simpa only [Fintype.card_fin] using (Fintype.card_congr ord).ge
+ have floor : n ≤ (regions).histBase := Nat.le_add_right ..
+ have histEnd := ShrinkResidentMemory.histogram_before_hidden regions n t labels
+ unfold canonicalRow canonicalBank MapWitness.actions at got
+ erw [List.getElem_ofFn] at got
+ dsimp only [MapWitness.jobInput, id] at got
+ have count := ShrinkPartyNative.Job.routed_histogram (g := g) (w := w) (n := n)
+ (endAddr := n) (limit := site.limit) (t := t) (packetEnd := packetEnd)
+ («side» := side) (T := T) (origin := origin) (baseline := baseline) (events := es) (out := out)
+ B (⇑ord) i X sel q.1.1 q.1.2 (jobs q) (q.2.symm ▸ hidden) (site.fits q.1.1)
+ site.width (pubAt q) site.mem v site.level site.term site.source j saved packets
+ floor histEnd header got (ord l)
+ erw [ordinal_names, ShrinkSiteBank.input_eq] at count
+ exact count
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleBankHistogramSum.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleBankHistogramSum.lean
new file mode 100644
index 0000000000..b0ec8a3098
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleBankHistogramSum.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.PairShrinkRoleBankHistogramStep
+import OAI.Computability.VPVNP.PairSimulationMapScanAcceptance
+
+/-!
+# Histogram of the physical shrinking bank
+
+The successful scan of a site's resident jobs adds the sum of their label
+multiplicities to each counter in the private histogram.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open ShrinkMapImage.Registers ResidentMapLoop.Exact MapResidentRows NodeArguments
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g n w t packetEnd : ℕ}
+ {X : State (a i) (packingLaneBits (a i) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : Site X}
+
+open private rowBase from OAI.Computability.VPVNP.PairShrinkRoleBankHistogramStep
+attribute [local instance] rowBase
+set_option allowUnsafeReducibility true in
+attribute [local reducible] rowBase
+set_option allowUnsafeReducibility true in
+attribute [local reducible] Compression.PackingData.shrinkTermLayout
+set_option allowUnsafeReducibility true in
+attribute [local irreducible] Compression.ShrinkEnergy.chosenLayout
+
+local notation "side" => selectedLayout X B.shrink sel
+variable (site : CanonicalSite B i X sel v w n t) (ord : B.Entry ≃ Fin t)
+ (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+ (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+
+local notation "bank" => canonicalBank site ord parent old hidden
+local notation "residents" => order (a := a i) (g := g) X side v
+
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "jobs" => ShrinkSiteBank.jobs (g := g) (w := w) B i X sel site.workspace
+ site.positions site.blocks site.cur site.bounds n site.rowEnd site.older site.later v old parent
+local notation "row" => MapWitness.rowEquiv (a := a i) (g := g) X side v
+open private jobPublic from OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+local notation:max "pubAt" q:max => jobPublic site old parent q
+set_option quotPrecheck false in
+local notation:max "bin" l:max => (((regions).histBase + (ord l).val : ℕ) : Word w)
+
+
+attribute [local irreducible] canonicalRow canonicalBank ResidentMapLoop.Exact.scan
+ MapWitness.input MapWitness.names
+
+set_option quotPrecheck false in
+local notation:max "countAt" j:max l:max =>
+ ((((MapWitness.names B (MapWitness.input (g := g) B i X sel v old parent hidden
+ (row j))).map (List.map (ord ∘ Sum.inl))).getD []).count (ord l))
+
+set_option maxHeartbeats 2200000 in
+-- The scan and row count use the same selected old, parent and hidden assignments.
+/-- The complete bank adds the sum of its physical row counts for each parameter ordinal. -/
+theorem canonicalBank_counts (baseline : Word w → Word w)
+ (packets : ∀ q, (jobs q).Packets packetEnd baseline)
+ {T : IncidenceDirectory w} {origin : ℕ}
+ (headers : ∀ j : Fin (residents).length, let q := row j
+ (jobs q).OldPublished (ShrinkCallABI.operands (slotDegree S)) (pubAt q)
+ (rowOrdinalWord (w := w) (a := a i) (g := g) X side v j) site.mem site.level T origin)
+ (node : Word w) {saved out : Scratch w n} {es : List (Event w)}
+ (got : scan node bank saved = some (es, out)) (l : B.Entry) :
+ rawScratch out (bin l) = rawScratch saved (bin l) +
+ ((∑ j : Fin (residents).length, countAt j l : ℕ) : Word w) := by
+ let rows := canonicalRow site ord old parent hidden
+ let delta (j : Fin (residents).length) : ℕ := countAt j l
+ have run : scan node (List.ofFn rows) saved = some (es, out) := by
+ rw [show List.ofFn rows = bank from canonicalRows_eq site ord old parent hidden]
+ exact got
+ have step (j : Fin (residents).length) (s : Scratch w n) (log : List (Event w))
+ (next : Scratch w n) (hit : rows j node s = some (log, next)) :
+ rawScratch next (bin l) = rawScratch s (bin l) + (delta j : Word w) :=
+ canonicalRow_count (g := g) (packetEnd := packetEnd) (T := T) (origin := origin)
+ site ord old parent hidden j baseline (packets (row j)) (headers j) node hit l
+ have total := scan_ofFn_add node rows (fun s => rawScratch s (bin l))
+ (fun j => (delta j : Word w)) step run
+ simpa only [← Nat.cast_sum] using total
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleBind.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleBind.lean
new file mode 100644
index 0000000000..ad80b0ff79
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleBind.lean
@@ -0,0 +1,38 @@
+import OAI.Computability.VPVNP.PairShrinkRoleStages
+
+/-! # Reassociating native parser stages and deterministic setup traces -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+variable {w endAddr : ℕ} {α β γ : Type*}
+
+theorem bind_assoc (a : Reader w endAddr α) (b : α → Reader w endAddr β)
+ (c : β → Reader w endAddr γ) :
+ bind (bind a b) c = bind a (fun v => bind (b v) c) := by
+ funext node saved bits
+ cases ha : a node saved bits with
+ | none => simp [bind, ha]
+ | some pair =>
+ obtain ⟨x, tail⟩ := pair
+ cases hb : b x.value node x.updated tail with
+ | none => simp [bind, ha, hb]
+ | some pair =>
+ obtain ⟨y, rest⟩ := pair
+ cases hc : c y.value node y.updated rest with
+ | none => simp [bind, ha, hb, hc]
+ | some pair =>
+ obtain ⟨z, last⟩ := pair
+ simp [bind, ha, hb, hc, List.append_assoc]
+
+theorem Setup.seq_reader (a b : Setup w endAddr) :
+ (a.seq b).reader = bind a.reader (fun _ => b.reader) := rfl
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCachedSetup.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCachedSetup.lean
new file mode 100644
index 0000000000..2a4421790a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCachedSetup.lean
@@ -0,0 +1,63 @@
+import OAI.Computability.VPVNP.PairShrinkRoleStages
+import OAI.Computability.VPVNP.PairShrinkRoleHandoff
+
+/-!
+# Caching the hidden-field address during a shrinking visit
+
+The installed handoff reads the live geometry, prepares the hidden scanner's
+four inputs, and saves its private base in the locator register used by the
+map. The traversal keeps the pending DFS stack throughout these local steps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {w p r endAddr : ℕ} {M : Machine w p r 11} {m : Memory w}
+ {dfs : Fin 9 ↪ Fin r} {loc : Fin 14 ↪ Fin r} {next : Fin p}
+ {pre post : Word w → Config w p r → Prop}
+
+/-- The cached handoff realizes a fixed tick trace and exposes its live
+outputs and preserved registers to the next reader. -/
+theorem cachedHiddenHandoff_realizes {pc : Fin (VertexLevel.hiddenCount + 1) → Fin p}
+ {inputs : Fin 6 ↪ Fin r} {stackEnd : Fin r}
+ (linked : ∀ i, M.code (pc i.castSucc) =
+ VertexLevel.hiddenHandoff (pc ∘ Fin.castSucc) loc inputs stackEnd
+ (pc (Fin.last VertexLevel.hiddenCount)) i)
+ (cacheRow : M.code (pc (Fin.last VertexLevel.hiddenCount)) = .copy (loc 8) (inputs 1) next)
+ (apart : ∀ i j, inputs i ≠ loc j)
+ (separate : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 →
+ dfs i ≠ loc 8 ∧ ∀ j, dfs i ≠ inputs j)
+ (start : ∀ node c, pre node c → c.pc = pc 0)
+ (resume : ∀ node c d, pre node c →
+ let G := c.privateMem (c.reg stackEnd)
+ let n := c.privateMem (G + 9)
+ d.pc = next → d.reg (inputs 0) = c.reg (loc 7) →
+ d.reg (inputs 1) = VertexLevel.hiddenBaseWord (c.privateMem (G + 8)) n →
+ d.reg (inputs 2) = n * n → d.reg (inputs 5) = c.reg (loc 11) →
+ d.reg (loc 8) = d.reg (inputs 1) →
+ (∀ j, j ≠ loc 8 → j ≠ inputs 0 → j ≠ inputs 1 → j ≠ inputs 2 → j ≠ inputs 5 →
+ d.reg j = c.reg j) →
+ d.privateMem = c.privateMem → d.persistent = c.persistent → post node d) :
+ Realizes (Setup.ticks (endAddr := endAddr) (VertexLevel.hiddenCount + 1)).reader M m dfs
+ pre (fun _ => post) := by
+ apply Setup.realizes
+ intro node c hc
+ obtain ⟨d, run, done, owner, base, stride, level, cached, keep, mem, pers⟩ :=
+ VertexLevel.cachedHiddenHandoff_run linked cacheRow apart c (start node c hc) m
+ refine ⟨d, resume node c d hc done owner base stride level cached keep mem pers,
+ ⟨?_, fun a _ => congrFun mem a, pers⟩, congrArg (DFS.scratch endAddr) mem, run⟩
+ intro i hi
+ obtain ⟨hloc, hinputs⟩ := separate i hi
+ exact keep _ hloc (hinputs 0) (hinputs 1) (hinputs 2) (hinputs 5)
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalData.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalData.lean
new file mode 100644
index 0000000000..84169df6bf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalData.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalSite
+import OAI.Computability.VPVNP.PairShrinkRoleMapStart
+import OAI.Computability.VPVNP.PairShrinkPackedPackets
+import OAI.Computability.VPVNP.PairShrinkRoleChildTyped
+import OAI.Computability.VPVNP.PairShrinkSiteSources
+import OAI.Computability.VPVNP.PairShrinkVertexPlacement
+
+/-!
+# Published inputs for one canonical shrinking visit
+
+The site data consist of its header words, field and map directories,
+position in the selected schedule, and the bounds of its private arrays.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace LocalHistory ShrinkBlockInputs ShrinkSlots
+open VertexImage ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows
+open TraversalRows TraversalRoles TraversalControllerInputs NodeArguments NodeArguments.ChildScan
+open ShrinkHiddenGuess
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g w n p r : ℕ} {Z : State (a i) (packingLaneBits (a i) g)}
+ {sel : SelectedScore.Selection B Z} {v : MapResidentRows.Site Z}
+ (site : CanonicalSite B i Z sel v w n (Fintype.card B.Entry))
+ (M : Machine w p r 11)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+ (j : Fin (executeLevels B f hf T hT X z).length)
+ (id : Fin (executeLevels B f hf T hT X z)[j].outputSites) (base : ℕ)
+
+private noncomputable local instance : DecidableEq Z.Base := Classical.decEq _
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "side" => selectedLayout Z B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink Z sel
+local notation "Y" => Z.shrinkNext B.shrink (S.shrink i) sel
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+local notation "seed" => ShrinkHiddenSlots.rows Z side widths v site.seed
+local notation "nodeAddr" => site.later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal (Y) v
+local notation "rowAddr" => address B.recordLimit (layerBase B.recordLimit base tags (j.val + 1))
+ id.val
+local notation "jobs" => ShrinkSiteBank.jobs B i Z sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v
+set_option quotPrecheck false in
+local notation "readerAt" => (shrinkPassReaders B f hf i rfl Z).termParsers sel
+
+/-- External row contents, nonwrapping address intervals and fixed schedule
+coordinates used by this one installed shrinking visit. -/
+structure CanonicalSiteData : Prop where
+ publicData : site.publicData = M.publicData
+ levels : site.levels = (vs).length
+ passIndex : site.passIndex = j.val
+ level : site.level = levelHead M.publicData site.mem j.val
+ siteAddr : nodeAddr = rowAddr
+ siteOrdinal : (siteIndex Z v).val = id.val
+ shrinking : tagLevel B f hf (vs)[j] = .shrink
+ index : (vs)[j].origin.ordinal = i.val
+ fit : layerBase B.recordLimit base tags ((vs).length + 1) < 2 ^ w
+ incidence : site.incidence.ActualColumns Z site.mem
+ strideFit : B.recordLimit + 2 < 2 ^ w
+ above : n ≤ NativeFrame.frameBase regions
+ frameRoom : NativeFrame.frameBase regions + 12 ≤ 2 ^ w
+ directory : ∀ node : Word w, node.val = nodeAddr →
+ (site.descriptor node).directoryBase = site.level + 14 ∧
+ ChildArguments.Resident (regions).arguments site.incidence site.mem site.older B.recordLimit n
+ node (site.descriptor node)
+ orderAt : ∀ node : Word w, node.val = nodeAddr →
+ (site.descriptor node).sites = List.ofFn fun k => (((readerAt).order.children v).entries k).val
+ abovePointer : ∀ u, n < (regions).arguments.base (childNode Z site.older B.recordLimit u)
+ oldNodes : ∀ u, childNode Z site.older B.recordLimit u < site.rowEnd
+ parentFit : nodeAddr < site.rowEnd
+ earlier : ∀ u, childNode Z site.older B.recordLimit u < nodeAddr
+ wire : Z.maxWireWidth ≤ n
+ hiddenWidth : ∀ motif t, widths motif (!side, t) ≤ n ^ 2
+ hiddenRoom : heap + (ShrinkHistoryRows.hiddenOrder Z).length * n ^ 2 ≤ 2 ^ w
+ selectors : site.hiddenArgs.selectorBits = (B.shrink.selectorBits : Word w)
+ rowStride : site.hiddenArgs.rowStride = hiddenStride i
+ headRoom : site.level.val + 38 < 2 ^ w
+ headers : Header.Published site.hiddenArgs site.level.val site.mem
+ countFit : site.hiddenArgs.countBase + site.hiddenArgs.owner < 2 ^ w
+ count : (site.mem (site.hiddenArgs.countBase + site.hiddenArgs.owner)).val = (seed).length
+ valid : ValidRows site.hiddenArgs site.mem seed
+ baseEq : site.hiddenArgs.scratchBase = heap
+ strideEq : site.hiddenArgs.slotStride = n ^ 2
+ ownerEq : site.hiddenArgs.owner = (siteIndex Z v).val
+ words : MapResidentInputs.Published site.mem site.level
+ ((ShrinkResidentLayout.layout Z site.source.first).params (a i) true w 3)
+ ((ShrinkResidentLayout.layout Z site.source.first).params (a i) true w 5) site.term 10
+ mapRoom : firstMap B i site.source v + (order Z side v).length < 2 ^ w
+ levelEq : site.level = (levelStart
+ (BlockProgram.layout B site.workspace.val site.positions site.blocks) site.cur : Word w)
+
+/-- The actual packet bounds and retained source rows for this parent
+assignment, at the physical vertex's external read boundary. -/
+structure CanonicalMapData (H : Word w) (parent : (Y).network.Half v) : Prop where
+ terminalRoom : H.val + 31 < 2 ^ w
+ sources : ∀ old q, ShrinkSiteBank.RowSources B i Z sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v old parent site.mem H q
+ space : ∀ old q, ShrinkCanonicalJob.PacketSpace B i Z sel q.1.1 q.1.2 (jobs old parent q)
+ n site.limit
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalDataUpdate.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalDataUpdate.lean
new file mode 100644
index 0000000000..f5f7552f32
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalDataUpdate.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalPacketFits
+import OAI.Computability.VPVNP.PairShrinkSiteInitialPackets
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalUpdate
+
+/-!
+# The shrinking row update from its published site and popped parent
+
+The child and hidden assignments of the selected term determine one private
+store shared by all resident jobs. The row directories fit those stores, and
+the retained map rows supply the source headers for the counter increments.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM PrivateRAM DFS Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess LeafSourceLoad
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open scoped Fin.CommRing
+open private termAt readerAt childOrder from OAI.Computability.VPVNP.PairShrinkRoleScheduledSuffix
+
+variable {K : Type} {C : Type*} [_root_.Field K] [CommRing C] {S : BlockSchedule K}
+ {B : S.Templates} {i : Fin S.steps} {g n w p r : ℕ}
+ {Z : State (a i) (packingLaneBits (a i) g)} {sel : SelectedScore.Selection B Z}
+ {v : MapResidentRows.Site Z} {site : CanonicalSite B i Z sel v w n (Fintype.card B.Entry)}
+ {M : Machine w p r 11} {f : B.Entry → C} {hf : B.IsSolution f} {lanes T : ℕ}
+ {hT : T * S.laneBits ≤ lanes} {X : State (S.degreeExponent 0) lanes}
+ {z : (B.execute f hf T hT X).Choices} {j : Fin (executeLevels B f hf T hT X z).length}
+ {id : Fin (executeLevels B f hf T hT X z)[j].outputSites} {base : ℕ}
+
+private noncomputable local instance : DecidableEq Z.Base := Classical.decEq _
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "side" => selectedLayout Z B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink Z sel
+local notation "Y" => Z.shrinkNext B.shrink (S.shrink i) sel
+local notation "nodeAddr" => site.later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal (Y) v
+local notation "rdr" => readerAt B f hf i Z sel
+local notation "ordAt" => childOrder B f hf i Z sel v
+local notation "term" => termAt B f hf i Z sel
+local notation "ptr" => childNode Z site.older B.recordLimit
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+
+variable (info : CanonicalSiteData site M f hf T hT X z j id base)
+ (ord : B.Entry ≃ Fin (Fintype.card B.Entry))
+ (old : Placed (Z.packingData.shrinkPlace (selectedLayout Z B.shrink sel) ∘
+ Z.packingInputIso.site.symm) Z.network.Half v)
+ (parent : (Z.shrinkNext B.shrink (S.shrink i) sel).network.Half v) {H : Word w}
+ (maps : CanonicalMapData site H parent)
+
+local notation "W" => B.shrinkPassWitnesses f hf i rfl Z sel v old parent
+local notation "jobs" => ShrinkSiteBank.jobs B i Z sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v old parent
+local notation "packetsAt" => TreeDecode.children rdr
+ (fun u b => Packet.mk (ptr u) (packed Z u b)) v old
+
+set_option maxHeartbeats 1200000 in
+-- Elaborating the scheduled witness compares its packed site and half assignments.
+/-- A choice of hidden fields and resident map witnesses for these two physical half assignments. -/
+private noncomputable def rowChoice : Type := (W).Choice
+
+local notation "RowChoice" =>
+ rowChoice (B := B) (f := f) (hf := hf) (i := i) (Z := Z) (sel := sel) (v := v) old parent
+
+set_option maxHeartbeats 1200000 in
+-- Construct the scheduled reader's choice tape once at its concrete physical site.
+/-- The choice tape and parameter increments of the selected native vertex job. -/
+private noncomputable def selectedJob (node : Word w) (x : RowChoice) : VertexJob B.Entry :=
+ ⟨node.val, (rdr).nodeBits v old parent x, (W).exponents x⟩
+
+local notation "chosenJob" =>
+ selectedJob (B := B) (f := f) (hf := hf) (i := i) (Z := Z) (sel := sel) (v := v) old parent
+
+include info maps
+
+set_option maxHeartbeats 4000000 in
+-- The native maps reindex the same term choices over their resident placement equalities.
+theorem CanonicalSiteData.update (x : RowChoice) (node : Word w) (saved : Scratch w n)
+ (atRow : node.val = nodeAddr)
+ (stored : (Packet.mk node.val (packed (Y) v parent)).Stored (regions).arguments saved)
+ (data : Fin 10 → Word w) (offset : Word w) (vals : Static 34 → Word w)
+ (frame : TreeDecode.VertexFrameData regions data offset vals saved)
+ (tail : List Bool) (job : VisitPath w n)
+ (hit : (canonicalParent site ord f hf).read node saved
+ ((chosenJob node x).bits ++ tail) = some (job, tail)) :
+ RowUpdate regions ord data offset vals saved job packetsAt (chosenJob node x).increment := by
+ let xs := children (t := term) Z v ordAt old
+ let es := ShrinkHiddenSlots.rows Z side widths v x.1
+ let batch := xs.map (Child.packet Z site.older B.recordLimit)
+ let baseline := storeRows heap (n ^ 2) es (storePackets (regions).arguments batch
+ (rawScratch saved))
+ have rep : scratch n (rawScratch saved) = saved := by
+ funext q
+ simp only [DFS.scratch, rawScratch, dite_eq_left q.prop]
+ have present : (Packet.mk nodeAddr (packed (Y) v parent)).Stored (regions).arguments
+ (scratch n (rawScratch saved)) := by rwa [rep, ← atRow]
+ have initial (q) : (jobs q).Packets n baseline := (ShrinkSiteBank.initialPackets B f hf i Z
+ sel site.workspace site.positions site.blocks site.cur site.bounds n site.rowEnd site.older
+ site.later site.limit v old parent x.1 q (rawScratch saved) xs es rfl rfl (maps.space old q)
+ info.oldNodes info.parentFit info.earlier info.wire present info.hiddenWidth info.hiddenRoom).1
+ have widthsFit := ShrinkHiddenSlots.rows_fit Z heap (n ^ 2) side widths v x.1 info.hiddenWidth
+ info.hiddenRoom
+ have positive : 0 < w := by
+ by_contra! h
+ have hw : w = 0 := by omega
+ have stride := info.strideFit
+ rw [hw, pow_zero] at stride
+ omega
+ obtain ⟨fits, nodes, above, before⟩ := info.childPacketFits node atRow old
+ exact canonicalParent_update site ord f hf old parent x node saved stored positive data offset
+ vals frame (info.orderAt node atRow) info.baseEq before
+ ((Nat.le_add_right ..).trans info.hiddenRoom)
+ (fun e he => info.strideEq ▸ (widthsFit e he).2) fits nodes above baseline initial
+ (canonicalOldPublished site old parent H info.levelEq (maps.sources old)) tail job hit
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalExecution.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalExecution.lean
new file mode 100644
index 0000000000..8c6b3c06b7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalExecution.lean
@@ -0,0 +1,166 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalItems
+import OAI.Computability.VPVNP.PairShrinkRolePhysicalSite
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalData
+
+/-!
+# The canonical shrinking parser in the installed vertex image
+
+A published site supplies the level, child, hidden and resident directories.
+The parent packet supplies its half assignment. The physical stage switch
+and the linked gathers implement the parser on all tapes and all compatible
+incoming configurations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace LocalHistory ShrinkBlockInputs ShrinkSlots
+open VertexImage ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows
+open TraversalRows TraversalRoles TraversalControllerInputs NodeArguments NodeArguments.ChildScan
+open ShrinkHiddenGuess
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g w n p r : ℕ} {Z : State (a i) (packingLaneBits (a i) g)}
+ {sel : SelectedScore.Selection B Z} {v : MapResidentRows.Site Z}
+ (site : CanonicalSite B i Z sel v w n (Fintype.card B.Entry))
+ (ord : B.Entry → Fin (Fintype.card B.Entry))
+ (geometry rootFields leaf refresh : Segment)
+ (A : Placement (vertexParts B ord geometry rootFields leaf refresh) p r)
+ (M : Machine w p r 11)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+ (j : Fin (executeLevels B f hf T hT X z).length)
+ (id : Fin (executeLevels B f hf T hT X z)[j].outputSites) (base : ℕ)
+
+private noncomputable local instance : DecidableEq Z.Base := Classical.decEq _
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "side" => selectedLayout Z B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink Z sel
+local notation "Y" => Z.shrinkNext B.shrink (S.shrink i) sel
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+local notation "seed" => ShrinkHiddenSlots.rows Z side widths v site.seed
+local notation "nodeAddr" => site.later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal (Y) v
+local notation "rowAddr" => address B.recordLimit (layerBase B.recordLimit base tags (j.val + 1))
+ id.val
+local notation "jobs" => ShrinkSiteBank.jobs B i Z sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v
+set_option quotPrecheck false in
+local notation "readerAt" => (shrinkPassReaders B f hf i rfl Z).termParsers sel
+
+variable {first pitch offset publicH : ℕ} {raw : Memory w}
+ (ds : (k : Fin (executeLevels B f hf T hT X z).length) →
+ LevelDirectory (executeLevels B f hf T hT X z)[k] raw base)
+ (resident : Resident M.publicData site.mem publicH first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers (executeLevels B f hf T hT X z) ds))
+
+local notation "prv" => A.localRegs VertexImage.Part.shrink
+
+private theorem source_cursor {left right : Word w} (eqn : left = right)
+ (src : MapRowSource Z sel side site.mem left site.term) :
+ firstMap B i (eqn ▸ src : MapRowSource Z sel side site.mem right site.term) v =
+ firstMap B i src v := by cases eqn; rfl
+
+private theorem source_published {left right : Word w} (eqn : left = right)
+ (src : MapRowSource Z sel side site.mem left site.term)
+ (published : MapResidentInputs.Published site.mem left
+ ((ShrinkResidentLayout.layout Z src.first).params (a i) true w 3)
+ ((ShrinkResidentLayout.layout Z src.first).params (a i) true w 5) site.term 10) :
+ let aligned : MapRowSource Z sel side site.mem right site.term := eqn ▸ src
+ MapResidentInputs.Published site.mem right
+ ((ShrinkResidentLayout.layout Z aligned.first).params (a i) true w 3)
+ ((ShrinkResidentLayout.layout Z aligned.first).params (a i) true w 5) site.term 10 := by
+ cases eqn
+ exact published
+
+set_option maxHeartbeats 4000000 in
+-- The fixed term, site directory and register banks are shared by all physical subprograms.
+include resident in
+/-- All child and hidden guesses, resident map reads, histogram stores and rejections
+are those of the canonical family on the actual vertex host. -/
+theorem canonicalFamily_exactOn (installed : Contains A M)
+ (data : CanonicalSiteData site M f hf T hT X z j id base)
+ (H : Word w) (parent : (Y).network.Half v) (mapData : CanonicalMapData site H parent)
+ (ready : DFS.Scratch w n → Prop)
+ (frame : ∀ priv, ready (DFS.scratch n priv) → ShrinkCallFrameLive.Stored regions n priv)
+ (stored : ∀ s, ready s →
+ (Packet.mk nodeAddr (packed (Y) v parent)).Stored (regions).arguments s) :
+ (canonicalFamily site ord f hf parent).ExactOn (fun node s => node.val = rowAddr ∧ ready s)
+ M (A.entry .shrink) (A.dfsPC 3) A.dfs site.mem := by
+ let rows := vertex_rows B ord geometry rootFields leaf refresh A M installed
+ have dreg (k l) : prv k ≠ A.dfs l := fun h =>
+ vertex_dfs_apart B ord geometry rootFields leaf refresh A l ⟨k,h⟩
+ have sreg (k l) : prv k ≠ A.saved l := fun h =>
+ vertex_saved_apart B ord geometry rootFields leaf refresh A l ⟨k,h⟩
+ let invariant := canonicalInv (p := p) site ord A.dfs prv ready
+ have exactRows xs es := canonicalInv_items site ord f hf parent A.dfs prv ready xs es M
+ (A.stage .shrink) A.saved (A.dfsPC 3) rows dreg sreg H mapData.terminalRoom data.levelEq
+ mapData.sources mapData.space data.oldNodes data.parentFit data.earlier data.wire
+ data.hiddenWidth data.hiddenRoom data.baseEq data.strideEq stored data.orderAt
+ let source : MapRowSource Z sel side site.mem (levelHead M.publicData site.mem j.val)
+ site.term := data.level ▸ site.source
+ have cursor : firstMap B i source v = firstMap B i site.source v :=
+ source_cursor site data.level site.source
+ have physical := physicalSite_exactOn B ord M (A.stage .shrink) A.dfs A.saved prv (A.dfsPC 3)
+ rows (fun l _ k => (dreg k l).symm) f hf T hT X z ds resident j id data.shrinking i
+ data.index data.fit Z regions site.incidence site.older site.descriptor data.incidence
+ data.strideFit site.hiddenArgs seed sel side v site.term source ready
+ (canonicalActions site ord f hf parent) invariant frame data.above data.frameRoom
+ (fun node atRow => by
+ obtain ⟨dir, row⟩ := data.directory node (atRow.trans data.siteAddr.symm)
+ exact ⟨dir.trans (congrArg (· + 14) data.level), row⟩)
+ (fun _ _ u _ => ⟨data.oldNodes u, data.abovePointer u⟩) data.selectors data.rowStride
+ (data.level ▸ data.headRoom) (data.level ▸ data.headers) data.countFit data.count data.valid
+ data.baseEq (data.strideEq.trans (pow_two n)) (data.ownerEq.trans data.siteOrdinal)
+ data.siteOrdinal (source_published site data.level site.source data.words)
+ (canonicalActions_length site ord f hf parent) (fun node priv xs es c atRow good sites valid
+ parsed operands => by
+ apply canonicalInv_start (site := site) (ord := ord) (dfs := A.dfs) (reg := prv)
+ (ready := ready) (xs := xs) (es := es) (p := p)
+ (o := ⟨node, priv, c, atRow.trans data.siteAddr.symm, good, sites, valid, parsed,
+ data.level.symm ▸ operands⟩))
+ (fun xs es node => canonicalInv_stable site ord A.dfs prv ready xs es (A.stage .shrink)
+ (A.dfsPC 3) node)
+ (fun xs es => cursor ▸ exactRows xs es) (cursor ▸ data.mapRoom)
+ have entryEq : A.entry .shrink = A.stage .shrink (shrinkSegment B ord).entry := rfl
+ have degreeEq : a i = oldExponent i := rfl
+ simpa only [canonicalFamily, data.publicData, data.levels, data.passIndex, data.level, entryEq,
+ degreeEq] using physical
+
+set_option maxHeartbeats 2500000 in
+-- Specialization of the stored parent reader uses the selected output network.
+include resident in
+/-- One native parser covers all independently supplied parent halves at this physical site. -/
+theorem canonicalParent_exactOn (installed : Contains A M)
+ (data : CanonicalSiteData site M f hf T hT X z j id base) (H : Word w) (positive : 0 < w)
+ (maps : ∀ parent, CanonicalMapData site H parent)
+ (ready : (Y).network.Half v → DFS.Scratch w n → Prop)
+ (frame : ∀ parent priv, ready parent (DFS.scratch n priv) →
+ ShrinkCallFrameLive.Stored regions n priv)
+ (stored : ∀ parent s, ready parent s →
+ (Packet.mk nodeAddr (packed (Y) v parent)).Stored (regions).arguments s) :
+ (canonicalParent site ord f hf).ExactOn
+ (fun node s => node.val = rowAddr ∧ ∃ parent, ready parent s)
+ M (A.entry .shrink) (A.dfsPC 3) A.dfs site.mem := by
+ apply parentParser_exactOn (Y) v (regions).arguments (canonicalFamily site ord f hf) M
+ (A.entry .shrink) (A.dfsPC 3) A.dfs site.mem positive rowAddr ready
+ (fun parent s good => data.siteAddr ▸ stored parent s good)
+ intro parent
+ exact canonicalFamily_exactOn site ord geometry rootFields leaf refresh A M f hf T hT X z
+ j id base ds resident installed data H parent (maps parent) (ready parent) (frame parent)
+ (stored parent)
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalExterior.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalExterior.lean
new file mode 100644
index 0000000000..cee5ba71c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalExterior.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.PairShrinkMapExterior
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+import OAI.Computability.VPVNP.PairShrinkSiteSources
+
+/-!
+# Exterior scratch at a selected shrinking site
+
+The site's resident jobs share a histogram and hidden storage base. Every
+successful scan therefore preserves each cell below the hidden storage and
+outside the histogram, for any old, parent and hidden assignments.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open ShrinkMapImage.Registers ResidentMapLoop.Exact MapResidentRows NodeArguments
+open scoped Fin.CommRing
+open private jobPublic from OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g n w t packetEnd : ℕ}
+ {X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : MapResidentRows.Site X}
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "side" => selectedLayout X B.shrink sel
+variable (site : CanonicalSite B i X sel v w n t) (ord : B.Entry ≃ Fin t)
+ (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+ (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "jobs" => ShrinkSiteBank.jobs B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v old parent
+set_option quotPrecheck false in
+local notation:max "pubAt" q:max => ShrinkSiteBank.pub site.level (((jobs q).node : ℕ) : Word w)
+ regions n
+local notation "row" => MapWitness.rowEquiv (a := S.degreeExponent i.castSucc) (g := g) X side v
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+
+attribute [local irreducible] MapWitness.actions ShrinkPartyNative.Job.entryInput
+
+set_option maxHeartbeats 2200000 in
+-- Identify the fitted workspaces and published operands with those in the site's ordered bank.
+/-- The selected resident bank preserves every exterior cell below the hidden fields. -/
+theorem canonicalBank_exterior (baseline : Word w → Word w)
+ (packets : ∀ q, (jobs q).Packets packetEnd baseline)
+ {T : IncidenceDirectory w} {origin : ℕ}
+ (headers : ∀ j : Fin (order X side v).length, let q := row j
+ (jobs q).OldPublished (ShrinkCallABI.operands (slotDegree S)) (pubAt q)
+ (rowOrdinalWord (a := S.degreeExponent i.castSucc) (g := g) (w := w) X side v j)
+ site.mem site.level T origin)
+ (node : Word w) {initial final : Scratch w n} {es : List (Event w)}
+ (run : scan node (canonicalBank site ord parent old hidden) initial = some (es, final))
+ (address : Word w) (low : address.val < heap)
+ (exterior : address.val < (regions).histBase ∨ (regions).histBase + t ≤ address.val) :
+ rawScratch final address = rawScratch initial address := by
+ have labels : t ≤ (regions).histWords := by
+ change t ≤ Fintype.card B.Entry
+ simpa only [Fintype.card_fin] using (Fintype.card_congr ord).ge
+ exact MapWitness.scan_exterior (g := g) (w := w) (n := n) (t := t) (limit := site.limit)
+ (packetEnd := packetEnd) (T := T) (origin := origin) (events := es) (out := final)
+ B ord i X sel v hidden jobs site.mem site.level site.term
+ site.source site.width (fun q ↦ pubAt q) (fun q ↦ site.fits q.1.1) regions node initial
+ labels (fun _ ↦ rfl) (fun _ ↦ rfl) baseline packets headers (by
+ simpa only [canonicalBank, MapWitness.fittedActions, MapWitness.mapWorkspaces, jobPublic, id]
+ using run) address low exterior
+
+local notation "layout" => BlockProgram.layout B site.workspace.val site.positions site.blocks
+local notation "head" => DescriptorSpace.levelStart layout site.cur
+
+set_option maxHeartbeats 2200000 in
+-- Transport the popped node and chronological level into each row's physical source certificate.
+/-- Physical source certificates at the producing level supply the old headers for the scan. -/
+theorem canonicalBank_exterior_of_sources (baseline : Word w → Word w)
+ (packets : ∀ q, (jobs q).Packets packetEnd baseline) (H : Word w)
+ (here : site.level = (head : Word w))
+ (sources : ∀ q, ShrinkSiteBank.RowSources B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v old parent site.mem H q)
+ (node : Word w) {initial final : Scratch w n} {es : List (Event w)}
+ (run : scan node (canonicalBank site ord parent old hidden) initial = some (es, final))
+ (address : Word w) (low : address.val < heap)
+ (exterior : address.val < (regions).histBase ∨ (regions).histBase + t ≤ address.val) :
+ rawScratch final address = rawScratch initial address := by
+ apply canonicalBank_exterior (T := DescriptorSpace.packedIncidence layout w site.cur
+ (DemandRAM.oldCount X)) (origin := DescriptorSpace.tableBase layout site.cur (0 : Fin 6))
+ site ord old parent hidden baseline packets _ node run address low exterior
+ intro j
+ dsimp only
+ rw [here, ShrinkSiteBank.node_eq]
+ exact (sources (row j)).old
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalInvariant.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalInvariant.lean
new file mode 100644
index 0000000000..b7073c7dd6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalInvariant.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.PairShrinkRoleSiteOrigins
+import OAI.Computability.VPVNP.PairShrinkSiteActions
+
+/-!
+# The scratch invariant of the canonical shrinking map loop
+
+The ordered fields and parent packet determine the action list. The incoming
+configuration supplies an origin retained through every successful occurrence.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots LocalHistory
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows
+open NodeArguments NodeArguments.ChildScan
+open ShrinkHiddenGuess ResidentMapLoop.Exact
+open scoped Fin.CommRing
+
+variable {K : Type} {R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+ {B : S.Templates}
+ {i : Fin S.steps} {g w n p r : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+ {sel : SelectedScore.Selection B X} {v : MapResidentRows.Site X}
+ (site : CanonicalSite B i X sel v w n (Fintype.card B.Entry))
+ (ord : B.Entry → Fin (Fintype.card B.Entry)) (f : B.Entry → R) (hf : B.IsSolution f)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+ (dfs : Fin 9 ↪ Fin r) (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r)
+ (ready : DFS.Scratch w n → Prop)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "addr" => site.later + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal
+ (Y) v
+local notation "rowsAt" => ShrinkHiddenSlots.rows X side widths v
+local notation "common" => shared B ord i reg
+set_option quotPrecheck false in
+local notation "readerAt" => (shrinkPassReaders B f hf i rfl X).termParsers sel
+set_option quotPrecheck false in
+local notation "termAt" => (B.shrinkPassAt f hf i rfl X).step.term sel
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+local notation "jobs" => ShrinkSiteBank.jobs B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v
+
+variable (xs : List (Child X)) (es : List ShrinkHiddenGuess.Row)
+
+private noncomputable abbrev rowOrigin := SiteOrigin (p := p) dfs common regions site.level
+ site.term addr site.older B.recordLimit site.descriptor site.hiddenArgs (rowsAt site.seed)
+ site.mem ready xs es
+
+local notation "Origin" => rowOrigin (p := p) site ord dfs reg ready xs es
+
+/-- Every configuration at a map cursor retains a genuine origin with the same
+ABI and the exact operand cells needed by each subsequent occurrence. -/
+noncomputable def canonicalInv (node : Word w) (c : Config w p r) : Prop :=
+ ∃ o : Origin, o.node = node ∧ ShrinkSiteBank.siteInvariant site common o.entry node c
+
+theorem canonicalInv_start (o : Origin) :
+ canonicalInv site ord dfs reg ready xs es o.node o.entry :=
+ ⟨o, rfl, ShrinkSiteBank.siteInvariant_start site common o.entry o.node⟩
+
+theorem canonicalInv_stable (pc : Fin (shrinkSegment B ord).count → Fin p) (done : Fin p)
+ (node : Word w) :
+ (mapLoop B ord i pc reg done).Stable (canonicalInv site ord dfs reg ready xs es node) := by
+ exact OriginInvariant.stable (fun (o : Origin) u =>
+ ShrinkSiteBank.siteInvariant_stable site ord o.entry pc reg done u) node
+
+theorem canonicalActions_length :
+ (canonicalActions site ord f hf parent xs es).length = (order X side v).length :=
+ List.length_ofFn
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalItems.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalItems.lean
new file mode 100644
index 0000000000..9df4e36f3b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalItems.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalInvariant
+import OAI.Computability.VPVNP.PairShrinkLiveMapItems
+import OAI.Computability.VPVNP.PairShrinkRoleOriginPackets
+
+/-!
+# Exact map items for arbitrary parsed lists at a physical shrinking site
+
+The initial memory consists of the original caller's scratch, the decoded child
+packets and the absorbed fields. At each resident occurrence these stores supply
+the independent old halves, the popped parent and the shared hidden inputs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots LocalHistory
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows
+open NodeArguments NodeArguments.ChildScan
+open ShrinkHiddenGuess ResidentMapLoop.Exact
+open scoped Fin.CommRing
+
+variable {K : Type} {R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+ {B : S.Templates}
+ {i : Fin S.steps} {g w n p r : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+ {sel : SelectedScore.Selection B X} {v : MapResidentRows.Site X}
+ (site : CanonicalSite B i X sel v w n (Fintype.card B.Entry))
+ (ord : B.Entry → Fin (Fintype.card B.Entry)) (f : B.Entry → R) (hf : B.IsSolution f)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+ (dfs : Fin 9 ↪ Fin r) (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r)
+ (ready : DFS.Scratch w n → Prop)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "addr" => site.later + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal
+ (Y) v
+local notation "rowsAt" => ShrinkHiddenSlots.rows X side widths v
+local notation "common" => shared B ord i reg
+set_option quotPrecheck false in
+local notation "readerAt" => (shrinkPassReaders B f hf i rfl X).termParsers sel
+set_option quotPrecheck false in
+local notation "termAt" => (B.shrinkPassAt f hf i rfl X).step.term sel
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+local notation "jobs" => ShrinkSiteBank.jobs B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v
+
+variable (xs : List (Child X)) (es : List ShrinkHiddenGuess.Row)
+
+open private rowOrigin from OAI.Computability.VPVNP.PairShrinkRoleCanonicalInvariant
+local notation "Origin" => rowOrigin (p := p) site ord dfs reg ready xs es
+
+variable (M : Machine w p r 11) (pc : Fin (shrinkSegment B ord).count → Fin p)
+ (saved : VertexImage.Saved ↪ Fin r) (done : Fin p)
+
+set_option maxHeartbeats 3500000 in
+-- The native gather, witness, and packet placement use dependent old and output coordinates.
+theorem canonicalInv_items
+ (installed : ∀ j, M.code (pc j) = ((shrinkSegment B ord).row pc dfs saved reg done j).resize w)
+ (ds : ∀ j k, reg j ≠ dfs k) (ss : ∀ j k, reg j ≠ saved k)
+ (H : Word w) (terminalRoom : H.val + 31 < 2 ^ w)
+ (levelEq : site.level = (levelStart
+ (BlockProgram.layout B site.workspace.val site.positions site.blocks) site.cur : Word w))
+ (sources : ∀ old q, ShrinkSiteBank.RowSources B i X sel site.workspace site.positions
+ site.blocks site.cur site.bounds n site.rowEnd site.older site.later v old parent
+ site.mem H q)
+ (space : ∀ old q, ShrinkCanonicalJob.PacketSpace B i X sel q.1.1 q.1.2 (jobs old parent q)
+ n site.limit)
+ (oldNodes : ∀ u, childNode X site.older B.recordLimit u < site.rowEnd)
+ (parentFit : addr < site.rowEnd) (earlier : ∀ u, childNode X site.older B.recordLimit u < addr)
+ (wire : X.maxWireWidth ≤ n) (size : ∀ m t, widths m (!side, t) ≤ n ^ 2)
+ (room : heap + (ShrinkHistoryRows.hiddenOrder X).length * n ^ 2 ≤ 2 ^ w)
+ (baseEq : site.hiddenArgs.scratchBase = heap) (strideEq : site.hiddenArgs.slotStride = n ^ 2)
+ (stored : ∀ s, ready s → (Packet.mk addr (packed (Y) v parent)).Stored (regions).arguments s)
+ (orderAt : ∀ node : Word w, node.val = addr →
+ (site.descriptor node).sites =
+ List.ofFn fun j => (((readerAt).order.children v).entries j).val) :
+ Items (mapLoop B ord i pc reg done) M site.mem dfs (canonicalInv site ord dfs reg ready xs es)
+ (firstMap B i site.source v) (canonicalActions site ord f hf parent xs es) := by
+ let old := oldFields (term := termAt) X v ((readerAt).order.children v) xs
+ let hidden := hiddenFields X side widths v site.seed es
+ unfold canonicalActions typedActions canonicalInv
+ change Items _ _ _ _
+ (OriginInvariant (fun (o : Origin) node => o.node = node)
+ (fun o => ShrinkSiteBank.siteInvariant site common o.entry)) _
+ (canonicalBank site ord parent old hidden)
+ apply Items.existsInvariant (ShrinkSiteBank.actions_quiet site ord parent old hidden)
+ intro o
+ have word : o.node = ((addr : ℕ) : Word w) :=
+ (Fin.cast_val_eq_self o.node).symm.trans (congrArg (fun k : ℕ => (k : Word w)) o.atRow)
+ apply ShrinkSiteBank.exact_items (p := p) (r := r) (n := n) (w := w) (g := g)
+ (X := X) (B := B) (i := i) (sel := sel) (v := v) site ord parent old hidden M pc dfs
+ saved reg done
+ installed ds ss H terminalRoom levelEq (sources old) o.entry _ (word ▸ o.operands)
+ exact origin_packets (p := p) (r := r) (n := n) (w := w) (g := g)
+ site ord f hf parent dfs reg ready xs es o space oldNodes parentFit
+ earlier wire size room baseEq strideEq stored orderAt
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalLevelChecks.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalLevelChecks.lean
new file mode 100644
index 0000000000..be82e0bb30
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalLevelChecks.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.PairShrinkRoleIndexedUpdate
+import OAI.Computability.VPVNP.PairShrinkRoleIndexedSuffix
+import OAI.Computability.VPVNP.PairShrinkRoleLevelChecks
+import OAI.Computability.VPVNP.PairShrinkSiteOrdinal
+
+/-!
+# Checking the selected physical shrinking level
+
+The published row selects the stage, state and layout. Its stored parent
+determines the map calls at every site. The canonical parser's private writes
+and remaining tape therefore apply to the original selected term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM PrivateRAM DFS CompressorRecords Compression LocalHistory NetworkKernel
+open TreeDecode NodeArguments TraversalRows TraversalRoles VertexImage LeafSourceLoad
+open ShrinkRoleDirectory
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {w n : ℕ} {k : Type} {K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f) {lanes : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) (base : ℕ)
+ (i : Fin (executeLevels B f hf T hT X z).length)
+ (shrink : tagLevel B f hf ((executeLevels B f hf T hT X z).get i) = .shrink)
+
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "leaf" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "cap" => B.recordLimit
+local notation "pos" => layerBase cap base tags
+local notation "rows" => selectedLayers B f hf T hT X z
+local notation "v₀" => (vs).get i
+local notation "term" => (v₀).pass.step.term (v₀).term
+local notation "rdr" => originReader B f hf (v₀).origin (v₀).term
+local notation "ptr" => sitePointers cap ((pos) (i.val + 1)) (outputOrder v₀)
+local notation "row" u => (⟨⟨i,u⟩,shrink⟩ : ShrinkSite vs)
+
+variable {geo rootFields leafSeg shrinkSeg refreshSeg : Segment} {p regs : ℕ}
+ (A : Placement (segments geo rootFields leafSeg shrinkSeg refreshSeg) p regs)
+ (M : Machine w p regs 11) (m : Memory w) (offset : ℕ) (data : Fin 10 → Word w)
+ (vals : Static 34 → Word w) (order : B.Entry ≃ Fin (Fintype.card B.Entry))
+ (nodeCap limit power scan : ℕ)
+ (bank : (x : ShrinkSite (executeLevels B f hf T hT X z)) →
+ CanonicalSite B x.occurrence.i x.occurrence.state x.occurrence.selection
+ x.occurrence.site w n (Fintype.card B.Entry))
+ (handlers : NodeDispatch.Role → HookParser w n)
+
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n
+ (base + words cap rows) (Fintype.card B.Entry)
+local notation "hist" => privateHistogram order.symm (regions).histBase
+local notation "stable" => VertexFrameData regions data (offset : Word w) vals
+local notation "valid" => Budgeted (regions).arguments (SelectedPacketFormat B f hf T hT X z base)
+ stable (selectedDesc B f hf T hT X z base) hist nodeCap limit
+local notation "domain" => RoleDomains.Domain X cap base vs regions data (offset : Word w)
+ vals hist nodeCap limit .shrink
+local notation "H" => TerminalLink.header M.publicData
+local notation "reader" x => canonicalParent (bank x) order f hf
+
+attribute [local irreducible] executeLevels originReader selectedDesc shrinkPassReaders
+ canonicalParent
+
+include shrink
+set_option maxHeartbeats 3000000 in
+-- Compare the selected origin's dependent old and new halves with the physical kernel.
+theorem canonicalLevelChecks
+ (installed : handlers .shrink = ShrinkRoleDirectory.parser cap base leaf vs (fun x => reader x))
+ (link : Contains A M) (published : TraversalRoles.Reads w m offset cap base tags)
+ (codes : 2 < 2 ^ w) (tagEnd : offset + base + tagWords cap tags ≤ (H).val)
+ (headerFit : (H).val + 31 < 2 ^ w)
+ (start : n ≤ (regions).arguments.start)
+ (stride : frameStride (slotDegree S) n ≤ (regions).arguments.stride)
+ (histFit : (regions).histBase ≤ 2 ^ w) (nodes : base + words cap rows ≤ (regions).nodes)
+ (width : B.growthConstant ^ T * (X.maxWireWidth + 1) ≤ n) (limitFit : limit < 2 ^ w)
+ (run : (handlers .shrink).ExactOn domain M (A.entry (rolePart .shrink)) (A.dfsPC 3) A.dfs m)
+ (endRow : ∀ x, (bank x).rowEnd = base + words cap rows)
+ (oldBase : ∀ x, (bank x).older = (pos) x.val.1.val)
+ (info : ∀ x, CanonicalSiteData (bank x) M f hf T hT X z x.val.1
+ (RoleDomains.siteId B f hf T hT X z x) base)
+ (maps : ∀ x parent, CanonicalMapData (bank x) H parent)
+ (small : ∀ (u : (term).output.Site) (b : (term).output.Half u)
+ (a : Placed (term).place (v₀).input.network.Half u) (k : ((rdr).witness u a b).Choice) l,
+ ((rdr).witness u a b).exponents k l ≤ nodeCap)
+ (trace : ∀ x s bits tail job, (reader x).read
+ (ShrinkRoleDirectory.address cap base leaf vs x.val : Word w) s bits = some (job, tail) →
+ after m job.trace = m ∧ SourceTransport.Reads (TerminalLink.workerCell H) job.trace ∧
+ countProbes job.trace + 1 ≤ scan * (n.log2 + 1) ^ power ∧ job.trace.length + 9 ≤ n ^ 43) :
+ LevelChecks B f hf (dispatcher handlers m (offset : Word w)) valid hist
+ (JobGuard A M m (TerminalLink.workerCell H) (ordinalJobCost n power scan))
+ cap ((pos) i.val) v₀ := by
+ let family := fun x => reader x
+ have positive : 0 < w := by
+ cases w with
+ | zero => exact False.elim ((by decide : ¬2 < 2 ^ 0) codes)
+ | succ w => exact Nat.zero_lt_succ w
+ have val (u : (term).output.Site) : ((ptr u).1 : Word w).val = (ptr u).1 := by
+ apply Nat.mod_eq_of_lt
+ let x : ShrinkSite vs := row u
+ have bound := OutputRowDirectory.rowAddress_lt_end cap base leaf (outputTags vs)
+ (siteRows vs x.val)
+ have len : (outputTags vs).length = (vs).length := List.length_map _
+ rw [len] at bound
+ exact bound.trans (info x).fit
+ have physical (u : (term).output.Site) :
+ let x : ShrinkSite vs := row u
+ ((ptr u).1 : Word w).val = (bank x).later + (cap + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal x.occurrence.nextState x.occurrence.site := by
+ intro x
+ exact (val u).trans (info x).siteAddr.symm
+ apply levelChecks B f hf T hT X z base i shrink A M m regions offset data vals order
+ nodeCap limit power scan family handlers installed link published codes tagEnd headerFit
+ start stride histFit nodes width limitFit run
+ · intro u b pending s bits budget
+ let x : ShrinkSite vs := row u
+ refine indexedSiteSuffix v₀ u shrink (bank x) order _ s b ?_ positive
+ ((info x).orderAt _ (physical u)) bits
+ rw [endRow x, val u]
+ exact budget.frontier.head.2.2.2
+ · intro u b a k pending s tail job budget got
+ let x : ShrinkSite vs := row u
+ refine indexedSiteUpdate v₀ u shrink (bank x) (info x) order b a k (maps x _)
+ ((pos) i.val) (base + words cap rows) (oldBase x) (endRow x) _ s (physical u) ?_
+ data (offset : Word w) vals budget.frontier.frame tail job got
+ rw [val u]
+ exact budget.frontier.head.2.2.2
+ · exact small
+ · intro u b a k pending s job _ got
+ exact trace (row u) s _ [] job got
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalPacketFits.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalPacketFits.lean
new file mode 100644
index 0000000000..7171c5492c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalPacketFits.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalData
+import OAI.Computability.VPVNP.PairTreeDecoder
+
+/-! # Private argument bounds for the children of a canonical shrinking row -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords ShrinkBlockInputs LocalHistory
+open NetworkKernel
+open NodeArguments NodeArguments.ChildScan
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g w n p r : ℕ} {Z : State (a i) (packingLaneBits (a i) g)}
+ {sel : SelectedScore.Selection B Z} {v : MapResidentRows.Site Z}
+ {site : CanonicalSite B i Z sel v w n (Fintype.card B.Entry)} {M : Machine w p r 11}
+ {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f}
+ {lanes T : ℕ} {hT : T * S.laneBits ≤ lanes} {X : State (S.degreeExponent 0) lanes}
+ {z : (B.execute f hf T hT X).Choices} {j : Fin (executeLevels B f hf T hT X z).length}
+ {id : Fin (executeLevels B f hf T hT X z)[j].outputSites} {base : ℕ}
+
+local notation "Y" => Z.shrinkNext B.shrink (S.shrink i) sel
+local notation "addr" => site.later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal (Y) v
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "ptr" => childNode Z site.older B.recordLimit
+set_option quotPrecheck false in
+local notation "rdr" => (shrinkPassReaders B f hf i rfl Z).termParsers sel
+
+/-- The tree reader enumerates the descriptor's children in their physical order. Each of
+their half-wire packets fits the reserved argument slot above the geometry pointer. The
+histogram starts strictly beyond that pointer even for an empty child list. -/
+theorem CanonicalSiteData.childPacketFits (data : CanonicalSiteData site M f hf T hT X z j id base)
+ (node : Word w) (atRow : node.val = addr)
+ (old : Placed ((B.shrinkPassAt f hf i rfl Z).step.term sel).place Z.network.Half v) :
+ let packets := TreeDecode.children rdr (fun u b => Packet.mk (ptr u) (packed Z u b)) v old
+ (∀ q ∈ packets, q.Fits (regions).arguments w n) ∧
+ (∀ q ∈ packets, q.node < (regions).nodes) ∧
+ (∀ q ∈ packets, n < (regions).arguments.base q.node) ∧ n < (regions).histBase := by
+ let order := (rdr).order.children v
+ have row := (data.directory node atRow).2
+ have packetBounds (k : Fin order.length) :
+ let u := order.entries k
+ let q := Packet.mk (ptr u.val) (packed Z u.val (old u.val u.prop))
+ q.Fits (regions).arguments w n ∧
+ q.node < (regions).nodes ∧ n < (regions).arguments.base q.node := by
+ let u := order.entries k
+ have member : u.val ∈ (site.descriptor node).sites := by
+ rw [data.orderAt node atRow]
+ exact List.mem_ofFn.mpr ⟨k, rfl⟩
+ have size : (packed Z u.val (old u.val u.prop)).length = ChildArguments.width Z u.val := by
+ rw [← Child.payload_ofHalf]
+ exact Child.payload_length Z _
+ exact ⟨⟨row.stack _ member, size ▸ row.stride _ member, size ▸ (row.room _ member).le⟩,
+ data.oldNodes _, data.abovePointer _⟩
+ have all q (hq : q ∈ TreeDecode.children rdr (fun u b => Packet.mk (ptr u) (packed Z u b))
+ v old) : q.Fits (regions).arguments w n ∧ q.node < (regions).nodes ∧
+ n < (regions).arguments.base q.node := by
+ obtain ⟨k, rfl⟩ := List.mem_ofFn.mp hq
+ exact packetBounds k
+ have positive : 0 < site.rowEnd := Nat.zero_lt_of_lt data.parentFit
+ have before : n < (regions).histBase := by
+ change n < n + site.rowEnd * (2 * slotDegree S * n + 1)
+ exact Nat.lt_add_of_pos_right (Nat.mul_pos positive (Nat.succ_pos _))
+ exact ⟨fun q hq => (all q hq).1, fun q hq => (all q hq).2.1,
+ fun q hq => (all q hq).2.2, before⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalReader.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalReader.lean
new file mode 100644
index 0000000000..cb01a5fabb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalReader.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalSite
+import OAI.Computability.VPVNP.PairShrinkRoleMapActions
+import OAI.Computability.VPVNP.PairShrinkRoleParent
+import OAI.Computability.VPVNP.PairShrinkRoleTypedActions
+import OAI.Computability.VPVNP.PairShrinkRoleSelectedChildren
+import OAI.Computability.VPVNP.PairShrinkRolePhysicalHidden
+import OAI.Computability.VPVNP.PairShrinkRoleMapStart
+import OAI.Computability.VPVNP.PairShrinkSiteBank
+
+/-!
+# The canonical parser for a selected shrinking site
+
+The parent packet, the child descriptors and the absorbed fields select the
+concrete jobs for one physical shrinking site. Each job gathers from the
+site's arena and runs the selected matrix in the fitted private workspace.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows ResidentMapLoop.Exact
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (i : Fin S.steps) {g : ℕ} (X : State (a i) (packingLaneBits (a i) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "Old" => Placed (X.packingData.shrinkPlace side ∘ X.packingInputIso.site.symm)
+ X.network.Half v
+local notation "Hidden" => Placed (X.packingData.shrinkInternalOwner side)
+ (internalLabel widths side) v
+
+variable {B i X sel v} {t w n : ℕ}
+ (site : CanonicalSite B i X sel v w n t) (ord : B.Entry → Fin t)
+
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "jobs" => ShrinkSiteBank.jobs B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v
+private noncomputable abbrev jobPublic (old : Old) (parent : (Y).network.Half v)
+ (q : X.packingData.ResidentMap side v) : Fin 5 → Word w :=
+ ShrinkSiteBank.pub site.level ((jobs old parent q).node : Word w) regions n
+
+section
+
+-- Keep the selected input intact when checking the type of its fitted workspace.
+attribute [local irreducible] ShrinkPartyNative.Job.entryInput
+/-- The physical row's ordered resident jobs with their actual map operands. -/
+noncomputable def canonicalBank (parent : (Y).network.Half v) (old : Old) (hidden : Hidden) :
+ List (Action w n) :=
+ MapWitness.actions (g := g) (w := w) (endAddr := n) B ord i X sel v hidden (jobs old parent)
+ site.mem site.level site.term site.source site.width (jobPublic site old parent) fun q => by
+ unfold MapWitness.jobInput matrixFamily
+ exact ShrinkPartyNative.Job.mapWorkspace (a := a i) (b := b i) (g := g) (t := t) (w := w)
+ (n := n) (limit := site.limit) B (slotDegree S) ord X (S.shrink i) sel q.1.1 q.1.2
+ (jobs old parent q) (q.2.symm ▸ hidden) (site.fits q.1.1)
+
+end
+
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+open private termAt readerAt childOrder from OAI.Computability.VPVNP.PairShrinkRoleScheduledSuffix
+local notation "chosen" => termAt B f hf i X sel
+local notation "readers" => readerAt B f hf i X sel
+local notation "orderAt" => childOrder B f hf i X sel v
+
+/-- Index the row's jobs by the physical child and hidden reader outputs. -/
+noncomputable def canonicalActions (parent : (Y).network.Half v) :
+ List (Child X) → List Row → List (Action w n) :=
+ typedActions (term := chosen) X v orderAt side widths v site.seed
+ (canonicalBank site ord parent)
+
+local notation "childLoad" => selectedChildSetup site.publicData site.mem site.levels site.passIndex
+ S.steps i.val (a i)
+local notation "hiddenLoad" => physicalHiddenSetup B.shrink.selectorBits (hiddenStride i)
+ site.level.val site.mem
+local notation "mapLoad" => mapStartSetup site.mem site.level (Fin.val (siteIndex X v) : Word w)
+
+/-- The shrinking visit with its parent fixed and the incoming tape unrestricted. -/
+noncomputable def canonicalFamily (parent : (Y).network.Half v) : HookParser w n :=
+ hook (visitReader (regions).arguments site.incidence site.mem site.older B.recordLimit
+ site.descriptor (fun _ => site.hiddenArgs)
+ (fun _ => ShrinkHiddenSlots.rows X side widths v site.seed)
+ (canonicalActions site ord f hf parent) childLoad (fun _ => hiddenLoad) (fun _ _ => mapLoad))
+
+/-- Decode the parent at the popped address and then run its selected shrinking visit. -/
+noncomputable def canonicalParent : HookParser w n :=
+ parentParser (Y) v (regions).arguments (canonicalFamily site ord f hf)
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalScanUpdate.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalScanUpdate.lean
new file mode 100644
index 0000000000..3794413264
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalScanUpdate.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.PairShrinkRoleScheduledUpdate
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+
+/-!
+# Reading a scheduled shrinking witness with the canonical parent parser
+
+The stored parent selects the gather jobs. The two field readers recover the
+actual placed and hidden assignments. The exterior and counter identities of
+that bank then determine the private update on every witness prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess LeafSourceLoad
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows ResidentMapLoop.Exact
+open scoped Fin.CommRing
+open private termAt readerAt childOrder from OAI.Computability.VPVNP.PairShrinkRoleScheduledSuffix
+
+variable {K : Type} {C : Type*} [_root_.Field K] [CommRing C]
+ {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g n w t : ℕ}
+ {X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : MapResidentRows.Site X}
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+variable (site : CanonicalSite B i X sel v w n t) (ord : B.Entry ≃ Fin t)
+ (f : B.Entry → C) (hf : B.IsSolution f)
+ (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+local notation "W" => B.shrinkPassWitnesses f hf i rfl X sel v old parent
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "rdr" => readerAt B f hf i X sel
+local notation "ordAt" => childOrder B f hf i X sel v
+local notation "childAt" => childNode X site.older B.recordLimit
+local notation "packetsAt" => TreeDecode.children rdr
+ (fun u b => Packet.mk (childAt u) (packed X u b)) v old
+local notation "rowsAt" => ShrinkHiddenSlots.rows X side widths v
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+local notation "childLoad" => selectedChildSetup site.publicData site.mem site.levels site.passIndex
+ S.steps i.val (a i)
+local notation "hiddenLoad" => physicalHiddenSetup B.shrink.selectorBits (hiddenStride i)
+ site.level.val site.mem
+local notation "mapLoad" => mapStartSetup site.mem site.level (Fin.val (siteIndex X v) : Word w)
+
+set_option maxHeartbeats 4000000 in
+-- Align the scheduled kernel's placement types and the actual gathered field assignments.
+/-- The full native parent parser realizes the tree row's private-memory contract
+for every supplied continuation and incoming stored parent. -/
+theorem canonicalParent_update_of_bank (x : (W).Choice) (node : Word w) (saved : Scratch w n)
+ (stored : (Packet.mk node.val (packed (Y) v parent)).Stored (regions).arguments saved)
+ (positive : 0 < w) (data : Fin 10 → Word w) (offset : Word w) (vals : Static 34 → Word w)
+ (frame : TreeDecode.VertexFrameData regions data offset vals saved)
+ (order : (site.descriptor node).sites = List.ofFn fun j => ((ordAt).entries j).val)
+ (base : site.hiddenArgs.scratchBase = heap) (before : n < (regions).histBase)
+ (heapFit : heap ≤ 2 ^ w)
+ (rowFit : ∀ e ∈ rowsAt x.1, heap + e.1 * site.hiddenArgs.slotStride + e.2.length ≤ 2 ^ w)
+ (fits : ∀ q ∈ packetsAt, q.Fits (regions).arguments w n)
+ (nodes : ∀ q ∈ packetsAt, q.node < (regions).nodes)
+ (above : ∀ q ∈ packetsAt, n < (regions).arguments.base q.node)
+ (preserve : ∀ initial events final, scan node (canonicalBank site ord parent old x.1) initial =
+ some (events, final) → ∀ address : Word w, address.val < heap →
+ (address.val < (regions).histBase ∨ (regions).histBase + t ≤ address.val) →
+ rawScratch final address = rawScratch initial address)
+ (count : ∀ initial events final, scan node (canonicalBank site ord parent old x.1) initial =
+ some (events, final) → ∀ l, let address : Word w := ((regions).histBase + (ord l).val : ℕ)
+ rawScratch final address = rawScratch initial address + ((W).exponents x l : Word w))
+ (tail : List Bool) (job : VisitPath w n)
+ (hit : (canonicalParent site ord f hf).read node saved
+ ((rdr).nodeBits v old parent x ++ tail) = some (job, tail)) :
+ RowUpdate regions ord data offset vals saved job packetsAt ((W).exponents x) := by
+ rw [canonicalParent, parentParser_read _ _ _ _ node saved parent stored positive] at hit
+ have labels : t ≤ (regions).histWords := by
+ change t ≤ Fintype.card B.Entry
+ exact (by simpa only [Fintype.card_fin] using (Fintype.card_congr ord).symm : t = _).le
+ have bankEq := typedActions_encoded (term := termAt B f hf i X sel) X v ordAt
+ side widths v site.seed (canonicalBank site ord parent) old x.1
+ have scanRun {s : Scratch w n} {events final}
+ (h : scan node (canonicalActions site ord f hf parent
+ (children (t := termAt B f hf i X sel) X v ordAt old) (rowsAt x.1)) s =
+ some (events, final)) :
+ scan node (canonicalBank site ord parent old x.1) s = some (events, final) :=
+ (congrArg (fun actions => scan node actions s) bankEq).symm.trans h
+ refine scheduledRowUpdate B f hf i X sel v old parent x site.seed regions site.incidence site.mem
+ site.older B.recordLimit site.descriptor site.hiddenArgs (canonicalActions site ord f hf parent)
+ childLoad hiddenLoad mapLoad node saved ord data offset vals frame order
+ (fun _ => rfl) (fun _ => rfl) (fun _ => rfl) base before labels heapFit rowFit fits nodes above
+ ?_ ?_ tail job hit
+ · intro events final run address low outside
+ exact preserve _ events final (scanRun run) address low outside
+ · intro events final run l
+ exact count _ events final (scanRun run) l
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalSuffix.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalSuffix.lean
new file mode 100644
index 0000000000..5f4830676a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalSuffix.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+import OAI.Computability.VPVNP.PairShrinkRoleMapAcceptance
+
+/-! # Exact suffix of the canonical shrinking parser at a prepared parent -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows ResidentMapLoop.Exact
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (i : Fin S.steps) {g : ℕ} (X : State (a i) (packingLaneBits (a i) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "side" => selectedLayout X B.shrink sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+variable {B i X sel v} {t w n : ℕ}
+ (site : CanonicalSite B i X sel v w n t) (ord : B.Entry → Fin t)
+
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "jobs" => ShrinkSiteBank.jobs B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+open private termAt readerAt childOrder from OAI.Computability.VPVNP.PairShrinkRoleScheduledSuffix
+local notation "readers" => readerAt B f hf i X sel
+local notation "orderAt" => childOrder B f hf i X sel v
+
+local notation "childLoad" => selectedChildSetup site.publicData site.mem site.levels site.passIndex
+ S.steps i.val (a i)
+local notation "hiddenLoad" => physicalHiddenSetup B.shrink.selectorBits (hiddenStride i)
+ site.level.val site.mem
+local notation "mapLoad" => mapStartSetup site.mem site.level (Fin.val (siteIndex X v) : Word w)
+
+open private jobPublic from OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+
+attribute [local irreducible] ResidentMapLoop.Exact.scan MapWitness.actions
+
+set_option maxHeartbeats 1000000 in
+-- Align the selected physical stage's placement and half types with the scheduled term.
+theorem canonicalParent_suffix (parent : (Y).network.Half v) (node : Word w) (saved : Scratch w n)
+ (stored : (Packet.mk node.val (packed (Y) v parent)).Stored (regions).arguments saved)
+ (positive : 0 < w)
+ (order : (site.descriptor node).sites = List.ofFn fun j => ((orderAt).entries j).val)
+ (bits : List Bool) :
+ ((canonicalParent site ord f hf).read node saved bits).map Prod.snd =
+ ((TreeDecode.nodeReader readers v parent).read bits).map Prod.snd := by
+ have read := parentParser_read (Y) v (regions).arguments (canonicalFamily site ord f hf)
+ node saved parent stored positive bits
+ refine (congrArg (Option.map Prod.snd) read).trans ?_
+ unfold canonicalFamily
+ refine scheduledSuffix B f hf i X sel v parent site.seed (regions).arguments site.incidence
+ site.mem site.older B.recordLimit site.descriptor (fun _ => site.hiddenArgs)
+ (canonicalActions site ord f hf parent) childLoad (fun _ => hiddenLoad) (fun _ _ => mapLoad)
+ node saved order ?_ bits
+ intro old hidden tail out xs _ value
+ have same : canonicalActions site ord f hf parent xs out.value =
+ canonicalBank site ord parent old hidden := by
+ rw [value]
+ exact typedActions_encoded (term := termAt B f hf i X sel) X v orderAt side
+ (ShrinkPreparedCall.width B.shrink X sel) v site.seed
+ (canonicalBank site ord parent) old hidden
+ rw [same]
+ unfold canonicalBank
+ exact MapWitness.scan_accepts (g := g) (t := t) (w := w) (endAddr := n) B ord i X sel v hidden
+ (jobs old parent) site.mem site.level
+ site.term site.source site.width (jobPublic site old parent) _ old parent
+ (fun _ => rfl) (fun _ => rfl) node _
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalUpdate.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalUpdate.lean
new file mode 100644
index 0000000000..62ec1b3a38
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCanonicalUpdate.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalScanUpdate
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalExterior
+import OAI.Computability.VPVNP.PairShrinkRoleMapHistogramNative
+
+/-!
+# The actual child, frame and counter effects of the selected shrinking parser
+
+The stored parent selects the gather jobs. The old and absorbed field readers
+recover the two arguments of the resident bank, whose physical stores preserve
+the exterior and add the selected matrix entries to the histogram.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess LeafSourceLoad
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows ResidentMapLoop.Exact
+open scoped Fin.CommRing
+open private termAt readerAt childOrder from OAI.Computability.VPVNP.PairShrinkRoleScheduledSuffix
+open private jobPublic from OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+
+variable {K : Type} {C : Type*} [_root_.Field K] [CommRing C]
+ {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g n w t packetEnd : ℕ}
+ {X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : MapResidentRows.Site X}
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+variable (site : CanonicalSite B i X sel v w n t) (ord : B.Entry ≃ Fin t)
+ (f : B.Entry → C) (hf : B.IsSolution f)
+ (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+local notation "W" => B.shrinkPassWitnesses f hf i rfl X sel v old parent
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "jobs" => ShrinkSiteBank.jobs B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v old parent
+local notation "rowAt" => MapWitness.rowEquiv X side v
+local notation "rdr" => readerAt B f hf i X sel
+local notation "ordAt" => childOrder B f hf i X sel v
+local notation "childAt" => childNode X site.older B.recordLimit
+local notation "packetsAt" => TreeDecode.children rdr
+ (fun u b => Packet.mk (childAt u) (packed X u b)) v old
+local notation "rowsAt" => ShrinkHiddenSlots.rows X side widths v
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+set_option maxHeartbeats 4000000 in
+-- Align the scheduled kernel's placement types and the actual gathered field assignments.
+/-- The full native parent parser realizes the tree row's private-memory contract
+for every supplied continuation and incoming stored parent. -/
+theorem canonicalParent_update (x : (W).Choice) (node : Word w) (saved : Scratch w n)
+ (stored : (Packet.mk node.val (packed (Y) v parent)).Stored (regions).arguments saved)
+ (positive : 0 < w) (data : Fin 10 → Word w) (offset : Word w) (vals : Static 34 → Word w)
+ (frame : TreeDecode.VertexFrameData regions data offset vals saved)
+ (order : (site.descriptor node).sites = List.ofFn fun j => ((ordAt).entries j).val)
+ (base : site.hiddenArgs.scratchBase = heap) (before : n < (regions).histBase)
+ (heapFit : heap ≤ 2 ^ w)
+ (rowFit : ∀ e ∈ rowsAt x.1, heap + e.1 * site.hiddenArgs.slotStride + e.2.length ≤ 2 ^ w)
+ (fits : ∀ q ∈ packetsAt, q.Fits (regions).arguments w n)
+ (nodes : ∀ q ∈ packetsAt, q.node < (regions).nodes)
+ (above : ∀ q ∈ packetsAt, n < (regions).arguments.base q.node)
+ (baseline : Word w → Word w) (packets : ∀ q, (jobs q).Packets packetEnd baseline)
+ {T : IncidenceDirectory w} {origin : ℕ}
+ (headers : ∀ j, let q := rowAt j
+ (jobs q).OldPublished (ShrinkCallABI.operands (slotDegree S)) (jobPublic site old parent q)
+ (rowOrdinalWord X side v j) site.mem site.level T origin)
+ (tail : List Bool) (job : VisitPath w n)
+ (hit : (canonicalParent site ord f hf).read node saved
+ ((rdr).nodeBits v old parent x ++ tail) = some (job, tail)) :
+ RowUpdate regions ord data offset vals saved job packetsAt ((W).exponents x) := by
+ refine canonicalParent_update_of_bank site ord f hf old parent x node saved stored positive
+ data offset vals frame order base before heapFit rowFit fits nodes above ?_ ?_ tail job hit
+ · intro initial events final run
+ exact canonicalBank_exterior (g := g) (w := w) (n := n) (packetEnd := packetEnd)
+ (T := T) (origin := origin) (initial := initial) (final := final) (es := events)
+ site ord old parent x.1 baseline packets headers node run
+ · intro initial events final run
+ exact canonicalBank_histogram (g := g) (w := w) (n := n) (packetEnd := packetEnd)
+ (T := T) (origin := origin) (initial := initial) (final := final) (es := events)
+ site ord f hf old parent x baseline packets headers node run
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleChild.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleChild.lean
new file mode 100644
index 0000000000..76ce27acfa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleChild.lean
@@ -0,0 +1,218 @@
+import OAI.Computability.VPVNP.PairNodeChildStage
+import OAI.Computability.VPVNP.PairShrinkRoleStages
+
+/-!
+# Decoding the child arguments of a shrinking visit
+
+The popped descriptor supplies the list of old sites. A complete guess
+assigns each outgoing and incoming slot independently and leaves the suffix
+for the local kernel. Every shorter stream rejects inside the scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.ChildArguments
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DFS NodeArguments
+open NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {w p r k a g endAddr : ℕ} (X : State a g)
+
+/-- Bits consumed by one child's slots in the order of the native scan. -/
+noncomputable def width (u : X.network.Site) : ℕ :=
+ ChildSlots.length X u (ChildSlots.slots (2 ^ a))
+
+/-- Number of bits in the child part of a local shrinking argument. -/
+noncomputable def demand (us : List X.network.Site) : ℕ := (us.map (width X)).sum
+
+theorem payload_length (xs : List (Child X)) :
+ (xs.flatMap (Child.payload X)).length = demand X (xs.map Child.site) := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih =>
+ rw [List.flatMap_cons, List.length_append, ih, Child.payload_length]
+ rfl
+
+/-- Split an arbitrary sufficiently long tape at every old-site boundary. -/
+theorem chooseChildren (us : List X.network.Site) (bs : List Bool)
+ (enough : demand X us ≤ bs.length) :
+ ∃ xs : List (Child X), xs.map Child.site = us ∧
+ xs.flatMap (Child.payload X) ++ bs.drop (demand X us) = bs := by
+ induction us generalizing bs with
+ | nil => exact ⟨[], rfl, rfl⟩
+ | cons u us ih =>
+ have count : demand X (u :: us) = width X u + demand X us := rfl
+ rw [count] at enough
+ obtain ⟨x, hx, head⟩ := choose_payload X u bs (by change width X u ≤ _; omega)
+ have len : (x.payload X).length = width X u := by rw [Child.payload_length, hx]; rfl
+ rw [len] at head
+ obtain ⟨xs, hxs, rest⟩ := ih (bs.drop (width X u)) (by simp; omega)
+ exact ⟨x :: xs, by simp [hx, hxs], by
+ rw [count, ← List.drop_drop, List.flatMap_cons, List.append_assoc, rest, head]⟩
+
+/-- The row and its old-layer directory are read at their actual machine addresses. -/
+structure Descriptor (w : ℕ) (X : State a g) where
+ /-- External start address of the selected row's consecutive child-node pointers. -/
+ source : ℕ
+ /-- Machine-word address of the old-layer directory supplying the child argument geometry. -/
+ directoryBase : Word w
+ /-- Old sites of this parent's selected placement fiber, in the same order as the stored
+ child-node pointers. -/
+ sites : List X.network.Site
+
+variable {X} (A : Arena) (T : IncidenceDirectory w) (m : Memory w) (older cap : ℕ)
+
+/-- Physical bounds and contents required for the finite descriptor scan. -/
+structure Resident (endAddr : ℕ) (node : Word w) (row : Descriptor w X) : Prop where
+ directory : (ChildScan.directory a older cap A T).Stored m row.directoryBase
+ children : Row m node.val row.source (row.sites.map fun u => (childNode X older cap u : Word w))
+ nodes : ∀ u ∈ row.sites, childNode X older cap u < 2 ^ w
+ stack : ∀ u ∈ row.sites, endAddr ≤ A.base (childNode X older cap u)
+ stride : ∀ u ∈ row.sites, width X u ≤ A.stride
+ room : ∀ u ∈ row.sites, A.base (childNode X older cap u) + width X u < 2 ^ w
+
+variable {A T m older cap}
+
+private theorem requirements {node : Word w} {row : Descriptor w X}
+ (h : Resident A T m older cap endAddr node row) (xs : List (Child X))
+ (sites : xs.map Child.site = row.sites) :
+ Row m node.val row.source (xs.map fun x => (childNode X older cap x.site : Word w)) ∧
+ (∀ x ∈ xs, childNode X older cap x.site < 2 ^ w) ∧
+ (∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w) ∧
+ (∀ q ∈ xs.map (Child.packet X older cap), q.Fits A w endAddr) := by
+ have member (x : Child X) (hx : x ∈ xs) : x.site ∈ row.sites := sites ▸ List.mem_map_of_mem hx
+ refine ⟨?_, fun x hx => h.nodes _ (member x hx), fun x hx => ?_, ?_⟩
+ · simpa only [← sites, List.map_map, Function.comp_def] using h.children
+ · rw [Child.payload_length]
+ exact h.room _ (member x hx)
+ · intro q hq
+ obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hq
+ have hu := member x hx
+ exact ⟨h.stack _ hu, (Child.payload_length X x) ▸ h.stride _ hu,
+ (Child.payload_length X x) ▸ (h.room _ hu).le⟩
+
+variable (A T m older cap) (desc : Word w → Descriptor w X)
+
+/-- The header trace, per-child trace and actual addressed writes of this decode. -/
+noncomputable def outcome (node : Word w) (saved : Scratch w endAddr) (xs : List (Child X)) :
+ Outcome w endAddr (List (Child X)) where
+ value := xs
+ trace := ChildHeader.events m node (desc node).directoryBase ++ events X T m (desc node).source xs
+ updated := writePackets A (xs.map (Child.packet X older cap)) saved
+
+/-- On a complete prefix the native child stage uses precisely the values decoded
+from that prefix. The first kernel bit remains at the start of the returned suffix. -/
+noncomputable def reader : Reader w endAddr (List (Child X)) := fun node saved bs =>
+ let us := (desc node).sites
+ if h : demand X us ≤ bs.length then
+ let xs := (chooseChildren X us bs h).choose
+ some (outcome A T m older cap desc node saved xs, bs.drop (demand X us))
+ else none
+
+theorem reader_some {node : Word w} {saved : Scratch w endAddr} {bs rest : List Bool}
+ {out : Outcome w endAddr (List (Child X))}
+ (h : reader A T m older cap desc node saved bs = some (out, rest)) :
+ out.value.map Child.site = (desc node).sites ∧
+ out = outcome A T m older cap desc node saved out.value ∧
+ bs = out.value.flatMap (Child.payload X) ++ rest := by
+ simp only [reader] at h
+ split at h
+ next enough =>
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj h)
+ have spec := (chooseChildren X (desc node).sites bs enough).choose_spec
+ exact ⟨spec.1, rfl, spec.2.symm⟩
+ next => contradiction
+
+theorem reader_none_iff {node : Word w} {saved : Scratch w endAddr} {bs : List Bool} :
+ reader A T m older cap desc node saved bs = none ↔ bs.length < demand X (desc node).sites := by
+ by_cases h : demand X (desc node).sites ≤ bs.length
+ · simp [reader, h]
+ · simp [reader, h, lt_of_not_ge h]
+
+private theorem outcome_bits (node : Word w) (saved : Scratch w endAddr) (xs : List (Child X)) :
+ choiceBits (outcome A T m older cap desc node saved xs).trace =
+ xs.flatMap (Child.payload X) := by
+ simp only [outcome, PrimedInputRAM.Flow.choiceBits_append, (ChildHeader.cost ..).2.2,
+ (events_cost ..).1, List.nil_append]
+
+/-- Tape splitting holds even if no live DFS stack represents this particular scratch. -/
+theorem splitBits {node : Word w} {saved : Scratch w endAddr} {bs rest : List Bool}
+ {out : Outcome w endAddr (List (Child X))}
+ (h : reader A T m older cap desc node saved bs = some (out, rest)) :
+ bs = choiceBits out.trace ++ rest := by
+ obtain ⟨_, eqn, hb⟩ := reader_some A T m older cap desc h
+ exact (congrArg (fun o => choiceBits o.trace) eqn |>.trans
+ (outcome_bits A T m older cap desc ..)) ▸ hb
+
+variable {M : Machine w p r k} {s : ChildScan.Sites a p} {reg : Fin 16 ↪ Fin r}
+ {source : ChildSlots.Names (2 ^ a) r k} {ret : Fin p} {header : Fin 17 → Fin p}
+
+/-- The child reader starts at its first instruction with the popped parent, directory address,
+slot ordinals, and resident external rows required by its scan. -/
+structure Entry (header : Fin 17 → Fin p) (reg : Fin 16 ↪ Fin r) (M : Machine w p r k)
+ (source : ChildSlots.Names (2 ^ a) r k) (endAddr : ℕ) (node : Word w)
+ (c : Config w p r) : Prop where
+ pc : c.pc = header 0
+ parent : c.reg (reg 7) = node
+ directory : c.reg (reg 8) = (desc node).directoryBase
+ ordinals : source.Valid M c
+ resident : Resident A T m older cap endAddr node (desc node)
+
+variable {A T m older cap desc}
+
+/-- The register-bank or public-operand scan realizes the decoder on every tape.
+The postcondition can use the exact native stores and every untouched register to
+prepare the next stage at the common return label. -/
+theorem realizesWith {dfs : Fin 9 ↪ Fin r}
+ (hh : ChildHeader.Linked M header reg (s.guard 0))
+ (hl : ChildScan.LinkedWith M s reg source ret)
+ (apart : source.Apart reg) (rep : T.ActualColumns X m) (strideFit : cap + 2 < 2 ^ w)
+ (separate : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → ∀ j, dfs i ≠ reg j)
+ {pre : Word w → Config w p r → Prop} {post : List (Child X) → Word w → Config w p r → Prop}
+ (start : ∀ node c, pre node c → Entry A T m older cap desc header reg M source endAddr node c)
+ (finish : ∀ node c d xs, pre node c → xs.map Child.site = (desc node).sites → d.pc = ret →
+ d.persistent = c.persistent →
+ d.privateMem = storePackets A (xs.map (Child.packet X older cap)) c.privateMem →
+ (∀ i, ChildHeader.Preserved reg i → i ∉ mutableRegs reg → d.reg i = c.reg i) →
+ post xs node d) :
+ Realizes (endAddr := endAddr) (reader A T m older cap desc) M m dfs pre post := by
+ constructor
+ · intro node c bs out rest hc got
+ let h := start node c hc
+ obtain ⟨sites, result, split⟩ := reader_some A T m older cap desc got
+ obtain ⟨row, nodes, room, fits⟩ := requirements h.resident out.value sites
+ obtain ⟨d, hd, per, mem, scratchEq, regs, native⟩ := native_stageWith hh hl apart rep
+ out.value (desc node).source c h.ordinals h.pc
+ (by rw [h.directory]; exact h.resident.directory)
+ (by rw [h.parent]; exact row) strideFit nodes room
+ have frame : ShrinkRole.Frame dfs endAddr c d := by
+ refine ⟨fun i hi => regs (dfs i) (fun j _ => separate i hi j) ?_, fun z hz => ?_, per⟩
+ · simp [mutableRegs, separate i hi]
+ · rw [mem]
+ exact storePackets_below A _ c.privateMem endAddr fits z hz
+ have bits := (congrArg (fun o => choiceBits o.trace) result).trans
+ (outcome_bits A T m older cap desc ..)
+ refine ⟨bits ▸ split, d, finish node c d out.value hc sites hd per mem regs, frame,
+ (scratchEq endAddr).trans (congrArg Outcome.updated result).symm, ?_⟩
+ rw [bits, congrArg Outcome.trace result]
+ simpa only [h.parent, h.directory, List.flatMap_map, Function.comp_def, Child.packet, outcome]
+ using native
+ · intro node c bs hc failed
+ let h := start node c hc
+ let xs : List (Child X) := (desc node).sites.map (fun u => ⟨u, fun _ _ => false⟩)
+ have sites : xs.map Child.site = (desc node).sites := by simp [xs, Function.comp_def]
+ obtain ⟨row, nodes, room, _⟩ := requirements h.resident xs sites
+ apply reject_stageWith hh hl apart rep xs (desc node).source c h.ordinals h.pc
+ (by rw [h.directory]; exact h.resident.directory) (by rw [h.parent]; exact row)
+ strideFit nodes room bs
+ rw [payload_length, sites]
+ exact (reader_none_iff A T m older cap desc).mp failed
+
+end PairSimulation.ShrinkRole.ChildArguments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleChildDescriptor.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleChildDescriptor.lean
new file mode 100644
index 0000000000..2aaa04b3ac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleChildDescriptor.lean
@@ -0,0 +1,22 @@
+import OAI.Computability.VPVNP.PairShrinkRoleChild
+
+/-! # The two pointers and ordered site list of a packed shrink child descriptor -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.PackedChildren
+
+open BurstRAM Compression
+
+/-- The child list begins immediately after the two-word popped-node header.
+The caller's old level publishes the child-directory bank at offset fourteen. -/
+def descriptor {a g w : ℕ} {Z : State a g} (head : Word w) (sites : List Z.network.Site)
+ (node : Word w) : ChildArguments.Descriptor w Z := ⟨node.val + 2, head + 14, sites⟩
+
+end PairSimulation.ShrinkRole.PackedChildren
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleChildReads.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleChildReads.lean
new file mode 100644
index 0000000000..24c4973527
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleChildReads.lean
@@ -0,0 +1,237 @@
+import OAI.Computability.VPVNP.PairShrinkRoleBankChild
+import OAI.Computability.VPVNP.PairSimulationTerminalSplice
+import OAI.Computability.VPVNP.PairVertexLevelBounds
+import OAI.Computability.VPVNP.CompressorDescriptorSpace
+import OAI.Computability.VPVNP.CompressorRecordsShrinkFrame
+import OAI.Computability.VPVNP.CompressorFlowFootprint
+
+/-!
+# External reads of the native child decoder
+
+Each child consumes one pointer in the selected DFS row. Each slot probes its
+width, and each incoming slot first probes its inverse-incidence entry. The
+typed inverse column identifies the second probe even when the memory outside
+the old level contains arbitrary words. Guessing and storing the payload bits
+uses only private memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.ChildArguments
+
+open BurstRAM Compression CompressorRecords NodeArguments NodeArguments.ChildScan DFS
+open scoped Fin.CommRing
+open private offset_eq from OAI.Computability.VPVNP.PairNodeChildHeader
+
+variable {w a g endAddr : ℕ} {X : State a g} {T : IncidenceDirectory w} {m : Memory w}
+
+/-- Bounds for the two physical columns visited by the old-slot scan. -/
+structure ColumnsBelow (T : IncidenceDirectory w) (X : State a g) (limit : ℕ) : Prop where
+ incoming : T.actualIn.val + IncidenceDirectory.slotCount X ≤ limit
+ widths : T.width.val + IncidenceDirectory.slotCount X ≤ limit
+
+private theorem field_reads {limit : ℕ} (rep : T.ActualColumns X m)
+ (col : ColumnsBelow T X limit) (dir : Bool) (e : (X.Base × BitWord g) × Fin (2 ^ a)) :
+ SourceTransport.Reads (· < limit)
+ (FieldGuess.headerEvents T m dir (IncidenceDirectory.actualPort X e)) := by
+ have bound (base : Word w) (hb : base.val + IncidenceDirectory.slotCount X ≤ limit)
+ (f : (X.Base × BitWord g) × Fin (2 ^ a)) :
+ (base + IncidenceDirectory.actualPort X f).val < limit := by
+ rw [Fin.val_add]
+ exact (Nat.mod_le ..).trans_lt ((Nat.add_lt_add_left
+ (IncidenceDirectory.actualPort_lt X f) _).trans_le hb)
+ intro p v hp
+ cases dir <;> simp only [FieldGuess.headerEvents, Bool.false_eq_true, ite_false,
+ ite_true, List.mem_append, List.mem_cons, List.not_mem_nil, reduceCtorEq,
+ Event.read.injEq, false_or, or_false] at hp
+ · exact hp.1 ▸ bound T.width col.widths e
+ · rcases hp with ⟨rfl, _⟩ | ⟨rfl, _⟩
+ · exact bound T.actualIn col.incoming e
+ · rw [rep.actualIn]
+ exact bound T.width col.widths _
+
+private theorem slot_reads {limit : ℕ} (rep : T.ActualColumns X m) (col : ColumnsBelow T X limit)
+ (x : Child X) (slots : List (Bool × Fin (2 ^ a))) :
+ SourceTransport.Reads (· < limit) (ChildSlots.events X x.site T m x.data slots) := by
+ intro p v hp
+ obtain ⟨i, _, h⟩ := List.mem_flatMap.mp hp
+ simp only [List.mem_append, List.mem_cons, List.not_mem_nil, reduceCtorEq, false_or] at h
+ exact h.elim (field_reads rep col i.1 (x.site, i.2) p v)
+ ((FlowFootprint.bounds_of_noProbes (· < limit) (fun _ => False)
+ (PrivateFields.events_work (w := w) .guess (List.ofFn (x.data i))).2).1 p v)
+
+/-- External reads inside the loop over the child list. -/
+theorem scan_reads_below {limit : ℕ} (rep : T.ActualColumns X m)
+ (col : ColumnsBelow T X limit) (src : ℕ) (xs : List (Child X))
+ (row : src + xs.length ≤ limit) :
+ SourceTransport.Reads (· < limit) (events X T m src xs) := by
+ induction xs generalizing src with
+ | nil => intro p v hp; simp [events] at hp
+ | cons x xs ih =>
+ intro p v hp
+ simp only [events, childEvents, setupEvents, ChildAddress.events, List.mem_append,
+ List.mem_cons, List.not_mem_nil, reduceCtorEq, Event.read.injEq, false_or, or_false] at hp
+ rcases hp with (⟨rfl, _⟩ | h) | h
+ · exact (Nat.mod_le ..).trans_lt (by simp only [List.length_cons] at row; omega)
+ · exact slot_reads rep col x _ p v h
+ · exact ih (src + 1) (by simp only [List.length_cons] at row; omega) p v h
+
+/-- The two descriptor words and the seven old-level fields are the external
+reads of the native child header. -/
+theorem header_reads_below {limit : ℕ} (m : Memory w) (node base : Word w)
+ (parent : node.val + 1 < limit) (old : base.val + 6 < limit) :
+ SourceTransport.Reads (· < limit) (ChildHeader.events m node base) := by
+ have offset (b : Word w) (j : ℕ) (h : b.val + j < limit) : (b + (j : Word w)).val < limit := by
+ rw [Fin.val_add, Fin.val_natCast]
+ exact (Nat.mod_le ..).trans_lt ((Nat.add_le_add_left (Nat.mod_le ..) _).trans_lt h)
+ intro p v hp
+ simp only [ChildHeader.events, offset_eq, List.mem_cons, List.not_mem_nil, reduceCtorEq,
+ Event.read.injEq, false_or, or_false] at hp
+ rcases hp with ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩ |
+ ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩
+ · omega
+ · exact offset node 1 parent
+ · omega
+ all_goals (apply offset; omega)
+
+/-- The physical child-stage trace reads only the selected row, its directory
+and its incoming and width columns. This also applies to a singleton refresh. -/
+theorem trace_reads_below {limit : ℕ} (rep : T.ActualColumns X m) (col : ColumnsBelow T X limit)
+ (node base : Word w) (src : ℕ) (xs : List (Child X)) (parent : node.val + 1 < limit)
+ (old : base.val + 6 < limit) (row : src + xs.length ≤ limit) :
+ SourceTransport.Reads (· < limit) (ChildHeader.events m node base ++ events X T m src xs) :=
+ fun p v hp => (List.mem_append.mp hp).elim (header_reads_below m node base parent old p v)
+ (scan_reads_below rep col src xs row p v)
+
+variable {A : Arena} {older cap : ℕ} {desc : Word w → Descriptor w X}
+ {node : Word w} {saved : Scratch w endAddr} {bs rest : List Bool}
+ {out : Outcome w endAddr (List (Child X))}
+
+/-- Complete child reads are strictly below the terminal header whenever the
+parent row, old directory words and the two live columns lie below it. -/
+theorem reader_reads_below {limit : ℕ} (rep : T.ActualColumns X m) (col : ColumnsBelow T X limit)
+ (parent : node.val + 1 < limit) (old : (desc node).directoryBase.val + 6 < limit)
+ (row : (desc node).source + (desc node).sites.length ≤ limit)
+ (read : reader A T m older cap desc node saved bs = some (out, rest)) :
+ SourceTransport.Reads (· < limit) out.trace := by
+ obtain ⟨sites, result, _⟩ := reader_some A T m older cap desc read
+ have len : out.value.length = (desc node).sites.length := by
+ simpa using congrArg List.length sites
+ rw [congrArg Outcome.trace result]
+ exact trace_reads_below rep col node _ _ _ parent old (len ▸ row)
+
+open DescriptorSpace TraversalRoles TraversalRows VertexLevelBounds
+open private incidence_end_le from OAI.Computability.VPVNP.CompressorDescriptorSpace
+
+/-- In the descriptor allocation both columns end before the DFS row table. -/
+theorem ColumnsBelow.packed (L : Layout) (level : Fin L.levels)
+ (rows : IncidenceDirectory.slotCount X ≤ slotCapacity L) :
+ ColumnsBelow (packedIncidence L w level (IncidenceDirectory.slotCount X)) X (endAddress L) := by
+ let n := IncidenceDirectory.slotCount X
+ have packed : incidenceStart L level + 6 * n ≤ endAddress L :=
+ (Nat.add_le_add_left (Nat.mul_le_mul_left 6 rows) _).trans
+ ((incidence_end_le L level).trans (levelStart_mono L level.isLt))
+ constructor
+ · change (incidenceStart L level + 4 * n) % (2 ^ w) + n ≤ endAddress L
+ have := Nat.mod_le (incidenceStart L level + 4 * n) (2 ^ w)
+ omega
+ · change (incidenceStart L level + 5 * n) % (2 ^ w) + n ≤ endAddress L
+ have := Nat.mod_le (incidenceStart L level + 5 * n) (2 ^ w)
+ omega
+
+/-- The whole reserved child row fits inside the selected tag sequence's row
+table, including the payload of its last site. -/
+theorem selected_row_end (base cap : ℕ) (tags : List TaggedLayer) (j : Fin tags.length)
+ (id : Fin tags[j].layer.count) :
+ address cap (layerBase cap base tags j.val) id.val + 2 + cap ≤
+ base + words cap (tags.map TaggedLayer.layer) := by
+ have step := Nat.mul_le_mul_left (cap + 2) id.isLt
+ have finish := layerBase_mono cap base tags j.isLt
+ rw [layerBase_succ cap base tags j] at finish
+ simp only [endPos, address, layerBase, List.take_length] at finish ⊢
+ rw [Nat.mul_succ] at step
+ omega
+
+/-- Starting the child header at scalar 14 leaves all seven fields inside the
+old level, before the first DFS row. -/
+theorem old_fields_below (L : Layout) (level : Fin L.levels)
+ (wide : 21 ≤ levelHeaderWords L) :
+ (((levelStart L level + 14 : ℕ) : Word w)).val + 6 < endAddress L := by
+ have next := levelStart_mono L level.isLt
+ change levelStart L (level.val + 1) ≤ endAddress L at next
+ have advance : levelStart L (level.val + 1) = levelStart L level + levelWords L := by
+ simp only [levelStart, Nat.succ_mul, Nat.add_assoc]
+ have width : levelHeaderWords L ≤ levelWords L := by unfold levelWords; omega
+ rw [Fin.val_natCast]
+ have := Nat.mod_le (levelStart L level + 14) (2 ^ w)
+ omega
+
+/-- Specialize the read bound to a popped descriptor at its selected row
+address, with the old field bank starting at scalar 14 of the preceding
+physical level. -/
+theorem selected_reads_below (L : Layout) (level : Fin L.levels)
+ (rep : T.ActualColumns X m)
+ (columns : T = packedIncidence L w level (IncidenceDirectory.slotCount X))
+ (rows : IncidenceDirectory.slotCount X ≤ slotCapacity L)
+ (oldFields : 21 ≤ levelHeaderWords L)
+ (tags : List TaggedLayer) (j : Fin tags.length) (id : Fin tags[j].layer.count)
+ (addressEq : node.val = address cap (layerBase cap (endAddress L) tags j.val) id.val)
+ (directory : (desc node).directoryBase = ((levelStart L level + 14 : ℕ) : Word w))
+ (source : (desc node).source = node.val + 2)
+ (capacity : (desc node).sites.length ≤ cap) (H : Word w)
+ (before : endAddress L + words cap (tags.map TaggedLayer.layer) ≤ H.val)
+ (read : reader A T m older cap desc node saved bs = some (out, rest)) :
+ SourceTransport.Reads (· < H.val) out.trace := by
+ have base : endAddress L ≤ H.val := (Nat.le_add_right ..).trans before
+ have col := ColumnsBelow.packed (w := w) L level rows
+ have room := (selected_row_end (endAddress L) cap tags j id).trans before
+ rw [← addressEq] at room
+ refine reader_reads_below rep ?_ ?_ ?_ ?_ read
+ · rw [columns]
+ exact ⟨col.incoming.trans base, col.widths.trans base⟩
+ · omega
+ · rw [directory]
+ exact (old_fields_below L level oldFields).trans_le base
+ · rw [source]
+ omega
+
+/-- The register-bank initializer precedes the decoder with local ticks. Thus
+every external read of the hosted segment belongs to the child decoder. -/
+theorem bank_reads_of_reader {data : ℕ → Prop}
+ (safe : ∀ child tail, reader A T m older cap desc node saved bs = some (child, tail) →
+ SourceTransport.Reads data child.trace)
+ (got : BankChild.reader A T m older cap desc node saved bs = some (out, rest)) :
+ SourceTransport.Reads data out.trace := by
+ cases h : reader A T m older cap desc node saved bs with
+ | none => simp [BankChild.reader, ShrinkRole.bind, Setup.ticks, Setup.reader, h] at got
+ | some result =>
+ obtain ⟨child, tail⟩ := result
+ have eqn : (⟨child.value, List.replicate (2 ^ a) .tick ++ child.trace, child.updated⟩ :
+ Outcome w endAddr (List (Child X))) = out := by
+ simpa [BankChild.reader, ShrinkRole.bind, Setup.ticks, Setup.reader, h] using
+ (congrArg (Option.map Prod.fst) got)
+ intro p v hp
+ rw [← eqn] at hp
+ exact safe child tail h p v (by simpa using hp)
+
+/-- A strict read bound excludes both physical terminal control addresses. -/
+theorem worker_reads_of_below (H : Word w) (fit : H.val + 32 ≤ 2 ^ w)
+ {es : List (Event w)} (below : SourceTransport.Reads (· < H.val) es) :
+ SourceTransport.Reads (TerminalLink.workerCell H) es := by
+ intro p v hp
+ have low := below p v hp
+ have last : (H + 31).val = H.val + 31 := by
+ have numeral : (31 : Word w).val = 31 := by
+ change 31 % (2 ^ w) = 31
+ exact Nat.mod_eq_of_lt (by omega)
+ rw [Fin.val_add, numeral,
+ Nat.mod_eq_of_lt (by omega)]
+ exact ⟨low.ne, by omega⟩
+
+end PairSimulation.ShrinkRole.ChildArguments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleChildTyped.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleChildTyped.lean
new file mode 100644
index 0000000000..c24eeeeb72
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleChildTyped.lean
@@ -0,0 +1,217 @@
+import OAI.Computability.VPVNP.PairShrinkRoleChild
+
+/-!
+# Recovering the old half-wire assignment from the native child tape
+
+The outgoing slot order and the inverse incoming slot order reconstruct both
+independent halves of each child. The native reader therefore returns the
+actual typed arguments of a supplied witness, and every complete decode in
+placement order yields such an assignment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments.ChildScan
+
+open Compression LocalHistory NetworkKernel CompressorRecords
+variable {a g : ℕ} (X : State a g)
+
+/-- The inverse to recording independent outgoing and incoming slot fields. -/
+noncomputable def Child.half (x : Child X) : X.network.Half x.site :=
+ let unorder {f : X.network.Edge → X.network.Site} (ord : Order {e // x.site = f e})
+ (values : (j : Fin ord.length) → X.network.Payload (ord.entries j).val) :=
+ fun e h => Equiv.piCongrLeft (fun z : {e // x.site = f e} => X.network.Payload z.val)
+ ord.entries values ⟨e,h⟩
+ (unorder (outgoingOrder X x.site) (fun j => x.data (false,j)),
+ unorder (incomingOrder X x.site) (fun j => x.data (true,j)))
+
+theorem Child.ofHalf_half (x : Child X) : Child.ofHalf X x.site (x.half X) = x := by
+ rcases x with ⟨u, d⟩
+ unfold Child.ofHalf
+ congr 1
+ funext i
+ rcases i with ⟨b,j⟩
+ cases b <;> exact Equiv.piCongrLeft_apply_apply ..
+
+
+theorem Child.payload_eq_packed (x : Child X) : x.payload X = packed X x.site (x.half X) := by
+ simpa only [Child.ofHalf_half] using Child.payload_ofHalf X x.site (x.half X)
+
+private theorem Child.eq_of_half {x : Child X} {v : X.network.Site} (h : x.site = v) :
+ Child.ofHalf X v (h ▸ x.half X) = x := by
+ subst v
+ exact Child.ofHalf_half X x
+
+/-- Every list decoded in the placement order comes from old half-wire values
+at precisely the sites in the placement fiber. -/
+theorem exists_placed {R : Type*} {t : Term R X.network} (v : t.output.Site)
+ (ord : Order (t.Preimage v)) (xs : List (Child X))
+ (order : xs.map Child.site = List.ofFn fun j => (ord.entries j).val) :
+ ∃ h : Placed t.place X.network.Half v, children X v ord h = xs := by
+ have len : xs.length = ord.length := by simpa using congrArg List.length order
+ have bound (j : Fin ord.length) : j.val < xs.length := len.symm ▸ j.isLt
+ let atIndex (j : Fin ord.length) := xs[j.val]'(bound j)
+ have site (j : Fin ord.length) : (atIndex j).site = (ord.entries j).val := by
+ have h := congrArg (fun us => us[j.val]?) order
+ simpa [atIndex, List.getElem?_eq_getElem (bound j), j.isLt] using h
+ let halves (j : Fin ord.length) : X.network.Half (ord.entries j).val :=
+ site j ▸ (atIndex j).half X
+ let h : Placed t.place X.network.Half v := fun u hu =>
+ Equiv.piCongrLeft (fun z : t.Preimage v => X.network.Half z.val) ord.entries halves ⟨u,hu⟩
+ have selected (j : Fin ord.length) : h _ (ord.entries j).prop = halves j :=
+ Equiv.piCongrLeft_apply_apply ..
+ refine ⟨h, List.ext_getElem (by simp [children, len]) ?_⟩
+ intro n hn hx
+ let j : Fin ord.length := ⟨n, len ▸ hx⟩
+ simp only [children, List.getElem_ofFn]
+ exact (congrArg (Child.ofHalf X _) (selected j)).trans (Child.eq_of_half X (site j))
+
+/-- A site's exact tape prefix determines its entire independent slot assignment
+and the rest of the tape uniquely. -/
+theorem Child.uniquePrefix {x y : Child X} (site : x.site = y.site) {s t : List Bool}
+ (bits : x.payload X ++ s = y.payload X ++ t) : x = y ∧ s = t := by
+ rcases x with ⟨u, xs⟩
+ rcases y with ⟨v, ys⟩
+ change u = v at site
+ subst v
+ let x : Child X := ⟨u,xs⟩
+ let y : Child X := ⟨u,ys⟩
+ let parser := LocalHistory.half X.network u (outgoingOrder X u) (incomingOrder X u)
+ (statePayload X)
+ have enc (z : Child X) : z.payload X = packed X z.site (z.half X) := z.payload_eq_packed X
+ have words : parser.encode (x.half X) ++ s = parser.encode (y.half X) ++ t := by
+ change x.payload X ++ s = y.payload X ++ t at bits
+ rwa [enc x, enc y, packed_eq_encode, packed_eq_encode] at bits
+ have one := (parser.read_iff _ (x.half X) s).mpr rfl
+ have two := (parser.read_iff _ (y.half X) t).mpr words
+ obtain ⟨equal, rest⟩ := Prod.mk.inj (Option.some.inj (one.symm.trans two))
+ exact ⟨(x.ofHalf_half X).symm.trans
+ ((congrArg (Child.ofHalf X u) equal).trans (y.ofHalf_half X)), rest⟩
+
+theorem uniqueChildren {xs ys : List (Child X)} (order : xs.map Child.site = ys.map Child.site)
+ {s t : List Bool}
+ (bits : xs.flatMap (Child.payload X) ++ s = ys.flatMap (Child.payload X) ++ t) :
+ xs = ys ∧ s = t := by
+ induction xs generalizing ys with
+ | nil => cases ys <;> simp_all
+ | cons x xs ih =>
+ cases ys with
+ | nil => simp at order
+ | cons y ys =>
+ obtain ⟨head, tail⟩ := List.cons.inj order
+ rw [List.flatMap_cons, List.flatMap_cons, List.append_assoc, List.append_assoc] at bits
+ obtain ⟨rfl, rem⟩ := Child.uniquePrefix X head bits
+ obtain ⟨rfl, rfl⟩ := ih tail rem
+ exact ⟨rfl, rfl⟩
+
+end PairSimulation.NodeArguments.ChildScan
+
+namespace PairSimulation.ShrinkRole.ChildArguments
+
+open BurstRAM Compression CompressorRecords NodeArguments NodeArguments.ChildScan DFS
+
+variable {a g w endAddr : ℕ} {X : State a g} (A : Arena) (T : IncidenceDirectory w)
+ (m : Memory w) (older cap : ℕ) (desc : Word w → Descriptor w X)
+
+/-- Feeding the encoded list of arbitrary typed children returns the very same
+list, writes its packets, and leaves the supplied kernel suffix intact. -/
+theorem reader_encoded (node : Word w) (saved : Scratch w endAddr) (xs : List (Child X))
+ (sites : xs.map Child.site = (desc node).sites) (rest : List Bool) :
+ reader A T m older cap desc node saved (xs.flatMap (Child.payload X) ++ rest) =
+ some (outcome A T m older cap desc node saved xs, rest) := by
+ let bs := xs.flatMap (Child.payload X) ++ rest
+ have enough : demand X (desc node).sites ≤ bs.length := by
+ rw [← sites, ← payload_length]
+ simp [bs]
+ let picked := chooseChildren X (desc node).sites bs enough
+ obtain ⟨equal, suffix⟩ := uniqueChildren X (picked.choose_spec.1.trans sites.symm)
+ picked.choose_spec.2
+ change reader A T m older cap desc node saved bs = _
+ simp only [reader, dite_eq_left enough]
+ change some (outcome A T m older cap desc node saved picked.choose,
+ bs.drop (demand X (desc node).sites)) = _
+ rw [equal, suffix]
+
+open NetworkKernel LocalHistory
+open private fiber_encode from OAI.Computability.VPVNP.PairNodeArguments
+
+variable {R : Type*} {t : Term R X.network} (v : t.output.Site) (ord : Order (t.Preimage v))
+
+/-- The old half-wire part of the abstract site parser. -/
+noncomputable def placedReader : ChoiceReader (Placed t.place X.network.Half v) :=
+ fiber t.place v ord fun u =>
+ LocalHistory.half X.network u (outgoingOrder X u) (incomingOrder X u) (statePayload X)
+
+theorem children_bits (h : Placed t.place X.network.Half v) :
+ (children X v ord h).flatMap (Child.payload X) = (placedReader v ord).encode h := by
+ unfold placedReader
+ rw [fiber_encode]
+ simp only [children, List.flatMap_def, List.map_ofFn, Function.comp_def,
+ Child.payload_ofHalf, packed_eq_encode]
+
+private theorem children_injective : Function.Injective (children X v ord) := by
+ intro x y equal
+ let C := placedReader v ord
+ have eqn : C.encode x = C.encode y := by
+ rw [← children_bits v ord x, ← children_bits v ord y, equal]
+ have one := (C.read_iff _ x []).mpr rfl
+ have two := (C.read_iff _ y []).mpr (congrArg (· ++ []) eqn)
+ exact (Prod.mk.inj (Option.some.inj (one.symm.trans two))).1
+
+/-- Reading a placed half-wire witness consumes precisely its encoding and
+returns the corresponding old children in the descriptor's order. -/
+theorem reader_placed (node : Word w) (saved : Scratch w endAddr)
+ (order : (desc node).sites = List.ofFn fun j => (ord.entries j).val)
+ (h : Placed t.place X.network.Half v) (rest : List Bool) :
+ reader A T m older cap desc node saved ((placedReader v ord).encode h ++ rest) =
+ some (outcome A T m older cap desc node saved (children X v ord h), rest) := by
+ rw [← children_bits]
+ apply reader_encoded
+ rw [order]
+ simp [children, Child.ofHalf, Function.comp_def]
+
+/-- The exact tape, old sites, slot values, and scratch returned by a complete
+native read determine one placed half-wire assignment. -/
+theorem reader_unique_placed (node : Word w) (saved : Scratch w endAddr)
+ (order : (desc node).sites = List.ofFn fun j => (ord.entries j).val)
+ {bs rest : List Bool} {out : Outcome w endAddr (List (Child X))}
+ (read : reader A T m older cap desc node saved bs = some (out, rest)) :
+ ∃! h : Placed t.place X.network.Half v,
+ out = outcome A T m older cap desc node saved (children X v ord h) ∧
+ bs = (placedReader v ord).encode h ++ rest := by
+ obtain ⟨sites, eqn, stream⟩ := reader_some A T m older cap desc read
+ obtain ⟨h, data⟩ := exists_placed X v ord out.value (sites.trans order)
+ refine ⟨h, ⟨data ▸ eqn, ?_⟩, fun y hy => children_injective v ord ?_⟩
+ · rw [← children_bits, data, stream]
+ · exact (congrArg Outcome.value hy.1).symm.trans data.symm
+
+variable {R L : Type} [CommRing R] [Fintype L] {κ : L → R} {t : Term R X.network}
+
+/-- The actual native writes on the semantic witness establish exactly the
+typed packets carried by the local vertex job. -/
+theorem reader_childPackets (r : TermParsers κ t) (hp : ∀ u h, r.halfBits u h = packed X u h)
+ (v : t.output.Site) (node : Word w) (saved : Scratch w endAddr)
+ (order : (desc node).sites = List.ofFn fun j => ((r.order.children v).entries j).val)
+ (h : Placed t.place X.network.Half v) (rest : List Bool) :
+ let xs := children X v (r.order.children v) h
+ let qs := r.childPackets (childNode X older cap) v h
+ ∃ out, reader A T m older cap desc node saved (qs.flatMap Packet.bits ++ rest) =
+ some (out, rest) ∧ out.value = xs ∧ out.updated = writePackets A qs saved := by
+ intro xs qs
+ have packets := children_packets r hp older cap v h
+ change xs.map (Child.packet X older cap) = qs at packets
+ have bits : qs.flatMap Packet.bits = (placedReader v (r.order.children v)).encode h := by
+ rw [← packets, List.flatMap_map]
+ exact children_bits v (r.order.children v) h
+ refine ⟨outcome A T m older cap desc node saved xs, ?_, rfl, ?_⟩
+ · rw [bits]
+ exact reader_placed A T m older cap desc v (r.order.children v) node saved order h rest
+ · rw [← packets]; rfl
+
+end PairSimulation.ShrinkRole.ChildArguments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleCompiledSite.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleCompiledSite.lean
new file mode 100644
index 0000000000..a4ef435924
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleCompiledSite.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalSite
+import OAI.Computability.VPVNP.PairShrinkRolePackedHidden
+import OAI.Computability.VPVNP.PairShrinkRoleChildDescriptor
+import OAI.Computability.VPVNP.PairShrinkRolePackedRow
+import OAI.Computability.VPVNP.PairSimulationShrinkMapCompiledSource
+
+/-!
+# The physical data of a shrinking site in the selected compressor image
+
+The site reads its own term rows and owner tables from the compiled payload.
+The child descriptor uses the selected pass's ordered fiber. Its private
+hidden and matrix operands share the same post-stack reservation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords DescriptorSpace
+open ShrinkBlockInputs LocalHistory ShrinkMapImage.Registers MapResidentRows
+open scoped Fin.CommRing
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K} (B : S.Templates)
+ (f : B.Entry → A) (hf : B.IsSolution f) (i : Fin S.steps) {g w : ℕ}
+ (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+ (v : Site X) (pub : Fin 11 → Word w) (workspace : Word w)
+ (positions blocks cur n rowEnd older later limit levels : ℕ) (phy : Memory w)
+ (payload : CompiledResident.ShrinkPayload B workspace positions blocks n cur i X sel phy)
+
+local notation "D" => BlockProgram.layout B workspace.val positions blocks
+local notation "t" => Fintype.card B.Entry
+local notation "R" => TerminalLayout.privateRegions (slotDegree S) n rowEnd t
+local notation "side" => SelectedFinish.chosen B X sel
+local notation "levelAt" => (levelStart D cur : Word w)
+local notation "tab" => (fun j : Fin 6 => tableBase D cur j)
+local notation "termAt" => ShrinkInput.termHead (w := w) X (tab 0)
+
+private noncomputable abbrev selectedSource :=
+ (mapRowSource_compiled B workspace positions blocks n cur i X sel payload).choose
+
+local notation "sourceAt" => selectedSource B i X sel workspace positions blocks cur n phy payload
+
+variable (width : MapConstants.widthThreshold B.shrink ≤ w)
+ (fits : ∀ m, canonicalFits B i X sel (w := w) (Fintype.card B.Entry) n rowEnd older limit m)
+
+/-- The concrete parser site on the packed level. Its operand banks are the
+ones read by the compressor, locator, and selected party map code. -/
+def compiledSite : CanonicalSite B i X sel v w n t where
+ workspace := workspace
+ positions := positions
+ blocks := blocks
+ cur := cur
+ bounds := payload.bounds
+ rowEnd := rowEnd
+ older := older
+ later := later
+ limit := limit
+ fits := fits
+ mem := phy
+ level := levelAt
+ term := termAt
+ source := sourceAt
+ width := width
+ publicData := pub
+ levels := levels
+ passIndex := cur
+ incidence := packedIncidence D w cur (X.positions * 2 ^ a i)
+ descriptor := PackedChildren.descriptor levelAt (oldSites B f hf i X sel v)
+ hiddenArgs := PackedHidden.arguments B i X sel workspace positions blocks cur n R v
+ seed := fun _ _ => ⟨0, Nat.two_pow_pos _⟩
+
+local notation "site" => compiledSite B f hf i X sel v pub workspace positions blocks cur n
+ rowEnd older later limit levels phy payload width fits
+
+/-- The matrix owner directory starts at table five of this chronological level. -/
+theorem compiledSite_first : (site).source.first = tab 5 :=
+ (mapRowSource_compiled B workspace positions blocks n cur i X sel payload).choose_spec.1
+
+/-- All map reads of this source lie in the retained producing level. -/
+theorem compiledSite_inLevel : (site).source.InLevel D cur :=
+ (mapRowSource_compiled B workspace positions blocks n cur i X sel payload).choose_spec.2.1
+
+/-- The four header values read by the map loop are present at their
+actual offsets in the terminal vertex's memory. -/
+theorem compiledSite_published :
+ let p := (ShrinkResidentLayout.layout X (site).source.first).params (a i) true w
+ MapResidentInputs.Published phy levelAt (p 3) (p 5) termAt 10 := by
+ rw [compiledSite_first B f hf i X sel v pub workspace positions blocks cur n
+ rowEnd older later limit levels phy payload width fits]
+ exact (mapRowSource_compiled B workspace positions blocks n cur i X sel payload).choose_spec.2.2
+
+/-- The exclusive stop pointer of the selected map row fits the word. -/
+theorem compiledSite_mapRoom :
+ ShrinkVertexImage.firstMap B i (site).source v + (order X side v).length < 2 ^ w := by
+ have bound := (directory_fit X (site).source.first v (site).source.fit).2
+ rw [MapResidentRows.length_eq]
+ exact bound
+
+end PairSimulation.ShrinkRole
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleDirectory.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleDirectory.lean
new file mode 100644
index 0000000000..a3049272e7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleDirectory.lean
@@ -0,0 +1,219 @@
+import OAI.Computability.VPVNP.PairOutputRowDirectory
+import OAI.Computability.VPVNP.PairTraversalRoleDispatch
+
+/-!
+# Decoding a shrinking visit from the popped row address
+
+Each output site belongs to one occurrence of a selected term. Distinct
+occurrences remain distinct even when the same term is chosen twice. The
+parser receives only the popped word and scratch state. Its physical row
+selects both the term occurrence and the site in that term's output network.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRoleDirectory
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords Compression LocalHistory
+open TraversalRows TraversalRoles DFS
+open scoped Fin.CommRing
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → R} {hf : B.IsSolution f}
+
+/-- The order used when writing the rows of the chosen term's actual output network. -/
+noncomputable def outputOrder (v : SelectedLevel B f hf) :
+ Order (v.pass.step.term v.term).output.Site :=
+ (v.pass.output_eq v.term).symm ▸ siteOrder (v.pass.next v.term)
+
+/-- The second component is a site in the first component's term output. -/
+abbrev Site (passes : List (SelectedLevel B f hf)) :=
+ Σ j : Fin passes.length, (passes[j].pass.step.term passes[j].term).output.Site
+
+/-- Only occurrences whose recorded kernel is a shrinking pass. -/
+abbrev ShrinkSite (passes : List (SelectedLevel B f hf)) :=
+ {x : Site passes // tagLevel B f hf passes[x.1] = .shrink}
+
+/-- Turn the selected pass sequence into its output DFS layers, retaining the producing role of
+each layer. -/
+noncomputable def outputTags (passes : List (SelectedLevel B f hf)) : List TaggedLayer :=
+ passes.map fun v => ⟨levelLayer B f hf v, tagLevel B f hf v⟩
+
+/-- Numerical ordinals in a physical row are exactly the selected term's site order. -/
+noncomputable def siteRows (passes : List (SelectedLevel B f hf)) :
+ Site passes ≃ OutputRowDirectory.Row (outputTags passes) :=
+ Equiv.sigmaCongr (finCongr (by simp [outputTags])) fun j =>
+ (outputOrder passes[j]).entries.symm.trans <| finCongr <| by
+ simp only [outputTags, Fin.getElem_fin, List.getElem_map]
+ rfl
+
+variable (cap base : ℕ) (leaf : TaggedLayer) (passes : List (SelectedLevel B f hf))
+
+/-- Natural row address in the physical arena for a concrete chosen term and site. -/
+noncomputable def address (x : Site passes) : ℕ :=
+ TraversalRows.address cap (layerBase cap base (leaf :: outputTags passes) (x.1.val + 1))
+ ((outputOrder passes[x.1]).entries.symm x.2).val
+
+private theorem row_address (x : Site passes) :
+ OutputRowDirectory.rowAddress cap base leaf (outputTags passes) (siteRows passes x) =
+ address cap base leaf passes x := rfl
+
+/-- Row addresses distinguish both the selected term occurrence and its output site. -/
+theorem address_injective : Function.Injective (address cap base leaf passes) := by
+ intro x y h
+ apply (siteRows passes).injective
+ apply OutputRowDirectory.rowAddress_injective cap base leaf (outputTags passes)
+ rwa [row_address, row_address]
+
+private def asShrink (x : Site passes) : Option (ShrinkSite passes) :=
+ if h : tagLevel B f hf passes[x.1] = .shrink then some ⟨x, h⟩ else none
+
+private theorem asShrink_eq_some_iff (x : Site passes) (s : ShrinkSite passes) :
+ asShrink passes x = some s ↔ x = s.val := by
+ unfold asShrink
+ split
+ · rw [Option.some.injEq, Subtype.ext_iff]
+ · rename_i h
+ simp only [reduceCtorEq, false_iff]
+ exact fun e => h (e ▸ s.property)
+
+variable {w endAddr : ℕ}
+
+/-- Recover the shrink site from the physical node word. The decoder rejects
+cursor rows, refresh rows, interiors of rows and addresses outside the row arena. -/
+noncomputable def decode (node : Word w) : Option (ShrinkSite passes) :=
+ (OutputRowDirectory.decode cap base leaf (outputTags passes) node).bind fun row =>
+ asShrink passes ((siteRows passes).symm row)
+
+/-- Successful decoding is equivalent to equality with the actual natural row address. -/
+theorem decode_eq_some_iff
+ (fit : layerBase cap base (leaf :: outputTags passes) (passes.length + 1) ≤ 2 ^ w)
+ (node : Word w) (x : ShrinkSite passes) :
+ decode cap base leaf passes node = some x ↔ node.val = address cap base leaf passes x.val := by
+ have fits : layerBase cap base (leaf :: outputTags passes) ((outputTags passes).length + 1) ≤
+ 2 ^ w := by simpa only [outputTags, List.length_map] using fit
+ rw [decode, Option.bind_eq_some_iff]
+ constructor
+ · rintro ⟨row, located, shrink⟩
+ have he := (asShrink_eq_some_iff passes _ x).mp shrink
+ have er : row = siteRows passes x.val := by rw [← he, Equiv.apply_symm_apply]
+ rw [er] at located
+ have e := (OutputRowDirectory.decode_eq_some_iff cap base leaf (outputTags passes) fits
+ node (siteRows passes x.val)).mp located
+ exact e.trans (row_address cap base leaf passes x.val)
+ · intro ha
+ refine ⟨siteRows passes x.val, ?_, ?_⟩
+ · apply (OutputRowDirectory.decode_eq_some_iff cap base leaf (outputTags passes) fits
+ node (siteRows passes x.val)).mpr
+ exact ha.trans (row_address cap base leaf passes x.val).symm
+ · apply (asShrink_eq_some_iff passes _ _).mpr
+ exact Equiv.symm_apply_apply _ _
+
+/-- The physical word of each valid shrink row round-trips to its typed site.
+The end may equal the word modulus because the allocated interval is half-open. -/
+theorem decode_address
+ (fit : layerBase cap base (leaf :: outputTags passes) (passes.length + 1) ≤ 2 ^ w)
+ (x : ShrinkSite passes) :
+ decode cap base leaf passes (address cap base leaf passes x.val : Word w) = some x := by
+ apply (decode_eq_some_iff cap base leaf passes fit _ x).mpr
+ rw [Fin.val_natCast]
+ apply Nat.mod_eq_of_lt
+ have below := OutputRowDirectory.rowAddress_lt_end cap base leaf (outputTags passes)
+ (siteRows passes x.val)
+ rw [row_address] at below
+ exact below.trans_le (by simpa only [outputTags, List.length_map] using fit)
+
+/-- Select the parser for the actual shrinking site without passing any
+level or owner as an additional input to the hook. -/
+noncomputable def parser (readers : ShrinkSite passes → HookParser w endAddr) :
+ HookParser w endAddr where
+ read node saved bs := (decode cap base leaf passes node).bind fun x =>
+ (readers x).read node saved bs
+
+/-- The global reader returns exactly the local path and remaining bits
+for the unique chosen site. This also identifies local and global rejection. -/
+theorem read_at (readers : ShrinkSite passes → HookParser w endAddr)
+ (fit : layerBase cap base (leaf :: outputTags passes) (passes.length + 1) ≤ 2 ^ w)
+ (node : Word w) (x : ShrinkSite passes) (ha : node.val = address cap base leaf passes x.val)
+ (saved : Scratch w endAddr) (bs : List Bool) :
+ (parser cap base leaf passes readers).read node saved bs = (readers x).read node saved bs := by
+ simp only [parser, (decode_eq_some_iff cap base leaf passes fit node x).mpr ha, Option.bind_some]
+
+/-- Geometry and packet contents may vary with the selected output site. -/
+def Domain (ready : ShrinkSite passes → Scratch w endAddr → Prop)
+ (node : Word w) (saved : Scratch w endAddr) : Prop :=
+ ∃ x : ShrinkSite passes, node.val = address cap base leaf passes x.val ∧ ready x saved
+
+/-- The dispatcher's actual tag probe selects the recorded role of this site. -/
+theorem dispatch_at_site {m : Memory w} {offset : ℕ}
+ (published : TraversalRoles.Reads w m offset cap base (leaf :: outputTags passes))
+ (codes : 2 < 2 ^ w) (fit : offset + base + tagWords cap (leaf :: outputTags passes) ≤ 2 ^ w)
+ (node : Word w) (x : Site passes) (ha : node.val = address cap base leaf passes x) :
+ NodeDispatch.role (m ((offset : Word w) + node).val) =
+ (tagLevel B f hf passes[x.1]).dispatch := by
+ let outputs := outputTags passes
+ let row := siteRows passes x
+ let j : Fin (leaf :: outputs).length := row.1.succ
+ let id : Fin (leaf :: outputs)[j].layer.count := row.2
+ have probe := published.dispatch codes fit j id
+ change NodeDispatch.role (m ((offset : Word w) +
+ (OutputRowDirectory.rowAddress cap base leaf (outputTags passes) row : Word w)).val) = _
+ at probe
+ rw [show OutputRowDirectory.rowAddress cap base leaf (outputTags passes) row =
+ address cap base leaf passes x from row_address cap base leaf passes x, ← ha] at probe
+ have role : (leaf :: outputs)[j].role = tagLevel B f hf passes[x.1] := by
+ simp [j, row, siteRows, outputs, outputTags]
+ rfl
+ rw [show (node.val : Word w) = node from Fin.ext (Nat.mod_eq_of_lt node.isLt)] at probe
+ exact probe.trans (congrArg Role.dispatch role)
+
+/-- On genuine output rows, the typed shrink domain is the same domain as
+the physical role guard, with the site's packet invariant preserved. -/
+theorem domain_iff_dispatch {m : Memory w} {offset : ℕ}
+ (published : TraversalRoles.Reads w m offset cap base (leaf :: outputTags passes))
+ (codes : 2 < 2 ^ w) (fit : offset + base + tagWords cap (leaf :: outputTags passes) ≤ 2 ^ w)
+ (ready : Site passes → Scratch w endAddr → Prop) (node : Word w) (saved : Scratch w endAddr)
+ (genuine : ∃ x : Site passes, node.val = address cap base leaf passes x ∧ ready x saved) :
+ Domain cap base leaf passes (fun x => ready x.val) node saved ↔
+ NodeDispatch.role (m ((offset : Word w) + node).val) = .shrink := by
+ constructor
+ · rintro ⟨x, ha, _⟩
+ rw [dispatch_at_site cap base leaf passes published codes fit node x.val ha, x.property]
+ rfl
+ · intro role
+ obtain ⟨x, ha, ok⟩ := genuine
+ rw [dispatch_at_site cap base leaf passes published codes fit node x ha] at role
+ have shrink : tagLevel B f hf passes[x.1] = .shrink := by
+ cases h : tagLevel B f hf passes[x.1] <;> simp_all [Role.dispatch]
+ exact ⟨⟨x, shrink⟩, ha, ok⟩
+
+/-- Assemble the genuine per-site native equivalences at their common
+shrink entry and DFS continuation. Success and rejection use the same site. -/
+theorem exactOn {p r k' : ℕ} (M : Machine w p r k') (visit ret : Fin p)
+ (dfs : Fin 9 ↪ Fin r) (m : Memory w)
+ (readers : ShrinkSite passes → HookParser w endAddr)
+ (ready : ShrinkSite passes → Scratch w endAddr → Prop)
+ (fit : layerBase cap base (leaf :: outputTags passes) (passes.length + 1) ≤ 2 ^ w)
+ (localExact : ∀ x : ShrinkSite passes, (readers x).ExactOn
+ (fun node saved => node.val = address cap base leaf passes x.val ∧ ready x saved)
+ M visit ret dfs m) :
+ (parser cap base leaf passes readers).ExactOn
+ (Domain cap base leaf passes ready) M visit ret dfs m := by
+ constructor
+ · intro node saved domain bs job tail got
+ obtain ⟨x, atRow, good⟩ := domain
+ rw [read_at cap base leaf passes readers fit node x atRow] at got
+ exact (localExact x).success node saved ⟨atRow, good⟩ bs job tail got
+ · intro node bs c top pending domain pc current stack ptr h5 h6 one failed
+ obtain ⟨x, atRow, good⟩ := domain
+ rw [read_at cap base leaf passes readers fit node x atRow] at failed
+ exact (localExact x).reject node bs c top pending ⟨atRow, good⟩
+ pc current stack ptr h5 h6 one failed
+
+end PairSimulation.ShrinkRoleDirectory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleExact.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleExact.lean
new file mode 100644
index 0000000000..c55056c00a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleExact.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PairShrinkRoleChild
+import OAI.Computability.VPVNP.PairShrinkRoleHidden
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoopExact
+
+/-!
+# Joining the child, hidden and resident-map stages of a shrinking visit
+
+A directory load before each stage prepares its input registers. The native
+reads pass the exact remaining tape through these loads and through the
+deterministic resident maps. The join accounts for every private-memory write
+and preserves the pending DFS stack on successful returns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM DFS Compression CompressorRecords
+open NodeArguments NodeArguments.ChildScan
+open ShrinkHiddenGuess
+open scoped Fin.CommRing
+
+variable {w endAddr a g p r k : ℕ} {α β : Type*}
+
+variable {X : State a g} (A : Arena) (T : IncidenceDirectory w) (m : Memory w)
+ (older cap : ℕ) (desc : Word w → ChildArguments.Descriptor w X)
+ (args : List (Child X) → Args w) (seed : List (Child X) → List Row)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w endAddr))
+ (loadChild : Setup w endAddr) (loadHidden : List (Child X) → Setup w endAddr)
+ (loadMaps : List (Child X) → List Row → Setup w endAddr)
+
+/-- Trace, scratch and stream decoder for the actual three scans. The
+directory loads receive the values chosen by all preceding stages. -/
+noncomputable def visitReader : Reader w endAddr Unit :=
+ bind loadChild.reader fun _ =>
+ bind (ChildArguments.reader A T m older cap desc) fun xs =>
+ bind (loadHidden xs).reader fun _ =>
+ bind (hiddenReader (args xs) m (seed xs)) fun es =>
+ bind (loadMaps xs es).reader fun _ => ResidentMapLoop.Exact.mapReader (maps xs es)
+
+/-- Exactness of a shrinking visit in the DFS machine. The operand loads
+supply the required register values before each native reader; the resident
+entry callbacks check the selected matrix occurrences on the prepared scratch. -/
+theorem native_exactOn {M : Machine w p r k} {dfs : Fin 9 ↪ Fin r} {visit : Fin p}
+ {domain : Word w → Scratch w endAddr → Prop}
+ {beginChild childInput : Word w → Config w p r → Prop}
+ {afterChild hiddenInput : List (Child X) → Word w → Config w p r → Prop}
+ {afterHidden : List (Child X) → List Row → Word w → Config w p r → Prop}
+ (mapLoop : ResidentMapLoop.Program p r)
+ (mapInv : List (Child X) → List Row → Word w → Config w p r → Prop)
+ (mapBase : List (Child X) → List Row → ℕ)
+ (start : ∀ node c top pending, domain node (scratch endAddr c.privateMem) →
+ Entry dfs endAddr visit node c top pending → beginChild node c)
+ (load₁ : Realizes loadChild.reader M m dfs beginChild (fun _ => childInput))
+ (children : Realizes (endAddr := endAddr) (ChildArguments.reader A T m older cap desc)
+ M m dfs childInput afterChild)
+ (load₂ : ∀ xs, Realizes (loadHidden xs).reader M m dfs
+ (afterChild xs) (fun _ => hiddenInput xs))
+ (hidden : ∀ xs, Realizes (endAddr := endAddr) (hiddenReader (args xs) m (seed xs)) M m dfs
+ (hiddenInput xs) (afterHidden xs))
+ (load₃ : ∀ xs es, Realizes (loadMaps xs es).reader M m dfs (afterHidden xs es)
+ (fun _ => ResidentMapLoop.Exact.Entry mapLoop (mapInv xs es) (mapBase xs es)
+ (maps xs es).length))
+ (linked : mapLoop.Linked M) (stable : ∀ xs es node, mapLoop.Stable (mapInv xs es node))
+ (apart : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → dfs i ≠ mapLoop.cursor)
+ (items : ∀ xs es, ResidentMapLoop.Exact.Items mapLoop M m dfs (mapInv xs es)
+ (mapBase xs es) (maps xs es))
+ (room : ∀ xs es, mapBase xs es + (maps xs es).length < 2 ^ w) :
+ (hook (visitReader A T m older cap desc args seed maps loadChild loadHidden loadMaps)).ExactOn
+ domain M visit mapLoop.done dfs m := by
+ let stages := load₁.bind fun _ => children.bind fun xs => (load₂ xs).bind fun _ =>
+ (hidden xs).bind fun es => (load₃ xs es).bind fun _ =>
+ (ResidentMapLoop.Exact.maps_realizes mapLoop linked (stable xs es) apart (maps xs es)
+ (mapBase xs es) (items xs es) (room xs es)).weakenPost (fun _ _ _ h => h.1)
+ apply stages.exactOn _ start
+ have cs : Splits (endAddr := endAddr) (ChildArguments.reader A T m older cap desc) :=
+ fun _ _ _ _ _ h => ChildArguments.splitBits A T m older cap desc h
+ have hs xs : Splits (endAddr := endAddr) (hiddenReader (args xs) m (seed xs)) :=
+ hiddenReader_split (args xs) m (seed xs)
+ have ms xs es : Splits (ResidentMapLoop.Exact.mapReader (maps xs es)) :=
+ fun _ _ _ _ _ h => ResidentMapLoop.Exact.splitBits (items xs es |>.quiet) h
+ have all := loadChild.splits.bind fun _ => cs.bind fun xs => (loadHidden xs).splits.bind fun _ =>
+ (hs xs).bind fun es => (loadMaps xs es).splits.bind fun _ => ms xs es
+ exact fun node saved bs out rest _ h => all node saved bs out rest h
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleFieldFrame.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleFieldFrame.lean
new file mode 100644
index 0000000000..c710826a0a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleFieldFrame.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.PairShrinkCallFrameStores
+
+/-!
+# Vertex frame, counters and packet cells after both shrinking field stores
+
+The old-child packets lie between the geometry pointer and the histogram. The
+hidden-field slots lie beyond the verifier stacks. Hence the physical memory
+passed to the first map has the original frame and histogram, and reads each
+argument packet exactly as the child batch wrote it.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open BurstRAM DFS NodeArguments LeafSourceLoad VertexImage TreeDecode
+open scoped Fin.CommRing
+open private child_outside from OAI.Computability.VPVNP.PairShrinkCallFrameStores
+
+variable {w n pitch : ℕ} {R : LeafArena.Regions} {priv : Word w → Word w}
+ {qs : List Packet} {es : List ShrinkHiddenGuess.Row}
+local notation "heap" => ShrinkCallABI.hiddenBase R n
+local notation "G" => NativeFrame.frameBase R
+local notation "childMem" => ChildScan.storePackets R.arguments qs priv
+local notation "written" => scratch n (ShrinkHiddenGuess.storeRows heap pitch es childMem)
+
+namespace ShrinkRole
+
+private theorem rawScratch_of_eq {m₁ m₂ : Word w → Word w} (x : Word w) (h : m₁ x = m₂ x) :
+ rawScratch (scratch n m₁) x = rawScratch (scratch n m₂) x := by
+ by_cases live : n ≤ x.val <;> simp [rawScratch, scratch, live, h]
+
+private theorem fields_outside (x : Word w)
+ (room : ∀ e ∈ es, heap + e.1 * pitch + e.2.length ≤ 2 ^ w)
+ (fits : ∀ q ∈ qs, q.Fits R.arguments w n) (below : x.val < heap)
+ (outside : ∀ q ∈ qs, x.val < R.arguments.base q.node ∨
+ R.arguments.base q.node + q.bits.length ≤ x.val) :
+ rawScratch written x = rawScratch (scratch n priv) x := by
+ apply rawScratch_of_eq
+ exact (ShrinkCallFrameLive.hidden_below heap pitch es x room below).trans
+ (child_outside R.arguments qs x (fun q hq ↦ (fits q hq).2.2) outside)
+
+private theorem fields_above_arguments (k : ℕ) (lo : R.histBase ≤ k) (hi : k < heap)
+ (heapFit : heap ≤ 2 ^ w) (room : ∀ e ∈ es, heap + e.1 * pitch + e.2.length ≤ 2 ^ w)
+ (fits : ∀ q ∈ qs, q.Fits R.arguments w n) (nodes : ∀ q ∈ qs, q.node < R.nodes) :
+ rawScratch written (k : Word w) = rawScratch (scratch n priv) (k : Word w) := by
+ have val : (k : Word w).val = k := Nat.mod_eq_of_lt (hi.trans_le heapFit)
+ apply fields_outside (k : Word w) room fits (val.le.trans_lt hi)
+ intro q hq
+ exact .inr ((Nat.add_le_add_left (fits q hq).2.1 _).trans
+ ((R.node_before (nodes q hq)).trans (lo.trans val.ge)))
+
+/-- The physical word of an individual histogram counter survives both readers. -/
+theorem fields_histCell (k : ℕ) (within : k < R.histWords) (heapFit : heap ≤ 2 ^ w)
+ (room : ∀ e ∈ es, heap + e.1 * pitch + e.2.length ≤ 2 ^ w)
+ (fits : ∀ q ∈ qs, q.Fits R.arguments w n) (nodes : ∀ q ∈ qs, q.node < R.nodes) :
+ rawScratch written ((R.histBase + k : ℕ) : Word w) =
+ rawScratch (scratch n priv) ((R.histBase + k : ℕ) : Word w) := by
+ have before := R.hist_before
+ have stack : R.cacheBase + 38 ≤ heap := Nat.le_add_right ..
+ exact fields_above_arguments _ (Nat.le_add_right ..) (by omega) heapFit room fits nodes
+
+/-- Both readers retain the original value of the entire typed histogram. -/
+theorem fields_histogram {Label : Type} (order : Fin R.histWords ≃ Label)
+ (heapFit : heap ≤ 2 ^ w) (room : ∀ e ∈ es, heap + e.1 * pitch + e.2.length ≤ 2 ^ w)
+ (fits : ∀ q ∈ qs, q.Fits R.arguments w n) (nodes : ∀ q ∈ qs, q.node < R.nodes) :
+ privateHistogram order R.histBase written =
+ privateHistogram order R.histBase (scratch n priv) := by
+ funext l
+ exact congrArg Fin.val (fields_histCell _ (order.symm l).isLt heapFit room fits nodes)
+
+/-- Throughout the argument arena the hidden scan leaves the logical child batch intact. -/
+theorem fields_arguments (room : ∀ e ∈ es, heap + e.1 * pitch + e.2.length ≤ 2 ^ w)
+ (a : ℕ) (before : a < R.histBase) :
+ rawScratch written (a : Word w) =
+ rawScratch (writePackets R.arguments qs (scratch n priv)) (a : Word w) := by
+ rw [← ChildScan.scratch_storePackets]
+ apply rawScratch_of_eq
+ apply ShrinkCallFrameLive.hidden_below heap pitch es _ room
+ have hist : R.histBase ≤ R.cacheBase := (Nat.le_add_right ..).trans R.hist_before
+ have stack : R.cacheBase + 38 ≤ heap := Nat.le_add_right ..
+ exact (Nat.mod_le ..).trans_lt (before.trans_le (hist.trans (by omega)))
+
+/-- Every cell of any genuine argument packet, including an older pending sibling,
+reads exactly as it would immediately after the logical child writes. -/
+theorem fields_packet (q : Packet) (realNode : q.node < R.nodes)
+ (width : q.bits.length ≤ R.arguments.stride)
+ (room : ∀ e ∈ es, heap + e.1 * pitch + e.2.length ≤ 2 ^ w) (i : Fin q.bits.length) :
+ rawScratch written ((R.arguments.base q.node + i.val : ℕ) : Word w) =
+ rawScratch (writePackets R.arguments qs (scratch n priv))
+ ((R.arguments.base q.node + i.val : ℕ) : Word w) :=
+ fields_arguments room _ ((Nat.add_lt_add_left (i.isLt.trans_le width) _).trans_le
+ (R.node_before realNode))
+
+end ShrinkRole
+
+/-- Both shrinking readers retain the geometry pointer, all twelve geometry fields,
+and the cached validator operands in the scratch used by the resident map loop. -/
+theorem TreeDecode.VertexFrameData.after_shrink_fields {data : Fin 10 → Word w}
+ {offset : Word w} {vals : Static 34 → Word w}
+ (frame : VertexFrameData R data offset vals (scratch n priv)) (above : n ≤ G)
+ (heapFit : heap ≤ 2 ^ w) (room : ∀ e ∈ es, heap + e.1 * pitch + e.2.length ≤ 2 ^ w)
+ (fits : ∀ q ∈ qs, q.Fits R.arguments w n) (nodes : ∀ q ∈ qs, q.node < R.nodes)
+ (abovePointer : ∀ q ∈ qs, n < R.arguments.base q.node) :
+ VertexFrameData R data offset vals written := by
+ have hist : R.histBase ≤ G := Nat.le_add_right ..
+ have cache : G ≤ R.cacheBase := R.hist_before
+ have stack : R.cacheBase + 38 ≤ heap := Nat.le_add_right ..
+ apply frame.transfer
+ · exact ShrinkRole.fields_outside _ room fits ((Nat.mod_le ..).trans_lt (by omega))
+ (fun q hq ↦ .inl ((Nat.mod_le ..).trans_lt (abovePointer q hq)))
+ · intro j
+ have hi := j.isLt
+ exact ShrinkRole.fields_above_arguments _ (hist.trans (Nat.le_add_right ..)) (by omega)
+ heapFit room fits nodes
+ · intro j
+ have hi : j.offset < 38 := by cases j <;> simp [Static.offset]; omega
+ exact ShrinkRole.fields_above_arguments _ ((hist.trans cache).trans (Nat.le_add_right ..))
+ ((Nat.add_lt_add_left hi _).trans_le stack) heapFit room fits nodes
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleHandoff.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleHandoff.lean
new file mode 100644
index 0000000000..3713797eee
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleHandoff.lean
@@ -0,0 +1,312 @@
+import OAI.Computability.VPVNP.PairNodeChildLoop
+import OAI.Computability.VPVNP.PairSimulationInlineLiteral
+import OAI.Computability.VPVNP.PairSimulationLeafScalarStartup
+
+/-!
+# Hosted operand handoffs from the traversal-level locator
+
+The child header reader needs the popped node and the old level's directory
+fields. Shrink and refresh share this two-copy entry sequence. The hidden
+shrink-field reader additionally needs the selected owner and the private
+buffer in which it stores absorbed fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexLevel
+
+open BurstRAM BurstRAM.PrivateRAM NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r : ℕ}
+
+/-- Copy the located node and its old-level field pointer to the child reader. -/
+def childHandoff (pc : Fin 2 → Fin p) (loc : Fin 14 ↪ Fin r) (child : Fin 16 ↪ Fin r)
+ (next : Fin p) : Fin 2 → Instr w p r 11 :=
+ ![.copy (child 7) (loc 0) (pc 1), .copy (child 8) (loc 12) next]
+
+theorem resize_childHandoff (pc : Fin 2 → Fin p) (loc : Fin 14 ↪ Fin r) (child : Fin 16 ↪ Fin r)
+ (next : Fin p) (i : Fin 2) :
+ (childHandoff (w := 5) pc loc child next i).resize w = childHandoff pc loc child next i := by
+ fin_cases i <;> rfl
+
+/-- Only the two named child registers change. -/
+theorem childHandoff_run {M : Machine w p r 11} {pc : Fin 2 → Fin p} {loc : Fin 14 ↪ Fin r}
+ {child : Fin 16 ↪ Fin r} {next : Fin p}
+ (linked : ∀ i, M.code (pc i) = childHandoff pc loc child next i)
+ (apart : child 7 ≠ loc 12) (c : Config w p r) (hc : c.pc = pc 0) (m : Memory w) :
+ ∃ out, Prefix M m c out [] (List.replicate 2 .tick) ∧ out.pc = next ∧
+ out.reg (child 7) = c.reg (loc 0) ∧ out.reg (child 8) = c.reg (loc 12) ∧
+ (∀ j, j ≠ child 7 → j ≠ child 8 → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let a := c.put (pc 1) (child 7) (c.reg (loc 0))
+ let out := a.put next (child 8) (c.reg (loc 12))
+ have s₀ : M.program.step c = .localStep a := by
+ change (M.code c.pc).run _ _ = _
+ rw [hc, linked]
+ rfl
+ have s₁ : M.program.step a = .localStep out := by
+ change (M.code (pc 1)).run _ _ = _
+ rw [linked]
+ change CallAction.localStep (a.put next (child 8) (a.reg (loc 12))) = _
+ simp [a, out, Config.put, Function.update_of_ne apart.symm]
+ have path : ReadPrefix M m c (List.replicate 2 .tick) out :=
+ ReadPrefix.tick s₀ (ReadPrefix.tick s₁ (ReadPrefix.nil _))
+ exact ⟨out, ReadPrefix.execute path, rfl,
+ by simp [out, a, Config.put], by simp [out, Config.put],
+ fun j h7 h8 => by simp [out, a, Config.put, Function.update_of_ne h7, Function.update_of_ne h8],
+ rfl, rfl⟩
+
+set_option synthInstance.maxSize 10000
+
+@[irreducible] private noncomputable def scalarPorts : ℕ := Fintype.card LeafStartup.ScalarPort
+
+/-- The cache holds 38 words. Each of the scalar stacks following it
+occupies a private interval of capacity `n^40`. -/
+noncomputable def hiddenBaseWord (cache n : Word w) : Word w :=
+ cache + 38 + (scalarPorts : Word w) * n^40
+
+theorem hiddenBaseWord_cast (cache n : ℕ) :
+ hiddenBaseWord (cache : Word w) (n : Word w) =
+ ((cache + 38 + Fintype.card LeafStartup.ScalarPort * n^40 : ℕ) : Word w) := by
+ have cast (t : ℕ) : (cache : Word w) + 38 + (t : Word w) * (n : Word w)^40 =
+ ((cache + 38 + t * n^40 : ℕ) : Word w) := by push_cast; rfl
+ unfold hiddenBaseWord scalarPorts
+ exact cast _
+
+/-- One geometry-pointer load, the existing fixed literal block for the
+number of scalar stacks, and twenty private reads, copies and arithmetic rows. -/
+noncomputable abbrev hiddenCount : ℕ := (scalarPorts + 2 + 20) + 1
+
+theorem hiddenCount_eq : hiddenCount = Fintype.card LeafStartup.ScalarPort + 23 := by
+ unfold hiddenCount scalarPorts
+ rfl
+
+instance : NeZero hiddenCount := ⟨Nat.succ_ne_zero (scalarPorts + 2 + 20)⟩
+
+private def hiddenTailPC {C : ℕ} (pc : Fin ((C + 2 + 20) + 1) → Fin p) (i : Fin 20) :=
+ pc ((i.natAdd (C + 2)).succ)
+
+private def hiddenLiteralPC {C : ℕ} (pc : Fin ((C + 2 + 20) + 1) → Fin p) : Fin (C + 3) → Fin p :=
+ Fin.lastCases (hiddenTailPC pc 0) (fun i => pc (i.castAdd 20).succ)
+
+private def hiddenTail (pc : Fin 20 → Fin p) (loc : Fin 14 ↪ Fin r) (i : Fin 6 ↪ Fin r)
+ (next : Fin p) : Fin 20 → Instr w p r 11 :=
+ ![.constant (i 5) 9 (pc 1),
+ .binary .add (i 2) (i 1) (i 5) (pc 2),
+ .loadPrivate (i 2) (i 2) (pc 3),
+ .binary .mul (i 5) (i 2) (i 2) (pc 4),
+ .binary .mul (i 5) (i 5) (i 5) (pc 5),
+ .binary .mul (i 5) (i 5) (i 2) (pc 6),
+ .binary .mul (i 5) (i 5) (i 5) (pc 7),
+ .binary .mul (i 5) (i 5) (i 5) (pc 8),
+ .binary .mul (i 5) (i 5) (i 5) (pc 9),
+ .binary .mul (i 0) (i 0) (i 5) (pc 10),
+ .binary .mul (i 2) (i 2) (i 2) (pc 11),
+ .constant (i 5) 8 (pc 12),
+ .binary .add (i 1) (i 1) (i 5) (pc 13),
+ .loadPrivate (i 1) (i 1) (pc 14),
+ .constant (i 5) 19 (pc 15),
+ .binary .add (i 5) (i 5) (i 5) (pc 16),
+ .binary .add (i 1) (i 1) (i 5) (pc 17),
+ .binary .add (i 1) (i 1) (i 0) (pc 18),
+ .copy (i 0) (loc 7) (pc 19),
+ .copy (i 5) (loc 11) next]
+
+/-- Read the geometry pointer first, even if the caller's pointer register
+overlaps a destination. Synthesize the scalar-port count using the shared
+zero-and-one literal routine before computing the first transient address. -/
+noncomputable def hiddenHandoff (pc : Fin hiddenCount → Fin p) (loc : Fin 14 ↪ Fin r)
+ (inputs : Fin 6 ↪ Fin r) (stackEnd : Fin r) (next : Fin p) : Fin hiddenCount → Instr w p r 11 :=
+ Fin.cases (n := scalarPorts + 2 + 20)
+ (.loadPrivate (inputs 1) stackEnd (hiddenLiteralPC (C := scalarPorts) pc 0))
+ (Fin.addCases (m := scalarPorts + 2) (n := 20) (motive := fun _ => Instr w p r 11)
+ (InlinePublic.literalInstruction w scalarPorts scalarPorts
+ (hiddenLiteralPC (C := scalarPorts) pc) (inputs 5) (inputs 0))
+ (hiddenTail (hiddenTailPC (C := scalarPorts) pc) loc inputs next))
+
+theorem resize_hiddenHandoff (pc : Fin hiddenCount → Fin p) (loc : Fin 14 ↪ Fin r)
+ (inputs : Fin 6 ↪ Fin r) (stackEnd : Fin r) (next : Fin p) (i : Fin hiddenCount) :
+ (hiddenHandoff (w := 5) pc loc inputs stackEnd next i).resize w =
+ hiddenHandoff pc loc inputs stackEnd next i := by
+ refine Fin.cases rfl (fun j => ?_) i
+ refine Fin.addCases (m := scalarPorts + 2) (n := 20) (fun k => ?_) (fun k => ?_) j
+ · simp only [hiddenHandoff, Fin.cases_succ, Fin.addCases_left, InlinePublic.literalInstruction]
+ split_ifs <;> rfl
+ · simp only [hiddenHandoff, Fin.cases_succ, Fin.addCases_right]
+ fin_cases k <;> rfl
+
+set_option maxHeartbeats 2000000 in
+-- Simplifying the twenty register updates expands a nested bank of word operations.
+private theorem hiddenTail_run {M : Machine w p r 11} {pc : Fin 20 → Fin p}
+ {loc : Fin 14 ↪ Fin r} {inputs : Fin 6 ↪ Fin r} {next : Fin p}
+ (linked : ∀ i, M.code (pc i) = hiddenTail pc loc inputs next i)
+ (apart : ∀ i j, inputs i ≠ loc j) (c : Config w p r) (hc : c.pc = pc 0)
+ (C : ℕ) (ports : c.reg (inputs 0) = (C : Word w)) :
+ let G := c.reg (inputs 1)
+ let n := c.privateMem (G + 9)
+ let cache := c.privateMem (G + 8)
+ ∃ out, PrimedCounter.GuessWord.Prefix M c (List.replicate 20 .tick) out ∧ out.pc = next ∧
+ out.reg (inputs 0) = c.reg (loc 7) ∧ out.reg (inputs 1) = cache + 38 + (C : Word w) * n^40 ∧
+ out.reg (inputs 2) = n*n ∧ out.reg (inputs 5) = c.reg (loc 11) ∧
+ (∀ j, j ≠ inputs 0 → j ≠ inputs 1 → j ≠ inputs 2 → j ≠ inputs 5 → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ intro G n cache
+ let c1 := c.put (pc 1) (inputs 5) (9)
+ let c2 := c1.put (pc 2) (inputs 2) (G + 9)
+ let c3 := c2.put (pc 3) (inputs 2) (n)
+ let c4 := c3.put (pc 4) (inputs 5) (n^2)
+ let c5 := c4.put (pc 5) (inputs 5) (n^4)
+ let c6 := c5.put (pc 6) (inputs 5) (n^5)
+ let c7 := c6.put (pc 7) (inputs 5) (n^10)
+ let c8 := c7.put (pc 8) (inputs 5) (n^20)
+ let c9 := c8.put (pc 9) (inputs 5) (n^40)
+ let c10 := c9.put (pc 10) (inputs 0) ((C : Word w) * n^40)
+ let c11 := c10.put (pc 11) (inputs 2) (n*n)
+ let c12 := c11.put (pc 12) (inputs 5) (8)
+ let c13 := c12.put (pc 13) (inputs 1) (G+8)
+ let c14 := c13.put (pc 14) (inputs 1) (cache)
+ let c15 := c14.put (pc 15) (inputs 5) (19)
+ let c16 := c15.put (pc 16) (inputs 5) (38)
+ let c17 := c16.put (pc 17) (inputs 1) (cache+38)
+ let c18 := c17.put (pc 18) (inputs 1) (cache+38+(C : Word w)*n^40)
+ let c19 := c18.put (pc 19) (inputs 0) (c.reg (loc 7))
+ let c20 := c19.put next (inputs 5) (c.reg (loc 11))
+ have step (i : Fin 20) (d : Config w p r) (hd : d.pc = pc i) {act}
+ (row : (hiddenTail pc loc inputs next i).run M.publicData d = act) :
+ M.program.step d = act := by
+ change (M.code d.pc).run _ _ = _
+ rw [hd, linked]
+ exact row
+ have path : PrimedCounter.GuessWord.Prefix M c (List.replicate 20 .tick) c20 := by
+ refine .tick (next := c1) (step 0 c hc ?_) <|
+ .tick (next := c2) (step 1 c1 rfl ?_) <|
+ .tick (next := c3) (step 2 c2 rfl ?_) <|
+ .tick (next := c4) (step 3 c3 rfl ?_) <|
+ .tick (next := c5) (step 4 c4 rfl ?_) <|
+ .tick (next := c6) (step 5 c5 rfl ?_) <|
+ .tick (next := c7) (step 6 c6 rfl ?_) <|
+ .tick (next := c8) (step 7 c7 rfl ?_) <|
+ .tick (next := c9) (step 8 c8 rfl ?_) <|
+ .tick (next := c10) (step 9 c9 rfl ?_) <|
+ .tick (next := c11) (step 10 c10 rfl ?_) <|
+ .tick (next := c12) (step 11 c11 rfl ?_) <|
+ .tick (next := c13) (step 12 c12 rfl ?_) <|
+ .tick (next := c14) (step 13 c13 rfl ?_) <|
+ .tick (next := c15) (step 14 c14 rfl ?_) <|
+ .tick (next := c16) (step 15 c15 rfl ?_) <|
+ .tick (next := c17) (step 16 c16 rfl ?_) <|
+ .tick (next := c18) (step 17 c17 rfl ?_) <|
+ .tick (next := c19) (step 18 c18 rfl ?_) <|
+ .tick (next := c20) (step 19 c19 rfl ?_) <|
+ .nil _
+ all_goals simp (config := { zetaDelta := true, decide := true })
+ [hiddenTail, Instr.run, Config.put, BinaryOp.eval, Function.update_of_ne (apart _ _).symm,
+ ports]
+ all_goals congr 2 <;> ring
+ refine ⟨c20, path, rfl, ?_, ?_, ?_, ?_, ?_, rfl, rfl⟩
+ all_goals first | intro j h0 h1 h2 h5 | skip
+ all_goals simp (config := { zetaDelta := true, decide := true })
+ [Config.put, Function.update_of_ne, *]
+
+/-- The owner and old level come from the locator. The hidden-field array
+starts immediately above the geometry's operand cache and all leaf scalar
+stacks, and its individual slots have stride `n*n`. -/
+theorem hiddenHandoff_run {M : Machine w p r 11} {pc : Fin hiddenCount → Fin p}
+ {loc : Fin 14 ↪ Fin r} {inputs : Fin 6 ↪ Fin r} {stackEnd : Fin r} {next : Fin p}
+ (linked : ∀ i, M.code (pc i) = hiddenHandoff pc loc inputs stackEnd next i)
+ (apart : ∀ i j, inputs i ≠ loc j) (c : Config w p r) (hc : c.pc = pc 0) (m : Memory w) :
+ let G := c.privateMem (c.reg stackEnd)
+ let n := c.privateMem (G + 9)
+ ∃ out, Prefix M m c out [] (List.replicate hiddenCount .tick) ∧ out.pc = next ∧
+ out.reg (inputs 0) = c.reg (loc 7) ∧
+ out.reg (inputs 1) = hiddenBaseWord (c.privateMem (G + 8)) n ∧
+ out.reg (inputs 2) = n * n ∧ out.reg (inputs 5) = c.reg (loc 11) ∧
+ (∀ j, j ≠ inputs 0 → j ≠ inputs 1 → j ≠ inputs 2 → j ≠ inputs 5 → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ intro G n
+ let a := c.put (hiddenLiteralPC (C := scalarPorts) pc 0) (inputs 1) G
+ have first : M.program.step c = .localStep a := by
+ change (M.code c.pc).run _ _ = _
+ rw [hc, linked]
+ rfl
+ have lit (i : Fin (scalarPorts + 2)) : M.code (hiddenLiteralPC (C := scalarPorts) pc i.castSucc) =
+ InlinePublic.literalInstruction w scalarPorts scalarPorts
+ (hiddenLiteralPC (C := scalarPorts) pc) (inputs 5) (inputs 0) i := by
+ simp only [hiddenLiteralPC, Fin.lastCases_castSucc]
+ rw [linked]
+ simp only [hiddenHandoff, Fin.cases_succ, Fin.addCases_left, hiddenLiteralPC]
+ obtain ⟨mid, litPath, atEnd, ports, keep, mem, pers⟩ :=
+ InlinePublic.literal_prefix (inputs.injective.ne (by decide)) le_rfl lit a rfl
+ simp only [hiddenLiteralPC, Fin.lastCases_last] at atEnd
+ have tail (i : Fin 20) : M.code (hiddenTailPC (C := scalarPorts) pc i) =
+ hiddenTail (hiddenTailPC (C := scalarPorts) pc) loc inputs next i := by
+ simp only [hiddenTailPC]
+ rw [linked]
+ simp only [hiddenHandoff, Fin.cases_succ, Fin.addCases_right]
+ obtain ⟨out, tailPath, done, owner, base, stride, level, keepTail, tailMem, tailPers⟩ :=
+ hiddenTail_run tail apart mid atEnd scalarPorts ports
+ have trace := (PrimedCounter.GuessWord.Prefix.tick first litPath).append tailPath
+ have path : PrimedCounter.GuessWord.Prefix M c (List.replicate hiddenCount .tick) out := by
+ simpa only [← List.replicate_succ, ← List.replicate_add, hiddenCount, Nat.succ_add] using trace
+ have quiet (k : ℕ) : choiceBits (List.replicate k (.tick : Event w)) = [] := by
+ induction k with | zero => rfl | succ k ih => simpa [List.replicate_succ, choiceBits] using ih
+ have geom : mid.reg (inputs 1) = G := by
+ rw [keep _ (inputs.injective.ne (by decide)) (inputs.injective.ne (by decide))]
+ simp [a]
+ have located (j : Fin 14) : mid.reg (loc j) = c.reg (loc j) := by
+ rw [keep _ (apart _ _).symm (apart _ _).symm]
+ simp [a, Config.put, Function.update_of_ne (apart _ _).symm]
+ have hm : mid.privateMem = c.privateMem := mem
+ refine ⟨out, fun f bs => by simpa only [quiet] using path.execute f m bs, done,
+ owner.trans (located 7), ?_, ?_, level.trans (located 11), ?_, tailMem.trans hm,
+ tailPers.trans pers⟩
+ · simpa only [hiddenBaseWord, geom, hm] using base
+ · simpa only [geom, hm] using stride
+ · intro j h0 h1 h2 h5
+ rw [keepTail _ h0 h1 h2 h5, keep _ h5 h0]
+ exact Function.update_of_ne h1 ..
+
+/-- Save the hidden-field base in locator register eight for the map that
+follows the absorbed-field scan. The extra copy takes exactly one tick. -/
+theorem cachedHiddenHandoff_run {M : Machine w p r 11} {pc : Fin (hiddenCount + 1) → Fin p}
+ {loc : Fin 14 ↪ Fin r} {inputs : Fin 6 ↪ Fin r} {stackEnd : Fin r} {next : Fin p}
+ (linked : ∀ i, M.code (pc i.castSucc) =
+ hiddenHandoff (pc ∘ Fin.castSucc) loc inputs stackEnd (pc (Fin.last hiddenCount)) i)
+ (cacheRow : M.code (pc (Fin.last hiddenCount)) = .copy (loc 8) (inputs 1) next)
+ (apart : ∀ i j, inputs i ≠ loc j) (c : Config w p r) (hc : c.pc = pc 0) (m : Memory w) :
+ let G := c.privateMem (c.reg stackEnd)
+ let n := c.privateMem (G + 9)
+ ∃ out, Prefix M m c out [] (List.replicate (hiddenCount + 1) .tick) ∧ out.pc = next ∧
+ out.reg (inputs 0) = c.reg (loc 7) ∧
+ out.reg (inputs 1) = hiddenBaseWord (c.privateMem (G + 8)) n ∧
+ out.reg (inputs 2) = n * n ∧ out.reg (inputs 5) = c.reg (loc 11) ∧
+ out.reg (loc 8) = out.reg (inputs 1) ∧
+ (∀ j, j ≠ loc 8 → j ≠ inputs 0 → j ≠ inputs 1 → j ≠ inputs 2 → j ≠ inputs 5 →
+ out.reg j = c.reg j) ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ intro G n
+ obtain ⟨mid, first, atCopy, owner, base, stride, level, frame, mem, pers⟩ :=
+ hiddenHandoff_run (pc := pc ∘ Fin.castSucc) linked apart c hc m
+ let out := mid.put next (loc 8) (mid.reg (inputs 1))
+ have step : M.program.step mid = .localStep out := by
+ change (M.code mid.pc).run _ _ = _
+ rw [atCopy, cacheRow]
+ rfl
+ have last : Prefix M m mid out [] [.tick] :=
+ ReadPrefix.execute (ReadPrefix.tick step (ReadPrefix.nil _))
+ have keep (j : Fin r) (h : j ≠ loc 8) : out.reg j = mid.reg j := Function.update_of_ne h ..
+ refine ⟨out, ?_, rfl, (keep _ (apart 0 8)).trans owner, (keep _ (apart 1 8)).trans base,
+ (keep _ (apart 2 8)).trans stride, (keep _ (apart 5 8)).trans level, ?_,
+ fun j h8 h0 h1 h2 h5 => (keep j h8).trans (frame j h0 h1 h2 h5), mem, pers⟩
+ · simpa only [List.nil_append, List.replicate_succ'] using first.trans last
+ · exact (Config.put_same ..).trans (keep _ (apart 1 8)).symm
+
+end PairSimulation.VertexLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleHeaderSetup.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleHeaderSetup.lean
new file mode 100644
index 0000000000..7cc30e2daf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleHeaderSetup.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenHeaderTrace
+import OAI.Computability.VPVNP.PairShrinkHiddenSegmentRun
+
+/-! # Exact DFS stage for the hosted hidden-field header compiler -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM ShrinkHiddenGuess
+open private no_choices from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+open scoped Fin.CommRing
+
+variable {w p r endAddr : ℕ}
+
+/-- The hosted header loads the five published fields and changes only registers. -/
+def hiddenHeader (s t oldHead : ℕ) (m : Memory w) : Setup w endAddr where
+ trace _ _ := Header.canonicalTrace s t (oldHead : Word w) m
+ updated _ saved := saved
+ quiet _ _ := no_choices ..
+
+/-- Link the actual installed header at its segment entry to the hidden guess
+loop. The scratch and trace hold uniformly for every eligible configuration. -/
+theorem hiddenHeader_realizes {M : Machine w p r 11} {m : Memory w}
+ (s t : ℕ) (pc : Fin (Table.segmentCount s t) → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (prv : Fin (Table.R s t) ↪ Fin r) (ret : Fin p)
+ (rows : ∀ i, M.code (pc i) = ((Table.segment s t).row pc dfs saved prv ret i).resize w)
+ (g : Args w) (oldHead : ℕ) (selectors : g.selectorBits = (s : Word w))
+ (stride : g.rowStride = t) (fit : oldHead + 38 < 2 ^ w)
+ (headers : Header.Published g oldHead m)
+ (separate : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 →
+ dfs i ∉ Set.range ((Table.vm s t).trans prv))
+ {pre post : Word w → Config w p r → Prop}
+ (start : ∀ node c, pre node c → c.pc = pc (Table.segment s t).entry ∧
+ Table.SegmentOperands s t prv g oldHead c)
+ (resume : ∀ node c d, pre node c → d.pc = Table.segmentLoop s t pc (.inl .one) →
+ Inputs g ((Table.regs s t).trans prv) d → d.privateMem = c.privateMem →
+ d.persistent = c.persistent →
+ (∀ i, i ∉ Set.range ((Table.vm s t).trans prv) → d.reg i = c.reg i) → post node d) :
+ Realizes (hiddenHeader (endAddr := endAddr) s t oldHead m).reader M m dfs pre
+ (fun _ => post) := by
+ apply Setup.realizes
+ intro node c hc
+ obtain ⟨ep,operands⟩ := start node c hc
+ obtain ⟨d,path,entry,inputs,mem,pers,keep,_⟩ :=
+ Table.segment_prepare_raw M pc dfs saved prv ret rows g m oldHead c ep operands
+ selectors stride fit headers
+ rw [Header.trace_canonical s t _ _ c m _ operands.level] at path
+ exact ⟨d, resume node c d hc entry inputs mem pers keep,
+ ⟨fun i hi => keep _ (separate i hi), fun addr _ => congrFun mem addr, pers⟩,
+ congrArg (DFS.scratch endAddr) mem, path⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleHidden.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleHidden.lean
new file mode 100644
index 0000000000..fee7b435f4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleHidden.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.PairShrinkRoleStages
+import OAI.Computability.VPVNP.PairNodeChildStage
+import OAI.Computability.VPVNP.PairShrinkHiddenDecode
+import OAI.Computability.VPVNP.PairShrinkHiddenCost
+
+/-!
+# The hidden-field stage of a shrinking vertex
+
+The native directory gives an ID and width for each absorbed field at the
+vertex. A full prefix supplies exactly those fields and updates their scratch
+cells. A stream ending in any one of the fields rejects.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+open scoped Fin.CommRing
+
+variable {w endAddr p r k : ℕ} {M : Machine w p r k} {pc : Stage → Fin p}
+ {reg : Fin 22 ↪ Fin r} {done : Fin p}
+
+private def packets (es : List Row) : List Packet := es.map fun e => ⟨e.1,e.2⟩
+
+private theorem stored (g : Args w) (es : List Row) (priv : Word w → Word w) :
+ storeRows g.scratchBase g.slotStride es priv =
+ storePackets ⟨g.scratchBase,g.slotStride⟩ (packets es) priv := by
+ simp only [storeRows, storePackets, packets, List.foldl_map, Arena.base]
+
+/-- The parsed rows use the dense hidden ID as the slot number in scratch. -/
+def hiddenReader (g : Args w) (m : Memory w) (seed : List Row) :
+ Reader w endAddr (List Row) := fun _ saved bs =>
+ if (stream seed).length ≤ bs.length then
+ let (es,tail) := decode seed bs
+ some (⟨es, events g m es,
+ writePackets ⟨g.scratchBase,g.slotStride⟩ (packets es) saved⟩,tail)
+ else none
+
+private theorem decoded_split (seed : List Row) (bs : List Bool) :
+ stream (decode seed bs).1 ++ (decode seed bs).2 = bs := by
+ induction seed generalizing bs with
+ | nil => rfl
+ | cons e seed ih =>
+ simp only [decode, stream, List.flatMap_cons, List.append_assoc]
+ rw [← stream, ih, List.take_append_drop]
+
+theorem hiddenReader_split (g : Args w) (m : Memory w) (seed : List Row)
+ (node : Word w) (saved : DFS.Scratch w endAddr) (bs out tail)
+ (read : hiddenReader g m seed node saved bs = some (out, tail)) :
+ bs = choiceBits out.trace ++ tail := by
+ unfold hiddenReader at read
+ split at read
+ · obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj read)
+ rw [(cost g m _).2.2]
+ exact (decoded_split seed bs).symm
+ · contradiction
+
+/-- Registers outside the hidden-field loop's writes retain their values. -/
+def HiddenPreserved (reg : Fin 22 ↪ Fin r) (q : Fin r) : Prop :=
+ q ≠ reg 3 ∧ q ≠ reg 21 ∧ ∀ j ∈ ShrinkHiddenGuess.scratch, q ≠ reg j
+
+/-- Run the actual instruction table on the decoded fields. The scratch
+update is computed from the entry scratch, even if other cells in the full
+private memory differ. -/
+theorem hidden_realizes (link : ShrinkHiddenGuess.Linked M pc reg done)
+ (g : Args w) (m : Memory w) (seed : List Row) (dfs : Fin 9 ↪ Fin r)
+ (pre : Word w → Config w p r → Prop) (post : List Row → Word w → Config w p r → Prop)
+ (entry : ∀ node c, pre node c → c.pc = pc (.inl .one) ∧ Inputs g reg c)
+ (fit : g.countBase + g.owner < 2 ^ w) (count : (m (g.countBase + g.owner)).val = seed.length)
+ (valid : ValidRows g m seed) (above : endAddr ≤ g.scratchBase)
+ (apart : ∀ i, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → HiddenPreserved reg (dfs i))
+ (resume : ∀ node c es d, pre node c → ValidRows g m es → d.pc = done →
+ d.privateMem = storeRows g.scratchBase g.slotStride es c.privateMem →
+ d.persistent = c.persistent → (∀ q, HiddenPreserved reg q → d.reg q = c.reg q) →
+ post es node d) :
+ Realizes (hiddenReader (endAddr := endAddr) g m seed) M m dfs pre post := by
+ constructor
+ · intro node c bs out tail hc read
+ have splitBits := hiddenReader_split g m seed node _ bs out tail read
+ unfold hiddenReader at read
+ split at read
+ · rename_i enough
+ let es := (decode seed bs).1
+ obtain ⟨len,_,rows⟩ := decode_valid g m seed valid bs enough
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj read)
+ obtain ⟨ep,inputs⟩ := entry _ _ hc
+ obtain ⟨d,path,donePC,keep,mem,pers⟩ :=
+ ShrinkHiddenGuess.native link g m es c ep inputs fit (count.trans len.symm) rows
+ have frameReg (q) (h : HiddenPreserved reg q) := keep q h.1 h.2.1 h.2.2
+ refine ⟨splitBits,d,resume node c es d hc rows donePC mem pers frameReg,?_,?_,?_⟩
+ · refine ⟨fun i hi => frameReg _ (apart i hi), ?_, pers⟩
+ intro a ha
+ rw [mem]
+ have low {xs : List Row}
+ (ends : ∀ e ∈ xs, g.slot e.1 + e.2.length ≤ 2 ^ w) (priv : Word w → Word w) :
+ storeRows g.scratchBase g.slotStride xs priv a = priv a := by
+ induction xs generalizing priv with
+ | nil => rfl
+ | cons e xs ih =>
+ apply (ih (fun e he => ends e (List.mem_cons_of_mem _ he)) _).trans
+ exact PrivateFields.storeBits_outside _ _ _ a (ends e List.mem_cons_self)
+ (Or.inl (ha.trans_le (above.trans (Nat.le_add_right ..))))
+ apply low
+ intro e he
+ obtain ⟨i,hi,eqn⟩ := List.mem_iff_getElem.mp he
+ exact eqn ▸ (rows ⟨i,hi⟩).2.2.le
+ · rw [mem, stored, scratch_storePackets]
+ · change Prefix M m c d (choiceBits (events g m es)) (events g m es)
+ rwa [(cost g m es).2.2]
+ · contradiction
+ · intro node c bs hc reject
+ by_cases enough : (stream seed).length ≤ bs.length
+ · simp [hiddenReader, enough] at reject
+ · obtain ⟨ep,inputs⟩ := entry _ _ hc
+ exact native_short link g m seed c ep inputs fit count valid bs (Nat.lt_of_not_ge enough)
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleHiddenCapacity.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleHiddenCapacity.lean
new file mode 100644
index 0000000000..88c76842d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleHiddenCapacity.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.PairShrinkRolePackedHidden
+import OAI.Computability.VPVNP.PairShrinkPackedCapacity
+
+/-!
+# Uniform capacity of the hidden fields at the selected shrinking sites
+
+The packed directory and the post-stack reservation suffice for the actual
+zero seed at every output site, for all selected branches beyond one length
+threshold. No field values or coefficient assignments enter the threshold.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.PackedHidden
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords DescriptorSpace
+open ShrinkBlockInputs ShrinkHistoryRows ShrinkCallCapacity CursorBounds CursorNetwork
+open TraversalRows Filter LocalHistory
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (u : PairExponents B.growthConstant) (b₀ : ℕ) (hb : max S.laneBits 5 ≤ b₀)
+ {start : ℕ → ℕ} (hs : PolynomiallyBounded start)
+
+local notation "P" => initialPositions b₀
+local notation "T" => blockCount (u.θ : ℝ)
+local notation "degree" => slotDegree S
+
+include hs hb in
+/-- All header, term, count, row and private-slot facts for any chosen shrinking
+occurrence and any of its packed sites. -/
+theorem eventually_hidden :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b₀ n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b₀ n)
+ (hT : T n * S.laneBits ≤ lanes) (A : Type*) [CommRing A]
+ (f : B.Entry → A) (hf : B.IsSolution f),
+ let initial := pairInput S labels hD
+ let firstRow := endAddress (BlockProgram.layout B (start n) (P n) (T n))
+ let w := wordBits b₀ n
+ ∀ z : (B.execute f hf (T n) hT initial).Choices,
+ let vs := executeLevels B f hf (T n) hT initial z
+ let rows := words B.recordLimit (selectedLayers B f hf (T n) hT initial z)
+ let R := NativeFrame.regions degree n firstRow rows (Fintype.card B.Entry)
+ ∀ (j : Fin vs.length) (i : Fin S.steps) {g : ℕ}
+ (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+ (bs : List Bool), vs[j] = shrinkLevel B f hf i X sel bs →
+ ∀ (word : Word w) (m : Memory w),
+ CompiledResident.ShrinkPayload B word (P n) (T n) n j.val i X sel m →
+ ∀ v : MapResidentRows.Site X, Facts B i X sel word (P n) (T n) j.val n R v m := by
+ classical
+ have hb₁ : 1 ≤ b₀ := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ filter_upwards [eventually_packed_handoff B u b₀ hb hs,
+ eventually_levels B u b₀ hb (fieldFactor B.shrink),
+ CursorRAM.eventual_word_room b₀ hb₁ (PolynomiallyBounded.const B.shrink.selectorBits),
+ eventually_ge_atTop 1] with n handoff size selectorRoom hn
+ intro base lanes labels hD hT A _ f hf initial firstRow w z vs rows R j i g X sel bs atPass
+ word m payload v
+ obtain ⟨pos, wide⟩ := size labels hD hT A f hf z vs[j] (List.getElem_mem j.isLt)
+ change vs[j].input.positions ≤ P n at pos
+ change fieldFactor B.shrink * (vs[j].input.maxWireWidth + 1) ≤ n at wide
+ rw [atPass] at pos wide
+ have count := motif_count X pos (shrinkLevel B f hf i X sel bs).oldDegree_le
+ have bound := (handoff labels hD hT A f hf z).1
+ apply of_payload B i X sel word (P n) (T n) j.val n R v m payload selectorRoom
+ · intro motif t
+ have h := X.packingData.shrinkTerm_bounds (State.two_le_packingColors _)
+ (Nat.two_pow_pos _) X.shrinkNumber X.packingWidth (fun _ => X.width_le_maxWireWidth _)
+ B.shrink motif (sel motif)
+ exact ((h.2 _).2.trans wide).trans (Nat.le_mul_of_pos_right _ hn)
+ · have occupied : (hiddenOrder X).length * (n * n) ≤ 4 * (P n * degree) * n ^ 2 := by
+ change (ShrinkTermInputs.motifCount X * 4) * (n * n) ≤ _
+ rw [Nat.mul_comm (ShrinkTermInputs.motifCount X) 4, pow_two]
+ exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_left 4 count)
+ apply lt_of_le_of_lt (Nat.add_le_add_left (occupied.trans ?_) _) bound
+ unfold extent
+ omega
+
+end PairSimulation.ShrinkRole.PackedHidden
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleHiddenTyped.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleHiddenTyped.lean
new file mode 100644
index 0000000000..e5840e1678
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleHiddenTyped.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.PairShrinkRoleHidden
+import OAI.Computability.VPVNP.PairShrinkHiddenTypedDecode
+
+/-!
+# The hidden-stage reader on the actual owned half-wires
+
+The native hidden directory keeps the same IDs and field lengths for every
+assignment at a fixed vertex. Reading an arbitrary full tape prefix recovers
+a unique assignment on its owned fields. Reading a specified assignment's
+encoding returns those exact rows and preserves an arbitrary suffix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression Compression.ShrinkMotif NetworkKernel CompressorRecords
+open ShrinkHiddenSlots ShrinkHiddenGuess
+
+variable {a g w endAddr : ℕ} (X : State a (packingLaneBits a g)) (layout : Bool)
+ (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (v : (X.Base × BitWord (Shrink.J a)) × BitWord g)
+
+local notation "Hidden" => Placed (X.packingData.shrinkInternalOwner layout)
+ (internalLabel widths layout) v
+local notation "Rows" => ShrinkHiddenSlots.rows X layout widths v
+
+private theorem hiddenLength_eq (a b : Hidden) : (stream (Rows a)).length =
+ (stream (Rows b)).length := by
+ simp only [stream, List.flatMap_def, ShrinkHiddenSlots.rows, List.map_ofFn,
+ List.length_flatten, List.length_ofFn, Function.comp_def]
+
+variable (arg : Args w) (mem : Memory w)
+ (seed : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel widths layout) v)
+
+/-- All accepted raw rows at a selected vertex determine one and only one
+typed hidden assignment on the consumed prefix. -/
+theorem hiddenReader_typed {node : Word w} {saved : DFS.Scratch w endAddr}
+ {bs tail : List Bool} {out : Outcome w endAddr (List Row)}
+ (hit : hiddenReader arg mem (Rows seed) node saved bs = some (out, tail)) :
+ ∃! h : Hidden, out.value = Rows h ∧ bs = stream (Rows h) ++ tail := by
+ unfold hiddenReader at hit
+ split at hit
+ · rename_i enough
+ obtain ⟨h, decoded, part⟩ := decode_rows X layout widths v seed bs enough
+ rw [decoded] at hit
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj hit)
+ refine ⟨h, ⟨rfl,part⟩, ?_⟩
+ intro h' ok
+ exact (rows_prefix_unique X layout widths v h' h _ _ (ok.2.symm.trans part)).1
+ · contradiction
+
+/-- Starting on a genuine hidden assignment and any continuation returns the
+precise dense-ID rows of that assignment, together with their native stores. -/
+theorem hiddenReader_encoded (h : Hidden) (node : Word w) (saved : DFS.Scratch w endAddr)
+ (tail : List Bool) :
+ ∃ out, hiddenReader arg mem (Rows seed) node saved (stream (Rows h) ++ tail) =
+ some (out, tail) ∧
+ out.value = Rows h := by
+ let bs := stream (Rows h) ++ tail
+ have enough : (stream (Rows seed)).length ≤ bs.length := by
+ rw [hiddenLength_eq X layout widths v seed h]
+ simp [bs]
+ obtain ⟨z, decoded, part⟩ := decode_rows X layout widths v seed bs enough
+ obtain ⟨hz, rest⟩ := rows_prefix_unique X layout widths v h z tail _ part
+ subst z
+ unfold hiddenReader
+ rw [ite_eq_left enough, decoded, ← rest]
+ exact ⟨_, rfl, rfl⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleImageChildren.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleImageChildren.lean
new file mode 100644
index 0000000000..e580dd98d3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleImageChildren.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PairShrinkRoleSelectedEntry
+import OAI.Computability.VPVNP.PairShrinkRoleBankChild
+import OAI.Computability.VPVNP.PairVertexStageChildren
+
+/-!
+# Physical child argument scan in the fixed shrinking image
+
+The selected substep first copies the node and old directory pointer, builds
+its slot-ordinal register bank, and reads the child arguments. Every register
+outside that segment's bank is preserved, including the shared level locator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression CompressorRecords
+open ShrinkVertexImage VertexStagePrefix NodeArguments NodeArguments.ChildScan
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) {t : ℕ}
+ (ord : B.Entry → Fin t) (i : Fin S.steps) {p r w g endAddr : ℕ} (M : Machine w p r 11)
+ (pc : Fin (shrinkSegment B ord).count → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r) (done : Fin p)
+ (installed : ∀ k, M.code (pc k) = ((shrinkSegment B ord).row pc dfs saved reg done k).resize w)
+
+/-- The concrete register embedding for the old-child argument scan within the selected shrink
+stage. -/
+noncomputable abbrev argumentBank :=
+ childBank (afterChildren B ord i).code (afterChildren B ord i).locator (activeBank B ord i reg)
+
+variable (X : State (S.degreeExponent i.castSucc) g)
+ (A : Arena) (T : IncidenceDirectory w) (m : Memory w) (older cap : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w X)
+
+/-- This is the trace of the physical child prefix in a scheduled stage. -/
+noncomputable def imageChildren : Reader w endAddr (List (Child X)) :=
+ bind (Setup.ticks 2).reader fun _ => BankChild.reader A T m older cap desc
+
+include installed in
+/-- Exact local execution, including partial tapes, on the installed child
+code. The inputs are the located words and actual rows, and the continuation
+gets the complete packet writes as a function of its original memory. -/
+theorem imageChildren_realizes
+ (apart : ∀ j : Fin 9, j = 3 ∨ j = 5 ∨ j = 6 ∨ j = 7 →
+ ∀ q, dfs j ≠ argumentBank B ord i reg q)
+ (rep : T.ActualColumns X m) (strideFit : cap + 2 < 2 ^ w)
+ {pre : Word w → Config w p r → Prop} {post : List (Child X) → Word w → Config w p r → Prop}
+ (start : ∀ node c, pre node c → c.pc = activePC B ord i pc (active B ord i).code.entry ∧
+ c.reg (LocatedBody.commonLocator (active B ord) reg 0) = node ∧
+ c.reg (LocatedBody.commonLocator (active B ord) reg 12) = (desc node).directoryBase ∧
+ ChildArguments.Resident A T m older cap endAddr node (desc node))
+ (resume : ∀ node c d xs, pre node c → xs.map Child.site = (desc node).sites →
+ d.pc = afterChildPC B ord i pc (afterChildren B ord i).code.entry →
+ d.persistent = c.persistent →
+ d.privateMem = storePackets A (xs.map (Child.packet X older cap)) c.privateMem →
+ (∀ j, j ∉ Set.range (argumentBank B ord i reg) → d.reg j = c.reg j) → post xs node d) :
+ Realizes (imageChildren (endAddr := endAddr) i X A T m older cap desc) M m dfs pre post := by
+ let prep := childPrep B ord i
+ let place := activePC B ord i pc
+ let localRegs := activeBank B ord i reg
+ let bank := argumentBank B ord i reg
+ let loc := locatorRegs (afterChildren B ord i).code (afterChildren B ord i).locator localRegs
+ let child := ChildCode.RegisterBank.regs bank
+ have loc_eq (j : Fin 14) : loc j = LocatedBody.commonLocator (active B ord) reg j :=
+ active_locator B ord reg i j
+ have code := active_rows B ord M pc dfs saved reg done installed i
+ have hand := (child_rows (oldExponent i) (afterChildren B ord i).code
+ (afterChildren B ord i).locator M place dfs saved localRegs done code).1
+ obtain ⟨_,body,_⟩ := prep.links M place dfs saved localRegs done code
+ let next := prep.phasePC place (ChildCode.RegisterBank.segment (oldExponent i)).entry
+ let mid (node : Word w) (d : Config w p r) := d.pc = next ∧ d.reg (child 7) = node ∧
+ d.reg (child 8) = (desc node).directoryBase ∧
+ ChildArguments.Resident A T m older cap endAddr node (desc node) ∧
+ ∃ c, pre node c ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ j, j ∉ Set.range bank → d.reg j = c.reg j
+ have before : Realizes (Setup.ticks (endAddr := endAddr) 2).reader M m dfs pre
+ (fun _ => mid) := by
+ apply childHandoff_realizes hand
+ · exact Preparation.disjoint localRegs _ _
+ · exact fun j hj => ⟨apart j hj _, apart j hj _⟩
+ · exact fun node c hc => (start node c hc).1
+ · intro node c d hc atNext hn hd keep mem pers
+ obtain ⟨_,hNode,hDir,resident⟩ := start node c hc
+ refine ⟨atNext,hn.trans ((loc_eq 0) ▸ hNode),hd.trans ((loc_eq 12) ▸ hDir),resident,
+ c,hc,mem,pers,?_⟩
+ exact fun j free => keep j (fun h => free ⟨_,h.symm⟩) (fun h => free ⟨_,h.symm⟩)
+ apply before.bind
+ intro _
+ apply BankChild.realizes (prep.phasePC place) saved bank _ body apart rep strideFit
+ · exact fun _ _ h => ⟨h.1,h.2.1,h.2.2.1,h.2.2.2.1⟩
+ · intro node d out xs hd sites exit per mem keep
+ obtain ⟨c,hc,dm,ds,beforeRegs⟩ := hd.2.2.2.2
+ exact resume node c out xs hc sites exit (per.trans ds) (dm ▸ mem)
+ (fun j free => (keep j free).trans (beforeRegs j free))
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleIndexedSuffix.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleIndexedSuffix.lean
new file mode 100644
index 0000000000..c9de570c59
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleIndexedSuffix.lean
@@ -0,0 +1,55 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalSuffix
+import OAI.Computability.VPVNP.PairShrinkSelectedKernelTransport
+
+/-! # The native shrinking suffix at the original selected term -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression CompressorRecords LocalHistory TreeDecode TraversalRoles NodeArguments DFS
+open ShrinkRoleDirectory
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {k : Type} {K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ {B : S.Templates} {f : B.Entry → K} {hf : B.IsSolution f}
+ (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site)
+ (h : tagLevel B f hf v = .shrink) {w n g : ℕ}
+ (p : CanonicalSite B (occurrence v u h).i (occurrence v u h).state
+ (occurrence v u h).selection (occurrence v u h).site w n g)
+ (ord : B.Entry → Fin g) (node : Word w) (saved : Scratch w n)
+ (z : (v.pass.step.term v.term).output.Half u)
+
+local notation "o" => occurrence v u h
+local notation "parser" => (shrinkPassReaders B f hf (o).i rfl (o).state).termParsers (o).selection
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n p.rowEnd
+ (Fintype.card B.Entry)
+
+attribute [local irreducible] originReader shrinkPassReaders nodeReader canonicalParent
+
+set_option maxHeartbeats 1100000 in
+-- The physical half and child order have indices recovered from the selected origin.
+/-- Every tape at the original row has the unread suffix of its selected term reader. -/
+theorem indexedSiteSuffix
+ (stored : (Packet.mk node.val
+ (pullBits (v.pass.output_eq v.term) (packed (v.pass.next v.term)) u z)).Stored
+ (regions).arguments saved)
+ (positive : 0 < w)
+ (orderAt : (p.descriptor node).sites =
+ List.ofFn fun j => (((parser).order.children (o).site).entries j).val)
+ (bits : List Bool) :
+ ((canonicalParent p ord f hf).read node saved bits).map Prod.snd =
+ ((nodeReader (originReader B f hf v.origin v.term) u z).read bits).map Prod.snd := by
+ have parent := halfEquiv_packed v u h z
+ rw [parent] at stored
+ exact (canonicalParent_suffix p ord f hf (halfEquiv v u h z) node saved stored positive orderAt
+ bits).trans (node_suffix v u h z bits).symm
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleIndexedUpdate.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleIndexedUpdate.lean
new file mode 100644
index 0000000000..7cd60fbf6b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleIndexedUpdate.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalDataUpdate
+import OAI.Computability.VPVNP.PairShrinkSelectedKernelTransport
+
+/-!
+# Reindexing the shrinking site's actual private writes
+
+The selected level stores its outgoing parent half in the original output
+coordinates. Reindexing that half and the placed child halves identifies
+the literal tape prefix, child pointers and parameter multiplicities.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM PrivateRAM DFS Compression CompressorRecords LocalHistory NetworkKernel NodeArguments
+open TreeDecode TraversalRoles TraversalRows ShrinkRoleDirectory LeafSourceLoad
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {K : Type} {R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+ {B : S.Templates} {f : B.Entry → R} {hf : B.IsSolution f}
+ (selected : SelectedLevel B f hf) (u : (selected.pass.step.term selected.term).output.Site)
+ (shrinking : tagLevel B f hf selected = .shrink)
+
+local notation "x" => occurrence selected u shrinking
+local notation "tr" => selected.pass.step.term selected.term
+local notation "r₀" => originReader B f hf selected.origin selected.term
+
+variable {w n p r lanes T : ℕ}
+ (site : CanonicalSite B (occurrence selected u shrinking).i
+ (occurrence selected u shrinking).state
+ (occurrence selected u shrinking).selection (occurrence selected u shrinking).site w n
+ (Fintype.card B.Entry))
+ {M : Machine w p r 11} {hT : T * S.laneBits ≤ lanes} {X : State (S.degreeExponent 0) lanes}
+ {z : (B.execute f hf T hT X).Choices} {j : Fin (executeLevels B f hf T hT X z).length}
+ {id : Fin (executeLevels B f hf T hT X z)[j].outputSites} {base : ℕ}
+
+local notation "regions" rowEnd => TerminalLayout.privateRegions (slotDegree S) n rowEnd
+ (Fintype.card B.Entry)
+local notation "addr" => site.later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal (x).nextState (x).site
+
+attribute [local irreducible] occurrence canonicalParent originReader shrinkPassReaders
+ TermParsers.nodeBits TreeDecode.children
+
+set_option maxHeartbeats 2400000 in
+-- The original and scheduled kernels index halves and witnesses by dependent placements.
+theorem indexedSiteUpdate (info : CanonicalSiteData site M f hf T hT X z j id base)
+ (order : B.Entry ≃ Fin (Fintype.card B.Entry)) (b : (tr).output.Half u)
+ (a : Placed (tr).place selected.input.network.Half u) (k : ((r₀).witness u a b).Choice)
+ {H : Word w} (maps : CanonicalMapData site H (halfEquiv selected u shrinking b))
+ (older rowEnd : ℕ) (oldBase : site.older = older) (endRow : site.rowEnd = rowEnd)
+ (node : Word w) (s : Scratch w n) (atRow : node.val = addr)
+ (stored : (Packet.mk node.val (pullBits (selected.pass.output_eq selected.term)
+ (packed (selected.pass.next selected.term)) u b)).Stored (regions rowEnd).arguments s)
+ (data : Fin 10 → Word w) (offset : Word w) (vals : Static 34 → Word w)
+ (frame : VertexFrameData (regions rowEnd) data offset vals s)
+ (tail : List Bool) (job : VisitPath w n)
+ (hit : (canonicalParent site order f hf).read node s
+ ((r₀).nodeBits u a b k ++ tail) = some (job, tail)) :
+ RowUpdate (regions rowEnd) order data offset vals s job
+ (TreeDecode.children r₀ (fun v y => ⟨(sitePointers B.recordLimit older
+ (siteOrder selected.input) v).1, packed selected.input v y⟩) u a)
+ (((r₀).witness u a b).exponents k) := by
+ subst rowEnd
+ subst older
+ have fields := witness_fields selected u shrinking b a k
+ have update := info.update order (placedEquiv selected u shrinking a)
+ (halfEquiv selected u shrinking b) maps (witnessEquiv selected u shrinking b a k)
+ node s atRow (by rw [← halfEquiv_packed selected u shrinking b]; exact stored)
+ data offset vals frame tail job (by rw [fields.1] at hit; exact hit)
+ rw [ShrinkRoleDirectory.children_packets selected u shrinking a site.older, fields.2]
+ exact update
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleItemOrigins.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleItemOrigins.lean
new file mode 100644
index 0000000000..0a49c68143
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleItemOrigins.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoopExact
+
+/-!
+# Resident map invariants with an arbitrary prepared origin
+
+The packet and operand proofs can be established for a fixed map-loop entry
+configuration. Any later configuration may retain that origin as a witness.
+The same selected actions still execute on its current scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentMapLoop.Exact
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {w n p r k : ℕ} {Ω : Type*} {P : Program p r} {M : Machine w p r k} {m : Memory w}
+ {dfs : Fin 9 ↪ Fin r} {inv : Ω → Word w → Config w p r → Prop}
+ {eligible : Ω → Word w → Prop}
+
+/-- Origin-dependent data that can be retained through the whole row. -/
+def OriginInvariant (eligible : Ω → Word w → Prop)
+ (inv : Ω → Word w → Config w p r → Prop) (node : Word w) (c : Config w p r) : Prop :=
+ ∃ origin, eligible origin node ∧ inv origin node c
+
+theorem OriginInvariant.stable (each : ∀ origin node, P.Stable (inv origin node)) (node : Word w) :
+ P.Stable (OriginInvariant eligible inv node) := by
+ rintro c d ⟨origin, good, live⟩ regs mem persistent
+ exact ⟨origin, good, each origin node c d live regs mem persistent⟩
+
+/-- The actions and their guard addresses are identical across origins. The
+actual native item takes the origin belonging to the input configuration. -/
+theorem Items.existsInvariant {src : ℕ} {actions : List (Action w n)}
+ (quiet : ∀ a ∈ actions, NoChoices a)
+ (each : ∀ origin, Items P M m dfs (inv origin) src actions) :
+ Items P M m dfs (OriginInvariant eligible inv) src actions := by
+ induction actions generalizing src with
+ | nil => trivial
+ | cons a rest ih =>
+ refine ⟨⟨quiet a List.mem_cons_self, ?_, ?_⟩,
+ ih (fun b hb => quiet b (List.mem_cons_of_mem _ hb)) (fun o => (each o).2)⟩
+ · rintro node c es out atItem cursor ⟨o, good, live⟩ hit
+ obtain ⟨d, done, keep, frame⟩ := (each o).1.success node c es out atItem cursor live hit
+ exact ⟨d, done, ⟨o, good, keep⟩, frame⟩
+ · rintro node c atItem cursor ⟨o, _, live⟩ bad
+ exact (each o).1.reject node c atItem cursor live bad
+
+end PairSimulation.ResidentMapLoop.Exact
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleLevelChecks.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleLevelChecks.lean
new file mode 100644
index 0000000000..4316d7607b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleLevelChecks.lean
@@ -0,0 +1,211 @@
+import OAI.Computability.VPVNP.PairDispatchedRowEffects
+import OAI.Computability.VPVNP.PairVertexRoleDomains
+import OAI.Computability.VPVNP.PairVertexOrdinalRoleCost
+import OAI.Computability.VPVNP.PairShrinkRoleRowUpdate
+import OAI.Computability.VPVNP.PairVertexSelectedDesc
+import OAI.Computability.VPVNP.PairSimulationFieldReadSafety
+
+/-!
+# Selected shrinking rows in the terminal traversal
+
+The same address selects the physical role, the shrinking site, and the term
+reader. Replacing the popped packet by the selected children consumes one
+vertex's histogram allowance. This holds for every prepared parent half and
+every remaining private tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM PrivateRAM DFS CompressorRecords Compression LocalHistory NetworkKernel
+open TreeDecode NodeArguments TraversalRows TraversalRoles VertexImage LeafSourceLoad
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {w n h : ℕ}
+
+variable {k K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f) {lanes : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) (base : ℕ)
+
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "leaf" => (⟨leafLayer (siteOrder X), .cursor⟩ : TaggedLayer)
+local notation "cap" => B.recordLimit
+local notation "pos" => layerBase cap base (tags)
+local notation "desc" => selectedDesc B f hf T hT X z base
+local notation "fmt" => SelectedPacketFormat B f hf T hT X z base
+local notation "rows" => selectedLayers B f hf T hT X z
+
+variable (i : Fin (executeLevels B f hf T hT X z).length)
+ (shrink : tagLevel B f hf ((executeLevels B f hf T hT X z).get i) = .shrink)
+local notation "v₀" => (vs).get i
+local notation "term" => ((v₀).pass.step.term (v₀).term)
+local notation "Site" => (term).output.Site
+local notation "Half" => (term).output.Half
+local notation "PlacedAt" => Placed (term).place (v₀).input.network.Half
+local notation "rdr" => originReader B f hf (v₀).origin (v₀).term
+local notation "ptr" => sitePointers cap ((pos) (i.val + 1)) (ShrinkRoleDirectory.outputOrder v₀)
+local notation "oldAddr" => (fun u => (sitePointers cap ((pos) i.val) (siteOrder (v₀).input) u).1)
+local notation "before" => (fun u b => Packet.mk ((oldAddr) u) (packed (v₀).input u b))
+local notation "head" => (fun u b => Packet.mk ((ptr) u).1 (pullBits ((v₀).pass.output_eq (v₀).term)
+ (packed ((v₀).pass.next (v₀).term)) u b))
+local notation "site" => (fun u => (⟨⟨i,u⟩, shrink⟩ : ShrinkRoleDirectory.ShrinkSite vs))
+
+variable {geo rootFields leafSeg shrinkSeg refreshSeg : Segment} {p regs : ℕ}
+ (A : Placement (segments geo rootFields leafSeg shrinkSeg refreshSeg) p regs)
+ (M : Machine w p regs 11) (m : Memory w) (R : LeafArena.Regions)
+ (offset : ℕ) (data : Fin 10 → Word w) (vals : Static 34 → Word w) (order : B.Entry ≃ Fin h)
+ (nodeCap limit power scan : ℕ)
+ (readers : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z) → HookParser w n)
+ (handlers : NodeDispatch.Role → HookParser w n)
+
+local notation "stable" => VertexFrameData R data (offset : Word w) vals
+local notation "hist" => privateHistogram order.symm R.histBase
+local notation "valid" => Budgeted R.arguments fmt stable desc hist nodeCap limit
+local notation "H" => TerminalLink.header M.publicData
+local notation "allow" => TerminalLink.workerCell H
+local notation "hook₀" => dispatcher handlers m (offset : Word w)
+local notation "cost" => ordinalJobCost n power scan
+
+attribute [local irreducible] executeLevels originReader selectedDesc
+
+set_option maxHeartbeats 3500000 in
+-- The indexed pass carries dependent input, output and kernel witness types.
+/-- Assemble a genuinely indexed shrinking level from its site-reader and
+machine-cell laws. Its descendant table, packet format, counter headroom,
+physical dispatch tag and wrapped path costs are computed on the selected
+branch. -/
+theorem levelChecks
+ (installed : handlers .shrink = ShrinkRoleDirectory.parser cap base leaf vs readers)
+ (link : Contains A M) (published : TraversalRoles.Reads w m offset cap base tags)
+ (codes : 2 < 2 ^ w) (tagEnd : offset + base + tagWords cap tags ≤ (H).val)
+ (headerFit : (H).val + 31 < 2 ^ w)
+ (start : n ≤ R.arguments.start) (stride : frameStride (slotDegree S) n ≤ R.arguments.stride)
+ (histFit : R.histBase ≤ 2 ^ w) (nodes : base + words cap rows ≤ R.nodes)
+ (width : B.growthConstant ^ T * (X.maxWireWidth + 1) ≤ n) (limitFit : limit < 2 ^ w)
+ (run : (handlers .shrink).ExactOn
+ (RoleDomains.Domain X cap base vs R data (offset : Word w) vals hist nodeCap limit .shrink)
+ M (A.entry (rolePart .shrink)) (A.dfsPC 3) A.dfs m)
+ (suffix : ∀ (u : Site) (b : Half u) pending s bits, valid (head u b :: pending) s →
+ ((readers (site u)).read ((ptr u).1 : Word w) s bits).map Prod.snd =
+ ((nodeReader rdr u b).read bits).map Prod.snd)
+ (update : ∀ (u : Site) (b : Half u) (a : PlacedAt u)
+ (k : ((rdr).witness u a b).Choice) pending s tail job, valid (head u b :: pending) s →
+ (readers (site u)).read ((ptr u).1 : Word w) s ((rdr).nodeBits u a b k ++ tail) =
+ some (job, tail) →
+ RowUpdate R order data (offset : Word w) vals s job
+ (TreeDecode.children rdr before u a)
+ (((rdr).witness u a b).exponents k))
+ (small : ∀ (u : Site) (b : Half u) (a : PlacedAt u)
+ (k : ((rdr).witness u a b).Choice) l, ((rdr).witness u a b).exponents k l ≤ nodeCap)
+ (trace : ∀ (u : Site) (b : Half u) (a : PlacedAt u)
+ (k : ((rdr).witness u a b).Choice) pending s job, valid (head u b :: pending) s →
+ (readers (site u)).read ((ptr u).1 : Word w) s ((rdr).nodeBits u a b k) = some (job, []) →
+ after m job.trace = m ∧ SourceTransport.Reads allow job.trace ∧
+ countProbes job.trace + 1 ≤ scan * (n.log2 + 1) ^ power ∧ job.trace.length + 9 ≤ n ^ 43) :
+ LevelChecks B f hf hook₀ valid hist (JobGuard A M m allow cost) cap ((pos) i.val) v₀ := by
+ have next : (pos) (i.val + 1) = TraversalRows.address cap ((pos) i.val)
+ (siteOrder (v₀).input).length := selected_level_bases B f hf T hT X z base i
+ unfold LevelChecks
+ rw [← next]
+ have tagFit : offset + base + tagWords cap tags ≤ 2 ^ w := tagEnd.trans (H).isLt.le
+ have endEq : (pos) ((vs).length + 1) = base + tagWords cap tags := by
+ rw [selected_endBase, tagWords, selected_layers]
+ have rowsFit : (pos) ((vs).length + 1) ≤ 2 ^ w := by rw [endEq]; omega
+ have nodeBelow (u) : (ptr u).1 < (pos) ((vs).length + 1) := by
+ have bound := OutputRowDirectory.rowAddress_lt_end cap base leaf
+ (ShrinkRoleDirectory.outputTags vs)
+ (ShrinkRoleDirectory.siteRows vs (site u).val)
+ have len : (ShrinkRoleDirectory.outputTags vs).length = (vs).length := List.length_map _
+ rw [len] at bound
+ exact bound
+ have nodeVal (u) : ((ptr u).1 : Word w).val = (ptr u).1 :=
+ Nat.mod_eq_of_lt ((nodeBelow u).trans_le rowsFit)
+ have localRead u (s : Scratch w n) bits :
+ (handlers .shrink).read ((ptr u).1 : Word w) s bits =
+ (readers (site u)).read ((ptr u).1 : Word w) s bits := by
+ rw [installed]
+ exact ShrinkRoleDirectory.read_at cap base leaf vs readers rowsFit _ (site u) (nodeVal u) s bits
+ have tag u : NodeDispatch.role (m ((offset : Word w) + ((ptr u).1 : Word w)).val) = .shrink := by
+ have physical := ShrinkRoleDirectory.dispatch_at_site cap base leaf vs published codes tagFit
+ ((ptr u).1 : Word w) (site u).val (nodeVal u)
+ exact physical.trans (congrArg TraversalRoles.Role.dispatch shrink)
+ have tagCell u : allow ((offset : Word w) + ((ptr u).1 : Word w)).val := by
+ apply TerminalLink.workerCell_of_lt headerFit
+ rw [← Nat.cast_add, Fin.val_natCast]
+ have bound := nodeBelow u
+ rw [endEq] at bound
+ exact (Nat.mod_le ..).trans_lt (by omega)
+ have counts u b a k pending (s : Scratch w n) (job : VisitPath w n)
+ (h : valid (head u b :: pending) s)
+ (eff : RowUpdate R order data (offset : Word w) vals s job
+ (TreeDecode.children rdr before u a)
+ (((rdr).witness u a b).exponents k)) (l) :
+ hist (job.update s) l = hist s l + ((rdr).witness u a b).exponents k l := by
+ change (rawScratch _ ((R.histBase + (order l).val : ℕ) : Word w)).val = _
+ rw [eff.counters l]
+ simpa only [privateHistogram, Equiv.symm_symm, Fin.cast_val_eq_self] using
+ h.word_add limitFit l (small u b a k l)
+ have types := selected_children_fit B f hf T hT X z base R start stride histFit nodes width i
+ have raw : NodeStep (handlers .shrink) valid rdr ptr before head := by
+ apply nodeStep_of_suffix
+ · intro u b pending s bits h
+ rw [localRead]
+ exact suffix u b pending s bits h
+ · intro u b pending s bits job tail a k h got enc
+ rw [localRead, enc] at got
+ have eff := update u b a k pending s tail job h got
+ refine h.push ?_ eff.frame (types u a) ?_
+ (fun l => (counts u b a k pending s job h eff l).le.trans
+ (Nat.add_le_add_left (small u b a k l) _))
+ · exact (selectedDesc_level B f hf T hT X z base i u).trans
+ (children_addresses rdr before oldAddr (fun _ _ => rfl) desc u a).symm
+ · intro q hq j
+ have typed := (List.mem_append.mp hq).elim (types u a q)
+ (fun old => (h.frontier.prepared.2 q (List.mem_cons_of_mem _ old)).imp_right And.left)
+ have endArg := R.node_before
+ ((selected_packet_node B f hf T hT X z base typed.1).trans_le nodes)
+ have slot := typed.2.2.1
+ have low := typed.2.1
+ have index := j.isLt
+ exact eff.arguments _ (by omega) (by omega)
+ constructor
+ · exact dispatcher_nodeStep tag raw
+ · intro u b a k pending s h
+ obtain ⟨body, read, remaining⟩ := raw.complete u b pending s a k [] h
+ rw [List.append_nil] at read
+ have domain : RoleDomains.Domain X cap base vs R data (offset : Word w) vals hist nodeCap limit
+ .shrink ((ptr u).1 : Word w) s :=
+ ⟨site u, nodeVal u, h.frontier.frame, h.headRoom, b, h.frontier.head.2.2⟩
+ have native := run.success _ s domain _ body [] read
+ rw [localRead] at read
+ have full := read
+ rw [← List.append_nil ((rdr).nodeBits u a b k)] at full
+ have eff := update u b a k pending s [] body h full
+ have bodyGuard := trace u b a k pending s body h read
+ have charge := dispatchJob_cost (m := m) (offset := (offset : Word w))
+ (node := ((ptr u).1 : Word w))
+ (saved := s) body
+ have realizes : RealizesJob hist
+ ⟨(ptr u).1,(rdr).nodeBits u a b k,((rdr).witness u a b).exponents k⟩ body := by
+ refine ⟨native.1, by simpa only [List.append_nil] using native.2.2.1.symm, ?_⟩
+ intro t en l
+ rw [eff.enabled_eq t en]
+ exact counts u b a k pending s body h eff l
+ let rawCost (j : VisitPath w n) := countProbes j.trace + 1 ≤ scan * (n.log2 + 1) ^ power ∧
+ j.trace.length + 9 ≤ n ^ 43
+ have guard : RoleJobGuard A M m .shrink allow rawCost body := ⟨native.2.2.2,bodyGuard⟩
+ exact ⟨_, dispatchJob_realizes realizes, ⟨rfl,native.2.1⟩,
+ dispatchJob_guard link h.frontier.frame.resident (tag u) (tagCell u) native.1 guard
+ (fun ok => ⟨charge.1.trans_le ok.1, charge.2.trans ok.2⟩), remaining⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleMapAcceptance.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapAcceptance.lean
new file mode 100644
index 0000000000..e674f7b4ef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapAcceptance.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PairShrinkRoleMapActions
+import OAI.Computability.VPVNP.PairSimulationMapScanAcceptance
+
+/-!
+# Acceptance of the selected shrinking site's native map scan
+
+The packed row enumerates all resident motif-party occurrences. The gathers
+and matrix routines use the current scratch in order, and their success
+bits are determined by the typed inputs at those occurrences.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots ShrinkMapImage.Registers
+open ResidentMapLoop.Exact MapResidentRows
+
+variable {g : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t w endAddr : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+
+private noncomputable local instance acceptanceProofBase : DecidableEq X.Base := Classical.decEq _
+
+local notation "side" => selectedLayout X B.shrink sel
+local notation "F" => ShrinkVertexImage.matrixFamily B ord i
+local notation "G" => ShrinkVertexImage.gatherFamily B ord i
+
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+ (jobs : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ ShrinkPartyNative.Job X B.shrink (S.shrink i) sel q.1.1 q.1.2 w)
+
+variable (m : Memory w) (level term : Word w)
+ (R : MapRowSource X sel (selectedLayout X B.shrink sel) m level term)
+ (hw : MapConstants.widthThreshold B.shrink ≤ w)
+ (pub : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v → Fin 5 → Word w)
+ (workspace : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ MapHandlerOperand.Workspace (w := w) (ShrinkVertexImage.matrixFamily B ord i)
+ demandMass_pos (jobInput B i X sel v hidden jobs q))
+
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+
+set_option maxHeartbeats 2500000 in
+-- The native input is indexed simultaneously by the site, party and the scheduled matrix family.
+/-- The actual shrinking map scan succeeds on any starting scratch exactly
+when the scheduled kernel's interpreters accept every resident occurrence. -/
+theorem scan_accepts
+ (children : ∀ q, (jobs q).old = Eq.rec (motive := fun u _ => Placed
+ (X.packingData.shrinkPlace side) (X.packingData.oldWireNetwork X.packingWidth).Half u)
+ (placedOld B i X sel v old) q.2.symm)
+ (newHalf : ∀ q, (jobs q).parent = Eq.rec (motive := fun u _ =>
+ (X.shrinkNext B.shrink (S.shrink i) sel).network.Half u) parent q.2.symm)
+ (node : Word w) (saved : Scratch w endAddr) :
+ (scan node (actions B ord i X sel v hidden jobs m level term R hw pub workspace) saved).isSome ↔
+ ∀ q, (names B (input B i X sel v old parent hidden q)).isSome := by
+ let idx := rowEquiv X side v
+ let accept (q : X.packingData.ResidentMap side v) :=
+ (names B (input B i X sel v old parent hidden q)).isSome = true
+ unfold actions
+ refine (scan_ofFn_iff node _ (fun j => accept (idx j)) ?_ saved).trans idx.forall_congr_right
+ intro j scratch
+ let q := idx j
+ let I := jobInput B i X sel v hidden jobs q
+ change (rowAction (F) (G) X sel v m level term R j I (jobs q) hw (pub q) (workspace q)
+ scratch).isSome = true ↔ _
+ have native := rowAction_isSome (g := g) (ready := S.shrink i) (jobMotif := q.1.1)
+ (F) (G) X sel v m level term R j I (jobs q) hw (pub q) (workspace q) scratch
+ have equal : I = input B i X sel v old parent hidden q :=
+ ShrinkPartyNative.Job.entryInput_eq_witness B i X sel v old parent hidden q (jobs q)
+ (children q) (newHalf q)
+ have labels : (MapHandlerOperand.names (F) demandMass_pos I).isSome =
+ (names B (input B i X sel v old parent hidden q)).isSome := by
+ change ((names B I).map (List.map (F).ordinal)).isSome = _
+ rw [Option.isSome_map, equal]
+ exact Iff.of_eq (congrArg (· = true) (native.trans labels))
+
+end PairSimulation.ShrinkRole.MapWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleMapActions.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapActions.lean
new file mode 100644
index 0000000000..242db148f7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapActions.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.PairShrinkRoleMapLabels
+import OAI.Computability.VPVNP.PairShrinkMapJobInput
+import OAI.Computability.VPVNP.PairShrinkVertexImage
+import OAI.Computability.VPVNP.PairSimulationShrinkRowAction
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoopExact
+
+/-!
+# Native map actions of the selected shrinking site
+
+The packed row enumerates all resident motif-party occurrences. The gathers
+and matrix routines use the current scratch in order, and their success
+bits are determined by the typed inputs at those occurrences.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots ShrinkMapImage.Registers
+open ResidentMapLoop.Exact MapResidentRows
+
+variable {g : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t w endAddr : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+
+private noncomputable local instance acceptanceBase : DecidableEq X.Base := Classical.decEq _
+
+local notation "side" => selectedLayout X B.shrink sel
+local notation "F" => ShrinkVertexImage.matrixFamily B ord i
+local notation "G" => ShrinkVertexImage.gatherFamily B ord i
+
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+ (jobs : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ ShrinkPartyNative.Job X B.shrink (S.shrink i) sel q.1.1 q.1.2 w)
+
+set_option maxHeartbeats 1500000 in
+-- The party index transports the hidden assignment to the selected occurrence.
+/-- Matrix-entry input of a resident party job, with the site's hidden assignment transported
+along the party's placement equality. -/
+noncomputable abbrev jobInput (q : X.packingData.ResidentMap side v) :=
+ ShrinkPartyNative.Job.entryInput B X (S.shrink i) sel q.1.1 q.1.2 (jobs q) (q.2.symm ▸ hidden)
+
+variable (m : Memory w) (level term : Word w)
+ (R : MapRowSource X sel (selectedLayout X B.shrink sel) m level term)
+ (hw : MapConstants.widthThreshold B.shrink ≤ w)
+ (pub : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v → Fin 5 → Word w)
+ (workspace : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ MapHandlerOperand.Workspace (w := w) (ShrinkVertexImage.matrixFamily B ord i)
+ demandMass_pos (jobInput B i X sel v hidden jobs q))
+
+set_option maxHeartbeats 2500000 in
+-- The job and its workspace depend on the row index of the selected gathering routine.
+/-- The native actions in the actual selected row order. Every later action
+receives the scratch returned by its predecessor. -/
+noncomputable def actions : List (Action w endAddr) :=
+ List.ofFn fun j : Fin (order X side v).length => fun _ saved =>
+ let q := rowEquiv X side v j
+ rowAction (F) (G) X sel v m level term R j (jobInput B i X sel v hidden jobs q) (jobs q)
+ hw (pub q) (workspace q) saved
+
+end PairSimulation.ShrinkRole.MapWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleMapHistogramNative.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapHistogramNative.lean
new file mode 100644
index 0000000000..c98ba1af3e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapHistogramNative.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.PairShrinkRoleBankHistogramSum
+import OAI.Computability.VPVNP.PairShrinkRoleMapLabels
+import OAI.Computability.VPVNP.PairShrinkSiteSources
+
+/-!
+# The scheduled exponent in the physical shrinking histogram
+
+The selected site's row enumerates its resident motif parties. The actual
+private gather and grouped map at each occurrence add their emitted names
+to the common counters. Summing those stores in row order gives the exponent
+of the local kernel witness, including repetitions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+section Histogram
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open ShrinkMapImage.Registers ResidentMapLoop.Exact MapResidentRows NodeArguments
+open scoped Fin.CommRing
+
+variable {K : Type} {C : Type*} [_root_.Field K] [CommRing C] {S : BlockSchedule K}
+ {B : S.Templates}
+ {i : Fin S.steps} {g n w t packetEnd : ℕ}
+ {X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : MapResidentRows.Site X}
+open private rowBase from OAI.Computability.VPVNP.PairShrinkRoleBankHistogramStep
+attribute [local instance] rowBase
+set_option allowUnsafeReducibility true in
+attribute [local reducible] rowBase Compression.PackingData.shrinkTermLayout
+set_option allowUnsafeReducibility true in
+attribute [local irreducible] Compression.ShrinkEnergy.chosenLayout
+
+variable (site : CanonicalSite B i X sel v w n t) (ord : B.Entry ≃ Fin t)
+ (f : B.Entry → C) (hf : B.IsSolution f)
+ (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+local notation "W" => B.shrinkPassWitnesses f hf i rfl X sel v old parent
+local notation "side" => selectedLayout X B.shrink sel
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "jobs" => ShrinkSiteBank.jobs (g := g) (w := w) B i X sel site.workspace
+ site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v old parent
+open private jobPublic from OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+local notation:max "pubAt" q:max => jobPublic site old parent q
+local notation "row" => MapWitness.rowEquiv (a := a i) (g := g) X side v
+set_option quotPrecheck false in
+local notation:max "bin" l:max => (((regions).histBase + (ord l).val : ℕ) : Word w)
+
+set_option maxHeartbeats 1000000 in
+-- Expose the selected hidden assignment once without unfolding every resident matrix.
+private noncomputable abbrev witnessHidden (x : (W).Choice) :
+ Placed (X.packingData.shrinkInternalOwner side)
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) side) v := x.1
+
+local notation:max "absorbed" x:max => witnessHidden (B := B) (i := i) (X := X) (sel := sel)
+ (v := v) f hf old parent x
+attribute [local irreducible] ResidentMapLoop.Exact.scan MapWitness.actions canonicalBank
+ MapWitness.names MapWitness.input NodeArguments.rawScratch
+
+set_option maxHeartbeats 1800000 in
+-- Compare the same packed witness in the scheduled, physical and resident map indices.
+/-- Every successful scan of the site's actual gather and matrix rows adds its
+scheduled local exponent to the indicated private word. -/
+theorem canonicalBank_histogram (x : (W).Choice) (baseline : Word w → Word w)
+ (packets : ∀ q, (jobs q).Packets packetEnd baseline)
+ {T : IncidenceDirectory w} {origin : ℕ}
+ (headers : ∀ j, let q := row j
+ (jobs q).OldPublished (ShrinkCallABI.operands (slotDegree S)) (pubAt q)
+ (rowOrdinalWord X side v j) site.mem site.level T origin)
+ (node : Word w) {initial final : Scratch w n} {es : List (Event w)}
+ (scanOk : scan node (canonicalBank site (⇑ord) parent old (absorbed x)) initial =
+ some (es, final))
+ (l : B.Entry) :
+ rawScratch final (bin l) = rawScratch initial (bin l) + ((W).exponents x l : Word w) := by
+ have counts := canonicalBank_counts (B := B) (i := i) (X := X) (sel := sel) (v := v)
+ site ord old parent (absorbed x) baseline packets headers node scanOk l
+ have total := MapWitness.ordinal_sum B f hf i X sel v old parent ord x l
+ exact counts.trans (congrArg (fun k : ℕ => rawScratch initial (bin l) + (k : Word w)) total)
+
+end Histogram
+
+section Header
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open ShrinkMapImage.Registers ResidentMapLoop.Exact MapResidentRows NodeArguments
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K}
+ {B : S.Templates}
+ {i : Fin S.steps} {g n w t : ℕ}
+ {X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)}
+ {sel : X.ShrinkSelection B.shrink} {v : MapResidentRows.Site X}
+private noncomputable local instance countSiteBase : DecidableEq X.Base := Classical.decEq _
+
+variable (site : CanonicalSite B i X sel v w n t)
+ (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "jobs" => ShrinkSiteBank.jobs B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v old parent
+open private jobPublic from OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+local notation:max "pubAt" q:max => jobPublic site old parent q
+local notation "row" => MapWitness.rowEquiv X side v
+
+local notation "layout" => BlockProgram.layout B site.workspace.val site.positions site.blocks
+local notation "head" => DescriptorSpace.levelStart layout site.cur
+
+set_option maxHeartbeats 2200000 in
+-- Identifying the physical row transports the node pointer and the same dense ordinal.
+/-- The selected vertex's row certificate supplies the actual old-header
+operand at each ordered job, including its loaded node and stage words. -/
+theorem canonicalOldPublished (H : Word w) (here : site.level = (head : Word w))
+ (sources : ∀ q, ShrinkSiteBank.RowSources B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v old parent site.mem H q)
+ (j : Fin (order X side v).length) :
+ let q := row j
+ (jobs q).OldPublished (ShrinkCallABI.operands (slotDegree S)) (pubAt q)
+ (rowOrdinalWord X side v j) site.mem site.level
+ (DescriptorSpace.packedIncidence layout w site.cur (DemandRAM.oldCount X))
+ (DescriptorSpace.tableBase layout site.cur (0 : Fin 6)) := by
+ dsimp only
+ rw [jobPublic, here, ShrinkSiteBank.node_eq]
+ exact (sources (row j)).old
+
+end Header
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleMapLabels.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapLabels.lean
new file mode 100644
index 0000000000..63db2e2a5a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapLabels.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.PairShrinkRoleMapWitness
+import OAI.Computability.VPVNP.PairSimulationMapResidentRows
+import OAI.Computability.VPVNP.CompressorSlotState
+
+/-!
+# Histogram exponents of a scheduled shrinking kernel
+
+Every resident occurrence contributes its whole sequence of returned labels,
+including repetitions. Counting these sequences in physical row order gives
+the exponent of the corresponding entry in the common parameter alphabet.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel LocalHistory
+open MotifGrid MotifBlocks MotifConversion CompressorRecords
+open CompressorRecords.ShrinkSlots MapResidentRows
+open private names_eq from OAI.Computability.VPVNP.PairShrinkRoleMapWitness
+
+variable {a g : ℕ} in
+/-- The physical directory order and the resident subtype use opposite
+orientations of the same site equality. -/
+noncomputable def rowEquiv (Z : State a (packingLaneBits a g)) (side : Bool) (site : Site Z) :
+ Fin (order Z side site).length ≃ Z.packingData.ResidentMap side site :=
+ (order Z side site).entries.trans (Equiv.subtypeEquivRight fun _ => eq_comm)
+
+variable {R : Type*} [CommRing R]
+
+private theorem entry_count {L : Type} [Fintype L] [DecidableEq L] {n : ℕ} (κ : L → R)
+ (idx : Option (Fin n → L)) (x : (entryWitness κ idx).Choice) (l : L) :
+ (entryWitness κ idx).exponents x l = ((idx.map List.ofFn).getD []).count l := by
+ cases idx with
+ | none => exact x.elim
+ | some seq =>
+ have count := PrivateLabels.count_entry seq (Fintype.equivFin L) l
+ rw [List.count_map_of_injective _ _ (Fintype.equivFin L).injective] at count
+ exact count.symm
+
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g : ℕ}
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+
+private noncomputable local instance countsBase : DecidableEq X.Base := Classical.decEq _
+
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+
+local notation "W" => B.shrinkPassWitnesses f hf i rfl X sel v old parent
+local notation "side" => selectedLayout X B.shrink sel
+local notation "call" => input B i X sel v old parent
+
+set_option maxHeartbeats 2000000 in
+-- The sum uses the dependent product in the scheduled reindexed witness.
+/-- The exponent of one shrinking label is the sum of its multiplicities
+over all resident occurrences of the kernel. -/
+theorem exponent_count [DecidableEq (parameterData B.shrink).Entry]
+ (x : (W).Choice) (label : (parameterData B.shrink).Entry) :
+ (W).exponents x (.inl label) = ∑ q : X.packingData.ResidentMap side v,
+ ((names B (call x.1 q)).getD []).count label := by
+ let κ := f ∘ Sum.inl
+ let ix (q : X.packingData.ResidentMap side v) :=
+ let arg := call x.1 q
+ entry B.shrink demandMass_pos arg.demand arg.payload arg.party arg.demandBits arg.supplyBits
+ change (∑ q, (entryWitness κ (ix q)).exponents (x.2 q) label) = _
+ apply Finset.sum_congr rfl
+ intro q _
+ rw [names_eq]
+ exact entry_count κ (ix q) (x.2 q) label
+
+/-- The other template's labels have zero exponent in a shrinking witness. -/
+theorem refresh_exponent (x : (W).Choice) (label : (parameterData B.refresh).Entry) :
+ (W).exponents x (.inr label) = 0 := rfl
+
+/-- Flatten the map-entry label lists in resident directory order for the given choice of
+shrinking map calls. -/
+noncomputable def emitted (x : (W).Choice) : List (parameterData B.shrink).Entry :=
+ (List.ofFn fun j => (names B (call x.1 (rowEquiv X side v j))).getD []).flatten
+
+private theorem count_flatten {L : Type} [DecidableEq L] (rows : List (List L)) (l : L) :
+ rows.flatten.count l = (rows.map fun r => r.count l).sum := by
+ induction rows with
+ | nil => rfl
+ | cons r rs ih =>
+ simp only [List.flatten_cons, List.count_append, ih, List.map_cons, List.sum_cons]
+
+set_option maxHeartbeats 2000000 in
+-- Match the physical resident enumeration to the dependent witness product.
+/-- The native label stream contributes the exact exponent, with all duplicate
+labels from repeated base copies retained. -/
+theorem emitted_count [DecidableEq (parameterData B.shrink).Entry]
+ (x : (W).Choice) (label : (parameterData B.shrink).Entry) :
+ (emitted B f hf i X sel v old parent x).count label = (W).exponents x (.inl label) := by
+ rw [emitted, count_flatten, List.map_ofFn, List.sum_ofFn,
+ exponent_count B f hf i X sel v old parent]
+ exact Fintype.sum_equiv (rowEquiv X side v) _ _ (fun _ => rfl)
+
+set_option maxHeartbeats 2500000 in
+-- Summing along the actual row pulls the reindexed witness through the common alphabet.
+/-- Counting the fixed finite machine ordinals gives the full scheduled exponent vector. -/
+theorem ordinal_sum {t : ℕ} (ord : B.Entry ≃ Fin t) (x : (W).Choice) (label : B.Entry) :
+ (∑ j : Fin (order X side v).length,
+ (((names B (call x.1 (rowEquiv X side v j))).map (List.map (ord ∘ Sum.inl))).getD []).count
+ (ord label)) = (W).exponents x label := by
+ classical
+ cases label with
+ | inl l =>
+ rw [exponent_count B f hf i X sel v old parent]
+ apply Fintype.sum_equiv (rowEquiv X side v)
+ intro j
+ cases h : names B (call x.1 (rowEquiv X side v j)) with
+ | none => rfl
+ | some seq =>
+ exact List.count_map_of_injective seq (ord ∘ Sum.inl)
+ (ord.injective.comp Sum.inl_injective) l
+ | inr l =>
+ rw [refresh_exponent B f hf i X sel v old parent]
+ apply Finset.sum_eq_zero
+ intro j _
+ cases h : names B (call x.1 (rowEquiv X side v j)) with
+ | none => rfl
+ | some seq =>
+ apply List.count_eq_zero.mpr
+ intro mem
+ obtain ⟨a, _, he⟩ := List.mem_map.mp mem
+ exact Sum.inl_ne_inr (ord.injective he)
+
+end PairSimulation.ShrinkRole.MapWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleMapStart.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapStart.lean
new file mode 100644
index 0000000000..611b041550
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapStart.lean
@@ -0,0 +1,190 @@
+import OAI.Computability.VPVNP.PairShrinkVertexLinks
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherSource
+import OAI.Computability.VPVNP.PairShrinkRoleExact
+
+/-!
+# Entering the map-list loop in the actual shrinking role
+
+The reload and the five external header probes prepare the loop at the row of the
+selected site. The chronological trace depends on the published level and owner.
+All private cells are retained, including the child and hidden fields just written.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkVertexImage
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression CompressorRecords
+open ShrinkMapImage Registers MapResidentInputs MapResidentRows NodeArguments.ChildScan
+open ShrinkRole DFS
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+ {p r w : ℕ} (pc : Fin (shrinkSegment B ord).count → Fin p)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r) (done : Fin p)
+
+/-- First instruction of the histogram reload reached before the resident map loop at this
+scheduled shrink. -/
+abbrev reloadStart := Segment.leftPC (ShrinkMapReload.setup (maps B ord i)) (maps B ord i).code
+ (reloadPC B ord i pc) (0 : Fin 4)
+
+/-- Embedding of the map loop's shared locator registers into the enclosing shrink stage's
+private register bank. -/
+abbrev shared := (gatherShared (matrixFamily B ord i) (gatherFamily B ord i)).trans
+ (reloadRegs B ord i reg)
+
+/-- Physical program counters for the gather-enabled resident map handler inside the selected
+stage. -/
+abbrev gatheredPC :=
+ matrixPC B ord i pc ∘ gatherLocations (matrixFamily B ord i) (gatherFamily B ord i)
+
+/-- Program-counter map for the core resident map loop after locating it inside the
+gather-enabled handler. -/
+abbrev basePC := corePC (matrixFamily B ord i) (gatherFamily B ord i) (gatheredPC B ord i pc)
+
+/-- The resident map loop installed for this shrink, with its physical program counters, shared
+registers, and return address. -/
+abbrev mapLoop := loop (matrixFamily B ord i) mapRegisters (basePC B ord i pc)
+ (shared B ord i reg) done
+
+/-- Each of the fourteen live location registers lies outside the seven modified
+registers of the map header. -/
+theorem locator_header_frame (l : Fin 14) : HeaderFrame
+ (mapRegisters.headerReg (shared B ord i reg)) (shared B ord i reg (l.castAdd 10)) := by
+ have away (k : Fin 24) (hk : 14 ≤ k.val) :
+ shared B ord i reg (l.castAdd 10) ≠ shared B ord i reg k := by
+ apply (shared B ord i reg).injective.ne
+ intro he
+ have eq := congrArg Fin.val he
+ change l.val = k.val at eq
+ omega
+ exact ⟨away _ (by decide), away _ (by decide), away _ (by decide), away _ (by decide),
+ away _ (by decide), away _ (by decide), away _ (by decide)⟩
+
+/-- Physical data supplied to the item loop, including all resident source operands and
+the unchanged memory used to establish each item's field invariant. -/
+structure MapStart (common : Fin 24 ↪ Fin r) (dfs : Fin 9 ↪ Fin r)
+ (term : Word w) (c d : Config w p r) : Prop where
+ geometry : d.reg (common 9) = c.privateMem (c.reg (dfs 6))
+ histogram : d.reg (common 10) = c.privateMem (c.privateMem (c.reg (dfs 6)) + 11)
+ term : d.reg (common 16) = term
+ stride : d.reg (common 17) = 10
+ one : d.reg (common 22) = 1
+ outside : ∀ q, q ≠ common 9 → q ≠ common 10 →
+ HeaderFrame (mapRegisters.headerReg common) q → d.reg q = c.reg q
+ memory : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+/-- Sixteen header instructions follow the four private reload instructions. -/
+def mapStartSetup {endAddr : ℕ} (m : Memory w) (level owner : Word w) : Setup w endAddr where
+ trace _ _ := List.replicate 4 .tick ++ headerEvents m level owner
+ updated _ s := s
+ quiet _ _ := by simpa [choiceBits] using (headerCost m level owner).2.2
+
+theorem mapStart_cost (m : Memory w) (level owner : Word w) :
+ (List.replicate 4 (Event.tick : Event w) ++ headerEvents m level owner).length = 20 ∧
+ countProbes (List.replicate 4 .tick ++ headerEvents m level owner) = 5 := by
+ obtain ⟨len, probes, _⟩ := headerCost m level owner
+ exact ⟨by simp [len], by simpa [countProbes] using probes⟩
+
+variable {g : ℕ} {Z : State (oldExponent i) (packingLaneBits (oldExponent i) g)}
+ {sel : Z.ShrinkSelection B.shrink} {side : Bool} {m : Memory w} {level term : Word w}
+ (source : MapRowSource Z sel side m level term) (site : Site Z)
+
+/-- First resident map entry for the selected site's directory row, obtained from the row base,
+site ordinal, and fixed row capacity. -/
+abbrev firstMap :=
+ ((ShrinkResidentLayout.layout Z source.first).params (oldExponent i) true w 5).val +
+ (siteIndex Z site).val * capacity (oldExponent i)
+
+variable (M : Machine w p r 11) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (rows : ∀ a, M.code (pc a) = ((shrinkSegment B ord).row pc dfs saved reg done a).resize w)
+ (words : Published m level
+ ((ShrinkResidentLayout.layout Z source.first).params (oldExponent i) true w 3)
+ ((ShrinkResidentLayout.layout Z source.first).params (oldExponent i) true w 5) term 10)
+ (room : level.val + 37 < 2 ^ w)
+
+set_option maxHeartbeats 1400000 in
+-- The real image contains nested dependent register banks for every party and stage.
+include rows words room in
+/-- The concrete gathered map image reaches the correct guard and the exact selected row.
+It prepares the term table, the raw geometry head, and the histogram pointer. -/
+theorem mapStart_native (c : Config w p r) (start : c.pc = reloadStart B ord i pc)
+ (oldHead : c.reg (shared B ord i reg 11) = level)
+ (owner : (c.reg (shared B ord i reg 7)).val = (siteIndex Z site).val) :
+ let src := firstMap B i source site
+ let P := mapLoop B ord i pc reg done
+ ∃ d, Prefix M m c d [] (List.replicate 4 .tick ++
+ headerEvents m level ((siteIndex Z site).val : Word w)) ∧
+ d.pc = P.test ∧ d.reg P.cursor = (src : Word w) ∧
+ d.reg P.stop = ((src + (order Z side site).length : ℕ) : Word w) ∧ d.reg P.one = 1 ∧
+ MapStart (shared B ord i reg) dfs term c d := by
+ let common := shared B ord i reg
+ let loc := ((maps B ord i).locator).trans (reloadRegs B ord i reg)
+ obtain ⟨reload, matrix⟩ := ShrinkMapReload.links (maps B ord i) M (reloadPC B ord i pc)
+ dfs saved (reloadRegs B ord i reg) done (reload_rows B ord i M pc dfs saved reg done rows)
+ obtain ⟨mid, pre, entry, geometry, histogram, keep, memory, persist⟩ :=
+ ShrinkMapReload.run reload c start m
+ have keepLoc (l : Fin 14) (h₉ : l ≠ 9) (h₁₀ : l ≠ 10) : mid.reg (loc l) = c.reg (loc l) :=
+ keep _ (loc.injective.ne h₉) (loc.injective.ne h₁₀)
+ have head : mid.reg ((mapRegisters.headerReg common) 0) = level :=
+ (keepLoc 11 (by decide) (by decide)).trans oldHead
+ have ownerEq : (mid.reg ((mapRegisters.headerReg common) 1)).val = (siteIndex Z site).val :=
+ (congrArg Fin.val (keepLoc 7 (by decide) (by decide))).trans owner
+ have ownerWord : mid.reg ((mapRegisters.headerReg common) 1) =
+ ((siteIndex Z site).val : Word w) := by
+ rw [← ownerEq]
+ exact Fin.ext (Nat.mod_eq_of_lt (mid.reg ((mapRegisters.headerReg common) 1)).isLt).symm
+ have hl := map_linked B ord i M (matrixPC B ord i pc) dfs saved (reloadRegs B ord i reg)
+ done matrix
+ obtain ⟨out, hdr, result, cursor, stop, termAt, stride⟩ :=
+ source.header_native site _ _ _ hl.header mid entry head ownerEq words room
+ rw [ownerWord] at hdr
+ exact ⟨out, pre.trans hdr, result.pc, cursor, stop, result.one,
+ ⟨(result.frame _ (locator_header_frame B ord i reg 9)).trans geometry,
+ (result.frame _ (locator_header_frame B ord i reg 10)).trans histogram, termAt, stride,
+ result.one,
+ fun q h₉ h₁₀ hf => (result.frame q hf).trans (keep q h₉ h₁₀),
+ result.memory.trans memory, result.persistent.trans persist⟩⟩
+
+set_option maxHeartbeats 1400000 in
+-- The real image contains nested dependent register banks for every party and stage.
+include rows words room in
+/-- The remaining invariant can use every fact from the genuine map header and reload;
+the code, exact trace, loop pointers, state and stack frame are already discharged. -/
+theorem mapStart_realizes {endAddr : ℕ} {pre inv : Word w → Config w p r → Prop}
+ (start : ∀ node c, pre node c → c.pc = reloadStart B ord i pc)
+ (oldHead : ∀ node c, pre node c → c.reg (shared B ord i reg 11) = level)
+ (owner : ∀ node c, pre node c → (c.reg (shared B ord i reg 7)).val = (siteIndex Z site).val)
+ (separate : ∀ l : Fin 9, l = 3 ∨ l = 5 ∨ l = 6 ∨ l = 7 →
+ dfs l ∉ Set.range (shared B ord i reg))
+ (resume : ∀ node c d, pre node c → MapStart (shared B ord i reg) dfs term c d → inv node d) :
+ Realizes (endAddr := endAddr) (mapStartSetup m level ((siteIndex Z site).val : Word w)).reader
+ M m dfs pre (fun _ => ResidentMapLoop.Exact.Entry (mapLoop B ord i pc reg done) inv
+ (firstMap B i source site) (order Z side site).length) := by
+ apply Setup.realizes
+ intro node c hc
+ obtain ⟨d, run, pc', cursor, stop, one, facts⟩ :=
+ mapStart_native B ord i pc reg done source site M dfs saved rows words room c
+ (start node c hc) (oldHead node c hc) (owner node c hc)
+ refine ⟨d, ⟨pc', cursor, stop, one, resume node c d hc facts⟩, ⟨?_, ?_, facts.persistent⟩,
+ congrArg (scratch endAddr) facts.memory, run⟩
+ · intro j hj
+ have off (l : Fin 24) : dfs j ≠ shared B ord i reg l := fun e => separate j hj ⟨l, e.symm⟩
+ exact facts.outside _ (off _) (off _)
+ ⟨off _, off _, off _, off _, off _, off _, off _⟩
+ · intro a _
+ exact congrFun facts.memory a
+
+end PairSimulation.ShrinkVertexImage
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleMapStartReads.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapStartReads.lean
new file mode 100644
index 0000000000..a3b03781ac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapStartReads.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairShrinkRoleMapStart
+import OAI.Computability.VPVNP.PairSimulationFieldReadSafety
+
+/-!
+# The five external addresses at entry to a shrinking map row
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkVertexImage
+
+open BurstRAM CompressorRecords Compression ShrinkMapImage.Registers
+open MapResidentInputs MapResidentRows
+open scoped Fin.CommRing
+open private fetch from OAI.Computability.VPVNP.PairSimulationMapResidentInputs
+
+variable {w : ℕ} {m : Memory w} {level owner : Word w} {data : ℕ → Prop}
+
+/-- Only four header cells and the selected site's count word are probed. -/
+theorem mapStart_reads
+ (header : ∀ n ∈ ({34, 35, 36, 37} : Finset ℕ), data (level + (n : Word w)).val)
+ (countCell : data (m (level + 34).val + owner).val) :
+ SourceTransport.Reads data (List.replicate 4 .tick ++ headerEvents m level owner) := by
+ intro a v h
+ simp only [headerEvents, fetch, List.mem_append, List.mem_replicate, List.mem_cons,
+ List.not_mem_nil, reduceCtorEq, Event.read.injEq, and_false, false_or, or_false] at h
+ rcases h with ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩
+ · exact header 34 (by decide)
+ · exact countCell
+ · exact header 35 (by decide)
+ · exact header 36 (by decide)
+ · exact header 37 (by decide)
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (i : Fin S.steps)
+ {g : ℕ} {Z : State (oldExponent i) (packingLaneBits (oldExponent i) g)}
+ {sel : Z.ShrinkSelection B.shrink} {side : Bool} {term : Word w}
+ (source : MapRowSource Z sel side m level term) (site : Site Z)
+
+/-- The live level and count regions both precede the terminal header. The chronological
+prefix consequently reads only cells that survive the enclosing worker's state splice. -/
+theorem mapStart_worker_reads (H : Word w) (hfit : H.val + 31 < 2 ^ w)
+ (hlevel : level.val + 38 ≤ H.val)
+ (hdir : (ShrinkResidentLayout.layout Z source.first).endAddr ≤ H.val)
+ (published : Published m level
+ ((ShrinkResidentLayout.layout Z source.first).params (oldExponent i) true w 3)
+ ((ShrinkResidentLayout.layout Z source.first).params (oldExponent i) true w 5) term 10) :
+ SourceTransport.Reads (TerminalLink.workerCell H) (List.replicate 4 .tick ++
+ headerEvents m level ((siteIndex Z site).val : Word w)) := by
+ let L := ShrinkResidentLayout.layout Z source.first
+ let owner := (siteIndex Z site).val
+ have addr (n : ℕ) (hn : n ≤ 37) : (level + (n : Word w)).val = level.val + n := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (show n < 2 ^ w by omega),
+ Nat.mod_eq_of_lt (show level.val + n < 2 ^ w by omega)]
+ have howner : owner < L.sites := (siteIndex Z site).isLt
+ obtain ⟨_, _, hc, hr⟩ := L.ranges true
+ have low : L.counts true + owner < H.val :=
+ (Nat.add_lt_add_left howner _).trans_le
+ (hc.le.trans ((Nat.le_add_right ..).trans (hr.trans hdir)))
+ obtain ⟨_, _, _, _, counts, _, _⟩ := ShrinkResidentLayout.frame Z source.first true source.fit
+ apply mapStart_reads
+ · intro n hn
+ have bound : n ≤ 37 := by
+ simp only [Finset.mem_insert, Finset.mem_singleton] at hn
+ omega
+ apply TerminalLink.workerCell_of_lt hfit
+ rw [addr n bound]
+ omega
+ · have actual : m (level + 34).val = L.params (oldExponent i) true w 3 := by
+ rw [show (34 : Word w) = ((34 : ℕ) : Word w) from rfl, addr 34 (by decide)]
+ exact published.countsAt
+ apply TerminalLink.workerCell_of_lt hfit
+ rw [actual, Fin.val_add, Fin.val_natCast, counts]
+ change (L.counts true + owner % (2 ^ w)) % (2 ^ w) < H.val
+ have total : L.counts true + owner < 2 ^ w := low.trans H.isLt
+ rw [Nat.mod_eq_of_lt (show owner < 2 ^ w by omega), Nat.mod_eq_of_lt total]
+ exact low
+
+end PairSimulation.ShrinkVertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleMapWitness.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapWitness.lean
new file mode 100644
index 0000000000..e74ab2f4aa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleMapWitness.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenParser
+import OAI.Computability.VPVNP.PairSimulationRecordedMapCalls
+
+/-!
+# Syntactic acceptance at the resident shrinking maps
+
+Once a parent has chosen its placed old halves and its owned hidden fields,
+the remaining kernel choices are exactly the local entry witnesses at its
+resident motif parties. Each passing entry has one choice and each failing
+entry has none, regardless of the specialized values of the parameters.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel LocalHistory
+open MotifBlocks MotifConversion MotifGrid MotifDemandPadding MotifSelector
+open CompressorRecords
+
+variable {K R : Type*} [Field K] [CommRing R] {S : BlockSchedule K} (B : S.Templates)
+ (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g : ℕ}
+
+local notation "a" => S.degreeExponent i.castSucc
+local notation "b" => S.degreeExponent i.succ
+variable (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink)
+/-- Classical equality on base vertices for enumerating the resident shrinking maps at a chosen
+site. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+private noncomputable abbrev layout :=
+ X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth sel
+
+private noncomputable abbrev supplyWidth (motif : X.packingData.Motif) :=
+ X.packingData.shrinkSupplyWidths X.shrinkNumber X.packingWidth B.shrink motif (sel motif)
+
+private noncomputable abbrev output :=
+ let d := 2 ^ S.degreeExponent i.castSucc
+ let l := layout B i X sel
+ X.packingData.shrinkOutput l (subdivisions d (2 * d + 1) (2 ^ S.degreeExponent i.succ))
+ (fun m t => supplyWidth B i X sel m (l, t)) (X.shrinkStateIndex (S.shrink i) l)
+
+local notation "P" => X.packingData
+local notation "lay" => layout B i X sel
+local notation "width" => supplyWidth B i X sel
+local notation "subd" => subdivisions (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b)
+
+variable (v : (X.Base × BitWord (packingTagBits (2 ^ S.degreeExponent i.castSucc))) × BitWord g)
+variable (old : Placed (X.packingData.shrinkPlace (layout B i X sel) ∘ X.packingInputIso.site.symm)
+ X.network.Half v)
+variable (new : (output B i X sel).Half v)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (layout B i X sel))
+ (internalLabel (supplyWidth B i X sel) (layout B i X sel)) v)
+
+private def pullPlaced {N Y : Network} {U : Type} (iso : N.Iso Y) (place : N.Site → U)
+ (site : U) (h : Placed (place ∘ iso.site.symm) Y.Half site) : Placed place N.Half site :=
+ fun u hu => iso.pullHalf u (h (iso.site u) (by simpa only [Function.comp_apply,
+ Equiv.symm_apply_apply] using hu))
+
+/-- Pull the placed old halves back to the coordinates used in the actual motif calls. -/
+noncomputable def placedOld :
+ Placed ((P).shrinkPlace lay) ((P).oldWireNetwork X.packingWidth).Half v :=
+ pullPlaced X.packingInputIso ((P).shrinkPlace lay) v old
+
+set_option maxHeartbeats 2000000 in
+-- The six-party coordinates unfold the selected term layout.
+/-- The real local demand and supply coordinates, in the selected row's six-party layout. -/
+noncomputable def input (q : (P).ResidentMap lay v) : EntryInput B.shrink :=
+ ⟨(P).shrinkDemandWidths X.shrinkNumber X.packingWidth q.1.1, (sel q.1.1).val, q.1.2,
+ (P).shrinkLocalDemandArg (State.two_le_packingColors a) (Nat.two_pow_pos a)
+ X.shrinkNumber X.shrinkOrder X.packingWidth lay q.1.1 q.1.2
+ (q.2.symm ▸ placedOld B i X sel v old),
+ (P).shrinkLocalSupplyArg lay subd width (X.shrinkStateIndex (S.shrink i) lay)
+ (S.shrink i).count_pos q.1.1 q.1.2 (q.2.symm ▸ hidden) (q.2.symm ▸ new)⟩
+
+/-- The label sequence returned by the metered entry interpreter, including repetitions. -/
+noncomputable def names (arg : EntryInput B.shrink) :
+ Option (List (parameterData B.shrink).Entry) :=
+ (runEntry B.shrink demandMass_pos arg.demand arg.payload arg.party
+ (MotifEntry.demandBits demandSource demandTarget arg.party arg.demandBits)
+ (mapHalf supply (fun _ => MotifEntry.inputBits) arg.supplyBits)).1
+
+private theorem choice_iff {L : Type} [Fintype L] {n : ℕ} (κ : L → R)
+ (idx : Option (Fin n → L)) :
+ Nonempty (entryWitness κ idx).Choice ↔ (idx.map List.ofFn).isSome = true := by
+ cases idx with
+ | none => exact ⟨fun ⟨c⟩ => c.elim, by simp⟩
+ | some t => exact ⟨fun _ => rfl, fun _ => ⟨()⟩⟩
+
+private theorem choice_subsingleton {L : Type} [Fintype L] {n : ℕ} (κ : L → R)
+ (idx : Option (Fin n → L)) : Subsingleton (entryWitness κ idx).Choice := by
+ cases idx with
+ | none => exact inferInstanceAs (Subsingleton Empty)
+ | some t => exact inferInstanceAs (Subsingleton Unit)
+
+local notation "calls" => input B i X sel v old new
+local notation "witness" => B.shrinkPassWitnesses f hf i rfl X sel v old new
+private noncomputable abbrev index (arg : EntryInput B.shrink) :=
+ entry B.shrink demandMass_pos arg.demand arg.payload arg.party arg.demandBits arg.supplyBits
+local notation "entries" => fun h q => index B (calls h q)
+
+private theorem names_eq (arg : EntryInput B.shrink) :
+ names B arg =
+ (entry B.shrink demandMass_pos arg.demand arg.payload arg.party
+ arg.demandBits arg.supplyBits).map List.ofFn :=
+ runEntry_list B.shrink demandMass_pos arg.demand arg.payload arg.party
+ arg.demandBits arg.supplyBits
+
+set_option maxHeartbeats 2500000 in
+-- The witness type unfolds the scheduled state reindexing and product of the resident entries.
+/-- A fixed hidden assignment extends to exactly one scheduled kernel choice
+if and only if all its resident interpreter calls succeed. -/
+theorem unique_iff :
+ (∃! x : (witness).Choice, x.1 = hidden) ↔
+ ∀ q : (P).ResidentMap lay v, (names B (calls hidden q)).isSome = true := by
+ let κ := f ∘ Sum.inl
+ let idx := entries
+ change (∃! x : (h : _) × ((q : (P).ResidentMap lay v) → (entryWitness κ (idx h q)).Choice),
+ x.1 = hidden) ↔ _
+ constructor
+ · rintro ⟨⟨h, maps⟩, rfl, _⟩ q
+ rw [names_eq]
+ exact (choice_iff κ (idx h q)).mp ⟨maps q⟩
+ · intro all
+ have exist (q) : Nonempty (entryWitness κ (idx hidden q)).Choice :=
+ (choice_iff κ _).mpr (names_eq B (calls hidden q) ▸ all q)
+ refine ⟨⟨hidden, fun q => (exist q).some⟩, rfl, ?_⟩
+ rintro ⟨h, maps⟩ rfl
+ congr 1
+ funext q
+ exact (choice_subsingleton κ _).allEq ..
+
+set_option maxHeartbeats 2500000 in
+-- The chosen kernel is elaborated in the common parameter alphabet.
+theorem exists_iff :
+ (∃ x : (witness).Choice, x.1 = hidden) ↔
+ ∀ q : (P).ResidentMap lay v, (names B (calls hidden q)).isSome = true := by
+ constructor
+ · rintro ⟨⟨h, maps⟩, rfl⟩ q
+ rw [names_eq]
+ exact (choice_iff (f ∘ Sum.inl) ((entries) h q)).mp ⟨maps q⟩
+ · intro pass
+ exact ((unique_iff B f hf i X sel v old new hidden).mpr pass).exists
+
+end PairSimulation.ShrinkRole.MapWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleOriginPackets.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleOriginPackets.lean
new file mode 100644
index 0000000000..407dcbabb5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleOriginPackets.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalInvariant
+import OAI.Computability.VPVNP.PairShrinkSiteInitialPackets
+
+/-!
+# Resident packet readback at a canonical shrinking map origin
+
+The initial memory consists of the original caller's scratch, the decoded child
+packets and the absorbed fields. At each resident occurrence these stores supply
+the independent old halves, the popped parent and the shared hidden inputs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots LocalHistory
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows
+open NodeArguments NodeArguments.ChildScan
+open ShrinkHiddenGuess ResidentMapLoop.Exact
+open scoped Fin.CommRing
+
+variable {K : Type} {R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+ {B : S.Templates}
+ {i : Fin S.steps} {g w n p r : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+ {sel : SelectedScore.Selection B X} {v : MapResidentRows.Site X}
+ (site : CanonicalSite B i X sel v w n (Fintype.card B.Entry))
+ (ord : B.Entry → Fin (Fintype.card B.Entry)) (f : B.Entry → R) (hf : B.IsSolution f)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+ (dfs : Fin 9 ↪ Fin r) (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r)
+ (ready : DFS.Scratch w n → Prop)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "addr" => site.later + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal
+ (Y) v
+local notation "rowsAt" => ShrinkHiddenSlots.rows X side widths v
+local notation "common" => shared B ord i reg
+set_option quotPrecheck false in
+local notation "readerAt" => (shrinkPassReaders B f hf i rfl X).termParsers sel
+set_option quotPrecheck false in
+local notation "termAt" => (B.shrinkPassAt f hf i rfl X).step.term sel
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+local notation "jobs" => ShrinkSiteBank.jobs B i X sel site.workspace site.positions site.blocks
+ site.cur site.bounds n site.rowEnd site.older site.later v
+
+variable (xs : List (Child X)) (es : List ShrinkHiddenGuess.Row)
+
+open private rowOrigin from OAI.Computability.VPVNP.PairShrinkRoleCanonicalInvariant
+local notation "Origin" => rowOrigin (p := p) site ord dfs reg ready xs es
+
+set_option quotPrecheck false in
+local notation "chosenOld" => oldFields (term := termAt) X v ((readerAt).order.children v) xs
+local notation "chosenHidden" => hiddenFields X side widths v site.seed es
+local notation "J" => jobs chosenOld parent
+
+set_option maxHeartbeats 2200000 in
+-- Each resident half is transported along its actual packed site.
+theorem origin_packets (o : Origin)
+ (space : ∀ old q, ShrinkCanonicalJob.PacketSpace B i X sel q.1.1 q.1.2 (jobs old parent q)
+ n site.limit)
+ (oldNodes : ∀ u, childNode X site.older B.recordLimit u < site.rowEnd)
+ (parentFit : addr < site.rowEnd) (earlier : ∀ u, childNode X site.older B.recordLimit u < addr)
+ (wire : X.maxWireWidth ≤ n) (size : ∀ m t, widths m (!side, t) ≤ n ^ 2)
+ (room : heap + (ShrinkHistoryRows.hiddenOrder X).length * n ^ 2 ≤ 2 ^ w)
+ (baseEq : site.hiddenArgs.scratchBase = heap) (strideEq : site.hiddenArgs.slotStride = n ^ 2)
+ (stored : ∀ s, ready s → (Packet.mk addr (packed (Y) v parent)).Stored (regions).arguments s)
+ (orderAt : ∀ node : Word w, node.val = addr →
+ (site.descriptor node).sites =
+ List.ofFn fun j => (((readerAt).order.children v).entries j).val)
+ (q : X.packingData.ResidentMap side v) :
+ (J q).Packets n o.entry.privateMem ∧ (J q).ChildWords o.entry.privateMem n ∧
+ ShrinkCallSupplyCells.Absorbed X side widths q.1.1 q.1.2 (J q).scratch
+ (q.2.symm ▸ chosenHidden) o.entry.privateMem ∧
+ (∀ u, (J q).arena.base ((J q).nodes u) + (J q).arena.stride ≤ (J q).scratch.hist) ∧
+ (J q).arena.base (J q).node + (J q).arena.stride ≤ (J q).scratch.hist := by
+ have child := children_oldFields (term := termAt) X v ((readerAt).order.children v) xs
+ (o.sites.trans (orderAt o.node o.atRow))
+ have abs := rows_hiddenFields X side widths v site.hiddenArgs site.mem site.seed es
+ o.node o.parsed
+ have inputs := ShrinkSiteBank.initialPackets B f hf i X sel site.workspace site.positions
+ site.blocks site.cur site.bounds n site.rowEnd site.older site.later site.limit v chosenOld
+ parent
+ chosenHidden q o.before xs es child abs (space chosenOld q) oldNodes parentFit
+ earlier wire
+ (stored _ o.prepared) size room
+ rw [o.operands.memory, baseEq, strideEq]
+ exact inputs
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRolePackedChildren.lean b/lean/OAI/Computability/VPVNP/PairShrinkRolePackedChildren.lean
new file mode 100644
index 0000000000..4c9e5bd526
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRolePackedChildren.lean
@@ -0,0 +1,223 @@
+import OAI.Computability.VPVNP.PairShrinkPackedRows
+import OAI.Computability.VPVNP.PairShrinkOldHalfAddresses
+import OAI.Computability.VPVNP.PairShrinkRoleChildDescriptor
+import OAI.Computability.VPVNP.PairSimulationMapResidentRows
+import OAI.Computability.VPVNP.PairTerminalSiteDirectories
+import OAI.Computability.VPVNP.PairVertexCompiledPayload
+import OAI.Computability.VPVNP.PairShrinkRolePackedRow
+import OAI.Computability.VPVNP.PairShrinkRolePackedNumeric
+
+/-!
+# The child directory of a packed shrinking visit
+
+The producing level publishes seven child operands. The selected traversal
+writes the children in placement-fiber order. Together these give the row
+descriptor and its actual readback at a later physical vertex call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.PackedChildren
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TraversalControllerInputs NodeArguments NodeArguments.ChildScan
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TerminalProgram
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+/-- The published count of old incidences is the count in the input-state incidence model. -/
+private theorem old_count {a g : ℕ} (Z : State a (packingLaneBits a g)) :
+ DemandRAM.oldCount Z = Z.positions * 2 ^ a := by
+ rw [State.positions, Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv _), Fintype.card_fin]
+
+private theorem payload_width {a g : ℕ} (Z : State a g) (v : Z.network.Site) :
+ ChildArguments.width Z v ≤ 2 * (2 ^ a) * Z.maxWireWidth := by
+ let zero : Z.network.Half v := ⟨fun _ _ _ => false, fun _ _ _ => false⟩
+ have size := Child.payload_length Z (Child.ofHalf Z v zero)
+ rw [Child.payload_ofHalf] at size
+ exact size.symm.trans_le (packed_length_le Z v zero)
+
+/-- The child-stage premises needed by the physical site reader. -/
+structure Ready {w a g : ℕ} (Z : State a g) (regions : LeafArena.Regions)
+ (inc : IncidenceDirectory w) (m : Memory w) (older cap n addr : ℕ) (level : Word w)
+ (desc : Word w → ChildArguments.Descriptor w Z) : Prop where
+ columns : inc.ActualColumns Z m
+ strideFit : cap + 2 < 2 ^ w
+ above : n ≤ NativeFrame.frameBase regions
+ frameRoom : NativeFrame.frameBase regions + 12 ≤ 2 ^ w
+ headRoom : level.val + 38 < 2 ^ w
+ directory : ∀ node : Word w, node.val = addr →
+ (desc node).directoryBase = level + 14 ∧
+ ChildArguments.Resident regions.arguments inc m older cap n node (desc node)
+ bounds : ∀ node : Word w, node.val = addr → ∀ u ∈ (desc node).sites,
+ childNode Z older cap u < regions.nodes ∧ n < regions.arguments.base (childNode Z older cap u)
+
+variable {K R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+variable {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => selected B f hf T hT X z
+local notation "rows" => selectedLayers B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+
+variable {G : Group} {n : ℕ} (cur : Fin (executeLevels B f hf T hT X z).length)
+variable (i : Fin S.steps) {g : ℕ}
+variable (Z : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g))
+variable (sel : SelectedScore.Selection B Z) (tape : List Bool)
+variable (occurrence : (executeLevels B f hf T hT X z)[cur] = shrinkLevel B f hf i Z sel tape)
+
+local notation "pub" => terminalOperands G
+local notation "L" => BlockProgram.layout B (terminalOperands G 2).val X.positions T
+local notation "firstRow" => endAddress L
+local notation "rowEnd" => firstRow + words B.recordLimit rows
+local notation "old" => layerBase B.recordLimit firstRow tags cur.val
+local notation "later" => layerBase B.recordLimit firstRow tags (cur.val + 1)
+local notation "inc" => packedIncidence L G.w cur.val (Z.positions * 2 ^ ShrinkBlockInputs.a i)
+local notation "area" =>
+ TerminalLayout.privateRegions (slotDegree S) n (rowEnd) (Fintype.card B.Entry)
+
+variable {baseBits laneBits ord : ℕ}
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+variable {calendar reference phy : Memory G.w}
+variable {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+variable (entry : VertexEntry B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+variable (pack : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+variable (frame : LinkedVertexMemory G reference ord phy)
+
+include occurrence in
+/-- The private child argument interval is strictly above the geometry pointer
+and ends below the histogram for every input site, including all members of
+the selected fiber. -/
+theorem child_geometry (maxWidth : Z.maxWireWidth ≤ n)
+ (frameRoom : NativeFrame.frameBase area + 12 ≤ 2 ^ G.w) (u : Z.network.Site) :
+ let child := childNode Z old B.recordLimit u
+ child < (area).nodes ∧ n < (area).arguments.base child ∧
+ ChildArguments.width Z u ≤ (area).arguments.stride ∧
+ (area).arguments.base child + ChildArguments.width Z u < 2 ^ G.w := by
+ intro child
+ have below : child < rowEnd := by
+ rw [show child = _ from ShrinkOldHalves.Physical.childNode_eq Z old B.recordLimit u]
+ exact ShrinkPackedRows.packed_shrink_address B f hf T hT X z (pub 2).val cur i Z sel tape
+ occurrence u
+ have low : firstRow ≤ child := by
+ change firstRow ≤ firstRow + _ + _
+ omega
+ have degree : 2 ^ ShrinkBlockInputs.a i ≤ slotDegree S :=
+ (shrinkLevel B f hf i Z sel tape).oldDegree_le
+ have len : ChildArguments.width Z u ≤ (area).arguments.stride :=
+ (payload_width Z u).trans ((Nat.mul_le_mul (Nat.mul_le_mul_left 2 degree) maxWidth).trans
+ (Nat.le_succ _))
+ have hist : (area).histBase < 2 ^ G.w := by
+ unfold NativeFrame.frameBase at frameRoom
+ omega
+ exact ⟨below, TerminalLayout.geometryPointer_before_node L low, len,
+ ((Nat.add_le_add_left len _).trans ((area).node_before below)).trans_lt hist⟩
+
+include pack in
+/-- The stride and exclusive end fit the actual machine word, including the
+first nonempty cursor layer. -/
+theorem row_fit :
+ B.recordLimit + 2 < 2 ^ G.w ∧ layerBase B.recordLimit firstRow tags ((passes).length + 1) <
+ 2 ^ G.w := by
+ have packedRoom := pack.arena
+ have endEq : tagWords B.recordLimit tags = words B.recordLimit rows :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ rw [endEq] at packedRoom
+ have room : rowEnd < 2 ^ G.w := calc
+ _ ≤ firstRow + 2 * words B.recordLimit rows + (Y).totalWidth := by omega
+ _ ≤ (vertexHeader G).val := packedRoom
+ _ < _ := (vertexHeader G).isLt
+ have positive : 1 ≤ ((rows).map Layer.count).sum := by
+ rw [selected_layer_counts B f hf T hT X z, List.sum_cons]
+ exact (Nat.succ_le_of_lt X.positions_pos).trans (Nat.le_add_right _ _)
+ have stride := Nat.mul_le_mul_left (B.recordLimit + 2) positive
+ rw [Nat.mul_one] at stride
+ have count : (tags).length = (passes).length + 1 := by simp [selected]
+ rw [← count, layerBase, List.take_length, selected_layers]
+ exact ⟨(stride.trans (Nat.le_add_left _ _)).trans_lt room, room⟩
+
+local notation "level" => levelHead pub phy cur.val
+
+set_option maxHeartbeats 1500000 in
+-- The native memory predicates have dependent types indexed by the chosen compression term.
+include occurrence entry pack frame in
+/-- At the real packed vertex call, the retained source supplies the incidence
+columns and seven directory operands. The stored traversal supplies the popped
+row and the exact ordered child words. The two numeric hypotheses hold
+simultaneously for all occurrences by `eventually_geometry`. -/
+theorem of_payload
+ (data : CompiledResident.ShrinkPayload B (pub 2) X.positions T n cur.val i Z sel phy)
+ (site : MapResidentRows.Site Z) (maxWidth : Z.maxWireWidth ≤ n)
+ (frameRoom : NativeFrame.frameBase area + 12 ≤ 2 ^ G.w) :
+ let desc := descriptor level (oldSites B f hf i Z sel site)
+ let target := address B.recordLimit later (MapResidentRows.siteIndex Z site).val
+ Ready Z area inc phy old B.recordLimit n target level desc := by
+ intro desc target
+ have live : (passes).length < (L).levels :=
+ (executeLevels_length B f hf T hT X z).trans_lt (by rw [BlockProgram.actual_level_count]; omega)
+ obtain ⟨low, high⟩ := pack.traversal_frames frame
+ have wide : 28 ≤ (L).shape.scalarFields := by change 28 ≤ 54; decide
+ obtain ⟨ds, stored⟩ := entry.site_directories live wide low high
+ have head := entry.site_level_head live wide low high cur.val cur.isLt.le
+ have baseCell : phy (levelStart L cur.val + 14) = (old : Word G.w) := by
+ have cell := stored.currentBase cur.val (by
+ simpa only [levelFibers, List.length_ofFn] using cur.isLt.le)
+ rw [levelFibers_tags passes ds] at cell
+ simpa only [levelStart, Nat.zero_mul, Nat.add_zero, TraversalRoles.selected] using cell
+ have operands : (ChildScan.directory (ShrinkBlockInputs.a i) old B.recordLimit
+ (area).arguments inc).Stored phy (level + 14) := by
+ rw [head.1]
+ exact data.child.bank old baseCell
+ have cols := data.sources.old.incidence
+ rw [old_count Z] at cols
+ have layers := selected_layers B f hf T hT X z
+ have rowMem := pack.rows frame (layers ▸ selected_capacity B f hf T hT X z)
+ (layers ▸ entry.rows)
+ rw [layers] at rowMem
+ have row := selectedChildRow B f hf T hT X z i Z sel tape cur occurrence rowMem site
+ have caps := row_fit B f hf T hT X z pack
+ have rowEndFit : rowEnd < 2 ^ G.w := by
+ have count : (tags).length = (passes).length + 1 := by simp [selected]
+ simpa only [← count, layerBase, List.take_length, layers] using caps.2
+ have child := child_geometry B f hf T hT X z cur i Z sel tape occurrence maxWidth frameRoom
+ have oldRoom : levelStart L cur.val + 65 < 2 ^ G.w := data.words.oldRoom
+ have headRoom : (level).val + 38 < 2 ^ G.w := by rw [head.2]; omega
+ have above : n ≤ (area).histBase := Nat.le_add_right _ _
+ refine ⟨cols, caps.1, above.trans (Nat.le_add_right _ _), frameRoom, headRoom, ?_, ?_⟩
+ · intro node addr
+ refine ⟨rfl, operands, ?_, fun u _ => (child u).1.trans rowEndFit,
+ fun u _ => (child u).2.1.le, fun u _ => (child u).2.2.1, fun u _ => (child u).2.2.2⟩
+ change DFS.Row phy node.val (node.val + 2)
+ ((oldSites B f hf i Z sel site).map fun u => (childNode Z old B.recordLimit u : Word G.w))
+ rw [addr]
+ exact row
+ · exact fun _ _ u _ => ⟨(child u).1, (child u).2.1⟩
+
+include occurrence entry pack frame in
+/-- The packed child certificate is available at any later physical site,
+directly from the calendar's retained payloads and the linked vertex frame. -/
+theorem atVertex
+ (history : SelectedPayloadHistory.Past B f hf L
+ (CompiledResident.payload B f hf (pub 2) X.positions T n) passes calendar)
+ (site : MapResidentRows.Site Z) (maxWidth : Z.maxWireWidth ≤ n)
+ (frameRoom : NativeFrame.frameBase area + 12 ≤ 2 ^ G.w) :
+ let desc := descriptor level (oldSites B f hf i Z sel site)
+ let target := address B.recordLimit later (MapResidentRows.siteIndex Z site).val
+ Ready Z area inc phy old B.recordLimit n target level desc := by
+ have data := CompiledResident.shrink_vertex history entry pack frame cur occurrence
+ exact of_payload B f hf T hT X z cur i Z sel tape occurrence entry pack frame data site
+ maxWidth frameRoom
+
+end PairSimulation.ShrinkRole.PackedChildren
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRolePackedHidden.lean b/lean/OAI/Computability/VPVNP/PairShrinkRolePackedHidden.lean
new file mode 100644
index 0000000000..5ba0bbcd9d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRolePackedHidden.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.CompressorCompiledResident
+import OAI.Computability.VPVNP.PairShrinkRoleMapStart
+import OAI.Computability.VPVNP.PairShrinkCallABI
+import OAI.Computability.VPVNP.PairShrinkHiddenRows
+import OAI.Computability.VPVNP.PairShrinkHiddenInputs
+
+/-!
+# The selected shrinking site's hidden arguments in the packed calendar
+
+The compressor stores the count and identifier row for each owner. The same
+level stores the selected term words and the five pointers used by the site's
+hidden-field reader. A zero assignment supplies the parser with the exact
+field lengths and identifiers for arbitrary later guesses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkRole.PackedHidden
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords DescriptorSpace
+open ShrinkBlockInputs ShrinkSliceSweep ShrinkHistoryRows ShrinkHiddenGuess NetworkKernel
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (i : Fin S.steps)
+ {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+ (base : Word w) (positions blocks cur n : ℕ)
+
+local notation "D" => BlockProgram.layout B base.val positions blocks
+local notation "head" => levelStart D cur
+local notation "tab" => (fun j : Fin 6 => tableBase D cur j)
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "role" => SelectedArena.roleBase X term (10 : Word w)
+local notation "side" => SelectedFinish.chosen B X sel
+local notation "widths" => ShrinkHiddenRows.widths X B.shrink sel
+local notation "L" => ShrinkResidentLayout.layout X (tab 5)
+local notation "params" => (L).params (a i) false w
+local notation "T" => ShrinkOutput.splitBank (b := b i) X B.shrink sel term 10 role (tab 2)
+local notation "siteType" => MapResidentRows.Site X
+
+/-- These words are obtained from the current level, the packed site ordinal,
+and the argument frame at the actual vertex. -/
+abbrev arguments (R : LeafArena.Regions) (v : siteType) : Args w :=
+ ShrinkHiddenRows.args X T params v (ShrinkCallABI.hiddenBase R n) (n * n)
+
+/-- The identifiers and lengths are independent of the guessed hidden values. -/
+def zeroRows (v : siteType) : List Row :=
+ ShrinkHiddenSlots.rows X side widths v (fun _ _ => ⟨0, Nat.two_pow_pos _⟩)
+
+variable (R : LeafArena.Regions) (v : MapResidentRows.Site X)
+local notation "arg" => arguments B i X sel base positions blocks cur n R v
+local notation "seed" => zeroRows B i X sel v
+
+/-- Inputs required by the physical hidden reader, for this exact packed site. -/
+structure Facts (m : Memory w) : Prop where
+ selectors : (arg).selectorBits = (B.shrink.selectorBits : Word w)
+ rowStride : (arg).rowStride = ShrinkVertexImage.hiddenStride i
+ headRoom : head + 38 < 2 ^ w
+ headers : Header.Published arg head m
+ countFit : (arg).countBase + (arg).owner < 2 ^ w
+ count : (m ((arg).countBase + (arg).owner)).val = (seed).length
+ valid : ValidRows arg m seed
+ scratch : (arg).scratchBase = ShrinkCallABI.hiddenBase R n
+ pitch : (arg).slotStride = n * n
+ owner : (arg).owner = (MapResidentRows.siteIndex X v).val
+
+set_option maxHeartbeats 2000000 in
+-- The selected split bank and packed owner order are dependent on the stage exponent.
+/-- Recover every external input from the native compressor payload. The only
+additional bounds here concern the post-stack private reservation and the
+fixed selector literal. -/
+theorem of_payload (m : Memory w)
+ (payload : CompiledResident.ShrinkPayload B base positions blocks n cur i X sel m)
+ (selectors : B.shrink.selectorBits < 2 ^ w)
+ (slots : ∀ motif t, widths motif (!side, t) ≤ n * n)
+ (space : ShrinkCallABI.hiddenBase R n + (hiddenOrder X).length * (n * n) < 2 ^ w) :
+ Facts B i X sel base positions blocks cur n R v m := by
+ classical
+ have room := payload.words.oldRoom
+ have h10 : (10 : Word w).val = 10 := Nat.mod_eq_of_lt (show 10 < 2 ^ w by omega)
+ have splitRoom := payload.bounds.packedRoom
+ rw [h10] at splitRoom
+ have allocation : (T).Fits := ShrinkOutput.fits X B.shrink sel term 10 role (tab 2)
+ (S.shrink i) (by decide) splitRoom
+ have residentFit : (L).endAddr < 2 ^ w :=
+ payload.bounds.residentEnd.trans_lt
+ ((levelStart_mono D payload.bounds.nextLive.le).trans_lt payload.bounds.room)
+ have terms : Terms X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) T
+ B.shrink X.packingWidth sel m := by
+ intro idx
+ let motif := (ShrinkMotifOrder.stateNumber X).symm idx
+ have h := payload.sources.terms motif
+ have e : ShrinkTermSelection.rowBase X term 10 motif =
+ Fin.ofNat (2 ^ w) ((term).val + idx.val * 10) := by
+ simp only [ShrinkTermSelection.rowBase, motif, Equiv.apply_symm_apply]
+ rw [e] at h
+ exact h
+ have dir : Directory (hiddenOrder X) (packedOrder X) (X.packingData.shrinkInternalOwner side)
+ params m := payload.sources.residents false
+ have selected : (T).selectors.val = B.shrink.selectorBits := Nat.mod_eq_of_lt selectors
+ let h : Placed (X.packingData.shrinkInternalOwner side) (internalLabel widths side) v :=
+ fun _ _ => ⟨0, Nat.two_pow_pos _⟩
+ obtain ⟨countFit, rowFit⟩ := ShrinkHiddenRows.directory_fit X T (tab 5) v residentFit
+ (ShrinkCallABI.hiddenBase R n) (n * n) widths h
+ obtain ⟨_, _, _, _, counts, stride, rows⟩ :=
+ ShrinkResidentLayout.frame X (tab 5) false residentFit
+ have headAt (j : ℕ) (hj : j ≤ 65) : ((head : Word w) + (j : Word w)).val = head + j := by
+ rw [← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ have hdr : Header.Published arg head m := by
+ refine ⟨?_, ?_, ?_, ?_, ?_⟩
+ · change m (head + 31) = (((params 3).val : ℕ) : Word w)
+ rw [counts]
+ exact payload.words.residentHeads 1
+ · change m (head + 32) = (((params 5).val : ℕ) : Word w)
+ rw [rows]
+ exact payload.words.residentHeads 2
+ · rw [← headAt 36 (by decide)]
+ exact payload.words.level.termHead.trans (Fin.cast_val_eq_self _).symm
+ · rw [← headAt 37 (by decide)]
+ exact payload.words.level.termStride
+ · rw [← headAt 38 (by decide)]
+ exact payload.words.level.layout
+ exact ⟨rfl, stride, by omega, hdr, countFit,
+ ShrinkHiddenRows.count X T params m dir widths v h _ _,
+ ShrinkHiddenRows.valid_rows X B.shrink sel T params m terms allocation selected dir v h
+ _ _ slots space rowFit.le, rfl, rfl, rfl⟩
+
+end PairSimulation.ShrinkRole.PackedHidden
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRolePackedNumeric.lean b/lean/OAI/Computability/VPVNP/PairShrinkRolePackedNumeric.lean
new file mode 100644
index 0000000000..d42ad91723
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRolePackedNumeric.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory
+import OAI.Computability.VPVNP.PairShrinkCallCapacity
+import OAI.Computability.VPVNP.PairTerminalPackedBudget
+
+/-! # Word and wire bounds for the children of a packed shrinking pass -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.PackedChildren
+
+open Compression CompressorRecords CursorBounds CursorNetwork DescriptorSpace Filter TraversalRows
+
+/-- One input-length threshold fits the twelve geometry words and every selected
+shrinking input's wire widths, uniformly in the specialization and branch. -/
+theorem eventually_geometry {k : Type} [_root_.Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (b : ℕ)
+ (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hstart : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let L := BlockProgram.layout B (start n) X.positions T
+ ∀ z : (B.execute f hf T hT X).Choices,
+ let passes := executeLevels B f hf T hT X z
+ let rows := words B.recordLimit (selectedLayers B f hf T hT X z)
+ let regions := TerminalLayout.privateRegions (slotDegree S) n
+ (endAddress L + rows) (Fintype.card B.Entry)
+ ∀ (j : Fin passes.length) (i : Fin S.steps) {g : ℕ}
+ (Z : State (S.degreeExponent i.castSucc)
+ (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : SelectedScore.Selection B Z) (bits : List Bool),
+ passes[j] = shrinkLevel B f hf i Z sel bits →
+ Z.maxWireWidth ≤ n ∧ NativeFrame.frameBase regions + 12 ≤ 2 ^ wordBits b n := by
+ filter_upwards [ShrinkCallCapacity.eventually_levels B u b hb 1,
+ TerminalLayout.eventually_packedFit B u b hb hstart 0 (fun _ ↦ 0)
+ (PolynomiallyBounded.const 0)] with n levels fit
+ intro base lanes labels hD hT A _ f hf X T L z passes rows regions j i g Z sel bits atPass
+ have width := (levels labels hD hT A f hf z passes[j] (List.getElem_mem j.isLt)).2
+ rw [atPass, Nat.one_mul] at width
+ refine ⟨(Nat.le_succ Z.maxWireWidth).trans width, ?_⟩
+ have packed := fit labels hD hT A f hf z
+ have positions : X.positions = initialPositions b n := pairInput_positions S labels hD
+ dsimp only [regions, L]
+ rw [positions]
+ exact (packed.2.2.1.trans (Nat.le_add_right _ 38)).trans (by
+ simpa only [Nat.zero_mul, Nat.add_zero, LeafArena.Regions.stackBase] using packed.2.2.2.1.le)
+
+end PairSimulation.ShrinkRole.PackedChildren
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRolePackedRow.lean b/lean/OAI/Computability/VPVNP/PairShrinkRolePackedRow.lean
new file mode 100644
index 0000000000..8375846f4c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRolePackedRow.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.CompressorRecordRefreshArgumentAddress
+import OAI.Computability.VPVNP.CompressorRefreshTraversalChild
+import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory
+import OAI.Computability.VPVNP.PairNodeChildPackets
+import OAI.Computability.VPVNP.PairSimulationMapResidentRows
+
+/-! # The ordered child addresses stored at a selected shrinking site -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression CompressorRecords LocalHistory TraversalRows TraversalRoles
+open NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private successor_rows from OAI.Computability.VPVNP.CompressorRefreshTraversalChild
+open private next_number from OAI.Computability.VPVNP.CompressorRecordsShrinkPreimages
+
+variable {K R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+ (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (initial : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT initial).Choices)
+ (i : Fin S.steps) {g : ℕ}
+ (Z : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : Z.ShrinkSelection B.shrink) (bits : List Bool)
+
+/-- The old sites at a packed site, in the order consumed by the kernel's child reader. -/
+noncomputable abbrev oldSites (site : MapResidentRows.Site Z) : List Z.network.Site :=
+ List.ofFn fun j => ((((shrinkPassReaders B f hf i rfl Z).order sel).children site).entries j).val
+
+/-- The successor's argument ordinal is the packed-site index used by the resident map rows. -/
+@[simp] theorem shrinkSiteOrdinal_eq (site : MapResidentRows.Site Z) :
+ PortRefresh.ArgumentAddress.siteOrdinal (Z.shrinkNext B.shrink (S.shrink i) sel) site =
+ (MapResidentRows.siteIndex Z site).val := by
+ let Y := Z.shrinkNext B.shrink (S.shrink i) sel
+ apply Eq.trans _ (next_number Z B.shrink (S.shrink i) sel (packedSiteEquiv.symm site))
+ change (Y.baseIndex site.1).val * 2 ^ g + (bitWordFinEquiv g site.2).val =
+ (bitWordFinEquiv g site.2).val + 2 ^ g * (Y.baseIndex site.1).val
+ ac_rfl
+
+local notation "level" => shrinkLevel B f hf i Z sel bits
+local notation "passes" => executeLevels B f hf T hT initial z
+local notation "tags" => TraversalRoles.selected B f hf T hT initial z
+
+set_option maxHeartbeats 2000000 in
+-- Identifying the child list reduces the scheduled pass's dependent site and order transports.
+private theorem packedRow {w cap older later : ℕ} {mem : Memory w}
+ (rows : (levelLayer B f hf level).Rows w mem cap older later) (site : MapResidentRows.Site Z) :
+ let addr := address cap later (MapResidentRows.siteIndex Z site).val
+ DFS.Row mem addr (addr + 2) ((oldSites B f hf i Z sel site).map fun u =>
+ (childNode Z older cap u : Word w)) := by
+ let out := siteOrder (Z.shrinkNext B.shrink (S.shrink i) sel)
+ let idx := out.entries.symm site
+ have ord : idx.val = (MapResidentRows.siteIndex Z site).val :=
+ next_number Z B.shrink (S.shrink i) sel (packedSiteEquiv.symm site)
+ have row := (rows idx).2
+ change DFS.Row mem (address cap later idx.val) (address cap later idx.val + 2)
+ ((List.ofFn fun j => ((siteOrder Z).entries.symm
+ ((((shrinkPassReaders B f hf i rfl Z).order sel).children
+ (out.entries idx)).entries j).val).val).map
+ fun id => (address cap older id : Word w)) at row
+ rw [show out.entries idx = site from Equiv.apply_symm_apply .., ord] at row
+ simpa only [oldSites, List.map_ofFn, Function.comp_def, childNode, sitePointers] using row
+
+/-- The physical DFS row contains precisely the ordered old-site fiber of this occurrence.
+Each child word points into the preceding selected layer at that site's ordinal. -/
+theorem selectedChildRow (stage : Fin (passes).length)
+ (occurrence : (passes)[stage] = level) {w base : ℕ} {mem : Memory w}
+ (rows : AllRows w mem B.recordLimit base base (selectedLayers B f hf T hT initial z))
+ (site : MapResidentRows.Site Z) :
+ let older := layerBase B.recordLimit base tags stage.val
+ let later := layerBase B.recordLimit base tags (stage.val + 1)
+ let addr := address B.recordLimit later (MapResidentRows.siteIndex Z site).val
+ DFS.Row mem addr (addr + 2) ((oldSites B f hf i Z sel site).map fun u =>
+ (childNode Z older B.recordLimit u : Word w)) := by
+ have all : AllRows w mem B.recordLimit base base ((tags).map TaggedLayer.layer) := by
+ rwa [selected_layers]
+ have bound : stage.val + 1 < (tags).length := by simp [TraversalRoles.selected]
+ have atLevel : (tags)[stage.val + 1].layer = levelLayer B f hf level := by
+ simp only [TraversalRoles.selected, List.getElem_cons_succ, List.getElem_map]
+ exact congrArg (levelLayer B f hf) occurrence
+ have atRow := successor_rows all stage.val bound
+ rw [atLevel] at atRow
+ exact packedRow B f hf i Z sel bits atRow site
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleParent.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleParent.lean
new file mode 100644
index 0000000000..795583ccb1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleParent.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.PairRefreshHalfDecoder
+
+/-!
+# Selecting a shrinking node's stored parent argument
+
+The current site's packed packet fixes its full outgoing and incoming half-wire
+assignment. Its native parser can therefore use the corresponding typed map jobs
+for all field choices on the incoming tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM Compression NodeArguments DFS
+open scoped Fin.CommRing
+
+variable {w n a g p r k : ℕ} (Y : State a g) (v : Y.network.Site) (A : Arena)
+ (family : Y.network.Half v → HookParser w n)
+
+/-- Read the packed output half at the popped descriptor's actual address. -/
+noncomputable def parentParser : HookParser w n where
+ read node s bits := (RefreshHalfDecoder.parent Y v A node.val s).bind
+ fun z => (family z).read node s bits
+
+theorem parentParser_read (node : Word w) (s : Scratch w n) (z : Y.network.Half v)
+ (stored : (Packet.mk node.val (packed Y v z)).Stored A s) (positive : 0 < w)
+ (bits : List Bool) :
+ (parentParser Y v A family).read node s bits = (family z).read node s bits := by
+ simp only [parentParser, RefreshHalfDecoder.parent_eq Y v A node.val s z stored positive,
+ Option.bind_some]
+
+/-- A single native parser handles every prepared value of the parent packet,
+including distinct independent endpoint assignments at the same physical row. -/
+theorem parentParser_exactOn (M : Machine w p r k) (visit ret : Fin p) (dfs : Fin 9 ↪ Fin r)
+ (m : Memory w) (positive : 0 < w) (address : ℕ) (ready : Y.network.Half v → Scratch w n → Prop)
+ (stored : ∀ z s, ready z s → (Packet.mk address (packed Y v z)).Stored A s)
+ (exactAt : ∀ z, (family z).ExactOn (fun node s => node.val = address ∧ ready z s)
+ M visit ret dfs m) :
+ (parentParser Y v A family).ExactOn (fun node s => node.val = address ∧ ∃ z, ready z s)
+ M visit ret dfs m := by
+ constructor
+ · rintro node s ⟨atRow, z, good⟩ bs job tail hit
+ rw [parentParser_read Y v A family node s z (atRow ▸ stored z s good) positive] at hit
+ exact (exactAt z).success node s ⟨atRow, good⟩ bs job tail hit
+ · rintro node bs c top pending ⟨atRow, z, good⟩ pc reg stack atEnd h5 h6 h3 fail
+ rw [parentParser_read Y v A family node _ z (atRow ▸ stored z _ good) positive] at fail
+ exact (exactAt z).reject node bs c top pending ⟨atRow, good⟩ pc reg stack atEnd h5 h6 h3 fail
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleParsed.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleParsed.lean
new file mode 100644
index 0000000000..4f9920316c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleParsed.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.PairShrinkRoleBind
+
+/-! # Retaining the actual argument of a successful native parse -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM DFS
+
+variable {w n p r k : ℕ} {α : Type*}
+
+/-- A concrete result of the reader on some finite input stream and entry scratch. -/
+def Parsed (reader : Reader w n α) (node : Word w) (x : α) : Prop :=
+ ∃ s bits out tail, reader node s bits = some (out, tail) ∧ out.value = x
+
+/-- In addition to the native postcondition, the continuation can use the fact
+that the data came from the very reader it is linked to. -/
+theorem Realizes.withParsed {reader : Reader w n α} {M : Machine w p r k} {m : Memory w}
+ {dfs : Fin 9 ↪ Fin r} {pre : Word w → Config w p r → Prop}
+ {post : α → Word w → Config w p r → Prop} (h : Realizes reader M m dfs pre post) :
+ Realizes reader M m dfs pre (fun x node c => post x node c ∧ Parsed reader node x) := by
+ refine ⟨?_, h.reject⟩
+ intro node c bs out tail hc read
+ obtain ⟨parts, d, done, frame, store, run⟩ := h.success node c bs out tail hc read
+ exact ⟨parts, d, ⟨done, _, bs, out, tail, read, rfl⟩, frame, store, run⟩
+
+theorem Parsed.afterSetup {reader : Reader w n α} {setup : Setup w n}
+ {node : Word w} {x : α} (h : Parsed (bind setup.reader (fun _ => reader)) node x) :
+ Parsed reader node x := by
+ obtain ⟨s, bs, out, tail, hit, value⟩ := h
+ change (reader node (setup.updated node s) bs).map _ = some (out, tail) at hit
+ obtain ⟨⟨v, rest⟩, done, eqn⟩ := Option.map_eq_some_iff.mp hit
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj eqn
+ exact ⟨_, bs, v, rest, done, value⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRolePhysicalHidden.lean b/lean/OAI/Computability/VPVNP/PairShrinkRolePhysicalHidden.lean
new file mode 100644
index 0000000000..7544873878
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRolePhysicalHidden.lean
@@ -0,0 +1,232 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCachedSetup
+import OAI.Computability.VPVNP.PairShrinkRoleHeaderSetup
+import OAI.Computability.VPVNP.PairShrinkRoleHidden
+import OAI.Computability.VPVNP.PairShrinkVertexLinks
+
+/-!
+# The absorbed-field scan in the selected shrinking stage
+
+The handoff saves the live hidden-field base in the shared locator bank.
+The header reads the selected old level and passes its directory to the
+guess loop. These two stages leave the entry scratch intact. The loop
+writes precisely the decoded fields and returns to the map reload.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM ShrinkHiddenGuess VertexImage VertexStagePrefix
+open Compression CompressorRecords ShrinkVertexImage
+open scoped Fin.CommRing
+
+variable {w p r endAddr : ℕ}
+
+/-- The geometry and located old level at the end of the child scan. -/
+structure PhysicalHiddenEntry (entry : Fin p) (dfs : Fin 9 ↪ Fin r) (loc : Fin 14 ↪ Fin r)
+ (g : Args w) (oldHead : ℕ) (c : Config w p r) : Prop where
+ pc : c.pc = entry
+ owner : c.reg (loc 7) = (g.owner : Word w)
+ oldLevel : c.reg (loc 11) = (oldHead : Word w)
+ base : let G := c.privateMem (c.reg (dfs 6))
+ VertexLevel.hiddenBaseWord (c.privateMem (G + 8)) (c.privateMem (G + 9)) =
+ (g.scratchBase : Word w)
+ stride : let G := c.privateMem (c.reg (dfs 6))
+ let n := c.privateMem (G + 9)
+ n * n = (g.slotStride : Word w)
+
+/-- The setup trace consists of the handoff ticks and the real compiler's
+five reads of the old level. -/
+noncomputable def physicalHiddenSetup (s t oldHead : ℕ) (m : Memory w) : Setup w endAddr :=
+ (Setup.ticks (VertexLevel.hiddenCount + 1)).seq (hiddenHeader s t oldHead m)
+
+private theorem setup_realizes_core {M : Machine w p r 11} {m : Memory w} (s t : ℕ)
+ (hp : Fin (VertexLevel.hiddenCount + 1) → Fin p)
+ (phasePC : Fin (Table.segmentCount s t) → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r) (loc : Fin 14 ↪ Fin r)
+ (prv : Fin (Table.R s t) ↪ Fin r) (ret : Fin p) (g : Args w) (oldHead : ℕ)
+ (load : ∀ j, M.code (hp j.castSucc) = VertexLevel.hiddenHandoff (hp ∘ Fin.castSucc) loc
+ ((Table.segmentInputs s t).trans prv) (dfs 6) (hp (Fin.last VertexLevel.hiddenCount)) j)
+ (copy : M.code (hp (Fin.last VertexLevel.hiddenCount)) = .copy (loc 8)
+ (prv (Table.segmentInputs s t 1)) (phasePC (Table.segment s t).entry))
+ (phase : ∀ j, M.code (phasePC j) =
+ ((Table.segment s t).row phasePC dfs saved prv ret j).resize w)
+ (freeLoc : ∀ j, loc j ∉ Set.range prv)
+ (safe : ∀ j : Fin 9, j = 3 ∨ j = 5 ∨ j = 6 ∨ j = 7 → dfs j ≠ loc 8 ∧ dfs j ∉ Set.range prv)
+ (selectors : g.selectorBits = (s : Word w)) (pitch : g.rowStride = t)
+ (fit : oldHead + 38 < 2 ^ w) (headers : Header.Published g oldHead m)
+ {pre post : Word w → Config w p r → Prop}
+ (start : ∀ node c, pre node c → PhysicalHiddenEntry (hp 0) dfs loc g oldHead c)
+ (finish : ∀ node c d, pre node c → d.pc = Table.segmentLoop s t phasePC (.inl .one) →
+ Inputs g ((Table.regs s t).trans prv) d → d.reg (loc 8) = (g.scratchBase : Word w) →
+ d.privateMem = c.privateMem → d.persistent = c.persistent →
+ (∀ q, q ≠ loc 8 → q ∉ Set.range prv → d.reg q = c.reg q) → post node d) :
+ Realizes (physicalHiddenSetup (endAddr := endAddr) s t oldHead m).reader M m dfs
+ pre (fun _ => post) := by
+ let src := (Table.segmentInputs s t).trans prv
+ let mid (node : Word w) (d : Config w p r) : Prop :=
+ d.pc = phasePC (Table.segment s t).entry ∧ Table.SegmentOperands s t prv g oldHead d ∧
+ d.reg (loc 8) = (g.scratchBase : Word w) ∧ ∃ c, pre node c ∧ d.privateMem = c.privateMem ∧
+ d.persistent = c.persistent ∧ ∀ q, q ≠ loc 8 → q ∉ Set.range prv → d.reg q = c.reg q
+ have boot : Realizes (Setup.ticks (endAddr := endAddr) (VertexLevel.hiddenCount + 1)).reader
+ M m dfs pre (fun _ => mid) := by
+ apply cachedHiddenHandoff_realizes (pre := pre) (post := mid) (pc := hp) (inputs := src)
+ load copy (fun a b e => freeLoc b ⟨Table.segmentInputs s t a, e⟩)
+ (fun j hj => ⟨(safe j hj).1, fun k e => (safe j hj).2 ⟨Table.segmentInputs s t k, e.symm⟩⟩)
+ (fun node c hc => (start node c hc).pc)
+ intro node c d hc G n atHead owner base stride level cached keep mem pers
+ have ready := start node c hc
+ refine ⟨atHead, ⟨level.trans ready.oldLevel, owner.trans ready.owner,
+ base.trans ready.base, stride.trans ready.stride⟩, cached.trans (base.trans ready.base),
+ c, hc, mem, pers, ?_⟩
+ intro q ne outside
+ have free (k : Fin 6) : q ≠ src k := fun e => outside ⟨Table.segmentInputs s t k, e.symm⟩
+ exact keep q ne (free 0) (free 1) (free 2) (free 5)
+ apply Setup.seq_realizes (b := hiddenHeader s t oldHead m) boot
+ apply hiddenHeader_realizes (pre := mid) (post := post) s t phasePC dfs saved prv ret phase g
+ oldHead selectors pitch fit headers
+ (fun j hj ⟨k, eqn⟩ => (safe j hj).2 ⟨Table.vm s t k, eqn⟩) (fun _ _ h => ⟨h.1, h.2.1⟩)
+ intro node d z hd atLoop values mem pers keep
+ obtain ⟨_, _, cached, c, hc, dm, dp, kept⟩ := hd
+ have frame (q : Fin r) (outside : q ∉ Set.range prv) : z.reg q = d.reg q :=
+ keep q fun ⟨k, eqn⟩ => outside ⟨Table.vm s t k, eqn⟩
+ exact finish node c z hc atLoop values ((frame _ (freeLoc 8)).trans cached)
+ (mem.trans dm) (pers.trans dp) (fun q hq outside => (frame q outside).trans (kept q hq outside))
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps) (M : Machine w p r 11)
+ (pc : Fin (shrinkSegment B ord).count → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r) (done : Fin p)
+ (installed : ∀ j, M.code (pc j) = ((shrinkSegment B ord).row pc dfs saved reg done j).resize w)
+ (separate : ∀ j : Fin 9, j = 3 ∨ j = 5 ∨ j = 6 ∨ j = 7 → ∀ k, dfs j ≠ reg k)
+ (m : Memory w) (g : Args w) (oldHead : ℕ)
+ (selectors : g.selectorBits = (B.shrink.selectorBits : Word w))
+ (pitch : g.rowStride = hiddenStride i) (fit : oldHead + 38 < 2 ^ w)
+ (headers : Header.Published g oldHead m)
+ {pre : Word w → Config w p r → Prop}
+
+attribute [local irreducible] ShrinkVertexImage.maps
+
+local notation "s" => B.shrink.selectorBits
+local notation "t₀" => hiddenStride i
+local notation "lr" => LocatedBody.commonLocator (active B ord) reg
+local notation "prv" => hiddenRegs B ord i reg
+local notation "locPC" => hiddenPC B ord i pc
+private noncomputable abbrev preparationPC (j : Fin (VertexLevel.hiddenCount + 1)) : Fin p :=
+ (hiddenPrep B ord i).setupPC (afterChildPC B ord i pc) j
+local notation "handoff" => preparationPC B ord i pc
+private noncomputable abbrev reloadEntry := reloadPC B ord i pc (mapReload B ord i).code.entry
+local notation "reloadDest" => reloadEntry B ord i pc
+local notation "loop" => Table.segmentLoop s t₀ locPC
+private noncomputable abbrev scanBank := (Table.regs s t₀).trans prv
+local notation "bank" => scanBank B ord i reg
+
+private theorem loc_free (j : Fin 14) : lr j ∉ Set.range prv := by
+ rintro ⟨k, h⟩
+ exact Preparation.disjoint (afterChildRegs B ord i reg) k ((mapReload B ord i).locator j)
+ (h.trans (map_locator_shared B ord i reg j).symm)
+
+private theorem scan_free (q : Fin r) (h : q ∉ Set.range prv) : HiddenPreserved bank q := by
+ have free (k : Fin 22) : q ≠ bank k := fun eqn => h ⟨Table.regs s t₀ k, eqn.symm⟩
+ exact ⟨free _, free _, fun j _ => free j⟩
+
+private noncomputable abbrev hiddenInputs := (Table.segmentInputs s t₀).trans prv
+local notation "src" => hiddenInputs B ord i reg
+
+include installed in
+private theorem handoffLinks :
+ (∀ j, M.code (handoff j.castSucc) = VertexLevel.hiddenHandoff (handoff ∘ Fin.castSucc) lr
+ src (dfs 6) (handoff (Fin.last VertexLevel.hiddenCount)) j) ∧
+ M.code (handoff (Fin.last VertexLevel.hiddenCount)) =
+ .copy (lr 8) (src 1) (locPC (Table.segment s t₀).entry) := by
+ let physical := (mapReload B ord i).locator.trans (reloadRegs B ord i reg)
+ have locEq : physical = lr := DFunLike.ext _ _ (map_locator_shared B ord i reg)
+ have rows := ShrinkVertexStage.prepare_rows s t₀ (mapReload B ord i) M
+ (afterChildPC B ord i pc) dfs saved (afterChildRegs B ord i reg) done
+ (after_child_rows B ord i M pc dfs saved reg done installed)
+ constructor
+ · intro j
+ apply (rows.1 j).trans
+ exact congrArg (fun l => VertexLevel.hiddenHandoff (handoff ∘ Fin.castSucc) l src (dfs 6)
+ (handoff (Fin.last VertexLevel.hiddenCount)) j) locEq
+ · apply rows.2.1.trans
+ exact congrArg (fun l : Fin 14 ↪ Fin r => Instr.copy (w := w) (k := 11) (l 8) (src 1)
+ (locPC (Table.segment s t₀).entry)) locEq
+
+include separate in
+private theorem protectedDFS (j : Fin 9) (hj : j = 3 ∨ j = 5 ∨ j = 6 ∨ j = 7) :
+ dfs j ≠ lr 8 ∧ dfs j ∉ Set.range prv := by
+ refine ⟨separate j hj (LocatedBody.commonLocator (active B ord)
+ (Function.Embedding.refl _) 8), ?_⟩
+ rintro ⟨k, e⟩
+ exact separate j hj (hiddenRegs B ord i (Function.Embedding.refl _) k) e.symm
+
+include installed separate selectors pitch fit headers in
+/-- Link the selected image's setup rows to the native header and retain
+the cached field base, all exterior registers, and the original private memory. -/
+theorem physicalHiddenSetup_realizes
+ (start : ∀ node c, pre node c → PhysicalHiddenEntry (handoff 0) dfs lr g oldHead c)
+ {post : Word w → Config w p r → Prop}
+ (finish : ∀ node c d, pre node c → d.pc = loop (.inl .one) → Inputs g bank d →
+ d.reg (lr 8) = (g.scratchBase : Word w) → d.privateMem = c.privateMem →
+ d.persistent = c.persistent →
+ (∀ q, q ≠ lr 8 → q ∉ Set.range prv → d.reg q = c.reg q) → post node d) :
+ Realizes (physicalHiddenSetup (endAddr := endAddr) s t₀ oldHead m).reader M m dfs
+ pre (fun _ => post) := by
+ have links := handoffLinks B ord i M pc dfs saved reg done installed
+ exact setup_realizes_core (M := M) (m := m) (pre := pre) (post := post) (endAddr := endAddr)
+ s t₀ handoff locPC dfs saved lr prv reloadDest g oldHead links.1 links.2
+ (hidden_rows B ord i M pc dfs saved reg done installed) (loc_free B ord i reg)
+ (protectedDFS B ord i dfs reg separate)
+ selectors pitch fit headers start finish
+
+include installed separate selectors pitch fit headers in
+/-- Run setup and the entire hidden scan in the selected image. On success,
+the map receives the exact field writes and the saved hidden base. -/
+theorem physicalHidden_realizes
+ (start : ∀ node c, pre node c → PhysicalHiddenEntry (handoff 0) dfs lr g oldHead c)
+ (seed : List Row) (countFit : g.countBase + g.owner < 2 ^ w)
+ (count : (m (g.countBase + g.owner)).val = seed.length) (valid : ValidRows g m seed)
+ (above : endAddr ≤ g.scratchBase) {post : List Row → Word w → Config w p r → Prop}
+ (finish : ∀ node c d es, pre node c → ValidRows g m es → d.pc = reloadDest →
+ d.privateMem = storeRows g.scratchBase g.slotStride es c.privateMem →
+ d.persistent = c.persistent → d.reg (lr 8) = (g.scratchBase : Word w) →
+ (∀ j : Fin 14, j ≠ 8 → d.reg (lr j) = c.reg (lr j)) →
+ (∀ q, q ≠ lr 8 → q ∉ Set.range prv → d.reg q = c.reg q) → post es node d) :
+ Realizes (bind (physicalHiddenSetup s t₀ oldHead m).reader fun _ =>
+ hiddenReader (endAddr := endAddr) g m seed) M m dfs pre post := by
+ let mid (node : Word w) (d : Config w p r) : Prop :=
+ d.pc = loop (.inl .one) ∧ Inputs g bank d ∧ d.reg (lr 8) = (g.scratchBase : Word w) ∧
+ ∃ c, pre node c ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ q, q ≠ lr 8 → q ∉ Set.range prv → d.reg q = c.reg q
+ have setup : Realizes (physicalHiddenSetup (endAddr := endAddr) s t₀ oldHead m).reader
+ M m dfs pre (fun _ => mid) :=
+ physicalHiddenSetup_realizes (pre := pre) (post := mid) (endAddr := endAddr) B ord i M pc
+ dfs saved reg done installed separate m g oldHead
+ selectors pitch fit headers start (fun _ c _ hc ep inputs cache mem pers keep =>
+ ⟨ep, inputs, cache, c, hc, mem, pers, keep⟩)
+ have scan := (Table.segment_linked s t₀ M locPC dfs saved prv reloadDest
+ (hidden_rows B ord i M pc dfs saved reg done installed)).2
+ apply setup.bind
+ intro _
+ apply hidden_realizes scan g m seed dfs mid post (fun _ _ h => ⟨h.1, h.2.1⟩)
+ countFit count valid above (fun j hj => scan_free B ord i reg _ fun ⟨k, eqn⟩ =>
+ separate j hj (hiddenRegs B ord i (Function.Embedding.refl _) k) eqn.symm)
+ intro node d es z hd validRows atExit mem pers keep
+ obtain ⟨_, _, cached, c, hc, dm, dp, kept⟩ := hd
+ have frame (q : Fin r) (outside : q ∉ Set.range prv) : z.reg q = d.reg q :=
+ keep q (scan_free B ord i reg q outside)
+ have ext (q : Fin r) (ne : q ≠ lr 8) (outside : q ∉ Set.range prv) : z.reg q = c.reg q :=
+ (frame q outside).trans (kept q ne outside)
+ exact finish node c z es hc validRows atExit (dm ▸ mem) (pers.trans dp)
+ ((frame _ (loc_free B ord i reg 8)).trans cached)
+ (fun j hj => ext _ ((LocatedBody.commonLocator (active B ord) reg).injective.ne hj)
+ (loc_free B ord i reg j)) ext
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRolePhysicalSite.lean b/lean/OAI/Computability/VPVNP/PairShrinkRolePhysicalSite.lean
new file mode 100644
index 0000000000..728c2cbe4f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRolePhysicalSite.lean
@@ -0,0 +1,246 @@
+import OAI.Computability.VPVNP.PairShrinkRoleSelectedChildren
+import OAI.Computability.VPVNP.PairShrinkRoleParsed
+import OAI.Computability.VPVNP.PairShrinkRolePhysicalHidden
+import OAI.Computability.VPVNP.PairShrinkRoleSiteOperands
+import OAI.Computability.VPVNP.PairShrinkCallFrameStores
+
+/-!
+# Exact native parser at a selected shrinking site
+
+The level switch, argument directory, two field readers and resident-map header
+are all linked to the installed image. Their outputs are the actual map operands
+and the ordered private stores, starting at the caller's original scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression CompressorRecords LocalHistory
+open NodeArguments NodeArguments.ChildScan TraversalRows TraversalRoles TraversalControllerInputs
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentInputs MapResidentRows
+open ShrinkHiddenGuess
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t : ℕ} (ord : B.Entry → Fin t) {w p r n : ℕ} (M : Machine w p r 11)
+ (pc : Fin (shrinkSegment B ord).count → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r) (done : Fin p)
+ (installed : ∀ k, M.code (pc k) = ((shrinkSegment B ord).row pc dfs saved reg done k).resize w)
+ (separate : ∀ k : Fin 9, k = 3 ∨ k = 5 ∨ k = 6 ∨ k = 7 → ∀ l, dfs k ≠ reg l)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "lr" => LocatedBody.commonLocator (active B ord) reg
+
+variable {H first pitch offset base : ℕ} {raw m : Memory w}
+ (ds : (j : Fin (executeLevels B f hf T hT X z).length) →
+ LevelDirectory (executeLevels B f hf T hT X z)[j] raw base)
+ (resident : Resident M.publicData m H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers (executeLevels B f hf T hT X z) ds))
+ (j : Fin (executeLevels B f hf T hT X z).length)
+ (id : Fin (executeLevels B f hf T hT X z)[j].outputSites)
+ (shrinking : tagLevel B f hf (executeLevels B f hf T hT X z)[j] = .shrink) (i : Fin S.steps)
+ (index : (executeLevels B f hf T hT X z)[j].origin.ordinal = i.val)
+ (fit : layerBase B.recordLimit base (TraversalRoles.selected B f hf T hT X z)
+ ((executeLevels B f hf T hT X z).length + 1) < 2 ^ w)
+ {g : ℕ} (Z : State (oldExponent i) (packingLaneBits (oldExponent i) g))
+ (regions : LeafArena.Regions) (inc : IncidenceDirectory w) (older : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w Z) (rep : inc.ActualColumns Z m)
+ (strideFit : B.recordLimit + 2 < 2 ^ w)
+
+local notation "level" => levelHead M.publicData m j.val
+local notation "targetAddr" => address B.recordLimit (layerBase B.recordLimit base tags (j.val + 1))
+ id.val
+local notation "arena" => LeafArena.Regions.arguments regions
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+local notation "cs" => selectedChildSetup M.publicData m (List.length passes) j.val S.steps i.val
+ (oldExponent i)
+local notation "hs" => physicalHiddenSetup B.shrink.selectorBits (hiddenStride i) (Fin.val level) m
+local notation "common" => shared B ord i reg
+local notation "P" => mapLoop B ord i pc reg done
+
+private noncomputable abbrev originalRows (xs : List (Child Z)) :=
+ xs.map (Child.packet Z older B.recordLimit)
+
+local notation "packets" => originalRows B i Z older
+
+variable (arg : Args w) (seed : List ShrinkHiddenGuess.Row) (sel : Z.ShrinkSelection B.shrink)
+ (side : Bool) (site : MapResidentRows.Site Z) (term : Word w)
+ (source : MapRowSource Z sel side m (levelHead M.publicData m j.val) term)
+ (ready : DFS.Scratch w n → Prop)
+ (actions : List (Child Z) → List ShrinkHiddenGuess.Row → List (ResidentMapLoop.Exact.Action w n))
+ (inv : List (Child Z) → List ShrinkHiddenGuess.Row → Word w → Config w p r → Prop)
+
+local notation "ms" => mapStartSetup m level (Fin.val (siteIndex Z site) : Word w)
+local notation "src" => firstMap B i source site
+
+set_option maxHeartbeats 4000000 in
+-- Align each selected stage and its nested finite code and register embeddings.
+include installed separate ds resident shrinking index fit rep strideFit in
+/-- The original DFS hook executes all local readers on an arbitrary tape, including
+truncated arguments and rejections inside the resident row. -/
+theorem physicalSite_exactOn
+ (frame : ∀ priv, ready (DFS.scratch n priv) → ShrinkCallFrameLive.Stored regions n priv)
+ (above : n ≤ NativeFrame.frameBase regions)
+ (frameRoom : NativeFrame.frameBase regions + 12 ≤ 2 ^ w)
+ (directory : ∀ node : Word w, node.val = targetAddr →
+ (desc node).directoryBase = level + 14 ∧
+ ChildArguments.Resident arena inc m older B.recordLimit n node (desc node))
+ (bounds : ∀ node : Word w, node.val = targetAddr → ∀ u ∈ (desc node).sites,
+ childNode Z older B.recordLimit u < regions.nodes ∧
+ n < (arena).base (childNode Z older B.recordLimit u))
+ (selectors : arg.selectorBits = (B.shrink.selectorBits : Word w))
+ (rowStride : arg.rowStride = hiddenStride i) (headRoom : (level).val + 38 < 2 ^ w)
+ (headers : ShrinkHiddenGuess.Header.Published arg (level).val m)
+ (countFit : arg.countBase + arg.owner < 2 ^ w)
+ (count : (m (arg.countBase + arg.owner)).val = seed.length)
+ (valid : ValidRows arg m seed) (baseWord : arg.scratchBase = heap)
+ (pitchWord : arg.slotStride = n * n) (ownerWord : arg.owner = id.val)
+ (siteWord : (siteIndex Z site).val = id.val)
+ (words : MapResidentInputs.Published m level
+ ((ShrinkResidentLayout.layout Z source.first).params (oldExponent i) true w 3)
+ ((ShrinkResidentLayout.layout Z source.first).params (oldExponent i) true w 5) term 10)
+ (lengths : ∀ xs es, (actions xs es).length = (order Z side site).length)
+ (initial : ∀ node (priv : Word w → Word w) xs es c, node.val = targetAddr →
+ ready (DFS.scratch n priv) → xs.map Child.site = (desc node).sites → ValidRows arg m es →
+ Parsed (n := n) (hiddenReader arg m seed) node es →
+ SiteMapInput common dfs regions n node level term
+ (storeRows arg.scratchBase arg.slotStride es (storePackets arena (packets xs) priv)) c →
+ inv xs es node c)
+ (stable : ∀ xs es node, (P).Stable (inv xs es node))
+ (items : ∀ xs es, ResidentMapLoop.Exact.Items P M m dfs (inv xs es) src (actions xs es))
+ (mapRoom : src + (order Z side site).length < 2 ^ w) :
+ (hook (visitReader arena inc m older B.recordLimit desc (fun _ => arg) (fun _ => seed) actions
+ cs (fun _ => hs) (fun _ _ => ms))).ExactOn (fun node s => node.val = targetAddr ∧ ready s)
+ M (pc (shrinkSegment B ord).entry) done dfs m := by
+ let pre (node : Word w) (c : Config w p r) :=
+ c.pc = pc (shrinkSegment B ord).entry ∧ c.reg (dfs 7) = node ∧ node.val = targetAddr ∧
+ c.reg (dfs 6) = (n : Word w) ∧ ready (DFS.scratch n c.privateMem)
+ let argsEnd (xs : List (Child Z)) (node : Word w) (d : Config w p r) :=
+ d.pc = afterChildPC B ord i pc (afterChildren B ord i).code.entry ∧
+ VertexLevel.Located M.publicData m lr node j.val (id.val : Word w) d ∧
+ d.reg (dfs 6) = (n : Word w) ∧ ShrinkCallFrameLive.Stored regions n d.privateMem ∧
+ node.val = targetAddr ∧ xs.map Child.site = (desc node).sites ∧
+ ∃ priv, ready (DFS.scratch n priv) ∧ d.privateMem = storePackets arena (packets xs) priv
+ have children : Realizes (endAddr := n) (bind (cs).reader fun _ =>
+ ChildArguments.reader arena inc m older B.recordLimit desc) M m dfs pre argsEnd := by
+ apply selectedChildren_realizes B ord M pc dfs saved reg done f hf T hT X z installed ds
+ resident j id shrinking i index fit separate Z arena inc older desc rep strideFit
+ (fun _ _ h => ⟨h.1,h.2.1,h.2.2.1⟩) (fun node _ h => directory node h.2.2.1)
+ intro node c d xs hc sites ep loc endEq _ mem
+ have addr := hc.2.2.1
+ have row := (directory node addr).2
+ have child (x : Child Z) (hx : x ∈ xs) := bounds node addr x.site
+ (sites ▸ List.mem_map_of_mem hx)
+ have fs : ∀ q ∈ packets xs, q.Fits arena w n := by
+ intro q hq
+ obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hq
+ have hx' : x.site ∈ (desc node).sites := sites ▸ List.mem_map_of_mem hx
+ exact ⟨row.stack _ hx', (Child.payload_length Z x) ▸ row.stride _ hx',
+ (Child.payload_length Z x) ▸ (row.room _ hx').le⟩
+ have geom := (frame _ hc.2.2.2.2).children (packets xs) fs
+ (fun q hq => by obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hq; exact (child x hx).1)
+ (fun q hq => by obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hq; exact (child x hx).2) frameRoom
+ exact ⟨ep,loc,endEq.trans hc.2.2.2.1,mem ▸ geom,addr,sites,c.privateMem,hc.2.2.2.2,mem⟩
+ let hiddenEnd (xs : List (Child Z)) (es : List ShrinkHiddenGuess.Row) (node : Word w)
+ (d : Config w p r) :=
+ d.pc = reloadStart B ord i pc ∧ d.reg (lr 0) = node ∧ d.reg (lr 11) = level ∧
+ d.reg (lr 7) = (id.val : Word w) ∧ d.reg (lr 8) = (heap : Word w) ∧
+ d.reg (dfs 6) = (n : Word w) ∧ ShrinkCallFrameLive.Stored regions n d.privateMem ∧
+ node.val = targetAddr ∧ xs.map Child.site = (desc node).sites ∧ ValidRows arg m es ∧
+ ∃ priv, ready (DFS.scratch n priv) ∧ d.privateMem =
+ storeRows arg.scratchBase arg.slotStride es (storePackets arena (packets xs) priv)
+ have hidden (xs) : Realizes (endAddr := n) (bind (hs).reader fun _ => hiddenReader arg m seed)
+ M m dfs (argsEnd xs) (hiddenEnd xs) := by
+ apply physicalHidden_realizes B ord i M pc dfs saved reg done installed separate m arg
+ (level).val selectors rowStride headRoom headers
+ · intro node d hd
+ obtain ⟨ep, loc, endWord, geom, _⟩ := hd
+ refine ⟨ep, ownerWord ▸ loc.owner, loc.oldHead.trans (Fin.cast_val_eq_self _).symm, ?_, ?_⟩
+ · dsimp only
+ rw [endWord, geom.pointer, geom.cache, geom.length, VertexLevel.hiddenBaseWord_cast,
+ baseWord]
+ rfl
+ · dsimp only
+ rw [endWord, geom.pointer, geom.length, pitchWord, Nat.cast_mul]
+ · exact countFit
+ · exact count
+ · exact valid
+ · rw [baseWord]
+ exact above.trans (by
+ unfold NativeFrame.frameBase ShrinkCallABI.hiddenBase LeafArena.Regions.stackBase
+ LeafArena.Regions.cacheBase
+ omega)
+ · intro node c d es hc validRows ep mem _ cache locs ext
+ obtain ⟨_, loc, endWord, geom, addr, sites, priv, good, childMem⟩ := hc
+ have hf (e) (he : e ∈ es) : heap + e.1 * arg.slotStride + e.2.length ≤ 2 ^ w := by
+ obtain ⟨k, hk, rfl⟩ := List.mem_iff_getElem.mp he
+ simpa only [← baseWord, Args.slot] using (validRows ⟨k, hk⟩).2.2.le
+ have gg := geom.hidden arg.slotStride es above hf
+ rw [← baseWord] at gg
+ have df : d.reg (dfs 6) = c.reg (dfs 6) := ext _
+ (separate 6 (by decide) _) (fun ⟨_, eqn⟩ => separate 6 (by decide) _ eqn.symm)
+ exact ⟨ep, (locs 0 (by decide)).trans loc.state.node,
+ (locs 11 (by decide)).trans loc.oldHead, (locs 7 (by decide)).trans loc.owner,
+ baseWord ▸ cache, df.trans endWord, mem ▸ gg, addr, sites, validRows, priv, good,
+ childMem ▸ mem⟩
+ have commonApart (k : Fin 9) (hk : k = 3 ∨ k = 5 ∨ k = 6 ∨ k = 7) :
+ dfs k ∉ Set.range common := fun ⟨_, h⟩ => separate k hk _ h.symm
+ have ownerFit : id.val < 2 ^ w := by rw [← ownerWord]; omega
+ have load (xs es) : Realizes (endAddr := n) (ms).reader M m dfs
+ (fun node c => hiddenEnd xs es node c ∧
+ Parsed (n := n) (bind (hs).reader (fun _ => hiddenReader arg m seed)) node es)
+ (fun _ => ResidentMapLoop.Exact.Entry P (inv xs es) src (actions xs es).length) := by
+ rw [lengths]
+ apply mapStart_realizes B ord i pc reg done source site M dfs saved installed words
+ (by omega) (fun _ _ h => h.1.1)
+ · intro node c hc
+ exact (congrArg c.reg (map_locator_shared B ord i reg 11)).trans hc.1.2.2.1
+ · intro node c hc
+ have eqn := (congrArg c.reg (map_locator_shared B ord i reg 7)).trans hc.1.2.2.2.1
+ exact (congrArg Fin.val eqn).trans ((Nat.mod_eq_of_lt ownerFit).trans siteWord.symm)
+ · exact commonApart
+ · intro node c d input start
+ obtain ⟨hc, parsed⟩ := input
+ obtain ⟨_, atNode, atLevel, _, cache, endWord, geom, addr, sites, validRows, priv, good, mem⟩
+ := hc
+ exact initial node priv xs es d addr good sites validRows parsed.afterSetup
+ (siteMapInput_of_start B ord i reg dfs regions (separate 6 (by decide)) geom endWord atNode
+ atLevel cache mem start)
+ have link := (map_linked B ord i M (matrixPC B ord i pc) dfs saved (reloadRegs B ord i reg)
+ done (selected_map_rows B ord i M pc dfs saved reg done installed)).loop
+ have endLabel : (P).done = done := rfl
+ have loops xs es : Realizes (ResidentMapLoop.Exact.mapReader (actions xs es)) M m dfs
+ (ResidentMapLoop.Exact.Entry P (inv xs es) src (actions xs es).length)
+ (fun _ _ d => d.pc = done) := (ResidentMapLoop.Exact.maps_realizes P link (stable xs es)
+ (fun k hk => separate k hk _) (actions xs es) src (items xs es)
+ ((lengths xs es) ▸ mapRoom)).weakenPost (fun _ _ _ h => h.1.trans endLabel)
+ have run := children.bind fun xs => (hidden xs).withParsed.bind fun es =>
+ (load xs es).bind fun _ => loops xs es
+ have path : Realizes (visitReader arena inc m older B.recordLimit desc (fun _ => arg)
+ (fun _ => seed) actions cs (fun _ => hs) (fun _ _ => ms)) M m dfs pre
+ (fun _ _ d => d.pc = done) := by
+ simpa only [visitReader, bind_assoc] using run
+ apply path.exactOn _ (fun node c _ _ h entry =>
+ ⟨entry.pc, entry.nodeWord, h.1, entry.endWord, h.2⟩)
+ intro node s bs out rest _ h
+ have sc : Splits (endAddr := n) (ChildArguments.reader arena inc m older B.recordLimit desc) :=
+ fun _ _ _ _ _ h => ChildArguments.splitBits arena inc m older B.recordLimit desc h
+ have sh : Splits (endAddr := n) (hiddenReader arg m seed) := hiddenReader_split arg m seed
+ have quiet xs es : Splits (ResidentMapLoop.Exact.mapReader (actions xs es)) :=
+ fun _ _ _ _ _ h => ResidentMapLoop.Exact.splitBits (items xs es |>.quiet) h
+ exact ((cs).splits.bind fun _ => sc.bind fun xs => (hs).splits.bind fun _ =>
+ sh.bind fun es => (ms).splits.bind fun _ => quiet xs es)
+ node s bs out rest h
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleRowUpdate.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleRowUpdate.lean
new file mode 100644
index 0000000000..d52f9a48ee
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleRowUpdate.lean
@@ -0,0 +1,33 @@
+import OAI.Computability.VPVNP.PairVertexFrameData
+
+/-! # Private cells updated by a selected shrinking row -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM PrivateRAM DFS TreeDecode NodeArguments LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {w n h : ℕ} {L : Type}
+
+/-- The scratch-cell laws of a successful body read. The child scan writes
+the argument arena, and the resident scans add the selected label counts. -/
+structure RowUpdate (R : LeafArena.Regions) (order : L ≃ Fin h) (data : Fin 10 → Word w)
+ (offset : Word w) (vals : Static 34 → Word w) (s : Scratch w n) (job : VisitPath w n)
+ (children : List Packet) (exponent : L → ℕ) : Prop where
+ enabled_eq : ∀ t, job.enabled t → t = s
+ frame : VertexFrameData R data offset vals (job.update s)
+ arguments : ∀ a : ℕ, n ≤ a → a < R.histBase →
+ rawScratch (job.update s) (a : Word w) =
+ rawScratch (writePackets R.arguments children s) (a : Word w)
+ counters : ∀ l, let a : Word w := (R.histBase + (order l).val : ℕ)
+ rawScratch (job.update s) a = rawScratch s a + (exponent l : Word w)
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleScheduledSuffix.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleScheduledSuffix.lean
new file mode 100644
index 0000000000..09253286cb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleScheduledSuffix.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PairShrinkRoleTreeSuffix
+
+/-!
+# Exact suffix of a selected shrinking term
+
+The map acceptance condition at a concrete shrinking vertex asks for each
+resident six-party call to return its formal labels. On the stored child and
+hidden arguments, this is precisely the condition for extending the hidden
+fields to a kernel witness of the chosen term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.ShrinkMotif CompressorRecords NetworkKernel
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+open private layout supplyWidth from OAI.Computability.VPVNP.PairShrinkRoleMapWitness
+
+variable {K R : Type*} [Field K] [CommRing R] {S : BlockSchedule K} (B : S.Templates)
+ (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g w endAddr : ℕ}
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink)
+ (v : (X.Base × BitWord (packingTagBits (2 ^ S.degreeExponent i.castSucc))) × BitWord g)
+
+private noncomputable abbrev termAt := (B.shrinkPassAt f hf i rfl X).step.term sel
+local notation "Tr" => termAt B f hf i X sel
+private noncomputable abbrev readerAt := (shrinkPassReaders B f hf i rfl X).termParsers sel
+local notation "rdr" => readerAt B f hf i X sel
+local notation "layoutAt" => layout B i X sel
+local notation "widthAt" => supplyWidth B i X sel
+local notation "hiddenRows" => ShrinkHiddenSlots.rows X layoutAt widthAt v
+private noncomputable abbrev childOrder := (rdr).order.children v
+local notation "orderAt" => childOrder B f hf i X sel v
+
+set_option maxHeartbeats 2000000 in
+-- The scheduled kernel includes the state reindexing and dependent map arguments.
+/-- The physical reader and the selected term reader return the same remaining
+stream, provided that each map scan tests its specified resident call. -/
+theorem scheduledSuffix (new : (Tr).output.Half v)
+ (placeholder : Placed (X.packingData.shrinkInternalOwner layoutAt)
+ (internalLabel widthAt layoutAt) v)
+ (A : Arena) (T : IncidenceDirectory w) (m : Memory w) (older cap : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w X) (args : List (Child X) → Args w)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w endAddr))
+ (loadChild : Setup w endAddr) (loadHidden : List (Child X) → Setup w endAddr)
+ (loadMaps : List (Child X) → List Row → Setup w endAddr)
+ (node : Word w) (saved : Scratch w endAddr)
+ (order : (desc node).sites = List.ofFn fun j => ((orderAt).entries j).val)
+ (checks : ∀ (old : Placed (Tr).place X.network.Half v) hidden tail out,
+ let xs := children (t := Tr) X v orderAt old
+ hiddenReader (args xs) m (hiddenRows placeholder) node
+ (hiddenInputScratch A older cap loadChild loadHidden xs node saved)
+ (stream (hiddenRows hidden) ++ tail) = some (out, tail) →
+ out.value = hiddenRows hidden →
+ ((ResidentMapLoop.Exact.scan node (maps xs out.value)
+ ((loadMaps xs out.value).updated node out.updated)).isSome ↔
+ ∀ q : X.packingData.ResidentMap layoutAt v,
+ (MapWitness.names B (MapWitness.input B i X sel v old new hidden q)).isSome))
+ (bits : List Bool) :
+ ((hook (visitReader A T m older cap desc args (fun _ => hiddenRows placeholder)
+ maps loadChild loadHidden loadMaps)).read node saved bits).map Prod.snd =
+ ((TreeDecode.nodeReader rdr v new).read bits).map Prod.snd := by
+ refine treeSuffix_of_maps (term := Tr) (K := fun x => ((rdr).witness v x new).Choice)
+ A T m older cap desc args (fun _ => hiddenRows placeholder) maps
+ loadChild loadHidden loadMaps hiddenRows v orderAt node saved (TreeDecode.nodeReader rdr v new)
+ (fun _ x => x.1) order ?_ ?_ ?_ ?_ bits
+ · intro old x
+ change (ChildArguments.placedReader (t := Tr) v orderAt).encode old ++
+ ((shrinkPassReaders B f hf i rfl X).kernel sel v old new).encode x = _
+ rw [ShrinkHiddenSlots.kernel_encode B f hf i X sel v old new x]
+ rfl
+ · intro xs bs tail out hit
+ exact (hiddenReader_typed X layoutAt widthAt v (args xs) m placeholder hit).exists
+ · intro xs hidden tail
+ exact hiddenReader_encoded X layoutAt widthAt v (args xs) m placeholder hidden node _ tail
+ · intro old hidden tail out xs hit val
+ exact (checks old hidden tail out hit val).trans
+ (MapWitness.exists_iff B f hf i X sel v old new hidden).symm
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleScheduledUpdate.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleScheduledUpdate.lean
new file mode 100644
index 0000000000..22448a9395
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleScheduledUpdate.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PairShrinkRoleVisitEffect
+import OAI.Computability.VPVNP.PairShrinkRoleRowUpdate
+import OAI.Computability.VPVNP.PairShrinkRoleFieldFrame
+import OAI.Computability.VPVNP.PairShrinkVertexFrameScan
+
+/-!
+# The cell update at a shrinking vertex of the scheduled tree
+
+The exact field prefix fixes the input memory of the resident map scan. Its
+exterior cells preserve both the common vertex frame and the preceding-level
+arguments. The private histogram starts at its incoming value, so the
+increment of that scan is the increment of the whole visit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.ShrinkMotif CompressorRecords NetworkKernel
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess LeafSourceLoad
+open private layout supplyWidth from OAI.Computability.VPVNP.PairShrinkRoleMapWitness
+open scoped Fin.CommRing
+
+variable {w n t g : ℕ} {K R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+ (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps)
+ (Z : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : Z.ShrinkSelection B.shrink)
+ (v : (Z.Base × BitWord (packingTagBits (2 ^ S.degreeExponent i.castSucc))) × BitWord g)
+
+open private term parser childOrder from OAI.Computability.VPVNP.PairShrinkRoleVisitEffect
+local notation "Tr" => term B f hf i Z sel
+local notation "rdr" => parser B f hf i Z sel
+local notation "ord" => childOrder B f hf i Z sel v
+local notation "rowsAt" => ShrinkHiddenSlots.rows Z (layout B i Z sel) (supplyWidth B i Z sel) v
+
+variable (old : Placed (term B f hf i Z sel).place Z.network.Half v)
+ (new : (term B f hf i Z sel).output.Half v)
+ (k : ((parser B f hf i Z sel).witness v old new).Choice)
+ (placeholder : Placed (Z.packingData.shrinkInternalOwner (layout B i Z sel))
+ (internalLabel (supplyWidth B i Z sel) (layout B i Z sel)) v)
+ (regions : LeafArena.Regions) (inc : IncidenceDirectory w) (m : Memory w) (older cap : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w Z) (arg : Args w)
+ (maps : List (Child Z) → List Row → List (ResidentMapLoop.Exact.Action w n))
+ (cs hs ms : Setup w n) (node : Word w) (saved : Scratch w n)
+
+local notation "es" => rowsAt (Sigma.fst k)
+local notation "addr" => childNode Z older cap
+local notation "packetsAt" => TreeDecode.children rdr
+ (fun u b => Packet.mk (addr u) (packed Z u b)) v old
+local notation "xs" => children (t := Tr) Z v ord old
+local notation "heap" => ShrinkCallABI.hiddenBase regions n
+local notation "initial" => scratch n (storeRows heap arg.slotStride es
+ (storePackets regions.arguments packetsAt (rawScratch saved)))
+local notation "visit" => visitReader regions.arguments inc m older cap desc (fun _ => arg)
+ (fun _ => rowsAt placeholder) maps cs (fun _ => hs) (fun _ _ => ms)
+
+set_option maxHeartbeats 2000000 in
+-- The physical field order and the tree order are the two presentations of this dependent fiber.
+/-- Starting on any prepared scratch, a successful read of the given term witness
+satisfies the selected row's update contract. Only the resident scan's exterior
+and histogram identities are needed after the two native field scans. -/
+theorem scheduledRowUpdate (labels : B.Entry ≃ Fin t) (data : Fin 10 → Word w)
+ (offset : Word w) (vals : Static 34 → Word w)
+ (frame : TreeDecode.VertexFrameData regions data offset vals saved)
+ (order : (desc node).sites = List.ofFn fun j => ((ord).entries j).val)
+ (childSetup : ∀ s, cs.updated node s = s) (hiddenSetup : ∀ s, hs.updated node s = s)
+ (mapSetup : ∀ s, ms.updated node s = s) (base : arg.scratchBase = heap)
+ (before : n < regions.histBase) (labelFit : t ≤ regions.histWords)
+ (heapFit : heap ≤ 2 ^ w) (rowFit : ∀ e ∈ es, heap + e.1 * arg.slotStride + e.2.length ≤ 2 ^ w)
+ (fits : ∀ q ∈ packetsAt, q.Fits regions.arguments w n)
+ (nodes : ∀ q ∈ packetsAt, q.node < regions.nodes)
+ (above : ∀ q ∈ packetsAt, n < regions.arguments.base q.node)
+ (exterior : ∀ events final, ResidentMapLoop.Exact.scan node (maps xs es) initial =
+ some (events, final) → ∀ q : Word w, q.val < heap →
+ (q.val < regions.histBase ∨ regions.histBase + t ≤ q.val) →
+ rawScratch final q = rawScratch initial q)
+ (increment : ∀ events final, ResidentMapLoop.Exact.scan node (maps xs es) initial =
+ some (events, final) → ∀ l, let a : Word w := (regions.histBase + (labels l).val : ℕ)
+ rawScratch final a = rawScratch initial a +
+ (((rdr).witness v old new).exponents k l : Word w))
+ (tail : List Bool) (job : VisitPath w n)
+ (hit : (hook visit).read node saved ((rdr).nodeBits v old new k ++ tail) = some (job, tail)) :
+ RowUpdate regions labels data offset vals saved job packetsAt
+ (((rdr).witness v old new).exponents k) := by
+ have rep : scratch n (rawScratch saved) = saved := by
+ funext q
+ simp only [DFS.scratch, rawScratch, dite_eq_left q.prop]
+ have packetEq : (rdr).childPackets addr v old = packetsAt := by
+ have h (u z) : (rdr).halfBits u z = packed Z u z := (packed_eq_encode Z u z).symm
+ simp only [TermParsers.childPackets, TreeDecode.children, h]
+ have effect := scheduledVisitEffect B f hf i Z sel v old new k placeholder regions.arguments inc
+ m older cap desc arg maps cs hs ms node (rawScratch saved) tail order
+ childSetup hiddenSetup mapSetup
+ dsimp only at effect
+ rw [rep, hit, Option.map_some, base, packetEq] at effect
+ obtain ⟨⟨events, final⟩, run, equal⟩ := Option.map_eq_some_iff.mp effect.symm
+ have finalEq : final = job.update saved := (Prod.mk.inj equal).1
+ have exterior' := exterior events final run
+ have original : TreeDecode.VertexFrameData regions data offset vals
+ (scratch n (rawScratch saved)) := by rwa [rep]
+ have fieldFrame := original.after_shrink_fields
+ (before.le.trans (Nat.le_add_right ..)) heapFit rowFit fits nodes above
+ refine ⟨?_, finalEq ▸ fieldFrame.after_map before labelFit heapFit exterior', ?_, ?_⟩
+ · obtain ⟨⟨out, rest⟩, _, eqn⟩ := Option.map_eq_some_iff.mp hit
+ cases eqn
+ exact fun _ h => h
+ · intro a _ ha
+ have low := (Nat.mod_le a (2 ^ w)).trans_lt ha
+ have below : regions.histBase ≤ regions.cacheBase :=
+ (Nat.le_add_right ..).trans regions.hist_before
+ have endCache : regions.cacheBase + 38 ≤ heap := Nat.le_add_right ..
+ have hi : (a : Word w).val < heap :=
+ low.trans_le (below.trans ((Nat.le_add_right _ 38).trans endCache))
+ have atWord := exterior' (a : Word w) hi (Or.inl low)
+ have keep := fields_arguments (priv := rawScratch saved) (qs := packetsAt) rowFit a ha
+ rw [rep] at keep
+ exact finalEq ▸ atWord.trans keep
+ · intro l
+ dsimp only
+ rw [← finalEq, increment events final run l]
+ exact congrArg (· + _) ((fields_histCell (labels l).val ((labels l).isLt.trans_le labelFit)
+ heapFit rowFit fits nodes).trans (congrArg (fun s => rawScratch s _) rep))
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleSelectedChildren.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleSelectedChildren.lean
new file mode 100644
index 0000000000..df5805afb7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleSelectedChildren.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.PairShrinkRoleImageChildren
+import OAI.Computability.VPVNP.PairShrinkRoleBind
+
+/-! # Reading the child packets of a selected shrinking site -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression CompressorRecords LocalHistory
+open NodeArguments NodeArguments.ChildScan TraversalRows TraversalRoles TraversalControllerInputs
+open ShrinkVertexImage VertexStagePrefix
+open scoped Fin.CommRing
+
+variable {w endAddr : ℕ}
+
+/-- The located level selects a degree, after which the node and old directory
+are copied and the ordinal registers filled in order. -/
+def selectedChildSetup (pub : Fin 11 → Word w) (m : Memory w) (levels old steps stage a : ℕ) :
+ Setup w endAddr :=
+ (((locatorSetup pub m (old + 1) (levels - (old + 1))).seq
+ (Setup.ticks (steps + 7 + 2 * stage))).seq (Setup.ticks 2)).seq (Setup.ticks (2 ^ a))
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) {t : ℕ}
+ (ord : B.Entry → Fin t) {p r : ℕ} (M : Machine w p r 11)
+ (pc : Fin (shrinkSegment B ord).count → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r) (done : Fin p)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "lr" => LocatedBody.commonLocator (active B ord) reg
+private noncomputable abbrev switchRegs :=
+ (VertexStageDispatch.scratchBank (fun i => (active B ord i).tailCount)).trans reg
+local notation "sr" => switchRegs B ord reg
+
+/-- The descriptor, geometry register and located old header survive the complete
+child scan. Both the sites and the private packet writes are the ones actually parsed. -/
+theorem selectedChildren_realizes
+ (installed : ∀ k, M.code (pc k) = ((shrinkSegment B ord).row pc dfs saved reg done k).resize w)
+ {H first pitch offset base : ℕ} {raw m : Memory w}
+ (ds : (j : Fin (passes).length) → LevelDirectory passes[j] raw base)
+ (resident : Resident M.publicData m H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers passes ds))
+ (j : Fin (passes).length) (id : Fin passes[j].outputSites)
+ (shrinking : tagLevel B f hf passes[j] = .shrink) (i : Fin S.steps)
+ (index : passes[j].origin.ordinal = i.val)
+ (fit : layerBase B.recordLimit base tags ((passes).length + 1) < 2 ^ w)
+ (separate : ∀ k : Fin 9, k = 3 ∨ k = 5 ∨ k = 6 ∨ k = 7 → ∀ l, dfs k ≠ reg l)
+ {g : ℕ} (Z : State (oldExponent i) g) (A : Arena) (inc : IncidenceDirectory w)
+ (older : ℕ) (desc : Word w → ChildArguments.Descriptor w Z)
+ (rep : inc.ActualColumns Z m) (strideFit : B.recordLimit + 2 < 2 ^ w)
+ {pre : Word w → Config w p r → Prop} {post : List (Child Z) → Word w → Config w p r → Prop}
+ (start : ∀ node c, pre node c → c.pc = pc (shrinkSegment B ord).entry ∧
+ c.reg (dfs 7) = node ∧ node.val =
+ address B.recordLimit (layerBase B.recordLimit base tags (j.val + 1)) id.val)
+ (directory : ∀ node c, pre node c →
+ (desc node).directoryBase = levelHead M.publicData m j.val + 14 ∧
+ ChildArguments.Resident A inc m older B.recordLimit endAddr node (desc node))
+ (resume : ∀ node c d xs, pre node c → xs.map Child.site = (desc node).sites →
+ d.pc = afterChildPC B ord i pc (afterChildren B ord i).code.entry →
+ VertexLevel.Located M.publicData m lr node j.val (id.val : Word w) d →
+ d.reg (dfs 6) = c.reg (dfs 6) → d.persistent = c.persistent →
+ d.privateMem = storePackets A (xs.map (Child.packet Z older B.recordLimit)) c.privateMem →
+ post xs node d) :
+ Realizes (endAddr := endAddr) (bind
+ (selectedChildSetup M.publicData m (passes).length j.val S.steps i.val (oldExponent i)).reader
+ fun _ => ChildArguments.reader A inc m older B.recordLimit desc) M m dfs pre post := by
+ let mid (node : Word w) (d : Config w p r) : Prop :=
+ d.pc = activePC B ord i pc (active B ord i).code.entry ∧
+ VertexLevel.Located M.publicData m lr node j.val (id.val : Word w) d ∧
+ ∃ c, pre node c ∧ d.reg (dfs 6) = c.reg (dfs 6) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent
+ have away (k : Fin 9) (hk : k = 3 ∨ k = 5 ∨ k = 6 ∨ k = 7) :
+ dfs k ∉ Set.range lr ∧ dfs k ∉ Set.range sr :=
+ ⟨fun ⟨_, h⟩ => separate k hk _ h.symm, fun ⟨_, h⟩ => separate k hk _ h.symm⟩
+ have first := selectedEntry_realizes B ord M pc dfs saved reg done f hf T hT X z
+ (endAddr := endAddr) installed ds resident j id shrinking i index fit away start
+ (post := mid) (fun _ c _ hc ep located mem pers keep =>
+ ⟨ep, located, c, hc, keep _ (away 6 (by decide)).1 (away 6 (by decide)).2, mem, pers⟩)
+ have free (l : Fin 14) : lr l ∉ Set.range (argumentBank B ord i reg) := by
+ rintro ⟨k, h⟩
+ exact Preparation.disjoint (activeBank B ord i reg) k ((afterChildren B ord i).locator l)
+ (h.trans (active_locator B ord reg i l).symm)
+ have child : Realizes (endAddr := endAddr)
+ (imageChildren i Z A inc m older B.recordLimit desc) M m dfs mid post := by
+ apply imageChildren_realizes B ord i M pc dfs saved reg done installed Z A inc m older
+ B.recordLimit desc (fun k hk _ => separate k hk _) rep strideFit
+ · intro node d hd
+ obtain ⟨ep, loc, c, hc, _⟩ := hd
+ obtain ⟨dir, resident⟩ := directory node c hc
+ exact ⟨ep, loc.state.node, loc.oldFields.trans dir.symm, resident⟩
+ · intro node d out xs hd sites ep pers mem keep
+ obtain ⟨_, loc, c, hc, endEq, dm, dp⟩ := hd
+ exact resume node c out xs hc sites ep
+ (VertexStageDispatch.retainLocated loc (fun l => keep _ (free l)))
+ ((keep _ (fun ⟨_, h⟩ => separate 6 (by decide) _ h.symm)).trans endEq)
+ (pers.trans dp) (dm ▸ mem)
+ simpa only [selectedChildSetup, Setup.seq_reader, bind_assoc, imageChildren, BankChild.reader]
+ using first.bind (fun _ => child)
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleSelectedEntry.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleSelectedEntry.lean
new file mode 100644
index 0000000000..555e089fc6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleSelectedEntry.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.PairShrinkRoleSetup
+import OAI.Computability.VPVNP.PairShrinkVertexLinks
+
+/-! # Canonical DFS prefix at the selected shrinking stage -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression CompressorRecords LocalHistory
+open TraversalRows TraversalRoles TraversalControllerInputs NodeArguments.ChildScan
+open ShrinkVertexImage
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) {t : ℕ}
+ (ord : B.Entry → Fin t) {p r w endAddr : ℕ} (M : Machine w p r 11)
+ (pc : Fin (shrinkSegment B ord).count → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r) (done : Fin p)
+ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "lr" => LocatedBody.commonLocator (active B ord) reg
+private noncomputable abbrev selectorBank :=
+ (VertexStageDispatch.scratchBank (fun i => (active B ord i).tailCount)).trans reg
+
+/-- The locator and the stage switch in the fixed finite image, with no
+entry assumptions on any of their temporaries. -/
+theorem selectedEntry_realizes
+ (installed : ∀ k, M.code (pc k) = ((shrinkSegment B ord).row pc dfs saved reg done k).resize w)
+ {H first pitch offset base : ℕ} {raw m : Memory w}
+ (ds : (j : Fin (passes).length) → LevelDirectory passes[j] raw base)
+ (resident : Resident M.publicData m H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers passes ds))
+ (j : Fin (passes).length) (id : Fin passes[j].outputSites)
+ (shrinking : tagLevel B f hf passes[j] = .shrink) (i : Fin S.steps)
+ (index : passes[j].origin.ordinal = i.val)
+ (fit : layerBase B.recordLimit base tags ((passes).length + 1) < 2 ^ w)
+ (apart : ∀ k : Fin 9, k = 3 ∨ k = 5 ∨ k = 6 ∨ k = 7 →
+ dfs k ∉ Set.range lr ∧ dfs k ∉ Set.range (selectorBank B ord reg))
+ {pre post : Word w → Config w p r → Prop}
+ (start : ∀ node c, pre node c → c.pc = pc (shrinkSegment B ord).entry ∧
+ c.reg (dfs 7) = node ∧ node.val =
+ address B.recordLimit (layerBase B.recordLimit base tags (j.val + 1)) id.val)
+ (resume : ∀ node c d, pre node c → d.pc = activePC B ord i pc (active B ord i).code.entry →
+ VertexLevel.Located M.publicData m lr node j.val (id.val : Word w) d →
+ d.privateMem = c.privateMem → d.persistent = c.persistent →
+ (∀ q, q ∉ Set.range lr → q ∉ Set.range (selectorBank B ord reg) → d.reg q = c.reg q) →
+ post node d) :
+ Realizes (endAddr := endAddr)
+ ((locatorSetup M.publicData m (j.val + 1) ((passes).length - (j.val + 1))).seq
+ (Setup.ticks (S.steps + 7 + 2 * i.val))).reader M m dfs pre (fun _ => post) := by
+ apply Setup.realizes
+ intro node c hc
+ obtain ⟨ep,hn,addr⟩ := start node c hc
+ obtain ⟨l,idx,_,d,path,entry,loc,mem,per,keep⟩ :=
+ selected_entry B ord M pc dfs saved reg done installed f hf T hT X z ds resident j id
+ shrinking c ep (hn ▸ addr) fit
+ obtain rfl : l = i := Fin.ext (idx.symm.trans index)
+ exact ⟨d,resume node c d hc entry (hn ▸ loc) mem per keep,
+ ⟨fun k hk => keep _ (apart k hk).1 (apart k hk).2, fun addr _ => congrFun mem addr,per⟩,
+ congrArg (DFS.scratch endAddr) mem,path⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleSetup.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleSetup.lean
new file mode 100644
index 0000000000..c4254d13b4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleSetup.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.PairShrinkRoleStages
+import OAI.Computability.VPVNP.PairShrinkRoleHandoff
+import OAI.Computability.VPVNP.PairVertexLevelLocator
+
+/-!
+# Physical operand loads of a shrinking visit
+
+The level scan reads the old header and computes the packed owner of the popped
+row. The child handoff copies the node and old-field address. The hidden
+handoff obtains its owner and old header from the locator and its stride from
+the geometry in private memory. All three stages preserve the pending stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM DFS TraversalControllerInputs TraversalRoles TraversalRows
+open VertexLevelBounds
+open scoped Fin.CommRing
+
+variable {w p r endAddr : ℕ} {M : Machine w p r 11} {m : Memory w}
+ {dfs : Fin 9 ↪ Fin r} {regs : Fin 14 ↪ Fin r} {next : Fin p}
+ {pre post : Word w → Config w p r → Prop}
+
+/-- The trace of the selected level scan includes every candidate level it passes. -/
+def locatorSetup (pub : Fin 11 → Word w) (m : Memory w) (level later : ℕ) : Setup w endAddr where
+ trace _ _ := VertexLevel.trace pub m level later
+ updated _ s := s
+ quiet _ _ := (VertexLevel.trace_cost pub m level later).2.2
+
+/-- Locate a genuine noninitial row, without relying on any scratch register at entry. -/
+theorem locator_realizes {loc : Fin 35 → Fin p} {saved : VertexImage.Saved ↪ Fin r}
+ (code : ∀ i, M.code (loc i) = (VertexLevel.segment.row loc dfs saved regs next i).resize w)
+ {H first pitch offset cap base : ℕ} {old : TaggedLayer} {ls : List (Fiber w)}
+ (resident : Resident M.publicData m H first pitch offset cap base old ls)
+ (stage : Fin (old :: ls.map Prod.fst).length) (level : ℕ) (hs : stage.val = level + 1)
+ (id : Fin (old :: ls.map Prod.fst)[stage].layer.count)
+ (fit : layerBase cap base (old :: ls.map Prod.fst) (ls.length + 1) < 2 ^ w)
+ (separate : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → dfs i ∉ Set.range regs)
+ (start : ∀ node c, pre node c → c.pc = loc VertexLevel.segment.entry ∧
+ c.reg (dfs 7) = node ∧ node.val = address cap (layerBase cap base (old :: ls.map Prod.fst)
+ stage) id)
+ (resume : ∀ node c d, pre node c → d.pc = next →
+ VertexLevel.Located M.publicData m regs node level (id.val : Word w) d →
+ VertexLevel.Frame regs c d → post node d) :
+ Realizes (endAddr := endAddr)
+ (locatorSetup M.publicData m (level + 1) (ls.length - (level + 1))).reader
+ M m dfs pre (fun _ => post) := by
+ apply Setup.realizes
+ intro node c hc
+ obtain ⟨pc,hnode,addr⟩ := start _ _ hc
+ obtain ⟨d,run,done,located,fr⟩ :=
+ VertexLevel.run M loc dfs saved regs next code resident stage level hs id c pc
+ (hnode ▸ addr) fit
+ exact ⟨d, resume node c d hc done (hnode ▸ located) fr,
+ ⟨fun i hi => fr.outside _ (separate i hi), fun a _ => congrFun fr.privateMem a,
+ fr.persistent⟩, congrArg (DFS.scratch endAddr) fr.privateMem, run⟩
+
+/-- The two real copy rows prepare the node and directory pointer in the child bank. -/
+theorem childHandoff_realizes {pc : Fin 2 → Fin p} {child : Fin 16 ↪ Fin r}
+ (code : ∀ i, M.code (pc i) = VertexLevel.childHandoff pc regs child next i)
+ (apart : child 7 ≠ regs 12)
+ (separate : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → dfs i ≠ child 7 ∧ dfs i ≠ child 8)
+ (start : ∀ node c, pre node c → c.pc = pc 0)
+ (resume : ∀ node c d, pre node c → d.pc = next → d.reg (child 7) = c.reg (regs 0) →
+ d.reg (child 8) = c.reg (regs 12) →
+ (∀ q, q ≠ child 7 → q ≠ child 8 → d.reg q = c.reg q) →
+ d.privateMem = c.privateMem → d.persistent = c.persistent → post node d) :
+ Realizes (Setup.ticks (endAddr := endAddr) 2).reader M m dfs pre (fun _ => post) := by
+ apply Setup.realizes
+ intro node c hc
+ obtain ⟨d,run,done,nodeWord,dirWord,keep,mem,pers⟩ :=
+ VertexLevel.childHandoff_run code apart c (start _ _ hc) m
+ exact ⟨d, resume node c d hc done nodeWord dirWord keep mem pers,
+ ⟨fun i hi => keep _ (separate i hi).1 (separate i hi).2, fun a _ => congrFun mem a, pers⟩,
+ congrArg (DFS.scratch endAddr) mem, run⟩
+
+/-- The installed rows compute the owner, scratch base beyond the scalar stacks,
+stride, and old level.
+The squared stride uses the geometry word at offset nine. -/
+theorem hiddenHandoff_realizes {pc : Fin VertexLevel.hiddenCount → Fin p}
+ {inputs : Fin 6 ↪ Fin r} {stackEnd : Fin r}
+ (code : ∀ i, M.code (pc i) = VertexLevel.hiddenHandoff pc regs inputs stackEnd next i)
+ (apart : ∀ i j, inputs i ≠ regs j)
+ (separate : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → ∀ j, dfs i ≠ inputs j)
+ (start : ∀ node c, pre node c → c.pc = pc 0)
+ (resume : ∀ node c d, pre node c →
+ let geom := c.privateMem (c.reg stackEnd)
+ let n := c.privateMem (geom + 9)
+ d.pc = next → d.reg (inputs 0) = c.reg (regs 7) →
+ d.reg (inputs 1) = VertexLevel.hiddenBaseWord (c.privateMem (geom + 8)) n →
+ d.reg (inputs 2) = n * n → d.reg (inputs 5) = c.reg (regs 11) →
+ (∀ q, q ≠ inputs 0 → q ≠ inputs 1 → q ≠ inputs 2 → q ≠ inputs 5 → d.reg q = c.reg q) →
+ d.privateMem = c.privateMem → d.persistent = c.persistent → post node d) :
+ Realizes (Setup.ticks (endAddr := endAddr) VertexLevel.hiddenCount).reader M m dfs
+ pre (fun _ => post) := by
+ apply Setup.realizes
+ intro node c hc
+ obtain ⟨d,run,done,owner,base,stride,head,keep,mem,pers⟩ :=
+ VertexLevel.hiddenHandoff_run code apart c (start _ _ hc) m
+ exact ⟨d, resume node c d hc done owner base stride head keep mem pers,
+ ⟨fun i hi => keep _ (separate i hi 0) (separate i hi 1) (separate i hi 2) (separate i hi 5),
+ fun a _ => congrFun mem a, pers⟩, congrArg (DFS.scratch endAddr) mem, run⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleSiteOperands.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleSiteOperands.lean
new file mode 100644
index 0000000000..9f0d881f40
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleSiteOperands.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PairShrinkRoleMapStart
+import OAI.Computability.VPVNP.PairShrinkCallFrameLive
+import OAI.Computability.VPVNP.PairShrinkSiteBank
+
+/-! # Concrete operands at the first resident map of a shrinking site -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression CompressorRecords
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentInputs MapResidentRows
+open scoped Fin.CommRing
+
+variable {w p r n : ℕ}
+
+/-- Operands left by the map reload and header, before the first motif ID is read.
+The published term row and its stride accompany the five live gather inputs. -/
+structure SiteMapInput (common : Fin 24 ↪ Fin r) (dfs : Fin 9 ↪ Fin r)
+ (R : LeafArena.Regions) (n : ℕ) (node level term : Word w)
+ (expected : Word w → Word w) (c : Config w p r) : Prop where
+ node : c.reg (common 0) = node
+ level : c.reg (common 11) = level
+ geometry : c.reg (common 9) = (NativeFrame.frameBase R : Word w)
+ histogram : c.reg (common 10) = (R.histBase : Word w)
+ hidden : c.reg (common 8) = (ShrinkCallABI.hiddenBase R n : Word w)
+ term : c.reg (common 16) = term
+ stride : c.reg (common 17) = 10
+ one : c.reg (common 22) = 1
+ endWord : c.reg (dfs 6) = (n : Word w)
+ memory : c.privateMem = expected
+
+/-- The six-party programs use these five public operands at every row of this site. -/
+theorem SiteMapInput.pub_eq {common : Fin 24 ↪ Fin r} {dfs : Fin 9 ↪ Fin r}
+ {R : LeafArena.Regions} {node level term : Word w} {expected : Word w → Word w}
+ {c : Config w p r} (h : SiteMapInput common dfs R n node level term expected c) :
+ ShrinkCallABI.pub c common = ShrinkSiteBank.pub level node R n := by
+ funext j
+ fin_cases j
+ · exact h.level
+ · exact h.node
+ · exact h.geometry
+ · exact h.histogram
+ · exact h.hidden
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r)
+ (dfs : Fin 9 ↪ Fin r) (R : LeafArena.Regions)
+
+local notation "lr" => LocatedBody.commonLocator (active B ord) reg
+local notation "common" => shared B ord i reg
+
+/-- The reload and five external reads supply the exact operands in the map ABI.
+The argument and hidden bits remain at their original physical addresses. -/
+theorem siteMapInput_of_start
+ {node level term : Word w} {before after : Config w p r} {expected : Word w → Word w}
+ (apart : ∀ l, dfs 6 ≠ reg l)
+ (geom : ShrinkCallFrameLive.Stored R n before.privateMem)
+ (endWord : before.reg (dfs 6) = (n : Word w))
+ (atNode : before.reg (lr 0) = node) (atLevel : before.reg (lr 11) = level)
+ (atHidden : before.reg (lr 8) = (ShrinkCallABI.hiddenBase R n : Word w))
+ (mem : before.privateMem = expected)
+ (loaded : MapStart common dfs term before after) :
+ SiteMapInput common dfs R n node level term expected after := by
+ have frame (j : Fin 14) (h9 : j ≠ 9) (h10 : j ≠ 10) :
+ after.reg (common (j.castAdd 10)) = before.reg (lr j) := by
+ have h (k : Fin 14) (hne : j ≠ k) : common (j.castAdd 10) ≠ common (k.castAdd 10) :=
+ (common).injective.ne ((Fin.castAddEmb 10).injective.ne hne)
+ exact (loaded.outside _ (h 9 h9) (h 10 h10) (locator_header_frame B ord i reg j)).trans
+ (congrArg before.reg (map_locator_shared B ord i reg j))
+ have free (j : Fin 24) : dfs 6 ≠ common j := apart _
+ refine ⟨(frame 0 (by decide) (by decide)).trans atNode,
+ (frame 11 (by decide) (by decide)).trans atLevel, ?_, ?_,
+ (frame 8 (by decide) (by decide)).trans atHidden, loaded.term, loaded.stride, loaded.one,
+ (loaded.outside _ (free _) (free _)
+ ⟨free _, free _, free _, free _, free _, free _, free _⟩).trans endWord,
+ loaded.memory.trans mem⟩
+ · rw [loaded.geometry, endWord, geom.pointer]
+ · rw [loaded.histogram, endWord, geom.pointer, geom.histogram]
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleSiteOrigins.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleSiteOrigins.lean
new file mode 100644
index 0000000000..1b3aa5376d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleSiteOrigins.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PairShrinkRoleSiteOperands
+import OAI.Computability.VPVNP.PairShrinkRoleItemOrigins
+import OAI.Computability.VPVNP.PairShrinkRoleParsed
+import OAI.Computability.VPVNP.PairShrinkRoleChild
+import OAI.Computability.VPVNP.PairShrinkRoleHidden
+
+/-!
+# The concrete origin retained throughout one selected shrinking map row
+
+The parser has fixed the parent, child list and absorbed fields. The origin
+records their actual memory and the initialized map ABI from the installed
+header. It may vary with the caller's unused memory and registers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM Compression NodeArguments NodeArguments.ChildScan
+open ShrinkHiddenGuess ResidentMapLoop.Exact
+
+variable {w n p r a g k : ℕ} {Z : State a g} (dfs : Fin 9 ↪ Fin r) (common : Fin 24 ↪ Fin r)
+ (regions : LeafArena.Regions) (level term : Word w) (address older cap : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w Z) (arg : Args w) (seed : List ShrinkHiddenGuess.Row)
+ (m : Memory w) (ready : DFS.Scratch w n → Prop)
+ (xs : List (Child Z)) (es : List ShrinkHiddenGuess.Row)
+
+/-- The raw entry may vary, but the five map operands, typed stores and accepted
+hidden parse are determined by the selected physical data. -/
+structure SiteOrigin where
+ /-- Word address of the popped node whose row the handler is reading. -/
+ node : Word w
+ /-- Private memory before the child packets and hidden rows are stored for this visit. -/
+ before : Word w → Word w
+ /-- Machine configuration on entry to the resident map scan after installing the child
+ packets and hidden rows. -/
+ entry : Config w p r
+ atRow : node.val = address
+ prepared : ready (DFS.scratch n before)
+ sites : xs.map Child.site = (desc node).sites
+ valid : ValidRows arg m es
+ parsed : Parsed (n := n) (hiddenReader arg m seed) node es
+ operands : SiteMapInput common dfs regions n node level term
+ (storeRows arg.scratchBase arg.slotStride es
+ (storePackets regions.arguments (xs.map (Child.packet Z older cap)) before)) entry
+
+local notation "Origin" => SiteOrigin (p := p) dfs common regions level term address older cap
+ desc arg seed m ready xs es
+
+/-- One retained initial configuration suffices for the whole resident loop. -/
+def siteInv (fixed : Origin → Config w p r → Prop) (node : Word w) (c : Config w p r) : Prop :=
+ ∃ origin : Origin, origin.node = node ∧ fixed origin c
+
+variable {P : ResidentMapLoop.Program p r} {M : Machine w p r k}
+
+theorem siteInv_stable (fixed : Origin → Config w p r → Prop)
+ (stable : ∀ origin, P.Stable (fixed origin)) (node : Word w) :
+ P.Stable (siteInv dfs common regions level term address older cap desc arg seed m ready xs es
+ fixed node) :=
+ OriginInvariant.stable (inv := fun origin _ => fixed origin) (fun origin _ => stable origin) node
+
+/-- The actual header output is one witness for the initial map invariant. -/
+theorem siteInv_start (fixed : Origin → Config w p r → Prop)
+ (initial : ∀ origin : Origin, fixed origin origin.entry)
+ (node : Word w) (priv : Word w → Word w) (c : Config w p r) (atRow : node.val = address)
+ (good : ready (DFS.scratch n priv)) (sites : xs.map Child.site = (desc node).sites)
+ (valid : ValidRows arg m es) (parsed : Parsed (n := n) (hiddenReader arg m seed) node es)
+ (operands : SiteMapInput common dfs regions n node level term
+ (storeRows arg.scratchBase arg.slotStride es
+ (storePackets regions.arguments (xs.map (Child.packet Z older cap)) priv)) c) :
+ siteInv dfs common regions level term address older cap desc arg seed m ready xs es
+ fixed node c := by
+ let origin : Origin := ⟨node, priv, c, atRow, good, sites, valid, parsed, operands⟩
+ exact ⟨origin, rfl, initial origin⟩
+
+/-- The origin may be chosen anew for each compatible entry configuration, while
+each selected action is independent of that choice. -/
+theorem siteInv_items (fixed : Origin → Config w p r → Prop)
+ {start : ℕ} {actions : List (Action w n)} (quiet : ∀ job ∈ actions, NoChoices job)
+ (items : ∀ origin : Origin, Items P M m dfs (fun _ => fixed origin) start actions) :
+ Items P M m dfs
+ (siteInv dfs common regions level term address older cap desc arg seed m ready xs es fixed)
+ start actions :=
+ Items.existsInvariant (inv := fun origin _ => fixed origin) quiet items
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleStages.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleStages.lean
new file mode 100644
index 0000000000..a6787969e9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleStages.lean
@@ -0,0 +1,256 @@
+import OAI.Computability.VPVNP.PairNodeChildLoop
+
+/-!
+# Composing the native stages of a shrinking vertex
+
+The old-half-wire reader passes its exact stream suffix and private memory
+to the hidden-field reader. The deterministic resident maps start with the
+resulting private fields. The same entry scratch determines the path and
+the entire returned scratch for every compatible native configuration.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM DFS NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {w endAddr p r k : ℕ} {α β : Type*}
+
+/-- The data, native trace, and full scratch result of one local stage. -/
+structure Outcome (w endAddr : ℕ) (α : Type*) where
+ /-- Typed value produced by this visit stage, such as its decoded child arguments or chosen
+ hidden fields. -/
+ value : α
+ /-- Chronological native events emitted while producing the stage's value. -/
+ trace : List (Event w)
+ /-- Private scratch image retained by the next stage after this reader finishes. -/
+ updated : Scratch w endAddr
+
+/-- A partial visit-stage decoder for a node and scratch image. Success returns the typed
+outcome and the unconsumed suffix of the choice tape. -/
+abbrev Reader (w endAddr : ℕ) (α : Type*) :=
+ Word w → Scratch w endAddr → List Bool → Option (Outcome w endAddr α × List Bool)
+
+/-- The four DFS registers and every private stack address protected across
+the stage, together with its persistent word. -/
+structure Frame (dfs : Fin 9 ↪ Fin r) (endAddr : ℕ) (c d : Config w p r) : Prop where
+ registers : ∀ i, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → d.reg (dfs i) = c.reg (dfs i)
+ below : ∀ a : Word w, a.val < endAddr → d.privateMem a = c.privateMem a
+ persistent : d.persistent = c.persistent
+
+theorem Frame.trans {dfs : Fin 9 ↪ Fin r} {c d e : Config w p r}
+ (h : Frame dfs endAddr c d) (h' : Frame dfs endAddr d e) : Frame dfs endAddr c e :=
+ ⟨fun i hi => (h'.registers i hi).trans (h.registers i hi),
+ fun a ha => (h'.below a ha).trans (h.below a ha), h'.persistent.trans h.persistent⟩
+
+theorem Frame.keepsPending {dfs : Fin 9 ↪ Fin r} {c d : Config w p r}
+ (h : Frame dfs endAddr c d) {top : ℕ} {pending : List (Word w)}
+ (atEnd : top + pending.length = endAddr) (st : Represents c.privateMem top pending) :
+ Represents d.privateMem top pending := by
+ refine ⟨st.1, fun i => (h.below _ ?_).trans (st.2 i)⟩
+ change (top + i.val) % (2 ^ w) < endAddr
+ exact (Nat.mod_le ..).trans_lt (atEnd ▸ Nat.add_lt_add_left i.isLt top)
+
+/-- Each accepted result runs from every native input satisfying the entry
+predicate, and a failed read precludes returning for every fuel. -/
+structure Realizes (read : Reader w endAddr α) (M : Machine w p r k) (m : Memory w)
+ (dfs : Fin 9 ↪ Fin r) (pre : Word w → Config w p r → Prop)
+ (post : α → Word w → Config w p r → Prop) : Prop where
+ success : ∀ node c bs out rest, pre node c →
+ read node (scratch endAddr c.privateMem) bs = some (out, rest) →
+ bs = choiceBits out.trace ++ rest ∧ ∃ d, post out.value node d ∧ Frame dfs endAddr c d ∧
+ scratch endAddr d.privateMem = out.updated ∧ Prefix M m c d (choiceBits out.trace) out.trace
+ reject : ∀ node c bs, pre node c →
+ read node (scratch endAddr c.privateMem) bs = none → ¬ Returns M c m bs
+
+/-- Pass the first stage's parsed values, scratch, and suffix to the next. -/
+def bind (first : Reader w endAddr α) (next : α → Reader w endAddr β) :
+ Reader w endAddr β := fun node saved bs =>
+ match first node saved bs with
+ | none => none
+ | some (a, tail) => (next a.value node a.updated tail).map fun (b, rest) =>
+ (⟨b.value, a.trace ++ b.trace, b.updated⟩, rest)
+
+/-- Successful parses split the supplied tape at the native choice events. -/
+def Splits (read : Reader w endAddr α) : Prop :=
+ ∀ node saved bs out rest, read node saved bs = some (out, rest) →
+ bs = choiceBits out.trace ++ rest
+
+theorem Splits.bind {first : Reader w endAddr α} {next : α → Reader w endAddr β}
+ (h : Splits first) (h' : ∀ a, Splits (next a)) : Splits (ShrinkRole.bind first next) := by
+ intro node saved bs out rest read
+ cases hx : first node saved bs with
+ | none => simp [ShrinkRole.bind, hx] at read
+ | some pair =>
+ obtain ⟨x, tail⟩ := pair
+ cases hy : next x.value node x.updated tail with
+ | none => simp [ShrinkRole.bind, hx, hy] at read
+ | some pair =>
+ obtain ⟨y, leftover⟩ := pair
+ obtain ⟨rfl,rfl⟩ : (⟨y.value, x.trace ++ y.trace, y.updated⟩ : Outcome w endAddr β) = out ∧
+ leftover = rest := by simpa [ShrinkRole.bind, hx, hy] using read
+ rw [PrimedInputRAM.Flow.choiceBits_append, h _ _ _ _ _ hx, (h' x.value) _ _ _ _ _ hy,
+ List.append_assoc]
+
+variable {M : Machine w p r k} {m : Memory w} {dfs : Fin 9 ↪ Fin r}
+ {pre : Word w → Config w p r → Prop} {mid : α → Word w → Config w p r → Prop}
+ {post : β → Word w → Config w p r → Prop}
+
+/-- A later consumer may discard unused facts established at the exit. -/
+theorem Realizes.weakenPost {read : Reader w endAddr α}
+ {done done' : α → Word w → Config w p r → Prop}
+ (h : Realizes read M m dfs pre done)
+ (weaken : ∀ a node d, done a node d → done' a node d) :
+ Realizes read M m dfs pre done' := by
+ refine ⟨?_, h.reject⟩
+ intro node c bs out rest hc got
+ obtain ⟨part,d,hd,fr,updated,path⟩ := h.success node c bs out rest hc got
+ exact ⟨part, d, weaken _ _ _ hd, fr, updated, path⟩
+
+/-- A rejection in a later stage follows back through the successful prefixes
+of the earlier stages. This covers truncation within any consumed field. -/
+theorem Realizes.bind {first : Reader w endAddr α} {next : α → Reader w endAddr β}
+ (h : Realizes first M m dfs pre mid) (h' : ∀ a, Realizes (next a) M m dfs (mid a) post) :
+ Realizes (bind first next) M m dfs pre post := by
+ constructor
+ · intro node c bs out rest hc hr
+ cases ha : first node (scratch endAddr c.privateMem) bs with
+ | none => simp [ShrinkRole.bind, ha] at hr
+ | some z =>
+ obtain ⟨a,tail⟩ := z
+ obtain ⟨part,d,hd,fr,sd,one⟩ := h.success _ _ _ _ _ hc ha
+ cases hb : next a.value node a.updated tail with
+ | none => simp [ShrinkRole.bind, ha, hb] at hr
+ | some z =>
+ obtain ⟨b,left⟩ := z
+ simp only [ShrinkRole.bind, ha, hb, Option.map_some,
+ Option.some.injEq, Prod.mk.injEq] at hr
+ obtain ⟨rfl,rfl⟩ := hr
+ obtain ⟨part',e,he,fr',se,two⟩ :=
+ (h' a.value).success node d tail b left hd (sd ▸ hb)
+ rw [PrimedInputRAM.Flow.choiceBits_append]
+ exact ⟨by rw [part, part', List.append_assoc], e, he, fr.trans fr', se, one.trans two⟩
+ · intro node c bs hc hr
+ cases ha : first node (scratch endAddr c.privateMem) bs with
+ | none => exact h.reject node c bs hc ha
+ | some z =>
+ obtain ⟨a,tail⟩ := z
+ obtain ⟨part,d,hd,_,sd,one⟩ := h.success _ _ _ _ _ hc ha
+ cases hb : next a.value node a.updated tail with
+ | none =>
+ rw [part]
+ exact mt (one.returns tail).mp ((h' a.value).reject node d tail hd (sd ▸ hb))
+ | some z => rcases z with ⟨b,left⟩; simp [ShrinkRole.bind, ha, hb] at hr
+
+/-- A deterministic register-setup stage described on the caller's scratch. -/
+structure Setup (w endAddr : ℕ) where
+ /-- Events of the deterministic setup at the given popped node and incoming scratch image. -/
+ trace : Word w → Scratch w endAddr → List (Event w)
+ /-- Scratch image left by the deterministic setup for the subsequent visit stage. -/
+ updated : Word w → Scratch w endAddr → Scratch w endAddr
+ quiet : ∀ node saved, choiceBits (trace node saved) = []
+
+/-- Expose deterministic setup as a unit-valued reader that emits its trace, updates scratch,
+and retains the entire choice tape. -/
+def Setup.reader (s : Setup w endAddr) : Reader w endAddr Unit := fun node saved bs =>
+ some (⟨(), s.trace node saved, s.updated node saved⟩, bs)
+
+/-- A register-only setup has a fixed number of local ticks and keeps all scratch. -/
+def Setup.ticks (n : ℕ) : Setup w endAddr where
+ trace _ _ := List.replicate n .tick
+ updated _ s := s
+ quiet _ _ := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa only [List.replicate_succ, choiceBits] using ih
+
+/-- Consecutive setup fragments expose one trace and the last scratch update. -/
+def Setup.seq (a b : Setup w endAddr) : Setup w endAddr where
+ trace n s := a.trace n s ++ b.trace n (a.updated n s)
+ updated n s := b.updated n (a.updated n s)
+ quiet n s := by
+ simp only [PrimedInputRAM.Flow.choiceBits_append, a.quiet, b.quiet, List.nil_append]
+
+theorem Setup.seq_realizes {a b : Setup w endAddr}
+ {pre mid post : Word w → Config w p r → Prop}
+ (ha : Realizes a.reader M m dfs pre (fun _ => mid))
+ (hb : Realizes b.reader M m dfs mid (fun _ => post)) :
+ Realizes (a.seq b).reader M m dfs pre (fun _ => post) :=
+ ha.bind fun _ => hb
+
+theorem Setup.splits (s : Setup w endAddr) : Splits s.reader := by
+ intro node saved bs out rest h
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj h)
+ simp only [s.quiet, List.nil_append]
+
+/-- A linked setup may read the real directory or write the private operands.
+Its specified trace and writes must hold on every eligible input configuration. -/
+theorem Setup.realizes {M : Machine w p r k} {m : Memory w} {dfs : Fin 9 ↪ Fin r}
+ (s : Setup w endAddr) {pre post : Word w → Config w p r → Prop}
+ (run : ∀ node c, pre node c →
+ ∃ d, post node d ∧ Frame dfs endAddr c d ∧
+ scratch endAddr d.privateMem = s.updated node (scratch endAddr c.privateMem) ∧
+ Prefix M m c d [] (s.trace node (scratch endAddr c.privateMem))) :
+ Realizes s.reader M m dfs pre (fun _ => post) := by
+ constructor
+ · intro node c bs out rest hc h
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj h)
+ simpa only [s.quiet, List.nil_append, true_and] using run node c hc
+ · intro node c bs hc h
+ cases h
+
+/-- Convert the composed local reader into one DFS visit with its full
+scratch snapshot as the input condition. -/
+def hook (read : Reader w endAddr α) : HookParser w endAddr where
+ read node saved bs := (read node saved bs).map fun (out, rest) =>
+ (⟨node, out.trace, (· = saved), fun _ => out.updated⟩, rest)
+
+/-- Native state at a DFS visit after the node was popped. -/
+structure Entry (dfs : Fin 9 ↪ Fin r) (endAddr : ℕ) (visit : Fin p) (node : Word w)
+ (c : Config w p r) (top : ℕ) (pending : List (Word w)) : Prop where
+ pc : c.pc = visit
+ nodeWord : c.reg (dfs 7) = node
+ stack : Represents c.privateMem top pending
+ atEnd : top + pending.length = endAddr
+ topWord : c.reg (dfs 5) = (top : Word w)
+ endWord : c.reg (dfs 6) = (endAddr : Word w)
+ one : c.reg (dfs 3) = 1
+
+/-- Any compatible entry configuration produces the same parsed trace and
+scratch result. The bit identity must also hold for a successful read whose
+input scratch currently has no compatible DFS stack. -/
+theorem Realizes.exactOn {visit ret : Fin p} {read : Reader w endAddr α}
+ (h : Realizes read M m dfs pre (fun _ _ d => d.pc = ret))
+ {domain : Word w → Scratch w endAddr → Prop}
+ (splitBits : ∀ node saved bs out rest, domain node saved →
+ read node saved bs = some (out, rest) → bs = choiceBits out.trace ++ rest)
+ (start : ∀ node c top pending, domain node (scratch endAddr c.privateMem) →
+ Entry dfs endAddr visit node c top pending → pre node c) :
+ (hook read).ExactOn domain M visit ret dfs m := by
+ constructor
+ · intro node saved dom bs job tail hr
+ obtain ⟨⟨out, rest⟩, got, eqn⟩ := Option.map_eq_some_iff.mp hr
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj eqn
+ refine ⟨rfl, rfl, splitBits _ _ _ _ _ dom got, ?_⟩
+ intro c top pending enabled pc nodeWord stack atEnd topWord endWord one
+ change scratch endAddr c.privateMem = saved at enabled
+ have hc := start node c top pending (enabled ▸ dom)
+ ⟨pc, nodeWord, stack, atEnd, topWord, endWord, one⟩
+ obtain ⟨_,d,done,fr,updated,path⟩ := h.success node c bs out rest hc (enabled ▸ got)
+ exact ⟨d, done, (fr.registers 7 (by simp)).trans nodeWord,
+ (fr.registers 5 (by simp)).trans topWord, (fr.registers 6 (by simp)).trans endWord,
+ (fr.registers 3 (by simp)).trans one, fr.persistent, fr.keepsPending atEnd stack,
+ updated, path⟩
+ · intro node bs c top pending dom pc nodeWord stack atEnd topWord endWord one reject
+ exact h.reject node c bs (start _ _ _ _ dom
+ ⟨pc, nodeWord, stack, atEnd, topWord, endWord, one⟩) (Option.map_eq_none_iff.mp reject)
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleSuffix.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleSuffix.lean
new file mode 100644
index 0000000000..e28412b533
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleSuffix.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.PairShrinkRoleExact
+import OAI.Computability.VPVNP.PairShrinkRoleChildTyped
+import OAI.Computability.VPVNP.PairShrinkRoleHiddenTyped
+import OAI.Computability.VPVNP.PairTreeNodeReaders
+
+/-!
+# Choice suffixes of shrinking visits
+
+A successful visit consumes two adjacent fields: the independent arguments
+of the placed children, followed by the owned absorbed words. Its deterministic
+map scan decides acceptance on the resulting scratch and consumes no suffix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM DFS Compression CompressorRecords NetworkKernel
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+open scoped Fin.CommRing
+
+variable {w endAddr a g : ℕ} {α β : Type*}
+
+private def Accepts (read : Reader w endAddr α) (node : Word w) (saved : Scratch w endAddr)
+ (bs rest : List Bool) : Prop := ∃ out, read node saved bs = some (out,rest)
+
+private theorem accepts_bind (first : Reader w endAddr α) (next : α → Reader w endAddr β)
+ (node : Word w) (saved : Scratch w endAddr) (bs rest : List Bool) :
+ Accepts (bind first next) node saved bs rest ↔ ∃ a tail,
+ first node saved bs = some (a,tail) ∧ Accepts (next a.value) node a.updated tail rest := by
+ cases ha : first node saved bs with
+ | none => simp [Accepts, bind, ha]
+ | some pair =>
+ obtain ⟨a,tail⟩ := pair
+ cases hb : next a.value node a.updated tail with
+ | none => simp [Accepts, bind, ha, hb]
+ | some pair => obtain ⟨b,remain⟩ := pair; simp [Accepts, bind, ha, hb]
+
+private theorem accepts_maps (js : List (ResidentMapLoop.Exact.Action w endAddr))
+ (node : Word w) (saved : Scratch w endAddr) (bs rest : List Bool) :
+ Accepts (ResidentMapLoop.Exact.mapReader js) node saved bs rest ↔
+ bs = rest ∧ (ResidentMapLoop.Exact.scan node js saved).isSome := by
+ cases h : ResidentMapLoop.Exact.scan node js saved with
+ | none => simp [Accepts, ResidentMapLoop.Exact.mapReader, h]
+ | some pair => obtain ⟨es,out⟩ := pair; simp [Accepts, ResidentMapLoop.Exact.mapReader, h]
+
+variable {X : State a g} (A : Arena) (T : IncidenceDirectory w) (m : Memory w)
+ (older cap : ℕ) (desc : Word w → ChildArguments.Descriptor w X)
+ (args : List (Child X) → Args w) (seed : List (Child X) → List Row)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w endAddr))
+ (loadChild : Setup w endAddr) (loadHidden : List (Child X) → Setup w endAddr)
+ (loadMaps : List (Child X) → List Row → Setup w endAddr)
+
+/-- Exact acceptance, factoring out the deterministic setup stages. The old
+and hidden results determine the actual starting scratch for the map checks. -/
+theorem visitReader_suffix_iff (node : Word w) (saved : Scratch w endAddr) (bs rest : List Bool) :
+ (∃ out, visitReader A T m older cap desc args seed maps loadChild loadHidden loadMaps
+ node saved bs = some (out,rest)) ↔ ∃ old tail h,
+ ChildArguments.reader A T m older cap desc node (loadChild.updated node saved) bs =
+ some (old,tail) ∧
+ hiddenReader (args old.value) m (seed old.value) node
+ ((loadHidden old.value).updated node old.updated) tail = some (h,rest) ∧
+ (ResidentMapLoop.Exact.scan node (maps old.value h.value)
+ ((loadMaps old.value h.value).updated node h.updated)).isSome := by
+ change Accepts _ _ _ _ _ ↔ _
+ simp only [visitReader, accepts_bind, accepts_maps, Setup.reader, Option.some.injEq,
+ Prod.mk.injEq, and_assoc]
+ constructor
+ · rintro ⟨_,_,rfl,rfl,old,tail,ho,_,_,rfl,rfl,h,_,hh,_,_,rfl,rfl,rfl,good⟩
+ exact ⟨old,tail,h,ho,hh,good⟩
+ · rintro ⟨old,tail,h,ho,hh,good⟩
+ exact ⟨_,_,rfl,rfl,old,tail,ho,_,_,rfl,rfl,h,rest,hh,_,_,rfl,rfl,rfl,good⟩
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleTreeSuffix.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleTreeSuffix.lean
new file mode 100644
index 0000000000..899873073a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleTreeSuffix.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairShrinkRoleSuffix
+import OAI.Computability.VPVNP.PairShrinkRoleMapWitness
+
+/-!
+# Comparing a shrinking visit with its typed kernel reader
+
+At a vertex the first guesses describe the placed old half-wires, and the
+next guesses describe the hidden assignments. The native scratch after both
+writes supplies the resident map checks. Matching those deterministic checks
+to the chosen kernel gives equality of the suffix on every input tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM BurstRAM.PrivateRAM DFS Compression CompressorRecords NetworkKernel
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+
+variable {w endAddr a g : ℕ} {R L : Type*} {X : State a g} {term : Term R X.network}
+ (A : Arena) (T : IncidenceDirectory w) (m : Memory w)
+ (older cap : ℕ) (desc : Word w → ChildArguments.Descriptor w X)
+ (args : List (Child X) → Args w) (seed : List (Child X) → List Row)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w endAddr))
+ (loadChild : Setup w endAddr) (loadHidden : List (Child X) → Setup w endAddr)
+ (loadMaps : List (Child X) → List Row → Setup w endAddr)
+
+/-- The private cells used by the hidden scan, after storing the old
+arguments and running the hidden-stage setup. -/
+noncomputable def hiddenInputScratch (xs : List (Child X)) (node : Word w)
+ (saved : Scratch w endAddr) :=
+ (loadHidden xs).updated node
+ (writePackets A (xs.map (Child.packet X older cap)) (loadChild.updated node saved))
+
+private theorem some_suffix {α : Type*} (o : Option (α × List Bool)) (tail : List Bool) :
+ o.map Prod.snd = some tail ↔ ∃ out, o = some (out, tail) := by
+ cases o with
+ | none => simp
+ | some pair => obtain ⟨x,b⟩ := pair; simp
+
+private theorem hook_suffix {α : Type*} (read : Reader w endAddr α) (node : Word w)
+ (saved : Scratch w endAddr) (bits : List Bool) :
+ ((hook read).read node saved bits).map Prod.snd = (read node saved bits).map Prod.snd := by
+ cases hr : read node saved bits with
+ | none => simp [hook, hr]
+ | some pair => obtain ⟨x,b⟩ := pair; simp [hook, hr]
+
+variable {H : Type} (rowData : H → List Row) (v : term.output.Site) (ord : Order (term.Preimage v))
+ (node : Word w) (saved : Scratch w endAddr)
+
+local notation "Old" => Placed term.place X.network.Half v
+local notation "oldList" => children X v ord
+local notation "beforeHidden" => hiddenInputScratch A older cap loadChild loadHidden
+local notation "nativeReader" => visitReader A T m older cap desc args seed maps
+ loadChild loadHidden loadMaps
+
+/-- The child and hidden decoders give their exact typed prefixes. Only the
+deterministic test on the resulting resident fields depends on the kernel. -/
+theorem treeSuffix_of_maps {K : Old → Type} (C : ChoiceReader ((x : Old) × K x))
+ (hidden : ∀ x, K x → H)
+ (order : (desc node).sites = List.ofFn fun j => (ord.entries j).val)
+ (enc : ∀ x k, C.encode ⟨x, k⟩ =
+ (ChildArguments.placedReader v ord).encode x ++ stream (rowData (hidden x k)))
+ (sound : ∀ xs bs tail out, hiddenReader (args xs) m (seed xs) node
+ (beforeHidden xs node saved) bs = some (out, tail) →
+ ∃ h, out.value = rowData h ∧ bs = stream (rowData h) ++ tail)
+ (complete : ∀ xs h tail, ∃ out, hiddenReader (args xs) m (seed xs) node
+ (beforeHidden xs node saved) (stream (rowData h) ++ tail) = some (out, tail) ∧
+ out.value = rowData h)
+ (checks : ∀ x h tail out, let xs := oldList x
+ hiddenReader (args xs) m (seed xs) node (beforeHidden xs node saved)
+ (stream (rowData h) ++ tail) = some (out, tail) →
+ out.value = rowData h →
+ ((ResidentMapLoop.Exact.scan node (maps xs out.value)
+ ((loadMaps xs out.value).updated node out.updated)).isSome ↔ ∃ k, hidden x k = h))
+ (bits : List Bool) :
+ ((hook nativeReader).read node saved bits).map Prod.snd = (C.read bits).map Prod.snd := by
+ rw [hook_suffix]
+ apply Option.ext
+ intro rest
+ rw [some_suffix, some_suffix, visitReader_suffix_iff]
+ constructor
+ · rintro ⟨o,tail,out,childRun,hidRun,pass⟩
+ obtain ⟨x,⟨rfl,part⟩,_⟩ := ChildArguments.reader_unique_placed A T m older cap desc v ord node
+ (loadChild.updated node saved) order childRun
+ obtain ⟨h,eqn,prefixEq⟩ := sound (oldList x) tail rest out hidRun
+ rw [prefixEq] at hidRun
+ obtain ⟨k,hk⟩ := (checks x h rest out hidRun eqn).mp pass
+ refine ⟨⟨x, k⟩,(C.read_iff ..).mpr ?_⟩
+ rw [enc, hk, List.append_assoc, ← prefixEq]
+ exact part
+ · rintro ⟨⟨x, k⟩,hr⟩
+ have part := (C.read_iff ..).mp hr
+ rw [enc, List.append_assoc] at part
+ let xs := oldList x
+ let remain := stream (rowData (hidden x k)) ++ rest
+ let o := ChildArguments.outcome A T m older cap desc node (loadChild.updated node saved) xs
+ obtain ⟨out,hidRun,eqn⟩ := complete xs (hidden x k) rest
+ refine ⟨o,remain,out,?_,hidRun,(checks x (hidden x k) rest out hidRun eqn).mpr ⟨k,rfl⟩⟩
+ rw [part]
+ exact ChildArguments.reader_placed A T m older cap desc v ord node _ order x remain
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleTypedActions.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleTypedActions.lean
new file mode 100644
index 0000000000..ca955c1edd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleTypedActions.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.PairShrinkRoleScheduledSuffix
+import OAI.Computability.VPVNP.PairShrinkRoleParsed
+
+/-!
+# Typed resident actions for the parsed raw field lists
+
+The old children and hidden rows have unique typed encodings. A list of
+resident actions may therefore be indexed by the physical readers' outputs.
+On every completed parse the recovered values are exactly the supplied fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression Compression.ShrinkMotif NetworkKernel CompressorRecords
+open NodeArguments NodeArguments.ChildScan ShrinkHiddenSlots ShrinkHiddenGuess LocalHistory
+open private ChildArguments.children_injective from OAI.Computability.VPVNP.PairShrinkRoleChildTyped
+
+variable {α β : Type*}
+
+open Classical in
+/-- Decode a value in the image of a fixed injective encoding. The default only
+serves to define a total indexing function outside that image. -/
+noncomputable def recover (encode : α → β) (base : α) (y : β) : α :=
+ if h : ∃ x, encode x = y then h.choose else base
+
+theorem recover_encode (encode : α → β) (inj : Function.Injective encode) (base x : α) :
+ recover encode base (encode x) = x := by
+ have h : ∃ z, encode z = encode x := ⟨x, rfl⟩
+ rw [recover, dite_eq_left h]
+ exact inj h.choose_spec
+
+variable {R : Type*} {a g : ℕ} (X : State a (packingLaneBits a g))
+ {term : Term R X.network} (v : term.output.Site) (ord : Order (term.Preimage v))
+
+/-- Recover the old placement from the child list in descriptor order. -/
+noncomputable def oldFields (xs : List (Child X)) : Placed term.place X.network.Half v :=
+ recover (children X v ord) (fun _ _ => (fun _ _ _ => false, fun _ _ _ => false)) xs
+
+theorem oldFields_encoded (h : Placed term.place X.network.Half v) :
+ oldFields X v ord (children X v ord h) = h :=
+ recover_encode _ (ChildArguments.children_injective v ord) _ h
+
+theorem children_oldFields (xs : List (Child X))
+ (order : xs.map Child.site = List.ofFn fun j => (ord.entries j).val) :
+ children X v ord (oldFields X v ord xs) = xs := by
+ obtain ⟨h, rfl⟩ := exists_placed X v ord xs order
+ rw [oldFields_encoded]
+
+variable (layout : Bool) (widths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+ (site : (X.Base × BitWord (Shrink.J a)) × BitWord g)
+
+local notation "rowsAt" => ShrinkHiddenSlots.rows X layout widths site
+local notation "Hidden" => Placed (X.packingData.shrinkInternalOwner layout)
+ (internalLabel widths layout) site
+
+private theorem rows_injective : Function.Injective (rowsAt) := by
+ intro h k eqn
+ exact (rows_prefix_unique X layout widths site h k [] [] (eqn ▸ rfl)).1
+
+/-- Recover the absorbed half-wire fields from their dense IDs and little-endian bits. -/
+noncomputable def hiddenFields (seed : Hidden) (es : List Row) : Hidden :=
+ recover (rowsAt) seed es
+
+theorem hiddenFields_encoded (seed h : Hidden) :
+ hiddenFields X layout widths site seed (rowsAt h) = h :=
+ recover_encode _ (rows_injective X layout widths site) seed h
+
+variable {w n : ℕ}
+
+/-- A successful native hidden parse is always in the image of the typed encoding. -/
+theorem rows_hiddenFields (arg : Args w) (m : Memory w) (seed : Hidden) (es : List Row)
+ (node : Word w) (parsed : Parsed (n := n) (hiddenReader arg m (rowsAt seed)) node es) :
+ rowsAt (hiddenFields X layout widths site seed es) = es := by
+ obtain ⟨s, bits, out, tail, hit, rfl⟩ := parsed
+ obtain ⟨h, eqn, _⟩ := (hiddenReader_typed X layout widths site arg m seed hit).exists
+ rw [eqn, hiddenFields_encoded]
+
+/-- Run the same resident calls when the physical interface provides raw lists. -/
+noncomputable def typedActions (seed : Hidden)
+ (bank : Placed term.place X.network.Half v → Hidden → List (ResidentMapLoop.Exact.Action w n))
+ (xs : List (Child X)) (es : List Row) : List (ResidentMapLoop.Exact.Action w n) :=
+ bank (oldFields X v ord xs) (hiddenFields X layout widths site seed es)
+
+theorem typedActions_encoded (seed : Hidden)
+ (bank : Placed term.place X.network.Half v → Hidden → List (ResidentMapLoop.Exact.Action w n))
+ (old : Placed term.place X.network.Half v) (hidden : Hidden) :
+ typedActions X v ord layout widths site seed bank (children X v ord old) (rowsAt hidden) =
+ bank old hidden := by
+ simp only [typedActions, oldFields_encoded, hiddenFields_encoded]
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoleVisitEffect.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoleVisitEffect.lean
new file mode 100644
index 0000000000..3a138cf949
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoleVisitEffect.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.PairShrinkRoleScheduledSuffix
+
+/-!
+# Private memory of a scheduled shrinking visit
+
+On the encoding of a kernel witness, the field readers write the preceding
+sites' argument packets and then the owned hidden words. The resident maps run
+on the projection of these two native store sequences, with an arbitrary tape
+suffix and arbitrary initial private memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression Compression.ShrinkMotif CompressorRecords NetworkKernel
+open LocalHistory NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+open private stored from OAI.Computability.VPVNP.PairShrinkRoleHidden
+open private layout supplyWidth from OAI.Computability.VPVNP.PairShrinkRoleMapWitness
+
+variable {w n : ℕ}
+
+/-- The hidden reader's scratch is the projection of the ordered native row stores
+for any full private memory representing its entry scratch. -/
+theorem hiddenReader_stores (arg : Args w) (m : Memory w) (seed : List Row) (node : Word w)
+ (priv : Word w → Word w) (bits tail : List Bool) (out : Outcome w n (List Row))
+ (hit : hiddenReader arg m seed node (scratch n priv) bits = some (out, tail)) :
+ out.updated = scratch n (storeRows arg.scratchBase arg.slotStride out.value priv) := by
+ unfold hiddenReader at hit
+ split at hit
+ · obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj hit)
+ rw [stored, scratch_storePackets]
+ · contradiction
+
+variable {a g : ℕ} {X : State a g}
+
+private theorem visit_effect (A : Arena) (inc : IncidenceDirectory w) (m : Memory w)
+ (older cap : ℕ) (desc : Word w → ChildArguments.Descriptor w X)
+ (arg : Args w) (seed : List Row)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w n))
+ (cs hs ms : Setup w n) (node : Word w) (priv : Word w → Word w)
+ (xs : List (Child X)) (qs : List Packet) (es : List Row) (bits hidBits tail : List Bool)
+ (c : Outcome w n (List (Child X))) (h : Outcome w n (List Row))
+ (childRead : ChildArguments.reader A inc m older cap desc node (scratch n priv)
+ bits = some (c, hidBits))
+ (childValue : c.value = xs) (childStore : c.updated = scratch n (storePackets A qs priv))
+ (hiddenRead : hiddenReader arg m seed node (scratch n (storePackets A qs priv)) hidBits =
+ some (h, tail)) (hiddenValue : h.value = es)
+ (childSetup : cs.updated node (scratch n priv) = scratch n priv)
+ (hiddenSetup : hs.updated node c.updated = c.updated)
+ (mapSetup : ms.updated node h.updated = h.updated) :
+ ((hook (visitReader A inc m older cap desc (fun _ => arg) (fun _ => seed) maps
+ cs (fun _ => hs) (fun _ _ => ms))).read node (scratch n priv) bits).map
+ (fun (j, rest) => (j.update (scratch n priv), rest)) =
+ (ResidentMapLoop.Exact.scan node (maps xs es)
+ (scratch n (storeRows arg.scratchBase arg.slotStride es (storePackets A qs priv)))).map
+ (fun (_, final) => (final, tail)) := by
+ have written := hiddenReader_stores arg m seed node (storePackets A qs priv) hidBits tail h
+ hiddenRead
+ rw [hiddenValue] at written
+ have hid : hiddenReader arg m seed node c.updated hidBits = some (h, tail) :=
+ childStore ▸ hiddenRead
+ simp only [hook, visitReader, bind, Setup.reader, childSetup, childRead, hiddenSetup, hid,
+ childValue, hiddenValue, mapSetup, ResidentMapLoop.Exact.mapReader, Option.map_map]
+ rw [written]
+ cases ResidentMapLoop.Exact.scan node (maps xs es)
+ (scratch n (storeRows arg.scratchBase arg.slotStride es (storePackets A qs priv))) <;> rfl
+
+variable {K R : Type*} [Field K] [CommRing R] {S : BlockSchedule K} (B : S.Templates)
+ (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps)
+ (Z : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : Z.ShrinkSelection B.shrink)
+ (v : (Z.Base × BitWord (packingTagBits (2 ^ S.degreeExponent i.castSucc))) × BitWord g)
+
+private noncomputable abbrev term := (B.shrinkPassAt f hf i rfl Z).step.term sel
+local notation "Tr" => term B f hf i Z sel
+private noncomputable abbrev parser := (shrinkPassReaders B f hf i rfl Z).termParsers sel
+local notation "rdr" => parser B f hf i Z sel
+private noncomputable abbrev childOrder := (rdr).order.children v
+local notation "ord" => childOrder B f hf i Z sel v
+local notation "rowsAt" => ShrinkHiddenSlots.rows Z (layout B i Z sel) (supplyWidth B i Z sel) v
+
+set_option maxHeartbeats 2000000 in
+-- Identifying the encoded kernel reduces its dependent scheduled witness and reader.
+/-- The scratch returned by the physical hook on a witness prefix is exactly the
+resident scan's output on that witness's child packets and absorbed field rows.
+This equality covers rejection by any map in the scan. -/
+theorem scheduledVisitEffect (old : Placed (Tr).place Z.network.Half v)
+ (new : (Tr).output.Half v) (k : ((rdr).witness v old new).Choice)
+ (placeholder : Placed (Z.packingData.shrinkInternalOwner (layout B i Z sel))
+ (internalLabel (supplyWidth B i Z sel) (layout B i Z sel)) v)
+ (A : Arena) (inc : IncidenceDirectory w) (m : Memory w) (older cap : ℕ)
+ (desc : Word w → ChildArguments.Descriptor w Z) (arg : Args w)
+ (maps : List (Child Z) → List Row → List (ResidentMapLoop.Exact.Action w n))
+ (cs hs ms : Setup w n) (node : Word w) (priv : Word w → Word w) (tail : List Bool)
+ (order : (desc node).sites = List.ofFn fun j => ((ord).entries j).val)
+ (childSetup : ∀ s, cs.updated node s = s) (hiddenSetup : ∀ s, hs.updated node s = s)
+ (mapSetup : ∀ s, ms.updated node s = s) :
+ let xs := children (t := Tr) Z v ord old
+ let qs := (rdr).childPackets (childNode Z older cap) v old
+ let es := rowsAt k.1
+ let after := storeRows arg.scratchBase arg.slotStride es (storePackets A qs priv)
+ let visit := visitReader A inc m older cap desc (fun _ => arg)
+ (fun _ => rowsAt placeholder) maps cs (fun _ => hs) (fun _ _ => ms)
+ ((hook visit).read node (scratch n priv) ((rdr).nodeBits v old new k ++ tail)).map
+ (fun (j, rest) => (j.update (scratch n priv), rest)) =
+ (ResidentMapLoop.Exact.scan node (maps xs es) (scratch n after)).map
+ (fun (_, final) => (final, tail)) := by
+ intro xs qs es after visit
+ let hidBits := stream es ++ tail
+ let c := ChildArguments.outcome A inc m older cap desc node (scratch n priv) xs
+ have packets : xs.map (Child.packet Z older cap) = qs := by
+ have halves (u z) : (rdr).halfBits u z = packed Z u z := (packed_eq_encode Z u z).symm
+ simp only [xs, qs, children, List.map_ofFn, Function.comp_def, TermParsers.childPackets,
+ Child.packet, Child.payload_ofHalf, halves]
+ rfl
+ have childStore : c.updated = scratch n (storePackets A qs priv) := by
+ rw [scratch_storePackets, ← packets]
+ rfl
+ have input : (rdr).nodeBits v old new k ++ tail =
+ (ChildArguments.placedReader (t := Tr) v ord).encode old ++ hidBits := by
+ change ((ChildArguments.placedReader (t := Tr) v ord).encode old ++
+ ((shrinkPassReaders B f hf i rfl Z).kernel sel v old new).encode k) ++ tail = _
+ rw [ShrinkHiddenSlots.kernel_encode B f hf i Z sel v old new k, List.append_assoc]
+ rfl
+ obtain ⟨h, hiddenRead, hiddenValue⟩ := hiddenReader_encoded Z (layout B i Z sel)
+ (supplyWidth B i Z sel) v arg m placeholder k.1 node
+ (scratch n (storePackets A qs priv)) tail
+ apply visit_effect A inc m older cap desc arg (rowsAt placeholder) maps cs hs ms node priv
+ xs qs es
+ _ hidBits tail c h _ rfl childStore hiddenRead hiddenValue (childSetup _) (hiddenSetup _)
+ (mapSetup _)
+ rw [input]
+ exact ChildArguments.reader_placed (t := Tr) A inc m older cap desc v ord node _ order old hidBits
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRouteABI.lean b/lean/OAI/Computability/VPVNP/PairShrinkRouteABI.lean
new file mode 100644
index 0000000000..ce8c9dc9fb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRouteABI.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherRegisters
+import OAI.Computability.VPVNP.PairShrinkVertexImage
+
+/-!
+# Live operands across the selected shrinking-row dispatch
+
+The actual five public operand registers survive the resident ID, term and
+layout reads. The state operand is exactly the overwritten motif ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkVertexImage
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords ShrinkMapImage
+open ShrinkMapImage.Registers
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t r : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (locals : Fin (maps B ord i).code.privateRegs ↪ Fin r)
+
+local notation "F" => matrixFamily B ord i
+local notation "G" => gatherFamily B ord i
+local notation "cm" => Function.Embedding.trans (gatherShared (F) (G)) locals
+local notation "tmp" => locals (layoutTemp (F) (G))
+
+theorem route_abi (ds : ∀ a j, locals a ≠ dfs j) (ss : ∀ a j, locals a ≠ saved j)
+ (idx : MapHandlerImage.Index B.shrink) :
+ (∀ j, Protected mapRegisters (cm) (tmp) (dfs j)) ∧
+ (∀ j : Fin 5, Protected mapRegisters (cm) (tmp)
+ ((F).inputs dfs saved (cm) idx j.castSucc)) ∧
+ (F).inputs dfs saved (cm) idx (Fin.last 5) = (mapRegisters.headerReg (cm)) 6 := by
+ have apart := (hosted_banks (F) (G) dfs saved locals ds ss).2.2
+ have separated : ∀ j : Fin 5, ShrinkCallABI.sourceSlot j.castSucc ≠ mapRegisters.zero ∧
+ ∀ l : Fin 11, 6 ≤ l.val → l.val ≤ 9 → ShrinkCallABI.sourceSlot j.castSucc ≠
+ mapRegisters.header l := by decide
+ refine ⟨?_, ?_, rfl⟩
+ · intro j
+ exact ⟨(ds _ _).symm, (ds _ _).symm, fun l _ _ ↦ (ds _ _).symm⟩
+ · intro j
+ have spec := separated j
+ exact ⟨apart _, (cm).injective.ne spec.1,
+ fun l lo hi ↦ (cm).injective.ne (spec.2 l lo hi)⟩
+
+end PairSimulation.ShrinkVertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRoutedExterior.lean b/lean/OAI/Computability/VPVNP/PairShrinkRoutedExterior.lean
new file mode 100644
index 0000000000..cdbfc7ead2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRoutedExterior.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.PairShrinkJobExterior
+import OAI.Computability.VPVNP.PairSimulationShrinkRowAction
+
+/-! # Exterior scratch of a complete shrinking resident occurrence -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif MotifEntry
+open MotifBlocks MotifGrid MotifConversion NetworkKernel CompressorRecords
+open CompressorRecords.ShrinkSlots NodeArguments ShrinkMapImage.Registers MapResidentRows
+
+variable {w g packetEnd endAddr t n limit : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (B : S.Templates) (ord : B.Entry → Fin t) (i : Fin S.steps)
+local notation "degree" => slotDegree S
+local notation "family" => ShrinkVertexImage.matrixFamily B ord i
+local notation "gathers" => ShrinkVertexImage.gatherFamily B ord i
+variable (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+variable (sel : X.ShrinkSelection B.shrink)
+variable (m : X.packingData.Motif) (party : Fin 6)
+variable (J : Job X B.shrink (S.shrink i) sel m party w)
+private noncomputable local instance routedBaseDecidable : DecidableEq X.Base := Classical.decEq _
+local notation "BW" => ShrinkPreparedCall.widthsDemand X m
+local notation "idx" => Fin.val (ShrinkMotifOrder.stateNumber X m)
+local notation "cd" => ShrinkCallDemandCells.cdBase X m J.arena J.nodes
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel))
+ (X.packingData.shrinkPartySite (selectedLayout X B.shrink sel) m party))
+local notation "call" => Job.entryInput B X (S.shrink i) sel m party J hidden
+local notation "L" => MapHandlerOperand.layout family demandMass_pos call
+variable (ok : ShrinkCallFields.Fits (w := w) (n := n) (limit := limit) (t := t)
+ (u := repetitions B.shrink (ShrinkPreparedCall.widthsDemand X m)) B.shrink
+ (ShrinkPreparedCall.widthsDemand X m) (sel m).val J.scratch (ShrinkMotifOrder.stateNumber X m).val
+ (ShrinkCallDemandCells.cdBase X m J.arena J.nodes))
+local notation "W" => Job.mapWorkspace B degree ord X (S.shrink i) sel m party J hidden ok
+variable (hw : MapConstants.widthThreshold B.shrink ≤ w)
+variable (P : Fin 5 → Word w) (mem : Memory w) (site : Site X) (level term : Word w)
+variable {side : Bool} (src : MapRowSource X sel side mem level term)
+variable (row : Fin (order X side site).length)
+local notation "st" => rowOrdinalWord (w := w) (a := S.degreeExponent i.castSucc) (g := g)
+ X side site row
+
+set_option maxHeartbeats 2000000 in
+-- The scheduled row, party input and gathered output share a dependent job index.
+/-- The route adds events and passes the gathered map's scratch on to the
+next action. All its exterior cells agree with the incoming logical scratch. -/
+theorem Job.routed_preserves (saved : DFS.Scratch w endAddr)
+ {baseline : Word w → Word w} (packets : J.Packets packetEnd baseline)
+ (histEnd : J.scratch.hist + t ≤ J.scratch.hidden)
+ {T : IncidenceDirectory w} {origin : ℕ}
+ (old : J.OldPublished (ShrinkCallABI.operands degree) P st mem level T origin)
+ {events : List (Event w)} {out : DFS.Scratch w endAddr}
+ (got : rowAction (g := g) (ready := S.shrink i) (side := side) (jobMotif := m)
+ family gathers X sel site mem level term src row call J hw P W saved =
+ some (events, out)) :
+ ∀ q : Word w, q.val < J.scratch.staging →
+ (q.val < J.scratch.hist ∨ J.scratch.hist + t ≤ q.val) →
+ rawScratch out q = rawScratch saved q := by
+ unfold rowAction at got
+ obtain ⟨⟨trace, last⟩, raw, pair⟩ := Option.map_eq_some_iff.mp got
+ have same : last = out := (Prod.mk.inj pair).2
+ rw [← same]
+ exact Job.gathered_preserves B ord i X sel m party J hidden ok hw P st mem saved
+ packets histEnd old raw
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkRowBudget.lean b/lean/OAI/Computability/VPVNP/PairShrinkRowBudget.lean
new file mode 100644
index 0000000000..29a907ced3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkRowBudget.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairMapSuccessBudget
+import OAI.Computability.VPVNP.PairSimulationShrinkRowAction
+
+/-! # Native costs of a selected shrinking map row
+
+The route uses a published resident identifier, a grid identifier and one
+layout flag. The private operand-gather trace and the matrix descriptor
+writer are charged on the scratch snapshot at this occurrence.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.ShrinkSlots
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifGrid MotifBlocks MotifConversion MapResidentRows MapHandlerOperand NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {t shared w g endAddr : ℕ} (F : MapHandlerImage.Family B t shared) (G : ShrinkGatherBank.Family F)
+ (X : State G.a (packingLaneBits G.a g)) {δ : ℝ}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} (sel : X.ShrinkSelection B)
+ (site : Site X) (m : Memory w) (level term : Word w)
+
+/-- Classical decidable equality on the compression state’s base vertices for the cost bounds
+of a selected shrinking map row. -/
+private noncomputable local instance rowBudgetBase : DecidableEq X.Base := Classical.decEq _
+variable {side : Bool} (R : MapRowSource X sel side m level term)
+ (i : Fin (order X side site).length)
+ (I : LocalHistory.EntryInput B) {jobMotif : X.packingData.Motif}
+ (J : ShrinkPartyNative.Job (a := G.a) (b := G.b) (g := g) X B ready sel jobMotif I.party w)
+ (hw : MapConstants.widthThreshold B ≤ w) (pub : Fin 5 → Word w)
+ (W : Workspace F demandMass_pos I) (saved : DFS.Scratch w endAddr)
+
+local notation "key" => Prod.mk (demandGrid B demandMass_pos I.demand) I.party
+local notation "st" => rowOrdinalWord (w := w) (a := G.a) (g := g) X side site i
+local notation "gTrace" => J.trace (G.operands (key)) (G.node (key)) pub (st) m
+
+/-- The two finite selector chains are the only variable part of the route. -/
+theorem routeEvents_length :
+ (routeEvents X sel side site m level term R i).length =
+ 15 + 2*((demandOrder B.grid.demands).symm (rowGrid (B := B) X side site i)).val +
+ 2*(entry X side site i).2.val := by
+ simp only [routeEvents,List.length_append,List.length_replicate,
+ (MapResidentInputs.itemCost ..).1,(ShrinkLayoutBranch.cost ..).1]
+ omega
+
+set_option maxHeartbeats 1400000 in
+-- The row trace transports the party-indexed gather through the selected matrix handler.
+/-- A successful routed gather and matrix, including its concrete writes
+to the histogram. The gather trace is the one for this job, with its real
+stage-, term- and party-dependent operands. -/
+theorem rowAction_cost {es : List (Event w)} {out : DFS.Scratch w endAddr}
+ (hit : rowAction F G X sel site m level term R i I J hw pub W saved = some (es, out)) :
+ es.length ≤ 15 + 2*Fintype.card B.grid.demands + 12 +
+ (gTrace).length + F.clock (key) (repetitions B I.demand) ∧
+ countProbes es = 3 + countProbes (gTrace) + F.probes (key) := by
+ unfold rowAction at hit
+ obtain ⟨⟨front,up⟩,gathered,routed⟩ := Option.map_eq_some_iff.mp hit
+ unfold gatheredAction at gathered
+ obtain ⟨⟨trace,last⟩,matrix,copied⟩ := Option.map_eq_some_iff.mp gathered
+ obtain ⟨_,equal,_⟩ := (F.action_some_iff demandMass_pos I hw pub (st) m W endAddr
+ (J.updated endAddr saved)).mp matrix
+ rw [← (Prod.mk.inj routed).1,← (Prod.mk.inj copied).1,equal]
+ obtain ⟨bound,probes⟩ := F.successEvents_cost demandMass_pos I hw pub (st) m
+ have grid := ((demandOrder B.grid.demands).symm (rowGrid (B := B) X side site i)).isLt
+ simp only [Finset.length_toList, ← Fintype.card_coe] at grid
+ have party := (entry X side site i).2.isLt
+ simp only [List.length_append,countProbes_append,routeEvents_length,
+ (routeEvents_cost X sel side site m level term R i).1,probes]
+ omega
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkScanCoefficient.lean b/lean/OAI/Computability/VPVNP/PairShrinkScanCoefficient.lean
new file mode 100644
index 0000000000..3b8ac5ed4d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkScanCoefficient.lean
@@ -0,0 +1,44 @@
+import OAI.Computability.VPVNP.PairShrinkVertexImage
+import OAI.Computability.VPVNP.PairShrinkGatherClock
+import OAI.Computability.VPVNP.PairSimulationMapResidentRows
+import OAI.Computability.VPVNP.PairSimulationMapHandlerClock
+import OAI.Computability.VPVNP.ShrinkFieldBounds
+
+/-! # The fixed coefficient of the installed shrinking map scan -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open Compression Compression.ShrinkMotif CompressorRecords
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+
+local notation "F" => ShrinkVertexImage.matrixFamily B ord i
+local notation "G" => ShrinkVertexImage.gatherFamily B ord i
+
+/-- The finite clock table yields one constant for all grid and party
+choices, before incorporating the fixed resident gather rows. -/
+noncomputable def matrixFactor : ℕ :=
+ (F).clockFactor * ((MapNativeClock.uniform B.shrink).choose+1) * (fieldFactor B.shrink+1)
+
+/-- One fixed coefficient for the scheduled stage covers all stored
+resident rows, their operand copies and the repeated private matrices. -/
+noncomputable def stageCoefficient : ℕ :=
+ let Q := (G).clockConstant (fieldFactor B.shrink+1)
+ let stageRows := MapResidentRows.capacity (S.degreeExponent i.castSucc)
+ 1+2*stageRows+stageRows*(27+2*Fintype.card B.shrink.grid.demands+Q+matrixFactor B ord i)+
+ stageRows*(3+Q+(F).probeBound)
+
+/-- Sum of the resident-map cost coefficients over the shrinking stages in one fixed block
+schedule. -/
+noncomputable def scanCoefficient : ℕ := ∑ i : Fin S.steps, stageCoefficient B ord i
+
+end PairSimulation.ShrinkRole.MapWitness
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSelectedCapacity.lean b/lean/OAI/Computability/VPVNP/PairShrinkSelectedCapacity.lean
new file mode 100644
index 0000000000..39967684d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSelectedCapacity.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.PairShrinkCallCapacity
+import OAI.Computability.VPVNP.PairShrinkGeometryLimit
+import OAI.Computability.VPVNP.PairShrinkRoleHandoff
+
+/-!
+# Shrinking workspace capacity for a rectangular descriptor allocation
+
+Each old-level state is transported along its packing-lane equality. Its
+hidden fields start at the end of the native scalar verifier stacks. The
+polynomial upper address is fixed before specializing coefficients or choosing
+compression terms, vertices, and local copy counts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkCallCapacity
+
+open CursorNetwork CursorBounds Compression Compression.ShrinkMotif
+open CompressorRecords Filter TraversalRows MotifConversion ShrinkCallFields
+
+private theorem reindex_bounds {a l g : ℕ} (Z : State a l) (eqn : l = packingLaneBits a g) :
+ let X : State a (packingLaneBits a g) := eqn ▸ Z
+ X.positions = Z.positions ∧ X.maxWireWidth = Z.maxWireWidth := by
+ subst l
+ exact ⟨rfl, rfl⟩
+
+/-- The real old child row lies inside the terminal reservation whenever its
+layer is the published prefix of the complete selected row list. -/
+theorem layer_addresses {a g : ℕ} (X : State a g) (cap firstRow : ℕ)
+ (before after : List Layer) (current : Layer) (count : current.count = X.positions)
+ (v : X.network.Site) :
+ firstRow + words cap before + (cap + 2) * PortRefresh.ArgumentAddress.siteOrdinal X v <
+ firstRow + words cap (before ++ current :: after) := by
+ have ord : PortRefresh.ArgumentAddress.siteOrdinal X v < X.positions := by
+ unfold PortRefresh.ArgumentAddress.siteOrdinal State.positions
+ rw [Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv g), Fintype.card_fin]
+ have hb := (X.baseIndex v.1).isLt
+ have hl := (bitWordFinEquiv g v.2).isLt
+ calc
+ _ < (X.baseIndex v.1).val * 2 ^ g + 2 ^ g := Nat.add_lt_add_left hl _
+ _ = ((X.baseIndex v.1).val + 1) * 2 ^ g := (Nat.succ_mul ..).symm
+ _ ≤ _ := Nat.mul_le_mul_right _ hb
+ have step := Nat.mul_lt_mul_of_pos_left (count ▸ ord) (by omega : 0 < cap + 2)
+ simp only [words, List.map_append, List.map_cons, List.sum_append, List.sum_cons,
+ Nat.mul_add]
+ omega
+
+open BurstRAM in
+open scoped Fin.CommRing in
+/-- Both words produced by the hidden handoff have their exact natural
+values in the reserved region, including the square stride. -/
+theorem handoff_words {w n motifs : ℕ} (G : LeafArena.Regions)
+ (room : mapBase G (Fintype.card LeafStartup.ScalarPort) n + extent motifs n < 2 ^ w) :
+ (VertexLevel.hiddenBaseWord (G.cacheBase : Word w) (n : Word w)).val =
+ mapBase G (Fintype.card LeafStartup.ScalarPort) n ∧
+ ((n : Word w) * (n : Word w)).val = n * n := by
+ have baseFit : mapBase G (Fintype.card LeafStartup.ScalarPort) n < 2 ^ w := by omega
+ have strideFit : n * n < 2 ^ w := by
+ unfold extent at room
+ rw [pow_two] at room
+ omega
+ rw [VertexLevel.hiddenBaseWord_cast, ← Nat.cast_mul]
+ exact ⟨Nat.mod_eq_of_lt baseFit, Nat.mod_eq_of_lt strideFit⟩
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k}
+
+open Classical in
+/-- Scratch and copy bound used by the actual selected map. -/
+noncomputable abbrev SelectedFits {a g : ℕ} (X : State a (packingLaneBits a g))
+ (B : S.Templates) (sel : X.ShrinkSelection B.shrink) (m : X.packingData.Motif)
+ (G : LeafArena.Regions) (b n limit older pitch : ℕ) : Prop :=
+ let demand := X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m
+ let scratch := ShrinkCallHeader.scratch X (mapBase G (Fintype.card LeafStartup.ScalarPort) n)
+ (n * n) G.histBase
+ Fits (w := wordBits b n) (n := n) (limit := limit) (u := repetitions B.shrink demand)
+ (t := Fintype.card B.Entry) B.shrink demand (sel m).val scratch
+ (ShrinkMotifOrder.stateNumber X m).val (ShrinkCallHeader.cdBase X m G.arguments older pitch)
+
+/-- The terminal layout with the dedicated map reserve fits a live word.
+The scalar cache and all its stacks precede every shrink call's hidden word. -/
+theorem eventually_reserved (B : S.Templates) (u : PairExponents B.growthConstant)
+ (D : DescriptorSpace.Shape) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {start : ℕ → ℕ} (hs : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let L := DescriptorSpace.cursorLayout D b S.steps u.θ (start n) n
+ ∀ z : (B.execute f hf T hT X).Choices,
+ let rows := words B.recordLimit (selectedLayers B f hf T hT X z)
+ let G := NativeFrame.regions (slotDegree S) n (DescriptorSpace.endAddress L)
+ rows (Fintype.card B.Entry)
+ mapBase G (Fintype.card LeafStartup.ScalarPort) n +
+ extent (initialPositions b n * slotDegree S) n < 2 ^ wordBits b n := by
+ let extra n := extent (initialPositions b n * slotDegree S) n
+ have poly : PolynomiallyBounded extra := extent_bounded
+ ((CursorRAM.bounded_positions b).mul (.const (slotDegree S)))
+ filter_upwards [TerminalLayout.eventually_fitWithReserve B u D b hb hs
+ (Fintype.card LeafStartup.ScalarPort) extra poly] with n fit
+ intro base lanes labels hD hT R _ f hf X T L z rows G
+ exact (fit labels hD hT R f hf z).2.2.2
+
+open Classical in
+/-- The actual admitted map has fitted fields and capacity on every selected
+shrinking level. The remaining numerical row premise locates the published
+child layer inside the selected DFS rows. -/
+theorem eventually_selected (B : S.Templates) (u : PairExponents B.growthConstant)
+ (D : DescriptorSpace.Shape) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {start : ℕ → ℕ} (hs : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ let initial := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let L := DescriptorSpace.cursorLayout D b S.steps u.θ (start n) n
+ ∀ z : (B.execute f hf T hT initial).Choices,
+ let labelsN := Fintype.card B.Entry
+ let ports := Fintype.card LeafStartup.ScalarPort
+ let rows := words B.recordLimit (selectedLayers B f hf T hT initial z)
+ let G := NativeFrame.regions (slotDegree S) n (DescriptorSpace.endAddress L) rows labelsN
+ let limit := NativeFrame.postStackLimit (slotDegree S) b start labelsN ports n +
+ extent (initialPositions b n * slotDegree S) n
+ ∀ v ∈ executeLevels B f hf T hT initial z, ∀ {g : ℕ}
+ (eqn : v.inputLanes = packingLaneBits v.inputExponent g),
+ let X : State v.inputExponent (packingLaneBits v.inputExponent g) := eqn ▸ v.input
+ ∀ (sel : X.ShrinkSelection B.shrink) (m : X.packingData.Motif) (older pitch : ℕ),
+ (∀ site : X.network.Site,
+ older + pitch * PortRefresh.ArgumentAddress.siteOrdinal X site < G.nodes) →
+ SelectedFits X B sel m G b n limit older pitch := by
+ let labelsN := Fintype.card B.Entry
+ let ports := Fintype.card LeafStartup.ScalarPort
+ let work := NativeFrame.postStackLimit (slotDegree S) b start labelsN ports
+ have hb₁ : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ have cap := eventually_terminal_fits B.shrink b (slotDegree S) labelsN ports hb₁
+ (workLimit := work) (NativeFrame.postStackLimit_bounded _ _ hs _ _)
+ filter_upwards [cap, eventually_levels B u b hb (fieldFactor B.shrink + 1),
+ NativeFrame.eventually_selected_histBase B u D b hb hs] with n fits fields hist
+ intro base lanes labels hD hT R _ f hf initial T L z count wordsN rows G limit v hv g eqn
+ X sel m older pitch node
+ have live := fields labels hD hT R f hf z v hv
+ obtain ⟨hp, hw⟩ := reindex_bounds v.input eqn
+ have hhist := hist labels hD hT R f hf z (slotDegree S) count
+ have endFit := NativeFrame.postStack_le wordsN hhist
+ exact fits X sel m (DescriptorSpace.endAddress L) rows older pitch endFit v.oldDegree_le
+ (hp ▸ live.1) (hw ▸ live.2) node
+
+end PairSimulation.ShrinkCallCapacity
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSelectedExponentBound.lean b/lean/OAI/Computability/VPVNP/PairShrinkSelectedExponentBound.lean
new file mode 100644
index 0000000000..8a182de65e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSelectedExponentBound.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.PairShrinkNodeLabelBudget
+import OAI.Computability.VPVNP.PairTraversalRoles
+import OAI.Computability.VPVNP.PairSelectedKernelReaders
+import OAI.Computability.VPVNP.CompressorLevelCounts
+
+/-! # Histogram headroom at a selected shrinking level
+
+The tag determines the scheduled shrinking pass. Its resident map witnesses
+give the exponents of the selected reader, and the branch width bound controls
+the number of copies in each resident map.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open Compression Compression.ShrinkMotif CompressorRecords LocalHistory TraversalRoles
+
+variable {k K : Type*} [Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+
+local notation "reader" v => originReader B f hf (SelectedLevel.origin v) (SelectedLevel.term v)
+
+/-- Each coordinate of the exponent vector contributed by one shrinking
+vertex fits the quadratic histogram allowance. -/
+theorem level_exponent_le_square (v : SelectedLevel B f hf) (shrink : tagLevel B f hf v = .shrink)
+ {n : ℕ} (hn : 1 ≤ n) (width : v.input.maxWireWidth ≤ n)
+ (large : ∀ j : Fin S.steps,
+ 2 * (MapResidentRows.capacity (S.degreeExponent j.castSucc) * fieldFactor B.shrink) ≤ n) :
+ ∀ u b a x l, ((reader v).witness u a b).exponents x l ≤ n ^ 2 := by
+ rcases v with ⟨deg, lanes, outDeg, outLanes, Y, p, origin, term, tape⟩
+ cases origin with
+ | shrink j eqn Y =>
+ subst lanes
+ intro u b a x l
+ exact MapWitness.exponent_le_square B f hf j Y term u a b x l hn width (large j)
+ | refresh => cases shrink
+
+/-- At every shrinking vertex on the chosen execution, the input width
+estimate of the branch suffices for the per-coordinate histogram bound. -/
+theorem selected_exponent_le_square {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+ (i : Fin (executeLevels B f hf T hT X z).length)
+ (shrink : tagLevel B f hf (executeLevels B f hf T hT X z)[i] = .shrink)
+ {n : ℕ} (hn : 1 ≤ n) (width : B.growthConstant ^ T * (X.maxWireWidth + 1) ≤ n)
+ (large : ∀ j : Fin S.steps,
+ 2 * (MapResidentRows.capacity (S.degreeExponent j.castSucc) * fieldFactor B.shrink) ≤ n) :
+ ∀ u b a x l,
+ ((reader ((executeLevels B f hf T hT X z).get i)).witness u a b).exponents x l ≤ n ^ 2 :=
+ level_exponent_le_square B f hf _ shrink hn
+ ((executeLevels_limits B f hf T hT X z _ (List.getElem_mem _)).2.trans width) large
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSelectedFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkSelectedFootprint.lean
new file mode 100644
index 0000000000..7947d44122
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSelectedFootprint.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.PairSelectedPacketGeometry
+import OAI.Computability.VPVNP.PairShrinkPhysicalSiteBank
+import OAI.Computability.VPVNP.PairShrinkRoleMapStartReads
+import OAI.Computability.VPVNP.PairShrinkCanonicalFootprint
+import OAI.Computability.VPVNP.PairShrinkSiteLocatorFootprint
+import OAI.Computability.VPVNP.PairShrinkSiteStartFootprint
+import OAI.Computability.VPVNP.PairShrinkSitePhysical
+
+/-!
+# External reads at a selected shrinking vertex
+
+The physical site selects its map header, owner count, term descriptor and
+interval banks from the chronological compressor payload. Their addresses
+lie below the terminal controller in the same memory used by the vertex.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) {G : Group} {n limit : ℕ}
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence BlockProgram.layout
+ BlockSchedule.Templates.execute StateExecution.finalState executeLevels
+set_option quotPrecheck false
+local notation "pub" => terminalOperands G
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val X.positions T
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "rowBase" => endAddress D
+local notation "rowEnd" => rowBase + words B.recordLimit (selectedLayers B f hf T hT X z)
+local notation "labelCount" => Fintype.card B.Entry
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ {baseBits laneBits ord : ℕ} {calendar reference phy : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n)
+ (executeLevels B f hf T hT X z) calendar)
+ (entry : TerminalProgram.VertexEntry (w := G.w) B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+ (packed : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ord phy)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+
+local notation "sites" => ShrinkRoleDirectory.ShrinkSite passes
+local notation "before" j => layerBase B.recordLimit rowBase tags j
+
+variable (fits : ∀ x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z),
+ ∀ m, canonicalFits B x.occurrence.i x.occurrence.state x.occurrence.selection (w := G.w)
+ (Fintype.card B.Entry) n
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T) +
+ words B.recordLimit (selectedLayers B f hf T hT X z))
+ (layerBase B.recordLimit
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T))
+ (TraversalRoles.selected B f hf T hT X z) x.val.1.val) limit m)
+variable (x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z))
+local notation "atSite" => physicalSiteBank B f hf hT X z history entry packed frame width fits x
+local notation "occ" => x.occurrence
+local notation "owner" => (MapResidentRows.siteIndex (occ).state (occ).site).val
+local notation "hdr" => vertexHeader G
+
+/-- The published map headers and all their resident rows lie inside the
+producing level, strictly below the terminal control cells. -/
+theorem physicalSiteBank_mapArea :
+ (atSite).source.InLevel D x.val.1.val ∧ levelStart D (x.val.1.val + 1) ≤ (hdr).val := by
+ have payload := CompiledResident.shrink_vertex (G := G) history entry packed frame
+ x.val.1 (occ).selected
+ have below : endAddress D ≤ (hdr).val :=
+ (Nat.le_add_right ..).trans ((Nat.le_add_right ..).trans packed.arena)
+ refine ⟨?_, (levelStart_mono D payload.bounds.nextLive.le).trans below⟩
+ exact compiledSite_inLevel B f hf (occ).i (occ).state (occ).selection (occ).site
+ pub (pub 2) X.positions T x.val.1.val n rowEnd (before x.val.1.val) (before (x.val.1.val + 1))
+ limit (passes).length phy payload width (fits x)
+
+/-- The four header loads and the indirect load of the site's resident
+count in the compiled reader preserve external memory. -/
+theorem physicalSiteBank_mapStart_footprint (node : Word G.w) (saved : DFS.Scratch G.w n) :
+ let load := ShrinkVertexImage.mapStartSetup phy (atSite).level (owner : Word G.w)
+ let es := load.trace node saved
+ SourceTransport.Reads (TerminalLink.workerCell hdr) es ∧
+ SourceTransport.Writes (fun _ ↦ False) es := by
+ dsimp only
+ have payload := CompiledResident.shrink_vertex (G := G) history entry packed frame
+ x.val.1 (occ).selected
+ have area := physicalSiteBank_mapArea B f hf hT X z history entry packed frame width fits x
+ have heads := compiledSite_published B f hf (occ).i (occ).state (occ).selection (occ).site
+ pub (pub 2) X.positions T x.val.1.val n rowEnd (before x.val.1.val) (before (x.val.1.val + 1))
+ limit (passes).length phy payload width (fits x)
+ have hroom := packed.room
+ constructor
+ · exact ShrinkVertexImage.mapStart_worker_reads B (occ).i (atSite).source (occ).site hdr
+ (by omega) (area.1.headerEnd.le.trans area.2) (area.1.rowsEnd.trans area.2) heads
+ · exact ShrinkVertexImage.mapStartSetup_noWrites phy (atSite).level (owner : Word G.w) node saved
+
+local notation "leaf" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+
+set_option maxHeartbeats 1800000 in
+-- Identify the selected input and output sites throughout the packed source and parser.
+/-- On any accepted tape the selected shrinking row returns its original
+external memory. Every external read belongs to the live terminal worker. -/
+theorem physicalSiteBank_trace (labelOrder : B.Entry → Fin labelCount) (node : Word G.w)
+ (saved : DFS.Scratch G.w n) (bits : List Bool) (job : DFS.VisitPath G.w n) (tail : List Bool)
+ (atRow : node.val = ShrinkRoleDirectory.address B.recordLimit rowBase leaf passes x.val)
+ (hit : (canonicalParent (atSite) labelOrder f hf).read node saved bits = some (job, tail)) :
+ after phy job.trace = phy ∧ SourceTransport.Reads (TerminalLink.workerCell hdr) job.trace := by
+ have payload := CompiledResident.shrink_vertex (G := G) history entry packed frame
+ x.val.1 (occ).selected
+ have area := physicalSiteBank_mapArea B f hf hT X z history entry packed frame width fits x
+ have heads := compiledSite_published B f hf (occ).i (occ).state (occ).selection (occ).site
+ pub (pub 2) X.positions T x.val.1.val n rowEnd (before x.val.1.val) (before (x.val.1.val + 1))
+ limit (passes).length phy payload width (fits x)
+ obtain ⟨_, sources⟩ := ShrinkSiteBank.rowSources_vertex B f hf hT X z X.positions n
+ x.val.1 (occ).i (occ).state (occ).selection _ (occ).selected history entry packed frame
+ have hroom := packed.room
+ have beforeHeader : endAddress D ≤ (hdr).val :=
+ (Nat.le_add_right ..).trans ((Nat.le_add_right ..).trans packed.arena)
+ have result := canonicalParent_worker (atSite) labelOrder f hf hdr node saved bits job tail
+ (by omega) beforeHeader rfl payload rfl area.1 area.2 heads
+ (physicalSiteBank_locator_footprint B f hf hT X z history entry packed frame width fits
+ x node saved)
+ (fun out rest read ↦ physicalSiteBank_child_footprint B f hf hT X z history entry packed frame
+ width fits x atRow read)
+ (fun parent old q ↦ sources (occ).site old parent q) hit
+ exact ⟨result.2, result.1⟩
+
+/-- The actual row pointer in the selected traversal fits its word. At this
+pointer every successful canonical read satisfies the external-memory laws. -/
+theorem physicalSiteBank_rowTrace (labelOrder : B.Entry → Fin labelCount)
+ (saved : DFS.Scratch G.w n) (bits : List Bool) (job : DFS.VisitPath G.w n) (tail : List Bool)
+ (hit : (canonicalParent (atSite) labelOrder f hf).read
+ (ShrinkRoleDirectory.address B.recordLimit rowBase leaf passes x.val : Word G.w) saved bits =
+ some (job, tail)) :
+ after phy job.trace = phy ∧ SourceTransport.Reads (TerminalLink.workerCell hdr) job.trace := by
+ have tagEq : tagWords B.recordLimit tags = words B.recordLimit (selectedLayers B f hf T hT X z) :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ have room := packed.arena
+ have limit₀ : (hdr).val < 2 ^ G.w := (hdr).isLt
+ have fit : layerBase B.recordLimit rowBase tags ((passes).length + 1) ≤ 2 ^ G.w := by
+ rw [TreeDecode.selected_endBase, ← tagEq]
+ omega
+ have decoded := ShrinkRoleDirectory.decode_address B.recordLimit rowBase leaf passes fit x
+ exact physicalSiteBank_trace B f hf hT X z history entry packed frame width fits x labelOrder
+ _ saved bits job tail
+ ((ShrinkRoleDirectory.decode_eq_some_iff B.recordLimit rowBase leaf passes fit _ x).mp decoded)
+ hit
+
+end PairSimulation.ShrinkRole
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSelectedKernelTransport.lean b/lean/OAI/Computability/VPVNP/PairShrinkSelectedKernelTransport.lean
new file mode 100644
index 0000000000..f825393fd4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSelectedKernelTransport.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.PairShrinkSelectedWitness
+
+/-!
+# Reindexing the shrinking kernel at a selected physical row
+
+Recovering the scheduled index and state from an origin preserves the
+placed arguments and every witness of the local product. In particular,
+the transported visit uses the same bits, exponent vector and ordered
+child packets, even when several residents emit the same label.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRoleDirectory
+
+open BurstRAM Compression CompressorRecords LocalHistory NodeArguments NetworkKernel
+open TreeDecode TraversalRows TraversalRoles
+set_option quotPrecheck false
+
+variable {k K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f} (v : SelectedLevel B f hf)
+ (u : (v.pass.step.term v.term).output.Site) (h : tagLevel B f hf v = .shrink)
+
+local notation "x" => occurrence v u h
+local notation "Z" => (x).state
+local notation "j" => (x).i
+local notation "sel" => (x).selection
+local notation "site" => (x).site
+local notation "r₀" => originReader B f hf v.origin v.term
+local notation "r₁" => (shrinkPassReaders B f hf j rfl Z).termParsers sel
+
+variable (z : (v.pass.step.term v.term).output.Half u)
+ (a : Placed (v.pass.step.term v.term).place v.input.network.Half u)
+local notation "parent" => halfEquiv v u h z
+local notation "old" => placedEquiv v u h a
+
+attribute [local irreducible] nodeReader shrinkPassReaders
+
+set_option maxHeartbeats 1500000 in
+-- Normalize the occurrence and its transported half without unfolding the node parser.
+/-- Reindexing the parent preserves the unread suffix on every bit stream. -/
+theorem node_suffix (bs : List Bool) :
+ ((nodeReader r₀ u z).read bs).map Prod.snd =
+ ((nodeReader r₁ site parent).read bs).map Prod.snd := by
+ rcases v with ⟨a,g,b,n,Y,p,origin,t,tape⟩
+ cases origin with
+ | shrink stage lengthEq Y =>
+ subst g
+ dsimp only [halfEquiv, occurrence, originReader, ShrinkOccurrence.nextState]
+ exact congrArg (fun zz => ((nodeReader ((shrinkPassReaders B f hf stage rfl Y).termParsers t)
+ u zz).read bs).map Prod.snd) (Equiv.refl_apply z).symm
+ | refresh => cases h
+
+set_option maxHeartbeats 1500000 in
+-- Compute the ordered finite placement fiber before comparing the child lists.
+theorem children_packets (base : ℕ) :
+ TreeDecode.children r₀
+ (fun t y => ⟨(sitePointers B.recordLimit base (siteOrder v.input) t).1, packed v.input t y⟩)
+ u a =
+ TreeDecode.children r₁
+ (fun t y => ⟨NodeArguments.ChildScan.childNode Z base B.recordLimit t, packed Z t y⟩)
+ site old := by
+ rcases v with ⟨a,g,b,n,Y,p,origin,t,tape⟩
+ cases origin with
+ | shrink stage lengthEq Y =>
+ subst g
+ rfl
+ | refresh => cases h
+
+end PairSimulation.ShrinkRoleDirectory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSelectedOccurrence.lean b/lean/OAI/Computability/VPVNP/PairShrinkSelectedOccurrence.lean
new file mode 100644
index 0000000000..d8dca45f6a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSelectedOccurrence.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PairVertexRoleDomains
+import OAI.Computability.VPVNP.PairSimulationMapResidentRows
+import OAI.Computability.VPVNP.CompressorLevelOrder
+
+/-! # The selected shrinking state and packed argument at a physical site -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRoleDirectory
+
+open Compression CompressorRecords LocalHistory TraversalRoles TraversalRows NodeArguments TreeDecode
+open private next_number from OAI.Computability.VPVNP.CompressorRecordsShrinkPreimages
+
+variable {k K : Type*} [Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f}
+
+/-- The selected chronological level at a particular scheduled shrink degree. -/
+noncomputable def shrinkLevel (i : Fin S.steps) {g : ℕ}
+ (Z : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : Z.ShrinkSelection B.shrink) (tape : List Bool) : SelectedLevel B f hf :=
+ ⟨_,_,_,_,Z,_,.shrink i rfl Z,sel,tape⟩
+
+/-- Specialize a dependent statement about a selected shrinking level and
+its output site to the actual input state, selection and scheduled index. -/
+theorem of_selected_shrink
+ (P : (v : SelectedLevel B f hf) → (v.pass.step.term v.term).output.Site → Prop)
+ (run : ∀ (i : Fin S.steps) (g : ℕ)
+ (Z : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : Z.ShrinkSelection B.shrink) (tape : List Bool) (u : MapResidentRows.Site Z),
+ P (shrinkLevel i Z sel tape) u)
+ (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site)
+ (h : tagLevel B f hf v = .shrink) : P v u := by
+ rcases v with ⟨a,g,b,n,Z,pass,origin,term,tape⟩
+ cases origin with
+ | shrink i hlen Z =>
+ subst g
+ exact run i _ Z term tape u
+ | refresh => cases h
+
+/-- The operands and numerical ordinal of the map row chosen by this level.
+Its input and selection are recovered from the actual stored pass origin. -/
+structure ShrinkOccurrence (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site) where
+ /-- The degree transition in the fixed block schedule. -/
+ i : Fin S.steps
+ /-- The number of residual lane coordinates. -/
+ lanes : ℕ
+ /-- The original state before this transition. -/
+ state : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) lanes)
+ /-- The admitted choice at each motif of the input state. -/
+ selection : state.ShrinkSelection B.shrink
+ /-- The native packed output site addressed by the vertex reader. -/
+ site : MapResidentRows.Site state
+ selected : v = shrinkLevel i state selection v.selector
+ index : v.origin.ordinal = i.val
+ ordinal : (MapResidentRows.siteIndex state site).val = ((outputOrder v).entries.symm u).val
+ /-- The independent input half of this row in both network presentations. -/
+ halves : (v.pass.step.term v.term).output.Half u ≃
+ (state.shrinkNext B.shrink (S.shrink i) selection).network.Half site
+ packed_eq : ∀ z, pullBits (v.pass.output_eq v.term) (packed (v.pass.next v.term)) u z =
+ packed (state.shrinkNext B.shrink (S.shrink i) selection) site (halves z)
+
+/-- Decode the selected output occurrence, preserving its site and chronological ordinal. -/
+noncomputable def occurrence (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site)
+ (h : tagLevel B f hf v = .shrink) : ShrinkOccurrence v u := by
+ rcases v with ⟨a,g,b,n,Z,pass,origin,term,tape⟩
+ cases origin with
+ | shrink i hlen Z =>
+ subst g
+ refine ⟨i,_,Z,term,u,rfl,rfl,?_,Equiv.refl _,fun _ => rfl⟩
+ exact (next_number Z B.shrink (S.shrink i) term (packedSiteEquiv.symm u)).symm
+ | refresh => cases h
+
+/-- Resolve a physically decoded shrinking-row address to its kernel operands. -/
+noncomputable abbrev ShrinkSite.occurrence {passes : List (SelectedLevel B f hf)} (x : ShrinkSite passes) :=
+ ShrinkRoleDirectory.occurrence passes[x.val.1] x.val.2 x.property
+
+/-- The native output state read at a recovered shrinking occurrence. -/
+noncomputable abbrev ShrinkOccurrence.nextState {v : SelectedLevel B f hf}
+ {u : (v.pass.step.term v.term).output.Site} (x : ShrinkOccurrence v u) :=
+ x.state.shrinkNext B.shrink (S.shrink x.i) x.selection
+
+/-- Both directions on independent output half assignments of the real map row. -/
+noncomputable def halfEquiv (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site)
+ (h : tagLevel B f hf v = .shrink) : (v.pass.step.term v.term).output.Half u ≃
+ (occurrence v u h).nextState.network.Half (occurrence v u h).site :=
+ (occurrence v u h).halves
+
+/-- The address-level conversion preserves the literal packed bit list,
+including the ordering of the incoming and outgoing halves. -/
+theorem halfEquiv_packed (v : SelectedLevel B f hf) (u : (v.pass.step.term v.term).output.Site)
+ (h : tagLevel B f hf v = .shrink) (z : (v.pass.step.term v.term).output.Half u) :
+ pullBits (v.pass.output_eq v.term) (packed (v.pass.next v.term)) u z =
+ packed (occurrence v u h).nextState (occurrence v u h).site (halfEquiv v u h z) :=
+ (occurrence v u h).packed_eq z
+
+end PairSimulation.ShrinkRoleDirectory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSelectedParent.lean b/lean/OAI/Computability/VPVNP/PairShrinkSelectedParent.lean
new file mode 100644
index 0000000000..278c9e527b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSelectedParent.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairShrinkSelectedOccurrence
+import OAI.Computability.VPVNP.PairShrinkRoleParent
+import OAI.Computability.VPVNP.PairVertexRoleNativeLeaf
+
+/-! # The prepared parent packet at each selected shrinking row -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open BurstRAM PrivateRAM Compression CompressorRecords DFS NodeArguments TreeDecode LocalHistory
+open TraversalRows TraversalRoles ShrinkRoleDirectory
+open scoped Fin.CommRing
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence
+
+variable {k K : Type*} [Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f}
+variable {w endAddr a g : ℕ} (X : State a g) (cap base : ℕ)
+ (passes : List (SelectedLevel B f hf)) (R : LeafArena.Regions) (data : Fin 10 → Word w)
+ (offset : Word w) (vals : LeafSourceLoad.Static 34 → Word w)
+ (hist : Scratch w endAddr → B.Entry → ℕ) (nodeCap limit : ℕ) (x : ShrinkSite passes)
+
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "addr₀" => ShrinkRoleDirectory.address cap base (leaf₀) passes x.val
+local notation "occ₀" => x.occurrence
+local notation "out₀" => Output X cap base passes R data offset vals hist nodeCap limit x.val
+
+/-- The common vertex frame and the decoded parent assignment at the actual
+packed output site, with sufficient credit for every label's local increments. -/
+structure Parent (z : (occ₀).nextState.network.Half (occ₀).site) (s : Scratch w endAddr) : Prop where
+ frame : VertexFrameData R data offset vals s
+ credit : ∀ l, hist s l + nodeCap ≤ limit
+ fits : (Packet.mk (addr₀) (packed (occ₀).nextState (occ₀).site z)).Fits R.arguments w endAddr
+ stored : (Packet.mk (addr₀) (packed (occ₀).nextState (occ₀).site z)).Stored R.arguments s
+
+local notation "par₀" => Parent X cap base passes R data offset vals hist nodeCap limit x
+
+set_option maxHeartbeats 1000000 in
+/-- The physical output packet yields the precise independent output half
+used by the shrinking kernel, and conversely. -/
+theorem output_iff_parent (s : Scratch w endAddr) : out₀ s ↔ ∃ z, par₀ z s := by
+ let v := passes[x.val.1]
+ let u := x.val.2
+ let e := x.occurrence.halves
+ have eqn (z : (v.pass.step.term v.term).output.Half u) :
+ outputPacket X cap base passes x.val z =
+ Packet.mk (addr₀) (packed (occ₀).nextState (occ₀).site (e z)) :=
+ congrArg (Packet.mk (addr₀)) (x.occurrence.packed_eq z)
+ constructor
+ · intro out
+ obtain ⟨z,fit,stored⟩ := out.packet
+ rw [eqn] at fit stored
+ exact ⟨e z,out.frame,out.credit,fit,stored⟩
+ · rintro ⟨z,ok⟩
+ refine ⟨ok.frame,ok.credit,e.symm z,?_⟩
+ rw [eqn,e.apply_symm_apply]
+ exact ⟨ok.fits,ok.stored⟩
+
+/-- Each allowed local update has its literal natural value in the word
+histogram while this shrinking parent is being processed. -/
+theorem Parent.word_add {z : (occ₀).nextState.network.Half (occ₀).site} {s : Scratch w endAddr}
+ (parent : par₀ z s) (wordFit : limit < 2^w) (l : B.Entry) (delta : ℕ) (charge : delta ≤ nodeCap) :
+ ((hist s l : Word w)+(delta : Word w)).val = hist s l + delta := by
+ rw [← Nat.cast_add,Fin.val_natCast]
+ exact Nat.mod_eq_of_lt ((Nat.add_le_add_left charge _).trans (parent.credit l) |>.trans_lt wordFit)
+
+/-- At this particular output row the physical decoder recovers exactly the
+parent half consumed by its native map-and-child subroutine. -/
+theorem parent_exact {p r k' : ℕ} (M : Machine w p r k') (visit ret : Fin p)
+ (dfs : Fin 9 ↪ Fin r) (m : Memory w) (positive : 0 < w)
+ (family : (occ₀).nextState.network.Half (occ₀).site → HookParser w endAddr)
+ (checked : ∀ z, (family z).ExactOn (fun node s => node.val = (addr₀) ∧ par₀ z s) M visit ret dfs m) :
+ (ShrinkRole.parentParser (occ₀).nextState (occ₀).site R.arguments family).ExactOn
+ (fun node s => node.val = (addr₀) ∧ out₀ s) M visit ret dfs m :=
+ restrict (ShrinkRole.parentParser_exactOn (occ₀).nextState (occ₀).site R.arguments family M visit ret dfs m
+ positive (addr₀) (par₀) (fun _ _ h => h.stored) checked) fun _ s h =>
+ ⟨h.1,(output_iff_parent X cap base passes R data offset vals hist nodeCap limit x s).mp h.2⟩
+
+end PairSimulation.VertexImage.RoleDomains
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSelectedWitness.lean b/lean/OAI/Computability/VPVNP/PairShrinkSelectedWitness.lean
new file mode 100644
index 0000000000..5520e5d0a5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSelectedWitness.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PairShrinkSelectedOccurrence
+import OAI.Computability.VPVNP.PairShrinkRoleScheduledSuffix
+
+/-!
+# Witnesses of the shrinking kernel at a selected physical row
+
+Recovering the scheduled index and state from an origin preserves the
+placed arguments and every witness of the local product. In particular,
+the transported visit uses the same bits, exponent vector and ordered
+child packets, even when several residents emit the same label.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRoleDirectory
+
+open BurstRAM Compression CompressorRecords LocalHistory NodeArguments NetworkKernel
+open TreeDecode TraversalRows TraversalRoles
+set_option quotPrecheck false
+
+
+variable {k K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f} (v : SelectedLevel B f hf)
+ (u : (v.pass.step.term v.term).output.Site) (h : tagLevel B f hf v = .shrink)
+
+local notation "x" => occurrence v u h
+local notation "Z" => (x).state
+local notation "j" => (x).i
+local notation "sel" => (x).selection
+local notation "site" => (x).site
+local notation "tr" => (B.shrinkPassAt f hf j rfl Z).step.term sel
+local notation "r₀" => originReader B f hf v.origin v.term
+local notation "r₁" => (shrinkPassReaders B f hf j rfl Z).termParsers sel
+local notation "Old" => Placed (v.pass.step.term v.term).place v.input.network.Half u
+local notation "PhysicalOld" => Placed (tr).place (Z).network.Half site
+
+set_option maxHeartbeats 1200000 in
+-- Eliminate the index equality in the shrinking pass before reindexing its placed fields.
+/-- Old half-wire assignments at the recovered shrinking site. -/
+noncomputable def placedEquiv : Old ≃ PhysicalOld := by
+ rcases v with ⟨a,g,b,n,Y,p,origin,t,tape⟩
+ cases origin with
+ | shrink stage lengthEq Y =>
+ subst g
+ with_unfolding_all exact Equiv.refl _
+ | refresh => cases h
+
+variable (z : (v.pass.step.term v.term).output.Half u)
+ (a : Placed (v.pass.step.term v.term).place v.input.network.Half u)
+local notation "parent" => halfEquiv v u h z
+local notation "old" => placedEquiv v u h a
+
+set_option maxHeartbeats 1500000 in
+-- Both witness types are dependent products over the reindexed resident map calls.
+/-- Reindex the entire local witness, including its hidden fields and map choices. -/
+noncomputable def witnessEquiv :
+ ((r₀).witness u a z).Choice ≃ ((r₁).witness site old parent).Choice := by
+ rcases v with ⟨a,g,b,n,Y,p,origin,t,tape⟩
+ cases origin with
+ | shrink stage lengthEq Y =>
+ subst g
+ with_unfolding_all exact Equiv.refl _
+ | refresh => cases h
+
+attribute [local irreducible] nodeReader TermParsers.nodeBits shrinkPassReaders
+
+set_option maxHeartbeats 1500000 in
+-- The selected parser and its transported witness reduce at the actual pass origin.
+theorem witness_fields (c : ((r₀).witness u a z).Choice) :
+ let chosen := witnessEquiv v u h z a c
+ (r₀).nodeBits u a z c = (r₁).nodeBits site old parent chosen ∧
+ ((r₀).witness u a z).exponents c = ((r₁).witness site old parent).exponents chosen := by
+ rcases v with ⟨a,g,b,n,Y,p,origin,t,tape⟩
+ cases origin with
+ | shrink stage lengthEq Y =>
+ subst g
+ dsimp only [witnessEquiv, placedEquiv, halfEquiv, occurrence, originReader,
+ ShrinkOccurrence.nextState, Equiv.refl_apply]
+ with_reducible exact ⟨rfl, rfl⟩
+ | refresh => cases h
+
+end PairSimulation.ShrinkRoleDirectory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteActions.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteActions.lean
new file mode 100644
index 0000000000..9b936f6b10
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteActions.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+import OAI.Computability.VPVNP.PairShrinkLiveOperands
+import OAI.Computability.VPVNP.PairShrinkGatherQuiet
+
+/-!
+# Determinism and live operands of a scheduled shrinking site
+
+All occurrences share a single hidden region and argument arena. The loop
+carries its initial public registers, the argument words below the histogram
+and the shared hidden words. Each occurrence gathers and evaluates its own
+selected input.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.MapWitness
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkSlots ShrinkMapImage.Registers
+open ResidentMapLoop.Exact MapResidentRows
+
+variable {g : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t w endAddr : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+ (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : X.ShrinkSelection B.shrink) (v : MapResidentRows.Site X)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "side" => selectedLayout X B.shrink sel
+local notation "F" => ShrinkVertexImage.matrixFamily B ord i
+local notation "G" => ShrinkVertexImage.gatherFamily B ord i
+
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+ (jobs : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ ShrinkPartyNative.Job X B.shrink (S.shrink i) sel q.1.1 q.1.2 w)
+
+variable (m : Memory w) (level term : Word w)
+ (R : MapRowSource X sel (selectedLayout X B.shrink sel) m level term)
+ (hw : MapConstants.widthThreshold B.shrink ≤ w)
+ (pub : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v → Fin 5 → Word w)
+ (workspace : (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v) →
+ MapHandlerOperand.Workspace (w := w) (ShrinkVertexImage.matrixFamily B ord i)
+ demandMass_pos (jobInput B i X sel v hidden jobs q))
+
+set_option maxHeartbeats 1300000 in
+-- Each action gathers from the row's selected party, then runs its local matrix.
+/-- The packed resident action list is deterministic for every public row and map workspace. -/
+theorem quiet (act : Action w endAddr)
+ (ha : act ∈ actions B ord i X sel v hidden jobs m level term R hw pub workspace) :
+ NoChoices act := by
+ unfold actions at ha
+ obtain ⟨j, rfl⟩ := List.mem_ofFn.mp ha
+ let q := rowEquiv X side v j
+ let I := jobInput B i X sel v hidden jobs q
+ let key := MapHandlerOperand.index demandMass_pos I
+ intro _ saved es updated got
+ exact rowAction_noChoices (F) (G) X sel v m level term R j I (jobs q) hw (pub q)
+ (workspace q) saved ((jobs q).trace_noChoices ((G).operands key) ((G).node key) (pub q)
+ (rowOrdinalWord (w := w) X side v j) m) got
+
+end PairSimulation.ShrinkRole.MapWitness
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows ShrinkRole ShrinkRole.MapWitness
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {i : Fin S.steps}
+variable {g w n t : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+variable {sel : SelectedScore.Selection B X} {v : Site X}
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+variable (site : CanonicalSite B i X sel v w n t) (ord : B.Entry → Fin t)
+variable (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "J" => jobs B i X sel site.workspace site.positions site.blocks site.cur site.bounds
+ n site.rowEnd site.older site.later v old parent
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+
+/-- The row reader, interval gather and selected local matrix consume no choice bits. -/
+theorem actions_quiet (act : ResidentMapLoop.Exact.Action w n)
+ (inRow : act ∈ canonicalBank site ord parent old hidden) :
+ ResidentMapLoop.Exact.NoChoices act := by
+ unfold canonicalBank at inRow
+ exact MapWitness.quiet B ord i X sel v hidden (J) site.mem site.level site.term site.source
+ site.width _ _ act inRow
+
+variable {p r : ℕ} (common : Fin 24 ↪ Fin r) (initial : Config w p r)
+
+/-- Register and physical operand invariant, independent of the resident
+currently selected by the cursor. -/
+noncomputable abbrev siteInvariant (_ : Word w) (c : Config w p r) : Prop :=
+ ShrinkResidentMemory.Invariant
+ (ShrinkCallHeader.scratch X (ShrinkCallABI.hiddenBase regions n) (n ^ 2) (regions).histBase)
+ initial.privateMem (residentLive common) initial.reg c
+
+theorem siteInvariant_start (u : Word w) : siteInvariant site common initial u initial :=
+ ShrinkResidentMemory.Invariant.start _ initial _
+
+theorem siteInvariant_stable
+ (pc : Fin (shrinkSegment B ord).count → Fin p)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r) (done : Fin p) (u : Word w) :
+ (mapLoop B ord i pc reg done).Stable
+ (siteInvariant site (shared B ord i reg) initial u) :=
+ ShrinkResidentMemory.Invariant.stable _ _ _ _ _ (residentLive_cursor _)
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteBank.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteBank.lean
new file mode 100644
index 0000000000..1679221a93
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteBank.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalJob
+import OAI.Computability.VPVNP.PairShrinkMapJobInput
+import OAI.Computability.VPVNP.PairShrinkCallFrameLive
+
+/-!
+# The resident map jobs of a selected shrinking vertex
+
+One old assignment and one parent packet determine the inputs of every
+resident occurrence. Their placement equalities reindex those arguments
+without changing any bit. Every job in the bank uses the same private
+arena and the two row bases of this actual shrinking substep.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+private noncomputable local instance bankBase : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+variable (workspace : Word w) (positions blocks cur : ℕ)
+variable (bounds : ShrinkResidentSources.Bounds B i X workspace positions blocks cur)
+variable (n rowEnd older later : ℕ)
+variable (v : (X.Base × BitWord (packingTagBits (2 ^ a i))) × BitWord g)
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+
+/-- The actual fixed job for any motif and party assigned to this popped site. -/
+noncomputable def jobs (q : X.packingData.ResidentMap side v) :
+ ShrinkPartyNative.Job X B.shrink (S.shrink i) sel q.1.1 q.1.2 w :=
+ ShrinkCanonicalJob.job B i X (S.shrink i) sel q.1.1 q.1.2 workspace positions blocks cur
+ bounds n rowEnd older later
+ (Eq.rec (motive := fun y _ ↦ Placed (X.packingData.shrinkPlace side)
+ (X.packingData.oldWireNetwork X.packingWidth).Half y)
+ (ShrinkRole.MapWitness.placedOld B i X sel v old) q.2.symm)
+ (Eq.rec (motive := fun y _ ↦ (Y).network.Half y) parent q.2.symm)
+
+local notation "J" => jobs B i X sel workspace positions blocks cur bounds n rowEnd older later
+ v old parent
+
+set_option maxHeartbeats 1800000 in
+-- The two kernel arguments have dependent site indices in both network presentations.
+/-- The concrete resident read has exactly the demand and supply bit vectors
+of its selected local tensor witness. -/
+theorem input_eq (q : X.packingData.ResidentMap side v) :
+ ShrinkPartyNative.Job.entryInput B X (S.shrink i) sel q.1.1 q.1.2 (J q)
+ (q.2.symm ▸ hidden) = ShrinkRole.MapWitness.input B i X sel v old parent hidden q :=
+ ShrinkPartyNative.Job.entryInput_eq_witness B i X sel v old parent hidden q (J q) rfl rfl
+
+/-- The five shared input registers used at every resident of the site. -/
+noncomputable def pub (level node : Word w) (regions : LeafArena.Regions) (n : ℕ) :
+ Fin 5 → Word w :=
+ ![level, node, (NativeFrame.frameBase regions : Word w), (regions.histBase : Word w),
+ (ShrinkCallABI.hiddenBase regions n : Word w)]
+
+/-- The loaded node number is independent of the resident chosen by the row. -/
+theorem node_eq (q : X.packingData.ResidentMap side v) :
+ (J q).node = later + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal (Y) v := by
+ change later + (B.recordLimit + 2) * PortRefresh.ArgumentAddress.siteOrdinal (Y)
+ (X.packingData.shrinkPartySite side q.1.1 q.1.2) = _
+ rw [q.2]
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteFieldsFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteFieldsFootprint.lean
new file mode 100644
index 0000000000..58b9302f3e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteFieldsFootprint.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PairShrinkSiteSources
+import OAI.Computability.VPVNP.PairShrinkGatherTraceReads
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-!
+# Public trace of each certified resident occurrence
+
+The interval gathers and the map argument reads use the same recorded
+operand registers. Their read domains follow directly from the two
+published row banks and the selected term's extent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+private noncomputable local instance fieldReadsBase : DecidableEq X.Base := Classical.decEq _
+variable (workspace : Word w) (positions blocks cur : ℕ)
+variable (bounds : ShrinkResidentSources.Bounds B i X workspace positions blocks cur)
+variable (n rowEnd older later : ℕ)
+variable (v : (X.Base × BitWord (packingTagBits (2 ^ a i))) × BitWord g)
+variable (x : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+variable (phy : Memory w) (H : Word w)
+local notation "side" => selectedLayout X B.shrink sel
+variable (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v)
+local notation "job" => jobs B i X sel workspace positions blocks cur bounds n rowEnd older later
+ v x parent q
+local notation "L" => BlockProgram.layout B workspace.val positions blocks
+local notation "here" => levelStart L cur
+local notation "nextHead" => levelStart L (cur + 1)
+local notation "cut" => tableBase L cur (0 : Fin 6)
+local notation "T" => packedIncidence L w cur (DemandRAM.oldCount X)
+local notation "shape" => levelShape (b := b i) X
+local notation "U" => packedIncidence L w (cur + 1) (actualCount shape)
+local notation "term" => ShrinkInput.termHead (w := w) X cut
+local notation "heads" => ShrinkOutput.heads shape (SelectedArena.roleBase X term 10)
+ (tableBase L cur (3 : Fin 6))
+local notation "absHead" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X cut) w
+local notation "regns" => TerminalLayout.privateRegions (slotDegree S) n rowEnd
+ (Fintype.card B.Entry)
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "node" => (later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal Y v : ℕ)
+local notation "P" => pub (here : Word w) (node : Word w) regns n
+local notation "O" => ShrinkCallABI.operands (slotDegree S)
+local notation "motif" => Prod.fst (Subtype.val q)
+local notation "st" => Nat.cast (R := Word w) (Fin.val (ShrinkMotifOrder.stateNumber X motif))
+
+variable (sources : RowSources B i X sel workspace positions blocks cur bounds n rowEnd
+ older later v x parent phy H q)
+
+variable {B i X sel workspace positions blocks cur bounds n rowEnd older later v x parent phy H q}
+include sources
+
+/-- Each public interval setup and copy in this resident stays in the worker read domain. -/
+theorem RowSources.gather_reads (room : H.val + 31 < 2 ^ w) :
+ SourceTransport.Reads (TerminalLink.workerCell H)
+ ((job).trace O ShrinkCallABI.node P st phy) :=
+ (job).trace_reads O ShrinkCallABI.node P st phy (TerminalLink.workerCell H)
+ sources.old sources.next ((job).abi_readSafe (slotDegree S) H room
+ sources.old sources.next sources.abArea sources.supplyArea)
+
+/-- The complete successful matrix event sequence reads only the row's recorded operands. -/
+theorem RowSources.success_reads {t : ℕ} (ordinal : B.Entry → Fin t)
+ (arg : LocalHistory.EntryInput B.shrink) (width : MapConstants.widthThreshold B.shrink ≤ w)
+ (room : H.val + 31 < 2 ^ w) :
+ SourceTransport.Reads (TerminalLink.workerCell H)
+ ((ShrinkCallABI.family B (slotDegree S) (a i) ordinal).successEvents
+ demandMass_pos arg width P st phy) :=
+ TerminalFootprint.reads_mono ((job).abi_success_reads (slotDegree S) B ordinal
+ sources.old sources.abArea sources.termEnd arg width)
+ (fun _ lo ↦ TerminalLink.workerCell_of_lt room lo)
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteFootprint.lean
new file mode 100644
index 0000000000..a2e91bd7b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteFootprint.lean
@@ -0,0 +1,139 @@
+import OAI.Computability.VPVNP.PairShrinkSiteFieldsFootprint
+import OAI.Computability.VPVNP.PairShrinkSiteRouteBounds
+import OAI.Computability.VPVNP.PairShrinkGatherTraceReads
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+import OAI.Computability.VPVNP.PairShrinkAbstractFootprint
+import OAI.Computability.VPVNP.PairShrinkOrdinalSources
+
+/-!
+# Public memory reads of the canonical shrinking map scan
+
+The route reads the identifier, the term and the layout bit. The selected
+party reads its certified interval headers. The matrix writer reads its
+public address operands. The intervening cursor tests and all map writes
+use private memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM DFS Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords ShrinkBlockInputs ShrinkSlots SourceTransport DescriptorSpace
+open ShrinkRole ShrinkRole.MapWitness ShrinkVertexImage ShrinkMapImage.Registers
+open MapResidentRows ResidentMapLoop.Exact TerminalFootprint
+open scoped Fin.CommRing
+
+private abbrev safeEvents {w : ℕ} (allow : ℕ → Prop) (es : List (Event w)) :=
+ Reads allow es ∧ Writes (fun _ ↦ False) es
+
+private theorem tick_safe {w : ℕ} (allow : ℕ → Prop) : safeEvents allow [.tick (w := w)] := by
+ constructor <;> intro a v h <;> simp at h
+
+private theorem append_safe {w : ℕ} {allow : ℕ → Prop} {es fs : List (Event w)}
+ (h : safeEvents allow es) (f : safeEvents allow fs) : safeEvents allow (es ++ fs) :=
+ ⟨reads_append h.1 f.1, fun a v hit ↦ (List.mem_append.mp hit).elim (h.2 a v) (f.2 a v)⟩
+
+private theorem scan_safe {w n : ℕ} (allow : ℕ → Prop) (node : Word w)
+ (jobs : List (Action w n)) (saved : Scratch w n) {es : List (Event w)} {updated : Scratch w n}
+ (one : ∀ j ∈ jobs, ∀ prior trace next,
+ j node prior = some (trace, next) → safeEvents allow trace)
+ (returned : scan node jobs saved = some (es, updated)) : safeEvents allow es := by
+ induction jobs generalizing saved es updated with
+ | nil =>
+ simp only [scan, Option.some.injEq, Prod.mk.injEq] at returned
+ exact returned.1 ▸ tick_safe allow
+ | cons j js ih =>
+ cases step : j node saved with
+ | none => simp [scan, step] at returned
+ | some pair =>
+ obtain ⟨head, mid⟩ := pair
+ cases tail : scan node js mid with
+ | none => simp [scan, step, tail] at returned
+ | some pair =>
+ obtain ⟨rest, out⟩ := pair
+ simp only [scan, step, tail, Option.some.injEq, Prod.mk.injEq] at returned
+ have a := one j List.mem_cons_self saved head mid step
+ have b := ih mid (fun k h ↦ one k (List.mem_cons_of_mem _ h)) tail
+ exact returned.1 ▸ append_safe (append_safe (append_safe (tick_safe allow) a)
+ (tick_safe allow)) b
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {i : Fin S.steps}
+variable {g w n t : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+variable {sel : X.ShrinkSelection B.shrink} {v : Site X}
+private noncomputable local instance stageBase : DecidableEq X.Base := Classical.decEq _
+variable (site : CanonicalSite B i X sel v w n t) (ord : B.Entry → Fin t)
+variable (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "J" => jobs B i X sel site.workspace site.positions site.blocks site.cur site.bounds
+ n site.rowEnd site.older site.later v old parent
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "L" => BlockProgram.layout B site.workspace.val site.positions site.blocks
+local notation "here" => Nat.cast (R := Word w) (levelStart L site.cur)
+
+local notation "F" => matrixFamily B ord i
+local notation "G" => gatherFamily B ord i
+
+attribute [local irreducible] Compression.ShrinkEnergy.chosenLayout MapWitness.rowEquiv
+ ShrinkMapImage.Registers.rowOrdinalWord
+
+set_option maxHeartbeats 1400000 in
+-- Instantiate the physical row function before the kernel sees the proof of workspace capacity.
+/-- Every event returned by the full actual resident list obeys the terminal
+worker read domain. All changes made during this scan are private. -/
+theorem scan_footprint (H : Word w) (room : H.val + 31 < 2 ^ w)
+ (levelEq : site.level = here) (area : site.source.InLevel L site.cur)
+ (before : levelStart L (site.cur + 1) ≤ H.val)
+ (sources : ∀ q, RowSources B i X sel site.workspace site.positions site.blocks site.cur
+ site.bounds n site.rowEnd site.older site.later v old parent site.mem H q)
+ (node : Word w) (saved : Scratch w n) {es : List (Event w)} {updated : Scratch w n}
+ (returned : scan node (canonicalBank site ord parent old hidden) saved = some (es, updated)) :
+ Reads (TerminalLink.workerCell H) es ∧ Writes (fun _ ↦ False) es := by
+ let ps (q : X.packingData.ResidentMap side v) := pub site.level ((J q).node : Word w) regions n
+ have scanBank
+ (W : ∀ q, MapHandlerOperand.Workspace (w := w) (F) demandMass_pos
+ (jobInput B i X sel v hidden (J) q))
+ (accept : scan node (actions B ord i X sel v hidden (J) site.mem site.level site.term
+ site.source site.width ps W) saved = some (es, updated)) :
+ safeEvents (TerminalLink.workerCell H) es := by
+ refine scan_safe (TerminalLink.workerCell H) node _ saved ?_ accept
+ intro act member prior trace next hit
+ apply MapWitness.actionFootprint B ord i X sel v hidden (J) site.mem site.level site.term
+ site.source site.width ps W (TerminalLink.workerCell H) _ _ _ act member node prior
+ trace next hit
+ · intro j
+ exact (route_worker B i site.source v j H area before room).1
+ · intro j
+ let q := rowEquiv X side v j
+ have reads := (sources q).gather_reads room
+ have nodeAddr := node_eq B i X sel site.workspace site.positions site.blocks site.cur
+ site.bounds n site.rowEnd site.older site.later v old parent q
+ have hst := row_ordinal (g := g) (w := w) (B := B) (i := i) (X := X)
+ (sel := sel) (v := v) j
+ rw [← levelEq, ← nodeAddr, ← hst] at reads
+ exact reads
+ · intro j
+ let q := rowEquiv X side v j
+ let I := jobInput B i X sel v hidden (J) q
+ have reads := (sources q).success_reads ord I site.width room
+ have nodeAddr := node_eq B i X sel site.workspace site.positions site.blocks site.cur
+ site.bounds n site.rowEnd site.older site.later v old parent q
+ have hst := row_ordinal (g := g) (w := w) (B := B) (i := i) (X := X)
+ (sel := sel) (v := v) j
+ rw [← levelEq, ← nodeAddr, ← hst] at reads
+ exact reads
+ unfold canonicalBank at returned
+ exact scanBank _ returned
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteHiddenFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteHiddenFootprint.lean
new file mode 100644
index 0000000000..ee4b9a86b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteHiddenFootprint.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.PairShrinkCanonicalSite
+import OAI.Computability.VPVNP.PairShrinkHiddenResidentFootprint
+import OAI.Computability.VPVNP.PairShrinkNodeStageCost
+import OAI.Computability.VPVNP.PairShrinkRoleHiddenTyped
+import OAI.Computability.VPVNP.PairShrinkRolePackedHidden
+import OAI.Computability.VPVNP.PairShrinkRolePhysicalHidden
+
+/-!
+# Hidden-stage reads of a packed shrinking site
+
+The old-level header, the selected owner's resident directory, and the
+selected term rows all precede the terminal header. On any successful
+hidden read, the decoded fields are a typed assignment at that same owner.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole.CanonicalSite
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.ShrinkMotif NetworkKernel
+open CompressorRecords DescriptorSpace SourceTransport ShrinkBlockInputs ShrinkHistoryRows
+open ShrinkSlots ShrinkHiddenGuess ShrinkVertexImage
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {i : Fin S.steps} {g w n t : ℕ} {X : State (a i) (packingLaneBits (a i) g)}
+ {sel : SelectedScore.Selection B X} {v : MapResidentRows.Site X}
+ (site : CanonicalSite B i X sel v w n t) (H : Word w)
+
+local notation "D" => BlockProgram.layout B site.workspace.val site.positions site.blocks
+local notation "head" => levelStart D site.cur
+local notation "tab" => (fun j : Fin 6 => tableBase D site.cur j)
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "role" => SelectedArena.roleBase X term (10 : Word w)
+local notation "bank" => ShrinkOutput.splitBank (b := b i) X B.shrink sel term 10 role (tab 2)
+local notation "R" => TerminalLayout.privateRegions (slotDegree S) n site.rowEnd
+ (Fintype.card B.Entry)
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "rows" => ShrinkHiddenSlots.rows X side widths v
+
+/-- The five probes of the physical hidden setup lie in the old-level header. -/
+theorem hiddenSetup_reads (terminalFit : H.val + 31 < 2 ^ w)
+ (beforeHeader : endAddress D ≤ H.val) (level : site.level = (head : Word w))
+ (node : Word w) (saved : DFS.Scratch w n) :
+ Reads (TerminalLink.workerCell H) ((physicalHiddenSetup B.shrink.selectorBits (hiddenStride i)
+ site.level.val site.mem).trace node saved) := by
+ have next := (levelStart_mono D site.bounds.nextLive.le).trans beforeHeader
+ have headerEnd : head + 66 ≤ H.val := by
+ apply le_trans _ next
+ change head + levelHeaderWords D ≤ levelStart D (site.cur + 1)
+ simp only [levelStart, Nat.succ_mul, levelWords]
+ omega
+ have raw : site.level.val = head := by
+ rw [level, Fin.val_natCast, Nat.mod_eq_of_lt (by have := H.isLt; omega)]
+ rw [raw]
+ change Reads _ (List.replicate (VertexLevel.hiddenCount + 1) .tick ++
+ Header.canonicalTrace B.shrink.selectorBits (hiddenStride i) (head : Word w) site.mem)
+ refine TerminalFootprint.reads_append (TerminalFootprint.reads_ticks _ _) ?_
+ let s := B.shrink.selectorBits
+ let d := hiddenStride i
+ let c : Config w 1 (Table.R s d) := ⟨0, 0, fun _ => (head : Word w), fun _ => 0⟩
+ change Reads _ (Header.canonicalTrace s d (head : Word w) site.mem)
+ rw [← Header.trace_canonical s d (Table.segmentInputs s d) (Table.vm s d) c site.mem
+ (head : Word w) rfl]
+ refine Header.trace_reads (TerminalLink.workerCell H) s d (Table.segmentInputs s d)
+ (Table.vm s d) c site.mem head rfl (by have := H.isLt; omega) ?_
+ intro j hj
+ simp only [List.mem_cons, List.not_mem_nil, or_false] at hj
+ exact TerminalFootprint.below H terminalFit (by omega)
+
+set_option maxHeartbeats 1600000 in
+-- The field directory and each guessed assignment are indexed by the selected owner.
+/-- Every accepted hidden-field tape reads the resident count, dense IDs and
+term cells of this packed site below the terminal header. -/
+theorem hiddenReader_reads (terminalFit : H.val + 31 < 2 ^ w) (beforeHeader : endAddress D ≤ H.val)
+ (payload : CompiledResident.ShrinkPayload B site.workspace site.positions site.blocks n
+ site.cur i X sel site.mem)
+ (args : site.hiddenArgs = PackedHidden.arguments B i X sel site.workspace site.positions
+ site.blocks site.cur n R v)
+ {node : Word w} {saved : DFS.Scratch w n} {bs tail : List Bool}
+ {out : Outcome w n (List Row)}
+ (hit : hiddenReader site.hiddenArgs site.mem (rows site.seed) node saved bs =
+ some (out, tail)) :
+ Reads (TerminalLink.workerCell H) out.trace := by
+ obtain ⟨h, shape, _⟩ := (hiddenReader_typed X side widths v site.hiddenArgs site.mem site.seed
+ hit).exists
+ rw [(ShrinkNodeCost.hidden_trace _ _ _ _ _ _ _ _ hit).1, shape, args]
+ have next := (levelStart_mono D site.bounds.nextLive.le).trans beforeHeader
+ have resident := site.bounds.residentEnd.trans next
+ have stepWord : (10 : Word w).val = 10 :=
+ Nat.mod_eq_of_lt (show 10 < 2 ^ w by omega)
+ have room := site.bounds.packedRoom
+ have slots := site.bounds.slotAfter
+ rw [stepWord] at room slots
+ have allocation := ShrinkOutput.fits (b := b i) X B.shrink sel term 10 role (tab 2)
+ (S.shrink i) (by decide) room
+ have lastTable : tab 3 ≤ H.val :=
+ (Nat.le_add_right ..).trans ((tableEnd_le_nextLevel D site.cur (3 : Fin 6)).trans next)
+ have termBound : (bank).widthBase ≤ H.val :=
+ (ShrinkOutput.width_le_slots (b := b i) X term 10 role (tab 2)).trans
+ (slots.trans lastTable)
+ apply TerminalFootprint.reads_mono _
+ (fun _ before => TerminalFootprint.below H terminalFit before)
+ exact ShrinkHiddenRows.reads_below X bank site.mem (tab 5) H.val allocation
+ (resident.trans_lt H.isLt) resident termBound (payload.sources.residents false) widths v h
+ (ShrinkCallABI.hiddenBase R n) (n * n)
+
+end PairSimulation.ShrinkRole.CanonicalSite
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteHistory.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteHistory.lean
new file mode 100644
index 0000000000..822dd4a781
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteHistory.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.PairTerminalSiteDirectories
+
+/-!
+# Selected payloads and DFS layer bases in a physical site memory
+
+The final prefix preserves the selected payloads in the reference memory.
+The vertex packet preserves the directories and their operands as the
+site loop advances, including the layer base of the terminal state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TraversalControllerInputs LiveProgram.PairStages
+open LiveProgram.PairStages.Group.Auxiliary
+open scoped Fin.CommRing
+
+variable {K A : Type*} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f} {n T : ℕ}
+variable {hT : T * S.laneBits ≤ n} {X : State (S.degreeExponent 0) n}
+variable {z : (B.execute f hf T hT X).Choices} {G : Group} {positions : ℕ}
+variable {baseBits laneBits : ℕ}
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "last" => List.length (List.dropLast (selectedLayers B f hf T hT X z))
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+set_option quotPrecheck false in
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val positions T
+
+private theorem selected_live : (vs).length < (D).levels := by
+ rw [← TerminalBootstrap.selected_last_index, TerminalBootstrap.selected_prior_length,
+ BlockProgram.actual_level_count, Nat.mul_comm T]
+ omega
+
+/-- All producing snapshots remain available in the actual physical memory
+at this ordinal of the linked vertex scan. -/
+theorem VertexEntry.packedSitePayload {cap width ord : ℕ} {table : Fin (D).shape.tables}
+ {roles : List TaggedLayer} {calendar reference phy : Memory G.w}
+ {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z D table baseBits laneBits (terminalOperands G)
+ calendar reference bits)
+ (packed : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord phy)
+ {data : SelectedPayloadHistory.Data (w := G.w) B f hf}
+ (past : SelectedPayloadHistory.Past B f hf D data (vs) calendar) :
+ SelectedPayloadHistory.Past B f hf D data (vs) phy := by
+ have live : (vs).length < (D).levels := selected_live
+ have idx := TerminalBootstrap.selected_last_index B f hf T hT X z
+ have frozen := entry.payload B f hf T hT X z (idx ▸ live) past
+ exact (packed.site_operands frame entry live (by change 28 ≤ 54; decide) frozen).2
+
+/-- Cell 14 of each live level contains that layer's actual DFS row prefix
+on entry to the physical site. The last state is included. -/
+theorem VertexEntry.packedSiteLayer {cap width ord : ℕ} {table : Fin (D).shape.tables}
+ {roles : List TaggedLayer} {calendar reference phy : Memory G.w}
+ {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z D table baseBits laneBits (terminalOperands G)
+ calendar reference bits)
+ (packed : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord phy)
+ (j : ℕ) (hj : j ≤ (vs).length) :
+ phy (levelStart D j + 14) = (layerBase B.recordLimit (endAddress D) tags j : Word G.w) := by
+ obtain ⟨low, high⟩ := packed.traversal_frames frame
+ obtain ⟨ds, stored⟩ := entry.site_directories selected_live
+ (by change 28 ≤ 54; decide) low high
+ have row := stored.currentBase j (by simpa only [levelFibers, List.length_ofFn] using hj)
+ rw [levelFibers_tags (vs) ds] at row
+ simpa only [levelStart, Nat.zero_mul, Nat.add_zero, TraversalRoles.selected] using row
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteInitialPackets.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteInitialPackets.lean
new file mode 100644
index 0000000000..37326665b9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteInitialPackets.lean
@@ -0,0 +1,164 @@
+import OAI.Computability.VPVNP.PairShrinkFirstMapMemory
+import OAI.Computability.VPVNP.PairShrinkPackedPackets
+import OAI.Computability.VPVNP.PairShrinkSiteBank
+import OAI.Computability.VPVNP.PairShrinkRoleChildTyped
+
+/-!
+# Resident operands after the shrinking site's two field scans
+
+The ordered children and once-guessed absorbed fields produce the entry
+memory of every map at the site. The old row pointers and the popped
+parent pointer lie in different layers. All their argument words precede
+the histogram, so the two scans preserve the parent packet while storing
+the children's independent halves and the hidden bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords CompressorRecords.ShrinkBlockInputs CompressorRecords.ShrinkSlots
+open NodeArguments NodeArguments.ChildScan DFS LocalHistory
+open scoped Fin.CommRing
+
+variable {K : Type} {R : Type*} [_root_.Field K] [CommRing R] {S : BlockSchedule K}
+variable (B : S.Templates)
+variable (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g w : ℕ}
+variable (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+local notation "side" => selectedLayout X B.shrink sel
+local notation "widths" => ShrinkPreparedCall.width B.shrink X sel
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+private noncomputable abbrev siteTerm := (B.shrinkPassAt f hf i rfl X).step.term sel
+private noncomputable abbrev siteParser := (shrinkPassReaders B f hf i rfl X).termParsers sel
+local notation "reader" => siteParser B f hf i X sel
+variable (workspace : Word w) (positions blocks cur : ℕ)
+variable (sp : ShrinkResidentSources.Bounds B i X workspace positions blocks cur)
+variable (n rowEnd older later limit : ℕ)
+variable (v : (X.Base × BitWord (packingTagBits (2 ^ a i))) × BitWord g)
+variable (old : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+variable (hidden : Placed (X.packingData.shrinkInternalOwner (selectedLayout X B.shrink sel))
+ (internalLabel (ShrinkPreparedCall.width B.shrink X sel) (selectedLayout X B.shrink sel)) v)
+variable (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v)
+local notation "J" => jobs B i X sel workspace positions blocks cur sp n rowEnd older later
+ v old parent q
+local notation "regions" => TerminalLayout.privateRegions (slotDegree S) n rowEnd
+ (Fintype.card B.Entry)
+local notation "parentNode" => later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal Y v
+local notation "parentPacket" => Packet.mk parentNode (packed Y v parent)
+local notation "hiddenRows" => ShrinkHiddenSlots.rows X side widths v hidden
+local notation "upper" => ShrinkCallABI.hiddenBase regions n
+local notation "keys" => ShrinkHistoryRows.hiddenOrder X
+local notation "ptr" => childNode X older B.recordLimit
+
+private theorem child_injective : Function.Injective (childNode X older B.recordLimit) := by
+ intro u u' eqn
+ apply (siteOrder X).entries.symm.injective
+ apply Fin.ext
+ change older + (B.recordLimit + 2) * ((siteOrder X).entries.symm u).val =
+ older + (B.recordLimit + 2) * ((siteOrder X).entries.symm u').val at eqn
+ exact Nat.eq_of_mul_eq_mul_left (by omega : 0 < B.recordLimit + 2) (Nat.add_left_cancel eqn)
+
+private theorem packed_move {d l : ℕ} (Z : State d l) {u u' : Z.network.Site} (e : u = u')
+ (h : Z.network.Half u) : packed Z u' (e ▸ h) = packed Z u h := by
+ cases e
+ rfl
+
+set_option maxHeartbeats 1000000 in
+-- The parent packet transports the half through the resident equality of sites.
+private theorem parent_eq :
+ Packet.mk (J).node (packed Y _ (J).parent) = parentPacket := by
+ exact congrArg₂ Packet.mk
+ (node_eq B i X sel workspace positions blocks cur sp n rowEnd older later v old parent q)
+ (packed_move Y q.2.symm parent)
+
+set_option maxHeartbeats 2400000 in
+-- The packet readbacks identify the dependent old and successor halves of the selected term.
+/-- In the physical store of the two parsed lists, every operand and the popped parent agree
+with the canonical resident job. The argument bounds hold through the end of each node slot. -/
+theorem initialPackets (priv : Word w → Word w) (xs : List (Child X))
+ (es : List ShrinkHiddenGuess.Row)
+ (encodedOld : children (t := siteTerm B f hf i X sel) X v ((reader).order.children v) old = xs)
+ (encodedHidden : hiddenRows = es)
+ (space : ShrinkCanonicalJob.PacketSpace B i X sel q.1.1 q.1.2 J n limit)
+ (oldNodes : ∀ u, ptr u < rowEnd) (parentNodeFit : parentNode < rowEnd)
+ (earlier : ∀ u, ptr u < parentNode) (wire : X.maxWireWidth ≤ n)
+ (present : (parentPacket).Stored (regions).arguments (scratch n priv))
+ (size : ∀ m t, widths m (!side, t) ≤ n ^ 2)
+ (room : upper + (keys).length * n ^ 2 ≤ 2 ^ w) :
+ let packets := xs.map (Child.packet X older B.recordLimit)
+ let after := ShrinkHiddenGuess.storeRows upper (n ^ 2) es
+ (storePackets (regions).arguments packets priv)
+ (J).Packets n after ∧ (J).ChildWords after n ∧
+ ShrinkCallSupplyCells.Absorbed X side widths q.1.1 q.1.2 (J).scratch (q.2.symm ▸ hidden)
+ after ∧
+ (∀ u, (J).arena.base ((J).nodes u) + (J).arena.stride ≤ (J).scratch.hist) ∧
+ (J).arena.base (J).node + (J).arena.stride ≤ (J).scratch.hist := by
+ rw [← encodedHidden]
+ intro packets after
+ have nodes (u) : ptr u = (J).nodes u :=
+ ShrinkOldHalves.Physical.childNode_eq X older B.recordLimit u
+ have node : (J).node = parentNode :=
+ node_eq B i X sel workspace positions blocks cur sp n rowEnd older later v old parent q
+ have kidsLow (u) : (J).arena.base ((J).nodes u) + (J).arena.stride ≤ (J).scratch.hist :=
+ (regions).node_before (nodes u ▸ oldNodes u)
+ have parentLow : (J).arena.base (J).node + (J).arena.stride ≤ (J).scratch.hist :=
+ (regions).node_before (node ▸ parentNodeFit)
+ have hist : (J).scratch.hist ≤ upper := (Nat.le_add_right ..).trans
+ (ShrinkCallCapacity.histogram_before regions (Fintype.card LeafStartup.ScalarPort) n)
+ have halves (u z) : (reader).halfBits u z = packed X u z := (packed_eq_encode X u z).symm
+ have names : ptr = (J).nodes := funext nodes
+ have packetEq : packets = (reader).childPackets (J).nodes v old := by
+ change xs.map (Child.packet X older B.recordLimit) = _
+ rw [← encodedOld, ← names]
+ simp only [children, List.map_ofFn, Function.comp_def, TermParsers.childPackets, Child.packet,
+ Child.payload_ofHalf, halves]
+ rfl
+ have nd : (((reader).childPackets (J).nodes v old).map Packet.node).Nodup := by
+ rw [TermParsers.childPackets_nodes (reader) (J).nodes v old, ← names]
+ exact List.nodup_ofFn_ofInjective ((child_injective B i X older).comp
+ (Subtype.val_injective.comp ((reader).order.children v).entries.injective))
+ have degree : 2 ^ a i ≤ slotDegree S :=
+ (Finset.le_sup (f := fun j : Fin (S.steps + 1) ↦ 2 ^ S.degreeExponent j)
+ (Finset.mem_univ i.castSucc)).trans (le_max_right ..)
+ have hiddenFit : upper ≤ 2 ^ w := (Nat.le_add_right ..).trans room
+ have fit : ∀ p ∈ packets, p.Fits (J).arena w n := by
+ intro p member
+ obtain ⟨x, _, rfl⟩ := List.mem_map.mp member
+ have length : (x.payload X).length ≤ (J).arena.stride := by
+ rw [Child.payload_eq_packed]
+ exact (packed_length_le X x.site (x.half X)).trans
+ ((Nat.mul_le_mul (Nat.mul_le_mul_left 2 degree) wire).trans (Nat.le_succ _))
+ exact ⟨Nat.le_add_right .., length, (Nat.add_le_add_left length _).trans
+ (((regions).node_before (oldNodes x.site)).trans (hist.trans hiddenFit))⟩
+ let childMem := storePackets (regions).arguments packets priv
+ have written : scratch n childMem = writePackets (J).arena packets (scratch n priv) :=
+ scratch_storePackets (J).arena packets priv
+ have child := ShrinkPartyNative.Job.childWords_of_packets B f hf i X sel v old q J (reader)
+ rfl halves (scratch n priv) childMem (packetEq ▸ fit) nd (packetEq ▸ written)
+ have pe := parent_eq B i X sel workspace positions blocks cur sp n rowEnd older later
+ v old parent q
+ have distinct : ∀ p ∈ packets, p.node ≠ (J).node := by
+ intro p member
+ obtain ⟨x, _, rfl⟩ := List.mem_map.mp member
+ exact node ▸ (earlier x.site).ne
+ have low : (J).arena.base (J).node + (packed Y _ (J).parent).length ≤ upper :=
+ (Nat.add_le_add_left space.parentFit.2.1 _).trans (parentLow.trans hist)
+ have field := (J).firstMapFields v hidden q childMem child
+ (fun u ↦ (kidsLow u).trans hist) size room
+ have parentKept := (J).parentStored_after_fields v hidden q childMem
+ (Packet.mk (J).node (packed Y _ (J).parent)) (scratch n priv) packets fit distinct written
+ space.parentFit (pe ▸ present) low size room
+ exact ⟨space.packets _ field.1 parentKept, field.1, field.2, kidsLow, parentLow⟩
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteLocatorFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteLocatorFootprint.lean
new file mode 100644
index 0000000000..07f1002179
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteLocatorFootprint.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.PairShrinkPhysicalSiteBank
+import OAI.Computability.VPVNP.PairShrinkRoleSelectedChildren
+import OAI.Computability.VPVNP.PairTerminalSiteDirectories
+import OAI.Computability.VPVNP.PairVertexLevelReads
+import OAI.Computability.VPVNP.PairRefreshVertexInputWrites
+
+/-! # Locator reads at a physical shrinking site -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression CompressorRecords DescriptorSpace LocalHistory
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TraversalRows TraversalRoles
+open TraversalControllerInputs
+
+private theorem childSetup_footprint {w endAddr H first pitch offset cap base : ℕ}
+ {pub : Fin 11 → Word w} {m : Memory w} {leaf : TaggedLayer} {ls : List (Fiber w)}
+ (resident : Resident pub m H first pitch offset cap base leaf ls)
+ (beforeH : ∀ j ≤ ls.length, first + j * pitch + 28 ≤ H)
+ (level : Fin ls.length) (steps stage a : ℕ) (node : Word w) (saved : Scratch w endAddr) :
+ let es := (selectedChildSetup pub m ls.length level.val steps stage a).trace node saved
+ SourceTransport.Reads (TerminalLink.workerCell (TerminalLink.header pub)) es ∧
+ SourceTransport.Writes (fun _ => False) es := by
+ dsimp only
+ have bound : level.val + 1 + (ls.length - (level.val + 1)) ≤ ls.length := by
+ have := level.isLt
+ omega
+ have reads := VertexLevel.trace_worker_reads resident beforeH _ _ bound
+ have writes := VertexLevel.trace_noWrites pub m (level.val + 1) (ls.length - (level.val + 1))
+ constructor <;> intro addr value member <;>
+ simp only [selectedChildSetup, Setup.seq, Setup.ticks, locatorSetup, List.mem_append,
+ List.mem_replicate, reduceCtorEq, and_false, or_false] at member
+ · exact reads addr value member
+ · exact writes addr value member
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) {G : Group} {n limit : ℕ}
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence
+set_option quotPrecheck false
+local notation "pub" => terminalOperands G
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val X.positions T
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "rowBase" => endAddress D
+local notation "rowEnd" => rowBase + words B.recordLimit (selectedLayers B f hf T hT X z)
+local notation "labelCount" => Fintype.card B.Entry
+
+local notation "sites" => ShrinkRoleDirectory.ShrinkSite passes
+local notation "before" j => layerBase B.recordLimit rowBase tags j
+
+/-- The selected child setup at every packed shrinking site reads only worker cells
+and makes no external writes, for any incoming node and scratch state. -/
+theorem physicalSiteBank_locator_footprint
+ {table : Fin (D).shape.tables} {baseBits laneBits ord : ℕ}
+ {calendar reference phy : Memory G.w} {bits : Fin (Y).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf D
+ (CompiledResident.payload B f hf (pub 2) X.positions T n) passes calendar)
+ (entry : TerminalProgram.VertexEntry B f hf T hT X z D table baseBits laneBits pub
+ calendar reference bits)
+ (packed : VertexPacked G D B.recordLimit tags (Y).totalWidth)
+ (frame : LinkedVertexMemory G reference ord phy)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+ (fits : ∀ x : sites, ∀ m, canonicalFits B x.occurrence.i x.occurrence.state
+ x.occurrence.selection (w := G.w) labelCount n rowEnd (before x.val.1.val) limit m)
+ (x : sites) (node : Word G.w) (saved : Scratch G.w n) :
+ let site := physicalSiteBank B f hf hT X z history entry packed frame width fits x
+ let es := (selectedChildSetup site.publicData site.mem site.levels site.passIndex
+ S.steps x.occurrence.i.val (ShrinkBlockInputs.a x.occurrence.i)).trace node saved
+ SourceTransport.Reads (TerminalLink.workerCell (vertexHeader G)) es ∧
+ SourceTransport.Writes (fun _ => False) es := by
+ have live : (passes).length < (D).levels :=
+ (executeLevels_length B f hf T hT X z).trans_lt (by rw [BlockProgram.actual_level_count]; omega)
+ have wide : 28 ≤ (D).shape.scalarFields := by change 28 ≤ 54; decide
+ obtain ⟨low, high⟩ := packed.traversal_frames frame
+ obtain ⟨ds, resident⟩ := entry.site_directories live wide low high
+ have len : (levelFibers passes ds).length = (passes).length := by
+ simp only [levelFibers, List.length_ofFn]
+ have beforeH (j : ℕ) (hj : j ≤ (levelFibers passes ds).length) :
+ levelStart D 0 + j * levelWords D + 28 ≤ (vertexHeader G).val :=
+ (TraversalResidentHandoff.headers_before D live wide j (len ▸ hj)).trans
+ ((Nat.le_add_right _ _).trans ((Nat.le_add_right _ _).trans packed.arena))
+ let level : Fin (levelFibers passes ds).length := ⟨x.val.1.val, by rw [len]; exact x.val.1.isLt⟩
+ have scan := childSetup_footprint resident beforeH level S.steps x.occurrence.i.val
+ (ShrinkBlockInputs.a x.occurrence.i) node saved
+ let es := (selectedChildSetup pub phy (passes).length x.val.1.val S.steps x.occurrence.i.val
+ (ShrinkBlockInputs.a x.occurrence.i)).trace node saved
+ change SourceTransport.Reads _ es ∧ SourceTransport.Writes _ es
+ simpa only [es, level, len] using scan
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteOrdinal.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteOrdinal.lean
new file mode 100644
index 0000000000..bafe01ac71
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteOrdinal.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.PairShrinkSelectedOccurrence
+
+/-! # Numerical owner of a selected shrinking output row -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open Compression CompressorRecords LocalHistory TraversalRows TraversalRoles ShrinkRoleDirectory
+
+variable {k : Type} [Field k] {S : BlockSchedule k} (B : S.Templates)
+ {K : Type*} [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (branch : (B.execute f hf T hT X).Choices)
+
+local notation "passes₀" => executeLevels B f hf T hT X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+
+/-- Output-site ordinal in the chronological level's stored site count. -/
+noncomputable def siteId (x : ShrinkSite (passes₀)) : Fin (passes₀)[x.val.1].outputSites :=
+ ⟨((outputOrder (passes₀)[x.val.1]).entries.symm x.val.2).val, by
+ rw [← levelLayer_count B f hf (passes₀)[x.val.1]]
+ exact ((outputOrder (passes₀)[x.val.1]).entries.symm x.val.2).isLt⟩
+
+/-- The native owner and the physical site row have the same natural index. -/
+theorem siteId_val (x : ShrinkSite (passes₀)) :
+ (siteId B f hf T hT X branch x).val = (MapResidentRows.siteIndex x.occurrence.state x.occurrence.site).val :=
+ x.occurrence.ordinal.symm
+
+/-- The chronological site address used by the physical dispatcher and by
+the selected canonical family coincide before conversion to machine words. -/
+theorem rowAddress_siteId (base : ℕ) (x : ShrinkSite (passes₀)) :
+ ShrinkRoleDirectory.address B.recordLimit base (leaf₀) (passes₀) x.val =
+ TraversalRows.address B.recordLimit (layerBase B.recordLimit base (selected B f hf T hT X branch)
+ (x.val.1.val+1)) (siteId B f hf T hT X branch x).val := rfl
+
+end PairSimulation.VertexImage.RoleDomains
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSitePhysical.lean b/lean/OAI/Computability/VPVNP/PairShrinkSitePhysical.lean
new file mode 100644
index 0000000000..3f5fa2108a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSitePhysical.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.PairShrinkSiteSources
+import OAI.Computability.VPVNP.PairShrinkSiteHistory
+import OAI.Computability.VPVNP.CompressorCompiledResident
+import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory
+
+/-!
+# The complete resident bank in the running terminal worker
+
+A single chronological shrinking occurrence supplies all row certificates
+for the vertex. Its old and successor DFS pointers, chosen terms and both
+interval banks remain readable after preceding vertices have flushed their
+private histograms.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots LocalHistory
+open TraversalRoles TraversalRows LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary
+open scoped Fin.CommRing
+
+variable {K : Type} {A : Type*} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+variable (B : S.Templates)
+variable (f : B.Entry → A) (hf : B.IsSolution f) {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes)
+variable (start : State (S.degreeExponent 0) lanes) (branch : (B.execute f hf T hT start).Choices)
+variable {G : Group} (positions n : ℕ)
+local notation "vs" => executeLevels B f hf T hT start branch
+local notation "tags" => selected B f hf T hT start branch
+local notation "rows" => selectedLayers B f hf T hT start branch
+local notation "params" => terminalOperands G
+set_option quotPrecheck false in
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val positions T
+local notation "rowEnd" => (endAddress D + words B.recordLimit rows)
+variable (cur : Fin (executeLevels B f hf T hT start branch).length) (i : Fin S.steps) {g : ℕ}
+variable (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+variable (tape : List Bool)
+local notation "older" => layerBase B.recordLimit (endAddress D) tags cur.val
+local notation "later" => layerBase B.recordLimit (endAddress D) tags (cur.val + 1)
+private noncomputable local instance bankBase : DecidableEq X.Base := Classical.decEq _
+
+set_option maxHeartbeats 2000000 in
+-- The selected pass and its actual directory share both dependent graph indices.
+/-- The producing pass yields all resident sources, for every possible old
+assignment and parent packet, at any later physical vertex call. -/
+theorem rowSources_vertex
+ (occurrence : vs[cur] = shrinkLevel B f hf i X sel tape)
+ {tab : Fin (D).shape.tables} {baseBits laneBits cap width ord : ℕ}
+ {roles : List TraversalRoles.TaggedLayer} {calendar reference phy : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT start) branch).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf D
+ (CompiledResident.payload B f hf (params 2) positions T n) vs calendar)
+ (entry : TerminalProgram.VertexEntry B f hf T hT start branch D tab baseBits laneBits params
+ calendar reference bits)
+ (packed : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord phy) :
+ ∃ bounds : ShrinkResidentSources.Bounds B i X (params 2) positions T cur.val,
+ ∀ v (x : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+ (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+ (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v),
+ RowSources B i X sel (params 2) positions T cur.val bounds n rowEnd older later v x parent
+ phy (vertexHeader G) q := by
+ have live := entry.packedSitePayload packed frame history
+ have input := CompiledResident.read live cur
+ rw [occurrence] at input
+ have data := (CompiledResident.shrink_payload ..).mp input
+ have shrinking : vs[cur].origin.ordinal < S.steps := by rw [occurrence]; exact i.isLt
+ refine ⟨data.bounds, fun v x parent q ↦ ?_⟩
+ apply rowSources B i X sel (params 2) positions T cur.val data.bounds n rowEnd older later
+ v x parent phy (vertexHeader G) q data.words data.sources
+ · exact entry.packedSiteLayer packed frame cur.val cur.isLt.le
+ · exact entry.packedSiteLayer packed frame (cur.val + 1) cur.isLt
+ · exact CompiledResident.shrink_successor_stride live cur shrinking
+ · exact (Nat.le_add_right ..).trans ((Nat.le_add_right ..).trans packed.arena)
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteRouteBounds.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteRouteBounds.lean
new file mode 100644
index 0000000000..05488f06ff
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteRouteBounds.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkMapRowRetention
+import OAI.Computability.VPVNP.PairShrinkRoleMapStartReads
+import OAI.Computability.VPVNP.PairSimulationShrinkRouteReads
+
+/-!
+# Reads of the shrinking site's map header and route
+
+The directory scan loads each occurrence in order. Its selected term address
+and the layout selector stay below the end of the same compressor level.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords DescriptorSpace
+open ShrinkVertexImage ShrinkMapImage.Registers MapResidentRows MapResidentInputs
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (i : Fin S.steps)
+variable {w g : ℕ} {X : State (oldExponent i) (packingLaneBits (oldExponent i) g)}
+variable {sel : X.ShrinkSelection B.shrink} {side : Bool} {mem : Memory w} {level term : Word w}
+variable (R : MapRowSource X sel side mem level term) (v : Site X)
+variable (j : Fin (order X side v).length) {L : Layout} {cur : ℕ} (H : Word w)
+
+private noncomputable local instance siteEq : DecidableEq X.Base := Classical.decEq _
+
+/-- The native guard may increment the map cursor through its exclusive end. -/
+theorem mapRoom :
+ firstMap B i R v + (order X side v).length < 2 ^ w := by
+ rw [length_eq X side v]
+ exact (directory_fit X R.first v R.fit).2
+
+/-- The three external probes on the route before the resident gather. -/
+theorem route_below (bound : R.InLevel L cur) (before : levelStart L (cur + 1) ≤ H.val) :
+ rowCursor X sel side v mem level term R j < H.val ∧
+ term.val + (ordinal X (entry X side v j).1).val * 10 < H.val ∧
+ (level + 38).val < H.val := by
+ let D := ShrinkResidentLayout.layout X R.first
+ have owner : (siteIndex X v).val < D.sites := (siteIndex X v).isLt
+ have cap : j.val < capacity (oldExponent i) := j.isLt.trans_eq (length_eq X side v)
+ have size := ShrinkResidentLayout.size_eq_rows X R.first true
+ have whole := (D.ranges true).2.2.2
+ rw [size] at whole
+ have count := Nat.mul_le_mul_right (capacity (oldExponent i)) owner
+ rw [Nat.succ_mul] at count
+ have head := (ShrinkResidentLayout.frame X R.first true R.fit).2.2.2.2.2.2
+ change ((D.params (oldExponent i) true w 5).val + (siteIndex X v).val * capacity _ + j.val <
+ H.val) ∧ _
+ rw [head]
+ have full : D.rows true + D.sites * capacity (oldExponent i) ≤ H.val :=
+ whole.trans (bound.rowsEnd.trans before)
+ have rank := (ordinal X (entry X side v j).1).isLt
+ have termTop := bound.termEnd.trans before
+ have layoutEnd := bound.headerEnd.trans_le before
+ refine ⟨?_, by omega, ?_⟩
+ · rw [Nat.add_assoc]
+ exact (Nat.add_lt_add_left (Nat.add_lt_add_left cap _) _).trans_le
+ ((Nat.add_le_add_left count _).trans full)
+ · change (level.val + (38 % (2 ^ w))) % (2 ^ w) < _
+ exact (Nat.mod_le ..).trans_lt ((Nat.add_le_add_left (Nat.mod_le ..) _).trans_lt layoutEnd)
+
+/-- The actual route probes stay in the worker's permitted cells. -/
+theorem route_worker (bound : R.InLevel L cur) (before : levelStart L (cur + 1) ≤ H.val)
+ (room : H.val + 31 < 2 ^ w) :
+ SourceTransport.Reads (TerminalLink.workerCell H)
+ (routeEvents X sel side v mem level term R j) ∧
+ SourceTransport.Writes (fun _ ↦ False) (routeEvents X sel side v mem level term R j) := by
+ have safe := route_below B i R v j H bound before
+ exact ⟨routeEvents_reads X sel side v mem level term R j (TerminalLink.workerCell H)
+ (TerminalLink.workerCell_of_lt room safe.1) (TerminalLink.workerCell_of_lt room safe.2.1)
+ (TerminalLink.workerCell_of_lt room safe.2.2),
+ routeEvents_noWrites X sel side v mem level term R j⟩
+
+/-- The five reads which reload the map header at this site use worker-readable cells. -/
+theorem mapStart_worker (bound : R.InLevel L cur) (before : levelStart L (cur + 1) ≤ H.val)
+ (room : H.val + 31 < 2 ^ w) (published : Published mem level
+ ((ShrinkResidentLayout.layout X R.first).params (oldExponent i) true w 3)
+ ((ShrinkResidentLayout.layout X R.first).params (oldExponent i) true w 5) term 10) :
+ SourceTransport.Reads (TerminalLink.workerCell H) (List.replicate 4 .tick ++
+ headerEvents mem level ((siteIndex X v).val : Word w)) :=
+ ShrinkVertexImage.mapStart_worker_reads B i R v H room (bound.headerEnd.le.trans before)
+ (bound.rowsEnd.trans before) published
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteSources.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteSources.lean
new file mode 100644
index 0000000000..78453c7713
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteSources.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.PairShrinkResidentPublication
+import OAI.Computability.VPVNP.PairShrinkCanonicalReadAreas
+
+/-!
+# The native source rows of a selected shrinking site
+
+All resident jobs draw their descriptor, old and surviving intervals and term
+fields from the same producing level. The original and successor DFS row
+pointers identify the old children and the popped parent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSiteBank
+
+open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif NetworkKernel
+open CompressorRecords DescriptorSpace ShrinkBlockInputs ShrinkSlots
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates) (i : Fin S.steps)
+variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X)
+private noncomputable local instance bankBase : DecidableEq X.Base := Classical.decEq _
+variable (workspace : Word w) (positions blocks cur : ℕ)
+variable (bounds : ShrinkResidentSources.Bounds B i X workspace positions blocks cur)
+variable (n rowEnd older later : ℕ)
+variable (v : (X.Base × BitWord (packingTagBits (2 ^ a i))) × BitWord g)
+variable (x : Placed (X.packingData.shrinkPlace (selectedLayout X B.shrink sel) ∘
+ X.packingInputIso.site.symm) X.network.Half v)
+variable (parent : (X.shrinkNext B.shrink (S.shrink i) sel).network.Half v)
+variable (phy : Memory w) (H : Word w)
+local notation "side" => selectedLayout X B.shrink sel
+variable (q : X.packingData.ResidentMap (selectedLayout X B.shrink sel) v)
+local notation "job" => jobs B i X sel workspace positions blocks cur bounds n rowEnd older later
+ v x parent q
+local notation "L" => BlockProgram.layout B workspace.val positions blocks
+local notation "here" => levelStart L cur
+local notation "nextHead" => levelStart L (cur + 1)
+local notation "cut" => tableBase L cur (0 : Fin 6)
+local notation "T" => packedIncidence L w cur (DemandRAM.oldCount X)
+local notation "shape" => levelShape (b := b i) X
+local notation "U" => packedIncidence L w (cur + 1) (actualCount shape)
+local notation "term" => ShrinkInput.termHead (w := w) X cut
+local notation "heads" => ShrinkOutput.heads shape (SelectedArena.roleBase X term 10)
+ (tableBase L cur (3 : Fin 6))
+local notation "absHead" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X cut) w
+local notation "regns" => TerminalLayout.privateRegions (slotDegree S) n rowEnd
+ (Fintype.card B.Entry)
+local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel
+local notation "node" => (later + (B.recordLimit + 2) *
+ PortRefresh.ArgumentAddress.siteOrdinal Y v : ℕ)
+local notation "P" => pub (here : Word w) (node : Word w) regns n
+local notation "O" => ShrinkCallABI.operands (slotDegree S)
+local notation "motif" => Prod.fst (Subtype.val q)
+local notation "st" => Nat.cast (R := Word w) (Fin.val (ShrinkMotifOrder.stateNumber X motif))
+
+/-- Per-row inputs to both native scans and the map argument writer. -/
+structure RowSources : Prop where
+ old : (job).OldPublished O P st phy (here : Word w) T cut
+ next : (job).SupplyPublished O ShrinkCallABI.node P st phy heads absHead U later
+ (B.recordLimit + 2)
+ abArea : (job).ABAreas (here : Word w) T cut H.val
+ supplyArea : (job).SupplyAreas (here : Word w) absHead heads U nextHead H.val phy
+ termEnd : ShrinkInput.termEnd X cut 10 ≤ H.val
+ two : 2 < 2 ^ w
+ termRoom : ShrinkInput.termEnd X cut 10 < 2 ^ w
+ pairs : ShrinkTermInputs.statePairs X (ShrinkInput.demandHead X cut) phy
+ fields : TermRecordScan.Fields B.shrink ShrinkSliceArrays.supplyRoles demandMass_pos
+ (ShrinkPreparedCall.widthsDemand X motif) (sel motif).val
+ (ShrinkTermSelection.rowBase X term 10 motif) phy
+
+set_option maxHeartbeats 2000000 in
+-- Reducing the common job fields identifies the exact parent and both physical interval banks.
+/-- Extract every resident's source contract and the checked read ranges
+from the producing pass's retained data. -/
+theorem rowSources
+ (words : ShrinkResidentHeaders.Words B i X sel workspace positions blocks cur n phy)
+ (data : ShrinkResidentSources.Data B i X (S.shrink i) sel workspace positions blocks cur phy)
+ (oldLayer : phy (here + 14) = (older : Word w))
+ (newLayer : phy (nextHead + 14) = (later : Word w))
+ (newStride : phy (nextHead + 15) = ((B.recordLimit + 2 : ℕ) : Word w))
+ (beforeHeader : endAddress L ≤ H.val) :
+ RowSources B i X sel workspace positions blocks cur bounds n rowEnd older later v x parent
+ phy H q := by
+ have evaluated := ShrinkResidentPublication.published_words B i X (S.shrink i) sel motif q.1.2
+ workspace positions blocks cur bounds n rowEnd older later (job).old (job).parent phy
+ words data oldLayer newLayer newStride
+ change (job).OldPublished O (pub (here : Word w) ((job).node : Word w) regns n) st
+ phy (here : Word w) T cut ∧ (job).SupplyPublished O ShrinkCallABI.node
+ (pub (here : Word w) ((job).node : Word w) regns n) st phy heads absHead U later
+ (B.recordLimit + 2) at evaluated
+ rw [node_eq] at evaluated
+ have safe := ShrinkCanonicalJob.read_areas B i X (S.shrink i) sel motif q.1.2 workspace
+ positions blocks cur bounds (job) rfl rfl H phy beforeHeader words.supply.successor
+ exact ⟨evaluated.1, evaluated.2, safe.1, safe.2.1, safe.2.2,
+ (ShrinkCanonicalJob.geometry B i X (S.shrink i) sel motif workspace
+ positions blocks cur bounds).two, safe.2.2.trans_lt H.isLt, data.pairs, data.terms motif⟩
+
+end PairSimulation.ShrinkSiteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSiteStartFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkSiteStartFootprint.lean
new file mode 100644
index 0000000000..df9ea0ebf1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSiteStartFootprint.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.PairShrinkSiteLocatorFootprint
+import OAI.Computability.VPVNP.PairShrinkRoleChildReads
+import OAI.Computability.VPVNP.PairRefreshVertexInputWrites
+import OAI.Computability.VPVNP.PairTraversalScanDirectory
+
+/-!
+# External probes at the start of a physical shrinking visit
+
+The selected old incidence bank and the packed parent row bound every external
+child probe. The decoder writes its guessed fields in private memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles NodeArguments NodeArguments.ChildScan
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary
+open scoped Fin.CommRing
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence
+set_option quotPrecheck false
+
+private theorem child_noWrites {w n a g : ℕ} {Z : State a g} {A : Arena}
+ {inc : IncidenceDirectory w} {m : Memory w} {older cap : ℕ}
+ {desc : Word w → ChildArguments.Descriptor w Z} {node : Word w} {saved : DFS.Scratch w n}
+ {bs tail : List Bool} {out : Outcome w n (List (Child Z))}
+ (read : ChildArguments.reader A inc m older cap desc node saved bs = some (out, tail)) :
+ SourceTransport.Writes (fun _ => False) out.trace := by
+ obtain ⟨_, result, _⟩ := ChildArguments.reader_some A inc m older cap desc read
+ rw [congrArg Outcome.trace result]
+ exact fun p v h => (List.mem_append.mp h).elim (ChildHeader.events_noWrites m _ _ p v)
+ (ChildScan.events_noWrites Z inc m _ _ p v)
+
+private theorem directory_row_end {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f}
+ (cap base : ℕ) (leaf : TaggedLayer) (passes : List (SelectedLevel B f hf))
+ (x : ShrinkRoleDirectory.Site passes) :
+ ShrinkRoleDirectory.address cap base leaf passes x + 2 + cap ≤
+ base + tagWords cap (leaf :: ShrinkRoleDirectory.outputTags passes) := by
+ let row := ShrinkRoleDirectory.siteRows passes x
+ let output := ShrinkRoleDirectory.outputTags passes
+ let tags := leaf :: output
+ let j : Fin tags.length := ⟨row.1.val + 1, Nat.succ_lt_succ row.1.isLt⟩
+ let id : Fin tags[j].layer.count := row.2
+ exact ChildArguments.selected_row_end base cap tags j id
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices)
+
+private theorem fiber_length (i : Fin S.steps) {g : ℕ}
+ (Z : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g))
+ (sel : Z.ShrinkSelection B.shrink) (tape : List Bool)
+ (member : shrinkLevel B f hf i Z sel tape ∈ executeLevels B f hf T hT X z)
+ (v : MapResidentRows.Site Z) :
+ (oldSites B f hf i Z sel v).length ≤ B.recordLimit := by
+ classical
+ have cap := selected_fiber_capacity B f hf T hT X z (shrinkLevel B f hf i Z sel tape) member v
+ let order := ((shrinkPassReaders B f hf i rfl Z).order sel).children v
+ have count := Fintype.card_congr order.entries
+ rw [Fintype.card_fin] at count
+ simpa only [oldSites, List.length_ofFn] using count.trans_le cap
+
+variable {G : Group} {n limit : ℕ}
+
+local notation "pub" => terminalOperands G
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val X.positions T
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "rowBase" => endAddress D
+local notation "rowEnd" => rowBase + words B.recordLimit (selectedLayers B f hf T hT X z)
+local notation "labelCount" => Fintype.card B.Entry
+local notation "before" j => layerBase B.recordLimit rowBase tags j
+local notation "leaf" => TaggedLayer.mk (leafLayer (siteOrder X)) .cursor
+local notation "sites" => ShrinkRoleDirectory.ShrinkSite passes
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ {baseBits laneBits ord : ℕ} {calendar reference phy : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n)
+ (executeLevels B f hf T hT X z) calendar)
+ (entry : TerminalProgram.VertexEntry B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+ (packed : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ord phy)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+
+local notation "bank" => physicalSiteBank B f hf hT X z history entry packed frame width
+local notation "area" s => TerminalLayout.privateRegions (slotDegree S) n
+ (CanonicalSite.rowEnd s) labelCount
+
+set_option maxHeartbeats 2000000 in
+-- The chronological level and its selected shrink kernel share dependent state indices.
+/-- Every successful child decode at the packed row of this occurrence reads worker cells
+and leaves external memory untouched, for every scratch state and input tape. -/
+theorem physicalSiteBank_child_footprint
+ (fits : ∀ x : sites, ∀ m, canonicalFits B x.occurrence.i x.occurrence.state
+ x.occurrence.selection (w := G.w) labelCount n rowEnd (before x.val.1.val) limit m)
+ (x : sites) {node : Word G.w} {saved : DFS.Scratch G.w n}
+ {bs tail : List Bool} {out : Outcome G.w n (List (Child x.occurrence.state))}
+ (atRow : node.val = ShrinkRoleDirectory.address B.recordLimit rowBase leaf passes x.val)
+ (read : ChildArguments.reader (area (bank fits x)).arguments (bank fits x).incidence
+ (bank fits x).mem (bank fits x).older B.recordLimit (bank fits x).descriptor node saved bs =
+ some (out, tail)) :
+ SourceTransport.Reads (TerminalLink.workerCell (vertexHeader G)) out.trace ∧
+ SourceTransport.Writes (fun _ => False) out.trace := by
+ refine ⟨ChildArguments.worker_reads_of_below _ packed.room ?_, child_noWrites read⟩
+ let o := x.occurrence
+ let j := x.val.1
+ have data := CompiledResident.shrink_vertex (G := G) history entry packed frame j o.selected
+ have count : IncidenceDirectory.slotCount o.state =
+ o.state.positions * 2 ^ ShrinkBlockInputs.a o.i := by
+ rw [State.positions, Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv _),
+ Fintype.card_fin]
+ have inc : (bank fits x).incidence =
+ packedIncidence D G.w j.val (IncidenceDirectory.slotCount o.state) := by
+ rw [count]
+ rfl
+ have rep : (bank fits x).incidence.ActualColumns o.state (bank fits x).mem := by
+ rw [inc]
+ exact data.sources.old.incidence
+ let level : Fin (D).levels := ⟨j.val, Nat.lt_of_succ_lt data.bounds.nextLive⟩
+ have columns := ChildArguments.ColumnsBelow.packed (w := G.w) D level data.bounds.oldCapacity
+ have arena := packed.arena
+ have descriptorEnd := directory_row_end B.recordLimit rowBase leaf passes x.val
+ change ShrinkRoleDirectory.address B.recordLimit rowBase leaf passes x.val + 2 + B.recordLimit ≤
+ rowBase + tagWords B.recordLimit tags at descriptorEnd
+ rw [← atRow] at descriptorEnd
+ have lower : rowBase ≤ (vertexHeader G).val := by omega
+ have old := ChildArguments.old_fields_below (w := G.w) D level (by change 21 ≤ 66; decide)
+ have directory : ((bank fits x).descriptor node).directoryBase =
+ ((levelStart D j.val + 14 : ℕ) : Word G.w) := by
+ change (levelStart D j.val : Word G.w) + 14 = _
+ rw [Nat.cast_add]
+ rfl
+ have member : (passes)[x.val.1] ∈ passes := List.getElem_mem x.val.1.isLt
+ rw [o.selected] at member
+ have len := fiber_length B f hf hT X z o.i o.state o.selection _ member o.site
+ apply ChildArguments.reader_reads_below rep _ _ _ _ read
+ · rw [inc]
+ exact ⟨columns.incoming.trans lower, columns.widths.trans lower⟩
+ · omega
+ · rw [directory]
+ exact old.trans_le lower
+ · change node.val + 2 + (oldSites B f hf o.i o.state o.selection o.site).length ≤ _
+ omega
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSurvivingAddress.lean b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingAddress.lean
new file mode 100644
index 0000000000..34570ee4ba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingAddress.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.PairShrinkOldHalfAddresses
+import OAI.Computability.VPVNP.PairShrinkSurvivingOperands
+
+/-!
+# Private argument addresses of surviving wire endpoints
+
+A surviving row supplies the numerical port at its selected endpoint.
+Division by the output degree recovers the site ordinal and remainder
+recovers the slot. The private packet node is a separate runtime operand.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSurvivingAddress
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData
+open CompressorRecords CompressorRecords.PhaseRecipe CompressorRecords.PortRefresh.ArgumentAddress
+open ShrinkOldHalves.Physical ShrinkSurvivingOperands NodeArguments
+open private unpack word_of_val from OAI.Computability.VPVNP.PairShrinkOldHalfAddresses
+
+/-- Use the oriented port for both the site ordinal and the slot in the resident packet. -/
+def field (degree : ℕ) (H : Header) (node : Expr) (dir : Bool) (port : Expr) : Expr :=
+ let args := { H.input degree port with node := node }
+ PortRefresh.ArgumentAddress.field degree args dir (port.mod (.lit degree))
+
+variable {a b g w pad : ℕ} (X : State a (packingLaneBits a g)) (layout : Bool)
+variable (subdiv : Fin 4 → ℕ) (width : X.packingData.Motif → Fin 4 → ℕ)
+variable {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+variable (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad)
+variable (m : X.packingData.Motif) (t : Fin 4) (dir : Bool) (j : Fin (subdiv t))
+local notation "Y" => X.shrinkOutputState layout subdiv width I
+
+/-- The actual port of the directed subdivision at either endpoint is the
+native slot of the local half assignment, including the translated target lane. -/
+theorem oriented_port_eq :
+ let e := X.packingData.shrinkArcEquiv layout subdiv I.outgoing (.inl ⟨t, m, j⟩)
+ (if dir then I.graph.actualGraph.target e else e) =
+ (site X layout m t dir, slot X layout subdiv width I m t dir j) := by
+ have ends := X.packingData.shrinkArc_endpoints layout subdiv I ⟨t, m, j⟩
+ cases dir with
+ | false => exact Prod.ext ends.1 rfl
+ | true => exact Prod.ext ends.2 rfl
+
+/-- The computed address is exactly the source pointer of the reverse-copy
+loop for this subdivision in the selected resident packet. -/
+theorem field_eq (H : Header) (T : IncidenceDirectory w) (A : Arena)
+ {layer stride : ℕ} {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w}
+ (stored : H.Stored T A layer stride pub state mem) (cols : T.ActualColumns (Y) mem)
+ (capacity : Fintype.card (Y).Base * 2 ^ g * 2 ^ b ≤ 2 ^ w)
+ (degreeFits : 2 ^ b < 2 ^ w) (node port : Expr) (nodeID : ℕ)
+ (nodeEq : node.eval pub state mem = CursorRAM.encode w nodeID)
+ (portEq : port.eval pub state mem = IncidenceDirectory.actualPort (Y)
+ (site X layout m t dir, slot X layout subdiv width I m t dir j)) :
+ (field (2 ^ b) H node dir port).eval pub state mem = CursorRAM.encode w
+ (A.fieldAddress (Y) (site X layout m t dir) nodeID dir
+ (slot X layout subdiv width I m t dir j)) := by
+ let u := site X layout m t dir
+ let k := slot X layout subdiv width I m t dir j
+ let n := siteOrdinal (Y) u
+ let args := { H.input (2 ^ b) port with node := node }
+ have idFit := (IncidenceDirectory.actualOrder (Y) (u, k)).isLt.trans_le capacity
+ have val : (port.eval pub state mem).val = n * 2 ^ b + k.val := by
+ rw [portEq, IncidenceDirectory.actualPort_number]
+ exact (Nat.mod_eq_of_lt idFit).trans (IncidenceDirectory.actualOrder_val (Y) (u, k))
+ have dval : (CursorRAM.encode w (2 ^ b)).val = 2 ^ b := Nat.mod_eq_of_lt degreeFits
+ have split := unpack (port.eval pub state mem) (CursorRAM.encode w (2 ^ b)) n k.val
+ (by rw [dval]; exact val) (by rw [dval]; exact k.isLt)
+ have rep : Represents pub state mem args (Y) u T A nodeID :=
+ ⟨stored.arenaBase, stored.arenaStride, nodeEq, word_of_val split.1,
+ stored.actualIn, stored.width⟩
+ exact eval_field rep cols dir _ k degreeFits (word_of_val split.2)
+
+end PairSimulation.ShrinkSurvivingAddress
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSurvivingBuffer.lean b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingBuffer.lean
new file mode 100644
index 0000000000..00f9faac87
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingBuffer.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairShrinkSurvivingFrames
+import OAI.Computability.VPVNP.PairNodeChildSlots
+
+/-!
+# Reassembling a surviving wire in private memory
+
+Writing the numbered subdivisions at their frame offsets stores the entire
+unsplit word, including when some subdivisions have width zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSurvivingBuffer
+
+open BurstRAM Compression Compression.ShrinkPayload ShrinkSurvivingFrames
+open private append_store from OAI.Computability.VPVNP.PairNodeChildSlots
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem slice_eq (b q : ℕ) (pos : 0 < q) (word : Fin b → Bool) (j : Fin q) :
+ List.ofFn (sliceWords b q pos word j) =
+ ((List.ofFn word).drop (start b q j)).take (splitWidth b q j) := by
+ have h := end_le b q pos j
+ apply List.ext_getElem
+ · simp only [List.length_ofFn, List.length_take, List.length_drop]
+ omega
+ · intro i hi _
+ have bound : i < splitWidth b q j := by simpa using hi
+ simp only [List.getElem_take, List.getElem_drop, List.getElem_ofFn]
+ change word (sliceBits b q pos ⟨j, ⟨i, bound⟩⟩) = word _
+ exact congrArg word (Fin.ext (bit_position b q pos j ⟨i, bound⟩))
+
+/-- The scan deposits every subdivision at its own frame offset. -/
+def fill (b q : ℕ) (pos : 0 < q) (word : Fin b → Bool) (dst : ℕ)
+ (mem : Word w → Word w) : Word w → Word w :=
+ (List.finRange q).foldl (fun m j ↦ PrivateFields.storeBits (dst + start b q j)
+ (List.ofFn (sliceWords b q pos word j)) m) mem
+
+/-- The private memory after the scan equals a single write of the unsplit word. -/
+theorem fill_eq (b q : ℕ) (pos : 0 < q) (word : Fin b → Bool) (dst : ℕ)
+ (mem : Word w → Word w) :
+ fill b q pos word dst mem = PrivateFields.storeBits dst (List.ofFn word) mem := by
+ let ws := List.ofFn (splitWidth b q)
+ let bs := List.ofFn word
+ let put (m : Word w → Word w) (j : Fin q) := PrivateFields.storeBits (dst + start b q j)
+ (List.ofFn (sliceWords b q pos word j)) m
+ have part (n : ℕ) (hn : n ≤ q) :
+ ((List.finRange q).take n).foldl put mem =
+ PrivateFields.storeBits dst (bs.take (ws.take n).sum) mem := by
+ induction n with
+ | zero => simp [PrivateFields.storeBits]
+ | succ n ih =>
+ let j : Fin q := ⟨n, hn⟩
+ have hj : n < (List.finRange q).length := by simp; omega
+ have hw : n < ws.length := by simp [ws]; omega
+ rw [List.take_succ_eq_append_getElem hj, List.foldl_append, ih (by omega),
+ List.sum_take_succ _ _ hw]
+ simp only [List.foldl_cons, List.foldl_nil, List.getElem_finRange, ws, List.getElem_ofFn]
+ change PrivateFields.storeBits (dst + start b q j) (List.ofFn (sliceWords b q pos word j))
+ (PrivateFields.storeBits dst (bs.take (start b q j)) mem) =
+ PrivateFields.storeBits dst (bs.take (start b q j + splitWidth b q j)) mem
+ rw [List.take_add, append_store, slice_eq]
+ have he := end_le b q pos j
+ simp [bs, Nat.min_eq_left (show start b q j ≤ b by omega)]
+ have tot : ws.sum = b := List.sum_ofFn.trans (sum_splitWidth b q pos)
+ simpa [fill, put, List.take_of_length_le (show (List.finRange q).length ≤ q by simp),
+ List.take_of_length_le (show ws.length ≤ q by simp [ws]), tot,
+ List.take_of_length_le (show bs.length ≤ b by simp [bs]), bs] using part q le_rfl
+
+/-- Reading any position of the completed destination buffer returns its bit. -/
+theorem fill_read (b q : ℕ) (pos : 0 < q) (word : Fin b → Bool) (dst : ℕ)
+ (mem : Word w → Word w) (fit : dst + b ≤ 2 ^ w) (i : Fin b) :
+ fill b q pos word dst mem ((dst + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (word i) := by
+ rw [fill_eq]
+ simpa only [List.getElem_ofFn] using PrivateFields.storeBits_read dst (List.ofFn word) mem
+ (by simpa using fit) ⟨i.val, by simp⟩
+
+end PairSimulation.ShrinkSurvivingBuffer
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSurvivingColumn.lean b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingColumn.lean
new file mode 100644
index 0000000000..efca47c6d2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingColumn.lean
@@ -0,0 +1,184 @@
+import OAI.Computability.VPVNP.PairShrinkSurvivingAddress
+import OAI.Computability.VPVNP.PairShrinkSurvivingPointers
+import OAI.Computability.VPVNP.PairResidentFrameColumn
+
+/-!
+# Gathering a surviving endpoint into the six-party map buffer
+
+The linked column computes three pointers per subdivision. The inverse sorted
+table supplies the native field's port. The row table supplies the frame.
+The full column reads one resident packet and writes one complete supply word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSurvivingColumn
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData
+open CompressorRecords CompressorRecords.PhaseRecipe CompressorRecords.ShrinkSliceSweep
+open NodeArguments ShrinkSurvivingPointers ShrinkSurvivingOperands ShrinkSurvivingFrames
+open private descriptor head_fit from OAI.Computability.VPVNP.PairShrinkSurvivingFrames
+open scoped Fin.CommRing
+
+/-- Common runtime parameters of the column. The node and private destination
+are supplied by the enclosing map job. -/
+structure Inputs where
+ /-- Runtime heads and dimensions used to recover the surviving endpoint's port and
+ subdivision frame. -/
+ tables : ShrinkSurvivingPointers.Inputs
+ /-- Argument-arena geometry and incidence columns of the state containing the subdivided
+ endpoint. -/
+ half : ShrinkOldHalves.Physical.Header
+ /-- DFS node expression selecting the private packet that contains this endpoint's
+ subdivision. -/
+ node : Expr
+ /-- Private base expression of the unsplit supply word being reconstructed. -/
+ destination : Expr
+
+/-- Build the reverse-copy setup for one subdivision from its oriented port, resident packet
+field, unsplit destination, and interval frame. -/
+def Inputs.setup (H : Inputs) (degree : ℕ) (subdiv : Fin 4 → ℕ) (t : Fin 4) (dir : Bool)
+ (j : Fin (subdiv t)) : ResidentColumn.Setup :=
+ let endpoint := port degree (H.tables.rect subdiv t j dir)
+ ⟨ShrinkSurvivingAddress.field degree H.half H.node dir endpoint, H.destination,
+ H.tables.frame subdiv t j, true⟩
+
+variable {a b g pad w : ℕ} (X : State a (packingLaneBits a g)) (layout : Bool)
+variable (subdiv : Fin 4 → ℕ) (width : X.packingData.Motif → Fin 4 → ℕ)
+variable {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+variable (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad)
+variable (m : X.packingData.Motif) (t : Fin 4) (dir : Bool)
+local notation "Y" => X.shrinkOutputState layout subdiv width I
+local notation "u" => site X layout m t dir
+local notation "slt" => slot X layout subdiv width I m t dir
+variable (z : (X.shrinkOutputState layout subdiv width I).network.Half (site X layout m t dir))
+variable (A : Arena) (node dst : ℕ)
+variable (bank : ShrinkSliceSweep.Row w)
+
+/-- Logical rows carry the actual native fields, including zero-length subdivisions. -/
+noncomputable def row (j : Fin (subdiv t)) : ResidentColumn.Row :=
+ ⟨A.fieldAddress (Y) (u) node dir (slt j), dst, head bank (subdiv t) j, 0,
+ start (width m t) (subdiv t) j, List.ofFn (fieldBits (Y) (u) z dir (slt j))⟩
+
+local notation "rows" => row X layout subdiv width I m t dir z A node dst bank
+
+theorem row_length (hpos : ∀ t, 0 < subdiv t) (j : Fin (subdiv t)) :
+ (rows j).bits.length = splitWidth (width m t) (subdiv t) j := by
+ have hs := slot_bits X layout subdiv width I hpos m t dir z j
+ exact (congrArg List.length hs).trans List.length_ofFn
+
+/-- The actual stored packet meets every frame's private source precondition. -/
+theorem reads {endAddr : ℕ} (priv : Word w → Word w)
+ (fit : (Packet.mk node (packed (Y) (u) z)).Fits A w endAddr)
+ (stored : (Packet.mk node (packed (Y) (u) z)).Stored A (DFS.scratch endAddr priv))
+ (j : Fin (subdiv t)) : (rows j).reads priv := by
+ intro i
+ let k : Fin ((Y).halfWidth (u) dir (slt j)) :=
+ ⟨i.val, by simpa only [row, List.length_ofFn] using i.isLt⟩
+ simpa only [row, Nat.add_zero, List.getElem_ofFn] using
+ packet_field (Y) (u) z A node priv fit stored dir (slt j) k
+
+/-- Each copy is from the packet below the workspace boundary into the
+unsplit word above it, so earlier writes preserve all later source bits. -/
+theorem fits (hpos : ∀ t, 0 < subdiv t) (pivot : ℕ)
+ (packetEnd : A.base node + (packed (Y) (u) z).length ≤ pivot)
+ (destStart : pivot ≤ dst) (destEnd : dst + width m t < 2 ^ w)
+ (j : Fin (subdiv t)) : (rows j).Fits w pivot := by
+ obtain ⟨pre, post, he, offset⟩ := packed_member (Y) (u) z dir (slt j)
+ have len := row_length X layout subdiv width I m t dir z A node dst bank hpos j
+ constructor
+ · intro _
+ change A.base node + NodeArguments.offset (Y) (u) dir (slt j) + 0 +
+ (List.ofFn (fieldBits (Y) (u) z dir (slt j))).length ≤ pivot
+ rw [← offset]
+ rw [he, List.length_append, List.length_append] at packetEnd
+ omega
+ · exact destStart
+ · intro _
+ change dst + start (width m t) (subdiv t) j + (rows j).bits.length < _
+ rw [len]
+ have := end_le (width m t) (subdiv t) (hpos t) j
+ omega
+
+variable (H : Inputs) {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w}
+variable (hpos : ∀ t, 0 < subdiv t)
+
+include hpos in
+/-- Combine the actual port ordinal, packet directory and final three-word
+interval image into the private worker's complete recorded row. -/
+theorem recorded {n A₀ : ℕ} (T : Allocation w n A₀) (alloc : T.Fits) (idx : Fin n)
+ (sameProfile : T.subdiv = subdiv) (atRow : T.row (idx, t) = bank)
+ (inc : IncidenceDirectory w) (layer stride : ℕ)
+ (half : H.half.Stored inc A layer stride pub state mem)
+ (cols : inc.ActualColumns (Y) mem)
+ (capacity : Fintype.card (Y).Base * 2 ^ g * 2 ^ b ≤ 2 ^ w) (degreeFit : 2 ^ b < 2 ^ w)
+ (nodeAt : H.node.eval pub state mem = CursorRAM.encode w node)
+ (destAt : H.destination.eval pub state mem = (dst : Word w))
+ (dense : H.tables.dense.eval pub state mem = (idx.val : Word w))
+ (interval : H.tables.intervalHead.eval pub state mem = (T.widthEnd : Word w))
+ (image : ShrinkSliceSweep.Image bank (width m t) mem)
+ (j : Fin (subdiv t))
+ (portAt : (port (2 ^ b) (H.tables.rect subdiv t j dir)).eval pub state mem =
+ IncidenceDirectory.actualPort (Y) ((u), slt j)) :
+ (rows j).Recorded (H.setup (2 ^ b) subdiv t dir j) pub state mem := by
+ subst subdiv
+ subst bank
+ let bank := T.row (idx, t)
+ let q := T.subdiv t
+ have count : bank.count.val = q := (T.row_vals alloc (idx, t)).2.2.2.2
+ have room : SliceSchedule.Workspace bank.total bank.dst bank.bank 1 q :=
+ count ▸ T.space alloc (idx, t)
+ have src := ShrinkSurvivingAddress.field_eq X layout T.subdiv width I m t dir j
+ H.half inc A half cols capacity degreeFit H.node _ node nodeAt portAt
+ have len := row_length X layout T.subdiv width I m t dir z A node dst bank hpos j
+ obtain ⟨hlen, hoff⟩ := descriptor image count j
+ refine ⟨src, destAt, frame_eval H.tables T alloc idx t j dense interval,
+ head_fit j room, hlen.trans len.symm, ?_⟩
+ intro hp
+ exact (hoff (len ▸ hp)).symm
+
+/-- The concatenation of these precise native writes is one unsplit word. -/
+theorem writes_operand (priv : Word w → Word w) :
+ ResidentColumn.writes rows (List.finRange (subdiv t)) priv =
+ PrivateFields.storeBits dst (List.ofFn (operand X layout subdiv width I hpos m t dir z))
+ priv :=
+ nativeFill_eq X layout subdiv width I hpos m t dir z dst priv
+
+
+/-- Run the complete linked subdivision column from one resident packet.
+Each iteration computes its pointers in the native register-setup machine. -/
+theorem native {p r k endAddr : ℕ} (M : Machine w p r k)
+ (vm : ∀ j, Fin (RegisterSetup.regCount ((H.setup (2 ^ b) subdiv t dir j).operands)) ↪ Fin r)
+ (inputs : Fin 6 → Fin r) (loc : ResidentColumn.Label (H.setup (2 ^ b) subdiv t dir) → Fin p)
+ (ret : Fin p)
+ (code : ∀ l, M.code (loc l) = ResidentColumn.instruction (H.setup (2 ^ b) subdiv t dir)
+ vm inputs loc ret l)
+ (apart : ∀ i v j, vm i v ≠ inputs j)
+ (recorded : ∀ j, (rows j).Recorded (H.setup (2 ^ b) subdiv t dir j) pub state mem)
+ (cfg : Config w p r)
+ (entry : cfg.pc = ResidentColumn.start (H.setup (2 ^ b) subdiv t dir) loc ret 0)
+ (hp : ∀ j : Fin 5, cfg.reg (inputs j.castSucc) = pub j)
+ (hs : cfg.reg (inputs (Fin.last 5)) = state)
+ (packetFit : (Packet.mk node (packed (Y) (u) z)).Fits A w endAddr)
+ (supplied : (Packet.mk node (packed (Y) (u) z)).Stored A (DFS.scratch endAddr cfg.privateMem))
+ (pivot : ℕ) (below : A.base node + (packed (Y) (u) z).length ≤ pivot)
+ (above : pivot ≤ dst) (room : dst + width m t < 2 ^ w) :
+ ∃ events out, ResidentColumn.Result (H.setup (2 ^ b) subdiv t dir) vm M ret rows
+ (List.finRange (subdiv t)) mem cfg out events ∧
+ out.privateMem = PrivateFields.storeBits dst
+ (List.ofFn (operand X layout subdiv width I hpos m t dir z)) cfg.privateMem := by
+ have fit := fits X layout subdiv width I m t dir z A node dst bank hpos pivot below above room
+ have read := reads X layout subdiv width I m t dir z A node dst bank cfg.privateMem
+ packetFit supplied
+ obtain ⟨events, out, result⟩ := ResidentColumn.native M loc ret code apart rows mem pub state
+ recorded pivot fit cfg entry hp hs read
+ exact ⟨events, out, result, result.memory.trans
+ (writes_operand X layout subdiv width I m t dir z A node dst bank hpos cfg.privateMem)⟩
+
+end PairSimulation.ShrinkSurvivingColumn
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSurvivingFrames.lean b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingFrames.lean
new file mode 100644
index 0000000000..460440403e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingFrames.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.CompressorShrinkSliceSweep
+import OAI.Computability.VPVNP.PairSimulationReverseSlices
+
+/-!
+# Copying one resident surviving interval back into its supply operand
+
+The descriptor bank contains one source field and one target per subdivision.
+The reverse copy reads the subdivision at offset zero and deposits it at the
+sum of the preceding subdivision widths in the unsplit operand.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSurvivingFrames
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.ShrinkPayload
+open CompressorRecords CompressorRecords.SliceSchedule CompressorRecords.ShrinkSliceArrays
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Bit offset of a subdivision in its unsplit word. -/
+def start (b q : ℕ) (j : Fin q) : ℕ := ((List.ofFn (splitWidth b q)).take j.val).sum
+
+theorem bit_position (b q : ℕ) (pos : 0 < q) (j : Fin q) (i : Fin (splitWidth b q j)) :
+ (sliceBits b q pos ⟨j, i⟩).val = start b q j + i.val := by
+ rw [sliceBits_offset]
+ simp [start, ← Fin.ofFn_take_eq_take_ofFn j.isLt.le, List.sum_ofFn, Fin.take]
+
+theorem end_le (b q : ℕ) (pos : 0 < q) (j : Fin q) :
+ start b q j + splitWidth b q j ≤ b := by
+ let ws := List.ofFn (splitWidth b q)
+ have hi : j.val < ws.length := by simp [ws]
+ have full : ws.sum = b := List.sum_ofFn.trans (sum_splitWidth b q pos)
+ have pieces := congrArg List.sum (List.take_append_drop (j.val + 1) ws)
+ rw [List.sum_append, List.sum_take_succ _ _ hi, full] at pieces
+ change (ws.take j.val).sum + splitWidth b q j ≤ b
+ rw [show ws[j.val] = splitWidth b q j from List.getElem_ofFn ..] at pieces
+ omega
+
+/-- Physical location of the first of the frame's three public cells. -/
+def head (row : ShrinkSliceSweep.Row w) (q : ℕ) (j : Fin q) :=
+ frameHead row.bank.val 1 q + 3 * j.val
+
+private theorem descriptor {b q : ℕ} {row : ShrinkSliceSweep.Row w} {mem : Memory w}
+ (image : ShrinkSliceSweep.Image row b mem) (count : row.count.val = q) (j : Fin q) :
+ (mem (head row q j + 2)).val = splitWidth b q j ∧
+ (0 < splitWidth b q j → (mem (head row q j + 1)).val = 0 ∧
+ (mem (head row q j)).val = start b q j) := by
+ obtain ⟨before, staged, stored, same⟩ := image.descriptors
+ rw [count] at stored same
+ have pos := Nat.zero_lt_of_lt j.isLt
+ let h := head row q j
+ have bank (a : ℕ) (ha : a ≤ 2) : mem (h + a) = staged (h + a) := by
+ apply same
+ · dsimp [h, head, frameHead]; omega
+ · simp only [stop, one_mul, h, head]
+ have := j.isLt
+ omega
+ obtain ⟨len, offsets⟩ := surviving_frame b q pos stored j
+ refine ⟨(congrArg Fin.val (bank 2 le_rfl)).trans len, ?_⟩
+ intro hp
+ let zero : Fin (splitWidth b q j) := ⟨0, hp⟩
+ obtain ⟨ht, hs⟩ := offsets zero
+ rw [bit_position] at hs
+ refine ⟨(congrArg Fin.val (bank 1 (by decide))).trans ht, ?_⟩
+ simpa only [Nat.add_zero, zero] using (congrArg Fin.val (bank 0 (by decide))).trans
+ (Nat.add_right_cancel hs)
+
+private theorem head_fit {row : ShrinkSliceSweep.Row w} {q : ℕ} (j : Fin q)
+ (space : Workspace row.total row.dst row.bank 1 q) : head row q j + 2 < 2 ^ w := by
+ apply lt_trans _ space.fits
+ simp only [head, stop, one_mul]
+ have := j.isLt
+ omega
+
+/-- The actual reverse header and private copy loop read this subdivision
+from its native slot and write it at its designated unsplit offset. -/
+theorem execute_piece {M : Machine w p r k} {pc : Fin 11 → Fin p}
+ {reg : Fin 6 ↪ Fin r} {arcPC : Fin 7 → Fin p} {done : Fin p}
+ (linked : ReverseSlices.Linked M pc reg (arcPC 0) done)
+ (copy : PrivateFields.Linked M .copy arcPC (PrivateSlices.copyRegs reg) done)
+ (c : Config w p r) (entry : c.pc = pc 0) (one : c.reg (reg 3) = 1)
+ {row : ShrinkSliceSweep.Row w} {b q : ℕ} (j : Fin q) {mem : Memory w}
+ (image : ShrinkSliceSweep.Image row b mem) (count : row.count.val = q)
+ (space : Workspace row.total row.dst row.bank 1 q)
+ (src dst : ℕ) (frame : c.reg (reg 5) = (head row q j : Word w))
+ (source : c.reg (reg 0) = (src : Word w)) (destination : c.reg (reg 2) = (dst : Word w))
+ (bits : Fin (splitWidth b q j) → Bool)
+ (fit : 0 < splitWidth b q j → src + splitWidth b q j ≤ 2 ^ w ∧
+ dst + start b q j + splitWidth b q j < 2 ^ w)
+ (safe : 0 < splitWidth b q j → dst + start b q j ≤ src ∨
+ src + splitWidth b q j ≤ dst + start b q j)
+ (data : ∀ i, c.privateMem ((src + i.val : ℕ) : Word w) = PrivateFields.bitValue w (bits i)) :
+ ReverseSlices.FrameResult M reg done c mem (head row q j : Word w)
+ (dst + start b q j) (List.ofFn bits) := by
+ let f : Word w := head row q j
+ obtain ⟨len, offsets⟩ := descriptor image count j
+ obtain ⟨lengthWord, offsetWords⟩ := ReverseSlices.oriented_frame_words true mem f
+ (head row q j) (start b q j) 0 _ rfl (head_fit j space) len (fun h ↦ (offsets h).symm)
+ apply ReverseSlices.execute_stored_frame true linked copy c entry one mem f frame
+ src dst 0 (start b q j) source destination (List.ofFn bits)
+ · simpa only [List.length_ofFn] using lengthWord
+ · simpa only [List.length_ofFn, Bool.true_eq, ite_true] using offsetWords
+ · simpa only [List.length_ofFn, Nat.add_zero] using fit
+ · simpa only [List.length_ofFn, Nat.add_zero] using safe
+ · intro i
+ simpa only [Nat.add_zero, List.getElem_ofFn] using data ⟨i.val, by simpa using i.isLt⟩
+
+end PairSimulation.ShrinkSurvivingFrames
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSurvivingOperands.lean b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingOperands.lean
new file mode 100644
index 0000000000..9dfff6b934
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingOperands.lean
@@ -0,0 +1,313 @@
+import OAI.Computability.VPVNP.PairPendingArguments
+import OAI.Computability.VPVNP.PairShrinkSurvivingBuffer
+import OAI.Computability.VPVNP.CompressorShrinkSelectedSlices
+import OAI.Computability.VPVNP.ShrinkStateOutput
+import OAI.Computability.VPVNP.ShrinkSupplyLocal
+
+/-!
+# Surviving supply operands in the shrinking kernel
+
+Each surviving wire is gathered from the numbered half-wires of the output
+state. At the target this uses the incoming slot of the translated actual
+arc. The two endpoints may hold independent half-wire assignments.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSurvivingOperands
+
+open Compression Compression.PackingData Compression.SurvivingSlots Compression.ShrinkPayload
+open LocalHistory NodeArguments
+
+private theorem outgoing_list {a g : ℕ} (X : State a g) (u : X.network.Site)
+ (z : X.network.Half u) (e : {e // u = X.network.src e}) :
+ List.ofFn (fieldBits X u z false ((outgoingOrder X u).entries.symm e)) =
+ List.ofFn (z.1 e.val e.property) := by
+ obtain ⟨j, rfl⟩ := (outgoingOrder X u).entries.surjective e
+ rw [Equiv.symm_apply_apply]
+ rfl
+
+private theorem incoming_list {a g : ℕ} (X : State a g) (u : X.network.Site)
+ (z : X.network.Half u) (e : {e // u = X.network.dst e}) :
+ List.ofFn (fieldBits X u z true ((incomingOrder X u).entries.symm e)) =
+ List.ofFn (z.2 e.val e.property) := by
+ obtain ⟨j, rfl⟩ := (incomingOrder X u).entries.surjective e
+ rw [Equiv.symm_apply_apply]
+ rfl
+
+private theorem ofFn_cast {n m : ℕ} (h : n = m) (f : Fin n → Bool) :
+ List.ofFn f = List.ofFn (cast (congrArg (fun n ↦ Fin n → Bool) h) f) := by
+ subst m
+ rfl
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+/-- Reading a resident packet's specified native slot gives the node's
+actual half-field. The private memory may already contain other packets. -/
+theorem packet_field {a g w endAddr : ℕ} (X : State a g) (u : X.network.Site)
+ (z : X.network.Half u) (arena : Arena) (node : ℕ) (mem : Word w → Word w)
+ (fits : (Packet.mk node (packed X u z)).Fits arena w endAddr)
+ (stored : (Packet.mk node (packed X u z)).Stored arena (DFS.scratch endAddr mem))
+ (dir : Bool) (port : Fin (2 ^ a)) (i : Fin (X.halfWidth u dir port)) :
+ mem ((arena.fieldAddress X u node dir port + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (fieldBits X u z dir port i) := by
+ obtain ⟨pre, post, pieces, addr⟩ := packed_member X u z dir port
+ have len : pre.length + i.val < (packed X u z).length := by rw [pieces]; simp; omega
+ let pos : Fin (packed X u z).length := ⟨pre.length + i.val, len⟩
+ have value := stored pos
+ let abs := arena.base node + pos.val
+ have hfit : abs < 2 ^ w := (Nat.add_lt_add_left pos.isLt _).trans_le fits.2.2
+ have above : endAddr ≤ (abs : Word w).val := by
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt hfit]
+ exact fits.1.trans (Nat.le_add_right _ _)
+ change rawScratch (DFS.scratch endAddr mem) (abs : Word w) = _ at value
+ rw [rawScratch, dite_eq_left above] at value
+ rw [Arena.fieldAddress, ← addr, Nat.add_assoc]
+ refine value.trans ?_
+ change PrivateFields.bitValue w ((packed X u z)[pre.length + i.val]) = _
+ simp [pieces, i.isLt]
+
+variable {a b g pad : ℕ} (X : State a (packingLaneBits a g))
+variable (layout : Bool) (subdiv : Fin 4 → ℕ)
+variable (width : X.packingData.Motif → Fin 4 → ℕ)
+variable {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+variable (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad)
+local notation "Y" => X.shrinkOutputState layout subdiv width I
+variable (hpos : ∀ t, 0 < subdiv t) (m : X.packingData.Motif) (t : Fin 4)
+
+/-- Packed source or target site of the specified supply edge. -/
+noncomputable def site : Bool → (X.Base × BitWord (packingTagBits (2 ^ a))) × BitWord g
+ | false => packedSiteEquiv (X.packingData.survivingRole layout (sourceRole layout t) m)
+ | true => packedSiteEquiv (X.packingData.survivingRole layout (targetRole layout t) m)
+
+/-- The native slot at the chosen end of one actual subdivision. -/
+noncomputable def slot (dir : Bool) (j : Fin (subdiv t)) : Fin (2 ^ b) :=
+ let i : Id X.packingData.Motif subdiv := ⟨t, m, j⟩
+ let e := X.packingData.shrinkArcEquiv layout subdiv I.outgoing (.inl i)
+ let ends := X.packingData.shrinkArc_endpoints layout subdiv I i
+ match dir with
+ | false => (outgoingOrder (Y) (site X layout m t false)).entries.symm ⟨e, ends.1.symm⟩
+ | true => (incomingOrder (Y) (site X layout m t true)).entries.symm ⟨e, ends.2.symm⟩
+
+/-- Outgoing slots retain the genuine arc number, while the incoming
+slot is the second component of the lifted slot permutation's image. -/
+theorem slot_number (dir : Bool) (j : Fin (subdiv t)) :
+ let e := X.packingData.shrinkArcEquiv layout subdiv I.outgoing (.inl ⟨t, m, j⟩)
+ slot X layout subdiv width I m t dir j =
+ if dir then (I.graph.actualGraph.target e).2 else e.2 := by
+ cases dir <;> rfl
+
+/-- Word read by the supply map from an arbitrary half-assignment at this endpoint. -/
+noncomputable def operand : (dir : Bool) → (Y).network.Half (site X layout m t dir) →
+ Fin (width m t) → Bool
+ | false => X.packingData.localSurvivingSource layout subdiv width I hpos m t
+ | true => X.packingData.localSurvivingTarget layout subdiv width I hpos m t
+
+/-- The physical node field is exactly the corresponding interval of the
+local supply operand, at either of its endpoints. -/
+theorem slot_bits (dir : Bool) (z : (Y).network.Half (site X layout m t dir)) (j : Fin (subdiv t)) :
+ List.ofFn (fieldBits (Y) _ z dir (slot X layout subdiv width I m t dir j)) =
+ List.ofFn (sliceWords (width m t) (subdiv t) (hpos t)
+ (operand X layout subdiv width I hpos m t dir z) j) := by
+ let i : Id X.packingData.Motif subdiv := ⟨t, m, j⟩
+ let e := X.packingData.shrinkArcEquiv layout subdiv I.outgoing (.inl i)
+ have he := X.packingData.shrinkArc_endpoints layout subdiv I i
+ have hw := X.packingData.shrinkSlotWidth_genuine layout subdiv width I.outgoing i
+ cases dir with
+ | false =>
+ change List.ofFn (fieldBits (Y) _ z false
+ ((outgoingOrder (Y) _).entries.symm ⟨e, he.1.symm⟩)) = _
+ refine (outgoing_list (Y) (site X layout m t false) z ⟨e, he.1.symm⟩).trans ?_
+ simp only [operand, localSurvivingSource, Equiv.apply_symm_apply]
+ exact ofFn_cast hw (z.1 e he.1.symm)
+ | true =>
+ change List.ofFn (fieldBits (Y) _ z true
+ ((incomingOrder (Y) _).entries.symm ⟨e, he.2.symm⟩)) = _
+ refine (incoming_list (Y) (site X layout m t true) z ⟨e, he.2.symm⟩).trans ?_
+ simp only [operand, localSurvivingTarget, Equiv.apply_symm_apply]
+ exact ofFn_cast hw (z.2 e he.2.symm)
+
+open CompressorRecords CompressorRecords.SliceSchedule ShrinkSurvivingFrames
+open scoped Fin.CommRing
+
+/-- Copy one native output slot into the operand buffer from a supplied
+parent packet, using the physical surviving row in level memory. -/
+theorem execute_slot {w p r k endAddr : ℕ} {M : Machine w p r k} {pc : Fin 11 → Fin p}
+ {reg : Fin 6 ↪ Fin r} {arcPC : Fin 7 → Fin p} {done : Fin p}
+ (linked : ReverseSlices.Linked M pc reg (arcPC 0) done)
+ (copy : PrivateFields.Linked M .copy arcPC (PrivateSlices.copyRegs reg) done)
+ (c : Config w p r) (entry : c.pc = pc 0) (one : c.reg (reg 3) = 1)
+ (dir : Bool) (z : (Y).network.Half (site X layout m t dir)) (j : Fin (subdiv t))
+ (arena : Arena) (node dst : ℕ)
+ (fits : (Packet.mk node (packed (Y) _ z)).Fits arena w endAddr)
+ (stored : (Packet.mk node (packed (Y) _ z)).Stored arena (DFS.scratch endAddr c.privateMem))
+ {row : ShrinkSliceSweep.Row w} {mem : Memory w}
+ (image : ShrinkSliceSweep.Image row (width m t) mem) (count : row.count.val = subdiv t)
+ (space : Workspace row.total row.dst row.bank 1 (subdiv t))
+ (frame : c.reg (reg 5) = (head row (subdiv t) j : Word w))
+ (dest : c.reg (reg 2) = (dst : Word w)) :
+ let src := arena.fieldAddress (Y) (site X layout m t dir) node dir
+ (slot X layout subdiv width I m t dir j)
+ let bits := sliceWords (width m t) (subdiv t) (hpos t)
+ (operand X layout subdiv width I hpos m t dir z) j
+ c.reg (reg 0) = (src : Word w) →
+ dst + width m t < 2 ^ w →
+ (dst + width m t ≤ arena.base node ∨ arena.base node + (packed (Y) _ z).length ≤ dst) →
+ ReverseSlices.FrameResult M reg done c mem (head row (subdiv t) j : Word w)
+ (dst + start (width m t) (subdiv t) j) (List.ofFn bits) := by
+ intro src bits source destFit apart
+ let u := site X layout m t dir
+ let port := slot X layout subdiv width I m t dir j
+ have same : List.ofFn (fieldBits (Y) u z dir port) = List.ofFn bits :=
+ slot_bits X layout subdiv width I hpos m t dir z j
+ have widthEq : (Y).halfWidth u dir port = splitWidth (width m t) (subdiv t) j := by
+ simpa only [List.length_ofFn] using congrArg List.length same
+ obtain ⟨pre, post, packEq, addr⟩ := packed_member (Y) u z dir port
+ have srcEq : src = arena.base node + pre.length := by
+ change arena.base node + offset (Y) u dir port = _
+ rw [addr]
+ have srcBound : src + splitWidth (width m t) (subdiv t) j ≤
+ arena.base node + (packed (Y) u z).length := by
+ rw [packEq, srcEq, ← widthEq]
+ simp only [List.length_append, List.length_ofFn]
+ omega
+ have endBound := ShrinkSurvivingFrames.end_le (width m t) (subdiv t) (hpos t) j
+ apply execute_piece linked copy c entry one j image count space src dst frame source dest bits
+ · intro _
+ exact ⟨srcBound.trans fits.2.2, by omega⟩
+ · intro _
+ change dst + width m t ≤ arena.base node ∨
+ arena.base node + (packed (Y) u z).length ≤ dst at apart
+ rcases apart with left | right
+ · exact Or.inl (le_trans (by omega) (left.trans (by rw [srcEq]; omega)))
+ · exact Or.inr (srcBound.trans (right.trans (Nat.le_add_right _ _)))
+ · intro i
+ let k : Fin ((Y).halfWidth u dir port) := ⟨i.val, widthEq.symm ▸ i.isLt⟩
+ have resident := packet_field (Y) u z arena node c.privateMem fits stored dir port k
+ refine resident.trans (congrArg (PrivateFields.bitValue w) ?_)
+ have e := congrArg (fun xs : List Bool ↦ xs[i.val]?) same
+ simpa [k, i.isLt, show i.val < (Y).halfWidth u dir port from widthEq.symm ▸ i.isLt] using e
+
+/-- Memory updates from visiting each actual output slot at this endpoint. -/
+noncomputable def nativeFill {w : ℕ} (dir : Bool) (z : (Y).network.Half (site X layout m t dir))
+ (dst : ℕ) (mem : Word w → Word w) : Word w → Word w :=
+ (List.finRange (subdiv t)).foldl (fun prev j ↦
+ PrivateFields.storeBits (dst + start (width m t) (subdiv t) j)
+ (List.ofFn (fieldBits (Y) _ z dir (slot X layout subdiv width I m t dir j))) prev) mem
+
+/-- Executing the memory updates from the full row stores exactly the
+surviving supply word, including its selector bits. -/
+theorem nativeFill_eq {w : ℕ} (dir : Bool) (z : (Y).network.Half (site X layout m t dir))
+ (dst : ℕ) (mem : Word w → Word w) :
+ nativeFill X layout subdiv width I m t dir z dst mem =
+ PrivateFields.storeBits dst (List.ofFn (operand X layout subdiv width I hpos m t dir z))
+ mem := by
+ unfold nativeFill
+ simp only [slot_bits X layout subdiv width I hpos m t dir z]
+ exact ShrinkSurvivingBuffer.fill_eq (width m t) (subdiv t) (hpos t) _ dst mem
+
+section Map
+
+open NetworkKernel ShrinkMotif
+open private readSupplyEnd from OAI.Computability.VPVNP.ShrinkSupplyLocal
+open private layoutCases layoutCases_active from OAI.Computability.VPVNP.ShrinkSupplyLocal
+
+variable (allWidths : X.packingData.Motif → Bool × Fin 4 → ℕ)
+local notation "W" => fun m t ↦ allWidths m (layout, t)
+local notation "S" => X.shrinkOutputState layout subdiv (W) I
+
+/-- Vertex of the six-party map which owns this end of the surviving wire. -/
+def party (layout : Bool) (t : Fin 4) : Bool → Fin 6
+ | false => supply.src (layout, t)
+ | true => supply.dst (layout, t)
+
+theorem party_site (dir : Bool) :
+ X.packingData.shrinkPartySite layout m (party layout t dir) = site X layout m t dir := by
+ cases dir <;> simp only [shrinkPartySite, party, role_src_survives, role_dst_survives, site]
+
+/-- Select the incoming or outgoing column of the actual local supply map
+at the active edge. Its opposite layout fields use the internal assignment. -/
+noncomputable def mapColumn (dir : Bool)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel allWidths layout)
+ (X.packingData.shrinkPartySite layout m (party layout t dir)))
+ (z : (S).network.Half (X.packingData.shrinkPartySite layout m (party layout t dir))) :
+ Fin (2 ^ allWidths m (layout, t)) :=
+ match dir with
+ | false =>
+ (X.packingData.shrinkLocalSupplyArg layout subdiv allWidths I hpos m _ h z).1 (layout, t) rfl
+ | true =>
+ (X.packingData.shrinkLocalSupplyArg layout subdiv allWidths I hpos m _ h z).2 (layout, t) rfl
+
+/-- The reconstructed operand is precisely the bit representation of the
+surviving column on independent local half-wires. -/
+theorem mapColumn_bits (dir : Bool)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel allWidths layout)
+ (X.packingData.shrinkPartySite layout m (party layout t dir)))
+ (z : (S).network.Half (X.packingData.shrinkPartySite layout m (party layout t dir))) :
+ RAMSerialization.wordBits _ (mapColumn X layout subdiv I hpos m t allWidths dir h z) =
+ operand X layout subdiv (W) I hpos m t dir
+ ⟨fun e he ↦ z.1 e ((party_site X layout m t dir).trans he),
+ fun e he ↦ z.2 e ((party_site X layout m t dir).trans he)⟩ := by
+ cases dir <;> simp only [mapColumn, shrinkLocalSupplyArg, readSupplyEnd, layoutCases_active,
+ Equiv.apply_symm_apply, operand] <;> rfl
+
+/-- Reading a gathered bit gives that coordinate of the local six-party
+map's actual supply basis index. -/
+theorem nativeFill_mapColumn {w : ℕ} (dir : Bool)
+ (h : Placed (X.packingData.shrinkInternalOwner layout) (internalLabel allWidths layout)
+ (X.packingData.shrinkPartySite layout m (party layout t dir)))
+ (z : (S).network.Half (X.packingData.shrinkPartySite layout m (party layout t dir)))
+ (dst : ℕ) (mem : Word w → Word w) (fit : dst + allWidths m (layout, t) ≤ 2 ^ w)
+ (i : Fin (allWidths m (layout, t))) :
+ let halves : (S).network.Half (site X layout m t dir) :=
+ ⟨fun e he ↦ z.1 e ((party_site X layout m t dir).trans he),
+ fun e he ↦ z.2 e ((party_site X layout m t dir).trans he)⟩
+ nativeFill X layout subdiv (W) I m t dir halves dst mem ((dst + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w (RAMSerialization.wordBits _
+ (mapColumn X layout subdiv I hpos m t allWidths dir h z) i) := by
+ intro halves
+ rw [nativeFill_eq X layout subdiv (W) I hpos m t dir halves dst mem, mapColumn_bits]
+ exact (PrivateFields.storeBits_read dst _ mem (by simpa using fit)
+ ⟨i.val, by simp⟩).trans (by simp only [List.getElem_ofFn]; rfl)
+
+end Map
+
+section Selection
+
+open MotifBlocks MotifGrid MotifConversion ShrinkMotif
+open CompressorRecords.ShrinkSliceSweep
+
+variable {K : Type*} [_root_.Field K] {factor : ℝ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable {w : ℕ}
+
+open Classical in
+/-- Extract exactly the three preconditions of the reverse reader from the
+selected global row sweep at the physical dense ordinal of a motif and role. -/
+theorem selected_inputs (s : X.ShrinkSelection F) (term : Word w) (stride widthBase : ℕ)
+ (mem : Memory w) :
+ let T := selectedAllocation F X s term stride widthBase subdiv
+ let sites := Shrink.packedIndex (a := a) (g := g) X.baseIndex
+ let id := (ShrinkMotifOrder.stateNumber X m, t)
+ let row := T.row id
+ T.Fits → (∀ i, Image (T.row i)
+ (selected X.packingData X.shrinkNumber sites T F X.packingWidth s i) mem) →
+ Image row (X.packingData.termWidths F X.shrinkNumber X.packingWidth s m T.layout t) mem ∧
+ row.count.val = subdiv t ∧ Workspace row.total row.dst row.bank 1 (subdiv t) := by
+ intro T sites id row fit images
+ have count : row.count.val = subdiv t := (T.row_vals fit id).2.2.2.2
+ refine ⟨?_, count, count ▸ T.space fit id⟩
+ simpa only [selected, id, ShrinkMotifOrder.stateNumber, Equiv.symm_apply_apply, sites]
+ using images id
+
+end Selection
+
+end PairSimulation.ShrinkSurvivingOperands
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSurvivingPointers.lean b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingPointers.lean
new file mode 100644
index 0000000000..60be9d2bc8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingPointers.lean
@@ -0,0 +1,215 @@
+import OAI.Computability.VPVNP.PairShrinkSurvivingOperands
+import OAI.Computability.VPVNP.CompressorSlotWidth
+import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe
+
+/-!
+# Runtime pointers for surviving supply slices
+
+The motif ordinal addresses a dense table of original CD arc numbers.
+Recover the old base and lane, insert the role and subdivision digits, and
+read the appropriate endpoint in the inverse sorted-field table. Removing
+the direction digit gives the next state's actual port number.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSurvivingPointers
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData
+open CompressorRecords CompressorRecords.PhaseRecipe CompressorRecords.ShrinkSliceSweep
+open ShrinkSurvivingFrames
+open scoped Fin.CommRing
+
+variable {w : ℕ} (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+
+/-- Runtime heads and dimensions of the retained shrinking tables. -/
+structure Inputs where
+ /-- Dense motif ordinal indexing both the absolute CD lookup and the four role-specific
+ interval records. -/
+ dense : Expr
+ /-- Head of the table mapping each dense motif ordinal to its original CD arc number. -/
+ absoluteHead : Expr
+ /-- Head of the inverse sorted-slot table indexed by a surviving arc number and endpoint
+ orientation. -/
+ inverseHead : Expr
+ /-- Number of remaining lanes used to split and reassemble the absolute CD arc address. -/
+ lanes : Expr
+ /-- Count of old base arcs used to displace a surviving arc's base number by its role
+ ordinal. -/
+ oldBases : Expr
+ /-- Start of the dense motif-by-role records containing the subdivision interval frames. -/
+ intervalHead : Expr
+
+/-- Read the original CD arc number at the dense motif's entry in the absolute-index table. -/
+def Inputs.absolute (H : Inputs) : Expr := .load (H.absoluteHead.add H.dense)
+
+/-- Insert the role and subdivision between the old CD base and its absolute lane. -/
+def Inputs.arc (H : Inputs) (subdiv : Fin 4 → ℕ) (t : Fin 4) (j : Fin (subdiv t)) : Expr :=
+ let abs := H.absolute
+ let base := (abs.div H.lanes).add (H.oldBases.mul (.lit t.val))
+ let key := (base.mul (.lit (∑ i, subdiv i))).add (.lit j.val)
+ (key.mul H.lanes).add (abs.mod H.lanes)
+
+/-- Read a sorted endpoint from the inverse table at the two-field arc address. -/
+def Inputs.rect (H : Inputs) (subdiv : Fin 4 → ℕ) (t : Fin 4)
+ (j : Fin (subdiv t)) (dir : Bool) : Expr :=
+ let field := ((H.arc subdiv t j).mul (.lit 2)).add (.lit dir.toNat)
+ .load (H.inverseHead.add field)
+
+/-- The sorted rows interleave outgoing and incoming owners at each site. -/
+def port (degree : ℕ) (rect : Expr) : Expr :=
+ let site := (rect.div (.lit degree)).div (.lit 2)
+ (site.mul (.lit degree)).add (rect.mod (.lit degree))
+
+/-- Dense ordinal and role address the interval bank. Its header includes
+two totals, two singleton cells and two subdivision columns. -/
+def Inputs.frame (H : Inputs) (subdiv : Fin 4 → ℕ) (t : Fin 4) (j : Fin (subdiv t)) : Expr :=
+ let id := (H.dense.mul (.lit 4)).add (.lit t.val)
+ let base := H.intervalHead.add (id.mul (.lit (5 + 7 * ∑ i, subdiv i)))
+ base.add (.lit (5 + 2 * subdiv t + 3 * j.val))
+
+variable {pub state mem}
+
+private theorem eval_divmod (x y : Expr) {n d : ℕ} (hx : (x.eval pub state mem).val = n)
+ (hy : (y.eval pub state mem).val = d) :
+ (x.div y).eval pub state mem = ((n / d : ℕ) : Word w) ∧
+ (x.mod y).eval pub state mem = ((n % d : ℕ) : Word w) := by
+ change Fin.ofNat _ ((x.eval pub state mem).val / (y.eval pub state mem).val) = _ ∧
+ Fin.ofNat _ ((x.eval pub state mem).val % (y.eval pub state mem).val) = _
+ rw [hx, hy]
+ exact ⟨rfl, rfl⟩
+
+variable (H : Inputs)
+
+/-- Removing the side bit from a represented sorted endpoint returns its
+site-major slot ID. This calculation uses the actual word divisions. -/
+theorem port_eval (rect : Expr) (degree site : ℕ) (side : Bool) (slot : Fin degree)
+ (hd : degree < 2 ^ w) (htwo : 2 < 2 ^ w)
+ (stored : (rect.eval pub state mem).val = (2 * site + side.toNat) * degree + slot.val) :
+ (port degree rect).eval pub state mem = ((site * degree + slot.val : ℕ) : Word w) := by
+ let owner := 2 * site + side.toNat
+ have hlen : ((Expr.lit degree).eval pub state mem).val = degree := Nat.mod_eq_of_lt hd
+ have ho : ((rect.div (.lit degree)).eval pub state mem).val = owner := by
+ have hs := (eval_divmod rect (.lit degree) stored hlen).1
+ have quotient : (owner * degree + slot.val) / degree = owner := by
+ rw [Nat.mul_comm owner, Nat.mul_add_div (Nat.zero_lt_of_lt slot.isLt),
+ Nat.div_eq_of_lt slot.isLt, Nat.add_zero]
+ rw [show (rect.div (.lit degree)).eval pub state mem = _ from hs, quotient]
+ exact Nat.mod_eq_of_lt (by
+ have hle := Nat.div_le_self (owner * degree + slot.val) degree
+ rw [quotient] at hle
+ exact hle.trans_lt (stored ▸ (rect.eval pub state mem).isLt))
+ have hmod := (eval_divmod rect (.lit degree) stored hlen).2
+ have hs := (eval_divmod (rect.div (.lit degree)) (.lit 2) ho
+ (show ((Expr.lit 2).eval pub state mem).val = 2 from Nat.mod_eq_of_lt htwo)).1
+ have sideLt : side.toNat < 2 := by cases side <;> decide
+ have quo : owner / 2 = site := by
+ change (2 * site + side.toNat) / 2 = site
+ rw [Nat.mul_add_div (by decide : 0 < 2), Nat.div_eq_of_lt sideLt, Nat.add_zero]
+ rw [quo] at hs
+ rw [Nat.mul_add_mod_of_lt slot.isLt] at hmod
+ change ((rect.div (.lit degree)).div (.lit 2)).eval pub state mem * (degree : Word w) +
+ (rect.mod (.lit degree)).eval pub state mem = _
+ rw [hs, hmod, Nat.cast_add, Nat.cast_mul]
+
+
+/-- Read the absolute arc field at the selected dense motif ordinal. -/
+theorem absolute_eval {a g : ℕ} (X : State a (packingLaneBits a g)) (m : X.packingData.Motif)
+ (base : Word w)
+ (dense : H.dense.eval pub state mem = ((ShrinkMotifOrder.stateNumber X m).val : Word w))
+ (head : H.absoluteHead.eval pub state mem = base)
+ (room : base.val + (ShrinkMotifOrder.stateNumber X m).val < 2 ^ w)
+ (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber base mem) :
+ (H.absolute.eval pub state mem).val =
+ (MotifAbsolute.absoluteIndex X.slots X.baseIndex m.val).val := by
+ let index := ShrinkMotifOrder.stateNumber X
+ have cell := directory (index m)
+ change (mem (base.val + (index m).val)).val =
+ (MotifAbsolute.absoluteIndex X.slots X.baseIndex (index.symm (index m)).val).val at cell
+ rw [index.symm_apply_apply] at cell
+ change (mem (H.absoluteHead.eval pub state mem + H.dense.eval pub state mem).val).val = _
+ rw [head, dense, Fin.val_add, Fin.val_natCast,
+ Nat.mod_eq_of_lt (by dsimp only [index]; omega : (index m).val < 2 ^ w), Nat.mod_eq_of_lt room]
+ exact cell
+
+/-- Evaluate the physical inverse-table read from the two-component field address. -/
+theorem rect_eval (subdiv : Fin 4 → ℕ) (t : Fin 4) (j : Fin (subdiv t)) (dir : Bool)
+ (inverse arc : ℕ) (atBase : H.inverseHead.eval pub state mem = (inverse : Word w))
+ (atArc : (H.arc subdiv t j).eval pub state mem = (arc : Word w))
+ (fits : inverse + (2 * arc + dir.toNat) < 2 ^ w) :
+ (H.rect subdiv t j dir).eval pub state mem = mem (inverse + (2 * arc + dir.toNat)) := by
+ change mem (H.inverseHead.eval pub state mem +
+ ((H.arc subdiv t j).eval pub state mem * (2 : Word w) + (dir.toNat : Word w))).val = _
+ rw [atBase, atArc, ← Nat.cast_ofNat (R := Word w) (n := 2), ← Nat.cast_mul,
+ ← Nat.cast_add, ← Nat.cast_add, mul_comm arc 2]
+ congr 1
+ exact Nat.mod_eq_of_lt fits
+
+section Arc
+
+variable {V H₀ Tag L : Type} {d c N J nL pad : ℕ}
+variable [AddCommGroup H₀] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H₀ Tag L d c) (subdiv : Fin 4 → ℕ)
+variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL)
+variable (m : P.Motif) (t : Fin 4) (j : Fin (subdiv t))
+
+/-- The genuine arc expression is the actual allocated rectangular record
+number, with the original CD lane retained as its lowest digit. -/
+theorem arc_eval
+ (absolute : (H.absolute.eval pub state mem).val =
+ (Slots.oldArcIndex P vertices tags lanes m.val).val)
+ (laneCount : (H.lanes.eval pub state mem).val = nL)
+ (bases : H.oldBases.eval pub state mem = (Slots.oldBaseArcCount N J d c : Word w)) :
+ (H.arc subdiv t j).eval pub state mem =
+ ((Slots.arcAddress P subdiv vertices tags lanes pad (.inl ⟨t, m, j⟩)).val : Word w) := by
+ let i : Compression.SurvivingSlots.Id P.Motif subdiv := ⟨t, m, j⟩
+ let old := P.baseMotifIndex vertices tags (P.baseMotif m)
+ let l := lanes (P.sourceLane m)
+ let stride := ∑ i, subdiv i
+ have abs : (H.absolute.eval pub state mem).val = l.val + nL * old.val := absolute
+ obtain ⟨div, mod⟩ := eval_divmod H.absolute H.lanes abs laneCount
+ rw [Nat.add_mul_div_left _ _ (Nat.zero_lt_of_lt l.isLt),
+ Nat.div_eq_of_lt l.isLt, Nat.zero_add] at div
+ rw [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt l.isLt] at mod
+ have lanesWord : H.lanes.eval pub state mem = (nL : Word w) :=
+ Fin.ext (laneCount.trans
+ (Nat.mod_eq_of_lt (laneCount ▸ (H.lanes.eval pub state mem).isLt)).symm)
+ have arc : (Slots.arcAddress P subdiv vertices tags lanes pad (.inl i)).val =
+ ((old.val + Slots.oldBaseArcCount N J d c * t.val) * stride + j.val) * nL + l.val := by
+ change l.val + nL * (j.val + stride * old.val +
+ (Slots.oldBaseArcCount N J d c * stride) * t.val) = _
+ ring
+ rw [show (Slots.arcAddress P subdiv vertices tags lanes pad (.inl ⟨t, m, j⟩)).val = _ from arc]
+ change (((H.absolute.div H.lanes).eval pub state mem +
+ H.oldBases.eval pub state mem * (t.val : Word w))
+ * (stride : Word w) + (j.val : Word w)) * H.lanes.eval pub state mem +
+ (H.absolute.mod H.lanes).eval pub state mem = _
+ rw [div, mod, bases, lanesWord]
+ simp only [Nat.cast_add, Nat.cast_mul]
+
+end Arc
+
+/-- Exact frame address in the retained row for a dynamic dense motif ordinal. -/
+theorem frame_eval {n A : ℕ} (T : Allocation w n A) (fit : T.Fits) (i : Fin n) (t : Fin 4)
+ (j : Fin (T.subdiv t)) (dense : H.dense.eval pub state mem = (i.val : Word w))
+ (interval : H.intervalHead.eval pub state mem = (T.widthEnd : Word w)) :
+ (H.frame T.subdiv t j).eval pub state mem =
+ (head (T.row (i, t)) (T.subdiv t) j : Word w) := by
+ have base := (T.row_vals fit (i, t)).2.2.1
+ have key : (Allocation.denseKey (i, t)).val = i.val * 4 + t.val := by
+ change t.val + 4 * i.val = _
+ omega
+ change H.intervalHead.eval pub state mem +
+ (H.dense.eval pub state mem * (4 : Word w) + (t.val : Word w)) *
+ ((5 + 7 * ∑ i, T.subdiv i : ℕ) : Word w) + ((5 + 2 * T.subdiv t + 3 * j.val : ℕ) : Word w) = _
+ rw [interval, dense, head, SliceSchedule.frameHead, base, Allocation.recordStart, key]
+ simp only [Allocation.recordStride, Allocation.stride, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+ ring
+
+end PairSimulation.ShrinkSurvivingPointers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSurvivingReadBounds.lean b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingReadBounds.lean
new file mode 100644
index 0000000000..bf12859f27
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingReadBounds.lean
@@ -0,0 +1,193 @@
+import OAI.Computability.VPVNP.PairShrinkSurvivingSelected
+import OAI.Computability.VPVNP.PairShrinkCallHeader
+import OAI.Computability.VPVNP.PairSimulationSliceReads
+import OAI.Computability.VPVNP.PairShrinkArgumentReadBounds
+
+/-!
+# External reads of the selected surviving-field gather
+
+The native column follows the old level's absolute CD and inverse slot tables.
+The next level supplies the incoming incidence and width prefixes. Its interval
+frame comes from the dense row allocated to this motif and role.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSurvivingReadBounds
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData
+open CompressorRecords PhaseRecipe SlotLevel ShrinkSlots ShrinkSliceSweep SliceSchedule
+open NodeArguments ShrinkSurvivingPointers ShrinkSurvivingOperands ShrinkSurvivingSelected
+open SourceTransport
+open private Allocation.local_stop Allocation.record_stop from
+ OAI.Computability.VPVNP.CompressorShrinkSliceSweep
+open scoped Fin.CommRing
+
+variable {w H : ℕ} {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w}
+local notation "safe" => Expr.ReadsFrom (· < H) pub state mem
+local notation "ev" => Expr.eval pub state mem
+
+private theorem cell_safe (level : Expr) (i : ℕ) (hs : safe level)
+ (room : (ev level).val + i < H) : safe (cell level i) := by
+ refine ⟨⟨hs, trivial⟩, ?_⟩
+ change (ev level + (i : Word w)).val < H
+ rw [Fin.val_add, Fin.val_natCast]
+ exact (Nat.mod_le _ _).trans_lt ((Nat.add_le_add_left (Nat.mod_le i _) _).trans_lt room)
+
+/-- The six addresses or dimensions supplied by the old level. -/
+structure TableReads (P : ShrinkSurvivingPointers.Inputs) (H : ℕ)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w) : Prop where
+ dense : P.dense.ReadsFrom (· < H) pub state mem
+ absolute : P.absoluteHead.ReadsFrom (· < H) pub state mem
+ inverse : P.inverseHead.ReadsFrom (· < H) pub state mem
+ lanes : P.lanes.ReadsFrom (· < H) pub state mem
+ bases : P.oldBases.ReadsFrom (· < H) pub state mem
+ interval : P.intervalHead.ReadsFrom (· < H) pub state mem
+
+theorem inputs_reads (a : ℕ) (level motif arena stride node dest : Expr)
+ (levelSafe : safe level) (motifSafe : safe motif) (arenaSafe : safe arena)
+ (strideSafe : safe stride) (oldRoom : (ev level).val + 42 < H)
+ (nextRoom : (ev (cell level 40)).val + 59 < H) :
+ let K := inputs a level motif arena stride node dest
+ TableReads K.tables H pub state mem ∧
+ ArgumentReadBounds.FieldsReadable K.half H pub state mem := by
+ intro K
+ have old (i : ℕ) (h : i ≤ 42) := cell_safe level i levelSafe (by omega)
+ have next (i : ℕ) (h : i ≤ 59) := cell_safe (cell level 40) i (old 40 (by decide)) (by omega)
+ exact ⟨⟨motifSafe, old 39 (by decide), old 41 (by decide), old 3 (by decide),
+ ⟨old 0 (by decide), trivial⟩, old 42 le_rfl⟩,
+ ⟨arenaSafe, strideSafe, next 58 (by decide), next 59 le_rfl⟩⟩
+
+/-- The job destination uses the old base and residual-lane counts. -/
+theorem destination_reads (O : ShrinkCallHeader.Operands) (a : ℕ) (dir : Bool) (t : Fin 4)
+ (levelSafe : safe O.level) (hiddenSafe : safe O.hidden) (strideSafe : safe O.slotStride)
+ (oldRoom : (ev O.level).val + 3 < H) : safe ((O.inputs a).surviving dir t) := by
+ have h₀ := cell_safe O.level 0 levelSafe (by omega)
+ have h₃ := cell_safe O.level 3 levelSafe oldRoom
+ have count : safe (O.count a) := ⟨⟨⟨h₀, trivial, h₃⟩, trivial⟩, trivial⟩
+ exact ⟨⟨hiddenSafe, ⟨trivial, count⟩, strideSafe⟩, trivial, strideSafe⟩
+
+variable {a b g : ℕ} {δ : ℝ} (X : State a (packingLaneBits a g))
+local notation "s" => levelShape (b := b) X
+local notation "sub" => Shape.subdivisions (levelShape (b := b) X)
+local notation "tags" => bitWordFinEquiv (packingTagBits (2 ^ a))
+local notation "lanes" => bitWordFinEquiv g
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Only one absolute CD and one inverse record are loaded to recover the
+endpoint port. Repeated occurrences of these loads stay inside the same arrays. -/
+theorem port_reads (P : ShrinkSurvivingPointers.Inputs) (m : X.packingData.Motif)
+ (t : Fin 4) (dir : Bool) (j : Fin ((levelShape (b := b) X).subdivisions t))
+ (heads : Heads) (absolute : Word w)
+ (hp : Published X P m heads absolute (b := b) (pub := pub) (state := state) (mem := mem))
+ (headsSafe : TableReads P H pub state mem)
+ (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absolute mem)
+ (absFit : absolute.val + (ShrinkMotifOrder.stateNumber X m).val < 2 ^ w)
+ (absRoom : absolute.val + (ShrinkMotifOrder.stateNumber X m).val < H)
+ (inverseRoom : SlotLevel.targetsHead s heads ≤ H) :
+ safe (port (2 ^ b) (P.rect sub t j dir)) := by
+ let ordinal := (ShrinkMotifOrder.stateNumber X m).val
+ have ha : safe P.absolute := by
+ refine ⟨⟨headsSafe.absolute, headsSafe.dense⟩, ?_⟩
+ change (ev P.absoluteHead + ev P.dense).val < H
+ rw [hp.absoluteHead, hp.dense, Fin.val_add, Fin.val_natCast]
+ exact (Nat.mod_le _ _).trans_lt
+ ((Nat.add_le_add_left (Nat.mod_le ordinal _) _).trans_lt absRoom)
+ have arcSafe : safe (P.arc sub t j) :=
+ ⟨⟨⟨⟨⟨⟨ha, headsSafe.lanes⟩, headsSafe.bases, trivial⟩, trivial⟩, trivial⟩, headsSafe.lanes⟩,
+ ha, headsSafe.lanes⟩
+ let id := Slots.arcAddress X.packingData sub X.baseIndex tags lanes (pad s) (.inl ⟨t, m, j⟩)
+ have abs := absolute_eval P X m absolute hp.dense hp.absoluteHead absFit directory
+ have arc : ev (P.arc sub t j) = (id.val : Word w) :=
+ arc_eval P X.packingData sub X.baseIndex tags lanes m t j abs hp.laneCount hp.oldBases
+ have inside : 2 * id.val + dir.toNat < fields s := by
+ let N := Slots.RecordCount (s).bases (s).tags (s).lanes (s).oldDegree (s).colors (pad s) sub
+ have hi : id.val < N := id.isLt
+ have side : dir.toNat < 2 := by cases dir <;> decide
+ change _ < N * 2
+ omega
+ have rectSafe : safe (P.rect sub t j dir) := by
+ refine ⟨⟨headsSafe.inverse, ⟨arcSafe, trivial⟩, trivial⟩, ?_⟩
+ change (ev P.inverseHead + (ev (P.arc sub t j) * (2 : Word w) + (dir.toNat : Word w))).val < H
+ rw [hp.inverseHead, arc, ← Nat.cast_ofNat (R := Word w) (n := 2), ← Nat.cast_mul,
+ ← Nat.cast_add, ← Nat.cast_add, Nat.mul_comm id.val 2, Fin.val_natCast]
+ exact (Nat.mod_le _ _).trans_lt ((Nat.add_lt_add_left inside _).trans_le inverseRoom)
+ exact ⟨⟨⟨⟨rectSafe, trivial⟩, trivial⟩, trivial⟩, rectSafe, trivial⟩
+
+/-- Confinement of every compiled operand in one native column, for either
+endpoint of the actual selected wire. -/
+theorem setup_reads (K : ShrinkSurvivingColumn.Inputs) (m : X.packingData.Motif)
+ (t : Fin 4) (dir : Bool) (j : Fin ((levelShape (b := b) X).subdivisions t))
+ (ready : ShrinkMotif.Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ)
+ (layout : Bool) (width : X.packingData.Motif → Fin 4 → ℕ)
+ (heads : Heads) (absolute : Word w)
+ (hp : Published X K.tables m heads absolute (b := b) (pub := pub) (state := state) (mem := mem))
+ (headsSafe : TableReads K.tables H pub state mem)
+ (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absolute mem)
+ (sorted : Build.OrderedTables X ready layout heads mem)
+ (absFit : absolute.val + (ShrinkMotifOrder.stateNumber X m).val < 2 ^ w)
+ (absRoom : absolute.val + (ShrinkMotifOrder.stateNumber X m).val < H)
+ (inverseRoom : SlotLevel.targetsHead s heads ≤ H)
+ (slotFit : finish s heads < 2 ^ w) (degreeFit : 2 ^ b < 2 ^ w) (twoFit : 2 < 2 ^ w)
+ (inc : IncidenceDirectory w) (A : Arena) {layer pitch : ℕ}
+ (stored : K.half.Stored inc A layer pitch pub state mem)
+ (fieldHeads : ArgumentReadBounds.FieldsReadable K.half H pub state mem)
+ (nodeSafe : safe K.node) (destSafe : safe K.destination) :
+ let slots := X.shrinkStateIndex ready layout
+ let Y := X.shrinkOutputState layout sub width slots
+ let size := Fintype.card Y.Base * 2 ^ g * 2 ^ b
+ inc.ActualColumns Y mem → size ≤ 2 ^ w → inc.actualIn.val + size ≤ H →
+ inc.width.val + size ≤ H → ∀ i, safe ((K.setup (2 ^ b) sub t dir j).operands i) := by
+ intro slots Y size cols cap inRoom widthRoom i
+ let portExpr := port (2 ^ b) (K.tables.rect sub t j dir)
+ let v := site X layout m t dir
+ let k := slot X layout sub width slots m t dir j
+ have portAt : ev portExpr = IncidenceDirectory.actualPort Y (v, k) :=
+ port_eq X ready layout width K.tables m t dir j heads absolute hp directory sorted
+ absFit slotFit degreeFit twoFit
+ have portSafe := port_reads X K.tables m t dir j heads absolute hp headsSafe directory
+ absFit absRoom inverseRoom
+ have src := ArgumentReadBounds.field Y v k K.half inc A stored cols cap degreeFit
+ K.node portExpr dir portAt H fieldHeads nodeSafe portSafe inRoom widthRoom
+ have frame : safe (K.tables.frame sub t j) :=
+ ⟨⟨headsSafe.interval, ⟨⟨headsSafe.dense, trivial⟩, trivial⟩, trivial⟩, trivial⟩
+ fin_cases i <;> first | exact src | exact destSafe | exact frame | trivial
+
+/-- Every native frame load is below the exclusive end of its dense row bank. -/
+theorem frame_end {n A : ℕ} (T : Allocation w n A) (fit : T.Fits) (idx : Fin n)
+ (t : Fin 4) (j : Fin (T.subdiv t)) :
+ ShrinkSurvivingFrames.head (T.row (idx, t)) (T.subdiv t) j + 2 < T.last := by
+ have bank := (T.row_vals fit (idx, t)).2.2.1
+ have localEnd := Allocation.local_stop T (idx, t)
+ have globalEnd := Allocation.record_stop T (idx, t)
+ have hi := j.isLt
+ apply lt_of_lt_of_le _ (localEnd.trans globalEnd)
+ simp only [ShrinkSurvivingFrames.head, bank, stop, one_mul]
+ omega
+
+theorem frame_reads {n A : ℕ} (T : Allocation w n A) (fit : T.Fits) (idx : Fin n)
+ (t : Fin 4) (j : Fin (T.subdiv t)) (room : T.last ≤ H) (bs : List Bool) :
+ let ptr := ShrinkSurvivingFrames.head (T.row (idx, t)) (T.subdiv t) j
+ Reads (· < H) (PrivateSlices.frameEvents mem (ptr : Word w) bs) := by
+ intro ptr
+ have h : ptr + 2 < H := (frame_end T fit idx t j).trans_le room
+ have hw : ptr + 2 < 2 ^ w := (frame_end T fit idx t j).trans fit.room
+ have atOne : ((ptr : Word w) + 1).val = ptr + 1 := by
+ rw [← Nat.cast_add_one]
+ exact Nat.mod_eq_of_lt (by omega)
+ have atTwo : ((ptr : Word w) + 1 + 1).val = ptr + 2 := by
+ rw [← Nat.cast_add_one, ← Nat.cast_add_one]
+ exact Nat.mod_eq_of_lt hw
+ apply PrivateSlices.frameEvents_reads
+ · exact (Nat.mod_le _ _).trans_lt (by omega)
+ · omega
+ · omega
+
+end PairSimulation.ShrinkSurvivingReadBounds
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSurvivingRect.lean b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingRect.lean
new file mode 100644
index 0000000000..734661f8c9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingRect.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.PairShrinkSurvivingOperands
+import OAI.Computability.VPVNP.CompressorRecordRefreshArgumentAddress
+import OAI.Computability.VPVNP.CompressorSlotCoreAccess
+
+/-!
+# Inverse slot-table lookup at a surviving subdivision
+
+The inverse array published by the shrinking slot construction keeps the
+orientation in the middle of each rectangular slot number. The site is the
+absolute endpoint of the selected arc, including its remaining lane.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSurvivingRect
+
+open BurstRAM Compression Compression.State Compression.PackingData Compression.ShrinkEnergy
+open Compression.ShrinkMotif
+open CompressorRecords CompressorRecords.Slots CompressorRecords.SlotLevel
+open CompressorRecords.SlotSchedule CompressorRecords.ShrinkSlots
+open CompressorRecords.PortRefresh.ArgumentAddress ShrinkSurvivingOperands
+
+variable {a b g w : ℕ} {δ : ℝ} (X : State a (packingLaneBits a g))
+variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) (layout : Bool)
+variable (width : X.packingData.Motif → Fin 4 → ℕ)
+local notation "s" => levelShape (b := b) X
+local notation "sub" => Shape.subdivisions (levelShape (b := b) X)
+local notation "I" => X.shrinkStateIndex ready layout
+local notation "Y" => X.shrinkOutputState layout sub width (I)
+local notation "tags" => bitWordFinEquiv (packingTagBits (2 ^ a))
+local notation "lanes" => bitWordFinEquiv g
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+variable (m : X.packingData.Motif) (t : Fin 4) (dir : Bool)
+variable (j : Fin ((levelShape (b := b) X).subdivisions t))
+
+private theorem site_index_eq (u : Site X.Base (BitWord (packingTagBits (2 ^ a))) (BitWord g)) :
+ (siteIndex X.baseIndex tags lanes u).val = siteOrdinal (Y) (packedSiteEquiv u) := by
+ let J := 2 ^ packingTagBits (2 ^ a)
+ let n := 2 ^ g
+ let v := (X.baseIndex u.1).val
+ let k := (tags u.2.1).val
+ let l := (lanes u.2.2).val
+ change l + n * k + J * n * v = (k + J * v) * n + l
+ ring
+
+/-- Read the inverse table at the physical candidate-field identifier.
+The two fields of each genuine arc have consecutive identifiers. -/
+theorem read_val (h : Heads) (mem : Memory w)
+ (tables : Build.OrderedTables X ready layout h mem)
+ (rectFit : owners s * (s).newDegree ≤ 2 ^ w) :
+ let idx := arcAddress X.packingData sub X.baseIndex tags lanes (pad s) (.inl ⟨t, m, j⟩)
+ let side : ℕ := if dir then 1 else 0
+ (mem (inverseHead s h + (2 * idx.val + side))).val =
+ siteOrdinal (Y) (site X layout m t dir) * 2 * 2 ^ b + side * 2 ^ b +
+ (slot X layout sub width (I) m t dir j).val := by
+ intro idx side
+ let i : ActualId X.packingData sub (pad s) := .inl ⟨t, m, j⟩
+ let e : Fin 2 := if dir then 1 else 0
+ let D := slotDirectory X.packingData sub X.baseIndex tags lanes layout (pad := pad s)
+ let hD := fun v ↦ (slotDirectory_degree X.packingData sub X.baseIndex tags lanes
+ (two_le_packingColors a) layout v).trans (Nat.add_sub_of_le ready.degree_budget)
+ let rank := (sortedFields D (2 ^ b) hD (i, e)).val
+ have eSide : e.val = side := by cases dir <;> rfl
+ have addr : (D.address (i, e)).val = 2 * idx.val + side := by
+ change e.val + 2 * idx.val = _
+ rw [eSide, Nat.add_comm]
+ rw [← addr, tables.byField, Fin.val_ofNat, Nat.mod_eq_of_lt
+ ((sortedFields D (2 ^ b) hD (i, e)).isLt.trans_le rectFit)]
+ have sorted := rectangular_slot X.packingData sub X.baseIndex tags lanes (two_le_packingColors a)
+ (orderedDyadicPacking_validTags X.slots X.baseIndex) layout ready.degree_budget
+ (Nat.one_lt_two_pow (Nat.succ_pos _).ne') i e
+ let z := paddedBaseId X.packingData sub i
+ let pos := actualEnd X.packingData sub tags layout dir i
+ have place : packedSiteEquiv pos = site X layout m t dir := by cases dir <;> rfl
+ have which : ((if e = 1 then (I).incoming else (I).outgoing) z).2 =
+ slot X layout sub width (I) m t dir j := by
+ cases dir with
+ | false => rfl
+ | true =>
+ change ((I).incoming z).2 = ((I).graph.base.target ((I).outgoing z)).2
+ exact congrArg Prod.snd ((I).match_eq z).symm
+ have owner : (D.owner (i, e)).val = side + 2 * siteOrdinal (Y) (site X layout m t dir) := by
+ have test : decide (e = 1) = dir := by cases dir <;> rfl
+ change e.val + 2 * (siteIndex X.baseIndex tags lanes
+ (actualEnd X.packingData sub tags layout (decide (e = 1)) i)).val = _
+ rw [test, site_index_eq X ready layout width, eSide, place]
+ change rank = _
+ change rank = ((if e = 1 then (I).incoming else (I).outgoing) z).2.val +
+ 2 ^ b * (D.owner (i, e)).val at sorted
+ rw [sorted, which, owner]
+ ring
+
+end PairSimulation.ShrinkSurvivingRect
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkSurvivingSelected.lean b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingSelected.lean
new file mode 100644
index 0000000000..d56a6cb8ac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkSurvivingSelected.lean
@@ -0,0 +1,221 @@
+import OAI.Computability.VPVNP.PairShrinkSurvivingColumn
+import OAI.Computability.VPVNP.PairShrinkSurvivingRect
+
+/-!
+# Surviving slice pointers on the selected shrinking graph
+
+The old header identifies the absolute CD array, the retained inverse slot
+array and the dense interval banks. The next header supplies the incidence
+and width columns of the private packet's state. Only the selected motif and
+the private map-job addresses vary between visits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkSurvivingSelected
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkEnergy
+open Compression.ShrinkMotif
+open CompressorRecords CompressorRecords.PhaseRecipe CompressorRecords.SlotLevel
+open CompressorRecords.ShrinkSlots CompressorRecords.PortRefresh.ArgumentAddress
+open CompressorRecords.ShrinkSliceSweep
+open ShrinkSurvivingOperands ShrinkSurvivingPointers NodeArguments
+open scoped Fin.CommRing
+
+/-- Address lookup relative to a dynamic level-header pointer. -/
+def cell (header : Expr) (offset : ℕ) : Expr := .load (header.add (.lit offset))
+
+/-- Dynamic heads used by the selected output node. The old degree exponent
+fixes the local packing radices. The input base count and the remaining lanes
+are read from the header at runtime. -/
+def inputs (a : ℕ) (level motif arena stride node dest : Expr) : ShrinkSurvivingColumn.Inputs :=
+ let next := cell level 40
+ let baseRadix := 2 ^ (packingTagBits (2 ^ a)) * (2 ^ a * (2 ^ (2 * 2 ^ a + 1) * 2 ^ a))
+ let H : ShrinkSurvivingPointers.Inputs :=
+ ⟨motif, cell level 39, cell level 41, cell level 3, (cell level 0).mul (.lit baseRadix),
+ cell level 42⟩
+ let half : ShrinkOldHalves.Physical.Header :=
+ ⟨arena, stride, cell next 14, cell next 15, cell next 57, cell next 58, cell next 59⟩
+ ⟨H, half, node, dest⟩
+
+variable {a b g w : ℕ} {δ : ℝ} (X : State a (packingLaneBits a g))
+variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) (layout : Bool)
+variable (width : X.packingData.Motif → Fin 4 → ℕ)
+local notation "s" => levelShape (b := b) X
+local notation "sub" => Shape.subdivisions (levelShape (b := b) X)
+local notation "I" => X.shrinkStateIndex ready layout
+local notation "Y" => X.shrinkOutputState layout sub width (I)
+local notation "tags" => bitWordFinEquiv (packingTagBits (2 ^ a))
+local notation "lanes" => bitWordFinEquiv g
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+variable (H : ShrinkSurvivingPointers.Inputs)
+variable (m : X.packingData.Motif) (t : Fin 4) (dir : Bool)
+variable (j : Fin ((levelShape (b := b) X).subdivisions t))
+variable {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w}
+
+/-- The runtime table expressions encode the selected motif, absolute CD and inverse-slot table
+heads, residual lane count, and old base-arc count. -/
+structure Published (heads : Heads) (absolute : Word w) : Prop where
+ dense : H.dense.eval pub state mem = ((ShrinkMotifOrder.stateNumber X m).val : Word w)
+ absoluteHead : H.absoluteHead.eval pub state mem = absolute
+ inverseHead : H.inverseHead.eval pub state mem = (SlotLevel.inverseHead s heads : Word w)
+ laneCount : (H.lanes.eval pub state mem).val = 2 ^ g
+ oldBases : H.oldBases.eval pub state mem =
+ (Slots.oldBaseArcCount (Fintype.card X.Base) (2 ^ packingTagBits (2 ^ a))
+ (2 ^ a) (2 * 2 ^ a + 1) : Word w)
+
+
+private theorem cell_eval (header : Expr) (n offset : ℕ)
+ (word : header.eval pub state mem = (n : Word w)) (fit : n + offset < 2 ^ w) :
+ (cell header offset).eval pub state mem = mem (n + offset) := by
+ change mem (header.eval pub state mem + (offset : Word w)).val = _
+ rw [word, ← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt fit]
+
+/-- Instantiate the runtime setup from the actual header cells. The only
+variable private operands are the arena, the node and the job's destination. -/
+theorem inputs_readback (heads : Heads) (absolute : Word w) (old next interval : ℕ)
+ (inc : IncidenceDirectory w) (A : Arena) (layer pitch : ℕ)
+ (header motif arena stride node dest : Expr)
+ (headerWord : header.eval pub state mem = (old : Word w))
+ (motifWord : motif.eval pub state mem = ((ShrinkMotifOrder.stateNumber X m).val : Word w))
+ (arenaWord : arena.eval pub state mem = (A.start : Word w))
+ (strideWord : stride.eval pub state mem = (A.stride : Word w))
+ (oldFit : old + 42 < 2 ^ w) (nextFit : next + 59 < 2 ^ w)
+ (vertices : mem (old + 0) = (Fintype.card X.Base : Word w))
+ (laneWord : (mem (old + 3)).val = 2 ^ g)
+ (absWord : mem (old + 39) = absolute) (nextWord : mem (old + 40) = (next : Word w))
+ (inverseWord : mem (old + 41) = (SlotLevel.inverseHead s heads : Word w))
+ (intervalWord : mem (old + 42) = (interval : Word w))
+ (layerWord : mem (next + 14) = (layer : Word w))
+ (pitchWord : mem (next + 15) = (pitch : Word w))
+ (outWord : mem (next + 57) = inc.actualOut)
+ (inWord : mem (next + 58) = inc.actualIn) (widthWord : mem (next + 59) = inc.width) :
+ let K := inputs a header motif arena stride node dest
+ Published X K.tables m heads absolute (b := b) (pub := pub) (state := state) (mem := mem) ∧
+ K.half.Stored inc A layer pitch pub state mem ∧
+ K.tables.intervalHead.eval pub state mem = (interval : Word w) := by
+ intro K
+ have oldAt (i : ℕ) (hi : i ≤ 42) := cell_eval header old i headerWord (by omega)
+ have newWord := (oldAt 40 (by decide)).trans nextWord
+ have newAt (i : ℕ) (hi : i ≤ 59) := cell_eval (cell header 40) next i newWord (by omega)
+ refine ⟨⟨motifWord, (oldAt 39 (by decide)).trans absWord,
+ (oldAt 41 (by decide)).trans inverseWord, ?_, ?_⟩,
+ ⟨arenaWord, strideWord, (newAt 14 (by decide)).trans layerWord,
+ (newAt 15 (by decide)).trans pitchWord, (newAt 57 (by decide)).trans outWord,
+ (newAt 58 (by decide)).trans inWord, (newAt 59 (by decide)).trans widthWord⟩,
+ (oldAt 42 le_rfl).trans intervalWord⟩
+ · exact (congrArg Fin.val (oldAt 3 (by decide))).trans laneWord
+ · change (cell header 0).eval pub state mem * _ = _
+ rw [(oldAt 0 (by decide)).trans vertices]
+ exact (Nat.cast_mul ..).symm
+
+/-- The runtime endpoint expression reads a genuine record from the retained
+tables and returns the exact state port on either side of the wire. -/
+theorem port_eq (heads : Heads) (absolute : Word w)
+ (hp : Published X H m heads absolute (b := b) (pub := pub) (state := state) (mem := mem))
+ (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absolute mem)
+ (tables : Build.OrderedTables X ready layout heads mem)
+ (absFit : absolute.val + (ShrinkMotifOrder.stateNumber X m).val < 2 ^ w)
+ (fit : finish s heads < 2 ^ w) (degreeFit : 2 ^ b < 2 ^ w) (twoFit : 2 < 2 ^ w) :
+ (port (2 ^ b) (H.rect sub t j dir)).eval pub state mem =
+ IncidenceDirectory.actualPort (Y)
+ (site X layout m t dir, slot X layout sub width (I) m t dir j) := by
+ let id := Slots.arcAddress X.packingData sub X.baseIndex tags lanes (pad s) (.inl ⟨t, m, j⟩)
+ let inverse := SlotLevel.inverseHead s heads
+ have abs := absolute_eval H X m absolute hp.dense hp.absoluteHead absFit directory
+ have idx : (H.arc sub t j).eval pub state mem = (id.val : Word w) :=
+ arc_eval H X.packingData sub X.baseIndex tags lanes m t j abs hp.laneCount hp.oldBases
+ have limit : inverse + fields s ≤ finish s heads := by
+ simp only [inverse, finish, widthHead, inHead, outHead, inverseBaseHead, stopAddress,
+ shiftsHead, targetsHead]
+ omega
+ have cap : owners s * (s).newDegree ≤ 2 ^ w := by
+ have r : owners s * (s).newDegree ≤ inverse := by
+ change _ ≤ rowsHead s heads + (owners s + fields s) * (s).newDegree
+ rw [Nat.add_mul]
+ omega
+ omega
+ have idxLimit : 2 * id.val + dir.toNat < fields s := by
+ let n := Slots.RecordCount (s).bases (s).tags (s).lanes (s).oldDegree
+ (s).colors (pad s) sub
+ change _ < n * 2
+ have hi : id.val < n := id.isLt
+ have hs : dir.toNat < 2 := by cases dir <;> decide
+ omega
+ have actual := rect_eval H sub t j dir inverse id.val hp.inverseHead idx (by omega)
+ have read := ShrinkSurvivingRect.read_val X ready layout width m t dir j heads mem tables cap
+ let v := siteOrdinal (Y) (site X layout m t dir)
+ let k := slot X layout sub width (I) m t dir j
+ have val : ((H.rect sub t j dir).eval pub state mem).val =
+ (2 * v + dir.toNat) * 2 ^ b + k.val := by
+ rw [actual]
+ have side : dir.toNat = (if dir then 1 else 0) := by cases dir <;> rfl
+ rw [side]
+ change (mem (inverse + (2 * id.val + (if dir then 1 else 0)))).val = _
+ rw [read]
+ change v * 2 * 2 ^ b + _ * 2 ^ b + k.val = (2 * v + _) * 2 ^ b + k.val
+ ring
+ refine (port_eval (H.rect sub t j dir) (2 ^ b) v dir k degreeFit twoFit val).trans ?_
+ rw [IncidenceDirectory.actualPort_number]
+ exact congrArg (fun n : ℕ ↦ (n : Word w))
+ (IncidenceDirectory.actualOrder_val (Y) (site X layout m t dir, k)).symm
+
+
+section Column
+
+open MotifBlocks MotifGrid MotifConversion Compression.ShrinkMotif
+
+variable {K : Type*} [_root_.Field K] {factor : ℝ}
+variable (F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (sel : X.ShrinkSelection F) (term : Word w) (stride widthBase : ℕ)
+local notation "T" => selectedAllocation F X sel term stride widthBase sub
+local notation "side" => Allocation.layout (T)
+local notation "wid" =>
+ fun m t ↦ X.packingData.termWidths F X.shrinkNumber X.packingWidth sel m side t
+local notation "slots" => X.shrinkStateIndex ready side
+local notation "output" => X.shrinkOutputState side sub (wid) slots
+local notation "idx" => ShrinkMotifOrder.stateNumber X m
+local notation "bank" => Allocation.row (T) (idx, t)
+
+/-- The per-piece recorded native setup follows from the final level's
+absolute-ID, inverse-slot, interval and incidence tables. -/
+theorem recorded (K₀ : ShrinkSurvivingColumn.Inputs) (heads : Heads) (absolute : Word w)
+ (inc : IncidenceDirectory w) (A : Arena) (node dst layer pitch : ℕ)
+ (z : (output).network.Half (site X side m t dir))
+ (published : Published X K₀.tables m heads absolute (b := b)
+ (pub := pub) (state := state) (mem := mem))
+ (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absolute mem)
+ (sorted : Build.OrderedTables X ready side heads mem)
+ (absFit : absolute.val + (idx).val < 2 ^ w) (slotFit : finish s heads < 2 ^ w)
+ (degreeFit : 2 ^ b < 2 ^ w) (twoFit : 2 < 2 ^ w)
+ (allocation : (T).Fits)
+ (images : ∀ i, Image ((T).row i)
+ (selected X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) (T)
+ F X.packingWidth sel i) mem)
+ (half : K₀.half.Stored inc A layer pitch pub state mem)
+ (columns : inc.ActualColumns (output) mem)
+ (capacity : Fintype.card (output).Base * 2 ^ g * 2 ^ b ≤ 2 ^ w)
+ (nodeWord : K₀.node.eval pub state mem = (node : Word w))
+ (destination : K₀.destination.eval pub state mem = (dst : Word w))
+ (interval : K₀.tables.intervalHead.eval pub state mem = ((T).widthEnd : Word w)) :
+ (ShrinkSurvivingColumn.row X side sub (wid) slots m t dir z A node dst bank j).Recorded
+ (K₀.setup (2 ^ b) sub t dir j) pub state mem := by
+ have ord := port_eq X ready side (wid) K₀.tables m t dir j heads absolute published directory
+ sorted absFit slotFit degreeFit twoFit
+ have image := (selected_inputs X sub m t F sel term stride widthBase mem allocation images).1
+ exact ShrinkSurvivingColumn.recorded X side sub (wid) slots m t dir z A node dst bank K₀
+ ready.count_pos (T) allocation idx rfl rfl inc layer pitch half columns capacity degreeFit
+ nodeWord destination published.dense interval image j ord
+
+end Column
+
+end PairSimulation.ShrinkSurvivingSelected
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkTraversalAtVertex.lean b/lean/OAI/Computability/VPVNP/PairShrinkTraversalAtVertex.lean
new file mode 100644
index 0000000000..e57838056a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkTraversalAtVertex.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.PairTerminalSiteDirectories
+
+/-! # The shrinking locator on the current linked vertex memory -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalControllerInputs
+
+open BurstRAM TraversalRoles
+open private resident_data_frame from OAI.Computability.VPVNP.PairTerminalSiteDirectories
+
+/-- Only the six terminal scalar words and the headers inside the
+level interval need to be stable. The reference directories keep their
+original word values when counters below the first level change. -/
+theorem Resident.transfer_interval {w H first pitch offset cap base limit : ℕ}
+ {pub : Fin 11 → Word w} {reference current : Memory w}
+ {leaf : TaggedLayer} {ls : List (Fiber w)}
+ (d : Resident pub reference H first pitch offset cap base leaf ls)
+ (headers : ∀ j ≤ ls.length, first + j * pitch + 28 ≤ limit)
+ (range : ∀ x, first ≤ x → x < limit → current x = reference x)
+ (terminal : ∀ j ∈ terminalScalars, current (H + j) = reference (H + j)) :
+ Resident pub current H first pitch offset cap base leaf ls := by
+ apply resident_data_frame d terminal
+ intro j hj o ho
+ exact range _ (by omega) ((Nat.add_lt_add_left ho _).trans_le (headers j hj))
+
+end PairSimulation.TraversalControllerInputs
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TraversalControllerInputs LiveProgram PairStages.Group.Auxiliary
+open scoped Fin.CommRing
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+ {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f} {lanes T : ℕ}
+ {hT : T * S.laneBits ≤ lanes} {X : State (S.degreeExponent 0) lanes}
+ {z : (B.execute f hf T hT X).Choices} {G : PairStages.Group} {positions : ℕ}
+
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "tags" => selected B f hf T hT X z
+local notation "pub" => terminalOperands G
+local notation "layout" => BlockProgram.layout B (Fin.val (pub 2)) positions T
+local notation "width" => State.totalWidth (StateExecution.finalState (B.execute f hf T hT X) z)
+
+/-- The installed shrink handler uses the same directory family that the
+calendar froze in the shared-bit reference memory. Its live locator reads
+the headers in the later memory of this vertex. -/
+theorem VertexEntry.shrinkLocator {baseBits laneBits ord : ℕ} {tab : Fin (layout).shape.tables}
+ {calendar reference current : Memory G.w} {bits : Fin (width) → Bool}
+ (entry : VertexEntry B f hf T hT X z (layout) tab baseBits laneBits (pub)
+ calendar reference bits)
+ (packed : VertexPacked G (layout) B.recordLimit (tags) (width))
+ (later : LinkedVertexMemory G reference ord current) :
+ ∃ ds : (i : Fin (vs).length) → LevelDirectory (vs)[i] reference (endAddress (layout)),
+ Resident (pub) current (vertexHeader G).val (levelStart (layout) 0) (levelWords (layout))
+ (words B.recordLimit (ls) + (width)) B.recordLimit (endAddress (layout))
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers (vs) ds) := by
+ have live : (vs).length < (layout).levels := by
+ rw [← TerminalBootstrap.selected_last_index, TerminalBootstrap.selected_prior_length,
+ BlockProgram.actual_level_count, Nat.mul_comm T]
+ omega
+ obtain ⟨ds, _, resident⟩ := entry.boundedDirectories
+ obtain ⟨range, terminal⟩ := packed.traversal_frames later
+ refine ⟨ds, resident.transfer_interval (limit := endAddress (layout)) ?_ ?_ terminal⟩
+ · intro j hj
+ apply TraversalResidentHandoff.headers_before (layout) live (by change 28 ≤ 54; decide) j
+ simpa only [levelFibers, List.length_ofFn] using hj
+ · intro x lo hi
+ exact range x (by simpa only [levelStart, Nat.zero_mul, Nat.add_zero] using lo) hi
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkUpdatedBelow.lean b/lean/OAI/Computability/VPVNP/PairShrinkUpdatedBelow.lean
new file mode 100644
index 0000000000..b3b6ae27c5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkUpdatedBelow.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.PairShrinkPartyNative
+
+/-!
+# Retaining saved scratch below a shrinking job's staging area
+
+The packet witness fixes the geometry of the row writes. Their destinations
+and lengths apply to any saved scratch, even when its contents and stack
+boundary differ from those of the witness.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkPartyNative
+
+open BurstRAM Compression Compression.ShrinkMotif MotifBlocks MotifGrid MotifConversion
+open NodeArguments
+open private Job.conditions from OAI.Computability.VPVNP.PairShrinkPartyNative
+
+variable {a b g w packetEnd endAddr : ℕ} {δ factor : ℝ} {K : Type*} [_root_.Field K]
+variable {X : State a (packingLaneBits a g)}
+variable {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection F}
+variable {m : X.packingData.Motif} {party : Fin 6} (J : Job X F ready sel m party w)
+
+/-- Applying the job's writes to arbitrary saved scratch preserves each address below staging. -/
+theorem Job.updated_below {baseline : Word w → Word w} (packets : J.Packets packetEnd baseline)
+ (saved : DFS.Scratch w endAddr) (q : Word w) (below : q.val < J.scratch.staging) :
+ rawScratch (J.updated endAddr saved) q = rawScratch saved q := by
+ by_cases live : endAddr ≤ q.val
+ · have kept := (ShrinkPartyColumns.memory J.scratch J.row J.scratch.staging
+ (fun c i ↦ (Job.conditions J packets c i).2.1) (fun c i ↦ (Job.conditions J packets c i).2.2)
+ (rawScratch saved)).2 q below
+ simpa only [Job.updated, rawScratch, dite_eq_left live, DFS.scratch] using kept
+ · simp only [rawScratch, dite_eq_right live]
+
+end PairSimulation.ShrinkPartyNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkVertexEntry.lean b/lean/OAI/Computability/VPVNP/PairShrinkVertexEntry.lean
new file mode 100644
index 0000000000..313e6d6ff3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkVertexEntry.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.PairShrinkVertexImage
+import OAI.Computability.VPVNP.PairVertexLocatedBodyLinks
+import OAI.Computability.VPVNP.PairVertexStageRun
+
+/-!
+# Entering the actual shrinking stage of a selected traversal
+
+A popped descriptor on a shrinking level reaches the fixed stage whose degree
+matches the selected pass. Its local register view reads the same located owner
+and old header, even when its finite matrix bank uses a different numbering.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkVertexImage
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression CompressorRecords LocalHistory
+open TraversalRows TraversalRoles TraversalControllerInputs NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t : ℕ} (ord : B.Entry → Fin t)
+
+/-- The located child, hidden-field, and resident-map program for the selected elementary
+shrinking step. -/
+noncomputable abbrev active (i : Fin S.steps) : LocatedBody :=
+ ShrinkVertexStage.stage (S.degreeExponent i.castSucc) B.shrink.selectorBits (maps B ord i)
+
+variable {p r w : ℕ} (M : Machine w p r 11)
+ (pc : Fin (shrinkSegment B ord).count → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r) (done : Fin p)
+ (rows : ∀ a, M.code (pc a) = ((shrinkSegment B ord).row pc dfs saved reg done a).resize w)
+
+include rows in
+theorem active_rows (i : Fin S.steps) (j : Fin (active B ord i).code.count) :
+ let dest := LocatedBody.stagePC (active B ord) pc i
+ let localRegs := LocatedBody.stageBank (active B ord) reg i
+ M.code (dest j) = ((active B ord i).code.row dest dfs saved localRegs done j).resize w :=
+ LocatedBody.stage_rows (active B ord) M pc dfs saved reg done rows i j
+
+theorem active_locator (i : Fin S.steps) (j : Fin 14) :
+ LocatedBody.stageBank (active B ord) reg i ((active B ord i).locator j) =
+ LocatedBody.commonLocator (active B ord) reg j :=
+ LocatedBody.shared_locator (active B ord) reg i j
+
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+
+include rows in
+/-- Reach the selected stage's first child handoff with the published descriptor and owner.
+The exact trace includes the real level search and the fixed modulo dispatcher. -/
+theorem selected_entry {H first pitch offset base : ℕ} {raw m : Memory w}
+ (ds : (j : Fin (passes).length) → LevelDirectory passes[j] raw base)
+ (resident : Resident M.publicData m H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers passes ds))
+ (j : Fin (passes).length) (id : Fin passes[j].outputSites)
+ (shrinking : tagLevel B f hf passes[j] = .shrink)
+ (c : Config w p r) (start : c.pc = pc (shrinkSegment B ord).entry)
+ (node : (c.reg (dfs 7)).val = address B.recordLimit
+ (layerBase B.recordLimit base tags (j.val + 1)) id.val)
+ (fit : layerBase B.recordLimit base tags ((passes).length + 1) < 2 ^ w) :
+ ∃ i : Fin S.steps, passes[j].origin.ordinal = i.val ∧
+ passes[j].inputExponent = S.degreeExponent i.castSucc ∧ ∃ out,
+ Prefix M m c out [] (VertexLevel.trace M.publicData m (j.val + 1)
+ ((passes).length - (j.val + 1)) ++ List.replicate (S.steps + 7 + 2 * i.val) .tick) ∧
+ out.pc = LocatedBody.stagePC (active B ord) pc i (active B ord i).code.entry ∧
+ VertexLevel.Located M.publicData m (LocatedBody.commonLocator (active B ord) reg)
+ (c.reg (dfs 7)) j.val (id.val : Word w) out ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ ∀ q, q ∉ Set.range (LocatedBody.commonLocator (active B ord) reg) →
+ q ∉ Set.range ((VertexStageDispatch.scratchBank
+ (fun i => (active B ord i).tailCount)).trans reg) →
+ out.reg q = c.reg q := by
+ let bodies := fun i => (active B ord i).normalized
+ let tail := fun i => (active B ord i).tailCount
+ let lr := (VertexStageDispatch.locatorBank tail).trans reg
+ let sr := (VertexStageDispatch.scratchBank tail).trans reg
+ obtain ⟨front, select, _⟩ := VertexStageDispatch.locatedFamily_link bodies dfs saved done M tail
+ (fun _ => rfl) pc reg rows
+ obtain ⟨mid, pre, atSelect, located, _, frame⟩ :=
+ VertexLevel.selected_run B f hf T hT X z ds M _ dfs saved lr _ front resident
+ j id c start node fit
+ have len : (m (H + 1)).val = (passes).length + 1 := by
+ simpa [levelFibers] using resident.levels
+ have bound : (passes).length < 2 ^ w := by have := (m (H + 1)).isLt; omega
+ have total := VertexLevel.selected_pass_count B f hf T hT X z
+ have positive : 0 < T := by
+ by_contra! h
+ have empty : (passes).length = 0 := by rw [total, Nat.eq_zero_of_le_zero h, Nat.zero_mul]
+ exact Nat.not_lt_zero _ (j.isLt.trans_eq empty)
+ have periodFit : S.steps + 1 < 2 ^ w :=
+ (Nat.le_mul_of_pos_left _ positive).trans_lt (total ▸ bound)
+ have safe (l : Fin 14) : lr l ∉ Set.range sr := by
+ rintro ⟨x, h⟩
+ exact VertexStageDispatch.locator_disjoint_scratch tail l ⟨x, reg.injective h⟩
+ obtain ⟨i, ordinal, exp, out, post, atBody, kept⟩ :=
+ VertexStageDispatch.scheduled_run B f hf T hT X z select (safe 13) periodFit j
+ (j.isLt.trans bound) shrinking mid atSelect located.stage m
+ exact ⟨i, ordinal, exp, out, pre.trans post, atBody,
+ VertexStageDispatch.retainLocated located (fun l => kept.regs _ (safe l)),
+ kept.memory.trans frame.privateMem, kept.persistent.trans frame.persistent,
+ fun q hl hs => (kept.regs q hs).trans (frame.outside q hl)⟩
+
+end PairSimulation.ShrinkVertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkVertexFrameScan.lean b/lean/OAI/Computability/VPVNP/PairShrinkVertexFrameScan.lean
new file mode 100644
index 0000000000..ffb5c266cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkVertexFrameScan.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PairShrinkCallFrameStores
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoopExact
+
+/-!
+# Retaining the vertex geometry through the resident map scan
+
+The geometry array and cached verifier words lie after the histogram and
+before the hidden scratch. The pointer at the live length lies below the
+histogram. The exterior identity of each map therefore preserves the whole
+vertex frame through the deterministic list of actions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM DFS NodeArguments LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {w n : ℕ} {R : LeafArena.Regions} {data : Fin 10 → Word w}
+ {offset : Word w} {vals : Static 34 → Word w}
+local notation "G" => NativeFrame.frameBase R
+local notation "hidden" => ShrinkCallABI.hiddenBase R n
+
+/-- The exterior clause of a shrinking map preserves every word in the
+tree decoder's vertex frame, including all cached verifier operands. -/
+theorem VertexFrameData.after_map {saved out : Scratch w n}
+ (h : VertexFrameData R data offset vals saved) {t : ℕ}
+ (beforeHist : n < R.histBase) (labels : t ≤ R.histWords) (fits : hidden ≤ 2 ^ w)
+ (exterior : ∀ q : Word w, q.val < hidden → (q.val < R.histBase ∨ R.histBase + t ≤ q.val) →
+ rawScratch out q = rawScratch saved q) : VertexFrameData R data offset vals out := by
+ have hist : R.histBase + t ≤ G := Nat.add_le_add_left labels _
+ have cache : G ≤ R.cacheBase := R.hist_before
+ have endCache : R.cacheBase + 38 ≤ hidden := Nat.le_add_right ..
+ have atCell (q : ℕ) (lo : R.histBase + t ≤ q) (hi : q < hidden) :
+ rawScratch out (q : Word w) = rawScratch saved (q : Word w) := by
+ have val : (q : Word w).val = q := Nat.mod_eq_of_lt (hi.trans_le fits)
+ exact exterior (q : Word w) (by rwa [val]) (.inr (by rwa [val]))
+ apply h.transfer
+ · have ptr : (n : Word w).val < R.histBase := (Nat.mod_le ..).trans_lt beforeHist
+ apply exterior _ _ (.inl ptr)
+ omega
+ · intro j
+ apply atCell _ (hist.trans (Nat.le_add_right ..))
+ have := j.isLt
+ omega
+ · intro j
+ have small : j.offset < 38 := by cases j <;> simp [Static.offset]; omega
+ exact atCell _ ((hist.trans cache).trans (Nat.le_add_right ..))
+ ((Nat.add_lt_add_left small _).trans_le endCache)
+
+/-- Word-by-word transfer through the exact pure map scan. This induction
+uses the actual scratch returned by the preceding occurrence. -/
+theorem VertexFrameData.scan {t : ℕ} (actions : List (ResidentMapLoop.Exact.Action w n))
+ (node : Word w) (saved : Scratch w n) (frame : VertexFrameData R data offset vals saved)
+ (beforeHist : n < R.histBase) (labels : t ≤ R.histWords) (fits : hidden ≤ 2 ^ w)
+ (exterior : ∀ act ∈ actions, ∀ initial events next, act node initial = some (events, next) →
+ ∀ q : Word w, q.val < hidden → (q.val < R.histBase ∨ R.histBase + t ≤ q.val) →
+ rawScratch next q = rawScratch initial q)
+ {events : List (Event w)} {out : Scratch w n}
+ (run : ResidentMapLoop.Exact.scan node actions saved = some (events, out)) :
+ VertexFrameData R data offset vals out := by
+ induction actions generalizing saved events out with
+ | nil =>
+ have eqn := (Prod.mk.inj (Option.some.inj run)).2
+ exact eqn ▸ frame
+ | cons act actions ih =>
+ cases first : act node saved with
+ | none => simp [ResidentMapLoop.Exact.scan, first] at run
+ | some pair =>
+ obtain ⟨es, mid⟩ := pair
+ have step := frame.after_map beforeHist labels fits
+ (exterior act List.mem_cons_self saved es mid first)
+ cases rest : ResidentMapLoop.Exact.scan node actions mid with
+ | none => simp [ResidentMapLoop.Exact.scan, first, rest] at run
+ | some pair =>
+ obtain ⟨tail, final⟩ := pair
+ simp only [ResidentMapLoop.Exact.scan, first, rest, Option.some.injEq, Prod.mk.injEq] at run
+ exact run.2 ▸ ih mid step (fun a ha ↦ exterior a (List.mem_cons_of_mem _ ha)) rest
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkVertexImage.lean b/lean/OAI/Computability/VPVNP/PairShrinkVertexImage.lean
new file mode 100644
index 0000000000..d7dbda492c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkVertexImage.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairShrinkVertexStage
+import OAI.Computability.VPVNP.PairShrinkCallABI
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherImage
+import OAI.Computability.VPVNP.CompressorLevelCounts
+
+/-!
+# The fixed finite image of a shrinking vertex visit
+
+The block schedule fixes the old and new degree of every shrinking substep. At the
+selected substep the machine guesses the child packets and absorbed bits, selects the
+recorded layout, gathers the actual party fields, executes the selected matrix, and
+increments the private parameter histogram. Its only public bank is the terminal ABI.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkVertexImage
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression CompressorRecords
+open MotifConversion ShrinkMapImage
+
+/-- The old header and packed owner already occupy locator registers 11 and 7. The
+remaining map-control registers and its zero word have a separate interval. -/
+def mapRegisters : Registers 24 where
+ header := ⟨![11, 7, 14, 15, 16, 17, 18, 19, 20, 21, 22], by decide⟩
+ zero := 23
+ apart := by decide
+
+@[simp] theorem mapRegisters_level : mapRegisters.header 0 = 11 := rfl
+@[simp] theorem mapRegisters_owner : mapRegisters.header 1 = 7 := rfl
+@[simp] theorem mapRegisters_ordinal : mapRegisters.header 6 = 18 := rfl
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+
+/-- The six-party map handler family for this scheduled old degree and the global
+parameter-entry numbering. -/
+abbrev matrixFamily := ShrinkCallABI.family B (slotDegree S) (S.degreeExponent i.castSucc) ord
+
+/-- Both layout gathers use the actual old and new degree and the same live operands
+as the matrix writer. -/
+def gatherFamily : ShrinkGatherBank.Family (matrixFamily B ord i) where
+ a := S.degreeExponent i.castSucc
+ b := S.degreeExponent i.succ
+ operands _ := ShrinkCallABI.operands (slotDegree S)
+ node _ := ShrinkCallABI.node
+
+/-- The located native resident map handler, including its operand gathers and the locator
+embedding into the shared register bank. -/
+def maps : LocatedBody where
+ code := Registers.segmentWithGather (matrixFamily B ord i) (gatherFamily B ord i) mapRegisters
+ locator := (Fin.castAddEmb 10).trans
+ (Registers.gatherShared (matrixFamily B ord i) (gatherFamily B ord i))
+
+/-- A complete eleven-public-word shrinking segment, fixed across all visited levels and
+all input lengths. The caller supplies only the numbering of its fixed parameter entries. -/
+def shrinkSegment : Segment := ShrinkVertexStage.image B (maps B ord)
+
+/-- The installed selected map body includes the input reader, both layout branches, the
+gather loops, the matrix writer, and the actual rejecting opcode. -/
+theorem map_linked {p r w : ℕ} (M : Machine w p r 11) (pc : Fin (maps B ord i).code.count → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (maps B ord i).code.privateRegs ↪ Fin r) (done : Fin p)
+ (rows : ∀ a, M.code (pc a) = ((maps B ord i).code.row pc dfs saved reg done a).resize w) :
+ let F := matrixFamily B ord i
+ let G := gatherFamily B ord i
+ Registers.GatherLinked F G mapRegisters (pc ∘ Registers.gatherLocations F G)
+ dfs saved ((Registers.gatherShared F G).trans reg) ((Registers.gatherMatrix F G).trans reg)
+ ((Registers.gatherLocal F G).trans reg) (reg (Registers.layoutTemp F G)) done M := by
+ intro F G
+ apply Registers.gatherLinked
+ exact Registers.gatherSegment_rows F G mapRegisters dfs saved done pc reg M rows
+
+end PairSimulation.ShrinkVertexImage
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkVertexLinks.lean b/lean/OAI/Computability/VPVNP/PairShrinkVertexLinks.lean
new file mode 100644
index 0000000000..d252583c63
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkVertexLinks.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PairShrinkVertexEntry
+
+/-!
+# Installed component rows of the actual shrinking image
+
+The address and register maps below are computed from the single hosted segment.
+They recover the hidden-field code and gathered map code after the child scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkVertexImage
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression CompressorRecords
+open ShrinkMapImage VertexStagePrefix NodeArguments
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t : ℕ} (ord : B.Entry → Fin t) (i : Fin S.steps)
+
+/-- Input degree exponent at this elementary step of the block schedule. -/
+abbrev oldExponent := S.degreeExponent i.castSucc
+/-- Maximum number of hidden-field IDs reserved for a site's directory row at this old degree. -/
+abbrev hiddenStride := ShrinkResidentLayout.rowCapacity (oldExponent i) false
+/-- The resident map handler prefixed with the private histogram-base reload. -/
+abbrev mapReload := ShrinkMapReload.body (maps B ord i)
+/-- Instruction segment that guesses the hidden fields using the shrink block's selector width
+and the old degree's directory stride. -/
+abbrev hiddenCode := ShrinkHiddenGuess.Table.segment B.shrink.selectorBits (hiddenStride i)
+/-- The preparation that installs hidden-field guessing immediately ahead of the histogram
+reload and resident maps. -/
+abbrev hiddenPrep :=
+ ShrinkVertexStage.prepare B.shrink.selectorBits (hiddenStride i) (mapReload B ord i)
+/-- The located continuation entered after the old-child argument scan, consisting of
+hidden-field guessing, histogram reload, and resident maps. -/
+abbrev afterChildren :=
+ ShrinkVertexStage.withHidden B.shrink.selectorBits (hiddenStride i) (mapReload B ord i)
+/-- The child-scan preparation that links the input degree's child argument bank to the located
+hidden-field and map continuation. -/
+abbrev childPrep := childPreparation (oldExponent i) (afterChildren B ord i).code
+ (afterChildren B ord i).locator
+
+variable {p r w : ℕ} (M : Machine w p r 11) (pc : Fin (shrinkSegment B ord).count → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (shrinkSegment B ord).privateRegs ↪ Fin r)
+ (done : Fin p) (rows : ∀ a, M.code (pc a) =
+ ((shrinkSegment B ord).row pc dfs saved reg done a).resize w)
+
+/-- Translate instruction ordinals of this elementary shrink into program counters in the whole
+shrinking segment. -/
+abbrev activePC := LocatedBody.stagePC (active B ord) pc i
+/-- Embed this elementary shrink's private registers into the bank reserved for the whole
+shrinking segment. -/
+abbrev activeBank := LocatedBody.stageBank (active B ord) reg i
+
+/-- Program counters of the continuation after child preparation, including the hidden-field
+reader and the resident maps. -/
+abbrev afterChildPC := (childPrep B ord i).bodyPC (activePC B ord i pc)
+/-- Private registers of the continuation after the child scan, as embedded in the selected
+stage's bank. -/
+abbrev afterChildRegs := Preparation.bodyRegs (ChildCode.RegisterBank.segment (oldExponent i))
+ (afterChildren B ord i).code (activeBank B ord i reg)
+
+/-- Program-counter map of the hidden-field guessing phase inside the continuation reached
+after the child scan. -/
+abbrev hiddenPC := (hiddenPrep B ord i).phasePC (afterChildPC B ord i pc)
+/-- Register embedding used by the hidden-field guessing phase in the post-child continuation. -/
+abbrev hiddenRegs := Preparation.phaseRegs (hiddenCode B i) (mapReload B ord i).code
+ (afterChildRegs B ord i reg)
+
+/-- Program-counter map of the histogram reload and resident map body reached after
+hidden-field preparation. -/
+abbrev reloadPC := (hiddenPrep B ord i).bodyPC (afterChildPC B ord i pc)
+/-- Register embedding for the histogram reload and resident map continuation after the
+hidden-field scan. -/
+abbrev reloadRegs := Preparation.bodyRegs (hiddenCode B i) (mapReload B ord i).code
+ (afterChildRegs B ord i reg)
+
+/-- Program counters for the resident map body on the far side of its four-instruction
+histogram reload. -/
+abbrev matrixPC := Segment.rightPC (ShrinkMapReload.setup (maps B ord i)) (maps B ord i).code
+ (reloadPC B ord i pc)
+
+include rows in
+theorem after_child_rows (j : Fin (afterChildren B ord i).code.count) :
+ M.code (afterChildPC B ord i pc j) = ((afterChildren B ord i).code.row (afterChildPC B ord i pc)
+ dfs saved (afterChildRegs B ord i reg) done j).resize w :=
+ (child_rows (oldExponent i) (afterChildren B ord i).code (afterChildren B ord i).locator M
+ (activePC B ord i pc) dfs saved (activeBank B ord i reg) done
+ (active_rows B ord M pc dfs saved reg done rows i)).2.2.2 j
+
+include rows in
+theorem hidden_rows (j : Fin (hiddenCode B i).count) :
+ M.code (hiddenPC B ord i pc j) = ((hiddenCode B i).row (hiddenPC B ord i pc)
+ dfs saved (hiddenRegs B ord i reg)
+ ((reloadPC B ord i pc) (mapReload B ord i).code.entry) j).resize w :=
+ (ShrinkVertexStage.prepare_rows B.shrink.selectorBits (hiddenStride i) (mapReload B ord i)
+ M (afterChildPC B ord i pc) dfs saved (afterChildRegs B ord i reg) done
+ (after_child_rows B ord i M pc dfs saved reg done rows)).2.2.1 j
+
+include rows in
+theorem reload_rows (j : Fin (mapReload B ord i).code.count) :
+ M.code (reloadPC B ord i pc j) = ((mapReload B ord i).code.row (reloadPC B ord i pc)
+ dfs saved (reloadRegs B ord i reg) done j).resize w :=
+ (ShrinkVertexStage.prepare_rows B.shrink.selectorBits (hiddenStride i) (mapReload B ord i)
+ M (afterChildPC B ord i pc) dfs saved (afterChildRegs B ord i reg) done
+ (after_child_rows B ord i M pc dfs saved reg done rows)).2.2.2 j
+
+include rows in
+/-- The real role's map and party gather share these exact rows. -/
+theorem selected_map_rows (j : Fin (maps B ord i).code.count) :
+ M.code (matrixPC B ord i pc j) = ((maps B ord i).code.row (matrixPC B ord i pc)
+ dfs saved (reloadRegs B ord i reg) done j).resize w :=
+ (ShrinkMapReload.links (maps B ord i) M (reloadPC B ord i pc) dfs saved (reloadRegs B ord i reg)
+ done (reload_rows B ord i M pc dfs saved reg done rows)).2 j
+
+/-- The matrix and gather operands see the very same fourteen physical words that the
+locator populated before the selected child and hidden routines. -/
+theorem map_locator_shared (j : Fin 14) :
+ reloadRegs B ord i reg ((maps B ord i).locator j) =
+ LocatedBody.commonLocator (active B ord) reg j :=
+ active_locator B ord reg i j
+
+end PairSimulation.ShrinkVertexImage
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkVertexPlacement.lean b/lean/OAI/Computability/VPVNP/PairShrinkVertexPlacement.lean
new file mode 100644
index 0000000000..fbe141e176
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkVertexPlacement.lean
@@ -0,0 +1,50 @@
+import OAI.Computability.VPVNP.PairShrinkVertexLinks
+import OAI.Computability.VPVNP.PairVertexSiteSegments
+
+/-!
+# The shrinking role's labels and register frame in the terminal vertex image
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkVertexImage
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage Compression
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {t : ℕ} (ord : B.Entry → Fin t)
+ (geometry rootFields leaf refresh : Segment) {p r w : ℕ}
+
+/-- The vertex instruction segments for geometry, root fields, leaf processing, the scheduled
+shrinking program, and refresh. -/
+noncomputable abbrev vertexParts := segments geometry rootFields leaf (shrinkSegment B ord) refresh
+
+variable (A : VertexImage.Placement (vertexParts B ord geometry rootFields leaf refresh) p r)
+ (M : Machine w p r 11)
+
+theorem vertex_rows (h : VertexImage.Contains A M) (i : Fin (shrinkSegment B ord).count) :
+ M.code (A.stage .shrink i) = ((shrinkSegment B ord).row (A.stage .shrink) A.dfs A.saved
+ (A.localRegs .shrink) (A.dfsPC 3) i).resize w :=
+ stage_linked A M h .shrink i
+
+/-- The role can use its entire allocated register range while preserving the DFS bank. -/
+theorem vertex_dfs_apart (j : Fin 9) : A.dfs j ∉ Set.range (A.localRegs .shrink) := by
+ rintro ⟨i, h⟩
+ exact (A.reg.injective.ne (by simp) : A.localRegs .shrink i ≠ A.dfs j) h
+
+theorem vertex_saved_apart (j : Saved) : A.saved j ∉ Set.range (A.localRegs .shrink) := by
+ rintro ⟨i, h⟩
+ exact (A.reg.injective.ne (by simp) : A.localRegs .shrink i ≠ A.saved j) h
+
+/-- Any subroutine bank placed inside the shrinking segment enjoys the same separation. -/
+theorem vertex_subbank_apart {n : ℕ} (bank : Fin n ↪ Fin (shrinkSegment B ord).privateRegs)
+ (j : Fin 9) : A.dfs j ∉ Set.range (bank.trans (A.localRegs .shrink)) :=
+ fun ⟨i, h⟩ => vertex_dfs_apart B ord geometry rootFields leaf refresh A j ⟨bank i, h⟩
+
+end PairSimulation.ShrinkVertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkVertexStage.lean b/lean/OAI/Computability/VPVNP/PairShrinkVertexStage.lean
new file mode 100644
index 0000000000..bf0ca73c96
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkVertexStage.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.PairShrinkHiddenSegment
+import OAI.Computability.VPVNP.PairShrinkMapReload
+import OAI.Computability.VPVNP.CompressorShrinkResidentLayout
+import OAI.Computability.VPVNP.CompressionTemplates
+
+/-!
+# Child, absorbed-field, and map code in one shrinking stage
+
+The old level determines the child degree and the fixed capacity of its absorbed-field
+rows. After loading the hidden operands, the stage saves the actual hidden base in
+locator register eight, for the subsequent map's supply-half reads.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkVertexStage
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage VertexStagePrefix CompressorRecords Compression
+open scoped Fin.CommRing
+
+variable {p r w : ℕ}
+
+/-- Load the four hidden-field operands and cache the private field base for the map. -/
+def prepare (s t : ℕ) (B : LocatedBody) :
+ Preparation (ShrinkHiddenGuess.Table.segment s t) B.code where
+ count := VertexLevel.hiddenCount + 1
+ entry := 0
+ row pc dfs _ phaseRegs bodyRegs next :=
+ let locator := B.locator.trans bodyRegs
+ let inputs := (ShrinkHiddenGuess.Table.segmentInputs s t).trans phaseRegs
+ Fin.lastCases (.copy (locator 8) (inputs 1) next)
+ (VertexLevel.hiddenHandoff (pc ∘ Fin.castSucc) locator inputs (dfs 6)
+ (pc (Fin.last VertexLevel.hiddenCount)))
+
+/-- Place the hidden-field preparation in front of the supplied located body and lift its
+locator into the enlarged private register bank. -/
+def withHidden (s t : ℕ) (B : LocatedBody) : LocatedBody where
+ code := (prepare s t B).assemble
+ locator := B.locator.trans (Fin.castAddEmb (ShrinkHiddenGuess.Table.segment s t).privateRegs)
+
+/-- The selected stage reaches its map after scanning the child list and the hidden rows. -/
+def stage (degreeExponent selectors : ℕ) (maps : LocatedBody) : LocatedBody :=
+ (withHidden selectors (ShrinkResidentLayout.rowCapacity degreeExponent false)
+ (ShrinkMapReload.body maps)).withChildren degreeExponent
+
+/-- All stage constants are chosen before the live traversal. The modulo selector chooses
+the appropriate body for each occurrence of a shrinking level in the repeated schedule. -/
+def image {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (maps : Fin S.steps → LocatedBody) : Segment :=
+ LocatedBody.family fun i =>
+ stage (S.degreeExponent i.castSucc) B.shrink.selectorBits (maps i)
+
+theorem prepare_rows (s t : ℕ) (B : LocatedBody) (M : Machine w p r 11)
+ (pc : Fin (withHidden s t B).code.count → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : Saved ↪ Fin r) (reg : Fin (withHidden s t B).code.privateRegs ↪ Fin r)
+ (done : Fin p) (rows : ∀ i, M.code (pc i) =
+ ((withHidden s t B).code.row pc dfs saved reg done i).resize w) :
+ let X := prepare s t B
+ let H := ShrinkHiddenGuess.Table.segment s t
+ let ps := Preparation.phaseRegs H B.code reg
+ let bs := Preparation.bodyRegs H B.code reg
+ let inputs := (ShrinkHiddenGuess.Table.segmentInputs s t).trans ps
+ let locator := B.locator.trans bs
+ let pre := X.setupPC pc
+ (∀ i, M.code (pre i.castSucc) =
+ VertexLevel.hiddenHandoff (pre ∘ Fin.castSucc) locator inputs (dfs 6)
+ (pre (Fin.last VertexLevel.hiddenCount)) i) ∧
+ M.code (pre (Fin.last VertexLevel.hiddenCount)) =
+ .copy (locator 8) (inputs 1) (X.phasePC pc H.entry) ∧
+ (∀ i, M.code (X.phasePC pc i) =
+ (H.row (X.phasePC pc) dfs saved ps (X.bodyPC pc B.code.entry) i).resize w) ∧
+ (∀ i, M.code (X.bodyPC pc i) = (B.code.row (X.bodyPC pc) dfs saved bs done i).resize w) := by
+ let X := prepare s t B
+ obtain ⟨pre, phase, body⟩ := X.links M pc dfs saved reg done rows
+ refine ⟨fun i => ?_, ?_, phase, body⟩
+ · apply (pre i.castSucc).trans
+ simp only [X, prepare, Fin.lastCases_castSucc, VertexLevel.resize_hiddenHandoff]
+ · apply (pre (Fin.last VertexLevel.hiddenCount)).trans
+ simp only [X, prepare, Fin.lastCases_last, Instr.resize]
+
+end PairSimulation.ShrinkVertexStage
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairShrinkVisitFootprint.lean b/lean/OAI/Computability/VPVNP/PairShrinkVisitFootprint.lean
new file mode 100644
index 0000000000..19d519839a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairShrinkVisitFootprint.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.PairShrinkNodeStageCost
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-!
+# Read-only support of a complete shrinking vertex visit
+
+A successful visit follows the child, absorbed-field and map readers on the
+scratch and tape returned by their predecessors. The union of their actual
+read domains bounds the chronological trace even if a later DFS visit fails.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM DFS Compression CompressorRecords CompressorRecords.SourceTransport
+open NodeArguments NodeArguments.ChildScan ShrinkHiddenGuess
+
+/-- Every external memory access in the trace is a read at an address satisfying `allow`. -/
+abbrev TraceSupport {w : ℕ} (allow : ℕ → Prop) (es : List (Event w)) : Prop :=
+ Reads allow es ∧ Writes (fun _ ↦ False) es
+
+theorem TraceSupport.append {w : ℕ} {allow : ℕ → Prop} {a b : List (Event w)}
+ (first : TraceSupport allow a) (last : TraceSupport allow b) : TraceSupport allow (a ++ b) :=
+ ⟨fun i v h ↦ (List.mem_append.mp h).elim (first.1 i v) (last.1 i v),
+ fun i v h ↦ (List.mem_append.mp h).elim (first.2 i v) (last.2 i v)⟩
+
+theorem TraceSupport.memory {w : ℕ} {allow : ℕ → Prop} {es : List (Event w)}
+ (h : TraceSupport allow es) (m : Memory w) : after m es = m :=
+ funext fun _ ↦ after_outside m h.2 id
+
+variable {w n a g : ℕ} {X : State a g} (arena : Arena) (inc : IncidenceDirectory w)
+ (m : Memory w) (older cap : ℕ) (desc : Word w → ChildArguments.Descriptor w X)
+ (args : List (Child X) → Args w) (seed : List (Child X) → List Row)
+ (maps : List (Child X) → List Row → List (ResidentMapLoop.Exact.Action w n))
+ (first : Setup w n) (second : List (Child X) → Setup w n)
+ (third : List (Child X) → List Row → Setup w n) (node : Word w) (allow : ℕ → Prop)
+
+/-- Only readers that the native visit reaches contribute to the footprint. -/
+theorem visit_footprint (saved : Scratch w n) (bits tail : List Bool) (job : VisitPath w n)
+ (entry : TraceSupport allow (first.trace node saved))
+ (child : ∀ c rest, ChildArguments.reader arena inc m older cap desc node
+ (first.updated node saved) bits = some (c, rest) → TraceSupport allow c.trace)
+ (hiddenSetup : ∀ xs s, TraceSupport allow ((second xs).trace node s))
+ (hidden : ∀ xs (s : Scratch w n) b out rem,
+ hiddenReader (args xs) m (seed xs) node s b = some (out, rem) →
+ TraceSupport allow out.trace)
+ (mapSetup : ∀ xs hs s, TraceSupport allow ((third xs hs).trace node s))
+ (scan : ∀ xs hs s trace final,
+ ResidentMapLoop.Exact.scan node (maps xs hs) s = some (trace, final) →
+ TraceSupport allow trace)
+ (hit : (hook (visitReader arena inc m older cap desc args seed maps first second third)).read
+ node saved bits = some (job, tail)) : TraceSupport allow job.trace := by
+ obtain ⟨⟨out, rest⟩, found, eqn⟩ := Option.map_eq_some_iff.mp hit
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj eqn
+ obtain ⟨c, middle, h, final, trace, childRead, hiddenRead, scanned, _, _, _, events⟩ :=
+ ShrinkNodeCost.visit_trace_reached arena inc m older cap desc args seed maps first second third
+ node saved bits rest out found
+ have childTrace := congrArg Outcome.trace
+ (ChildArguments.reader_some arena inc m older cap desc childRead).2.1
+ have hiddenTrace := (ShrinkNodeCost.hidden_trace (args c.value) m (seed c.value) node
+ ((second c.value).updated node c.updated) middle rest h hiddenRead).1
+ change TraceSupport allow out.trace
+ rw [events, ← hiddenTrace]
+ have ch : TraceSupport allow (ChildHeader.events m node (desc node).directoryBase ++
+ ChildScan.events X inc m (desc node).source c.value) :=
+ (congrArg (TraceSupport allow) childTrace).mp (child c middle childRead)
+ have throughChild := (entry.append ch).append (hiddenSetup c.value c.updated)
+ have throughHidden := throughChild.append (hidden _ _ _ _ _ hiddenRead)
+ exact (throughHidden.append (mapSetup c.value h.value h.updated)).append (scan _ _ _ _ _ scanned)
+
+end PairSimulation.ShrinkRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationAnchorClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationAnchorClock.lean
new file mode 100644
index 0000000000..37b4420ee5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationAnchorClock.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.PairSimulationAnchorDecode
+
+/-!
+# Exact native clock of a successful anchor scan
+
+The descending loop visits each validated selector once. For each copy
+the cost includes its preparation, padded field read, lookup and store.
+The terminating cursor comparison takes one more instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.AnchorDecode.Program
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM MotifEntry
+open scoped Fin.CommRing
+open private iteration step_at from OAI.Computability.VPVNP.PairSimulationAnchorDecode
+
+variable {X : Type*} {w p r k b payload u : ℕ} (P : Program X p r k)
+
+/-- Exact cost of a single successful copy, including its ordinal store. -/
+def visitTicks (code : X ↪ Word b) (x : X) :=
+ 5 + ((6 * b + 1) + MapLookup.selectorTicks code (code x) P.xs)
+
+/-- All copy clocks and the final empty-loop guard. -/
+def successTicks (code : X ↪ Word b) (θ : Fin u → X) :=
+ (∑ i, P.visitTicks code (θ i)) + 1
+
+theorem successTicks_le (code : X ↪ Word b) (θ : Fin u → X) :
+ P.successTicks code θ ≤ P.visitCap b * u + 1 := by
+ unfold successTicks
+ apply Nat.add_le_add_right
+ calc
+ ∑ i, P.visitTicks code (θ i) ≤ ∑ _ : Fin u, P.visitCap b := by
+ apply Finset.sum_le_sum
+ intro i _
+ have bound := MapLookup.selectorTicks_le code (code (θ i)) P.xs
+ unfold visitTicks visitCap
+ omega
+ _ = _ := by simp [Nat.mul_comm]
+
+variable {P} {M : Machine w p r k}
+
+private theorem partial_success (link : P.Linked M) (fits : b ≤ w) (code : X ↪ Word b)
+ (hk : ∀ x, M.publicData (P.key x) = MapLookup.widen fits (code x))
+ (bits : Fin (payload + u * b) → Bool) (base dest n : ℕ) (hn : n ≤ u)
+ (c : Config w p r) (ready : P.Ready bits base dest n c)
+ (hi : base + (payload + u * b) < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : base + (payload + u * b) ≤ dest ∨ dest + u ≤ base)
+ (θ : Fin u → X) (valid : ∀ i, decode P.xs code (readTag bits i) = some (θ i)) :
+ ∃ d, Prefix M c (List.replicate (P.successTicks code (θ ∘ Fin.castLE hn)) .tick) d ∧
+ P.Frame dest n c d ∧ d.pc = P.done ∧
+ ∀ i : Fin u, i.val < n →
+ d.privateMem ((dest + i.val : ℕ) : Word w) = M.publicData (P.name (θ i)) := by
+ induction n generalizing c with
+ | zero =>
+ let d := {c with pc := P.done}
+ have eq : c.reg (P.reg 6) = c.reg (P.reg 7) := ready.output.trans ready.stop.symm
+ have step : M.program.step c = .localStep d := by
+ rw [step_at link 0 ready.pc]
+ simp [instruction, Instr.run, eq, d]
+ have time : P.successTicks code (θ ∘ Fin.castLE hn) = 1 := by simp [successTicks]
+ rw [time]
+ exact ⟨d, .tick step (.nil _), ⟨fun _ _ _ _ _ _ ↦ rfl, fun _ _ ↦ rfl, rfl⟩,
+ rfl, fun i h ↦ (Nat.not_lt_zero i.val h).elim⟩
+ | succ n ih =>
+ let i : Fin u := ⟨n,hn⟩
+ obtain ⟨t, mid, _, pre, frame, result⟩ :=
+ iteration link fits code hk bits base dest i c ready hi hd sep
+ rcases result with ⟨invalid,_⟩ | ⟨x,ok,next,value,clock⟩
+ · simp [valid] at invalid
+ have xeq : x = θ i := Option.some.inj (ok.symm.trans (valid i))
+ subst x
+ have tag : code (θ i) = readTag bits i := by simpa using List.find?_some (valid i)
+ have tick : t = P.visitTicks code (θ i) := by rw [clock, ← tag]; rfl
+ obtain ⟨d, tail, frame', done, stored⟩ := ih (by omega) mid next
+ have clockStep : P.successTicks code (θ ∘ Fin.castLE hn) =
+ t + P.successTicks code (θ ∘ Fin.castLE (show n ≤ u by omega)) := by
+ unfold successTicks
+ rw [Fin.sum_univ_castSucc, tick]
+ change (∑ j : Fin n, P.visitTicks code (θ ⟨j.val, _⟩)) + P.visitTicks code (θ i) + 1 =
+ P.visitTicks code (θ i) + ((∑ j : Fin n, P.visitTicks code (θ ⟨j.val, _⟩)) + 1)
+ omega
+ rw [clockStep,List.replicate_add]
+ refine ⟨d, pre.append tail, ?_, done, ?_⟩
+ · refine ⟨fun a h₀ h₁ h₂ h₅ h₆ ↦ (frame'.regs a h₀ h₁ h₂ h₅ h₆).trans
+ (frame.regs a h₀ h₁ h₂ h₅ h₆), ?_, frame'.persistent.trans frame.persistent⟩
+ intro a ha
+ exact (frame'.memory a (by omega)).trans
+ (frame.memory a (by change a.val < dest + n ∨ dest + n + 1 ≤ a.val; omega))
+ · intro j hj
+ by_cases eq : j = i
+ · subst j
+ refine (frame'.memory _ (Or.inr ?_)).trans value
+ change dest + n ≤ (dest + n) % (2 ^ w)
+ rw [Nat.mod_eq_of_lt (by omega)]
+ · have : j.val ≠ n := fun h ↦ eq (Fin.ext h)
+ exact stored j (by omega)
+
+/-- Successful anchor decoding takes the same computed number of ticks
+for every compatible entry configuration. It returns all validated
+selector ordinals at their designated private addresses. -/
+theorem native_success (link : P.Linked M) (fits : b ≤ w) (code : X ↪ Word b)
+ (hk : ∀ x, M.publicData (P.key x) = MapLookup.widen fits (code x))
+ (bits : Fin (payload + u * b) → Bool) (base dest : ℕ)
+ (c : Config w p r) (ready : P.Ready bits base dest u c)
+ (hi : base + (payload + u * b) < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : base + (payload + u * b) ≤ dest ∨ dest + u ≤ base)
+ (θ : Fin u → X) (ok : selectors? P.xs code (readTag bits) = some θ) :
+ ∃ d, Prefix M c (List.replicate (P.successTicks code θ) .tick) d ∧
+ P.Frame dest u c d ∧ d.pc = P.done ∧
+ ∀ i : Fin u, d.privateMem ((dest + i.val : ℕ) : Word w) = M.publicData (P.name (θ i)) := by
+ have valid (i : Fin u) : decode P.xs code (readTag bits i) = some (θ i) := by
+ simp only [selectors?, Vector.getElem_ofFn] at ok
+ split at ok
+ · cases ok
+ exact (Option.some_get _).symm
+ · cases ok
+ obtain ⟨d, run, frame, pc, val⟩ :=
+ partial_success link fits code hk bits base dest u le_rfl c ready hi hd sep θ valid
+ exact ⟨d, run, frame, pc, fun i ↦ val i i.isLt⟩
+
+end PairSimulation.AnchorDecode.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationAnchorDecode.lean b/lean/OAI/Computability/VPVNP/PairSimulationAnchorDecode.lean
new file mode 100644
index 0000000000..24826a34cd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationAnchorDecode.lean
@@ -0,0 +1,335 @@
+import OAI.Computability.VPVNP.PairSimulationSelectorLookupClock
+
+/-!
+# Native scan of the anchor's selector sequence
+
+A vertex call reads selectors from the high end of the anchor wire and
+writes each decoded ordinal in its original copy position. Its control
+table is independent of the repetition count. The output cells may be on
+either side of the input slice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.AnchorDecode
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM MotifEntry
+open scoped Fin.CommRing
+
+variable {X : Type*} {w p r k b payload u : ℕ}
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+
+private theorem val_word {n : ℕ} (h : n < 2 ^ w) : (word w n).val = n := Nat.mod_eq_of_lt h
+
+/-- The first six registers of the loop belong to the padded field reader. -/
+def fieldRegs (reg : Fin 9 ↪ Fin r) : Fin 6 ↪ Fin r :=
+ (Fin.castLEEmb (by decide : 6 ≤ 9)).trans reg
+
+/-- Registers 6 and 7 are the descending output cursor and its lower bound.
+Register 8 contains the fixed selector width. -/
+structure Program (X : Type*) (p r k : ℕ) where
+ /-- Selectors in the order tested by the lookup. -/
+ xs : List X
+ /-- Public port of each selector's encoded tag. -/
+ key : X → Fin k
+ /-- Public port of the ordinal stored after a successful lookup. -/
+ name : X → Fin k
+ /-- Nine registers for the reader, cursor pair and selector width. -/
+ reg : Fin 9 ↪ Fin r
+ /-- Control locations for the five outer loop instructions. -/
+ pc : Fin 5 → Fin p
+ /-- Control locations of the padded bit-field reader. -/
+ reader : Fin 7 → Fin p
+ /-- Physical location of each instruction in the fixed lookup table. -/
+ label : (ReadDecode.selectorFlow xs key name (fieldRegs reg) (reg 0)).Label → Fin p
+ /-- Continuation after all selectors have been written. -/
+ done : Fin p
+ /-- Failure continuation for an unused selector code. -/
+ bad : Fin p
+
+namespace Program
+
+variable (P : Program X p r k)
+
+/-- Lookup flow for the field reader's raw tag. -/
+def selector := ReadDecode.selectorFlow P.xs P.key P.name (fieldRegs P.reg) (P.reg 0)
+
+/-- Test the cursor, prepare the descending field read, and store its ordinal. -/
+def instruction : Fin 5 → Instr w p r k :=
+ ![.jumpEq (P.reg 6) (P.reg 7) P.done (P.pc 1),
+ .binary .sub (P.reg 6) (P.reg 6) (P.reg 4) (P.pc 2),
+ .binary .sub (P.reg 2) (P.reg 1) (P.reg 8) (P.pc 3),
+ .constant (P.reg 0) 0 (P.reader 0), .storePrivate (P.reg 6) (P.reg 0) (P.pc 0)]
+
+theorem resize_instruction (i : Fin 5) :
+ (P.instruction (w := 1) i).resize w = P.instruction i := by fin_cases i <;> rfl
+
+/-- All links for the five outer rows, the padded reader and the fixed selector table. -/
+structure Linked (M : Machine w p r k) : Prop where
+ outer : ∀ i, M.code (P.pc i) = P.instruction i
+ reader : FieldRead.Linked M P.reader (fieldRegs P.reg) (P.label P.selector.entry)
+ lookup : Flow.Linked M P.selector P.label (P.pc 4) P.bad
+
+/-- Input register and private slice invariant with n remaining copies. -/
+structure Ready (bits : Fin (payload + u * b) → Bool) (base dest n : ℕ)
+ (c : Config w p r) : Prop where
+ pc : c.pc = P.pc 0
+ cursor : c.reg (P.reg 1) = word w (base + (payload + b * n))
+ dataEnd : c.reg (P.reg 3) = word w (base + (payload + u * b))
+ one : c.reg (P.reg 4) = 1
+ output : c.reg (P.reg 6) = word w (dest + n)
+ stop : c.reg (P.reg 7) = word w dest
+ width : c.reg (P.reg 8) = word w b
+ data : ∀ i : Fin (payload + u * b),
+ c.privateMem (word w (base + i.val)) = encodeBit w (bits i)
+
+/-- Only the designated scratch registers and output interval may change. -/
+structure Frame (dest n : ℕ) (c d : Config w p r) : Prop where
+ regs : ∀ a, a ≠ P.reg 0 → a ≠ P.reg 1 → a ≠ P.reg 2 → a ≠ P.reg 5 → a ≠ P.reg 6 →
+ d.reg a = c.reg a
+ memory : ∀ a : Word w, a.val < dest ∨ dest + n ≤ a.val → d.privateMem a = c.privateMem a
+ persistent : d.persistent = c.persistent
+
+/-- The partial scan either decoded all remaining positions, or hit a
+particular unused selector code. -/
+def Outcome (M : Machine w p r k) (code : X ↪ Word b) (bits : Fin (payload + u * b) → Bool)
+ (dest n : ℕ) (d : Config w p r) : Prop :=
+ (d.pc = P.done ∧ ∀ i : Fin u, i.val < n → ∃ x,
+ decode P.xs code (readTag bits i) = some x ∧
+ d.privateMem (word w (dest + i.val)) = M.publicData (P.name x)) ∨
+ (d.pc = P.bad ∧ ∃ i : Fin u, i.val < n ∧ decode P.xs code (readTag bits i) = none)
+
+variable {P} {M : Machine w p r k}
+
+private theorem step_at (link : P.Linked M) (i : Fin 5) {c : Config w p r} (hc : c.pc = P.pc i) :
+ M.program.step c = (P.instruction i).run M.publicData c := by
+ simp [Machine.program, hc, link.outer i]
+
+private theorem prepare (link : P.Linked M) (bits : Fin (payload + u * b) → Bool)
+ (base dest n : ℕ) (c : Config w p r) (h : P.Ready bits base dest (n + 1) c)
+ (hd : dest + (n + 1) < 2 ^ w) :
+ ∃ start, Prefix M c (List.replicate 4 .tick) start ∧ start.pc = P.reader 0 ∧
+ start.reg (P.reg 0) = 0 ∧ start.reg (P.reg 2) = word w (base + (payload + b * n)) ∧
+ start.reg (P.reg 6) = word w (dest + n) ∧
+ (∀ a, a ≠ P.reg 0 → a ≠ P.reg 2 → a ≠ P.reg 6 → start.reg a = c.reg a) ∧
+ start.privateMem = c.privateMem ∧ start.persistent = c.persistent := by
+ let c₁ := {c with pc := P.pc 1}
+ let c₂ := c₁.put (P.pc 2) (P.reg 6) (word w (dest + n))
+ let c₃ := c₂.put (P.pc 3) (P.reg 2) (word w (base + (payload + b * n)))
+ let start := c₃.put (P.reader 0) (P.reg 0) 0
+ have ne : c.reg (P.reg 6) ≠ c.reg (P.reg 7) := by
+ rw [h.output, h.stop]
+ intro he
+ have hv := congrArg Fin.val he
+ rw [val_word hd, val_word (by omega : dest < 2 ^ w)] at hv
+ omega
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step_at link 0 h.pc]
+ simp [instruction, Instr.run, ne, c₁]
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at link 1 rfl]
+ change CallAction.localStep (c₁.put (P.pc 2) (P.reg 6) (c.reg (P.reg 6) - c.reg (P.reg 4))) = _
+ simp [c₂, h.output, h.one, word, ← add_assoc]
+ have s₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step_at link 2 rfl]
+ change CallAction.localStep
+ (c₂.put (P.pc 3) (P.reg 2) (c₂.reg (P.reg 1) - c₂.reg (P.reg 8))) = _
+ simp [c₃, c₂, c₁, Config.put, h.cursor, h.width, Nat.mul_succ, word, ← add_assoc]
+ have s₃ : M.program.step c₃ = .localStep start := step_at link 3 rfl
+ refine ⟨_, .tick s₀ (.tick s₁ (.tick s₂ (.tick s₃ (.nil _)))), rfl, by simp [start],
+ by simp [start, c₃, Config.put], by simp [start, c₃, c₂, Config.put], ?_, rfl, rfl⟩
+ intro a h₀ h₂ h₆
+ simp [start, c₃, c₂, c₁, Config.put, Function.update_of_ne, h₀, h₂, h₆]
+
+/-- Native bound for the control, reading, decoding and store of one anchor copy. -/
+def visitCap (P : Program X p r k) (b : ℕ) := (6 * b + 1) + (2 * P.xs.length + 1) + 5
+
+private theorem iteration (link : P.Linked M) (fits : b ≤ w) (code : X ↪ Word b)
+ (hk : ∀ x, M.publicData (P.key x) = MapLookup.widen fits (code x))
+ (bits : Fin (payload + u * b) → Bool) (base dest : ℕ) (i : Fin u)
+ (c : Config w p r) (ready : P.Ready bits base dest (i.val + 1) c)
+ (hi : base + (payload + u * b) < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : base + (payload + u * b) ≤ dest ∨ dest + u ≤ base) :
+ ∃ ticks d, ticks ≤ P.visitCap b ∧ Prefix M c (List.replicate ticks .tick) d ∧
+ P.Frame (dest + i.val) 1 c d ∧
+ ((decode P.xs code (readTag bits i) = none ∧ d.pc = P.bad) ∨
+ (∃ x, decode P.xs code (readTag bits i) = some x ∧ P.Ready bits base dest i.val d ∧
+ d.privateMem (word w (dest + i.val)) = M.publicData (P.name x) ∧
+ ticks = 5 + ((6*b+1) + MapLookup.selectorTicks code (readTag bits i) P.xs))) := by
+ have hit := i.isLt
+ obtain ⟨start, prep, hs, hz, hl, ho, rest, hm, hp⟩ :=
+ prepare link bits base dest i.val c ready (by omega)
+ let fr := fieldRegs P.reg
+ have hh : start.reg (fr 1) = word w (base + (payload + b * i.val) + b) := by
+ change start.reg (P.reg 1) = _
+ rw [rest, ready.cursor, Nat.mul_succ, Nat.add_assoc, Nat.add_assoc] <;> simp
+ have de : start.reg (fr 3) = word w (base + (payload + u * b)) := by
+ change start.reg (P.reg 3) = _
+ rw [rest, ready.dataEnd] <;> simp
+ have one : start.reg (fr 4) = 1 := by
+ change start.reg (P.reg 4) = _
+ rw [rest, ready.one] <;> simp
+ let t := (6*b+1) + MapLookup.selectorTicks code (readTag bits i) P.xs
+ have bound : t ≤ (6*b+1) + (2*P.xs.length+1) :=
+ Nat.add_le_add_left (MapLookup.selectorTicks_le ..) _
+ obtain ⟨mid, run, exit, cur, keep, mem, pers⟩ :=
+ ReadDecode.native_tag_exact M P.reader fr (P.reg 0) (P.reg.injective.ne (by decide))
+ P.xs code P.key P.name fits hk P.label (P.pc 4) P.bad link.reader link.lookup
+ bits base i start hs hi hz hh hl de one (hm ▸ ready.data)
+ have pre : Prefix M c (List.replicate (4 + t) .tick) mid := by
+ rw [List.replicate_add]
+ exact prep.append run
+ have regKeep (a : Fin r) (h₀ : a ≠ P.reg 0) (h₁ : a ≠ P.reg 1)
+ (h₂ : a ≠ P.reg 2) (h₅ : a ≠ P.reg 5) (h₆ : a ≠ P.reg 6) : mid.reg a = c.reg a :=
+ (keep a h₀ h₁ h₅ h₀).trans (rest a h₀ h₂ h₆)
+ have memEq := mem.trans hm
+ have perEq := pers.trans hp
+ cases hx : decode P.xs code (readTag bits i) with
+ | none =>
+ rw [hx] at exit
+ exact ⟨_, _, by unfold visitCap; omega, pre,
+ ⟨regKeep, fun a _ ↦ congrFun memEq a, perEq⟩, Or.inl ⟨rfl, exit⟩⟩
+ | some x =>
+ rw [hx] at exit
+ obtain ⟨pcStore, ordinal⟩ := exit
+ have addr : mid.reg (P.reg 6) = word w (dest + i.val) :=
+ (keep _ (P.reg.injective.ne (by decide)) (P.reg.injective.ne (by decide))
+ (P.reg.injective.ne (by decide)) (P.reg.injective.ne (by decide))).trans ho
+ let d := mid.store (P.pc 0) (word w (dest + i.val)) (M.publicData (P.name x))
+ have store : M.program.step mid = .localStep d := by
+ rw [step_at link 4 pcStore]
+ change CallAction.localStep (mid.store (P.pc 0) (mid.reg (P.reg 6)) (mid.reg (P.reg 0))) = _
+ rw [addr, ordinal]
+ have away (a : Word w) (ha : a.val < dest + i.val ∨ dest + i.val + 1 ≤ a.val) :
+ d.privateMem a = c.privateMem a := by
+ have ha' : a ≠ word w (dest + i.val) := by
+ intro he
+ have hv := congrArg Fin.val he
+ rw [val_word (by omega : dest + i.val < 2 ^ w)] at hv
+ omega
+ exact (Config.store_other mid (P.pc 0) (word w (dest + i.val)) a _ ha').trans
+ (congrFun memEq a)
+ refine ⟨4 + t + 1, d, by unfold visitCap; omega, ?_, ⟨regKeep, away, perEq⟩,
+ Or.inr ⟨x, rfl, ?_, Config.store_same .., by unfold t; omega⟩⟩
+ · rw [List.replicate_add]
+ exact pre.append (.tick store (.nil _))
+ · refine ⟨rfl, cur, ?_, ?_, addr, ?_, ?_, ?_⟩
+ · exact (regKeep _ (by simp) (by simp) (by simp) (by simp) (by simp)).trans ready.dataEnd
+ · exact (regKeep _ (by simp) (by simp) (by simp) (by simp) (by simp)).trans ready.one
+ · exact (regKeep _ (by simp) (by simp) (by simp) (by simp) (by simp)).trans ready.stop
+ · exact (regKeep _ (by simp) (by simp) (by simp) (by simp) (by simp)).trans ready.width
+ · intro j
+ have hj := j.isLt
+ have hval : (word w (base + j.val)).val = base + j.val := val_word (by omega)
+ exact (away _ (by rw [hval]; omega)).trans (ready.data j)
+
+/-- The physical loop scans the remaining n slots. A successful suffix is
+kept in its original positions while the lower-index slots are filled. -/
+theorem loop (link : P.Linked M) (fits : b ≤ w) (code : X ↪ Word b)
+ (hk : ∀ x, M.publicData (P.key x) = MapLookup.widen fits (code x))
+ (bits : Fin (payload + u * b) → Bool) (base dest n : ℕ) (hn : n ≤ u)
+ (c : Config w p r) (ready : P.Ready bits base dest n c)
+ (hi : base + (payload + u * b) < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : base + (payload + u * b) ≤ dest ∨ dest + u ≤ base) :
+ ∃ ticks d, ticks ≤ P.visitCap b * n + 1 ∧ Prefix M c (List.replicate ticks .tick) d ∧
+ P.Frame dest n c d ∧ P.Outcome M code bits dest n d := by
+ induction n generalizing c with
+ | zero =>
+ let d := {c with pc := P.done}
+ have eq : c.reg (P.reg 6) = c.reg (P.reg 7) := ready.output.trans ready.stop.symm
+ have hs : M.program.step c = .localStep d := by
+ rw [step_at link 0 ready.pc]
+ simp [instruction, Instr.run, eq, d]
+ exact ⟨1, d, by simp, .tick hs (.nil _), ⟨fun _ _ _ _ _ _ ↦ rfl, fun _ _ ↦ rfl, rfl⟩,
+ Or.inl ⟨rfl, fun i h ↦ (Nat.not_lt_zero i.val h).elim⟩⟩
+ | succ n ih =>
+ let i : Fin u := ⟨n, hn⟩
+ obtain ⟨t, mid, bound, pre, frame, result⟩ :=
+ iteration link fits code hk bits base dest i c ready hi hd sep
+ rcases result with ⟨invalid, bad⟩ | ⟨x, ok, next, value, _⟩
+ · refine ⟨t, mid, ?_, pre, ⟨frame.regs, ?_, frame.persistent⟩,
+ Or.inr ⟨bad, i, by simp [i], invalid⟩⟩
+ · rw [Nat.mul_succ]
+ omega
+ · intro a ha
+ apply frame.memory
+ change a.val < dest + n ∨ dest + n + 1 ≤ a.val
+ omega
+ · obtain ⟨s, d, budget, tail, frame', result'⟩ := ih (by omega) mid next
+ refine ⟨t + s, d, ?_, ?_, ?_, ?_⟩
+ · rw [Nat.mul_succ]
+ omega
+ · rw [List.replicate_add]
+ exact pre.append tail
+ · refine ⟨fun a h₀ h₁ h₂ h₅ h₆ ↦ (frame'.regs a h₀ h₁ h₂ h₅ h₆).trans
+ (frame.regs a h₀ h₁ h₂ h₅ h₆), ?_, frame'.persistent.trans frame.persistent⟩
+ intro a ha
+ exact (frame'.memory a (by omega)).trans
+ (frame.memory a (by change a.val < dest + n ∨ dest + n + 1 ≤ a.val; omega))
+ · rcases result' with ⟨done, values⟩ | ⟨bad, j, hj, invalid⟩
+ · refine Or.inl ⟨done, fun j hj ↦ ?_⟩
+ by_cases he : j = i
+ · subst j
+ refine ⟨x, ok, (frame'.memory _ (Or.inr ?_)).trans value⟩
+ rw [val_word (by change dest + n < 2 ^ w; omega)]
+ · have hj' : j.val ≠ n := fun h ↦ he (Fin.ext h)
+ exact values j (by omega)
+ · exact Or.inr ⟨bad, j, by omega, invalid⟩
+
+/-- Every decoded ordinal is available at dest+i when the complete anchor
+sequence is valid. An unused code transfers control to the bad exit. The
+cap also holds for a rejection partway through the scan. -/
+theorem native (link : P.Linked M) (fits : b ≤ w) (code : X ↪ Word b)
+ (hk : ∀ x, M.publicData (P.key x) = MapLookup.widen fits (code x))
+ (bits : Fin (payload + u * b) → Bool) (base dest : ℕ)
+ (c : Config w p r) (ready : P.Ready bits base dest u c)
+ (hi : base + (payload + u * b) < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : base + (payload + u * b) ≤ dest ∨ dest + u ≤ base) :
+ ∃ ticks d, ticks ≤ P.visitCap b * u + 1 ∧ Prefix M c (List.replicate ticks .tick) d ∧
+ P.Frame dest u c d ∧
+ (match selectors? P.xs code (readTag bits) with
+ | none => d.pc = P.bad
+ | some θ => d.pc = P.done ∧
+ ∀ i, d.privateMem (word w (dest + i.val)) = M.publicData (P.name (θ i))) := by
+ obtain ⟨t, d, bound, pre, frame, result⟩ :=
+ loop link fits code hk bits base dest u le_rfl c ready hi hd sep
+ refine ⟨t, d, bound, pre, frame, ?_⟩
+ rcases result with ⟨done, readback⟩ | ⟨bad, i, _, invalid⟩
+ · choose θ dec val using fun i : Fin u ↦ readback i i.isLt
+ have hs : selectors? P.xs code (readTag bits) = some θ := by
+ simp [selectors?, Vector.getElem_ofFn, dec]
+ rw [hs]
+ exact ⟨done, val⟩
+ · have hs : selectors? P.xs code (readTag bits) = none := by
+ simp only [selectors?, Vector.getElem_ofFn]
+ apply dite_eq_right
+ intro h
+ have hh := h i
+ simp [invalid] at hh
+ rw [hs]
+ exact bad
+
+/-- An invalid sequence rejects the genuine interpreter on every branch
+stream, for every amount of fuel. -/
+theorem native_reject (link : P.Linked M) (fits : b ≤ w) (code : X ↪ Word b)
+ (hk : ∀ x, M.publicData (P.key x) = MapLookup.widen fits (code x))
+ (bits : Fin (payload + u * b) → Bool) (base dest : ℕ)
+ (c : Config w p r) (ready : P.Ready bits base dest u c)
+ (hi : base + (payload + u * b) < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : base + (payload + u * b) ≤ dest ∨ dest + u ≤ base)
+ (invalid : selectors? P.xs code (readTag bits) = none) (hb : M.code P.bad = .reject)
+ (fuel : ℕ) (mem : Memory w) (bs : List Bool) : execute M.program fuel c mem bs = none := by
+ obtain ⟨_, _, _, pre, _, endPC⟩ := native link fits code hk bits base dest c ready hi hd sep
+ rw [invalid] at endPC
+ exact MapLookup.reject_after_ticks pre (fun e he ↦ List.eq_of_mem_replicate he)
+ (endPC ▸ hb) fuel mem bs
+
+end Program
+end PairSimulation.AnchorDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationAssembly.lean b/lean/OAI/Computability/VPVNP/PairSimulationAssembly.lean
new file mode 100644
index 0000000000..5b785390dd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationAssembly.lean
@@ -0,0 +1,330 @@
+import OAI.Computability.VPVNP.PairSimulationHistoryBounds
+import OAI.Computability.VPVNP.CompressedRAMMonomials
+import OAI.Computability.VPVNP.CompressorShrinkMotifOrder
+
+/-!
+# Binary readers for the repeated RAM compressor
+
+The branch selectors read the admitted payload coordinates of each motif.
+At the selected term, the layout reader consumes the absorbed fields and
+checks the local map entries. These choices compose along the same
+branch-dependent executions as the monomial witnesses of equation (12.2).
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open CompressorRecords Compression NetworkKernel
+open scoped Classical
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {κ : L → R}
+
+/-- Enumerate the indices of `Fin n` in increasing order. The position passed to a descriptor
+reader is the index itself. -/
+def Order.fin (n : ℕ) : Order (Fin n) := ⟨n, Equiv.refl _⟩
+
+/-- Enumerate a pair of ordered sets by dividing a single position among blocks of length
+`t.length`. Within the block for an entry of `s`, visit every entry of `t` in order. -/
+def Order.prod {I J : Type} (s : Order I) (t : Order J) : Order (I × J) :=
+ ⟨s.length * t.length, finProdFinEquiv.symm.trans (s.entries.prodCongr t.entries)⟩
+
+/-- Scanning a descriptor list and retaining just the records in one fiber
+preserves the relative order of their numerical identifiers. -/
+noncomputable def Order.restrict {I : Type} (s : Order I) (P : I → Prop) [Fintype (Subtype P)] :
+ Order (Subtype P) :=
+ letI := LinearOrder.lift' (fun x : Subtype P => s.entries.symm x.val)
+ (s.entries.symm.injective.comp Subtype.val_injective)
+ ⟨Fintype.card _, (Fintype.orderIsoFinOfCardEq _ rfl).toEquiv⟩
+
+/-- Site order follows the stored base numbering and the binary lane
+coordinate. Each site's outgoing slots then occur in slot-number order. -/
+def siteOrder {a g : ℕ} (X : State a g) : Order X.network.Site :=
+ Order.prod ⟨_, X.baseIndex.symm⟩ ⟨_, (bitWordFinEquiv g).symm⟩
+
+/-- Order all outgoing edges first by their source site's base and lane coordinates, then by
+their slot number. The terminal history reader uses this order to read one payload per
+edge. -/
+def edgeOrder {a g : ℕ} (X : State a g) : Order X.network.Edge :=
+ (siteOrder X).prod (Order.fin (2 ^ a))
+
+/-- A descriptor supplies the selection parser and the ordered data for
+each of the resulting local kernel checks. The old arc payloads are the
+bit words in the current lifted state. -/
+structure PassReaders {a g b n : ℕ} {X : State a g} (p : StatePass R X b n)
+ (W : p.MapWitnesses κ) where
+ /-- Binary reader for the choice of term at this pass. The selected index determines which
+ local ordering, kernel readers and successor state apply. -/
+ select : ChoiceReader p.step.Choice
+ /-- For each selected term, specify the order of each site's children and the outgoing and
+ incoming incidences read at those children. -/
+ order : ∀ i, LocalOrder (p.step.term i)
+ /-- Reader for the local monomial witness at output site `v` of term `i`, given the old
+ half-edge assignments `x` of its children and the new half-edge assignment `z`. -/
+ kernel : ∀ i v x z, ChoiceReader (W i v x z).Choice
+
+/-- All the local parsers, indexed by the original execution and its
+monomial witnesses. -/
+def ExecutionReaders {a g b n : ℕ} {X : State a g} :
+ (E : StateExecution R b n X) → E.MapWitnesses κ → Type
+ | .done _, _ => Unit
+ | .more p tail, W => PassReaders p W.1 × ((i : p.step.Choice) → ExecutionReaders (tail i) (W.2 i))
+
+open private transportWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+
+private def transportReaders {N Y : Network} (e : N = Y) (H : History R N)
+ (W : H.KernelWitnesses κ) (r : Readers H W) :
+ Readers (e ▸ H) (transportWitnesses e H W) := by
+ cases e
+ exact r
+
+/-- At a terminal state, read each arc once and pass the assignment to
+all sites. At intermediate states, the output identification transports
+the continuation and its parsers together. -/
+noncomputable def executionHistoryReaders {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (W : E.MapWitnesses κ) (r : ExecutionReaders E W) : Readers E.history (E.historyWitnesses W) := by
+ induction E with
+ | done X => exact ⟨edgeOrder X, siteOrder X, statePayload X⟩
+ | @more a g b' n' X p tail ih =>
+ exact ⟨r.1.select, r.1.order, statePayload X, r.1.kernel,
+ fun i => transportReaders (p.output_eq i).symm _ _ (ih i (W.2 i) (r.2 i))⟩
+
+/-- When two executions are joined, read the continuation selected by the
+full choice of the first execution, preserving the same selector stream. -/
+noncomputable def bindReaders {b' n' a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z))
+ (W : E.MapWitnesses κ) (V : ∀ z, (f z).MapWitnesses κ)
+ (r : ExecutionReaders E W) (s : ∀ z, ExecutionReaders (f z) (V z)) :
+ ExecutionReaders (E.bind f) (E.bindWitnesses f W V) := by
+ induction E with
+ | done X => exact s ()
+ | more p tail ih => exact ⟨r.1, fun i => ih i _ (W.2 i) (fun z => V ⟨i,z⟩) (r.2 i) (fun z => s ⟨i,z⟩)⟩
+
+variable {a b l d : ℕ} {μ : ℝ}
+
+/-- Readers on every input with the correct number of lanes. -/
+abbrev ProcedureReaders (P : Procedure R a b l d μ) (W : P.MapWitnesses κ) :=
+ ∀ g n h X, ExecutionReaders (P.run g n h X) (W g n h X)
+
+namespace ProcedureReaders
+
+/-- Supply the empty execution reader for the identity procedure. Its input is already the
+final state, so there is no pass choice or kernel to parse. -/
+def id (a : ℕ) (κ : L → R) : ProcedureReaders (Procedure.id R a) (Procedure.MapWitnesses.id a κ) := by
+ intro g n h X
+ have hn := h.trans (Nat.zero_add g)
+ subst g
+ exact ()
+
+/-- Lift readers for each admissible input of a single pass to readers for its one-step
+procedure. Each term uses the supplied pass reader and leads directly to the terminal
+execution. -/
+def ofPass {C : ℝ} (hd : 0 < d) (hμ : 0 ≤ μ) (hC : 0 ≤ C)
+ (f : ∀ g (X : State a (l + g)), StatePass R X b g)
+ (hc : ∀ g X (i : (f g X).step.Choice), X.positions = d * ((f g X).next i).positions)
+ (he : ∀ g X (i : (f g X).step.Choice),
+ ((f g X).next i).energy ≤ μ * X.energy + C * (X.positions : ℝ) ^ 2)
+ (W : ∀ g X, (f g X).MapWitnesses κ) (r : ∀ g X, PassReaders (f g X) (W g X)) :
+ ProcedureReaders (Procedure.ofPass hd hμ hC f hc he) (Procedure.MapWitnesses.ofPass hd hμ hC f hc he W) := by
+ intro g n h X
+ subst n
+ exact ⟨r g X, fun _ => ()⟩
+
+/-- Compose two procedure readers along their executions. Each full choice of the first
+procedure supplies the final state on which the second procedure's reader starts. -/
+noncomputable def seq {c l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} {Q : Procedure R b c l' d' ν}
+ {W : P.MapWitnesses κ} {V : Q.MapWitnesses κ} (r : ProcedureReaders P W) (s : ProcedureReaders Q V) :
+ ProcedureReaders (P.seq Q) (W.seq V) :=
+ fun g n h X =>
+ let E := P.run (l'+g) n (h.trans (Nat.add_assoc l l' g)) X
+ bindReaders E _ (W _ _ _ X) _ (r _ _ _ X) (fun z => s _ _ _ (E.finalState z))
+
+/-- Transport readers and their map witnesses across equalities of the procedure's input and
+output exponents, consumed lanes, position factor and energy coefficient. -/
+def reindex {a' b' l' d' : ℕ} {μ' : ℝ} {P : Procedure R a b l d μ} {W : P.MapWitnesses κ}
+ (r : ProcedureReaders P W) {ha : a = a'} {hb : b = b'} {hl : l = l'} {hd : d = d'} {hμ : μ = μ'} :
+ ProcedureReaders (P.reindex ha hb hl hd hμ) W.reindex := by
+ subst a' b' l' d' μ'
+ exact r
+
+end ProcedureReaders
+
+/-- Build readers for `T` iterations of a procedure that consumes `l` lane bits each time and
+leaves `g` at the end. The continuation uses the state selected by the preceding iteration. -/
+noncomputable def repeatReaders {P : Procedure R a a l d μ} {W : P.MapWitnesses κ} (r : ProcedureReaders P W) (g : ℕ) :
+ (T n : ℕ) → (h : n = T*l + g) → (X : State a n) →
+ ExecutionReaders (P.repeatExecution g T n h X) (Procedure.repeatWitnesses W g T n h X)
+ | 0, n, h, X => ProcedureReaders.id a κ g n (by simpa using h) X
+ | t+1, n, h, X =>
+ let E := P.run (t*l+g) n (by rw [h, Nat.succ_mul]; omega) X
+ bindReaders E _ _ _ (r _ _ _ X) (fun z => repeatReaders r g t _ rfl (E.finalState z))
+
+
+open private prefixWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+
+variable {k : Type*} [Field k] (S : BlockSchedule k)
+
+private noncomputable def prefixReaders (shrink : S.ShrinkProcedures R)
+ (W : ∀ i : Fin S.steps, (shrink i).MapWitnesses κ)
+ (r : ∀ i, ProcedureReaders (shrink i) (W i)) (j : ℕ) (hj : j ≤ S.steps) :
+ ProcedureReaders (S.shrinkPrefix shrink j hj) (prefixWitnesses S shrink W j hj) :=
+ match j with
+ | 0 => by
+ simp only [prefixWitnesses, BlockSchedule.shrinkPrefix]
+ exact (ProcedureReaders.id _ κ).reindex
+ | j + 1 => by
+ simp only [prefixWitnesses, BlockSchedule.shrinkPrefix]
+ exact ((prefixReaders shrink W r j (by omega)).seq (r ⟨j,hj⟩).reindex).reindex
+
+/-- Assemble readers for one scheduled block. Compose the readers of all shrink levels in
+schedule order, then attach the refresh reader at the state reached by that sequence. -/
+noncomputable def assembleReaders (shrink : S.ShrinkProcedures R) (refresh : S.RefreshProcedure R)
+ (W : ∀ i : Fin S.steps, (shrink i).MapWitnesses κ) (V : refresh.MapWitnesses κ)
+ (r : ∀ i, ProcedureReaders (shrink i) (W i)) (s : ProcedureReaders refresh V) :
+ ProcedureReaders (S.assembleBlock shrink refresh) (S.assembleBlockWitnesses shrink refresh W V) := by
+ unfold BlockSchedule.assembleBlock BlockSchedule.assembleBlockWitnesses
+ exact ((prefixReaders S shrink W r S.steps le_rfl).reindex.seq s).reindex
+
+
+section Selectors
+
+open MotifGrid MotifBlocks MotifConversion MotifSelector
+
+variable {J D E I : Type} [Fintype J] [Fintype D] [Fintype E] [Fintype I]
+ {src dst : D → J} {P : Supply J E} {p : D → ℚ} {q : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock k src dst P (realWidths p) (realWidths q) H H')
+ (motifs : Order I) (edges : Order E) (hq : ∀ e, 0 < q e) (demand : I → D → ℕ)
+
+/-- One common word width for all nonzero-demand motifs of the pass. -/
+noncomputable def selectorWidth : ℕ := (Finset.univ.sup (fun i => outerCap B (demand i))).size
+
+theorem selectorWidth_le (M : ℕ) (hM : ∀ i j, demand i j ≤ M) :
+ selectorWidth B demand ≤
+ (((∑ j, MotifAdmission.weight p j) + 1) * B.scale * B.radius.num.natAbs *
+ MotifAdmission.denominator q).size + Nat.clog 2 (M + 1) := by
+ let bound := (((∑ j, MotifAdmission.weight p j) + 1) * B.scale * B.radius.num.natAbs *
+ MotifAdmission.denominator q).size + Nat.clog 2 (M+1)
+ apply Nat.size_le.mpr
+ change Finset.univ.sup (fun i => outerCap B (demand i)) < 2 ^ bound
+ apply lt_of_le_of_lt (Finset.sup_le (a := 2 ^ bound - 1) ?_) (by have := Nat.two_pow_pos bound; omega)
+ intro i _
+ have h : outerCap B (demand i) < 2 ^ bound := Nat.size_le.mp (outerCap_bits_le B (demand i) M (hM i))
+ omega
+
+private theorem selector_fits (i : I) : outerCap B (demand i) < 2 ^ selectorWidth B demand :=
+ (Finset.le_sup (f := fun j => outerCap B (demand j)) (Finset.mem_univ i)).trans_lt (Nat.lt_size_self _)
+
+/-- Read the admitted coordinates in the fixed motif and supply-edge orders. -/
+noncomputable def selectPass : ChoiceReader ((i : I) → ↥(outerIndices B (demand i))) :=
+ motifPassReader B motifs.entries edges.entries hq demand (selectorWidth B demand) (selector_fits B demand)
+
+theorem selectPass_bits_le (v : (i : I) → ↥(outerIndices B (demand i))) :
+ ((selectPass B motifs edges hq demand).encode v).length ≤ motifs.length * (edges.length * selectorWidth B demand) :=
+ motifPass_bits_le B motifs.entries edges.entries hq demand _ (selector_fits B demand) v
+
+end Selectors
+
+section Concrete
+
+variable {S} (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+
+open MotifGrid MotifConversion ShrinkMotif Refresh
+
+/-- The dense term row is the packed bundle ordinal followed by its CD
+rank. This is the same row the native demand and term scans visit. -/
+noncomputable def shrinkMotifOrder {a g : ℕ} (X : State a (packingLaneBits a g)) :
+ Order X.packingData.Motif :=
+ ⟨Fintype.card X.packingData.Motif, CompressorRecords.ShrinkMotifOrder.entries X⟩
+
+set_option maxHeartbeats 2000000 in
+/-- Construct the selector and kernel readers of shrink level `i`. They enumerate packed motifs
+and the eight supply edges, then read each chosen term's absorbed fields and local map
+choices in the restricted site orders. -/
+noncomputable def shrinkPassReaders (i : Fin S.steps) {g n : ℕ}
+ (h : n = packingLaneBits (S.degreeExponent i.castSucc) g)
+ (X : State (S.degreeExponent i.castSucc) n) :
+ PassReaders (B.shrinkPassAt f hf i h X) (B.shrinkPassWitnesses f hf i h X) := by
+ subst n
+ let motifs := shrinkMotifOrder X
+ let edges := Order.prod ⟨2, finTwoEquiv⟩ (Order.fin 4)
+ let parsers := fun s => shrinkStateParsers X B.shrink (f ∘ Sum.inl) ((B.solution_iff f).mp hf).1
+ (S.shrink i) s (fun _ => (motifs.prod (Order.fin 4)).restrict _)
+ (fun _ => (motifs.prod (Order.fin 6)).restrict _) (fun _ => (siteOrder X).restrict _)
+ exact ⟨selectPass B.shrink motifs edges supplyMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth),
+ fun s => (parsers s).order, fun s => (parsers s).read⟩
+
+set_option maxHeartbeats 2000000 in
+/-- Equip the one-pass shrink procedure at level `i` with its concrete binary readers for every
+input state satisfying the packing lane count. -/
+noncomputable def shrinkProcedureReaders (i : Fin S.steps) :
+ ProcedureReaders (B.shrinkProcedure f hf i) (B.shrinkProcedureWitnesses f hf i) :=
+ ProcedureReaders.ofPass _ _ _ _ _ _ _
+ (fun g X => shrinkPassReaders B f hf i (packingLaneBits_add _ g) X)
+
+/-- Construct the refresh procedure's readers by enumerating base–lane motifs and port–expander
+supply edges. After the admitted payload choice, the local parsers use the restricted site
+order to read the selected term. -/
+noncomputable def refreshProcedureReaders :
+ ProcedureReaders (B.refreshProcedure f hf) (B.refreshProcedureWitnesses f hf) := by
+ apply ProcedureReaders.ofPass
+ intro g X
+ let motifs := Order.prod ⟨_, X.baseIndex.symm⟩ ⟨_, (bitWordFinEquiv g).symm⟩
+ let edges := (Order.fin (2 ^ S.portExponent)).prod (Order.fin (2 ^ S.expanderExponent))
+ have hq (e : Fin (2 ^ S.portExponent) × Fin (2 ^ S.expanderExponent)) : 0 < expanderMass S.baseDegree e := by
+ unfold expanderMass BlockSchedule.baseDegree
+ positivity
+ let parsers := fun c => refreshStateParsers X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2
+ (f ∘ Sum.inr) ((B.solution_iff f).mp hf).2 c (fun _ => (siteOrder X).restrict _)
+ exact ⟨selectPass B.refresh motifs edges hq (blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X)),
+ fun c => (parsers c).order, fun c => (parsers c).read⟩
+
+/-- All actual term and entry parsers of the fixed schedule, including
+the branch-dependent inputs to its last port refresh. -/
+noncomputable def blockReaders : ProcedureReaders (B.procedure f hf) (B.procedureWitnesses f hf) :=
+ assembleReaders S _ _ _ _ (shrinkProcedureReaders B f hf) (refreshProcedureReaders B f hf)
+
+/-- Read the history of `T` concrete compressor blocks from `X`. The repeated shrink and
+refresh readers follow the selected branches, and the terminal reader visits the final
+state's edges and sites. -/
+noncomputable def executeReaders {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) :
+ Readers (B.execute f hf T h X).history (B.executeWitnesses f hf T h X) :=
+ executionHistoryReaders _ _ (repeatReaders (blockReaders B f hf) _ T n (Nat.add_sub_of_le h).symm X)
+
+end Concrete
+
+section Cursor
+
+open CursorNetwork CursorRouting BurstRAM BurstRAM.PrivateRAM
+
+variable {S} {D e w p r k' base lanes : ℕ} [NeZero D]
+ (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (M : Machine w p r k') (fuel : ℕ)
+ (initial : Word w) (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w)
+ (labels : Fin D ≃ Fin base ⊕ Fin lanes) (hD : 1 < D) (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+
+/-- The binary reader for the occurrence type of the repeated compressor
+on the padded RAM cursor network, using its actual branch descriptors. -/
+noncomputable def compressedReader :
+ ChoiceReader (compressedRAMCount B f hf M fuel initial header hw hc labels hD T hT).Choice :=
+ let hpad := Nat.add_sub_of_le S.degree_bounds.1
+ cursorReader M fuel initial hw hc header labels hD hpad _ _ (executeReaders B f hf T hT _)
+
+/-- The weighted count of complete binary streams is the original capped
+path count, with every stream carrying its own parameter exponents. -/
+theorem compressed_weightedStreams :
+ let W := compressedRAMCount B f hf M fuel initial header hw hc labels hD T hT
+ let C := compressedReader B f hf M fuel initial header hw hc labels hD T hT
+ ∑ bs : successful W C, Diagonal.labelMonomial f (W.exponents (C.completeEquiv.symm bs)) =
+ (Nat.card (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2 ^ D) header)
+ (withinCaps (2 ^ D) (2 ^ e))) : R) :=
+ weightedStreams _ _
+
+end Cursor
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationAssemblyBounds.lean b/lean/OAI/Computability/VPVNP/PairSimulationAssemblyBounds.lean
new file mode 100644
index 0000000000..f0c3e8f5b7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationAssemblyBounds.lean
@@ -0,0 +1,274 @@
+import OAI.Computability.VPVNP.PairSimulationAssembly
+
+/-!
+# Per-vertex bit bounds on the actual repeated compressor
+
+The field records of Theorem 7.1 cover each choice read below a selected
+vertex. Joining two procedures and repeating a block preserve this
+coverage at every selected term. This bounds the private binary string
+at each final site, including independent old half-arc guesses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression NetworkKernel CompressorRecords
+open scoped Classical
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {κ : L → R}
+
+/-- Use the same order, arc payloads and kernel choices as the complete
+history reader. -/
+noncomputable def PassReaders.termParsers {a g b n : ℕ} {X : State a g} {p : StatePass R X b n}
+ {W : p.MapWitnesses κ} (r : PassReaders p W) (i : p.step.Choice) : TermParsers κ (p.step.term i) :=
+ ⟨r.order i, statePayload X, W i, r.kernel i⟩
+
+/-- Every term of every reachable pass has enough recorded field width at each output site to
+cover the bits for its children's old halves and its local kernel choice. -/
+def ExecutionCovered {a g b n : ℕ} {X : State a g} :
+ (E : StateExecution R b n X) → (W : E.MapWitnesses κ) → ExecutionReaders E W → E.Records → Prop
+ | .done _, _, _, _ => True
+ | .more _ tail, W, r, rec =>
+ (∀ i, (r.1.termParsers i).Covered (rec.1 i)) ∧
+ ∀ i, ExecutionCovered (tail i) (W.2 i) (r.2 i) (rec.2 i)
+
+private def castParsers {N Y Z : Network} (e : N = Y) (c : TermChain R N Z) (r : ChainParsers κ c) :
+ ChainParsers κ (e ▸ c) := by cases e; exact r
+
+private theorem castCovered {N Y Z : Network} (e : N = Y) (c : TermChain R N Z) (r : ChainParsers κ c)
+ (h : Covered c r) : Covered (e ▸ c) (castParsers e c r) := by cases e; exact h
+
+/-- Follow the actual term choices into the local subtree parsers of this
+branch of the existing compression history. -/
+noncomputable def branchParsers {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (W : E.MapWitnesses κ) (r : ExecutionReaders E W) (rec : E.Records) (z : E.Choices) :
+ ChainParsers κ (E.termChain rec z) := by
+ induction E with
+ | done => exact PUnit.unit
+ | more p tail ih =>
+ exact ⟨r.1.termParsers z.1, castParsers (p.output_eq z.1).symm _ (ih z.1 (W.2 z.1) (r.2 z.1) (rec.2 z.1) z.2)⟩
+
+theorem branchParsers_covered {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (W : E.MapWitnesses κ) (r : ExecutionReaders E W) (rec : E.Records) (h : ExecutionCovered E W r rec) (z : E.Choices) :
+ Covered (E.termChain rec z) (branchParsers E W r rec z) := by
+ induction E with
+ | done => trivial
+ | more p tail ih =>
+ exact ⟨h.1 z.1, castCovered (p.output_eq z.1).symm _ _ (ih z.1 _ _ _ (h.2 z.1) z.2)⟩
+
+theorem bindCovered {b' n' a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z))
+ (W : E.MapWitnesses κ) (V : ∀ z, (f z).MapWitnesses κ)
+ (r : ExecutionReaders E W) (s : ∀ z, ExecutionReaders (f z) (V z))
+ (u : E.Records) (v : ∀ z, (f z).Records) (hu : ExecutionCovered E W r u)
+ (hv : ∀ z, ExecutionCovered (f z) (V z) (s z) (v z)) :
+ ExecutionCovered (E.bind f) _ (bindReaders E f W V r s) (E.bindRecords f u v) := by
+ induction E with
+ | done X => exact hv ()
+ | more p tail ih => exact ⟨hu.1, fun i => ih i _ (W.2 i) _ (r.2 i) _ (u.2 i) _ (hu.2 i) (fun z => hv ⟨i,z⟩)⟩
+
+variable {a b l d C m : ℕ} {μ : ℝ}
+
+/-- Coverage of a procedure on every legal input state and lane count. Each branch of the
+resulting execution is checked against the records supplied by the procedure's record
+bounds. -/
+abbrev ProcedureCovered {P : Procedure R a b l d μ} {W : P.MapWitnesses κ}
+ (r : ProcedureReaders P W) (B : P.RecordBounds C m) :=
+ ∀ g n h X, ExecutionCovered (P.run g n h X) _ (r g n h X) (B.records g n h X)
+
+namespace ProcedureCovered
+
+theorem id (a C : ℕ) (κ : L → R) :
+ ProcedureCovered (ProcedureReaders.id a κ) (Procedure.RecordBounds.id R a C) := by
+ intro g n h X
+ have hn := h.trans (Nat.zero_add g)
+ subst g
+ trivial
+
+theorem ofPass {A : ℝ} (hd : 0 < d) (hμ : 0 ≤ μ) (hA : 0 ≤ A)
+ (f : ∀ g (X : State a (l + g)), StatePass R X b g)
+ (hc : ∀ g X (i : (f g X).step.Choice), X.positions = d * ((f g X).next i).positions)
+ (he : ∀ g X (i : (f g X).step.Choice),
+ ((f g X).next i).energy ≤ μ * X.energy + A * (X.positions : ℝ) ^ 2)
+ (W : ∀ g X, (f g X).MapWitnesses κ) (r : ∀ g X, PassReaders (f g X) (W g X))
+ (rec : ∀ g X, (f g X).Records) (hb : ∀ g X, (f g X).Bounded (rec g X) C)
+ (hcov : ∀ g X i, ((r g X).termParsers i).Covered (rec g X i)) :
+ ProcedureCovered (ProcedureReaders.ofPass hd hμ hA f hc he W r)
+ (Procedure.RecordBounds.ofPass hd hμ hA f hc he rec hb) := by
+ intro g n h X
+ subst n
+ exact ⟨hcov g X, fun _ => trivial⟩
+
+theorem seq {c l' d' D n : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} {Q : Procedure R b c l' d' ν}
+ {W : P.MapWitnesses κ} {V : Q.MapWitnesses κ} {r : ProcedureReaders P W} {s : ProcedureReaders Q V}
+ {B : P.RecordBounds C m} {B' : Q.RecordBounds D n} (h : ProcedureCovered r B) (h' : ProcedureCovered s B') :
+ ProcedureCovered (r.seq s) (B.seq B') :=
+ fun g n eqn X =>
+ let E := P.run (l'+g) n (eqn.trans (Nat.add_assoc l l' g)) X
+ bindCovered E _ _ _ _ _ _ _ (h _ _ _ X) (fun z => h' _ _ _ (E.finalState z))
+
+theorem mono {P : Procedure R a b l d μ} {W : P.MapWitnesses κ}
+ {r : ProcedureReaders P W} {B : P.RecordBounds C m} {D n : ℕ} (h : ProcedureCovered r B)
+ (hC : C ≤ D) (hm : m ≤ n) : ProcedureCovered r (B.mono hC hm) := h
+
+theorem reindex {a' b' l' d' : ℕ} {μ' : ℝ} {P : Procedure R a b l d μ} {W : P.MapWitnesses κ}
+ {r : ProcedureReaders P W} {B : P.RecordBounds C m} (h : ProcedureCovered r B)
+ {ha : a = a'} {hb : b = b'} {hl : l = l'} {hd : d = d'} {hμ : μ = μ'} :
+ ProcedureCovered (r.reindex (ha := ha) (hb := hb) (hl := hl) (hd := hd) (hμ := hμ)) B.reindex := by
+ subst a' b' l' d' μ'
+ exact h
+
+end ProcedureCovered
+
+theorem repeatCovered {P : Procedure R a a l d μ} {W : P.MapWitnesses κ} {r : ProcedureReaders P W}
+ {B : P.RecordBounds C m} (hc : ProcedureCovered r B) (g T n : ℕ) (h : n = T*l + g) (X : State a n) :
+ ExecutionCovered (P.repeatExecution g T n h X) _ (repeatReaders r g T n h X) (Procedure.repeatRecords B g T n h X) := by
+ induction T generalizing n with
+ | zero =>
+ have hn : n = g := by simpa using h
+ subst g
+ trivial
+ | succ t ih =>
+ let E := P.run (t*l+g) n (by rw [h,Nat.succ_mul]; omega) X
+ exact bindCovered E _ _ _ _ _ _ _ (hc _ _ _ X) (fun z => ih _ rfl (E.finalState z))
+
+open private prefixReaders from OAI.Computability.VPVNP.PairSimulationAssembly
+open private prefixWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+open private prefixRecordBounds from OAI.Computability.VPVNP.CompressionBlockHistory
+
+variable {k : Type*} [Field k] (S : BlockSchedule k)
+
+private theorem prefixCovered (shrink : S.ShrinkProcedures R)
+ (W : ∀ i : Fin S.steps, (shrink i).MapWitnesses κ) (r : ∀ i, ProcedureReaders (shrink i) (W i))
+ (B : ∀ i, (shrink i).RecordBounds C 1) (h : ∀ i, ProcedureCovered (r i) (B i)) (j : ℕ) (hj : j ≤ S.steps) :
+ ProcedureCovered (prefixReaders S shrink W r j hj) (prefixRecordBounds S shrink B j hj) := by
+ induction j with
+ | zero =>
+ simp only [prefixRecordBounds, prefixReaders, prefixWitnesses, BlockSchedule.shrinkPrefix]
+ exact (ProcedureCovered.id _ C κ).reindex
+ | succ j ih =>
+ simp only [prefixRecordBounds, prefixReaders, prefixWitnesses, BlockSchedule.shrinkPrefix]
+ exact (((ih (Nat.le_of_succ_le hj)).seq (h ⟨j,hj⟩).reindex).mono (max_le le_rfl le_rfl) le_rfl).reindex
+
+private theorem assembleCovered (shrink : S.ShrinkProcedures R) (refresh : S.RefreshProcedure R)
+ {D : Fin S.steps → ℕ} (W : ∀ i, (shrink i).MapWitnesses κ) (V : refresh.MapWitnesses κ)
+ (r : ∀ i, ProcedureReaders (shrink i) (W i)) (s : ProcedureReaders refresh V)
+ (B : ∀ i, (shrink i).RecordBounds (D i) 1) (B' : refresh.RecordBounds C 1)
+ (h : ∀ i, ProcedureCovered (r i) (B i)) (h' : ProcedureCovered s B') :
+ ProcedureCovered (assembleReaders S shrink refresh W V r s) (S.assembleBlockRecords shrink refresh B B') := by
+ unfold assembleReaders BlockSchedule.assembleBlockRecords
+ apply ProcedureCovered.reindex
+ apply ProcedureCovered.seq _ h'
+ apply ProcedureCovered.reindex
+ exact prefixCovered S shrink W r _ (fun i => h i) S.steps le_rfl
+
+
+omit [CommRing R] in
+private theorem recordWidths_mono {N Y : Network} (c : TermChain R N Y) {u v : ℕ}
+ (h : c.AllRecordsLe u) (hle : u ≤ v) : c.AllRecordsLe v := by
+ induction c with
+ | done => trivial
+ | more _ _ _ ih => exact ⟨fun x i => (h.1 x i).trans hle, fun x j => (h.2.1 x j).trans hle, ih h.2.2⟩
+
+section Concrete
+
+open MotifConversion Refresh
+open private recordsAt from OAI.Computability.VPVNP.ShrinkProcedureHistory
+
+variable {S} (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+
+set_option maxHeartbeats 2000000 in
+private theorem shrinkPassCovered (i : Fin S.steps) {g n : ℕ}
+ (h : n = packingLaneBits (S.degreeExponent i.castSucc) g) (X : State (S.degreeExponent i.castSucc) n)
+ (s : (B.shrinkPassAt f hf i h X).step.Choice) :
+ ((shrinkPassReaders B f hf i h X).termParsers s).Covered (recordsAt B f hf i h X s) := by
+ subst n
+ let motifs := shrinkMotifOrder X
+ intro v old new ch
+ exact shrinkStateParsers_covered X B.shrink (f ∘ Sum.inl) ((B.solution_iff f).mp hf).1 (S.shrink i) s
+ (fun _ => (motifs.prod (Order.fin 4)).restrict _) (fun _ => (motifs.prod (Order.fin 6)).restrict _)
+ (fun _ => (siteOrder X).restrict _) v old new ch
+
+set_option maxHeartbeats 2000000 in
+private theorem shrinkProcedureCovered (i : Fin S.steps) :
+ ProcedureCovered (shrinkProcedureReaders B f hf i) (B.shrinkProcedureRecords f hf i) :=
+ ProcedureCovered.ofPass _ _ _ _ _ _ _ _ _ _ (fun g X => shrinkPassCovered B f hf i (packingLaneBits_add _ g) X)
+
+private theorem refreshProcedureCovered :
+ ProcedureCovered (refreshProcedureReaders B f hf) (B.refreshProcedureRecords f hf) := by
+ intro g n h X
+ subst n
+ refine ⟨fun c v old new ch => ?_, fun _ => trivial⟩
+ exact refreshStateParsers_covered X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2
+ (f ∘ Sum.inr) ((B.solution_iff f).mp hf).2 c (fun _ => (siteOrder X).restrict _) v old new ch
+
+theorem blockReaders_covered : ProcedureCovered (blockReaders B f hf) (B.recordBounds f hf) :=
+ assembleCovered S _ _ _ _ _ _ _ _ (shrinkProcedureCovered B f hf) (refreshProcedureCovered B f hf)
+
+/-- On a complete choice of terms, use the concrete readers and records
+of the compressor to expand one final vertex. -/
+noncomputable def selectedParsers {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T h X).Choices) :
+ ChainParsers f ((B.execute f hf T h X).termChain (B.records f hf T h X) z) :=
+ branchParsers _ _ (repeatReaders (blockReaders B f hf) _ T n (Nat.add_sub_of_le h).symm X) _ z
+
+theorem selectedParsers_covered {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T h X).Choices) :
+ Covered ((B.execute f hf T h X).termChain (B.records f hf T h X) z) (selectedParsers B f hf T h X z) :=
+ branchParsers_covered _ _ _ _ (repeatCovered (blockReaders_covered B f hf) _ T n (Nat.add_sub_of_le h).symm X) z
+
+/-- The per-site private string uses at most the per-block growth factor
+times the larger of the leaf-string bound and the intermediate field bound. -/
+theorem selectedSite_length_le {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T h X).Choices) (P : SiteParsers f X.network)
+ (L : ℕ) (hL : ∀ u a p, ((P.read u a).encode p).length ≤ L) :
+ let chain := (B.execute f hf T h X).termChain (B.records f hf T h X) z
+ let parsers := finalParsers chain (selectedParsers B f hf T h X z) P
+ ∀ v a p, ((parsers.read v a).encode p).length ≤
+ B.growthConstant ^ T * max L (B.growthConstant ^ T * (X.maxWireWidth + 1)) := by
+ let chain := (B.execute f hf T h X).termChain (B.records f hf T h X) z
+ let width := B.growthConstant ^ T * (X.maxWireWidth + 1)
+ obtain ⟨_, _, _, counts, records, _⟩ := B.branch_bounds f hf T h X z
+ have hrec : chain.AllRecordsLe (max L width) := by
+ exact recordWidths_mono chain records (le_max_right _ _)
+ have hb := finalParsers_bound chain (selectedParsers B f hf T h X z)
+ (selectedParsers_covered B f hf T h X z) P (fun _ => 1) (max L width) hrec
+ (fun u a p => (hL u a p).trans (by simp))
+ exact fun v a p => (hb v a p).trans (Nat.mul_le_mul_right _ (counts v))
+
+end Concrete
+
+section Cursor
+
+open CursorNetwork CursorRouting BurstRAM BurstRAM.PrivateRAM
+
+variable {S} {D e w p r k' base lanes : ℕ} [NeZero D]
+ (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+ (M : Machine w p r k') (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2^D * 2^e < 2^w) (labels : Fin D ≃ Fin base ⊕ Fin lanes) (hD : 1 < D)
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+
+/-- The bound on private bits at every final vertex, specialized to the
+original capped machine's validating leaf bursts. -/
+theorem cursorSite_length_le :
+ let hpad := Nat.add_sub_of_le S.degree_bounds.1
+ let X := cursorState labels hD hpad (ramFieldBits (2^e) w : RAMSystem D → ℕ)
+ let E := B.execute f hf T hT X
+ let P := cursorSiteParsers M fuel initial header hw hc labels hD hpad f
+ ∀ z : E.Choices, let chain := E.termChain (B.records f hf T hT X) z
+ let parsers := finalParsers chain (selectedParsers B f hf T hT X z) P
+ ∀ v a p, ((parsers.read v a).encode p).length ≤
+ B.growthConstant^T * max (2 * 2^e * (fuel+w)) (B.growthConstant^T * (X.maxWireWidth+1)) := by
+ intro hpad X E P z
+ exact selectedSite_length_le B f hf T hT X z P _ (cursorSiteParsers_length_le M fuel initial header hw hc labels hD hpad f)
+
+end Cursor
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationBranchDecoder.lean b/lean/OAI/Computability/VPVNP/PairSimulationBranchDecoder.lean
new file mode 100644
index 0000000000..46dfdc8e14
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationBranchDecoder.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PairSimulationSelectorReindex
+
+/-! # Decoding the physical term bursts along a compression branch
+
+A packet at one level consists of one full native burst per motif, in
+worker order. The worker executes those bursts in its advised memory.
+Its accepted choice determines the next state and the decoder of the
+remaining levels. The final state consumes exactly the empty suffix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords NetworkKernel BurstRAM
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {B : S.Templates}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w : ℕ} {X : State a g} {p : StatePass A X b n} {o : PassOrigin B f hf p}
+
+private def packetRows {m : ℕ} (ts : List (List Bool)) (h : ts.length = m) (i : Fin m) : List Bool :=
+ ts.get (Fin.cast h.symm i)
+
+private theorem ofFn_packetRows {m : ℕ} (ts : List (List Bool)) (h : ts.length = m) :
+ List.ofFn (packetRows ts h) = ts := by
+ subst m
+ exact List.ofFn_get ts
+
+/-- Check the number of bursts and the actual ordinal worker execution
+before using the worker's proved inverse to recover the term. -/
+noncomputable def WorkerInput.decodePacket (I : WorkerInput o w) (ts : List (List Bool)) :
+ Option p.step.Choice :=
+ if h : ts.length = o.motifCount then
+ let rows := packetRows ts h
+ if ok : (I.run rows).isSome then some (I.termEquiv.symm ⟨rows, ok⟩) else none
+ else none
+
+theorem WorkerInput.decodePacket_iff (I : WorkerInput o w) (ts : List (List Bool)) (i : p.step.Choice) :
+ I.decodePacket ts = some i ↔ List.ofFn (I.termEquiv i).val = ts := by
+ classical
+ constructor
+ · intro h
+ unfold decodePacket at h
+ split at h
+ next hlen =>
+ dsimp only at h
+ split at h
+ next ok =>
+ have same := I.termEquiv.symm_apply_eq.mp (Option.some.inj h)
+ rw [← same]
+ exact ofFn_packetRows ts hlen
+ next => contradiction
+ next => contradiction
+ · rintro rfl
+ let rows := (I.termEquiv i).val
+ have hlen : (List.ofFn rows).length = o.motifCount := List.length_ofFn
+ have same : packetRows (List.ofFn rows) hlen = rows := by
+ funext j
+ simp [packetRows]
+ have ok : (I.run rows).isSome := (I.termEquiv i).prop
+ change I.decodePacket (List.ofFn rows) = some i
+ rw [decodePacket, dite_eq_left hlen]
+ change (if h : (I.run (packetRows (List.ofFn rows) hlen)).isSome then
+ some (I.termEquiv.symm ⟨packetRows (List.ofFn rows) hlen,h⟩) else none) = some i
+ simp only [same,dite_eq_left ok]
+ exact congrArg some (I.termEquiv.symm_apply_apply i)
+
+/-- Decode an arbitrary list of chronological level packets. The order
+of subsequent workers depends on the term recovered at each level. -/
+noncomputable def decodeOrdinalTapes {a g b n : ℕ} {X : State a g} (E : StateExecution A b n X) :
+ (origin : PassOrigins B f hf E) → WorkerInputs E origin w → List (List (List Bool)) → Option E.Choices :=
+ match E with
+ | .done _ => fun _ _ ts => match ts with | [] => some () | _ :: _ => none
+ | .more _ tail => fun origin inputs ts => match ts with
+ | [] => none
+ | packet :: rest => (inputs.1.decodePacket packet).bind fun i =>
+ (decodeOrdinalTapes (tail i) (origin.2 i) (inputs.2 i) rest).map (Sigma.mk i)
+
+variable {a' g' b' n' : ℕ} {Y : State a' g'} (E : StateExecution A b' n' Y)
+ (origin : PassOrigins B f hf E) (inputs : WorkerInputs E origin w)
+
+theorem decodeOrdinalTapes_encode (z : E.Choices) :
+ decodeOrdinalTapes E origin inputs (ordinalTapes E origin inputs z) = some z := by
+ induction E with
+ | done => cases z; rfl
+ | more p tail ih =>
+ obtain ⟨i,z⟩ := z
+ simp only [ordinalTapes, decodeOrdinalTapes,
+ (inputs.1.decodePacket_iff _ i).mpr rfl, Option.bind_some,
+ ih i (origin.2 i) (inputs.2 i) z]
+ rfl
+
+/-- Exact inverse on all inputs, including empty executions, malformed
+bursts, missing motifs and surplus level packets. -/
+theorem decodeOrdinalTapes_iff (ts : List (List (List Bool))) (z : E.Choices) :
+ decodeOrdinalTapes E origin inputs ts = some z ↔ ordinalTapes E origin inputs z = ts := by
+ constructor
+ · induction E generalizing ts with
+ | done =>
+ cases ts <;> cases z <;> simp [decodeOrdinalTapes, ordinalTapes]
+ | more p tail ih =>
+ cases ts with
+ | nil => simp [decodeOrdinalTapes]
+ | cons packet rest =>
+ intro hz
+ simp only [decodeOrdinalTapes] at hz
+ obtain ⟨i,hi,ht⟩ := Option.bind_eq_some_iff.mp hz
+ obtain ⟨u,hu,rfl⟩ := Option.map_eq_some_iff.mp ht
+ exact congrArg₂ List.cons ((inputs.1.decodePacket_iff packet i).mp hi)
+ (ih i (origin.2 i) (inputs.2 i) rest u hu)
+ · rintro rfl
+ exact decodeOrdinalTapes_encode E origin inputs z
+
+theorem decodeOrdinalTapes_isSome_iff (ts : List (List (List Bool))) :
+ (decodeOrdinalTapes E origin inputs ts).isSome ↔ ∃! z, ordinalTapes E origin inputs z = ts := by
+ rw [Option.isSome_iff_exists]
+ constructor
+ · rintro ⟨z,hz⟩
+ have e := (decodeOrdinalTapes_iff E origin inputs ts z).mp hz
+ exact ⟨z,e,fun u hu => ordinalTapes_injective E origin inputs (hu.trans e.symm)⟩
+ · rintro ⟨z,e,_⟩
+ exact ⟨z,(decodeOrdinalTapes_iff E origin inputs ts z).mpr e⟩
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationCounters.lean b/lean/OAI/Computability/VPVNP/PairSimulationCounters.lean
new file mode 100644
index 0000000000..71b7bef77f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationCounters.lean
@@ -0,0 +1,574 @@
+import OAI.Computability.VPVNP.PairSimulationHistory
+import OAI.Computability.VPVNP.LiveNominationSweep
+import OAI.Computability.VPVNP.RAMRecords
+import OAI.Computability.VPVNP.RAMUniform
+import Mathlib.Data.ZMod.Defs
+import Mathlib.Tactic.FinCases
+
+/-!
+# Flushing a final vertex's gadget histogram
+
+At the end of its burst the vertex has a private array of gadget exponents.
+The shared array holds the nominated production histogram first and the
+gadget histogram second. Seven fixed instructions loop over the suffix.
+Each iteration loads one private count and makes one external read and write.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.Counters
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Registers hold external cursor, external end, private cursor, one,
+external count, and local count. -/
+def instruction (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) : Fin 7 → Instr w p r k :=
+ ![.jumpEq (reg 0) (reg 1) done (pc 1), .loadPrivate (reg 5) (reg 2) (pc 2),
+ .readExternal (reg 4) (reg 0) (pc 3), .binary .add (reg 4) (reg 4) (reg 5) (pc 4),
+ .writeExternal (reg 0) (reg 4) (pc 5), .binary .add (reg 0) (reg 0) (reg 3) (pc 6),
+ .binary .add (reg 2) (reg 2) (reg 3) (pc 0)]
+
+theorem resize_instruction (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) (i : Fin 7) :
+ (instruction (w := 1) (k := k) pc reg done i).resize w = instruction pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- Require the seven code rows of the histogram flush at their assigned labels. They
+accumulate the local gadget counts into the shared histogram suffix and jump to `done` at
+its end. -/
+def Linked (M : Machine w p r k) (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+variable {M : Machine w p r k} {pc : Fin 7 → Fin p} {reg : Fin 6 ↪ Fin r} {done : Fin p}
+
+private abbrev word (w i : ℕ) : Word w := (i : Word w)
+
+private theorem val_word {i : ℕ} (hi : i < 2 ^ w) : (word w i).val = i := Nat.mod_eq_of_lt hi
+
+private theorem step_at (hl : Linked M pc reg done) (i : Fin 7) (c : Config w p r) (hc : c.pc =
+ pc i) :
+ M.program.step c = (instruction pc reg done i).run M.publicData c := by simp [Machine.program,
+ hc, hl i]
+
+private theorem local_step {c d : Config w p r} (hs : M.program.step c = .localStep d)
+ (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute M.program (fuel+1) c m bits = (execute M.program fuel d m bits).map
+ (Report.prepend .tick) := by
+ simp only [execute, hs]
+
+private theorem read_step {c : Config w p r} {a : Word w} {f : Word w → Config w p r}
+ (hs : M.program.step c = .read a f) (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute M.program (fuel+1) c m bits =
+ (execute M.program fuel (f (m a.val)) m bits).map (Report.prepend (.read a (m a.val))) := by
+ simp only [execute, hs]
+
+private theorem write_step {c d : Config w p r} {a v : Word w} (hs : M.program.step c =
+ .write a v d)
+ (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute M.program (fuel+1) c m bits =
+ (execute M.program fuel d (writeMemory m a v) bits).map (Report.prepend (.write a v)) := by
+ simp only [execute, hs]
+
+private def nextConfig (c : Config w p r) (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r)
+ (src dst : ℕ) (old : Word w) : Config w p r :=
+ let gain := c.privateMem (word w src)
+ let cp := c.put (pc 2) (reg 5) gain
+ let cr := cp.put (pc 3) (reg 4) old
+ let ca := cr.put (pc 4) (reg 4) (old + gain)
+ let cd := ca.put (pc 6) (reg 0) (word w (dst+1))
+ cd.put (pc 0) (reg 2) (word w (src+1))
+
+private def componentEvents (address old gain : Word w) : List (Event w) :=
+ [.tick, .tick, .read address old, .tick, .write address (old+gain), .tick, .tick]
+
+private theorem execute_component (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (src dst : ℕ) (hd : dst < 2 ^ w) (hsrc : c.reg (reg 2) = word w src)
+ (hdst : c.reg (reg 0) = word w dst) (hone : c.reg (reg 3) = 1) (hne : c.reg (reg 0) ≠ c.reg
+ (reg 1))
+ (fuel : ℕ) (m : Memory w) (bs : List Bool) :
+ let gain := c.privateMem (word w src)
+ execute M.program (fuel+7) c m bs =
+ (execute M.program fuel (nextConfig c pc reg src dst (m dst))
+ (writeMemory m (word w dst) (m dst+gain)) bs).map
+ (fun rep ↦ ⟨componentEvents (word w dst) (m dst) gain ++ rep.events, rep.result⟩) := by
+ let gain := c.privateMem (word w src)
+ let ct := {c with pc := pc 1}
+ let cp := c.put (pc 2) (reg 5) gain
+ let cr := cp.put (pc 3) (reg 4) (m dst)
+ let ca := cr.put (pc 4) (reg 4) (m dst + gain)
+ let cw := {ca with pc := pc 5}
+ let cd := ca.put (pc 6) (reg 0) (word w (dst+1))
+ have s0 : M.program.step c = .localStep ct := by
+ rw [step_at hl 0 c hc]
+ change CallAction.localStep {c with
+ pc := if c.reg (reg 0) = c.reg (reg 1) then done else pc 1} = _
+ simp [hne, ct]
+ have s1 : M.program.step ct = .localStep cp := by
+ rw [step_at hl 1 ct rfl]
+ change CallAction.localStep (ct.put (pc 2) (reg 5) (c.privateMem (c.reg (reg 2)))) = _
+ rw [hsrc]
+ rfl
+ have s2 : M.program.step cp = .read (word w dst) (fun v ↦ cp.put (pc 3) (reg 4) v) := by
+ rw [step_at hl 2 cp rfl]
+ change CallAction.read (cp.reg (reg 0)) _ = _
+ simp [cp, Config.put, hdst]
+ have s3 : M.program.step cr = .localStep ca := by
+ rw [step_at hl 3 cr rfl]
+ change CallAction.localStep (cr.put (pc 4) (reg 4) (cr.reg (reg 4) + cr.reg (reg 5))) = _
+ simp [ca, cr, cp, Config.put]
+ have s4 : M.program.step ca = .write (word w dst) (m dst + gain) cw := by
+ rw [step_at hl 4 ca rfl]
+ change CallAction.write (ca.reg (reg 0)) (ca.reg (reg 4)) cw = _
+ simp [ca, cr, cp, Config.put, hdst]
+ have s5 : M.program.step cw = .localStep cd := by
+ rw [step_at hl 5 cw rfl]
+ change CallAction.localStep (cw.put (pc 6) (reg 0) (cw.reg (reg 0) + cw.reg (reg 3))) = _
+ simp [cd, cw, ca, cr, cp, Config.put, hdst, hone, word]
+ have s6 : M.program.step cd = .localStep (nextConfig c pc reg src dst (m dst)) := by
+ rw [step_at hl 6 cd rfl]
+ change CallAction.localStep (cd.put (pc 0) (reg 2) (cd.reg (reg 2) + cd.reg (reg 3))) = _
+ simp [nextConfig, cd, ca, cr, cp, Config.put, hsrc, hone, word, gain]
+ dsimp only
+ rw [local_step s0, local_step s1, read_step s2, val_word hd, local_step s3, write_step s4,
+ local_step s5, local_step s6]
+ simp [Option.map_map, Function.comp_def, Report.prepend, componentEvents, gain]
+
+/-- Accumulation at consecutive addresses with the original memory elsewhere. -/
+def addRange (src dst n : ℕ) (priv : Word w → Word w) (m : Memory w) (a : ℕ) : Word w :=
+ if dst ≤ a ∧ a < dst+n then m a + priv (word w (src+(a-dst))) else m a
+
+private theorem range_succ (src dst n : ℕ) (hd : dst < 2 ^ w) (priv : Word w → Word w)
+ (m : Memory w) :
+ addRange (src+1) (dst+1) n priv (writeMemory m (word w dst) (m dst+priv (word w src))) =
+ addRange src dst (n+1) priv m := by
+ funext a
+ by_cases ha : a = dst
+ · subst a
+ simp [addRange, writeMemory, val_word hd]
+ · simp only [addRange, writeMemory, val_word hd, ha, ↓reduceIte]
+ split_ifs with h h' h' <;> first | rfl | (congr 3; omega)
+
+/-- Genuine chronological transcript of all component updates, including the last loop test. -/
+def events (priv : Word w → Word w) (m : Memory w) (src dst : ℕ) : ℕ → List (Event w)
+ | 0 => [.tick]
+ | n+1 =>
+ let gain := priv (word w src)
+ componentEvents (word w dst) (m dst) gain ++
+ events priv (writeMemory m (word w dst) (m dst+gain)) (src+1) (dst+1) n
+
+theorem events_cost (priv : Word w → Word w) (m : Memory w) (src dst n : ℕ) :
+ (events priv m src dst n).length = 7*n+1 ∧ countProbes (events priv m src dst n) = 2*n ∧
+ choiceBits (events priv m src dst n) = [] := by
+ induction n generalizing m src dst with
+ | zero => exact ⟨rfl,rfl,rfl⟩
+ | succ n ih =>
+ obtain ⟨hl,hp,hb⟩ := ih (writeMemory m (word w dst) (m dst+priv (word w src))) (src+1) (dst+1)
+ simp [events, componentEvents, countProbes, choiceBits, hl, hp, hb]
+ omega
+
+/-- Replaying the burst log at the next call produces exactly the same
+memory as the continuation within the current call. -/
+theorem after_events (priv : Word w → Word w) (m : Memory w) (src dst n : ℕ)
+ (fit : dst + n < 2 ^ w) :
+ after m (events priv m src dst n) = addRange src dst n priv m := by
+ induction n generalizing m src dst with
+ | zero => funext a; simp [after, events, update, addRange]
+ | succ n ih =>
+ rw [events, show ∀ es tail, after m (es ++ tail) = after (after m es) tail by simp [after]]
+ change after (writeMemory m (word w dst) (m dst+priv (word w src))) _ = _
+ rw [ih _ (src+1) (dst+1) (by omega)]
+ exact range_succ _ _ _ (by omega) _ _
+
+/-- Run the whole suffix within the current burst, then pass control to any
+continuation with the updated external memory and original private histogram. -/
+theorem execute_range (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (src dst n : ℕ) (hsrc : src + n < 2 ^ w) (hdst : dst + n < 2 ^ w)
+ (hr : c.reg (reg 0) = word w dst) (he : c.reg (reg 1) = word w (dst + n))
+ (hs : c.reg (reg 2) = word w src) (ho : c.reg (reg 3) = 1) (m : Memory w) :
+ ∃ out, out.pc = done ∧ out.persistent = c.persistent ∧ out.privateMem = c.privateMem ∧
+ out.reg (reg 0) = word w (dst+n) ∧ out.reg (reg 2) = word w (src+n) ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 2 → j ≠ reg 4 → j ≠ reg 5 → out.reg j = c.reg j) ∧
+ ∀ fuel bs, execute M.program (fuel+7*n+1) c m bs =
+ (execute M.program fuel out (addRange src dst n c.privateMem m) bs).map
+ (fun rep ↦ ⟨events c.privateMem m src dst n ++ rep.events, rep.result⟩) := by
+ induction n generalizing c src dst m with
+ | zero =>
+ have h0 : c.reg (reg 0) = c.reg (reg 1) := hr.trans (by simpa using he.symm)
+ have s0 : M.program.step c = .localStep {c with pc := done} := by
+ rw [step_at hl 0 c hc]
+ change CallAction.localStep {c with
+ pc := if c.reg (reg 0) = c.reg (reg 1) then done else pc 1} = _
+ simp [h0]
+ refine ⟨{c with pc := done},rfl,rfl,rfl,by simpa using hr,by simpa using hs,
+ fun _ _ _ _ _ ↦ rfl,?_⟩
+ intro fuel bs
+ have hmem : addRange src dst 0 c.privateMem m = m := by funext a; simp [addRange]
+ simp [local_step s0, hmem, events]
+ rfl
+ | succ n ih =>
+ let next := nextConfig c pc reg src dst (m dst)
+ let m' := writeMemory m (word w dst) (m dst + c.privateMem (word w src))
+ have hn : c.reg (reg 0) ≠ c.reg (reg 1) := by
+ rw [hr, he]
+ intro h
+ have hv := congrArg Fin.val h
+ rw [val_word (by omega : dst < 2^w), val_word hdst] at hv
+ omega
+ have ea : src+1+n = src+(n+1) := by omega
+ have eb : dst+1+n = dst+(n+1) := by omega
+ have other (j : Fin r) (h0 : j ≠ reg 0) (h2 : j ≠ reg 2) (h4 : j ≠ reg 4) (h5 : j ≠ reg 5) :
+ next.reg j = c.reg j := by
+ simp [next, nextConfig, Config.put, Function.update_of_ne, h0, h2, h4, h5]
+ obtain ⟨out,hpc,hpers,hpriv,hd,hs',ho',run⟩ := ih next rfl (src+1) (dst+1) (ea ▸ hsrc)
+ (eb ▸ hdst)
+ (by simp [next, nextConfig, Config.put]) (by rw [other,eb,he] <;> simp)
+ (by simp [next, nextConfig, Config.put]) (by rw [other,ho] <;> simp) m'
+ refine ⟨out,hpc,hpers,hpriv,eb ▸ hd,ea ▸ hs',fun j a b d e ↦ (ho' j a b d e).trans
+ (other j a b d e),?_⟩
+ intro fuel bs
+ rw [show fuel+7*(n+1)+1 = (fuel+7*n+1)+7 by omega,
+ execute_component hl c hc src dst (by omega) hs hr ho hn]
+ change (execute M.program _ next m' bs).map _ = _
+ rw [run]
+ have hm : addRange (src+1) (dst+1) n next.privateMem m' =
+ addRange src dst (n+1) c.privateMem m := range_succ _ _ _ (by omega) _ _
+ rw [hm]
+ simp [Option.map_map, Function.comp_def, events, m', next, nextConfig, Config.put]
+
+/-- Logical effect of a single successful vertex. The label number is an
+offset in the gadget suffix of the contiguous production/gadget array. -/
+def addHistogram {g : ℕ} (base grammar : ℕ) (h : Fin g → ℕ) (m : Memory w) (a : ℕ) : Word w :=
+ if ha : base+grammar ≤ a ∧ a < base+grammar+g then
+ m a + word w (h ⟨a-(base+grammar), by omega⟩)
+ else m a
+
+theorem addHistogram_at {g : ℕ} (base grammar : ℕ) (h : Fin g → ℕ) (m : Memory w) (i : Fin g) :
+ addHistogram base grammar h m (base+grammar+i) = m (base+grammar+i) + word w (h i) := by
+ simp [addHistogram, i.isLt]
+
+theorem addHistogram_outside {g : ℕ} (base grammar : ℕ) (h : Fin g → ℕ) (m : Memory w) (a : ℕ)
+ (ha : a < base + grammar ∨ base + grammar + g ≤ a) : addHistogram base grammar h m a = m a := by
+ have he : ¬ (base+grammar ≤ a ∧ a < base+grammar+g) := by omega
+ simp [addHistogram, he]
+
+private theorem range_eq_histogram {g : ℕ} (base grammar src : ℕ) (h : Fin g → ℕ)
+ (priv : Word w → Word w) (hm : ∀ i : Fin g, priv (word w (src+i)) = word w (h i))
+ (m : Memory w) :
+ addRange src (base+grammar) g priv m = addHistogram base grammar h m := by
+ funext a
+ by_cases ha : base+grammar ≤ a ∧ a < base+grammar+g
+ · let i : Fin g := ⟨a-(base+grammar),by omega⟩
+ have he : base+grammar+i.val = a := by dsimp [i]; omega
+ rw [← he, addHistogram_at]
+ simp [addRange, i.isLt]
+ simpa [word] using hm i
+ · simp [addRange, addHistogram, ha]
+
+/-- Native vertex flush with no new branches. The continuation receives
+the combined histogram and all private state accumulated by the expansion. -/
+theorem execute_vertex_events {g : ℕ} (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (base grammar src : ℕ) (h : Fin g → ℕ) (hpriv : ∀ i : Fin g, c.privateMem (word w (src+i)) =
+ word w (h i))
+ (hsrc : src+g < 2^w) (hdst : base+grammar+g < 2^w)
+ (hr : c.reg (reg 0) = word w (base+grammar)) (he : c.reg (reg 1) = word w (base+grammar+g))
+ (hs : c.reg (reg 2) = word w src) (ho : c.reg (reg 3) = 1) (m : Memory w) :
+ ∃ out es, out.pc = done ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ es = events c.privateMem m src (base+grammar) g ∧
+ es.length = 7*g+1 ∧ countProbes es = 2*g ∧ choiceBits es = [] ∧
+ after m es = addHistogram base grammar h m ∧
+ ∀ fuel bs, execute M.program (fuel+7*g+1) c m bs =
+ (execute M.program fuel out (addHistogram base grammar h m) bs).map
+ (fun rep ↦ ⟨es ++ rep.events, rep.result⟩) := by
+ obtain ⟨out,hpc,hpersist,hmem,_,_,_,run⟩ :=
+ execute_range hl c hc src (base+grammar) g hsrc hdst hr he hs ho m
+ have cost := events_cost c.privateMem m src (base+grammar) g
+ refine ⟨out,_,hpc,hmem,hpersist,rfl,cost.1,cost.2.1,cost.2.2,?_,?_⟩
+ · rw [after_events _ _ _ _ _ hdst, range_eq_histogram base grammar src h _ hpriv m]
+ simpa only [range_eq_histogram base grammar src h _ hpriv m] using run
+
+theorem execute_vertex {g : ℕ} (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (base grammar src : ℕ) (h : Fin g → ℕ) (hpriv : ∀ i : Fin g, c.privateMem (word w (src+i)) =
+ word w (h i))
+ (hsrc : src+g < 2^w) (hdst : base+grammar+g < 2^w)
+ (hr : c.reg (reg 0) = word w (base+grammar)) (he : c.reg (reg 1) = word w (base+grammar+g))
+ (hs : c.reg (reg 2) = word w src) (ho : c.reg (reg 3) = 1) (m : Memory w) :
+ ∃ out es, out.pc = done ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ es.length = 7*g+1 ∧ countProbes es = 2*g ∧ choiceBits es = [] ∧
+ after m es = addHistogram base grammar h m ∧
+ ∀ fuel bs, execute M.program (fuel+7*g+1) c m bs =
+ (execute M.program fuel out (addHistogram base grammar h m) bs).map
+ (fun rep ↦ ⟨es ++ rep.events, rep.result⟩) := by
+ obtain ⟨out, es, pc, mem, state, _, rest⟩ :=
+ execute_vertex_events hl c hc base grammar src h hpriv hsrc hdst hr he hs ho m
+ exact ⟨out, es, pc, mem, state, rest⟩
+
+/-- Entry code from a vertex continuation. Its four parameter words give
+the shared base, production count, gadget count, and private histogram base.
+The total width is part of the fixed problem's parameters. -/
+def entryCode (atPC : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (param : Fin 4 → Fin k)
+ (loop : Fin p) : Fin 7 → Instr w p r k :=
+ ![.publicWord (reg 0) (param 0) (atPC 1), .publicWord (reg 4) (param 1) (atPC 2),
+ .binary .add (reg 0) (reg 0) (reg 4) (atPC 3), .publicWord (reg 1) (param 2) (atPC 4),
+ .binary .add (reg 1) (reg 0) (reg 1) (atPC 5), .publicWord (reg 2) (param 3) (atPC 6),
+ .constant (reg 3) 1 loop]
+
+/-- The full flush starts at its first public-word instruction. Every
+register may hold arbitrary data left by the preceding vertex expansion.
+The parameter loads cost seven local steps once for the whole suffix. -/
+theorem execute_flush {g : ℕ} (hl : Linked M pc reg done) (atPC : Fin 7 → Fin p) (param : Fin 4
+ → Fin k)
+ (hcode : ∀ i, M.code (atPC i) = entryCode atPC reg param (pc 0) i)
+ (c : Config w p r) (hc : c.pc = atPC 0) (base grammar src : ℕ)
+ (hbase : M.publicData (param 0) = word w base) (hgrammar : M.publicData (param 1) =
+ word w grammar)
+ (hg : M.publicData (param 2) = word w g) (hprivate : M.publicData (param 3) = word w src)
+ (h : Fin g → ℕ) (hpriv : ∀ i : Fin g, c.privateMem (word w (src+i)) = word w (h i))
+ (hsrc : src+g < 2^w) (hdst : base+grammar+g < 2^w) (m : Memory w) :
+ ∃ out es, out.pc = done ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ es.length = 7*g+8 ∧ countProbes es = 2*g ∧ choiceBits es = [] ∧
+ after m es = addHistogram base grammar h m ∧
+ ∀ fuel bs, execute M.program (fuel+7*g+8) c m bs =
+ (execute M.program fuel out (addHistogram base grammar h m) bs).map
+ (fun rep ↦ ⟨es ++ rep.events, rep.result⟩) := by
+ have step (i : Fin 7) (d : Config w p r) (hp : d.pc = atPC i) :
+ M.program.step d = (entryCode atPC reg param (pc 0) i).run M.publicData d := by
+ simp [Machine.program, hp, hcode i]
+ let c1 := c.put (atPC 1) (reg 0) (M.publicData (param 0))
+ let c2 := c1.put (atPC 2) (reg 4) (M.publicData (param 1))
+ let c3 := c2.put (atPC 3) (reg 0) (c2.reg (reg 0)+c2.reg (reg 4))
+ let c4 := c3.put (atPC 4) (reg 1) (M.publicData (param 2))
+ let c5 := c4.put (atPC 5) (reg 1) (c4.reg (reg 0)+c4.reg (reg 1))
+ let c6 := c5.put (atPC 6) (reg 2) (M.publicData (param 3))
+ let start := c6.put (pc 0) (reg 3) 1
+ let ticks : List (Event w) := [.tick,.tick,.tick,.tick,.tick,.tick,.tick]
+ have pre : PrimedCounter.GuessWord.Prefix M c ticks start :=
+ .tick (step 0 c hc) (.tick (step 1 c1 rfl) (.tick (step 2 c2 rfl) (.tick (step 3 c3 rfl)
+ (.tick (step 4 c4 rfl) (.tick (step 5 c5 rfl) (.tick (step 6 c6 rfl) (.nil start)))))))
+ have hr : start.reg (reg 0) = word w (base+grammar) := by
+ simp [start, c6, c5, c4, c3, c2, c1, Config.put, hbase, hgrammar, word]
+ have he : start.reg (reg 1) = word w (base+grammar+g) := by
+ simp [start, c6, c5, c4, c3, c2, c1, Config.put, hbase, hgrammar, hg, word]
+ have hs : start.reg (reg 2) = word w src := by simp [start, c6, Config.put, hprivate]
+ obtain ⟨out,es,ho,hm,hp,hlen,hpr,hb,ha,hex⟩ := execute_vertex hl start rfl base grammar src h
+ hpriv hsrc hdst hr he hs (by simp [start]) m
+ refine ⟨out,ticks++es,ho,hm,hp,by simp [ticks, hlen],hpr,hb,ha,?_⟩
+ intro fuel bs
+ have pref := pre.execute (fuel+7*g+1) m bs
+ change execute M.program (fuel+7*g+1+7) c m bs = _ at pref
+ rw [show fuel+7*g+8 = fuel+7*g+1+7 by omega, pref, hex]
+ simp [Option.map_map, Function.comp_def, ticks]
+
+private def entryPC (i : Fin 7) : Fin 15 := ⟨i.val,by omega⟩
+private def loopPC (i : Fin 7) : Fin 15 := ⟨7+i.val,by omega⟩
+
+/-- Fixed finite table for the complete flush with an accepting exit. The
+linked version can replace the exit with the caller's next instruction. -/
+def template : Template 15 6 4 where
+ entry := entryPC 0
+ literalWidth := 1
+ code j := if hj : j.val < 7 then
+ entryCode entryPC (Function.Embedding.refl _) id (loopPC 0) ⟨j.val,hj⟩
+ else if hj' : j.val < 14 then
+ instruction loopPC (Function.Embedding.refl _) 14 ⟨j.val-7,by omega⟩
+ else .accept
+
+/-- Concrete instantiation at an arbitrary word width and a vertex's actual
+private memory. The deterministic halt includes the final instruction. -/
+theorem template_execute {g : ℕ} (base grammar src : ℕ) (h : Fin g → ℕ)
+ (c : Config w 15 6) (hc : c.pc = template.entry)
+ (hpriv : ∀ i : Fin g, c.privateMem (word w (src+i)) = word w (h i))
+ (hsrc : src+g < 2^w) (hdst : base+grammar+g < 2^w) (m : Memory w) :
+ let data := ![word w base, word w grammar, word w g, word w src]
+ let T := template.instantiate w data
+ ∃ es, execute T.program (7*g+9) c m [] = some ⟨es,none⟩ ∧
+ es.length = 7*g+8 ∧ countProbes es = 2*g ∧ choiceBits es = [] ∧
+ after m es = addHistogram base grammar h m := by
+ let data := ![word w base, word w grammar, word w g, word w src]
+ let T := template.instantiate w data
+ have hl : Linked T loopPC (Function.Embedding.refl _) 14 := by intro i; fin_cases i <;> rfl
+ have hentry (i : Fin 7) : T.code (entryPC i) =
+ entryCode entryPC (Function.Embedding.refl _) id (loopPC 0) i := by fin_cases i <;> rfl
+ obtain ⟨out,es,ho,_,_,hlen,hp,hb,hm,run⟩ := execute_flush hl entryPC id hentry c hc
+ base grammar src rfl rfl rfl rfl h hpriv hsrc hdst m
+ refine ⟨es,?_,hlen,hp,hb,hm⟩
+ change execute T.program (7*g+9) c m [] = _
+ have hs : T.program.step out = .finish none := by
+ change (T.code out.pc).run T.publicData out = _
+ rw [ho]
+ rfl
+ rw [show 7*g+9 = 1+7*g+8 by omega, run 1 [], execute, hs]
+ simp
+
+/-- Fold the effects of the per-vertex continuations in visit order. -/
+def visit {V : Type*} {g : ℕ} (base grammar : ℕ) (h : V → Fin g → ℕ) (vs : List V) (m : Memory w) :=
+ vs.foldl (fun acc v ↦ addHistogram base grammar (h v) acc) m
+
+theorem visit_at {V : Type*} {g : ℕ} (base grammar : ℕ) (h : V → Fin g → ℕ) (vs : List V)
+ (m : Memory w) (i : Fin g) :
+ visit base grammar h vs m (base+grammar+i) =
+ m (base+grammar+i) + word w ((vs.map fun v ↦ h v i).sum) := by
+ induction vs generalizing m with
+ | nil => simp [visit, word]
+ | cons v vs ih =>
+ change visit base grammar h vs (addHistogram base grammar (h v) m) _ = _
+ rw [ih, addHistogram_at]
+ simp [word, add_assoc]
+
+theorem visit_outside {V : Type*} {g : ℕ} (base grammar : ℕ) (h : V → Fin g → ℕ) (vs : List V)
+ (m : Memory w) (a : ℕ) (ha : a < base + grammar ∨ base + grammar + g ≤ a) :
+ visit base grammar h vs m a = m a := by
+ induction vs generalizing m with
+ | nil => rfl
+ | cons v vs ih =>
+ change visit base grammar h vs (addHistogram base grammar (h v) m) a = _
+ rw [ih, addHistogram_outside _ _ _ _ _ ha]
+
+/-- The production nomination at every prefix address survives all vertex bursts. -/
+theorem nomination_preserved {V : Type*} {g : ℕ} (base grammar : ℕ) (h : V → Fin g → ℕ)
+ (vs : List V) (m : Memory w) (i : Fin grammar) :
+ visit base grammar h vs m (base+i) = m (base+i) :=
+ visit_outside _ _ _ _ _ _ (Or.inl (Nat.add_lt_add_left i.isLt base))
+
+/-- Any prefix of the selected visit order has exact natural-valued counters.
+Bounding the total by R² bounds every intermediate coordinate by the same
+2r-bit capacity, independently of the order of the visits. -/
+theorem prefix_fits {V : Type*} {g r' : ℕ} (base grammar : ℕ) (h : V → Fin g → ℕ)
+ (first rest : List V) (m : Memory w) (i : Fin g) (hz : m (base + grammar + i) = 0)
+ (hw : 2 * r' ≤ w) (bound : ((first ++ rest).map fun v ↦ h v i).sum < (2 ^ r') ^ 2) :
+ (visit base grammar h first m (base+grammar+i)).val = (first.map fun v ↦ h v i).sum ∧
+ (visit base grammar h first m (base+grammar+i)).val < 2^(2*r') := by
+ rw [List.map_append, List.sum_append, ← pow_mul, Nat.mul_comm r' 2] at bound
+ have hsum : (first.map fun v ↦ h v i).sum < 2^(2*r') := by omega
+ have hfit := hsum.trans_le (Nat.pow_le_pow_right (by decide : 0 < 2) hw)
+ rw [visit_at, hz, zero_add, val_word hfit]
+ exact ⟨rfl, hsum⟩
+
+open NetworkKernel
+
+/-- At a vertex the old stored word plus the current natural increment is
+the next word's natural value. It is at most the total and fits in 2r bits. -/
+theorem component_no_overflow {V : Type*} {g r' : ℕ} (base grammar : ℕ) (h : V → Fin g → ℕ)
+ (first rest : List V) (v : V) (m : Memory w) (i : Fin g) (hz : m (base + grammar + i) = 0)
+ (hw : 2 * r' ≤ w) (bound : ((first ++ v::rest).map fun u ↦ h u i).sum < (2 ^ r') ^ 2) :
+ let old := visit base grammar h first m (base+grammar+i)
+ let new := visit base grammar h (first++[v]) m (base+grammar+i)
+ new.val = old.val + h v i ∧ new.val ≤ ((first ++ v::rest).map fun u ↦ h u i).sum ∧
+ new.val < 2^(2*r') := by
+ dsimp only
+ have hpre := prefix_fits base grammar h first (v::rest) m i hz hw bound
+ have hnext := prefix_fits base grammar h (first++[v]) rest m i hz hw
+ (by simpa only [List.append_assoc,
+ List.cons_append, List.nil_append] using bound)
+ rw [hpre.1, hnext.1]
+ refine ⟨?_, ?_, hnext.1 ▸ hnext.2⟩ <;> simp [List.map_append, List.sum_append]
+
+/-- Lemma 10.1 initializes every gadget counter to zero when the suffix
+starts beyond the prescribed header addresses. -/
+theorem initial_suffix_zero {g : ℕ} (S base grammar : ℕ) (header : ℕ → Word w)
+ (hseparate : S ≤ base + grammar) (i : Fin g) :
+ RAMMemory.initialMemory S header (base+grammar+i) = 0 := by
+ simp [RAMMemory.initialMemory, show ¬ base+grammar+i < S by omega]
+
+section History
+
+open LocalHistory
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+
+/-- Final-vertex private histograms in the actual descriptor's visit order.
+A selector descends only into its selected term, whose witnesses already
+include the local maps and all the children placed at that site. -/
+noncomputable def vertexHistograms {N : Network} (H : History A N) (K : H.KernelWitnesses κ)
+ (desc : Readers H K) (F : Factors A N) (W : ∀ v z, MonomialWitness κ (F v z))
+ (p : (H.expandedWitness K F W).Choice) : List (Label → ℕ) := by
+ induction H with
+ | @stop N =>
+ let q := History.stopChoice K F W p
+ exact List.ofFn (fun i ↦ (W (desc.2.1.entries i)
+ (WireTensor.edgeAssignment N.src N.dst q.1 (desc.2.1.entries i))).exponents (q.2
+ (desc.2.1.entries i)))
+ | branch s tail ih =>
+ let q := History.branchChoice s tail K F W p
+ exact ih q.1 (K.2 q.1) (desc.2.2.2.2 q.1) ((s.term q.1).push F)
+ ((s.term q.1).pushWitness F W (K.1 q.1)) q.2
+
+/-- Summing the completed private histograms gives the formal monomial
+exponent of the selected occurrence, including syntactically nonzero
+monomials whose evaluated scalar may vanish. -/
+theorem vertexHistograms_sum {N : Network} (H : History A N) (K : H.KernelWitnesses κ)
+ (desc : Readers H K) (F : Factors A N) (W : ∀ v z, MonomialWitness κ (F v z))
+ (p : (H.expandedWitness K F W).Choice) (l : Label) :
+ ((vertexHistograms H K desc F W p).map fun h ↦ h l).sum = (H.expandedWitness K F W).exponents
+ p l := by
+ induction H with
+ | @stop N =>
+ obtain ⟨⟨z,x⟩,rfl⟩ := (History.stopChoice K F W).symm.surjective p
+ rw [vertexHistograms, List.map_ofFn, List.sum_ofFn, History.stopChoice_exponents]
+ exact desc.2.1.entries.sum_comp (fun v ↦ (W v (WireTensor.edgeAssignment N.src N.dst z
+ v)).exponents (x v) l)
+ | branch s tail ih =>
+ obtain ⟨⟨i,q⟩,rfl⟩ := (History.branchChoice s tail K F W).symm.surjective p
+ rw [vertexHistograms, History.branchChoice_exponents]
+ exact ih i _ _ _ _ q
+
+/-- The physical suffix and the formal ν(e) agree for every selected
+history. A bound on *total* degree gives exact readback of every coordinate
+in the 2r-bit output convention. -/
+theorem history_readback {N : Network} (H : History A N) (K : H.KernelWitnesses κ)
+ (desc : Readers H K) (F : Factors A N) (W : ∀ v z, MonomialWitness κ (F v z))
+ (p : (H.expandedWitness K F W).Choice) {g : ℕ} (labels : Fin g ≃ Label) (base grammar r' : ℕ)
+ (m : Memory w) (hz : ∀ i : Fin g, m (base+grammar+i) = 0) (hw : 2*r' ≤ w)
+ (bound : (∑ l, (H.expandedWitness K F W).exponents p l) < (2^r')^2) (i : Fin g) :
+ (visit base grammar (fun (h : Label → ℕ) j ↦ h (labels j))
+ (vertexHistograms H K desc F W p) m (base+grammar+i)).val =
+ (H.expandedWitness K F W).exponents p (labels i) := by
+ have hsum := vertexHistograms_sum H K desc F W p (labels i)
+ have coord := Finset.single_le_sum (s := Finset.univ)
+ (fun (l : Label) _ ↦ Nat.zero_le ((H.expandedWitness K F W).exponents p l)) (Finset.mem_univ
+ (labels i))
+ refine (prefix_fits base grammar (fun (h : Label → ℕ) j ↦ h (labels j))
+ (vertexHistograms H K desc F W p) [] m i (hz i) hw ?_).1.trans hsum
+ rw [List.append_nil, hsum]
+ exact coord.trans_lt bound
+
+/-- Readback in the live exponent routine's single contiguous array. Its
+first coordinates are the already nominated µ words and the remaining
+coordinates are exactly ν(e) for the chosen compression occurrence. -/
+theorem live_array_readback {N : Network} (H : History A N) (K : H.KernelWitnesses κ)
+ (desc : Readers H K) (F : Factors A N) (W : ∀ v z, MonomialWitness κ (F v z))
+ (p : (H.expandedWitness K F W).Choice) {g grammar r' : ℕ} (labels : Fin g ≃ Label)
+ (base : Word w)
+ (fit : base.val + grammar ≤ 2 ^ w) (μ : Fin grammar → Word (2 * r')) (m : Memory w)
+ (hz : ∀ i : Fin g, m (base.val+grammar+i) = 0) (hw : 2*r' ≤ w)
+ (bound : (∑ l, (H.expandedWitness K F W).exponents p l) < (2^r')^2) (j : Fin (grammar+g)) :
+ let initial := LiveNominations.stored base fit μ m
+ let final := visit base.val grammar (fun (h : Label → ℕ) i ↦ h (labels i))
+ (vertexHistograms H K desc F W p) initial
+ (final (base.val+j)).val = Fin.addCases (fun i ↦ (μ i).val)
+ (fun i ↦ (H.expandedWitness K F W).exponents p (labels i)) j := by
+ dsimp only
+ cases j using Fin.addCases with
+ | left i =>
+ rw [Fin.addCases_left]
+ change (visit _ _ _ _ _ (base.val+i.val)).val = _
+ rw [nomination_preserved, LiveNominations.stored_at, Fin.val_ofNat,
+ Nat.mod_eq_of_lt ((μ i).isLt.trans_le (Nat.pow_le_pow_right (by decide) hw))]
+ | right i =>
+ rw [Fin.addCases_right]
+ change (visit _ _ _ _ _ (base.val+(grammar+i.val))).val = _
+ rw [← Nat.add_assoc]
+ apply history_readback H K desc F W p labels base.val grammar r' _ _ hw bound i
+ intro l
+ rw [LiveNominations.stored_outside _ _ _ _ _ (Or.inr (by omega)), hz]
+
+end History
+
+end PairSimulation.Counters
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationDFS.lean b/lean/OAI/Computability/VPVNP/PairSimulationDFS.lean
new file mode 100644
index 0000000000..ea913e08d4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationDFS.lean
@@ -0,0 +1,296 @@
+import OAI.Computability.VPVNP.PairSimulationEndpointBits
+import OAI.Computability.VPVNP.PairSimulationHistory
+
+/-!
+# Traversing stored child lists inside a final-vertex burst
+
+The private stack grows downward. After a vertex has been popped, a contiguous
+private interval immediately before the pending suffix receives its child
+descriptor addresses in increasing list order. This uses one external read per
+child and leaves the pending suffix and the rest of private memory untouched.
+The next pop therefore visits the first child.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.DFS
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+
+private theorem val_word {n : ℕ} (h : n < 2^w) : (word w n).val = n := Nat.mod_eq_of_lt h
+
+/-- The live stack, from the first pending visit through the last. -/
+def Represents (priv : Word w → Word w) (top : ℕ) (xs : List (Word w)) : Prop :=
+ top + xs.length < 2^w ∧ ∀ i : Fin xs.length, priv (word w (top+i.val)) = xs[i.val]
+
+theorem represents_cons {priv : Word w → Word w} {top : ℕ} {x : Word w} {xs : List (Word w)}
+ (h : Represents priv top (x :: xs)) : priv (word w top) = x ∧ Represents priv (top+1) xs := by
+ refine ⟨by simpa using h.2 0, by simpa [Nat.add_assoc, Nat.add_comm 1] using h.1, ?_⟩
+ intro i
+ have hi : i.val+1 < (x::xs).length := by simp
+ simpa [Nat.add_assoc, Nat.add_comm 1] using h.2 ⟨i.val+1, hi⟩
+
+/-- The stored count and row pointer of a descriptor. -/
+def Row (m : Memory w) (node src : ℕ) (kids : List (Word w)) : Prop :=
+ node+1 < 2^w ∧ src+kids.length < 2^w ∧
+ m node = word w src ∧ m (node+1) = word w kids.length ∧ ∀ i : Fin kids.length, m (src+i.val) = kids[i.val]
+
+private theorem copy_children {m : Memory w} {node src top : ℕ} {xs kids : List (Word w)}
+ {priv : Word w → Word w} (hstack : Represents priv top xs) (hr : Row m node src kids)
+ (hspace : kids.length ≤ top) :
+ Represents (EndpointBits.copySlice m src (top - kids.length) kids.length priv) (top - kids.length) (kids ++ xs) := by
+ obtain ⟨hfit, hcells⟩ := hstack
+ obtain ⟨_, _, _, _, hk⟩ := hr
+ have htop : top - kids.length + kids.length = top := Nat.sub_add_cancel hspace
+ constructor
+ · rw [List.length_append, ← Nat.add_assoc, htop]; exact hfit
+ · intro i
+ have hi : i.val < kids.length + xs.length := by simpa using i.isLt
+ have ha : top - kids.length + i.val < 2^w := by omega
+ unfold EndpointBits.copySlice
+ simp only [val_word ha]
+ by_cases h : i.val < kids.length
+ · rw [ite_eq_left (by omega), List.getElem_append_left h]
+ simpa using hk ⟨i.val,h⟩
+ · rw [ite_eq_right (by omega), List.getElem_append_right (by omega)]
+ have he : top - kids.length + i.val = top + (i.val-kids.length) := by omega
+ rw [he]
+ exact hcells ⟨i.val-kids.length, by omega⟩
+
+/-- Registers 0–4 are shared with the contiguous copy loop. Registers 5–8
+hold the stack top, stack end, popped descriptor, and child count. -/
+def instruction (pc : Fin 9 → Fin p) (reg : Fin 9 ↪ Fin r) (visit copy done : Fin p) : Fin 9 → Instr w p r k :=
+ ![.jumpEq (reg 5) (reg 6) done (pc 1), .loadPrivate (reg 7) (reg 5) (pc 2),
+ .binary .add (reg 5) (reg 5) (reg 3) visit,
+ .readExternal (reg 0) (reg 7) (pc 4), .binary .add (reg 4) (reg 7) (reg 3) (pc 5),
+ .readExternal (reg 8) (reg 4) (pc 6), .binary .sub (reg 5) (reg 5) (reg 8) (pc 7),
+ .copy (reg 2) (reg 5) (pc 8), .binary .add (reg 1) (reg 0) (reg 8) copy]
+
+theorem resize_instruction (pc : Fin 9 → Fin p) (reg : Fin 9 ↪ Fin r) (visit copy done : Fin p) (i : Fin 9) :
+ (instruction (w := 1) (k := k) pc reg visit copy done i).resize w = instruction pc reg visit copy done i := by
+ fin_cases i <;> rfl
+
+/-- Require the nine dispatcher instructions at the specified program counters and registers.
+They pop a node, transfer control to `visit`, prepare its child interval for `copy`, and
+jump to `done` on an empty stack. -/
+def Linked (M : Machine w p r k) (pc : Fin 9 → Fin p) (reg : Fin 9 ↪ Fin r)
+ (visit copy done : Fin p) := ∀ i, M.code (pc i) = instruction pc reg visit copy done i
+
+variable {M : Machine w p r k} {pc : Fin 9 → Fin p} {reg : Fin 9 ↪ Fin r} {visit copy done : Fin p}
+
+private theorem step_at (h : Linked M pc reg visit copy done) (c : Config w p r) (i : Fin 9)
+ (hc : c.pc = pc i) : M.program.step c = (instruction pc reg visit copy done i).run M.publicData c := by
+ simp [Machine.program, hc, h i]
+
+private abbrev copyRegs (reg : Fin 9 ↪ Fin r) : Fin 5 ↪ Fin r := (Fin.castAddEmb 4).trans reg
+
+/-- The empty stack enters the continuation with one deterministic test. -/
+theorem execute_empty (hl : Linked M pc reg visit copy done) (c : Config w p r) (hc : c.pc = pc 0)
+ (he : c.reg (reg 5) = c.reg (reg 6)) (fuel : ℕ) (m : Memory w) (bs : List Bool) :
+ execute M.program (fuel+1) c m bs =
+ (execute M.program fuel {c with pc := done} m bs).map (Report.prepend .tick) := by
+ have hs : M.program.step c = .localStep {c with pc := done} := by
+ rw [step_at hl c 0 hc]
+ simp [instruction, Instr.run, he]
+ simp only [execute, hs]
+
+/-- One pop selects the descriptor at the top and passes the remaining stack
+to the vertex code. This step consumes no binary choice or external probe. -/
+theorem execute_pop (hl : Linked M pc reg visit copy done) (c : Config w p r) (hc : c.pc = pc 0)
+ (top : ℕ) (x : Word w) (xs : List (Word w)) (hstack : Represents c.privateMem top (x::xs))
+ (ht : c.reg (reg 5) = word w top) (he : c.reg (reg 6) = word w (top+(x::xs).length))
+ (h1 : c.reg (reg 3) = 1) :
+ ∃ out, out.pc = visit ∧ out.reg (reg 5) = word w (top+1) ∧ out.reg (reg 7) = x ∧
+ (∀ i, i ≠ reg 5 → i ≠ reg 7 → out.reg i = c.reg i) ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent ∧ Represents out.privateMem (top+1) xs ∧
+ ∀ fuel m bs, execute M.program (fuel+3) c m bs =
+ (execute M.program fuel out m bs).map (fun r => ⟨[.tick,.tick,.tick] ++ r.events,r.result⟩) := by
+ let c₁ := {c with pc := pc 1}
+ let c₂ := c₁.put (pc 2) (reg 7) x
+ let out := c₂.put visit (reg 5) (word w (top+1))
+ have hn : c.reg (reg 5) ≠ c.reg (reg 6) := by
+ rw [ht,he]
+ intro h
+ have hf := hstack.1
+ have hh := congrArg Fin.val h
+ rw [val_word (by omega : top < 2^w), val_word hf] at hh
+ simp at hh
+ have hs₀ : M.program.step c = .localStep c₁ := by rw [step_at hl c 0 hc]; simp [instruction, Instr.run, hn,c₁]
+ have hs₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at hl c₁ 1 rfl]
+ change CallAction.localStep (c₁.put (pc 2) (reg 7) (c.privateMem (c.reg (reg 5)))) = _
+ rw [ht, (represents_cons hstack).1]
+ have hs₂ : M.program.step c₂ = .localStep out := by
+ rw [step_at hl c₂ 2 rfl]
+ change CallAction.localStep (c₂.put visit (reg 5) (c₂.reg (reg 5) + c₂.reg (reg 3))) = _
+ simp [c₂,c₁,Config.put,ht,h1,out,word]
+ refine ⟨out,rfl,by simp [out],by simp [out,c₂,Config.put],?_,rfl,rfl,(represents_cons hstack).2,?_⟩
+ · intro i h5 h7
+ simp [out,c₂,c₁,Config.put,Function.update_of_ne h5,Function.update_of_ne h7]
+ · intro fuel m bs
+ simp [execute, hs₀, hs₁, hs₂, Option.map_map, Function.comp_def, Report.prepend]
+
+private def prepared (c : Config w p r) (pc : Fin 9 → Fin p) (reg : Fin 9 ↪ Fin r)
+ (copy : Fin p) (node src top count : ℕ) : Config w p r :=
+ let c₄ := c.put (pc 4) (reg 0) (word w src)
+ let c₅ := c₄.put (pc 5) (reg 4) (word w (node+1))
+ let c₆ := c₅.put (pc 6) (reg 8) (word w count)
+ let c₇ := c₆.put (pc 7) (reg 5) (word w (top-count))
+ let c₈ := c₇.put (pc 8) (reg 2) (word w (top-count))
+ c₈.put copy (reg 1) (word w (src+count))
+
+private def headerEvents (w node src count : ℕ) : List (Event w) :=
+ [.read (word w node) (word w src), .tick, .read (word w (node+1)) (word w count), .tick, .tick, .tick]
+
+private theorem prepare_execute (hl : Linked M pc reg visit copy done) (c : Config w p r) (hc : c.pc = pc 3)
+ (m : Memory w) (node src top : ℕ) (kids : List (Word w)) (hr : Row m node src kids)
+ (hnode : c.reg (reg 7) = word w node) (ht : c.reg (reg 5) = word w top)
+ (hone : c.reg (reg 3) = 1) (space : kids.length ≤ top) (fuel : ℕ) (bs : List Bool) :
+ execute M.program (fuel+6) c m bs =
+ (execute M.program fuel (prepared c pc reg copy node src top kids.length) m bs).map
+ (fun rep => ⟨headerEvents w node src kids.length ++ rep.events, rep.result⟩) := by
+ let c₄ := c.put (pc 4) (reg 0) (word w src)
+ let c₅ := c₄.put (pc 5) (reg 4) (word w (node+1))
+ let c₆ := c₅.put (pc 6) (reg 8) (word w kids.length)
+ let c₇ := c₆.put (pc 7) (reg 5) (word w (top-kids.length))
+ let c₈ := c₇.put (pc 8) (reg 2) (word w (top-kids.length))
+ have s₃ : M.program.step c = .read (word w node) (fun t => c.put (pc 4) (reg 0) t) := by
+ rw [step_at hl c 3 hc]; simp [instruction,Instr.run,hnode]
+ have s₄ : M.program.step c₄ = .localStep c₅ := by
+ rw [step_at hl c₄ 4 rfl]
+ change CallAction.localStep (c₄.put (pc 5) (reg 4) (c₄.reg (reg 7) + c₄.reg (reg 3))) = _
+ simp [c₄,c₅,Config.put,hnode,hone,word]
+ have s₅ : M.program.step c₅ = .read (word w (node+1)) (fun t => c₅.put (pc 6) (reg 8) t) := by
+ rw [step_at hl c₅ 5 rfl]; simp [instruction, Instr.run,c₅]
+ have s₆ : M.program.step c₆ = .localStep c₇ := by
+ rw [step_at hl c₆ 6 rfl]
+ change CallAction.localStep (c₆.put (pc 7) (reg 5) (c₆.reg (reg 5) - c₆.reg (reg 8))) = _
+ simp [c₄,c₅,c₆,c₇,Config.put,ht,word,Nat.cast_sub space]
+ have s₇ : M.program.step c₇ = .localStep c₈ := by
+ rw [step_at hl c₇ 7 rfl]; simp [instruction,Instr.run,c₇,c₈]
+ have s₈ : M.program.step c₈ = .localStep (prepared c pc reg copy node src top kids.length) := by
+ rw [step_at hl c₈ 8 rfl]
+ change CallAction.localStep (c₈.put copy (reg 1) (c₈.reg (reg 0) + c₈.reg (reg 8))) = _
+ simp [c₈,c₇,c₆,c₅,c₄,Config.put,prepared,word]
+ have read₃ : m (word w node).val = word w src := by rw [val_word (by have := hr.1; omega : node < 2^w)]; exact hr.2.2.1
+ have read₅ : m (word w (node+1)).val = word w kids.length := by rw [val_word hr.1]; exact hr.2.2.2.1
+ have eq₄ : c.put (pc 4) (reg 0) (word w src) = c₄ := rfl
+ have eq₆ : c₅.put (pc 6) (reg 8) (word w kids.length) = c₆ := rfl
+ simp only [execute, s₃, read₃, eq₄, s₄, s₅, read₅, eq₆, s₆, s₇, s₈]
+ simp [Option.map_map, Function.comp_def, Report.prepend, headerEvents]
+
+/-- The descriptor header costs two probes, and the loop fetches each child
+address once. The returned stack begins with the complete ordered child
+list, followed by the original pending vertices. -/
+theorem execute_children {arcPC : Fin 5 → Fin p} (hl : Linked M pc reg visit (arcPC 0) done)
+ (ha : EndpointBits.Linked M arcPC (copyRegs reg) (pc 0)) (c : Config w p r) (hc : c.pc = pc 3)
+ (m : Memory w) (node src top : ℕ) (kids pending : List (Word w))
+ (hr : Row m node src kids) (hstack : Represents c.privateMem top pending)
+ (hnode : c.reg (reg 7) = word w node) (ht : c.reg (reg 5) = word w top)
+ (h1 : c.reg (reg 3) = 1) (hspace : kids.length ≤ top) :
+ ∃ out, out.pc = pc 0 ∧ out.reg (reg 5) = word w (top-kids.length) ∧
+ out.reg (reg 6) = c.reg (reg 6) ∧ out.reg (reg 3) = 1 ∧ out.persistent = c.persistent ∧
+ out.privateMem = EndpointBits.copySlice m src (top-kids.length) kids.length c.privateMem ∧
+ Represents out.privateMem (top-kids.length) (kids ++ pending) ∧
+ ∀ fuel bs, execute M.program (fuel + (5*kids.length+7)) c m bs =
+ (execute M.program fuel out m bs).map (fun rep =>
+ ⟨headerEvents w node src kids.length ++ EndpointBits.events m src kids.length ++ rep.events, rep.result⟩) := by
+ let start := prepared c pc reg (arcPC 0) node src top kids.length
+ have htop : top - kids.length + kids.length = top := Nat.sub_add_cancel hspace
+ have fit : top - kids.length + kids.length < 2^w := by rw [htop]; have := hstack.1; omega
+ obtain ⟨out,hpc,hpriv,_,_,other,hmem,hex⟩ := EndpointBits.execute_arc ha start rfl m src (top-kids.length)
+ kids.length hr.2.1 fit
+ (by change start.reg (reg 0) = _; simp [start,prepared,Config.put])
+ (by change start.reg (reg 1) = _; simp [start,prepared,Config.put])
+ (by change start.reg (reg 2) = _; simp [start,prepared,Config.put])
+ (by change start.reg (reg 3) = _; simp [start,prepared,Config.put,h1])
+ have memEq : out.privateMem = EndpointBits.copySlice m src (top-kids.length) kids.length c.privateMem := hmem
+ refine ⟨out,hpc,?_,?_,?_,hpriv,memEq,memEq ▸ copy_children hstack hr hspace,?_⟩
+ · rw [other (reg 5) (reg.injective.ne (by decide)) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))]
+ simp [start,prepared,Config.put]
+ · rw [other (reg 6) (reg.injective.ne (by decide)) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))]
+ simp [start,prepared,Config.put]
+ · rw [other (reg 3) (reg.injective.ne (by decide)) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))]
+ simp [start,prepared,Config.put,h1]
+ · intro fuel bs
+ rw [show fuel + (5*kids.length+7) = (fuel+5*kids.length+1)+6 by omega,
+ prepare_execute hl c hc m node src top kids hr hnode ht h1 hspace]
+ change (execute M.program (fuel+5*kids.length+1) start m bs).map _ = _
+ rw [hex]
+ simp [Option.map_map,Function.comp_def]
+
+theorem children_probes (m : Memory w) (node src count : ℕ) :
+ countProbes (headerEvents w node src count ++ EndpointBits.events m src count) = 2 + count := by
+ simp [headerEvents, countProbes, EndpointBits.probes, Nat.add_comm, Nat.add_left_comm]
+
+/-- A terminating descent through the actual rows in external memory.
+The list index retains the order of every visit, including multiple visits
+to equal descriptor addresses if the input rows contain duplicates. -/
+inductive Visits (m : Memory w) (endAddr : ℕ) :
+ List (Word w) → List (Word w) → List (Event w) → Prop
+ | nil : Visits m endAddr [] [] [.tick]
+ | cons {node : Word w} {pending kids nodes : List (Word w)} {src : ℕ} {es : List (Event w)}
+ (row : Row m node.val src kids) (fits : kids.length + pending.length ≤ endAddr)
+ (rest : Visits m endAddr (kids ++ pending) nodes es) :
+ Visits m endAddr (node :: pending) (node :: nodes)
+ ([.tick,.tick,.tick] ++ headerEvents w node.val src kids.length ++
+ EndpointBits.events m src kids.length ++ es)
+
+/-- All visits of a finite traversal are realized by the fixed RAM
+dispatcher when the entry hook immediately returns to the child-row scan.
+The continuation may use all remaining fuel and arbitrary branch bits. -/
+theorem execute_visits {arcPC : Fin 5 → Fin p}
+ (hl : Linked M pc reg (pc 3) (arcPC 0) done)
+ (ha : EndpointBits.Linked M arcPC (copyRegs reg) (pc 0))
+ {m : Memory w} {endAddr : ℕ} {pending nodes : List (Word w)} {es : List (Event w)}
+ (visits : Visits m endAddr pending nodes es) (c : Config w p r) (hc : c.pc = pc 0)
+ (top : ℕ) (hstack : Represents c.privateMem top pending)
+ (hptr : top + pending.length = endAddr) (ht : c.reg (reg 5) = word w top)
+ (he : c.reg (reg 6) = word w endAddr) (h1 : c.reg (reg 3) = 1) :
+ ∃ out, out.pc = done ∧ out.reg (reg 5) = word w endAddr ∧ out.persistent = c.persistent ∧
+ ∀ fuel bs, execute M.program (fuel + es.length) c m bs =
+ (execute M.program fuel out m bs).map (fun r => ⟨es ++ r.events, r.result⟩) := by
+ induction visits generalizing c top with
+ | nil =>
+ have htop : top = endAddr := by simpa using hptr
+ refine ⟨{c with pc := done}, rfl, htop ▸ ht, rfl, ?_⟩
+ intro fuel bs
+ exact execute_empty hl c hc (by rw [ht,he,htop]) fuel m bs
+ | @cons node pending kids nodes src es row fits rest ih =>
+ obtain ⟨popped,hpc,hsp,hnode,hreg,hmemory,hstate,hstack',hpop⟩ :=
+ execute_pop hl c hc top node pending hstack ht (hptr ▸ he) h1
+ have hp1 := (hreg (reg 3) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans h1
+ have hp6 := (hreg (reg 6) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans he
+ have hs : kids.length ≤ top+1 := by simp only [List.length_cons] at hptr; omega
+ obtain ⟨next,hpc',ht',he',h1',hp',_,stackNext,hkids⟩ :=
+ execute_children hl ha popped hpc m node.val src (top+1) kids pending row hstack'
+ (hnode.trans (by simp [word])) hsp hp1 hs
+ have ptrNext : top + 1 - kids.length + (kids ++ pending).length = endAddr := by
+ simp only [List.length_append]; simp only [List.length_cons] at hptr; omega
+ obtain ⟨out,hout,htout,hstateout,hex⟩ :=
+ ih next hpc' _ stackNext ptrNext ht' (he'.trans hp6) h1'
+ refine ⟨out,hout,htout,hstateout.trans (hp'.trans hstate),?_⟩
+ intro fuel bs
+ have hlen (m : Memory w) (src n : ℕ) : (EndpointBits.events m src n).length = 5*n+1 := by
+ induction n generalizing src with
+ | zero => rfl
+ | succ n ih => simp [EndpointBits.events,ih]; omega
+ rw [show fuel + (([.tick,.tick,.tick] : List (Event w)) ++ headerEvents w node.val src kids.length ++
+ EndpointBits.events m src kids.length ++ es).length =
+ ((fuel+es.length) + (5*kids.length+7)) + 3 by
+ simp only [List.length_append, headerEvents, List.length_cons, List.length_nil, hlen]; omega]
+ rw [hpop, hkids, hex]
+ simp [Option.map_map, Function.comp_def, List.append_assoc]
+
+end PairSimulation.DFS
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationDFSDecode.lean b/lean/OAI/Computability/VPVNP/PairSimulationDFSDecode.lean
new file mode 100644
index 0000000000..3011f0cbb0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationDFSDecode.lean
@@ -0,0 +1,206 @@
+import OAI.Computability.VPVNP.PairSimulationDFSHooks
+
+/-!
+# Exact-use decoding of linked depth-first calls
+
+For a fixed descriptor tree the node order is deterministic. A local reader
+may reject its remaining stream, or consume a prefix and return the updated
+scratch state. If the linked local instructions realize each successful
+prefix and reject failed reads, the complete native traversal accepts
+exactly the strings that decode through all sites with empty suffix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.DFS
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+open private copyRegs from OAI.Computability.VPVNP.PairSimulationDFS
+
+variable {w p r k : ℕ}
+
+/-- Some fuel suffices to reach an accepting or returning native instruction. -/
+def Returns (M : Machine w p r k) (c : Config w p r) (m : Memory w) (bs : List Bool) : Prop :=
+ ∃ fuel rep, execute M.program fuel c m bs = some rep
+
+private theorem guessed_addFuel {C : Type*} {P : Program w C} {f : ℕ} {c : C} {es : List (Event w)}
+ {res : Option (Word w)} (h : Guessed P f c es res) (extra : ℕ) :
+ Guessed P (extra + f) c es res := by
+ induction h with
+ | done h => exact .done h
+ | step h _ ih => exact .step h ih
+ | branch h _ ih => exact .branch h ih
+ | read h _ ih => exact .read h ih
+ | write h _ ih => exact .write h ih
+
+private theorem returns_prefix {M : Machine w p r k} {c d : Config w p r} {m : Memory w}
+ {bs tail : List Bool} {n : ℕ} {append : Report w → Report w}
+ (h : ∀ f, execute M.program (f + n) c m bs = (execute M.program f d m tail).map append) :
+ Returns M c m bs ↔ Returns M d m tail := by
+ constructor
+ · rintro ⟨f,rep,he⟩
+ obtain ⟨hg,hc,hb⟩ := execute_iff.mp he
+ have big := execute_iff.mpr ⟨guessed_addFuel hg n,hc,hb⟩
+ rw [Nat.add_comm n f,h] at big
+ obtain ⟨out,ho,_⟩ := Option.map_eq_some_iff.mp big
+ exact ⟨f,out,ho⟩
+ · rintro ⟨f,rep,he⟩
+ exact ⟨f+n,append rep,by rw [h,he]; rfl⟩
+
+/-- Branch parser for the descriptor indicated by the top stack word. The
+argument data are the caller's scratch above the reserved stack interval. -/
+structure HookParser (w endAddr : ℕ) where
+ /-- Read one descriptor visit from its node address, the current private scratch and the
+ remaining choice bits. A successful read returns the selected visit path and unused
+ suffix. -/
+ read : Word w → Scratch w endAddr → List Bool → Option (VisitPath w endAddr × List Bool)
+
+/-- Decode the nodes in traversal order. After each successful read, apply that visit's scratch
+update and pass its unused bits to the next node. A failed read rejects the entire list. -/
+def HookParser.decode {endAddr : ℕ} (P : HookParser w endAddr) :
+ List (Word w) → Scratch w endAddr → List Bool → Option (Scratch w endAddr × List Bool)
+ | [], s, bs => some (s,bs)
+ | n :: ns, s, bs => do
+ let (job,tail) ← P.read n s bs
+ P.decode ns (job.update s) tail
+
+/-- The failed-read obligation applies on any incident bits or scratch
+state, including field combinations incompatible across an older wire. -/
+structure HookParser.Exact {endAddr : ℕ} (P : HookParser w endAddr) (M : Machine w p r k)
+ (visit ret : Fin p) (reg : Fin 9 ↪ Fin r) (m : Memory w) : Prop where
+ success : ∀ node s bs job tail, P.read node s bs = some (job,tail) →
+ job.node = node ∧ job.enabled s ∧ bs = choiceBits job.trace ++ tail ∧
+ job.Linked M visit ret reg m
+ reject : ∀ node bs (c : Config w p r) top pending,
+ c.pc = visit → c.reg (reg 7) = node → Represents c.privateMem top pending →
+ top + pending.length = endAddr → c.reg (reg 5) = (top : Word w) → c.reg (reg 6) = (endAddr : Word w) → c.reg (reg 3) = 1 →
+ P.read node (scratch endAddr c.privateMem) bs = none → ¬ Returns M c m bs
+
+/-- Local equivalence on the supplied argument states at a genuine descriptor
+address. The domain can record the private pointer layout and the canonical
+bit words written by the parent without constraining the bit values. -/
+structure HookParser.ExactOn {endAddr : ℕ} (P : HookParser w endAddr)
+ (domain : Word w → Scratch w endAddr → Prop) (M : Machine w p r k)
+ (visit ret : Fin p) (reg : Fin 9 ↪ Fin r) (m : Memory w) : Prop where
+ success : ∀ node s, domain node s → ∀ bs job tail, P.read node s bs = some (job,tail) →
+ job.node = node ∧ job.enabled s ∧ bs = choiceBits job.trace ++ tail ∧
+ job.Linked M visit ret reg m
+ reject : ∀ node bs (c : Config w p r) top pending, domain node (scratch endAddr c.privateMem) →
+ c.pc = visit → c.reg (reg 7) = node → Represents c.privateMem top pending →
+ top + pending.length = endAddr → c.reg (reg 5) = (top : Word w) → c.reg (reg 6) = (endAddr : Word w) → c.reg (reg 3) = 1 →
+ P.read node (scratch endAddr c.privateMem) bs = none → ¬ Returns M c m bs
+
+/-- The invariant is needed at the current visit and, on success, at every
+visit reached from its updated scratch state and unconsumed branch suffix. -/
+def HookParser.ValidAlong {endAddr : ℕ} (P : HookParser w endAddr)
+ (domain : Word w → Scratch w endAddr → Prop) :
+ List (Word w) → Scratch w endAddr → List Bool → Prop
+ | [], _, _ => True
+ | n :: ns, s, bs => domain n s ∧ ∀ job tail, P.read n s bs = some (job,tail) →
+ P.ValidAlong domain ns (job.update s) tail
+
+theorem HookParser.validAlong_of_forall {endAddr : ℕ} (P : HookParser w endAddr)
+ (domain : Word w → Scratch w endAddr → Prop) (ns : List (Word w))
+ (all : ∀ n ∈ ns, ∀ s, domain n s) (s : Scratch w endAddr) (bs : List Bool) :
+ P.ValidAlong domain ns s bs := by
+ induction ns generalizing s bs with
+ | nil => trivial
+ | cons n ns ih => exact ⟨all n List.mem_cons_self s, fun job tail _ =>
+ ih (fun n hn => all n (List.mem_cons_of_mem _ hn)) (job.update s) tail⟩
+
+/-- Both directions of the native whole-call characterization, for
+a terminal continuation that requires exact consumption of the bit stream.
+The proof also handles zero-child rows and zero-bit local checks. -/
+theorem returns_iff_decode_on {M : Machine w p r k} {pc : Fin 9 → Fin p} {arcPC : Fin 5 → Fin p}
+ {reg : Fin 9 ↪ Fin r} {visit done : Fin p} (hl : Linked M pc reg visit (arcPC 0) done)
+ (ha : EndpointBits.Linked M arcPC (copyRegs reg) (pc 0)) {m : Memory w} {endAddr : ℕ}
+ {pending nodes : List (Word w)} {es : List (Event w)}
+ (visits : Visits m endAddr pending nodes es)
+ (P : HookParser w endAddr) {domain : Word w → Scratch w endAddr → Prop}
+ (exactHook : P.ExactOn domain M visit (pc 3) reg m)
+ (terminal : ∀ (c : Config w p r) bs, c.pc = done → (Returns M c m bs ↔ bs = []))
+ (c : Config w p r) (hc : c.pc = pc 0) (top : ℕ) (hstack : Represents c.privateMem top pending)
+ (hptr : top + pending.length = endAddr) (ht : c.reg (reg 5) = (top : Word w))
+ (he : c.reg (reg 6) = (endAddr : Word w)) (h1 : c.reg (reg 3) = 1) (bs : List Bool)
+ (valid : P.ValidAlong domain nodes (scratch endAddr c.privateMem) bs) :
+ Returns M c m bs ↔ ∃ out, P.decode nodes (scratch endAddr c.privateMem) bs = some (out,[]) := by
+ induction visits generalizing c top bs with
+ | nil =>
+ have htop : top = endAddr := by simpa using hptr
+ rw [returns_prefix (fun f => execute_empty hl c hc (by rw [ht,he,htop]) f m bs),
+ terminal _ _ rfl]
+ simp [HookParser.decode]
+ | @cons node pending kids nodes src es row fits rest ih =>
+ obtain ⟨popped,hpc,hsp,hnode,hreg,hpopMem,hstate,hstack',hpop⟩ :=
+ execute_pop hl c hc top node pending hstack ht (hptr ▸ he) h1
+ have hp1 :=
+ (hreg (reg 3) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans h1
+ have hp6 :=
+ (hreg (reg 6) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans he
+ rw [returns_prefix fun f => hpop f m bs]
+ cases read : P.read node (scratch endAddr c.privateMem) bs with
+ | none =>
+ have hn := exactHook.reject node bs popped (top+1) pending (hpopMem ▸ valid.1)
+ hpc hnode hstack'
+ (by simp only [List.length_cons] at hptr; omega) hsp hp6 hp1
+ (by rw [hpopMem]; exact read)
+ simp [HookParser.decode,read,hn]
+ | some q =>
+ obtain ⟨job,tail⟩ := q
+ obtain ⟨haddr,hen,hbits,hook⟩ := exactHook.success _ _ valid.1 _ _ _ read
+ obtain ⟨back,hback,hnode',hsp',hend',hone',hstate',hstack'',hupdate,hcall⟩ :=
+ hook popped (top+1) pending (hpopMem ▸ hen) hpc (hnode.trans haddr.symm) hstack'
+ (by simp only [List.length_cons] at hptr; omega) hsp hp6 hp1
+ have hreturn : Returns M popped m bs ↔ Returns M back m tail := by
+ rw [hbits]
+ exact returns_prefix (fun f => hcall f tail)
+ have hs : kids.length ≤ top+1 := by simp only [List.length_cons] at hptr; omega
+ obtain ⟨next,hpc',ht',he',h1',_,hm,stackNext,hkids⟩ :=
+ execute_children hl ha back hback m node.val src (top+1) kids pending row hstack''
+ (hnode'.trans (haddr.trans (by simp))) hsp' hone' hs
+ have ptrNext : top+1-kids.length+(kids++pending).length = endAddr := by
+ simp only [List.length_append]; simp only [List.length_cons] at hptr; omega
+ have aux : scratch endAddr next.privateMem = scratch endAddr back.privateMem := by
+ funext a
+ rw [hm]
+ change EndpointBits.copySlice _ _ _ _ _ a.val = _
+ have bound := a.prop
+ unfold EndpointBits.copySlice
+ rw [ite_eq_right (by simp only [List.length_append] at ptrNext; omega)]
+ rfl
+ have validNext : P.ValidAlong domain nodes (scratch endAddr next.privateMem) tail := by
+ rw [aux, hupdate, hpopMem]
+ exact valid.2 _ _ read
+ rw [hreturn,returns_prefix fun f => hkids f tail,
+ ih next hpc' _ stackNext ptrNext ht' (he'.trans hend') h1' tail validNext,
+ aux,hupdate,hpopMem]
+ simp [HookParser.decode,read]
+
+/-- Both directions of the native whole-call characterization, for
+a terminal continuation that requires exact consumption of the bit stream.
+The proof also handles zero-child rows and zero-bit local checks. -/
+theorem returns_iff_decode {M : Machine w p r k} {pc : Fin 9 → Fin p} {arcPC : Fin 5 → Fin p}
+ {reg : Fin 9 ↪ Fin r} {visit done : Fin p} (hl : Linked M pc reg visit (arcPC 0) done)
+ (ha : EndpointBits.Linked M arcPC (copyRegs reg) (pc 0)) {m : Memory w} {endAddr : ℕ}
+ {pending nodes : List (Word w)} {es : List (Event w)}
+ (visits : Visits m endAddr pending nodes es)
+ (P : HookParser w endAddr) (exactHook : P.Exact M visit (pc 3) reg m)
+ (terminal : ∀ (c : Config w p r) bs, c.pc = done → (Returns M c m bs ↔ bs = []))
+ (c : Config w p r) (hc : c.pc = pc 0) (top : ℕ) (hstack : Represents c.privateMem top pending)
+ (hptr : top + pending.length = endAddr) (ht : c.reg (reg 5) = (top : Word w))
+ (he : c.reg (reg 6) = (endAddr : Word w)) (h1 : c.reg (reg 3) = 1) (bs : List Bool) :
+ Returns M c m bs ↔ ∃ out, P.decode nodes (scratch endAddr c.privateMem) bs = some (out,[]) := by
+ have exactOn : P.ExactOn (fun _ _ => True) M visit (pc 3) reg m :=
+ ⟨fun node s _ => exactHook.success node s,
+ fun node bs c top pending _ => exactHook.reject node bs c top pending⟩
+ exact returns_iff_decode_on hl ha visits P exactOn terminal c hc top hstack hptr ht he h1 bs
+ (P.validAlong_of_forall _ nodes (fun _ _ _ => trivial) _ bs)
+
+end PairSimulation.DFS
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationDFSHooks.lean b/lean/OAI/Computability/VPVNP/PairSimulationDFSHooks.lean
new file mode 100644
index 0000000000..0b24fba160
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationDFSHooks.lean
@@ -0,0 +1,243 @@
+import OAI.Computability.VPVNP.PairSimulationDFS
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-!
+# Linking final-vertex work to the native traversal
+
+A local vertex routine may consume private choices and update its scratch
+arrays, including the histogram above the stack. The dispatcher pops its
+descriptor address and gives it control. Its return resumes the stored child
+scan. This composition accounts separately for the routine's actual trace
+and the traversal's reads, with the same unused stream suffix throughout.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.DFS
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+open private copyRegs headerEvents from OAI.Computability.VPVNP.PairSimulationDFS
+
+variable {w p r k : ℕ}
+
+/-- The portion of private memory at word addresses greater than or equal to the exclusive
+stack end. Local visit routines use these cells for arguments and accumulated histogram
+entries. -/
+abbrev Scratch (w endAddr : ℕ) := {a : Word w // endAddr ≤ a.val} → Word w
+
+/-- Restrict a machine's private memory to addresses at or above the stack end, giving the
+scratch state passed to a local visit. -/
+def scratch (endAddr : ℕ) (priv : Word w → Word w) : Scratch w endAddr := fun a => priv a.val
+
+/-- One specified path through the site routine. Distinct items can have
+the same address and update the same exponent, with their separate traces. -/
+structure VisitPath (w endAddr : ℕ) where
+ /-- Descriptor address this visit expects in the dispatcher's node register after the stack
+ pop. -/
+ node : Word w
+ /-- Chronological RAM events of this local visit. They determine its consumed choice bits,
+ instruction count and external probes in the combined traversal. -/
+ trace : List (Event w)
+ /-- Precondition on the incoming scratch contents for this particular visit path. Successive
+ visits test it after applying the preceding paths' updates. -/
+ enabled : Scratch w endAddr → Prop
+ /-- Scratch contents produced on successful return from the local routine. The next visit
+ reads its prepared arguments and accumulated counts from this state. -/
+ update : Scratch w endAddr → Scratch w endAddr
+
+/-- The local arguments prepared by one occurrence must enable the next
+occurrence. This allows malformed field assignments to reject. -/
+def Ready {endAddr : ℕ} : List (VisitPath w endAddr) → Scratch w endAddr → Prop
+ | [], _ => True
+ | j :: js, s => j.enabled s ∧ Ready js (j.update s)
+
+/-- The exact execution contract of an embedded vertex routine. Pending
+stack cells are preserved until the dispatcher prepends its child list. -/
+def VisitPath.Linked {endAddr : ℕ} (job : VisitPath w endAddr) (M : Machine w p r k)
+ (visit ret : Fin p) (reg : Fin 9 ↪ Fin r) (m : Memory w) : Prop :=
+ ∀ (c : Config w p r) (top : ℕ) (pending : List (Word w)),
+ job.enabled (scratch endAddr c.privateMem) → c.pc = visit → c.reg (reg 7) = job.node → Represents c.privateMem top pending →
+ top + pending.length = endAddr → c.reg (reg 5) = (top : Word w) → c.reg (reg 6) = (endAddr : Word w) → c.reg (reg 3) = 1 →
+ ∃ out, out.pc = ret ∧ out.reg (reg 7) = job.node ∧ out.reg (reg 5) = (top : Word w) ∧
+ out.reg (reg 6) = (endAddr : Word w) ∧ out.reg (reg 3) = 1 ∧ out.persistent = c.persistent ∧
+ Represents out.privateMem top pending ∧ scratch endAddr out.privateMem = job.update (scratch endAddr c.privateMem) ∧
+ ∀ fuel bs, execute M.program (fuel + job.trace.length) c m (choiceBits job.trace ++ bs) =
+ (execute M.program fuel out m bs).map (fun r => ⟨job.trace ++ r.events,r.result⟩)
+
+private theorem choiceBits_copy (m : Memory w) (src n : ℕ) : choiceBits (EndpointBits.events m src n) = [] := by
+ induction n generalizing src with
+ | zero => rfl
+ | succ n ih => simpa only [EndpointBits.events, List.cons_append, List.nil_append, choiceBits] using ih _
+
+private theorem length_copy (m : Memory w) (src n : ℕ) : (EndpointBits.events m src n).length = 5*n+1 := by
+ induction n generalizing src with
+ | zero => rfl
+ | succ n ih => simp [EndpointBits.events,ih]; omega
+
+private theorem probes_append (a b : List (Event w)) : countProbes (a++b) = countProbes a + countProbes b := by
+ induction a with
+ | nil => simp [countProbes]
+ | cons e a ih => cases e <;> simp [countProbes,ih,Nat.add_comm,Nat.add_left_comm]
+
+/-- For a fixed chosen native path at each visit, control overhead adds no
+choice bits and each state update acts on the previous routine's scratch.
+The theorem includes the exact length and probe count on the combined path. -/
+theorem execute_linked_visits_supported {M : Machine w p r k} {pc : Fin 9 → Fin p} {arcPC : Fin 5 → Fin p}
+ {reg : Fin 9 ↪ Fin r} {visit done : Fin p}
+ (hl : Linked M pc reg visit (arcPC 0) done) (ha : EndpointBits.Linked M arcPC (copyRegs reg) (pc 0))
+ {m : Memory w} {endAddr : ℕ} {pending nodes : List (Word w)} {control : List (Event w)}
+ (visits : Visits m endAddr pending nodes control)
+ (jobs : List (VisitPath w endAddr)) (hjobs : jobs.map VisitPath.node = nodes)
+ (hook : ∀ job ∈ jobs, job.Linked M visit (pc 3) reg m)
+ (c : Config w p r) (hc : c.pc = pc 0) (top : ℕ) (hstack : Represents c.privateMem top pending)
+ (hptr : top + pending.length = endAddr) (ht : c.reg (reg 5) = (top : Word w))
+ (he : c.reg (reg 6) = (endAddr : Word w)) (h1 : c.reg (reg 3) = 1)
+ (ready : Ready jobs (scratch endAddr c.privateMem)) :
+ ∃ out es, out.pc = done ∧ out.persistent = c.persistent ∧ out.reg (reg 6) = (endAddr : Word w) ∧
+ ((∀ j ∈ jobs, after m j.trace = m) → after m es = m) ∧
+ (∀ ev ∈ es, ev ∈ control ∨ ∃ j ∈ jobs, ev ∈ j.trace) ∧
+ scratch endAddr out.privateMem = jobs.foldl (fun s j => j.update s) (scratch endAddr c.privateMem) ∧
+ choiceBits es = jobs.flatMap (fun j => choiceBits j.trace) ∧
+ es.length = control.length + (jobs.map fun j => j.trace.length).sum ∧
+ countProbes es = countProbes control + (jobs.map fun j => countProbes j.trace).sum ∧
+ ∀ fuel bs, execute M.program (fuel+es.length) c m (choiceBits es ++ bs) =
+ (execute M.program fuel out m bs).map (fun r => ⟨es++r.events,r.result⟩) := by
+ induction visits generalizing c top jobs with
+ | nil =>
+ cases jobs with
+ | cons j js => simp at hjobs
+ | nil =>
+ have htop : top = endAddr := by simpa using hptr
+ exact ⟨{c with pc := done}, [.tick], rfl,rfl,he,(fun _ => rfl),(fun _ h => Or.inl h),rfl,rfl,rfl,rfl,
+ fun fuel bs => execute_empty hl c hc (by rw [ht,he,htop]) fuel m bs⟩
+ | @cons node pending kids nodes src es row fits rest ih =>
+ cases jobs with
+ | nil => simp at hjobs
+ | cons j js =>
+ obtain ⟨hj,hjs⟩ := List.cons.inj hjobs
+ obtain ⟨popped,hpc,hsp,hnode,hreg,hmemPop,hstate,hstack',hpop⟩ :=
+ execute_pop hl c hc top node pending hstack ht (hptr ▸ he) h1
+ have hp1 := (hreg (reg 3) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans h1
+ have hp6 := (hreg (reg 6) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans he
+ obtain ⟨back,hback,hnode',hsp',hend',hone',hstate',hstack'',hupdate,hcall⟩ :=
+ hook j List.mem_cons_self popped (top+1) pending (by rw [hmemPop]; exact ready.1) hpc (hnode.trans hj.symm) hstack'
+ (by simp only [List.length_cons] at hptr; omega) hsp hp6 hp1
+ have hs : kids.length ≤ top+1 := by simp only [List.length_cons] at hptr; omega
+ obtain ⟨next,hpc',ht',he',h1',hp',hm,stackNext,hkids⟩ :=
+ execute_children hl ha back hback m node.val src (top+1) kids pending row hstack''
+ (hnode'.trans (hj.trans (by simp))) hsp' hone' hs
+ have ptrNext : top+1-kids.length+(kids++pending).length = endAddr := by
+ simp only [List.length_append]; simp only [List.length_cons] at hptr; omega
+ have aux : scratch endAddr next.privateMem = scratch endAddr back.privateMem := by
+ funext a
+ rw [hm]
+ change EndpointBits.copySlice _ _ _ _ _ a.val = _
+ have bound := a.prop
+ unfold EndpointBits.copySlice
+ rw [ite_eq_right (by simp only [List.length_append] at ptrNext; omega)]
+ rfl
+ obtain ⟨out,tail,hout,hper,regEnd,memTail,support,hfinish,hbits,hsteps,hprobes,hex⟩ := ih js hjs
+ (fun q hq => hook q (List.mem_cons_of_mem _ hq)) next hpc' _ stackNext ptrNext ht' (he'.trans hend') h1'
+ (by rw [aux,hupdate,hmemPop]; exact ready.2)
+ let tick3 : List (Event w) := [.tick,.tick,.tick]
+ let field := headerEvents w node.val src kids.length ++ EndpointBits.events m src kids.length
+ let all := tick3 ++ j.trace ++ field ++ tail
+ have bf : choiceBits field = [] := by simp [field,
+ headerEvents, choiceBits, choiceBits_copy]
+ have fl : field.length = 5*kids.length+7 := by simp [field,headerEvents,length_copy]
+ have ab : choiceBits all = choiceBits j.trace ++ choiceBits tail := by
+ simp [all, tick3, PrimedInputRAM.Flow.choiceBits_append, choiceBits, bf]
+ refine ⟨out,all,hout,hper.trans (hp'.trans (hstate'.trans hstate)),regEnd,?_,?_,?_,?_,?_,?_,?_⟩
+ · intro stay
+ have copyKeeps (src count : ℕ) : after m (EndpointBits.events m src count) = m := by
+ induction count generalizing src with
+ | zero => rfl
+ | succ n ih => exact ih (src+1)
+ have headerKeeps : after m (headerEvents w node.val src kids.length) = m := rfl
+ have append (a b : List (Event w)) : after m (a++b) = after (after m a) b := List.foldl_append
+ rw [show all = tick3 ++ (j.trace ++ ((headerEvents w node.val src kids.length ++ EndpointBits.events m src kids.length) ++ tail)) by simp [all,field,List.append_assoc],
+ append,show after m tick3 = m from rfl,append,stay _ List.mem_cons_self,append,append,headerKeeps,
+ copyKeeps,memTail (fun q h => stay _ (List.mem_cons_of_mem _ h))]
+ · intro ev hev
+ have rest := support ev
+ simp only [all, field, tick3, List.mem_append] at hev
+ simp only [List.mem_append]
+ rcases hev with ((h | h) | (h | h)) | h
+ · exact Or.inl (Or.inl (Or.inl (Or.inl h)))
+ · exact Or.inr ⟨j,List.mem_cons_self,h⟩
+ · exact Or.inl (Or.inl (Or.inl (Or.inr h)))
+ · exact Or.inl (Or.inl (Or.inr h))
+ · rcases rest h with last | ⟨j',member,hit⟩
+ · exact Or.inl (Or.inr last)
+ · exact Or.inr ⟨j',List.mem_cons_of_mem _ member,hit⟩
+ · simpa only [List.foldl_cons, aux, hupdate, hmemPop] using hfinish
+ · simp only [List.flatMap_cons, ab, hbits]
+ · simp only [all, field, List.length_append, hsteps, List.map_cons, List.sum_cons]
+ dsimp [tick3]
+ omega
+ · simp only [all,field,probes_append,hprobes,List.map_cons,List.sum_cons]
+ dsimp [tick3,countProbes]
+ omega
+ · intro fuel bs
+ rw [ab, List.append_assoc]
+ have hn : fuel+all.length = ((fuel+tail.length + (5*kids.length+7)) + j.trace.length) + 3 := by
+ simp only [all,List.length_append,fl]; dsimp [tick3]; omega
+ rw [hn,hpop,hcall,hkids,hex]
+ simp [Option.map_map,Function.comp_def,all,tick3,field,List.append_assoc]
+
+/-- The framed traversal, forgetting the support of its event list. -/
+theorem execute_linked_visits_framed {M : Machine w p r k} {pc : Fin 9 → Fin p} {arcPC : Fin 5 → Fin p}
+ {reg : Fin 9 ↪ Fin r} {visit done : Fin p}
+ (hl : Linked M pc reg visit (arcPC 0) done) (ha : EndpointBits.Linked M arcPC (copyRegs reg) (pc 0))
+ {m : Memory w} {endAddr : ℕ} {pending nodes : List (Word w)} {control : List (Event w)}
+ (visits : Visits m endAddr pending nodes control)
+ (jobs : List (VisitPath w endAddr)) (hjobs : jobs.map VisitPath.node = nodes)
+ (hook : ∀ job ∈ jobs, job.Linked M visit (pc 3) reg m)
+ (c : Config w p r) (hc : c.pc = pc 0) (top : ℕ) (hstack : Represents c.privateMem top pending)
+ (hptr : top + pending.length = endAddr) (ht : c.reg (reg 5) = (top : Word w))
+ (he : c.reg (reg 6) = (endAddr : Word w)) (h1 : c.reg (reg 3) = 1)
+ (ready : Ready jobs (scratch endAddr c.privateMem)) :
+ ∃ out es, out.pc = done ∧ out.persistent = c.persistent ∧ out.reg (reg 6) = (endAddr : Word w) ∧
+ ((∀ j ∈ jobs, after m j.trace = m) → after m es = m) ∧
+ scratch endAddr out.privateMem = jobs.foldl (fun s j => j.update s) (scratch endAddr c.privateMem) ∧
+ choiceBits es = jobs.flatMap (fun j => choiceBits j.trace) ∧
+ es.length = control.length + (jobs.map fun j => j.trace.length).sum ∧
+ countProbes es = countProbes control + (jobs.map fun j => countProbes j.trace).sum ∧
+ ∀ fuel bs, execute M.program (fuel+es.length) c m (choiceBits es ++ bs) =
+ (execute M.program fuel out m bs).map (fun r => ⟨es++r.events,r.result⟩) := by
+ obtain ⟨out, es, pc', state, endReg, mem, _, rest⟩ :=
+ execute_linked_visits_supported hl ha visits jobs hjobs hook c hc top hstack hptr ht he h1 ready
+ exact ⟨out, es, pc', state, endReg, mem, rest⟩
+
+/-- The original traversal statement, with the scratch, event, and cost
+projections used by callers that do not inspect the ending stack register. -/
+theorem execute_linked_visits {M : Machine w p r k} {pc : Fin 9 → Fin p} {arcPC : Fin 5 → Fin p}
+ {reg : Fin 9 ↪ Fin r} {visit done : Fin p}
+ (hl : Linked M pc reg visit (arcPC 0) done) (ha : EndpointBits.Linked M arcPC (copyRegs reg) (pc 0))
+ {m : Memory w} {endAddr : ℕ} {pending nodes : List (Word w)} {control : List (Event w)}
+ (visits : Visits m endAddr pending nodes control)
+ (jobs : List (VisitPath w endAddr)) (hjobs : jobs.map VisitPath.node = nodes)
+ (hook : ∀ job ∈ jobs, job.Linked M visit (pc 3) reg m)
+ (c : Config w p r) (hc : c.pc = pc 0) (top : ℕ) (hstack : Represents c.privateMem top pending)
+ (hptr : top + pending.length = endAddr) (ht : c.reg (reg 5) = (top : Word w))
+ (he : c.reg (reg 6) = (endAddr : Word w)) (h1 : c.reg (reg 3) = 1)
+ (ready : Ready jobs (scratch endAddr c.privateMem)) :
+ ∃ out es, out.pc = done ∧ out.persistent = c.persistent ∧
+ scratch endAddr out.privateMem = jobs.foldl (fun s j => j.update s) (scratch endAddr c.privateMem) ∧
+ choiceBits es = jobs.flatMap (fun j => choiceBits j.trace) ∧
+ es.length = control.length + (jobs.map fun j => j.trace.length).sum ∧
+ countProbes es = countProbes control + (jobs.map fun j => countProbes j.trace).sum ∧
+ ∀ fuel bs, execute M.program (fuel+es.length) c m (choiceBits es ++ bs) =
+ (execute M.program fuel out m bs).map (fun r => ⟨es++r.events,r.result⟩) := by
+ obtain ⟨out,es,pc,state,_,_,rest⟩ :=
+ execute_linked_visits_framed hl ha visits jobs hjobs hook c hc top hstack hptr ht he h1 ready
+ exact ⟨out,es,pc,state,rest⟩
+
+end PairSimulation.DFS
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationDescriptorRows.lean b/lean/OAI/Computability/VPVNP/PairSimulationDescriptorRows.lean
new file mode 100644
index 0000000000..7e854a96e7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationDescriptorRows.lean
@@ -0,0 +1,184 @@
+import OAI.Computability.VPVNP.PairSimulationDFS
+import OAI.Computability.VPVNP.CompressorRecordPreimageScan
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-!
+# Converting preimage identifiers to child descriptor addresses
+
+A native pass reads a site's stored count and child identifiers. It writes
+a header and a separate row of addresses in the older level's descriptor
+table. The input order, including the empty preimage list, is preserved.
+The child scan reads and writes one word per old position independently
+of the widths of all tensor fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.DescriptorRows
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+
+private theorem val_word {n : ℕ} (h : n < 2^w) : (word w n).val = n := Nat.mod_eq_of_lt h
+
+/-- Register 0 scans identifiers up to register 1. Register 2 is the
+destination cursor. Registers 3–5 contain the older table base, its
+descriptor stride and the unit. Register 6 holds the current address. -/
+def body : Flow 7 0 :=
+ .seq (.line (.read 6 0)) <|
+ .seq (.line (.binary .mul 6 6 4)) <|
+ .seq (.line (.binary .add 6 6 3)) <|
+ .seq (.line (.write 2 6)) <|
+ .seq (.line (.binary .add 0 0 5)) (.line (.binary .add 2 2 5))
+
+/-- While the input cursor is below its end, read each child identifier, convert it to an
+address in the older descriptor table, and write that address at the advancing destination
+cursor. -/
+def scan : Flow 7 0 := .whileLt 0 1 body
+
+/-- Compute a child descriptor's address in word arithmetic by adding its identifier times the
+older table's row stride to the table base. -/
+def address (base stride id : Word w) : Word w := id*stride+base
+
+private def advance (rs : Regs w 7) (value : Word w) : Regs w 7 :=
+ Function.update (Function.update (Function.update rs 6 value) 0 (rs 0 + rs 5)) 2 (rs 2 + rs 5)
+
+private def events (src dst value addr : Word w) : List (Event w) :=
+ [.read src value,.tick,.tick,.write dst addr,.tick,.tick]
+
+private theorem body_exec (pub : Fin 0 → Word w) (state : Word w) (rs : Regs w 7) (m : Memory w) :
+ let id := m (rs 0).val
+ let addr := address (rs 3) (rs 4) id
+ Flow.Exec pub state body rs m (events (rs 0) (rs 2) id addr)
+ (advance rs addr) (writeMemory m (rs 2) addr) := by
+ dsimp only
+ unfold body events advance address
+ apply Flow.Exec.seq (.line rfl)
+ apply Flow.Exec.seq (.line rfl)
+ apply Flow.Exec.seq (.line rfl)
+ apply Flow.Exec.seq (.line rfl)
+ apply Flow.Exec.seq (.line rfl)
+ apply Flow.Exec.line
+ simp (config := {decide := true}) [Op.effect,BinaryOp.eval,Function.update]
+
+/-- Exact state of the output row, with all other memory cells retained. -/
+def rowMemory (src dst count : ℕ) (base stride : Word w) (m : Memory w) : Memory w := fun i =>
+ if dst ≤ i ∧ i < dst+count then address base stride (m (src+(i-dst))) else m i
+
+private theorem rowMemory_succ (src dst count : ℕ) (base stride : Word w) (m : Memory w)
+ (h : dst < 2^w) (before : src+(count+1) ≤ dst) :
+ rowMemory (src+1) (dst+1) count base stride (writeMemory m (word w dst) (address base stride (m src))) =
+ rowMemory src dst (count+1) base stride m := by
+ funext i
+ by_cases hd : i = dst
+ · subst i; simp [rowMemory,writeMemory,val_word h]
+ · simp only [rowMemory,writeMemory,val_word h]
+ split_ifs <;> first | rfl | (congr 2; omega)
+
+/-- The finite loop scans exactly the indicated interval, returning its
+external probe count and instruction count even for an empty child row. -/
+theorem scan_exec (pub : Fin 0 → Word w) (state : Word w) (rs : Regs w 7) (m : Memory w)
+ (src dst count : ℕ) (base stride : Word w) (hs : rs 0 = word w src)
+ (he : rs 1 = word w (src+count)) (hd : rs 2 = word w dst) (hb : rs 3 = base)
+ (hst : rs 4 = stride) (hone : rs 5 = 1) (fit : dst+count < 2^w) (before : src+count ≤ dst) :
+ ∃ es out, Flow.Exec pub state scan rs m es out (rowMemory src dst count base stride m) ∧
+ countProbes es = 2*count ∧ es.length = 7*count+1 ∧ choiceBits es = [] := by
+ induction count generalizing rs m src dst with
+ | zero =>
+ have hn : ¬ rs 0 < rs 1 := by rw [hs, he]; simp
+ have hm : rowMemory src dst 0 base stride m = m := by funext i; simp [rowMemory]
+ rw [hm]
+ exact ⟨[.tick],rs,.whileDone hn,rfl,rfl,rfl⟩
+ | succ n ih =>
+ have hfit : src+(n+1) < 2^w := by omega
+ have lt : rs 0 < rs 1 := by
+ change (rs 0).val < (rs 1).val
+ rw [hs,he,val_word (by omega : src < 2^w),val_word hfit]; omega
+ let addr := address base stride (m src)
+ let out := advance rs addr
+ let m' := writeMemory m (word w dst) addr
+ have ex := body_exec pub state rs m
+ rw [hs,hd,hb,hst,val_word (by omega : src < 2^w)] at ex
+ change Flow.Exec pub state body rs m (events (word w src) (word w dst) (m src) addr) out m' at ex
+ obtain ⟨es,last,loop,hcost,hlen,hchoice⟩ := ih out m' (src+1) (dst+1)
+ (by simp [out,advance,Function.update,hs,hone,word])
+ (by simp [out,advance,Function.update,he,word]; ring)
+ (by simp [out,advance,hd,hone,word])
+ (by simp [out,advance,Function.update,hb]) (by simp [out,advance,Function.update,hst])
+ (by simp [out,advance,Function.update,hone]) (by omega) (by omega)
+ have hm := rowMemory_succ src dst n base stride m (by omega) before
+ change rowMemory (src+1) (dst+1) n base stride m' = _ at hm
+ refine ⟨_,last,hm ▸ Flow.Exec.whileStep lt ex loop,?_,?_,?_⟩
+ · simp [events,countProbes,hcost]; omega
+ · simp [events,hlen]; omega
+ · simpa [events,choiceBits] using hchoice
+
+/-- Link the identifier scan to arbitrary native successor code. -/
+theorem linked_scan {p : ℕ} {M : Machine w p 7 0} {pc : scan.Label → Fin p} {stop bad : Fin p}
+ (hl : Flow.Linked M scan pc stop bad) (hbad : M.code bad = .reject)
+ (state : Word w) (priv : Word w → Word w) (rs : Regs w 7) (m : Memory w)
+ (src dst count : ℕ) (base stride : Word w) (hs : rs 0 = word w src)
+ (he : rs 1 = word w (src+count)) (hd : rs 2 = word w dst) (hb : rs 3 = base)
+ (hst : rs 4 = stride) (hone : rs 5 = 1) (fit : dst+count < 2^w) (before : src+count ≤ dst) :
+ ∃ es out, countProbes es = 2*count ∧ choiceBits es = [] ∧ ∀ fuel bs,
+ execute M.program (7*count+1+fuel) ⟨pc scan.entry,state,rs,priv⟩ m bs =
+ (execute M.program fuel ⟨stop,state,out,priv⟩ (rowMemory src dst count base stride m) bs).map
+ (Flow.prependEvents es) := by
+ obtain ⟨es,out,run,probes,steps,bits⟩ := scan_exec M.publicData state rs m src dst count base stride
+ hs he hd hb hst hone fit before
+ refine ⟨es,out,probes,bits,?_⟩
+ intro fuel bs
+ simpa only [steps,bits,List.nil_append] using run.execute hl hbad priv fuel bs
+
+/-- A separate fixed three-probe block loads the preimage count from
+register 0 and writes the row pointer and count at the node's first two
+descriptor cells. Register 1 holds the row pointer, register 2 the node
+address, and register 3 the unit. -/
+def header : List (Op 5 0) :=
+ [.read 4 0,.write 2 1,.binary .add 2 2 3,.write 2 4]
+
+theorem header_native (pub : Fin 0 → Word w) (state : Word w) (regs : Regs w 5)
+ (mem : Memory w) (priv : Word w → Word w) :
+ let M := (template header 4).instantiate w pub
+ let n := mem (regs 0).val
+ execute M.program 5 ⟨M.entry,state,regs,priv⟩ mem [] =
+ some ⟨[.read (regs 0) n,.write (regs 2) (regs 1),.tick,.write (regs 2+regs 3) n],some n⟩ := by
+ change execute _ (1 + header.length) _ _ _ = _
+ rw [execute_template, run_eq_trace]
+ simp (config := {decide := true}) [header,trace,Op.effect,BinaryOp.eval,Function.update]
+
+/-- A scanned preimage row and the written header have precisely the
+representation read by the native stack traversal. -/
+theorem represents_DFS_row (mem : Memory w) (node src dst : ℕ) (countCell base stride : Word w)
+ (ids : List (Word w)) (hrow : rowRepresents mem countCell (word w src) ids)
+ (hsrc : src < 2^w) (fit : dst+ids.length < 2^w) (before : node+1 < dst)
+ :
+ let final := rowMemory src dst ids.length base stride mem
+ let headers := writeMemory (writeMemory final (word w node) (word w dst))
+ (word w (node+1)) (mem countCell.val)
+ DFS.Row headers node dst (ids.map (address base stride)) := by
+ dsimp only
+ refine ⟨by omega,by simpa using fit,?_,?_,?_⟩
+ · simp only [writeMemory,val_word (by omega : node+1 < 2^w),val_word (by omega : node < 2^w),
+ ite_eq_right (by omega : node ≠ node+1),↓reduceIte]
+ · simp only [writeMemory,val_word (by omega : node+1 < 2^w),↓reduceIte,List.length_map]
+ exact Fin.ext (hrow.1.trans (val_word (by omega : ids.length < 2^w)).symm)
+ · intro i
+ have hi : i.val < ids.length := by simpa using i.isLt
+ have hh := hrow.2 ⟨i.val,hi⟩
+ rw [val_word hsrc] at hh
+ simp only [writeMemory,val_word (by omega : node+1 < 2^w),val_word (by omega : node < 2^w),
+ ite_eq_right (by omega : dst+i.val ≠ node), ite_eq_right (by omega : dst+i.val ≠ node+1)]
+ simp [rowMemory,show dst+i.val < dst+ids.length by omega,hh]
+
+end PairSimulation.DescriptorRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationEndpointBits.lean b/lean/OAI/Computability/VPVNP/PairSimulationEndpointBits.lean
new file mode 100644
index 0000000000..6d940aa2a6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationEndpointBits.lean
@@ -0,0 +1,257 @@
+import OAI.Computability.VPVNP.PairSimulationFinalBits
+
+/-!
+# Reading a final arc inside a vertex call
+
+The five-opcode loop reads a contiguous final arc from external memory and
+copies its bits into the private tape of the current vertex. It can be entered
+at each source or target incidence with new interval bounds. Its continuation
+keeps all private cells outside that interval, and the external memory and
+branch stream are available to the rest of the vertex expansion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.EndpointBits
+
+open BurstRAM BurstRAM.PrivateRAM FinalBits PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+
+private theorem val_word {a : ℕ} (h : a < 2 ^ w) : (word w a).val = a :=
+ Nat.mod_eq_of_lt h
+
+/-- Registers hold the current source, exclusive source end, current private
+destination, one, and a temporary word. -/
+def instruction (pc : Fin 5 → Fin p) (reg : Fin 5 ↪ Fin r) (done : Fin p) : Fin 5 → Instr w p r k :=
+ ![.jumpEq (reg 0) (reg 1) done (pc 1), .readExternal (reg 4) (reg 0) (pc 2),
+ .storePrivate (reg 2) (reg 4) (pc 3), .binary .add (reg 2) (reg 2) (reg 3) (pc 4),
+ .binary .add (reg 0) (reg 0) (reg 3) (pc 0)]
+
+/-- The vertex reader has the same opcodes and jump targets at every word width. -/
+theorem resize_instruction (pc : Fin 5 → Fin p) (reg : Fin 5 ↪ Fin r) (done : Fin p) (i : Fin 5) :
+ (instruction (w := 1) (k := k) pc reg done i).resize w = instruction pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- Require the five endpoint-copy instructions at the supplied program counters. Each
+iteration loads one external arc cell into the private tape and advances both cursors until
+control reaches `done`. -/
+def Linked (M : Machine w p r k) (pc : Fin 5 → Fin p) (reg : Fin 5 ↪ Fin r) (done : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+variable {M : Machine w p r k} {pc : Fin 5 → Fin p} {reg : Fin 5 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (hl : Linked M pc reg done) (i : Fin 5) (c : Config w p r)
+ (hc : c.pc = pc i) : M.program.step c = (instruction pc reg done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+/-- Actual chronological events, including the loop exit test at width zero. -/
+def events (m : Memory w) (src : ℕ) : ℕ → List (Event w)
+ | 0 => [.tick]
+ | n+1 => [.tick, .read (word w src) (m src), .tick, .tick, .tick] ++ events m (src+1) n
+
+theorem probes (m : Memory w) (src n : ℕ) : countProbes (events m src n) = n := by
+ induction n generalizing src with
+ | zero => rfl
+ | succ n ih => simp [events, countProbes, ih, Nat.add_comm]
+
+/-- Closed form for the private-memory slice after the loop. -/
+def copySlice (m : Memory w) (src dst n : ℕ) (old : Word w → Word w) (a : Word w) : Word w :=
+ if dst ≤ a.val ∧ a.val < dst+n then m (src + (a.val-dst)) else old a
+
+private theorem copySlice_succ (m : Memory w) (src dst n : ℕ) (old : Word w → Word w)
+ (hd : dst < 2 ^ w) :
+ copySlice m (src+1) (dst+1) n (Function.update old (word w dst) (m src)) =
+ copySlice m src dst (n+1) old := by
+ funext a
+ by_cases ha : a.val = dst
+ · have he : a = word w dst := Fin.ext (ha.trans (val_word hd).symm)
+ simp [copySlice, he, val_word hd]
+ · have he : a ≠ word w dst := fun e ↦ ha ((congrArg Fin.val e).trans (val_word hd))
+ simp only [copySlice, Function.update_of_ne he]
+ split_ifs with h h' h' <;> first | rfl | (congr 1; omega)
+
+private def advance (c : Config w p r) (pc : Fin 5 → Fin p) (reg : Fin 5 ↪ Fin r)
+ (src dst : ℕ) (value : Word w) : Config w p r :=
+ let cr := {c with pc := pc 1}
+ let ct := cr.put (pc 2) (reg 4) value
+ let cs := ct.store (pc 3) (word w dst) value
+ let cd := cs.put (pc 4) (reg 2) (word w (dst+1))
+ cd.put (pc 0) (reg 0) (word w (src+1))
+
+private theorem local_step {c d : Config w p r} (hs : M.program.step c = .localStep d)
+ (fuel : ℕ) (m : Memory w) (bs : List Bool) :
+ execute M.program (fuel+1) c m bs = (execute M.program fuel d m bs).map
+ (Report.prepend .tick) := by
+ simp only [execute, hs]
+
+private theorem read_step {c : Config w p r} {a : Word w} {g : Word w → Config w p r}
+ (hs : M.program.step c = .read a g) (fuel : ℕ) (m : Memory w) (bs : List Bool) :
+ execute M.program (fuel+1) c m bs = (execute M.program fuel (g (m a.val)) m bs).map
+ (Report.prepend (.read a (m a.val))) := by
+ simp only [execute, hs]
+
+private theorem execute_body (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (m : Memory w) (src dst : ℕ) (hs : src < 2 ^ w) (hr : c.reg (reg 0) = word w src)
+ (hd : c.reg (reg 2) = word w dst) (h1 : c.reg (reg 3) = 1) (hn : c.reg (reg 0) ≠ c.reg (reg 1))
+ (fuel : ℕ) (bs : List Bool) :
+ execute M.program (fuel+5) c m bs =
+ (execute M.program fuel (advance c pc reg src dst (m src)) m bs).map
+ (fun rep ↦ ⟨[.tick, .read (word w src) (m src), .tick, .tick, .tick] ++ rep.events,
+ rep.result⟩) := by
+ let cr := {c with pc := pc 1}
+ let ct := cr.put (pc 2) (reg 4) (m src)
+ let cs := ct.store (pc 3) (word w dst) (m src)
+ let cd := cs.put (pc 4) (reg 2) (word w (dst+1))
+ have s0 : M.program.step c = .localStep cr := by
+ rw [step_at hl 0 c hc]
+ change CallAction.localStep {c with
+ pc := if c.reg (reg 0) = c.reg (reg 1) then done else pc 1} = _
+ simp [hn, cr]
+ have s1 : M.program.step cr = .read (word w src) (fun v ↦ cr.put (pc 2) (reg 4) v) := by
+ rw [step_at hl 1 cr rfl]
+ change CallAction.read (c.reg (reg 0)) _ = _
+ rw [hr]
+ have s2 : M.program.step ct = .localStep cs := by
+ rw [step_at hl 2 ct rfl]
+ change CallAction.localStep (ct.store (pc 3) (ct.reg (reg 2)) (ct.reg (reg 4))) = _
+ simp [cs, ct, cr, Config.put, hd]
+ have s3 : M.program.step cs = .localStep cd := by
+ rw [step_at hl 3 cs rfl]
+ change CallAction.localStep (cs.put (pc 4) (reg 2) (cs.reg (reg 2) + cs.reg (reg 3))) = _
+ simp [cd, cs, ct, cr, Config.store, Config.put, hd, h1, word]
+ have s4 : M.program.step cd = .localStep (advance c pc reg src dst (m src)) := by
+ rw [step_at hl 4 cd rfl]
+ change CallAction.localStep (cd.put (pc 0) (reg 0) (cd.reg (reg 0) + cd.reg (reg 3))) = _
+ simp [advance, cd, cs, ct, cr, Config.store, Config.put, hr, h1, word]
+ have hread : execute M.program (fuel+4) cr m bs =
+ (execute M.program (fuel+3) ct m bs).map (Report.prepend (.read (word w src) (m src))) := by
+ rw [read_step s1, val_word hs]
+ rw [local_step s0, hread, local_step s2, local_step s3, local_step s4]
+ simp [Option.map_map, Function.comp_def, Report.prepend]
+
+/-- Exact native execution inside an arbitrary vertex call. There is one
+read per incident bit and no private branches. The updated private slice is
+available to an arbitrary continuation at the chosen exit. -/
+theorem execute_arc (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (m : Memory w) (src dst n : ℕ) (hsrc : src + n < 2 ^ w) (hdst : dst + n < 2 ^ w)
+ (hread : c.reg (reg 0) = word w src) (hend : c.reg (reg 1) = word w (src + n))
+ (hwrite : c.reg (reg 2) = word w dst) (hone : c.reg (reg 3) = 1) :
+ ∃ out, out.pc = done ∧ out.persistent = c.persistent ∧
+ out.reg (reg 0) = word w (src+n) ∧ out.reg (reg 2) = word w (dst+n) ∧
+ (∀ i, i ≠ reg 0 → i ≠ reg 2 → i ≠ reg 4 → out.reg i = c.reg i) ∧
+ out.privateMem = copySlice m src dst n c.privateMem ∧
+ ∀ fuel bs, execute M.program (fuel + 5*n+1) c m bs =
+ (execute M.program fuel out m bs).map (fun rep ↦ ⟨events m src n ++ rep.events,
+ rep.result⟩) := by
+ induction n generalizing c src dst with
+ | zero =>
+ have he : c.reg (reg 0) = c.reg (reg 1) := hread.trans (by simpa using hend.symm)
+ have s0 : M.program.step c = .localStep {c with pc := done} := by
+ rw [step_at hl 0 c hc]
+ change CallAction.localStep {c with
+ pc := if c.reg (reg 0) = c.reg (reg 1) then done else pc 1} = _
+ simp [he]
+ refine ⟨{c with pc := done}, rfl, rfl, by simpa using hread, by simpa using hwrite,
+ fun _ _ _ _ ↦ rfl, ?_, ?_⟩
+ · funext a
+ simp [copySlice]
+ · intro fuel bs
+ simp [execute, s0, events]
+ rfl
+ | succ n ih =>
+ let next := advance c pc reg src dst (m src)
+ have ne : c.reg (reg 0) ≠ c.reg (reg 1) := by
+ rw [hread, hend]
+ intro e
+ have hv := congrArg Fin.val e
+ rw [val_word (by omega : src < 2^w), val_word hsrc] at hv
+ omega
+ have es : src+1+n = src+(n+1) := by omega
+ have ed : dst+1+n = dst+(n+1) := by omega
+ have regOther (i : Fin r) (h0 : i ≠ reg 0) (h2 : i ≠ reg 2) (h4 : i ≠ reg 4) :
+ next.reg i = c.reg i := by
+ simp [next, advance, Config.put, Config.store, Function.update_of_ne, h0, h2, h4]
+ obtain ⟨out, ho, hp, ha, hb, hrest, hpriv, hex⟩ := ih next rfl (src+1) (dst+1)
+ (es ▸ hsrc) (ed ▸ hdst) (by simp [next, advance, Config.put])
+ (by rw [regOther, es, hend] <;> simp)
+ (by simp [next, advance, Config.put]) (by rw [regOther, hone] <;> simp)
+ refine ⟨out, ho, hp, es ▸ ha, ed ▸ hb, fun i h0 h2 h4 ↦ (hrest i h0 h2 h4).trans
+ (regOther i h0 h2 h4), hpriv.trans (copySlice_succ _ _ _ _ _ (by omega)), ?_⟩
+ intro fuel bs
+ rw [show fuel + 5*(n+1)+1 = (fuel+5*n+1)+5 by omega,
+ execute_body hl c hc m src dst (by omega) hread hwrite hone ne]
+ change (execute M.program _ next m bs).map _ = _
+ rw [hex]
+ simp [Option.map_map, Function.comp_def, events]
+
+variable {E : ℕ} (width : Fin E → ℕ)
+
+/-- Beginning of an arc relative to the lower address of the bit array. -/
+def offset (e : Fin E) : ℕ := ∑ i : Fin e, width (Fin.castLE e.isLt.le i)
+
+theorem arc_fits (e : Fin E) : offset width e + width e ≤ ∑ t, width t := by
+ have h := Finset.sum_le_univ_sum_of_nonneg (s := Finset.univ.map (Fin.castLEEmb e.isLt))
+ (fun t ↦ Nat.zero_le (width t))
+ rw [Finset.sum_map, Fin.sum_univ_castSucc] at h
+ exact h
+
+variable (N : NetworkKernel.Network) (number : N.Edge ≃ Fin E)
+ (encode : ∀ e, N.Payload e ≃ (Fin (width (number e)) → Bool))
+
+/-- An incidence reader linked inside a final vertex call copies exactly the
+edge payload of equation (7.1) into its private workspace. The copy executes
+from the first loop opcode, including for a zero-width edge. -/
+theorem execute_payload (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (low : ℕ) (fit : low + ∑ t, width t < 2 ^ w) (f : Fin (∑ t,
+ width t) → Bool) (initial : Memory w)
+ (e : N.Edge) (dst : ℕ) (hdst : dst + width (number e) < 2 ^ w)
+ (hread : c.reg (reg 0) = word w (low + offset width (number e)))
+ (hend : c.reg (reg 1) = word w (low + offset width (number e) + width (number e)))
+ (hwrite : c.reg (reg 2) = word w dst) (hone : c.reg (reg 3) = 1) :
+ let mem := after initial (eventLog (reports w low f))
+ let src := low + offset width (number e)
+ let n := width (number e)
+ ∃ out, out.pc = done ∧
+ (∀ j : Fin n, out.privateMem (word w (dst+j)) =
+ encodeBit w (encode e (payloads width N number encode f e) j)) ∧
+ ∀ fuel bs, execute M.program (fuel + 5*n+1) c mem bs =
+ (execute M.program fuel out mem bs).map (fun rep ↦ ⟨events mem src n ++ rep.events,
+ rep.result⟩) := by
+ dsimp only
+ have bound := arc_fits width (number e)
+ obtain ⟨out,ho,_,_,_,_,hm,run⟩ := execute_arc hl c hc _ _ _ _
+ (by omega) hdst hread hend hwrite hone
+ refine ⟨out, ho, ?_, run⟩
+ intro j
+ have hj := j.isLt
+ have ha : (word w (dst+j)).val = dst+j := val_word (by omega)
+ rw [hm, payloads_bit, copySlice, ha]
+ have hi : dst ≤ dst+j ∧ dst+j < dst+width (number e) := ⟨by omega, by omega⟩
+ simp only [hi, and_self, ↓reduceIte, Nat.add_sub_cancel_left]
+ have hj' := index_val width (number e) j
+ change (index width (number e) j).val = offset width (number e) + j.val at hj'
+ rw [Nat.add_assoc, ← hj', readback low fit]
+
+/-- Summing the native reader's probe counts at the source and target of
+every arc gives twice the total bit width. Loops contribute both incidences. -/
+theorem endpoint_probe_total [DecidableEq N.Site] (m : Memory w) (low : ℕ) :
+ (∑ v : N.Site, ∑ e : N.Edge,
+ ((if v = N.src e then countProbes (events m (low + offset width (number e)) (width
+ (number e))) else 0) +
+ (if v = N.dst e then countProbes (events m (low + offset width (number e)) (width
+ (number e))) else 0))) =
+ 2 * ∑ t, width t := by
+ rw [Finset.sum_comm]
+ simp [probes, Finset.sum_add_distrib, number.sum_comp, two_mul]
+
+end PairSimulation.EndpointBits
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationEntryWork.lean b/lean/OAI/Computability/VPVNP/PairSimulationEntryWork.lean
new file mode 100644
index 0000000000..77e3c2a309
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationEntryWork.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PairSimulationKernels
+import OAI.Computability.VPVNP.PairSimulationPrivateLabels
+import OAI.Computability.VPVNP.CompressionTemplates
+
+/-!
+# Work of a recorded map occurrence
+
+At a shrink or refresh site, the descriptor records the number of repeated
+base lookups as the map's degree. The fixed selector and base-entry tables
+therefore give a bound in terms of that individual degree on every input,
+including a syntactic zero. Successful lists additionally cost seven native
+counter instructions per label and the loop's final test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression MotifGrid MotifBlocks MotifConversion MotifDemandPadding MotifSelector
+
+universe u
+variable {k : Type u} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+
+/-- Complete arguments of a recorded template lookup, including arbitrary
+incident coordinates in their declared half-wire widths. -/
+structure EntryInput where
+ /-- Number of input bits requested on each demand edge. -/
+ demand : D → ℕ
+ /-- Number of payload bits requested on each supply edge. -/
+ payload : S → ℕ
+ /-- Party at which the interpreter looks up the local tensor entry. -/
+ party : J
+ /-- Input coordinates on the demand half-wires incident to the party. -/
+ demandBits : HalfBits a b demand party
+ /-- Input coordinates on the supply half-wires at the template's computed widths. -/
+ supplyBits : Half P (fun e ↦ Word (supplyWidths B demand payload e)) party
+
+open scoped Classical in
+/-- The actual metered template interpreter and the length of the native
+label-counter prefix when the input is accepted. -/
+noncomputable def EntryInput.work (hp : ∀ i, 0 < p i) (x : EntryInput B) : ℕ :=
+ let res := runEntry B hp x.demand x.payload x.party
+ (MotifEntry.demandBits a b x.party x.demandBits)
+ (mapHalf P (fun _ ↦ MotifEntry.inputBits) x.supplyBits)
+ res.2 + res.1.elim 0 (fun names ↦ 7 * names.length + 1)
+
+/-- The constant depends only on the fixed template and precedes the input
+widths, outer index, party and every supplied bit. -/
+theorem entry_work_le_degree (hp : ∀ i, 0 < p i) :
+ ∃ K : ℕ, ∀ x : EntryInput B, x.work B hp ≤ K * (repetitions B x.demand + 1) ^ 2 := by
+ classical
+ let A := ∑ z : B.grid.demands, ∑ i, baseDemand B z i
+ let W := ∑ s : Selector B, ∑ e, basePayload B s e
+ let K := Fintype.card S * (12 * B.selectorBits + 12 * W + 48) +
+ Fintype.card D * (12 * A + 7) + 2 * (selectorTable B).length + 18
+ have ha (z : B.grid.demands) (i : D) : baseDemand B z i ≤ A :=
+ (Finset.single_le_sum (fun j _ ↦ Nat.zero_le (baseDemand B z j)) (Finset.mem_univ i)).trans
+ (Finset.single_le_sum (fun z _ ↦ Nat.zero_le (∑ j, baseDemand B z j)) (Finset.mem_univ z))
+ have hw (s : Selector B) (e : S) : basePayload B s e ≤ W :=
+ (Finset.single_le_sum (fun j _ ↦ Nat.zero_le (basePayload B s j)) (Finset.mem_univ e)).trans
+ (Finset.single_le_sum (fun s _ ↦ Nat.zero_le (∑ j, basePayload B s j)) (Finset.mem_univ s))
+ refine ⟨K + 8, fun x ↦ ?_⟩
+ let z := demandGrid B hp x.demand
+ let n := repetitions B x.demand
+ let run := runEntry B hp x.demand x.payload x.party
+ (MotifEntry.demandBits a b x.party x.demandBits)
+ (mapHalf P (fun _ ↦ MotifEntry.inputBits) x.supplyBits)
+ have hr : run.2 ≤ K * (n+1)^2 :=
+ MotifEntry.run_le a b (baseDemand B z) _ P _ (lookup B z) _ _ _ _ _ _ (ha z) hw
+ have hl : run.1.elim 0 (fun names ↦ 7 * names.length + 1) ≤ 7*n + 1 := by
+ dsimp only [run]
+ rw [runEntry_list]
+ cases entry B hp x.demand x.payload x.party x.demandBits x.supplyBits <;> simp [n]
+ change run.2 + _ ≤ _
+ rw [Nat.add_mul]
+ apply Nat.add_le_add hr
+ exact hl.trans (by change 7*n+1 ≤ 8*(n+1)^2; nlinarith)
+
+variable {T : BlockSchedule k}
+
+/-- The two actual map interpreters at a block schedule's sites. The recorded
+degree of a map bounds its base copies. A diagonal test can emit no labels. -/
+inductive MapInvocation (F : T.Templates) (d : ℕ)
+ | shrink (input : EntryInput F.shrink) (degree : repetitions F.shrink input.demand ≤ d)
+ | refresh (input : EntryInput F.refresh) (degree : repetitions F.refresh input.demand ≤ d)
+ | noLookup
+
+/-- Interpreter and label-counter work of the selected lookup, or zero when no lookup runs. -/
+noncomputable def MapInvocation.work {F : T.Templates} {d : ℕ} : MapInvocation F d → ℕ
+ | .shrink x _ => x.work _ ShrinkMotif.demandMass_pos
+ | .refresh x _ => x.work _ (fun _ ↦ zero_lt_one)
+ | .noLookup => 0
+
+/-- One constant controls both template tables at every level. -/
+theorem mapInvocation_bound (F : T.Templates) :
+ ∃ K : ℕ, ∀ d (m : MapInvocation F d), m.work ≤ K * (d + 1)^2 := by
+ obtain ⟨A, hA⟩ := entry_work_le_degree F.shrink ShrinkMotif.demandMass_pos
+ obtain ⟨B, hB⟩ := entry_work_le_degree F.refresh (fun _ ↦ zero_lt_one)
+ refine ⟨max A B, fun d m ↦ ?_⟩
+ cases m with
+ | noLookup => exact Nat.zero_le _
+ | shrink x hx =>
+ exact (hA x).trans (Nat.mul_le_mul (le_max_left ..)
+ (Nat.pow_le_pow_left (Nat.succ_le_succ hx) 2))
+ | refresh x hx =>
+ exact (hB x).trans (Nat.mul_le_mul (le_max_right ..)
+ (Nat.pow_le_pow_left (Nat.succ_le_succ hx) 2))
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationFieldRead.lean b/lean/OAI/Computability/VPVNP/PairSimulationFieldRead.lean
new file mode 100644
index 0000000000..49b457f3d4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationFieldRead.lean
@@ -0,0 +1,204 @@
+import OAI.Computability.VPVNP.MotifEntry
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+
+/-!
+# Reading a padded motif field in private RAM
+
+Incident bit strings occupy consecutive private cells. The reader scans a
+little-endian field from its high end, doubling its accumulator before adding
+the next bit. A private comparison selects a load inside the string and a
+literal zero beyond it. Both paths take six instructions per bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.FieldRead
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord MotifEntry PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {w p r k len : ℕ}
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+
+private theorem val_word {n : ℕ} (hn : n < 2 ^ w) : (word w n).val = n :=
+ Nat.mod_eq_of_lt hn
+
+/-- Registers hold the accumulator, descending cursor, field start, data
+end, one, and a temporary bit. All three addresses are absolute. -/
+def instruction (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) : Fin 7 → Instr w p r k :=
+ ![.jumpEq (reg 1) (reg 2) done (pc 1), .binary .sub (reg 1) (reg 1) (reg 4) (pc 2),
+ .binary .add (reg 0) (reg 0) (reg 0) (pc 3), .jumpLt (reg 1) (reg 3) (pc 4) (pc 5),
+ .loadPrivate (reg 5) (reg 1) (pc 6), .constant (reg 5) 0 (pc 6),
+ .binary .add (reg 0) (reg 0) (reg 5) (pc 0)]
+
+theorem resize_instruction (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) (i : Fin 7) :
+ (instruction (w := 1) (k := k) pc reg done i).resize w = instruction pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- Require the seven padded-field reader instructions at the assigned labels and registers.
+The descending scan doubles the accumulator and adds either the private bit or a padding
+zero before returning to its loop test. -/
+def Linked (M : Machine w p r k) (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+/-- A concrete register file and instruction table. Its eighth instruction
+returns the result word in register zero. -/
+def template : Template 8 6 0 where
+ literalWidth := 1
+ entry := 0
+ code := Fin.lastCases (.returnState 0)
+ (instruction Fin.castSucc (Function.Embedding.refl _) (Fin.last 7))
+
+theorem template_linked (pub : Fin 0 → Word w) :
+ Linked (template.instantiate w pub) Fin.castSucc (Function.Embedding.refl _) (Fin.last 7) := by
+ intro i
+ change ((Fin.lastCases _ _ i.castSucc : Instr 1 8 6 0).resize w) = _
+ rw [Fin.lastCases_castSucc]
+ exact resize_instruction _ _ _ i
+
+variable {M : Machine w p r k} {pc : Fin 7 → Fin p} {reg : Fin 6 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (hl : Linked M pc reg done) (i : Fin 7) {c : Config w p r}
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+/-- Reading the highest bit last in the sum gives the descending Horner recursion. -/
+theorem readField_succ_last (bits : Fin len → Bool) (off n : ℕ) :
+ readField bits off (n + 1) =
+ readField bits off n + (paddedBit bits (off + n)).toNat * 2 ^ n := by
+ rw [readField_eq_sum, readField_eq_sum, Fin.sum_univ_castSucc]
+ rfl
+
+private theorem body (hl : Linked M pc reg done) (bits : Fin len → Bool) (base pos : ℕ)
+ (c : Config w p r) (hc : c.pc = pc 0) (hne : c.reg (reg 1) ≠ c.reg (reg 2))
+ (hcursor : c.reg (reg 1) = word w (base + pos + 1)) (hone : c.reg (reg 4) = 1)
+ (hend : c.reg (reg 3) = word w (base + len)) (hfit : base + pos < 2 ^ w)
+ (hdataFit : base + len < 2 ^ w)
+ (hdata : ∀ j : Fin len, c.privateMem (word w (base + j.val)) = encodeBit w (bits j)) :
+ ∃ out, Prefix M c (List.replicate 6 .tick) out ∧ out.pc = pc 0 ∧
+ out.reg (reg 0) = c.reg (reg 0) + c.reg (reg 0) + word w (paddedBit bits pos).toNat ∧
+ out.reg (reg 1) = word w (base + pos) ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 5 → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let c₁ := {c with pc := pc 1}
+ let c₂ := c₁.put (pc 2) (reg 1) (word w (base + pos))
+ let twice := c.reg (reg 0) + c.reg (reg 0)
+ let c₃ := c₂.put (pc 3) (reg 0) twice
+ let c₄ := {c₃ with pc := if pos < len then pc 4 else pc 5}
+ let bit := word w (paddedBit bits pos).toNat
+ let c₅ := c₄.put (pc 6) (reg 5) bit
+ let out := c₅.put (pc 0) (reg 0) (twice + bit)
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step_at hl 0 hc]
+ simp [instruction, Instr.run, hne, c₁]
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at hl 1 rfl]
+ change CallAction.localStep (c₁.put (pc 2) (reg 1) (c.reg (reg 1) - c.reg (reg 4))) = _
+ simp [c₂, hcursor, hone, word]
+ have s₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step_at hl 2 rfl]
+ change CallAction.localStep (c₂.put (pc 3) (reg 0) (c₂.reg (reg 0) + c₂.reg (reg 0))) = _
+ simp [c₃, c₂, c₁, Config.put, twice]
+ have hcurs : c₃.reg (reg 1) = word w (base + pos) := by simp [c₃, c₂, Config.put]
+ have hlim : c₃.reg (reg 3) = word w (base + len) := by simp [c₃, c₂, c₁, Config.put, hend]
+ have hlt : c₃.reg (reg 1) < c₃.reg (reg 3) ↔ pos < len := by
+ rw [hcurs, hlim, Fin.lt_def, val_word hfit, val_word hdataFit, Nat.add_lt_add_iff_left]
+ have s₃ : M.program.step c₃ = .localStep c₄ := by
+ rw [step_at hl 3 rfl]
+ change CallAction.localStep
+ {c₃ with pc := if c₃.reg (reg 1) < c₃.reg (reg 3) then pc 4 else pc 5} = _
+ simp [c₄, hlt]
+ have s₄ : M.program.step c₄ = .localStep c₅ := by
+ by_cases h : pos < len
+ · rw [step_at hl 4 (by simp [c₄, h])]
+ change CallAction.localStep (c₄.put (pc 6) (reg 5) (c.privateMem (c₃.reg (reg 1)))) = _
+ rw [hcurs, hdata ⟨pos, h⟩]
+ cases hb : bits ⟨pos, h⟩ <;> simp [c₅, bit, paddedBit, h, hb, encodeBit]
+ · rw [step_at hl 5 (by simp [c₄, h])]
+ change CallAction.localStep (c₄.put (pc 6) (reg 5) 0) = _
+ simp [c₅, bit, paddedBit, h]
+ have s₅ : M.program.step c₅ = .localStep out := by
+ rw [step_at hl 6 rfl]
+ change CallAction.localStep (c₅.put (pc 0) (reg 0) (c₅.reg (reg 0) + c₅.reg (reg 5))) = _
+ simp [out, c₅, c₄, c₃, Config.put]
+ refine ⟨out, .tick s₀ (.tick s₁ (.tick s₂ (.tick s₃ (.tick s₄ (.tick s₅ (.nil _)))))),
+ rfl, by simp [out, twice, bit], by simp [out, c₅, c₄, c₃, c₂, Config.put], ?_, rfl, rfl⟩
+ intro j h₀ h₁ h₅
+ simp [out, c₅, c₄, c₃, c₂, c₁, Config.put, Function.update_of_ne, h₀, h₁, h₅]
+
+/-- Exact private execution with any initial accumulator. All registers
+outside the accumulator, cursor and temporary, and all memory cells, are
+preserved for the continuation. -/
+theorem accumulate (hl : Linked M pc reg done) (bits : Fin len → Bool) (base off n : ℕ)
+ (c : Config w p r) (hc : c.pc = pc 0) (hfit : base + off + n < 2 ^ w)
+ (hdataFit : base + len < 2 ^ w)
+ (hcursor : c.reg (reg 1) = word w (base + off + n))
+ (hstop : c.reg (reg 2) = word w (base + off))
+ (hend : c.reg (reg 3) = word w (base + len)) (hone : c.reg (reg 4) = 1)
+ (hdata : ∀ j : Fin len, c.privateMem (word w (base + j.val)) = encodeBit w (bits j)) :
+ ∃ out, Prefix M c (List.replicate (6 * n + 1) .tick) out ∧ out.pc = done ∧
+ out.reg (reg 0) = c.reg (reg 0) * word w (2 ^ n) + word w (readField bits off n) ∧
+ out.reg (reg 1) = word w (base + off) ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 5 → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ induction n generalizing c with
+ | zero =>
+ have eq : c.reg (reg 1) = c.reg (reg 2) := hcursor.trans hstop.symm
+ have hs : M.program.step c = .localStep {c with pc := done} := by
+ rw [step_at hl 0 hc]
+ simp [instruction, Instr.run, eq]
+ exact ⟨_, .tick hs (.nil _), rfl, by simp [word, readField], hcursor,
+ fun _ _ _ _ ↦ rfl, rfl, rfl⟩
+ | succ n ih =>
+ have ne : c.reg (reg 1) ≠ c.reg (reg 2) := by
+ rw [hcursor, hstop]
+ intro eq
+ have h := congrArg Fin.val eq
+ rw [val_word hfit, val_word (by omega : base + off < 2 ^ w)] at h
+ omega
+ obtain ⟨mid, pre, hm, hacc, hcur, other, hmem, hper⟩ := body hl bits base (off + n) c hc ne
+ (by simpa [Nat.add_assoc] using hcursor) hone hend (by omega) hdataFit hdata
+ obtain ⟨out, tail, ho, ha, hcur', other', hmem', hper'⟩ := ih mid hm (by omega)
+ (by simpa [Nat.add_assoc] using hcur) (by rw [other, hstop] <;> simp)
+ (by rw [other, hend] <;> simp) (by rw [other, hone] <;> simp) (hmem ▸ hdata)
+ refine ⟨out, ?_, ho, ?_, hcur', fun j h₀ h₁ h₅ ↦
+ (other' j h₀ h₁ h₅).trans (other j h₀ h₁ h₅), hmem'.trans hmem, hper'.trans hper⟩
+ · convert pre.append tail using 1
+ rw [← List.replicate_add]
+ congr 1
+ omega
+ · rw [ha, hacc, readField_succ_last]
+ simp only [word, pow_succ, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+ ring
+
+/-- A zeroed accumulator and a field at most one word wide recover the
+natural value. The prefix length agrees exactly with the abstract meter,
+also for the empty field and for fields extending into padding. -/
+theorem native_read (hl : Linked M pc reg done) (bits : Fin len → Bool) (base off n : ℕ)
+ (c : Config w p r) (hc : c.pc = pc 0) (hn : n ≤ w) (hfit : base + off + n < 2 ^ w)
+ (hdataFit : base + len < 2 ^ w)
+ (hzero : c.reg (reg 0) = 0) (hcursor : c.reg (reg 1) = word w (base + off + n))
+ (hstop : c.reg (reg 2) = word w (base + off)) (hend : c.reg (reg 3) = word w (base + len))
+ (hone : c.reg (reg 4) = 1)
+ (hdata : ∀ j : Fin len, c.privateMem (word w (base + j.val)) = encodeBit w (bits j)) :
+ ∃ out, Prefix M c (List.replicate (meteredField bits off n).2 .tick) out ∧ out.pc = done ∧
+ (out.reg (reg 0)).val = readField bits off n ∧ out.reg (reg 1) = word w (base + off) ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 5 → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ rw [meteredField_spec]
+ obtain ⟨out, pre, ho, ha, hcur, other, hmem, hper⟩ := accumulate hl bits base off n c hc
+ hfit hdataFit hcursor hstop hend hone hdata
+ refine ⟨out, pre, ho, ?_, hcur, other, hmem, hper⟩
+ rw [ha, hzero, zero_mul, zero_add, val_word]
+ exact (readField_lt bits off n).trans_le (Nat.pow_le_pow_right (by decide) hn)
+
+end PairSimulation.FieldRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationFieldReadSafety.lean b/lean/OAI/Computability/VPVNP/PairSimulationFieldReadSafety.lean
new file mode 100644
index 0000000000..640098b395
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationFieldReadSafety.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.PairSimulationSliceReads
+import OAI.Computability.VPVNP.PairSimulationTerminalSplice
+import OAI.Computability.VPVNP.PairSimulationRefreshSliceClock
+import OAI.Computability.VPVNP.CompressorSliceIndexedStarts
+
+/-!
+# Field traces below the terminal header
+
+External reads confined below the allocated terminal header exclude its stage and
+saved-state cells. The two slice formats locate their length and offsets at different
+addresses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open BurstRAM CompressorRecords CompressorRecords.PhaseRecipe CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+variable {w : ℕ} {data : ℕ → Prop}
+
+/-- All addresses below a fitting terminal header avoid the stage cell and saved word. -/
+theorem TerminalLink.workerCell_of_lt {H : Word w} (fit : H.val + 31 < 2 ^ w)
+ {i : ℕ} (below : i < H.val) : TerminalLink.workerCell H i := by
+ have last : (H + 31).val = H.val + 31 := by
+ rw [Fin.val_add, show (31 : Word w) = ((31 : ℕ) : Word w) from rfl, Fin.val_natCast,
+ Nat.mod_eq_of_lt (by omega : 31 < 2 ^ w), Nat.mod_eq_of_lt fit]
+ exact ⟨below.ne, by rw [last]; omega⟩
+
+/-- Register formulas whose loads all precede the terminal header read worker cells. -/
+theorem TerminalLink.expr_worker_reads {H : Word w} (fit : H.val + 31 < 2 ^ w)
+ {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w} {e : Expr}
+ (allowed : e.ReadsFrom (· < H.val) pub state mem) :
+ e.ReadsFrom (TerminalLink.workerCell H) pub state mem :=
+ allowed.mono fun _ hi => TerminalLink.workerCell_of_lt fit hi
+
+/-- A natural frame head and its two successors all lie below the terminal header. -/
+theorem PrivateSlices.frameEvents_worker_reads {H : Word w} (fit : H.val + 31 < 2 ^ w)
+ (m : Memory w) (head : ℕ) (bs : List Bool) (before : head + 2 < H.val) :
+ Reads (TerminalLink.workerCell H) (PrivateSlices.frameEvents m (head : Word w) bs) := by
+ have bound := before.trans H.isLt
+ have a₀ : (head : Word w).val = head := Nat.mod_eq_of_lt (by omega)
+ have a₁ : ((head : Word w) + 1).val = head + 1 := by
+ rw [← Nat.cast_add_one]
+ exact Nat.mod_eq_of_lt (by omega)
+ have a₂ : ((head : Word w) + 1 + 1).val = head + 2 := by
+ rw [← Nat.cast_add_one, ← Nat.cast_add_one]
+ exact Nat.mod_eq_of_lt bound
+ apply PrivateSlices.frameEvents_reads <;> apply TerminalLink.workerCell_of_lt fit <;> omega
+
+/-- Source-major indexing puts the three cells of any AB frame strictly inside
+the allocated interval bank for its bundle. -/
+theorem PrivateSlices.ab_frame_before {bank H m n : ℕ} (source : Fin m) (target : Fin n)
+ (before : bank + IndexedStarts.capacity m n ≤ H) :
+ bank + m + n + 3 * (source.val * n + target.val) + 2 < H := by
+ have idx : source.val * n + target.val < m * n := calc
+ _ < source.val * n + n := Nat.add_lt_add_left target.isLt _
+ _ = (source.val + 1) * n := (Nat.succ_mul ..).symm
+ _ ≤ _ := Nat.mul_le_mul_right n source.isLt
+ unfold IndexedStarts.capacity at before
+ omega
+
+/-- The surviving row holds one frame per subdivision, preceding its directory
+references in the same allocated bank. -/
+theorem PrivateSlices.surviving_frame_before {bank H q : ℕ} (j : Fin q)
+ (before : SliceSchedule.stop bank 1 q ≤ H) :
+ SliceSchedule.frameHead bank 1 q + 3 * j.val + 2 < H := by
+ simp only [SliceSchedule.stop, one_mul] at before
+ have := j.isLt
+ omega
+
+/-- The two reads of a refresh segment use the selected width and offset column heads
+at its physical ordinal. -/
+theorem RefreshSliceClock.segmentEvents_reads_iff (m : Memory w) (width offset ordinal : Word w)
+ (bs : List Bool) :
+ Reads data (RefreshSliceClock.segmentEvents m width offset ordinal bs) ↔
+ data (width + ordinal).val ∧ data (offset + ordinal).val := by
+ have header : Reads data (RefreshSliceClock.segmentEvents m width offset ordinal bs) ↔
+ Reads data (RefreshSliceClock.headerEvents m width offset ordinal) := by
+ constructor
+ · exact fun h a v hv => h a v (List.mem_append_left _ hv)
+ · intro h a v hv
+ exact (List.mem_append.mp hv).elim (h a v) (PrivateFields.events_reads .copy bs a v)
+ rw [header]
+ simp [RefreshSliceClock.headerEvents, Reads, or_imp, forall_and]
+
+/-- All segments in two allocated refresh columns precede the terminal controls.
+The bound uses the ordinal within the columns, including at their last cell. -/
+theorem RefreshSliceClock.segmentEvents_worker_reads {H : Word w} (fit : H.val + 31 < 2 ^ w)
+ (m : Memory w) (width offset ordinal : Word w) (bs : List Bool) {n : ℕ} (idx : ordinal.val < n)
+ (widthBefore : width.val + n ≤ H.val) (offsetBefore : offset.val + n ≤ H.val) :
+ Reads (TerminalLink.workerCell H)
+ (RefreshSliceClock.segmentEvents m width offset ordinal bs) := by
+ rw [RefreshSliceClock.segmentEvents_reads_iff]
+ have below (base : Word w) (bound : base.val + n ≤ H.val) : (base + ordinal).val < H.val := by
+ have h := (Nat.add_lt_add_left idx base.val).trans_le bound
+ rwa [Fin.val_add, Nat.mod_eq_of_lt (h.trans H.isLt)]
+ exact ⟨TerminalLink.workerCell_of_lt fit (below width widthBefore),
+ TerminalLink.workerCell_of_lt fit (below offset offsetBefore)⟩
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationFinalBitScan.lean b/lean/OAI/Computability/VPVNP/PairSimulationFinalBitScan.lean
new file mode 100644
index 0000000000..5cdf909c10
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationFinalBitScan.lean
@@ -0,0 +1,373 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalSplice
+import OAI.Computability.VPVNP.PairSimulationFinalBitWorker
+
+/-!
+# Native histories of the terminal shared-bit worker
+
+The terminal header gives the total number of bits and their base address.
+The worker consumes singleton choices in descending physical order and then
+consumes one empty closing call. Replaying its reports builds the same memory
+image as the shared-wire reports used by the contraction formula.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.FinalBits.Worker
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The two header cells stay outside the address range written by the worker. -/
+structure Layout (pub : Fin 11 → Word w) (m : Memory w) (lo count : ℕ) : Prop where
+ base_eq : base pub m = (lo : Word w)
+ total_eq : total pub m = (count : Word w)
+ fits : lo + count < 2 ^ w
+ base_disjoint : ∀ j < count, (header pub + 13).val ≠ lo + j
+ total_disjoint : ∀ j < count, (header pub + 12).val ≠ lo + j
+
+private theorem header_offset (pub : Fin 11 → Word w) (k : ℕ) (hk : k < 32)
+ (room : (header pub).val + 32 ≤ 2 ^ w) :
+ (header pub + (k : Word w)).val = (header pub).val + k := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : k < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega)]
+
+/-- The physical wire interval ends below the terminal header. -/
+theorem Layout.ofBelow {pub : Fin 11 → Word w} {m : Memory w} {lo count : ℕ}
+ (hb : base pub m = (lo : Word w)) (ht : total pub m = (count : Word w))
+ (below : lo + count ≤ (header pub).val) (room : (header pub).val + 32 ≤ 2 ^ w) :
+ Layout pub m lo count := by
+ refine ⟨hb, ht, by omega, ?_, ?_⟩
+ · intro j hj
+ rw [show (header pub + 13).val = _ from header_offset pub 13 (by decide) room]
+ omega
+ · intro j hj
+ rw [show (header pub + 12).val = _ from header_offset pub 12 (by decide) room]
+ omega
+
+/-- The reports contain the actual header reads, choices, writes, returned
+ordinals and the accepting report of the last call. -/
+def reports (pub : Fin 11 → Word w) : (i : ℕ) → (m : Memory w) →
+ {n : ℕ} → (Fin n → Bool) → List (Report w)
+ | _, m, 0, _ => [closeReport pub m]
+ | i, m, n + 1, f =>
+ let r := activeReport pub (i : Word w) m (f (Fin.last n))
+ r :: reports pub (i + 1) (after m r.events) (Fin.init f)
+
+private theorem active_at {pub : Fin 11 → Word w} {m : Memory w} {lo count i n : ℕ}
+ (h : Layout pub m lo count) (hcount : i + (n + 1) = count) :
+ (i : Word w) < total pub m ∧ address pub m (i : Word w) = cursor w lo n := by
+ have ht := h.fits
+ constructor
+ · rw [h.total_eq]
+ change i % (2 ^ w) < count % (2 ^ w)
+ rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)]
+ omega
+ · rw [address, h.base_eq, h.total_eq, ← hcount]
+ simp only [cursor, Nat.cast_add, Nat.cast_one]
+ abel
+
+private theorem next_layout {pub : Fin 11 → Word w} {m : Memory w} {lo count i n : ℕ}
+ (h : Layout pub m lo count) (hcount : i + (n + 1) = count) (b : Bool) :
+ Layout pub (after m (activeReport pub (i : Word w) m b).events) lo count := by
+ have hj : n < count := by omega
+ have hv : (cursor w lo n).val = lo + n :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left hj lo).trans h.fits)
+ rw [active_image, (active_at h hcount).2]
+ refine ⟨?_, ?_, h.fits, h.base_disjoint, h.total_disjoint⟩
+ · simpa only [base, writeMemory, hv, ite_eq_right (h.base_disjoint n hj)] using h.base_eq
+ · simpa only [total, writeMemory, hv, ite_eq_right (h.total_disjoint n hj)] using h.total_eq
+
+private theorem run_from {pub : Fin 11 → Word w} {lo count : ℕ} (extra n i : ℕ)
+ (m : Memory w) (h : Layout pub m lo count) (hcount : i + n = count) (f : Fin n → Bool) :
+ runSegment (table.instantiate w pub).program (extra + 24) (some (i : Word w)) m
+ (calls f ++ [[]]) = some (reports pub i m f) := by
+ induction n generalizing i m with
+ | zero =>
+ have hi : (i : Word w) = total pub m := by simpa [← hcount] using h.total_eq.symm
+ change runSegment _ _ (some (i : Word w)) m [[]] = _
+ rw [runSegment, close pub _ m hi]
+ rfl
+ | succ n ih =>
+ let b := f (Fin.last n)
+ let m' := after m (activeReport pub (i : Word w) m b).events
+ have tailRun := ih (i + 1) m' (next_layout h hcount b) (by omega) (Fin.init f)
+ rw [calls_succ, List.cons_append, runSegment, active pub _ m (active_at h hcount).1]
+ simp only [active_result, ← Nat.cast_add_one]
+ change (runSegment _ _ (some ((i + 1 : ℕ) : Word w)) m' _).map _ = _
+ rw [tailRun]
+ rfl
+
+/-- Full native execution from the zero ordinal, including the closing call. -/
+theorem run_scan (pub : Fin 11 → Word w) (m : Memory w) {lo count : ℕ}
+ (h : Layout pub m lo count) (f : Fin count → Bool) (extra : ℕ) :
+ runSegment (table.instantiate w pub).program (extra + 24) (some 0) m
+ (calls f ++ [[]]) = some (reports pub 0 m f) :=
+ run_from extra count 0 m h (Nat.zero_add count) f
+
+private theorem image_from {pub : Fin 11 → Word w} {lo count : ℕ} (n i : ℕ)
+ (m : Memory w) (h : Layout pub m lo count) (hcount : i + n = count) (f : Fin n → Bool) :
+ after m (eventLog (reports pub i m f)) = after m (eventLog (FinalBits.reports w lo f)) := by
+ induction n generalizing i m with
+ | zero => exact close_image pub m
+ | succ n ih =>
+ let b := f (Fin.last n)
+ let m' := after m (activeReport pub (i : Word w) m b).events
+ have tailRun := ih (i + 1) m' (next_layout h hcount b) (by omega) (Fin.init f)
+ rw [reports, FinalBits.reports_succ]
+ simp only [eventLog, List.flatMap_cons, after, List.foldl_append]
+ change after m' (eventLog (reports pub (i + 1) m' (Fin.init f))) =
+ after (after m (bitReport (cursor w lo n) b).events) (eventLog (FinalBits.reports w lo (Fin.init f)))
+ rw [tailRun]
+ have mem : m' = after m (bitReport (cursor w lo n) b).events := by
+ rw [bitReport_memory, ← (active_at h hcount).2]
+ exact active_image pub _ m b
+ rw [mem]
+
+/-- Native reports replay to the original reverse-order wire image. -/
+theorem image (pub : Fin 11 → Word w) (m : Memory w) {lo count : ℕ}
+ (h : Layout pub m lo count) (f : Fin count → Bool) :
+ after m (eventLog (reports pub 0 m f)) = after m (eventLog (FinalBits.reports w lo f)) :=
+ image_from count 0 m h (Nat.zero_add count) f
+
+theorem readback (pub : Fin 11 → Word w) (m : Memory w) {lo count : ℕ}
+ (h : Layout pub m lo count) (f : Fin count → Bool) (j : Fin count) :
+ after m (eventLog (reports pub 0 m f)) (lo + j) = encodeBit w (f j) := by
+ rw [image pub m h f]
+ exact FinalBits.readback lo h.fits f m j
+
+theorem outside (pub : Fin 11 → Word w) (m : Memory w) {lo count : ℕ}
+ (h : Layout pub m lo count) (f : Fin count → Bool) (a : ℕ) (ha : a < lo ∨ lo + count ≤ a) :
+ after m (eventLog (reports pub 0 m f)) a = m a := by
+ rw [image pub m h f]
+ exact FinalBits.outside lo h.fits f m a ha
+
+theorem scan_cost (pub : Fin 11 → Word w) (n i : ℕ) (m : Memory w) (f : Fin n → Bool) :
+ (reports pub i m f).length = n + 1 ∧
+ RAMBuckets.cost Report.probes (reports pub i m f) = 4 * n + 2 ∧
+ ∀ r ∈ reports pub i m f, r.probes ≤ 3 ∧ r.events.length ≤ 23 := by
+ induction n generalizing i m with
+ | zero =>
+ simp only [reports, List.length_singleton, RAMBuckets.cost, (close_cost pub m).1,
+ List.mem_singleton, forall_eq, (close_cost pub m).2]
+ decide
+ | succ n ih =>
+ let b := f (Fin.last n)
+ let r := activeReport pub (i : Word w) m b
+ obtain ⟨hlen, hcost, hlocal⟩ := ih (i + 1) (after m r.events) (Fin.init f)
+ have hr := active_cost pub (i : Word w) m b
+ let rest := reports pub (i + 1) (after m r.events) (Fin.init f)
+ change rest.length = _ at hlen
+ change RAMBuckets.cost Report.probes rest = _ at hcost
+ change (r :: rest).length = _ ∧ RAMBuckets.cost Report.probes (r :: rest) = _ ∧ ∀ s ∈ r :: rest, _
+ change r.probes = 3 ∧ r.events.length = 23 at hr
+ simp only [List.length_cons, hlen, RAMBuckets.cost, hr.1, hcost, List.mem_cons, forall_eq_or_imp]
+ exact ⟨trivial, by omega, ⟨hr.1.le, hr.2.le⟩, hlocal⟩
+
+private theorem complete_from {pub : Fin 11 → Word w} {lo count : ℕ} (extra n i : ℕ)
+ (m : Memory w) (h : Layout pub m lo count) (hcount : i + n = count)
+ (bs : List (List Bool)) (rs : List (Report w))
+ (run : runSegment (table.instantiate w pub).program (extra + 24) (some (i : Word w)) m bs = some rs)
+ (halt : endState (some (i : Word w)) rs = none) :
+ ∃ f : Fin n → Bool, bs = calls f ++ [[]] ∧ rs = reports pub i m f := by
+ induction n generalizing i m bs rs with
+ | zero =>
+ have hi : (i : Word w) = total pub m := by simpa [← hcount] using h.total_eq.symm
+ cases bs with
+ | nil =>
+ obtain rfl : rs = [] := (Option.some.inj run).symm
+ contradiction
+ | cons head tail =>
+ rw [runSegment, close pub _ m hi] at run
+ cases head with
+ | cons => contradiction
+ | nil =>
+ cases tail with
+ | cons => contradiction
+ | nil =>
+ exact ⟨Fin.elim0, rfl, (Option.some.inj run).symm⟩
+ | succ n ih =>
+ cases bs with
+ | nil =>
+ obtain rfl : rs = [] := (Option.some.inj run).symm
+ contradiction
+ | cons head tail =>
+ rw [runSegment, active pub _ m (active_at h hcount).1] at run
+ cases head with
+ | nil => contradiction
+ | cons b rest =>
+ cases rest with
+ | cons => contradiction
+ | nil =>
+ obtain ⟨ts, hts, rfl⟩ := Option.map_eq_some_iff.mp run
+ let r := activeReport pub (i : Word w) m b
+ have hs : r.result = some ((i + 1 : ℕ) : Word w) := by simp [r]
+ change runSegment _ _ r.result (after m r.events) tail = some ts at hts
+ change endState r.result ts = none at halt
+ rw [hs] at hts halt
+ obtain ⟨f, rfl, rfl⟩ := ih (i + 1) (after m r.events) (next_layout h hcount b)
+ (by omega) tail ts hts halt
+ refine ⟨Fin.snoc f b, ?_, ?_⟩
+ · simp [calls_succ]
+ · simp [reports, r]
+
+theorem reports_halt (pub : Fin 11 → Word w) (n i : ℕ) (m : Memory w) (f : Fin n → Bool)
+ (start : Option (Word w)) : endState start (reports pub i m f) = none := by
+ induction n generalizing i m start with
+ | zero => rfl
+ | succ n ih => exact ih _ _ _ _
+
+/-- Acceptance itself forces every data choice, the number of calls and the
+single empty closing call. The reports retain the full native probe history. -/
+theorem accepted_iff (pub : Fin 11 → Word w) (m : Memory w) {lo count : ℕ}
+ (h : Layout pub m lo count) (extra : ℕ) (bs : List (List Bool)) (rs : List (Report w)) :
+ (runSegment (table.instantiate w pub).program (extra + 24) (some 0) m bs = some rs ∧
+ endState (some 0) rs = none) ↔
+ ∃ f : Fin count → Bool, bs = calls f ++ [[]] ∧ rs = reports pub 0 m f := by
+ constructor
+ · rintro ⟨run, halt⟩
+ exact complete_from extra count 0 m h (Nat.zero_add count) bs rs run halt
+ · rintro ⟨f, rfl, rfl⟩
+ exact ⟨run_scan pub m h f extra, reports_halt pub _ 0 m f _⟩
+
+/-- Shared-bit assignments enumerate exactly the accepted paths. The cap
+predicate may include clock and external-probe bounds on the actual reports. -/
+noncomputable def acceptedEquiv (pub : Fin 11 → Word w) (m : Memory w) {lo count : ℕ}
+ (h : Layout pub m lo count) (extra : ℕ) (caps : List (Report w) → Prop)
+ (bound : ∀ f : Fin count → Bool, caps (reports pub 0 m f)) :
+ (Fin count → Bool) ≃ ActualPaths (table.instantiate w pub).program (extra + 24) 0 m caps := by
+ let path (f : Fin count → Bool) :
+ ActualPaths (table.instantiate w pub).program (extra + 24) 0 m caps :=
+ ⟨calls f ++ [[]], reports pub 0 m f, run_scan pub m h f extra, reports_halt pub _ 0 m f _, bound f⟩
+ apply Equiv.ofBijective path
+ constructor
+ · intro f g he
+ exact calls_injective (List.append_cancel_right (congrArg Subtype.val he))
+ · rintro ⟨bs, rs, run, halt, _⟩
+ obtain ⟨f, hf, _⟩ := (accepted_iff pub m h extra bs rs).mp ⟨run, halt⟩
+ exact ⟨f, Subtype.ext hf.symm⟩
+
+open CompressorRecords.SourceTransport
+open private testEvents from OAI.Computability.VPVNP.PairSimulationFinalBitWorker
+
+private def away (pub : Fin 11 → Word w) (x : ℕ) : Prop :=
+ x ≠ (header pub).val ∧ x ≠ (header pub + 31).val
+
+private theorem field_away (pub : Fin 11 → Word w) (room : (header pub).val + 32 ≤ 2 ^ w)
+ (k : ℕ) (hk : 0 < k) (hk' : k < 31) : away pub (header pub + (k : Word w)).val := by
+ rw [away, header_offset pub k (by omega) room,
+ show (header pub + 31).val = _ from header_offset pub 31 (by decide) room]
+ omega
+
+private theorem active_frame {pub : Fin 11 → Word w} {m : Memory w} {i : Word w} (b : Bool)
+ (room : (header pub).val + 32 ≤ 2 ^ w) (dest : away pub (address pub m i).val) :
+ Reads (away pub) (activeReport pub i m b).events ∧ Writes (away pub) (activeReport pub i m b).events := by
+ constructor <;> intro a v mem
+ · simp only [activeReport, testEvents, List.mem_append, List.mem_replicate, List.mem_cons,
+ List.not_mem_nil, Event.read.injEq, reduceCtorEq, and_false, false_or, or_false] at mem
+ rcases mem with ⟨rfl, _⟩ | ⟨rfl, _⟩
+ · exact field_away pub room 12 (by decide) (by decide)
+ · exact field_away pub room 13 (by decide) (by decide)
+ · simp only [activeReport, testEvents, List.mem_append, List.mem_replicate, List.mem_cons,
+ List.not_mem_nil, Event.write.injEq, reduceCtorEq, and_false, false_or, or_false] at mem
+ obtain ⟨rfl, _⟩ := mem
+ exact dest
+
+private theorem close_frame (pub : Fin 11 → Word w) (m : Memory w)
+ (room : (header pub).val + 32 ≤ 2 ^ w) :
+ Reads (away pub) (closeReport pub m).events ∧ Writes (away pub) (closeReport pub m).events := by
+ constructor <;> intro a v mem
+ · simp only [closeReport, testEvents, List.mem_append, List.mem_replicate, List.mem_cons,
+ List.not_mem_nil, Event.read.injEq, reduceCtorEq, and_false, false_or, or_false] at mem
+ obtain ⟨rfl, _⟩ := mem
+ exact field_away pub room 12 (by decide) (by decide)
+ · simp only [closeReport, testEvents, List.mem_append, List.mem_replicate, List.mem_cons,
+ List.not_mem_nil, reduceCtorEq, and_false, false_or] at mem
+
+private theorem frame_from {pub : Fin 11 → Word w} {lo count : ℕ} (n i : ℕ)
+ (m : Memory w) (h : Layout pub m lo count) (hcount : i + n = count) (f : Fin n → Bool)
+ (room : (header pub).val + 32 ≤ 2 ^ w) (below : lo + count ≤ (header pub).val) :
+ ∀ r ∈ reports pub i m f, Reads (away pub) r.events ∧ Writes (away pub) r.events := by
+ induction n generalizing i m with
+ | zero =>
+ simpa only [reports, List.mem_singleton, forall_eq] using close_frame pub m room
+ | succ n ih =>
+ intro r hr
+ rw [reports, List.mem_cons] at hr
+ rcases hr with rfl | hr
+ · apply active_frame _ room
+ rw [(active_at h hcount).2, away,
+ show (header pub + 31).val = _ from header_offset pub 31 (by decide) room]
+ have fit := h.fits
+ change (lo + n) % (2 ^ w) ≠ _ ∧ (lo + n) % (2 ^ w) ≠ _
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+ · exact ih (i + 1) _ (next_layout h hcount _) (by omega) (Fin.init f) r hr
+
+/-- All probes avoid the controller cells which hold the phase and the worker's
+persistent state between calls. -/
+theorem controller_frame (pub : Fin 11 → Word w) (m : Memory w) {lo count : ℕ}
+ (h : Layout pub m lo count) (f : Fin count → Bool)
+ (room : (header pub).val + 32 ≤ 2 ^ w) (below : lo + count ≤ (header pub).val) :
+ let data := fun x => x ≠ (TerminalLink.header pub).val ∧ x ≠ (TerminalLink.header pub + 31).val
+ Reads data (eventLog (reports pub 0 m f)) ∧ Writes data (eventLog (reports pub 0 m f)) := by
+ have frames := frame_from count 0 m h (Nat.zero_add count) f room below
+ constructor <;> intro a v mem
+ · obtain ⟨r, hr, he⟩ := List.mem_flatMap.mp mem
+ exact (frames r hr).1 a v he
+ · obtain ⟨r, hr, he⟩ := List.mem_flatMap.mp mem
+ exact (frames r hr).2 a v he
+
+private theorem linked_cost (addr : Word w) (rs : List (Report w)) (state : Word w) :
+ RAMBuckets.cost Report.probes (TerminalLink.stageReports addr (.resume TerminalLink.Stage.sharedBits state) rs) =
+ RAMBuckets.cost Report.probes rs + 4 * rs.length := by
+ induction rs generalizing state with
+ | nil => rfl
+ | cons r rs ih =>
+ let e := TerminalLink.Entry.resume TerminalLink.Stage.sharedBits state
+ have next : (e.follow r).isSome := by
+ cases hr : r.result <;> simp only [e, TerminalLink.Entry.follow, TerminalLink.target, hr] <;> rfl
+ rw [TerminalLink.stageReports, RAMBuckets.cost, TerminalLink.report_probes]
+ change 1 + (r.probes + 2 + (if (e.follow r).isSome then 2 else 0)) + _ = _
+ rw [next]
+ simp only [↓reduceIte, RAMBuckets.cost, List.length_cons, TerminalLink.Entry.stage, ih]
+ omega
+
+/-- Each linked call costs four additional probes, including the handoff from
+the accepting worker call to the vertex stage. -/
+theorem stage_cost (pub : Fin 11 → Word w) (m : Memory w) {count : ℕ} (f : Fin count → Bool) :
+ RAMBuckets.cost Report.probes (TerminalLink.stageReports (header pub)
+ (.resume TerminalLink.Stage.sharedBits 0) (reports pub 0 m f)) = 8 * count + 6 := by
+ obtain ⟨len, cost, _⟩ := scan_cost pub count 0 m f
+ rw [linked_cost, cost, len]
+ omega
+
+/-- The shared-bit stage of the linked terminal program. Its physical reports
+include the control reads and writes for each returned ordinal and the
+handoff to the vertex worker after the closing call. -/
+theorem stageRun (workers : TerminalLink.Stage → LiveProgram.PairTable)
+ (bank : workers TerminalLink.Stage.sharedBits = ⟨28, 5, table⟩)
+ (pub : Fin 11 → Word w) (src phy : Memory w) {lo count : ℕ}
+ (h : Layout pub src lo count) (f : Fin count → Bool) (cap : ℕ)
+ (clock : 54 ≤ cap) (room : (header pub).val + 32 ≤ 2 ^ w)
+ (below : lo + count ≤ (header pub).val)
+ (valid : (TerminalLink.Entry.resume TerminalLink.Stage.sharedBits (0 : Word w)).Valid (header pub) phy)
+ (agree : Agree (TerminalLink.workerCell (header pub)) src phy) :
+ TerminalLink.StageRun workers pub cap (.resume TerminalLink.Stage.sharedBits 0) src phy
+ (calls f ++ [[]]) (reports pub 0 src f) := by
+ apply TerminalLink.closed_stage_run workers pub 24 cap _ src phy _ _ (by omega) clock valid agree
+ (controller_frame pub src h f room below).1
+ · change runSegment ((workers TerminalLink.Stage.sharedBits).table.instantiate w pub).program 24
+ (some 0) src _ = _
+ rw [bank]
+ exact run_scan pub src h f 0
+ · exact reports_halt pub count 0 src f _
+
+end PairSimulation.FinalBits.Worker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationFinalBitWorker.lean b/lean/OAI/Computability/VPVNP/PairSimulationFinalBitWorker.lean
new file mode 100644
index 0000000000..91586d9cbd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationFinalBitWorker.lean
@@ -0,0 +1,233 @@
+import OAI.Computability.VPVNP.PairSimulationFinalBits
+import OAI.Computability.VPVNP.PairSimulationTerminalLink
+
+/-!
+# Final shared-bit worker on the eleven-operand pair interface
+
+Each call reads the total width from the terminal header. A live ordinal
+takes one choice and writes it in reverse address order. The closing ordinal
+accepts with an empty choice stream, and an ordinal above the total rejects.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.FinalBits.Worker
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Base word of the terminal header shared with the stage controller. -/
+abbrev header (pub : Fin 11 → Word w) : Word w := TerminalLink.header pub
+
+/-- Instructions for computing the header address, testing the ordinal and writing one chosen bit. -/
+def instruction (width : ℕ) (pc : Fin 28) : Instr width 28 5 11 :=
+ match pc.val with
+ | 0 => .publicWord 1 7 1
+ | 1 => .constant 2 1 2
+ | 2 => .binary .shiftLeft 1 2 1 3
+ | 3 => .binary .mul 1 1 1 4
+ | 4 => .publicWord 3 2 5
+ | 5 => .binary .add 1 3 1 6
+ | 6 => .constant 3 32 7
+ | 7 => .binary .sub 1 1 3 8
+ | 8 => .stateWord 0 9
+ | 9 => .constant 3 12 10
+ | 10 => .binary .add 3 1 3 11
+ | 11 => .readExternal 3 3 12
+ | 12 => .jumpLt 0 3 13 25
+ | 13 => .constant 4 13 14
+ | 14 => .binary .add 4 1 4 15
+ | 15 => .readExternal 4 4 16
+ | 16 => .binary .add 4 4 3 17
+ | 17 => .binary .sub 4 4 0 18
+ | 18 => .binary .sub 4 4 2 19
+ | 19 => .choose 20 21
+ | 20 => .constant 3 1 22
+ | 21 => .constant 3 0 22
+ | 22 => .writeExternal 4 3 23
+ | 23 => .binary .add 0 0 2 24
+ | 24 => .returnState 0
+ | 25 => .jumpEq 0 3 26 27
+ | 26 => .accept
+ | _ => .reject
+
+/-- Width-independent terminal shared-bit table with all eleven live public operands. -/
+def table : Template 28 5 11 := ⟨6, 0, instruction 6⟩
+
+theorem resize_instruction (width : ℕ) (pc : Fin 28) :
+ (instruction 6 pc).resize width = instruction width pc := by fin_cases pc <;> rfl
+
+/-- Number of wire bits published in terminal header cell 12. -/
+def total (pub : Fin 11 → Word w) (m : Memory w) := m (header pub + 12).val
+
+/-- First wire address published in terminal header cell 13. -/
+def base (pub : Fin 11 → Word w) (m : Memory w) := m (header pub + 13).val
+
+/-- Physical destination of the bit chosen at this ordinal. -/
+def address (pub : Fin 11 → Word w) (m : Memory w) (i : Word w) :=
+ base pub m + total pub m - i - 1
+
+private def testEvents (pub : Fin 11 → Word w) (m : Memory w) : List (Event w) :=
+ List.replicate 11 .tick ++ [.read (header pub + 12) (total pub m), .tick]
+
+/-- Report of a data call, including both header reads and its sole external write. -/
+def activeReport (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) (b : Bool) : Report w :=
+ ⟨testEvents pub m ++ [.tick, .tick, .read (header pub + 13) (base pub m),
+ .tick, .tick, .tick, .choice b, .tick, .write (address pub m i) (encodeBit w b), .tick],
+ some (i + 1)⟩
+
+/-- Report of the accepting call at the final ordinal. -/
+def closeReport (pub : Fin 11 → Word w) (m : Memory w) : Report w :=
+ ⟨testEvents pub m ++ [.tick], none⟩
+
+@[simp] theorem active_result (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) (b : Bool) :
+ (activeReport pub i m b).result = some (i + 1) := rfl
+
+@[simp] theorem close_result (pub : Fin 11 → Word w) (m : Memory w) :
+ (closeReport pub m).result = none := rfl
+
+theorem active_cost (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) (b : Bool) :
+ (activeReport pub i m b).probes = 3 ∧ (activeReport pub i m b).events.length = 23 := ⟨rfl, rfl⟩
+
+theorem close_cost (pub : Fin 11 → Word w) (m : Memory w) :
+ (closeReport pub m).probes = 1 ∧ (closeReport pub m).events.length = 14 := ⟨rfl, rfl⟩
+
+theorem active_image (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) (b : Bool) :
+ after m (activeReport pub i m b).events = writeMemory m (address pub m i) (encodeBit w b) := rfl
+
+theorem close_image (pub : Fin 11 → Word w) (m : Memory w) :
+ after m (closeReport pub m).events = m := rfl
+
+
+private def tested (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) : Config w 28 5 :=
+ ⟨12, i, ![i, header pub, 1, total pub m, 0], fun _ => 0⟩
+
+private theorem enter (pub : Fin 11 → Word w) (i : Word w) (m : Memory w)
+ (bs : List Bool) (fuel : ℕ) :
+ let M := table.instantiate w pub
+ let pc : Fin 28 := if i < total pub m then 13 else 25
+ execute M.program (fuel + 13) (M.program.start i) m bs =
+ (execute M.program fuel {tested pub i m with pc := pc} m bs).map
+ (fun r => ⟨testEvents pub m ++ r.events, r.result⟩) := by
+ let M := table.instantiate w pub
+ let span := BinaryOp.shiftLeft.eval 1 (pub 7)
+ let a := M.program.start i
+ let b := a.put 1 1 (pub 7)
+ let c := b.put 2 2 1
+ let d := c.put 3 1 span
+ let e := d.put 4 1 (span * span)
+ let f := e.put 5 3 (pub 2)
+ let g := f.put 6 1 (pub 2 + span * span)
+ let h := g.put 7 3 32
+ let j := h.put 8 1 (header pub)
+ let k := j.put 9 0 i
+ let l := k.put 10 3 12
+ let t := l.put 11 3 (header pub + 12)
+ let out : Config w 28 5 := {tested pub i m with pc := if i < total pub m then 13 else 25}
+ have s0 : M.program.step a = .localStep b := rfl
+ have s1 : M.program.step b = .localStep c := rfl
+ have s2 : M.program.step c = .localStep d := rfl
+ have s3 : M.program.step d = .localStep e := rfl
+ have s4 : M.program.step e = .localStep f := rfl
+ have s5 : M.program.step f = .localStep g := rfl
+ have s6 : M.program.step g = .localStep h := rfl
+ have s7 : M.program.step h = .localStep j := rfl
+ have s8 : M.program.step j = .localStep k := rfl
+ have s9 : M.program.step k = .localStep l := rfl
+ have s10 : M.program.step l = .localStep t := rfl
+ have s11 : M.program.step t = .read (header pub + 12) (t.put 12 3) := rfl
+ have regs : (t.put 12 3 (total pub m)).reg = (tested pub i m).reg := by
+ funext idx
+ fin_cases idx <;> rfl
+ have s12 : M.program.step (t.put 12 3 (m (header pub + 12).val)) = .localStep out := by
+ change CallAction.localStep
+ (⟨out.pc, i, (t.put 12 3 (total pub m)).reg, fun _ => 0⟩ : Config w 28 5) = _
+ rw [regs]
+ rfl
+ change execute M.program (fuel + 13) a m bs = (execute M.program fuel out m bs).map _
+ simp only [execute, s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]
+ cases execute M.program fuel out m bs <;> rfl
+
+theorem active (pub : Fin 11 → Word w) (i : Word w) (m : Memory w)
+ (hi : i < total pub m) (bs : List Bool) (extra : ℕ) :
+ let M := table.instantiate w pub
+ execute M.program (extra + 24) (M.program.start i) m bs =
+ match bs with
+ | [b] => some (activeReport pub i m b)
+ | _ => none := by
+ let M := table.instantiate w pub
+ let a : Config w 28 5 := {tested pub i m with pc := 13}
+ let b := a.put 14 4 13
+ let c := b.put 15 4 (header pub + 13)
+ let d := c.put 16 4 (base pub m)
+ let e := d.put 17 4 (base pub m + total pub m)
+ let f := e.put 18 4 (base pub m + total pub m - i)
+ let g := f.put 19 4 (address pub m i)
+ let choice (v : Bool) : Config w 28 5 := {g with pc := if v then 20 else 21}
+ let emit (v : Bool) := g.put 22 3 (encodeBit w v)
+ let advance (v : Bool) : Config w 28 5 := {emit v with pc := 23}
+ let finish (v : Bool) := (advance v).put 24 0 (i + 1)
+ have s13 : M.program.step a = .localStep b := rfl
+ have s14 : M.program.step b = .localStep c := rfl
+ have s15 : M.program.step c = .read (header pub + 13) (c.put 16 4) := rfl
+ have s16 : M.program.step (c.put 16 4 (m (header pub + 13).val)) = .localStep e := rfl
+ have s17 : M.program.step e = .localStep f := rfl
+ have s18 : M.program.step f = .localStep g := rfl
+ have s19 : M.program.step g = .branch choice := rfl
+ have s20 (v : Bool) : M.program.step (choice v) = .localStep (emit v) := by cases v <;> rfl
+ have s22 (v : Bool) : M.program.step (emit v) =
+ .write (address pub m i) (encodeBit w v) (advance v) := rfl
+ have s23 (v : Bool) : M.program.step (advance v) = .localStep (finish v) := rfl
+ have s24 (v : Bool) : M.program.step (finish v) = .finish (some (i + 1)) := rfl
+ dsimp only
+ rw [show extra + 24 = (extra + 11) + 13 by omega, enter pub i m bs, ite_eq_left hi]
+ change (execute M.program (extra + 11) a m bs).map _ = _
+ cases bs with
+ | nil => simp only [execute, s13, s14, s15, s16, s17, s18, s19, Option.map_none]
+ | cons v tail =>
+ cases tail <;> simp only [execute, s13, s14, s15, s16, s17, s18, s19, s20, s22, s23, s24] <;> rfl
+
+theorem close (pub : Fin 11 → Word w) (i : Word w) (m : Memory w)
+ (hi : i = total pub m) (bs : List Bool) (extra : ℕ) :
+ let M := table.instantiate w pub
+ execute M.program (extra + 24) (M.program.start i) m bs =
+ if bs = [] then some (closeReport pub m) else none := by
+ let M := table.instantiate w pub
+ let a : Config w 28 5 := {tested pub i m with pc := 25}
+ let b : Config w 28 5 := {a with pc := if i = total pub m then 26 else 27}
+ have s25 : M.program.step a = .localStep b := rfl
+ have s26 : M.program.step b = .finish none := by
+ dsimp only [b]
+ rw [ite_eq_left hi]
+ rfl
+ dsimp only
+ rw [show extra + 24 = (extra + 11) + 13 by omega, enter pub i m bs, ite_eq_right (not_lt.mpr hi.ge)]
+ change (execute M.program (extra + 11) a m bs).map _ = _
+ cases bs <;> simp only [execute, s25, s26] <;> rfl
+
+theorem overrun (pub : Fin 11 → Word w) (i : Word w) (m : Memory w)
+ (hi : total pub m < i) (bs : List Bool) (extra : ℕ) :
+ let M := table.instantiate w pub
+ execute M.program (extra + 24) (M.program.start i) m bs = none := by
+ let M := table.instantiate w pub
+ let a : Config w 28 5 := {tested pub i m with pc := 25}
+ let b : Config w 28 5 := {a with pc := if i = total pub m then 26 else 27}
+ have s25 : M.program.step a = .localStep b := rfl
+ have s27 : M.program.step b = .reject := by
+ dsimp only [b]
+ rw [ite_eq_right hi.ne']
+ rfl
+ dsimp only
+ rw [show extra + 24 = (extra + 11) + 13 by omega, enter pub i m bs, ite_eq_right hi.not_gt]
+ change (execute M.program (extra + 11) a m bs).map _ = _
+ simp only [execute, s25, s27, Option.map_none]
+
+end PairSimulation.FinalBits.Worker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationFinalBits.lean b/lean/OAI/Computability/VPVNP/PairSimulationFinalBits.lean
new file mode 100644
index 0000000000..fe8f93335c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationFinalBits.lean
@@ -0,0 +1,498 @@
+import OAI.Computability.VPVNP.NetworkKernel
+import OAI.Computability.VPVNP.PrimedInputRAMChoices
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+import OAI.Computability.VPVNP.RAMChain
+import OAI.Computability.VPVNP.RAMRecords
+import OAI.Computability.VPVNP.RAMUniform
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Data.ZMod.Defs
+
+/-!
+# Native scan of the final arc bits
+
+After the compression descriptors have supplied the total width, the burst
+starts at the exclusive upper address of the final bit array. Each data call
+decrements this cursor, makes one binary choice, writes its value at the new
+cursor and returns that cursor. The lower address is fixed public data, so
+the same instruction table works for every selection of compression terms.
+The reads at the two incident positions use the same prefix-sum address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.FinalBits
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+/-- The two registers hold the cursor and a temporary word. The data calls
+return to the dispatcher. At the lower address the fragment jumps to its
+continuation without making a choice or accessing external memory. -/
+def instruction {p r k : ℕ} (w : ℕ) (pc : Fin 10 → Fin p)
+ (reg : Fin 2 ↪ Fin r) (base : Fin k) (done : Fin p) : Fin 10 → Instr w p r k :=
+ ![.stateWord (reg 0) (pc 1), .publicWord (reg 1) base (pc 2),
+ .jumpEq (reg 0) (reg 1) done (pc 3), .constant (reg 1) 1 (pc 4),
+ .binary .sub (reg 0) (reg 0) (reg 1) (pc 5), .choose (pc 6) (pc 7),
+ .constant (reg 1) 1 (pc 8), .constant (reg 1) 0 (pc 8),
+ .writeExternal (reg 0) (reg 1) (pc 9), .returnState (reg 0)]
+
+/-- The ten scan instructions occupy their designated labels in the host machine. -/
+def Linked {w p r k : ℕ} (M : Machine w p r k) (pc : Fin 10 → Fin p)
+ (reg : Fin 2 ↪ Fin r) (base : Fin k) (done : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction w pc reg base done i
+
+variable {w p r k : ℕ} {M : Machine w p r k} {pc : Fin 10 → Fin p}
+ {reg : Fin 2 ↪ Fin r} {base : Fin k} {done : Fin p}
+
+/-- Report of one bit call. -/
+def bitReport (a : Word w) (b : Bool) : Report w :=
+ ⟨[.tick, .tick, .tick, .tick, .tick, .choice b, .tick, .write a (encodeBit w b)], some a⟩
+
+@[simp] theorem bitReport_probes (a : Word w) (b : Bool) : (bitReport a b).probes = 1 := rfl
+
+@[simp] theorem bitReport_result (a : Word w) (b : Bool) : (bitReport a b).result = some a := rfl
+
+@[simp] theorem bitReport_memory (a : Word w) (b : Bool) (m : Memory w) :
+ after m (bitReport a b).events = writeMemory m a (encodeBit w b) := rfl
+
+private theorem step_at (hl : Linked M pc reg base done) (i : Fin 10) (c : Config w p r)
+ (hc : c.pc = pc i) : M.program.step c = (instruction w pc reg base done i).run M.publicData
+ c := by
+ simp [Machine.program, hc, hl i]
+
+private def tested (c : Config w p r) (pc : Fin 10 → Fin p)
+ (reg : Fin 2 ↪ Fin r) (low : Word w) (target : Fin p) : Config w p r :=
+ (c.put (pc 1) (reg 0) c.persistent).put target (reg 1) low
+
+private theorem execute_test (hl : Linked M pc reg base done) (c : Config w p r)
+ (hc : c.pc = pc 0) (m : Memory w) (bs : List Bool) (fuel : ℕ) :
+ let target := if c.persistent = M.publicData base then done else pc 3
+ execute M.program (fuel + 3) c m bs =
+ (execute M.program fuel (tested c pc reg (M.publicData base) target) m bs).map
+ (fun rep ↦ ⟨[.tick,.tick,.tick] ++ rep.events, rep.result⟩) := by
+ let a := c.put (pc 1) (reg 0) c.persistent
+ let d := a.put (pc 2) (reg 1) (M.publicData base)
+ have s0 : M.program.step c = .localStep a := step_at hl 0 c hc
+ have s1 : M.program.step a = .localStep d := step_at hl 1 _ rfl
+ have s2 : M.program.step d = .localStep
+ (tested c pc reg (M.publicData base) (if c.persistent = M.publicData base then done else pc
+ 3)) := by
+ rw [step_at hl 2 d rfl]
+ change CallAction.localStep {d with
+ pc := if d.reg (reg 0) = d.reg (reg 1) then done else pc 3} = _
+ simp [d, a, Config.put, tested]
+ dsimp only
+ simp only [execute, s0, s1, s2]
+ simp [Option.map_map, Function.comp_def, Report.prepend]
+
+/-- Exact native execution of a data call on *any* supplied branch stream.
+Missing or unused bits reject even when the machine has excess fuel. -/
+theorem execute_bit (hl : Linked M pc reg base done) (c : Config w p r) (hc : c.pc = pc 0)
+ (hs : c.persistent ≠ M.publicData base) (m : Memory w) (bs : List Bool) (extra : ℕ) :
+ execute M.program (extra + 9) c m bs =
+ match bs with
+ | [b] => some (bitReport (c.persistent - 1) b)
+ | _ => none := by
+ rw [show extra + 9 = (extra + 6) + 3 by omega, execute_test hl c hc]
+ simp only [hs, ↓reduceIte]
+ let ct := tested c pc reg (M.publicData base) (pc 3)
+ let cd := ct.put (pc 4) (reg 1) 1
+ let cb := cd.put (pc 5) (reg 0) (c.persistent - 1)
+ let choose (b : Bool) := {cb with pc := if b then pc 6 else pc 7}
+ let cw (b : Bool) := cb.put (pc 8) (reg 1) (encodeBit w b)
+ let cr (b : Bool) := {cw b with pc := pc 9}
+ have s3 : M.program.step ct = .localStep cd := step_at hl 3 _ rfl
+ have s4 : M.program.step cd = .localStep cb := by
+ rw [step_at hl 4 cd rfl]
+ change CallAction.localStep (cd.put (pc 5) (reg 0) (cd.reg (reg 0) - cd.reg (reg 1))) = _
+ simp [cb, cd, ct, tested, Config.put]
+ have s5 : M.program.step cb = .branch choose := step_at hl 5 _ rfl
+ have s67 (b : Bool) : M.program.step (choose b) = .localStep (cw b) := by
+ cases b with
+ | false => exact step_at hl 7 _ rfl
+ | true => exact step_at hl 6 _ rfl
+ have s8 (b : Bool) : M.program.step (cw b) = .write (c.persistent-1) (encodeBit w b) (cr b) := by
+ rw [step_at hl 8 (cw b) rfl]
+ change CallAction.write ((cw b).reg (reg 0)) ((cw b).reg (reg 1)) (cr b) = _
+ simp [cw, cb, Config.put]
+ have s9 (b : Bool) : M.program.step (cr b) = .finish (some (c.persistent - 1)) := by
+ rw [step_at hl 9 (cr b) rfl]
+ change CallAction.finish (some ((cr b).reg (reg 0))) = _
+ simp [cr, cw, cb, Config.put]
+ change (execute M.program (extra + 6) ct m bs).map _ = _
+ cases bs with
+ | nil => simp only [execute, s3, s4, s5, Option.map_none]
+ | cons b tail =>
+ cases tail <;> simp only [execute, s3, s4, s5, s67, s8, s9] <;> rfl
+
+/-- The lower-bound test composes with arbitrary native continuation code. -/
+theorem execute_done (hl : Linked M pc reg base done) (c : Config w p r) (hc : c.pc = pc 0)
+ (hs : c.persistent = M.publicData base) (m : Memory w) (bs : List Bool) (fuel : ℕ) :
+ let out := (c.put (pc 1) (reg 0) c.persistent).put done (reg 1) (M.publicData base)
+ execute M.program (fuel + 3) c m bs = (execute M.program fuel out m bs).map
+ (fun rep ↦ ⟨[.tick,.tick,.tick] ++ rep.events, rep.result⟩) := by
+ simp [execute_test hl c hc, hs, tested]
+
+/-- Standalone table with an accepting continuation. The ten labels of the
+scan are embedded unchanged in this eleven-instruction template. -/
+def template : Template 11 2 1 where
+ literalWidth := 1
+ entry := 0
+ code j := if h : j.val < 10 then
+ instruction 1 Fin.castSucc (Function.Embedding.refl _) 0 10 ⟨j.val,h⟩
+ else .accept
+
+theorem template_linked (pub : Fin 1 → Word w) :
+ Linked (template.instantiate w pub) Fin.castSucc (Function.Embedding.refl _) 0 10 := by
+ intro i
+ fin_cases i <;> rfl
+
+/-- Ascending physical address; the scan visits the addresses in reverse. -/
+def cursor (w low n : ℕ) : Word w := ((low + n : ℕ) : Word w)
+
+@[simp] private theorem cursor_pred (low n : ℕ) :
+ cursor w low (n+1) - 1 = cursor w low n := by
+ simp [cursor, ← Nat.add_assoc]
+
+private theorem cursor_ne {low n : ℕ} (fit : low + (n + 1) < 2 ^ w) :
+ cursor w low (n+1) ≠ cursor w low 0 := by
+ intro he
+ have hv := congrArg Fin.val he
+ simp only [cursor, Fin.val_natCast, Nat.add_zero, Nat.mod_eq_of_lt fit,
+ Nat.mod_eq_of_lt (show low < 2^w by omega)] at hv
+ omega
+
+/-- A successful branch stream for the whole scan, before the continuation. -/
+def calls {n : ℕ} (f : Fin n → Bool) : List (List Bool) :=
+ (List.ofFn fun i ↦ [f i]).reverse
+
+/-- Exact chronological reports for the choices written in the scan. -/
+def reports {n : ℕ} (w low : ℕ) (f : Fin n → Bool) : List (Report w) :=
+ (List.ofFn fun i ↦ bitReport (cursor w low i) (f i)).reverse
+
+@[simp] theorem calls_length {n : ℕ} (f : Fin n → Bool) : (calls f).length = n := by simp [calls]
+
+theorem calls_succ {n : ℕ} (f : Fin (n + 1) → Bool) :
+ calls f = [f (Fin.last n)] :: calls (Fin.init f) := by
+ rw [calls, List.ofFn_succ', List.concat_eq_append, List.reverse_concat']
+ rfl
+
+theorem reports_succ {n : ℕ} (low : ℕ) (f : Fin (n + 1) → Bool) :
+ reports w low f = bitReport (cursor w low n) (f (Fin.last n)) :: reports w low
+ (Fin.init f) := by
+ rw [reports, List.ofFn_succ', List.concat_eq_append, List.reverse_concat']
+ rfl
+
+private theorem execute_succ (hl : Linked M pc reg base done) (he : M.entry = pc 0)
+ (low n : ℕ) (fit : low + (n + 1) < 2 ^ w) (hpub : M.publicData base = cursor w low 0)
+ (m : Memory w) (bs : List Bool) (extra : ℕ) :
+ execute M.program (extra + 9) (M.program.start (cursor w low (n+1))) m bs =
+ match bs with
+ | [b] => some (bitReport (cursor w low n) b)
+ | _ => none := by
+ have hs : cursor w low (n+1) ≠ M.publicData base := hpub ▸ cursor_ne fit
+ rw [execute_bit hl _ he hs]
+ change (match bs with
+ | [b] => some (bitReport (cursor w low (n+1) - 1) b)
+ | _ => none) = _
+ rw [cursor_pred]
+
+/-- The native scan can be followed by arbitrary further calls. The memory
+passed to those calls is the memory obtained by replaying the actual writes. -/
+theorem run_scan (hl : Linked M pc reg base done) (he : M.entry = pc 0) (low n : ℕ)
+ (fit : low + n < 2 ^ w) (hpub : M.publicData base = cursor w low 0)
+ (f : Fin n → Bool) (m : Memory w) (tail : List (List Bool)) (extra : ℕ) :
+ runSegment M.program (extra+9) (some (cursor w low n)) m (calls f ++ tail) =
+ (runSegment M.program (extra+9) (some (cursor w low 0))
+ (after m (eventLog (reports w low f))) tail).map (reports w low f ++ ·) := by
+ induction n generalizing m with
+ | zero =>
+ simp [calls, reports, eventLog, after]
+ | succ n ih =>
+ rw [calls_succ, reports_succ, List.cons_append, runSegment,
+ execute_succ hl he low n fit hpub]
+ simp only [bitReport_result, bitReport_memory]
+ rw [ih (by omega) (Fin.init f)]
+ simp [eventLog, after, Option.map_map, Function.comp_def]
+ rfl
+
+/-- For any scan of the prescribed length, success forces one singleton
+choice per physical address. This excludes all extra and missing choices. -/
+theorem scan_complete (hl : Linked M pc reg base done) (he : M.entry = pc 0) (low n : ℕ)
+ (fit : low + n < 2 ^ w) (hpub : M.publicData base = cursor w low 0) (m : Memory w)
+ (bs : List (List Bool)) (rs : List (Report w)) (extra : ℕ)
+ (hlen : bs.length = n)
+ (hr : runSegment M.program (extra + 9) (some (cursor w low n)) m bs = some rs) :
+ ∃ f : Fin n → Bool, bs = calls f ∧ rs = reports w low f := by
+ induction n generalizing m bs rs with
+ | zero =>
+ have hb : bs = [] := List.length_eq_zero_iff.mp hlen
+ subst bs
+ obtain rfl : rs = [] := (Option.some.inj hr).symm
+ exact ⟨Fin.elim0, rfl, rfl⟩
+ | succ n ih =>
+ cases bs with
+ | nil => simp at hlen
+ | cons head rest =>
+ have hlen' : rest.length = n := by simpa using hlen
+ rw [runSegment, execute_succ hl he low n fit hpub] at hr
+ cases head with
+ | nil => contradiction
+ | cons b more =>
+ cases more with
+ | cons => contradiction
+ | nil =>
+ obtain ⟨ts, ht, rfl⟩ := Option.map_eq_some_iff.mp hr
+ obtain ⟨g, rfl, rfl⟩ := ih (by omega) _ _ ts hlen' ht
+ refine ⟨Fin.snoc g b, ?_, ?_⟩
+ · simp [calls_succ]
+ · simp [reports_succ]
+
+theorem calls_injective {n : ℕ} : Function.Injective (@calls n) := by
+ intro f g he
+ have h := congrArg List.reverse he
+ simp only [calls, List.reverse_reverse, List.ofFn_inj] at h
+ funext i
+ exact (List.cons.inj (congrFun h i)).1
+
+/-- Histories reaching the end of the data phase in exactly the scheduled
+number of calls. The subsequent vertex visits supply the continuation. -/
+abbrev ScanPaths {C : Type*} (P : Program w C) (fuel low n : ℕ) (m : Memory w) :=
+ {bs : List (List Bool) // bs.length = n ∧
+ (runSegment P fuel (some (cursor w low n)) m bs).isSome}
+
+/-- Bijective enumeration by native branch paths, including the empty scan. -/
+noncomputable def scanEquiv (hl : Linked M pc reg base done) (he : M.entry = pc 0) (low n : ℕ)
+ (fit : low + n < 2 ^ w) (hpub : M.publicData base = cursor w low 0) (m : Memory w)
+ (extra : ℕ) :
+ (Fin n → Bool) ≃ ScanPaths M.program (extra+9) low n m := by
+ let path (f : Fin n → Bool) : ScanPaths M.program (extra+9) low n m := ⟨calls f,
+ calls_length f, by
+ have h := run_scan hl he low n fit hpub f m [] extra
+ simpa [runSegment] using congrArg Option.isSome h⟩
+ apply Equiv.ofBijective path
+ constructor
+ · intro f g eq
+ exact calls_injective (congrArg Subtype.val eq)
+ · rintro ⟨bs,hlen,hs⟩
+ obtain ⟨rs,hr⟩ := Option.isSome_iff_exists.mp hs
+ obtain ⟨f,hf,_⟩ := scan_complete hl he low n fit hpub m bs rs extra hlen hr
+ exact ⟨f, Subtype.ext hf.symm⟩
+
+private def stopReport (w : ℕ) : Report w := ⟨[.tick,.tick,.tick], none⟩
+
+private theorem execute_stop (hl : Linked M pc reg base done) (he : M.entry = pc 0)
+ (ha : M.code done = .accept) (low : ℕ) (hpub : M.publicData base = cursor w low 0)
+ (m : Memory w) (bs : List Bool) (extra : ℕ) :
+ execute M.program (extra+9) (M.program.start (cursor w low 0)) m bs =
+ if bs = [] then some (stopReport w) else none := by
+ rw [show extra+9 = (extra+6)+3 by omega, execute_done hl _ he hpub.symm]
+ have hs (c : Config w p r) (hc : c.pc = done) : M.program.step c = .finish none := by
+ simp [Machine.program, hc, ha, Instr.run]
+ have hfinish (c : Config w p r) (hc : c.pc = done) (fuel : ℕ) :
+ execute M.program (fuel+1) c m bs = if bs = [] then some ⟨[],none⟩ else none := by
+ simp only [execute, hs c hc]
+ rw [hfinish _ rfl]
+ cases bs <;> rfl
+
+/-- With an accepting exit, every complete native history consists of the
+data choices followed by the deterministic halt call. Here the stream is
+unrestricted: reaching acceptance itself forces the number of data calls. -/
+theorem accepted_iff (hl : Linked M pc reg base done) (he : M.entry = pc 0)
+ (ha : M.code done = .accept) (low n : ℕ) (fit : low + n < 2 ^ w)
+ (hpub : M.publicData base = cursor w low 0) (m : Memory w) (bs : List (List Bool)) (extra : ℕ) :
+ (∃ rs, runSegment M.program (extra+9) (some (cursor w low n)) m bs = some rs ∧
+ endState (some (cursor w low n)) rs = none) ↔ ∃ f : Fin n → Bool, bs = calls f ++ [[]] := by
+ constructor
+ · rintro ⟨rs, hr, hend⟩
+ induction n generalizing m bs rs with
+ | zero =>
+ cases bs with
+ | nil => obtain rfl : rs = [] := (Option.some.inj hr).symm; contradiction
+ | cons b rest =>
+ rw [runSegment, execute_stop hl he ha low hpub] at hr
+ cases b with
+ | cons => contradiction
+ | nil =>
+ cases rest with
+ | nil => exact ⟨Fin.elim0, rfl⟩
+ | cons => contradiction
+ | succ n ih =>
+ cases bs with
+ | nil => obtain rfl : rs = [] := (Option.some.inj hr).symm; contradiction
+ | cons b rest =>
+ rw [runSegment, execute_succ hl he low n fit hpub] at hr
+ cases b with
+ | nil => contradiction
+ | cons v vs =>
+ cases vs with
+ | cons => contradiction
+ | nil =>
+ obtain ⟨ts,ht,rfl⟩ := Option.map_eq_some_iff.mp hr
+ obtain ⟨g,rfl⟩ := ih (by omega) _ _ ts ht hend
+ exact ⟨Fin.snoc g v, by simp [calls_succ]⟩
+ · rintro ⟨f,rfl⟩
+ refine ⟨reports w low f ++ [stopReport w], ?_, ?_⟩
+ · rw [run_scan hl he low n fit hpub, runSegment, execute_stop hl he ha low hpub]
+ rfl
+ · rw [endState_append]
+ rfl
+
+/-- Exactly one call and one external write per physical bit. -/
+theorem scan_cost (low n : ℕ) (f : Fin n → Bool) :
+ (reports w low f).length = n ∧ RAMBuckets.cost Report.probes (reports w low f) = 2*n := by
+ constructor
+ · simp [reports]
+ · induction n with
+ | zero => rfl
+ | succ n ih =>
+ rw [reports_succ, RAMBuckets.cost, bitReport_probes, ih]
+ omega
+
+private theorem replay_store {n : ℕ} (low : ℕ) (fit : low + n < 2 ^ w)
+ (f : Fin n → Bool) (m : Memory w) (cells : List (Fin n)) :
+ after m (eventLog (cells.map fun (i : Fin n) ↦ bitReport (cursor w low i) (f i))) =
+ store (scratchAddress low fit.le) (encodeBit w ∘ f) cells m := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih =>
+ have he : cursor w low i = scratchAddress low fit.le i := by
+ apply Fin.ext
+ exact Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt low).trans fit)
+ simp only [List.map_cons, eventLog, List.flatMap_cons, store]
+ rw [show ∀ es tail, after m (es ++ tail) = after (after m es) tail by simp [after]]
+ rw [bitReport_memory]
+ exact (ih _).trans (by rw [he]; rfl)
+
+private theorem after_reports {n : ℕ} (low : ℕ) (fit : low + n < 2 ^ w)
+ (f : Fin n → Bool) (m : Memory w) :
+ after m (eventLog (reports w low f)) =
+ store (scratchAddress low fit.le) (encodeBit w ∘ f) (List.finRange n).reverse m := by
+ rw [reports, List.ofFn_eq_map, ← List.map_reverse]
+ exact replay_store low fit f m _
+
+/-- The physical cell at every address receives the unique bit chosen there. -/
+theorem readback {n : ℕ} (low : ℕ) (fit : low + n < 2 ^ w)
+ (f : Fin n → Bool) (m : Memory w) (i : Fin n) :
+ after m (eventLog (reports w low f)) (low+i) = encodeBit w (f i) := by
+ rw [after_reports low fit]
+ exact store_at _ _ _ _ (by simp : i ∈ (List.finRange n).reverse)
+
+/-- All cells outside the scanned interval retain their previous contents. -/
+theorem outside {n : ℕ} (low : ℕ) (fit : low + n < 2 ^ w) (f : Fin n → Bool)
+ (m : Memory w) (a : ℕ) (ha : a < low ∨ low + n ≤ a) :
+ after m (eventLog (reports w low f)) a = m a := by
+ rw [after_reports low fit]
+ apply store_outside
+ intro i _
+ have := i.isLt
+ change a ≠ low+i.val
+ omega
+
+variable {E : ℕ} (width : Fin E → ℕ)
+
+/-- Edge number and offset address a single contiguous bit array. -/
+def index (e : Fin E) (j : Fin (width e)) : Fin (∑ e, width e) :=
+ finSigmaFinEquiv ⟨e,j⟩
+
+theorem index_val (e : Fin E) (j : Fin (width e)) :
+ (index width e j).val = (∑ i : Fin e, width (Fin.castLE e.isLt.le i)) + j :=
+ finSigmaFinEquiv_apply _
+
+/-- Splitting the scan into its arc words, including the unique empty word
+for every zero-width arc. -/
+def arcWords : (Fin (∑ e, width e) → Bool) ≃ ((e : Fin E) → Fin (width e) → Bool) where
+ toFun f e j := f (index width e j)
+ invFun z i :=
+ let p := (finSigmaFinEquiv (n := width)).symm i
+ z p.1 p.2
+ left_inv f := by funext i; simp [index]
+ right_inv z := by
+ funext e j
+ exact congrArg (fun p : (e : Fin E) × Fin (width e) ↦ z p.1 p.2)
+ ((finSigmaFinEquiv (n := width)).symm_apply_apply ⟨e,j⟩)
+
+variable (N : NetworkKernel.Network) (number : N.Edge ≃ Fin E)
+ (encode : ∀ e, N.Payload e ≃ (Fin (width (number e)) → Bool))
+
+/-- A scan assignment is precisely a payload assignment to the edges of the
+network in the contraction formula. Parallel arcs keep distinct numbers. -/
+def payloads : (Fin (∑ e, width e) → Bool) ≃ ((e : N.Edge) → N.Payload e) :=
+ (arcWords width).trans ((Equiv.piCongrLeft' (fun e ↦ Fin (width e) → Bool) number.symm).trans
+ (Equiv.piCongrRight fun e ↦ (encode e).symm))
+
+@[simp] theorem payloads_bit (f : Fin (∑ e, width e) → Bool) (e : N.Edge) (j : Fin (width
+ (number e))) :
+ encode e (payloads width N number encode f e) j = f (index width (number e) j) := by
+ change encode e ((encode e).symm _) j = _
+ rw [Equiv.apply_symm_apply]
+ rfl
+
+/-- Both incident payloads in equation (7.1) read the stored bit, even for
+loops or multiple edges with identical endpoints. -/
+theorem endpoint_bits (low : ℕ) (fit : low + ∑ e, width e < 2 ^ w)
+ (f : Fin (∑ e, width e) → Bool) (m : Memory w) (e : N.Edge) (j : Fin (width (number e))) :
+ let halves := WireTensor.edgeAssignment N.src N.dst (payloads width N number encode f)
+ let cell := after m (eventLog (reports w low f)) (low + (index width (number e) j).val)
+ cell = encodeBit w (encode e ((halves (N.src e)).1 e rfl) j) ∧
+ cell = encodeBit w (encode e ((halves (N.dst e)).2 e rfl) j) := by
+ simp [WireTensor.edgeAssignment, readback low fit]
+
+/-- The two reads may belong to different vertex calls. From either read
+label the interpreter passes precisely the incident value to its private
+destination register, preserves external memory and consumes no choice. -/
+theorem execute_endpoint_read (low : ℕ) (fit : low + ∑ e, width e < 2 ^ w)
+ (f : Fin (∑ e, width e) → Bool) (m : Memory w) (e : N.Edge) (j : Fin (width (number e)))
+ (c : Config w p r) (dst addr : Fin r) (next : Fin p)
+ (hread : M.code c.pc = .readExternal dst addr next)
+ (haddr : (c.reg addr).val = low + (index width (number e) j).val)
+ (bits : List Bool) (fuel : ℕ) :
+ let mem := after m (eventLog (reports w low f))
+ let val := encodeBit w (encode e (payloads width N number encode f e) j)
+ execute M.program (fuel+1) c mem bits =
+ (execute M.program fuel (c.put next dst val) mem bits).map (Report.prepend (.read
+ (c.reg addr) val)) := by
+ dsimp only
+ simp only [execute, M.step_read c hread, haddr, readback low fit, payloads_bit]
+
+/-- For the actual fixed template, the independent summation indices of the
+network biject onto the native scan histories. -/
+noncomputable def networkScanEquiv (low : ℕ) (fit : low + ∑ e, width e < 2 ^ w)
+ (m : Memory w) (extra : ℕ) :
+ ((e : N.Edge) → N.Payload e) ≃
+ ScanPaths (template.instantiate w (fun _ ↦ cursor w low 0)).program
+ (extra+9) low (∑ e, width e) m :=
+ (payloads width N number encode).symm.trans
+ (scanEquiv (template_linked _) rfl low _ fit rfl m extra)
+
+/-- Complete accepting paths of the standalone table enumerate each network
+summand exactly once, with no restriction on the proposed history length. -/
+noncomputable def acceptedNetworkEquiv (low : ℕ) (fit : low + ∑ e, width e < 2 ^ w)
+ (m : Memory w) (extra : ℕ) :
+ ((e : N.Edge) → N.Payload e) ≃
+ ActualPaths (template.instantiate w (fun _ ↦ cursor w low 0)).program
+ (extra+9) (cursor w low (∑ e, width e)) m (fun _ ↦ True) := by
+ apply (payloads width N number encode).symm.trans
+ let T := template.instantiate w (fun _ ↦ cursor w low 0)
+ have accepted := accepted_iff (template_linked (fun _ ↦ cursor w low 0)) rfl rfl
+ low _ fit rfl m
+ let path (f : Fin (∑ e, width e) → Bool) :
+ ActualPaths T.program (extra+9) (cursor w low (∑ e, width e)) m (fun _ ↦ True) :=
+ ⟨calls f ++ [[]], by
+ obtain ⟨rs,hr,he⟩ := (accepted _ extra).mpr ⟨f,rfl⟩
+ exact ⟨rs,hr,he,trivial⟩⟩
+ apply Equiv.ofBijective path
+ constructor
+ · intro f g h
+ exact calls_injective (List.append_cancel_right (congrArg Subtype.val h))
+ · rintro ⟨bs,rs,hr,he,_⟩
+ obtain ⟨f,hf⟩ := (accepted bs extra).mp ⟨rs,hr,he⟩
+ exact ⟨f, Subtype.ext hf.symm⟩
+
+end PairSimulation.FinalBits
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationHistogramFrame.lean b/lean/OAI/Computability/VPVNP/PairSimulationHistogramFrame.lean
new file mode 100644
index 0000000000..254489e170
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationHistogramFrame.lean
@@ -0,0 +1,34 @@
+import OAI.Computability.VPVNP.PairSimulationPrivateLabels
+
+/-!
+# Private memory outside the histogram
+
+The label loop changes one word per emitted name. The remaining addresses
+retain their exact initial contents on the same path.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.PrivateLabels
+
+open BurstRAM
+open scoped Fin.CommRing
+
+variable {w t : ℕ}
+
+theorem accumulate_outside (base : ℕ) (names : List (Fin t)) (mem : Word w → Word w)
+ (addr : Word w) (apart : ∀ i : Fin t, addr ≠ ((base + i.val : ℕ) : Word w)) :
+ accumulate base names mem addr = mem addr := by
+ induction names generalizing mem with
+ | nil => rfl
+ | cons i names ih =>
+ rw [accumulate, ih]
+ exact Function.update_of_ne (apart i) ..
+
+end PairSimulation.PrivateLabels
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationHistory.lean b/lean/OAI/Computability/VPVNP/PairSimulationHistory.lean
new file mode 100644
index 0000000000..cfbea7515b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationHistory.lean
@@ -0,0 +1,459 @@
+import OAI.Computability.VPVNP.CompressorRecordChoices
+import OAI.Computability.VPVNP.CompressionHistory
+import OAI.Computability.VPVNP.MotifEntryWitness
+import OAI.Computability.VPVNP.CursorInitialCheck
+import OAI.Computability.VPVNP.CursorStateCount
+import OAI.Computability.VPVNP.RAMGuessBudget
+
+/-!
+# Binary paths through a local compression history
+
+Section 13 reads the old half-indices of each child once, then uses the same
+arguments in the local map tests and the child's expansion. An absorbed
+supply field is owned by one site and has just one code even if several map
+arguments read it. These readers operate on a shared suffix of a binary
+stream, so the encoding of a site can be followed immediately by its siblings.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open CompressorRecords NetworkKernel
+open scoped Classical
+
+/-- An ordered descriptor list with each of its entries present once. -/
+structure Order (I : Type) where
+ /-- Number of positions in the descriptor's enumeration. -/
+ length : ℕ
+ /-- Bijection from descriptor positions to entries, used to visit each entry once in that
+ order. -/
+ entries : Fin length ≃ I
+
+/-- Read a list of dependent fields or child vertices in descriptor order. -/
+def Order.reader {I : Type} (o : Order I) {B : I → Type} (c : ∀ i, ChoiceReader (B i)) :
+ ChoiceReader (∀ i, B i) :=
+ (ChoiceReader.vector o.length _ (fun j => c (o.entries j))).reindex (Equiv.piCongrLeft B o.entries)
+
+theorem Order.reader_length {I : Type} [Fintype I] (o : Order I) {B : I → Type}
+ (c : ∀ i, ChoiceReader (B i)) (x : ∀ i, B i) :
+ ((o.reader c).encode x).length = ∑ i, ((c i).encode (x i)).length := by
+ unfold reader ChoiceReader.reindex
+ dsimp only
+ rw [ChoiceReader.vector_length]
+ apply Fintype.sum_equiv o.entries
+ intro i
+ rfl
+
+/-- Read the first factor and then the second, with no separator or tag. -/
+def pair {α β : Type} (a : ChoiceReader α) (b : ChoiceReader β) : ChoiceReader (α × β) :=
+ (a.sigma fun _ => b).reindex (Equiv.sigmaEquivProd α β)
+
+@[simp] theorem pair_length {α β : Type} (a : ChoiceReader α) (b : ChoiceReader β) (x : α × β) :
+ ((pair a b).encode x).length = (a.encode x.1).length + (b.encode x.2).length :=
+ List.length_append ..
+
+/-- The arguments of a placement kernel only mention fields owned here. -/
+def fiberEquiv {I V : Type} (p : I → V) (B : I → Type) (v : V) :
+ ((i : {i // v = p i}) → B i.val) ≃ Placed p B v where
+ toFun f i hi := f ⟨i,hi⟩
+ invFun f i := f i.val i.property
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+/-- Only fields in the stored preimage list are consumed. -/
+def fiber {I V : Type} (p : I → V) {B : I → Type} (v : V)
+ (order : Order {i // v = p i}) (c : ∀ i, ChoiceReader (B i)) : ChoiceReader (Placed p B v) :=
+ (order.reader fun i => c i.val).reindex (fiberEquiv p B v)
+
+theorem fiber_length {I V : Type} (p : I → V) {B : I → Type} (v : V)
+ [Fintype {i // v = p i}] (order : Order {i // v = p i}) (c : ∀ i, ChoiceReader (B i))
+ (a : Placed p B v) :
+ ((fiber p v order c).encode a).length = ∑ i : {i // v = p i}, ((c i.val).encode (a i.val i.prop)).length :=
+ order.reader_length (fun i => c i.val) (fun i => a i.val i.prop)
+
+/-- Outgoing and incoming indices are independent, also for a self-loop. -/
+def half (N : Network) (v : N.Site) (src : Order {e // v = N.src e})
+ (dst : Order {e // v = N.dst e}) (payload : ∀ e, ChoiceReader (N.Payload e)) :
+ ChoiceReader (N.Half v) :=
+ pair (fiber N.src v src payload) (fiber N.dst v dst payload)
+
+theorem half_length (N : Network) (v : N.Site) (src : Order {e // v = N.src e})
+ (dst : Order {e // v = N.dst e}) (payload : ∀ e, ChoiceReader (N.Payload e)) (a : N.Half v) :
+ ((half N v src dst payload).encode a).length =
+ (∑ e : {e // v = N.src e}, ((payload e.val).encode (a.1 e.val e.prop)).length) +
+ (∑ e : {e // v = N.dst e}, ((payload e.val).encode (a.2 e.val e.prop)).length) := by
+ simp only [half, pair_length, fiber_length]
+
+/-- An actual arc carries its declared number of bits, including the empty word. -/
+def bitField (w : ℕ) : ChoiceReader (Fin w → Bool) :=
+ (ChoiceReader.bounded w (2 ^ w) le_rfl).reindex (RAMSerialization.wordBits w)
+
+@[simp] theorem bitField_length (w : ℕ) (z : Fin w → Bool) : ((bitField w).encode z).length = w := by
+ simp [bitField, ChoiceReader.reindex, ChoiceReader.bounded, PrimedCounter.digits]
+
+/-- The old and final payloads in a lifted compressor state have explicit bit readers. -/
+def statePayload {a g : ℕ} (X : Compression.State a g) (e : X.network.Edge) :
+ ChoiceReader (X.network.Payload e) := bitField (X.width ((e.1.1,e.2),e.1.2))
+
+/-- Reader for an impossible local choice. Every input stream fails to decode. -/
+def reject : ChoiceReader Empty where
+ encode x := nomatch x
+ read _ := none
+ read_iff _ x := nomatch x
+
+/-- Reader for a successful deterministic local check. It returns the unique choice and
+consumes zero bits. -/
+def accept : ChoiceReader Unit := ChoiceReader.single () (fun _ => rfl)
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+
+/-- Test the map arguments before recursing. Successful entries use no bits
+and the indicated parameter occurrences retain their own multiplicities. -/
+def entryReader {u : ℕ} (κ : Label → A) (idx : Option (Fin u → Label)) :
+ ChoiceReader (MotifConversion.entryWitness κ idx).Choice :=
+ match idx with
+ | none => reject
+ | some _ => accept
+
+@[simp] theorem entryReader_length {u : ℕ} (κ : Label → A) (idx : Option (Fin u → Label))
+ (x : (MotifConversion.entryWitness κ idx).Choice) :
+ ((entryReader κ idx).encode x).length = 0 := by
+ cases idx with
+ | none => exact x.elim
+ | some => rfl
+
+/-- A layout sums over one word per absorbed wire. Each map entry sees the
+entire resulting local assignment, including a shared field at both ends. -/
+def layoutReader {N : Network} (L : Layout A N) (W : ∀ v a h z, MonomialWitness κ (L.entry v a h z))
+ (hidden : ∀ e, ChoiceReader (L.Label e)) (owners : ∀ v, Order {e // v = L.owner e})
+ (entry : ∀ v a h z, ChoiceReader (W v a h z).Choice)
+ (v : L.output.Site) (a : Placed L.place N.Half v) (z : L.output.Half v) :
+ ChoiceReader (L.kernelWitness W v a z).Choice :=
+ (fiber L.owner v (owners v) hidden).sigma (fun h => entry v a h z)
+
+/-- Per-site field and child orders from the descriptor of a selected term. -/
+structure LocalOrder {N : Network} (t : Term A N) where
+ /-- Traversal order of the input sites placed at each output site of the term. -/
+ children : ∀ v, Order (t.Preimage v)
+ /-- Order in which to read the outgoing half-wire payloads at each input site. -/
+ outgoing : ∀ u, Order {e // u = N.src e}
+ /-- Order in which to read the incoming half-wire payloads at each input site, after its
+ outgoing payloads. -/
+ incoming : ∀ u, Order {e // u = N.dst e}
+
+/-- Read the old half-bits, the local kernel choices, and then each child.
+Kernel checks see the same arguments passed to the child readers. -/
+def pushReader {N : Network} (t : Term A N) (o : LocalOrder t)
+ (payload : ∀ e, ChoiceReader (N.Payload e))
+ (F : Factors A N) (W : ∀ u b, MonomialWitness κ (F u b))
+ (child : ∀ u b, ChoiceReader (W u b).Choice)
+ (K : ∀ v a z, MonomialWitness κ (t.kernel v a z))
+ (kernel : ∀ v a z, ChoiceReader (K v a z).Choice)
+ (v : t.output.Site) (z : t.output.Half v) :
+ ChoiceReader (t.pushWitness F W K v z).Choice :=
+ ((fiber t.place v (o.children v) (fun u => half N u (o.outgoing u) (o.incoming u) payload)).sigma
+ (fun a => (pair (kernel v a z)
+ ((o.children v).reader fun u => child u.val (a u.val u.prop))).reindex (Equiv.prodComm _ _))).reindex
+ (t.pushChoice F W K v z).symm
+
+theorem pushReader_length {N : Network} (t : Term A N) (o : LocalOrder t)
+ (payload : ∀ e, ChoiceReader (N.Payload e))
+ (F : Factors A N) (W : ∀ u b, MonomialWitness κ (F u b))
+ (child : ∀ u b, ChoiceReader (W u b).Choice)
+ (K : ∀ v a z, MonomialWitness κ (t.kernel v a z))
+ (kernel : ∀ v a z, ChoiceReader (K v a z).Choice) (v : t.output.Site) (z : t.output.Half v)
+ (p : (t.pushWitness F W K v z).Choice) :
+ let x := t.pushChoice F W K v z p
+ ((pushReader t o payload F W child K kernel v z).encode p).length =
+ (∑ u : t.Preimage v, ((half N u.val (o.outgoing u.val) (o.incoming u.val) payload).encode
+ (x.1 u.val u.prop)).length) + (((kernel v x.1 z).encode x.2.2).length +
+ ∑ u : t.Preimage v, ((child u.val (x.1 u.val u.prop)).encode (x.2.1 u)).length) := by
+ change List.length ((_ : List Bool) ++ (_ ++ _)) = _
+ simp only [List.length_append]
+ let x := t.pushChoice F W K v z p
+ exact congrArg₂ (· + ·) (fiber_length t.place v (o.children v)
+ (fun u => half N u (o.outgoing u) (o.incoming u) payload) x.1) (congrArg (_ + ·)
+ ((o.children v).reader_length (fun u => child u.val (x.1 u.val u.prop)) x.2.1))
+
+/-- At the terminal level, the same arc assignment is passed to every site.
+At a branch, the descriptor phase supplies the choice and the local field
+and vertex orders of that choice. -/
+def Readers {N : Network} (H : History A N) : H.KernelWitnesses κ → Type :=
+ match H with
+ | .stop => fun _ => Order N.Edge × Order N.Site × (∀ e, ChoiceReader (N.Payload e))
+ | .branch s tail => fun K =>
+ ChoiceReader s.Choice × ((i : s.Choice) → LocalOrder (s.term i)) ×
+ (∀ e, ChoiceReader (N.Payload e)) ×
+ (∀ i v a z, ChoiceReader (K.1 i v a z).Choice) ×
+ ((i : s.Choice) → Readers (tail i) (K.2 i))
+
+/-- One binary parser for the semantic occurrence type of (12.2).
+All branch selectors precede the shared arc assignment. The final-site
+readers descend through the stored preimage lists, including on branches
+whose term selections change the network topology. -/
+noncomputable def historyReader {N : Network} (H : History A N) (K : H.KernelWitnesses κ)
+ (desc : Readers H K) (F : Factors A N) (W : ∀ u b, MonomialWitness κ (F u b))
+ (leaf : ∀ u b, ChoiceReader (W u b).Choice) : ChoiceReader (H.expandedWitness K F W).Choice := by
+ induction H with
+ | @stop N =>
+ exact ((desc.1.reader desc.2.2).sigma fun z => desc.2.1.reader fun v =>
+ leaf v (WireTensor.edgeAssignment N.src N.dst z v)).reindex (History.stopChoice K F W).symm
+ | @branch N s tail ih =>
+ exact (desc.1.sigma fun i => ih i (K.2 i) (desc.2.2.2.2 i) _ _
+ (pushReader (s.term i) (desc.2.1 i) desc.2.2.1 F W leaf (K.1 i) (desc.2.2.2.1 i))).reindex
+ (History.branchChoice s tail K F W).symm
+
+/-- Every successful complete binary stream gives precisely one occurrence,
+even if several streams accumulate the same exponent vector. -/
+def successful {x : A} (W : MonomialWitness κ x) (C : ChoiceReader W.Choice) :=
+ {bs : List Bool // ∃ p, C.read bs = some (p, [])}
+
+noncomputable instance {x : A} (W : MonomialWitness κ x) (C : ChoiceReader W.Choice) :
+ Fintype (successful W C) := Fintype.ofEquiv _ C.completeEquiv
+
+/-- Weighted enumeration of binary transcripts. The exponent vector on an
+accepted transcript is computed on its decoded occurrence. -/
+theorem weightedStreams {x : A} (W : MonomialWitness κ x) (C : ChoiceReader W.Choice) :
+ ∑ bs : successful W C, Diagonal.labelMonomial κ (W.exponents (C.completeEquiv.symm bs)) = x :=
+ (Fintype.sum_equiv (ι := successful W C) C.completeEquiv.symm _ _ (fun _ => rfl)).trans W.evaluates
+
+theorem history_weightedStreams {N : Network} (H : History A N) (K : H.KernelWitnesses κ)
+ (desc : Readers H K) (F : Factors A N) (W : ∀ u b, MonomialWitness κ (F u b))
+ (leaf : ∀ u b, ChoiceReader (W u b).Choice) :
+ let E := H.expandedWitness K F W
+ let C := historyReader H K desc F W leaf
+ ∑ bs : successful E C, Diagonal.labelMonomial κ (E.exponents (C.completeEquiv.symm bs)) = contract N F :=
+ weightedStreams _ _
+
+
+section Validator
+
+open BurstRAM BurstRAM.PrivateRAM RAMSort RAMLayout CursorNetwork CursorRouting
+
+variable {w p r k d e : ℕ} (M : Machine w p r k) (fuel : ℕ) (initial header : Word w)
+ (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (v : Fin (2^d)) (inc : Fin (width d (2^e) w) → Bool)
+
+private abbrev reportBits (rs : List (Report w)) := rs.flatMap (fun r => guessBits r.events)
+
+/-- Execute the original site loop once. The unused suffix is kept for the
+following child. The final status, successor, sort and memory tests are
+performed on the reports of this same loop. -/
+def incidentPrefix (bs : List Bool) : Option (List (Report w) × List Bool) := do
+ let raw := readIncident inc
+ let edges := (scanSuccessors hw hc initial v raw).1
+ if !edges.valid then none else
+ let (rs, rest) ← runSite M.program fuel (2^d) (2^e) v.val edges.input bs
+ if (finishReports edges.input edges.output rs []).1 &&
+ (checkSiteMemory (e := e) hw v header raw edges rs).1 then return (rs, rest) else none
+
+private theorem completeReport_iff (bs : List Bool) (rs : List (Report w)) :
+ let raw := readIncident inc
+ let edges := (scanSuccessors hw hc initial v raw).1
+ (M.validateIncident fuel initial header hw hc v inc bs).1 = some rs ↔
+ edges.valid = true ∧ SiteCheck M.program fuel (2^d) (2^e) v.val edges.input edges.output rs ∧
+ bs = reportBits rs ∧ (checkSiteMemory (e := e) hw v header raw edges rs).1 = true := by
+ let raw := readIncident inc
+ let edges := (scanSuccessors hw hc initial v raw).1
+ let b := (M.runBucket fuel (2^d) (2^e) v.val edges.input edges.output bs).1
+ have hb : b = some rs ↔ SiteCheck M.program fuel (2^d) (2^e) v.val edges.input edges.output rs ∧
+ bs = reportBits rs := M.runBucket_iff (Nat.two_pow_pos e)
+ dsimp only
+ change (if edges.valid then _ else (none, _)).1 = some rs ↔ edges.valid = true ∧
+ SiteCheck _ _ _ _ _ _ _ rs ∧ bs = reportBits rs ∧ (checkSiteMemory (e := e) hw v header raw edges rs).1 = true
+ rw [← and_assoc (a := SiteCheck ..), ← hb]
+ split_ifs with he
+ · dsimp only
+ cases hb' : (M.runBucket fuel (2^d) (2^e) v.val edges.input edges.output bs).1 with
+ | none =>
+ have h : b = none := hb'
+ change (none : Option (List (Report w))) = some rs ↔ _
+ simp [he,h]
+ | some ts =>
+ have h : b = some ts := hb'
+ change (if (checkSiteMemory (e := e) hw v header raw edges ts).1 then some ts else none) = some rs ↔ _
+ by_cases ht : ts = rs
+ · subst ts
+ cases (checkSiteMemory (e := e) hw v header raw edges rs).1 <;> simp [he, h]
+ · cases hm : (checkSiteMemory (e := e) hw v header raw edges ts).1 <;> simp [he, h, ht]
+ · simp [he]
+
+/-- On every incident bit vector, even one incompatible with the remote
+vertices, this parser takes exactly the accepting validator's private bits. -/
+theorem incidentPrefix_iff (bs tail : List Bool) (rs : List (Report w)) :
+ incidentPrefix M fuel initial header hw hc v inc bs = some (rs, tail) ↔
+ (M.validateIncident fuel initial header hw hc v inc (reportBits rs)).1 = some rs ∧
+ bs = reportBits rs ++ tail := by
+ let raw := readIncident inc
+ let edges := (scanSuccessors hw hc initial v raw).1
+ have hs := completeReport_iff M fuel initial header hw hc v inc (reportBits rs) rs
+ dsimp only at hs
+ rw [hs]
+ change _ ↔ (edges.valid = true ∧ SiteCheck _ _ _ _ _ _ _ _ ∧ _ ∧
+ (checkSiteMemory (e := e) hw v header raw edges rs).1 = true) ∧ _
+ unfold incidentPrefix
+ dsimp only
+ by_cases he : edges.valid = true
+ · have he' : (scanSuccessors hw hc initial v (readIncident inc)).1.valid = true := he
+ simp only [he', Bool.not_true, Bool.false_eq_true, ↓reduceIte, Option.bind_eq_bind,
+ Option.bind_eq_some_iff, Prod.exists, Bool.and_eq_true]
+ constructor
+ · rintro ⟨ts, rest, hrun, hfinish⟩
+ split at hfinish
+ · rename_i ok
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj hfinish)
+ obtain ⟨hr, hbits⟩ := (runSite_iff (Nat.two_pow_pos e)).mp hrun
+ obtain ⟨hend, hm⟩ := ok
+ exact ⟨⟨he, ⟨hr, ((finishReports_spec ..).mp hend).2⟩, trivial, hm⟩, hbits⟩
+ · contradiction
+ · rintro ⟨⟨_, ⟨hr, hend⟩, _, hm⟩, hbits⟩
+ refine ⟨rs, tail, (runSite_iff (Nat.two_pow_pos e)).mpr ⟨hr, hbits⟩, ?_⟩
+ have hd := (finishReports_spec edges.input edges.output rs []).mpr ⟨rfl,hend⟩
+ change (if (finishReports edges.input edges.output rs []).1 = true ∧
+ (checkSiteMemory (e := e) hw v header raw edges rs).1 = true then _ else _) = _
+ rw [ite_eq_left ⟨hd,hm⟩]
+ rfl
+ · have he' : (scanSuccessors hw hc initial v (readIncident inc)).1.valid = false := Bool.eq_false_iff.mpr he
+ simp [he', he]
+
+/-- The raw reader returns an accepting string as its own representation. -/
+def incidentReader : ChoiceReader (M.IncidentPaths fuel initial header hw hc v inc) where
+ encode x := x.val
+ read bs := match h : incidentPrefix M fuel initial header hw hc v inc bs with
+ | none => none
+ | some (rs, rest) => some (⟨reportBits rs, Option.isSome_iff_exists.mpr
+ ⟨rs, ((incidentPrefix_iff M fuel initial header hw hc v inc bs rest rs).mp h).1⟩⟩, rest)
+ read_iff bs x tail := by
+ constructor
+ · intro h
+ split at h
+ · contradiction
+ · rename_i rs rest hp
+ have eq := Prod.mk.inj (Option.some.inj h)
+ rw [← eq.2, ← eq.1]
+ exact ((incidentPrefix_iff ..).mp hp).2
+ · rintro rfl
+ obtain ⟨rs, hr⟩ := Option.isSome_iff_exists.mp x.prop
+ have hx := ((completeReport_iff M fuel initial header hw hc v inc x.val rs).mp hr).2.2.1
+ have hp := (incidentPrefix_iff M fuel initial header hw hc v inc (x.val ++ tail) tail rs).mpr
+ ⟨hx ▸ hr, by rw [hx]⟩
+ split
+ · rename_i h
+ rw [hp] at h
+ contradiction
+ · rename_i rs' rest hp'
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj (hp'.symm.trans hp))
+ exact congrArg some (Prod.ext (Subtype.ext hx.symm) rfl)
+
+/-- The successful raw prefix bound holds for independent half-wires as
+well as for a globally consistent assignment. -/
+theorem incidentReader_length_le (x : M.IncidentPaths fuel initial header hw hc v inc) :
+ ((incidentReader M fuel initial header hw hc v inc).encode x).length ≤ 2 * 2^e * (fuel + w) := by
+ obtain ⟨rs, hr⟩ := Option.isSome_iff_exists.mp x.prop
+ have hcplt := (completeReport_iff M fuel initial header hw hc v inc x.val rs).mp hr
+ have hsite := hcplt.2.1.1
+ have hlen := hsite.cost_lt (Nat.two_pow_pos e)
+ rw [RAMBuckets.cost_eq_length_add_probes] at hlen
+ have hrlen := (M.validateIncident_boundedReports fuel initial header hw hc v inc hr).1.2
+ have hbits (ts : List (Report w)) (ht : ∀ r ∈ ts, r.events.length < fuel) :
+ (reportBits ts).length ≤ ts.length * fuel + w * RAMBuckets.probeCount Report.probes ts := by
+ induction ts with
+ | nil => simp [reportBits, RAMBuckets.probeCount]
+ | cons r ts ih =>
+ have he := length_guessBits_le r.events
+ have hf := ht r (List.mem_cons_self ..)
+ have hb := ih fun t h => ht t (List.mem_cons_of_mem _ h)
+ simp only [reportBits, List.flatMap_cons, List.length_append, List.length_cons, Nat.succ_mul,
+ RAMBuckets.probeCount, Nat.mul_add, Report.probes] at *
+ omega
+ change x.val.length ≤ _
+ rw [hcplt.2.2.1]
+ calc
+ _ ≤ _ := hbits rs hrlen
+ _ ≤ (2 * 2^e) * fuel + w * (2 * 2^e) := Nat.add_le_add
+ (Nat.mul_le_mul_right _ (by omega)) (Nat.mul_le_mul_left _ (by omega))
+ _ = _ := by rw [Nat.mul_add, Nat.mul_comm w]
+
+end Validator
+section Cursor
+
+open BurstRAM BurstRAM.PrivateRAM RAMLayout CursorNetwork CursorRouting
+
+variable {w p r k D e : ℕ} [NeZero D] (M : Machine w p r k) (fuel : ℕ) (initial : Word w)
+ (hw : 2 ≤ w) (hc : 2^D * 2^e < 2^w)
+
+/-- Route and clamp checks precede any private validator choice. The
+transit case keeps the incoming suffix intact, including when it is nonempty. -/
+def bufferReader (hdr : Word w) (v : Position D) (buf : Buffers D (2^e) w) :
+ ChoiceReader {bs : List Bool // initialAccept M fuel initial hdr hw hc v buf bs = true} := by
+ by_cases hp : routeAccept (2^e) w v (readBuffer buf) = true
+ · by_cases hz : v.1 = 0
+ · exact (incidentReader M fuel initial hdr hw hc v.2 (incidentBuffer v buf)).reindex
+ (Equiv.subtypeEquivRight fun _ => by simp [initialAccept, hp, hz])
+ · refine ChoiceReader.single ⟨[], by simp [initialAccept, hp, hz]⟩ ?_
+ intro x
+ apply Subtype.ext
+ simpa [initialAccept, hp, hz] using x.prop
+ · exact ⟨fun x => False.elim (hp (Bool.and_eq_true_iff.mp x.prop).1),
+ fun _ => none, fun _ x _ => False.elim (hp (Bool.and_eq_true_iff.mp x.prop).1)⟩
+
+theorem bufferReader_length_le (hdr : Word w) (v : Position D) (buf : Buffers D (2^e) w)
+ (x : {bs : List Bool // initialAccept M fuel initial hdr hw hc v buf bs = true}) :
+ ((bufferReader M fuel initial hw hc hdr v buf).encode x).length ≤ 2 * 2^e * (fuel+w) := by
+ unfold bufferReader
+ split
+ · split
+ · exact incidentReader_length_le M fuel initial hdr hw hc v.2 (incidentBuffer v buf) _
+ · exact Nat.zero_le _
+ · rename_i h
+ exact (h (Bool.and_eq_true_iff.mp x.prop).1).elim
+
+/-- The actual cursor factor, on any supplied half-wire assignment. -/
+noncomputable def initialReader (header : ℕ → Word w) (v : Position D)
+ (z : (validatorNetwork D e w).Half v) : ChoiceReader (initialChoices M fuel initial header hw hc v z) :=
+ (bufferReader M fuel initial hw hc (header v.2) v (halfBuffers v z)).reindex
+ (initialAcceptEquiv M fuel initial header hw hc v z)
+
+/-- Transport actual leaf readers, including their individual accepting
+branch strings, into the dyadic-degree compressor's site coordinates. -/
+def pushLeafReaders {N Y : Network} (I : N.Iso Y) (P : Factors Type N) (c : ∀ u b, ChoiceReader (P u b)) :
+ ∀ v b, ChoiceReader (I.pushFactors P v b) :=
+ Equiv.piCongrLeft (fun v => ∀ b, ChoiceReader (I.pushFactors P v b)) I.site fun u z =>
+ (I.pushFactors_at P u z).symm ▸ c u (I.pullHalf u z)
+
+variable {b l a padding : ℕ} {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+ (header : ℕ → Word w) (labels : Fin D ≃ Fin b ⊕ Fin l) (hD : 1 < D) (hd : 2 + padding = 2 ^ a)
+ (T : History A (cursorState labels hD hd (ramFieldBits (2^e) w : RAMSystem D → ℕ)).network)
+ (K : T.KernelWitnesses κ) (desc : Readers T K)
+
+/-- Read the terms, shared arc bits and all local subtrees of a compression
+of the paper's RAM network, preserving the multiplicity of (12.2). -/
+noncomputable def cursorReader : ChoiceReader (expandedRAMStateCount M fuel initial header hw hc labels hD hd T K).Choice :=
+ let bits := (ramFieldBits (2^e) w : RAMSystem D → ℕ)
+ let I := cursorStateIso labels hD hd (ramSystemOrder D) bits
+ let P : Factors Type (paddedNetwork D padding bits) := fun v z =>
+ initialChoices M fuel initial header hw hc v (unpadHalf padding v z)
+ let fin : ∀ u z, Fintype (P u z) := fun u z =>
+ initialChoicesFintype M fuel initial header hw hc u (unpadHalf padding u z)
+ letI : ∀ v z, Fintype (I.pushFactors P v z) := I.pushChoiceFintype P fin
+ historyReader T K desc _ (fun v z => MonomialWitness.paths κ (I.pushFactors P v z))
+ (pushLeafReaders I P fun u z => initialReader M fuel initial hw hc header u (unpadHalf padding u z))
+
+/-- Equation (13.1)'s weighted equality with the original capped RAM path
+count, for the supplied kernel descriptors of the compressed history. -/
+theorem cursor_weightedStreams :
+ let E := expandedRAMStateCount M fuel initial header hw hc labels hD hd T K
+ let C := cursorReader M fuel initial hw hc header labels hD hd T K desc
+ ∑ bs : successful E C, Diagonal.labelMonomial κ (E.exponents (C.completeEquiv.symm bs)) =
+ (Nat.card (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2^D) header)
+ (withinCaps (2^D) (2^e))) : A) :=
+ weightedStreams _ _
+
+end Cursor
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationHistoryBounds.lean b/lean/OAI/Computability/VPVNP/PairSimulationHistoryBounds.lean
new file mode 100644
index 0000000000..62c6152713
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationHistoryBounds.lean
@@ -0,0 +1,343 @@
+import OAI.Computability.VPVNP.PairSimulationKernels
+import OAI.Computability.VPVNP.ShrinkStateWitness
+import OAI.Computability.VPVNP.ShrinkStateHistory
+import OAI.Computability.VPVNP.RefreshHistory
+import OAI.Computability.VPVNP.RefreshMonomialWitness
+
+/-!
+# Size of the binary stream at a final vertex
+
+Only locally summed fields contribute bits at an internal history node.
+The other bits belong to the placement-fiber children. This gives the
+same recursion as the occurrence count in Theorem 7.1, with the maximum
+per-record or initial-validator bit length as its multiplier.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords Compression
+open scoped Classical
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A} {N Y : Network}
+
+/-- Local vertex factors with their finite monomial choices and binary
+readers. The factor may depend on independently chosen half-wires. -/
+structure SiteParsers (κ : Label → A) (N : Network) where
+ /-- Value of each site's factor as a function of its incident half-wire assignment. -/
+ factors : Factors A N
+ /-- Finite monomial expansion of each site factor at the given half-wire assignment. -/
+ witnesses : ∀ u b, MonomialWitness κ (factors u b)
+ /-- Binary reader for a monomial witness choice at a site with the specified incident
+ half-wire assignment. -/
+ read : ∀ u b, ChoiceReader (witnesses u b).Choice
+
+/-- Data for reading one compression term's contribution at an output site, including the child
+order, input payload readers, and local kernel witnesses. -/
+structure TermParsers (κ : Label → A) (t : Term A N) where
+ /-- Orders of the children at each output site and of the two families of incident arcs at
+ each child. -/
+ order : LocalOrder t
+ /-- Binary reader for the payload type of each input arc, used to encode the children's
+ half-wire assignments. -/
+ payload : ∀ e, ChoiceReader (N.Payload e)
+ /-- Monomial expansion of the local kernel for each output site, placed input assignment, and
+ output half-wire assignment. -/
+ witness : ∀ v a z, MonomialWitness κ (t.kernel v a z)
+ /-- Binary reader for a choice in the local kernel's monomial expansion at the supplied
+ arguments. -/
+ read : ∀ v a z, ChoiceReader (witness v a z).Choice
+
+/-- Push the input site factors and their parsers through the term. The output parser reads the
+old halves, a local kernel choice, and the children in descriptor order. -/
+noncomputable def TermParsers.push {t : Term A N} (r : TermParsers κ t) (P : SiteParsers κ N) :
+ SiteParsers κ t.output where
+ factors := t.push P.factors
+ witnesses := t.pushWitness P.factors P.witnesses r.witness
+ read := pushReader t r.order r.payload P.factors P.witnesses P.read r.witness r.read
+
+/-- The bits consumed at the node, before it expands any children. -/
+noncomputable def TermParsers.ownBits {t : Term A N} (r : TermParsers κ t)
+ (v : t.output.Site) (a : Placed t.place N.Half v) (z : t.output.Half v) (p : (r.witness v a z).Choice) :=
+ (∑ u : t.Preimage v, ((half N u.val (r.order.outgoing u.val) (r.order.incoming u.val) r.payload).encode
+ (a u.val u.prop)).length) + ((r.read v a z).encode p).length
+
+/-- The descriptor's fields cover the old halves and locally summed indices.
+A field used by several maps can appear once on the left-hand side. -/
+def TermParsers.Covered {t : Term A N} (r : TermParsers κ t) (rec : t.output.Site → SiteRecords) : Prop :=
+ ∀ v a z p, r.ownBits v a z p ≤ ∑ f, (rec v).width f
+
+theorem TermParsers.push_bound {t : Term A N} (r : TermParsers κ t) (rec : t.output.Site → SiteRecords)
+ (cov : r.Covered rec) (P : SiteParsers κ N) (count : N.Site → ℕ) (B : ℕ)
+ (hfield : ∀ v f, (rec v).width f ≤ B)
+ (hP : ∀ u b p, ((P.read u b).encode p).length ≤ count u * B)
+ (v : t.output.Site) (z : t.output.Half v) (p : ((r.push P).witnesses v z).Choice) :
+ (((r.push P).read v z).encode p).length ≤ t.pushHistorySize rec count v * B := by
+ let x := t.pushChoice P.factors P.witnesses r.witness v z p
+ have he := pushReader_length t r.order r.payload P.factors P.witnesses P.read r.witness r.read v z p
+ dsimp only at he
+ erw [he, ← Nat.add_assoc]
+ change r.ownBits v x.1 z x.2.2 + _ ≤ _
+ rw [Term.pushHistorySize, Nat.add_mul, Finset.sum_mul]
+ apply Nat.add_le_add
+ · refine (cov v x.1 z x.2.2).trans ?_
+ calc
+ _ ≤ ∑ _ : (rec v).Field, B := Finset.sum_le_sum fun f _ => hfield v f
+ _ = Fintype.card (rec v).Field * B := by simp
+ _ ≤ (rec v).count * B := Nat.mul_le_mul_right _ (by unfold SiteRecords.count; omega)
+ · exact Finset.sum_le_sum fun u _ => hP u.val _ _
+
+section Slots
+
+variable {a b g n : ℕ} (X : State a g)
+
+/-- The outgoing descriptor list has the native outgoing-slot order. -/
+def outgoingOrder (u : X.network.Site) : Order {e // u = X.network.src e} :=
+ ⟨2^a, ⟨fun j => ⟨(u,j),rfl⟩, fun e => e.1.2, fun _ => rfl,
+ fun e => Subtype.ext (Prod.ext e.2 rfl)⟩⟩
+
+/-- The incoming descriptor list follows the inverse slot permutation.
+Thus parallel arcs appear at their own incoming and outgoing positions. -/
+def incomingOrder (u : X.network.Site) : Order {e // u = X.network.dst e} :=
+ let t := X.slots.actualGraph.target
+ ⟨2^a, ((outgoingOrder X u).entries).trans (t.symm.subtypeEquiv
+ (p := fun e : (X.Base × BitWord g) × Fin (2^a) => u = X.network.src e)
+ (q := fun e => u = X.network.dst e) fun e => by change (u = e.1) ↔ u = (t (t.symm e)).1; simp)⟩
+
+private theorem statePayload_length (e : X.network.Edge) (p : X.network.Payload e) :
+ ((statePayload X e).encode p).length = X.width ((e.1.1,e.2),e.1.2) := bitField_length _ _
+
+theorem stateHalf_length (u : X.network.Site) (src : Order {e // u = X.network.src e})
+ (dst : Order {e // u = X.network.dst e}) (h : X.network.Half u) :
+ ((half X.network u src dst (statePayload X)).encode h).length =
+ ∑ dir : Bool, ∑ j, X.halfWidth u dir j := by
+ rw [half_length]
+ simp only [statePayload_length]
+ rw [Fintype.sum_bool, Nat.add_comm (∑ j, X.halfWidth u true j)]
+ congr 1
+ · symm
+ apply Fintype.sum_equiv (outgoingOrder X u).entries
+ intro j
+ rfl
+ · symm
+ apply Fintype.sum_equiv (incomingOrder X u).entries
+ intro j
+ rfl
+
+/-- The common slot-record constructor charges each old half and all
+absorbed-word bits to genuine fields of the new site. -/
+theorem statePass_covered (pass : StatePass A X b n) (extra : pass.Records) (i : pass.step.Choice)
+ (r : TermParsers κ (pass.step.term i)) (hpayload : r.payload = statePayload X)
+ (hkernel : ∀ v a z p, ((r.read v a z).encode p).length ≤ ∑ f, (extra i v).width f) :
+ r.Covered (pass.slotRecords extra i) := by
+ intro v a z p
+ rw [TermParsers.ownBits, hpayload]
+ simp_rw [stateHalf_length]
+ unfold StatePass.slotRecords
+ simp only [Fintype.sum_sum_type, Sum.elim_inl, Sum.elim_inr, Fintype.sum_prod_type]
+ have h := hkernel v a z p
+ omega
+
+end Slots
+
+/-- Parsers for the actual terms on one selected branch. -/
+def ChainParsers (κ : Label → A) {N Y : Network} : TermChain A N Y → Type 1
+ | .done _ => PUnit
+ | .more t _ tail => TermParsers κ t × ChainParsers κ tail
+
+/-- Propagate the initial site parsers through each term to obtain parsers for the final
+network. -/
+noncomputable def finalParsers {N Y : Network} (c : TermChain A N Y) (r : ChainParsers κ c) (P : SiteParsers κ N) :
+ SiteParsers κ Y :=
+ match c with
+ | .done _ => P
+ | .more _ _ tail => finalParsers tail r.2 (r.1.push P)
+
+/-- At every term and output site, the bits for the old halves and the local kernel choice fit
+within the sum of that site's recorded field widths. -/
+def Covered {N Y : Network} (c : TermChain A N Y) (r : ChainParsers κ c) : Prop :=
+ match c with
+ | .done _ => True
+ | .more _ rec tail => r.1.Covered rec ∧ Covered tail r.2
+
+/-- A vertex's binary choices are bounded by its recursive history size
+times the largest allowance for one field or initial validator. -/
+theorem finalParsers_bound (c : TermChain A N Y) (r : ChainParsers κ c) (cov : Covered c r)
+ (P : SiteParsers κ N) (count : N.Site → ℕ) (B : ℕ) (hb : c.AllRecordsLe B)
+ (hP : ∀ u b p, ((P.read u b).encode p).length ≤ count u * B) :
+ ∀ v z p, (((finalParsers c r P).read v z).encode p).length ≤ c.occurrences count v * B := by
+ induction c with
+ | done => exact hP
+ | more t rec tail ih =>
+ exact ih r.2 cov.2 (r.1.push P) (t.pushHistorySize rec count) hb.2.2
+ (r.1.push_bound rec cov.1 P count B hb.1 hP)
+
+/-- Combine the local parser's size recurrence with the compressor's block
+count, field widths and initial-vertex bit bound. -/
+theorem finalParsers_blockBound (c : TermChain A N Y) (r : ChainParsers κ c) (cov : Covered c r)
+ (P : SiteParsers κ N) {C W s T L : ℕ} (hC : 1 ≤ C) (hc : c.Bounded C W)
+ (hlen : c.length ≤ s * T) (hP : ∀ u b p, ((P.read u b).encode p).length ≤ L) :
+ ∀ v z p, (((finalParsers c r P).read v z).encode p).length ≤
+ (C ^ s) ^ T * max L ((C ^ s) ^ T * (W+1)) := by
+ obtain ⟨hs, hw⟩ := c.blockGrowth hC hc hlen
+ let B := max L ((C ^ s)^T * (W+1))
+ have hh := finalParsers_bound c r cov P (fun _ => 1) B
+ (c.allRecordsLe_of_peak (W := W) (Nat.le_trans (Nat.le_trans (Nat.le_succ _) hw) (le_max_right ..)))
+ (fun u b p => (hP u b p).trans (by simp [B]))
+ exact fun v z p => (hh v z p).trans (Nat.mul_le_mul_right _ (hs v))
+
+/-- Supply the fixed native slot numbering and use only the recorded list
+of old child positions at each output site. -/
+def stateOrder {a g : ℕ} (X : State a g) (t : Term A X.network)
+ (children : ∀ v, Order (t.Preimage v)) : LocalOrder t :=
+ ⟨children, outgoingOrder X, incomingOrder X⟩
+
+section ShrinkState
+
+open State MotifBlocks MotifGrid MotifConversion PackingData ShrinkMotif
+
+variable {a b g : ℕ} {δ factor : ℝ} (X : State a (packingLaneBits a g))
+ {k : Type*} [Field k] (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+ {R : Type*} [CommRing R] (κ : (parameterData B).Entry → R) (hκ : (parameterData B).IsSolution κ)
+ (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) (s : X.ShrinkSelection B)
+
+variable (owners : ∀ v, Order {e // v = X.packingData.shrinkInternalOwner
+ (X.packingData.shrinkTermLayout B X.shrinkNumber X.packingWidth s) e})
+ (maps : ∀ v, Order {p : X.packingData.Motif × Fin 6 // X.packingData.shrinkPartySite
+ (X.packingData.shrinkTermLayout B X.shrinkNumber X.packingWidth s) p.1 p.2 = v})
+ (children : ∀ v, Order (((X.shrinkStatePass B κ hκ ready).step.term s).Preimage v))
+
+set_option maxHeartbeats 1200000 in
+/-- Parse the shrinking pass in the dyadic state coordinates actually used
+by the scheduled procedure. -/
+noncomputable def shrinkStateParsers : TermParsers (N := X.network) κ ((X.shrinkStatePass B κ hκ ready).step.term s) where
+ order := stateOrder X _ children
+ payload := statePayload X
+ witness := X.shrinkStateKernelWitness B κ hκ ready s
+ read := fun v _ _ => shrinkReader X.packingData (two_le_packingColors _) (Nat.two_pow_pos _)
+ X.shrinkNumber X.shrinkOrder X.packingWidth B κ hκ ready (X.shrinkStateIndex ready)
+ s owners maps v _ _
+
+set_option maxHeartbeats 1200000 in
+/-- The concrete kernel's word choices are included in the original
+shrinking-site descriptor used in the proof of Theorem 7.1. -/
+theorem shrinkStateParsers_covered :
+ (shrinkStateParsers X B κ hκ ready s owners maps children).Covered
+ ((X.shrinkStatePass B κ hκ ready).slotRecords (X.shrinkExtraRecords B κ hκ ready) s) := by
+ apply statePass_covered X (X.shrinkStatePass B κ hκ ready) (X.shrinkExtraRecords B κ hκ ready) s _ rfl
+ intro v a z x
+ have he := shrinkReader_length X.packingData (two_le_packingColors _) (Nat.two_pow_pos _)
+ X.shrinkNumber X.shrinkOrder X.packingWidth B κ hκ ready (X.shrinkStateIndex ready)
+ s owners maps v _ _ x
+ apply he.le.trans
+ unfold State.shrinkExtraRecords PackingData.shrinkSiteRecords
+ simp only [Fintype.sum_sum_type]
+ refine (le_of_eq ?_).trans (Nat.le_add_right _ _)
+ let owner := X.packingData.shrinkInternalOwner
+ (X.packingData.shrinkTermLayout B X.shrinkNumber X.packingWidth s)
+ let equiv : {e // v = owner e} ≃ {e // owner e = v} :=
+ Equiv.subtypeEquivRight fun _ => eq_comm
+ let f (e : X.packingData.Motif × Fin 4) := X.packingData.shrinkSupplyWidths X.shrinkNumber X.packingWidth B
+ e.1 (s e.1) (!(X.packingData.shrinkTermLayout B X.shrinkNumber X.packingWidth s),e.2)
+ convert! Fintype.sum_equiv equiv (fun i => f i.val) (fun i => f i.val) (fun _ => rfl) using 1
+ congr 1
+ ext j
+ simp
+
+end ShrinkState
+
+section RefreshState
+
+open Refresh DegreeRefresh MotifConversion SpectralGeometry
+
+variable {a g a₀ dH : ℕ} {k : Type*} [Field k] {K K' : ℝ}
+ (X : State a (a + g)) (P : RegularArcGraph (Fin (2 ^ a)) dH) (hdH : 0 < dH)
+ (hconn : (arcSupportGraph P.multiplicity).Connected)
+ (F : RefreshBlock k (expanderSupply P hdH hconn) (2 ^ a₀) K K')
+ (hD : 1 < 2 ^ a) (hd : dH + 1 ≤ 2 ^ a₀)
+ {R : Type*} [CommRing R] (κ : (parameterData F).Entry → R) (hκ : (parameterData F).IsSolution κ)
+ (c : DyadicRefreshChoice X P hdH hconn F)
+
+variable (children : ∀ v, Order (((dyadicRefreshPass X P hdH hconn F hD hd κ hκ).step.term c).Preimage v))
+
+set_option maxHeartbeats 1200000 in
+/-- The degree-refresh map in the same coordinates as the actual block execution. -/
+noncomputable def refreshStateParsers : TermParsers (N := X.network) κ ((dyadicRefreshPass X P hdH hconn F hD hd κ hκ).step.term c) where
+ order := stateOrder X _ children
+ payload := statePayload X
+ witness := dyadicRefreshKernelWitness X P hdH hconn F hD hd κ hκ c
+ read := fun v _ _ => refreshReader (splitSlots X) (bitWordFinEquiv a) (splitWidths X)
+ P hdH hconn F hD hd c κ hκ v _ _
+
+set_option maxHeartbeats 1200000 in
+/-- Its kernel is a deterministic entry check. Only the placed old halves
+contribute private wire guesses, all covered by the slot records. -/
+theorem refreshStateParsers_covered :
+ (refreshStateParsers X P hdH hconn F hD hd κ hκ c children).Covered
+ ((dyadicRefreshPass X P hdH hconn F hD hd κ hκ).slotRecords (refreshLocalRecords X P hdH hconn F hD hd κ hκ) c) := by
+ apply statePass_covered X (dyadicRefreshPass X P hdH hconn F hD hd κ hκ) _ c _ rfl
+ intro v old new p
+ have h := listedEntryReader_length κ _ _ (refreshNames_spec (splitSlots X) (bitWordFinEquiv a)
+ (splitWidths X) P hdH hconn F hD hd c v _ _) p
+ exact h.le.trans (Nat.zero_le _)
+
+end RefreshState
+section CursorState
+
+open CursorNetwork CursorRouting BurstRAM BurstRAM.PrivateRAM
+
+variable {w p r k D e b l a padding : ℕ} [NeZero D]
+ (M : Machine w p r k) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2^D * 2^e < 2^w)
+ (labels : Fin D ≃ Fin b ⊕ Fin l) (hD : 1 < D) (hd : 2+padding = 2^a)
+
+private theorem castReader_le {α β : Type} (h : α = β) (r : ChoiceReader α) (L : ℕ)
+ (hL : ∀ x, (r.encode x).length ≤ L) :
+ ∀ y, (((h ▸ r) : ChoiceReader β).encode y).length ≤ L := by
+ subst β
+ exact hL
+
+private theorem pushLeafReaders_le {N Y : Network} (I : N.Iso Y) (P : Factors Type N)
+ (c : ∀ u b, ChoiceReader (P u b)) (L : ℕ) (hL : ∀ u b p, ((c u b).encode p).length ≤ L) :
+ ∀ v z p, ((pushLeafReaders I P c v z).encode p).length ≤ L := by
+ intro v
+ obtain ⟨u, rfl⟩ := I.site.surjective v
+ intro z
+ rw [pushLeafReaders, Equiv.piCongrLeft_apply_apply]
+ exact castReader_le _ _ L (hL u (I.pullHalf u z))
+
+/-- The input factors and their concrete binary readers in compressor-state coordinates. -/
+noncomputable def cursorSiteParsers (κ : Label → A) :
+ SiteParsers κ (cursorState labels hD hd (ramFieldBits (2^e) w : RAMSystem D → ℕ)).network :=
+ let bits := (ramFieldBits (2^e) w : RAMSystem D → ℕ)
+ let I := cursorStateIso labels hD hd (ramSystemOrder D) bits
+ let P : Factors Type (paddedNetwork D padding bits) := fun v z =>
+ initialChoices M fuel initial header hw hc v (unpadHalf padding v z)
+ let fin : ∀ u z, Fintype (P u z) := fun u z =>
+ initialChoicesFintype M fuel initial header hw hc u (unpadHalf padding u z)
+ letI : ∀ v z, Fintype (I.pushFactors P v z) := I.pushChoiceFintype P fin
+ ⟨fun v z => (Fintype.card (I.pushFactors P v z) : A),
+ fun v z => MonomialWitness.paths κ (I.pushFactors P v z),
+ pushLeafReaders I P fun u z => initialReader M fuel initial hw hc header u (unpadHalf padding u z)⟩
+
+theorem cursorSiteParsers_length_le (κ : Label → A) :
+ ∀ v z p, (((cursorSiteParsers M fuel initial header hw hc labels hD hd κ).read v z).encode p).length ≤
+ 2 * 2^e * (fuel+w) := by
+ unfold cursorSiteParsers
+ dsimp only
+ exact pushLeafReaders_le (cursorStateIso labels hD hd (ramSystemOrder D) (ramFieldBits (2^e) w))
+ (fun u z => initialChoices M fuel initial header hw hc u (unpadHalf padding u z))
+ (fun u z => initialReader M fuel initial hw hc header u (unpadHalf padding u z)) _
+ (fun u z p => bufferReader_length_le M fuel initial hw hc (header u.2) u
+ (halfBuffers u (unpadHalf padding u z)) _)
+
+end CursorState
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationInlineLiteral.lean b/lean/OAI/Computability/VPVNP/PairSimulationInlineLiteral.lean
new file mode 100644
index 0000000000..bd19701e61
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationInlineLiteral.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Native synthesis of a fixed table word
+
+A fixed instruction block loads a natural constant modulo the current word modulus.
+Its only literal operands are zero and one. Every block of the same capacity takes the
+same number of local steps, including at width zero and after the accumulator wraps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.InlinePublic
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {p r k w : ℕ}
+
+/-- The first two instructions initialize the unit and accumulator registers. Each
+remaining instruction either increments the accumulator or copies it to itself. -/
+def literalInstruction (w C value : ℕ) (pc : Fin (C + 3) → Fin p)
+ (unit acc : Fin r) (i : Fin (C + 2)) : Instr w p r k :=
+ if i.val = 0 then .constant unit 1 (pc i.succ)
+ else if i.val = 1 then .constant acc 0 (pc i.succ)
+ else if i.val - 2 < value then .binary .add acc acc unit (pc i.succ)
+ else .copy acc acc (pc i.succ)
+
+theorem literal_resize (C value : ℕ) (pc : Fin (C + 3) → Fin p)
+ (unit acc : Fin r) (i : Fin (C + 2)) :
+ (literalInstruction (k := k) 2 C value pc unit acc i).resize w =
+ literalInstruction w C value pc unit acc i := by
+ unfold literalInstruction
+ split <;> rename_i h
+ · rfl
+ · split <;> rename_i h'
+ · rfl
+ · split <;> rfl
+
+/-- Executing the constant block uses exactly two initializations and one tick for
+each reserved position. It preserves the private memory and every other register. -/
+theorem literal_prefix {C value : ℕ} {M : Machine w p r k}
+ {pc : Fin (C + 3) → Fin p} {unit acc : Fin r} (hu : unit ≠ acc) (hv : value ≤ C)
+ (hc : ∀ i : Fin (C + 2), M.code (pc i.castSucc) =
+ literalInstruction w C value pc unit acc i) (c : Config w p r) (hp : c.pc = pc 0) :
+ ∃ out, Prefix M c (List.replicate (C + 2) .tick) out ∧
+ out.pc = pc (Fin.last (C + 2)) ∧ out.reg acc = (value : Word w) ∧
+ (∀ j, j ≠ unit → j ≠ acc → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let row (j : ℕ) (hj : j ≤ C) : Fin (C + 3) := ⟨j + 2, by omega⟩
+ let cu := c.put (pc ⟨1, by omega⟩) unit 1
+ let mid (j : ℕ) (hj : j ≤ C) :=
+ cu.put (pc (row j hj)) acc ((min j value : ℕ) : Word w)
+ have he (i : Fin (C + 2)) (a : Config w p r) (hpc : a.pc = pc i.castSucc) :
+ M.program.step a = (literalInstruction w C value pc unit acc i).run M.publicData a := by
+ simp only [Machine.program, hpc, hc]
+ have h0 : M.program.step c = .localStep cu := by
+ rw [he (⟨0, by omega⟩ : Fin (C + 2)) c hp]
+ rfl
+ have h1 : M.program.step cu = .localStep (mid 0 (Nat.zero_le _)) := by
+ rw [he (⟨1, by omega⟩ : Fin (C + 2)) cu rfl]
+ simp [literalInstruction, mid, row, Instr.run]
+ congr 2
+ have walk (j : ℕ) (hj : j ≤ C) :
+ Prefix M c (List.replicate (j + 2) .tick) (mid j hj) := by
+ induction j with
+ | zero => exact .tick h0 (.tick h1 (.nil _))
+ | succ j ih =>
+ have hj' : j ≤ C := by omega
+ have s : M.program.step (mid j hj') = .localStep (mid (j + 1) hj) := by
+ rw [he (⟨j + 2, by omega⟩ : Fin (C + 2)) _ rfl]
+ have h₀ : j + 2 ≠ 0 := by omega
+ have h₁ : j + 2 ≠ 1 := by omega
+ simp only [literalInstruction, h₀, h₁, ite_false, Nat.add_sub_cancel]
+ by_cases h : j < value
+ · simp [h, Instr.run, BinaryOp.eval, mid, cu, Config.put, hu,
+ min_eq_left h.le, row]
+ · have hmin : min (j + 1) value = value := min_eq_right (by omega)
+ simp [h, Instr.run, mid, Config.put, min_eq_right (by omega : value ≤ j), hmin, row]
+ simpa [List.replicate_succ'] using (ih hj').append (.tick s (.nil _))
+ refine ⟨mid C le_rfl, walk C le_rfl, rfl, ?_, ?_, rfl, rfl⟩
+ · simp [mid, min_eq_right hv]
+ · intro j hju hja
+ simp [mid, cu, Config.put, Function.update_of_ne hja, Function.update_of_ne hju]
+
+end PairSimulation.InlinePublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationInlinePrefix.lean b/lean/OAI/Computability/VPVNP/PairSimulationInlinePrefix.lean
new file mode 100644
index 0000000000..e18eb25625
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationInlinePrefix.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.PairSimulationInlinePublic
+
+/-!
+# Linking lowered table prefixes into a larger native machine
+
+The caller may place a continuation directly at an accepting exit and its own rejecting
+instruction at a failure exit. A source prefix only executes nonterminal rows, so these
+exit labels can be shared even when the source instruction at the exit is absent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.InlinePublic
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {v w C p r k P R K : ℕ}
+
+/-- Install the consecutive source blocks and local registers at enclosing locations. -/
+def embedding (C p r : ℕ) (pc : Fin (p * (C + 3)) → Fin P) (reg : Fin (r + 2) ↪ Fin R) :
+ Placement C p r P R where
+ pc i j := pc ((canonical C p r).pc i j)
+ reg := (canonical C p r).reg.trans reg
+ unit := reg (canonical C p r).unit
+ acc := reg (canonical C p r).acc
+ distinct := fun e => (canonical C p r).distinct (reg.injective e)
+ reg_unit i e := (canonical C p r).reg_unit i (reg.injective e)
+ reg_acc i e := (canonical C p r).reg_acc i (reg.injective e)
+
+/-- A terminal source entry can be an external continuation label. Its outgoing row
+is unnecessary when linking prefixes. -/
+def Placement.withExits (D : Placement C p r P R) (exit : Fin p → Option (Fin P)) :
+ Placement C p r P R :=
+ {D with pc := fun i j => if j = 0 then (exit i).getD (D.entry i) else D.pc i j}
+
+@[simp] theorem Placement.entry_withExits (D : Placement C p r P R)
+ (exit : Fin p → Option (Fin P)) (i : Fin p) :
+ (D.withExits exit).entry i = (exit i).getD (D.entry i) := by
+ simp [Placement.entry, Placement.withExits]
+
+/-- A nonterminal source row has a continuation. -/
+def continues : Instr v p r k → Bool
+ | .returnState _ | .accept | .reject => false
+ | _ => true
+
+private theorem continues_local {i : Instr v p r k} {pub : Fin k → Word w}
+ {s next : Config w p r} (h : (i.resize w).run pub s = .localStep next) :
+ continues i = true := by
+ cases i <;> first | rfl | cases h
+
+private theorem continues_branch {i : Instr v p r k} {pub : Fin k → Word w}
+ {s : Config w p r} {next : Bool → Config w p r} (h : (i.resize w).run pub s = .branch next) :
+ continues i = true := by
+ cases i <;> first | rfl | cases h
+
+@[simp] theorem padded_length (pad : ℕ) (es : List (Event w)) :
+ (padded pad es).length = (pad + 1) * es.length := by
+ induction es with
+ | nil => simp [padded]
+ | cons e es ih => simp [padded, ih, Nat.mul_succ]; omega
+
+@[simp] theorem padded_ticks (pad n : ℕ) :
+ padded pad (List.replicate n (.tick : Event w)) = List.replicate ((pad + 1) * n) .tick := by
+ induction n with
+ | zero => rfl
+ | succ n ih =>
+ rw [List.replicate_succ, padded, ih, ← List.replicate_succ, ← List.replicate_add]
+ congr 1
+ rw [Nat.mul_succ]
+ omega
+
+private theorem tickBits (pad : ℕ) (es : List (Event w)) :
+ choiceBits (List.replicate pad .tick ++ es) = choiceBits es := by
+ induction pad with
+ | zero => rfl
+ | succ pad ih => simpa [List.replicate_succ, choiceBits] using ih
+
+@[simp] theorem padded_choiceBits (pad : ℕ) (es : List (Event w)) :
+ choiceBits (padded pad es) = choiceBits es := by
+ induction es with
+ | nil => rfl
+ | cons e es ih => rw [padded, tickBits]; cases e <;> simp [choiceBits, ih]
+
+/-- Transport every local path, with the same choice bits and the exact fixed slowdown.
+Only nonterminal code must be linked. The host's final configuration exposes the entire
+source register file, the private memory, and the enclosing caller's register frame. -/
+theorem prefix_lower (T : Template p r k) (bank : Fin k → ℕ) (D : Placement C p r P R)
+ (M : Machine w P R K) {frame : Fin R → Word w}
+ (bound : ∀ j, operand bank (T.code j) ≤ C)
+ (hc : ∀ j, continues (T.code j) = true → ContainsAt M T bank D j)
+ {s last : Config w p r} {h : Config w P R} {es : List (Event w)}
+ (path : Prefix (T.instantiate w (fun j => (bank j : Word w))) s es last)
+ (rel : Related D frame s h) :
+ ∃ out, Prefix M h (padded (C + 2) es) out ∧ Related D frame last out := by
+ induction path generalizing h with
+ | nil s => exact ⟨h, .nil _, rel⟩
+ | @tick s next last es step tail ih =>
+ obtain ⟨mid, pre, actions⟩ := simulate_row (bound s.pc) (hc s.pc (continues_local step)) rel
+ rw [step] at actions
+ generalize hmid : M.program.step mid = act at actions
+ cases actions with
+ | localStep nextRel =>
+ obtain ⟨out, post, outRel⟩ := ih nextRel
+ exact ⟨out, pre.append (.tick hmid post), outRel⟩
+ | @choice s g b last es step tail ih =>
+ obtain ⟨mid, pre, actions⟩ := simulate_row (bound s.pc) (hc s.pc (continues_branch step)) rel
+ rw [step] at actions
+ generalize hmid : M.program.step mid = act at actions
+ cases actions with
+ | branch nextRel =>
+ obtain ⟨out, post, outRel⟩ := ih (nextRel b)
+ exact ⟨out, pre.append (.choice hmid post), outRel⟩
+
+/-- The map table's deterministic path and its computed histogram share the same private
+memory. A bound on the source tick count scales by the uniform block length. -/
+theorem ticks_lower (T : Template p r k) (bank : Fin k → ℕ) (D : Placement C p r P R)
+ (M : Machine w P R K) {frame : Fin R → Word w}
+ (bound : ∀ j, operand bank (T.code j) ≤ C)
+ (hc : ∀ j, continues (T.code j) = true → ContainsAt M T bank D j)
+ {s last : Config w p r} {h : Config w P R} {n : ℕ}
+ (path : Prefix (T.instantiate w (fun j => (bank j : Word w))) s (List.replicate n .tick) last)
+ (rel : Related D frame s h) :
+ ∃ out, Prefix M h (List.replicate ((C + 3) * n) .tick) out ∧ Related D frame last out := by
+ simpa using prefix_lower T bank D M bound hc path rel
+
+/-- View a live host configuration as source state at a known entry. -/
+def restrict (D : Placement C p r P R) (pc : Fin p) (h : Config w P R) : Config w p r :=
+ ⟨pc, h.persistent, h.reg ∘ D.reg, h.privateMem⟩
+
+theorem restrict_related (D : Placement C p r P R) (pc : Fin p) (h : Config w P R)
+ (hp : h.pc = D.entry pc) : Related D h.reg (restrict D pc h) h :=
+ ⟨⟨fun _ => rfl, rfl, rfl, fun _ _ => rfl⟩, hp⟩
+
+end PairSimulation.InlinePublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationInlinePublic.lean b/lean/OAI/Computability/VPVNP/PairSimulationInlinePublic.lean
new file mode 100644
index 0000000000..88a45af9c3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationInlinePublic.lean
@@ -0,0 +1,236 @@
+import OAI.Computability.VPVNP.PairSimulationInlineLiteral
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# Lowering a static public bank to a fixed native instruction table
+
+The enclosing machine supplies only code labels and register positions. Its public
+words are available to other routines. Each source instruction occupies an equally long
+block consisting of a local constant synthesis followed by the relocated operation.
+The final operation has the source's branches, probes and halt behavior.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.InlinePublic
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {v w C p r k P R K : ℕ}
+
+/-- A fixed bound covering every source immediate and every fixed public word. -/
+def capacity (T : Template p r k) (bank : Fin k → ℕ) := 2 ^ T.literalWidth + ∑ i, bank i
+
+/-- Native locations of the relocated code, source registers, and the two scratch words. -/
+structure Placement (C p r P R : ℕ) where
+ /-- Host code address for each source instruction and offset in its block of `C + 3`
+ instructions. -/
+ pc : Fin p → Fin (C + 3) → Fin P
+ /-- Embed the source registers into the host register file for the relocated instruction. -/
+ reg : Fin r ↪ Fin R
+ /-- Scratch register initialized to one for the increments used to synthesize a fixed
+ operand. -/
+ unit : Fin R
+ /-- Scratch register that accumulates the fixed operand before the relocated instruction
+ runs. -/
+ acc : Fin R
+ distinct : unit ≠ acc
+ reg_unit : ∀ i, reg i ≠ unit
+ reg_acc : ∀ i, reg i ≠ acc
+
+namespace Placement
+
+/-- Host address at offset zero of the block for a given source instruction. -/
+def entry (D : Placement C p r P R) (i : Fin p) := D.pc i 0
+
+/-- A host register reserved for the enclosing program, distinct from both scratch registers
+and all relocated source registers. -/
+def privateReg (D : Placement C p r P R) (j : Fin R) : Prop :=
+ j ≠ D.unit ∧ j ≠ D.acc ∧ j ∉ Set.range D.reg
+
+end Placement
+
+/-- The word prepared by this source row. -/
+def operand (bank : Fin k → ℕ) : Instr v p r k → ℕ
+ | .constant _ a _ => a.val
+ | .publicWord _ i _ => bank i
+ | _ => 0
+
+theorem operand_le (T : Template p r k) (bank : Fin k → ℕ) (j : Fin p) :
+ operand bank (T.code j) ≤ capacity T bank := by
+ cases T.code j with
+ | constant dst a next => exact a.isLt.le.trans (Nat.le_add_right _ _)
+ | publicWord dst i next =>
+ exact (Finset.single_le_sum (fun j _ => Nat.zero_le (bank j)) (Finset.mem_univ i)).trans
+ (Nat.le_add_left _ _)
+ | _ => exact Nat.zero_le _
+
+/-- Only the two instructions with immediate data are replaced by a copy from the
+accumulator. All other operands and control transfers are directly relocated. -/
+def body (D : Placement C p r P R) : Instr v p r k → Instr w P R K
+ | .constant a _ j | .publicWord a _ j => .copy (D.reg a) D.acc (D.entry j)
+ | .stateWord a j => .stateWord (D.reg a) (D.entry j)
+ | .copy a b j => .copy (D.reg a) (D.reg b) (D.entry j)
+ | .binary op a b c j => .binary op (D.reg a) (D.reg b) (D.reg c) (D.entry j)
+ | .loadPrivate a b j => .loadPrivate (D.reg a) (D.reg b) (D.entry j)
+ | .storePrivate a b j => .storePrivate (D.reg a) (D.reg b) (D.entry j)
+ | .jumpEq a b y n => .jumpEq (D.reg a) (D.reg b) (D.entry y) (D.entry n)
+ | .jumpLt a b y n => .jumpLt (D.reg a) (D.reg b) (D.entry y) (D.entry n)
+ | .choose y n => .choose (D.entry y) (D.entry n)
+ | .readExternal a b j => .readExternal (D.reg a) (D.reg b) (D.entry j)
+ | .writeExternal a b j => .writeExternal (D.reg a) (D.reg b) (D.entry j)
+ | .returnState a => .returnState (D.reg a)
+ | .accept => .accept
+ | .reject => .reject
+
+@[simp] theorem body_resize (D : Placement C p r P R) (i : Instr v p r k) :
+ (body (w := 2) (K := K) D i).resize w = body D i := by cases i <;> rfl
+
+/-- Code for one uniform block in a host with any public-word ABI. -/
+def row (T : Template p r k) (bank : Fin k → ℕ) (D : Placement C p r P R)
+ (j : Fin p) : Fin (C + 3) → Instr 2 P R K :=
+ Fin.lastCases (body D (T.code j))
+ (literalInstruction 2 C (operand bank (T.code j)) (D.pc j) D.unit D.acc)
+
+/-- Consecutive code blocks and a trailing scratch register pair. -/
+def canonical (C p r : ℕ) : Placement C p r (p * (C + 3)) (r + 2) where
+ pc i t := finProdFinEquiv (i, t)
+ reg := Fin.castAddEmb 2
+ unit := ⟨r, by omega⟩
+ acc := ⟨r + 1, by omega⟩
+ distinct h := by have := congrArg Fin.val h; dsimp at this; omega
+ reg_unit i h := by have := congrArg Fin.val h; exact i.isLt.ne this
+ reg_acc i h := by have hh := congrArg Fin.val h; change i.val = r + 1 at hh; omega
+
+/-- Closed width-two template. Neither its labels nor its code depends on the word width. -/
+def compiled (K : ℕ) (T : Template p r k) (bank : Fin k → ℕ) :
+ Template (p * (capacity T bank + 3)) (r + 2) K where
+ literalWidth := 2
+ entry := (canonical (capacity T bank) p r).entry T.entry
+ code a := let jt := finProdFinEquiv.symm a
+ row T bank (canonical (capacity T bank) p r) jt.1 jt.2
+
+/-- The complete block is present at this source label. -/
+def ContainsAt (M : Machine w P R K) (T : Template p r k) (bank : Fin k → ℕ)
+ (D : Placement C p r P R) (j : Fin p) :=
+ ∀ t, M.code (D.pc j t) = (row (K := K) T bank D j t).resize w
+
+theorem compiled_contains (T : Template p r k) (bank : Fin k → ℕ) (pub : Fin K → Word w)
+ (j : Fin p) : ContainsAt ((compiled K T bank).instantiate w pub) T bank
+ (canonical (capacity T bank) p r) j := by
+ intro t
+ change (row T bank _ (finProdFinEquiv.symm (finProdFinEquiv (j, t))).1
+ (finProdFinEquiv.symm (finProdFinEquiv (j, t))).2).resize w = _
+ simp
+
+/-- Observable configuration data. The enclosing code can reserve unrelated registers. -/
+structure Agrees (D : Placement C p r P R) (frame : Fin R → Word w)
+ (s : Config w p r) (h : Config w P R) : Prop where
+ reg : ∀ i, h.reg (D.reg i) = s.reg i
+ privateMem : h.privateMem = s.privateMem
+ persistent : h.persistent = s.persistent
+ frame : ∀ i, D.privateReg i → h.reg i = frame i
+
+/-- The host is at the entry of the current source instruction's block, agrees on source
+registers, private memory and persistent state, and matches the given frame on enclosing
+registers. -/
+def Related (D : Placement C p r P R) (frame : Fin R → Word w)
+ (s : Config w p r) (h : Config w P R) : Prop := Agrees D frame s h ∧ h.pc = D.entry s.pc
+
+private theorem agree_put {D : Placement C p r P R} {frame : Fin R → Word w}
+ {s : Config w p r} {h : Config w P R} (a : Agrees D frame s h)
+ (next : Fin p) (i : Fin r) (x : Word w) :
+ Related D frame (s.put next i x) (h.put (D.entry next) (D.reg i) x) := by
+ refine ⟨⟨?_, a.privateMem, a.persistent, ?_⟩, rfl⟩
+ · intro l
+ by_cases he : l = i <;> simp [Config.put, he, a.reg]
+ · intro l hl
+ have he : l ≠ D.reg i := fun e => hl.2.2 ⟨i, e.symm⟩
+ simp [Config.put, Function.update_of_ne he, a.frame l hl]
+
+private theorem agree_pc {D : Placement C p r P R} {frame : Fin R → Word w}
+ {s : Config w p r} {h : Config w P R} (a : Agrees D frame s h) (next : Fin p) :
+ Related D frame {s with pc := next} {h with pc := D.entry next} :=
+ ⟨⟨a.reg, a.privateMem, a.persistent, a.frame⟩, rfl⟩
+
+/-- A matching native action has the same observable event and relates all continuations. -/
+inductive ActionsMatch {S H : Type*} (rel : S → H → Prop) :
+ CallAction w S → CallAction w H → Prop
+ | localStep {s h} (next : rel s h) : ActionsMatch rel (.localStep s) (.localStep h)
+ | branch {s h} (next : ∀ b, rel (s b) (h b)) : ActionsMatch rel (.branch s) (.branch h)
+ | read {addr s h} (next : ∀ v, rel (s v) (h v)) : ActionsMatch rel (.read addr s) (.read addr h)
+ | write {addr val s h} (next : rel s h) : ActionsMatch rel (.write addr val s) (.write addr val h)
+ | finish (res) : ActionsMatch rel (.finish res) (.finish res)
+ | reject : ActionsMatch rel .reject .reject
+
+private theorem body_action {D : Placement C p r P R} {frame : Fin R → Word w}
+ {s : Config w p r} {h : Config w P R} (a : Agrees D frame s h) (bank : Fin k → ℕ)
+ (pub : Fin K → Word w) (i : Instr v p r k) (ha : h.reg D.acc = (operand bank i : Word w)) :
+ ActionsMatch (Related D frame) ((i.resize w).run (fun j => (bank j : Word w)) s)
+ ((body D i).run pub h) := by
+ cases i with
+ | constant dst val next | publicWord dst val next =>
+ apply ActionsMatch.localStep
+ rw [ha]
+ exact agree_put a _ _ _
+ | stateWord dst next =>
+ simp only [Instr.resize, Instr.run, body, a.persistent]
+ exact .localStep (agree_put a _ _ _)
+ | copy dst src next | binary _ dst src _ next | loadPrivate dst src next =>
+ simp only [Instr.resize, Instr.run, body, a.reg, a.privateMem]
+ exact .localStep (agree_put a _ _ _)
+ | storePrivate addr src next =>
+ simp only [Instr.resize, Instr.run, body, a.reg]
+ exact .localStep ⟨⟨a.reg, congrArg (fun m => Function.update m _ _) a.privateMem,
+ a.persistent, a.frame⟩, rfl⟩
+ | jumpEq lhs rhs yes no | jumpLt lhs rhs yes no =>
+ simp only [Instr.resize, Instr.run, body, a.reg]
+ split <;> exact .localStep (agree_pc a _)
+ | choose yes no =>
+ exact .branch (fun b => by cases b <;> exact agree_pc a _)
+ | readExternal dst addr next =>
+ simp only [Instr.resize, Instr.run, body, a.reg]
+ exact .read (fun _ => agree_put a _ _ _)
+ | writeExternal addr src next =>
+ simp only [Instr.resize, Instr.run, body, a.reg]
+ exact .write (agree_pc a _)
+ | returnState src =>
+ simp only [Instr.resize, Instr.run, body, a.reg]
+ exact .finish _
+ | accept => exact .finish _
+ | reject => exact .reject
+
+/-- Exact one-row simulation, from an arbitrary source and host configuration. -/
+theorem simulate_row {T : Template p r k} {bank : Fin k → ℕ} {D : Placement C p r P R}
+ {M : Machine w P R K} {frame : Fin R → Word w} {s : Config w p r} {h : Config w P R}
+ (bound : operand bank (T.code s.pc) ≤ C) (hc : ContainsAt M T bank D s.pc)
+ (rel : Related D frame s h) :
+ ∃ mid, Prefix M h (List.replicate (C + 2) .tick) mid ∧
+ ActionsMatch (Related D frame)
+ ((T.instantiate w (fun j => (bank j : Word w))).program.step s) (M.program.step mid) := by
+ have installed (i : Fin (C + 2)) : M.code (D.pc s.pc i.castSucc) =
+ literalInstruction w C (operand bank (T.code s.pc)) (D.pc s.pc) D.unit D.acc i := by
+ rw [hc, row, Fin.lastCases_castSucc, literal_resize]
+ obtain ⟨mid, pref, hp, ha, hr, hm, hs⟩ := literal_prefix D.distinct bound installed h rel.2
+ refine ⟨mid, pref, ?_⟩
+ change ActionsMatch _ (((T.code s.pc).resize w).run _ s) ((M.code mid.pc).run _ mid)
+ rw [hp, hc, row, Fin.lastCases_last, body_resize]
+ apply body_action _ _ _ _ ha
+ exact ⟨fun i => (hr (D.reg i) (D.reg_unit i) (D.reg_acc i)).trans (rel.1.reg i),
+ hm.trans rel.1.privateMem, hs.trans rel.1.persistent,
+ fun i hi => (hr i hi.1 hi.2.1).trans (rel.1.frame i hi)⟩
+
+/-- Nonterminal traces insert the constant block's local ticks before each source event. -/
+def padded (pad : ℕ) : List (Event w) → List (Event w)
+ | [] => []
+ | e :: es => List.replicate pad .tick ++ e :: padded pad es
+
+end PairSimulation.InlinePublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationInlineSegment.lean b/lean/OAI/Computability/VPVNP/PairSimulationInlineSegment.lean
new file mode 100644
index 0000000000..8eed4f463c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationInlineSegment.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PairSimulationInlinePrefix
+import OAI.Computability.VPVNP.PairVertexImage
+
+/-!
+# Installing a lowered native table in the final-vertex image
+
+Accepting source exits point directly to the caller's continuation. A failing source
+exit addresses a native rejecting opcode. The interior of each block is the width-two
+static-bank compiler, widened to the literal format of the enclosing vertex image.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.InlinePublic
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {p r k P R K w : ℕ}
+
+/-- The source table's allocated code and register ranges. -/
+abbrev blockCount (T : Template p r k) (bank : Fin k → ℕ) := p * (capacity T bank + 3)
+
+private def success {v : ℕ} : Instr v p r k → Bool
+ | .accept => true
+ | _ => false
+
+/-- Every successful source exit uses the caller's continuation label. -/
+def linkedPlacement (T : Template p r k) (bank : Fin k → ℕ)
+ (loc : Fin (blockCount T bank) → Fin P) (reg : Fin (r + 2) ↪ Fin R) (done : Fin P) :
+ Placement (capacity T bank) p r P R :=
+ (embedding (capacity T bank) p r loc reg).withExits fun j =>
+ if success (T.code j) then some done else none
+
+/-- Every register outside the physical local bank belongs to the caller frame. -/
+theorem linked_privateReg (T : Template p r k) (bank : Fin k → ℕ)
+ (loc : Fin (blockCount T bank) → Fin P) (reg : Fin (r + 2) ↪ Fin R) (done : Fin P)
+ {i : Fin R} (outside : i ∉ Set.range reg) :
+ (linkedPlacement T bank loc reg done).privateReg i :=
+ ⟨fun h => outside ⟨_, h.symm⟩, fun h => outside ⟨_, h.symm⟩,
+ fun ⟨_, h⟩ => outside ⟨_, h⟩⟩
+
+theorem success_entry (T : Template p r k) (bank : Fin k → ℕ)
+ (loc : Fin (blockCount T bank) → Fin P) (reg : Fin (r + 2) ↪ Fin R) (done : Fin P)
+ {j : Fin p} (hj : T.code j = .accept) :
+ (linkedPlacement T bank loc reg done).entry j = done := by
+ simp [linkedPlacement, hj, success]
+
+private theorem code_at {T : Template p r k} {bank : Fin k → ℕ}
+ {loc : Fin (blockCount T bank) → Fin P} {reg : Fin (r + 2) ↪ Fin R} {done : Fin P}
+ {j : Fin p} (hn : success (T.code j) = false) (t : Fin (capacity T bank + 3)) :
+ (linkedPlacement T bank loc reg done).pc j t = loc (finProdFinEquiv (j, t)) := by
+ by_cases he : t = 0
+ · subst t
+ simp [linkedPlacement, Placement.withExits, hn, Placement.entry, embedding, canonical]
+ · simp [linkedPlacement, Placement.withExits, he, embedding, canonical]
+
+/-- The table rows are physically consecutive in the local label bank. The unreachable
+accept rows also transfer to the caller when entered directly. -/
+def linkedRows (T : Template p r k) (bank : Fin k → ℕ)
+ (loc : Fin (blockCount T bank) → Fin P) (reg : Fin (r + 2) ↪ Fin R) (done : Fin P)
+ (a : Fin (blockCount T bank)) : Instr 2 P R K :=
+ let jt := finProdFinEquiv.symm a
+ let D := linkedPlacement T bank loc reg done
+ match T.code jt.1 with
+ | .accept => .jumpEq D.acc D.acc done done
+ | .reject => .reject
+ | _ => row T bank D jt.1 jt.2
+
+/-- Every nonterminal row of the physically installed array satisfies the native
+prefix theorem's code hypothesis. -/
+theorem contains_linkedRows (T : Template p r k) (bank : Fin k → ℕ)
+ (loc : Fin (blockCount T bank) → Fin P) (reg : Fin (r + 2) ↪ Fin R) (done : Fin P)
+ (M : Machine w P R K)
+ (installed : ∀ a, M.code (loc a) = (linkedRows T bank loc reg done a).resize w)
+ (j : Fin p) (live : continues (T.code j) = true) :
+ ContainsAt M T bank (linkedPlacement T bank loc reg done) j := by
+ have hs : success (T.code j) = false := by
+ cases he : T.code j <;> first | rfl | simp [he, continues] at live
+ intro t
+ rw [code_at hs, installed]
+ simp only [linkedRows, Equiv.symm_apply_apply]
+ cases he : T.code j <;> first | rfl | simp [he, continues] at live
+
+theorem rejecting_entry (T : Template p r k) (bank : Fin k → ℕ)
+ (loc : Fin (blockCount T bank) → Fin P) (reg : Fin (r + 2) ↪ Fin R) (done : Fin P)
+ (M : Machine w P R K)
+ (installed : ∀ a, M.code (loc a) = (linkedRows T bank loc reg done a).resize w)
+ {j : Fin p} (hj : T.code j = .reject) :
+ M.code ((linkedPlacement T bank loc reg done).entry j) = .reject := by
+ unfold Placement.entry
+ rw [code_at (by rw [hj]; rfl), installed]
+ simp [linkedRows, hj, Instr.resize]
+
+private theorem resize_image (op : Instr 2 P R K) : (op.resize 5).resize w = op.resize w := by
+ cases op <;> try rfl
+ case constant dst val next => simp only [Instr.resize, resize_literal (by decide : 2 ≤ 5)]
+
+/-- The fixed public table occupies a native vertex segment with its own two scratch
+registers. The DFS registers and saved bootstrap registers can be framed by the caller. -/
+def segment (T : Template p r k) (bank : Fin k → ℕ) : VertexImage.Segment where
+ count := blockCount T bank
+ privateRegs := r + 2
+ entry := finProdFinEquiv (T.entry, (0 : Fin (capacity T bank + 3)))
+ row loc _ _ reg done a := (linkedRows T bank loc reg done a).resize 5
+
+theorem segment_entry (T : Template p r k) (bank : Fin k → ℕ)
+ (loc : Fin (blockCount T bank) → Fin P) (reg : Fin (r + 2) ↪ Fin R) (done : Fin P)
+ (entryLive : continues (T.code T.entry) = true) :
+ (linkedPlacement T bank loc reg done).entry T.entry = loc (segment T bank).entry := by
+ apply code_at
+ cases he : T.code T.entry <;> first | rfl | simp [he, continues] at entryLive
+
+/-- Extract the installed width-two rows from the actual five-bit image. -/
+theorem segment_rows (T : Template p r k) (bank : Fin k → ℕ)
+ (loc : Fin (blockCount T bank) → Fin P) (dfs : Fin 9 ↪ Fin R)
+ (saved : VertexImage.Saved ↪ Fin R) (reg : Fin (r + 2) ↪ Fin R) (done : Fin P)
+ (M : Machine w P R 11)
+ (installed : ∀ a, M.code (loc a) =
+ ((segment T bank).row loc dfs saved reg done a).resize w) (a : Fin (blockCount T bank)) :
+ M.code (loc a) = (linkedRows T bank loc reg done a).resize w :=
+ (installed a).trans (resize_image _)
+
+end PairSimulation.InlinePublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationKernels.lean b/lean/OAI/Computability/VPVNP/PairSimulationKernels.lean
new file mode 100644
index 0000000000..dca3588d8d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationKernels.lean
@@ -0,0 +1,189 @@
+import OAI.Computability.VPVNP.PairSimulationHistory
+import OAI.Computability.VPVNP.ShrinkMonomialWitness
+import OAI.Computability.VPVNP.DegreeRefreshEntries
+import OAI.Computability.VPVNP.StatePassHistory
+
+/-!
+# Binary readers at the two compression kernels
+
+The shrinking kernel reads a separate word for each locally absorbed edge
+and traverses all six-party entries resident at the site. The degree refresh
+tests its diagonal segments and evaluates a single entry. The fixed motif
+evaluator produces the ordered list of parameter names even before scalar
+specialization.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords MotifGrid MotifBlocks MotifConversion MotifDemandPadding MotifSelector
+
+section Motif
+
+variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+ {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+ (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+
+/-- The metered entry interpreter returns the exact parameter list, including
+repeated labels and the empty success at zero repetitions. -/
+theorem runEntry_list [DecidableEq J] (hp : ∀ i, 0 < p i) (w : D → ℕ) (v : S → ℕ)
+ (j : J) (x : HalfBits a b w j) (y : Half P (fun e => Word (supplyWidths B w v e)) j) :
+ (runEntry B hp w v j (MotifEntry.demandBits a b j x)
+ (mapHalf P (fun _ => MotifEntry.inputBits) y)).1 = (entry B hp w v j x y).map List.ofFn := by
+ unfold runEntry entry
+ erw [MotifEntry.run_value]
+ unfold MotifEntry.describe MotifEntry.labels
+ erw [MotifEntry.indices_eq_groupedIndices (u := repetitions B w) P (basePayload B) (selectorTable B) (fun s => by simp [selectorTable])]
+ simp_rw [MotifEntry.demandFields_eq a b (demand_le B hp w)]
+ rw [Option.map_map]
+ rfl
+
+variable {R : Type*} [CommRing R] {Label : Type} [Fintype Label] (κ : Label → R)
+
+/-- The executable check branches only on the output of the interpreter. -/
+def listedEntryReader {u : ℕ} (idx : Option (Fin u → Label)) (names : Option (List Label))
+ (hn : names = idx.map List.ofFn) : ChoiceReader (entryWitness κ idx).Choice :=
+ let raw : ChoiceReader (if names.isSome then Unit else Empty) := by
+ split <;> first | exact accept | exact reject
+ have h : (if names.isSome then Unit else Empty) = (entryWitness κ idx).Choice := by
+ cases idx <;> subst names <;> rfl
+ raw.reindex (Equiv.cast h)
+
+theorem listedEntryReader_length {u : ℕ} (idx : Option (Fin u → Label)) (names : Option (List Label))
+ (hn : names = idx.map List.ofFn) (x : (entryWitness κ idx).Choice) :
+ ((listedEntryReader κ idx names hn).encode x).length = 0 := by
+ cases idx with
+ | none => exact x.elim
+ | some t => subst names; rfl
+
+/-- Check a party's motif entry on the supplied demand and supply halves. The interpreter's
+optional parameter list determines rejection or a unique zero-bit choice. -/
+noncomputable def motifEntryReader [DecidableEq J] (κ : (parameterData B).Entry → R) (hp : ∀ i, 0 < p i)
+ (w : D → ℕ) (v : S → ℕ) (j : J) (x : HalfBits a b w j) (y : Half P (fun e => Word (supplyWidths B w v e)) j) :
+ ChoiceReader (entryWitness κ (entry B hp w v j x y)).Choice :=
+ listedEntryReader κ _ _ (runEntry_list B hp w v j x y)
+
+end Motif
+
+section Shrink
+
+open Compression Compression.PackingData Compression.ShrinkMotif WireTensor
+open scoped Classical
+
+variable {V H Tag L : Type} {d c d' pad : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+ [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+ [DecidableEq V] [DecidableEq Tag] [DecidableEq L] (P : PackingData V H Tag L d c)
+ (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering) (order : P.ThickNumbering)
+ (w : Arc V H Tag L d c → ℕ) {next : Equiv.Perm (V × Tag)}
+ {k R : Type*} [Field k] [CommRing R] {H' δ : ℝ}
+ (B : FixedBlock k demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) (31 / 16) H')
+ (κ : (parameterData B).Entry → R) (hκ : (parameterData B).IsSolution κ)
+ (ready : Ready d c d' δ) (I : ∀ l : Bool, P.ShrinkIndex l (subdivisions d c d') next d' pad)
+ (s : ∀ m, P.ShrinkChoice number w B m)
+
+/-- The shrinking choice is parsed from absorbed words followed by resident
+map checks on the selected layout's sliced old and new indices. -/
+noncomputable def shrinkReader
+ (owners : ∀ v, Order {e // v = P.shrinkInternalOwner (P.shrinkTermLayout B number w s) e})
+ (maps : ∀ v, Order {p : P.Motif × Fin 6 // P.shrinkPartySite (P.shrinkTermLayout B number w s) p.1 p.2 = v})
+ (v a z) :
+ ChoiceReader (P.shrinkKernelWitness hc hd number order w B κ hκ ready I s v a z).Choice :=
+ let l := P.shrinkTermLayout B number w s
+ let widths := fun m => P.shrinkSupplyWidths number w B m (s m)
+ let sd := subdivisions d c d'
+ let T := P.shrinkLayout hc hd number order w l sd widths (I l) ready.count_pos
+ (fun m => P.shrinkMap number w B κ m (s m))
+ let W := P.shrinkLayoutEntryWitness hc hd number order w l sd widths (I l) ready.count_pos
+ (fun m => P.shrinkMap number w B κ m (s m)) (fun m j x y =>
+ entryWitness κ (entry B demandMass_pos (P.shrinkDemandWidths number w m) (s m).val j x y))
+ layoutReader T W (fun e => ChoiceReader.bounded (widths e.1 (!l,e.2)) _ le_rfl) owners
+ (fun v a h z => (maps v).reader fun r =>
+ motifEntryReader B κ demandMass_pos (P.shrinkDemandWidths number w r.1.1) (s r.1.1).val r.1.2
+ (P.shrinkLocalDemandArg hc hd number order w l r.1.1 r.1.2 (r.2.symm ▸ a))
+ (P.shrinkLocalSupplyArg l sd widths (I l) ready.count_pos r.1.1 r.1.2 (r.2.symm ▸ h) (r.2.symm ▸ z)))
+ v a z
+
+/-- The local matrix checks consume no private bits. The only guessed bits
+of the shrinking kernel are the absorbed words, each at its declared width. -/
+theorem shrinkReader_length
+ (owners : ∀ v, Order {e // v = P.shrinkInternalOwner (P.shrinkTermLayout B number w s) e})
+ (maps : ∀ v, Order {p : P.Motif × Fin 6 // P.shrinkPartySite (P.shrinkTermLayout B number w s) p.1 p.2 = v})
+ (v a z) (x : (P.shrinkKernelWitness hc hd number order w B κ hκ ready I s v a z).Choice) :
+ ((shrinkReader P hc hd number order w B κ hκ ready I s owners maps v a z).encode x).length =
+ ∑ e : {e // v = P.shrinkInternalOwner (P.shrinkTermLayout B number w s) e},
+ P.shrinkSupplyWidths number w B e.1.1 (s e.1.1) (!(P.shrinkTermLayout B number w s),e.1.2) := by
+ unfold shrinkReader layoutReader
+ change List.length ((_ : List Bool) ++ _) = _
+ rw [List.length_append]
+ erw [fiber_length, Order.reader_length]
+ simp only [motifEntryReader, listedEntryReader_length, Finset.sum_const_zero, Nat.add_zero,
+ ChoiceReader.bounded, PrimedCounter.digits, BurstRAM.length_wordBits]
+ congr 1
+
+end Shrink
+
+section Refresh
+
+open Compression Compression.Refresh SpectralGeometry Compression.DegreeRefresh
+open scoped Classical
+
+variable {k : Type*} [Field k] {D dH d₀ : ℕ} {K K' : ℝ}
+ {V E L : Type} [Fintype V] [Fintype E] [Fintype L] [AddCommGroup E] [AddCommGroup L]
+ (G : Compression.LiftedSlots V D (E × L)) (port : E ≃ Fin D) (w : (V × Fin D) × (E × L) → ℕ)
+ (P : RegularArcGraph (Fin D) dH) (hdH : 0 < dH) (hconn : (arcSupportGraph P.multiplicity).Connected)
+ (F : FixedBlock k tieSource tieTarget (expanderSupply P hdH hconn)
+ (realWidths tieMass) (realWidths (expanderMass d₀)) K K')
+ (hD : 1 < D) (hd : dH + 1 ≤ d₀) (c : BlockChoices G port w P hdH hconn F)
+ {R : Type*} [CommRing R] [Fintype (parameterData F).Entry]
+ (κ : (parameterData F).Entry → R) (hκ : (parameterData F).IsSolution κ)
+
+/-- Run the same two external-segment tests as the refresh map, then
+interpret the selected motif on its actual demand and supply arguments. -/
+noncomputable def refreshNames (v : (V × Fin D) × L)
+ (a : Placed (refreshPositions port) (actualWireGraph G w).Half v)
+ (z : (expanderBranchGraph G port w P hdH hconn F hD hd c).Half v) : Option (List (parameterData F).Entry) :=
+ let p := promotedSites.symm v
+ let t := oldPortMatching G port
+ let widths := groupedWidths port w
+ let dst := bundleTarget G
+ let n := blockSupplyWidths G port w P hdH hconn F c
+ let C := fun s e ↦ Fin (2 ^ n s e)
+ let old := originalIso G port w
+ let new := promotedIso G port w P.toSlotGraph hD hd C n (fun s e ↦ (wordIndex (n s e)).symm)
+ let x := old.pullHalf p (a (originalSites port p) (by simp [p, originalSites, promotedSites, refreshPositions]))
+ let u := new.pullHalf p z
+ let seg := incidentPortSegments t dst (oldPortMatching_bundle G port) widths p
+ (u.1 (.inl p) rfl) (u.2 (.inl (dst.symm p)) (dst.apply_symm_apply p).symm)
+ let y := supplyHalf (R := ℤ) dst widths Prod.fst (fun e ↦ (P.reverse e).1) C (d₀ - (dH + 1)) p u
+ if x.1 ((p.1,p.2),p.2) rfl = seg.1 p.2 ∧
+ seg.2 p.2 = incomingHalf (R := ℤ) t widths p.1 p.2 p.2 x then
+ (runEntry F (fun _ ↦ zero_lt_one) (blockDemandWidths G port w p.1) (c p.1).val p.2
+ (MotifEntry.demandBits _ _ p.2 (portInput (R := ℤ) t widths p.1 p.2 x seg))
+ (mapHalf _ (fun _ => MotifEntry.inputBits) y)).1
+ else none
+
+omit [Fintype (parameterData F).Entry] in
+theorem refreshNames_spec (v a z) :
+ refreshNames G port w P hdH hconn F hD hd c v a z =
+ (refreshEntryIndices G port w P hdH hconn F hD hd c (promotedSites.symm v) a z).map List.ofFn := by
+ unfold refreshNames refreshEntryIndices
+ dsimp only
+ split_ifs
+ · exact runEntry_list ..
+ · rfl
+
+/-- At a refreshed port the two ties and the entry checks determine its
+choice entirely from the arguments already supplied by the descriptor. -/
+noncomputable def refreshReader (v a z) :
+ ChoiceReader (expanderKernelWitness G port w P hdH hconn F hD hd c κ hκ v a z).Choice :=
+ listedEntryReader κ _ _ (refreshNames_spec G port w P hdH hconn F hD hd c v a z)
+
+end Refresh
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafAddress.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafAddress.lean
new file mode 100644
index 0000000000..237c4cccc9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafAddress.lean
@@ -0,0 +1,366 @@
+import OAI.Computability.VPVNP.LiveAuxiliaryHeaderPreparation
+import OAI.Computability.VPVNP.PrimedCounterData
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+import OAI.Computability.VPVNP.PairSimulationLeafCoordinates
+
+/-!
+# The native leaf address and auxiliary header reader
+
+The descriptor address on the depth-first stack identifies a row in the initial
+cursor layout. The reader divides out the row stride, recovers the cursor and
+the two blocks of address bits, and reads the complete auxiliary header word.
+Beyond the prepared shadow region it supplies zero without probing memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafAddress
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Registers for dividing a DFS node address into its row index, cursor and site, then loading
+the site's auxiliary header word. -/
+inductive Reg where
+ | node | tmp | idx | low | site | cursor | addr | zero | header
+ deriving DecidableEq
+
+instance : Fintype Reg :=
+ ⟨{.node,.tmp,.idx,.low,.site,.cursor,.addr,.zero,.header}, fun i => by cases i <;> decide⟩
+
+/-- The row base and stride, two coordinate radices, and shadow base and span consumed by the
+leaf address decoder. -/
+inductive Field where
+ | base | stride | radixB | radixL | shadow | span
+ deriving DecidableEq
+
+instance : Fintype Field :=
+ ⟨{.base,.stride,.radixB,.radixL,.shadow,.span}, fun i => by cases i <;> decide⟩
+
+/-- Decode the two coordinates with the arithmetic of the host's word width. -/
+def decode (node base stride radixB radixL : Word w) : Word w × Word w :=
+ let idx := BinaryOp.div.eval (node-base) stride
+ let high := BinaryOp.mod.eval idx radixL
+ let cb := BinaryOp.div.eval idx radixL
+ let low := BinaryOp.mod.eval cb radixB
+ let cursor := BinaryOp.div.eval cb radixB
+ (cursor, low+high*radixB)
+
+theorem decode_packed {w : ℕ} (node base stride radixB radixL : Word w)
+ {cursor low high : ℕ}
+ (hnode : base.val + stride.val * ((cursor * radixB.val + low) * radixL.val + high) = node.val)
+ (hs : 0 < stride.val) (hb : low < radixB.val) (hl : high < radixL.val)
+ (hsite : low + high * radixB.val < 2^w) :
+ (decode node base stride radixB radixL).1.val = cursor ∧
+ (decode node base stride radixB radixL).2.val = low + high * radixB.val := by
+ have divVal (x y : Word w) : (BinaryOp.div.eval x y).val = x.val / y.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)
+ have modVal (x y : Word w) : (BinaryOp.mod.eval x y).val = x.val % y.val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt)
+ have divPacked (q : ℕ) {d t : ℕ} (ht : t < d) : (q * d + t) / d = q := by
+ rw [Nat.mul_comm q, Nat.mul_add_div ((Nat.zero_le t).trans_lt ht), Nat.div_eq_of_lt ht, Nat.add_zero]
+ have hbase : base ≤ node := show base.val ≤ node.val by omega
+ have hidx : (node - base).val / stride.val = (cursor * radixB.val + low) * radixL.val + high := by
+ rw [Fin.sub_val_of_le hbase, ← hnode, Nat.add_sub_cancel_left, Nat.mul_div_cancel_left _ hs]
+ simp only [decode, divVal, modVal, hidx, divPacked _ hl, divPacked _ hb,
+ Nat.mul_add_mod_of_lt hl, Nat.mul_add_mod_of_lt hb, Fin.val_add, Fin.val_mul,
+ Nat.mod_eq_of_lt (show high * radixB.val < 2^w by omega), Nat.mod_eq_of_lt hsite, and_self]
+
+section Geometry
+
+open CursorNetwork CursorRouting Compression LocalHistory TraversalRows
+
+/-- The native word decoder recovers both coordinates of the auxiliary processor
+from the physical address of its initial traversal row. -/
+theorem decode_leaf_row {W b l a p : ℕ} {S : Type} [Fintype S]
+ (hD : 1 < b + l) (hd : 2 + p = 2^a) (bits : S → ℕ) (cap : ℕ) (v : Position (b+l))
+ (node base stride radixB radixL : Word W) (hwidth : b+l ≤ W)
+ (hs : stride.val = cap+2) (hb : radixB.val = 2^b) (hl : radixL.val = 2^l)
+ (hnode : node.val = (sitePointers cap base.val
+ (siteOrder (cursorState (cursorCoordinateLabels b l) hD hd bits))
+ (lanePositions (cursorCoordinateLabels b l) v)).1) :
+ (decode node base stride radixB radixL).1.val = v.1.val ∧
+ (decode node base stride radixB radixL).2.val = v.2.val := by
+ let u := lanePositions (cursorCoordinateLabels b l) v
+ let low := (bitWordFinEquiv b u.1.2).val
+ let high := (bitWordFinEquiv l u.2).val
+ obtain ⟨hrow, hsite⟩ := LeafCoordinates.leaf_row hD hd bits base.val cap v
+ have ha : base.val + stride.val * ((v.1.val * radixB.val + low) * radixL.val + high) = node.val := by
+ rw [hnode, hs, hb, hl]
+ exact hrow.symm
+ have hv : low + high * radixB.val = v.2.val := by
+ rw [hb, Nat.mul_comm, Nat.add_comm]
+ exact hsite.symm
+ have pair := decode_packed node base stride radixB radixL ha (by omega)
+ (hb ▸ (bitWordFinEquiv b u.1.2).isLt) (hl ▸ (bitWordFinEquiv l u.2).isLt)
+ (hv ▸ v.2.isLt.trans_le (Nat.pow_le_pow_right (by decide) hwidth))
+ exact ⟨pair.1, pair.2.trans hv⟩
+
+end Geometry
+
+/-- Both exits receive the cursor, site, and header. The node register is read-only. -/
+def instruction (pc : Fin 20 → Fin p) (reg : Reg ↪ Fin r) (pub : Field → Fin k)
+ (launch transit : Fin p) : Fin 20 → Instr w p r k :=
+ ![.publicWord (reg .tmp) (pub .base) (pc 1),
+ .binary .sub (reg .idx) (reg .node) (reg .tmp) (pc 2),
+ .publicWord (reg .tmp) (pub .stride) (pc 3),
+ .binary .div (reg .idx) (reg .idx) (reg .tmp) (pc 4),
+ .publicWord (reg .tmp) (pub .radixL) (pc 5),
+ .binary .mod (reg .site) (reg .idx) (reg .tmp) (pc 6),
+ .binary .div (reg .idx) (reg .idx) (reg .tmp) (pc 7),
+ .publicWord (reg .tmp) (pub .radixB) (pc 8),
+ .binary .mod (reg .low) (reg .idx) (reg .tmp) (pc 9),
+ .binary .div (reg .cursor) (reg .idx) (reg .tmp) (pc 10),
+ .binary .mul (reg .site) (reg .site) (reg .tmp) (pc 11),
+ .binary .add (reg .site) (reg .low) (reg .site) (pc 12),
+ .publicWord (reg .tmp) (pub .shadow) (pc 13),
+ .binary .add (reg .addr) (reg .tmp) (reg .site) (pc 14),
+ .publicWord (reg .tmp) (pub .span) (pc 15),
+ .constant (reg .zero) 0 (pc 16),
+ .jumpLt (reg .site) (reg .tmp) (pc 17) (pc 18),
+ .readExternal (reg .header) (reg .addr) (pc 19),
+ .constant (reg .header) 0 (pc 19),
+ .jumpEq (reg .cursor) (reg .zero) launch transit]
+
+theorem resize_instruction (pc : Fin 20 → Fin p) (reg : Reg ↪ Fin r) (pub : Field → Fin k)
+ (launch transit : Fin p) (i : Fin 20) :
+ (instruction (w := 1) pc reg pub launch transit i).resize w =
+ instruction pc reg pub launch transit i := by fin_cases i <;> rfl
+
+/-- The machine contains all 20 decoder instructions at the assigned labels, with the specified
+register placement, operands, and launch and transit continuations. -/
+def Linked (M : Machine w p r k) (pc : Fin 20 → Fin p) (reg : Reg ↪ Fin r) (pub : Field → Fin k)
+ (launch transit : Fin p) : Prop := ∀ i, M.code (pc i) = instruction pc reg pub launch transit i
+
+/-- Every register except the eight scratch slots is preserved, including the DFS node. -/
+def Preserved (reg : Reg ↪ Fin r) (a : Fin r) : Prop := ∀ i, i ≠ .node → a ≠ reg i
+
+theorem preserved_node (reg : Reg ↪ Fin r) : Preserved reg (reg .node) :=
+ fun _ h => reg.injective.ne h.symm
+
+variable {M : Machine w p r k} {pc : Fin 20 → Fin p} {reg : Reg ↪ Fin r} {pub : Field → Fin k}
+ {launch transit : Fin p}
+
+private theorem step_at (hl : Linked M pc reg pub launch transit) (i : Fin 20) {c : Config w p r}
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg pub launch transit i).run M.publicData c := by
+ change (M.code c.pc).run _ _ = _
+ rw [hc,hl]
+
+/-- The address arithmetic, including the bounds-test operands, occupies the first sixteen slots. -/
+private theorem head_native (hl : Linked M pc reg pub launch transit)
+ (c : Config w p r) (entry : c.pc = pc 0) :
+ let f := M.publicData ∘ pub
+ let coord := decode (c.reg (reg .node)) (f .base) (f .stride) (f .radixB) (f .radixL)
+ ∃ q, Prefix M c (List.replicate 16 .tick) q ∧ q.pc = pc 16 ∧
+ q.reg (reg .cursor) = coord.1 ∧ q.reg (reg .site) = coord.2 ∧
+ q.reg (reg .addr) = f .shadow + coord.2 ∧ q.reg (reg .tmp) = f .span ∧ q.reg (reg .zero) = 0 ∧
+ (∀ a, Preserved reg a → q.reg a = c.reg a) ∧ q.privateMem = c.privateMem ∧ q.persistent = c.persistent := by
+ dsimp only
+ refine ⟨_, .tick (step_at hl 0 entry) (.tick (step_at hl 1 rfl) (.tick (step_at hl 2 rfl)
+ (.tick (step_at hl 3 rfl) (.tick (step_at hl 4 rfl) (.tick (step_at hl 5 rfl)
+ (.tick (step_at hl 6 rfl) (.tick (step_at hl 7 rfl) (.tick (step_at hl 8 rfl)
+ (.tick (step_at hl 9 rfl) (.tick (step_at hl 10 rfl) (.tick (step_at hl 11 rfl)
+ (.tick (step_at hl 12 rfl) (.tick (step_at hl 13 rfl) (.tick (step_at hl 14 rfl)
+ (.tick (step_at hl 15 rfl) (.nil _)))))))))))))))), rfl, ?_, ?_, ?_, ?_, ?_, ?_, rfl, rfl⟩
+ all_goals first | (solve | simp [Config.put, decode, Function.update_apply, reg.injective.eq_iff, BinaryOp.eval]) | skip
+ intro a ha
+ simp [Config.put, Function.update_of_ne (ha .tmp (by decide)),
+ Function.update_of_ne (ha .idx (by decide)), Function.update_of_ne (ha .site (by decide)),
+ Function.update_of_ne (ha .low (by decide)), Function.update_of_ne (ha .cursor (by decide)),
+ Function.update_of_ne (ha .addr (by decide)), Function.update_of_ne (ha .zero (by decide))]
+
+/-- The sole possible probe is issued at the translated physical address. -/
+def events (m : Memory w) (shadow span site : Word w) : List (Event w) :=
+ let a := shadow+site
+ List.replicate 17 .tick ++ [if site < span then .read a (m a.val) else .tick, .tick]
+
+/-- Read the site's word at the shadow base plus its index. Return zero when the index reaches
+or exceeds the prepared span. -/
+def header (m : Memory w) (shadow span site : Word w) : Word w :=
+ if site < span then m (shadow+site).val else 0
+
+theorem cost (m : Memory w) (shadow span site : Word w) :
+ (events m shadow span site).length = 19 ∧
+ countProbes (events m shadow span site) = (decide (site < span)).toNat ∧
+ choiceBits (events m shadow span site) = [] := by
+ by_cases h : site < span <;> simp only [events, h, decide_true, decide_false, ↓reduceIte] <;>
+ exact ⟨rfl,rfl,rfl⟩
+
+/-- Every continuation receives the original bit suffix and external memory, the decoded
+coordinates and the complete word, after the nineteen indicated instructions. -/
+theorem native (hl : Linked M pc reg pub launch transit) (m : Memory w)
+ (c : Config w p r) (entry : c.pc = pc 0) :
+ let f := M.publicData ∘ pub
+ let coord := decode (c.reg (reg .node)) (f .base) (f .stride) (f .radixB) (f .radixL)
+ ∃ d, d.pc = (if coord.1 = 0 then launch else transit) ∧
+ d.reg (reg .cursor) = coord.1 ∧ d.reg (reg .site) = coord.2 ∧
+ d.reg (reg .header) = header m (f .shadow) (f .span) coord.2 ∧
+ (∀ a, Preserved reg a → d.reg a = c.reg a) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ fuel bs, execute M.program (fuel + 19) c m bs =
+ (execute M.program fuel d m bs).map fun t => ⟨events m (f .shadow) (f .span) coord.2 ++ t.events,t.result⟩ := by
+ intro f coord
+ obtain ⟨q, pre, hpc, hcur, hsite, haddr, hspan, hzero, frame, mem, per⟩ := head_native hl c entry
+ let atLoad := {q with pc := if coord.2 < f .span then pc 17 else pc 18}
+ let value := header m (f .shadow) (f .span) coord.2
+ let loaded := atLoad.put (pc 19) (reg .header) value
+ let d := {loaded with pc := if coord.1 = 0 then launch else transit}
+ have bounds : M.program.step q = .localStep atLoad := by
+ rw [step_at hl 16 hpc]
+ change CallAction.localStep {q with pc := if q.reg (reg .site) < q.reg (reg .tmp) then _ else _} = _
+ rw [hsite,hspan]
+ have dispatch : M.program.step loaded = .localStep d := by
+ rw [step_at hl 19 rfl]
+ change CallAction.localStep {loaded with pc := if loaded.reg (reg .cursor) = loaded.reg (reg .zero) then _ else _} = _
+ simp [loaded, atLoad, d, Config.put, hcur, hzero, coord, f]
+ refine ⟨d,rfl,?_,?_,by simp [d,loaded,value],?_,mem,per,?_⟩
+ · simpa [d,loaded,atLoad,Config.put,coord,f] using hcur
+ · simpa [d,loaded,atLoad,Config.put,coord,f] using hsite
+ · intro a ha
+ simpa [d,loaded,atLoad,Config.put,Function.update_of_ne (ha .header (by decide))] using frame a ha
+ · intro fuel bs
+ have headRun := pre.execute (fuel+3) m bs
+ change execute M.program ((fuel+3)+16) c m bs = _ at headRun
+ rw [show fuel+19 = (fuel+3)+16 by omega, headRun]
+ by_cases h : coord.2 < f .span
+ · have read : M.program.step atLoad =
+ .read (f .shadow+coord.2) (fun x => atLoad.put (pc 19) (reg .header) x) := by
+ rw [step_at hl 17 (by simp [atLoad,h])]
+ change CallAction.read (q.reg (reg .addr)) _ = _
+ rw [haddr]
+ have put : atLoad.put (pc 19) (reg .header) (m (f .shadow+coord.2).val) = loaded := by
+ simp [loaded,value,header,h]
+ simp only [execute, bounds, read, put, dispatch, Option.map_map, Function.comp_def, events, h, ↓reduceIte]
+ rfl
+ · have lit : M.program.step atLoad = .localStep loaded := by
+ rw [step_at hl 18 (by simp [atLoad,h])]
+ change CallAction.localStep (atLoad.put _ _ 0) = _
+ simp [loaded,value,header,h]
+ simp only [execute, bounds, lit, dispatch, Option.map_map, Function.comp_def, events, h, ↓reduceIte]
+ rfl
+
+
+section Header
+
+open PrimedInputRAM
+
+/-- The auxiliary header at physical width `W` returns the widened virtual word,
+including the complete nominated histogram and the zero padding. -/
+theorem headerMemory_widen {L : Lengths} {n r H w W s : ℕ} {Q : Layout L n r H w}
+ (D : PrimedCounter.Data Q s) (hw : 0 < w) (hwidth : w ≤ W) (j : ℕ) :
+ (headerMemory L D.header (D.hist.map (fun x => (x.val : Word W))) j).val = (D.initial j).val := by
+ have hbit (b : Bool) : encodeBit W b = ((encodeBit w b).val : Word W) := by
+ cases b <;> simp [encodeBit, Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')]
+ have hcut (i : Fin 3) : Fin.ofNat (2^W) (cutLength L i) = ((Fin.ofNat (2^w) (cutLength L i)).val : Word W) := by
+ rw [Fin.val_ofNat, Nat.mod_eq_of_lt (Q.cutLength_lt i), Fin.ofNat_eq_cast]
+ have eqWord : headerMemory L D.header (D.hist.map (fun x => (x.val : Word W))) j =
+ ((D.initial j).val : Word W) := by
+ unfold PrimedCounter.Data.initial headerMemory
+ dsimp only
+ split_ifs <;> first | apply hcut | apply hbit | simp [List.getElem?_map]
+ cases D.hist[j-Header.count L]? <;> rfl
+ rw [eqWord, Fin.val_natCast, Nat.mod_eq_of_lt ((D.initial j).isLt.trans_le
+ (Nat.pow_le_pow_right (by decide) hwidth))]
+
+/-- Running the live descriptor and copy calls establishes the shadow-memory
+hypothesis used by the leaf reader, including when the virtual width is smaller. -/
+theorem prepare_initial {L : Lengths} {n a H u s : ℕ} {Q : Layout L n a H u}
+ (D : PrimedCounter.Data Q s) (hu : 0 < u) (width : u ≤ w)
+ (src : Fin 7 → Word w) (table shadow : Word w) (m : Memory w)
+ (areas : LiveAuxiliaryHeaders.Areas table shadow L D.hist.length src)
+ (inputs : LiveAuxiliaryHeaders.InputArrays L D.header (D.hist.map (fun x => (x.val : Word w))) src m)
+ (fresh : ∀ a < LiveAuxiliaryHeaders.span L D.hist.length, m (shadow.val+a) = 0) :
+ let init := (LiveAuxiliaryHeaders.initTable.instantiate w
+ (LiveAuxiliaryHeaders.initData L D.hist.length shadow table src)).program
+ let ncopy := LiveAuxiliaryHeaders.populated L D.hist.length
+ ∃ es rs, execute init 79 (init.start 0) m [] = some ⟨es,none⟩ ∧
+ runSegment (LiveHeaderCopyDispatch.program table) 64 (some 0)
+ (after m es) (List.replicate ncopy []) = some rs ∧
+ ∀ a < LiveAuxiliaryHeaders.span L D.hist.length,
+ (after (after m es) (eventLog rs) (shadow.val+a)).val = (D.initial a).val := by
+ let hist := D.hist.map (fun x => (x.val : Word w))
+ have len : hist.length = D.hist.length := List.length_map _
+ obtain ⟨es,rs,he,hr,_,_,hm,_⟩ := LiveAuxiliaryHeaders.prepare_native L D.header hist
+ src table shadow m (len ▸ areas) inputs (len ▸ fresh)
+ refine ⟨es,rs,by simpa only [len] using he,by simpa only [len] using hr,?_⟩
+ intro a ha
+ rw [hm _ (len ▸ ha)]
+ exact headerMemory_widen D hu width a
+
+end Header
+
+section Geometry
+
+open PrimedInputRAM CursorNetwork CursorRouting Compression LocalHistory TraversalRows
+
+variable {L : Lengths} {n a H u s b l t j : ℕ} {Q : Layout L n a H u}
+variable {S : Type} [Fintype S]
+
+/-- The translated read agrees with the virtual auxiliary RAM at every address,
+including addresses beyond the histogram. -/
+theorem header_initial (D : PrimedCounter.Data Q s) (m : Memory w) (shadow limit site : Word w)
+ (hlimit : limit.val = LiveAuxiliaryHeaders.span L D.hist.length)
+ (fits : shadow.val + limit.val ≤ 2^w)
+ (prepared : ∀ i < limit.val, (m (shadow.val+i)).val = (D.initial i).val) :
+ (header m shadow limit site).val = (D.initial site.val).val := by
+ by_cases h : site < limit
+ · have less : site.val < limit.val := h
+ rw [header, ite_eq_left h, Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ exact prepared _ less
+ · have le : limit.val ≤ site.val := Nat.le_of_not_gt h
+ rw [header, ite_eq_right h, PrimedCounter.Data.initial,
+ LiveAuxiliaryHeaders.headerMemory_past_end _ _ _ (hlimit ▸ le)]
+ rfl
+
+/-- On the descriptor emitted for this cursor processor, the fixed native table
+enters the matching validator or transit routine with the entire auxiliary word.
+The shadow hypothesis is the memory postcondition of header preparation. -/
+theorem leaf_native (hl : Linked M pc reg pub launch transit) (m : Memory w)
+ (c : Config w p r) (entry : c.pc = pc 0) (D : PrimedCounter.Data Q s)
+ (hD : 1 < b+l) (hd : 2+j = 2^t) (bits : S → ℕ) (cap : ℕ) (v : Position (b+l))
+ (hwidth : b+l ≤ w) :
+ let f := M.publicData ∘ pub
+ (f .stride).val = cap+2 → (f .radixB).val = 2^b → (f .radixL).val = 2^l →
+ (c.reg (reg .node)).val = (sitePointers cap (f .base).val
+ (siteOrder (cursorState (cursorCoordinateLabels b l) hD hd bits))
+ (lanePositions (cursorCoordinateLabels b l) v)).1 →
+ (f .span).val = LiveAuxiliaryHeaders.span L D.hist.length →
+ (f .shadow).val + (f .span).val ≤ 2^w →
+ (∀ i < (f .span).val, (m ((f .shadow).val+i)).val = (D.initial i).val) →
+ ∃ d, d.pc = (if v.1.val = 0 then launch else transit) ∧
+ (d.reg (reg .cursor)).val = v.1.val ∧ (d.reg (reg .site)).val = v.2.val ∧
+ (d.reg (reg .header)).val = (D.initial v.2.val).val ∧
+ (∀ a, Preserved reg a → d.reg a = c.reg a) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ fuel bs, execute M.program (fuel + 19) c m bs =
+ (execute M.program fuel d m bs).map fun z =>
+ ⟨events m (f .shadow) (f .span) (v.2.val : Word w) ++ z.events,z.result⟩ := by
+ intro f hs hb hL hnode hspan fits ready
+ let coord := decode (c.reg (reg .node)) (f .base) (f .stride) (f .radixB) (f .radixL)
+ obtain ⟨hcur, hsite⟩ := decode_leaf_row hD hd bits cap v _ _ _ _ _ hwidth hs hb hL hnode
+ change coord.1.val = v.1.val at hcur
+ change coord.2.val = v.2.val at hsite
+ have heq : coord.1 = 0 ↔ v.1.val = 0 := by rw [Fin.ext_iff, Fin.val_zero,hcur]
+ have he : coord.2 = (v.2.val : Word w) := Fin.ext (hsite.trans (Nat.mod_eq_of_lt (hsite ▸ coord.2.isLt)).symm)
+ obtain ⟨d, hpc, hc, hv, hw, frame, mem, per, run⟩ := native hl m c entry
+ change d.pc = (if coord.1 = 0 then launch else transit) at hpc
+ change d.reg (reg .header) = header m (f .shadow) (f .span) coord.2 at hw
+ refine ⟨d,by simpa only [heq] using hpc, (congrArg Fin.val hc).trans hcur,
+ (congrArg Fin.val hv).trans hsite, ?_,frame,mem,per,?_⟩
+ · rw [hw, header_initial D _ _ _ _ hspan fits ready, hsite]
+ · intro fuel bs
+ rw [← he]
+ exact run fuel bs
+
+end Geometry
+
+end PairSimulation.LeafAddress
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafArena.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafArena.lean
new file mode 100644
index 0000000000..712ff77b89
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafArena.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.PairSimulationStackSpace
+import OAI.Computability.VPVNP.PairNodeArguments
+
+/-! # Private addresses of the cursor-leaf verifier -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafArena
+
+open NodeArguments StackMachine Filter BurstRAM
+
+/-- The node arguments occupy their full stride even at the last genuine
+descriptor. The histogram and further reserved scratch precede the cache
+of 38 virtual operands. Each verifier stack starts beyond the entire cache. -/
+structure Regions where
+ /-- The start and stride of the private argument frames indexed by descriptor node addresses. -/
+ arguments : Arena
+ /-- Exclusive upper bound on node indices with reserved argument frames. -/
+ nodes : ℕ
+ /-- Number of private words reserved for the histogram immediately after the node frames. -/
+ histWords : ℕ
+ /-- Number of additional scratch words reserved between the histogram and the operand cache. -/
+ otherWords : ℕ
+
+/-- First private histogram address, immediately following the last reserved node frame. -/
+def Regions.histBase (R : Regions) := R.arguments.base R.nodes
+/-- First private address for the cached auxiliary operands, after the histogram and its
+neighboring scratch interval. -/
+def Regions.cacheBase (R : Regions) := R.histBase + R.histWords + R.otherWords
+/-- First available private address for verifier stacks, immediately after the 38 cached
+operand words. -/
+def Regions.stackBase (R : Regions) := R.cacheBase + 38
+
+theorem Regions.node_before {R : Regions} {node : ℕ} (h : node < R.nodes) :
+ R.arguments.base node + R.arguments.stride ≤ R.histBase := R.arguments.before h
+
+theorem Regions.hist_before (R : Regions) : R.histBase + R.histWords ≤ R.cacheBase :=
+ Nat.le_add_right _ _
+
+theorem Regions.cache_before (R : Regions) (i : Fin 38) : R.cacheBase + i.val < R.stackBase := by
+ unfold stackBase; omega
+
+/-- Consecutive pointer slots of the actual virtual verifier's named-port
+table. All address widths and counts are runtime parameters. -/
+def Regions.layout {w ports : ℕ} {K : Type} (R : Regions) (order : K ↪ Fin ports) (capacity : ℕ)
+ (fits : R.stackBase + ports*capacity < 2^w) : Layout K w :=
+ Layout.consecutive order R.stackBase capacity fits
+
+theorem Regions.stack_above {w ports : ℕ} {K : Type} (R : Regions) (order : K ↪ Fin ports)
+ (capacity : ℕ) (fits : R.stackBase + ports*capacity < 2^w) (j : K) :
+ R.stackBase ≤ (R.layout order capacity fits).base j := Nat.le_add_right _ _
+
+theorem Regions.stack_above_dfs {w ports endAddr : ℕ} {K : Type} (R : Regions) (order : K ↪ Fin ports)
+ (capacity : ℕ) (fits : R.stackBase + ports*capacity < 2^w) (before : endAddr ≤ R.arguments.start)
+ (j : K) : endAddr ≤ (R.layout order capacity fits).base j := by
+ apply (le_trans _ (R.stack_above order capacity fits j))
+ unfold Regions.stackBase Regions.cacheBase Regions.histBase Arena.base
+ omega
+
+/-- Any fixed polynomial bound on the public descriptor addresses and
+stride gives a single threshold for the histogram, the operand cache,
+and all stacks with their verified capacity `n^40`. -/
+theorem eventually_fit {B : ℕ} (hB : 1 ≤ B) (ports offsetExp nodeExp strideExp histExp otherExp : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ R : Regions, R.arguments.start ≤ n^offsetExp → R.nodes ≤ n^nodeExp →
+ R.arguments.stride ≤ n^strideExp → R.histWords ≤ n^histExp → R.otherWords ≤ n^otherExp →
+ R.stackBase + ports*n^40 < 2^CursorBounds.wordBits B n := by
+ let e := max offsetExp (max (nodeExp+strideExp) (max histExp otherExp))
+ filter_upwards [eventually_ge_atTop 42,eventually_port_space hB ports (e+1) 40] with n hn space
+ intro R hs hnodes hstride hh ho
+ have hn₁ : 1 ≤ n := by omega
+ have mono {i : ℕ} (h : i ≤ e) := Nat.pow_le_pow_right hn₁ h
+ have start := hs.trans (mono (le_max_left ..))
+ have prod : R.nodes*R.arguments.stride ≤ n^e := calc
+ _ ≤ n^nodeExp*n^strideExp := Nat.mul_le_mul hnodes hstride
+ _ = n^(nodeExp+strideExp) := (Nat.pow_add ..).symm
+ _ ≤ _ := mono ((le_max_left ..).trans (le_max_right ..))
+ have hH := hh.trans (mono ((le_max_left ..).trans ((le_max_right ..).trans (le_max_right ..))))
+ have hO := ho.trans (mono ((le_max_right ..).trans ((le_max_right ..).trans (le_max_right ..))))
+ apply space R.stackBase (n^40) _ le_rfl
+ unfold Regions.stackBase Regions.cacheBase Regions.histBase Arena.base
+ have hp := Nat.one_le_pow e n hn₁
+ have hb : 42*n^e ≤ n^(e+1) := by rw [pow_succ']; exact Nat.mul_le_mul_right _ hn
+ omega
+
+end PairSimulation.LeafArena
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafArguments.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafArguments.lean
new file mode 100644
index 0000000000..3f5c88cf61
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafArguments.lean
@@ -0,0 +1,243 @@
+import OAI.Computability.VPVNP.PairNodeArguments
+import OAI.Computability.VPVNP.CompressorRecordsCursorCoordinates
+import OAI.Computability.VPVNP.SlotDemandSlices
+import Mathlib.Data.Fin.Tuple.Take
+
+/-!
+# The four actual argument vectors at a cursor leaf
+
+Outgoing slot zero is the stay arc and slot one is the flip arc. The
+incoming slots retain these same numbers at their destinations. Each
+genuine arc concatenates the successor fields and then the sorting
+fields in the order used by the validator. The dummy arcs have width
+zero, so the four vectors occupy four consecutive private intervals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafArguments
+
+open Compression CursorNetwork CursorRouting RAMLayout RAMSort NodeArguments LocalHistory
+open scoped Classical Fin.CommRing
+
+variable {D H w : ℕ}
+
+/-- Width of the numerical system column in the padded cursor arc. -/
+private theorem column_width (j : Fin (D + layerCount D)) :
+ ramFieldBits H w ((ramSystemOrder D).symm j) = if j.val < D then 8*w else blockBits H w := by
+ obtain ⟨s,rfl⟩ := (ramSystemOrder D).surjective j
+ rw [Equiv.symm_apply_apply]
+ cases s with
+ | inl i =>
+ change 8*w = if i.val < D then _ else _
+ rw [ite_eq_left i.isLt]
+ | inr l =>
+ change blockBits H w = if D + l.ordinal.val < D then _ else _
+ rw [ite_eq_right (by omega)]
+
+/-- Compression and the site validator number every bit of the actual
+message systems identically. -/
+theorem ordered_ram_offset (s : RAMSystem D) (i : Fin (ramFieldBits H w s)) :
+ (PackingData.orderedBits (ramSystemOrder D) (ramFieldBits H w) ⟨s,i⟩).val =
+ (ramFieldOffset D H w ⟨s,i⟩).val := by
+ rw [PackingData.orderedBits_offset, PackingData.fieldStart]
+ simp_rw [column_width]
+ cases s with
+ | inl j =>
+ erw [ramFieldOffset_successor (H := H) j i]
+ change (∑ t : Fin j.val, if t.val < D then 8*w else blockBits H w) + i.val = _
+ simp [fun t : Fin j.val => t.isLt.trans j.isLt]
+ | inr l =>
+ erw [ramFieldOffset_sort (D := D) l i]
+ change (∑ t : Fin (D + l.ordinal.val), if t.val < D then 8*w else blockBits H w) + i.val = _
+ rw [Fin.sum_univ_add]
+ simp [Fin.val_castAdd, Fin.val_natAdd]
+
+variable {b l a p : ℕ} [NeZero (b+l)] (hD : 1 < b+l) (hd : 2+p=2^a)
+
+private abbrev bits (H w : ℕ) := (ramFieldBits H w : RAMSystem (b+l) → ℕ)
+
+/-- The padded compression state for the cursor graph, with base and lane coordinates and the
+widths of the successor and sorting messages. -/
+noncomputable abbrev state (H w : ℕ) := cursorState (cursorCoordinateLabels b l) hD hd (bits (b := b) (l := l) H w)
+/-- Identify the padded cursor graph with its compression state, numbering payload bits in RAM
+system order. -/
+noncomputable abbrev iso (H w : ℕ) := cursorStateIso (cursorCoordinateLabels b l) hD hd (ramSystemOrder (b+l)) (bits (b := b) (l := l) H w)
+
+/-- The padded slot index of the genuine stay or flip arc designated by the side bit. -/
+def realSlot (hd : 2+p=2^a) (side : Bool) := finCongr hd (paddingSlots p (.inl side))
+
+omit [NeZero (b+l)] in
+private theorem width_real (e : Arc (b+l)) :
+ (state hD hd H w).width ((((iso hD hd H w).edge (.inl e)).1.1, ((iso hD hd H w).edge (.inl e)).2),
+ ((iso hD hd H w).edge (.inl e)).1.2) = ramPayloadWidth (b+l) H w := by
+ change CursorNetwork.paddedWidth (bits (b := b) (l := l) H w) ((stateEdges (cursorCoordinateLabels b l) hd).symm (stateEdges (cursorCoordinateLabels b l) hd (.inl e))) = _
+ rw [Equiv.symm_apply_apply]
+ exact (ramPayloadWidth_eq_sum _ _ _).symm
+
+omit [NeZero (b+l)] in
+private theorem real_payload (e : Arc (b+l)) (y : Payload (bits (b := b) (l := l) H w)) :
+ List.ofFn (((iso hD hd H w).payload (.inl e)) y) = List.ofFn (ramPayloadEquiv (b+l) H w y) := by
+ refine (List.ofFn_congr (width_real hD hd e) (((iso hD hd H w).payload (.inl e)) y)).trans ?_
+ apply congrArg List.ofFn
+ funext j
+ obtain ⟨⟨s,i⟩,rfl⟩ := (ramFieldOffset (b+l) H w).surjective j
+ rw [ramPayloadEquiv_offset]
+ let order := ramSystemOrder (b+l)
+ let idx := PackingData.orderedBits order (bits (b := b) (l := l) H w)
+ change ((Equiv.piCurry _).symm y) (idx.symm ⟨(ramFieldOffset _ _ _ ⟨s,i⟩).val, _⟩) = _
+ let q := ramFieldOffset (b+l) H w ⟨s,i⟩
+ let k : Fin (∑ s, bits (b := b) (l := l) H w s) := ⟨q.val, by
+ rw [← ramPayloadWidth_eq_sum (b+l) H w]; exact q.isLt⟩
+ have he : idx.symm k = ⟨s,i⟩ := idx.injective ((idx.apply_symm_apply k).trans (Fin.ext (ordered_ram_offset s i).symm))
+ exact congrArg (fun t : (s : RAMSystem (b+l)) × Fin (ramFieldBits H w s) => y t.1 t.2) he
+
+/-- The state's independent halves, interpreted in the padded cursor's
+original coordinates. -/
+noncomputable def buffers (v : Position (b+l)) (z : (state hD hd H w).network.Half (lanePositions (cursorCoordinateLabels b l) v)) :=
+ halfBuffers v (unpadHalf p v ((iso hD hd H w).pullHalf v z))
+
+theorem outgoing_bits (v : Position (b+l))
+ (z : (state hD hd H w).network.Half (lanePositions (cursorCoordinateLabels b l) v)) (side : Bool) :
+ List.ofFn (fieldBits (state hD hd H w) _ z false (realSlot hd side)) =
+ List.ofFn (buffers hD hd v z (.outgoing side)) := by
+ let I := iso hD hd H w
+ let e : Arc (b+l) := (v.1,v.2,side)
+ let val := z.1 (I.edge (.inl e)) rfl
+ have h := real_payload hD hd e ((I.payload (.inl e)).symm val)
+ rw [Equiv.apply_symm_apply] at h
+ exact h
+
+private theorem incoming_edge (v : Position (b+l)) (side : Bool) :
+ ((incomingOrder (state hD hd H w) (lanePositions (cursorCoordinateLabels b l) v)).entries (realSlot hd side)).val =
+ (iso hD hd H w).edge (.inl (incomingArc v side)) := by
+ let I := iso hD hd H w
+ let X := state hD hd H w
+ let e := incomingArc v side
+ let slot := realSlot hd side
+ change X.slots.actualGraph.target.symm (I.site v, slot) = I.edge (.inl e)
+ apply X.slots.actualGraph.target.injective
+ rw [Equiv.apply_symm_apply]
+ apply Prod.ext
+ · change I.site v = X.network.dst (I.edge (.inl e))
+ exact (congrArg I.site (head_incomingArc v side).symm).trans (I.dst (.inl e))
+ · rfl
+
+private theorem incoming_congr {X : State a l} {u : X.network.Site} (z : X.network.Half u)
+ {e e' : X.network.Edge} (he : e = e') (h : u = X.network.dst e) (h' : u = X.network.dst e') :
+ List.ofFn (z.2 e h) = List.ofFn (z.2 e' h') := by cases he; rfl
+
+theorem incoming_bits (v : Position (b+l))
+ (z : (state hD hd H w).network.Half (lanePositions (cursorCoordinateLabels b l) v)) (side : Bool) :
+ List.ofFn (fieldBits (state hD hd H w) _ z true (realSlot hd side)) =
+ List.ofFn (buffers hD hd v z (.incoming side)) := by
+ let I := iso hD hd H w
+ let e := incomingArc v side
+ have he : I.site v = (state hD hd H w).network.dst (I.edge (.inl e)) :=
+ (congrArg I.site (head_incomingArc v side).symm).trans (I.dst (.inl e))
+ let val := z.2 (I.edge (.inl e)) he
+ have h := real_payload hD hd e ((I.payload (.inl e)).symm val)
+ rw [Equiv.apply_symm_apply] at h
+ exact (incoming_congr z (incoming_edge hD hd v side) _ he).trans h
+
+omit [NeZero (b+l)] in
+/-- Every slot at either end is genuine precisely at ordinal zero or one. -/
+theorem field_width (u : (state hD hd H w).network.Site) (dir : Bool) (j : Fin (2^a)) :
+ (state hD hd H w).halfWidth u dir j = if j.val < 2 then ramPayloadWidth (b+l) H w else 0 := by
+ rw [ramPayloadWidth_eq_sum]
+ cases dir with
+ | false => exact cursorSlotWidth hD hd (bits (b := b) (l := l) H w) u.1.1 u.1.2 u.2 j
+ | true =>
+ let old := (state hD hd H w).slots.actualTarget.symm ((u.1,j),u.2)
+ exact cursorSlotWidth hD hd (bits (b := b) (l := l) H w) old.1.1.1 old.1.1.2 old.2 j
+
+
+theorem realSlot_val (side : Bool) : (realSlot hd side).val = side.toNat := by cases side <;> rfl
+
+private theorem two_fields {m width : ℕ} (hm : 2 ≤ m) :
+ (∑ i : Fin m, if i.val < 2 then width else 0) = 2*width := by
+ obtain ⟨n,rfl⟩ := Nat.exists_eq_add_of_le hm
+ rw [Fin.sum_univ_add]
+ have htail (j : Fin n) : ¬ 2 + j.val ≤ 1 := by omega
+ simp [Fin.val_castAdd, Fin.val_natAdd, htail, two_mul]
+
+omit [NeZero (b+l)] in
+theorem end_width (u : (state hD hd H w).network.Site) (dir : Bool) :
+ (∑ j, (state hD hd H w).halfWidth u dir j) = 2 * ramPayloadWidth (b+l) H w := by
+ simp_rw [field_width hD hd]
+ exact two_fields (by omega)
+
+omit [NeZero (b+l)] in
+theorem real_width (u : (state hD hd H w).network.Site) (dir side : Bool) :
+ (state hD hd H w).halfWidth u dir (realSlot hd side) = ramPayloadWidth (b+l) H w := by
+ rw [field_width hD hd, realSlot_val, ite_eq_left (by cases side <;> decide)]
+
+/-- Ordinals of the two outgoing and the two incoming private vectors. -/
+def portNumber (dir side : Bool) : ℕ := (if dir then 2 else 0) + side.toNat
+
+/-- Select the incoming half-wire when the direction bit is true and the outgoing half-wire
+otherwise, at the given side. -/
+def port (dir side : Bool) : LocalPort := if dir then .incoming side else .outgoing side
+
+omit [NeZero (b+l)] in
+theorem real_offset (u : (state hD hd H w).network.Site) (dir side : Bool) :
+ offset (state hD hd H w) u dir (realSlot hd side) = portNumber dir side * ramPayloadWidth (b+l) H w := by
+ let X := state hD hd H w
+ let j := realSlot hd side
+ let width := ramPayloadWidth (b+l) H w
+ have hj : j.val < 2 := by rw [realSlot_val]; cases side <;> decide
+ have pre : ((List.ofFn (X.halfWidth u dir)).take j.val).sum = side.toNat * width := by
+ rw [← Fin.ofFn_take_eq_take_ofFn j.isLt.le, List.sum_ofFn]
+ calc
+ _ = ∑ _ : Fin j.val, width := Finset.sum_congr rfl fun i _ => by
+ change X.halfWidth u dir (Fin.castLE _ i) = width
+ rw [field_width hD hd]
+ exact ite_eq_left (i.isLt.trans hj)
+ _ = _ := by simp [j, realSlot_val]
+ change (if dir then ∑ k, X.halfWidth u false k else 0) + _ = _
+ rw [pre, end_width hD hd]
+ cases dir <;> simp [portNumber, Nat.add_mul, width]
+
+omit [NeZero (b+l)] in
+theorem packed_length_four (u : (state hD hd H w).network.Site) (z : (state hD hd H w).network.Half u) :
+ (packed (state hD hd H w) u z).length = 4 * ramPayloadWidth (b+l) H w := by
+ rw [packed_length, Fintype.sum_bool, end_width hD hd, end_width hD hd]
+ omega
+
+private theorem ofFn_bit {m n : ℕ} (x : Fin m → Bool) (y : Fin n → Bool) (he : m = n)
+ (hb : List.ofFn x = List.ofFn y) (i : Fin n) : x (Fin.cast he.symm i) = y i := by
+ subst n
+ exact congrFun (List.ofFn_inj.mp hb) i
+
+/-- The word actually read at the port offset of the private node arena
+is the validator's requested bit of the independently supplied half-wires. -/
+theorem read_port {ww : ℕ} (A : Arena) (node : ℕ) (v : Position (b+l))
+ (z : (state hD hd H w).network.Half (lanePositions (cursorCoordinateLabels b l) v))
+ (mem : BurstRAM.Word ww → BurstRAM.Word ww) (fit : A.base node + 4 * ramPayloadWidth (b+l) H w ≤ 2^ww)
+ (dir side : Bool) (i : Fin (ramPayloadWidth (b+l) H w)) :
+ PrivateFields.storeBits (A.base node) (packed (state hD hd H w) _ z) mem
+ ((A.base node + portNumber dir side * ramPayloadWidth (b+l) H w + i.val : ℕ) : BurstRAM.Word ww) =
+ PrivateFields.bitValue ww (buffers hD hd v z (port dir side) i) := by
+ let X := state hD hd H w
+ let u := lanePositions (cursorCoordinateLabels b l) v
+ let j := realSlot hd side
+ have len := real_width (H := H) (w := w) hD hd u dir side
+ have hb : List.ofFn (fieldBits X u z dir j) = List.ofFn (buffers hD hd v z (port dir side)) := by
+ cases dir with
+ | false => exact outgoing_bits hD hd v z side
+ | true => exact incoming_bits hD hd v z side
+ have word := stored_member X u A node z mem ((packed_length_four hD hd u z) ▸ fit)
+ dir j (Fin.cast len.symm i)
+ change PrivateFields.storeBits (A.base node) (packed X u z) mem
+ ((A.base node + offset X u dir j + i.val : ℕ) : BurstRAM.Word ww) = _ at word
+ have hoff : offset X u dir j = portNumber dir side * ramPayloadWidth (b+l) H w := real_offset hD hd u dir side
+ erw [hoff] at word
+ exact word.trans (congrArg _ (ofFn_bit _ _ len hb i))
+
+end PairSimulation.LeafArguments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafBoot.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafBoot.lean
new file mode 100644
index 0000000000..6c782f2ecb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafBoot.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.PairSimulationLeafBootSources
+import OAI.Computability.VPVNP.PairSimulationLeafArena
+
+/-!
+# Initializing a cursor-zero leaf from its four half buffers and operand cache
+
+The parent call supplies the decoded node and site addresses, the full O
+header, and the cache base. Its private RAM reads the 38 cached words,
+computes the stride, and executes the scalar and incident instruction
+tables. The result gives the entire private scratch after the last write.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafBoot
+
+open BurstRAM PrivateRAM RAMTape LeafStartup StackMachine LeafRegisterBank PrimedCounter.GuessWord
+open CursorNetwork CursorRouting RAMLayout
+open scoped Fin.CommRing
+
+set_option synthInstance.maxSize 10000
+
+variable {A : PrimedInputRAM.Lengths} {n a H s w d e p r k : ℕ} [NeZero d] {Q : PrimedInputRAM.Layout A n a H w}
+variable (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (v : Site d) (buf : Buffers d (2^e) w)
+
+/-- Instruction count for cursor-zero startup, including the fixed cache and capacity setup,
+scalar stack initialization, and incident-bit copy. -/
+noncomputable def ticks := 89 + scalarTicks D hw hc (0,v) buf + LeafIncidentMachine.ticks v (2^e) w
+
+omit [NeZero d] in
+/-- Word addresses of the four slices precede the private stack arena,
+so every word survives the allocation and scalar writes. -/
+private theorem still_stored (R : LeafArena.Regions) (L : Layout ScalarPort w) (node : ℕ)
+ (before : node+4*ramPayloadWidth d (2^e) w ≤ R.stackBase) (upper : R.stackBase < 2^w)
+ (above : ∀ j, R.stackBase ≤ L.base j) (old : Word w → Word w) (s : Stacks ScalarPort)
+ (stored : LeafIncidentLoad.Stored (LeafIncidentMachine.base node (ramPayloadWidth d (2^e) w)) buf old) :
+ LeafIncidentLoad.Stored (LeafIncidentMachine.base node (ramPayloadWidth d (2^e) w)) buf
+ (LeafLoadedBank.memory L s old) := by
+ intro port i
+ apply (LeafIncidentBank.memory_outside L s old _ ?_).trans (stored port i)
+ intro j
+ apply Or.inl
+ have hi := i.isLt
+ have hl : LeafIncidentMachine.base node (ramPayloadWidth d (2^e) w) port + i.val < R.stackBase := by
+ cases port with | outgoing side | incoming side => cases side <;> simp only [LeafIncidentMachine.base] <;> omega
+ change ((LeafIncidentMachine.base node _ port + i.val) % 2^w) < L.base j
+ rw [Nat.mod_eq_of_lt (hl.trans upper)]
+ exact hl.trans_le (above j)
+
+theorem run (M : Machine w p r k) (pc : Label → Fin p) (reg : Reg ↪ Fin r) (nPub : Fin k) (done : Fin p)
+ (link : Linked pc reg nPub done M) (R : LeafArena.Regions) (node : ℕ)
+ (fit : R.stackBase+Fintype.card ScalarPort*n^40 < 2^w) (before : node+4*ramPayloadWidth d (2^e) w ≤ R.stackBase)
+ (c : Config w p r) (entry : c.pc = pc (.pre 0)) (hnode : c.reg (nodeBase reg) = (node : Word w))
+ (cachePtr : c.reg (cacheBase reg) = (R.cacheBase : Word w)) (hn : M.publicData nPub = (n : Word w))
+ (address : c.reg (sources reg .address) = (v.val : Word w))
+ (header : c.reg (sources reg .header) = D.initial v)
+ (cache : LeafSourceLoad.Cached R.cacheBase c.privateMem
+ (fun j => sourceWord (auxiliary D hw hc (0,v) buf) D.pub j.dest))
+ (stored : LeafIncidentLoad.Stored (LeafIncidentMachine.base node (ramPayloadWidth d (2^e) w)) buf c.privateMem)
+ (room : ∀ j, (bank 52 (auxiliary D hw hc (0,v) buf) D.pub j).length ≤ n^40)
+ {top endAddr : ℕ} (pending : List (Word w)) (htop : top+pending.length = endAddr)
+ (previous : DFS.Represents c.privateMem top pending) (low : endAddr ≤ R.arguments.start) :
+ let L := R.layout portOrder.symm.toEmbedding (n^40) fit
+ let full := bank 52 (auxiliary D hw hc (0,v) buf) D.pub
+ ∃ out, Prefix M c (List.replicate (ticks D hw hc v buf) .tick) out ∧ out.pc = done ∧
+ Represents L (stack reg) out full ∧ out.persistent = c.persistent ∧
+ (∀ i, i ∉ Set.range reg → out.reg i = c.reg i) ∧
+ out.privateMem = LeafLoadedBank.memory L full c.privateMem ∧
+ DFS.Represents out.privateMem top pending ∧
+ DFS.scratch endAddr out.privateMem = LeafLoadedBank.scratch L full (DFS.scratch endAddr c.privateMem) := by
+ intro L full
+ let x := auxiliary D hw hc (0,v) buf
+ let scalarBank := scalarInput D hw hc (0,v) buf
+ have addr : c.reg (sources reg .address) = x.addrWord := by
+ rw [address]; apply Fin.ext
+ exact Nat.mod_eq_of_lt x.addrWord.isLt
+ obtain ⟨start,pre,hpc,hvals,hcursor,hstride,memA,stateA,nodeA,regsA⟩ :=
+ source_prefix pc reg nPub done M x D.pub n R.cacheBase link c entry addr header rfl cachePtr cache hn
+ have scalarRoom (j : ScalarPort) : (scalarBank j).length ≤ n^40 := by
+ change (fieldBits x D.pub (scalarField (field j))).length ≤ _
+ by_cases hi : field j = .incident
+ · simp [scalarField,hi,fieldBits]
+ · rw [scalarField,ite_eq_right hi]; exact room j
+ have sl (j : ScalarLabel) : M.code ((pc ∘ Label.scalar) j) =
+ LeafPortTable.instruction field (pc ∘ Label.scalar) (scalar reg) (pc (.incident (.inl 0))) scalarRows j :=
+ link (.scalar j)
+ obtain ⟨mid,runS,sitePC,rep,sourcesReady,stateS,regsS,memS⟩ :=
+ scalar_start D hw hc (0,v) buf M (scalar reg) (pc ∘ Label.scalar) (pc (.incident (.inl 0))) R.stackBase
+ (n^40) fit sl start hpc hcursor hstride hvals scalarRoom
+ change Represents L (stack reg) mid scalarBank at rep
+ change mid.privateMem = LeafLoadedBank.memory L scalarBank start.privateMem at memS
+ rw [memA] at memS
+ have pNode := (regsS (nodeBase reg) (by rintro ⟨i,h⟩; simp [nodeBase] at h)).trans (nodeA.trans hnode)
+ have ready : LeafIncidentGeometry.Ready d (2^e) w v.val node (L.base incident) (mid.reg ∘ geometry reg) := by
+ refine ⟨sourcesReady.d,?_,sourcesReady.bucket,sourcesReady.width,pNode,?_⟩
+ · change mid.reg (sources reg .address) = _
+ have val := sourcesReady.address
+ change mid.reg (sources reg .address) = x.addrWord at val
+ rw [val]
+ exact Fin.ext (Nat.mod_eq_of_lt x.addrWord.isLt).symm
+ · exact (rep.bases incident).trans (by simp [Layout.address])
+ have upper := (Nat.le_add_right R.stackBase _).trans_lt fit
+ have above (j : ScalarPort) := R.stack_above portOrder.symm.toEmbedding (n^40) fit j
+ have stored' : LeafIncidentLoad.Stored (LeafIncidentMachine.base node (ramPayloadWidth d (2^e) w)) buf mid.privateMem :=
+ memS ▸ still_stored buf R L node before upper above c.privateMem scalarBank stored
+ have fieldRoom : width d (2^e) w ≤ n^40 := by
+ have h := room incident
+ change (List.ofFn (RAMLayout.incidentBits x.sends x.v)).length ≤ n^40 at h
+ simpa only [List.length_ofFn] using h
+ have hDW := (Nat.le_add_right d e).trans_lt x.hcap
+ have incRows : LeafIncidentMachine.Linked M (pc ∘ Label.incident) (geometry reg) done := fun j => link (.incident j)
+ obtain ⟨out,runI,physical,fullRep,exactMem,kept,scratch⟩ := LeafIncidentBank.machine_run D hw hc v buf L
+ (stack reg) (geometry reg) (pc ∘ Label.incident) M done incRows node mid sitePC ready hDW stored'
+ (before.trans upper.le) (.inl (before.trans (above incident))) rfl (protect reg) c.privateMem pending htop previous
+ (R.stack_above_dfs _ _ fit low) rep scalarRoom fieldRoom memS
+ have all := (pre.append runS).append runI
+ rw [← List.replicate_add,← List.replicate_add] at all
+ refine ⟨out,all,physical.pc,fullRep,physical.persistent.trans (stateS.trans stateA),?_,exactMem,kept,scratch⟩
+ intro i hi
+ have ne (j : Reg) : i ≠ reg j := fun he => hi ⟨j,he.symm⟩
+ exact (physical.frame i (fun j _ => ne (geometryName j))).trans
+ ((regsS i (fun ⟨j,h⟩ => hi ⟨.inl j,h⟩)).trans (regsA i hi))
+
+end PairSimulation.LeafBoot
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafBootClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootClock.lean
new file mode 100644
index 0000000000..7b0ea6a879
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootClock.lean
@@ -0,0 +1,38 @@
+import OAI.Computability.VPVNP.PairSimulationLeafBoot
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentTable
+
+/-! # Uniform private clock for the complete auxiliary stack initializer -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafBoot
+
+open BurstRAM CursorNetwork CursorRouting LeafStartup Filter
+
+/-- One eventual bound applies to every input of the auxiliary initializer:
+the cache and stride cost 89 ticks, the scalar pass costs at most n^14,
+and the full incident copy costs at most n^5. -/
+theorem eventually_ticks :
+ ∀ᶠ n : ℕ in atTop, ∀ {A : PrimedInputRAM.Lengths} {a H s w d e : ℕ} [NeZero d]
+ {Q : PrimedInputRAM.Layout A n a H w} (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^d*2^e<2^w)
+ (v : Site d) (buf : Buffers d (2^e) w), ProcessorBudget n d e w → D.fuel ≤ n^10 →
+ ticks D hw hc v buf ≤ n^15 := by
+ filter_upwards [LeafPortTable.eventually_auxiliary_cost 52 34 scalarRows,eventually_ge_atTop 1024] with n hscalar hn
+ intro A a H s w d e inst Q D hw hc v buf bud hf
+ have hs := hscalar d e w (auxiliary D hw hc (0,v) buf) bud hf D.pub
+ change scalarTicks D hw hc (0,v) buf ≤ n^14 at hs
+ have hi := LeafIncidentMachine.ticks_le_of_budget v bud hn
+ have hn' : 1 ≤ n := by omega
+ have hp := Nat.pow_le_pow_right hn' (by decide : 5 ≤ 14)
+ have h1 := Nat.one_le_pow 14 n hn'
+ have hbig : 91*n^14 ≤ n^15 := by rw [pow_succ' n 14]; exact Nat.mul_le_mul_right _ (by omega)
+ unfold ticks
+ omega
+
+end PairSimulation.LeafBoot
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafBootHandoff.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootHandoff.lean
new file mode 100644
index 0000000000..8cfaa59b4f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootHandoff.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.PairSimulationRoutePrepare
+import OAI.Computability.VPVNP.PairSimulationLeafBootRows
+
+/-!
+# Passing the decoded leaf and its private-arena pointers to the verifier
+
+The routing scan may reuse its cache-address temporary. After a cursor-zero
+success the parent reloads the frame's cache pointer and computes the node
+argument base from the preserved node word, the arena stride, and the arena
+start. All seven instructions are private and deterministic.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafBootHandoff
+
+open BurstRAM PrivateRAM RAMTape PrimedCounter.GuessWord NodeArguments
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Seven native operand transfers from a successful route to the leaf initializer. -/
+def instruction (pc : Fin 7 → Fin p) (boot : LeafBoot.Reg ↪ Fin r) (leaf : LeafAddress.Reg ↪ Fin r)
+ (pub : RoutePrepare.Field → Fin k) (done : Fin p) : Fin 7 → Instr w p r k :=
+ ![.copy (LeafBoot.sources boot .address) (leaf .site) (pc 1),
+ .copy (LeafBoot.sources boot .header) (leaf .header) (pc 2),
+ .publicWord (LeafBoot.cacheBase boot) (pub .cache) (pc 3),
+ .publicWord (LeafBoot.tmp boot) (pub .stride) (pc 4),
+ .binary .mul (LeafBoot.nodeBase boot) (leaf .node) (LeafBoot.tmp boot) (pc 5),
+ .publicWord (LeafBoot.tmp boot) (pub .start) (pc 6),
+ .binary .add (LeafBoot.nodeBase boot) (LeafBoot.tmp boot) (LeafBoot.nodeBase boot) done]
+
+theorem resize_instruction (pc : Fin 7 → Fin p) (boot : LeafBoot.Reg ↪ Fin r) (leaf : LeafAddress.Reg ↪ Fin r)
+ (pub : RoutePrepare.Field → Fin k) (done : Fin p) (i : Fin 7) :
+ (instruction (w := 1) pc boot leaf pub done i).resize w = instruction pc boot leaf pub done i := by
+ fin_cases i <;> rfl
+
+/-- Registers overwritten during the successful route handoff. -/
+def Written (boot : LeafBoot.Reg ↪ Fin r) (j : Fin r) : Prop :=
+ j = LeafBoot.sources boot .address ∨ j = LeafBoot.sources boot .header ∨ j = LeafBoot.cacheBase boot ∨
+ j = LeafBoot.tmp boot ∨ j = LeafBoot.nodeBase boot
+
+theorem run (M : Machine w p r k) (pc : Fin 7 → Fin p) (boot : LeafBoot.Reg ↪ Fin r)
+ (leaf : LeafAddress.Reg ↪ Fin r) (pub : RoutePrepare.Field → Fin k) (done : Fin p)
+ (link : ∀ i, M.code (pc i) = instruction pc boot leaf pub done i)
+ (headSep : leaf .header ≠ LeafBoot.sources boot .address) (nodeSep : ¬ Written boot (leaf .node))
+ (R : LeafArena.Regions) (node : ℕ) (site head : Word w) (c : Config w p r) (entry : c.pc = pc 0)
+ (hv : c.reg (leaf .site) = site) (hh : c.reg (leaf .header) = head) (hn : c.reg (leaf .node) = (node : Word w))
+ (hb : M.publicData (pub .cache) = (R.cacheBase : Word w))
+ (hs : M.publicData (pub .stride) = (R.arguments.stride : Word w))
+ (ha : M.publicData (pub .start) = (R.arguments.start : Word w)) :
+ ∃ out, Prefix M c (List.replicate 7 .tick) out ∧ out.pc = done ∧
+ out.reg (LeafBoot.sources boot .address) = site ∧ out.reg (LeafBoot.sources boot .header) = head ∧
+ out.reg (LeafBoot.cacheBase boot) = (R.cacheBase : Word w) ∧
+ out.reg (LeafBoot.nodeBase boot) = (R.arguments.base node : Word w) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ ∀ j, ¬ Written boot j → out.reg j = c.reg j := by
+ let a := c.put (pc 1) (LeafBoot.sources boot .address) site
+ let b := a.put (pc 2) (LeafBoot.sources boot .header) head
+ let f := b.put (pc 3) (LeafBoot.cacheBase boot) (R.cacheBase : Word w)
+ let g := f.put (pc 4) (LeafBoot.tmp boot) (R.arguments.stride : Word w)
+ let n := g.put (pc 5) (LeafBoot.nodeBase boot) ((node*R.arguments.stride : ℕ) : Word w)
+ let u := n.put (pc 6) (LeafBoot.tmp boot) (R.arguments.start : Word w)
+ let out := u.put done (LeafBoot.nodeBase boot) ((R.arguments.base node : ℕ) : Word w)
+ have step (i : Fin 7) (s : Config w p r) (hpc : s.pc = pc i) :
+ M.program.step s = (instruction pc boot leaf pub done i).run M.publicData s := by
+ change (M.code s.pc).run M.publicData s = _
+ rw [hpc,link]
+ have keep {j : Fin r} (h : ¬Written boot j) : j ≠ LeafBoot.sources boot .address ∧
+ j ≠ LeafBoot.sources boot .header ∧ j ≠ LeafBoot.cacheBase boot ∧
+ j ≠ LeafBoot.tmp boot ∧ j ≠ LeafBoot.nodeBase boot := by
+ simpa only [Written, not_or] using h
+ obtain ⟨n₁,n₂,n₃,n₄,_⟩ := keep nodeSep
+ have run : Prefix M c (List.replicate 7 .tick) out := by
+ refine .tick (next := a) ?_ (.tick (next := b) ?_ (.tick (next := f) ?_ (.tick (next := g) ?_
+ (.tick (next := n) ?_ (.tick (next := u) ?_ (.tick ?_ (.nil _)))))))
+ · rw [step 0 c entry]; change CallAction.localStep (c.put _ _ _) = _; rw [hv]
+ · rw [step 1 a rfl]; change CallAction.localStep (a.put _ _ _) = _
+ rw [show a.reg (leaf .header) = head from (Function.update_of_ne headSep ..).trans hh]
+ · rw [step 2 b rfl]; change CallAction.localStep (b.put _ _ _) = _; rw [hb]
+ · rw [step 3 f rfl]; change CallAction.localStep (f.put _ _ _) = _; rw [hs]
+ · rw [step 4 g rfl]
+ have word : g.reg (leaf .node) = (node : Word w) := by
+ simp only [g,f,b,a,Config.put,Function.update_of_ne n₁,Function.update_of_ne n₂,
+ Function.update_of_ne n₃,Function.update_of_ne n₄,hn]
+ change CallAction.localStep (g.put _ _ (g.reg (leaf .node)*g.reg (LeafBoot.tmp boot))) = _
+ rw [word,show g.reg (LeafBoot.tmp boot) = _ from Function.update_self .., ← Nat.cast_mul]
+ · rw [step 5 n rfl]; change CallAction.localStep (n.put _ _ _) = _; rw [ha]
+ · rw [step 6 u rfl]
+ change CallAction.localStep (u.put _ _ (u.reg (LeafBoot.tmp boot)+u.reg (LeafBoot.nodeBase boot))) = _
+ simp [u,n,out,Config.put,LeafBoot.tmp,LeafBoot.nodeBase,Arena.base]
+ refine ⟨out,run,rfl,?_,?_,?_,Function.update_self ..,rfl,rfl,?_⟩
+ · simp [out,u,n,g,f,b,a,Config.put,LeafBoot.tmp,LeafBoot.nodeBase,LeafBoot.cacheBase]
+ · simp [out,u,n,g,f,b,Config.put,LeafBoot.tmp,LeafBoot.nodeBase,LeafBoot.cacheBase]
+ · simp [out,u,n,g,f,Config.put,LeafBoot.tmp,LeafBoot.nodeBase,LeafBoot.cacheBase]
+ · intro j h
+ obtain ⟨j₁,j₂,j₃,j₄,j₅⟩ := keep h
+ simp only [out,u,n,g,f,b,a,Config.put,Function.update_of_ne j₁,Function.update_of_ne j₂,
+ Function.update_of_ne j₃,Function.update_of_ne j₄,Function.update_of_ne j₅]
+
+end PairSimulation.LeafBootHandoff
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafBootRows.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootRows.lean
new file mode 100644
index 0000000000..fd0f40bff5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootRows.lean
@@ -0,0 +1,148 @@
+import OAI.Computability.VPVNP.PairSimulationLeafCapacity
+import OAI.Computability.VPVNP.PairSimulationLeafCachedSources
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentReady
+
+/-! # The linked native rows for the complete cursor-zero leaf startup -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafBoot
+
+open BurstRAM PrivateRAM RAMTape LeafStartup StackMachine LeafRegisterBank
+open scoped Fin.CommRing
+
+set_option synthInstance.maxSize 10000
+
+/-- Register names for the scalar initializer together with 30 additional slots used by the
+cursor-zero startup. -/
+abbrev Reg := ScalarReg ⊕ Fin 30
+/-- The incident-bit stack port of the concrete validator with 52 registers and 34 public
+operands. -/
+abbrev incident := LeafLoadedBank.incidentPort 52 34
+
+variable {w p r k : ℕ}
+
+/-- Embed the scalar initializer's register bank into the physical startup registers. -/
+def scalar (reg : Reg ↪ Fin r) : ScalarReg ↪ Fin r := ⟨fun j => reg (.inl j), fun _ _ h => Sum.inl.inj (reg.injective h)⟩
+
+/-- Place the scalar initializer's source words, including the 34 public operands, in their
+physical startup registers. -/
+def sources (reg : Reg ↪ Fin r) : Source 34 ↪ Fin r :=
+ ⟨fun j => reg (.inl (.inr j)), fun _ _ h => Sum.inr.inj (Sum.inl.inj (reg.injective h))⟩
+
+/-- Assign the incident loader's 30 register indices to startup registers, sharing the
+dimension, site address, bucket, word width and incident stack pointers with the scalar
+initializer. -/
+def geometryName (i : Fin 30) : Reg :=
+ if i = 11 then .inl (.inr .d) else if i = 13 then .inl (.inr .address) else
+ if i = 20 then .inl (.inr .bucket) else if i = 21 then .inl (.inr .width) else
+ if i = 23 then .inl (.inl (.pointers (.stack (.base incident)))) else
+ if i = 24 then .inl (.inl (.pointers (.stack (.top incident)))) else .inr i
+
+private theorem geometry_injective : Function.Injective geometryName := by
+ let back : Reg → Fin 30 := fun
+ | .inr i => i
+ | .inl (.inr .d) => 11
+ | .inl (.inr .address) => 13
+ | .inl (.inr .bucket) => 20
+ | .inl (.inr .width) => 21
+ | .inl (.inl (.pointers (.stack (.base _)))) => 23
+ | .inl (.inl (.pointers (.stack (.top _)))) => 24
+ | _ => 0
+ apply Function.LeftInverse.injective (g := back)
+ intro i; fin_cases i <;> rfl
+
+/-- The injective placement of the incident loader's geometry registers in the host machine. -/
+def geometry (reg : Reg ↪ Fin r) : Fin 30 ↪ Fin r := ⟨fun i => reg (geometryName i),reg.injective.comp geometry_injective⟩
+
+/-- Physical placement of the stack interpreter's named registers during cursor-zero
+initialization. -/
+abbrev stack (reg : Reg ↪ Fin r) := LeafRegisterBank.stack (scalar reg)
+/-- Physical placement of the allocation cursor, stride and stack registers used to assign the
+validator's private stack intervals. -/
+abbrev pointer (reg : Reg ↪ Fin r) := LeafFill.pointers (load (scalar reg))
+
+@[simp] theorem scalar_at (reg : Reg ↪ Fin r) (j : ScalarReg) : scalar reg j = reg (.inl j) := rfl
+@[simp] theorem source_at (reg : Reg ↪ Fin r) (j : Source 34) : sources reg j = reg (.inl (.inr j)) := rfl
+@[simp] theorem geometry_at (reg : Reg ↪ Fin r) (j : Fin 30) : geometry reg j = reg (geometryName j) := rfl
+
+/-- Startup register holding the private address of the first cached operand. -/
+def cacheBase (reg : Reg ↪ Fin r) := reg (.inr 0)
+/-- Startup register holding the base of the current node's private argument frame. -/
+def nodeBase (reg : Reg ↪ Fin r) := reg (.inr 22)
+/-- Temporary register used while calculating the stack capacity. -/
+def tmp (reg : Reg ↪ Fin r) := reg (.inr 1)
+
+theorem wiring (reg : Reg ↪ Fin r) :
+ LeafSourceLoad.Wiring (sources reg) (sources reg .header) (cacheBase reg)
+ (pointer reg .cursor) (stack reg .one) := by
+ constructor <;> simp [cacheBase,stack,pointer]
+
+theorem protect (reg : Reg ↪ Fin r) (j : Register ScalarPort) (_ht : j ≠ .tmp) (hj : j ≠ .top incident) :
+ ∀ i ∈ LeafIncidentMachine.changed, stack reg j ≠ geometry reg i := by
+ intro i hi
+ have hb : i ≠ 23 := fun e => (show (23 : Fin 30) ∉ LeafIncidentMachine.changed by decide) (e ▸ hi)
+ by_cases he : i = 24
+ · subst i
+ change stack reg j ≠ stack reg (.top incident)
+ exact (stack reg).injective.ne hj
+ · simp [stack,geometryName,hb,he]; split_ifs <;> simp
+
+/-- Program labels for the startup prelude, the 38 cache reads and increments, the capacity
+calculation, and the scalar and incident loaders. -/
+inductive Label where
+ | pre (i : Fin 5) | read (i : Fin 38) | increment (i : Fin 38)
+ | capacity (i : Fin 8) | scalar (j : ScalarLabel) | incident (j : LeafIncidentMachine.Stage)
+ deriving DecidableEq
+
+noncomputable instance : Fintype Label := derive_fintype% _
+
+variable (pc : Label → Fin p) (reg : Reg ↪ Fin r) (nPub : Fin k) (done : Fin p)
+
+/-- Jump to the cache read at the given index, or to the first capacity instruction when all 38
+words have been consumed. -/
+def readPC (i : Fin ((LeafSourceLoad.slots 34).length+1)) : Fin p :=
+ if h : i.val < 38 then pc (.read ⟨i.val,h⟩) else pc (.capacity 0)
+
+/-- Entry label for allocating the first scalar port's stack, with the allocation finalizer as
+the empty-list continuation. -/
+noncomputable def scalarEntry :=
+ LeafPointers.next scalarRows (fun a i => pc (.scalar (.pointer a i))) (pc (.scalar (.finish 0)))
+
+/-- The startup instruction at a leaf-boot label, linking the cache scan and capacity
+calculation to scalar initialization and the incident copy. -/
+noncomputable def instruction : Label → Instr w p r k
+ | .pre i => LeafSourceLoad.prelude (sources reg) (sources reg .address) (sources reg .header) (cacheBase reg)
+ (pointer reg .cursor) (stack reg .one) (pc ∘ Label.pre) (pc (.read 0)) i
+ | .read i => LeafSourceLoad.readInstr (sources reg) (pointer reg .cursor) (pc (.increment i))
+ ((LeafSourceLoad.slots 34)[i.val]'(by simpa only [LeafSourceLoad.length_slots] using i.isLt))
+ | .increment i => LeafSourceLoad.incInstr (pointer reg .cursor) (stack reg .one)
+ (readPC pc ((i.cast (by rw [LeafSourceLoad.length_slots])).succ))
+ | .capacity i => LeafCapacity.instruction (pc ∘ Label.capacity) (pointer reg .stride) (tmp reg) nPub (scalarEntry pc) i
+ | .scalar j => LeafPortTable.instruction field (pc ∘ Label.scalar) (scalar reg) (pc (.incident (.inl 0))) scalarRows j
+ | .incident j => LeafIncidentMachine.instruction (pc ∘ Label.incident) (geometry reg) done j
+
+private theorem resize_twice (i : Instr 1 p r k) : (i.resize 5).resize w = i.resize w := by
+ cases i <;> try rfl
+ case constant dst v next => simp only [Instr.resize,resize_literal (by decide : 1≤5)]
+
+theorem resize_instruction (j : Label) :
+ (instruction (w := 5) pc reg nPub done j).resize w = instruction pc reg nPub done j := by
+ cases j with
+ | pre i => simp only [instruction]; rw [← LeafSourceLoad.prelude_resize (w := 5),resize_twice,LeafSourceLoad.prelude_resize]
+ | read i | increment i => rfl
+ | capacity i => simp only [instruction]; rw [← LeafCapacity.resize_instruction (w := 5),resize_twice,LeafCapacity.resize_instruction]
+ | scalar j => simp only [instruction]; rw [← LeafPortTable.resize_instruction (w := 5),resize_twice,LeafPortTable.resize_instruction]
+ | incident j => exact LeafIncidentMachine.resize_instruction ..
+
+/-- Every startup label in the host machine executes its prescribed instruction with the
+designated length operand and return label. -/
+def Linked (M : Machine w p r k) : Prop := ∀ j, M.code (pc j) = instruction pc reg nPub done j
+
+end PairSimulation.LeafBoot
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafBootSources.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootSources.lean
new file mode 100644
index 0000000000..d2a90867f4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootSources.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.PairSimulationLeafBootRows
+
+/-! # The cached-source and capacity prefix of the linked leaf startup -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafBoot
+
+open BurstRAM PrivateRAM RAMTape LeafStartup StackMachine LeafRegisterBank PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k d e : ℕ} (pc : Label → Fin p) (reg : Reg ↪ Fin r) (nPub : Fin k) (done : Fin p)
+ (M : Machine w p r k)
+
+theorem source_prefix (x : VirtualSite.Input d e w) (args : Fin 34 → Word w) (n base : ℕ)
+ (link : Linked pc reg nPub done M) (c : Config w p r) (entry : c.pc = pc (.pre 0))
+ (addr : c.reg (sources reg .address) = x.addrWord) (hdr : c.reg (sources reg .header) = x.headerWord)
+ (initial : x.initialWord = 0) (hb : c.reg (cacheBase reg) = (base : Word w))
+ (cached : LeafSourceLoad.Cached base c.privateMem (fun j => sourceWord x args j.dest))
+ (hn : M.publicData nPub = (n : Word w)) :
+ ∃ out, Prefix M c (List.replicate 89 .tick) out ∧ out.pc = scalarEntry pc ∧
+ (∀ j, out.reg (sources reg j) = sourceWord x args j) ∧
+ out.reg (pointer reg .cursor) = ((base+38 : ℕ) : Word w) ∧
+ out.reg (pointer reg .stride) = ((n^40 : ℕ) : Word w) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧ out.reg (nodeBase reg) = c.reg (nodeBase reg) ∧
+ ∀ i, i ∉ Set.range reg → out.reg i = c.reg i := by
+ let inc (i : Fin (LeafSourceLoad.slots 34).length) := pc (.increment (i.cast (by rw [LeafSourceLoad.length_slots])))
+ have hread (i : Fin (LeafSourceLoad.slots 34).length) :
+ M.code (readPC pc i.castSucc) = LeafSourceLoad.readInstr (sources reg) (pointer reg .cursor)
+ (inc i) (LeafSourceLoad.slots 34)[i] := by
+ let j : Fin 38 := i.cast (by rw [LeafSourceLoad.length_slots])
+ have he : readPC pc i.castSucc = pc (.read j) := by simp [readPC,j, show i.val < 38 by simpa using i.isLt]; congr 2
+ rw [he]; exact link (.read j)
+ have hadv (i : Fin (LeafSourceLoad.slots 34).length) : M.code (inc i) =
+ LeafSourceLoad.incInstr (pointer reg .cursor) (stack reg .one) (readPC pc i.succ) :=
+ link (.increment (i.cast (by rw [LeafSourceLoad.length_slots])))
+ obtain ⟨mid,run,hm,values,cur,mem,persist,fr⟩ := LeafSourceLoad.cachedSources x args M (sources reg)
+ (sources reg .address) (sources reg .header) (cacheBase reg) (pointer reg .cursor) (stack reg .one)
+ (pc ∘ Label.pre) (readPC pc) inc (fun i => link (.pre i)) hread hadv (wiring reg) base c entry addr hdr initial hb cached
+ have atCap : mid.pc = pc (.capacity 0) := by simpa [readPC] using hm
+ have sep : pointer reg .stride ≠ tmp reg := by simp [pointer,tmp]
+ obtain ⟨out,capRun,hpc,stride,hmem,hstate,frame⟩ := LeafCapacity.run M (pc ∘ Label.capacity)
+ (pointer reg .stride) (tmp reg) sep nPub (scalarEntry pc) (fun i => link (.capacity i)) mid atCap n hn
+ have all := run.append capRun
+ rw [← List.replicate_add] at all
+ refine ⟨out,all,hpc,?_,?_,stride,hmem.trans mem,hstate.trans persist,?_,?_⟩
+ · exact fun j => (frame _ (by simp [pointer]) (by simp [tmp])).trans (values j)
+ · exact (frame _ (by simp [pointer]) (by simp [pointer,tmp])).trans cur
+ · exact (frame _ (by simp [nodeBase,pointer]) (by simp [nodeBase,tmp])).trans
+ (fr _ (by simp [nodeBase]) (by simp [nodeBase,pointer]) (by simp [nodeBase,stack]))
+ · intro i hi
+ have ne (j : Reg) : i ≠ reg j := fun he => hi ⟨j,he.symm⟩
+ exact (frame i (ne _) (ne _)).trans (fr i (fun _ => ne _) (ne _) (ne _))
+
+end PairSimulation.LeafBoot
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafBootWrites.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootWrites.lean
new file mode 100644
index 0000000000..17ba25aaea
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafBootWrites.lean
@@ -0,0 +1,39 @@
+import OAI.Computability.VPVNP.PairSimulationLeafBootRows
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentFootprint
+import OAI.Computability.VPVNP.PairSimulationLeafScalarWrites
+
+/-! # Register destinations of the complete virtual leaf bootstrap -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafBoot
+
+open BurstRAM PrivateRAM RegisterOperands LeafStartup
+
+variable {W p r k : ℕ}
+
+/-- Every scalar, capacity and incident initialization row writes only its
+declared operand bank. This covers rows reached by arbitrary physical data. -/
+theorem destination_mem (pc : Label → Fin p) (reg : Reg ↪ Fin r) (nPub : Fin k) (done : Fin p)
+ (j : Label) (a : Fin r) (h : destination (instruction (w := W) pc reg nPub done j) = some a) :
+ a ∈ Set.range reg := by
+ cases j with
+ | pre i => fin_cases i <;> exact ⟨_,Option.some.inj h⟩
+ | read i => exact ⟨_,Option.some.inj h⟩
+ | increment i => exact ⟨_,Option.some.inj h⟩
+ | capacity i => fin_cases i <;> exact ⟨_,Option.some.inj h⟩
+ | scalar j =>
+ obtain ⟨i,hi⟩ := LeafPortTable.destination_mem field (pc ∘ Label.scalar) (scalar reg)
+ (pc (.incident (.inl 0))) scalarRows j a h
+ exact ⟨.inl i,hi⟩
+ | incident i =>
+ obtain ⟨j,hj⟩ := LeafIncidentMachine.destination_mem (pc ∘ Label.incident) (geometry reg) done i a h
+ exact ⟨geometryName j,hj⟩
+
+end PairSimulation.LeafBoot
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafCacheRead.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafCacheRead.lean
new file mode 100644
index 0000000000..1ea177a09d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafCacheRead.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSourceLoad
+
+/-!
+# Reading the auxiliary leaf's cached operands in private RAM
+
+The pair call computes the constant-sized scalar array in private memory.
+A leaf loads its words in consecutive address order. The only extra register
+written is the cache cursor. Every load and increment is a private tick.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSourceLoad
+
+open BurstRAM PrivateRAM LeafRegisterBank PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {k w p r pubs : ℕ}
+
+/-- Load a scalar from the private cache at the current cursor. -/
+def readInstr (ports : Source k ↪ Fin r) (cursor : Fin r) (next : Fin p) (i : Static k) : Instr w p r pubs :=
+ .loadPrivate (ports i.dest) cursor next
+
+/-- Advance the private cache cursor by one word. -/
+def incInstr (cursor unit : Fin r) (next : Fin p) : Instr w p r pubs :=
+ .binary .add cursor cursor unit next
+
+private theorem fold_cursor (ports : Source k ↪ Fin r) (vals : Static k → Word w)
+ (cursor : Fin r) (hc : ∀ i : Static k, cursor ≠ ports i.dest) (ls : List (Static k))
+ (bank : Fin r → Word w) (a : Word w) :
+ ls.foldl (setStatic ports vals) (Function.update bank cursor a) =
+ Function.update (ls.foldl (setStatic ports vals) bank) cursor a := by
+ induction ls generalizing bank with
+ | nil => rfl
+ | cons i ls ih =>
+ simp only [List.foldl_cons]
+ unfold setStatic
+ rw [Function.update_comm (hc i)]
+ exact ih _
+
+theorem cached_rows (M : Machine w p r pubs) (ports : Source k ↪ Fin r) (cursor unit : Fin r)
+ (hcursor : ∀ i : Static k, cursor ≠ ports i.dest) (hunit : ∀ i : Static k, unit ≠ ports i.dest)
+ (hu : unit ≠ cursor) (vals : Static k → Word w)
+ (ls : List (Static k)) (pc : Fin (ls.length+1) → Fin p) (inc : Fin ls.length → Fin p)
+ (read : ∀ i : Fin ls.length, M.code (pc i.castSucc) = readInstr ports cursor (inc i) ls[i])
+ (advance : ∀ i : Fin ls.length, M.code (inc i) = incInstr cursor unit (pc i.succ))
+ (base : ℕ) (c : Config w p r) (entry : c.pc = pc 0)
+ (hc : c.reg cursor = (base : Word w)) (hone : c.reg unit = 1)
+ (cache : ∀ i : Fin ls.length, c.privateMem ((base+i.val : ℕ) : Word w) = vals ls[i]) :
+ Prefix M c (List.replicate (2*ls.length) .tick)
+ {c with
+ pc := pc (Fin.last ls.length)
+ reg := Function.update (ls.foldl (setStatic ports vals) c.reg) cursor ((base+ls.length : ℕ) : Word w)} := by
+ induction ls generalizing c base with
+ | nil =>
+ simp only [List.length_nil, List.foldl_nil, Nat.mul_zero, List.replicate_zero, Nat.add_zero,
+ ← hc, Function.update_eq_self]
+ rw [show Fin.last 0 = 0 from rfl, ← entry]
+ exact .nil c
+ | cons i ls ih =>
+ let t := c.put (inc 0) (ports i.dest) (vals i)
+ let u := t.put (pc (Fin.succ 0)) cursor ((base+1 : ℕ) : Word w)
+ have hread := read 0
+ change M.code (pc 0) = readInstr ports cursor (inc 0) i at hread
+ have hval := cache 0
+ change c.privateMem ((base+0 : ℕ) : Word w) = vals i at hval
+ rw [Nat.add_zero] at hval
+ have h₁ : M.program.step c = .localStep t := by
+ change (M.code c.pc).run M.publicData c = _
+ rw [entry,hread]
+ simp only [readInstr,Instr.run,hc,hval,t]
+ have hadd := advance 0
+ have h₂ : M.program.step t = .localStep u := by
+ change (M.code (inc 0)).run M.publicData t = _
+ rw [hadd]
+ simp only [incInstr,Instr.run,BinaryOp.eval,u,t,Config.put,Function.update_of_ne (hcursor i),
+ Function.update_of_ne (hunit i),hc,hone,Nat.cast_add,Nat.cast_one]
+ have tail := ih (fun j => pc j.succ) (fun j => inc j.succ) (fun j => read j.succ)
+ (fun j => advance j.succ) (base+1) u rfl (Function.update_self ..)
+ (by change (Function.update (Function.update c.reg _ _) cursor _) unit = 1
+ rw [Function.update_of_ne hu, Function.update_of_ne (hunit i), hone])
+ (fun j => by
+ have h := cache j.succ
+ change c.privateMem ((base+(j.val+1) : ℕ) : Word w) = vals ls[j] at h
+ change c.privateMem ((base+1+j.val : ℕ) : Word w) = vals ls[j]
+ simpa only [Nat.add_assoc, Nat.add_comm 1] using h)
+ change Prefix M u _ {c with
+ pc := pc (Fin.last ls.length).succ
+ reg := Function.update (ls.foldl (setStatic ports vals) (Function.update (setStatic ports vals c.reg i) cursor ((base+1 : ℕ) : Word w)))
+ cursor ((base+1+ls.length : ℕ) : Word w)} at tail
+ rw [fold_cursor ports vals cursor hcursor, Function.update_idem,
+ show base+1+ls.length = base+(ls.length+1) by omega] at tail
+ rw [show 2*(i::ls).length = (2*ls.length+1)+1 by simp; omega, List.replicate_succ,List.replicate_succ]
+ exact .tick h₁ (.tick h₂ tail)
+
+end PairSimulation.LeafSourceLoad
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafCacheWrite.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafCacheWrite.lean
new file mode 100644
index 0000000000..2364207eb3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafCacheWrite.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.PairSimulationLeafCacheRead
+
+/-!
+# Storing the coefficient counter's scalar cache once per pair call
+
+Each register produced by the operand evaluator is written into its
+prescribed private cache cell. The two-instruction store and increment
+sequence has no external actions and preserves the source registers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSourceLoad
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {k w p r pubs : ℕ}
+
+/-- Store one computed operand at the private cache cursor. -/
+def storeInstr (src : Static k → Fin r) (cursor : Fin r) (next : Fin p) (i : Static k) : Instr w p r pubs :=
+ .storePrivate cursor (src i) next
+
+/-- The exact consecutive output words, final cursor and unchanged surrounding private state. -/
+structure Stored (c out : Config w p r) (cursor : Fin r) (base : ℕ) (xs : List (Word w)) : Prop where
+ persistent : out.persistent = c.persistent
+ cursor_end : out.reg cursor = ((base+xs.length : ℕ) : Word w)
+ frame : ∀ j, j ≠ cursor → out.reg j = c.reg j
+ values : ∀ i : Fin xs.length, out.privateMem ((base+i.val : ℕ) : Word w) = xs[i]
+ outside : ∀ a : Word w, a.val < base ∨ base+xs.length ≤ a.val → out.privateMem a = c.privateMem a
+
+theorem write_rows (M : Machine w p r pubs) (src : Static k → Fin r) (cursor unit : Fin r)
+ (hs : ∀ j, src j ≠ cursor) (hu : unit ≠ cursor) (ls : List (Static k)) (vals : Static k → Word w)
+ (pc : Fin (ls.length+1) → Fin p) (inc : Fin ls.length → Fin p)
+ (store : ∀ i : Fin ls.length, M.code (pc i.castSucc) = storeInstr src cursor (inc i) ls[i])
+ (advance : ∀ i : Fin ls.length, M.code (inc i) = incInstr cursor unit (pc i.succ))
+ (base : ℕ) (c : Config w p r) (entry : c.pc = pc 0)
+ (hc : c.reg cursor = (base : Word w)) (hone : c.reg unit = 1)
+ (ready : ∀ j, c.reg (src j) = vals j) (fit : base+ls.length ≤ 2^w) :
+ ∃ out, Prefix M c (List.replicate (2*ls.length) .tick) out ∧
+ out.pc = pc (Fin.last ls.length) ∧ Stored c out cursor base (ls.map vals) := by
+ induction ls generalizing c base with
+ | nil =>
+ exact ⟨c, .nil c, entry, rfl, hc, fun _ _ => rfl, fun i => Fin.elim0 i, fun _ _ => rfl⟩
+ | cons j ls ih =>
+ let t := c.store (inc 0) (base : Word w) (vals j)
+ let u := t.put (pc (Fin.succ 0)) cursor ((base+1 : ℕ) : Word w)
+ have hstore := store 0
+ change M.code (pc 0) = storeInstr src cursor (inc 0) j at hstore
+ have h₁ : M.program.step c = .localStep t := by
+ change (M.code c.pc).run M.publicData c = _
+ rw [entry,hstore]
+ simp only [storeInstr,Instr.run,hc,ready,t]
+ have h₂ : M.program.step t = .localStep u := by
+ change (M.code (inc 0)).run M.publicData t = _
+ rw [advance 0]
+ simp only [incInstr,Instr.run,BinaryOp.eval,t,u,Config.store,hc,hone,Nat.cast_add,Nat.cast_one]
+ have hlen : base+1+ls.length ≤ 2^w := by simp only [List.length_cons] at fit; omega
+ obtain ⟨out,tail,done,stored⟩ := ih (fun i => pc i.succ) (fun i => inc i.succ)
+ (fun i => store i.succ) (fun i => advance i.succ) (base+1) u rfl (Function.update_self ..)
+ (by change Function.update c.reg cursor _ unit = 1; rw [Function.update_of_ne hu,hone])
+ (fun i => by change Function.update c.reg cursor _ (src i) = _; rw [Function.update_of_ne (hs i),ready]) hlen
+ have run := Prefix.tick h₁ (Prefix.tick h₂ tail)
+ have ticks : 2*(j::ls).length = (2*ls.length+1)+1 := by simp; omega
+ rw [ticks,List.replicate_succ,List.replicate_succ]
+ refine ⟨out,run,done,stored.persistent,?_,?_,?_,?_⟩
+ · simpa only [List.length_map,List.length_cons,Nat.add_assoc,Nat.add_comm 1] using stored.cursor_end
+ · intro i hi
+ exact (stored.frame i hi).trans (Function.update_of_ne hi ..)
+ · intro i
+ have hb : base < 2^w := by omega
+ induction i using Fin.cases with
+ | zero =>
+ have keep := stored.outside (base : Word w) (.inl (by change base % _ < _; rw [Nat.mod_eq_of_lt hb]; omega))
+ change out.privateMem ((base+0 : ℕ) : Word w) = vals j
+ rw [Nat.add_zero,keep]
+ exact Function.update_self ..
+ | succ i =>
+ have h := stored.values i
+ change out.privateMem ((base+(i.val+1) : ℕ) : Word w) = (ls.map vals)[i]
+ simpa only [Nat.add_assoc,Nat.add_comm 1] using h
+ · intro a ha
+ have hx : a.val < base+1 ∨ base+1+(ls.map vals).length ≤ a.val := by
+ simp only [List.length_map,List.length_cons] at ha ⊢; omega
+ rw [stored.outside a hx]
+ apply Function.update_of_ne
+ intro he
+ have hb : base < 2^w := by omega
+ have hv : a.val = base := (congrArg Fin.val he).trans (Nat.mod_eq_of_lt hb)
+ simp only [List.length_map,List.length_cons] at ha
+ omega
+
+end PairSimulation.LeafSourceLoad
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafCachedSources.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafCachedSources.lean
new file mode 100644
index 0000000000..c5638e6444
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafCachedSources.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSourcePrelude
+import OAI.Computability.VPVNP.PairSimulationLeafCacheWrite
+
+/-! # The complete scalar source bank for a virtual leaf of a pair call -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSourceLoad
+
+open BurstRAM PrivateRAM RAMTape LeafRegisterBank PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {d e w k r p pubs : ℕ}
+
+theorem slot_offset (i : Fin (slots k).length) : ((slots k)[i]).offset = i.val := by
+ have hi : i.val < 4+k := by simpa only [length_slots] using i.isLt
+ have h : ((slots k).map Static.offset)[i.val]'(by simpa using hi) = i.val := by
+ simp only [slots_offsets,List.getElem_range]
+ simp only [List.getElem_map] at h
+ exact h
+
+/-- Private array at the offset reserved by the pair's leaf arena. -/
+def Cached (base : ℕ) (m : Word w → Word w) (vals : Static k → Word w) : Prop :=
+ ∀ j, m ((base+j.offset : ℕ) : Word w) = vals j
+
+theorem Stored.cached {c out : Config w p r} {cursor : Fin r} {base : ℕ} {vals : Static k → Word w}
+ (h : Stored c out cursor base ((slots k).map vals)) : Cached base out.privateMem vals := by
+ intro j
+ obtain ⟨i,hi,he⟩ := List.mem_iff_getElem.mp (mem_slots j)
+ let ix : Fin (slots k).length := ⟨i,hi⟩
+ have hix : (slots k)[ix] = j := he
+ have off : j.offset = i := hix ▸ slot_offset ix
+ rw [off]
+ have hv := h.values ⟨i, by simpa only [List.length_map] using hi⟩
+ have hm : i < ((slots k).map vals).length := by simpa only [List.length_map] using hi
+ change out.privateMem ((base+i : ℕ) : Word w) = ((slots k).map vals)[i]'hm at hv
+ simpa only [List.getElem_map, he] using hv
+
+/-- From the actual dynamic address and header, and the resident 38-word
+cache, furnish every input of the pointer and scalar-port initializer. -/
+theorem cachedSources (x : VirtualSite.Input d e w) (vals : Fin k → Word w)
+ (M : Machine w p r pubs) (ports : Source k ↪ Fin r) (site hdr base cursor unit : Fin r)
+ (pre : Fin 5 → Fin p) (pc : Fin ((slots k).length+1) → Fin p) (inc : Fin (slots k).length → Fin p)
+ (preRows : ∀ i, M.code (pre i) = prelude ports site hdr base cursor unit pre (pc 0) i)
+ (read : ∀ i : Fin (slots k).length, M.code (pc i.castSucc) = readInstr ports cursor (inc i) (slots k)[i])
+ (advance : ∀ i : Fin (slots k).length, M.code (inc i) = incInstr cursor unit (pc i.succ))
+ (wires : Wiring ports hdr base cursor unit) (cacheBase : ℕ) (c : Config w p r) (entry : c.pc = pre 0)
+ (ha : c.reg site = x.addrWord) (hh : c.reg hdr = x.headerWord) (hzero : x.initialWord = 0)
+ (hb : c.reg base = (cacheBase : Word w))
+ (ready : Cached cacheBase c.privateMem (fun i : Static k => sourceWord x vals i.dest)) :
+ ∃ out, Prefix M c (List.replicate (5+2*(4+k)) .tick) out ∧ out.pc = pc (Fin.last (slots k).length) ∧
+ (∀ j, out.reg (ports j) = sourceWord x vals j) ∧
+ out.reg cursor = ((cacheBase+(4+k) : ℕ) : Word w) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ ∀ i, (∀ j, i ≠ ports j) → i ≠ cursor → i ≠ unit → out.reg i = c.reg i := by
+ let args := fun i : Static k => sourceWord x vals i.dest
+ let mid : Config w p r := {c with pc := pc 0, reg := prepBank ports site hdr base cursor unit c.reg}
+ have start := prep_run M ports site hdr base cursor unit pre (pc 0) preRows wires c entry
+ have hc : mid.reg cursor = (cacheBase : Word w) := by simp [mid,prepBank,wires.different,hb]
+ have hone : mid.reg unit = 1 := Function.update_self ..
+ have hcache (i : Fin (slots k).length) : mid.privateMem ((cacheBase+i.val : ℕ) : Word w) = args (slots k)[i] := by
+ simpa only [slot_offset] using ready (slots k)[i]
+ have body := cached_rows M ports cursor unit (fun i => wires.cursor_disjoint i.dest)
+ (fun i => wires.unit_disjoint i.dest) wires.different.symm args (slots k) pc inc read advance cacheBase mid
+ rfl hc hone hcache
+ let dst := (slots k).foldl (setStatic ports args) mid.reg
+ let out := {mid with
+ pc := pc (Fin.last (slots k).length)
+ reg := Function.update dst cursor ((cacheBase+(slots k).length : ℕ) : Word w)}
+ have run := start.append body
+ change Prefix M c (List.replicate 5 .tick ++ List.replicate (2*(slots k).length) .tick) out at run
+ rw [← List.replicate_add,length_slots] at run
+ refine ⟨out,run,rfl,?_,?_,rfl,rfl,?_⟩
+ · intro j
+ change Function.update dst cursor _ (ports j) = _
+ rw [Function.update_of_ne (wires.cursor_disjoint j).symm]
+ have readAt (i : Static k) : dst (ports i.dest) = sourceWord x vals i.dest := by
+ rw [show dst (ports i.dest) = _ from fold_at ports args (slots k) mid.reg i, ite_eq_left (mem_slots i)]
+ have other (j : Source k) (h : ∀ i : Static k, j ≠ i.dest) : dst (ports j) = mid.reg (ports j) :=
+ fold_outside ports args _ _ _ (fun i => ports.injective.ne (h i))
+ cases j with
+ | d | width | bucket | fuel | operand _ => first | exact readAt .d | exact readAt .width | exact readAt .bucket | exact readAt .fuel | exact readAt (.operand _)
+ | initial | address | header =>
+ rw [other _ (by intro i; cases i <;> simp [Static.dest])]
+ simp [mid,prepBank,(wires.unit_disjoint _).symm,(wires.cursor_disjoint _).symm,sourceWord,hzero,ha,hh]
+ · change Function.update dst cursor _ cursor = _
+ rw [Function.update_self, length_slots]
+ · intro i hi hcur hu
+ change Function.update dst cursor _ i = _
+ rw [Function.update_of_ne hcur]
+ unfold dst
+ rw [fold_outside ports args _ _ i (fun j => hi j.dest)]
+ exact prep_preserve ports site hdr base cursor unit c.reg i hi hcur hu
+
+end PairSimulation.LeafSourceLoad
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafCapacity.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafCapacity.lean
new file mode 100644
index 0000000000..be49eacebb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafCapacity.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.PairSimulationLeafScalarStartup
+
+/-! # Native computation of the verifier's private port capacity -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafCapacity
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Read n, square to its eighth power, retain that factor, then square to its
+thirty-second power and multiply. The stride can immediately be used by the
+pointer allocation table. -/
+def instruction (pc : Fin 8 → Fin p) (dst tmp : Fin r) (nPub : Fin k) (done : Fin p) : Fin 8 → Instr w p r k :=
+ ![.publicWord dst nPub (pc 1), .binary .mul dst dst dst (pc 2), .binary .mul dst dst dst (pc 3),
+ .binary .mul dst dst dst (pc 4), .copy tmp dst (pc 5), .binary .mul dst dst dst (pc 6),
+ .binary .mul dst dst dst (pc 7), .binary .mul dst dst tmp done]
+
+theorem resize_instruction (pc : Fin 8 → Fin p) (dst tmp : Fin r) (nPub : Fin k) (done : Fin p)
+ (i : Fin 8) : (instruction (w := 1) pc dst tmp nPub done i).resize w = instruction pc dst tmp nPub done i := by
+ fin_cases i <;> rfl
+
+theorem run (M : Machine w p r k) (pc : Fin 8 → Fin p) (dst tmp : Fin r) (sep : dst ≠ tmp) (nPub : Fin k)
+ (done : Fin p) (link : ∀ i, M.code (pc i) = instruction pc dst tmp nPub done i)
+ (c : Config w p r) (hc : c.pc = pc 0) (n : ℕ) (hpub : M.publicData nPub = (n : Word w)) :
+ ∃ out, Prefix M c (List.replicate 8 .tick) out ∧ out.pc = done ∧ out.reg dst = ((n^40 : ℕ) : Word w) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ ∀ i, i ≠ dst → i ≠ tmp → out.reg i = c.reg i := by
+ let a := (n : Word w)
+ let s₁ := c.put (pc 1) dst a
+ let s₂ := s₁.put (pc 2) dst (a^2)
+ let s₃ := s₂.put (pc 3) dst (a^4)
+ let s₄ := s₃.put (pc 4) dst (a^8)
+ let s₅ := s₄.put (pc 5) tmp (a^8)
+ let s₆ := s₅.put (pc 6) dst (a^16)
+ let s₇ := s₆.put (pc 7) dst (a^32)
+ let out := s₇.put done dst (a^40)
+ have step (i : Fin 8) (s : Config w p r) (hs : s.pc = pc i) :
+ M.program.step s = (instruction pc dst tmp nPub done i).run M.publicData s := by
+ change (M.code s.pc).run _ _ = _; rw [hs,link]
+ refine ⟨out, .tick (next := s₁) ?_ (.tick (next := s₂) ?_ (.tick (next := s₃) ?_ (.tick (next := s₄) ?_ (.tick (next := s₅) ?_ (.tick (next := s₆) ?_ (.tick (next := s₇) ?_ (.tick (next := out) ?_ (.nil _)))))))), rfl,
+ by simp [out,a,Config.put],rfl,rfl,?_⟩
+ · rw [step 0 c hc]; simp [instruction,Instr.run,s₁,hpub,a]
+ · rw [step 1 s₁ rfl]; simp [instruction,Instr.run,s₁,s₂,Config.put,BinaryOp.eval,pow_two]
+ · rw [step 2 s₂ rfl]; simp [instruction,Instr.run,s₂,s₃,Config.put,BinaryOp.eval,← pow_add]
+ · rw [step 3 s₃ rfl]; simp [instruction,Instr.run,s₃,s₄,Config.put,BinaryOp.eval,← pow_add]
+ · rw [step 4 s₄ rfl]; simp [instruction,Instr.run,s₄,s₅,Config.put]
+ · rw [step 5 s₅ rfl]; simp [instruction,Instr.run,s₄,s₅,s₆,Config.put,BinaryOp.eval,sep,← pow_add]
+ · rw [step 6 s₆ rfl]; simp [instruction,Instr.run,s₆,s₇,Config.put,BinaryOp.eval,← pow_add]
+ · rw [step 7 s₇ rfl]; simp [instruction,Instr.run,s₅,s₆,s₇,out,Config.put,BinaryOp.eval,sep.symm,← pow_add]
+ · intro i hd ht; simp [out,s₇,s₆,s₅,s₄,s₃,s₂,s₁,Config.put,Function.update_of_ne hd,Function.update_of_ne ht]
+
+end PairSimulation.LeafCapacity
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafCoordinates.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafCoordinates.lean
new file mode 100644
index 0000000000..e7716b6eb4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafCoordinates.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.CompressorRecordsCursorCoordinates
+import OAI.Computability.VPVNP.PairTraversalRows
+
+/-! # Decoding a cursor processor from its initial traversal row -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafCoordinates
+
+open CursorNetwork CursorRouting Compression LocalHistory TraversalRows
+
+variable {b l a p : ℕ} {S : Type} [Fintype S]
+
+/-- The compressor encodes its first binary coordinate at the most
+significant bit of the integer. -/
+theorem index_bit {n : ℕ} (x : BitWord n) (i : Fin n) :
+ (bitWordFinEquiv n x).val.testBit i.val = finTwoEquiv (x i.rev) := by
+ induction n with
+ | zero => exact i.elim0
+ | succ n ih =>
+ rw [bitWordFinEquiv_val, Nat.add_comm, Nat.testBit_two_pow_mul_add _ (bitWordFinEquiv n (Fin.tail x)).isLt]
+ induction i using Fin.lastCases with
+ | last =>
+ simp only [Fin.val_last,Nat.lt_irrefl,↓reduceIte,Nat.sub_self,Fin.rev_last]
+ generalize x 0 = bit
+ fin_cases bit <;> decide
+ | cast i =>
+ simpa [i.isLt,Fin.rev_castSucc,Fin.tail] using ih (Fin.tail x) i
+
+/-- Undo the order change between the cursor's little-endian address and
+the compressor's two big-endian coordinate blocks. -/
+theorem site_number (v : Position (b+l)) :
+ let u := lanePositions (cursorCoordinateLabels b l) v
+ v.2.val = 2^b * (bitWordFinEquiv l u.2).val + (bitWordFinEquiv b u.1.2).val := by
+ intro u
+ let low := (bitWordFinEquiv b u.1.2).val
+ let high := (bitWordFinEquiv l u.2).val
+ have hlo : low < 2^b := (bitWordFinEquiv b u.1.2).isLt
+ have hhi : high < 2^l := (bitWordFinEquiv l u.2).isLt
+ have hsum : 2^b * high + low < 2^(b+l) := calc
+ 2^b * high + low < 2^b * high + 2^b := Nat.add_lt_add_left hlo _
+ _ = 2^b * (high+1) := (Nat.mul_succ ..).symm
+ _ ≤ 2^b * 2^l := Nat.mul_le_mul_left _ hhi
+ _ = _ := (Nat.pow_add ..).symm
+ apply Nat.eq_of_testBit_eq
+ intro t
+ by_cases h : t < b+l
+ · rw [Nat.testBit_two_pow_mul_add _ hlo]
+ by_cases ht : t < b
+ · let j : Fin b := ⟨t,ht⟩
+ rw [ite_eq_left ht]
+ change v.2.val.testBit (j.castAdd l).val = (bitWordFinEquiv b u.1.2).val.testBit j.val
+ rw [← addressWord_bit, index_bit]
+ change finTwoEquiv (addressWord _ v.2 (j.castAdd l)) =
+ finTwoEquiv (addressWord _ v.2 (j.rev.rev.castAdd l))
+ rw [Fin.rev_rev]
+ · let j : Fin l := ⟨t-b,by omega⟩
+ have hj : (j.natAdd b).val = t := by change b+(t-b)=t; omega
+ rw [ite_eq_right ht, ← hj, ← addressWord_bit v.2 (j.natAdd b), hj]
+ change _ = (bitWordFinEquiv l u.2).val.testBit j.val
+ rw [index_bit]
+ change finTwoEquiv (addressWord _ v.2 (j.natAdd b)) =
+ finTwoEquiv (addressWord _ v.2 (j.rev.rev.natAdd b))
+ rw [Fin.rev_rev]
+ · have hp := Nat.pow_le_pow_right (by decide : 1 ≤ 2) (Nat.le_of_not_gt h)
+ exact (Nat.testBit_lt_two_pow (v.2.isLt.trans_le hp)).trans (Nat.testBit_lt_two_pow (hsum.trans_le hp)).symm
+
+theorem leaf_row (hD : 1 < b+l) (hd : 2+p=2^a) (bits : S → ℕ)
+ (base cap : ℕ) (v : Position (b+l)) :
+ let X := cursorState (cursorCoordinateLabels b l) hD hd bits
+ let u := lanePositions (cursorCoordinateLabels b l) v
+ let low := (bitWordFinEquiv b u.1.2).val
+ let high := (bitWordFinEquiv l u.2).val
+ (sitePointers cap base (siteOrder X) u).1 = base + (cap+2)*((v.1.val*2^b+low)*2^l+high) ∧
+ v.2.val = 2^b*high + low := by
+ intro X u low high
+ refine ⟨?_,site_number v⟩
+ change base + (cap+2)*(high+2^l*(low+2^b*v.1.val)) = _
+ ac_rfl
+
+end PairSimulation.LeafCoordinates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafCount.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafCount.lean
new file mode 100644
index 0000000000..ac9eee69fc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafCount.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.PairSimulationLeafValidation
+import OAI.Computability.VPVNP.RAMProcessorChoiceCount
+
+/-! # The exact path count of the virtual validator on independent half-wires -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafStartup
+
+open BurstRAM RAMLayout RAMTape LiveProgram PrivateRAM CursorNetwork CursorRouting
+open RAMTape.SiteProcessorPorts
+
+set_option synthInstance.maxSize 10000
+
+variable {d e w k p : ℕ} (r : ℕ) (x : VirtualSite.Input d e w) (args : Fin k → Word w)
+
+/-- The site validator that first checks its guard, generates a bounded choice stream, then
+tests that stream against the virtual machine. -/
+def processor (T : Template p r k) : FiniteRoutine (Port r k) :=
+ (guard r k).followedBy ((stream r k).followedBy (perChoice r (expr k) T))
+
+/-- Step budget for the guard, successor checks, choice generation and per-choice validation at
+this site. -/
+def steps :=
+ perChoiceBudget d e w r x.fuel + (4*choiceBound e w x.fuel+1) +
+ 3 + Successors.steps d w (decide (0 < x.v.val))
+
+private theorem readyToChoose :
+ Function.update (Function.update (guarded r x args) (pub r (expr k) ProcessorPublic.budgetPort)
+ (List.replicate (choiceBound e w x.fuel) true)) (native r (expr k) (.test .choices)) [] =
+ guarded r x args := by
+ have hb := guarded_public r x args ProcessorPublic.budgetPort (by decide)
+ have hc := guarded_native r x args (.test .choices)
+ change guarded r x args (pub r (expr k) ProcessorPublic.budgetPort) =
+ List.replicate (choiceBound e w x.fuel) true at hb
+ change guarded r x args (native r (expr k) (.test .choices)) = [] at hc
+ rw [← hb, Function.update_eq_self, ← hc, Function.update_eq_self]
+
+variable (T : Template p r k)
+
+/-- Number of incident paths of the instantiated virtual machine for this site's fuel, initial
+and header words, and incident bits. -/
+noncomputable def pathCount := Nat.card ((T.instantiate w args).IncidentPaths x.fuel x.initialWord x.headerWord
+ x.hw x.hc x.v (RAMLayout.incidentBits x.sends x.v))
+
+theorem choices_sum :
+ ((ProcessorChoices.words (choiceBound e w x.fuel)).map fun bs => (accepts r x args T bs).toNat).sum =
+ pathCount r x args T := by
+ let shared := (sendArraysEquiv d (2^e) w).symm x.sends
+ have h := ProcessorChoices.site_choices (T.instantiate w args) x.fuel x.initialWord (fun _ => x.headerWord)
+ x.hw x.hc shared x.v
+ simpa only [BurstRAM.incidentBits, shared, Equiv.apply_symm_apply, pathCount, accepts, choiceBound] using h
+
+private theorem stream_verdict (hv : x.valid) (t : ℕ) (ht : perChoiceBudget d e w r x.fuel ≤ t) :
+ let proc := (stream r k).followedBy (perChoice r (expr k) T)
+ let clock := t + 4*choiceBound e w x.fuel + 1
+ (∀ c, proc.body.count c clock (guarded r x args) = pathCount r x args T) ∧
+ (∀ c, proc.body.AllStops c clock (guarded r x args)) := by
+ intro proc clock
+ let credits := List.replicate (choiceBound e w x.fuel) true
+ let creditPort := pub r (expr k) ProcessorPublic.budgetPort
+ let streamPort := native r (expr k) (.test .choices)
+ have hne : creditPort ≠ streamPort := by simp [creditPort, streamPort, pub, native]
+ have rs := readyToChoose r x args
+ change Function.update (Function.update (guarded r x args) creditPort credits) streamPort [] = _ at rs
+ constructor
+ · intro c
+ let cont := (perChoice r (expr k) T).body.count c
+ have h := ProcessorChoices.count creditPort streamPort hne (guarded r x args) credits cont t
+ rw [rs, show credits.length = choiceBound e w x.fuel from List.length_replicate] at h
+ change ((stream r k).body.followedBy (perChoice r (expr k) T).body).count c clock _ = _
+ rw [Routine.count_followedBy, show (stream r k).body.count cont clock (guarded r x args) = _ from h]
+ have per (bs : List Bool) : cont t (Function.update (Function.update (guarded r x args) creditPort [])
+ streamPort bs) = (accepts r x args T bs).toNat := (perChoice_verdict r x args T bs hv t ht).1 c
+ simp only [per, choices_sum]
+ · intro c
+ let cont := (perChoice r (expr k) T).body.AllStops c
+ have h := ProcessorChoices.allStops_iff creditPort streamPort hne (guarded r x args) credits cont t
+ rw [rs, show credits.length = choiceBound e w x.fuel from List.length_replicate] at h
+ change ((stream r k).body.followedBy (perChoice r (expr k) T).body).AllStops c clock _
+ rw [Routine.allStops_followedBy]
+ exact h.mpr fun bs _ => (perChoice_verdict r x args T bs hv t ht).2 c
+
+/-- Every possible guard rejection, nominated finite string, private call, and
+sorting pass is counted by the fixed finite stack program. -/
+theorem processor_spec (t : ℕ) (ht : steps r x ≤ t) :
+ (∀ c, (processor r T).body.count c t (bank r x args) = pathCount r x args T) ∧
+ (∀ c, (processor r T).body.AllStops c t (bank r x args)) := by
+ classical
+ let read := Successors.steps d w (decide (0 < x.v.val))
+ let nom := 4*choiceBound e w x.fuel + 1
+ let inner := t-(2+read+nom)
+ have ht' : perChoiceBudget d e w r x.fuel + nom + 3 + read ≤ t := ht
+ have hin : perChoiceBudget d e w r x.fuel ≤ inner := by dsimp [inner]; omega
+ have hclock : t = (inner + 4*choiceBound e w x.fuel + 1) + 2 + read := by dsimp [nom,inner] at *; omega
+ let proc := (stream r k).followedBy (perChoice r (expr k) T)
+ have hi (hv : x.valid) := stream_verdict r x args T hv inner hin
+ constructor
+ · intro c
+ let cont := proc.body.count c
+ let close := fun f out => cont f (installStacks (guardPort r k) (bank r x args) out)
+ have hg := Successors.checked_shared_count x.hw x.hc x.sends (bank r x args ∘ guardPort r k) x.v x.initialWord
+ rfl rfl rfl rfl rfl rfl rfl (fun _ _ => rfl) close (inner+4*choiceBound e w x.fuel+1)
+ change ((guard r k).body.followedBy proc.body).count c t _ = _
+ rw [Routine.count_followedBy, guard, FiniteRoutine.count_onPorts _ _ (guardPort_injective r k), hclock]
+ dsimp only at hg
+ by_cases hv : x.valid
+ · rw [ite_eq_left (show SuccessorSendOK _ _ _ _ ∧ SuccessorReceiveOK _ _ _ _ from hv)] at hg
+ exact hg.trans ((hi hv).1 c)
+ · rw [ite_eq_right (show ¬(SuccessorSendOK _ _ _ _ ∧ SuccessorReceiveOK _ _ _ _) from hv)] at hg
+ refine hg.trans ?_
+ rw [← choices_sum]
+ simp [accepts_invalid r x args T _ hv]
+ · intro c
+ let cont := proc.body.AllStops c
+ let close := fun f out => cont f (installStacks (guardPort r k) (bank r x args) out)
+ let rem := inner+4*choiceBound e w x.fuel
+ have hg := Successors.checked_shared_allStops x.hw x.hc x.sends (bank r x args ∘ guardPort r k) x.v x.initialWord
+ rfl rfl rfl rfl rfl rfl rfl (fun _ _ => rfl) close rem
+ change ((guard r k).body.followedBy proc.body).AllStops c t _
+ rw [Routine.allStops_followedBy, guard, FiniteRoutine.allStops_onPorts _ _ (guardPort_injective r k)]
+ have he : t = rem+3+read := by dsimp [rem]; omega
+ rw [he]
+ exact hg.mpr fun hv => (hi hv).2 c
+
+section Cursor
+
+variable {L : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout L n a H w}
+ (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (v : Position d) (buf : Buffers d (2^e) w)
+
+/-- The virtual RAM uses its actual 52 registers and 34 public operands.
+After the cursor routing tests, the cursor-zero computation realizes the
+initial network factor on the supplied four independent buffers. -/
+theorem auxiliary_count [NeZero d] (hz : v.1 = 0)
+ (hroute : routeAccept (2^e) w v (readBuffer buf) = true)
+ (t : ℕ) (ht : steps 52 (auxiliary D hw hc v buf) ≤ t) :
+ let x := auxiliary D hw hc v buf
+ (∀ c, (processor 52 PrimedCounter.Program.table).body.count c t (bank 52 x D.pub) =
+ Nat.card {bs : List Bool // initialAccept D.machine D.fuel 0 (D.initial v.2) hw hc v buf bs = true}) ∧
+ (∀ c, (processor 52 PrimedCounter.Program.table).body.AllStops c t (bank 52 x D.pub)) := by
+ intro x
+ have h := processor_spec 52 x D.pub PrimedCounter.Program.table t ht
+ refine ⟨fun c => (h.1 c).trans (Nat.card_congr ?_), h.2⟩
+ apply Equiv.subtypeEquivRight
+ intro bs
+ change (D.machine.validateIncident D.fuel 0 (D.initial v.2) hw hc v.2
+ (RAMLayout.incidentBits (sends v buf) v.2) bs).1.isSome = true ↔ _
+ rw [sends_incident]
+ simp [initialAccept, hroute, hz]
+
+end Cursor
+end PairSimulation.LeafStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldCode.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldCode.lean
new file mode 100644
index 0000000000..0c2634aed4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldCode.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.PairSimulationLeafFieldSources
+
+/-!
+# Private RAM instructions that stage one scalar leaf field
+
+Only the destination length, value, and one arithmetic temporary are
+written. Source words occupy a fixed register bank shared by every field.
+The field number and its operand register are selected by finite control.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafStartup.Staging
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord
+
+/-- The three writable scalar-staging destinations holding the field length, field value and
+arithmetic temporary. -/
+inductive Out | len | value | tmp deriving DecidableEq
+instance : Fintype Out := derive_fintype% _
+/-- Named staging registers for the three outputs, constants and site geometry, and the virtual
+machine's indexed public operands. -/
+inductive Reg (k : ℕ)
+ | out (i : Out) | zero | one | d | width | bucket | fuel | address | initial | header | operand (i : Fin k)
+ deriving DecidableEq, Fintype
+
+/-- A scalar-staging expression that copies one register or applies a binary word operation to
+two registers. -/
+inductive Rhs (k : ℕ)
+ | copy (src : Reg k)
+ | binary (op : BinaryOp) (a b : Reg k)
+
+/-- One scalar-staging assignment, pairing a writable destination with the expression whose
+word it receives. -/
+abbrev Line (k : ℕ) := Out × Rhs k
+
+variable {k w p r pubs : ℕ}
+
+/-- The fixed assignments that compute a field's stack length and source word from the leaf's
+geometry and cached operands. -/
+def code : Field k → List (Line k)
+ | .blank | .incident => [(.len,.copy .zero),(.value,.copy .one)]
+ | .zeroWord => [(.len,.copy .width),(.value,.copy .zero)]
+ | .address => [(.len,.copy .d),(.value,.copy .address)]
+ | .addressWidth => [(.len,.copy .d),(.value,.copy .one)]
+ | .width => [(.len,.copy .width),(.value,.copy .one)]
+ | .slots => [(.len,.binary .add .bucket .bucket),(.len,.binary .add (.out .len) (.out .len)),(.value,.copy .one)]
+ | .bucket => [(.len,.copy .bucket),(.value,.copy .one)]
+ | .fuel => [(.len,.copy .fuel),(.value,.copy .one)]
+ | .siteCredit => [(.len,.binary .add .bucket .bucket),(.len,.binary .sub (.out .len) .one),(.value,.copy .one)]
+ | .choices => [(.tmp,.binary .add .bucket .bucket),(.len,.binary .add .fuel .width),
+ (.len,.binary .mul (.out .tmp) (.out .len)),(.value,.copy .one)]
+ | .cap => [(.value,.binary .shiftLeft .one .d),(.value,.binary .mul (.out .value) .bucket),(.len,.copy .width)]
+ | .lower => [(.value,.binary .mul .address .bucket),(.len,.copy .width)]
+ | .upper => [(.value,.binary .add .address .one),(.value,.binary .mul (.out .value) .bucket),(.len,.copy .width)]
+ | .initial => [(.len,.copy .width),(.value,.copy .initial)]
+ | .siteWord => [(.len,.copy .width),(.value,.copy .address)]
+ | .header => [(.len,.copy .width),(.value,.copy .header)]
+ | .operand i => [(.len,.copy .width),(.value,.copy (.operand i))]
+
+theorem length_le (f : Field k) : (code f).length ≤ 4 := by cases f <;> simp [code]
+
+/-- Compile a scalar-staging assignment to a host copy or binary instruction that jumps to the
+supplied continuation. -/
+def instruction (ports : Reg k ↪ Fin r) (next : Fin p) (line : Line k) : Instr w p r pubs :=
+ match line.2 with
+ | .copy src => .copy (ports (.out line.1)) (ports src) next
+ | .binary op a b => .binary op (ports (.out line.1)) (ports a) (ports b) next
+
+theorem resize_instruction (ports : Reg k ↪ Fin r) (next : Fin p) (l : Line k) :
+ (instruction (w := 1) (pubs := pubs) ports next l).resize w = instruction ports next l := by
+ obtain ⟨o,s⟩ := l
+ cases s <;> rfl
+
+/-- Evaluate a scalar-staging expression against the current named register values using
+machine-word arithmetic. -/
+def Rhs.eval (bank : Reg k → Word w) : Rhs k → Word w
+ | .copy src => bank src
+ | .binary op a b => op.eval (bank a) (bank b)
+
+/-- Update the named destination register with the value of one staging assignment. -/
+def applyLine (bank : Reg k → Word w) (l : Line k) : Reg k → Word w :=
+ Function.update bank (.out l.1) (l.2.eval bank)
+
+/-- Perform a staging assignment in the host register bank using the physical placement of its
+source and destination registers. -/
+def applyPhysical (ports : Reg k ↪ Fin r) (bank : Fin r → Word w) (l : Line k) : Fin r → Word w :=
+ Function.update bank (ports (.out l.1)) (l.2.eval (bank ∘ ports))
+
+theorem physical_at (ports : Reg k ↪ Fin r) (ls : List (Line k)) (bank : Fin r → Word w) :
+ ls.foldl (applyPhysical ports) bank ∘ ports = ls.foldl applyLine (bank ∘ ports) := by
+ induction ls generalizing bank with
+ | nil => rfl
+ | cons l ls ih =>
+ simp only [List.foldl_cons, ih]
+ congr 1
+ funext i
+ by_cases he : i = .out l.1
+ · subst i; simp [applyPhysical, applyLine]
+ · simp [applyPhysical,applyLine,he,ports.injective.ne he]
+
+theorem physical_outside (ports : Reg k ↪ Fin r) (ls : List (Line k)) (bank : Fin r → Word w)
+ (j : Fin r) (h : ∀ o, j ≠ ports (.out o)) : ls.foldl (applyPhysical ports) bank j = bank j := by
+ induction ls generalizing bank with
+ | nil => rfl
+ | cons l ls ih => simp only [List.foldl_cons, ih, applyPhysical, Function.update_of_ne (h l.1)]
+
+/-- Each row makes an actual private step in the supplied parent table. -/
+theorem run (M : Machine w p r pubs) (ports : Reg k ↪ Fin r) (ls : List (Line k))
+ (pc : Fin (ls.length+1) → Fin p)
+ (link : ∀ i : Fin ls.length, M.code (pc i.castSucc) = instruction ports (pc i.succ) ls[i])
+ (c : Config w p r) (entry : c.pc = pc 0) :
+ Prefix M c (List.replicate ls.length .tick)
+ {c with pc := pc (Fin.last ls.length), reg := ls.foldl (applyPhysical ports) c.reg} := by
+ induction ls generalizing c with
+ | nil =>
+ change Prefix M c [] {c with pc := pc (Fin.last 0)}
+ rw [show Fin.last 0 = 0 from rfl, ← entry]
+ exact .nil c
+ | cons l ls ih =>
+ let u : Config w p r := {c with pc := pc (Fin.succ 0), reg := applyPhysical ports c.reg l}
+ have h := link 0
+ have step : M.program.step c = .localStep u := by
+ change (M.code c.pc).run M.publicData c = _
+ rw [entry]
+ change M.code (pc 0) = instruction ports (pc (Fin.succ 0)) l at h
+ rw [h]
+ obtain ⟨dst,rhs⟩ := l
+ cases rhs <;> rfl
+ exact .tick step (ih (fun i => pc i.succ) (fun i => link i.succ) u rfl)
+
+end PairSimulation.LeafStartup.Staging
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldCopy.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldCopy.lean
new file mode 100644
index 0000000000..9cdceb2832
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldCopy.lean
@@ -0,0 +1,213 @@
+import OAI.Computability.VPVNP.PairSimulationPrivateFields
+import OAI.Computability.VPVNP.PairSimulationStackMemory
+
+/-!
+# Moving a logical-order half-wire field into a private bit stack
+
+The selected half-wire is stored in increasing logical order. A stack grows
+upwards with its first logical bit at the highest occupied address. This
+fixed five-row fragment therefore advances the source and retreats the
+destination. Missing chain endpoints use the same loop with a zero source.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafFieldCopy
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {bits p r k : ℕ}
+
+/-- Encode a natural address in a machine word. -/
+abbrev word (bits n : ℕ) : Word bits := (n : Word bits)
+
+/-- Read a resident half-wire cell or supply the clamped zero bit. -/
+inductive Source | resident | zero deriving DecidableEq
+
+/-- Word returned by this source at the current cursor. -/
+def Source.value (m : Word bits → Word bits) (a : Word bits) : Source → Word bits
+ | .resident => m a
+ | .zero => 0
+
+/-- Source cursor, destination base, exclusive destination cursor, unit, temporary. -/
+def instruction (source : Source) (pc : Fin 5 → Fin p) (reg : Fin 5 ↪ Fin r) (done : Fin p) :
+ Fin 5 → Instr bits p r k :=
+ ![.jumpEq (reg 2) (reg 1) done (pc 1),
+ .binary .sub (reg 2) (reg 2) (reg 3) (pc 2),
+ (match source with
+ | .resident => .loadPrivate (reg 4) (reg 0) (pc 3)
+ | .zero => .constant (reg 4) 0 (pc 3)),
+ .storePrivate (reg 2) (reg 4) (pc 4),
+ .binary .add (reg 0) (reg 0) (reg 3) (pc 0)]
+
+theorem resize_instruction (source : Source) (pc : Fin 5 → Fin p) (reg : Fin 5 ↪ Fin r)
+ (done : Fin p) (i : Fin 5) :
+ (instruction (bits := 1) (k := k) source pc reg done i).resize bits =
+ instruction source pc reg done i := by cases source <;> fin_cases i <;> rfl
+
+/-- The host instruction table contains the five-row descending copy loop. -/
+def Linked (M : Machine bits p r k) (source : Source) (pc : Fin 5 → Fin p) (reg : Fin 5 ↪ Fin r)
+ (done : Fin p) := ∀ i, M.code (pc i) = instruction source pc reg done i
+
+/-- Write a bit list into private stack memory with its head at the highest address. -/
+def place (lo : ℕ) : List Bool → (Word bits → Word bits) → Word bits → Word bits
+ | [], m => m
+ | b :: bs, m => place lo bs (Function.update m (word bits (lo+bs.length)) (PrivateFields.bitValue bits b))
+
+theorem place_outside (lo : ℕ) (bs : List Bool) (m : Word bits → Word bits) (a : Word bits)
+ (fit : lo+bs.length ≤ 2^bits) (ha : a.val < lo ∨ lo+bs.length ≤ a.val) :
+ place lo bs m a = m a := by
+ induction bs generalizing m with
+ | nil => rfl
+ | cons b bs ih =>
+ simp only [List.length_cons] at fit ha
+ rw [place, ih _ (by omega) (by omega)]
+ apply Function.update_of_ne
+ intro h
+ have e := congrArg Fin.val h
+ change a.val = (lo+bs.length) % 2^bits at e
+ rw [Nat.mod_eq_of_lt (by omega)] at e
+ omega
+
+theorem place_at (lo : ℕ) (pre : List Bool) (b : Bool) (tail : List Bool) (m : Word bits → Word bits)
+ (fit : lo+(pre++b::tail).length ≤ 2^bits) :
+ place lo (pre++b::tail) m (word bits (lo+tail.length)) = PrivateFields.bitValue bits b := by
+ induction pre generalizing m with
+ | nil =>
+ change place lo tail _ _ = _
+ simp only [List.nil_append, List.length_cons] at fit
+ have hf : lo+tail.length < 2^bits := by omega
+ rw [place_outside _ _ _ _ hf.le (.inr (by change _ ≤ _ % _; rw [Nat.mod_eq_of_lt hf]))]
+ exact Function.update_self ..
+ | cons x pre ih =>
+ apply ih
+ simp only [List.length_append, List.length_cons] at *
+ omega
+
+variable {M : Machine bits p r k} {source : Source} {pc : Fin 5 → Fin p} {reg : Fin 5 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (link : Linked M source pc reg done) (i : Fin 5) (c : Config bits p r)
+ (hc : c.pc = pc i) : M.program.step c = (instruction source pc reg done i).run M.publicData c := by
+ simp [Machine.program, hc, link i]
+
+private theorem iteration {src dst : ℕ} (link : Linked M source pc reg done) (c : Config bits p r)
+ (hc : c.pc = pc 0) (hs : c.reg (reg 0) = word bits src)
+ (hd : c.reg (reg 2) = word bits (dst+1)) (hneq : c.reg (reg 2) ≠ c.reg (reg 1))
+ (h1 : c.reg (reg 3) = 1) (b : Bool)
+ (value : (source.value c.privateMem (word bits src)) =
+ PrivateFields.bitValue bits b) :
+ ∃ out, Prefix M c (List.replicate 5 .tick) out ∧ out.pc = pc 0 ∧
+ out.reg (reg 0) = word bits (src+1) ∧ out.reg (reg 2) = word bits dst ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j) ∧
+ out.privateMem = Function.update c.privateMem (word bits dst) (PrivateFields.bitValue bits b) ∧
+ out.persistent = c.persistent := by
+ let a := { c with pc := pc 1 }
+ let d := a.put (pc 2) (reg 2) (word bits dst)
+ let v := d.put (pc 3) (reg 4) (PrivateFields.bitValue bits b)
+ let m := v.store (pc 4) (word bits dst) (PrivateFields.bitValue bits b)
+ let out := m.put (pc 0) (reg 0) (word bits (src+1))
+ have s0 : M.program.step c = .localStep a := by
+ rw [step_at link 0 c hc]
+ simp [instruction, Instr.run, hneq, a]
+ have s1 : M.program.step a = .localStep d := by
+ rw [step_at link 1 a rfl]
+ simp [instruction, Instr.run, BinaryOp.eval, d, a, hd, h1, word]
+ have s2 : M.program.step d = .localStep v := by
+ rw [step_at link 2 d rfl]
+ cases source <;> simp_all [instruction, Instr.run, d, v, a, Config.put, Source.value]
+ have s3 : M.program.step v = .localStep m := by
+ rw [step_at link 3 v rfl]
+ simp [instruction, Instr.run, v, m, d, Config.put]
+ have s4 : M.program.step m = .localStep out := by
+ rw [step_at link 4 m rfl]
+ simp [instruction, Instr.run, BinaryOp.eval, m, out, v, d, a, Config.store, Config.put, hs, h1, word]
+ refine ⟨out, .tick s0 (.tick s1 (.tick s2 (.tick s3 (.tick s4 (.nil _))))),
+ rfl, by simp [out], by simp [out,m,v,d,Config.put,Config.store], ?_, rfl, rfl⟩
+ intro j h0 h2 h4
+ simp [out,m,v,d,a,Config.put,Config.store,Function.update_of_ne h0,Function.update_of_ne h2,
+ Function.update_of_ne h4]
+
+/-- Exact native result, with the unrelated registers and cells framed. -/
+structure Result (reg : Fin 5 ↪ Fin r) (done : Fin p) (c out : Config bits p r)
+ (src lo : ℕ) (bs : List Bool) : Prop where
+ pc : out.pc = done
+ source : out.reg (reg 0) = word bits (src+bs.length)
+ destination : out.reg (reg 2) = word bits lo
+ frame : ∀ j, j ≠ reg 0 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j
+ privateMem : out.privateMem = place lo bs c.privateMem
+ persistent : out.persistent = c.persistent
+
+theorem run (link : Linked M source pc reg done) (c : Config bits p r) (hc : c.pc = pc 0)
+ (src lo : ℕ) (bs : List Bool) (hs : c.reg (reg 0) = word bits src)
+ (hb : c.reg (reg 1) = word bits lo) (he : c.reg (reg 2) = word bits (lo+bs.length))
+ (h1 : c.reg (reg 3) = 1) (fit : lo+bs.length < 2^bits)
+ (safe : source = .resident → src+bs.length ≤ 2^bits ∧
+ (src+bs.length ≤ lo ∨ lo+bs.length ≤ src))
+ (data : ∀ i : Fin bs.length,
+ (source.value c.privateMem (word bits (src+i.val))) =
+ PrivateFields.bitValue bits bs[i.val]) :
+ ∃ out, Prefix M c (List.replicate (5*bs.length+1) .tick) out ∧ Result reg done c out src lo bs := by
+ induction bs generalizing c src with
+ | nil =>
+ have eq : c.reg (reg 2) = c.reg (reg 1) := he.trans hb.symm
+ let out := {c with pc := done}
+ have s : M.program.step c = .localStep out := by
+ rw [step_at link 0 c hc]
+ simp [instruction, Instr.run, eq, out]
+ exact ⟨out, .tick s (.nil _), rfl, hs, he, fun _ _ _ _ ↦ rfl, rfl, rfl⟩
+ | cons b bs ih =>
+ simp only [List.length_cons, ← Nat.add_assoc] at he fit
+ have neq : c.reg (reg 2) ≠ c.reg (reg 1) := by
+ rw [he,hb]
+ intro h
+ have e := congrArg Fin.val h
+ change (lo+bs.length+1) % 2^bits = lo % 2^bits at e
+ rw [Nat.mod_eq_of_lt fit, Nat.mod_eq_of_lt (by omega)] at e
+ omega
+ have val := data ⟨0, by simp⟩
+ simp only [Nat.add_zero,List.getElem_cons_zero] at val
+ obtain ⟨next,pref,hpc,hsrc,hdst,frame,hm,hper⟩ := iteration link c hc hs he neq h1 b val
+ have data' (i : Fin bs.length) :
+ (source.value next.privateMem (word bits (src+1+i.val))) =
+ PrivateFields.bitValue bits bs[i.val] := by
+ have e := data ⟨i.val+1, by simp⟩
+ simp only [List.getElem_cons_succ] at e
+ cases source with
+ | zero => exact e
+ | resident =>
+ have ss := safe rfl
+ simp only [List.length_cons] at ss
+ have hi := i.isLt
+ have ne : word bits (src+1+i.val) ≠ word bits (lo+bs.length) := by
+ intro h
+ have eq := congrArg Fin.val h
+ change _ % 2^bits = _ % 2^bits at eq
+ rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)] at eq
+ omega
+ simp only [Source.value] at e ⊢
+ rw [hm, Function.update_of_ne ne]
+ simpa [Nat.add_assoc, Nat.add_comm 1] using e
+ have keep (i : Fin 5) (a : i ≠ 0) (b : i ≠ 2) (d : i ≠ 4) :=
+ frame _ (reg.injective.ne a) (reg.injective.ne b) (reg.injective.ne d)
+ obtain ⟨out,tail,res⟩ := ih next hpc (src+1) hsrc
+ ((keep 1 (by decide) (by decide) (by decide)).trans hb) hdst
+ ((keep 3 (by decide) (by decide) (by decide)).trans h1) (by omega)
+ (fun h ↦ by have e := safe h; simp only [List.length_cons] at e; omega) data'
+ refine ⟨out, ?_, res.pc, ?_, res.destination, ?_, ?_, res.persistent.trans hper⟩
+ · convert pref.append tail using 1
+ rw [← List.replicate_add]
+ congr 1
+ simp; omega
+ · simpa [Nat.add_assoc, Nat.add_comm 1] using res.source
+ · intro j h0 h2 h4
+ exact (res.frame j h0 h2 h4).trans (frame j h0 h2 h4)
+ · rw [res.privateMem, hm, place]
+
+end PairSimulation.LeafFieldCopy
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldSources.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldSources.lean
new file mode 100644
index 0000000000..30fd50550b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldSources.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.PairSimulationLeafScalarLoad
+import OAI.Computability.VPVNP.PrimedCounterVirtualFuel
+
+/-!
+# Scalar sources for initializing the virtual verifier's private stacks
+
+Every scalar stack is either a width-bounded binary word or a unary tally.
+Only the incident bit vector needs the field-copy subroutine. Addresses,
+caps and bucket endpoints are the words actually seen by the auxiliary
+site verifier.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafStartup
+
+open BurstRAM RAMTape LeafScalarLoad
+
+variable {d e w k : ℕ}
+
+/-- The loading mode, bit count and source word for each scalar input field of a virtual site.
+The incident port starts empty for the later half-wire copy. -/
+def source (x : VirtualSite.Input d e w) (pub : Fin k → Word w) : Field k → Mode × ℕ × Word w
+ | .blank | .incident => (.tally,0,1)
+ | .zeroWord => (.binary,w,0)
+ | .address => (.binary,d,x.addrWord)
+ | .addressWidth => (.tally,d,1)
+ | .width => (.tally,w,1)
+ | .slots => (.tally,4*2^e,1)
+ | .bucket => (.tally,2^e,1)
+ | .fuel => (.tally,x.fuel,1)
+ | .siteCredit => (.tally,2*2^e-1,1)
+ | .choices => (.tally,choiceBound e w x.fuel,1)
+ | .cap => (.binary,w,⟨2^d*2^e,x.hc⟩)
+ | .lower => (.binary,w,SiteEndpoints.startWord e w x.v x.hcap)
+ | .upper => (.binary,w,SiteEndpoints.endWord e w x.v x.hcap)
+ | .initial => (.binary,w,x.initialWord)
+ | .siteWord => (.binary,w,x.addrWord)
+ | .header => (.binary,w,x.headerWord)
+ | .operand i => (.binary,w,pub i)
+
+theorem scalarSpec (x : VirtualSite.Input d e w) (pub : Fin k → Word w) (f : Field k)
+ (hs : f ≠ .incident) :
+ let v := source x pub f
+ payload v.1 v.2.2 v.2.1 = (fieldBits x pub f).reverse := by
+ have hw : 0 < w := (by decide : 0 < 2).trans_le x.hw
+ cases f <;> first
+ | rfl
+ | contradiction
+ | exact payload_word _ _ rfl
+ | (simp only [source, fieldBits, payload_tally _ hw, List.reverse_replicate])
+
+/-- The slot tally and choice-stream length fit in machine words when staging the site's scalar
+fields. -/
+structure SourceFit (x : VirtualSite.Input d e w) : Prop where
+ slots : 4*2^e < 2^w
+ choices : choiceBound e w x.fuel < 2^w
+
+theorem SourceFit.length {x : VirtualSite.Input d e w} (h : SourceFit x)
+ (pub : Fin k → Word w) (f : Field k) : (source x pub f).2.1 < 2^w := by
+ have he := Nat.two_pow_pos e
+ have hw := Nat.lt_two_pow_self (n := w)
+ have hd := x.hcap
+ have hslots := h.slots
+ have hchoices := h.choices
+ have hF : x.fuel ≤ choiceBound e w x.fuel :=
+ (Nat.le_add_right x.fuel w).trans (Nat.le_mul_of_pos_left _ (by positivity))
+ cases f <;> dsimp only [source] <;> omega
+
+end PairSimulation.LeafStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldStage.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldStage.lean
new file mode 100644
index 0000000000..109d675e58
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafFieldStage.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.PairSimulationLeafFieldCode
+
+/-! # Correctness of the private length and value rows for a scalar field -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafStartup.Staging
+
+open BurstRAM PrivateRAM RAMTape PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {d e w k p r pubs : ℕ}
+
+/-- The staging bank contains the constants, dimensions, fuel, site words and public operands
+of the specified virtual input. -/
+structure Sources (x : VirtualSite.Input d e w) (pub : Fin k → Word w) (bank : Reg k → Word w) : Prop where
+ zero : bank .zero = 0
+ one : bank .one = 1
+ d : bank .d = (d : Word w)
+ width : bank .width = (w : Word w)
+ bucket : bank .bucket = ((2^e : ℕ) : Word w)
+ fuel : bank .fuel = (x.fuel : Word w)
+ address : bank .address = x.addrWord
+ initial : bank .initial = x.initialWord
+ header : bank .header = x.headerWord
+ operand : ∀ i, bank (.operand i) = pub i
+
+private theorem cast_word {a : ℕ} (ha : a < 2^w) : (a : Word w) = ⟨a,ha⟩ :=
+ Fin.ext (Nat.mod_eq_of_lt ha)
+
+theorem stagedWords (x : VirtualSite.Input d e w) (pub : Fin k → Word w) (bank : Reg k → Word w)
+ (ready : Sources x pub bank) (f : Field k) :
+ let dst := (code f).foldl applyLine bank
+ dst (.out .len) = ((source x pub f).2.1 : Word w) ∧ dst (.out .value) = (source x pub f).2.2 := by
+ have ha : x.addrWord = (x.v.val : Word w) := (cast_word x.addrWord.isLt).symm
+ have hlo : SiteEndpoints.startWord e w x.v x.hcap = ((x.v.val*2^e : ℕ) : Word w) :=
+ (cast_word (SiteEndpoints.startWord e w x.v x.hcap).isLt).symm
+ have hhi : SiteEndpoints.endWord e w x.v x.hcap = (((x.v.val+1)*2^e : ℕ) : Word w) :=
+ (cast_word (SiteEndpoints.endWord e w x.v x.hcap).isLt).symm
+ have hcap : (⟨2^d*2^e,x.hc⟩ : Word w) = ((2^d*2^e : ℕ) : Word w) := (cast_word x.hc).symm
+ have hpos : 1 ≤ 2*2^e := by have := Nat.two_pow_pos e; omega
+ have hd : d < w := (Nat.le_add_right d e).trans_lt x.hcap
+ have dx : d % 2^w = d := Nat.mod_eq_of_lt (hd.trans (Nat.lt_two_pow_self (n := w)))
+ have one : 1 % 2^w = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by have := x.hw; omega))
+ cases f <;> simp [code,applyLine,Rhs.eval,source,ready.zero,ready.one,ready.d,ready.width,
+ ready.bucket,ready.fuel,ready.address,ready.initial,ready.header,ready.operand,Function.update,
+ dx,one,hd,Nat.shiftLeft_eq,ha,hlo,hhi,hcap,choiceBound,Nat.cast_sub hpos,BinaryOp.eval] <;> ring
+
+/-- The staging rows feed the filler with its exact length and word, and leave
+private memory and every register outside the three output slots untouched. -/
+theorem stage_run (x : VirtualSite.Input d e w) (pub : Fin k → Word w) (f : Field k)
+ (M : Machine w p r pubs) (ports : Reg k ↪ Fin r) (pc : Fin ((code f).length+1) → Fin p)
+ (link : ∀ i : Fin (code f).length, M.code (pc i.castSucc) = instruction ports (pc i.succ) (code f)[i])
+ (c : Config w p r) (entry : c.pc = pc 0) (ready : Sources x pub (c.reg ∘ ports)) (fit : SourceFit x) :
+ ∃ post, Prefix M c (List.replicate (code f).length .tick) post ∧ post.pc = pc (Fin.last (code f).length) ∧
+ post.privateMem = c.privateMem ∧ post.persistent = c.persistent ∧
+ (post.reg (ports (.out .len))).val = (source x pub f).2.1 ∧
+ post.reg (ports (.out .value)) = (source x pub f).2.2 ∧
+ ∀ j, (∀ o, j ≠ ports (.out o)) → post.reg j = c.reg j := by
+ have hr := run M ports (code f) pc link c entry
+ have eq := physical_at ports (code f) c.reg
+ have h := stagedWords x pub (c.reg ∘ ports) ready f
+ have hl := (congrFun eq (.out .len)).trans h.1
+ have hv := (congrFun eq (.out .value)).trans h.2
+ have hn := congrArg Fin.val hl
+ exact ⟨_, hr, rfl, rfl, rfl, hn.trans (Nat.mod_eq_of_lt (fit.length pub f)), hv, fun j hj => physical_outside ports (code f) c.reg j hj⟩
+
+end PairSimulation.LeafStartup.Staging
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafFill.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafFill.lean
new file mode 100644
index 0000000000..8256543c1e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafFill.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.PairSimulationLeafPointers
+
+/-!
+# Installing a scalar field in the validator's represented stack bank
+
+Only the selected top pointer and its occupied cells change. The proof also
+covers empty fields and allows later leaves to reuse a previously occupied
+region. All reads and writes in the initialization are private.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafFill
+
+open RAMTape BurstRAM PrivateRAM PrimedInputRAM PrimedCounter.GuessWord StackMachine
+open scoped Fin.CommRing
+
+variable {K : Type} {w p r k : ℕ}
+
+/-- Registers for a scalar stack fill, combining the stack allocation registers with the
+field's length and source word. -/
+inductive Reg (K : Type) where | pointers (j : LeafPointers.Reg K) | length | value
+ deriving DecidableEq, Fintype
+
+/-- Embed the stack allocation registers into the physical register placement of the scalar
+fill loop. -/
+def pointers (reg : Reg K ↪ Fin r) : LeafPointers.Reg K ↪ Fin r :=
+ ⟨fun i => reg (.pointers i),fun _ _ h => Reg.pointers.inj (reg.injective h)⟩
+
+/-- The host placement of stack registers reached through the fill loop's allocation registers. -/
+def stack (reg : Reg K ↪ Fin r) := LeafPointers.stack (pointers reg)
+
+@[simp] theorem pointers_at (reg : Reg K ↪ Fin r) (i : LeafPointers.Reg K) :
+ pointers reg i = reg (.pointers i) := rfl
+
+@[simp] theorem stack_at (reg : Reg K ↪ Fin r) (i : Register K) :
+ stack reg i = reg (.pointers (.stack i)) := rfl
+
+/-- The six physical registers of a port's scalar write loop, in order from its top pointer
+through length, value, zero, one and scratch. -/
+def fieldRegisters (reg : Reg K ↪ Fin r) (a : K) : Fin 6 ↪ Fin r where
+ toFun := ![stack reg (.top a),reg .length,reg .value,stack reg .zero,stack reg .one,stack reg .tmp]
+ inj' := by
+ intro i j h
+ fin_cases i <;> fin_cases j <;> simp_all
+
+@[simp] theorem fieldRegisters_at (reg : Reg K ↪ Fin r) (a : K) (i : Fin 6) :
+ fieldRegisters reg a i = ![stack reg (.top a),reg .length,reg .value,stack reg .zero,stack reg .one,
+ stack reg .tmp] i := rfl
+
+variable [DecidableEq K]
+
+theorem contents_install (L : Layout K w) (a : K) (s : Stacks K) (xs : List Bool)
+ (old new : Word w → Word w) (hs : L.Contents old s) (hfit : ∀ j, (s j).length ≤ L.capacity)
+ (written : ∀ i : Fin xs.reverse.length, new (L.address a i.val) = encodeBit w xs.reverse[i.val])
+ (frame : ∀ u, u.val < L.base a ∨ L.base a+L.capacity ≤ u.val → new u = old u) :
+ L.Contents new (Function.update s a xs) := by
+ intro j pre b tail he
+ by_cases hj : j = a
+ · subst j
+ rw [Function.update_self] at he
+ have lt : tail.length < xs.reverse.length := by simp [he]
+ simpa [he, List.reverse_append, List.reverse_cons, List.append_assoc] using written ⟨tail.length,lt⟩
+ · rw [Function.update_of_ne hj] at he
+ have lt : tail.length < (s j).length := by simp [he]; omega
+ rw [frame]
+ · exact hs j pre b tail he
+ · rw [L.address_val j (lt.le.trans (hfit j))]
+ rcases L.apart j a hj with left | right
+ · exact .inl ((Nat.add_lt_add_left (lt.trans_le (hfit j)) _).trans_le left)
+ · exact .inr (right.trans (Nat.le_add_right ..))
+
+/-- Deterministic execution of a scalar-port load, starting from a represented
+bank and the two runtime operands. The destination port is empty at entry. -/
+theorem install_scalar {M : Machine w p r k} {mode : LeafScalarLoad.Mode} {pc : Fin 6 → Fin p}
+ {done : Fin p} (L : Layout K w) (reg : Reg K ↪ Fin r) (a : K) (s : Stacks K) (xs : List Bool)
+ (value : Word w) (c : Config w p r) (link : LeafScalarLoad.Linked M mode pc (fieldRegisters reg a) done)
+ (hw : 0 < w) (hc : c.pc = pc 0) (rep : Represents L (stack reg) c s) (ha : s a = [])
+ (fit : ∀ j, (s j).length ≤ L.capacity) (room : xs.length ≤ L.capacity)
+ (hlen : c.reg (reg .length) = (xs.length : Word w)) (hval : c.reg (reg .value) = value)
+ (bits : LeafScalarLoad.payload mode value xs.length = xs.reverse) :
+ ∃ out, Prefix M c (List.replicate (6*xs.length+1) .tick) out ∧ out.pc = done ∧
+ Represents L (stack reg) out (Function.update s a xs) ∧ out.persistent = c.persistent ∧
+ (∀ i, i ∉ Set.range reg → out.reg i = c.reg i) ∧
+ ∀ u, u.val < L.base a ∨ L.base a+xs.length ≤ u.val → out.privateMem u = c.privateMem u := by
+ have bound := (Nat.add_le_add_left room (L.base a)).trans_lt (L.fits a)
+ have hp : c.reg (fieldRegisters reg a 0) = (L.base a : Word w) := by
+ change c.reg (stack reg (.top a)) = _
+ rw [rep.tops,ha]; rfl
+ obtain ⟨out,run,res⟩ := LeafScalarLoad.load_prefix link hw xs.length (L.base a) value c hc hp
+ hlen hval rep.zero rep.unit bound
+ have dst := res.destination
+ change out.reg (stack reg (.top a)) = _ at dst
+ rw [bits,List.length_reverse] at dst
+ have mem := res.memory
+ rw [bits] at mem
+ have unchanged (u : Word w) (hu : u.val < L.base a ∨ L.base a+xs.length ≤ u.val) :
+ out.privateMem u = c.privateMem u := by
+ rw [mem]
+ exact PrivateFields.storeBits_outside (L.base a) xs.reverse c.privateMem u (by simpa using bound.le)
+ (by simpa using hu)
+ have keep (i : Register K) (hne : i ≠ .top a) (ht : i ≠ .tmp) :
+ out.reg (stack reg i) = c.reg (stack reg i) :=
+ res.frame _ (by simpa using hne) (by simp) (by simpa using ht)
+ refine ⟨out,run,res.pc,?_,res.persistent,?_,unchanged⟩
+ · refine ⟨(keep .one nofun nofun).trans rep.unit,(keep .zero nofun nofun).trans rep.zero,
+ fun j => (keep (.base j) nofun nofun).trans (rep.bases j),?_,?_⟩
+ · intro j
+ by_cases hj : j = a
+ · subst j; rw [Function.update_self]; exact dst
+ · rw [Function.update_of_ne hj,keep (.top j) (by simpa using hj) nofun,rep.tops]
+ · apply contents_install L a s xs c.privateMem out.privateMem rep.cells fit
+ · intro i
+ rw [mem]
+ exact PrivateFields.storeBits_read (L.base a) xs.reverse c.privateMem (by simpa using bound.le) i
+ · intro u hu
+ exact unchanged u (hu.imp_right ((Nat.add_le_add_left room _).trans ·))
+ · intro i hi
+ have ne (j : Reg K) : i ≠ reg j := fun he => hi ⟨j,he.symm⟩
+ exact res.frame _ (ne _) (ne _) (ne _)
+
+end PairSimulation.LeafFill
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafFrame.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafFrame.lean
new file mode 100644
index 0000000000..90d3e2349e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafFrame.lean
@@ -0,0 +1,248 @@
+import OAI.Computability.VPVNP.PairSimulationLeafHandler
+import OAI.Computability.VPVNP.PairSimulationVertexJobs
+import OAI.Computability.VPVNP.PairPendingArguments
+import OAI.Computability.VPVNP.PairSimulationLeafArena
+
+/-!
+# The private-memory frame of a cursor leaf visit
+
+All writes made by the bounded stack program lie inside its own stack
+intervals. In particular a successful leaf preserves the earlier private
+histogram and the stored arguments of other pending vertices, cell by cell,
+whenever the deterministic input preparation preserves those cells.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open BurstRAM RAMTape DFS
+open scoped Fin.CommRing
+
+variable {W endAddr : ℕ} {K Q : Type} [DecidableEq K]
+
+/-- Even a partial or rejected prefix only writes inside the designated
+intervals. Each source step can increase any one stack by at most one. -/
+theorem footprint_writes_inside (L : Layout K W) (code : StackCode K Q) (fuel : ℕ)
+ (q : Q) (s : Stacks K) (bits : List Bool) (room : ∀ j, (s j).length+fuel ≤ L.capacity) :
+ ∀ write ∈ (footprint L code fuel q s bits).writes,
+ ∃ j, L.base j ≤ write.1.val ∧ write.1.val < L.base j + L.capacity := by
+ induction fuel generalizing q s bits with
+ | zero => simp [footprint]
+ | succ fuel ih =>
+ have dec (j : K) : (s j).length+fuel ≤ L.capacity := Nat.le_trans (by omega) (room j)
+ cases op : code q with
+ | push j b next =>
+ have can : (s j).length < L.capacity := by have := room j; omega
+ have after (k : K) : ((Function.update s j (b :: s j)) k).length + fuel ≤ L.capacity := by
+ by_cases hk : k = j
+ · subst k; simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using room j
+ · simpa [Function.update_of_ne hk] using dec k
+ intro write mem
+ rcases List.mem_cons.mp (show write ∈ (_,_) :: (footprint L code fuel next _ bits).writes from
+ by simpa only [footprint, op, Footprint.prepend, List.cons_append, List.nil_append] using mem)
+ with first | later
+ · subst write
+ exact ⟨j, by rw [L.address_val j can.le]; omega, by rw [L.address_val j can.le]; omega⟩
+ · exact ih _ _ _ after _ later
+ | pop j next =>
+ have after (k : K) : ((Function.update s j (s j).tail) k).length + fuel ≤ L.capacity := by
+ by_cases hk : k = j
+ · subst k; simp only [Function.update_self, List.length_tail]; have := dec j; omega
+ · simpa [Function.update_of_ne hk] using dec k
+ simpa only [footprint, op, Footprint.prepend, List.nil_append] using
+ ih (next (s j).head?) _ bits after
+ | goto next =>
+ simpa only [footprint, op, Footprint.prepend, List.nil_append] using ih next s bits dec
+ | choose low high =>
+ cases bits with
+ | nil => simp [footprint, op]
+ | cons b bs =>
+ simpa only [footprint, op, Footprint.prepend, List.nil_append] using ih (if b then high else low) s bs dec
+ | halt b => simp [footprint, op]
+
+private theorem applyWrites_away (f : Footprint W) (mem : Word W → Word W) (a : Word W)
+ (away : ∀ write ∈ f.writes, a ≠ write.1) : f.applyWrites mem a = mem a := by
+ obtain ⟨events,writes⟩ := f
+ change ∀ write ∈ writes, a ≠ write.1 at away
+ unfold Footprint.applyWrites
+ dsimp only
+ induction writes generalizing mem with
+ | nil => rfl
+ | cons write writes ih =>
+ rw [List.foldl_cons, ih _ (fun v h => away v (List.mem_cons_of_mem _ h)),
+ Function.update_of_ne (away write List.mem_cons_self)]
+
+/-- Cell-level scratch frame on every stream, for use by the DFS histogram
+and by any remaining pending argument packets. -/
+theorem footprint_scratch_outside (L : Layout K W) (code : StackCode K Q) (fuel : ℕ)
+ (q : Q) (s : Stacks K) (bits : List Bool) (room : ∀ j, (s j).length+fuel ≤ L.capacity)
+ (saved : Scratch W endAddr) (cell : {a : Word W // endAddr ≤ a.val})
+ (outside : ∀ j, cell.val.val < L.base j ∨ L.base j + L.capacity ≤ cell.val.val) :
+ (footprint L code fuel q s bits).applyScratch endAddr saved cell = saved cell := by
+ unfold Footprint.applyScratch
+ rw [applyWrites_away _ _ _ (by
+ intro write hw eqn
+ obtain ⟨j,lo,hi⟩ := footprint_writes_inside L code fuel q s bits room write hw
+ rw [← eqn] at lo hi
+ rcases outside j with h | h <;> omega)]
+ simp [cell.property]
+
+end PairSimulation.StackMachine
+
+namespace PairSimulation.LeafHandler
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork LeafStartup StackMachine DFS
+open LocalHistory NodeArguments
+open scoped Fin.CommRing
+
+variable {d e w W endAddr : ℕ} [NeZero d]
+ {L : PrimedInputRAM.Lengths} {n ai H s : ℕ} {Q : PrimedInputRAM.Layout L n ai H w}
+ (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (storage : StackMachine.Layout (Port 52 34) W)
+ (load : Word W → Scratch W endAddr → Input d e w W endAddr) (clock : ℕ)
+ (node : Word W) (saved : Scratch W endAddr) (bits tail : List Bool)
+ (job : VisitPath W endAddr)
+
+/-- The leaf's trace, its enabling scratch, and the cells it preserves are
+all determined by the actual native stack path. -/
+theorem parser_observations
+ (hit : (parser D hw hc storage load clock).read node saved bits = some (job,tail))
+ (det : choiceBits (load node saved).trace = [])
+ (room : ∀ j, (auxiliaryBank D hw hc (load node saved).pos (load node saved).buffers j).length + clock ≤ storage.capacity) :
+ job.node = node ∧ (∀ old, job.enabled old ↔ old = saved) ∧ bits = choiceBits job.trace ++ tail ∧
+ ∀ cell : {a : Word W // endAddr ≤ a.val},
+ (∀ j, cell.val.val < storage.base j ∨ storage.base j + storage.capacity ≤ cell.val.val) →
+ job.update saved cell = (load node saved).prepared cell := by
+ let x := load node saved
+ by_cases route : Routed x
+ · by_cases hz : x.pos.1 = 0
+ · let bank := auxiliaryBank D hw hc x.pos x.buffers
+ let fp := footprint storage auxiliaryCode clock auxiliaryEntry bank bits
+ change (if Routed x then _ else none) = some (job,tail) at hit
+ rw [ite_eq_left route, ite_eq_left hz] at hit
+ change (match parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => none
+ | some y => if y.accept then some (⟨node,x.trace++fp.events,(· = saved),fun _ => fp.applyScratch endAddr x.prepared⟩,y.rest) else none) =
+ some (job,tail) at hit
+ cases hp : parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => rw [hp] at hit; contradiction
+ | some y =>
+ rw [hp] at hit
+ cases ok : y.accept with
+ | false => simp [ok] at hit
+ | true =>
+ obtain ⟨rfl,rfl⟩ := (by simpa only [ok,↓reduceIte,Option.some.injEq,Prod.mk.injEq] using hit.symm :
+ job = ⟨node,x.trace++fp.events,(· = saved),fun _ => fp.applyScratch endAddr x.prepared⟩ ∧ tail = y.rest)
+ refine ⟨rfl, fun _ => Iff.rfl, ?_, fun cell away =>
+ footprint_scratch_outside storage auxiliaryCode clock auxiliaryEntry bank bits room x.prepared cell away⟩
+ change bits = choiceBits (x.trace ++ fp.events) ++ y.rest
+ rw [PrimedInputRAM.Flow.choiceBits_append,show choiceBits x.trace = [] from det,List.nil_append]
+ exact (footprint_parse storage hp ok).1
+ · have pair : job = ⟨node,x.trace,(· = saved),fun _ => x.prepared⟩ ∧ tail = bits := by
+ simpa only [parser,show load node saved = x from rfl,ite_eq_left route,ite_eq_right hz,
+ Option.some.injEq,Prod.mk.injEq] using hit.symm
+ obtain ⟨rfl,rfl⟩ := pair
+ exact ⟨rfl,fun _ => Iff.rfl,by change _ = choiceBits x.trace ++ _; rw [show choiceBits x.trace = [] from det]; rfl,fun _ _ => rfl⟩
+ · simp only [parser,show load node saved = x from rfl,ite_eq_right route,reduceCtorEq] at hit
+
+
+/-- Every other pending packet below the virtual stack intervals retains
+the bit values established by the deterministic input preparation. -/
+theorem parser_pending
+ (hit : (parser D hw hc storage load clock).read node saved bits = some (job,tail))
+ (det : choiceBits (load node saved).trace = [])
+ (room : ∀ j, (auxiliaryBank D hw hc (load node saved).pos (load node saved).buffers j).length + clock ≤ storage.capacity)
+ (arena : Arena) (q : Packet) (fits : q.Fits arena W endAddr)
+ (below : ∀ j, arena.base q.node + q.bits.length ≤ storage.base j)
+ (prefixStored : q.Stored arena (load node saved).prepared) :
+ q.Stored arena (job.update saved) := by
+ apply prefixStored.congr
+ intro i
+ let a : Word W := ((arena.base q.node + i.val : ℕ) : Word W)
+ have val : a.val = arena.base q.node+i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans_le fits.2.2)
+ have above : endAddr ≤ a.val := val ▸ fits.1.trans (Nat.le_add_right _ _)
+ have frame := (parser_observations D hw hc storage load clock node saved bits tail job hit det room).2.2.2
+ ⟨a,above⟩ (fun j => Or.inl (val ▸ (Nat.add_lt_add_left i.isLt _).trans_le (below j)))
+ change rawScratch (job.update saved) a = rawScratch (load node saved).prepared a
+ simpa only [rawScratch, dite_eq_left above] using frame
+
+
+/-- Realize a selected zero-label occurrence after the suffix comparison.
+This proof is independent of how the original cursor factors were transported. -/
+theorem realizes_zero {Label α : Type} (reader : CompressorRecords.ChoiceReader α)
+ (power : α → Label → ℕ) (zero : ∀ x label, power x label = 0) (address : ℕ)
+ (addr : node.val = address)
+ (accept : ∀ x suffix, ∃ actual, (parser D hw hc storage load clock).read node saved
+ (reader.encode x ++ suffix) = some (actual,suffix))
+ (cell : Label → {a : Word W // endAddr ≤ a.val})
+ (away : ∀ label j, (cell label).val.val < storage.base j ∨
+ storage.base j+storage.capacity ≤ (cell label).val.val)
+ (det : choiceBits (load node saved).trace = [])
+ (prefixFrame : ∀ label, (load node saved).prepared (cell label) = saved (cell label))
+ (room : ∀ j, (auxiliaryBank D hw hc (load node saved).pos (load node saved).buffers j).length+clock ≤ storage.capacity)
+ (x : α) (suffix : List Bool) :
+ ∃ actual, (parser D hw hc storage load clock).read node saved (reader.encode x ++ suffix) = some (actual,suffix) ∧
+ actual.enabled saved ∧ RealizesJob (fun old label => (old (cell label)).val) ⟨address,reader.encode x,power x⟩ actual := by
+ obtain ⟨actual,hit⟩ := accept x suffix
+ obtain ⟨num,enabled,consumed,frame⟩ := parser_observations D hw hc storage load clock node saved
+ (reader.encode x ++ suffix) suffix actual hit det room
+ refine ⟨actual,hit,(enabled saved).mpr rfl,⟨?_,(List.append_cancel_right consumed).symm,?_⟩⟩
+ · change actual.node = (address : Word W)
+ rw [num,← addr]
+ simp
+ · intro old h label
+ have eqn := (enabled old).mp h
+ subst old
+ change (actual.update saved (cell label)).val = (saved (cell label)).val + power x label
+ rw [frame (cell label) (away label),prefixFrame label,zero,Nat.add_zero]
+
+end PairSimulation.LeafHandler
+
+namespace PairSimulation.LeafArena
+
+open BurstRAM DFS NodeArguments
+open scoped Fin.CommRing
+
+private theorem hist_lt (R : Regions) (i : Fin R.histWords) : R.histBase+i.val < R.stackBase := by
+ have h := (Nat.add_lt_add_left i.isLt R.histBase).trans_le R.hist_before
+ exact h.trans_le (Nat.le_add_right _ _)
+
+/-- A real histogram cell of the private layout, above the DFS stack and
+strictly before the operand cache and all verifier stacks. -/
+def Regions.histCell {W endAddr : ℕ} (R : Regions) (h : R.stackBase ≤ 2^W)
+ (above : endAddr ≤ R.histBase) (i : Fin R.histWords) : {a : Word W // endAddr ≤ a.val} :=
+ ⟨((R.histBase+i.val : ℕ) : Word W), by
+ change endAddr ≤ (R.histBase+i.val) % 2^W
+ rw [Nat.mod_eq_of_lt ((hist_lt R i).trans_le h)]
+ exact above.trans (Nat.le_add_right _ _)⟩
+
+theorem Regions.histCell_below {W endAddr ports : ℕ} {K : Type}
+ (R : Regions) (order : K ↪ Fin ports) (capacity : ℕ) (fit : R.stackBase + ports*capacity < 2^W)
+ (above : endAddr ≤ R.histBase) (i : Fin R.histWords) (j : K) :
+ (R.histCell (W := W) ((Nat.le_add_right _ _).trans fit.le) above i).val.val <
+ (R.layout order capacity fit).base j := by
+ change (R.histBase+i.val) % 2^W < _
+ have lo := hist_lt R i
+ rw [Nat.mod_eq_of_lt (lo.trans_le ((Nat.le_add_right _ _).trans fit.le))]
+ exact lo.trans_le (R.stack_above order capacity fit j)
+
+/-- A still-pending argument packet is below every verifier stack in the
+same allocated layout, regardless of its assigned bits. -/
+theorem Regions.packet_below {W endAddr ports : ℕ} {K : Type} (R : Regions) (order : K ↪ Fin ports)
+ (capacity : ℕ) (fit : R.stackBase + ports*capacity < 2^W) (q : Packet)
+ (hq : q.node < R.nodes) (fitted : q.Fits R.arguments W endAddr) (j : K) :
+ R.arguments.base q.node + q.bits.length ≤ (R.layout order capacity fit).base j := by
+ apply (le_trans _ (R.stack_above order capacity fit j))
+ have h := (Nat.add_le_add_left fitted.2.1 _).trans (R.node_before hq)
+ unfold Regions.stackBase Regions.cacheBase
+ omega
+
+end PairSimulation.LeafArena
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafFront.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafFront.lean
new file mode 100644
index 0000000000..c5c08087a9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafFront.lean
@@ -0,0 +1,222 @@
+import OAI.Computability.VPVNP.PairSimulationRoutePrepare
+import OAI.Computability.VPVNP.PairSimulationLeafCachedSources
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+import OAI.Computability.VPVNP.PairSimulationLeafRouteFork
+
+/-!
+# The deterministic front of a physical cursor leaf
+
+The descriptor pointer determines the cursor, site and shadow header. The
+setup then reads the cached virtual dimensions and the four fields of the
+stored packet. A passed route enters the private validator at cursor zero
+and returns at a transit cursor. An inconsistent route rejects in this call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafFront
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork RAMLayout
+open PrimedInputRAM Compression LocalHistory TraversalRows DFS
+open scoped Fin.CommRing
+
+variable {W p r k : ℕ}
+
+/-- Labels and operand allocations for the decoded-address and routing prefix. -/
+structure Program (p r k : ℕ) where
+ /-- Leaf-address decode and translated header read. -/
+ addressPC : Fin 20 → Fin p
+ /-- The address-reader registers, including the persistent input node slot. -/
+ leaf : LeafAddress.Reg ↪ Fin r
+ /-- The public address-reader operands. -/
+ addressPub : LeafAddress.Field → Fin k
+ /-- The 29 setup instructions after either address-reader exit. -/
+ preparePC : RoutePrepare.Stage → Fin p
+ /-- The public arena and cache pointers. -/
+ preparePub : RoutePrepare.Field → Fin k
+ /-- The complete route scan. -/
+ route : RouteSchedule.Program p r
+ /-- Entry to the cursor-zero validator initialization. -/
+ init : Fin p
+ /-- Return to the caller at a transit cursor. -/
+ transit : Fin p
+ apart : ∀ j i, leaf j ≠ route.reg i
+
+variable (P : Program p r k)
+
+/-- Both address-reader exits join the setup before the routing test. -/
+structure Program.Linked (M : Machine W p r k) : Prop where
+ address : LeafAddress.Linked M P.addressPC P.leaf P.addressPub
+ (P.preparePC (.inl 0)) (P.preparePC (.inl 0))
+ prepare : RoutePrepare.Linked M P.preparePC P.route.reg P.leaf P.preparePub (P.route.pc 0)
+ route : P.route.Linked M
+ pass : M.code P.route.yes = .jumpEq (P.route.reg 0) (P.route.reg 17) P.init P.transit
+ fail : M.code P.route.no = .reject
+
+variable {D e w : ℕ} [NeZero D]
+
+/-- Exact event list on a passed route. Only the header access may probe
+external memory, and the complete list consumes no branch bits. -/
+def trace (m : Memory W) (pub : LeafAddress.Field → Word W) (v : Position D) (e w : ℕ) :
+ List (Event W) :=
+ LeafAddress.events m (pub .shadow) (pub .span) (v.2.val : Word W) ++
+ List.replicate (RoutePrepare.ticks + (RouteSchedule.routeTicks W v (2 ^ e) w + 1)) .tick
+
+private theorem tick_bits (n : ℕ) : choiceBits (List.replicate n (.tick : Event W)) = [] := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [List.replicate_succ, choiceBits, ih]
+
+theorem trace_cost (m : Memory W) (pub : LeafAddress.Field → Word W) (v : Position D) (e w : ℕ) :
+ (trace m pub v e w).length =
+ 19 + (RoutePrepare.ticks + (RouteSchedule.routeTicks W v (2 ^ e) w + 1)) ∧
+ choiceBits (trace m pub v e w) = [] := by
+ have h := LeafAddress.cost m (pub .shadow) (pub .span) (v.2.val : Word W)
+ exact ⟨by simp [trace, h.1], by simp [trace, Flow.choiceBits_append, h.2.2, tick_bits]⟩
+
+/-- The only external probe in the front is the translated header read, exactly
+when the site's address is within the prepared shadow region. -/
+theorem trace_probes (m : Memory W) (pub : LeafAddress.Field → Word W) (v : Position D) (e w : ℕ) :
+ countProbes (trace m pub v e w) = (decide ((v.2.val : Word W) < pub .span)).toNat := by
+ have ticks (n : ℕ) : countProbes (List.replicate n (.tick : Event W)) = 0 := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [List.replicate_succ, countProbes, ih]
+ rw [trace, countProbes_append, ticks, Nat.add_zero]
+ exact (LeafAddress.cost m (pub .shadow) (pub .span) (v.2.val : Word W)).2.1
+
+variable {L : Lengths} {n a H s b l t pad : ℕ} {Q : Layout L n a H w}
+variable [NeZero (b + l)]
+
+/-- Fixed arena pointers, cursor dimensions and prepared translated shadow
+header, all read by the physical prefix. -/
+structure Operands (P : Program p r k) (M : Machine W p r k) (m : Memory W)
+ (data : PrimedCounter.Data Q s) (R : LeafArena.Regions) (b l cap : ℕ) : Prop where
+ stride : (M.publicData (P.addressPub .stride)).val = cap + 2
+ radixB : (M.publicData (P.addressPub .radixB)).val = 2 ^ b
+ radixL : (M.publicData (P.addressPub .radixL)).val = 2 ^ l
+ span : (M.publicData (P.addressPub .span)).val = LiveAuxiliaryHeaders.span L data.hist.length
+ fits : (M.publicData (P.addressPub .shadow)).val + (M.publicData (P.addressPub .span)).val ≤ 2 ^ W
+ header : ∀ i < (M.publicData (P.addressPub .span)).val,
+ (m ((M.publicData (P.addressPub .shadow)).val + i)).val = (data.initial i).val
+ arenaStart : M.publicData (P.preparePub .start) = (R.arguments.start : Word W)
+ arenaStride : M.publicData (P.preparePub .stride) = (R.arguments.stride : Word W)
+ cacheBase : M.publicData (P.preparePub .cache) = (R.cacheBase : Word W)
+
+/-- Geometry words placed in the private operand cache by the enclosing
+final-site call. -/
+structure Cache (R : LeafArena.Regions) (d w H : ℕ) (mem : Word W → Word W) : Prop where
+ dimension : mem (R.cacheBase : Word W) = (d : Word W)
+ width : mem ((R.cacheBase + 1 : ℕ) : Word W) = (w : Word W)
+ bucket : mem ((R.cacheBase + 2 : ℕ) : Word W) = (H : Word W)
+
+/-- Recover the three geometry operands from the final-site private cache. -/
+theorem Cache.of_cached {R : LeafArena.Regions} {mem : Word W → Word W} {d w H : ℕ}
+ {vals : LeafSourceLoad.Static k → Word W} (cached : LeafSourceLoad.Cached R.cacheBase mem vals)
+ (hd : vals .d = (d : Word W)) (hw : vals .width = (w : Word W))
+ (hH : vals .bucket = (H : Word W)) : Cache R d w H mem :=
+ ⟨(cached .d).trans hd, (cached .width).trans hw, (cached .bucket).trans hH⟩
+
+/-- Successful native return data needed by the stack initializer and the DFS caller. -/
+structure Result (P : Program p r k) (data : PrimedCounter.Data Q s) (v : Position (b + l))
+ (c out : Config W p r) : Prop where
+ pc : out.pc = (if v.1 = 0 then P.init else P.transit)
+ cursor : (out.reg (P.leaf .cursor)).val = v.1.val
+ site : (out.reg (P.leaf .site)).val = v.2.val
+ header : (out.reg (P.leaf .header)).val = (data.initial v.2.val).val
+ node : out.reg (P.leaf .node) = c.reg (P.leaf .node)
+ frame : ∀ j, LeafAddress.Preserved P.leaf j → (∀ i, j ≠ P.route.reg i) → out.reg j = c.reg j
+ memory : out.privateMem = c.privateMem
+ persistent : out.persistent = c.persistent
+
+private theorem off_bank {reg : Fin 32 ↪ Fin r} {j : Fin r} (h : ∀ i, j ≠ reg i) :
+ RouteSchedule.Keep reg j :=
+ ⟨⟨⟨fun i _ ↦ h i,h 4,h 16⟩,h 3,h 28⟩,h 21⟩
+
+private theorem word_of_val {x : Word W} {a : ℕ} (h : x.val = a) : x = (a : Word W) :=
+ Fin.ext (h.trans (Nat.mod_eq_of_lt (h ▸ x.isLt)).symm)
+
+open private returns_prefix from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+variable {P}
+
+/-- The three linked stages implement the physical leaf front on every fitted
+stored cursor packet. A failed route cannot return on any branch suffix. -/
+theorem native {M : Machine W p r k} (hl : P.Linked M) (m : Memory W)
+ (data : PrimedCounter.Data Q s) (R : LeafArena.Regions) (cap : ℕ)
+ (op : Operands P M m data R b l cap) (hD : 1 < b + l) (hd : 2 + pad = 2 ^ t)
+ (budget : ProcessorBudget n (b + l) e w) (host : w ≤ W)
+ (node : Word W) (v : Position (b + l))
+ (z : (LeafArguments.state hD hd (2 ^ e) w).network.Half
+ (lanePositions (cursorCoordinateLabels b l) v))
+ (c : Config W p r) (entry : c.pc = P.addressPC 0) (nodeReg : c.reg (P.leaf .node) = node)
+ (row : node.val = (sitePointers cap (M.publicData (P.addressPub .base)).val
+ (siteOrder (LeafArguments.state hD hd (2 ^ e) w))
+ (lanePositions (cursorCoordinateLabels b l) v)).1)
+ (cached : Cache R (b + l) w (2 ^ e) c.privateMem) {endAddr : ℕ}
+ (fit : (LeafHandler.cursorPacket hD hd node.val v z).Fits R.arguments W endAddr)
+ (stored : (LeafHandler.cursorPacket hD hd node.val v z).Stored R.arguments
+ (scratch endAddr c.privateMem)) :
+ let buf := LeafArguments.buffers hD hd v z
+ let es := trace m (M.publicData ∘ P.addressPub) v e w
+ (routeAccept (2 ^ e) w v (readBuffer buf) = true →
+ ∃ out, Result P data v c out ∧ ∀ fuel bs, execute M.program (fuel + es.length) c m bs =
+ (execute M.program fuel out m bs).map fun rep ↦ ⟨es ++ rep.events, rep.result⟩) ∧
+ (routeAccept (2 ^ e) w v (readBuffer buf) = false → ∀ bs, ¬ Returns M c m bs) := by
+ intro buf es
+ let pub := M.publicData ∘ P.addressPub
+ let tailCost := RoutePrepare.ticks + (RouteSchedule.routeTicks W v (2 ^ e) w + 1)
+ obtain ⟨hW, _, _⟩ := RouteSchedule.hostFits budget host
+ obtain ⟨q, hq, qcursor, qsite, qheader, qframe, qmem, qper, addrRun⟩ :=
+ LeafAddress.leaf_native hl.address m c entry data hD hd (ramFieldBits (2 ^ e) w) cap v hW.le
+ op.stride op.radixB op.radixL (nodeReg ▸ row) op.span op.fits op.header
+ have qnode := (qframe _ (LeafAddress.preserved_node _)).trans nodeReg
+ have prep : RoutePrepare.Ready M P.leaf P.preparePub R node.val (2 ^ e) w v q :=
+ ⟨word_of_val qcursor, word_of_val qsite, qnode.trans (word_of_val rfl),
+ op.arenaStart, op.arenaStride, op.cacheBase, qmem ▸ cached.dimension,
+ qmem ▸ cached.width, qmem ▸ cached.bucket⟩
+ let base := RoutePrepare.portBase (W := W) R.arguments node.val (b + l) (2 ^ e) w
+ have resident : RouteCall.Resident q base buf := by
+ intro port i
+ rw [qmem]
+ exact RoutePrepare.resident_cursorPacket hD hd R.arguments node v z c fit stored port i
+ obtain ⟨u, setup, hu, inputs, width, umem, uper, uframe⟩ :=
+ RoutePrepare.run hl.prepare P.apart q (by simpa using hq) prep hW resident
+ obtain ⟨passed, failed⟩ :=
+ LeafRouteFork.native budget host hl.route v buf base hu inputs width hl.pass hl.fail
+ constructor
+ · intro good
+ obtain ⟨out, scan, ho, oframe⟩ := passed good
+ have regKeep (j : Fin r) (hj : ∀ i, j ≠ P.route.reg i) : out.reg j = q.reg j :=
+ (oframe.regs _ (off_bank hj)).trans (uframe j hj)
+ have rleaf (j : LeafAddress.Reg) := regKeep (P.leaf j) (P.apart j)
+ refine ⟨out, ⟨ho, (congrArg Fin.val (rleaf .cursor)).trans qcursor,
+ (congrArg Fin.val (rleaf .site)).trans qsite,
+ (congrArg Fin.val (rleaf .header)).trans qheader,
+ (rleaf .node).trans (qframe _ (LeafAddress.preserved_node _)),
+ fun j h₁ h₂ ↦ (regKeep j h₂).trans (qframe j h₁), oframe.memory.trans (umem.trans qmem),
+ oframe.persistent.trans (uper.trans qper)⟩, ?_⟩
+ have both : Prefix M q (List.replicate tailCost .tick) out := by
+ rw [show tailCost = RoutePrepare.ticks + (RouteSchedule.routeTicks W v (2 ^ e) w + 1)
+ from rfl, List.replicate_add]
+ exact setup.append scan
+ intro fuel bs
+ have hlen : es.length = 19 + tailCost := (trace_cost m pub v e w).1
+ have ht := both.execute fuel m bs
+ simp only [List.length_replicate, tick_bits, List.nil_append] at ht
+ rw [hlen, show fuel + (19 + tailCost) = (fuel + tailCost) + 19 by omega, addrRun, ht]
+ simp [es, trace, tailCost, Option.map_map, Function.comp_def, List.append_assoc]
+ · intro bad bs hret
+ have afterAddr := (returns_prefix (fun fuel ↦ addrRun fuel bs)).mp hret
+ have afterPrep : Returns M u m bs := (returns_prefix (n := RoutePrepare.ticks) (fun fuel ↦ by
+ simpa only [List.length_replicate, tick_bits, List.nil_append] using
+ setup.execute fuel m bs)).mp afterAddr
+ exact failed bad m bs afterPrep
+
+end PairSimulation.LeafFront
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafGeometryLoad.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafGeometryLoad.lean
new file mode 100644
index 0000000000..e28927a843
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafGeometryLoad.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PairSimulationLeafImage
+
+/-!
+# Reloading leaf operands at the descriptor visit
+
+Private word `endAddr` points to the geometry array. Its first ten consecutive
+words supply the leaf's descriptor fields, argument arena, and input length.
+The native loader uses the DFS end pointer and the DFS unit register.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafGeometryLoad
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord LeafRegisterBank LeafSourceLoad
+open scoped Fin.CommRing
+
+/-- The location of each leaf operand in the ten-word private geometry record. Address fields
+occupy slots 0 through 5, arena fields occupy 6 through 8, and the input size occupies slot
+9. -/
+def slot : LeafImage.Pub ≃ Fin 10 where
+ toFun
+ | .address .base => 0
+ | .address .stride => 1
+ | .address .radixB => 2
+ | .address .radixL => 3
+ | .address .shadow => 4
+ | .address .span => 5
+ | .arena .start => 6
+ | .arena .stride => 7
+ | .arena .cache => 8
+ | .size => 9
+ invFun := ![.address .base, .address .stride, .address .radixB, .address .radixL,
+ .address .shadow, .address .span, .arena .start, .arena .stride, .arena .cache, .size]
+ left_inv j := by cases j <;> (try casesm* LeafAddress.Field) <;> (try casesm* RoutePrepare.Field) <;> rfl
+ right_inv j := by fin_cases j <;> rfl
+
+/-- Instruction labels for the initial geometry-pointer load and the ten pairs of field loads
+and cursor increments. -/
+abbrev Label := Unit ⊕ Fin 10 ⊕ Fin 10
+
+private def fields (i : Fin 10) : Static 6 := (slots 6)[i.val]'i.isLt
+
+private def offset (s : Static 6) : Fin 10 := ⟨s.offset,by cases s <;> simp [Static.offset]; omega⟩
+
+private theorem offset_field (i : Fin 10) : offset (fields i) = i :=
+ Fin.ext (slot_offset (k := 6) ⟨i.val,i.isLt⟩)
+
+variable {p r k w : ℕ} (pc : Label → Fin p) (dfs : Fin 9 ↪ Fin r) (ports : Source 6 ↪ Fin r)
+ (cursor : Fin r) (done : Fin p)
+
+/-- Physical destination register for the operand in the given geometry slot. -/
+def bank (i : Fin 10) : Fin r := ports (fields i).dest
+
+private def readPC (i : Fin 11) := if h : i.val < 10 then pc (.inr (.inl ⟨i.val,h⟩)) else done
+
+/-- Fetch the private geometry pointer, load each of its ten consecutive words into the
+assigned register, and advance the pointer with the DFS unit register. -/
+def instruction : Label → Instr w p r k
+ | .inl _ => .loadPrivate cursor (dfs 6) (readPC pc done 0)
+ | .inr (.inl i) => .loadPrivate (bank ports i) cursor (pc (.inr (.inr i)))
+ | .inr (.inr i) => .binary .add cursor cursor (dfs 3) (readPC pc done i.succ)
+
+theorem resize_instruction (i : Label) :
+ (instruction (w := 5) (k := k) pc dfs ports cursor done i).resize w =
+ instruction pc dfs ports cursor done i := by
+ rcases i with i | i | i <;> rfl
+
+/-- The contents of the geometry record, independent of the incoming leaf
+registers. The assembler also uses slots ten and eleven for other vertex roles. -/
+structure Stored (endAddr base : ℕ) (mem : Word w → Word w) (values : Fin 10 → Word w) : Prop where
+ pointer : mem (endAddr : Word w) = (base : Word w)
+ values_at : ∀ i : Fin 10, mem ((base+i.val : ℕ) : Word w) = values i
+
+/-- One private pointer read and ten private loads with address increments.
+Registers outside the ten destinations and the cursor are preserved. -/
+theorem run (M : Machine w p r k) (rows : ∀ i, M.code (pc i) = instruction pc dfs ports cursor done i)
+ (endAddr base : ℕ) (values : Fin 10 → Word w) (c : Config w p r) (entry : c.pc = pc (.inl ()))
+ (ptr : c.reg (dfs 6) = (endAddr : Word w)) (one : c.reg (dfs 3) = 1)
+ (saved : Stored endAddr base c.privateMem values)
+ (apart : ∀ j, cursor ≠ ports j) (unit_sep : ∀ j, dfs 3 ≠ ports j) (unit_cursor : dfs 3 ≠ cursor) :
+ ∃ out, Prefix M c (List.replicate 21 .tick) out ∧ out.pc = done ∧
+ (∀ i, out.reg (bank ports i) = values i) ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent ∧ ∀ j, j ≠ cursor → (∀ i, j ≠ ports i) → out.reg j = c.reg j := by
+ let start := c.put (readPC pc done 0) cursor (base : Word w)
+ have first : M.program.step c = .localStep start := by
+ change (M.code c.pc).run _ _ = _
+ rw [entry,rows]
+ simp only [instruction,Instr.run,ptr,saved.pointer,start]
+ let vals := fun j : Static 6 => values (offset j)
+ let inc := fun i : Fin (slots 6).length => pc (.inr (.inr i))
+ have rd (i : Fin (slots 6).length) : M.code (readPC pc done i.castSucc) =
+ readInstr ports cursor (inc i) (slots 6)[i] := by
+ have hr : readPC pc done i.castSucc = pc (.inr (.inl i)) := by
+ simp [readPC,show i.val < 10 from i.isLt]; rfl
+ rw [hr]
+ exact rows (.inr (.inl i))
+ have adv (i : Fin (slots 6).length) : M.code (inc i) =
+ incInstr cursor (dfs 3) (readPC pc done i.succ) := rows (.inr (.inr i))
+ have path := cached_rows M ports cursor (dfs 3) (fun j => apart j.dest)
+ (fun j => unit_sep j.dest) unit_cursor vals (slots 6) (readPC pc done) inc rd adv base start rfl
+ (Function.update_self ..) (by simp [start,Config.put,Function.update_of_ne unit_cursor,one])
+ (fun i => by
+ change c.privateMem ((base+i.val : ℕ) : Word w) = values (offset (fields i))
+ exact (saved.values_at i).trans (congrArg values (offset_field i)).symm)
+ refine ⟨_, .tick first path, rfl, ?_, rfl, rfl, ?_⟩
+ · intro i
+ change Function.update ((slots 6).foldl (setStatic ports vals) start.reg) cursor _ (ports (fields i).dest) = values i
+ rw [Function.update_of_ne (apart _).symm, fold_at, ite_eq_left (mem_slots _)]
+ exact congrArg values (offset_field i)
+ · intro j hj hu
+ change Function.update ((slots 6).foldl (setStatic ports vals) start.reg) cursor _ j = c.reg j
+ rw [Function.update_of_ne hj,fold_outside ports vals (slots 6) start.reg j (fun i => hu i.dest)]
+ exact Function.update_of_ne hj ..
+
+end PairSimulation.LeafGeometryLoad
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafGuard.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafGuard.lean
new file mode 100644
index 0000000000..68e38ccbb9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafGuard.lean
@@ -0,0 +1,169 @@
+import OAI.Computability.VPVNP.PairSimulationLeafStartup
+import OAI.Computability.VPVNP.RAMTapeSuccessorTotal
+import OAI.Computability.VPVNP.RAMProcessorChoices
+import OAI.Computability.VPVNP.RAMTapeSitePostPorts
+
+/-! # Successor fields and the private choice bank of a virtual validator -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafStartup
+
+open BurstRAM RAMLayout RAMTape LiveProgram PrivateRAM
+open RAMTape.SiteProcessorPorts
+
+set_option synthInstance.maxSize 10000
+
+variable {d e w k r p : ℕ}
+
+/-- Map a successor-check port into the leaf processor's cut-register bank. -/
+def guardPort (r k : ℕ) : Successors.Port → Port r k :=
+ cut r (expr k) ∘ SiteCutBank.ports
+
+theorem guardPort_injective (r k : ℕ) : Function.Injective (guardPort r k) :=
+ (cut_injective r _).comp SiteCutBank.ports_injective
+
+/-- The successor check with its ports assigned to the leaf's cut-register bank. -/
+def guard (r k : ℕ) : FiniteRoutine (Port r k) := Successors.checked.onPorts (guardPort r k)
+
+/-- The choice-generation routine that reads the processor's public budget and fills its
+private choice stack. -/
+def stream (r k : ℕ) : FiniteRoutine (Port r k) :=
+ .ofRoutine (ProcessorChoices.routine (pub r (expr k) ProcessorPublic.budgetPort)
+ (native r (expr k) (.test .choices)))
+
+variable (r : ℕ) (x : VirtualSite.Input d e w) (args : Fin k → Word w)
+
+/-- The successor-port stacks after finishing the incident record and computing the guard
+verdict for the virtual site. -/
+def finished : Stacks Successors.Port :=
+ Successors.guardResult (Successors.sharedFinish x.hc x.sends x.v (bank r x args ∘ guardPort r k))
+
+/-- The leaf's initial stack bank with the results of the successor guard installed on its
+assigned ports. -/
+noncomputable def guarded : Stacks (Port r k) :=
+ installStacks (guardPort r k) (bank r x args) (finished r x args)
+
+/-- The stack bank at interpreter entry, with the generated bits on the choice port and the
+spent public budget cleared. -/
+noncomputable def entered (bits : List Bool) : Stacks (Port r k) :=
+ Function.update (Function.update (guarded r x args) (pub r (expr k) ProcessorPublic.budgetPort) [])
+ (native r (expr k) (.test .choices)) bits
+
+theorem guarded_at (i : Successors.Port) :
+ guarded r x args (guardPort r k i) = finished r x args i :=
+ installStacks_at (guardPort_injective r k) _ _ i
+
+theorem guarded_native (i : SiteProcessor.Port r k) :
+ guarded r x args (native r (expr k) i) = bank r x args (native r (expr k) i) :=
+ installStacks_outside _ _ (fun j => Ne.symm (native_ne_cut r _ i (SiteCutBank.ports j)))
+
+theorem guarded_public (i : ProcessorPublic.Port) (hi : i ≠ ProcessorPublic.incidentPort) :
+ guarded r x args (pub r (expr k) i) = bank r x args (pub r (expr k) i) := by
+ by_cases h : ∃ j, SiteCutBank.ports j = Sum.inl i
+ · obtain ⟨j,hj⟩ := h
+ change guarded r x args (cut r _ (.inl i)) = bank r x args (cut r _ (.inl i))
+ rw [← hj, show cut r (expr k) (SiteCutBank.ports j) = guardPort r k j from rfl, guarded_at]
+ cases j with
+ | address | width | cap | initial | tmp | capTmp =>
+ simp only [finished, Successors.guardResult, Successors.sharedFinish, Successors.finish,
+ Successors.afterNormalize]
+ split <;> rfl
+ | incident => exact (hi (Sum.inl.inj hj).symm).elim
+ | outPresent | running | verdict | record | word => contradiction
+ · exact installStacks_outside _ _ (fun j hh => h ⟨j,cut_injective r _ hh⟩)
+
+theorem entered_native (bits : List Bool) (i : SiteProcessor.Port r k) :
+ entered r x args bits (native r (expr k) i) =
+ if i = .test .choices then bits else bank r x args (native r (expr k) i) := by
+ by_cases hi : i = .test .choices
+ · subst i; simp [entered]
+ · rw [entered, Function.update_of_ne (by simpa [native] using hi),
+ Function.update_of_ne (by simp [native, pub]), guarded_native, ite_eq_right hi]
+
+theorem entered_public (bits : List Bool) (i : ProcessorPublic.Port)
+ (hb : i ≠ ProcessorPublic.budgetPort) (hi : i ≠ ProcessorPublic.incidentPort) :
+ entered r x args bits (pub r (expr k) i) = bank r x args (pub r (expr k) i) := by
+ rw [entered, Function.update_of_ne (by simp [pub, native]), Function.update_of_ne (by simpa [pub] using hb),
+ guarded_public r x args i hi]
+
+theorem entered_guard (bits : List Bool) (i : Successors.Port) :
+ entered r x args bits (guardPort r k i) = finished r x args i := by
+ have hn : guardPort r k i ≠ native r (expr k) (.test .choices) :=
+ (native_ne_cut r (expr k) (.test .choices) (SiteCutBank.ports i)).symm
+ have hb : guardPort r k i ≠ pub r (expr k) ProcessorPublic.budgetPort := by
+ intro h
+ have he := cut_injective r (expr k) (show cut r _ (SiteCutBank.ports i) = cut r _ (.inl ProcessorPublic.budgetPort) from h)
+ exact (by decide : ∀ j, SiteCutBank.ports j ≠ .inl ProcessorPublic.budgetPort) i he
+ rw [entered, Function.update_of_ne hn, Function.update_of_ne hb, guarded_at]
+
+theorem registers (hv : x.valid) :
+ Successors.CutRegisters (bank r x args ∘ guardPort r k) (finished r x args) x.hw x.summary
+ ((List.ofFn (RAMLayout.incidentBits x.sends x.v)).drop (16*w)) :=
+ Successors.guarded_cutRegisters x.hw x.hc x.initialWord x.sends x.v _ rfl hv.1 hv.2
+
+theorem cost_at (hv : x.valid) (side : Successors.Side) :
+ finished r x args (.word side 1) = wordBits (x.sideWord side) := by
+ obtain ⟨z,hz,he⟩ := (registers r x args hv).cost side
+ exact hz.trans (congrArg wordBits (Fin.ext (he.trans (x.sideWord_val side).symm)))
+
+/-- The interpreter receives every decoded cut, all public words, and the
+generated bit string on the same ports used by its actual graph. -/
+theorem entered_call (T : Template p r k) (hv : x.valid) (bits : List Bool) :
+ entered r x args bits ∘ callPorts r (expr k) = (x.bare T args bits).bare := by
+ have hn := entered_native r x args bits
+ have hp := entered_public r x args bits
+ have ha := entered_guard r x args bits
+ have regs := registers r x args hv
+ funext i
+ change entered r x args bits (callPorts r (expr k) i) = _
+ cases i with
+ | isa i =>
+ cases i with
+ | persistent => exact (ha _).trans (regs.state .receive)
+ | logPort q => cases q <;> exact hn _
+ | reg | pub | work => exact hn _
+ | credit i =>
+ cases i with
+ | publicH | publicFuel | globalCap => exact hp _ (by decide) (by decide)
+ | budget j =>
+ cases j with
+ | site => exact hp _ (by decide) (by decide)
+ | cost => exact (ha _).trans (cost_at r x args hv .receive)
+ | fuel | call | globalLeft | tmp => exact hn _
+ | savedStart | ordinal | copyA | copyB | arithA | arithB => exact hn _
+ | test i =>
+ cases i with
+ | word j =>
+ cases j with
+ | lower | boundary => exact hp _ (by decide) (by decide)
+ | targetCost => exact (ha _).trans (cost_at r x args hv .send)
+ | targetState => exact (ha _).trans (regs.state .send)
+ | cost | cap | state => exact hn _
+ | bit j =>
+ cases j with
+ | running => exact (ha _).trans (regs.running .receive)
+ | hasTarget => exact (ha _).trans regs.outPresent
+ | targetRunning => exact (ha _).trans (regs.running .send)
+ | choices | verdict | left | right | tmp | out | sourceTmp | copyTmp => exact hn _
+ | record i =>
+ cases i with
+ | field j =>
+ fin_cases j
+ · exact hn _
+ · exact hp _ (by decide) (by decide)
+ · exact hp _ (by decide) (by decide)
+ · exact hn _
+ · exact hn _
+ | zeros => exact (hp _ (by decide) (by decide)).trans (UnaryWord.zeros_wordBits w).symm
+ | remaining => exact hp _ (by decide) (by decide)
+ | temp | reverseBuffer | output => exact hn _
+ | scratch j => exact hn _
+
+end PairSimulation.LeafStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafHandler.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafHandler.lean
new file mode 100644
index 0000000000..68e53ba87f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafHandler.lean
@@ -0,0 +1,204 @@
+import OAI.Computability.VPVNP.PairSimulationLeafNativeCount
+import OAI.Computability.VPVNP.PairSimulationStackScratch
+
+/-!
+# The cursor-leaf handler inside the descriptor traversal
+
+The deterministic prefix decodes the genuine site address, reads the shadow
+header, runs the local routing tests, and initializes the virtual bit stacks
+at cursor zero. The remaining native instructions implement the auxiliary
+machine on those supplied bits. The handler returns the entire unused
+choice suffix, including when the next descriptor needs no choices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafHandler
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork LeafStartup StackMachine DFS
+open scoped Fin.CommRing
+open private returns_prefix from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+set_option synthInstance.maxSize 10000
+
+variable {d e w W endAddr p r k : ℕ} [NeZero d]
+
+/-- Data and effects of the deterministic leaf prefix on the supplied private
+argument buffer. -/
+structure Input (d e w W endAddr : ℕ) where
+ /-- The cursor coordinate and site decoded from the leaf's physical node address. -/
+ pos : Position d
+ /-- The four half-wire buffers supplied by the parent to this cursor visit. -/
+ buffers : Buffers d (2^e) w
+ /-- The RAM events of the deterministic prefix before the transit return or auxiliary
+ interpreter call. -/
+ trace : List (Event W)
+ /-- The private scratch after routing and any stack initialization needed at cursor zero. -/
+ prepared : Scratch W endAddr
+
+variable {A : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout A n a H w}
+ (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (storage : StackMachine.Layout (Port 52 34) W)
+ (load : Word W → Scratch W endAddr → Input d e w W endAddr)
+ (clock : ℕ)
+
+/-- The local routing check accepts the decoded site position and the bits read from its four
+buffers. -/
+abbrev Routed (x : Input d e w W endAddr) : Prop :=
+ routeAccept (2^e) w x.pos (readBuffer x.buffers) = true
+
+/-- A linked leaf visit, using the exact push footprint also for cells of
+stacks later popped back to their original size. -/
+noncomputable def parser : HookParser W endAddr where
+ read node saved bits :=
+ let x := load node saved
+ if Routed x then
+ if x.pos.1 = 0 then
+ let bank := auxiliaryBank D hw hc x.pos x.buffers
+ match parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => none
+ | some result =>
+ if result.accept then
+ let f := footprint storage auxiliaryCode clock auxiliaryEntry bank bits
+ some (⟨node,x.trace ++ f.events,(· = saved),fun _ => f.applyScratch endAddr x.prepared⟩,result.rest)
+ else none
+ else some (⟨node,x.trace,(· = saved),fun _ => x.prepared⟩,bits)
+ else none
+
+variable {M : Machine W p r k} {visit ret : Fin p} {dfs : Fin 9 ↪ Fin r}
+ {pc : Option auxiliaryProcessor.State → Fin 7 → Fin p} {reg : Register (Port 52 34) ↪ Fin r}
+ {m : Memory W}
+
+/-- Native prefix specification, ending at either the verified stack
+interpreter's first row or the caller's continuation for a transit site. -/
+structure Preparation (domain : Word W → Scratch W endAddr → Prop) (M : Machine W p r k)
+ (visit ret : Fin p) (dfs : Fin 9 ↪ Fin r) (pc : Option auxiliaryProcessor.State → Fin 7 → Fin p)
+ (reg : Register (Port 52 34) ↪ Fin r) (m : Memory W) : Prop where
+ deterministic : ∀ node saved, domain node saved → choiceBits (load node saved).trace = []
+ run : ∀ node (c : Config W p r) top pending, domain node (scratch endAddr c.privateMem) →
+ c.pc = visit → c.reg (dfs 7) = node → DFS.Represents c.privateMem top pending →
+ top + pending.length = endAddr → c.reg (dfs 5) = (top : Word W) →
+ c.reg (dfs 6) = (endAddr : Word W) → c.reg (dfs 3) = 1 →
+ let x := load node (scratch endAddr c.privateMem)
+ Routed x → ∃ mid, mid.pc = (if x.pos.1 = 0 then pc auxiliaryEntry 0 else ret) ∧
+ mid.persistent = c.persistent ∧ (∀ j : Fin 9, j = 3 ∨ j = 5 ∨ j = 6 ∨ j = 7 →
+ mid.reg (dfs j) = c.reg (dfs j)) ∧ DFS.Represents mid.privateMem top pending ∧
+ scratch endAddr mid.privateMem = x.prepared ∧
+ (x.pos.1 = 0 → StackMachine.Represents storage reg mid (auxiliaryBank D hw hc x.pos x.buffers)) ∧
+ ∀ fuel bits, execute M.program (fuel+x.trace.length) c m bits =
+ (execute M.program fuel mid m bits).map (fun r => ⟨x.trace++r.events,r.result⟩)
+ reject : ∀ node (c : Config W p r) top pending, domain node (scratch endAddr c.privateMem) →
+ c.pc = visit → c.reg (dfs 7) = node → DFS.Represents c.privateMem top pending →
+ top + pending.length = endAddr → c.reg (dfs 5) = (top : Word W) →
+ c.reg (dfs 6) = (endAddr : Word W) → c.reg (dfs 3) = 1 →
+ ¬Routed (load node (scratch endAddr c.privateMem)) → ∀ bits, ¬Returns M c m bits
+
+/-- Exactness on the actual node and typed buffer domain, with arbitrary
+independent input bits, arbitrary used scratch, and arbitrary stream suffix. -/
+theorem parser_exactOn {domain : Word W → Scratch W endAddr → Prop}
+ (prep : Preparation D hw hc storage load domain M visit ret dfs pc reg m)
+ (linked : StackMachine.Linked M auxiliaryCode pc reg ret) (hW : 0 < W)
+ (apart : ∀ i j, dfs i ≠ reg j) (above : ∀ j, endAddr ≤ storage.base j)
+ (time : ∀ node saved, domain node saved → let x := load node saved
+ steps 52 (auxiliary D hw hc x.pos x.buffers) ≤ clock)
+ (room : ∀ node saved, domain node saved → let x := load node saved
+ ∀ j, (auxiliaryBank D hw hc x.pos x.buffers j).length + clock ≤ storage.capacity) :
+ (parser D hw hc storage load clock).ExactOn domain M visit ret dfs m := by
+ constructor
+ · intro node saved dom bits job tail read
+ let x := load node saved
+ let bank := auxiliaryBank D hw hc x.pos x.buffers
+ have det := prep.deterministic node saved dom
+ change choiceBits x.trace = [] at det
+ by_cases route : Routed x
+ · by_cases hz : x.pos.1 = 0
+ · let f := footprint storage auxiliaryCode clock auxiliaryEntry bank bits
+ have parsed : ∃ result, parse auxiliaryCode clock auxiliaryEntry bank bits = some result ∧
+ result.accept = true ∧ job = ⟨node,x.trace++f.events,(· = saved),fun _ => f.applyScratch endAddr x.prepared⟩ ∧
+ tail = result.rest := by
+ change (if Routed x then _ else none) = some (job,tail) at read
+ rw [ite_eq_left route,ite_eq_left hz] at read
+ change (match parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => none
+ | some y => if y.accept then some (⟨node,x.trace++f.events,(· = saved),fun _ => f.applyScratch endAddr x.prepared⟩,y.rest) else none) = some (job,tail) at read
+ cases h : parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => rw [h] at read; contradiction
+ | some y =>
+ rw [h] at read
+ cases ok : y.accept with
+ | false => simp [ok] at read
+ | true =>
+ simp only [ok,↓reduceIte,Option.some.injEq,Prod.mk.injEq] at read
+ exact ⟨y,rfl,ok,read.1.symm,read.2.symm⟩
+ obtain ⟨y,hy,ok,rfl,rfl⟩ := parsed
+ have splitBits := (footprint_parse storage hy ok).1
+ refine ⟨rfl,rfl,?_,?_⟩
+ · simpa only [PrimedInputRAM.Flow.choiceBits_append,det,List.nil_append] using splitBits
+ · intro c top pending enabled atPC nodeReg stack atEnd topReg endReg one
+ change scratch endAddr c.privateMem = saved at enabled
+ obtain ⟨mid,dst,persist,keep,st,sc,represented,start⟩ := prep.run node c top pending
+ (enabled ▸ dom) atPC nodeReg stack atEnd topReg endReg one (by rwa [enabled])
+ rw [enabled] at dst sc represented start
+ have stops := (auxiliary_closed D hw hc x.pos x.buffers hz route clock (time _ _ dom)).2
+ obtain ⟨out,run,retpc,_,mem,frame⟩ := footprint_native linked hW
+ (fun _ _ h j => reachable_capacity stops (room _ _ dom) h j) hy ok mid
+ (by simpa [x,hz] using dst) (represented hz)
+ have regs (j : Fin 9) (h : j = 3 ∨ j = 5 ∨ j = 6 ∨ j = 7) :=
+ (frame.dfsReg dfs apart j).trans (keep j h)
+ refine ⟨out,retpc,(regs 7 (by decide)).trans nodeReg,(regs 5 (by decide)).trans topReg,
+ (regs 6 (by decide)).trans endReg,(regs 3 (by decide)).trans one,frame.persistent.trans persist,
+ frame.keepsPending above atEnd st,?_,?_⟩
+ · rw [mem,Footprint.scratch_applyWrites,sc]
+ · intro fuel more
+ change execute M.program (fuel+(x.trace++f.events).length) c m (choiceBits (x.trace++f.events)++more) = _
+ rw [PrimedInputRAM.Flow.choiceBits_append,det,List.nil_append,List.length_append,
+ show fuel+(x.trace.length+f.events.length)=(fuel+f.events.length)+x.trace.length by omega,
+ start,run.execute]
+ simp only [Option.map_map,Function.comp_def,List.append_assoc]; rfl
+ · have ht : job = ⟨node,x.trace,(· = saved),fun _ => x.prepared⟩ ∧ tail = bits := by
+ simpa only [parser,show load node saved = x from rfl,ite_eq_left route,ite_eq_right hz,Option.some.injEq,Prod.mk.injEq] using read.symm
+ obtain ⟨rfl,rfl⟩ := ht
+ refine ⟨rfl,rfl,by simp [det],?_⟩
+ intro c top pending enabled atPC nodeReg stack atEnd topReg endReg one
+ change scratch endAddr c.privateMem = saved at enabled
+ obtain ⟨mid,dst,persist,keep,st,sc,_,start⟩ := prep.run node c top pending
+ (enabled ▸ dom) atPC nodeReg stack atEnd topReg endReg one (by rwa [enabled])
+ rw [enabled] at dst sc start
+ refine ⟨mid,?_,(keep 7 (by decide)).trans nodeReg,(keep 5 (by decide)).trans topReg,
+ (keep 6 (by decide)).trans endReg,(keep 3 (by decide)).trans one,persist,st,sc,?_⟩
+ · simpa only [show load node saved = x from rfl,hz,↓reduceIte] using dst
+ · intro fuel more
+ simpa only [det,List.nil_append] using start fuel more
+ · simp only [parser,show load node saved = x from rfl,ite_eq_right route,reduceCtorEq] at read
+ · intro node bits c top pending dom atPC nodeReg stack atEnd topReg endReg one fail
+ let saved := scratch endAddr c.privateMem
+ let x := load node saved
+ let bank := auxiliaryBank D hw hc x.pos x.buffers
+ by_cases route : Routed x
+ · obtain ⟨mid,dst,_,_,_,_,represented,start⟩ := prep.run node c top pending dom atPC nodeReg stack
+ atEnd topReg endReg one route
+ by_cases hz : x.pos.1 = 0
+ · have bad : acceptPrefix auxiliaryCode clock auxiliaryEntry bank bits = none := by
+ cases h : parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => simp [acceptPrefix,haltPrefix,h]
+ | some y =>
+ cases ok : y.accept with
+ | false => simp [acceptPrefix,haltPrefix,h,ok]
+ | true =>
+ simp only [parser,show load node (scratch endAddr c.privateMem) = x from rfl,ite_eq_left route,ite_eq_left hz,
+ show auxiliaryBank D hw hc x.pos x.buffers = bank from rfl,h,ok,↓reduceIte,reduceCtorEq] at fail
+ have stops := (auxiliary_closed D hw hc x.pos x.buffers hz route clock (time _ _ dom)).2
+ have reject := rejects_returns linked hW (fun _ _ h j => reachable_capacity stops (room _ _ dom) h j)
+ stops mid (by simpa only [show load node (scratch endAddr c.privateMem) = x from rfl,hz,↓reduceIte] using dst)
+ (represented hz) m bits bad
+ exact fun ok => reject ((returns_prefix (fun fuel => start fuel bits)).mp ok)
+ · simp only [parser,show load node (scratch endAddr c.privateMem) = x from rfl,ite_eq_left route,ite_eq_right hz,reduceCtorEq] at fail
+ · exact prep.reject node c top pending dom atPC nodeReg stack atEnd topReg endReg one route bits
+
+end PairSimulation.LeafHandler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafImage.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafImage.lean
new file mode 100644
index 0000000000..92e624e769
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafImage.lean
@@ -0,0 +1,221 @@
+import OAI.Computability.VPVNP.PairSimulationLeafFront
+import OAI.Computability.VPVNP.PairSimulationLeafBootHandoff
+import OAI.Computability.VPVNP.PairSimulationRouteBank
+
+/-!
+# Native instruction image of a descriptor leaf
+
+The address reader shares the DFS node slot. A transit cursor returns directly
+from the route check. At cursor zero, seven instructions copy the site and header
+and supply the two private-memory pointers to the stack initializer. The
+initialized stack pointers are the ones used by the auxiliary processor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafImage
+
+open BurstRAM PrivateRAM RAMTape LeafStartup
+
+set_option synthInstance.maxSize 10000
+
+/-- Internal labels of the leaf call. The return label belongs to its caller. -/
+inductive Label where
+ | address (i : Fin 20)
+ | prepare (i : RoutePrepare.Stage)
+ | route (i : RouteBank.Address)
+ | handoff (i : Fin 7)
+ | boot (i : LeafBoot.Label)
+ | stack (q : Option auxiliaryProcessor.State) (i : Fin 7)
+
+noncomputable instance : Fintype Label := by classical exact derive_fintype% _
+
+/-- The address reader uses the caller's node register and eight private slots. -/
+inductive Reg where
+ | dfs (i : Fin 9)
+ | address (i : {j : LeafAddress.Reg // j ≠ .node})
+ | route (i : Fin 32)
+ | boot (i : LeafBoot.Reg)
+
+noncomputable instance : Fintype Reg := by classical exact derive_fintype% _
+
+/-- Public operands of the leaf image, grouped into address fields, private arena fields, and
+input size. -/
+inductive Pub where
+ | address (j : LeafAddress.Field)
+ | arena (j : RoutePrepare.Field)
+ | size
+ deriving DecidableEq, Fintype
+
+variable {p r k w : ℕ}
+
+private def leafName (j : LeafAddress.Reg) : Reg :=
+ if h : j = .node then .dfs 7 else .address ⟨j,h⟩
+
+private theorem leafName_injective : Function.Injective leafName := by
+ let back : Reg → LeafAddress.Reg := fun
+ | .address j => j.val
+ | _ => .node
+ apply Function.LeftInverse.injective (g := back)
+ intro i
+ by_cases h : i = .node <;> simp [back,leafName,h]
+
+variable (pc : Label → Fin p) (reg : Reg ↪ Fin r) (pub : Pub → Fin k) (ret : Fin p)
+
+/-- Embed the nine caller DFS registers into the register bank of the linked leaf. -/
+def dfsReg : Fin 9 ↪ Fin r := ⟨fun i => reg (.dfs i),fun _ _ h => Reg.dfs.inj (reg.injective h)⟩
+
+/-- Assign the address decoder's registers, sharing its node input with DFS register 7. -/
+def leafReg : LeafAddress.Reg ↪ Fin r := ⟨fun i => reg (leafName i),reg.injective.comp leafName_injective⟩
+
+/-- Assign the routing test's 32 registers to their slots in the linked leaf. -/
+def routeReg : Fin 32 ↪ Fin r := ⟨fun i => reg (.route i),fun _ _ h => Reg.route.inj (reg.injective h)⟩
+
+/-- Assign the leaf initializer's registers to their slots in the linked leaf. -/
+def bootReg : LeafBoot.Reg ↪ Fin r := ⟨fun i => reg (.boot i),fun _ _ h => Reg.boot.inj (reg.injective h)⟩
+
+@[simp] theorem node_dfs : leafReg reg .node = dfsReg reg 7 := rfl
+
+theorem dfs_preserved (i : Fin 9) : LeafAddress.Preserved (leafReg reg) (dfsReg reg i) := by
+ intro j hj
+ apply reg.injective.ne
+ simp [leafName,hj]
+
+theorem dfs_ne_route (i : Fin 9) (j : Fin 32) : dfsReg reg i ≠ routeReg reg j :=
+ reg.injective.ne (by intro h; cases h)
+
+theorem dfs_ne_boot (i : Fin 9) (j : LeafBoot.Reg) : dfsReg reg i ≠ bootReg reg j :=
+ reg.injective.ne (by intro h; cases h)
+
+theorem dfs_offBoot (i : Fin 9) : dfsReg reg i ∉ Set.range (bootReg reg) :=
+ fun ⟨j,h⟩ => dfs_ne_boot reg i j h.symm
+
+theorem dfs_ne_stack (i : Fin 9) (j : StackMachine.Register ScalarPort) :
+ dfsReg reg i ≠ LeafBoot.stack (bootReg reg) j := dfs_ne_boot reg i _
+
+theorem leaf_ne_route (i : LeafAddress.Reg) (j : Fin 32) : leafReg reg i ≠ routeReg reg j := by
+ apply reg.injective.ne
+ by_cases h : i = .node <;> simp [leafName,h]
+
+theorem leaf_ne_boot (i : LeafAddress.Reg) (j : LeafBoot.Reg) : leafReg reg i ≠ bootReg reg j := by
+ apply reg.injective.ne
+ by_cases h : i = .node <;> simp [leafName,h]
+
+theorem dfs_not_written (i : Fin 9) : ¬ LeafBootHandoff.Written (bootReg reg) (dfsReg reg i) := by
+ intro h
+ rcases h with h | h | h | h | h <;> exact dfs_ne_boot reg i _ h
+
+/-- Locate an initializer instruction using its boot label in the linked leaf image. -/
+def bootPC : LeafBoot.Label → Fin p := pc ∘ Label.boot
+/-- Locate the specified native instruction row of an auxiliary stack-machine state. -/
+def stackPC (q : Option auxiliaryProcessor.State) (i : Fin 7) : Fin p := pc (.stack q i)
+
+/-- Connect the address decoder and routing instructions to the cursor-zero handoff and the
+caller's transit return. -/
+def front : LeafFront.Program p r k where
+ addressPC := pc ∘ Label.address
+ leaf := leafReg reg
+ addressPub := pub ∘ Pub.address
+ preparePC := pc ∘ Label.prepare
+ preparePub := pub ∘ Pub.arena
+ route := RouteBank.program (pc ∘ Label.route) (routeReg reg)
+ init := pc (.handoff 0)
+ transit := ret
+ apart := leaf_ne_route reg
+
+/-- Literal-width five retains the constants of the geometry and initializer
+rows. The placement functions and the return label are supplied by the host. -/
+noncomputable def instruction : Label → Instr 5 p r k
+ | .address i => LeafAddress.instruction (pc ∘ Label.address) (leafReg reg) (pub ∘ Pub.address)
+ (pc (.prepare (.inl 0))) (pc (.prepare (.inl 0))) i
+ | .prepare i => RoutePrepare.instruction (pc ∘ Label.prepare) (routeReg reg) (leafReg reg)
+ (pub ∘ Pub.arena) ((front pc reg pub ret).route.pc 0) i
+ | .route (.inl a) => (RouteBank.text (pc ∘ Label.route) (routeReg reg) (.inl a)).resize 5
+ | .route (.inr i) =>
+ if i = 0 then .jumpEq (routeReg reg 0) (routeReg reg 17) (pc (.handoff 0)) ret else .reject
+ | .handoff i => LeafBootHandoff.instruction (pc ∘ Label.handoff) (bootReg reg) (leafReg reg)
+ (pub ∘ Pub.arena) (bootPC pc (.pre 0)) i
+ | .boot i => LeafBoot.instruction (bootPC pc) (bootReg reg) (pub .size) (stackPC pc auxiliaryEntry 0) i
+ | .stack q i => StackMachine.instruction auxiliaryCode (stackPC pc) (LeafBoot.stack (bootReg reg)) ret q i
+
+/-- All native interfaces used by the caller's execution proof. -/
+structure Linked (M : Machine w p r k) : Prop where
+ front : (LeafImage.front pc reg pub ret).Linked M
+ handoff : ∀ i, M.code (pc (.handoff i)) = LeafBootHandoff.instruction (pc ∘ Label.handoff)
+ (bootReg reg) (leafReg reg) (pub ∘ Pub.arena) (bootPC pc (.pre 0)) i
+ boot : LeafBoot.Linked (bootPC pc) (bootReg reg) (pub .size) (stackPC pc auxiliaryEntry 0) M
+ stack : StackMachine.Linked M auxiliaryCode (stackPC pc) (LeafBoot.stack (bootReg reg)) ret
+
+private theorem resize_one (i : Instr 1 p r k) : (i.resize 5).resize w = i.resize w := by
+ cases i <;> try rfl
+ case constant dst v next => simp only [Instr.resize,resize_literal (by decide : 1 ≤ 5)]
+
+theorem linked (M : Machine w p r k)
+ (rows : ∀ i, M.code (pc i) = (instruction pc reg pub ret i).resize w) :
+ Linked pc reg pub ret M := by
+ constructor
+ · constructor
+ · intro i
+ change M.code (pc (.address i)) = _
+ rw [rows (.address i)]
+ simp only [instruction]
+ rw [← LeafAddress.resize_instruction (w := 5), resize_one, LeafAddress.resize_instruction]
+ rfl
+ · intro i
+ exact (rows (.prepare i)).trans (RoutePrepare.resize_instruction ..)
+ · apply RouteBank.linked
+ intro a
+ exact (rows (.route (.inl a))).trans (resize_one _)
+ · exact rows (.route (.inr 0))
+ · exact rows (.route (.inr 1))
+ · intro i
+ rw [rows (.handoff i)]
+ simp only [instruction]
+ rw [← LeafBootHandoff.resize_instruction (w := 5),resize_one,LeafBootHandoff.resize_instruction]
+ · intro i
+ exact (rows (.boot i)).trans (LeafBoot.resize_instruction ..)
+ · intro q i
+ change M.code (pc (.stack q i)) = _
+ rw [rows (.stack q i)]
+ simp only [instruction]
+ rw [← StackMachine.resize_instruction (w := 5),resize_one,StackMachine.resize_instruction]
+
+/-- Canonical finite image with an accepting return. An enclosing DFS template
+can instead use `instruction` at its own labels and supply its loop continuation. -/
+abbrev Address := Label ⊕ Unit
+/-- Number the internal leaf instructions in the standalone template's address space, which
+also reserves a return address. -/
+noncomputable def locations : Label → Fin (Fintype.card Address) := fun i => Fintype.equivFin Address (.inl i)
+/-- The standalone template's designated return address, occupied by an accepting instruction. -/
+noncomputable def returnPC : Fin (Fintype.card Address) := Fintype.equivFin Address (.inr ())
+/-- Number the named leaf registers for use by the standalone template. -/
+noncomputable def registers : Reg ↪ Fin (Fintype.card Reg) := (Fintype.equivFin Reg).toEmbedding
+/-- Number the named leaf operands for use in the standalone template's public data. -/
+noncomputable def publics : Pub ≃ Fin (Fintype.card Pub) := Fintype.equivFin Pub
+
+/-- The standalone native leaf program with five-bit literals, entry at the first
+address-decoding row, and an accepting return instruction. -/
+noncomputable def template : Template (Fintype.card Address) (Fintype.card Reg) (Fintype.card Pub) where
+ literalWidth := 5
+ entry := locations (.address 0)
+ code i := match (Fintype.equivFin Address).symm i with
+ | .inl a => instruction locations registers publics returnPC a
+ | .inr _ => .accept
+
+theorem template_linked (data : Fin (Fintype.card Pub) → Word w) :
+ Linked locations registers publics returnPC (template.instantiate w data) := by
+ apply linked
+ intro i
+ simp [Template.instantiate,template,locations]
+
+theorem template_return (data : Fin (Fintype.card Pub) → Word w) :
+ (template.instantiate w data).code returnPC = .accept := by
+ simp [Template.instantiate,template,returnPC,Instr.resize]
+
+end PairSimulation.LeafImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafImageFrame.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafImageFrame.lean
new file mode 100644
index 0000000000..2427002412
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafImageFrame.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.PairSimulationLeafImageHandler
+import OAI.Computability.VPVNP.PairSimulationLeafFrame
+
+/-! # Preserving the other descriptor inputs, histogram and geometry at a leaf -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafVisit
+
+open BurstRAM PrivateRAM LeafHandler LeafStartup DFS CursorNetwork
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ} {A : PrimedInputRAM.Lengths} {n a H s : ℕ}
+ {Q : PrimedInputRAM.Layout A n a H w} (D : PrimedCounter.Data Q s)
+ {b l e endAddr : ℕ} [NeZero (b+l)] (budget : ProcessorBudget n (b+l) e w)
+ (R : LeafArena.Regions) (fit : R.stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ {M : Machine w p r k} (pub : LeafImage.Pub → Fin k) (m : Memory w)
+
+theorem loaded_below (f : LeafAddress.Field → Word w) (node : Word w) (saved : Scratch w endAddr)
+ (i : {a : Word w // endAddr ≤ a.val}) (below : i.val.val < R.stackBase) :
+ (loaded D budget R fit f m node saved).prepared i = saved i := by
+ let L := storage R fit
+ let x := loaded D budget R fit f m node saved
+ let bank := auxiliaryBank D budget.tags budget.capFits x.pos x.buffers
+ have h : ¬ ∃ j, LeafLoadedBank.occupies L bank i.val j := by
+ rintro ⟨j,bot,_⟩
+ exact (not_le_of_gt (below.trans_le (R.stack_above _ _ fit j))) bot
+ change (if x.pos.1 = 0 then LeafLoadedBank.scratch L bank saved else saved) i = _
+ split
+ · simp only [LeafLoadedBank.scratch,LeafLoadedBank.readCell,dite_eq_right h,Option.getD_none]
+ · rfl
+
+/-- A successful physical leaf leaves every word below its allocated stacks
+unchanged. This includes the cache of 38 actual auxiliary operands, the
+geometry pointer and descriptors, the parent and sibling argument packets,
+and the label histogram. -/
+theorem read_below (clock : ℕ) (node : Word w) (saved : Scratch w endAddr)
+ (bits : List Bool) {job : VisitPath w endAddr} {tail : List Bool}
+ (read : (leafParser (M := M) D budget R fit pub m clock).read node saved bits = some (job,tail))
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length + clock ≤ n^40)
+ (i : {a : Word w // endAddr ≤ a.val}) (below : i.val.val < R.stackBase) :
+ job.update saved i = saved i := by
+ let f := fields (M := M) pub
+ let input := loaded (endAddr := endAddr) D budget R fit f m
+ obtain ⟨_,_,_,frame⟩ := parser_observations D budget.tags budget.capFits (storage R fit) input clock
+ node saved bits tail job read (trace_bits D budget m f _ _) (room _ _)
+ exact (frame i fun j => Or.inl (below.trans_le (R.stack_above _ _ fit j))).trans
+ (loaded_below D budget R fit m f node saved i below)
+
+end PairSimulation.LeafVisit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafImageHandler.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafImageHandler.lean
new file mode 100644
index 0000000000..d222885ce1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafImageHandler.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.PairSimulationLeafImagePreparation
+import OAI.Computability.VPVNP.PairSimulationLeafReadback
+import OAI.Computability.VPVNP.PairSimulationLeafArena
+
+/-! # Exact cursor-leaf role of the bounded terminal-site simulator -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafVisit
+
+open BurstRAM PrivateRAM CursorNetwork CursorRouting LeafHandler LeafStartup DFS
+open Filter
+open scoped Fin.CommRing
+
+set_option synthInstance.maxSize 10000
+
+variable {w p r k : ℕ} {A : PrimedInputRAM.Lengths} {n a H s : ℕ}
+ {Q : PrimedInputRAM.Layout A n a H w} (D : PrimedCounter.Data Q s)
+ {b l e degree pad endAddr : ℕ} [NeZero (b+l)] (hD : 1 < b+l) (hd : 2+pad=2^degree)
+ (budget : ProcessorBudget n (b+l) e w) (R : LeafArena.Regions) (cap : ℕ)
+ (fit : R.stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+
+variable {M : Machine w p r k} (pc : LeafImage.Label → Fin p) (reg : LeafImage.Reg ↪ Fin r)
+ (pub : LeafImage.Pub → Fin k) (ret : Fin p) (m : Memory w)
+
+/-- The DFS leaf parser for the concrete instruction image, using its public address fields,
+physical argument buffers, stack layout, and interpreter clock. -/
+noncomputable def leafParser (clock : ℕ) : HookParser w endAddr :=
+ parser D budget.tags budget.capFits (storage R fit)
+ (loaded D budget R fit (fields (M := M) pub) m) clock
+
+/-- The finite table implements the entire cursor factor at each genuine
+leaf with the parent's supplied half-wires. The header, routing, private
+input banks and accepting choice interpreter all belong to its execution. -/
+theorem image_exact (clock : ℕ) (link : LeafImage.Linked pc reg pub ret M)
+ (op : LeafFront.Operands (LeafImage.front pc reg pub ret) M m D R b l cap)
+ (hsize : M.publicData (pub .size) = (n : Word w)) (lo : endAddr ≤ R.arguments.start)
+ (time : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w),
+ steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ clock)
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length + clock ≤ n^40) :
+ (leafParser (endAddr := endAddr) (M := M) D budget R fit pub m clock).ExactOn
+ (Domain (e := e) D hD hd R cap (fields (M := M) pub)) M (pc (.address 0)) ret (LeafImage.dfsReg reg) m := by
+ have sourceRoom (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j :=
+ (Nat.le_add_right _ clock).trans (room v buf j)
+ have prep := preparation D hD hd budget R cap fit pc reg pub ret m link op hsize lo sourceRoom
+ exact parser_exactOn D budget.tags budget.capFits (storage R fit) _ clock prep link.stack
+ (by have := budget.tags; omega) (LeafImage.dfs_ne_stack reg)
+ (R.stack_above_dfs _ _ fit lo) (fun _ _ _ => time _ _) (fun _ _ _ => room _ _)
+
+/-- The source clock and stack space in the exactness theorem hold
+eventually with the actual auxiliary machine's private cutoff. -/
+theorem eventually_resources :
+ ∀ᶠ n : ℕ in atTop, ∀ d e w [NeZero d] (budget : ProcessorBudget n d e w)
+ (A : PrimedInputRAM.Lengths) (a H s : ℕ) (Q : PrimedInputRAM.Layout A n a H w) (D : PrimedCounter.Data Q s),
+ D.fuel ≤ n^10 → ∀ (v : Position d) (buf : Buffers d (2^e) w),
+ steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ n^39 ∧
+ ∀ j, (auxiliaryBank D budget.tags budget.capFits v buf j).length+n^39 ≤ n^40 := by
+ filter_upwards [eventually_steps 52, eventually_ge_atTop 128] with n bound hn
+ intro d e w _ budget A a H s Q D hf v buf
+ let x := auxiliary D budget.tags budget.capFits v buf
+ refine ⟨bound d e w x budget hf,fun j => ?_⟩
+ have h₁ := bank_length_le x 52 hn budget hf D.pub j
+ have h₂ := Nat.pow_le_pow_right (by omega : 1 ≤ n) (by decide : 12 ≤ 39)
+ have h₃ : 2*n^39 ≤ n^40 := by rw [pow_succ' n 39]; exact Nat.mul_le_mul_right _ (by omega)
+ change (bank 52 x D.pub j).length+n^39 ≤ n^40
+ omega
+
+end PairSimulation.LeafVisit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafImagePreparation.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafImagePreparation.lean
new file mode 100644
index 0000000000..0f1e055ce5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafImagePreparation.lean
@@ -0,0 +1,233 @@
+import OAI.Computability.VPVNP.PairSimulationLeafImage
+import OAI.Computability.VPVNP.PairSimulationLeafBootClock
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentArena
+import OAI.Computability.VPVNP.PairSimulationLeafPhysicalInput
+
+/-! # Running the actual finite cursor-leaf image on a stored DFS packet -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafVisit
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork LeafHandler LeafStartup DFS
+open NodeArguments LocalHistory TraversalRows PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+set_option synthInstance.maxSize 10000
+
+variable {w p r k : ℕ} {A : PrimedInputRAM.Lengths} {n a H s : ℕ}
+ {Q : PrimedInputRAM.Layout A n a H w} (D : PrimedCounter.Data Q s)
+ {b l e degree pad endAddr : ℕ} [NeZero (b+l)]
+ (hD : 1 < b+l) (hd : 2+pad = 2^degree) (budget : ProcessorBudget n (b+l) e w)
+ (R : LeafArena.Regions) (cap : ℕ)
+ (fit : R.stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+
+/-- The auxiliary stack layout in the leaf's private arena, assigning capacity n^40 to each
+port in the fixed port order. -/
+noncomputable abbrev storage := R.layout portOrder.symm.toEmbedding (n^40) fit
+
+/-- The whole deterministic prefix, including the seven operand-transfer
+instructions on a cursor-zero visit. -/
+noncomputable def trace (m : Memory w) (fields : LeafAddress.Field → Word w)
+ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) : List (Event w) :=
+ LeafFront.trace m fields v e w ++
+ if v.1 = 0 then List.replicate (7+LeafBoot.ticks D budget.tags budget.capFits v.2 buf) .tick else []
+
+/-- Decode the node and its private buffers into a leaf handler input, including the prefix
+trace and the initialized auxiliary scratch for a cursor-zero visit. -/
+noncomputable def loaded (fields : LeafAddress.Field → Word w) (m : Memory w)
+ (node : Word w) (saved : Scratch w endAddr) : Input (b+l) e w w endAddr :=
+ let v := physicalPosition (b+l) fields node
+ let buf := physicalBuffers (b+l) (2^e) w R.arguments node saved
+ let bank := auxiliaryBank D budget.tags budget.capFits v buf
+ ⟨v,buf,trace D budget m fields v buf,
+ if v.1 = 0 then LeafLoadedBank.scratch (storage R fit) bank saved else saved⟩
+
+/-- The static words cached for the leaf initializer, giving the cursor dimension, word width,
+bucket size, auxiliary fuel, and public operands. -/
+def cacheWords (d e : ℕ) : LeafSourceLoad.Static 34 → Word w
+ | .d => d | .width => w | .bucket => ((2^e : ℕ) : Word w) | .fuel => D.fuel | .operand i => D.pub i
+
+private theorem cache_eq {d : ℕ} (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (v : Position d) (buf : Buffers d (2^e) w) :
+ (fun j : LeafSourceLoad.Static 34 => LeafRegisterBank.sourceWord (auxiliary D hw hc v buf) D.pub j.dest) =
+ cacheWords D d e := by
+ funext i; cases i <;> rfl
+
+/-- Data actually stored by the parent node and the final-site cache writer.
+The buffers need no compatibility condition across distinct wires. -/
+def Domain (fields : LeafAddress.Field → Word w) (node : Word w) (saved : Scratch w endAddr) : Prop :=
+ node.val < R.nodes ∧ LeafSourceLoad.Cached R.cacheBase (rawScratch saved) (cacheWords D (b+l) e) ∧
+ ∃ (v : Position (b+l))
+ (z : (LeafArguments.state hD hd (2^e) w).network.Half (lanePositions (cursorCoordinateLabels b l) v)),
+ node.val = (sitePointers cap (fields .base).val (siteOrder (LeafArguments.state hD hd (2^e) w))
+ (lanePositions (cursorCoordinateLabels b l) v)).1 ∧
+ (cursorPacket hD hd node.val v z).Fits R.arguments w endAddr ∧
+ (cursorPacket hD hd node.val v z).Stored R.arguments saved
+
+include fit in
+private theorem cache_actual {endAddr : ℕ} (lo : endAddr ≤ R.arguments.start)
+ (m : Word w → Word w) (vals : LeafSourceLoad.Static 34 → Word w)
+ (cached : LeafSourceLoad.Cached R.cacheBase (rawScratch (scratch endAddr m)) vals) :
+ LeafSourceLoad.Cached R.cacheBase m vals := by
+ intro i
+ have jlt : i.offset < 38 := by cases i <;> simp [LeafSourceLoad.Static.offset]; omega
+ have upper : R.cacheBase + i.offset < 2^w :=
+ (R.cache_before ⟨_,jlt⟩).trans ((Nat.le_add_right _ _).trans_lt fit)
+ have low : endAddr ≤ R.cacheBase := by
+ unfold LeafArena.Regions.cacheBase LeafArena.Regions.histBase Arena.base; omega
+ have lower : endAddr ≤ ((R.cacheBase+i.offset : ℕ) : Word w).val := by
+ rw [Fin.val_natCast,Nat.mod_eq_of_lt upper]; omega
+ have h := cached i
+ simpa only [rawScratch,lower,↓reduceDIte,scratch] using h
+
+private theorem bits_ticks (n : ℕ) : choiceBits (List.replicate n (.tick : Event w)) = [] := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa only [List.replicate_succ,choiceBits] using ih
+
+theorem trace_bits (m : Memory w) (fields : LeafAddress.Field → Word w)
+ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) : choiceBits (trace D budget m fields v buf) = [] := by
+ rw [trace,PrimedInputRAM.Flow.choiceBits_append,(LeafFront.trace_cost m fields v e w).2,List.nil_append]
+ split <;> first | exact bits_ticks _ | rfl
+
+variable {M : Machine w p r k} (pc : LeafImage.Label → Fin p) (reg : LeafImage.Reg ↪ Fin r)
+ (pub : LeafImage.Pub → Fin k) (ret : Fin p) (m : Memory w)
+
+/-- Read the address decoder's public operands from the linked machine through the leaf's port
+assignment. -/
+abbrev fields := M.publicData ∘ pub ∘ LeafImage.Pub.address
+
+set_option maxHeartbeats 1600000 in
+/-- Every row of the concrete finite leaf image executes the deterministic
+prefix required by the DFS hook, including the malformed-route exit. -/
+theorem preparation (link : LeafImage.Linked pc reg pub ret M)
+ (op : LeafFront.Operands (LeafImage.front pc reg pub ret) M m D R b l cap)
+ (hsize : M.publicData (pub .size) = (n : Word w)) (lo : endAddr ≤ R.arguments.start)
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length ≤ n^40) :
+ Preparation (endAddr := endAddr) D budget.tags budget.capFits (storage R fit) (loaded D budget R fit (fields (M := M) pub) m)
+ (Domain (e := e) D hD hd R cap (fields (M := M) pub)) M (pc (.address 0)) ret (LeafImage.dfsReg reg)
+ (LeafImage.stackPC pc) (LeafBoot.stack (LeafImage.bootReg reg)) m := by
+ let P := LeafImage.front pc reg pub ret
+ let f := fields (M := M) pub
+ let L := storage R fit
+ let boot := LeafImage.bootReg reg
+ have hW := (RouteSchedule.hostFits budget (le_refl w)).1.le
+ have actual (node : Word w) (c : Config w p r) (dom : Domain (e := e) D hD hd R cap f node (scratch endAddr c.privateMem))
+ (hc : c.pc = pc (.address 0)) (hn : c.reg (LeafImage.dfsReg reg 7) = node) :
+ ∃ (v : Position (b+l)) (z : (LeafArguments.state hD hd (2^e) w).network.Half
+ (lanePositions (cursorCoordinateLabels b l) v)),
+ let buf := LeafArguments.buffers hD hd v z
+ let x := loaded D budget R fit f m node (scratch endAddr c.privateMem)
+ x = ⟨v,buf,trace D budget m f v buf,if v.1 = 0 then
+ LeafLoadedBank.scratch L (auxiliaryBank D budget.tags budget.capFits v buf) (scratch endAddr c.privateMem)
+ else scratch endAddr c.privateMem⟩ ∧
+ (cursorPacket hD hd node.val v z).Fits R.arguments w endAddr ∧
+ (cursorPacket hD hd node.val v z).Stored R.arguments (scratch endAddr c.privateMem) ∧
+ LeafSourceLoad.Cached R.cacheBase c.privateMem (cacheWords D (b+l) e) ∧
+ (routeAccept (2^e) w v (readBuffer buf) = true → ∃ q, LeafFront.Result P D v c q ∧
+ ∀ fuel bits, execute M.program (fuel+(LeafFront.trace m f v e w).length) c m bits =
+ (execute M.program fuel q m bits).map fun x => ⟨LeafFront.trace m f v e w++x.events,x.result⟩) ∧
+ (routeAccept (2^e) w v (readBuffer buf) = false → ∀ bs, ¬Returns M c m bs) := by
+ obtain ⟨_,hc',v,z,row,space,stored⟩ := dom
+ have cache := cache_actual R fit lo c.privateMem (cacheWords D (b+l) e) hc'
+ have cache3 := LeafFront.Cache.of_cached cache (show cacheWords D (b+l) e .d = _ from rfl)
+ (show cacheWords D (b+l) e .width = _ from rfl) (show cacheWords D (b+l) e .bucket = _ from rfl)
+ have pf := LeafFront.native link.front m D R cap op hD hd budget (le_refl _) node v z c hc hn
+ row cache3 space stored
+ refine ⟨v,z,?_,space,stored,cache,pf⟩
+ unfold loaded
+ rw [physicalPosition_eq hD hd f node cap v hW op.stride op.radixB op.radixL row,
+ physicalBuffers_eq hD hd R.arguments node _ v z (by omega) space stored]
+ constructor
+ · intro node saved _
+ exact trace_bits D budget m f _ _
+ · intro node c top pending dom hc hn hs hend _ _ _
+ obtain ⟨v,z,eq,space,stored,cache,good,_⟩ := actual node c dom hc hn
+ let buf := LeafArguments.buffers hD hd v z
+ intro x hr
+ have hx : x = _ := eq
+ rw [hx] at hr ⊢
+ obtain ⟨q,qres,qr⟩ := good hr
+ have qframe (i : Fin 9) := qres.frame _ (LeafImage.dfs_preserved reg i) (LeafImage.dfs_ne_route reg i)
+ by_cases zero : v.1 = 0
+ · have zv : v = (0,v.2) := Prod.ext zero rfl
+ let root := v.2
+ obtain ⟨a',ha,ap,site,header,cp,bp,memA,pstA,regA⟩ :=
+ LeafBootHandoff.run M (pc ∘ LeafImage.Label.handoff) boot (LeafImage.leafReg reg) (pub ∘ LeafImage.Pub.arena)
+ (LeafImage.bootPC pc (.pre 0)) link.handoff (LeafImage.leaf_ne_boot reg .header _)
+ (LeafImage.dfs_not_written reg 7) R node.val (root.val : Word w) (D.initial root.val) q
+ (by change q.pc = pc (.handoff 0); exact qres.pc.trans (ite_eq_left zero))
+ (Fin.ext (qres.site.trans (Nat.mod_eq_of_lt (qres.site ▸ (q.reg (P.leaf .site)).isLt)).symm))
+ (Fin.ext qres.header) (by change q.reg (P.leaf .node) = (node.val : Word w); rw [qres.node, show c.reg (P.leaf .node) = node from hn]; simp)
+ op.cacheBase op.arenaStride op.arenaStart
+ have old : a'.privateMem = c.privateMem := memA.trans qres.memory
+ have hlen : (cursorPacket hD hd node.val v z).bits.length = 4*ramPayloadWidth (b+l) (2^e) w :=
+ LeafArguments.packed_length_four hD hd _ z
+ have before : R.arguments.base node.val + 4*ramPayloadWidth (b+l) (2^e) w ≤ R.stackBase := by
+ have h₁ := R.node_before dom.1
+ have h₂ := hlen ▸ space.2.1
+ unfold LeafArena.Regions.stackBase LeafArena.Regions.cacheBase; omega
+ have incident : LeafIncidentLoad.Stored
+ (LeafIncidentMachine.base (R.arguments.base node.val) (ramPayloadWidth (b+l) (2^e) w)) buf a'.privateMem := by
+ intro port j
+ have res := RoutePrepare.resident_cursorPacket hD hd R.arguments node v z c space stored port j
+ rw [old]
+ change c.privateMem (LeafFieldCopy.word w (_ + j.val)) = _
+ change c.privateMem (((LeafHandler.portBase R.arguments node.val _ port : ℕ) : Word w) + _) = _ at res
+ rw [← Nat.cast_add] at res
+ have eqBit (x : Bool) : (x.toNat : Word w) = PrivateFields.bitValue w x := by cases x <;> rfl
+ rw [eqBit] at res
+ cases port with | outgoing side | incoming side =>
+ cases side <;> simpa [LeafFieldCopy.word,LeafIncidentMachine.base,LeafHandler.portBase,LeafArguments.portNumber,buf] using res
+ obtain ⟨out,run,outpc,rep,pst,regs,_,pendingOk,scratchOk⟩ :=
+ LeafBoot.run D budget.tags budget.capFits root buf M (LeafImage.bootPC pc) boot (pub .size)
+ (LeafImage.stackPC pc auxiliaryEntry 0) link.boot R (R.arguments.base node.val) fit before a' ap
+ bp cp hsize site header (by rw [old,cache_eq]; exact cache) incident
+ (room (0,root) buf) pending hend (old ▸ hs) lo
+ have sf : scratch endAddr a'.privateMem = scratch endAddr c.privateMem := congrArg (scratch endAddr) old
+ have zz : auxiliaryBank D budget.tags budget.capFits v buf = auxiliaryBank D budget.tags budget.capFits (0,root) buf :=
+ congrArg (fun v => auxiliaryBank D budget.tags budget.capFits v buf) zv
+ refine ⟨out,?_,pst.trans (pstA.trans qres.persistent),fun i _ =>
+ (regs _ (LeafImage.dfs_offBoot reg i)).trans ((regA _ (LeafImage.dfs_not_written reg i)).trans (qframe i)),
+ pendingOk,?_,fun _ => ?_,?_⟩
+ · simpa only [zero,↓reduceIte] using outpc
+ · rw [ite_eq_left zero]
+ change scratch endAddr out.privateMem =
+ LeafLoadedBank.scratch L (auxiliaryBank D budget.tags budget.capFits v buf) (scratch endAddr c.privateMem)
+ rw [zz,←sf]
+ exact scratchOk
+ · change StackMachine.Represents L (LeafBoot.stack boot) out (auxiliaryBank D budget.tags budget.capFits v buf)
+ rw [zz]
+ exact rep
+ · intro fuel bits
+ let g := LeafFront.trace m f v e w
+ let t := LeafBoot.ticks D budget.tags budget.capFits root buf
+ have tail := ha.append run
+ change Prefix M q (List.replicate 7 .tick ++ List.replicate t .tick) out at tail
+ rw [← List.replicate_add] at tail
+ have htail := tail.execute fuel m bits
+ simp only [List.length_replicate,bits_ticks,List.nil_append] at htail
+ change execute M.program (fuel+(trace D budget m f v buf).length) c m bits = _
+ simp only [trace,zero,↓reduceIte,List.length_append,List.length_replicate]
+ rw [show fuel+((LeafFront.trace m f v e w).length+(7+t))=(fuel+(7+t))+g.length by dsimp [g]; omega,
+ qr,htail]
+ simp only [Option.map_map,Function.comp_def,List.append_assoc]; rfl
+ · refine ⟨q,?_,qres.persistent,fun i _ => qframe i,qres.memory ▸ hs,?_,fun hz => (zero hz).elim,?_⟩
+ · simpa only [zero,↓reduceIte,P,LeafImage.front] using qres.pc
+ · simp only [zero,↓reduceIte,qres.memory]
+ · intro fuel bits
+ simpa only [trace,zero,↓reduceIte,List.append_nil] using qr fuel bits
+ · intro node c top pending dom hc hn _ _ _ _ _ hr
+ obtain ⟨v,z,eq,_,_,_,_,reject⟩ := actual node c dom hc hn
+ rw [eq] at hr
+ exact reject (Bool.eq_false_iff.mpr hr)
+
+end PairSimulation.LeafVisit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafImageWork.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafImageWork.lean
new file mode 100644
index 0000000000..34954896b6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafImageWork.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.PairSimulationLeafImageHandler
+
+/-! # Per-leaf instruction and probe bounds at the actual auxiliary cutoff -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open BurstRAM RAMTape
+
+variable {K Q : Type} [DecidableEq K] {w : ℕ}
+
+/-- A missing choice, failed halt, or expired source clock also respects
+the same native transition bound. -/
+theorem footprint_length_le (L : Layout K w) (code : StackCode K Q) (fuel : ℕ)
+ (q : Q) (s : Stacks K) (bits : List Bool) :
+ (footprint L code fuel q s bits).events.length ≤ 4*fuel := by
+ induction fuel generalizing q s bits with
+ | zero => rfl
+ | succ fuel ih =>
+ cases h : code q with
+ | push | pop | goto =>
+ simp only [footprint,h,Footprint.prepend,List.length_append,List.length_replicate,Nat.mul_succ]
+ exact Nat.add_le_add_left (ih ..) _ |>.trans_eq (Nat.add_comm ..)
+ | choose lo hi =>
+ cases bits with
+ | nil => simp only [footprint,h,List.length_replicate,Nat.mul_succ]; omega
+ | cons b bs =>
+ simp only [footprint,h,Footprint.prepend,List.length_append,List.length_cons,List.length_nil,Nat.mul_succ]
+ have := ih (if b then hi else lo) s bs; omega
+ | halt b => cases b <;> simp [footprint,h,Nat.mul_succ]
+
+end PairSimulation.StackMachine
+
+namespace PairSimulation.LeafVisit
+
+open BurstRAM PrivateRAM CursorNetwork CursorRouting LeafHandler LeafStartup DFS Filter
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ} {A : PrimedInputRAM.Lengths} {n a H s : ℕ}
+ {Q : PrimedInputRAM.Layout A n a H w} (D : PrimedCounter.Data Q s)
+ {b l e endAddr : ℕ} [NeZero (b+l)] (budget : ProcessorBudget n (b+l) e w)
+ (R : LeafArena.Regions) (fit : R.stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ {M : Machine w p r k} (pub : LeafImage.Pub → Fin k) (m : Memory w)
+
+private theorem tick_probes (n : ℕ) : countProbes (List.replicate n (.tick : Event w)) = 0 := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [List.replicate_succ,countProbes,ih]
+
+theorem trace_probes (f : LeafAddress.Field → Word w) (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) :
+ countProbes (trace D budget m f v buf) ≤ 1 := by
+ rw [trace,countProbes_append,LeafFront.trace_probes]
+ by_cases hz : v.1=0
+ · rw [ite_eq_left hz,tick_probes]
+ cases decide ((v.2.val : Word w) < f .span) <;> decide
+ · rw [ite_eq_right hz,show countProbes ([] : List (Event w)) = 0 from rfl]
+ cases decide ((v.2.val : Word w) < f .span) <;> decide
+
+theorem trace_length (f : LeafAddress.Field → Word w) (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w)
+ (hn : 2048 ≤ n) (cost : LeafBoot.ticks D budget.tags budget.capFits v.2 buf ≤ n^15) :
+ (trace D budget m f v buf).length ≤ n^16 := by
+ have hroute := (RouteSchedule.routeTicks_le w v (2^e) w).trans (RouteSchedule.clock_le budget hn)
+ have h₁ : 1 ≤ n := by omega
+ have h₅ := Nat.pow_le_pow_right h₁ (by decide : 5 ≤ 15)
+ have hbig : 60*n^15 ≤ n^16 := by rw [pow_succ' n 15]; exact Nat.mul_le_mul_right _ (by omega)
+ have := Nat.one_le_pow 15 n h₁
+ rw [trace,List.length_append,(LeafFront.trace_cost ..).1]
+ simp only [RoutePrepare.ticks]
+ split <;> simp only [List.length_replicate,List.length_nil] <;> omega
+
+/-- Room for the native role dispatch and its operand reload is included in
+the private-work estimate. Only the translated virtual header may probe
+external memory inside this leaf. -/
+theorem parser_work (hn : 2048 ≤ n)
+ (boot : ∀ (v : Site (b+l)) (buf : Buffers (b+l) (2^e) w),
+ LeafBoot.ticks D budget.tags budget.capFits v buf ≤ n^15)
+ (node : Word w) (saved : Scratch w endAddr) (bits : List Bool) {job : VisitPath w endAddr} {tail : List Bool}
+ (read : (leafParser (M := M) D budget R fit pub m (n^39)).read node saved bits = some (job,tail)) :
+ countProbes job.trace ≤ 1 ∧ job.trace.length + 47 ≤ n^40 := by
+ let f := fields (M := M) pub
+ let v := physicalPosition (b+l) f node
+ let buf := physicalBuffers (b+l) (2^e) w R.arguments node saved
+ obtain ⟨probes,cost⟩ := LeafHandler.parser_work D budget.tags budget.capFits (storage R fit)
+ (loaded D budget R fit f m) (n^39) node saved bits read
+ refine ⟨probes.trans_le (trace_probes D budget m f v buf),?_⟩
+ have t := trace_length D budget m f v buf hn (boot v.2 buf)
+ change job.trace.length ≤ (trace D budget m f v buf).length+4*n^39 at cost
+ have h₁ : 1 ≤ n := by omega
+ have h₁₆ := Nat.pow_le_pow_right h₁ (by decide : 16 ≤ 39)
+ have := Nat.one_le_pow 39 n h₁
+ have cap : 52*n^39 ≤ n^40 := by rw [pow_succ' n 39]; exact Nat.mul_le_mul_right _ (by omega)
+ omega
+
+/-- Include the complete compiled prefix and interpreter's event counts
+even when the stack computation rejects or its input tape ends early. -/
+theorem malformed_work (hn : 2048 ≤ n) (f : LeafAddress.Field → Word w)
+ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) (bits : List Bool)
+ (boot : LeafBoot.ticks D budget.tags budget.capFits v.2 buf ≤ n^15) :
+ let head := trace D budget m f v buf
+ let body := StackMachine.footprint (storage R fit) auxiliaryCode (n^39) auxiliaryEntry
+ (auxiliaryBank D budget.tags budget.capFits v buf) bits
+ countProbes (head ++ body.events) ≤ 1 ∧ (head ++ body.events).length + 47 ≤ n^40 := by
+ intro head body
+ rw [countProbes_append,StackMachine.footprint_probes,Nat.add_zero,List.length_append]
+ refine ⟨trace_probes D budget m f v buf,?_⟩
+ have ht : head.length ≤ n^16 := trace_length D budget m f v buf hn boot
+ have hb : body.events.length ≤ 4*n^39 := StackMachine.footprint_length_le ..
+ have h₁ : 1 ≤ n := by omega
+ have h₁₆ := Nat.pow_le_pow_right h₁ (by decide : 16 ≤ 39)
+ have := Nat.one_le_pow 39 n h₁
+ have cap : 52*n^39 ≤ n^40 := by rw [pow_succ' n 39]; exact Nat.mul_le_mul_right _ (by omega)
+ omega
+
+end PairSimulation.LeafVisit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafImageWrites.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafImageWrites.lean
new file mode 100644
index 0000000000..12b84463bc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafImageWrites.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PairSimulationLeafImage
+import OAI.Computability.VPVNP.PairSimulationRouteBankWrites
+import OAI.Computability.VPVNP.PairSimulationLeafBootWrites
+
+/-!
+# Register writes of the native cursor leaf
+
+The destination of every writing instruction belongs to the leaf's allocated
+registers. An enclosing machine may keep its virtual public operands in any
+disjoint bank, including during external reads and on rejected paths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafImage
+
+open BurstRAM PrivateRAM RegisterOperands RAMTape LeafStartup
+
+variable {w p r k : ℕ}
+
+private theorem of_some {α : Type*} (reg : α ↪ Fin r) {j : α} {a : Fin r}
+ (h : some (reg j) = some a) : a ∈ Set.range reg :=
+ ⟨j, Option.some.inj h⟩
+
+private theorem address_mem (pc : Fin 20 → Fin p) (reg : LeafAddress.Reg ↪ Fin r)
+ (pub : LeafAddress.Field → Fin k) (launch transit : Fin p) (i : Fin 20) (a : Fin r)
+ (h : destination (LeafAddress.instruction (w := w) pc reg pub launch transit i) = some a) :
+ a ∈ Set.range reg := by
+ fin_cases i <;> first | exact of_some reg h | contradiction
+
+private theorem prepare_mem (pc : RoutePrepare.Stage → Fin p) (reg : Fin 32 ↪ Fin r)
+ (leaf : LeafAddress.Reg ↪ Fin r) (pub : RoutePrepare.Field → Fin k) (done : Fin p)
+ (i : RoutePrepare.Stage) (a : Fin r)
+ (h : destination (RoutePrepare.instruction (W := w) pc reg leaf pub done i) = some a) :
+ a ∈ Set.range reg := by
+ cases i with
+ | inl i | inr i => fin_cases i <;> exact of_some reg h
+
+private theorem handoff_mem (pc : Fin 7 → Fin p) (boot : LeafBoot.Reg ↪ Fin r)
+ (leaf : LeafAddress.Reg ↪ Fin r) (pub : RoutePrepare.Field → Fin k) (done : Fin p)
+ (i : Fin 7) (a : Fin r)
+ (h : destination (LeafBootHandoff.instruction (w := w) pc boot leaf pub done i) = some a) :
+ a ∈ Set.range boot := by
+ fin_cases i <;> exact of_some boot h
+
+private theorem stack_mem {K Q : Type} (code : StackCode K Q) (pc : Q → Fin 7 → Fin p)
+ (reg : StackMachine.Register K ↪ Fin r) (done : Fin p) (q : Q) (i : Fin 7) (a : Fin r)
+ (h : destination (StackMachine.instruction (w := w) (k := k) code pc reg done q i) = some a) :
+ a ∈ Set.range reg := by
+ cases op : code q with
+ | push _ _ _ | pop _ _ | goto _ | choose _ _ =>
+ fin_cases i <;> simp [StackMachine.instruction, op, destination] at h <;> exact ⟨_,h⟩
+ | halt b =>
+ cases b <;> fin_cases i <;> simp [StackMachine.instruction, op, destination] at h
+ exact ⟨_,h⟩
+
+/-- Every register written by the composite leaf belongs to its physical register
+embedding. This statement covers every opcode, independent of reachability. -/
+theorem destination_mem (pc : Label → Fin p) (reg : Reg ↪ Fin r) (pub : Pub → Fin k)
+ (ret : Fin p) (j : Label) (a : Fin r)
+ (h : destination (instruction pc reg pub ret j) = some a) : a ∈ Set.range reg := by
+ cases j with
+ | address i =>
+ obtain ⟨t,ht⟩ := address_mem _ (leafReg reg) _ _ _ i a h
+ exact ⟨_,ht⟩
+ | prepare i =>
+ obtain ⟨t,ht⟩ := prepare_mem _ (routeReg reg) (leafReg reg) _ _ i a h
+ exact ⟨.route t,ht⟩
+ | route j =>
+ cases j with
+ | inl j =>
+ simp only [instruction,destination_resize] at h
+ obtain ⟨t,ht⟩ := RouteBank.destination_mem _ (routeReg reg) (.inl j) a h
+ exact ⟨.route t,ht⟩
+ | inr j => fin_cases j <;> contradiction
+ | handoff i =>
+ obtain ⟨t,ht⟩ := handoff_mem _ (bootReg reg) (leafReg reg) _ _ i a h
+ exact ⟨.boot t,ht⟩
+ | boot i =>
+ obtain ⟨t,ht⟩ := LeafBoot.destination_mem _ (bootReg reg) _ _ i a h
+ exact ⟨.boot t,ht⟩
+ | stack q i =>
+ obtain ⟨t,ht⟩ := stack_mem auxiliaryCode _ (LeafBoot.stack (bootReg reg)) _ q i a h
+ exact ⟨_,ht⟩
+
+end PairSimulation.LeafImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentArena.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentArena.lean
new file mode 100644
index 0000000000..43b0632b9f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentArena.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentTable
+import OAI.Computability.VPVNP.PairSimulationLeafPhysicalInput
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentScratch
+import OAI.Computability.VPVNP.PairSimulationLeafArena
+
+/-!
+# Supplying the four private half-wire buffers of a DFS node
+
+The parent stores one packed array at the interval indexed by the
+descriptor address. The loader reads its four occupied arc slots in
+their numerical order. Initializing other stack ports preserves these
+cells when the node arena and stack arena are disjoint.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentArena
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork RAMLayout
+open LeafIncidentLoad (Stored)
+open LeafFieldCopy (word)
+open scoped Fin.CommRing
+
+variable {W D H w p r k : ℕ}
+
+/-- The four source addresses inside the selected node's private argument packet. -/
+def sourceBase (A : NodeArguments.Arena) (node : ℕ) (D H w : ℕ) :=
+ LeafIncidentMachine.base (A.base node) (ramPayloadWidth D H w)
+
+theorem sourceBase_eq (A : NodeArguments.Arena) (node D H w : ℕ) :
+ sourceBase A node D H w = LeafHandler.portBase A node (ramPayloadWidth D H w) := by
+ funext p
+ cases p with | outgoing s | incoming s => cases s <;>
+ simp [sourceBase,LeafIncidentMachine.base,LeafHandler.portBase,LeafArguments.portNumber]
+
+/-- Scalar stack initialization leaves every independent half-wire bit
+available at its original node-arena address. -/
+theorem stored_after_scalars {K : Type} (L : StackMachine.Layout K W) (s : RAMTape.Stacks K)
+ (A : NodeArguments.Arena) (node : ℕ) (buf : Buffers D H w) (old : Word W → Word W)
+ (stored : Stored (sourceBase A node D H w) buf old)
+ (fit : A.base node+4*ramPayloadWidth D H w ≤ 2^W)
+ (apart : ∀ j, L.base j+(s j).length ≤ A.base node ∨ A.base node+4*ramPayloadWidth D H w ≤ L.base j) :
+ Stored (sourceBase A node D H w) buf (LeafLoadedBank.memory L s old) := by
+ intro port i
+ have h : A.base node ≤ sourceBase A node D H w port ∧
+ sourceBase A node D H w port+ramPayloadWidth D H w ≤ A.base node+4*ramPayloadWidth D H w := by
+ cases port with
+ | outgoing side | incoming side => cases side <;> simp only [sourceBase,LeafIncidentMachine.base] <;> omega
+ rw [LeafIncidentBank.memory_outside]
+ · exact stored port i
+ · intro j
+ have hi := i.isLt
+ have hsep := apart j
+ change (_ % 2^W) < _ ∨ _ ≤ (_ % 2^W)
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+
+/-- A stored packet read from DFS scratch remains valid in the represented
+scalar bank that immediately precedes the incident copy. -/
+theorem stored_leaf {K : Type} {b l a z endAddr : ℕ} [NeZero (b+l)] (hd : 1 < b+l) (hz : 2+z = 2^a)
+ (A : NodeArguments.Arena) (node : Word W) (v : Position (b+l))
+ (halves : (LeafArguments.state hd hz H w).network.Half
+ (lanePositions (cursorCoordinateLabels b l) v))
+ (L : StackMachine.Layout K W) (s : RAMTape.Stacks K) (old : Word W → Word W)
+ (fits : (LeafHandler.cursorPacket hd hz node.val v halves).Fits A W endAddr)
+ (stored : (LeafHandler.cursorPacket hd hz node.val v halves).Stored A (DFS.scratch endAddr old))
+ (apart : ∀ j, L.base j+(s j).length ≤ A.base node.val ∨
+ A.base node.val+4*ramPayloadWidth (b+l) H w ≤ L.base j) :
+ Stored (sourceBase A node.val (b+l) H w) (LeafArguments.buffers hd hz v halves) (LeafLoadedBank.memory L s old) := by
+ have len := LeafArguments.packed_length_four hd hz _ halves
+ have fit : A.base node.val+4*ramPayloadWidth (b+l) H w ≤ 2^W := len ▸ fits.2.2
+ apply stored_after_scalars _ _ _ _ _ _ _ fit apart
+ have h := LeafHandler.physicalStored hd hz A node (DFS.scratch endAddr old) v halves fits stored
+ rw [← sourceBase_eq] at h
+ intro port i
+ have hh := h port i
+ have bound : A.base node.val ≤ sourceBase A node.val (b+l) H w port ∧
+ sourceBase A node.val (b+l) H w port+ramPayloadWidth (b+l) H w ≤ A.base node.val+4*ramPayloadWidth (b+l) H w := by
+ cases port with | outgoing side | incoming side => cases side <;> simp only [sourceBase,LeafIncidentMachine.base] <;> omega
+ have above : endAddr ≤ A.base node.val := fits.1
+ have hi := i.isLt
+ have ha : endAddr ≤ (word W (sourceBase A node.val (b+l) H w port+i.val)).val := by
+ change _ ≤ _ % _
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+ simpa only [NodeArguments.rawScratch,ha,↓reduceDIte,DFS.scratch] using hh
+
+/-- In the physical regions of a leaf the whole argument packet precedes
+every stack, so its bits survive scalar initialization without a per-port
+separation hypothesis. -/
+theorem stored_leaf_regions {K : Type} {b l a z endAddr ports : ℕ} [NeZero (b+l)]
+ (hd : 1 < b+l) (hz : 2+z = 2^a) (R : LeafArena.Regions) (node : Word W)
+ (v : Position (b+l)) (halves : (LeafArguments.state hd hz H w).network.Half
+ (lanePositions (cursorCoordinateLabels b l) v))
+ (order : K ↪ Fin ports) (capacity : ℕ) (room : R.stackBase + ports*capacity < 2^W)
+ (s : RAMTape.Stacks K) (old : Word W → Word W) (active : node.val < R.nodes)
+ (fits : (LeafHandler.cursorPacket hd hz node.val v halves).Fits R.arguments W endAddr)
+ (stored : (LeafHandler.cursorPacket hd hz node.val v halves).Stored R.arguments (DFS.scratch endAddr old)) :
+ Stored (sourceBase R.arguments node.val (b+l) H w) (LeafArguments.buffers hd hz v halves)
+ (LeafLoadedBank.memory (R.layout order capacity room) s old) := by
+ apply stored_leaf hd hz R.arguments node v halves _ s old fits stored
+ intro j
+ apply Or.inr
+ have size : 4*ramPayloadWidth (b+l) H w ≤ R.arguments.stride :=
+ (LeafArguments.packed_length_four hd hz _ halves) ▸ fits.2.1
+ have before := R.node_before active
+ have after := R.stack_above order capacity room j
+ have interval : R.histBase ≤ R.stackBase := by
+ unfold LeafArena.Regions.stackBase LeafArena.Regions.cacheBase
+ omega
+ omega
+
+end PairSimulation.LeafIncidentArena
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentBank.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentBank.lean
new file mode 100644
index 0000000000..c6376440f2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentBank.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentScratch
+import OAI.Computability.VPVNP.PairSimulationLeafFieldCopy
+
+/-!
+# Representing the full stack bank after loading the incident bits
+
+The descending native copy stores the head of the logical list at its highest
+address. Updating the incident stack's exclusive top therefore installs the
+list with exactly the stack representation used by the interpreter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentBank
+
+open BurstRAM PrivateRAM RAMTape StackMachine PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {K : Type} [DecidableEq K] {W p r : ℕ}
+
+private theorem place_read (lo : ℕ) (xs : List Bool) (old : Word W → Word W)
+ (fit : lo+xs.length ≤ 2^W) (i : Fin xs.reverse.length) :
+ LeafFieldCopy.place lo xs old (LeafFieldCopy.word W (lo+i.val)) = encodeBit W xs.reverse[i.val] := by
+ have hi : i.val < xs.length := by simpa using i.isLt
+ let j := xs.length-1-i.val
+ have hj : j < xs.length := by dsimp [j]; omega
+ let tail := xs.drop (j+1)
+ have hx : xs = xs.take j ++ xs[j] :: tail := by
+ rw [show xs[j] :: tail = xs.drop j from List.getElem_cons_drop hj, List.take_append_drop]
+ have hlen : tail.length = i.val := by simp only [tail,List.length_drop,j]; omega
+ have atBit := LeafFieldCopy.place_at lo (xs.take j) xs[j] tail old (by rwa [← hx])
+ rw [← hx, hlen] at atBit
+ simpa only [List.getElem_reverse, j, PrivateFields.bitValue, encodeBit] using atBit
+
+/-- Install one physical field in its own disjoint stack interval. -/
+theorem placed_contents (L : Layout K W) (a : K) (s : Stacks K) (xs : List Bool)
+ (old : Word W → Word W) (rep : L.Contents old s)
+ (fit : ∀ j, (s j).length ≤ L.capacity) (room : xs.length ≤ L.capacity) :
+ L.Contents (LeafFieldCopy.place (L.base a) xs old) (Function.update s a xs) := by
+ have bound := ((Nat.add_le_add_left room _).trans_lt (L.fits a)).le
+ apply LeafFill.contents_install L a s xs old _ rep fit
+ · intro i
+ exact place_read _ xs old bound i
+ · intro u hu
+ exact LeafFieldCopy.place_outside _ xs old u bound (hu.imp_right ((Nat.add_le_add_left room _).trans ·))
+
+/-- Only the incident top pointer needs a new value. Scratch register
+contents may change freely; the other base and top pointers keep their values. -/
+theorem represents (L : Layout K W) (reg : Register K ↪ Fin r) (a : K) (s : Stacks K)
+ (xs : List Bool) (c out : Config W p r) (rep : Represents L reg c s)
+ (fit : ∀ j, (s j).length ≤ L.capacity) (room : xs.length ≤ L.capacity)
+ (mem : out.privateMem = LeafFieldCopy.place (L.base a) xs c.privateMem)
+ (top : out.reg (reg (.top a)) = L.address a xs.length)
+ (regs : ∀ j : Register K, j ≠ .tmp → j ≠ .top a → out.reg (reg j) = c.reg (reg j)) :
+ Represents L reg out (Function.update s a xs) := by
+ refine ⟨(regs .one nofun nofun).trans rep.unit, (regs .zero nofun nofun).trans rep.zero,
+ fun j => (regs (.base j) nofun nofun).trans (rep.bases j), ?_, ?_⟩
+ · intro j
+ by_cases h : j = a
+ · subst j; simpa using top
+ · simpa [Function.update_of_ne h] using (regs (.top j) nofun (by simpa using h)).trans (rep.tops j)
+ · rw [mem]
+ exact placed_contents L a s xs _ rep.cells fit room
+
+/-- The exact private memory is determined by the old workspace and the
+full bank. Outside both the scalar data and the new incident bits, stale
+private cells keep their previous values. -/
+theorem placed_memory (L : Layout K W) (a : K) (s : Stacks K) (xs : List Bool)
+ (old scalar : Word W → Word W) (rep : L.Contents scalar s)
+ (fit : ∀ j, (s j).length ≤ L.capacity) (room : xs.length ≤ L.capacity)
+ (blank : s a = []) (hs : scalar = LeafLoadedBank.memory L s old) :
+ LeafFieldCopy.place (L.base a) xs scalar = LeafLoadedBank.memory L (Function.update s a xs) old := by
+ apply LeafLoadedBank.memory_eq L _ old _ (placed_contents L a s xs scalar rep fit room)
+ · intro j
+ by_cases hj : j = a <;> simp [hj,room,fit]
+ · intro u outside
+ have h := outside a
+ rw [Function.update_self] at h
+ rw [LeafFieldCopy.place_outside _ _ _ _ ((Nat.add_le_add_left room _).trans (L.fits a).le) h, hs]
+ apply memory_outside
+ intro j
+ by_cases hj : j = a
+ · subst j; rw [blank]; simp; omega
+ · simpa [Function.update_of_ne hj] using outside j
+
+variable {d e w k regs : ℕ}
+
+set_option synthInstance.maxSize 10000 in
+/-- Specialize the physical installation to the actual site-port layout.
+The incident vector is precisely the field omitted by the scalar startup. -/
+theorem fullBank (L : Layout (LeafStartup.Port regs k) W) (reg : Register (LeafStartup.Port regs k) ↪ Fin r)
+ (x : VirtualSite.Input d e w) (args : Fin k → Word w) (c out : Config W p r)
+ (rep : Represents L reg c (LeafRegisterBank.scalarBank LeafStartup.field x args))
+ (fit : ∀ j, (LeafRegisterBank.scalarBank (LeafStartup.field (r := regs)) x args j).length ≤ L.capacity)
+ (room : RAMLayout.width d (2^e) w ≤ L.capacity)
+ (mem : out.privateMem = LeafFieldCopy.place (L.base (LeafLoadedBank.incidentPort regs k))
+ (List.ofFn (RAMLayout.incidentBits x.sends x.v)) c.privateMem)
+ (top : out.reg (reg (.top (LeafLoadedBank.incidentPort regs k))) =
+ L.address (LeafLoadedBank.incidentPort regs k) (RAMLayout.width d (2^e) w))
+ (regsEq : ∀ j : Register (LeafStartup.Port regs k), j ≠ .tmp → j ≠ .top (LeafLoadedBank.incidentPort regs k) →
+ out.reg (reg j) = c.reg (reg j))
+ (old : Word W → Word W)
+ (hs : c.privateMem = LeafLoadedBank.memory L (LeafRegisterBank.scalarBank LeafStartup.field x args) old) :
+ Represents L reg out (LeafStartup.bank regs x args) ∧
+ out.privateMem = LeafLoadedBank.memory L (LeafStartup.bank regs x args) old := by
+ let a := LeafLoadedBank.incidentPort regs k
+ let s := LeafRegisterBank.scalarBank (LeafStartup.field (r := regs)) x args
+ let xs := List.ofFn (RAMLayout.incidentBits x.sends x.v)
+ have hroom : xs.length ≤ L.capacity := by simpa [xs] using room
+ have htop : out.reg (reg (.top a)) = L.address a xs.length := by simpa only [a,xs,List.length_ofFn] using top
+ have hb : s a = [] := by
+ have he := (LeafLoadedBank.field_incident_iff (r := regs) (k := k) a).2 rfl
+ simp [s, LeafRegisterBank.scalarBank, he, LeafRegisterBank.scalarField, LeafStartup.fieldBits]
+ rw [← LeafLoadedBank.install_incident x args]
+ exact ⟨represents L reg a s xs c out rep fit hroom mem htop regsEq,
+ mem.trans (placed_memory L a s xs old c.privateMem rep.cells fit hroom hb hs)⟩
+
+end PairSimulation.LeafIncidentBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentCore.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentCore.lean
new file mode 100644
index 0000000000..33fd83135f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentCore.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSuccessorFields
+import OAI.Computability.VPVNP.PairSimulationLeafSuccessorBits
+import OAI.Computability.VPVNP.PairSimulationLeafSortStream
+
+/-!
+# The full native incident decoder for a cursor-zero leaf
+
+The two chain fields are loaded first. Two arithmetic rows switch the
+source offset and field width to the sorting layout, followed by the
+triangular layer scan. All three subgraphs share a descending destination
+cursor, so the resulting stack has the logical order of the virtual RAM
+validator even when the supplied halves disagree.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentCore
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork RAMLayout PrimedCounter.GuessWord
+open LeafFieldCopy (word)
+open scoped Fin.CommRing
+
+variable {W D H w p r k : ℕ}
+
+/-- Successor-field stages, setup instructions and sorting-field stages. -/
+abbrev Stage := LeafSuccessorFields.Stage ⊕ (Fin 2 ⊕ LeafSortFields.Stage)
+
+/-- Embed the successor loader in the thirty-register incident machine. -/
+def successorRegs (reg : Fin 30 ↪ Fin r) : Fin 20 ↪ Fin r := (Fin.castAddEmb 10).trans reg
+
+/-- Sorting counters reuse the three successor-class temporaries. -/
+def sortMap : Fin 17 ↪ Fin 30 := ⟨![0,1,2,3,4,5,6,7,8,9,10,11,12,17,18,19,16], by decide⟩
+/-- Embed the sorting loader in the thirty-register incident machine. -/
+def sortRegs (reg : Fin 30 ↪ Fin r) := sortMap.trans reg
+
+/-- The row that loads the indicated successor or sorting field. -/
+def instruction (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) : Stage → Instr W p r k
+ | .inl s => LeafSuccessorFields.instruction (pc ∘ Sum.inl) (successorRegs reg) (pc (.inr (.inl 0))) s
+ | .inr (.inl i) =>
+ (![.binary .mul (reg 6) (reg 11) (reg 5) (pc (.inr (.inl 1))),
+ .copy (reg 5) (reg 25) (pc (.inr (.inr .resetPhase)))] : Fin 2 → Instr W p r k) i
+ | .inr (.inr s) => LeafSortFields.instruction (pc ∘ Sum.inr ∘ Sum.inr) (sortRegs reg) done s
+
+theorem resize_instruction (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) (s : Stage) :
+ (instruction (W := 1) (k := k) pc reg done s).resize W = instruction pc reg done s := by
+ rcases s with s | i | s
+ · exact LeafSuccessorFields.resize_instruction ..
+ · fin_cases i <;> rfl
+ · exact LeafSortFields.resize_instruction ..
+
+/-- The incident core's relocatable instruction rows occur in the host table. -/
+def Linked (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) :=
+ ∀ s, M.code (pc s) = instruction pc reg done s
+
+/-- Registers that the incident core may write. -/
+def changed : List (Fin 30) := [0,1,2,4,5,6,17,18,19]
+/-- Equality of every register outside the core's write footprint. -/
+def Frame (reg : Fin 30 ↪ Fin r) (c out : Config W p r) :=
+ ∀ i, (∀ j ∈ changed, i ≠ reg j) → out.reg i = c.reg i
+
+private theorem successor_change : ∀ j ∈ LeafSuccessorFields.changed, Fin.castAdd 10 j ∈ changed := by decide
+private theorem sort_change : ∀ j ∈ LeafSortFields.changed, sortMap j ∈ changed := by decide
+
+/-- Instruction count for the successor and sorting field loads at this site. -/
+def ticks (v : Site D) (H w : ℕ) :=
+ LeafSuccessorFields.ticks v w+2+(3+LeafSortFields.streamTicks D H w 0 (layerCount D) (by simp))
+
+variable [NeZero D]
+
+theorem stream_eq (v : Site D) (buf : Buffers D H w) :
+ (LeafSuccessorFields.succBits false v buf ++ LeafSuccessorFields.succBits true v buf) ++
+ LeafSortFields.stream buf 0 (layerCount D) (by simp) = List.ofFn (incidentBuffer (0,v) buf) := by
+ rw [LeafSuccessorFields.succBits_eq,LeafSuccessorFields.succBits_eq,
+ LeafSortFields.stream_eq_fields, ← RAMTape.SortSchedule.exchangeNumbers 0 D]
+ exact (RAMTape.SortSchedule.incident_stream 0 (incidentBuffer (0,v) buf)).symm
+
+/-- The materialized incident stack and exact physical continuation of the core. -/
+structure Result (reg : Fin 30 ↪ Fin r) (done : Fin p) (lo : ℕ) (v : Site D) (buf : Buffers D H w)
+ (c out : Config W p r) : Prop where
+ pc : out.pc = done
+ cursor : out.reg (reg 2) = word W lo
+ frame : Frame reg c out
+ memory : out.privateMem = LeafFieldCopy.place lo (List.ofFn (incidentBuffer (0,v) buf)) c.privateMem
+ persistent : out.persistent = c.persistent
+
+theorem run (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p)
+ (hl : Linked M pc reg done) (base : LocalPort → ℕ) (buf : Buffers D H w)
+ (v : Site D) (lo : ℕ) (c : Config W p r) (hc : c.pc = pc (.inl .sendNext))
+ (hf : LeafSuccessorFields.Fixed (successorRegs reg) base v w c)
+ (hblock : c.reg (reg 25) = word W (blockBits H w)) (hDW : D < W)
+ (hd : c.reg (reg 2) = word W (lo+width D H w)) (stored : LeafIncidentLoad.Stored base buf c.privateMem)
+ (fit : lo+width D H w < 2^W) (sourceFit : ∀ a, base a+ramPayloadWidth D H w ≤ 2^W)
+ (apart : ∀ a, base a+ramPayloadWidth D H w ≤ lo ∨ lo+width D H w ≤ base a) :
+ (ticks v H w ≤ 80*w+6*D+29+layerCount D*(10*blockBits H w+14)) ∧
+ ∃ out, Prefix M c (List.replicate (ticks v H w) .tick) out ∧ Result reg done lo v buf c out := by
+ let lower := lo+layerCount D*(2*blockBits H w)
+ have split : lower+16*w = lo+width D H w := by dsimp [lower,width]; ring
+ have lower_le : lo ≤ lower := Nat.le_add_right ..
+ obtain ⟨a,first,ra⟩ := LeafSuccessorFields.pair_run (fun s => hl (.inl s)) base buf v lower c hc hf hDW
+ (split ▸ hd) stored (split ▸ fit) sourceFit (fun x => by have := apart x; omega)
+ have fa := hf.of_frame ra.frame
+ have keepA (i : Fin r) (hi : ∀ j ∈ changed, i ≠ reg j) : a.reg i = c.reg i :=
+ ra.frame i (fun j hj => hi _ (successor_change j hj))
+ have ba : a.reg (reg 25) = word W (blockBits H w) := (keepA _ (by
+ intro j hj; apply reg.injective.ne; intro eq; exact (show (25 : Fin 30) ∉ changed by decide) (eq ▸ hj))).trans hblock
+ let b := a.put (pc (.inr (.inl 1))) (reg 6) (word W (D*(8*w)))
+ let d := b.put (pc (.inr (.inr .resetPhase))) (reg 5) (word W (blockBits H w))
+ have s₀ : M.program.step a = .localStep b := by
+ change (M.code a.pc).run M.publicData a = _
+ rw [ra.pc,hl (.inr (.inl 0))]
+ have dim : a.reg (reg 11) = word W D := fa.dims
+ have len : a.reg (reg 5) = word W (8*w) := fa.len
+ simp [instruction,Instr.run,BinaryOp.eval,b,dim,len,word]
+ have s₁ : M.program.step b = .localStep d := by
+ change (M.code (pc (.inr (.inl 1)))).run M.publicData b = _
+ rw [hl (.inr (.inl 1))]
+ simp [instruction,Instr.run,d,b,Config.put,ba]
+ have middle : Prefix M a (List.replicate 2 .tick) d := .tick s₀ (.tick s₁ (.nil _))
+ have keepD (i : Fin 30) (h5 : i ≠ 5) (h6 : i ≠ 6) : d.reg (reg i) = a.reg (reg i) := by
+ simp [d,b,Config.put,Function.update_of_ne (reg.injective.ne h5),Function.update_of_ne (reg.injective.ne h6)]
+ have fixed : LeafSortFields.Fixed (sortRegs reg) base D H w d := by
+ refine ⟨(keepD 3 (by decide) (by decide)).trans fa.one, Config.put_same .., ?_,
+ (keepD 11 (by decide) (by decide)).trans fa.dims, (keepD 12 (by decide) (by decide)).trans fa.last,
+ (keepD 16 (by decide) (by decide)).trans fa.zero⟩
+ intro x
+ have hx := fa.bases x
+ cases x with
+ | outgoing s | incoming s => cases s <;> exact (keepD _ (by decide) (by decide)).trans hx
+ have stored' : LeafIncidentLoad.Stored base buf d.privateMem := by
+ change LeafIncidentLoad.Stored base buf a.privateMem
+ rw [ra.memory]
+ apply LeafSortFields.stored_place _ _ _ _ _ stored _ sourceFit
+ · intro x; have := apart x; simp only [List.length_append,LeafSuccessorFields.length_succBits]; omega
+ · simp only [List.length_append,LeafSuccessorFields.length_succBits]; omega
+ obtain ⟨n,hn,out,last,hpc,hcur,frame,hm,hper,nticks⟩ := LeafSortFields.sort_run
+ (fun s => hl (.inr (.inr s))) base buf lo d rfl fixed (Nat.pos_of_ne_zero (NeZero.ne D))
+ (hDW.trans Nat.lt_two_pow_self) (by change d.reg (reg 6) = _; simp [d,b,Config.put])
+ ((keepD 2 (by decide) (by decide)).trans ra.cursor) stored' (by omega) sourceFit
+ (fun x => by have := apart x; omega)
+ have clock := LeafSuccessorFields.ticks_le v w
+ refine ⟨by dsimp [ticks]; omega,out, ?_,hpc,hcur, ?_, ?_,hper.trans ra.persistent⟩
+ · simpa only [ticks,← nticks,List.replicate_add,List.append_assoc] using first.append (middle.append last)
+ · intro i hi
+ rw [frame i (fun j hj => hi _ (sort_change j hj))]
+ simp [d,b,Config.put,Function.update_of_ne (hi 5 (by decide)),Function.update_of_ne (hi 6 (by decide)),keepA i hi]
+ · rw [hm]
+ change LeafFieldCopy.place lo _ a.privateMem = _
+ rw [ra.memory]
+ conv_rhs => rw [← stream_eq v buf, LeafIncidentLoad.place_append,LeafSortFields.stream_length]
+
+end PairSimulation.LeafIncidentCore
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentFootprint.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentFootprint.lean
new file mode 100644
index 0000000000..34dd59d387
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentFootprint.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentMachine
+import OAI.Computability.VPVNP.PrivateRAMRegisterOperands
+
+/-! # Register destinations of the cursor-zero incident loader -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentMachine
+
+open BurstRAM PrivateRAM RegisterOperands
+
+variable {W p r k : ℕ}
+
+private def Contained {n : ℕ} (reg : Fin n ↪ Fin r) (op : Instr W p r k) :=
+ ∀ a, destination op = some a → a ∈ Set.range reg
+
+private theorem widen {a b : ℕ} (u : Fin a ↪ Fin b) (reg : Fin b ↪ Fin r) {op : Instr W p r k}
+ (h : Contained (u.trans reg) op) : Contained reg op := by
+ intro j hj
+ obtain ⟨i,hi⟩ := h j hj
+ exact ⟨u i,hi⟩
+
+private theorem mover (source : LeafFieldCopy.Source) (pc : Fin 5 → Fin p) (reg : Fin 5 ↪ Fin r)
+ (done : Fin p) (i : Fin 5) : Contained (W := W) (k := k) reg (LeafFieldCopy.instruction source pc reg done i) := by
+ intro a ha
+ cases source <;> fin_cases i <;> first | exact ⟨_, Option.some.inj ha⟩ | contradiction
+
+private theorem prepare (port : Option CursorNetwork.LocalPort) (pc : Fin 2 → Fin p)
+ (reg : Fin 11 ↪ Fin r) (done : Fin p) (i : Fin 2) :
+ Contained (W := W) (k := k) reg (LeafIncidentLoad.prepare port pc reg done i) := by
+ intro a ha
+ cases port <;> fin_cases i <;> exact ⟨_, Option.some.inj ha⟩
+
+private theorem classifier (pc : Fin 6 → Fin p) (reg : Fin 4 ↪ Fin r) (done : Fin p) (i : Fin 6) :
+ Contained (W := W) (k := k) reg (LeafSuccessorClass.instruction pc reg done i) := by
+ intro a ha
+ fin_cases i <;> first | exact ⟨_, Option.some.inj ha⟩ | contradiction
+
+private theorem successor (pc : LeafSuccessorFields.Stage → Fin p) (reg : Fin 20 ↪ Fin r) (done : Fin p)
+ (s : LeafSuccessorFields.Stage) : Contained (W := W) (k := k) reg (LeafSuccessorFields.instruction pc reg done s) := by
+ cases s with
+ | classify recv i => exact widen _ reg (classifier _ _ _ i)
+ | prepare recv use i => exact widen _ reg (prepare _ _ _ _ i)
+ | move recv use i => exact widen _ reg (widen _ _ (mover _ _ _ _ i))
+ | sender recv => intro a ha; cases recv <;> exact ⟨_,Option.some.inj ha⟩
+ | _ => intro a ha; first | exact ⟨_,Option.some.inj ha⟩ | contradiction
+
+private theorem sort (pc : LeafSortFields.Stage → Fin p) (reg : Fin 17 ↪ Fin r) (done : Fin p)
+ (s : LeafSortFields.Stage) : Contained (W := W) (k := k) reg (LeafSortFields.instruction pc reg done s) := by
+ cases s with
+ | prepare recv side i =>
+ simp only [LeafSortFields.instruction]
+ exact widen (Fin.castAddEmb 6) reg (prepare _ _ (LeafSortFields.subRegs reg) _ i)
+ | move recv side i =>
+ simp only [LeafSortFields.instruction]
+ exact widen (Fin.castAddEmb 6) reg (widen (Fin.castAddEmb 6) (LeafSortFields.subRegs reg)
+ (mover .resident _ (LeafIncidentLoad.copyRegs (LeafSortFields.subRegs reg)) _ i))
+ | _ => intro a ha; first | exact ⟨_,Option.some.inj ha⟩ | contradiction
+
+private theorem core (pc : LeafIncidentCore.Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p)
+ (s : LeafIncidentCore.Stage) : Contained (W := W) (k := k) reg (LeafIncidentCore.instruction pc reg done s) := by
+ rcases s with s | i | s
+ · exact widen _ reg (successor _ _ _ s)
+ · intro a ha; fin_cases i <;> exact ⟨_,Option.some.inj ha⟩
+ · exact widen _ reg (sort _ _ _ s)
+
+/-- Every written register is an operand of the loader's actual embedding. -/
+theorem destination_mem (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) (i : Stage) (a : Fin r)
+ (ha : destination (instruction (W := W) (k := k) pc reg done i) = some a) : a ∈ Set.range reg := by
+ cases i with
+ | inl i =>
+ change destination (LeafIncidentGeometry.emit reg _ LeafIncidentGeometry.rows[i]) = some a at ha
+ generalize LeafIncidentGeometry.rows[i] = line at ha
+ obtain ⟨j,rhs⟩ := line
+ cases rhs <;> exact ⟨j,Option.some.inj ha⟩
+ | inr i => exact core _ _ _ i a ha
+
+end PairSimulation.LeafIncidentMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentGeometry.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentGeometry.lean
new file mode 100644
index 0000000000..447cc04973
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentGeometry.lean
@@ -0,0 +1,222 @@
+import Mathlib.Tactic.Linarith
+import OAI.Computability.VPVNP.CursorFieldOffsets
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Initial private registers for copying the virtual validator's incident vector
+
+The 24 straight-line instructions compute the rectangular arc stride, the
+triangular sorting-layer count, the four source bases, and the exclusive
+end of the incident stack. Each arithmetic row is width independent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentGeometry
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord RAMLayout CursorRouting
+open scoped Fin.CommRing
+
+variable {W p r k D H w : ℕ}
+
+/-- An incident-geometry assignment's right-hand side, drawn from a five-bit literal, a
+register copy, or a binary operation on two registers. -/
+inductive Operand where
+ | literal (n : Fin 32) | copy (i : Fin 30) | binary (op : BinaryOp) (i j : Fin 30)
+
+/-- One incident-geometry assignment pairing a destination in the thirty-register bank with its
+right-hand side. -/
+abbrev Line := Fin 30 × Operand
+
+/-- The straight-line assignments that derive payload widths, the four argument-buffer bases,
+and the incident stack endpoint from the raw geometry. -/
+def rows : List Line :=
+ [(3,.literal 1),(16,.literal 0),(12,.binary .sub 11 3),(14,.binary .shiftLeft 3 11),
+ (5,.literal 8),(5,.binary .mul 5 21),(25,.literal 20),(25,.binary .mul 25 20),(25,.binary .mul 25 21),
+ (28,.binary .add 11 3),(28,.binary .mul 28 11),(29,.literal 2),(28,.binary .div 28 29),
+ (28,.binary .mul 28 25),(26,.binary .mul 11 5),(26,.binary .add 26 28),(27,.binary .add 28 5),
+ (27,.binary .add 27 27),(7,.copy 22),(8,.binary .add 7 26),(9,.binary .add 8 26),
+ (10,.binary .add 9 26),(24,.binary .add 23 27),(2,.copy 24)]
+
+/-- Index of an instruction in the 24-row incident-geometry calculation. -/
+abbrev Stage := Fin 24
+
+/-- The program counter for the next geometry row, or the caller's continuation after the last
+assignment. -/
+def target (pc : Stage → Fin p) (done : Fin p) (i : Fin (rows.length+1)) :=
+ if h : i.val < rows.length then pc ⟨i.val,h⟩ else done
+
+/-- Compile a geometry assignment into a native constant, copy, or binary instruction with the
+specified continuation. -/
+def emit (reg : Fin 30 ↪ Fin r) (dst : Fin p) (l : Line) : Instr W p r k :=
+ match l.2 with
+ | .literal n => .constant (reg l.1) (n.val : Word W) dst
+ | .copy i => .copy (reg l.1) (reg i) dst
+ | .binary op i j => .binary op (reg l.1) (reg i) (reg j) dst
+
+/-- The native instruction for a given geometry row, using the linked registers and the next
+row's program counter. -/
+def instruction (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) (i : Stage) : Instr W p r k :=
+ emit reg (target pc done i.succ) rows[i]
+
+theorem resize_instruction (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) (i : Stage) :
+ (instruction (W := 5) (k := k) pc reg done i).resize W = instruction pc reg done i := by
+ unfold instruction emit
+ generalize rows[i] = l
+ rcases l with ⟨dst,rhs⟩
+ cases rhs with
+ | literal v =>
+ change Instr.constant _ (Fin.ofNat (2^W) (v.val % 32)) _ = .constant _ (v.val : Word W) _
+ rw [Nat.mod_eq_of_lt v.isLt]; rfl
+ | copy _ => rfl
+ | binary _ _ _ => rfl
+
+/-- The machine contains the compiled geometry instruction at every assigned row and uses the
+specified continuation for the last one. -/
+def Linked (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+/-- Evaluate a geometry assignment's right-hand side on the current thirty-register word bank. -/
+def Operand.eval (bank : Fin 30 → Word W) : Operand → Word W
+ | .literal n => (n.val : Word W)
+ | .copy i => bank i
+ | .binary op i j => op.eval (bank i) (bank j)
+
+private def assign (reg : Fin 30 ↪ Fin r) (bank : Fin r → Word W) (l : Line) :=
+ Function.update bank (reg l.1) (l.2.eval (bank ∘ reg))
+
+private theorem sequence (M : Machine W p r k) (reg : Fin 30 ↪ Fin r) (ls : List Line)
+ (pc : Fin (ls.length+1) → Fin p) (hl : ∀ i : Fin ls.length, M.code (pc i.castSucc) = emit reg (pc i.succ) ls[i])
+ (c : Config W p r) (hc : c.pc = pc 0) :
+ Prefix M c (List.replicate ls.length .tick)
+ {c with pc := pc (Fin.last ls.length),reg := ls.foldl (assign reg) c.reg} := by
+ induction ls generalizing c with
+ | nil =>
+ change Prefix M c [] {c with pc := pc (Fin.last 0)}
+ rw [show Fin.last 0 = 0 from rfl,← hc]; exact .nil c
+ | cons l ls ih =>
+ let mid := c.put (pc (Fin.succ 0)) (reg l.1) (l.2.eval (c.reg ∘ reg))
+ have s : M.program.step c = .localStep mid := by
+ change (M.code c.pc).run _ _ = _
+ have row := hl 0
+ change M.code (pc 0) = emit reg (pc (Fin.succ 0)) l at row
+ rw [hc,row]; rcases l with ⟨dst,rhs⟩; cases rhs <;> rfl
+ exact .tick s (ih (fun i => pc i.succ) (fun i => hl i.succ) mid rfl)
+
+private theorem assign_at (reg : Fin 30 ↪ Fin r) (ls : List Line) (bank : Fin r → Word W) :
+ ls.foldl (assign reg) bank ∘ reg =
+ ls.foldl (fun b l => Function.update b l.1 (l.2.eval b)) (bank ∘ reg) := by
+ induction ls generalizing bank with
+ | nil => rfl
+ | cons l ls ih =>
+ rw [List.foldl_cons,List.foldl_cons,ih]; congr 1
+ funext i
+ by_cases h : i = l.1 <;> simp [h,assign]
+
+private theorem assign_frame (reg : Fin 30 ↪ Fin r) (ls : List Line) (bank : Fin r → Word W) (i : Fin r)
+ (outside : ∀ l ∈ ls, i ≠ reg l.1) : ls.foldl (assign reg) bank i = bank i := by
+ induction ls generalizing bank with
+ | nil => rfl
+ | cons l ls ih =>
+ rw [List.foldl_cons,ih _ (fun j hj => outside j (List.mem_cons_of_mem l hj)),assign,
+ Function.update_of_ne (outside l (List.mem_cons_self ..))]
+
+/-- The six input registers hold the dimension, site, bucket size, word width, argument base,
+and stack base for the incident copy. -/
+structure Ready (D H w site nodeBase stackBase : ℕ) (bank : Fin 30 → Word W) : Prop where
+ dim : bank 11 = (D : Word W)
+ site : bank 13 = (site : Word W)
+ bucket : bank 20 = (H : Word W)
+ width : bank 21 = (w : Word W)
+ arena : bank 22 = (nodeBase : Word W)
+ base : bank 23 = (stackBase : Word W)
+
+/-- The geometry registers hold the derived counts, payload widths, four buffer bases, and
+destination stack endpoint needed for the incident copy. -/
+structure Prepared (D H w nodeBase stackBase : ℕ) (bank : Fin 30 → Word W) : Prop where
+ one : bank 3 = 1
+ zero : bank 16 = 0
+ last : bank 12 = ((D-1 : ℕ) : Word W)
+ count : bank 14 = ((2^D : ℕ) : Word W)
+ successor : bank 5 = ((8*w : ℕ) : Word W)
+ block : bank 25 = ((blockBits H w : ℕ) : Word W)
+ arc : bank 26 = ((ramPayloadWidth D H w : ℕ) : Word W)
+ size : bank 27 = ((RAMLayout.width D H w : ℕ) : Word W)
+ base₀ : bank 7 = (nodeBase : Word W)
+ base₁ : bank 8 = ((nodeBase+ramPayloadWidth D H w : ℕ) : Word W)
+ base₂ : bank 9 = ((nodeBase+2*ramPayloadWidth D H w : ℕ) : Word W)
+ base₃ : bank 10 = ((nodeBase+3*ramPayloadWidth D H w : ℕ) : Word W)
+ top : bank 24 = ((stackBase+RAMLayout.width D H w : ℕ) : Word W)
+ cursor : bank 2 = ((stackBase+RAMLayout.width D H w : ℕ) : Word W)
+
+private theorem triangular_fit (D : ℕ) : D*(D+1)<2^(D+1) := by
+ induction D with
+ | zero => decide
+ | succ d ih =>
+ rcases d with _|d
+ · decide
+ · rcases d with _|d
+ · decide
+ · rw [pow_succ]
+ have h : d+2+2 ≤ 2*(d+2) := by omega
+ nlinarith
+
+private theorem layers (D : ℕ) (hD : D < W) (hW : 2 ≤ W) :
+ BinaryOp.div.eval (((D : Word W)+1)*(D : Word W)) 2 = ((layerCount D : ℕ) : Word W) := by
+ have hfit := (triangular_fit D).trans_le (Nat.pow_le_pow_right (by decide : 0<2) hD)
+ have hm : ((D : Word W)+1)*(D : Word W) = (((D+1)*D : ℕ) : Word W) := by push_cast; rfl
+ have h2 : 2 < 2^W := (by decide : 2<2^2).trans_le (Nat.pow_le_pow_right (by decide) hW)
+ have hval : (2 : Word W).val = 2 := Nat.mod_eq_of_lt h2
+ have hnum : (((D+1)*D : ℕ) : Word W).val = (D+1)*D := Nat.mod_eq_of_lt (by simpa [Nat.mul_comm] using hfit)
+ simp only [BinaryOp.eval,hm,hval,hnum,layerCount,Nat.choose_two_right,Nat.add_one_sub_one]
+ rfl
+
+private theorem site_count (D : ℕ) (hd : D Function.update b l.1 (l.2.eval b)) bank) := by
+ have hl := layers D hW (by omega)
+ have hc := site_count D hW
+ have sub : ((D-1 : ℕ) : Word W) = (D : Word W)-1 := by rw [Nat.cast_sub hD,Nat.cast_one]
+ constructor <;>
+ simp (config := {decide := true}) [rows,Operand.eval,Function.update,eval_add,eval_mul,eval_sub,
+ h.dim,h.width,h.bucket,h.arena,h.base,hl,hc,sub,blockBits,ramPayloadWidth,RAMLayout.width] <;> ring
+
+/-- Exact deterministic prefix from the six caller-supplied geometry registers. -/
+theorem run (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p)
+ (link : Linked M pc reg done) (c : Config W p r) (hc : c.pc = pc 0)
+ {site nodeBase stackBase : ℕ} (ready : Ready D H w site nodeBase stackBase (c.reg ∘ reg))
+ (hD : 1 ≤ D) (hW : D < W) :
+ ∃ out, Prefix M c (List.replicate rows.length .tick) out ∧ out.pc = done ∧
+ Prepared D H w nodeBase stackBase (out.reg ∘ reg) ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent ∧ ∀ i, (∀ l ∈ rows, i ≠ reg l.1) → out.reg i = c.reg i := by
+ have h := sequence M reg rows (target pc done) (fun i => by
+ have stepPC : target pc done i.castSucc = pc i := by
+ simp [target,i.isLt]; congr 1
+ rw [stepPC]; exact link i) c
+ (by simpa [target, rows] using hc)
+ let out : Config W p r := {c with pc := done,reg := rows.foldl (assign reg) c.reg}
+ have endPC : target pc done (Fin.last rows.length) = done := by simp [target]
+ rw [endPC] at h
+ refine ⟨out,h,rfl,?_,rfl,rfl,assign_frame reg rows c.reg⟩
+ change Prepared _ _ _ _ _ (rows.foldl (assign reg) c.reg ∘ reg)
+ rw [assign_at]
+ exact result _ ready hD hW
+
+end PairSimulation.LeafIncidentGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentLoad.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentLoad.lean
new file mode 100644
index 0000000000..2b707ba780
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentLoad.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.PairSimulationLeafFieldCopy
+import OAI.Computability.VPVNP.CursorInitialCheck
+
+/-!
+# Loading a selected incident field from the four resident cursor arcs
+
+The direction and selected arc are finite control. The source offset, length,
+four half-buffer bases and descending destination cursor are runtime words.
+An endpoint selects the zero source. The local program never consults a
+global wire assignment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentLoad
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord CursorNetwork CursorRouting RAMLayout
+open LeafFieldCopy (word)
+open scoped Fin.CommRing
+
+variable {bits w D H p r k : ℕ}
+
+/-- First five operands are shared with the descending field mover, then
+length, arc offset, and the two outgoing and two incoming buffer bases. -/
+def baseReg : LocalPort → Fin 11
+ | .outgoing false => 7
+ | .outgoing true => 8
+ | .incoming false => 9
+ | .incoming true => 10
+
+/-- Registers of the field mover inside the incident-loader register file. -/
+def copyRegs (reg : Fin 11 ↪ Fin r) : Fin 5 ↪ Fin r := (Fin.castAddEmb 6).trans reg
+
+/-- Select resident input for an available port and zeros at a missing endpoint. -/
+def mode : Option LocalPort → LeafFieldCopy.Source
+ | none => .zero
+ | some _ => .resident
+
+/-- Private address of a field within its half-wire buffer. -/
+def sourceAddress (base : LocalPort → ℕ) (offset : ℕ) : Option LocalPort → ℕ
+ | none => 0
+ | some port => base port+offset
+
+/-- The two address setup rows followed by the five-row move loop. -/
+def prepare (port : Option LocalPort) (pc : Fin 2 → Fin p) (reg : Fin 11 ↪ Fin r) (copy : Fin p) :
+ Fin 2 → Instr bits p r k :=
+ ![(match port with
+ | none => .constant (reg 0) 0 (pc 1)
+ | some a => .binary .add (reg 0) (reg (baseReg a)) (reg 6) (pc 1)),
+ .binary .sub (reg 1) (reg 2) (reg 5) copy]
+
+theorem resize_prepare (port : Option LocalPort) (pc : Fin 2 → Fin p) (reg : Fin 11 ↪ Fin r)
+ (copy : Fin p) (i : Fin 2) :
+ (prepare (bits := 1) (k := k) port pc reg copy i).resize bits = prepare port pc reg copy i := by
+ cases port <;> fin_cases i <;> rfl
+
+/-- All four resident half-wire arrays encode their declared bits. -/
+def Stored (base : LocalPort → ℕ) (buf : Buffers D H w) (m : Word bits → Word bits) :=
+ ∀ port i, m (word bits (base port+i.val)) = PrivateFields.bitValue bits (buf port i)
+
+/-- The selected consecutive bits of one port, or zeros when that port is absent. -/
+def Field (port : Option LocalPort) (offset : ℕ) (n : ℕ)
+ (fit : offset+n ≤ ramPayloadWidth D H w) (buf : Buffers D H w) : List Bool :=
+ List.ofFn fun i : Fin n => match port with
+ | none => false
+ | some a => buf a ⟨offset+i.val, by have := i.isLt; omega⟩
+
+@[simp] theorem length_field (port : Option LocalPort) (offset n : ℕ) (fit) (buf : Buffers D H w) :
+ (Field port offset n fit buf).length = n := List.length_ofFn
+
+theorem place_append (lo : ℕ) (xs ys : List Bool) (m : Word bits → Word bits) :
+ LeafFieldCopy.place lo (xs++ys) m =
+ LeafFieldCopy.place lo ys (LeafFieldCopy.place (lo+ys.length) xs m) := by
+ induction xs generalizing m with
+ | nil => rfl
+ | cons x xs ih => simp [LeafFieldCopy.place, ih, Nat.add_assoc, Nat.add_comm xs.length ys.length]
+
+/-- State and continuation of a completed native field copy. -/
+structure Result (reg : Fin 11 ↪ Fin r) (done : Fin p) (c out : Config bits p r)
+ (lo : ℕ) (bs : List Bool) : Prop where
+ pc : out.pc = done
+ cursor : out.reg (reg 2) = word bits lo
+ frame : ∀ i, i ≠ reg 0 → i ≠ reg 1 → i ≠ reg 2 → i ≠ reg 4 → out.reg i = c.reg i
+ mem : out.privateMem = LeafFieldCopy.place lo bs c.privateMem
+ persistent : out.persistent = c.persistent
+
+/-- Copy or clamp the chosen whole field. This theorem accounts for both
+address setup instructions, every bit movement and the terminal test. -/
+theorem copy_run (M : Machine bits p r k) (port : Option LocalPort)
+ (pc : Fin 2 → Fin p) (copy : Fin 5 → Fin p) (reg : Fin 11 ↪ Fin r) (done : Fin p)
+ (hprep : ∀ i, M.code (pc i) = prepare port pc reg (copy 0) i)
+ (hcopy : LeafFieldCopy.Linked M (mode port) copy (copyRegs reg) done)
+ (base : LocalPort → ℕ) (buf : Buffers D H w) (offset n lo : ℕ)
+ (inside : offset+n ≤ ramPayloadWidth D H w) (fit : lo+n < 2^bits)
+ (apart : ∀ a, base a+ramPayloadWidth D H w ≤ lo ∨ lo+n ≤ base a)
+ (sourceFit : ∀ a, base a+ramPayloadWidth D H w ≤ 2^bits)
+ (c : Config bits p r) (hc : c.pc = pc 0) (hbase : ∀ a, c.reg (reg (baseReg a)) = word bits (base a))
+ (hlen : c.reg (reg 5) = word bits n) (hoff : c.reg (reg 6) = word bits offset)
+ (hdst : c.reg (reg 2) = word bits (lo+n)) (hone : c.reg (reg 3) = 1)
+ (stored : Stored base buf c.privateMem) :
+ ∃ out, Prefix M c (List.replicate (5*n+3) .tick) out ∧
+ Result reg done c out lo (Field port offset n inside buf) := by
+ let src := sourceAddress base offset port
+ let a := c.put (pc 1) (reg 0) (word bits src)
+ let b := a.put (copy 0) (reg 1) (word bits lo)
+ have s₀ : M.program.step c = .localStep a := by
+ cases port <;> simp [Machine.program, hc, hprep 0, prepare, Instr.run, BinaryOp.eval,
+ hbase,hoff, src, sourceAddress, a, word]
+ have s₁ : M.program.step a = .localStep b := by
+ change (M.code (pc 1)).run M.publicData a = _
+ rw [hprep 1]
+ simp [prepare, Instr.run, BinaryOp.eval, b, a, Config.put, hdst, hlen, word]
+ have pre : Prefix M c (List.replicate 2 .tick) b := .tick s₀ (.tick s₁ (.nil _))
+ let bs := Field port offset n inside buf
+ have length : bs.length = n := length_field ..
+ have data (i : Fin bs.length) :
+ (mode port).value b.privateMem (word bits (src+i.val)) = PrivateFields.bitValue bits bs[i.val] := by
+ cases port with
+ | none => simp [bs, Field, mode, LeafFieldCopy.Source.value, PrivateFields.bitValue]
+ | some port =>
+ have hi : offset+i.val < ramPayloadWidth D H w := by have := i.isLt; omega
+ simpa [bs, Field, mode, LeafFieldCopy.Source.value, src, sourceAddress, b, a, Config.put,
+ Nat.add_assoc] using stored port ⟨offset+i.val,hi⟩
+ have safe (h : mode port = .resident) : src+bs.length ≤ 2^bits ∧
+ (src+bs.length ≤ lo ∨ lo+bs.length ≤ src) := by
+ cases port with
+ | none => contradiction
+ | some port =>
+ have := sourceFit port
+ have := apart port
+ simp only [src,sourceAddress,length]
+ omega
+ obtain ⟨out,tail,res⟩ := LeafFieldCopy.run hcopy b rfl src lo bs
+ (by change b.reg (reg 0) = _; simp [b,a,Config.put]) (by change b.reg (reg 1) = _; simp [b])
+ (by change b.reg (reg 2) = _; simp [b,a,Config.put,hdst,length])
+ (by change b.reg (reg 3) = _; simp [b,a,Config.put,hone])
+ (by rwa [length]) safe data
+ refine ⟨out, ?_, res.pc, res.destination, ?_, res.privateMem, res.persistent⟩
+ · convert pre.append tail using 1
+ rw [← List.replicate_add, length]
+ congr 1; omega
+ · intro i h0 h1 h2 h4
+ rw [res.frame i h0 h2 h4]
+ simp [b,a,Config.put,Function.update_of_ne h0,Function.update_of_ne h1]
+
+end PairSimulation.LeafIncidentLoad
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentMachine.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentMachine.lean
new file mode 100644
index 0000000000..6fa341b5e5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentMachine.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentCore
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentGeometry
+import OAI.Computability.VPVNP.RAMApplications
+
+/-!
+# Fixed native table for preparing the virtual validator's incident stack
+
+Six caller words designate the geometry, the current site and the two
+private intervals. The table computes every address and fills the stack
+directly from the four resident halves. Its destination top is the exclusive
+end even though the working cursor retreats to the base.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentMachine
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork RAMLayout PrimedCounter.GuessWord
+open LeafFieldCopy (word)
+
+variable {W D H w p r k : ℕ}
+
+/-- Control labels of the geometry preparation and field-loading loops. -/
+abbrev Stage := LeafIncidentGeometry.Stage ⊕ LeafIncidentCore.Stage
+
+/-- The native row for preparing the field addresses or copying their bits. -/
+def instruction (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) : Stage → Instr W p r k
+ | .inl i => LeafIncidentGeometry.instruction (pc ∘ Sum.inl) reg (pc (.inr (.inl .sendNext))) i
+ | .inr s => LeafIncidentCore.instruction (pc ∘ Sum.inr) reg done s
+
+private theorem resize_twice (i : Instr 1 p r k) : (i.resize 5).resize W = i.resize W := by
+ cases i <;> try rfl
+ case constant dst v next => simp only [Instr.resize, resize_literal (show 1 ≤ 5 by decide)]
+
+theorem resize_instruction (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) (s : Stage) :
+ (instruction (W := 5) (k := k) pc reg done s).resize W = instruction pc reg done s := by
+ cases s with
+ | inl i => exact LeafIncidentGeometry.resize_instruction ..
+ | inr s =>
+ change (LeafIncidentCore.instruction _ _ _ _).resize _ = _
+ rw [← LeafIncidentCore.resize_instruction (W := 5) (pc ∘ Sum.inr) reg done s, resize_twice,
+ LeafIncidentCore.resize_instruction]
+ rfl
+
+/-- The complete incident machine is installed at the chosen host labels. -/
+def Linked (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p) :=
+ ∀ s, M.code (pc s) = instruction pc reg done s
+
+/-- Starting address of each of the four resident half-wire arrays. -/
+def base (node width : ℕ) : LocalPort → ℕ
+ | .outgoing false => node
+ | .outgoing true => node+width
+ | .incoming false => node+2*width
+ | .incoming true => node+3*width
+
+/-- Register write footprint of the geometry and incident-loading stages together. -/
+def changed : List (Fin 30) := (LeafIncidentGeometry.rows.map Prod.fst) ++ LeafIncidentCore.changed
+
+/-- Total native instructions, including the 24 geometry-preparation rows. -/
+def ticks (v : Site D) (H w : ℕ) := 24+LeafIncidentCore.ticks v H w
+
+variable [NeZero D]
+
+/-- Exact memory, register frame and continuation after incident materialization. -/
+structure Result (reg : Fin 30 ↪ Fin r) (done : Fin p) (lo : ℕ) (v : Site D) (buf : Buffers D H w)
+ (c out : Config W p r) : Prop where
+ pc : out.pc = done
+ top : out.reg (reg 24) = word W (lo+width D H w)
+ cursor : out.reg (reg 2) = word W lo
+ frame : ∀ i, (∀ j ∈ changed, i ≠ reg j) → out.reg i = c.reg i
+ memory : out.privateMem = LeafFieldCopy.place lo (List.ofFn (incidentBuffer (0,v) buf)) c.privateMem
+ persistent : out.persistent = c.persistent
+
+/-- Full machine execution from raw word arguments, including the arithmetic
+that prepares the source bases, both field lengths and the stack top. -/
+theorem run (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 30 ↪ Fin r) (done : Fin p)
+ (hl : Linked M pc reg done) (node lo : ℕ) (buf : Buffers D H w) (v : Site D)
+ (c : Config W p r) (hc : c.pc = pc (.inl 0))
+ (ready : LeafIncidentGeometry.Ready D H w v.val node lo (c.reg ∘ reg)) (hDW : D < W)
+ (stored : LeafIncidentLoad.Stored (base node (ramPayloadWidth D H w)) buf c.privateMem)
+ (destFits : lo+width D H w < 2^W) (srcFits : node+4*ramPayloadWidth D H w ≤ 2^W)
+ (sep : node+4*ramPayloadWidth D H w ≤ lo ∨ lo+width D H w ≤ node) :
+ (ticks v H w ≤ 80*w+6*D+53+layerCount D*(10*blockBits H w+14)) ∧
+ ∃ out, Prefix M c (List.replicate (ticks v H w) .tick) out ∧ Result reg done lo v buf c out := by
+ have linkG : LeafIncidentGeometry.Linked M (pc ∘ Sum.inl) reg (pc (.inr (.inl .sendNext))) :=
+ fun s => hl (.inl s)
+ obtain ⟨a,prep,ap,g,am,aper,af⟩ := LeafIncidentGeometry.run M _ _ _ linkG c hc ready
+ (Nat.pos_of_ne_zero (NeZero.ne D)) hDW
+ let origin := base node (ramPayloadWidth D H w)
+ have dim : a.reg (reg 11) = c.reg (reg 11) := af _ fun l hl => reg.injective.ne (fun e =>
+ (show (11 : Fin 30) ∉ LeafIncidentGeometry.rows.map Prod.fst by decide) (e ▸ List.mem_map_of_mem hl))
+ have site : a.reg (reg 13) = c.reg (reg 13) := af _ fun l hl => reg.injective.ne (fun e =>
+ (show (13 : Fin 30) ∉ LeafIncidentGeometry.rows.map Prod.fst by decide) (e ▸ List.mem_map_of_mem hl))
+ have fixed : LeafSuccessorFields.Fixed (LeafIncidentCore.successorRegs reg) origin v w a := by
+ refine ⟨g.one,g.successor,?_,dim.trans ready.dim,g.last,site.trans ready.site,g.count,g.zero⟩
+ intro port
+ cases port with
+ | outgoing side => cases side with | false => exact g.base₀ | true => exact g.base₁
+ | incoming side => cases side with | false => exact g.base₂ | true => exact g.base₃
+ have bound (p : LocalPort) : node ≤ origin p ∧ origin p+ramPayloadWidth D H w ≤ node+4*ramPayloadWidth D H w := by
+ cases p with | outgoing s | incoming s => cases s <;> simp only [origin,base] <;> omega
+ obtain ⟨cost,out,body,res⟩ := LeafIncidentCore.run M (pc ∘ Sum.inr) reg done
+ (fun s => hl (.inr s)) origin buf v lo a ap fixed g.block hDW g.cursor (am ▸ stored) destFits
+ (fun p => (bound p).2.trans srcFits)
+ (fun p => sep.imp ((bound p).2.trans) (fun h => h.trans (bound p).1))
+ have top : out.reg (reg 24) = a.reg (reg 24) := res.frame _ fun j hj => reg.injective.ne (fun e =>
+ (show (24 : Fin 30) ∉ LeafIncidentCore.changed by decide) (e ▸ hj))
+ refine ⟨by unfold ticks; omega,out, ?_,res.pc,top.trans g.top,res.cursor, ?_, ?_,res.persistent.trans aper⟩
+ · change Prefix M c (List.replicate 24 .tick) a at prep
+ simpa only [ticks,List.replicate_add] using prep.append body
+ · intro i hi
+ rw [res.frame i (fun j hj => hi j (List.mem_append_right _ hj))]
+ exact af i (fun l h => hi _ (List.mem_append_left _ (List.mem_map_of_mem h)))
+ · rw [res.memory,am]
+
+end PairSimulation.LeafIncidentMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentReady.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentReady.lean
new file mode 100644
index 0000000000..40dfdd9b58
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentReady.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentMachine
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentBank
+
+/-!
+# Native incident loader at the auxiliary stack-interpreter boundary
+
+The executable two-direction successor scan and triangular layer scan finish
+with the exact auxiliary stack bank. Its scalar cells and pending descriptor
+stack survive the copy. The new DFS scratch is determined on all addresses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentBank
+
+open BurstRAM PrivateRAM CursorNetwork CursorRouting RAMLayout RAMTape StackMachine
+open PrimedCounter.GuessWord LeafStartup
+
+set_option synthInstance.maxSize 10000
+
+variable {d e w W p r k endAddr top : ℕ} [NeZero d]
+variable {A : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout A n a H w}
+
+/-- The destination stack port for incident bits in the auxiliary validator with 52 registers
+and 34 public operands. -/
+abbrev incident := LeafLoadedBank.incidentPort 52 34
+
+/-- Execute the actual leaf incident table from the six raw geometry words.
+The stack-top register is shared with its virtual port, and the protected
+register assignment is disjoint from the table's explicitly changed rows. -/
+theorem machine_run (data : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hcap : 2^d*2^e < 2^w)
+ (v : Site d) (buf : Buffers d (2^e) w) (L : Layout (Port 52 34) W)
+ (stack : Register (Port 52 34) ↪ Fin r) (geom : Fin 30 ↪ Fin r)
+ (pc : LeafIncidentMachine.Stage → Fin p) (M : Machine W p r k) (done : Fin p)
+ (linked : LeafIncidentMachine.Linked M pc geom done) (node : ℕ) (c : Config W p r)
+ (entry : c.pc = pc (.inl 0))
+ (ready : LeafIncidentGeometry.Ready d (2^e) w v.val node (L.base incident) (c.reg ∘ geom))
+ (hDW : d < W)
+ (stored : LeafIncidentLoad.Stored (LeafIncidentMachine.base node (ramPayloadWidth d (2^e) w))
+ buf c.privateMem)
+ (srcFits : node+4*ramPayloadWidth d (2^e) w ≤ 2^W)
+ (sep : node+4*ramPayloadWidth d (2^e) w ≤ L.base incident ∨
+ L.base incident+width d (2^e) w ≤ node)
+ (shared : geom 24 = stack (.top incident))
+ (protect : ∀ j : Register (Port 52 34), j ≠ .tmp → j ≠ .top incident →
+ ∀ i ∈ LeafIncidentMachine.changed, stack j ≠ geom i)
+ (old : Word W → Word W) (pending : List (Word W)) (htop : top+pending.length = endAddr)
+ (previous : DFS.Represents old top pending) (above : ∀ j, endAddr ≤ L.base j) :
+ let x := auxiliary data hw hcap (0,v) buf
+ let scalar := LeafRegisterBank.scalarBank (field (r := 52)) x data.pub
+ let full := bank 52 x data.pub
+ Represents L stack c scalar → (∀ j, (scalar j).length ≤ L.capacity) →
+ width d (2^e) w ≤ L.capacity → c.privateMem = LeafLoadedBank.memory L scalar old →
+ ∃ out, Prefix M c (List.replicate (LeafIncidentMachine.ticks v (2^e) w) .tick) out ∧
+ LeafIncidentMachine.Result geom done (L.base incident) v buf c out ∧
+ Represents L stack out full ∧ out.privateMem = LeafLoadedBank.memory L full old ∧
+ DFS.Represents out.privateMem top pending ∧
+ DFS.scratch endAddr out.privateMem = LeafLoadedBank.scratch L full (DFS.scratch endAddr old) := by
+ intro x scalar full rep fit room initial
+ have dest := (Nat.add_le_add_left room (L.base incident)).trans_lt (L.fits incident)
+ obtain ⟨_, out, prefixRun, phys⟩ := LeafIncidentMachine.run M pc geom done linked node (L.base incident)
+ buf v c entry ready hDW stored dest srcFits sep
+ have mem : out.privateMem = LeafFieldCopy.place (L.base incident)
+ (List.ofFn (incidentBits x.sends x.v)) c.privateMem := by
+ have eqn := sends_incident (0,v) buf
+ change incidentBits x.sends x.v = incidentBuffer (0,v) buf at eqn
+ rw [eqn]
+ exact phys.memory
+ have newTop : out.reg (stack (.top incident)) = L.address incident (width d (2^e) w) := by
+ rw [← shared]
+ exact phys.top
+ obtain ⟨rep', exactMem⟩ := fullBank L stack x data.pub c out rep fit room mem newTop
+ (fun j ht hi => phys.frame _ (protect j ht hi)) old initial
+ exact ⟨out, prefixRun, phys, rep', exactMem, initialized_scratch L full exactMem above htop previous⟩
+
+end PairSimulation.LeafIncidentBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentScratch.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentScratch.lean
new file mode 100644
index 0000000000..4bc8d6b29f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentScratch.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.PairSimulationLeafLoadedBank
+
+/-!
+# The pending DFS stack after leaf initialization
+
+The descriptors still to visit lie strictly below the scratch boundary.
+Loading the virtual validator only changes words in its occupied stack
+intervals, all of which start at or above that boundary. Restricting the
+resulting memory to the scratch region gives the initialized leaf bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentBank
+
+open BurstRAM RAMTape StackMachine
+open scoped Fin.CommRing
+
+variable {K : Type} {w : ℕ}
+
+/-- A cell outside every occupied interval retains its previous word. -/
+theorem memory_outside (L : Layout K w) (s : Stacks K) (old : Word w → Word w) (a : Word w)
+ (outside : ∀ j, a.val < L.base j ∨ L.base j+(s j).length ≤ a.val) :
+ LeafLoadedBank.memory L s old a = old a := by
+ have empty : ¬ ∃ j, LeafLoadedBank.occupies L s a j := by
+ rintro ⟨j, lo, hi⟩
+ rcases outside j with below | beyond <;> omega
+ rw [LeafLoadedBank.memory, LeafLoadedBank.readCell, dite_eq_right empty]
+ rfl
+
+/-- Installing the leaf bank preserves all pending DFS descriptors and
+updates scratch by precisely the bank's occupied words. -/
+theorem initialized_scratch (L : Layout K w) (s : Stacks K) {old mem : Word w → Word w}
+ {endAddr top : ℕ} {pending : List (Word w)} (loaded : mem = LeafLoadedBank.memory L s old)
+ (above : ∀ j, endAddr ≤ L.base j) (htop : top+pending.length = endAddr)
+ (rep : DFS.Represents old top pending) :
+ DFS.Represents mem top pending ∧
+ DFS.scratch endAddr mem = LeafLoadedBank.scratch L s (DFS.scratch endAddr old) := by
+ subst mem
+ refine ⟨⟨rep.1, ?_⟩, LeafLoadedBank.scratch_memory L s endAddr old⟩
+ intro i
+ apply (memory_outside L s old _ ?_).trans (rep.2 i)
+ intro j
+ apply Or.inl
+ change ((top+i.val : ℕ) : Word w).val < L.base j
+ have pos := i.isLt
+ have fit := rep.1
+ rw [Fin.val_cast_of_lt (by omega)]
+ have hj := above j
+ omega
+
+end PairSimulation.LeafIncidentBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentTable.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentTable.lean
new file mode 100644
index 0000000000..057f5fb700
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafIncidentTable.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentMachine
+
+/-!
+# The fixed instruction image and virtual clock of the incident loader
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafIncidentMachine
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork RAMLayout
+
+variable {W D H w n : ℕ}
+
+/-- Standalone machine states, including the return location. -/
+abbrev PC := Option Stage
+
+/-- Numerical instruction address for an incident-loader label. -/
+noncomputable def rowPC (s : Stage) : Fin (Fintype.card PC) := Fintype.equivFin PC (some s)
+/-- Numerical address of the standalone accepting return. -/
+noncomputable def returnPC : Fin (Fintype.card PC) := Fintype.equivFin PC none
+
+/-- The same opcode image is instantiated at every host word width. -/
+noncomputable def template : Template (Fintype.card PC) 30 0 where
+ literalWidth := 5
+ entry := rowPC (.inl 0)
+ code i := match (Fintype.equivFin PC).symm i with
+ | some s => instruction rowPC (Function.Embedding.refl _) returnPC s
+ | none => .accept
+
+theorem template_linked (pub : Fin 0 → Word W) :
+ Linked (template.instantiate W pub) rowPC (Function.Embedding.refl _) returnPC := by
+ intro s
+ simpa only [Template.instantiate, template, rowPC, Equiv.symm_apply_apply] using
+ resize_instruction (k := 0) (W := W) rowPC (Function.Embedding.refl _) returnPC s
+
+/-- A numerical bound on the actual native instruction count that is
+independent of the four supplied half-wire strings. -/
+theorem ticks_le (v : Site D) (H w : ℕ) :
+ ticks v H w ≤ 80*w+6*D+53+layerCount D*(10*blockBits H w+14) := by
+ have ha (l : Layer D) : LeafSortFields.advanceTicks l ≤ 5 := by
+ unfold LeafSortFields.advanceTicks
+ split_ifs <;> decide
+ have sum : LeafSortFields.streamTicks D H w 0 (layerCount D) (by simp) ≤
+ layerCount D*(10*blockBits H w+14) := by
+ unfold LeafSortFields.streamTicks
+ rw [List.sum_ofFn]
+ calc
+ _ ≤ ∑ _ : Fin (layerCount D), (10*blockBits H w+14) :=
+ Finset.sum_le_sum fun i _ => by have := ha ((layerEquiv D).symm i); simpa only [Nat.zero_add] using
+ (Nat.add_le_add_left this (10*blockBits H w+9))
+ _ = _ := by simp
+ have := LeafSuccessorFields.ticks_le v w
+ unfold ticks LeafIncidentCore.ticks
+ omega
+
+/-- The loader occupies at most a fifth-power portion of the live private
+clock for the parameters of the virtual auxiliary processor. -/
+theorem ticks_le_of_budget {e : ℕ} (v : Site D) (bud : ProcessorBudget n D e w) (hn : 1024 ≤ n) :
+ ticks v (2^e) w ≤ n^5 := by
+ have hD : D+1 ≤ n := by have := bud.phase_le; omega
+ have lc : layerCount D ≤ n^2 := by
+ rw [layerCount,Nat.choose_two_right,pow_two]
+ exact (Nat.div_le_self ..).trans (Nat.mul_le_mul hD (by omega))
+ have hb : blockBits (2^e) w ≤ 40*n^2 := calc
+ _ ≤ 4*(2*n)*5*n := by unfold blockBits; gcongr <;> first | exact bud.word_le | exact bud.bucket_le
+ _ = _ := by ring
+ have n2 := Nat.one_le_pow 2 n (show 1 ≤ n by omega)
+ have p := Nat.mul_le_mul lc (show 10*blockBits (2^e) w+14 ≤ 414*n^2 by omega)
+ have hn4 : n ≤ n^4 := Nat.le_self_pow (by decide) n
+ have he : n^2*(414*n^2) = 414*n^4 := by ring
+ have hw := bud.word_le
+ have hd : D ≤ n := by omega
+ have final : 553*n^4 ≤ n^5 := by rw [pow_succ' n 4]; exact Nat.mul_le_mul_right _ (by omega)
+ have bound := ticks_le v (2^e) w
+ omega
+
+end PairSimulation.LeafIncidentMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafJobReadback.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafJobReadback.lean
new file mode 100644
index 0000000000..b079ef6fe8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafJobReadback.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.PairSimulationLeafPhysicalInput
+import OAI.Computability.VPVNP.PairSimulationLeafReadback
+import OAI.Computability.VPVNP.PairSimulationNominationAssembly
+
+/-!
+# Exact acceptance at the cursor leaves of the selected compression tree
+
+The numerical row address and private four-port buffer identify the leaf
+reader used in the compressor state. A successful DFS visit consumes its
+selected occurrence's word and returns the entire suffix. Conversely every
+successful visit comes from that site's occurrence type.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafHandler
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork RAMLayout Compression DFS
+open LocalHistory TraversalRows NodeArguments NetworkKernel CompressorRecords
+open scoped Fin.CommRing
+
+universe u
+
+private theorem castReader_suffix {α β : Type u} (h : α = β) (reader : ChoiceReader α)
+ (bits : List Bool) : (((h ▸ reader) : ChoiceReader β).read bits).map Prod.snd =
+ (reader.read bits).map Prod.snd := by
+ subst β
+ rfl
+
+/-- Transporting an occurrence to its compressor site only changes the
+dependent result type. The unread suffix is identical. -/
+theorem pushLeafReaders_suffix {N Y : Network} (I : N.Iso Y) (P : Factors Type N)
+ (read : ∀ u h, ChoiceReader (P u h)) (v : N.Site) (z : Y.Half (I.site v))
+ (bits : List Bool) :
+ ((pushLeafReaders I P read (I.site v) z).read bits).map Prod.snd =
+ ((read v (I.pullHalf v z)).read bits).map Prod.snd := by
+ rw [pushLeafReaders, Equiv.piCongrLeft_apply_apply]
+ exact castReader_suffix _ _ _
+
+variable {b l a p e w W endAddr : ℕ} [NeZero (b+l)] (hD : 1 < b+l) (hd : 2+p = 2^a)
+ {L : PrimedInputRAM.Lengths} {n ai H s : ℕ} {Q : PrimedInputRAM.Layout L n ai H w}
+ (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^(b+l)*2^e < 2^w)
+ {R : Type*} [CommRing R] {Label : Type} [Fintype Label] (f : Label → R)
+ (clock : ℕ) (bound : NominationClock D hw hc clock)
+ (storage : StackMachine.Layout (LeafStartup.Port 52 34) W)
+ (pub : LeafAddress.Field → Word W) (arena : Arena)
+ (trace : Word W → Scratch W endAddr → List (Event W))
+ (prepared : Word W → Scratch W endAddr → Scratch W endAddr)
+ (node : Word W) (saved : Scratch W endAddr) (cap : ℕ) (v : Position (b+l))
+ (z : (LeafArguments.state hD hd (2^e) w).network.Half (lanePositions (cursorCoordinateLabels b l) v))
+
+/-- The numerical row header and pending packet supplied to an actual leaf. -/
+structure StoredCursorRow : Prop where
+ width : b+l ≤ W
+ stride : (pub .stride).val = cap+2
+ radixB : (pub .radixB).val = 2^b
+ radixL : (pub .radixL).val = 2^l
+ address : node.val = (sitePointers cap (pub .base).val (siteOrder (LeafArguments.state hD hd (2^e) w))
+ (lanePositions (cursorCoordinateLabels b l) v)).1
+ fit : (cursorPacket hD hd node.val v z).Fits arena W endAddr
+ stored : (cursorPacket hD hd node.val v z).Stored arena saved
+
+variable (row : StoredCursorRow hD hd pub arena node saved cap v z)
+
+/-- The native leaf parser specialized to a node and four half-wire buffers decoded from the
+physical row and private argument arena. -/
+noncomputable abbrev cursorHook :=
+ parser D hw hc storage (physicalInput (b+l) e w pub arena trace prepared) clock
+
+/-- The selected nomination reader at the cursor site, specialized to its supplied half-wire
+assignment. -/
+noncomputable abbrev cursorSiteReader :=
+ (nominationSites D hw hc (cursorCoordinateLabels b l) hD hd f clock bound).read
+ (lanePositions (cursorCoordinateLabels b l) v) z
+
+include row in
+/-- This is the compressed occurrence reader on the genuine, ordered
+cursor state, evaluated on precisely the word stream seen by the physical hook. -/
+theorem cursorHook_suffix (bits : List Bool) :
+ ((cursorHook D hw hc clock storage pub arena trace prepared).read node saved bits).map Prod.snd =
+ ((cursorSiteReader hD hd D hw hc f clock bound v z).read bits).map Prod.snd := by
+ let I := LeafArguments.iso hD hd (2^e) w
+ let old := unpadHalf p v (I.pullHalf v z)
+ let input := physicalInput (b+l) e w pub arena trace prepared
+ have correct := physicalInput_correct hD hd pub arena trace prepared node saved cap v z
+ row.width row.stride row.radixB row.radixL row.address row.fit row.stored
+ have suffix := parser_nomination D hw hc storage input clock node saved bits v old
+ (congrArg Input.pos correct) (congrArg Input.buffers correct) (bound v old)
+ let P : Factors Type (paddedNetwork (b+l) p (ramFieldBits (2^e) w : RAMSystem (b+l) → ℕ)) :=
+ fun u y => initialChoices D.machine D.fuel 0 D.initial hw hc u (unpadHalf p u y)
+ exact suffix.trans (pushLeafReaders_suffix I P (fun u y =>
+ LeafStartup.nominationReader D hw hc u (unpadHalf p u y) clock (bound _ _)) v z bits).symm
+
+private theorem read_exists {α β : Type*} {native : Option (β × List Bool)} (reader : ChoiceReader α)
+ (bits tail : List Bool) (h : native.map Prod.snd = (reader.read bits).map Prod.snd) :
+ (∃ job, native = some (job,tail)) ↔ ∃ x, bits = reader.encode x ++ tail := by
+ constructor
+ · rintro ⟨job, hj⟩
+ rw [hj,Option.map_some] at h
+ obtain ⟨⟨x, suffix⟩, read, rfl⟩ := Option.map_eq_some_iff.mp h.symm
+ exact ⟨x, (reader.read_iff bits x suffix).mp read⟩
+ · rintro ⟨x, hx⟩
+ rw [(reader.read_iff bits x tail).mpr hx,Option.map_some] at h
+ obtain ⟨⟨job,suffix⟩, read, rfl⟩ := Option.map_eq_some_iff.mp h
+ exact ⟨job,read⟩
+
+include row in
+/-- On arbitrary private bits, a hook path with this exact unread suffix
+exists precisely when the selected site's reader has the corresponding prefix. -/
+theorem cursorHook_read_iff (bits tail : List Bool) :
+ (∃ job, (cursorHook D hw hc clock storage pub arena trace prepared).read node saved bits =
+ some (job,tail)) ↔ ∃ x, bits = (cursorSiteReader hD hd D hw hc f clock bound v z).encode x ++ tail :=
+ read_exists _ bits tail (cursorHook_suffix hD hd D hw hc f clock bound storage pub arena trace
+ prepared node saved cap v z row bits)
+
+include row in
+/-- In the one-node leaf preorder the successful native hook and the
+semantic leaf occurrence consume exactly the same private prefix. -/
+theorem cursorHook_preorder_iff (bits tail : List Bool) :
+ (∃ out, (cursorHook D hw hc clock storage pub arena trace prepared).decode [node] saved bits =
+ some (out,tail)) ↔ ∃ x, bits = (cursorSiteReader hD hd D hw hc f clock bound v z).encode x ++ tail := by
+ rw [← cursorHook_read_iff hD hd D hw hc f clock bound storage pub arena trace prepared node saved
+ cap v z row]
+ let hook := cursorHook D hw hc clock storage pub arena trace prepared
+ change (∃ out, hook.decode [node] saved bits = some (out,tail)) ↔ ∃ job, hook.read node saved bits = some (job,tail)
+ cases hr : hook.read node saved bits with
+ | none => simp [HookParser.decode, hr]
+ | some pair =>
+ obtain ⟨job,suffix⟩ := pair
+ simp [HookParser.decode, hr]
+
+end PairSimulation.LeafHandler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafLoadedBank.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafLoadedBank.lean
new file mode 100644
index 0000000000..96bf28cac1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafLoadedBank.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.PairSimulationLeafPortTable
+import OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+/-!
+# Exact private workspace after initializing a virtual validator
+
+The stack bank determines every word inside its occupied intervals.
+Outside them initialization preserves the old word, including stale cells
+from earlier leaves in the same private call. This determines the scratch
+state passed to the native stack interpreter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafLoadedBank
+
+open BurstRAM PrivateRAM PrimedInputRAM RAMTape StackMachine LeafStartup LeafRegisterBank
+
+variable {K : Type} {w : ℕ} (L : Layout K w) (s : Stacks K)
+
+/-- Addresses actually written for one occupied stack. -/
+def occupies (a : Word w) (j : K) := L.base j ≤ a.val ∧ a.val < L.base j + (s j).length
+
+open scoped Classical in
+/-- Look up the encoded bit occupying a private stack address, counting from the bottom of the
+stack. Return none for an unoccupied address. -/
+noncomputable def readCell (a : Word w) : Option (Word w) :=
+ if h : ∃ j, occupies L s a j then
+ let j := Classical.choose h
+ let hj := Classical.choose_spec h
+ let i := a.val - L.base j
+ have inside : i < (s j).reverse.length := by
+ change L.base j ≤ a.val ∧ a.val < L.base j + (s j).length at hj
+ simp only [List.length_reverse, i]; omega
+ some (encodeBit w (s j).reverse[i])
+ else none
+
+/-- Initialize occupied private stack cells with their encoded bits and retain the old memory
+at every other address. -/
+noncomputable def memory (old : Word w → Word w) (a : Word w) : Word w :=
+ (readCell L s a).getD (old a)
+
+theorem readCell_value (mem : Word w → Word w) (contents : L.Contents mem s)
+ (fit : ∀ j, (s j).length ≤ L.capacity) (a : Word w) (hwritten : ∃ j, occupies L s a j) :
+ readCell L s a = some (mem a) := by
+ classical
+ let j := Classical.choose hwritten
+ have hj : L.base j ≤ a.val ∧ a.val < L.base j+(s j).length := Classical.choose_spec hwritten
+ let i := a.val-L.base j
+ let ix := (s j).length-1-i
+ have hi : i < (s j).length := by dsimp [i]; omega
+ have hx : ix < (s j).length := by dsimp [ix]; omega
+ let tail := (s j).drop (ix+1)
+ have he : s j = (s j).take ix ++ (s j)[ix] :: tail := by
+ rw [show (s j)[ix] :: tail = (s j).drop ix from List.getElem_cons_drop hx,List.take_append_drop]
+ have htail : tail.length = i := by simp only [tail,List.length_drop,ix]; omega
+ have haddr : L.address j i = a := by
+ apply Fin.ext
+ rw [L.address_val _ (hi.le.trans (fit j))]
+ dsimp [i]; omega
+ have val := contents j _ _ _ he
+ rw [htail,haddr] at val
+ rw [readCell,dite_eq_left hwritten]
+ change some (encodeBit w ((s j).reverse[i]'(by simpa using hi))) = _
+ rw [List.getElem_reverse]
+ exact congrArg some val.symm
+
+/-- The exact updated memory follows from physical occupancy and the frame.
+The right side is a function of the old memory and the logical stack bank. -/
+theorem memory_eq (old new : Word w → Word w) (contents : L.Contents new s)
+ (fit : ∀ j, (s j).length ≤ L.capacity)
+ (frame : ∀ a, (∀ j, a.val < L.base j ∨ L.base j + (s j).length ≤ a.val) → new a = old a) :
+ new = memory L s old := by
+ funext a
+ by_cases h : ∃ j, occupies L s a j
+ · rw [memory,readCell_value L s new contents fit a h]; rfl
+ · rw [memory,readCell,dite_eq_right h]
+ exact frame a fun j => by have := not_exists.mp h j; unfold occupies at this; omega
+
+/-- Apply stack initialization to the saved DFS scratch by replacing its occupied cells with
+encoded stack bits. -/
+noncomputable def scratch {endAddr : ℕ} (saved : DFS.Scratch w endAddr) : DFS.Scratch w endAddr :=
+ fun a => (readCell L s a.val).getD (saved a)
+
+theorem scratch_memory (endAddr : ℕ) (old : Word w → Word w) :
+ DFS.scratch endAddr (memory L s old) = scratch L s (DFS.scratch endAddr old) := rfl
+
+section Site
+
+variable {d e k r : ℕ}
+
+/-- The leaf startup port that supplies the serialized incident data to the virtual site
+processor. -/
+def incidentPort (r k : ℕ) : LeafStartup.Port r k :=
+ SiteProcessorPorts.pub r (LeafStartup.expr k) ProcessorPublic.incidentPort
+
+/-- The finite source decoder designates precisely one incident port. -/
+theorem field_incident_iff (j : LeafStartup.Port r k) :
+ LeafStartup.field j = .incident ↔ j = incidentPort r k := by
+ constructor
+ · intro h
+ unfold LeafStartup.field at h
+ split at h <;> first | contradiction | rfl
+ · rintro rfl; rfl
+
+theorem install_incident (x : VirtualSite.Input d e w) (args : Fin k → Word w) :
+ Function.update (scalarBank (LeafStartup.field (r := r)) x args) (incidentPort r k)
+ (List.ofFn (RAMLayout.incidentBits x.sends x.v)) = LeafStartup.bank r x args := by
+ funext j
+ by_cases hj : j = incidentPort r k
+ · subst j; rw [Function.update_self]; rfl
+ · rw [Function.update_of_ne hj]
+ change fieldBits x args (scalarField (LeafStartup.field j)) = _
+ rw [scalarField,ite_eq_right (mt (field_incident_iff j).mp hj)]
+ rfl
+
+end Site
+end PairSimulation.LeafLoadedBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafNativeCount.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafNativeCount.lean
new file mode 100644
index 0000000000..748f87c359
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafNativeCount.lean
@@ -0,0 +1,247 @@
+import OAI.Computability.VPVNP.PairSimulationLeafCount
+import OAI.Computability.VPVNP.PairSimulationStackNativeCalls
+import OAI.Computability.VPVNP.PairSimulationHistory
+
+/-!
+# Native stack nominations at cursor leaves
+
+The virtual validator first nominates a finite private stream, then checks
+it. The binary instructions of this nomination program have their own
+complete words. The reader below consumes those actual instruction choices.
+At a leaf each accepted occurrence has exponent zero, so a bijection of
+finite choices transports its contribution to the original cursor factor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open RAMTape CompressorRecords
+
+variable {K Q : Type*} [DecidableEq K]
+
+private theorem consumed {code : StackCode K Q} {fuel : ℕ} {q : Q} {s : Stacks K}
+ {bits rest : List Bool} (h : acceptPrefix code fuel q s bits = some rest) :
+ acceptPrefix code fuel q s (bits.take (bits.length - rest.length)) = some [] ∧
+ bits = bits.take (bits.length - rest.length) ++ rest := by
+ obtain ⟨pre, hpre, rfl⟩ := (acceptPrefix_iff ..).mp h
+ simp only [List.length_append, Nat.add_sub_cancel, List.take_left]
+ exact ⟨(acceptPrefix_iff ..).mpr ⟨pre, hpre, (List.append_nil _).symm⟩, trivial⟩
+
+/-- Parse the actual stack nomination bits and return the exact consumed
+word as the occurrence, keeping the unconsumed suffix for the next leaf. -/
+def completeReader (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K) :
+ ChoiceReader (CompleteStreams code fuel q s) where
+ encode x := x.val
+ read bits :=
+ match h : acceptPrefix code fuel q s bits with
+ | none => none
+ | some rest => some (⟨bits.take (bits.length - rest.length), (consumed h).1⟩, rest)
+ read_iff bits x tail := by
+ constructor
+ · intro h
+ split at h
+ · contradiction
+ · rename_i rest hr
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj h)
+ exact (consumed hr).2
+ · intro h
+ have mem : x.val ∈ acceptedWords code fuel q s := by
+ simpa [acceptPrefix_iff] using x.prop
+ have read := (acceptPrefix_iff code fuel q s bits tail).mpr ⟨x.val, mem, h⟩
+ split
+ · rename_i fail
+ rw [read] at fail
+ contradiction
+ · rename_i rest hit
+ obtain rfl := Option.some.inj (hit.symm.trans read)
+ apply congrArg some
+ refine Prod.ext ?_ rfl
+ apply Subtype.ext
+ change bits.take (bits.length - rest.length) = x.val
+ simp [h]
+
+/-- Projecting away the occurrence recovers the stack interpreter's
+actual remaining input. -/
+theorem completeReader_suffix (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K)
+ (bits : List Bool) :
+ ((completeReader code fuel q s).read bits).map Prod.snd = acceptPrefix code fuel q s bits := by
+ unfold completeReader
+ dsimp only
+ split <;> simp_all
+
+private theorem reindex_suffix {α β : Type*} (C : ChoiceReader α) (e : α ≃ β) (bits : List Bool) :
+ ((C.reindex e).read bits).map Prod.snd = (C.read bits).map Prod.snd := by
+ cases h : C.read bits <;> simp [ChoiceReader.reindex, h]
+
+theorem completeReader_length_lt (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K)
+ (x : CompleteStreams code fuel q s) : ((completeReader code fuel q s).encode x).length < fuel := by
+ have step {t : ℕ} {q : Q} {s : Stacks K} {bits : List Bool} {y : Exit K Q}
+ (h : parse code t q s bits = some y) : bits.length + y.unused < y.rest.length + t := by
+ induction t generalizing q s bits with
+ | zero => simp [parse] at h
+ | succ t ih =>
+ cases op : code q with
+ | push | pop | goto =>
+ have := ih (by simpa only [parse, op] using h)
+ omega
+ | choose low high =>
+ cases bits with
+ | nil => simp [parse, op] at h
+ | cons b bits =>
+ have := ih (by simpa only [parse, op] using h)
+ simp only [List.length_cons]
+ omega
+ | halt status =>
+ simp only [parse, op, Option.some.injEq] at h
+ subst y
+ dsimp only
+ omega
+ have ok := x.prop
+ unfold acceptPrefix haltPrefix at ok
+ split at ok
+ · contradiction
+ · rename_i y hy
+ have bound := step hy
+ split at ok
+ · simp only [Option.some.injEq] at ok
+ rw [ok, List.length_nil, Nat.zero_add] at bound
+ change x.val.length < fuel
+ omega
+ · contradiction
+
+end PairSimulation.StackMachine
+
+namespace PairSimulation.LeafStartup
+
+open BurstRAM BurstRAM.PrivateRAM RAMTape CursorNetwork CursorRouting CompressorRecords
+open StackMachine
+
+set_option synthInstance.maxSize 10000
+
+/-- The validator has direct accepting/rejecting halts. A normal fall-through
+of this closed stack program rejects. -/
+def auxiliaryProcessor : FiniteRoutine (Port 52 34) := processor 52 PrimedCounter.Program.table
+
+/-- The closed stack program for the auxiliary validator, with rejection on ordinary
+fall-through. -/
+def auxiliaryCode : StackCode (Port 52 34) (Option auxiliaryProcessor.State) :=
+ auxiliaryProcessor.body.close false
+
+/-- The initial control state of the closed auxiliary stack program. -/
+def auxiliaryEntry : Option auxiliaryProcessor.State := some auxiliaryProcessor.body.entry
+
+variable {w d e : ℕ} [NeZero d] {L : PrimedInputRAM.Lengths} {n a H s : ℕ}
+ {Q : PrimedInputRAM.Layout L n a H w} (D : PrimedCounter.Data Q s)
+ (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w)
+ (v : Position d) (buf : Buffers d (2 ^ e) w)
+
+/-- The auxiliary validator's initial stacks built from the cursor position, four supplied
+buffers, and primed counter's public operands. -/
+noncomputable abbrev auxiliaryBank := bank 52 (auxiliary D hw hc v buf) D.pub
+
+theorem auxiliary_closed (hz : v.1 = 0) (routed : routeAccept (2 ^ e) w v (readBuffer buf) = true)
+ (t : ℕ) (bound : steps 52 (auxiliary D hw hc v buf) ≤ t) :
+ stackPaths auxiliaryCode t auxiliaryEntry (auxiliaryBank D hw hc v buf) =
+ Nat.card {bs : List Bool // initialAccept D.machine D.fuel 0 (D.initial v.2) hw hc v buf bs = true} ∧
+ StopsWithin auxiliaryCode t auxiliaryEntry (auxiliaryBank D hw hc v buf) := by
+ have spec := auxiliary_count D hw hc v buf hz routed t bound
+ exact ⟨(Routine.stackPaths_close auxiliaryProcessor.body false t auxiliaryEntry _).trans (spec.1 _),
+ (Routine.stopsWithin_close_iff auxiliaryProcessor.body false t auxiliaryEntry _).mpr (spec.2 _)⟩
+
+variable {W p r k : ℕ} {M : Machine W p r k} {pc : Option auxiliaryProcessor.State → Fin 7 → Fin p}
+ {reg : StackMachine.Register (Port 52 34) ↪ Fin r} {done : Fin p} {storage : StackMachine.Layout (Port 52 34) W}
+
+/-- Execution on the actual bank built from the auxiliary public operands
+and four independent half-wire buffers. Every true halt goes to the
+linked native continuation with its suffix and framed private memory. -/
+theorem auxiliary_native (hz : v.1 = 0) (routed : routeAccept (2 ^ e) w v (readBuffer buf) = true)
+ (t : ℕ) (bound : steps 52 (auxiliary D hw hc v buf) ≤ t)
+ (linked : StackMachine.Linked M auxiliaryCode pc reg done) (hW : 0 < W)
+ (fit : ∀ j, (auxiliaryBank D hw hc v buf j).length + t ≤ storage.capacity)
+ (c : Config W p r) (atPC : c.pc = pc auxiliaryEntry 0)
+ (rep : Represents storage reg c (auxiliaryBank D hw hc v buf))
+ (extra : ℕ) (m : Memory W) (bits : List Bool) :
+ NativeCall M storage reg done extra (4 * t) c m bits
+ (parse auxiliaryCode t auxiliaryEntry (auxiliaryBank D hw hc v buf) bits) := by
+ have stops := (auxiliary_closed D hw hc v buf hz routed t bound).2
+ exact parse_native linked hW (fun _ _ path j => reachable_capacity stops fit path j) t extra (.inr stops) c atPC rep m bits
+
+/-- The instantiated, accepting native burst counts exactly the choices
+of the original cursor on these supplied buffers. -/
+theorem auxiliary_native_card (hz : v.1 = 0) (routed : routeAccept (2 ^ e) w v (readBuffer buf) = true)
+ (t : ℕ) (bound : steps 52 (auxiliary D hw hc v buf) ≤ t)
+ (linked : StackMachine.Linked M auxiliaryCode pc reg done) (close : M.code done = .accept) (hW : 0 < W)
+ (fit : ∀ j, (auxiliaryBank D hw hc v buf j).length + t ≤ storage.capacity)
+ (c : Config W p r) (atPC : c.pc = pc auxiliaryEntry 0)
+ (rep : Represents storage reg c (auxiliaryBank D hw hc v buf)) (extra : ℕ) (m : Memory W) :
+ Nat.card {bs : List Bool // (execute M.program (extra + 4 * t) c m bs).isSome = true} =
+ Nat.card {bs : List Bool // initialAccept D.machine D.fuel 0 (D.initial v.2) hw hc v buf bs = true} := by
+ obtain ⟨count, stops⟩ := auxiliary_closed D hw hc v buf hz routed t bound
+ exact (nativeStreams_card linked close hW (fun _ _ path j => reachable_capacity stops fit path j) t extra
+ (.inr stops) c atPC rep m).trans count
+
+variable (z : (validatorNetwork d e w).Half v)
+
+/-- Occurrences at a leaf carry zero exponent. A finite bijection transfers
+the validated stack nomination multiplicity to the initial cursor factor. -/
+noncomputable def nominationEquiv (hz : v.1 = 0)
+ (routed : routeAccept (2 ^ e) w v (readBuffer (halfBuffers v z)) = true) (t : ℕ)
+ (bound : steps 52 (auxiliary D hw hc v (halfBuffers v z)) ≤ t) :
+ CompleteStreams auxiliaryCode t auxiliaryEntry (auxiliaryBank D hw hc v (halfBuffers v z)) ≃
+ initialChoices D.machine D.fuel 0 D.initial hw hc v z := by
+ apply Fintype.equivOfCardEq
+ rw [completeStreams_card, ← Nat.card_eq_fintype_card]
+ exact (auxiliary_closed D hw hc v (halfBuffers v z) hz routed t bound).1.trans
+ (Nat.card_congr (initialAcceptEquiv D.machine D.fuel 0 D.initial hw hc v z))
+
+/-- At cursor zero read the actual stack program's choices. A valid transit
+site uses the empty word and a failed routing test rejects before nomination. -/
+noncomputable def nominationReader (t : ℕ) (bound : steps 52 (auxiliary D hw hc v (halfBuffers v z)) ≤ t) :
+ ChoiceReader (initialChoices D.machine D.fuel 0 D.initial hw hc v z) :=
+ if h : v.1 = 0 ∧ routeAccept (2 ^ e) w v (readBuffer (halfBuffers v z)) = true then
+ (completeReader auxiliaryCode t auxiliaryEntry (auxiliaryBank D hw hc v (halfBuffers v z))).reindex
+ (nominationEquiv D hw hc v z h.1 h.2 t bound)
+ else LocalHistory.initialReader D.machine D.fuel 0 hw hc D.initial v z
+
+/-- On every local input the reader returns exactly the suffix left by the
+native nomination parser, the deterministic transit, or the failed guard. -/
+theorem nominationReader_suffix (t : ℕ)
+ (bound : steps 52 (auxiliary D hw hc v (halfBuffers v z)) ≤ t) (bits : List Bool) :
+ ((nominationReader D hw hc v z t bound).read bits).map Prod.snd =
+ if routeAccept (2 ^ e) w v (readBuffer (halfBuffers v z)) then
+ if v.1 = 0 then
+ acceptPrefix auxiliaryCode t auxiliaryEntry (auxiliaryBank D hw hc v (halfBuffers v z)) bits
+ else some bits
+ else none := by
+ unfold nominationReader
+ by_cases route : routeAccept (2 ^ e) w v (readBuffer (halfBuffers v z)) = true
+ · by_cases zero : v.1 = 0
+ · simp only [route, zero, and_self, ↓reduceDIte, ↓reduceIte, StackMachine.reindex_suffix,
+ completeReader_suffix]
+ · simp only [route, zero, false_and, ↓reduceDIte, ↓reduceIte, LocalHistory.initialReader,
+ StackMachine.reindex_suffix, LocalHistory.bufferReader, ChoiceReader.single, Option.map_some]
+ · simp only [route, Bool.false_eq_true, and_false, ↓reduceDIte, ↓reduceIte, LocalHistory.initialReader,
+ StackMachine.reindex_suffix, LocalHistory.bufferReader, Option.map_none]
+
+theorem nominationReader_length_le (t : ℕ) (bound : steps 52 (auxiliary D hw hc v (halfBuffers v z)) ≤ t)
+ (x : initialChoices D.machine D.fuel 0 D.initial hw hc v z) :
+ ((nominationReader D hw hc v z t bound).encode x).length ≤ t := by
+ unfold nominationReader
+ split
+ · exact (completeReader_length_lt _ _ _ _ _).le
+ · unfold LocalHistory.initialReader ChoiceReader.reindex
+ dsimp only
+ apply (LocalHistory.bufferReader_length_le D.machine D.fuel 0 hw hc (D.initial v.2) v (halfBuffers v z) _).trans
+ apply Nat.le_trans _ bound
+ unfold steps choiceBound
+ change 2 * 2^e * (D.fuel + w) ≤ _ + (4 * (2 * 2^e * (D.fuel + w)) + 1) + 3 + _
+ omega
+
+end PairSimulation.LeafStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafPhysicalInput.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafPhysicalInput.lean
new file mode 100644
index 0000000000..99ff9c73b8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafPhysicalInput.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.PairSimulationLeafHandler
+import OAI.Computability.VPVNP.PairSimulationLeafAddress
+import OAI.Computability.VPVNP.PairSimulationLeafArguments
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentLoad
+import OAI.Computability.VPVNP.PairPendingArguments
+
+/-!
+# Reading a cursor leaf from the physical DFS arguments
+
+The host decodes its current row pointer with the public row stride and
+radices. Its private argument arena contains four consecutive bit vectors.
+On a stored cursor packet these operations recover the typed position and
+all four half-wires, including independently assigned incoming wires.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafHandler
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork RAMLayout Compression DFS
+open LocalHistory TraversalRows NodeArguments
+open scoped Fin.CommRing
+
+variable {d W endAddr : ℕ}
+
+/-- Decode the descriptor row using the same operands as the native address reader. -/
+def physicalPosition (d : ℕ) [NeZero d] (pub : LeafAddress.Field → Word W)
+ (node : Word W) : Position d :=
+ let coord := LeafAddress.decode node (pub .base) (pub .stride) (pub .radixB) (pub .radixL)
+ (Fin.ofNat d coord.1.val, Fin.ofNat (2^d) coord.2.val)
+
+/-- The four bases passed to the incident-field mover, in native slot order. -/
+def portBase (arena : Arena) (node width : ℕ) : LocalPort → ℕ
+ | .outgoing side => arena.base node + LeafArguments.portNumber false side * width
+ | .incoming side => arena.base node + LeafArguments.portNumber true side * width
+
+/-- Read the single private word occupied by each argument bit. -/
+def physicalBuffers (d H w : ℕ) (arena : Arena) (node : Word W)
+ (saved : Scratch W endAddr) : Buffers d H w :=
+ fun port i => decide ((rawScratch saved ((portBase arena node.val (ramPayloadWidth d H w) port +
+ i.val : ℕ) : Word W)).val ≠ 0)
+
+/-- The deterministic prefix supplies its trace and resulting scratch.
+The input position and buffer bits are projections of its actual operands. -/
+def physicalInput (d e w : ℕ) [NeZero d] (pub : LeafAddress.Field → Word W)
+ (arena : Arena) (trace : Word W → Scratch W endAddr → List (Event W))
+ (prepared : Word W → Scratch W endAddr → Scratch W endAddr)
+ (node : Word W) (saved : Scratch W endAddr) : Input d e w W endAddr :=
+ ⟨physicalPosition d pub node, physicalBuffers d (2^e) w arena node saved,
+ trace node saved, prepared node saved⟩
+
+variable {b l a p H w : ℕ} [NeZero (b+l)] (hD : 1 < b+l) (hd : 2+p = 2^a)
+
+/-- The pending half-wire packet for this site, with its numerical row address. -/
+noncomputable def cursorPacket (node : ℕ) (v : Position (b+l))
+ (z : (LeafArguments.state hD hd H w).network.Half (lanePositions (cursorCoordinateLabels b l) v)) :
+ Packet :=
+ ⟨node, packed (LeafArguments.state hD hd H w) _ z⟩
+
+theorem physicalPosition_eq (pub : LeafAddress.Field → Word W) (node : Word W)
+ (cap : ℕ) (v : Position (b+l)) (hwidth : b+l ≤ W)
+ (hs : (pub .stride).val = cap+2) (hb : (pub .radixB).val = 2^b)
+ (hl : (pub .radixL).val = 2^l)
+ (hn : node.val = (sitePointers cap (pub .base).val (siteOrder (LeafArguments.state hD hd H w))
+ (lanePositions (cursorCoordinateLabels b l) v)).1) :
+ physicalPosition (b+l) pub node = v := by
+ obtain ⟨hc, ha⟩ := LeafAddress.decode_leaf_row hD hd (ramFieldBits H w : RAMSystem (b+l) → ℕ)
+ cap v node (pub .base) (pub .stride) (pub .radixB) (pub .radixL) hwidth hs hb hl hn
+ apply Prod.ext <;> apply Fin.ext
+ · change _ % (b+l) = v.1.val
+ rw [hc, Nat.mod_eq_of_lt v.1.isLt]
+ · change _ % (2^(b+l)) = v.2.val
+ rw [ha, Nat.mod_eq_of_lt v.2.isLt]
+
+private theorem storedPort (arena : Arena) (node : Word W) (saved : Scratch W endAddr)
+ (v : Position (b+l))
+ (z : (LeafArguments.state hD hd H w).network.Half (lanePositions (cursorCoordinateLabels b l) v))
+ (fits : (cursorPacket hD hd node.val v z).Fits arena W endAddr)
+ (stored : (cursorPacket hD hd node.val v z).Stored arena saved) (dir side : Bool)
+ (i : Fin (ramPayloadWidth (b+l) H w)) :
+ rawScratch saved ((arena.base node.val + LeafArguments.portNumber dir side *
+ ramPayloadWidth (b+l) H w + i.val : ℕ) : Word W) =
+ PrivateFields.bitValue W (LeafArguments.buffers hD hd v z (LeafArguments.port dir side) i) := by
+ let q := cursorPacket hD hd node.val v z
+ let width := ramPayloadWidth (b+l) H w
+ have len : q.bits.length = 4 * width := LeafArguments.packed_length_four hD hd _ z
+ have hi : LeafArguments.portNumber dir side * width + i.val < q.bits.length := by
+ rw [len]
+ have lt : i.val < width := i.isLt
+ cases dir <;> cases side <;> simp [LeafArguments.portNumber] <;> omega
+ let j : Fin q.bits.length := ⟨_, hi⟩
+ have hold := stored j
+ have write := PrivateFields.storeBits_read (arena.base node.val) q.bits (rawScratch saved) fits.2.2 j
+ have physical := LeafArguments.read_port hD hd arena node.val v z (rawScratch saved)
+ (len ▸ fits.2.2) dir side i
+ change rawScratch saved ((arena.base node.val + LeafArguments.portNumber dir side * width + i.val : ℕ) : Word W) = _
+ rw [Nat.add_assoc] at physical ⊢
+ exact hold.trans (write.symm.trans physical)
+
+/-- The resident packet satisfies the exact memory precondition of the native
+incident-field loader on each of its four ports. -/
+theorem physicalStored (arena : Arena) (node : Word W) (saved : Scratch W endAddr)
+ (v : Position (b+l))
+ (z : (LeafArguments.state hD hd H w).network.Half (lanePositions (cursorCoordinateLabels b l) v))
+ (fits : (cursorPacket hD hd node.val v z).Fits arena W endAddr)
+ (stored : (cursorPacket hD hd node.val v z).Stored arena saved) :
+ LeafIncidentLoad.Stored (portBase arena node.val (ramPayloadWidth (b+l) H w))
+ (LeafArguments.buffers hD hd v z) (rawScratch saved) := by
+ intro port i
+ cases port with
+ | outgoing side => exact storedPort hD hd arena node saved v z fits stored false side i
+ | incoming side => exact storedPort hD hd arena node saved v z fits stored true side i
+
+/-- Reading the private four-port bank yields the semantic half-wire bits. -/
+theorem physicalBuffers_eq (arena : Arena) (node : Word W) (saved : Scratch W endAddr)
+ (v : Position (b+l))
+ (z : (LeafArguments.state hD hd H w).network.Half (lanePositions (cursorCoordinateLabels b l) v))
+ (hW : 0 < W) (fits : (cursorPacket hD hd node.val v z).Fits arena W endAddr)
+ (stored : (cursorPacket hD hd node.val v z).Stored arena saved) :
+ physicalBuffers (b+l) H w arena node saved = LeafArguments.buffers hD hd v z := by
+ funext port i
+ have h := physicalStored hD hd arena node saved v z fits stored port i
+ change decide ((rawScratch saved (LeafFieldCopy.word W (_ + i.val))).val ≠ 0) = _
+ rw [h]
+ have one : 1 < 2^W := Nat.one_lt_two_pow hW.ne'
+ cases LeafArguments.buffers hD hd v z port i <;>
+ simp [PrivateFields.bitValue, Nat.mod_eq_of_lt one]
+
+/-- The physical handler input recovers the semantic cursor site and its
+independent buffers on each fitted, stored leaf of the DFS. -/
+theorem physicalInput_correct {e : ℕ} (pub : LeafAddress.Field → Word W) (arena : Arena)
+ (trace : Word W → Scratch W endAddr → List (Event W))
+ (prepared : Word W → Scratch W endAddr → Scratch W endAddr)
+ (node : Word W) (saved : Scratch W endAddr) (cap : ℕ) (v : Position (b+l))
+ (z : (LeafArguments.state hD hd (2^e) w).network.Half (lanePositions (cursorCoordinateLabels b l) v))
+ (hwidth : b+l ≤ W) (hs : (pub .stride).val = cap+2)
+ (hb : (pub .radixB).val = 2^b) (hl : (pub .radixL).val = 2^l)
+ (hn : node.val = (sitePointers cap (pub .base).val (siteOrder (LeafArguments.state hD hd (2^e) w))
+ (lanePositions (cursorCoordinateLabels b l) v)).1)
+ (fits : (cursorPacket hD hd node.val v z).Fits arena W endAddr)
+ (stored : (cursorPacket hD hd node.val v z).Stored arena saved) :
+ physicalInput (b+l) e w pub arena trace prepared node saved =
+ ⟨v, LeafArguments.buffers hD hd v z, trace node saved, prepared node saved⟩ := by
+ unfold physicalInput
+ rw [physicalPosition_eq hD hd pub node cap v hwidth hs hb hl hn,
+ physicalBuffers_eq hD hd arena node saved v z (by omega) fits stored]
+
+end PairSimulation.LeafHandler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafPlacement.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafPlacement.lean
new file mode 100644
index 0000000000..e89719bbbf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafPlacement.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.PairSimulationLeafGeometryLoad
+import OAI.Computability.VPVNP.PairVertexImage
+
+/-! # Allocating the leaf role inside the final vertex instruction image -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRole
+
+open BurstRAM PrivateRAM LeafRegisterBank
+
+set_option synthInstance.maxSize 10000
+
+/-- Labels of the cursor-leaf segment, covering both the private geometry loader and the
+verifier body. -/
+abbrev Label := LeafGeometryLoad.Label ⊕ LeafImage.Label
+
+/-- Only the nine common DFS registers are external to this allocation. -/
+inductive Private where
+ | cursor
+ | operand (i : Source 6)
+ | address (i : {j : LeafAddress.Reg // j ≠ .node})
+ | route (i : Fin 32)
+ | boot (i : LeafBoot.Reg)
+
+noncomputable instance : Fintype Private := by classical exact derive_fintype% _
+
+/-- Number of instruction rows reserved for the leaf geometry loader and verifier body
+together. -/
+noncomputable def labelCount := Fintype.card Label
+/-- Number of leaf-local register names to reserve in the enclosing vertex image. -/
+noncomputable def privateCount := Fintype.card Private
+
+/-- Number the loader and body labels for placement in the leaf segment of the vertex
+instruction table. -/
+noncomputable def labelIndex : Label ≃ Fin labelCount := Fintype.equivFin _
+/-- Number the leaf-local registers for allocation in the vertex's register bank. -/
+noncomputable def privateIndex : Private ≃ Fin privateCount := Fintype.equivFin _
+
+variable {p r : ℕ}
+variable (pc : Label → Fin p) (dfs : Fin 9 ↪ Fin r) (priv : Private ↪ Fin r)
+
+/-- Every shared DFS register has a physical index distinct from every leaf-local register. -/
+def Apart := ∀ i j, dfs i ≠ priv j
+
+/-- Assign a leaf body register to the shared DFS bank or to the private address, routing or
+startup bank according to its name. -/
+def place : LeafImage.Reg → Fin r
+ | .dfs i => dfs i
+ | .address i => priv (.address i)
+ | .route i => priv (.route i)
+ | .boot i => priv (.boot i)
+
+private theorem place_injective (apart : Apart dfs priv) : Function.Injective (place dfs priv) := by
+ intro i j h
+ cases i <;> cases j <;> simp only [place,dfs.injective.eq_iff,priv.injective.eq_iff] at h
+ all_goals first | contradiction | cases h; rfl | exact (apart _ _ h).elim | exact (apart _ _ h.symm).elim
+
+/-- The injective placement of all verifier body registers, using disjoint DFS and leaf-local
+register banks. -/
+def bodyReg (apart : Apart dfs priv) : LeafImage.Reg ↪ Fin r := ⟨place dfs priv,place_injective dfs priv apart⟩
+
+/-- Embed the geometry loader's source registers in the leaf-local operand bank. -/
+def ports : Source 6 ↪ Fin r := ⟨fun i => priv (.operand i),fun _ _ h => Private.operand.inj (priv.injective h)⟩
+
+/-- The ten physical registers receiving the geometry words used as operands by the verifier
+body. -/
+def values := LeafGeometryLoad.bank (ports priv)
+
+/-- Place a private geometry-load instruction at its label in the combined leaf segment. -/
+def loadPC := pc ∘ Sum.inl
+/-- Place a verifier body instruction at its label in the combined leaf segment. -/
+def bodyPC := pc ∘ Sum.inr
+
+theorem dfs_body (apart : Apart dfs priv) : LeafImage.dfsReg (bodyReg dfs priv apart) = dfs := rfl
+
+theorem value_outside (apart : Apart dfs priv) (i : Fin 10) : values priv i ∉ Set.range (bodyReg dfs priv apart) := by
+ rintro ⟨j,h⟩
+ cases j with
+ | dfs j => exact apart j _ h
+ | address j | route j | boot j =>
+ have e := priv.injective h
+ cases e
+
+end PairSimulation.LeafRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafPointers.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafPointers.lean
new file mode 100644
index 0000000000..ca8328f2b4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafPointers.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.PairSimulationLeafScalarLoad
+
+/-!
+# Allocating the auxiliary validator's private stack ports
+
+The loop is unrolled only over the fixed set of machine ports. Each port
+receives two equal pointers at its empty interval. Existing cells may hold
+arbitrary values. The capacity and first address come from the enclosing
+call's registers, so the instruction table is independent of the input length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafPointers
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord RAMTape StackMachine
+open scoped Fin.CommRing
+
+variable {K : Type} {N w p r k : ℕ}
+
+/-- The validator's stack registers together with the allocation cursor and per-stack address
+stride. -/
+inductive Reg (K : Type) where
+ | stack (j : Register K) | cursor | stride
+ deriving DecidableEq, Fintype
+
+/-- Physical embedding of the stack registers inside the pointer allocator's register bank. -/
+def stack (reg : Reg K ↪ Fin r) : Register K ↪ Fin r :=
+ ⟨fun i => reg (.stack i),fun _ _ h => Reg.stack.inj (reg.injective h)⟩
+
+@[simp] theorem stack_apply (reg : Reg K ↪ Fin r) (j : Register K) :
+ stack reg j = reg (.stack j) := rfl
+
+/-- The final two rows initialize the permanent zero and unit operands. -/
+def finish (pc : Fin 2 → Fin p) (reg : Reg K ↪ Fin r) (done : Fin p) : Fin 2 → Instr w p r k :=
+ ![.constant (reg (.stack .zero)) 0 (pc 1), .constant (reg (.stack .one)) 1 done]
+
+/-- Three instructions set a port's base and top to the current cursor, then advance the cursor
+by one stack stride. -/
+def allocate (a : K) (pc : Fin 3 → Fin p) (reg : Reg K ↪ Fin r) (next : Fin p) :
+ Fin 3 → Instr w p r k :=
+ ![.copy (reg (.stack (.base a))) (reg .cursor) (pc 1),
+ .copy (reg (.stack (.top a))) (reg .cursor) (pc 2),
+ .binary .add (reg .cursor) (reg .cursor) (reg .stride) next]
+
+theorem resize_allocate (a : K) (pc : Fin 3 → Fin p) (reg : Reg K ↪ Fin r) (next : Fin p)
+ (i : Fin 3) : (allocate (w := 1) (k := k) a pc reg next i).resize w = allocate a pc reg next i := by
+ fin_cases i <;> rfl
+
+theorem resize_finish (pc : Fin 2 → Fin p) (reg : Reg K ↪ Fin r) (done : Fin p) (i : Fin 2) :
+ (finish (w := 1) (k := k) pc reg done i).resize w = finish pc reg done i := by fin_cases i <;> rfl
+
+variable (M : Machine w p r k) (reg : Reg K ↪ Fin r)
+
+/-- Continue at the first allocation instruction of the next port, or at the end label once the
+list is empty. -/
+def next (todo : List K) (pc : K → Fin 3 → Fin p) (endPC : Fin p) : Fin p :=
+ todo.head?.elim endPC (fun a => pc a 0)
+
+/-- The host code allocates each port in the given order and links the last allocation to the
+specified end label. -/
+def Rows (pc : K → Fin 3 → Fin p) (endPC : Fin p) : List K → Prop
+ | [] => True
+ | a::as => (∀ i, M.code (pc a i) = allocate a (pc a) reg (next as pc endPC) i) ∧ Rows pc endPC as
+
+private theorem walk (pc : K → Fin 3 → Fin p) (endPC : Fin p) (todo : List K)
+ (hl : Rows M reg pc endPC todo) (hn : todo.Nodup) (base stride : ℕ) (c : Config w p r)
+ (hc : c.pc = next todo pc endPC) (hbase : c.reg (reg .cursor) = (base : Word w))
+ (hstride : c.reg (reg .stride) = (stride : Word w)) :
+ ∃ out, Prefix M c (List.replicate (3*todo.length) .tick) out ∧ out.pc = endPC ∧
+ (∀ j : Fin todo.length, let a := todo[j.val]
+ out.reg (reg (.stack (.base a))) = ((base+j.val*stride : ℕ) : Word w) ∧
+ out.reg (reg (.stack (.top a))) = ((base+j.val*stride : ℕ) : Word w)) ∧
+ (∀ i, i ≠ reg .cursor → (∀ a ∈ todo, i ≠ reg (.stack (.base a)) ∧ i ≠ reg (.stack (.top a))) →
+ out.reg i = c.reg i) ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ induction todo generalizing base c with
+ | nil => exact ⟨c,.nil _,hc,fun i => i.elim0,fun _ _ _ => rfl,rfl,rfl⟩
+ | cons a as ih =>
+ have hrows := hl.1
+ have hnodup := List.nodup_cons.mp hn
+ let ptr := (base : Word w)
+ let c₁ := c.put (pc a 1) (reg (.stack (.base a))) ptr
+ let c₂ := c₁.put (pc a 2) (reg (.stack (.top a))) ptr
+ let mid := c₂.put (next as pc endPC) (reg .cursor) ((base+stride : ℕ) : Word w)
+ have st₀ : M.program.step c = .localStep c₁ := by
+ change (M.code c.pc).run _ _ = _
+ rw [hc,show next (a::as) pc endPC = pc a 0 from rfl,hrows 0]; simp [allocate,Instr.run,c₁,ptr,hbase]
+ have st₁ : M.program.step c₁ = .localStep c₂ := by
+ change (M.code (pc a 1)).run _ c₁ = _
+ rw [hrows 1]; simp [allocate,Instr.run,c₂,c₁,Config.put,hbase,ptr]
+ have st₂ : M.program.step c₂ = .localStep mid := by
+ change (M.code (pc a 2)).run _ c₂ = _
+ rw [hrows 2]; simp [allocate,Instr.run,mid,c₂,c₁,Config.put,BinaryOp.eval,hbase,hstride]
+ have head : Prefix M c (List.replicate 3 .tick) mid := .tick st₀ (.tick st₁ (.tick st₂ (.nil _)))
+ obtain ⟨out,run,hd,values,frame,mem,state⟩ := ih hl.2 hnodup.2 (base+stride) mid rfl
+ (by simp [mid,Config.put]) (by simp [mid,c₂,c₁,Config.put,hstride])
+ have all := head.append run
+ rw [← List.replicate_add,show 3+3*as.length=3*(a::as).length by simp; omega] at all
+ refine ⟨out,all,hd,?_,?_,mem,state⟩
+ · intro j
+ induction j using Fin.cases with
+ | zero =>
+ change out.reg (reg (.stack (.base a))) = _ ∧ out.reg (reg (.stack (.top a))) = _
+ constructor
+ · rw [frame _ (by simp) (fun b hb => by have hn := ne_of_mem_of_not_mem hb hnodup.1; simp [Ne.symm hn])]
+ simp [mid,c₂,c₁,ptr,Config.put]
+ · rw [frame _ (by simp) (fun b hb => by have hn := ne_of_mem_of_not_mem hb hnodup.1; simp [Ne.symm hn])]
+ simp [mid,c₂,c₁,ptr,Config.put]
+ | succ j =>
+ simpa [Nat.succ_mul,Nat.add_assoc,Nat.add_left_comm,Nat.add_comm] using values j
+ · intro i hi ha
+ have hhead := ha a (List.mem_cons_self ..)
+ rw [frame _ hi (fun b hb => ha b (List.mem_cons_of_mem _ hb))]
+ simp [mid,c₂,c₁,Config.put,Function.update_of_ne hi,Function.update_of_ne hhead.1,
+ Function.update_of_ne hhead.2]
+
+/-- From the caller's base address and stride, install the actual pointer registers
+and represent an empty bank even when this is a later leaf reusing the same region. -/
+theorem initialize_pointers (L : Layout K w) (order : Fin N ≃ K) (base : ℕ)
+ (hlayout : ∀ i, L.base (order i) = base+i.val*L.capacity) (pc : K → Fin 3 → Fin p)
+ (endPC : Fin 2 → Fin p) (done : Fin p) (hl : Rows M reg pc (endPC 0) (List.ofFn order))
+ (hf : ∀ i, M.code (endPC i) = finish endPC reg done i) (c : Config w p r)
+ (hc : c.pc = next (List.ofFn order) pc (endPC 0))
+ (hbase : c.reg (reg .cursor) = (base : Word w)) (hstride : c.reg (reg .stride) = (L.capacity : Word w)) :
+ ∃ out, Prefix M c (List.replicate (3*N+2) .tick) out ∧ out.pc = done ∧
+ Represents L (stack reg) out (fun _ => []) ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent ∧ ∀ i, i ∉ Set.range reg → out.reg i = c.reg i := by
+ have hn : (List.ofFn order).Nodup := List.nodup_ofFn.mpr order.injective
+ obtain ⟨mid,run,hm,values,frame,mem,state⟩ := walk M reg pc (endPC 0) _ hl hn base L.capacity c hc hbase hstride
+ let u := mid.put (endPC 1) (reg (.stack .zero)) 0
+ let out := u.put done (reg (.stack .one)) 1
+ have h₀ : M.program.step mid = .localStep u := by
+ change (M.code mid.pc).run _ _ = _; rw [hm,hf 0]; rfl
+ have h₁ : M.program.step u = .localStep out := by
+ change (M.code (endPC 1)).run _ _ = _; rw [hf 1]; rfl
+ have fin : Prefix M mid (List.replicate 2 .tick) out := .tick h₀ (.tick h₁ (.nil _))
+ have hr := run.append fin
+ rw [List.length_ofFn,← List.replicate_add] at hr
+ have ptr (a : K) : mid.reg (reg (.stack (.base a))) = L.address a 0 ∧
+ mid.reg (reg (.stack (.top a))) = L.address a 0 := by
+ obtain ⟨i,rfl⟩ := order.surjective a
+ have eq := values (i.cast (List.length_ofFn.symm))
+ simpa [List.getElem_ofFn,Layout.address,hlayout] using eq
+ refine ⟨out,hr,rfl,?_,mem,state,?_⟩
+ · refine ⟨?_,?_,?_,?_,?_⟩
+ · simp [out,Config.put]
+ · simp [out,u,Config.put]
+ · intro a; simpa [out,u,Config.put] using (ptr a).1
+ · intro a; simpa [out,u,Config.put] using (ptr a).2
+ · intro a pre bit tail he; simp at he
+ · intro i hi
+ have ne (j : Reg K) : i ≠ reg j := fun e => hi ⟨j,e.symm⟩
+ rw [show out.reg i = mid.reg i by simp [out,u,Config.put,Function.update_of_ne (ne _)]]
+ exact frame _ (ne _) (fun _ _ => ⟨ne _,ne _⟩)
+
+end PairSimulation.LeafPointers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafPortLoad.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafPortLoad.lean
new file mode 100644
index 0000000000..f179c44c29
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafPortLoad.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PairSimulationLeafRegisterBank
+import OAI.Computability.VPVNP.PairSimulationLeafFieldStage
+
+/-! # Linking the operand staging and scalar loops at each virtual-validator port -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRegisterBank
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord RAMTape LeafStartup StackMachine
+open scoped Fin.CommRing
+
+variable {d e w k p r pubs : ℕ} {K : Type} [DecidableEq K]
+
+/-- The incident stack stays empty until its four supplied half-wire buffers are decoded. -/
+def scalarField (f : Field k) : Field k := if f = .incident then .blank else f
+
+theorem scalarField_ne (f : Field k) : scalarField f ≠ .incident := by by_cases h : f = .incident <;> simp [scalarField,h]
+
+/-- Choose tally loading for unary counts and empty fields, and binary loading for word-valued
+fields. -/
+def mode : Field k → LeafScalarLoad.Mode
+ | .blank | .incident | .addressWidth | .width | .slots | .bucket | .fuel | .siteCredit | .choices => .tally
+ | _ => .binary
+
+theorem mode_eq (x : VirtualSite.Input d e w) (args : Fin k → Word w) (f : Field k) :
+ mode f = (source x args f).1 := by cases f <;> rfl
+
+omit [DecidableEq K] in
+theorem preserveSources (reg : Reg K k ↪ Fin r) (x : VirtualSite.Input d e w) (args : Fin k → Word w)
+ (old new : Config w p r) (ready : Staging.Sources x args (old.reg ∘ stage reg))
+ (hz : new.reg (stack reg .zero) = 0) (ho : new.reg (stack reg .one) = 1)
+ (frame : ∀ j : Source k, new.reg (reg (.inr j)) = old.reg (reg (.inr j))) :
+ Staging.Sources x args (new.reg ∘ stage reg) :=
+ ⟨hz,ho,(frame .d).trans ready.d,(frame .width).trans ready.width,(frame .bucket).trans ready.bucket,
+ (frame .fuel).trans ready.fuel,(frame .address).trans ready.address,(frame .initial).trans ready.initial,
+ (frame .header).trans ready.header,fun i => (frame (.operand i)).trans (ready.operand i)⟩
+
+/-- Prepare the length and value using native rows, then write the represented
+stack directly at the pointer initialized for this port. The public source
+registers are available to the next port. -/
+theorem scalar_run (x : VirtualSite.Input d e w) (args : Fin k → Word w) (f : Field k)
+ (hf : f ≠ .incident) (M : Machine w p r pubs) (reg : Reg K k ↪ Fin r) (L : Layout K w) (a : K)
+ (stagePC : Fin ((Staging.code f).length+1) → Fin p) (fillPC : Fin 6 → Fin p) (done : Fin p)
+ (joinPC : stagePC (Fin.last (Staging.code f).length) = fillPC 0)
+ (stageRows : ∀ i : Fin (Staging.code f).length, M.code (stagePC i.castSucc) =
+ Staging.instruction (stage reg) (stagePC i.succ) (Staging.code f)[i])
+ (fillRows : LeafScalarLoad.Linked M (mode f) fillPC (LeafFill.fieldRegisters (load reg) a) done)
+ (c : Config w p r) (hc : c.pc = stagePC 0) (s : Stacks K) (rep : Represents L (stack reg) c s)
+ (ready : Staging.Sources x args (c.reg ∘ stage reg)) (empty : s a = [])
+ (fit : ∀ j, (s j).length ≤ L.capacity) (room : (fieldBits x args f).length ≤ L.capacity) :
+ let xs := fieldBits x args f
+ ∃ out, Prefix M c (List.replicate ((Staging.code f).length+(6*xs.length+1)) .tick) out ∧
+ out.pc = done ∧ Represents L (stack reg) out (Function.update s a xs) ∧
+ Staging.Sources x args (out.reg ∘ stage reg) ∧ out.persistent = c.persistent ∧
+ (∀ i, i ∉ Set.range reg → out.reg i = c.reg i) ∧
+ ∀ u, u.val < L.base a ∨ L.base a+xs.length ≤ u.val → out.privateMem u = c.privateMem u := by
+ intro xs
+ let ls := Staging.code f
+ let mid : Config w p r := {c with pc := stagePC (Fin.last ls.length), reg := ls.foldl (Staging.applyPhysical (stage reg)) c.reg}
+ have staged : Prefix M c (List.replicate ls.length .tick) mid :=
+ Staging.run M (stage reg) ls stagePC stageRows c hc
+ have midrep := staged_represents reg L s ls mid.pc c rep
+ change Represents L (stack reg) mid s at midrep
+ let v := source x args f
+ have spec := scalarSpec x args f hf
+ change LeafScalarLoad.payload v.1 v.2.2 v.2.1 = xs.reverse at spec
+ have len := congrArg List.length spec
+ simp only [LeafScalarLoad.payload_length,List.length_reverse] at len
+ have words := Staging.stagedWords x args (c.reg ∘ stage reg) ready f
+ have physical := Staging.physical_at (stage reg) ls c.reg
+ have hlen : mid.reg (load reg .length) = (xs.length : Word w) := by
+ refine ((congrFun physical (.out .len)).trans words.1).trans ?_
+ exact congrArg (fun n : ℕ => (n : Word w)) len
+ have hval : mid.reg (load reg .value) = v.2.2 := (congrFun physical (.out .value)).trans words.2
+ have bitSpec : LeafScalarLoad.payload (mode f) v.2.2 xs.length = xs.reverse := by
+ rw [← len,mode_eq x args]; exact spec
+ obtain ⟨out,loaded,hpc,hrep,hstate,fr,mem⟩ :=
+ LeafFill.install_scalar L (load reg) a s xs v.2.2 mid fillRows (by have := x.hw; omega) joinPC
+ midrep empty fit room hlen hval bitSpec
+ have hr := staged.append loaded
+ rw [← List.replicate_add] at hr
+ have preservedOuter (i : Fin r) (hl : i ∉ Set.range (load reg)) (hs : ∀ o, i ≠ stage reg (.out o)) :
+ out.reg i = c.reg i :=
+ (fr i hl).trans (Staging.physical_outside (stage reg) ls c.reg i hs)
+ refine ⟨out,hr,hpc,hrep,preserveSources reg x args c out ready hrep.zero hrep.unit ?_,hstate,?_,mem⟩
+ · intro j
+ apply preservedOuter
+ · rintro ⟨i,he⟩; simp at he
+ · intro o; cases o <;> simp [stagingName]
+ · intro i hi
+ apply preservedOuter
+ · rintro ⟨j,he⟩; exact hi ⟨.inl j,he⟩
+ · exact fun o he => hi ⟨stagingName (.out o),he.symm⟩
+
+end PairSimulation.LeafRegisterBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafPortTable.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafPortTable.lean
new file mode 100644
index 0000000000..a26aaf66ec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafPortTable.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.PairSimulationLeafPortWalk
+
+/-! # Finite instruction table allocating and filling every scalar leaf port -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafPortTable
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord RAMTape StackMachine
+open LeafStartup LeafRegisterBank
+open scoped Fin.CommRing
+
+variable {K : Type} [DecidableEq K] {d e w k p r pubs N : ℕ}
+
+/-- Rows for allocating a port, finishing allocation, staging its scalar field and filling its
+private stack. -/
+inductive Label (K : Type) where
+ | pointer (a : K) (i : Fin 3)
+ | finish (i : Fin 2)
+ | stage (a : K) (i : Fin 4)
+ | fill (a : K) (i : Fin 6)
+ deriving DecidableEq, Fintype
+
+/-- Construct the successor-port lookup for a fixed traversal list, using the head of the
+remaining suffix at each port. -/
+def followers : List K → K → Option K
+ | [] => fun _ => none
+ | a::as => Function.update (followers as) a as.head?
+
+/-- The successor lookup agrees with the traversal list at every port, including the final
+port's empty successor. -/
+def Follows (next : K → Option K) : List K → Prop
+ | [] => True
+ | a::as => next a = as.head? ∧ Follows next as
+
+omit [DecidableEq K] in
+private theorem follows_congr {f g : K → Option K} {todo : List K}
+ (he : ∀ a ∈ todo, f a = g a) (hf : Follows f todo) : Follows g todo := by
+ induction todo with
+ | nil => trivial
+ | cons a as ih =>
+ exact ⟨(he a (List.mem_cons_self ..)).symm.trans hf.1, ih (fun j hj => he j (List.mem_cons_of_mem a hj)) hf.2⟩
+
+theorem follows (todo : List K) (hn : todo.Nodup) : Follows (followers todo) todo := by
+ induction todo with
+ | nil => trivial
+ | cons a as ih =>
+ have h := List.nodup_cons.mp hn
+ refine ⟨Function.update_self ..,follows_congr ?_ (ih h.2)⟩
+ intro j hj
+ exact (Function.update_of_ne (ne_of_mem_of_not_mem hj h.1) ..).symm
+
+variable (tag : K → Field k) (pc : Label K → Fin p) (reg : Reg K k ↪ Fin r) (done : Fin p)
+
+/-- Map a staging index to that port's staging row, with the final index pointing to the first
+scalar fill instruction. -/
+def stagePC : StageLabels tag p := fun a i =>
+ let len := (Staging.code (scalarField (tag a))).length
+ if h : i.val < len then pc (.stage a ⟨i.val,h.trans_le (Staging.length_le _)⟩) else pc (.fill a 0)
+
+/-- The allocation, staging or fill instruction for one labeled row of the port list, including
+its continuation to the following port. -/
+def instruction (todo : List K) : Label K → Instr w p r pubs
+ | .pointer a i => LeafPointers.allocate a (fun j => pc (.pointer a j)) (LeafFill.pointers (load reg))
+ ((followers todo a).elim (pc (.finish 0)) fun b => pc (.pointer b 0)) i
+ | .finish i => LeafPointers.finish (fun j => pc (.finish j)) (LeafFill.pointers (load reg))
+ (first tag (stagePC tag pc) done todo) i
+ | .stage a i =>
+ let ls := Staging.code (scalarField (tag a))
+ if h : i.val < ls.length then
+ Staging.instruction (stage reg) (stagePC tag pc a (Fin.succ ⟨i.val,h⟩)) ls[i.val]
+ else .reject
+ | .fill a i => LeafScalarLoad.instruction (mode (scalarField (tag a))) (fun j => pc (.fill a j))
+ (LeafFill.fieldRegisters (load reg) a)
+ ((followers todo a).elim done fun b => stagePC tag pc b 0) i
+
+theorem resize_instruction (todo : List K) (label : Label K) :
+ (instruction (w := 1) (pubs := pubs) tag pc reg done todo label).resize w =
+ instruction tag pc reg done todo label := by
+ cases label with
+ | pointer a i => simp only [instruction, LeafPointers.resize_allocate]
+ | finish i => simp only [instruction, LeafPointers.resize_finish]
+ | stage a i =>
+ simp only [instruction]
+ split <;> first | exact Staging.resize_instruction .. | rfl
+ | fill a i => simp only [instruction, LeafScalarLoad.resize_instruction]
+
+variable (M : Machine w p r pubs)
+
+theorem rows (allPorts : List K) (hn : allPorts.Nodup)
+ (link : ∀ j, M.code (pc j) = instruction tag pc reg done allPorts j) :
+ LeafPointers.Rows M (LeafFill.pointers (load reg)) (fun a i => pc (.pointer a i)) (pc (.finish 0)) allPorts ∧
+ ScalarRows tag M reg (stagePC tag pc) (fun a i => pc (.fill a i)) done allPorts := by
+ have sub (todo : List K) (hf : Follows (followers allPorts) todo) :
+ LeafPointers.Rows M (LeafFill.pointers (load reg)) (fun a i => pc (.pointer a i)) (pc (.finish 0)) todo ∧
+ ScalarRows tag M reg (stagePC tag pc) (fun a i => pc (.fill a i)) done todo := by
+ induction todo with
+ | nil => exact ⟨trivial,trivial⟩
+ | cons a as ih =>
+ obtain ⟨ptr,sc⟩ := ih hf.2
+ refine ⟨⟨?_,ptr⟩,?_,?_,?_,sc⟩
+ · intro i
+ simpa only [instruction,hf.1,LeafPointers.next] using link (.pointer a i)
+ · simp [stagePC]
+ · intro i
+ let j : Fin 4 := ⟨i.val,i.isLt.trans_le (Staging.length_le _)⟩
+ have hpc : stagePC tag pc a i.castSucc = pc (.stage a j) := by simp [stagePC,j,i.isLt]
+ rw [hpc,link]
+ simp [instruction,j,i.isLt]
+ · intro i
+ simpa only [instruction,hf.1,first] using link (.fill a i)
+ exact sub allPorts (follows _ hn)
+
+/-- Native scalar startup from the fixed rows. Its label set, register wiring,
+and instructions are independent of the input values and widths. -/
+theorem startup (order : Fin N ≃ K) (L : Layout K w) (base : ℕ)
+ (hlayout : ∀ i, L.base (order i) = base+i.val*L.capacity)
+ (x : VirtualSite.Input d e w) (args : Fin k → Word w)
+ (link : ∀ j, M.code (pc j) = instruction tag pc reg done (List.ofFn order) j)
+ (c : Config w p r) (hc : c.pc = LeafPointers.next (List.ofFn order) (fun a i => pc (.pointer a i)) (pc (.finish 0)))
+ (hbase : c.reg (LeafFill.pointers (load reg) .cursor) = (base : Word w))
+ (hstride : c.reg (LeafFill.pointers (load reg) .stride) = (L.capacity : Word w))
+ (inputs : ∀ j, c.reg (reg (.inr j)) = sourceWord x args j) (room : ∀ a, (scalarBank tag x args a).length ≤ L.capacity) :
+ ∃ out, Prefix M c (List.replicate (3*N+2+((List.ofFn order).map (ticks tag x args)).sum) .tick) out ∧
+ out.pc = done ∧ Represents L (stack reg) out (scalarBank tag x args) ∧
+ Staging.Sources x args (out.reg ∘ stage reg) ∧ out.persistent = c.persistent ∧
+ (∀ i, i ∉ Set.range reg → out.reg i = c.reg i) ∧
+ ∀ u, (∀ a, u.val < L.base a ∨ L.base a+(scalarBank tag x args a).length ≤ u.val) →
+ out.privateMem u = c.privateMem u := by
+ obtain ⟨hp,hs⟩ := rows tag pc reg done M (List.ofFn order) (List.nodup_ofFn.mpr order.injective) link
+ exact scalar_startup tag x args M reg L (stagePC tag pc) (fun a i => pc (.fill a i)) done order base
+ hlayout (fun a i => pc (.pointer a i)) (fun i => pc (.finish i)) hp (fun i => link (.finish i)) hs c hc hbase hstride inputs room
+
+end PairSimulation.LeafPortTable
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafPortWalk.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafPortWalk.lean
new file mode 100644
index 0000000000..5581db4d69
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafPortWalk.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.PairSimulationLeafPortLoad
+
+/-!
+# Filling the validator's fixed scalar-port list in a single private call
+
+The scalar pass visits each port exactly once. The caller can reuse its
+private arena at the next leaf. The incident port remains available for
+the separate copy from the four half-wire buffers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRegisterBank
+
+open BurstRAM PrivateRAM RAMTape LeafStartup StackMachine PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {K : Type} [DecidableEq K] {d e w k p r pubs N : ℕ}
+ (tag : K → Field k) (x : VirtualSite.Input d e w) (args : Fin k → Word w)
+
+/-- The completed scalar stack contents of each port, obtained by encoding its field for the
+given site and operands. -/
+def scalarBank : Stacks K := fun a => fieldBits x args (scalarField (tag a))
+
+/-- The intermediate scalar bank with the unvisited ports empty and the visited ports holding
+their completed fields. -/
+def pending (todo : List K) : Stacks K := fun a => if a ∈ todo then [] else scalarBank tag x args a
+
+/-- The instruction count to stage one port's scalar field and run the six-row fill loop for
+its bits. -/
+def ticks (a : K) := (Staging.code (scalarField (tag a))).length + (6*(scalarBank tag x args a).length+1)
+
+/-- Program labels for each port's field-specific staging sequence, including the index used
+for its continuation. -/
+abbrev StageLabels (tag : K → Field k) (p : ℕ) :=
+ (a : K) → Fin ((Staging.code (scalarField (tag a))).length+1) → Fin p
+
+/-- The first staging label of the next port to fill, or the exit label once the traversal list
+is empty. -/
+def first (label : StageLabels tag p) (done : Fin p) (todo : List K) :=
+ todo.head?.elim done fun a => label a 0
+
+variable (M : Machine w p r pubs) (reg : Reg K k ↪ Fin r) (L : Layout K w)
+ (stages : StageLabels tag p) (fills : K → Fin 6 → Fin p) (done : Fin p)
+
+/-- The host machine implements each port's field-specific staging and fill rows, with
+continuations that visit the list in order. -/
+def ScalarRows : List K → Prop
+ | [] => True
+ | a::rest =>
+ let f := scalarField (tag a)
+ stages a (Fin.last (Staging.code f).length) = fills a 0 ∧
+ (∀ i : Fin (Staging.code f).length, M.code (stages a i.castSucc) =
+ Staging.instruction (stage reg) (stages a i.succ) (Staging.code f)[i]) ∧
+ LeafScalarLoad.Linked M (mode f) (fills a) (LeafFill.fieldRegisters (load reg) a) (first tag stages done rest) ∧
+ ScalarRows rest
+
+theorem scalar_walk (todo : List K) (hn : todo.Nodup) (link : ScalarRows tag M reg stages fills done todo)
+ (c : Config w p r) (hc : c.pc = first tag stages done todo)
+ (rep : Represents L (stack reg) c (pending tag x args todo))
+ (ready : Staging.Sources x args (c.reg ∘ stage reg)) (room : ∀ a, (scalarBank tag x args a).length ≤ L.capacity) :
+ ∃ out, Prefix M c (List.replicate (todo.map (ticks tag x args)).sum .tick) out ∧ out.pc = done ∧
+ Represents L (stack reg) out (scalarBank tag x args) ∧ Staging.Sources x args (out.reg ∘ stage reg) ∧
+ out.persistent = c.persistent ∧ (∀ i, i ∉ Set.range reg → out.reg i = c.reg i) ∧
+ ∀ u, (∀ a ∈ todo, u.val < L.base a ∨ L.base a+(scalarBank tag x args a).length ≤ u.val) →
+ out.privateMem u = c.privateMem u := by
+ induction todo generalizing c with
+ | nil =>
+ have hbank : pending tag x args [] = scalarBank tag x args := by funext i; simp [pending]
+ exact ⟨c,.nil _,hc,hbank ▸ rep,ready,rfl,fun _ _ => rfl,fun _ _ => rfl⟩
+ | cons a rest ih =>
+ have nodup := List.nodup_cons.mp hn
+ obtain ⟨hj,hs,hf,hrest⟩ := link
+ have fit (j : K) : ((pending tag x args (a::rest)) j).length ≤ L.capacity := by
+ by_cases h : j ∈ a::rest <;> simp [pending, h, room]
+ obtain ⟨mid,head,atPC,rep',ready',state,regs,mem⟩ := scalar_run x args (scalarField (tag a))
+ (scalarField_ne _) M reg L a (stages a) (fills a) _ hj hs hf c hc (pending tag x args (a::rest))
+ rep ready (by simp [pending]) fit (room a)
+ have eq : Function.update (pending tag x args (a::rest)) a (scalarBank tag x args a) =
+ pending tag x args rest := by
+ funext i
+ by_cases hi : i = a
+ · subst i; simp [pending,nodup.1]
+ · simp [pending,hi]
+ change Represents L (stack reg) mid (Function.update _ a (scalarBank tag x args a)) at rep'
+ obtain ⟨out,tail,hd,rep'',rdy'',pst,fr,unchanged⟩ := ih nodup.2 hrest mid atPC (eq ▸ rep') ready'
+ have run := head.append tail
+ rw [← List.replicate_add] at run
+ exact ⟨out,run,hd,rep'',rdy'',pst.trans state,fun i hi => (fr i hi).trans (regs i hi),
+ fun u hu => (unchanged u (fun j hj => hu j (List.mem_cons_of_mem _ hj))).trans (mem u (hu a (List.mem_cons_self ..)))⟩
+
+/-- Scalar input registers furnished by the enclosing private call. -/
+def sourceWord (x : VirtualSite.Input d e w) (args : Fin k → Word w) : Source k → Word w
+ | .d => (d : Word w)
+ | .width => (w : Word w)
+ | .bucket => ((2^e : ℕ) : Word w)
+ | .fuel => (x.fuel : Word w)
+ | .address => x.addrWord
+ | .initial => x.initialWord
+ | .header => x.headerWord
+ | .operand i => args i
+
+/-- The deterministic pointer and scalar tables are consecutive subprograms
+of the same native RAM. No pre-initialized stack bank is required. -/
+theorem scalar_startup (order : Fin N ≃ K) (base : ℕ) (hlayout : ∀ i, L.base (order i) = base+i.val*L.capacity)
+ (allocPC : K → Fin 3 → Fin p) (endPC : Fin 2 → Fin p)
+ (allocation : LeafPointers.Rows M (LeafFill.pointers (load reg)) allocPC (endPC 0) (List.ofFn order))
+ (finish : ∀ i, M.code (endPC i) = LeafPointers.finish endPC (LeafFill.pointers (load reg))
+ (first tag stages done (List.ofFn order)) i)
+ (rows : ScalarRows tag M reg stages fills done (List.ofFn order)) (c : Config w p r)
+ (hc : c.pc = LeafPointers.next (List.ofFn order) allocPC (endPC 0))
+ (hbase : c.reg (LeafFill.pointers (load reg) .cursor) = (base : Word w))
+ (hstride : c.reg (LeafFill.pointers (load reg) .stride) = (L.capacity : Word w))
+ (inputs : ∀ j, c.reg (reg (.inr j)) = sourceWord x args j) (room : ∀ a, (scalarBank tag x args a).length ≤ L.capacity) :
+ ∃ out, Prefix M c (List.replicate (3*N+2+((List.ofFn order).map (ticks tag x args)).sum) .tick) out ∧
+ out.pc = done ∧ Represents L (stack reg) out (scalarBank tag x args) ∧
+ Staging.Sources x args (out.reg ∘ stage reg) ∧ out.persistent = c.persistent ∧
+ (∀ i, i ∉ Set.range reg → out.reg i = c.reg i) ∧
+ ∀ u, (∀ a, u.val < L.base a ∨ L.base a+(scalarBank tag x args a).length ≤ u.val) →
+ out.privateMem u = c.privateMem u := by
+ obtain ⟨mid,allocated,atPC,empty,memory,state,frame⟩ := LeafPointers.initialize_pointers M
+ (LeafFill.pointers (load reg)) L order base hlayout allocPC endPC _ allocation finish c hc hbase hstride
+ have loaded (j : Source k) : mid.reg (reg (.inr j)) = sourceWord x args j :=
+ (frame _ (by rintro ⟨i,he⟩; simp at he)).trans (inputs j)
+ have rdy : Staging.Sources x args (mid.reg ∘ stage reg) :=
+ ⟨empty.zero,empty.unit,loaded .d,loaded .width,loaded .bucket,loaded .fuel,loaded .address,
+ loaded .initial,loaded .header,fun i => loaded (.operand i)⟩
+ have bank0 : pending tag x args (List.ofFn order) = fun _ => [] := by
+ funext a
+ simp [pending, List.mem_ofFn, order.surjective a]
+ obtain ⟨out,filled,hd,rep,rdy',pst,regs,mem⟩ := scalar_walk tag x args M reg L stages fills done
+ _ (List.nodup_ofFn.mpr order.injective) rows mid atPC (bank0 ▸ empty) rdy room
+ have run := allocated.append filled
+ rw [← List.replicate_add] at run
+ refine ⟨out,run,hd,rep,rdy',pst.trans state,?_,?_⟩
+ · intro i hi
+ exact (regs i hi).trans (frame i (fun ⟨j,hj⟩ => hi ⟨_,hj⟩))
+ · intro u hu
+ exact (mem u (fun a _ => hu a)).trans (congrFun memory u)
+
+end PairSimulation.LeafRegisterBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafReadback.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafReadback.lean
new file mode 100644
index 0000000000..bcf47522d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafReadback.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.PairSimulationLeafHandler
+
+/-! # Reading the semantic occurrence at a physical cursor leaf -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafHandler
+
+open BurstRAM CursorRouting CursorNetwork LeafStartup StackMachine DFS
+
+set_option synthInstance.maxSize 10000
+
+variable {d e w W endAddr : ℕ} [NeZero d]
+ {A : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout A n a H w}
+ (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (storage : StackMachine.Layout (Port 52 34) W)
+ (load : Word W → Scratch W endAddr → Input d e w W endAddr) (clock : ℕ)
+ (node : Word W) (saved : Scratch W endAddr) (bits : List Bool)
+
+theorem parser_suffix :
+ let x := load node saved
+ ((parser D hw hc storage load clock).read node saved bits).map Prod.snd =
+ if Routed x then if x.pos.1 = 0 then
+ acceptPrefix auxiliaryCode clock auxiliaryEntry (auxiliaryBank D hw hc x.pos x.buffers) bits
+ else some bits else none := by
+ intro x
+ by_cases hr : Routed x
+ · by_cases hz : x.pos.1 = 0
+ · let bank := auxiliaryBank D hw hc x.pos x.buffers
+ change ((if Routed x then _ else none) : Option (VisitPath W endAddr × List Bool)).map Prod.snd = _
+ rw [ite_eq_left hr,ite_eq_left hr,ite_eq_left hz,ite_eq_left hz]
+ let f := footprint storage auxiliaryCode clock auxiliaryEntry bank bits
+ change (match parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => none
+ | some y => if y.accept then some (⟨node,x.trace++f.events,(· = saved),fun _ => f.applyScratch endAddr x.prepared⟩,y.rest) else none : Option (VisitPath W endAddr × List Bool)).map Prod.snd =
+ acceptPrefix auxiliaryCode clock auxiliaryEntry bank bits
+ unfold acceptPrefix haltPrefix
+ cases he : parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => rfl
+ | some y => cases ok : y.accept <;> simp [ok]
+ · simp only [parser,show load node saved = x from rfl,ite_eq_left hr,ite_eq_right hz,Option.map_some]
+ · simp only [parser,show load node saved = x from rfl,ite_eq_right hr,Option.map_none]
+
+/-- An actual private argument supplied by its parent uses the same suffix
+as the leaf reader of the weighted occurrence expansion. This equality also
+covers incompatible half-wire combinations, failed routes, and transit sites. -/
+theorem parser_nomination (v : Position d) (z : (validatorNetwork d e w).Half v)
+ (position : (load node saved).pos = v) (buffer : (load node saved).buffers = halfBuffers v z)
+ (bound : steps 52 (auxiliary D hw hc v (halfBuffers v z)) ≤ clock) :
+ ((parser D hw hc storage load clock).read node saved bits).map Prod.snd =
+ ((nominationReader D hw hc v z clock bound).read bits).map Prod.snd := by
+ rw [parser_suffix,nominationReader_suffix]
+ simp only [Routed,position,buffer]
+
+/-- The deterministic prefix supplies all external probes. A successful
+cursor-zero call adds at most four native transitions per bounded stack
+instruction, with the same bound on all choices and independent input bits. -/
+theorem parser_work {job : VisitPath W endAddr} {tail : List Bool}
+ (h : (parser D hw hc storage load clock).read node saved bits = some (job,tail)) :
+ let x := load node saved
+ countProbes job.trace = countProbes x.trace ∧ job.trace.length ≤ x.trace.length+4*clock := by
+ intro x
+ have append (as bs : List (Event W)) : countProbes (as++bs) = countProbes as+countProbes bs := by
+ induction as with
+ | nil => simp [countProbes]
+ | cons a as ih => cases a <;> simp [countProbes,ih,Nat.add_assoc]
+ by_cases hr : Routed (load node saved)
+ · by_cases hz : (load node saved).pos.1 = 0
+ · let bank := auxiliaryBank D hw hc x.pos x.buffers
+ let f := footprint storage auxiliaryCode clock auxiliaryEntry bank bits
+ simp only [parser,ite_eq_left hr,ite_eq_left hz] at h
+ change (match parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => none
+ | some y => if y.accept then some (⟨node,x.trace++f.events,(· = saved),fun _ => f.applyScratch endAddr x.prepared⟩,y.rest) else none) = some (job,tail) at h
+ cases hp : parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => rw [hp] at h; contradiction
+ | some y =>
+ rw [hp] at h
+ cases ok : y.accept with
+ | false => simp only [ok,Bool.false_eq_true,↓reduceIte,reduceCtorEq] at h
+ | true =>
+ simp only [ok,↓reduceIte,Option.some.injEq,Prod.mk.injEq] at h
+ rw [← h.1,append,List.length_append]
+ have probes : countProbes f.events = 0 := footprint_probes ..
+ have time : f.events.length + 4*y.unused + 3 = 4*clock := (footprint_parse storage hp ok).2
+ simp only [probes,Nat.add_zero,true_and]
+ omega
+ · simp only [parser,ite_eq_left hr,ite_eq_right hz,Option.some.injEq,Prod.mk.injEq] at h
+ rw [← h.1]
+ exact ⟨rfl,Nat.le_add_right _ _⟩
+ · simp only [parser,ite_eq_right hr,reduceCtorEq] at h
+
+end PairSimulation.LeafHandler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafReads.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafReads.lean
new file mode 100644
index 0000000000..56b31a6b8c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafReads.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.PairSimulationLeafRoleJobs
+import OAI.Computability.VPVNP.PairTerminalFootprint
+import OAI.Computability.VPVNP.CompressorFlowFootprint
+
+/-! # Public-memory footprint of a selected cursor leaf -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRole
+
+open BurstRAM CursorNetwork CursorRouting LeafStartup StackMachine DFS LeafHandler
+open CompressorRecords.SourceTransport TerminalFootprint
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Every external event of a leaf is its optional virtual header read. -/
+private def Supported (allow : ℕ → Prop) (es : List (Event w)) : Prop :=
+ Reads allow es ∧ Writes (fun _ => False) es
+
+private theorem supported_append {allow : ℕ → Prop} {es fs : List (Event w)}
+ (left : Supported allow es) (right : Supported allow fs) : Supported allow (es++fs) :=
+ ⟨reads_append left.1 right.1, fun a v h => (List.mem_append.mp h).elim (left.2 a v) (right.2 a v)⟩
+
+private theorem supported_ticks (allow : ℕ → Prop) (n : ℕ) : Supported allow (List.replicate n (.tick : Event w)) := by
+ refine ⟨reads_ticks _ _,?_⟩
+ intro a v h
+ have eq : (.write a v : Event w) = .tick := List.eq_of_mem_replicate h
+ cases eq
+
+private theorem unchanged {es : List (Event w)} (nowrite : Writes (fun _ => False) es)
+ (m : Memory w) : after m es = m := by
+ induction es generalizing m with
+ | nil => rfl
+ | cons e es ih =>
+ have tail : Writes (fun _ => False) es := fun a v h => nowrite a v (List.mem_cons_of_mem _ h)
+ cases e with
+ | write a v => exact (nowrite a v List.mem_cons_self).elim
+ | read | tick | choice => exact ih tail m
+
+variable {L : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout L n a H w}
+ (D : PrimedCounter.Data Q s) {b l e endAddr : ℕ} [NeZero (b+l)] (budget : ProcessorBudget n (b+l) e w)
+ (R : LeafArena.Regions) (fit : R.stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ (m : Memory w) (data : Fin 10 → Word w) (node : Word w) (saved : Scratch w endAddr)
+ (clock : ℕ) (bits tail : List Bool) (job : VisitPath w endAddr)
+
+private theorem input_supported (allow : ℕ → Prop) (fields : LeafAddress.Field → Word w)
+ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w)
+ (shadow : (v.2.val : Word w) < fields .span → allow (fields .shadow+(v.2.val : Word w)).val) :
+ Supported allow (LeafVisit.trace D budget m fields v buf) := by
+ unfold LeafVisit.trace LeafFront.trace LeafAddress.events
+ refine supported_append (supported_append (supported_append (supported_ticks _ 17) ?_) (supported_ticks _ _)) ?_
+ · split
+ · rename_i h
+ refine ⟨?_,?_⟩
+ · intro a x mem
+ simp only [List.mem_cons, List.not_mem_nil, reduceCtorEq, Event.read.injEq, or_false] at mem
+ exact mem.1 ▸ shadow h
+ · intro a x mem
+ simp at mem
+ · exact supported_ticks _ 2
+ · split
+ · exact supported_ticks _ _
+ · exact supported_ticks _ 0
+
+private theorem parser_supported (storage : StackMachine.Layout (Port 52 34) w)
+ (load : Word w → Scratch w endAddr → Input (b+l) e w w endAddr) (allow : ℕ → Prop)
+ (head : Supported allow (load node saved).trace)
+ (read : (LeafHandler.parser D budget.tags budget.capFits storage load clock).read node saved bits = some (job,tail)) :
+ Supported allow job.trace := by
+ let x := load node saved
+ let bank := auxiliaryBank D budget.tags budget.capFits x.pos x.buffers
+ let f := footprint storage auxiliaryCode clock auxiliaryEntry bank bits
+ by_cases hr : Routed x
+ · by_cases hz : x.pos.1 = 0
+ · change (if Routed x then _ else none) = some (job,tail) at read
+ rw [ite_eq_left hr,ite_eq_left hz] at read
+ change (match parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => none
+ | some y => if y.accept then some (⟨node,x.trace++f.events,(· = saved),fun _ => f.applyScratch endAddr x.prepared⟩,y.rest)
+ else none) = some (job,tail) at read
+ cases hp : parse auxiliaryCode clock auxiliaryEntry bank bits with
+ | none => rw [hp] at read; contradiction
+ | some y =>
+ rw [hp] at read
+ cases ok : y.accept with
+ | false => simp [ok] at read
+ | true =>
+ simp only [ok,↓reduceIte,Option.some.injEq,Prod.mk.injEq] at read
+ rw [←read.1]
+ exact supported_append head (CompressorRecords.FlowFootprint.bounds_of_noProbes _ _ (footprint_probes ..))
+ · change (if Routed x then _ else none) = some (job,tail) at read
+ rw [ite_eq_left hr,ite_eq_right hz] at read
+ cases read
+ exact head
+ · change (if Routed x then _ else none) = some (job,tail) at read
+ rw [ite_eq_right hr] at read
+ contradiction
+
+/-- A successful physical leaf leaves public memory intact. The shadow word
+is the only allowed read, for every private input and every remaining suffix. -/
+theorem site_footprint (allow : ℕ → Prop)
+ (shadow : ∀ site : Word w, site < addressFields data .span → allow (addressFields data .shadow+site).val)
+ (hit : (parser data D budget R fit m clock).read node saved bits = some (job,tail)) :
+ Reads allow job.trace ∧ after m job.trace = m := by
+ let fields := addressFields data
+ let load := LeafVisit.loaded (endAddr := endAddr) D budget R fit fields m
+ let storage := LeafVisit.storage R fit
+ let source : HookParser w endAddr := LeafHandler.parser D budget.tags budget.capFits storage load clock
+ obtain ⟨old, read, _, _, logs, _, _⟩ := reload_read source node saved bits tail job hit
+ have front : Supported allow (load node saved).trace :=
+ input_supported D budget m allow fields _ _ (shadow _)
+ have support := parser_supported D budget node saved clock bits tail old storage load allow front read
+ rw [logs]
+ have full := supported_append (supported_ticks allow 21) support
+ exact ⟨full.1, unchanged full.2 m⟩
+
+end PairSimulation.LeafRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafRealization.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafRealization.lean
new file mode 100644
index 0000000000..a5fe451848
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafRealization.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairSimulationLeafFrame
+import OAI.Computability.VPVNP.PairSimulationLeafJobReadback
+
+/-! # Physical realization of each actual compressed cursor-leaf occurrence -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafHandler
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork LeafStartup StackMachine DFS
+open LocalHistory NodeArguments
+open scoped Fin.CommRing
+
+variable {e w W endAddr : ℕ}
+ {L : PrimedInputRAM.Lengths} {n ai H s : ℕ} {Q : PrimedInputRAM.Layout L n ai H w}
+ (D : PrimedCounter.Data Q s) (hw : 2 ≤ w)
+ (storage : StackMachine.Layout (Port 52 34) W) (clock : ℕ)
+ (node : Word W) (saved : Scratch W endAddr)
+
+section Cursor
+
+open RAMLayout Compression TraversalRows
+
+variable {b l a p : ℕ} [NeZero (b+l)] (hD : 1 < b+l) (hd : 2+p = 2^a)
+ {R : Type*} [CommRing R] {Label : Type} [Fintype Label] (f : Label → R)
+ (hc' : 2^(b+l)*2^e < 2^w) (bound : NominationClock D hw hc' clock)
+ (pub : LeafAddress.Field → Word W) (arena : Arena)
+ (trace : Word W → Scratch W endAddr → List (Event W))
+ (prepared : Word W → Scratch W endAddr → Scratch W endAddr)
+ (cap : ℕ) (v : Position (b+l))
+ (z : (LeafArguments.state hD hd (2^e) w).network.Half (lanePositions (cursorCoordinateLabels b l) v))
+ (row : StoredCursorRow hD hd pub arena node saved cap v z)
+
+include row in
+/-- The true selected leaf job has the correct descriptor address and event
+choices. Every designated private histogram word retains its old value.
+This includes repeated visits with a nonzero preexisting histogram. -/
+theorem cursorHook_realizes
+ (cell : Label → {a : Word W // endAddr ≤ a.val})
+ (away : ∀ label j, (cell label).val.val < storage.base j ∨
+ storage.base j+storage.capacity ≤ (cell label).val.val)
+ (det : choiceBits (trace node saved) = [])
+ (prefixFrame : ∀ label, prepared node saved (cell label) = saved (cell label))
+ (room : ∀ j, (auxiliaryBank D hw hc' v (LeafArguments.buffers hD hd v z) j).length+clock ≤ storage.capacity) :
+ ∀ (code suffix : List Bool),
+ (∃ x, code = (cursorSiteReader hD hd D hw hc' f clock bound v z).encode x) →
+ ∃ actual, (cursorHook D hw hc' clock storage pub arena trace prepared).read node saved
+ (code++suffix) = some (actual,suffix) ∧ actual.enabled saved ∧
+ RealizesJob (fun old label => (old (cell label)).val) ⟨node.val,code,fun _ => 0⟩ actual := by
+ intro code suffix chosen
+ obtain ⟨x,hx⟩ := chosen
+ obtain ⟨actual,hit⟩ := (cursorHook_read_iff hD hd D hw hc' f clock bound storage pub arena trace
+ prepared node saved cap v z row (code++suffix) suffix).mpr ⟨x,congrArg (· ++ suffix) hx⟩
+ let input := physicalInput (b+l) e w pub arena trace prepared
+ have hp := physicalPosition_eq (H := 2^e) (w := w) hD hd pub node cap v row.width row.stride
+ row.radixB row.radixL row.address
+ have hb := physicalBuffers_eq hD hd arena node saved v z (by have := row.width; omega) row.fit row.stored
+ have capacity (j : Port 52 34) :
+ (auxiliaryBank D hw hc' (input node saved).pos (input node saved).buffers j).length+clock ≤ storage.capacity := by
+ change (auxiliaryBank D hw hc' (physicalPosition (b+l) pub node) (physicalBuffers (b+l) (2^e) w arena node saved) j).length+clock ≤ _
+ rw [hp,hb]
+ exact room j
+ obtain ⟨addr,enabled,consumed,frame⟩ := parser_observations D hw hc' storage input clock node saved
+ (code++suffix) suffix actual hit det capacity
+ refine ⟨actual,hit,(enabled saved).mpr rfl,⟨?_,(List.append_cancel_right consumed).symm,?_⟩⟩
+ · change actual.node = (node.val : Word W)
+ simp [addr]
+ · intro old h label
+ have eqn := (enabled old).mp h
+ subst old
+ change (actual.update saved (cell label)).val = (saved (cell label)).val + 0
+ rw [frame (cell label) (away label), show (input node saved).prepared (cell label) = _ from prefixFrame label,
+ Nat.add_zero]
+
+end Cursor
+end PairSimulation.LeafHandler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafRegisterBank.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafRegisterBank.lean
new file mode 100644
index 0000000000..b7eaa3dff1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafRegisterBank.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.PairSimulationLeafFill
+import OAI.Computability.VPVNP.PairSimulationLeafFieldCode
+
+/-! # Register wiring between the virtual validator's operand staging and scalar fill loop -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRegisterBank
+
+open RAMTape BurstRAM PrivateRAM LeafStartup StackMachine
+open scoped Fin.CommRing
+
+variable {K : Type} {k r : ℕ}
+
+/-- Input register names for the site dimensions, bucket, fuel, address and words, and the
+virtual machine's public operands. -/
+inductive Source (k : ℕ) where
+ | d | width | bucket | fuel | address | initial | header | operand (i : Fin k)
+ deriving DecidableEq, Fintype
+
+/-- The combined scalar-loader register bank, with fill-loop registers and a separate bank of
+source words. -/
+abbrev Reg (K : Type) (k : ℕ) := LeafFill.Reg K ⊕ Source k
+
+/-- Physical embedding of the fill-loop registers in the combined scalar-loader bank. -/
+def load (reg : Reg K k ↪ Fin r) : LeafFill.Reg K ↪ Fin r :=
+ ⟨fun j => reg (.inl j),fun _ _ h => Sum.inl.inj (reg.injective h)⟩
+
+/-- Wire each staging register to its scalar source, fill destination, or shared stack constant
+and temporary. -/
+def stagingName : Staging.Reg k → Reg K k
+ | .out .len => .inl .length
+ | .out .value => .inl .value
+ | .out .tmp => .inl (.pointers (.stack .tmp))
+ | .zero => .inl (.pointers (.stack .zero))
+ | .one => .inl (.pointers (.stack .one))
+ | .d => .inr .d
+ | .width => .inr .width
+ | .bucket => .inr .bucket
+ | .fuel => .inr .fuel
+ | .address => .inr .address
+ | .initial => .inr .initial
+ | .header => .inr .header
+ | .operand i => .inr (.operand i)
+
+private theorem stagingName_injective : Function.Injective (stagingName (K := K) (k := k)) := by
+ intro a b h
+ cases a <;> cases b <;> (try casesm* Staging.Out) <;> simp_all [stagingName]
+
+/-- The injective host placement of staging registers induced by their wiring into the
+scalar-loader bank. -/
+def stage (reg : Reg K k ↪ Fin r) : Staging.Reg k ↪ Fin r :=
+ ⟨fun j => reg (stagingName j),reg.injective.comp stagingName_injective⟩
+
+@[simp] theorem load_at (reg : Reg K k ↪ Fin r) (j : LeafFill.Reg K) : load reg j = reg (.inl j) := rfl
+
+@[simp] theorem stage_at (reg : Reg K k ↪ Fin r) (j : Staging.Reg k) : stage reg j = reg (stagingName j) := rfl
+
+/-- Physical placement of the validator's stack registers in the scalar-loader bank. -/
+abbrev stack (reg : Reg K k ↪ Fin r) := LeafFill.stack (load reg)
+
+theorem preserved (reg : Reg K k ↪ Fin r) (j : Register K) (hj : j ≠ .tmp) (o : Staging.Out) :
+ stack reg j ≠ stage reg (.out o) := by cases o <;> simp [stack,stagingName,hj]
+
+variable {w p : ℕ}
+
+/-- Staging writes only three scratch registers. The entire logical stack
+bank therefore retains its private cells and pointers. -/
+theorem staged_represents (reg : Reg K k ↪ Fin r) (L : Layout K w) (s : Stacks K)
+ (ls : List (Staging.Line k)) (pc : Fin p) (c : Config w p r) (rep : Represents L (stack reg) c s) :
+ Represents L (stack reg) {c with pc := pc,reg := ls.foldl (Staging.applyPhysical (stage reg)) c.reg} s := by
+ have keep (j : Register K) (hj : j ≠ .tmp) := Staging.physical_outside (stage reg) ls c.reg _
+ (preserved reg j hj)
+ exact ⟨(keep .one nofun).trans rep.unit,(keep .zero nofun).trans rep.zero,
+ fun a => (keep (.base a) nofun).trans (rep.bases a), fun a => (keep (.top a) nofun).trans (rep.tops a),rep.cells⟩
+
+end PairSimulation.LeafRegisterBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafRole.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafRole.lean
new file mode 100644
index 0000000000..25c1c94695
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafRole.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.PairSimulationLeafPlacement
+import OAI.Computability.VPVNP.PrivateRAMRegisterOperands
+
+/-! # The eleven-public-word leaf segment of the final-vertex program -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRole
+
+open BurstRAM PrivateRAM RegisterOperands
+open scoped Classical
+
+set_option maxRecDepth 4000
+
+variable {p r w : ℕ} (pc : Label → Fin p) (dfs : Fin 9 ↪ Fin r) (priv : Private ↪ Fin r)
+ (apart : Apart dfs priv) (ret : Fin p)
+
+/-- The ten operand values appear in private registers on the native machine.
+The caller's original eleven public words occupy the other side of the
+verification machine's public bank. -/
+def operands : Fin (10+11) → Operand r 11 :=
+ Fin.addCases (fun i => .register (values priv i)) Operand.public
+
+/-- The position of a leaf operand in the ten geometry slots preceding the eleven original
+vertex operands. -/
+def pubSlot (j : LeafImage.Pub) : Fin (10+11) := (LeafGeometryLoad.slot j).castAdd 11
+
+/-- A verifier body instruction with its registers placed in the host, calls directed to leaf
+body labels and returns directed to the caller. -/
+noncomputable def body (j : LeafImage.Label) : Instr 5 (p+p) r (10+11) :=
+ LeafImage.instruction (enter ∘ bodyPC pc) (bodyReg dfs priv apart) pubSlot (caller ret) j
+
+/-- Physical rows emit only register copies for the ten geometry fields. -/
+noncomputable def instruction : Label → Instr 5 p r 11
+ | .inl j => LeafGeometryLoad.instruction (loadPC pc) dfs (ports priv) (priv .cursor) (bodyPC pc (.address 0)) j
+ | .inr j => translate fold (operands priv) (body pc dfs priv apart ret j)
+
+attribute [local irreducible] labelCount privateCount
+private noncomputable def segmentRow (place : Fin labelCount → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (fresh : Fin privateCount ↪ Fin r) (ret : Fin p) (i : Fin labelCount) : Instr 5 p r 11 :=
+ let priv := privateIndex.toEmbedding.trans fresh
+ if h : Apart dfs priv then instruction (place ∘ labelIndex) dfs priv h ret (labelIndex.symm i) else .reject
+
+/-- The actual disjoint placement supplied by the vertex table uses the body
+and geometry rows. An aliased placement outside that ABI rejects. -/
+noncomputable abbrev segment : VertexImage.Segment where
+ count := labelCount
+ privateRegs := privateCount
+ entry := labelIndex (.inl (.inl ()))
+ row place dfs _ fresh ret i := segmentRow place dfs fresh ret i
+
+private theorem segment_count : segment.count = labelCount := rfl
+
+private theorem segment_regs : segment.privateRegs = privateCount := rfl
+
+-- Explicit transports let the type checker compare the segment bounds directly,
+-- without enumerating the finite types of leaf labels and registers.
+theorem segment_row (place : Fin labelCount → Fin p) (saved : VertexImage.Saved ↪ Fin r)
+ (fresh : Fin privateCount ↪ Fin r) (h : Apart dfs (privateIndex.toEmbedding.trans fresh))
+ (j : Label) :
+ segment.row (p := p) (r := r) (place ∘ Fin.cast segment_count) dfs saved
+ ((finCongr segment_regs).toEmbedding.trans fresh) ret
+ (Fin.cast segment_count.symm (labelIndex j)) =
+ instruction (place ∘ labelIndex) dfs (privateIndex.toEmbedding.trans fresh) h ret j := by
+ change segmentRow place dfs fresh ret (labelIndex j) = _
+ unfold segmentRow
+ rw [dite_eq_left h,labelIndex.symm_apply_apply]
+
+/-- The eleven-operand host machine contains every leaf instruction at the chosen label and
+resized to its word width. -/
+def Contains (A : Machine w p r 11) : Prop :=
+ ∀ j, A.code (pc j) = (instruction pc dfs priv apart ret j).resize w
+
+theorem load_linked {A : Machine w p r 11} (h : Contains pc dfs priv apart ret A)
+ (i : LeafGeometryLoad.Label) :
+ A.code (loadPC pc i) = LeafGeometryLoad.instruction (loadPC pc) dfs (ports priv) (priv .cursor)
+ (bodyPC pc (.address 0)) i :=
+ (h (.inl i)).trans (LeafGeometryLoad.resize_instruction ..)
+
+/-- Host addresses of the leaf body, after its geometry reload. -/
+def inside := Set.range (bodyPC pc)
+
+noncomputable instance : DecidablePred (inside pc) := fun _ => Classical.propDecidable _
+
+/-- Verifier body code at a placed leaf-body label, with rejection at indices outside that
+body. -/
+noncomputable def text (i : Fin p) : Instr w (p+p) r (10+11) :=
+ if h : inside pc i then (body pc dfs priv apart ret h.choose).resize w else .reject
+
+theorem text_at (inj : Function.Injective pc) (j : LeafImage.Label) :
+ text pc dfs priv apart ret (bodyPC pc j) = (body pc dfs priv apart ret j).resize w := by
+ have h : inside pc (bodyPC pc j) := ⟨j,rfl⟩
+ have eqn : h.choose = j := Sum.inr.inj (inj h.choose_spec)
+ simp [text,h,eqn]
+
+variable (A : Machine w p r 11) (data : Fin 10 → Word w)
+
+/-- Prepend the ten loaded geometry words to the eleven public operands of the host vertex
+machine. -/
+def publicData : Fin (10+11) → Word w := Fin.addCases data A.publicData
+
+/-- The shadow machine that executes the leaf body using the extended operand table and
+preserves access to the host caller. -/
+noncomputable def verification : Machine w (p+p) r (10+11) :=
+ shadow A (inside pc) (text pc dfs priv apart ret) (publicData A data) (Fin.natAdd 10)
+
+theorem verification_linked (inj : Function.Injective pc) :
+ LeafImage.Linked (enter ∘ bodyPC pc) (bodyReg dfs priv apart) pubSlot (caller ret)
+ (verification pc dfs priv apart ret A data) := by
+ apply LeafImage.linked
+ intro j
+ change (shadow ..).code (enter (bodyPC pc j)) = _
+ rw [shadow_code_enter _ _ _ _ _ _ (show inside pc (bodyPC pc j) from ⟨j,rfl⟩)]
+ exact text_at pc dfs priv apart ret inj j
+
+theorem physical_rows (inj : Function.Injective pc) (h : Contains pc dfs priv apart ret A)
+ (i : Fin p) (hi : inside pc i) :
+ A.code i = translate fold (operands priv) (text pc dfs priv apart ret i) := by
+ rcases hi with ⟨j,rfl⟩
+ rw [text_at pc dfs priv apart ret inj j]
+ exact (h (.inr j)).trans (translate_resize ..)
+
+theorem agreement (c : Config w p r) (h : ∀ i, c.reg (values priv i) = data i) :
+ Agrees (operands priv) (publicData A data) A.publicData c.reg := by
+ intro i
+ refine Fin.addCases (fun j => ?_) (fun j => ?_) i
+ · simpa only [operands,publicData,Fin.addCases_left,Operand.value] using h j
+ · simp only [operands,publicData,Fin.addCases_right,Operand.value]
+
+end PairSimulation.LeafRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafRoleExecution.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafRoleExecution.lean
new file mode 100644
index 0000000000..56603f1629
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafRoleExecution.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.PairSimulationLeafRole
+
+/-! # Exact leaf calls after loading the private geometry record -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRole
+
+open BurstRAM PrivateRAM RegisterOperands PrimedCounter.GuessWord DFS
+open scoped Classical Fin.CommRing
+
+variable {p r w endAddr : ℕ} (pc : Label → Fin p) (dfs : Fin 9 ↪ Fin r) (priv : Private ↪ Fin r)
+ (apart : Apart dfs priv) (ret : Fin p) (A : Machine w p r 11) (data : Fin 10 → Word w)
+
+private theorem public_ok (i : Fin 11) : publicData A data (Fin.natAdd 10 i) = A.publicData i :=
+ Fin.addCases_right ..
+
+/-- No verifier body instruction writes to any of the ten registers containing the loaded
+geometry operands. -/
+def PreservesOperands : Prop :=
+ ∀ j : LeafImage.Label, ∀ i : Fin 10, destination (body pc dfs priv apart ret j) ≠ some (values priv i)
+
+private theorem frame (inj : Function.Injective pc) (keep : PreservesOperands pc dfs priv apart ret)
+ (q : Fin p) (inside' : inside pc q) (n : Fin (10+11)) (a : Fin r)
+ (eqn : operands priv n = .register a) :
+ destination (text (w := w) pc dfs priv apart ret q) ≠ some a := by
+ rcases inside' with ⟨j,rfl⟩
+ rw [text_at pc dfs priv apart ret inj j,destination_resize]
+ revert eqn
+ refine Fin.addCases (fun i => ?_) (fun i => ?_) n
+ · simp only [operands,Fin.addCases_left,Operand.register.injEq]
+ rintro rfl; exact keep j i
+ · simp [operands]
+
+theorem execute_body (inj : Function.Injective pc) (h : Contains pc dfs priv apart ret A)
+ (keep : PreservesOperands pc dfs priv apart ret) (c : Config w p r)
+ (ready : ∀ i, c.reg (values priv i) = data i) (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute (verification pc dfs priv apart ret A data).program fuel (enterConfig c) m bits =
+ execute A.program fuel c m bits :=
+ execute_enter A (inside pc) (text pc dfs priv apart ret) (publicData A data) (Fin.natAdd 10)
+ (public_ok A data) (operands priv) (physical_rows pc dfs priv apart ret A inj h)
+ (frame pc dfs priv apart ret inj keep) c (agreement priv A data c ready) fuel m bits
+
+theorem execute_return {c : Config w (p+p) r} (hr : c.pc = caller ret)
+ (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute (verification pc dfs priv apart ret A data).program fuel c m bits =
+ execute A.program fuel (project c) m bits :=
+ execute_caller_of_pc A (inside pc) (text pc dfs priv apart ret) (publicData A data) (Fin.natAdd 10)
+ (public_ok A data) c hr fuel m bits
+
+private def ticks (w : ℕ) := List.replicate 21 (.tick : Event w)
+
+private theorem ticks_bits : choiceBits (ticks w) = [] := rfl
+
+/-- Include the reload's twenty-one ticks in the actual visit. The read job is
+enabled at the scratch image from which it was decoded. -/
+def withReload (P : HookParser w endAddr) : HookParser w endAddr where
+ read node saved bits := (P.read node saved bits).map fun (job,tail) =>
+ (⟨job.node,ticks w ++ job.trace,fun s => s = saved ∧ job.enabled s,job.update⟩,tail)
+
+private theorem reload {c : Config w p r} (h : Contains pc dfs priv apart ret A)
+ (base : ℕ) (saved : LeafGeometryLoad.Stored endAddr base c.privateMem data)
+ (entry : c.pc = loadPC pc (.inl ())) (endReg : c.reg (dfs 6) = (endAddr : Word w))
+ (one : c.reg (dfs 3) = 1) :
+ ∃ ready, Prefix A c (ticks w) ready ∧ ready.pc = bodyPC pc (.address 0) ∧
+ (∀ i, ready.reg (values priv i) = data i) ∧ ready.privateMem = c.privateMem ∧
+ ready.persistent = c.persistent ∧ ∀ i, ready.reg (dfs i) = c.reg (dfs i) := by
+ obtain ⟨out,path,entry',ready,mem,state,other⟩ := LeafGeometryLoad.run (loadPC pc) dfs (ports priv)
+ (priv .cursor) (bodyPC pc (.address 0)) A (load_linked pc dfs priv apart ret h) endAddr base data c entry
+ endReg one saved (fun j => priv.injective.ne (by intro e; cases e)) (fun j => apart _ _) (apart _ _)
+ exact ⟨out,path,entry',ready,mem,state,fun i => other _ (apart i _) (fun _ => apart i _)⟩
+
+open private returns_prefix from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+/-- Transfer the proved semantic parser to the actual eleven-operand image.
+The continuation may execute arbitrary instructions and may revisit this
+descriptor with different registers and a new choice suffix. -/
+theorem exact (inj : Function.Injective pc) (h : Contains pc dfs priv apart ret A)
+ (keep : PreservesOperands pc dfs priv apart ret) (P : HookParser w endAddr)
+ (domain : Word w → Scratch w endAddr → Prop) (base : ℕ) (m : Memory w)
+ (stored : ∀ node (c : Config w p r), domain node (scratch endAddr c.privateMem) →
+ LeafGeometryLoad.Stored endAddr base c.privateMem data)
+ (semantic : P.ExactOn domain (verification pc dfs priv apart ret A data)
+ (enter (bodyPC pc (.address 0))) (caller ret) dfs m) :
+ (withReload P).ExactOn domain A (loadPC pc (.inl ())) ret dfs m := by
+ have eval := execute_body pc dfs priv apart ret A data inj h keep
+ constructor
+ · intro node saved domain' bits actual tail read
+ obtain ⟨⟨job,rest⟩,source,e⟩ := Option.map_eq_some_iff.mp read
+ cases e
+ obtain ⟨hn,enabled,split,call⟩ := semantic.success node saved domain' bits job _ source
+ refine ⟨hn,⟨rfl,enabled⟩,?_,?_⟩
+ · simpa only [PrimedInputRAM.Flow.choiceBits_append,ticks_bits,List.nil_append] using split
+ · intro c top pending enabled' entry nodeAt stack limit topAt endAt one
+ obtain ⟨eqn,jobEnabled⟩ := enabled'
+ have cached := stored node c (eqn ▸ domain')
+ obtain ⟨ready,pre,readyPC,bank,mem,state,regs⟩ := reload pc dfs priv apart ret A data h base cached entry endAt one
+ obtain ⟨out,done,nodeDone,topDone,endDone,oneDone,stateDone,stackDone,scratchDone,exec⟩ :=
+ call (enterConfig ready) top pending (mem ▸ jobEnabled) (congrArg enter readyPC)
+ ((regs 7).trans nodeAt) (mem ▸ stack) limit ((regs 5).trans topAt) ((regs 6).trans endAt) ((regs 3).trans one)
+ refine ⟨project out,?_,nodeDone,topDone,endDone,oneDone,stateDone.trans state,stackDone,?_,?_⟩
+ · change fold out.pc = ret; rw [done,fold_caller]
+ · exact scratchDone.trans (congrArg (job.update ∘ scratch endAddr) mem)
+ · intro fuel bs
+ change execute A.program (fuel+(ticks w ++ job.trace).length) c m (choiceBits (ticks w ++ job.trace) ++ bs) = _
+ rw [List.length_append, show fuel + ((ticks w).length+job.trace.length) =
+ (fuel+job.trace.length)+(ticks w).length by omega]
+ simp only [PrimedInputRAM.Flow.choiceBits_append,ticks_bits,List.nil_append]
+ have hp := pre.execute (fuel+job.trace.length) m (choiceBits job.trace ++ bs)
+ simp only [ticks_bits,List.nil_append] at hp
+ rw [hp,← eval ready bank,exec,execute_return pc dfs priv apart ret A data done]
+ simp [Option.map_map,Function.comp_def,List.append_assoc]
+ · intro node bits c top pending dom entry nodeAt stack limit topAt endAt one read
+ have bad : P.read node (scratch endAddr c.privateMem) bits = none := by
+ simpa only [withReload,Option.map_eq_none_iff] using read
+ obtain ⟨ready,pre,readyPC,bank,mem,_,regs⟩ := reload pc dfs priv apart ret A data h base (stored node c dom) entry endAt one
+ have deny := semantic.reject node bits (enterConfig ready) top pending (mem ▸ dom) (congrArg enter readyPC)
+ ((regs 7).trans nodeAt) (mem ▸ stack) limit ((regs 5).trans topAt) ((regs 6).trans endAt) ((regs 3).trans one)
+ (mem ▸ bad)
+ intro ok
+ have after := (returns_prefix (fun fuel => by
+ simpa only [ticks_bits,List.nil_append] using pre.execute fuel m bits)).mp ok
+ obtain ⟨fuel,rep,accept⟩ := after
+ exact deny ⟨fuel,rep,(eval ready bank fuel m bits).trans accept⟩
+
+end PairSimulation.LeafRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafRoleHandler.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafRoleHandler.lean
new file mode 100644
index 0000000000..a39657ecbd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafRoleHandler.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.PairSimulationLeafRoleExecution
+import OAI.Computability.VPVNP.PairSimulationLeafImageHandler
+import OAI.Computability.VPVNP.PairSimulationLeafImageWrites
+
+/-!
+# Exactness of the cursor-leaf segment in the eleven-operand vertex table
+
+The physical domain contains the node packet, the 38 cached auxiliary operands
+and the ten geometry words reached through the DFS end pointer. Together these
+determine the parser on the actual private memory at entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRole
+
+open BurstRAM PrivateRAM RegisterOperands PrimedCounter.GuessWord DFS NodeArguments CursorNetwork
+open LeafStartup
+open scoped Fin.CommRing Classical
+
+set_option synthInstance.maxSize 10000
+
+variable {p r w endAddr : ℕ} (pc : Label → Fin p) (dfs : Fin 9 ↪ Fin r) (priv : Private ↪ Fin r)
+ (apart : Apart dfs priv) (ret : Fin p) (A : Machine w p r 11) (data : Fin 10 → Word w)
+
+/-- The domain's typed scratch contains the complete physical record used at entry. -/
+theorem stored_actual (base : ℕ) (mem : Word w → Word w) (lo : endAddr ≤ base)
+ (hi : base+10 ≤ 2^w)
+ (h : LeafGeometryLoad.Stored endAddr base (rawScratch (scratch endAddr mem)) data) :
+ LeafGeometryLoad.Stored endAddr base mem data := by
+ have lower (n : ℕ) (hn : endAddr ≤ n) (hw : n < 2^w) : endAddr ≤ (n : Word w).val := by
+ rwa [Fin.val_natCast,Nat.mod_eq_of_lt hw]
+ constructor
+ · simpa only [rawScratch,lower endAddr (le_refl _) (by omega),↓reduceDIte,scratch] using h.pointer
+ · intro i
+ have small := i.isLt
+ simpa only [rawScratch,lower (base+i.val) (by omega) (by omega),↓reduceDIte,scratch] using h.values_at i
+
+/-- Read the decoder's row or shadow field from its corresponding slot in the ten geometry
+words. -/
+def addressFields (j : LeafAddress.Field) := data (LeafGeometryLoad.slot (.address j))
+
+private theorem verification_fields :
+ LeafVisit.fields (M := verification pc dfs priv apart ret A data) pubSlot = addressFields data := by
+ funext j
+ simp only [LeafVisit.fields,Function.comp_apply,verification,shadow,publicData,pubSlot,addressFields,Fin.addCases_left]
+
+variable {L : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout L n a H w}
+ (D : PrimedCounter.Data Q s) {b l e degree pad : ℕ} [NeZero (b+l)] (hD : 1 < b+l)
+ (hd : 2+pad=2^degree) (budget : ProcessorBudget n (b+l) e w)
+ (R : LeafArena.Regions) (cap base : ℕ) (fit : R.stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ (m : Memory w) (clock : ℕ)
+
+/-- The parser uses the field words stored in the geometry record. -/
+noncomputable def parser : HookParser w endAddr :=
+ withReload (LeafHandler.parser D budget.tags budget.capFits (LeafVisit.storage R fit)
+ (LeafVisit.loaded D budget R fit (addressFields data) m) clock)
+
+/-- The saved scratch and node satisfy the leaf visit's input conditions, and the same scratch
+stores the geometry record used to decode its address. -/
+def Domain (node : Word w) (saved : Scratch w endAddr) :=
+ LeafVisit.Domain (e := e) D hD hd R cap (addressFields data) node saved ∧
+ LeafGeometryLoad.Stored endAddr base (rawScratch saved) data
+
+theorem native_exact (inj : Function.Injective pc) (rows : Contains pc dfs priv apart ret A)
+ (op : LeafFront.Operands (LeafImage.front (enter ∘ bodyPC pc) (bodyReg dfs priv apart) pubSlot (caller ret))
+ (verification pc dfs priv apart ret A data) m D R b l cap)
+ (hsize : data (LeafGeometryLoad.slot .size) = (n : Word w)) (arenaLow : endAddr ≤ R.arguments.start)
+ (geometryLow : endAddr ≤ base) (geometryFits : base+10 ≤ 2^w)
+ (time : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w),
+ steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ clock)
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length+clock ≤ n^40) :
+ (parser (endAddr := endAddr) data D budget R fit m clock).ExactOn (Domain (e := e) data D hD hd R cap base)
+ A (loadPC pc (.inl ())) ret dfs m := by
+ let V := verification pc dfs priv apart ret A data
+ have size : V.publicData (pubSlot .size) = (n : Word w) := by
+ simpa only [V,verification,shadow,publicData,pubSlot,Fin.addCases_left] using hsize
+ have semantic := LeafVisit.image_exact (M := V) (endAddr := endAddr) D hD hd budget R cap fit
+ (enter ∘ bodyPC pc) (bodyReg dfs priv apart) pubSlot (caller ret) m clock
+ (verification_linked pc dfs priv apart ret A data inj) op size arenaLow time room
+ unfold LeafVisit.leafParser at semantic
+ rw [verification_fields pc dfs priv apart ret A data] at semantic
+ have keep : PreservesOperands pc dfs priv apart ret := fun j i h =>
+ value_outside dfs priv apart i (LeafImage.destination_mem _ _ _ _ j _ h)
+ apply exact pc dfs priv apart ret A data inj rows keep _ _ base m
+ · intro node c h
+ exact stored_actual data base c.privateMem geometryLow geometryFits h.2
+ · exact ⟨fun node s h => semantic.success node s h.1,
+ fun node bs c top pending h => semantic.reject node bs c top pending h.1⟩
+
+end PairSimulation.LeafRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafRoleJobs.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafRoleJobs.lean
new file mode 100644
index 0000000000..96ecc7d5ca
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafRoleJobs.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSegment
+import OAI.Computability.VPVNP.PairSimulationLeafRealization
+import OAI.Computability.VPVNP.PairSimulationLeafImageFrame
+
+/-! # The selected cursor occurrence on the terminal vertex's native leaf role -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRole
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork LeafStartup DFS
+open LocalHistory LeafHandler
+open scoped Fin.CommRing
+
+variable {w : ℕ} {L : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout L n a H w}
+ (D : PrimedCounter.Data Q s) {b l e degree pad endAddr : ℕ} [NeZero (b+l)]
+ (hD : 1 < b+l) (hd : 2+pad=2^degree) (budget : ProcessorBudget n (b+l) e w)
+ {K : Type*} [CommRing K] {Label : Type} [Fintype Label] (f : Label → K)
+ (clock : ℕ) (bound : NominationClock D budget.tags budget.capFits clock)
+ (data : Fin 10 → Word w) (R : LeafArena.Regions) (cap : ℕ)
+ (fit : R.stackBase + Fintype.card ScalarPort * n^40 < 2^w)
+ (m : Memory w) (node : Word w) (saved : Scratch w endAddr)
+ (v : Position (b+l)) (z : (LeafArguments.state hD hd (2^e) w).network.Half
+ (lanePositions (cursorCoordinateLabels b l) v))
+ (row : StoredCursorRow hD hd (addressFields data) R.arguments node saved cap v z)
+
+include row in
+/-- Each selected source occurrence is accepted by the actual role reader
+with the same code and suffix. The reload is deterministic and the physical
+histogram retains every component, including nonzero incoming counts. -/
+theorem selected_job (cell : Label → {a : Word w // endAddr ≤ a.val})
+ (below : ∀ i, (cell i).val.val < R.stackBase)
+ (room : ∀ j, (auxiliaryBank D budget.tags budget.capFits v (LeafArguments.buffers hD hd v z) j).length
+ + clock ≤ n^40) (code suffix : List Bool)
+ (selected : ∃ x, code = (cursorSiteReader hD hd D budget.tags budget.capFits f clock bound v z).encode x) :
+ ∃ actual, (parser data D budget R fit m clock).read node saved (code++suffix) = some (actual,suffix) ∧
+ actual.enabled saved ∧ RealizesJob (fun old i => (old (cell i)).val) ⟨node.val,code,fun _ => 0⟩ actual := by
+ let L := LeafVisit.storage R fit
+ let fld := addressFields data
+ let inp := LeafVisit.loaded (endAddr := endAddr) D budget R fit fld m
+ let tr := fun n s => (inp n s).trace
+ let prep := fun n s => (inp n s).prepared
+ have away (i : Label) (j : ScalarPort) : (cell i).val.val < L.base j ∨ L.base j+L.capacity ≤ (cell i).val.val :=
+ Or.inl ((below i).trans_le (R.stack_above _ _ fit j))
+ obtain ⟨j,hit,en,real⟩ := cursorHook_realizes D budget.tags L clock node saved hD hd f budget.capFits
+ bound fld R.arguments tr prep cap v z row cell away
+ (LeafVisit.trace_bits D budget m fld _ _) (fun i => LeafVisit.loaded_below D budget R fit m fld node saved
+ (cell i) (below i)) room code suffix selected
+ let extended : VisitPath w endAddr :=
+ ⟨j.node,List.replicate 21 .tick ++ j.trace,fun s => s = saved ∧ j.enabled s,j.update⟩
+ change (LeafHandler.parser D budget.tags budget.capFits L inp clock).read node saved (code++suffix) =
+ some (j,suffix) at hit
+ refine ⟨extended,?_,⟨rfl,en⟩,⟨real.address,?_,fun s h i => real.counts s h.2 i⟩⟩
+ · change ((LeafHandler.parser D budget.tags budget.capFits L inp clock).read node saved (code++suffix)).map _ = _
+ rw [hit]; rfl
+ · exact real.bits
+
+/-- Every successful physical leaf, independently of its chosen occurrence,
+preserves all sibling packets, geometry and histogram cells before the stacks. -/
+theorem below_stack (bits tail : List Bool) (job : VisitPath w endAddr)
+ (hit : (parser data D budget R fit m clock).read node saved bits = some (job,tail))
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length + clock ≤ n^40)
+ (i : {a : Word w // endAddr ≤ a.val}) (before : i.val.val < R.stackBase) :
+ job.update saved i = saved i := by
+ let source : HookParser w endAddr := LeafHandler.parser D budget.tags budget.capFits (LeafVisit.storage R fit)
+ (LeafVisit.loaded D budget R fit (addressFields data) m) clock
+ obtain ⟨old,read,_,upd,_,_,_⟩ := reload_read source node saved bits tail job hit
+ let measure : Machine w 1 0 10 := ⟨0,fun _ => .reject,data⟩
+ rw [upd]
+ exact LeafVisit.read_below (M := measure) D budget R fit LeafGeometryLoad.slot m clock node saved bits read room i before
+
+end PairSimulation.LeafRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafRouteFork.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafRouteFork.lean
new file mode 100644
index 0000000000..c245e3886a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafRouteFork.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.PairSimulationRouteValidator
+import OAI.Computability.VPVNP.PairSimulationLeafHandler
+
+/-! # Returning from the route scan or entering the private stack verifier -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRouteFork
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork PrimedCounter.GuessWord DFS
+open scoped Fin.CommRing
+
+variable {d H w W p r k : ℕ} [NeZero d]
+ {M : Machine W p r k} {P : RouteSchedule.Program p r}
+ {c : Config W p r} (v : Position d) (buf : Buffers d H w) (base : LocalPort → Word W)
+
+/-- Once the native scan passes, its preserved cursor determines whether
+the local factor returns immediately or executes the virtual validator. -/
+theorem after_scan {init transit : Fin p} {t : ℕ}
+ (inputs : RouteSchedule.Inputs P.reg v buf base c)
+ (fit : d ≤ 2^W)
+ (row : M.code P.yes = .jumpEq (P.reg 0) (P.reg 17) init transit)
+ (stop : M.code P.no = .reject) {u : Config W p r}
+ (scan : Prefix M c (List.replicate t .tick) u)
+ (status : u.pc = (if routeAccept H w v (readBuffer buf) then P.yes else P.no))
+ (frame : RouteRange.Frame (RouteSchedule.Keep P.reg) c u) :
+ (routeAccept H w v (readBuffer buf) = true →
+ ∃ out, Prefix M c (List.replicate (t+1) .tick) out ∧
+ out.pc = (if v.1 = 0 then init else transit) ∧
+ RouteRange.Frame (RouteSchedule.Keep P.reg) c out) ∧
+ (routeAccept H w v (readBuffer buf) = false →
+ ∀ mem bits, ¬ Returns M c mem bits) := by
+ constructor
+ · intro good
+ have hp : u.pc = P.yes := by simpa only [good,↓reduceIte] using status
+ have hu := inputs.transfer frame
+ have eqz : u.reg (P.reg 0) = u.reg (P.reg 17) ↔ v.1 = 0 := by
+ rw [hu.cursor,hu.zero]
+ constructor
+ · intro eq
+ apply Fin.ext
+ have hv := congrArg Fin.val eq
+ rw [Fin.val_natCast,Nat.mod_eq_of_lt (v.1.isLt.trans_le fit)] at hv
+ exact hv
+ · rintro hz
+ simp [hz]
+ let out := {u with pc := if v.1=0 then init else transit}
+ have step : M.program.step u = .localStep out := by
+ simp only [Machine.program,hp,row,Instr.run,eqz,out]
+ refine ⟨out,?_,rfl,⟨frame.regs,frame.memory,frame.persistent⟩⟩
+ rw [List.replicate_add]
+ exact scan.append (.tick step (.nil _))
+ · intro bad mem bits ok
+ obtain ⟨fuel,rep,hr⟩ := ok
+ have hp : u.pc = P.no := by simpa only [bad,Bool.false_eq_true,↓reduceIte] using status
+ have nope := MapLookup.reject_after_ticks scan (fun _ h => List.eq_of_mem_replicate h) (hp ▸ stop) fuel mem bits
+ rw [nope] at hr; contradiction
+
+/-- The actual fixed cursor route checker followed by the returning branch,
+at the application's word widths and record capacities. -/
+theorem native {e n : ℕ} {init transit : Fin p} (budget : ProcessorBudget n d e w) (host : w ≤ W)
+ (hl : P.Linked M) (v : Position d) (buf : Buffers d (2^e) w) (base : LocalPort → Word W)
+ (atPC : c.pc = P.pc 0) (inputs : RouteSchedule.Inputs P.reg v buf base c)
+ (width : c.reg (P.reg 21) = ((8*w : ℕ) : Word W))
+ (row : M.code P.yes = .jumpEq (P.reg 0) (P.reg 17) init transit)
+ (stop : M.code P.no = .reject) :
+ (routeAccept (2^e) w v (readBuffer buf) = true →
+ ∃ out, Prefix M c (List.replicate (RouteSchedule.routeTicks W v (2^e) w+1) .tick) out ∧
+ out.pc = (if v.1 = 0 then init else transit) ∧ RouteRange.Frame (RouteSchedule.Keep P.reg) c out) ∧
+ (routeAccept (2^e) w v (readBuffer buf) = false → ∀ mem bits, ¬ Returns M c mem bits) := by
+ obtain ⟨hd,hs,ht⟩ := RouteSchedule.hostFits budget host
+ obtain ⟨out,path,pc,frame⟩ := RouteSchedule.native_exact hl v buf base c atPC inputs width hd hs ht
+ exact after_scan v buf base inputs (hd.le.trans (Nat.lt_two_pow_self.le)) row stop path pc frame
+
+end PairSimulation.LeafRouteFork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarLoad.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarLoad.lean
new file mode 100644
index 0000000000..7afb35031e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarLoad.lean
@@ -0,0 +1,185 @@
+import OAI.Computability.VPVNP.PairSimulationLeafStartup
+import OAI.Computability.VPVNP.PairSimulationPrivateFields
+import OAI.Computability.VPVNP.PairSimulationStackMemory
+import OAI.Computability.VPVNP.LiveHeaderBits
+
+/-!
+# Native private writes for the virtual validator's scalar stack fields
+
+A six-row loop writes one private word per stack cell, in increasing address
+order. For a binary word the loop counts down the bit position. For a unary
+tally it writes the low bit of the unchanged input word on each iteration.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafScalarLoad
+
+open BurstRAM PrivateRAM PrimedInputRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Select either the successive bits of a binary word or repeated copies of its low bit for a
+unary tally. -/
+inductive Mode where | binary | tally deriving DecidableEq
+
+/-- Read bit index `i` of the source word in binary mode, or bit zero in tally mode. -/
+def bit (mode : Mode) (value : Word w) (i : ℕ) : Bool :=
+ value.val.testBit (if mode = .tally then 0 else i)
+
+/-- Order in private memory, starting at the port base. -/
+def payload (mode : Mode) (value : Word w) : ℕ → List Bool
+ | 0 => []
+ | len+1 => bit mode value len :: payload mode value len
+
+@[simp] theorem payload_length (mode : Mode) (value : Word w) (len : ℕ) :
+ (payload mode value len).length = len := by induction len <;> simp_all [payload]
+
+private theorem payload_get (mode : Mode) (value : Word w) (len : ℕ)
+ (i : ℕ) (hi : i < len) :
+ (payload mode value len)[i]'(by simpa using hi) = bit mode value (len-1-i) := by
+ induction len generalizing i with
+ | zero => omega
+ | succ n ih =>
+ cases i with
+ | zero => simp [payload]
+ | succ i =>
+ simp only [payload, List.getElem_cons_succ]
+ exact (ih i (by omega)).trans (by congr 1; omega)
+
+theorem payload_word {a : ℕ} (v : Word a) (value : Word w) (h : value.val = v.val) :
+ payload .binary value a = (wordBits v).reverse := by
+ apply List.ext_getElem (by simp)
+ intro i hi hj
+ rw [payload_get .binary value a i (by simpa using hi), List.getElem_reverse]
+ simp only [wordBits, List.length_ofFn, List.getElem_ofFn, bit, reduceCtorEq, ↓reduceIte, h]
+ exact LiveHeader.testBit_wordBits v ⟨a-1-i,by simp at hi; omega⟩
+
+theorem payload_tally (len : ℕ) (hw : 0 < w) :
+ payload .tally (1 : Word w) len = List.replicate len true := by
+ induction len with
+ | zero => rfl
+ | succ n ih => simp [payload, bit, ih, hw, List.replicate_succ]
+
+/-- Registers hold destination, remaining length, value, zero, one and scratch. -/
+def instruction (mode : Mode) (pc : Fin 6 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) :
+ Fin 6 → Instr w p r k :=
+ ![.jumpEq (reg 1) (reg 3) done (pc 1),
+ .binary .sub (reg 1) (reg 1) (reg 4) (pc 2),
+ .binary .shiftRight (reg 5) (reg 2) (reg (if mode = .tally then 3 else 1)) (pc 3),
+ .binary .bitAnd (reg 5) (reg 5) (reg 4) (pc 4),
+ .storePrivate (reg 0) (reg 5) (pc 5), .binary .add (reg 0) (reg 0) (reg 4) (pc 0)]
+
+theorem resize_instruction (mode : Mode) (pc : Fin 6 → Fin p) (reg : Fin 6 ↪ Fin r)
+ (done : Fin p) (i : Fin 6) : (instruction (w := 1) (k := k) mode pc reg done i).resize w =
+ instruction mode pc reg done i := by fin_cases i <;> rfl
+
+/-- The six host instructions at the designated labels implement the scalar write loop for the
+chosen mode and continuation. -/
+def Linked (M : Machine w p r k) (mode : Mode) (pc : Fin 6 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) :=
+ ∀ i, M.code (pc i) = instruction mode pc reg done i
+
+variable {mode : Mode} {M : Machine w p r k} {pc : Fin 6 → Fin p} {reg : Fin 6 ↪ Fin r} {done : Fin p}
+
+/-- The scalar loop exits at its continuation with all bits stored starting at `dst`, the
+destination advanced and the remaining count zero. Only its destination, count and
+temporary registers can change. -/
+structure Result (reg : Fin 6 ↪ Fin r) (done : Fin p) (c out : Config w p r) (dst : ℕ) (xs : List Bool) : Prop where
+ pc : out.pc = done
+ destination : out.reg (reg 0) = ((dst+xs.length : ℕ) : Word w)
+ remaining : out.reg (reg 1) = 0
+ frame : ∀ i, i ≠ reg 0 → i ≠ reg 1 → i ≠ reg 5 → out.reg i = c.reg i
+ memory : out.privateMem = PrivateFields.storeBits dst xs c.privateMem
+ persistent : out.persistent = c.persistent
+
+private theorem step_at (hl : Linked M mode pc reg done) (i : Fin 6) (c : Config w p r) (h : c.pc = pc i) :
+ M.program.step c = (instruction mode pc reg done i).run M.publicData c := by
+ change (M.code c.pc).run _ _ = _
+ rw [h,hl i]
+
+private theorem iteration (hl : Linked M mode pc reg done) (hw : 0 < w) (c : Config w p r)
+ (hc : c.pc = pc 0) (n : ℕ) (fit : n+1 < 2^w) (hlen : c.reg (reg 1) = ((n+1 : ℕ) : Word w))
+ (hz : c.reg (reg 3) = 0) (ho : c.reg (reg 4) = 1) :
+ ∃ next, Prefix M c (List.replicate 6 .tick) next ∧ next.pc = pc 0 ∧
+ next.reg (reg 0) = c.reg (reg 0)+1 ∧ next.reg (reg 1) = (n : Word w) ∧
+ (∀ i, i ≠ reg 0 → i ≠ reg 1 → i ≠ reg 5 → next.reg i = c.reg i) ∧
+ next.privateMem = Function.update c.privateMem (c.reg (reg 0)) (encodeBit w (bit mode (c.reg (reg 2)) n)) ∧
+ next.persistent = c.persistent := by
+ let c₁ := {c with pc := pc 1}
+ let c₂ := c₁.put (pc 2) (reg 1) (n : Word w)
+ let shift := (if mode = .tally then 0 else n : ℕ)
+ let shifted := BinaryOp.shiftRight.eval (c.reg (reg 2)) (shift : Word w)
+ let c₃ := c₂.put (pc 3) (reg 5) shifted
+ let b := encodeBit w (bit mode (c.reg (reg 2)) n)
+ let c₄ := c₃.put (pc 4) (reg 5) b
+ let c₅ := c₄.store (pc 5) (c.reg (reg 0)) b
+ let next := c₅.put (pc 0) (reg 0) (c.reg (reg 0)+1)
+ have ne : c.reg (reg 1) ≠ c.reg (reg 3) := by
+ rw [hlen,hz]
+ intro he
+ have eq := congrArg Fin.val he
+ change (n+1) % (2^w) = 0 at eq
+ rw [Nat.mod_eq_of_lt fit] at eq
+ omega
+ have hshift : shift < 2^w := by dsimp [shift]; split <;> omega
+ have hbit : BinaryOp.bitAnd.eval shifted 1 = b := by
+ rw [show BinaryOp.bitAnd.eval shifted 1 = _ from Opcodes.readBit_word hw (c.reg (reg 2)) (shift : Word w)]
+ simp only [Fin.val_natCast, Nat.mod_eq_of_lt hshift, b, bit, shift]
+ have s₀ : M.program.step c = .localStep c₁ := by rw [step_at hl 0 c hc]; simp [instruction, Instr.run, ne, c₁]
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at hl 1 c₁ rfl]; simp [instruction, Instr.run, c₁, c₂, BinaryOp.eval, hlen,ho]
+ have s₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step_at hl 2 c₂ rfl]
+ cases mode <;> simp [instruction, Instr.run, c₁,c₂,c₃,Config.put,shift,shifted,hz]
+ have s₃ : M.program.step c₃ = .localStep c₄ := by
+ rw [step_at hl 3 c₃ rfl]
+ simp [instruction,Instr.run,c₁,c₂,c₃,c₄,Config.put,ho,hbit]
+ have s₄ : M.program.step c₄ = .localStep c₅ := by
+ rw [step_at hl 4 c₄ rfl]; simp [instruction,Instr.run,c₁,c₂,c₃,c₄,c₅,Config.put]
+ have s₅ : M.program.step c₅ = .localStep next := by
+ rw [step_at hl 5 c₅ rfl]; simp [instruction,Instr.run,c₁,c₂,c₃,c₄,c₅,next,Config.put,Config.store,BinaryOp.eval,ho]
+ refine ⟨next,.tick s₀ (.tick s₁ (.tick s₂ (.tick s₃ (.tick s₄ (.tick s₅ (.nil _)))))), rfl,?_,?_,?_,rfl,rfl⟩
+ · simp [next,Config.put]
+ · simp [next,c₅,c₄,c₃,c₂,Config.store,Config.put]
+ · intro i h₀ h₁ h₅
+ simp [next,c₅,c₄,c₃,c₂,c₁,Config.put,Config.store,Function.update_of_ne h₀,
+ Function.update_of_ne h₁, Function.update_of_ne h₅]
+
+/-- All writes are private. One terminal test and six native transitions
+per cell suffice on every input value. -/
+theorem load_prefix (hl : Linked M mode pc reg done) (hw : 0 < w) (n dst : ℕ) (value : Word w)
+ (c : Config w p r) (hc : c.pc = pc 0) (hd : c.reg (reg 0) = (dst : Word w))
+ (hlen : c.reg (reg 1) = (n : Word w)) (hv : c.reg (reg 2) = value)
+ (hz : c.reg (reg 3) = 0) (ho : c.reg (reg 4) = 1) (fit : dst+n < 2^w) :
+ ∃ out, Prefix M c (List.replicate (6*n+1) .tick) out ∧ Result reg done c out dst (payload mode value n) := by
+ induction n generalizing c dst with
+ | zero =>
+ let out := {c with pc := done}
+ have eq : c.reg (reg 1) = c.reg (reg 3) := hlen.trans hz.symm
+ have step : M.program.step c = .localStep out := by
+ rw [step_at hl 0 c hc]; simp [instruction,Instr.run,eq,out]
+ exact ⟨out,.tick step (.nil _),rfl,hd,hlen,fun _ _ _ _ => rfl,rfl,rfl⟩
+ | succ n ih =>
+ obtain ⟨next,head,hn,hdst,hlen',frame,mem,hp⟩ := iteration hl hw c hc n (by omega) hlen hz ho
+ have keep (j : Fin 6) (h₀ : j ≠ 0) (h₁ : j ≠ 1) (h₅ : j ≠ 5) :=
+ frame (reg j) (reg.injective.ne h₀) (reg.injective.ne h₁) (reg.injective.ne h₅)
+ obtain ⟨out, tail, res⟩ := ih (dst+1) next hn (by simp [hdst,hd]) hlen'
+ ((keep 2 (by decide) (by decide) (by decide)).trans hv)
+ ((keep 3 (by decide) (by decide) (by decide)).trans hz)
+ ((keep 4 (by decide) (by decide) (by decide)).trans ho) (by omega)
+ have run := head.append tail
+ rw [← List.replicate_add, show 6+(6*n+1) = 6*(n+1)+1 by omega] at run
+ refine ⟨out,run,res.pc,?_,res.remaining,fun i h₀ h₁ h₅ => (res.frame i h₀ h₁ h₅).trans (frame i h₀ h₁ h₅),
+ ?_,res.persistent.trans hp⟩
+ · simpa [Nat.add_assoc,Nat.add_comm 1] using res.destination
+ · rw [res.memory,mem,hd,hv,payload,PrivateFields.storeBits]
+ rfl
+
+end PairSimulation.LeafScalarLoad
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarStartup.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarStartup.lean
new file mode 100644
index 0000000000..f82ee01580
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarStartup.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairSimulationLeafScalarTable
+
+/-!
+# Initializing all scalar stacks of the actual auxiliary RAM
+
+Starting at the first allocation row, the only data-dependent inputs are
+the real source registers, the arena base and capacity. The resulting
+private memory function is determined on every address. The incident
+stack is empty for the ensuing half-wire copy.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafStartup
+
+open BurstRAM PrivateRAM RAMTape StackMachine PrimedCounter.GuessWord LeafRegisterBank
+open scoped Fin.CommRing
+
+set_option synthInstance.maxSize 10000
+
+variable {A : PrimedInputRAM.Lengths} {n a H s w d e p r k : ℕ} {Q : PrimedInputRAM.Layout A n a H w}
+variable (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (v : CursorNetwork.Position d) (buf : CursorNetwork.Buffers d (2^e) w)
+
+/-- A private stack port of the concrete leaf site processor with 52 registers and 34 public
+operands. -/
+abbrev ScalarPort := LeafStartup.Port 52 34
+/-- The concrete register bank for filling the scalar ports from site data and the validator's
+34 public operands. -/
+abbrev ScalarReg := LeafRegisterBank.Reg ScalarPort 34
+/-- Instruction labels for allocating, staging and filling the concrete validator's scalar
+stacks. -/
+abbrev ScalarLabel := LeafPortTable.Label ScalarPort
+
+/-- Enumerate all concrete scalar ports by consecutive indices for the startup traversal. -/
+noncomputable def portOrder : Fin (Fintype.card ScalarPort) ≃ ScalarPort := (Fintype.equivFin ScalarPort).symm
+
+/-- The list of all scalar ports visited once, in the order used to allocate and fill the
+private stacks. -/
+noncomputable def scalarRows := List.ofFn portOrder
+
+/-- The scalar stacks encoded from the auxiliary site's input, its half-wire buffers and the
+counter's public operands, with the incident stack awaiting its separate copy. -/
+noncomputable def scalarInput : Stacks ScalarPort := scalarBank field (auxiliary D hw hc v buf) D.pub
+
+/-- Exact instruction count for allocating and filling the concrete list of scalar ports at
+this auxiliary site. -/
+noncomputable def scalarTicks := LeafPortTable.cost field (auxiliary D hw hc v buf) D.pub scalarRows
+
+theorem incident_install :
+ Function.update (scalarInput D hw hc v buf) (LeafLoadedBank.incidentPort 52 34)
+ (List.ofFn (CursorNetwork.incidentBuffer v buf)) = bank 52 (auxiliary D hw hc v buf) D.pub := by
+ have h := LeafLoadedBank.install_incident (r := 52) (auxiliary D hw hc v buf) D.pub
+ simpa only [scalarInput,auxiliary,sends_incident] using h
+
+/-- The whole allocation-and-scalar pass in the enclosing machine, including
+its exact scratch update and preservation of all other native registers. -/
+theorem scalar_start (M : Machine w p r k) (reg : ScalarReg ↪ Fin r) (pc : ScalarLabel → Fin p)
+ (done : Fin p) (base cap : ℕ) (fit : base + Fintype.card ScalarPort*cap < 2^w)
+ (link : ∀ j, M.code (pc j) = LeafPortTable.instruction field pc reg done scalarRows j)
+ (c : Config w p r)
+ (entry : c.pc = LeafPointers.next scalarRows (fun a i => pc (.pointer a i)) (pc (.finish 0)))
+ (hbase : c.reg (LeafFill.pointers (load reg) .cursor) = (base : Word w))
+ (hcap : c.reg (LeafFill.pointers (load reg) .stride) = (cap : Word w))
+ (inputs : ∀ j, c.reg (reg (.inr j)) = sourceWord (auxiliary D hw hc v buf) D.pub j)
+ (room : ∀ a, (scalarInput D hw hc v buf a).length ≤ cap) :
+ let L := Layout.consecutive portOrder.symm.toEmbedding base cap fit
+ ∃ out, Prefix M c (List.replicate (scalarTicks D hw hc v buf) .tick) out ∧ out.pc = done ∧
+ Represents L (stack reg) out (scalarInput D hw hc v buf) ∧
+ Staging.Sources (auxiliary D hw hc v buf) D.pub (out.reg ∘ stage reg) ∧
+ out.persistent = c.persistent ∧ (∀ i, i ∉ Set.range reg → out.reg i = c.reg i) ∧
+ out.privateMem = LeafLoadedBank.memory L (scalarInput D hw hc v buf) c.privateMem := by
+ intro L
+ have hl (i) : L.base (portOrder i) = base + i.val*L.capacity := by simp [L,Layout.consecutive]
+ obtain ⟨out,run,hpc,rep,ready,state,regs,mem⟩ := LeafPortTable.startup field pc reg done M portOrder L base hl
+ (auxiliary D hw hc v buf) D.pub link c entry hbase hcap inputs room
+ refine ⟨out,?_,hpc,rep,ready,state,regs,LeafLoadedBank.memory_eq L _ _ _ rep.cells room mem⟩
+ simpa only [scalarTicks,LeafPortTable.cost,scalarRows,List.length_ofFn] using run
+
+end PairSimulation.LeafStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarTable.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarTable.lean
new file mode 100644
index 0000000000..983d4e8fdc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarTable.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.PairSimulationLeafLoadedBank
+import OAI.Computability.VPVNP.PairSimulationStackSpace
+
+/-! # Finite scalar-startup template and its virtual-leaf clock -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafPortTable
+
+open BurstRAM PrivateRAM RAMTape LeafStartup LeafRegisterBank StackMachine Filter
+
+variable {K : Type} [Fintype K] [DecidableEq K] {k w : ℕ}
+
+/-- The instruction labels of the scalar startup table together with one additional return
+label. -/
+abbrev PC (K : Type) := Label K ⊕ Unit
+
+/-- The numbered program counter of a labeled allocation, staging or fill instruction in the
+scalar startup template. -/
+noncomputable def rowPC (a : Label K) : Fin (Fintype.card (PC K)) := Fintype.equivFin _ (.inl a)
+/-- The numbered return label reached after the final scalar port in the standalone startup
+template. -/
+noncomputable def returnPC (K : Type) [Fintype K] : Fin (Fintype.card (PC K)) := Fintype.equivFin _ (.inr ())
+/-- Assign the scalar-loader registers consecutive indices in the standalone startup template. -/
+noncomputable def registers (K : Type) [Fintype K] (k : ℕ) :
+ Reg K k ↪ Fin (Fintype.card (Reg K k)) := (Fintype.equivFin _).toEmbedding
+
+/-- The code depends only on the static port set and assignment. Its inputs
+are the caller's source words, the arena cursor and its runtime stride. -/
+noncomputable def template (tag : K → Field k) (todo : List K) :
+ Template (Fintype.card (PC K)) (Fintype.card (Reg K k)) 0 where
+ literalWidth := 1
+ entry := LeafPointers.next todo (fun a i => rowPC (.pointer a i)) (rowPC (.finish 0))
+ code i := match (Fintype.equivFin (PC K)).symm i with
+ | .inl l => instruction tag rowPC (registers K k) (returnPC K) todo l
+ | .inr _ => .accept
+
+theorem template_rows (tag : K → Field k) (todo : List K) (pub : Fin 0 → Word w) (l : Label K) :
+ ((template tag todo).instantiate w pub).code (rowPC l) =
+ instruction tag rowPC (registers K k) (returnPC K) todo l := by
+ simpa [Template.instantiate,template,rowPC] using
+ resize_instruction (w := w) (pubs := 0) tag rowPC (registers K k) (returnPC K) todo l
+
+/-- The total instruction count for allocating three rows per port, finishing allocation in two
+steps, and staging and writing every requested field. -/
+def cost {d e : ℕ} (tag : K → Field k) (x : VirtualSite.Input d e w) (args : Fin k → Word w)
+ (todo : List K) := 3*todo.length+2+(todo.map (ticks tag x args)).sum
+
+omit [Fintype K] [DecidableEq K] in
+theorem cost_le {d e B : ℕ} (tag : K → Field k) (x : VirtualSite.Input d e w) (args : Fin k → Word w)
+ (todo : List K) (bound : ∀ a, (fieldBits x args (tag a)).length ≤ B) :
+ cost tag x args todo ≤ 2+todo.length*(8+6*B) := by
+ have per (a : K) : ticks tag x args a ≤ 5+6*B := by
+ have h := Staging.length_le (scalarField (tag a))
+ have hb : (scalarBank tag x args a).length ≤ B := by
+ by_cases hi : tag a = .incident
+ · simp [scalarBank,scalarField,hi,fieldBits]
+ · simpa [scalarBank,scalarField,hi] using bound a
+ unfold ticks
+ omega
+ have sum (ls : List K) : (ls.map (ticks tag x args)).sum ≤ ls.length*(5+6*B) := by
+ induction ls with
+ | nil => simp
+ | cons a ls ih =>
+ change ticks tag x args a + (ls.map (ticks tag x args)).sum ≤ (ls.length+1)*(5+6*B)
+ rw [Nat.add_mul,Nat.one_mul,Nat.add_comm (ls.length*(5+6*B))]
+ exact Nat.add_le_add (per a) ih
+ unfold cost
+ have h := sum todo
+ rw [Nat.mul_add todo.length 8, Nat.mul_add todo.length 5] at *
+ omega
+
+theorem eventually_auxiliary_cost (r k : ℕ) (todo : List (LeafStartup.Port r k)) :
+ ∀ᶠ n : ℕ in atTop, ∀ d e w (x : VirtualSite.Input d e w), ProcessorBudget n d e w →
+ x.fuel ≤ n^10 → ∀ args : Fin k → Word w, cost LeafStartup.field x args todo ≤ n^14 := by
+ filter_upwards [eventually_ge_atTop (max 128 todo.length)] with n hn
+ intro d e w x bud hf args
+ have h₁ : 1 ≤ n := by omega
+ have h₁₂ := Nat.one_le_pow 12 n h₁
+ have h₁₃ := Nat.one_le_pow 13 n h₁
+ have h := cost_le LeafStartup.field x args todo (bank_length_le x r (by omega) bud hf args)
+ have small : 8+6*n^12 ≤ 14*n^12 := by omega
+ have big := Nat.mul_le_mul (show todo.length ≤ n by omega) small
+ have heq : n*(14*n^12)=14*n^13 := by rw [pow_succ' n 12]; ring
+ have hfinal : 16*n^13 ≤ n^14 := by rw [pow_succ' n 13]; exact Nat.mul_le_mul_right _ (by omega)
+ omega
+
+end PairSimulation.LeafPortTable
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarWrites.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarWrites.lean
new file mode 100644
index 0000000000..4e0c0b5c47
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafScalarWrites.lean
@@ -0,0 +1,38 @@
+import OAI.Computability.VPVNP.PairSimulationLeafPortTable
+import OAI.Computability.VPVNP.PrivateRAMRegisterOperands
+
+/-! # Register destinations of the scalar leaf startup -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafPortTable
+
+open BurstRAM PrivateRAM RegisterOperands LeafStartup LeafRegisterBank
+
+variable {K : Type} [DecidableEq K] {k p r w pubs : ℕ}
+
+/-- Pointer allocation, field staging, and scalar filling write into the
+register bank supplied by the enclosing leaf machine. -/
+theorem destination_mem (field : K → Field k) (pc : Label K → Fin p) (reg : Reg K k ↪ Fin r)
+ (done : Fin p) (rows : List K) (j : Label K) (a : Fin r)
+ (h : destination (instruction (w := w) (pubs := pubs) field pc reg done rows j) = some a) :
+ a ∈ Set.range reg := by
+ cases j with
+ | pointer port i | finish i | fill port i =>
+ fin_cases i <;> first | exact ⟨_, Option.some.inj h⟩ | contradiction
+ | stage port i =>
+ simp only [instruction] at h
+ split at h
+ · rename_i hi
+ generalize (Staging.code (scalarField (field port)))[i.val] = line at h
+ obtain ⟨dst,rhs⟩ := line
+ cases rhs <;> cases dst <;> exact ⟨_, Option.some.inj h⟩
+ · contradiction
+
+end PairSimulation.LeafPortTable
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSegment.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSegment.lean
new file mode 100644
index 0000000000..3e5d3d8d84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSegment.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PairSimulationLeafRoleHandler
+import OAI.Computability.VPVNP.PairSimulationLeafImageWork
+import OAI.Computability.VPVNP.PairNativeFrameLeaf
+import OAI.Computability.VPVNP.PairVertexSiteSegments
+
+/-! # Installing the cursor leaf in the actual terminal vertex image -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRole
+
+open BurstRAM PrivateRAM RegisterOperands VertexImage PrimedCounter.GuessWord
+open DFS CursorNetwork CursorRouting LeafStartup NativeFrame
+open scoped Fin.CommRing Classical
+
+set_option synthInstance.maxSize 10000
+attribute [local irreducible] labelCount privateCount
+
+variable {geometry rootFields shrink refresh : Segment} {p r w : ℕ}
+ (V : Placement (segments geometry rootFields segment shrink refresh) p r)
+ (M : Machine w p r 11)
+
+/-- Place a numbered cursor-leaf instruction at its absolute program counter in the final
+vertex image. -/
+noncomputable def sitePC (j : Label) := V.stage .leaf (labelIndex j)
+
+/-- Place the leaf's private registers in the register interval assigned to the leaf stage of
+the final vertex image. -/
+noncomputable def privateRegs : Private ↪ Fin r := privateIndex.toEmbedding.trans (V.localRegs .leaf)
+
+theorem sitePC_injective : Function.Injective (sitePC V) := by
+ intro i j h
+ have e := V.pc.injective h
+ change Sum.inr (⟨Part.leaf,labelIndex i⟩ : (s : Part) × Fin ((segments geometry rootFields segment shrink refresh s).count)) =
+ Sum.inr ⟨Part.leaf,labelIndex j⟩ at e
+ exact labelIndex.injective (eq_of_heq (Sigma.mk.inj (Sum.inr.inj e)).2)
+
+theorem site_apart : Apart V.dfs (privateRegs V) := fun i j => V.reg.injective.ne (by intro h; cases h)
+
+theorem site_contains (h : VertexImage.Contains V M) :
+ Contains (sitePC V) V.dfs (privateRegs V) (site_apart V) (V.dfsPC 3) M := by
+ intro j
+ exact (stage_linked V M h .leaf (labelIndex j)).trans
+ (congrArg (Instr.resize w) (segment_row V.dfs (V.dfsPC 3) (V.stage .leaf) V.saved
+ (V.localRegs .leaf) (site_apart V) j))
+
+variable {L : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout L n a H w}
+ (D : PrimedCounter.Data Q s) {b l e degree pad : ℕ} [NeZero (b + l)]
+ (hD : 1 < b + l) (hd : 2 + pad = 2 ^ degree) (budget : ProcessorBudget n (b + l) e w)
+ (m : Memory w) (header role : Word w) (arity cap clock : ℕ)
+
+private abbrev layout := fromHeader arity M.publicData header m
+private abbrev words := leafWords arity M.publicData header role m
+
+variable (fit : (layout M m header arity).stackBase + Fintype.card ScalarPort * n ^ 40 < 2 ^ w)
+
+/-- The physical leaf reads the actual terminal header and twelve-word
+frame installed by the vertex bootstrap. The exclusive DFS end is the input
+length, and both successful exits resume the child-list header. -/
+theorem site_exact (link : VertexImage.Contains V M)
+ (stride : (m (header + 15).val).val = cap + 2) (rb : (m (header + 18).val).val = 2 ^ b)
+ (rl : (m (header + 19).val).val = 2 ^ l)
+ (span : (m (header + 20).val).val = LiveAuxiliaryHeaders.span L D.hist.length)
+ (shadowFit : (M.publicData 3).val + (m (header + 20).val).val ≤ 2 ^ w)
+ (headers : ∀ i < (m (header + 20).val).val, (m ((M.publicData 3).val + i)).val = (D.initial i).val)
+ (size : (M.publicData 6).val = n)
+ (time : ∀ (v : Position (b + l)) (buf : Buffers (b + l) (2 ^ e) w),
+ steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ clock)
+ (room : ∀ (v : Position (b + l)) (buf : Buffers (b + l) (2 ^ e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length + clock ≤ n ^ 40) :
+ let R := fromHeader arity M.publicData header m
+ let data := leafWords arity M.publicData header role m
+ (parser (endAddr := n) data D budget R fit m clock).ExactOn
+ (Domain (e := e) data D hD hd R cap (frameBase R)) M (V.entry .leaf) (V.dfsPC 3) V.dfs m := by
+ intro R data
+ let pc := sitePC V
+ let priv := privateRegs V
+ let sep := site_apart V
+ let ret := V.dfsPC 3
+ let sem := verification pc V.dfs priv sep ret M data
+ have assigned : sem.publicData ∘ pubSlot = data ∘ LeafGeometryLoad.slot := by
+ funext j
+ simp only [sem, verification, shadow, publicData, Function.comp_apply, pubSlot, Fin.addCases_left]
+ obtain ⟨op, length⟩ := leaf_operands arity M.publicData header role m (enter ∘ bodyPC pc)
+ (bodyReg V.dfs priv sep) pubSlot (caller ret) sem assigned D b l cap stride rb rl span shadowFit headers size
+ have start : n = R.arguments.start := size.symm
+ have geoLow : n ≤ frameBase R := by
+ change n ≤ R.arguments.start + R.nodes * R.arguments.stride + R.histWords
+ omega
+ have geoFit : frameBase R + 10 ≤ 2 ^ w := by
+ have high := (Nat.le_add_right R.stackBase _).trans_lt fit
+ change R.histBase + R.histWords + R.otherWords + 38 < 2 ^ w at high
+ change R.histBase + R.histWords + 10 ≤ 2 ^ w
+ omega
+ exact native_exact pc V.dfs priv sep ret M data D hD hd budget R cap (frameBase R) fit m clock
+ (sitePC_injective V) (site_contains V M link) op ((congrFun assigned .size).symm.trans length)
+ start.le geoLow geoFit time room
+
+/-- Exact accounting for the geometry reload. Every source job has the same
+external probes, update and choice suffix in the physical parser. -/
+theorem reload_read {endAddr : ℕ} (P : HookParser w endAddr) (node : Word w) (saved : Scratch w endAddr)
+ (bits tail : List Bool) (job : VisitPath w endAddr) (h : (withReload P).read node saved bits = some (job,tail)) :
+ ∃ source, P.read node saved bits = some (source,tail) ∧ job.node = source.node ∧
+ job.update = source.update ∧ job.trace = List.replicate 21 .tick ++ source.trace ∧
+ countProbes job.trace = countProbes source.trace ∧ job.trace.length = 21 + source.trace.length := by
+ obtain ⟨⟨source,rest⟩,read,e⟩ := Option.map_eq_some_iff.mp h
+ cases e
+ exact ⟨source,read,rfl,rfl,rfl,rfl,by rw [List.length_append]; rfl⟩
+
+/-- The native reload leaves room for the surrounding role dispatch. -/
+theorem site_work (hn : 2048 ≤ n)
+ (boot : ∀ (v : Site (b + l)) (buf : Buffers (b + l) (2 ^ e) w),
+ LeafBoot.ticks D budget.tags budget.capFits v buf ≤ n ^ 15)
+ (node : Word w) (saved : Scratch w n) (bits tail : List Bool) (job : VisitPath w n)
+ (h : (parser (words M m header role arity) D budget (layout M m header arity) fit m (n ^ 39)).read
+ node saved bits = some (job,tail)) :
+ countProbes job.trace ≤ 1 ∧ job.trace.length + 26 ≤ n ^ 40 := by
+ let data := words M m header role arity
+ let R := layout M m header arity
+ let source : HookParser w n := LeafHandler.parser D budget.tags budget.capFits (LeafVisit.storage R fit)
+ (LeafVisit.loaded D budget R fit (addressFields data) m) (n ^ 39)
+ obtain ⟨old,hit,_,_,_,probes,ticks⟩ := reload_read source node saved bits tail job h
+ let measure : Machine w 1 0 10 := ⟨0,fun _ => .reject,data⟩
+ obtain ⟨p,t⟩ := LeafVisit.parser_work (M := measure) D budget R fit LeafGeometryLoad.slot m hn boot node saved bits hit
+ rw [probes,ticks]; exact ⟨p,by omega⟩
+
+end PairSimulation.LeafRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSortFields.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSortFields.lean
new file mode 100644
index 0000000000..bae07d95c3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSortFields.lean
@@ -0,0 +1,270 @@
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentLoad
+import OAI.Computability.VPVNP.PrimedInputRAMPortCode
+
+/-!
+# Native triangular scan of the sorting fields at cursor zero
+
+Phase and step count upwards. Each step reads one outgoing and one incoming
+block from the common arc offset. Both selections depend on the cross-site
+bit, equal to phase minus step. The incoming selection tests that bit against
+the last cursor. Every row below is independent of the number of phases.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSortFields
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork RAMLayout
+open LeafIncidentLoad (Field Stored)
+open LeafFieldCopy (word)
+open scoped Fin.CommRing
+
+variable {W w D H p r k : ℕ}
+
+/-- Control locations of the triangular sorting-field traversal and its copy loops. -/
+inductive Stage where
+ | resetPhase | phaseTest | resetStep | stride | outgoing | incoming
+ | advance | stepTest | nextStep | nextPhase
+ | prepare (receive side : Bool) (i : Fin 2)
+ | move (receive side : Bool) (i : Fin 5)
+ deriving DecidableEq, Fintype
+
+/-- Select an outgoing or incoming half-wire by the endpoint bit. -/
+def port (receive side : Bool) : LocalPort := if receive then .incoming side else .outgoing side
+
+/-- Place the field loader's eleven registers inside the sorting traversal. -/
+def subRegs (reg : Fin 17 ↪ Fin r) : Fin 11 ↪ Fin r := (Fin.castAddEmb 6).trans reg
+
+/-- The shared mover uses registers 0–10. The remaining registers hold D,
+D−1, phase, step, stride bit and zero. -/
+def instruction (pc : Stage → Fin p) (reg : Fin 17 ↪ Fin r) (done : Fin p) :
+ Stage → Instr W p r k
+ | .resetPhase => .constant (reg 13) 0 (pc .phaseTest)
+ | .phaseTest => .jumpLt (reg 13) (reg 11) (pc .resetStep) done
+ | .resetStep => .constant (reg 14) 0 (pc .stride)
+ | .stride => .binary .sub (reg 15) (reg 13) (reg 14) (pc .outgoing)
+ | .outgoing => .jumpEq (reg 15) (reg 16) (pc (.prepare false true 0)) (pc (.prepare false false 0))
+ | .incoming => .jumpEq (reg 15) (reg 12) (pc (.prepare true true 0)) (pc (.prepare true false 0))
+ | .advance => .binary .add (reg 6) (reg 6) (reg 5) (pc .stepTest)
+ | .stepTest => .jumpLt (reg 14) (reg 13) (pc .nextStep) (pc .nextPhase)
+ | .nextStep => .binary .add (reg 14) (reg 14) (reg 3) (pc .stride)
+ | .nextPhase => .binary .add (reg 13) (reg 13) (reg 3) (pc .phaseTest)
+ | .prepare recv side i =>
+ LeafIncidentLoad.prepare (some (port recv side)) (pc ∘ Stage.prepare recv side)
+ (subRegs reg) (pc (.move recv side 0)) i
+ | .move recv side i =>
+ LeafFieldCopy.instruction .resident (pc ∘ Stage.move recv side)
+ (LeafIncidentLoad.copyRegs (subRegs reg)) (pc (if recv then .advance else .incoming)) i
+
+theorem resize_instruction (pc : Stage → Fin p) (reg : Fin 17 ↪ Fin r) (done : Fin p) (s : Stage) :
+ (instruction (W := 1) (k := k) pc reg done s).resize W = instruction pc reg done s := by
+ cases s <;> try rfl
+ case prepare recv side i => fin_cases i <;> rfl
+ case move recv side i => fin_cases i <;> rfl
+
+/-- The host table contains the sorting traversal's physical instructions. -/
+def Linked (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 17 ↪ Fin r) (done : Fin p) :=
+ ∀ s, M.code (pc s) = instruction pc reg done s
+
+/-- Start of this sorting layer's field in one half-wire payload. -/
+def arcStart (l : Layer D) (H w : ℕ) := D*(8*w)+l.ordinal.val*blockBits H w
+
+theorem fieldFits (l : Layer D) (H w : ℕ) : arcStart l H w+blockBits H w ≤ ramPayloadWidth D H w := by
+ unfold arcStart ramPayloadWidth
+ have h := Nat.mul_le_mul_right (blockBits H w) l.ordinal.isLt
+ rw [Nat.succ_mul] at h
+ omega
+
+/-- Endpoint bit chosen for the outgoing or incoming field of a sorting layer. -/
+def side (l : Layer D) (receive : Bool) : Bool := decide (l.siteBit = if receive then D-1 else 0)
+
+/-- Bits of the selected resident sorting field. -/
+def field (l : Layer D) (receive : Bool) (buf : Buffers D H w) : List Bool :=
+ Field (some (port receive (side l receive))) (arcStart l H w) (blockBits H w) (fieldFits l H w) buf
+
+@[simp] theorem field_length (l : Layer D) (receive : Bool) (buf : Buffers D H w) :
+ (field l receive buf).length = blockBits H w := List.length_ofFn
+
+/-- Concatenate a layer's outgoing field with its incoming field. -/
+def block (l : Layer D) (buf : Buffers D H w) := field l false buf ++ field l true buf
+
+@[simp] theorem block_length (l : Layer D) (buf : Buffers D H w) :
+ (block l buf).length = 2*blockBits H w := by simp [block, two_mul]
+
+/-- Index of a field-loader register in the sorting register file. -/
+def index (i : Fin 11) : Fin 17 := Fin.castAdd 6 i
+
+/-- Constant operands for a complete sorting-layer traversal. -/
+structure Fixed (reg : Fin 17 ↪ Fin r) (base : LocalPort → ℕ) (D H w : ℕ) (c : Config W p r) : Prop where
+ one : c.reg (reg 3) = 1
+ len : c.reg (reg 5) = word W (blockBits H w)
+ bases : ∀ a, c.reg (reg (index (LeafIncidentLoad.baseReg a))) = word W (base a)
+ dims : c.reg (reg 11) = word W D
+ last : c.reg (reg 12) = word W (D-1)
+ zero : c.reg (reg 16) = 0
+
+/-- Register operands that can change in a sorting-field scan. -/
+def changed : List (Fin 17) := [0,1,2,4,6,13,14,15]
+
+/-- Registers preserved while one sorting-field step executes. -/
+def Frame (reg : Fin 17 ↪ Fin r) (c out : Config W p r) :=
+ ∀ i, (∀ j ∈ changed, i ≠ reg j) → out.reg i = c.reg i
+
+theorem Frame.trans {reg : Fin 17 ↪ Fin r} {a b c : Config W p r}
+ (h : Frame reg a b) (h' : Frame reg b c) : Frame reg a c :=
+ fun i hi => (h' i hi).trans (h i hi)
+
+theorem Fixed.of_frame {reg : Fin 17 ↪ Fin r} {base D H w} {c out : Config W p r}
+ (hc : Fixed reg base D H w c) (h : Frame reg c out) : Fixed reg base D H w out := by
+ have keep (j : Fin 17) (hj : j ∉ changed) : out.reg (reg j) = c.reg (reg j) :=
+ h _ (fun i hi => reg.injective.ne (fun eq => hj (eq ▸ hi)))
+ refine ⟨(keep _ (by decide)).trans hc.one, (keep _ (by decide)).trans hc.len, ?_,
+ (keep _ (by decide)).trans hc.dims, (keep _ (by decide)).trans hc.last, (keep _ (by decide)).trans hc.zero⟩
+ intro port
+ exact (keep _ (by cases port with | outgoing side | incoming side => cases side <;> decide)).trans (hc.bases port)
+
+theorem frame_put {reg : Fin 17 ↪ Fin r} (c : Config W p r) (next : Fin p) (j : Fin 17)
+ (v : Word W) (hj : j ∈ changed) : Frame reg c (c.put next (reg j) v) :=
+ fun _ hi => Function.update_of_ne (hi j hj) _ _
+
+theorem stored_place (base : LocalPort → ℕ) (buf : Buffers D H w) (m : Word W → Word W)
+ (lo : ℕ) (bs : List Bool) (h : Stored base buf m)
+ (fit : lo+bs.length ≤ 2^W) (hf : ∀ a, base a+ramPayloadWidth D H w ≤ 2^W)
+ (apart : ∀ a, base a+ramPayloadWidth D H w ≤ lo ∨ lo+bs.length ≤ base a) :
+ Stored base buf (LeafFieldCopy.place lo bs m) := by
+ intro a i
+ have hi := i.isLt
+ have hh := hf a
+ have hs := apart a
+ rw [LeafFieldCopy.place_outside _ _ _ _ fit]
+ · exact h a i
+ · change (base a + i.val) % 2^W < lo ∨ lo+bs.length ≤ (base a+i.val) % 2^W
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+
+variable {M : Machine W p r k} {pc : Stage → Fin p} {reg : Fin 17 ↪ Fin r} {done : Fin p}
+
+theorem step_at (hl : Linked M pc reg done) (q : Stage) (c : Config W p r) (hc : c.pc = pc q) :
+ M.program.step c = (instruction pc reg done q).run M.publicData c := by simp [Machine.program, hc, hl q]
+
+private theorem move_run (hl : Linked M pc reg done) (l : Layer D) (recv : Bool)
+ (base : LocalPort → ℕ) (buf : Buffers D H w) (lo : ℕ) (c : Config W p r)
+ (hc : c.pc = pc (.prepare recv (side l recv) 0)) (hf : Fixed reg base D H w c)
+ (ho : c.reg (reg 6) = word W (arcStart l H w))
+ (hd : c.reg (reg 2) = word W (lo+blockBits H w)) (hs : Stored base buf c.privateMem)
+ (fit : lo+blockBits H w < 2^W) (sourceFit : ∀ a, base a+ramPayloadWidth D H w ≤ 2^W)
+ (sep : ∀ a, base a+ramPayloadWidth D H w ≤ lo ∨ lo+blockBits H w ≤ base a) :
+ ∃ out, Prefix M c (List.replicate (5*blockBits H w+3) .tick) out ∧
+ out.pc = pc (if recv then .advance else .incoming) ∧ out.reg (reg 2) = word W lo ∧
+ (∀ i, i ≠ reg 0 → i ≠ reg 1 → i ≠ reg 2 → i ≠ reg 4 → out.reg i = c.reg i) ∧
+ out.privateMem = LeafFieldCopy.place lo (field l recv buf) c.privateMem ∧
+ out.persistent = c.persistent := by
+ let s := side l recv
+ obtain ⟨out,pref,res⟩ := LeafIncidentLoad.copy_run M (some (port recv s))
+ (pc ∘ Stage.prepare recv s) (pc ∘ Stage.move recv s) (subRegs reg)
+ (pc (if recv then .advance else .incoming))
+ (fun i => hl (.prepare recv s i)) (fun i => hl (.move recv s i))
+ base buf (arcStart l H w) (blockBits H w) lo (fieldFits l H w) fit sep sourceFit c hc
+ hf.bases hf.len ho hd hf.one hs
+ exact ⟨out, pref, res.pc, res.cursor, res.frame, res.mem, res.persistent⟩
+
+private theorem word_eq_iff {a b : ℕ} (ha : a < 2^W) (hb : b < 2^W) :
+ word W a = word W b ↔ a = b := by
+ constructor
+ · intro h
+ have he := congrArg Fin.val h
+ change a % 2^W = b % 2^W at he
+ rwa [Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb] at he
+ · rintro rfl; rfl
+
+private theorem move_frame (reg : Fin 17 ↪ Fin r) {c out : Config W p r}
+ (h : ∀ i, i ≠ reg 0 → i ≠ reg 1 → i ≠ reg 2 → i ≠ reg 4 → out.reg i = c.reg i) :
+ Frame reg c out := fun i hi => h i (hi 0 (by decide)) (hi 1 (by decide)) (hi 2 (by decide)) (hi 4 (by decide))
+
+/-- Both physical fields of one layer, before the address and loop counters advance. -/
+theorem layer_run (hl : Linked M pc reg done) (l : Layer D) (base : LocalPort → ℕ)
+ (buf : Buffers D H w) (lo : ℕ) (c : Config W p r)
+ (hc : c.pc = pc .stride) (hf : Fixed reg base D H w c) (hD : D < 2^W)
+ (hp : c.reg (reg 13) = word W l.phase) (ht : c.reg (reg 14) = word W l.step)
+ (ho : c.reg (reg 6) = word W (arcStart l H w)) (hd : c.reg (reg 2) = word W (lo+2*blockBits H w))
+ (hs : Stored base buf c.privateMem) (fit : lo+2*blockBits H w < 2^W)
+ (sourceFit : ∀ a, base a+ramPayloadWidth D H w ≤ 2^W)
+ (sep : ∀ a, base a+ramPayloadWidth D H w ≤ lo ∨ lo+2*blockBits H w ≤ base a) :
+ ∃ out, Prefix M c (List.replicate (10*blockBits H w+9) .tick) out ∧
+ out.pc = pc .advance ∧ out.reg (reg 2) = word W lo ∧
+ out.reg (reg 6) = c.reg (reg 6) ∧ out.reg (reg 13) = c.reg (reg 13) ∧
+ out.reg (reg 14) = c.reg (reg 14) ∧ Frame reg c out ∧
+ out.privateMem = LeafFieldCopy.place lo (block l buf) c.privateMem ∧ out.persistent = c.persistent := by
+ let a := c.put (pc .outgoing) (reg 15) (word W l.siteBit)
+ let b := {a with pc := pc (.prepare false (side l false) 0)}
+ have s0 : M.program.step c = .localStep a := by
+ rw [step_at hl _ c hc]
+ simp [instruction,Instr.run,BinaryOp.eval,a,hp,ht,word,Layer.siteBit,Nat.cast_sub l.step_le]
+ have heq : a.reg (reg 15) = a.reg (reg 16) ↔ l.siteBit = 0 := by
+ simp only [a,Config.put,Function.update_self,Function.update_of_ne (reg.injective.ne (by decide : (16 : Fin 17) ≠ 15)),hf.zero]
+ exact word_eq_iff (l.siteBit_lt.trans hD) (Nat.two_pow_pos W)
+ have s1 : M.program.step a = .localStep b := by
+ rw [step_at hl .outgoing a rfl]
+ simp [instruction,Instr.run,b,side,heq]
+ split <;> simp_all
+ have fb : Frame reg c b := frame_put c _ 15 _ (by decide)
+ have hD₁ : c.reg (reg 2) = word W (lo+blockBits H w+blockBits H w) := by
+ simpa [two_mul,Nat.add_assoc] using hd
+ obtain ⟨u,pu,hup,hud,ku,hu,hperu⟩ := move_run hl l false base buf (lo+blockBits H w) b rfl
+ (hf.of_frame fb) (by simpa [b,a,Config.put] using ho) (by simpa [b,a,Config.put] using hD₁)
+ hs (by omega) sourceFit (fun a => by have := sep a; omega)
+ let d := {u with pc := pc (.prepare true (side l true) 0)}
+ have fb_u : Frame reg b u := move_frame reg ku
+ have fdu : Frame reg c d := fb.trans fb_u
+ have hfu := hf.of_frame fdu
+ have hstride : u.reg (reg 15) = word W l.siteBit := by
+ rw [ku _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))
+ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))]
+ exact Config.put_same ..
+ have eqr : u.reg (reg 15) = u.reg (reg 12) ↔ l.siteBit = D-1 := by
+ change u.reg (reg 15) = d.reg (reg 12) ↔ _
+ rw [hstride,hfu.last]
+ exact word_eq_iff (l.siteBit_lt.trans hD) (by omega)
+ have s2 : M.program.step u = .localStep d := by
+ rw [step_at hl .incoming u hup]
+ simp [instruction,Instr.run,d,side,eqr]
+ split <;> simp_all
+ have su : Stored base buf u.privateMem := by
+ rw [hu]
+ exact stored_place _ _ _ _ _ hs (by simp; omega) sourceFit (fun a => by have := sep a; simp; omega)
+ have keepU (i : Fin 17) (h0 : i ≠ 0) (h1 : i ≠ 1) (h2 : i ≠ 2) (h4 : i ≠ 4) :
+ u.reg (reg i) = b.reg (reg i) := ku _ (reg.injective.ne h0) (reg.injective.ne h1)
+ (reg.injective.ne h2) (reg.injective.ne h4)
+ have off : d.reg (reg 6) = word W (arcStart l H w) := by
+ change u.reg (reg 6) = _
+ rw [keepU 6 (by decide) (by decide) (by decide) (by decide)]
+ simpa [b,a,Config.put] using ho
+ obtain ⟨out,pv,hvp,hvd,kv,hv,hperv⟩ := move_run hl l true base buf lo d rfl
+ hfu off hud su (by omega) sourceFit (fun a => by have := sep a; omega)
+ have both (i : Fin 17) (h0 : i ≠ 0) (h1 : i ≠ 1) (h2 : i ≠ 2) (h4 : i ≠ 4) (h15 : i ≠ 15) :
+ out.reg (reg i) = c.reg (reg i) := by
+ rw [kv _ (reg.injective.ne h0) (reg.injective.ne h1) (reg.injective.ne h2) (reg.injective.ne h4)]
+ change u.reg (reg i) = _
+ rw [keepU _ h0 h1 h2 h4]
+ exact Function.update_of_ne (reg.injective.ne h15) _ _
+ refine ⟨out, ?_, hvp, hvd, both _ (by decide) (by decide) (by decide) (by decide) (by decide),
+ both _ (by decide) (by decide) (by decide) (by decide) (by decide),
+ both _ (by decide) (by decide) (by decide) (by decide) (by decide),
+ fdu.trans (move_frame reg kv), ?_, hperv.trans hperu⟩
+ · have pre : Prefix M c (List.replicate 2 .tick) b := .tick s0 (.tick s1 (.nil _))
+ have mid : Prefix M u (List.replicate 1 .tick) d := .tick s2 (.nil _)
+ convert pre.append (pu.append (mid.append pv)) using 1
+ repeat rw [← List.replicate_add]
+ congr 1; omega
+ · rw [hv]
+ change LeafFieldCopy.place lo (field l true buf) u.privateMem = _
+ rw [hu,block,LeafIncidentLoad.place_append,field_length]
+ rfl
+
+end PairSimulation.LeafSortFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSortStream.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSortStream.lean
new file mode 100644
index 0000000000..89dba0bd95
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSortStream.lean
@@ -0,0 +1,55 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSortWalk
+import OAI.Computability.VPVNP.RAMTapeSortScheduleFields
+
+/-!
+# Identifying the native sort-field stream with the local cursor decoder
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSortFields
+
+open CursorNetwork CursorRouting RAMLayout RAMTape.SortSchedule
+
+variable {D w H : ℕ} [NeZero D]
+
+theorem previous_zero : ((finRotate D).symm (0 : Fin D)).val = D-1 := by
+ cases D with
+ | zero => exact (NeZero.ne 0 rfl).elim
+ | succ n =>
+ have he : (finRotate (n+1)).symm 0 = Fin.last n :=
+ (finRotate (n+1)).symm_apply_eq.mpr (finRotate_last ..).symm
+ simp [he]
+
+/-- A native sorting-field read addresses exactly the selected half on
+every bit. The current cursor reads bit zero and the predecessor cursor
+reads bit D−1 of the layer mask. -/
+theorem field_eq (l : Layer D) (recv : Bool) (v : Site D) (buf : Buffers D H w) :
+ field l recv buf = List.ofFn fun j : Fin (blockBits H w) =>
+ incidentBuffer (0,v) buf (offset D H w (.inr (l,if recv then 1 else 0,j))) := by
+ apply congrArg List.ofFn
+ funext j
+ have addr : (ramFieldOffset D H w ⟨.inr l,j⟩).val = arcStart l H w+j.val := ramFieldOffset_sort l j
+ cases recv <;>
+ simp only [port,side,Bool.false_eq_true,↓reduceIte,
+ incidentBuffer,decodeIncident,Function.comp_apply,Equiv.symm_apply_apply,decodeSlot,
+ Fin.val_zero,readBuffer,systemMask,Nat.testBit_two_pow,previous_zero]
+ all_goals (congr 2; exact addr.symm)
+
+theorem stream_eq_fields (v : Site D) (buf : Buffers D H w) :
+ stream buf 0 (layerCount D) (by simp) =
+ (List.range (layerCount D)).flatMap (fieldPair (incidentBuffer (0,v) buf)) := by
+ rw [stream,List.flatMap_def]
+ apply congrArg List.flatten
+ apply List.ext_getElem (by simp)
+ intro i hi hj
+ have h : i < layerCount D := by simpa using hi
+ simp [fieldPair,block,field_eq _ false v buf,field_eq _ true v buf,h]
+
+end PairSimulation.LeafSortFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSortWalk.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSortWalk.lean
new file mode 100644
index 0000000000..8f54710c5f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSortWalk.lean
@@ -0,0 +1,241 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSortFields
+
+/-!
+# Executing the complete sorting-field traversal of a virtual RAM leaf
+
+The native scan visits the two fields of each layer in triangular order.
+Its private-memory result puts the concatenation of those fields into the
+descending part of the incident stack, preserving the resident half buffers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSortFields
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork RAMLayout
+open LeafFieldCopy (word)
+open scoped Fin.CommRing
+
+variable {W w D H p r k : ℕ}
+variable {M : Machine W p r k} {pc : Stage → Fin p} {reg : Fin 17 ↪ Fin r} {done : Fin p}
+
+/-- The physical control and counters match a sorting-layer ordinal, or have reached the return. -/
+def At (pc : Stage → Fin p) (reg : Fin 17 ↪ Fin r) (done : Fin p) (D i : ℕ)
+ (c : Config W p r) : Prop :=
+ if h : i < layerCount D then
+ let l := (layerEquiv D).symm ⟨i,h⟩
+ c.pc = pc .stride ∧ c.reg (reg 13) = word W l.phase ∧ c.reg (reg 14) = word W l.step
+ else c.pc = done
+
+private theorem at_layer (l : Layer D) (i : ℕ) (hi : l.ordinal.val = i) (c : Config W p r)
+ (hc : c.pc = pc .stride) (hp : c.reg (reg 13) = word W l.phase)
+ (ht : c.reg (reg 14) = word W l.step) : At pc reg done D i c := by
+ subst i
+ have eq : (layerEquiv D).symm l.ordinal = l := (layerEquiv D).symm_apply_apply l
+ simpa [At,l.ordinal.isLt,eq] using And.intro hc (And.intro hp ht)
+
+private theorem word_lt_iff {a b : ℕ} (ha : a < 2^W) (hb : b < 2^W) :
+ word W a < word W b ↔ a < b := by
+ change a % 2^W < b % 2^W ↔ _
+ rw [Nat.mod_eq_of_lt ha,Nat.mod_eq_of_lt hb]
+
+/-- Number of instructions to advance the triangular pair of counters. -/
+def advanceTicks (l : Layer D) := if l.step < l.phase then 3 else if l.phase+1 < D then 5 else 4
+
+/-- Advance from the end of a field pair to the next ordinal or the exit.
+The two cases of a triangular row boundary are handled by genuine comparisons. -/
+theorem advance_run (hl : Linked M pc reg done) (l : Layer D) (base : LocalPort → ℕ)
+ (c : Config W p r) (hc : c.pc = pc .advance) (hf : Fixed reg base D H w c)
+ (hD : D < 2^W) (hp : c.reg (reg 13) = word W l.phase)
+ (ht : c.reg (reg 14) = word W l.step) (ho : c.reg (reg 6) = word W (arcStart l H w)) :
+ ∃ cost ≤ 5, ∃ out, Prefix M c (List.replicate cost .tick) out ∧
+ At pc reg done D (l.ordinal.val+1) out ∧
+ out.reg (reg 6) = word W (arcStart l H w + blockBits H w) ∧
+ out.reg (reg 2) = c.reg (reg 2) ∧ Frame reg c out ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧ cost = advanceTicks l := by
+ let a := c.put (pc .stepTest) (reg 6) (word W (arcStart l H w + blockBits H w))
+ have s0 : M.program.step c = .localStep a := by
+ rw [step_at hl .advance c hc]
+ simp [instruction,Instr.run,BinaryOp.eval,ho,hf.len,a,word]
+ have f0 : Frame reg c a := frame_put c _ 6 _ (by decide)
+ have e : a.reg (reg 14) < a.reg (reg 13) ↔ l.step < l.phase := by
+ simpa [a,Config.put,ht,hp] using (word_lt_iff (W := W) (l.step_le.trans_lt (l.phase_lt.trans hD))
+ (l.phase_lt.trans hD))
+ by_cases more : l.step < l.phase
+ · let b := {a with pc := pc .nextStep}
+ let out := b.put (pc .stride) (reg 14) (word W (l.step+1))
+ have s1 : M.program.step a = .localStep b := by
+ rw [step_at hl .stepTest a rfl]
+ simp [instruction,Instr.run,b,e,more]
+ have s2 : M.program.step b = .localStep out := by
+ rw [step_at hl .nextStep b rfl]
+ simp [instruction,Instr.run,BinaryOp.eval,b,a,out,Config.put,ht,hf.one,word]
+ let next : Layer D := ⟨l.phase,l.step+1,l.phase_lt,more⟩
+ refine ⟨3, by decide, out, .tick s0 (.tick s1 (.tick s2 (.nil _))), ?_, ?_, ?_,
+ f0.trans (frame_put b _ 14 _ (by decide)), rfl,rfl,by simp [advanceTicks,more]⟩
+ · exact at_layer next _ (by simp [next,Layer.ordinal,Nat.add_assoc]) _ rfl
+ (by simp [out,b,a,Config.put,next,hp]) (Config.put_same ..)
+ · simp [out,b,a,Config.put]
+ · simp [out,b,a,Config.put]
+ · let b := {a with pc := pc .nextPhase}
+ let d := b.put (pc .phaseTest) (reg 13) (word W (l.phase+1))
+ have s1 : M.program.step a = .localStep b := by
+ rw [step_at hl .stepTest a rfl]
+ simp [instruction,Instr.run,b,e,more]
+ have s2 : M.program.step b = .localStep d := by
+ rw [step_at hl .nextPhase b rfl]
+ simp [instruction,Instr.run,BinaryOp.eval,b,a,d,Config.put,hp,hf.one,word]
+ have f2 : Frame reg c d := f0.trans (frame_put b _ 13 _ (by decide))
+ have h := l.phase_lt
+ have hrow : l.step = l.phase := le_antisymm l.step_le (by omega)
+ have eq : l.ordinal.val+1 = layerCount (l.phase+1) := by
+ rw [PrimedInputRAM.PortCode.layerCount_next]
+ change layerCount l.phase + l.step + 1 = _
+ omega
+ have e' : d.reg (reg 13) < d.reg (reg 11) ↔ l.phase+1 < D := by
+ simpa [d,b,a,Config.put,hf.dims] using (word_lt_iff (W := W) (by omega : l.phase+1 < 2^W) hD)
+ by_cases live : l.phase+1 < D
+ · let f := {d with pc := pc .resetStep}
+ let out := f.put (pc .stride) (reg 14) 0
+ have s3 : M.program.step d = .localStep f := by
+ rw [step_at hl .phaseTest d rfl]
+ simp [instruction,Instr.run,f,e',live]
+ have s4 : M.program.step f = .localStep out := step_at hl .resetStep f rfl
+ let next : Layer D := ⟨l.phase+1,0,live,by omega⟩
+ refine ⟨5, le_rfl, out,.tick s0 (.tick s1 (.tick s2 (.tick s3 (.tick s4 (.nil _))))),
+ ?_, ?_, ?_, f2.trans (frame_put f _ 14 _ (by decide)),rfl,rfl,by simp [advanceTicks,more,live]⟩
+ · exact at_layer next _ (by simpa [next,Layer.ordinal] using eq.symm) _ rfl
+ (by simp [out,f,d,Config.put,next]) (Config.put_same ..)
+ · simp [out,f,d,b,a,Config.put]
+ · simp [out,f,d,b,a,Config.put]
+ · let out := {d with pc := done}
+ have s3 : M.program.step d = .localStep out := by
+ rw [step_at hl .phaseTest d rfl]
+ simp [instruction,Instr.run,out,e',live]
+ have last : l.ordinal.val+1 = layerCount D := by rw [eq, show l.phase+1 = D by omega]
+ refine ⟨4,by decide,out,.tick s0 (.tick s1 (.tick s2 (.tick s3 (.nil _)))),
+ by simp [At,last,out], ?_, ?_,f2,rfl,rfl,by simp [advanceTicks,more,live]⟩
+ · simp [out,d,b,a,Config.put]
+ · simp [out,d,b,a,Config.put]
+
+/-- Logical stream of a consecutive interval of layer ordinals. -/
+def stream (buf : Buffers D H w) (i n : ℕ) (fits : i+n ≤ layerCount D) : List Bool :=
+ (List.ofFn fun j : Fin n => block ((layerEquiv D).symm ⟨i+j.val, by have := j.isLt; omega⟩) buf).flatten
+
+private theorem stream_succ (buf : Buffers D H w) (i n : ℕ) (fits : i+(n+1) ≤ layerCount D) :
+ stream buf i (n+1) fits =
+ block ((layerEquiv D).symm ⟨i,by omega⟩) buf ++ stream buf (i+1) n (by omega) := by
+ simp only [stream,List.ofFn_succ,List.flatten_cons,Fin.val_zero,Nat.add_zero,Fin.val_succ]
+ congr 2
+ apply congrArg List.ofFn
+ funext j
+ simp [Nat.add_assoc,Nat.add_comm 1]
+
+@[simp] theorem stream_length (buf : Buffers D H w) (i n : ℕ) (fits) :
+ (stream buf i n fits).length = n*(2*blockBits H w) := by
+ induction n generalizing i with
+ | zero => simp [stream]
+ | succ n ih => rw [stream_succ,List.length_append,block_length,ih]; ring
+
+/-- Total number of native instructions for the indicated consecutive sorting layers. -/
+def streamTicks (D H w i n : ℕ) (fits : i+n ≤ layerCount D) : ℕ :=
+ (List.ofFn fun j : Fin n =>
+ 10*blockBits H w+9+advanceTicks ((layerEquiv D).symm ⟨i+j.val, by have := j.isLt; omega⟩)).sum
+
+private theorem streamTicks_succ (D H w i n : ℕ) (fits : i+(n+1) ≤ layerCount D) :
+ streamTicks D H w i (n+1) fits =
+ 10*blockBits H w+9+advanceTicks ((layerEquiv D).symm ⟨i,by omega⟩) +
+ streamTicks D H w (i+1) n (by omega) := by
+ simp [streamTicks,List.ofFn_succ,Nat.add_assoc,Nat.add_comm 1]
+
+private theorem walk (hl : Linked M pc reg done) (base : LocalPort → ℕ) (buf : Buffers D H w)
+ (lo i n : ℕ) (finish : i+n = layerCount D) (c : Config W p r) (hc : At pc reg done D i c)
+ (hf : Fixed reg base D H w c) (hD : D < 2^W)
+ (ho : c.reg (reg 6) = word W (D*(8*w)+i*blockBits H w))
+ (hd : c.reg (reg 2) = word W (lo+n*(2*blockBits H w))) (hs : LeafIncidentLoad.Stored base buf c.privateMem)
+ (fit : lo+n*(2*blockBits H w) < 2^W) (sourceFit : ∀ a, base a+ramPayloadWidth D H w ≤ 2^W)
+ (sep : ∀ a, base a+ramPayloadWidth D H w ≤ lo ∨ lo+n*(2*blockBits H w) ≤ base a) :
+ ∃ t ≤ n*(10*blockBits H w+14), ∃ out, Prefix M c (List.replicate t .tick) out ∧
+ out.pc = done ∧ out.reg (reg 2) = word W lo ∧ Frame reg c out ∧
+ out.privateMem = LeafFieldCopy.place lo (stream buf i n finish.le) c.privateMem ∧ out.persistent = c.persistent ∧
+ t = streamTicks D H w i n finish.le := by
+ induction n generalizing i c with
+ | zero =>
+ have hi : i = layerCount D := by omega
+ exact ⟨0, by simp, c, .nil _, by simpa [At,hi] using hc, by simpa using hd,
+ fun _ _ => rfl, by simp [stream,LeafFieldCopy.place], rfl, by simp [streamTicks]⟩
+ | succ n ih =>
+ let B := blockBits H w
+ let l := (layerEquiv D).symm ⟨i, by omega⟩
+ have ord : l.ordinal.val = i := congrArg Fin.val ((layerEquiv D).apply_symm_apply ⟨i,by omega⟩)
+ have ha : c.pc = pc .stride ∧ c.reg (reg 13) = word W l.phase ∧ c.reg (reg 14) = word W l.step := by
+ simpa [At,show i < layerCount D by omega,l] using hc
+ let lower := lo+n*(2*B)
+ have hlen : lower + 2*blockBits H w = lo+(n+1)*(2*blockBits H w) := by dsimp [lower,B]; ring
+ have hlow : lo ≤ lower := Nat.le_add_right ..
+ have hprefix := layer_run hl l base buf lower c ha.1 hf hD ha.2.1 ha.2.2
+ (by simpa [arcStart,ord] using ho) (hlen ▸ hd) hs (hlen ▸ fit) sourceFit
+ (fun a => by have := sep a; omega)
+ obtain ⟨u,pre,up,ud,uo,uph,ust,fu,um,uper⟩ := hprefix
+ obtain ⟨cost,bound,v,adv,va,vo,vd,fv,vm,vper,vticks⟩ := advance_run hl l base u up (hf.of_frame fu) hD
+ (uph.trans ha.2.1) (ust.trans ha.2.2) (by simpa [uo,arcStart,ord] using ho)
+ have hstore : LeafIncidentLoad.Stored base buf v.privateMem := by
+ rw [vm,um]
+ exact stored_place _ _ _ _ _ hs (by rw [block_length,hlen]; exact fit.le) sourceFit
+ (fun a => by rw [block_length,hlen]; have := sep a; omega)
+ have vOff : v.reg (reg 6) = word W (D*(8*w)+(i+1)*blockBits H w) := by
+ rw [vo,arcStart,ord]
+ congr 1; ring
+ have same : i+1+n = layerCount D := by omega
+ have hrest := Nat.add_le_add_left (Nat.mul_le_mul_right (2*blockBits H w) (Nat.le_succ n)) lo
+ obtain ⟨cost',bound',out,tail,hpc,hcur,ff,hm,hper,hticks⟩ := ih (i+1) same v (ord ▸ va)
+ (hf.of_frame (fu.trans fv)) vOff (vd.trans ud) hstore (hrest.trans_lt fit)
+ (fun a => (sep a).imp_right hrest.trans)
+ refine ⟨(10*B+9)+cost+cost', ?_,out, ?_,hpc,hcur,(fu.trans fv).trans ff, ?_,hper.trans (vper.trans uper), ?_⟩
+ · have eq : (n+1)*(10*B+14) = n*(10*B+14)+(10*B+14) := by ring
+ dsimp only [B] at eq ⊢
+ omega
+ · simpa only [List.replicate_add,B,List.append_assoc] using pre.append (adv.append tail)
+ · rw [hm,vm,um,stream_succ,LeafIncidentLoad.place_append,stream_length]
+ · rw [vticks,hticks,streamTicks_succ]
+
+/-- The full finite-control triangular scan on four resident half buffers. -/
+theorem sort_run (hl : Linked M pc reg done) (base : LocalPort → ℕ) (buf : Buffers D H w)
+ (lo : ℕ) (c : Config W p r) (hc : c.pc = pc .resetPhase) (hf : Fixed reg base D H w c)
+ (hpos : 0 < D) (hD : D < 2^W) (ho : c.reg (reg 6) = word W (D*(8*w)))
+ (hd : c.reg (reg 2) = word W (lo+layerCount D*(2*blockBits H w)))
+ (hs : LeafIncidentLoad.Stored base buf c.privateMem) (fit : lo+layerCount D*(2*blockBits H w) < 2^W)
+ (sourceFit : ∀ a, base a+ramPayloadWidth D H w ≤ 2^W)
+ (sep : ∀ a, base a+ramPayloadWidth D H w ≤ lo ∨ lo+layerCount D*(2*blockBits H w) ≤ base a) :
+ ∃ t ≤ 3+layerCount D*(10*blockBits H w+14), ∃ out, Prefix M c (List.replicate t .tick) out ∧
+ out.pc = done ∧ out.reg (reg 2) = word W lo ∧ Frame reg c out ∧
+ out.privateMem = LeafFieldCopy.place lo (stream buf 0 (layerCount D) (by simp)) c.privateMem ∧
+ out.persistent = c.persistent ∧ t = 3+streamTicks D H w 0 (layerCount D) (by simp) := by
+ let a := c.put (pc .phaseTest) (reg 13) 0
+ let b := {a with pc := pc .resetStep}
+ let d := b.put (pc .stride) (reg 14) 0
+ have s0 : M.program.step c = .localStep a := step_at hl _ c hc
+ have s1 : M.program.step a = .localStep b := by
+ rw [step_at hl .phaseTest a rfl]
+ have test : a.reg (reg 13) < a.reg (reg 11) := by
+ simpa [a,Config.put,hf.dims] using (word_lt_iff (Nat.two_pow_pos W) hD).mpr hpos
+ simp [instruction,Instr.run,b,test]
+ have s2 : M.program.step b = .localStep d := step_at hl .resetStep b rfl
+ have fd : Frame reg c d := (frame_put c _ 13 _ (by decide)).trans (frame_put b _ 14 _ (by decide))
+ let first : Layer D := ⟨0,0,hpos,le_rfl⟩
+ have at0 : At pc reg done D 0 d := at_layer first 0 rfl d rfl
+ (by simp [first,d,b,a,Config.put]) (Config.put_same ..)
+ obtain ⟨t,ht,out,run,exit,cur,frame,hm,per,exactTicks⟩ := walk hl base buf lo 0 (layerCount D) (by simp) d at0
+ (hf.of_frame fd) hD (by simpa [d,b,a,Config.put] using ho) (by simpa [d,b,a,Config.put] using hd)
+ hs fit sourceFit sep
+ have start : Prefix M c (List.replicate 3 .tick) d := .tick s0 (.tick s1 (.tick s2 (.nil _)))
+ exact ⟨3+t,by omega,out,by simpa only [List.replicate_add] using start.append run,
+ exit,cur,fd.trans frame,hm,per,congrArg (3+·) exactTicks⟩
+
+end PairSimulation.LeafSortFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSourceLoad.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSourceLoad.lean
new file mode 100644
index 0000000000..07750f5b16
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSourceLoad.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.PairSimulationLeafPortWalk
+import OAI.Computability.VPVNP.LivePublicCounterOperands
+import OAI.Computability.VPVNP.LivePublicVirtualSites
+
+/-!
+# Loading the fixed public register vector of an auxiliary leaf
+
+The live program supplies the virtual address width and bucket, its own word
+width, the auxiliary clock, and all 34 auxiliary operands. Two of the latter
+are taken from the live program's literal prefix. The current leaf address
+and its full header word are dynamic and enter through separate registers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSourceLoad
+
+open BurstRAM PrivateRAM RAMTape LiveProgram LeafRegisterBank PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+/-- Fields fixed for all auxiliary leaf visits in one pair invocation. -/
+inductive Static (k : ℕ) where
+ | d | width | bucket | fuel | operand (i : Fin k)
+ deriving DecidableEq, Fintype
+
+variable {k r p pubs w : ℕ}
+
+/-- The register-bank field receiving a fixed scalar or public operand. -/
+def Static.dest : Static k → Source k
+ | .d => .d | .width => .width | .bucket => .bucket | .fuel => .fuel | .operand i => .operand i
+
+theorem Static.dest_injective : Function.Injective (@Static.dest k) := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [Static.dest]
+
+/-- Cache order for the four geometry scalars followed by the public operands. -/
+def slots (k : ℕ) : List (Static k) := [.d,.width,.bucket,.fuel] ++ (List.finRange k).map .operand
+
+theorem mem_slots (i : Static k) : i ∈ slots k := by cases i <;> simp [slots]
+
+@[simp] theorem length_slots : (slots k).length = 4+k := by simp [slots]; omega
+
+/-- The expression that computes a fixed leaf scalar from the live pair operands. -/
+def expr (c : Constants) : Static 34 → InputOperand
+ | .d => .geometry (.clog2 virtualSites)
+ | .width => .geometry .w
+ | .bucket => .geometry (.pow2 (.divConst (.add (.clog2 .n) (.lit 3)) 4))
+ | .fuel => .geometry PrimedCounter.virtualFuel
+ | .operand i => CounterPublic.operands c i
+
+/-- Update the scalar's destination register while preserving the other registers. -/
+def setStatic (ports : Source k ↪ Fin r) (vals : Static k → Word w)
+ (bank : Fin r → Word w) (i : Static k) := Function.update bank (ports i.dest) (vals i)
+
+theorem fold_at (ports : Source k ↪ Fin r) (vals : Static k → Word w) (ls : List (Static k))
+ (bank : Fin r → Word w) (j : Static k) :
+ ls.foldl (setStatic ports vals) bank (ports j.dest) = if j ∈ ls then vals j else bank (ports j.dest) := by
+ induction ls generalizing bank with
+ | nil => simp
+ | cons i ls ih =>
+ rw [List.foldl_cons,ih]
+ by_cases hi : j = i
+ · subst i; simp [setStatic]
+ · simp [hi,setStatic,ports.injective.ne (Static.dest_injective.ne hi)]
+
+theorem fold_outside (ports : Source k ↪ Fin r) (vals : Static k → Word w) (ls : List (Static k))
+ (bank : Fin r → Word w) (j : Fin r) (h : ∀ i : Static k, j ≠ ports i.dest) :
+ ls.foldl (setStatic ports vals) bank j = bank j := by
+ induction ls generalizing bank with
+ | nil => rfl
+ | cons i ls ih => simp only [List.foldl_cons, ih, setStatic, Function.update_of_ne (h i)]
+
+/-- The field's offset in the private scalar cache. -/
+def Static.offset : Static k → ℕ
+ | .d => 0 | .width => 1 | .bucket => 2 | .fuel => 3 | .operand i => 4+i.val
+
+theorem slots_offsets : (slots k).map Static.offset = List.range (4+k) := by
+ rw [List.range_add]
+ simp only [slots, List.map_append, List.map_cons, List.map_nil, Static.offset, List.map_map]
+ rw [← List.map_coe_finRange_eq_range (n := k), List.map_map]
+ rfl
+
+end PairSimulation.LeafSourceLoad
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSourceOperands.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSourceOperands.lean
new file mode 100644
index 0000000000..5dedc70e31
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSourceOperands.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSourceLoad
+
+/-! # The 38 private leaf-cache values at the paper's public parameters -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSourceLoad
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork RAMTape LiveProgram
+open LeafRegisterBank LeafStartup
+open scoped Fin.CommRing
+
+variable (c : Constants) {p : UniversalMachine.Program} {B n H : ℕ}
+ {i : Fin (2^(n^c.chainPower-1))}
+ (Q : PrimedInputRAM.Layout ((CounterPublic.spec p c).lengths n i) n (addressWidth B n) H
+ (CursorBounds.wordBits B n))
+ (D : PrimedCounter.Data Q (n^(c.circuitExponent+5)))
+
+private theorem bucket_eval (g : Geometry) :
+ (.pow2 (.divConst (.add (.clog2 .n) (.lit 3)) 4) : PublicExpr).eval g = 2^roundedUp 1 4 g.n := by
+ change 2^((Nat.clog 2 g.n+3)/4) = _
+ rw [roundedUp,pow_one,Nat.clog_pow_left]
+
+/-- The length-only operands and the two own-prefix slots agree with the
+actual coefficient counter on every pair, exterior cut and nomination. -/
+theorem paper_operands (hB : 1 ≤ B) (hn : 2 ≤ n) (hp : Q.program = p)
+ (hbase : Q.scratchBase = 2^CursorBounds.virtualBits B n) (hf : D.Fits) (hroot : D.root.val = 0)
+ (hw : 2 ≤ CursorBounds.wordBits B n)
+ (hc : 2^CursorBounds.virtualBits B n*2^roundedUp 1 4 n < 2^CursorBounds.wordBits B n)
+ (v : Position (CursorBounds.virtualBits B n))
+ (buf : Buffers (CursorBounds.virtualBits B n) (2^roundedUp 1 4 n) (CursorBounds.wordBits B n))
+ (j : Static 34) :
+ let g := AssemblerPublic.geometry B n H
+ let lit := CounterPublic.actualPrefix p
+ let x := auxiliary D hw hc v buf
+ Pieces.word g lit (expr c j) = sourceWord x D.pub j.dest ∧
+ match expr c j with
+ | .geometry e => e.Fits g (2^g.w)
+ | a => a.eval g lit < 2^g.w := by
+ let g := AssemblerPublic.geometry B n H
+ let d := CursorBounds.virtualBits B n
+ let e := roundedUp 1 4 n
+ let w := CursorBounds.wordBits B n
+ have he := Nat.two_pow_pos e
+ have hd := Nat.two_pow_pos d
+ have hdFit : 2^d < 2^w := (Nat.le_mul_of_pos_right _ he).trans_lt hc
+ have heFit : 2^e < 2^w := (Nat.le_mul_of_pos_left _ hd).trans_lt hc
+ have virtualFit := virtualSites_fits (H := H) hB hn hdFit
+ have hsite : virtualSites.eval g = 2^d := virtualSites_eval g hn
+ have hnine : 9 ≤ w := by
+ change 9 ≤ (addressWidth B n+10)^4
+ exact (by omega : 9 ≤ addressWidth B n+10).trans (Nat.le_self_pow (by decide) _)
+ have hwidth : w < 2^w := Nat.lt_two_pow_self
+ cases j with
+ | operand j => exact CounterPublic.operands_correct c Q D hB hn hp hbase hf hroot j
+ | width => exact ⟨rfl, hwidth,trivial⟩
+ | fuel =>
+ have hfuel := D.fuel_eq_virtualFuel g rfl
+ constructor
+ · change Fin.ofNat _ (PrimedCounter.virtualFuel.eval g) = (D.fuel : Word w)
+ exact congrArg (Fin.ofNat (2^w)) hfuel.symm
+ · exact PrimedCounter.virtualFuel_fits g hnine
+ | bucket =>
+ have hval := bucket_eval g
+ constructor
+ · change Fin.ofNat _ _ = ((2^e : ℕ) : Word w)
+ exact congrArg (Fin.ofNat (2^w)) hval
+ · exact ⟨hval ▸ heFit,virtualFit.2.2.2⟩
+ | d =>
+ have hval : (.clog2 virtualSites : PublicExpr).eval g = d := by
+ change Nat.clog 2 (virtualSites.eval g) = d
+ rw [hsite,Nat.clog_pow 2 _ Nat.one_lt_two]
+ constructor
+ · change Fin.ofNat _ _ = (d : Word w)
+ exact congrArg (Fin.ofNat (2^w)) hval
+ · exact ⟨hval ▸ (Nat.lt_two_pow_self (n := d)).trans hdFit,virtualFit⟩
+
+end PairSimulation.LeafSourceLoad
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSourcePrelude.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSourcePrelude.lean
new file mode 100644
index 0000000000..5d27d20f71
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSourcePrelude.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.PairSimulationLeafCacheRead
+
+/-! # Staging the leaf address, full header, and private cache pointer -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSourceLoad
+
+open BurstRAM PrivateRAM LeafRegisterBank PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {k w r p pubs : ℕ}
+
+/-- Five native instructions initializing the site, header and cache-read registers. -/
+def prelude (ports : Source k ↪ Fin r) (site hdr base cursor unit : Fin r)
+ (pc : Fin 5 → Fin p) (done : Fin p) : Fin 5 → Instr w p r pubs :=
+ ![.copy (ports .address) site (pc 1), .copy (ports .header) hdr (pc 2),
+ .constant (ports .initial) 0 (pc 3), .copy cursor base (pc 4), .constant unit 1 done]
+
+theorem prelude_resize (ports : Source k ↪ Fin r) (site hdr base cursor unit : Fin r)
+ (pc : Fin 5 → Fin p) (done : Fin p) (i : Fin 5) :
+ (prelude (w := 1) (pubs := pubs) ports site hdr base cursor unit pc done i).resize w =
+ prelude ports site hdr base cursor unit pc done i := by fin_cases i <;> rfl
+
+/-- Register disjointness needed to read each input before it can be overwritten. -/
+structure Wiring (ports : Source k ↪ Fin r) (hdr base cursor unit : Fin r) : Prop where
+ header : hdr ≠ ports .address
+ baseAddress : base ≠ ports .address
+ baseHeader : base ≠ ports .header
+ baseInitial : base ≠ ports .initial
+ cursor_disjoint : ∀ j, cursor ≠ ports j
+ unit_disjoint : ∀ j, unit ≠ ports j
+ different : cursor ≠ unit
+
+/-- Register file after the five scalar-reader initialization instructions. -/
+def prepBank (ports : Source k ↪ Fin r) (site hdr base cursor unit : Fin r) (bank : Fin r → Word w) :=
+ Function.update (Function.update (Function.update (Function.update (Function.update bank
+ (ports .address) (bank site)) (ports .header) (bank hdr)) (ports .initial) 0) cursor (bank base)) unit 1
+
+theorem prep_run (M : Machine w p r pubs) (ports : Source k ↪ Fin r) (site hdr base cursor unit : Fin r)
+ (pc : Fin 5 → Fin p) (done : Fin p)
+ (link : ∀ i, M.code (pc i) = prelude ports site hdr base cursor unit pc done i)
+ (wires : Wiring ports hdr base cursor unit) (c : Config w p r) (entry : c.pc = pc 0) :
+ Prefix M c (List.replicate 5 .tick) {c with pc := done, reg := prepBank ports site hdr base cursor unit c.reg} := by
+ let a := c.put (pc 1) (ports .address) (c.reg site)
+ let b := a.put (pc 2) (ports .header) (c.reg hdr)
+ let z := b.put (pc 3) (ports .initial) 0
+ let t := z.put (pc 4) cursor (c.reg base)
+ have row (i : Fin 5) (s : Config w p r) (he : s.pc = pc i) :
+ M.program.step s = (prelude ports site hdr base cursor unit pc done i).run M.publicData s := by
+ change (M.code s.pc).run M.publicData s = _
+ rw [he,link]
+ refine .tick (next := a) ?_ (.tick (next := b) ?_ (.tick (next := z) ?_ (.tick (next := t) ?_ (.tick ?_ (.nil _)))))
+ · rw [row 0 c entry]; rfl
+ · rw [row 1 a rfl]
+ change CallAction.localStep (a.put (pc 2) (ports .header) (a.reg hdr)) = _
+ rw [show a.reg hdr = c.reg hdr from Function.update_of_ne wires.header ..]
+ · rw [row 2 b rfl]; rfl
+ · rw [row 3 z rfl]
+ change CallAction.localStep (z.put (pc 4) cursor (z.reg base)) = _
+ have he : z.reg base = c.reg base := by
+ simp only [z,b,a,Config.put,Function.update_of_ne wires.baseInitial,Function.update_of_ne wires.baseHeader,
+ Function.update_of_ne wires.baseAddress]
+ rw [he]
+ · rw [row 4 t rfl]; rfl
+
+theorem prep_preserve (ports : Source k ↪ Fin r) (site hdr base cursor unit : Fin r) (bank : Fin r → Word w)
+ (j : Fin r) (h : ∀ i, j ≠ ports i) (hc : j ≠ cursor) (hu : j ≠ unit) :
+ prepBank ports site hdr base cursor unit bank j = bank j := by
+ simp only [prepBank,Function.update_of_ne hu,Function.update_of_ne hc,
+ Function.update_of_ne (h .initial), Function.update_of_ne (h .header), Function.update_of_ne (h .address)]
+
+end PairSimulation.LeafSourceLoad
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafStartup.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafStartup.lean
new file mode 100644
index 0000000000..b79aa30b58
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafStartup.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.RAMTapeVirtualSite
+import OAI.Computability.VPVNP.RAMTapeSiteProcessorPorts
+import OAI.Computability.VPVNP.CursorIncidentExtension
+import OAI.Computability.VPVNP.CursorInitialCheck
+import OAI.Computability.VPVNP.PrimedCounterData
+
+/-!
+# Input stacks of an auxiliary RAM validator in a compression history
+
+The auxiliary RAM has an entire word of header data at each address, including
+the nomination words. Each input of the successor reader is taken from the
+four half-wire buffers at the current vertex. Only the selected local incident
+vector is used. The sender array extending it serves in the correctness proof.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafStartup
+
+open BurstRAM CursorNetwork CursorRouting RAMLayout RAMTape LiveProgram
+open RAMTape.SiteProcessorPorts
+
+variable {d e w k r : ℕ}
+
+/-- The constant-zero expression at each public index used to fix the type of the auxiliary
+site processor's ports. -/
+abbrev expr (k : ℕ) : Fin k → PublicExpr := fun _ => .lit 0
+/-- The private stack ports of a site processor with `r` machine registers and `k` public
+operand positions. -/
+abbrev Port (r k : ℕ) := SiteProcessorPorts.Port r (expr k)
+
+/-- Names of the finite collection of public fields copied into a leaf's
+private stacks. A blank port gets length zero. -/
+inductive Field (k : ℕ) where
+ | blank | zeroWord | address | addressWidth | incident | width | slots | bucket
+ | fuel | siteCredit | choices | cap | lower | upper | initial | siteWord | header
+ | operand (i : Fin k)
+ deriving DecidableEq
+
+/-- Port assignments are fixed by the two linked stack machines. -/
+def field : Port r k → Field k
+ | .inl (.inl (.isa (.pub i))) => .operand i
+ | .inl (.inl (.credit (.budget .globalLeft))) => .zeroWord
+ | .inl (.inr (.inl (.inr .fuel))) => .fuel
+ | .inl (.inr (.inl (.inr .callCredit))) => .siteCredit
+ | .inl (.inr (.inl (.inr .choiceBudget))) => .choices
+ | .inl (.inr (.inl (.inr .globalCap))) => .cap
+ | .inl (.inr (.inl (.inr .startCost))) => .lower
+ | .inl (.inr (.inl (.inr .endCost))) => .upper
+ | .inl (.inr (.inl (.inr .initial))) => .initial
+ | .inl (.inr (.inl (.inr .addressWord))) => .siteWord
+ | .inl (.inr (.inl (.inr .headerWord))) => .header
+ | .inl (.inr (.inl (.inl (.inr (.shape .word))))) => .width
+ | .inl (.inr (.inl (.inl (.inr (.shape .blocks))))) => .slots
+ | .inl (.inr (.inl (.inl (.inr .remaining)))) => .slots
+ | .inl (.inr (.inl (.inl (.inr .zeros)))) => .zeroWord
+ | .inl (.inr (.inl (.inl (.inl (.inl .address))))) => .address
+ | .inl (.inr (.inl (.inl (.inl (.inl .incident))))) => .incident
+ | .inl (.inr (.inl (.inl (.inl (.inr (.inl .bucket)))))) => .bucket
+ | .inl (.inr (.inl (.inl (.inl (.inr (.inr .address)))))) => .addressWidth
+ | _ => .blank
+
+/-- Number of choice bits reserved for the site validator, twice its bucket size times the sum
+of its fuel and word width. -/
+def choiceBound (e w fuel : ℕ) := 2 * 2^e * (fuel+w)
+
+/-- Encode one input field as its stack bits, using binary words, unary counts, the site's
+incident vector or the selected public operand. -/
+def fieldBits (x : VirtualSite.Input d e w) (pub : Fin k → Word w) : Field k → List Bool
+ | .blank => []
+ | .zeroWord => wordBits (0 : Word w)
+ | .address => wordBits x.v
+ | .addressWidth => List.replicate d true
+ | .incident => List.ofFn (RAMLayout.incidentBits x.sends x.v)
+ | .width => List.replicate w true
+ | .slots => List.replicate (4*2^e) true
+ | .bucket => List.replicate (2^e) true
+ | .fuel => List.replicate x.fuel true
+ | .siteCredit => List.replicate (2*2^e-1) true
+ | .choices => List.replicate (choiceBound e w x.fuel) true
+ | .cap => wordBits (⟨2^d*2^e,x.hc⟩ : Word w)
+ | .lower => wordBits (SiteEndpoints.startWord e w x.v x.hcap)
+ | .upper => wordBits (SiteEndpoints.endWord e w x.v x.hcap)
+ | .initial => wordBits x.initialWord
+ | .siteWord => wordBits x.addrWord
+ | .header => wordBits x.headerWord
+ | .operand i => wordBits (pub i)
+
+/-- Assign each processor port the stack encoding of its input field for the specified site and
+public operands. -/
+def bank (r : ℕ) (x : VirtualSite.Input d e w) (pub : Fin k → Word w) : Stacks (Port r k) :=
+ fieldBits x pub ∘ field
+
+section Cursor
+
+variable {L : PrimedInputRAM.Lengths} {n a H s : ℕ} {Q : PrimedInputRAM.Layout L n a H w}
+
+/-- Local sender arrays from independently supplied half-wires. End clamps
+come from the decoder at the two chain endpoints. -/
+def sends (v : Position d) (buf : Buffers d (2^e) w) : SendArrays d (2^e) w :=
+ localExtension v.2
+ (fun s j => readBuffer buf ⟨.outgoing ((systemMask s).val.testBit v.1.val), s, j⟩)
+ (fun s j => readBuffer buf ⟨.incoming ((systemMask s).val.testBit ((finRotate d).symm v.1).val), s, j⟩)
+
+theorem sends_incident (v : Position d) (buf : Buffers d (2^e) w) :
+ RAMLayout.incidentBits (sends v buf) v.2 = incidentBuffer v buf :=
+ localExtension_incident v.2 _ _
+
+/-- The auxiliary call graph receives its complete header word and the exact
+private cutoff of the finite coefficient counter. -/
+noncomputable def auxiliary (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (v : Position d) (buf : Buffers d (2^e) w) : VirtualSite.Input d e w where
+ fuel := D.fuel
+ v := v.2
+ initialWord := 0
+ headerWord := D.initial v.2
+ sends := sends v buf
+ hw := hw
+ hc := hc
+
+theorem auxiliary_incident (D : PrimedCounter.Data Q s) (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (v : Position d) (buf : Buffers d (2^e) w) :
+ fieldBits (auxiliary D hw hc v buf) D.pub .incident = List.ofFn (incidentBuffer v buf) :=
+ congrArg List.ofFn (sends_incident v buf)
+
+end Cursor
+end PairSimulation.LeafStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorBits.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorBits.lean
new file mode 100644
index 0000000000..41f3dba6e4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorBits.lean
@@ -0,0 +1,53 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSuccessorCode
+
+/-!
+# Successor fields in the serialized incident buffer
+
+At cursor zero every successor mask selects the flip arc for a send. A
+receive selects that arc exactly for the mask reaching the last cursor bit.
+The first site's absent receive and the final site's absent send each supply
+one entire zero field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSuccessorFields
+
+open CursorNetwork CursorRouting RAMLayout
+
+variable {D H w : ℕ} [NeZero D]
+
+private theorem mask_last (j : Fin D) :
+ (systemMask (.inl j)).val.testBit (-1 : Fin D).val = decide (j.val = D-1) := by
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (NeZero.ne D)
+ simp only [systemMask, Fin.coe_neg_one, Nat.testBit_two_pow_sub_one]
+ simp only [show n < j.val + 1 ↔ j.val = n.succ - 1 by have := j.isLt; omega]
+
+/-- The outgoing and incoming successor blocks loaded by the native RAM
+are the corresponding slices of the site's decoded cursor-zero input. -/
+theorem succBits_eq (recv : Bool) (v : Site D) (buf : Buffers D H w) :
+ succBits recv v buf = List.ofFn fun j : Fin (8*w) =>
+ incidentBuffer (0,v) buf (offset D H w (.inl (if recv then 1 else 0, j))) := by
+ unfold succBits LeafIncidentLoad.Field
+ apply congrArg List.ofFn
+ funext j
+ simp only [incidentBuffer, decodeIncident, Function.comp_apply, Equiv.symm_apply_apply]
+ cases recv with
+ | false =>
+ by_cases hv : v.val + 1 < 2^D
+ · simp [selected, active, sender, sourceOffset, port, useSide, decodeSlot, hv, systemMask, readBuffer]
+ exact congrArg (buf (.outgoing true)) (Fin.ext (ramFieldOffset_successor _ _).symm)
+ · simp [selected, active, port, decodeSlot, hv]
+ | true =>
+ by_cases hv : 0 < v.val
+ · simp [selected, active, sender, sourceOffset, port, useSide, decodeSlot, hv, mask_last, readBuffer]
+ exact congrArg (buf _) (Fin.ext (ramFieldOffset_successor _ _).symm)
+ · simp [selected, active, port, decodeSlot, hv]
+
+end PairSimulation.LeafSuccessorFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorClass.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorClass.lean
new file mode 100644
index 0000000000..fddbd34595
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorClass.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSuccessorMask
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Native successor-class selection
+
+A nonwrapping successor flips a nonempty low-bit prefix. The six native
+rows compute its XOR mask and count the halvings needed to reach one.
+The sender and unit registers are preserved, including at mask one.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSuccessorClass
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord CursorRouting
+
+variable {W D p r pubs : ℕ}
+
+/-- Sender, unit, mask and class occupy registers 0, 1, 2 and 3 respectively. -/
+def instruction (pc : Fin 6 → Fin p) (reg : Fin 4 ↪ Fin r) (done : Fin p) :
+ Fin 6 → Instr W p r pubs :=
+ ![.binary .add (reg 2) (reg 0) (reg 1) (pc 1),
+ .binary .bitXor (reg 2) (reg 0) (reg 2) (pc 2),
+ .constant (reg 3) 0 (pc 3),
+ .jumpLt (reg 1) (reg 2) (pc 4) done,
+ .binary .shiftRight (reg 2) (reg 2) (reg 1) (pc 5),
+ .binary .add (reg 3) (reg 3) (reg 1) (pc 3)]
+
+theorem resize_instruction (pc : Fin 6 → Fin p) (reg : Fin 4 ↪ Fin r) (done : Fin p) (i : Fin 6) :
+ (instruction (W := 1) (pubs := pubs) pc reg done i).resize W = instruction pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- The host contains the six rows that compute a nonwrapping successor's XOR mask and its
+class by repeated halving. -/
+def Linked (M : Machine W p r pubs) (pc : Fin 6 → Fin p) (reg : Fin 4 ↪ Fin r) (done : Fin p) :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+/-- Exact observable state at the continuation. Only the two output
+registers may have changed, and the final mask is one. -/
+structure Result (reg : Fin 4 ↪ Fin r) (done : Fin p) (index : ℕ) (c out : Config W p r) : Prop where
+ pc : out.pc = done
+ maskValue : (out.reg (reg 2)).val = 1
+ classValue : (out.reg (reg 3)).val = index
+ frame : ∀ j, j ≠ reg 2 → j ≠ reg 3 → out.reg j = c.reg j
+ memory : out.privateMem = c.privateMem
+ persistent : out.persistent = c.persistent
+
+variable {M : Machine W p r pubs} {pc : Fin 6 → Fin p} {reg : Fin 4 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (link : Linked M pc reg done) (j : Fin 6) (c : Config W p r)
+ (hc : c.pc = pc j) : M.program.step c = (instruction pc reg done j).run M.publicData c := by
+ simp [Machine.program, hc, link j]
+
+private theorem loop (link : Linked M pc reg done) (rem i : ℕ) (c : Config W p r)
+ (hfit : i+rem < W) (hc : c.pc = pc 3) (ho : (c.reg (reg 1)).val = 1)
+ (hm : (c.reg (reg 2)).val = mask rem) (hi : (c.reg (reg 3)).val = i) :
+ ∃ out, Prefix M c (List.replicate (3*rem+1) .tick) out ∧ Result reg done (i+rem) c out := by
+ induction rem generalizing c i with
+ | zero =>
+ have hn : ¬ c.reg (reg 1) < c.reg (reg 2) := by
+ change ¬ (c.reg (reg 1)).val < (c.reg (reg 2)).val
+ rw [ho, hm, mask_one]
+ omega
+ let out := {c with pc := done}
+ have step : M.program.step c = .localStep out := by
+ rw [step_at link 3 c hc]
+ change CallAction.localStep {c with pc := if c.reg (reg 1) < c.reg (reg 2) then pc 4 else done} = _
+ simp [hn, out]
+ exact ⟨out, .tick step (.nil _), rfl, hm.trans mask_one, hi, fun _ _ _ => rfl, rfl, rfl⟩
+ | succ j ih =>
+ have test : c.reg (reg 1) < c.reg (reg 2) := by
+ change (c.reg (reg 1)).val < (c.reg (reg 2)).val
+ rw [ho, hm]
+ exact one_lt_mask_succ j
+ let c₁ := {c with pc := pc 4}
+ let c₂ := c₁.put (pc 5) (reg 2) (BinaryOp.shiftRight.eval (c₁.reg (reg 2)) (c₁.reg (reg 1)))
+ let c₃ := c₂.put (pc 3) (reg 3) (BinaryOp.add.eval (c₂.reg (reg 3)) (c₂.reg (reg 1)))
+ have s₁ : M.program.step c = .localStep c₁ := by
+ rw [step_at link 3 c hc]
+ change CallAction.localStep {c with pc := if c.reg (reg 1) < c.reg (reg 2) then pc 4 else done} = _
+ simp [test, c₁]
+ have s₂ : M.program.step c₁ = .localStep c₂ := step_at link 4 c₁ rfl
+ have s₃ : M.program.step c₂ = .localStep c₃ := step_at link 5 c₂ rfl
+ have h1 : (c₃.reg (reg 1)).val = 1 := by simpa [c₃, c₂, c₁, Config.put] using ho
+ have h2 : (c₃.reg (reg 2)).val = mask j := by
+ simpa [c₃, c₂, c₁, Config.put] using step_shift (t := j) (W := W) (by omega) _ hm _ ho
+ have h3 : (c₃.reg (reg 3)).val = i+1 := by
+ have bound : i+1 < 2^W := (show i+1 < W by omega).trans Nat.lt_two_pow_self
+ simp [c₃, c₂, c₁, Config.put, BinaryOp.eval, Fin.val_add, hi, ho, Nat.mod_eq_of_lt bound]
+ obtain ⟨out, tail, res⟩ := ih (i+1) c₃ (by omega) rfl h1 h2 h3
+ refine ⟨out, ?_, res.pc, res.maskValue, ?_, ?_, res.memory, res.persistent⟩
+ · rw [show 3*(j+1)+1 = 3*j+1+1+1+1 by omega]
+ exact .tick s₁ (.tick s₂ (.tick s₃ tail))
+ · rw [res.classValue]; omega
+ · intro x h₂ h₃
+ rw [res.frame x h₂ h₃]
+ simp [c₃, c₂, c₁, Config.put, Function.update_of_ne h₂, Function.update_of_ne h₃]
+
+/-- Compute the class of the actual successor edge using an arbitrary
+embedding into a native RAM table. Each successful loop iteration costs
+three instructions, in addition to initialization and the last test. -/
+theorem native (link : Linked M pc reg done) (c : Config W p r) (hc : c.pc = pc 0)
+ (x : ℕ) (hx : x+1 < 2^D) (hD : D ≤ W)
+ (hs : (c.reg (reg 0)).val = x) (ho : (c.reg (reg 1)).val = 1) :
+ ∃ out, Prefix M c (List.replicate (4+3*(successorClass hx).val) .tick) out ∧
+ Result reg done (successorClass hx).val c out := by
+ subst x
+ let a := c.put (pc 1) (reg 2) (BinaryOp.add.eval (c.reg (reg 0)) (c.reg (reg 1)))
+ let b := a.put (pc 2) (reg 2) (BinaryOp.bitXor.eval (a.reg (reg 0)) (a.reg (reg 2)))
+ let d := b.put (pc 3) (reg 3) 0
+ have s₁ : M.program.step c = .localStep a := step_at link 0 c hc
+ have s₂ : M.program.step a = .localStep b := step_at link 1 a rfl
+ have s₃ : M.program.step b = .localStep d := step_at link 2 b rfl
+ have hmask : (d.reg (reg 2)).val = mask (successorClass hx).val := by
+ simpa [d,b,a,Config.put] using sender_xor (c.reg (reg 0)) (c.reg (reg 1)) hD hx ho
+ have h1 : (d.reg (reg 1)).val = 1 := by simpa [d,b,a,Config.put] using ho
+ obtain ⟨out, tail, res⟩ := loop link (successorClass hx).val 0 d
+ (by have := (successorClass hx).isLt; omega) rfl h1 hmask (by simp [d,Config.put])
+ refine ⟨out, ?_, res.pc, res.maskValue, by simpa using res.classValue, ?_, res.memory, res.persistent⟩
+ · rw [show 4+3*(successorClass hx).val = 3*(successorClass hx).val+1+1+1+1 by omega]
+ exact .tick s₁ (.tick s₂ (.tick s₃ tail))
+ · intro z h₂ h₃
+ rw [res.frame z h₂ h₃]
+ simp [d,b,a,Config.put, Function.update_of_ne h₂, Function.update_of_ne h₃]
+
+end PairSimulation.LeafSuccessorClass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorCode.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorCode.lean
new file mode 100644
index 0000000000..b96fe66093
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorCode.lean
@@ -0,0 +1,173 @@
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentLoad
+import OAI.Computability.VPVNP.PairSimulationLeafSuccessorClass
+
+/-!
+# Native table for the successor fields at cursor zero
+
+The first eleven registers are the shared incident-field mover. Registers
+11–14 hold the dimension, last cursor, site, and site count. Register 16
+holds zero. The three temporaries 17–19 hold the sender, mask, and class.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSuccessorFields
+
+open BurstRAM PrivateRAM CursorNetwork CursorRouting PrimedCounter.GuessWord
+open LeafFieldCopy (word)
+
+variable {D H w W p r k : ℕ}
+
+/-- Control labels for testing outgoing and incoming endpoints, classifying the sender,
+choosing a half-wire and copying its successor field. -/
+inductive Stage where
+ | sendNext | sendTest | recvTest | sender (recv : Bool) | zeroOffset (recv : Bool)
+ | classify (recv : Bool) (i : Fin 6) | offset (recv : Bool) | side
+ | prepare (recv : Bool) (use : Option Bool) (i : Fin 2)
+ | move (recv : Bool) (use : Option Bool) (i : Fin 5)
+ deriving DecidableEq, Fintype
+
+/-- Embed the incident-field mover's eleven registers in the first eleven slots of the
+successor loader. -/
+def subRegs (reg : Fin 20 ↪ Fin r) : Fin 11 ↪ Fin r := (Fin.castAddEmb 9).trans reg
+
+/-- Wire the classifier's sender, unit, mask and class registers to successor-loader slots 17,
+3, 18 and 19. -/
+def classRegs (reg : Fin 20 ↪ Fin r) : Fin 4 ↪ Fin r :=
+ (⟨![17,3,18,19], by decide⟩ : Fin 4 ↪ Fin 20).trans reg
+
+/-- Turn a selected side into the incoming or outgoing half-wire port, retaining an absent
+selection at an endpoint. -/
+def port (recv : Bool) (use : Option Bool) : Option LocalPort :=
+ use.map fun side => if recv then .incoming side else .outgoing side
+
+/-- The successor-loader row at a given stage, from testing whether an edge exists through
+choosing the source field and moving its bits. -/
+def instruction (pc : Stage → Fin p) (reg : Fin 20 ↪ Fin r) (done : Fin p) : Stage → Instr W p r k
+ | .sendNext => .binary .add (reg 17) (reg 13) (reg 3) (pc .sendTest)
+ | .sendTest => .jumpEq (reg 17) (reg 14) (pc (.zeroOffset false)) (pc (.sender false))
+ | .recvTest => .jumpEq (reg 13) (reg 16) (pc (.zeroOffset true)) (pc (.sender true))
+ | .sender false => .copy (reg 17) (reg 13) (pc (.classify false 0))
+ | .sender true => .binary .sub (reg 17) (reg 13) (reg 3) (pc (.classify true 0))
+ | .zeroOffset recv => .constant (reg 6) 0 (pc (.prepare recv none 0))
+ | .classify recv i => LeafSuccessorClass.instruction (pc ∘ Stage.classify recv) (classRegs reg)
+ (pc (.offset recv)) i
+ | .offset recv => .binary .mul (reg 6) (reg 19) (reg 5) (pc (if recv then .side else .prepare false (some true) 0))
+ | .side => .jumpEq (reg 19) (reg 12) (pc (.prepare true (some true) 0)) (pc (.prepare true (some false) 0))
+ | .prepare recv use i => LeafIncidentLoad.prepare (port recv use) (pc ∘ Stage.prepare recv use)
+ (subRegs reg) (pc (.move recv use 0)) i
+ | .move recv use i => LeafFieldCopy.instruction (LeafIncidentLoad.mode (port recv use))
+ (pc ∘ Stage.move recv use) (LeafIncidentLoad.copyRegs (subRegs reg)) (if recv then done else pc .recvTest) i
+
+theorem resize_instruction (pc : Stage → Fin p) (reg : Fin 20 ↪ Fin r) (done : Fin p) (s : Stage) :
+ (instruction (W := 1) (k := k) pc reg done s).resize W = instruction pc reg done s := by
+ cases s <;> try rfl
+ case sender recv => cases recv <;> rfl
+ case classify => exact LeafSuccessorClass.resize_instruction ..
+ case prepare => exact LeafIncidentLoad.resize_prepare ..
+ case move => exact LeafFieldCopy.resize_instruction ..
+
+/-- Each host instruction at a successor-loader stage implements its prescribed row using the
+supplied register placement and exit. -/
+def Linked (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 20 ↪ Fin r) (done : Fin p) :=
+ ∀ s, M.code (pc s) = instruction pc reg done s
+
+/-- The sending site index of an outgoing edge is the current index. For an incoming edge it is
+the preceding index, with subtraction truncated at zero. -/
+def sender (recv : Bool) (v : Fin (2^D)) := if recv then v.val-1 else v.val
+
+/-- Whether the indicated edge exists without wrapping. An incoming edge requires a positive
+site index and outgoing requires a successor below the site count. -/
+def active (recv : Bool) (v : Fin (2^D)) : Bool :=
+ if recv then decide (0 < v.val) else decide (v.val+1 < 2^D)
+
+theorem sender_lt (recv : Bool) (v : Fin (2^D)) (h : active recv v = true) : sender recv v + 1 < 2^D := by
+ cases recv <;> simp [active, sender] at h ⊢ <;> have := v.isLt <;> omega
+
+/-- The low-bit successor class of the edge's sender, or no class at a missing nonwrapping
+endpoint. -/
+def selected (recv : Bool) (v : Fin (2^D)) : Option (Fin D) :=
+ if h : active recv v then some (successorClass (sender_lt recv v h)) else none
+
+/-- The outgoing field uses the true side. The incoming field uses that side exactly for the
+final successor class. -/
+def useSide (recv : Bool) (j : Fin D) : Bool := if recv then decide (j.val = D-1) else true
+
+/-- Offset of the selected successor field in its half-wire buffer, measured in blocks of eight
+machine words' worth of bits. -/
+def sourceOffset (recv : Bool) (v : Fin (2^D)) (w : ℕ) := ((selected recv v).map Fin.val).getD 0 * (8*w)
+
+theorem offsetFits [NeZero D] (recv : Bool) (v : Fin (2^D)) :
+ sourceOffset recv v w + 8*w ≤ ramPayloadWidth D H w := by
+ unfold sourceOffset ramPayloadWidth
+ cases h : selected recv v with
+ | none =>
+ have hd : 1 ≤ D := Nat.pos_of_ne_zero (NeZero.ne D)
+ have := Nat.mul_le_mul_right (8*w) hd
+ simp only [Option.map_none, Option.getD_none, Nat.zero_mul, Nat.zero_add]
+ omega
+ | some j =>
+ have := Nat.mul_le_mul_right (8*w) j.isLt
+ rw [Nat.succ_mul] at this
+ simp only [Option.map_some, Option.getD_some]
+ omega
+
+/-- The eight-word successor field selected from the incoming or outgoing half-wire buffer,
+with an all-zero field at a missing endpoint. -/
+def succBits [NeZero D] (recv : Bool) (v : Fin (2^D)) (buf : Buffers D H w) : List Bool :=
+ LeafIncidentLoad.Field (port recv ((selected recv v).map (useSide recv))) (sourceOffset recv v w) (8*w)
+ (offsetFits recv v) buf
+
+@[simp] theorem length_succBits [NeZero D] (recv : Bool) (v : Fin (2^D)) (buf : Buffers D H w) :
+ (succBits recv v buf).length = 8*w := List.length_ofFn
+
+/-- The shared mover and geometry registers hold the constants, half-wire bases, field length,
+dimension and site coordinates required for successor selection. -/
+structure Fixed (reg : Fin 20 ↪ Fin r) (base : LocalPort → ℕ) (v : Fin (2^D)) (w : ℕ) (c : Config W p r) : Prop where
+ one : c.reg (reg 3) = 1
+ len : c.reg (reg 5) = word W (8*w)
+ bases : ∀ a, c.reg (subRegs reg (LeafIncidentLoad.baseReg a)) = word W (base a)
+ dims : c.reg (reg 11) = word W D
+ last : c.reg (reg 12) = word W (D-1)
+ site : c.reg (reg 13) = word W v.val
+ sites : c.reg (reg 14) = word W (2^D)
+ zero : c.reg (reg 16) = 0
+
+/-- Indices of the eight local registers that the successor-field selection and copy may
+overwrite. -/
+def changed : List (Fin 20) := [0,1,2,4,6,17,18,19]
+
+/-- Every host register outside the successor loader's eight writable slots agrees between the
+input and output configurations. -/
+def Frame (reg : Fin 20 ↪ Fin r) (c out : Config W p r) :=
+ ∀ i, (∀ j ∈ changed, i ≠ reg j) → out.reg i = c.reg i
+
+theorem Frame.trans {reg : Fin 20 ↪ Fin r} {a b c : Config W p r} (h : Frame reg a b) (h' : Frame reg b c) :
+ Frame reg a c := fun i hi => (h' i hi).trans (h i hi)
+
+theorem Fixed.of_frame {reg : Fin 20 ↪ Fin r} {base v w} {c out : Config W p r}
+ (f : Fixed reg base (D := D) v w c) (h : Frame reg c out) : Fixed reg base v w out := by
+ have keep (j : Fin 20) (hj : j ∉ changed) : out.reg (reg j) = c.reg (reg j) :=
+ h _ (fun a ha => reg.injective.ne (fun eq => hj (eq ▸ ha)))
+ refine ⟨(keep _ (by decide)).trans f.one, (keep _ (by decide)).trans f.len, ?_,
+ (keep _ (by decide)).trans f.dims, (keep _ (by decide)).trans f.last, (keep _ (by decide)).trans f.site,
+ (keep _ (by decide)).trans f.sites, (keep _ (by decide)).trans f.zero⟩
+ intro a
+ exact (keep (Fin.castAdd 9 (LeafIncidentLoad.baseReg a))
+ (by cases a with | outgoing b | incoming b => cases b <;> decide)).trans (f.bases a)
+
+theorem frame_put {reg : Fin 20 ↪ Fin r} (c : Config W p r) (next : Fin p) (j : Fin 20)
+ (v : Word W) (hj : j ∈ changed) : Frame reg c (c.put next (reg j) v) :=
+ fun _ hi => Function.update_of_ne (hi j hj) _ _
+
+theorem step_at {M : Machine W p r k} {pc : Stage → Fin p} {reg : Fin 20 ↪ Fin r} {done : Fin p}
+ (hl : Linked M pc reg done) (s : Stage) (c : Config W p r) (hc : c.pc = pc s) :
+ M.program.step c = (instruction pc reg done s).run M.publicData c := by simp [Machine.program,hc,hl s]
+
+end PairSimulation.LeafSuccessorFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorEndpoints.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorEndpoints.lean
new file mode 100644
index 0000000000..14a078cd43
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorEndpoints.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSuccessorCode
+
+/-!
+# Testing the endpoints of successor fields
+
+A site sends its successor field unless it is the last site. It receives
+a field unless it is site zero. The active paths enter the classifier with
+the sending site's address, while the two endpoints select a zero field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSuccessorFields
+
+open BurstRAM PrivateRAM CursorNetwork PrimedCounter.GuessWord
+open LeafFieldCopy (word)
+open scoped Fin.CommRing
+
+variable {D W p r k : ℕ} {M : Machine W p r k} {pc : Stage → Fin p}
+variable {reg : Fin 20 ↪ Fin r} {done : Fin p}
+
+private theorem endpoint_test (link : Linked M pc reg done) (recv : Bool) (base : LocalPort → ℕ)
+ (v : Fin (2^D)) (w : ℕ) (c : Config W p r) (hc : c.pc = pc (if recv then .recvTest else .sendNext))
+ (fixed : Fixed reg base v w c) (hDW : D < W) :
+ ∃ d, Prefix M c (List.replicate (if recv then 1 else 2) .tick) d ∧
+ d.pc = pc (if active recv v then .sender recv else .zeroOffset recv) ∧
+ d.reg (reg 2) = c.reg (reg 2) ∧ Frame reg c d ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ have cap : 2^D < 2^W := Nat.pow_lt_pow_right (by decide) hDW
+ have vfit := v.isLt.trans cap
+ cases recv with
+ | false =>
+ let next := c.put (pc .sendTest) (reg 17) (BinaryOp.add.eval (c.reg (reg 13)) (c.reg (reg 3)))
+ have s₁ : M.program.step c = .localStep next := step_at link .sendNext c hc
+ have val : (next.reg (reg 17)).val = v.val+1 := by
+ have fit : v.val+1 < 2^W := lt_of_le_of_lt v.isLt cap
+ simp [next, Config.put, BinaryOp.eval, fixed.site, fixed.one, word, Fin.val_add, Fin.val_natCast,
+ Nat.mod_eq_of_lt vfit, Nat.mod_eq_of_lt fit, Nat.mod_eq_of_lt (by omega : 1 < 2^W)]
+ have sites : (next.reg (reg 14)).val = 2^D := by
+ have eq : next.reg (reg 14) = word W (2^D) := by simpa [next, Config.put] using fixed.sites
+ rw [eq, Fin.val_cast_of_lt cap]
+ let d := {next with pc := pc (if active false v then .sender false else .zeroOffset false)}
+ have s₂ : M.program.step next = .localStep d := by
+ rw [step_at link .sendTest next rfl]
+ by_cases hv : v.val+1 < 2^D
+ · have ne : next.reg (reg 17) ≠ next.reg (reg 14) := by
+ intro he
+ have := congrArg Fin.val he
+ omega
+ simp [instruction, Instr.run, d, active, hv, ne]
+ · have he : next.reg (reg 17) = next.reg (reg 14) := Fin.ext (by have := v.isLt; omega)
+ simp [instruction, Instr.run, d, active, hv, he]
+ refine ⟨d, .tick s₁ (.tick s₂ (.nil _)), rfl, ?_, frame_put c _ 17 _ (by decide), rfl, rfl⟩
+ simp [d, next, Config.put]
+ | true =>
+ let d := {c with pc := pc (if active true v then .sender true else .zeroOffset true)}
+ have val : (c.reg (reg 13)).val = v.val := by
+ rw [fixed.site, Fin.val_cast_of_lt vfit]
+ have s₁ : M.program.step c = .localStep d := by
+ rw [step_at link .recvTest c hc]
+ by_cases hv : 0 < v.val
+ · have ne : c.reg (reg 13) ≠ c.reg (reg 16) := by
+ rw [fixed.zero]
+ intro he
+ rw [he] at val
+ simp at val
+ omega
+ simp [instruction, Instr.run, d, active, hv, ne]
+ · have he : c.reg (reg 13) = c.reg (reg 16) := by
+ rw [fixed.zero]
+ exact Fin.ext (by simpa only [Fin.val_zero] using val.trans (Nat.eq_zero_of_not_pos hv))
+ simp [instruction, Instr.run, d, active, hv, he]
+ exact ⟨d, .tick s₁ (.nil _), rfl, rfl, fun _ _ => rfl, rfl, rfl⟩
+
+/-- Run the linked endpoint rows. Both paths preserve the destination cursor
+in register two, every register in the frame, and all private memory. -/
+theorem endpoint_run (link : Linked M pc reg done) (recv : Bool) (base : LocalPort → ℕ)
+ (v : Fin (2^D)) (w : ℕ) (c : Config W p r) (hc : c.pc = pc (if recv then .recvTest else .sendNext))
+ (fixed : Fixed reg base v w c) (hDW : D < W) :
+ ∃ d, Prefix M c (List.replicate (if recv then 2 else 3) .tick) d ∧
+ (if active recv v then d.pc = pc (.classify recv 0) ∧ (d.reg (reg 17)).val = sender recv v
+ else d.pc = pc (.prepare recv none 0) ∧ d.reg (reg 6) = 0) ∧
+ d.reg (reg 2) = c.reg (reg 2) ∧ Frame reg c d ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨b, test, atBranch, cursor, frame, mem, state⟩ := endpoint_test link recv base v w c hc fixed hDW
+ have ext {d : Config W p r} (h : M.program.step b = .localStep d) :
+ Prefix M c (List.replicate (if recv then 2 else 3) .tick) d := by
+ have run := test.append (.tick h (.nil _) : Prefix M b [.tick] d)
+ cases recv <;> exact run
+ have fb := fixed.of_frame frame
+ cases use : active recv v with
+ | false =>
+ simp only [use, Bool.false_eq_true, ↓reduceIte] at atBranch ⊢
+ let d := b.put (pc (.prepare recv none 0)) (reg 6) 0
+ have hs : M.program.step b = .localStep d := step_at link (.zeroOffset recv) b atBranch
+ refine ⟨d, ext hs, ⟨rfl, ?_⟩, ?_, frame.trans (frame_put b _ 6 _ (by decide)), mem, state⟩
+ · simp [d, Config.put]
+ · simpa [d, Config.put] using cursor
+ | true =>
+ simp only [use, ↓reduceIte] at atBranch ⊢
+ let value := if recv then BinaryOp.sub.eval (b.reg (reg 13)) (b.reg (reg 3)) else b.reg (reg 13)
+ let d := b.put (pc (.classify recv 0)) (reg 17) value
+ have hs : M.program.step b = .localStep d := by
+ cases recv <;> exact step_at link (.sender _) b atBranch
+ have vfit := v.isLt.trans (Nat.pow_lt_pow_right (by decide : 1 < 2) hDW)
+ have value_eq : value = word W (sender recv v) := by
+ cases recv with
+ | false => exact fb.site
+ | true =>
+ have hv : 0 < v.val := by simpa [active] using use
+ change b.reg (reg 13) - b.reg (reg 3) = word W (v.val-1)
+ rw [fb.site, fb.one, sub_eq_iff_eq_add]
+ simpa only [word, Nat.cast_add, Nat.cast_one] using
+ congrArg (fun n : ℕ => (n : Word W)) (Nat.sub_add_cancel hv).symm
+ have hsender : sender recv v < 2^W := by cases recv <;> simp [sender] <;> omega
+ refine ⟨d, ext hs, ⟨rfl, ?_⟩, ?_, frame.trans (frame_put b _ 17 _ (by decide)), mem, state⟩
+ · simp [d, Config.put, value_eq, word, Fin.val_cast_of_lt hsender]
+ · simpa [d, Config.put] using cursor
+
+end PairSimulation.LeafSuccessorFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorFields.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorFields.lean
new file mode 100644
index 0000000000..0423017594
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorFields.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSuccessorSelect
+import OAI.Computability.VPVNP.PairSimulationLeafSuccessorEndpoints
+import OAI.Computability.VPVNP.PairSimulationLeafSortFields
+
+/-!
+# Executing both successor fields in the native leaf loader
+
+The machine copies the outgoing bits first, then the incoming bits, using a
+descending destination cursor. Nonwrapping edges select their own low-bit
+mask class. A missing edge contributes a whole zero field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSuccessorFields
+
+open BurstRAM PrivateRAM CursorNetwork CursorRouting PrimedCounter.GuessWord
+open LeafFieldCopy (word)
+open LeafIncidentLoad (Stored)
+
+variable {W D H w p r k : ℕ} {M : Machine W p r k} {pc : Stage → Fin p} {reg : Fin 20 ↪ Fin r} {done : Fin p}
+
+/-- Instruction count for selecting one incoming or outgoing successor field, including
+endpoint tests and any class calculation. -/
+def selectionTicks (recv : Bool) (v : Fin (2^D)) : ℕ :=
+ (if recv then 2 else 3) + (selected recv v).elim 0 (fun j => 5+3*j.val+(if recv then 1 else 0))
+
+theorem selectionTicks_le (recv : Bool) (v : Fin (2^D)) : selectionTicks recv v ≤ 3*D+9 := by
+ unfold selectionTicks
+ cases h : selected recv v with
+ | none => cases recv <;> simp
+ | some j => have := j.isLt; cases recv <;> simp <;> omega
+
+private theorem selection_run (link : Linked M pc reg done) (recv : Bool) (base : LocalPort → ℕ)
+ (v : Fin (2^D)) (c : Config W p r) (hc : c.pc = pc (if recv then .recvTest else .sendNext))
+ (hf : Fixed reg base v w c) (hDW : D < W) :
+ ∃ out, Prefix M c (List.replicate (selectionTicks recv v) .tick) out ∧
+ out.pc = pc (.prepare recv ((selected recv v).map (useSide recv)) 0) ∧
+ out.reg (reg 6) = word W (sourceOffset recv v w) ∧ out.reg (reg 2) = c.reg (reg 2) ∧
+ Frame reg c out ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ obtain ⟨d, pre, hd, hcur, hframe, hmem, hp⟩ := endpoint_run link recv base v w c hc hf hDW
+ cases hact : active recv v with
+ | false =>
+ simp only [hact, Bool.false_eq_true, ↓reduceIte] at hd
+ simpa [selectionTicks, selected, sourceOffset, hact] using
+ (show ∃ out, Prefix M c (List.replicate (if recv then 2 else 3) .tick) out ∧
+ out.pc = pc (.prepare recv none 0) ∧ out.reg (reg 6) = 0 ∧ out.reg (reg 2) = c.reg (reg 2) ∧
+ Frame reg c out ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent from
+ ⟨d, pre, hd.1, hd.2, hcur, hframe, hmem, hp⟩)
+ | true =>
+ simp only [hact, ite_true] at hd
+ obtain ⟨out, tail, hpc, hoff, hc', hf', hm', hp'⟩ := classify_run link recv base v d hd.1
+ (hf.of_frame hframe) hDW hact hd.2
+ refine ⟨out, ?_, ?_, ?_, hc'.trans hcur, hframe.trans hf', hm'.trans hmem, hp'.trans hp⟩
+ · simpa [selectionTicks, selected, hact, ← List.replicate_add] using pre.append tail
+ · simpa [selected, hact] using hpc
+ · simpa [sourceOffset, selected, hact] using hoff
+
+variable [NeZero D]
+
+/-- The field copy reaches its exit with the private cursor at the lower address and the
+selected bits placed there, preserving persistent state and registers outside the writable
+slots. -/
+structure Result (reg : Fin 20 ↪ Fin r) (exit : Fin p) (lo : ℕ) (bits : List Bool)
+ (c out : Config W p r) : Prop where
+ pc : out.pc = exit
+ cursor : out.reg (reg 2) = word W lo
+ frame : Frame reg c out
+ memory : out.privateMem = LeafFieldCopy.place lo bits c.privateMem
+ persistent : out.persistent = c.persistent
+
+/-- Select and move one entire successor field, restoring every architectural
+input needed for the following direction. -/
+theorem field_run (link : Linked M pc reg done) (recv : Bool) (base : LocalPort → ℕ)
+ (buf : Buffers D H w) (v : Fin (2^D)) (lo : ℕ) (c : Config W p r)
+ (hc : c.pc = pc (if recv then .recvTest else .sendNext)) (hf : Fixed reg base v w c) (hDW : D < W)
+ (hd : c.reg (reg 2) = word W (lo+8*w)) (stored : Stored base buf c.privateMem)
+ (fit : lo+8*w < 2^W) (sourceFit : ∀ a, base a+ramPayloadWidth D H w ≤ 2^W)
+ (apart : ∀ a, base a+ramPayloadWidth D H w ≤ lo ∨ lo+8*w ≤ base a) :
+ ∃ out, Prefix M c (List.replicate (selectionTicks recv v+(5*(8*w)+3)) .tick) out ∧
+ Result reg (if recv then done else pc .recvTest) lo (succBits recv v buf) c out := by
+ obtain ⟨d, prefixRun, he, ho, hcur, fr, mem, persist⟩ := selection_run link recv base v c hc hf hDW
+ let use := (selected recv v).map (useSide recv)
+ let exit := if recv then done else pc .recvTest
+ have fd := hf.of_frame fr
+ obtain ⟨out, copy, res⟩ := LeafIncidentLoad.copy_run M (port recv use)
+ (pc ∘ Stage.prepare recv use) (pc ∘ Stage.move recv use) (subRegs reg) exit
+ (fun j => link (.prepare recv use j)) (fun j => link (.move recv use j))
+ base buf (sourceOffset recv v w) (8*w) lo (offsetFits recv v) fit apart sourceFit
+ d he fd.bases fd.len ho (hcur.trans hd) fd.one (mem ▸ stored)
+ refine ⟨out, ?_, res.pc, res.cursor, fr.trans ?_, ?_, res.persistent.trans persist⟩
+ · simpa only [← List.replicate_add] using prefixRun.append copy
+ · intro i hi
+ exact res.frame i (hi 0 (by decide)) (hi 1 (by decide)) (hi 2 (by decide)) (hi 4 (by decide))
+ · simpa only [mem, succBits, use] using res.mem
+
+/-- Total instructions for selecting and copying the outgoing and incoming successor fields,
+each of length eight times the word width. -/
+def ticks (v : Fin (2^D)) (w : ℕ) :=
+ (selectionTicks false v+(5*(8*w)+3)) + (selectionTicks true v+(5*(8*w)+3))
+
+omit [NeZero D] in
+theorem ticks_le (v : Fin (2^D)) (w : ℕ) : ticks v w ≤ 80*w+6*D+24 := by
+ have := selectionTicks_le false v
+ have := selectionTicks_le true v
+ dsimp [ticks]
+ omega
+
+/-- The complete pair of physical fields is placed at the destination in
+the send-then-receive logical order, including both nonwrapping endpoints. -/
+theorem pair_run (link : Linked M pc reg done) (base : LocalPort → ℕ)
+ (buf : Buffers D H w) (v : Fin (2^D)) (lo : ℕ) (c : Config W p r)
+ (hc : c.pc = pc .sendNext) (hf : Fixed reg base v w c) (hDW : D < W)
+ (hd : c.reg (reg 2) = word W (lo+16*w)) (stored : Stored base buf c.privateMem)
+ (fit : lo+16*w < 2^W) (sourceFit : ∀ a, base a+ramPayloadWidth D H w ≤ 2^W)
+ (apart : ∀ a, base a+ramPayloadWidth D H w ≤ lo ∨ lo+16*w ≤ base a) :
+ ∃ out, Prefix M c (List.replicate (ticks v w) .tick) out ∧
+ Result reg done lo (succBits false v buf ++ succBits true v buf) c out := by
+ have hd' : c.reg (reg 2) = word W ((lo+8*w)+8*w) := by convert hd using 2; omega
+ have sep (a : LocalPort) : base a+ramPayloadWidth D H w ≤ lo+8*w ∨ (lo+8*w)+8*w ≤ base a := by
+ have := apart a; omega
+ obtain ⟨d, send, sr⟩ := field_run link false base buf v (lo+8*w) c hc hf hDW hd' stored
+ (by omega) sourceFit sep
+ have intact : Stored base buf d.privateMem := by
+ rw [sr.memory]
+ exact LeafSortFields.stored_place base buf _ _ _ stored (by simp; omega) sourceFit
+ (fun a => by simpa only [length_succBits] using sep a)
+ obtain ⟨out, receive, rr⟩ := field_run link true base buf v lo d sr.pc (hf.of_frame sr.frame) hDW
+ sr.cursor intact (by omega) sourceFit (fun a => by have := apart a; omega)
+ refine ⟨out, ?_, rr.pc, rr.cursor, sr.frame.trans rr.frame, ?_, rr.persistent.trans sr.persistent⟩
+ · simpa only [ticks, ← List.replicate_add] using send.append receive
+ · rw [rr.memory, sr.memory, LeafIncidentLoad.place_append, length_succBits]
+
+end PairSimulation.LeafSuccessorFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorMask.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorMask.lean
new file mode 100644
index 0000000000..92444cd418
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorMask.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.CursorRouting
+import OAI.Computability.VPVNP.RAMProgram
+
+/-!
+# Low-bit masks in the native successor selector
+
+The XOR of a nonwrapping sender and its successor is a nonempty prefix of
+one bits. A one-bit right shift shortens that prefix by one. These identities
+justify both the selector's initial register and its subsequent countdown.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSuccessorClass
+
+open BurstRAM BurstRAM.PrivateRAM
+
+/-- The bits from zero through `t`, inclusive. -/
+def mask (t : ℕ) := 2 ^ (t+1) - 1
+
+theorem mask_one : mask 0 = 1 := rfl
+
+theorem mask_pos (t : ℕ) : 0 < mask t := by
+ have h := Nat.two_pow_pos t
+ rw [mask, pow_succ]
+ omega
+
+theorem one_lt_mask_succ (t : ℕ) : 1 < mask (t+1) := by
+ have h := mask_pos t
+ rw [mask] at h
+ rw [mask, pow_succ _ (t+1)]
+ omega
+
+theorem mask_half (t : ℕ) : mask (t+1) / 2 = mask t := by
+ have h := Nat.two_pow_pos (t+1)
+ rw [mask, mask, pow_succ _ (t+1)]
+ omega
+
+theorem mask_lt_mod {t W : ℕ} (h : t < W) : mask t < 2^W := by
+ have hle := Nat.pow_le_pow_right (by decide : 0 < 2) (show t+1 ≤ W from h)
+ have hp := Nat.two_pow_pos (t+1)
+ unfold mask
+ omega
+
+theorem step_shift {t W : ℕ} (h : t+1 < W) (a : Word W) (ha : a.val = mask (t+1))
+ (one : Word W) (ho : one.val = 1) :
+ (BinaryOp.shiftRight.eval a one).val = mask t := by
+ simp only [BinaryOp.eval, ho, show 1 < W by omega, ↓reduceIte, Fin.val_ofNat, ha,
+ Nat.shiftRight_eq_div_pow, pow_one, mask_half, Nat.mod_eq_of_lt (mask_lt_mod (by omega : t < W))]
+
+/-- The arithmetic instructions produce the mask for the sender's unique
+nonwrapping successor class. -/
+theorem sender_xor {W : ℕ} (a one : Word W) {D : ℕ} (hD : D ≤ W)
+ (hx : a.val+1 < 2^D) (ho : one.val = 1) :
+ (BinaryOp.bitXor.eval a (BinaryOp.add.eval a one)).val = mask (CursorRouting.successorClass hx).val := by
+ have hnext := hx.trans_le (Nat.pow_le_pow_right (by decide : 0 < 2) hD)
+ have hxor := (CursorRouting.successorClass_eq_iff hx (CursorRouting.successorClass hx)).mp rfl
+ change a.val ^^^ (a.val+1) = mask (CursorRouting.successorClass hx).val at hxor
+ simp only [BinaryOp.eval, Fin.val_ofNat, Fin.val_add, ho, Nat.mod_eq_of_lt hnext, hxor,
+ Nat.mod_eq_of_lt (mask_lt_mod ((CursorRouting.successorClass hx).isLt.trans_le hD))]
+
+end PairSimulation.LeafSuccessorClass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorSelect.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorSelect.lean
new file mode 100644
index 0000000000..67e774b80b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafSuccessorSelect.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PairSimulationLeafSuccessorCode
+
+/-!
+# Choosing the source arc and offset for an active successor field
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafSuccessorFields
+
+open BurstRAM PrivateRAM CursorNetwork CursorRouting PrimedCounter.GuessWord
+open LeafFieldCopy (word)
+open scoped Fin.CommRing
+
+variable {W D w p r k : ℕ} {M : Machine W p r k} {pc : Stage → Fin p} {reg : Fin 20 ↪ Fin r} {done : Fin p}
+
+theorem classify_run (link : Linked M pc reg done) (recv : Bool) (base : LocalPort → ℕ)
+ (v : Fin (2^D)) (c : Config W p r) (hc : c.pc = pc (.classify recv 0))
+ (hf : Fixed reg base v w c) (hDW : D < W) (hactive : active recv v = true)
+ (hsender : (c.reg (reg 17)).val = sender recv v) :
+ let j := successorClass (sender_lt recv v hactive)
+ ∃ out, Prefix M c (List.replicate (5+3*j.val+(if recv then 1 else 0)) .tick) out ∧
+ out.pc = pc (.prepare recv (some (useSide recv j)) 0) ∧
+ out.reg (reg 6) = word W (j.val*(8*w)) ∧ out.reg (reg 2) = c.reg (reg 2) ∧
+ Frame reg c out ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let j := successorClass (sender_lt recv v hactive)
+ have hl : LeafSuccessorClass.Linked M (pc ∘ Stage.classify recv) (classRegs reg) (pc (.offset recv)) :=
+ fun i => link (.classify recv i)
+ have hone : (c.reg (classRegs reg 1)).val = 1 := by
+ change (c.reg (reg 3)).val = 1
+ rw [hf.one]
+ exact Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega))
+ obtain ⟨a, pa, ra⟩ := LeafSuccessorClass.native hl c hc (sender recv v) (sender_lt recv v hactive)
+ hDW.le hsender hone
+ have fa : Frame reg c a :=
+ fun z hz => ra.frame z (hz 18 (by decide)) (hz 19 (by decide))
+ have fixed := hf.of_frame fa
+ have cur : a.reg (reg 2) = c.reg (reg 2) :=
+ ra.frame _ (reg.injective.ne (by decide : (2 : Fin 20) ≠ 18))
+ (reg.injective.ne (by decide : (2 : Fin 20) ≠ 19))
+ have hfit : j.val < 2^W := (j.isLt.trans hDW).trans Nat.lt_two_pow_self
+ have hj : a.reg (reg 19) = word W j.val := by
+ apply Fin.ext
+ exact ra.classValue.trans (Nat.mod_eq_of_lt hfit).symm
+ let b := a.put (pc (if recv then .side else .prepare false (some true) 0)) (reg 6) (word W (j.val*(8*w)))
+ have step : M.program.step a = .localStep b := by
+ rw [step_at link _ a ra.pc]
+ simp [instruction, Instr.run, BinaryOp.eval, hj, fixed.len, b, word]
+ have fb : Frame reg a b := frame_put _ _ _ _ (by decide)
+ have cur' : b.reg (reg 2) = c.reg (reg 2) := by simpa [b, Config.put] using cur
+ dsimp only
+ cases recv with
+ | false =>
+ refine ⟨b, ?_, rfl, by simp [b, Config.put, j], cur', fa.trans fb, ra.memory, ra.persistent⟩
+ have h := pa.append (Prefix.tick step (.nil b))
+ change Prefix M c (List.replicate (5+3*j.val+0) .tick) b
+ change Prefix M c (List.replicate (4+3*j.val) .tick ++ List.replicate 1 .tick) b at h
+ rwa [← List.replicate_add, show 4+3*j.val+1 = 5+3*j.val+0 by omega] at h
+ | true =>
+ let dest := pc (.prepare true (some (useSide true j)) 0)
+ let out := {b with pc := dest}
+ have hlast : D-1 < 2^W := (show D-1 < W by omega).trans Nat.lt_two_pow_self
+ have eq : b.reg (reg 19) = b.reg (reg 12) ↔ j.val = D-1 := by
+ simp only [b, Config.put, Function.update_of_ne (reg.injective.ne (by decide : (19 : Fin 20) ≠ 6)),
+ Function.update_of_ne (reg.injective.ne (by decide : (12 : Fin 20) ≠ 6)), hj, fixed.last]
+ constructor
+ · intro h
+ have e := congrArg Fin.val h
+ change j.val % 2^W = (D-1)%2^W at e
+ rwa [Nat.mod_eq_of_lt hfit, Nat.mod_eq_of_lt hlast] at e
+ · rintro h; rw [h]
+ have sside : M.program.step b = .localStep out := by
+ rw [step_at link .side b rfl]
+ simp only [instruction, Instr.run, eq, out, dest, useSide, ite_true]
+ split <;> simp_all
+ refine ⟨out, ?_, rfl, by simp [out, b, Config.put, j], cur', fa.trans fb, ra.memory, ra.persistent⟩
+ have h := pa.append (Prefix.tick step (.tick sside (.nil out)))
+ change Prefix M c (List.replicate (5+3*j.val+1) .tick) out
+ change Prefix M c (List.replicate (4+3*j.val) .tick ++ List.replicate 2 .tick) out at h
+ rwa [← List.replicate_add, show 4+3*j.val+2 = 5+3*j.val+1 by omega] at h
+
+end PairSimulation.LeafSuccessorFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationLeafValidation.lean b/lean/OAI/Computability/VPVNP/PairSimulationLeafValidation.lean
new file mode 100644
index 0000000000..8407d2d7fc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationLeafValidation.lean
@@ -0,0 +1,173 @@
+import OAI.Computability.VPVNP.PairSimulationLeafGuard
+import OAI.Computability.VPVNP.RAMTapeVirtualSiteGraph
+import OAI.Computability.VPVNP.RAMTapeSiteValidated
+
+/-! # The call and sorting passes of the full-word virtual leaf validator -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafStartup
+
+open BurstRAM RAMLayout RAMTape LiveProgram PrivateRAM RAMSerialization RAMMemory
+open RAMTape.SiteProcessorPorts
+
+set_option synthInstance.maxSize 10000
+
+variable {d e w k p : ℕ} (r : ℕ) (x : VirtualSite.Input d e w) (args : Fin k → Word w)
+
+/-- The input stack bank for the site's postprocessing pass, including the output block, the
+incident suffix after the two successor fields, and the encoded received and sent records. -/
+def rawPost (pr sr : Option (WordRecord w)) (block : List Bool) : Stacks SitePost.Port :=
+ SitePost.rawBank d w (4*2^e) (wordBits x.v) block
+ ((List.ofFn (RAMLayout.incidentBits x.sends x.v)).drop (16*w)) []
+ (List.ofFn ((recordFormat x.hw).encode pr)) (List.ofFn ((recordFormat x.hw).encode sr))
+
+theorem entered_post (hv : x.valid) (bs : List Bool) :
+ ∃ pr sr : Option (WordRecord w), pr.map WordRecord.record = x.summary.received ∧
+ sr.map WordRecord.record = x.summary.sent ∧
+ entered r x args bs ∘ postPorts r (expr k) = rawPost x pr sr [] := by
+ have regs := registers r x args hv
+ choose records hm hbits using regs.record
+ let pr := records .receive
+ let sr := records .send
+ refine ⟨pr,sr,hm .receive,hm .send,?_⟩
+ have recBits (side : Successors.Side) :
+ entered r x args bs (guardPort r k (.record side)) =
+ List.ofFn ((recordFormat x.hw).encode (records side)) := by
+ rw [entered_guard, hbits side]
+ exact List.append_nil _
+ have inc := (entered_guard r x args bs .incident).trans regs.incident
+ have pubField := entered_public r x args bs
+ have addr := pubField ProcessorPublic.addressPort (by decide) (by decide)
+ have wid := pubField ProcessorPublic.widthPort (by decide) (by decide)
+ have slots := pubField (.inl SiteSetup.slotsPort) (by decide) (by decide)
+ have dw := pubField ProcessorPublic.addressWidthPort (by decide) (by decide)
+ have block := entered_native r x args bs (.record .output)
+ have blank (j : SitePost.Port) : entered r x args bs (.inr (.inr j)) = [] := by
+ rw [entered, Function.update_of_ne (by simp [native]), Function.update_of_ne (by simp [pub])]
+ exact installStacks_outside _ _ (by rintro i; cases i <;> intro h <;> cases h)
+ funext j
+ rcases j with (c | (((i|z)|o)|u)) | a
+ · cases c <;> exact blank _
+ · cases i <;> first | exact block | exact inc | exact wid | exact blank _
+ · cases z <;> first | exact addr | exact blank _
+ · cases o <;> exact blank _
+ · cases u; exact slots
+ · cases a <;> first | exact recBits .receive | exact recBits .send | exact dw
+
+theorem summary_spec : x.summary.Spec x.hw x.hc x.initialWord x.v x.sends :=
+ scanSuccessors_spec x.hw x.hc x.initialWord x.v (sortIncident x.sends x.v) x.sends
+ (sortIncident_offset x.sends x.v)
+
+variable (T : Template p r k) (bs : List Bool)
+
+/-- Whether the instantiated machine's incident validator returns a report sequence for this
+site's initial word, header, incident bits and supplied choice stream. -/
+def accepts : Bool :=
+ ((T.instantiate w args).validateIncident x.fuel x.initialWord x.headerWord x.hw x.hc x.v
+ (RAMLayout.incidentBits x.sends x.v) bs).1.isSome
+
+theorem accepts_validated (hv : x.valid) :
+ (accepts r x args T bs).toNat = match x.validated T args bs with
+ | none => 0
+ | some rs => (checkSiteMemory (e := e) x.hw x.v x.headerWord (sortIncident x.sends x.v) x.summary rs).1.toNat := by
+ have he := (summary_spec x).valid_iff.mpr hv
+ unfold accepts Machine.validateIncident
+ change ((if x.summary.valid then _ else _) : Option (List (Report w)) × ℕ).1.isSome.toNat = _
+ rw [ite_eq_left he]
+ dsimp only
+ rw [Machine.runBucket_result]
+ conv_lhs =>
+ pattern validateSite ..
+ change x.validated T args bs
+ cases x.validated T args bs with
+ | none => rfl
+ | some rs =>
+ dsimp only
+ change (if (checkSiteMemory (e := e) x.hw x.v x.headerWord
+ (sortIncident x.sends x.v) x.summary rs).1 then some rs else none).isSome.toNat = _
+ cases (checkSiteMemory (e := e) x.hw x.v x.headerWord (sortIncident x.sends x.v) x.summary rs).1 <;> rfl
+
+theorem accepts_invalid (hv : ¬x.valid) : accepts r x args T bs = false := by
+ have h := Bool.eq_false_iff.mpr (fun hp => hv ((summary_spec x).valid_iff.mp hp))
+ change (if x.summary.valid then _ else (none, _)).1.isSome = false
+ rw [h]; rfl
+
+/-- For each guessed finite bit string the virtual processor rejects or reaches its
+terminal memory test. The deterministic call and sort steps share the emitted block. -/
+theorem perChoice_verdict (hv : x.valid) (t : ℕ) (ht : perChoiceBudget d e w r x.fuel ≤ t) :
+ (∀ c, (perChoice r (expr k) T).body.count c t (entered r x args bs) = (accepts r x args T bs).toNat) ∧
+ (∀ c, (perChoice r (expr k) T).body.AllStops c t (entered r x args bs)) := by
+ rw [accepts_validated r x args T bs hv]
+ let entry := entered r x args bs
+ have hbare := entered_call r x args T hv bs
+ change entry ∘ callPorts r (expr k) = _ at hbare
+ obtain ⟨pr,sr,hpr,hsr,hpost⟩ := entered_post r x args hv bs
+ change entry ∘ postPorts r (expr k) = _ at hpost
+ obtain ⟨m,hm,booted⟩ := SiteProcessor.boot_run T (x.bare T args bs) x.addrWord rfl rfl
+ change m ≤ r*(8*w+3)+3*(0*(w+1)+1)+2 + (0+0+0+21*w+9) at hm
+ change SiteProcessor.boot.Runs m (x.bare T args bs).bare (x.staged T args bs).bank at booted
+ obtain ⟨n,hn,graph⟩ := x.graphOutcome T args bs
+ change n ≤ SiteCutBank.graphBudget r w e x.fuel at hn
+ unfold VirtualSite.Input.GraphOutcome at graph
+ unfold perChoiceBudget at ht
+ have hp := callPorts_injective r (expr k)
+ cases he : x.validated T args bs with
+ | none =>
+ rw [he] at graph
+ have htime : t = (t-(m+n+1))+(m+n)+1 := by omega
+ have bad := SiteProcessor.callSite_reject T booted graph
+ constructor
+ · intro c
+ change (((SiteProcessor.callSite T).onPorts (callPorts r (expr k))).body.followedBy
+ (post r (expr k)).body).count c t entry = 0
+ rw [Routine.count_followedBy, FiniteRoutine.count_onPorts _ _ hp, hbare, htime]
+ exact (bad.verdict _ (fun _ _ => True) _).1
+ · intro c
+ change (((SiteProcessor.callSite T).onPorts (callPorts r (expr k))).body.followedBy
+ (post r (expr k)).body).AllStops c t entry
+ rw [Routine.allStops_followedBy, FiniteRoutine.allStops_onPorts _ _ hp, hbare, htime]
+ exact (bad.verdict (fun _ _ => 0) _ _).2
+ | some rs =>
+ rw [he] at graph
+ obtain ⟨u, records, hrecords, run⟩ := graph
+ let out := (u.afterClose x.hw (2^e) records).bank
+ have hr : (SiteProcessor.callSite T).Runs (m+n) (x.bare T args bs).bare out :=
+ booted.followedBy (SiteProcessor.graphRoutine_run T run)
+ have framed := (SiteProcessor.callSite T).runs_onPorts hp entry hr
+ rw [installStacks_eq hp entry _ (fun i => congrFun hbare i)] at framed
+ have htime : t = (t-(m+n))+(m+n) := by omega
+ have raw : installStacks (callPorts r (expr k)) entry out ∘ postPorts r (expr k) =
+ rawPost x pr sr (out (.record .output)) := by
+ rw [installCall_post r (expr k) (portsInj := hp), hpost]
+ funext j
+ rcases j with (c | (((i|z)|o)|a)) | ext
+ · cases c <;> rfl
+ · cases i <;> rfl
+ · cases z <;> rfl
+ · cases o <;> rfl
+ · cases a; rfl
+ · cases ext <;> rfl
+ have finish := SitePost.complete_records x.hw x.hc x.sends x.v (fun _ => x.headerWord) x.initialWord
+ x.summary (summary_spec x) rs records hrecords pr sr hpr hsr (t-(m+n)) (by omega)
+ constructor
+ · intro c
+ change (((SiteProcessor.callSite T).onPorts (callPorts r (expr k))).body.followedBy
+ (post r (expr k)).body).count c t entry = _
+ rw [Routine.count_followedBy, htime, framed.count_eq, post, FiniteRoutine.count_onPorts _ _
+ (postPorts_injective r (expr k)), raw]
+ exact finish.1 _
+ · intro c
+ change (((SiteProcessor.callSite T).onPorts (callPorts r (expr k))).body.followedBy
+ (post r (expr k)).body).AllStops c t entry
+ rw [Routine.allStops_followedBy, htime, framed.allStops_iff, post, FiniteRoutine.allStops_onPorts _ _
+ (postPorts_injective r (expr k)), raw]
+ exact finish.2 _
+
+end PairSimulation.LeafStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapArgumentInput.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapArgumentInput.lean
new file mode 100644
index 0000000000..9fe657265e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapArgumentInput.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.PairSimulationMapArgumentWriter
+import OAI.Computability.VPVNP.PairSimulationMapCallSetup
+
+/-!
+# Reading a published private descriptor as the input of a grouped map
+
+The map's raw incident fields already occupy private memory before its argument
+writer executes. For each live bit, the physical layout separates the bit from
+both the call descriptor and the selector directory. Thus the stores establish
+the descriptor readback while preserving all demand and supply bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapArgumentWriter
+
+open MotifSelector MotifBlocks MotifGrid MotifConversion MotifEntry
+open BurstRAM BurstRAM.PrivateRAM MapPortAgreement MapResidentAgreement
+open CompressorRecords CompressorRecords.PhaseRecipe
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k p w t u : ℕ}
+ (A : MapEntryTable.Allocation B z j r k) (args : MapCallSetup.Arg D E ≃ Fin
+ (Fintype.card (MapCallSetup.Arg D E))) (loc : A.Address → Fin p)
+ {demand : D → ℕ} {v : E → ℕ} {d : DemandBits src dst demand j}
+ {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (X : MapEntry.Program.Workspace (A.program loc) demand v d x t w)
+
+/-- Each live cell lies outside both the private argument range and the future
+selector directory. The pointer directory can wrap around the word modulus. -/
+def separated (addr cell : BurstRAM.Word w) : Prop :=
+ (cell.val < addr.val ∨ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ cell.val) ∧
+ ∀ i : MapDirectoryInit.Row A, cell ≠ X.directory + (i.val : BurstRAM.Word w)
+
+/-- Physical readback and layout of the old half-wire buffers before publishing
+the map's private call descriptor. -/
+structure ResidentFields (addr : BurstRAM.Word w)
+ (mem : BurstRAM.Word w → BurstRAM.Word w) : Prop where
+ payloadFit : ∀ e, v e < 2 ^ w
+ supplyBase : ∀ t : Port G j,
+ X.portBase t = (X.base (MapDirectoryInit.portField t) : BurstRAM.Word w)
+ supply : ∀ (t : Port G j) (i : Fin (v (edge t) + u * B.selectorBits)),
+ let cell := X.portBase t + (i.val : BurstRAM.Word w)
+ mem cell = PrimedInputRAM.encodeBit w (field x t i) ∧ separated A loc X addr cell
+ demandCells : ∀ (q : Bool × D) (i : Fin (MapRow.endpoint src dst j demand d q).1),
+ let cell := ((X.base (.inl q) + i.val : ℕ) : BurstRAM.Word w)
+ mem cell = PrimedInputRAM.encodeBit w ((MapRow.endpoint src dst j demand d q).2 i) ∧
+ separated A loc X addr cell
+
+/-- Descriptor stores may be performed by an enclosing machine. The map only
+reads its pointer and the shared private memory of the resulting configuration. -/
+theorem input_of_published (addr : BurstRAM.Word w) (old : BurstRAM.Word w → BurstRAM.Word w)
+ (c : Config w p r) (ptr : Fin r) (hp : c.reg ptr = addr)
+ (stored : ∀ a, c.privateMem (addr + ((args a).val : BurstRAM.Word w)) =
+ MapCallSetup.values A loc X a)
+ (frame : ∀ q : BurstRAM.Word w, q.val < addr.val ∨
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val → c.privateMem q = old q)
+ (cells : ResidentFields A loc X addr old) : MapCallSetup.Input A args loc X ptr c := by
+ refine ⟨fun a ↦ hp ▸ stored a, cells.payloadFit, cells.supplyBase, ?_, ?_,
+ fun t i ↦ (cells.supply t i).2.2, fun q i ↦ (cells.demandCells q i).2.2⟩
+ · intro t i
+ exact (frame _ (cells.supply t i).2.1).trans (cells.supply t i).1
+ · intro q i
+ exact (frame _ (cells.demandCells q i).2.1).trans (cells.demandCells q i).1
+
+variable (base : Expr) (fields : MapCallSetup.Arg D E → Expr)
+
+local notation "f" => fields ∘ args.symm
+
+/-- A compiled writer whose expressions read the recorded term's argument
+values delivers the typed input to the map's register and directory initializer. -/
+theorem native_input (vm : Fin (RegisterSetup.regCount (recipes base f)) ↪ Fin r)
+ (inputs : Fin 6 → Fin r) (aux : Fin 3 ↪ Fin r) (place : Address base f → Fin p)
+ (done : Fin p) (M : Machine w p r k) (link : ∀ a,
+ M.code (place a) = (text base f vm inputs aux place done a).resize w)
+ (safe : ∀ i q, vm i ≠ inputs q) (apart : ∀ i q, vm i ≠ aux q)
+ (c : Config w p r) (m : Memory w) (start : c.pc = setupPC base f place 0) :
+ let pub := fun i : Fin 5 ↦ c.reg (inputs i.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := base.eval pub state m
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ 2 ^ w →
+ (∀ a, (fields a).eval pub state m = MapCallSetup.values A loc X a) →
+ ResidentFields A loc X addr c.privateMem →
+ ∃ (ev : List (Event w)) (out : Config w p r),
+ ev.length = clock base f ∧ countProbes ev = ∑ i, ((recipes base f) i).loads ∧
+ choiceBits ev = [] ∧ out.pc = done ∧ out.reg (aux 0) = addr ∧
+ MapCallSetup.Input A args loc X (aux 0) out ∧ out.persistent = c.persistent ∧
+ (∀ q : BurstRAM.Word w, q.val < addr.val ∨
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val →
+ out.privateMem q = c.privateMem q) ∧
+ (∀ q, (∀ i, q ≠ vm i) → (∀ i, q ≠ aux i) → out.reg q = c.reg q) ∧
+ ∀ fuel bs, execute M.program (fuel + ev.length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep ↦ ⟨ev ++ rep.events, rep.result⟩) := by
+ intro pub state addr fit read cells
+ obtain ⟨ev, out, len, probes, choices, stop, ptr, per, words, frame, regs, run⟩ :=
+ native base f vm inputs aux place done M link safe apart c m start fit
+ refine ⟨ev, out, len, probes, choices, stop, ptr, ?_, per, frame, regs, run⟩
+ apply input_of_published A args loc X addr c.privateMem out (aux 0) ptr _ frame cells
+ intro a
+ rw [words]
+ simpa only [Function.comp_apply, Equiv.symm_apply_apply] using read a
+
+end PairSimulation.MapArgumentWriter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapArgumentWriter.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapArgumentWriter.lean
new file mode 100644
index 0000000000..47c099a5e4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapArgumentWriter.lean
@@ -0,0 +1,201 @@
+import OAI.Computability.VPVNP.CompressorRecordPrivateDescriptor
+import OAI.Computability.VPVNP.CompressorRegisterSetupTrace
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-!
+# Publishing the live arguments of a motif call
+
+The register compiler reads a fixed family of expressions from external records.
+The last expression computes the private descriptor base. The writer sets the
+map's descriptor pointer, stores the preceding results in consecutive words and
+jumps to the map call. Its instruction and probe counts depend only on the
+expressions, including when their values depend on the chosen term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapArgumentWriter
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe
+open PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {n w p r k : ℕ} (base : Expr) (fields : Fin n → Expr)
+
+/-- The map's descriptor base is computed in the same pass as the argument values. -/
+def recipes : Fin (n + 1) → Expr := Fin.snoc fields base
+
+/-- Assignment list for all fields followed by the descriptor base. -/
+abbrev lines := RegisterSetup.lines (recipes base fields)
+/-- Code slots for the assignment list, pointer setup, and individual stores. -/
+abbrev Address := Fin (lines base fields).length ⊕ Fin 3 ⊕ Fin n × Bool
+
+variable (vm : Fin (RegisterSetup.regCount (recipes base fields)) ↪ Fin r)
+ (inputs : Fin 6 → Fin r) (aux : Fin 3 ↪ Fin r)
+ (loc : Address base fields → Fin p) (done : Fin p)
+
+/-- Enter the indexed assignment or the pointer setup after the final one. -/
+def setupPC (i : ℕ) : Fin p :=
+ if h : i < (lines base fields).length then loc (.inl ⟨i, h⟩) else loc (.inr (.inl 0))
+
+private def storePC (i : Fin (n + 1)) : Fin p :=
+ if h : i.val < n then loc (.inr (.inr (⟨i.val, h⟩, false))) else done
+
+private def output (i : Fin (n + 1)) := vm (RegisterSetup.output (recipes base fields) i)
+
+/-- Relocatable instructions for expression evaluation, pointer installation
+and publication of the argument words. The last store jumps through its
+increment instruction to the caller's map-entry continuation. -/
+def text : Address base fields → Instr 2 p r k
+ | .inl i => RegisterSetup.instruction vm inputs (lines base fields)[i.val]
+ (setupPC base fields loc (i.val + 1))
+ | .inr (.inl i) =>
+ ![.copy (aux 0) (output base fields vm (Fin.last n)) (loc (.inr (.inl 1))),
+ .copy (aux 1) (aux 0) (loc (.inr (.inl 2))),
+ .constant (aux 2) 1 (storePC base fields loc done 0)] i
+ | .inr (.inr (i, false)) =>
+ .storePrivate (aux 1) (output base fields vm i.castSucc) (loc (.inr (.inr (i, true))))
+ | .inr (.inr (i, true)) =>
+ .binary .add (aux 1) (aux 1) (aux 2) (storePC base fields loc done i.succ)
+
+/-- Exact instruction count, including the private pointer copy and all stores. -/
+def clock := (lines base fields).length + (3 + 2 * n)
+
+private theorem tick_log (t : ℕ) : choiceBits (List.replicate t (.tick : Event w)) = [] ∧
+ countProbes (List.replicate t (.tick : Event w)) = 0 := by
+ induction t with
+ | zero => exact ⟨rfl, rfl⟩
+ | succ t ih => simpa only [List.replicate_succ, choiceBits, countProbes] using ih
+
+/-- External reads use the live six input registers and private stores preserve
+every address outside the descriptor. The returned trace composes with every
+fuel and branch-bit continuation on the same external memory. -/
+theorem native_raw (M : Machine w p r k) (link : ∀ a,
+ M.code (loc a) = (text base fields vm inputs aux loc done a).resize w)
+ (safe : ∀ i j, vm i ≠ inputs j) (apart : ∀ i j, vm i ≠ aux j)
+ (c : Config w p r) (m : Memory w) (start : c.pc = setupPC base fields loc 0) :
+ let pub := fun i : Fin 5 ↦ c.reg (inputs i.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := base.eval pub state m
+ addr.val + n ≤ 2 ^ w →
+ let ev := (RowRecipe.evaluate pub state m (lines base fields) (fun i ↦ c.reg (vm i))).1 ++
+ List.replicate (3 + 2 * n) (.tick : Event w)
+ ∃ out : Config w p r,
+ ev.length = clock base fields ∧ countProbes ev = ∑ i, ((recipes base fields) i).loads ∧
+ choiceBits ev = [] ∧ out.pc = done ∧ out.reg (aux 0) = addr ∧
+ out.persistent = c.persistent ∧
+ (∀ i : Fin n, out.privateMem (addr + (i.val : Word w)) = (fields i).eval pub state m) ∧
+ (∀ a : Word w, a.val < addr.val ∨ addr.val + n ≤ a.val →
+ out.privateMem a = c.privateMem a) ∧
+ (∀ j, (∀ i, j ≠ vm i) → (∀ i, j ≠ aux i) → out.reg j = c.reg j) ∧
+ ∀ fuel bs, execute M.program (fuel + ev.length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep ↦ ⟨ev ++ rep.events, rep.result⟩) := by
+ intro pub state addr fit
+ let f := recipes base fields
+ have setup : RegisterSetup.Linked vm inputs M (setupPC base fields loc)
+ (RegisterSetup.lines f) := by
+ intro i
+ have hi : i.val < (lines base fields).length := i.isLt
+ rw [show setupPC base fields loc i.val = loc (.inl i) by simp [setupPC, hi], link]
+ exact RegisterSetup.resize_instruction ..
+ let ev := (RowRecipe.evaluate pub state m (RegisterSetup.lines f) (fun i ↦ c.reg (vm i))).1
+ obtain ⟨d, len, probes, choices, atCopy, mem, pers, vals, frame, run⟩ :=
+ RegisterSetup.execute_setup_raw f inputs vm M m _ setup safe c start
+ have here : d.pc = loc (.inr (.inl 0)) := by
+ simpa only [setupPC, f, lines, lt_self_iff_false, ↓reduceDIte] using atCopy
+ let d' := d.put (loc (.inr (.inl 1))) (aux 0) addr
+ have ptr : d.reg (output base fields vm (Fin.last n)) = addr := by
+ simpa only [output, f, recipes, Fin.snoc_last, addr, pub, state] using vals (Fin.last n)
+ have step : M.program.step d = .localStep d' := by
+ change (M.code d.pc).run M.publicData d = _
+ rw [here, link]
+ change CallAction.localStep (d.put _ _ (d.reg (output base fields vm (Fin.last n)))) = _
+ rw [ptr]
+ let header : Fin 2 → Fin p := ![loc (.inr (.inl 1)), loc (.inr (.inl 2))]
+ let next := fun i : Fin n ↦ loc (.inr (.inr (i, true)))
+ let values := fun i : Fin n ↦ output base fields vm i.castSucc
+ have store : PrivateDescriptor.Linked M values (aux 0) (aux 1) (aux 2) header
+ (storePC base fields loc done) next := by
+ refine ⟨link (.inr (.inl 1)), link (.inr (.inl 2)), ?_, ?_⟩
+ · intro i
+ rw [show storePC base fields loc done i.castSucc = loc (.inr (.inr (i, false))) by
+ simp [storePC, i.isLt], link]
+ rfl
+ · intro i
+ exact link (.inr (.inr (i, true)))
+ have addr' : d'.reg (aux 0) = addr := Config.put_same ..
+ obtain ⟨out, tail, atDone, pers', ptr', written, outside, keep⟩ :=
+ PrivateDescriptor.publish M values (aux 0) (aux 1) (aux 2) header
+ (storePC base fields loc done) next store (aux.injective.ne (by decide))
+ (aux.injective.ne (by decide)) (aux.injective.ne (by decide))
+ (fun _ ↦ ⟨apart _ _, apart _ _⟩) d' rfl (addr' ▸ fit)
+ let ticks := List.replicate (3 + 2 * n) (.tick : Event w)
+ have suffix : Prefix M d ticks out := by
+ dsimp only [ticks]
+ rw [show 3 + 2 * n = (2 + 2 * n) + 1 by omega, List.replicate_succ]
+ exact .tick step tail
+ have prop := tick_log (w := w) (3 + 2 * n)
+ have endPtr := ptr'.trans addr'
+ refine ⟨out, ?_, ?_, ?_, ?_, endPtr, pers'.trans pers, ?_, ?_, ?_, ?_⟩
+ · change (ev ++ ticks).length = _
+ rw [List.length_append, show ev.length = (RegisterSetup.lines f).length from len]
+ simp only [ticks, List.length_replicate, clock, lines, f]
+ · rw [countProbes_append, probes, prop.2, Nat.add_zero]
+ · rw [PrimedInputRAM.Flow.choiceBits_append, choices, prop.1, List.nil_append]
+ · simpa [storePC] using atDone
+ · intro i
+ rw [← endPtr, written]
+ have h : values i ≠ aux 0 := apart _ _
+ change Function.update d.reg (aux 0) addr (values i) = _
+ rw [Function.update_of_ne h]
+ simpa only [values, output, f, recipes, Fin.snoc_castSucc, pub, state] using vals i.castSucc
+ · intro a ha
+ exact (outside _ (addr' ▸ ha)).trans (congrFun mem a)
+ · intro j hbank haux
+ exact (keep j (haux 1) (haux 2)).trans
+ ((Function.update_of_ne (haux 0) ..).trans (frame j hbank))
+ · intro fuel bs
+ change execute M.program (fuel + (ev ++ ticks).length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep ↦ ⟨(ev ++ ticks) ++ rep.events, rep.result⟩)
+ change ∀ f bs, execute M.program (f + ev.length) c m bs =
+ (execute M.program f d m bs).map (fun rep ↦ ⟨ev ++ rep.events, rep.result⟩) at run
+ have hs := suffix.execute fuel m bs
+ rw [prop.1, List.nil_append] at hs
+ rw [List.length_append, show fuel + (ev.length + ticks.length) =
+ (fuel + ticks.length) + ev.length by omega, run, hs]
+ simp [Option.map_map, Function.comp_def, List.append_assoc]
+
+/-- External reads use the live six input registers and private stores preserve
+every address outside the descriptor. The returned trace composes with every
+fuel and branch-bit continuation on the same external memory. -/
+theorem native (M : Machine w p r k) (link : ∀ a,
+ M.code (loc a) = (text base fields vm inputs aux loc done a).resize w)
+ (safe : ∀ i j, vm i ≠ inputs j) (apart : ∀ i j, vm i ≠ aux j)
+ (c : Config w p r) (m : Memory w) (start : c.pc = setupPC base fields loc 0) :
+ let pub := fun i : Fin 5 ↦ c.reg (inputs i.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := base.eval pub state m
+ addr.val + n ≤ 2 ^ w →
+ ∃ (ev : List (Event w)) (out : Config w p r),
+ ev.length = clock base fields ∧ countProbes ev = ∑ i, ((recipes base fields) i).loads ∧
+ choiceBits ev = [] ∧ out.pc = done ∧ out.reg (aux 0) = addr ∧
+ out.persistent = c.persistent ∧
+ (∀ i : Fin n, out.privateMem (addr + (i.val : Word w)) = (fields i).eval pub state m) ∧
+ (∀ a : Word w, a.val < addr.val ∨ addr.val + n ≤ a.val →
+ out.privateMem a = c.privateMem a) ∧
+ (∀ j, (∀ i, j ≠ vm i) → (∀ i, j ≠ aux i) → out.reg j = c.reg j) ∧
+ ∀ fuel bs, execute M.program (fuel + ev.length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep ↦ ⟨ev ++ rep.events, rep.result⟩) := by
+ intro pub state addr fit
+ obtain ⟨out, prop⟩ :=
+ native_raw base fields vm inputs aux loc done M link safe apart c m start fit
+ exact ⟨_, out, prop⟩
+
+end PairSimulation.MapArgumentWriter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapBank.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapBank.lean
new file mode 100644
index 0000000000..97daa3c4cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapBank.lean
@@ -0,0 +1,291 @@
+import OAI.Computability.VPVNP.PairSimulationMapRowCode
+import OAI.Computability.VPVNP.PairSimulationMapRowLoop
+import OAI.Computability.VPVNP.PairSimulationMapDriverCode
+
+/-!
+# Installing the row driver and every selector's matrix in one finite table
+
+For a fixed block, grid point and party, all selectors share the query, cursor,
+and result registers. Each selector has its own width and matrix ports. The
+row returns to the driver's label store, and all failed paths use the common
+rejecting exit. The enclosing program can supply the final width-check address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapBank
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MapLookup
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {J D E : Type} [Fintype J] [Fintype D] [Fintype E]
+ {K : Type} [Field K] {src dst : D → J} {G : Supply J E}
+ {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H')
+ (z : B.grid.demands) (j : J) {r k p w : ℕ}
+
+/-- Register slots shared across all selector rows of one map bank. Six belong to the outer
+driver, and the endpoint and group slots include the label register returned to that
+driver. -/
+abbrev Register (D E : Type) := Fin 6 ⊕ MapRowFields.Slot (LabelField D E) (D ⊕ E)
+
+/-- The selector's dispatch ordinal and the width and matrix words for that row. -/
+abbrev PublicPort :=
+ Selector B ⊕ ((s : Selector B) × MapRowCode.Port (LabelRow B z s j) (LabelField D E) (D ⊕ E))
+
+/-- Shared register and public-port positions inside an enclosing machine. -/
+structure Allocation (r k : ℕ) where
+ /-- Inject the row bank's driver and field slots into the enclosing machine's register file. -/
+ register : Register D E ↪ Fin r
+ /-- Assign distinct public-word positions to the selector ordinals and the widths, keys, and
+ parameter names of each selector's matrix. -/
+ port : PublicPort B z j ↪ Fin k
+
+private noncomputable def number (X : Type*) [Finite X] : X ≃ Fin (Nat.card X) := by
+ letI := Fintype.ofFinite X
+ exact Fintype.equivFinOfCardEq Nat.card_eq_fintype_card.symm
+
+/-- These finite counts always suffice for this fixed motif. -/
+noncomputable def allocation :
+ Allocation B z j (Nat.card (Register D E)) (Nat.card (PublicPort B z j)) := by
+ classical
+ exact ⟨(number _).toEmbedding, (number _).toEmbedding⟩
+
+namespace Allocation
+
+variable {B z j} (A : Allocation B z j r k)
+
+/-- Place the endpoint, group, and scratch registers used by the selected matrix row in the
+machine register file. -/
+def rowReg : MapRowFields.Registers (LabelField D E) (D ⊕ E) r :=
+ Function.Embedding.inr.trans A.register
+
+/-- The driver's last register is precisely the shared row result. -/
+def driverReg : Fin 7 ↪ Fin r :=
+ (⟨Fin.lastCases (.inr (.label : MapRowFields.Slot (LabelField D E) (D ⊕ E))) Sum.inl, by
+ intro l m he
+ fin_cases l <;> fin_cases m <;> first | rfl | cases he⟩ : Fin 7 ↪ Register D E).trans A.register
+
+/-- Public port holding the ordinal against which the driver compares the loaded selector. -/
+def selectorPort (s : Selector B) : Fin k := A.port (.inl s)
+
+/-- Public port for the selected base demand width or supply payload width of group `g`. -/
+def widthPort (s : Selector B) (g : D ⊕ E) : Fin k := A.port (.inr ⟨s, .inl g⟩)
+
+/-- Public port holding the expected digit of field `f` in matrix row `y` for selector `s`. -/
+def keyPort (s : Selector B) (y : LabelRow B z s j) (f : LabelField D E) : Fin k :=
+ A.port (.inr ⟨s, .inr (.inl (y, f))⟩)
+
+/-- Public port holding the parameter ordinal returned when the lookup matches row `y` for
+selector `s`. -/
+def namePort (s : Selector B) (y : LabelRow B z s j) : Fin k :=
+ A.port (.inr ⟨s, .inr (.inr y)⟩)
+
+/-- Local public values can be installed without constraining any other public ports. -/
+noncomputable def words (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (selector : Selector B ↪ BurstRAM.Word w)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) :
+ PublicPort B z j → BurstRAM.Word w
+ | .inl s => selector s
+ | .inr ⟨s, .inl g⟩ => ((Sum.elim (baseDemand B z) (basePayload B s) g : ℕ) : BurstRAM.Word w)
+ | .inr ⟨s, .inr (.inl (y, f))⟩ => labelKey B z s j fd (fs s) y f
+ | .inr ⟨s, .inr (.inr y)⟩ => ordinal (lookup B z s j y.1 y.2)
+
+/-- Install the complete fixed public table while preserving enclosing ports. -/
+noncomputable def install (values : PublicPort B z j → BurstRAM.Word w)
+ (other : Fin k → BurstRAM.Word w) (q : Fin k) : BurstRAM.Word w := by
+ classical
+ exact if h : ∃ a, A.port a = q then values h.choose else other q
+
+theorem install_at (values : PublicPort B z j → BurstRAM.Word w) (other : Fin k → BurstRAM.Word w)
+ (a : PublicPort B z j) : A.install values other (A.port a) = values a := by
+ classical
+ have he : ∃ t, A.port t = A.port a := ⟨a, rfl⟩
+ rw [install, dite_eq_left he, A.port.injective he.choose_spec]
+
+/-- Code and public words determine the exact comparison and row ordinal at each selector. -/
+theorem public_spec (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (selector : Selector B ↪ BurstRAM.Word w) (ordinal : (parameterData B).Entry → BurstRAM.Word w)
+ (M : Machine w p r k)
+ (h : ∀ a, M.publicData (A.port a) = words fd fs selector ordinal a) :
+ Function.Injective (M.publicData ∘ A.selectorPort) ∧
+ (∀ s g, M.publicData (A.widthPort s g) =
+ ((Sum.elim (baseDemand B z) (basePayload B s) g : ℕ) : BurstRAM.Word w)) ∧
+ (∀ s y f, M.publicData (A.keyPort s y f) = labelKey B z s j fd (fs s) y f) ∧
+ (∀ s y, M.publicData (A.namePort s y) = ordinal (lookup B z s j y.1 y.2)) := by
+ have he : M.publicData ∘ A.selectorPort = selector := funext fun s ↦ h (.inl s)
+ exact ⟨he ▸ selector.injective, fun s g ↦ h (.inr ⟨s, .inl g⟩),
+ fun s y f ↦ h (.inr ⟨s, .inr (.inl (y, f))⟩), fun s y ↦ h (.inr ⟨s, .inr (.inr y)⟩)⟩
+
+/-- Only body labels are allocated for a row. Its exit belongs to the driver. -/
+noncomputable abbrev RowBody (s : Selector B) :=
+ {a : MapRowCode.RowAddress B z s j A.rowReg (A.widthPort s) (A.keyPort s) (A.namePort s) //
+ MapRowCode.inBody _ _ a = true}
+
+/-- The two exits designate the following width comparison and rejection. -/
+noncomputable abbrev Address :=
+ (Fin 5 ⊕ (Selector B × Bool)) ⊕ ((s : Selector B) × A.RowBody s) ⊕ Bool
+
+variable (loc : A.Address → Fin p)
+
+/-- Place a selector's row instructions in the bank, redirect its successful return to the
+driver's label store, and send its failed lookup to the shared rejecting exit. -/
+noncomputable def rowPlace (s : Selector B)
+ (a : MapRowCode.RowAddress B z s j A.rowReg (A.widthPort s) (A.keyPort s) (A.namePort s)) :
+ Fin p :=
+ if h : MapRowCode.inBody _ _ a then loc (.inr (.inl ⟨s, ⟨a, h⟩⟩)) else
+ match a with
+ | .inr (.inr (.inr (.inr false))) => loc (.inl (.inl 2))
+ | _ => loc (.inr (.inr true))
+
+/-- Program counters for field reads, matrix lookup, and offset advancement of one selector's
+row in the combined bank. -/
+noncomputable def sites (s : Selector B) :=
+ MapRowCode.rowSites B z s j A.rowReg (A.widthPort s) (A.keyPort s) (A.namePort s)
+ (A.rowPlace loc s)
+
+/-- Assemble the driver that walks the private selector array, dispatches to the chosen row,
+stores its returned label, and enters the width check after the last copy. -/
+noncomputable def driver : MapDriver.Program (Selector B) p r k where
+ selectors := selectorTable B
+ port := A.selectorPort
+ reg := A.driverReg
+ pc i := loc (.inl (.inl i))
+ comparePC s b := loc (.inl (.inr (s, b)))
+ rowPC s := (A.sites loc s).fields.first
+ ((A.sites loc s).lookupPC (MapRow.nameFlow B z s j A.rowReg (A.keyPort s) (A.namePort s)).entry)
+ (labelFields D E)
+ checkWidths := loc (.inr (.inr false))
+ bad := loc (.inr (.inr true))
+
+/-- The row result register coincides with the driver's label register, while
+all six controller operands occupy separate locations. -/
+theorem registerLayout : MapRowLoop.RegisterLayout B (A.driver loc) A.rowReg := by
+ constructor
+ · rfl
+ · intro i hi a
+ fin_cases i <;> first
+ | exact (hi rfl).elim
+ | apply A.register.injective.ne; exact Sum.inl_ne_inr
+
+
+open Classical in
+/-- Fixed text relocated to the encompassing address space. Only the body instructions
+are used when linking it into a larger evaluation pipeline. -/
+noncomputable def text : A.Address → Instr 2 p r k
+ | .inl a => ((A.driver loc).code a).resize 2
+ | .inr (.inl ⟨s, a⟩) =>
+ MapRowCode.text _ _ (A.rowPlace loc s) A.rowReg MapRow.group (A.widthPort s)
+ (labelFields D E) a.val
+ | .inr (.inr false) => .accept
+ | .inr (.inr true) => .reject
+
+/-- Test whether an address belongs to the driver or a selected row body. The two exits have
+separate addresses for use by an enclosing program. -/
+def inBody : A.Address → Bool
+ | .inr (.inr _) => false
+ | _ => true
+
+private theorem driver_resize (a : MapDriver.Program.Location (Selector B)) :
+ (((A.driver loc).code a).resize 2).resize w = ((A.driver loc).code a).resize w := by
+ rcases a with i | ⟨s, b⟩
+ · fin_cases i <;> rfl
+ · cases b <;> rfl
+
+/-- Every selector returns to the shared label store. All its rejecting paths target
+the driver's common bad exit. -/
+theorem linked (M : Machine w p r k) (h : ∀ a, A.inBody a = true →
+ M.code (loc a) = (A.text loc a).resize w) :
+ (A.driver loc).Linked M ∧ ∀ s, MapRow.Linked B z s j A.rowReg (A.widthPort s) (A.keyPort s)
+ (A.namePort s) (A.sites loc s) M ((A.driver loc).pc 2) (A.driver loc).bad := by
+ constructor
+ · apply MapDriver.Program.linked_of_code _ (Finset.nodup_toList _)
+ intro a
+ have he : (A.driver loc).address a = loc (.inl a) := by rcases a with i | ⟨s, b⟩ <;> rfl
+ rw [he, h _ rfl]
+ exact A.driver_resize loc a
+ · intro s
+ apply MapRowCode.row_linked B z s j A.rowReg (A.widthPort s) (A.keyPort s)
+ (A.namePort s) (A.rowPlace loc s) M
+ intro a ha
+ rw [rowPlace, dite_eq_left ha, h _ rfl]
+ rfl
+
+/-- A fixed numbering of the combined address set. -/
+noncomputable def locations : A.Address ≃ Fin (Nat.card A.Address) := number _
+
+/-- Standalone finite implementation for all selected rows together with their driver. -/
+noncomputable def template : Template (Nat.card A.Address) r k :=
+ let place := A.locations
+ ⟨2, (A.driver place).pc 0, fun i ↦ A.text place (place.symm i)⟩
+
+/-- All code links of the entire driver and every decoded row hold in the same machine
+for every word width and public input. -/
+theorem template_linked (pub : Fin k → BurstRAM.Word w) :
+ let loc := A.locations
+ let M := A.template.instantiate w pub
+ (A.driver loc).Linked M ∧ ∀ s, MapRow.Linked B z s j A.rowReg (A.widthPort s) (A.keyPort s)
+ (A.namePort s) (A.sites loc s) M ((A.driver loc).pc 2) (A.driver loc).bad := by
+ dsimp only
+ apply A.linked
+ intro a _
+ simp [template, Template.instantiate]
+
+/-- Install all row widths, all selector ordinals and all fixed matrix words in
+the same standalone instruction table. -/
+noncomputable def machine (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (selector : Selector B ↪ BurstRAM.Word w)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) :
+ Machine w (Nat.card A.Address) r k :=
+ A.template.instantiate w (A.install (words fd fs selector ordinal) (fun _ ↦ 0))
+
+variable [DecidableEq J] {u : ℕ} (demand : D → ℕ) (v : E → ℕ)
+ (d : MotifEntry.DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j)
+ (base : LabelField D E → ℕ) (θ : Fin u → Selector B)
+
+/-- The actual finite driver and row machine writes the ordered parameter ordinals
+of every copy and reaches the final-width checker with the full offset vector. -/
+theorem native (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (selector : Selector B ↪ BurstRAM.Word w) (ordinal : (parameterData B).Entry → BurstRAM.Word w)
+ (source dest : ℕ) (hs : source + u < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : source + u ≤ dest ∨ dest + u ≤ source) (c : Config w (Nat.card A.Address) r) :
+ let P := A.driver A.locations
+ let M := A.machine fd fs selector ordinal
+ let buffers := MapRowLoop.buffers B z j demand v d x base θ
+ let label := fun i ↦ ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i (θ i)
+ (fun e ↦ MotifEntry.offset (fun l ↦ basePayload B (θ l) e) i))
+ (∀ i : Fin u, MapRowFields.Fits MapRow.group
+ (Sum.elim (baseDemand B z) (basePayload B (θ i))) (buffers i.val) w) →
+ (∀ f (l : Fin ((buffers 0).len f)), ((base f + l.val : ℕ) : BurstRAM.Word w).val < dest ∨
+ dest + u ≤ ((base f + l.val : ℕ) : BurstRAM.Word w).val) →
+ P.Ready M θ label source dest 0 c → MapRowFields.Resident A.rowReg (buffers 0) c →
+ ∃ ticks out, ticks ≤ P.visitCap (MapRowLoop.rowCap B z j) * u + 1 ∧
+ PrimedCounter.GuessWord.Prefix M c (List.replicate ticks .tick) out ∧
+ out.pc = P.checkWidths ∧ MapRowFields.Resident A.rowReg (buffers u) out ∧
+ (∀ i : Fin u, out.privateMem ((dest + i.val : ℕ) : BurstRAM.Word w) = label i) ∧
+ (∀ a : BurstRAM.Word w, a.val < dest ∨ dest + u ≤ a.val →
+ out.privateMem a = c.privateMem a) ∧ out.persistent = c.persistent := by
+ intro P M buffers label fit hbits ready resident
+ obtain ⟨code, rows⟩ := A.template_linked (A.install (words fd fs selector ordinal) (fun _ ↦ 0))
+ obtain ⟨inj, widths, keys, names⟩ := A.public_spec fd fs selector ordinal M
+ (A.install_at (words fd fs selector ordinal) (fun _ ↦ 0))
+ have layout := A.registerLayout A.locations
+ have run := MapRowLoop.rowRuns B z j demand v d x base θ P A.rowReg layout ordinal
+ A.widthPort A.keyPort A.namePort (A.sites A.locations) M P.bad (fun _ ↦ rfl) rows
+ fd fs widths keys names fit
+ exact P.native code inj θ (fun i ↦ Finset.mem_toList.mpr (Finset.mem_univ _)) label
+ _ source dest _ (MapRowLoop.stable B z j demand v d x base θ P A.rowReg layout dest hbits)
+ run hs hd sep c ready resident
+
+end Allocation
+
+end PairSimulation.MapBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapCallArg.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapCallArg.lean
new file mode 100644
index 0000000000..a11ff91b2b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapCallArg.lean
@@ -0,0 +1,30 @@
+import OAI.Computability.VPVNP.PairSimulationMapLookup
+
+/-!
+# Word fields of the private motif-call descriptor
+
+Every map initializer reads a fixed set of addresses and widths. Its callers
+use this same field order to compile their descriptor writes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapCallSetup
+
+open MapLookup
+
+/-- A fixed descriptor with no derived ends, offsets, or per-copy selector sequence. -/
+inductive Arg (D E : Type) where
+ | base (f : LabelField D E)
+ | demand (e : D)
+ | payload (e : E)
+ | copies | directory | source | target | hist
+ deriving DecidableEq, Fintype
+
+end PairSimulation.MapCallSetup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapCallExact.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapCallExact.lean
new file mode 100644
index 0000000000..47f370296f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapCallExact.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.PairSimulationMapEntryExact
+import OAI.Computability.VPVNP.PairSimulationMapPost
+import OAI.Computability.VPVNP.PairSimulationTickTerminal
+
+/-!
+# Exact successful clock of an initialized and inlined motif map
+
+The register recipes and the pointer directory add a fixed prefix to the successful
+map evaluation. Inlining the public constants then multiplies the length of this
+entire prefix by the block length. The host reaches its successful continuation with
+the same private memory as the source computation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifDemandPadding MotifEntry
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord InlinePublic MapEntryTable
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {r k t w P R : ℕ}
+
+namespace MapConstants
+
+variable (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : MapCallTable.Layout B (demandGrid B hp I.demand) I.party r k)
+ (ord : (parameterData B).Entry → Fin t)
+
+local notation "loc" => L.corePC L.locations
+local notation "d" => demandBits src dst I.party I.demandBits
+local notation "x" => mapHalf G (fun _ ↦ inputBits) I.supplyBits
+local notation "u" => repetitions B I.demand
+
+/-- Source tick count at the given selector sequence, including both initializer phases. -/
+noncomputable def entryTicks (hw : widthThreshold B ≤ w) (θ : Fin u → Selector B) : ℕ :=
+ L.lines.length + (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ (MapInline.callProgram L).successTicks d x θ ((fits_of_threshold B hw).2.1 _)
+ (fits_of_threshold B hw).2.2.1 (source (w := w) L ord).publicData
+
+/-- The fixed natural public bank runs the initialized map for exactly its successful
+tick count. The memory equality includes the directory written by initialization. -/
+theorem source_run_success_exact (hw : widthThreshold B ≤ w)
+ (X : MapEntry.Program.Workspace (MapInline.callProgram L) I.demand I.payload d x t w)
+ (c : Config w (Nat.card L.Address) r) (pc : c.pc = (source (w := w) L ord).entry)
+ (input : MapCallSetup.Input L.core L.args loc X L.ptr c)
+ (θ : Fin u → Selector B)
+ (selected : (selectorRun G (selectorTable B) (selectorCode B) I.payload I.party x).1 = some θ)
+ (valid : ∀ e, I.payload e = totalWidth (basePayload B) θ e) :
+ let ticks := entryTicks hp I L ord hw θ
+ ∃ out, ticks ≤ L.lines.length + (1 + 3 * (MapPortAgreement.ports G I.party
+ L.core.edgeOrder).length) + MapNativeClock.cap B (demandGrid B hp I.demand) I.party u ∧
+ Prefix (source (w := w) L ord) c (List.replicate ticks .tick) out ∧
+ out.pc = (MapInline.callProgram L).done ∧ out.persistent = c.persistent ∧
+ out.privateMem = (MapInline.callProgram L).successMemory X
+ (selectorWord B (fits_of_threshold B hw).2.2.2) ord θ
+ (MapCallSetup.directoryMemory L.core loc X c.privateMem) := by
+ let M := source (w := w) L ord
+ let P₀ := MapInline.callProgram L
+ obtain ⟨fb, fd, fs, hs⟩ := fits_of_threshold B hw
+ let sel := selectorWord B hs
+ have pub (a : MapEntryTable.PublicPort B (demandGrid B hp I.demand) I.party) :
+ M.publicData (L.core.pub a) = Allocation.words fb (fd _) fs sel
+ (fun e ↦ ((ord e).val : BurstRAM.Word w)) a := by
+ change (rawBank L.core ord (L.core.pub a) : BurstRAM.Word w) = _
+ rw [rawBank_at, words_eq_cast]
+ obtain ⟨init, dir, core⟩ := L.links L.locations M (fun a _ ↦ L.template_at _ a)
+ obtain ⟨m, first, ready, persistent, outside⟩ :=
+ MapCallSetup.native L.core L.args loc X L.slots M L.ptr L.scratch L.directoryApart
+ (L.dirPC L.locations) dir L.vm L.output L.vmApart (L.initPC L.locations) init
+ (by simp [MapCallTable.Layout.initPC]) c pc input
+ have directory : m.privateMem = MapCallSetup.directoryMemory L.core loc X c.privateMem :=
+ PrivateScratch.eq_write _ _ ready.selector.resident.pointers outside
+ obtain ⟨out, bound, tail, done, keep, written⟩ :=
+ P₀.native_success_exact X M (L.core.linked loc M core) (L.core.separate loc)
+ sel ord fb (fd _) fs (L.core.public_spec loc fb (fd _) fs sel _ M pub) m ready
+ θ selected valid
+ refine ⟨out, Nat.add_le_add_left bound _, ?_, done, keep.trans persistent, ?_⟩
+ · rw [entryTicks, List.replicate_add]
+ exact first.append tail
+ · rw [written, directory]
+
+end MapConstants
+
+namespace MapInline
+
+open MapConstants
+
+variable (ord : (parameterData B).Entry → Fin t) (hp : ∀ e, 0 < p₀ e)
+ (I : LocalHistory.EntryInput B)
+ (L : MapCallTable.Layout B (demandGrid B hp I.demand) I.party r k)
+
+local notation "loc" => L.corePC L.locations
+local notation "d" => demandBits src dst I.party I.demandBits
+local notation "x" => mapHalf G (fun _ ↦ inputBits) I.supplyBits
+local notation "u" => repetitions B I.demand
+
+/-- Transport the exact successful source path and its canonical private memory to
+the host. The caller's registers, exterior memory and histogram are framed on that path. -/
+theorem run_entryInput_success_exact
+ (V : Placement (capacity L.template (rawBank L.core ord)) (Nat.card L.Address) r P R)
+ (M : Machine w P R 11) (linked : Linked L ord V M) (hw : widthThreshold B ≤ w)
+ (X : MapEntry.Program.Workspace (callProgram L) I.demand I.payload d x t w)
+ (h : Config w P R) (pc : h.pc = V.entry L.template.entry)
+ (input : MapCallSetup.Input L.core L.args loc X L.ptr (restrict V L.template.entry h))
+ (apart : ∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w))
+ (θ : Fin u → Selector B)
+ (selected : (selectorRun G (selectorTable B) (selectorCode B) I.payload I.party x).1 = some θ)
+ (valid : ∀ e, I.payload e = totalWidth (basePayload B) θ e) :
+ let ticks := factor L ord * entryTicks hp I L ord hw θ
+ let sel := selectorWord B (fits_of_threshold B hw).2.2.2
+ let names := (runEntry B hp I.demand I.payload I.party d x).1.map (List.map ord)
+ ∃ out, ticks ≤ factor L ord * (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party u) ∧
+ Prefix M h (List.replicate ticks .tick) out ∧ out.persistent = h.persistent ∧
+ (∀ i, V.privateReg i → out.reg i = h.reg i) ∧
+ (∀ a, MapCallSetup.Outside L.core loc X a → out.privateMem a = h.privateMem a) ∧
+ Outcome X.hist (V.entry (callProgram L).bad) (V.entry (callProgram L).done) h out names ∧
+ MapCallSetup.Success L.core loc X sel ord h.privateMem out.privateMem ∧
+ out.pc = V.entry (callProgram L).done ∧
+ out.privateMem = (callProgram L).successMemory X sel ord θ
+ (MapCallSetup.directoryMemory L.core loc X h.privateMem) := by
+ intro ticks sel names
+ let c := restrict V L.template.entry h
+ let S := source (w := w) L ord
+ obtain ⟨last, bound, pre, done, per, memory⟩ :=
+ source_run_success_exact hp I L ord hw X c rfl input θ selected valid
+ obtain ⟨n, other, _, otherPre, _, save, effect, post⟩ :=
+ (source_run_post hp I L ord hw X c rfl input apart).path
+ have accept (s : Config w (Nat.card L.Address) r) (hs : s.pc = (callProgram L).done) :
+ S.program.step s = .finish none := by
+ change ((L.template.code s.pc).resize w).run _ s = _
+ rw [hs, (exit_codes L).2]
+ rfl
+ have terminal : S.program.step other = .reject ∨
+ ∃ result, S.program.step other = .finish result := by
+ change (callProgram L).Effect c other X.hist names at effect
+ cases hn : names with
+ | none =>
+ rw [hn] at effect
+ left
+ change ((L.template.code other.pc).resize w).run _ other = _
+ rw [effect.1, (exit_codes L).1]
+ rfl
+ | some _ =>
+ rw [hn] at effect
+ exact Or.inr ⟨none, accept _ effect.1⟩
+ obtain ⟨_, rfl⟩ := Prefix.ticks_terminal_unique pre otherPre (Or.inr ⟨none, accept _ done⟩)
+ terminal
+ obtain ⟨out, pref, rel⟩ := ticks_lower L.template (rawBank L.core ord) V M
+ (operand_le L.template (rawBank L.core ord)) linked pre (restrict_related V _ h pc)
+ refine ⟨out, Nat.mul_le_mul_left _ bound, pref, rel.1.persistent.trans per, rel.1.frame,
+ fun a ha ↦ (congrFun rel.1.privateMem a).trans (save a ha), ?_, rel.1.privateMem ▸ post,
+ rel.2.trans (congrArg V.entry done), rel.1.privateMem.trans memory⟩
+ change (callProgram L).Effect c last X.hist names at effect
+ cases hn : names with
+ | none | some _ =>
+ rw [hn] at effect
+ refine ⟨rel.2.trans (congrArg V.entry effect.1), fun i ↦ ?_⟩
+ rw [rel.1.privateMem]
+ exact effect.2 i
+
+end MapInline
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapCallRun.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapCallRun.lean
new file mode 100644
index 0000000000..a95565df00
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapCallRun.lean
@@ -0,0 +1,182 @@
+import OAI.Computability.VPVNP.PairSimulationMapCallSetup
+
+/-!
+# A native motif call from its private descriptor
+
+Initializing all operand registers and installing the pointer directory precede
+the actual map evaluation on the same machine. The combined prefix counts every
+initializer tick and retains the initial histogram on all rejecting paths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapCallSetup
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry
+open MapEntryTable MapPortAgreement MapResidentAgreement
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord CompressorRecords
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k p w t u : ℕ}
+
+omit [DecidableEq J] in
+private theorem prepend_post {P : MapEntry.Program B z j p r k} {M : Machine w p r k}
+ {c m : Config w p r} {n hist cap : ℕ} {value : Option (List (Fin t))}
+ {saved after : BurstRAM.Word w → Prop} {post : PrivateScratch.Memory w → Prop}
+ (pre : Prefix M c (List.replicate n .tick) m) (per : m.persistent = c.persistent)
+ (mem : ∀ l : Fin t, m.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w))
+ (old : ∀ a, saved a → m.privateMem a = c.privateMem a) (sub : ∀ a, saved a → after a)
+ (run : P.RunsPost M m hist cap after value post) :
+ P.RunsPost M c hist (n + cap) saved value post := by
+ obtain ⟨steps, out, bound, tail, hp, frame, result, exactMem⟩ := run.path
+ refine ⟨n + steps, out, Nat.add_le_add_left bound _, ?_, hp.trans per,
+ fun a ha ↦ (frame a (sub a ha)).trans (old a ha), ?_, exactMem⟩
+ · rw [List.replicate_add]
+ exact pre.append tail
+ · cases value <;> simpa only [MapEntry.Program.Effect, mem] using result
+
+variable (A : Allocation B z j r k) (args : Arg D E ≃ Fin (Fintype.card (Arg D E)))
+ (slots : Register D E ≃ Fin (Fintype.card (Register D E))) (loc : A.Address → Fin p)
+ {demand : D → ℕ} {v : E → ℕ} {d : DemandBits src dst demand j}
+ {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (X : MapEntry.Program.Workspace (A.program loc) demand v d x t w)
+
+/-- All input cells and all exterior call state outside the pointer directory,
+selector and label staging arrays, and histogram survive the full call. -/
+def Outside (a : BurstRAM.Word w) : Prop :=
+ (A.program loc).Outside X a ∧
+ ∀ i : MapDirectoryInit.Row A, a ≠ X.directory + (i.val : BurstRAM.Word w)
+
+/-- The operand initializer's private directory after all port pointers have been written. -/
+noncomputable def directoryMemory (old : PrivateScratch.Memory w) : PrivateScratch.Memory w :=
+ PrivateScratch.write X.directory (fun i : MapDirectoryInit.Row A ↦
+ MapResidentAgreement.selectorStart v X.portBase ((ports G j A.edgeOrder).get i)) old
+
+/-- Complete successful memory update, including the newly published pointer directory. -/
+def Success (sel : Selector B ↪ BurstRAM.Word w) (ord : (parameterData B).Entry → Fin t)
+ (old new : PrivateScratch.Memory w) : Prop :=
+ (A.program loc).Success X sel ord (directoryMemory A loc X old) new
+
+/-- Once the operands give a successful row sequence, each output memory cell depends
+on the initial memory only at that same cell. -/
+theorem Success.eq_at {sel : Selector B ↪ BurstRAM.Word w} {ord : (parameterData B).Entry → Fin t}
+ {old old' new new' : PrivateScratch.Memory w}
+ (h : Success A loc X sel ord old new) (h' : Success A loc X sel ord old' new')
+ (θ : Fin u → Selector B) (tags : (selectorRun G (selectorTable B) (selectorCode B) v j x).1 =
+ some θ) (valid : ∀ e, v e = totalWidth (basePayload B) θ e)
+ (a : BurstRAM.Word w) (ha : old a = old' a) : new a = new' a := by
+ rw [h θ tags valid, h' θ tags valid]
+ exact (A.program loc).successMemory_congr_at X sel ord θ a
+ (PrivateScratch.write_congr_at _ _ a ha)
+
+/-- Fixed setup geometry and the native body can all occupy arbitrary addresses of
+the enclosing vertex machine. Only the prescribed instruction text is required. -/
+theorem run_post (M : Machine w p r k)
+ (core : ∀ a, A.installed a = true → M.code (loc a) = (A.text loc a).resize w)
+ (ptr : Fin r) (scratch : Fin 2 ↪ Fin r) (apart : ∀ a i, A.reg a ≠ scratch i)
+ (dirPC : MapDirectoryInit.Address A → Fin p)
+ (dirLink : ∀ a, M.code (dirPC a) =
+ (MapDirectoryInit.text A scratch dirPC ((A.selector loc).scan 0) a).resize w)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t)
+ (pub : ∀ a, M.publicData (A.pub a) = Allocation.words fb fd fs sel
+ (fun e ↦ ((ord e).val : BurstRAM.Word w)) a)
+ (histApart : ∀ (l : Fin t) (i : MapDirectoryInit.Row A),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) :
+ let f := recipes A args (MapDirectoryInit.portField (anchorPort G j)) slots
+ ∀ (vm : Fin (RegisterSetup.regCount f) ↪ Fin r)
+ (_place : ∀ a, vm (RegisterSetup.output f (slots a)) = A.reg a)
+ (_safe : ∀ i, vm i ≠ ptr) (pc : ℕ → Fin p)
+ (_hl : MapInitCompiler.Linked vm ptr M pc (RegisterSetup.lines f))
+ (_endPC : pc (RegisterSetup.lines f).length = dirPC (.inl ()))
+ (c : Config w p r), c.pc = pc 0 → Input A args loc X ptr c →
+ (A.program loc).RunsPost M c X.hist ((RegisterSetup.lines f).length +
+ (1 + 3 * (ports G j A.edgeOrder).length) + MapNativeClock.cap B z j u) (Outside A loc X)
+ ((MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.map (List.map ord))
+ (Success A loc X sel ord c.privateMem) := by
+ intro f vm place safe pc hl endPC c hc input
+ obtain ⟨m, pre, ready, hp, hm⟩ := native A args loc X slots M ptr scratch apart dirPC dirLink
+ vm place safe pc hl endPC c hc input
+ have result := (A.program loc).native_post X M (A.linked loc M core) (A.separate loc)
+ sel ord fb fd fs
+ (A.public_spec loc fb fd fs sel _ M pub) m ready
+ have hdir : m.privateMem = directoryMemory A loc X c.privateMem :=
+ PrivateScratch.eq_write _ _ ready.selector.resident.pointers hm
+ apply prepend_post pre hp (fun l ↦ hm _ (histApart l)) (fun a ha ↦ hm a ha.2)
+ (fun _ ha ↦ ha.1)
+ change (A.program loc).RunsPost M m X.hist _ _ _
+ ((A.program loc).Success X sel ord (directoryMemory A loc X c.privateMem))
+ rw [← hdir]
+ exact result
+
+/-- Keep the map result and the exterior memory frame. -/
+theorem run_framed (M : Machine w p r k)
+ (core : ∀ a, A.installed a = true → M.code (loc a) = (A.text loc a).resize w)
+ (ptr : Fin r) (scratch : Fin 2 ↪ Fin r) (apart : ∀ a i, A.reg a ≠ scratch i)
+ (dirPC : MapDirectoryInit.Address A → Fin p)
+ (dirLink : ∀ a, M.code (dirPC a) =
+ (MapDirectoryInit.text A scratch dirPC ((A.selector loc).scan 0) a).resize w)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t)
+ (pub : ∀ a, M.publicData (A.pub a) = Allocation.words fb fd fs sel
+ (fun e ↦ ((ord e).val : BurstRAM.Word w)) a)
+ (histApart : ∀ (l : Fin t) (i : MapDirectoryInit.Row A),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) :
+ let f := recipes A args (MapDirectoryInit.portField (anchorPort G j)) slots
+ ∀ (vm : Fin (RegisterSetup.regCount f) ↪ Fin r)
+ (_place : ∀ a, vm (RegisterSetup.output f (slots a)) = A.reg a)
+ (_safe : ∀ i, vm i ≠ ptr) (pc : ℕ → Fin p)
+ (_hl : MapInitCompiler.Linked vm ptr M pc (RegisterSetup.lines f))
+ (_endPC : pc (RegisterSetup.lines f).length = dirPC (.inl ()))
+ (c : Config w p r), c.pc = pc 0 → Input A args loc X ptr c →
+ (A.program loc).RunsFramed M c X.hist ((RegisterSetup.lines f).length +
+ (1 + 3 * (ports G j A.edgeOrder).length) + MapNativeClock.cap B z j u) (Outside A loc X)
+ ((MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.map (List.map ord)) := by
+ intro f vm place safe pc hl endPC c hc input
+ exact (run_post A args slots loc X M core ptr scratch apart dirPC dirLink fb fd fs
+ sel ord pub histApart vm place safe pc hl endPC c hc input).framed _
+
+/-- The full initializer and map prefix, projected to its histogram result. -/
+theorem run (M : Machine w p r k)
+ (core : ∀ a, A.installed a = true → M.code (loc a) = (A.text loc a).resize w)
+ (ptr : Fin r) (scratch : Fin 2 ↪ Fin r) (apart : ∀ a i, A.reg a ≠ scratch i)
+ (dirPC : MapDirectoryInit.Address A → Fin p)
+ (dirLink : ∀ a, M.code (dirPC a) =
+ (MapDirectoryInit.text A scratch dirPC ((A.selector loc).scan 0) a).resize w)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t)
+ (pub : ∀ a, M.publicData (A.pub a) = Allocation.words fb fd fs sel
+ (fun e ↦ ((ord e).val : BurstRAM.Word w)) a)
+ (histApart : ∀ (l : Fin t) (i : MapDirectoryInit.Row A),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) :
+ let f := recipes A args (MapDirectoryInit.portField (anchorPort G j)) slots
+ ∀ (vm : Fin (RegisterSetup.regCount f) ↪ Fin r)
+ (_place : ∀ a, vm (RegisterSetup.output f (slots a)) = A.reg a)
+ (_safe : ∀ i, vm i ≠ ptr) (pc : ℕ → Fin p)
+ (_hl : MapInitCompiler.Linked vm ptr M pc (RegisterSetup.lines f))
+ (_endPC : pc (RegisterSetup.lines f).length = dirPC (.inl ()))
+ (c : Config w p r), c.pc = pc 0 → Input A args loc X ptr c →
+ (A.program loc).Runs M c X.hist ((RegisterSetup.lines f).length +
+ (1 + 3 * (ports G j A.edgeOrder).length) + MapNativeClock.cap B z j u)
+ ((MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.map (List.map ord)) := by
+ intro f vm place safe pc hl endPC c hc input
+ exact (run_framed A args slots loc X M core ptr scratch apart dirPC dirLink fb fd fs
+ sel ord pub histApart vm place safe pc hl endPC c hc input).forget _
+
+end PairSimulation.MapCallSetup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapCallSetup.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapCallSetup.lean
new file mode 100644
index 0000000000..f5c2e65168
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapCallSetup.lean
@@ -0,0 +1,313 @@
+import OAI.Computability.VPVNP.PairSimulationMapCallArg
+import OAI.Computability.VPVNP.PairSimulationMapExecutable
+import OAI.Computability.VPVNP.PairSimulationMapDirectoryInit
+import OAI.Computability.VPVNP.PairSimulationMapInitCompiler
+
+/-!
+# Computing initial map registers from the private call descriptor
+
+The caller supplies the live widths, one base per endpoint, the copy count, and
+the directory, selector-array, label-array and histogram bases. The fixed register
+recipes compute all derived bounds from these words. Reads access private memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapCallSetup
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry MapLookup
+open MapEntryTable MapPortAgreement MapResidentAgreement
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open CompressorRecords CompressorRecords.PhaseRecipe
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k p w t u : ℕ} (A : Allocation B z j r k)
+
+variable (args : Arg D E ≃ Fin (Fintype.card (Arg D E)))
+ (anchorField : LabelField D E)
+
+/-- Expression that loads a map-call operand from the private descriptor at the offset assigned
+by `args`. -/
+def arg (a : Arg D E) : Expr := .header (args a).val
+
+private def endLength (src dst : D → J) (G : Supply J E) (j : J) : LabelField D E → Expr
+ | .inl (false, e) => if j = src e then arg args (.demand e) else .lit 0
+ | .inl (true, e) => if j = dst e then arg args (.demand e) else .lit 0
+ | .inr (false, e) => if j = G.src e then arg args (.payload e) else .lit 0
+ | .inr (true, e) => if j = G.dst e then arg args (.payload e) else .lit 0
+
+/-- Expression for each register, including unused scratch registers initialized to zero. -/
+noncomputable def recipe : Register D E → Expr :=
+ let read := arg args
+ let tagWidth := (read .copies).mul (.lit B.selectorBits)
+ let anchor := (read (.base anchorField)).add (read (.payload (edge (anchorPort G j))))
+ let high := anchor.add tagWidth
+ let sourceEnd := (read .source).add (read .copies)
+ let targetEnd := (read .target).add (read .copies)
+ fun
+ | .inl (.inl a) =>
+ ![.lit 0, .lit 0, .lit 0, .lit 1, .lit 0, .lit 0, .lit 0, read .directory,
+ (read .directory).add (.lit (ports G j A.edgeOrder).length), anchor, tagWidth] a
+ | .inl (.inr a) =>
+ ![.lit 0, high, .lit 0, high, .lit 1, .lit 0, sourceEnd, read .source,
+ .lit B.selectorBits] a
+ | .inr (.inl (.inl a)) => ![read .source, sourceEnd, read .target, .lit 1, .lit 0, .lit 0] a
+ | .inr (.inl (.inr (.base f))) => read (.base f)
+ | .inr (.inl (.inr (.dataEnd f))) => (read (.base f)).add (endLength args src dst G j f)
+ | .inr (.inl (.inr .one)) => .lit 1
+ | .inr (.inl (.inr _)) => .lit 0
+ | .inr (.inr (.inl e)) => read (.payload e)
+ | .inr (.inr (.inr a)) => ![read .target, targetEnd, read .hist, .lit 1, .lit 0, .lit 0] a
+
+variable (slots : Register D E ≃ Fin (Fintype.card (Register D E)))
+
+/-- Index the initial register expressions by the compiler's numerical output slots, using
+`slots.symm` to recover each logical map register. -/
+noncomputable def recipes (i : Fin (Fintype.card (Register D E))) : Expr :=
+ recipe A args anchorField (slots.symm i)
+
+/-- One private load in a compiled expression reads the designated descriptor word. -/
+theorem eval_arg (values : Arg D E → BurstRAM.Word w) (c : Config w p r) (ptr : Fin r)
+ (h : ∀ a, c.privateMem (c.reg ptr + ((args a).val : BurstRAM.Word w)) = values a)
+ (a : Arg D E) :
+ (arg args a).eval (fun _ ↦ c.reg ptr) (c.reg ptr) (MapInitCompiler.memory c.privateMem) =
+ values a := by
+ simpa [arg, Expr.header, Expr.headerAddress, Expr.add, Expr.eval, BinaryOp.eval,
+ MapInitCompiler.memory] using h a
+
+variable (loc : A.Address → Fin p) {demand : D → ℕ} {v : E → ℕ}
+ {d : DemandBits src dst demand j} {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (X : MapEntry.Program.Workspace (A.program loc) demand v d x t w)
+
+/-- The natural data supplied by the caller, converted to machine words. -/
+noncomputable def values : Arg D E → BurstRAM.Word w
+ | .base f => (X.base f : BurstRAM.Word w)
+ | .demand e => (demand e : BurstRAM.Word w)
+ | .payload e => (v e : BurstRAM.Word w)
+ | .copies => (u : BurstRAM.Word w)
+ | .directory => X.directory
+ | .source => (X.source : BurstRAM.Word w)
+ | .target => (X.target : BurstRAM.Word w)
+ | .hist => (X.hist : BurstRAM.Word w)
+
+private theorem len_eq (θ : Fin u → Selector B) (f : LabelField D E)
+ (mem : BurstRAM.Memory w) (pub : Fin 5 → BurstRAM.Word w) (st : BurstRAM.Word w)
+ (he : ∀ a, (arg args a).eval pub st mem = values A loc X a) :
+ (endLength args src dst G j f).eval pub st mem =
+ ((MapRowLoop.buffers B z j demand v d x X.base θ 0).len f : BurstRAM.Word w) := by
+ rcases f with ⟨b, e⟩ | ⟨b, e⟩
+ all_goals cases b
+ · by_cases h : j = src e <;> simp [MapRowLoop.buffers, MapRow.endpoint, endLength, h, he,
+ values, Expr.eval]
+ · by_cases h : j = dst e <;> simp [MapRowLoop.buffers, MapRow.endpoint, endLength, h, he,
+ values, Expr.eval]
+ · by_cases h : j = G.src e <;> simp [MapRowLoop.buffers, MapRow.endpoint, endLength, h, he,
+ values, Expr.eval]
+ · by_cases h : j = G.dst e <;> simp [MapRowLoop.buffers, MapRow.endpoint, endLength, h, he,
+ values, Expr.eval]
+
+/-- Exact native setup prefix before directory construction. Its outputs are the
+map's allocated registers, and its fixed length is independent of all live widths. -/
+theorem load (vm : Fin (RegisterSetup.regCount (recipes A args anchorField slots)) ↪ Fin r)
+ (place : ∀ a, vm (RegisterSetup.output (recipes A args anchorField slots) (slots a)) = A.reg a)
+ (ptr : Fin r) (safe : ∀ i, vm i ≠ ptr) (M : Machine w p r k) (pc : ℕ → Fin p)
+ (link : MapInitCompiler.Linked vm ptr M pc
+ (RegisterSetup.lines (recipes A args anchorField slots)))
+ (c : Config w p r) (hc : c.pc = pc 0) :
+ ∃ out, Prefix M c
+ (List.replicate (RegisterSetup.lines (recipes A args anchorField slots)).length .tick) out ∧
+ out.pc = pc (RegisterSetup.lines (recipes A args anchorField slots)).length ∧
+ (∀ a, out.reg (A.reg a) =
+ (recipe A args anchorField a).eval (fun _ ↦ c.reg ptr) (c.reg ptr)
+ (MapInitCompiler.memory c.privateMem)) ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent ∧ ∀ q, (∀ i, q ≠ vm i) → out.reg q = c.reg q := by
+ obtain ⟨out, pre, hd, outputs, rest, hm, hp⟩ :=
+ MapInitCompiler.native (recipes A args anchorField slots) vm ptr safe M pc link c hc
+ exact ⟨out, pre, hd, fun a ↦ by simpa [place, recipes] using outputs (slots a),
+ hm, hp, rest⟩
+
+
+/-- Combine the computed register formulas with the actual incident bit cells and
+the newly installed directory. All remaining assumptions refer to the call operands. -/
+theorem ready_of_registers (out : Config w p r)
+ (start : out.pc = (A.program loc).selector.scan 0)
+ (anchor : X.portBase (anchorPort G j) = (X.base anchorField : BurstRAM.Word w))
+ (hv : ∀ e, v e < 2 ^ w) (mem : BurstRAM.Memory w) (pub : Fin 5 → BurstRAM.Word w)
+ (st : BurstRAM.Word w) (he : ∀ a, (arg args a).eval pub st mem = values A loc X a)
+ (regs : ∀ a, out.reg (A.reg a) = (recipe A args anchorField a).eval pub st mem)
+ (resident : MapResidentAgreement.Resident A.edgeOrder x X.portBase out.privateMem X.directory)
+ (bits : ∀ (θ : Fin u → Selector B) f
+ (l : Fin ((MapRowLoop.buffers B z j demand v d x X.base θ 0).len f)),
+ out.privateMem ((X.base f + l.val : ℕ) : BurstRAM.Word w) =
+ PrimedInputRAM.encodeBit w ((MapRowLoop.buffers B z j demand v d x X.base θ 0).bits f l)) :
+ (A.program loc).Ready X out := by
+ have atSlot (a) := regs a
+ constructor
+ · refine ⟨start, ?_, ?_, ?_, ?_, ?_, ?_, resident, ?_, ?_, ?_, ?_, ?_, ?_⟩
+ · exact (atSlot (.inl (.inl 7))).trans (he .directory)
+ · apply (atSlot (.inl (.inl 8))).trans
+ simp [recipe, Expr.add, Expr.eval, BinaryOp.eval, he, values,
+ MapEntryTable.Allocation.program]
+ · apply (atSlot (.inl (.inl 9))).trans
+ simp [recipe, Expr.add, Expr.eval, BinaryOp.eval, he, values, selectorStart, anchor]
+ · apply (atSlot (.inl (.inl 10))).trans
+ simp [recipe, Expr.mul, Expr.eval, BinaryOp.eval, he, values]
+ · exact (atSlot (.inl (.inl 3))).trans rfl
+ · exact (atSlot (.inl (.inl 4))).trans rfl
+ · apply (atSlot (.inl (.inr 3))).trans
+ simp [recipe, Expr.add, Expr.mul, Expr.eval, BinaryOp.eval, he, values, anchor, add_assoc]
+ · exact (atSlot (.inl (.inr 1))).trans (atSlot (.inl (.inr 3))).symm
+ · exact (atSlot (.inl (.inr 4))).trans rfl
+ · apply (atSlot (.inl (.inr 6))).trans
+ simp [recipe, Expr.add, Expr.eval, BinaryOp.eval, he, values]
+ · exact (atSlot (.inl (.inr 7))).trans (he .source)
+ · exact (atSlot (.inl (.inr 8))).trans rfl
+ · intro θ
+ constructor
+ · exact (atSlot (.inr (.inl (.inr .one)))).trans rfl
+ · exact fun f ↦ (atSlot (.inr (.inl (.inr (.base f))))).trans (he (.base f))
+ · intro f
+ apply (atSlot (.inr (.inl (.inr (.dataEnd f))))).trans
+ simp [recipe, Expr.add, Expr.eval, BinaryOp.eval, he, values,
+ len_eq A args loc X θ f mem pub st he, MapRowLoop.buffers]
+ · intro g
+ apply (atSlot (.inr (.inl (.inr (.offset g))))).trans
+ cases g <;> simp [recipe, Expr.eval, MapRowLoop.buffers]
+ · exact bits θ
+ · exact (atSlot (.inr (.inl (.inl 0)))).trans (he .source)
+ · apply (atSlot (.inr (.inl (.inl 1)))).trans
+ simp [recipe, Expr.add, Expr.eval, BinaryOp.eval, he, values]
+ · exact (atSlot (.inr (.inl (.inl 2)))).trans (he .target)
+ · exact (atSlot (.inr (.inl (.inl 3)))).trans rfl
+ · intro e
+ have h := (atSlot (.inr (.inr (.inl e)))).trans (he (.payload e))
+ exact (congrArg Fin.val h).trans (Nat.mod_eq_of_lt (hv e))
+ · refine ⟨(atSlot (.inr (.inr (.inr 0)))).trans (he .target), ?_,
+ (atSlot (.inr (.inr (.inr 2)))).trans (he .hist), (atSlot (.inr (.inr (.inr 3)))).trans rfl⟩
+ apply (atSlot (.inr (.inr (.inr 1)))).trans
+ simp [recipe, Expr.add, Expr.eval, BinaryOp.eval, he, values]
+
+/-- Raw caller data for initializing the map, independent of the selector sequence. -/
+structure Input (ptr : Fin r) (c : Config w p r) : Prop where
+ descriptor : ∀ a, c.privateMem (c.reg ptr + ((args a).val : BurstRAM.Word w)) = values A loc X a
+ payloadFit : ∀ e, v e < 2 ^ w
+ supplyBase : ∀ t : Port G j,
+ X.portBase t = (X.base (MapDirectoryInit.portField t) : BurstRAM.Word w)
+ supply : ∀ (t : Port G j) (l : Fin (v (edge t) + u * B.selectorBits)),
+ c.privateMem (X.portBase t + (l.val : BurstRAM.Word w)) =
+ PrimedInputRAM.encodeBit w (field x t l)
+ demandCells : ∀ q : Bool × D, ∀ l : Fin (MapRow.endpoint src dst j demand d q).1,
+ c.privateMem ((X.base (.inl q) + l.val : ℕ) : BurstRAM.Word w) =
+ PrimedInputRAM.encodeBit w ((MapRow.endpoint src dst j demand d q).2 l)
+ supplyApart : ∀ (t : Port G j) (l : Fin (v (edge t) + u * B.selectorBits))
+ (a : MapDirectoryInit.Row A),
+ X.portBase t + (l.val : BurstRAM.Word w) ≠ X.directory + (a.val : BurstRAM.Word w)
+ demandApart : ∀ q : Bool × D, ∀ l : Fin (MapRow.endpoint src dst j demand d q).1,
+ ∀ a : MapDirectoryInit.Row A,
+ ((X.base (.inl q) + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (a.val : BurstRAM.Word w)
+
+private def segment {w : ℕ} (mem : BurstRAM.Word w → BurstRAM.Word w) (base : ℕ)
+ (b : (l : ℕ) × (Fin l → Bool)) : Prop :=
+ ∀ i : Fin b.1, mem ((base + i.val : ℕ) : BurstRAM.Word w) = PrimedInputRAM.encodeBit w (b.2 i)
+
+private theorem rowData (mem : BurstRAM.Word w → BurstRAM.Word w)
+ (hb : ∀ t : Port G j, X.portBase t = (X.base (MapDirectoryInit.portField t) : BurstRAM.Word w))
+ (hs : ∀ (t : Port G j) (l : Fin (v (edge t) + u * B.selectorBits)),
+ mem (X.portBase t + (l.val : BurstRAM.Word w)) = PrimedInputRAM.encodeBit w (field x t l))
+ (hd : ∀ q : Bool × D, segment mem (X.base (.inl q)) (MapRow.endpoint src dst j demand d q))
+ (θ : Fin u → Selector B) (f : LabelField D E) :
+ ∀ l : Fin ((MapRowLoop.buffers B z j demand v d x X.base θ 0).len f),
+ mem ((X.base f + l.val : ℕ) : BurstRAM.Word w) =
+ PrimedInputRAM.encodeBit w
+ ((MapRowLoop.buffers B z j demand v d x X.base θ 0).bits f l) := by
+ rcases f with q | ⟨b, e⟩
+ · exact hd q
+ · change segment mem (X.base (.inr (b, e)))
+ (MapRow.endpoint G.src G.dst j v (mapHalf G (fun _ ↦ payloadBits) x) (b, e))
+ cases b <;> rw [MapRow.endpoint]
+ · split
+ · rename_i he
+ intro i
+ let t : Port G j := .inl ⟨e, he⟩
+ have cell := hs t (Fin.castLE (Nat.le_add_right ..) i)
+ change mem (X.portBase t + (i.val : BurstRAM.Word w)) = _ at cell
+ rw [hb] at cell
+ rw [Nat.cast_add]
+ exact cell
+ · exact fun i ↦ i.elim0
+ · split
+ · rename_i he
+ intro i
+ let t : Port G j := .inr ⟨e, he⟩
+ have cell := hs t (Fin.castLE (Nat.le_add_right ..) i)
+ change mem (X.portBase t + (i.val : BurstRAM.Word w)) = _ at cell
+ rw [hb] at cell
+ rw [Nat.cast_add]
+ exact cell
+ · exact fun i ↦ i.elim0
+
+/-- The descriptor reader and directory writer leave the actual map program ready at
+its first instruction, preserving every private cell outside the fixed port directory. -/
+theorem native (slots : Register D E ≃ Fin (Fintype.card (Register D E))) (M : Machine w p r k)
+ (ptr : Fin r) (scratch : Fin 2 ↪ Fin r) (apart : ∀ a i, A.reg a ≠ scratch i)
+ (dirPC : MapDirectoryInit.Address A → Fin p)
+ (dirLink : ∀ a, M.code (dirPC a) =
+ (MapDirectoryInit.text A scratch dirPC ((A.selector loc).scan 0) a).resize w) :
+ let anchor := MapDirectoryInit.portField (anchorPort G j)
+ let f := recipes A args anchor slots
+ ∀ (vm : Fin (RegisterSetup.regCount f) ↪ Fin r)
+ (_place : ∀ a, vm (RegisterSetup.output f (slots a)) = A.reg a)
+ (_safe : ∀ i, vm i ≠ ptr) (pc : ℕ → Fin p)
+ (_hl : MapInitCompiler.Linked vm ptr M pc (RegisterSetup.lines f))
+ (_endPC : pc (RegisterSetup.lines f).length = dirPC (.inl ()))
+ (c : Config w p r), c.pc = pc 0 → Input A args loc X ptr c →
+ ∃ out, Prefix M c (List.replicate
+ ((RegisterSetup.lines f).length + (1 + 3 * (ports G j A.edgeOrder).length)) .tick) out ∧
+ (A.program loc).Ready X out ∧ out.persistent = c.persistent ∧
+ ∀ q, (∀ a : MapDirectoryInit.Row A, q ≠ X.directory + (a.val : BurstRAM.Word w)) →
+ out.privateMem q = c.privateMem q := by
+ intro anchor f vm place safe pc hl endPC c hc input
+ obtain ⟨m, pre, hm, vals, mem, per, _⟩ :=
+ load A args anchor slots vm place ptr safe M pc hl c hc
+ have he := eval_arg args (values A loc X) c ptr input.descriptor
+ have dir : m.reg (A.selectors.scanReg 7) = X.directory :=
+ (vals (.inl (.inl 7))).trans (he .directory)
+ have one : m.reg (A.selectors.scanReg 3) = 1 := (vals (.inl (.inl 3))).trans rfl
+ obtain ⟨out, tail, start, hp, keep, pointers, outside⟩ :=
+ MapDirectoryInit.native A scratch dirPC ((A.selector loc).scan 0) M dirLink apart m
+ (hm.trans endPC) one X.portsFit.le
+ rw [dir] at pointers outside
+ have frame (q) (hq : ∀ a : MapDirectoryInit.Row A, q ≠ X.directory + (a.val : BurstRAM.Word w)) :
+ out.privateMem q = c.privateMem q := (outside q hq).trans (congrFun mem q)
+ have supply (t : Port G j) (l : Fin (v (edge t) + u * B.selectorBits)) :
+ out.privateMem (X.portBase t + (l.val : BurstRAM.Word w)) =
+ PrimedInputRAM.encodeBit w (field x t l) :=
+ (frame _ (input.supplyApart t l)).trans (input.supply t l)
+ have dem (q : Bool × D) (l : Fin (MapRow.endpoint src dst j demand d q).1) :
+ out.privateMem ((X.base (.inl q) + l.val : ℕ) : BurstRAM.Word w) =
+ PrimedInputRAM.encodeBit w ((MapRow.endpoint src dst j demand d q).2 l) :=
+ (frame _ (input.demandApart q l)).trans (input.demandCells q l)
+ refine ⟨out, ?_, ready_of_registers A args anchor loc X out start
+ (input.supplyBase _) input.payloadFit _ _ _ he (fun a ↦ (keep _ (apart a 0) (apart a 1)).trans
+ (vals a)) ⟨?_, supply⟩ (rowData A loc X _ input.supplyBase supply dem), hp.trans per, frame⟩
+ · rw [List.replicate_add]
+ exact pre.append tail
+ · intro a
+ let t := (ports G j A.edgeOrder).get a
+ have base : m.reg (A.bank.rowReg (.base (MapDirectoryInit.portField t))) = X.portBase t :=
+ ((vals (.inr (.inl (.inr (.base (MapDirectoryInit.portField t)))))).trans
+ (he (.base (MapDirectoryInit.portField t)))).trans (input.supplyBase t).symm
+ have width : m.reg (A.expected (edge t)) = (v (edge t) : BurstRAM.Word w) :=
+ (vals (.inr (.inr (.inl (edge t))))).trans (he (.payload (edge t)))
+ exact (pointers a).trans (congrArg₂ (· + ·) base width)
+
+end PairSimulation.MapCallSetup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapCallTable.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapCallTable.lean
new file mode 100644
index 0000000000..890a1dc50f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapCallTable.lean
@@ -0,0 +1,309 @@
+import OAI.Computability.VPVNP.PairSimulationMapCallRun
+
+/-!
+# Complete motif call table including initialization
+
+A single fixed table loads the operand expressions from the private descriptor,
+constructs the port directory, and enters the grouped map interpreter. The
+expression compiler writes directly into the interpreter's allocated registers.
+The descriptor pointer and the directory temporaries occupy distinct registers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapCallTable
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry
+open MapEntryTable MapPortAgreement MapResidentAgreement MapCallSetup
+open BurstRAM.PrivateRAM CompressorRecords
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H')
+ (z : B.grid.demands) (j : J) {r k p w u t : ℕ}
+
+private noncomputable def number (X : Type*) [Finite X] : X ≃ Fin (Nat.card X) := by
+ letI := Fintype.ofFinite X
+ exact Fintype.equivFinOfCardEq Nat.card_eq_fintype_card.symm
+
+variable {B z j} in
+/-- Map-call register initialization expressions using the field of this party's anchor port to
+locate its selector suffix. -/
+noncomputable abbrev formulas (A : Allocation B z j r k)
+ (args : Arg D E ≃ Fin (Fintype.card (Arg D E)))
+ (slots : Register D E ≃ Fin (Fintype.card (Register D E))) :=
+ recipes A args (MapDirectoryInit.portField (anchorPort G j)) slots
+
+/-- Register layout for the compiler bank and the map, including their shared outputs. -/
+structure Layout (r k : ℕ) where
+ /-- Register and public-word allocation, with supply-edge order, for the grouped map
+ interpreter entered after call initialization. -/
+ core : Allocation B z j r k
+ /-- Number the fields of the private call descriptor so each argument can be loaded by its
+ word offset. -/
+ args : Arg D E ≃ Fin (Fintype.card (Arg D E))
+ /-- Number the map interpreter's logical registers to identify the corresponding
+ initialization outputs. -/
+ slots : Register D E ≃ Fin (Fintype.card (Register D E))
+ /-- Place the expression compiler's output and scratch registers in the physical register
+ file. Each output aliases its designated map register. -/
+ vm : Fin (RegisterSetup.regCount (formulas core args slots)) ↪ Fin r
+ /-- Register containing the base address of the private call descriptor during register
+ initialization. -/
+ ptr : Fin r
+ /-- Two temporary registers for the port directory writer, holding the current directory cell
+ and the selector-suffix pointer to store there. -/
+ scratch : Fin 2 ↪ Fin r
+ output : ∀ a, vm (RegisterSetup.output (formulas core args slots) (slots a)) = core.reg a
+ vmApart : ∀ i, vm i ≠ ptr
+ directoryApart : ∀ a i, core.reg a ≠ scratch i
+
+/-- Allocate the output and expression scratch bank, then two directory temporaries
+and the descriptor pointer. The seed supplies the public ports and edge order. -/
+noncomputable def allocate (seed : Allocation B z j r k)
+ (args : Arg D E ≃ Fin (Fintype.card (Arg D E)))
+ (slots : Register D E ≃ Fin (Fintype.card (Register D E))) :
+ Layout B z j (RegisterSetup.regCount (formulas seed args slots) + 3) k := by
+ let f := formulas seed args slots
+ let N := RegisterSetup.regCount f
+ let vm : Fin N ↪ Fin (N + 3) := Fin.castAddEmb 3
+ let out : Register D E ↪ Fin (N + 3) :=
+ ⟨fun a ↦ vm (RegisterSetup.output f (slots a)), fun a b h ↦ slots.injective <|
+ Fin.ext (congrArg (Fin.val : Fin N → ℕ) (vm.injective h))⟩
+ let core : Allocation B z j (N + 3) k := ⟨out, seed.pub, seed.edgeOrder⟩
+ let dir : Fin 2 ↪ Fin (N + 3) := (Fin.castAddEmb 1).trans (Fin.natAddEmb N)
+ refine ⟨core, args, slots, vm, (Fin.last 2).natAdd N, dir, fun _ ↦ rfl, ?_, ?_⟩
+ · intro i eq
+ have he := congrArg Fin.val eq
+ change i.val = N + 2 at he
+ have hi : i.val < N := i.isLt
+ omega
+ · intro a i eq
+ have he := congrArg Fin.val eq
+ change (RegisterSetup.output f (slots a)).val = N + i.val at he
+ have hi : (RegisterSetup.output f (slots a)).val < N := (RegisterSetup.output f (slots a)).isLt
+ omega
+
+namespace Layout
+
+variable {B z j} (L : Layout B z j r k)
+
+/-- Ordered assignments emitted by the expression compiler to initialize the map registers from
+the private descriptor. -/
+noncomputable abbrev lines := RegisterSetup.lines (formulas L.core L.args L.slots)
+
+/-- Instruction addresses of the complete map call, partitioned into descriptor setup, port
+directory construction, and grouped map evaluation. -/
+noncomputable abbrev Address :=
+ Fin L.lines.length ⊕ MapDirectoryInit.Address L.core ⊕ L.core.Address
+
+variable (loc : L.Address → Fin p)
+
+/-- Relocate an instruction address of the grouped map interpreter into the complete call
+table. -/
+def corePC (a : L.core.Address) := loc (.inr (.inr a))
+
+/-- Relocate an address of the incident port directory initializer into the complete call
+table. -/
+def dirPC (a : MapDirectoryInit.Address L.core) := loc (.inr (.inl a))
+
+/-- Program counter for a compiled register assignment, with the end of the assignment list
+transferring control to the directory initializer. -/
+noncomputable def initPC (n : ℕ) :=
+ if h : n < L.lines.length then loc (.inl ⟨n, h⟩) else L.dirPC loc (.inl ())
+
+/-- Emit the instruction at a call-table address, linking the last setup assignment to the
+directory writer and the directory writer to the map's selector scan. -/
+noncomputable def text : L.Address → Instr 2 p r k
+ | .inl i => MapInitCompiler.instruction L.vm L.ptr L.lines[i.val] (L.initPC loc (i.val + 1))
+ | .inr (.inl a) => MapDirectoryInit.text L.core L.scratch (L.dirPC loc)
+ ((L.core.selector (L.corePC loc)).scan 0) a
+ | .inr (.inr a) => L.core.text (L.corePC loc) a
+
+/-- Keep the successful exit available as the caller's continuation. -/
+noncomputable def installed : L.Address → Bool
+ | .inr (.inr a) => L.core.installed a
+ | _ => true
+
+/-- Finite numbering of all descriptor setup, directory, and map interpreter addresses in this
+layout. -/
+noncomputable def locations : L.Address ≃ Fin (Nat.card L.Address) := number _
+
+/-- Standalone template for a complete map call, starting with descriptor setup and using the
+finite address numbering for all jump targets. -/
+noncomputable def template : Template (Nat.card L.Address) r k :=
+ ⟨2, L.initPC L.locations 0, fun pc ↦ L.text L.locations (L.locations.symm pc)⟩
+
+theorem template_at (pub : Fin k → BurstRAM.Word w) (a : L.Address) :
+ (L.template.instantiate w pub).code (L.locations a) = (L.text L.locations a).resize w := by
+ simp [template, Template.instantiate]
+
+/-- These are the precise instruction-level links of initialization and execution. -/
+theorem links (M : Machine w p r k) (h : ∀ a, L.installed a = true →
+ M.code (loc a) = (L.text loc a).resize w) :
+ MapInitCompiler.Linked L.vm L.ptr M (L.initPC loc) L.lines ∧
+ (∀ a, M.code (L.dirPC loc a) = (MapDirectoryInit.text L.core L.scratch (L.dirPC loc)
+ ((L.core.selector (L.corePC loc)).scan 0) a).resize w) ∧
+ ∀ a, L.core.installed a = true → M.code (L.corePC loc a) =
+ (L.core.text (L.corePC loc) a).resize w := by
+ refine ⟨?_, fun a ↦ h (.inr (.inl a)) rfl, fun a ha ↦ h (.inr (.inr a)) ha⟩
+ intro i
+ rw [initPC, dite_eq_left i.isLt]
+ exact (h (.inl i) rfl).trans (MapInitCompiler.resize_instruction ..)
+
+/-- Execute the installed finite table, including the operand and directory prefix. -/
+theorem native_post (M : Machine w p r k) (h : ∀ a, L.installed a = true →
+ M.code (loc a) = (L.text loc a).resize w)
+ {demand : D → ℕ} {v : E → ℕ} {d : DemandBits src dst demand j}
+ {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (X : MapEntry.Program.Workspace (L.core.program (L.corePC loc)) demand v d x t w)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t) (pub : ∀ a, M.publicData (L.core.pub a) =
+ Allocation.words fb fd fs sel (fun e ↦ ((ord e).val : BurstRAM.Word w)) a)
+ (histApart : ∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w))
+ (c : Config w p r) (hc : c.pc = L.initPC loc 0)
+ (input : Input L.core L.args (L.corePC loc) X L.ptr c) :
+ (L.core.program (L.corePC loc)).RunsPost M c X.hist (L.lines.length +
+ (1 + 3 * (ports G j L.core.edgeOrder).length) + MapNativeClock.cap B z j u)
+ (MapCallSetup.Outside L.core (L.corePC loc) X)
+ ((MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.map (List.map ord))
+ (MapCallSetup.Success L.core (L.corePC loc) X sel ord c.privateMem) := by
+ obtain ⟨init, dir, core⟩ := L.links loc M h
+ exact MapCallSetup.run_post L.core L.args L.slots (L.corePC loc) X M core L.ptr L.scratch
+ L.directoryApart (L.dirPC loc) dir fb fd fs sel ord pub histApart L.vm L.output L.vmApart
+ (L.initPC loc) init (by simp [initPC]) c hc input
+
+/-- The exact memory update implies preservation outside the written cells. -/
+theorem native_framed (M : Machine w p r k) (h : ∀ a, L.installed a = true →
+ M.code (loc a) = (L.text loc a).resize w)
+ {demand : D → ℕ} {v : E → ℕ} {d : DemandBits src dst demand j}
+ {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (X : MapEntry.Program.Workspace (L.core.program (L.corePC loc)) demand v d x t w)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t) (pub : ∀ a, M.publicData (L.core.pub a) =
+ Allocation.words fb fd fs sel (fun e ↦ ((ord e).val : BurstRAM.Word w)) a)
+ (histApart : ∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w))
+ (c : Config w p r) (hc : c.pc = L.initPC loc 0)
+ (input : Input L.core L.args (L.corePC loc) X L.ptr c) :
+ (L.core.program (L.corePC loc)).RunsFramed M c X.hist (L.lines.length +
+ (1 + 3 * (ports G j L.core.edgeOrder).length) + MapNativeClock.cap B z j u)
+ (MapCallSetup.Outside L.core (L.corePC loc) X)
+ ((MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.map (List.map ord)) :=
+ (L.native_post loc M h X fb fd fs sel ord pub histApart c hc input).framed _
+
+/-- The histogram and exit semantics of the native call. -/
+theorem native (M : Machine w p r k) (h : ∀ a, L.installed a = true →
+ M.code (loc a) = (L.text loc a).resize w)
+ {demand : D → ℕ} {v : E → ℕ} {d : DemandBits src dst demand j}
+ {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (X : MapEntry.Program.Workspace (L.core.program (L.corePC loc)) demand v d x t w)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t) (pub : ∀ a, M.publicData (L.core.pub a) =
+ Allocation.words fb fd fs sel (fun e ↦ ((ord e).val : BurstRAM.Word w)) a)
+ (histApart : ∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w))
+ (c : Config w p r) (hc : c.pc = L.initPC loc 0)
+ (input : Input L.core L.args (L.corePC loc) X L.ptr c) :
+ (L.core.program (L.corePC loc)).Runs M c X.hist (L.lines.length +
+ (1 + 3 * (ports G j L.core.edgeOrder).length) + MapNativeClock.cap B z j u)
+ ((MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.map (List.map ord)) :=
+ (L.native_framed loc M h X fb fd fs sel ord pub histApart c hc input).forget _
+
+/-- The very same instruction and public-data bank implements the map for all live
+inputs. Only the resident raw descriptor and the actual input bit slices are required. -/
+theorem run_entryInput_post (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : Layout B (demandGrid B hp I.demand) I.party r k)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B (demandGrid B hp I.demand) e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t) :
+ let loc := L.corePC L.locations
+ let P := L.core.program loc
+ let pub := L.core.install
+ (Allocation.words fb fd fs sel (fun e ↦ ((ord e).val : BurstRAM.Word w))) (fun _ ↦ 0)
+ let M := L.template.instantiate w pub
+ let demand := demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ inputBits) I.supplyBits
+ ∀ (X : MapEntry.Program.Workspace P I.demand I.payload demand supply t w)
+ (c : Config w (Nat.card L.Address) r), c.pc = M.entry →
+ Input L.core L.args loc X L.ptr c →
+ (∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ P.RunsPost M c X.hist (L.lines.length +
+ (1 + 3 * (ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand))
+ (MapCallSetup.Outside L.core loc X)
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord))
+ (MapCallSetup.Success L.core loc X sel ord c.privateMem) := by
+ intro loc P pub M demand supply X c hc input disj
+ exact L.native_post L.locations M (fun a _ ↦ L.template_at pub a) X fb fd fs sel ord
+ (L.core.install_at (Allocation.words fb fd fs sel (fun e ↦ ((ord e).val : BurstRAM.Word w)))
+ (fun _ ↦ 0)) disj c hc input
+
+/-- The exterior memory frame at a recorded native call. -/
+theorem run_entryInput_framed (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : Layout B (demandGrid B hp I.demand) I.party r k)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B (demandGrid B hp I.demand) e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t) :
+ let loc := L.corePC L.locations
+ let P := L.core.program loc
+ let pub := L.core.install
+ (Allocation.words fb fd fs sel (fun e ↦ ((ord e).val : BurstRAM.Word w))) (fun _ ↦ 0)
+ let M := L.template.instantiate w pub
+ let demand := demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ inputBits) I.supplyBits
+ ∀ (X : MapEntry.Program.Workspace P I.demand I.payload demand supply t w)
+ (c : Config w (Nat.card L.Address) r), c.pc = M.entry →
+ Input L.core L.args loc X L.ptr c →
+ (∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ P.RunsFramed M c X.hist (L.lines.length +
+ (1 + 3 * (ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand))
+ (MapCallSetup.Outside L.core loc X)
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord)) := by
+ intro loc P pub M demand supply X c hc input disj
+ exact (run_entryInput_post hp I L fb fd fs sel ord X c hc input disj).framed _
+
+/-- The same physical path evaluated on an actual recorded template invocation. -/
+theorem run_entryInput (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : Layout B (demandGrid B hp I.demand) I.party r k)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B (demandGrid B hp I.demand) e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t) :
+ let loc := L.corePC L.locations
+ let P := L.core.program loc
+ let pub := L.core.install
+ (Allocation.words fb fd fs sel (fun e ↦ ((ord e).val : BurstRAM.Word w))) (fun _ ↦ 0)
+ let M := L.template.instantiate w pub
+ let demand := demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ inputBits) I.supplyBits
+ ∀ (X : MapEntry.Program.Workspace P I.demand I.payload demand supply t w)
+ (c : Config w (Nat.card L.Address) r), c.pc = M.entry →
+ Input L.core L.args loc X L.ptr c →
+ (∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ P.Runs M c X.hist (L.lines.length + (1 + 3 * (ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand))
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord)) := by
+ intro loc P pub M demand supply X c hc input disj
+ exact (run_entryInput_framed hp I L fb fd fs sel ord X c hc input disj).forget _
+
+end Layout
+
+end PairSimulation.MapCallTable
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapChainWork.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapChainWork.lean
new file mode 100644
index 0000000000..60d356ba80
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapChainWork.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairSimulationEntryWork
+import OAI.Computability.VPVNP.CompressionHistory
+
+/-!
+# Summing local map checks and leaf runs in a placement history
+
+Each selected term places old vertices intact at one output vertex. The
+work of its map interpreters and of the original leaves therefore obeys
+the same placement-fiber recurrence as the recorded occurrence count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel Compression
+
+variable {k A : Type*} [Field k] {S : BlockSchedule k} {N Y : Network}
+
+/-- Interpreter inputs at the individual map slots of an entire branch.
+The index on each invocation is the degree recorded at that slot. -/
+def MapInputs (B : S.Templates) : {N Y : Network} → TermChain A N Y → Type
+ | _, _, .done _ => PUnit
+ | _, _, .more _ rec tail =>
+ (∀ v i, MapInvocation B ((rec v).degree i)) × MapInputs B tail
+
+open scoped Classical in
+/-- Sum the instruction charges of individual recorded map slots and original leaves
+inside the actual preimage subtree of each final site. -/
+noncomputable def mapAndLeafCost {B : S.Templates}
+ (cost : {d : ℕ} → MapInvocation B d → ℕ) : {N Y : Network} → (c : TermChain A N Y) →
+ MapInputs B c → (N.Site → ℕ) → Y.Site → ℕ
+ | _, _, .done _, _, leaf => leaf
+ | _, _, .more t _ tail, calls, leaf =>
+ mapAndLeafCost cost tail calls.2 fun v ↦
+ (∑ i, cost (calls.1 v i)) + ∑ u : t.Preimage v, leaf u.val
+
+/-- Metered interpreter charges in the same placement fibers. -/
+noncomputable abbrev mapAndLeafWork {B : S.Templates} (c : TermChain A N Y) (calls : MapInputs B c)
+ (leaf : N.Site → ℕ) := mapAndLeafCost MapInvocation.work c calls leaf
+
+/-- This bound holds for every input to every recorded interpreter, without
+an acceptance requirement or equality of independently supplied half-wires. -/
+theorem mapAndLeafCost_le {B : S.Templates} (cost : {d : ℕ} → MapInvocation B d → ℕ)
+ (c : TermChain A N Y) (calls : MapInputs B c)
+ {L T : ℕ} (hk : ∀ d ≤ L, ∀ m : MapInvocation B d, cost m ≤ T)
+ (hl : c.AllRecordsLe L) (leaf count : N.Site → ℕ)
+ (hstart : ∀ v, leaf v ≤ count v * T) :
+ ∀ v, mapAndLeafCost cost c calls leaf v ≤ c.occurrences count v * T := by
+ classical
+ induction c with
+ | done => exact hstart
+ | more t rec tail ih =>
+ apply ih calls.2 hl.2.2 _ (t.pushHistorySize rec count)
+ intro v
+ rw [Term.pushHistorySize, Nat.add_mul, Finset.sum_mul]
+ apply Nat.add_le_add
+ · calc
+ _ ≤ ∑ _i : (rec v).Map, T := Finset.sum_le_sum fun i _ ↦
+ hk _ (hl.2.1 v i) (calls.1 v i)
+ _ = Fintype.card (rec v).Map * T := by simp
+ _ ≤ (rec v).count * T :=
+ Nat.mul_le_mul_right _ (by unfold SiteRecords.count; omega)
+ · exact Finset.sum_le_sum fun u _ ↦ hstart u.val
+
+/-- This bound holds for every input to every recorded interpreter, without
+an acceptance requirement or equality of independently supplied half-wires. -/
+theorem mapAndLeafWork_le {B : S.Templates} (c : TermChain A N Y) (calls : MapInputs B c)
+ {K L T : ℕ} (hk : ∀ d (m : MapInvocation B d), m.work ≤ K * (d + 1) ^ 2)
+ (hl : c.AllRecordsLe L) (ht : K * (L + 1) ^ 2 ≤ T) (leaf count : N.Site → ℕ)
+ (hstart : ∀ v, leaf v ≤ count v * T) :
+ ∀ v, mapAndLeafWork c calls leaf v ≤ c.occurrences count v * T := by
+ apply mapAndLeafCost_le MapInvocation.work c calls _ hl leaf count hstart
+ intro d hd m
+ exact (hk d m).trans ((Nat.mul_le_mul_left _
+ (Nat.pow_le_pow_left (Nat.succ_le_succ hd) 2)).trans ht)
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapConsistency.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapConsistency.lean
new file mode 100644
index 0000000000..f30ab2cca0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapConsistency.lean
@@ -0,0 +1,213 @@
+import OAI.Computability.VPVNP.MotifEntry
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Native comparison of the inner selector arrays
+
+The comparison in Theorem 6.1 reads one resident tag per copy from a port
+and its anchor. It accumulates the bitwise OR of their differences. Thus a
+later match cannot erase an earlier mismatch, and the same accumulator can
+be passed from port to port. The scan takes seven private steps per copy
+and one exit test, including for arbitrary inputs to a final-site call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapConsistency
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Registers hold the left cursor, exclusive left end, right cursor,
+constant one, difference mask, and two scratch words. -/
+def instruction (pc : Fin 7 → Fin p) (reg : Fin 7 ↪ Fin r) (done : Fin p) :
+ Fin 7 → Instr w p r k :=
+ ![.jumpEq (reg 0) (reg 1) done (pc 1),
+ .loadPrivate (reg 5) (reg 0) (pc 2), .loadPrivate (reg 6) (reg 2) (pc 3),
+ .binary .bitXor (reg 5) (reg 5) (reg 6) (pc 4),
+ .binary .bitOr (reg 4) (reg 4) (reg 5) (pc 5),
+ .binary .add (reg 0) (reg 0) (reg 3) (pc 6),
+ .binary .add (reg 2) (reg 2) (reg 3) (pc 0)]
+
+theorem resize_instruction (pc : Fin 7 → Fin p) (reg : Fin 7 ↪ Fin r) (done : Fin p) (i : Fin 7) :
+ (instruction (w := 1) (k := k) pc reg done i).resize w = instruction pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- The enclosing machine embeds every comparison instruction at its designated label. -/
+def Linked (M : Machine w p r k) (pc : Fin 7 → Fin p) (reg : Fin 7 ↪ Fin r) (done : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+private theorem difference_zero (mask x y : Word w) :
+ BinaryOp.bitOr.eval mask (BinaryOp.bitXor.eval x y) = 0 ↔ mask = 0 ∧ x = y := by
+ have hx : (BinaryOp.bitXor.eval x y).val = x.val ^^^ y.val :=
+ Nat.mod_eq_of_lt (Nat.xor_lt_two_pow x.isLt y.isLt)
+ have ho : (BinaryOp.bitOr.eval mask (BinaryOp.bitXor.eval x y)).val =
+ mask.val ||| (BinaryOp.bitXor.eval x y).val :=
+ Nat.mod_eq_of_lt (Nat.or_lt_two_pow mask.isLt (BinaryOp.bitXor.eval x y).isLt)
+ rw [Fin.ext_iff, ho, hx]
+ change (mask.val ||| (x.val ^^^ y.val) = 0) ↔ _
+ rw [Nat.or_eq_zero_iff]
+ constructor
+ · rintro ⟨hm, he⟩
+ refine ⟨Fin.ext hm, Fin.ext ?_⟩
+ calc
+ x.val = (x.val ^^^ y.val) ^^^ y.val := by simp
+ _ = y.val := by simp [he]
+ · rintro ⟨rfl, rfl⟩
+ simp
+
+variable {M : Machine w p r k} {pc : Fin 7 → Fin p} {reg : Fin 7 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (hl : Linked M pc reg done) (i : Fin 7) {c : Config w p r}
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+/-- The comparison only writes the two cursors, the mask and the two scratch registers. -/
+def Frame (reg : Fin 7 ↪ Fin r) (c out : Config w p r) : Prop :=
+ ∀ j, j ≠ reg 0 → j ≠ reg 2 → j ≠ reg 4 → j ≠ reg 5 → j ≠ reg 6 → out.reg j = c.reg j
+
+private theorem iteration (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (hne : c.reg (reg 0) ≠ c.reg (reg 1)) (hone : c.reg (reg 3) = 1) :
+ ∃ out, Prefix M c (List.replicate 7 .tick) out ∧ out.pc = pc 0 ∧
+ out.reg (reg 0) = c.reg (reg 0) + 1 ∧ out.reg (reg 2) = c.reg (reg 2) + 1 ∧
+ (out.reg (reg 4) = 0 ↔ c.reg (reg 4) = 0 ∧
+ c.privateMem (c.reg (reg 0)) = c.privateMem (c.reg (reg 2))) ∧
+ Frame reg c out ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let x := c.privateMem (c.reg (reg 0))
+ let y := c.privateMem (c.reg (reg 2))
+ let d := BinaryOp.bitXor.eval x y
+ let c₁ := {c with pc := pc 1}
+ let c₂ := c₁.put (pc 2) (reg 5) x
+ let c₃ := c₂.put (pc 3) (reg 6) y
+ let c₄ := c₃.put (pc 4) (reg 5) d
+ let c₅ := c₄.put (pc 5) (reg 4) (BinaryOp.bitOr.eval (c.reg (reg 4)) d)
+ let c₆ := c₅.put (pc 6) (reg 0) (c.reg (reg 0) + 1)
+ let out := c₆.put (pc 0) (reg 2) (c.reg (reg 2) + 1)
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step_at hl 0 hc]
+ simp [instruction, Instr.run, hne, c₁]
+ have s₁ : M.program.step c₁ = .localStep c₂ := step_at hl 1 rfl
+ have s₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step_at hl 2 rfl]
+ change CallAction.localStep (c₂.put (pc 3) (reg 6) (c.privateMem (c₂.reg (reg 2)))) = _
+ simp [c₃, c₂, c₁, Config.put, y]
+ have s₃ : M.program.step c₃ = .localStep c₄ := by
+ rw [step_at hl 3 rfl]
+ change CallAction.localStep (c₃.put (pc 4) (reg 5)
+ (BinaryOp.bitXor.eval (c₃.reg (reg 5)) (c₃.reg (reg 6)))) = _
+ simp [c₄, c₃, c₂, d, Config.put]
+ have s₄ : M.program.step c₄ = .localStep c₅ := by
+ rw [step_at hl 4 rfl]
+ change CallAction.localStep (c₄.put (pc 5) (reg 4)
+ (BinaryOp.bitOr.eval (c₄.reg (reg 4)) (c₄.reg (reg 5)))) = _
+ simp [c₅, c₄, c₃, c₂, c₁, Config.put]
+ have s₅ : M.program.step c₅ = .localStep c₆ := by
+ rw [step_at hl 5 rfl]
+ change CallAction.localStep (c₅.put (pc 6) (reg 0) (c₅.reg (reg 0) + c₅.reg (reg 3))) = _
+ simp [c₆, c₅, c₄, c₃, c₂, c₁, Config.put, hone]
+ have s₆ : M.program.step c₆ = .localStep out := by
+ rw [step_at hl 6 rfl]
+ change CallAction.localStep (c₆.put (pc 0) (reg 2) (c₆.reg (reg 2) + c₆.reg (reg 3))) = _
+ simp [out, c₆, c₅, c₄, c₃, c₂, c₁, Config.put, hone]
+ refine ⟨out, .tick s₀ (.tick s₁ (.tick s₂ (.tick s₃ (.tick s₄ (.tick s₅ (.tick s₆ (.nil _))))))),
+ rfl, by simp [out, c₆, Config.put], by simp [out], ?_, ?_, rfl, rfl⟩
+ · simpa [out, c₆, c₅, Config.put, d, x, y] using difference_zero (c.reg (reg 4)) x y
+ · intro j h₀ h₂ h₄ h₅ h₆
+ simp [out, c₆, c₅, c₄, c₃, c₂, c₁, Config.put, Function.update_of_ne, h₀, h₂, h₄, h₅, h₆]
+
+/-- Execute the comparison on two private arrays. They may overlap and their
+values need not be valid selector codes. The output mask is zero precisely
+when the incoming mask was zero and every compared word agreed. -/
+theorem compareArrays (hl : Linked M pc reg done) {n : ℕ} (x y : Fin n → Word w)
+ (left right : Word w) (c : Config w p r) (hc : c.pc = pc 0)
+ (hleft : c.reg (reg 0) = left) (hend : c.reg (reg 1) = left + (n : Word w))
+ (hright : c.reg (reg 2) = right) (h1 : c.reg (reg 3) = 1) (hn : n < 2 ^ w)
+ (hx : ∀ i : Fin n, c.privateMem (left + (i.val : Word w)) = x i)
+ (hy : ∀ i : Fin n, c.privateMem (right + (i.val : Word w)) = y i) :
+ ∃ out, Prefix M c (List.replicate (7 * n + 1) .tick) out ∧ out.pc = done ∧
+ out.reg (reg 0) = left + (n : Word w) ∧ out.reg (reg 2) = right + (n : Word w) ∧
+ (out.reg (reg 4) = 0 ↔ c.reg (reg 4) = 0 ∧ ∀ i, x i = y i) ∧
+ Frame reg c out ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ induction n generalizing left right c with
+ | zero =>
+ have he : c.reg (reg 0) = c.reg (reg 1) := hleft.trans (by simpa using hend.symm)
+ have hs : M.program.step c = .localStep {c with pc := done} := by
+ rw [step_at hl 0 hc]
+ simp [instruction, Instr.run, he]
+ exact ⟨_, .tick hs (.nil _), rfl, by simpa using hleft, by simpa using hright,
+ by simp, fun _ _ _ _ _ _ ↦ rfl, rfl, rfl⟩
+ | succ n ih =>
+ have ne : c.reg (reg 0) ≠ c.reg (reg 1) := by
+ rw [hleft, hend]
+ intro h
+ have hz : ((n + 1 : ℕ) : Word w) = 0 := add_left_cancel (a := left) (by simpa using h.symm)
+ have hv := congrArg Fin.val hz
+ change (n + 1) % (2 ^ w) = 0 at hv
+ rw [Nat.mod_eq_of_lt hn] at hv
+ omega
+ obtain ⟨mid, pre, hpc, hl', hr', mask, frame, hmem, hp⟩ := iteration hl c hc ne h1
+ have htail (base : Word w) (i : Fin n) :
+ base + 1 + (i.val : Word w) = base + (i.succ.val : Word w) := by
+ simp [Fin.val_succ, add_assoc, add_comm (1 : Word w)]
+ obtain ⟨out, tail, ho, hleft', hright', hm, frame', hm', hp'⟩ :=
+ ih (fun i ↦ x i.succ) (fun i ↦ y i.succ) (left + 1) (right + 1) mid hpc
+ (hl'.trans (by rw [hleft]))
+ (by rw [frame, hend] <;> simp [add_assoc, add_comm (1 : Word w)])
+ (hr'.trans (by rw [hright])) (by rw [frame, h1] <;> simp) (by omega)
+ (fun i ↦ by rw [hmem, htail]; exact hx i.succ)
+ (fun i ↦ by rw [hmem, htail]; exact hy i.succ)
+ refine ⟨out, ?_, ho, ?_, ?_, ?_, fun j h₀ h₂ h₄ h₅ h₆ ↦
+ (frame' j h₀ h₂ h₄ h₅ h₆).trans (frame j h₀ h₂ h₄ h₅ h₆), hm'.trans hmem, hp'.trans hp⟩
+ · convert pre.append tail using 1
+ rw [← List.replicate_add]
+ congr 1
+ omega
+ · simpa [add_assoc, add_comm (1 : Word w)] using hleft'
+ · simpa [add_assoc, add_comm (1 : Word w)] using hright'
+ · have hx₀ : c.privateMem left = x 0 := by simpa using hx 0
+ have hy₀ : c.privateMem right = y 0 := by simpa using hy 0
+ rw [hm, mask, hleft, hright, hx₀, hy₀, Fin.forall_fin_succ, and_assoc]
+
+/-- The two exit instructions test the accumulated difference mask. Each input
+takes the same number of ticks, including an unused selector pattern or an
+empty sequence. Selector validity is checked by the anchor's table lookup. -/
+theorem compareTags {b u : ℕ} (enc : Word b ↪ Word w)
+ (hl : Linked M pc reg done) (test yes no : Fin p)
+ (hz : M.code done = .constant (reg 5) 0 test)
+ (hj : M.code test = .jumpEq (reg 4) (reg 5) yes no)
+ (x y : Fin u → Word b) (left right : Word w) (c : Config w p r) (hc : c.pc = pc 0)
+ (hleft : c.reg (reg 0) = left) (hend : c.reg (reg 1) = left + (u : Word w))
+ (hright : c.reg (reg 2) = right) (h1 : c.reg (reg 3) = 1) (hzero : c.reg (reg 4) = 0)
+ (hu : u < 2 ^ w) (hx : ∀ i : Fin u, c.privateMem (left + (i.val : Word w)) = enc (x i))
+ (hy : ∀ i : Fin u, c.privateMem (right + (i.val : Word w)) = enc (y i)) :
+ ∃ out, Prefix M c (List.replicate (7 * u + 3) .tick) out ∧
+ out.pc = (if ∀ i, x i = y i then yes else no) ∧
+ Frame reg c out ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ obtain ⟨mid, pre, hm, _, _, mask, frame, hmem, hper⟩ :=
+ compareArrays hl (enc ∘ x) (enc ∘ y) left right c hc hleft hend hright h1 hu hx hy
+ have he : mid.reg (reg 4) = 0 ↔ ∀ i, x i = y i := by
+ simpa [hzero, Function.comp_def] using mask
+ let q := mid.put test (reg 5) 0
+ let out := {q with pc := if ∀ i, x i = y i then yes else no}
+ have s₀ : M.program.step mid = .localStep q := by simp [Machine.program, hm, hz, Instr.run, q]
+ have s₁ : M.program.step q = .localStep out := by
+ change (M.code test).run M.publicData q = _
+ rw [hj]
+ simp [Instr.run, out, q, Config.put, he]
+ have tail : Prefix M mid (List.replicate 2 .tick) out := .tick s₀ (.tick s₁ (.nil _))
+ refine ⟨out, ?_, rfl, ?_, hmem, hper⟩
+ · convert pre.append tail using 1
+ rw [← List.replicate_add]
+ · intro j h₀ h₂ h₄ h₅ h₆
+ simpa [out, q, Config.put, Function.update_of_ne h₅] using frame j h₀ h₂ h₄ h₅ h₆
+
+end PairSimulation.MapConsistency
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapConstants.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapConstants.lean
new file mode 100644
index 0000000000..2a90a575d5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapConstants.lean
@@ -0,0 +1,215 @@
+import OAI.Computability.VPVNP.PairSimulationMapCallTable
+
+/-!
+# Width-independent public constants of a fixed motif entry
+
+A row compares actual endpoint digits with the natural coordinates of a
+fixed basis tuple. The selector codes, ordinal names, base widths and row
+coordinates form a finite table independent of the host word width. Casting
+this single table gives exactly the public words of the descriptor-to-map
+program at every fitting width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapConstants
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifDemandPadding MapLookup
+open BurstRAM.PrivateRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H') (z : B.grid.demands)
+ (j : J) {r k w t : ℕ}
+
+/-- Selectors are numbered once for the fixed base motif. -/
+noncomputable def selectorOrdinal : Selector B ≃ Fin (Fintype.card (Selector B)) :=
+ Fintype.equivFin _
+
+/-- Encode each fixed selector's ordinal injectively in a machine word when the word space is
+large enough for the selector table. -/
+noncomputable def selectorWord (h : Fintype.card (Selector B) ≤ 2 ^ w) :
+ Selector B ↪ BurstRAM.Word w := (selectorOrdinal B).toEmbedding.trans (Fin.castLEEmb h)
+
+open Classical in
+/-- Absent endpoints have value zero; the two directions have distinct keys. -/
+noncomputable def halfDigit {A : Type} (a b : A → J) (width : A → ℕ) (j : J)
+ (x : HalfBits a b width j) : Bool × A → ℕ
+ | (false, e) => if h : j = a e then (x.1 e h).val else 0
+ | (true, e) => if h : j = b e then (x.2 e h).val else 0
+
+private theorem widen_eq_cast {n : ℕ} (fits : n ≤ w) (x : Word n) :
+ MapLookup.widen fits x = (x.val : BurstRAM.Word w) := by
+ apply Fin.ext
+ exact (Nat.mod_eq_of_lt (x.isLt.trans_le (Nat.pow_le_pow_right (by decide) fits))).symm
+
+omit [Fintype J] in
+theorem halfKey_eq_digit {A : Type} (a b : A → J) (width : A → ℕ) (fits : ∀ e, width e ≤ w)
+ (j : J) (x : HalfBits a b width j) (f : Bool × A) :
+ MapLookup.halfKey a b width fits j x f = (halfDigit a b width j x f : BurstRAM.Word w) := by
+ obtain ⟨side, e⟩ := f
+ cases side with
+ | false =>
+ by_cases h : j = a e <;> simp [MapLookup.halfKey, halfDigit, h, widen_eq_cast]
+ | true =>
+ by_cases h : j = b e <;> simp [MapLookup.halfKey, halfDigit, h, widen_eq_cast]
+
+/-- The physical public constants indexed by code ports, dispatch ordinals,
+widths, endpoint comparison fields and the actual global parameter ordinal. -/
+noncomputable def rawConstants (ordinal : (parameterData B).Entry → Fin t) :
+ MapEntryTable.PublicPort B z j → ℕ
+ | .inl s => (selectorCode B s).val
+ | .inr (.inl s) => (selectorOrdinal B s).val
+ | .inr (.inr ⟨s, .inl g⟩) => Sum.elim (baseDemand B z) (basePayload B s) g
+ | .inr (.inr ⟨s, .inr (.inl (y, f))⟩) =>
+ Sum.elim (halfDigit src dst (baseDemand B z) j y.1)
+ (halfDigit G.src G.dst (basePayload B s) j y.2) f
+ | .inr (.inr ⟨s, .inr (.inr y)⟩) => (ordinal (lookup B z s j y.1 y.2)).val
+
+/-- These are the same words at every width supporting the base fields and
+the selector numbering. The choice of ordinals does not depend on width. -/
+theorem words_eq_cast (ordinal : (parameterData B).Entry → Fin t) (fb : B.selectorBits ≤ w)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (hs : Fintype.card (Selector B) ≤ 2 ^ w) (a : MapEntryTable.PublicPort B z j) :
+ MapEntryTable.Allocation.words fb fd fs (selectorWord B hs)
+ (fun e ↦ ((ordinal e).val : BurstRAM.Word w)) a =
+ (rawConstants B z j ordinal a : BurstRAM.Word w) := by
+ rcases a with s | (s | ⟨s, g | (⟨y, f⟩ | y)⟩)
+ · exact widen_eq_cast fb (selectorCode B s)
+ · apply Fin.ext
+ exact (Nat.mod_eq_of_lt ((selectorOrdinal B s).isLt.trans_le hs)).symm
+ · rfl
+ · cases f with
+ | inl e => exact halfKey_eq_digit src dst (baseDemand B z) fd j y.1 e
+ | inr e => exact halfKey_eq_digit G.src G.dst (basePayload B s) (fs s) j y.2 e
+ · rfl
+
+variable {B z j} (A : MapEntryTable.Allocation B z j r k)
+
+open Classical in
+/-- The numerical public bank used when inlining the whole call template.
+All enclosing positions outside the map allocation carry zero. -/
+noncomputable def rawBank (ordinal : (parameterData B).Entry → Fin t) (i : Fin k) : ℕ :=
+ if h : ∃ a, A.pub a = i then rawConstants B z j ordinal h.choose else 0
+
+theorem rawBank_at (ordinal : (parameterData B).Entry → Fin t)
+ (a : MapEntryTable.PublicPort B z j) :
+ rawBank A ordinal (A.pub a) = rawConstants B z j ordinal a := by
+ classical
+ have h : ∃ c, A.pub c = A.pub a := ⟨a, rfl⟩
+ rw [rawBank, dite_eq_left h, A.pub.injective h.choose_spec]
+
+/-- At every public port, including unused enclosing ports, the installed
+word table is the cast of one natural array. -/
+theorem installed_eq_cast (ordinal : (parameterData B).Entry → Fin t) (fb : B.selectorBits ≤ w)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (hs : Fintype.card (Selector B) ≤ 2 ^ w) :
+ A.install (MapEntryTable.Allocation.words fb fd fs (selectorWord B hs)
+ (fun e ↦ ((ordinal e).val : BurstRAM.Word w))) (fun _ ↦ 0) =
+ fun i ↦ (rawBank A ordinal i : BurstRAM.Word w) := by
+ classical
+ funext i
+ by_cases h : ∃ a, A.pub a = i
+ · obtain ⟨a, rfl⟩ := h
+ rw [A.install_at, rawBank_at]
+ exact words_eq_cast ..
+ · simp [MapEntryTable.Allocation.install, rawBank, h]
+
+variable (B)
+
+/-- A fixed bit-width threshold, uniform across all parties and grid
+points. It also accommodates the whole selector enumeration. -/
+noncomputable def widthThreshold : ℕ :=
+ B.selectorBits + (∑ z : B.grid.demands, ∑ e, baseDemand B z e) +
+ (∑ s : Selector B, ∑ e, basePayload B s e) + Fintype.card (Selector B)
+
+theorem fits_of_threshold (hw : widthThreshold B ≤ w) :
+ B.selectorBits ≤ w ∧ (∀ z e, baseDemand B z e ≤ w) ∧ (∀ s e, basePayload B s e ≤ w) ∧
+ Fintype.card (Selector B) ≤ 2 ^ w := by
+ dsimp only [widthThreshold] at hw
+ refine ⟨by omega, fun z e ↦ ?_, fun s e ↦ ?_, ?_⟩
+ · have he := Finset.single_le_sum (fun i _ ↦ Nat.zero_le (baseDemand B z i)) (Finset.mem_univ e)
+ have hz := Finset.single_le_sum (fun z _ ↦ Nat.zero_le (∑ i, baseDemand B z i))
+ (Finset.mem_univ z)
+ omega
+ · have he := Finset.single_le_sum (fun i _ ↦ Nat.zero_le (basePayload B s i)) (Finset.mem_univ e)
+ have hs := Finset.single_le_sum (fun s _ ↦ Nat.zero_le (∑ i, basePayload B s i))
+ (Finset.mem_univ s)
+ omega
+ · exact (show Fintype.card (Selector B) ≤ w by omega).trans Nat.lt_two_pow_self.le
+
+/-- The fixed threshold is eventually met by the live RAM word format. -/
+theorem eventually_width (exponent : ℕ) (hb : 1 ≤ exponent) :
+ ∀ᶠ n : ℕ in Filter.atTop, widthThreshold B ≤ CursorBounds.wordBits exponent n := by
+ filter_upwards [Filter.eventually_ge_atTop (2 ^ widthThreshold B)] with n hn
+ have hlog := (Nat.le_log2 (by have := Nat.two_pow_pos (widthThreshold B); omega : n ≠ 0)).mpr hn
+ exact (hlog.trans (BurstRAM.log2_le_addressWidth hb n)).trans
+ ((Nat.le_add_right (BurstRAM.addressWidth exponent n) 10).trans
+ (Nat.le_self_pow (by decide : 4 ≠ 0) _))
+
+section Call
+
+variable [DecidableEq J] {B} (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : MapCallTable.Layout B (demandGrid B hp I.demand) I.party r k)
+ (ord : (parameterData B).Entry → Fin t)
+
+/-- The source template of the public-bank lowering, using only natural
+constants fixed before the host width and the private descriptor are chosen. -/
+noncomputable def source {z : B.grid.demands} {j : J}
+ (L : MapCallTable.Layout B z j r k) (ord : (parameterData B).Entry → Fin t) :
+ Machine w (Nat.card L.Address) r k :=
+ L.template.instantiate w (fun i ↦ (rawBank L.core ord i : BurstRAM.Word w))
+
+/-- The raw constant bank runs the complete descriptor reader, port-directory
+builder, selector decoder, row scan, width checks and histogram updates. -/
+theorem source_run_framed (hw : widthThreshold B ≤ w) :
+ let loc := L.corePC L.locations
+ let P := L.core.program loc
+ let M := source (w := w) L ord
+ let demand := MotifEntry.demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ MotifEntry.inputBits) I.supplyBits
+ ∀ (X : MapEntry.Program.Workspace P I.demand I.payload demand supply t w)
+ (c : Config w (Nat.card L.Address) r), c.pc = M.entry →
+ MapCallSetup.Input L.core L.args loc X L.ptr c →
+ (∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ P.RunsFramed M c X.hist (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand))
+ (MapCallSetup.Outside L.core loc X)
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord)) := by
+ obtain ⟨fb, fd, fs, hs⟩ := fits_of_threshold B hw
+ have run := MapCallTable.Layout.run_entryInput_framed hp I L fb (fd _) fs (selectorWord B hs) ord
+ rw [installed_eq_cast L.core ord fb (fd _) fs hs] at run
+ exact run
+
+/-- The raw constant bank runs the complete descriptor reader, port-directory
+builder, selector decoder, row scan, width checks and histogram updates. -/
+theorem source_run (hw : widthThreshold B ≤ w) :
+ let loc := L.corePC L.locations
+ let P := L.core.program loc
+ let M := source (w := w) L ord
+ let demand := MotifEntry.demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ MotifEntry.inputBits) I.supplyBits
+ ∀ (X : MapEntry.Program.Workspace P I.demand I.payload demand supply t w)
+ (c : Config w (Nat.card L.Address) r), c.pc = M.entry →
+ MapCallSetup.Input L.core L.args loc X L.ptr c →
+ (∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ P.Runs M c X.hist (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand))
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord)) := by
+ intro loc P M demand supply X c pc input apart
+ exact (source_run_framed hp I L ord hw X c pc input apart).forget P
+
+end Call
+
+end PairSimulation.MapConstants
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapDirectoryInit.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapDirectoryInit.lean
new file mode 100644
index 0000000000..e4de463f89
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapDirectoryInit.lean
@@ -0,0 +1,177 @@
+import OAI.Computability.VPVNP.PairSimulationMapEntryTable
+
+/-!
+# Initializing the grouped map's incident selector directory
+
+The private directory contains one word for each incident half-wire, in the
+order consumed by the selector scanner. A fixed three-instruction block adds
+the edge's payload width to that half-wire's bit base, stores the pointer,
+and advances the cursor. A self-loop therefore supplies two directory rows.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapDirectoryInit
+
+open MotifSelector MotifBlocks MotifConversion MotifGrid MapPortAgreement
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k p w : ℕ} (A : MapEntryTable.Allocation B z j r k)
+
+/-- The source and target ports refer to different row-bank base registers. -/
+def portField : Port G j → MapLookup.LabelField D E
+ | .inl e => .inr (false, e.val)
+ | .inr e => .inr (true, e.val)
+
+/-- Index of an incident supply port in the order scanned by the directory initializer. A
+self-loop contributes one source row and one target row. -/
+abbrev Row := Fin (ports G j A.edgeOrder).length
+/-- Directory initialization addresses, consisting of a cursor setup followed by three
+instructions per incident port to compute, store, and advance. -/
+abbrev Address := Unit ⊕ Row A × Fin 3
+
+variable (scratch : Fin 2 ↪ Fin r) (place : Address A → Fin p) (done : Fin p)
+
+private def rowPC (n : ℕ) : Fin p :=
+ if h : n < (ports G j A.edgeOrder).length then place (.inr (⟨n, h⟩, 0)) else done
+
+/-- Relocatable copy, add, private store and increment instructions. -/
+def text : Address A → Instr 2 p r k
+ | .inl _ => .copy (scratch 0) (A.selectors.scanReg 7) (rowPC A place done 0)
+ | .inr (i, t) =>
+ let port := (ports G j A.edgeOrder).get i
+ ![.binary .add (scratch 1) (A.bank.rowReg (.base (portField port)))
+ (A.expected (MapResidentAgreement.edge port)) (place (.inr (i, 1))),
+ .storePrivate (scratch 0) (scratch 1) (place (.inr (i, 2))),
+ .binary .add (scratch 0) (scratch 0) (A.selectors.scanReg 3)
+ (rowPC A place done (i.val + 1))] t
+
+private abbrev slot (c : Config w p r) (i : ℕ) : BurstRAM.Word w :=
+ c.reg (A.selectors.scanReg 7) + (i : BurstRAM.Word w)
+
+private abbrev pointer (c : Config w p r) (i : Row A) : BurstRAM.Word w :=
+ let port := (ports G j A.edgeOrder).get i
+ c.reg (A.bank.rowReg (.base (portField port))) +
+ c.reg (A.expected (MapResidentAgreement.edge port))
+
+private structure After (c : Config w p r) (n : ℕ) (out : Config w p r) : Prop where
+ pc : out.pc = rowPC A place done n
+ cursor : out.reg (scratch 0) = slot A c n
+ frame : ∀ a, a ≠ scratch 0 → a ≠ scratch 1 → out.reg a = c.reg a
+ persistent : out.persistent = c.persistent
+ written : ∀ i : Row A, i.val < n → out.privateMem (slot A c i.val) = pointer A c i
+ outside : ∀ a, (∀ i : Row A, i.val < n → a ≠ slot A c i.val) → out.privateMem a = c.privateMem a
+
+variable (M : Machine w p r k)
+ (link : ∀ a, M.code (place a) = (text A scratch place done a).resize w)
+ (apart : ∀ a i, A.reg a ≠ scratch i)
+
+private theorem slot_injective (c : Config w p r) (fit : (ports G j A.edgeOrder).length ≤ 2 ^ w)
+ (i t : Row A) (eq : slot A c i.val = slot A c t.val) : i = t := by
+ have hw : (i.val : BurstRAM.Word w) = (t.val : BurstRAM.Word w) := add_left_cancel eq
+ have hv := congrArg Fin.val hw
+ change i.val % (2 ^ w) = t.val % (2 ^ w) at hv
+ exact Fin.ext (by simpa only [Nat.mod_eq_of_lt (i.isLt.trans_le fit),
+ Nat.mod_eq_of_lt (t.isLt.trans_le fit)] using hv)
+
+include link apart
+
+private theorem step_row (c mid : Config w p r) (i : Row A)
+ (st : After A scratch place done c i.val mid) (one : c.reg (A.selectors.scanReg 3) = 1)
+ (fit : (ports G j A.edgeOrder).length ≤ 2 ^ w) :
+ ∃ out, Prefix M mid (List.replicate 3 .tick) out ∧
+ After A scratch place done c (i.val + 1) out := by
+ let sum := mid.put (place (.inr (i, 1))) (scratch 1) (pointer A c i)
+ let store := sum.store (place (.inr (i, 2))) (slot A c i.val) (pointer A c i)
+ let out := store.put (rowPC A place done (i.val + 1)) (scratch 0) (slot A c (i.val + 1))
+ have start : mid.pc = place (.inr (i, 0)) := by simpa [rowPC, i.isLt] using st.pc
+ have keep (a) : mid.reg (A.reg a) = c.reg (A.reg a) := st.frame _ (apart _ _) (apart _ _)
+ have sa : M.program.step mid = .localStep sum := by
+ change (M.code mid.pc).run M.publicData mid = _
+ rw [start, link]
+ change BurstRAM.CallAction.localStep (mid.put _ _ (mid.reg (A.reg _) + mid.reg (A.reg _))) = _
+ rw [keep, keep]
+ rfl
+ have ss : M.program.step sum = .localStep store := by
+ change (M.code (place (.inr (i, 1)))).run M.publicData sum = _
+ rw [link]
+ change BurstRAM.CallAction.localStep
+ (sum.store _ (sum.reg (scratch 0)) (sum.reg (scratch 1))) = _
+ simp [store, sum, Config.put, st.cursor]
+ have si : M.program.step store = .localStep out := by
+ change (M.code (place (.inr (i, 2)))).run M.publicData store = _
+ rw [link]
+ change BurstRAM.CallAction.localStep (store.put _ _ (store.reg (scratch 0) +
+ store.reg (A.selectors.scanReg 3))) = _
+ have hreg : A.selectors.scanReg 3 ≠ scratch 1 := apart _ _
+ have hone : mid.reg (A.selectors.scanReg 3) = 1 := (keep _).trans one
+ simp [out, store, sum, Config.store, Config.put,
+ Function.update_of_ne hreg, st.cursor, hone, slot, add_assoc]
+ refine ⟨out, .tick sa (.tick ss (.tick si (.nil _))), rfl, Config.put_same .., ?_,
+ st.persistent, ?_, ?_⟩
+ · intro q h0 h1
+ simpa [out, store, sum, Config.put, Config.store, Function.update_of_ne h0,
+ Function.update_of_ne h1]
+ using st.frame q h0 h1
+ · intro t ht
+ by_cases he : t = i
+ · subst t
+ exact Config.store_same sum (place (.inr (i, 2))) _ _
+ · have hv : t.val ≠ i.val := fun h => he (Fin.ext h)
+ have hslot : slot A c t.val ≠ slot A c i.val := fun h => he (slot_injective A c fit t i h)
+ exact (Config.store_other sum (place (.inr (i, 2))) _ _ (pointer A c i) hslot).trans
+ (st.written t (by omega))
+ · intro a ha
+ exact (Config.store_other sum (place (.inr (i, 2))) _ _ (pointer A c i)
+ (ha i (Nat.lt_succ_self _))).trans
+ (st.outside a fun t ht => ha t (Nat.lt_succ_of_lt ht))
+
+/-- Starting with arbitrary private memory, the native instructions write every
+selector-start pointer and transfer control to the scanner. The addresses may
+wrap around the word modulus, as long as the directory has at most that many rows. -/
+theorem native (c : Config w p r) (start : c.pc = place (.inl ()))
+ (one : c.reg (A.selectors.scanReg 3) = 1) (fit : (ports G j A.edgeOrder).length ≤ 2 ^ w) :
+ ∃ out, Prefix M c (List.replicate (1 + 3 * (ports G j A.edgeOrder).length) .tick) out ∧
+ out.pc = done ∧ out.persistent = c.persistent ∧
+ (∀ a, a ≠ scratch 0 → a ≠ scratch 1 → out.reg a = c.reg a) ∧
+ (∀ i : Row A, out.privateMem (c.reg (A.selectors.scanReg 7) + (i.val : BurstRAM.Word w)) =
+ let t := (ports G j A.edgeOrder).get i
+ c.reg (A.bank.rowReg (.base (portField t))) +
+ c.reg (A.expected (MapResidentAgreement.edge t))) ∧
+ ∀ a, (∀ i : Row A, a ≠ c.reg (A.selectors.scanReg 7) + (i.val : BurstRAM.Word w)) →
+ out.privateMem a = c.privateMem a := by
+ have run (n : ℕ) (hn : n ≤ (ports G j A.edgeOrder).length) : ∃ mid,
+ Prefix M c (List.replicate (1 + 3 * n) .tick) mid ∧ After A scratch place done c n mid := by
+ induction n with
+ | zero =>
+ let mid := c.put (rowPC A place done 0) (scratch 0) (c.reg (A.selectors.scanReg 7))
+ have sc : M.program.step c = .localStep mid := by
+ change (M.code c.pc).run M.publicData c = _
+ rw [start, link]
+ rfl
+ refine ⟨mid, .tick sc (.nil _), rfl, ?_, ?_, rfl, fun i hi ↦ (Nat.not_lt_zero _ hi).elim,
+ fun _ _ ↦ rfl⟩
+ · simp [mid, slot]
+ · intro a h _
+ exact Function.update_of_ne h ..
+ | succ n ih =>
+ let i : Row A := ⟨n, hn⟩
+ obtain ⟨mid, pre, st⟩ := ih (by omega)
+ obtain ⟨out, tail, hout⟩ := step_row A scratch place done M link apart c mid i st one fit
+ refine ⟨out, ?_, hout⟩
+ simpa only [← List.replicate_add, Nat.mul_succ, Nat.add_assoc] using pre.append tail
+ obtain ⟨out, path, st⟩ := run _ le_rfl
+ exact ⟨out, path, by simpa [rowPC] using st.pc, st.persistent, st.frame,
+ fun i ↦ st.written i i.isLt, fun a ha ↦ st.outside a fun i _ ↦ ha i⟩
+
+end PairSimulation.MapDirectoryInit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapDriver.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapDriver.lean
new file mode 100644
index 0000000000..c529de4924
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapDriver.lean
@@ -0,0 +1,383 @@
+import OAI.Computability.VPVNP.PairSimulationAnchorDecode
+import OAI.Computability.VPVNP.PairSimulationMapStream
+
+/-!
+# Native dispatch and repetition of the selected map rows
+
+Each pass reads the next private selector ordinal and compares it with the
+fixed selector ports. A match jumps directly to the corresponding row's
+first instruction. All row subroutines return to the same label store.
+After the last copy the driver transfers control to the full-width test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapDriver
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {S : Type*} {w p r k u : ℕ}
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+
+private theorem val_word {n : ℕ} (h : n < 2 ^ w) : (word w n).val = n := Nat.mod_eq_of_lt h
+
+/-- Registers hold the selector cursor and end, label cursor, one, loaded
+ordinal, comparison temporary, and the label returned by the selected row. -/
+structure Program (S : Type*) (p r k : ℕ) where
+ /-- Selectors in the order the driver tests when dispatching a decoded ordinal. -/
+ selectors : List S
+ /-- Public-word position holding the dispatch ordinal for each selector. -/
+ port : S → Fin k
+ /-- Place the selector cursor and end, label cursor, increment, loaded ordinal, comparison
+ temporary, and returned label in seven distinct registers. -/
+ reg : Fin 7 ↪ Fin r
+ /-- Program counters for the five outer-loop instructions that test for completion, load a
+ selector, store a label, and advance both cursors. -/
+ pc : Fin 5 → Fin p
+ /-- Instruction addresses for one selector's dispatch pair. The false branch loads its public
+ ordinal and the true branch compares that ordinal with the private one. -/
+ comparePC : S → Bool → Fin p
+ /-- Entry address of the row evaluator chosen by a successful selector comparison. -/
+ rowPC : S → Fin p
+ /-- Continuation that checks final widths after the driver consumes the selector array. -/
+ checkWidths : Fin p
+ /-- Rejecting continuation taken when the comparison chain exhausts all selectors. -/
+ bad : Fin p
+
+namespace Program
+
+variable (P : Program S p r k)
+
+/-- An exhausted comparison chain jumps to the rejecting exit. -/
+def first : List S → Fin p
+ | [] => P.bad
+ | x :: _ => P.comparePC x false
+
+/-- The five outer-loop instructions for checking the selector cursor, loading the next
+ordinal, storing the row's returned label, and incrementing the two cursors. -/
+def instruction : Fin 5 → Instr w p r k :=
+ ![.jumpEq (P.reg 0) (P.reg 1) P.checkWidths (P.pc 1),
+ .loadPrivate (P.reg 4) (P.reg 0) (P.first P.selectors),
+ .storePrivate (P.reg 2) (P.reg 6) (P.pc 3),
+ .binary .add (P.reg 0) (P.reg 0) (P.reg 3) (P.pc 4),
+ .binary .add (P.reg 2) (P.reg 2) (P.reg 3) (P.pc 0)]
+
+theorem resize_instruction (i : Fin 5) :
+ (P.instruction (w := 1) i).resize w = P.instruction i := by fin_cases i <;> rfl
+
+/-- Two actual opcodes per fixed selector, with an independent hit target. -/
+def dispatch (M : Machine w p r k) : List S → Prop
+ | [] => True
+ | s :: ss =>
+ M.code (P.comparePC s false) = .publicWord (P.reg 5) (P.port s) (P.comparePC s true) ∧
+ M.code (P.comparePC s true) =
+ .jumpEq (P.reg 4) (P.reg 5) (P.rowPC s) (P.first ss) ∧ dispatch M ss
+
+/-- The machine implements both the five outer driver instructions and the ordered
+load-and-compare dispatch for every selector in the table. -/
+structure Linked (M : Machine w p r k) : Prop where
+ outer : ∀ i, M.code (P.pc i) = P.instruction i
+ table : P.dispatch M P.selectors
+
+variable {P} {M : Machine w p r k}
+
+open Classical in
+/-- Two instructions per candidate through the first match, in table order. -/
+noncomputable def dispatchSteps : List S → S → ℕ
+ | [], _ => 0
+ | a :: as, s => if s = a then 2 else 2 + dispatchSteps as s
+
+/-- Successful dispatch consumes at most two instructions per selector.
+The selected row receives the loaded ordinal and the same private memory. -/
+theorem dispatch_hit_exact (ss : List S) (hl : P.dispatch M ss)
+ (inj : Function.Injective (M.publicData ∘ P.port)) (s : S) (member : s ∈ ss)
+ (c : Config w p r) (hc : c.pc = P.first ss) (hs : c.reg (P.reg 4) = M.publicData (P.port s)) :
+ ∃ n d, n ≤ 2 * ss.length ∧ n = dispatchSteps ss s ∧
+ Prefix M c (List.replicate n .tick) d ∧ d.pc = P.rowPC s ∧
+ (∀ j, j ≠ P.reg 5 → d.reg j = c.reg j) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ induction ss generalizing c with
+ | nil => simp at member
+ | cons x xs ih =>
+ let mid := c.put (P.comparePC x true) (P.reg 5) (M.publicData (P.port x))
+ have load : M.program.step c = .localStep mid := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hc, first, hl.1]
+ rfl
+ have test : M.program.step mid = .localStep {mid with pc :=
+ (if M.publicData (P.port s) = M.publicData (P.port x) then P.rowPC x else P.first xs)} := by
+ rw [show M.program.step mid = (M.code mid.pc).run M.publicData mid from rfl,
+ show mid.pc = P.comparePC x true from rfl, hl.2.1]
+ change CallAction.localStep {mid with pc :=
+ (if mid.reg (P.reg 4) = mid.reg (P.reg 5) then P.rowPC x else P.first xs)} = _
+ simp [mid, Config.put, hs]
+ have keep (j : Fin r) (hj : j ≠ P.reg 5) : mid.reg j = c.reg j := by
+ simp [mid, Config.put, Function.update_of_ne hj]
+ by_cases h : s = x
+ · subst x
+ rw [ite_eq_left rfl] at test
+ exact ⟨2, _, by simp, by simp [dispatchSteps], .tick load (.tick test (.nil _)),
+ rfl, keep, rfl, rfl⟩
+ · have ne : M.publicData (P.port s) ≠ M.publicData (P.port x) := inj.ne h
+ rw [ite_eq_right ne] at test
+ obtain ⟨n, d, bound, ticks, pre, pc, other, mem, per⟩ := ih hl.2.2
+ ((List.mem_cons.mp member).resolve_left h) {mid with pc := P.first xs} rfl
+ ((keep _ (by simp)).trans hs)
+ refine ⟨2 + n, d, by simp; omega, by simp [dispatchSteps, h, ticks], ?_, pc,
+ fun j hj ↦ (other j hj).trans (keep j hj), mem, per⟩
+ rw [List.replicate_add]
+ exact .tick load (.tick test pre)
+
+/-- Successful dispatch consumes at most two instructions per selector.
+The selected row receives the loaded ordinal and the same private memory. -/
+theorem dispatch_hit (ss : List S) (hl : P.dispatch M ss)
+ (inj : Function.Injective (M.publicData ∘ P.port)) (s : S) (member : s ∈ ss)
+ (c : Config w p r) (hc : c.pc = P.first ss) (hs : c.reg (P.reg 4) = M.publicData (P.port s)) :
+ ∃ n d, n ≤ 2 * ss.length ∧ Prefix M c (List.replicate n .tick) d ∧ d.pc = P.rowPC s ∧
+ (∀ j, j ≠ P.reg 5 → d.reg j = c.reg j) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨n, d, bound, _, rest⟩ := dispatch_hit_exact ss hl inj s member c hc hs
+ exact ⟨n, d, bound, rest⟩
+
+/-- Controller instructions change four registers and may store in the
+label array. A row invariant stable under these changes can include all
+resident input bits, base addresses, and current demand and supply offsets. -/
+def Stable (P : Program S p r k) (inv : ℕ → Config w p r → Prop) (dest u : ℕ) : Prop :=
+ ∀ n c d, inv n c →
+ (∀ j, j ≠ P.reg 0 → j ≠ P.reg 2 → j ≠ P.reg 4 → j ≠ P.reg 5 → d.reg j = c.reg j) →
+ (∀ a : Word w, a.val < dest ∨ dest + u ≤ a.val → d.privateMem a = c.privateMem a) →
+ d.persistent = c.persistent → inv n d
+
+/-- One row contract is discharged by the selected row's own native prefix.
+It advances the local offsets and leaves the driver cursor words intact. -/
+def RowRuns (P : Program S p r k) (M : Machine w p r k) (θ : Fin u → S)
+ (labelWord : Fin u → Word w) (inv : ℕ → Config w p r → Prop) (cap : ℕ) : Prop :=
+ ∀ (i : Fin u) c, c.pc = P.rowPC (θ i) → inv i.val c →
+ ∃ n d, n ≤ cap ∧ Prefix M c (List.replicate n .tick) d ∧ d.pc = P.pc 2 ∧
+ d.reg (P.reg 6) = labelWord i ∧ inv (i.val + 1) d ∧
+ (∀ j : Fin 4, d.reg (P.reg (Fin.castLE (by decide) j)) =
+ c.reg (P.reg (Fin.castLE (by decide) j))) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent
+
+/-- A row prefix carrying a further predicate on its actual instruction count. -/
+def RowRunsWith (P : Program S p r k) (M : Machine w p r k) (θ : Fin u → S)
+ (labelWord : Fin u → Word w) (inv : ℕ → Config w p r → Prop) (cap : ℕ)
+ (clock : Fin u → ℕ → Prop) : Prop :=
+ ∀ (i : Fin u) c, c.pc = P.rowPC (θ i) → inv i.val c →
+ ∃ n d, n ≤ cap ∧ clock i n ∧ Prefix M c (List.replicate n .tick) d ∧ d.pc = P.pc 2 ∧
+ d.reg (P.reg 6) = labelWord i ∧ inv (i.val + 1) d ∧
+ (∀ j : Fin 4, d.reg (P.reg (Fin.castLE (by decide) j)) =
+ c.reg (P.reg (Fin.castLE (by decide) j))) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent
+
+/-- A ready loop boundary includes all completed labels and all resident
+selectors. Unused cells of the output array may hold arbitrary values. -/
+structure Ready (P : Program S p r k) (M : Machine w p r k) (θ : Fin u → S)
+ (labelWord : Fin u → Word w) (src dest n : ℕ) (c : Config w p r) : Prop where
+ pc : c.pc = P.pc 0
+ source : c.reg (P.reg 0) = word w (src + n)
+ stop : c.reg (P.reg 1) = word w (src + u)
+ target : c.reg (P.reg 2) = word w (dest + n)
+ one : c.reg (P.reg 3) = 1
+ selectors : ∀ i : Fin u, c.privateMem (word w (src + i.val)) = M.publicData (P.port (θ i))
+ labels : ∀ i : Fin u, i.val < n → c.privateMem (word w (dest + i.val)) = labelWord i
+
+private theorem step_at (link : P.Linked M) (i : Fin 5) {c : Config w p r} (hc : c.pc = P.pc i) :
+ M.program.step c = (P.instruction i).run M.publicData c := by
+ simp [Machine.program, hc, link.outer i]
+
+/-- Budget for one loop test, ordinal load, fixed dispatch, selected row,
+label store and two cursor increments. -/
+def visitCap (P : Program S p r k) (rowCap : ℕ) := 5 + 2 * P.selectors.length + rowCap
+
+/-- The same path returns the label and charges exactly the row's own ticks plus
+the comparison-chain ticks and five loop instructions. -/
+theorem visitWith (link : P.Linked M) (inj : Function.Injective (M.publicData ∘ P.port))
+ (θ : Fin u → S) (member : ∀ i, θ i ∈ P.selectors) (labelWord : Fin u → Word w)
+ (inv : ℕ → Config w p r → Prop) (src dest cap : ℕ) (stable : P.Stable inv dest u)
+ (clock : Fin u → ℕ → Prop) (row : P.RowRunsWith M θ labelWord inv cap clock)
+ (hs : src + u < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : src + u ≤ dest ∨ dest + u ≤ src) (i : Fin u) (c : Config w p r)
+ (ready : P.Ready M θ labelWord src dest i.val c) (hi : inv i.val c) :
+ ∃ n d, n ≤ P.visitCap cap ∧
+ (∃ t, clock i t ∧ n = 5 + dispatchSteps P.selectors (θ i) + t) ∧
+ Prefix M c (List.replicate n .tick) d ∧
+ P.Ready M θ labelWord src dest (i.val + 1) d ∧ inv (i.val + 1) d ∧
+ (∀ a : Word w, a ≠ word w (dest + i.val) → d.privateMem a = c.privateMem a) ∧
+ d.persistent = c.persistent := by
+ have hit := i.isLt
+ have ne : c.reg (P.reg 0) ≠ c.reg (P.reg 1) := by
+ rw [ready.source, ready.stop]
+ intro he
+ have hv := congrArg Fin.val he
+ rw [val_word (by omega : src + i.val < 2 ^ w), val_word hs] at hv
+ omega
+ let c₁ := {c with pc := P.pc 1}
+ let c₂ := c₁.put (P.first P.selectors) (P.reg 4) (M.publicData (P.port (θ i)))
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step_at link 0 ready.pc]
+ simp [instruction, Instr.run, ne, c₁]
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at link 1 rfl]
+ change CallAction.localStep (c₁.put _ _ (c.privateMem (c.reg (P.reg 0)))) = _
+ rw [ready.source, ready.selectors i]
+ obtain ⟨a, selected, ha, dispatchTicks, dispatchRun, selectedPC, other, sm, sp⟩ :=
+ dispatch_hit_exact P.selectors link.table inj (θ i) (member i) c₂ rfl (by simp [c₂])
+ have keep (j : Fin r) (h4 : j ≠ P.reg 4) (h5 : j ≠ P.reg 5) : selected.reg j = c.reg j :=
+ (other j h5).trans (by simp [c₂, c₁, Config.put, Function.update_of_ne h4])
+ have si : inv i.val selected :=
+ stable _ c selected hi (fun j _ _ h4 h5 ↦ keep j h4 h5) (fun j _ ↦ congrFun sm j) sp
+ obtain ⟨t, returned, bound, rowTicks, run, hr, value, next, controls, rm, rp⟩ :=
+ row i selected selectedPC si
+ have ctrl (j : Fin 4) : returned.reg (P.reg (Fin.castLE (by decide) j)) =
+ c.reg (P.reg (Fin.castLE (by decide) j)) := by
+ apply (controls j).trans
+ apply keep <;> apply P.reg.injective.ne <;> intro h <;>
+ have he := congrArg Fin.val h <;> change j.val = _ at he <;> have := j.isLt <;> omega
+ have srcReg : returned.reg (P.reg 0) = word w (src + i.val) := (ctrl 0).trans ready.source
+ have dstReg : returned.reg (P.reg 2) = word w (dest + i.val) := (ctrl 2).trans ready.target
+ have one : returned.reg (P.reg 3) = 1 := (ctrl 3).trans ready.one
+ let stored := returned.store (P.pc 3) (word w (dest + i.val)) (labelWord i)
+ let advanced := stored.put (P.pc 4) (P.reg 0) (word w (src + (i.val + 1)))
+ let d := advanced.put (P.pc 0) (P.reg 2) (word w (dest + (i.val + 1)))
+ have s₂ : M.program.step returned = .localStep stored := by
+ rw [step_at link 2 hr]
+ change CallAction.localStep (returned.store _ (returned.reg (P.reg 2))
+ (returned.reg (P.reg 6))) = _
+ rw [dstReg, value]
+ have s₃ : M.program.step stored = .localStep advanced := by
+ rw [step_at link 3 rfl]
+ change CallAction.localStep
+ (stored.put _ _ (returned.reg (P.reg 0) + returned.reg (P.reg 3))) = _
+ simp [advanced, srcReg, one, word, add_assoc]
+ have s₄ : M.program.step advanced = .localStep d := by
+ rw [step_at link 4 rfl]
+ change CallAction.localStep (advanced.put _ _
+ (advanced.reg (P.reg 2) + advanced.reg (P.reg 3))) = _
+ simp [d, advanced, stored, Config.put, Config.store, dstReg, one, word, add_assoc]
+ have tail : Prefix M returned (List.replicate 3 .tick) d :=
+ .tick s₂ (.tick s₃ (.tick s₄ (.nil _)))
+ have keep' (j : Fin r) (h0 : j ≠ P.reg 0) (h2 : j ≠ P.reg 2) : d.reg j = returned.reg j := by
+ simp [d, advanced, stored, Config.put, Config.store, Function.update_of_ne h0,
+ Function.update_of_ne h2]
+ have unchanged (j : Word w) (h : j ≠ word w (dest + i.val)) :
+ d.privateMem j = returned.privateMem j :=
+ Config.store_other returned (P.pc 3) (word w (dest + i.val)) j (labelWord i) h
+ have away (j : Word w) (h : j ≠ word w (dest + i.val)) : d.privateMem j = c.privateMem j :=
+ (unchanged j h).trans ((congrFun rm j).trans (congrFun sm j))
+ have exactDest := val_word (by omega : dest + i.val < 2 ^ w)
+ refine ⟨2 + a + t + 3, d, by unfold visitCap; omega, ⟨t, rowTicks, by omega⟩,
+ ?_, ?_, ?_, away, rp.trans sp⟩
+ · simp only [List.replicate_add]
+ exact ((Prefix.tick s₀ (.tick s₁ dispatchRun)).append run).append tail
+ · refine ⟨rfl, by simp [d, advanced, Config.put],
+ (keep' _ (by simp) (by simp)).trans ((ctrl 1).trans ready.stop),
+ by simp [d], (keep' _ (by simp) (by simp)).trans one, ?_, ?_⟩
+ · intro j
+ have hv := j.isLt
+ apply (away _ ?_).trans (ready.selectors j)
+ intro h
+ have hh := congrArg Fin.val h
+ rw [val_word (by omega : src + j.val < 2 ^ w), exactDest] at hh
+ omega
+ · intro j hj
+ by_cases he : j = i
+ · subst j; exact Config.store_same returned (P.pc 3) _ _
+ · apply (away _ ?_).trans (ready.labels j (by have h := Fin.val_ne_of_ne he; omega))
+ intro h
+ have hh := congrArg Fin.val h
+ rw [val_word (by have := j.isLt; omega : dest + j.val < 2 ^ w), exactDest] at hh
+ exact he (Fin.ext (Nat.add_left_cancel hh))
+ · refine stable _ returned d next (fun j h0 h2 _ _ ↦ keep' j h0 h2) (fun j hj ↦ ?_) rfl
+ apply unchanged
+ intro he
+ have hh := congrArg Fin.val he
+ rw [exactDest] at hh
+ omega
+
+private theorem visit (link : P.Linked M) (inj : Function.Injective (M.publicData ∘ P.port))
+ (θ : Fin u → S) (member : ∀ i, θ i ∈ P.selectors) (labelWord : Fin u → Word w)
+ (inv : ℕ → Config w p r → Prop) (src dest cap : ℕ) (stable : P.Stable inv dest u)
+ (row : P.RowRuns M θ labelWord inv cap) (hs : src + u < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : src + u ≤ dest ∨ dest + u ≤ src) (i : Fin u) (c : Config w p r)
+ (ready : P.Ready M θ labelWord src dest i.val c) (hi : inv i.val c) :
+ ∃ n d, n ≤ P.visitCap cap ∧ Prefix M c (List.replicate n .tick) d ∧
+ P.Ready M θ labelWord src dest (i.val + 1) d ∧ inv (i.val + 1) d ∧
+ (∀ a : Word w, a ≠ word w (dest + i.val) → d.privateMem a = c.privateMem a) ∧
+ d.persistent = c.persistent := by
+ have r : P.RowRunsWith M θ labelWord inv cap (fun _ _ ↦ True) := by
+ intro j q hq hv
+ obtain ⟨n, d, bound, post⟩ := row j q hq hv
+ exact ⟨n, d, bound, trivial, post⟩
+ obtain ⟨n, d, bound, _, post⟩ := visitWith link inj θ member labelWord inv src dest cap stable
+ (fun _ _ ↦ True) r hs hd sep i c ready hi
+ exact ⟨n, d, bound, post⟩
+
+/-- Repeat actual selected row calls in input order. Every written label is
+already available at the next copy boundary, and the next row receives the
+updated offset invariant. -/
+theorem visits (link : P.Linked M) (inj : Function.Injective (M.publicData ∘ P.port))
+ (θ : Fin u → S) (member : ∀ i, θ i ∈ P.selectors) (labelWord : Fin u → Word w)
+ (inv : ℕ → Config w p r → Prop) (src dest cap : ℕ) (stable : P.Stable inv dest u)
+ (row : P.RowRuns M θ labelWord inv cap) (hs : src + u < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : src + u ≤ dest ∨ dest + u ≤ src) (c : Config w p r)
+ (ready : P.Ready M θ labelWord src dest 0 c) (h0 : inv 0 c) (n : ℕ) (hn : n ≤ u) :
+ ∃ ticks d, ticks ≤ P.visitCap cap * n ∧ Prefix M c (List.replicate ticks .tick) d ∧
+ P.Ready M θ labelWord src dest n d ∧ inv n d ∧
+ (∀ a : Word w, a.val < dest ∨ dest + n ≤ a.val → d.privateMem a = c.privateMem a) ∧
+ d.persistent = c.persistent := by
+ induction n with
+ | zero => exact ⟨0, c, by simp, .nil _, ready, h0, fun _ _ ↦ rfl, rfl⟩
+ | succ n ih =>
+ obtain ⟨t, mid, bound, pre, hr, hi, mem, per⟩ := ih (by omega)
+ let i : Fin u := ⟨n, hn⟩
+ obtain ⟨s, d, budget, tail, hr', hi', hm, hp⟩ :=
+ visit link inj θ member labelWord inv src dest cap stable row hs hd sep i mid hr hi
+ refine ⟨t + s, d, ?_, ?_, hr', hi', ?_, hp.trans per⟩
+ · rw [Nat.mul_succ]
+ omega
+ · rw [List.replicate_add]
+ exact pre.append tail
+ · intro a ha
+ apply (hm a ?_).trans (mem a (by omega))
+ intro he
+ have hh := congrArg Fin.val he
+ rw [val_word (by change dest + n < 2 ^ w; omega)] at hh
+ change a.val = dest + n at hh
+ omega
+
+/-- At the final-width checker the label slice is in copy order and the
+row invariant has reached its final offsets. This includes the zero-copy
+case, which executes exactly the loop's final test. -/
+theorem native (link : P.Linked M) (inj : Function.Injective (M.publicData ∘ P.port))
+ (θ : Fin u → S) (member : ∀ i, θ i ∈ P.selectors) (labelWord : Fin u → Word w)
+ (inv : ℕ → Config w p r → Prop) (src dest cap : ℕ) (stable : P.Stable inv dest u)
+ (row : P.RowRuns M θ labelWord inv cap) (hs : src + u < 2 ^ w) (hd : dest + u < 2 ^ w)
+ (sep : src + u ≤ dest ∨ dest + u ≤ src) (c : Config w p r)
+ (ready : P.Ready M θ labelWord src dest 0 c) (h0 : inv 0 c) :
+ ∃ ticks d, ticks ≤ P.visitCap cap * u + 1 ∧ Prefix M c (List.replicate ticks .tick) d ∧
+ d.pc = P.checkWidths ∧ inv u d ∧
+ (∀ i : Fin u, d.privateMem (word w (dest + i.val)) = labelWord i) ∧
+ (∀ a : Word w, a.val < dest ∨ dest + u ≤ a.val → d.privateMem a = c.privateMem a) ∧
+ d.persistent = c.persistent := by
+ obtain ⟨t, m, bound, pre, hr, hi, hm, hp⟩ :=
+ visits link inj θ member labelWord inv src dest cap stable row hs hd sep c ready h0 u le_rfl
+ let d := {m with pc := P.checkWidths}
+ have eq : m.reg (P.reg 0) = m.reg (P.reg 1) := hr.source.trans hr.stop.symm
+ have stop : M.program.step m = .localStep d := by
+ rw [step_at link 0 hr.pc]
+ simp [instruction, Instr.run, eq, d]
+ refine ⟨t + 1, d, Nat.add_le_add_right bound _, ?_, rfl, ?_, fun i ↦ hr.labels i i.isLt, hm, hp⟩
+ · rw [List.replicate_add]
+ exact pre.append (.tick stop (.nil _))
+ · exact stable _ m d hi (fun _ _ _ _ _ ↦ rfl) (fun _ _ ↦ rfl) rfl
+
+end Program
+end PairSimulation.MapDriver
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapDriverCode.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapDriverCode.lean
new file mode 100644
index 0000000000..17a25ee663
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapDriverCode.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.PairSimulationMapDriver
+
+/-!
+# Relocatable instruction text for the streamed row driver
+
+The successor of a failed ordinal test is fixed by the selector's position
+in the table. The row entry points, full-width check, and bad exit can all
+belong to a surrounding map program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapDriver.Program
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {S : Type*} {w p r k : ℕ} (P : MapDriver.Program S p r k)
+
+/-- Labels of the driver's five outer instructions and its two dispatch instructions per
+selector. -/
+abbrev Location (S : Type*) := Fin 5 ⊕ (S × Bool)
+
+/-- Select an outer label, public-word load, or equality jump. -/
+def address : Location S → Fin p := Sum.elim P.pc (fun x ↦ P.comparePC x.1 x.2)
+
+/-- The residual fixed table after comparing the named selector. -/
+noncomputable def remaining (s : S) : List S → List S
+ | [] => []
+ | x :: xs => by
+ classical
+ exact if s = x then xs else remaining s xs
+
+/-- Bounded targets are already relocated into the enclosing instruction table. -/
+noncomputable def code : Location S → Instr 1 p r k
+ | .inl i => P.instruction i
+ | .inr (s, false) => .publicWord (P.reg 5) (P.port s) (P.comparePC s true)
+ | .inr (s, true) =>
+ .jumpEq (P.reg 4) (P.reg 5) (P.rowPC s) (P.first (remaining s P.selectors))
+
+private theorem dispatch_of_code {M : Machine w p r k}
+ (rows : ∀ loc, M.code (P.address loc) = (P.code loc).resize w)
+ (xs : List S) (hn : xs.Nodup)
+ (tail : ∀ s ∈ xs, remaining s P.selectors = remaining s xs) : P.dispatch M xs := by
+ induction xs with
+ | nil => trivial
+ | cons x xs ih =>
+ have hd := List.nodup_cons.mp hn
+ refine ⟨rows (.inr (x, false)), ?_, ih hd.2 ?_⟩
+ · have hx := tail x (List.mem_cons_self ..)
+ have he : remaining x P.selectors = xs := hx.trans (by simp [remaining])
+ change M.code (P.address (.inr (x, true))) = _
+ rw [rows]
+ change Instr.jumpEq _ _ _ (P.first (remaining x P.selectors)) = _
+ rw [he]
+ · intro s hs
+ have ne : s ≠ x := fun he ↦ hd.1 (he ▸ hs)
+ exact (tail s (List.mem_cons_of_mem _ hs)).trans (by simp [remaining, ne])
+
+/-- Installing each emitted opcode links the driver, including the dispatch
+of the final selector and the empty-table case. -/
+theorem linked_of_code {M : Machine w p r k} (hn : P.selectors.Nodup)
+ (rows : ∀ loc, M.code (P.address loc) = (P.code loc).resize w) : P.Linked M := by
+ constructor
+ · intro i
+ exact (rows (.inl i)).trans (P.resize_instruction i)
+ · exact dispatch_of_code P rows _ hn fun _ _ ↦ rfl
+
+end PairSimulation.MapDriver.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapDriverExact.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapDriverExact.lean
new file mode 100644
index 0000000000..b5c44f6bb0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapDriverExact.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.PairSimulationMapRowLoop
+
+/-!
+# Exact ticks of the successful row driver
+
+The number of comparisons for a copy is the position of its selector in the
+fixed dispatch table. The selected row supplies its own input-dependent tick
+count. The same path stores every label and carries the offset and register
+invariants to the width check.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapDriver.Program
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+open private MapDriver.val_word MapDriver.Program.step_at from
+ OAI.Computability.VPVNP.PairSimulationMapDriver
+open private MapDriver.Program.stable_saved from OAI.Computability.VPVNP.PairSimulationMapDriverFrame
+
+variable {S : Type*} {w p r k u : ℕ} (P : MapDriver.Program S p r k)
+ (θ : Fin u → S) (rowSteps : Fin u → ℕ)
+
+/-- Test, selector load, dispatch, selected row, label store and two increments. -/
+noncomputable def visitSteps (i : Fin u) : ℕ :=
+ 5 + dispatchSteps P.selectors (θ i) + rowSteps i
+
+/-- The final exit test follows the last copy. -/
+noncomputable def exactSteps : ℕ := (∑ i, P.visitSteps θ rowSteps i) + 1
+
+variable {P} {M : Machine w p r k}
+ (link : P.Linked M) (inj : Function.Injective (M.publicData ∘ P.port))
+ (member : ∀ i, θ i ∈ P.selectors) (labelWord : Fin u → Word w)
+ (inv : ℕ → Config w p r → Prop) (src dest cap : ℕ) (stable : P.Stable inv dest u)
+
+include link inj member stable in
+private theorem visits_exact
+ (row : P.RowRunsWith M θ labelWord inv cap (fun i n ↦ n = rowSteps i))
+ (hs : src + u < 2 ^ w) (hd : dest + u < 2 ^ w) (sep : src + u ≤ dest ∨ dest + u ≤ src)
+ (c : Config w p r) (ready : P.Ready M θ labelWord src dest 0 c) (h0 : inv 0 c)
+ (n : ℕ) (hn : n ≤ u) :
+ let ticks := MapRowLoop.prefixWidth (P.visitSteps θ rowSteps) n
+ ∃ d, ticks ≤ P.visitCap cap * n ∧ Prefix M c (List.replicate ticks .tick) d ∧
+ P.Ready M θ labelWord src dest n d ∧ inv n d ∧
+ (∀ a : Word w, a.val < dest ∨ dest + n ≤ a.val → d.privateMem a = c.privateMem a) ∧
+ d.persistent = c.persistent := by
+ dsimp only
+ induction n with
+ | zero =>
+ rw [MapRowLoop.prefix_zero]
+ exact ⟨c, by simp, .nil _, ready, h0, fun _ _ ↦ rfl, rfl⟩
+ | succ n ih =>
+ obtain ⟨m, bound, pre, hr, hi, mem, per⟩ := ih (by omega)
+ let i : Fin u := ⟨n, hn⟩
+ obtain ⟨s, d, hbound, ⟨ticks, he, h⟩, tail, hr', hi', hm, hp⟩ :=
+ visitWith link inj θ member labelWord inv src dest cap stable _ row hs hd sep i m hr hi
+ have eq : s = P.visitSteps θ rowSteps i := h.trans (congrArg _ he)
+ rw [eq] at hbound tail
+ rw [show n + 1 = i.val + 1 from rfl, MapRowLoop.prefix_next, Nat.mul_succ]
+ refine ⟨d, Nat.add_le_add bound hbound, ?_, hr', hi', ?_, hp.trans per⟩
+ · rw [List.replicate_add]
+ exact pre.append tail
+ · intro a ha
+ change a.val < dest ∨ dest + (n + 1) ≤ a.val at ha
+ apply (hm a ?_).trans (mem a (by omega))
+ intro same
+ have hv := congrArg Fin.val same
+ rw [MapDriver.val_word (by change dest + n < 2 ^ w; omega)] at hv
+ change a.val = dest + n at hv
+ omega
+
+include link inj member stable in
+/-- The complete exact path preserves the exterior registers, delivers each label at
+its private array position, and leaves all other private cells unchanged. -/
+theorem native_exact_framed (save : Fin r → Prop) (keep : P.OutsideWrites save)
+ (rows : P.FramedRowsWith θ rowSteps M labelWord inv cap save)
+ (hs : src + u < 2 ^ w) (hd : dest + u < 2 ^ w) (sep : src + u ≤ dest ∨ dest + u ≤ src)
+ (c : Config w p r) (ready : P.Ready M θ labelWord src dest 0 c) (h0 : inv 0 c) :
+ ∃ d, P.exactSteps θ rowSteps ≤ P.visitCap cap * u + 1 ∧
+ Prefix M c (List.replicate (P.exactSteps θ rowSteps) .tick) d ∧
+ d.pc = P.checkWidths ∧ inv u d ∧ Saved save c d ∧
+ (∀ i : Fin u, d.privateMem ((dest + i.val : ℕ) : Word w) = labelWord i) ∧
+ (∀ a : Word w, a.val < dest ∨ dest + u ≤ a.val → d.privateMem a = c.privateMem a) ∧
+ d.persistent = c.persistent := by
+ let framed n d := inv n d ∧ Saved save c d
+ have stable' : P.Stable framed dest u := MapDriver.Program.stable_saved P stable keep c
+ obtain ⟨m, bound, pre, hr, hi, hm, hp⟩ :=
+ visits_exact θ rowSteps link inj member labelWord framed src dest cap stable'
+ (rows c) hs hd sep c ready ⟨h0, fun _ _ ↦ rfl⟩ u le_rfl
+ rw [MapRowLoop.prefix_last] at bound pre
+ let d := {m with pc := P.checkWidths}
+ have eq : m.reg (P.reg 0) = m.reg (P.reg 1) := hr.source.trans hr.stop.symm
+ have stop : M.program.step m = .localStep d := by
+ rw [MapDriver.Program.step_at link 0 hr.pc]
+ simp [instruction, Instr.run, eq, d]
+ have final := stable' u m d hi (fun _ _ _ _ _ ↦ rfl) (fun _ _ ↦ rfl) rfl
+ refine ⟨d, Nat.add_le_add_right bound _, ?_, rfl, final.1, final.2,
+ fun i ↦ hr.labels i i.isLt, hm, hp⟩
+ rw [exactSteps, List.replicate_add]
+ exact pre.append (.tick stop (.nil _))
+
+end PairSimulation.MapDriver.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapDriverFrame.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapDriverFrame.lean
new file mode 100644
index 0000000000..02b4c31d62
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapDriverFrame.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairSimulationMapDriver
+
+/-!
+# Register preservation across all selected row calls
+
+The controller can carry an arbitrary collection of exterior registers
+through dispatch, the selected row and the label store. A later width check
+or histogram flush may therefore use operands prepared before the copy loop.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapDriver.Program
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {S : Type*} {w p r k u : ℕ} (P : MapDriver.Program S p r k)
+
+/-- All the saved registers retain their initial words. -/
+def Saved (save : Fin r → Prop) (initial c : Config w p r) : Prop :=
+ ∀ j, save j → c.reg j = initial.reg j
+
+/-- The four registers modified by the driver's own instructions are excluded.
+The selected rows supply their own preservation proof. -/
+def OutsideWrites (save : Fin r → Prop) : Prop :=
+ ∀ j, save j → j ≠ P.reg 0 ∧ j ≠ P.reg 2 ∧ j ≠ P.reg 4 ∧ j ≠ P.reg 5
+
+/-- The row contract with a register frame carried from an arbitrary initial state. -/
+def FramedRows (M : Machine w p r k) (θ : Fin u → S) (labelWord : Fin u → Word w)
+ (inv : ℕ → Config w p r → Prop) (cap : ℕ) (save : Fin r → Prop) : Prop :=
+ ∀ initial, P.RowRuns M θ labelWord (fun n c ↦ inv n c ∧ Saved save initial c) cap
+
+/-- Exact row calls preserving a chosen exterior register set. -/
+def FramedRowsWith (θ : Fin u → S) (rowSteps : Fin u → ℕ) (M : Machine w p r k)
+ (labelWord : Fin u → Word w)
+ (inv : ℕ → Config w p r → Prop) (cap : ℕ) (save : Fin r → Prop) : Prop :=
+ ∀ initial, P.RowRunsWith M θ labelWord (fun n c ↦ inv n c ∧ Saved save initial c) cap
+ (fun i n ↦ n = rowSteps i)
+
+theorem FramedRowsWith.forget {M : Machine w p r k} {θ : Fin u → S} {steps : Fin u → ℕ}
+ {labelWord : Fin u → Word w} {inv : ℕ → Config w p r → Prop} {cap : ℕ} {save : Fin r → Prop}
+ (h : P.FramedRowsWith θ steps M labelWord inv cap save) :
+ P.FramedRows M θ labelWord inv cap save := by
+ intro initial i c pc ready
+ obtain ⟨n, out, bound, _, path⟩ := h initial i c pc ready
+ exact ⟨n, out, bound, path⟩
+
+theorem FramedRows.forget {M : Machine w p r k} {θ : Fin u → S}
+ {labelWord : Fin u → Word w} {inv : ℕ → Config w p r → Prop} {cap : ℕ}
+ {save : Fin r → Prop} (rows : P.FramedRows M θ labelWord inv cap save) :
+ P.RowRuns M θ labelWord inv cap := by
+ intro i c hc hi
+ obtain ⟨n, d, bound, pre, pc, label, hr, controls, mem, per⟩ :=
+ rows c i c hc ⟨hi, fun _ _ ↦ rfl⟩
+ exact ⟨n, d, bound, pre, pc, label, hr.1, controls, mem, per⟩
+
+private theorem stable_saved {inv : ℕ → Config w p r → Prop} {dest u : ℕ}
+ {save : Fin r → Prop} (stable : P.Stable inv dest u) (keep : P.OutsideWrites save)
+ (initial : Config w p r) :
+ P.Stable (fun n c ↦ inv n c ∧ Saved save initial c) dest u := by
+ intro n c d h regs mem per
+ refine ⟨stable n c d h.1 regs mem per, fun j hj ↦ ?_⟩
+ obtain ⟨h0, h2, h4, h5⟩ := keep j hj
+ exact (regs j h0 h2 h4 h5).trans (h.2 j hj)
+
+/-- Both the complete label slice and all exterior operands are available
+on entry to the linked final-width checker. -/
+theorem native_framed {M : Machine w p r k} (link : P.Linked M)
+ (inj : Function.Injective (M.publicData ∘ P.port))
+ (θ : Fin u → S) (member : ∀ i, θ i ∈ P.selectors) (labelWord : Fin u → Word w)
+ (inv : ℕ → Config w p r → Prop) (src dest cap : ℕ) (stable : P.Stable inv dest u)
+ (save : Fin r → Prop) (keep : P.OutsideWrites save)
+ (rows : P.FramedRows M θ labelWord inv cap save) (hs : src + u < 2 ^ w)
+ (hd : dest + u < 2 ^ w) (sep : src + u ≤ dest ∨ dest + u ≤ src)
+ (c : Config w p r) (ready : P.Ready M θ labelWord src dest 0 c) (h0 : inv 0 c) :
+ ∃ ticks d, ticks ≤ P.visitCap cap * u + 1 ∧ Prefix M c (List.replicate ticks .tick) d ∧
+ d.pc = P.checkWidths ∧ inv u d ∧ Saved save c d ∧
+ (∀ i : Fin u, d.privateMem ((dest + i.val : ℕ) : Word w) = labelWord i) ∧
+ (∀ a : Word w, a.val < dest ∨ dest + u ≤ a.val → d.privateMem a = c.privateMem a) ∧
+ d.persistent = c.persistent := by
+ obtain ⟨n, d, budget, pre, pc, hr, labels, mem, per⟩ :=
+ native link inj θ member labelWord (fun i d ↦ inv i d ∧ Saved save c d)
+ src dest cap (stable_saved P stable keep c) (rows c) hs hd sep c ready ⟨h0, fun _ _ ↦ rfl⟩
+ exact ⟨n, d, budget, pre, pc, hr.1, hr.2, labels, mem, per⟩
+
+end PairSimulation.MapDriver.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapEntry.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapEntry.lean
new file mode 100644
index 0000000000..b08ee67849
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapEntry.lean
@@ -0,0 +1,403 @@
+import OAI.Computability.VPVNP.PairSimulationMapEntryProgram
+import OAI.Computability.VPVNP.PairSimulationMapNativeClock
+import OAI.Computability.VPVNP.PairSimulationMapDriverExact
+import OAI.Computability.VPVNP.PairSimulationPrivateScratch
+
+/-!
+# Executing an entire grouped motif entry in private RAM
+
+All incident half-wires may be arbitrary. The native program checks selectors,
+loads each selected matrix row, compares the full width vector, and increments
+one counter per output label. The rejecting paths leave every counter intact.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapEntry.Program
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord MotifSelector MotifEntry
+open MotifBlocks MotifGrid MotifConversion MapPortAgreement MapResidentAgreement
+open scoped Fin.CommRing
+
+variable {K J D E : Type} [Field K] [Fintype J] [DecidableEq J] [Fintype D] [Fintype E]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {w p r k u t : ℕ} (P : Program B z j p r k)
+
+/-- All per-call numerical locations, including separate selector and label arrays. -/
+structure Workspace (P : Program B z j p r k) (demand : D → ℕ) (v : E → ℕ)
+ (d : DemandBits src dst demand j) (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j)
+ (t w : ℕ) where
+ /-- Private word address of each incident supply half-wire's first bit, used with its payload
+ width to locate the selector suffix. -/
+ portBase : Port G j → BurstRAM.Word w
+ /-- Private base address of the incident-port directory whose entries point to the selector
+ suffixes. -/
+ directory : BurstRAM.Word w
+ /-- Private base address of each demand or supply endpoint's bit slice, used when reading a
+ selected matrix row. -/
+ base : MapLookup.LabelField D E → ℕ
+ /-- Start address of the private selector ordinal array written by the decoder and read by
+ the row driver. -/
+ source : ℕ
+ /-- Start address of the private parameter label array written by the row driver and read by
+ the histogram loop. -/
+ target : ℕ
+ /-- Base address of the private counters indexed by parameter ordinal. -/
+ hist : ℕ
+ portsFit : (ports G j P.edgeOrder).length < 2 ^ w
+ tagFit : u * B.selectorBits < 2 ^ w
+ anchorFit :
+ (portBase (anchorPort G j)).val + (v (edge (anchorPort G j)) + u * B.selectorBits) < 2 ^ w
+ anchorApart :
+ (portBase (anchorPort G j)).val + (v (edge (anchorPort G j)) + u * B.selectorBits) ≤ source ∨
+ source + u ≤ (portBase (anchorPort G j)).val
+ ordinalFit : source + u < 2 ^ w
+ labelFit : target + u < 2 ^ w
+ histogramFit : hist + t ≤ 2 ^ w
+ ordinalsBefore : source + u ≤ target
+ sourceHistApart : source + u ≤ hist ∨ hist + t ≤ source
+ targetHistApart : target + u ≤ hist ∨ hist + t ≤ target
+ inputApart : ∀ (θ : Fin u → Selector B) f
+ (l : Fin ((MapRowLoop.buffers B z j demand v d x base θ 0).len f)),
+ ((base f + l.val : ℕ) : BurstRAM.Word w).val < source
+ fieldsFit : ∀ (θ : Fin u → Selector B) (i : Fin u), MapRowFields.Fits MapRow.group
+ (Sum.elim (baseDemand B z) (basePayload B (θ i)))
+ (MapRowLoop.buffers B z j demand v d x base θ i.val) w
+ totalsFit : ∀ (θ : Fin u → Selector B) e, totalWidth (basePayload B) θ e < 2 ^ w
+
+variable {demand : D → ℕ} {v : E → ℕ} {d : DemandBits src dst demand j}
+ {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (X : Workspace P demand v d x t w)
+
+/-- Resident pointers, bit data, zero offsets and full-vector comparison targets.
+Every deterministic stage may now execute even if the incident data are invalid. -/
+structure Ready (c : Config w p r) : Prop where
+ selector : P.selector.Ready P.edgeOrder x X.portBase X.directory X.source c
+ row : ∀ θ,
+ MapRowFields.Resident P.bank.rowReg (MapRowLoop.buffers B z j demand v d x X.base θ 0) c
+ source : c.reg (P.driver.reg 0) = (X.source : BurstRAM.Word w)
+ stop : c.reg (P.driver.reg 1) = ((X.source + u : ℕ) : BurstRAM.Word w)
+ target : c.reg (P.driver.reg 2) = (X.target : BurstRAM.Word w)
+ one : c.reg (P.driver.reg 3) = 1
+ expected : ∀ e, (c.reg (P.expected e)).val = v e
+ histogram : MapFinish.HistogramReady (u := u) P.histReg X.target X.hist c
+
+omit [DecidableEq J] in
+private theorem selector_reg {sel lab : ℕ} {c m : Config w p r}
+ (frame : P.selector.Frame sel lab c m) {a : Fin r} (save : P.SelectorSaved a) :
+ m.reg a = c.reg a := frame.regs a save.1 (save.2 0) (save.2 1) (save.2 2) (save.2 5) (save.2 6)
+
+/-- The exit and the value of each histogram cell on this particular path. -/
+def Effect (c out : Config w p r) (hist : ℕ) : Option (List (Fin t)) → Prop
+ | none => out.pc = P.bad ∧ ∀ l : Fin t, out.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w)
+ | some names => out.pc = P.done ∧ ∀ l : Fin t,
+ out.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w) + (names.count l : BurstRAM.Word w)
+
+/-- Value and histogram effect of the entire map entry, on the very same
+machine for all inputs, up to its success or failure continuation. -/
+structure Runs (M : Machine w p r k) (c : Config w p r) (hist cap : ℕ)
+ (value : Option (List (Fin t))) : Prop where
+ path : ∃ n out, n ≤ cap ∧ Prefix M c (List.replicate n .tick) out ∧
+ out.persistent = c.persistent ∧ P.Effect c out hist value
+
+/-- The same path both executes the map and preserves each saved private cell. -/
+structure RunsFramed (M : Machine w p r k) (c : Config w p r) (hist cap : ℕ)
+ (save : BurstRAM.Word w → Prop) (value : Option (List (Fin t))) : Prop where
+ path : ∃ n out, n ≤ cap ∧ Prefix M c (List.replicate n .tick) out ∧
+ out.persistent = c.persistent ∧ (∀ a, save a → out.privateMem a = c.privateMem a) ∧
+ P.Effect c out hist value
+
+omit [DecidableEq J] in
+theorem RunsFramed.forget {M : Machine w p r k} {c : Config w p r} {hist cap : ℕ}
+ {save : BurstRAM.Word w → Prop} {value : Option (List (Fin t))}
+ (h : P.RunsFramed M c hist cap save value) : P.Runs M c hist cap value := by
+ obtain ⟨n, out, bound, pre, per, _, effect⟩ := h.path
+ exact ⟨n, out, bound, pre, per, effect⟩
+
+/-- The map writes only the selector, label and histogram arrays. -/
+def Outside (a : BurstRAM.Word w) : Prop :=
+ (a.val < X.source ∨ X.source + u ≤ a.val) ∧
+ (a.val < X.target ∨ X.target + u ≤ a.val) ∧
+ ∀ l : Fin t, a ≠ ((X.hist + l.val : ℕ) : BurstRAM.Word w)
+
+/-- Exact postconditions and the exterior frame hold on the same native prefix. -/
+structure RunsPost (M : Machine w p r k) (c : Config w p r) (hist cap : ℕ)
+ (save : BurstRAM.Word w → Prop) (value : Option (List (Fin t)))
+ (post : PrivateScratch.Memory w → Prop) : Prop where
+ path : ∃ n out, n ≤ cap ∧ Prefix M c (List.replicate n .tick) out ∧
+ out.persistent = c.persistent ∧ (∀ a, save a → out.privateMem a = c.privateMem a) ∧
+ P.Effect c out hist value ∧ post out.privateMem
+
+omit [DecidableEq J] in
+theorem RunsPost.framed {M : Machine w p r k} {c : Config w p r} {hist cap : ℕ}
+ {save : BurstRAM.Word w → Prop} {value : Option (List (Fin t))}
+ {post : PrivateScratch.Memory w → Prop} (h : P.RunsPost M c hist cap save value post) :
+ P.RunsFramed M c hist cap save value := by
+ obtain ⟨n, out, bound, pre, per, frame, effect, _⟩ := h.path
+ exact ⟨n, out, bound, pre, per, frame, effect⟩
+
+/-- Exact memory on a successful map: selector ordinals and labels are stored in
+copy order before each emitted label increments its histogram bin. -/
+noncomputable def successMemory (selector : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t) (θ : Fin u → Selector B)
+ (old : PrivateScratch.Memory w) : PrivateScratch.Memory w :=
+ let labels := fun i ↦ ord (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i (θ i)
+ (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i))
+ PrivateLabels.accumulate X.hist (List.ofFn labels)
+ (PrivateScratch.write (X.target : BurstRAM.Word w) (fun i ↦ ((labels i).val : BurstRAM.Word w))
+ (PrivateScratch.write (X.source : BurstRAM.Word w) (fun i ↦ selector (θ i)) old))
+
+/-- The successful selector and its complete width vector determine every written word. -/
+def Success (selector : Selector B ↪ BurstRAM.Word w) (ord : (parameterData B).Entry → Fin t)
+ (old new : PrivateScratch.Memory w) : Prop :=
+ ∀ θ : Fin u → Selector B, (selectorRun G (selectorTable B) (selectorCode B) v j x).1 = some θ →
+ (∀ e, v e = totalWidth (basePayload B) θ e) → new = P.successMemory X selector ord θ old
+
+theorem successMemory_congr_at (selector : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t) (θ : Fin u → Selector B)
+ {old old' : PrivateScratch.Memory w} (a : BurstRAM.Word w) (ha : old a = old' a) :
+ P.successMemory X selector ord θ old a = P.successMemory X selector ord θ old' a :=
+ PrivateScratch.accumulate_congr_at _ _ a
+ (PrivateScratch.write_congr_at _ _ a (PrivateScratch.write_congr_at _ _ a ha))
+
+/-- The exact row-driver clock depends on input bits, decoded selectors, and the fixed
+public table. The argument bases and the contents of exterior memory play no role. -/
+noncomputable def driverTicks (d : DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j) (θ : Fin u → Selector B)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (words : Fin k → BurstRAM.Word w) : ℕ :=
+ P.driver.exactSteps θ (MapRowLoop.rowSteps B z j demand v d x θ fd fs P.bank.keyPort words)
+
+set_option maxHeartbeats 1200000 in
+-- The dependent register and memory types unfold through each fixed row-bank phase.
+/-- Run the selected rows once and expose the private labels, widths, and histogram operands
+together with the exact number of executed instructions. -/
+theorem runSelectedRows (M : Machine w p r k) (linked : P.Linked M) (separate : P.Separate)
+ (selector : Selector B ↪ BurstRAM.Word w) (ordinal : (parameterData B).Entry → Fin t)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (pub : P.Public M selector (fun s ↦ ((ordinal s).val : BurstRAM.Word w)) fb fd fs)
+ (c : Config w p r) (ready : P.Ready X c) (θ : Fin u → Selector B)
+ (m : Config w p r) (frame : P.selector.Frame X.source u c m)
+ (hm : m.pc = P.selector.decoder.done)
+ (hselWords : ∀ i : Fin u, m.privateMem ((X.source + i.val : ℕ) : BurstRAM.Word w) =
+ M.publicData (P.selector.decoder.name (θ i))) :
+ let labels := fun i ↦ ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i (θ i)
+ (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i))
+ let ticks := P.driverTicks d x θ fd fs M.publicData
+ ∃ mid, ticks ≤ P.driver.visitCap (MapRowLoop.rowCap B z j) * u + 1 ∧
+ Prefix M m (List.replicate ticks .tick) mid ∧ mid.pc = P.driver.checkWidths ∧
+ (∀ e, (mid.reg (P.bank.rowReg (.offset (.inr e)))).val = totalWidth (basePayload B) θ e) ∧
+ (∀ e, (mid.reg (P.expected e)).val = v e) ∧
+ MapFinish.HistogramReady (u := u) P.histReg X.target X.hist mid ∧
+ (∀ i : Fin u, mid.privateMem ((X.target + i.val : ℕ) : BurstRAM.Word w) =
+ ((labels i).val : BurstRAM.Word w)) ∧
+ (∀ a : BurstRAM.Word w, a.val < X.target ∨ X.target + u ≤ a.val →
+ mid.privateMem a = m.privateMem a) ∧ mid.persistent = m.persistent := by
+ classical
+ dsimp only
+ let A := P.bank
+ let drive := P.driver
+ let inv : ℕ → Config w p r → Prop := fun n ↦
+ MapRowFields.Resident A.rowReg (MapRowLoop.buffers B z j demand v d x X.base θ n)
+ let labels := fun i ↦ ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i (θ i)
+ (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i))
+ let names := fun i ↦ ((labels i).val : BurstRAM.Word w)
+ let save := fun a ↦ (∃ e, a = P.expected e) ∨ (∃ i, a = P.histReg i)
+ have ext (a) (h : save a) (b) : a ≠ A.register b := by
+ rcases h with ⟨e, rfl⟩ | ⟨i, rfl⟩
+ · exact separate.expectedRow e b
+ · exact separate.histRow i b
+ have rowFrame : MapRowLoop.OutsideRowWrites A.rowReg save := fun a ha ↦
+ ⟨ext a ha _, fun _ ↦ ext a ha _, ext a ha _, ext a ha _, ext a ha _, fun _ ↦ ext a ha _⟩
+ have driveFrame : drive.OutsideWrites save := fun a ha ↦
+ ⟨ext a ha _, ext a ha _, ext a ha _, ext a ha _⟩
+ obtain ⟨dlink, rlink⟩ := A.linked P.loc M linked.body
+ obtain ⟨inj, widths, keys, output⟩ := A.public_spec fd fs selector _ M pub.rows
+ have run := MapRowLoop.rowRunsExactFramed B z j demand v d x X.base θ drive A.rowReg
+ (A.registerLayout P.loc) (fun s ↦ ((ordinal s).val : BurstRAM.Word w)) A.widthPort
+ A.keyPort A.namePort (A.sites P.loc) M drive.bad
+ (fun _ ↦ rfl) rlink fd fs widths keys output (X.fieldsFit θ) save rowFrame
+ have stable := MapRowLoop.stable B z j demand v d x X.base θ drive A.rowReg
+ (A.registerLayout P.loc) X.target (fun f l ↦ .inl ((X.inputApart θ f l).trans_le
+ ((Nat.le_add_right _ _).trans X.ordinalsBefore)))
+ have kept (a) : m.reg (A.register a) = c.reg (A.register a) :=
+ selector_reg P frame (separate.bank a)
+ have start : inv 0 m := by
+ let h := ready.row θ
+ exact ⟨(kept _).trans h.one, fun f ↦ (kept _).trans (h.base f),
+ fun f ↦ (kept _).trans (h.dataEnd f), fun g ↦ (kept _).trans (h.offset g),
+ fun f l ↦ (frame.memory _ (.inl (X.inputApart θ f l))).trans (h.data f l)⟩
+ have dready : drive.Ready M θ names X.source X.target 0 m :=
+ ⟨hm.trans linked.selectorExit, (kept _).trans ready.source, (kept _).trans ready.stop,
+ (kept _).trans ready.target, (kept _).trans ready.one, fun i ↦
+ (hselWords i).trans (pub.name _), fun i hi ↦ (Nat.not_lt_zero _ hi).elim⟩
+ obtain ⟨mid, h₂, rows, widthPC, endInv, saved, labelWords, memory, hp⟩ :=
+ MapDriver.Program.native_exact_framed θ
+ (MapRowLoop.rowSteps B z j demand v d x θ fd fs A.keyPort M.publicData) dlink inj
+ (fun i ↦ Finset.mem_toList.mpr (Finset.mem_univ _)) names
+ inv X.source X.target (MapRowLoop.rowCap B z j) stable save driveFrame run X.ordinalFit
+ X.labelFit (.inl X.ordinalsBefore) m dready start
+ have totals (e) : (mid.reg (A.rowReg (.offset (.inr e)))).val =
+ totalWidth (basePayload B) θ e := by
+ rw [endInv.offset]
+ simp only [MapRowLoop.buffers, Sum.elim_inr, MapRowLoop.prefix_last]
+ exact Nat.mod_eq_of_lt (X.totalsFit θ e)
+ have he (e) : (mid.reg (P.expected e)).val = v e := by
+ rw [saved _ (.inl ⟨e, rfl⟩), selector_reg P frame (separate.expected e), ready.expected]
+ have hh (i) : mid.reg (P.histReg i) = c.reg (P.histReg i) :=
+ (saved _ (.inr ⟨i, rfl⟩)).trans (selector_reg P frame (separate.histogram i))
+ have hready : MapFinish.HistogramReady (u := u) P.histReg X.target X.hist mid :=
+ ⟨(hh 0).trans ready.histogram.cursor, (hh 1).trans ready.histogram.stop,
+ (hh 2).trans ready.histogram.base, (hh 3).trans ready.histogram.one⟩
+ exact ⟨mid, h₂, rows, widthPC, totals, he, hready, labelWords, memory, hp⟩
+
+set_option maxHeartbeats 1200000 in
+-- The public keys and memory slices of the same grouped matrix reduce in four dependent phases.
+/-- Every path uses genuine finite-table instructions and its cap includes
+the rejecting paths on disagreement, unused tags and false payload totals. -/
+theorem native_post (M : Machine w p r k) (linked : P.Linked M) (separate : P.Separate)
+ (selector : Selector B ↪ BurstRAM.Word w) (ordinal : (parameterData B).Entry → Fin t)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (pub : P.Public M selector (fun s ↦ ((ordinal s).val : BurstRAM.Word w)) fb fd fs)
+ (c : Config w p r) (ready : P.Ready X c) :
+ P.RunsPost M c X.hist (MapNativeClock.cap B z j u) (P.Outside X)
+ ((MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.map (List.map ordinal))
+ (P.Success X selector ordinal c.privateMem) := by
+ classical
+ obtain ⟨n₁, m, h₁, pre, frame, res⟩ :=
+ (P.selector.native linked.selector P.edgeOrder fb (selectorCode B) pub.key x X.portBase
+ X.directory X.source c ready.selector X.portsFit X.tagFit X.anchorFit X.ordinalFit
+ X.anchorApart).path
+ let sel := (selectorRun G (selectorTable B) (selectorCode B) v j x).1
+ rw [linked.table] at res
+ have hfirst : n₁ ≤ (7 * (u * B.selectorBits) + 6) * (2 * Fintype.card E) + 3 +
+ ((6 * B.selectorBits + 1 + (2 * (selectorTable B).length + 1) + 5) * u + 1) := by
+ unfold AnchorDecode.Program.visitCap at h₁
+ rw [linked.table] at h₁
+ exact h₁.trans (Nat.add_le_add_right (Nat.add_le_add_right
+ (Nat.mul_le_mul_left _ (ports_length_le G j P.edgeOrder)) _) _)
+ have address (l : Fin t) : ((X.hist + l.val : ℕ) : BurstRAM.Word w).val = X.hist + l.val :=
+ Nat.mod_eq_of_lt (Nat.add_lt_add_left l.isLt X.hist |>.trans_le X.histogramFit)
+ have outside (l : Fin t) (atWord : ℕ) (apart : atWord + u ≤ X.hist ∨ X.hist + t ≤ atWord) :
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w).val < atWord ∨
+ atWord + u ≤ ((X.hist + l.val : ℕ) : BurstRAM.Word w).val := by
+ rw [address l]
+ have := l.isLt
+ omega
+ have hsHist (l : Fin t) : m.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) :=
+ frame.memory _ (outside l _ X.sourceHistApart)
+ rw [MapFinish.entry_value]
+ change P.RunsPost M c X.hist _ (P.Outside X) ((sel.bind _).map _) _
+ cases hsel : sel with
+ | none =>
+ dsimp only [sel] at hsel
+ rw [hsel] at res
+ refine ⟨n₁, m, hfirst.trans (by unfold MapNativeClock.cap; omega), pre, frame.persistent,
+ fun a ha ↦ frame.memory a ha.1, ⟨res.trans linked.selectorBad, hsHist⟩, ?_⟩
+ intro θ hit
+ rw [hsel] at hit
+ cases hit
+ | some θ =>
+ dsimp only [sel] at hsel
+ rw [hsel] at res
+ obtain ⟨hm, hselWords⟩ := res
+ let labels := fun i ↦ ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i (θ i)
+ (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i))
+ let names := fun i ↦ ((labels i).val : BurstRAM.Word w)
+ let n₂ := P.driverTicks d x θ fd fs M.publicData
+ obtain ⟨mid, h₂, rows, widthPC, totals, he, hready, labelWords, memory, hp⟩ :=
+ P.runSelectedRows X M linked separate selector ordinal fb fd fs pub c ready θ m frame hm
+ hselWords
+ obtain ⟨n₃, out, h₃, last, per, done⟩ := MapFinish.native (basePayload B) θ v
+ (List.ofFn P.edgeOrder)
+ (fun e ↦ List.mem_ofFn.mpr ⟨P.edgeOrder.symm e, P.edgeOrder.apply_symm_apply e⟩)
+ _ P.expected P.guardTemp M P.guardPC P.histPC P.histReg P.done P.bad linked.guard
+ linked.histogram
+ X.target X.hist labels mid (widthPC.trans linked.rowExit) totals he hready X.histogramFit
+ X.targetHistApart X.labelFit labelWords
+ have hmid (l : Fin t) : mid.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) :=
+ (memory _ (outside l _ X.targetHistApart)).trans (hsHist l)
+ refine ⟨n₁ + n₂ + n₃, out, ?_, ?_, per.trans (hp.trans frame.persistent), ?_, ?_, ?_⟩
+ · simp only [List.length_ofFn] at h₃
+ unfold MapNativeClock.cap
+ change n₂ ≤ (5 + 2 * (selectorTable B).length + MapRowLoop.rowCap B z j) * u + 1 at h₂
+ omega
+ · rw [List.replicate_add, List.replicate_add]
+ exact (pre.append rows).append last
+ · intro a ha
+ have keep := (memory a ha.2.1).trans (frame.memory a ha.1)
+ by_cases valid : ∀ e, v e = totalWidth (basePayload B) θ e
+ · rw [ite_eq_left valid] at done
+ rw [done.2, PrivateLabels.accumulate_outside _ _ _ a ha.2.2]
+ exact keep
+ · rw [ite_eq_right valid] at done
+ exact (congrFun done.2 a).trans keep
+ · dsimp only [Option.bind_some]
+ by_cases valid : ∀ e, v e = totalWidth (basePayload B) θ e
+ · rw [ite_eq_left valid] at done ⊢
+ refine ⟨done.1, fun l ↦ ?_⟩
+ rw [done.2, PrivateLabels.accumulate_at _ _ _ X.histogramFit, hmid]
+ simp only [List.map_ofFn, labels, Function.comp_def]
+ · rw [ite_eq_right valid] at done ⊢
+ exact ⟨done.1, fun l ↦ (congrFun done.2 _).trans (hmid l)⟩
+ · intro θ' hit valid
+ have eq := Option.some.inj (hit.symm.trans hsel)
+ subst θ'
+ rw [ite_eq_left valid] at done
+ have sels : m.privateMem = PrivateScratch.write (X.source : BurstRAM.Word w)
+ (fun i ↦ selector (θ i)) c.privateMem := by
+ apply PrivateScratch.eq_write
+ · intro i
+ rw [← Nat.cast_add]
+ exact (hselWords i).trans ((pub.name _).trans (pub.rows (.inl (θ i))))
+ · intro a ne
+ exact frame.memory a (PrivateScratch.outside_of_ne _ a ne)
+ have labs : mid.privateMem = PrivateScratch.write (X.target : BurstRAM.Word w) names
+ m.privateMem := by
+ apply PrivateScratch.eq_write
+ · intro i
+ simpa only [Nat.cast_add] using labelWords i
+ · intro a ne
+ exact memory a (PrivateScratch.outside_of_ne _ a ne)
+ rw [done.2, labs, sels]
+ rfl
+
+/-- Project the exterior-cell guarantee from the exact native post-state. -/
+theorem native_framed (M : Machine w p r k) (linked : P.Linked M) (separate : P.Separate)
+ (selector : Selector B ↪ BurstRAM.Word w) (ordinal : (parameterData B).Entry → Fin t)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (pub : P.Public M selector (fun s ↦ ((ordinal s).val : BurstRAM.Word w)) fb fd fs)
+ (c : Config w p r) (ready : P.Ready X c) :
+ P.RunsFramed M c X.hist (MapNativeClock.cap B z j u) (P.Outside X)
+ ((MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.map (List.map ordinal)) :=
+ (P.native_post X M linked separate selector ordinal fb fd fs pub c ready).framed P
+
+/-- Project the exact map result and histogram from its framed native path. -/
+theorem native (M : Machine w p r k) (linked : P.Linked M) (separate : P.Separate)
+ (selector : Selector B ↪ BurstRAM.Word w) (ordinal : (parameterData B).Entry → Fin t)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (pub : P.Public M selector (fun s ↦ ((ordinal s).val : BurstRAM.Word w)) fb fd fs)
+ (c : Config w p r) (ready : P.Ready X c) :
+ P.Runs M c X.hist (MapNativeClock.cap B z j u)
+ ((MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.map (List.map ordinal)) :=
+ (P.native_framed X M linked separate selector ordinal fb fd fs pub c ready).forget P
+
+end PairSimulation.MapEntry.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapEntryExact.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapEntryExact.lean
new file mode 100644
index 0000000000..24bbc13680
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapEntryExact.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.PairSimulationMapEntry
+import OAI.Computability.VPVNP.PairSimulationMapSelectorClock
+import OAI.Computability.VPVNP.PairSimulationMapFinishExact
+
+/-!
+# Successful grouped map calls have an exact clock and private state
+
+The successful selector sequence fixes the tag checks, row dispatches and group
+widths. The endpoint bits fix the label comparisons. The same deterministic
+path writes the two staging arrays and increments exactly the emitted labels.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapEntry.Program
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord MotifSelector MotifEntry
+open MotifBlocks MotifGrid MotifConversion MapPortAgreement MapResidentAgreement
+open scoped Fin.CommRing
+
+variable {K J D E : Type} [Field K] [Fintype J] [DecidableEq J] [Fintype D] [Fintype E]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {w p r k u t : ℕ} (P : Program B z j p r k)
+ {demand : D → ℕ} {v : E → ℕ} {d : DemandBits src dst demand j}
+ {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+
+/-- Every successful call on the same input uses this tick count at all ready
+configurations, including calls with different initial histogram counts. -/
+noncomputable def successTicks (d : DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j) (θ : Fin u → Selector B)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (words : Fin k → BurstRAM.Word w) : ℕ :=
+ P.selector.successTicks (selectorCode B) θ (ports G j P.edgeOrder).length +
+ P.driverTicks d x θ fd fs words + ((Fintype.card E + 1) + (7 * u + 1))
+
+set_option maxHeartbeats 1000000 in
+-- The three native prefixes share dependent row, width, and private-memory operands.
+/-- Execute the three linked phases. The successful prefix, tick bound, continuation,
+persistent state, and equality of every private word refer to the same endpoint. -/
+theorem native_success_exact (X : Workspace P demand v d x t w) (M : Machine w p r k)
+ (linked : P.Linked M) (separate : P.Separate) (selector : Selector B ↪ BurstRAM.Word w)
+ (ordinal : (parameterData B).Entry → Fin t) (fb : B.selectorBits ≤ w)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (pub : P.Public M selector (fun s ↦ ((ordinal s).val : BurstRAM.Word w)) fb fd fs)
+ (c : Config w p r) (ready : P.Ready X c) (θ : Fin u → Selector B)
+ (selected : (selectorRun G (selectorTable B) (selectorCode B) v j x).1 = some θ)
+ (valid : ∀ e, v e = totalWidth (basePayload B) θ e) :
+ let ticks := P.successTicks d x θ fd fs M.publicData
+ ∃ out, ticks ≤ MapNativeClock.cap B z j u ∧ Prefix M c (List.replicate ticks .tick) out ∧
+ out.pc = P.done ∧ out.persistent = c.persistent ∧
+ out.privateMem = P.successMemory X selector ordinal θ c.privateMem := by
+ classical
+ dsimp only
+ have hit : (selectorRun G P.selector.decoder.xs (selectorCode B) v j x).1 = some θ := by
+ rw [linked.table]
+ exact selected
+ obtain ⟨m, first, frame, hm, sels⟩ := P.selector.native_success linked.selector P.edgeOrder
+ fb (selectorCode B) pub.key x X.portBase X.directory X.source c ready.selector X.portsFit
+ X.tagFit X.anchorFit X.ordinalFit X.anchorApart θ hit
+ let labels := fun i ↦ ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i (θ i) (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i))
+ obtain ⟨mid, h₂, rows, atWidth, totals, he, hist, labelWords, memory, hp⟩ :=
+ P.runSelectedRows X M linked separate selector ordinal fb fd fs pub c ready θ m frame hm sels
+ obtain ⟨out, last, done, bins, per⟩ := MapFinish.native_success (basePayload B) θ v
+ (List.ofFn P.edgeOrder) _ P.expected P.guardTemp M P.guardPC P.histPC P.histReg P.done P.bad
+ linked.guard linked.histogram X.target X.hist labels mid (atWidth.trans linked.rowExit)
+ totals he hist X.histogramFit X.targetHistApart X.labelFit labelWords valid
+ refine ⟨out, ?_, ?_, done, per.trans (hp.trans frame.persistent), ?_⟩
+ · have h₁ := P.selector.successTicks_le (selectorCode B) θ (ports G j P.edgeOrder).length
+ unfold AnchorDecode.Program.visitCap at h₁
+ rw [linked.table] at h₁
+ have hh := h₁.trans (Nat.add_le_add_right (Nat.add_le_add_right
+ (Nat.mul_le_mul_left _ (ports_length_le G j P.edgeOrder)) _) _)
+ change P.driverTicks d x θ fd fs M.publicData ≤
+ (5 + 2 * (selectorTable B).length + MapRowLoop.rowCap B z j) * u + 1 at h₂
+ unfold successTicks MapNativeClock.cap
+ omega
+ · unfold successTicks
+ rw [List.replicate_add, List.replicate_add]
+ simpa only [List.length_ofFn] using (first.append rows).append last
+ · have sm : m.privateMem = PrivateScratch.write (X.source : BurstRAM.Word w)
+ (fun i ↦ selector (θ i)) c.privateMem := by
+ apply PrivateScratch.eq_write
+ · intro i
+ rw [← Nat.cast_add]
+ exact (sels i).trans ((pub.name _).trans (pub.rows (.inl (θ i))))
+ · intro a ha
+ exact frame.memory a (PrivateScratch.outside_of_ne _ a ha)
+ have lm : mid.privateMem = PrivateScratch.write (X.target : BurstRAM.Word w)
+ (fun i ↦ ((labels i).val : BurstRAM.Word w)) m.privateMem := by
+ apply PrivateScratch.eq_write
+ · intro i
+ simpa only [Nat.cast_add] using labelWords i
+ · intro a ha
+ exact memory a (PrivateScratch.outside_of_ne _ a ha)
+ rw [bins, lm, sm]
+ rfl
+
+end PairSimulation.MapEntry.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapEntryProgram.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapEntryProgram.lean
new file mode 100644
index 0000000000..c9a15a80a3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapEntryProgram.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.PairSimulationMapBank
+import OAI.Computability.VPVNP.PairSimulationMapSelectors
+import OAI.Computability.VPVNP.PairSimulationMapFinish
+
+/-!
+# The linked instruction blocks of one grouped map entry
+
+The program uses one selector directory and fixed matrix bank at a chosen grid
+point and party. The width guards and histogram scan share the same machine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapEntry
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM MotifSelector MotifBlocks MotifGrid MotifConversion
+open MapPortAgreement
+open scoped Fin.CommRing
+
+variable {K J D E : Type} [Field K] [Fintype J] [Fintype D] [Fintype E]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H')
+ (z : B.grid.demands) (j : J) {w p r k : ℕ}
+
+/-- Locations of the fixed instructions and registers used by the four phases. -/
+structure Program (p r k : ℕ) where
+ /-- The selector directory scan and decoder for the block. -/
+ selector : MapSelectors.Program (Selector B) p r k
+ /-- Registers and public ports for the matrix rows at grid point `z` and party `j`. -/
+ bank : MapBank.Allocation B z j r k
+ /-- Machine instruction address assigned to each bank address. -/
+ loc : bank.Address → Fin p
+ /-- Order in which the width guard checks the supply edges. -/
+ edgeOrder : Fin (Fintype.card E) ≃ E
+ /-- Register holding the expected total width for each edge. -/
+ expected : E → Fin r
+ /-- Register compared with itself at the end of the width guard. -/
+ guardTemp : Fin r
+ /-- Machine instruction addresses of the width comparisons. -/
+ guardPC : (MapWidths.checkCode (fun e ↦ bank.rowReg (.offset (.inr e))) expected guardTemp
+ (List.ofFn edgeOrder) : Flow r k).Label → Fin p
+ /-- Instruction addresses of the histogram scan. -/
+ histPC : Fin 7 → Fin p
+ /-- Machine registers used by the histogram scan. -/
+ histReg : Fin 6 ↪ Fin r
+ /-- Continuation after the histogram scan finishes. -/
+ done : Fin p
+ /-- Rejection address shared by the selector, row driver and width guard. -/
+ bad : Fin p
+
+namespace Program
+
+variable {B z j} (P : Program B z j p r k)
+
+/-- The matrix row driver at the instruction addresses assigned by `P.loc`. -/
+noncomputable abbrev driver := P.bank.driver P.loc
+
+/-- Compare each accumulated edge offset with its expected width in `P.edgeOrder`. -/
+noncomputable abbrev guardCode : Flow r k := MapWidths.checkCode
+ (fun e ↦ P.bank.rowReg (.offset (.inr e))) P.expected P.guardTemp (List.ofFn P.edgeOrder)
+
+/-- Instruction links for the common machine, including the shared rejection target. -/
+structure Linked (M : Machine w p r k) : Prop where
+ selector : P.selector.Linked M
+ table : P.selector.decoder.xs = selectorTable B
+ selectorExit : P.selector.decoder.done = P.driver.pc 0
+ selectorBad : P.selector.decoder.bad = P.bad
+ rowExit : P.driver.checkWidths = P.guardPC P.guardCode.entry
+ rowBad : P.driver.bad = P.bad
+ body : ∀ a, P.bank.inBody a = true → M.code (P.loc a) = (P.bank.text P.loc a).resize w
+ guard : Flow.Linked M P.guardCode P.guardPC (P.histPC 0) P.bad
+ histogram : PrivateLabels.Linked M P.histPC P.histReg P.done
+
+/-- An exterior register survives the selector directory walk and decoder. -/
+def SelectorSaved (a : Fin r) : Prop := MapPortScan.Preserved P.selector.reg a ∧
+ ∀ i, a ≠ P.selector.decoder.reg i
+
+/-- The row bank, width targets and histogram operands can all be prepared
+before entering the selector walk. Only the row bank uses the row scratch words. -/
+structure Separate : Prop where
+ bank : ∀ a, P.SelectorSaved (P.bank.register a)
+ expected : ∀ e, P.SelectorSaved (P.expected e)
+ histogram : ∀ i, P.SelectorSaved (P.histReg i)
+ expectedRow : ∀ e a, P.expected e ≠ P.bank.register a
+ histRow : ∀ i a, P.histReg i ≠ P.bank.register a
+
+/-- The fixed code bits and matrix keys use the live word size. The two
+selector phases share the same ordinal for each selector. -/
+structure Public (M : Machine w p r k) (selector : Selector B ↪ BurstRAM.Word w)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) (fb : B.selectorBits ≤ w)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w) : Prop where
+ key : ∀ s, M.publicData (P.selector.decoder.key s) = MapLookup.widen fb (selectorCode B s)
+ name : ∀ s, M.publicData (P.selector.decoder.name s) = M.publicData (P.bank.selectorPort s)
+ rows : ∀ a, M.publicData (P.bank.port a) = MapBank.Allocation.words fd fs selector ordinal a
+
+end Program
+end PairSimulation.MapEntry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapEntryTable.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapEntryTable.lean
new file mode 100644
index 0000000000..13c6c9aa77
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapEntryTable.lean
@@ -0,0 +1,279 @@
+import OAI.Computability.VPVNP.PairSimulationMapEntryProgram
+import OAI.Computability.VPVNP.PairSimulationMapSelectorBank
+
+/-!
+# Complete private instruction table for a grouped motif entry
+
+The selector scan, row driver, full-width comparison and histogram loop share
+one program counter space and one fixed public-word bank. The decoder and the
+row dispatcher share selector ordinals. The expected widths and histogram
+registers occupy distinct positions throughout both earlier phases.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapEntryTable
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MapLookup
+open BurstRAM.PrivateRAM PrimedInputRAM
+
+variable {J D E : Type} [Fintype J] [Fintype D] [Fintype E]
+ {K : Type} [Field K] {src dst : D → J} {G : Supply J E}
+ {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H')
+ (z : B.grid.demands) (j : J) {r k p w : ℕ}
+
+/-- Logical registers of the grouped map interpreter, comprising selector registers, row-bank
+registers, one expected width per supply edge, and six histogram registers. -/
+abbrev Register (D E : Type) :=
+ MapSelectorBank.Register ⊕ MapBank.Register D E ⊕ E ⊕ Fin 6
+
+/-- Public-word indices for the selector codes and the row bank's selector ordinals, widths,
+matrix keys, and parameter ordinals. -/
+abbrev PublicPort := Selector B ⊕ MapBank.PublicPort B z j
+
+/-- The allocation can be embedded in a larger vertex program. -/
+structure Allocation (r k : ℕ) where
+ /-- Inject the grouped interpreter's logical register slots into the machine register file. -/
+ reg : Register D E ↪ Fin r
+ /-- Inject the selector-code and matrix-table ports into the enclosing machine's public-word
+ bank. -/
+ pub : PublicPort B z j ↪ Fin k
+ /-- Fixed enumeration of the supply edges used for the port directory and the final width
+ checks. -/
+ edgeOrder : Fin (Fintype.card E) ≃ E
+
+private noncomputable def number (X : Type*) [Finite X] : X ≃ Fin (Nat.card X) := by
+ letI := Fintype.ofFinite X
+ exact Fintype.equivFinOfCardEq Nat.card_eq_fintype_card.symm
+
+/-- One concrete finite allocation before the number of copies, word width, or input. -/
+noncomputable def allocation :
+ Allocation B z j (Nat.card (Register D E)) (Nat.card (PublicPort B z j)) := by
+ classical
+ let bank := MapBank.allocation B z j
+ letI : Finite (MapBank.PublicPort B z j) := Finite.of_injective bank.port bank.port.injective
+ exact ⟨(number _).toEmbedding, (number _).toEmbedding, (Fintype.equivFin E).symm⟩
+
+namespace Allocation
+
+variable {B z j} (A : Allocation B z j r k)
+
+/-- Selector scanner and decoder allocation within the entry table. The decoder's output-name
+ports are shared with the row bank's dispatch ordinals. -/
+def selectors : MapSelectorBank.Allocation (Selector B) r k where
+ register := Function.Embedding.inl.trans A.reg
+ port := (⟨Sum.elim Sum.inl (Sum.inr ∘ Sum.inl), by
+ intro a b h
+ cases a <;> cases b <;> simp_all⟩ : _ ↪ PublicPort B z j).trans A.pub
+
+/-- Restrict the entry table's registers and public ports to the selected-row driver and matrix
+bank. -/
+def bank : MapBank.Allocation B z j r k where
+ register := (Function.Embedding.inl.trans Function.Embedding.inr).trans A.reg
+ port := Function.Embedding.inr.trans A.pub
+
+/-- Assign one separate physical register per supply edge for its expected total payload width. -/
+def expected : E ↪ Fin r :=
+ ((Function.Embedding.inl.trans Function.Embedding.inr).trans Function.Embedding.inr).trans A.reg
+
+/-- Place the six private histogram-loop registers in the grouped interpreter's register file. -/
+def histReg : Fin 6 ↪ Fin r :=
+ ((Function.Embedding.inr.trans Function.Embedding.inr).trans Function.Embedding.inr).trans A.reg
+
+/-- Use the row bank's temporary register as the scratch word for the final width guard. -/
+def guardTemp := A.bank.rowReg .tmp
+
+/-- Compiled checks comparing each supply edge's accumulated offset with its expected payload
+width, in the allocation's edge order. -/
+noncomputable def guard : Flow r k :=
+ MapWidths.checkCode (fun e ↦ A.bank.rowReg (.offset (.inr e))) A.expected A.guardTemp
+ (List.ofFn A.edgeOrder)
+
+/-- Addresses of the selector scan and decoder instructions installed in the entry table, with
+their exits supplied by the enclosing interpreter. -/
+abbrev SelectorBody :=
+ {a : A.selectors.Address (selectorTable B) // A.selectors.inBody (selectorTable B) a = true}
+
+/-- Addresses of the row driver and matrix lookup bodies installed in the entry table, with the
+driver continuations supplied by the enclosing interpreter. -/
+noncomputable abbrev BankBody := {a : A.bank.Address // A.bank.inBody a = true}
+
+/-- Addresses of the selector phase, row bank, width checks, seven histogram instructions, and
+the success and rejection exits. -/
+noncomputable abbrev Address := A.SelectorBody ⊕ A.BankBody ⊕ Fin A.guard.length ⊕ Fin 7 ⊕ Bool
+
+variable (loc : A.Address → Fin p)
+
+/-- Address of the grouped map's normal continuation when `bad` is false or its common
+rejecting exit when `bad` is true. -/
+def exitPC (bad : Bool) := loc (.inr (.inr (.inr (.inr bad))))
+
+/-- Address in the complete entry table of histogram instruction `i`. -/
+def histPC (i : Fin 7) := loc (.inr (.inr (.inr (.inl i))))
+
+/-- Relocate a width-guard label to its numbered instruction in the complete entry table. -/
+noncomputable def guardPC (l : A.guard.Label) := loc (.inr (.inr (.inl (A.guard.labels l))))
+
+/-- Redirect the row driver's successful exit into the first guard instruction. -/
+noncomputable def bankPlace (a : A.bank.Address) : Fin p :=
+ if h : A.bank.inBody a then loc (.inr (.inl ⟨a, h⟩)) else
+ match a with
+ | .inr (.inr false) => A.guardPC loc A.guard.entry
+ | _ => A.exitPC loc true
+
+/-- Redirect a successful selector scan into the driver's first test. -/
+noncomputable def selectorPlace (a : A.selectors.Address (selectorTable B)) : Fin p :=
+ if h : A.selectors.inBody (selectorTable B) a then loc (.inl ⟨a, h⟩) else
+ match a with
+ | .exit false => (A.bank.driver (A.bankPlace loc)).pc 0
+ | _ => A.exitPC loc true
+
+/-- The relocated selector program whose successful decoder enters row dispatch and whose
+failure reaches the entry table's common rejecting exit. -/
+noncomputable def selector :=
+ A.selectors.program (selectorTable B) (A.selectorPlace loc)
+
+/-- The concrete four phases in the same address space. -/
+noncomputable def program : MapEntry.Program B z j p r k where
+ selector := A.selector loc
+ bank := A.bank
+ loc := A.bankPlace loc
+ edgeOrder := A.edgeOrder
+ expected := A.expected
+ guardTemp := A.guardTemp
+ guardPC := A.guardPC loc
+ histPC := A.histPC loc
+ histReg := A.histReg
+ done := A.exitPC loc false
+ bad := A.exitPC loc true
+
+/-- The complete code, including a common reject instruction and a normal exit. -/
+noncomputable def text : A.Address → Instr 2 p r k
+ | .inl a => A.selectors.text (selectorTable B) (A.selectorPlace loc) a.val
+ | .inr (.inl a) => A.bank.text (A.bankPlace loc) a.val
+ | .inr (.inr (.inl a)) =>
+ ((A.guard.code (A.guard.labels.symm a)).map
+ (fun l ↦ (l.map (A.guardPC loc)).getD (A.histPC loc 0))).emit (A.exitPC loc true)
+ | .inr (.inr (.inr (.inl i))) =>
+ PrivateLabels.instruction (A.histPC loc) A.histReg (A.exitPC loc false) i
+ | .inr (.inr (.inr (.inr false))) => .accept
+ | .inr (.inr (.inr (.inr true))) => .reject
+
+/-- Only the successful continuation can be replaced by an enclosing procedure. -/
+def installed : A.Address → Bool
+ | .inr (.inr (.inr (.inr false))) => false
+ | _ => true
+
+/-- The actual instructions discharge the common evaluator's control hypotheses. -/
+theorem linked (M : Machine w p r k) (h : ∀ a, A.installed a = true →
+ M.code (loc a) = (A.text loc a).resize w) : (A.program loc).Linked M := by
+ refine ⟨?_, rfl, rfl, rfl, rfl, rfl, ?_, ?_, ?_⟩
+ · apply A.selectors.linked (selectorTable B) (A.selectorPlace loc)
+ intro a ha
+ rw [selectorPlace, dite_eq_left ha, h _ rfl]
+ rfl
+ · change ∀ a : A.bank.Address, A.bank.inBody a = true →
+ M.code (A.bankPlace loc a) = (A.bank.text (A.bankPlace loc) a).resize w
+ intro a ha
+ have he : A.bankPlace loc a = loc (.inr (.inl ⟨a, ha⟩)) := by
+ simp only [bankPlace, ha, ↓reduceDIte]
+ rw [he]
+ exact h _ rfl
+ · change Flow.Linked M A.guard (A.guardPC loc) (A.histPC loc 0) (A.exitPC loc true)
+ constructor
+ intro l
+ have hl := h (.inr (.inr (.inl (A.guard.labels l)))) rfl
+ change M.code (A.guardPC loc l) = _ at hl
+ rw [hl]
+ simp [text]
+ · intro i
+ change M.code (A.histPC loc i) = _
+ rw [histPC, h _ rfl]
+ fin_cases i <;> rfl
+
+private theorem selectorSaved {q : Fin r} (h : ∀ a, q ≠ A.selectors.register a) :
+ (A.program loc).SelectorSaved q :=
+ ⟨⟨h (.inl 0), h (.inl 1), h (.inl 2), h (.inl 4), h (.inl 5), h (.inl 6), h (.inl 7)⟩,
+ fun i ↦ h (.inr i)⟩
+
+/-- Width targets and histogram registers survive both earlier stages. -/
+theorem separate : (A.program loc).Separate :=
+ ⟨fun _ ↦ A.selectorSaved loc (fun _ ↦ A.reg.injective.ne Sum.inr_ne_inl),
+ fun _ ↦ A.selectorSaved loc (fun _ ↦ A.reg.injective.ne Sum.inr_ne_inl),
+ fun _ ↦ A.selectorSaved loc (fun _ ↦ A.reg.injective.ne Sum.inr_ne_inl),
+ fun _ _ ↦ A.reg.injective.ne (Sum.inr_injective.ne Sum.inr_ne_inl),
+ fun _ _ ↦ A.reg.injective.ne (Sum.inr_injective.ne Sum.inr_ne_inl)⟩
+
+/-- The public selector codes precede the public row bank. Every decoded ordinal
+uses exactly the port tested by row dispatch. -/
+noncomputable def words (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (selector : Selector B ↪ BurstRAM.Word w)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) : PublicPort B z j → BurstRAM.Word w :=
+ Sum.elim (fun s ↦ MapLookup.widen fb (selectorCode B s))
+ (MapBank.Allocation.words fd fs selector ordinal)
+
+theorem public_spec (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (selector : Selector B ↪ BurstRAM.Word w)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) (M : Machine w p r k)
+ (h : ∀ a, M.publicData (A.pub a) = words fb fd fs selector ordinal a) :
+ (A.program loc).Public M selector ordinal fb fd fs :=
+ ⟨fun s ↦ h (.inl s), fun _ ↦ rfl, fun a ↦ h (.inr a)⟩
+
+/-- Install public values at their fixed addresses inside an enclosing bank. -/
+noncomputable def install (values : PublicPort B z j → BurstRAM.Word w)
+ (other : Fin k → BurstRAM.Word w) (q : Fin k) : BurstRAM.Word w := by
+ classical
+ exact if h : ∃ a, A.pub a = q then values h.choose else other q
+
+theorem install_at (values : PublicPort B z j → BurstRAM.Word w) (other : Fin k → BurstRAM.Word w)
+ (a : PublicPort B z j) : A.install values other (A.pub a) = values a := by
+ classical
+ have he : ∃ t, A.pub t = A.pub a := ⟨a, rfl⟩
+ rw [install, dite_eq_left he, A.pub.injective he.choose_spec]
+
+/-- Bijection numbering every symbolic instruction address of the complete grouped map entry. -/
+noncomputable def locations : A.Address ≃ Fin (Nat.card A.Address) := number _
+
+/-- Numerical fixed finite table; all relative and absolute targets above are its own PCs. -/
+noncomputable def template : Template (Nat.card A.Address) r k :=
+ let place := A.locations
+ ⟨2, (A.selector place).scan 0, fun i ↦ A.text place (place.symm i)⟩
+
+theorem template_linked (pub : Fin k → BurstRAM.Word w) :
+ (A.program A.locations).Linked (A.template.instantiate w pub) := by
+ apply A.linked
+ intro a _
+ simp [template, Template.instantiate]
+
+
+/-- Both final exits are genuine terminal instructions of the standalone template. -/
+theorem template_exits (pub : Fin k → BurstRAM.Word w) :
+ let P := A.program A.locations
+ let M := A.template.instantiate w pub
+ M.code P.bad = .reject ∧ M.code P.done = .accept := by
+ dsimp only
+ simp [template, Template.instantiate, program, exitPC, text, Instr.resize]
+
+/-- The fixed template instantiated with its actual selector, width and matrix words. -/
+noncomputable def machine (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (selector : Selector B ↪ BurstRAM.Word w)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) : Machine w (Nat.card A.Address) r k :=
+ A.template.instantiate w (A.install (words fb fd fs selector ordinal) (fun _ ↦ 0))
+
+theorem machine_public (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (selector : Selector B ↪ BurstRAM.Word w)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) :
+ (A.program A.locations).Public (A.machine fb fd fs selector ordinal)
+ selector ordinal fb fd fs :=
+ A.public_spec A.locations fb fd fs selector ordinal _ (A.install_at _ (fun _ ↦ 0))
+
+end Allocation
+
+end PairSimulation.MapEntryTable
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapExecutable.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapExecutable.lean
new file mode 100644
index 0000000000..891c2123af
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapExecutable.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.PairSimulationMapEntryTable
+import OAI.Computability.VPVNP.PairSimulationMapEntry
+import OAI.Computability.VPVNP.PairSimulationEntryWork
+
+/-!
+# Native execution of the grouped motif map
+
+The concrete table runs on arbitrary incident bit strings in a prepared workspace.
+A successful map increments the histogram at the emitted ordinals; a malformed
+map reaches the actual reject instruction with the original counters.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapEntryTable.Allocation
+
+open MotifGrid MotifBlocks MotifSelector MotifDemandPadding MotifConversion MotifEntry
+open BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k u w t : ℕ} (A : Allocation B z j r k)
+
+/-- The complete fixed machine computes exactly the grouped-map entry, with one
+private tick prefix on every path and the stated linear-in-copies budget. -/
+theorem native (demand : D → ℕ) (v : E → ℕ) (d : DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t)
+ (X : MapEntry.Program.Workspace (A.program A.locations) demand v d x t w)
+ (c : Config w (Nat.card A.Address) r) (hc : (A.program A.locations).Ready X c) :
+ let P := A.program A.locations
+ let M := A.machine fb fd fs sel (fun e ↦ ((ord e).val : BurstRAM.Word w))
+ P.Runs M c X.hist (MapNativeClock.cap B z j u)
+ ((MapStream.evaluate src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).map (List.map ord)) := by
+ dsimp only
+ rw [MapStream.evaluate_eq_run]
+ exact (A.program A.locations).native X _ (A.template_linked _) (A.separate A.locations)
+ sel ord fb fd fs (A.machine_public fb fd fs sel _) c hc
+
+/-- The shrinking and refreshing node records supply exactly these concrete demand
+and supply half-wire words. The machine returns the interpreter result at that call. -/
+theorem native_entryInput (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (alloc : Allocation B (demandGrid B hp I.demand) I.party r k)
+ (fb : B.selectorBits ≤ w) (fd : ∀ e, baseDemand B (demandGrid B hp I.demand) e ≤ w)
+ (fs : ∀ s e, basePayload B s e ≤ w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t) :
+ let demand := demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ inputBits) I.supplyBits
+ let P := alloc.program alloc.locations
+ let M := alloc.machine fb fd fs sel (fun e ↦ ((ord e).val : BurstRAM.Word w))
+ ∀ (X : MapEntry.Program.Workspace P I.demand I.payload demand supply t w)
+ (c : Config w (Nat.card alloc.Address) r), P.Ready X c →
+ P.Runs M c X.hist (MapNativeClock.cap B (demandGrid B hp I.demand) I.party
+ (repetitions B I.demand))
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord)) := by
+ intro demand supply P M X c ready
+ exact (alloc.program alloc.locations).native X _ (alloc.template_linked _)
+ (alloc.separate alloc.locations) sel ord fb fd fs (alloc.machine_public fb fd fs sel _) c ready
+
+end PairSimulation.MapEntryTable.Allocation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapFinish.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapFinish.lean
new file mode 100644
index 0000000000..9968a32581
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapFinish.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairSimulationMapTotalCheck
+import OAI.Computability.VPVNP.PairSimulationPrivateLabels
+import OAI.Computability.VPVNP.PairSimulationMapStream
+
+/-!
+# Finishing a grouped map in the native private workspace
+
+The entry's complete payload vector is checked before any parameter counter
+is incremented. A successful check processes the emitted ordinals in copy
+order, preserving the multiplicity of repeated labels.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapFinish
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM MotifSelector
+open scoped Fin.CommRing
+
+variable {J D E Q V : Type*} {w p r k t u bits : ℕ}
+
+open private nameRun_value from OAI.Computability.VPVNP.MotifEntry
+
+/-- Split the actual metered entry into the selector stage, the full-vector
+test and the list of exact local parameter names. -/
+theorem entry_value [DecidableEq J] [Fintype D] [Fintype E]
+ (src dst : D → J) (a b : D → ℕ) (G : Supply J E) (width : Q → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e ↦ MotifSelector.Word (width s e)) j → V)
+ (table : List Q) (code : Q ↪ MotifSelector.Word bits) (v : E → ℕ) (j : J)
+ (d : MotifEntry.DemandBits src dst b j) (x : Half G (fun e ↦ Fin (v e + u * bits) → Bool) j) :
+ (MotifEntry.run src dst a b G width lookup table code v j d x).1 =
+ (MotifEntry.selectorRun G table code v j x).1.bind fun θ ↦
+ if ∀ e, v e = totalWidth width θ e then some (List.ofFn fun i ↦
+ MapStream.readRow src dst a b G width lookup v j d x i (θ i)
+ (fun e ↦ MotifEntry.offset (fun l ↦ width (θ l) e) i)) else none := by
+ unfold MotifEntry.run
+ dsimp only
+ cases h : (MotifEntry.selectorRun G table code v j x).1 with
+ | none => rfl
+ | some θ =>
+ dsimp only
+ rw [MotifEntry.totalRun_spec]
+ simp only [decide_eq_true_eq, Option.bind_some]
+ split
+ · simp only [(MotifEntry.scanCopies_spec _).1, nameRun_value, MapStream.readRow]
+ · rfl
+
+/-- The fixed registers used by the counter loop are initialized before
+checking the width vector. The width comparisons do not change them. -/
+structure HistogramReady (reg : Fin 6 ↪ Fin r) (src base : ℕ) (c : Config w p r) : Prop where
+ cursor : c.reg (reg 0) = (src : BurstRAM.Word w)
+ stop : c.reg (reg 1) = ((src + u : ℕ) : BurstRAM.Word w)
+ base : c.reg (reg 2) = (base : BurstRAM.Word w)
+ one : c.reg (reg 3) = 1
+
+open scoped Classical in
+/-- Follow the actual width guards and the native private label scan in one
+machine. Every syntactic width mismatch exits before its first counter write. -/
+theorem native (width : Q → E → ℕ) (θ : Fin u → Q) (v : E → ℕ) (es : List E)
+ (cover : ∀ e, e ∈ es) (lhs rhs : E → Fin r) (tmp : Fin r) (M : Machine w p r k)
+ (guardPC : (MapWidths.checkCode lhs rhs tmp es : Flow r k).Label → Fin p)
+ (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done bad : Fin p)
+ (guards : Flow.Linked M (MapWidths.checkCode lhs rhs tmp es) guardPC (pc 0) bad)
+ (counts : PrivateLabels.Linked M pc reg done) (src base : ℕ)
+ (names : Fin u → Fin t) (c : Config w p r)
+ (hc : c.pc = guardPC (MapWidths.checkCode lhs rhs tmp es : Flow r k).entry)
+ (hx : ∀ e, (c.reg (lhs e)).val = totalWidth width θ e) (hy : ∀ e, (c.reg (rhs e)).val = v e)
+ (ready : HistogramReady (u := u) reg src base c) (hfit : base + t ≤ 2 ^ w)
+ (apart : src + u ≤ base ∨ base + t ≤ src) (endFit : src + u < 2 ^ w)
+ (data : ∀ i : Fin u, c.privateMem ((src + i.val : ℕ) : BurstRAM.Word w) =
+ ((names i).val : BurstRAM.Word w)) :
+ ∃ n out, n ≤ (es.length + 1) + (7 * u + 1) ∧ Prefix M c (List.replicate n .tick) out ∧
+ out.persistent = c.persistent ∧
+ if ∀ e, v e = totalWidth width θ e then out.pc = done ∧
+ out.privateMem = PrivateLabels.accumulate base (List.ofFn names) c.privateMem
+ else out.pc = bad ∧ out.privateMem = c.privateMem := by
+ classical
+ obtain ⟨g, hg, pre⟩ := MapWidths.totalCheck_native width θ v es cover lhs rhs tmp M guardPC
+ (pc 0) bad guards c hc hx hy
+ by_cases valid : ∀ e, v e = totalWidth width θ e
+ · rw [ite_eq_left valid] at pre
+ let mid := {c with pc := pc 0}
+ let ns := List.ofFn names
+ have hlen : ns.length = u := List.length_ofFn
+ have stored (i : Fin ns.length) : mid.privateMem ((src + i.val : ℕ) : BurstRAM.Word w) =
+ (ns[i.val].val : BurstRAM.Word w) := by
+ have hi : i.val < u := hlen ▸ i.isLt
+ simpa [ns, mid] using data ⟨i.val, hi⟩
+ obtain ⟨out, run, hpc, mem, per⟩ := PrivateLabels.run_separated counts ns src base mid rfl
+ ready.cursor
+ (by rw [hlen]; exact ready.stop) ready.base ready.one hfit (by simpa only [hlen] using apart)
+ (by simpa only [hlen] using endFit) stored
+ refine ⟨g + (7 * u + 1), out, Nat.add_le_add_right hg _, ?_, per, ?_⟩
+ · rw [List.replicate_add, ← hlen]
+ exact pre.append run
+ · rw [ite_eq_left valid]
+ exact ⟨hpc, mem⟩
+ · rw [ite_eq_right valid] at pre
+ exact ⟨g, {c with pc := bad}, hg.trans (Nat.le_add_right ..), pre, rfl,
+ by rw [ite_eq_right valid]; exact ⟨rfl, rfl⟩⟩
+
+end PairSimulation.MapFinish
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapFinishExact.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapFinishExact.lean
new file mode 100644
index 0000000000..1028cfc2d1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapFinishExact.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PairSimulationMapFinish
+
+/-!
+# Exact native time for the successful width check and label histogram
+
+Each matching width consumes one guard instruction, and a final guard transfers
+control to the histogram scan. That scan increments one private counter for each
+emitted label, including repetitions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapWidths
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM
+
+variable {E : Type*} {w p r k : ℕ}
+
+/-- A successful guard sequence reads every tested pair and reaches the final guard. -/
+theorem checkSteps_of_all (eq : E → Bool) (es : List E) (all : ∀ e ∈ es, eq e = true) :
+ checkSteps eq es = es.length + 1 := by
+ induction es with
+ | nil => rfl
+ | cons e es ih =>
+ rw [checkSteps, ite_eq_left (all e List.mem_cons_self), List.length_cons,
+ ih (fun i hi => all i (List.mem_cons_of_mem e hi))]
+ omega
+
+/-- The complete successful guard chain leaves the counter operands intact. -/
+theorem checkCode_success (lhs rhs : E → Fin r) (scratch : Fin r) (es : List E)
+ (M : Machine w p r k) (label : (checkCode lhs rhs scratch es : Flow r k).Label → Fin p)
+ (stop bad : Fin p) (link : Flow.Linked M (checkCode lhs rhs scratch es) label stop bad)
+ (c : Config w p r) (hc : c.pc = label (checkCode lhs rhs scratch es : Flow r k).entry)
+ (valid : ∀ e ∈ es, c.reg (lhs e) = c.reg (rhs e)) :
+ Prefix M c (List.replicate (es.length + 1) .tick) {c with pc := stop} := by
+ let same := fun e ↦ decide (c.reg (lhs e) = c.reg (rhs e))
+ have all (e : E) (he : e ∈ es) : same e = true := decide_eq_true (valid e he)
+ have pre := checkCode_native lhs rhs scratch es M label stop bad link c hc
+ change Prefix M c (List.replicate (checkSteps same es) .tick)
+ {c with pc := if es.all same then stop else bad} at pre
+ rwa [checkSteps_of_all same es all, ite_eq_left (List.all_eq_true.mpr all)] at pre
+
+end PairSimulation.MapWidths
+
+namespace PairSimulation.MapFinish
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM MotifSelector
+open scoped Fin.CommRing
+
+variable {E Q : Type*} {w p r k t u : ℕ}
+
+/-- Matching payload widths give the exact successful path, including the empty
+width vector and an empty sequence of emitted labels. -/
+theorem native_success (width : Q → E → ℕ) (θ : Fin u → Q) (v : E → ℕ) (es : List E)
+ (lhs rhs : E → Fin r) (tmp : Fin r) (M : Machine w p r k)
+ (guardPC : (MapWidths.checkCode lhs rhs tmp es : Flow r k).Label → Fin p)
+ (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done bad : Fin p)
+ (guards : Flow.Linked M (MapWidths.checkCode lhs rhs tmp es) guardPC (pc 0) bad)
+ (counts : PrivateLabels.Linked M pc reg done) (src base : ℕ)
+ (names : Fin u → Fin t) (c : Config w p r)
+ (hc : c.pc = guardPC (MapWidths.checkCode lhs rhs tmp es : Flow r k).entry)
+ (hx : ∀ e, (c.reg (lhs e)).val = totalWidth width θ e) (hy : ∀ e, (c.reg (rhs e)).val = v e)
+ (ready : HistogramReady (u := u) reg src base c) (hfit : base + t ≤ 2 ^ w)
+ (apart : src + u ≤ base ∨ base + t ≤ src) (endFit : src + u < 2 ^ w)
+ (data : ∀ i : Fin u, c.privateMem ((src + i.val : ℕ) : BurstRAM.Word w) =
+ ((names i).val : BurstRAM.Word w))
+ (valid : ∀ e, v e = totalWidth width θ e) :
+ ∃ out, Prefix M c (List.replicate ((es.length + 1) + (7 * u + 1)) .tick) out ∧
+ out.pc = done ∧
+ out.privateMem = PrivateLabels.accumulate base (List.ofFn names) c.privateMem ∧
+ out.persistent = c.persistent := by
+ let mid := {c with pc := pc 0}
+ have pre := MapWidths.checkCode_success lhs rhs tmp es M guardPC (pc 0) bad guards c hc
+ (fun e _ => Fin.ext ((hx e).trans ((valid e).symm.trans (hy e).symm)))
+ let ns := List.ofFn names
+ have hlen : ns.length = u := List.length_ofFn
+ have stored (i : Fin ns.length) : mid.privateMem ((src + i.val : ℕ) : BurstRAM.Word w) =
+ (ns[i.val].val : BurstRAM.Word w) := by
+ simpa only [ns, List.getElem_ofFn] using data ⟨i.val, hlen ▸ i.isLt⟩
+ obtain ⟨out, run, hpc, mem, per⟩ := PrivateLabels.run_separated counts ns src base mid rfl
+ ready.cursor (hlen ▸ ready.stop) ready.base ready.one hfit (hlen ▸ apart) (hlen ▸ endFit) stored
+ refine ⟨out, ?_, hpc, mem, per⟩
+ rw [List.replicate_add, ← hlen]
+ exact pre.append run
+
+end PairSimulation.MapFinish
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerAction.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerAction.lean
new file mode 100644
index 0000000000..6ecb945bf6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerAction.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.PairSimulationMapHandlerImage
+import OAI.Computability.VPVNP.PairSimulationMapCallExact
+import OAI.Computability.VPVNP.PairSimulationMapWriterClock
+import OAI.Computability.VPVNP.PairSimulationMapScratch
+
+/-!
+# Deterministic actions of selected grid and party handlers
+
+An action depends on the recorded motif entry, the six descriptor operands,
+external memory and the incoming upper scratch. It is defined at exactly the
+successful entries. The chronological trace includes the external reads of the
+argument writer and all ticks of the initialized and lowered map.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapHandlerImage.Family
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe MapConstants
+open private RegisterSetup.no_choices from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+open private tick_log from OAI.Computability.VPVNP.PairSimulationMapArgumentWriter
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'} {t shared w : ℕ}
+ (F : Family B t shared) (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (hw : widthThreshold B ≤ w) (pub : Fin 5 → BurstRAM.Word w) (state : BurstRAM.Word w)
+ (m : Memory w)
+
+local notation "idx" => (demandGrid B hp I.demand, I.party)
+local notation "L" => F.layout idx
+local notation "d" => demandBits src dst I.party I.demandBits
+local notation "x" => mapHalf G (fun _ ↦ inputBits) I.supplyBits
+local notation "names" => Prod.fst (runEntry B hp I.demand I.payload I.party d x)
+
+/-- The typed field bits fix all map branch lengths, while the six operands
+and external memory fix the precise read addresses and returned words. -/
+noncomputable def successEvents : List (Event w) :=
+ let selected := (selectorRun G (selectorTable B) (selectorCode B) I.payload I.party x).1
+ MapArgumentWriter.events (F.base idx) (F.fields idx) pub state m ++
+ List.replicate (MapInline.factor L F.ordinal * selected.elim 0 (entryTicks hp I L F.ordinal hw))
+ .tick
+
+theorem successEvents_noChoices : choiceBits (F.successEvents hp I hw pub state m) = [] := by
+ simp only [successEvents, MapArgumentWriter.events, PrimedInputRAM.Flow.choiceBits_append,
+ RegisterSetup.no_choices, (tick_log _).1, List.nil_append]
+
+/-- All external reads in the full visit belong to the descriptor expressions. -/
+theorem successEvents_readsFrom (data : ℕ → Prop)
+ (baseSafe : (F.base idx).ReadsFrom data pub state m)
+ (fieldSafe : ∀ a, (F.field idx a).ReadsFrom data pub state m) :
+ SourceTransport.Reads data (F.successEvents hp I hw pub state m) := by
+ intro a v h
+ rcases List.mem_append.mp h with read | tick
+ · exact MapArgumentWriter.events_readsFrom (F.base idx) (F.fields idx) data pub state m
+ baseSafe (fun j ↦ fieldSafe ((F.layout idx).args.symm j)) a v read
+ · cases List.eq_of_mem_replicate tick
+
+theorem successEvents_noWrites :
+ SourceTransport.Writes (fun _ ↦ False) (F.successEvents hp I hw pub state m) := by
+ intro a v h
+ rcases List.mem_append.mp h with write | tick
+ · exact MapArgumentWriter.events_noWrites (F.base idx) (F.fields idx) pub state m a v write
+ · cases List.eq_of_mem_replicate tick
+
+variable (X : MapEntry.Program.Workspace
+ (MapInline.callProgram (F.layout (demandGrid B hp I.demand, I.party)))
+ I.demand I.payload (demandBits src dst I.party I.demandBits)
+ (mapHalf G (fun _ ↦ inputBits) I.supplyBits) t w)
+ (endAddr : ℕ) (saved : DFS.Scratch w endAddr)
+
+/-- The selected occurrence either rejects or returns its native trace and
+complete outgoing scratch to the enclosing map loop. -/
+noncomputable def action : Option (List (Event w) × DFS.Scratch w endAddr) :=
+ let layout := L
+ if (names).isSome then
+ some (F.successEvents hp I hw pub state m, MapScratch.upper layout.core layout.args
+ (layout.corePC layout.locations) X ((F.base idx).eval pub state m)
+ (selectorWord B (fits_of_threshold B hw).2.2.2) F.ordinal endAddr saved)
+ else none
+
+theorem action_none_iff : F.action hp I hw pub state m X endAddr saved = none ↔ names = none := by
+ cases h : names <;> simp [action, h]
+
+theorem action_isSome :
+ (F.action hp I hw pub state m X endAddr saved).isSome = (names).isSome := by
+ cases h : names <;> simp [action, h]
+
+/-- A successful action returns precisely the chronological trace and the
+prescribed update of the incoming upper scratch. -/
+theorem action_some_iff {es : List (Event w)} {updated : DFS.Scratch w endAddr} :
+ let layout := L
+ F.action hp I hw pub state m X endAddr saved = some (es, updated) ↔
+ (names).isSome = true ∧ es = F.successEvents hp I hw pub state m ∧
+ updated = MapScratch.upper layout.core layout.args (layout.corePC layout.locations)
+ X ((F.base idx).eval pub state m) (selectorWord B (fits_of_threshold B hw).2.2.2)
+ F.ordinal endAddr saved := by
+ dsimp only
+ cases good : (names).isSome
+ · simp only [action, good, Bool.false_eq_true, ↓reduceIte, reduceCtorEq, false_and]
+ · simp only [action, good, ↓reduceIte, Option.some.injEq, Prod.mk.injEq, true_and]
+ exact and_congr eq_comm eq_comm
+
+theorem action_noChoices {es : List (Event w)} {updated : DFS.Scratch w endAddr}
+ (got : F.action hp I hw pub state m X endAddr saved = some (es, updated)) :
+ choiceBits es = [] := by
+ dsimp only [action] at got
+ split at got
+ · rw [← (Prod.mk.inj (Option.some.inj got)).1]
+ exact F.successEvents_noChoices hp I hw pub state m
+ · contradiction
+
+end PairSimulation.MapHandlerImage.Family
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerClock.lean
new file mode 100644
index 0000000000..36a684dd41
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerClock.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.PairSimulationMapHandlerImage
+import OAI.Computability.VPVNP.PairSimulationMapChainWork
+
+/-!
+# Instruction and probe bounds for the fixed map handler family
+
+The descriptor writer's instruction count and its external probes are
+fixed for each grid point and party. The rest of the call uses only private
+instructions. These bounds also cover prefixes ending at rejection.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapHandlerImage.Family
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MapConstants
+open BurstRAM LocalHistory Compression
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'} {t s w : ℕ}
+ (F : Family B t s)
+
+/-- A handler initializes its descriptor, selects the entry, then runs the table. -/
+noncomputable def clock (i : Index B) (u : ℕ) : ℕ :=
+ let L := F.layout i
+ MapArgumentWriter.clock (F.base i) (F.fields i) + MapInline.factor L F.ordinal *
+ (L.lines.length + (1 + 3 * (MapPortAgreement.ports G i.2 L.core.edgeOrder).length) +
+ MapNativeClock.cap B i.1 i.2 u)
+
+/-- Only the compiled external loads in the descriptor writer charge probes. -/
+noncomputable def probes (i : Index B) : ℕ :=
+ ∑ j, ((MapArgumentWriter.recipes (F.base i) (F.fields i)) j).loads
+
+private noncomputable def init (i : Index B) : ℕ :=
+ (F.layout i).lines.length + (1 + 3 * (MapPortAgreement.ports G i.2
+ (F.layout i).core.edgeOrder).length)
+
+private noncomputable def localFactor (i : Index B) : ℕ :=
+ MapArgumentWriter.clock (F.base i) (F.fields i) + MapInline.factor (F.layout i) F.ordinal *
+ (init F i + 1)
+
+/-- One fixed multiplier covers descriptor writing, initialization and literal lowering. -/
+noncomputable def clockFactor : ℕ := ∑ i, F.localFactor i
+
+/-- The finite bound on external loads is independent of all repetition counts. -/
+noncomputable def probeBound : ℕ := ∑ i, F.probes i
+
+theorem probes_le (i : Index B) : F.probes i ≤ F.probeBound :=
+ Finset.single_le_sum (fun a _ ↦ Nat.zero_le (F.probes a)) (Finset.mem_univ i)
+
+theorem clock_le (i : Index B) (u : ℕ) :
+ F.clock i u ≤ F.clockFactor * (MapNativeClock.cap B i.1 i.2 u + 1) := by
+ let n := MapNativeClock.cap B i.1 i.2 u
+ let a := MapArgumentWriter.clock (F.base i) (F.fields i)
+ let h := MapInline.factor (F.layout i) F.ordinal
+ have hi : a + h * (init F i + 1) ≤ F.clockFactor :=
+ Finset.single_le_sum (fun j _ ↦ Nat.zero_le (F.localFactor j)) (Finset.mem_univ i)
+ calc
+ _ ≤ (a + h * (init F i + 1)) * (n + 1) := by
+ rw [Nat.add_mul, Nat.mul_assoc]
+ apply Nat.add_le_add (Nat.le_mul_of_pos_right a (Nat.succ_pos n))
+ apply Nat.mul_le_mul_left
+ change init F i + n ≤ _
+ rw [Nat.add_mul, Nat.one_mul, Nat.mul_add, Nat.mul_one]
+ omega
+ _ ≤ _ := Nat.mul_le_mul_right _ hi
+
+/-- Apply the bounds to the exact instruction and probe conclusions of the native handler.
+Every prefix has a smaller resource use on that same path. -/
+theorem trace_le (i : Index B) (u : ℕ) (trace pre : List (Event w))
+ (len : trace.length ≤ F.clock i u) (loads : countProbes trace = F.probes i)
+ (isPrefix : pre <+: trace) :
+ pre.length ≤ F.clockFactor * (MapNativeClock.cap B i.1 i.2 u + 1) ∧
+ countProbes pre ≤ F.probeBound := by
+ refine ⟨isPrefix.length_le.trans (len.trans (F.clock_le i u)), ?_⟩
+ obtain ⟨tail, rfl⟩ := isPrefix
+ rw [countProbes_append] at loads
+ have bound := F.probes_le i
+ omega
+
+variable {S : BlockSchedule K} (T : S.Templates) {ss sr : ℕ}
+ (shrink : Family T.shrink t ss) (refresh : Family T.refresh t sr)
+
+open scoped Classical in
+/-- Instruction bound and external probe count for a map invocation. Shrink and refresh use the
+handler selected by the demand grid point and party, with the clock evaluated at the
+demand's repetition count. A node without a lookup costs zero in both coordinates. -/
+noncomputable def costs {d : ℕ} : MapInvocation T d → ℕ × ℕ
+ | .shrink x _ =>
+ let i := (demandGrid T.shrink ShrinkMotif.demandMass_pos x.demand, x.party)
+ (shrink.clock i (repetitions T.shrink x.demand), shrink.probes i)
+ | .refresh x _ =>
+ let i := (demandGrid T.refresh (fun _ ↦ zero_lt_one) x.demand, x.party)
+ (refresh.clock i (repetitions T.refresh x.demand), refresh.probes i)
+ | .noLookup => (0, 0)
+
+/-- The same two fixed constants can be used at every selected shrink and refresh node. -/
+theorem costs_le {d : ℕ} (m : MapInvocation T d) :
+ (costs T shrink refresh m).1 ≤
+ (max shrink.clockFactor refresh.clockFactor + 1) * (m.nativeCap T + 1) ∧
+ (costs T shrink refresh m).2 ≤ max shrink.probeBound refresh.probeBound := by
+ classical
+ cases m with
+ | shrink x _ =>
+ exact ⟨(shrink.clock_le ..).trans (Nat.mul_le_mul_right _
+ ((le_max_left ..).trans (Nat.le_succ _))), (shrink.probes_le _).trans (le_max_left ..)⟩
+ | refresh x _ =>
+ exact ⟨(refresh.clock_le ..).trans (Nat.mul_le_mul_right _
+ ((le_max_right ..).trans (Nat.le_succ _))), (refresh.probes_le _).trans (le_max_right ..)⟩
+ | noLookup => exact ⟨Nat.zero_le _, Nat.zero_le _⟩
+
+/-- Charge the actual selected maps in their placement subtree to the same occurrence
+count used for the child fields and the vertex history. -/
+theorem probeTotal_le {A : Type*} {N Y : NetworkKernel.Network}
+ (c : NetworkKernel.TermChain A N Y) (calls : MapInputs T c) {L : ℕ} (hl : c.AllRecordsLe L)
+ (leaf count : N.Site → ℕ)
+ (h : ∀ v, leaf v ≤ count v * max shrink.probeBound refresh.probeBound) :
+ ∀ v, mapAndLeafCost (fun m ↦ (costs T shrink refresh m).2) c calls leaf v ≤
+ c.occurrences count v * max shrink.probeBound refresh.probeBound :=
+ mapAndLeafCost_le _ c calls (fun _ _ m ↦ (costs_le T shrink refresh m).2) hl leaf count h
+
+end PairSimulation.MapHandlerImage.Family
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerExact.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerExact.lean
new file mode 100644
index 0000000000..560cc6d58e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerExact.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.PairSimulationMapHandlerAction
+import OAI.Computability.VPVNP.PairSimulationMapHandlerRun
+import OAI.Computability.VPVNP.PairSimulationMapWrittenExact
+
+/-!
+# Native executions of the deterministic grid and party actions
+
+A successful action fixes the chronological event list and the complete upper
+scratch of the same execution prefix. An unsuccessful action executes into a
+rejecting instruction of its selected handler.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapHandlerImage.Family
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe MapConstants
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'} {t shared p r w : ℕ}
+ (F : Family B t shared) (pc : F.Address → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r) (own : F.PrivateReg ↪ Fin r)
+ (advance : Fin p) (M : Machine w p r 11)
+ (installed : ∀ a, M.code (pc a) = (F.text pc dfs saved common own advance a).resize w)
+ (banks : F.Apart dfs saved common own)
+
+include installed banks in
+theorem native_success_exact (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (hw : widthThreshold B ≤ w) (c : Config w p r) (m : Memory w) :
+ let i : Index B := (demandGrid B hp I.demand, I.party)
+ let L := F.layout i
+ let d := demandBits src dst I.party I.demandBits
+ let x := mapHalf G (fun _ ↦ inputBits) I.supplyBits
+ let inputs := F.inputs dfs saved common i
+ let pub := fun j : Fin 5 ↦ c.reg (inputs j.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := (F.base i).eval pub state m
+ let outside := fun q : BurstRAM.Word w ↦ q.val < addr.val ∨
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val
+ let names := (runEntry B hp I.demand I.payload I.party d x).1.map (List.map F.ordinal)
+ ∀ (X : MapEntry.Program.Workspace (MapInline.callProgram L) I.demand I.payload d x t w)
+ (endAddr : ℕ) (savedScratch : DFS.Scratch w endAddr),
+ DFS.scratch endAddr c.privateMem = savedScratch → names.isSome = true →
+ c.pc = F.target pc i →
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ 2 ^ w →
+ (∀ a, (F.field i a).eval pub state m =
+ MapCallSetup.values L.core (L.corePC L.locations) X a) →
+ MapArgumentWriter.ResidentFields L.core (L.corePC L.locations) X addr c.privateMem →
+ (∀ l : Fin t, outside ((X.hist + l.val : ℕ) : BurstRAM.Word w)) →
+ (∀ (l : Fin t) (j : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (j.val : BurstRAM.Word w)) →
+ let es := F.successEvents hp I hw pub state m
+ ∃ out, NodeArguments.ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ MapArgumentWriter.clock (F.base i) (F.fields i) + MapInline.factor L F.ordinal *
+ (L.lines.length + (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B i.1 i.2 (repetitions B I.demand)) ∧
+ countProbes es = ∑ j, ((MapArgumentWriter.recipes (F.base i) (F.fields i)) j).loads ∧
+ choiceBits es = [] ∧ out.pc = advance ∧
+ out.persistent = c.persistent ∧
+ (∀ q, (∀ a : F.Local i, q ≠ F.localReg own i a) → out.reg q = c.reg q) ∧
+ (∀ q, outside q → MapCallSetup.Outside L.core (L.corePC L.locations) X q →
+ out.privateMem q = c.privateMem q) ∧
+ (∀ l : Fin t, out.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) +
+ ((names.getD []).count l : BurstRAM.Word w)) ∧
+ DFS.scratch endAddr out.privateMem = MapScratch.upper L.core L.args (L.corePC L.locations)
+ X addr (selectorWord B (fits_of_threshold B hw).2.2.2) F.ordinal endAddr
+ savedScratch := by
+ intro i L d x inputs pub state addr outside names X endAddr savedScratch incoming good start fit
+ values resident hist directory es
+ have run : (run src dst (baseDemand B i.1) I.demand G (basePayload B) (lookup B i.1)
+ (selectorTable B) (selectorCode B) I.payload i.2 d x).1.isSome = true := by
+ simpa only [names, i, runEntry, Option.isSome_map] using good
+ obtain ⟨θ, selected, valid⟩ := MapScratch.sequence_of_success run
+ let V := F.placement pc own advance i
+ obtain ⟨writer, body, done, _⟩ := F.links pc dfs saved common own advance M installed i
+ obtain ⟨out, pre, len, reads, choice, exit, per, regs, memory, histogram, post, _⟩ :=
+ MapArgumentWriter.written_success_exact hp I L F.ordinal V (F.base i) (F.field i) X (F.vm own i)
+ inputs (F.aux own i) (F.writerPC pc i) M writer (F.vm_safe dfs saved common own banks i)
+ (F.vm_aux own i) (F.pointer pc own advance i) body hw c m start fit values resident
+ hist directory θ selected valid
+ have trace : es = MapArgumentWriter.events (F.base i) (F.fields i) pub state m ++
+ List.replicate (MapInline.factor L F.ordinal * entryTicks hp I L F.ordinal hw θ) .tick := by
+ exact congrArg (fun pick : Option (Fin (repetitions B I.demand) → Selector B) ↦
+ MapArgumentWriter.events (F.base i) (F.fields i) pub state m ++
+ List.replicate (MapInline.factor L F.ordinal * pick.elim 0 (entryTicks hp I L F.ordinal hw))
+ (.tick : Event w)) selected
+ rw [trace]
+ refine ⟨out, pre, len, reads, choice, exit.trans done, per, ?_, memory, histogram, ?_⟩
+ · intro q apart
+ apply regs q
+ · apply InlinePublic.linked_privateReg
+ rintro ⟨v, eq⟩
+ exact apart (.inr (.inr v)) eq.symm
+ · exact fun v ↦ apart (.inl v)
+ · intro v
+ fin_cases v <;> exact apart _
+ · exact MapScratch.exact_upper L.core L.args (L.corePC L.locations) X addr
+ (selectorWord B (fits_of_threshold B hw).2.2.2) F.ordinal endAddr savedScratch
+ incoming run post
+
+include installed banks in
+/-- Both branches of the selected action run on the actual linked image.
+A missing entry rejects every fuel bound and incoming choice stream. -/
+theorem action_native (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (hw : widthThreshold B ≤ w) (c : Config w p r) (m : Memory w) :
+ let i : Index B := (demandGrid B hp I.demand, I.party)
+ let L := F.layout i
+ let d := demandBits src dst I.party I.demandBits
+ let x := mapHalf G (fun _ ↦ inputBits) I.supplyBits
+ let inputs := F.inputs dfs saved common i
+ let pub := fun j : Fin 5 ↦ c.reg (inputs j.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := (F.base i).eval pub state m
+ let outside := fun q : BurstRAM.Word w ↦ q.val < addr.val ∨
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val
+ let names := (runEntry B hp I.demand I.payload I.party d x).1.map (List.map F.ordinal)
+ ∀ (X : MapEntry.Program.Workspace (MapInline.callProgram L) I.demand I.payload d x t w)
+ (endAddr : ℕ) (savedScratch : DFS.Scratch w endAddr),
+ DFS.scratch endAddr c.privateMem = savedScratch →
+ c.pc = F.target pc i →
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ 2 ^ w →
+ (∀ a, (F.field i a).eval pub state m =
+ MapCallSetup.values L.core (L.corePC L.locations) X a) →
+ MapArgumentWriter.ResidentFields L.core (L.corePC L.locations) X addr c.privateMem →
+ (∀ l : Fin t, outside ((X.hist + l.val : ℕ) : BurstRAM.Word w)) →
+ (∀ (l : Fin t) (j : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (j.val : BurstRAM.Word w)) →
+ match F.action hp I hw pub state m X endAddr savedScratch with
+ | none => ∀ bs, ¬ DFS.Returns M c m bs
+ | some (es, updated) => ∃ out, NodeArguments.ChildScan.Prefix M m c out [] es ∧
+ out.pc = advance ∧ out.persistent = c.persistent ∧
+ (∀ q, (∀ a : F.Local i, q ≠ F.localReg own i a) → out.reg q = c.reg q) ∧
+ (∀ q, outside q → MapCallSetup.Outside L.core (L.corePC L.locations) X q →
+ out.privateMem q = c.privateMem q) ∧
+ (∀ l : Fin t, out.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) +
+ ((names.getD []).count l : BurstRAM.Word w)) ∧
+ DFS.scratch endAddr out.privateMem = updated := by
+ intro i L d x inputs pub state addr outside names X endAddr savedScratch incoming start fit
+ values resident hist directory
+ cases got : F.action hp I hw pub state m X endAddr savedScratch with
+ | none =>
+ have miss := (F.action_none_iff hp I hw pub state m X endAddr savedScratch).mp got
+ obtain ⟨out, es, pre, _, _, _, exit, _⟩ := F.native pc dfs saved common own advance M
+ installed banks hp I hw c m X start fit values resident hist directory
+ have reject : M.code out.pc = .reject := by
+ simpa only [miss, Option.map_none, Option.isSome_none, Bool.false_eq_true, ↓reduceIte]
+ using exit
+ intro bs returns
+ obtain ⟨fuel, rep, ran⟩ := (pre.returns bs).mp returns
+ have step : M.program.step out = .reject := by
+ change (M.code out.pc).run M.publicData out = _
+ rw [reject]
+ rfl
+ cases fuel <;> simp only [execute, step, reduceCtorEq] at ran
+ | some pair =>
+ obtain ⟨es, updated⟩ := pair
+ obtain ⟨ok, trace, final⟩ :=
+ (F.action_some_iff hp I hw pub state m X endAddr savedScratch).mp got
+ have good : names.isSome = true := by simpa only [names, Option.isSome_map] using ok
+ obtain ⟨out, pre, _, _, _, endPC, per, regs, mem, counts, scratch⟩ :=
+ F.native_success_exact pc dfs saved common own advance M installed banks hp I hw c m X
+ endAddr savedScratch incoming good start fit values resident hist directory
+ exact ⟨out, trace ▸ pre, endPC, per, regs, mem, counts, scratch.trans final.symm⟩
+
+end PairSimulation.MapHandlerImage.Family
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerFrame.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerFrame.lean
new file mode 100644
index 0000000000..f3b2b19776
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerFrame.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.PairSimulationMapHandlerExact
+import OAI.Computability.VPVNP.PairSimulationMapHandlerOperand
+import OAI.Computability.VPVNP.PairShrinkRoleStages
+
+/-!
+# The physical map handler preserves the DFS stack and role registers
+
+All writable arrays of a prepared map call start above the exclusive end
+of the saved stack. Successful visits therefore update only the upper scratch
+according to the exact action. Unsuccessful visits execute to a rejecting opcode.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapHandlerOperand
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MapConstants MotifEntry
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords.PhaseRecipe MapHandlerImage
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'} {t shared p r w : ℕ}
+ (F : MapHandlerImage.Family B t shared) (hp : ∀ i, 0 < p₀ i) (I : LocalHistory.EntryInput B)
+ (X : Workspace F hp I (w := w)) (endAddr : ℕ)
+
+/-- Numerical placement of every interval written by the handler. -/
+structure Bounds (descriptor : BurstRAM.Word w) : Prop where
+ descriptorBase : endAddr ≤ descriptor.val
+ selectorBase : endAddr ≤ X.source
+ labelBase : endAddr ≤ X.target
+ histogramBase : endAddr ≤ X.hist
+ directoryBase : endAddr ≤ X.directory.val
+ directoryRoom : X.directory.val +
+ (MapPortAgreement.ports G I.party (layout F hp I).core.edgeOrder).length ≤ 2 ^ w
+
+variable {F hp I X endAddr}
+
+theorem Bounds.below {descriptor : BurstRAM.Word w} (h : Bounds F hp I X endAddr descriptor)
+ (a : BurstRAM.Word w) (ha : a.val < endAddr) :
+ a.val < descriptor.val ∧
+ MapCallSetup.Outside (layout F hp I).core
+ ((layout F hp I).corePC (layout F hp I).locations) X a := by
+ refine ⟨ha.trans_le h.descriptorBase, ⟨.inl (ha.trans_le h.selectorBase),
+ .inl (ha.trans_le h.labelBase), ?_⟩, ?_⟩
+ · intro l eqn
+ have val := congrArg Fin.val eqn
+ change a.val = (X.hist + l.val) % (2 ^ w) at val
+ rw [Nat.mod_eq_of_lt ((Nat.add_lt_add_left l.isLt _).trans_le X.histogramFit)] at val
+ exact (ha.trans_le h.histogramBase).not_ge (val ▸ Nat.le_add_right ..)
+ · intro i eqn
+ have cast : (X.directory.val : BurstRAM.Word w) = X.directory :=
+ Fin.ext (Nat.mod_eq_of_lt X.directory.isLt)
+ have same : X.directory + (i.val : BurstRAM.Word w) =
+ ((X.directory.val + i.val : ℕ) : BurstRAM.Word w) := by rw [Nat.cast_add, cast]
+ have val := congrArg Fin.val (eqn.trans same)
+ change a.val = (X.directory.val + i.val) % (2 ^ w) at val
+ rw [Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans_le h.directoryRoom)] at val
+ exact (ha.trans_le h.directoryBase).not_ge (val ▸ Nat.le_add_right ..)
+
+variable (F hp I) (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (common : Fin shared ↪ Fin r) (c : Config w p r) (m : BurstRAM.Memory w)
+
+/-- Run the exact action on the saved scratch. The caller receives its complete
+register banks and the lower stack prefix, alongside the actual histogram readback. -/
+theorem Prepared.action_native (pc : F.Address → Fin p) (own : F.PrivateReg ↪ Fin r)
+ (advance : Fin p) (M : Machine w p r 11) (installed : ∀ a,
+ M.code (pc a) = (F.text pc dfs saved common own advance a).resize w)
+ (banks : F.Apart dfs saved common own) (hw : widthThreshold B ≤ w)
+ (X : Workspace F hp I) (endAddr : ℕ) (initial : DFS.Scratch w endAddr)
+ (incoming : DFS.scratch endAddr c.privateMem = initial) (hpc : c.pc = F.target pc (index hp I))
+ (prepared : Prepared F hp I dfs saved common c m X)
+ (bounds : Bounds F hp I X endAddr (addr F hp I dfs saved common c m)) :
+ let a := addr F hp I dfs saved common c m
+ let L := layout F hp I
+ match F.action hp I hw (pub F hp I dfs saved common c) (state F hp I dfs saved common c)
+ m X endAddr initial with
+ | none => ∀ bs, ¬ DFS.Returns M c m bs
+ | some (es, updated) => ∃ out, NodeArguments.ChildScan.Prefix M m c out [] es ∧
+ out.pc = advance ∧ ShrinkRole.Frame dfs endAddr c out ∧
+ (∀ i, out.reg (dfs i) = c.reg (dfs i)) ∧
+ (∀ i, out.reg (saved i) = c.reg (saved i)) ∧
+ (∀ i, out.reg (common i) = c.reg (common i)) ∧
+ (∀ q, q.val < a.val ∨ a.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val →
+ MapCallSetup.Outside L.core (L.corePC L.locations) X q →
+ out.privateMem q = c.privateMem q) ∧
+ (∀ l : Fin t, out.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) +
+ (((names F hp I).getD []).count l : BurstRAM.Word w)) ∧
+ DFS.scratch endAddr out.privateMem = updated := by
+ dsimp only
+ let result := F.action hp I hw (pub F hp I dfs saved common c) (state F hp I dfs saved common c)
+ m X endAddr initial
+ have run := F.action_native pc dfs saved common own advance M installed banks hp I hw c m X
+ endAddr initial incoming hpc prepared.fit prepared.fields prepared.resident prepared.histogram
+ prepared.directory
+ cases eqn : result with
+ | none =>
+ dsimp only [result] at eqn
+ rw [eqn] at run ⊢
+ exact run
+ | some pair =>
+ obtain ⟨es, updated⟩ := pair
+ dsimp only [result] at eqn
+ rw [eqn] at run ⊢
+ obtain ⟨out, path, exit, per, regs, mem, counts, scratch⟩ := run
+ have keep (i) : out.reg (dfs i) = c.reg (dfs i) := regs _ fun _ ↦ (banks.dfs _ i).symm
+ have lower (q : BurstRAM.Word w) (hq : q.val < endAddr) : out.privateMem q = c.privateMem q :=
+ mem _ (.inl (bounds.below q hq).1) (bounds.below q hq).2
+ exact ⟨out, path, exit, ⟨fun i _ ↦ keep i, lower, per⟩, keep,
+ fun i ↦ regs _ fun _ ↦ (banks.saved _ i).symm, fun i ↦ regs _ fun _ ↦ (banks.shared _ i).symm,
+ mem, counts, scratch⟩
+
+end PairSimulation.MapHandlerOperand
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerImage.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerImage.lean
new file mode 100644
index 0000000000..e7987b1042
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerImage.lean
@@ -0,0 +1,249 @@
+import OAI.Computability.VPVNP.PairSimulationMapInlineImage
+import OAI.Computability.VPVNP.PairSimulationMapArgumentWriter
+
+/-!
+# Vertex image of the grid-point and party map handlers
+
+Every fixed handler first evaluates its argument recipes and writes the raw
+call descriptor. The descriptor pointer goes directly into the lowered map's
+pointer register. All successful calls enter the common continuation, while
+failed calls reach a rejecting instruction local to the selected handler.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapHandlerImage
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MapConstants
+open BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H') {t shared p r w : ℕ}
+
+/-- The writer's six incoming values can be selected from DFS, saved bootstrap,
+or the enclosing role's own shared header and cursor registers. -/
+abbrev Source (shared : ℕ) := Fin 9 ⊕ VertexImage.Saved ⊕ Fin shared
+
+/-- A demand grid point paired with the party whose local map table handles that demand. -/
+abbrev Index := B.grid.demands × J
+
+/-- Fixed code and data recipes for one whole role. -/
+structure Family (t shared : ℕ) where
+ /-- Number of source registers allocated to each grid-point and party map table. Lowering the
+ table adds two scratch registers. -/
+ regCount : Index B → ℕ
+ /-- Number of public ports in each source map table, used to index the constants that will be
+ inlined. -/
+ portCount : Index B → ℕ
+ /-- Register, port and argument allocations used to assemble the map call table for each
+ demand grid point and party. -/
+ layout : ∀ i : Index B, MapCallTable.Layout B i.1 i.2 (regCount i) (portCount i)
+ /-- Assigns each motif parameter entry its histogram index, shared by the lookup tables of
+ every handler in the family. -/
+ ordinal : (parameterData B).Entry → Fin t
+ /-- Expression whose value is the first private word of the call descriptor for the selected
+ handler. -/
+ base : Index B → Expr
+ /-- Expression that computes the word to publish for each named descriptor argument of the
+ selected handler. -/
+ field : Index B → MapCallSetup.Arg D E → Expr
+ /-- Chooses a DFS, saved bootstrap or role-shared register for each of the descriptor
+ writer's five public operands and its state operand. -/
+ source : Index B → Fin 6 → Source shared
+
+private noncomputable def number (X : Type*) [Finite X] : X ≃ Fin (Nat.card X) := by
+ letI := Fintype.ofFinite X
+ exact Fintype.equivFinOfCardEq Nat.card_eq_fintype_card.symm
+
+namespace Family
+
+variable {B} (F : Family B t shared)
+
+/-- Descriptor field expressions in physical slot order. The layout's inverse argument
+numbering recovers the named argument stored at each offset. -/
+noncomputable def fields (i : Index B) := F.field i ∘ (F.layout i).args.symm
+
+/-- Vertex code segment for one lowered map call table, with the family's parameter ordinals
+embedded among its lookup constants. -/
+noncomputable abbrev image (i : Index B) := MapInline.imageSegment (F.layout i) F.ordinal
+
+/-- Local instruction addresses for evaluating one handler's field and base expressions,
+installing its descriptor pointer and storing the fields. -/
+noncomputable abbrev WriterPC (i : Index B) :=
+ MapArgumentWriter.Address (F.base i) (F.fields i)
+
+/-- Instruction addresses of the whole family. Each selects a grid point and party, then either
+a descriptor writer instruction or a row of the lowered map. -/
+noncomputable abbrev Address := (i : Index B) × (F.WriterPC i ⊕ Fin (F.image i).count)
+
+/-- Size of the register bank needed to evaluate all descriptor field expressions and the base
+expression for one handler. -/
+noncomputable abbrev VMCount (i : Index B) :=
+ RegisterSetup.regCount (MapArgumentWriter.recipes (F.base i) (F.fields i))
+
+/-- Registers private to one handler, grouped into the expression evaluator, two
+descriptor-writing temporaries, and the map's source registers plus two lowering
+temporaries. -/
+noncomputable abbrev Local (i : Index B) := Fin (F.VMCount i) ⊕ Fin 2 ⊕ Fin (F.regCount i + 2)
+
+/-- A private register identified by its grid-point and party handler and its slot in that
+handler's local bank. -/
+noncomputable abbrev PrivateReg := (i : Index B) × F.Local i
+
+variable (pc : F.Address → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (common : Fin shared ↪ Fin r) (own : F.PrivateReg ↪ Fin r) (advance : Fin p)
+
+/-- Resolves one of the writer's six input operands to the physical DFS, saved or shared
+register chosen by the handler's source assignment. -/
+def inputs (i : Index B) (a : Fin 6) : Fin r :=
+ (F.source i a).elim dfs (Sum.elim saved common)
+
+/-- Embeds the selected handler's local register slots into the host machine through the
+allocation of the family's private registers. -/
+noncomputable def localReg (i : Index B) : F.Local i ↪ Fin r :=
+ (⟨Sigma.mk i, fun _ _ h ↦ eq_of_heq (Sigma.mk.inj h).2⟩ : F.Local i ↪ F.PrivateReg).trans own
+
+/-- Physical registers used by the selected handler's expression evaluator to compute the
+descriptor fields and pointer. -/
+noncomputable def vm (i : Index B) : Fin (F.VMCount i) ↪ Fin r :=
+ Function.Embedding.inl.trans (F.localReg own i)
+
+/-- Physical register embedding for one lowered map, including its source map registers and the
+two scratch registers used to materialize constants. -/
+noncomputable def mapReg (i : Index B) : Fin (F.regCount i + 2) ↪ Fin r :=
+ (Function.Embedding.inr.trans Function.Embedding.inr).trans (F.localReg own i)
+
+/-- The descriptor publisher returns the pointer in exactly the source map's pointer
+register. Its two other temporaries belong to the writer. -/
+noncomputable def aux (i : Index B) : Fin 3 ↪ Fin r :=
+ (⟨Fin.cases (.inr (.inr ((F.layout i).ptr.castAdd 2))) (fun j ↦ .inr (.inl j)), by
+ intro a b h
+ fin_cases a <;> fin_cases b <;> first | rfl | cases h⟩ :
+ Fin 3 ↪ F.Local i).trans (F.localReg own i)
+
+/-- Host program counter of an instruction in the selected handler's descriptor writer. -/
+def writerPC (i : Index B) (a : F.WriterPC i) := pc ⟨i, .inl a⟩
+
+/-- Host program counter of a row in the selected handler's lowered map segment. -/
+def mapPC (i : Index B) (a : Fin (F.image i).count) := pc ⟨i, .inr a⟩
+
+/-- Installs one lowered map at its assigned instruction and register locations, routing
+success to the shared continuation and rejection to its local reject instruction. -/
+noncomputable def placement (i : Index B) :=
+ MapInline.imagePlacement (F.layout i) F.ordinal (F.mapPC pc i) (F.mapReg own i) advance
+
+/-- The dynamically selected target starts with the actual descriptor writer. -/
+noncomputable def target (i : Index B) :=
+ MapArgumentWriter.setupPC (F.base i) (F.fields i) (F.writerPC pc i) 0
+
+/-- The first part of each grid/party bank is the raw argument writer, followed
+by the actual inlined eleven-port map code. -/
+noncomputable def text : F.Address → Instr 5 p r 11
+ | ⟨i, .inl a⟩ =>
+ (MapArgumentWriter.text (F.base i) (F.fields i) (F.vm own i) (F.inputs dfs saved common i)
+ (F.aux own i) (F.writerPC pc i) (F.mapPC pc i (F.image i).entry) a).resize 5
+ | ⟨i, .inr a⟩ =>
+ (F.image i).row (F.mapPC pc i) dfs saved (F.mapReg own i) advance a
+
+/-- The role's shared inputs and the caller's saved registers lie outside the bank
+in which the handlers publish and evaluate their descriptors. -/
+structure Apart : Prop where
+ dfs : ∀ a b, own a ≠ dfs b
+ saved : ∀ a b, own a ≠ saved b
+ shared : ∀ a b, own a ≠ common b
+
+theorem vm_safe (h : F.Apart dfs saved common own) (i : Index B) (a b) :
+ F.vm own i a ≠ F.inputs dfs saved common i b := by
+ unfold inputs
+ cases F.source i b with
+ | inl j => exact h.dfs _ j
+ | inr x =>
+ cases x with
+ | inl j => exact h.saved _ j
+ | inr j => exact h.shared _ j
+
+/-- All writer scratch slots are disjoint from the map pointer and writer cursors. -/
+theorem vm_aux (i : Index B) (a b) : F.vm own i a ≠ F.aux own i b := by
+ fin_cases b <;> exact (F.localReg own i).injective.ne Sum.inl_ne_inr
+
+theorem pointer (i : Index B) :
+ (F.placement pc own advance i).reg (F.layout i).ptr = F.aux own i 0 := rfl
+
+private theorem resize5 (op : Instr 2 p r 11) : (op.resize 5).resize w = op.resize w := by
+ cases op <;> try rfl
+ case constant dst val next => simp only [Instr.resize, resize_literal (by decide : 2 ≤ 5)]
+
+variable (M : Machine w p r 11)
+ (installed : ∀ a, M.code (pc a) = (F.text pc dfs saved common own advance a).resize w)
+
+include installed in
+/-- Per-handler links extracted from the actual rows of the complete image. -/
+theorem links (i : Index B) :
+ let V := F.placement pc own advance i
+ (∀ a, M.code (F.writerPC pc i a) = (MapArgumentWriter.text (F.base i) (F.fields i)
+ (F.vm own i) (F.inputs dfs saved common i) (F.aux own i) (F.writerPC pc i)
+ (V.entry (F.layout i).template.entry) a).resize w) ∧
+ MapInline.Linked (F.layout i) F.ordinal V M ∧
+ V.entry (MapInline.callProgram (F.layout i)).done = advance ∧
+ M.code (V.entry (MapInline.callProgram (F.layout i)).bad) = .reject := by
+ intro V
+ let rows := fun a ↦ installed ⟨i, .inr a⟩
+ refine ⟨?_, MapInline.imageLinked (F.layout i) F.ordinal _ _ advance dfs saved M rows,
+ MapInline.imageDone (F.layout i) F.ordinal _ _ advance,
+ MapInline.imageReject (F.layout i) F.ordinal _ _ advance dfs saved M rows⟩
+ intro a
+ rw [show V.entry (F.layout i).template.entry = F.mapPC pc i (F.image i).entry from
+ MapInline.imageEntry ..]
+ exact (installed ⟨i, .inl a⟩).trans (resize5 _)
+
+/-- Finite numbering of all descriptor writer instructions and lowered map rows, used to
+address the family as one vertex segment. -/
+noncomputable def locations : F.Address ≃ Fin (Nat.card F.Address) := number _
+
+/-- Numbers the role's shared registers together with every handler's private slots for
+allocation in the vertex segment's register bank. -/
+noncomputable def registers :
+ (Fin shared ⊕ F.PrivateReg) ≃ Fin (Nat.card (Fin shared ⊕ F.PrivateReg)) :=
+ number _
+
+/-- A native vertex subsegment with a designated grid/party entry. In a larger
+role, the caller can use the other targets of the same installed table. -/
+noncomputable def segment (i : Index B) : VertexImage.Segment where
+ count := Nat.card F.Address
+ privateRegs := Nat.card (Fin shared ⊕ F.PrivateReg)
+ entry := F.target F.locations i
+ row loc dfs saved localRegs done a :=
+ F.text (loc ∘ F.locations) dfs saved
+ ((Function.Embedding.inl.trans F.registers.toEmbedding).trans localRegs)
+ ((Function.Embedding.inr.trans F.registers.toEmbedding).trans localRegs)
+ done (F.locations.symm a)
+
+/-- The surrounding role can recover every installed handler row from the
+ordinary vertex segment interface at its finite program-counter numbering. -/
+theorem segment_rows (chosen : Index B) (loc : Fin (Nat.card F.Address) → Fin p)
+ (localRegs : Fin (Nat.card (Fin shared ⊕ F.PrivateReg)) ↪ Fin r)
+ (rows : ∀ a, M.code (loc a) =
+ ((F.segment chosen).row loc dfs saved localRegs advance a).resize w)
+ (a : F.Address) :
+ M.code (loc (F.locations a)) = (F.text (loc ∘ F.locations) dfs saved
+ ((Function.Embedding.inl.trans F.registers.toEmbedding).trans localRegs)
+ ((Function.Embedding.inr.trans F.registers.toEmbedding).trans localRegs)
+ advance a).resize w := by
+ simpa only [segment, Equiv.symm_apply_apply] using rows (F.locations a)
+
+/-- All registers of a different grid/party handler survive the selected handler. -/
+theorem different_registers {i j : Index B} (ne : i ≠ j) (x : F.Local i) (y : F.Local j) :
+ F.localReg own i x ≠ F.localReg own j y := by
+ intro eq
+ exact ne (congrArg Sigma.fst (own.injective eq))
+
+end Family
+
+end PairSimulation.MapHandlerImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerOperand.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerOperand.lean
new file mode 100644
index 0000000000..4e3905627a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerOperand.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.PairSimulationMapHandlerRun
+import OAI.Computability.VPVNP.PairSimulationMapHandlerClock
+
+/-!
+# Calling a grouped matrix on its prepared physical operands
+
+The selected role's data are one entry input and the associated resident wire
+and descriptor addresses. The native writer reads its six real operands and
+publishes the descriptor at the evaluated base. This interface retains every
+register and memory frame needed to continue at the next resident row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapHandlerOperand
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MapConstants MotifEntry
+open BurstRAM.PrivateRAM CompressorRecords.PhaseRecipe MapHandlerImage
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'} {t shared p r w : ℕ}
+ (F : MapHandlerImage.Family B t shared) (hp : ∀ i, 0 < p₀ i) (I : LocalHistory.EntryInput B)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r)
+
+/-- The demand-grid point and party selecting the handler for this entry. -/
+noncomputable abbrev index : Index B := (demandGrid B hp I.demand, I.party)
+
+/-- The selected handler's map call table layout. -/
+noncomputable abbrev layout := F.layout (index hp I)
+
+/-- Memory locations and size bounds for running the selected map on this entry's bits. -/
+noncomputable abbrev Workspace := MapEntry.Program.Workspace (MapInline.callProgram (layout F hp I))
+ I.demand I.payload (demandBits src dst I.party I.demandBits)
+ (mapHalf G (fun _ ↦ inputBits) I.supplyBits) t w
+
+/-- Parameter ordinals reported by the entry evaluator, or `none` on rejection. -/
+noncomputable abbrev names := (runEntry B hp I.demand I.payload I.party
+ (demandBits src dst I.party I.demandBits) (mapHalf G (fun _ ↦ inputBits) I.supplyBits)).1.map
+ (List.map F.ordinal)
+
+variable (c : Config w p r) (m : BurstRAM.Memory w)
+
+/-- Value of the selected handler's `j`-th public operand at entry. -/
+noncomputable abbrev pub (j : Fin 5) := c.reg (F.inputs dfs saved common (index hp I) j.castSucc)
+
+/-- Value of the sixth operand, used as the state word in descriptor expressions. -/
+noncomputable abbrev state := c.reg (F.inputs dfs saved common (index hp I) (Fin.last 5))
+
+/-- Descriptor base address evaluated from the handler's six operands and external memory. -/
+noncomputable abbrev addr := (F.base (index hp I)).eval (pub F hp I dfs saved common c)
+ (state F hp I dfs saved common c) m
+
+/-- Numerical and semantic facts established by the selected physical shrink
+or refresh operand materializer, at the handler's actual entry configuration. -/
+structure Prepared (X : Workspace F hp I) : Prop where
+ fit : (addr F hp I dfs saved common c m).val + Fintype.card (MapCallSetup.Arg D E) ≤ 2 ^ w
+ fields : ∀ a, (F.field (index hp I) a).eval (pub F hp I dfs saved common c)
+ (state F hp I dfs saved common c) m =
+ MapCallSetup.values (layout F hp I).core ((layout F hp I).corePC (layout F hp I).locations)
+ X a
+ resident : MapArgumentWriter.ResidentFields (layout F hp I).core
+ ((layout F hp I).corePC (layout F hp I).locations) X
+ (addr F hp I dfs saved common c m) c.privateMem
+ histogram : ∀ l : Fin t, ((X.hist + l.val : ℕ) : BurstRAM.Word w).val <
+ (addr F hp I dfs saved common c m).val ∨
+ (addr F hp I dfs saved common c m).val + Fintype.card (MapCallSetup.Arg D E) ≤
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w).val
+ directory : ∀ (l : Fin t) (i : MapDirectoryInit.Row (layout F hp I).core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)
+
+/-- This is the physical step consumed by the resident loop. The bound is the
+selected handler's clock; its exact external count is the operand expression loads. -/
+theorem native (pc : F.Address → Fin p) (own : F.PrivateReg ↪ Fin r) (advance : Fin p)
+ (M : Machine w p r 11) (installed : ∀ a,
+ M.code (pc a) = (F.text pc dfs saved common own advance a).resize w)
+ (banks : F.Apart dfs saved common own) (hw : widthThreshold B ≤ w) (X : Workspace F hp I)
+ (hpc : c.pc = F.target pc (index hp I)) (prepared : Prepared F hp I dfs saved common c m X) :
+ let i := index hp I
+ let a := addr F hp I dfs saved common c m
+ ∃ out es, NodeArguments.ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ F.clock i (repetitions B I.demand) ∧ BurstRAM.countProbes es = F.probes i ∧
+ BurstRAM.choiceBits es = [] ∧
+ (if (names F hp I).isSome then out.pc = advance else M.code out.pc = .reject) ∧
+ out.persistent = c.persistent ∧
+ (∀ q, (∀ b : F.Local i, q ≠ F.localReg own i b) → out.reg q = c.reg q) ∧
+ (∀ q, q.val < a.val ∨ a.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val →
+ MapCallSetup.Outside (layout F hp I).core ((layout F hp I).corePC (layout F hp I).locations)
+ X q →
+ out.privateMem q = c.privateMem q) ∧
+ ∀ l : Fin t, out.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) +
+ (((names F hp I).getD []).count l : BurstRAM.Word w) :=
+ F.native pc dfs saved common own advance M installed banks hp I hw c m X hpc
+ prepared.fit prepared.fields prepared.resident prepared.histogram prepared.directory
+
+end PairSimulation.MapHandlerOperand
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerRun.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerRun.lean
new file mode 100644
index 0000000000..bbf61676ae
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapHandlerRun.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PairSimulationMapHandlerImage
+import OAI.Computability.VPVNP.PairSimulationMapWrittenCall
+
+/-!
+# Executing the selected grid and party handler
+
+The family supplies the descriptor writer and map subroutine links for the
+grid row and party recorded at this visit. The call consumes only deterministic
+events, reaches the common advance address or a real rejection, and preserves
+all other handler registers and every cell outside its workspace.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapHandlerImage.Family
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe MapConstants
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'} {t shared p r w : ℕ}
+ (F : Family B t shared) (pc : F.Address → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r) (own : F.PrivateReg ↪ Fin r)
+ (advance : Fin p) (M : Machine w p r 11)
+ (installed : ∀ a, M.code (pc a) = (F.text pc dfs saved common own advance a).resize w)
+ (banks : F.Apart dfs saved common own)
+
+include installed banks in
+theorem native (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B) (hw : widthThreshold B ≤ w)
+ (c : Config w p r) (m : Memory w) :
+ let i : Index B := (demandGrid B hp I.demand, I.party)
+ let L := F.layout i
+ let d := demandBits src dst I.party I.demandBits
+ let x := mapHalf G (fun _ ↦ inputBits) I.supplyBits
+ let inputs := F.inputs dfs saved common i
+ let pub := fun j : Fin 5 ↦ c.reg (inputs j.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := (F.base i).eval pub state m
+ let outside := fun q : BurstRAM.Word w ↦ q.val < addr.val ∨
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val
+ let names := (runEntry B hp I.demand I.payload I.party d x).1.map (List.map F.ordinal)
+ ∀ (X : MapEntry.Program.Workspace (MapInline.callProgram L) I.demand I.payload d x t w),
+ c.pc = F.target pc i →
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ 2 ^ w →
+ (∀ a, (F.field i a).eval pub state m =
+ MapCallSetup.values L.core (L.corePC L.locations) X a) →
+ MapArgumentWriter.ResidentFields L.core (L.corePC L.locations) X addr c.privateMem →
+ (∀ l : Fin t, outside ((X.hist + l.val : ℕ) : BurstRAM.Word w)) →
+ (∀ (l : Fin t) (j : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (j.val : BurstRAM.Word w)) →
+ ∃ out es, NodeArguments.ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ MapArgumentWriter.clock (F.base i) (F.fields i) + MapInline.factor L F.ordinal *
+ (L.lines.length + (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B i.1 i.2 (repetitions B I.demand)) ∧
+ countProbes es = ∑ j, ((MapArgumentWriter.recipes (F.base i) (F.fields i)) j).loads ∧
+ choiceBits es = [] ∧ (if names.isSome then out.pc = advance else M.code out.pc = .reject) ∧
+ out.persistent = c.persistent ∧
+ (∀ q, (∀ a : F.Local i, q ≠ F.localReg own i a) → out.reg q = c.reg q) ∧
+ (∀ q, outside q → MapCallSetup.Outside L.core (L.corePC L.locations) X q →
+ out.privateMem q = c.privateMem q) ∧
+ ∀ l : Fin t, out.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((X.hist + l.val : ℕ) : BurstRAM.Word w) +
+ ((names.getD []).count l : BurstRAM.Word w) := by
+ intro i L d x inputs pub state addr outside names X start fit values resident hist directory
+ let V := F.placement pc own advance i
+ obtain ⟨writer, body, done, bad⟩ := F.links pc dfs saved common own advance M installed i
+ obtain ⟨out, es, pre, len, reads, choice, exit, per, regs, memory, histogram⟩ :=
+ MapArgumentWriter.written_call hp I L F.ordinal V (F.base i) (F.field i) X (F.vm own i)
+ inputs (F.aux own i) (F.writerPC pc i) M writer (F.vm_safe dfs saved common own banks i)
+ (F.vm_aux own i) (F.pointer pc own advance i) body hw c m start fit values resident
+ hist directory
+ refine ⟨out, es, pre, len, reads, choice, ?_, per, ?_, memory, histogram⟩
+ · change out.pc = (if names.isSome then V.entry (MapInline.callProgram L).done
+ else V.entry (MapInline.callProgram L).bad) at exit
+ cases h : names.isSome
+ · simp only [h, Bool.false_eq_true, ↓reduceIte] at exit ⊢
+ exact exit ▸ bad
+ · simp only [h, ↓reduceIte] at exit ⊢
+ exact exit.trans done
+ · intro q apart
+ apply regs q
+ · apply InlinePublic.linked_privateReg
+ rintro ⟨v, eq⟩
+ exact apart (.inr (.inr v)) eq.symm
+ · exact fun v ↦ apart (.inl v)
+ · intro v
+ fin_cases v <;> exact apart _
+
+/-- All grid and party cases have a common fixed bound for writer probes and a
+common linear bound for the full writer and lowered map clock. -/
+theorem uniform : ∃ C : ℕ, ∀ (i : Index B) (u : ℕ),
+ (∑ j, ((MapArgumentWriter.recipes (F.base i) (F.fields i)) j).loads) ≤ C ∧
+ MapArgumentWriter.clock (F.base i) (F.fields i) + MapInline.factor (F.layout i) F.ordinal *
+ ((F.layout i).lines.length + (1 + 3 * (MapPortAgreement.ports G i.2
+ (F.layout i).core.edgeOrder).length) + MapNativeClock.cap B i.1 i.2 u) ≤ C * (u + 1) := by
+ obtain ⟨A, hA⟩ := MapInline.uniform F.ordinal (fun z j ↦ F.layout (z, j))
+ let overhead (i : Index B) := MapArgumentWriter.clock (F.base i) (F.fields i) +
+ ∑ j, ((MapArgumentWriter.recipes (F.base i) (F.fields i)) j).loads
+ let W := ∑ i : Index B, overhead i
+ refine ⟨W + A, fun i u ↦ ?_⟩
+ have hi : overhead i ≤ W := Finset.single_le_sum (fun j _ ↦ Nat.zero_le (overhead j))
+ (Finset.mem_univ i)
+ constructor
+ · exact ((Nat.le_add_left ..).trans hi).trans (Nat.le_add_right ..)
+ · have hclock := ((Nat.le_add_right ..).trans hi).trans
+ (Nat.le_mul_of_pos_right W (Nat.succ_pos u))
+ simpa only [Nat.add_mul] using Nat.add_le_add hclock (hA i.1 i.2 u)
+
+end PairSimulation.MapHandlerImage.Family
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapInitCompiler.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapInitCompiler.lean
new file mode 100644
index 0000000000..963ba1539f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapInitCompiler.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Register recipes reading the private call descriptor
+
+The existing straight-line recipe compiler assigns disjoint outputs and
+reuses a bounded scratch bank. For a map call its loads read private memory
+at addresses computed from the live descriptor pointer. Every instruction
+therefore contributes one tick and both memories are preserved.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapInitCompiler
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedStackRAM
+open CompressorRecords CompressorRecords.RowRecipe CompressorRecords.PhaseRecipe
+open private emit_list from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+open scoped Fin.CommRing
+
+variable {n v w p r k : ℕ}
+
+/-- The recipe evaluator uses natural addresses while the private memory accepts words. -/
+def memory (cells : Word w → Word w) : Memory w := fun i ↦ cells (i : Word w)
+
+/-- Retarget the compiler's read instruction to the private memory of the current call. -/
+def instruction (bank : Fin v ↪ Fin r) (ptr : Fin r) (a : Assign v 5) (next : Fin p) :
+ Instr w p r k :=
+ match a.rhs with
+ | .read j => .loadPrivate (bank a.dst) (bank j) next
+ | _ => RegisterSetup.instruction bank (fun _ ↦ ptr) a next
+
+theorem resize_instruction (bank : Fin v ↪ Fin r) (ptr : Fin r) (a : Assign v 5) (next : Fin p) :
+ (instruction (w := 2) (k := k) bank ptr a next).resize w =
+ instruction bank ptr a next := by
+ obtain ⟨d, rhs⟩ := a
+ cases rhs <;> simp only [instruction, RegisterSetup.instruction, Instr.resize,
+ Fin.ofNat_val_eq_self]
+
+/-- Installation condition for the private descriptor initializer. At each indexed program
+counter the machine contains the compiled assignment with the next index as its successor. -/
+def Linked (bank : Fin v ↪ Fin r) (ptr : Fin r) (M : Machine w p r k) (pc : ℕ → Fin p)
+ (lines : List (Assign v 5)) : Prop :=
+ ∀ i : Fin lines.length, M.code (pc i.val) = instruction bank ptr lines[i.val] (pc (i.val + 1))
+
+private theorem execute_lines (bank : Fin v ↪ Fin r) (ptr : Fin r) (safe : ∀ i, bank i ≠ ptr)
+ (M : Machine w p r k) (pc : ℕ → Fin p) (lines : List (Assign v 5))
+ (hl : Linked bank ptr M pc lines) (c : Config w p r) (hc : c.pc = pc 0) :
+ let s := c.reg ptr
+ let vals := (evaluate (fun _ ↦ s) s (memory c.privateMem) lines (c.reg ∘ bank)).2
+ ∃ d, Prefix M c (List.replicate lines.length .tick) d ∧ d.pc = pc lines.length ∧
+ (∀ i, d.reg (bank i) = vals i) ∧ (∀ a, (∀ i, a ≠ bank i) → d.reg a = c.reg a) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ induction lines generalizing pc c with
+ | nil => exact ⟨c, .nil _, hc, fun _ ↦ rfl, fun _ _ ↦ rfl, rfl, rfl⟩
+ | cons a lines ih =>
+ let val := a.rhs.value (fun _ ↦ c.reg ptr) (c.reg ptr) (memory c.privateMem) (c.reg ∘ bank)
+ let mid := c.put (pc 1) (bank a.dst) val
+ have hs : M.program.step c = .localStep mid := by
+ have h := hl ⟨0, by simp⟩
+ change M.code (pc 0) = instruction bank ptr a (pc 1) at h
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hc, h]
+ obtain ⟨dst, rhs⟩ := a
+ cases rhs <;> first | rfl | simp [instruction, Instr.run, mid, val, RHS.value, memory]
+ have hr : mid.reg ∘ bank = Function.update (c.reg ∘ bank) a.dst val := by
+ funext i
+ by_cases he : i = a.dst <;> simp [mid, Config.put, he]
+ have hp : mid.reg ptr = c.reg ptr := Function.update_of_ne (Ne.symm (safe _)) ..
+ have tail : Linked bank ptr M (fun i ↦ pc (i + 1)) lines :=
+ fun i ↦ hl ⟨i.val + 1, by simp [i.isLt]⟩
+ obtain ⟨d, pre, hd, vals, rest, hm, hper⟩ := ih _ tail mid rfl
+ refine ⟨d, .tick hs pre, hd, ?_, ?_, hm, hper⟩
+ · intro i
+ simpa only [evaluate, hp, hr, show mid.privateMem = c.privateMem from rfl, val] using vals i
+ · exact fun q hq ↦ (rest q hq).trans (Function.update_of_ne (hq _) ..)
+
+/-- Load a complete finite output vector from a private descriptor. The number of
+ticks depends solely on the chosen recipes. Outside registers and all cells survive. -/
+theorem native (f : Fin n → Expr) (bank : Fin (RegisterSetup.regCount f) ↪ Fin r)
+ (ptr : Fin r) (safe : ∀ i, bank i ≠ ptr) (M : Machine w p r k) (pc : ℕ → Fin p)
+ (hl : Linked bank ptr M pc (RegisterSetup.lines f)) (c : Config w p r) (hc : c.pc = pc 0) :
+ ∃ d, Prefix M c (List.replicate (RegisterSetup.lines f).length .tick) d ∧
+ d.pc = pc (RegisterSetup.lines f).length ∧
+ (∀ i, d.reg (bank (RegisterSetup.output f i)) =
+ (f i).eval (fun _ ↦ c.reg ptr) (c.reg ptr) (memory c.privateMem)) ∧
+ (∀ a, (∀ i, a ≠ bank i) → d.reg a = c.reg a) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨d, pre, hd, vals, rest, hm, hper⟩ := execute_lines bank ptr safe M pc _ hl c hc
+ refine ⟨d, pre, hd, fun i ↦ (vals _).trans ?_, rest, hm, hper⟩
+ exact (emit_list f _ _ _ (List.finRange n) _ i).trans (ite_eq_left (List.mem_finRange i))
+
+end PairSimulation.MapInitCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapInline.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapInline.lean
new file mode 100644
index 0000000000..e098f37208
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapInline.lean
@@ -0,0 +1,183 @@
+import OAI.Computability.VPVNP.PairSimulationMapConstants
+import OAI.Computability.VPVNP.PairSimulationInlinePrefix
+
+/-!
+# A reusable motif map on the eleven public input words
+
+The installed body obtains every fixed selector and label constant from its
+instructions. Its two exit labels can be the enclosing continuation and
+failure labels. A successful call increments the resident histogram exactly
+once per output label. A failed call preserves every histogram cell.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapInline
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifDemandPadding
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord InlinePublic MapConstants
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k t w P R : ℕ}
+ (L : MapCallTable.Layout B z j r k) (ord : (parameterData B).Entry → Fin t)
+
+/-- The slowdown per source instruction, fixed for the entire role and grid point. -/
+noncomputable def factor := capacity L.template (rawBank L.core ord) + 3
+
+/-- The standalone fixed map table, ready to instantiate with the actual eleven words. -/
+noncomputable def template11 : Template (Nat.card L.Address * factor L ord) (r + 2) 11 :=
+ compiled 11 L.template (rawBank L.core ord)
+
+/-- Grouped entry program at the core instruction addresses of the numbered call table. Its
+success and failure labels identify the exits to relocate when inlining the table. -/
+noncomputable abbrev callProgram := L.core.program (L.corePC L.locations)
+
+theorem exit_codes :
+ L.template.code (callProgram L).bad = .reject ∧
+ L.template.code (callProgram L).done = .accept := by
+ simp [MapCallTable.Layout.template, callProgram, MapEntryTable.Allocation.program,
+ MapCallTable.Layout.corePC, MapEntryTable.Allocation.exitPC, MapCallTable.Layout.text,
+ MapEntryTable.Allocation.text]
+
+/-- Exact private histogram and the continuation reached in the enclosing machine. -/
+def Outcome {p r : ℕ} (hist : ℕ) (bad done : Fin p) (c out : Config w p r) :
+ Option (List (Fin t)) → Prop
+ | none => out.pc = bad ∧ ∀ l : Fin t,
+ out.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w)
+ | some names => out.pc = done ∧ ∀ l : Fin t,
+ out.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w) =
+ c.privateMem ((hist + l.val : ℕ) : BurstRAM.Word w) + (names.count l : BurstRAM.Word w)
+
+variable (V : Placement (capacity L.template (rawBank L.core ord)) (Nat.card L.Address) r P R)
+ (M : Machine w P R 11)
+
+/-- Instruction-level installation requires only the body between the exits. -/
+def Linked : Prop := ∀ pc, continues (L.template.code pc) = true →
+ ContainsAt M L.template (rawBank L.core ord) V pc
+
+/-- A fully framed host path from a restricted initial configuration. -/
+def Runs (h : Config w P R) (hist cap : ℕ) (result : Option (List (Fin t))) : Prop :=
+ ∃ n out, n ≤ factor L ord * cap ∧ Prefix M h (List.replicate n .tick) out ∧
+ out.persistent = h.persistent ∧ (∀ i, V.privateReg i → out.reg i = h.reg i) ∧
+ Outcome hist (V.entry (callProgram L).bad) (V.entry (callProgram L).done) h out result
+
+/-- The exact host path, including all private cells saved by the complete map call. -/
+def RunsFramed (h : Config w P R) (hist cap : ℕ) (save : BurstRAM.Word w → Prop)
+ (result : Option (List (Fin t))) : Prop :=
+ ∃ n out, n ≤ factor L ord * cap ∧ Prefix M h (List.replicate n .tick) out ∧
+ out.persistent = h.persistent ∧ (∀ i, V.privateReg i → out.reg i = h.reg i) ∧
+ (∀ a, save a → out.privateMem a = h.privateMem a) ∧
+ Outcome hist (V.entry (callProgram L).bad) (V.entry (callProgram L).done) h out result
+
+theorem RunsFramed.forget {h : Config w P R} {hist cap : ℕ} {save : BurstRAM.Word w → Prop}
+ {value : Option (List (Fin t))} (run : RunsFramed L ord V M h hist cap save value) :
+ Runs L ord V M h hist cap value := by
+ obtain ⟨n, out, cap, path, per, reg, _, endAt⟩ := run
+ exact ⟨n, out, cap, path, per, reg, endAt⟩
+
+/-- Transport the concrete source call without using any of the caller's public words. -/
+theorem lift_run_framed (linked : Linked L ord V M) (h : Config w P R)
+ (pc : h.pc = V.entry L.template.entry)
+ {hist cap : ℕ} {result : Option (List (Fin t))}
+ {save : BurstRAM.Word w → Prop}
+ (path : (callProgram L).RunsFramed (source (w := w) L ord) (restrict V L.template.entry h)
+ hist cap save result) : RunsFramed L ord V M h hist cap save result := by
+ obtain ⟨n, last, hn, pre, keep, saved, endAt⟩ := path.path
+ obtain ⟨out, pref, rel⟩ := ticks_lower L.template (rawBank L.core ord) V M
+ (operand_le L.template (rawBank L.core ord)) linked pre (restrict_related V _ h pc)
+ refine ⟨factor L ord * n, out, Nat.mul_le_mul_left _ hn, pref, rel.1.persistent.trans keep,
+ rel.1.frame, fun a ha ↦ (congrFun rel.1.privateMem a).trans (saved a ha), ?_⟩
+ cases result with
+ | none =>
+ refine ⟨rel.2.trans (congrArg V.entry endAt.1), fun i ↦ ?_⟩
+ rw [rel.1.privateMem]
+ exact endAt.2 i
+ | some names =>
+ refine ⟨rel.2.trans (congrArg V.entry endAt.1), fun i ↦ ?_⟩
+ rw [rel.1.privateMem]
+ exact endAt.2 i
+
+/-- The full map from a resident raw descriptor to the enclosing histogram.
+The eleven public input words are arbitrary. -/
+theorem run_entryInput_framed (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : MapCallTable.Layout B (demandGrid B hp I.demand) I.party r k)
+ (V : Placement (capacity L.template (rawBank L.core ord)) (Nat.card L.Address) r P R)
+ (M : Machine w P R 11) (linked : Linked L ord V M) (hw : widthThreshold B ≤ w) :
+ let loc := L.corePC L.locations
+ let demand := MotifEntry.demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ MotifEntry.inputBits) I.supplyBits
+ ∀ (X : MapEntry.Program.Workspace (callProgram L) I.demand I.payload demand supply t w)
+ (h : Config w P R), h.pc = V.entry L.template.entry →
+ MapCallSetup.Input L.core L.args loc X L.ptr (restrict V L.template.entry h) →
+ (∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ RunsFramed L ord V M h X.hist (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand))
+ (MapCallSetup.Outside L.core loc X)
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord)) := by
+ intro loc demand supply X h pc input apart
+ exact lift_run_framed L ord V M linked h pc (source_run_framed hp I L ord hw X _ rfl input apart)
+
+/-- The full map from a resident raw descriptor to the enclosing histogram.
+The eleven public input words are arbitrary. -/
+theorem run_entryInput (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : MapCallTable.Layout B (demandGrid B hp I.demand) I.party r k)
+ (V : Placement (capacity L.template (rawBank L.core ord)) (Nat.card L.Address) r P R)
+ (M : Machine w P R 11) (linked : Linked L ord V M) (hw : widthThreshold B ≤ w) :
+ let loc := L.corePC L.locations
+ let demand := MotifEntry.demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ MotifEntry.inputBits) I.supplyBits
+ ∀ (X : MapEntry.Program.Workspace (callProgram L) I.demand I.payload demand supply t w)
+ (h : Config w P R), h.pc = V.entry L.template.entry →
+ MapCallSetup.Input L.core L.args loc X L.ptr (restrict V L.template.entry h) →
+ (∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ Runs L ord V M h X.hist (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand))
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord)) := by
+ intro loc demand supply X h pc input apart
+ exact (run_entryInput_framed ord hp I L V M linked hw X h pc input apart).forget L ord V M
+
+/-- The canonical finite code discharges every installation condition. -/
+theorem template11_linked (pub : Fin 11 → BurstRAM.Word w) :
+ Linked L ord (canonical (capacity L.template (rawBank L.core ord)) (Nat.card L.Address) r)
+ ((template11 L ord).instantiate w pub) :=
+ fun pc _ ↦ compiled_contains L.template (rawBank L.core ord) pub pc
+
+/-- One constant works for all grid points, parties, repetitions and word widths.
+It includes expression initialization, the private directory, and the inlined constants. -/
+theorem uniform {rr kk : B.grid.demands → J → ℕ}
+ (layouts : ∀ z j, MapCallTable.Layout B z j (rr z j) (kk z j)) :
+ ∃ A : ℕ, ∀ z j u, factor (layouts z j) ord *
+ ((layouts z j).lines.length + (1 + 3 *
+ (MapPortAgreement.ports G j (layouts z j).core.edgeOrder).length) +
+ MapNativeClock.cap B z j u) ≤ A * (u + 1) := by
+ obtain ⟨C, hC⟩ := MapNativeClock.uniform B
+ let start := fun z j ↦ (layouts z j).lines.length +
+ (1 + 3 * (MapPortAgreement.ports G j (layouts z j).core.edgeOrder).length)
+ let weight := fun z j ↦ factor (layouts z j) ord * (start z j + C)
+ refine ⟨∑ z : B.grid.demands, ∑ j, weight z j, fun z j u ↦ ?_⟩
+ have hweight := (Finset.single_le_sum (fun i _ ↦ Nat.zero_le (weight z i))
+ (Finset.mem_univ j)).trans (Finset.single_le_sum (fun a _ ↦ Nat.zero_le (∑ i, weight a i))
+ (Finset.mem_univ z))
+ have hstart := Nat.le_mul_of_pos_right (start z j) (Nat.succ_pos u)
+ calc
+ _ ≤ factor (layouts z j) ord * ((start z j + C) * (u + 1)) := by
+ rw [Nat.add_mul]
+ exact Nat.mul_le_mul_left _ (Nat.add_le_add hstart (hC z j u))
+ _ = weight z j * (u + 1) := (Nat.mul_assoc ..).symm
+ _ ≤ _ := Nat.mul_le_mul_right _ hweight
+
+end PairSimulation.MapInline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapInlineImage.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapInlineImage.lean
new file mode 100644
index 0000000000..29f009cfa7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapInlineImage.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.PairSimulationMapInline
+import OAI.Computability.VPVNP.PairSimulationInlineSegment
+
+/-!
+# The concrete grouped map call inside the native vertex image
+
+A grid point and a party determine the selector and matrix table. This segment installs
+its width-two code in the vertex image's literal format. The image can reuse the same
+table at every visit by entering it with the current private descriptor pointer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapInline
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion
+open BurstRAM.PrivateRAM InlinePublic MapConstants CompressorRecords
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k t w P R : ℕ}
+ (L : MapCallTable.Layout B z j r k) (ord : (parameterData B).Entry → Fin t)
+
+/-- All labels and registers are fixed for this map template. -/
+noncomputable def imageSegment : VertexImage.Segment := segment L.template (rawBank L.core ord)
+
+variable (loc : Fin (imageSegment L ord).count → Fin P) (reg : Fin (r + 2) ↪ Fin R)
+ (done : Fin P)
+
+/-- Places the lowered call table and its registers in the host image. Successful exits
+transfer to the supplied continuation, while a failing exit uses the segment's reject row. -/
+noncomputable abbrev imagePlacement := linkedPlacement L.template (rawBank L.core ord) loc reg done
+
+private theorem init_continues {v W R₁ p' k' : ℕ} (a : RowRecipe.Assign v 5)
+ (bank : Fin v ↪ Fin R₁) (ptr : Fin R₁) (next : Fin p') :
+ continues (MapInitCompiler.instruction (w := W) (k := k') bank ptr a next) = true := by
+ obtain ⟨dst, rhs⟩ := a
+ cases rhs <;> rfl
+
+/-- The initial source opcode is the first operand assignment or the directory initializer. -/
+theorem entry_continues : continues (L.template.code L.template.entry) = true := by
+ change continues (L.text L.locations (L.locations.symm (L.initPC L.locations 0))) = true
+ unfold MapCallTable.Layout.initPC
+ split
+ · simp only [Equiv.symm_apply_apply, MapCallTable.Layout.text]
+ exact init_continues _ _ _ _
+ · simp [MapCallTable.Layout.dirPC, MapCallTable.Layout.text, MapDirectoryInit.text, continues]
+
+theorem imageEntry :
+ (imagePlacement L ord loc reg done).entry L.template.entry =
+ loc (imageSegment L ord).entry :=
+ segment_entry _ _ _ _ _ (entry_continues L)
+
+theorem imageDone : (imagePlacement L ord loc reg done).entry (callProgram L).done = done :=
+ success_entry _ _ _ _ _ (exit_codes L).2
+
+variable (dfs : Fin 9 ↪ Fin R) (saved : VertexImage.Saved ↪ Fin R)
+ (M : Machine w P R 11)
+ (installed : ∀ a, M.code (loc a) =
+ ((imageSegment L ord).row loc dfs saved reg done a).resize w)
+
+include installed in
+/-- The actual installed rows discharge the code premise of the native map call. -/
+theorem imageLinked : Linked L ord (imagePlacement L ord loc reg done) M :=
+ contains_linkedRows _ _ _ _ _ M (segment_rows _ _ _ dfs saved reg done M installed)
+
+include installed in
+/-- A failed map reaches the machine's genuine rejecting instruction. -/
+theorem imageReject : M.code ((imagePlacement L ord loc reg done).entry (callProgram L).bad) =
+ .reject :=
+ rejecting_entry _ _ _ _ _ M (segment_rows _ _ _ dfs saved reg done M installed) (exit_codes L).1
+
+end PairSimulation.MapInline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapInvocationClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapInvocationClock.lean
new file mode 100644
index 0000000000..2bb9746d4b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapInvocationClock.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.PairSimulationMapInline
+
+/-!
+# Uniform clocks for the actual shrink and refresh map code
+
+Each grid row and party uses a fixed allocation of registers, public constants
+and instructions. The descriptor and private fields vary with the selected
+vertex. Both catalogue ordinals share the enclosing histogram.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapInline
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion
+open MapCallTable LocalHistory
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H') {t : ℕ}
+
+/-- A concrete descriptor and register layout for each member of the fixed family. -/
+noncomputable def layout (z : B.grid.demands) (j : J) :=
+ MapCallTable.allocate B z j (MapEntryTable.allocation B z j)
+ (Fintype.equivFin _) (Fintype.equivFin _)
+
+variable (ordinal : (parameterData B).Entry → Fin t)
+
+/-- The instruction bound of the fixed, physically lowered layout at a given copy count. -/
+noncomputable def cap (z : B.grid.demands) (j : J) (u : ℕ) : ℕ :=
+ let L := layout B z j
+ factor L ordinal * (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G j L.core.edgeOrder).length) + MapNativeClock.cap B z j u)
+
+theorem cap_uniform : ∃ C : ℕ, ∀ z j u, cap B ordinal z j u ≤ C * (u + 1) :=
+ uniform ordinal (layout B)
+
+/-- All numerical table entries fit exactly in every sufficiently wide host word,
+simultaneously over all parties and grid points. -/
+theorem eventually_exact :
+ ∀ᶠ w : ℕ in Filter.atTop, ∀ z j i,
+ ((MapConstants.rawBank (layout B z j).core ordinal i : BurstRAM.Word w)).val =
+ MapConstants.rawBank (layout B z j).core ordinal i := by
+ let bank := fun z j ↦ MapConstants.rawBank (layout B z j).core ordinal
+ let bound := ∑ z : B.grid.demands, ∑ j, ∑ i, bank z j i
+ filter_upwards [Filter.eventually_ge_atTop bound] with w hw
+ intro z j i
+ have hi := Finset.single_le_sum (fun a _ ↦ Nat.zero_le (bank z j a)) (Finset.mem_univ i)
+ have hj := Finset.single_le_sum (fun b _ ↦ Nat.zero_le (∑ a, bank z b a)) (Finset.mem_univ j)
+ have hz := Finset.single_le_sum (fun c _ ↦ Nat.zero_le (∑ b, ∑ a, bank c b a)) (Finset.mem_univ z)
+ exact Nat.mod_eq_of_lt ((((hi.trans hj).trans hz).trans hw).trans_lt Nat.lt_two_pow_self)
+
+/-- Initialization and literal expansion cost a fixed factor relative to the
+five-phase map clock, including a possibly empty row. -/
+theorem cap_relative :
+ ∃ C : ℕ, ∀ z j u, cap B ordinal z j u ≤ C * (MapNativeClock.cap B z j u + 1) := by
+ let start := fun z j ↦ (layout B z j).lines.length +
+ (1 + 3 * (MapPortAgreement.ports G j (layout B z j).core.edgeOrder).length)
+ let weight := fun z j ↦ factor (layout B z j) ordinal * (start z j + 1)
+ refine ⟨∑ z : B.grid.demands, ∑ j, weight z j, fun z j u ↦ ?_⟩
+ have hweight := (Finset.single_le_sum (fun i _ ↦ Nat.zero_le (weight z i))
+ (Finset.mem_univ j)).trans (Finset.single_le_sum (fun a _ ↦ Nat.zero_le (∑ i, weight a i))
+ (Finset.mem_univ z))
+ let n := MapNativeClock.cap B z j u
+ calc
+ _ ≤ factor (layout B z j) ordinal * ((start z j + 1) * (n + 1)) := by
+ apply Nat.mul_le_mul_left
+ change start z j + n ≤ _
+ rw [Nat.add_mul, Nat.one_mul, Nat.mul_add, Nat.mul_one]
+ omega
+ _ = weight z j * (n + 1) := (Nat.mul_assoc ..).symm
+ _ ≤ _ := Nat.mul_le_mul_right _ hweight
+
+open Compression
+
+variable {S : BlockSchedule K} (T : S.Templates) (ord : T.Entry → Fin t)
+
+open scoped Classical in
+/-- The clock of the actual map call selected by the compressor. -/
+noncomputable def invocationCap {d : ℕ} : MapInvocation T d → ℕ
+ | .shrink x _ => cap T.shrink (ord ∘ Sum.inl)
+ (demandGrid T.shrink ShrinkMotif.demandMass_pos x.demand) x.party
+ (repetitions T.shrink x.demand)
+ | .refresh x _ => cap T.refresh (ord ∘ Sum.inr)
+ (demandGrid T.refresh (fun _ ↦ zero_lt_one) x.demand) x.party (repetitions T.refresh x.demand)
+ | .noLookup => 0
+
+/-- One linear bound includes every initializer, inlined table constant and local
+histogram increment across both map templates. -/
+theorem invocation_uniform :
+ ∃ C : ℕ, ∀ d (m : MapInvocation T d), invocationCap T ord m ≤ C * (d + 1) := by
+ classical
+ obtain ⟨A, hA⟩ := cap_uniform T.shrink (ord ∘ Sum.inl)
+ obtain ⟨A', hA'⟩ := cap_uniform T.refresh (ord ∘ Sum.inr)
+ refine ⟨max A A', fun d m ↦ ?_⟩
+ cases m with
+ | shrink x hx => exact (hA ..).trans (Nat.mul_le_mul (le_max_left ..) (Nat.succ_le_succ hx))
+ | refresh x hx => exact (hA' ..).trans (Nat.mul_le_mul (le_max_right ..) (Nat.succ_le_succ hx))
+ | noLookup => exact Nat.zero_le _
+
+/-- This is the constant used by the selected-vertex clock on the concrete lowered map. -/
+theorem invocation_relative :
+ ∃ A : ℕ, ∀ d (m : MapInvocation T d), invocationCap T ord m ≤
+ (A + 1) * (m.nativeCap T + 1) := by
+ classical
+ obtain ⟨A, hA⟩ := cap_relative T.shrink (ord ∘ Sum.inl)
+ obtain ⟨A', hA'⟩ := cap_relative T.refresh (ord ∘ Sum.inr)
+ refine ⟨max A A', fun d m ↦ ?_⟩
+ cases m with
+ | shrink x _ =>
+ exact (hA ..).trans (Nat.mul_le_mul_right _ ((le_max_left ..).trans (Nat.le_succ _)))
+ | refresh x _ =>
+ exact (hA' ..).trans (Nat.mul_le_mul_right _ ((le_max_right ..).trans (Nat.le_succ _)))
+ | noLookup => exact Nat.zero_le _
+
+end PairSimulation.MapInline
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapLookup.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapLookup.lean
new file mode 100644
index 0000000000..9629a4ec7f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapLookup.lean
@@ -0,0 +1,445 @@
+import OAI.Computability.VPVNP.MotifConversion
+import OAI.Computability.VPVNP.PrimedInputRAMFlowLinks
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Native fixed-table lookups for motif maps
+
+The code compares the supplied fields with fixed public words. On the first
+matching row it loads the corresponding selector or label ordinal. Reaching
+the end of the table transfers control to the rejecting instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapLookup
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM PrimedStackRAM
+
+variable {ι X : Type*} {w p r k : ℕ}
+
+/-- A finite decision tree with public constants at the comparison nodes. -/
+inductive Tree (ι X : Type*) (k : ℕ) where
+ | miss
+ | hit (x : X)
+ | test (i : ι) (constant : Fin k) (yes no : Tree ι X k)
+
+namespace Tree
+
+/-- One native dispatch loads an output or goes to the bad exit. Each
+comparison takes one public-word load and one conditional jump. -/
+def eval (pub : Fin k → Word w) (input : ι → Word w) : Tree ι X k → Option X × ℕ
+ | .miss => (none, 1)
+ | .hit x => (some x, 1)
+ | .test i j yes no =>
+ let a := if input i = pub j then eval pub input yes else eval pub input no
+ (a.1, 2 + a.2)
+
+/-- Lower the decision tree to the same structured finite table compiler
+used by the coefficient machine. -/
+def flow (query : ι → Fin r) (tmp out : Fin r) (name : X → Fin k) : Tree ι X k → Flow r k
+ | .miss => .line (.guardLt tmp tmp)
+ | .hit x => .line (.publicWord out (name x))
+ | .test i j yes no =>
+ (Flow.line (.publicWord tmp j)).seq
+ (.ifEq (query i) tmp (flow query tmp out name yes) (flow query tmp out name no))
+
+/-- Success leaves the ordinal in the output register at the normal exit.
+A miss reaches the rejecting exit. Each path consumes exactly its computed
+number of ticks, without a probe or binary choice. -/
+theorem native (t : Tree ι X k) (query : ι → Fin r) (tmp out : Fin r) (name : X → Fin k)
+ (ht : ∀ i, query i ≠ tmp) (M : Machine w p r k)
+ (label : (t.flow query tmp out name).Label → Fin p)
+ (stop bad : Fin p) (hl : Flow.Linked M (t.flow query tmp out name) label stop bad)
+ (c : Config w p r) (hc : c.pc = label (t.flow query tmp out name).entry) :
+ let a := t.eval M.publicData (fun i ↦ c.reg (query i))
+ ∃ final, Prefix M c (List.replicate a.2 .tick) final ∧
+ (match a.1 with
+ | none => final.pc = bad
+ | some x => final.pc = stop ∧ final.reg out = M.publicData (name x)) ∧
+ (∀ j, j ≠ tmp → j ≠ out → final.reg j = c.reg j) ∧
+ final.privateMem = c.privateMem ∧ final.persistent = c.persistent := by
+ dsimp only
+ induction t generalizing c with
+ | miss =>
+ have hs : M.program.step c = .localStep {c with pc := bad} := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hc,
+ hl.atLabel _]
+ change CallAction.localStep {c with pc := if c.reg tmp < c.reg tmp then stop else bad} = _
+ simp
+ exact ⟨_, .tick hs (.nil _), rfl, fun _ _ _ ↦ rfl, rfl, rfl⟩
+ | hit x =>
+ let final := c.put stop out (M.publicData (name x))
+ have hs : M.program.step c = .localStep final := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hc,
+ hl.atLabel _]
+ rfl
+ exact ⟨_, .tick hs (.nil _), ⟨rfl, by simp [final]⟩,
+ fun j _ hj ↦ by simp [final, Config.put, Function.update_of_ne hj], rfl, rfl⟩
+ | test i j yes no hy hn =>
+ let cond := Flow.ifEq (query i) tmp (yes.flow query tmp out name) (no.flow query tmp out name)
+ let place := fun a : cond.Label ↦ label (.inr a)
+ let mid := c.put (place cond.entry) tmp (M.publicData j)
+ have hs : M.program.step c = .localStep mid := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hc, hl.atLabel _]
+ rfl
+ have heq (u : ι) : mid.reg (query u) = c.reg (query u) := by
+ simp [mid, Config.put, Function.update_of_ne (ht u)]
+ have hcond : Flow.Linked M cond place stop bad := hl.seqRight
+ have jump : M.program.step mid = .localStep {mid with pc :=
+ (if c.reg (query i) = M.publicData j then
+ place (.inr (.inl (yes.flow query tmp out name).entry))
+ else place (.inr (.inr (no.flow query tmp out name).entry)))} := by
+ rw [show M.program.step mid = (M.code mid.pc).run M.publicData mid from rfl,
+ show mid.pc = place cond.entry from rfl, hcond.atLabel _]
+ change CallAction.localStep
+ {mid with pc := if mid.reg (query i) = mid.reg tmp then _ else _} = _
+ rw [heq, show mid.reg tmp = M.publicData j from Config.put_same ..]
+ rfl
+ have hinputs : (fun u ↦ mid.reg (query u)) = fun u ↦ c.reg (query u) := funext heq
+ have hrest (a : Fin r) (ha : a ≠ tmp) : mid.reg a = c.reg a := by
+ simp [mid, Config.put, Function.update_of_ne ha]
+ by_cases h : c.reg (query i) = M.publicData j
+ · rw [ite_eq_left h] at jump
+ obtain ⟨d, pre, hd, ho, hm, hp⟩ := hy _ hcond.ifEqYes
+ {mid with pc := place (.inr (.inl (yes.flow query tmp out name).entry))} rfl
+ change Prefix M _ (List.replicate (yes.eval _ (fun u ↦ mid.reg (query u))).2 .tick) d at pre
+ rw [hinputs] at pre
+ change (match (yes.eval _ (fun u ↦ mid.reg (query u))).1 with
+ | none => _ | some _ => _) at hd
+ rw [hinputs] at hd
+ simp only [eval, h, ↓reduceIte, List.replicate_add]
+ exact ⟨d, .tick hs (.tick jump pre), hd, fun a ht' ho' ↦
+ (ho a ht' ho').trans (hrest a ht'), hm, hp⟩
+ · rw [ite_eq_right h] at jump
+ obtain ⟨d, pre, hd, ho, hm, hp⟩ := hn _ hcond.ifEqNo
+ {mid with pc := place (.inr (.inr (no.flow query tmp out name).entry))} rfl
+ change Prefix M _ (List.replicate (no.eval _ (fun u ↦ mid.reg (query u))).2 .tick) d at pre
+ rw [hinputs] at pre
+ change (match (no.eval _ (fun u ↦ mid.reg (query u))).1 with
+ | none => _ | some _ => _) at hd
+ rw [hinputs] at hd
+ simp only [eval, h, ↓reduceIte, List.replicate_add]
+ exact ⟨d, .tick hs (.tick jump pre), hd, fun a ht' ho' ↦
+ (ho a ht' ho').trans (hrest a ht'), hm, hp⟩
+
+end Tree
+
+/-- Comparing a row stops at the first differing field. -/
+def row (key : ι → Fin k) (yes no : Tree ι X k) : List ι → Tree ι X k
+ | [] => yes
+ | i :: is => .test i (key i) (row key yes no is) no
+
+/-- Compile a finite table in its given order, permitting partial tables. -/
+def table (fields : List ι) (key : X → ι → Fin k) : List X → Tree ι X k
+ | [] => .miss
+ | x :: xs => row (key x) (.hit x) (table fields key xs) fields
+
+private theorem row_eval (pub : Fin k → Word w) (input : ι → Word w) (key : ι → Fin k)
+ (yes no : Tree ι X k) (fields : List ι) :
+ let branch := if fields.all (fun i ↦ decide (input i = pub (key i))) then yes else no
+ ((row key yes no fields).eval pub input).1 = (branch.eval pub input).1 ∧
+ ((row key yes no fields).eval pub input).2 ≤
+ 2 * fields.length + (branch.eval pub input).2 := by
+ induction fields with
+ | nil => simp [row]
+ | cons i is ih =>
+ by_cases h : input i = pub (key i)
+ · simp only [row, Tree.eval, h, ↓reduceIte, List.all_cons, decide_true, Bool.true_and,
+ List.length_cons, Nat.mul_succ]
+ exact ⟨ih.1, by have := ih.2; omega⟩
+ · simp [row, Tree.eval, h]
+
+/-- The path returns the first matching row and performs at most two tests
+per row field plus the final dispatch. -/
+theorem table_eval (pub : Fin k → Word w) (input : ι → Word w) (fields : List ι)
+ (key : X → ι → Fin k) (xs : List X) :
+ ((table fields key xs).eval pub input).1 =
+ xs.find? (fun x ↦ fields.all fun i ↦ decide (input i = pub (key x i))) ∧
+ ((table fields key xs).eval pub input).2 ≤ 2 * fields.length * xs.length + 1 := by
+ induction xs with
+ | nil => simp [table, Tree.eval]
+ | cons x xs ih =>
+ have hr := row_eval pub input (key x) (.hit x) (table fields key xs) fields
+ by_cases h : fields.all (fun i ↦ decide (input i = pub (key x i))) = true
+ · simp only [h, ↓reduceIte, Tree.eval] at hr
+ simp only [table, List.find?_cons, h, List.length_cons, Nat.mul_succ]
+ exact ⟨hr.1, by have := hr.2; omega⟩
+ · simp only [Bool.eq_false_iff.mpr h, Bool.false_eq_true, ↓reduceIte] at hr
+ simp only [table, List.find?_cons, h, List.length_cons, Nat.mul_succ]
+ exact ⟨hr.1.trans ih.1, by have := hr.2; have := ih.2; omega⟩
+
+
+/-- Public ports can be allocated from the fixed rows and fields alone. -/
+def publicData (ports : (X × ι ⊕ X) ≃ Fin k) (key : X → ι → Word w)
+ (name : X → Word w) (i : Fin k) : Word w :=
+ (ports.symm i).elim (fun q ↦ key q.1 q.2) name
+
+@[simp] theorem publicData_key (ports : (X × ι ⊕ X) ≃ Fin k) (key : X → ι → Word w)
+ (name : X → Word w) (x : X) (i : ι) :
+ publicData ports key name (ports (.inl (x, i))) = key x i := by simp [publicData]
+
+@[simp] theorem publicData_name (ports : (X × ι ⊕ X) ≃ Fin k) (key : X → ι → Word w)
+ (name : X → Word w) (x : X) :
+ publicData ports key name (ports (.inr x)) = name x := by simp [publicData]
+
+/-- A pathwise step cap, actual normal or bad exit, and the complete
+private-memory frame available at that exit. -/
+def Runs (M : Machine w p r k) (c : Config w p r) (stop bad : Fin p) (tmp out : Fin r)
+ (name : X → Word w) (result : Option X) (cap : ℕ) : Prop :=
+ ∃ steps final, steps ≤ cap ∧ Prefix M c (List.replicate steps .tick) final ∧
+ (match result with
+ | none => final.pc = bad
+ | some x => final.pc = stop ∧ final.reg out = name x) ∧
+ (∀ j, j ≠ tmp → j ≠ out → final.reg j = c.reg j) ∧
+ final.privateMem = c.privateMem ∧ final.persistent = c.persistent
+
+/-- A deterministic tick prefix ending in the rejecting instruction rejects
+with every fuel budget, including one that expires inside the prefix. -/
+theorem reject_after_ticks {M : Machine w p r k} {c final : Config w p r}
+ {es : List (Event w)} (h : Prefix M c es final) (ticks : ∀ e ∈ es, e = .tick)
+ (bad : M.code final.pc = .reject) (fuel : ℕ) (mem : Memory w) (bits : List Bool) :
+ execute M.program fuel c mem bits = none := by
+ induction h generalizing fuel with
+ | nil =>
+ cases fuel <;> simp [execute, Machine.program, bad, Instr.run]
+ | tick step _ ih =>
+ cases fuel with
+ | zero => rfl
+ | succ fuel =>
+ simp [execute, step, ih (fun e he ↦ ticks e (List.mem_cons_of_mem _ he)) bad fuel]
+ | @choice _ _ b _ _ _ _ _ => exact (by simpa using ticks (.choice b) (by simp) : False).elim
+
+/-- A missing key rejects on every continuation budget and branch tape. -/
+theorem Runs.rejects {M : Machine w p r k} {c : Config w p r} {stop bad : Fin p}
+ {tmp out : Fin r} {name : X → Word w} {cap : ℕ}
+ (h : Runs M c stop bad tmp out name none cap) (hb : M.code bad = .reject)
+ (fuel : ℕ) (mem : Memory w) (bits : List Bool) : execute M.program fuel c mem bits = none := by
+ obtain ⟨n, d, _, pref, hd, _⟩ := h
+ exact reject_after_ticks pref (fun e he ↦ (List.eq_of_mem_replicate he))
+ (hd ▸ hb) fuel mem bits
+
+/-- The actual instructions read the given public key words. In particular
+a short path on an early match satisfies the same cap as the longest path. -/
+theorem native_table (xs : List X) (fields : List ι) (key : X → ι → Fin k)
+ (name : X → Fin k) (query : ι → Fin r) (tmp out : Fin r) (ht : ∀ i, query i ≠ tmp)
+ (M : Machine w p r k) (label : ((table fields key xs).flow query tmp out name).Label → Fin p)
+ (stop bad : Fin p) (hl : Flow.Linked M ((table fields key xs).flow query tmp out name)
+ label stop bad) (c : Config w p r)
+ (hc : c.pc = label ((table fields key xs).flow query tmp out name).entry) :
+ Runs M c stop bad tmp out (M.publicData ∘ name)
+ (xs.find? (fun x ↦ fields.all fun i ↦ decide (c.reg (query i) = M.publicData (key x i))))
+ (2 * fields.length * xs.length + 1) := by
+ obtain ⟨d, pre, hd, ho, hm, hp⟩ := (table fields key xs).native query tmp out name ht M label
+ stop bad hl c hc
+ obtain ⟨hr, hn⟩ := table_eval M.publicData (fun i ↦ c.reg (query i)) fields key xs
+ rw [hr] at hd
+ exact ⟨_, d, hn, pre, hd, ho, hm, hp⟩
+
+/-- Allocate the public ports once and compile an ordinary finite program.
+Its opcode table and register numbering are independent of the word width. -/
+def tableFlow (ports : (X × ι ⊕ X) ≃ Fin k) (xs : List X) (fields : List ι)
+ (query : ι → Fin r) (tmp out : Fin r) : Flow r k :=
+ (table fields (fun x i ↦ ports (.inl (x, i))) xs).flow query tmp out (fun x ↦ ports (.inr x))
+
+/-- The compiler provides a concrete instruction table with all constants
+installed. A caller can enter with arbitrary private memory and input
+registers. The common exit returns the ordinal and the bad exit rejects. -/
+theorem compiled_table (ports : (X × ι ⊕ X) ≃ Fin k) (xs : List X) (fields : List ι)
+ (query : ι → Fin r) (tmp out : Fin r) (ht : ∀ i, query i ≠ tmp)
+ (key : X → ι → Word w) (name : X → Word w) (rs : Fin r → Word w)
+ (state : Word w) (priv : Word w → Word w) :
+ let block := tableFlow ports xs fields query tmp out
+ let M := (block.template (some out)).instantiate w (publicData ports key name)
+ let c : Config w (block.length + 2) r := ⟨block.pc block.entry, state, rs, priv⟩
+ Runs M c block.exitPC block.rejectPC tmp out name
+ (xs.find? (fun x ↦ fields.all fun i ↦ decide (rs (query i) = key x i)))
+ (2 * fields.length * xs.length + 1) ∧ M.code block.rejectPC = .reject := by
+ dsimp only
+ let block := tableFlow ports xs fields query tmp out
+ let pub := publicData ports key name
+ let M := (block.template (some out)).instantiate w pub
+ let c : Config w (block.length + 2) r := ⟨block.pc block.entry, state, rs, priv⟩
+ have h := native_table xs fields (fun x i ↦ ports (.inl (x, i))) (fun x ↦ ports (.inr x))
+ query tmp out ht M block.pc block.exitPC block.rejectPC
+ (Flow.template_linked block (some out) pub) c rfl
+ refine ⟨?_, ?_⟩
+ · simpa only [M, c, Template.instantiate, pub, Function.comp_def, publicData_key,
+ publicData_name] using h
+ · change ((block.template (some out)).code block.rejectPC).resize w = _
+ rw [Flow.template_reject]
+ rfl
+
+/-- Widen a fixed base-motif field to one machine register without truncation. -/
+def widen {b : ℕ} (h : b ≤ w) : Word b ↪ Word w :=
+ Fin.castLEEmb (Nat.pow_le_pow_right (by decide) h)
+
+/-- Compare the anchor word against the fixed selector codes. The first
+matching selector returns its recorded ordinal. An unused code reaches
+the rejecting exit in at most twice the table length plus one tick. -/
+theorem native_selector {b : ℕ} (fits : b ≤ w) (xs : List X) (code : X ↪ Word b)
+ (key name : X → Fin k) (src tmp out : Fin r) (ht : src ≠ tmp) (tag : Word b)
+ (M : Machine w p r k) (hkey : ∀ x, M.publicData (key x) = widen fits (code x))
+ (label : ((table [()] (fun x _ ↦ key x) xs).flow (fun _ ↦ src) tmp out name).Label → Fin p)
+ (stop bad : Fin p) (hl : Flow.Linked M
+ ((table [()] (fun x _ ↦ key x) xs).flow (fun _ ↦ src) tmp out name) label stop bad)
+ (c : Config w p r) (hc : c.pc = label
+ ((table [()] (fun x _ ↦ key x) xs).flow (fun _ ↦ src) tmp out name).entry)
+ (hs : c.reg src = widen fits tag) :
+ Runs M c stop bad tmp out (M.publicData ∘ name) (MotifEntry.decode xs code tag)
+ (2 * xs.length + 1) := by
+ have h := native_table xs [()] (fun x _ ↦ key x) name (fun _ ↦ src) tmp out
+ (fun _ ↦ ht) M label stop bad hl c hc
+ simpa [MotifEntry.decode, hs, hkey, eq_comm] using h
+
+
+section Label
+
+open MotifGrid MotifBlocks MotifSelector MotifDemandPadding MotifConversion
+
+variable {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {src dst : D → J} {P : Supply J S}
+
+open Classical in
+/-- Absent endpoints contribute zero to the fixed tuple of compared words.
+The two ends of a loop have distinct positions. -/
+noncomputable def halfKey {E : Type} (a b : E → J) (width : E → ℕ) (fit : ∀ e, width e ≤ w)
+ (j : J) (x : HalfBits a b width j) : Bool × E → BurstRAM.Word w
+ | (false, e) => if h : j = a e then widen (fit e) (x.1 e h) else 0
+ | (true, e) => if h : j = b e then widen (fit e) (x.2 e h) else 0
+
+omit [Fintype J] in
+private theorem halfKey_injective {E : Type} (a b : E → J) (width : E → ℕ)
+ (fit : ∀ e, width e ≤ w) (j : J) : Function.Injective (halfKey a b width fit j) := by
+ intro x y he
+ apply Prod.ext
+ · funext e h
+ have eq := congrFun he (false, e)
+ simpa [halfKey, h] using eq
+ · funext e h
+ have eq := congrFun he (true, e)
+ simpa [halfKey, h] using eq
+
+variable {K : Type} [Field K] {p₀ : D → ℚ} {q₀ : S → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst P (realWidths p₀) (realWidths q₀) H H')
+ (z : B.grid.demands) (s : Selector B) (j : J)
+
+/-- Exactly the two input tuples in the fixed label lookup of the motif evaluator. -/
+abbrev LabelRow := HalfBits src dst (baseDemand B z) j ×
+ Half P (fun e ↦ MotifSelector.Word (basePayload B s e)) j
+
+open Classical in
+/-- The fixed matrix has one row for each pair of local coordinates. -/
+noncomputable def labelRows : List (LabelRow B z s j) := Finset.univ.toList
+
+theorem mem_labelRows (x : LabelRow B z s j) : x ∈ labelRows B z s j := by simp [labelRows]
+
+/-- An endpoint field used in matrix-row lookup. The sum distinguishes demand from supply
+edges, and the Boolean selects the source or target endpoint. -/
+abbrev LabelField (D S : Type) := (Bool × D) ⊕ (Bool × S)
+
+open Classical in
+/-- All endpoints can be numbered once for a fixed base motif. -/
+noncomputable def labelFields (D S : Type) [Fintype D] [Fintype S] : List (LabelField D S) :=
+ Finset.univ.toList
+
+theorem mem_labelFields (i : LabelField D S) : i ∈ labelFields D S := by simp [labelFields]
+
+/-- The same bound holds at all grid points, selectors and parties of the
+fixed motif, before choosing the widths or the number of outer copies. -/
+theorem label_step_cap :
+ 2 * (labelFields D S).length * (labelRows B z s j).length + 1 ≤
+ 2 * (labelFields D S).length * Nat.card (parameterData B).Entry + 1 := by
+ classical
+ let incl : LabelRow B z s j → (parameterData B).Entry := fun x ↦ lookup B z s j x.1 x.2
+ have hinj : Function.Injective incl := by
+ rintro ⟨a, b⟩ ⟨a', b'⟩ h
+ have h₁ := eq_of_heq (Sigma.mk.inj h).2
+ have h₂ := eq_of_heq (Sigma.mk.inj h₁).2
+ exact eq_of_heq (Sigma.mk.inj h₂).2
+ have hcard := Nat.card_le_card_of_injective incl hinj
+ simp only [labelRows, Finset.length_toList, Finset.card_univ]
+ exact Nat.add_le_add_right (Nat.mul_le_mul_left _ (by simpa using hcard)) 1
+
+variable (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ e, basePayload B s e ≤ w)
+
+/-- Every demand and supply coordinate is represented by its widened natural digit. -/
+noncomputable def labelKey (x : LabelRow B z s j) : LabelField D S → BurstRAM.Word w :=
+ Sum.elim (halfKey src dst (baseDemand B z) fd j x.1)
+ (halfKey P.src P.dst (basePayload B s) fs j x.2)
+
+theorem labelKey_injective : Function.Injective (labelKey B z s j fd fs) := by
+ intro x y h
+ exact Prod.ext (halfKey_injective _ _ _ fd j (funext (fun i ↦ congrFun h (.inl i))))
+ (halfKey_injective _ _ _ fs j (funext (fun i ↦ congrFun h (.inr i))))
+
+/-- Scan the complete fixed local matrix. The query registers hold the
+decoded fields of one copy, in their own endpoint positions. A successful
+scan emits precisely the ordinal of the parameter in equation (6.2). -/
+theorem native_label_exact (rows : List (LabelRow B z s j)) (complete : ∀ x, x ∈ rows)
+ (fields : List (LabelField D S)) (covers : ∀ i, i ∈ fields)
+ (key : LabelRow B z s j → LabelField D S → Fin k) (name : LabelRow B z s j → Fin k)
+ (query : LabelField D S → Fin r) (tmp out : Fin r) (ht : ∀ i, query i ≠ tmp)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) (M : Machine w p r k)
+ (hkey : ∀ y i, M.publicData (key y i) = labelKey B z s j fd fs y i)
+ (hname : ∀ y, M.publicData (name y) = ordinal (lookup B z s j y.1 y.2))
+ (label : ((table fields key rows).flow query tmp out name).Label → Fin p)
+ (stop bad : Fin p) (hl : Flow.Linked M ((table fields key rows).flow query tmp out name)
+ label stop bad) (c : Config w p r)
+ (hc : c.pc = label ((table fields key rows).flow query tmp out name).entry)
+ (x : LabelRow B z s j) (hquery : ∀ i, c.reg (query i) = labelKey B z s j fd fs x i) :
+ let a := (table fields key rows).eval M.publicData (labelKey B z s j fd fs x)
+ ∃ final, Prefix M c (List.replicate a.2 .tick) final ∧
+ final.pc = stop ∧ final.reg out = ordinal (lookup B z s j x.1 x.2) ∧
+ (∀ i, i ≠ tmp → i ≠ out → final.reg i = c.reg i) ∧
+ final.privateMem = c.privateMem ∧ final.persistent = c.persistent := by
+ intro a
+ let isMatch := fun y ↦ fields.all fun i ↦ decide (c.reg (query i) = M.publicData (key y i))
+ have hm (y) : isMatch y = true ↔ x = y := by
+ simp only [isMatch, List.all_eq_true, decide_eq_true_eq, hquery, hkey]
+ exact ⟨fun h ↦ labelKey_injective B z s j fd fs (funext (fun i ↦ h i (covers i))),
+ fun e _ _ ↦ e ▸ rfl⟩
+ have hf : rows.find? isMatch = some x := by
+ cases he : rows.find? isMatch with
+ | none =>
+ exact ((List.find?_eq_none.mp he x (complete x)) ((hm x).2 rfl)).elim
+ | some y =>
+ have eq := (hm y).1 (List.find?_some he)
+ rw [eq]
+ obtain ⟨final, pre, exit, frame, mem, state⟩ :=
+ (table fields key rows).native query tmp out name ht M label stop bad hl c hc
+ have result := (table_eval M.publicData (fun i ↦ c.reg (query i)) fields key rows).1.trans hf
+ rw [result] at exit
+ rw [funext hquery] at pre
+ exact ⟨final, pre, exit.1, exit.2.trans (hname x), frame, mem, state⟩
+
+/-- The complete local matrix lookup also satisfies its uniform table cap. -/
+theorem native_label (rows : List (LabelRow B z s j)) (complete : ∀ x, x ∈ rows)
+ (fields : List (LabelField D S)) (covers : ∀ i, i ∈ fields)
+ (key : LabelRow B z s j → LabelField D S → Fin k) (name : LabelRow B z s j → Fin k)
+ (query : LabelField D S → Fin r) (tmp out : Fin r) (ht : ∀ i, query i ≠ tmp)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) (M : Machine w p r k)
+ (hkey : ∀ y i, M.publicData (key y i) = labelKey B z s j fd fs y i)
+ (hname : ∀ y, M.publicData (name y) = ordinal (lookup B z s j y.1 y.2))
+ (label : ((table fields key rows).flow query tmp out name).Label → Fin p)
+ (stop bad : Fin p) (hl : Flow.Linked M ((table fields key rows).flow query tmp out name)
+ label stop bad) (c : Config w p r)
+ (hc : c.pc = label ((table fields key rows).flow query tmp out name).entry)
+ (x : LabelRow B z s j) (hquery : ∀ i, c.reg (query i) = labelKey B z s j fd fs x i) :
+ Runs M c stop bad tmp out (fun y ↦ ordinal (lookup B z s j y.1 y.2)) (some x)
+ (2 * fields.length * rows.length + 1) := by
+ let a := (table fields key rows).eval M.publicData (labelKey B z s j fd fs x)
+ obtain ⟨final, pre, pc, value, frame, mem, state⟩ :=
+ native_label_exact B z s j fd fs rows complete fields covers key name query tmp out ht
+ ordinal M hkey hname label stop bad hl c hc x hquery
+ exact ⟨a.2, final, (table_eval ..).2, pre, ⟨pc, value⟩, frame, mem, state⟩
+
+end Label
+
+end PairSimulation.MapLookup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapNativeClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapNativeClock.lean
new file mode 100644
index 0000000000..6571ca85f1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapNativeClock.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PairSimulationMapRowLoop
+import OAI.Computability.VPVNP.PairSimulationMapSelectors
+import OAI.Computability.VPVNP.PairSimulationMapTotalCheck
+import OAI.Computability.VPVNP.PairSimulationEntryWork
+
+/-!
+# Instruction budgets for a complete fixed-template map call
+
+The bounds include the port comparison, selector decoder, repeated label
+lookups, the full-vector width comparison and the local histogram update.
+The table constant is chosen before the dynamic widths and all input bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapNativeClock
+
+open MotifBlocks MotifConversion MotifGrid MotifSelector MapPortAgreement
+
+variable {K J D E : Type} [Field K] [Fintype J] [Fintype D] [Fintype E]
+ {src dst : D → J} {G : Supply J E} {p : D → ℚ} {q : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p) (realWidths q) H H')
+
+/-- The instruction bounds of the five linked phases at a selected grid row.
+Two incident ports per supply edge suffice even when both ends are at this party. -/
+noncomputable def cap (z : B.grid.demands) (j : J) (u : ℕ) : ℕ :=
+ ((7 * (u * B.selectorBits) + 6) * (2 * Fintype.card E) + 3) +
+ ((6 * B.selectorBits + 1 + (2 * (selectorTable B).length + 1) + 5) * u + 1) +
+ ((5 + 2 * (selectorTable B).length + MapRowLoop.rowCap B z j) * u + 1) +
+ (Fintype.card E + 1) + (7 * u + 1)
+
+/-- Fixing the tables gives a linear instruction cap, including the final
+width comparisons on a descriptor whose totals differ. -/
+theorem uniform : ∃ C : ℕ, ∀ z j u, cap B z j u ≤ C * (u + 1) := by
+ let M := ∑ z : B.grid.demands, ∑ j, MapRowLoop.rowCap B z j
+ let C := (7 * B.selectorBits + 6) * (2 * Fintype.card E) + 3 +
+ (6 * B.selectorBits + 1 + (2 * (selectorTable B).length + 1) + 5 + 1) +
+ (5 + 2 * (selectorTable B).length + M + 1) + (Fintype.card E + 1) + 8
+ refine ⟨C, fun z j u ↦ ?_⟩
+ have hm : MapRowLoop.rowCap B z j ≤ M :=
+ (Finset.single_le_sum (fun a _ ↦ Nat.zero_le (MapRowLoop.rowCap B z a))
+ (Finset.mem_univ j)).trans
+ (Finset.single_le_sum (fun a _ ↦ Nat.zero_le (∑ j, MapRowLoop.rowCap B a j))
+ (Finset.mem_univ z))
+ unfold cap
+ dsimp only [C]
+ nlinarith only [Nat.mul_le_mul_right u hm, hm, Nat.zero_le u, Nat.zero_le M,
+ Nat.zero_le B.selectorBits, Nat.zero_le (Fintype.card E * B.selectorBits),
+ Nat.zero_le (Fintype.card E * u), Nat.zero_le (selectorTable B).length]
+
+end PairSimulation.MapNativeClock
+
+namespace PairSimulation.LocalHistory
+
+open Compression MotifBlocks MotifGrid MotifConversion MotifSelector
+
+variable {K : Type} [Field K] {S : BlockSchedule K} (B : S.Templates)
+
+open scoped Classical in
+/-- The exact two motif tables of the selected compressor. Direct equality
+checks emit no parameters and use their separate field comparison routines. -/
+noncomputable def MapInvocation.nativeCap {d : ℕ} : MapInvocation B d → ℕ
+ | .shrink x _ => MapNativeClock.cap B.shrink
+ (demandGrid B.shrink ShrinkMotif.demandMass_pos x.demand) x.party
+ (repetitions B.shrink x.demand)
+ | .refresh x _ => MapNativeClock.cap B.refresh
+ (demandGrid B.refresh (fun _ ↦ zero_lt_one) x.demand) x.party (repetitions B.refresh x.demand)
+ | .noLookup => 0
+
+/-- A single table constant covers both actual passes and all malformed bits. -/
+theorem mapInvocation_nativeCap (B : S.Templates) :
+ ∃ C : ℕ, ∀ d (m : MapInvocation B d), m.nativeCap B ≤ C * (d + 1) := by
+ classical
+ obtain ⟨A, ha⟩ := MapNativeClock.uniform B.shrink
+ obtain ⟨A', ha'⟩ := MapNativeClock.uniform B.refresh
+ refine ⟨max A A', fun d m ↦ ?_⟩
+ cases m with
+ | shrink x hx => exact (ha ..).trans (Nat.mul_le_mul (le_max_left ..) (Nat.succ_le_succ hx))
+ | refresh x hx => exact (ha' ..).trans (Nat.mul_le_mul (le_max_right ..) (Nat.succ_le_succ hx))
+ | noLookup => exact Nat.zero_le _
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapOffsets.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapOffsets.lean
new file mode 100644
index 0000000000..c9969bf85e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapOffsets.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowLinks
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Advancing the field offsets of one decoded motif copy
+
+Each selected base profile supplies one fixed width for each demand or supply
+group. Loading its public width and adding it to the group's offset takes two
+private instructions. The finite group list is part of the fixed template.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapOffsets
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {E : Type*} {w p r k : ℕ}
+
+/-- Load each listed group's public width into `tmp` and add it to the group's offset. -/
+def code (off : E ↪ Fin r) (delta : E → Fin k) (tmp : Fin r) : List E → Flow r k
+ | [] => .line (.guardEq tmp tmp)
+ | e :: es =>
+ (Flow.line (.publicWord tmp (delta e))).seq
+ ((Flow.line (.binary .add (off e) (off e) tmp)).seq (code off delta tmp es))
+
+/-- After one pass over distinct groups, their offset registers contain the
+old value plus the selected public width. Registers outside the group list
+and the scratch register retain their original values. -/
+theorem native [DecidableEq E] (off : E ↪ Fin r) (delta : E → Fin k) (tmp : Fin r)
+ (disjoint : ∀ e, off e ≠ tmp) (es : List E) (hd : es.Nodup)
+ (M : Machine w p r k) (label : (code off delta tmp es).Label → Fin p)
+ (stop bad : Fin p) (link : Flow.Linked M (code off delta tmp es) label stop bad)
+ (c : Config w p r) (hc : c.pc = label (code off delta tmp es).entry) :
+ ∃ out, Prefix M c (List.replicate (2 * es.length + 1) .tick) out ∧ out.pc = stop ∧
+ (∀ e, out.reg (off e) = c.reg (off e) + if e ∈ es then M.publicData (delta e) else 0) ∧
+ (∀ j, j ≠ tmp → (∀ e ∈ es, j ≠ off e) → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ induction es generalizing c with
+ | nil =>
+ have hs : M.program.step c = .localStep {c with pc := stop} := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hc, link.atLabel]
+ change CallAction.localStep {c with pc := if c.reg tmp = c.reg tmp then stop else bad} = _
+ simp
+ exact ⟨_, .tick hs (.nil _), rfl, by simp, fun _ _ _ ↦ rfl, rfl, rfl⟩
+ | cons e es ih =>
+ let tail := code off delta tmp es
+ let addLabel : (code off delta tmp (e :: es)).Label := .inr (.inl ())
+ let c₁ := c.put (label addLabel) tmp (M.publicData (delta e))
+ let enter := label (.inr (.inr tail.entry))
+ let c₂ := c₁.put enter (off e) (c.reg (off e) + M.publicData (delta e))
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hc, link.atLabel]
+ rfl
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [show M.program.step c₁ = (M.code (label addLabel)).run M.publicData c₁ from rfl,
+ link.atLabel addLabel]
+ change CallAction.localStep (c₁.put enter (off e) (c₁.reg (off e) + c₁.reg tmp)) = _
+ simp [c₂, c₁, Config.put, Function.update_of_ne (disjoint e)]
+ have short : Prefix M c [.tick, .tick] c₂ := .tick s₀ (.tick s₁ (.nil _))
+ obtain ⟨out, pre, ho, regs, other, hm, hp⟩ :=
+ ih (List.nodup_cons.mp hd).2 ((label ∘ Sum.inr) ∘ Sum.inr) link.seqRight.seqRight c₂ rfl
+ refine ⟨out, ?_, ho, ?_, ?_, hm, hp⟩
+ · convert short.append pre using 1
+ change List.replicate (2 * (e :: es).length + 1) _ =
+ List.replicate 2 _ ++ List.replicate (2 * es.length + 1) _
+ rw [← List.replicate_add, List.length_cons]
+ congr 1
+ omega
+ · intro x
+ rw [regs]
+ by_cases h : x = e
+ · subst x
+ simp [c₂, (List.nodup_cons.mp hd).1]
+ · simp [c₂, c₁, Config.put, Function.update_of_ne (disjoint x), h]
+ · intro j htmp hgroup
+ rw [other j htmp (fun i hi ↦ hgroup i (List.mem_cons_of_mem _ hi))]
+ simp [c₂, c₁, Config.put, Function.update_of_ne (hgroup e List.mem_cons_self),
+ Function.update_of_ne htmp]
+
+end PairSimulation.MapOffsets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapPortAgreement.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapPortAgreement.lean
new file mode 100644
index 0000000000..01a81c1b7d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapPortAgreement.lean
@@ -0,0 +1,173 @@
+import OAI.Computability.VPVNP.PairSimulationMapConsistency
+import Mathlib.Data.List.FinRange
+
+/-!
+# Port comparisons for the grouped motif map
+
+A party visits the source incidences in a fixed edge order, then the target
+incidences in that order. A loop contributes both of its ports. Within each
+port the selector copies are consecutive. Agreement of the resulting two
+word arrays is the selector test in the motif entry algorithm on page 21.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapPortAgreement
+
+open MotifSelector
+
+variable {J E : Type*} {u bits : ℕ}
+
+/-- The two incidences of a self-loop are distinct ports. -/
+abbrev Port (G : Supply J E) (j : J) := {e // j = G.src e} ⊕ {e // j = G.dst e}
+
+/-- Read a half-wire tag through its source or target incidence. -/
+def portTag {G : Supply J E} {j : J} (tags : Half G (fun _ => Fin u → Word bits) j) :
+ Port G j → Fin u → Word bits
+ | .inl e => tags.1 e.val e.property
+ | .inr e => tags.2 e.val e.property
+
+variable [DecidableEq J] [Fintype E]
+
+theorem consistent_iff_ports (G : Supply J E) (j : J)
+ (tags : Half G (fun _ => Fin u → Word bits) j) :
+ MotifEntry.consistent G j tags = true ↔
+ ∀ (p : Port G j) (i : Fin u), portTag tags p i = MotifEntry.anchor G j tags i := by
+ simp only [MotifEntry.consistent, decide_eq_true_iff]
+ constructor
+ · intro h p
+ cases p with
+ | inl e => simpa [e.property, portTag] using (h e.val).1
+ | inr e => simpa [e.property, portTag] using (h e.val).2
+ · intro h e
+ constructor
+ · split
+ · rename_i he
+ exact h (.inl ⟨e, he⟩)
+ · trivial
+ · split
+ · rename_i he
+ exact h (.inr ⟨e, he⟩)
+ · trivial
+
+private def keep (P : E → Prop) [DecidablePred P] (e : E) : Option {e // P e} :=
+ if h : P e then some ⟨e, h⟩ else none
+
+omit [Fintype E] in
+private theorem mem_keep {P : E → Prop} [DecidablePred P] {e : E} {t : {e // P e}} :
+ t ∈ keep P e ↔ t.val = e := by
+ unfold keep
+ split
+ · simp [Subtype.ext_iff, eq_comm]
+ · rename_i he
+ have ht : t.val ≠ e := fun h => he (h ▸ t.property)
+ simp [ht]
+
+private def incidences (P : E → Prop) [DecidablePred P]
+ (order : Fin (Fintype.card E) ≃ E) : List {e // P e} :=
+ (List.ofFn order).filterMap (keep P)
+
+private theorem mem_incidences {P : E → Prop} [DecidablePred P]
+ (order : Fin (Fintype.card E) ≃ E) (t : {e // P e}) : t ∈ incidences P order := by
+ apply List.mem_filterMap.mpr
+ exact ⟨t.val, List.mem_ofFn.mpr ⟨order.symm t.val, order.apply_symm_apply _⟩,
+ by simp [keep, t.property]⟩
+
+private theorem incidences_nodup (P : E → Prop) [DecidablePred P]
+ (order : Fin (Fintype.card E) ≃ E) : (incidences P order).Nodup :=
+ List.Nodup.filterMap (fun _ _ _ h h' => (mem_keep.mp h).symm.trans (mem_keep.mp h'))
+ (List.nodup_ofFn_ofInjective order.injective)
+
+private theorem length_incidences_le (P : E → Prop) [DecidablePred P]
+ (order : Fin (Fintype.card E) ≃ E) : (incidences P order).length ≤ Fintype.card E := by
+ simpa [incidences] using List.length_filterMap_le (keep P) (List.ofFn order)
+
+/-- The comparison schedule uses only the party, supply graph and fixed edge numbering. -/
+def ports (G : Supply J E) (j : J) (order : Fin (Fintype.card E) ≃ E) : List (Port G j) :=
+ (incidences (fun e => j = G.src e) order).map Sum.inl ++
+ (incidences (fun e => j = G.dst e) order).map Sum.inr
+
+theorem mem_ports (G : Supply J E) (j : J) (order : Fin (Fintype.card E) ≃ E) (p : Port G j) :
+ p ∈ ports G j order := by
+ cases p with
+ | inl e => exact List.mem_append_left _ (List.mem_map_of_mem (mem_incidences order e))
+ | inr e => exact List.mem_append_right _ (List.mem_map_of_mem (mem_incidences order e))
+
+theorem ports_nodup (G : Supply J E) (j : J) (order : Fin (Fintype.card E) ≃ E) :
+ (ports G j order).Nodup := by
+ apply List.Nodup.append
+ · exact (incidences_nodup _ order).map Sum.inl_injective
+ · exact (incidences_nodup _ order).map Sum.inr_injective
+ · intro p hl hr
+ obtain ⟨s, _, rfl⟩ := List.mem_map.mp hl
+ obtain ⟨t, _, ht⟩ := List.mem_map.mp hr
+ cases ht
+
+theorem ports_length_le (G : Supply J E) (j : J) (order : Fin (Fintype.card E) ≃ E) :
+ (ports G j order).length ≤ 2 * Fintype.card E := by
+ simpa [ports, two_mul] using Nat.add_le_add (length_incidences_le (fun e => j = G.src e) order)
+ (length_incidences_le (fun e => j = G.dst e) order)
+
+/-- The incident-port array in port-major order. -/
+def leftTags (G : Supply J E) (j : J) (order : Fin (Fintype.card E) ≃ E)
+ (tags : Half G (fun _ => Fin u → Word bits) j) (k : Fin ((ports G j order).length * u)) :
+ Word bits :=
+ let pi := finProdFinEquiv.symm k
+ portTag tags ((ports G j order).get pi.1) pi.2
+
+/-- Each block repeats the anchor's selector sequence. -/
+def rightTags (G : Supply J E) (j : J) (order : Fin (Fintype.card E) ≃ E)
+ (tags : Half G (fun _ => Fin u → Word bits) j) (k : Fin ((ports G j order).length * u)) :
+ Word bits :=
+ MotifEntry.anchor G j tags (finProdFinEquiv.symm k).2
+
+/-- Pointwise equality of the two resident arrays computes precisely the
+motif selector agreement test, including an empty selector sequence. -/
+theorem consistent_iff_scan (G : Supply J E) (j : J) (order : Fin (Fintype.card E) ≃ E)
+ (tags : Half G (fun _ => Fin u → Word bits) j) :
+ MotifEntry.consistent G j tags = true ↔
+ ∀ k, leftTags G j order tags k = rightTags G j order tags k := by
+ rw [consistent_iff_ports]
+ constructor
+ · exact fun h k => h _ _
+ · intro h p i
+ obtain ⟨a, rfl⟩ := List.mem_iff_get.mp (mem_ports G j order p)
+ simpa only [leftTags, rightTags, Equiv.symm_apply_apply] using h (finProdFinEquiv (a, i))
+
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+/-- On the two resident tag arrays the fixed native dispatch branches exactly
+as the grouped motif entry does. All inputs incur the same instruction count. -/
+theorem consistent_native {w p r k : ℕ} {M : Machine w p r k} {pc : Fin 7 → Fin p}
+ {reg : Fin 7 ↪ Fin r} {done : Fin p} (G : Supply J E) (j : J)
+ (order : Fin (Fintype.card E) ≃ E) (tags : Half G (fun _ => Fin u → Word bits) j)
+ (enc : Word bits ↪ BurstRAM.Word w) (hl : MapConsistency.Linked M pc reg done)
+ (test yes no : Fin p) (hz : M.code done = .constant (reg 5) 0 test)
+ (hj : M.code test = .jumpEq (reg 4) (reg 5) yes no)
+ (left right : BurstRAM.Word w) (c : Config w p r) (hc : c.pc = pc 0)
+ (hleft : c.reg (reg 0) = left) (hright : c.reg (reg 2) = right)
+ (h1 : c.reg (reg 3) = 1) (hzero : c.reg (reg 4) = 0) :
+ let n := (ports G j order).length * u
+ c.reg (reg 1) = left + (n : BurstRAM.Word w) → n < 2 ^ w →
+ (∀ i : Fin n, c.privateMem (left + (i.val : BurstRAM.Word w)) =
+ enc (leftTags G j order tags i)) →
+ (∀ i : Fin n, c.privateMem (right + (i.val : BurstRAM.Word w)) =
+ enc (rightTags G j order tags i)) →
+ ∃ out, Prefix M c (List.replicate (7 * n + 3) .tick) out ∧
+ out.pc = (if MotifEntry.consistent G j tags then yes else no) ∧
+ MapConsistency.Frame reg c out ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent := by
+ intro n hend hfit hx hy
+ obtain ⟨out, run, hpc, frame, hm, hp⟩ := MapConsistency.compareTags enc hl test yes no hz hj
+ (leftTags G j order tags) (rightTags G j order tags) left right c hc hleft hend hright h1 hzero
+ hfit hx hy
+ exact ⟨out, run, by simpa only [consistent_iff_scan G j order tags] using hpc, frame, hm, hp⟩
+
+end PairSimulation.MapPortAgreement
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapPortScan.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapPortScan.lean
new file mode 100644
index 0000000000..e39a3cf4a5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapPortScan.lean
@@ -0,0 +1,187 @@
+import OAI.Computability.VPVNP.PairSimulationMapConsistency
+
+/-!
+# A private directory scan comparing all incident selector fields
+
+Each directory cell points to the beginning of a port's selector suffix.
+The enclosing loop reads that pointer and compares the suffix to the same
+anchor, carrying the difference mask across ports. The anchor and directory
+may overlap any of the input fields because every memory access is a read.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapPortScan
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- The comparison loop uses the first seven of the directory scanner's registers. -/
+def innerRegs (reg : Fin 11 ↪ Fin r) : Fin 7 ↪ Fin r := (Fin.castLEEmb (by decide)).trans reg
+
+/-- Registers 7 through 10 hold the directory cursor, its exclusive end,
+the first selector bit of the anchor, and the common selector length. -/
+def instruction (pc : Fin 7 → Fin p) (reg : Fin 11 ↪ Fin r) (inner yes no : Fin p) :
+ Fin 7 → Instr w p r k :=
+ ![.jumpEq (reg 7) (reg 8) (pc 5) (pc 1),
+ .loadPrivate (reg 0) (reg 7) (pc 2), .binary .add (reg 1) (reg 0) (reg 10) (pc 3),
+ .copy (reg 2) (reg 9) inner, .binary .add (reg 7) (reg 7) (reg 3) (pc 0),
+ .constant (reg 5) 0 (pc 6), .jumpEq (reg 4) (reg 5) yes no]
+
+theorem resize_instruction (pc : Fin 7 → Fin p) (reg : Fin 11 ↪ Fin r) (inner yes no : Fin p)
+ (i : Fin 7) :
+ (instruction (w := 1) (k := k) pc reg inner yes no i).resize w =
+ instruction pc reg inner yes no i := by
+ fin_cases i <;> rfl
+
+/-- The fixed outer code invokes the same inner loop for every directory entry. -/
+structure Linked (M : Machine w p r k) (pc inner : Fin 7 → Fin p) (reg : Fin 11 ↪ Fin r)
+ (yes no : Fin p) : Prop where
+ outer : ∀ i, M.code (pc i) = instruction pc reg (inner 0) yes no i
+ body : MapConsistency.Linked M inner (innerRegs reg) (pc 4)
+
+/-- The port-directory scan writes the directory cursor and six inner-loop registers. -/
+def Preserved (reg : Fin 11 ↪ Fin r) (a : Fin r) : Prop :=
+ a ≠ reg 0 ∧ a ≠ reg 1 ∧ a ≠ reg 2 ∧ a ≠ reg 4 ∧ a ≠ reg 5 ∧ a ≠ reg 6 ∧ a ≠ reg 7
+
+/-- All words of every selected slice equal the corresponding words of the anchor. -/
+def Agrees (mem : Word w → Word w) (dir anchor : Word w) (ports width : ℕ) : Prop :=
+ ∀ i : Fin ports, ∀ j : Fin width,
+ mem (mem (dir + (i.val : Word w)) + (j.val : Word w)) = mem (anchor + (j.val : Word w))
+
+instance (mem : Word w → Word w) (dir anchor : Word w) (ports width : ℕ) :
+ Decidable (Agrees mem dir anchor ports width) := inferInstanceAs (Decidable (∀ _, ∀ _, _))
+
+variable {M : Machine w p r k} {pc inner : Fin 7 → Fin p} {reg : Fin 11 ↪ Fin r} {yes no : Fin p}
+
+private theorem step_at (hl : Linked M pc inner reg yes no) (i : Fin 7) {c : Config w p r}
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg (inner 0) yes no i).run M.publicData c := by
+ simp [Machine.program, hc, hl.outer i]
+
+private theorem onePort (hl : Linked M pc inner reg yes no) (width : ℕ) (c : Config w p r)
+ (hc : c.pc = pc 0) (hne : c.reg (reg 7) ≠ c.reg (reg 8))
+ (hlen : c.reg (reg 10) = (width : Word w)) (hw : width < 2 ^ w) (h1 : c.reg (reg 3) = 1) :
+ ∃ out, Prefix M c (List.replicate (7*width+6) .tick) out ∧ out.pc = pc 0 ∧
+ out.reg (reg 7) = c.reg (reg 7) + 1 ∧
+ (out.reg (reg 4) = 0 ↔ c.reg (reg 4) = 0 ∧ ∀ j : Fin width,
+ c.privateMem (c.privateMem (c.reg (reg 7)) + (j.val : Word w)) =
+ c.privateMem (c.reg (reg 9) + (j.val : Word w))) ∧
+ (∀ a, Preserved reg a → out.reg a = c.reg a) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let start := c.privateMem (c.reg (reg 7))
+ let anchor := c.reg (reg 9)
+ let c₁ := {c with pc := pc 1}
+ let c₂ := c₁.put (pc 2) (reg 0) start
+ let c₃ := c₂.put (pc 3) (reg 1) (start + (width : Word w))
+ let q := c₃.put (inner 0) (reg 2) anchor
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step_at hl 0 hc]
+ simp [instruction, Instr.run, hne, c₁]
+ have s₁ : M.program.step c₁ = .localStep c₂ := step_at hl 1 rfl
+ have s₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step_at hl 2 rfl]
+ change CallAction.localStep (c₂.put (pc 3) (reg 1) (c₂.reg (reg 0) + c₂.reg (reg 10))) = _
+ simp [c₃, c₂, c₁, Config.put, hlen]
+ have s₃ : M.program.step c₃ = .localStep q := by
+ rw [step_at hl 3 rfl]
+ change CallAction.localStep (c₃.put (inner 0) (reg 2) (c₃.reg (reg 9))) = _
+ simp [q, c₃, c₂, c₁, Config.put, anchor]
+ have setup : Prefix M c (List.replicate 4 .tick) q :=
+ .tick s₀ (.tick s₁ (.tick s₂ (.tick s₃ (.nil _))))
+ obtain ⟨d, scan, hd, _, _, mask, frame, hm, hp⟩ :=
+ MapConsistency.compareArrays hl.body (fun i : Fin width ↦ c.privateMem (start+(i.val:Word w)))
+ (fun i : Fin width ↦ c.privateMem (anchor+(i.val:Word w))) start anchor q rfl
+ (by change q.reg (reg 0) = _; simp [q, c₃, c₂, Config.put])
+ (by change q.reg (reg 1) = _; simp [q, c₃, Config.put])
+ (by change q.reg (reg 2) = _; simp [q])
+ (by change q.reg (reg 3) = _; simp [q, c₃, c₂, c₁, Config.put, h1]) hw
+ (fun _ ↦ rfl) (fun _ ↦ rfl)
+ have d3 : d.reg (reg 3) = 1 := by
+ rw [frame] <;> simp [innerRegs, q, c₃, c₂, c₁, Config.put, h1]
+ have d7 : d.reg (reg 7) = c.reg (reg 7) := by
+ rw [frame] <;> simp [innerRegs, q, c₃, c₂, c₁, Config.put]
+ let out := d.put (pc 0) (reg 7) (c.reg (reg 7) + 1)
+ have last : M.program.step d = .localStep out := by
+ rw [step_at hl 4 hd]
+ change CallAction.localStep (d.put (pc 0) (reg 7) (d.reg (reg 7) + d.reg (reg 3))) = _
+ rw [d7, d3]
+ have finalStep : Prefix M d (List.replicate 1 .tick) out := .tick last (.nil _)
+ refine ⟨out, ?_, rfl, by simp [out], ?_, ?_, hm, hp⟩
+ · convert (setup.append scan).append finalStep using 1
+ rw [← List.replicate_add, ← List.replicate_add]
+ congr 1
+ omega
+ · change d.reg (reg 4) = 0 ↔ _ at mask
+ simpa [out, q, c₃, c₂, c₁, Config.put, innerRegs, start, anchor] using mask
+ · rintro a ⟨h₀,h₁,h₂,h₄,h₅,h₆,h₇⟩
+ change Function.update d.reg (reg 7) _ a = _
+ rw [Function.update_of_ne h₇, frame]
+ · simp [q, c₃, c₂, c₁, Config.put, Function.update_of_ne, h₀, h₁, h₂]
+ all_goals assumption
+
+/-- The loop walks the pointer table and branches to its declared success
+or failure label. Its fixed trace length applies on malformed words too. -/
+theorem run (hl : Linked M pc inner reg yes no) (ports width : ℕ) (dir anchor : Word w)
+ (c : Config w p r) (hc : c.pc = pc 0) (hdir : c.reg (reg 7) = dir)
+ (hend : c.reg (reg 8) = dir + (ports : Word w)) (ha : c.reg (reg 9) = anchor)
+ (hlen : c.reg (reg 10) = (width : Word w)) (hn : ports < 2 ^ w) (hw : width < 2 ^ w)
+ (h1 : c.reg (reg 3) = 1) :
+ ∃ out, Prefix M c (List.replicate ((7*width+6)*ports+3) .tick) out ∧
+ out.pc = (if c.reg (reg 4) = 0 ∧ Agrees c.privateMem dir anchor ports width
+ then yes else no) ∧
+ (∀ a, Preserved reg a → out.reg a = c.reg a) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ induction ports generalizing c dir with
+ | zero =>
+ have he : c.reg (reg 7) = c.reg (reg 8) := hdir.trans (by simpa using hend.symm)
+ let q := {c with pc := pc 5}
+ let d := q.put (pc 6) (reg 5) 0
+ let out := {d with pc := if c.reg (reg 4) = 0 then yes else no}
+ have s₀ : M.program.step c = .localStep q := by
+ rw [step_at hl 0 hc]
+ simp [instruction, Instr.run, he, q]
+ have s₁ : M.program.step q = .localStep d := step_at hl 5 rfl
+ have s₂ : M.program.step d = .localStep out := by
+ rw [step_at hl 6 rfl]
+ change CallAction.localStep
+ {d with pc := if d.reg (reg 4) = d.reg (reg 5) then yes else no} = _
+ simp [d, q, out, Config.put]
+ refine ⟨out, .tick s₀ (.tick s₁ (.tick s₂ (.nil _))), by simp [out, Agrees], ?_, rfl, rfl⟩
+ rintro a ⟨_,_,_,_,h₅,_,_⟩
+ simp [out, d, q, Config.put, Function.update_of_ne h₅]
+ | succ n ih =>
+ have ne : c.reg (reg 7) ≠ c.reg (reg 8) := by
+ rw [hdir, hend]
+ intro h
+ have hz : ((n+1 : ℕ) : Word w) = 0 := add_left_cancel (a := dir) (by simpa using h.symm)
+ have hv := congrArg Fin.val hz
+ change (n+1) % (2 ^ w) = 0 at hv
+ rw [Nat.mod_eq_of_lt hn] at hv
+ omega
+ obtain ⟨d, pre, hd, cursor, mask, frame, hm, hp⟩ := onePort hl width c hc ne hlen hw h1
+ obtain ⟨out, rest, ho, other, hm', hp'⟩ :=
+ ih (dir+1) d hd (by rw [cursor, hdir])
+ (by rw [frame, hend] <;> simp [Preserved, add_assoc, add_comm (1:Word w)])
+ (by rw [frame, ha]; simp [Preserved])
+ (by rw [frame, hlen]; simp [Preserved]) (by omega)
+ (by rw [frame, h1]; simp [Preserved])
+ refine ⟨out, ?_, ?_, fun a h ↦ (other a h).trans (frame a h), hm'.trans hm, hp'.trans hp⟩
+ · convert pre.append rest using 1
+ rw [← List.replicate_add]
+ congr 1
+ rw [Nat.mul_succ]
+ omega
+ · rw [ho]
+ simp [mask, hm, hdir, ha, Agrees, Fin.forall_fin_succ, add_assoc, add_comm (1 : Word w),
+ and_assoc]
+
+end PairSimulation.MapPortScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapPost.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapPost.lean
new file mode 100644
index 0000000000..13db53ab19
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapPost.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.PairSimulationMapInline
+
+/-!
+# Private memory after an inlined motif map call
+
+Lowering the public constants changes the register allocation and instruction count.
+The host uses the source call's private memory, so its output satisfies the same
+canonical update of the directory, selector, label and histogram cells.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifDemandPadding
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord InlinePublic
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k t w P R : ℕ}
+
+namespace MapConstants
+
+variable (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : MapCallTable.Layout B (demandGrid B hp I.demand) I.party r k)
+ (ord : (parameterData B).Entry → Fin t)
+
+/-- Installing the cast of the fixed natural constant bank preserves the
+canonical private-memory update of the full descriptor-driven map. -/
+theorem source_run_post (hw : widthThreshold B ≤ w) :
+ let loc := L.corePC L.locations
+ let A := L.core.program loc
+ let M := source (w := w) L ord
+ let demand := MotifEntry.demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ MotifEntry.inputBits) I.supplyBits
+ ∀ (X : MapEntry.Program.Workspace A I.demand I.payload demand supply t w)
+ (c : Config w (Nat.card L.Address) r), c.pc = M.entry →
+ MapCallSetup.Input L.core L.args loc X L.ptr c →
+ (∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ A.RunsPost M c X.hist (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand))
+ (MapCallSetup.Outside L.core loc X)
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord))
+ (MapCallSetup.Success L.core loc X (selectorWord B (fits_of_threshold B hw).2.2.2)
+ ord c.privateMem) := by
+ obtain ⟨fb, fd, fs, hs⟩ := fits_of_threshold B hw
+ have run := MapCallTable.Layout.run_entryInput_post hp I L fb (fd _) fs (selectorWord B hs) ord
+ rw [installed_eq_cast L.core ord fb (fd _) fs hs] at run
+ exact run
+
+end MapConstants
+
+namespace MapInline
+
+open MapConstants
+
+variable (L : MapCallTable.Layout B z j r k) (ord : (parameterData B).Entry → Fin t)
+ (V : Placement (capacity L.template (rawBank L.core ord)) (Nat.card L.Address) r P R)
+ (M : Machine w P R 11)
+
+/-- The call returns its exit, histogram, preserved caller state and private-memory
+postcondition on a single host instruction path. -/
+def RunsPost (h : Config w P R) (hist cap : ℕ) (save : BurstRAM.Word w → Prop)
+ (result : Option (List (Fin t))) (post : PrivateScratch.Memory w → Prop) : Prop :=
+ ∃ n out, n ≤ factor L ord * cap ∧ Prefix M h (List.replicate n .tick) out ∧
+ out.persistent = h.persistent ∧ (∀ i, V.privateReg i → out.reg i = h.reg i) ∧
+ (∀ a, save a → out.privateMem a = h.privateMem a) ∧
+ Outcome hist (V.entry (callProgram L).bad) (V.entry (callProgram L).done) h out result ∧
+ post out.privateMem
+
+/-- An individual source prefix of length `n` has exactly `factor L ord * n` host ticks.
+Its private postcondition holds on the same host state as its register and histogram effects. -/
+theorem lift_path_post (linked : Linked L ord V M) (h : Config w P R)
+ (pc : h.pc = V.entry L.template.entry)
+ {hist n : ℕ} {result : Option (List (Fin t))} {save : BurstRAM.Word w → Prop}
+ {post : PrivateScratch.Memory w → Prop} {last : Config w (Nat.card L.Address) r}
+ (pre : Prefix (source (w := w) L ord) (restrict V L.template.entry h)
+ (List.replicate n .tick) last)
+ (persistent : last.persistent = h.persistent)
+ (saved : ∀ a, save a → last.privateMem a = h.privateMem a)
+ (effect : (callProgram L).Effect (restrict V L.template.entry h) last hist result)
+ (ok : post last.privateMem) :
+ ∃ out, Prefix M h (List.replicate (factor L ord * n) .tick) out ∧
+ out.persistent = h.persistent ∧ (∀ i, V.privateReg i → out.reg i = h.reg i) ∧
+ (∀ a, save a → out.privateMem a = h.privateMem a) ∧
+ Outcome hist (V.entry (callProgram L).bad) (V.entry (callProgram L).done) h out result ∧
+ post out.privateMem := by
+ obtain ⟨out, pref, rel⟩ := ticks_lower L.template (rawBank L.core ord) V M
+ (operand_le L.template (rawBank L.core ord)) linked pre (restrict_related V _ h pc)
+ refine ⟨out, pref, rel.1.persistent.trans persistent, rel.1.frame,
+ fun a ha ↦ (congrFun rel.1.privateMem a).trans (saved a ha), ?_, rel.1.privateMem ▸ ok⟩
+ cases result with
+ | none | some _ =>
+ refine ⟨rel.2.trans (congrArg V.entry effect.1), fun i ↦ ?_⟩
+ rw [rel.1.privateMem]
+ exact effect.2 i
+
+/-- Lower the complete source call, retaining its postcondition and multiplying its
+instruction bound by the fixed block length. -/
+theorem lift_run_post (linked : Linked L ord V M) (h : Config w P R)
+ (pc : h.pc = V.entry L.template.entry) {hist cap : ℕ} {result : Option (List (Fin t))}
+ {save : BurstRAM.Word w → Prop} {post : PrivateScratch.Memory w → Prop}
+ (path : (callProgram L).RunsPost (source (w := w) L ord) (restrict V L.template.entry h)
+ hist cap save result post) : RunsPost L ord V M h hist cap save result post := by
+ obtain ⟨n, last, bound, pre, per, frame, effect, ok⟩ := path.path
+ obtain ⟨out, facts⟩ := lift_path_post L ord V M linked h pc pre per frame effect ok
+ exact ⟨factor L ord * n, out, Nat.mul_le_mul_left _ bound, facts⟩
+
+/-- Run the inlined map from the caller's resident descriptor. The canonical memory
+update uses the same initial host memory and the same exit as the histogram result. -/
+theorem run_entryInput_post (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : MapCallTable.Layout B (demandGrid B hp I.demand) I.party r k)
+ (V : Placement (capacity L.template (rawBank L.core ord)) (Nat.card L.Address) r P R)
+ (M : Machine w P R 11) (linked : Linked L ord V M) (hw : widthThreshold B ≤ w) :
+ let loc := L.corePC L.locations
+ let demand := MotifEntry.demandBits src dst I.party I.demandBits
+ let supply := mapHalf G (fun _ ↦ MotifEntry.inputBits) I.supplyBits
+ ∀ (X : MapEntry.Program.Workspace (callProgram L) I.demand I.payload demand supply t w)
+ (h : Config w P R), h.pc = V.entry L.template.entry →
+ MapCallSetup.Input L.core L.args loc X L.ptr (restrict V L.template.entry h) →
+ (∀ (l : Fin t) (i : MapDirectoryInit.Row L.core),
+ ((X.hist + l.val : ℕ) : BurstRAM.Word w) ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ RunsPost L ord V M h X.hist (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand))
+ (MapCallSetup.Outside L.core loc X)
+ ((runEntry B hp I.demand I.payload I.party demand supply).1.map (List.map ord))
+ (MapCallSetup.Success L.core loc X (selectorWord B (fits_of_threshold B hw).2.2.2)
+ ord h.privateMem) := by
+ intro loc demand supply X h pc input apart
+ exact lift_run_post L ord V M linked h pc (source_run_post hp I L ord hw X _ rfl input apart)
+
+end MapInline
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapResidentAgreement.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapResidentAgreement.lean
new file mode 100644
index 0000000000..aef9a23bdb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapResidentAgreement.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.PairSimulationMapPortScan
+import OAI.Computability.VPVNP.PairSimulationMapPortAgreement
+import OAI.Computability.VPVNP.PairSimulationMapTagBits
+
+/-!
+# Agreement of all selector tags on the resident incident fields
+
+The scan's directory contains one selector-start pointer per source and
+target incidence of the party. Each pointer skips that port's own payload.
+All comparisons read the single original anchor field. The successful exit
+is exactly the agreement condition of the grouped motif entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapResidentAgreement
+
+open MotifSelector MotifEntry MapPortAgreement PrimedInputRAM
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {J E : Type*} {u b w : ℕ} {G : Supply J E} {v : E → ℕ} {party : J}
+
+/-- The underlying supply edge of either port. -/
+def edge : Port G party → E
+ | .inl e => e.val
+ | .inr e => e.val
+
+/-- The original bit field at one port, including its own payload. -/
+def field (x : Half G (fun e => Fin (v e + u * b) → Bool) party) :
+ (t : Port G party) → Fin (v (edge t) + u * b) → Bool
+ | .inl e => x.1 e.val e.property
+ | .inr e => x.2 e.val e.property
+
+variable [DecidableEq J]
+
+/-- The incidence selected by the motif interpreter for its reference field.
+If the anchor is a self-loop the source incidence supplies the reference. -/
+def anchorPort (G : Supply J E) (party : J) : Port G party :=
+ if h : party = G.src (G.anchor party) then .inl ⟨G.anchor party,h⟩
+ else .inr ⟨G.anchor party, ((G.anchor_incident party).resolve_left fun he ↦ h he.symm).symm⟩
+
+omit [DecidableEq J] in
+theorem read_port (x : Half G (fun e => Fin (v e + u * b) → Bool) party) (t : Port G party) :
+ portTag (mapHalf G (fun _ ↦ readTag) x) t = readTag (field x t) := by
+ cases t <;> rfl
+
+theorem read_anchor (x : Half G (fun e => Fin (v e + u * b) → Bool) party) :
+ anchor G party (mapHalf G (fun _ ↦ readTag) x) = readTag (field x (anchorPort G party)) := by
+ unfold anchor anchorPort
+ split
+ · rename_i h
+ rw [dite_eq_left h]
+ rfl
+ · rename_i h
+ rw [dite_eq_right h]
+ rfl
+
+/-- The first selector cell is located immediately after the port's payload. -/
+def selectorStart (v : E → ℕ) (base : Port G party → BurstRAM.Word w) (t : Port G party) :
+ BurstRAM.Word w := base t + (v (edge t) : BurstRAM.Word w)
+
+variable [Fintype E]
+
+/-- The input fields and pointer table needed by the native checker. Bits
+on two halves of a self-loop can differ and all the fields may be malformed. -/
+structure Resident (order : Fin (Fintype.card E) ≃ E)
+ (x : Half G (fun e => Fin (v e + u * b) → Bool) party) (base : Port G party → BurstRAM.Word w)
+ (mem : BurstRAM.Word w → BurstRAM.Word w) (dir : BurstRAM.Word w) : Prop where
+ pointers : ∀ i : Fin (ports G party order).length,
+ mem (dir + (i.val : BurstRAM.Word w)) = selectorStart v base ((ports G party order).get i)
+ cells : ∀ t : Port G party, ∀ i : Fin (v (edge t) + u * b),
+ mem (base t + (i.val : BurstRAM.Word w)) = encodeBit w (field x t i)
+
+/-- The pointer-based word predicate, directly on the original resident
+bits, is equivalent to the agreement test on the decoded selectors. -/
+theorem agrees_iff (order : Fin (Fintype.card E) ≃ E)
+ (x : Half G (fun e => Fin (v e + u * b) → Bool) party) (base : Port G party → BurstRAM.Word w)
+ (mem : BurstRAM.Word w → BurstRAM.Word w) (dir : BurstRAM.Word w)
+ (hres : Resident order x base mem dir) (hlen : u * b < 2 ^ w) :
+ MapPortScan.Agrees mem dir (selectorStart v base (anchorPort G party))
+ (ports G party order).length (u * b) ↔
+ consistent G party (mapHalf G (fun _ ↦ readTag) x) := by
+ let t₀ := anchorPort G party
+ have cell (t : Port G party) (i : Fin (u * b)) :
+ mem (selectorStart v base t + (i.val : BurstRAM.Word w)) =
+ encodeBit w (field x t (Fin.natAdd (v (edge t)) i)) := by
+ simpa [selectorStart, add_assoc] using hres.cells t (Fin.natAdd (v (edge t)) i)
+ have hh (t : Port G party) : (∀ j : Fin (u * b),
+ mem (selectorStart v base t + (j.val : BurstRAM.Word w)) =
+ mem (selectorStart v base t₀ + (j.val : BurstRAM.Word w))) ↔
+ ∀ i : Fin u, readTag (field x t) i = readTag (field x t₀) i := by
+ rw [MapConsistency.readTag_eq_iff_suffix]
+ simp_rw [cell]
+ constructor
+ · intro h i
+ have hw : 0 < w := by
+ by_contra! hz
+ have hwz := Nat.eq_zero_of_le_zero hz
+ have hn : u * b < 1 := by simpa only [hwz, pow_zero] using hlen
+ have hi := i.isLt
+ omega
+ apply Bool.eq_iff_iff.mpr
+ rw [← encodeBit_eq_one hw, ← encodeBit_eq_one hw, h i]
+ · exact fun h i ↦ congrArg _ (h i)
+ rw [consistent_iff_ports]
+ simp_rw [read_port, read_anchor]
+ constructor
+ · intro h t
+ obtain ⟨i, he⟩ := List.mem_iff_get.mp (mem_ports G party order t)
+ apply (hh t).mp
+ simpa only [hres.pointers i, he, t₀] using h i
+ · intro h i
+ simpa only [hres.pointers i, t₀] using (hh ((ports G party order).get i)).mpr (h _)
+
+/-- The machine reads each port's pointer, scans its raw bits, and sends
+every inconsistent input to the rejecting continuation. -/
+theorem native {p r k : ℕ} {M : Machine w p r k} {pc inner : Fin 7 → Fin p}
+ {reg : Fin 11 ↪ Fin r} {yes no : Fin p} (hl : MapPortScan.Linked M pc inner reg yes no)
+ (order : Fin (Fintype.card E) ≃ E) (x : Half G (fun e => Fin (v e + u * b) → Bool) party)
+ (base : Port G party → BurstRAM.Word w) (dir : BurstRAM.Word w) (c : Config w p r)
+ (hc : c.pc = pc 0) (hdir : c.reg (reg 7) = dir)
+ (hend : c.reg (reg 8) = dir + ((ports G party order).length : BurstRAM.Word w))
+ (ha : c.reg (reg 9) = selectorStart v base (anchorPort G party))
+ (hw : c.reg (reg 10) = ((u * b : ℕ) : BurstRAM.Word w))
+ (h1 : c.reg (reg 3) = 1) (hzero : c.reg (reg 4) = 0)
+ (hres : Resident order x base c.privateMem dir)
+ (hn : (ports G party order).length < 2 ^ w) (hlen : u * b < 2 ^ w) :
+ ∃ out, Prefix M c (List.replicate ((7*(u * b)+6)*(ports G party order).length+3) .tick) out ∧
+ out.pc = (if consistent G party (mapHalf G (fun _ ↦ readTag) x) then yes else no) ∧
+ (∀ a, MapPortScan.Preserved reg a → out.reg a = c.reg a) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ obtain ⟨out, pre, ho, frame, hm, hp⟩ :=
+ MapPortScan.run hl _ _ dir _ c hc hdir hend ha hw hn hlen h1
+ refine ⟨out, pre, ?_, frame, hm, hp⟩
+ simpa only [hzero, true_and, agrees_iff order x base _ dir hres hlen] using ho
+
+end PairSimulation.MapResidentAgreement
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapResidentInputs.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapResidentInputs.lean
new file mode 100644
index 0000000000..7501ec302f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapResidentInputs.lean
@@ -0,0 +1,346 @@
+import OAI.Computability.VPVNP.PairNodeChildLoop
+
+/-!
+# Reading the map list and term pointers of a shrinking site
+
+Four consecutive level words give the map-count head, dense-ID table head,
+term head, and term stride. Every packed site's count is its row capacity
+(6dQ), so the count already read supplies the row stride. The next
+fragment splits one ID into its motif and party and reads the first word
+of the motif's term record, the demand-grid ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapResidentInputs
+
+open BurstRAM PrivateRAM NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.read ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r k : ℕ}
+
+/-- Registers zero and one hold the old level header and packed site ordinal.
+Registers two and three receive the half-open map-ID range, and four and
+five the term-table base and stride. Registers eight to ten are scratch. -/
+def headerCode (pc : Fin 16 → Fin p) (reg : Fin 11 ↪ Fin r) (done : Fin p) :
+ Fin 16 → Instr w p r k :=
+ ![.constant (reg 9) 17 (pc 1), .binary .add (reg 9) (reg 9) (reg 9) (pc 2),
+ .binary .add (reg 9) (reg 0) (reg 9) (pc 3),
+ .readExternal (reg 2) (reg 9) (pc 4), .binary .add (reg 2) (reg 2) (reg 1) (pc 5),
+ .readExternal (reg 3) (reg 2) (pc 6), .constant (reg 10) 1 (pc 7),
+ .binary .add (reg 9) (reg 9) (reg 10) (pc 8), .readExternal (reg 2) (reg 9) (pc 9),
+ .binary .mul (reg 8) (reg 1) (reg 3) (pc 10), .binary .add (reg 2) (reg 2) (reg 8) (pc 11),
+ .binary .add (reg 3) (reg 2) (reg 3) (pc 12), .binary .add (reg 9) (reg 9) (reg 10) (pc 13),
+ .readExternal (reg 4) (reg 9) (pc 14), .binary .add (reg 9) (reg 9) (reg 10) (pc 15),
+ .readExternal (reg 5) (reg 9) done]
+
+theorem resize_headerCode (pc : Fin 16 → Fin p) (reg : Fin 11 ↪ Fin r) (done : Fin p) (i : Fin 16) :
+ (headerCode (w := 5) (k := k) pc reg done i).resize w = headerCode pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- The header scan is linked to the first map-list guard. -/
+def HeaderLinked (M : Machine w p r k) (pc : Fin 16 → Fin p) (reg : Fin 11 ↪ Fin r)
+ (done : Fin p) : Prop := ∀ i, M.code (pc i) = headerCode pc reg done i
+
+/-- The count word at this packed site. -/
+def count (m : Memory w) (level site : Word w) : Word w := m (m (level + 34).val + site).val
+
+/-- First cell of this site's packed map-ID row. -/
+def rowStart (m : Memory w) (level site : Word w) : Word w :=
+ m (level + 35).val + site * count m level site
+
+private def fetch (m : Memory w) (addr : Word w) := Event.read addr (m addr.val)
+
+/-- The header trace includes the indirect count read and the four pointer
+or stride words. All reads come from the supplied external memory. -/
+def headerEvents (m : Memory w) (level site : Word w) : List (Event w) :=
+ [.tick, .tick, .tick, fetch m (level+34), .tick, fetch m (m (level+34).val + site),
+ .tick, .tick, fetch m (level+35), .tick, .tick, .tick, .tick, fetch m (level+36),
+ .tick, fetch m (level+37)]
+
+theorem headerCost (m : Memory w) (level site : Word w) :
+ (headerEvents m level site).length = 16 ∧ countProbes (headerEvents m level site) = 5 ∧
+ choiceBits (headerEvents m level site) = [] := ⟨rfl,rfl,rfl⟩
+
+/-- The entry scan preserves all registers outside its seven destinations. -/
+def HeaderFrame (reg : Fin 11 ↪ Fin r) (j : Fin r) : Prop :=
+ j ≠ reg 2 ∧ j ≠ reg 3 ∧ j ≠ reg 4 ∧ j ≠ reg 5 ∧ j ≠ reg 8 ∧ j ≠ reg 9 ∧ j ≠ reg 10
+
+/-- Cursor bounds and term lookup data actually read for the enclosing loop. -/
+structure HeaderResult (reg : Fin 11 ↪ Fin r) (done : Fin p) (m : Memory w) (c d : Config w p r) :
+ Prop where
+ pc : d.pc = done
+ cursor : d.reg (reg 2) = rowStart m (c.reg (reg 0)) (c.reg (reg 1))
+ stop : d.reg (reg 3) = rowStart m (c.reg (reg 0)) (c.reg (reg 1)) +
+ count m (c.reg (reg 0)) (c.reg (reg 1))
+ term : d.reg (reg 4) = m (c.reg (reg 0) + 36).val
+ stride : d.reg (reg 5) = m (c.reg (reg 0) + 37).val
+ one : d.reg (reg 10) = 1
+ frame : ∀ a, HeaderFrame reg a → d.reg a = c.reg a
+ memory : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+variable {M : Machine w p r k} {reg : Fin 11 ↪ Fin r} {done : Fin p}
+
+private theorem headerStep {pc : Fin 16 → Fin p} (hl : HeaderLinked M pc reg done) (i : Fin 16)
+ {c : Config w p r} (h : c.pc = pc i) :
+ M.program.step c = (headerCode pc reg done i).run M.publicData c := by
+ simp [Machine.program, h, hl i]
+
+private theorem next_word (x : Word w) (n : ℕ) :
+ x + (n : Word w) + 1 = x + ((n + 1 : ℕ) : Word w) := by simp [add_assoc]
+
+/-- The header fragment has fixed instruction and probe counts on all
+external words, including an empty row. -/
+theorem header_native {pc : Fin 16 → Fin p} (hl : HeaderLinked M pc reg done)
+ (m : Memory w) (c : Config w p r) (hc : c.pc = pc 0) :
+ ∃ d, Prefix M m c d [] (headerEvents m (c.reg (reg 0)) (c.reg (reg 1))) ∧
+ HeaderResult reg done m c d := by
+ have path := ReadPrefix.tick (headerStep hl 0 hc)
+ (ReadPrefix.tick (headerStep hl 1 rfl)
+ (ReadPrefix.tick (headerStep hl 2 rfl)
+ (ReadPrefix.read (m := m) _ (headerStep hl 3 rfl)
+ (ReadPrefix.tick (headerStep hl 4 rfl)
+ (ReadPrefix.read _ (headerStep hl 5 rfl)
+ (ReadPrefix.tick (headerStep hl 6 rfl)
+ (ReadPrefix.tick (headerStep hl 7 rfl)
+ (ReadPrefix.read _ (headerStep hl 8 rfl)
+ (ReadPrefix.tick (headerStep hl 9 rfl)
+ (ReadPrefix.tick (headerStep hl 10 rfl)
+ (ReadPrefix.tick (headerStep hl 11 rfl)
+ (ReadPrefix.tick (headerStep hl 12 rfl)
+ (ReadPrefix.read _ (headerStep hl 13 rfl)
+ (ReadPrefix.tick (headerStep hl 14 rfl)
+ (ReadPrefix.read _ (headerStep hl 15 rfl) (ReadPrefix.nil _))))))))))))))))
+ let last {d : Config w p r} {es : List (Event w)} (_ : ReadPrefix M m c es d) := d
+ have h17 : (17 : Word w) + 17 = 34 := (Nat.cast_add (R := Word w) 17 17).symm
+ have h34 : c.reg (reg 0) + 34 + 1 = c.reg (reg 0) + 35 := next_word _ 34
+ have h35 : c.reg (reg 0) + 35 + 1 = c.reg (reg 0) + 36 := next_word _ 35
+ have h36 : c.reg (reg 0) + 36 + 1 = c.reg (reg 0) + 37 := next_word _ 36
+ refine ⟨last path, ?_, rfl, ?_, ?_, ?_, ?_, ?_, ?_, rfl, rfl⟩
+ · intro fuel tail
+ simpa (config := {decide := true}) only [headerEvents, fetch, last, Config.put,
+ Function.update_apply, reg.injective.eq_iff, ↓reduceIte, BinaryOp.eval, h17, h34, h35, h36,
+ List.nil_append] using ReadPrefix.execute path fuel tail
+ all_goals try
+ solve | simp (config := {decide := true}) [rowStart, count, last, Config.put,
+ reg.injective.eq_iff, BinaryOp.eval, *]
+ rintro a ⟨h₂,h₃,h₄,h₅,h₈,h₉,h₁₀⟩
+ simp [last, Config.put, Function.update_of_ne, h₂,h₃,h₄,h₅,h₈,h₉,h₁₀]
+
+/-- Fetch the current map ID, divide it by six to obtain motif and party,
+and read the first word of that motif's selected term. The row cursor
+is advanced by the enclosing loop. -/
+def itemCode (pc : Fin 7 → Fin p) (reg : Fin 11 ↪ Fin r) (done : Fin p) :
+ Fin 7 → Instr w p r k :=
+ ![.readExternal (reg 6) (reg 2) (pc 1), .constant (reg 9) 6 (pc 2),
+ .binary .mod (reg 7) (reg 6) (reg 9) (pc 3),
+ .binary .div (reg 6) (reg 6) (reg 9) (pc 4),
+ .binary .mul (reg 8) (reg 6) (reg 5) (pc 5),
+ .binary .add (reg 8) (reg 4) (reg 8) (pc 6), .readExternal (reg 9) (reg 8) done]
+
+theorem resize_itemCode (pc : Fin 7 → Fin p) (reg : Fin 11 ↪ Fin r) (done : Fin p) (i : Fin 7) :
+ (itemCode (w := 3) (k := k) pc reg done i).resize w = itemCode pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- The item reader returns directly to the native motif/party dispatch. -/
+def ItemLinked (M : Machine w p r k) (pc : Fin 7 → Fin p) (reg : Fin 11 ↪ Fin r)
+ (done : Fin p) : Prop := ∀ i, M.code (pc i) = itemCode pc reg done i
+
+/-- The address calculated by the native division, multiply and add. -/
+def termAddr (m : Memory w) (cursor term stride : Word w) : Word w :=
+ term + BinaryOp.div.eval (m cursor.val) 6 * stride
+
+/-- The item probe sequence is independent of the entered control table. -/
+def itemEvents (m : Memory w) (cursor term stride : Word w) : List (Event w) :=
+ [fetch m cursor, .tick, .tick, .tick, .tick, .tick, fetch m (termAddr m cursor term stride)]
+
+theorem itemCost (m : Memory w) (cursor term stride : Word w) :
+ (itemEvents m cursor term stride).length = 7 ∧
+ countProbes (itemEvents m cursor term stride) = 2 ∧
+ choiceBits (itemEvents m cursor term stride) = [] :=
+ ⟨rfl,rfl,rfl⟩
+
+/-- Outputs for one map, including the term-row base needed by the field reader. -/
+structure ItemResult (reg : Fin 11 ↪ Fin r) (done : Fin p) (m : Memory w) (c d : Config w p r) :
+ Prop where
+ pc : d.pc = done
+ motif : d.reg (reg 6) = BinaryOp.div.eval (m (c.reg (reg 2)).val) 6
+ party : d.reg (reg 7) = BinaryOp.mod.eval (m (c.reg (reg 2)).val) 6
+ term : d.reg (reg 8) = termAddr m (c.reg (reg 2)) (c.reg (reg 4)) (c.reg (reg 5))
+ grid : d.reg (reg 9) = m (termAddr m (c.reg (reg 2)) (c.reg (reg 4)) (c.reg (reg 5))).val
+ frame : ∀ a, (∀ i : Fin 11, 6 ≤ i.val → i.val ≤ 9 → a ≠ reg i) → d.reg a = c.reg a
+ memory : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+private theorem itemStep {pc : Fin 7 → Fin p} (hl : ItemLinked M pc reg done) (i : Fin 7)
+ {c : Config w p r} (h : c.pc = pc i) :
+ M.program.step c = (itemCode pc reg done i).run M.publicData c := by
+ simp [Machine.program, h, hl i]
+
+/-- Both item probes and the complete continuation state on arbitrary memory. -/
+theorem item_native {pc : Fin 7 → Fin p} (hl : ItemLinked M pc reg done)
+ (m : Memory w) (c : Config w p r) (hc : c.pc = pc 0) :
+ ∃ d, Prefix M m c d [] (itemEvents m (c.reg (reg 2)) (c.reg (reg 4)) (c.reg (reg 5))) ∧
+ ItemResult reg done m c d := by
+ have path := ReadPrefix.read (m := m) _ (itemStep hl 0 hc)
+ (ReadPrefix.tick (itemStep hl 1 rfl) (ReadPrefix.tick (itemStep hl 2 rfl)
+ (ReadPrefix.tick (itemStep hl 3 rfl) (ReadPrefix.tick (itemStep hl 4 rfl)
+ (ReadPrefix.tick (itemStep hl 5 rfl)
+ (ReadPrefix.read _ (itemStep hl 6 rfl) (ReadPrefix.nil _)))))))
+ let last {d : Config w p r} {es : List (Event w)} (_ : ReadPrefix M m c es d) := d
+ refine ⟨last path, ?_, rfl, ?_, ?_, ?_, ?_, ?_, rfl, rfl⟩
+ · intro fuel tail
+ simpa (config := {decide := true}) [itemEvents, fetch, last, termAddr, Config.put,
+ reg.injective.eq_iff, BinaryOp.eval] using ReadPrefix.execute path fuel tail
+ all_goals try
+ solve | simp (config := {decide := true}) [last, termAddr, Config.put, reg.injective.eq_iff,
+ BinaryOp.eval]
+ intro a h
+ simp [last, Config.put, Function.update_of_ne (h 6 (by decide) (by decide)),
+ Function.update_of_ne (h 7 (by decide) (by decide)),
+ Function.update_of_ne (h 8 (by decide) (by decide)),
+ Function.update_of_ne (h 9 (by decide) (by decide))]
+
+/-- The four published level fields in ordinary external-memory coordinates. -/
+structure Published (m : Memory w) (level counts ids term : Word w) (stride : ℕ) : Prop where
+ countsAt : m (level.val + 34) = counts
+ idsAt : m (level.val + 35) = ids
+ termAt : m (level.val + 36) = term
+ strideAt : m (level.val + 37) = (stride : Word w)
+
+private theorem val_add_nat (x : Word w) (n : ℕ) (fit : x.val + n < 2 ^ w) :
+ (x + (n : Word w)).val = x.val + n := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : n < 2 ^ w), Nat.mod_eq_of_lt fit]
+
+private theorem word_val (x : Word w) : (x.val : Word w) = x := Fin.ext (Nat.mod_eq_of_lt x.isLt)
+
+/-- The term publisher and the later data-head publisher retain the two
+previously written map heads. The data-head publisher also retains both
+words written by the term publisher. -/
+theorem Published.of_head_frames {before terms last : Memory w} {level counts ids term : Word w}
+ {stride : ℕ} (countWord : before (level.val + 34) = counts)
+ (rowWord : before (level.val + 35) = ids)
+ (termWord : terms (level.val + 36) = term)
+ (strideWord : terms (level.val + 37) = (stride : Word w))
+ (termFrame : ∀ x < level.val + 36, terms x = before x)
+ (dataFrame : ∀ x < level.val + 40, last x = terms x) :
+ Published last level counts ids term stride :=
+ ⟨(dataFrame _ (by omega)).trans ((termFrame _ (by omega)).trans countWord),
+ (dataFrame _ (by omega)).trans ((termFrame _ (by omega)).trans rowWord),
+ (dataFrame _ (by omega)).trans termWord, (dataFrame _ (by omega)).trans strideWord⟩
+
+/-- Later updates elsewhere in memory preserve the directory descriptor. -/
+theorem Published.retain {m last : Memory w} {level counts ids term : Word w} {stride : ℕ}
+ (pub : Published m level counts ids term stride)
+ (keep : ∀ n, 34 ≤ n → n ≤ 37 → last (level.val + n) = m (level.val + n)) :
+ Published last level counts ids term stride :=
+ ⟨(keep 34 (by decide) (by decide)).trans pub.countsAt,
+ (keep 35 (by decide) (by decide)).trans pub.idsAt,
+ (keep 36 (by decide) (by decide)).trans pub.termAt,
+ (keep 37 (by decide) (by decide)).trans pub.strideAt⟩
+
+/-- Readback at a fitted header and count cell. Row cursor arithmetic is
+word arithmetic, so the exclusive row end may coincide with the modulus. -/
+theorem HeaderResult.readback {reg : Fin 11 ↪ Fin r} {done : Fin p}
+ {m : Memory w} {c d : Config w p r} (h : HeaderResult reg done m c d)
+ (counts ids term : Word w) (stride n : ℕ)
+ (pub : Published m (c.reg (reg 0)) counts ids term stride)
+ (headerFit : (c.reg (reg 0)).val + 37 < 2 ^ w)
+ (countFit : counts.val + (c.reg (reg 1)).val < 2 ^ w)
+ (value : (m (counts.val + (c.reg (reg 1)).val)).val = n) :
+ let start := ids.val + (c.reg (reg 1)).val * n
+ d.reg (reg 2) = (start : Word w) ∧ d.reg (reg 3) = ((start+n : ℕ) : Word w) ∧
+ d.reg (reg 4) = term ∧ d.reg (reg 5) = (stride : Word w) := by
+ let level := c.reg (reg 0)
+ let site := c.reg (reg 1)
+ have addr (i : ℕ) (hi : i ≤ 37) : (level + (i : Word w)).val = level.val + i :=
+ val_add_nat level i (by change level.val + 37 < 2 ^ w at headerFit; omega)
+ have countAddr : (counts + site).val = counts.val + site.val := by
+ simpa only [word_val] using val_add_nat counts site.val countFit
+ have hc : count m level site = (n : Word w) := by
+ unfold count
+ have h34 : (level + 34).val = level.val + 34 := addr 34 (by decide)
+ rw [h34, pub.countsAt, countAddr, ← value, word_val]
+ have row : rowStart m level site = ((ids.val + site.val*n : ℕ) : Word w) := by
+ unfold rowStart
+ have h35 : (level + 35).val = level.val + 35 := addr 35 (by decide)
+ rw [h35, pub.idsAt, hc]
+ simp only [Nat.cast_add, Nat.cast_mul, word_val]
+ refine ⟨h.cursor.trans row, h.stop.trans ?_, h.term.trans ?_, h.stride.trans ?_⟩
+ · change rowStart m level site + count m level site = _
+ rw [row, hc]
+ exact (Nat.cast_add ..).symm
+ · exact (congrArg m (addr 36 (by decide))).trans pub.termAt
+ · exact (congrArg m (addr 37 (by decide))).trans pub.strideAt
+
+/-- On a genuine resident occurrence, native division and remainder recover
+the motif ordinal and the six-valued party without truncation. The grid word
+is read at the ordinary, fitted address in the selected term table. -/
+theorem ItemResult.readback {reg : Fin 11 ↪ Fin r} {done : Fin p}
+ {m : Memory w} {c d : Config w p r} (h : ItemResult reg done m c d)
+ (ordinal : ℕ) (party : Fin 6) (base stride : ℕ) (h6 : 6 < 2 ^ w)
+ (idAt : (m (c.reg (reg 2)).val).val = ordinal * 6 + party.val)
+ (hbase : c.reg (reg 4) = (base : Word w)) (hstride : c.reg (reg 5) = (stride : Word w))
+ (room : base + ordinal * stride < 2 ^ w) :
+ (d.reg (reg 6)).val = ordinal ∧ (d.reg (reg 7)).val = party.val ∧
+ (d.reg (reg 8)).val = base + ordinal * stride ∧
+ d.reg (reg 9) = m (base + ordinal * stride) := by
+ let id := m (c.reg (reg 2)).val
+ have div : (BinaryOp.div.eval id 6).val = ordinal := by
+ change id.val / (6 : Word w).val % (2 ^ w) = ordinal
+ rw [show (6 : Word w).val = 6 from Nat.mod_eq_of_lt h6,
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt id.isLt)]
+ change id.val = ordinal*6 + party.val at idAt
+ rw [idAt]
+ have := party.isLt
+ omega
+ have modEq : (BinaryOp.mod.eval id 6).val = party.val := by
+ change id.val % (6 : Word w).val % (2 ^ w) = party.val
+ rw [show (6 : Word w).val = 6 from Nat.mod_eq_of_lt h6,
+ Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt id.isLt)]
+ change id.val = ordinal*6 + party.val at idAt
+ rw [idAt]
+ have := party.isLt
+ omega
+ have hdiv : BinaryOp.div.eval id 6 = (ordinal : Word w) := by rw [← div, word_val]
+ have ht : (termAddr m (c.reg (reg 2)) (c.reg (reg 4)) (c.reg (reg 5))).val =
+ base + ordinal * stride := by
+ change (c.reg (reg 4) + BinaryOp.div.eval id 6 * c.reg (reg 5)).val = _
+ rw [hbase, hstride, hdiv, ← Nat.cast_mul, ← Nat.cast_add]
+ exact Nat.mod_eq_of_lt room
+ exact ⟨(congrArg Fin.val h.motif).trans div, (congrArg Fin.val h.party).trans modEq,
+ (congrArg Fin.val h.term).trans ht, h.grid.trans (congrArg m ht)⟩
+
+/-- Fixed slots occupied by both readers in the pair worker. -/
+abbrev Address := Fin 16 ⊕ Fin 7
+
+/-- The readers share the surrounding eleven public words and have no
+private public-parameter bank of their own. Their exits link to the map
+guard and selected map evaluator. -/
+def text (place : Address → Fin p) (reg : Fin 11 ↪ Fin r) (guard dispatch : Fin p) :
+ Address → Instr 5 p r 11
+ | .inl i => headerCode (place ∘ Sum.inl) reg guard i
+ | .inr i => itemCode (place ∘ Sum.inr) reg dispatch i
+
+/-- Placing the fixed instruction slots supplies both native reader links. -/
+theorem linked (M : Machine w p r 11) (place : Address → Fin p) (reg : Fin 11 ↪ Fin r)
+ (guard dispatch : Fin p)
+ (code : ∀ a, M.code (place a) = (text place reg guard dispatch a).resize w) :
+ HeaderLinked M (place ∘ Sum.inl) reg guard ∧ ItemLinked M (place ∘ Sum.inr) reg dispatch := by
+ constructor
+ · intro i
+ exact (code (.inl i)).trans (resize_headerCode ..)
+ · intro i
+ apply (code (.inr i)).trans
+ fin_cases i <;> rfl
+
+end PairSimulation.MapResidentInputs
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapResidentRows.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapResidentRows.lean
new file mode 100644
index 0000000000..6ddd67fc99
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapResidentRows.lean
@@ -0,0 +1,241 @@
+import OAI.Computability.VPVNP.CompressorShrinkResidentLayout
+import OAI.Computability.VPVNP.CompressorShrinkTermSelection
+import OAI.Computability.VPVNP.PairSimulationMapResidentInputs
+
+/-!
+# Reading a shrinking map occurrence and its demand-grid point
+
+The count and ID arrays published in the old level's header at offsets 34
+and 35 are indexed by packed site. Each ID has the dense motif ordinal
+as its quotient by six and the party as its remainder. The quotient indexes
+the term table published at offsets 36 and 37, whose first word selects
+the demand-grid point for that occurrence.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.MapResidentRows
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData CompressorRecords LocalHistory
+open MotifGrid MotifBlocks MotifConversion ShrinkMotif
+open scoped Classical Fin.CommRing
+
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+
+/-- A packed site in the selected shrinking layout. -/
+abbrev Site := (X.Base × BitWord (Shrink.J a)) × BitWord g
+
+/-- The site numeral used by the count and ID arrays. -/
+abbrev siteIndex (site : Site X) := (ShrinkHistoryRows.packedOrder X).entries.symm site
+
+/-- The restriction of dense motif-and-party order to one packed site. -/
+abbrev order (layout : Bool) (site : Site X) :=
+ ShrinkHistoryRows.residents (ShrinkHistoryRows.mapOrder X)
+ (fun e => X.packingData.shrinkPartySite layout e.1 e.2) site
+
+/-- The motif and party of a position in a packed site’s ordered map row. -/
+abbrev entry (layout : Bool) (site : Site X) (r : Fin (order X layout site).length) :=
+ ((order X layout site).entries r).val
+
+/-- The term-table ordinal of a shrinking motif. -/
+abbrev ordinal (m : X.packingData.Motif) := (shrinkMotifOrder X).entries.symm m
+
+/-- The number of map occurrences at each packed site. -/
+abbrev capacity (a : ℕ) := ShrinkResidentLayout.rowCapacity a true
+
+/-- The compressor’s map directory specialized to the selected layout. -/
+abbrev Directory (layout : Bool) (p : Fin 6 → Word w) (mem : Memory w) :=
+ ShrinkHistoryRows.Directory (ShrinkHistoryRows.mapOrder X) (ShrinkHistoryRows.packedOrder X)
+ (fun e => X.packingData.shrinkPartySite layout e.1 e.2) p mem
+
+theorem length_eq (layout : Bool) (site : Site X) : (order X layout site).length = capacity a := by
+ change Fintype.card {e : X.packingData.Motif × Fin 6 //
+ site = X.packingData.shrinkPartySite layout e.1 e.2} = _
+ exact (Fintype.card_congr (Equiv.subtypeEquivRight (fun _ => eq_comm))).trans
+ (ShrinkHistoryRows.map_count X layout site)
+
+variable {layout : Bool} {p : Fin 6 → Word w} {mem : Memory w}
+
+theorem count_read (rows : Directory X layout p mem) (site : Site X) :
+ (mem ((p 3).val + (siteIndex X site).val)).val = capacity a :=
+ (rows.count site).trans (length_eq X layout site)
+
+set_option maxHeartbeats 1200000 in
+/-- A site ordinal indexes the ordered fiber. The word stored there is
+the global motif-and-party ordinal, even if several parties share the site. -/
+theorem id_read (rows : Directory X layout p mem) (rowSize : (p 4).val = capacity a)
+ (fit : (ShrinkHistoryRows.mapOrder X).length ≤ 2^w) (site : Site X)
+ (r : Fin (order X layout site).length) :
+ (mem ((p 5).val + (siteIndex X site).val * capacity a + r.val)).val =
+ (ordinal X (entry X layout site r).1).val * 6 + (entry X layout site r).2.val := by
+ let e := entry X layout site r
+ let i := (ShrinkHistoryRows.mapOrder X).entries.symm e
+ have h := congrArg Fin.val (rows.idAt site r)
+ rw [rowSize] at h
+ exact h.trans ((Nat.mod_eq_of_lt (i.isLt.trans_le fit)).trans
+ (ShrinkResidentLayout.map_id X e.1 e.2))
+
+theorem id_digits (rows : Directory X layout p mem) (rowSize : (p 4).val = capacity a)
+ (fit : (ShrinkHistoryRows.mapOrder X).length ≤ 2^w) (site : Site X)
+ (r : Fin (order X layout site).length) :
+ let id := mem ((p 5).val + (siteIndex X site).val * capacity a + r.val)
+ id.val / 6 = (ordinal X (entry X layout site r).1).val ∧
+ id.val % 6 = (entry X layout site r).2.val := by
+ dsimp only
+ rw [id_read X rows rowSize fit site r]
+ have := (entry X layout site r).2.isLt
+ omega
+
+/-- The physical arena bounds the count address and even the exclusive
+end of the last packed site's map row. -/
+theorem directory_fit (first : ℕ) (site : Site X)
+ (fit : (ShrinkResidentLayout.layout X first).endAddr < 2^w) :
+ let p := (ShrinkResidentLayout.layout X first).params a true w
+ (p 3).val + (siteIndex X site).val < 2^w ∧
+ (p 5).val + (siteIndex X site).val * capacity a + capacity a < 2^w := by
+ let L := ShrinkResidentLayout.layout X first
+ have hi : (siteIndex X site).val < L.sites := (siteIndex X site).isLt
+ have size : L.size true = L.sites * capacity a := ShrinkResidentLayout.size_eq_rows X first true
+ obtain ⟨_,_,_,_,hc,_,hr⟩ := ShrinkResidentLayout.frame X first true fit
+ have cend := (L.ranges true).2.2.1
+ have rend := (L.ranges true).2.2.2
+ have bound := Nat.mul_le_mul_right (capacity a) hi
+ rw [Nat.succ_mul] at bound
+ change L.endAddr < 2^w at fit
+ change (L.params a true w 3).val + (siteIndex X site).val < 2^w ∧
+ (L.params a true w 5).val + (siteIndex X site).val * capacity a + capacity a < 2^w
+ rw [hc, hr]
+ change L.counts true + (siteIndex X site).val < 2^w ∧
+ L.rows true + (siteIndex X site).val * capacity a + capacity a < 2^w
+ rw [size] at rend
+ constructor
+ · exact (Nat.add_lt_add_left hi _).trans_le (cend.le.trans
+ ((Nat.le_add_right ..).trans (rend.trans fit.le)))
+ · rw [Nat.add_assoc]
+ exact (Nat.add_le_add_left bound _).trans_lt (rend.trans_lt fit)
+
+set_option maxHeartbeats 900000 in
+/-- Read the dense ID from the actual allocated map bank. -/
+theorem allocated_id (first : ℕ) (fit : (ShrinkResidentLayout.layout X first).endAddr < 2^w)
+ (rows : Directory X layout ((ShrinkResidentLayout.layout X first).params a true w) mem)
+ (site : Site X) (r : Fin (order X layout site).length) :
+ let p := (ShrinkResidentLayout.layout X first).params a true w
+ (mem ((p 5).val + (siteIndex X site).val * capacity a + r.val)).val =
+ (ordinal X (entry X layout site r).1).val * 6 + (entry X layout site r).2.val := by
+ let L := ShrinkResidentLayout.layout X first
+ let p := L.params a true w
+ obtain ⟨_,ho,_,_,_,hc,_⟩ := ShrinkResidentLayout.frame X first true fit
+ have oldFits : L.size true ≤ 2^w := ho.symm.le.trans (p 0).isLt.le
+ exact id_read X (layout := layout) (p := p) (mem := mem) rows hc oldFits site r
+
+end PairSimulation.MapResidentRows
+
+namespace PairSimulation.MapResidentInputs
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords MapResidentRows
+open MotifGrid MotifBlocks MotifConversion ShrinkMotif
+open scoped Classical Fin.CommRing
+
+variable {a g w : ℕ} (X : State a (packingLaneBits a g))
+variable {layout : Bool} {mem : Memory w} {pcs regs : ℕ} {reg : Fin 11 ↪ Fin regs}
+ {done : Fin pcs} {c d : Config w pcs regs}
+
+/-- The output cursor and stop registers delimit exactly this site's ordered
+map row. Registers four and five recover the term head and ten-word stride. -/
+theorem HeaderResult.directory (h : HeaderResult reg done mem c d)
+ (first : ℕ) (fit : (ShrinkResidentLayout.layout X first).endAddr < 2^w)
+ (rows : Directory X layout ((ShrinkResidentLayout.layout X first).params a true w) mem)
+ (site : Site X) (siteReg : (c.reg (reg 1)).val = (siteIndex X site).val)
+ (term : Word w)
+ (pub : Published mem (c.reg (reg 0)) ((ShrinkResidentLayout.layout X first).params a true w 3)
+ ((ShrinkResidentLayout.layout X first).params a true w 5) term 10)
+ (headerFit : (c.reg (reg 0)).val + 37 < 2^w) :
+ let p := (ShrinkResidentLayout.layout X first).params a true w
+ let start := (p 5).val + (siteIndex X site).val * capacity a
+ d.reg (reg 2) = (start : Word w) ∧ d.reg (reg 3) = ((start+(order X layout site).length : ℕ) : Word w) ∧
+ d.reg (reg 4) = term ∧ d.reg (reg 5) = 10 := by
+ let p := (ShrinkResidentLayout.layout X first).params a true w
+ have cf := (directory_fit X first site fit).1
+ have cnt := count_read X rows site
+ rw [← siteReg] at cf cnt
+ have hr := h.readback (p 3) (p 5) term 10 (capacity a) pub headerFit cf cnt
+ simpa only [siteReg, length_eq, Nat.cast_ofNat] using hr
+
+variable {k : Type*} [_root_.Field k] {factor : ℝ}
+variable (F : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31/16) factor)
+variable {dense term : Word w} {cap : ℕ} {s : X.ShrinkSelection F}
+ {before : Memory w} {rs : List (Report w)}
+
+private theorem grid_at (terms : ShrinkTermSelection.Written F X dense term 10 cap s before rs)
+ (m : X.packingData.Motif) (room : term.val + (ordinal X m).val * 10 < 2^w)
+ (retained : mem (term.val + (ordinal X m).val * 10) =
+ after before (eventLog rs) (term.val + (ordinal X m).val * 10)) :
+ F.grid.demands.toList[(mem (term.val + (ordinal X m).val * 10)).val]? =
+ some (demandGrid F demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m)).val := by
+ have hb : (ShrinkTermSelection.rowBase X term 10 m).val =
+ term.val + (ordinal X m).val * 10 := Nat.mod_eq_of_lt room
+ rw [retained, ← hb]
+ exact (terms.fields m).1
+
+private theorem fits_ten {base i n bound : ℕ} (hi : i < n) (fit : base + n*10 ≤ bound) :
+ 6 < bound ∧ base + i*10 < bound := by omega
+
+private theorem ItemResult.term_selected (h : ItemResult reg done mem c d)
+ (m : X.packingData.Motif) (j : Fin 6)
+ (ident : (mem (c.reg (reg 2)).val).val = (ordinal X m).val * 6 + j.val)
+ (headReg : c.reg (reg 4) = term) (strideReg : c.reg (reg 5) = 10)
+ (terms : ShrinkTermSelection.Written F X dense term 10 cap s before rs)
+ (termFit : term.val + (LocalHistory.shrinkMotifOrder X).length * 10 ≤ 2^w)
+ (retained : mem (term.val + (ordinal X m).val * 10) =
+ after before (eventLog rs) (term.val + (ordinal X m).val * 10)) :
+ (d.reg (reg 6)).val = (ordinal X m).val ∧ (d.reg (reg 7)).val = j.val ∧
+ (d.reg (reg 8)).val = term.val + (ordinal X m).val * 10 ∧
+ F.grid.demands.toList[(d.reg (reg 9)).val]? = some (demandGrid F demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m)).val := by
+ obtain ⟨h6,room⟩ := fits_ten (ordinal X m).isLt termFit
+ have head : c.reg (reg 4) = (term.val : Word w) :=
+ headReg.trans (Fin.ext (Nat.mod_eq_of_lt term.isLt)).symm
+ have strideCast : c.reg (reg 5) = ((10 : ℕ) : Word w) := by simpa only [Nat.cast_ofNat] using strideReg
+ obtain ⟨hm,hj,ha,hz⟩ := h.readback (ordinal X m).val j term.val 10 h6 ident head strideCast room
+ exact ⟨hm,hj,ha,(congrArg (fun z : Word w => F.grid.demands.toList[z.val]?) hz).trans
+ (grid_at X F terms m room retained)⟩
+
+set_option maxHeartbeats 1500000 in
+/-- At a position of this site's ordered map row, the native reader returns
+the dense motif ordinal, its six-valued party, and the demand-grid point
+written by the term worker for this motif. -/
+theorem ItemResult.selected (h : ItemResult reg done mem c d)
+ (first : ℕ) (fit : (ShrinkResidentLayout.layout X first).endAddr < 2^w)
+ (rows : Directory X layout ((ShrinkResidentLayout.layout X first).params a true w) mem)
+ (site : Site X) (r : Fin (order X layout site).length)
+ (cursor : (c.reg (reg 2)).val = ((ShrinkResidentLayout.layout X first).params a true w 5).val +
+ (siteIndex X site).val * capacity a + r.val)
+ (headReg : c.reg (reg 4) = term) (strideReg : c.reg (reg 5) = 10)
+ (terms : ShrinkTermSelection.Written F X dense term 10 cap s before rs)
+ (termFit : term.val + (LocalHistory.shrinkMotifOrder X).length * 10 ≤ 2^w)
+ (retained : ∀ m : X.packingData.Motif, mem (term.val + (ordinal X m).val * 10) =
+ after before (eventLog rs) (term.val + (ordinal X m).val * 10)) :
+ let e := entry X layout site r
+ (d.reg (reg 6)).val = (ordinal X e.1).val ∧ (d.reg (reg 7)).val = e.2.val ∧
+ (d.reg (reg 8)).val = term.val + (ordinal X e.1).val * 10 ∧
+ F.grid.demands.toList[(d.reg (reg 9)).val]? = some (demandGrid F demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth e.1)).val := by
+ intro e
+ refine ItemResult.term_selected X F (dense := dense) (term := term) (cap := cap) (s := s)
+ (before := before) (rs := rs) h e.1 e.2 ?_ headReg strideReg terms termFit (retained e.1)
+ refine (congrArg (fun n : ℕ => (mem n).val) cursor).trans ?_
+ exact allocated_id X (layout := layout) (mem := mem) first fit rows site r
+
+end PairSimulation.MapResidentInputs
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapRow.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapRow.lean
new file mode 100644
index 0000000000..8f7405c584
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapRow.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.PairSimulationMapRowExact
+
+/-! # Uniformly bounded native evaluation of one decoded motif row -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapRow
+
+open MotifSelector MotifDemandPadding MotifEntry MotifGrid MotifBlocks MotifConversion MapLookup
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {J D E : Type} [DecidableEq J] [Fintype J] [Fintype D] [Fintype E]
+ {K : Type} [Field K] {src dst : D → J} {G : Supply J E}
+ {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H')
+ (z : B.grid.demands) (s : Selector B) {u w r k pcCount : ℕ}
+ (i : Fin u) (j : J) (demand : D → ℕ) (v : E → ℕ) (d : DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j)
+ (base : LabelField D E → ℕ) (off : E → ℕ) (fd : ∀ e, baseDemand B z e ≤ w)
+ (fs : ∀ e, basePayload B s e ≤ w)
+ (reg : MapRowFields.Registers (LabelField D E) (D ⊕ E) r) (widthPort : (D ⊕ E) → Fin k)
+ (key : LabelRow B z s j → LabelField D E → Fin k) (name : LabelRow B z s j → Fin k)
+ (P : Sites (pcCount := pcCount) B z s j reg widthPort key name)
+
+/-- Reading one decoded copy computes its prescribed parameter ordinal and advances
+the natural offsets of every group. The only private operations are deterministic ticks. -/
+theorem native (ordinal : (parameterData B).Entry → BurstRAM.Word w)
+ (M : Machine w pcCount r k) (stop bad : Fin pcCount)
+ (hl : Linked B z s j reg widthPort key name P M stop bad)
+ (hp : ∀ g, M.publicData (widthPort g) =
+ ((Sum.elim (baseDemand B z) (basePayload B s) g : ℕ) : BurstRAM.Word w))
+ (hkey : ∀ y f, M.publicData (key y f) = labelKey B z s j fd fs y f)
+ (hname : ∀ y, M.publicData (name y) = ordinal (lookup B z s j y.1 y.2))
+ (fit : MapRowFields.Fits group (Sum.elim (baseDemand B z) (basePayload B s))
+ (slices B z i j demand v d x base off) w)
+ (c : Config w pcCount r)
+ (hc : c.pc = P.fields.first (P.lookupPC (nameFlow B z s j reg key name).entry)
+ (labelFields D E))
+ (hr : MapRowFields.Resident reg (slices B z i j demand v d x base off) c) :
+ let buffers := slices B z i j demand v d x base off
+ let width := Sum.elim (baseDemand B z) (basePayload B s)
+ ∃ n ≤ cap B z s j, ∃ out, Prefix M c (List.replicate n .tick) out ∧ out.pc = stop ∧
+ out.reg (reg .label) = ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i s off) ∧
+ MapRowFields.Resident reg { buffers with offset := fun g ↦ buffers.offset g + width g } out ∧
+ (∀ q, q ≠ reg .label → (∀ g, q ≠ reg (.offset g)) → q ≠ reg .tmp →
+ q ≠ reg .start → q ≠ reg .cursor → (∀ f, q ≠ reg (.query f)) → out.reg q = c.reg q) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ intro buffers width
+ exact ⟨exactSteps B z s i j demand v d x off fd fs key M.publicData,
+ exactSteps_le_cap B z s i j demand v d x off fd fs key M.publicData,
+ native_exact B z s i j demand v d x base off fd fs reg widthPort key name P ordinal M stop bad
+ hl hp hkey hname fit c hc hr⟩
+
+end PairSimulation.MapRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapRowCode.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapRowCode.lean
new file mode 100644
index 0000000000..2582ccda14
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapRowCode.lean
@@ -0,0 +1,229 @@
+import OAI.Computability.VPVNP.PairSimulationMapRow
+
+/-!
+# Finite instruction table for one decoded base row
+
+The field setup and padded reader have four and seven instruction rows per
+endpoint. Their exits follow the fixed field order. The lookup and offset
+advance blocks use their own finite labels. A pair of final instructions
+returns the parameter ordinal or rejects.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapRowCode
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM MapRowFields
+open scoped Fin.CommRing
+
+variable {I A : Type*} [DecidableEq I] {r k p w : ℕ}
+
+/-- Distinct addresses of all instruction rows, including the two exits. -/
+abbrev Address (I : Type*) (look advance : Flow r k) :=
+ (I × Fin 4) ⊕ (I × Fin 7) ⊕ Fin look.length ⊕ Fin advance.length ⊕ Bool
+
+variable (look advance : Flow r k) (loc : Address I look advance → Fin p)
+
+/-- Program counters for the four setup instructions and seven padded-reader instructions of
+each endpoint, relocated into the row's address space. -/
+def fieldSites : Sites I p where
+ setupPC i a := loc (.inl (i, a))
+ readerPC i a := loc (.inr (.inl (i, a)))
+
+/-- Relocate a label of the matrix lookup flow to its instruction address in the row table. -/
+def lookupPC (a : look.Label) : Fin p := loc (.inr (.inr (.inl (look.labels a))))
+
+/-- Relocate a label of the group offset advance flow to its instruction address in the row
+table. -/
+def advancePC (a : advance.Label) : Fin p := loc (.inr (.inr (.inr (.inl (advance.labels a)))))
+
+/-- The row's normal return address when `bad` is false or its rejecting address when `bad` is
+true. -/
+def exitPC (bad : Bool) : Fin p := loc (.inr (.inr (.inr (.inr bad))))
+
+/-- Resolve the fall-through after the field's reader against the fixed field order. -/
+def afterField (sites : Sites I p) (stop : Fin p) (i : I) : List I → Fin p
+ | [] => stop
+ | h :: rest => if h = i then sites.first stop rest else afterField sites stop i rest
+
+variable (reg : Registers I A r) (group : I → A) (widthPort : A → Fin k)
+ (fields : List I)
+
+/-- Instructions for the fixed base row in a larger enclosing instruction address space. -/
+def text : Address I look advance → Instr 2 p r k
+ | .inl (i, a) =>
+ let sites := fieldSites look advance loc
+ setup reg group widthPort (sites.setupPC i) (sites.readerPC i) i a
+ | .inr (.inl (i, a)) =>
+ let sites := fieldSites look advance loc
+ let start := lookupPC look advance loc look.entry
+ FieldRead.instruction (sites.readerPC i) (readerRegs reg i) (afterField sites start i fields) a
+ | .inr (.inr (.inl n)) =>
+ let start := advancePC look advance loc advance.entry
+ let toPC := fun t : Option look.Label ↦ (t.map (lookupPC look advance loc)).getD start
+ ((look.code (look.labels.symm n)).map toPC).emit (exitPC look advance loc true)
+ | .inr (.inr (.inr (.inl n))) =>
+ let toPC := fun t : Option advance.Label ↦
+ (t.map (advancePC look advance loc)).getD (exitPC look advance loc false)
+ ((advance.code (advance.labels.symm n)).map toPC).emit (exitPC look advance loc true)
+ | .inr (.inr (.inr (.inr false))) => .returnState (reg .label)
+ | .inr (.inr (.inr (.inr true))) => .reject
+
+private theorem fields_linked (sites : Sites I p) (stop : Fin p) (M : Machine w p r k)
+ (fs : List I) (hn : fs.Nodup)
+ (hs : ∀ i ∈ fs, ∀ a, M.code (sites.setupPC i a) =
+ setup reg group widthPort (sites.setupPC i) (sites.readerPC i) i a)
+ (hr : ∀ i ∈ fs, FieldRead.Linked M (sites.readerPC i) (readerRegs reg i)
+ (afterField sites stop i fs)) :
+ Linked reg group widthPort M sites stop fs := by
+ induction fs with
+ | nil => trivial
+ | cons i fs ih =>
+ obtain ⟨hi, hn'⟩ := List.nodup_cons.mp hn
+ refine ⟨hs i (by simp), ?_, ih hn' (fun j hj ↦ hs j (by simp [hj])) ?_⟩
+ · simpa [afterField] using hr i List.mem_cons_self
+ · intro j hj
+ have ne : i ≠ j := fun he ↦ hi (he ▸ hj)
+ simpa [afterField, ne] using hr j (List.mem_cons_of_mem _ hj)
+
+/-- The normal and rejecting exits can instead belong to the enclosing evaluator. -/
+def inBody : Address I look advance → Bool
+ | .inr (.inr (.inr (.inr _))) => false
+ | _ => true
+
+/-- Linking the concrete text supplies the instruction hypotheses of each subroutine. -/
+theorem linked (M : Machine w p r k) (hn : fields.Nodup)
+ (h : ∀ a, inBody look advance a = true →
+ M.code (loc a) = (text look advance loc reg group widthPort fields a).resize w) :
+ let sites := fieldSites look advance loc
+ let l := lookupPC look advance loc
+ let a := advancePC look advance loc
+ let stop := exitPC look advance loc false
+ let bad := exitPC look advance loc true
+ Linked reg group widthPort M sites (l look.entry) fields ∧
+ Flow.Linked M look l (a advance.entry) bad ∧ Flow.Linked M advance a stop bad := by
+ intro sites l a stop bad
+ refine ⟨fields_linked reg group widthPort sites _ M fields hn ?_ ?_, ⟨?_⟩, ⟨?_⟩⟩
+ · intro i _ t
+ rw [show sites.setupPC i t = loc (.inl (i, t)) from rfl, h _ rfl]
+ fin_cases t <;> rfl
+ · intro i _ t
+ rw [show sites.readerPC i t = loc (.inr (.inl (i, t))) from rfl, h _ rfl]
+ fin_cases t <;> rfl
+ · intro t
+ rw [show l t = loc (.inr (.inr (.inl (look.labels t)))) from rfl, h _ rfl]
+ simp [text, l, a, bad]
+ · intro t
+ rw [show a t = loc (.inr (.inr (.inr (.inl (advance.labels t))))) from rfl, h _ rfl]
+ simp [text, a, stop, bad]
+
+variable [Fintype I]
+
+/-- Numerical labels chosen entirely from the finite table, before word width or input. -/
+noncomputable def addresses :
+ Address I look advance ≃ Fin (Fintype.card (Address I look advance)) :=
+ Fintype.equivFin _
+
+/-- A standalone executable template whose normal exit returns the emitted ordinal. -/
+noncomputable def template : Template (Fintype.card (Address I look advance)) r k :=
+ let place := addresses (I := I) look advance
+ ⟨2, (fieldSites look advance place).first (lookupPC look advance place look.entry) fields,
+ fun pc ↦ text look advance place reg group widthPort fields (place.symm pc)⟩
+
+/-- The standalone table has all required instruction rows for every word width. -/
+theorem template_text (pub : Fin k → Word w) (a : Address I look advance) :
+ let place := addresses (I := I) look advance
+ ((template look advance reg group widthPort fields).instantiate w pub).code (place a) =
+ (text look advance place reg group widthPort fields a).resize w := by
+ simp [template, Template.instantiate]
+
+
+section Block
+
+open MotifSelector MotifDemandPadding MotifGrid MotifBlocks MotifConversion MapLookup
+
+variable {J D E : Type} [Fintype J] [Fintype D] [Fintype E]
+ {K : Type} [Field K] {src dst : D → J} {G : Supply J E}
+ {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H')
+ (z : B.grid.demands) (s : Selector B) (j : J)
+ (reg : Registers (LabelField D E) (D ⊕ E) r) (wp : (D ⊕ E) → Fin k)
+ (key : LabelRow B z s j → LabelField D E → Fin k) (name : LabelRow B z s j → Fin k)
+
+/-- All counters of a decoded base row's code. -/
+noncomputable abbrev RowAddress :=
+ Address (LabelField D E) (MapRow.nameFlow B z s j reg key name) (MapRow.advanceFlow reg wp)
+
+/-- Link a row's fixed setup, read, lookup and cursor advance to the chosen PC positions. -/
+noncomputable def rowSites (place : RowAddress B z s j reg wp key name → Fin p) :
+ MapRow.Sites (pcCount := p) B z s j reg wp key name :=
+ ⟨fieldSites _ _ place, lookupPC _ _ place, advancePC _ _ place⟩
+
+open scoped Classical in
+/-- Only the indicated body addresses are required to match. The exit addresses
+can hold the next iteration or the caller's rejection instruction. -/
+theorem row_linked (place : RowAddress B z s j reg wp key name → Fin p) (M : Machine w p r k)
+ (h : ∀ a, inBody _ _ a = true → M.code (place a) =
+ (text _ _ place reg MapRow.group wp (labelFields D E) a).resize w) :
+ MapRow.Linked B z s j reg wp key name (rowSites B z s j reg wp key name place) M
+ (exitPC _ _ place false) (exitPC _ _ place true) := by
+ obtain ⟨hf, hl, ha⟩ := linked _ _ place reg MapRow.group wp (labelFields D E) M
+ (Finset.nodup_toList _) h
+ exact ⟨hf, hl, ha⟩
+
+open scoped Classical in
+/-- A single finite machine text realizes the decoded row links simultaneously for all
+word widths and public inputs. Its size uses only the fixed motif data. -/
+theorem row_template :
+ let Addr := RowAddress B z s j reg wp key name
+ let place := addresses (I := LabelField D E) (MapRow.nameFlow B z s j reg key name)
+ (MapRow.advanceFlow reg wp)
+ let sites := rowSites B z s j reg wp key name place
+ ∃ T : Template (Fintype.card Addr) r k,
+ T.entry = sites.fields.first (sites.lookupPC (MapRow.nameFlow B z s j reg key name).entry)
+ (labelFields D E) ∧ ∀ w (pub : Fin k → BurstRAM.Word w),
+ MapRow.Linked B z s j reg wp key name sites (T.instantiate w pub)
+ (exitPC _ _ place false) (exitPC _ _ place true) ∧
+ (T.instantiate w pub).code (exitPC _ _ place false) = .returnState (reg .label) ∧
+ (T.instantiate w pub).code (exitPC _ _ place true) = .reject := by
+ dsimp only
+ refine ⟨template _ _ reg MapRow.group wp (labelFields D E), rfl, fun w pub ↦ ⟨?_, ?_, ?_⟩⟩
+ · exact row_linked B z s j reg wp key name _ _ (fun a _ ↦ template_text _ _ _ _ _ _ pub a)
+ · exact template_text _ _ _ _ _ _ pub (.inr (.inr (.inr (.inr false))))
+ · exact template_text _ _ _ _ _ _ pub (.inr (.inr (.inr (.inr true))))
+
+/-- Width constants, every compared row word, and every emitted ordinal can occupy
+separate public ports of the fixed program. -/
+abbrev Port (X I A : Type*) := A ⊕ ((X × I) ⊕ X)
+
+/-- Public-word assignment for one selector, grid point, and party, giving the group widths,
+the expected digit at each row field, and the parameter ordinal of each matched row. -/
+noncomputable def publicWords
+ (ports : Port (LabelRow B z s j) (LabelField D E) (D ⊕ E) ≃ Fin k)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ e, basePayload B s e ≤ w)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) (a : Fin k) : BurstRAM.Word w :=
+ (ports.symm a).elim
+ (fun g ↦ ((Sum.elim (baseDemand B z) (basePayload B s) g : ℕ) : BurstRAM.Word w))
+ (Sum.elim (fun q ↦ labelKey B z s j fd fs q.1 q.2)
+ (fun y ↦ ordinal (lookup B z s j y.1 y.2)))
+
+theorem publicWords_spec
+ (ports : Port (LabelRow B z s j) (LabelField D E) (D ⊕ E) ≃ Fin k)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ e, basePayload B s e ≤ w)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w) :
+ let pub := publicWords B z s j ports fd fs ordinal
+ (∀ g, pub (ports (.inl g)) =
+ ((Sum.elim (baseDemand B z) (basePayload B s) g : ℕ) : BurstRAM.Word w)) ∧
+ (∀ y i, pub (ports (.inr (.inl (y, i)))) = labelKey B z s j fd fs y i) ∧
+ (∀ y, pub (ports (.inr (.inr y))) = ordinal (lookup B z s j y.1 y.2)) := by
+ simp [publicWords]
+
+end Block
+
+end PairSimulation.MapRowCode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapRowExact.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapRowExact.lean
new file mode 100644
index 0000000000..b341427cd2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapRowExact.lean
@@ -0,0 +1,265 @@
+import OAI.Computability.VPVNP.PairSimulationMapRowFields
+import OAI.Computability.VPVNP.PairSimulationMapOffsets
+
+/-!
+# One decoded copy of a grouped motif in private RAM
+
+The selected grid point, selector and party fix all widths, compared fields,
+and row names. The variable input consists of the resident wire bits, their
+base addresses and the running offsets. The program reads the fields, selects
+the corresponding fixed parameter, and advances both demand and supply offsets.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapRow
+
+open MotifSelector MotifDemandPadding MotifEntry MotifGrid MotifBlocks MotifConversion MapLookup
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {J D E : Type} [DecidableEq J]
+
+/-- Source and target are separate positions even for loops. Absent positions
+have an empty resident bit slice. -/
+def endpoint {A : Type} (src dst : A → J) (j : J) (len : A → ℕ)
+ (x : DemandBits src dst len j) : Bool × A → (l : ℕ) × (Fin l → Bool)
+ | (false, e) => if h : j = src e then ⟨len e, x.1 e h⟩ else ⟨0, Fin.elim0⟩
+ | (true, e) => if h : j = dst e then ⟨len e, x.2 e h⟩ else ⟨0, Fin.elim0⟩
+
+/-- The two ends of each group share its running offset. -/
+def group : LabelField D E → D ⊕ E
+ | .inl (_, e) => .inl e
+ | .inr (_, e) => .inr e
+
+private theorem digit_eq_widen {l w n : ℕ} (hn : n ≤ w) (bits : Fin l → Bool) (off : ℕ) :
+ (readField bits off n : BurstRAM.Word w) = widen hn (fieldIndex bits off n) := by
+ apply Fin.ext
+ exact Nat.mod_eq_of_lt ((readField_lt ..).trans_le (Nat.pow_le_pow_right (by decide) hn))
+
+private theorem read_empty (off n : ℕ) :
+ readField (Fin.elim0 : Fin 0 → Bool) off n = 0 := by simp [readField_eq_sum, paddedBit]
+
+variable [Fintype J] [Fintype D] [Fintype E]
+ {K : Type} [Field K] {src dst : D → J} {G : Supply J E}
+ {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ} (B : FixedBlock K src dst G
+ (realWidths p₀) (realWidths q₀) H H') (z : B.grid.demands) (s : Selector B)
+ {u : ℕ} (i : Fin u) (j : J) (demand : D → ℕ) (v : E → ℕ) (d : DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j)
+ (base : LabelField D E → ℕ) (off : E → ℕ)
+
+/-- A copy's complete endpoint slices, including demand padding and payload clipping. -/
+noncomputable def slices : MapRowFields.Slices (LabelField D E) (D ⊕ E) := by
+ let edges := Sum.elim (endpoint src dst j demand d)
+ (endpoint G.src G.dst j v (mapHalf G (fun _ ↦ payloadBits) x))
+ exact ⟨fun f ↦ (edges f).1, fun f ↦ (edges f).2, base,
+ Sum.elim (fun e ↦ baseDemand B z e * i.val) off⟩
+
+/-- The tuple of base demand digits and base payload digits from this copy. -/
+noncomputable def row : LabelRow B z s j :=
+ (demandFields src dst (baseDemand B z) i j d, mapHalf G (fun e b ↦
+ fieldIndex (payloadBits b) (off e) (basePayload B s e)) x)
+
+variable {w : ℕ} (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ e, basePayload B s e ≤ w)
+
+/-- The digits actually read by the native field scan give exactly the public-table key. -/
+theorem digit_eq_key (f : LabelField D E) :
+ MapRowFields.digit group (Sum.elim (baseDemand B z) (basePayload B s))
+ (slices B z i j demand v d x base off) f =
+ labelKey B z s j fd fs (row B z s i j demand v d x off) f := by
+ let read (seg : (l : ℕ) × (Fin l → Bool)) (off n : ℕ) : BurstRAM.Word w :=
+ (readField seg.2 off n : BurstRAM.Word w)
+ rcases f with ⟨b, e⟩ | ⟨b, e⟩
+ · change read (endpoint src dst j demand d (b, e)) _ _ = _
+ cases b <;> rw [endpoint]
+ · split
+ · rename_i h
+ simpa [read, labelKey, halfKey, h, row, demandFields, slices, group] using
+ digit_eq_widen (fd e) (d.1 e h) (baseDemand B z e * i.val)
+ · rename_i h
+ simp [read, read_empty, labelKey, halfKey, h]
+ · split
+ · rename_i h
+ simpa [read, labelKey, halfKey, h, row, demandFields, slices, group] using
+ digit_eq_widen (fd e) (d.2 e h) (baseDemand B z e * i.val)
+ · rename_i h
+ simp [read, read_empty, labelKey, halfKey, h]
+ · change read (endpoint G.src G.dst j v (mapHalf G (fun _ ↦ payloadBits) x) (b, e)) _ _ = _
+ cases b <;> rw [endpoint]
+ · split
+ · rename_i h
+ simpa [read, labelKey, halfKey, h, row, mapHalf, slices, group] using
+ digit_eq_widen (fs e) (payloadBits (x.1 e h)) (off e)
+ · rename_i h
+ simp [read, read_empty, labelKey, halfKey, h]
+ · split
+ · rename_i h
+ simpa [read, labelKey, halfKey, h, row, mapHalf, slices, group] using
+ digit_eq_widen (fs e) (payloadBits (x.2 e h)) (off e)
+ · rename_i h
+ simp [read, read_empty, labelKey, halfKey, h]
+
+
+variable {r k pcCount : ℕ}
+
+/-- A single cursor register per demand or supply group. -/
+def offsetReg (reg : MapRowFields.Registers (LabelField D E) (D ⊕ E) r) : (D ⊕ E) ↪ Fin r :=
+ (⟨MapRowFields.Slot.offset, fun _ _ ↦ MapRowFields.Slot.offset.inj⟩ :
+ (D ⊕ E) ↪ MapRowFields.Slot (LabelField D E) (D ⊕ E)).trans reg
+
+/-- Advance groups in a fixed order, including groups with no endpoint at the party. -/
+noncomputable def groups (D E : Type) [Fintype D] [Fintype E] : List (D ⊕ E) :=
+ Finset.univ.toList
+
+theorem mem_groups (g : D ⊕ E) : g ∈ groups D E := by simp [groups]
+
+theorem groups_nodup : (groups D E).Nodup := Finset.nodup_toList _
+
+variable (reg : MapRowFields.Registers (LabelField D E) (D ⊕ E) r)
+ (widthPort : (D ⊕ E) → Fin k)
+ (key : LabelRow B z s j → LabelField D E → Fin k) (name : LabelRow B z s j → Fin k)
+
+/-- Concrete table text chosen before the number of repetitions or the wire inputs. -/
+noncomputable def nameFlow : Flow r k :=
+ (table (labelFields D E) key (labelRows B z s j)).flow
+ (fun f ↦ reg (.query f)) (reg .tmp) (reg .label) name
+
+/-- Advance every demand and supply group's shared endpoint offset by the selected row's public
+width. -/
+noncomputable def advanceFlow : Flow r k :=
+ MapOffsets.code (offsetReg reg) widthPort (reg .tmp) (groups D E)
+
+/-- A fixed dispatch for the selected grid, selector and party. All links are between
+individual instruction rows. The enclosing evaluator supplies its normal and bad exits. -/
+structure Sites where
+ /-- Locations of the setup and padded-reader instructions used to assemble this row's
+ endpoint digits. -/
+ fields : MapRowFields.Sites (LabelField D E) pcCount
+ /-- Program-counter placement for the flow that looks up a parameter name from the assembled
+ endpoint digits. -/
+ lookupPC : (nameFlow B z s j reg key name).Label → Fin pcCount
+ /-- Program-counter placement for the flow that advances the demand and supply offsets after
+ lookup. -/
+ advancePC : (advanceFlow reg widthPort).Label → Fin pcCount
+
+variable (P : Sites (pcCount := pcCount) B z s j reg widthPort key name)
+
+/-- The machine links the field reads, parameter lookup, and offset updates in order, directing
+success to the supplied continuation and failure to the bad exit. -/
+structure Linked (M : Machine w pcCount r k) (stop bad : Fin pcCount) : Prop where
+ fields : MapRowFields.Linked reg group widthPort M P.fields
+ (P.lookupPC (nameFlow B z s j reg key name).entry) (labelFields D E)
+ lookup : Flow.Linked M (nameFlow B z s j reg key name) P.lookupPC
+ (P.advancePC (advanceFlow reg widthPort).entry) bad
+ advance : Flow.Linked M (advanceFlow reg widthPort) P.advancePC stop bad
+
+/-- Worst-case cost of the path for this base copy. -/
+noncomputable def cap : ℕ :=
+ MapRowFields.steps group (Sum.elim (baseDemand B z) (basePayload B s)) (labelFields D E) +
+ (2 * (labelFields D E).length * (labelRows B z s j).length + 1) +
+ (2 * (groups D E).length + 1)
+
+omit [DecidableEq J] in
+/-- One bound serves all branches of the fixed block before choosing any inputs,
+word width, repetitions, grid point, selector or party. -/
+theorem exists_uniform_cap : ∃ C : ℕ, ∀ z s j, cap B z s j ≤ C := by
+ classical
+ refine ⟨∑ z : B.grid.demands, ∑ s : Selector B, ∑ j, cap B z s j, fun z s j ↦ ?_⟩
+ calc
+ cap B z s j ≤ ∑ j', cap B z s j' :=
+ Finset.single_le_sum (fun _ _ ↦ Nat.zero_le _) (Finset.mem_univ j)
+ _ ≤ ∑ s', ∑ j', cap B z s' j' :=
+ Finset.single_le_sum (f := fun s' : Selector B ↦ ∑ j', cap B z s' j')
+ (fun _ _ ↦ Nat.zero_le _) (Finset.mem_univ s)
+ _ ≤ ∑ z', ∑ s', ∑ j', cap B z' s' j' :=
+ Finset.single_le_sum (f := fun z' : B.grid.demands ↦ ∑ s', ∑ j', cap B z' s' j')
+ (fun _ _ ↦ Nat.zero_le _) (Finset.mem_univ z)
+
+/-- The exact count uses the physical public bank and this copy's decoded row.
+The field scan and the cursor advances take fixed time. The label lookup stops
+as soon as its first matching row is found. -/
+noncomputable def exactSteps (pub : Fin k → BurstRAM.Word w) : ℕ :=
+ MapRowFields.steps group (Sum.elim (baseDemand B z) (basePayload B s)) (labelFields D E) +
+ ((table (labelFields D E) key (labelRows B z s j)).eval pub
+ (labelKey B z s j fd fs (row B z s i j demand v d x off))).2 +
+ (2 * (groups D E).length + 1)
+
+omit [DecidableEq J] in
+theorem exactSteps_le_cap (pub : Fin k → BurstRAM.Word w) :
+ exactSteps B z s i j demand v d x off fd fs key pub ≤ cap B z s j := by
+ exact Nat.add_le_add_right (Nat.add_le_add_left (table_eval ..).2 _) _
+
+/-- Reading one decoded copy computes its prescribed parameter ordinal and advances
+the natural offsets of every group. The only private operations are deterministic ticks. -/
+theorem native_exact (ordinal : (parameterData B).Entry → BurstRAM.Word w)
+ (M : Machine w pcCount r k) (stop bad : Fin pcCount)
+ (hl : Linked B z s j reg widthPort key name P M stop bad)
+ (hp : ∀ g, M.publicData (widthPort g) =
+ ((Sum.elim (baseDemand B z) (basePayload B s) g : ℕ) : BurstRAM.Word w))
+ (hkey : ∀ y f, M.publicData (key y f) = labelKey B z s j fd fs y f)
+ (hname : ∀ y, M.publicData (name y) = ordinal (lookup B z s j y.1 y.2))
+ (fit : MapRowFields.Fits group (Sum.elim (baseDemand B z) (basePayload B s))
+ (slices B z i j demand v d x base off) w)
+ (c : Config w pcCount r)
+ (hc : c.pc = P.fields.first (P.lookupPC (nameFlow B z s j reg key name).entry)
+ (labelFields D E))
+ (hr : MapRowFields.Resident reg (slices B z i j demand v d x base off) c) :
+ let buffers := slices B z i j demand v d x base off
+ let width := Sum.elim (baseDemand B z) (basePayload B s)
+ let n := exactSteps B z s i j demand v d x off fd fs key M.publicData
+ ∃ out, Prefix M c (List.replicate n .tick) out ∧ out.pc = stop ∧
+ out.reg (reg .label) = ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i s off) ∧
+ MapRowFields.Resident reg { buffers with offset := fun g ↦ buffers.offset g + width g } out ∧
+ (∀ q, q ≠ reg .label → (∀ g, q ≠ reg (.offset g)) → q ≠ reg .tmp →
+ q ≠ reg .start → q ≠ reg .cursor → (∀ f, q ≠ reg (.query f)) → out.reg q = c.reg q) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ classical
+ intro buffers width n
+ let fields := labelFields D E
+ let y := row B z s i j demand v d x off
+ obtain ⟨m, pre, hm, digits, frame, mem, per⟩ :=
+ MapRowFields.native reg group widthPort width buffers M P.fields _ fields
+ hl.fields hp fit c hc hr
+ have keys (f : LabelField D E) : m.reg (reg (.query f)) = labelKey B z s j fd fs y f :=
+ (digits f (mem_labelFields f)).trans (digit_eq_key B z s i j demand v d x base off fd fs f)
+ obtain ⟨a, scan, ha, hname', rest, mem', per'⟩ := native_label_exact B z s j fd fs
+ (labelRows B z s j) (mem_labelRows B z s j) fields mem_labelFields key name
+ (fun f ↦ reg (.query f)) (reg .tmp) (reg .label) (by simp) ordinal M hkey hname
+ P.lookupPC _ bad hl.lookup m hm y keys
+ obtain ⟨out, adv, hd, vals, stable, mem'', per''⟩ :=
+ MapOffsets.native (offsetReg reg) widthPort (reg .tmp) (by simp [offsetReg])
+ (groups D E) groups_nodup M P.advancePC stop bad hl.advance a ha
+ have am := MapRowFields.resident_frame reg buffers hr frame mem
+ have hmem := mem''.trans (mem'.trans mem)
+ have hframe (q) (hn : q ≠ reg .label) (hg : ∀ g, q ≠ reg (.offset g)) (ht : q ≠ reg .tmp)
+ (hs : q ≠ reg .start) (hc' : q ≠ reg .cursor) (hq : ∀ f, q ≠ reg (.query f)) :
+ out.reg q = c.reg q :=
+ (stable q ht fun g _ ↦ hg g).trans <| (rest q ht hn).trans <|
+ frame q hs hc' ht fun f _ ↦ hq f
+ refine ⟨out, ?_, hd, ?_, ?_, hframe, hmem, per''.trans (per'.trans per)⟩
+ · dsimp only [n, exactSteps]
+ rw [List.replicate_add, List.replicate_add]
+ exact (pre.append scan).append adv
+ · exact (stable _ (by simp) (by simp [offsetReg])).trans hname'
+ · constructor
+ · rw [hframe, hr.one] <;> simp
+ · intro f
+ rw [hframe, hr.base] <;> simp
+ · intro f
+ rw [hframe, hr.dataEnd] <;> simp
+ · intro g
+ have h := vals g
+ change out.reg (reg (.offset g)) = a.reg (reg (.offset g)) + _ at h
+ rw [ite_eq_left (mem_groups g), hp, rest, am.offset] at h <;> try simp
+ simpa [width, Nat.cast_add] using h
+ · intro f l
+ rw [hmem, hr.data]
+
+end PairSimulation.MapRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapRowFields.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapRowFields.lean
new file mode 100644
index 0000000000..2eea621316
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapRowFields.lean
@@ -0,0 +1,226 @@
+import OAI.Computability.VPVNP.PairSimulationMapStream
+import OAI.Computability.VPVNP.PairSimulationFieldRead
+
+/-!
+# Preparing the registers of a fixed motif row
+
+Every endpoint has its own base address, exclusive end and output register.
+Both endpoints of a group use the same current offset. Four instructions
+initialize the padded field reader from these resident registers and a fixed
+width port. The resulting loop preserves the register fields already read.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapRowFields
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM MotifEntry
+open scoped Fin.CommRing
+
+variable {I A : Type*} {w p r k : ℕ}
+
+/-- Fixed register allocation for row extraction, including both endpoint directions. -/
+inductive Slot (I A : Type*) where
+ | query (i : I)
+ | base (i : I)
+ | dataEnd (i : I)
+ | offset (g : A)
+ | cursor | start | one | tmp | label
+ deriving DecidableEq, Fintype
+
+/-- Inject the endpoint data and query slots, shared group offsets, and working registers for
+one row into the machine's physical registers. -/
+abbrev Registers (I A : Type*) (r : ℕ) := Slot I A ↪ Fin r
+
+/-- The padded reader writes the field's query register directly. -/
+def readerRegs (reg : Registers I A r) (i : I) : Fin 6 ↪ Fin r :=
+ (⟨![Slot.query i, .cursor, .start, .dataEnd i, .one, .tmp], by
+ intro l m h
+ fin_cases l <;> fin_cases m <;> first | rfl | cases h⟩ :
+ Fin 6 ↪ Slot I A).trans reg
+
+/-- Absolute field start, fixed width, exclusive high cursor and zero accumulator. -/
+def setup (reg : Registers I A r) (group : I → A) (width : A → Fin k)
+ (pc : Fin 4 → Fin p) (reader : Fin 7 → Fin p) (i : I) : Fin 4 → Instr w p r k :=
+ ![.binary .add (reg .start) (reg (.base i)) (reg (.offset (group i))) (pc 1),
+ .publicWord (reg .tmp) (width (group i)) (pc 2),
+ .binary .add (reg .cursor) (reg .start) (reg .tmp) (pc 3),
+ .constant (reg (.query i)) 0 (reader 0)]
+
+theorem resize_setup (reg : Registers I A r) (group : I → A) (width : A → Fin k)
+ (pc : Fin 4 → Fin p) (reader : Fin 7 → Fin p) (i : I) (a : Fin 4) :
+ (setup (w := 1) reg group width pc reader i a).resize w =
+ setup reg group width pc reader i a := by fin_cases a <;> rfl
+
+/-- Resident bit slices and current group offsets for one iteration. A zero-length
+slice represents an absent port and yields zero at any offset. -/
+structure Slices (I A : Type*) where
+ /-- Number of resident bits for each endpoint slice. An absent endpoint has length zero. -/
+ len : I → ℕ
+ /-- The bit at each in-range position of an endpoint's resident slice. -/
+ bits : (i : I) → Fin (len i) → Bool
+ /-- Private start address of each endpoint's resident bit slice. -/
+ base : I → ℕ
+ /-- Current bit offset shared by the endpoints of each demand or supply group. -/
+ offset : A → ℕ
+
+variable (reg : Registers I A r) (group : I → A) (port : A → Fin k)
+ (width : A → ℕ) (x : Slices I A)
+
+/-- Layout and cursors are resident before the scan and survive it intact. -/
+structure Resident (c : Config w p r) : Prop where
+ one : c.reg (reg .one) = 1
+ base : ∀ i, c.reg (reg (.base i)) = (x.base i : Word w)
+ dataEnd : ∀ i, c.reg (reg (.dataEnd i)) = ((x.base i + x.len i : ℕ) : Word w)
+ offset : ∀ a, c.reg (reg (.offset a)) = (x.offset a : Word w)
+ data : ∀ i (j : Fin (x.len i)), c.privateMem ((x.base i + j.val : ℕ) : Word w) =
+ encodeBit w (x.bits i j)
+
+/-- Full end and high cursor fit also for padded reads and malformed final totals. -/
+structure Fits (w : ℕ) : Prop where
+ width_le : ∀ a, width a ≤ w
+ high : ∀ i, x.base i + x.offset (group i) + width (group i) < 2 ^ w
+ dataEnd : ∀ i, x.base i + x.len i < 2 ^ w
+
+/-- Frame on every register outside the scratch words and the current output fields. -/
+def Frame (fs : List I) (c d : Config w p r) : Prop :=
+ ∀ q, q ≠ reg .start → q ≠ reg .cursor → q ≠ reg .tmp →
+ (∀ i ∈ fs, q ≠ reg (.query i)) → d.reg q = c.reg q
+
+theorem resident_frame {fs : List I} {c d : Config w p r}
+ (hr : Resident reg x c) (hf : Frame reg fs c d) (hm : d.privateMem = c.privateMem) :
+ Resident reg x d := by
+ constructor
+ · rw [hf, hr.one] <;> simp
+ · intro i
+ rw [hf, hr.base] <;> simp
+ · intro i
+ rw [hf, hr.dataEnd] <;> simp
+ · intro a
+ rw [hf, hr.offset] <;> simp
+ · intro i j
+ rw [hm, hr.data]
+
+/-- The natural digit stored in the word-sized query register. -/
+def digit (i : I) : Word w :=
+ (readField (x.bits i) (x.offset (group i)) (width (group i)) : Word w)
+
+/-- The four setup instructions and the padded field loop for one endpoint. -/
+theorem oneField (M : Machine w p r k) (i : I) (pc : Fin 4 → Fin p)
+ (reader : Fin 7 → Fin p) (done : Fin p)
+ (hl : ∀ l, M.code (pc l) = setup reg group port pc reader i l)
+ (read : FieldRead.Linked M reader (readerRegs reg i) done)
+ (hp : ∀ a, M.publicData (port a) = (width a : Word w)) (fit : Fits group width x w)
+ (c : Config w p r) (hc : c.pc = pc 0) (hr : Resident reg x c) :
+ ∃ d, Prefix M c (List.replicate (6 * width (group i) + 5) .tick) d ∧ d.pc = done ∧
+ d.reg (reg (.query i)) = digit group width x i ∧ Frame reg [i] c d ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ let off := x.base i + x.offset (group i)
+ let n := width (group i)
+ let c₁ := c.put (pc 1) (reg .start) (off : Word w)
+ let c₂ := c₁.put (pc 2) (reg .tmp) (n : Word w)
+ let c₃ := c₂.put (pc 3) (reg .cursor) ((off + n : ℕ) : Word w)
+ let c₄ := c₃.put (reader 0) (reg (.query i)) 0
+ have step (l : Fin 4) (d : Config w p r) (h : d.pc = pc l) :
+ M.program.step d = (setup reg group port pc reader i l).run M.publicData d := by
+ simp [Machine.program, h, hl l]
+ have h₀ : M.program.step c = .localStep c₁ := by
+ rw [step 0 c hc]
+ change CallAction.localStep (c.put _ _ (c.reg (reg (.base i)) + c.reg (reg (.offset _)))) = _
+ simp [c₁, off, hr.base, hr.offset]
+ have h₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step 1 c₁ rfl]
+ change CallAction.localStep (c₁.put _ _ (M.publicData _)) = _
+ rw [hp]
+ have h₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step 2 c₂ rfl]
+ change CallAction.localStep (c₂.put _ _ (c₂.reg (reg .start) + c₂.reg (reg .tmp))) = _
+ simp [c₃, c₂, c₁, Config.put]
+ have h₃ : M.program.step c₃ = .localStep c₄ := step 3 c₃ rfl
+ obtain ⟨d, run, hd, hdigit, _, frame, hm, hper⟩ :=
+ FieldRead.native_read read (x.bits i) (x.base i) (x.offset (group i)) n c₄ rfl
+ (fit.width_le _) (fit.high i) (fit.dataEnd i)
+ (by change c₄.reg (reg (.query i)) = 0; simp [c₄])
+ (by change c₄.reg (reg .cursor) = _; simp [c₄, c₃, Config.put, off])
+ (by change c₄.reg (reg .start) = _; simp [c₄, c₃, c₂, c₁, Config.put, off])
+ (by change c₄.reg (reg (.dataEnd i)) = _; simp [c₄, c₃, c₂, c₁, Config.put, hr.dataEnd])
+ (by change c₄.reg (reg .one) = _; simp [c₄, c₃, c₂, c₁, Config.put, hr.one]) (hr.data i)
+ rw [meteredField_spec] at run
+ refine ⟨d, ?_, hd, ?_, ?_, hm, hper⟩
+ · have pre := Prefix.tick h₀ (.tick h₁ (.tick h₂ (.tick h₃ run)))
+ convert pre using 1
+ simp [n, List.replicate_succ]
+ · apply Fin.ext
+ rw [digit, Fin.val_natCast, Nat.mod_eq_of_lt]
+ · exact hdigit
+ · exact (readField_lt ..).trans_le (Nat.pow_le_pow_right (by decide) (fit.width_le _))
+ · intro q hs hc ht hq
+ have hqi := hq i (by simp)
+ have keep := frame q hqi hc ht
+ exact keep.trans (by simp [c₄, c₃, c₂, c₁, Config.put, hqi, hc, ht, hs])
+
+
+/-- Each field's four setup rows and seven reader rows occupy fixed program counters. -/
+structure Sites (I : Type*) (p : ℕ) where
+ /-- Four program counters per endpoint for setting up its padded field read. -/
+ setupPC : I → Fin 4 → Fin p
+ /-- Seven program counters per endpoint for the padded reader that writes the query digit. -/
+ readerPC : I → Fin 7 → Fin p
+
+/-- Enter the setup block of the first field in the list, transferring directly to `stop` when
+the list is empty. -/
+def Sites.first (sites : Sites I p) (stop : Fin p) : List I → Fin p
+ | [] => stop
+ | i :: _ => sites.setupPC i 0
+
+/-- Instruction-level links, with each field reader going straight to the next setup. -/
+def Linked (M : Machine w p r k) (sites : Sites I p) (stop : Fin p) : List I → Prop
+ | [] => True
+ | i :: rest =>
+ (∀ l, M.code (sites.setupPC i l) =
+ setup reg group port (sites.setupPC i) (sites.readerPC i) i l) ∧
+ FieldRead.Linked M (sites.readerPC i) (readerRegs reg i) (sites.first stop rest) ∧
+ Linked M sites stop rest
+
+/-- Every path for a selected base motif pays for exactly its fixed endpoint widths. -/
+def steps (fs : List I) : ℕ := (fs.map fun i ↦ 6 * width (group i) + 5).sum
+
+/-- All queried digits are simultaneously available at the lookup entry. Private bits,
+resident geometry and every register outside the stated frame are preserved. -/
+theorem native (M : Machine w p r k) (sites : Sites I p) (stop : Fin p) (fs : List I)
+ (hl : Linked reg group port M sites stop fs)
+ (hp : ∀ a, M.publicData (port a) = (width a : Word w))
+ (fit : Fits group width x w) (c : Config w p r) (hc : c.pc = sites.first stop fs)
+ (hr : Resident reg x c) :
+ ∃ d, Prefix M c (List.replicate (steps group width fs) .tick) d ∧ d.pc = stop ∧
+ (∀ i ∈ fs, d.reg (reg (.query i)) = digit group width x i) ∧
+ Frame reg fs c d ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ classical
+ induction fs generalizing c with
+ | nil => exact ⟨c, .nil _, hc, by simp, fun _ _ _ _ _ ↦ rfl, rfl, rfl⟩
+ | cons i rest ih =>
+ obtain ⟨mid, pre, pc, val, frame, mem, per⟩ := oneField reg group port width x M i
+ (sites.setupPC i) (sites.readerPC i) _ hl.1 hl.2.1 hp fit c hc hr
+ obtain ⟨d, tail, hd, vals, frame', mem', per'⟩ :=
+ ih hl.2.2 mid pc (resident_frame reg x hr frame mem)
+ refine ⟨d, ?_, hd, ?_, ?_, mem'.trans mem, per'.trans per⟩
+ · simpa only [steps, List.map_cons, List.sum_cons, List.replicate_add] using pre.append tail
+ · intro j hj
+ by_cases h : j ∈ rest
+ · exact vals j h
+ · have hj' : j = i := (List.mem_cons.mp hj).resolve_right h
+ subst j
+ apply (frame' _ (by simp) (by simp) (by simp) ?_).trans val
+ intro k hk he
+ exact h ((Slot.query.inj (reg.injective he)) ▸ hk)
+ · intro q hs hc ht hq
+ exact (frame' q hs hc ht fun i h ↦ hq i (List.mem_cons_of_mem _ h)).trans
+ (frame q hs hc ht fun j h ↦ hq j (List.mem_cons.mpr (.inl (List.mem_singleton.mp h))))
+
+end PairSimulation.MapRowFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapRowLoop.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapRowLoop.lean
new file mode 100644
index 0000000000..bb893045f6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapRowLoop.lean
@@ -0,0 +1,218 @@
+import OAI.Computability.VPVNP.PairSimulationMapRow
+import OAI.Computability.VPVNP.PairSimulationMapDriverFrame
+
+/-!
+# Resident motif rows throughout the private selector loop
+
+After each decoded selector the native row advances every group offset. The
+same invariant supplies the next row's read addresses and the final total
+for each supply edge, including supply edges absent at the current party.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapRowLoop
+
+open MotifSelector MotifDemandPadding MotifEntry MotifGrid MotifBlocks MotifConversion MapLookup
+open BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {K J D E : Type} [Field K] [Fintype J] [DecidableEq J] [Fintype D] [Fintype E]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H')
+ (z : B.grid.demands) (j : J) {u w p r k : ℕ} (demand : D → ℕ) (v : E → ℕ)
+ (d : DemandBits src dst demand j) (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j)
+ (base : LabelField D E → ℕ) (θ : Fin u → Selector B)
+
+/-- Sum of the widths of the first `n` copies, with value zero when `n > u`. -/
+def prefixWidth {u : ℕ} (f : Fin u → ℕ) (n : ℕ) : ℕ :=
+ if h : n ≤ u then ∑ i : Fin n, f (Fin.castLE h i) else 0
+
+@[simp] theorem prefix_zero (f : Fin u → ℕ) : prefixWidth f 0 = 0 := by simp [prefixWidth]
+
+theorem prefix_eq_offset (f : Fin u → ℕ) (i : Fin u) : prefixWidth f i.val = offset f i := by
+ simp [prefixWidth, offset, i.isLt.le]
+
+theorem prefix_last (f : Fin u → ℕ) : prefixWidth f u = ∑ i, f i := by simp [prefixWidth]
+
+theorem prefix_next (f : Fin u → ℕ) (i : Fin u) :
+ prefixWidth f (i.val + 1) = prefixWidth f i.val + f i := by
+ have hi : i.val + 1 ≤ u := i.isLt
+ simp only [prefixWidth, dite_eq_left hi, dite_eq_left i.isLt.le]
+ rw [Fin.sum_univ_castSucc]
+ rfl
+
+/-- Endpoint buffers do not move. Demand groups have fixed stride and each
+supply group has the stride selected at the preceding copy. -/
+noncomputable def buffers (n : ℕ) : MapRowFields.Slices (LabelField D E) (D ⊕ E) := by
+ let edges := Sum.elim (MapRow.endpoint src dst j demand d)
+ (MapRow.endpoint G.src G.dst j v (mapHalf G (fun _ ↦ payloadBits) x))
+ exact ⟨fun f ↦ (edges f).1, fun f ↦ (edges f).2, base,
+ Sum.elim (fun e ↦ baseDemand B z e * n) (fun e ↦ prefixWidth (fun i ↦ basePayload B (θ i) e) n)⟩
+
+private theorem buffers_copy (i : Fin u) : buffers B z j demand v d x base θ i.val =
+ MapRow.slices B z i j demand v d x base (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i) := by
+ simp [buffers, MapRow.slices, prefix_eq_offset]
+
+private theorem buffers_next (i : Fin u) : buffers B z j demand v d x base θ (i.val + 1) =
+ { buffers B z j demand v d x base θ i.val with
+ offset := fun g ↦ (buffers B z j demand v d x base θ i.val).offset g +
+ Sum.elim (baseDemand B z) (basePayload B (θ i)) g } := by
+ dsimp only [buffers]
+ congr 1
+ funext g
+ cases g <;> simp [Nat.mul_succ, prefix_next]
+
+variable (P : MapDriver.Program (Selector B) p r k)
+ (reg : MapRowFields.Registers (LabelField D E) (D ⊕ E) r)
+
+/-- A shared output register passes the returned ordinal directly to the driver.
+All the other controller registers lie outside the row workspace. -/
+structure RegisterLayout : Prop where
+ label : P.reg 6 = reg .label
+ apart : ∀ i : Fin 7, i ≠ 6 → ∀ a, P.reg i ≠ reg a
+
+/-- Private labels are stored outside the original endpoint words. -/
+theorem stable (layout : RegisterLayout B P reg) (labelBase : ℕ)
+ (sep : ∀ f (l : Fin ((buffers B z j demand v d x base θ 0).len f)),
+ ((base f + l.val : ℕ) : BurstRAM.Word w).val < labelBase ∨
+ labelBase + u ≤ ((base f + l.val : ℕ) : BurstRAM.Word w).val) :
+ P.Stable (w := w) (fun n ↦ MapRowFields.Resident reg (buffers B z j demand v d x base θ n))
+ labelBase u := by
+ intro n c c' hr regs mem _
+ have kept (a) : c'.reg (reg a) = c.reg (reg a) :=
+ regs _ (Ne.symm (layout.apart 0 (by decide) a)) (Ne.symm (layout.apart 2 (by decide) a))
+ (Ne.symm (layout.apart 4 (by decide) a)) (Ne.symm (layout.apart 5 (by decide) a))
+ exact ⟨(kept _).trans hr.one, fun f ↦ (kept _).trans (hr.base f),
+ fun f ↦ (kept _).trans (hr.dataEnd f), fun g ↦ (kept _).trans (hr.offset g),
+ fun f l ↦ (mem _ (sep f l)).trans (hr.data f l)⟩
+
+/-- Sum of the row instruction bounds over all selectors at grid point `z` and party `j`. -/
+noncomputable def rowCap : ℕ := ∑ s : Selector B, MapRow.cap B z s j
+
+/-- Fixed labels, decoded fields, temporary words and advancing offsets may
+be modified by a row. Other registers can be carried through the full scan. -/
+def OutsideRowWrites (save : Fin r → Prop) : Prop :=
+ ∀ q, save q → q ≠ reg .label ∧ (∀ g, q ≠ reg (.offset g)) ∧ q ≠ reg .tmp ∧
+ q ≠ reg .start ∧ q ≠ reg .cursor ∧ ∀ f, q ≠ reg (.query f)
+
+/-- The single-copy clock sees only the wire bits, preceding decoded selectors,
+and the fixed comparison table. -/
+noncomputable def rowSteps (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (key : ∀ s, LabelRow B z s j → LabelField D E → Fin k) (pub : Fin k → BurstRAM.Word w)
+ (i : Fin u) : ℕ :=
+ MapRow.exactSteps B z (θ i) i j demand v d x
+ (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i) fd (fs _) (key _) pub
+
+/-- The actual row subroutine also preserves every requested exterior word
+for the width test, histogram flush or enclosing vertex call. -/
+theorem rowRunsExactFramed (layout : RegisterLayout B P reg)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w)
+ (port : Selector B → (D ⊕ E) → Fin k)
+ (key : ∀ s, LabelRow B z s j → LabelField D E → Fin k) (name : ∀ s, LabelRow B z s j → Fin k)
+ (sites : ∀ s, MapRow.Sites (pcCount := p) B z s j reg (port s) (key s) (name s))
+ (M : Machine w p r k) (bad : Fin p)
+ (entry : ∀ s, P.rowPC s = (sites s).fields.first
+ ((sites s).lookupPC (MapRow.nameFlow B z s j reg (key s) (name s)).entry) (labelFields D E))
+ (linked : ∀ s, MapRow.Linked B z s j reg (port s) (key s) (name s) (sites s) M (P.pc 2) bad)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (widths : ∀ s g, M.publicData (port s g) =
+ ((Sum.elim (baseDemand B z) (basePayload B s) g : ℕ) : BurstRAM.Word w))
+ (keys : ∀ s y f, M.publicData (key s y f) = labelKey B z s j fd (fs s) y f)
+ (names : ∀ s y, M.publicData (name s y) = ordinal (lookup B z s j y.1 y.2))
+ (fit : ∀ i : Fin u, MapRowFields.Fits MapRow.group
+ (Sum.elim (baseDemand B z) (basePayload B (θ i)))
+ (buffers B z j demand v d x base θ i.val) w)
+ (save : Fin r → Prop) (saved : OutsideRowWrites reg save) :
+ P.FramedRowsWith θ (rowSteps B z j demand v d x θ fd fs key M.publicData) M
+ (fun i ↦ ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i (θ i)
+ (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i)))
+ (fun n ↦ MapRowFields.Resident reg (buffers B z j demand v d x base θ n))
+ (rowCap B z j) save := by
+ intro initial i c hc state
+ obtain ⟨hr, frame⟩ := state
+ have hbuf := buffers_copy B z j demand v d x base θ i
+ obtain ⟨out, pre, pc, label, hr', keep, mem, per⟩ :=
+ MapRow.native_exact B z (θ i) i j demand v d x base _ fd (fs _) reg (port _) (key _) (name _)
+ (sites _) ordinal M (P.pc 2) bad (linked _) (widths _) (keys _) (names _) (hbuf ▸ fit i) c
+ (hc.trans (entry _)) (hbuf ▸ hr)
+ have hn := MapRow.exactSteps_le_cap B z (θ i) i j demand v d x
+ (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i) fd (fs _) (key _) M.publicData
+ refine ⟨_, out, hn.trans (Finset.single_le_sum (fun s _ ↦ Nat.zero_le (MapRow.cap B z s j))
+ (Finset.mem_univ (θ i))), rfl, pre, pc, layout.label ▸ label, ?_, ?_, mem, per⟩
+ · constructor
+ · change MapRowFields.Resident reg (buffers B z j demand v d x base θ (i.val + 1)) out
+ rw [buffers_next, hbuf]
+ exact hr'
+ · intro q hq
+ obtain ⟨hlabel, hoff, htmp, hstart, hcur, hquery⟩ := saved q hq
+ exact (keep q hlabel hoff htmp hstart hcur hquery).trans (frame q hq)
+ · intro t
+ have h₆ : Fin.castLE (show 4 ≤ 7 by decide) t ≠ 6 := by fin_cases t <;> decide
+ have apart := layout.apart _ h₆
+ exact keep _ (apart _) (fun g ↦ apart _) (apart _) (apart _) (apart _) (fun f ↦ apart _)
+
+/-- The actual row subroutine also preserves every requested exterior word
+for the width test, histogram flush or enclosing vertex call. -/
+theorem rowRunsFramed (layout : RegisterLayout B P reg)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w)
+ (port : Selector B → (D ⊕ E) → Fin k)
+ (key : ∀ s, LabelRow B z s j → LabelField D E → Fin k) (name : ∀ s, LabelRow B z s j → Fin k)
+ (sites : ∀ s, MapRow.Sites (pcCount := p) B z s j reg (port s) (key s) (name s))
+ (M : Machine w p r k) (bad : Fin p)
+ (entry : ∀ s, P.rowPC s = (sites s).fields.first
+ ((sites s).lookupPC (MapRow.nameFlow B z s j reg (key s) (name s)).entry) (labelFields D E))
+ (linked : ∀ s, MapRow.Linked B z s j reg (port s) (key s) (name s) (sites s) M (P.pc 2) bad)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (widths : ∀ s g, M.publicData (port s g) =
+ ((Sum.elim (baseDemand B z) (basePayload B s) g : ℕ) : BurstRAM.Word w))
+ (keys : ∀ s y f, M.publicData (key s y f) = labelKey B z s j fd (fs s) y f)
+ (names : ∀ s y, M.publicData (name s y) = ordinal (lookup B z s j y.1 y.2))
+ (fit : ∀ i : Fin u, MapRowFields.Fits MapRow.group
+ (Sum.elim (baseDemand B z) (basePayload B (θ i)))
+ (buffers B z j demand v d x base θ i.val) w)
+ (save : Fin r → Prop) (saved : OutsideRowWrites reg save) :
+ P.FramedRows M θ (fun i ↦ ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i (θ i)
+ (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i)))
+ (fun n ↦ MapRowFields.Resident reg (buffers B z j demand v d x base θ n))
+ (rowCap B z j) save :=
+ MapDriver.Program.FramedRowsWith.forget P (rowRunsExactFramed B z j demand v d x base θ
+ P reg layout ordinal port key name sites M bad entry linked fd fs widths keys names fit
+ save saved)
+
+/-- Discharge the driver's row subroutine contract by following the actual
+field reads, fixed label comparisons and group-offset opcodes. -/
+theorem rowRuns (layout : RegisterLayout B P reg)
+ (ordinal : (parameterData B).Entry → BurstRAM.Word w)
+ (port : Selector B → (D ⊕ E) → Fin k)
+ (key : ∀ s, LabelRow B z s j → LabelField D E → Fin k) (name : ∀ s, LabelRow B z s j → Fin k)
+ (sites : ∀ s, MapRow.Sites (pcCount := p) B z s j reg (port s) (key s) (name s))
+ (M : Machine w p r k) (bad : Fin p)
+ (entry : ∀ s, P.rowPC s = (sites s).fields.first
+ ((sites s).lookupPC (MapRow.nameFlow B z s j reg (key s) (name s)).entry) (labelFields D E))
+ (linked : ∀ s, MapRow.Linked B z s j reg (port s) (key s) (name s) (sites s) M (P.pc 2) bad)
+ (fd : ∀ e, baseDemand B z e ≤ w) (fs : ∀ s e, basePayload B s e ≤ w)
+ (widths : ∀ s g, M.publicData (port s g) =
+ ((Sum.elim (baseDemand B z) (basePayload B s) g : ℕ) : BurstRAM.Word w))
+ (keys : ∀ s y f, M.publicData (key s y f) = labelKey B z s j fd (fs s) y f)
+ (names : ∀ s y, M.publicData (name s y) = ordinal (lookup B z s j y.1 y.2))
+ (fit : ∀ i : Fin u, MapRowFields.Fits MapRow.group
+ (Sum.elim (baseDemand B z) (basePayload B (θ i)))
+ (buffers B z j demand v d x base θ i.val) w) :
+ P.RowRuns M θ (fun i ↦ ordinal (MapStream.readRow src dst (baseDemand B z) demand G
+ (basePayload B) (lookup B z) v j d x i (θ i)
+ (fun e ↦ offset (fun l ↦ basePayload B (θ l) e) i)))
+ (fun n ↦ MapRowFields.Resident reg (buffers B z j demand v d x base θ n)) (rowCap B z j) := by
+ exact MapDriver.Program.FramedRows.forget P
+ (rowRunsFramed B z j demand v d x base θ P reg layout ordinal port key name sites M bad
+ entry linked fd fs widths keys names fit (fun _ ↦ False) (fun _ h ↦ h.elim))
+
+end PairSimulation.MapRowLoop
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapScanAcceptance.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapScanAcceptance.lean
new file mode 100644
index 0000000000..14ddd2dd7a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapScanAcceptance.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoopExact
+
+/-!
+# Acceptance of a finite row of deterministic resident maps
+
+Even though each successful map changes the scratch passed to the next,
+the scan's success bit depends only on the acceptance predicate of each
+occurrence when that predicate holds for all starting scratch values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentMapLoop.Exact
+
+open BurstRAM DFS
+
+variable {w endAddr n : ℕ}
+
+/-- Once each occurrence's success bit is determined by its typed input,
+the whole scratch-dependent loop succeeds exactly when every occurrence does. -/
+theorem scan_ofFn_iff (node : Word w) (rows : Fin n → Action w endAddr) (accepts : Fin n → Prop)
+ (spec : ∀ i s, (rows i node s).isSome ↔ accepts i) (saved : Scratch w endAddr) :
+ (scan node (List.ofFn rows) saved).isSome ↔ ∀ i, accepts i := by
+ induction n generalizing saved with
+ | zero => simp [scan]
+ | succ n ih =>
+ rw [List.ofFn_succ, Fin.forall_fin_succ]
+ cases head : rows 0 node saved with
+ | none =>
+ have no : ¬ accepts 0 := fun h => by simpa [head] using (spec 0 saved).mpr h
+ simp [scan, head, no]
+ | some pair =>
+ obtain ⟨es, mid⟩ := pair
+ have yes := (spec 0 saved).mp (by simp [head])
+ have next := ih (fun i => rows i.succ) (fun i => accepts i.succ)
+ (fun i => spec i.succ) mid
+ cases rest : scan node (List.ofFn fun i => rows i.succ) mid with
+ | none => simpa only [scan, head, rest, true_and, yes] using next
+ | some pair =>
+ obtain ⟨tail, final⟩ := pair
+ simpa only [scan, head, rest, true_and, yes, Option.isSome_some] using next
+
+/-- On a successful scan, any coordinate updated additively by each
+occurrence receives the sum of the actual updates in row order. -/
+theorem scan_ofFn_add {β : Type*} [AddCommMonoid β] (node : Word w)
+ (rows : Fin n → Action w endAddr) (coord : Scratch w endAddr → β) (delta : Fin n → β)
+ (step : ∀ j s es out, rows j node s = some (es, out) → coord out = coord s + delta j)
+ {saved out : Scratch w endAddr} {es : List (Event w)}
+ (run : scan node (List.ofFn rows) saved = some (es, out)) :
+ coord out = coord saved + ∑ j, delta j := by
+ induction n generalizing saved out es with
+ | zero =>
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj run)
+ simp
+ | succ n ih =>
+ rw [List.ofFn_succ] at run
+ cases head : rows 0 node saved with
+ | none => simp [scan, head] at run
+ | some pair =>
+ obtain ⟨first, mid⟩ := pair
+ cases rest : scan node (List.ofFn fun j => rows j.succ) mid with
+ | none => simp [scan, head, rest] at run
+ | some pair =>
+ obtain ⟨tail, last⟩ := pair
+ simp only [scan, head, rest, Option.some.injEq, Prod.mk.injEq] at run
+ rw [← run.2, ih (fun j => rows j.succ) (fun j => delta j.succ) (fun j => step j.succ) rest,
+ step 0 saved first mid head, Fin.sum_univ_succ, add_assoc]
+
+end PairSimulation.ResidentMapLoop.Exact
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapScratch.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapScratch.lean
new file mode 100644
index 0000000000..a4ae79b142
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapScratch.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.PairSimulationMapCallRun
+import OAI.Computability.VPVNP.PairSimulationDFSHooks
+
+/-!
+# Exact upper scratch of a successful grouped-map visit
+
+The descriptor publisher writes its argument words, the initializer writes
+the pointer directory, and the evaluator writes the decoded selector ordinals
+and parameter labels before incrementing the histogram. At an individual
+address this result depends only on the incoming contents of that address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapScratch
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry MapCallSetup MapEntryTable
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k p w t u : ℕ}
+ (A : Allocation B z j r k) (args : Arg D E ≃ Fin (Fintype.card (Arg D E)))
+ (loc : A.Address → Fin p) {demand : D → ℕ} {v : E → ℕ}
+ {d : DemandBits src dst demand j} {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (X : MapEntry.Program.Workspace (A.program loc) demand v d x t w)
+ (addr : BurstRAM.Word w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t)
+
+/-- The descriptor's address and field order come from the fixed argument writer. -/
+noncomputable def published (old : PrivateScratch.Memory w) : PrivateScratch.Memory w :=
+ PrivateScratch.write addr (fun i ↦ values A loc X (args.symm i)) old
+
+/-- Complete private memory update used when the selector and total-width checks succeed. -/
+noncomputable def successMemory (old : PrivateScratch.Memory w) : PrivateScratch.Memory w :=
+ let init := directoryMemory A loc X (published A args loc X addr old)
+ (selectorRun G (selectorTable B) (selectorCode B) v j x).1.elim init
+ (fun θ ↦ (A.program loc).successMemory X sel ord θ init)
+
+/-- The semantic entry succeeds only at a decoded sequence with its full width vector. -/
+theorem sequence_of_success
+ (good : (MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.isSome = true) :
+ ∃ θ, (selectorRun G (selectorTable B) (selectorCode B) v j x).1 = some θ ∧
+ ∀ e, v e = totalWidth (basePayload B) θ e := by
+ rw [MapFinish.entry_value] at good
+ cases hs : (selectorRun G (selectorTable B) (selectorCode B) v j x).1 with
+ | none => simp [hs] at good
+ | some θ =>
+ rw [hs, Option.bind_some] at good
+ split at good
+ · exact ⟨θ, rfl, by assumption⟩
+ · simp at good
+
+/-- On a successful native visit every private address has the prescribed value. -/
+theorem exact_memory {old new : PrivateScratch.Memory w}
+ (good : (MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.isSome = true)
+ (post : Success A loc X sel ord (published A args loc X addr old) new) :
+ new = successMemory A args loc X addr sel ord old := by
+ obtain ⟨θ, tags, valid⟩ := sequence_of_success good
+ simpa only [successMemory, tags, Option.elim_some] using post θ tags valid
+
+theorem successMemory_congr_at {old old' : PrivateScratch.Memory w} (q : BurstRAM.Word w)
+ (h : old q = old' q) :
+ successMemory A args loc X addr sel ord old q =
+ successMemory A args loc X addr sel ord old' q := by
+ have init : directoryMemory A loc X (published A args loc X addr old) q =
+ directoryMemory A loc X (published A args loc X addr old') q :=
+ PrivateScratch.write_congr_at _ _ q (PrivateScratch.write_congr_at _ _ q h)
+ cases hs : (selectorRun G (selectorTable B) (selectorCode B) v j x).1 with
+ | none => simpa only [successMemory, hs, Option.elim_none] using init
+ | some θ => simpa only [successMemory, hs, Option.elim_some] using
+ (A.program loc).successMemory_congr_at X sel ord θ q init
+
+/-- The canonical outgoing upper scratch is defined on the upper scratch alone. -/
+noncomputable def upper (endAddr : ℕ) (saved : DFS.Scratch w endAddr) : DFS.Scratch w endAddr :=
+ DFS.scratch endAddr (successMemory A args loc X addr sel ord
+ (fun a ↦ if h : endAddr ≤ a.val then saved ⟨a, h⟩ else 0))
+
+theorem exact_upper (endAddr : ℕ) (saved : DFS.Scratch w endAddr)
+ {old new : PrivateScratch.Memory w}
+ (incoming : DFS.scratch endAddr old = saved)
+ (good : (MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.isSome = true)
+ (post : Success A loc X sel ord (published A args loc X addr old) new) :
+ DFS.scratch endAddr new = upper A args loc X addr sel ord endAddr saved := by
+ rw [exact_memory A args loc X addr sel ord good post]
+ funext a
+ apply successMemory_congr_at
+ rw [dite_eq_left a.property]
+ exact congrFun incoming a
+
+/-- Two successful visits with the same incoming upper scratch agree at every upper word. -/
+theorem success_upper_eq (endAddr : ℕ) {old old' new new' : PrivateScratch.Memory w}
+ (incoming : DFS.scratch endAddr old = DFS.scratch endAddr old')
+ (good : (MotifEntry.run src dst (baseDemand B z) demand G (basePayload B) (lookup B z)
+ (selectorTable B) (selectorCode B) v j d x).1.isSome = true)
+ (post : Success A loc X sel ord (published A args loc X addr old) new)
+ (post' : Success A loc X sel ord (published A args loc X addr old') new') :
+ DFS.scratch endAddr new = DFS.scratch endAddr new' := by
+ exact (exact_upper A args loc X addr sel ord endAddr _ incoming good post).trans
+ (exact_upper A args loc X addr sel ord endAddr _ rfl good post').symm
+
+end PairSimulation.MapScratch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapScratchOutside.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapScratchOutside.lean
new file mode 100644
index 0000000000..c25b63859b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapScratchOutside.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.PairSimulationMapScratch
+import OAI.Computability.VPVNP.PairSimulationHistogramFrame
+import OAI.Computability.VPVNP.PairPendingArguments
+
+/-!
+# Exterior words of the grouped map's deterministic scratch update
+
+The descriptor and directory writes affect their indexed words. The selector
+and label writes affect fitted consecutive intervals. Histogram increments
+affect their selected bins. This calculation applies to any incoming scratch
+in the pure map interpreter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapScratch
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry MapCallSetup MapEntryTable
+open scoped Fin.CommRing
+
+private theorem write_other {w n : ℕ} (base : BurstRAM.Word w)
+ (value : Fin n → BurstRAM.Word w) (old : PrivateScratch.Memory w) (q : BurstRAM.Word w)
+ (apart : ∀ i : Fin n, q ≠ base + (i.val : BurstRAM.Word w)) :
+ PrivateScratch.write base value old q = old q := by
+ unfold PrivateScratch.write
+ apply dite_eq_right
+ rintro ⟨i, hi⟩
+ exact apart i hi.symm
+
+private theorem apart_of_interval {w n base : ℕ} (q : BurstRAM.Word w)
+ (room : base + n ≤ 2 ^ w) (outside : q.val < base ∨ base + n ≤ q.val) (i : Fin n) :
+ q ≠ (base : BurstRAM.Word w) + (i.val : BurstRAM.Word w) := by
+ intro eqn
+ have val := congrArg Fin.val eqn
+ rw [← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans_le
+ room)] at val
+ have := i.isLt
+ omega
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k p w t u : ℕ}
+ (A : Allocation B z j r k) (args : Arg D E ≃ Fin (Fintype.card (Arg D E)))
+ (loc : A.Address → Fin p) {demand : D → ℕ} {v : E → ℕ}
+ {d : DemandBits src dst demand j} {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (X : MapEntry.Program.Workspace (A.program loc) demand v d x t w)
+ (addr : BurstRAM.Word w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t)
+
+/-- Exterior cells agree with the input memory after evaluating the pure map update. -/
+theorem successMemory_outside (old : PrivateScratch.Memory w) (q : BurstRAM.Word w)
+ (fit : addr.val + Fintype.card (Arg D E) ≤ 2 ^ w)
+ (descriptor : q.val < addr.val ∨ addr.val + Fintype.card (Arg D E) ≤ q.val)
+ (other : MapCallSetup.Outside A loc X q) :
+ successMemory A args loc X addr sel ord old q = old q := by
+ have ptr (i : Fin (Fintype.card (Arg D E))) : q ≠ addr + (i.val : BurstRAM.Word w) := by
+ simpa only [Fin.cast_val_eq_self] using apart_of_interval q fit descriptor i
+ have desc : published A args loc X addr old q = old q := write_other _ _ _ _ ptr
+ let first := directoryMemory A loc X (published A args loc X addr old)
+ have directory : first q = old q := (write_other _ _ _ _ other.2).trans desc
+ cases code : (selectorRun G (selectorTable B) (selectorCode B) v j x).1 with
+ | none => simpa only [successMemory, code, Option.elim_none] using directory
+ | some θ =>
+ have hs := apart_of_interval q X.ordinalFit.le other.1.1
+ have ht := apart_of_interval q X.labelFit.le other.1.2.1
+ simp only [successMemory, code, Option.elim_some, MapEntry.Program.successMemory]
+ rw [PrivateLabels.accumulate_outside _ _ _ q other.1.2.2, write_other _ _ _ _ ht,
+ write_other _ _ _ _ hs]
+ exact directory
+
+/-- Project the same exterior identity through the scratch boundary. -/
+theorem upper_outside (endAddr : ℕ) (saved : DFS.Scratch w endAddr) (q : BurstRAM.Word w)
+ (fit : addr.val + Fintype.card (Arg D E) ≤ 2 ^ w)
+ (descriptor : q.val < addr.val ∨ addr.val + Fintype.card (Arg D E) ≤ q.val)
+ (other : MapCallSetup.Outside A loc X q) :
+ NodeArguments.rawScratch (upper A args loc X addr sel ord endAddr saved) q =
+ NodeArguments.rawScratch saved q := by
+ by_cases live : endAddr ≤ q.val
+ · simp only [NodeArguments.rawScratch, dite_eq_left live, upper, DFS.scratch]
+ exact (successMemory_outside A args loc X addr sel ord _ q fit descriptor other).trans
+ (dite_eq_left live)
+ · simp only [NodeArguments.rawScratch, dite_eq_right live]
+
+end PairSimulation.MapScratch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapSelectorBank.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapSelectorBank.lean
new file mode 100644
index 0000000000..cb11449f28
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapSelectorBank.lean
@@ -0,0 +1,190 @@
+import OAI.Computability.VPVNP.PairSimulationMapSelectors
+
+/-!
+# Relocatable finite text of the complete motif selector phase
+
+The directory scanner checks every incident selector suffix against the
+anchor. It enters the fixed anchor decoder on agreement, and both parts
+share a bad exit. The success address can be the first row-driver test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapSelectorBank
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+
+variable {X : Type*} {p r k w b : ℕ}
+
+/-- The selector phase's disjoint banks of eleven directory-scan registers and nine
+anchor-decoder registers. -/
+abbrev Register := Fin 11 ⊕ Fin 9
+
+/-- The first group holds port-scanner registers and the second holds
+anchor-decoder registers. Public ports contain raw codes and ordinals. -/
+structure Allocation (X : Type*) (r k : ℕ) where
+ /-- Place the directory scanner's registers and the anchor decoder's registers at distinct
+ positions in the enclosing machine. -/
+ register : Register ↪ Fin r
+ /-- Allocate distinct public ports to each selector's raw bit code and to its decoded
+ ordinal. -/
+ port : (X ⊕ X) ↪ Fin k
+
+/-- Finite placement for all selector-stage opcodes and two continuation addresses. -/
+inductive Location (lookupRows : ℕ) where
+ | directory (i : Fin 7)
+ | compareBits (i : Fin 7)
+ | decoder (i : Fin 5)
+ | reader (i : Fin 7)
+ | lookup (i : Fin lookupRows)
+ | exit (bad : Bool)
+ deriving Fintype, DecidableEq
+
+private noncomputable def number (Y : Type*) [Finite Y] : Y ≃ Fin (Nat.card Y) := by
+ letI := Fintype.ofFinite Y
+ exact Fintype.equivFinOfCardEq Nat.card_eq_fintype_card.symm
+
+/-- Standalone allocation that numbers all twenty selector registers and both public words of
+each selector. -/
+noncomputable def allocation (X : Type*) [Finite X] :
+ Allocation X (Nat.card Register) (Nat.card (X ⊕ X)) :=
+ ⟨(number Register).toEmbedding, (number (X ⊕ X)).toEmbedding⟩
+
+namespace Allocation
+
+variable (A : Allocation X r k)
+
+/-- Physical register placement for the eleven registers of the incident port scanner. -/
+def scanReg : Fin 11 ↪ Fin r := Function.Embedding.inl.trans A.register
+/-- Physical register placement for the nine registers of the anchor selector decoder. -/
+def decoderReg : Fin 9 ↪ Fin r := Function.Embedding.inr.trans A.register
+/-- Public port containing the raw selector code against which the extracted anchor bits are
+compared. -/
+def codePort (x : X) := A.port (.inl x)
+/-- Public port containing the ordinal produced when the anchor decoder matches this selector's
+code. -/
+def namePort (x : X) := A.port (.inr x)
+
+/-- Finite lookup flow that compares the extracted anchor field against the listed selector
+codes and loads the matching ordinal into the decoder's output register. -/
+def lookup (xs : List X) : Flow r k :=
+ ReadDecode.selectorFlow xs A.codePort A.namePort (AnchorDecode.fieldRegs A.decoderReg)
+ (A.decoderReg 0)
+
+/-- Addresses of the selector phase, including the directory and agreement loops, the anchor
+decoder and reader, the lookup rows for the given selector list, and both exits. -/
+abbrev Address (xs : List X) := Location (A.lookup xs).length
+
+variable (xs : List X) (loc : A.Address xs → Fin p)
+
+/-- The two components share the bad continuation. The successful decoder
+leaves its ordinal array ready at the supplied success address. -/
+def program : MapSelectors.Program X p r k where
+ decoder := {
+ xs := xs
+ key := A.codePort
+ name := A.namePort
+ reg := A.decoderReg
+ pc i := loc (.decoder i)
+ reader i := loc (.reader i)
+ label l := loc (.lookup ((A.lookup xs).labels l))
+ done := loc (.exit false)
+ bad := loc (.exit true) }
+ scan i := loc (.directory i)
+ inner i := loc (.compareBits i)
+ reg := A.scanReg
+ saved := by
+ intro i _ _ _
+ have ne (j : Fin 11) : A.decoderReg i ≠ A.scanReg j :=
+ A.register.injective.ne Sum.inr_ne_inl
+ exact ⟨ne 0, ne 1, ne 2, ne 4, ne 5, ne 6, ne 7⟩
+
+/-- Test whether a selector-phase address designates an instruction body that an enclosing
+program installs, with both continuations supplied by the caller. -/
+def inBody : A.Address xs → Bool
+ | .exit _ => false
+ | _ => true
+
+/-- The finite text uses a normal or bad halt only in standalone placements.
+A linked use installs the body and gives both exits to its enclosing program. -/
+def text : A.Address xs → Instr 2 p r k
+ | .directory i =>
+ let P := A.program xs loc
+ MapPortScan.instruction P.scan P.reg (P.inner 0) (P.decoder.pc 0) P.decoder.bad i
+ | .compareBits i =>
+ let P := A.program xs loc
+ MapConsistency.instruction P.inner (MapPortScan.innerRegs P.reg) (P.scan 4) i
+ | .decoder i => (A.program xs loc).decoder.instruction i
+ | .reader i =>
+ let P := (A.program xs loc).decoder
+ FieldRead.instruction P.reader (AnchorDecode.fieldRegs P.reg) (P.label P.selector.entry) i
+ | .lookup i =>
+ let P := (A.program xs loc).decoder
+ ((P.selector.code ((A.lookup xs).labels.symm i)).map (fun l ↦ (l.map P.label).getD (P.pc 4)))
+ |>.emit P.bad
+ | .exit false => .accept
+ | .exit true => .reject
+
+/-- Matching the body text at its relocated addresses discharges the
+instruction hypotheses of the port scan, bit comparison, field reader,
+selector lookup and ordinal-writing loop simultaneously. -/
+theorem linked (M : Machine w p r k) (install : ∀ a, A.inBody xs a = true →
+ M.code (loc a) = (A.text xs loc a).resize w) :
+ (A.program xs loc).Linked M := by
+ constructor
+ · constructor
+ · intro i
+ apply (install (.directory i) rfl).trans
+ fin_cases i <;> rfl
+ · intro i
+ apply (install (.compareBits i) rfl).trans
+ fin_cases i <;> rfl
+ · constructor
+ · intro i
+ apply (install (.decoder i) rfl).trans
+ fin_cases i <;> rfl
+ · intro i
+ apply (install (.reader i) rfl).trans
+ fin_cases i <;> rfl
+ · constructor
+ intro l
+ apply (install (.lookup ((A.lookup xs).labels l)) rfl).trans
+ let D := (A.program xs loc).decoder
+ have eq : (A.lookup xs).labels.symm ((A.lookup xs).labels l) = l :=
+ (A.lookup xs).labels.symm_apply_apply l
+ exact congrArg (fun q : D.selector.Label ↦ (((D.selector.code q).map
+ (fun t ↦ (t.map D.label).getD (D.pc 4))).emit D.bad).resize w) eq
+
+/-- Install the fixed public constants in a surrounding public-word bank. -/
+def words (fits : b ≤ w) (code : X ↪ Word b) (ordinal : X → Word w) : X ⊕ X → Word w :=
+ Sum.elim (fun x ↦ MapLookup.widen fits (code x)) ordinal
+
+theorem public_spec (M : Machine w p r k) (fits : b ≤ w) (code : X ↪ Word b)
+ (ordinal : X → Word w) (h : ∀ a, M.publicData (A.port a) = words fits code ordinal a) :
+ (∀ x, M.publicData ((A.program xs loc).decoder.key x) = MapLookup.widen fits (code x)) ∧
+ ∀ x, M.publicData ((A.program xs loc).decoder.name x) = ordinal x :=
+ ⟨fun x ↦ h (.inl x), fun x ↦ h (.inr x)⟩
+
+/-- Numbering this body and its exits gives a standalone finite template. -/
+noncomputable def locations : A.Address xs ≃ Fin (Nat.card (A.Address xs)) := number _
+
+/-- Standalone finite selector template that enters the incident-port scan and accepts after
+decoding the agreed anchor suffix or rejects a failed check. -/
+noncomputable def template : Template (Nat.card (A.Address xs)) r k :=
+ let loc := A.locations xs
+ ⟨2, (A.program xs loc).scan 0, fun i ↦ A.text xs loc (loc.symm i)⟩
+
+theorem template_linked (pub : Fin k → Word w) :
+ (A.program xs (A.locations xs)).Linked ((A.template xs).instantiate w pub) := by
+ apply A.linked
+ intro a _
+ simp [template, Template.instantiate]
+
+end Allocation
+end PairSimulation.MapSelectorBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapSelectorClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapSelectorClock.lean
new file mode 100644
index 0000000000..5f3eb56dd3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapSelectorClock.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairSimulationMapSelectors
+import OAI.Computability.VPVNP.PairSimulationAnchorClock
+
+/-!
+# Exact time for a successful map selector phase
+
+The directory scan compares every incident tag with the anchor. The
+decoder then visits the successful selector codes in descending copy
+order. Together they give the instruction count for the complete phase.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapSelectors.Program
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord MotifEntry
+open MotifSelector (Supply Half mapHalf)
+open MapPortAgreement MapResidentAgreement
+open scoped Fin.CommRing
+
+variable {X J E : Type*} {w p r k u b : ℕ} (P : Program X p r k)
+
+/-- Exact time to check all resident tags and write the selected ordinals. -/
+def successTicks (code : X ↪ Word b) (θ : Fin u → X) (ports : ℕ) : ℕ :=
+ (7 * (u * b) + 6) * ports + 3 + P.decoder.successTicks code θ
+
+theorem successTicks_le (code : X ↪ Word b) (θ : Fin u → X) (ports : ℕ) :
+ P.successTicks code θ ports ≤ (7 * (u * b) + 6) * ports + 3 + (P.decoder.visitCap b * u + 1) :=
+ Nat.add_le_add_left (P.decoder.successTicks_le code θ) _
+
+variable {P} [DecidableEq J] [Fintype E] {G : Supply J E} {party : J}
+ {v : E → ℕ} {M : Machine w p r k}
+
+/-- Every successful selector sequence gives the same exact clock for all
+ready configurations and yields the selector names at their destination cells. -/
+theorem native_success (hl : P.Linked M) (order : Fin (Fintype.card E) ≃ E) (fits : b ≤ w)
+ (code : X ↪ Word b) (keys : ∀ z, M.publicData (P.decoder.key z) = MapLookup.widen fits (code z))
+ (x : Half G (fun e ↦ Fin (v e + u * b) → Bool) party) (base : Port G party → Word w)
+ (dir : Word w) (dest : ℕ) (c : Config w p r) (ready : P.Ready order x base dir dest c)
+ (hn : (ports G party order).length < 2 ^ w) (hlen : u * b < 2 ^ w)
+ (hi : (base (anchorPort G party)).val + (v (edge (anchorPort G party)) + u * b) < 2 ^ w)
+ (hd : dest + u < 2 ^ w)
+ (sep : (base (anchorPort G party)).val + (v (edge (anchorPort G party)) + u * b) ≤ dest ∨
+ dest + u ≤ (base (anchorPort G party)).val)
+ (θ : Fin u → X) (ok : (selectorRun G P.decoder.xs code v party x).1 = some θ) :
+ ∃ d, Prefix M c (List.replicate (P.successTicks code θ (ports G party order).length) .tick) d ∧
+ P.Frame dest u c d ∧ d.pc = P.decoder.done ∧
+ ∀ i : Fin u, d.privateMem ((dest + i.val : ℕ) : Word w) = M.publicData (P.decoder.name (θ i)) := by
+ let t := anchorPort G party
+ let tags := mapHalf G (fun _ ↦ readTag) x
+ rw [selectorRun_value] at ok
+ change (if consistent G party tags then selectors? P.decoder.xs code (anchor G party tags)
+ else none) = some θ at ok
+ have agree : consistent G party tags = true := by
+ by_contra h
+ simp only [h, ↓reduceIte, reduceCtorEq] at ok
+ have anchorOK : selectors? P.decoder.xs code (readTag (field x t)) = some θ := by
+ simpa only [agree, ↓reduceIte, show anchor G party tags = readTag (field x t) from read_anchor x] using ok
+ obtain ⟨mid, pre, hm, frame, hmem, hp⟩ := MapResidentAgreement.native hl.scan order x base dir c
+ ready.pc ready.directory ready.endDir ready.anchor ready.width ready.one ready.zero ready.resident hn hlen
+ change mid.pc = (if consistent G party tags then P.decoder.pc 0 else P.decoder.bad) at hm
+ rw [ite_eq_left agree] at hm
+ have keep (i : Fin 9) (h₀ : i ≠ 0) (h₂ : i ≠ 2) (h₅ : i ≠ 5) :
+ mid.reg (P.decoder.reg i) = c.reg (P.decoder.reg i) := frame _ (P.saved i h₀ h₂ h₅)
+ have baseVal : ((base t).val : Word w) = base t := Fin.ext (Nat.mod_eq_of_lt (base t).isLt)
+ have dat : P.decoder.Ready (field x t) (base t).val dest u mid := by
+ constructor
+ · exact hm
+ · rw [keep 1 (by decide) (by decide) (by decide), ready.cursor, ready.dataEnd]
+ simp only [Nat.cast_add, Nat.mul_comm b u, baseVal, t]
+ · rw [keep 3 (by decide) (by decide) (by decide), ready.dataEnd]
+ simp only [Nat.cast_add, baseVal, t]
+ · exact (keep 4 (by decide) (by decide) (by decide)).trans ready.decoderOne
+ · exact (keep 6 (by decide) (by decide) (by decide)).trans ready.output
+ · exact (keep 7 (by decide) (by decide) (by decide)).trans ready.stop
+ · exact (keep 8 (by decide) (by decide) (by decide)).trans ready.codeWidth
+ · intro i
+ simpa only [hmem, Nat.cast_add, baseVal] using ready.resident.cells t i
+ obtain ⟨d, dec, f, done, stored⟩ :=
+ P.decoder.native_success hl.decoder fits code keys (field x t) (base t).val dest mid dat hi hd sep θ anchorOK
+ refine ⟨d, ?_, ?_, done, stored⟩
+ · rw [successTicks, List.replicate_add]
+ exact pre.append dec
+ · exact ⟨fun a hs h₀ h₁ h₂ h₅ h₆ ↦ (f.regs a h₀ h₁ h₂ h₅ h₆).trans (frame a hs),
+ fun a ha ↦ (f.memory a ha).trans (congrFun hmem a), f.persistent.trans hp⟩
+
+end PairSimulation.MapSelectors.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapSelectors.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapSelectors.lean
new file mode 100644
index 0000000000..cbfb26215a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapSelectors.lean
@@ -0,0 +1,164 @@
+import OAI.Computability.VPVNP.PairSimulationMapResidentAgreement
+import OAI.Computability.VPVNP.PairSimulationAnchorDecode
+
+/-!
+# Executing the grouped motif's selector phase in private memory
+
+Agreement across all incident fields leads directly to the decoder of the
+anchor field. A disagreement or an unused code reaches the same failure
+label. Each successful copy writes its selector ordinal at its own index.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapSelectors
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord MotifEntry
+open MotifSelector (Supply Half mapHalf)
+open MapPortAgreement MapResidentAgreement
+open scoped Fin.CommRing
+
+variable {X J E : Type*} [DecidableEq J] [Fintype E] {G : Supply J E} {party : J}
+variable {w p r k u b : ℕ} {v : E → ℕ}
+
+/-- The decoder's six incoming registers survive the directory walk.
+Scratch registers may be shared between the fragments. -/
+structure Program (X : Type*) (p r k : ℕ) where
+ /-- The fixed selector-code table and ordinal output loop. -/
+ decoder : AnchorDecode.Program X p r k
+ /-- The outer port-directory control labels. -/
+ scan : Fin 7 → Fin p
+ /-- The selector-bit comparison control labels. -/
+ inner : Fin 7 → Fin p
+ /-- The port-directory register allocation. -/
+ reg : Fin 11 ↪ Fin r
+ saved : ∀ i : Fin 9, i ≠ 0 → i ≠ 2 → i ≠ 5 → MapPortScan.Preserved reg (decoder.reg i)
+
+namespace Program
+
+variable (P : Program X p r k)
+
+/-- Both failure paths use the decoder's bad label. -/
+structure Linked (M : Machine w p r k) : Prop where
+ scan : MapPortScan.Linked M P.scan P.inner P.reg (P.decoder.pc 0) P.decoder.bad
+ decoder : P.decoder.Linked M
+
+/-- Entry data for a complete selector invocation. The anchor base is the
+base of its resident port. The decoder starts with its two high cursors. -/
+structure Ready (order : Fin (Fintype.card E) ≃ E)
+ (x : Half G (fun e ↦ Fin (v e + u * b) → Bool) party) (base : Port G party → Word w)
+ (dir : Word w) (dest : ℕ) (c : Config w p r) : Prop where
+ pc : c.pc = P.scan 0
+ directory : c.reg (P.reg 7) = dir
+ endDir : c.reg (P.reg 8) = dir + ((ports G party order).length : Word w)
+ anchor : c.reg (P.reg 9) = selectorStart v base (anchorPort G party)
+ width : c.reg (P.reg 10) = ((u * b : ℕ) : Word w)
+ one : c.reg (P.reg 3) = 1
+ zero : c.reg (P.reg 4) = 0
+ resident : Resident order x base c.privateMem dir
+ dataEnd : c.reg (P.decoder.reg 3) = base (anchorPort G party) +
+ ((v (edge (anchorPort G party)) + u * b : ℕ) : Word w)
+ cursor : c.reg (P.decoder.reg 1) = c.reg (P.decoder.reg 3)
+ decoderOne : c.reg (P.decoder.reg 4) = 1
+ output : c.reg (P.decoder.reg 6) = ((dest + u : ℕ) : Word w)
+ stop : c.reg (P.decoder.reg 7) = (dest : Word w)
+ codeWidth : c.reg (P.decoder.reg 8) = (b : Word w)
+
+/-- Registers needed by a continuation and private cells outside the ordinal
+destination interval survive both phases. -/
+structure Frame (dest u : ℕ) (c d : Config w p r) : Prop where
+ regs : ∀ a, MapPortScan.Preserved P.reg a → a ≠ P.decoder.reg 0 → a ≠ P.decoder.reg 1 →
+ a ≠ P.decoder.reg 2 → a ≠ P.decoder.reg 5 → a ≠ P.decoder.reg 6 → d.reg a = c.reg a
+ memory : ∀ a : Word w, a.val < dest ∨ dest + u ≤ a.val → d.privateMem a = c.privateMem a
+ persistent : d.persistent = c.persistent
+
+/-- Native result of the full selector phase, including ordinals on success
+and the genuine failure exit on every syntactic zero. -/
+structure Runs (M : Machine w p r k) (result : Option (Fin u → X)) (cap dest : ℕ)
+ (c : Config w p r) : Prop where
+ path : ∃ ticks d, ticks ≤ cap ∧ Prefix M c (List.replicate ticks .tick) d ∧ Frame P dest u c d ∧
+ match result with
+ | none => d.pc = P.decoder.bad
+ | some θ => d.pc = P.decoder.done ∧ ∀ i : Fin u,
+ d.privateMem ((dest + i.val : ℕ) : Word w) = M.publicData (P.decoder.name (θ i))
+
+variable {P} {M : Machine w p r k}
+
+omit [DecidableEq J] [Fintype E] in
+/-- The selector scan rejects inconsistent or unused tags on every external
+memory, branch tape and instruction budget when its bad exit is a reject. -/
+theorem Runs.rejects {cap dest : ℕ} {c : Config w p r} (hr : Runs (u := u) P M none cap dest c)
+ (hb : M.code P.decoder.bad = .reject) (fuel : ℕ) (mem : Memory w) (bits : List Bool) :
+ execute M.program fuel c mem bits = none := by
+ obtain ⟨_, _, _, pre, _, hpc⟩ := hr.path
+ exact MapLookup.reject_after_ticks pre (fun _ h ↦ List.eq_of_mem_replicate h)
+ (hpc ▸ hb) fuel mem bits
+
+/-- The native selector phase realizes the value of the metered motif
+interpreter on its actual resident half-wires. Its pathwise work bound also
+holds for unmatched half-wires and all unused anchor selector codes. -/
+theorem native (hl : P.Linked M) (order : Fin (Fintype.card E) ≃ E) (fits : b ≤ w)
+ (code : X ↪ Word b) (keys : ∀ z, M.publicData (P.decoder.key z) = MapLookup.widen fits (code z))
+ (x : Half G (fun e ↦ Fin (v e + u * b) → Bool) party) (base : Port G party → Word w)
+ (dir : Word w) (dest : ℕ) (c : Config w p r) (ready : P.Ready order x base dir dest c)
+ (hn : (ports G party order).length < 2 ^ w) (hlen : u * b < 2 ^ w)
+ (hi : (base (anchorPort G party)).val + (v (edge (anchorPort G party)) + u * b) < 2 ^ w)
+ (hd : dest + u < 2 ^ w)
+ (sep : (base (anchorPort G party)).val + (v (edge (anchorPort G party)) + u * b) ≤ dest ∨
+ dest + u ≤ (base (anchorPort G party)).val) :
+ Runs P M (selectorRun G P.decoder.xs code v party x).1
+ (((7 * (u * b) + 6) * (ports G party order).length + 3) + (P.decoder.visitCap b * u + 1))
+ dest c := by
+ let scanCost := (7 * (u * b) + 6) * (ports G party order).length + 3
+ let t := anchorPort G party
+ let tags := mapHalf G (fun _ ↦ readTag) x
+ obtain ⟨mid, pre, hm, frame, hmem, hp⟩ := MapResidentAgreement.native hl.scan order x base dir c
+ ready.pc ready.directory ready.endDir ready.anchor ready.width ready.one ready.zero
+ ready.resident hn hlen
+ change mid.pc = (if consistent G party tags then P.decoder.pc 0 else P.decoder.bad) at hm
+ rw [selectorRun_value]
+ change Runs P M (if consistent G party tags
+ then selectors? P.decoder.xs code (anchor G party tags) else none) (scanCost + _) dest c
+ by_cases hc : consistent G party tags = true
+ · rw [ite_eq_left hc] at hm ⊢
+ have keep (i : Fin 9) (h₀ : i ≠ 0) (h₂ : i ≠ 2) (h₅ : i ≠ 5) :
+ mid.reg (P.decoder.reg i) = c.reg (P.decoder.reg i) :=
+ frame _ (P.saved i h₀ h₂ h₅)
+ have baseVal : ((base t).val : Word w) = base t :=
+ Fin.ext (Nat.mod_eq_of_lt (base t).isLt)
+ have dat : P.decoder.Ready (field x t) (base t).val dest u mid := by
+ constructor
+ · exact hm
+ · rw [keep 1 (by decide) (by decide) (by decide), ready.cursor, ready.dataEnd]
+ simp only [Nat.cast_add, Nat.mul_comm b u, baseVal, t]
+ · rw [keep 3 (by decide) (by decide) (by decide), ready.dataEnd]
+ simp only [Nat.cast_add, baseVal, t]
+ · exact (keep 4 (by decide) (by decide) (by decide)).trans ready.decoderOne
+ · exact (keep 6 (by decide) (by decide) (by decide)).trans ready.output
+ · exact (keep 7 (by decide) (by decide) (by decide)).trans ready.stop
+ · exact (keep 8 (by decide) (by decide) (by decide)).trans ready.codeWidth
+ · intro i
+ simpa only [hmem, Nat.cast_add, baseVal] using ready.resident.cells t i
+ obtain ⟨ticks, d, cap, dec, f, res⟩ :=
+ P.decoder.native hl.decoder fits code keys (field x t) (base t).val dest mid dat hi hd sep
+ refine ⟨scanCost + ticks, d, Nat.add_le_add_left cap _, ?_, ?_, ?_⟩
+ · rw [List.replicate_add]
+ exact pre.append dec
+ · exact ⟨fun a hs h₀ h₁ h₂ h₅ h₆ ↦ (f.regs a h₀ h₁ h₂ h₅ h₆).trans (frame a hs),
+ fun a ha ↦ (f.memory a ha).trans (congrFun hmem a), f.persistent.trans hp⟩
+ · rw [show anchor G party tags = readTag (field x t) from read_anchor x]
+ cases hsel : selectors? P.decoder.xs code (readTag (field x t)) <;>
+ rw [hsel] at res <;> exact res
+ · rw [ite_eq_right hc] at hm ⊢
+ exact ⟨scanCost, mid, Nat.le_add_right _ _, pre,
+ ⟨fun a hs _ _ _ _ _ ↦ frame a hs, fun a _ ↦ congrFun hmem a, hp⟩,
+ hm⟩
+
+end Program
+end PairSimulation.MapSelectors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapStream.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapStream.lean
new file mode 100644
index 0000000000..1fec940384
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapStream.lean
@@ -0,0 +1,342 @@
+import OAI.Computability.VPVNP.PairSimulationMapLookup
+
+/-!
+# Reading a grouped motif one copy at a time
+
+Each iteration checks the two ends of all incident selectors against the
+anchor, decodes the common tag, and reads the local demand and payload row.
+The cursor advances on every supply edge, including edges away from the
+party. The terminal test compares this entire vector with the descriptor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapStream
+
+open MotifSelector MotifEntry
+
+variable {J D E S V : Type*} {bits u : ℕ}
+
+/-- Offsets of the next copy and labels of the completed copies, newest first. -/
+structure Cursor (E V : Type*) where
+ /-- Cumulative payload width already consumed on each supply edge, giving the starting bit
+ offset of the next copy. -/
+ offset : E → ℕ
+ /-- Labels obtained from completed copies, stored newest first so the scan can prepend each
+ new row result. -/
+ labelsRev : List V
+
+/-- Read one selector and one row per iteration. A malformed copy stops the scan. -/
+def scan (width : S → E → ℕ) : {n : ℕ} → (Fin n → Option S) →
+ (Fin n → S → (E → ℕ) → V) → Cursor E V → Option (Cursor E V)
+ | 0, _, _, c => some c
+ | n + 1, select, row, c => (select 0).bind fun s ↦
+ scan width (n := n) (fun i ↦ select i.succ) (fun i ↦ row i.succ)
+ ⟨fun e ↦ c.offset e + width s e, row 0 s c.offset :: c.labelsRev⟩
+
+/-- At a copy boundary the cumulative offset fits a fixed multiple of the copy index,
+even for a descriptor whose final width test will fail. -/
+theorem offset_le {n W : ℕ} (width : S → E → ℕ) (hw : ∀ s e, width s e ≤ W)
+ (θ : Fin n → S) (e : E) (i : Fin n) :
+ MotifEntry.offset (fun l ↦ width (θ l) e) i ≤ i.val * W := by
+ unfold MotifEntry.offset
+ simpa using Finset.sum_le_sum (s := Finset.univ)
+ (fun t : Fin i.val ↦ fun _ ↦ hw (θ (Fin.castLE i.isLt.le t)) e)
+
+/-- The full-vector comparison can use the same bound on arbitrary decoded selectors. -/
+theorem totalWidth_le {n W : ℕ} (width : S → E → ℕ) (hw : ∀ s e, width s e ≤ W)
+ (θ : Fin n → S) (e : E) : totalWidth width θ e ≤ n * W := by
+ simpa [totalWidth] using Finset.sum_le_sum (s := Finset.univ) (fun i _ ↦ hw (θ i) e)
+
+/-- A missing or inconsistent tag rejects the complete stream at any position. -/
+theorem scan_none (width : S → E → ℕ) {n : ℕ} (select : Fin n → Option S)
+ (row : Fin n → S → (E → ℕ) → V) (c : Cursor E V) (i : Fin n)
+ (hi : select i = none) : scan width select row c = none := by
+ induction n generalizing c with
+ | zero => exact i.elim0
+ | succ n ih =>
+ refine Fin.cases ?_ (fun j ↦ ?_) i hi
+ · intro h
+ simp [scan, h]
+ · intro h
+ cases he : select 0 with
+ | none => simp [scan, he]
+ | some s =>
+ simp only [scan, he, Option.bind_some]
+ exact ih _ _ _ j h
+
+private theorem offset_zero {n : ℕ} (w : Fin (n + 1) → ℕ) : MotifEntry.offset w 0 = 0 := by
+ change (∑ t : Fin 0, w (Fin.castLE (by omega) t)) = 0
+ simp
+
+private theorem offset_succ {n : ℕ} (w : Fin (n + 1) → ℕ) (i : Fin n) :
+ MotifEntry.offset w i.succ = w 0 + MotifEntry.offset (fun j ↦ w j.succ) i := by
+ unfold MotifEntry.offset
+ simp only [Fin.val_succ]
+ rw [Fin.sum_univ_succ]
+ rfl
+
+/-- The cursor before copy `i` is its prefix sum, the final cursor is the total,
+and each accepted row appears with its original multiplicity and copy position. -/
+theorem scan_some (width : S → E → ℕ) {n : ℕ} (select : Fin n → Option S)
+ (row : Fin n → S → (E → ℕ) → V) (c : Cursor E V) (θ : Fin n → S)
+ (ht : ∀ i, select i = some (θ i)) :
+ scan width select row c =
+ some ⟨fun e ↦ c.offset e + totalWidth width θ e,
+ (List.ofFn fun i ↦ row i (θ i)
+ (fun e ↦ c.offset e + MotifEntry.offset (fun l ↦ width (θ l) e) i)).reverse ++
+ c.labelsRev⟩ := by
+ induction n generalizing c with
+ | zero => simp [scan, totalWidth]
+ | succ n ih =>
+ simp only [scan, ht 0, Option.bind_some]
+ rw [ih _ _ _ (fun i ↦ θ i.succ) (fun i ↦ ht i.succ)]
+ simp [List.ofFn_succ, totalWidth, Fin.sum_univ_succ, offset_succ,
+ Nat.add_assoc, offset_zero]
+
+variable [DecidableEq J] [Fintype E]
+
+/-- Check both port directions at this copy, including both ends of a loop. -/
+def agrees (G : Supply J E) (j : J) (tags : Half G (fun _ ↦ Fin u → Word bits) j)
+ (i : Fin u) : Bool :=
+ let t := anchor G j tags i
+ decide (∀ e, (if h : j = G.src e then tags.1 e h i = t else True) ∧
+ (if h : j = G.dst e then tags.2 e h i = t else True))
+
+theorem consistent_iff_agrees (G : Supply J E) (j : J)
+ (tags : Half G (fun _ ↦ Fin u → Word bits) j) :
+ consistent G j tags = true ↔ ∀ i, agrees G j tags i = true := by
+ simp only [consistent, agrees, decide_eq_true_eq]
+ constructor
+ · intro h i e
+ obtain ⟨a, b⟩ := h e
+ constructor <;> split at * <;> simp_all
+ · intro h e
+ constructor
+ · split
+ · rename_i he
+ exact fun i ↦ by simpa [he] using (h i e).1
+ · trivial
+ · split
+ · rename_i he
+ exact fun i ↦ by simpa [he] using (h i e).2
+ · trivial
+
+/-- Restrict the input to one selector position to invoke the native whole-array
+agreement test on this copy. -/
+theorem agrees_eq_consistent_one (G : Supply J E) (j : J)
+ (tags : Half G (fun _ ↦ Fin u → Word bits) j) (i : Fin u) :
+ agrees G j tags i = consistent G j
+ (mapHalf G (fun _ t (_ : Fin 1) ↦ t i) tags) := by
+ let one := mapHalf G (fun _ t (_ : Fin 1) ↦ t i) tags
+ have ha (k : Fin 1) : anchor G j one k = anchor G j tags i := by
+ unfold anchor
+ split <;> rfl
+ apply Bool.eq_iff_iff.mpr
+ change agrees G j tags i = true ↔ consistent G j one = true
+ rw [consistent_iff_agrees]
+ simp only [Fin.forall_fin_one, agrees, ha]
+ rfl
+
+/-- An unused anchor code and a mismatch between any two incident ports
+both suppress the row lookup for this copy. -/
+def selectCopy (G : Supply J E) (table : List S) (code : S ↪ Word bits)
+ (j : J) (tags : Half G (fun _ ↦ Fin u → Word bits) j) (i : Fin u) : Option S :=
+ if agrees G j tags i then decode table code (anchor G j tags i) else none
+
+/-- A native precheck of the complete port arrays leaves just one anchor-table
+lookup per copy in the subsequent loop. -/
+theorem selectCopy_of_consistent (G : Supply J E) (table : List S) (code : S ↪ Word bits)
+ (j : J) (tags : Half G (fun _ ↦ Fin u → Word bits) j)
+ (ha : consistent G j tags = true) (i : Fin u) :
+ selectCopy G table code j tags i = decode table code (anchor G j tags i) := by
+ simp [selectCopy, (consistent_iff_agrees G j tags).1 ha i]
+
+/-- The local base-matrix row indexed by demand and payload fields, starting
+each payload field at the current cursor. -/
+def readRow (src dst : D → J) (a b : D → ℕ) (G : Supply J E) (width : S → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e ↦ Word (width s e)) j → V)
+ (v : E → ℕ) (j : J) (d : DemandBits src dst b j)
+ (x : Half G (fun e ↦ Fin (v e + u * bits) → Bool) j)
+ (i : Fin u) (s : S) (off : E → ℕ) : V :=
+ lookup s j (demandFields src dst a i j d)
+ (mapHalf G (fun e y ↦ fieldIndex (payloadBits y) (off e) (width s e)) x)
+
+/-- Check all final payload offsets and restore the order of the emitted labels. -/
+def finish (v : E → ℕ) (c : Cursor E V) : Option (List V) :=
+ if ∀ e, v e = c.offset e then some c.labelsRev.reverse else none
+
+/-- The complete streaming evaluator starts at zero and validates the full
+vector before returning the labels in copy order. -/
+def evaluate (src dst : D → J) (a b : D → ℕ) (G : Supply J E) (width : S → E → ℕ)
+ (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e ↦ Word (width s e)) j → V)
+ (table : List S) (code : S ↪ Word bits) (v : E → ℕ) (j : J)
+ (d : DemandBits src dst b j) (x : Half G (fun e ↦ Fin (v e + u * bits) → Bool) j) :
+ Option (List V) :=
+ let tags := mapHalf G (fun _ ↦ readTag) x
+ (scan width (selectCopy G table code j tags)
+ (readRow src dst a b G width lookup v j d x) ⟨fun _ ↦ 0, []⟩).bind (finish v)
+
+/-- Factor out a port-major native agreement pass. The remaining scan only
+decodes the anchor and reads payload and demand rows. -/
+theorem evaluate_after_consistency (src dst : D → J) (a b : D → ℕ) (G : Supply J E)
+ (width : S → E → ℕ) (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e ↦ Word (width s e)) j → V)
+ (table : List S) (code : S ↪ Word bits) (v : E → ℕ) (j : J)
+ (d : DemandBits src dst b j) (x : Half G (fun e ↦ Fin (v e + u * bits) → Bool) j) :
+ let tags := mapHalf G (fun _ ↦ readTag) x
+ evaluate src dst a b G width lookup table code v j d x =
+ if consistent G j tags then
+ (scan width (fun i ↦ decode table code (anchor G j tags i))
+ (readRow src dst a b G width lookup v j d x) ⟨fun _ ↦ 0, []⟩).bind (finish v)
+ else none := by
+ intro tags
+ change (scan width (selectCopy G table code j tags)
+ (readRow src dst a b G width lookup v j d x) ⟨fun _ ↦ 0, []⟩).bind (finish v) = _
+ by_cases ha : consistent G j tags = true
+ · rw [ite_eq_left ha, funext (selectCopy_of_consistent G table code j tags ha)]
+ · have hm : ¬ ∀ i, agrees G j tags i = true := fun h ↦ ha ((consistent_iff_agrees G j tags).2 h)
+ obtain ⟨i, hi⟩ := not_forall.mp hm
+ rw [ite_eq_right ha, scan_none width (selectCopy G table code j tags) _ _ i
+ (by simp [selectCopy, hi])]
+ rfl
+
+private theorem selectors_pointwise (table : List S) (code : S ↪ Word bits)
+ (t : Fin u → Word bits) (θ : Fin u → S) :
+ selectors? table code t = some θ ↔ ∀ i, decode table code (t i) = some (θ i) := by
+ simp only [selectors?, Vector.getElem_ofFn]
+ split
+ · rename_i h
+ simp only [Option.some.injEq]
+ constructor
+ · rintro rfl i
+ exact (Option.some_get (h i)).symm
+ · intro he
+ exact funext fun i ↦ Option.get_of_eq_some _ (he i)
+ · rename_i h
+ simp only [reduceCtorEq, false_iff]
+ intro he
+ exact h fun i ↦ by simp [he i]
+
+private theorem selectors_none (table : List S) (code : S ↪ Word bits) (t : Fin u → Word bits)
+ (h : selectors? table code t = none) : ∃ i, decode table code (t i) = none := by
+ by_contra! hn
+ have hs (i : Fin u) := Option.isSome_iff_ne_none.mpr (hn i)
+ have he := (selectors_pointwise table code t (fun i ↦ (decode table code (t i)).get (hs i))).2
+ (fun i ↦ (Option.some_get (hs i)).symm)
+ simp [h] at he
+
+/-- Equivalence with the metered entry interpreter for arbitrary input bits and
+arbitrary selector tables, with no consistency, completeness or width hypotheses. -/
+theorem evaluate_eq_run [Fintype D] (src dst : D → J) (a b : D → ℕ) (G : Supply J E)
+ (width : S → E → ℕ) (lookup : ∀ s j, MotifDemandPadding.HalfBits src dst a j →
+ Half G (fun e ↦ Word (width s e)) j → V)
+ (table : List S) (code : S ↪ Word bits) (v : E → ℕ) (j : J)
+ (d : DemandBits src dst b j) (x : Half G (fun e ↦ Fin (v e + u * bits) → Bool) j) :
+ evaluate src dst a b G width lookup table code v j d x =
+ (MotifEntry.run src dst a b G width lookup table code v j d x).1 := by
+ rw [MotifEntry.run_value]
+ let tags := mapHalf G (fun _ ↦ readTag) x
+ let row := readRow src dst a b G width lookup v j d x
+ let sel := fun i ↦ decode table code (anchor G j tags i)
+ let start : Cursor E V := ⟨fun _ ↦ 0, []⟩
+ rw [evaluate_after_consistency]
+ unfold describe labels indices
+ change (if consistent G j tags then (scan width sel row start).bind (finish v) else none) =
+ Option.map _ (if consistent G j tags then
+ (selectors? table code (anchor G j tags)).bind _ else none)
+ by_cases ha : consistent G j tags = true
+ · simp only [ha, ↓reduceIte]
+ cases hs : selectors? table code (anchor G j tags) with
+ | none =>
+ obtain ⟨i, hi⟩ := selectors_none _ _ _ hs
+ rw [scan_none width sel row start i hi]
+ rfl
+ | some θ =>
+ rw [scan_some width sel row start θ ((selectors_pointwise _ _ _ θ).1 hs)]
+ simp only [Option.bind_some, extract, finish, start, Nat.zero_add, List.append_nil,
+ List.reverse_reverse]
+ split <;> rfl
+ · simp [ha]
+
+
+section FixedBlock
+
+open MotifGrid MotifBlocks MotifConversion MotifDemandPadding MapLookup
+
+variable {K J D E : Type} [Field K] [Fintype J] [Fintype D] [Fintype E]
+ {src dst : D → J} {G : Supply J E} {p : D → ℚ} {q : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p) (realWidths q) H H')
+ (z : B.grid.demands) (s : Selector B) (j : J) {wordWidth : ℕ}
+ (fd : ∀ e, baseDemand B z e ≤ wordWidth) (fs : ∀ e, basePayload B s e ≤ wordWidth)
+
+/-- The row search tests the finite word tuple used by the native lookup tree.
+Neither the row table nor the field list depends on the number of repetitions. -/
+noncomputable def searchRow (x : LabelRow B z s j) : Option (LabelRow B z s j) :=
+ let key := labelKey B z s j fd fs
+ (labelRows B z s j).find? (fun y ↦ (labelFields D E).all fun i ↦ decide (key x i = key y i))
+
+theorem searchRow_eq (x : LabelRow B z s j) : searchRow B z s j fd fs x = some x := by
+ let key := labelKey B z s j fd fs
+ let isMatch := fun y ↦ (labelFields D E).all fun i ↦ decide (key x i = key y i)
+ change (labelRows B z s j).find? isMatch = some x
+ cases he : (labelRows B z s j).find? isMatch with
+ | none =>
+ have hm : isMatch x = true := by simp [isMatch]
+ exact ((List.find?_eq_none.mp he x (mem_labelRows B z s j x)) hm).elim
+ | some y =>
+ have hm := List.find?_some he
+ simp only [isMatch, List.all_eq_true, decide_eq_true_eq] at hm
+ rw [labelKey_injective B z s j fd fs (funext (fun i ↦ hm i (mem_labelFields i)))]
+
+/-- The name is taken from the matching row of the fixed matrix. -/
+noncomputable def rowName (x : HalfBits src dst (baseDemand B z) j)
+ (y : Half G (fun e ↦ Word (basePayload B s e)) j) : (parameterData B).Entry :=
+ let found := searchRow B z s j fd fs (x, y)
+ let r := found.get (by simp [found, searchRow_eq])
+ lookup B z s j r.1 r.2
+
+theorem rowName_eq (x : HalfBits src dst (baseDemand B z) j)
+ (y : Half G (fun e ↦ Word (basePayload B s e)) j) :
+ rowName B z s j fd fs x y = lookup B z s j x y := by
+ simp [rowName, searchRow_eq]
+
+variable [DecidableEq J]
+
+/-- Execute the scan with the fixed selector and local matrix tables of this
+block. The register width only has to contain the base digits used by the row tree. -/
+noncomputable def runBlock (hp : ∀ e, 0 < p e) (demand : D → ℕ) (v : E → ℕ)
+ (fd : ∀ e, baseDemand B (demandGrid B hp demand) e ≤ wordWidth)
+ (fs : ∀ t e, basePayload B t e ≤ wordWidth) (j : J)
+ (d : DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (supplyWidths B demand v e) → Bool) j) :
+ Option (List (parameterData B).Entry) :=
+ let z := demandGrid B hp demand
+ evaluate src dst (baseDemand B z) demand G (basePayload B)
+ (fun s j ↦ rowName B z s j fd (fs s)) (selectorTable B) (selectorCode B) v j d x
+
+theorem runBlock_eq_runEntry (hp : ∀ e, 0 < p e) (demand : D → ℕ) (v : E → ℕ)
+ (fd : ∀ e, baseDemand B (demandGrid B hp demand) e ≤ wordWidth)
+ (fs : ∀ t e, basePayload B t e ≤ wordWidth) (j : J)
+ (d : DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (supplyWidths B demand v e) → Bool) j) :
+ runBlock B hp demand v fd fs j d x = (runEntry B hp demand v j d x).1 := by
+ let z := demandGrid B hp demand
+ have he : (fun s j ↦ rowName B z s j fd (fs s)) = lookup B z :=
+ funext fun s ↦ funext fun j ↦ funext fun d ↦ funext fun x ↦ rowName_eq B z s j fd (fs s) d x
+ unfold runBlock runEntry
+ dsimp only
+ rw [he]
+ exact evaluate_eq_run ..
+
+end FixedBlock
+
+end PairSimulation.MapStream
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapTagBits.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapTagBits.lean
new file mode 100644
index 0000000000..1b680970f8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapTagBits.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.PairSimulationMapConsistency
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+
+/-!
+# Comparing selector suffixes in their original private bit fields
+
+The payload lengths at two incident ports can differ. Starting each cursor
+above its own payload, a private scan compares every bit in their selectors.
+This checks the same condition as comparing the decoded selector words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapConsistency
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord MotifEntry PrimedInputRAM
+open scoped Fin.CommRing
+
+private theorem readField_eq_iff {len len' : ℕ} (x : Fin len → Bool) (y : Fin len' → Bool)
+ (a b n : ℕ) :
+ readField x a n = readField y b n ↔
+ ∀ j : Fin n, paddedBit x (a + j.val) = paddedBit y (b + j.val) := by
+ have digit (l r : Bool) (p q : ℕ) :
+ l.toNat + 2*p = r.toNat + 2*q ↔ l = r ∧ p = q := by
+ cases l <;> cases r <;> simp <;> omega
+ induction n generalizing a b with
+ | zero => simp [readField]
+ | succ n ih =>
+ simp only [readField, digit, ih (a+1) (b+1), Fin.forall_fin_succ]
+ simp [Fin.val_succ, Nat.add_assoc, Nat.add_comm 1]
+
+/-- Flattening the copy and bit indices enumerates exactly the suffix above
+the payload. This equivalence also covers zero-bit tags and zero copies. -/
+theorem readTag_eq_iff_suffix {u bits v v' : ℕ}
+ (x : Fin (v + u * bits) → Bool) (y : Fin (v' + u * bits) → Bool) :
+ (∀ i : Fin u, readTag x i = readTag y i) ↔
+ ∀ j : Fin (u * bits), x (Fin.natAdd v j) = y (Fin.natAdd v' j) := by
+ have pos {a : ℕ} (z : Fin (a + u * bits) → Bool) (i : Fin u) (j : Fin bits) :
+ paddedBit z (a + bits*i.val + j.val) = z (Fin.natAdd a (finProdFinEquiv (i,j))) := by
+ have he : a + bits*i.val + j.val = (Fin.natAdd a (finProdFinEquiv (i,j))).val := by
+ change a + bits*i.val + j.val = a + (j.val + bits*i.val)
+ omega
+ rw [he]
+ simp only [paddedBit, dite_eq_left (Fin.natAdd a (finProdFinEquiv (i,j))).isLt]
+ have chunk (i : Fin u) : readTag x i = readTag y i ↔ ∀ j : Fin bits,
+ x (Fin.natAdd v (finProdFinEquiv (i,j))) = y (Fin.natAdd v' (finProdFinEquiv (i,j))) := by
+ rw [Fin.ext_iff]
+ change readField x _ _ = readField y _ _ ↔ _
+ rw [readField_eq_iff]
+ simp_rw [pos]
+ constructor
+ · intro h j
+ obtain ⟨⟨i,k⟩,rfl⟩ := finProdFinEquiv.surjective j
+ exact (chunk i).mp (h i) k
+ · intro h i
+ exact (chunk i).mpr fun j ↦ h (finProdFinEquiv (i,j))
+
+/-- The native loop starts at the two payload boundaries and compares the
+resident bits directly. It takes seven ticks per selector bit and one final
+test. Its mask can feed the next port's comparison. -/
+theorem compareResidentTags {w p r k u bits v v' : ℕ} {M : Machine w p r k}
+ {pc : Fin 7 → Fin p} {reg : Fin 7 ↪ Fin r} {done : Fin p}
+ (hl : Linked M pc reg done) (x : Fin (v + u * bits) → Bool) (y : Fin (v' + u * bits) → Bool)
+ (base base' : Word w) (c : Config w p r) (hc : c.pc = pc 0)
+ (hleft : c.reg (reg 0) = base + (v : Word w))
+ (hend : c.reg (reg 1) = base + ((v + u * bits : ℕ) : Word w))
+ (hright : c.reg (reg 2) = base' + (v' : Word w)) (h1 : c.reg (reg 3) = 1)
+ (hn : u * bits < 2 ^ w)
+ (hx : ∀ i : Fin (v + u * bits), c.privateMem (base + (i.val : Word w)) = encodeBit w (x i))
+ (hy : ∀ i : Fin (v' + u * bits), c.privateMem (base' + (i.val : Word w)) = encodeBit w (y i)) :
+ ∃ out, Prefix M c (List.replicate (7 * (u * bits) + 1) .tick) out ∧ out.pc = done ∧
+ (out.reg (reg 4) = 0 ↔ c.reg (reg 4) = 0 ∧ ∀ i : Fin u, readTag x i = readTag y i) ∧
+ Frame reg c out ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let left (j : Fin (u * bits)) := encodeBit w (x (Fin.natAdd v j))
+ let right (j : Fin (u * bits)) := encodeBit w (y (Fin.natAdd v' j))
+ obtain ⟨out, pre, hp, _, _, mask, frame, hm, hs⟩ :=
+ compareArrays hl left right _ _ c hc hleft (by simpa [add_assoc] using hend) hright h1 hn
+ (fun i ↦ by simpa [left, add_assoc] using hx (Fin.natAdd v i))
+ (fun i ↦ by simpa [right, add_assoc] using hy (Fin.natAdd v' i))
+ refine ⟨out, pre, hp, ?_, frame, hm, hs⟩
+ rw [mask, readTag_eq_iff_suffix]
+ refine and_congr_right fun _ ↦ ⟨?_, fun h i ↦ congrArg (encodeBit w) (h i)⟩
+ intro h i
+ have hw : 0 < w := by
+ by_contra! hzero
+ have hz : w = 0 := Nat.eq_zero_of_le_zero hzero
+ have hi := i.isLt
+ have hh : u * bits < 1 := by simpa only [hz, pow_zero] using hn
+ omega
+ apply Bool.eq_iff_iff.mpr
+ rw [← encodeBit_eq_one hw, ← encodeBit_eq_one hw, show
+ encodeBit w (x (Fin.natAdd v i)) = encodeBit w (y (Fin.natAdd v' i)) from h i]
+
+end PairSimulation.MapConsistency
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapTotalCheck.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapTotalCheck.lean
new file mode 100644
index 0000000000..47d302a793
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapTotalCheck.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.PairSimulationMapWidths
+import OAI.Computability.VPVNP.PrimedInputRAMFlowLinks
+import OAI.Computability.VPVNP.MotifPayload
+
+/-!
+# Checking the entire supply width vector in private RAM
+
+The fixed motif has one running total and one descriptor width for each
+supply edge, including edges at other parties. A fixed sequence of guards
+compares their resident word registers and branches to rejection on the
+first discrepancy.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapWidths
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM PrimedStackRAM
+
+variable {E : Type*} {w p r k : ℕ}
+
+/-- The constant final guard is also the empty-edge exit. -/
+def checkCode (lhs rhs : E → Fin r) (scratch : Fin r) : List E → Flow r k
+ | [] => .line (.guardEq scratch scratch)
+ | e :: es => (Flow.line (.guardEq (lhs e) (rhs e))).seq (checkCode lhs rhs scratch es)
+
+/-- Number of comparisons executed up to the first mismatch or the final guard. -/
+def checkSteps (eq : E → Bool) : List E → ℕ
+ | [] => 1
+ | e :: es => if eq e then 1 + checkSteps eq es else 1
+
+theorem checkSteps_le (eq : E → Bool) (es : List E) : checkSteps eq es ≤ es.length + 1 := by
+ induction es with
+ | nil => exact le_rfl
+ | cons e es ih =>
+ cases h : eq e <;> simp [checkSteps, h]
+ omega
+
+/-- The fixed guards consume no guesses, perform no probes and preserve
+all registers, private memory and the persistent word on both exits. -/
+theorem checkCode_native (lhs rhs : E → Fin r) (scratch : Fin r) (es : List E)
+ (M : Machine w p r k) (label : (checkCode lhs rhs scratch es : Flow r k).Label → Fin p)
+ (stop bad : Fin p) (link : Flow.Linked M (checkCode lhs rhs scratch es) label stop bad)
+ (c : Config w p r) (hpc : c.pc = label (checkCode lhs rhs scratch es : Flow r k).entry) :
+ let same := fun e ↦ decide (c.reg (lhs e) = c.reg (rhs e))
+ Prefix M c (List.replicate (checkSteps same es) .tick)
+ {c with pc := if es.all same then stop else bad} := by
+ dsimp only
+ induction es generalizing c with
+ | nil =>
+ have hs : M.program.step c = .localStep {c with pc := stop} := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hpc, link.atLabel]
+ change CallAction.localStep {c with pc := if c.reg scratch = c.reg scratch
+ then stop else bad} = _
+ simp
+ exact .tick hs (.nil _)
+ | cons e es ih =>
+ let tail := checkCode lhs rhs scratch es (k := k)
+ let enter := label (Sum.inr tail.entry)
+ by_cases he : c.reg (lhs e) = c.reg (rhs e)
+ · have hs : M.program.step c = .localStep {c with pc := enter} := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hpc, link.atLabel]
+ change CallAction.localStep {c with pc := if c.reg (lhs e) = c.reg (rhs e)
+ then enter else bad} = _
+ simp [he]
+ have rest := ih (label ∘ Sum.inr) link.seqRight {c with pc := enter} rfl
+ simp only [checkSteps, he, decide_true, ↓reduceIte, List.all_cons, Bool.true_and]
+ simpa only [Nat.add_comm 1, List.replicate_succ] using Prefix.tick hs rest
+ · have hs : M.program.step c = .localStep {c with pc := bad} := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, hpc, link.atLabel]
+ change CallAction.localStep {c with pc := if c.reg (lhs e) = c.reg (rhs e)
+ then enter else bad} = _
+ simp [he]
+ simpa only [checkSteps, he, decide_false, Bool.false_eq_true, ↓reduceIte, List.all_cons,
+ Bool.false_and, List.replicate_one] using Prefix.tick hs (.nil _)
+
+open scoped Classical in
+/-- Compare the full totals produced by an actual inner selector list with the
+descriptor widths, even for a malformed descriptor. All tested natural values
+must fit the word; all other cells and registers can be arbitrary. -/
+theorem totalCheck_native {Q : Type*} {u : ℕ} (width : Q → E → ℕ) (θ : Fin u → Q)
+ (v : E → ℕ) (es : List E) (cover : ∀ e, e ∈ es)
+ (lhs rhs : E → Fin r) (scratch : Fin r) (M : Machine w p r k)
+ (label : (checkCode lhs rhs scratch es : Flow r k).Label → Fin p)
+ (stop bad : Fin p) (link : Flow.Linked M (checkCode lhs rhs scratch es) label stop bad)
+ (c : Config w p r) (hpc : c.pc = label (checkCode lhs rhs scratch es : Flow r k).entry)
+ (hx : ∀ e, (c.reg (lhs e)).val = MotifSelector.totalWidth width θ e)
+ (hy : ∀ e, (c.reg (rhs e)).val = v e) :
+ ∃ steps ≤ es.length + 1, Prefix M c (List.replicate steps .tick)
+ {c with pc := if ∀ e, v e = MotifSelector.totalWidth width θ e then stop else bad} := by
+ classical
+ let same := fun e ↦ decide (c.reg (lhs e) = c.reg (rhs e))
+ have hsame : es.all same = true ↔ ∀ e, v e = MotifSelector.totalWidth width θ e := by
+ simp only [List.all_eq_true, same, decide_eq_true_eq]
+ constructor
+ · intro h e
+ exact (hy e).symm.trans ((congrArg Fin.val (h e (cover e))).symm.trans (hx e))
+ · intro h e _
+ exact Fin.ext ((hx e).trans ((h e).symm.trans (hy e).symm))
+ refine ⟨checkSteps same es, checkSteps_le .., ?_⟩
+ have run := checkCode_native lhs rhs scratch es M label stop bad link c hpc
+ change Prefix M c (List.replicate (checkSteps same es) .tick)
+ {c with pc := if es.all same then stop else bad} at run
+ simpa only [hsame] using run
+
+end PairSimulation.MapWidths
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapWidths.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapWidths.lean
new file mode 100644
index 0000000000..537fc143e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapWidths.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.MotifEntry
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Native width sums for the inner selector sequence
+
+After a selector is decoded, its width on each supply edge is a fixed table
+entry. A private RAM scan over one edge's width cells gives either the field
+offset before a copy or the full total checked against the term descriptor.
+The scan preserves memory and has a fixed linear instruction count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapWidths
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+
+private theorem val_word {n : ℕ} (h : n < 2 ^ w) : (word w n).val = n := Nat.mod_eq_of_lt h
+
+/-- Registers hold cursor, exclusive end, running sum, the constant one and a
+temporary width. Each successful iteration consists of four private instructions. -/
+def instruction (pc : Fin 4 → Fin p) (reg : Fin 5 ↪ Fin r) (done : Fin p) :
+ Fin 4 → Instr w p r k :=
+ ![.jumpEq (reg 0) (reg 1) done (pc 1), .loadPrivate (reg 4) (reg 0) (pc 2),
+ .binary .add (reg 2) (reg 2) (reg 4) (pc 3), .binary .add (reg 0) (reg 0) (reg 3) (pc 0)]
+
+theorem resize_instruction (pc : Fin 4 → Fin p) (reg : Fin 5 ↪ Fin r) (done : Fin p) (i : Fin 4) :
+ (instruction (w := 1) (k := k) pc reg done i).resize w = instruction pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- The machine stores the four width-scan instructions at the addresses given by `pc`. -/
+def Linked (M : Machine w p r k) (pc : Fin 4 → Fin p) (reg : Fin 5 ↪ Fin r) (done : Fin p) :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+variable {M : Machine w p r k} {pc : Fin 4 → Fin p} {reg : Fin 5 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (hl : Linked M pc reg done) (i : Fin 4) {c : Config w p r}
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+private theorem body (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (hne : c.reg (reg 0) ≠ c.reg (reg 1)) (src x : ℕ) (hs : c.reg (reg 0) = word w src)
+ (hx : c.privateMem (word w src) = word w x) (h1 : c.reg (reg 3) = 1) :
+ ∃ out, Prefix M c (List.replicate 4 .tick) out ∧ out.pc = pc 0 ∧
+ out.reg (reg 0) = word w (src + 1) ∧ out.reg (reg 2) = c.reg (reg 2) + word w x ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let c₁ := {c with pc := pc 1}
+ let c₂ := c₁.put (pc 2) (reg 4) (word w x)
+ let c₃ := c₂.put (pc 3) (reg 2) (c.reg (reg 2) + word w x)
+ let out := c₃.put (pc 0) (reg 0) (word w (src + 1))
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step_at hl 0 hc]
+ simp [instruction, Instr.run, hne, c₁]
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at hl 1 rfl]
+ change CallAction.localStep (c₁.put (pc 2) (reg 4) (c.privateMem (c.reg (reg 0)))) = _
+ rw [hs, hx]
+ have s₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step_at hl 2 rfl]
+ change CallAction.localStep (c₂.put (pc 3) (reg 2) (c₂.reg (reg 2) + c₂.reg (reg 4))) = _
+ simp [c₃, c₂, c₁, Config.put]
+ have s₃ : M.program.step c₃ = .localStep out := by
+ rw [step_at hl 3 rfl]
+ change CallAction.localStep (c₃.put (pc 0) (reg 0) (c₃.reg (reg 0) + c₃.reg (reg 3))) = _
+ simp [out, c₃, c₂, c₁, Config.put, hs, h1, word]
+ refine ⟨out, .tick s₀ (.tick s₁ (.tick s₂ (.tick s₃ (.nil _)))), rfl, by simp [out],
+ by simp [out, c₃, Config.put], ?_, rfl, rfl⟩
+ intro j h₀ h₂ h₄
+ simp [out, c₃, c₂, c₁, Config.put, Function.update_of_ne, h₀, h₂, h₄]
+
+/-- The loop scans the given resident widths, including an empty prefix.
+Its register result is the machine-word sum and its instruction count is
+independent of all widths and all other memory cells. -/
+theorem accumulate (hl : Linked M pc reg done) {n : ℕ} (x : Fin n → ℕ) (src : ℕ)
+ (c : Config w p r) (hc : c.pc = pc 0) (hsrc : c.reg (reg 0) = word w src)
+ (hend : c.reg (reg 1) = word w (src + n)) (hfit : src + n < 2 ^ w)
+ (h1 : c.reg (reg 3) = 1)
+ (mem : ∀ j : Fin n, c.privateMem (word w (src + j.val)) = word w (x j)) :
+ ∃ out, Prefix M c (List.replicate (4 * n + 1) .tick) out ∧ out.pc = done ∧
+ out.reg (reg 2) = c.reg (reg 2) + word w (∑ j, x j) ∧
+ out.reg (reg 0) = word w (src + n) ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ induction n generalizing src c with
+ | zero =>
+ have he : c.reg (reg 0) = c.reg (reg 1) := hsrc.trans (by simpa using hend.symm)
+ have hs : M.program.step c = .localStep {c with pc := done} := by
+ rw [step_at hl 0 hc]
+ simp [instruction, Instr.run, he]
+ exact ⟨_, .tick hs (.nil _), rfl, by simp [word], hsrc, fun _ _ _ _ ↦ rfl, rfl, rfl⟩
+ | succ n ih =>
+ have ne : c.reg (reg 0) ≠ c.reg (reg 1) := by
+ rw [hsrc, hend]
+ intro he
+ have h := congrArg Fin.val he
+ rw [val_word (by omega : src < 2 ^ w), val_word hfit] at h
+ omega
+ obtain ⟨mid, pre, hpc, hcur, hacc, other, hmem, hp⟩ :=
+ body hl c hc ne src (x 0) hsrc (by simpa using mem 0) h1
+ have endEq : src + 1 + n = src + (n + 1) := by omega
+ obtain ⟨out, tail, ho, ha, hcur', other', hm', hp'⟩ :=
+ ih (fun j ↦ x j.succ) (src + 1) mid hpc hcur
+ (by rw [endEq, other, hend] <;> simp) (endEq ▸ hfit)
+ (by rw [other, h1] <;> simp) (fun j ↦ by
+ rw [hmem, show src + 1 + j.val = src + j.succ.val by simp [Fin.val_succ]; omega]
+ exact mem j.succ)
+ refine ⟨out, ?_, ho, ?_, endEq ▸ hcur', fun j h₀ h₂ h₄ ↦
+ (other' j h₀ h₂ h₄).trans (other j h₀ h₂ h₄), hm'.trans hmem, hp'.trans hp⟩
+ · convert pre.append tail using 1
+ rw [← List.replicate_add]
+ congr 1
+ omega
+ · rw [ha, hacc, Fin.sum_univ_succ]
+ simp [word, add_assoc]
+
+/-- A zeroed accumulator returns the natural prefix total when it fits the
+word. This is the offset or total computed by the abstract motif interpreter. -/
+theorem widthPrefix_native (hl : Linked M pc reg done) {n : ℕ} (x : Fin n → ℕ) (src : ℕ)
+ (c : Config w p r) (hc : c.pc = pc 0) (hsrc : c.reg (reg 0) = word w src)
+ (hend : c.reg (reg 1) = word w (src + n)) (hfit : src + n < 2 ^ w)
+ (hzero : c.reg (reg 2) = 0) (h1 : c.reg (reg 3) = 1) (htotal : (∑ j, x j) < 2 ^ w)
+ (mem : ∀ j : Fin n, c.privateMem (word w (src + j.val)) = word w (x j)) :
+ ∃ out, Prefix M c (List.replicate (4 * n + 1) .tick) out ∧ out.pc = done ∧
+ (out.reg (reg 2)).val = (MotifEntry.widthPrefix x).1 ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ obtain ⟨out, pre, ho, ha, _, _, hm, hp⟩ := accumulate hl x src c hc hsrc hend hfit h1 mem
+ refine ⟨out, pre, ho, ?_, hm, hp⟩
+ rw [ha, hzero, zero_add, val_word htotal, MotifEntry.widthPrefix_spec]
+
+end PairSimulation.MapWidths
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapWordBounds.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapWordBounds.lean
new file mode 100644
index 0000000000..389a262e0f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapWordBounds.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.PairSimulationMapStream
+import OAI.Computability.VPVNP.CompressorRecordsCursorCapacity
+
+/-!
+# Word capacity for the motif's private field reads
+
+On any decoded selector sequence, all its running payload offsets are
+bounded by its length times the largest width in the fixed table. This bound
+also covers sequences whose totals disagree with the descriptor. Demand
+padding and selector offsets likewise remain addressable on the live RAM.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapStream
+
+open CursorBounds BurstRAM Filter MotifBlocks MotifConversion MotifSelector MotifGrid
+
+variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S]
+variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ}
+variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H')
+
+/-- All fixed table words fit, and every field-read start and end below the
+indicated private workspace prefix fit without modular wraparound. Each
+incident payload limit may be an arbitrary word width up to the branch cap. -/
+theorem eventually_polynomial_field_addresses (bexp : ℕ) (hb : 1 ≤ bexp)
+ (bound : ℕ → ℕ) (hbound : PolynomiallyBounded bound) :
+ ∀ᶠ n : ℕ in atTop,
+ let w := CursorBounds.wordBits bexp n
+ B.selectorBits ≤ w ∧ (∀ z e, baseDemand B z e ≤ w) ∧ (∀ s e, basePayload B s e ≤ w) ∧
+ ∀ u ≤ n, ∀ z (θ : Fin u → Selector B) (i : Fin u) (base : ℕ), base ≤ bound n →
+ (∀ e, base + baseDemand B z e * i.val + baseDemand B z e < 2 ^ w) ∧
+ (∀ e, base + MotifEntry.offset (fun l ↦ basePayload B (θ l) e) i +
+ basePayload B (θ i) e < 2 ^ w) ∧
+ (∀ e, totalWidth (basePayload B) θ e < 2 ^ w) ∧
+ ∀ v ≤ n, base + v + B.selectorBits * i.val + B.selectorBits < 2 ^ w := by
+ let A := ∑ z : B.grid.demands, ∑ e, baseDemand B z e
+ let W := ∑ s : Selector B, ∑ e, basePayload B s e
+ let C := max B.selectorBits (max A W)
+ have hsel : B.selectorBits ≤ C := le_max_left ..
+ have hd (z) (e) : baseDemand B z e ≤ C :=
+ ((Finset.single_le_sum (fun j _ ↦ Nat.zero_le (baseDemand B z j)) (Finset.mem_univ e)).trans
+ (Finset.single_le_sum (fun z _ ↦ Nat.zero_le (∑ j, baseDemand B z j))
+ (Finset.mem_univ z))).trans ((le_max_left A W).trans (le_max_right ..))
+ have hs (s) (e) : basePayload B s e ≤ C :=
+ ((Finset.single_le_sum (fun j _ ↦ Nat.zero_le (basePayload B s j)) (Finset.mem_univ e)).trans
+ (Finset.single_le_sum (fun s _ ↦ Nat.zero_le (∑ j, basePayload B s j))
+ (Finset.mem_univ s))).trans ((le_max_right A W).trans (le_max_right ..))
+ have room := CompressorRecords.CursorRAM.eventual_word_room bexp hb
+ ((hbound.add PolynomiallyBounded.id).add
+ (PolynomiallyBounded.id.mul (PolynomiallyBounded.const C)))
+ filter_upwards [room, eventually_ge_atTop (2 ^ C)] with n hmod hn
+ let w := CursorBounds.wordBits bexp n
+ have hlog : C ≤ n.log2 :=
+ (Nat.le_log2 (by have := Nat.two_pow_pos C; omega : n ≠ 0)).mpr hn
+ have hc : C ≤ w :=
+ (hlog.trans (log2_le_addressWidth hb n)).trans
+ ((Nat.le_add_right (addressWidth bexp n) 10).trans (Nat.le_self_pow (by decide : 4 ≠ 0) _))
+ refine ⟨hsel.trans hc, fun z e ↦ (hd z e).trans hc, fun s e ↦ (hs s e).trans hc, ?_⟩
+ intro u hu z θ i base hbase
+ change bound n + n + n * C < 2 ^ w at hmod
+ dsimp only [w] at hmod
+ have hi : i.val + 1 ≤ n := i.isLt.trans_le hu
+ have hcend (v : ℕ) (hv : v ≤ C) :
+ v * i.val + v ≤ n * C := by
+ rw [← Nat.mul_succ, Nat.mul_comm]
+ exact Nat.mul_le_mul hi hv
+ refine ⟨fun e ↦ ?_, fun e ↦ ?_, fun e ↦ ?_, fun v hv ↦ ?_⟩
+ · have := hcend _ (hd z e)
+ omega
+ · have h := offset_le (basePayload B) hs θ e i
+ have he : i.val * C + C ≤ n * C := by rw [← Nat.succ_mul]; exact Nat.mul_le_mul_right C hi
+ have := hs (θ i) e
+ omega
+ · have h := (totalWidth_le (basePayload B) hs θ e).trans (Nat.mul_le_mul_right C hu)
+ omega
+ · have := hcend _ hsel
+ omega
+
+/-- Specialize the address bound to a packed local field workspace. -/
+theorem eventually_field_addresses (bexp : ℕ) (hb : 1 ≤ bexp) :
+ ∀ᶠ n : ℕ in atTop,
+ let w := CursorBounds.wordBits bexp n
+ B.selectorBits ≤ w ∧ (∀ z e, baseDemand B z e ≤ w) ∧ (∀ s e, basePayload B s e ≤ w) ∧
+ ∀ u ≤ n, ∀ z (θ : Fin u → Selector B) (i : Fin u) (base : ℕ), base ≤ n ^ 5 →
+ (∀ e, base + baseDemand B z e * i.val + baseDemand B z e < 2 ^ w) ∧
+ (∀ e, base + MotifEntry.offset (fun l ↦ basePayload B (θ l) e) i +
+ basePayload B (θ i) e < 2 ^ w) ∧
+ (∀ e, totalWidth (basePayload B) θ e < 2 ^ w) ∧
+ ∀ v ≤ n, base + v + B.selectorBits * i.val + B.selectorBits < 2 ^ w :=
+ eventually_polynomial_field_addresses B bexp hb (fun n ↦ n ^ 5) (PolynomiallyBounded.id.pow 5)
+
+end PairSimulation.MapStream
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapWorkspace.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapWorkspace.lean
new file mode 100644
index 0000000000..344b8fc23f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapWorkspace.lean
@@ -0,0 +1,290 @@
+import OAI.Computability.VPVNP.PairSimulationMapCallSetup
+import OAI.Computability.VPVNP.PairSimulationNodeFieldSpace
+
+/-!
+# Physical workspace of a selected map call
+
+The live-word capacity estimates of Section 13 apply to every payload offset
+of every selector sequence, including sequences ultimately rejected by the
+width guards. Given the physical slice positions and separated scratch blocks,
+these estimates construct the workspace consumed by the executable map.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapWorkspace
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry MapLookup MapPortAgreement
+open MapResidentAgreement MapEntryTable NodeArguments
+open CursorBounds Filter
+open scoped Fin.CommRing
+
+variable {J D E K : Type} [Fintype J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H')
+ {w n u t p r k : ℕ}
+
+/-- Capacity available throughout the numerically bounded workspace of one selected node. -/
+structure Capacity (w n limit : ℕ) : Prop where
+ selectorBits : B.selectorBits ≤ w
+ demandBits : ∀ z e, baseDemand B z e ≤ w
+ payloadBits : ∀ s e, basePayload B s e ≤ w
+ room : limit < 2 ^ w
+ fields : ∀ a ≤ limit, ReadEndsFit B w n a
+
+variable [DecidableEq J] {B} {z : B.grid.demands} {j : J}
+ (P : MapEntry.Program B z j p r k)
+ (demand : D → ℕ) (v : E → ℕ)
+
+/-- Natural addresses of the operand slices and scratch blocks. The histogram may be
+shared across successive calls. -/
+structure Regions (D E : Type) where
+ /-- Natural start address of each demand or supply endpoint's raw bit slice in private
+ memory. -/
+ base : LabelField D E → ℕ
+ /-- Natural base address of the incident-port directory that stores pointers to the supply
+ selector suffixes. -/
+ directory : ℕ
+ /-- Natural start address of the private array of decoded selector ordinals, one per copy. -/
+ source : ℕ
+ /-- Natural start address of the private array of parameter labels returned by the selected
+ rows. -/
+ target : ℕ
+ /-- Natural base address of the parameter histogram whose counters may be shared across map
+ calls. -/
+ hist : ℕ
+
+variable (R : Regions D E)
+
+/-- Actual raw half-wire width, including all selector suffix bits on supply. -/
+def rawWidth (selectorBits u : ℕ) : LabelField D E → ℕ
+ | .inl (_, e) => demand e
+ | .inr (_, e) => v e + u * selectorBits
+
+/-- All physical ranges fit in a common prefix. The source and target sides
+may use the same addresses wherever their values agree. -/
+structure Ordered (u t limit : ℕ) : Prop where
+ inputEnd : ∀ f, R.base f + rawWidth demand v B.selectorBits u f ≤ R.directory
+ directoryEnd : R.directory + (ports G j P.edgeOrder).length ≤ R.source
+ selectorEnd : R.source + u ≤ R.target
+ labelEnd : R.target + u ≤ limit
+ histogramEnd : R.hist + t ≤ limit
+ histApart : R.target + u ≤ R.hist ∨ R.hist + t ≤ R.directory
+
+variable {demand v} (d : DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j)
+
+private theorem len_le (θ : Fin u → Selector B) (f : LabelField D E) :
+ (MapRowLoop.buffers B z j demand v d x R.base θ 0).len f ≤
+ rawWidth demand v B.selectorBits u f := by
+ rcases f with ⟨b, e⟩ | ⟨b, e⟩
+ · cases b
+ · by_cases h : j = src e <;> simp [MapRowLoop.buffers, MapRow.endpoint, rawWidth, h]
+ · by_cases h : j = dst e <;> simp [MapRowLoop.buffers, MapRow.endpoint, rawWidth, h]
+ · cases b
+ · by_cases h : j = G.src e <;> simp [MapRowLoop.buffers, MapRow.endpoint, rawWidth, h]
+ · by_cases h : j = G.dst e <;> simp [MapRowLoop.buffers, MapRow.endpoint, rawWidth, h]
+
+/-- Construct the full native workspace using a bound on copy count and the physical
+address inequalities. All selector-dependent obligations follow from capacity. -/
+noncomputable def workspace {limit : ℕ} (C : Capacity B w n limit) (hu : u ≤ n)
+ (h : Ordered P demand v R u t limit) :
+ MapEntry.Program.Workspace P demand v d x t w := by
+ have hds : R.directory ≤ R.source := (Nat.le_add_right ..).trans h.directoryEnd
+ have hst : R.source ≤ R.target := (Nat.le_add_right ..).trans h.selectorEnd
+ have htl : R.target ≤ limit := (Nat.le_add_right ..).trans h.labelEnd
+ have hdl := hds.trans (hst.trans htl)
+ have hbase f : R.base f ≤ limit :=
+ (Nat.le_add_right ..).trans ((h.inputEnd f).trans hdl)
+ let pb (a : Port G j) := R.base (MapDirectoryInit.portField a)
+ have pend (a : Port G j) : pb a + (v (edge a) + u * B.selectorBits) ≤ R.directory := by
+ cases a with
+ | inl e => exact h.inputEnd (.inr (false, e.val))
+ | inr e => exact h.inputEnd (.inr (true, e.val))
+ have pval (a : Port G j) : (pb a : BurstRAM.Word w).val = pb a :=
+ Nat.mod_eq_of_lt ((hbase _).trans_lt C.room)
+ let a := anchorPort G j
+ refine ⟨fun q ↦ (pb q : BurstRAM.Word w), (R.directory : BurstRAM.Word w), R.base,
+ R.source, R.target, R.hist, ?_, ?_, ?_, ?_, ?_, ?_, h.histogramEnd.trans C.room.le,
+ h.selectorEnd, ?_, ?_, ?_, ?_, ?_⟩
+ · exact ((Nat.le_add_left ..).trans h.directoryEnd).trans_lt
+ ((hst.trans htl).trans_lt C.room)
+ · exact ((Nat.le_add_left ..).trans ((Nat.le_add_left ..).trans (pend a))).trans_lt
+ (hdl.trans_lt C.room)
+ · rw [pval]
+ exact (pend a).trans_lt (hdl.trans_lt C.room)
+ · rw [pval]
+ exact Or.inl ((pend a).trans hds)
+ · exact h.selectorEnd.trans_lt (htl.trans_lt C.room)
+ · exact h.labelEnd.trans_lt C.room
+ · exact h.histApart.imp (fun e ↦ h.selectorEnd.trans ((Nat.le_add_right ..).trans e))
+ (fun e ↦ e.trans hds)
+ · exact h.histApart.imp id (fun e ↦ e.trans (hds.trans hst))
+ · intro θ f l
+ have lt := Nat.add_lt_add_left (l.isLt.trans_le (len_le (z := z) R d x θ f)) (R.base f)
+ have hend := lt.trans_le (h.inputEnd f)
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt (hend.trans (hdl.trans_lt C.room))]
+ exact hend.trans_le hds
+ · intro θ i
+ constructor
+ · intro g
+ cases g with
+ | inl e => exact C.demandBits z e
+ | inr e => exact C.payloadBits (θ i) e
+ · intro f
+ have reads := C.fields (R.base f) (hbase f) u hu z θ i
+ rcases f with ⟨b, e⟩ | ⟨b, e⟩
+ · exact reads.1 e
+ · simpa only [MapRowLoop.buffers, MapRow.group, Sum.elim_inr,
+ MapRowLoop.prefix_eq_offset] using reads.2.1 e
+ · intro f
+ have endLe := Nat.add_le_add_left (len_le (z := z) R d x θ f) (R.base f)
+ exact (endLe.trans (h.inputEnd f)).trans_lt (hdl.trans_lt C.room)
+ · intro θ e
+ cases u with
+ | zero => simp [totalWidth]
+ | succ k =>
+ exact (C.fields (R.base (MapDirectoryInit.portField a)) (hbase _) _ hu z θ 0).2.2.1 e
+
+private theorem word_ne {a b w : ℕ} (h : a < b) (hb : b < 2 ^ w) :
+ (a : BurstRAM.Word w) ≠ (b : BurstRAM.Word w) := by
+ intro he
+ have eq := congrArg Fin.val he
+ change a % (2 ^ w) = b % (2 ^ w) at eq
+ rw [Nat.mod_eq_of_lt (h.trans hb), Nat.mod_eq_of_lt hb] at eq
+ omega
+
+omit [Fintype J] [Fintype D] in
+private theorem demand_len (q : Bool × D) :
+ (MapRow.endpoint src dst j demand d q).1 ≤ demand q.2 := by
+ rcases q with ⟨b, e⟩
+ cases b
+ · by_cases h : j = src e <;> simp [MapRow.endpoint, h]
+ · by_cases h : j = dst e <;> simp [MapRow.endpoint, h]
+
+omit [DecidableEq J] in
+private theorem port_raw (q : Port G j) :
+ rawWidth demand v B.selectorBits u (MapDirectoryInit.portField q) =
+ v (edge q) + u * B.selectorBits := by
+ cases q <;> rfl
+
+/-- The histogram may be below the directory or above the label staging. Either
+physical ordering prevents setup stores from changing any histogram counter. -/
+theorem histogram_apart {limit : ℕ} (C : Capacity B w n limit)
+ (h : Ordered P demand v R u t limit) (l : Fin t) (i : Fin (ports G j P.edgeOrder).length) :
+ ((R.hist + l.val : ℕ) : BurstRAM.Word w) ≠
+ (R.directory : BurstRAM.Word w) + (i.val : BurstRAM.Word w) := by
+ rw [← Nat.cast_add]
+ have di := (Nat.add_lt_add_left i.isLt R.directory).trans_le h.directoryEnd
+ have tl := (Nat.add_lt_add_left l.isLt R.hist).trans_le h.histogramEnd
+ rcases h.histApart with before | after
+ · apply Ne.symm
+ exact word_ne (di.trans_le (by have := h.selectorEnd; omega)) (tl.trans C.room)
+ · apply word_ne
+ · have ht := Nat.add_lt_add_left l.isLt R.hist
+ omega
+ · exact (di.trans_le (by have := h.selectorEnd; have := h.labelEnd; omega)).trans C.room
+
+/-- A raw descriptor and the actual stored half-wire bits suffice to build the
+initializer's input. The physical ordering proves all directory disjointness tests. -/
+theorem input {limit : ℕ} (A : Allocation B z j r k) (loc : A.Address → Fin p)
+ (args : MapCallSetup.Arg D E ≃ Fin (Fintype.card (MapCallSetup.Arg D E)))
+ (C : Capacity B w n limit) (hu : u ≤ n) (h : Ordered (A.program loc) demand v R u t limit)
+ (ptr : Fin r) (c : BurstRAM.PrivateRAM.Config w p r) :
+ let X := workspace (A.program loc) R d x C hu h
+ (∀ a, c.privateMem (c.reg ptr + ((args a).val : BurstRAM.Word w)) =
+ MapCallSetup.values A loc X a) →
+ (∀ (q : Port G j) (l : Fin (v (edge q) + u * B.selectorBits)),
+ c.privateMem ((R.base (MapDirectoryInit.portField q) + l.val : ℕ) : BurstRAM.Word w) =
+ PrimedInputRAM.encodeBit w (field x q l)) →
+ (∀ (q : Bool × D) (l : Fin (MapRow.endpoint src dst j demand d q).1),
+ c.privateMem ((R.base (.inl q) + l.val : ℕ) : BurstRAM.Word w) =
+ PrimedInputRAM.encodeBit w ((MapRow.endpoint src dst j demand d q).2 l)) →
+ MapCallSetup.Input A args loc X ptr c := by
+ intro X descriptor supply dem
+ have dlim : R.directory ≤ limit := by
+ have := h.directoryEnd; have := h.selectorEnd; have := h.labelEnd; omega
+ have di (i : MapDirectoryInit.Row A) : R.directory + i.val < 2 ^ w := by
+ have hi := i.isLt
+ have de := h.directoryEnd
+ change R.directory + (ports G j A.edgeOrder).length ≤ R.source at de
+ exact (show R.directory + i.val < limit by
+ have := h.selectorEnd; have := h.labelEnd; omega).trans C.room
+ refine ⟨descriptor, ?_, fun _ ↦ rfl, ?_, dem, ?_, ?_⟩
+ · intro e
+ have eh := h.inputEnd (.inr (false, e))
+ change R.base (.inr (false, e)) + (v e + u * B.selectorBits) ≤ R.directory at eh
+ exact (show v e ≤ limit by omega).trans_lt C.room
+ · intro q l
+ change c.privateMem ((R.base (MapDirectoryInit.portField q) : BurstRAM.Word w) + _) = _
+ simpa only [Nat.cast_add] using supply q l
+ · intro q l i
+ have endLe := h.inputEnd (MapDirectoryInit.portField q)
+ rw [port_raw] at endLe
+ have hi := (Nat.add_lt_add_left l.isLt (R.base (MapDirectoryInit.portField q))).trans_le endLe
+ change (R.base (MapDirectoryInit.portField q) : BurstRAM.Word w) + _ ≠
+ (R.directory : BurstRAM.Word w) + _
+ rw [← Nat.cast_add, ← Nat.cast_add]
+ exact word_ne (hi.trans_le (Nat.le_add_right ..)) (di i)
+ · intro q l i
+ have eh := h.inputEnd (.inl q)
+ change R.base (.inl q) + demand q.2 ≤ R.directory at eh
+ have hi := (Nat.add_lt_add_left (l.isLt.trans_le (demand_len d q)) _).trans_le eh
+ change ((R.base (.inl q) + l.val : ℕ) : BurstRAM.Word w) ≠ (R.directory : BurstRAM.Word w) + _
+ rw [← Nat.cast_add]
+ exact word_ne (hi.trans_le (Nat.le_add_right ..)) (di i)
+
+section Selected
+
+open CursorNetwork Compression CompressorRecords TraversalRows
+
+variable {S : BlockSchedule K}
+
+omit [DecidableEq J] in
+/-- Every node in every selected descriptor branch has the map capacity required above.
+The threshold is chosen before the branch, its coefficient specialization, and the node. -/
+theorem eventually_selected_capacity (F : DescriptorSpace.Shape) (T : S.Templates)
+ (u₀ : PairExponents T.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {start first extra : ℕ → ℕ} (hs : PolynomiallyBounded start)
+ (hf : PolynomiallyBounded first) (he : PolynomiallyBounded extra) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u₀.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R₀ : Type*) [CommRing R₀] (f : T.Entry → R₀) (hsol : T.IsSolution f),
+ let X := pairInput S labels hD
+ let count := blockCount (u₀.θ : ℝ) n
+ let exec := T.execute f hsol count hT X
+ let layout := DescriptorSpace.cursorLayout F b S.steps u₀.θ (start n) n
+ let arena : Arena := ⟨first n, frameStride (slotDegree S) n⟩
+ ∀ choice : exec.Choices, ∀ v node,
+ node ∈ (selectedTrees T f hsol count hT X choice
+ (DescriptorSpace.endAddress layout) v).preorder →
+ Capacity B (wordBits b n) n (arena.base node + arena.stride + extra n) := by
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ filter_upwards [eventually_selected_node_fields B F T u₀ b hb hs hf he,
+ MapStream.eventually_polynomial_field_addresses B b hb' (fun _ ↦ 0)
+ (PolynomiallyBounded.const 0)] with n selected widths
+ intro base lanes labels hD hT R₀ _ f hsol X count exec layout arena choice v node member
+ have room := selected labels hD hT R₀ f hsol choice v node member
+ exact ⟨widths.1, widths.2.1, widths.2.2.1, room.1, room.2.1⟩
+
+omit [DecidableEq J] in
+/-- A polynomial upper limit on the shared scratch region also supports every field
+read in the whole prefix. This covers operands materialized above the node's own frame. -/
+theorem eventually_capacity (b : ℕ) (hb : 1 ≤ b) (limit : ℕ → ℕ)
+ (hl : PolynomiallyBounded limit) :
+ ∀ᶠ n : ℕ in atTop, Capacity B (wordBits b n) n (limit n) := by
+ filter_upwards [MapStream.eventually_polynomial_field_addresses B b hb limit hl,
+ CursorRAM.eventual_word_room b hb hl] with n widths room
+ exact ⟨widths.1, widths.2.1, widths.2.2.1, room, fun addr ha u hu z θ i ↦
+ widths.2.2.2 u hu z θ i addr ha⟩
+
+end Selected
+
+end PairSimulation.MapWorkspace
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapWorkspaceLayout.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapWorkspaceLayout.lean
new file mode 100644
index 0000000000..b382505058
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapWorkspaceLayout.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.PairSimulationMapWorkspace
+
+/-!
+# Consecutive scratch regions for a native map call
+
+The live histogram and operand fields may be at different addresses from one
+call to the next. Above their exclusive ends the caller reserves space for
+the port directory, the fixed argument descriptor, the selector ordinals, and
+the output labels. The two copy arrays have the same capacity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapWorkspace
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MapLookup MapPortAgreement
+open CursorBounds Filter
+
+variable {D E : Type} [Fintype D] [Fintype E]
+
+/-- Reserve the two possible ends of each supply edge before the argument descriptor. -/
+def descriptorBase (E : Type) [Fintype E] (directory : ℕ) : ℕ :=
+ directory + 2 * Fintype.card E
+
+/-- The selector ordinals start immediately after the fixed descriptor. -/
+def ordinalBase (D E : Type) [Fintype D] [Fintype E] (directory : ℕ) : ℕ :=
+ descriptorBase E directory + Fintype.card (MapCallSetup.Arg D E)
+
+/-- The label array follows the reserved selector-ordinal array. -/
+def scratchRegions (fieldBase : LabelField D E → ℕ) (directory hist copies : ℕ) :
+ Regions D E where
+ base := fieldBase
+ directory := directory
+ source := ordinalBase D E directory
+ target := ordinalBase D E directory + copies
+ hist := hist
+
+/-- Exclusive end of the label array, including its unused reserved capacity. -/
+def scratchEnd (D E : Type) [Fintype D] [Fintype E] (directory copies : ℕ) : ℕ :=
+ ordinalBase D E directory + copies + copies
+
+variable {J K : Type} [Fintype J] [DecidableEq J] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {p r k w n u t copies hist directory limit : ℕ}
+ (P : MapEntry.Program B z j p r k) (demand : D → ℕ) (v : E → ℕ)
+ (fieldBase : LabelField D E → ℕ)
+
+/-- The descriptor has a distinct address for each argument, strictly before
+the first scratch ordinal. -/
+theorem descriptorWord_lt (D E : Type) [Fintype D] [Fintype E] (directory : ℕ)
+ (a : Fin (Fintype.card (MapCallSetup.Arg D E))) :
+ descriptorBase E directory + a.val < ordinalBase D E directory :=
+ Nat.add_lt_add_left a.isLt _
+
+/-- All writable map arrays are separated for any supplied operand bases whose
+ends and the live histogram precede the directory. -/
+theorem scratchRegions_ordered
+ (fields : ∀ f, fieldBase f + rawWidth demand v B.selectorBits u f ≤ directory)
+ (histEnd : hist + t ≤ directory) (hc : u ≤ copies)
+ (room : scratchEnd D E directory copies ≤ limit) :
+ Ordered P demand v (scratchRegions fieldBase directory hist copies) u t limit := by
+ have hports := ports_length_le G j P.edgeOrder
+ dsimp only [scratchEnd, ordinalBase, descriptorBase] at room
+ constructor <;> dsimp only [scratchRegions, ordinalBase, descriptorBase]
+ · exact fields
+ · omega
+ · omega
+ · omega
+ · omega
+ · exact Or.inr histEnd
+
+variable (d : MotifEntry.DemandBits src dst demand j)
+ (x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j)
+
+/-- The natural layout supplies the workspace of the actual native map program,
+including all selector-dependent reads on unsuccessful choices. -/
+noncomputable def scratchWorkspace (C : Capacity B w n limit) (hu : u ≤ n)
+ (fields : ∀ f, fieldBase f + rawWidth demand v B.selectorBits u f ≤ directory)
+ (histEnd : hist + t ≤ directory) (hc : u ≤ copies)
+ (room : scratchEnd D E directory copies ≤ limit) :
+ MapEntry.Program.Workspace P demand v d x t w :=
+ workspace P (scratchRegions fieldBase directory hist copies) d x C hu
+ (scratchRegions_ordered P demand v fieldBase fields histEnd hc room)
+
+/-- Above field and histogram starts at most `n ^ 5`, leave room for a payload
+of at most `n` bits and every selector suffix of at most `n` copies. -/
+def liveDirectory (selectorBits counters n : ℕ) : ℕ :=
+ n ^ 5 + n + n * selectorBits + counters
+
+omit [DecidableEq J] in
+theorem eventually_scratchCapacity
+ (B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H')
+ (b t : ℕ) (hb : 1 ≤ b) :
+ ∀ᶠ n : ℕ in atTop, Capacity B (wordBits b n) n
+ (scratchEnd D E (liveDirectory B.selectorBits t n) n) := by
+ apply eventually_capacity (B := B) b hb
+ unfold scratchEnd ordinalBase descriptorBase liveDirectory
+ have tags := PolynomiallyBounded.id.mul (PolynomiallyBounded.const B.selectorBits)
+ have directory := (((PolynomiallyBounded.id.pow 5).add PolynomiallyBounded.id).add tags).add
+ (PolynomiallyBounded.const t)
+ have descriptors := directory.add (PolynomiallyBounded.const (2 * Fintype.card E))
+ have ordinals := descriptors.add (PolynomiallyBounded.const (Fintype.card (MapCallSetup.Arg D E)))
+ exact (ordinals.add PolynomiallyBounded.id).add PolynomiallyBounded.id
+
+/-- The same capacity, fixed before the branch, constructs workspaces for all
+map inputs of these numerical sizes. No equality of the proposed total widths
+with the selected payload is required. -/
+noncomputable def liveWorkspace
+ (C : Capacity B w n (scratchEnd D E (liveDirectory B.selectorBits t n) n))
+ (hu : u ≤ n) (hbase : ∀ f, fieldBase f ≤ n ^ 5) (hhist : hist ≤ n ^ 5)
+ (hd : ∀ e, demand e ≤ n) (hv : ∀ e, v e ≤ n) :
+ MapEntry.Program.Workspace P demand v d x t w := by
+ apply scratchWorkspace P demand v fieldBase d x C hu (copies := n)
+ (directory := liveDirectory B.selectorBits t n) (hist := hist)
+ · intro f
+ rcases f with ⟨b, e⟩ | ⟨b, e⟩
+ · have := hbase (.inl (b, e))
+ have := hd e
+ simp only [rawWidth, liveDirectory]
+ omega
+ · have := hbase (.inr (b, e))
+ have := hv e
+ have := Nat.mul_le_mul_right B.selectorBits hu
+ simp only [rawWidth, liveDirectory]
+ omega
+ · unfold liveDirectory
+ omega
+ · exact hu
+ · rfl
+
+end PairSimulation.MapWorkspace
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapWriterClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapWriterClock.lean
new file mode 100644
index 0000000000..af910560db
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapWriterClock.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.PairSimulationMapArgumentWriter
+import OAI.Computability.VPVNP.CompressorRegisterSetupClock
+
+/-!
+# Canonical event sequence of the map argument writer
+
+The native writer evaluates its expressions using the six live input
+words and the external memory. The events are exactly those of the same
+expression list evaluated with a zeroed compiler bank, followed by the
+private descriptor stores. Thus their order and contents are determined
+by the inputs even when the caller's other registers and memory vary.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapArgumentWriter
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.PhaseRecipe
+open scoped Fin.CommRing
+
+variable {n w p r k : ℕ} (base : Expr) (fields : Fin n → Expr)
+
+/-- Every public record read in assignment order followed by the fixed
+private-store and cursor instructions. -/
+def events (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) : List (Event w) :=
+ (RowRecipe.evaluate pub state m (lines base fields) (fun _ ↦ 0)).1 ++
+ List.replicate (3 + 2 * n) .tick
+
+/-- Every external read in the writer's canonical trace belongs to the
+region certified for its base and field expressions. -/
+theorem events_readsFrom (data : ℕ → Prop) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w)
+ (baseSafe : base.ReadsFrom data pub state m)
+ (fieldSafe : ∀ i, (fields i).ReadsFrom data pub state m) :
+ SourceTransport.Reads data (events base fields pub state m) := by
+ have allowed (i : Fin (n + 1)) : ((recipes base fields) i).ReadsFrom data pub state m := by
+ refine Fin.lastCases ?_ (fun j ↦ ?_) i
+ · simpa only [recipes, Fin.snoc_last] using baseSafe
+ · simpa only [recipes, Fin.snoc_castSucc] using fieldSafe j
+ intro a v h
+ rcases List.mem_append.mp h with entry | entry
+ · exact RegisterSetup.lines_reads (recipes base fields) data pub state m allowed _ a v entry
+ · cases List.eq_of_mem_replicate entry
+
+/-- The external memory is read-only during the complete writer, including
+the descriptor stores in the private memory. -/
+theorem events_noWrites (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) :
+ SourceTransport.Writes (fun _ ↦ False) (events base fields pub state m) := by
+ have rows {r : ℕ} (ls : List (RowRecipe.Assign r 5)) (rs : PrimedStackRAM.Regs w r) :
+ SourceTransport.Writes (fun _ ↦ False) (RowRecipe.evaluate pub state m ls rs).1 := by
+ induction ls generalizing rs with
+ | nil => simp [SourceTransport.Writes, RowRecipe.evaluate]
+ | cons line rest ih =>
+ intro a v h
+ rcases List.mem_cons.mp h with head | tail
+ · cases eq : line.rhs <;> simp [RowRecipe.RHS.event, eq] at head
+ · exact ih _ a v tail
+ intro a v h
+ rcases List.mem_append.mp h with entry | entry
+ · exact rows _ _ a v entry
+ · cases List.eq_of_mem_replicate entry
+
+variable (vm : Fin (RegisterSetup.regCount (recipes base fields)) ↪ Fin r)
+ (inputs : Fin 6 → Fin r) (aux : Fin 3 ↪ Fin r)
+ (loc : Address base fields → Fin p) (done : Fin p)
+
+/-- On every caller configuration, the linked writer executes the same
+canonical trace for its input words and external records. The output
+descriptor and exterior memory frame refer to this very execution. -/
+theorem native_exact (M : Machine w p r k) (link : ∀ a,
+ M.code (loc a) = (text base fields vm inputs aux loc done a).resize w)
+ (safe : ∀ i j, vm i ≠ inputs j) (apart : ∀ i j, vm i ≠ aux j)
+ (c : Config w p r) (m : Memory w) (start : c.pc = setupPC base fields loc 0) :
+ let pub := fun i : Fin 5 ↦ c.reg (inputs i.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := base.eval pub state m
+ addr.val + n ≤ 2 ^ w →
+ let ev := events base fields pub state m
+ ∃ out : Config w p r,
+ ev.length = clock base fields ∧ countProbes ev = ∑ i, ((recipes base fields) i).loads ∧
+ choiceBits ev = [] ∧ out.pc = done ∧ out.reg (aux 0) = addr ∧
+ out.persistent = c.persistent ∧
+ (∀ i : Fin n, out.privateMem (addr + (i.val : Word w)) = (fields i).eval pub state m) ∧
+ (∀ a : Word w, a.val < addr.val ∨ addr.val + n ≤ a.val →
+ out.privateMem a = c.privateMem a) ∧
+ (∀ j, (∀ i, j ≠ vm i) → (∀ i, j ≠ aux i) → out.reg j = c.reg j) ∧
+ ∀ fuel bs, execute M.program (fuel + ev.length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep ↦ ⟨ev ++ rep.events, rep.result⟩) := by
+ intro pub state addr fit
+ obtain ⟨out, prop⟩ :=
+ native_raw base fields vm inputs aux loc done M link safe apart c m start fit
+ have eq := RegisterSetup.events_eq (recipes base fields) pub state m (fun i ↦ c.reg (vm i))
+ change (RowRecipe.evaluate pub state m (lines base fields) (fun i ↦ c.reg (vm i))).1 =
+ (RowRecipe.evaluate pub state m (lines base fields) (fun _ ↦ 0)).1 at eq
+ dsimp only [events]
+ rw [← eq]
+ exact ⟨out, prop⟩
+
+end PairSimulation.MapArgumentWriter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapWrittenCall.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapWrittenCall.lean
new file mode 100644
index 0000000000..e21682eb44
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapWrittenCall.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.PairSimulationMapArgumentInput
+import OAI.Computability.VPVNP.PairSimulationMapPost
+import OAI.Computability.VPVNP.PairNodeChildLoop
+
+/-!
+# Executing a resident motif call on the enclosing RAM
+
+The descriptor writer reads the external record before control enters the
+inlined motif table. Both phases share the caller's private memory. Their
+composition gives the event prefix used by the resident-map loop, including
+the histogram effect and the frame on the other live operands.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapArgumentWriter
+
+open MotifSelector MotifBlocks MotifGrid MotifConversion MotifEntry MotifDemandPadding
+open BurstRAM BurstRAM.PrivateRAM InlinePublic MapConstants MapInline
+open CompressorRecords CompressorRecords.PhaseRecipe
+open scoped Fin.CommRing
+open private tick_log from OAI.Computability.VPVNP.PairSimulationMapArgumentWriter
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {r k p R w t : ℕ} (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : MapCallTable.Layout B (demandGrid B hp I.demand) I.party r k)
+ (ord : (parameterData B).Entry → Fin t)
+ (V : Placement (capacity L.template (rawBank L.core ord)) (Nat.card L.Address) r p R)
+ (base : Expr) (fields : MapCallSetup.Arg D E → Expr)
+
+local notation "f" => fields ∘ L.args.symm
+local notation "loc" => L.corePC L.locations
+local notation "d" => demandBits src dst I.party I.demandBits
+local notation "x" => mapHalf G (fun _ ↦ inputBits) I.supplyBits
+
+/-- Native execution of the externally supplied operand recipes and the complete
+motif map. The prefix consumes no branch bits. Every external probe belongs to
+the fixed argument recipes, and the histogram changes by the emitted ordinals. -/
+theorem written_call_post
+ (X : MapEntry.Program.Workspace (callProgram L) I.demand I.payload d x t w)
+ (vm : Fin (RegisterSetup.regCount (recipes base f)) ↪ Fin R)
+ (inputs : Fin 6 → Fin R) (aux : Fin 3 ↪ Fin R) (place : Address base f → Fin p)
+ (M : Machine w p R 11) (link : ∀ a, M.code (place a) =
+ (text base f vm inputs aux place (V.entry L.template.entry) a).resize w)
+ (safe : ∀ i j, vm i ≠ inputs j) (apart : ∀ i j, vm i ≠ aux j)
+ (pointer : V.reg L.ptr = aux 0) (body : MapInline.Linked L ord V M)
+ (hw : widthThreshold B ≤ w) (c : Config w p R) (m : Memory w)
+ (start : c.pc = setupPC base f place 0) :
+ let pub := fun i : Fin 5 ↦ c.reg (inputs i.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := base.eval pub state m
+ let outside := fun q : BurstRAM.Word w ↦ q.val < addr.val ∨
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val
+ let hist := fun i : Fin t ↦ ((X.hist + i.val : ℕ) : BurstRAM.Word w)
+ let names := (runEntry B hp I.demand I.payload I.party d x).1.map (List.map ord)
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ 2 ^ w →
+ (∀ a, (fields a).eval pub state m = MapCallSetup.values L.core loc X a) →
+ ResidentFields L.core loc X addr c.privateMem →
+ (∀ l, outside (hist l)) →
+ (∀ l (i : MapDirectoryInit.Row L.core), hist l ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ ∃ (out : Config w p R) (es : List (Event w)),
+ NodeArguments.ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ clock base f + factor L ord * (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand)) ∧
+ countProbes es = ∑ i, ((recipes base f) i).loads ∧ choiceBits es = [] ∧
+ out.pc = (if names.isSome then V.entry (callProgram L).done
+ else V.entry (callProgram L).bad) ∧
+ out.persistent = c.persistent ∧
+ (∀ j, V.privateReg j → (∀ i, j ≠ vm i) → (∀ i, j ≠ aux i) → out.reg j = c.reg j) ∧
+ (∀ q, outside q → MapCallSetup.Outside L.core loc X q → out.privateMem q = c.privateMem q) ∧
+ (∀ l, out.privateMem (hist l) = c.privateMem (hist l) +
+ ((names.getD []).count l : BurstRAM.Word w)) ∧
+ MapCallSetup.Success L.core loc X (selectorWord B (fits_of_threshold B hw).2.2.2) ord
+ (PrivateScratch.write addr (MapCallSetup.values L.core loc X ∘ L.args.symm) c.privateMem)
+ out.privateMem := by
+ intro pub state addr outside hist names fit read cells histOutside dirApart
+ obtain ⟨ev, mid, len, probes, choices, pc, ptr, per, words, mem, regs, first⟩ :=
+ native base f vm inputs aux place (V.entry L.template.entry) M link safe apart c m start fit
+ have input : MapCallSetup.Input L.core L.args loc X L.ptr (restrict V L.template.entry mid) := by
+ apply input_of_published L.core L.args loc X addr c.privateMem _ L.ptr
+ · change mid.reg (V.reg L.ptr) = addr
+ rw [pointer, ptr]
+ · intro a
+ change mid.privateMem (addr + ((L.args a).val : BurstRAM.Word w)) = _
+ rw [words]
+ simpa only [Function.comp_apply, Equiv.symm_apply_apply] using read a
+ · exact mem
+ · exact cells
+ obtain ⟨n, out, bound, tail, keep, savedRegs, savedMem, result, post⟩ :=
+ run_entryInput_post ord hp I L V M body hw X mid pc input dirApart
+ let ticks := List.replicate n (.tick : Event w)
+ have ht : choiceBits ticks = [] ∧ countProbes ticks = 0 := tick_log n
+ have endAt : Outcome X.hist (V.entry (callProgram L).bad) (V.entry (callProgram L).done)
+ mid out names := result
+ have published : mid.privateMem =
+ PrivateScratch.write addr (MapCallSetup.values L.core loc X ∘ L.args.symm) c.privateMem := by
+ apply PrivateScratch.eq_write
+ · intro i
+ exact (words i).trans (read (L.args.symm i))
+ · intro q hq
+ have cast : (addr.val : BurstRAM.Word w) = addr := Fin.ext (Nat.mod_eq_of_lt addr.isLt)
+ exact mem q (PrivateScratch.outside_of_ne addr.val q fun i ↦ cast.symm ▸ hq i)
+ have path₁ : NodeArguments.ChildScan.Prefix M m c mid [] ev := first
+ have path₂ : NodeArguments.ChildScan.Prefix M m mid out [] ticks := by
+ intro fuel more
+ simpa only [ticks, (tick_log n).1] using tail.execute fuel m more
+ refine ⟨out, ev ++ ticks, path₁.trans path₂, ?_, ?_, ?_, ?_, keep.trans per,
+ ?_, ?_, ?_, published ▸ post⟩
+ · rw [List.length_append, len, List.length_replicate]
+ exact Nat.add_le_add_left bound _
+ · rw [countProbes_append, probes, ht.2, Nat.add_zero]
+ · rw [PrimedInputRAM.Flow.choiceBits_append, choices, ht.1, List.nil_append]
+ · cases eq : names <;> rw [eq] at endAt <;> exact endAt.1
+ · exact fun j hj hv ha ↦ (savedRegs j hj).trans (regs j hv ha)
+ · exact fun q ho hmap ↦ (savedMem q hmap).trans (mem q ho)
+ · intro l
+ cases eq : names with
+ | none =>
+ rw [eq] at endAt
+ simpa [hist] using (endAt.2 l).trans (mem _ (histOutside l))
+ | some ls =>
+ rw [eq] at endAt
+ exact (endAt.2 l).trans
+ (congrArg (· + (ls.count l : BurstRAM.Word w)) (mem _ (histOutside l)))
+
+/-- The execution prefix, counters, and exterior frame of the same native call. -/
+theorem written_call (X : MapEntry.Program.Workspace (callProgram L) I.demand I.payload d x t w)
+ (vm : Fin (RegisterSetup.regCount (recipes base f)) ↪ Fin R)
+ (inputs : Fin 6 → Fin R) (aux : Fin 3 ↪ Fin R) (place : Address base f → Fin p)
+ (M : Machine w p R 11) (link : ∀ a, M.code (place a) =
+ (text base f vm inputs aux place (V.entry L.template.entry) a).resize w)
+ (safe : ∀ i j, vm i ≠ inputs j) (apart : ∀ i j, vm i ≠ aux j)
+ (pointer : V.reg L.ptr = aux 0) (body : MapInline.Linked L ord V M)
+ (hw : widthThreshold B ≤ w) (c : Config w p R) (m : Memory w)
+ (start : c.pc = setupPC base f place 0) :
+ let pub := fun i : Fin 5 ↦ c.reg (inputs i.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := base.eval pub state m
+ let outside := fun q : BurstRAM.Word w ↦ q.val < addr.val ∨
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val
+ let hist := fun i : Fin t ↦ ((X.hist + i.val : ℕ) : BurstRAM.Word w)
+ let names := (runEntry B hp I.demand I.payload I.party d x).1.map (List.map ord)
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ 2 ^ w →
+ (∀ a, (fields a).eval pub state m = MapCallSetup.values L.core loc X a) →
+ ResidentFields L.core loc X addr c.privateMem →
+ (∀ l, outside (hist l)) →
+ (∀ l (i : MapDirectoryInit.Row L.core), hist l ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ ∃ (out : Config w p R) (es : List (Event w)),
+ NodeArguments.ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ clock base f + factor L ord * (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand)) ∧
+ countProbes es = ∑ i, ((recipes base f) i).loads ∧ choiceBits es = [] ∧
+ out.pc = (if names.isSome then V.entry (callProgram L).done
+ else V.entry (callProgram L).bad) ∧
+ out.persistent = c.persistent ∧
+ (∀ j, V.privateReg j → (∀ i, j ≠ vm i) → (∀ i, j ≠ aux i) → out.reg j = c.reg j) ∧
+ (∀ q, outside q → MapCallSetup.Outside L.core loc X q → out.privateMem q = c.privateMem q) ∧
+ ∀ l, out.privateMem (hist l) = c.privateMem (hist l) +
+ ((names.getD []).count l : BurstRAM.Word w) := by
+ intro pub state addr outside hist names fit read cells histOutside dirApart
+ obtain ⟨out, es, path, cap, probes, choices, pc, per, regFrame, memFrame, counts, _⟩ :=
+ written_call_post hp I L ord V base fields X vm inputs aux place M link safe apart pointer
+ body hw c m start fit read cells histOutside dirApart
+ exact ⟨out, es, path, cap, probes, choices, pc, per, regFrame, memFrame, counts⟩
+
+end PairSimulation.MapArgumentWriter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationMapWrittenExact.lean b/lean/OAI/Computability/VPVNP/PairSimulationMapWrittenExact.lean
new file mode 100644
index 0000000000..8bd0cb02c9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationMapWrittenExact.lean
@@ -0,0 +1,151 @@
+import OAI.Computability.VPVNP.PairSimulationMapWrittenCall
+import OAI.Computability.VPVNP.PairSimulationMapCallExact
+import OAI.Computability.VPVNP.PairSimulationMapWriterClock
+
+/-!
+# Exact chronological trace of a successful descriptor writer and map
+
+The writer's six input words and the external memory determine its ordered
+reads. The succeeding native map contributes the exact ticks of the decoded
+row sequence. The complete prefix carries the canonical histogram and private
+scratch updates on the enclosing machine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapArgumentWriter
+
+open MotifSelector MotifBlocks MotifGrid MotifConversion MotifEntry MotifDemandPadding
+open BurstRAM BurstRAM.PrivateRAM InlinePublic MapConstants MapInline
+open CompressorRecords CompressorRecords.PhaseRecipe
+open scoped Fin.CommRing
+open private tick_log from OAI.Computability.VPVNP.PairSimulationMapArgumentWriter
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {r k p R w t : ℕ} (hp : ∀ e, 0 < p₀ e) (I : LocalHistory.EntryInput B)
+ (L : MapCallTable.Layout B (demandGrid B hp I.demand) I.party r k)
+ (ord : (parameterData B).Entry → Fin t)
+ (V : Placement (capacity L.template (rawBank L.core ord)) (Nat.card L.Address) r p R)
+ (base : Expr) (fields : MapCallSetup.Arg D E → Expr)
+
+local notation "f" => fields ∘ L.args.symm
+local notation "loc" => L.corePC L.locations
+local notation "d" => demandBits src dst I.party I.demandBits
+local notation "x" => mapHalf G (fun _ ↦ inputBits) I.supplyBits
+
+set_option maxHeartbeats 800000 in
+-- The writer and inlined map share dependent addresses for all input, staging and output cells.
+/-- Native execution of the externally supplied operand recipes and the complete
+motif map. The prefix consumes no branch bits. Every external probe belongs to
+the fixed argument recipes, and the histogram changes by the emitted ordinals. -/
+theorem written_success_exact
+ (X : MapEntry.Program.Workspace (callProgram L) I.demand I.payload d x t w)
+ (vm : Fin (RegisterSetup.regCount (recipes base f)) ↪ Fin R)
+ (inputs : Fin 6 → Fin R) (aux : Fin 3 ↪ Fin R) (place : Address base f → Fin p)
+ (M : Machine w p R 11) (link : ∀ a, M.code (place a) =
+ (text base f vm inputs aux place (V.entry L.template.entry) a).resize w)
+ (safe : ∀ i j, vm i ≠ inputs j) (apart : ∀ i j, vm i ≠ aux j)
+ (pointer : V.reg L.ptr = aux 0) (body : MapInline.Linked L ord V M)
+ (hw : widthThreshold B ≤ w) (c : Config w p R) (m : Memory w)
+ (start : c.pc = setupPC base f place 0) :
+ let pub := fun i : Fin 5 ↦ c.reg (inputs i.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ let addr := base.eval pub state m
+ let outside := fun q : BurstRAM.Word w ↦ q.val < addr.val ∨
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ q.val
+ let hist := fun i : Fin t ↦ ((X.hist + i.val : ℕ) : BurstRAM.Word w)
+ let names := (runEntry B hp I.demand I.payload I.party d x).1.map (List.map ord)
+ addr.val + Fintype.card (MapCallSetup.Arg D E) ≤ 2 ^ w →
+ (∀ a, (fields a).eval pub state m = MapCallSetup.values L.core loc X a) →
+ ResidentFields L.core loc X addr c.privateMem →
+ (∀ l, outside (hist l)) →
+ (∀ l (i : MapDirectoryInit.Row L.core), hist l ≠ X.directory + (i.val : BurstRAM.Word w)) →
+ ∀ (θ : Fin (repetitions B I.demand) → Selector B),
+ (selectorRun G (selectorTable B) (selectorCode B) I.payload I.party x).1 = some θ →
+ (∀ e, I.payload e = totalWidth (basePayload B) θ e) →
+ let n := factor L ord * entryTicks hp I L ord hw θ
+ let es := events base f pub state m ++ List.replicate n (.tick : Event w)
+ ∃ (out : Config w p R),
+ NodeArguments.ChildScan.Prefix M m c out [] es ∧
+ es.length ≤ clock base f + factor L ord * (L.lines.length +
+ (1 + 3 * (MapPortAgreement.ports G I.party L.core.edgeOrder).length) +
+ MapNativeClock.cap B (demandGrid B hp I.demand) I.party (repetitions B I.demand)) ∧
+ countProbes es = ∑ i, ((recipes base f) i).loads ∧ choiceBits es = [] ∧
+ out.pc = V.entry (callProgram L).done ∧
+ out.persistent = c.persistent ∧
+ (∀ j, V.privateReg j → (∀ i, j ≠ vm i) → (∀ i, j ≠ aux i) → out.reg j = c.reg j) ∧
+ (∀ q, outside q → MapCallSetup.Outside L.core loc X q → out.privateMem q = c.privateMem q) ∧
+ (∀ l, out.privateMem (hist l) = c.privateMem (hist l) +
+ ((names.getD []).count l : BurstRAM.Word w)) ∧
+ MapCallSetup.Success L.core loc X (selectorWord B (fits_of_threshold B hw).2.2.2) ord
+ (PrivateScratch.write addr (MapCallSetup.values L.core loc X ∘ L.args.symm) c.privateMem)
+ out.privateMem ∧
+ out.privateMem = (callProgram L).successMemory X
+ (selectorWord B (fits_of_threshold B hw).2.2.2) ord θ
+ (MapCallSetup.directoryMemory L.core loc X
+ (PrivateScratch.write addr (MapCallSetup.values L.core loc X ∘ L.args.symm)
+ c.privateMem)) := by
+ intro pub state addr outside hist names fit read cells histOutside dirApart θ selected valid n es
+ let ev := events base f pub state m
+ obtain ⟨mid, len, probes, choices, pc, ptr, per, words, mem, regs, first⟩ :=
+ native_exact base f vm inputs aux place (V.entry L.template.entry) M link safe apart
+ c m start fit
+ have input : MapCallSetup.Input L.core L.args loc X L.ptr (restrict V L.template.entry mid) := by
+ apply input_of_published L.core L.args loc X addr c.privateMem _ L.ptr
+ · change mid.reg (V.reg L.ptr) = addr
+ rw [pointer, ptr]
+ · intro a
+ change mid.privateMem (addr + ((L.args a).val : BurstRAM.Word w)) = _
+ rw [words]
+ simpa only [Function.comp_apply, Equiv.symm_apply_apply] using read a
+ · exact mem
+ · exact cells
+ obtain ⟨out, bound, tail, keep, savedRegs, savedMem, result, post, done, allMem⟩ :=
+ run_entryInput_success_exact ord hp I L V M body hw X mid pc input dirApart θ selected valid
+ let ticks := List.replicate n (.tick : Event w)
+ change PrimedCounter.GuessWord.Prefix M mid ticks out at tail
+ have ht : choiceBits ticks = [] ∧ countProbes ticks = 0 := tick_log n
+ have endAt : Outcome X.hist (V.entry (callProgram L).bad) (V.entry (callProgram L).done)
+ mid out names := result
+ have published : mid.privateMem =
+ PrivateScratch.write addr (MapCallSetup.values L.core loc X ∘ L.args.symm) c.privateMem := by
+ apply PrivateScratch.eq_write
+ · intro i
+ exact (words i).trans (read (L.args.symm i))
+ · intro q hq
+ have cast : (addr.val : BurstRAM.Word w) = addr := Fin.ext (Nat.mod_eq_of_lt addr.isLt)
+ exact mem q (PrivateScratch.outside_of_ne addr.val q fun i ↦ cast.symm ▸ hq i)
+ have path₁ : NodeArguments.ChildScan.Prefix M m c mid [] ev := first
+ have path₂ : NodeArguments.ChildScan.Prefix M m mid out [] ticks := by
+ intro fuel more
+ simpa only [ht.1] using tail.execute fuel m more
+ refine ⟨out, path₁.trans path₂, ?_, ?_, ?_, done, keep.trans per, ?_, ?_, ?_,
+ published ▸ post, published ▸ allMem⟩
+ · change (ev ++ ticks).length ≤ _
+ rw [List.length_append, len, List.length_replicate]
+ exact Nat.add_le_add_left bound _
+ · change countProbes (ev ++ ticks) = _
+ rw [countProbes_append, probes, ht.2, Nat.add_zero]
+ · change choiceBits (ev ++ ticks) = _
+ rw [PrimedInputRAM.Flow.choiceBits_append, choices, ht.1, List.nil_append]
+ · exact fun j hj hv ha ↦ (savedRegs j hj).trans (regs j hv ha)
+ · exact fun q ho hmap ↦ (savedMem q hmap).trans (mem q ho)
+ · intro l
+ cases eq : names with
+ | none =>
+ rw [eq] at endAt
+ simpa [hist] using (endAt.2 l).trans (mem _ (histOutside l))
+ | some ls =>
+ rw [eq] at endAt
+ exact (endAt.2 l).trans
+ (congrArg (· + (ls.count l : BurstRAM.Word w)) (mem _ (histOutside l)))
+
+end PairSimulation.MapArgumentWriter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationNodeFieldSpace.lean b/lean/OAI/Computability/VPVNP/PairSimulationNodeFieldSpace.lean
new file mode 100644
index 0000000000..cc6b1185fd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationNodeFieldSpace.lean
@@ -0,0 +1,224 @@
+import OAI.Computability.VPVNP.PairNodeArguments
+import OAI.Computability.VPVNP.PairTraversalNodeBounds
+import OAI.Computability.VPVNP.PairSimulationMapWordBounds
+import OAI.Computability.VPVNP.CompressorDescriptorSquare
+import OAI.Computability.VPVNP.CompressorDescriptorBranchSpace
+
+/-!
+# Word capacity of the private DFS argument frames
+
+Section 13 indexes a private argument interval by the absolute address of its
+DFS row. The row lies in the selected branch's descriptor region, while the
+stride only needs to accommodate the two sets of half-wire fields of a single
+site. Bounding both before choosing the branch gives a live-word bound on the
+product of row address and stride, including all offsets used by the map
+entry readers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.NodeArguments
+
+open CursorBounds CursorNetwork Compression CompressorRecords TraversalRows Filter
+open MotifBlocks MotifConversion MotifSelector MotifGrid MapStream
+
+variable {a g : ℕ}
+
+/-- All the independent half-wires at a vertex fit in two degree-sized rows
+of maximum-width slots. -/
+theorem packed_length_le (X : State a g) (v : X.network.Site) (h : X.network.Half v) :
+ (packed X v h).length ≤ 2 * (2 ^ a) * X.maxWireWidth := by
+ rw [packed_length]
+ calc
+ _ ≤ ∑ _ : Bool, ∑ _ : Fin (2 ^ a), X.maxWireWidth :=
+ Finset.sum_le_sum fun dir _ ↦ Finset.sum_le_sum fun j _ ↦ X.halfWidth_le_max v dir j
+ _ = _ := by simp [two_mul, Nat.add_mul]
+
+/-- Even an empty field has its start and exclusive end inside the full
+argument interval. -/
+theorem field_end_le (X : State a g) (v : X.network.Site) (h : X.network.Half v)
+ (A : Arena) (node : ℕ) (dir : Bool) (j : Fin (2 ^ a)) :
+ A.fieldAddress X v node dir j + X.halfWidth v dir j ≤ A.base node + (packed X v h).length := by
+ obtain ⟨pre, post, eqn, len⟩ := packed_member X v h dir j
+ rw [Arena.fieldAddress, ← len, eqn]
+ simp only [List.length_append, List.length_ofFn]
+ omega
+
+/-- Reserve both sets of numbered half-wires using the fixed schedule's
+maximum degree and an upper bound on every selected width. -/
+def frameStride (degree width : ℕ) : ℕ := 2 * degree * width + 1
+
+theorem frameStride_bounded (degree : ℕ) : PolynomiallyBounded (frameStride degree) :=
+ ((PolynomiallyBounded.const (2 * degree)).mul PolynomiallyBounded.id).add
+ (PolynomiallyBounded.const 1)
+
+variable {k : Type*} [_root_.Field k] {J D S₀ : Type} [Fintype J] [Fintype D] [Fintype S₀]
+variable {src dst : D → J} {P : Supply J S₀} {p : D → ℚ} {q : S₀ → ℚ} {H H' : ℝ}
+
+/-- The four kinds of map-reader endpoints, including cumulative payload
+offsets even when a selector sequence later fails its total-width check. -/
+def ReadEndsFit (B : FixedBlock k src dst P (realWidths p) (realWidths q) H H')
+ (w n address : ℕ) : Prop :=
+ ∀ u ≤ n, ∀ z (θ : Fin u → Selector B) (i : Fin u),
+ (∀ e, address + baseDemand B z e * i.val + baseDemand B z e < 2 ^ w) ∧
+ (∀ e, address + MotifEntry.offset (fun l ↦ basePayload B (θ l) e) i +
+ basePayload B (θ i) e < 2 ^ w) ∧
+ (∀ e, totalWidth (basePayload B) θ e < 2 ^ w) ∧
+ ∀ v ≤ n, address + v + B.selectorBits * i.val + B.selectorBits < 2 ^ w
+
+/-- Polynomial bounds may be fixed independently for the first private
+address, the *absolute* row address, the stride and an additional scratch
+suffix. Every address up to the resulting end supports the map's reads. -/
+theorem eventually_sparseFrame (B : FixedBlock k src dst P (realWidths p) (realWidths q) H H')
+ (b : ℕ) (hb : 1 ≤ b) {first limit stride extra : ℕ → ℕ}
+ (hf : PolynomiallyBounded first) (hl : PolynomiallyBounded limit)
+ (hs : PolynomiallyBounded stride) (he : PolynomiallyBounded extra) :
+ ∀ᶠ n : ℕ in atTop, ∀ node ≤ limit n,
+ let arena : Arena := ⟨first n, stride n⟩
+ arena.base node + arena.stride + extra n < 2 ^ wordBits b n ∧
+ ∀ addr ≤ arena.base node + arena.stride + extra n, ReadEndsFit B (wordBits b n) n addr := by
+ let bound := fun n ↦ first n + limit n * stride n + stride n + extra n
+ have hc : PolynomiallyBounded bound := ((hf.add (hl.mul hs)).add hs).add he
+ filter_upwards [CursorRAM.eventual_word_room b hb hc,
+ eventually_polynomial_field_addresses B b hb bound hc] with n hroom hmap
+ intro node hnode arena
+ have h : arena.base node + arena.stride + extra n ≤ bound n :=
+ Nat.add_le_add_right (Nat.add_le_add_right (Nat.add_le_add_left
+ (Nat.mul_le_mul_right _ hnode) _) _) _
+ exact ⟨h.trans_lt hroom, fun addr ha u hu z θ i ↦
+ hmap.2.2.2 u hu z θ i addr (ha.trans h)⟩
+
+/-- Start shared map scratch beyond the reserved frame for the last possible
+node. Frames at all smaller absolute node addresses precede this workspace. -/
+def Arena.scratch (A : Arena) (limit : ℕ) := A.base limit + A.stride
+
+theorem Arena.frame_before_scratch (A : Arena) {node limit : ℕ} (hn : node ≤ limit) :
+ A.base node + A.stride ≤ A.scratch limit :=
+ Nat.add_le_add_right (Nat.add_le_add_left (Nat.mul_le_mul_right _ hn) _) _
+
+/-- The same address bound applies to a common scratch arena above *all*
+private argument frames, for every address in its reserved suffix. -/
+theorem eventually_global_map_scratch
+ (B : FixedBlock k src dst P (realWidths p) (realWidths q) H H') (b : ℕ) (hb : 1 ≤ b)
+ {first rowStart stride extra : ℕ → ℕ} (hf : PolynomiallyBounded first)
+ (hl : PolynomiallyBounded rowStart) (hs : PolynomiallyBounded stride)
+ (he : PolynomiallyBounded extra) :
+ ∀ᶠ n : ℕ in atTop,
+ let arena : Arena := ⟨first n, stride n⟩
+ let limit := rowStart n + (initialPositions b n) ^ 2
+ let scratch := arena.scratch limit
+ scratch + extra n < 2 ^ wordBits b n ∧
+ (∀ node ≤ limit, arena.base node + arena.stride ≤ scratch) ∧
+ ∀ off ≤ extra n, ReadEndsFit B (wordBits b n) n (scratch + off) := by
+ let limit n := rowStart n + (initialPositions b n) ^ 2
+ have hc : PolynomiallyBounded limit := hl.add ((CursorRAM.bounded_positions b).pow 2)
+ filter_upwards [eventually_sparseFrame B b hb hf hc hs he] with n room
+ intro arena last scratch
+ obtain ⟨endFit, reads⟩ := room (limit n) le_rfl
+ exact ⟨endFit, fun _ h ↦ arena.frame_before_scratch h,
+ fun off hoff ↦ reads _ (Nat.add_le_add_left hoff _)⟩
+
+/-- The total argument interval and every individual native slot endpoint
+lie below the word modulus. The map read bound is specialized to the actual
+`fieldAddress`, independent of the guessed bits. -/
+structure SiteFits (B : FixedBlock k src dst P (realWidths p) (realWidths q) H H')
+ (w n : ℕ) (arena : Arena) (node : ℕ) (X : State a g) : Prop where
+ packed : ∀ v h, (NodeArguments.packed X v h).length ≤ arena.stride
+ exclusiveEnd : arena.base node + arena.stride < 2 ^ w
+ slot : ∀ v dir j, arena.fieldAddress X v node dir j + X.halfWidth v dir j < 2 ^ w ∧
+ ReadEndsFit B w n (arena.fieldAddress X v node dir j)
+
+private theorem siteFits_of_bound (B : FixedBlock k src dst P (realWidths p) (realWidths q) H H')
+ (w n : ℕ) (arena : Arena) (node : ℕ) (X : State a g)
+ (hs : 2 * (2 ^ a) * X.maxWireWidth ≤ arena.stride) (hr : arena.base node + arena.stride < 2 ^ w)
+ (hm : ∀ x ≤ arena.base node + arena.stride, ReadEndsFit B w n x) :
+ SiteFits B w n arena node X := by
+ have hp (v) (h) := (packed_length_le X v h).trans hs
+ refine ⟨hp, hr, fun v dir j ↦ ?_⟩
+ let h : X.network.Half v := ⟨fun _ _ _ ↦ false, fun _ _ _ ↦ false⟩
+ have he := (field_end_le X v h arena node dir j).trans (Nat.add_le_add_left (hp v h) _)
+ exact ⟨he.trans_lt hr, hm _ ((Nat.le_add_right _ _).trans he)⟩
+
+variable {S : BlockSchedule k}
+
+/-- For the actual selected cursor history, all frame and slot endpoints fit
+on every intermediate input and on the final state. The threshold precedes
+the coefficient specialization, the branch, the visited DFS node and the
+old half-wire values. -/
+theorem eventually_selected_node_fields
+ (M : FixedBlock k src dst P (realWidths p) (realWidths q) H H')
+ (F : DescriptorSpace.Shape) (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start privateStart extra : ℕ → ℕ}
+ (hstart : PolynomiallyBounded start) (hprivate : PolynomiallyBounded privateStart)
+ (hextra : PolynomiallyBounded extra) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ let layout := DescriptorSpace.cursorLayout F b S.steps u.θ (start n) n
+ let arena : Arena := ⟨privateStart n, frameStride (slotDegree S) n⟩
+ ∀ z : E.Choices, let Y := E.finalState z
+ ∀ v node,
+ node ∈ (selectedTrees B f hf T hT X z (DescriptorSpace.endAddress layout) v).preorder →
+ arena.base node + arena.stride + extra n < 2 ^ wordBits b n ∧
+ (∀ addr ≤ arena.base node + arena.stride + extra n,
+ ReadEndsFit M (wordBits b n) n addr) ∧
+ SiteFits M (wordBits b n) n arena node Y ∧
+ ∀ level ∈ executeLevels B f hf T hT X z,
+ SiteFits M (wordBits b n) n arena node level.input := by
+ let limit n := start n + (initialPositions b n) ^ 2
+ have hl : PolynomiallyBounded limit := hstart.add ((CursorRAM.bounded_positions b).pow 2)
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ let K := B.recordLimit + 2
+ have sparse := eventually_sparseFrame M b hb' hprivate hl
+ (frameStride_bounded (slotDegree S)) hextra
+ filter_upwards [sparse,
+ DescriptorSpace.eventually_selected_square F B u b hb K, eventually_pairBranchBounds B u b hb,
+ eventually_ge_atTop 3] with n hspace hsquare hbranch hn
+ intro base lanes labels hD hT R _ f hf X T E layout arena z Y v node hnode
+ let rowBase := DescriptorSpace.endAddress layout
+ let layers := selectedLayers B f hf T hT X z
+ have below := selectedTrees_below B f hf T hT X z rowBase v hnode
+ have foot := selected_words_le B f hf T hT X z
+ change words B.recordLimit layers ≤ K * Y.positions * B.growthConstant ^ T at foot
+ have rows_lt : rowBase + words B.recordLimit layers < start n + (processorCount b n) ^ 2 := by
+ refine lt_of_le_of_lt ?_ (hsquare (start n) labels hD hT R f hf z)
+ change rowBase + words B.recordLimit layers ≤ rowBase +
+ K * (X.positions + processorCount b n + Y.positions * B.growthConstant ^ T + Y.totalWidth) + 1
+ nlinarith only [foot, Nat.zero_le (K * (X.positions + processorCount b n + Y.totalWidth))]
+ have proc : processorCount b n ≤ initialPositions b n :=
+ (Nat.pow_le_pow_right Nat.zero_lt_two (addressBits_le_virtualBits b n hn)).trans
+ (Nat.le_mul_of_pos_right _ (by omega : 0 < virtualBits b n))
+ have hlim : node ≤ limit n := below.le.trans (rows_lt.le.trans
+ (Nat.add_le_add_left (Nat.pow_le_pow_left proc 2) _))
+ obtain ⟨hroom, hmap⟩ := hspace node hlim
+ have branch := hbranch.2.2 labels hD hT R f hf z
+ have hlimWidth : B.growthConstant ^ T * (X.maxWireWidth + 1) ≤ n := by
+ have hw := branch.2.2.2.2.2.1
+ change ((B.growthConstant ^ T * (X.maxWireWidth + 1) : ℕ) : ℝ) ≤ (n : ℝ) ^ (3 / 10 : ℝ) at hw
+ have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast (show 1 ≤ n by omega)
+ have hpow : (n : ℝ) ^ (3 / 10 : ℝ) ≤ n := by
+ simpa using Real.rpow_le_rpow_of_exponent_le hn' (by norm_num : (3 / 10 : ℝ) ≤ 1)
+ exact_mod_cast hw.trans hpow
+ have fit {c l : ℕ} (Z : State c l) (hd : 2 ^ c ≤ slotDegree S) (hw : Z.maxWireWidth ≤ n) :
+ SiteFits M (wordBits b n) n arena node Z := by
+ apply siteFits_of_bound
+ · exact (Nat.mul_le_mul (Nat.mul_le_mul_left 2 hd) hw).trans (Nat.le_succ _)
+ · exact (Nat.le_add_right _ _).trans_lt hroom
+ · exact fun addr ha ↦ hmap addr (ha.trans (Nat.le_add_right _ _))
+ refine ⟨hroom, hmap, fit Y ?_ (branch.2.2.2.2.1.trans hlimWidth), fun level hlevel ↦ ?_⟩
+ · exact (Finset.le_sup (f := fun i : Fin (S.steps + 1) ↦ 2 ^ S.degreeExponent i)
+ (Finset.mem_univ 0)).trans (le_max_right _ _)
+ · exact fit level.input level.oldDegree_le
+ (((executeLevels_limits B f hf T hT X z level hlevel).2).trans hlimWidth)
+
+end PairSimulation.NodeArguments
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationNominationAssembly.lean b/lean/OAI/Computability/VPVNP/PairSimulationNominationAssembly.lean
new file mode 100644
index 0000000000..d9fe3aa39f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationNominationAssembly.lean
@@ -0,0 +1,175 @@
+import OAI.Computability.VPVNP.PairSimulationLeafNativeCount
+import OAI.Computability.VPVNP.PairSimulationStackSpace
+import OAI.Computability.VPVNP.PairSimulationSelectorReindex
+import OAI.Computability.VPVNP.PairSimulationVertexJobs
+
+/-!
+# Stack nominations as the leaves of the compressed coefficient counter
+
+At a cursor-zero leaf, the binary choices are the stack program's tagged
+nomination, followed by its deterministic checks. At a transit leaf the
+routing test determines the empty choice. Both readers are transported
+into the padded state's original zero-exponent factors before the first
+shrinking pass. They therefore compose with the actual term workers and
+shared scan on every selected branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords Compression BurstRAM BurstRAM.PrivateRAM
+open CursorRouting CursorNetwork Filter
+open scoped Classical
+
+variable {d e w n a H s : ℕ} [NeZero d] {L : PrimedInputRAM.Lengths}
+ {Q : PrimedInputRAM.Layout L n a H w} (D : PrimedCounter.Data Q s)
+ (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+
+/-- A common source clock for all independently chosen incident halves. -/
+def NominationClock (t : ℕ) : Prop :=
+ ∀ v (z : (validatorNetwork d e w).Half v),
+ LeafStartup.steps 52 (LeafStartup.auxiliary D hw hc v (halfBuffers v z)) ≤ t
+
+/-- The same threshold works for all admissible input dimensions and
+instances of the auxiliary coefficient machine. -/
+theorem eventually_nominationClock :
+ ∀ᶠ n : ℕ in atTop, ∀ d e w [NeZero d] (budget : BurstRAM.ProcessorBudget n d e w)
+ (L : PrimedInputRAM.Lengths) (a H s : ℕ) (Q : PrimedInputRAM.Layout L n a H w) (D : PrimedCounter.Data Q s),
+ D.fuel ≤ n^10 → NominationClock D budget.tags budget.capFits (n^39) := by
+ filter_upwards [LeafStartup.eventually_steps 52] with n bound
+ intro d e w _ budget L a H s Q D hD v z
+ exact bound d e w (LeafStartup.auxiliary D budget.tags budget.capFits v (halfBuffers v z)) budget hD
+
+variable {base lanes degree padding : ℕ} (labels : Fin d ≃ Fin base ⊕ Fin lanes)
+ (hd : 1 < d) (hpad : 2+padding = 2^degree)
+variable {R : Type*} [CommRing R] {Label : Type} [Fintype Label] (f : Label → R)
+ (t : ℕ) (clock : NominationClock D hw hc t)
+
+/-- Site parsers for the padded initial cursor network, using the clocked stack-nomination
+reader on the incident halves of each underlying leaf. -/
+noncomputable def nominationSites :
+ SiteParsers f (cursorState labels hd hpad (ramFieldBits (2^e) w : RAMSystem d → ℕ)).network :=
+ let bits := (ramFieldBits (2^e) w : RAMSystem d → ℕ)
+ let I := cursorStateIso labels hd hpad (ramSystemOrder d) bits
+ let P : Factors Type (paddedNetwork d padding bits) := fun v z =>
+ initialChoices D.machine D.fuel 0 D.initial hw hc v (unpadHalf padding v z)
+ { (cursorSiteParsers D.machine D.fuel 0 D.initial hw hc labels hd hpad f) with
+ read := pushLeafReaders I P fun v z => LeafStartup.nominationReader D hw hc v (unpadHalf padding v z) t
+ (clock v (unpadHalf padding v z)) }
+
+open private pushLeafReaders_le from OAI.Computability.VPVNP.PairSimulationHistoryBounds
+
+theorem nominationSites_length_le :
+ let P := nominationSites D hw hc labels hd hpad f t clock
+ ∀ v z p, ((P.read v z).encode p).length ≤ t := by
+ let bits := (ramFieldBits (2^e) w : RAMSystem d → ℕ)
+ let I := cursorStateIso labels hd hpad (ramSystemOrder d) bits
+ let P : Factors Type (paddedNetwork d padding bits) := fun v z =>
+ initialChoices D.machine D.fuel 0 D.initial hw hc v (unpadHalf padding v z)
+ exact pushLeafReaders_le I P (fun v z => LeafStartup.nominationReader D hw hc v (unpadHalf padding v z) t
+ (clock v (unpadHalf padding v z))) t
+ (fun v z p => LeafStartup.nominationReader_length_le D hw hc v (unpadHalf padding v z) t (clock _ _) p)
+
+theorem nominationSites_zero :
+ let P := nominationSites D hw hc labels hd hpad f t clock
+ ∀ v z p label, (P.witnesses v z).exponents p label = 0 := fun _ _ _ _ => rfl
+
+section Compression
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) (g : B.Entry → R) (hg : B.IsSolution g)
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+/-- The auxiliary machine count with tagged stack nominations at the
+leaves and the same compressed monomial occurrence type. -/
+noncomputable def nominationCompressedReader :
+ ChoiceReader (compressedRAMCount B g hg D.machine D.fuel 0 D.initial hw hc labels hd T hT).Choice :=
+ let X := scanInput labels hd S e w
+ let E := B.execute g hg T hT X
+ let P := nominationSites D hw hc labels hd (Nat.add_sub_of_le S.degree_bounds.1) g t clock
+ historyReader E.history (B.executeWitnesses g hg T hT X) (executeReaders B g hg T hT X) P.factors P.witnesses P.read
+
+theorem nominationCompressed_sum :
+ let W := compressedRAMCount B g hg D.machine D.fuel 0 D.initial hw hc labels hd T hT
+ let C := nominationCompressedReader D hw hc labels hd t clock B g hg T hT
+ ∑ x : successful W C, Diagonal.labelMonomial g (W.exponents (C.completeEquiv.symm x)) =
+ (Nat.card (ActualPaths D.machine.program D.fuel 0 (RAMMemory.initialMemory (2^d) D.initial)
+ (withinCaps (2^d) (2^e))) : R) :=
+ weightedStreams _ _
+
+theorem nominationSelected_length_le :
+ let X := scanInput labels hd S e w
+ let E := B.execute g hg T hT X
+ let P := nominationSites D hw hc labels hd (Nat.add_sub_of_le S.degree_bounds.1) g t clock
+ ∀ z : E.Choices, let c := E.termChain (B.records g hg T hT X) z
+ let parser := finalParsers c (selectedParsers B g hg T hT X z) P
+ ∀ v y x, ((parser.read v y).encode x).length ≤
+ B.growthConstant^T * max t (B.growthConstant^T * (X.maxWireWidth+1)) := by
+ intro X E P z
+ exact selectedSite_length_le B g hg T hT X z P t (nominationSites_length_le D hw hc labels hd
+ (Nat.add_sub_of_le S.degree_bounds.1) g t clock)
+
+/-- The reordered leaf choices still decompose into the actual DFS jobs
+on the selected history, with all increments supplied by internal maps. -/
+theorem nominationSelected_jobs :
+ let X := scanInput labels hd S e w
+ let E := B.execute g hg T hT X
+ let P := nominationSites D hw hc labels hd (Nat.add_sub_of_le S.degree_bounds.1) g t clock
+ ∀ z : E.Choices, let c := E.termChain (B.records g hg T hT X) z
+ let r := selectedParsers B g hg T hT X z
+ ∀ (ptr : RowPointers c) (leaves : X.network.Site → ℕ × ℕ),
+ JobsSpec (finalParsers c r P) (chainTrees c r ptr (fun v => leafTree (leaves v)))
+ (vertexJobs c r ptr P leaves) := by
+ intro X E P z c r ptr leaves
+ exact vertexJobs_spec c r ptr P leaves
+
+variable {ww pp rr kk : ℕ} (M : Machine ww pp rr kk) (pc : Fin 10 → Fin pp) (reg : Fin 2 ↪ Fin rr)
+ (first : Fin kk) (done : Fin pp) (hl : FinalBits.Linked M pc reg first done) (entry : M.entry = pc 0)
+ (low : ℕ) (pub : M.publicData first = FinalBits.cursor ww low 0) (extra : ℕ)
+ (memory : (B.execute g hg T hT (scanInput labels hd S e w)).Choices → Memory ww)
+ (fit : ∀ z : (B.execute g hg T hT (scanInput labels hd S e w)).Choices,
+ low + ((B.execute g hg T hT (scanInput labels hd S e w)).finalState z).totalWidth < 2^ww)
+
+/-- The stack nomination streams and native shared-arc calls for the
+same auxiliary coefficient counter. -/
+noncomputable def nominationTrace :
+ TraceEncoding (compressedRAMCount B g hg D.machine D.fuel 0 D.initial hw hc labels hd T hT).Choice :=
+ let X := scanInput labels hd S e w
+ let E := B.execute g hg T hT X
+ let P := nominationSites D hw hc labels hd (Nat.add_sub_of_le S.degree_bounds.1) g t clock
+ scanTrace E.history (B.executeWitnesses g hg T hT X) (executeReaders B g hg T hT X)
+ (executionScanPhases X M pc reg first done hl entry low pub extra E memory fit) P.factors P.witnesses P.read
+
+variable (inputs : WorkerInputs (B.execute g hg T hT (scanInput labels hd S e w))
+ (executeOrigins B g hg T hT (scanInput labels hd S e w)) ww)
+
+/-- The same stack leaves with full-width ordinal-worker tapes. -/
+noncomputable def nominationReindex :
+ SelectorReindex (nominationTrace D hw hc labels hd t clock B g hg T hT M pc reg first done hl entry low pub extra memory fit) :=
+ let X := scanInput labels hd S e w
+ let E := B.execute g hg T hT X
+ let P := nominationSites D hw hc labels hd (Nat.add_sub_of_le S.degree_bounds.1) g t clock
+ executionReindex X M pc reg first done hl entry low pub extra E _
+ (repeatReaders (blockReaders B g hg) _ T lanes (Nat.add_sub_of_le hT).symm X)
+ (executeOrigins B g hg T hT X) inputs P memory fit
+
+theorem nominationReindex_sum :
+ let W := compressedRAMCount B g hg D.machine D.fuel 0 D.initial hw hc labels hd T hT
+ let C := nominationReindex D hw hc labels hd t clock B g hg T hT M pc reg first done hl entry low pub extra memory fit inputs
+ letI := Fintype.ofEquiv W.Choice C.decode.symm
+ ∑ x : Set.range C.emit, Diagonal.labelMonomial g (W.exponents (C.decode x)) =
+ (Nat.card (ActualPaths D.machine.program D.fuel 0 (RAMMemory.initialMemory (2^d) D.initial)
+ (withinCaps (2^d) (2^e))) : R) := by
+ intro W C
+ let := Fintype.ofEquiv W.Choice C.decode.symm
+ exact (Fintype.sum_equiv C.decode _ _ fun _ => rfl).trans W.evaluates
+
+end Compression
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationNominationData.lean b/lean/OAI/Computability/VPVNP/PairSimulationNominationData.lean
new file mode 100644
index 0000000000..ef9e57253f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationNominationData.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.PairSimulationOrdinalData
+import OAI.Computability.VPVNP.PairSimulationNominationJobs
+
+/-! # Complete native ordinal phase data for the virtual nomination counter -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords Compression BurstRAM BurstRAM.PrivateRAM CursorNetwork CursorRouting
+open scoped Classical
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {A : Type*} [CommRing A] {d e w n a H s b l : ℕ} [NeZero d]
+ {L : PrimedInputRAM.Lengths} {Q : PrimedInputRAM.Layout L n a H w} (D : PrimedCounter.Data Q s)
+ (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (labels : Fin d ≃ Fin b ⊕ Fin l) (hD : 1 < d)
+ (t : ℕ) (clock : NominationClock D hw hc t) (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) (T : ℕ) (hT : T * S.laneBits ≤ l)
+ {ww pp rr kk : ℕ} (N : Machine ww pp rr kk) (pc : Fin 10 → Fin pp) (reg : Fin 2 ↪ Fin rr)
+ (base : Fin kk) (done : Fin pp) (hl : FinalBits.Linked N pc reg base done) (he : N.entry = pc 0)
+ (low : ℕ) (pub : N.publicData base = FinalBits.cursor ww low 0) (extra : ℕ)
+ (memory : (B.execute f hf T hT (scanInput labels hD S e w)).Choices → Memory ww)
+ (fit : ∀ z : (B.execute f hf T hT (scanInput labels hD S e w)).Choices,
+ low + ((B.execute f hf T hT (scanInput labels hD S e w)).finalState z).totalWidth < 2 ^ ww)
+ (inputs : WorkerInputs (B.execute f hf T hT (scanInput labels hD S e w))
+ (executeOrigins B f hf T hT (scanInput labels hD S e w)) ww)
+
+local notation "X" => scanInput labels hD S e w
+local notation "E" => B.execute f hf T hT X
+local notation "P" => nominationSites D hw hc labels hD (Nat.add_sub_of_le (And.left S.degree_bounds)) f t clock
+local notation "readers" => repeatReaders (blockReaders B f hf) _ T l (Eq.symm (Nat.add_sub_of_le hT)) X
+local notation "origin" => executeOrigins B f hf T hT X
+local notation "records" => B.records f hf T hT X
+local notation "R" => nominationReindex D hw hc labels hD t clock B f hf T hT N pc reg base done hl he low pub extra memory fit inputs
+
+/-- Complete terminal data for each selected chronological descriptor branch
+of the actual virtual coefficient counter, including its legal shared scan
+and independently selected site histories. -/
+noncomputable abbrev NominationData (z : (E).Choices) :=
+ BranchData X N pc reg base done hl he low pub extra E _ readers records P memory fit z
+
+/-- Every combination of a legal descriptor selection, a shared payload and
+independent valid site histories occurs exactly once in the ordinal image. -/
+noncomputable def nominationDataEquiv :
+ ((z : (E).Choices) × NominationData D hw hc labels hD t clock B f hf T hT N pc reg base done hl he low pub extra memory fit z) ≃
+ Set.range (R).emit :=
+ ordinalDataEquiv X N pc reg base done hl he low pub extra E _ readers origin inputs records P memory fit
+
+set_option maxHeartbeats 1200000 in
+/-- Exact descriptor and arc calls, per-site preorder tapes, and exponents
+of the recovered monomial choice, on the same selected terminal datum. -/
+theorem nominationData_jobs :
+ ∀ z : (E).Choices, let Y := (E).finalState z
+ let scan := stateScanPhase Y N pc reg base done hl he low pub (memory z) extra (fit z)
+ let c := (E).termChain records z
+ let r := selectedParsers B f hf T hT X z
+ ∀ x : TerminalData scan (finalParsers c r P),
+ let p := nominationDataEquiv D hw hc labels hD t clock B f hf T hT N pc reg base done hl he low pub extra memory fit inputs ⟨z,x⟩
+ let mon := compressedRAMCount B f hf D.machine D.fuel 0 D.initial hw hc labels hD T hT
+ p.val.termCalls = ordinalTapes E origin inputs z ∧ p.val.arcCalls = scan.calls x.arcs ∧
+ ∀ (ptr : RowPointers c) (leaves : (X).network.Site → ℕ × ℕ),
+ let jobs := vertexJobs c r ptr P leaves
+ p.val.vertices = List.ofFn (fun j => (x.jobs jobs ((siteOrder Y).entries j)).flatMap VertexJob.bits) ∧
+ ∀ label, mon.exponents ((R).decode p) label = ∑ v, ((x.jobs jobs v).map (fun j => j.increment label)).sum := by
+ intro z Y scan c r x p mon
+ refine ⟨rfl,rfl,fun ptr leaves => ?_⟩
+ let hs := vertexJobs_spec c r ptr P leaves
+ have hp := ordinalDataEquiv_exponents X N pc reg base done hl he low pub extra E _ readers origin inputs records P memory fit z x
+ exact ⟨x.jobBits _ _ hs (siteOrder Y) (selectorCodes E _ readers z),
+ fun label => (congrFun hp label).trans (x.jobPowers _ _ hs label)⟩
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationNominationJobs.lean b/lean/OAI/Computability/VPVNP/PairSimulationNominationJobs.lean
new file mode 100644
index 0000000000..9c6651d4eb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationNominationJobs.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.PairSimulationNominationAssembly
+import OAI.Computability.VPVNP.PairSimulationTraceJobs
+
+/-!
+# One selected job family for every native nomination trace
+
+The physical term tapes select the same branch used to interpret the
+shared native arc calls. On its output graph the four-half-wire validator
+uses the tagged nomination stream. The private vertex strings and the
+global exponent vector come from precisely these preorder jobs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords Compression BurstRAM BurstRAM.PrivateRAM CursorNetwork CursorRouting
+open scoped Classical
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) {A : Type*} [CommRing A]
+ (f : B.Entry → A) (hf : B.IsSolution f) {d e w n a H s b l : ℕ} [NeZero d]
+ {L : PrimedInputRAM.Lengths} {Q : PrimedInputRAM.Layout L n a H w} (D : PrimedCounter.Data Q s)
+ (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (labels : Fin d ≃ Fin b ⊕ Fin l) (hD : 1 < d)
+ (t : ℕ) (clock : NominationClock D hw hc t) (T : ℕ) (hT : T * S.laneBits ≤ l)
+ {ww pp rr kk : ℕ} (N : Machine ww pp rr kk) (pc : Fin 10 → Fin pp) (reg : Fin 2 ↪ Fin rr)
+ (base : Fin kk) (done : Fin pp) (hl : FinalBits.Linked N pc reg base done) (he : N.entry = pc 0)
+ (low : ℕ) (pub : N.publicData base = FinalBits.cursor ww low 0) (extra : ℕ)
+ (memory : (B.execute f hf T hT (scanInput labels hD S e w)).Choices → Memory ww)
+ (fit : ∀ z : (B.execute f hf T hT (scanInput labels hD S e w)).Choices,
+ low + ((B.execute f hf T hT (scanInput labels hD S e w)).finalState z).totalWidth < 2 ^ ww)
+ (inputs : WorkerInputs (B.execute f hf T hT (scanInput labels hD S e w))
+ (executeOrigins B f hf T hT (scanInput labels hD S e w)) ww)
+
+theorem nominationOrdinal_jobs :
+ let X := scanInput labels hD S e w
+ let E := B.execute f hf T hT X
+ let origin := executeOrigins B f hf T hT X
+ let P := nominationSites D hw hc labels hD (Nat.add_sub_of_le S.degree_bounds.1) f t clock
+ let W := compressedRAMCount B f hf D.machine D.fuel 0 D.initial hw hc labels hD T hT
+ let R := nominationReindex D hw hc labels hD t clock B f hf T hT N pc reg base done hl he low pub extra memory fit inputs
+ ∀ p : Set.range R.emit, ∃ z : E.Choices,
+ let Y := E.finalState z
+ let scan := stateScanPhase Y N pc reg base done hl he low pub (memory z) extra (fit z)
+ let c := E.termChain (B.records f hf T hT X) z
+ let r := selectedParsers B f hf T hT X z
+ ∃ x : TerminalData scan (finalParsers c r P),
+ p.val.termCalls = ordinalTapes E origin inputs z ∧ p.val.arcCalls = scan.calls x.arcs ∧
+ ∀ (ptr : RowPointers c) (leaves : X.network.Site → ℕ × ℕ),
+ let jobs := vertexJobs c r ptr P leaves
+ p.val.vertices = List.ofFn (fun j => (x.jobs jobs ((siteOrder Y).entries j)).flatMap VertexJob.bits) ∧
+ ∀ label, W.exponents (R.decode p) label = ∑ v, ((x.jobs jobs v).map (fun j => j.increment label)).sum := by
+ intro X E origin P W R p
+ let readers := repeatReaders (blockReaders B f hf) _ T l (Nat.add_sub_of_le hT).symm X
+ obtain ⟨q,hq⟩ := p.prop
+ obtain ⟨z,x,hph,hpow⟩ := executionTrace_jobs X N pc reg base done hl he low pub extra E _ readers
+ (B.records f hf T hT X) P memory fit q
+ have e := executionReindex_emit X N pc reg base done hl he low pub extra E _ readers origin inputs P memory fit q z
+ (congrArg Phases.selectors hph)
+ change R.emit q = _ at e
+ rw [hq] at e
+ have dec := R.decode_emit q
+ have heq : (⟨R.emit q,q,rfl⟩ : Set.range R.emit) = p := Subtype.ext hq
+ rw [heq] at dec
+ refine ⟨z,x,congrArg OrdinalPhases.termCalls e,(congrArg OrdinalPhases.arcCalls e).trans (congrArg Phases.arcCalls hph),
+ fun ptr leaves => ?_⟩
+ let hs := vertexJobs_spec (E.termChain (B.records f hf T hT X) z) (selectedParsers B f hf T hT X z) ptr P leaves
+ exact ⟨((congrArg OrdinalPhases.vertices e).trans (congrArg Phases.vertices hph)).trans (x.jobBits _ _ hs _ _),
+ fun label => (congrArg (fun c => W.exponents c label) dec).trans ((congrFun hpow label).trans (x.jobPowers _ _ hs label))⟩
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationOrdinalData.lean b/lean/OAI/Computability/VPVNP/PairSimulationOrdinalData.lean
new file mode 100644
index 0000000000..b8feb8fac9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationOrdinalData.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalDataComplete
+import OAI.Computability.VPVNP.PairSimulationSelectorReindex
+
+/-!
+# Physical ordinal emissions and dependent terminal data
+
+An emitted sequence determines its descriptor branch, shared-arc payload
+and all independent site witnesses. Conversely every such combination
+produces an emission. The inverse recovers the branch used by the actual
+ordinal workers, including the physical order of the shared and site tapes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords Compression BurstRAM BurstRAM.PrivateRAM
+open scoped Classical
+
+private theorem terminal_injective {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {N : Network}
+ {scan : ScanPhase N} {P : SiteParsers κ N} (o : Order N.Site) (sels : List (List Bool)) :
+ Function.Injective (fun x : TerminalData scan P => x.phases o sels) := by
+ rintro ⟨a,x⟩ ⟨b,y⟩ h
+ obtain rfl : a=b := scan.calls_injective (congrArg Phases.arcCalls h)
+ have hv := congrArg Phases.vertices h
+ have each := List.ofFn_inj.mp hv
+ congr 1
+ funext v
+ obtain ⟨j,rfl⟩ := o.entries.surjective v
+ exact (P.read (o.entries j) _).completeEquiv.injective (Subtype.ext (congrFun each j))
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} {B : S.Templates} {A : Type*} [CommRing A]
+ {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w ww p r k : ℕ} (X : State a g)
+ (M : Machine ww p r k) (pc : Fin 10 → Fin p) (reg : Fin 2 ↪ Fin r) (base : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg base done) (he : M.entry = pc 0) (low : ℕ)
+ (pub : M.publicData base = FinalBits.cursor ww low 0) (extra : ℕ)
+ (E : StateExecution A b n X) (W : E.MapWitnesses f) (rds : ExecutionReaders E W)
+ (origin : PassOrigins B f hf E) (inputs : WorkerInputs E origin w) (rec : E.Records) (P : SiteParsers f X.network)
+ (memory : E.Choices → Memory ww) (fit : ∀ z, low + (E.finalState z).totalWidth < 2^ww)
+
+/-- One descriptor selection, the corresponding physical final-arc scan,
+and one site witness at every vertex of its selected output network. -/
+noncomputable abbrev BranchData (z : E.Choices) :=
+ TerminalData (stateScanPhase (E.finalState z) M pc reg base done hl he low pub (memory z) extra (fit z))
+ (terminalSites E W rds rec P z)
+
+local notation "Data" => BranchData X M pc reg base done hl he low pub extra E W rds rec P memory fit
+local notation "R" => executionReindex X M pc reg base done hl he low pub extra E W rds origin inputs P memory fit
+
+/-- Emit the selected branch's physical ordinal-worker tapes together with the final shared-arc
+calls and the vertex tapes in site order. -/
+noncomputable def ordinalDataPhases (z : E.Choices) (x : Data z) : OrdinalPhases :=
+ let phases := x.phases (siteOrder (E.finalState z)) (selectorCodes E W rds z)
+ ⟨ordinalTapes E origin inputs z,phases.arcCalls,phases.vertices⟩
+
+local notation "emit" => ordinalDataPhases X M pc reg base done hl he low pub extra E W rds origin inputs rec P memory fit
+
+private theorem emit_mem (z : E.Choices) (x : Data z) : emit z x ∈ Set.range (R).emit := by
+ let phases := x.phases (siteOrder (E.finalState z)) (selectorCodes E W rds z)
+ have hp := terminalData_emits X M pc reg base done hl he low pub extra E W rds rec P memory fit z x
+ refine ⟨⟨phases,hp⟩,?_⟩
+ exact executionReindex_emit X M pc reg base done hl he low pub extra E W rds origin inputs P memory fit _ z rfl
+
+private theorem emit_injective : Function.Injective (fun y : (z : E.Choices) × Data z => emit y.1 y.2) := by
+ rintro ⟨z,x⟩ ⟨z',x'⟩ h
+ obtain rfl : z=z' := ordinalTapes_injective E origin inputs (congrArg OrdinalPhases.termCalls h)
+ apply congrArg (Sigma.mk z)
+ apply terminal_injective (siteOrder (E.finalState z)) (selectorCodes E W rds z)
+ exact congrArg₂ (Phases.mk (selectorCodes E W rds z)) (congrArg OrdinalPhases.arcCalls h) (congrArg OrdinalPhases.vertices h)
+
+private theorem emit_onto (p : Set.range (R).emit) : ∃ z, ∃ x : Data z, emit z x = p.val := by
+ obtain ⟨q,hq⟩ := p.prop
+ obtain ⟨z,x,hx,_⟩ := executionTrace_jobs X M pc reg base done hl he low pub extra E W rds rec P memory fit q
+ refine ⟨z,x,?_⟩
+ have h := executionReindex_emit X M pc reg base done hl he low pub extra E W rds origin inputs P memory fit q z
+ (congrArg Phases.selectors hx)
+ rw [hq,hx] at h
+ exact h.symm
+
+/-- A genuine equivalence in both directions, independent of any physical
+acceptance assertion for the online calendar or terminal interpreter. -/
+noncomputable def ordinalDataEquiv : ((z : E.Choices) × Data z) ≃ Set.range (R).emit :=
+ Equiv.ofBijective (fun y => ⟨emit y.1 y.2,emit_mem X M pc reg base done hl he low pub extra E W rds origin inputs rec P memory fit y.1 y.2⟩)
+ ⟨fun _ _ h => emit_injective X M pc reg base done hl he low pub extra E W rds origin inputs rec P memory fit (congrArg Subtype.val h),
+ fun p => by obtain ⟨z,x,h⟩ := emit_onto X M pc reg base done hl he low pub extra E W rds origin inputs rec P memory fit p
+ exact ⟨⟨z,x⟩,Subtype.ext h⟩⟩
+
+/-- The three chronological fields of the physical ordinal emission. -/
+theorem ordinalDataEquiv_apply (z : E.Choices) (x : Data z) :
+ (ordinalDataEquiv X M pc reg base done hl he low pub extra E W rds origin inputs rec P memory fit ⟨z,x⟩).val =
+ emit z x := rfl
+
+set_option maxHeartbeats 1200000 in
+/-- The decoded global exponent is exactly the sum of the selected site's
+witness exponents in this very terminal occurrence. -/
+theorem ordinalDataEquiv_exponents (z : E.Choices) (x : Data z) :
+ let p := ordinalDataEquiv X M pc reg base done hl he low pub extra E W rds origin inputs rec P memory fit ⟨z,x⟩
+ (E.history.expandedWitness (E.historyWitnesses W) P.factors P.witnesses).exponents ((R).decode p) = x.exponents := by
+ intro p
+ obtain ⟨q,hq⟩ := p.prop
+ obtain ⟨z',x',hx,hpow⟩ := executionTrace_jobs X M pc reg base done hl he low pub extra E W rds rec P memory fit q
+ have h := executionReindex_emit X M pc reg base done hl he low pub extra E W rds origin inputs P memory fit q z'
+ (congrArg Phases.selectors hx)
+ rw [hq,hx] at h
+ have eq : (⟨z,x⟩ : (z : E.Choices) × Data z) = ⟨z',x'⟩ :=
+ emit_injective X M pc reg base done hl he low pub extra E W rds origin inputs rec P memory fit h
+ have powers := congrArg (fun y : (z : E.Choices) × Data z => y.2.exponents) eq
+ have same : (⟨(R).emit q,q,rfl⟩ : Set.range (R).emit) = p := Subtype.ext hq
+ rw [← same,SelectorReindex.decode_emit]
+ exact hpow.trans powers.symm
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationPhysicalRootGather.lean b/lean/OAI/Computability/VPVNP/PairSimulationPhysicalRootGather.lean
new file mode 100644
index 0000000000..0f223b0f0e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationPhysicalRootGather.lean
@@ -0,0 +1,183 @@
+import OAI.Computability.VPVNP.PairSimulationPhysicalScanData
+import OAI.Computability.VPVNP.PairTerminalGatherNative
+import OAI.Computability.VPVNP.PairTerminalGatherReadSafety
+
+/-!
+# Gathering the chosen terminal payload into the private root packet
+
+The three incidence directories precede the shared-bit bank. The completed
+physical bit phase preserves those rows and writes each bit once. Its outgoing
+and incoming gathers use that same bank, with the inverse directory selecting
+the source of each incoming slot.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.PhysicalScanData
+
+open BurstRAM PrivateRAM Compression CompressorRecords LocalHistory TerminalLink
+open TerminalGatherGeometry TerminalRootGather
+open scoped Fin.CommRing
+
+open private incidence_end_le from OAI.Computability.VPVNP.CompressorDescriptorSpace
+
+/-- On the selected descriptor layout the inverse and width columns are
+packed at columns 4 and 5 of the last level. Its prefix table also ends
+before the final wire bank, even when that level has no arcs. -/
+theorem packed_heads (D : DescriptorSpace.Layout) (last : Fin D.levels)
+ (tab : Fin D.shape.tables) (L : Layout) (n : ℕ) (slots : n ≤ DescriptorSpace.slotCapacity D)
+ (cells : n ≤ DescriptorSpace.tableWords D)
+ (inverse : L.incomingHead = DescriptorSpace.incidenceBase D last n 4)
+ (widths : L.widthHead = DescriptorSpace.incidenceBase D last n 5)
+ (starts : L.prefixHead = DescriptorSpace.tableBase D last tab)
+ (wireBase : DescriptorSpace.endAddress D ≤ L.wires) :
+ ∀ h ∈ [L.incomingHead, L.widthHead, L.prefixHead], h + n ≤ L.wires := by
+ have next := (DescriptorSpace.levelStart_mono D last.isLt).trans wireBase
+ have array := (incidence_end_le D last).trans next
+ have prefixEnd := (DescriptorSpace.tableEnd_le_nextLevel D last tab).trans next
+ have bound := Nat.mul_le_mul_left 6 slots
+ change DescriptorSpace.incidenceStart D last + 6 * DescriptorSpace.slotCapacity D ≤ _ at array
+ intro h hh
+ simp only [List.mem_cons, List.not_mem_nil, or_false] at hh
+ rcases hh with rfl | rfl | rfl
+ · rw [inverse]
+ change DescriptorSpace.incidenceStart D last + 4 * n + n ≤ _
+ omega
+ · rw [widths]
+ change DescriptorSpace.incidenceStart D last + 5 * n + n ≤ _
+ omega
+ · rw [starts]
+ omega
+
+variable {a g w p r k : ℕ} (X : State a g)
+ (M : Machine w p r k) (pc : Fin 10 → Fin p) (reg : Fin 2 ↪ Fin r) (base : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg base done) (he : M.entry = pc 0)
+ (low : ℕ) (pub : M.publicData base = FinalBits.cursor w low 0) (m : Memory w) (extra : ℕ)
+ (fit : low + X.totalWidth < 2 ^ w)
+
+local notation "scan" => stateScanPhase X M pc reg base done hl he low pub m extra fit
+local notation "bits" => assignment X M pc reg base done hl he low pub m extra fit
+
+variable {width : ℕ} (F : DescriptorSpace.Shape) (limit : ℕ)
+ (S : VertexImage.Part → VertexImage.Segment) (ops : Fin 11 → Word width) (cap : ℕ)
+ {input : Memory width} (q : QuietPrefix (TerminalProgram.workers F limit S) ops cap input)
+ (src : Memory width) (L : Layout) (layout : FinalBits.Worker.Layout ops src L.wires X.totalWidth)
+ (clock : 54 ≤ cap) (room : (header ops).val + 32 ≤ 2 ^ width)
+ (below : L.wires + X.totalWidth ≤ (header ops).val)
+ (agree : SourceTransport.Agree (workerCell (header ops)) src q.traversalRows.val.memory)
+
+local notation "bank" => physical X M pc reg base done hl he low pub m extra fit F limit S
+ ops cap src q.traversalRows.val.memory L.wires layout clock room below agree
+
+/-- The fourth block of this quiet prefix is indexed by the nomination's data path. -/
+noncomputable def bitPaths : (scan).Path ≃ q.BitPaths := bank
+
+variable (valid : (Entry.resume Stage.sharedBits (0 : Word width)).Valid
+ (header ops) q.traversalRows.val.memory)
+
+local notation "arrayBits" => fun x i =>
+ bits x (Fin.cast (TerminalPrefix.width_sum X) i)
+
+include valid in
+private theorem bank_read (x : (scan).Path) (i : Fin (∑ j, TerminalPrefix.width X j)) :
+ (bank x).val.memory (L.wires + i.val) = PrivateFields.bitValue width (arrayBits x i) :=
+ SharedBitPhase.readback F limit S ops cap src _ layout clock room below agree valid _
+ (Fin.cast (TerminalPrefix.width_sum X) i)
+
+variable (rows : Rows X L src)
+ (heads : ∀ h ∈ [L.incomingHead, L.widthHead, L.prefixHead],
+ h + TerminalPrefix.arcCount X ≤ L.wires)
+
+include valid rows heads
+
+/-- All three gathered directories keep their source entries through the linked shared-bit phase. -/
+theorem rows_after_bits (x : (scan).Path) : Rows X L (bank x).val.memory := by
+ apply rows.transfer
+ intro h hh i
+ have head := heads h hh
+ have hi := i.isLt
+ have lt : h + i.val < L.wires := by omega
+ have h31 : (header ops + 31).val = (header ops).val + 31 := by
+ rw [Fin.val_add]
+ change ((header ops).val + 31 % (2 ^ width)) % (2 ^ width) = _
+ rw [Nat.mod_eq_of_lt (by omega : 31 < 2 ^ width), Nat.mod_eq_of_lt (by omega)]
+ have data : workerCell (header ops) (h + i.val) := ⟨by omega, by omega⟩
+ have image := SharedBitPhase.memory_image F limit S ops cap src _ layout clock room below
+ agree valid (bits x)
+ exact (image _ data).symm.trans (FinalBits.outside L.wires layout.fits _ src _ (.inl lt))
+
+variable {v : X.network.Site} (num : Numbering X L v)
+
+include num
+
+local notation "argument(" x ")" => NodeArguments.packed X v
+ (WireTensor.edgeAssignment X.network.src X.network.dst (ScanPhase.payload scan x) v)
+
+/-- The root packet includes both endpoint slots of a loop, as well as
+every slot of parallel arcs and every empty field of a zero-width arc. -/
+theorem packet (x : (scan).Path) : L.packet (bank x).val.memory =
+ (argument(x)).map (PrivateFields.bitValue width) := by
+ have rr := rows_after_bits X M pc reg base done hl he low pub m extra fit F limit S
+ ops cap q src L layout clock room below agree valid rows heads x
+ have read := bank_read X M pc reg base done hl he low pub m extra fit F limit S
+ ops cap q src L layout clock room below agree valid x
+ rw [payload X M pc reg base done hl he low pub m extra fit x]
+ exact packet_eq num rr (arrayBits x) read
+
+/-- The linked root-gather instruction sequence installs the nomination's
+argument in the private store and reaches the DFS continuation. -/
+theorem native_root_reads {P T : ℕ} {host : Machine width P T 11} {labels : PC → Fin P}
+ {regs : Reg ↪ Fin T} {exit : Fin P} (code : Linked host labels regs exit)
+ (destFit : L.dest + TerminalGatherNative.argumentSize X v < 2 ^ width)
+ (x : (scan).Path) (c : Config width P T) (hc : c.pc = labels (.boot 0))
+ (saved : Saved L regs c) (hn : host.publicData 6 = (L.n : Word width))
+ (stride : c.privateMem (c.privateMem (L.n : Word width) + 7) = (L.stride : Word width)) :
+ ∃ out es, out.pc = exit ∧ Frame regs c out ∧
+ out.privateMem = PrivateFields.storeBits L.dest argument(x) c.privateMem ∧
+ Cost es (15 + 21 * 2 ^ a + 5 * TerminalGatherNative.argumentSize X v)
+ (5 * 2 ^ a + TerminalGatherNative.argumentSize X v) ∧
+ SourceTransport.Reads (workerCell (header ops)) es ∧
+ Prefix host (bank x).val.memory c es out := by
+ have rr := rows_after_bits X M pc reg base done hl he low pub m extra fit F limit S
+ ops cap q src L layout clock room below agree valid rows heads x
+ have read := bank_read X M pc reg base done hl he low pub m extra fit F limit S
+ ops cap q src L layout clock room below agree valid x
+ have bound := layout.fits
+ have countFit : TerminalPrefix.arcCount X < 2 ^ width := by
+ have h := heads L.widthHead (by simp)
+ omega
+ have enough := fits num rr (arrayBits x) read countFit
+ (fun h hh => (heads h hh).trans (by omega)) bound destFit
+ have allowed := worker_readable num rr (header ops) (by omega)
+ (fun h hh => (heads h hh).trans (by omega)) below
+ obtain ⟨out, es, ret, frame, image, cost, reads, run⟩ :=
+ TerminalRootGather.run_reads code L _ enough c hc saved hn stride _ allowed
+ rw [payload X M pc reg base done hl he low pub m extra fit x]
+ refine ⟨out, es, ret, frame, image.trans (placed_packet num rr _ read enough _), ?_, reads, run⟩
+ simpa only [num.degree, packet_eq num rr _ read, List.length_map, NodeArguments.packed_length,
+ TerminalGatherNative.argumentSize] using cost
+
+/-- Private memory and the remaining branch stream at the root DFS continuation. -/
+theorem native_root {P T : ℕ} {host : Machine width P T 11} {labels : PC → Fin P}
+ {regs : Reg ↪ Fin T} {exit : Fin P} (code : Linked host labels regs exit)
+ (destFit : L.dest + TerminalGatherNative.argumentSize X v < 2 ^ width)
+ (x : (scan).Path) (c : Config width P T) (hc : c.pc = labels (.boot 0))
+ (saved : Saved L regs c) (hn : host.publicData 6 = (L.n : Word width))
+ (stride : c.privateMem (c.privateMem (L.n : Word width) + 7) = (L.stride : Word width)) :
+ ∃ out es, out.pc = exit ∧ Frame regs c out ∧
+ out.privateMem = PrivateFields.storeBits L.dest argument(x) c.privateMem ∧
+ Cost es (15 + 21 * 2 ^ a + 5 * TerminalGatherNative.argumentSize X v)
+ (5 * 2 ^ a + TerminalGatherNative.argumentSize X v) ∧
+ Prefix host (bank x).val.memory c es out := by
+ obtain ⟨out, es, ret, frame, image, cost, _, run⟩ :=
+ native_root_reads X M pc reg base done hl he low pub m extra fit F limit S ops cap q src L
+ layout clock room below agree valid rows heads num code destFit x c hc saved hn stride
+ exact ⟨out, es, ret, frame, image, cost, run⟩
+
+end PairSimulation.PhysicalScanData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationPhysicalRootRows.lean b/lean/OAI/Computability/VPVNP/PairSimulationPhysicalRootRows.lean
new file mode 100644
index 0000000000..09e222d083
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationPhysicalRootRows.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.PairSimulationPhysicalRootGather
+import OAI.Computability.VPVNP.PairTerminalPrefixLayout
+import OAI.Computability.VPVNP.PairTraversalArena
+
+/-!
+# The endpoint directories in the selected traversal arena
+
+The prefix worker publishes the start of every outgoing arc. Its final write
+to the role header avoids the six incidence columns. The next stage writes
+the descriptor rows and role tags above the selected level's tables, so the
+endpoint gather sees the same inverse, width and prefix values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.PhysicalScanData
+
+open BurstRAM PrivateRAM Compression CompressorRecords TerminalGatherGeometry
+open TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+variable {a g w : ℕ} (X : State a g) (L : TerminalRootGather.Layout)
+ (D : DescriptorSpace.Layout) (last : Fin D.levels) (tab : Fin D.shape.tables)
+
+open private transfer_incidence from OAI.Computability.VPVNP.PairTerminalPrefixLayout
+
+/-- The bootstrap of the terminal header preserves the selected state's
+packed incidence columns used by the prefix worker. -/
+theorem columns_after_bootstrap (A : TerminalBootstrap.Header D last) (limit rad : ℕ)
+ (pub : Fin 11 → Word w) (m : Memory w) (ready : TerminalBootstrap.Ready D last A pub m)
+ (exp : (pub 7).val = rad) (hr : rad < w) (reserve : 32 ≤ D.base + 2 ^ rad * 2 ^ rad)
+ (room : D.base + 2 ^ rad * 2 ^ rad ≤ 2 ^ w)
+ (above : DescriptorSpace.endAddress D ≤ TerminalBootstrap.address D.base rad)
+ (slots : TerminalPrefix.arcCount X ≤ DescriptorSpace.slotCapacity D)
+ (columns : (DescriptorSpace.packedIncidence D w last (TerminalPrefix.arcCount X)).ActualColumns
+ X m) :
+ (DescriptorSpace.packedIncidence D w last (TerminalPrefix.arcCount X)).ActualColumns X
+ (after m (TerminalBootstrap.report D.shape limit pub 0 m).events) := by
+ obtain ⟨_, _, _, keep, _⟩ :=
+ TerminalBootstrap.native D last A limit pub m 0 ready rad exp hr reserve room
+ exact transfer_incidence D last X _ rfl slots above
+ (by unfold TerminalBootstrap.address; omega) columns (fun x hx => keep x (.inl hx))
+
+/-- Recover the three gather columns from the complete native prefix run,
+including its closing publication in header word 14. -/
+theorem prefix_rows (pub : Fin 11 → Word w) (m : Memory w) (rs : List (Report w))
+ (end_le : DescriptorSpace.endAddress D ≤ (TerminalLink.header pub).val)
+ (room : (TerminalLink.header pub).val + 32 ≤ 2 ^ w)
+ (slots : TerminalPrefix.arcCount X ≤ DescriptorSpace.slotCapacity D)
+ (cells : TerminalPrefix.arcCount X ≤ DescriptorSpace.tableWords D)
+ (inverse : L.incomingHead = DescriptorSpace.incidenceBase D last (TerminalPrefix.arcCount X) 4)
+ (widths : L.widthHead = DescriptorSpace.incidenceBase D last (TerminalPrefix.arcCount X) 5)
+ (starts : L.prefixHead = DescriptorSpace.tableBase D last tab)
+ (columns : (DescriptorSpace.packedIncidence D w last (TerminalPrefix.arcCount X)).ActualColumns
+ X m)
+ (scan : TerminalPrefix.Segment.Run pub X
+ (DescriptorSpace.packedIncidence D w last (TerminalPrefix.arcCount X))
+ (DescriptorSpace.tableBase D last tab : Word w) m rs) :
+ Rows X L (after m (eventLog rs)) := by
+ let H := TerminalLink.header pub
+ let n := TerminalPrefix.arcCount X
+ let T := DescriptorSpace.packedIncidence D w last n
+ have bound := packed_heads D last tab {L with wires := DescriptorSpace.endAddress D} n
+ slots cells inverse widths starts le_rfl
+ have hi : L.incomingHead + n ≤ DescriptorSpace.endAddress D := bound _ (by simp)
+ have hw : L.widthHead + n ≤ DescriptorSpace.endAddress D := bound _ (by simp)
+ have hs : L.prefixHead + n ≤ DescriptorSpace.endAddress D := bound _ (by simp)
+ have header_at (j : ℕ) (hj : j < 32) : (H + (j : Word w)).val = H.val + j := by
+ change (H.val + j % (2 ^ w)) % (2 ^ w) = _
+ have small : H.val + j < 2 ^ w := by change (TerminalLink.header pub).val + j < _; omega
+ rw [Nat.mod_eq_of_lt (by omega : j < 2 ^ w), Nat.mod_eq_of_lt small]
+ have boundH : DescriptorSpace.endAddress D ≤ H.val := end_le
+ have fit : H.val < 2 ^ w := H.isLt
+ have port : L.incomingHead = T.actualIn.val := by
+ change L.incomingHead = DescriptorSpace.incidenceBase D last n 4 % (2 ^ w)
+ rw [← inverse, Nat.mod_eq_of_lt (by omega)]
+ have width : L.widthHead = T.width.val := by
+ change L.widthHead = DescriptorSpace.incidenceBase D last n 5 % (2 ^ w)
+ rw [← widths, Nat.mod_eq_of_lt (by omega)]
+ have start : L.prefixHead = ((DescriptorSpace.tableBase D last tab : ℕ) : Word w).val := by
+ change L.prefixHead = DescriptorSpace.tableBase D last tab % (2 ^ w)
+ rw [← starts, Nat.mod_eq_of_lt (by omega)]
+ have before : L.incomingHead + n ≤ L.prefixHead := by
+ rw [inverse, starts]
+ change DescriptorSpace.incidenceStart D last + 4 * n + n ≤
+ DescriptorSpace.incidenceStart D last + 6 * DescriptorSpace.slotCapacity D +
+ tab.val * DescriptorSpace.tableWords D
+ have h : n ≤ DescriptorSpace.slotCapacity D := slots
+ omega
+ have sumCell : (H + 12).val = H.val + 12 := header_at 12 (by decide)
+ have roleCell : (H + 14).val = H.val + 14 := header_at 14 (by decide)
+ have old : T.ActualColumns X
+ (writeMemory m (H + 14) (TerminalPrefix.Segment.roleValue pub X m)) :=
+ transfer_incidence D last X n rfl slots boundH fit columns (fun x hx => by
+ rw [writeMemory, ite_eq_right (by omega)])
+ exact rows_of_prefix X L
+ ⟨port, width, start, by omega, Or.inr (by change L.incomingHead + n ≤ (H + 12).val; omega),
+ Or.inl (by rwa [← start])⟩ old scan.stored
+
+/-- The row and role builders preserve the gather directories below their arena. -/
+theorem arena_rows (cap rowBase displacement : ℕ) (roles : List TaggedLayer) (src : Memory w)
+ (rows : Rows X L src) (bounds : ∀ h ∈ [L.incomingHead, L.widthHead, L.prefixHead],
+ h + TerminalPrefix.arcCount X ≤ rowBase) :
+ Rows X L (build cap rowBase rowBase (roles.map TaggedLayer.layer)
+ (writeTags displacement cap rowBase roles src)) := by
+ apply rows.transfer
+ intro h hh i
+ have head := bounds h hh
+ have hi := i.isLt
+ have addr : h + i.val < rowBase := by omega
+ rw [build_outside _ _ _ _ _ _ (.inl addr),
+ write_tags_outside _ _ _ _ _ _ (.inl (addr.trans_le (Nat.le_add_left _ _)))]
+
+end PairSimulation.PhysicalScanData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationPhysicalScanData.lean b/lean/OAI/Computability/VPVNP/PairSimulationPhysicalScanData.lean
new file mode 100644
index 0000000000..236df0c889
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationPhysicalScanData.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.PairSimulationSharedBitPhase
+import OAI.Computability.VPVNP.PairTerminalGatherGeometry
+
+/-!
+# Wire assignments of the terminal scan in a nomination trace
+
+The earlier data scan makes one singleton choice per wire bit in descending
+address order. The terminal worker appends one empty closing call and writes
+those same bits to the selected physical bank. The construction includes
+empty banks and zero-width edges.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.PhysicalScanData
+
+open BurstRAM PrivateRAM Compression CompressorRecords LocalHistory
+
+variable {a g w p r k : ℕ} (X : State a g)
+ (M : Machine w p r k) (pc : Fin 10 → Fin p) (reg : Fin 2 ↪ Fin r) (base : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg base done) (he : M.entry = pc 0)
+ (low : ℕ) (pub : M.publicData base = FinalBits.cursor w low 0) (m : Memory w) (extra : ℕ)
+ (fit : low + X.totalWidth < 2 ^ w)
+
+local notation "scan" => stateScanPhase X M pc reg base done hl he low pub m extra fit
+
+private def resize {n t : ℕ} (h : n = t) : (Fin n → Bool) ≃ (Fin t → Bool) :=
+ Equiv.arrowCongr (finCongr h) (Equiv.refl Bool)
+
+private theorem calls_resize {n t : ℕ} (h : n = t) (f : Fin n → Bool) :
+ FinalBits.calls (resize h f) = FinalBits.calls f := by cases h; rfl
+
+/-- Enumerate each successful data scan by its complete assignment in the state's address order. -/
+noncomputable def assignment : (scan).Path ≃ (Fin X.totalWidth → Bool) :=
+ (FinalBits.scanEquiv hl he low (∑ i, TerminalPrefix.width X i)
+ (by rwa [TerminalPrefix.width_sum]) pub m extra).symm.trans
+ (resize (TerminalPrefix.width_sum X))
+
+local notation "bits" => assignment X M pc reg base done hl he low pub m extra fit
+
+theorem calls (x : (scan).Path) : (scan).calls x = FinalBits.calls (bits x) := by
+ let read := FinalBits.scanEquiv hl he low (∑ i, TerminalPrefix.width X i)
+ (by rwa [TerminalPrefix.width_sum]) pub m extra
+ change x.val = FinalBits.calls (resize (TerminalPrefix.width_sum X) (read.symm x))
+ rw [calls_resize]
+ exact congrArg Subtype.val (read.apply_symm_apply x).symm
+
+/-- Grouping the flat assignment by outgoing arc gives the payload used by
+the nomination's vertex witnesses. -/
+theorem payload (x : (scan).Path) : (scan).payload x =
+ TerminalGatherGeometry.payload X
+ (fun i => bits x (Fin.cast (TerminalPrefix.width_sum X) i)) := by
+ let read := FinalBits.scanEquiv hl he low (∑ i, TerminalPrefix.width X i)
+ (by rwa [TerminalPrefix.width_sum]) pub m extra
+ have heq : (fun i => bits x (Fin.cast (TerminalPrefix.width_sum X) i)) = read.symm x := by
+ funext i
+ change (read.symm x) (Fin.cast (TerminalPrefix.width_sum X).symm
+ (Fin.cast (TerminalPrefix.width_sum X) i)) = (read.symm x) i
+ rw [Fin.cast_cast, Fin.cast_refl]; rfl
+ rw [heq, ← TerminalGatherGeometry.phase_payload X M pc reg base done hl he low pub m extra fit]
+ exact congrArg (scan).payload (read.apply_symm_apply x).symm
+
+open private payload_bit from OAI.Computability.VPVNP.PairTerminalGatherGeometry
+
+/-- Physical ordinal of a bit within one edge's payload. -/
+def index (e : X.network.Edge) (j : Fin (X.width ((e.1.1, e.2), e.1.2))) : Fin X.totalWidth :=
+ Fin.cast (TerminalPrefix.width_sum X) (FinalBits.index (TerminalPrefix.width X)
+ (TerminalGatherGeometry.number X e) (Fin.cast (TerminalGatherGeometry.scan_width X e).symm j))
+
+theorem payload_bit_eq (x : (scan).Path) (e : X.network.Edge)
+ (j : Fin (X.width ((e.1.1, e.2), e.1.2))) :
+ (scan).payload x e j = bits x (index X e j) := by
+ rw [payload X M pc reg base done hl he low pub m extra fit]
+ exact payload_bit X _ e j
+
+variable {width : ℕ} (F : DescriptorSpace.Shape) (limit : ℕ)
+ (S : VertexImage.Part → VertexImage.Segment) (ops : Fin 11 → Word width) (cap : ℕ)
+ (src phy : Memory width) (lo : ℕ) (layout : FinalBits.Worker.Layout ops src lo X.totalWidth)
+ (clock : 54 ≤ cap) (room : (TerminalLink.header ops).val + 32 ≤ 2 ^ width)
+ (below : lo + X.totalWidth ≤ (TerminalLink.header ops).val)
+ (agree : SourceTransport.Agree (TerminalLink.workerCell (TerminalLink.header ops)) src phy)
+
+/-- Transport nomination data directly to a completed shared-bit record of
+the terminal program, allowing independent word sizes and base addresses. -/
+noncomputable def physical :
+ (scan).Path ≃ TerminalLink.CompletedPhase (TerminalProgram.workers F limit S) ops cap
+ (.resume TerminalLink.Stage.sharedBits 0) phy :=
+ (bits).trans (SharedBitPhase.equiv F limit S ops cap src phy layout clock room below agree)
+
+local notation "linked" => physical X M pc reg base done hl he low pub m extra fit F limit S
+ ops cap src phy lo layout clock room below agree
+
+theorem physical_choices (x : (scan).Path) :
+ (linked x).val.choices = (scan).calls x ++ [[]] := by
+ rw [calls X M pc reg base done hl he low pub m extra fit]
+ rfl
+
+/-- Physical readback from the chosen phase yields the bit of the actual
+payload supplied to both incident vertex witnesses. -/
+theorem physical_payload (x : (scan).Path) (e : X.network.Edge)
+ (j : Fin (X.width ((e.1.1, e.2), e.1.2)))
+ (valid : (TerminalLink.Entry.resume TerminalLink.Stage.sharedBits (0 : Word width)).Valid
+ (TerminalLink.header ops) phy) :
+ (linked x).val.memory (lo + (index X e j).val) = PrimedInputRAM.encodeBit width
+ ((scan).payload x e j) := by
+ rw [payload_bit_eq X M pc reg base done hl he low pub m extra fit]
+ exact SharedBitPhase.readback F limit S ops cap src phy layout clock room below agree valid _ _
+
+end PairSimulation.PhysicalScanData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationPrivateFields.lean b/lean/OAI/Computability/VPVNP/PairSimulationPrivateFields.lean
new file mode 100644
index 0000000000..46db644439
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationPrivateFields.lean
@@ -0,0 +1,346 @@
+import OAI.Computability.VPVNP.PairSimulationHistory
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Private bit fields in a final-site call
+
+A guess writes each consumed branch bit to one private word. A copy uses the
+same storage order and takes each bit from an existing private slice. The two
+fragments accept arbitrary program labels and leave the external memory and
+the registers of the enclosing traversal available to their continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.PrivateFields
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Source of the bits written to a private field. Guess mode consumes branch bits and copy
+mode loads an existing private slice. -/
+inductive Mode
+ | guess | copy
+ deriving DecidableEq
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+private theorem val_word {n : ℕ} (hn : n < 2^w) : (word w n).val = n := Nat.mod_eq_of_lt hn
+
+/-- Each private cell holds the word zero or one. -/
+def bitValue (w : ℕ) (b : Bool) : Word w := if b then 1 else 0
+
+/-- Registers are source cursor, exclusive destination end, destination
+cursor, one and temporary. Only the two cursors and the temporary are written. -/
+def instruction (mode : Mode) (pc : Fin 7 → Fin p) (reg : Fin 5 ↪ Fin r) (done : Fin p) :
+ Fin 7 → Instr w p r k :=
+ ![.jumpEq (reg 2) (reg 1) done (pc 1),
+ (match mode with | .guess => .choose (pc 2) (pc 3) | .copy => .loadPrivate (reg 4) (reg 0) (pc 4)),
+ .constant (reg 4) 1 (pc 4), .constant (reg 4) 0 (pc 4),
+ .storePrivate (reg 2) (reg 4) (pc 5), .binary .add (reg 2) (reg 2) (reg 3) (pc 6),
+ .binary .add (reg 0) (reg 0) (reg 3) (pc 0)]
+
+theorem resize_instruction (mode : Mode) (pc : Fin 7 → Fin p) (reg : Fin 5 ↪ Fin r)
+ (done : Fin p) (i : Fin 7) :
+ (instruction (w := 1) (k := k) mode pc reg done i).resize w = instruction mode pc reg done i := by
+ cases mode <;> fin_cases i <;> rfl
+
+/-- The machine contains the seven instructions of the selected guess or copy loop at the
+specified labels, with the given registers and continuation. -/
+def Linked (M : Machine w p r k) (mode : Mode) (pc : Fin 7 → Fin p) (reg : Fin 5 ↪ Fin r)
+ (done : Fin p) : Prop := ∀ i, M.code (pc i) = instruction mode pc reg done i
+
+/-- A private-memory slice in increasing physical-address order. -/
+def storeBits (dst : ℕ) : List Bool → (Word w → Word w) → Word w → Word w
+ | [], old => old
+ | b :: bs, old => storeBits (dst+1) bs (Function.update old (word w dst) (bitValue w b))
+
+theorem storeBits_outside (dst : ℕ) (bs : List Bool) (old : Word w → Word w) (a : Word w)
+ (fit : dst+bs.length ≤ 2^w) (outside : a.val < dst ∨ dst+bs.length ≤ a.val) :
+ storeBits dst bs old a = old a := by
+ induction bs generalizing dst old with
+ | nil => rfl
+ | cons b bs ih =>
+ simp only [List.length_cons] at fit outside
+ rw [storeBits, ih _ _ (by omega) (by omega)]
+ apply Function.update_of_ne
+ intro he
+ have h := congrArg Fin.val he
+ rw [val_word (by omega : dst < 2^w)] at h
+ omega
+
+theorem storeBits_read (dst : ℕ) (bs : List Bool) (old : Word w → Word w)
+ (fit : dst+bs.length ≤ 2^w) (i : Fin bs.length) :
+ storeBits dst bs old (word w (dst+i.val)) = bitValue w bs[i.val] := by
+ induction bs generalizing dst old with
+ | nil => exact i.elim0
+ | cons b bs ih =>
+ have hfit : dst+bs.length+1 ≤ 2^w := by simpa [Nat.add_assoc] using fit
+ induction i using Fin.cases with
+ | zero =>
+ change storeBits (dst+1) bs (Function.update old (word w dst) (bitValue w b)) (word w dst) = _
+ rw [storeBits_outside _ _ _ _ (by omega) (.inl (by rw [val_word (by omega)]; omega))]
+ exact Function.update_self ..
+ | succ i =>
+ simpa [storeBits, Nat.add_assoc, Nat.add_comm 1] using ih (dst+1) _ (by omega) i
+
+private def headEvents (mode : Mode) (b : Bool) : List (Event w) :=
+ match mode with
+ | .guess => [.tick, .choice b, .tick]
+ | .copy => [.tick, .tick]
+
+/-- The exact local trace, including the final range test. -/
+def events (mode : Mode) : List Bool → List (Event w)
+ | [] => [.tick]
+ | b :: bs => (headEvents mode b ++ [.tick,.tick,.tick]) ++ events mode bs
+
+theorem events_bits (mode : Mode) (bs : List Bool) :
+ choiceBits (events (w := w) mode bs) = if mode = .guess then bs else [] := by
+ cases mode <;> induction bs with
+ | nil => rfl
+ | cons b bs ih => simp [events, headEvents, choiceBits, ih]
+
+theorem events_work (mode : Mode) (bs : List Bool) :
+ (events (w := w) mode bs).length = (if mode = .guess then 6 else 5)*bs.length+1 ∧
+ countProbes (events (w := w) mode bs) = 0 := by
+ cases mode <;> induction bs with
+ | nil => exact ⟨rfl,rfl⟩
+ | cons b bs ih => simp [events, headEvents, countProbes, ih.1, ih.2]; omega
+
+variable {M : Machine w p r k} {mode : Mode} {pc : Fin 7 → Fin p} {reg : Fin 5 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (hl : Linked M mode pc reg done) (i : Fin 7) (c : Config w p r)
+ (hc : c.pc = pc i) : M.program.step c = (instruction mode pc reg done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+/-- Exact state transition for one bit. The copy reads its value before
+either cursor advances. -/
+private theorem iteration (hl : Linked M mode pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (b : Bool) (h1 : c.reg (reg 3) = 1) (hne : c.reg (reg 2) ≠ c.reg (reg 1))
+ (hload : mode = .copy → c.privateMem (c.reg (reg 0)) = bitValue w b) :
+ ∃ out, Prefix M c (headEvents mode b ++ [.tick,.tick,.tick]) out ∧ out.pc = pc 0 ∧
+ out.reg (reg 0) = c.reg (reg 0) + 1 ∧ out.reg (reg 2) = c.reg (reg 2) + 1 ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j) ∧
+ out.privateMem = Function.update c.privateMem (c.reg (reg 2)) (bitValue w b) ∧
+ out.persistent = c.persistent := by
+ let c₁ := {c with pc := pc 1}
+ let loaded := c.put (pc 4) (reg 4) (bitValue w b)
+ let stored := loaded.store (pc 5) (c.reg (reg 2)) (bitValue w b)
+ let next := stored.put (pc 6) (reg 2) (c.reg (reg 2) + 1)
+ let out := next.put (pc 0) (reg 0) (c.reg (reg 0) + 1)
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step_at hl 0 c hc]
+ simp [instruction, Instr.run, hne, c₁]
+ have pre : Prefix M c (headEvents mode b) loaded := by
+ cases mode with
+ | copy =>
+ refine .tick s₀ (.tick ?_ (.nil _))
+ rw [step_at hl 1 c₁ rfl]
+ change CallAction.localStep (c.put (pc 4) (reg 4) (c.privateMem (c.reg (reg 0)))) = _
+ rw [hload rfl]
+ | guess =>
+ have s₁ : M.program.step c₁ = .branch (fun b ↦ {c₁ with pc := if b then pc 2 else pc 3}) :=
+ step_at hl 1 c₁ rfl
+ cases b with
+ | false => exact .tick s₀ (.choice (b := false) s₁ (.tick (step_at hl 3 _ rfl) (.nil _)))
+ | true => exact .tick s₀ (.choice (b := true) s₁ (.tick (step_at hl 2 _ rfl) (.nil _)))
+ have s₄ : M.program.step loaded = .localStep stored := by
+ rw [step_at hl 4 loaded rfl]
+ simp [instruction, Instr.run, loaded, stored, Config.put]
+ have s₅ : M.program.step stored = .localStep next := by
+ rw [step_at hl 5 stored rfl]
+ simp [instruction, Instr.run, next, stored, loaded, Config.store, Config.put, BinaryOp.eval, h1]
+ have s₆ : M.program.step next = .localStep out := by
+ rw [step_at hl 6 next rfl]
+ simp [instruction, Instr.run, out, next, stored, loaded, Config.store, Config.put, BinaryOp.eval, h1]
+ refine ⟨out, pre.append (.tick s₄ (.tick s₅ (.tick s₆ (.nil _)))), rfl, by simp [out],
+ by simp [out, next, Config.put], ?_, rfl, rfl⟩
+ intro j h₀ h₂ h₄
+ simp [out, next, stored, loaded, Config.store, Config.put, Function.update_of_ne h₀,
+ Function.update_of_ne h₂, Function.update_of_ne h₄]
+
+/-- The frame and exit data shared by guessing and copying. -/
+structure Result (reg : Fin 5 ↪ Fin r) (done : Fin p) (c out : Config w p r)
+ (src dst : ℕ) (bs : List Bool) : Prop where
+ pc : out.pc = done
+ source : out.reg (reg 0) = word w (src+bs.length)
+ destination : out.reg (reg 2) = word w (dst+bs.length)
+ frame : ∀ j, j ≠ reg 0 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j
+ privateMem : out.privateMem = storeBits dst bs c.privateMem
+ persistent : out.persistent = c.persistent
+
+private theorem field_loop (hl : Linked M mode pc reg done) (c : Config w p r)
+ (hc : c.pc = pc 0) (src dst : ℕ) (bs : List Bool) (hs : c.reg (reg 0) = word w src)
+ (hd : c.reg (reg 2) = word w dst) (he : c.reg (reg 1) = word w (dst+bs.length))
+ (hone : c.reg (reg 3) = 1) (fit : dst+bs.length < 2^w)
+ (safe : mode = .copy → src+bs.length ≤ 2^w ∧ (dst ≤ src ∨ src+bs.length ≤ dst))
+ (data : mode = .copy → ∀ i : Fin bs.length, c.privateMem (word w (src+i.val)) = bitValue w bs[i.val]) :
+ ∃ out, Prefix M c (events mode bs) out ∧ Result reg done c out src dst bs := by
+ induction bs generalizing c src dst with
+ | nil =>
+ let out := {c with pc := done}
+ have eq : c.reg (reg 2) = c.reg (reg 1) := hd.trans he.symm
+ have s : M.program.step c = .localStep out := by
+ rw [step_at hl 0 c hc]
+ simp [instruction, Instr.run, eq, out]
+ exact ⟨out, .tick s (.nil _), rfl, hs, hd, fun _ _ _ _ ↦ rfl, rfl, rfl⟩
+ | cons b bs ih =>
+ have hlen : dst+1+bs.length = dst+(b::bs).length := by simp; omega
+ have neq : c.reg (reg 2) ≠ c.reg (reg 1) := by
+ rw [hd, he]
+ intro h
+ have e := congrArg Fin.val h
+ rw [val_word (by simp at fit; omega : dst < 2^w), val_word fit] at e
+ simp at e
+ have hload (h : mode = .copy) : c.privateMem (c.reg (reg 0)) = bitValue w b := by
+ simpa [hs] using data h 0
+ obtain ⟨next, pre, hn, hsrc, hdst, hframe, hmem, hp⟩ := iteration hl c hc b hone neq hload
+ have hs' : next.reg (reg 0) = word w (src+1) := by simp [hsrc, hs, word]
+ have hd' : next.reg (reg 2) = word w (dst+1) := by simp [hdst, hd, word]
+ have keep (j : Fin 5) (h₀ : j ≠ 0) (h₂ : j ≠ 2) (h₄ : j ≠ 4) :
+ next.reg (reg j) = c.reg (reg j) :=
+ hframe _ (reg.injective.ne h₀) (reg.injective.ne h₂) (reg.injective.ne h₄)
+ have data' (h : mode = .copy) (i : Fin bs.length) :
+ next.privateMem (word w (src+1+i.val)) = bitValue w bs[i.val] := by
+ have hsafe := safe h
+ have hi := i.isLt
+ have hfit : src+1+i.val < 2^w := by simp only [List.length_cons] at hsafe; omega
+ have hne : word w (src+1+i.val) ≠ word w dst := by
+ intro eq
+ have e := congrArg Fin.val eq
+ rw [val_word hfit, val_word (by simp at fit; omega)] at e
+ simp only [List.length_cons] at hsafe
+ omega
+ rw [hmem, hd, Function.update_of_ne hne]
+ simpa [Nat.add_assoc, Nat.add_comm 1] using data h ⟨i.val+1, by simp⟩
+ obtain ⟨out, tail, result⟩ := ih next hn (src+1) (dst+1) hs' hd'
+ ((keep 1 (by decide) (by decide) (by decide)).trans (hlen ▸ he))
+ ((keep 3 (by decide) (by decide) (by decide)).trans hone)
+ (hlen ▸ fit) (fun h ↦ by have hh := safe h; simp only [List.length_cons] at hh; omega) data'
+ refine ⟨out, pre.append tail, result.pc, ?_, ?_, ?_, ?_, result.persistent.trans hp⟩
+ · simpa [Nat.add_assoc, Nat.add_comm 1] using result.source
+ · simpa [hlen] using result.destination
+ · intro j h₀ h₂ h₄
+ exact (result.frame j h₀ h₂ h₄).trans (hframe j h₀ h₂ h₄)
+ · rw [result.privateMem, hmem, hd, storeBits]
+
+/-- One fresh binary branch for each field bit, in address order. -/
+theorem guess_prefix (hl : Linked M .guess pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (dst : ℕ) (bs : List Bool) (hd : c.reg (reg 2) = word w dst)
+ (he : c.reg (reg 1) = word w (dst+bs.length)) (hone : c.reg (reg 3) = 1)
+ (fit : dst+bs.length < 2^w) :
+ ∃ out, Prefix M c (events .guess bs) out ∧ Result reg done c out (c.reg (reg 0)).val dst bs :=
+ field_loop hl c hc _ dst bs (Fin.ext (Nat.mod_eq_of_lt (c.reg (reg 0)).isLt).symm)
+ hd he hone fit (by simp) (by simp)
+
+/-- A private-to-private forward slice copy. The permitted overlap includes
+the identical slice and moving the slice toward lower addresses. -/
+theorem copy_prefix (hl : Linked M .copy pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (src dst : ℕ) (bs : List Bool) (hs : c.reg (reg 0) = word w src)
+ (hd : c.reg (reg 2) = word w dst) (he : c.reg (reg 1) = word w (dst+bs.length))
+ (hone : c.reg (reg 3) = 1) (fit : dst+bs.length < 2^w) (hsrc : src+bs.length ≤ 2^w)
+ (safe : dst ≤ src ∨ src+bs.length ≤ dst)
+ (data : ∀ i : Fin bs.length, c.privateMem (word w (src+i.val)) = bitValue w bs[i.val]) :
+ ∃ out, Prefix M c (events .copy bs) out ∧ Result reg done c out src dst bs :=
+ field_loop hl c hc src dst bs hs hd he hone fit (fun _ ↦ ⟨hsrc,safe⟩) (fun _ ↦ data)
+
+/-- The abstract reader serializes the bits in exactly the native store order. -/
+theorem bitField_encode {n : ℕ} (f : Fin n → Bool) :
+ (LocalHistory.bitField n).encode f = List.ofFn f := by
+ let x := (RAMSerialization.wordBits n).symm f
+ change List.ofFn (RAMSerialization.wordBits n (Fin.ofNat _ x.val)) = _
+ rw [show Fin.ofNat (2^n) x.val = x from Fin.ext (Nat.mod_eq_of_lt x.isLt)]
+ exact congrArg List.ofFn ((RAMSerialization.wordBits n).apply_symm_apply f)
+
+/-- Exact suffix, fuel, stored bits and frame when reading one field of a
+compression kernel. The enclosing vertex may immediately read its next field. -/
+theorem execute_guess (hl : Linked M .guess pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (dst n : ℕ) (hd : c.reg (reg 2) = word w dst) (he : c.reg (reg 1) = word w (dst+n))
+ (hone : c.reg (reg 3) = 1) (fit : dst+n < 2^w) (f : Fin n → Bool) :
+ ∃ out, Result reg done c out (c.reg (reg 0)).val dst (List.ofFn f) ∧
+ (∀ i : Fin n, out.privateMem (word w (dst+i.val)) = bitValue w (f i)) ∧
+ ∀ fuel mem tail, execute M.program (fuel+(6*n+1)) c mem ((LocalHistory.bitField n).encode f ++ tail) =
+ (execute M.program fuel out mem tail).map (fun rep ↦ ⟨events .guess (List.ofFn f) ++ rep.events, rep.result⟩) := by
+ obtain ⟨out, pref, res⟩ := guess_prefix hl c hc dst (List.ofFn f) hd (by simpa using he)
+ hone (by simpa using fit)
+ refine ⟨out, res, ?_, ?_⟩
+ · intro i
+ rw [res.privateMem]
+ simpa using storeBits_read dst (List.ofFn f) c.privateMem (by simpa using fit.le)
+ ⟨i.val, by simp⟩
+ · intro fuel mem tail
+ simpa [events_bits, (events_work .guess (w := w) (List.ofFn f)).1, bitField_encode] using pref.execute fuel mem tail
+
+/-- A copy has no branch bits or external probes and takes five local
+steps per bit plus the final test. -/
+theorem execute_copy (hl : Linked M .copy pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (src dst : ℕ) (bs : List Bool) (hs : c.reg (reg 0) = word w src)
+ (hd : c.reg (reg 2) = word w dst) (he : c.reg (reg 1) = word w (dst+bs.length))
+ (hone : c.reg (reg 3) = 1) (fit : dst+bs.length < 2^w) (hsrc : src+bs.length ≤ 2^w)
+ (safe : dst ≤ src ∨ src+bs.length ≤ dst)
+ (data : ∀ i : Fin bs.length, c.privateMem (word w (src+i.val)) = bitValue w bs[i.val]) :
+ ∃ out, Result reg done c out src dst bs ∧ ∀ fuel mem tail,
+ execute M.program (fuel+(5*bs.length+1)) c mem tail =
+ (execute M.program fuel out mem tail).map (fun rep ↦ ⟨events .copy bs ++ rep.events,rep.result⟩) := by
+ obtain ⟨out,pref,res⟩ := copy_prefix hl c hc src dst bs hs hd he hone fit hsrc safe data
+ exact ⟨out, res, fun fuel mem tail ↦ by
+ simpa [events_bits, (events_work .copy (w := w) bs).1] using pref.execute fuel mem tail⟩
+
+/-- The RAM rejects a short field independently of the linked continuation. -/
+theorem guess_short (hl : Linked M .guess pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (dst n : ℕ) (hd : c.reg (reg 2) = word w dst) (he : c.reg (reg 1) = word w (dst+n))
+ (hone : c.reg (reg 3) = 1) (fit : dst+n < 2^w)
+ (bits : List Bool) (h : bits.length < n) (fuel : ℕ) (mem : Memory w) :
+ execute M.program fuel c mem bits = none := by
+ let rest := List.replicate (n-bits.length-1) false
+ let full := bits ++ false :: rest
+ have hlen : full.length = n := by simp [full,rest]; omega
+ obtain ⟨out, pref, res⟩ := guess_prefix hl c hc dst full hd (hlen ▸ he) hone (hlen ▸ fit)
+ apply pref.execute_short fuel mem bits rest false
+ simp [events_bits, full]
+
+/-- With an accepting continuation, complete native paths are in bijection
+with the independent assignments of the declared field bits. -/
+theorem guess_accepts_iff (hl : Linked M .guess pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (dst n : ℕ) (hd : c.reg (reg 2) = word w dst) (he : c.reg (reg 1) = word w (dst+n))
+ (hone : c.reg (reg 3) = 1) (fit : dst+n < 2^w)
+ (finish : ∀ out : Config w p r, out.pc = done → M.program.step out = .finish none)
+ (mem : Memory w) (bits : List Bool) :
+ (execute M.program (1+(6*n+1)) c mem bits).isSome ↔ ∃! f : Fin n → Bool, bits = List.ofFn f := by
+ constructor
+ · intro accepted
+ have hlen : n ≤ bits.length := by
+ by_contra! h
+ rw [guess_short hl c hc dst n hd he hone fit bits h] at accepted
+ contradiction
+ let field := bits.take n
+ have len : field.length = n := by simp [field,hlen]
+ have hsplit : bits = field ++ bits.drop n := (List.take_append_drop ..).symm
+ obtain ⟨out,pref,res⟩ := guess_prefix hl c hc dst field hd (len ▸ he) hone (len ▸ fit)
+ have hrun := pref.execute 1 mem (bits.drop n)
+ rw [events_bits, (events_work .guess (w := w) field).1, len] at hrun
+ simp only [ite_true, ← hsplit] at hrun
+ rw [hrun] at accepted
+ have hempty : bits.drop n = [] := by
+ by_contra h
+ simp [execute, finish out res.pc, h] at accepted
+ have hbits : bits = field := by simpa [hempty] using hsplit
+ have eqLen := hbits ▸ len
+ let f (i : Fin n) := bits[i.val]'(by rw [eqLen]; exact i.isLt)
+ have hef : bits = List.ofFn f := List.ext_getElem (by simpa using eqLen) (by simp [f])
+ exact ⟨f, hef, fun g hg ↦ List.ofFn_injective (hg.symm.trans hef)⟩
+ · rintro ⟨f, rfl, _⟩
+ obtain ⟨out,res,_,run⟩ := execute_guess hl c hc dst n hd he hone fit f
+ have h := run 1 mem []
+ simp only [bitField_encode, List.append_nil] at h
+ rw [h]
+ simp [execute, finish out res.pc]
+
+end PairSimulation.PrivateFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationPrivateLabels.lean b/lean/OAI/Computability/VPVNP/PairSimulationPrivateLabels.lean
new file mode 100644
index 0000000000..323b45fa29
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationPrivateLabels.lean
@@ -0,0 +1,250 @@
+import OAI.Computability.VPVNP.PairSimulationKernels
+import OAI.Computability.VPVNP.PairSimulationCounters
+import Mathlib.Data.List.Count
+
+/-!
+# Accumulating one map's labels in private memory
+
+The motif interpreter emits one ordinal per copy, including repeated
+ordinals. Seven opcodes visit these private words in sequence and increment
+the corresponding private counters. This is the array read by the external
+histogram flush at the end of the final-site call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.PrivateLabels
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k t : ℕ}
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+
+private theorem val_word {n : ℕ} (h : n < 2^w) : (word w n).val = n := Nat.mod_eq_of_lt h
+
+/-- Registers hold the label cursor, its exclusive end, histogram base, one,
+a label/address, and a count. The same table works at every word width. -/
+def instruction (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) : Fin 7 → Instr w p r k :=
+ ![.jumpEq (reg 0) (reg 1) done (pc 1), .loadPrivate (reg 4) (reg 0) (pc 2),
+ .binary .add (reg 4) (reg 2) (reg 4) (pc 3), .loadPrivate (reg 5) (reg 4) (pc 4),
+ .binary .add (reg 5) (reg 5) (reg 3) (pc 5), .storePrivate (reg 4) (reg 5) (pc 6),
+ .binary .add (reg 0) (reg 0) (reg 3) (pc 0)]
+
+theorem resize_instruction (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) (i : Fin 7) :
+ (instruction (w := 1) (k := k) pc reg done i).resize w = instruction pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- The machine contains the seven instructions that scan emitted label ordinals and increment
+their private histogram cells. -/
+def Linked (M : Machine w p r k) (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r) (done : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+/-- The folded histogram uses a separate update for each emitted occurrence. -/
+def accumulate (base : ℕ) : List (Fin t) → (Word w → Word w) → Word w → Word w
+ | [], mem => mem
+ | j :: js, mem =>
+ let addr := word w (base + j.val)
+ accumulate base js (Function.update mem addr (mem addr + 1))
+
+theorem accumulate_at (base : ℕ) (names : List (Fin t)) (mem : Word w → Word w)
+ (hfit : base+t ≤ 2^w) (i : Fin t) :
+ accumulate base names mem (word w (base+i.val)) = mem (word w (base+i.val)) + (names.count i : Word w) := by
+ induction names generalizing mem with
+ | nil => simp [accumulate]
+ | cons j js ih =>
+ rw [accumulate, ih]
+ by_cases h : j = i
+ · subst j; simp [add_assoc]; exact add_comm _ _
+ · have hne : word w (base+i.val) ≠ word w (base+j.val) := by
+ intro e
+ have hi := i.isLt
+ have hj := j.isLt
+ have he := congrArg Fin.val e
+ rw [val_word (by omega : base+i.val < 2^w), val_word (by omega : base+j.val < 2^w)] at he
+ exact h (Fin.ext (Nat.add_left_cancel he).symm)
+ rw [Function.update_of_ne hne]
+ simp [h]
+
+variable {M : Machine w p r k} {pc : Fin 7 → Fin p} {reg : Fin 6 ↪ Fin r} {done : Fin p}
+
+private theorem step_at (hl : Linked M pc reg done) (i : Fin 7) (c : Config w p r)
+ (hc : c.pc = pc i) : M.program.step c = (instruction pc reg done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+private theorem iteration (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 0)
+ (src base : ℕ) (j : Fin t) (hs : c.reg (reg 0) = word w src) (hb : c.reg (reg 2) = word w base)
+ (hone : c.reg (reg 3) = 1) (hne : c.reg (reg 0) ≠ c.reg (reg 1))
+ (hj : c.privateMem (word w src) = word w j.val) :
+ ∃ out, Prefix M c (List.replicate 7 .tick) out ∧ out.pc = pc 0 ∧
+ out.reg (reg 0) = word w (src+1) ∧
+ (∀ i, i ≠ reg 0 → i ≠ reg 4 → i ≠ reg 5 → out.reg i = c.reg i) ∧
+ out.privateMem = Function.update c.privateMem (word w (base+j.val)) (c.privateMem (word w (base+j.val))+1) ∧
+ out.persistent = c.persistent := by
+ let c₁ := {c with pc := pc 1}
+ let c₂ := c₁.put (pc 2) (reg 4) (word w j.val)
+ let addr := word w (base+j.val)
+ let c₃ := c₂.put (pc 3) (reg 4) addr
+ let c₄ := c₃.put (pc 4) (reg 5) (c.privateMem addr)
+ let c₅ := c₄.put (pc 5) (reg 5) (c.privateMem addr + 1)
+ let c₆ := c₅.store (pc 6) addr (c.privateMem addr + 1)
+ let out := c₆.put (pc 0) (reg 0) (word w (src+1))
+ have s₀ : M.program.step c = .localStep c₁ := by rw [step_at hl 0 c hc]; simp [instruction,Instr.run,hne,c₁]
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at hl 1 c₁ rfl]
+ change CallAction.localStep (c₁.put (pc 2) (reg 4) (c.privateMem (c.reg (reg 0)))) = _
+ rw [hs,hj]
+ have s₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step_at hl 2 c₂ rfl]
+ change CallAction.localStep (c₂.put (pc 3) (reg 4) (c₂.reg (reg 2) + c₂.reg (reg 4))) = _
+ simp [c₃,c₂,c₁,Config.put,hb,addr,word]
+ have s₃ : M.program.step c₃ = .localStep c₄ := by
+ rw [step_at hl 3 c₃ rfl]
+ change CallAction.localStep (c₃.put (pc 4) (reg 5) (c.privateMem (c₃.reg (reg 4)))) = _
+ simp [c₃,c₄,Config.put]
+ have s₄ : M.program.step c₄ = .localStep c₅ := by
+ rw [step_at hl 4 c₄ rfl]
+ change CallAction.localStep (c₄.put (pc 5) (reg 5) (c₄.reg (reg 5) + c₄.reg (reg 3))) = _
+ simp [c₅,c₄,c₃,c₂,c₁,Config.put,hone]
+ have s₅ : M.program.step c₅ = .localStep c₆ := by
+ rw [step_at hl 5 c₅ rfl]
+ change CallAction.localStep (c₅.store (pc 6) (c₅.reg (reg 4)) (c₅.reg (reg 5))) = _
+ simp [c₆,c₅,c₄,c₃,Config.put]
+ have s₆ : M.program.step c₆ = .localStep out := by
+ rw [step_at hl 6 c₆ rfl]
+ change CallAction.localStep (c₆.put (pc 0) (reg 0) (c₆.reg (reg 0) + c₆.reg (reg 3))) = _
+ simp [out,c₆,c₅,c₄,c₃,c₂,c₁,Config.store,Config.put,hs,hone,word]
+ refine ⟨out,.tick s₀ (.tick s₁ (.tick s₂ (.tick s₃ (.tick s₄ (.tick s₅ (.tick s₆ (.nil _))))))),
+ rfl,by simp [out],?_,rfl,rfl⟩
+ intro i h0 h4 h5
+ simp [out,c₆,c₅,c₄,c₃,c₂,c₁,Config.store,Config.put,Function.update_of_ne h0,
+ Function.update_of_ne h4,Function.update_of_ne h5]
+
+/-- The complete native scan has no probes or binary choices. Its private
+state contains every histogram update and preserves every other cell. -/
+theorem run_separated (hl : Linked M pc reg done) (names : List (Fin t)) (src base : ℕ)
+ (c : Config w p r) (hc : c.pc = pc 0) (hs : c.reg (reg 0) = word w src)
+ (he : c.reg (reg 1) = word w (src+names.length)) (hb : c.reg (reg 2) = word w base)
+ (h1 : c.reg (reg 3) = 1) (fit : base+t ≤ 2^w) (apart : src+names.length ≤ base ∨ base+t ≤ src)
+ (hend : src+names.length < 2^w)
+ (hdata : ∀ i : Fin names.length, c.privateMem (word w (src+i.val)) = word w (names[i.val]).val) :
+ ∃ out, Prefix M c (List.replicate (7*names.length+1) .tick) out ∧ out.pc = done ∧
+ out.privateMem = accumulate base names c.privateMem ∧ out.persistent = c.persistent := by
+ induction names generalizing src c with
+ | nil =>
+ have eq : c.reg (reg 0) = c.reg (reg 1) := hs.trans (by simpa using he.symm)
+ let out := {c with pc := done}
+ have s : M.program.step c = .localStep out := by rw [step_at hl 0 c hc]; simp [instruction,Instr.run,eq,out]
+ exact ⟨out,.tick s (.nil _),rfl,rfl,rfl⟩
+ | cons j js ih =>
+ have neq : c.reg (reg 0) ≠ c.reg (reg 1) := by
+ rw [hs,he]; intro eq
+ have h := congrArg Fin.val eq
+ rw [val_word (by omega : src < 2^w), val_word hend] at h
+ simp at h
+ have hj : c.privateMem (word w src) = word w j.val := by simpa using hdata 0
+ obtain ⟨c', pre, hc', hs', other, hm, hp⟩ := iteration hl c hc src base j hs hb h1 neq hj
+ have endEq : src+1+js.length = src+(j::js).length := by simp; omega
+ have tailData (i : Fin js.length) : c'.privateMem (word w (src+1+i.val)) = word w (js[i.val]).val := by
+ have hi := i.isLt
+ have hj := j.isLt
+ have hne : word w (src+1+i.val) ≠ word w (base+j.val) := by
+ intro eq
+ have h := congrArg Fin.val eq
+ simp only [List.length_cons] at apart hend
+ rw [val_word (by omega : src+1+i.val < 2^w), val_word (by omega : base+j.val < 2^w)] at h
+ omega
+ rw [hm, Function.update_of_ne hne]
+ simpa [Nat.add_assoc,Nat.add_comm 1] using hdata ⟨i.val+1,by simp⟩
+ obtain ⟨out, pre', hpc, hmem, hper⟩ := ih (src+1) c' hc' hs'
+ ((other _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans
+ (endEq ▸ he)) ((other _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))
+ (reg.injective.ne (by decide))).trans hb) ((other _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))
+ (reg.injective.ne (by decide))).trans h1) (by rcases apart with h | h; exact .inl (endEq ▸ h); exact .inr (by omega))
+ (endEq ▸ hend) tailData
+ refine ⟨out,?_,hpc,?_,hper.trans hp⟩
+ · convert pre.append pre' using 1
+ rw [← List.replicate_add]
+ congr 1
+ simp; omega
+ · rw [hmem,hm]; rfl
+
+/-- A forward allocation with the counter bank above its label words. -/
+theorem run (hl : Linked M pc reg done) (names : List (Fin t)) (src base : ℕ)
+ (c : Config w p r) (hc : c.pc = pc 0) (hs : c.reg (reg 0) = word w src)
+ (he : c.reg (reg 1) = word w (src+names.length)) (hb : c.reg (reg 2) = word w base)
+ (h1 : c.reg (reg 3) = 1) (fit : base+t ≤ 2^w) (before : src+names.length ≤ base)
+ (hend : src+names.length < 2^w)
+ (hdata : ∀ i : Fin names.length, c.privateMem (word w (src+i.val)) = word w (names[i.val]).val) :
+ ∃ out, Prefix M c (List.replicate (7*names.length+1) .tick) out ∧ out.pc = done ∧
+ out.privateMem = accumulate base names c.privateMem ∧ out.persistent = c.persistent :=
+ run_separated hl names src base c hc hs he hb h1 fit (.inl before) hend hdata
+
+/-- Counting copies in the emitted list recovers the formal map exponent. -/
+theorem count_entry {Label : Type} [DecidableEq Label] {u : ℕ} (f : Fin u → Label)
+ (idx : Label ≃ Fin t) (label : Label) :
+ ((List.ofFn f).map idx).count (idx label) = MotifConversion.entryMultiplicity f label := by
+ rw [List.count_map_of_injective _ _ idx.injective]
+ induction u with
+ | zero => simp [MotifConversion.entryMultiplicity]
+ | succ u ih =>
+ unfold MotifConversion.entryMultiplicity
+ rw [Fin.sum_univ_succ, List.ofFn_succ, List.count_cons]
+ by_cases h : f 0 = label <;> simp [h, ih, MotifConversion.entryMultiplicity, Nat.add_comm]
+
+
+/-- The last private scan of a vertex links directly to the common external
+histogram suffix. Previously accumulated maps and every copy of the last
+map are both present when the suffix is flushed. -/
+theorem run_flush {entry : Fin 7 → Fin p} {flushPC : Fin 7 → Fin p} {flushReg : Fin 6 ↪ Fin r}
+ {exit : Fin p} (hl : Linked M pc reg (entry 0)) (hf : Counters.Linked M flushPC flushReg exit)
+ (param : Fin 4 → Fin k) (hcode : ∀ i, M.code (entry i) = Counters.entryCode entry flushReg param (flushPC 0) i)
+ (names : List (Fin t)) (src base external grammar : ℕ) (c : Config w p r) (hc : c.pc = pc 0)
+ (hs : c.reg (reg 0) = word w src) (he : c.reg (reg 1) = word w (src+names.length))
+ (hb : c.reg (reg 2) = word w base) (h1 : c.reg (reg 3) = 1)
+ (fit : base+t < 2^w) (before : src+names.length ≤ base)
+ (hdata : ∀ i : Fin names.length, c.privateMem (word w (src+i.val)) = word w (names[i.val]).val)
+ (hpub : M.publicData (param 0) = word w external)
+ (hgrammar : M.publicData (param 1) = word w grammar) (hcount : M.publicData (param 2) = word w t)
+ (hbase : M.publicData (param 3) = word w base) (hout : external+grammar+t < 2^w)
+ (prior : Fin t → ℕ) (hprior : ∀ i : Fin t, c.privateMem (word w (base+i)) = word w (prior i)) (m : Memory w) :
+ let target := Counters.addHistogram external grammar (fun i => prior i + names.count i) m
+ ∃ out es, out.pc = exit ∧ es.length = 7*names.length+1+(7*t+8) ∧ countProbes es = 2*t ∧
+ choiceBits es = [] ∧ after m es = target ∧ ∀ fuel bs,
+ execute M.program (fuel+es.length) c m bs =
+ (execute M.program fuel out target bs).map (fun r => ⟨es++r.events,r.result⟩) := by
+ obtain ⟨q,hpre,hq,hm,_⟩ := run hl names src base c hc hs he hb h1 fit.le before
+ (by omega) hdata
+ have hh (i : Fin t) : q.privateMem (word w (base+i)) = word w (prior i + names.count i) := by
+ rw [hm, accumulate_at base names _ fit.le i, hprior i]
+ simp [word]
+ obtain ⟨out, fs, hp, _, _, hlen, hpr, hchoices, hend, hrun⟩ :=
+ Counters.execute_flush hf entry param hcode q hq external grammar base hpub hgrammar hcount hbase
+ (fun i => prior i + names.count i) hh fit hout m
+ let n := 7*names.length+1
+ have prep (n : ℕ) (es : List (Event w)) : choiceBits (List.replicate n .tick ++ es) = choiceBits es ∧
+ countProbes (List.replicate n .tick ++ es) = countProbes es ∧ after m (List.replicate n .tick ++ es) = after m es := by
+ induction n with
+ | zero => simp
+ | succ n ih => simpa only [List.replicate_succ, List.cons_append, choiceBits, countProbes, after,
+ List.foldl_cons, update] using ih
+ have hbts : choiceBits (List.replicate n (.tick : Event w)) = [] := by simpa [choiceBits] using (prep n []).1
+ refine ⟨out,List.replicate n .tick ++ fs,hp,by simp [n,hlen],(prep n fs).2.1.trans hpr,
+ (prep n fs).1.trans hchoices,(prep n fs).2.2.trans hend,?_⟩
+ intro fuel bs
+ have hp := hpre.execute (fuel+7*t+8) m bs
+ change execute M.program ((fuel+7*t+8)+(List.replicate n (.tick : Event w)).length) c m
+ (choiceBits (List.replicate n .tick) ++ bs) = _ at hp
+ rw [hbts,List.nil_append,List.length_replicate] at hp
+ rw [List.length_append,List.length_replicate,hlen,
+ show fuel + (n + (7*t+8)) = (fuel+7*t+8)+n by omega, hp, hrun]
+ simp [Option.map_map,Function.comp_def,List.append_assoc,n]
+
+end PairSimulation.PrivateLabels
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationPrivateScratch.lean b/lean/OAI/Computability/VPVNP/PairSimulationPrivateScratch.lean
new file mode 100644
index 0000000000..c8bf5cbb6a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationPrivateScratch.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.PairSimulationHistogramFrame
+
+/-!
+# Private arrays and pointwise dependence on the incoming memory
+
+Writing a finite word array replaces precisely its addressed cells. Incrementing
+a list of histogram labels depends at each address only on that address's original
+contents. These operations describe the scratch state of a successful map call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.PrivateScratch
+
+open BurstRAM
+open scoped Fin.CommRing
+
+/-- Contents of private scratch memory as a word-valued function of a machine-word address. -/
+abbrev Memory (w : ℕ) := Word w → Word w
+
+variable {w n t : ℕ}
+
+/-- The result of storing all values in a consecutive private array. -/
+noncomputable def write (base : Word w) (value : Fin n → Word w) (mem : Memory w) (a : Word w) :
+ Word w := by
+ classical
+ exact if h : ∃ i : Fin n, base + (i.val : Word w) = a then value h.choose else mem a
+
+theorem eq_write (base : Word w) (value : Fin n → Word w) {old new : Memory w}
+ (cells : ∀ i : Fin n, new (base + (i.val : Word w)) = value i)
+ (frame : ∀ a : Word w, (∀ i : Fin n, a ≠ base + (i.val : Word w)) → new a = old a) :
+ new = write base value old := by
+ classical
+ funext a
+ by_cases h : ∃ i : Fin n, base + (i.val : Word w) = a
+ · rw [write, dite_eq_left h, ← cells, h.choose_spec]
+ · rw [write, dite_eq_right h]
+ exact frame a (fun i hi ↦ h ⟨i, hi.symm⟩)
+
+/-- An address distinct from every word in a natural-addressed array is outside
+its natural interval. -/
+theorem outside_of_ne (base : ℕ) (a : Word w)
+ (h : ∀ i : Fin n, a ≠ (base : Word w) + (i.val : Word w)) :
+ a.val < base ∨ base + n ≤ a.val := by
+ by_contra! hi
+ let i : Fin n := ⟨a.val - base, by omega⟩
+ apply h i
+ rw [← Nat.cast_add, show base + i.val = a.val by dsimp [i]; omega]
+ exact Fin.ext (Nat.mod_eq_of_lt a.isLt).symm
+
+theorem write_congr_at (base : Word w) (value : Fin n → Word w) {old old' : Memory w}
+ (a : Word w) (h : old a = old' a) : write base value old a = write base value old' a := by
+ simp only [write, h]
+
+theorem accumulate_congr_at (base : ℕ) (names : List (Fin t)) {old old' : Memory w}
+ (a : Word w) (h : old a = old' a) :
+ PrivateLabels.accumulate base names old a = PrivateLabels.accumulate base names old' a := by
+ induction names generalizing old old' with
+ | nil => exact h
+ | cons l ls ih =>
+ apply ih
+ by_cases he : a = ((base + l.val : ℕ) : Word w)
+ · subst a
+ simp only [Function.update_self, h]
+ · simp only [Function.update_of_ne he, h]
+
+end PairSimulation.PrivateScratch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationPrivateSlices.lean b/lean/OAI/Computability/VPVNP/PairSimulationPrivateSlices.lean
new file mode 100644
index 0000000000..116c8d5719
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationPrivateSlices.lean
@@ -0,0 +1,329 @@
+import OAI.Computability.VPVNP.PairSimulationPrivateFields
+import OAI.Computability.VPVNP.CompressorSliceSchedule
+
+/-!
+# Reading slice records inside a final-site call
+
+The setup reads the length at frame address plus two before using either
+offset. A positive length selects the source and target offset reads,
+adds these to the supplied private field bases and enters the copy loop.
+An empty intersection returns immediately.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.PrivateSlices
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords.SliceSchedule
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+private abbrev word (w n : ℕ) : Word w := (n : Word w)
+private theorem val_word {n : ℕ} (hn : n < 2^w) : (word w n).val = n := Nat.mod_eq_of_lt hn
+
+/-- Registers 0–4 share the copy-loop ABI. The sixth register is the
+external address of the first offset and is preserved. -/
+def instruction (pc : Fin 11 → Fin p) (reg : Fin 6 ↪ Fin r) (copy done : Fin p) :
+ Fin 11 → Instr w p r k :=
+ ![.binary .add (reg 4) (reg 5) (reg 3) (pc 1),
+ .binary .add (reg 4) (reg 4) (reg 3) (pc 2),
+ .readExternal (reg 1) (reg 4) (pc 3), .constant (reg 4) 0 (pc 4),
+ .jumpEq (reg 1) (reg 4) done (pc 5),
+ .readExternal (reg 4) (reg 5) (pc 6), .binary .add (reg 0) (reg 0) (reg 4) (pc 7),
+ .binary .add (reg 4) (reg 5) (reg 3) (pc 8), .readExternal (reg 4) (reg 4) (pc 9),
+ .binary .add (reg 2) (reg 2) (reg 4) (pc 10), .binary .add (reg 1) (reg 2) (reg 1) copy]
+
+theorem resize_instruction (pc : Fin 11 → Fin p) (reg : Fin 6 ↪ Fin r) (copy done : Fin p) (i : Fin 11) :
+ (instruction (w := 1) (k := k) pc reg copy done i).resize w = instruction pc reg copy done i := by
+ fin_cases i <;> rfl
+
+/-- The machine contains the eleven slice-setup instructions that check the length, return for
+an empty slice, or apply both offsets and enter the copy loop. -/
+def Linked (M : Machine w p r k) (pc : Fin 11 → Fin p) (reg : Fin 6 ↪ Fin r)
+ (copy done : Fin p) : Prop := ∀ i, M.code (pc i) = instruction pc reg copy done i
+
+/-- Restrict the slice-setup register allocation to the first five registers shared with the
+private copy loop. -/
+def copyRegs (reg : Fin 6 ↪ Fin r) : Fin 5 ↪ Fin r := (Fin.castAddEmb 1).trans reg
+
+/-- Exact header trace. Empty records read only the length cell. -/
+def headerEvents (mem : Memory w) (frame : Word w) : List (Event w) :=
+ let addr := frame+1+1
+ let len := mem addr.val
+ [.tick,.tick,.read addr len,.tick,.tick] ++
+ if len = 0 then [] else [.read frame (mem frame.val),.tick,.tick,.read (frame+1) (mem (frame+1).val),.tick,.tick]
+
+/-- The header contains local instructions and external reads only. -/
+private inductive ReadPrefix (M : Machine w p r k) (m : Memory w) :
+ Config w p r → List (Event w) → Config w p r → Prop
+ | nil (c) : ReadPrefix M m c [] c
+ | tick {c d z es} (hs : M.program.step c = .localStep d) (tail : ReadPrefix M m d es z) :
+ ReadPrefix M m c (.tick :: es) z
+ | read {c g z es} (a : Word w) (hs : M.program.step c = .read a g)
+ (tail : ReadPrefix M m (g (m a.val)) es z) : ReadPrefix M m c (.read a (m a.val) :: es) z
+
+private theorem ReadPrefix.execute {M : Machine w p r k} {m : Memory w} {c d : Config w p r}
+ {es : List (Event w)} (h : ReadPrefix M m c es d) (fuel : ℕ) (bs : List Bool) :
+ BurstRAM.execute M.program (fuel+es.length) c m bs =
+ (BurstRAM.execute M.program fuel d m bs).map (fun rep ↦ ⟨es ++ rep.events,rep.result⟩) := by
+ induction h with
+ | nil => simp
+ | tick hs tail ih | read _ hs tail ih =>
+ rw [List.length_cons, ← Nat.add_assoc]
+ simp [BurstRAM.execute, hs, ih, Option.map_map, Function.comp_def, Report.prepend]
+
+variable {M : Machine w p r k} {pc : Fin 11 → Fin p} {reg : Fin 6 ↪ Fin r} {copy done : Fin p}
+
+private theorem step_at (hl : Linked M pc reg copy done) (i : Fin 11) (c : Config w p r)
+ (hc : c.pc = pc i) : M.program.step c = (instruction pc reg copy done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+/-- The header exit and its copy operands. On the empty branch the offsets
+need no values, so the input field bases stay available. -/
+structure HeaderResult (reg : Fin 6 ↪ Fin r) (copy done : Fin p) (c out : Config w p r)
+ (frame : Word w) (m : Memory w) : Prop where
+ pc : out.pc = if m (frame+1+1).val = 0 then done else copy
+ args : m (frame+1+1).val ≠ 0 →
+ out.reg (reg 0) = c.reg (reg 0) + m frame.val ∧
+ out.reg (reg 2) = c.reg (reg 2) + m (frame+1).val ∧
+ out.reg (reg 1) = out.reg (reg 2) + m (frame+1+1).val
+ frameRegs : ∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j
+ memory : out.privateMem = c.privateMem
+ persistent : out.persistent = c.persistent
+
+/-- Execute the length-first header read and pass the resulting registers to
+the linked copy or to the empty-slice continuation. -/
+theorem execute_header (hl : Linked M pc reg copy done) (c : Config w p r) (hc : c.pc = pc 0)
+ (h1 : c.reg (reg 3) = 1) (mem : Memory w) :
+ ∃ out, HeaderResult reg copy done c out (c.reg (reg 5)) mem ∧ ∀ fuel bs,
+ execute M.program (fuel+(headerEvents mem (c.reg (reg 5))).length) c mem bs =
+ (execute M.program fuel out mem bs).map (fun rep ↦ ⟨headerEvents mem (c.reg (reg 5)) ++ rep.events,rep.result⟩) := by
+ let f := c.reg (reg 5)
+ let len := mem (f+1+1).val
+ let c₁ := c.put (pc 1) (reg 4) (f+1)
+ let c₂ := c₁.put (pc 2) (reg 4) (f+1+1)
+ let c₃ := c₂.put (pc 3) (reg 1) len
+ let c₄ := c₃.put (pc 4) (reg 4) 0
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step_at hl 0 c hc]
+ change CallAction.localStep (c.put (pc 1) (reg 4) (f+c.reg (reg 3))) = _
+ rw [h1]
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at hl 1 c₁ rfl]
+ change CallAction.localStep (c₁.put (pc 2) (reg 4) (c₁.reg (reg 4)+c₁.reg (reg 3))) = _
+ simp [c₂,c₁,Config.put,h1]
+ have s₂ : M.program.step c₂ = .read (f+1+1) (fun v ↦ c₂.put (pc 3) (reg 1) v) := by
+ rw [step_at hl 2 c₂ rfl]
+ change CallAction.read (c₂.reg (reg 4)) _ = _
+ rw [Config.put_same]
+ have s₃ : M.program.step c₃ = .localStep c₄ := step_at hl 3 c₃ rfl
+ have s₄ : M.program.step c₄ = .localStep {c₄ with pc := if len = 0 then done else pc 5} := by
+ rw [step_at hl 4 c₄ rfl]
+ change CallAction.localStep {c₄ with pc := if c₄.reg (reg 1) = c₄.reg (reg 4) then done else pc 5} = _
+ simp [c₄,c₃,Config.put]
+ let tested (dest : Fin p) := {c₄ with pc := dest}
+ let first : List (Event w) := [.tick,.tick,.read (f+1+1) len,.tick,.tick]
+ have test {es : List (Event w)} {out : Config w p r}
+ (tail : ReadPrefix M mem (tested (if len=0 then done else pc 5)) es out) :
+ ReadPrefix M mem c (first ++ es) out :=
+ .tick s₀ (.tick s₁ (.read _ s₂ (.tick s₃ (.tick s₄ tail))))
+ by_cases hz : len = 0
+ · let out := tested done
+ have tail : ReadPrefix M mem (tested (if len=0 then done else pc 5)) [] out := by
+ rw [ite_eq_left hz]; exact .nil _
+ have ht : headerEvents mem f = first ++ [] := by simp [headerEvents, ← show mem (f+1+1).val = len from rfl, hz,first,len]
+ refine ⟨out, ⟨?_, ?_, ?_, rfl, rfl⟩, ?_⟩
+ · change done = if len=0 then done else copy
+ simp [hz]
+ · exact fun h ↦ (h hz).elim
+ · intro j _ hj₁ _ hj₄
+ simp [out,tested,c₄,c₃,c₂,c₁,Config.put,Function.update_of_ne hj₄, Function.update_of_ne hj₁]
+ · intro fuel bs
+ change execute M.program (fuel+(headerEvents mem f).length) c mem bs = _
+ rw [ht]
+ exact (test tail).execute fuel bs
+ · let c₅ := tested (pc 5)
+ let c₆ := c₅.put (pc 6) (reg 4) (mem f.val)
+ let c₇ := c₆.put (pc 7) (reg 0) (c.reg (reg 0) + mem f.val)
+ let c₈ := c₇.put (pc 8) (reg 4) (f+1)
+ let c₉ := c₈.put (pc 9) (reg 4) (mem (f+1).val)
+ let dst := c.reg (reg 2) + mem (f+1).val
+ let c₁₀ := c₉.put (pc 10) (reg 2) dst
+ let out := c₁₀.put copy (reg 1) (dst+len)
+ have s₅ : M.program.step c₅ = .read f (fun v ↦ c₅.put (pc 6) (reg 4) v) := by
+ rw [step_at hl 5 c₅ rfl]
+ change CallAction.read (c₅.reg (reg 5)) _ = _
+ simp [c₅,tested,c₄,c₃,c₂,c₁,Config.put,f]
+ have s₆ : M.program.step c₆ = .localStep c₇ := by
+ rw [step_at hl 6 c₆ rfl]
+ change CallAction.localStep (c₆.put (pc 7) (reg 0) (c₆.reg (reg 0)+c₆.reg (reg 4))) = _
+ simp [c₇,c₆,c₅,tested,c₄,c₃,c₂,c₁,Config.put]
+ have s₇ : M.program.step c₇ = .localStep c₈ := by
+ rw [step_at hl 7 c₇ rfl]
+ change CallAction.localStep (c₇.put (pc 8) (reg 4) (c₇.reg (reg 5)+c₇.reg (reg 3))) = _
+ simp [c₈,c₇,c₆,c₅,tested,c₄,c₃,c₂,c₁,Config.put,f,h1]
+ have s₈ : M.program.step c₈ = .read (f+1) (fun v ↦ c₈.put (pc 9) (reg 4) v) := by
+ rw [step_at hl 8 c₈ rfl]
+ change CallAction.read (c₈.reg (reg 4)) _ = _
+ rw [Config.put_same]
+ have s₉ : M.program.step c₉ = .localStep c₁₀ := by
+ rw [step_at hl 9 c₉ rfl]
+ change CallAction.localStep (c₉.put (pc 10) (reg 2) (c₉.reg (reg 2)+c₉.reg (reg 4))) = _
+ simp [c₁₀,c₉,c₈,c₇,c₆,c₅,tested,c₄,c₃,c₂,c₁,Config.put,dst]
+ have s₁₀ : M.program.step c₁₀ = .localStep out := by
+ rw [step_at hl 10 c₁₀ rfl]
+ change CallAction.localStep (c₁₀.put copy (reg 1) (c₁₀.reg (reg 2)+c₁₀.reg (reg 1))) = _
+ simp [out,c₁₀,c₉,c₈,c₇,c₆,c₅,tested,c₄,c₃,Config.put]
+ let es : List (Event w) := [.read f (mem f.val),.tick,.tick,.read (f+1) (mem (f+1).val),.tick,.tick]
+ have tail : ReadPrefix M mem (tested (if len=0 then done else pc 5)) es out := by
+ rw [ite_eq_right hz]
+ exact .read _ s₅ (.tick s₆ (.tick s₇ (.read _ s₈ (.tick s₉ (.tick s₁₀ (.nil _))))))
+ have ht : headerEvents mem f = first ++ es := by
+ change first ++ (if len = 0 then [] else es) = _
+ rw [ite_eq_right hz]
+ refine ⟨out, ⟨?_, ?_, ?_, rfl, rfl⟩, ?_⟩
+ · change copy = if len=0 then done else copy
+ simp [hz]
+ · intro _
+ simp [out,c₁₀,c₉,c₈,c₇,Config.put, dst, f, len]
+ · intro j hj₀ hj₁ hj₂ hj₄
+ simp [out,c₁₀,c₉,c₈,c₇,c₆,c₅,tested,c₄,c₃,c₂,c₁,Config.put,Function.update_of_ne hj₀,
+ Function.update_of_ne hj₁,Function.update_of_ne hj₂,Function.update_of_ne hj₄]
+ · intro fuel bs
+ change execute M.program (fuel+(headerEvents mem f).length) c mem bs = _
+ rw [ht]
+ exact (test tail).execute fuel bs
+
+/-- A zero-length frame returns directly. A nonempty frame also executes
+the full private-copy loop after its three header reads. -/
+def frameEvents (mem : Memory w) (frame : Word w) (bs : List Bool) : List (Event w) :=
+ headerEvents mem frame ++ if bs.isEmpty then [] else PrivateFields.events .copy bs
+
+theorem frame_work (mem : Memory w) (frame : Word w) (bs : List Bool)
+ (h : (mem (frame+1+1).val).val = bs.length) :
+ (frameEvents mem frame bs).length = (if bs.isEmpty then 5 else 5*bs.length+12) ∧
+ countProbes (frameEvents mem frame bs) = (if bs.isEmpty then 1 else 3) := by
+ cases bs with
+ | nil =>
+ have hz : mem (frame+1+1).val = 0 := Fin.ext h
+ simp [frameEvents, headerEvents, hz, countProbes]
+ | cons b bs =>
+ have hne : mem (frame+1+1).val ≠ 0 := by
+ intro hz
+ rw [hz] at h
+ simp at h
+ have hw := PrivateFields.events_work (w := w) .copy (b::bs)
+ simp only [ite_false, reduceCtorEq] at hw
+ simp [frameEvents, headerEvents, hne, countProbes, hw.1, hw.2]
+
+variable {arcPC : Fin 7 → Fin p}
+
+/-- Read a completed frame and copy its declared bits. Fit, source contents
+and forward-copy overlap conditions are needed only for positive lengths.
+Outside its destination interval the entire private memory is preserved. -/
+theorem execute_frame (hl : Linked M pc reg (arcPC 0) done)
+ (hcopy : PrivateFields.Linked M .copy arcPC (copyRegs reg) done)
+ (c : Config w p r) (hc : c.pc = pc 0) (h1 : c.reg (reg 3) = 1)
+ {pub : Fin 6 → Word w} {old new : List ℕ} {initial mem : Memory w} {completed : ℕ}
+ (frames : FramesAt pub old new initial mem completed) (a : Fin completed)
+ (frameFit : (pub 5).val+3*a.val+2 < 2^w) (src dst : ℕ)
+ (hf : c.reg (reg 5) = word w ((pub 5).val+3*a.val))
+ (hs : c.reg (reg 0) = word w src) (hd : c.reg (reg 2) = word w dst)
+ (bs : List Bool) (hlen : bs.length = (sliceAt old new a.val).length)
+ (fit : 0 < bs.length → src + (sliceAt old new a.val).sourceOffset + bs.length ≤ 2^w ∧
+ dst + (sliceAt old new a.val).targetOffset + bs.length < 2^w)
+ (safe : 0 < bs.length → dst + (sliceAt old new a.val).targetOffset ≤ src + (sliceAt old new a.val).sourceOffset ∨
+ src + (sliceAt old new a.val).sourceOffset + bs.length ≤ dst + (sliceAt old new a.val).targetOffset)
+ (data : ∀ i : Fin bs.length,
+ c.privateMem (word w (src+(sliceAt old new a.val).sourceOffset+i.val)) = PrivateFields.bitValue w bs[i.val]) :
+ ∃ out, out.pc = done ∧ out.persistent = c.persistent ∧
+ out.privateMem = PrivateFields.storeBits (dst+(sliceAt old new a.val).targetOffset) bs c.privateMem ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j) ∧
+ (∀ fuel more, execute M.program (fuel+(frameEvents mem (c.reg (reg 5)) bs).length) c mem more =
+ (execute M.program fuel out mem more).map
+ (fun rep ↦ ⟨frameEvents mem (c.reg (reg 5)) bs ++ rep.events,rep.result⟩)) ∧
+ (frameEvents mem (c.reg (reg 5)) bs).length = (if bs.isEmpty then 5 else 5*bs.length+12) ∧
+ countProbes (frameEvents mem (c.reg (reg 5)) bs) = (if bs.isEmpty then 1 else 3) := by
+ let base := (pub 5).val+3*a.val
+ let frame := c.reg (reg 5)
+ let s := sliceAt old new a.val
+ have ha₀ : frame.val = base := by rw [show frame = word w base from hf, val_word (by dsimp [base]; omega)]
+ have ha₁ : (frame+1).val = base+1 := by
+ rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (by omega : 1 < 2^w), ha₀,
+ Nat.mod_eq_of_lt (by dsimp [base]; omega)]
+ have ha₂ : (frame+1+1).val = base+2 := by
+ rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (by omega : 1 < 2^w), ha₁,
+ Nat.mod_eq_of_lt (by dsimp [base]; omega)]
+ have hlenWord : (mem (frame+1+1).val).val = bs.length := by
+ rw [ha₂, hlen]
+ exact frames.lengths a.val a.isLt
+ obtain ⟨prepared, prep, run⟩ := execute_header hl c hc h1 mem
+ obtain ⟨work, probes⟩ := frame_work mem frame bs hlenWord
+ cases bs with
+ | nil =>
+ have hz : mem (frame+1+1).val = 0 := Fin.ext hlenWord
+ have hpc : prepared.pc = done := prep.pc.trans (ite_eq_left hz)
+ refine ⟨prepared,hpc,prep.persistent,prep.memory,prep.frameRegs,?_,work,probes⟩
+ intro fuel more
+ simpa [frameEvents] using run fuel more
+ | cons b bs =>
+ let bits := b :: bs
+ have hp : 0 < bits.length := Nat.succ_pos _
+ have hnz : mem (frame+1+1).val ≠ 0 := by
+ intro he
+ rw [he] at hlenWord
+ simp at hlenWord
+ have hpc : prepared.pc = arcPC 0 := prep.pc.trans (ite_eq_right hnz)
+ obtain ⟨pa,pb,pe⟩ := prep.args hnz
+ obtain ⟨hso,hto⟩ := frames.offsets a.val a.isLt (by rw [← hlen]; exact hp)
+ have hsrc : mem frame.val = word w s.sourceOffset := by
+ rw [ha₀]
+ apply Fin.ext
+ rw [show (mem base).val = s.sourceOffset from hso]
+ exact (Nat.mod_eq_of_lt (hso ▸ (mem base).isLt)).symm
+ have hdst : mem (frame+1).val = word w s.targetOffset := by
+ rw [ha₁]
+ apply Fin.ext
+ rw [show (mem (base+1)).val = s.targetOffset from hto]
+ exact (Nat.mod_eq_of_lt (hto ▸ (mem (base+1)).isLt)).symm
+ have hlen' : mem (frame+1+1).val = word w bits.length := by
+ apply Fin.ext
+ rw [show (mem (frame+1+1).val).val = bits.length from hlenWord]
+ exact (Nat.mod_eq_of_lt (hlenWord ▸ (mem (frame+1+1).val).isLt)).symm
+ have hs' : prepared.reg ((copyRegs reg) 0) = word w (src+s.sourceOffset) := by
+ change prepared.reg (reg 0) = _
+ rw [pa, hs, hsrc]; simp [word]
+ have hd' : prepared.reg ((copyRegs reg) 2) = word w (dst+s.targetOffset) := by
+ change prepared.reg (reg 2) = _
+ rw [pb, hd, hdst]; simp [word]
+ have he' : prepared.reg ((copyRegs reg) 1) = word w (dst+s.targetOffset+bits.length) := by
+ change prepared.reg (reg 1) = _
+ rw [pe, show prepared.reg (reg 2) = word w (dst+s.targetOffset) from hd', hlen']; simp [word]
+ have hone : prepared.reg ((copyRegs reg) 3) = 1 :=
+ (prep.frameRegs (reg 3) (reg.injective.ne (by decide)) (reg.injective.ne (by decide))
+ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans h1
+ obtain ⟨out,res,crun⟩ := PrivateFields.execute_copy hcopy prepared hpc (src+s.sourceOffset)
+ (dst+s.targetOffset) bits hs' hd' he' hone (fit hp).2 (fit hp).1 (safe hp)
+ (by rw [prep.memory]; exact data)
+ refine ⟨out,res.pc,res.persistent.trans prep.persistent,?_,?_,?_,work,probes⟩
+ · rw [res.privateMem, prep.memory]
+ · intro j h₀ h₁ h₂ h₄
+ exact (res.frame j h₀ h₂ h₄).trans (prep.frameRegs j h₀ h₁ h₂ h₄)
+ · intro fuel more
+ have hrun := run (fuel+(5*bits.length+1)) more
+ rw [crun] at hrun
+ have hframe : frameEvents mem frame bits = headerEvents mem frame ++ PrivateFields.events .copy bits := rfl
+ rw [show frameEvents mem (c.reg (reg 5)) (b :: bs) = _ from hframe, List.length_append,
+ (PrivateFields.events_work (w := w) .copy bits).1]
+ simp only [reduceCtorEq, ite_false]
+ simpa [Option.map_map, Function.comp_def, frame, List.append_assoc, Nat.add_assoc,
+ Nat.add_comm (headerEvents mem (c.reg (reg 5))).length] using hrun
+
+end PairSimulation.PrivateSlices
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationReadDecode.lean b/lean/OAI/Computability/VPVNP/PairSimulationReadDecode.lean
new file mode 100644
index 0000000000..ab423cd40e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationReadDecode.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.PairSimulationFieldRead
+import OAI.Computability.VPVNP.PairSimulationMapLookup
+
+/-!
+# Reading and decoding one selector inside a vertex call
+
+The field loop exits directly at the selector table's first instruction.
+Both fragments use the same accumulator for the raw tag and the same
+temporary. The ordinal can replace the accumulator or be retained in a
+separate register. Unused codes go to the rejecting exit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ReadDecode
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM MotifEntry
+open scoped Fin.CommRing
+
+variable {X : Type*} {w p r k b len : ℕ}
+
+/-- The code table for one selector uses the field reader's result and
+temporary registers. -/
+def selectorFlow (xs : List X) (key name : X → Fin k) (reg : Fin 6 ↪ Fin r)
+ (out : Fin r) : Flow r k :=
+ (MapLookup.table [()] (fun x _ ↦ key x) xs).flow (fun _ ↦ reg 0) (reg 5) out name
+
+/-- The complete in-call result, including the raw tag when the output is
+allocated separately. The cursor points at the low end of the field. -/
+def Runs (M : Machine w p r k) (c : Config w p r) (reg : Fin 6 ↪ Fin r)
+ (out : Fin r) (stop bad : Fin p) (name : X → Fin k) (raw : Word w)
+ (low cap : ℕ) (result : Option X) : Prop :=
+ ∃ n final, n ≤ cap ∧ Prefix M c (List.replicate n .tick) final ∧
+ (match result with
+ | none => final.pc = bad
+ | some x => final.pc = stop ∧ final.reg out = M.publicData (name x)) ∧
+ final.reg (reg 1) = (low : Word w) ∧
+ (reg 0 ≠ out → final.reg (reg 0) = raw) ∧
+ (∀ a, a ≠ reg 0 → a ≠ reg 1 → a ≠ reg 5 → a ≠ out → final.reg a = c.reg a) ∧
+ final.privateMem = c.privateMem ∧ final.persistent = c.persistent
+
+/-- A missing selector rejects even if the budget expires before the lookup. -/
+theorem Runs.rejects {M : Machine w p r k} {c : Config w p r} {reg : Fin 6 ↪ Fin r}
+ {out : Fin r} {stop bad : Fin p} {name : X → Fin k} {raw : Word w} {low cap : ℕ}
+ (h : Runs M c reg out stop bad name raw low cap none) (hb : M.code bad = .reject)
+ (fuel : ℕ) (mem : Memory w) (bits : List Bool) : execute M.program fuel c mem bits = none := by
+ obtain ⟨n, d, _, pre, hd, _⟩ := h
+ exact MapLookup.reject_after_ticks pre (fun e he ↦ List.eq_of_mem_replicate he)
+ (hd ▸ hb) fuel mem bits
+
+/-- From the field loop entry, read the actual private bits and compare the
+result against the public code table. A field in the padded tail needs no
+additional initialized cells. The two bounds are instruction dispatches. -/
+theorem native (M : Machine w p r k) (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r)
+ (out : Fin r) (hcur : reg 1 ≠ out) (xs : List X) (code : X ↪ Word b)
+ (key name : X → Fin k) (fits : b ≤ w)
+ (hkey : ∀ x, M.publicData (key x) = MapLookup.widen fits (code x))
+ (label : (selectorFlow xs key name reg out).Label → Fin p) (stop bad : Fin p)
+ (read : FieldRead.Linked M pc reg (label (selectorFlow xs key name reg out).entry))
+ (lookup : Flow.Linked M (selectorFlow xs key name reg out) label stop bad)
+ (bits : Fin len → Bool) (base off : ℕ) (c : Config w p r) (hc : c.pc = pc 0)
+ (hf : base + off + b < 2 ^ w) (hd : base + len < 2 ^ w) (hzero : c.reg (reg 0) = 0)
+ (hhigh : c.reg (reg 1) = ((base + off + b : ℕ) : Word w))
+ (hlow : c.reg (reg 2) = ((base + off : ℕ) : Word w))
+ (hend : c.reg (reg 3) = ((base + len : ℕ) : Word w)) (hone : c.reg (reg 4) = 1)
+ (hdata : ∀ i : Fin len, c.privateMem ((base + i.val : ℕ) : Word w) = encodeBit w (bits i)) :
+ Runs M c reg out stop bad name (MapLookup.widen fits (fieldIndex bits off b))
+ (base + off) ((6 * b + 1) + (2 * xs.length + 1))
+ (decode xs code (fieldIndex bits off b)) := by
+ obtain ⟨mid, pre, hm, hv, hcursor, frame, hmem, hstate⟩ :=
+ FieldRead.native_read read bits base off b c hc fits hf hd hzero hhigh hlow hend hone hdata
+ rw [meteredField_spec] at pre
+ have htag : mid.reg (reg 0) = MapLookup.widen fits (fieldIndex bits off b) := Fin.ext hv
+ obtain ⟨n, final, bound, scan, exit, rest, mem, state⟩ :=
+ MapLookup.native_selector fits xs code key name (reg 0) (reg 5) out
+ (reg.injective.ne (by decide)) (fieldIndex bits off b) M hkey label stop bad
+ lookup mid hm htag
+ refine ⟨(6 * b + 1) + n, final, Nat.add_le_add_left bound _, ?_, exit, ?_, ?_, ?_,
+ mem.trans hmem, state.trans hstate⟩
+ · rw [List.replicate_add]
+ exact pre.append scan
+ · exact (rest _ (reg.injective.ne (by decide)) hcur).trans hcursor
+ · intro ha
+ exact (rest _ (reg.injective.ne (by decide)) ha).trans htag
+ · intro a h₀ h₁ h₅ ha
+ exact (rest _ h₅ ha).trans (frame a h₀ h₁ h₅)
+
+/-- The selector read for copy i starts above the payload. Its two absolute
+endpoints fit whenever the incident wire's exclusive end fits. -/
+theorem tag_fits {u payload : ℕ} (base : ℕ) (i : Fin u)
+ (fit : base + (payload + u * b) < 2 ^ w) :
+ base + (payload + b * i.val) + b < 2 ^ w := by
+ have h := Nat.mul_le_mul_left b i.isLt
+ rw [Nat.mul_succ] at h
+ rw [Nat.mul_comm u b] at fit
+ omega
+
+/-- Decode the exact selector used by the motif evaluator on an incident
+wire. The program and its public code ports are fixed across copy indices. -/
+theorem native_tag {u payload : ℕ} (M : Machine w p r k) (pc : Fin 7 → Fin p)
+ (reg : Fin 6 ↪ Fin r) (out : Fin r) (hcur : reg 1 ≠ out) (xs : List X)
+ (code : X ↪ Word b) (key name : X → Fin k) (fits : b ≤ w)
+ (hkey : ∀ x, M.publicData (key x) = MapLookup.widen fits (code x))
+ (label : (selectorFlow xs key name reg out).Label → Fin p) (stop bad : Fin p)
+ (read : FieldRead.Linked M pc reg (label (selectorFlow xs key name reg out).entry))
+ (lookup : Flow.Linked M (selectorFlow xs key name reg out) label stop bad)
+ (bits : Fin (payload + u * b) → Bool) (base : ℕ) (i : Fin u) (c : Config w p r)
+ (hc : c.pc = pc 0) (hd : base + (payload + u * b) < 2 ^ w) (hzero : c.reg (reg 0) = 0)
+ (hhigh : c.reg (reg 1) = ((base + (payload + b * i.val) + b : ℕ) : Word w))
+ (hlow : c.reg (reg 2) = ((base + (payload + b * i.val) : ℕ) : Word w))
+ (hend : c.reg (reg 3) = ((base + (payload + u * b) : ℕ) : Word w))
+ (hone : c.reg (reg 4) = 1)
+ (hdata : ∀ j : Fin (payload + u * b),
+ c.privateMem ((base + j.val : ℕ) : Word w) = encodeBit w (bits j)) :
+ Runs M c reg out stop bad name (MapLookup.widen fits (readTag bits i))
+ (base + (payload + b * i.val)) ((6 * b + 1) + (2 * xs.length + 1))
+ (decode xs code (readTag bits i)) :=
+ native M pc reg out hcur xs code key name fits hkey label stop bad read lookup bits base _
+ c hc (tag_fits base i hd) hd hzero hhigh hlow hend hone hdata
+
+end PairSimulation.ReadDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRecordedMapCalls.lean b/lean/OAI/Computability/VPVNP/PairSimulationRecordedMapCalls.lean
new file mode 100644
index 0000000000..1263ba01e8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRecordedMapCalls.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.PairSimulationEntryWork
+import OAI.Computability.VPVNP.ShrinkHistory
+import OAI.Computability.VPVNP.RefreshHistory
+
+/-!
+# Map work at selected shrink and refresh records
+
+The degree in an actual map record is exactly the number of copies in its
+motif call. The input coordinates are read from independently supplied old,
+new and absorbed half-wire arguments. No global consistency of those
+arguments is required.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression Compression.PackingData Compression.ShrinkMotif
+open NetworkKernel MotifConversion
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+
+section Shrink
+
+variable {V H Tag L : Type} {d c d' pad : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (P : PackingData V H Tag L d c) (number : P.BundleNumbering) (order : P.ThickNumbering)
+variable (w : Arc V H Tag L d c → ℕ) (sel : ∀ m, P.ShrinkChoice number w B.shrink m)
+
+set_option maxHeartbeats 1600000 in
+-- Elaborating the packed resident types reduces the full six-party layout.
+/-- Use the recorded six-party row's own demand and supply fields. The
+result has the exact degree recorded by the chosen layout. -/
+noncomputable def recordedShrinkCall (hc : 2 ≤ c) (hd : 0 < d) (l : Bool) (subdiv : Fin 4 → ℕ)
+ {next : Equiv.Perm (V × Tag)} (I : P.ShrinkIndex l subdiv next d' pad)
+ (hsub : ∀ t, 0 < subdiv t) (site : (V × Tag) × L) (m : P.ResidentMap l site)
+ (x : Placed (P.shrinkPlace l) (P.oldWireNetwork w).Half site)
+ (h : Placed (P.shrinkInternalOwner l) (internalLabel
+ (fun m ↦ P.shrinkSupplyWidths number w B.shrink m (sel m)) l) site)
+ (z : (P.shrinkOutput l subdiv (fun m t ↦
+ P.shrinkSupplyWidths number w B.shrink m (sel m) (l, t)) I).Half site) :
+ MapInvocation B ((P.shrinkSiteRecords number w B.shrink sel l site).degree m) :=
+ .shrink ⟨P.shrinkDemandWidths number w m.1.1, (sel m.1.1).val, m.1.2,
+ P.shrinkLocalDemandArg hc hd number order w l m.1.1 m.1.2 (m.2.symm ▸ x),
+ P.shrinkLocalSupplyArg l subdiv _ I hsub m.1.1 m.1.2 (m.2.symm ▸ h) (m.2.symm ▸ z)⟩ le_rfl
+
+end Shrink
+
+open Refresh DegreeRefresh MotifDemandPadding MotifSelector
+
+section Refresh
+
+variable {g : ℕ} (X : State S.portExponent (S.portExponent + g))
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+variable (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh)
+
+/-- At a refreshed port, only row zero is a motif call. The remaining two
+rows test equalities and perform no parameter lookup. -/
+noncomputable def recordedRefreshCall (v : (X.Base × Fin (2 ^ S.portExponent)) × BitWord g)
+ (m : Fin 3)
+ (x : HalfBits tieSource tieTarget (blockDemandWidths (splitSlots X)
+ (bitWordFinEquiv _) (splitWidths X) (v.1.1, v.2)) v.1.2)
+ (y : Half S.portSupply (fun e ↦ MotifSelector.Word (supplyWidths B.refresh
+ (blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) (v.1.1, v.2))
+ (choice (v.1.1, v.2)).val e)) v.1.2) :
+ MapInvocation B ((refreshLocalRecords X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2
+ (f ∘ Sum.inr) ((B.solution_iff f).mp hf).2 choice v).degree m) := by
+ by_cases h : m = 0
+ · subst m
+ exact .refresh ⟨_, (choice (v.1.1, v.2)).val, v.1.2, x, y⟩ le_rfl
+ · exact .noLookup
+
+end Refresh
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRefreshSliceClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationRefreshSliceClock.lean
new file mode 100644
index 0000000000..64f312370b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRefreshSliceClock.lean
@@ -0,0 +1,264 @@
+import OAI.Computability.VPVNP.PairSimulationPrivateSlices
+import OAI.Computability.VPVNP.CompressorRecordRefreshReadback
+
+/-!
+# Reading and copying external segments at a refreshed port
+
+The refresh directory stores widths and offsets in separate columns. Both local
+directions use the same native copy code with their own column bases. Its six setup
+instructions address the columns, read the interval and prepare the private copy.
+The final loop test is executed even for an empty segment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RefreshSliceClock
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.read ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r k : ℕ}
+
+/-- Registers 0–4 use the private-copy ABI. Registers 5–7 hold the segment
+ordinal and the two directory column heads. -/
+def instruction (pc : Fin 6 → Fin p) (reg : Fin 8 ↪ Fin r) (copy : Fin p) :
+ Fin 6 → Instr w p r k :=
+ ![.binary .add (reg 4) (reg 6) (reg 5) (pc 1), .readExternal (reg 1) (reg 4) (pc 2),
+ .binary .add (reg 4) (reg 7) (reg 5) (pc 3), .readExternal (reg 4) (reg 4) (pc 4),
+ .binary .add (reg 0) (reg 0) (reg 4) (pc 5), .binary .add (reg 1) (reg 2) (reg 1) copy]
+
+theorem resize_instruction (pc : Fin 6 → Fin p) (reg : Fin 8 ↪ Fin r) (copy : Fin p) (i : Fin 6) :
+ (instruction (w := 1) (k := k) pc reg copy i).resize w = instruction pc reg copy i := by
+ fin_cases i <;> rfl
+
+/-- At the six supplied program counters the machine executes the refreshed segment's setup,
+reading width and offset from their columns and entering the private copy loop. -/
+def Linked (M : Machine w p r k) (pc : Fin 6 → Fin p) (reg : Fin 8 ↪ Fin r) (copy : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction pc reg copy i
+
+/-- Restrict the segment setup's eight-register allocation to the first five registers used by
+the private copy loop. -/
+def copyRegs (reg : Fin 8 ↪ Fin r) : Fin 5 ↪ Fin r := (Fin.castAddEmb 3).trans reg
+
+/-- The six setup events for one refreshed segment, including reads at the width and offset
+column heads plus the segment ordinal and the values returned there. -/
+def headerEvents (mem : Memory w) (width offset ordinal : Word w) : List (Event w) :=
+ [.tick, .read (width + ordinal) (mem (width + ordinal).val),
+ .tick, .read (offset + ordinal) (mem (offset + ordinal).val), .tick, .tick]
+
+/-- Trace for one refreshed segment from its two directory reads through the last copy-loop
+test. It costs seven events plus five per bit and makes exactly two external probes. -/
+def segmentEvents (mem : Memory w) (width offset ordinal : Word w) (bs : List Bool) :
+ List (Event w) :=
+ headerEvents mem width offset ordinal ++ PrivateFields.events .copy bs
+
+theorem segment_work (mem : Memory w) (width offset ordinal : Word w) (bs : List Bool) :
+ (segmentEvents mem width offset ordinal bs).length = 7 + 5 * bs.length ∧
+ countProbes (segmentEvents mem width offset ordinal bs) = 2 := by
+ have h := PrivateFields.events_work (w := w) .copy bs
+ simp [segmentEvents, headerEvents, h.1, h.2, countProbes]
+ omega
+
+variable {M : Machine w p r k} {pc : Fin 6 → Fin p} {reg : Fin 8 ↪ Fin r} {copy : Fin p}
+
+private theorem step_at (hl : Linked M pc reg copy) (i : Fin 6) {c : Config w p r}
+ (hc : c.pc = pc i) : M.program.step c = (instruction pc reg copy i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+/-- Read the two actual cells and prepare the source, destination and end operands. -/
+theorem execute_header (hl : Linked M pc reg copy) (c : Config w p r) (hc : c.pc = pc 0)
+ (mem : Memory w) :
+ let id := c.reg (reg 5)
+ let wid := c.reg (reg 6)
+ let off := c.reg (reg 7)
+ ∃ d, d.pc = copy ∧ d.reg (reg 0) = c.reg (reg 0) + mem (off + id).val ∧
+ d.reg (reg 1) = c.reg (reg 2) + mem (wid + id).val ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 4 → d.reg j = c.reg j) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ ∀ fuel bs, execute M.program (fuel + 6) c mem bs =
+ (execute M.program fuel d mem bs).map
+ (fun rep => ⟨headerEvents mem wid off id ++ rep.events, rep.result⟩) := by
+ intro id wid off
+ let c₁ := c.put (pc 1) (reg 4) (wid + id)
+ let c₂ := c₁.put (pc 2) (reg 1) (mem (wid + id).val)
+ let c₃ := c₂.put (pc 3) (reg 4) (off + id)
+ let c₄ := c₃.put (pc 4) (reg 4) (mem (off + id).val)
+ let c₅ := c₄.put (pc 5) (reg 0) (c.reg (reg 0) + mem (off + id).val)
+ let d := c₅.put copy (reg 1) (c.reg (reg 2) + mem (wid + id).val)
+ have path : ReadPrefix M mem c (headerEvents mem wid off id) d := by
+ refine ReadPrefix.tick (d := c₁) (step_at hl 0 hc)
+ (ReadPrefix.read (g := fun v => c₁.put (pc 2) (reg 1) v) _ ?_
+ (ReadPrefix.tick (d := c₃) ?_ (ReadPrefix.read (g := fun v => c₃.put (pc 4) (reg 4) v) _ ?_
+ (ReadPrefix.tick (d := c₅) ?_ (ReadPrefix.tick ?_ (ReadPrefix.nil d))))))
+ · rw [step_at hl 1 (c := c₁) rfl]
+ change CallAction.read (c₁.reg (reg 4)) _ = _
+ rw [Config.put_same]
+ · rw [step_at hl 2 (c := c₂) rfl]
+ change CallAction.localStep (c₂.put (pc 3) (reg 4) (c₂.reg (reg 7) + c₂.reg (reg 5))) = _
+ simp [c₃, c₂, c₁, Config.put, off, id]
+ · rw [step_at hl 3 (c := c₃) rfl]
+ change CallAction.read (c₃.reg (reg 4)) _ = _
+ rw [Config.put_same]
+ · rw [step_at hl 4 (c := c₄) rfl]
+ change CallAction.localStep (c₄.put (pc 5) (reg 0) (c₄.reg (reg 0) + c₄.reg (reg 4))) = _
+ simp [c₅, c₄, c₃, c₂, c₁, Config.put]
+ · rw [step_at hl 5 (c := c₅) rfl]
+ change CallAction.localStep (c₅.put copy (reg 1) (c₅.reg (reg 2) + c₅.reg (reg 1))) = _
+ simp [d, c₅, c₄, c₃, c₂, c₁, Config.put]
+ refine ⟨d, rfl, by simp [d, c₅, Config.put], Config.put_same .., ?_, rfl, rfl,
+ ReadPrefix.execute path⟩
+ intro j h₀ h₁ h₄
+ simp [d, c₅, c₄, c₃, c₂, c₁, Config.put, Function.update_of_ne h₀,
+ Function.update_of_ne h₁, Function.update_of_ne h₄]
+
+variable {arcPC : Fin 7 → Fin p} {done : Fin p}
+
+/-- Exact native run for the independently supplied half-word at one port. -/
+theorem execute_segment (hl : Linked M pc reg (arcPC 0))
+ (hcopy : PrivateFields.Linked M .copy arcPC (copyRegs reg) done) (mem : Memory w)
+ (c : Config w p r) (hc : c.pc = pc 0) (src dst : ℕ) (bs : List Bool)
+ (hs : c.reg (reg 0) = (src : Word w)) (hd : c.reg (reg 2) = (dst : Word w))
+ (hone : c.reg (reg 3) = 1)
+ (len : (mem (c.reg (reg 6) + c.reg (reg 5)).val).val = bs.length)
+ (dstFit : dst + bs.length < 2 ^ w) :
+ let id := c.reg (reg 5)
+ let wid := c.reg (reg 6)
+ let off := c.reg (reg 7)
+ let start := src + (mem (off + id).val).val
+ start + bs.length ≤ 2 ^ w → (dst ≤ start ∨ start + bs.length ≤ dst) →
+ (∀ i : Fin bs.length,
+ c.privateMem ((start + i.val : ℕ) : Word w) = PrivateFields.bitValue w bs[i.val]) →
+ ∃ out, out.pc = done ∧ out.persistent = c.persistent ∧
+ out.privateMem = PrivateFields.storeBits dst bs c.privateMem ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j) ∧
+ ∀ fuel tail, execute M.program (fuel + (7 + 5 * bs.length)) c mem tail =
+ (execute M.program fuel out mem tail).map
+ (fun rep => ⟨segmentEvents mem wid off id bs ++ rep.events, rep.result⟩) := by
+ intro id wid off start srcFit safe data
+ obtain ⟨d, dp, s, e, keep, dm, dt, run⟩ := execute_header hl c hc mem
+ have s' : d.reg ((copyRegs reg) 0) = (start : Word w) := by
+ change d.reg (reg 0) = _
+ simp only [s, hs, start, Nat.cast_add, Fin.cast_val_eq_self, off, id]
+ have e' : d.reg ((copyRegs reg) 1) = ((dst + bs.length : ℕ) : Word w) := by
+ change d.reg (reg 1) = _
+ rw [e, hd, ← len, Nat.cast_add, Fin.cast_val_eq_self]
+ have fixReg (i : Fin 8) (h₀ : i ≠ 0) (h₁ : i ≠ 1) (h₄ : i ≠ 4) : d.reg (reg i) = c.reg (reg i) :=
+ keep _ (reg.injective.ne h₀) (reg.injective.ne h₁) (reg.injective.ne h₄)
+ obtain ⟨out, res, copyRun⟩ := PrivateFields.execute_copy hcopy d dp start dst bs s'
+ ((fixReg 2 (by decide) (by decide) (by decide)).trans hd) e'
+ ((fixReg 3 (by decide) (by decide) (by decide)).trans hone) dstFit srcFit safe (dm ▸ data)
+ refine ⟨out, res.pc, res.persistent.trans dt, dm ▸ res.privateMem, ?_, ?_⟩
+ · intro j h₀ h₁ h₂ h₄
+ exact (res.frame j h₀ h₂ h₄).trans (keep j h₀ h₁ h₄)
+ · intro fuel tail
+ have h := run (fuel + (5 * bs.length + 1)) tail
+ rw [copyRun] at h
+ simpa only [segmentEvents, id, off, wid, Option.map_map, Function.comp_def, List.append_assoc,
+ show fuel + (5 * bs.length + 1) + 6 = fuel + (7 + 5 * bs.length) by omega] using h
+
+section Port
+
+open CompressorRecords CompressorRecords.PortRefresh CompressorRecords.RefreshRAM
+open CompressorRecords.PortRefresh.NewSlots
+open Compression Compression.Refresh Compression.DegreeRefresh
+
+variable {a g : ℕ} (X : State a (a + g)) (q : Fin 8 → BurstRAM.Word w) (mem : Memory w)
+local notation "ord" => sites (D := 2 ^ a) X.baseIndex (bitWordFinEquiv g)
+local notation "S" => Fintype.card X.Base * 2 ^ a * 2 ^ g * 2 ^ a
+
+/-- Physically addressed traces for all segments in either local direction, including
+the diagonal port. The bit index type is the length word read from that direction. -/
+def portTrace (fit : S ≤ 2 ^ w) (outgoing : Bool) (e : DyadicArc X.Base (BitWord g) a)
+ (bits : Fin (Readback.interval X q mem fit outgoing e).1 → Bool) : List (Event w) :=
+ segmentEvents mem (if outgoing then q 1 else q 7) (if outgoing then q 5 else q 6)
+ (idWord ord fit e) (List.ofFn bits)
+
+/-- The native copy consumes the physical interval addressed by the port trace.
+The header ABI takes the two column heads and the source-major port ordinal. -/
+theorem execute_port {fit : S ≤ 2 ^ w} (outgoing : Bool) (e : DyadicArc X.Base (BitWord g) a)
+ (bits : Fin (Readback.interval X q mem fit outgoing e).1 → Bool)
+ (hl : Linked M pc reg (arcPC 0))
+ (hcopy : PrivateFields.Linked M .copy arcPC (copyRegs reg) done)
+ (c : Config w p r) (hc : c.pc = pc 0) (src dst : ℕ)
+ (hs : c.reg (reg 0) = (src : BurstRAM.Word w)) (hd : c.reg (reg 2) = (dst : BurstRAM.Word w))
+ (hone : c.reg (reg 3) = 1) (hi : c.reg (reg 5) = idWord ord fit e)
+ (hw : c.reg (reg 6) = if outgoing then q 1 else q 7)
+ (ho : c.reg (reg 7) = if outgoing then q 5 else q 6) :
+ let interval := Readback.interval X q mem fit outgoing e
+ let start := src + interval.2
+ dst + interval.1 < 2 ^ w → start + interval.1 ≤ 2 ^ w →
+ (dst ≤ start ∨ start + interval.1 ≤ dst) →
+ (∀ i : Fin interval.1, c.privateMem ((start + i.val : ℕ) : BurstRAM.Word w) =
+ PrivateFields.bitValue w (bits i)) →
+ ∃ out, out.pc = done ∧ out.persistent = c.persistent ∧
+ out.privateMem = PrivateFields.storeBits dst (List.ofFn bits) c.privateMem ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j) ∧
+ ∀ fuel tail, execute M.program (fuel + (portTrace X q mem fit outgoing e bits).length)
+ c mem tail = (execute M.program fuel out mem tail).map
+ (fun rep => ⟨portTrace X q mem fit outgoing e bits ++ rep.events, rep.result⟩) := by
+ intro interval start dstFit srcFit safe data
+ have len : (mem (c.reg (reg 6) + c.reg (reg 5)).val).val = interval.1 := by
+ rw [hw, hi]
+ cases outgoing <;> rfl
+ have offset : (mem (c.reg (reg 7) + c.reg (reg 5)).val).val = interval.2 := by
+ rw [ho, hi]
+ cases outgoing <;> rfl
+ have exec := execute_segment hl hcopy mem c hc src dst (List.ofFn bits) hs hd hone
+ (len.trans List.length_ofFn.symm) (by simpa only [List.length_ofFn] using dstFit)
+ simp only [List.length_ofFn, List.getElem_ofFn, offset] at exec
+ obtain ⟨out, exitPC, persistent, contents, frame, run⟩ :=
+ exec srcFit safe (fun i => data ⟨i.val, by simpa using i.isLt⟩)
+ refine ⟨out, exitPC, persistent, contents, frame, fun fuel tail => ?_⟩
+ simpa only [portTrace, (segment_work ..).1, List.length_ofFn, hw, ho, hi] using run fuel tail
+
+theorem port_group_clock {fit : S ≤ 2 ^ w} (stored : SegmentFields X q fit mem)
+ (outgoing : Bool) (v : (X.Base × BitWord g) × Fin (2 ^ a))
+ (bits : ∀ j, Fin (Readback.interval X q mem fit outgoing (v, j)).1 → Bool) :
+ let traces := fun j => portTrace X q mem fit outgoing (v, j) (bits j)
+ (∑ j, (traces j).length) ≤ 2 ^ a * (7 + 5 * X.maxWireWidth) ∧
+ (∑ j, countProbes (traces j)) = 2 ^ a * 2 := by
+ intro traces
+ have hw (j : Fin (2 ^ a)) :
+ (traces j).length ≤ 7 + 5 * X.maxWireWidth ∧ countProbes (traces j) = 2 := by
+ let e := (v, j)
+ have he := Readback.interval_spec X q mem stored e
+ have hb : (Readback.interval X q mem fit outgoing e).1 ≤ X.maxWireWidth := by
+ cases outgoing
+ · rw [he.2]; exact X.width_le_maxWireWidth _
+ · rw [he.1]; exact X.width_le_maxWireWidth _
+ have h := segment_work mem (if outgoing then q 1 else q 7) (if outgoing then q 5 else q 6)
+ (idWord ord fit e) (List.ofFn (bits j))
+ have le : (List.ofFn (bits j)).length ≤ X.maxWireWidth := by simpa using hb
+ exact ⟨h.1.le.trans (Nat.add_le_add_left (Nat.mul_le_mul_left 5 le) 7), h.2⟩
+ constructor
+ · simpa only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] using
+ Finset.sum_le_sum (s := Finset.univ) (fun j _ => (hw j).1)
+ · rw [Finset.sum_congr rfl (fun j _ => (hw j).2)]
+ simp
+
+/-- The refresh kernel takes the outgoing and incoming segments independently. -/
+theorem incident_clock {fit : S ≤ 2 ^ w} (stored : SegmentFields X q fit mem)
+ (v : (X.Base × BitWord g) × Fin (2 ^ a))
+ (bits : ∀ dir j, Fin (Readback.interval X q mem fit dir (v, j)).1 → Bool) :
+ let traces := fun dir j => portTrace X q mem fit dir (v, j) (bits dir j)
+ (∑ j, (traces true j).length) + (∑ j, (traces false j).length) ≤
+ (2 * 2 ^ a) * (7 + 5 * X.maxWireWidth) ∧
+ (∑ j, countProbes (traces true j)) + (∑ j, countProbes (traces false j)) =
+ (2 * 2 ^ a) * 2 := by
+ intro traces
+ have out := port_group_clock X q mem stored true v (bits true)
+ have inc := port_group_clock X q mem stored false v (bits false)
+ rw [two_mul (2 ^ a), Nat.add_mul, Nat.add_mul]
+ exact ⟨Nat.add_le_add out.1 inc.1, congrArg₂ Nat.add out.2 inc.2⟩
+
+end Port
+
+end PairSimulation.RefreshSliceClock
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationResidentDispatchCode.lean b/lean/OAI/Computability/VPVNP/PairSimulationResidentDispatchCode.lean
new file mode 100644
index 0000000000..adc6a4a86d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationResidentDispatchCode.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.PairSimulationResidentMapDispatch
+import OAI.Computability.VPVNP.PairSimulationMapDriverCode
+
+/-!
+# Fixed code for the demand and party dispatch
+
+A table's two instructions per entry are assembled once and then relocated
+into the enclosing shrinking or refreshing role. All control words fit the
+small literal format used by the live vertex program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentMapDispatch.Cases
+
+open BurstRAM BurstRAM.PrivateRAM
+open MapDriver.Program (remaining)
+
+variable {X : Type*} {w p r k : ℕ} (C : Cases X p r)
+
+/-- The address of a case's zero test (`false`) or decrement (`true`). -/
+def address : X × Bool → Fin p
+ | (x, false) => C.test x
+ | (x, true) => C.subtract x
+
+/-- The zero test jumps to the case target on a match. The decrement continues with the tail. -/
+noncomputable def text : X × Bool → Instr 5 p r k
+ | (x, false) => .jumpEq C.index C.zero (C.target x) (C.subtract x)
+ | (x, true) => .binary .sub C.index C.index C.one (C.start (remaining x C.items))
+
+private theorem linked_from (M : Machine w p r k)
+ (h : ∀ a, M.code (C.address a) = (C.text a).resize w)
+ (xs : List X) (nodup : xs.Nodup)
+ (suffix : ∀ x ∈ xs, remaining x C.items = remaining x xs) : C.Linked M xs := by
+ induction xs with
+ | nil => trivial
+ | cons x xs ih =>
+ obtain ⟨fresh, nd⟩ := List.nodup_cons.mp nodup
+ have tail : remaining x C.items = xs := (suffix x (List.mem_cons_self ..)).trans
+ (by simp [remaining])
+ refine ⟨h (x, false), ?_, ih nd ?_⟩
+ · change M.code (C.address (x, true)) = _
+ rw [h]
+ change Instr.binary .sub C.index C.index C.one (C.start (remaining x C.items)) = _
+ rw [tail]
+ · intro y hy
+ have ne : y ≠ x := fun eq ↦ fresh (eq ▸ hy)
+ exact (suffix y (List.mem_cons_of_mem _ hy)).trans (by simp [remaining, ne])
+
+/-- Installing the emitted instructions supplies the case-chain link
+for every fixed enumerated list, including the empty list. -/
+theorem linked (M : Machine w p r k) (nodup : C.items.Nodup)
+ (rows : ∀ a, M.code (C.address a) = (C.text a).resize w) : C.Linked M C.items :=
+ linked_from C M rows C.items nodup fun _ _ ↦ rfl
+
+end PairSimulation.ResidentMapDispatch.Cases
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationResidentDispatchImage.lean b/lean/OAI/Computability/VPVNP/PairSimulationResidentDispatchImage.lean
new file mode 100644
index 0000000000..48940fd241
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationResidentDispatchImage.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.PairSimulationResidentDispatchCode
+
+/-!
+# A relocatable finite image for resident map dispatch
+
+The chosen enumerations are the term descriptor's demand-grid order and the
+motif's party order. A single initialization row supplies zero. All succeeding
+branches use the two checked ordinal chains and end at the corresponding map.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentDispatchImage
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord ResidentMapDispatch
+open scoped Fin.CommRing
+
+variable {Z J : Type*} {p r k w nz nj : ℕ}
+
+/-- Instruction positions for initialization, grid dispatch, and party dispatch within a grid. -/
+abbrev Address (Z J : Type*) := Unit ⊕ (Z × Bool) ⊕ (Z × J × Bool)
+
+/-- The grid and party enumerations, instruction placement, targets, and dispatch registers. -/
+structure Image (Z J : Type*) (nz nj p r : ℕ) where
+ /-- Grid identifiers in demand descriptor order. -/
+ grids : Fin nz ≃ Z
+ /-- Party identifiers in motif order. -/
+ parties : Fin nj ≃ J
+ /-- Machine address assigned to each dispatch instruction. -/
+ place : Address Z J → Fin p
+ /-- Entry address of the resident map for a given grid and party. -/
+ target : Z → J → Fin p
+ /-- Rejecting continuation shared by both dispatch tables. -/
+ bad : Fin p
+ /-- Register holding the grid ordinal. -/
+ grid : Fin r
+ /-- Register holding the party ordinal. -/
+ party : Fin r
+ /-- Register initialized to zero for the case tests. -/
+ zero : Fin r
+ /-- Register supplying one for each ordinal decrement. -/
+ one : Fin r
+
+namespace Image
+
+variable (A : Image Z J nz nj p r)
+
+/-- The comparison chain that selects a party's map target in grid `z`. -/
+def partyCases (z : Z) : Cases J p r where
+ items := List.ofFn A.parties
+ test j := A.place (.inr (.inr (z, j, false)))
+ subtract j := A.place (.inr (.inr (z, j, true)))
+ target := A.target z
+ bad := A.bad
+ index := A.party
+ zero := A.zero
+ one := A.one
+
+/-- The comparison chain that transfers control to the selected grid's party table. -/
+def gridCases : Cases Z p r where
+ items := List.ofFn A.grids
+ test z := A.place (.inr (.inl (z, false)))
+ subtract z := A.place (.inr (.inl (z, true)))
+ target z := (A.partyCases z).start (A.partyCases z).items
+ bad := A.bad
+ index := A.grid
+ zero := A.zero
+ one := A.one
+
+/-- The two-stage dispatch program assembled from the grid and party tables. -/
+def program : Program Z J p r := ⟨A.gridCases, A.partyCases, fun _ ↦ rfl, fun _ ↦ rfl⟩
+
+/-- The instruction at each image position, including the initial write to the zero register. -/
+noncomputable def text : Address Z J → Instr 5 p r k
+ | .inl _ => .constant A.zero 0 (A.gridCases.start A.gridCases.items)
+ | .inr (.inl x) => A.gridCases.text x
+ | .inr (.inr (z, y)) => (A.partyCases z).text y
+
+/-- Every dispatch instruction is installed at its assigned address at the machine's word width. -/
+def Linked (M : Machine w p r k) : Prop := ∀ a, M.code (A.place a) = (A.text a).resize w
+
+/-- The grid, party, zero, and one registers are pairwise distinct. -/
+structure Distinct : Prop where
+ gz : A.zero ≠ A.grid
+ pz : A.zero ≠ A.party
+ go' : A.one ≠ A.grid
+ po : A.one ≠ A.party
+ oz : A.one ≠ A.zero
+ pg : A.party ≠ A.grid
+
+/-- Execute the installed instructions on the actual encoded grid and party
+numbers. The returned PC uses their values in the chosen descriptor orders. -/
+theorem native (M : Machine w p r k) (link : A.Linked M) (apart : A.Distinct)
+ (g : Fin nz) (j : Fin nj) (gfit : g.val < 2 ^ w) (jfit : j.val < 2 ^ w)
+ (c : Config w p r) (pc : c.pc = A.place (.inl ()))
+ (grid : c.reg A.grid = (g.val : Word w)) (party : c.reg A.party = (j.val : Word w))
+ (one : c.reg A.one = 1) :
+ ∃ d, Prefix M c (List.replicate (1 + ((2 * g.val + 1) + (2 * j.val + 1))) .tick) d ∧
+ d.pc = A.target (A.grids g) (A.parties j) ∧
+ (∀ q, q ≠ A.zero → q ≠ A.grid → q ≠ A.party → d.reg q = c.reg q) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ let m := c.put (A.gridCases.start A.gridCases.items) A.zero 0
+ have init : M.program.step c = .localStep m := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, pc, link]
+ rfl
+ have keep (q) (hq : q ≠ A.zero) : m.reg q = c.reg q := by
+ simp [m, Config.put, Function.update_of_ne hq]
+ let gs : Fin A.gridCases.items.length := ⟨g.val, by simp [gridCases]⟩
+ let js : Fin (A.partyCases A.gridCases.items[gs.val]).items.length :=
+ ⟨j.val, by simp [partyCases]⟩
+ have gd : A.gridCases.Linked M A.gridCases.items := A.gridCases.linked M
+ (List.nodup_ofFn_ofInjective A.grids.injective) (fun a ↦ by cases a with | mk z b =>
+ cases b <;> exact link (.inr (.inl (z, _))))
+ have pd (z) : (A.partyCases z).Linked M (A.partyCases z).items := (A.partyCases z).linked M
+ (List.nodup_ofFn_ofInjective A.parties.injective) (fun a ↦ by cases a with | mk j b =>
+ cases b <;> exact link (.inr (.inr (z, j, _))))
+ obtain ⟨d, tail, hd, frame, mem, per⟩ := A.program.hit M gd pd gs js m rfl
+ ((keep _ apart.gz.symm).trans grid) ((keep _ apart.pz.symm).trans party)
+ (Config.put_same ..) ((keep _ apart.oz).trans one) gfit jfit apart.gz apart.go'
+ (fun _ ↦ ⟨apart.pg, rfl, rfl, apart.pz, apart.po⟩)
+ refine ⟨d, ?_, ?_, fun q hz hg hp ↦ (frame q hg hp).trans (keep q hz), mem, per⟩
+ · rw [List.replicate_add]
+ exact .tick init tail
+ · change d.pc = A.target _ _ at hd
+ simpa [program, gridCases, partyCases, gs, js] using hd
+
+end Image
+end PairSimulation.ResidentDispatchImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationResidentMapDispatch.lean b/lean/OAI/Computability/VPVNP/PairSimulationResidentMapDispatch.lean
new file mode 100644
index 0000000000..19f21c4cc8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationResidentMapDispatch.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.PairSimulationMapDriver
+
+/-!
+# Dispatching a resident map by its demand grid and party
+
+Each fixed grid row and party has a distinct matrix image. The selected term
+stores the demand ordinal, and the resident directory supplies the party. Two
+finite comparison chains decrement these ordinals until they reach their own
+images. No public constants beyond the zero and one registers are needed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentMapDispatch
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {X Z J : Type*} {w p r k : ℕ}
+
+/-- A separate test and subtraction instruction for each fixed alternative. -/
+structure Cases (X : Type*) (p r : ℕ) where
+ /-- Cases in ordinal order, starting at zero. -/
+ items : List X
+ /-- Address of each case's test for a zero index. -/
+ test : X → Fin p
+ /-- Address of the decrement that skips each unmatched case. -/
+ subtract : X → Fin p
+ /-- Destination when the corresponding case matches. -/
+ target : X → Fin p
+ /-- Destination when the case list is exhausted. -/
+ bad : Fin p
+ /-- Register holding the remaining ordinal. -/
+ index : Fin r
+ /-- Register used as zero by the comparison instruction. -/
+ zero : Fin r
+ /-- Register used as one by the decrement instruction. -/
+ one : Fin r
+
+namespace Cases
+
+variable (C : Cases X p r)
+
+/-- Enter the first case test, or the rejecting continuation if the list is empty. -/
+def start : List X → Fin p
+ | [] => C.bad
+ | x :: _ => C.test x
+
+/-- The machine tests the current index and decrements it before testing the next case. -/
+def Linked (M : Machine w p r k) : List X → Prop
+ | [] => True
+ | x :: xs => M.code (C.test x) = .jumpEq C.index C.zero (C.target x) (C.subtract x) ∧
+ M.code (C.subtract x) = .binary .sub C.index C.index C.one (C.start xs) ∧ Linked M xs
+
+/-- Dispatch takes two ticks per skipped case and one for a matching case. -/
+def ticks (size i : ℕ) : ℕ := 2 * min size i + if i < size then 1 else 0
+
+theorem ticks_le (size i : ℕ) : ticks size i ≤ 2 * size + 1 := by
+ unfold ticks
+ have := min_le_left size i
+ split <;> omega
+
+/-- A valid ordinal reaches precisely its own table image. Any unused ordinal
+exhausts the chain and enters the rejecting continuation. -/
+theorem run (M : Machine w p r k) (items : List X) (link : C.Linked M items)
+ (i : ℕ) (fit : i < 2 ^ w) (c : Config w p r) (pc : c.pc = C.start items)
+ (val : c.reg C.index = (i : Word w)) (zero : c.reg C.zero = 0) (one : c.reg C.one = 1)
+ (z : C.zero ≠ C.index) (o : C.one ≠ C.index) :
+ ∃ d, Prefix M c (List.replicate (ticks items.length i) .tick) d ∧
+ d.pc = (items[i]?.elim C.bad C.target) ∧
+ (∀ q, q ≠ C.index → d.reg q = c.reg q) ∧ d.privateMem = c.privateMem ∧
+ d.persistent = c.persistent := by
+ induction items generalizing i c with
+ | nil => exact ⟨c, by simpa [ticks] using Prefix.nil (M := M) c, pc, fun _ _ ↦ rfl, rfl, rfl⟩
+ | cons x xs ih =>
+ have head : M.program.step c =
+ .localStep {c with pc := if (i : Word w) = 0 then C.target x else C.subtract x} := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, pc, start, link.1]
+ change CallAction.localStep {c with pc := if c.reg C.index = c.reg C.zero then _ else _} = _
+ rw [val, zero]
+ cases i with
+ | zero =>
+ have h : M.program.step c = .localStep {c with pc := C.target x} := by simpa using head
+ exact ⟨{c with pc := C.target x}, by simpa [ticks] using Prefix.tick h (.nil _),
+ rfl, fun _ _ ↦ rfl, rfl, rfl⟩
+ | succ i =>
+ have nz : ((i + 1 : ℕ) : Word w) ≠ 0 := by
+ intro eq
+ have hv := congrArg Fin.val eq
+ change (i + 1) % (2 ^ w) = 0 at hv
+ rw [Nat.mod_eq_of_lt fit] at hv
+ omega
+ let a := {c with pc := C.subtract x}
+ let b := a.put (C.start xs) C.index (i : Word w)
+ have first : M.program.step c = .localStep a := head.trans (by rw [ite_eq_right nz])
+ have second : M.program.step a = .localStep b := by
+ rw [show M.program.step a = (M.code (C.subtract x)).run M.publicData a from rfl, link.2.1]
+ change CallAction.localStep (a.put (C.start xs) C.index (c.reg C.index - c.reg C.one)) = _
+ simp [b, val, one]
+ have keep (q) (h : q ≠ C.index) : b.reg q = c.reg q := by
+ simp [a, b, Config.put, Function.update_of_ne h]
+ obtain ⟨d, run, outPC, frame, mem, per⟩ := ih link.2.2 i (by omega) b rfl
+ (Config.put_same ..) ((keep C.zero z).trans zero) ((keep C.one o).trans one)
+ have hlen : ticks (x :: xs).length (i + 1) = 2 + ticks xs.length i := by
+ simp only [ticks, List.length_cons, Nat.succ_lt_succ_iff, min_add_add_right]
+ omega
+ refine ⟨d, ?_, outPC, fun q h ↦ (frame q h).trans (keep q h), mem, per⟩
+ rw [hlen, List.replicate_add]
+ exact .tick first (.tick second run)
+
+end Cases
+
+/-- The first fixed table transfers to the selected grid's party table. -/
+structure Program (Z J : Type*) (p r : ℕ) where
+ /-- First-stage table indexed by the demand-grid ordinal. -/
+ grids : Cases Z p r
+ /-- Second-stage party table for each grid. -/
+ parties : Z → Cases J p r
+ enter : ∀ z, grids.target z = (parties z).start (parties z).items
+ bad : ∀ z, (parties z).bad = grids.bad
+
+namespace Program
+
+variable (P : Program Z J p r)
+
+/-- The two-stage native dispatch uses the stored grid and party ordinals.
+All registers outside those two operand words survive both comparison chains. -/
+theorem hit (M : Machine w p r k) (gridLink : P.grids.Linked M P.grids.items)
+ (partyLink : ∀ z, (P.parties z).Linked M (P.parties z).items)
+ (g : Fin P.grids.items.length) (j : Fin (P.parties P.grids.items[g.val]).items.length)
+ (c : Config w p r) (pc : c.pc = P.grids.start P.grids.items)
+ (grid : c.reg P.grids.index = (g.val : Word w))
+ (party : c.reg (P.parties P.grids.items[g.val]).index = (j.val : Word w))
+ (zero : c.reg P.grids.zero = 0) (one : c.reg P.grids.one = 1)
+ (gfit : g.val < 2 ^ w) (jfit : j.val < 2 ^ w)
+ (g₀ : P.grids.zero ≠ P.grids.index) (g₁ : P.grids.one ≠ P.grids.index)
+ (separate : ∀ z, (P.parties z).index ≠ P.grids.index ∧
+ (P.parties z).zero = P.grids.zero ∧ (P.parties z).one = P.grids.one ∧
+ (P.parties z).zero ≠ (P.parties z).index ∧ (P.parties z).one ≠ (P.parties z).index) :
+ let z := P.grids.items[g.val]
+ let C := P.parties z
+ ∃ d, Prefix M c (List.replicate ((2 * g.val + 1) + (2 * j.val + 1)) .tick) d ∧
+ d.pc = C.target C.items[j.val] ∧
+ (∀ q, q ≠ P.grids.index → q ≠ C.index → d.reg q = c.reg q) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ intro z C
+ obtain ⟨a, first, ha, frame, mem, per⟩ := P.grids.run M _ gridLink g.val gfit c pc grid
+ zero one g₀ g₁
+ rw [List.getElem?_eq_getElem g.isLt, Option.elim_some, P.enter] at ha
+ obtain ⟨i, hz, ho, cz, co⟩ := separate z
+ obtain ⟨d, tail, hd, saved, dm, dp⟩ := C.run M _ (partyLink z) j.val jfit a ha
+ ((frame _ i).trans party) (hz ▸ (frame _ g₀).trans zero) (ho ▸ (frame _ g₁).trans one) cz co
+ rw [List.getElem?_eq_getElem j.isLt, Option.elim_some] at hd
+ refine ⟨d, ?_, hd, fun q hq hq' ↦ (saved q hq').trans (frame q hq), dm.trans mem, dp.trans per⟩
+ simp only [Cases.ticks, Nat.min_eq_right g.isLt.le, ite_eq_left g.isLt] at first
+ have hj : j.val < (P.parties z).items.length := j.isLt
+ simp only [Cases.ticks, Nat.min_eq_right hj.le, ite_eq_left hj] at tail
+ rw [List.replicate_add]
+ exact first.append tail
+
+end Program
+end PairSimulation.ResidentMapDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationResidentMapLoop.lean b/lean/OAI/Computability/VPVNP/PairSimulationResidentMapLoop.lean
new file mode 100644
index 0000000000..a41af1ce82
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationResidentMapLoop.lean
@@ -0,0 +1,195 @@
+import OAI.Computability.VPVNP.PairNodeChildLoop
+import OAI.Computability.VPVNP.PairSimulationResidentMapDispatch
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+
+/-!
+# Visiting a selected node's resident map entries
+
+The loop tests the private row cursor against its exclusive end, enters the
+resident entry routine, and advances the cursor only on success. Histograms
+retain the increments of all earlier successful entries when a later map is
+syntactically zero. Neither the directory order nor repeated names are deduplicated.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentMapLoop
+
+open BurstRAM BurstRAM.PrivateRAM NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r k t : ℕ}
+
+/-- The value of one occurrence may be zero. The two bounds include directory
+reads, operand preparation, matrix dispatch, and the private parameter scan. -/
+structure Job (t : ℕ) where
+ /-- Parameter labels emitted by the map, or `none` if it rejects. -/
+ names : Option (List (Fin t))
+ /-- Bound on events in the descriptor read and map execution. -/
+ work : ℕ
+ /-- Bound on probes in the descriptor read and map execution. -/
+ probes : ℕ
+
+/-- Concatenate the labels of successive jobs up to the first failure, retaining multiplicities. -/
+def labels : List (Job t) → List (Fin t)
+ | [] => []
+ | j :: js => j.names.elim [] (fun names ↦ names ++ labels js)
+
+/-- Whether every job returned a list of labels. -/
+def passed (js : List (Job t)) : Bool := js.all fun j ↦ j.names.isSome
+
+/-- Event bound charging a test and an advance per job, plus the final test. -/
+def work (js : List (Job t)) : ℕ := (js.map fun j ↦ 2 + j.work).sum + 1
+
+/-- Sum of the probe bounds for the individual jobs. -/
+def probes (js : List (Job t)) : ℕ := (js.map Job.probes).sum
+
+/-- The item starts at its genuine descriptor-reader entry. The returning
+map takes the increment row; unsuccessful map images enter their rejecting halt. -/
+structure Program (p r : ℕ) where
+ /-- Address of the test for the end of the directory slice. -/
+ test : Fin p
+ /-- Address of the cursor increment after a successful item. -/
+ advance : Fin p
+ /-- Entry address of the current item's descriptor reader. -/
+ item : Fin p
+ /-- Continuation reached when the cursor equals the exclusive end. -/
+ done : Fin p
+ /-- Register holding the current directory row. -/
+ cursor : Fin r
+ /-- Register holding the exclusive end of the directory slice. -/
+ stop : Fin r
+ /-- Register supplying one for cursor increments. -/
+ one : Fin r
+ stopApart : stop ≠ cursor
+ oneApart : one ≠ cursor
+
+namespace Program
+
+variable (P : Program p r)
+
+/-- Test the cursor against its exclusive end (`false`) or advance it and retest (`true`). -/
+def control : Bool → Instr w p r k
+ | false => .jumpEq P.cursor P.stop P.done P.item
+ | true => .binary .add P.cursor P.cursor P.one P.test
+
+/-- The machine contains the cursor test and advance instructions at the loop addresses. -/
+structure Linked (M : Machine w p r k) : Prop where
+ test : M.code P.test = P.control false
+ advance : M.code P.advance = P.control true
+
+/-- Scratch facts for the remaining operands survive the two loop rows. -/
+def Stable (inv : Config w p r → Prop) : Prop :=
+ ∀ c d, inv c → (∀ q, q ≠ P.cursor → d.reg q = c.reg q) →
+ d.privateMem = c.privateMem → d.persistent = c.persistent → inv d
+
+/-- An item reader and map body at its real directory position. The accepted
+result and all future operand buffers can depend on the supplied half-wires. -/
+def Item (M : Machine w p r k) (m : Memory w) (inv : Config w p r → Prop)
+ (hist : Fin t → Word w) (src : ℕ) (j : Job t) : Prop :=
+ ∀ c, c.pc = P.item → c.reg P.cursor = (src : Word w) → inv c →
+ ∃ d es, Prefix M m c d [] es ∧ es.length ≤ j.work ∧ countProbes es ≤ j.probes ∧
+ choiceBits es = [] ∧ (if j.names.isSome then d.pc = P.advance else M.code d.pc = .reject) ∧
+ inv d ∧ d.reg P.cursor = c.reg P.cursor ∧ d.reg P.stop = c.reg P.stop ∧
+ d.reg P.one = c.reg P.one ∧ d.persistent = c.persistent ∧
+ ∀ l, d.privateMem (hist l) = c.privateMem (hist l) + ((j.names.getD []).count l : Word w)
+
+/-- Every source position receives its own callback; a repeated local matrix
+and a repeated output label retain their separate occurrences. -/
+def Items (M : Machine w p r k) (m : Memory w) (inv : Config w p r → Prop)
+ (hist : Fin t → Word w) : ℕ → List (Job t) → Prop
+ | _, [] => True
+ | src, j :: js => P.Item M m inv hist src j ∧ Items M m inv hist (src + 1) js
+
+private theorem tick {M : Machine w p r k} (m : Memory w) {c d : Config w p r}
+ (h : M.program.step c = .localStep d) : Prefix M m c d [] [.tick] :=
+ fun fuel bs ↦ ReadPrefix.execute (ReadPrefix.tick h (ReadPrefix.nil _)) fuel bs
+
+/-- Run the actual loop, retaining the exact prefix of successful parameter
+labels on every rejecting branch. The bounds also hold when the first entry fails. -/
+theorem native (M : Machine w p r k) (m : Memory w) (link : P.Linked M)
+ (inv : Config w p r → Prop) (stable : P.Stable inv) (hist : Fin t → Word w)
+ (js : List (Job t)) (src : ℕ) (items : P.Items M m inv hist src js)
+ (fit : src + js.length < 2 ^ w)
+ (c : Config w p r) (pc : c.pc = P.test) (cursor : c.reg P.cursor = (src : Word w))
+ (stop : c.reg P.stop = ((src + js.length : ℕ) : Word w)) (one : c.reg P.one = 1) (hi : inv c) :
+ ∃ d es, Prefix M m c d [] es ∧ es.length ≤ work js ∧ countProbes es ≤ probes js ∧
+ choiceBits es = [] ∧ (if passed js then d.pc = P.done else M.code d.pc = .reject) ∧ inv d ∧
+ d.persistent = c.persistent ∧ ∀ l, d.privateMem (hist l) = c.privateMem (hist l) +
+ ((labels js).count l : Word w) := by
+ induction js generalizing c src with
+ | nil =>
+ let d := {c with pc := P.done}
+ have step : M.program.step c = .localStep d := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, pc, link.test]
+ simp [control, Instr.run, cursor, stop, d]
+ exact ⟨d, [.tick], tick m step, by simp [work], by simp [probes, countProbes], rfl, rfl,
+ stable c d hi (fun _ _ ↦ rfl) rfl rfl, rfl, fun _ ↦ by simp [labels, d]⟩
+ | cons j js ih =>
+ let a := {c with pc := P.item}
+ have ne : c.reg P.cursor ≠ c.reg P.stop := by
+ rw [cursor, stop]
+ intro eq
+ have e := congrArg Fin.val eq
+ change src % (2 ^ w) = (src + (j :: js).length) % (2 ^ w) at e
+ rw [Nat.mod_eq_of_lt (by simp at fit; omega), Nat.mod_eq_of_lt fit] at e
+ simp at e
+ have step : M.program.step c = .localStep a := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, pc, link.test]
+ simp [control, Instr.run, ne, a]
+ have first := tick m step
+ obtain ⟨mid, es, path, len, probe, choices, hmid, him, cs, st, one', per, hs⟩ :=
+ items.1 a rfl cursor (stable c a hi (fun _ _ ↦ rfl) rfl rfl)
+ cases names : j.names with
+ | none =>
+ have endPC : M.code mid.pc = .reject := by simpa [names] using hmid
+ refine ⟨mid, [Event.tick] ++ es, first.trans path, ?_, ?_, ?_, ?_, him, per, ?_⟩
+ · simp [work]; omega
+ · simpa [probes, countProbes] using probe.trans (Nat.le_add_right _ _)
+ · simpa [choiceBits] using choices
+ · simpa [passed, names] using endPC
+ · simpa [labels, names, a] using hs
+ | some ls =>
+ have hp : mid.pc = P.advance := by simpa [names] using hmid
+ let b := mid.put P.test P.cursor ((src + 1 : ℕ) : Word w)
+ have add : M.program.step mid = .localStep b := by
+ rw [show M.program.step mid = (M.code mid.pc).run M.publicData mid from rfl, hp,
+ link.advance]
+ change CallAction.localStep (mid.put P.test P.cursor (mid.reg P.cursor + mid.reg P.one)) = _
+ rw [cs, one', show a.reg P.cursor = (src : Word w) from cursor,
+ show a.reg P.one = 1 from one]
+ simp [b]
+ have keep (q) (hq : q ≠ P.cursor) : b.reg q = mid.reg q := by
+ simp [b, Config.put, Function.update_of_ne hq]
+ have lenEq : src + 1 + js.length = src + (j :: js).length := by simp; omega
+ obtain ⟨out, tail, run, hlen, hprobe, hchoices, hpc, hout, hper, hhist⟩ :=
+ ih (src + 1) items.2 (lenEq ▸ fit) b rfl (Config.put_same ..)
+ ((keep P.stop P.stopApart).trans (st.trans (lenEq ▸ stop)))
+ ((keep P.one P.oneApart).trans (one'.trans one)) (stable mid b him keep rfl rfl)
+ let events := (([.tick] ++ es) ++ [.tick]) ++ tail
+ refine ⟨out, events, ((first.trans path).trans (tick m add)).trans run, ?_, ?_, ?_, ?_, hout,
+ hper.trans per, ?_⟩
+ · simp only [events, work, List.length_append, List.length_cons, List.length_nil,
+ List.map_cons, List.sum_cons] at hlen ⊢
+ omega
+ · simp only [events, countProbes_append, countProbes, probes, List.map_cons, List.sum_cons,
+ Nat.zero_add, Nat.add_zero] at hprobe ⊢
+ exact Nat.add_le_add probe hprobe
+ · simp [events, PrimedInputRAM.Flow.choiceBits_append, choiceBits, choices, hchoices]
+ · simpa [passed, names] using hpc
+ · intro l
+ rw [hhist]
+ change mid.privateMem (hist l) + _ = _
+ rw [hs l]
+ simp [labels, names, a, add_assoc]
+
+end Program
+end PairSimulation.ResidentMapLoop
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationResidentMapLoopExact.lean b/lean/OAI/Computability/VPVNP/PairSimulationResidentMapLoopExact.lean
new file mode 100644
index 0000000000..9d591daba4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationResidentMapLoopExact.lean
@@ -0,0 +1,225 @@
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoop
+import OAI.Computability.VPVNP.PairShrinkRoleStages
+
+/-!
+# Exact parsing of a resident map loop
+
+Each map acts on the scratch left by its predecessors. A failed entry
+rejects the burst at that occurrence. The native guard and advance rows
+consume no choices and execute at their actual cursor addresses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ResidentMapLoop.Exact
+
+open BurstRAM BurstRAM.PrivateRAM DFS ShrinkRole NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private Program.tick from OAI.Computability.VPVNP.PairSimulationResidentMapLoop
+
+variable {w endAddr p r k : ℕ}
+
+/-- Deterministic evaluation of one selected occurrence on the actual scratch. -/
+abbrev Action (w endAddr : ℕ) :=
+ Word w → Scratch w endAddr → Option (List (Event w) × Scratch w endAddr)
+
+/-- Every successful evaluation of this occurrence, on any node and saved scratch, yields a
+trace with an empty sequence of choice bits. -/
+def NoChoices (j : Action w endAddr) : Prop :=
+ ∀ node saved es updated, j node saved = some (es, updated) → choiceBits es = []
+
+/-- Trace and scratch of the linked test, occurrence, advance and remaining entries. -/
+def scan (node : Word w) : List (Action w endAddr) → Scratch w endAddr →
+ Option (List (Event w) × Scratch w endAddr)
+ | [], s => some ([.tick], s)
+ | j :: js, s =>
+ match j node s with
+ | none => none
+ | some (es, mid) =>
+ match scan node js mid with
+ | none => none
+ | some (tail, out) => some ((([.tick] ++ es) ++ [.tick]) ++ tail, out)
+
+/-- Run the resident occurrences on successive scratch states as a shrink-role reader. Success
+returns their scan trace and final scratch with the entire choice tape as the remainder. -/
+def mapReader (js : List (Action w endAddr)) : Reader w endAddr Unit := fun node saved bs =>
+ (scan node js saved).map fun (es, out) => (⟨(), es, out⟩, bs)
+
+private theorem scan_bits (js : List (Action w endAddr)) (node : Word w)
+ (saved : Scratch w endAddr) {es : List (Event w)} {out : Scratch w endAddr}
+ (quiet : ∀ j ∈ js, NoChoices j) (got : scan node js saved = some (es, out)) :
+ choiceBits es = [] := by
+ induction js generalizing saved es out with
+ | nil =>
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj got)
+ rfl
+ | cons j js ih =>
+ cases h : j node saved with
+ | none => simp [scan, h] at got
+ | some pair =>
+ obtain ⟨first, mid⟩ := pair
+ cases hr : scan node js mid with
+ | none => simp [scan, h, hr] at got
+ | some pair =>
+ obtain ⟨tail, last⟩ := pair
+ simp only [scan, h, hr, Option.some.injEq, Prod.mk.injEq] at got
+ rw [← got.1]
+ simp only [PrimedInputRAM.Flow.choiceBits_append, choiceBits,
+ quiet j List.mem_cons_self node saved first mid h,
+ ih mid (fun v hv => quiet v (List.mem_cons_of_mem _ hv)) hr, List.nil_append]
+
+theorem splitBits {js : List (Action w endAddr)} (quiet : ∀ j ∈ js, NoChoices j)
+ {node : Word w} {saved : Scratch w endAddr} {bs rest : List Bool}
+ {out : Outcome w endAddr Unit} (h : mapReader js node saved bs = some (out, rest)) :
+ bs = choiceBits out.trace ++ rest := by
+ obtain ⟨⟨es, last⟩, got, eqn⟩ := Option.map_eq_some_iff.mp h
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj eqn
+ rw [show choiceBits es = [] from scan_bits js node saved quiet got]
+ rfl
+
+variable (P : Program p r) (M : Machine w p r k) (m : Memory w) (dfs : Fin 9 ↪ Fin r)
+ (inv : Word w → Config w p r → Prop)
+
+/-- Exact deterministic semantics needed from the descriptor reader and the
+selected matrix routine at this one occurrence. -/
+structure Item (src : ℕ) (j : Action w endAddr) : Prop where
+ noChoices : NoChoices j
+ success : ∀ node c es updated, c.pc = P.item → c.reg P.cursor = (src : Word w) → inv node c →
+ j node (scratch endAddr c.privateMem) = some (es, updated) →
+ ∃ d, d.pc = P.advance ∧ inv node d ∧ d.reg P.cursor = c.reg P.cursor ∧
+ d.reg P.stop = c.reg P.stop ∧ d.reg P.one = c.reg P.one ∧ ShrinkRole.Frame dfs endAddr c d ∧
+ scratch endAddr d.privateMem = updated ∧ Prefix M m c d [] es
+ reject : ∀ node c, c.pc = P.item → c.reg P.cursor = (src : Word w) → inv node c →
+ j node (scratch endAddr c.privateMem) = none → ∀ bs, ¬ Returns M c m bs
+
+/-- Exact machine realization of each occurrence in list order at successive cursor positions
+starting at `src`, with both successful execution and rejection specified at each position. -/
+def Items : ℕ → List (Action w endAddr) → Prop
+ | _, [] => True
+ | src, j :: js => Item P M m dfs inv src j ∧ Items (src + 1) js
+
+variable {P M m dfs inv} in
+theorem Items.quiet {js : List (Action w endAddr)} {src : ℕ}
+ (items : Items P M m dfs inv src js) : ∀ j ∈ js, NoChoices j := by
+ induction js generalizing src with
+ | nil => simp
+ | cons j js ih =>
+ intro v hv
+ rcases List.mem_cons.mp hv with rfl | hv
+ · exact items.1.noChoices
+ · exact ih items.2 v hv
+
+/-- Configuration at the scan guard with cursor `src`, exclusive end `src + count`, unit
+increment and the node's operand invariant. This is the entry condition for realizing the
+map reader. -/
+structure Entry (src count : ℕ) (node : Word w) (c : Config w p r) : Prop where
+ pc : c.pc = P.test
+ cursor : c.reg P.cursor = (src : Word w)
+ stop : c.reg P.stop = ((src + count : ℕ) : Word w)
+ one : c.reg P.one = 1
+ ready : inv node c
+
+variable {M m dfs inv}
+
+private theorem native (link : P.Linked M) (stable : ∀ node, P.Stable (inv node))
+ (apart : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → dfs i ≠ P.cursor)
+ (js : List (Action w endAddr)) (src : ℕ) (items : Items P M m dfs inv src js)
+ (fit : src + js.length < 2 ^ w) (node : Word w) (c : Config w p r)
+ (h : Entry P inv src js.length node c) :
+ match scan node js (scratch endAddr c.privateMem) with
+ | none => ∀ bs, ¬ Returns M c m bs
+ | some (es, updated) => ∃ d, d.pc = P.done ∧ inv node d ∧ ShrinkRole.Frame dfs endAddr c d ∧
+ scratch endAddr d.privateMem = updated ∧ Prefix M m c d [] es := by
+ induction js generalizing src c with
+ | nil =>
+ let d := {c with pc := P.done}
+ have step : M.program.step c = .localStep d := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, h.pc, link.test]
+ simp [Program.control, Instr.run, h.cursor, h.stop, d]
+ exact ⟨d, rfl, stable node c d h.ready (fun _ _ => rfl) rfl rfl,
+ ⟨fun _ _ => rfl, fun _ _ => rfl, rfl⟩, rfl, Program.tick m step⟩
+ | cons j js ih =>
+ let a := {c with pc := P.item}
+ have ne : c.reg P.cursor ≠ c.reg P.stop := by
+ rw [h.cursor, h.stop]
+ intro eqn
+ have e := congrArg Fin.val eqn
+ change src % (2 ^ w) = (src + (j :: js).length) % (2 ^ w) at e
+ rw [Nat.mod_eq_of_lt ((Nat.le_add_right ..).trans_lt fit), Nat.mod_eq_of_lt fit] at e
+ simp at e
+ have step : M.program.step c = .localStep a := by
+ rw [show M.program.step c = (M.code c.pc).run M.publicData c from rfl, h.pc, link.test]
+ simp [Program.control, Instr.run, ne, a]
+ have first := Program.tick m step
+ have ready := stable node c a h.ready (fun _ _ => rfl) rfl rfl
+ cases hj : j node (scratch endAddr c.privateMem) with
+ | none =>
+ simp only [scan, hj]
+ exact fun bs => mt (first.returns bs).mp (items.1.reject node a rfl h.cursor ready hj bs)
+ | some pair =>
+ obtain ⟨es, updated⟩ := pair
+ obtain ⟨mid, pc, ri, cs, st, one, frame, mem, path⟩ :=
+ items.1.success node a es updated rfl h.cursor ready hj
+ let b := mid.put P.test P.cursor ((src + 1 : ℕ) : Word w)
+ have add : M.program.step mid = .localStep b := by
+ rw [show M.program.step mid = (M.code mid.pc).run M.publicData mid from rfl,
+ pc, link.advance]
+ change CallAction.localStep (mid.put P.test P.cursor (mid.reg P.cursor + mid.reg P.one)) = _
+ rw [cs, one, show a.reg P.cursor = _ from h.cursor, show a.reg P.one = _ from h.one]
+ simp [b]
+ have keep (q) (hq : q ≠ P.cursor) : b.reg q = mid.reg q := by
+ simp [b, Config.put, Function.update_of_ne hq]
+ have len : src + 1 + js.length = src + (j :: js).length := by simp; omega
+ have next : Entry P inv (src + 1) js.length node b :=
+ ⟨rfl, Config.put_same .., (keep P.stop P.stopApart).trans (st.trans (len ▸ h.stop)),
+ (keep P.one P.oneApart).trans (one.trans h.one), stable node mid b ri keep rfl rfl⟩
+ have pre := (first.trans path).trans (Program.tick m add)
+ have result := ih (src + 1) items.2 (len ▸ fit) b next
+ have memory : scratch endAddr b.privateMem = updated := mem
+ rw [memory] at result
+ cases hr : scan node js updated with
+ | none =>
+ rw [hr] at result
+ simp only [scan, hj, hr]
+ exact fun bs => mt (pre.returns bs).mp (result bs)
+ | some pair =>
+ obtain ⟨tail, last⟩ := pair
+ rw [hr] at result
+ obtain ⟨d, done, rd, fd, sd, run⟩ := result
+ have advance : ShrinkRole.Frame dfs endAddr mid b :=
+ ⟨fun i hi => keep _ (apart i hi), fun _ _ => rfl, rfl⟩
+ have guard : ShrinkRole.Frame dfs endAddr c a :=
+ ⟨fun _ _ => rfl, fun _ _ => rfl, rfl⟩
+ simp only [scan, hj, hr]
+ exact ⟨d, done, rd, ((guard.trans frame).trans advance).trans fd, sd, pre.trans run⟩
+
+/-- The linked map loop preserves every remaining tape bit. A rejected occurrence
+rules out returning from the original guard even when previous maps succeeded. -/
+theorem maps_realizes (link : P.Linked M) (stable : ∀ node, P.Stable (inv node))
+ (apart : ∀ i : Fin 9, i = 3 ∨ i = 5 ∨ i = 6 ∨ i = 7 → dfs i ≠ P.cursor)
+ (js : List (Action w endAddr)) (src : ℕ) (items : Items P M m dfs inv src js)
+ (fit : src + js.length < 2 ^ w) :
+ Realizes (mapReader js) M m dfs (Entry P inv src js.length)
+ (fun _ node d => d.pc = P.done ∧ inv node d) := by
+ constructor
+ · intro node c bs out rest hc got
+ obtain ⟨⟨es, updated⟩, result, eqn⟩ := Option.map_eq_some_iff.mp got
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj eqn
+ have h := native P link stable apart js src items fit node c hc
+ rw [result] at h
+ obtain ⟨d, pc, ready, frame, mem, path⟩ := h
+ have quiet := scan_bits js node _ items.quiet result
+ exact ⟨by simp [quiet], d, ⟨pc, ready⟩, frame, mem, quiet ▸ path⟩
+ · intro node c bs hc bad
+ have result := Option.map_eq_none_iff.mp bad
+ have h := native P link stable apart js src items fit node c hc
+ rw [result] at h
+ exact h bs
+
+end PairSimulation.ResidentMapLoop.Exact
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationReverseSlices.lean b/lean/OAI/Computability/VPVNP/PairSimulationReverseSlices.lean
new file mode 100644
index 0000000000..3bb8acf298
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationReverseSlices.lean
@@ -0,0 +1,305 @@
+import OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+/-!
+# Reading a subdivision slice from the new supply field
+
+The frame stores the old-field offset first and the new-field offset second.
+Recovering an old argument from a surviving supply field copies in the
+opposite direction. The header reads the same three addresses in the same
+order, then enters the ordinary private copy loop with the new field as source.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ReverseSlices
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords.SliceSchedule
+open PrivateSlices (copyRegs headerEvents frameEvents frame_work)
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.read ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r k : ℕ}
+
+/-- Exchange the two offset-add instructions. Register 0 is still the
+private source cursor and register 2 the private destination cursor. -/
+def instruction (pc : Fin 11 → Fin p) (reg : Fin 6 ↪ Fin r) (copy done : Fin p)
+ (i : Fin 11) : Instr w p r k :=
+ if i = 6 then .binary .add (reg 2) (reg 2) (reg 4) (pc 7)
+ else if i = 9 then .binary .add (reg 0) (reg 0) (reg 4) (pc 10)
+ else PrivateSlices.instruction pc reg copy done i
+
+theorem resize_instruction (pc : Fin 11 → Fin p) (reg : Fin 6 ↪ Fin r) (copy done : Fin p)
+ (i : Fin 11) :
+ (instruction (w := 1) (k := k) pc reg copy done i).resize w =
+ instruction pc reg copy done i := by
+ fin_cases i <;> rfl
+
+/-- The eleven assigned instructions implement reverse frame setup, adding the new offset to
+the source and the old offset to the destination before copying a nonempty slice. -/
+def Linked (M : Machine w p r k) (pc : Fin 11 → Fin p) (reg : Fin 6 ↪ Fin r)
+ (copy done : Fin p) : Prop := ∀ i, M.code (pc i) = instruction pc reg copy done i
+
+variable {M : Machine w p r k} {pc : Fin 11 → Fin p} {reg : Fin 6 ↪ Fin r} {copy done : Fin p}
+
+private theorem step_at (hl : Linked M pc reg copy done) (i : Fin 11) (c : Config w p r)
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg copy done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+private structure Prepared (reg : Fin 6 ↪ Fin r) (copy done : Fin p)
+ (c d : Config w p r) (f srcOff dstOff : Word w) (m : Memory w) : Prop where
+ pc : d.pc = if m (f + 1 + 1).val = 0 then done else copy
+ args : m (f + 1 + 1).val ≠ 0 →
+ d.reg (reg 0) = c.reg (reg 0) + srcOff ∧
+ d.reg (reg 2) = c.reg (reg 2) + dstOff ∧
+ d.reg (reg 1) = d.reg (reg 2) + m (f + 1 + 1).val
+ regs : ∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 2 → j ≠ reg 4 → d.reg j = c.reg j
+ memory : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+private theorem header (hl : Linked M pc reg copy done) (c : Config w p r) (hc : c.pc = pc 0)
+ (h1 : c.reg (reg 3) = 1) (m : Memory w) :
+ let f := c.reg (reg 5)
+ ∃ d, Prepared reg copy done c d f (m (f + 1).val) (m f.val) m ∧
+ ReadPrefix M m c (headerEvents m f) d := by
+ intro f
+ let len := m (f + 1 + 1).val
+ let u₁ := c.put (pc 1) (reg 4) (f + 1)
+ let u₂ := u₁.put (pc 2) (reg 4) (f + 1 + 1)
+ let u₃ := u₂.put (pc 3) (reg 1) len
+ let u₄ := u₃.put (pc 4) (reg 4) 0
+ let tested := {u₄ with pc := if len = 0 then done else pc 5}
+ let first : List (Event w) := [.tick, .tick, .read (f + 1 + 1) len, .tick, .tick]
+ have test {es : List (Event w)} {out : Config w p r} (tail : ReadPrefix M m tested es out) :
+ ReadPrefix M m c (first ++ es) out := by
+ refine ReadPrefix.tick (d := u₁) ?_ (ReadPrefix.tick (d := u₂) ?_
+ (ReadPrefix.read (g := fun v ↦ u₂.put (pc 3) (reg 1) v) _ ?_
+ (ReadPrefix.tick (d := u₄) ?_ (ReadPrefix.tick ?_ tail))))
+ · rw [step_at hl 0 c hc]
+ change CallAction.localStep (c.put _ _ (f + c.reg (reg 3))) = _
+ rw [h1]
+ · rw [step_at hl 1 u₁ rfl]
+ change CallAction.localStep (u₁.put _ _ (u₁.reg (reg 4) + u₁.reg (reg 3))) = _
+ simp [u₂, u₁, Config.put, h1]
+ · rw [step_at hl 2 u₂ rfl]
+ change CallAction.read (u₂.reg (reg 4)) (fun v ↦ u₂.put (pc 3) (reg 1) v) = _
+ rw [Config.put_same]
+ · exact step_at hl 3 u₃ rfl
+ · rw [step_at hl 4 u₄ rfl]
+ change CallAction.localStep {u₄ with
+ pc := if u₄.reg (reg 1) = u₄.reg (reg 4) then done else pc 5} = _
+ simp [tested, u₄, u₃, Config.put]
+ by_cases hz : len = 0
+ · refine ⟨tested, ⟨?_, fun h ↦ (h hz).elim, ?_, rfl, rfl⟩, ?_⟩
+ · change (if len = 0 then done else pc 5) = if len = 0 then done else copy
+ simp [hz]
+ · intro j _ hj₁ _ hj₄
+ simp [tested, u₄, u₃, u₂, u₁, Config.put,
+ Function.update_of_ne hj₄, Function.update_of_ne hj₁]
+ · simpa [headerEvents, first, len, show m (f + 1 + 1).val = 0 from hz] using
+ test (ReadPrefix.nil tested)
+ · let u₆ := tested.put (pc 6) (reg 4) (m f.val)
+ let dst := c.reg (reg 2) + m f.val
+ let u₇ := u₆.put (pc 7) (reg 2) dst
+ let u₈ := u₇.put (pc 8) (reg 4) (f + 1)
+ let u₉ := u₈.put (pc 9) (reg 4) (m (f + 1).val)
+ let u₁₀ := u₉.put (pc 10) (reg 0) (c.reg (reg 0) + m (f + 1).val)
+ let out := u₁₀.put copy (reg 1) (dst + len)
+ let last : List (Event w) :=
+ [.read f (m f.val), .tick, .tick, .read (f + 1) (m (f + 1).val), .tick, .tick]
+ have tail : ReadPrefix M m tested last out := by
+ refine ReadPrefix.read (g := fun v ↦ tested.put (pc 6) (reg 4) v) _ ?_
+ (ReadPrefix.tick (d := u₇) ?_ (ReadPrefix.tick (d := u₈) ?_
+ (ReadPrefix.read (g := fun v ↦ u₈.put (pc 9) (reg 4) v) _ ?_
+ (ReadPrefix.tick (d := u₁₀) ?_ (ReadPrefix.tick ?_ (ReadPrefix.nil out))))))
+ · rw [step_at hl 5 tested (by simp [tested, hz])]
+ change CallAction.read (tested.reg (reg 5)) (fun v ↦ tested.put (pc 6) (reg 4) v) = _
+ simp [tested, u₄, u₃, u₂, u₁, Config.put, f]
+ · rw [step_at hl 6 u₆ rfl]
+ change CallAction.localStep (u₆.put _ _ (u₆.reg (reg 2) + u₆.reg (reg 4))) = _
+ simp [u₇, u₆, dst, tested, u₄, u₃, u₂, u₁, Config.put]
+ · rw [step_at hl 7 u₇ rfl]
+ change CallAction.localStep (u₇.put _ _ (u₇.reg (reg 5) + u₇.reg (reg 3))) = _
+ simp [u₈, u₇, u₆, tested, u₄, u₃, u₂, u₁, Config.put, h1, f]
+ · rw [step_at hl 8 u₈ rfl]
+ change CallAction.read (u₈.reg (reg 4)) (fun v ↦ u₈.put (pc 9) (reg 4) v) = _
+ rw [Config.put_same]
+ · rw [step_at hl 9 u₉ rfl]
+ change CallAction.localStep (u₉.put _ _ (u₉.reg (reg 0) + u₉.reg (reg 4))) = _
+ simp [u₁₀, u₉, u₈, u₇, u₆, tested, u₄, u₃, u₂, u₁, Config.put]
+ · rw [step_at hl 10 u₁₀ rfl]
+ change CallAction.localStep (u₁₀.put _ _ (u₁₀.reg (reg 2) + u₁₀.reg (reg 1))) = _
+ simp [out, u₁₀, u₉, u₈, u₇, u₆, tested, u₄, u₃, Config.put]
+ refine ⟨out, ⟨?_, ?_, ?_, rfl, rfl⟩, ?_⟩
+ · change copy = if len = 0 then done else copy
+ simp [hz]
+ · intro _
+ simp [out, u₁₀, u₉, u₈, u₇, dst, len, Config.put]
+ · intro j h₀ h₁ h₂ h₄
+ simp [out, u₁₀, u₉, u₈, u₇, u₆, tested, u₄, u₃, u₂, u₁, Config.put,
+ Function.update_of_ne h₀, Function.update_of_ne h₁, Function.update_of_ne h₂,
+ Function.update_of_ne h₄]
+ · simpa [headerEvents, first, last, len, show m (f + 1 + 1).val ≠ 0 from hz] using test tail
+
+private theorem oriented_header (reverse : Bool)
+ (hl : if reverse then Linked M pc reg copy done else PrivateSlices.Linked M pc reg copy done)
+ (c : Config w p r) (hc : c.pc = pc 0) (h1 : c.reg (reg 3) = 1) (m : Memory w) :
+ let f := c.reg (reg 5)
+ ∃ d, Prepared reg copy done c d f
+ (if reverse then m (f + 1).val else m f.val) (if reverse then m f.val else m (f + 1).val) m ∧
+ ∀ fuel more, execute M.program (fuel + (headerEvents m f).length) c m more =
+ (execute M.program fuel d m more).map
+ (fun rep ↦ ⟨headerEvents m f ++ rep.events, rep.result⟩) := by
+ cases reverse with
+ | false =>
+ obtain ⟨d, h, run⟩ := PrivateSlices.execute_header hl c hc h1 m
+ exact ⟨d, ⟨h.pc, h.args, h.frameRegs, h.memory, h.persistent⟩, run⟩
+ | true =>
+ obtain ⟨d, h, pre⟩ := header hl c hc h1 m
+ exact ⟨d, h, ReadPrefix.execute pre⟩
+
+/-- The exact continuation of a slice copy in either direction. -/
+abbrev FrameResult (M : Machine w p r k) (reg : Fin 6 ↪ Fin r) (done : Fin p)
+ (c : Config w p r) (m : Memory w) (f : Word w) (dst : ℕ) (bs : List Bool) : Prop :=
+ ∃ out, out.pc = done ∧ out.persistent = c.persistent ∧
+ out.privateMem = PrivateFields.storeBits dst bs c.privateMem ∧
+ (∀ j, j ≠ reg 0 → j ≠ reg 1 → j ≠ reg 2 → j ≠ reg 4 → out.reg j = c.reg j) ∧
+ (∀ fuel more, execute M.program (fuel + (frameEvents m f bs).length) c m more =
+ (execute M.program fuel out m more).map
+ (fun rep ↦ ⟨frameEvents m f bs ++ rep.events, rep.result⟩)) ∧
+ (frameEvents m f bs).length = (if bs.isEmpty then 5 else 5 * bs.length + 12) ∧
+ countProbes (frameEvents m f bs) = (if bs.isEmpty then 1 else 3)
+
+private theorem word_of_val {u : Word w} {n : ℕ} (h : u.val = n) : u = (n : Word w) := by
+ apply Fin.ext
+ exact h.trans (Nat.mod_eq_of_lt (h ▸ u.isLt)).symm
+
+variable {arcPC : Fin 7 → Fin p}
+
+/-- Use only the three words of the resident frame. The first offset belongs
+to the old field and the second to the new one. The selected direction determines
+which is used as the private source offset. Empty frames need only their length. -/
+theorem execute_stored_frame (reverse : Bool)
+ (hl : if reverse then Linked M pc reg (arcPC 0) done
+ else PrivateSlices.Linked M pc reg (arcPC 0) done)
+ (hcopy : PrivateFields.Linked M .copy arcPC (copyRegs reg) done)
+ (c : Config w p r) (hc : c.pc = pc 0) (h1 : c.reg (reg 3) = 1)
+ (m : Memory w) (f : Word w) (hf : c.reg (reg 5) = f)
+ (src dst srcOff dstOff : ℕ)
+ (hs : c.reg (reg 0) = (src : Word w)) (hd : c.reg (reg 2) = (dst : Word w))
+ (bs : List Bool) (hlen : (m (f + 1 + 1).val).val = bs.length)
+ (offsets : 0 < bs.length →
+ (if reverse then m (f + 1).val else m f.val).val = srcOff ∧
+ (if reverse then m f.val else m (f + 1).val).val = dstOff)
+ (fit : 0 < bs.length → src + srcOff + bs.length ≤ 2 ^ w ∧ dst + dstOff + bs.length < 2 ^ w)
+ (safe : 0 < bs.length → dst + dstOff ≤ src + srcOff ∨ src + srcOff + bs.length ≤ dst + dstOff)
+ (data : ∀ i : Fin bs.length, c.privateMem ((src + srcOff + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w bs[i.val]) :
+ FrameResult M reg done c m f (dst + dstOff) bs := by
+ obtain ⟨d, h, head⟩ := oriented_header reverse hl c hc h1 m
+ rw [hf] at h head
+ obtain ⟨work, probes⟩ := frame_work m f bs hlen
+ cases bs with
+ | nil =>
+ have hz : m (f + 1 + 1).val = 0 := Fin.ext hlen
+ refine ⟨d, h.pc.trans (ite_eq_left hz), h.persistent, h.memory, h.regs, ?_, work, probes⟩
+ simpa [frameEvents] using head
+ | cons b bs =>
+ let bits := b :: bs
+ have hp : 0 < bits.length := Nat.succ_pos _
+ have hz : m (f + 1 + 1).val ≠ 0 := by intro eq; rw [eq] at hlen; simp at hlen
+ obtain ⟨hsrc, hdst, hend⟩ := h.args hz
+ obtain ⟨sOff, dOff⟩ := offsets hp
+ have source : d.reg ((copyRegs reg) 0) = ((src + srcOff : ℕ) : Word w) := by
+ change d.reg (reg 0) = _
+ rw [hsrc, hs, word_of_val sOff, Nat.cast_add]
+ have dest : d.reg ((copyRegs reg) 2) = ((dst + dstOff : ℕ) : Word w) := by
+ change d.reg (reg 2) = _
+ rw [hdst, hd, word_of_val dOff, Nat.cast_add]
+ have limit : d.reg ((copyRegs reg) 1) = ((dst + dstOff + bits.length : ℕ) : Word w) := by
+ change d.reg (reg 1) = _
+ rw [hend, show d.reg (reg 2) = _ from dest, word_of_val hlen]
+ simp [bits]
+ have one : d.reg ((copyRegs reg) 3) = 1 :=
+ (h.regs _ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))
+ (reg.injective.ne (by decide)) (reg.injective.ne (by decide))).trans h1
+ obtain ⟨out, pref, res⟩ := PrivateFields.copy_prefix hcopy d (h.pc.trans (ite_eq_right hz))
+ (src + srcOff) (dst + dstOff) bits source dest limit one (fit hp).2 (fit hp).1 (safe hp)
+ (by rw [h.memory]; exact data)
+ refine ⟨out, res.pc, res.persistent.trans h.persistent, ?_, ?_, ?_, work, probes⟩
+ · rw [res.privateMem, h.memory]
+ · intro j h₀ h₁ h₂ h₄
+ exact (res.frame j h₀ h₂ h₄).trans (h.regs j h₀ h₁ h₂ h₄)
+ · intro fuel more
+ let es := PrivateFields.events (w := w) .copy bits
+ have crun := pref.execute fuel m more
+ simp only [PrivateFields.events_bits, reduceCtorEq, ite_false, List.nil_append] at crun
+ change execute M.program (fuel + (headerEvents m f ++ es).length) c m more = _
+ rw [List.length_append,
+ show fuel + (_ + es.length) = (fuel + es.length) + (headerEvents m f).length by omega,
+ head, show execute M.program (fuel + es.length) d m more = _ from crun]
+ simp [frameEvents, bits, Option.map_map, Function.comp_def, List.append_assoc]
+
+/-- Convert the three consecutive natural addresses of a fitted frame to native word
+addresses. Empty records need no offset equalities. -/
+theorem oriented_frame_words (reverse : Bool) (m : Memory w) (f : Word w)
+ (n oldOffset newOffset len : ℕ) (hf : f = (n : Word w)) (fit : n + 2 < 2 ^ w)
+ (hlen : (m (n + 2)).val = len)
+ (offsets : 0 < len → (m n).val = oldOffset ∧ (m (n + 1)).val = newOffset) :
+ (m (f + 1 + 1).val).val = len ∧
+ (0 < len →
+ (if reverse then m (f + 1).val else m f.val).val =
+ (if reverse then newOffset else oldOffset) ∧
+ (if reverse then m f.val else m (f + 1).val).val =
+ (if reverse then oldOffset else newOffset)) := by
+ subst f
+ have h₀ : (n : Word w).val = n := Nat.mod_eq_of_lt (by omega)
+ have h₁ : ((n : Word w) + 1).val = n + 1 := by
+ rw [← Nat.cast_add_one]
+ exact Nat.mod_eq_of_lt (by omega)
+ have h₂ : ((n : Word w) + 1 + 1).val = n + 2 := by
+ rw [← Nat.cast_add_one, ← Nat.cast_add_one]
+ exact Nat.mod_eq_of_lt fit
+ rw [h₀, h₁, h₂]
+ refine ⟨hlen, fun positive ↦ ?_⟩
+ cases reverse
+ · exact offsets positive
+ · exact (offsets positive).symm
+
+/-- Reverse a completed source-major frame, copying from its new private field
+back into its old private field at the recorded offset. -/
+theorem execute_frame (hl : Linked M pc reg (arcPC 0) done)
+ (hcopy : PrivateFields.Linked M .copy arcPC (copyRegs reg) done)
+ (c : Config w p r) (hc : c.pc = pc 0) (h1 : c.reg (reg 3) = 1)
+ {pub : Fin 6 → Word w} {old new : List ℕ} {initial m : Memory w} {completed : ℕ}
+ (frames : FramesAt pub old new initial m completed) (a : Fin completed)
+ (frameFit : (pub 5).val + 3 * a.val + 2 < 2 ^ w) (src dst : ℕ)
+ (hf : c.reg (reg 5) = (((pub 5).val + 3 * a.val : ℕ) : Word w))
+ (hs : c.reg (reg 0) = (src : Word w)) (hd : c.reg (reg 2) = (dst : Word w))
+ (bs : List Bool) (hlen : bs.length = (sliceAt old new a.val).length)
+ (fit : 0 < bs.length → src + (sliceAt old new a.val).targetOffset + bs.length ≤ 2 ^ w ∧
+ dst + (sliceAt old new a.val).sourceOffset + bs.length < 2 ^ w)
+ (safe : 0 < bs.length →
+ dst + (sliceAt old new a.val).sourceOffset ≤ src + (sliceAt old new a.val).targetOffset ∨
+ src + (sliceAt old new a.val).targetOffset + bs.length ≤
+ dst + (sliceAt old new a.val).sourceOffset)
+ (data : ∀ i : Fin bs.length,
+ c.privateMem ((src + (sliceAt old new a.val).targetOffset + i.val : ℕ) : Word w) =
+ PrivateFields.bitValue w bs[i.val]) :
+ FrameResult M reg done c m (c.reg (reg 5)) (dst + (sliceAt old new a.val).sourceOffset) bs := by
+ let s := sliceAt old new a.val
+ obtain ⟨len, off⟩ := oriented_frame_words true m (c.reg (reg 5))
+ ((pub 5).val + 3 * a.val) s.sourceOffset s.targetOffset bs.length hf frameFit
+ ((frames.lengths a.val a.isLt).trans hlen.symm)
+ (fun hp ↦ frames.offsets a.val a.isLt (hlen ▸ hp))
+ exact execute_stored_frame true hl hcopy c hc h1 m (c.reg (reg 5)) rfl src dst
+ s.targetOffset s.sourceOffset hs hd bs len off fit safe data
+
+end PairSimulation.ReverseSlices
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteAddresses.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteAddresses.lean
new file mode 100644
index 0000000000..ea85b56106
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteAddresses.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Selecting the three resident field addresses at a cursor vertex
+
+The two mask bits select the outgoing and incoming sides independently.
+The same running offset locates the system's field in all four local buffers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteAddresses
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Input flags, buffer bases and field offset, together with the three output addresses. -/
+inductive Reg where
+ | outFlag | inFlag | outBase (side : Bool) | inBase (side : Bool)
+ | offset | zero | unused | used | incoming
+ deriving DecidableEq, Fintype
+
+/-- Each outgoing branch adds the offset to both starts. The incoming
+branch adds it to the selected incoming start. -/
+def instruction (pc : Fin 8 → Fin p) (reg : Reg ↪ Fin r) (done : Fin p) :
+ Fin 8 → Instr w p r k :=
+ ![.jumpEq (reg .outFlag) (reg .zero) (pc 1) (pc 3),
+ .binary .add (reg .unused) (reg (.outBase true)) (reg .offset) (pc 2),
+ .binary .add (reg .used) (reg (.outBase false)) (reg .offset) (pc 5),
+ .binary .add (reg .unused) (reg (.outBase false)) (reg .offset) (pc 4),
+ .binary .add (reg .used) (reg (.outBase true)) (reg .offset) (pc 5),
+ .jumpEq (reg .inFlag) (reg .zero) (pc 6) (pc 7),
+ .binary .add (reg .incoming) (reg (.inBase false)) (reg .offset) done,
+ .binary .add (reg .incoming) (reg (.inBase true)) (reg .offset) done]
+
+theorem resize_instruction (pc : Fin 8 → Fin p) (reg : Reg ↪ Fin r) (done : Fin p)
+ (i : Fin 8) : (instruction (w := 1) (k := k) pc reg done i).resize w =
+ instruction pc reg done i := by fin_cases i <;> rfl
+
+/-- The machine contains the eight address-selection rows at their assigned labels. -/
+def Linked (M : Machine w p r k) (pc : Fin 8 → Fin p) (reg : Reg ↪ Fin r) (done : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+/-- The outgoing and incoming side bits and the four local buffer bases at entry. -/
+structure Ready (reg : Reg ↪ Fin r) (c : Config w p r) (outFlag inFlag : Bool)
+ (outBase inBase : Bool → Word w) (offset : Word w) : Prop where
+ outgoing : c.reg (reg .outFlag) = (outFlag.toNat : Word w)
+ incoming : c.reg (reg .inFlag) = (inFlag.toNat : Word w)
+ outBase : ∀ b, c.reg (reg (.outBase b)) = outBase b
+ inBase : ∀ b, c.reg (reg (.inBase b)) = inBase b
+ offset : c.reg (reg .offset) = offset
+ zero : c.reg (reg .zero) = 0
+
+/-- The selected field starts, return label and state preserved for the field scan. -/
+structure Result (reg : Reg ↪ Fin r) (done : Fin p) (c d : Config w p r) (outFlag inFlag : Bool)
+ (outBase inBase : Bool → Word w) (offset : Word w) : Prop where
+ pc : d.pc = done
+ unused : d.reg (reg .unused) = outBase (!outFlag) + offset
+ used : d.reg (reg .used) = outBase outFlag + offset
+ incoming : d.reg (reg .incoming) = inBase inFlag + offset
+ frame : ∀ q, q ≠ reg .unused → q ≠ reg .used → q ≠ reg .incoming → d.reg q = c.reg q
+ memory : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+/-- Exactly five native local steps select the three absolute addresses. -/
+theorem native {M : Machine w p r k} {pc : Fin 8 → Fin p} {reg : Reg ↪ Fin r} {done : Fin p}
+ (hl : Linked M pc reg done) (hw : 0 < w) (c : Config w p r) (hc : c.pc = pc 0)
+ {outFlag inFlag : Bool} {outBase inBase : Bool → Word w} {offset : Word w}
+ (h : Ready reg c outFlag inFlag outBase inBase offset) :
+ ∃ d, Prefix M c (List.replicate 5 .tick) d ∧ Result reg done c d outFlag inFlag outBase inBase offset := by
+ let unusedPC : Fin 8 := if outFlag then 3 else 1
+ let usedPC : Fin 8 := if outFlag then 4 else 2
+ let incomingPC : Fin 8 := if inFlag then 7 else 6
+ let c₁ := {c with pc := pc unusedPC}
+ let c₂ := c₁.put (pc usedPC) (reg .unused) (outBase (!outFlag) + offset)
+ let c₃ := c₂.put (pc 5) (reg .used) (outBase outFlag + offset)
+ let c₄ := {c₃ with pc := pc incomingPC}
+ let d := c₄.put done (reg .incoming) (inBase inFlag + offset)
+ have step (i : Fin 8) (a : Config w p r) (ha : a.pc = pc i) :
+ M.program.step a = (instruction pc reg done i).run M.publicData a := by
+ change (M.code a.pc).run _ _ = _
+ rw [ha, hl i]
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step 0 c hc]
+ change CallAction.localStep {c with pc := if c.reg (reg .outFlag) = c.reg (reg .zero) then pc 1 else pc 3} = _
+ rw [h.outgoing, h.zero]
+ cases outFlag <;> simp [c₁, unusedPC, Nat.ne_of_gt hw]
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step unusedPC c₁ rfl]
+ cases outFlag <;> simp [unusedPC, usedPC, instruction, Instr.run, BinaryOp.eval, c₂, c₁, h.outBase, h.offset]
+ have s₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step usedPC c₂ rfl]
+ cases outFlag <;> simp [usedPC, instruction, Instr.run, BinaryOp.eval, c₃, c₂, c₁, Config.put,
+ h.outBase, h.offset]
+ have s₃ : M.program.step c₃ = .localStep c₄ := by
+ rw [step 5 c₃ rfl]
+ change CallAction.localStep {c₃ with pc := if c₃.reg (reg .inFlag) = c₃.reg (reg .zero) then pc 6 else pc 7} = _
+ cases inFlag <;> simp [c₄, incomingPC, c₃, c₂, c₁, Config.put, h.incoming, h.zero, Nat.ne_of_gt hw]
+ have s₄ : M.program.step c₄ = .localStep d := by
+ rw [step incomingPC c₄ rfl]
+ cases inFlag <;> simp [incomingPC, instruction, Instr.run, BinaryOp.eval, d, c₄, c₃, c₂, c₁, Config.put,
+ h.inBase, h.offset]
+ refine ⟨d, .tick s₀ (.tick s₁ (.tick s₂ (.tick s₃ (.tick s₄ (.nil _))))), rfl, ?_, ?_, ?_, ?_, rfl, rfl⟩
+ · simp [d, c₄, c₃, c₂, Config.put]
+ · simp [d, c₄, c₃, Config.put]
+ · simp [d]
+ · intro q hn hu hi
+ simp [d, c₄, c₃, c₂, c₁, Config.put, Function.update_of_ne hn, Function.update_of_ne hu,
+ Function.update_of_ne hi]
+
+end PairSimulation.RouteAddresses
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteBank.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteBank.lean
new file mode 100644
index 0000000000..79d057ca49
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteBank.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.PairSimulationRouteSchedule
+
+/-!
+# Fixed instruction bank for the complete cursor routing scan
+
+Seven scheduler instructions, three three-instruction loops, and two
+53-instruction field calls run the entire scan. The two exit labels may
+be connected to the surrounding leaf program. The standalone table puts
+accept and reject at these exits and requires no public data.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteBank
+
+open BurstRAM BurstRAM.PrivateRAM RouteSchedule
+
+variable {W p r k : ℕ}
+
+/-- Control labels in scheduler, successor, sorting-phase and sorting-step order. -/
+abbrev Control := Fin 7 ⊕ Fin 3 ⊕ Fin 3 ⊕ Fin 3
+
+/-- Geometry, address selection, and the field-bit scan of one invocation. -/
+abbrev Call := Fin 30 ⊕ Fin 8 ⊕ Fin 15
+
+/-- The two field calls have separate return labels in the surrounding loops. -/
+abbrev Body := Control ⊕ Call ⊕ Call
+
+/-- All instruction addresses, followed by the success and failure exits. -/
+abbrev Address := Body ⊕ Fin 2
+
+private def callLabels (place : Call → Fin p) : CallLabels p where
+ geom i := place (.inl i)
+ addr i := place (.inr (.inl i))
+ field i := place (.inr (.inr i))
+
+/-- Relocate all internal labels, both exits, and the register bank. -/
+def program (loc : Address → Fin p) (reg : Fin 32 ↪ Fin r) : Program p r where
+ reg := reg
+ pc i := loc (.inl (.inl (.inl i)))
+ succ i := loc (.inl (.inl (.inr (.inl i))))
+ phase i := loc (.inl (.inl (.inr (.inr (.inl i)))))
+ step i := loc (.inl (.inl (.inr (.inr (.inr i)))))
+ sCall := callLabels (fun a => loc (.inl (.inr (.inl a))))
+ lCall := callLabels (fun a => loc (.inl (.inr (.inr a))))
+ yes := loc (.inr 0)
+ no := loc (.inr 1)
+
+private def callText (labels : CallLabels p) (reg : Fin 32 ↪ Fin r)
+ (done : Fin p) : Call → Instr 1 p r k
+ | .inl i => RouteGeometry.instruction labels.geom (RouteCall.geometryRegs reg) (labels.addr 0) i
+ | .inr (.inl i) =>
+ RouteAddresses.instruction labels.addr (RouteCall.addressRegs reg) (labels.field 0) i
+ | .inr (.inr i) => RouteField.instruction labels.field (RouteCall.fieldRegs reg) done i
+
+/-- Literal, word-width-independent instructions with the requested addresses. -/
+def text (loc : Address → Fin p) (reg : Fin 32 ↪ Fin r) (a : Address) : Instr 1 p r k :=
+ let P := program loc reg
+ match a with
+ | .inl (.inl (.inl i)) => P.instruction i
+ | .inl (.inl (.inr (.inl i))) =>
+ RouteLoop.instruction P.succ (reg 3) (reg 2) (reg 23) (P.sCall.geom 0) (P.pc 3) i
+ | .inl (.inl (.inr (.inr (.inl i)))) =>
+ RouteLoop.instruction P.phase (reg 3) (reg 2) (reg 23) (P.pc 4) (P.pc 6) i
+ | .inl (.inl (.inr (.inr (.inr i)))) =>
+ RouteLoop.instruction P.step (reg 4) (reg 28) (reg 23) (P.lCall.geom 14) (P.phase 2) i
+ | .inl (.inr (.inl a)) => callText P.sCall reg (P.pc 2) a
+ | .inl (.inr (.inr a)) => callText P.lCall reg (P.pc 5) a
+ | .inr i => if i = 0 then .accept else .reject
+
+private theorem call_linked (M : Machine W p r k) (loc : Call → Fin p) (reg : Fin 32 ↪ Fin r)
+ (done : Fin p) (h : ∀ a, M.code (loc a) = (callText (callLabels loc) reg done a).resize W) :
+ let L := callLabels loc
+ RouteCall.Linked M L.geom L.addr L.field reg done := by
+ constructor
+ · intro i
+ exact (h (.inl i)).trans (RouteGeometry.resize_instruction ..)
+ · intro i
+ exact (h (.inr (.inl i))).trans (RouteAddresses.resize_instruction ..)
+ · intro i
+ exact (h (.inr (.inr i))).trans (RouteField.resize_instruction ..)
+
+/-- The relocated body supplies every scheduler and field-call link. The
+caller can install its own instructions at the two exit labels. -/
+theorem linked (M : Machine W p r k) (loc : Address → Fin p) (reg : Fin 32 ↪ Fin r)
+ (h : ∀ a : Body, M.code (loc (.inl a)) = (text loc reg (.inl a)).resize W) :
+ (program loc reg).Linked M := by
+ constructor
+ · intro i
+ exact (h (.inl (.inl i))).trans ((program loc reg).resize_instruction i)
+ · intro i
+ exact (h (.inl (.inr (.inl i)))).trans (RouteLoop.resize_instruction ..)
+ · intro i
+ exact (h (.inl (.inr (.inr (.inl i))))).trans (RouteLoop.resize_instruction ..)
+ · intro i
+ exact (h (.inl (.inr (.inr (.inr i))))).trans (RouteLoop.resize_instruction ..)
+ · exact call_linked M _ reg _ (fun a => h (.inr (.inl a)))
+ · exact call_linked M _ reg _ (fun a => h (.inr (.inr a)))
+
+private def controlLocations : Control ≃ Fin 16 :=
+ ((Equiv.refl _).sumCongr (((Equiv.refl _).sumCongr finSumFinEquiv).trans finSumFinEquiv)).trans
+ finSumFinEquiv
+
+private def callLocations : Call ≃ Fin 53 :=
+ ((Equiv.refl _).sumCongr finSumFinEquiv).trans finSumFinEquiv
+
+/-- Numeric program counters 0–121 contain the body. Counters 122 and
+123 are the successful and failed exits. -/
+def locations : Address ≃ Fin 124 :=
+ (((controlLocations.sumCongr ((callLocations.sumCongr callLocations).trans finSumFinEquiv)).trans
+ finSumFinEquiv).sumCongr (Equiv.refl _)).trans finSumFinEquiv
+
+/-- Canonical allocation of the scan's 32 register slots and 124 labels. -/
+def canonical : Program 124 32 := program locations (Function.Embedding.refl _)
+
+/-- Complete finite program text, with terminal instructions at its exits. -/
+def template : Template 124 32 0 :=
+ ⟨1, canonical.pc 0, fun i => text locations (Function.Embedding.refl _) (locations.symm i)⟩
+
+/-- Instantiate the same table at any host word width. -/
+def machine (W : ℕ) : Machine W 124 32 0 := template.instantiate W Fin.elim0
+
+theorem machine_linked (W : ℕ) : canonical.Linked (machine W) := by
+ apply linked
+ intro a
+ simp [machine, template, Template.instantiate]
+
+theorem machine_entry (W : ℕ) : (machine W).entry = canonical.pc 0 := rfl
+
+theorem machine_yes (W : ℕ) : (machine W).code canonical.yes = .accept := by
+ change (text (k := 0) locations (Function.Embedding.refl _) (locations.symm (locations (.inr 0)))).resize W = _
+ rw [locations.symm_apply_apply]
+ rfl
+
+theorem machine_no (W : ℕ) : (machine W).code canonical.no = .reject := by
+ change (text (k := 0) locations (Function.Embedding.refl _) (locations.symm (locations (.inr 1)))).resize W = _
+ rw [locations.symm_apply_apply]
+ rfl
+
+end PairSimulation.RouteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteBankWrites.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteBankWrites.lean
new file mode 100644
index 0000000000..98b0ee278a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteBankWrites.lean
@@ -0,0 +1,42 @@
+import OAI.Computability.VPVNP.PairSimulationRouteBank
+import OAI.Computability.VPVNP.PrivateRAMRegisterOperands
+
+/-! # Register destinations in the complete cursor routing scan -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteBank
+
+open BurstRAM PrivateRAM RouteSchedule RegisterOperands
+open private callText from OAI.Computability.VPVNP.PairSimulationRouteBank
+open private RouteGeometry.row from OAI.Computability.VPVNP.PairSimulationRouteGeometry
+
+variable {p r k : ℕ}
+
+private theorem call_destination_mem (labels : CallLabels p) (reg : Fin 32 ↪ Fin r)
+ (done : Fin p) (j : Call) (a : Fin r)
+ (h : destination (callText (k := k) labels reg done j) = some a) : a ∈ Set.range reg := by
+ rcases j with i | i | i
+ · simp only [callText, RouteGeometry.instruction] at h
+ cases eqn : (RouteGeometry.row i).2 <;> rw [eqn] at h <;> exact ⟨_, Option.some.inj h⟩
+ · fin_cases i <;> first | exact ⟨_, Option.some.inj h⟩ | contradiction
+ · fin_cases i <;> first | exact ⟨_, Option.some.inj h⟩ | contradiction
+
+/-- Each write in the scheduler, its loops, or either field call targets one
+of the 32 registers in the relocated routing bank. -/
+theorem destination_mem (loc : Address → Fin p) (reg : Fin 32 ↪ Fin r) (j : Address) (a : Fin r)
+ (h : destination (text (k := k) loc reg j) = some a) : a ∈ Set.range reg := by
+ rcases j with (control | sCall | lCall) | exit
+ · rcases control with i | i | i | i <;> fin_cases i <;>
+ first | exact ⟨_, Option.some.inj h⟩ | contradiction
+ · exact call_destination_mem _ reg _ sCall a h
+ · exact call_destination_mem _ reg _ lCall a h
+ · fin_cases exit <;> contradiction
+
+end PairSimulation.RouteBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteCall.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteCall.lean
new file mode 100644
index 0000000000..e9d8474df6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteCall.lean
@@ -0,0 +1,270 @@
+import OAI.Computability.VPVNP.CursorInitialCheck
+import OAI.Computability.VPVNP.PairSimulationRouteAddresses
+import OAI.Computability.VPVNP.PairSimulationRouteField
+import OAI.Computability.VPVNP.PairSimulationRouteGeometry
+
+/-!
+# One native call checking a cursor routing field
+
+The geometry block selects the two side bits and the payload test. A second
+block adds the field offset to the corresponding resident buffer bases. The
+field loop checks the unused outgoing bit and the selected payload test at
+each bit position, accumulating any mismatch into the caller's mask.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteCall
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open CursorRouting CursorNetwork RAMLayout
+open scoped Fin.CommRing
+
+variable {D H w W p r k : ℕ}
+
+/-- The bit tests belonging to one successor or sorting field. -/
+def Good [NeZero D] (v : Position D) (buf : Buffers D H w) (s : RAMSystem D) : Prop :=
+ ∀ j : Fin (ramFieldBits H w s),
+ readBuffer buf ⟨.outgoing (!(systemMask s).val.testBit v.1.val), s, j⟩ = false ∧
+ (payloadTest v s j).run (readBuffer buf) = true
+
+theorem good_iff_bitTests [NeZero D] (v : Position D) (buf : Buffers D H w) (s : RAMSystem D) :
+ Good v buf s ↔ ∀ j, (bitTests v s j).all (BitTest.run (readBuffer buf)) = true := by
+ simp [Good, bitTests, BitTest.run]
+
+open private routeAccept_iff from OAI.Computability.VPVNP.CursorRouteChecker
+
+theorem routeAccept_iff_good [NeZero D] (v : Position D) (buf : Buffers D H w) :
+ routeAccept H w v (readBuffer buf) = true ↔ ∀ s, Good v buf s :=
+ routeAccept_iff v (readBuffer buf)
+
+/-- The scheduler's running offset at entry to this field. -/
+def startOffset (D H w : ℕ) : RAMSystem D → ℕ
+ | .inl j => j.val * (8 * w)
+ | .inr l => D * (8 * w) + l.ordinal.val * blockBits H w
+
+theorem offset_bit (s : RAMSystem D) (j : Fin (ramFieldBits H w s)) :
+ (ramFieldOffset D H w ⟨s, j⟩).val = startOffset D H w s + j.val := by
+ cases s with
+ | inl k => exact ramFieldOffset_successor k j
+ | inr l => exact ramFieldOffset_sort l j
+
+/-- Each of the four local half-wire buffers resides at its own base.
+The bases and memory addresses are host words. -/
+def Resident (c : Config W p r) (base : LocalPort → Word W) (buf : Buffers D H w) : Prop :=
+ ∀ port j, c.privateMem (base port + (j.val : Word W)) = ((buf port j).toNat : Word W)
+
+private theorem agrees_iff_good [NeZero D] (v : Position D) (buf : Buffers D H w)
+ (s : RAMSystem D) (c : Config W p r) (base : LocalPort → Word W)
+ (hres : Resident c base buf) (hW : D < W) :
+ let out := (systemMask s).val.testBit v.1.val
+ let inc := (systemMask s).val.testBit ((finRotate D).symm v.1).val
+ let off : Word W := (startOffset D H w s : Word W)
+ RouteField.Agrees c.privateMem (RouteGeometry.mode v s : Word W)
+ (base (.outgoing (!out)) + off) (base (.outgoing out) + off)
+ (base (.incoming inc) + off) (ramFieldBits H w s) ↔ Good v buf s := by
+ have cell (port : LocalPort) (j : Fin (ramFieldBits H w s)) :
+ c.privateMem (base port + (startOffset D H w s : Word W) + (j.val : Word W)) =
+ ((readBuffer buf ⟨port, s, j⟩).toNat : Word W) := by
+ simpa only [readBuffer, offset_bit, Nat.cast_add, add_assoc] using
+ hres port (ramFieldOffset D H w ⟨s, j⟩)
+ have h2 : 2 < 2 ^ W := calc
+ 2 < 2 ^ 2 := by decide
+ _ ≤ 2 ^ W := Nat.pow_le_pow_right (by decide) (by have := NeZero.pos D; omega)
+ have h10 : (1 : Word W) ≠ 0 := by
+ intro he
+ have hv := congrArg Fin.val he
+ change 1 % 2 ^ W = 0 at hv
+ rw [Nat.mod_eq_of_lt (by omega)] at hv
+ omega
+ have h20 : (2 : Word W) ≠ 0 := by
+ intro he
+ have hv := congrArg Fin.val he
+ change 2 % 2 ^ W = 0 at hv
+ rw [Nat.mod_eq_of_lt h2] at hv
+ omega
+ have h21 : (2 : Word W) ≠ 1 := by
+ intro he
+ have hv := congrArg Fin.val he
+ change 2 % 2 ^ W = 1 % 2 ^ W at hv
+ rw [Nat.mod_eq_of_lt h2, Nat.mod_eq_of_lt (by omega)] at hv
+ omega
+ have clear (b : Bool) : (b.toNat : Word W) = 0 ↔ b = false := by cases b <;> simp [h10]
+ have same (a b : Bool) : (a.toNat : Word W) = (b.toNat : Word W) ↔ a = b := by
+ cases a <;> cases b <;> simp [h10, Ne.symm h10]
+ dsimp only
+ unfold RouteField.Agrees Good
+ simp_rw [cell, clear]
+ apply forall_congr'
+ intro j
+ apply and_congr_right'
+ by_cases hz : v.1 = 0
+ · cases s with
+ | inl m =>
+ by_cases ha : v.2.val + 1 < 2 ^ D ∧ v.2.val ^^^ (v.2.val + 1) = (systemMask (.inl m)).val <;>
+ simp [RouteGeometry.mode, RouteField.PayloadOK, payloadTest, BitTest.run, hz, ha, h10, clear]
+ | inr l => simp [RouteGeometry.mode, RouteField.PayloadOK, payloadTest, BitTest.run, hz]
+ · simp [RouteGeometry.mode, RouteField.PayloadOK, payloadTest, BitTest.run, hz, h20, h21, same]
+
+/-- The first twelve slots carry the geometry inputs and outputs. -/
+def geometryRegs (reg : Fin 32 ↪ Fin r) : Fin 12 ↪ Fin r :=
+ (Fin.castLEEmb (by decide)).trans reg
+
+/-- Register holding the base of the indicated outgoing buffer. -/
+def outSlot : Bool → Fin 32
+ | false => 12
+ | true => 13
+
+/-- Register holding the base of the indicated incoming buffer. -/
+def inSlot : Bool → Fin 32
+ | false => 14
+ | true => 15
+
+private def addressSlot : RouteAddresses.Reg → Fin 32
+ | .outFlag => 5
+ | .inFlag => 6
+ | .outBase b => outSlot b
+ | .inBase b => inSlot b
+ | .offset => 16
+ | .zero => 17
+ | .unused => 18
+ | .used => 19
+ | .incoming => 20
+
+/-- Connect the side flags, buffer bases and selected cursors to the address block. -/
+def addressRegs (reg : Fin 32 ↪ Fin r) : RouteAddresses.Reg ↪ Fin r :=
+ (⟨addressSlot, by decide⟩ : RouteAddresses.Reg ↪ Fin 32).trans reg
+
+private def fieldSlot : Fin 11 → Fin 32 := ![18, 19, 20, 21, 7, 22, 23, 24, 25, 26, 27]
+
+/-- Connect the selected cursors, width, mode and sticky mask to the field scanner. -/
+def fieldRegs (reg : Fin 32 ↪ Fin r) : Fin 11 ↪ Fin r :=
+ (⟨fieldSlot, by decide⟩ : Fin 11 ↪ Fin 32).trans reg
+
+/-- All register slots written by at least one block of the call. -/
+def Scratch (i : Fin 32) : Prop :=
+ 5 ≤ i.val ∧ i.val ≤ 11 ∨ 18 ≤ i.val ∧ i.val ≤ 20 ∨ i.val = 22 ∨ 24 ≤ i.val ∧ i.val ≤ 27
+
+instance (i : Fin 32) : Decidable (Scratch i) := by unfold Scratch; infer_instance
+
+/-- The register is outside the scratch slots of the three blocks. -/
+def Preserved (reg : Fin 32 ↪ Fin r) (a : Fin r) : Prop :=
+ ∀ i : Fin 32, Scratch i → a ≠ reg i
+
+theorem preserved_reg (reg : Fin 32 ↪ Fin r) (i : Fin 32) (h : ¬ Scratch i) :
+ Preserved reg (reg i) := fun _ hs he ↦ h (reg.injective he ▸ hs)
+
+/-- The geometry exit enters the address block, whose exit enters the field scan. -/
+structure Linked (M : Machine W p r k) (gpc : Fin 30 → Fin p) (apc : Fin 8 → Fin p)
+ (fpc : Fin 15 → Fin p) (reg : Fin 32 ↪ Fin r) (done : Fin p) : Prop where
+ geometry : RouteGeometry.Linked M gpc (geometryRegs reg) (apc 0)
+ addresses : RouteAddresses.Linked M apc (addressRegs reg) (fpc 0)
+ field : RouteField.Linked M fpc (fieldRegs reg) done
+
+/-- Live cursor and scheduler inputs at the entry to a routing field. -/
+structure Ready (reg : Fin 32 ↪ Fin r) (v : Position D) (s : RAMSystem D)
+ (base : LocalPort → Word W) (c : Config W p r) : Prop where
+ geometry : RouteGeometry.Ready (geometryRegs reg) v s c
+ outBase : ∀ b, c.reg (reg (outSlot b)) = base (.outgoing b)
+ inBase : ∀ b, c.reg (reg (inSlot b)) = base (.incoming b)
+ offset : c.reg (reg 16) = (startOffset D H w s : Word W)
+ zero : c.reg (reg 17) = 0
+ width : c.reg (reg 21) = (ramFieldBits H w s : Word W)
+ one : c.reg (reg 23) = 1
+
+/-- Clock for geometry, the five address-selection instructions, and the scan. -/
+def ticks (W : ℕ) [NeZero D] (v : Position D) (s : RAMSystem D) (width : ℕ) : ℕ :=
+ RouteGeometry.ticks s + 5 + RouteField.steps (RouteGeometry.mode v s : Word W) width
+
+theorem ticks_le (W : ℕ) [NeZero D] (v : Position D) (s : RAMSystem D) (width : ℕ) :
+ ticks W v s width ≤ 13 * width + 34 := by
+ have ht : RouteGeometry.ticks s ≤ 26 := by cases s <;> simp [RouteGeometry.ticks]
+ have := RouteField.steps_le (RouteGeometry.mode v s : Word W) width
+ unfold ticks
+ omega
+
+/-- The final mask records the field tests and preserves earlier failures. -/
+structure Result [NeZero D] (reg : Fin 32 ↪ Fin r) (done : Fin p) (v : Position D)
+ (buf : Buffers D H w) (s : RAMSystem D) (c d : Config W p r) : Prop where
+ pc : d.pc = done
+ mask : d.reg (reg 22) = 0 ↔ c.reg (reg 22) = 0 ∧ Good v buf s
+ frame : ∀ a, Preserved reg a → d.reg a = c.reg a
+ memory : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+private theorem geometry_preserves (reg : Fin 32 ↪ Fin r) (i : Fin 32) (hi : 12 ≤ i.val) :
+ RouteGeometry.Preserved (geometryRegs reg) (reg i) := by
+ intro j _ he
+ have hv := congrArg Fin.val (reg.injective he)
+ change i.val = j.val at hv
+ have := j.isLt
+ omega
+
+private theorem field_preserves {reg : Fin 32 ↪ Fin r} {a : Fin r} (h : Preserved reg a) :
+ RouteField.Preserved (fieldRegs reg) a :=
+ ⟨h 18 (by decide), h 19 (by decide), h 20 (by decide), h 22 (by decide),
+ h 24 (by decide), h 25 (by decide), h 26 (by decide), h 27 (by decide)⟩
+
+/-- Run geometry and address selection, then check the entire resident field.
+The mask remains zero exactly when the initial mask was zero and every bit
+test at this system accepts. -/
+theorem run [NeZero D] {M : Machine W p r k} {gpc : Fin 30 → Fin p} {apc : Fin 8 → Fin p}
+ {fpc : Fin 15 → Fin p} {reg : Fin 32 ↪ Fin r} {done : Fin p}
+ (hl : Linked M gpc apc fpc reg done) (v : Position D) (s : RAMSystem D)
+ (hw : D < W) (hfit : ramFieldBits H w s < 2 ^ W) (c : Config W p r)
+ (hc : c.pc = gpc (RouteGeometry.entry s)) {base : LocalPort → Word W} {buf : Buffers D H w}
+ (h : Ready (H := H) (w := w) reg v s base c) (hres : Resident c base buf) :
+ ∃ d, Prefix M c (List.replicate (ticks W v s (ramFieldBits H w s)) .tick) d ∧
+ Result reg done v buf s c d := by
+ obtain ⟨g, pre, geo⟩ := RouteGeometry.native hl.geometry v s hw c hc h.geometry
+ have kept (i : Fin 32) (hi : 12 ≤ i.val) : g.reg (reg i) = c.reg (reg i) :=
+ geo.frame _ (geometry_preserves reg i hi)
+ let out := (systemMask s).val.testBit v.1.val
+ let inc := (systemMask s).val.testBit ((finRotate D).symm v.1).val
+ let off : Word W := (startOffset D H w s : Word W)
+ have ha : RouteAddresses.Ready (addressRegs reg) g out inc
+ (fun b ↦ base (.outgoing b)) (fun b ↦ base (.incoming b)) off :=
+ ⟨geo.outgoing, geo.incoming,
+ fun b ↦ (kept _ (by cases b <;> decide)).trans (h.outBase b),
+ fun b ↦ (kept _ (by cases b <;> decide)).trans (h.inBase b),
+ (kept 16 (by decide)).trans h.offset, (kept 17 (by decide)).trans h.zero⟩
+ obtain ⟨a, ptrs, addr⟩ :=
+ RouteAddresses.native hl.addresses (Nat.zero_le D |>.trans_lt hw) g geo.pc ha
+ have akeep (i : Fin 32) (h₀ : i ≠ 18) (h₁ : i ≠ 19) (h₂ : i ≠ 20) :
+ a.reg (reg i) = g.reg (reg i) :=
+ addr.frame _ (fun he ↦ h₀ (reg.injective he)) (fun he ↦ h₁ (reg.injective he))
+ (fun he ↦ h₂ (reg.injective he))
+ have mode : a.reg (fieldRegs reg 4) = (RouteGeometry.mode v s : Word W) :=
+ (akeep 7 (by decide) (by decide) (by decide)).trans geo.modeWord
+ have mask : a.reg (fieldRegs reg 5) = c.reg (reg 22) :=
+ (akeep 22 (by decide) (by decide) (by decide)).trans (kept 22 (by decide))
+ have width : a.reg (fieldRegs reg 3) = (ramFieldBits H w s : Word W) :=
+ (akeep 21 (by decide) (by decide) (by decide)).trans ((kept 21 (by decide)).trans h.width)
+ have one : a.reg (fieldRegs reg 6) = 1 :=
+ (akeep 23 (by decide) (by decide) (by decide)).trans ((kept 23 (by decide)).trans h.one)
+ obtain ⟨d, scan, hd, _, _, _, hmask, frame, mem, per⟩ :=
+ RouteField.run hl.field (ramFieldBits H w s) a addr.pc width one hfit
+ rw [mode] at scan hmask
+ have unused : a.reg (fieldRegs reg 0) = base (.outgoing (!out)) + off := addr.unused
+ have used : a.reg (fieldRegs reg 1) = base (.outgoing out) + off := addr.used
+ have incoming : a.reg (fieldRegs reg 2) = base (.incoming inc) + off := addr.incoming
+ rw [unused, used, incoming, addr.memory, geo.memory, mask] at hmask
+ refine ⟨d, ?_, hd, ?_, ?_, mem.trans (addr.memory.trans geo.memory),
+ per.trans (addr.persistent.trans geo.persistent)⟩
+ · rw [ticks, List.replicate_add, List.replicate_add]
+ exact (pre.append ptrs).append scan
+ · exact hmask.trans (and_congr_right' (agrees_iff_good v buf s c base hres hw))
+ · intro x hx
+ refine (frame x (field_preserves hx)).trans ((addr.frame x (hx 18 (by decide))
+ (hx 19 (by decide)) (hx 20 (by decide))).trans (geo.frame x ?_))
+ intro j hj
+ apply hx (Fin.castLE (by decide) j)
+ exact Or.inl ⟨hj, by change j.val ≤ 11; have := j.isLt; omega⟩
+
+end PairSimulation.RouteCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteClock.lean
new file mode 100644
index 0000000000..c81ac1e2c4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteClock.lean
@@ -0,0 +1,47 @@
+import OAI.Computability.VPVNP.RAMApplications
+import OAI.Computability.VPVNP.CursorFieldOffsets
+
+/-!
+# Clock for the native cursor routing checks
+
+The scheduler visits one successor field per cursor bit and at most one sort
+field per phase and step. Each resident word takes at most thirteen ticks.
+The processor's bounds on bucket size and word width put the entire scan,
+including its field setup and final decision, within the stated clock.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteClock
+
+open BurstRAM RAMLayout
+
+/-- The successor loop, nested sort loop and final decision fit within the
+routing allowance on both live and virtual processors. -/
+theorem scheduler_le {n D e w : ℕ} (budget : ProcessorBudget n D e w) (hn : 2048 ≤ n) :
+ (13 * (8 * w) + 37) * D + 2 + (((13 * blockBits (2 ^ e) w + 37) * D + 5) * D + 2) + 4 ≤
+ n ^ 5 := by
+ have hd : D ≤ n := by have h := budget.phase_le; omega
+ have hw := budget.word_le
+ have hH := budget.bucket_le
+ have hb : blockBits (2 ^ e) w ≤ 40 * n ^ 2 := calc
+ _ ≤ 4 * (2 * n) * 5 * n := by unfold blockBits; gcongr
+ _ = _ := by ring
+ have pos : 0 < n := by omega
+ have hn1 : 1 ≤ n ^ 4 := Nat.one_le_pow _ _ pos
+ have hn2 : n ≤ n ^ 4 := Nat.le_self_pow (by decide) n
+ have hn3 : n ^ 2 ≤ n ^ 4 := Nat.pow_le_pow_right pos (by decide)
+ calc
+ _ ≤ (13 * (8 * n) + 37) * n + 2 + (((13 * (40 * n ^ 2) + 37) * n + 5) * n + 2) + 4 := by
+ gcongr
+ _ = 520 * n ^ 4 + 141 * n ^ 2 + 42 * n + 8 := by ring
+ _ ≤ 711 * n ^ 4 := by omega
+ _ ≤ n ^ 5 := by rw [pow_succ' n 4]; exact Nat.mul_le_mul_right _ (by omega)
+
+end PairSimulation.RouteClock
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteField.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteField.lean
new file mode 100644
index 0000000000..4e2602ca2a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteField.lean
@@ -0,0 +1,358 @@
+import OAI.Computability.VPVNP.PairSimulationMapConsistency
+
+/-!
+# Scanning a resident field for the cursor routing constraints
+
+Each unused outgoing word must be zero. The mode determines the additional
+test on the used outgoing field. It is skipped at an active launch, clamped
+at an inactive successor, and compared with the selected incoming field at
+a transit vertex. The scan accumulates differences into a mask and advances
+all three cursors through the full field even after a mismatch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteField
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Registers 0–2 are the unused outgoing, used outgoing and selected
+incoming cursors. Registers 3–6 are the width, mode, sticky mask and one.
+Registers 7–10 are the loop index, zero and two scratch words. -/
+def instruction (pc : Fin 15 → Fin p) (reg : Fin 11 ↪ Fin r) (done : Fin p) :
+ Fin 15 → Instr w p r k :=
+ ![.constant (reg 7) 0 (pc 1), .constant (reg 8) 0 (pc 2),
+ .jumpEq (reg 7) (reg 3) done (pc 3), .loadPrivate (reg 9) (reg 0) (pc 4),
+ .binary .bitOr (reg 5) (reg 5) (reg 9) (pc 5),
+ .jumpEq (reg 4) (reg 8) (pc 11) (pc 6), .loadPrivate (reg 9) (reg 1) (pc 7),
+ .jumpEq (reg 4) (reg 6) (pc 10) (pc 8), .loadPrivate (reg 10) (reg 2) (pc 9),
+ .binary .bitXor (reg 9) (reg 9) (reg 10) (pc 10),
+ .binary .bitOr (reg 5) (reg 5) (reg 9) (pc 11),
+ .binary .add (reg 0) (reg 0) (reg 6) (pc 12),
+ .binary .add (reg 1) (reg 1) (reg 6) (pc 13),
+ .binary .add (reg 2) (reg 2) (reg 6) (pc 14),
+ .binary .add (reg 7) (reg 7) (reg 6) (pc 2)]
+
+/-- Resizing each instruction preserves its register operands and jump destinations. -/
+theorem resize_instruction (pc : Fin 15 → Fin p) (reg : Fin 11 ↪ Fin r) (done : Fin p)
+ (i : Fin 15) :
+ (instruction (w := 1) (k := k) pc reg done i).resize w = instruction pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- Each site in the machine contains its route-field instruction. -/
+def Linked (M : Machine w p r k) (pc : Fin 15 → Fin p) (reg : Fin 11 ↪ Fin r)
+ (done : Fin p) : Prop := ∀ i, M.code (pc i) = instruction pc reg done i
+
+/-- The mode word specifies the constraint on the selected outgoing field. -/
+def PayloadOK (mode used incoming : Word w) : Prop :=
+ if mode = 0 then True else if mode = 1 then used = 0 else used = incoming
+
+/-- Cost of dispatch and comparison for the selected outgoing word. -/
+def payloadSteps (mode : Word w) : ℕ := if mode = 0 then 1 else if mode = 1 then 4 else 6
+
+/-- Two setup instructions, a final exit test, and one pass through each word. -/
+def steps (mode : Word w) (width : ℕ) : ℕ := (7 + payloadSteps mode) * width + 3
+
+theorem steps_le (mode : Word w) (width : ℕ) : steps mode width ≤ 13 * width + 3 := by
+ have h : payloadSteps mode ≤ 6 := by
+ unfold payloadSteps
+ split <;> (first | decide | split <;> decide)
+ exact Nat.add_le_add_right (Nat.mul_le_mul_right width (by omega)) 3
+
+/-- The bits of all three arrays relevant to the current routing mode. -/
+def Agrees (mem : Word w → Word w) (mode unused used incoming : Word w) (width : ℕ) : Prop :=
+ ∀ j : Fin width, mem (unused + (j.val : Word w)) = 0 ∧
+ PayloadOK mode (mem (used + (j.val : Word w))) (mem (incoming + (j.val : Word w)))
+
+/-- The scan preserves the width, mode, constant one and all enclosing registers. -/
+def Preserved (reg : Fin 11 ↪ Fin r) (a : Fin r) : Prop :=
+ a ≠ reg 0 ∧ a ≠ reg 1 ∧ a ≠ reg 2 ∧ a ≠ reg 5 ∧ a ≠ reg 7 ∧ a ≠ reg 8 ∧
+ a ≠ reg 9 ∧ a ≠ reg 10
+
+variable {M : Machine w p r k} {pc : Fin 15 → Fin p} {reg : Fin 11 ↪ Fin r} {done : Fin p}
+
+theorem step_at (hl : Linked M pc reg done) (i : Fin 15) {c : Config w p r}
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc reg done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+theorem or_zero (x y : Word w) : BinaryOp.bitOr.eval x y = 0 ↔ x = 0 ∧ y = 0 := by
+ have h : (BinaryOp.bitOr.eval x y).val = x.val ||| y.val :=
+ Nat.mod_eq_of_lt (Nat.or_lt_two_pow x.isLt y.isLt)
+ simp only [Fin.ext_iff, h, Fin.val_zero, Nat.or_eq_zero_iff]
+
+theorem xor_zero (x y : Word w) : BinaryOp.bitXor.eval x y = 0 ↔ x = y := by
+ have h : (BinaryOp.bitXor.eval x y).val = x.val ^^^ y.val :=
+ Nat.mod_eq_of_lt (Nat.xor_lt_two_pow x.isLt y.isLt)
+ rw [Fin.ext_iff, h]
+ change x.val ^^^ y.val = 0 ↔ _
+ constructor
+ · intro he
+ apply Fin.ext
+ calc
+ x.val = (x.val ^^^ y.val) ^^^ y.val := by simp
+ _ = y.val := by simp [he]
+ · rintro rfl
+ simp
+
+private theorem payload (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 5)
+ (h1 : c.reg (reg 6) = 1) (h0 : c.reg (reg 8) = 0) :
+ ∃ out, Prefix M c (List.replicate (payloadSteps (c.reg (reg 4))) .tick) out ∧ out.pc = pc 11 ∧
+ (out.reg (reg 5) = 0 ↔ c.reg (reg 5) = 0 ∧ PayloadOK (c.reg (reg 4))
+ (c.privateMem (c.reg (reg 1))) (c.privateMem (c.reg (reg 2)))) ∧
+ (∀ a, a ≠ reg 5 → a ≠ reg 9 → a ≠ reg 10 → out.reg a = c.reg a) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ by_cases skip : c.reg (reg 4) = 0
+ · let out := {c with pc := pc 11}
+ have s₅ : M.program.step c = .localStep out := by
+ rw [step_at hl 5 hc]
+ change CallAction.localStep
+ {c with pc := if c.reg (reg 4) = c.reg (reg 8) then pc 11 else pc 6} = _
+ simp [out, skip, h0]
+ refine ⟨out, ?_, rfl, by simp [out, PayloadOK, skip], fun _ _ _ _ ↦ rfl, rfl, rfl⟩
+ rw [show payloadSteps (c.reg (reg 4)) = 1 by simp [payloadSteps, skip]]
+ exact .tick s₅ (.nil _)
+ let used := c.privateMem (c.reg (reg 1))
+ let c₆ := {c with pc := pc 6}
+ let c₇ := c₆.put (pc 7) (reg 9) used
+ have s₅ : M.program.step c = .localStep c₆ := by
+ rw [step_at hl 5 hc]
+ change CallAction.localStep
+ {c with pc := if c.reg (reg 4) = c.reg (reg 8) then pc 11 else pc 6} = _
+ simp [c₆, skip, h0]
+ have s₆ : M.program.step c₆ = .localStep c₇ := step_at hl 6 rfl
+ by_cases clamp : c.reg (reg 4) = 1
+ · let c₁₀ := {c₇ with pc := pc 10}
+ let out := c₁₀.put (pc 11) (reg 5) (BinaryOp.bitOr.eval (c.reg (reg 5)) used)
+ have s₇ : M.program.step c₇ = .localStep c₁₀ := by
+ rw [step_at hl 7 rfl]
+ change CallAction.localStep
+ {c₇ with pc := if c₇.reg (reg 4) = c₇.reg (reg 6) then pc 10 else pc 8} = _
+ simp [c₁₀, c₇, c₆, Config.put, clamp, h1]
+ have s₁₀ : M.program.step c₁₀ = .localStep out := by
+ rw [step_at hl 10 rfl]
+ change CallAction.localStep (c₁₀.put (pc 11) (reg 5)
+ (BinaryOp.bitOr.eval (c₁₀.reg (reg 5)) (c₁₀.reg (reg 9)))) = _
+ simp [out, c₁₀, c₇, c₆, Config.put]
+ refine ⟨out, ?_, rfl, ?_, ?_, rfl, rfl⟩
+ · rw [show payloadSteps (c.reg (reg 4)) = 4 by
+ simp only [payloadSteps, ite_eq_right skip, ite_eq_left clamp]]
+ exact .tick s₅ (.tick s₆ (.tick s₇ (.tick s₁₀ (.nil _))))
+ · simp only [out, Config.put, Function.update_self, or_zero, PayloadOK, ite_eq_right skip,
+ ite_eq_left clamp, used]
+ · intro a h₅ h₉ _
+ simp [out, c₁₀, c₇, c₆, Config.put, Function.update_of_ne, h₅, h₉]
+ · let incoming := c.privateMem (c.reg (reg 2))
+ let c₈ := {c₇ with pc := pc 8}
+ let c₉ := c₈.put (pc 9) (reg 10) incoming
+ let diff := BinaryOp.bitXor.eval used incoming
+ let c₁₀ := c₉.put (pc 10) (reg 9) diff
+ let out := c₁₀.put (pc 11) (reg 5) (BinaryOp.bitOr.eval (c.reg (reg 5)) diff)
+ have s₇ : M.program.step c₇ = .localStep c₈ := by
+ rw [step_at hl 7 rfl]
+ change CallAction.localStep
+ {c₇ with pc := if c₇.reg (reg 4) = c₇.reg (reg 6) then pc 10 else pc 8} = _
+ simp [c₈, c₇, c₆, Config.put, clamp, h1]
+ have s₈ : M.program.step c₈ = .localStep c₉ := by
+ rw [step_at hl 8 rfl]
+ change CallAction.localStep (c₈.put (pc 9) (reg 10) (c₈.privateMem (c₈.reg (reg 2)))) = _
+ simp [c₉, c₈, c₇, c₆, incoming, Config.put]
+ have s₉ : M.program.step c₉ = .localStep c₁₀ := by
+ rw [step_at hl 9 rfl]
+ change CallAction.localStep (c₉.put (pc 10) (reg 9)
+ (BinaryOp.bitXor.eval (c₉.reg (reg 9)) (c₉.reg (reg 10)))) = _
+ simp [c₁₀, diff, c₉, c₈, c₇, Config.put]
+ have s₁₀ : M.program.step c₁₀ = .localStep out := by
+ rw [step_at hl 10 rfl]
+ change CallAction.localStep (c₁₀.put (pc 11) (reg 5)
+ (BinaryOp.bitOr.eval (c₁₀.reg (reg 5)) (c₁₀.reg (reg 9)))) = _
+ simp [out, c₁₀, c₉, c₈, c₇, c₆, Config.put]
+ refine ⟨out, ?_, rfl, ?_, ?_, rfl, rfl⟩
+ · rw [show payloadSteps (c.reg (reg 4)) = 6 by simp [payloadSteps, skip, clamp]]
+ exact .tick s₅ (.tick s₆ (.tick s₇ (.tick s₈ (.tick s₉ (.tick s₁₀ (.nil _))))))
+ · simp only [out, Config.put, Function.update_self, or_zero, diff, xor_zero, PayloadOK,
+ ite_eq_right skip, ite_eq_right clamp, used, incoming]
+ · intro a h₅ h₉ h₁₀
+ simp [out, c₁₀, c₉, c₈, c₇, c₆, Config.put, Function.update_of_ne, h₅, h₉, h₁₀]
+
+private theorem advance (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 11)
+ (h1 : c.reg (reg 6) = 1) :
+ ∃ out, Prefix M c (List.replicate 4 .tick) out ∧ out.pc = pc 2 ∧
+ out.reg (reg 0) = c.reg (reg 0) + 1 ∧ out.reg (reg 1) = c.reg (reg 1) + 1 ∧
+ out.reg (reg 2) = c.reg (reg 2) + 1 ∧ out.reg (reg 7) = c.reg (reg 7) + 1 ∧
+ (∀ a, a ≠ reg 0 → a ≠ reg 1 → a ≠ reg 2 → a ≠ reg 7 → out.reg a = c.reg a) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let c₁ := c.put (pc 12) (reg 0) (c.reg (reg 0) + 1)
+ let c₂ := c₁.put (pc 13) (reg 1) (c.reg (reg 1) + 1)
+ let c₃ := c₂.put (pc 14) (reg 2) (c.reg (reg 2) + 1)
+ let out := c₃.put (pc 2) (reg 7) (c.reg (reg 7) + 1)
+ have s₀ : M.program.step c = .localStep c₁ := by
+ rw [step_at hl 11 hc]
+ change CallAction.localStep (c.put (pc 12) (reg 0) (c.reg (reg 0) + c.reg (reg 6))) = _
+ rw [h1]
+ have s₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [step_at hl 12 rfl]
+ change CallAction.localStep (c₁.put (pc 13) (reg 1) (c₁.reg (reg 1) + c₁.reg (reg 6))) = _
+ simp [c₂, c₁, Config.put, h1]
+ have s₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [step_at hl 13 rfl]
+ change CallAction.localStep (c₂.put (pc 14) (reg 2) (c₂.reg (reg 2) + c₂.reg (reg 6))) = _
+ simp [c₃, c₂, c₁, Config.put, h1]
+ have s₃ : M.program.step c₃ = .localStep out := by
+ rw [step_at hl 14 rfl]
+ change CallAction.localStep (c₃.put (pc 2) (reg 7) (c₃.reg (reg 7) + c₃.reg (reg 6))) = _
+ simp [out, c₃, c₂, c₁, Config.put, h1]
+ refine ⟨out, .tick s₀ (.tick s₁ (.tick s₂ (.tick s₃ (.nil _)))),
+ rfl, ?_, ?_, ?_, ?_, ?_, rfl, rfl⟩
+ · simp [out, c₃, c₂, c₁, Config.put]
+ · simp [out, c₃, c₂, Config.put]
+ · simp [out, c₃, Config.put]
+ · simp [out]
+ · intro a h₀ h₁ h₂ h₇
+ simp [out, c₃, c₂, c₁, Config.put, Function.update_of_ne, h₀, h₁, h₂, h₇]
+
+private theorem iteration (hl : Linked M pc reg done) (c : Config w p r) (hc : c.pc = pc 2)
+ (hne : c.reg (reg 7) ≠ c.reg (reg 3)) (h1 : c.reg (reg 6) = 1) (hz : c.reg (reg 8) = 0) :
+ ∃ out, Prefix M c (List.replicate (7 + payloadSteps (c.reg (reg 4))) .tick) out ∧
+ out.pc = pc 2 ∧ out.reg (reg 0) = c.reg (reg 0) + 1 ∧
+ out.reg (reg 1) = c.reg (reg 1) + 1 ∧ out.reg (reg 2) = c.reg (reg 2) + 1 ∧
+ out.reg (reg 7) = c.reg (reg 7) + 1 ∧
+ (out.reg (reg 5) = 0 ↔ c.reg (reg 5) = 0 ∧ c.privateMem (c.reg (reg 0)) = 0 ∧
+ PayloadOK (c.reg (reg 4)) (c.privateMem (c.reg (reg 1))) (c.privateMem (c.reg (reg 2)))) ∧
+ out.reg (reg 8) = 0 ∧ (∀ a, Preserved reg a → out.reg a = c.reg a) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ let x := c.privateMem (c.reg (reg 0))
+ let c₁ := {c with pc := pc 3}
+ let c₂ := c₁.put (pc 4) (reg 9) x
+ let q := c₂.put (pc 5) (reg 5) (BinaryOp.bitOr.eval (c.reg (reg 5)) x)
+ have s₂ : M.program.step c = .localStep c₁ := by
+ rw [step_at hl 2 hc]
+ simp [instruction, Instr.run, hne, c₁]
+ have s₃ : M.program.step c₁ = .localStep c₂ := step_at hl 3 rfl
+ have s₄ : M.program.step c₂ = .localStep q := by
+ rw [step_at hl 4 rfl]
+ change CallAction.localStep
+ (c₂.put _ _ (BinaryOp.bitOr.eval (c₂.reg (reg 5)) (c₂.reg (reg 9)))) = _
+ simp [q, c₂, c₁, Config.put]
+ have first : Prefix M c (List.replicate 3 .tick) q := .tick s₂ (.tick s₃ (.tick s₄ (.nil _)))
+ obtain ⟨mid, body, hpc, mask, frame, mem, per⟩ := payload hl q rfl
+ (by simp [q, c₂, c₁, Config.put, h1]) (by simp [q, c₂, c₁, Config.put, hz])
+ have keep (a : Fin r) (h₅ : a ≠ reg 5) (h₉ : a ≠ reg 9) (h₁₀ : a ≠ reg 10) :
+ mid.reg a = c.reg a := by
+ rw [frame a h₅ h₉ h₁₀]
+ simp [q, c₂, c₁, Config.put, Function.update_of_ne, h₅, h₉]
+ obtain ⟨out, incr, ret, r₀, r₁, r₂, r₇, frame', mem', per'⟩ := advance hl mid hpc
+ ((keep _ (by simp) (by simp) (by simp)).trans h1)
+ have mode : q.reg (reg 4) = c.reg (reg 4) := by simp [q, c₂, c₁, Config.put]
+ rw [mode] at body
+ refine ⟨out, ?_, ret, ?_, ?_, ?_, ?_, ?_, ?_, ?_, mem'.trans mem, per'.trans per⟩
+ · convert (first.append body).append incr using 1
+ rw [← List.replicate_add, ← List.replicate_add]
+ congr 1
+ omega
+ · rw [r₀, keep] <;> simp
+ · rw [r₁, keep] <;> simp
+ · rw [r₂, keep] <;> simp
+ · rw [r₇, keep] <;> simp
+ · rw [frame' (reg 5) (by simp) (by simp) (by simp) (by simp), mask]
+ simp [q, c₂, c₁, Config.put, or_zero, x, and_assoc]
+ · rw [frame', keep, hz] <;> simp
+ · rintro a ⟨h₀, h₁, h₂, h₅, h₇, _, h₉, h₁₀⟩
+ exact (frame' a h₀ h₁ h₂ h₇).trans (keep a h₅ h₉ h₁₀)
+
+private theorem loop (hl : Linked M pc reg done) (n : ℕ) (c : Config w p r) (hc : c.pc = pc 2)
+ (hend : c.reg (reg 3) = c.reg (reg 7) + (n : Word w))
+ (h1 : c.reg (reg 6) = 1) (hz : c.reg (reg 8) = 0) (hfit : n < 2 ^ w) :
+ ∃ out, Prefix M c (List.replicate ((7 + payloadSteps (c.reg (reg 4))) * n + 1) .tick) out ∧
+ out.pc = done ∧ out.reg (reg 0) = c.reg (reg 0) + (n : Word w) ∧
+ out.reg (reg 1) = c.reg (reg 1) + (n : Word w) ∧
+ out.reg (reg 2) = c.reg (reg 2) + (n : Word w) ∧
+ (out.reg (reg 5) = 0 ↔ c.reg (reg 5) = 0 ∧ Agrees c.privateMem (c.reg (reg 4))
+ (c.reg (reg 0)) (c.reg (reg 1)) (c.reg (reg 2)) n) ∧
+ (∀ a, Preserved reg a → out.reg a = c.reg a) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ induction n generalizing c with
+ | zero =>
+ have he : c.reg (reg 7) = c.reg (reg 3) := by simpa using hend.symm
+ have hs : M.program.step c = .localStep {c with pc := done} := by
+ rw [step_at hl 2 hc]
+ simp [instruction, Instr.run, he]
+ exact ⟨_, .tick hs (.nil _), rfl, by simp, by simp, by simp, by simp [Agrees],
+ fun _ _ ↦ rfl, rfl, rfl⟩
+ | succ n ih =>
+ have ne : c.reg (reg 7) ≠ c.reg (reg 3) := by
+ rw [hend]
+ intro he
+ have hz' : ((n + 1 : ℕ) : Word w) = 0 :=
+ add_left_cancel (a := c.reg (reg 7)) (by simpa using he.symm)
+ have hv := congrArg Fin.val hz'
+ change (n + 1) % (2 ^ w) = 0 at hv
+ rw [Nat.mod_eq_of_lt hfit] at hv
+ omega
+ obtain ⟨mid, pre, hpc, hu, hs, hi, hidx, mask, hzero, frame, hmem, hper⟩ :=
+ iteration hl c hc ne h1 hz
+ have hm : mid.reg (reg 4) = c.reg (reg 4) := frame _ (by simp [Preserved])
+ obtain ⟨out, tail, ho, hu', hs', hi', mask', frame', hmem', hper'⟩ :=
+ ih mid hpc (by rw [frame _ (by simp [Preserved]), hidx, hend]
+ simp [add_assoc, add_comm (1 : Word w)])
+ ((frame _ (by simp [Preserved])).trans h1) hzero (by omega)
+ refine ⟨out, ?_, ho, ?_, ?_, ?_, ?_, fun a ha ↦ (frame' a ha).trans (frame a ha),
+ hmem'.trans hmem, hper'.trans hper⟩
+ · rw [hm] at tail
+ convert pre.append tail using 1
+ rw [← List.replicate_add, Nat.mul_succ]
+ congr 1
+ omega
+ · simpa [hu, add_assoc, add_comm (1 : Word w)] using hu'
+ · simpa [hs, add_assoc, add_comm (1 : Word w)] using hs'
+ · simpa [hi, add_assoc, add_comm (1 : Word w)] using hi'
+ · rw [mask', mask, hmem, hm, hu, hs, hi]
+ simp [Agrees, Fin.forall_fin_succ, Fin.val_succ, add_assoc, add_comm (1 : Word w), and_assoc]
+
+/-- The fixed jump table checks all resident words in the three routed slices.
+The pointers may wrap or overlap. The only size restriction ensures that the
+width fits in the loop counter. -/
+theorem run (hl : Linked M pc reg done) (width : ℕ) (c : Config w p r) (hc : c.pc = pc 0)
+ (hwidth : c.reg (reg 3) = (width : Word w)) (h1 : c.reg (reg 6) = 1) (hfit : width < 2 ^ w) :
+ ∃ out, Prefix M c (List.replicate (steps (c.reg (reg 4)) width) .tick) out ∧ out.pc = done ∧
+ out.reg (reg 0) = c.reg (reg 0) + (width : Word w) ∧
+ out.reg (reg 1) = c.reg (reg 1) + (width : Word w) ∧
+ out.reg (reg 2) = c.reg (reg 2) + (width : Word w) ∧
+ (out.reg (reg 5) = 0 ↔ c.reg (reg 5) = 0 ∧
+ Agrees c.privateMem (c.reg (reg 4)) (c.reg (reg 0)) (c.reg (reg 1)) (c.reg (reg 2)) width) ∧
+ (∀ a, Preserved reg a → out.reg a = c.reg a) ∧ out.privateMem = c.privateMem ∧
+ out.persistent = c.persistent := by
+ let q := c.put (pc 1) (reg 7) 0
+ let d := q.put (pc 2) (reg 8) 0
+ have s₀ : M.program.step c = .localStep q := step_at hl 0 hc
+ have s₁ : M.program.step q = .localStep d := step_at hl 1 rfl
+ have pre : Prefix M c (List.replicate 2 .tick) d := .tick s₀ (.tick s₁ (.nil _))
+ obtain ⟨out, tail, hpc, r₀, r₁, r₂, mask, frame, mem, per⟩ := loop hl width d rfl
+ (by simp [d, q, Config.put, hwidth]) (by simp [d, q, Config.put, h1]) (by simp [d]) hfit
+ have mode : d.reg (reg 4) = c.reg (reg 4) := by simp [d, q, Config.put]
+ rw [mode] at tail
+ refine ⟨out, ?_, hpc, ?_, ?_, ?_, ?_, ?_, mem, per⟩
+ · convert pre.append tail using 1
+ rw [← List.replicate_add]
+ congr 1
+ unfold steps
+ omega
+ · simpa [d, q, Config.put] using r₀
+ · simpa [d, q, Config.put] using r₁
+ · simpa [d, q, Config.put] using r₂
+ · simpa [d, q, Config.put] using mask
+ · intro a h
+ rw [frame a h]
+ obtain ⟨_, _, _, _, h₇, h₈, _, _⟩ := h
+ simp [d, q, Config.put, Function.update_of_ne, h₇, h₈]
+
+end PairSimulation.RouteField
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteGeometry.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteGeometry.lean
new file mode 100644
index 0000000000..205342f566
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteGeometry.lean
@@ -0,0 +1,355 @@
+import OAI.Computability.VPVNP.CursorRouteChecker
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+import OAI.Computability.VPVNP.PairSimulationRouteSuccessorWord
+
+/-!
+# Native mask geometry at a cursor position
+
+The successor entry constructs its low-bit mask and tests the site against
+the unique nonwrapping successor. The sorting entry constructs a one-bit
+mask from phase and step. Both entries extract the outgoing and incoming
+bits from that mask, including the last cursor on arrival at cursor zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteGeometry
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork
+open scoped Fin.CommRing
+
+variable {D W p r k : ℕ}
+
+/-- Value of the outer counter at this field, either a successor class or a sorting phase. -/
+def outerIndex : RAMSystem D → ℕ
+ | .inl k => k.val
+ | .inr l => l.phase
+
+/-- Entry row for the system's geometry calculation. -/
+def entry : RAMSystem D → Fin 30
+ | .inl _ => 0
+ | .inr _ => 14
+
+/-- Number of native instructions executed along the selected entry path. -/
+def ticks : RAMSystem D → ℕ
+ | .inl _ => 26
+ | .inr _ => 16
+
+/-- At cursor zero a failed successor test clamps the selected outgoing
+field. Every other cursor compares the two selected fields. -/
+def mode [NeZero D] (v : Position D) (s : RAMSystem D) : ℕ :=
+ if v.1 = 0 then
+ match s with
+ | .inl j => if v.2.val + 1 < 2 ^ D ∧
+ v.2.val ^^^ (v.2.val + 1) = (systemMask (.inl j)).val then 0 else 1
+ | .inr _ => 0
+ else 2
+
+private inductive Operand
+ | zero | one
+ | binary (op : BinaryOp) (lhs rhs : Fin 12)
+
+/-- Rows 0–13 generate a successor mask and the inactive-source flag.
+Rows 14–17 generate a sorting mask and clear that flag. Rows 18–29 select
+the mode, form the cyclic predecessor, and read the two mask bits. -/
+private def row : Fin 30 → Fin 12 × Operand :=
+ ![(8, .one), (9, .binary .shiftLeft 8 3), (9, .binary .add 9 9),
+ (9, .binary .sub 9 8), (10, .binary .add 1 8), (10, .binary .bitXor 1 10),
+ (10, .binary .bitXor 10 9), (10, .binary .div 10 10), (11, .binary .shiftLeft 8 2),
+ (11, .binary .sub 11 8), (11, .binary .bitXor 11 1), (11, .binary .div 11 11),
+ (11, .binary .sub 8 11), (7, .binary .bitOr 10 11),
+ (8, .one), (10, .binary .sub 3 4), (9, .binary .shiftLeft 8 10), (7, .zero),
+ (10, .binary .div 0 0), (11, .binary .sub 8 10), (7, .binary .mul 7 11),
+ (10, .binary .add 10 10), (7, .binary .add 7 10), (11, .binary .mul 11 2),
+ (11, .binary .add 11 0), (11, .binary .sub 11 8), (5, .binary .shiftRight 9 0),
+ (5, .binary .bitAnd 5 8), (6, .binary .shiftRight 9 11), (6, .binary .bitAnd 6 8)]
+
+private def next (pc : Fin 30 → Fin p) (done : Fin p) (i : Fin 30) : Fin p :=
+ if i = 13 then pc 18 else if h : i.val + 1 < 30 then pc ⟨i.val + 1, h⟩ else done
+
+/-- The finite native geometry table with relocated register operands and continuations. -/
+def instruction (pc : Fin 30 → Fin p) (reg : Fin 12 ↪ Fin r) (done : Fin p)
+ (i : Fin 30) : Instr W p r k :=
+ let dst := reg (row i).1
+ let j := next pc done i
+ match (row i).2 with
+ | .zero => .constant dst 0 j
+ | .one => .constant dst 1 j
+ | .binary op lhs rhs => .binary op dst (reg lhs) (reg rhs) j
+
+theorem resize_instruction (pc : Fin 30 → Fin p) (reg : Fin 12 ↪ Fin r) (done : Fin p)
+ (i : Fin 30) :
+ (instruction (W := 1) (k := k) pc reg done i).resize W = instruction pc reg done i := by
+ unfold instruction
+ cases (row i).2 <;> rfl
+
+/-- Every row of the geometry table occurs in the enclosing machine. -/
+def Linked (M : Machine W p r k) (pc : Fin 30 → Fin p) (reg : Fin 12 ↪ Fin r) (done : Fin p) :=
+ ∀ i, M.code (pc i) = instruction pc reg done i
+
+/-- Registers outside the three results and four scratch slots. -/
+def Preserved (reg : Fin 12 ↪ Fin r) (a : Fin r) : Prop :=
+ ∀ i : Fin 12, 5 ≤ i.val → a ≠ reg i
+
+/-- Position, dimension and loop counters supplied by the routing scheduler. -/
+structure Ready (reg : Fin 12 ↪ Fin r) (v : Position D) (s : RAMSystem D)
+ (c : Config W p r) : Prop where
+ cursor : c.reg (reg 0) = (v.1.val : Word W)
+ site : c.reg (reg 1) = (v.2.val : Word W)
+ dimension : c.reg (reg 2) = (D : Word W)
+ outer : c.reg (reg 3) = (outerIndex s : Word W)
+ step : ∀ l, s = .inr l → c.reg (reg 4) = (l.step : Word W)
+
+/-- The selected sides and mode at the continuation, together with the register and memory frame. -/
+structure Result [NeZero D] (reg : Fin 12 ↪ Fin r) (done : Fin p) (v : Position D)
+ (s : RAMSystem D) (c d : Config W p r) : Prop where
+ pc : d.pc = done
+ outgoing : d.reg (reg 5) = (((systemMask s).val.testBit v.1.val).toNat : Word W)
+ incoming : d.reg (reg 6) =
+ (((systemMask s).val.testBit ((finRotate D).symm v.1).val).toNat : Word W)
+ modeWord : d.reg (reg 7) = (mode v s : Word W)
+ frame : ∀ a, Preserved reg a → d.reg a = c.reg a
+ memory : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+private def Operand.value (get : Fin 12 → Word W) : Operand → Word W
+ | .zero => 0
+ | .one => 1
+ | .binary op lhs rhs => op.eval (get lhs) (get rhs)
+
+private def advance (pc : Fin 30 → Fin p) (reg : Fin 12 ↪ Fin r) (done : Fin p) (i : Fin 30)
+ (c : Config W p r) :=
+ c.put (next pc done i) (reg (row i).1) ((row i).2.value (c.reg ∘ reg))
+
+variable {M : Machine W p r k} {pc : Fin 30 → Fin p} {reg : Fin 12 ↪ Fin r} {done : Fin p}
+
+private theorem local_step (hl : Linked M pc reg done) (i : Fin 30) (c : Config W p r)
+ (hc : c.pc = pc i) : M.program.step c = .localStep (advance pc reg done i c) := by
+ change (M.code c.pc).run M.publicData c = _
+ rw [hc, hl]
+ unfold instruction advance
+ cases (row i).2 <;> rfl
+
+private def walk (pc : Fin 30 → Fin p) (reg : Fin 12 ↪ Fin r) (done : Fin p)
+ (is : List (Fin 30)) (c : Config W p r) :=
+ is.foldl (fun d i => advance pc reg done i d) c
+
+private theorem advance_frame (i : Fin 30) (c : Config W p r) (a : Fin r)
+ (ha : Preserved reg a) : (advance pc reg done i c).reg a = c.reg a := by
+ have dst : ∀ j : Fin 30, 5 ≤ (row j).1.val := by decide
+ exact Function.update_of_ne (ha _ (dst i)) _ _
+
+private theorem walk_frame (is : List (Fin 30)) (c : Config W p r) (a : Fin r)
+ (ha : Preserved reg a) : (walk pc reg done is c).reg a = c.reg a := by
+ induction is generalizing c with
+ | nil => rfl
+ | cons i is ih => exact (ih _).trans (advance_frame _ _ _ ha)
+
+private def successors : List (Fin 30) := [0,1,2,3,4,5,6,7,8,9,10,11,12,13]
+private def sorting : List (Fin 30) := [14,15,16,17]
+private def finish : List (Fin 30) := [18,19,20,21,22,23,24,25,26,27,28,29]
+
+private theorem walk_prefix (hl : Linked M pc reg done) (is : List (Fin 30))
+ (c : Config W p r)
+ (linked : List.IsChain (fun i j => next pc done i = pc j) is)
+ (atHead : ∀ i ∈ is.head?, c.pc = pc i) :
+ Prefix M c (List.replicate is.length .tick) (walk pc reg done is c) := by
+ induction is generalizing c with
+ | nil => exact .nil _
+ | cons i is ih =>
+ refine .tick (local_step hl i c (atHead i rfl)) (ih _ ?_ ?_)
+ · exact linked.tail
+ · cases is with
+ | nil => simp
+ | cons j js =>
+ intro a ha
+ have he : a = j := Option.some.inj ha.symm
+ subst a
+ exact (List.isChain_cons_cons.mp linked).1
+
+private theorem native_path (hl : Linked M pc reg done) (s : RAMSystem D) (c : Config W p r)
+ (hc : c.pc = pc (entry s)) :
+ let first := match s with | .inl _ => successors | .inr _ => sorting
+ Prefix M c (List.replicate (ticks s) .tick) (walk pc reg done finish (walk pc reg done first c)) := by
+ have hf : List.IsChain (fun i j => next pc done i = pc j) finish := by
+ simp only [finish, List.isChain_cons_cons, List.IsChain.singleton, and_true]
+ repeat' first | rfl | constructor
+ cases s with
+ | inl k =>
+ refine (walk_prefix hl successors c ?_ ?_).append (walk_prefix hl finish _ hf ?_)
+ · simp only [successors, List.isChain_cons_cons, List.IsChain.singleton, and_true]
+ repeat' first | rfl | constructor
+ · intro i hi
+ cases Option.some.inj hi
+ exact hc
+ · intro i hi
+ cases Option.some.inj hi
+ rfl
+ | inr l =>
+ refine (walk_prefix hl sorting c ?_ ?_).append (walk_prefix hl finish _ hf ?_)
+ · simp only [sorting, List.isChain_cons_cons, List.IsChain.singleton, and_true]
+ repeat' first | rfl | constructor
+ · intro i hi
+ cases Option.some.inj hi
+ exact hc
+ · intro i hi
+ cases Option.some.inj hi
+ rfl
+
+private theorem read_row (j : Fin 12) (l : Fin 30) (c : Config W p r) :
+ (advance pc reg done l c).reg (reg j) =
+ if j = (row l).1 then (row l).2.value (c.reg ∘ reg) else c.reg (reg j) := by
+ simp only [advance, Config.put, Function.update_apply, reg.injective.eq_iff]
+
+private abbrev shl (x : Word W) := BinaryOp.shiftLeft.eval (1 : Word W) x
+private abbrev nz (x : Word W) := BinaryOp.div.eval x x
+private abbrev xor (x y : Word W) := BinaryOp.bitXor.eval x y
+private abbrev flagOr (x y : Word W) := BinaryOp.bitOr.eval x y
+
+private theorem successor_values (c : Config W p r) :
+ let q := walk pc reg done successors c
+ let i := c.reg (reg 3)
+ let x := c.reg (reg 1)
+ let m := shl i + shl i - 1
+ q.reg (reg 8) = 1 ∧ q.reg (reg 9) = m ∧
+ q.reg (reg 7) = flagOr (nz (xor (xor x (x + 1)) m))
+ (1 - nz (xor (shl (c.reg (reg 2)) - 1) x)) := by
+ dsimp only [walk, successors, List.foldl]
+ simp [read_row, row, Operand.value, Function.comp_apply, shl, nz, xor, flagOr, BinaryOp.eval]
+
+private theorem sorting_values (c : Config W p r) :
+ let q := walk pc reg done sorting c
+ q.reg (reg 8) = 1 ∧ q.reg (reg 9) = shl (c.reg (reg 3) - c.reg (reg 4)) ∧
+ q.reg (reg 7) = 0 := by
+ dsimp only [walk, sorting, List.foldl]
+ simp [read_row, row, Operand.value, Function.comp_apply, shl, BinaryOp.eval]
+
+private abbrev readBit (x i : Word W) :=
+ BinaryOp.bitAnd.eval (BinaryOp.shiftRight.eval x i) 1
+
+private theorem finish_values (q : Config W p r) (h1 : q.reg (reg 8) = 1) :
+ let d := walk pc reg done finish q
+ let cur := q.reg (reg 0)
+ let nonzero := nz cur
+ let atZero := 1 - nonzero
+ let prev := atZero * q.reg (reg 2) + cur - 1
+ let mask := q.reg (reg 9)
+ d.reg (reg 5) = readBit mask cur ∧ d.reg (reg 6) = readBit mask prev ∧
+ d.reg (reg 7) = q.reg (reg 7) * atZero + (nonzero + nonzero) := by
+ dsimp only [walk, finish, List.foldl]
+ simp [read_row, row, Operand.value, Function.comp_apply, readBit, nz, BinaryOp.eval, h1]
+ rfl
+
+private def initialClamp (x : Site D) : RAMSystem D → Bool
+ | .inl j => decide (¬ (x.val + 1 < 2 ^ D ∧ x.val ^^^ (x.val + 1) = (systemMask (.inl j)).val))
+ | .inr _ => false
+
+private def startRows : RAMSystem D → List (Fin 30)
+ | .inl _ => successors
+ | .inr _ => sorting
+
+private theorem kept_input (j : Fin 12) (hj : j.val < 5) : Preserved reg (reg j) := by
+ intro i hi he
+ have := congrArg Fin.val (reg.injective he)
+ omega
+
+private theorem prev_zero [NeZero D] : ((finRotate D).symm 0).val = D - 1 := by
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (NeZero.ne D)
+ have eq : (finRotate (n+1)).symm 0 = Fin.last n :=
+ (finRotate (n+1)).symm_apply_eq.mpr finRotate_last.symm
+ simp [eq]
+
+private theorem cursor_values [NeZero D] (v : Position D) (s : RAMSystem D) (hw : D < W) :
+ let cur := (v.1.val : Word W)
+ let z := nz cur
+ (1 - z) * (D : Word W) + cur - 1 = (((finRotate D).symm v.1).val : Word W) ∧
+ ((initialClamp v.2 s).toNat : Word W) * (1 - z) + (z + z) = (mode v s : Word W) := by
+ dsimp only
+ rw [show nz (v.1.val : Word W) = _ from
+ RouteWord.div_self (v.1.isLt.trans (hw.trans Nat.lt_two_pow_self))]
+ by_cases h : v.1 = 0
+ · rw [h, Fin.val_zero, ite_eq_left rfl, prev_zero]
+ have hD : 1 ≤ D := Nat.pos_of_ne_zero (NeZero.ne D)
+ simp only [Nat.cast_zero, sub_zero, one_mul, add_zero, Nat.cast_sub hD, Nat.cast_one,
+ mul_one, true_and]
+ cases s with
+ | inl j =>
+ simp only [mode, h, ite_true, initialClamp]
+ split <;> simp_all
+ | inr l => simp [mode, h, initialClamp]
+ · have hn : v.1.val ≠ 0 := Fin.val_ne_zero_iff.mpr h
+ rw [ite_eq_right hn, coe_finRotate_symm_of_ne_zero h]
+ simp [Nat.cast_sub (Nat.pos_of_ne_zero hn), mode, h]
+ exact one_add_one_eq_two
+
+private theorem final_values [NeZero D] (v : Position D) (s : RAMSystem D) (hw : D < W)
+ (q : Config W p r) (hc : q.reg (reg 0) = (v.1.val : Word W))
+ (hD : q.reg (reg 2) = (D : Word W)) (hone : q.reg (reg 8) = 1)
+ (hm : q.reg (reg 9) = ((systemMask s).val : Word W))
+ (hs : q.reg (reg 7) = ((initialClamp v.2 s).toNat : Word W)) :
+ let d := walk pc reg done finish q
+ d.reg (reg 5) = (((systemMask s).val.testBit v.1.val).toNat : Word W) ∧
+ d.reg (reg 6) = (((systemMask s).val.testBit ((finRotate D).symm v.1).val).toNat : Word W) ∧
+ d.reg (reg 7) = (mode v s : Word W) := by
+ have ⟨hout, hin, hmode⟩ := finish_values (pc := pc) (done := done) q hone
+ dsimp only at hout hin hmode ⊢
+ rw [hc, hm] at hout
+ rw [hc, hD, hm, (cursor_values v s hw).1] at hin
+ rw [hc, hs, (cursor_values v s hw).2] at hmode
+ have bound := (systemMask s).isLt.trans (Nat.pow_lt_pow_right (by decide) hw)
+ exact ⟨hout.trans (RouteWord.maskBit (v.1.isLt.trans hw) bound),
+ hin.trans (RouteWord.maskBit (((finRotate D).symm v.1).isLt.trans hw) bound), hmode⟩
+
+private theorem sort_ready (v : Position D) (l : RAMLayout.Layer D) (hw : D < W)
+ (c : Config W p r) (h : Ready reg v (.inr l) c) :
+ let q := walk pc reg done sorting c
+ q.reg (reg 8) = 1 ∧ q.reg (reg 9) = ((systemMask (.inr l)).val : Word W) ∧
+ q.reg (reg 7) = ((initialClamp v.2 (.inr l)).toNat : Word W) := by
+ have ⟨h1, hm, hs⟩ := sorting_values (pc := pc) (reg := reg) (done := done) c
+ rw [h.outer, h.step l rfl] at hm
+ change _ = shl ((l.phase : Word W) - (l.step : Word W)) at hm
+ rw [← Nat.cast_sub l.step_le] at hm
+ exact ⟨h1, hm.trans (RouteWord.shl_one (l.siteBit_lt.trans hw)), hs⟩
+
+private theorem setup_ready (v : Position D) (s : RAMSystem D) (hw : D < W)
+ (c : Config W p r) (h : Ready reg v s c) :
+ let q := walk pc reg done (startRows s) c
+ q.reg (reg 8) = 1 ∧ q.reg (reg 9) = ((systemMask s).val : Word W) ∧
+ q.reg (reg 7) = ((initialClamp v.2 s).toNat : Word W) := by
+ cases s with
+ | inr l => exact sort_ready v l hw c h
+ | inl j =>
+ have ⟨h1, hm, hs⟩ := successor_values (pc := pc) (reg := reg) (done := done) c
+ rw [h.outer] at hm
+ rw [h.outer, h.dimension, h.site] at hs
+ have geom := RouteWord.successor_values v.2 j hw
+ exact ⟨h1, hm.trans geom.1, hs.trans geom.2⟩
+
+/-- The two fixed entry paths compute every field's side flags and test mode
+from the live system counters and position words. -/
+theorem native [NeZero D] (hl : Linked M pc reg done) (v : Position D) (s : RAMSystem D)
+ (hw : D < W) (c : Config W p r) (hc : c.pc = pc (entry s)) (h : Ready reg v s c) :
+ ∃ d, Prefix M c (List.replicate (ticks s) .tick) d ∧ Result reg done v s c d := by
+ let q := walk pc reg done (startRows s) c
+ let d := walk pc reg done finish q
+ have ⟨one, mask, clamp⟩ := setup_ready (pc := pc) (done := done) v s hw c h
+ have cursor : q.reg (reg 0) = (v.1.val : Word W) :=
+ (walk_frame _ _ _ (kept_input 0 (by decide))).trans h.cursor
+ have dim : q.reg (reg 2) = (D : Word W) :=
+ (walk_frame _ _ _ (kept_input 2 (by decide))).trans h.dimension
+ have ⟨outgoing, incoming, modeWord⟩ :=
+ final_values (pc := pc) (done := done) v s hw q cursor dim one mask clamp
+ refine ⟨d, ?_, rfl, outgoing, incoming, modeWord, ?_, ?_, ?_⟩
+ · cases s <;> exact native_path hl _ c hc
+ · intro a ha
+ exact (walk_frame _ q a ha).trans (walk_frame _ c a ha)
+ · cases s <;> rfl
+ · cases s <;> rfl
+
+end PairSimulation.RouteGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteLoop.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteLoop.lean
new file mode 100644
index 0000000000..75a32ca761
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteLoop.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+import Mathlib.Algebra.BigOperators.Fin
+
+/-!
+# Native counted traversal of cursor routing fields
+
+The field scheduler uses the same three labels for a successor scan, a
+phase scan, and the scan of steps within a phase. The body may itself
+traverse an inner loop. The traversal theorem counts every test, increment
+and body instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteLoop
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- The loop resets the index, tests it against the exclusive bound and
+advances it after the body. The constant-one register is an input. -/
+def instruction (pc : Fin 3 → Fin p) (index bound one : Fin r) (body done : Fin p) :
+ Fin 3 → Instr w p r k :=
+ ![.constant index 0 (pc 1), .jumpEq index bound done body,
+ .binary .add index index one (pc 1)]
+
+theorem resize_instruction (pc : Fin 3 → Fin p) (index bound one : Fin r) (body done : Fin p)
+ (i : Fin 3) : (instruction (w := 1) (k := k) pc index bound one body done i).resize w =
+ instruction pc index bound one body done i := by fin_cases i <;> rfl
+
+/-- All three loop-control instructions occur in the enclosing machine. -/
+def Linked (M : Machine w p r k) (pc : Fin 3 → Fin p) (index bound one : Fin r)
+ (body done : Fin p) : Prop := ∀ i, M.code (pc i) = instruction pc index bound one body done i
+
+variable {M : Machine w p r k} {pc : Fin 3 → Fin p} {index bound one : Fin r} {body done : Fin p}
+
+private theorem step_at (hl : Linked M pc index bound one body done) (i : Fin 3) {c : Config w p r}
+ (hc : c.pc = pc i) :
+ M.program.step c = (instruction pc index bound one body done i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+/-- Run the fixed loop on a body with an exact per-index instruction count.
+The invariant may refer to registers, private memory and the processed prefix. -/
+theorem run_exact (hl : Linked M pc index bound one body done) (n : ℕ) (cost : Fin n → ℕ)
+ (hn : n < 2 ^ w) (I : ℕ → Config w p r → Prop)
+ (bound_ok : ∀ i q, I i q → q.reg bound = (n : Word w))
+ (retag : ∀ i q dst, I i q → I i { q with pc := dst })
+ (visit : ∀ i : Fin n, ∀ q : Config w p r, q.pc = body → q.reg index = (i.val : Word w) →
+ I i.val q → ∃ d, Prefix M q (List.replicate (cost i) .tick) d ∧ d.pc = pc 2 ∧
+ d.reg index = (i.val : Word w) ∧ d.reg one = 1 ∧
+ I (i.val + 1) (d.put (pc 1) index ((i.val + 1 : ℕ) : Word w)))
+ (c : Config w p r) (hc : c.pc = pc 0) (init : I 0 (c.put (pc 1) index 0)) :
+ ∃ d, Prefix M c (List.replicate (2 + ∑ i, (cost i + 2)) .tick) d ∧
+ d.pc = done ∧ d.reg index = (n : Word w) ∧ I n d := by
+ have loop (m : ℕ) (hm : m ≤ n) :
+ ∃ q, Prefix M c (List.replicate (1 + ∑ i : Fin m, (cost (Fin.castLE hm i) + 2)) .tick) q ∧
+ q.pc = pc 1 ∧ q.reg index = (m : Word w) ∧ I m q := by
+ induction m with
+ | zero =>
+ have start : M.program.step c = .localStep (c.put (pc 1) index 0) := step_at hl 0 hc
+ refine ⟨_, ?_, rfl, by simp, init⟩
+ simp only [Finset.univ_eq_empty, Finset.sum_empty, Nat.add_zero]
+ exact .tick start (.nil _)
+ | succ m ih =>
+ let i : Fin n := ⟨m, hm⟩
+ obtain ⟨q, pre, hp, hidx, hI⟩ := ih (Nat.le_of_succ_le hm)
+ have ne : q.reg index ≠ q.reg bound := by
+ rw [hidx, bound_ok m q hI]
+ intro he
+ have hv := congrArg Fin.val he
+ change m % (2 ^ w) = n % (2 ^ w) at hv
+ rw [Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt hn] at hv
+ omega
+ let entered := {q with pc := body}
+ have first : M.program.step q = .localStep entered := by
+ rw [step_at hl 1 hp]
+ simp [instruction, Instr.run, entered, ne]
+ obtain ⟨mid, work, hp', hidx', h1, hnext⟩ :=
+ visit i entered rfl hidx (retag m q body hI)
+ let next := mid.put (pc 1) index ((m+1 : ℕ) : Word w)
+ have bump : M.program.step mid = .localStep next := by
+ rw [step_at hl 2 hp']
+ change CallAction.localStep (mid.put (pc 1) index (mid.reg index + mid.reg one)) = _
+ simp [hidx', h1, next, i]
+ refine ⟨next, ?_, rfl, by simp [next], hnext⟩
+ have head : Prefix M q (List.replicate 1 .tick) entered := .tick first (.nil _)
+ have tail : Prefix M mid (List.replicate 1 .tick) next := .tick bump (.nil _)
+ rw [Fin.sum_univ_castSucc]
+ convert ((pre.append head).append work).append tail using 1
+ rw [← List.replicate_add, ← List.replicate_add, ← List.replicate_add]
+ congr 1
+ let prev := ∑ j : Fin m, (cost (Fin.castLE (Nat.le_of_succ_le hm) j) + 2)
+ change 1 + (prev + (cost i + 2)) = 1 + prev + 1 + cost i + 1
+ omega
+ obtain ⟨q, pre, hp, hidx, hI⟩ := loop n (le_refl n)
+ let out := {q with pc := done}
+ have he := hidx.trans (bound_ok n q hI).symm
+ have exitStep : M.program.step q = .localStep out := by
+ rw [step_at hl 1 hp]
+ simp [instruction, Instr.run, he, out]
+ have tail : Prefix M q (List.replicate 1 .tick) out := .tick exitStep (.nil _)
+ refine ⟨out, ?_, rfl, hidx, retag n q done hI⟩
+ convert pre.append tail using 1
+ rw [← List.replicate_add]
+ congr 1
+ simp only [Fin.castLE_refl]
+ omega
+
+end PairSimulation.RouteLoop
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRoutePhases.lean b/lean/OAI/Computability/VPVNP/PairSimulationRoutePhases.lean
new file mode 100644
index 0000000000..623694e163
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRoutePhases.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.PairSimulationRouteSteps
+
+/-!
+# The triangular sorting-phase traversal
+
+The outer counter supplies the phase to the step scan. Its step bound is
+phase plus one, so the offset after each phase is the start of the next
+triangular layer block. Every layer's routing check enters the final mask.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteSchedule
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork RAMLayout
+open scoped Fin.CommRing
+
+variable {D H w W p r k : ℕ} [NeZero D]
+
+/-- Prefix invariant after a given number of complete sorting phases. -/
+structure PhaseState (reg : Fin 32 ↪ Fin r) (v : Position D) (buf : Buffers D H w)
+ (width i : ℕ) (c d : Config W p r) : Prop extends RouteRange.Frame (PhaseKeep reg) c d where
+ offset : d.reg (reg 16) = c.reg (reg 16) + ((layerCount i * width : ℕ) : Word W)
+ maskEq : d.reg (reg 22) = 0 ↔ c.reg (reg 22) = 0 ∧
+ ∀ l : Layer D, l.phase < i → RouteCall.Good v buf (.inr l)
+
+open private layerCount_succ from OAI.Computability.VPVNP.RAMLayout
+
+/-- Run all sorting fields using the same fixed phase and step control code
+at every input size. The clock counts every visit on malformed inputs. -/
+theorem phases_exact {P : Program p r} {M : Machine W p r k} (hl : P.Linked M)
+ (v : Position D) (buf : Buffers D H w) (base : LocalPort → Word W) (c : Config W p r)
+ (hc : c.pc = P.phase 0) (inp : Inputs P.reg v buf base c)
+ (hwidth : c.reg (P.reg 21) = (blockBits H w : Word W))
+ (hoff : c.reg (P.reg 16) = ((D * (8 * w) : ℕ) : Word W))
+ (hW : D < W) (hfit : blockBits H w < 2 ^ W) :
+ ∃ d, Prefix M c (List.replicate (phaseTicks W v H w) .tick) d ∧ d.pc = P.pc 6 ∧
+ d.reg (P.reg 3) = (D : Word W) ∧ PhaseState P.reg v buf (blockBits H w) D c d := by
+ let bw := blockBits H w
+ let I i d := PhaseState P.reg v buf bw i c d
+ have stable (j : Fin 32) (hs : ¬ RouteCall.Scratch j) (h₄ : j ≠ 4)
+ (h₁₆ : j ≠ 16) (h₃ : j ≠ 3) (h₂₈ : j ≠ 28) :
+ PhaseKeep P.reg (P.reg j) :=
+ ⟨rangeKeep_reg P.reg 4 j hs h₄ h₁₆, P.reg.injective.ne h₃, P.reg.injective.ne h₂₈⟩
+ have init : I 0 (c.put (P.phase 1) (P.reg 3) 0) := by
+ refine ⟨(RouteRange.Frame.refl c).put _ _ _ (fun _ h ↦ h.2.1), ?_, ?_⟩
+ · simp [layerCount, Config.put]
+ · simp [Config.put]
+ have visit (i : Fin D) (q : Config W p r) (hpc : q.pc = P.pc 4)
+ (hidx : q.reg (P.reg 3) = (i.val : Word W)) (hI : I i.val q) :
+ ∃ d, Prefix M q (List.replicate (rowTicks W v H w i + 1) .tick) d ∧
+ d.pc = P.phase 2 ∧ d.reg (P.reg 3) = (i.val : Word W) ∧ d.reg (P.reg 23) = 1 ∧
+ I (i.val+1) (d.put (P.phase 1) (P.reg 3) ((i.val+1 : ℕ) : Word W)) := by
+ let start := q.put (P.step 0) (P.reg 28) ((i.val+1 : ℕ) : Word W)
+ have fstart : RouteRange.Frame (PhaseKeep P.reg) c start :=
+ hI.toFrame.put _ _ _ fun _ h ↦ h.2.2
+ have inStart := inp.transfer (narrowFrame fstart fun _ h ↦ h.1)
+ have hone := (hI.regs _ (stable 23 (by decide) (by decide) (by decide)
+ (by decide) (by decide))).trans inp.one
+ have first : M.program.step q = .localStep start := by
+ change (M.code q.pc).run M.publicData q = _
+ rw [hpc, hl.control 4]
+ change CallAction.localStep (q.put (P.step 0) (P.reg 28)
+ (q.reg (P.reg 3) + q.reg (P.reg 23))) = _
+ simp [start, hidx, hone]
+ have hi : start.reg (P.reg 3) = (i.val : Word W) := by simp [start, Config.put, hidx]
+ have hwb : start.reg (P.reg 21) = (blockBits H w : Word W) :=
+ (fstart.regs _ (stable 21 (by decide) (by decide) (by decide)
+ (by decide) (by decide))).trans hwidth
+ have ho : start.reg (P.reg 16) = ((D*(8*w)+layerCount i.val*bw : ℕ) : Word W) := by
+ simp [start, Config.put, hI.offset, hoff, bw]
+ obtain ⟨d, scan, hd, _, hscan⟩ := steps_exact hl v buf base i start rfl inStart hi
+ (by simp [start]) hwb ho hW hfit
+ have g := fstart.trans (narrowFrame hscan.toFrame (keep₂ := PhaseKeep P.reg) fun _ h ↦ h.1)
+ have dphase : d.reg (P.reg 3) = (i.val : Word W) :=
+ (hscan.regs _ (rangeKeep_reg P.reg 4 3 (by decide) (by decide) (by decide))).trans hi
+ refine ⟨d, ?_, hd, dphase, (g.regs _ (stable 23 (by decide) (by decide)
+ (by decide) (by decide) (by decide))).trans inp.one, ?_⟩
+ · rw [Nat.add_comm (rowTicks W v H w i) 1, List.replicate_add]
+ exact (Prefix.tick first (.nil _)).append scan
+ refine ⟨g.put _ _ _ (fun _ h ↦ h.2.1), ?_, ?_⟩
+ · change Function.update d.reg (P.reg 3) _ (P.reg 16) = _
+ rw [Function.update_of_ne (P.reg.injective.ne (by decide)), hscan.offset]
+ change Function.update q.reg (P.reg 28) _ (P.reg 16) + _ = _
+ rw [Function.update_of_ne (P.reg.injective.ne (by decide)), hI.offset, layerCount_succ]
+ simp [bw, Nat.add_mul, add_assoc]
+ · change Function.update d.reg (P.reg 3) _ (P.reg 22) = 0 ↔ _
+ rw [Function.update_of_ne (P.reg.injective.ne (by decide)), hscan.maskEq]
+ change (Function.update q.reg (P.reg 28) _ (P.reg 22) = 0 ∧ _) ↔ _
+ rw [Function.update_of_ne (P.reg.injective.ne (by decide)), hI.maskEq]
+ constructor
+ · rintro ⟨⟨hz, before⟩, row⟩
+ refine ⟨hz, fun l hlayer ↦ ?_⟩
+ by_cases he : l.phase = i.val
+ · let j : Fin (i.val+1) := ⟨l.step, by have := l.step_le; omega⟩
+ have eq : layer i j = l := Layer.ext he.symm rfl
+ exact eq ▸ row j j.isLt
+ · exact before l (by omega)
+ · rintro ⟨hz, before⟩
+ exact ⟨⟨hz, fun l h ↦ before l (by omega)⟩, fun j _ ↦ before (layer i j) (by simp [layer])⟩
+ have hd : D < 2 ^ W := hW.trans (Nat.lt_two_pow_self)
+ exact RouteLoop.run_exact hl.phases D (fun i ↦ rowTicks W v H w i + 1) hd I
+ (fun _ _ h ↦ (h.regs _ (stable 2 (by decide) (by decide) (by decide)
+ (by decide) (by decide))).trans inp.dimension)
+ (fun _ _ _ h ↦ ⟨⟨h.regs, h.memory, h.persistent⟩, h.offset, h.maskEq⟩)
+ visit c hc init
+
+/-- The sorting traversal is bounded by the same clock on all inputs. -/
+theorem phases {P : Program p r} {M : Machine W p r k} (hl : P.Linked M)
+ (v : Position D) (buf : Buffers D H w) (base : LocalPort → Word W) (c : Config W p r)
+ (hc : c.pc = P.phase 0) (inp : Inputs P.reg v buf base c)
+ (hwidth : c.reg (P.reg 21) = (blockBits H w : Word W))
+ (hoff : c.reg (P.reg 16) = ((D * (8 * w) : ℕ) : Word W))
+ (hW : D < W) (hfit : blockBits H w < 2 ^ W) :
+ ∃ ticks d, ticks ≤ ((13 * blockBits H w + 37)*D + 5)*D + 2 ∧
+ Prefix M c (List.replicate ticks .tick) d ∧ d.pc = P.pc 6 ∧
+ d.reg (P.reg 3) = (D : Word W) ∧ PhaseState P.reg v buf (blockBits H w) D c d := by
+ obtain ⟨d, pre, hp, hi, st⟩ := phases_exact hl v buf base c hc inp hwidth hoff hW hfit
+ exact ⟨_, d, phaseTicks_le W v H w, pre, hp, hi, st⟩
+
+end PairSimulation.RouteSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRoutePrepare.lean b/lean/OAI/Computability/VPVNP/PairSimulationRoutePrepare.lean
new file mode 100644
index 0000000000..f84ae3e205
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRoutePrepare.lean
@@ -0,0 +1,257 @@
+import OAI.Computability.VPVNP.PairSimulationLeafArena
+import OAI.Computability.VPVNP.PairSimulationLeafPhysicalInput
+import OAI.Computability.VPVNP.PairSimulationLeafIncidentGeometry
+import OAI.Computability.VPVNP.PairSimulationRouteSchedule
+
+/-!
+# Preparing the routing checker from the private DFS arguments
+
+A leaf enters with a decoded cursor, site and descriptor address. Fourteen
+instructions copy the coordinates, compute the descriptor's argument base,
+and read the three geometry words in the operand cache. Fifteen arithmetic
+instructions compute the successor and sorting widths and the four buffer
+bases. Every instruction contributes one tick.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RoutePrepare
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork RAMLayout
+open NodeArguments
+open LeafIncidentGeometry (Line)
+open scoped Fin.CommRing
+
+variable {D H w W p r k : ℕ}
+
+/-- Public pointers to the argument arena and the private geometry cache. -/
+inductive Field where
+ | start | stride | cache
+ deriving DecidableEq
+
+instance : Fintype Field :=
+ ⟨{.start,.stride,.cache}, fun i => by cases i <;> decide⟩
+
+/-- The labels of the operand fetches and the arithmetic sequence. -/
+abbrev Stage := Fin 14 ⊕ Fin 15
+
+/-- Number of native private instructions before the first route test. -/
+def ticks : ℕ := 29
+
+/-- Host-word address of the first bit of a stored half-wire. -/
+def portBase (A : Arena) (node D H w : ℕ) (port : LocalPort) : Word W :=
+ (LeafHandler.portBase A node (ramPayloadWidth D H w) port : Word W)
+
+private def fetch (pc : Fin 14 → Fin p) (reg : Fin 32 ↪ Fin r) (leaf : LeafAddress.Reg ↪ Fin r)
+ (pub : Field → Fin k) (next : Fin p) : Fin 14 → Instr W p r k :=
+ ![.copy (reg 0) (leaf .cursor) (pc 1),
+ .copy (reg 1) (leaf .site) (pc 2),
+ .publicWord (reg 7) (pub .stride) (pc 3),
+ .binary .mul (reg 12) (leaf .node) (reg 7) (pc 4),
+ .publicWord (reg 7) (pub .start) (pc 5),
+ .binary .add (reg 12) (reg 7) (reg 12) (pc 6),
+ .publicWord (reg 7) (pub .cache) (pc 7),
+ .loadPrivate (reg 2) (reg 7) (pc 8),
+ .constant (reg 23) 1 (pc 9),
+ .binary .add (reg 7) (reg 7) (reg 23) (pc 10),
+ .loadPrivate (reg 8) (reg 7) (pc 11),
+ .binary .add (reg 7) (reg 7) (reg 23) (pc 12),
+ .loadPrivate (reg 29) (reg 7) (pc 13),
+ .constant (reg 17) 0 next]
+
+private def rows : List Line :=
+ [(7,.literal 8), (21,.binary .mul 7 8),
+ (7,.literal 20), (29,.binary .mul 7 29), (29,.binary .mul 29 8),
+ (7,.binary .add 2 23), (7,.binary .mul 7 2), (8,.literal 2), (7,.binary .div 7 8),
+ (7,.binary .mul 7 29), (8,.binary .mul 2 21), (7,.binary .add 8 7),
+ (13,.binary .add 12 7), (14,.binary .add 13 7), (15,.binary .add 14 7)]
+
+private def arithmeticRegs (reg : Fin 32 ↪ Fin r) : Fin 30 ↪ Fin r :=
+ (Fin.castLEEmb (by decide)).trans reg
+
+private def target (pc : Stage → Fin p) (done : Fin p) (i : Fin (rows.length + 1)) : Fin p :=
+ if h : i.val < 15 then pc (.inr ⟨i.val,h⟩) else done
+
+/-- The leaf, route and public banks can be embedded at any host indices. -/
+def instruction (pc : Stage → Fin p) (reg : Fin 32 ↪ Fin r) (leaf : LeafAddress.Reg ↪ Fin r)
+ (pub : Field → Fin k) (done : Fin p) : Stage → Instr W p r k
+ | .inl i => fetch (pc ∘ Sum.inl) reg leaf pub (pc (.inr 0)) i
+ | .inr i => LeafIncidentGeometry.emit (arithmeticRegs reg) (target pc done i.succ) rows[i]
+
+theorem resize_instruction (pc : Stage → Fin p) (reg : Fin 32 ↪ Fin r)
+ (leaf : LeafAddress.Reg ↪ Fin r) (pub : Field → Fin k) (done : Fin p) (i : Stage) :
+ (instruction (W := 5) pc reg leaf pub done i).resize W =
+ instruction pc reg leaf pub done i := by
+ cases i with
+ | inl i => fin_cases i <;> rfl
+ | inr i => fin_cases i <;> rfl
+
+/-- Every setup instruction is present at its designated machine label. -/
+def Linked (M : Machine W p r k) (pc : Stage → Fin p) (reg : Fin 32 ↪ Fin r)
+ (leaf : LeafAddress.Reg ↪ Fin r) (pub : Field → Fin k) (done : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction pc reg leaf pub done i
+
+/-- Native operands at entry, after the leaf address decoder. -/
+structure Ready (M : Machine W p r k) (leaf : LeafAddress.Reg ↪ Fin r) (pub : Field → Fin k)
+ (R : LeafArena.Regions) (node H w : ℕ) (v : Position D) (c : Config W p r) : Prop where
+ cursor : c.reg (leaf .cursor) = (v.1.val : Word W)
+ site : c.reg (leaf .site) = (v.2.val : Word W)
+ address : c.reg (leaf .node) = (node : Word W)
+ start : M.publicData (pub .start) = (R.arguments.start : Word W)
+ stride : M.publicData (pub .stride) = (R.arguments.stride : Word W)
+ cacheBase : M.publicData (pub .cache) = (R.cacheBase : Word W)
+ dimension : c.privateMem (R.cacheBase : Word W) = (D : Word W)
+ width : c.privateMem ((R.cacheBase+1 : ℕ) : Word W) = (w : Word W)
+ bucket : c.privateMem ((R.cacheBase+2 : ℕ) : Word W) = (H : Word W)
+
+variable {M : Machine W p r k} {pc : Stage → Fin p} {reg : Fin 32 ↪ Fin r}
+ {leaf : LeafAddress.Reg ↪ Fin r} {pub : Field → Fin k} {done : Fin p}
+ {R : LeafArena.Regions} {node : ℕ} {v : Position D}
+
+private structure Fetched (bank : Fin 30 → Word W) (R : LeafArena.Regions) (node H w : ℕ)
+ (v : Position D) : Prop where
+ cursor : bank 0 = (v.1.val : Word W)
+ site : bank 1 = (v.2.val : Word W)
+ dimension : bank 2 = (D : Word W)
+ width : bank 8 = (w : Word W)
+ arena : bank 12 = (R.arguments.base node : Word W)
+ zero : bank 17 = 0
+ one : bank 23 = 1
+ bucket : bank 29 = (H : Word W)
+
+private theorem fetch_run (link : Linked M pc reg leaf pub done) (apart : ∀ j i, leaf j ≠ reg i)
+ (c : Config W p r) (entry : c.pc = pc (.inl 0)) (h : Ready M leaf pub R node H w v c) :
+ ∃ q, Prefix M c (List.replicate 14 .tick) q ∧ q.pc = pc (.inr 0) ∧
+ Fetched (q.reg ∘ arithmeticRegs reg) R node H w v ∧ q.privateMem = c.privateMem ∧
+ q.persistent = c.persistent ∧ ∀ j, (∀ i, j ≠ reg i) → q.reg j = c.reg j := by
+ have step (i : Fin 14) {d : Config W p r} (hi : d.pc = pc (.inl i)) :
+ M.program.step d =
+ (fetch (pc ∘ Sum.inl) reg leaf pub (pc (.inr 0)) i).run M.publicData d := by
+ change (M.code d.pc).run _ _ = _
+ rw [hi,link]; rfl
+ refine ⟨_, .tick (step 0 entry) (.tick (step 1 rfl) (.tick (step 2 rfl) (.tick (step 3 rfl)
+ (.tick (step 4 rfl) (.tick (step 5 rfl) (.tick (step 6 rfl) (.tick (step 7 rfl)
+ (.tick (step 8 rfl) (.tick (step 9 rfl) (.tick (step 10 rfl) (.tick (step 11 rfl)
+ (.tick (step 12 rfl) (.tick (step 13 rfl) (.nil _)))))))))))))), rfl, ?_, rfl, rfl, ?_⟩
+ · have width : c.privateMem ((R.cacheBase : Word W)+1) = (w : Word W) := by
+ simpa only [Nat.cast_add,Nat.cast_one] using h.width
+ have bucket : c.privateMem ((R.cacheBase : Word W)+1+1) = (H : Word W) := by
+ rw [show (R.cacheBase : Word W)+1+1 = ((R.cacheBase+2 : ℕ) : Word W) by push_cast; ring]
+ exact h.bucket
+ constructor <;> simp (config := {decide := true}) [arithmeticRegs, Config.put,
+ reg.injective.eq_iff, apart, BinaryOp.eval, h.cursor, h.site,
+ h.address, h.start, h.stride, h.cacheBase, h.dimension, width, bucket, Arena.base]
+ · intro j hj
+ simp only [Config.put, Function.update_of_ne (hj _)]
+
+open private sequence assign_at assign_frame layers eval_add eval_mul from
+ OAI.Computability.VPVNP.PairSimulationLeafIncidentGeometry
+
+private structure Calculated (bank : Fin 30 → Word W) (R : LeafArena.Regions) (node H w : ℕ)
+ (v : Position D) : Prop where
+ cursor : bank 0 = (v.1.val : Word W)
+ site : bank 1 = (v.2.val : Word W)
+ dimension : bank 2 = (D : Word W)
+ base₀ : bank 12 = portBase R.arguments node D H w (.outgoing false)
+ base₁ : bank 13 = portBase R.arguments node D H w (.outgoing true)
+ base₂ : bank 14 = portBase R.arguments node D H w (.incoming false)
+ base₃ : bank 15 = portBase R.arguments node D H w (.incoming true)
+ zero : bank 17 = 0
+ successor : bank 21 = ((8*w : ℕ) : Word W)
+ one : bank 23 = 1
+ sorting : bank 29 = (blockBits H w : Word W)
+
+private theorem calculated (bank : Fin 30 → Word W) (h : Fetched bank R node H w v) (hw : D < W) :
+ Calculated (rows.foldl (fun b l => Function.update b l.1 (l.2.eval b)) bank) R node H w v := by
+ have tri := layers D hw (by have := v.1.isLt; omega)
+ constructor <;> simp (config := {decide := true}) [rows, LeafIncidentGeometry.Operand.eval,
+ Function.update, eval_add, eval_mul, h.cursor, h.site, h.dimension, h.arena, h.zero,
+ h.one, h.width, h.bucket, tri, portBase, LeafHandler.portBase, LeafArguments.portNumber,
+ ramPayloadWidth, blockBits] <;> ring
+
+/-- Word addresses used by the checker read the four consecutive packet intervals. -/
+theorem resident_of_stored {buf : Buffers D H w} {A : Arena} {c : Config W p r}
+ (stored : LeafIncidentLoad.Stored (LeafHandler.portBase A node (ramPayloadWidth D H w))
+ buf c.privateMem) : RouteCall.Resident c (portBase A node D H w) buf := by
+ intro port i
+ have h := stored port i
+ let start := LeafHandler.portBase A node (ramPayloadWidth D H w) port
+ change c.privateMem ((start + i.val : ℕ) : Word W) = _ at h
+ change c.privateMem ((start : Word W) + _) = _
+ rw [← Nat.cast_add,h]
+ cases buf port i <;> rfl
+
+/-- After a stored DFS packet, the checker reads its independently supplied
+half-wire bits. The DFS stack below the scratch boundary can have arbitrary contents. -/
+theorem resident_cursorPacket {b l a pad endAddr : ℕ} [NeZero (b + l)]
+ (hD : 1 < b + l) (hd : 2 + pad = 2 ^ a) (A : Arena) (addr : Word W)
+ (v : Position (b + l))
+ (z : (LeafArguments.state hD hd H w).network.Half
+ (lanePositions (cursorCoordinateLabels b l) v)) (c : Config W p r)
+ (fit : (LeafHandler.cursorPacket hD hd addr.val v z).Fits A W endAddr)
+ (stored : (LeafHandler.cursorPacket hD hd addr.val v z).Stored A
+ (DFS.scratch endAddr c.privateMem)) :
+ RouteCall.Resident c (portBase A addr.val (b + l) H w) (LeafArguments.buffers hD hd v z) := by
+ apply resident_of_stored
+ intro port i
+ have bits := LeafHandler.physicalStored hD hd A addr _ v z fit stored port i
+ let size := ramPayloadWidth (b + l) H w
+ let offset := LeafHandler.portBase A addr.val size port + i.val
+ have lower : A.base addr.val ≤ offset := by
+ cases port <;> simp only [offset,LeafHandler.portBase] <;> omega
+ have upper : offset < A.base addr.val + 4*size := by
+ have hi : i.val < size := i.isLt
+ cases port with | outgoing side | incoming side =>
+ cases side <;> simp [offset,LeafHandler.portBase,LeafArguments.portNumber] <;> omega
+ have len : (LeafHandler.cursorPacket hD hd addr.val v z).bits.length = 4*size :=
+ LeafArguments.packed_length_four hD hd _ z
+ have small : offset < 2^W := upper.trans_le (len ▸ fit.2.2)
+ have inScratch : endAddr ≤ ((offset : Word W)).val := by
+ change endAddr ≤ offset % 2^W
+ rw [Nat.mod_eq_of_lt small]
+ exact fit.1.trans lower
+ change rawScratch (DFS.scratch endAddr c.privateMem) (offset : Word W) = _ at bits
+ have read := (dite_eq_left inScratch :
+ rawScratch (DFS.scratch endAddr c.privateMem) (offset : Word W) = _)
+ exact read.symm.trans bits
+
+/-- The linked code enters the scheduler with all coordinates, widths and
+private bases initialized and preserves every register outside its routing bank. -/
+theorem run (link : Linked M pc reg leaf pub done) (apart : ∀ j i, leaf j ≠ reg i)
+ (c : Config W p r) (entry : c.pc = pc (.inl 0)) (h : Ready M leaf pub R node H w v c)
+ (hw : D < W) {buf : Buffers D H w}
+ (resident : RouteCall.Resident c (portBase R.arguments node D H w) buf) :
+ ∃ d, Prefix M c (List.replicate ticks .tick) d ∧ d.pc = done ∧
+ RouteSchedule.Inputs reg v buf (portBase R.arguments node D H w) d ∧
+ d.reg (reg 21) = ((8*w : ℕ) : Word W) ∧ d.privateMem = c.privateMem ∧
+ d.persistent = c.persistent ∧ ∀ j, (∀ i, j ≠ reg i) → d.reg j = c.reg j := by
+ obtain ⟨q,pre,hpc,hq,mem,per,frame⟩ := fetch_run link apart c entry h
+ let regs := arithmeticRegs reg
+ have tail := sequence M regs rows (target pc done) (fun i => by
+ have atPC : target pc done i.castSucc = pc (.inr i) := by
+ simp [target,show i.val < 15 from i.isLt]; congr 1
+ rw [atPC]; exact link (.inr i)) q (by simpa [target] using hpc)
+ have last : target pc done (Fin.last rows.length) = done := rfl
+ rw [last] at tail
+ have combined : Prefix M c (List.replicate ticks .tick) _ := pre.append tail
+ refine ⟨_, combined, rfl, ?_⟩
+ · have result := calculated (q.reg ∘ regs) hq hw
+ rw [← assign_at] at result
+ refine ⟨⟨result.cursor, result.site, result.dimension, ?_, ?_, result.zero, result.one,
+ result.sorting, ?_⟩,
+ result.successor,mem,per,?_⟩
+ · intro b; cases b with | false => exact result.base₀ | true => exact result.base₁
+ · intro b; cases b with | false => exact result.base₂ | true => exact result.base₃
+ · intro port i
+ change q.privateMem _ = _
+ rw [mem]; exact resident port i
+ · intro j hj
+ exact (assign_frame regs rows q.reg j (fun l _ => hj _)).trans (frame j hj)
+
+end PairSimulation.RoutePrepare
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteRange.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteRange.lean
new file mode 100644
index 0000000000..3a2b54d2a3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteRange.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PairSimulationRouteLoop
+
+/-!
+# Concatenated fixed-width field ranges in the cursor checker
+
+Successor fields have one common width, as do the steps of any sorting
+phase. At the return from each field the scheduler advances the running
+offset. The final mask expresses the conjunction of all tests in the range.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteRange
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Registers retained by the range, and its unmodified memories. -/
+structure Frame (keep : Fin r → Prop) (c d : Config w p r) : Prop where
+ regs : ∀ a, keep a → d.reg a = c.reg a
+ memory : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+theorem Frame.refl {keep : Fin r → Prop} (c : Config w p r) : Frame keep c c :=
+ ⟨fun _ _ ↦ rfl,rfl,rfl⟩
+
+theorem Frame.trans {keep : Fin r → Prop} {a b c : Config w p r}
+ (f : Frame keep a b) (g : Frame keep b c) : Frame keep a c :=
+ ⟨fun j h ↦ (g.regs j h).trans (f.regs j h), g.memory.trans f.memory,
+ g.persistent.trans f.persistent⟩
+
+theorem Frame.put {keep : Fin r → Prop} {c d : Config w p r} (f : Frame keep c d)
+ (pc : Fin p) (i : Fin r) (x : Word w) (skip : ∀ a, keep a → a ≠ i) :
+ Frame keep c (d.put pc i x) :=
+ ⟨fun a h ↦ (Function.update_of_ne (skip a h) ..).trans (f.regs a h), f.memory, f.persistent⟩
+
+/-- One field's returned mask and untouched registers, before advancing
+the offset and loop index. -/
+structure Field (keep : Fin r → Prop) (index off mask : Fin r) (good : Prop)
+ (c d : Config w p r) : Prop extends Frame keep c d where
+ indexEq : d.reg index = c.reg index
+ offset : d.reg off = c.reg off
+ maskEq : d.reg mask = 0 ↔ c.reg mask = 0 ∧ good
+
+/-- Prefix of the range, after the first i fields have been visited. -/
+structure Partial {n : ℕ} (keep : Fin r → Prop) (off mask : Fin r) (width i : ℕ)
+ (test : Fin n → Prop) (c d : Config w p r) : Prop extends Frame keep c d where
+ offset : d.reg off = c.reg off + ((i * width : ℕ) : Word w)
+ maskEq : d.reg mask = 0 ↔ c.reg mask = 0 ∧ ∀ j : Fin n, j.val < i → test j
+
+/-- A range visit executes the proven native field call at each index and
+counts the actual offset addition and counted-loop instructions. -/
+theorem run_exact {M : Machine w p r k} {pc : Fin 3 → Fin p}
+ {index bound one off widthReg mask : Fin r} {body add done : Fin p}
+ (hl : RouteLoop.Linked M pc index bound one body done)
+ (ha : M.code add = .binary .add off off widthReg (pc 2))
+ (n width : ℕ) (cost : Fin n → ℕ) (hn : n < 2 ^ w) (test : Fin n → Prop)
+ (keep : Fin r → Prop) (hb : keep bound) (h1 : keep one) (hw : keep widthReg)
+ (skip : ∀ a, keep a → a ≠ index ∧ a ≠ off)
+ (hio : index ≠ off) (hmi : mask ≠ index) (hmo : mask ≠ off)
+ (c : Config w p r) (hc : c.pc = pc 0) (hbound : c.reg bound = (n : Word w))
+ (hone : c.reg one = 1) (hwidth : c.reg widthReg = (width : Word w))
+ (call : ∀ i : Fin n, ∀ q : Config w p r, q.pc = body → q.reg index = (i.val : Word w) →
+ Partial keep off mask width i.val test c q → ∃ d,
+ Prefix M q (List.replicate (cost i) .tick) d ∧ d.pc = add ∧
+ Field keep index off mask (test i) q d) :
+ ∃ d, Prefix M c (List.replicate (2 + ∑ i, (cost i + 3)) .tick) d ∧
+ d.pc = done ∧ d.reg index = (n : Word w) ∧
+ Partial keep off mask width n test c d := by
+ let I i d := Partial keep off mask width i test c d
+ have start : I 0 (c.put (pc 1) index 0) := by
+ refine ⟨(Frame.refl c).put _ _ _ (fun a h ↦ (skip a h).1), ?_, ?_⟩
+ · simp [Config.put, Function.update_of_ne hio.symm]
+ · simp [Config.put, Function.update_of_ne hmi]
+ have visit (i : Fin n) (q : Config w p r) (hp : q.pc = body) (hi : q.reg index = (i.val : Word w))
+ (hI : I i.val q) :
+ ∃ d, Prefix M q (List.replicate (cost i + 1) .tick) d ∧ d.pc = pc 2 ∧
+ d.reg index = (i.val : Word w) ∧ d.reg one = 1 ∧
+ I (i.val+1) (d.put (pc 1) index ((i.val+1 : ℕ) : Word w)) := by
+ obtain ⟨mid, pre, hm, f⟩ := call i q hp hi hI
+ let value := mid.reg off + mid.reg widthReg
+ let next := mid.put (pc 2) off value
+ have hs : M.program.step mid = .localStep next := by
+ simp [Machine.program, hm, ha, Instr.run, BinaryOp.eval, value, next]
+ have both := hI.toFrame.trans f.toFrame
+ have g := both.put (pc 2) off value fun a h ↦ (skip a h).2
+ refine ⟨next, ?_, rfl, ?_, (g.regs one h1).trans hone, ?_⟩
+ · rw [List.replicate_add]
+ exact pre.append (.tick hs (.nil _))
+ · change Function.update mid.reg off value index = _
+ rw [Function.update_of_ne hio, f.indexEq, hi]
+ refine ⟨g.put _ _ _ (fun a h ↦ (skip a h).1), ?_, ?_⟩
+ · have hcur := hI.offset
+ change Function.update next.reg index _ off = _
+ rw [Function.update_of_ne hio.symm]
+ simp [next, value, f.offset, hcur, both.regs widthReg hw, hwidth, Nat.add_mul, add_assoc]
+ · change Function.update next.reg index _ mask = 0 ↔ _
+ rw [Function.update_of_ne hmi]
+ change Function.update mid.reg off _ mask = 0 ↔ _
+ rw [Function.update_of_ne hmo, f.maskEq, hI.maskEq]
+ constructor
+ · rintro ⟨⟨hz, hprefix⟩, hlast⟩
+ refine ⟨hz, fun j hj ↦ ?_⟩
+ by_cases he : j = i
+ · simpa [he] using hlast
+ · exact hprefix j (by have hne : j.val ≠ i.val := fun h ↦ he (Fin.ext h); omega)
+ · rintro ⟨hz, hprefix⟩
+ exact ⟨⟨hz, fun j hj ↦ hprefix j (by omega)⟩, hprefix i (by omega)⟩
+ exact RouteLoop.run_exact hl n (fun i ↦ cost i + 1) hn I
+ (fun _ _ h ↦ (h.regs bound hb).trans hbound)
+ (fun _ _ _ h ↦ ⟨⟨h.regs, h.memory, h.persistent⟩, h.offset, h.maskEq⟩)
+ visit c hc start
+
+end PairSimulation.RouteRange
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteSchedule.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteSchedule.lean
new file mode 100644
index 0000000000..ce67365a9b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteSchedule.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.PairSimulationRouteCall
+import OAI.Computability.VPVNP.PairSimulationRouteRange
+
+/-!
+# Control tables for the cursor routing checker
+
+The machine first visits the successor classes in order. Then it visits
+each sorting phase and its steps in triangular order, advancing the same
+bit offset after each field. The program text is independent of all four
+buffer lengths and the number of systems.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteSchedule
+
+open BurstRAM BurstRAM.PrivateRAM CursorRouting CursorNetwork RAMLayout
+open scoped Fin.CommRing
+
+variable {D H w W p r k : ℕ}
+
+/-- Labels of a copy of the fixed three-part field checker. -/
+structure CallLabels (p : ℕ) where
+ /-- Geometry calculation. -/
+ geom : Fin 30 → Fin p
+ /-- Selection of the three addresses. -/
+ addr : Fin 8 → Fin p
+ /-- The field-bit scan. -/
+ field : Fin 15 → Fin p
+
+/-- The outer cursor checker has three counted loops and two copies of a
+field call, which return to the appropriate loop increment. -/
+structure Program (p r : ℕ) where
+ /-- Routing register bank. -/
+ reg : Fin 32 ↪ Fin r
+ /-- Initialization, transition, offset updates and final dispatch. -/
+ pc : Fin 7 → Fin p
+ /-- Successor class counter. -/
+ succ : Fin 3 → Fin p
+ /-- Sorting phase counter. -/
+ phase : Fin 3 → Fin p
+ /-- Sorting step counter. -/
+ step : Fin 3 → Fin p
+ /-- The successor field call. -/
+ sCall : CallLabels p
+ /-- The sorting field call. -/
+ lCall : CallLabels p
+ /-- All four input buffers pass the routing checks. -/
+ yes : Fin p
+ /-- At least one routing check fails. -/
+ no : Fin p
+
+variable (P : Program p r)
+
+/-- Seven scheduler instructions. Register 28 is the current sorting step
+bound, and register 29 supplies the fixed sorting block width. -/
+def Program.instruction : Fin 7 → Instr W p r k :=
+ ![.constant (P.reg 22) 0 (P.pc 1), .constant (P.reg 16) 0 (P.succ 0),
+ .binary .add (P.reg 16) (P.reg 16) (P.reg 21) (P.succ 2),
+ .copy (P.reg 21) (P.reg 29) (P.phase 0),
+ .binary .add (P.reg 28) (P.reg 3) (P.reg 23) (P.step 0),
+ .binary .add (P.reg 16) (P.reg 16) (P.reg 21) (P.step 2),
+ .jumpEq (P.reg 22) (P.reg 17) P.yes P.no]
+
+theorem Program.resize_instruction (i : Fin 7) :
+ (P.instruction (W := 1) (k := k) i).resize W = P.instruction i := by
+ fin_cases i <;> rfl
+
+/-- Every link from a loop into a field call and back is fixed once. -/
+structure Program.Linked (M : Machine W p r k) : Prop where
+ control : ∀ i, M.code (P.pc i) = P.instruction i
+ successors : RouteLoop.Linked M P.succ (P.reg 3) (P.reg 2) (P.reg 23) (P.sCall.geom 0) (P.pc 3)
+ phases : RouteLoop.Linked M P.phase (P.reg 3) (P.reg 2) (P.reg 23) (P.pc 4) (P.pc 6)
+ steps : RouteLoop.Linked M P.step (P.reg 4) (P.reg 28) (P.reg 23) (P.lCall.geom 14) (P.phase 2)
+ successorCall : RouteCall.Linked M P.sCall.geom P.sCall.addr P.sCall.field P.reg (P.pc 2)
+ layerCall : RouteCall.Linked M P.lCall.geom P.lCall.addr P.lCall.field P.reg (P.pc 5)
+
+/-- A one-dimensional field scan may write the index, the offset and the
+field-call scratch registers. -/
+def RangeKeep (reg : Fin 32 ↪ Fin r) (idx : Fin 32) (a : Fin r) : Prop :=
+ RouteCall.Preserved reg a ∧ a ≠ reg idx ∧ a ≠ reg 16
+
+/-- A sorting phase adds the outer index and step bound to the writable registers. -/
+def PhaseKeep (reg : Fin 32 ↪ Fin r) (a : Fin r) : Prop :=
+ RangeKeep reg 4 a ∧ a ≠ reg 3 ∧ a ≠ reg 28
+
+/-- The whole program additionally switches the field width between passes. -/
+def Keep (reg : Fin 32 ↪ Fin r) (a : Fin r) : Prop :=
+ PhaseKeep reg a ∧ a ≠ reg 21
+
+theorem rangeKeep_reg (reg : Fin 32 ↪ Fin r) (idx j : Fin 32) (h : ¬ RouteCall.Scratch j)
+ (hi : j ≠ idx) (ho : j ≠ 16) : RangeKeep reg idx (reg j) :=
+ ⟨RouteCall.preserved_reg reg j h, reg.injective.ne hi, reg.injective.ne ho⟩
+
+theorem keep_reg (reg : Fin 32 ↪ Fin r) (j : Fin 32) (h : ¬ RouteCall.Scratch j)
+ (h₄ : j ≠ 4) (h₁₆ : j ≠ 16) (h₃ : j ≠ 3) (h₂₈ : j ≠ 28) (h₂₁ : j ≠ 21) :
+ Keep reg (reg j) :=
+ ⟨⟨rangeKeep_reg reg _ _ h h₄ h₁₆, reg.injective.ne h₃, reg.injective.ne h₂₈⟩,
+ reg.injective.ne h₂₁⟩
+
+/-- Restrict a register frame to a subset of its preserved registers. -/
+theorem narrowFrame {keep₁ keep₂ : Fin r → Prop} {c d : Config W p r}
+ (f : RouteRange.Frame keep₁ c d) (h : ∀ a, keep₂ a → keep₁ a) : RouteRange.Frame keep₂ c d :=
+ ⟨fun a ha ↦ f.regs a (h a ha), f.memory, f.persistent⟩
+
+theorem keep_successor {a : Fin r} (h : Keep P.reg a) : RangeKeep P.reg 3 a :=
+ ⟨h.1.1.1,h.1.2.1,h.1.1.2.2⟩
+
+/-- Fixed inputs supplied by the leaf expansion. The original four buffers
+occupy private words and may have arbitrary contents. -/
+structure Inputs (reg : Fin 32 ↪ Fin r) (v : Position D) (buf : Buffers D H w)
+ (base : LocalPort → Word W) (c : Config W p r) : Prop where
+ cursor : c.reg (reg 0) = (v.1.val : Word W)
+ site : c.reg (reg 1) = (v.2.val : Word W)
+ dimension : c.reg (reg 2) = (D : Word W)
+ outBase : ∀ b, c.reg (reg (RouteCall.outSlot b)) = base (.outgoing b)
+ inBase : ∀ b, c.reg (reg (RouteCall.inSlot b)) = base (.incoming b)
+ zero : c.reg (reg 17) = 0
+ one : c.reg (reg 23) = 1
+ sortWidth : c.reg (reg 29) = (blockBits H w : Word W)
+ resident : RouteCall.Resident c base buf
+
+theorem Inputs.transfer {reg : Fin 32 ↪ Fin r} {v : Position D} {buf : Buffers D H w}
+ {base : LocalPort → Word W} {c d : Config W p r} (h : Inputs reg v buf base c)
+ (f : RouteRange.Frame (Keep reg) c d) : Inputs reg v buf base d := by
+ refine ⟨?_,?_,?_,?_,?_,?_,?_,?_,?_⟩
+ · exact (f.regs _ (keep_reg reg 0 (by decide) (by decide) (by decide)
+ (by decide) (by decide) (by decide))).trans h.cursor
+ · exact (f.regs _ (keep_reg reg 1 (by decide) (by decide) (by decide)
+ (by decide) (by decide) (by decide))).trans h.site
+ · exact (f.regs _ (keep_reg reg 2 (by decide) (by decide) (by decide)
+ (by decide) (by decide) (by decide))).trans h.dimension
+ · intro b
+ apply Eq.trans (f.regs _ ?_) (h.outBase b)
+ cases b <;> apply keep_reg <;> decide
+ · intro b
+ apply Eq.trans (f.regs _ ?_) (h.inBase b)
+ cases b <;> apply keep_reg <;> decide
+ · exact (f.regs _ (keep_reg reg 17 (by decide) (by decide) (by decide)
+ (by decide) (by decide) (by decide))).trans h.zero
+ · exact (f.regs _ (keep_reg reg 23 (by decide) (by decide) (by decide)
+ (by decide) (by decide) (by decide))).trans h.one
+ · exact (f.regs _ (keep_reg reg 29 (by decide) (by decide) (by decide)
+ (by decide) (by decide) (by decide))).trans h.sortWidth
+ · intro port j
+ rw [f.memory]
+ exact h.resident port j
+
+/-- A sorting step with its phase and zero-based step counter. -/
+def layer (phase : Fin D) (step : Fin (phase.val + 1)) : Layer D :=
+ ⟨phase.val, step.val, phase.isLt, Nat.le_of_lt_succ step.isLt⟩
+
+end PairSimulation.RouteSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteSteps.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteSteps.lean
new file mode 100644
index 0000000000..9a138363f1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteSteps.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.PairSimulationRouteTiming
+
+/-!
+# Checking the sorting fields of one cursor-routing phase
+
+Phase `a` visits its `a + 1` fields in ordinal order. Each iteration checks
+the current block of resident buffer bits and advances the common offset by
+the block width. The loop returns to the outer phase increment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteSchedule
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork RAMLayout
+open scoped Fin.CommRing
+
+variable {D H w W p r k : ℕ} [NeZero D]
+
+/-- Execute the sorting steps of a phase and collect their acceptance tests in the running mask. -/
+theorem steps_exact {P : Program p r} {M : Machine W p r k} (hl : P.Linked M)
+ (v : Position D) (buf : Buffers D H w) (base : LocalPort → Word W) (a : Fin D)
+ (c : Config W p r) (hc : c.pc = P.step 0) (inp : Inputs P.reg v buf base c)
+ (hphase : c.reg (P.reg 3) = (a.val : Word W))
+ (hbound : c.reg (P.reg 28) = ((a.val + 1 : ℕ) : Word W))
+ (hwidth : c.reg (P.reg 21) = (blockBits H w : Word W))
+ (hoff : c.reg (P.reg 16) = ((D * (8 * w) + layerCount a.val * blockBits H w : ℕ) : Word W))
+ (hW : D < W) (hfit : blockBits H w < 2 ^ W) :
+ ∃ d, Prefix M c (List.replicate (rowTicks W v H w a) .tick) d ∧ d.pc = P.phase 2 ∧
+ d.reg (P.reg 4) = ((a.val + 1 : ℕ) : Word W) ∧
+ RouteRange.Partial (RangeKeep P.reg 4) (P.reg 16) (P.reg 22) (blockBits H w) (a.val + 1)
+ (fun j : Fin (a.val + 1) ↦ RouteCall.Good v buf (.inr (layer a j))) c d := by
+ have widthKeep := rangeKeep_reg P.reg 4 21 (by decide) (by decide) (by decide)
+ apply RouteRange.run_exact hl.steps (hl.control 5) (a.val + 1) (blockBits H w)
+ (fun j ↦ RouteCall.ticks W v (.inr (layer a j)) (blockBits H w))
+ ((Nat.succ_le_of_lt a.isLt).trans_lt (hW.trans Nat.lt_two_pow_self))
+ (fun j ↦ RouteCall.Good v buf (.inr (layer a j))) (RangeKeep P.reg 4)
+ (rangeKeep_reg P.reg 4 28 (by decide) (by decide) (by decide))
+ (rangeKeep_reg P.reg 4 23 (by decide) (by decide) (by decide)) widthKeep
+ (fun _ h ↦ h.2) (P.reg.injective.ne (by decide)) (P.reg.injective.ne (by decide))
+ (P.reg.injective.ne (by decide)) c hc hbound inp.one hwidth
+ intro i q body index partialRun
+ have ready := inp.transfer (narrowFrame partialRun.toFrame (fun _ h ↦ h.1.1))
+ have phase := (partialRun.regs _ (rangeKeep_reg P.reg 4 3 (by decide) (by decide)
+ (by decide))).trans hphase
+ have callReady : RouteCall.Ready (H := H) (w := w) P.reg v (.inr (layer a i)) base q := by
+ refine ⟨⟨ready.cursor, ready.site, ready.dimension, phase, ?_⟩, ready.outBase, ready.inBase,
+ ?_, ready.zero, (partialRun.regs _ widthKeep).trans hwidth, ready.one⟩
+ · rintro l h
+ cases h
+ exact index
+ · rw [partialRun.offset, hoff]
+ simp [RouteCall.startOffset, layer, Layer.ordinal, Nat.add_mul, add_assoc]
+ obtain ⟨d, pre, res⟩ :=
+ RouteCall.run hl.layerCall v (.inr (layer a i)) hW hfit q body callReady ready.resident
+ exact ⟨d, pre, res.pc,
+ ⟨⟨fun x hx ↦ res.frame x hx.1, res.memory, res.persistent⟩,
+ res.frame _ (RouteCall.preserved_reg P.reg 4 (by decide)),
+ res.frame _ (RouteCall.preserved_reg P.reg 16 (by decide)), res.mask⟩⟩
+
+theorem steps {P : Program p r} {M : Machine W p r k} (hl : P.Linked M)
+ (v : Position D) (buf : Buffers D H w) (base : LocalPort → Word W) (a : Fin D)
+ (c : Config W p r) (hc : c.pc = P.step 0) (inp : Inputs P.reg v buf base c)
+ (hphase : c.reg (P.reg 3) = (a.val : Word W))
+ (hbound : c.reg (P.reg 28) = ((a.val + 1 : ℕ) : Word W))
+ (hwidth : c.reg (P.reg 21) = (blockBits H w : Word W))
+ (hoff : c.reg (P.reg 16) = ((D * (8 * w) + layerCount a.val * blockBits H w : ℕ) : Word W))
+ (hW : D < W) (hfit : blockBits H w < 2 ^ W) :
+ ∃ t d, t ≤ (13 * blockBits H w + 37) * (a.val + 1) + 2 ∧
+ Prefix M c (List.replicate t .tick) d ∧ d.pc = P.phase 2 ∧
+ d.reg (P.reg 4) = ((a.val + 1 : ℕ) : Word W) ∧
+ RouteRange.Partial (RangeKeep P.reg 4) (P.reg 16) (P.reg 22) (blockBits H w) (a.val + 1)
+ (fun j : Fin (a.val + 1) ↦ RouteCall.Good v buf (.inr (layer a j))) c d := by
+ obtain ⟨d, pre, result⟩ := steps_exact hl v buf base a c hc inp hphase hbound hwidth hoff hW hfit
+ exact ⟨_, d, rowTicks_le W v H w a, pre, result⟩
+
+end PairSimulation.RouteSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteSuccessorWord.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteSuccessorWord.lean
new file mode 100644
index 0000000000..5aa08c8c6d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteSuccessorWord.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.PairSimulationRouteWord
+import OAI.Computability.VPVNP.CursorRouting
+
+/-!
+# Computing the successor mask and the inactive-send flag
+
+A successor class uses the mask of its lowest `j + 1` bits. The zero-cursor
+send is inactive when the site has no nonwrapping successor or its successor
+changes a different set of bits. Native xor and self-division test the two
+conditions on host words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteWord
+
+open BurstRAM PrivateRAM CursorRouting
+open scoped Fin.CommRing
+
+private theorem xor_flag {W a b : ℕ} (ha : a < 2 ^ W) (hb : b < 2 ^ W) :
+ let t := BinaryOp.bitXor.eval (a : Word W) (b : Word W)
+ BinaryOp.div.eval t t = ((decide (a ≠ b)).toNat : Word W) := by
+ dsimp only
+ rw [xor_cast ha hb, div_self (Nat.xor_lt_two_pow ha hb)]
+ by_cases h : a = b <;> simp [h]
+
+/-- The native mask word and rejection flag of a successor system at cursor zero. -/
+theorem successor_values {D W : ℕ} (x : Site D) (j : Fin D) (hw : D < W) :
+ let shl := fun t : Word W => BinaryOp.shiftLeft.eval 1 t
+ let nz := fun t : Word W => BinaryOp.div.eval t t
+ let xor := fun a b : Word W => BinaryOp.bitXor.eval a b
+ let m := shl (j.val : Word W) + shl (j.val : Word W) - 1
+ m = ((systemMask (.inl j)).val : Word W) ∧
+ BinaryOp.bitOr.eval (nz (xor (xor (x.val : Word W) ((x.val : Word W) + 1)) m))
+ (1 - nz (xor (shl (D : Word W) - 1) (x.val : Word W))) =
+ ((decide (¬ (x.val + 1 < 2 ^ D ∧ x.val ^^^ (x.val + 1) = (systemMask (.inl j)).val))).toNat :
+ Word W) := by
+ dsimp only
+ have hp := Nat.pow_lt_pow_right (by decide : 1 < 2) hw
+ have hx : x.val < 2^W := x.isLt.trans hp
+ have hnext : x.val + 1 < 2^W := (Nat.succ_le_of_lt x.isLt).trans_lt hp
+ have hmask : (systemMask (.inl j)).val < 2^W := (systemMask (.inl j)).isLt.trans hp
+ have hlast : 2^D - 1 < 2^W := (Nat.sub_le ..).trans_lt hp
+ have castMask : ((2 ^ j.val : ℕ) : Word W) + ((2 ^ j.val : ℕ) : Word W) - 1 =
+ ((systemMask (.inl j)).val : Word W) := by
+ change _ = ((2 ^ (j.val + 1) - 1 : ℕ) : Word W)
+ rw [Nat.cast_sub (Nat.two_pow_pos _), Nat.pow_succ, Nat.mul_two, Nat.cast_add, Nat.cast_one]
+ have castLast : ((2^D : ℕ) : Word W) - 1 = ((2^D - 1 : ℕ) : Word W) := by
+ rw [Nat.cast_sub (Nat.two_pow_pos _), Nat.cast_one]
+ have castNext : (x.val : Word W) + 1 = ((x.val + 1 : ℕ) : Word W) := by simp
+ rw [shl_one (j.isLt.trans hw), castMask, shl_one hw, castLast, castNext,
+ xor_cast hx hnext, xor_flag (Nat.xor_lt_two_pow hx hnext) hmask, xor_flag hlast hx]
+ refine ⟨rfl, ?_⟩
+ have bound := x.isLt
+ have lastFlag : (1 : Word W) - ((decide (2^D - 1 ≠ x.val)).toNat : Word W) =
+ ((decide (¬ x.val + 1 < 2^D)).toNat : Word W) := by
+ by_cases h : x.val + 1 < 2^D
+ · have hne : 2^D - 1 ≠ x.val := by omega
+ simp [h, hne]
+ · have he : 2^D - 1 = x.val := by omega
+ simp [h, he]
+ rw [lastFlag, or_flags _ _ ((Nat.zero_le D).trans_lt hw)]
+ by_cases h : x.val + 1 < 2^D <;> simp [h]
+
+end PairSimulation.RouteWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteSuccessors.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteSuccessors.lean
new file mode 100644
index 0000000000..f8bacbc743
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteSuccessors.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.PairSimulationRouteTiming
+
+/-!
+# Checking the successor fields in cursor-bit order
+
+The counted range starts at offset zero. For each cursor bit it calls the
+native routing checker on the corresponding successor field and then advances
+the common offset by eight guest words. Its mismatch mask records exactly
+the failed successor checks on the four resident half-wire buffers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteSchedule
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork
+open scoped Fin.CommRing
+
+variable {D H w W p r k : ℕ} [NeZero D]
+
+theorem successors_exact {P : Program p r} {M : Machine W p r k} (hl : P.Linked M)
+ (v : Position D) (buf : Buffers D H w) (base : LocalPort → Word W) (c : Config W p r)
+ (hc : c.pc = P.succ 0) (inp : Inputs P.reg v buf base c)
+ (hwidth : c.reg (P.reg 21) = ((8 * w : ℕ) : Word W))
+ (hoff : c.reg (P.reg 16) = 0) (hW : D < W) (hfit : 8 * w < 2 ^ W) :
+ ∃ d, Prefix M c (List.replicate (succTicks W v H w) .tick) d ∧
+ d.pc = P.pc 3 ∧ d.reg (P.reg 3) = (D : Word W) ∧
+ RouteRange.Partial (RangeKeep P.reg 3) (P.reg 16) (P.reg 22) (8 * w) D
+ (fun i : Fin D ↦ RouteCall.Good v buf (.inl i)) c d := by
+ have widthKeep := rangeKeep_reg P.reg 3 21 (by decide) (by decide) (by decide)
+ apply RouteRange.run_exact hl.successors (hl.control 2) D (8 * w)
+ (fun i ↦ RouteCall.ticks W v (.inl i) (8 * w))
+ (hW.trans Nat.lt_two_pow_self) (fun i ↦ RouteCall.Good v buf (.inl i)) (RangeKeep P.reg 3)
+ (rangeKeep_reg P.reg 3 2 (by decide) (by decide) (by decide))
+ (rangeKeep_reg P.reg 3 23 (by decide) (by decide) (by decide))
+ widthKeep (fun _ h ↦ h.2) (P.reg.injective.ne (by decide)) (P.reg.injective.ne (by decide))
+ (P.reg.injective.ne (by decide)) c hc inp.dimension inp.one hwidth
+ intro i q body index partialRun
+ have ready := inp.transfer (narrowFrame partialRun.toFrame (fun _ h ↦ keep_successor P h))
+ have callReady : RouteCall.Ready (H := H) (w := w) P.reg v (.inl i) base q := by
+ refine ⟨⟨ready.cursor, ready.site, ready.dimension, index, fun _ he ↦ nomatch he⟩,
+ ready.outBase, ready.inBase, ?_, ready.zero, ?_, ready.one⟩
+ · simpa only [RouteCall.startOffset, hoff, zero_add] using partialRun.offset
+ · exact (partialRun.regs _ widthKeep).trans hwidth
+ obtain ⟨d, run, result⟩ := RouteCall.run hl.successorCall v (.inl i) hW hfit q body callReady ready.resident
+ exact ⟨d, run, result.pc,
+ ⟨⟨fun a ha ↦ result.frame a ha.1, result.memory, result.persistent⟩,
+ result.frame _ (RouteCall.preserved_reg P.reg 3 (by decide)),
+ result.frame _ (RouteCall.preserved_reg P.reg 16 (by decide)), result.mask⟩⟩
+
+theorem successors {P : Program p r} {M : Machine W p r k} (hl : P.Linked M)
+ (v : Position D) (buf : Buffers D H w) (base : LocalPort → Word W) (c : Config W p r)
+ (hc : c.pc = P.succ 0) (inp : Inputs P.reg v buf base c)
+ (hwidth : c.reg (P.reg 21) = ((8 * w : ℕ) : Word W))
+ (hoff : c.reg (P.reg 16) = 0) (hW : D < W) (hfit : 8 * w < 2 ^ W) :
+ ∃ t d, t ≤ (13 * (8 * w) + 37) * D + 2 ∧ Prefix M c (List.replicate t .tick) d ∧
+ d.pc = P.pc 3 ∧ d.reg (P.reg 3) = (D : Word W) ∧
+ RouteRange.Partial (RangeKeep P.reg 3) (P.reg 16) (P.reg 22) (8 * w) D
+ (fun i : Fin D ↦ RouteCall.Good v buf (.inl i)) c d := by
+ obtain ⟨d, pre, result⟩ := successors_exact hl v buf base c hc inp hwidth hoff hW hfit
+ exact ⟨_, d, succTicks_le W v H w, pre, result⟩
+
+end PairSimulation.RouteSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteTiming.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteTiming.lean
new file mode 100644
index 0000000000..a15fa8ae9c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteTiming.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.PairSimulationRouteSchedule
+import OAI.Computability.VPVNP.PairSimulationRouteClock
+
+/-!
+# Exact tick counts for the native routing checker
+
+The geometry and field-mode branches depend on the cursor position and
+current system. Each field visits its full width. Adding the fixed loop
+instructions therefore yields a trace length determined by the position
+and dimensions, independently of the resident bits and scratch registers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteSchedule
+
+open BurstRAM CursorRouting CursorNetwork RAMLayout
+
+variable {D : ℕ}
+
+/-- The complete routing clock, including initialization, width switch and dispatch. -/
+def clock (D H w : ℕ) : ℕ :=
+ (13 * (8 * w) + 37) * D + 2 + (((13 * blockBits H w + 37) * D + 5) * D + 2) + 4
+
+theorem clock_le {n e w : ℕ} (budget : ProcessorBudget n D e w) (hn : 2048 ≤ n) :
+ clock D (2 ^ e) w ≤ n ^ 5 := RouteClock.scheduler_le budget hn
+
+/-- A host at least as wide as the fitted processor holds its dimension and
+both native loop bounds. The processor's address envelope bounds the sorting block. -/
+theorem hostFits {n e w W : ℕ} (budget : ProcessorBudget n D e w) (hle : w ≤ W) :
+ D < W ∧ 8*w < 2 ^ W ∧ blockBits (2^e) w < 2 ^ W := by
+ have hH : 0 < 2 ^ e := Nat.two_pow_pos _
+ have cap : 2 ^ D < 2 ^ w :=
+ (Nat.le_mul_of_pos_right _ hH).trans_lt budget.capFits
+ have hd : D < w := by
+ by_contra! h
+ exact (not_le_of_gt cap) (Nat.pow_le_pow_right (by decide) h)
+ let a := 2 ^ (2 + e + D) + w + 32
+ have he : 2 ^ e ≤ a := calc
+ _ ≤ 2 ^ (2 + e + D) := Nat.pow_le_pow_right (by decide) (by omega)
+ _ ≤ a := by dsimp [a]; omega
+ have hw : w ≤ a := (Nat.le_add_left w _).trans (Nat.le_add_right _ 32)
+ have ha : 0 < a := by dsimp [a]; omega
+ have wide : 2 ^ w ≤ 2 ^ W := Nat.pow_le_pow_right (by decide) hle
+ have block : blockBits (2^e) w < 2 ^ W := calc
+ _ = 20 * (2^e * w) := by unfold blockBits; ring
+ _ ≤ 20 * (a * a) := Nat.mul_le_mul_left _ (Nat.mul_le_mul he hw)
+ _ = 20 * a ^ 2 := by rw [pow_two]
+ _ ≤ 64 * a ^ 4 := Nat.mul_le_mul (by decide) (Nat.pow_le_pow_right ha (by decide))
+ _ < 2 ^ w := budget.addresses
+ _ ≤ 2 ^ W := wide
+ have small : 8*w ≤ blockBits (2^e) w := Nat.mul_le_mul_right w (by omega)
+ exact ⟨hd.trans_le hle, small.trans_lt block, block⟩
+
+variable [NeZero D]
+
+/-- Successor calls, offset additions and counted-loop control. -/
+def succTicks (W : ℕ) (v : Position D) (H w : ℕ) : ℕ :=
+ 2 + ∑ i : Fin D, (RouteCall.ticks W v (.inl i) (ramFieldBits H w (.inl i)) + 3)
+
+/-- The step scan in one sorting phase, including its offset additions. -/
+def rowTicks (W : ℕ) (v : Position D) (H w : ℕ) (i : Fin D) : ℕ :=
+ 2 + ∑ j : Fin (i.val + 1), (RouteCall.ticks W v (.inr (layer i j)) (blockBits H w) + 3)
+
+/-- Sorting phases, with the instruction computing each step bound and the outer control. -/
+def phaseTicks (W : ℕ) (v : Position D) (H w : ℕ) : ℕ :=
+ 2 + ∑ i : Fin D, (rowTicks W v H w i + 3)
+
+/-- Exact tick count at the site, from the initial mask clear to the final branch. -/
+def routeTicks (W : ℕ) (v : Position D) (H w : ℕ) : ℕ :=
+ 2 + succTicks W v H w + 1 + phaseTicks W v H w + 1
+
+private theorem sum_le (n bound : ℕ) (f : Fin n → ℕ) (h : ∀ i, f i ≤ bound) :
+ ∑ i, f i ≤ bound * n := calc
+ _ ≤ ∑ _ : Fin n, bound := Finset.sum_le_sum (fun i _ ↦ h i)
+ _ = _ := by simp [Nat.mul_comm]
+
+theorem succTicks_le (W : ℕ) (v : Position D) (H w : ℕ) :
+ succTicks W v H w ≤ (13 * (8*w) + 37)*D + 2 := by
+ unfold succTicks
+ rw [Nat.add_comm 2]
+ apply Nat.add_le_add_right
+ apply sum_le
+ intro i
+ have := RouteCall.ticks_le W v (.inl i) (8*w)
+ change RouteCall.ticks W v (.inl i) (8*w) + 3 ≤ _
+ omega
+
+theorem rowTicks_le (W : ℕ) (v : Position D) (H w : ℕ) (i : Fin D) :
+ rowTicks W v H w i ≤ (13 * blockBits H w + 37) * (i.val + 1) + 2 := by
+ unfold rowTicks
+ rw [Nat.add_comm 2]
+ apply Nat.add_le_add_right
+ apply sum_le
+ intro j
+ have := RouteCall.ticks_le W v (.inr (layer i j)) (blockBits H w)
+ omega
+
+theorem phaseTicks_le (W : ℕ) (v : Position D) (H w : ℕ) :
+ phaseTicks W v H w ≤ ((13 * blockBits H w + 37)*D+5)*D+2 := by
+ unfold phaseTicks
+ rw [Nat.add_comm 2]
+ apply Nat.add_le_add_right
+ apply sum_le
+ intro i
+ have := rowTicks_le W v H w i
+ have := Nat.mul_le_mul_left (13*blockBits H w+37) (show i.val + 1 ≤ D from i.isLt)
+ omega
+
+theorem routeTicks_le (W : ℕ) (v : Position D) (H w : ℕ) :
+ routeTicks W v H w ≤ clock D H w := by
+ have := succTicks_le W v H w
+ have := phaseTicks_le W v H w
+ unfold routeTicks clock
+ omega
+
+end PairSimulation.RouteSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteValidator.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteValidator.lean
new file mode 100644
index 0000000000..3ffc47657a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteValidator.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.PairSimulationRouteSuccessors
+import OAI.Computability.VPVNP.PairSimulationRoutePhases
+import OAI.Computability.VPVNP.PairSimulationRouteTiming
+import OAI.Computability.VPVNP.PairSimulationMapLookup
+
+/-!
+# Executing the native routing checker on a cursor vertex
+
+The scheduler starts by clearing the mask and offset. After the successor
+fields it switches to the sorting-block width. The final jump tests the mask
+accumulated over both passes. All inputs, including inconsistent four-port
+buffers, reach their continuation within the same clock bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteSchedule
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord CursorRouting CursorNetwork RAMLayout
+open scoped Fin.CommRing
+
+variable {D H w W p r k : ℕ}
+
+variable [NeZero D] {P : Program p r} {M : Machine W p r k}
+
+/-- Run the linked scheduler on the resident buffers. It consumes only local ticks,
+preserves both memories, and jumps according to the exact routing predicate. -/
+theorem native_exact (hl : P.Linked M) (v : Position D) (buf : Buffers D H w)
+ (base : LocalPort → Word W) (c : Config W p r) (hc : c.pc = P.pc 0)
+ (inp : Inputs P.reg v buf base c) (hwidth : c.reg (P.reg 21) = ((8 * w : ℕ) : Word W))
+ (hw : D < W) (hsucc : 8 * w < 2 ^ W) (hsort : blockBits H w < 2 ^ W) :
+ ∃ d, Prefix M c (List.replicate (routeTicks W v H w) .tick) d ∧
+ d.pc = (if routeAccept H w v (readBuffer buf) then P.yes else P.no) ∧
+ RouteRange.Frame (Keep P.reg) c d := by
+ have control (i : Fin 7) (q : Config W p r) (hp : q.pc = P.pc i) :
+ M.program.step q = (P.instruction i).run M.publicData q := by
+ change (M.code q.pc).run M.publicData q = _
+ rw [hp, hl.control i]
+ let clear := c.put (P.pc 1) (P.reg 22) 0
+ let start := clear.put (P.succ 0) (P.reg 16) 0
+ have pre : Prefix M c (List.replicate 2 .tick) start :=
+ .tick (control 0 c hc) (.tick (control 1 clear rfl) (.nil _))
+ have f₀ : RouteRange.Frame (Keep P.reg) c start :=
+ ((RouteRange.Frame.refl c).put (P.pc 1) (P.reg 22) 0
+ (fun _ h ↦ h.1.1.1 22 (by decide))).put (P.succ 0) (P.reg 16) 0
+ (fun _ h ↦ h.1.1.2.2)
+ have width : start.reg (P.reg 21) = ((8*w : ℕ) : Word W) := by
+ simp [start, clear, Config.put, hwidth]
+ have off : start.reg (P.reg 16) = 0 := by simp [start]
+ have mask : start.reg (P.reg 22) = 0 := by simp [start, clear, Config.put]
+ obtain ⟨s, succRun, sPC, _, sState⟩ :=
+ successors_exact hl v buf base start rfl (inp.transfer f₀) width off hw hsucc
+ have fs := f₀.trans (narrowFrame sState.toFrame (fun _ h ↦ keep_successor P h))
+ let switch := s.put (P.phase 0) (P.reg 21) (s.reg (P.reg 29))
+ have changeWidth : Prefix M s (List.replicate 1 .tick) switch :=
+ .tick (control 3 s sPC) (.nil _)
+ have switched := fs.put (P.phase 0) (P.reg 21) (s.reg (P.reg 29)) (fun _ h ↦ h.2)
+ have swidth : switch.reg (P.reg 21) = (blockBits H w : Word W) := by
+ simpa [switch] using (inp.transfer fs).sortWidth
+ have soff : switch.reg (P.reg 16) = ((D*(8*w) : ℕ) : Word W) := by
+ simpa [switch, Config.put, off] using sState.offset
+ have smask : switch.reg (P.reg 22) = 0 ↔ ∀ j : Fin D, RouteCall.Good v buf (.inl j) := by
+ change Function.update s.reg (P.reg 21) _ (P.reg 22) = 0 ↔ _
+ rw [Function.update_of_ne (P.reg.injective.ne (by decide)), sState.maskEq, mask]
+ exact ⟨fun h j ↦ h.2 j j.isLt, fun h ↦ ⟨rfl, fun j _ ↦ h j⟩⟩
+ obtain ⟨l, layerRun, lPC, _, lState⟩ :=
+ phases_exact hl v buf base switch rfl (inp.transfer switched) swidth soff hw hsort
+ have fl := switched.trans (narrowFrame lState.toFrame (fun _ h ↦ h.1))
+ have ok : l.reg (P.reg 22) = 0 ↔ routeAccept H w v (readBuffer buf) = true := by
+ rw [lState.maskEq, smask, RouteCall.routeAccept_iff_good]
+ constructor
+ · rintro ⟨h₁,h₂⟩ (j | a)
+ · exact h₁ j
+ · exact h₂ a a.phase_lt
+ · exact fun h ↦ ⟨fun j ↦ h (.inl j), fun a _ ↦ h (.inr a)⟩
+ let final := {l with pc := if routeAccept H w v (readBuffer buf) then P.yes else P.no}
+ have dispatch : Prefix M l (List.replicate 1 .tick) final := by
+ apply Prefix.tick _ (.nil _)
+ rw [control 6 l lPC]
+ change CallAction.localStep {l with pc := if l.reg (P.reg 22) = l.reg (P.reg 17)
+ then P.yes else P.no} = _
+ simp only [(inp.transfer fl).zero, ok, final]
+ refine ⟨final, ?_, rfl, ⟨fl.regs, fl.memory, fl.persistent⟩⟩
+ unfold routeTicks
+ repeat rw [List.replicate_add]
+ exact (((pre.append succRun).append changeWidth).append layerRun).append dispatch
+
+/-- Every resident input reaches its routing continuation within the scheduler clock. -/
+theorem native (hl : P.Linked M) (v : Position D) (buf : Buffers D H w)
+ (base : LocalPort → Word W) (c : Config W p r) (hc : c.pc = P.pc 0)
+ (inp : Inputs P.reg v buf base c) (hwidth : c.reg (P.reg 21) = ((8 * w : ℕ) : Word W))
+ (hw : D < W) (hsucc : 8 * w < 2 ^ W) (hsort : blockBits H w < 2 ^ W) :
+ ∃ t d, t ≤ clock D H w ∧ Prefix M c (List.replicate t .tick) d ∧
+ d.pc = (if routeAccept H w v (readBuffer buf) then P.yes else P.no) ∧
+ RouteRange.Frame (Keep P.reg) c d := by
+ obtain ⟨d, pre, hp, frame⟩ := native_exact hl v buf base c hc inp hwidth hw hsucc hsort
+ exact ⟨_, d, routeTicks_le W v H w, pre, hp, frame⟩
+
+/-- With a rejecting instruction at the failed exit, every failed route rejects
+on every branch tape and external memory, including at budgets shorter than its scan. -/
+theorem native_reject (hl : P.Linked M) (v : Position D) (buf : Buffers D H w)
+ (base : LocalPort → Word W) (c : Config W p r) (hc : c.pc = P.pc 0)
+ (inp : Inputs P.reg v buf base c) (hwidth : c.reg (P.reg 21) = ((8 * w : ℕ) : Word W))
+ (hw : D < W) (hsucc : 8 * w < 2 ^ W) (hsort : blockBits H w < 2 ^ W)
+ (failed : routeAccept H w v (readBuffer buf) = false) (hbad : M.code P.no = .reject)
+ (fuel : ℕ) (mem : Memory W) (bits : List Bool) : execute M.program fuel c mem bits = none := by
+ obtain ⟨_, d, _, pre, hp, _⟩ := native hl v buf base c hc inp hwidth hw hsucc hsort
+ have bad : d.pc = P.no := by simpa [failed] using hp
+ exact MapLookup.reject_after_ticks pre (fun _ h ↦ List.eq_of_mem_replicate h)
+ (bad ▸ hbad) fuel mem bits
+
+end PairSimulation.RouteSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationRouteWord.lean b/lean/OAI/Computability/VPVNP/PairSimulationRouteWord.lean
new file mode 100644
index 0000000000..21263327a2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationRouteWord.lean
@@ -0,0 +1,63 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeFields
+
+/-!
+# Word operations for cursor route geometry
+
+The shift amount is a cursor coordinate below the host word width. The
+mask and lane indices fit in one host word. Under these bounds the native
+instructions compute the natural-number masks and the Boolean side flags.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.RouteWord
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+variable {W i m x y : ℕ}
+
+theorem shl_one (hi : i < W) :
+ BinaryOp.shiftLeft.eval (1 : Word W) (i : Word W) = ((2 ^ i : ℕ) : Word W) := by
+ have hw : 0 < W := (Nat.zero_le i).trans_lt hi
+ simp [BinaryOp.eval, Fin.val_natCast, Nat.mod_eq_of_lt (hi.trans Nat.lt_two_pow_self),
+ Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne'), hi, Nat.shiftLeft_eq]
+
+theorem maskBit (hi : i < W) (hm : m < 2 ^ W) :
+ BinaryOp.bitAnd.eval (BinaryOp.shiftRight.eval (m : Word W) (i : Word W)) 1 =
+ ((m.testBit i).toNat : Word W) := by
+ rw [PrimedInputRAM.Opcodes.readBit_word ((Nat.zero_le i).trans_lt hi), Fin.val_natCast,
+ Fin.val_natCast, Nat.mod_eq_of_lt hm, Nat.mod_eq_of_lt (hi.trans Nat.lt_two_pow_self)]
+ cases m.testBit i <;> rfl
+
+theorem xor_cast (hx : x < 2 ^ W) (hy : y < 2 ^ W) :
+ BinaryOp.bitXor.eval (x : Word W) (y : Word W) = ((x ^^^ y : ℕ) : Word W) := by
+ change Fin.ofNat _ ((x % (2^W)) ^^^ (y % (2^W))) = _
+ rw [Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hy]
+ rfl
+
+theorem div_self (hx : x < 2 ^ W) :
+ BinaryOp.div.eval (x : Word W) (x : Word W) = (if x = 0 then 0 else 1) := by
+ change Fin.ofNat _ ((x % (2^W)) / (x % (2^W))) = _
+ rw [Nat.mod_eq_of_lt hx]
+ by_cases h : x = 0
+ · subst x
+ rfl
+ · rw [ite_eq_right h, Nat.div_self (Nat.pos_of_ne_zero h)]
+ rfl
+
+theorem or_flags (a b : Bool) (hw : 0 < W) :
+ BinaryOp.bitOr.eval (a.toNat : Word W) (b.toNat : Word W) = ((a || b).toNat : Word W) := by
+ cases a <;> cases b <;> simp [BinaryOp.eval, Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')]
+
+theorem sub_cast (h : y ≤ x) :
+ BinaryOp.sub.eval (x : Word W) (y : Word W) = ((x - y : ℕ) : Word W) := by
+ exact (Nat.cast_sub h).symm
+
+end PairSimulation.RouteWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationScanTrace.lean b/lean/OAI/Computability/VPVNP/PairSimulationScanTrace.lean
new file mode 100644
index 0000000000..27192ac7ea
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationScanTrace.lean
@@ -0,0 +1,302 @@
+import OAI.Computability.VPVNP.PairSimulationAssembly
+import OAI.Computability.VPVNP.PairSimulationFinalBits
+
+/-!
+# Native final-arc calls inside the compressed occurrence count
+
+A trace retains the selector bit strings by level, the chronological native
+calls that write the shared final arcs, and one private expansion string
+per final site. The final shared assignment is decoded from the very same
+native calls used in the trace. Distinct traces remain distinguishable
+even when all their parameter exponents agree.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel Compression CompressorRecords BurstRAM BurstRAM.PrivateRAM
+open scoped Classical
+
+/-- Choice strings observed for a compressed occurrence, grouped into level selectors, shared
+final-arc calls and private expansions at the final sites. -/
+structure Phases where
+ /-- The compact term-selection strings along the chosen history branch, ordered from the
+ first pass to the last. -/
+ selectors : List (List Bool)
+ /-- The branch bits of each native call that writes the terminal shared edge payloads, in
+ execution order. -/
+ arcCalls : List (List Bool)
+ /-- The private expansion strings for the terminal site factors, listed in terminal site
+ order. -/
+ vertices : List (List Bool)
+
+/-- Extend a continuation trace by putting the current pass's selector string at the front of
+its selector list. -/
+def Phases.prepend (s : List Bool) (p : Phases) : Phases := ⟨s :: p.selectors, p.arcCalls, p.vertices⟩
+
+private theorem phases_prepend_eq {a b : List Bool} {p q : Phases} (h : Phases.prepend a p = Phases.prepend b q) :
+ a = b ∧ p = q := by
+ cases p
+ cases q
+ simpa [Phases.prepend, and_assoc] using h
+
+/-- The path type of the native final-arc phase and its reconstruction
+of the unique shared payload assignment. -/
+structure ScanPhase (N : Network) where
+ /-- The type of successful paths of the shared final-edge scan on this network. -/
+ Path : Type
+ /-- Bijection decoding a scan path to the shared payload on every edge of the terminal
+ network. -/
+ payload : Path ≃ ((e : N.Edge) → N.Payload e)
+ /-- The chronological list of burst choice strings emitted by a final-edge scan path. This
+ list identifies the path uniquely. -/
+ calls : Path → List (List Bool)
+ calls_injective : Function.Injective calls
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A}
+
+/-- A family of final-edge scans indexed by history leaves. At a branch it supplies a scan
+family for each possible term choice. -/
+def ScanPhases {N : Network} : History A N → Type 1
+ | .stop => ScanPhase N
+ | .branch s tail => (i : s.Choice) → ScanPhases (tail i)
+
+private abbrev Complete {I : Type} (r : ChoiceReader I) := {bits : List Bool // ∃ i, r.read bits = some (i,[])}
+
+/-- An encoding of occurrences by traces, with a bijection to occurrence indices and observable
+phase lists that distinguish the traces. -/
+structure TraceEncoding (I : Type) where
+ /-- The type of traces that encode the given semantic occurrence indices. -/
+ Trace : Type
+ /-- Bijection sending each complete trace to the occurrence it represents. -/
+ decode : Trace ≃ I
+ /-- Extract the observable selector, shared-arc, and private-site strings from an encoded
+ trace. -/
+ phases : Trace → Phases
+ phases_injective : Function.Injective phases
+
+/-- The observable phase lists determine the complete semantic occurrence. -/
+noncomputable def TraceEncoding.emitted {I : Type} (t : TraceEncoding I) :
+ Set.range t.phases ≃ I := (Equiv.ofInjective t.phases t.phases_injective).symm.trans t.decode
+
+private theorem ordered_bytes_injective {I : Type} (o : Order I) (P : I → List Bool → Prop) :
+ Function.Injective (fun xs : (i : I) → {bs // P i bs} => List.ofFn fun i => (xs (o.entries i)).val) := by
+ intro xs ys h
+ funext i
+ obtain ⟨j,rfl⟩ := o.entries.surjective i
+ exact Subtype.ext (congrFun (List.ofFn_inj.mp h) j)
+
+/-- Replace just the final shared choice by its native call path. Every
+descriptor and site reader still uses the selected term and its exact
+map and child arguments. -/
+noncomputable def scanTrace {N : Network} (H : History A N) (K : H.KernelWitnesses κ) (r : Readers H K)
+ (scan : ScanPhases H) (F : Factors A N) (W : ∀ v z, MonomialWitness κ (F v z))
+ (read : ∀ v z, ChoiceReader (W v z).Choice) : TraceEncoding (H.expandedWitness K F W).Choice := by
+ induction H with
+ | @stop N =>
+ let rest := fun z : (e : N.Edge) → N.Payload e => (v : N.Site) → Complete
+ (read v (WireTensor.edgeAssignment N.src N.dst z v))
+ let path := (p : scan.Path) × rest (scan.payload p)
+ let bytes (p : path) : Phases := ⟨[], scan.calls p.1, List.ofFn fun j => (p.2 (r.2.1.entries j)).val⟩
+ refine ⟨path, ((Equiv.sigmaCongrLeft (β := rest) scan.payload).trans
+ (Equiv.sigmaCongrRight (fun z => Equiv.piCongrRight fun v =>
+ (read v (WireTensor.edgeAssignment N.src N.dst z v)).completeEquiv.symm))).trans
+ (History.stopChoice K F W).symm, bytes, ?_⟩
+ rintro ⟨p,u⟩ ⟨q,v⟩ h
+ obtain rfl : p = q := scan.calls_injective (congrArg Phases.arcCalls h)
+ obtain rfl : u = v := ordered_bytes_injective r.2.1 _ (congrArg Phases.vertices h)
+ rfl
+ | @branch N s tail ih =>
+ let cont (i : s.Choice) := ih i (K.2 i) (r.2.2.2.2 i) (scan i) _ _
+ (pushReader (s.term i) (r.2.1 i) r.2.2.1 F W read (K.1 i) (r.2.2.2.1 i))
+ let sel := r.1.completeEquiv.symm
+ let path := (p : Complete r.1) × (cont (sel p)).Trace
+ let bytes (p : path) := Phases.prepend p.1.val ((cont (sel p.1)).phases p.2)
+ refine ⟨path, ((Equiv.sigmaCongrLeft (β := fun i => (cont i).Trace) sel).trans
+ (Equiv.sigmaCongrRight (fun i => (cont i).decode))).trans (History.branchChoice s tail K F W).symm, bytes, ?_⟩
+ rintro ⟨p,u⟩ ⟨q,v⟩ h
+ obtain ⟨hs, ht⟩ := phases_prepend_eq h
+ obtain rfl : p = q := Subtype.ext hs
+ obtain rfl : u = v := (cont (sel p)).phases_injective ht
+ rfl
+
+/-- A property of the chronological selectors and native shared arc calls
+at all leaves of a history. -/
+private def AtTerminals {N : Network} (H : History A N) : (K : H.KernelWitnesses κ) → Readers H K → ScanPhases H →
+ (List (List Bool) → List (List Bool) → Prop) → Prop :=
+ match H with
+ | .stop => fun _ _ scan P => ∀ p : scan.Path, P [] (scan.calls p)
+ | .branch _ tail => fun K r scan P => ∀ i, AtTerminals (tail i) (K.2 i) (r.2.2.2.2 i) (scan i)
+ (fun sel arcs => P (r.1.encode i :: sel) arcs)
+
+private theorem phases_atTerminals {N : Network} (H : History A N) (K : H.KernelWitnesses κ) (r : Readers H K)
+ (scan : ScanPhases H) (F : Factors A N) (W : ∀ v z, MonomialWitness κ (F v z))
+ (read : ∀ v z, ChoiceReader (W v z).Choice) (P : List (List Bool) → List (List Bool) → Prop)
+ (h : AtTerminals H K r scan P) (x : (scanTrace H K r scan F W read).Trace) :
+ let t := (scanTrace H K r scan F W read).phases x
+ P t.selectors t.arcCalls := by
+ induction H generalizing P with
+ | stop => exact h x.1
+ | branch s tail ih =>
+ let i := r.1.completeEquiv.symm x.1
+ have hx := congrArg Subtype.val (r.1.completeEquiv.apply_symm_apply x.1)
+ change r.1.encode i = x.1.val at hx
+ have ht := ih i (K.2 i) (r.2.2.2.2 i) (scan i) _ _
+ (pushReader (s.term i) (r.2.1 i) r.2.2.1 F W read (K.1 i) (r.2.2.2.1 i))
+ (fun sels arcs => P (r.1.encode i :: sels) arcs) (h i) x.2
+ dsimp only at ht
+ rw [hx] at ht
+ exact ht
+
+/-- Individual level strings in chronological order along a descriptor path. -/
+def selectorCodes {a g b n : ℕ} {X : State a g} :
+ (E : StateExecution A b n X) → (W : E.MapWitnesses κ) → ExecutionReaders E W → E.Choices → List (List Bool)
+ | .done _, _, _, _ => []
+ | .more _ tail, W, r, z => r.1.select.encode z.1 :: selectorCodes (tail z.1) (W.2 z.1) (r.2 z.1) z.2
+
+section State
+
+variable {a g w p r k : ℕ} (X : State a g)
+ (M : Machine w p r k) (pc : Fin 10 → Fin p) (reg : Fin 2 ↪ Fin r) (base : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg base done) (he : M.entry = pc 0)
+ (low : ℕ) (pub : M.publicData base = FinalBits.cursor w low 0) (m : Memory w) (extra : ℕ)
+
+private def actualWidth (e : X.network.Edge) : ℕ := X.width ((e.1.1,e.2),e.1.2)
+
+private def scanWidth (i : Fin (edgeOrder X).length) := actualWidth X ((edgeOrder X).entries i)
+
+private theorem scanWidth_sum : ∑ i, scanWidth X i = X.totalWidth := by
+ let e : X.network.Edge ≃ (X.Base × Fin (2 ^ a)) × BitWord g := ⟨
+ fun x => ((x.1.1,x.2),x.1.2), fun y => ((y.1.1,y.2),y.1.2), fun _ => rfl, fun _ => rfl⟩
+ exact Fintype.sum_equiv ((edgeOrder X).entries.trans e) _ _ fun _ => rfl
+
+private def payloadBits (e : X.network.Edge) :
+ X.network.Payload e ≃ (Fin (scanWidth X ((edgeOrder X).entries.symm e)) → Bool) := by
+ rw [scanWidth, Equiv.apply_symm_apply]
+ exact Equiv.refl _
+
+/-- For any linked scan, its successful call sequences are in bijection
+with the terminal edge payloads in the physical base, lane and slot order. -/
+noncomputable def stateScanPhase (fit : low + X.totalWidth < 2 ^ w) : ScanPhase X.network :=
+ let words := FinalBits.payloads (scanWidth X) X.network (edgeOrder X).entries.symm (payloadBits X)
+ let read := FinalBits.scanEquiv hl he low _ (by rwa [scanWidth_sum]) pub m extra
+ ⟨FinalBits.ScanPaths M.program (extra+9) low (∑ i, scanWidth X i) m, read.symm.trans words,
+ Subtype.val, Subtype.val_injective⟩
+
+omit [CommRing A] in
+private def castScans {N Y : Network} (e : N = Y) (H : History A N) (s : ScanPhases H) :
+ ScanPhases (e ▸ H) := by cases e; exact s
+
+/-- Equip each leaf of a state execution with the linked final-bit scan, using that branch's
+final network and its supplied terminal memory. -/
+noncomputable def executionScanPhases {b n : ℕ} (E : StateExecution A b n X)
+ (memory : E.Choices → Memory w) (fit : ∀ z, low + (E.finalState z).totalWidth < 2 ^ w) : ScanPhases E.history := by
+ induction E with
+ | done X => exact stateScanPhase X M pc reg base done hl he low pub (memory ()) extra (fit ())
+ | more p tail ih =>
+ exact fun i => castScans (p.output_eq i).symm _ (ih i (fun z => memory ⟨i,z⟩) (fun z => fit ⟨i,z⟩))
+
+open private transportWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+open private transportReaders from OAI.Computability.VPVNP.PairSimulationAssembly
+
+private theorem cast_atTerminals {N Y : Network} (e : N = Y) (H : History A N) (W : H.KernelWitnesses κ)
+ (r : Readers H W) (scan : ScanPhases H) (P : List (List Bool) → List (List Bool) → Prop)
+ (h : AtTerminals H W r scan P) :
+ AtTerminals (e ▸ H) (transportWitnesses e H W) (transportReaders e H W r) (castScans e H scan) P := by
+ cases e
+ exact h
+
+private theorem scan_atTerminals {b n : ℕ} (E : StateExecution A b n X) (W : E.MapWitnesses κ)
+ (r : ExecutionReaders E W) (memory : E.Choices → Memory w)
+ (fit : ∀ z, low + (E.finalState z).totalWidth < 2 ^ w)
+ (P : List (List Bool) → List (List Bool) → Prop)
+ (hp : ∀ z (path : FinalBits.ScanPaths M.program (extra+9) low (E.finalState z).totalWidth (memory z)),
+ P (selectorCodes E W r z) path.val) :
+ AtTerminals E.history (E.historyWitnesses W) (executionHistoryReaders E W r)
+ (executionScanPhases X M pc reg base done hl he low pub extra E memory fit) P := by
+ induction E generalizing P with
+ | done X =>
+ intro path
+ refine hp () ⟨path.val, ?_⟩
+ change path.val.length = X.totalWidth ∧
+ (runSegment M.program (extra+9) (some (FinalBits.cursor w low X.totalWidth)) (memory ()) path.val).isSome
+ simpa only [scanWidth_sum X] using path.prop
+ | more p tail ih =>
+ exact fun i => cast_atTerminals (p.output_eq i).symm _ _ _ _ _
+ (ih i (W.2 i) (r.2 i) (fun z => memory ⟨i,z⟩) (fun z => fit ⟨i,z⟩)
+ (fun sels arcs => P (r.1.select.encode i :: sels) arcs) (fun z path => hp ⟨i,z⟩ path))
+
+/-- Every observable trace contains the selectors of one actual branch
+and an accepted native shared scan on that same branch's output network
+and post-descriptor memory. -/
+theorem executionTrace_calls {b n : ℕ} (E : StateExecution A b n X) (W : E.MapWitnesses κ)
+ (r : ExecutionReaders E W) (memory : E.Choices → Memory w)
+ (fit : ∀ z, low + (E.finalState z).totalWidth < 2 ^ w) (P : SiteParsers κ X.network) :
+ let encoding := scanTrace E.history (E.historyWitnesses W) (executionHistoryReaders E W r)
+ (executionScanPhases X M pc reg base done hl he low pub extra E memory fit) P.factors P.witnesses P.read
+ ∀ p : Set.range encoding.phases, ∃ z : E.Choices, p.val.selectors = selectorCodes E W r z ∧
+ p.val.arcCalls.length = (E.finalState z).totalWidth ∧
+ (runSegment M.program (extra+9) (some (FinalBits.cursor w low (E.finalState z).totalWidth))
+ (memory z) p.val.arcCalls).isSome := by
+ intro encoding p
+ obtain ⟨t, ht⟩ := p.prop
+ rw [← ht]
+ let ok (sels arcs : List (List Bool)) := ∃ z : E.Choices, sels = selectorCodes E W r z ∧
+ arcs.length = (E.finalState z).totalWidth ∧
+ (runSegment M.program (extra+9) (some (FinalBits.cursor w low (E.finalState z).totalWidth)) (memory z) arcs).isSome
+ exact phases_atTerminals E.history (E.historyWitnesses W) (executionHistoryReaders E W r)
+ (executionScanPhases X M pc reg base done hl he low pub extra E memory fit) P.factors P.witnesses P.read ok
+ (scan_atTerminals X M pc reg base done hl he low pub extra E W r memory fit ok (fun z path => ⟨z,rfl,path.prop⟩)) t
+
+end State
+
+section Cursor
+
+open CursorNetwork CursorRouting
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {D e w p r k' b l : ℕ} [NeZero D]
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ (M : Machine w p r k') (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) (labels : Fin D ≃ Fin b ⊕ Fin l) (hD : 1 < D)
+ (T : ℕ) (hT : T * S.laneBits ≤ l)
+variable {ww pp rr kk : ℕ} (N : Machine ww pp rr kk) (pc : Fin 10 → Fin pp) (reg : Fin 2 ↪ Fin rr)
+ (base : Fin kk) (done : Fin pp) (hl : FinalBits.Linked N pc reg base done) (he : N.entry = pc 0)
+ (low : ℕ) (pub : N.publicData base = FinalBits.cursor ww low 0) (extra : ℕ)
+
+private noncomputable abbrev scanInput (S : BlockSchedule k) (e w : ℕ) :=
+ cursorState labels hD (Nat.add_sub_of_le S.degree_bounds.1) (ramFieldBits (2^e) w : RAMSystem D → ℕ)
+
+variable (memory : (B.execute f hf T hT (scanInput labels hD S e w)).Choices → Memory ww) (fit : ∀ z : (B.execute f hf T hT (scanInput labels hD S e w)).Choices,
+ low + ((B.execute f hf T hT (scanInput labels hD S e w)).finalState z).totalWidth < 2 ^ ww)
+
+/-- A complete compressed occurrence, with its final shared indices
+chosen by the linked machine's actual burst calls. -/
+noncomputable def compressedScanTrace :
+ TraceEncoding (compressedRAMCount B f hf M fuel initial header hw hc labels hD T hT).Choice :=
+ let E := B.execute f hf T hT (scanInput labels hD S e w)
+ let P := cursorSiteParsers M fuel initial header hw hc labels hD (Nat.add_sub_of_le S.degree_bounds.1) f
+ scanTrace E.history (B.executeWitnesses f hf T hT (scanInput labels hD S e w)) (executeReaders B f hf T hT (scanInput labels hD S e w))
+ (executionScanPhases (scanInput labels hD S e w) N pc reg base done hl he low pub extra E memory fit) P.factors P.witnesses P.read
+
+/-- The traced occurrences, with their native shared-arc call streams,
+retain exactly the original capped machine's weighted count. -/
+theorem compressedScanTrace_sum :
+ let W := compressedRAMCount B f hf M fuel initial header hw hc labels hD T hT
+ let paths := compressedScanTrace B f hf M fuel initial header hw hc labels hD T hT N pc reg base done hl he low pub extra memory fit
+ letI := Fintype.ofEquiv W.Choice paths.emitted.symm
+ ∑ p : Set.range paths.phases, Diagonal.labelMonomial f (W.exponents (paths.emitted p)) =
+ (Nat.card (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2^D) header)
+ (withinCaps (2^D) (2^e))) : A) := by
+ intro W paths
+ let := Fintype.ofEquiv W.Choice paths.emitted.symm
+ exact (Fintype.sum_equiv paths.emitted _ _ fun _ => rfl).trans W.evaluates
+
+end Cursor
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationSelectorBounds.lean b/lean/OAI/Computability/VPVNP/PairSimulationSelectorBounds.lean
new file mode 100644
index 0000000000..52b0d678bc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationSelectorBounds.lean
@@ -0,0 +1,316 @@
+import OAI.Computability.VPVNP.PairSimulationAssembly
+
+/-!
+# Binary size of the descriptor scans
+
+At a shrinking level the motifs are a subset of the old actual arcs. At
+a refresh level there is one motif per port block. Each consumes a fixed
+number of checked coordinates whose bit length is logarithmic in the
+largest incoming width. The estimates here sum the concrete selector
+stream and the old site and slot lists along the actual execution branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords NetworkKernel
+open scoped Classical
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {κ : L → R}
+
+/-- Extract the term-selector reader at each pass of an execution, following its selected
+continuation to form the reader for a whole descriptor path. -/
+def outerReaders {a g b n : ℕ} {X : State a g} :
+ (E : StateExecution R b n X) → (W : E.MapWitnesses κ) → ExecutionReaders E W → ChoiceReader.passReaders E
+ | .done _, _, _ => ()
+ | .more _ tail, W, r => ⟨r.1.select, fun i => outerReaders (tail i) (W.2 i) (r.2 i)⟩
+
+/-- Number of old site records and outgoing-slot records scanned once, plus
+the number of binary guesses made by the actual outer-term parser. -/
+def scanUnits {a g b n : ℕ} {X : State a g} :
+ (E : StateExecution R b n X) → (W : E.MapWitnesses κ) → ExecutionReaders E W → E.Choices → ℕ
+ | .done _, _, _, _ => 0
+ | @StateExecution.more _ _ _ _ a _ _ _ X _ tail, W, r, z =>
+ X.positions * (2 ^ a + 1) + (r.1.select.encode z.1).length + scanUnits (tail z.1) (W.2 z.1) (r.2 z.1) z.2
+
+theorem outerBits_le_scanUnits {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (W : E.MapWitnesses κ) (r : ExecutionReaders E W) (z : E.Choices) :
+ ((ChoiceReader.execution E (outerReaders E W r)).encode z).length ≤ scanUnits E W r z := by
+ induction E with
+ | done => exact le_rfl
+ | @more a g b' n' X p tail ih =>
+ change (r.1.select.encode z.1 ++ _).length ≤ X.positions * (2 ^ a + 1) + _ + _
+ rw [List.length_append]
+ exact Nat.add_le_add (Nat.le_add_left _ _) (ih z.1 (W.2 z.1) (r.2 z.1) z.2)
+
+/-- For every term choice, the next state has at most as many positions as the old one. The
+number of old site and slot records plus selector bits is at most `positions * K * (K +
+Nat.clog 2 (maxWireWidth + 1))`. -/
+def PassScanBound {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} {W : p.MapWitnesses κ}
+ (r : PassReaders p W) (K : ℕ) : Prop :=
+ ∀ i, (p.next i).positions ≤ X.positions ∧
+ X.positions * (2 ^ a + 1) + (r.select.encode i).length ≤
+ X.positions * K * (K + Nat.clog 2 (X.maxWireWidth+1))
+
+/-- Require the same per-pass scan constant at every branch of a state execution. -/
+def ScanBound {a g b n : ℕ} {X : State a g} :
+ (E : StateExecution R b n X) → (W : E.MapWitnesses κ) → ExecutionReaders E W → ℕ → Prop
+ | .done _, _, _, _ => True
+ | .more _ tail, W, r, K => PassScanBound r.1 K ∧ ∀ i, ScanBound (tail i) (W.2 i) (r.2 i) K
+
+private theorem scanBound_bind {a g b n b' n' : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z))
+ (W : E.MapWitnesses κ) (V : ∀ z, (f z).MapWitnesses κ)
+ (r : ExecutionReaders E W) (s : ∀ z, ExecutionReaders (f z) (V z)) (K : ℕ)
+ (hr : ScanBound E W r K) (hs : ∀ z, ScanBound (f z) (V z) (s z) K) :
+ ScanBound (E.bind f) _ (bindReaders E f W V r s) K := by
+ induction E with
+ | done => exact hs ()
+ | more _ _ ih => exact ⟨hr.1, fun i => ih i _ (W.2 i) _ (r.2 i) _ (hr.2 i) (fun z => hs ⟨i,z⟩)⟩
+
+variable {a b l d K : ℕ} {μ : ℝ}
+
+/-- A uniform per-pass scan bound for every execution of a procedure, over all admissible lane
+counts and input states. -/
+abbrev ProcedureScanBound {P : Procedure R a b l d μ} {W : P.MapWitnesses κ} (r : ProcedureReaders P W) (K : ℕ) :=
+ ∀ g n h X, ScanBound (P.run g n h X) _ (r g n h X) K
+
+namespace ProcedureScanBound
+
+private theorem id (a K : ℕ) (κ : L → R) : ProcedureScanBound (ProcedureReaders.id a κ) K := by
+ intro g n h X
+ have hn := h.trans (Nat.zero_add g)
+ subst g
+ trivial
+
+private theorem ofPass {A : ℝ} (hd : 0 < d) (hμ : 0 ≤ μ) (hA : 0 ≤ A)
+ (f : ∀ g (X : State a (l + g)), StatePass R X b g)
+ (hc : ∀ g X (i : (f g X).step.Choice), X.positions = d * ((f g X).next i).positions)
+ (he : ∀ g X (i : (f g X).step.Choice),
+ ((f g X).next i).energy ≤ μ * X.energy + A * (X.positions : ℝ) ^ 2)
+ (W : ∀ g X, (f g X).MapWitnesses κ) (r : ∀ g X, PassReaders (f g X) (W g X))
+ (hr : ∀ g X, PassScanBound (r g X) K) :
+ ProcedureScanBound (ProcedureReaders.ofPass hd hμ hA f hc he W r) K := by
+ intro g n h X
+ subst n
+ exact ⟨hr g X, fun _ => trivial⟩
+
+private theorem seq {c l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} {Q : Procedure R b c l' d' ν}
+ {W : P.MapWitnesses κ} {V : Q.MapWitnesses κ} {r : ProcedureReaders P W} {s : ProcedureReaders Q V}
+ (hr : ProcedureScanBound r K) (hs : ProcedureScanBound s K) : ProcedureScanBound (r.seq s) K :=
+ fun g n eqn X =>
+ let E := P.run (l'+g) n (eqn.trans (Nat.add_assoc l l' g)) X
+ scanBound_bind E _ _ _ _ _ K (hr _ _ _ X) (fun z => hs _ _ _ (E.finalState z))
+
+private theorem reindex {a' b' l' d' : ℕ} {μ' : ℝ} {P : Procedure R a b l d μ} {W : P.MapWitnesses κ}
+ {r : ProcedureReaders P W} (hr : ProcedureScanBound r K)
+ {ha : a = a'} {hb : b = b'} {hl : l = l'} {hd : d = d'} {hμ : μ = μ'} :
+ ProcedureScanBound (r.reindex (ha := ha) (hb := hb) (hl := hl) (hd := hd) (hμ := hμ)) K := by
+ subst a' b' l' d' μ'
+ exact hr
+
+end ProcedureScanBound
+
+open private prefixReaders from OAI.Computability.VPVNP.PairSimulationAssembly
+open private prefixWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+
+variable {k : Type*} [Field k] (S : BlockSchedule k)
+
+private theorem prefixScanBound (shrink : S.ShrinkProcedures R) (W : ∀ i, (shrink i).MapWitnesses κ)
+ (r : ∀ i, ProcedureReaders (shrink i) (W i)) (hr : ∀ i, ProcedureScanBound (r i) K) (j : ℕ) (hj : j ≤ S.steps) :
+ ProcedureScanBound (prefixReaders S shrink W r j hj) K := by
+ induction j with
+ | zero =>
+ simp only [prefixReaders, prefixWitnesses, BlockSchedule.shrinkPrefix]
+ exact (ProcedureScanBound.id _ K κ).reindex
+ | succ j ih =>
+ simp only [prefixReaders, prefixWitnesses, BlockSchedule.shrinkPrefix]
+ exact ((ih (Nat.le_of_succ_le hj)).seq (hr ⟨j,hj⟩).reindex).reindex
+
+private theorem assembleScanBound (shrink : S.ShrinkProcedures R) (refresh : S.RefreshProcedure R)
+ (W : ∀ i, (shrink i).MapWitnesses κ) (V : refresh.MapWitnesses κ)
+ (r : ∀ i, ProcedureReaders (shrink i) (W i)) (s : ProcedureReaders refresh V)
+ (h : ∀ i, ProcedureScanBound (r i) K) (h' : ProcedureScanBound s K) :
+ ProcedureScanBound (assembleReaders S shrink refresh W V r s) K := by
+ unfold assembleReaders
+ exact ((prefixScanBound S shrink W r h S.steps le_rfl).reindex.seq h').reindex
+
+private theorem repeatScanBound {P : Procedure R a a l d μ} {W : P.MapWitnesses κ} {r : ProcedureReaders P W}
+ (hr : ProcedureScanBound r K) (g T n : ℕ) (h : n = T*l + g) (X : State a n) :
+ ScanBound (P.repeatExecution g T n h X) _ (repeatReaders r g T n h X) K := by
+ induction T generalizing n with
+ | zero =>
+ have hn : n = g := by simpa using h
+ subst g
+ trivial
+ | succ t ih =>
+ let E := P.run (t*l+g) n (by rw [h, Nat.succ_mul]; omega) X
+ exact scanBound_bind E _ _ _ _ _ K (hr _ _ _ X) (fun z => ih _ rfl (E.finalState z))
+
+omit [CommRing R] in
+private theorem castAllRecordsLe {N Y Z : Network} (h : N = Y) (c : TermChain R N Z) (v : ℕ)
+ (hv : (h ▸ c : TermChain R Y Z).AllRecordsLe v) : c.AllRecordsLe v := by cases h; exact hv
+
+theorem scanUnits_le {a g b n C : ℕ} {X : State a g} (E : StateExecution R b n X) (W : E.MapWitnesses κ)
+ (r : ExecutionReaders E W) (rec : E.Records) (z : E.Choices) (K width : ℕ)
+ (hr : ScanBound E W r K) (hb : E.Bounded C rec) (hw : X.maxWireWidth ≤ width)
+ (hrec : (E.termChain rec z).AllRecordsLe width) :
+ scanUnits E W r z ≤ (E.termChain rec z).length * (X.positions * K * (K + Nat.clog 2 (width+1))) := by
+ induction E with
+ | done => exact Nat.zero_le _
+ | @more a g b' n' X p tail ih =>
+ let i := z.1
+ let Z := (tail i).termChain (rec.2 i) z.2
+ let per := X.positions * K * (K + Nat.clog 2 (width+1))
+ obtain ⟨hpos, hbits⟩ := hr.1 i
+ obtain ⟨fields, maps, htail⟩ := hrec
+ have next : (p.next i).maxWireWidth ≤ width := by
+ refine (hb.1 i).2.2.trans (Finset.sup_le fun v _ => max_le ?_ ?_)
+ · exact Finset.sup_le fun j _ => fields v j
+ · exact Finset.sup_le fun j _ => maps v j
+ have hc := ih i (W.2 i) (r.2 i) (rec.2 i) z.2 (hr.2 i) (hb.2 i) next (castAllRecordsLe (p.output_eq i).symm Z width htail)
+ have hp : X.positions * (2 ^ a + 1) + (r.1.select.encode i).length ≤ per :=
+ hbits.trans (Nat.mul_le_mul_left _ (Nat.add_le_add_left (Nat.clog_mono_right 2 (Nat.succ_le_succ hw)) _))
+ rw [StateExecution.length_more, Nat.succ_mul, Nat.add_comm]
+ exact Nat.add_le_add hp (hc.trans (Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ (Nat.mul_le_mul_right K hpos))))
+
+
+section Concrete
+
+open MotifGrid MotifBlocks MotifConversion MotifSelector ShrinkMotif Refresh DegreeRefresh
+
+private def capBits {J D E : Type} [Fintype J] [Fintype D] [Fintype E]
+ {src dst : D → J} {P : Supply J E} {p : D → ℚ} {q : E → ℚ} {H H' : ℝ}
+ (F : FixedBlock k src dst P (realWidths p) (realWidths q) H H') : ℕ :=
+ (((∑ i, MotifAdmission.weight p i) + 1) * F.scale * F.radius.num.natAbs * MotifAdmission.denominator q).size
+
+variable {S} (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+
+/-- Uniform coefficient for a scan in the fixed block. The width
+constant is determined by the two templates; the multiplicities by
+the degree schedule and the expander. -/
+noncomputable def scanConstant : ℕ :=
+ max (1 + max (capBits B.shrink) (capBits B.refresh))
+ (max (Finset.univ.sup (fun i : Fin S.steps =>
+ let d := 2 ^ S.degreeExponent i.castSucc
+ (d + 1) + d * 8))
+ ((2 ^ S.portExponent + 1) + 2 ^ S.portExponent * 2 ^ S.expanderExponent))
+
+private theorem scan_charge {n slots atoms bits w k log : ℕ}
+ (hcap : w ≤ k + log) (hsize : slots + 1 + atoms ≤ k) (hbits : bits ≤ n * atoms * w) :
+ n * (slots+1) + bits ≤ n * k * (k+log) := by
+ have hpos : 0 < k+log := by omega
+ calc
+ _ ≤ n * (slots+1) * (k+log) + n * atoms * (k+log) :=
+ Nat.add_le_add (Nat.le_mul_of_pos_right _ hpos) (hbits.trans (Nat.mul_le_mul_left _ hcap))
+ _ = n * (slots+1+atoms) * (k+log) := by ring
+ _ ≤ _ := Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ hsize)
+
+private theorem shrinkMotif_count {a g : ℕ} (X : State a (packingLaneBits a g)) :
+ (shrinkMotifOrder X).length ≤ X.positions * (2 ^ a) := by
+ have h := Fintype.card_le_of_injective (fun m : X.packingData.Motif => packingInputEdges X.Base a g m.val)
+ ((packingInputEdges X.Base a g).injective.comp Subtype.val_injective)
+ change Fintype.card X.packingData.Motif ≤ _
+ simpa only [State.positions, Fintype.card_prod, Fintype.card_fin] using h
+
+set_option maxHeartbeats 1500000 in
+theorem shrinkSelector_bound (i : Fin S.steps) {g n : ℕ} (h : n = packingLaneBits (S.degreeExponent i.castSucc) g)
+ (X : State (S.degreeExponent i.castSucc) n) : PassScanBound (shrinkPassReaders B f hf i h X) (scanConstant B) := by
+ subst n
+ intro s
+ let a := S.degreeExponent i.castSucc
+ let demand := X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth
+ let edges := Order.prod ⟨2, finTwoEquiv⟩ (Order.fin 4)
+ let K := scanConstant B
+ have hbase : capBits B.shrink ≤ K :=
+ (le_max_left _ _).trans ((Nat.le_add_left _ _).trans (le_max_left _ _))
+ have hsize : 2^a + 1 + 2^a * 8 ≤ K :=
+ (Finset.le_sup (f := fun j : Fin S.steps => 2 ^ S.degreeExponent j.castSucc + 1 +
+ 2 ^ S.degreeExponent j.castSucc * 8) (Finset.mem_univ i)).trans ((le_max_left _ _).trans (le_max_right _ _))
+ have hc := selectPass_bits_le B.shrink (shrinkMotifOrder X) edges supplyMass_pos demand s
+ have hw := selectorWidth_le B.shrink demand X.maxWireWidth
+ (X.packingData.shrinkDemandWidths_le (State.two_le_packingColors _) (Nat.two_pow_pos _) X.shrinkNumber X.packingWidth
+ (fun _ => X.width_le_maxWireWidth _))
+ refine ⟨?_, scan_charge (hw.trans (Nat.add_le_add_right hbase _)) hsize ?_⟩
+ · have hcpos := B.shrinkPassAt_positions f hf i rfl X s
+ exact (Nat.le_mul_of_pos_left _ (show 0 < packingFactor a by unfold packingFactor; positivity)).trans_eq hcpos.symm
+ · change ((selectPass B.shrink (shrinkMotifOrder X) edges supplyMass_pos demand).encode s).length ≤ _
+ refine hc.trans ?_
+ change (shrinkMotifOrder X).length * (8 * selectorWidth B.shrink demand) ≤ _
+ rw [← Nat.mul_assoc, ← Nat.mul_assoc X.positions (2 ^ a) 8]
+ exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (shrinkMotif_count X))
+
+private theorem refreshMotif_count {a g : ℕ} (X : State a (a+g)) :
+ Fintype.card X.Base * 2 ^ g ≤ X.positions := by
+ have hc : ∀ n, Fintype.card (BitWord n) = 2 ^ n := fun n => (Fintype.card_congr (bitWordFinEquiv n)).trans (Fintype.card_fin _)
+ rw [State.positions, Fintype.card_prod, hc, pow_add]
+ exact Nat.mul_le_mul_left _ (Nat.le_mul_of_pos_left _ (Nat.two_pow_pos _))
+
+set_option maxHeartbeats 1500000 in
+private theorem refreshScanBound : ProcedureScanBound (refreshProcedureReaders B f hf) (scanConstant B) := by
+ apply ProcedureScanBound.ofPass
+ intro g X c
+ let a := S.portExponent
+ let demand := blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X)
+ let motifs := Order.prod ⟨_, X.baseIndex.symm⟩ ⟨_, (bitWordFinEquiv g).symm⟩
+ let edges := (Order.fin (2^a)).prod (Order.fin (2 ^ S.expanderExponent))
+ have hq (e : Fin (2^a) × Fin (2^S.expanderExponent)) : 0 < expanderMass S.baseDegree e := by
+ unfold expanderMass BlockSchedule.baseDegree
+ positivity
+ have hcap : capBits B.refresh ≤ scanConstant B :=
+ (le_max_right _ _).trans ((Nat.le_add_left _ _).trans (le_max_left _ _))
+ have hsize : 2^a+1 + 2^a * 2^S.expanderExponent ≤ scanConstant B :=
+ (le_max_right _ _).trans (le_max_right _ _)
+ have hw := selectorWidth_le B.refresh demand X.maxWireWidth (fun u j => by
+ change internalWidth _ _ u j ≤ _
+ unfold internalWidth
+ split <;> exact X.width_le_maxWireWidth _)
+ refine ⟨(dyadicRefreshNext_positions X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1
+ B.refresh S.port_order S.degree_bounds.2 c).le, scan_charge (hw.trans (Nat.add_le_add_right hcap _)) hsize ?_⟩
+ change ((selectPass B.refresh motifs edges hq demand).encode c).length ≤ _
+ refine (selectPass_bits_le B.refresh motifs edges hq demand c).trans ?_
+ change (Fintype.card X.Base * 2^g) * (_ * _) ≤ _
+ rw [← Nat.mul_assoc]
+ exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (refreshMotif_count X))
+
+private theorem blockScanBound : ProcedureScanBound (blockReaders B f hf) (scanConstant B) :=
+ assembleScanBound S _ _ _ _ _ _ (fun i => ProcedureScanBound.ofPass _ _ _ _ _ _ _ _
+ (fun g X => shrinkSelector_bound B f hf i (packingLaneBits_add _ g) X)) (refreshScanBound B f hf)
+
+/-- Scan size on an actual complete selector path. This includes the old
+site and outgoing arc records at each pass, and all its choice bits. -/
+theorem execute_scanUnits {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T h X).Choices) :
+ let r := repeatReaders (blockReaders B f hf) _ T n (Nat.add_sub_of_le h).symm X
+ scanUnits (B.execute f hf T h X) _ r z ≤ ((S.steps+1)*T) * (X.positions * scanConstant B *
+ (scanConstant B + Nat.clog 2 (B.growthConstant ^ T * (X.maxWireWidth+1) + 1))) := by
+ let eqn := (Nat.add_sub_of_le h).symm
+ let width := B.growthConstant ^ T * (X.maxWireWidth+1)
+ have bound := repeatScanBound (blockScanBound B f hf) _ T n eqn X
+ obtain ⟨hb, hlen⟩ := Procedure.repeat_recordBounds (B.recordBounds f hf) _ T n eqn X
+ obtain ⟨_, _, _, _, hfields, _⟩ := B.branch_bounds f hf T h X z
+ have hpos : 0 < B.growthConstant := (by decide : 0 < 2).trans_le B.growthConstant_ge_two
+ have hw : X.maxWireWidth ≤ width := (Nat.le_succ _).trans (Nat.le_mul_of_pos_left _ (Nat.pow_pos hpos))
+ exact (scanUnits_le _ _ _ _ z (scanConstant B) width bound hb hw hfields).trans (Nat.mul_le_mul_right _ (hlen z))
+
+/-- The descriptor phase reads exactly the admitted sequence of term
+choices of the original repeated execution. -/
+noncomputable def executeOuterReader {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) :
+ ChoiceReader (B.execute f hf T h X).Choices :=
+ ChoiceReader.execution _ (outerReaders _ _ (repeatReaders (blockReaders B f hf) _ T n (Nat.add_sub_of_le h).symm X))
+
+theorem executeOuterReader_bits_le {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute f hf T h X).Choices) :
+ ((executeOuterReader B f hf T h X).encode z).length ≤ ((S.steps+1)*T) * (X.positions * scanConstant B *
+ (scanConstant B + Nat.clog 2 (B.growthConstant ^ T * (X.maxWireWidth+1) + 1))) :=
+ (outerBits_le_scanUnits _ _ _ z).trans (execute_scanUnits B f hf T h X z)
+
+end Concrete
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationSelectorLookupClock.lean b/lean/OAI/Computability/VPVNP/PairSimulationSelectorLookupClock.lean
new file mode 100644
index 0000000000..cd22384ff9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationSelectorLookupClock.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.PairSimulationReadDecode
+
+/-!
+# Exact instruction counts for one selector lookup
+
+The fixed selector table compares a single field per row, stopping at its
+first match. Its clock is determined by the raw selector word and the
+ordered public code table, including on a missing code.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapLookup
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {X : Type*} {w p r k b : ℕ}
+
+/-- Each tested row uses a public load and a comparison. The last
+instruction transfers to the rejecting or matching continuation. -/
+def selectorTicks (code : X ↪ Word b) (tag : Word b) : List X → ℕ
+ | [] => 1
+ | x :: xs => 2 + if code x = tag then 1 else selectorTicks code tag xs
+
+theorem selectorTicks_le (code : X ↪ Word b) (tag : Word b) (xs : List X) :
+ selectorTicks code tag xs ≤ 2 * xs.length + 1 := by
+ induction xs with
+ | nil => simp [selectorTicks]
+ | cons x xs ih =>
+ simp only [selectorTicks, List.length_cons, Nat.mul_succ]
+ split <;> omega
+
+/-- A successful table ordinal uses two instructions for each preceding
+row and two for its own row, followed by the public ordinal load. -/
+theorem selectorTicks_of_mem [DecidableEq X] (code : X ↪ Word b) (x : X) (xs : List X)
+ (member : x ∈ xs) : selectorTicks code (code x) xs = 2 * (xs.idxOf x + 1) + 1 := by
+ induction xs with
+ | nil => simp at member
+ | cons y ys ih =>
+ by_cases eq : y = x
+ · subst y
+ simp [selectorTicks]
+ · have miss := code.injective.ne eq
+ have tail : x ∈ ys := (List.mem_cons.mp member).resolve_left (Ne.symm eq)
+ rw [selectorTicks, ite_eq_right miss, ih tail, List.idxOf_cons_ne ys eq]
+ omega
+
+private theorem eval_selector (M : Machine w p r k) (fits : b ≤ w) (code : X ↪ Word b)
+ (key : X → Fin k) (keys : ∀ x, M.publicData (key x) = widen fits (code x)) (tag : Word b)
+ (xs : List X) :
+ ((table [()] (fun x _ ↦ key x) xs).eval M.publicData (fun _ ↦ widen fits tag)).2 =
+ selectorTicks code tag xs := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih =>
+ by_cases h : code x = tag
+ · simp [table, row, Tree.eval, selectorTicks, keys, h]
+ · have miss := (widen fits).injective.ne (Ne.symm h)
+ simpa only [table, row, Tree.eval, selectorTicks, keys, miss, h, ↓reduceIte,
+ Nat.add_left_cancel_iff] using ih
+
+/-- Run the linked selector lookup for its computed instruction count. -/
+theorem native_selector_exact (fits : b ≤ w) (xs : List X) (code : X ↪ Word b)
+ (key name : X → Fin k) (src tmp out : Fin r) (ht : src ≠ tmp) (tag : Word b)
+ (M : Machine w p r k) (keys : ∀ x, M.publicData (key x) = widen fits (code x))
+ (label : ((table [()] (fun x _ ↦ key x) xs).flow (fun _ ↦ src) tmp out name).Label → Fin p)
+ (stop bad : Fin p) (hl : Flow.Linked M
+ ((table [()] (fun x _ ↦ key x) xs).flow (fun _ ↦ src) tmp out name) label stop bad)
+ (c : Config w p r) (hc : c.pc = label
+ ((table [()] (fun x _ ↦ key x) xs).flow (fun _ ↦ src) tmp out name).entry)
+ (hs : c.reg src = widen fits tag) :
+ ∃ d, Prefix M c (List.replicate (selectorTicks code tag xs) .tick) d ∧
+ (match MotifEntry.decode xs code tag with
+ | none => d.pc = bad
+ | some x => d.pc = stop ∧ d.reg out = M.publicData (name x)) ∧
+ (∀ j, j ≠ tmp → j ≠ out → d.reg j = c.reg j) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ let tree := table [()] (fun x _ ↦ key x) xs
+ obtain ⟨d, pre, exit, rest, mem, pers⟩ := tree.native (fun _ ↦ src) tmp out name
+ (fun _ ↦ ht) M label stop bad hl c hc
+ have value := (table_eval M.publicData (fun _ : Unit ↦ c.reg src) [()] (fun x _ ↦ key x) xs).1
+ have clock := eval_selector M fits code key keys tag xs
+ rw [hs] at pre
+ refine ⟨d, ?_, ?_, rest, mem, pers⟩
+ · exact clock ▸ pre
+ · change (match (tree.eval M.publicData (fun _ ↦ c.reg src)).1 with
+ | none => _ | some _ => _) at exit
+ unfold tree at exit
+ rw [value] at exit
+ simpa [MotifEntry.decode, hs, keys, eq_comm] using exit
+
+end PairSimulation.MapLookup
+
+namespace PairSimulation.ReadDecode
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PrimedInputRAM MotifEntry
+open scoped Fin.CommRing
+
+variable {X : Type*} {w p r k b u payload : ℕ}
+
+/-- A tag is read with exactly six instructions per bit and one final guard,
+then looked up with the clock of its actual word. -/
+theorem native_tag_exact (M : Machine w p r k) (pc : Fin 7 → Fin p)
+ (reg : Fin 6 ↪ Fin r) (out : Fin r) (hcur : reg 1 ≠ out) (xs : List X)
+ (code : X ↪ Word b) (key name : X → Fin k) (fits : b ≤ w)
+ (hkey : ∀ x, M.publicData (key x) = MapLookup.widen fits (code x))
+ (label : (selectorFlow xs key name reg out).Label → Fin p) (stop bad : Fin p)
+ (read : FieldRead.Linked M pc reg (label (selectorFlow xs key name reg out).entry))
+ (lookup : Flow.Linked M (selectorFlow xs key name reg out) label stop bad)
+ (bits : Fin (payload + u * b) → Bool) (base : ℕ) (i : Fin u) (c : Config w p r)
+ (hc : c.pc = pc 0) (hd : base + (payload + u * b) < 2 ^ w) (hzero : c.reg (reg 0) = 0)
+ (hhigh : c.reg (reg 1) = ((base + (payload + b * i.val) + b : ℕ) : Word w))
+ (hlow : c.reg (reg 2) = ((base + (payload + b * i.val) : ℕ) : Word w))
+ (hend : c.reg (reg 3) = ((base + (payload + u * b) : ℕ) : Word w))
+ (hone : c.reg (reg 4) = 1)
+ (hdata : ∀ j : Fin (payload + u * b),
+ c.privateMem ((base + j.val : ℕ) : Word w) = encodeBit w (bits j)) :
+ ∃ d, Prefix M c
+ (List.replicate ((6*b+1) + MapLookup.selectorTicks code (readTag bits i) xs) .tick) d ∧
+ (match decode xs code (readTag bits i) with
+ | none => d.pc = bad
+ | some x => d.pc = stop ∧ d.reg out = M.publicData (name x)) ∧
+ d.reg (reg 1) = ((base + (payload + b * i.val) : ℕ) : Word w) ∧
+ (∀ a, a ≠ reg 0 → a ≠ reg 1 → a ≠ reg 5 → a ≠ out → d.reg a = c.reg a) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ obtain ⟨mid, pre, hm, hv, cur, frame, hmem, hpers⟩ :=
+ FieldRead.native_read read bits base _ b c hc fits (tag_fits base i hd) hd hzero hhigh hlow
+ hend hone hdata
+ rw [meteredField_spec] at pre
+ have htag : mid.reg (reg 0) = MapLookup.widen fits (readTag bits i) := Fin.ext hv
+ obtain ⟨d, scan, exit, rest, mem, pers⟩ := MapLookup.native_selector_exact fits xs code key name
+ (reg 0) (reg 5) out (reg.injective.ne (by decide)) (readTag bits i) M hkey label stop bad
+ lookup mid hm htag
+ rw [List.replicate_add]
+ exact ⟨d, pre.append scan, exit, (rest _ (reg.injective.ne (by decide)) hcur).trans cur,
+ fun a h₀ h₁ h₅ hOut ↦ (rest a h₅ hOut).trans (frame a h₀ h₁ h₅),
+ mem.trans hmem, pers.trans hpers⟩
+
+end PairSimulation.ReadDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationSelectorReindex.lean b/lean/OAI/Computability/VPVNP/PairSimulationSelectorReindex.lean
new file mode 100644
index 0000000000..f730cde4a5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationSelectorReindex.lean
@@ -0,0 +1,339 @@
+import OAI.Computability.VPVNP.CompressorSelectedTerms
+import OAI.Computability.VPVNP.CompressorTermWorkerScan
+import OAI.Computability.VPVNP.PairSimulationScanTrace
+
+/-!
+# Full-word native term tapes and compact semantic selectors
+
+The native ordinal worker guesses each nontrivial coordinate in a machine
+word. The local-history reader uses the cap of its current level. Both
+choices decode to the same admitted profile at the same physical ordinal.
+The resulting equivalence acts only on term selections and preserves each
+selected continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords CompressorRecords.SelectedTerms NetworkKernel BurstRAM BurstRAM.PrivateRAM
+open scoped Classical Fin.CommRing
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {B : S.Templates} {A : Type*} [CommRing A]
+ {f : B.Entry → A} {hf : B.IsSolution f}
+variable {a g b n : ℕ} {X : State a g} {p : StatePass A X b n}
+
+/-- The selected term before reading any bits, in physical motif ordinal order. -/
+structure TermRows (G : Grid k) (m M : ℕ) (C : Type) where
+ /-- The input demand width for each demand edge of each motif, indexed by physical motif
+ ordinal. -/
+ demand : Fin m → G.D → ℕ
+ bounded : ∀ i e, demand i e ≤ M
+ /-- Bijection between a pass term choice and the family of admitted supply profiles for its
+ motifs' demand rows. -/
+ rows : C ≃ TermRecordScan.Choices G.block demand
+
+set_option maxHeartbeats 1500000 in
+/-- Arrange the shrink or refresh motifs in physical ordinal order, with their demand widths
+and the corresponding bijection from pass choices to admitted supply profiles. -/
+noncomputable def termRows (o : PassOrigin B f hf p) :
+ TermRows (grid o) o.motifCount X.maxWireWidth p.step.Choice := by
+ cases o with
+ | shrink i h X =>
+ subst h
+ let ids := shrinkMotifOrder X
+ let d := X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth
+ refine ⟨fun j => d (ids.entries j), fun j e => ?_, (Equiv.piCongrLeft (fun u => ↥(MotifConversion.outerIndices B.shrink (d u))) ids.entries).symm⟩
+ exact X.packingData.shrinkDemandWidths_le (State.two_le_packingColors _) (Nat.two_pow_pos _)
+ X.shrinkNumber X.packingWidth (fun _ => X.width_le_maxWireWidth _) _ e
+ | refresh X =>
+ let ids := (Order.prod ⟨_, X.baseIndex.symm⟩ ⟨_, (bitWordFinEquiv n).symm⟩)
+ let d := Refresh.blockDemandWidths (Refresh.splitSlots X) (bitWordFinEquiv _) (Refresh.splitWidths X)
+ refine ⟨fun j => d (ids.entries j), fun j e => ?_, (Equiv.piCongrLeft (fun u => ↥(MotifConversion.outerIndices B.refresh (d u))) ids.entries).symm⟩
+ change Refresh.internalWidth _ _ _ _ ≤ _
+ unfold Refresh.internalWidth
+ split <;> exact X.width_le_maxWireWidth _
+
+/-- The rows used to decode native tapes are the actual demand and supply
+coordinates stored by the existing selected term batch. -/
+theorem termRows_batch (o : PassOrigin B f hf p) (c : p.step.Choice) :
+ (termRows o).demand = (batch o c).demand ∧ ∀ j, ((termRows o).rows c j).val = ((batch o c).choice j).val := by
+ cases o with
+ | shrink i h X => subst h; exact ⟨rfl,fun _ => rfl⟩
+ | refresh X => exact ⟨rfl,fun _ => rfl⟩
+
+/-- The grid-dependent additive word-width constant in the native term scan's bound, before the
+logarithmic contribution from the maximum demand width. -/
+noncomputable def workerFit (G : Grid k) := (TermWorker.scan_native G.block G.demandOrder.entries
+ G.supplyOrder.entries G.pPos G.qPos).choose
+
+/-- Public addressing, input rows, and the integer and instruction bounds
+for the fixed ordinal worker on one actual pass. -/
+structure WorkerInput (o : PassOrigin B f hf p) (w : ℕ) where
+ /-- Addresses and separation bounds for the demand and output term rows of every motif in
+ this pass. -/
+ layout : TermRecordScan.Layout o.motifCount (grid o).d (grid o).e w
+ /-- The worker's four address words in order, giving the demand base, demand stride, term
+ base, and term stride. -/
+ addr : Fin 4 → Word w
+ addresses : TermWorker.Addresses layout addr
+ /-- The initial worker memory containing the pass's demand widths at their assigned
+ addresses. -/
+ memory : Memory w
+ inputs : TermRecordScan.Inputs (grid o).demandOrder.entries layout (termRows o).demand memory
+ width : workerFit (grid o) + 4 * Nat.clog 2 (X.maxWireWidth+1) ≤ w
+ /-- Instruction allowance for each native motif call, large enough for the worker at this
+ word width and maximum wire width. -/
+ fuel : ℕ
+ clock : TermWorker.budget (grid o).block (grid o).d (grid o).e w X.maxWireWidth ≤ fuel
+
+variable {o : PassOrigin B f hf p} {w : ℕ}
+
+/-- Run one term-worker call per motif in ordinal order, starting with cursor zero and the
+supplied memory. Successful execution returns the reports for all calls. -/
+noncomputable def WorkerInput.run (I : WorkerInput o w) (tapes : Fin o.motifCount → List Bool) :=
+ let G := grid o
+ runSegment (TermWorker.program G.block G.demandOrder.entries G.supplyOrder.entries I.addr)
+ I.fuel (some 0) I.memory (List.ofFn tapes)
+
+/-- Families of per-motif burst tapes for which the native term-worker scan succeeds on this
+input. -/
+abbrev WorkerInput.Accepted (I : WorkerInput o w) := {tapes : Fin o.motifCount → List Bool // (I.run tapes).isSome}
+
+/-- Encode the selected supply profile at one physical motif ordinal as its native burst tape,
+in the grid's supply order and at the worker's coordinate width. -/
+noncomputable def workerTapes (o : PassOrigin B f hf p) (w : ℕ) (v : p.step.Choice) (j : Fin o.motifCount) :=
+ let G := grid o
+ TermRecordScan.tape G.block G.supplyOrder.entries ((termRows o).demand j) w (((termRows o).rows v j).val)
+
+/-- One accepting full-width stream family for every actual term, with
+the payload words in their prescribed strided rows. -/
+noncomputable def WorkerInput.termEquiv (I : WorkerInput o w) : p.step.Choice ≃ I.Accepted := by
+ let G := grid o
+ let D := termRows o
+ have h := (TermWorker.scan_native G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos).choose_spec
+ o.motifCount X.maxWireWidth w I.width I.layout I.addr I.addresses D.demand D.bounded I.memory I.inputs I.fuel I.clock
+ have sound := h.1
+ have total := h.2
+ let encode (v : p.step.Choice) : I.Accepted := ⟨workerTapes o w v, by
+ obtain ⟨rs,hr,_⟩ := total (D.rows v)
+ exact Option.isSome_iff_exists.mpr ⟨rs,hr⟩⟩
+ apply Equiv.ofBijective encode
+ constructor
+ · intro v u heq
+ have eq := congrArg Subtype.val heq
+ obtain ⟨v', hv', hu⟩ := (sound _).mp (encode v).prop
+ apply D.rows.injective
+ exact (hu (D.rows v) rfl).trans (hu (D.rows u) eq).symm
+ · intro tapes
+ obtain ⟨v,hv,_⟩ := (sound tapes.val).mp tapes.prop
+ refine ⟨D.rows.symm v, Subtype.ext ?_⟩
+ change (fun j => TermRecordScan.tape G.block G.supplyOrder.entries (D.demand j) w ((D.rows (D.rows.symm v) j).val)) = tapes.val
+ rw [Equiv.apply_symm_apply]
+ exact hv.symm
+
+theorem WorkerInput.termEquiv_tapes (I : WorkerInput o w) (v : p.step.Choice) :
+ (I.termEquiv v).val = workerTapes o w v := rfl
+
+/-- Change the physical bit widths through their common admitted term.
+The original decoder of a semantic stream and the native decoder of
+its image return the identical branch index. -/
+noncomputable def WorkerInput.recode (I : WorkerInput o w) (C : ChoiceReader p.step.Choice) :
+ {bs : List Bool // ∃ v, C.read bs = some (v,[])} ≃ I.Accepted :=
+ C.completeEquiv.symm.trans I.termEquiv
+
+theorem WorkerInput.recode_term (I : WorkerInput o w) (C : ChoiceReader p.step.Choice)
+ (bs : {bs : List Bool // ∃ v, C.read bs = some (v,[])}) :
+ I.termEquiv.symm (I.recode C bs) = C.completeEquiv.symm bs := I.termEquiv.symm_apply_apply _
+
+/-- The concrete native pass updates the physical term rows and returns
+exactly the re-encoded choice tapes, one burst per motif ordinal. -/
+theorem WorkerInput.selected_run (I : WorkerInput o w) (v : p.step.Choice) :
+ let G := grid o
+ ∃ rs, I.run (I.termEquiv v).val = some rs ∧
+ (∀ j, TermRecordScan.Fields G.block G.supplyOrder.entries G.pPos ((batch o v).demand j)
+ ((batch o v).choice j).val (I.layout.base j) (after I.memory (eventLog rs))) ∧
+ branchPaths rs = List.ofFn (workerTapes o w v) := by
+ let G := grid o
+ let D := termRows o
+ have h := (TermWorker.scan_native G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos).choose_spec
+ o.motifCount X.maxWireWidth w I.width I.layout I.addr I.addresses D.demand D.bounded I.memory I.inputs I.fuel I.clock
+ obtain ⟨rs,hr,hfield,_,_,_,hbits,_⟩ := h.2 (D.rows v)
+ exact ⟨rs,hr,fun j => by simpa only [← (termRows_batch o v).1, ← (termRows_batch o v).2 j] using hfield j,hbits⟩
+
+
+section Execution
+
+/-- Worker inputs for every pass reachable in an execution, including the input for each
+possible continuation after the current term choice. -/
+def WorkerInputs {a g b n : ℕ} {X : State a g} :
+ (E : StateExecution A b n X) → PassOrigins B f hf E → ℕ → Type
+ | .done _, _, _ => Unit
+ | .more _ tail, origin, w => WorkerInput origin.1 w × (∀ i, WorkerInputs (tail i) (origin.2 i) w)
+
+/-- One native burst tape per motif, grouped by compression level. -/
+noncomputable def ordinalTapes {a g b n : ℕ} {X : State a g} (E : StateExecution A b n X) :
+ (origin : PassOrigins B f hf E) → WorkerInputs E origin w → E.Choices → List (List (List Bool)) :=
+ match E with
+ | .done _ => fun _ _ _ => []
+ | .more _ tail => fun origin inputs z =>
+ List.ofFn ((inputs.1.termEquiv z.1).val) :: ordinalTapes (tail z.1) (origin.2 z.1) (inputs.2 z.1) z.2
+
+theorem ordinalTapes_injective {a g b n : ℕ} {X : State a g} (E : StateExecution A b n X)
+ (origin : PassOrigins B f hf E) (inputs : WorkerInputs E origin w) :
+ Function.Injective (ordinalTapes E origin inputs) := by
+ induction E with
+ | done => exact fun (i j : Unit) _ => Subsingleton.elim i j
+ | more _ _ ih =>
+ rintro ⟨i,u⟩ ⟨j,v⟩ h
+ obtain ⟨hs, ht⟩ := List.cons.inj h
+ obtain rfl : i = j := inputs.1.termEquiv.injective (Subtype.ext (List.ofFn_inj.mp hs))
+ exact congrArg (Sigma.mk i) (ih i (origin.2 i) (inputs.2 i) ht)
+
+theorem selectorCodes_injective {a g b n : ℕ} {X : State a g} (E : StateExecution A b n X)
+ (W : E.MapWitnesses f) (r : ExecutionReaders E W) : Function.Injective (selectorCodes E W r) := by
+ induction E with
+ | done => exact fun (i j : Unit) _ => Subsingleton.elim i j
+ | more _ _ ih =>
+ rintro ⟨i,u⟩ ⟨j,v⟩ h
+ obtain ⟨hs,ht⟩ := List.cons.inj h
+ obtain rfl : i = j := r.1.select.completeEquiv.injective (Subtype.ext hs)
+ exact congrArg (Sigma.mk i) (ih i (W.2 i) (r.2 i) ht)
+
+/-- Observable trace using one native term-worker tape per motif per pass, together with the
+final shared-arc calls and private site expansions. -/
+structure OrdinalPhases where
+ /-- Term-selection burst tapes grouped by compression level and ordered by motif ordinal
+ within each level. -/
+ termCalls : List (List (List Bool))
+ /-- The final shared-edge burst strings belonging to the occurrence selected by the term
+ tapes. -/
+ arcCalls : List (List Bool)
+ /-- The private expansion strings of the terminal sites for this occurrence, in scan order. -/
+ vertices : List (List Bool)
+
+/-- The native emission has one term burst per motif and retains the arc
+and vertex bursts of the same monomial occurrence. -/
+structure SelectorReindex {C : Type} (enc : TraceEncoding C) where
+ /-- Assign distinct ordinal-phase traces to the observable phase lists in the original trace
+ encoding. -/
+ emit : Set.range enc.phases → OrdinalPhases
+ injective : Function.Injective emit
+
+/-- Recover the semantic occurrence from an emitted ordinal trace by inverting the emission and
+decoding the original phase lists. -/
+noncomputable def SelectorReindex.decode {C : Type} {enc : TraceEncoding C} (r : SelectorReindex enc) :
+ Set.range r.emit ≃ C := (Equiv.ofInjective r.emit r.injective).symm.trans enc.emitted
+
+theorem SelectorReindex.decode_emit {C : Type} {enc : TraceEncoding C} (r : SelectorReindex enc) (x : Set.range enc.phases) :
+ r.decode ⟨r.emit x, x, rfl⟩ = enc.emitted x := by
+ simp only [decode, Equiv.trans_apply, Equiv.ofInjective_symm_apply]
+
+private noncomputable def reindexPhases {a g b n : ℕ} {X : State a g} (E : StateExecution A b n X)
+ (W : E.MapWitnesses f) (r : ExecutionReaders E W) (origin : PassOrigins B f hf E)
+ (inputs : WorkerInputs E origin w) {C : Type} (enc : TraceEncoding C)
+ (branch : Set.range enc.phases → E.Choices)
+ (hbranch : ∀ q : Set.range enc.phases, q.val.selectors = selectorCodes E W r (branch q)) : SelectorReindex enc where
+ emit q := ⟨ordinalTapes E origin inputs (branch q), q.val.arcCalls, q.val.vertices⟩
+ injective := by
+ intro x y h
+ have hb := ordinalTapes_injective E origin inputs (congrArg OrdinalPhases.termCalls h)
+ apply Subtype.ext
+ have hs := (hbranch x).trans ((congrArg (selectorCodes E W r) hb).trans (hbranch y).symm)
+ have ha := congrArg OrdinalPhases.arcCalls h
+ have hv := congrArg OrdinalPhases.vertices h
+ cases x with | mk x hx =>
+ cases y with | mk y hy =>
+ cases x; cases y; exact Phases.mk.injEq .. |>.mpr ⟨hs, ha, hv⟩
+
+variable {a g b n ww pp rr kk : ℕ} (X : State a g)
+ (M : Machine ww pp rr kk) (pc : Fin 10 → Fin pp) (reg : Fin 2 ↪ Fin rr) (base : Fin kk) (done : Fin pp)
+ (hl : FinalBits.Linked M pc reg base done) (he : M.entry = pc 0) (low : ℕ)
+ (pub : M.publicData base = FinalBits.cursor ww low 0) (extra : ℕ)
+
+/-- Re-encode every compact level selector by the actual ordinal worker
+of that level. The chosen continuation, terminal memory and vertex paths
+all refer to the decoded semantic branch. -/
+noncomputable def executionReindex (E : StateExecution A b n X) (W : E.MapWitnesses f) (r : ExecutionReaders E W)
+ (origin : PassOrigins B f hf E) (inputs : WorkerInputs E origin w) (P : SiteParsers f X.network)
+ (memory : E.Choices → Memory ww) (fit : ∀ z, low + (E.finalState z).totalWidth < 2 ^ ww) :
+ let enc := scanTrace E.history (E.historyWitnesses W) (executionHistoryReaders E W r)
+ (executionScanPhases X M pc reg base done hl he low pub extra E memory fit) P.factors P.witnesses P.read
+ SelectorReindex enc := by
+ intro enc
+ let reaches := executionTrace_calls X M pc reg base done hl he low pub extra E W r memory fit P
+ exact reindexPhases E W r origin inputs enc (fun q => (reaches q).choose) (fun q => (reaches q).choose_spec.1)
+
+theorem executionReindex_emit (E : StateExecution A b n X) (W : E.MapWitnesses f) (r : ExecutionReaders E W)
+ (origin : PassOrigins B f hf E) (inputs : WorkerInputs E origin w) (P : SiteParsers f X.network)
+ (memory : E.Choices → Memory ww) (fit : ∀ z, low + (E.finalState z).totalWidth < 2 ^ ww) :
+ let R := executionReindex X M pc reg base done hl he low pub extra E W r origin inputs P memory fit
+ ∀ q z, q.val.selectors = selectorCodes E W r z →
+ R.emit q = ⟨ordinalTapes E origin inputs z, q.val.arcCalls, q.val.vertices⟩ := by
+ intro R q z hz
+ let reaches := executionTrace_calls X M pc reg base done hl he low pub extra E W r memory fit P q
+ have heq := selectorCodes_injective E W r (reaches.choose_spec.1.symm.trans hz)
+ change OrdinalPhases.mk (ordinalTapes E origin inputs reaches.choose) q.val.arcCalls q.val.vertices = _
+ rw [heq]
+
+end Execution
+
+section Cursor
+
+open CursorNetwork CursorRouting
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ {D e w p r k' b l : ℕ} [NeZero D] (M : Machine w p r k') (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) (labels : Fin D ≃ Fin b ⊕ Fin l) (hD : 1 < D)
+ (T : ℕ) (hT : T * S.laneBits ≤ l)
+ {ww pp rr kk : ℕ} (N : Machine ww pp rr kk) (pc : Fin 10 → Fin pp) (reg : Fin 2 ↪ Fin rr)
+ (base : Fin kk) (done : Fin pp) (hl : FinalBits.Linked N pc reg base done) (he : N.entry = pc 0)
+ (low : ℕ) (pub : N.publicData base = FinalBits.cursor ww low 0) (extra : ℕ)
+ (memory : (B.execute f hf T hT (scanInput labels hD S e w)).Choices → Memory ww)
+ (fit : ∀ z : (B.execute f hf T hT (scanInput labels hD S e w)).Choices,
+ low + ((B.execute f hf T hT (scanInput labels hD S e w)).finalState z).totalWidth < 2 ^ ww)
+ (inputs : WorkerInputs (B.execute f hf T hT (scanInput labels hD S e w))
+ (executeOrigins B f hf T hT (scanInput labels hD S e w)) ww)
+
+/-- Re-encode the level selectors of a compressed RAM trace as the actual per-motif worker
+tapes along its selected execution branch. -/
+noncomputable def compressedReindex :
+ SelectorReindex (compressedScanTrace B f hf M fuel initial header hw hc labels hD T hT N pc reg base done hl he low pub extra memory fit) :=
+ let X := scanInput labels hD S e w
+ let E := B.execute f hf T hT X
+ let P := cursorSiteParsers M fuel initial header hw hc labels hD (Nat.add_sub_of_le S.degree_bounds.1) f
+ executionReindex X N pc reg base done hl he low pub extra E _
+ (repeatReaders (blockReaders B f hf) _ T l (Nat.add_sub_of_le hT).symm X)
+ (executeOrigins B f hf T hT X) inputs P memory fit
+
+/-- The coordinate expansion in the machine-word tapes preserves the full
+parameter exponent vector of every path. -/
+theorem compressedReindex_exponents :
+ let W := compressedRAMCount B f hf M fuel initial header hw hc labels hD T hT
+ let enc := compressedScanTrace B f hf M fuel initial header hw hc labels hD T hT N pc reg base done hl he low pub extra memory fit
+ let R := compressedReindex B f hf M fuel initial header hw hc labels hD T hT N pc reg base done hl he low pub extra memory fit inputs
+ ∀ q : Set.range enc.phases, W.exponents (R.decode ⟨R.emit q, q, rfl⟩) = W.exponents (enc.emitted q) := by
+ intro W enc R q
+ exact congrArg W.exponents (R.decode_emit q)
+
+/-- Weighted count with the actual per-motif native selector tapes. -/
+theorem compressedReindex_sum :
+ let W := compressedRAMCount B f hf M fuel initial header hw hc labels hD T hT
+ let R := compressedReindex B f hf M fuel initial header hw hc labels hD T hT N pc reg base done hl he low pub extra memory fit inputs
+ letI := Fintype.ofEquiv W.Choice R.decode.symm
+ ∑ q : Set.range R.emit, Diagonal.labelMonomial f (W.exponents (R.decode q)) =
+ (Nat.card (ActualPaths M.program fuel initial (RAMMemory.initialMemory (2^D) header)
+ (withinCaps (2^D) (2^e))) : A) := by
+ intro W R
+ let := Fintype.ofEquiv W.Choice R.decode.symm
+ exact (Fintype.sum_equiv R.decode _ _ fun _ => rfl).trans W.evaluates
+
+end Cursor
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationSelectorRow.lean b/lean/OAI/Computability/VPVNP/PairSimulationSelectorRow.lean
new file mode 100644
index 0000000000..84a7e53b7a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationSelectorRow.lean
@@ -0,0 +1,174 @@
+import OAI.Computability.VPVNP.PairSimulationBranchDecoder
+import OAI.Computability.VPVNP.CompressorOnlineTraceInverse
+import OAI.Computability.VPVNP.CompressorOnlineOrdinalInversion
+import OAI.Computability.VPVNP.CompressorTermWorkerFootprint
+
+/-! # Inverting the term selector of a valid physical online row
+
+Each successful burst advances the term worker by one ordinal, including
+bursts recovered from an arbitrary accepting path. The directory guard
+therefore forces the exact motif count. The admitted term and its entire
+list of burst choices are then recovered from the actual source execution.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords CompressorRecords.SelectedTerms NetworkKernel BurstRAM
+open CompressorRecords.Schedule CompressorRecords.Schedule.Online
+open scoped Fin.CommRing
+open private exact_length from OAI.Computability.VPVNP.CompressorOnlineOrdinalInversion
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {B : S.Templates}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w : ℕ} {X : State a g} {pass : StatePass A X b n} {o : PassOrigin B f hf pass}
+
+/-- Bundle the control type with its physical machine table, so equality
+of installed tables can be used even when the catalog indexes differ. -/
+abbrev ProgramTable (w : ℕ) := (Q : Type) × BurstRAM.Program w Q
+
+/-- The term-worker program paired with its control type, instantiated from the pass grid, the
+demand and supply orders, and the input's four address words. -/
+noncomputable def WorkerInput.table (I : WorkerInput o w) : ProgramTable w :=
+ ⟨_,TermWorker.program (grid o).block (grid o).demandOrder.entries (grid o).supplyOrder.entries I.addr⟩
+
+variable {d initial phases : ℕ} {C : Catalog d} {plan : Config C initial phases} {ports : Ports w}
+
+/-- The program and control type installed for a directory row, obtained by instantiating its
+catalog worker with the public words read from that row's input. -/
+def sourceTable (C : Catalog d) (ports : Ports w) (r : Directory.Row d w) : ProgramTable w :=
+ ⟨_, ((C r.worker).table.instantiate w (Directory.words C ports r.worker r.input)).program⟩
+
+private theorem same_table {P T : Schedule.Pass} {w : ℕ} (x : Fin P.params → Word w) (y : Fin T.params → Word w)
+ (hp : P = T) (hxy : ∀ j, x j = y (Fin.cast (congrArg Schedule.Pass.params hp) j)) :
+ (⟨_,(P.table.instantiate w x).program⟩ : ProgramTable w) = ⟨_,(T.table.instantiate w y).program⟩ := by
+ cases hp
+ obtain rfl : x = y := funext hxy
+ rfl
+
+/-- Identify the installed source using just the selected catalog row
+and its public operand words. -/
+theorem WorkerInput.installed_of_words (I : WorkerInput o w) (r : Directory.Row d w)
+ (code : C r.worker = TermWorker.motifPass (grid o).block (grid o).demandOrder.entries (grid o).e)
+ (words : ∀ j, Directory.words C ports r.worker r.input j =
+ TermWorker.motifData (grid o).block (grid o).demandOrder.entries (grid o).supplyOrder.entries w I.addr
+ (Fin.cast (congrArg Schedule.Pass.params code) j)) : sourceTable C ports r = I.table :=
+ same_table _ _ code words
+
+private theorem of_length {m : ℕ} (xs : List (List Bool)) (len : xs.length=m) :
+ ∃ t : Fin m → List Bool, List.ofFn t = xs := by
+ subst m
+ exact ⟨xs.get,List.ofFn_get _⟩
+
+/-- An arbitrary valid selector row, with the term table installed on its
+input addresses. The recipe's start, exclusive bound, and actual data
+memory are the only inputs besides the machine and fuel identities. -/
+theorem WorkerInput.validRow_unique (I : WorkerInput o w) (r : Directory.Row d w)
+ (valid : r.Valid C ports) (installed : sourceTable C ports r = I.table)
+ (fuel : r.fuel = I.fuel) (start : Directory.start C ports r.input = 0)
+ (bound : (Directory.bound C ports r.input).val = o.motifCount)
+ (memory : r.dataMemory C ports = I.memory) :
+ r.choices.length = o.motifCount ∧ ∃! i : pass.step.Choice, r.choices = List.ofFn (workerTapes o w i) := by
+ let G := grid o
+ let P := TermWorker.program G.block G.demandOrder.entries G.supplyOrder.entries I.addr
+ let stop := Directory.bound C ports r.input
+ let pub := Directory.words C ports r.worker r.input
+ let cursor (j : ℕ) : Word w := j
+ have fit : o.motifCount < 2^w := bound ▸ stop.isLt
+ have run := valid.sourceRun
+ rw [fuel,start,memory] at run
+ have swap := congrArg (fun table : ProgramTable w =>
+ runSegment table.2 I.fuel (some 0) I.memory r.choices) installed
+ have native : runSegment P I.fuel (some (cursor 0)) I.memory r.choices = some r.reports := swap ▸ run
+ have frame := valid.frame
+ rw [start,memory] at frame
+ have active (j : ℕ) (hj : j < o.motifCount) : cursor j < stop := by
+ change j % (2^w) < stop.val
+ rw [Nat.mod_eq_of_lt (hj.trans fit),bound]
+ exact hj
+ have closed : stop ≤ cursor o.motifCount := by
+ change stop.val ≤ o.motifCount % (2^w)
+ rw [Nat.mod_eq_of_lt fit,bound]
+ have progress (j : ℕ) (hj : j < o.motifCount) (mem : Memory w) (_ : True) (bits : List Bool)
+ (rep : Report w) (ok : execute P I.fuel (P.start (cursor j)) mem bits = some rep) :
+ rep.result = some (cursor (j+1)) ∧ True := by
+ let i : Fin o.motifCount := ⟨j,hj⟩
+ obtain ⟨hs,ht⟩ := I.addresses i
+ have fitS : (TermWorker.source I.addr (cursor j)).val+G.d ≤ 2^w := hs.symm ▸ I.layout.sourceFits i
+ have fitT : (TermWorker.base I.addr (cursor j)).val+2+G.e < 2^w := ht.symm ▸ I.layout.termFits i
+ have h := (TermWorker.Footprint.call G.block G.demandOrder.entries G.supplyOrder.entries I.addr
+ (cursor j) mem I.fuel bits rep fitS fitT ok).1
+ exact ⟨by simpa only [cursor,Nat.cast_add,Nat.cast_one] using h,trivial⟩
+ have len := exact_length P I.fuel ports r.worker pub stop cursor o.motifCount (fun _ _ => True)
+ active closed progress 0 (Nat.zero_le _) I.memory trivial r.choices r.reports native frame
+ have hlen : r.choices.length = o.motifCount := by simpa only [Nat.zero_add] using len
+ obtain ⟨t,ht⟩ := of_length r.choices hlen
+ have htRun : (I.run t).isSome := Option.isSome_iff_exists.mpr ⟨r.reports,by
+ change runSegment P I.fuel (some 0) I.memory (List.ofFn t) = some r.reports
+ rw [ht]; exact native⟩
+ let value := I.termEquiv.symm ⟨t,htRun⟩
+ have hvalue : List.ofFn (I.termEquiv value).val = r.choices :=
+ (congrArg (fun v : I.Accepted => List.ofFn v.val) (I.termEquiv.apply_symm_apply ⟨t,htRun⟩)).trans ht
+ refine ⟨hlen,value,hvalue.symm,fun j hj => ?_⟩
+ apply I.termEquiv.injective
+ exact Subtype.ext (List.ofFn_inj.mp (hj.symm.trans hvalue.symm))
+
+/-- The accepted term also describes the data in the actual post-worker
+memory. No new guess is made to choose the continuation state. -/
+theorem WorkerInput.validRow_fields (I : WorkerInput o w) (r : Directory.Row d w)
+ (valid : r.Valid C ports) (installed : sourceTable C ports r = I.table)
+ (fuel : r.fuel = I.fuel) (start : Directory.start C ports r.input = 0)
+ (bound : (Directory.bound C ports r.input).val = o.motifCount)
+ (memory : r.dataMemory C ports = I.memory) :
+ ∃ i : pass.step.Choice, I.decodePacket r.choices = some i ∧
+ ∀ j, TermRecordScan.Fields (grid o).block (grid o).supplyOrder.entries (grid o).pPos
+ ((batch o i).demand j) ((batch o i).choice j).val (I.layout.base j) (r.endMemory C ports) := by
+ obtain ⟨_,i,hi,_⟩ := I.validRow_unique r valid installed fuel start bound memory
+ obtain ⟨reports,hr,fields,_⟩ := I.selected_run i
+ have actual := valid.sourceRun
+ rw [fuel,start,memory,hi] at actual
+ have same := congrArg (fun table : ProgramTable w =>
+ runSegment table.2 I.fuel (some 0) I.memory (List.ofFn (workerTapes o w i))) installed
+ have worker : I.run (I.termEquiv i).val = some r.reports := same.symm.trans actual
+ have eq := Option.some.inj (hr.symm.trans worker)
+ rw [eq] at fields
+ refine ⟨i,(I.decodePacket_iff r.choices i).mpr hi.symm,?_⟩
+ simpa only [Directory.Row.endMemory,memory] using fields
+
+/-- The three entering control calls and the closing call do not change
+the multiplicity of the term selected by the recovered row. -/
+theorem WorkerInput.validStep_rowChoices (I : WorkerInput o w) (s : Run.Step d (initial+phases) w)
+ {cap : ℕ} {m : Memory w} (valid : s.Valid plan ports cap m) (installed : sourceTable C ports s.row = I.table)
+ (fuel : s.row.fuel = I.fuel) (start : Directory.start C ports s.row.input = 0)
+ (bound : (Directory.bound C ports s.row.input).val = o.motifCount)
+ (memory : s.row.dataMemory C ports = I.memory) :
+ ∃! i : pass.step.Choice, rowChoices s.row = [] :: [] :: [] :: (List.ofFn (workerTapes o w i) ++ [[]]) := by
+ obtain ⟨_,i,hi,hu⟩ := I.validRow_unique s.row valid.source installed fuel start bound memory
+ refine ⟨i,by simp only [rowChoices,hi],fun j hj => hu j ?_⟩
+ simpa only [rowChoices,List.cons.injEq,true_and,List.append_cancel_right_eq] using hj
+
+/-- The reference input used by the semantic decoder can have its own
+memory and private clock. For the recovered row, use the demand cells in
+the actual post-launch RAM and the fuel installed by the calendar. The
+canonical full-width tapes depend only on the pass and selected term. -/
+theorem WorkerInput.decode_validStep (I : WorkerInput o w) (s : Run.Step d (initial+phases) w)
+ {cap : ℕ} {m : Memory w} (valid : s.Valid plan ports cap m) (installed : sourceTable C ports s.row = I.table)
+ (start : Directory.start C ports s.row.input = 0)
+ (bound : (Directory.bound C ports s.row.input).val = o.motifCount)
+ (data : TermRecordScan.Inputs (grid o).demandOrder.entries I.layout (termRows o).demand (s.row.dataMemory C ports))
+ (budget : TermWorker.budget (grid o).block (grid o).d (grid o).e w X.maxWireWidth ≤ s.row.fuel) :
+ ∃! i : pass.step.Choice, I.decodePacket s.row.choices = some i ∧
+ rowChoices s.row = [] :: [] :: [] :: (List.ofFn (workerTapes o w i) ++ [[]]) := by
+ let J : WorkerInput o w := { I with memory := s.row.dataMemory C ports, inputs := data, fuel := s.row.fuel, clock := budget }
+ obtain ⟨_,i,hi,_⟩ := J.validRow_unique s.row valid.source installed rfl start bound rfl
+ have decoded := (I.decodePacket_iff s.row.choices i).mpr hi.symm
+ exact ⟨i,⟨decoded,by simp only [rowChoices,hi]⟩,fun j hj => Option.some.inj (hj.1.symm.trans decoded)⟩
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationSelectorStart.lean b/lean/OAI/Computability/VPVNP/PairSimulationSelectorStart.lean
new file mode 100644
index 0000000000..9db2ca6b58
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationSelectorStart.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.CompressorTermRowStart
+import OAI.Computability.VPVNP.CompressorSelectedTermWorker
+import OAI.Computability.VPVNP.PairSimulationWorkerCut
+
+/-! # Entering the selected motif table in the actual block script
+
+The directory's start, exclusive bound, and instantiated worker table
+are read back from the current physical recipe. The same boundary
+supplies the native selector cut at the current RAM and clock.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords CompressorRecords.SelectedTerms NetworkKernel BurstRAM
+open CompressorRecords.Schedule CompressorRecords.Schedule.Online DescriptorSpace BlockPlanner
+open scoped Fin.CommRing
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {B : S.Templates}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w : ℕ} {X : State a g} {p : StatePass A X b n} {o : PassOrigin B f hf p}
+
+private abbrev scriptPorts (script : Script) (base : Word w) := Workspace.ports (arity script.catalog) base
+
+/-- Interface of the physical calendar occurrence used by the branch cut. -/
+structure WorkerInput.SelectorBoundary (I : WorkerInput o w) (script : Script) (base : Word w)
+ (m : Memory w) (cap : ℕ) (j : Fin script.size) where
+ /-- The row-start witness for the live selector occurrence at the current script memory and
+ instruction cap. -/
+ entry : Run.RowStart script.plan (Workspace.ports (arity script.catalog) base) cap m
+ phase : entry.phase = j
+ worker : entry.worker = j
+ fuel : entry.fuel = I.fuel
+ table : RowStartTable entry = I.table
+ start : Directory.start script.catalog (Workspace.ports (arity script.catalog) base)
+ (rowInput script.plan (Workspace.ports (arity script.catalog) base) m entry.phase) = 0
+ stop : (Directory.bound script.catalog (Workspace.ports (arity script.catalog) base)
+ (rowInput script.plan (Workspace.ports (arity script.catalog) base) m entry.phase)).val = o.motifCount
+ memory : Directory.prepared script.catalog (Workspace.ports (arity script.catalog) base)
+ (rowInput script.plan (Workspace.ports (arity script.catalog) base) m entry.phase) = I.memory
+
+/-- Build the selector boundary at the current calendar row from its evaluated recipe operands,
+memory, and clock bounds, identifying the installed worker and its motif interval. -/
+noncomputable def WorkerInput.selectorStart (I : WorkerInput o w) (script : Script) (outer : DescriptorSpace.Layout)
+ (base : Word w) (hg : arity script.catalog = outer.shape.arity) (hb : base.val = outer.base)
+ (fit : levelStart outer 0 < 2^w) (m : Memory w) {cap : ℕ} (j : Fin script.size)
+ (code : script.catalog j = TermWorker.motifPass (grid o).block (grid o).demandOrder.entries (grid o).e)
+ (width : SelectedTermWorker.fitConstant B + 4*Nat.clog 2 (X.maxWireWidth+1) ≤ w)
+ (readable : ∀ i, levelStart outer 0 ≤ (I.layout.source i).val)
+ (writable : ∀ i, levelStart outer 0 ≤ (I.layout.base i).val)
+ (start : script.operand base m j (script.visit j).initial = 0)
+ (stop : (script.operand base m j (script.visit j).stop).val = o.motifCount)
+ (args : ∀ i, script.operand base m j ((script.visit j).params i) =
+ TermWorker.catalogWords (grid o).block (grid o).demandOrder.entries (grid o).supplyOrder.entries script.catalog j I.addr code i)
+ (phase : (calendar script.plan).phase (m (scriptPorts script base).ordinal.val).val = j.val)
+ (room : (m (scriptPorts script base).ordinal.val).val < directoryRows outer)
+ (active : m (scriptPorts script base).ordinal.val < m (scriptPorts script base).rows.val)
+ (recipeCap : (script.plan.recipes j).2.code.length+1+2*N script.size script.size+5 ≤ cap)
+ (dataCap : I.fuel+3+4*((script.catalog j).params+1)+2*N script.size script.size+5 ≤ cap)
+ (fresh : Directory.prepared script.catalog (scriptPorts script base) (rowInput script.plan (scriptPorts script base) m j) = I.memory) :
+ I.SelectorBoundary script base m cap j := by
+ let G := grid o
+ let port := Workspace.ports (arity script.catalog) base
+ have countFit : o.motifCount < 2^w := stop ▸ (script.operand base m j (script.visit j).stop).isLt
+ have stopWord : script.operand base m j (script.visit j).stop = (o.motifCount : Word w) :=
+ Fin.ext (stop.trans (Nat.mod_eq_of_lt countFit).symm)
+ have agree := OnlineFootprint.prepared script outer base hg hb fit m j room
+ rw [fresh] at agree
+ have boundaryInputs : TermRecordScan.Inputs G.demandOrder.entries I.layout (termRows o).demand m := by
+ intro i
+ funext x
+ obtain ⟨l,rfl⟩ := G.demandOrder.entries.surjective x
+ rw [DemandPreparation.demandAt_address G.demandOrder.entries _ _ (I.layout.sourceFits i)]
+ have hr := congrFun (I.inputs i) (G.demandOrder.entries l)
+ rw [DemandPreparation.demandAt_address G.demandOrder.entries _ _ (I.layout.sourceFits i)] at hr
+ exact (congrArg Fin.val (agree _ ((readable i).trans (Nat.le_add_right ..)))).trans hr
+ let entry := TermWorker.rowStart G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos
+ script outer base hg hb fit m j code I.layout I.addr I.addresses (termRows o).demand (termRows o).bounded
+ ((Nat.add_le_add_right (SelectedTermWorker.frameFit_le o) _).trans width) I.clock countFit readable writable
+ boundaryInputs stopWord args phase room active recipeCap dataCap
+ have snap := SourceOnline.evaluated_launch script base outer hg hb fit m j I.fuel [] room active
+ refine ⟨entry,rfl,rfl,rfl,?_,snap.start.trans start,(congrArg Fin.val snap.stop).trans stop,fresh⟩
+ let r : Directory.Row script.size w := ⟨rowInput script.plan port m j,j,I.fuel,[],[]⟩
+ exact I.installed_of_words (ports := port) r code (fun i => (congrFun snap.params i).trans (args i))
+
+/-- The typed boundary provides the cut at the actual stage memory. -/
+noncomputable def WorkerInput.SelectorBoundary.cut {I : WorkerInput o w} {script : Script}
+ {base : Word w} {m : Memory w} {cap : ℕ} {j : Fin script.size}
+ (v : I.SelectorBoundary script base m cap j) (controls : Run.ControlBounds script.plan cap (w := w))
+ (state : Word w) (tag : m (scriptPorts script base).tag.val = LiveStageLink.tagWord w (calendarIndex script.size script.size))
+ (live : m (scriptPorts script base).ordinal.val < m (scriptPorts script base).rows.val) :
+ BranchSegments.Cut (program script.plan (scriptPorts script base)) cap (some state) m p.step.Choice :=
+ I.selectorCut v.entry controls state tag live v.table v.fuel v.start v.stop v.memory
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationSharedBitControl.lean b/lean/OAI/Computability/VPVNP/PairSimulationSharedBitControl.lean
new file mode 100644
index 0000000000..b2d885b071
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationSharedBitControl.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.PairSimulationFinalBitScan
+import OAI.Computability.VPVNP.PairSimulationWorkerControl
+
+/-!
+# Shared-bit frames along partial native runs
+
+The shared-bit worker can write only one wire per data call. Its ordinary
+header words survive both that write and the controller's two handoff writes.
+This invariant covers any successful prefix of the terminal program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.FinalBits.Worker
+
+open BurstRAM PrivateRAM CompressorRecords LiveProgram
+open scoped Fin.CommRing
+
+variable {w : ℕ} {pub : Fin 11 → Word w} {lo count : ℕ}
+
+open private field_away active_at next_layout from OAI.Computability.VPVNP.PairSimulationFinalBitScan
+open private report_agree from OAI.Computability.VPVNP.PairSimulationTerminalSplice
+
+private theorem layout_transfer {src phy : Memory w} (h : Layout pub src lo count)
+ (room : (header pub).val + 32 ≤ 2 ^ w)
+ (agree : SourceTransport.Agree (TerminalLink.workerCell (header pub)) src phy) :
+ Layout pub phy lo count := by
+ refine ⟨?_, ?_, h.fits, h.base_disjoint, h.total_disjoint⟩
+ · exact (agree _ (field_away pub room 13 (by decide) (by decide))).symm.trans h.base_eq
+ · exact (agree _ (field_away pub room 12 (by decide) (by decide))).symm.trans h.total_eq
+
+private theorem successful_call (st : Word w) (m : Memory w) {fuel : ℕ} {bits : List Bool}
+ {r : Report w} (run : execute (table.instantiate w pub).program fuel
+ ((table.instantiate w pub).program.start st) m bits = some r) :
+ (st < total pub m ∧ ∃ b, r = activeReport pub st m b) ∨ r = closeReport pub m := by
+ have extended := execute_extend run 24
+ rcases lt_trichotomy st (total pub m) with hi | hi | hi
+ · rw [active pub st m hi] at extended
+ cases bits with
+ | nil => contradiction
+ | cons b bs =>
+ cases bs with
+ | cons => contradiction
+ | nil => exact .inl ⟨hi, b, (Option.some.inj extended).symm⟩
+ · rw [close pub st m hi] at extended
+ split at extended <;> try contradiction
+ exact .inr (Option.some.inj extended).symm
+ · rw [overrun pub st m hi] at extended
+ contradiction
+
+private theorem active_step (st : Word w) (m : Memory w) (h : Layout pub m lo count)
+ (live : st < total pub m) (b : Bool) {a : ℕ} (outside : a < lo ∨ lo + count ≤ a) :
+ let raw := after m (activeReport pub st m b).events
+ raw a = m a ∧ Layout pub raw lo count := by
+ have fit := h.fits
+ have hst : st.val < count := by
+ rw [h.total_eq] at live
+ change st.val < count % (2 ^ w) at live
+ rwa [Nat.mod_eq_of_lt (by omega)] at live
+ let j := count - st.val - 1
+ have splitCount : st.val + (j + 1) = count := by dsimp [j]; omega
+ have dest : address pub m st = cursor w lo j := by
+ simpa only [Fin.cast_val_eq_self] using (active_at h splitCount).2
+ have inside : (cursor w lo j).val = lo + j := Nat.mod_eq_of_lt (by omega)
+ have ne : a ≠ (address pub m st).val := by rw [dest, inside]; omega
+ exact ⟨by simp only [active_image, writeMemory, ite_eq_right ne],
+ by simpa only [Fin.cast_val_eq_self] using next_layout h splitCount b⟩
+
+/-- Every successful shared-bit burst preserves an address outside both the
+wire bank and the terminal controller cells. The invariant starts at the
+actual physical memory left by the row phase. -/
+def control (workers : TerminalLink.Stage → PairTable)
+ (bank : workers TerminalLink.Stage.sharedBits = ⟨28, 5, table⟩)
+ (cap a : ℕ) (src phy : Memory w) (layout : Layout pub src lo count)
+ (room : (header pub).val + 32 ≤ 2 ^ w)
+ (agree : SourceTransport.Agree (TerminalLink.workerCell (header pub)) src phy)
+ (outside : a < lo ∨ lo + count ≤ a) (cell : TerminalLink.workerCell (header pub) a) :
+ TerminalLink.WorkerControl workers pub cap TerminalLink.Stage.sharedBits a phy where
+ inv _ m := Layout pub m lo count
+ ready := layout_transfer layout room agree
+ advance st m bits rep h run := by
+ unfold TerminalLink.source at run
+ rw [bank] at run
+ have agreeOut := report_agree (header pub) (.resume TerminalLink.Stage.sharedBits st) rep m m
+ (fun _ _ => rfl)
+ have frame := (agreeOut a cell).symm
+ obtain ⟨live, b, rfl⟩ | rfl := successful_call st m run
+ · obtain ⟨rawFrame, rawLayout⟩ := active_step st m h live b outside
+ exact ⟨frame.trans rawFrame, fun _ _ => layout_transfer rawLayout room agreeOut⟩
+ · exact ⟨frame.trans (congrFun (close_image pub m) a), fun _ impossible => by
+ simp only [close_result, reduceCtorEq] at impossible⟩
+
+end PairSimulation.FinalBits.Worker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationSharedBitPhase.lean b/lean/OAI/Computability/VPVNP/PairSimulationSharedBitPhase.lean
new file mode 100644
index 0000000000..ab7c97cb5e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationSharedBitPhase.lean
@@ -0,0 +1,220 @@
+import OAI.Computability.VPVNP.PairSimulationFinalBitScan
+import OAI.Computability.VPVNP.PairSimulationTerminalBlocks
+import OAI.Computability.VPVNP.PairSimulationTerminalProgram
+import OAI.Computability.VPVNP.PairSimulationTerminalPhaseBuild
+
+/-!
+# The completed shared-bit phase of the terminal machine
+
+The phase reads the base and size of the wire bank from its terminal header.
+Every binary assignment determines one complete physical record, including
+the closing call and the handoff to the vertex worker. The reverse direction
+classifies the reads of an arbitrary successful worker call before
+transporting its reports back to the ordinary shared-bit scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.SharedBitPhase
+
+open BurstRAM PrivateRAM CompressorRecords TerminalLink
+open SourceTransport
+open scoped Fin.CommRing
+
+variable {w : ℕ} (F : DescriptorSpace.Shape) (limit : ℕ)
+ (S : VertexImage.Part → VertexImage.Segment)
+variable (pub : Fin 11 → Word w) (cap : ℕ)
+
+open private testEvents from OAI.Computability.VPVNP.PairSimulationFinalBitWorker
+open private field_away header_offset from OAI.Computability.VPVNP.PairSimulationFinalBitScan
+open FinalBits.Worker (activeReport closeReport total)
+
+/-- Every successful call, even on an arbitrary candidate tape and memory,
+reads only header words 12 and 13. -/
+private theorem call_reads (i : Word w) (m : Memory w) (b : List Bool) (r : Report w)
+ {fuel : ℕ} (enough : 24 ≤ fuel) (room : (header pub).val + 32 ≤ 2 ^ w)
+ (hc : execute (FinalBits.Worker.table.instantiate w pub).program fuel
+ ((FinalBits.Worker.table.instantiate w pub).program.start i) m b = some r) :
+ Reads (workerCell (header pub)) r.events := by
+ rw [show fuel = (fuel - 24) + 24 by omega] at hc
+ rcases lt_trichotomy i (total pub m) with hi | hi | hi
+ · rw [FinalBits.Worker.active pub i m hi] at hc
+ cases b with
+ | nil => contradiction
+ | cons b bs =>
+ cases bs with
+ | cons => contradiction
+ | nil =>
+ obtain rfl : r = activeReport pub i m b := (Option.some.inj hc).symm
+ intro a v mem
+ simp only [activeReport, testEvents, List.mem_append, List.mem_replicate, List.mem_cons,
+ List.not_mem_nil, Event.read.injEq, reduceCtorEq, and_false, false_or, or_false] at mem
+ rcases mem with ⟨rfl, _⟩ | ⟨rfl, _⟩
+ · exact field_away pub room 12 (by decide) (by decide)
+ · exact field_away pub room 13 (by decide) (by decide)
+ · rw [FinalBits.Worker.close pub i m hi] at hc
+ split at hc <;> try contradiction
+ obtain rfl : r = closeReport pub m := (Option.some.inj hc).symm
+ intro a v mem
+ simp only [closeReport, testEvents, List.mem_append, List.mem_replicate, List.mem_cons,
+ List.not_mem_nil, Event.read.injEq, reduceCtorEq, and_false, false_or, or_false] at mem
+ obtain ⟨rfl, _⟩ := mem
+ exact field_away pub room 12 (by decide) (by decide)
+ · rw [FinalBits.Worker.overrun pub i m hi] at hc
+ contradiction
+
+private theorem phase_reads {e phy bs ls final}
+ (h : Phase (TerminalProgram.workers F limit S) pub cap e phy bs ls final)
+ (stage : e.stage = Stage.sharedBits) (clock : 54 ≤ cap) (room : (header pub).val + 32 ≤ 2 ^ w) :
+ Reads (workerCell (header pub)) (eventLog (ls.map Prod.snd)) := by
+ have head {e : Entry w} {m b r} (stage : e.stage = Stage.sharedBits)
+ (call : execute (source (TerminalProgram.workers F limit S) e.stage pub) (rawFuel pub cap e)
+ ((source (TerminalProgram.workers F limit S) e.stage pub).start e.state) m b = some r) :
+ Reads (workerCell (header pub)) r.events := by
+ rw [stage] at call
+ have pre := prefix_length_le (header pub) e
+ apply call_reads pub e.state m b r (fuel := rawFuel pub cap e) (by unfold rawFuel; omega) room
+ exact call
+ induction h with
+ | last hc _ _ => simpa only [List.map_cons, List.map_nil, eventLog, List.flatMap_cons,
+ List.flatMap_nil, List.append_nil] using head stage hc
+ | more hc _ _ _ ih =>
+ intro a v mem
+ change Event.read a v ∈ _ ++ eventLog _ at mem
+ rcases List.mem_append.mp mem with hh | ht
+ · exact head stage hc a v hh
+ · exact ih stage a v ht
+
+/-- The physical phase record for an assignment to the entire wire bank. -/
+def block (src phy : Memory w) {count : ℕ} (f : Fin count → Bool) : Block w :=
+ let e := Entry.resume Stage.sharedBits (0 : Word w)
+ let rs := FinalBits.Worker.reports pub 0 src f
+ ⟨FinalBits.calls f ++ [[]], stageLogs e rs, after phy (eventLog (stageReports (header pub) e rs))⟩
+
+variable (src phy : Memory w) {lo count : ℕ}
+variable (layout : FinalBits.Worker.Layout pub src lo count) (clock : 54 ≤ cap)
+ (room : (header pub).val + 32 ≤ 2 ^ w) (below : lo + count ≤ (header pub).val)
+ (agree : Agree (workerCell (header pub)) src phy)
+
+include layout clock room below agree
+
+/-- All three components of the physical record are forced by its bit assignment. -/
+theorem phase_iff (B : Block w) :
+ Phase (TerminalProgram.workers F limit S) pub cap (.resume Stage.sharedBits 0)
+ phy B.choices B.logs B.memory ↔ ∃ f : Fin count → Bool, B = block pub src phy f := by
+ constructor
+ · intro ph
+ have ⟨run, halt, _⟩ := ph.source_segment _ _ _ src agree
+ (phase_reads F limit S pub cap ph rfl clock room)
+ change runSegment (FinalBits.Worker.table.instantiate w pub).program
+ cap (some 0) src _ = _ at run
+ rw [show cap = (cap - 24) + 24 by omega] at run
+ obtain ⟨f, hb, hr⟩ :=
+ (FinalBits.Worker.accepted_iff pub src layout (cap - 24) _ _).mp ⟨run, halt⟩
+ have hl := stageLogs_eq ph
+ rw [hr] at hl
+ have hm := ph.final_memory
+ rw [ph.reports_eq, hr] at hm
+ exact ⟨f, by cases B; simp only [block, Block.mk.injEq]; exact ⟨hb, hl, hm.symm⟩⟩
+ · rintro ⟨f, rfl⟩
+ apply Phase.of_source_segment (f := 24) clock agree
+ (FinalBits.Worker.controller_frame pub src layout f room below).1
+ · exact FinalBits.Worker.run_scan pub src layout f 0
+ · exact FinalBits.Worker.reports_halt pub count 0 src f _
+
+/-- Binary wire assignments enumerate all completed records with their
+individual private strings, raw tagged reports, and final physical memories. -/
+noncomputable def equiv :
+ (Fin count → Bool) ≃ CompletedPhase (TerminalProgram.workers F limit S) pub cap
+ (.resume Stage.sharedBits 0) phy :=
+ Equiv.ofBijective (fun f => ⟨block pub src phy f,
+ (phase_iff F limit S pub cap src phy layout clock room below agree _).mpr ⟨f, rfl⟩⟩) <| by
+ constructor
+ · intro f g h
+ exact FinalBits.calls_injective
+ (List.append_cancel_right (congrArg (fun B => B.val.choices) h))
+ · rintro ⟨B, ph⟩
+ obtain ⟨f, rfl⟩ := (phase_iff F limit S pub cap src phy layout clock room below agree B).mp ph
+ exact ⟨f, rfl⟩
+
+variable (valid : (Entry.resume Stage.sharedBits (0 : Word w)).Valid (header pub) phy)
+
+include F limit S valid
+
+/-- Native execution realizes the completed block and initializes the vertex
+worker's stage and ordinal in the two control cells. -/
+theorem native (f : Fin count → Bool) :
+ let B := block pub src phy f
+ let e := Entry.resume Stage.sharedBits (0 : Word w)
+ runSegment (program (TerminalProgram.workers F limit S) pub) cap (some e.marker)
+ phy B.choices = some (reports (header pub) B.logs) ∧
+ (Entry.resume Stage.vertices (0 : Word w)).Valid (header pub) B.memory := by
+ have run := FinalBits.Worker.stageRun (TerminalProgram.workers F limit S) rfl pub src phy
+ layout f cap clock room below valid agree
+ refine ⟨?_, run.valid _ rfl⟩
+ dsimp only [block]
+ rw [reports_stageLogs]
+ exact run.run
+
+/-- Outside the two terminal control cells the entire physical memory agrees
+with the contraction's shared-wire memory, including every untouched descriptor. -/
+theorem memory_image (f : Fin count → Bool) :
+ Agree (workerCell (header pub)) (after src (eventLog (FinalBits.reports w lo f)))
+ (equiv F limit S pub cap src phy layout clock room below agree f).val.memory := by
+ have run := FinalBits.Worker.stageRun (TerminalProgram.workers F limit S) rfl pub src phy
+ layout f cap clock room below valid agree
+ rw [← FinalBits.Worker.image pub src layout f]
+ exact run.agree
+
+/-- The phase corresponding to a wire assignment returns the chosen bit at every wire address. -/
+theorem readback (f : Fin count → Bool) (j : Fin count) :
+ (equiv F limit S pub cap src phy layout clock room below agree f).val.memory (lo + j) =
+ PrimedInputRAM.encodeBit w (f j) := by
+ have data : workerCell (header pub) (lo + j) := by
+ have h31 : (header pub + 31).val = (header pub).val + 31 :=
+ header_offset pub 31 (by decide) room
+ have hj := j.isLt
+ unfold workerCell
+ omega
+ have image := memory_image F limit S pub cap src phy layout clock room below agree valid f
+ exact (image _ data).symm.trans (FinalBits.readback lo layout.fits f src j)
+
+omit F limit S valid layout clock room below agree
+
+/-- The linked cost includes the closing call and every transfer of control. -/
+theorem probe_cost (f : Fin count → Bool) :
+ RAMBuckets.cost Report.probes (reports (header pub) (block pub src phy f).logs) =
+ 8 * count + 6 := by
+ dsimp only [block]
+ rw [reports_stageLogs]
+ exact FinalBits.Worker.stage_cost pub src f
+
+/-- The data calls have at most seven linked probes and at most 53 physical
+events. The same bounds include the closing call. -/
+theorem local_caps (f : Fin count → Bool) :
+ ∀ r ∈ reports (header pub) (block pub src phy f).logs, r.probes ≤ 7 ∧ r.events.length ≤ 53 := by
+ have bounds {e : Entry w} {rs : List (Report w)}
+ (h : ∀ r ∈ rs, r.probes ≤ 3 ∧ r.events.length ≤ 23) :
+ ∀ t ∈ stageReports (header pub) e rs, t.probes ≤ 7 ∧ t.events.length ≤ 53 := by
+ induction rs generalizing e with
+ | nil => simp [stageReports]
+ | cons r rs ih =>
+ intro t ht
+ rw [stageReports, List.mem_cons] at ht
+ rcases ht with rfl | ht
+ · obtain ⟨hp, hl⟩ := h r List.mem_cons_self
+ have := report_probes_le (header pub) e r
+ have := report_length_le (header pub) e r
+ omega
+ · exact ih (fun r hr => h r (List.mem_cons_of_mem _ hr)) t ht
+ dsimp only [block]
+ rw [reports_stageLogs]
+ exact bounds (FinalBits.Worker.scan_cost pub count 0 src f).2.2
+
+end PairSimulation.SharedBitPhase
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherBank.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherBank.lean
new file mode 100644
index 0000000000..ede275ea99
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherBank.lean
@@ -0,0 +1,231 @@
+import OAI.Computability.VPVNP.PairShrinkPartyNative
+import OAI.Computability.VPVNP.PairSimulationMapHandlerImage
+
+/-!
+# Relocatable gather code before each shrinking map writer
+
+Each grid, party and layout has a finite instruction range. The range copies
+all of the party's AB and surviving fields into its own staging slots and
+then jumps to the descriptor writer for that same grid and party.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkGatherBank
+
+open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData Compression.ShrinkMotif
+open Compression.ShrinkEnergy CompressorRecords CompressorRecords.PhaseRecipe
+open MotifBlocks MotifGrid MotifConversion
+
+variable {K : Type} [Field K] {factor : ℝ}
+variable {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+variable {t shared p r w : ℕ}
+
+/-- Select a shrinking gather by its demand grid point, one of the six motif parties, and the
+surviving layout bit. -/
+abbrev Key (B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor) :=
+ B.grid.demands × Fin 6 × Bool
+
+/-- One fixed shrinking stage uses old and new degree exponents chosen in the schedule. -/
+structure Family (_F : MapHandlerImage.Family B t shared) where
+ /-- Exponent of the old degree for this shrinking stage. Its degree and color count determine
+ the thick-wire frame count. -/
+ a : ℕ
+ /-- Exponent of the new degree used to determine the number of subdivisions of each surviving
+ role. -/
+ b : ℕ
+ /-- Call-header expressions for each grid point and party, supplying the level, motif,
+ argument and hidden-slot geometry, and histogram address. -/
+ operands : MapHandlerImage.Index B → ShrinkCallHeader.Operands
+ /-- Expression for the parent node whose packet supplies the surviving half-wire bits for a
+ grid-point and party handler. -/
+ node : MapHandlerImage.Index B → Expr
+
+variable {F : MapHandlerImage.Family B t shared} (G : Family F)
+
+namespace Family
+
+private def handler (i : Key B) : MapHandlerImage.Index B := (i.1, i.2.1)
+
+/-- The four role subdivision counts computed from the stage's old degree, color count, and new
+degree. -/
+noncomputable def profile := subdivisions (2 ^ G.a) (Shrink.colors G.a) (2 ^ G.b)
+
+/-- Number of thick-wire frames in an AB column, equal to one quarter of the old degree times
+the number of color patterns. -/
+def thickCount := 2 ^ (Shrink.colors G.a) * 2 ^ G.a / 4
+
+/-- Positions in the ordered list of AB and surviving frames incident to the selected party in
+the given layout. -/
+noncomputable abbrev Visits (i : Key B) :=
+ Fin (ShrinkPartyColumns.visits i.2.1 i.2.2 G.thickCount G.profile).length
+
+/-- Register-setup and frame-copy recipe for each visit, using the selected party's header
+operands and parent node expression. -/
+noncomputable def setup (i : Key B) : G.Visits i → ResidentColumn.Setup :=
+ ShrinkPartyColumns.gather i.2.1 i.2.2 G.thickCount G.profile
+ (ShrinkPartyNative.setups (G.operands (handler i)) (G.node (handler i)) G.a G.b i.2.1 i.2.2)
+
+/-- Instruction address consisting of a grid, party, and layout key and a label in that key's
+resident column gather. -/
+noncomputable abbrev Address := (i : Key B) × ResidentColumn.Label (G.setup i)
+/-- Private evaluator register identified by its gather key, frame visit, and operand-compiler
+register index. -/
+noncomputable abbrev PrivateReg := (i : Key B) × (v : G.Visits i) ×
+ Fin (RegisterSetup.regCount ((G.setup i v).operands))
+
+variable (loc : G.Address → Fin p)
+variable (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r)
+variable (own : G.PrivateReg ↪ Fin r) (writer : B.grid.demands → Fin 6 → Fin p)
+
+/-- Place an instruction of the selected resident column gather at its assigned machine program
+counter. -/
+def rowPC (i : Key B) (l : ResidentColumn.Label (G.setup i)) := loc ⟨i, l⟩
+
+/-- Embed one frame visit's operand-compiler registers into the gather family's private
+register allocation. -/
+noncomputable def vm (i : Key B) (v : G.Visits i) :
+ Fin (RegisterSetup.regCount ((G.setup i v).operands)) ↪ Fin r :=
+ (⟨fun a ↦ ⟨i, v, a⟩, fun _ _ h ↦ eq_of_heq (Sigma.mk.inj (eq_of_heq (Sigma.mk.inj h).2)).2⟩ :
+ Fin _ ↪ G.PrivateReg).trans own
+
+/-- A party with no frames goes directly to its writer. -/
+noncomputable def entry (z : B.grid.demands) (j : Fin 6) (l : Bool) :=
+ ResidentColumn.start (G.setup (z, j, l)) (G.rowPC loc (z, j, l)) (writer z j) 0
+
+/-- Five-bit template instructions for insertion at arbitrary program locations. -/
+noncomputable def text : G.Address → Instr 5 p r 11
+ | ⟨i, l⟩ => ResidentColumn.instruction (G.setup i) (G.vm own i)
+ (F.inputs dfs saved common (handler i)) (G.rowPC loc i) (writer i.1 i.2.1) l
+
+/-- Installation gives the precise code equation required by the linked native party theorem. -/
+theorem linked (M : Machine w p r 11)
+ (install : ∀ a, M.code (loc a) = (G.text loc dfs saved common own writer a).resize w)
+ (i : Key B) (l : ResidentColumn.Label (G.setup i)) :
+ M.code (G.rowPC loc i l) = ResidentColumn.instruction (G.setup i) (G.vm own i)
+ (F.inputs dfs saved common (handler i)) (G.rowPC loc i) (writer i.1 i.2.1) l := by
+ have twice (op : Instr 2 p r 11) : (op.resize 5).resize w = op.resize w := by
+ cases op <;> try rfl
+ case constant d a n => simp only [Instr.resize, resize_literal (by decide : 2 ≤ 5)]
+ rw [show G.rowPC loc i l = loc ⟨i,l⟩ from rfl, install]
+ change (ResidentColumn.instruction (w := 5) _ _ _ _ _ _).resize w = _
+ rw [← ResidentColumn.resize_instruction (w := 5), twice, ResidentColumn.resize_instruction]
+
+/-- The gather's private register bank is disjoint from the DFS, saved bootstrap, and shared
+registers that provide its inputs. -/
+structure Apart : Prop where
+ dfs : ∀ x j, own x ≠ dfs j
+ saved : ∀ x j, own x ≠ saved j
+ common : ∀ x j, own x ≠ common j
+
+/-- No scratch operand can clobber one of the six input registers. -/
+theorem safe (apart : G.Apart dfs saved common own) (i : Key B) (v : G.Visits i)
+ (a : Fin (RegisterSetup.regCount ((G.setup i v).operands))) (j : Fin 6) :
+ G.vm own i v a ≠ F.inputs dfs saved common (handler i) j := by
+ unfold MapHandlerImage.Family.inputs
+ rcases F.source (handler i) j with h | h | h
+ · exact apart.dfs _ h
+ · exact apart.saved _ h
+ · exact apart.common _ h
+
+/-- A returning gather preserves the loop, DFS and saved bootstrap registers for its writer. -/
+theorem preserved (apart : G.Apart dfs saved common own) (i : Key B) {M : Machine w p r 11}
+ {row : G.Visits i → ResidentColumn.Row} {mem : Memory w} {cfg out : Config w p r}
+ {events : List (Event w)}
+ (res : ResidentColumn.Result (G.setup i) (G.vm own i) M (writer i.1 i.2.1) row
+ (List.finRange _) mem cfg out events) :
+ (∀ j, out.reg (dfs j) = cfg.reg (dfs j)) ∧
+ (∀ j, out.reg (saved j) = cfg.reg (saved j)) ∧
+ (∀ j, out.reg (common j) = cfg.reg (common j)) :=
+ ⟨fun j ↦ res.regs _ (fun _ _ _ ↦ (apart.dfs _ j).symm),
+ fun j ↦ res.regs _ (fun _ _ _ ↦ (apart.saved _ j).symm),
+ fun j ↦ res.regs _ (fun _ _ _ ↦ (apart.common _ j).symm)⟩
+
+section Execution
+
+open CompressorRecords.ShrinkSlots
+
+variable {g : ℕ} {δ : ℝ} {X : State G.a (packingLaneBits G.a g)}
+variable {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} {sel : X.ShrinkSelection B}
+variable {m : X.packingData.Motif} {party : Fin 6} (z : B.grid.demands)
+variable (J : ShrinkPartyNative.Job X B ready sel m party w)
+local notation "side" => selectedLayout X B sel
+local notation "key" => Prod.mk z (Prod.mk party side)
+local notation "flatRow" => ShrinkPartyColumns.gather party side G.thickCount G.profile J.row
+
+/-- Enter the installed gather for the selected stage, grid point, party and layout.
+Its returning configuration is already at that grid point's descriptor writer. -/
+theorem execute {endAddr : ℕ} (M : Machine w p r 11)
+ (install : ∀ a, M.code (loc a) = (G.text loc dfs saved common own writer a).resize w)
+ (apart : G.Apart dfs saved common own)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+ {level absolute : Word w} {T U : IncidenceDirectory w} {origin layer pitch : ℕ}
+ {heads : SlotLevel.Heads}
+ (old : J.OldPublished (G.operands (z, party)) pub state mem level T origin)
+ (next : J.SupplyPublished (G.operands (z, party)) (G.node (z, party)) pub state mem heads
+ absolute U layer pitch)
+ (cfg : Config w p r) (entry : cfg.pc = G.entry loc writer z party side)
+ (hp : ∀ j : Fin 5, cfg.reg (F.inputs dfs saved common (z, party) j.castSucc) = pub j)
+ (hs : cfg.reg (F.inputs dfs saved common (z, party) (Fin.last 5)) = state)
+ (packets : J.Packets endAddr cfg.privateMem) :
+ ∃ events out, ResidentColumn.Result (G.setup key) (G.vm own key) M (writer z party)
+ flatRow (List.finRange _) mem cfg out events ∧ J.Assembled cfg.privateMem out.privateMem ∧
+ (∀ j, out.reg (dfs j) = cfg.reg (dfs j)) ∧
+ (∀ j, out.reg (saved j) = cfg.reg (saved j)) ∧
+ (∀ j, out.reg (common j) = cfg.reg (common j)) := by
+ obtain ⟨ev, out, run, assembled⟩ := ShrinkPartyNative.native_party J (G.operands (z, party))
+ (G.node (z, party)) pub state mem old next M (G.vm own key)
+ (F.inputs dfs saved common (z, party))
+ (G.rowPC loc key) (writer z party) (G.linked loc dfs saved common own writer M install key)
+ (G.safe dfs saved common own apart key) cfg entry hp hs packets
+ exact ⟨ev, out, run, assembled, G.preserved dfs saved common own writer apart key run⟩
+
+/-- The successful trace and upper scratch are fixed functions of the selected job and inputs.
+The gather has no reads outside the stated region and keeps the lower private stack. -/
+theorem execute_exact {endAddr : ℕ} (M : Machine w p r 11)
+ (install : ∀ a, M.code (loc a) = (G.text loc dfs saved common own writer a).resize w)
+ (apart : G.Apart dfs saved common own)
+ (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w)
+ {level absolute : Word w} {T U : IncidenceDirectory w} {origin layer pitch : ℕ}
+ {heads : SlotLevel.Heads}
+ (old : J.OldPublished (G.operands (z, party)) pub state mem level T origin)
+ (next : J.SupplyPublished (G.operands (z, party)) (G.node (z, party)) pub state mem heads
+ absolute U layer pitch)
+ (allowed : ℕ → Prop) (sites : ∀ c i, (J.row c i).ReadSafe
+ (ShrinkPartyNative.setups (G.operands (z, party)) (G.node (z, party)) G.a G.b party side c i)
+ allowed pub state mem)
+ (cfg : Config w p r) (entry : cfg.pc = G.entry loc writer z party side)
+ (hp : ∀ j : Fin 5, cfg.reg (F.inputs dfs saved common (z, party) j.castSucc) = pub j)
+ (hs : cfg.reg (F.inputs dfs saved common (z, party) (Fin.last 5)) = state)
+ (packets : J.Packets endAddr cfg.privateMem) :
+ let es := J.trace (G.operands (z, party)) (G.node (z, party)) pub state mem
+ ∃ out, ResidentColumn.Result (G.setup key) (G.vm own key) M (writer z party)
+ flatRow (List.finRange _) mem cfg out es ∧ J.Assembled cfg.privateMem out.privateMem ∧
+ SourceTransport.Reads allowed es ∧
+ DFS.scratch endAddr out.privateMem = J.updated endAddr (DFS.scratch endAddr cfg.privateMem) ∧
+ (∀ a : Word w, a.val < endAddr → out.privateMem a = cfg.privateMem a) ∧
+ (∀ j, out.reg (dfs j) = cfg.reg (dfs j)) ∧
+ (∀ j, out.reg (saved j) = cfg.reg (saved j)) ∧
+ (∀ j, out.reg (common j) = cfg.reg (common j)) := by
+ intro es
+ obtain ⟨out, run, assembled, reads, upper, lower⟩ := ShrinkPartyNative.native_party_reads J
+ (G.operands (z, party)) (G.node (z, party)) pub state mem old next M (G.vm own key)
+ (F.inputs dfs saved common (z, party)) (G.rowPC loc key) (writer z party)
+ (G.linked loc dfs saved common own writer M install key) (G.safe dfs saved common own apart key)
+ allowed sites cfg entry hp hs packets
+ exact ⟨out, run, assembled, reads, upper, lower, G.preserved dfs saved common own writer
+ apart key run⟩
+
+end Execution
+
+end Family
+
+end PairSimulation.ShrinkGatherBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherImage.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherImage.lean
new file mode 100644
index 0000000000..bad1ed259a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherImage.lean
@@ -0,0 +1,151 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkMapImage
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherBank
+import OAI.Computability.VPVNP.PairSimulationShrinkLayoutBranch
+
+/-!
+# The shrinking map image with both physical layout gathers
+
+The item reader selects its matrix by the recorded grid and party. At that
+address a further header read chooses one of two layouts. Its gather copies
+the appropriate old-child and surviving fields before entering the writer.
+Only completion of the writer and matrix advances the resident row cursor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM Compression.ShrinkMotif MotifSelector MotifGrid
+open MotifBlocks MotifConversion MapHandlerImage
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w : ℕ} (F : MapHandlerImage.Family B t shared)
+ (G : ShrinkGatherBank.Family F) (S : Registers shared)
+
+/-- Instruction labels for the resident map image, each five-row layout branch, and the gathers. -/
+noncomputable abbrev GatherAddress := Address F ⊕ (Index B × Fin 5) ⊕ G.Address
+
+/-- The role's shared registers, handler and gather banks, and layout selection register. -/
+noncomputable abbrev GatherRegister := Fin shared ⊕ F.PrivateReg ⊕ G.PrivateReg ⊕ Unit
+
+variable (pc : GatherAddress F G → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r)
+ (own : F.PrivateReg ↪ Fin r) (gatherReg : G.PrivateReg ↪ Fin r) (temp : Fin r) (ret : Fin p)
+
+/-- Placement of the resident map image within the full instruction table. -/
+noncomputable abbrev corePC : Address F → Fin p := pc ∘ Sum.inl
+
+/-- Address of row `l` in the layout branch for grid point `z` and party `j`. -/
+noncomputable abbrev layoutPC (z : B.grid.demands) (j : Fin 6) (l : Fin 5) :=
+ pc (.inr (.inl ((z,j), l)))
+
+/-- Placement of the field gather instructions within the full table. -/
+noncomputable abbrev gatherPC : G.Address → Fin p := pc ∘ Sum.inr ∘ Sum.inr
+
+/-- Descriptor writer entry reached after gathering operands for grid point `z` and party `j`. -/
+noncomputable abbrev writer (z : B.grid.demands) (j : Fin 6) :=
+ F.target (handlerPC F (corePC F G pc)) (z,j)
+
+/-- Dispatches a resident item's grid and party to the first row of its layout branch. -/
+noncomputable def gatherCases :=
+ { cases F S (corePC F G pc) common with target := fun z j ↦ layoutPC F G pc z j 0 }
+
+/-- Original reader, loop and matrix rows retain their jumps. The dispatch
+targets now enter the actual layout branch and field gather for each matrix. -/
+noncomputable def gatherText : GatherAddress F G → Instr 5 p r 11
+ | .inl (.inr (.inr (.inl l))) => (gatherCases F G S pc common).text l
+ | .inl l => text F S (corePC F G pc) dfs saved common own ret l
+ | .inr (.inl ((z,j),l)) => ShrinkLayoutBranch.code (layoutPC F G pc z j)
+ ((S.headerReg common) 0) ((S.headerReg common) 10) temp
+ (G.entry (gatherPC F G pc) (writer F G pc) z j) l
+ | .inr (.inr l) => G.text (gatherPC F G pc) dfs saved common gatherReg (writer F G pc) l
+
+/-- Each constituent's link inside this single installed word-RAM table. -/
+structure GatherLinked (M : Machine w p r 11) : Prop where
+ header : MapResidentInputs.HeaderLinked M (inputPC F (corePC F G pc) ∘ Sum.inl)
+ (S.headerReg common) (loopPC F (corePC F G pc) false)
+ item : MapResidentInputs.ItemLinked M (inputPC F (corePC F G pc) ∘ Sum.inr)
+ (S.headerReg common) (casePC F (corePC F G pc) (.inl ()))
+ loop : (loop F S (corePC F G pc) common ret).Linked M
+ dispatch : (gatherCases F G S pc common).Linked M
+ layout : ∀ z j, ShrinkLayoutBranch.Linked M (layoutPC F G pc z j)
+ ((S.headerReg common) 0) ((S.headerReg common) 10) temp
+ (G.entry (gatherPC F G pc) (writer F G pc) z j)
+ gather : ∀ l, M.code (gatherPC F G pc l) =
+ (G.text (gatherPC F G pc) dfs saved common gatherReg (writer F G pc) l).resize w
+ matrix : ∀ l, M.code (handlerPC F (corePC F G pc) l) =
+ (F.text (handlerPC F (corePC F G pc)) dfs saved common own
+ (loopPC F (corePC F G pc) true) l).resize w
+ bad : M.code (badPC F (corePC F G pc)) = .reject
+
+theorem gatherLinked (M : Machine w p r 11) (install : ∀ a, M.code (pc a) =
+ (gatherText F G S pc dfs saved common own gatherReg temp ret a).resize w) :
+ GatherLinked F G S pc dfs saved common own gatherReg temp ret M := by
+ obtain ⟨h, i⟩ := MapResidentInputs.linked M (inputPC F (corePC F G pc)) (S.headerReg common)
+ (loopPC F (corePC F G pc) false) (casePC F (corePC F G pc) (.inl ()))
+ (fun a ↦ install (.inl (.inl a)))
+ refine ⟨h, i, ⟨install (.inl (.inr (.inl false))), install (.inl (.inr (.inl true)))⟩,
+ fun a ↦ install (.inl (.inr (.inr (.inl a)))), ?_, fun a ↦ install (.inr (.inr a)),
+ fun a ↦ install (.inl (.inr (.inr (.inr (.inl a))))),
+ install (.inl (.inr (.inr (.inr (.inr ())))))⟩
+ intro z j l
+ exact (install (.inr (.inl ((z,j),l)))).trans (ShrinkLayoutBranch.resize_code ..)
+
+private noncomputable def number (A : Type*) [Finite A] : A ≃ Fin (Nat.card A) := by
+ classical
+ letI := Fintype.ofFinite A
+ exact Fintype.equivFinOfCardEq Nat.card_eq_fintype_card.symm
+
+/-- Numbers the instruction labels of the map image with both gathers. -/
+noncomputable def gatherLocations := number (GatherAddress F G)
+
+/-- Numbers the registers used by the map image with both gathers. -/
+noncomputable def gatherRegisters := number (GatherRegister F G)
+
+/-- Embeds the role's shared registers into the combined segment's numbered bank. -/
+noncomputable def gatherShared : Fin shared ↪ Fin (Nat.card (GatherRegister F G)) :=
+ Function.Embedding.inl.trans (gatherRegisters F G).toEmbedding
+
+/-- Embeds the map handlers' private registers into the combined segment's numbered bank. -/
+noncomputable def gatherMatrix : F.PrivateReg ↪ Fin (Nat.card (GatherRegister F G)) :=
+ Function.Embedding.inl.trans (Function.Embedding.inr.trans (gatherRegisters F G).toEmbedding)
+
+/-- Embeds the field gathers' private registers into the combined segment's numbered bank. -/
+noncomputable def gatherLocal : G.PrivateReg ↪ Fin (Nat.card (GatherRegister F G)) :=
+ Function.Embedding.inl.trans (Function.Embedding.inr.trans
+ (Function.Embedding.inr.trans (gatherRegisters F G).toEmbedding))
+
+/-- Number of the scratch register that computes the layout field's address and reads its bit. -/
+noncomputable def layoutTemp := gatherRegisters F G (.inr (.inr (.inr ())))
+
+/-- The final-vertex instruction segment for the shrinking map list, including
+the materialization of every physical operand field in its selected layout. -/
+noncomputable def segmentWithGather : VertexImage.Segment where
+ count := Nat.card (GatherAddress F G)
+ privateRegs := Nat.card (GatherRegister F G)
+ entry := inputPC F (corePC F G (gatherLocations F G)) (.inl 0)
+ row place dfs saved locals ret i :=
+ gatherText F G S (place ∘ gatherLocations F G) dfs saved ((gatherShared F G).trans locals)
+ ((gatherMatrix F G).trans locals) ((gatherLocal F G).trans locals)
+ (locals (layoutTemp F G)) ret ((gatherLocations F G).symm i)
+
+theorem gatherSegment_rows (place : Fin (Nat.card (GatherAddress F G)) → Fin p)
+ (locals : Fin (Nat.card (GatherRegister F G)) ↪ Fin r) (M : Machine w p r 11)
+ (h : ∀ a, M.code (place a) =
+ ((segmentWithGather F G S).row place dfs saved locals ret a).resize w)
+ (a : GatherAddress F G) :
+ M.code ((place ∘ gatherLocations F G) a) =
+ (gatherText F G S (place ∘ gatherLocations F G) dfs saved ((gatherShared F G).trans locals)
+ ((gatherMatrix F G).trans locals) ((gatherLocal F G).trans locals)
+ (locals (layoutTemp F G)) ret a).resize w := by
+ simpa [segmentWithGather] using h (gatherLocations F G a)
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherMatrix.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherMatrix.lean
new file mode 100644
index 0000000000..b25fe7c7ce
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherMatrix.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherImage
+import OAI.Computability.VPVNP.PairSimulationMapHandlerFrame
+
+/-!
+# Running one selected party gather and its matrix in the same machine
+
+The operand gather reads the selected stage and produces its exact scratch
+update. The grouped matrix tests those fields, updates the histogram, and
+returns to the row increment. A failed test rules out every returning burst.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.ShrinkSlots
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifGrid MotifBlocks MotifConversion MapHandlerOperand NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w g endAddr : ℕ} (F : MapHandlerImage.Family B t shared)
+ (G : ShrinkGatherBank.Family F) (S : Registers shared) (pc : GatherAddress F G → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r)
+ (own : F.PrivateReg ↪ Fin r) (gatherReg : G.PrivateReg ↪ Fin r) (temp : Fin r) (ret : Fin p)
+ (M : Machine w p r 11) (link : GatherLinked F G S pc dfs saved common own gatherReg temp ret M)
+ (mapApart : F.Apart dfs saved common own) (gatherApart : G.Apart dfs saved common gatherReg)
+ {X : State G.a (packingLaneBits G.a g)} {δ : ℝ}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} {selection : X.ShrinkSelection B}
+ {motif : X.packingData.Motif} (I : LocalHistory.EntryInput B)
+ (J : ShrinkPartyNative.Job X B ready selection motif I.party w)
+ (hw : MapConstants.widthThreshold B ≤ w)
+ (P : Fin 5 → Word w) (st : Word w) (m : Memory w)
+ (W : Workspace F demandMass_pos I) (oldScratch : DFS.Scratch w endAddr)
+
+local notation "side" => selectedLayout X B selection
+local notation "z" => demandGrid B demandMass_pos I.demand
+local notation "key" => (Prod.mk (z) I.party)
+local notation "gTrace" => J.trace (G.operands (key)) (G.node (key)) P st m
+local notation "post" => J.updated endAddr oldScratch
+local notation "raw" => F.action demandMass_pos I hw P st m W endAddr (post)
+local notation "ptr" => PhaseRecipe.Expr.eval P st m (F.base (key))
+local notation "L" => F.layout (key)
+
+/-- Prepend the selected party's gather trace to a successful matrix action on the
+gathered scratch. A rejected matrix entry yields `none`. -/
+noncomputable def gatheredAction : Option (List (Event w) × DFS.Scratch w endAddr) :=
+ (raw).map fun pair ↦ ((gTrace) ++ pair.1, pair.2)
+
+variable {level absolute : Word w} {T U : IncidenceDirectory w} {origin layer pitch : ℕ}
+ {heads : SlotLevel.Heads}
+
+set_option maxHeartbeats 1300000 in
+-- The selected term, typed packet and installed register bank have dependent indices.
+include link mapApart gatherApart in
+/-- The actual installed gather, descriptor writer and selected matrix act on
+a typed job and private packets with independent lower stack and scratch words. -/
+theorem gathered_native (allowed : ℕ → Prop)
+ (sites : ∀ c i, (J.row c i).ReadSafe
+ (ShrinkPartyNative.setups (G.operands (key)) (G.node (key)) G.a G.b I.party side c i)
+ allowed P st m)
+ (old : J.OldPublished (G.operands (key)) P st m level T origin)
+ (next : J.SupplyPublished (G.operands (key)) (G.node (key)) P st m heads absolute U layer pitch)
+ (c : Config w p r)
+ (atGather : c.pc = G.entry (gatherPC F G pc) (writer F G pc) (z) I.party side)
+ (inputs : ∀ j : Fin 5, c.reg (F.inputs dfs saved common (key) j.castSucc) = P j)
+ (stateReg : c.reg (F.inputs dfs saved common (key) (Fin.last 5)) = st)
+ (packets : J.Packets endAddr c.privateMem)
+ (incoming : DFS.scratch endAddr c.privateMem = oldScratch)
+ (readyCall : ∀ out : Config w p r, J.Assembled c.privateMem out.privateMem →
+ MapHandlerOperand.pub F demandMass_pos I dfs saved common out = P →
+ MapHandlerOperand.state F demandMass_pos I dfs saved common out = st →
+ Prepared F demandMass_pos I dfs saved common out m W)
+ (room : Bounds F demandMass_pos I W endAddr (ptr))
+ (histBefore : ∀ l : Fin t, ((W.hist + l.val : ℕ) : Word w).val < J.scratch.staging) :
+ match gatheredAction F G I J hw P st m W oldScratch with
+ | none => ∀ bs, ¬ DFS.Returns M c m bs
+ | some (es, updated) => ∃ out, Prefix M m c out [] es ∧
+ out.pc = loopPC F (corePC F G pc) true ∧ ShrinkRole.Frame dfs endAddr c out ∧
+ (∀ j, out.reg (dfs j) = c.reg (dfs j)) ∧ (∀ j, out.reg (saved j) = c.reg (saved j)) ∧
+ (∀ j, out.reg (common j) = c.reg (common j)) ∧
+ (∀ q, q.val < J.scratch.staging →
+ q.val < (ptr).val ∨ (ptr).val + Fintype.card ShrinkCallFields.Arg ≤ q.val →
+ MapCallSetup.Outside (L).core ((L).corePC (L).locations) W q →
+ out.privateMem q = c.privateMem q) ∧
+ (∀ l : Fin t, out.privateMem ((W.hist + l.val : ℕ) : Word w) =
+ c.privateMem ((W.hist + l.val : ℕ) : Word w) +
+ (((names F demandMass_pos I).getD []).count l : Word w)) ∧
+ DFS.scratch endAddr out.privateMem = updated := by
+ obtain ⟨mid, run, assembled, _, upper, lower, dreg, sreg, creg⟩ :=
+ G.execute_exact (gatherPC F G pc) dfs saved common gatherReg (writer F G pc) (z) J M
+ link.gather gatherApart P st m old next allowed sites c atGather inputs stateReg packets
+ have keep (j : Fin 6) : mid.reg (F.inputs dfs saved common (key) j) =
+ c.reg (F.inputs dfs saved common (key) j) := by
+ unfold MapHandlerImage.Family.inputs
+ rcases F.source (key) j with j | j | j
+ · exact dreg j
+ · exact sreg j
+ · exact creg j
+ have pEq : MapHandlerOperand.pub F demandMass_pos I dfs saved common mid = P :=
+ funext fun j ↦ (keep j.castSucc).trans (inputs j)
+ have sEq : MapHandlerOperand.state F demandMass_pos I dfs saved common mid = st :=
+ (keep (Fin.last 5)).trans stateReg
+ have ptrEq : MapHandlerOperand.addr F demandMass_pos I dfs saved common mid m = (ptr) :=
+ (congrArg (fun x ↦ PhaseRecipe.Expr.eval x
+ (MapHandlerOperand.state F demandMass_pos I dfs saved common mid) m (F.base (key))) pEq).trans
+ (congrArg (fun x ↦ PhaseRecipe.Expr.eval P x m (F.base (key))) sEq)
+ have pre : Prefix M m c mid [] (gTrace) := fun fuel more ↦ run.execute fuel more
+ have preFrame : ShrinkRole.Frame dfs endAddr c mid := ⟨fun j _ ↦ dreg j, lower, run.persistent⟩
+ have postEq : DFS.scratch endAddr mid.privateMem = (post) :=
+ upper.trans (congrArg (J.updated endAddr) incoming)
+ have mat := Prepared.action_native F demandMass_pos I dfs saved common mid m
+ (handlerPC F (corePC F G pc)) own (loopPC F (corePC F G pc) true) M link.matrix mapApart hw
+ W endAddr (post) postEq run.pc (readyCall mid assembled pEq sEq) (ptrEq ▸ room)
+ rw [pEq, sEq] at mat
+ cases h : (raw) with
+ | none =>
+ rw [h] at mat
+ simp only [gatheredAction, h, Option.map_none]
+ exact fun bs hret ↦ mat bs ((pre.returns bs).mp hret)
+ | some pair =>
+ obtain ⟨es, updated⟩ := pair
+ rw [h] at mat
+ obtain ⟨out, ran, atEnd, frame, df, sf, cf, mem, hist, us⟩ := mat
+ simp only [gatheredAction, h, Option.map_some]
+ refine ⟨out, pre.trans ran, atEnd, preFrame.trans frame,
+ fun j ↦ (df j).trans (dreg j), fun j ↦ (sf j).trans (sreg j),
+ fun j ↦ (cf j).trans (creg j), ?_, ?_, us⟩
+ · intro q lo exterior outside
+ exact (mem q (ptrEq ▸ exterior) outside).trans (assembled.below q lo)
+ · intro l
+ exact (hist l).trans (congrArg (fun v : Word w ↦ v + _) (assembled.below _ (histBefore l)))
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherRegisters.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherRegisters.lean
new file mode 100644
index 0000000000..375fc664a0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherRegisters.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherImage
+
+/-!
+# Register separation in the hosted shrinking map segment
+
+The combined register enumeration gives independent locations to the site
+header, private matrix evaluator, each operand gather and the layout scratch.
+Only the host's disjointness from DFS and saved registers is needed below.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open Compression.ShrinkMotif MotifGrid MotifBlocks MotifConversion
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {t shared r : ℕ} (F : MapHandlerImage.Family B t shared) (G : ShrinkGatherBank.Family F)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (locals : Fin (Nat.card (GatherRegister F G)) ↪ Fin r)
+ (dfsApart : ∀ x j, locals x ≠ dfs j) (savedApart : ∀ x j, locals x ≠ saved j)
+
+private theorem local_ne {x y : GatherRegister F G} (h : x ≠ y) :
+ locals (gatherRegisters F G x) ≠ locals (gatherRegisters F G y) :=
+ locals.injective.ne ((gatherRegisters F G).injective.ne h)
+
+include dfsApart savedApart in
+/-- Both native code families receive their true disjoint register bank. -/
+theorem hosted_banks :
+ F.Apart dfs saved ((gatherShared F G).trans locals) ((gatherMatrix F G).trans locals) ∧
+ G.Apart dfs saved ((gatherShared F G).trans locals) ((gatherLocal F G).trans locals) ∧
+ (∀ i, ((gatherShared F G).trans locals) i ≠ locals (layoutTemp F G)) := by
+ refine ⟨⟨fun _ _ ↦ dfsApart _ _, fun _ _ ↦ savedApart _ _, ?_⟩,
+ ⟨fun _ _ ↦ dfsApart _ _, fun _ _ ↦ savedApart _ _, ?_⟩, ?_⟩
+ · intro x j
+ exact local_ne F G locals (x := .inr (.inl x)) (y := .inl j) (by simp)
+ · intro x j
+ exact local_ne F G locals (x := .inr (.inr (.inl x))) (y := .inl j) (by simp)
+ · intro j
+ exact local_ne F G locals (x := .inl j) (y := .inr (.inr (.inr ()))) (by simp)
+
+variable (S : Registers shared) (common : Fin shared ↪ Fin r) (tmp : Fin r)
+
+/-- The item reader writes the motif, party, term pointer and grid, and the
+layout and ordinal branches use two further scratch registers. -/
+def Protected (q : Fin r) : Prop := q ≠ tmp ∧ q ≠ common S.zero ∧
+ ∀ l : Fin 11, 6 ≤ l.val → l.val ≤ 9 → q ≠ (S.headerReg common) l
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherRoute.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherRoute.lean
new file mode 100644
index 0000000000..14a31e33c3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherRoute.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherImage
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherSource
+
+/-!
+# Entering the selected shrinking party's field gather
+
+The count and ID tables use the same ordered list as the compression pass.
+The selected term determines the grid and the old header determines the
+layout. The chronological trace here depends only on those published words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords Compression Compression.ShrinkMotif
+open MotifGrid MotifBlocks MotifConversion MapResidentRows NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w a g : ℕ} (F : MapHandlerImage.Family B t shared)
+ (G : ShrinkGatherBank.Family F) (S : Registers shared)
+ (pc : GatherAddress F G → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r)
+ (own : F.PrivateReg ↪ Fin r) (gatherReg : G.PrivateReg ↪ Fin r) (tmp : Fin r) (ret : Fin p)
+ (M : Machine w p r 11) (link : GatherLinked F G S pc dfs saved common own gatherReg tmp ret M)
+ (X : State a (packingLaneBits a g)) (selection : X.ShrinkSelection B)
+ (side : Bool) (site : Site X) (m : Memory w) (level term : Word w)
+
+/-- Classical equality on base vertices for looking up the selected resident row. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+variable (R : MapRowSource X selection side m level term)
+ (i : Fin (order X side site).length)
+
+set_option maxHeartbeats 4500000 in
+-- The selected term, typed packet and installed register bank have dependent indices.
+include link in
+/-- Execute the real map-ID read, term read, grid and party cases, and layout
+read at the indicated resident-row address. All operand base registers survive. -/
+theorem enterGather (hw : 0 < w) (outside : ∀ b, common b ≠ tmp) (c : Config w p r)
+ (start : c.pc = inputPC F (corePC F G pc) (.inr 0))
+ (cursor : (c.reg ((S.headerReg common) 2)).val =
+ rowCursor X selection side site m level term R i)
+ (head : c.reg ((S.headerReg common) 0) = level)
+ (base : c.reg ((S.headerReg common) 4) = term)
+ (stride : c.reg ((S.headerReg common) 5) = 10)
+ (one : c.reg ((S.headerReg common) 10) = 1) :
+ let reg := S.headerReg common
+ let e := entry X side site i
+ let z := rowGrid (B := B) X side site i
+ ∃ d, Prefix M m c d [] (routeEvents X selection side site m level term R i) ∧
+ d.pc = G.entry (gatherPC F G pc) (writer F G pc) z e.2 side ∧
+ (d.reg (reg 6)).val = (ordinal X e.1).val ∧
+ (d.reg (reg 8)).val = term.val + (ordinal X e.1).val * 10 ∧
+ (∀ q, q ≠ tmp → q ≠ common S.zero →
+ (∀ l : Fin 11, 6 ≤ l.val → l.val ≤ 9 → q ≠ reg l) → d.reg q = c.reg q) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ intro reg e z
+ obtain ⟨d, reads, hp, hm, ht, frame, memory, persistent⟩ :=
+ item_selected F S (corePC F G pc) common M (fun z j ↦ layoutPC F G pc z j 0)
+ link.item link.dispatch X R.first R.fit R.rows site i c start cursor base stride one
+ R.terms R.termFit R.retained
+ change (d.reg (reg 6)).val = (ordinal X e.1).val at hm
+ change (d.reg (reg 8)).val = term.val + (ordinal X e.1).val * 10 at ht
+ have keep (j : Fin 11) (hj : j.val < 6 ∨ 9 < j.val) : d.reg (reg j) = c.reg (reg j) :=
+ frame _ (common.injective.ne (S.apart j).symm) (fun l lo hi ↦ reg.injective.ne (by
+ intro h
+ rw [h] at hj
+ omega))
+ have levelEq := (keep 0 (by decide)).trans head
+ have oneEq := (keep 10 (by decide)).trans one
+ obtain ⟨out, layoutRun, branch, _, savedReg, memEq, perEq⟩ := ShrinkLayoutBranch.native
+ (link.layout z e.2) m d hp hw (outside _) (outside _) oneEq side (by
+ rw [levelEq]
+ exact R.layout)
+ have address : c.reg (reg 2) = (rowCursor X selection side site m level term R i : Word w) := by
+ apply Fin.ext
+ change (c.reg (reg 2)).val = rowCursor X selection side site m level term R i % (2 ^ w)
+ rw [← cursor, Nat.mod_eq_of_lt (c.reg (reg 2)).isLt]
+ refine ⟨out, ?_, branch, ?_, ?_, ?_, memEq.trans memory, perEq.trans persistent⟩
+ · let ticks := List.replicate
+ (1 + ((2 * ((demandOrder B.grid.demands).symm z).val + 1) + (2 * e.2.val + 1)))
+ (.tick : Event w)
+ have readPrefix : Prefix M m c d [] (MapResidentInputs.itemEvents m
+ (c.reg (reg 2)) (c.reg (reg 4)) (c.reg (reg 5)) ++ ticks) := reads
+ have layoutPrefix : Prefix M m d out [] (ShrinkLayoutBranch.events m (d.reg (reg 0))) :=
+ layoutRun
+ let cursorWord := (rowCursor X selection side site m level term R i : Word w)
+ have readEq : MapResidentInputs.itemEvents m (c.reg (reg 2)) (c.reg (reg 4))
+ (c.reg (reg 5)) = MapResidentInputs.itemEvents m cursorWord term 10 :=
+ congr (congr (congrArg (MapResidentInputs.itemEvents m) address) base) stride
+ have eq : (MapResidentInputs.itemEvents m (c.reg (reg 2)) (c.reg (reg 4)) (c.reg (reg 5)) ++
+ ticks) ++ ShrinkLayoutBranch.events m (d.reg (reg 0)) =
+ routeEvents X selection side site m level term R i :=
+ congr (congrArg List.append (congrArg (fun es ↦ es ++ ticks) readEq))
+ (congrArg (ShrinkLayoutBranch.events m) levelEq)
+ exact eq ▸ readPrefix.trans layoutPrefix
+ · exact (congrArg Fin.val (savedReg (reg 6) (outside (S.header 6)))).trans hm
+ · exact (congrArg Fin.val (savedReg (reg 8) (outside (S.header 8)))).trans ht
+ · intro q nt nz nr
+ exact (savedReg q nt).trans (frame q nz nr)
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherSource.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherSource.lean
new file mode 100644
index 0000000000..f87bb832fd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkGatherSource.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkMapItem
+import OAI.Computability.VPVNP.PairSimulationShrinkLayoutBranch
+
+/-!
+# The published shrinking map row and its route trace
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords Compression Compression.ShrinkMotif
+open MotifGrid MotifBlocks MotifConversion MapResidentRows NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {w a g : ℕ}
+ (X : State a (packingLaneBits a g)) (selection : X.ShrinkSelection B)
+ (side : Bool) (site : Site X) (m : Memory w) (level term : Word w)
+
+/-- Classical equality on base vertices for indexing the shrinking directory. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Published data shared by every occurrence of the map list at this site. -/
+structure MapRowSource where
+ /-- First address of the shrinking resident directories. -/
+ first : ℕ
+ fit : (ShrinkResidentLayout.layout X first).endAddr < 2 ^ w
+ rows : Directory X side ((ShrinkResidentLayout.layout X first).params a true w) m
+ /-- Base address of the dense width pairs read by the shrinking term worker. -/
+ dense : Word w
+ /-- Step limit for each burst of the term worker. -/
+ cap : ℕ
+ /-- Public memory before the term worker ran. -/
+ before : Memory w
+ /-- Burst reports from writing the selected term records. -/
+ reports : List (Report w)
+ terms : ShrinkTermSelection.Written B X dense term 10 cap selection before reports
+ termFit : term.val + (LocalHistory.shrinkMotifOrder X).length * 10 ≤ 2 ^ w
+ retained : ∀ x : X.packingData.Motif, m (term.val + (ordinal X x).val * 10) =
+ after before (eventLog reports) (term.val + (ordinal X x).val * 10)
+ layout : m (level + 38).val = (side.toNat : Word w)
+
+variable (R : MapRowSource X selection side m level term)
+ (i : Fin (order X side site).length)
+
+/-- Address of entry `i` in the site's resident list of map IDs. -/
+noncomputable def rowCursor :=
+ ((ShrinkResidentLayout.layout X R.first).params a true w 5).val +
+ (siteIndex X site).val * capacity a + i.val
+
+/-- Demand grid determined by the shrinking widths of the motif in entry `i`. -/
+noncomputable def rowGrid := demandGrid B demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth (entry X side site i).1)
+
+/-- Events for reading the map ID and term, dispatching to the grid and party, and
+reading the layout before the gather begins. -/
+noncomputable def routeEvents :=
+ MapResidentInputs.itemEvents m (rowCursor X selection side site m level term R i : Word w)
+ term 10 ++ List.replicate
+ (1 + ((2 * ((demandOrder B.grid.demands).symm (rowGrid (B := B) X side site i)).val + 1) +
+ (2 * (entry X side site i).2.val + 1))) .tick ++ ShrinkLayoutBranch.events m level
+
+
+section Header
+
+open MotifBlocks MotifConversion MotifGrid Compression.ShrinkMotif MapResidentInputs
+
+variable {d l p r k : ℕ} {Z : State d (packingLaneBits d l)}
+ {factor : ℝ} {F : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {s : Z.ShrinkSelection F} {layout : Bool} {level address : Word w}
+ {mem : Memory w} {M : Machine w p r k}
+
+/-- The linked header enters the map guard with exactly the real cursor,
+exclusive end, term base and stride of this selected site. -/
+theorem MapRowSource.header_native (R : MapRowSource Z s layout mem level address)
+ (site : Site Z) (pc : Fin 16 → Fin p) (reg : Fin 11 ↪ Fin r) (done : Fin p)
+ (link : HeaderLinked M pc reg done) (c : Config w p r) (entry : c.pc = pc 0)
+ (levelReg : c.reg (reg 0) = level) (siteReg : (c.reg (reg 1)).val = (siteIndex Z site).val)
+ (words : Published mem level ((ShrinkResidentLayout.layout Z R.first).params d true w 3)
+ ((ShrinkResidentLayout.layout Z R.first).params d true w 5) address 10)
+ (room : level.val + 37 < 2 ^ w) :
+ let baseRow := ((ShrinkResidentLayout.layout Z R.first).params d true w 5).val +
+ (siteIndex Z site).val * capacity d
+ ∃ out, Prefix M mem c out [] (headerEvents mem level (c.reg (reg 1))) ∧
+ HeaderResult reg done mem c out ∧ out.reg (reg 2) = (baseRow : Word w) ∧
+ out.reg (reg 3) = ((baseRow + (order Z layout site).length : ℕ) : Word w) ∧
+ out.reg (reg 4) = address ∧ out.reg (reg 5) = 10 := by
+ obtain ⟨out, run, result⟩ := MapResidentInputs.header_native link mem c entry
+ rw [levelReg] at run
+ exact ⟨out, run, result, result.directory Z R.first R.fit R.rows site siteReg address
+ (levelReg ▸ words) (levelReg ▸ room)⟩
+
+end Header
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkLayoutBranch.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkLayoutBranch.lean
new file mode 100644
index 0000000000..62eb1f0ce9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkLayoutBranch.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.PairNodeChildLoop
+
+/-!
+# Selecting the resident shrinking layout
+
+The old level's field at offset 38 holds the chosen layout bit. The
+vertex reader doubles the five-bit literal 19 to obtain that offset,
+reads the published field and enters the matching gather continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkLayoutBranch
+
+open BurstRAM BurstRAM.PrivateRAM NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.read ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r k : ℕ}
+
+/-- Compute the layout field's address, read it, and branch on its word. -/
+def code (pc : Fin 5 → Fin p) (head one tmp : Fin r) (target : Bool → Fin p) :
+ Fin 5 → Instr w p r k :=
+ ![.constant tmp 19 (pc 1), .binary .add tmp tmp tmp (pc 2),
+ .binary .add tmp head tmp (pc 3), .readExternal tmp tmp (pc 4),
+ .jumpEq tmp one (target true) (target false)]
+
+theorem resize_code (pc : Fin 5 → Fin p) (head one tmp : Fin r) (target : Bool → Fin p)
+ (i : Fin 5) :
+ (code (w := 5) (k := k) pc head one tmp target i).resize w = code pc head one tmp target i := by
+ fin_cases i <;> rfl
+
+/-- Installation of the five instructions at their relocatable labels. -/
+def Linked (M : Machine w p r k) (pc : Fin 5 → Fin p) (head one tmp : Fin r)
+ (target : Bool → Fin p) : Prop := ∀ i, M.code (pc i) = code pc head one tmp target i
+
+/-- Chronological events on the external memory supplied to the vertex call. -/
+def events (mem : Memory w) (head : Word w) : List (Event w) :=
+ [.tick, .tick, .tick, .read (head + 38) (mem (head + 38).val), .tick]
+
+theorem cost (mem : Memory w) (head : Word w) :
+ (events mem head).length = 5 ∧ countProbes (events mem head) = 1 ∧
+ choiceBits (events mem head) = [] := ⟨rfl,rfl,rfl⟩
+
+variable {M : Machine w p r k} {pc : Fin 5 → Fin p} {head one tmp : Fin r} {target : Bool → Fin p}
+
+private theorem step_at (hl : Linked M pc head one tmp target) (i : Fin 5) {c : Config w p r}
+ (hc : c.pc = pc i) : M.program.step c = (code pc head one tmp target i).run M.publicData c := by
+ simp [Machine.program, hc, hl i]
+
+/-- The physical field selects its designated continuation. The scratch
+register receives the read word. Every other register and both kinds of
+caller state survive the branch. -/
+theorem native (hl : Linked M pc head one tmp target) (mem : Memory w) (c : Config w p r)
+ (start : c.pc = pc 0) (hw : 0 < w) (hhead : head ≠ tmp) (hone : one ≠ tmp)
+ (unit : c.reg one = 1) (side : Bool)
+ (published : mem (c.reg head + 38).val = (side.toNat : Word w)) :
+ ∃ d, Prefix M mem c d [] (events mem (c.reg head)) ∧ d.pc = target side ∧
+ d.reg tmp = (side.toNat : Word w) ∧ (∀ a, a ≠ tmp → d.reg a = c.reg a) ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ let addr := c.reg head + 38
+ let a := c.put (pc 1) tmp 19
+ let b := a.put (pc 2) tmp 38
+ let e := b.put (pc 3) tmp addr
+ let f := e.put (pc 4) tmp (mem addr.val)
+ let d := {f with pc := target side}
+ have s₀ : M.program.step c = .localStep a := step_at hl 0 start
+ have dbl : (19 : Word w) + 19 = 38 := (Nat.cast_add (R := Word w) 19 19).symm
+ have s₁ : M.program.step a = .localStep b := by
+ rw [step_at hl 1 (by rfl)]
+ change CallAction.localStep (a.put _ tmp (a.reg tmp + a.reg tmp)) = _
+ rw [show a.reg tmp = 19 from Config.put_same .., dbl]
+ have s₂ : M.program.step b = .localStep e := by
+ rw [step_at hl 2 (by rfl)]
+ change CallAction.localStep (b.put _ tmp (b.reg head + b.reg tmp)) = _
+ simp [a,b,e,addr,Config.put,Function.update_of_ne hhead]
+ have s₃ : M.program.step e = .read addr (fun x ↦ e.put (pc 4) tmp x) := by
+ rw [step_at hl 3 (by rfl)]
+ change CallAction.read (e.reg tmp) _ = _
+ rw [show e.reg tmp = addr from Config.put_same ..]
+ have word : f.reg tmp = (side.toNat : Word w) := (Config.put_same ..).trans published
+ have oneEq : f.reg one = 1 := by
+ simp [f,e,b,a,Config.put,Function.update_of_ne hone,unit]
+ have s₄ : M.program.step f = .localStep d := by
+ rw [step_at hl 4 (by rfl)]
+ change CallAction.localStep {f with pc := if f.reg tmp = f.reg one then _ else _} = _
+ rw [word,oneEq]
+ cases side with
+ | false =>
+ have ne : (0 : Word w) ≠ 1 := by
+ intro eq
+ have val := congrArg Fin.val eq
+ have lt : 1 < 2^w := Nat.one_lt_pow (by omega) (by decide)
+ change 0 = 1 % (2^w) at val
+ rw [Nat.mod_eq_of_lt lt] at val
+ omega
+ simp [d, ne]
+ | true => simp [d]
+ have path : ReadPrefix M mem c (events mem (c.reg head)) d :=
+ ReadPrefix.tick s₀ (ReadPrefix.tick s₁ (ReadPrefix.tick s₂
+ (ReadPrefix.read addr s₃ (ReadPrefix.tick s₄ (ReadPrefix.nil d)))))
+ refine ⟨d, ?_, rfl, word, ?_, rfl, rfl⟩
+ · intro fuel bs
+ exact ReadPrefix.execute path fuel bs
+ · intro j hj
+ simp [d,f,e,b,a,Config.put,Function.update_of_ne hj]
+
+end PairSimulation.ShrinkLayoutBranch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkLiveOperands.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkLiveOperands.lean
new file mode 100644
index 0000000000..9996288e12
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkLiveOperands.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherRegisters
+import OAI.Computability.VPVNP.PairSimulationMapHandlerOperand
+
+/-!
+# Operands carried through a shrinking-map list
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords Compression Compression.ShrinkMotif
+open MotifGrid MotifBlocks MotifConversion MapHandlerOperand
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w a b g endAddr : ℕ} (F : MapHandlerImage.Family B t shared)
+ (S : Registers shared) (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r)
+ (common : Fin shared ↪ Fin r) (tmp : Fin r)
+ {X : State a (packingLaneBits a g)} {δ : ℝ}
+ {ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ} {sel : X.ShrinkSelection B}
+ {motif : X.packingData.Motif} (I : LocalHistory.EntryInput B)
+ (J : ShrinkPartyNative.Job X B ready sel motif I.party w)
+ (P : Fin 5 → Word w) (st : Word w) (m : Memory w) (level term : Word w)
+ (W : Workspace F demandMass_pos I) (inv : Word w → Config w p r → Prop)
+
+local notation "reg" => S.headerReg common
+local notation "key" => Prod.mk (demandGrid B demandMass_pos I.demand) I.party
+
+/-- Live words and protected packet geometry after the child and absorbed-bit scans. -/
+structure LiveOperands (node : Word w) (c : Config w p r) : Prop where
+ head : c.reg ((reg) 0) = level
+ base : c.reg ((reg) 4) = term
+ stride : c.reg ((reg) 5) = 10
+ one : c.reg ((reg) 10) = 1
+ pubWords : ∀ j : Fin 5, c.reg (F.inputs dfs saved common (key) j.castSucc) = P j
+ packets : J.Packets endAddr c.privateMem
+ prepare : ∀ out : Config w p r, J.Assembled c.privateMem out.privateMem →
+ MapHandlerOperand.pub F demandMass_pos I dfs saved common out = P →
+ MapHandlerOperand.state F demandMass_pos I dfs saved common out = st →
+ Prepared F demandMass_pos I dfs saved common out m W
+ preserve : ∀ out : Config w p r, (∀ j, Protected S common tmp (common j) →
+ out.reg (common j) = c.reg (common j)) →
+ (∀ q, q.val < J.scratch.staging →
+ q.val < (PhaseRecipe.Expr.eval P st m (F.base (key))).val ∨
+ (PhaseRecipe.Expr.eval P st m (F.base (key))).val +
+ Fintype.card ShrinkCallFields.Arg ≤ q.val →
+ MapCallSetup.Outside (F.layout (key)).core ((F.layout (key)).corePC
+ (F.layout (key)).locations) W q → out.privateMem q = c.privateMem q) → inv node out
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapCompiledSource.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapCompiledSource.lean
new file mode 100644
index 0000000000..55c41acaa9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapCompiledSource.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkMapRowRetention
+import OAI.Computability.VPVNP.PairSimulationShrinkMapTermReadback
+import OAI.Computability.VPVNP.PairSimulationShrinkMapVertexMemory
+import OAI.Computability.VPVNP.CompressorCompiledResident
+import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory
+import OAI.Computability.VPVNP.CompressorShrinkScoreOperands
+
+/-!
+# The actual compiled shrinking map source at a selected vertex
+
+The compiled payload records the native term run of its producing occurrence
+and retains the grid ordinal of each of its selected motifs. The resident map
+and term heads in that same payload are the words read by the shrinking map
+segment. The final vertex frame preserves these operands at every ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM Compression CompressorRecords DescriptorSpace MapResidentRows LocalHistory
+open scoped Fin.CommRing
+
+variable {w : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ (base : Word w) (positions blocks n cur : ℕ) (i : Fin S.steps) {g : ℕ}
+ (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g))
+ (sel : SelectedScore.Selection B X)
+
+private noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+local notation "lay" => BlockProgram.layout B base.val positions blocks
+local notation "head" => levelStart lay cur
+local notation "next" => levelStart lay (cur + 1)
+local notation "tab" => (fun j : Fin 6 => tableBase lay cur j)
+local notation "term" => ShrinkInput.termHead (w := w) X (tab 0)
+local notation "bank" => ShrinkResidentLayout.layout X (tab 5)
+local notation "side" => SelectedFinish.chosen B X sel
+local notation "inc" => packedIncidence lay w cur (DemandRAM.oldCount X)
+
+open private grid_word_eq from OAI.Computability.VPVNP.PairSimulationShrinkMapTermReadback
+
+/-- Extract the map arrays, term records and descriptor from one compiled
+shrinking payload. The certificate for the term words is the actual run stored
+by the producer, with its original input memory and chronological reports. -/
+theorem mapRowSource_compiled {m : Memory w}
+ (payload : CompiledResident.ShrinkPayload B base positions blocks n cur i X sel m) :
+ let p := (bank).params (ShrinkBlockInputs.a i) true w
+ ∃ R : MapRowSource X sel side m (head : Word w) term,
+ R.first = tab 5 ∧ R.InLevel lay cur ∧
+ MapResidentInputs.Published m (head : Word w) (p 3) (p 5) term 10 := by
+ have bounds := payload.bounds
+ have words := payload.words
+ have room := words.oldRoom
+ have levelVal : (head : Word w).val = head := Nat.mod_eq_of_lt (by omega)
+ have low (j : Fin 6) : head + 65 < tab j := by
+ change head + 65 < head + 66 + 6 * slotCapacity lay + j.val * tableWords lay
+ omega
+ have firstEnd : tab 1 ≤ next :=
+ (Nat.le_add_right ..).trans (tableEnd_le_nextLevel lay cur (1 : Fin 6))
+ have termLow := (low 0).le.trans (ScorePackets.start_le_term i X (tab 0) bounds.termRoom)
+ have nextRoom := (levelStart_mono lay bounds.nextLive.le).trans_lt bounds.room
+ have rowFit := bounds.residentEnd.trans_lt nextRoom
+ have termHigh : (term).val + (shrinkMotifOrder X).length * 10 ≤ next := by
+ apply le_trans _ (bounds.termBefore.trans firstEnd)
+ rw [show (shrinkMotifOrder X).length =
+ ShrinkTermSelection.bundles X * ShrinkTermSelection.ranks (ShrinkBlockInputs.a i) from
+ ShrinkTermSelection.motifCount_eq X]
+ exact Nat.add_le_add_right (Nat.mod_le ..) _
+ obtain ⟨dense, fuel, before, reports, written⟩ := payload.termRun
+ have grid (e : X.packingData.Motif) :
+ m ((term).val + (ordinal X e).val * 10) =
+ after before (eventLog reports) ((term).val + (ordinal X e).val * 10) := by
+ have fits : (term).val + (ordinal X e).val * 10 < 2 ^ w := by
+ have epos := (ordinal X e).isLt
+ exact lt_of_lt_of_le (by omega) nextRoom.le
+ have addr : (ShrinkTermSelection.rowBase X term 10 e).val =
+ (term).val + (ordinal X e).val * 10 := Nat.mod_eq_of_lt fits
+ have live := (payload.sources.terms e).1
+ have source := (written.fields e).1
+ rw [addr] at live source
+ exact grid_word_eq live source
+ let params := (bank).params (ShrinkBlockInputs.a i) true w
+ have p : MapResidentInputs.Published m (head : Word w) (params 3) (params 5) term 10 := by
+ have pos (j : ℕ) (hj : j ≤ 65) : ((head : Word w) + (j : Word w)).val = head + j := by
+ rw [← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ refine ⟨?_, ?_, ?_, ?_⟩
+ · rw [levelVal]
+ exact words.residentHeads 4
+ · rw [levelVal]
+ exact words.residentHeads 5
+ · rw [levelVal, ← pos 36 (by decide)]
+ exact words.level.termHead
+ · rw [levelVal, ← pos 37 (by decide)]
+ exact words.level.termStride
+ let R : MapRowSource X sel side m (head : Word w) term :=
+ ⟨tab 5, rowFit, payload.sources.residents true, dense, fuel, before, reports, written,
+ termHigh.trans nextRoom.le, grid, words.level.layout⟩
+ have floor : levelsBase lay ≤ head := Nat.le_add_right ..
+ refine ⟨R, rfl, ⟨levelVal, ?_, ?_, ?_, bounds.residentEnd, ?_, termHigh⟩, p⟩
+ · rw [levelVal]
+ exact (by omega : head + 38 ≤ head + 65).trans_lt ((low 1).trans_le firstEnd)
+ · rw [levelVal]
+ omega
+ · exact (floor.trans (Nat.le_add_right ..)).trans (low 5).le
+ · exact (floor.trans (Nat.le_add_right ..)).trans termLow
+
+section Vertex
+
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TraversalRows
+
+variable {G : Group} {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes) (start : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT start).Choices)
+
+local notation "vs" => executeLevels B f hf T hT start z
+local notation "pub" => terminalOperands G
+set_option quotPrecheck false in
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val positions T
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT start) z
+
+/-- Read the actual row certificate at an arbitrary later final-site call of
+the packed terminal program, identifying the producing pass by its selected
+occurrence in the executed history. -/
+theorem mapRowSource_vertex (j : Fin (vs).length) (tape : List Bool)
+ (occurrence : vs[j] = shrinkLevel B f hf i X sel tape)
+ {table : Fin (D).shape.tables} {baseBits laneBits cap width ord : ℕ}
+ {roles : List TraversalRoles.TaggedLayer} {calendar reference phy : Memory G.w}
+ {bits : Fin (Y).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf D
+ (CompiledResident.payload B f hf (pub 2) positions T n) vs calendar)
+ (entry : TerminalProgram.VertexEntry B f hf T hT start z D table baseBits laneBits pub
+ calendar reference bits)
+ (packed : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord phy) :
+ let level := (levelStart D j.val : Word G.w)
+ let first := tableBase D j.val (5 : Fin 6)
+ let selectedTerm := ShrinkInput.termHead (w := G.w) X (tableBase D j.val (0 : Fin 6))
+ let p := (ShrinkResidentLayout.layout X first).params (ShrinkBlockInputs.a i) true G.w
+ ∃ R : MapRowSource X sel side phy level selectedTerm, R.first = first ∧
+ MapResidentInputs.Published phy level (p 3) (p 5) selectedTerm 10 := by
+ have own := CompiledResident.read history j
+ rw [occurrence] at own
+ have payload := (CompiledResident.shrink_payload ..).mp own
+ obtain ⟨R, first, bounds, heads⟩ :=
+ mapRowSource_compiled B (pub 2) positions T n j.val i X sel payload
+ have agree := entry.packedLevelWindow packed frame j
+ exact ⟨R.transport bounds agree, first, R.published bounds heads agree⟩
+
+end Vertex
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapImage.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapImage.lean
new file mode 100644
index 0000000000..ba493d3570
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapImage.lean
@@ -0,0 +1,173 @@
+import OAI.Computability.VPVNP.PairSimulationMapHandlerImage
+import OAI.Computability.VPVNP.PairSimulationMapResidentInputs
+import OAI.Computability.VPVNP.PairSimulationResidentDispatchImage
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoop
+import Mathlib.Data.List.NodupEquivFin
+
+/-!
+# The shrinking node's resident map loop in one finite instruction bank
+
+The count reader and each item reader feed the actual grid and party chains.
+Their targets are the lowered, descriptor-writing map handlers. Successful
+entries return to the common row increment; exhausting the row reaches the
+role continuation. All emitted instructions use the live five-bit literal format.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage
+
+open BurstRAM BurstRAM.PrivateRAM Compression.ShrinkMotif MotifSelector MotifGrid
+open MotifBlocks MotifConversion MapHandlerImage
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w : ℕ} (F : MapHandlerImage.Family B t shared)
+
+/-- Exactly the order of the grid numbers written by the selected-term worker. -/
+noncomputable def demandOrder (s : Finset K) : Fin s.toList.length ≃ s := by
+ classical
+ exact (List.Nodup.getEquiv s.toList s.nodup_toList).trans
+ (Equiv.subtypeEquivRight (fun _ ↦ Finset.mem_toList))
+
+/-- Instruction labels for the resident readers, loop, dispatcher, map handlers, and reject row. -/
+noncomputable abbrev Address := MapResidentInputs.Address ⊕ Bool ⊕
+ ResidentDispatchImage.Address B.grid.demands (Fin 6) ⊕ F.Address ⊕ Unit
+
+/-- The eleven header registers have their resident reader roles. The extra
+zero register serves the ordinal dispatcher and lies outside that reader bank. -/
+structure Registers (shared : ℕ) where
+ /-- Placement of the eleven reader registers in the shared bank. -/
+ header : Fin 11 ↪ Fin shared
+ /-- Shared register used for zero by the grid and party dispatcher. -/
+ zero : Fin shared
+ apart : ∀ i, zero ≠ header i
+
+namespace Registers
+
+variable (S : Registers shared) (loc : Address F → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r) (own : F.PrivateReg ↪ Fin r)
+ (done : Fin p)
+
+/-- Machine address of an instruction in the resident header or item reader. -/
+def inputPC (a : MapResidentInputs.Address) := loc (.inl a)
+
+/-- Machine address of a grid or party dispatch instruction. -/
+def casePC (a : ResidentDispatchImage.Address B.grid.demands (Fin 6)) := loc (.inr (.inr (.inl a)))
+
+/-- Machine address of a descriptor writer or map instruction in the handler family. -/
+noncomputable def handlerPC (a : F.Address) := loc (.inr (.inr (.inr (.inl a))))
+
+/-- Machine address of the cursor test (`false`) or increment (`true`). -/
+def loopPC (b : Bool) := loc (.inr (.inl b))
+
+/-- Reject address for a grid or party ordinal outside the dispatch table. -/
+def badPC := loc (.inr (.inr (.inr (.inr ()))))
+
+/-- Physical register assignment for the eleven resident reader registers. -/
+def headerReg : Fin 11 ↪ Fin r := S.header.trans common
+
+/-- Dispatches the grid and party ordinals read from an item to its descriptor writer. -/
+noncomputable def cases : ResidentDispatchImage.Image B.grid.demands (Fin 6)
+ B.grid.demands.toList.length 6 p r where
+ grids := demandOrder B.grid.demands
+ parties := Equiv.refl _
+ place := casePC F loc
+ target z j := F.target (handlerPC F loc) (z, j)
+ bad := badPC F loc
+ grid := (S.headerReg common) 9
+ party := (S.headerReg common) 7
+ zero := common S.zero
+ one := (S.headerReg common) 10
+
+/-- Tests the reader's cursor against the end of the row and advances it after each handler. -/
+noncomputable def loop : ResidentMapLoop.Program p r where
+ test := loopPC F loc false
+ advance := loopPC F loc true
+ item := inputPC F loc (.inr 0)
+ done := done
+ cursor := (S.headerReg common) 2
+ stop := (S.headerReg common) 3
+ one := (S.headerReg common) 10
+ stopApart := (S.headerReg common).injective.ne (by decide)
+ oneApart := (S.headerReg common).injective.ne (by decide)
+
+theorem distinct : (cases F S loc common).Distinct := by
+ constructor
+ · exact common.injective.ne (S.apart 9)
+ · exact common.injective.ne (S.apart 7)
+ · exact (S.headerReg common).injective.ne (by decide)
+ · exact (S.headerReg common).injective.ne (by decide)
+ · exact common.injective.ne (S.apart 10).symm
+ · exact (S.headerReg common).injective.ne (by decide)
+
+/-- Five-bit instructions for one resident map row scan, including all dispatch targets. -/
+noncomputable def text : Address F → Instr 5 p r 11
+ | .inl a => MapResidentInputs.text (inputPC F loc) (S.headerReg common)
+ (loopPC F loc false) (casePC F loc (.inl ())) a
+ | .inr (.inl b) => (loop F S loc common done).control b
+ | .inr (.inr (.inl a)) => (cases F S loc common).text a
+ | .inr (.inr (.inr (.inl a))) =>
+ F.text (handlerPC F loc) dfs saved common own (loopPC F loc true) a
+ | .inr (.inr (.inr (.inr _))) => .reject
+
+/-- Placing the one fixed table supplies the four program links and the
+complete handler family rows, with no condition on the external memory. -/
+theorem linked (M : Machine w p r 11)
+ (rows : ∀ a, M.code (loc a) = (text F S loc dfs saved common own done a).resize w) :
+ MapResidentInputs.HeaderLinked M (inputPC F loc ∘ Sum.inl) (S.headerReg common)
+ (loopPC F loc false) ∧
+ MapResidentInputs.ItemLinked M (inputPC F loc ∘ Sum.inr) (S.headerReg common)
+ (casePC F loc (.inl ())) ∧
+ (loop F S loc common done).Linked M ∧ (cases F S loc common).Linked M ∧
+ (∀ a, M.code (handlerPC F loc a) =
+ (F.text (handlerPC F loc) dfs saved common own (loopPC F loc true) a).resize w) ∧
+ M.code (badPC F loc) = .reject := by
+ obtain ⟨header, item⟩ := MapResidentInputs.linked M (inputPC F loc) (S.headerReg common)
+ (loopPC F loc false) (casePC F loc (.inl ())) (fun a ↦ rows (.inl a))
+ exact ⟨header, item, ⟨rows (.inr (.inl false)), rows (.inr (.inl true))⟩,
+ fun a ↦ rows (.inr (.inr (.inl a))), fun a ↦ rows (.inr (.inr (.inr (.inl a)))),
+ rows (.inr (.inr (.inr (.inr ()))))⟩
+
+/-- Numbering of the complete resident-map portion, independent of the input length. -/
+noncomputable def locations : Address F ≃ Fin (Nat.card (Address F)) := by
+ classical
+ letI := Fintype.ofFinite (Address F)
+ exact Fintype.equivFinOfCardEq Nat.card_eq_fintype_card.symm
+
+/-- Embeds the role's shared registers into the segment's numbered register bank. -/
+noncomputable def sharedRegs : Fin shared ↪ Fin (Nat.card (Fin shared ⊕ F.PrivateReg)) :=
+ Function.Embedding.inl.trans F.registers.toEmbedding
+
+/-- Embeds the handlers' private registers into the segment's numbered register bank. -/
+noncomputable def mapRegs : F.PrivateReg ↪ Fin (Nat.card (Fin shared ⊕ F.PrivateReg)) :=
+ Function.Embedding.inr.trans F.registers.toEmbedding
+
+/-- A segment compatible with the final-vertex image. The caller's level
+and packed-site inputs are its header registers zero and one. -/
+noncomputable def segment : VertexImage.Segment where
+ count := Nat.card (Address F)
+ privateRegs := Nat.card (Fin shared ⊕ F.PrivateReg)
+ entry := inputPC F (locations F) (.inl 0)
+ row place dfs saved locals ret i := text F S (place ∘ locations F) dfs saved
+ ((sharedRegs F).trans locals) ((mapRegs F).trans locals) ret ((locations F).symm i)
+
+/-- Recover the typed opcode rows inside any installation of this whole segment. -/
+theorem segment_rows (place : Fin (Nat.card (Address F)) → Fin p)
+ (locals : Fin (Nat.card (Fin shared ⊕ F.PrivateReg)) ↪ Fin r) (M : Machine w p r 11)
+ (h : ∀ a, M.code (place a) = ((segment F S).row place dfs saved locals done a).resize w)
+ (a : Address F) : M.code ((place ∘ locations F) a) =
+ (text F S (place ∘ locations F) dfs saved ((sharedRegs F).trans locals)
+ ((mapRegs F).trans locals) done a).resize w := by
+ simpa [segment] using h (locations F a)
+
+end Registers
+end PairSimulation.ShrinkMapImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapItem.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapItem.lean
new file mode 100644
index 0000000000..f0d72c23aa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapItem.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkMapImage
+import OAI.Computability.VPVNP.PairSimulationMapResidentRows
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+
+/-!
+# Dispatching one map of the actual shrinking directory
+
+A genuine packed row gives the dense motif ordinal, party and term-record
+address. Its first term word selects the same demand-grid point used by the
+six-party conversion evaluator. The external reads and all subsequent private
+branches below are actual instructions of the combined shrinking map image.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord CompressorRecords Compression
+open MotifGrid MotifBlocks MotifConversion ShrinkMotif MapResidentRows NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w a g : ℕ} (F : MapHandlerImage.Family B t shared)
+ (S : Registers shared) (loc : Address F → Fin p)
+ (common : Fin shared ↪ Fin r) (M : Machine w p r 11)
+ (target : B.grid.demands → Fin 6 → Fin p)
+ (item : MapResidentInputs.ItemLinked M (inputPC F loc ∘ Sum.inr) (S.headerReg common)
+ (casePC F loc (.inl ())))
+ (dispatch : ({ cases F S loc common with target := target }).Linked M)
+ (X : State a (packingLaneBits a g)) {layout : Bool} {m : Memory w}
+ {dense term : Word w} {cap : ℕ} {s : X.ShrinkSelection B}
+ {before : Memory w} {rs : List (Report w)}
+
+private theorem word_of_val {x : Word w} {n : ℕ} (h : x.val = n) : x = (n : Word w) := by
+ apply Fin.ext
+ rw [← h]
+ exact (Nat.mod_eq_of_lt x.isLt).symm
+
+open Classical in
+include item dispatch in
+/-- The item and dispatch prefix ends at the real writer of the intended
+`(z,j)` matrix. It preserves the motif and term pointers needed by that writer. -/
+theorem item_selected (first : ℕ) (fit : (ShrinkResidentLayout.layout X first).endAddr < 2 ^ w)
+ (rows : Directory X layout ((ShrinkResidentLayout.layout X first).params a true w) m)
+ (site : Site X) (i : Fin (order X layout site).length) (c : Config w p r)
+ (hc : c.pc = inputPC F loc (.inr 0))
+ (cursor : (c.reg ((S.headerReg common) 2)).val =
+ ((ShrinkResidentLayout.layout X first).params a true w 5).val +
+ (siteIndex X site).val * capacity a + i.val)
+ (headReg : c.reg ((S.headerReg common) 4) = term)
+ (strideReg : c.reg ((S.headerReg common) 5) = 10)
+ (one : c.reg ((S.headerReg common) 10) = 1)
+ (terms : ShrinkTermSelection.Written B X dense term 10 cap s before rs)
+ (termFit : term.val + (LocalHistory.shrinkMotifOrder X).length * 10 ≤ 2 ^ w)
+ (retained : ∀ x : X.packingData.Motif, m (term.val + (ordinal X x).val * 10) =
+ after before (eventLog rs) (term.val + (ordinal X x).val * 10)) :
+ let reg := S.headerReg common
+ let e := entry X layout site i
+ let z := demandGrid B demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth e.1)
+ let code := (demandOrder B.grid.demands).symm z
+ let es := MapResidentInputs.itemEvents m (c.reg (reg 2)) (c.reg (reg 4)) (c.reg (reg 5)) ++
+ List.replicate (1 + ((2 * code.val + 1) + (2 * e.2.val + 1))) .tick
+ ∃ d, NodeArguments.ChildScan.Prefix M m c d [] es ∧
+ d.pc = target z e.2 ∧
+ (d.reg (reg 6)).val = (ordinal X e.1).val ∧
+ (d.reg (reg 8)).val = term.val + (ordinal X e.1).val * 10 ∧
+ (∀ q, q ≠ common S.zero → (∀ l : Fin 11, 6 ≤ l.val → l.val ≤ 9 → q ≠ reg l) →
+ d.reg q = c.reg q) ∧ d.privateMem = c.privateMem ∧ d.persistent = c.persistent := by
+ intro reg e z code es
+ obtain ⟨m₁, read, info⟩ := MapResidentInputs.item_native item m c hc
+ obtain ⟨hm, hj, ht, hz⟩ := MapResidentInputs.ItemResult.selected X B info first fit rows site i
+ cursor headReg strideReg terms termFit retained
+ obtain ⟨hgrid, hval⟩ := List.getElem?_eq_some_iff.mp hz
+ let idx : Fin B.grid.demands.toList.length := ⟨(m₁.reg (reg 9)).val, hgrid⟩
+ have heq : demandOrder B.grid.demands idx = z := Subtype.ext hval
+ have iEq : idx = code := (demandOrder B.grid.demands).eq_symm_apply.mpr heq
+ have gv : (m₁.reg (reg 9)).val = code.val := congrArg Fin.val iEq
+ have one' : m₁.reg (reg 10) = 1 := (info.frame _ (fun l _ hi ↦ reg.injective.ne
+ (by intro eq; have h := congrArg Fin.val eq; change 10 = l.val at h; omega))).trans one
+ let C := { cases F S loc common with target := target }
+ have apart := distinct F S loc common
+ have apartC : C.Distinct := ⟨apart.gz, apart.pz, apart.go', apart.po, apart.oz, apart.pg⟩
+ obtain ⟨out, tail, outPC, frame, memory, persistent⟩ := C.native M dispatch
+ apartC code e.2 (gv ▸ (m₁.reg (reg 9)).isLt)
+ (hj ▸ (m₁.reg (reg 7)).isLt) m₁ info.pc (word_of_val gv) (word_of_val hj) one'
+ have next : NodeArguments.ChildScan.Prefix M m m₁ out []
+ (List.replicate (1 + ((2 * code.val + 1) + (2 * e.2.val + 1))) .tick) := by
+ intro fuel bs
+ have noBits (n : ℕ) : choiceBits (List.replicate n (.tick : Event w)) = [] := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa only [List.replicate_succ, choiceBits] using ih
+ simpa only [noBits, List.nil_append] using tail.execute fuel m bs
+ have untouched (l : Fin 11) (ng : l ≠ 9) (np : l ≠ 7) : out.reg (reg l) = m₁.reg (reg l) :=
+ frame _ (common.injective.ne (S.apart l).symm) (reg.injective.ne ng) (reg.injective.ne np)
+ refine ⟨out, read.trans next, ?_, ?_, ?_, ?_, memory.trans info.memory,
+ persistent.trans info.persistent⟩
+ · simpa [C, cases, code] using outPC
+ · rw [untouched 6 (by decide) (by decide), hm]
+ · rw [untouched 8 (by decide) (by decide), ht]
+ · intro q zero other
+ exact (frame _ zero (other 9 (by decide) (by decide)) (other 7 (by decide) (by decide))).trans
+ (info.frame _ other)
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapRowRetention.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapRowRetention.lean
new file mode 100644
index 0000000000..42de00a265
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapRowRetention.lean
@@ -0,0 +1,272 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherSource
+import OAI.Computability.VPVNP.PairTraversalResidentHandoff
+
+/-!
+# Retaining the shrinking map row on a chronological branch
+
+The site counters, map IDs, first term words, and five header words read by the
+shrinking map loop all lie between the level arena's base and the next level.
+The later selected passes write outside this interval. The terminal prefix
+preserves it as well.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords DescriptorSpace
+open MotifGrid MotifBlocks MotifConversion MapResidentRows
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {w a g : ℕ} {X : State a (packingLaneBits a g)} {selection : X.ShrinkSelection B}
+ {side : Bool} {m out : Memory w} {level term : Word w}
+
+/-- Classical decidable equality on the compression state’s base vertices for retaining the
+resident map rows across later passes. -/
+noncomputable local instance rowRetentionDecidableBase : DecidableEq X.Base := Classical.decEq _
+
+namespace MapRowSource
+
+variable (R : MapRowSource X selection side m level term)
+
+/-- The current allocation bounds the term array, both resident arrays, and
+the complete group of header words consumed by the native reader. -/
+structure InLevel (L : Layout) (j : ℕ) : Prop where
+ head : level.val = levelStart L j
+ headerEnd : level.val + 38 < levelStart L (j + 1)
+ word : level.val + 38 < 2 ^ w
+ firstStart : levelsBase L ≤ R.first
+ rowsEnd : (ShrinkResidentLayout.layout X R.first).endAddr ≤ levelStart L (j + 1)
+ termStart : levelsBase L ≤ term.val
+ termEnd : term.val + (LocalHistory.shrinkMotifOrder X).length * 10 ≤ levelStart L (j + 1)
+
+variable {L : Layout} {j : ℕ}
+
+/-- A later worker that frames the allocated resident bank preserves every
+site's counter and every ID in its ordered fiber. -/
+theorem directory_of_frame (first : ℕ) (fit : (ShrinkResidentLayout.layout X first).endAddr < 2 ^ w)
+ (directory : Directory X side ((ShrinkResidentLayout.layout X first).params a true w) m)
+ (agree : ∀ x, first ≤ x → x < (ShrinkResidentLayout.layout X first).endAddr → out x = m x) :
+ Directory X side ((ShrinkResidentLayout.layout X first).params a true w) out := by
+ let D := ShrinkResidentLayout.layout X first
+ let p := D.params a true w
+ obtain ⟨_, _, _, _, countAt, capAt, rowAt⟩ :=
+ ShrinkResidentLayout.frame X first true fit
+ have ranges := D.ranges true
+ have size : D.size true = D.sites * capacity a :=
+ ShrinkResidentLayout.size_eq_rows X first true
+ change ∀ x, D.first ≤ x → x < D.endAddr → out x = m x at agree
+ obtain ⟨owner, counts, rows, stop⟩ := ranges
+ constructor
+ · intro site
+ let i := siteIndex X site
+ have index : i.val < D.sites := i.isLt
+ have atCount : out ((p 3).val + i.val) = m ((p 3).val + i.val) := by
+ change (p 3).val = D.counts true at countAt
+ rw [countAt]
+ exact agree _ (by omega) (by omega)
+ exact (congrArg Fin.val atCount).trans (directory.count site)
+ · intro site i
+ let s := siteIndex X site
+ have siteFits : s.val + 1 ≤ D.sites := s.isLt
+ have width : i.val < capacity a := i.isLt.trans_eq (length_eq X side site)
+ have range := Nat.mul_le_mul_right (capacity a) siteFits
+ rw [Nat.succ_mul] at range
+ have atRow : out ((p 5).val + s.val * (p 4).val + i.val) =
+ m ((p 5).val + s.val * (p 4).val + i.val) := by
+ change (p 5).val = D.rows true at rowAt
+ change (p 4).val = capacity a at capAt
+ rw [rowAt, capAt]
+ exact agree _ (by omega) (by omega)
+ exact atRow.trans (directory.idAt site i)
+
+/-- Carry the count and ID fibers, selected term certificate and published
+layout through an update that preserves the completed level. -/
+noncomputable def transport (bounds : R.InLevel L j)
+ (agree : ∀ x, levelsBase L ≤ x → x < levelStart L (j + 1) → out x = m x) :
+ MapRowSource X selection side out level term := by
+ refine { R with rows := ?_, retained := ?_, layout := ?_ }
+ · exact directory_of_frame R.first R.fit R.rows fun x lo hi =>
+ agree x (bounds.firstStart.trans lo) (hi.trans_le bounds.rowsEnd)
+ · intro x
+ have before := (ordinal X x).isLt
+ have last := bounds.termEnd
+ exact (agree _ (bounds.termStart.trans (Nat.le_add_right ..)) (by omega)).trans (R.retained x)
+ · have hw := bounds.word
+ have add : (level + 38).val = level.val + 38 := by
+ change (level.val + (38 % 2 ^ w)) % 2 ^ w = _
+ rw [Nat.mod_eq_of_lt (by omega : 38 < 2 ^ w), Nat.mod_eq_of_lt hw]
+ have lowHead : levelsBase L ≤ level.val := bounds.head ▸ Nat.le_add_right ..
+ exact (agree _ (add ▸ (lowHead.trans (Nat.le_add_right ..))) (add ▸ bounds.headerEnd)).trans
+ R.layout
+
+/-- The same level frame preserves the four consecutive descriptor operands
+read before any map occurrence is dispatched. -/
+theorem published (bounds : R.InLevel L j) {counts ids : Word w}
+ (pub : MapResidentInputs.Published m level counts ids term 10)
+ (agree : ∀ x, levelsBase L ≤ x → x < levelStart L (j + 1) → out x = m x) :
+ MapResidentInputs.Published out level counts ids term 10 := by
+ apply pub.retain
+ intro o _ hi
+ have lo : levelsBase L ≤ level.val := bounds.head ▸ Nat.le_add_right ..
+ have endHead := bounds.headerEnd
+ exact agree _ (lo.trans (Nat.le_add_right ..)) (by omega)
+
+end MapRowSource
+end PairSimulation.ShrinkMapImage.Registers
+
+namespace CompressorRecords.SelectedDirectoryHistory
+
+open BurstRAM Compression DescriptorSpace PairSimulation.LocalHistory
+
+variable {w n : ℕ} {src : Fin n → Memory w → List (Report w) → Prop} {L : Layout}
+
+private theorem later_frames {js : List (Fin n)} {m : Memory w} {rs : List (Report w)}
+ (walk : SourceWalk src js m rs)
+ (writes : ∀ i u logs, src i u logs → SourceTransport.Writes
+ (fun x => x < levelsBase L ∨ levelStart L i.val ≤ x) (eventLog logs))
+ {first : ℕ} (later : ∀ i ∈ js, first ≤ i.val) :
+ ∀ x, levelsBase L ≤ x → x < levelStart L first → after m (eventLog rs) x = m x := by
+ induction walk with
+ | done => exact fun _ _ _ => rfl
+ | @next i is m xs ys head tail ih =>
+ intro x low high
+ have upper := high.trans_le (levelStart_mono L (later i List.mem_cons_self))
+ rw [SourceWalk.after_append, ih (fun k hk => later k (List.mem_cons_of_mem i hk)) x low high]
+ exact SourceTransport.after_outside m (writes i m xs head) (by omega)
+
+private theorem cut {J : Type*} {source : J → Memory w → List (Report w) → Prop}
+ (pre : List J) (j : J) (post : List J) {m : Memory w} {rs : List (Report w)}
+ (walk : SourceWalk source (pre ++ j :: post) m rs) :
+ ∃ xs ys zs, rs = xs ++ ys ++ zs ∧ SourceWalk source pre m xs ∧
+ source j (after m (eventLog xs)) ys ∧
+ SourceWalk source post (after (after m (eventLog xs)) (eventLog ys)) zs := by
+ induction pre generalizing m rs with
+ | nil =>
+ cases walk with
+ | next head tail => exact ⟨[], _, _, rfl, .done _, head, tail⟩
+ | cons k ks ih =>
+ cases walk with
+ | @next _ _ _ hs ts h tail =>
+ obtain ⟨xs, ys, zs, rfl, before, sel, rest⟩ := ih tail
+ refine ⟨hs ++ xs, ys, zs, by simp only [List.append_assoc], .next h before, ?_, ?_⟩
+ · rwa [SourceWalk.after_append]
+ · rwa [SourceWalk.after_append]
+
+/-- Cut the chronological run at any selected level. The final memory equals
+that packet's actual output at every address in the completed level region.
+The source may carry additional witnesses specific to a shrinking packet. -/
+theorem packet_retained (j : Fin n) {m : Memory w} {rs : List (Report w)}
+ (walk : SourceWalk src (List.finRange n) m rs)
+ (writes : ∀ i u logs, src i u logs → SourceTransport.Writes
+ (fun x => x < levelsBase L ∨ levelStart L i.val ≤ x) (eventLog logs)) :
+ ∃ pre visit rest, rs = pre ++ visit ++ rest ∧
+ SourceWalk src ((List.finRange n).take j.val) m pre ∧
+ src j (after m (eventLog pre)) visit ∧
+ SourceWalk src ((List.finRange n).drop (j.val + 1))
+ (after (after m (eventLog pre)) (eventLog visit)) rest ∧
+ ∀ x, levelsBase L ≤ x → x < levelStart L (j.val + 1) →
+ after m (eventLog rs) x = after (after m (eventLog pre)) (eventLog visit) x := by
+ let all := List.finRange n
+ have live : j.val < all.length := by simp [all]
+ have decomp : all.take j.val ++ j :: all.drop (j.val + 1) = all := by
+ have entry : all[j.val] = j := Fin.ext (by simp [all])
+ have tail := List.drop_eq_getElem_cons live
+ rw [entry] at tail
+ rw [← tail, List.take_append_drop]
+ obtain ⟨pre, visit, rest, logs, before, own, tail⟩ :=
+ cut (all.take j.val) j (all.drop (j.val + 1)) (by rw [decomp]; exact walk)
+ refine ⟨pre, visit, rest, logs, before, own, tail, ?_⟩
+ rw [logs, SourceWalk.after_append, SourceWalk.after_append]
+ apply later_frames tail writes
+ intro i hi
+ obtain ⟨k, hk, eq⟩ := List.mem_iff_getElem.mp hi
+ have idx := congrArg Fin.val eq
+ simp only [all, List.getElem_drop, List.getElem_finRange] at idx
+ change j.val + 1 + k = i.val at idx
+ omega
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f}
+variable {T d : ℕ} {hT : T * S.laneBits ≤ d} {X : State (S.degreeExponent 0) d}
+variable {z : (B.execute f hf T hT X).Choices}
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "emit" => Source (B := B) (f := f) (hf := hf) (z := z) L
+
+/-- Every packet of the selected directory walk already has the required
+write bound, including its low scheduler updates. -/
+theorem selected_packet_retained (j : Fin (vs).length) {m : Memory w} {rs : List (Report w)}
+ (walk : SourceWalk emit (List.finRange (vs).length) m rs) :
+ ∃ pre visit rest, rs = pre ++ visit ++ rest ∧
+ SourceWalk emit ((List.finRange (vs).length).take j.val) m pre ∧
+ emit j (after m (eventLog pre)) visit ∧
+ SourceWalk emit ((List.finRange (vs).length).drop (j.val + 1))
+ (after (after m (eventLog pre)) (eventLog visit)) rest ∧
+ ∀ x, levelsBase L ≤ x → x < levelStart L (j.val + 1) →
+ after m (eventLog rs) x = after (after m (eventLog pre)) (eventLog visit) x :=
+ packet_retained j walk fun _ _ _ h => h.2
+
+end CompressorRecords.SelectedDirectoryHistory
+
+namespace PairSimulation.ShrinkMapImage.Registers.MapRowSource
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords DescriptorSpace
+open MotifGrid MotifBlocks MotifConversion
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {w a g : ℕ} {X : State a (packingLaneBits a g)} {selection : X.ShrinkSelection B}
+ {side : Bool} {level term : Word w} {L : Layout} {n : ℕ}
+
+/-- A producing packet supplies the map-row certificate in its own post-memory.
+Cutting the full walk at that packet and replaying the remaining passes carries
+the certificate and its scanner operands to the last memory of the branch. -/
+theorem afterWalk {src : Fin n → Memory w → List (Report w) → Prop} (j : Fin n)
+ {m : Memory w} {rs : List (Report w)} (walk : SourceWalk src (List.finRange n) m rs)
+ (writes : ∀ i u logs, src i u logs → SourceTransport.Writes
+ (fun x => x < levelsBase L ∨ levelStart L i.val ≤ x) (eventLog logs))
+ (first : ℕ)
+ (produced : ∀ u visit, src j u visit →
+ let out := after u (eventLog visit)
+ let p := (ShrinkResidentLayout.layout X first).params a true w
+ ∃ R : MapRowSource X selection side out level term, R.first = first ∧ R.InLevel L j.val ∧
+ MapResidentInputs.Published out level (p 3) (p 5) term 10) :
+ let out := after m (eventLog rs)
+ let p := (ShrinkResidentLayout.layout X first).params a true w
+ ∃ R : MapRowSource X selection side out level term, R.first = first ∧ R.InLevel L j.val ∧
+ MapResidentInputs.Published out level (p 3) (p 5) term 10 := by
+ obtain ⟨pre, visit, _, _, _, own, _, agree⟩ :=
+ SelectedDirectoryHistory.packet_retained j walk writes
+ obtain ⟨R, atFirst, bounds, pub⟩ := produced _ visit own
+ exact ⟨R.transport bounds agree, atFirst, ⟨bounds.head, bounds.headerEnd, bounds.word,
+ bounds.firstStart, bounds.rowsEnd, bounds.termStart, bounds.termEnd⟩,
+ R.published bounds pub agree⟩
+
+end PairSimulation.ShrinkMapImage.Registers.MapRowSource
+
+namespace PairSimulation.TraversalResidentHandoff.Fields
+
+open BurstRAM Compression CompressorRecords DescriptorSpace
+
+/-- At the physical prefix exit, every map-row operand of a completed pass
+still has its calendar value. The prefix table lies in the final level. -/
+theorem before_final_level {w a g : ℕ} {L : Layout} {last j : ℕ} {tab : Fin L.shape.tables}
+ {A : TerminalBootstrap.Header L last} {cap H : ℕ} {Y : State a g}
+ {pub : Fin 11 → Word w} {calendar out : Memory w}
+ (fields : Fields L last tab A cap H Y pub calendar out) (earlier : j < last) :
+ ∀ x, levelsBase L ≤ x → x < levelStart L (j + 1) → out x = calendar x :=
+ fun x _ hx => fields.levelFrame x
+ ((hx.trans_le (levelStart_mono L earlier)).trans_le (Nat.le_add_right ..))
+
+end PairSimulation.TraversalResidentHandoff.Fields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapTermReadback.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapTermReadback.lean
new file mode 100644
index 0000000000..e1ceefca78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapTermReadback.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.PairSimulationMapResidentRows
+import OAI.Computability.VPVNP.CompressorShrinkScheduledRetention
+
+/-!
+# Agreement of the selected and retained shrinking grid words
+
+The native term worker and the later table readback identify the same demand
+grid point for every resident motif. The fixed grid enumerates each point
+once, so the actual word indices agree.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords DescriptorSpace PhaseRecipe Schedule
+open Compression BlockPlanner MapResidentRows NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {w : ℕ} {K : Type} [_root_.Field K] {S : BlockSchedule K}
+ (B : S.Templates) (i : Fin S.steps) {g : ℕ}
+ (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g))
+ (sel : X.ShrinkSelection B.shrink)
+ (base : Word w) (positions blocks round : ℕ) (m : Memory w)
+
+/-- Classical equality decision for base vertices used to compare retained term grid words with
+the words written by the term-selection worker. -/
+noncomputable local instance termReadbackBaseDecEq : DecidableEq X.Base := Classical.decEq _
+
+local notation "prog" => BlockProgram.script B
+local notation "L" => BlockProgram.layout B base.val positions blocks
+local notation "first" => Script.levelsPerBlock prog * round
+local notation "old" => first + i.val
+local notation "tab" => tableBase L old
+local notation "term" => ShrinkInput.termHead (w := w) X (tab (0 : Fin 6))
+private theorem grid_word_eq {α : Type*} {grid : Finset α} {x : α} {u v : Word w}
+ (h : grid.toList[u.val]? = some x) (h' : grid.toList[v.val]? = some x) : u = v := by
+ obtain ⟨hu, eu⟩ := List.getElem?_eq_some_iff.mp h
+ obtain ⟨hv, ev⟩ := List.getElem?_eq_some_iff.mp h'
+ exact Fin.ext (grid.nodup_toList.getElem_inj_iff.mp (eu.trans ev.symm))
+
+/-- The retained grid word equals the one selected by the native term worker. -/
+theorem term_readback {T : IncidenceDirectory w} {dense : Word w} {fuel : ℕ}
+ {before : Memory w} {rs : List (Report w)}
+ (back : ShrinkOutput.ScheduledReadbacks B i X sel base positions blocks round T m)
+ (terms : ShrinkTermSelection.Written B.shrink X dense term 10 fuel sel before rs)
+ (ten : (10 : Word w).val = 10)
+ (fit : (term).val + (LocalHistory.shrinkMotifOrder X).length * 10 < 2 ^ w)
+ (e : X.packingData.Motif) :
+ m ((term).val + (ordinal X e).val * 10) =
+ after before (eventLog rs) ((term).val + (ordinal X e).val * 10) := by
+ let id := ShrinkMotifOrder.stateNumber X e
+ have grid := (back.resident.terms id).1
+ change B.shrink.grid.demands.toList[(m (((term).val + id.val * (10 : Word w).val)
+ % (2 ^ w))).val]? = _ at grid
+ have index : (ordinal X e).val = id.val := rfl
+ have hi : id.val < (LocalHistory.shrinkMotifOrder X).length := index ▸ (ordinal X e).isLt
+ have room : (term).val + id.val * 10 < 2 ^ w := by omega
+ have eqn : (ShrinkMotifOrder.stateNumber X).symm id = e := Equiv.symm_apply_apply ..
+ rw [ten, Nat.mod_eq_of_lt room] at grid
+ change _ = some (MotifConversion.demandGrid B.shrink Compression.ShrinkMotif.demandMass_pos
+ (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth
+ ((ShrinkMotifOrder.stateNumber X).symm id))).val at grid
+ rw [eqn] at grid
+ have source := (terms.fields e).1
+ have address : (ShrinkTermSelection.rowBase X term 10 e).val = (term).val + id.val * 10 :=
+ Nat.mod_eq_of_lt room
+ rw [address] at source
+ rw [index]
+ exact grid_word_eq grid source
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapVertexMemory.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapVertexMemory.lean
new file mode 100644
index 0000000000..4b95840ae6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkMapVertexMemory.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.PairTerminalPackedPrefix
+import OAI.Computability.VPVNP.PairTerminalVertexFramePacked
+
+/-!
+# Selected compressor levels at a physical vertex call
+
+The terminal prefix publishes wire offsets in a table of the final level.
+The traversal rows, shared wire bits and role tags all lie above the level
+allocation. During the vertex scan the counter suffix lies below the levels
+and the two terminal controller words lie above them. Consequently each
+earlier level still has its calendar image when a vertex invokes a map.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace TraversalRows LocalHistory
+open LiveProgram.PairStages.Group.Auxiliary
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+ {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f} {n T : ℕ}
+ {hT : T * S.laneBits ≤ n} {X : State (S.degreeExponent 0) n}
+ {z : (B.execute f hf T hT X).Choices}
+ {L : Layout} {tab : Fin L.shape.tables} {baseBits laneBits : ℕ}
+local notation "last" => List.length (List.dropLast (selectedLayers B f hf T hT X z))
+local notation "levels" => executeLevels B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+
+/-- At each physical ordinal, all words up to the end of an earlier selected
+level have their calendar values. This includes its map headers and term rows. -/
+theorem VertexEntry.linkedLevelWindow {w : ℕ} {pub : Fin 11 → Word w}
+ {calendar reference phy : Memory w} {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits pub calendar reference bits)
+ {base grammar labels ord : ℕ}
+ (frame : VertexFrame.Linked (TerminalLink.header pub) base grammar labels reference ord phy)
+ (room : (TerminalLink.header pub).val + 32 ≤ 2 ^ w)
+ (counters : base + grammar + labels ≤ levelsBase L)
+ (arena : endAddress L ≤ (TerminalLink.header pub).val)
+ (allocated : (levels).length ≤ L.levels) (j : Fin (levels).length) :
+ ∀ x, levelsBase L ≤ x → x < levelStart L (j.val + 1) → phy x = calendar x := by
+ intro x lo hi
+ have final := TerminalBootstrap.selected_last_index B f hf T hT X z
+ have before := hi.trans_le (levelStart_mono L j.isLt)
+ have bound := before.trans_le (levelStart_mono L allocated)
+ have start : levelStart L last ≤ DescriptorSpace.tableBase L last tab := by
+ unfold DescriptorSpace.tableBase arrayBase incidenceStart
+ omega
+ rw [← final] at before
+ exact (frame.below room (counters.trans lo) (bound.trans_le arena)).trans
+ (entry.raw x bound (.inl (before.trans_le start)))
+
+open LiveProgram.PairStages
+
+variable {G : Group} {positions : ℕ}
+set_option quotPrecheck false in
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val positions T
+
+/-- The packed group workspace supplies the separation from both counter
+stores and controller stores for the actual terminal public operands. The
+calendar allocates one level for each selected pass and one for its output. -/
+theorem VertexEntry.packedLevelWindow {cap width ord : ℕ} {table : Fin (D).shape.tables}
+ {roles : List TraversalRoles.TaggedLayer} {calendar reference phy : Memory G.w}
+ {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z D table baseBits laneBits (terminalOperands G)
+ calendar reference bits)
+ (packed : VertexPacked G D cap roles width)
+ (frame : LinkedVertexMemory G reference ord phy)
+ (j : Fin (levels).length) :
+ ∀ x, levelsBase D ≤ x → x < levelStart D (j.val + 1) → phy x = calendar x := by
+ have base : (D).base ≤ levelsBase D := by
+ unfold levelsBase directoryBase plannerTag frameBase
+ omega
+ have allocated : (levels).length ≤ (D).levels := by
+ rw [← TerminalBootstrap.selected_last_index, TerminalBootstrap.selected_prior_length,
+ BlockProgram.actual_level_count, Nat.mul_comm T]
+ omega
+ have arena : endAddress D ≤ (vertexHeader G).val :=
+ (Nat.le_add_right ..).trans ((Nat.le_add_right ..).trans packed.arena)
+ exact entry.linkedLevelWindow frame packed.room (packed.counter_base.trans base)
+ arena allocated j
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkRouteOrdinal.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRouteOrdinal.lean
new file mode 100644
index 0000000000..e40cc0ed86
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRouteOrdinal.lean
@@ -0,0 +1,25 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherSource
+
+/-!
+# The dense ordinal passed as state to a selected shrinking map
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM Compression MapResidentRows
+open scoped Fin.CommRing
+
+/-- The dense motif ordinal loaded as the sixth operand of a resident row. -/
+noncomputable def rowOrdinalWord {w a g : ℕ} (X : State a (packingLaneBits a g)) (side : Bool)
+ (site : Site X) (i : Fin (order X side site).length) : Word w :=
+ ((ordinal X (MapResidentRows.entry X side site i).1).val : Word w)
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkRouteReads.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRouteReads.lean
new file mode 100644
index 0000000000..bed2343bf4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRouteReads.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherSource
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-!
+# Exact reads of the selected map route
+
+The native route reads three words, at the resident ID, selected term and old
+level layout. Its ordinal comparisons consume only local instruction ticks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.SourceTransport
+open Compression Compression.ShrinkMotif MotifGrid MotifBlocks MotifConversion MapResidentRows
+open scoped Fin.CommRing
+open private fetch from OAI.Computability.VPVNP.PairSimulationMapResidentInputs
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {w a g : ℕ} (X : State a (packingLaneBits a g)) (sel : X.ShrinkSelection B)
+ (side : Bool) (site : Site X) (m : Memory w) (level term : Word w)
+ (R : MapRowSource X sel side m level term) (i : Fin (order X side site).length)
+
+local notation "src" => rowCursor X sel side site m level term R i
+local notation "motif" => Prod.fst (entry X side site i)
+local notation "rank" => Fin.val (ordinal X (motif))
+local notation "ev" => routeEvents X sel side site m level term R i
+
+theorem rowCursor_fit : (src) < 2 ^ w := by
+ have h := (directory_fit X R.first site R.fit).2
+ have hi : i.val < capacity a := i.isLt.trans_eq (length_eq X side site)
+ exact (Nat.add_lt_add_left hi _).trans h
+
+private theorem termAddress_val : (MapResidentInputs.termAddr m ((src) : Word w) term 10).val =
+ term.val + (rank) * 10 := by
+ have fit := rowCursor_fit X sel side site m level term R i
+ have digits := allocated_id X R.first R.fit R.rows site i
+ change (m (src)).val = (rank) * 6 + (entry X side site i).2.val at digits
+ let id := m (src)
+ have rb := (ordinal X (motif)).isLt
+ have room := R.termFit
+ have h6 : 6 < 2 ^ w := by omega
+ have hTerm : term.val + (rank) * 10 < 2 ^ w := by omega
+ have q : (BinaryOp.div.eval id 6).val = (rank) := by
+ change id.val / (6 : Word w).val % (2 ^ w) = _
+ rw [show (6 : Word w).val = 6 from Nat.mod_eq_of_lt h6,
+ Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt id.isLt)]
+ change (m (src)).val / 6 = _
+ rw [digits]
+ have h := (entry X side site i).2.isLt
+ omega
+ have qWord : BinaryOp.div.eval id 6 = ((rank) : Word w) := by
+ rw [← q]
+ exact Fin.ext (Nat.mod_eq_of_lt (BinaryOp.div.eval id 6).isLt).symm
+ change (term + BinaryOp.div.eval (m (((src) : Word w).val)) 6 * 10).val = _
+ rw [show ((src) : Word w).val = (src) from Nat.mod_eq_of_lt fit, qWord,
+ show term = (term.val : Word w) from Fin.ext (Nat.mod_eq_of_lt term.isLt).symm]
+ change (((term.val : Word w) + ((rank) : Word w) * ((10 : ℕ) : Word w))).val = _
+ rw [← Nat.cast_mul, ← Nat.cast_add]
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt term.isLt] using Nat.mod_eq_of_lt hTerm
+
+/-- Three fitted addresses suffice for a read-footprint check of the entire
+dispatcher and layout branch, for every stored map in the shrinking row. -/
+theorem routeEvents_reads (allow : ℕ → Prop) (idSafe : allow (src))
+ (termSafe : allow (term.val + (rank) * 10)) (layoutSafe : allow (level + 38).val) :
+ Reads allow (ev) := by
+ unfold routeEvents
+ apply TerminalFootprint.reads_append
+ · apply TerminalFootprint.reads_append
+ · intro q val h
+ simp only [MapResidentInputs.itemEvents, fetch, List.mem_cons, List.not_mem_nil,
+ Event.read.injEq, reduceCtorEq, false_or, or_false] at h
+ rcases h with h | h
+ · rw [h.1, show ((src) : Word w).val = (src) from
+ Nat.mod_eq_of_lt (rowCursor_fit X sel side site m level term R i)]
+ exact idSafe
+ · rw [h.1, termAddress_val X sel side site m level term R i]
+ exact termSafe
+ · exact TerminalFootprint.reads_ticks allow _
+ · intro q val h
+ simp only [ShrinkLayoutBranch.events, List.mem_cons, List.not_mem_nil, Event.read.injEq,
+ reduceCtorEq, false_or, or_false] at h
+ exact h.1 ▸ layoutSafe
+
+/-- All external operations of the resident ID, term and layout route are reads. -/
+theorem routeEvents_noWrites : Writes (fun _ ↦ False) (ev) := by
+ intro q val h
+ rcases List.mem_append.mp h with previous | layout
+ · rcases List.mem_append.mp previous with item | tick
+ · simp only [MapResidentInputs.itemEvents, fetch, List.mem_cons, List.not_mem_nil,
+ reduceCtorEq, false_or] at item
+ · cases List.eq_of_mem_replicate tick
+ · simp only [ShrinkLayoutBranch.events, List.mem_cons, List.not_mem_nil, reduceCtorEq,
+ false_or] at layout
+
+theorem routeEvents_cost :
+ countProbes (ev) = 3 ∧ choiceBits (ev) = [] := by
+ have quiet (n) : countProbes (List.replicate n (.tick : Event w)) = 0 ∧
+ choiceBits (List.replicate n (.tick : Event w)) = [] := by
+ induction n with
+ | zero => exact ⟨rfl, rfl⟩
+ | succ n ih => simpa only [List.replicate_succ, countProbes, choiceBits] using ih
+ have a := MapResidentInputs.itemCost m ((src) : Word w) term 10
+ have b := ShrinkLayoutBranch.cost m level
+ simp only [routeEvents, countProbes_append, PrimedInputRAM.Flow.choiceBits_append,
+ a.2.1, a.2.2, b.2.1, b.2.2, (quiet _).1, (quiet _).2, List.nil_append, and_self]
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkRowAction.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRowAction.lean
new file mode 100644
index 0000000000..15e37f4bae
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRowAction.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkRouteOrdinal
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherMatrix
+import OAI.Computability.VPVNP.PairSimulationShrinkRouteReads
+
+/-!
+# Trace and acceptance of one shrinking resident map row
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.ShrinkSlots
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifGrid MotifBlocks MotifConversion MapResidentRows MapHandlerOperand NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w g endAddr : ℕ} (F : MapHandlerImage.Family B t shared)
+ (G : ShrinkGatherBank.Family F) (S : Registers shared) (pc : GatherAddress F G → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r)
+ (own : F.PrivateReg ↪ Fin r) (gatherReg : G.PrivateReg ↪ Fin r) (tmp : Fin r) (ret : Fin p)
+ (M : Machine w p r 11) (link : GatherLinked F G S pc dfs saved common own gatherReg tmp ret M)
+ (mapApart : F.Apart dfs saved common own) (gatherApart : G.Apart dfs saved common gatherReg)
+ (X : State G.a (packingLaneBits G.a g)) {δ : ℝ}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} (sel : X.ShrinkSelection B)
+ (site : Site X) (m : Memory w) (level term : Word w)
+
+private noncomputable local instance rowActionBase : DecidableEq X.Base := Classical.decEq _
+variable {side : Bool}
+
+variable (R : MapRowSource X sel side m level term) (i : Fin (order X side site).length)
+ (I : LocalHistory.EntryInput B)
+
+local notation "entryPair" => MapResidentRows.entry X side site i
+local notation "z" => demandGrid B demandMass_pos I.demand
+local notation "key" => Prod.mk (z) I.party
+local notation "route" => routeEvents X sel side site m level term R i
+local notation "src" => rowCursor X sel side site m level term R i
+local notation "reg" => S.headerReg common
+
+variable {jobMotif : X.packingData.Motif}
+ (J : ShrinkPartyNative.Job (a := G.a) (b := G.b) (g := g) X B ready sel jobMotif I.party w)
+ (hw : MapConstants.widthThreshold B ≤ w) (P : Fin 5 → Word w)
+ (W : Workspace F demandMass_pos I) (oldScratch : DFS.Scratch w endAddr)
+
+local notation "st" => rowOrdinalWord (w := w) (a := G.a) (g := g) X side site i
+
+set_option maxHeartbeats 1800000 in
+-- The field gather and stored row use the same selected compression indices.
+/-- Trace and final scratch for a successful row, including the route to its gather.
+A rejected matrix entry yields `none`. -/
+noncomputable def rowAction : Option (List (Event w) × DFS.Scratch w endAddr) :=
+ (gatheredAction (g := g) F G (X := X) (ready := ready) (selection := sel)
+ (motif := jobMotif) I J hw P (st) m W oldScratch).map fun pair ↦ ((route) ++ pair.1, pair.2)
+
+set_option maxHeartbeats 1800000 in
+-- Unfold the single dependent row action at its recorded stage and party.
+/-- An indexed resident row succeeds exactly when its underlying grouped matrix succeeds. -/
+theorem rowAction_isSome :
+ (rowAction F G X sel site m level term R i I J hw P W oldScratch).isSome =
+ (names F demandMass_pos I).isSome := by
+ simp only [rowAction, gatheredAction, Option.isSome_map, MapHandlerImage.Family.action_isSome,
+ names]
+
+set_option maxHeartbeats 1800000 in
+-- Unfold the single dependent row action at its recorded stage and party.
+/-- The dispatch and map add no guesses to a physical operand gather. -/
+theorem rowAction_noChoices {es : List (Event w)} {updated : DFS.Scratch w endAddr}
+ (quiet : choiceBits (J.trace (G.operands (key)) (G.node (key)) P (st) m) = [])
+ (got : rowAction F G X sel site m level term R i I J hw P W oldScratch = some (es, updated)) :
+ choiceBits es = [] := by
+ unfold rowAction at got
+ obtain ⟨⟨mid, last⟩, gathered, pair⟩ := Option.map_eq_some_iff.mp got
+ unfold gatheredAction at gathered
+ obtain ⟨⟨trace, final⟩, raw, inner⟩ := Option.map_eq_some_iff.mp gathered
+ have clean := F.action_noChoices demandMass_pos I hw P (st) m W endAddr
+ (J.updated endAddr oldScratch) raw
+ rw [← (Prod.mk.inj pair).1, ← (Prod.mk.inj inner).1]
+ simp only [PrimedInputRAM.Flow.choiceBits_append,
+ (routeEvents_cost X sel side site m level term R i).2, quiet, clean, List.nil_append]
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkRowFootprint.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRowFootprint.lean
new file mode 100644
index 0000000000..178c2a2554
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRowFootprint.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkRowAction
+import OAI.Computability.VPVNP.PairShrinkGatherQuiet
+
+/-!
+# Reads and writes of a complete selected shrinking row
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.ShrinkSlots SourceTransport
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifGrid MotifBlocks MotifConversion MapResidentRows MapHandlerOperand NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w g endAddr : ℕ} (F : MapHandlerImage.Family B t shared)
+ (G : ShrinkGatherBank.Family F) (S : Registers shared) (pc : GatherAddress F G → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r)
+ (own : F.PrivateReg ↪ Fin r) (gatherReg : G.PrivateReg ↪ Fin r) (tmp : Fin r) (ret : Fin p)
+ (M : Machine w p r 11) (link : GatherLinked F G S pc dfs saved common own gatherReg tmp ret M)
+ (mapApart : F.Apart dfs saved common own) (gatherApart : G.Apart dfs saved common gatherReg)
+ (X : State G.a (packingLaneBits G.a g)) {δ : ℝ}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} (sel : X.ShrinkSelection B)
+ (site : Site X) (m : Memory w) (level term : Word w)
+
+private noncomputable local instance rowFootprintBase : DecidableEq X.Base := Classical.decEq _
+variable {side : Bool}
+
+variable (R : MapRowSource X sel side m level term) (i : Fin (order X side site).length)
+ (I : LocalHistory.EntryInput B)
+
+local notation "entryPair" => MapResidentRows.entry X side site i
+local notation "z" => demandGrid B demandMass_pos I.demand
+local notation "key" => Prod.mk (z) I.party
+local notation "route" => routeEvents X sel side site m level term R i
+local notation "src" => rowCursor X sel side site m level term R i
+local notation "reg" => S.headerReg common
+
+variable {jobMotif : X.packingData.Motif}
+ (J : ShrinkPartyNative.Job (a := G.a) (b := G.b) (g := g) X B ready sel jobMotif I.party w)
+ (hw : MapConstants.widthThreshold B ≤ w) (P : Fin 5 → Word w)
+ (W : Workspace F demandMass_pos I) (oldScratch : DFS.Scratch w endAddr)
+
+local notation "st" => rowOrdinalWord (w := w) (a := G.a) (g := g) X side site i
+
+set_option maxHeartbeats 1600000 in
+-- Match the physical writer and gather traces to the dependent selected job.
+/-- The returned event list consists of the route, gather and successful matrix traces. -/
+theorem rowAction_trace {es : List (Event w)} {updated : DFS.Scratch w endAddr}
+ (got : rowAction F G X sel site m level term R i I J hw P W oldScratch = some (es, updated)) :
+ es = (route) ++ (J.trace (G.operands (key)) (G.node (key)) P (st) m ++
+ F.successEvents demandMass_pos I hw P (st) m) := by
+ unfold rowAction at got
+ obtain ⟨⟨mid, last⟩, gathered, pair⟩ := Option.map_eq_some_iff.mp got
+ unfold gatheredAction at gathered
+ obtain ⟨⟨trace, final⟩, raw, inner⟩ := Option.map_eq_some_iff.mp gathered
+ have known := (F.action_some_iff demandMass_pos I hw P (st) m W endAddr
+ (J.updated endAddr oldScratch)).mp raw
+ exact (Prod.mk.inj pair).1.symm.trans (congrArg (fun xs ↦ (route) ++ xs)
+ ((Prod.mk.inj inner).1.symm.trans (congrArg (fun xs ↦ _ ++ xs) known.2.1)))
+
+set_option maxHeartbeats 1600000 in
+-- The exact row action specializes its geometric footprint to the live source words.
+/-- A successful shrinking row has the concrete external read domain and never writes. -/
+theorem rowAction_footprint {es : List (Event w)} {updated : DFS.Scratch w endAddr}
+ (allow : ℕ → Prop) (idSafe : allow (src))
+ (termSafe : allow (term.val + (ordinal X (entryPair).1).val * 10))
+ (layoutSafe : allow (level + 38).val)
+ (gather : Reads allow (J.trace (G.operands (key)) (G.node (key)) P (st) m))
+ (baseSafe : (F.base (key)).ReadsFrom allow P (st) m)
+ (fieldSafe : ∀ a, (F.field (key) a).ReadsFrom allow P (st) m)
+ (got : rowAction F G X sel site m level term R i I J hw P W oldScratch = some (es, updated)) :
+ Reads allow es ∧ Writes (fun _ ↦ False) es := by
+ rw [rowAction_trace F G X sel site m level term R i I J hw P W oldScratch got]
+ constructor
+ · exact TerminalFootprint.reads_append
+ (routeEvents_reads X sel side site m level term R i allow idSafe termSafe layoutSafe)
+ (TerminalFootprint.reads_append gather
+ (F.successEvents_readsFrom demandMass_pos I hw P (st) m allow baseSafe fieldSafe))
+ · intro a v hit
+ rcases List.mem_append.mp hit with routeHit | tail
+ · exact routeEvents_noWrites X sel side site m level term R i a v routeHit
+ rcases List.mem_append.mp tail with gatherHit | matrixHit
+ · exact J.trace_noWrites (G.operands (key)) (G.node (key)) P (st) m a v gatherHit
+ · exact F.successEvents_noWrites demandMass_pos I hw P (st) m a v matrixHit
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkRowHistogram.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRowHistogram.lean
new file mode 100644
index 0000000000..853b0f9ee6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkRowHistogram.lean
@@ -0,0 +1,165 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkRowAction
+import OAI.Computability.VPVNP.PairSimulationMapScratchOutside
+import OAI.Computability.VPVNP.PairShrinkUpdatedBelow
+
+/-!
+# Histogram readback for a shrinking resident row
+
+The selector and label arrays are disjoint from the counter bank. For a successful
+entry, the descriptor, directory and gather writes also leave this bank intact.
+Each emitted ordinal then increments its own counter, including repeated ordinals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.MapScratch
+
+open MotifSelector MotifGrid MotifBlocks MotifConversion MotifEntry MapCallSetup MapEntryTable
+open scoped Fin.CommRing
+open private write_other apart_of_interval from OAI.Computability.VPVNP.PairSimulationMapScratchOutside
+
+variable {J D E K : Type} [Fintype J] [DecidableEq J] [Fintype D] [Fintype E] [Field K]
+ {src dst : D → J} {G : Supply J E} {p₀ : D → ℚ} {q₀ : E → ℚ} {H H' : ℝ}
+ {B : FixedBlock K src dst G (realWidths p₀) (realWidths q₀) H H'}
+ {z : B.grid.demands} {j : J} {r k p w t u : ℕ}
+ (A : Allocation B z j r k) (args : Arg D E ≃ Fin (Fintype.card (Arg D E)))
+ (loc : A.Address → Fin p) {demand : D → ℕ} {v : E → ℕ}
+ {d : DemandBits src dst demand j} {x : Half G (fun e ↦ Fin (v e + u * B.selectorBits) → Bool) j}
+ (W : MapEntry.Program.Workspace (A.program loc) demand v d x t w)
+ (addr : BurstRAM.Word w) (sel : Selector B ↪ BurstRAM.Word w)
+ (ord : (parameterData B).Entry → Fin t)
+
+local notation "entry" => Prod.fst (MotifEntry.run src dst (baseDemand B z) demand G (basePayload B)
+ (lookup B z) (selectorTable B) (selectorCode B) v j d x)
+local notation:max "bin" l:max => ((W.hist + Fin.val (l : Fin t) : ℕ) : BurstRAM.Word w)
+
+/-- On successful inputs the pure upper scratch update adds the exact number of emitted
+occurrences at a live counter cell disjoint from the descriptor and pointer directory. -/
+theorem upper_histogram (endAddr : ℕ) (saved : DFS.Scratch w endAddr)
+ (good : (entry).isSome = true) (l : Fin t) (live : endAddr ≤ (bin l).val)
+ (fit : addr.val + Fintype.card (Arg D E) ≤ 2 ^ w)
+ (descriptor : (bin l).val < addr.val ∨ addr.val + Fintype.card (Arg D E) ≤ (bin l).val)
+ (directory : ∀ i : MapDirectoryInit.Row A, bin l ≠ W.directory + (i.val : BurstRAM.Word w)) :
+ NodeArguments.rawScratch (upper A args loc W addr sel ord endAddr saved) (bin l) =
+ NodeArguments.rawScratch saved (bin l) + ((((entry).map (List.map ord)).getD []).count l :
+ BurstRAM.Word w) := by
+ let old := NodeArguments.rawScratch saved
+ have ptr (i : Fin (Fintype.card (Arg D E))) : bin l ≠ addr + (i.val : BurstRAM.Word w) := by
+ simpa only [Fin.cast_val_eq_self] using apart_of_interval (bin l) fit descriptor i
+ have desc : published A args loc W addr old (bin l) = old (bin l) := write_other _ _ _ _ ptr
+ have init : directoryMemory A loc W (published A args loc W addr old) (bin l) = old (bin l) :=
+ (write_other _ _ _ _ directory).trans desc
+ have value : (bin l).val = W.hist + l.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left l.isLt W.hist).trans_le W.histogramFit)
+ have exterior (base : ℕ) (apart : base + u ≤ W.hist ∨ W.hist + t ≤ base) :
+ (bin l).val < base ∨ base + u ≤ (bin l).val := by
+ rw [value]
+ have := l.isLt
+ omega
+ have source := apart_of_interval (bin l) W.ordinalFit.le (exterior W.source W.sourceHistApart)
+ have target := apart_of_interval (bin l) W.labelFit.le (exterior W.target W.targetHistApart)
+ obtain ⟨θ, pick, valid⟩ := sequence_of_success good
+ rw [NodeArguments.rawScratch, dite_eq_left live]
+ change successMemory A args loc W addr sel ord old (bin l) = old (bin l) + _
+ rw [successMemory, pick, Option.elim_some, MapEntry.Program.successMemory,
+ PrivateLabels.accumulate_at W.hist _ _ W.histogramFit l, write_other _ _ _ _ target,
+ write_other _ _ _ _ source, init, MapFinish.entry_value, pick, Option.bind_some,
+ ite_eq_left valid, Option.map_some, Option.getD_some, List.map_ofFn]
+ rfl
+
+end PairSimulation.MapScratch
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.ShrinkSlots
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifGrid MotifBlocks MotifConversion MapResidentRows MapHandlerOperand
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {t shared w g endAddr packetEnd : ℕ} (F : MapHandlerImage.Family B t shared)
+ (G : ShrinkGatherBank.Family F)
+ (X : State G.a (packingLaneBits G.a g)) {δ : ℝ}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} (sel : X.ShrinkSelection B)
+ (site : Site X) (m : Memory w) (level term : Word w)
+private noncomputable local instance histogramBase : DecidableEq X.Base := Classical.decEq _
+variable {side : Bool}
+variable (R : MapRowSource X sel side m level term) (i : Fin (order X side site).length)
+ (I : LocalHistory.EntryInput B) {motif : X.packingData.Motif}
+ (J : ShrinkPartyNative.Job (a := G.a) (b := G.b) (g := g) X B ready sel motif I.party w)
+ (hw : MapConstants.widthThreshold B ≤ w) (P : Fin 5 → Word w)
+ (W : Workspace F demandMass_pos I) (saved : DFS.Scratch w endAddr)
+
+local notation "key" => Prod.mk (demandGrid B demandMass_pos I.demand) I.party
+local notation "st" => rowOrdinalWord (w := w) (a := G.a) (g := g) X side site i
+local notation "ptr" => PhaseRecipe.Expr.eval P (st) m (F.base key)
+local notation "ptrAt" stage:max => PhaseRecipe.Expr.eval P stage m (F.base key)
+local notation:max "bin" l:max => ((W.hist + Fin.val (l : Fin t) : ℕ) : Word w)
+
+set_option maxHeartbeats 1800000 in
+-- The gathered map and its scratch use the same dependent field buffers.
+/-- A successful gather and map add the selected matrix multiplicities to the incoming counters. -/
+theorem gathered_histogram (stage : Word w) {baseline : Word w → Word w}
+ (packets : J.Packets packetEnd baseline)
+ (floor : endAddr ≤ W.hist)
+ (fit : (ptrAt stage).val + Fintype.card ShrinkCallFields.Arg ≤ 2 ^ w)
+ (below : W.hist + t ≤ J.scratch.staging)
+ (descriptor : ∀ l : Fin t, (bin l).val < (ptrAt stage).val ∨
+ (ptrAt stage).val + Fintype.card ShrinkCallFields.Arg ≤ (bin l).val)
+ (directory : ∀ (l : Fin t) (k : MapDirectoryInit.Row (F.layout key).core),
+ bin l ≠ W.directory + (k.val : Word w))
+ {es : List (Event w)} {out : DFS.Scratch w endAddr}
+ (got : gatheredAction (g := g) F G (X := X) (ready := ready) (selection := sel) (motif := motif)
+ I J hw P stage m W saved = some (es, out)) :
+ ∀ l : Fin t, NodeArguments.rawScratch out (bin l) = NodeArguments.rawScratch saved (bin l) +
+ (((names F demandMass_pos I).getD []).count l : Word w) := by
+ unfold gatheredAction at got
+ obtain ⟨⟨_, last⟩, raw, eq₂⟩ := Option.map_eq_some_iff.mp got
+ obtain ⟨good, _, upper⟩ := (F.action_some_iff demandMass_pos I hw P stage m W endAddr
+ (J.updated endAddr saved)).mp raw
+ intro l
+ have value : (bin l).val = W.hist + l.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left l.isLt W.hist).trans_le W.histogramFit)
+ have live : endAddr ≤ (bin l).val := by
+ rw [value]
+ exact floor.trans (Nat.le_add_right ..)
+ have low : (bin l).val < J.scratch.staging := by
+ rw [value]
+ exact (Nat.add_lt_add_left l.isLt _).trans_le below
+ rw [← (Prod.mk.inj eq₂).2, upper]
+ exact (MapScratch.upper_histogram (F.layout key).core (F.layout key).args
+ ((F.layout key).corePC (F.layout key).locations) W (ptrAt stage) _ F.ordinal endAddr
+ (J.updated endAddr saved) good l live fit (descriptor l) (directory l)).trans
+ (congrArg (· + _) (J.updated_below packets saved (bin l) low))
+
+set_option maxHeartbeats 1800000 in
+-- The gather, map and trace share dependent indices for the selected layout and row.
+/-- A successful resident row adds its own parameter multiplicities to the incoming counters. -/
+theorem rowAction_histogram {baseline : Word w → Word w} (packets : J.Packets packetEnd baseline)
+ (bounds : Bounds F demandMass_pos I W endAddr ptr)
+ (fit : (ptr).val + Fintype.card ShrinkCallFields.Arg ≤ 2 ^ w)
+ (below : W.hist + t ≤ J.scratch.staging)
+ (descriptor : ∀ l : Fin t, (bin l).val < (ptr).val ∨
+ (ptr).val + Fintype.card ShrinkCallFields.Arg ≤ (bin l).val)
+ (directory : ∀ (l : Fin t) (k : MapDirectoryInit.Row (F.layout key).core),
+ bin l ≠ W.directory + (k.val : Word w))
+ {es : List (Event w)} {out : DFS.Scratch w endAddr}
+ (got : rowAction (g := g) (ready := ready) (side := side) (jobMotif := motif)
+ F G X sel site m level term R i I J hw P W saved = some (es, out)) :
+ ∀ l : Fin t, NodeArguments.rawScratch out (bin l) = NodeArguments.rawScratch saved (bin l) +
+ (((names F demandMass_pos I).getD []).count l : Word w) := by
+ unfold rowAction at got
+ obtain ⟨⟨_, next⟩, gathered, eq₁⟩ := Option.map_eq_some_iff.mp got
+ rw [← (Prod.mk.inj eq₁).2]
+ exact gathered_histogram (g := g) F G X sel m I J hw P W saved (st)
+ packets bounds.histogramBase fit below descriptor directory gathered
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkScheduledItem.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkScheduledItem.lean
new file mode 100644
index 0000000000..af1bbbba97
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkScheduledItem.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkScheduledRow
+import OAI.Computability.VPVNP.PairSimulationShrinkLiveOperands
+import OAI.Computability.VPVNP.PairShrinkGatherQuiet
+import OAI.Computability.VPVNP.PairSimulationResidentMapLoopExact
+
+/-!
+# The concrete shrinking-map item of the exact row interpreter
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.ShrinkSlots
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifGrid MotifBlocks MotifConversion MapResidentRows MapHandlerOperand NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w g endAddr : ℕ} (F : MapHandlerImage.Family B t shared)
+ (G : ShrinkGatherBank.Family F) (S : Registers shared) (pc : GatherAddress F G → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r)
+ (own : F.PrivateReg ↪ Fin r) (gatherReg : G.PrivateReg ↪ Fin r) (tmp : Fin r) (ret : Fin p)
+ (M : Machine w p r 11) (link : GatherLinked F G S pc dfs saved common own gatherReg tmp ret M)
+ (mapApart : F.Apart dfs saved common own) (gatherApart : G.Apart dfs saved common gatherReg)
+ (X : State G.a (packingLaneBits G.a g)) {δ : ℝ}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} (sel : X.ShrinkSelection B)
+ (site : Site X) (m : Memory w) (level term : Word w)
+
+private noncomputable local instance scheduledItemBase : DecidableEq X.Base := Classical.decEq _
+variable {side : Bool}
+
+variable (R : MapRowSource X sel side m level term) (i : Fin (order X side site).length)
+ (I : LocalHistory.EntryInput B)
+
+local notation "entryPair" => MapResidentRows.entry X side site i
+local notation "z" => demandGrid B demandMass_pos I.demand
+local notation "key" => Prod.mk (z) I.party
+local notation "route" => routeEvents X sel side site m level term R i
+local notation "src" => rowCursor X sel side site m level term R i
+local notation "reg" => S.headerReg common
+
+variable {jobMotif : X.packingData.Motif}
+ (J : ShrinkPartyNative.Job (a := G.a) (b := G.b) (g := g) X B ready sel jobMotif I.party w)
+ (hw : MapConstants.widthThreshold B ≤ w) (P : Fin 5 → Word w)
+ (W : Workspace F demandMass_pos I)
+
+local notation "st" => rowOrdinalWord (w := w) (a := G.a) (g := g) X side site i
+
+variable {absolute : Word w} {T U : IncidenceDirectory w} {origin layer pitch : ℕ}
+ {heads : SlotLevel.Heads}
+
+variable (inv : Word w → Config w p r → Prop)
+
+local notation "loopProg" => loop F S (corePC F G pc) common ret
+local notation "action" => rowAction (endAddr := endAddr) F G X sel site m level term R i I J hw P W
+
+set_option maxHeartbeats 1900000 in
+-- The reader, party fields and local matrix share the actual selected row index.
+include link mapApart gatherApart in
+theorem exact_item (positive : 0 < w) (outside : ∀ b, common b ≠ tmp)
+ (dfSafe : ∀ j, Protected S common tmp (dfs j))
+ (pubSafe : ∀ j : Fin 5, Protected S common tmp (F.inputs dfs saved common (key) j.castSucc))
+ (stateSource : F.inputs dfs saved common (key) (Fin.last 5) = (reg) 6)
+ (layoutChoice : side = selectedLayout X B sel)
+ (party : (entryPair).2 = I.party) (grid : rowGrid (B := B) X side site i = (z))
+ (allowed : ℕ → Prop) (sites : ∀ c k, (J.row c k).ReadSafe
+ (ShrinkPartyNative.setups (G.operands (key)) (G.node (key)) G.a G.b I.party
+ (selectedLayout X B sel) c k)
+ allowed P (st) m)
+ (old : J.OldPublished (G.operands (key)) P (st) m level T origin)
+ (next : J.SupplyPublished (G.operands (key)) (G.node (key)) P (st) m heads
+ absolute U layer pitch)
+ (room : Bounds F demandMass_pos I W endAddr (PhaseRecipe.Expr.eval P (st) m (F.base (key))))
+ (histBefore : ∀ l : Fin t, ((W.hist + l.val : ℕ) : Word w).val < J.scratch.staging)
+ (live : ∀ n c, inv n c → LiveOperands (endAddr := endAddr) F S dfs saved common tmp
+ I J P (st) m level term W inv n c) :
+ ResidentMapLoop.Exact.Item (endAddr := endAddr) (loopProg) M m dfs inv (src)
+ (fun _ saved ↦ (action) saved) := by
+ have clock (n : Word w) (c : Config w p r) (entryPC : c.pc = (loopProg).item)
+ (atSrc : c.reg (loopProg).cursor = ((src) : Word w)) (hin : inv n c) :=
+ let h := live n c hin
+ row_native F G S pc dfs saved common own gatherReg tmp ret M link mapApart gatherApart X sel
+ site m level term R i I J hw P W (DFS.scratch endAddr c.privateMem) positive outside dfSafe
+ pubSafe stateSource layoutChoice party grid allowed sites old next c entryPC
+ ((congrArg Fin.val atSrc).trans
+ (Nat.mod_eq_of_lt (rowCursor_fit X sel side site m level term R i)))
+ h.head h.base h.stride h.one h.pubWords h.packets rfl h.prepare room histBefore
+ have safe (l : Fin 11) (lo : l.val < 6 ∨ 9 < l.val) : Protected S common tmp ((reg) l) := by
+ refine ⟨outside _, common.injective.ne (S.apart l).symm, ?_⟩
+ intro j a b
+ exact (reg).injective.ne (by intro eqn; rw [eqn] at lo; omega)
+ constructor
+ · intro node oldScratch es updated got
+ exact rowAction_noChoices F G X sel site m level term R i I J hw P W oldScratch
+ (J.trace_noChoices (G.operands (key)) (G.node (key)) P (st) m) got
+ · intro node c es updated enter cursor hin got
+ have run := clock node c enter cursor hin
+ change (action) (DFS.scratch endAddr c.privateMem) = some (es, updated) at got
+ rw [got] at run
+ obtain ⟨out, path, advance, frame, _, kept, memory, _, upper⟩ := run
+ exact ⟨out, advance, (live node c hin).preserve out kept memory,
+ kept _ (safe 2 (by decide)), kept _ (safe 3 (by decide)), kept _ (safe 10 (by decide)),
+ frame, upper, path⟩
+ · intro node c enter cursor hin got
+ have run := clock node c enter cursor hin
+ change (action) (DFS.scratch endAddr c.privateMem) = none at got
+ rw [got] at run
+ exact run
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationShrinkScheduledRow.lean b/lean/OAI/Computability/VPVNP/PairSimulationShrinkScheduledRow.lean
new file mode 100644
index 0000000000..e2fa4c9435
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationShrinkScheduledRow.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherRoute
+import OAI.Computability.VPVNP.PairSimulationShrinkRowAction
+import OAI.Computability.VPVNP.PairSimulationShrinkGatherRegisters
+
+/-!
+# One complete resident shrinking-map occurrence
+
+The published row identifies the motif, party and demand-grid value. The
+layout read enters the actual selected gather, whose scratch feeds the
+descriptor writer and grouped matrix. The resulting action covers both
+return to the enclosing row loop and rejection on a malformed local word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkMapImage.Registers
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords CompressorRecords.ShrinkSlots
+open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy
+open MotifGrid MotifBlocks MotifConversion MapResidentRows MapHandlerOperand NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+variable {K : Type} [Field K] {factor : ℝ}
+ {B : FixedBlock K demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor}
+ {p r t shared w g endAddr : ℕ} (F : MapHandlerImage.Family B t shared)
+ (G : ShrinkGatherBank.Family F) (S : Registers shared) (pc : GatherAddress F G → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : VertexImage.Saved ↪ Fin r) (common : Fin shared ↪ Fin r)
+ (own : F.PrivateReg ↪ Fin r) (gatherReg : G.PrivateReg ↪ Fin r) (tmp : Fin r) (ret : Fin p)
+ (M : Machine w p r 11) (link : GatherLinked F G S pc dfs saved common own gatherReg tmp ret M)
+ (mapApart : F.Apart dfs saved common own) (gatherApart : G.Apart dfs saved common gatherReg)
+ (X : State G.a (packingLaneBits G.a g)) {δ : ℝ}
+ {ready : Ready (2 ^ G.a) (2 * 2 ^ G.a + 1) (2 ^ G.b) δ} (sel : X.ShrinkSelection B)
+ (site : Site X) (m : Memory w) (level term : Word w)
+
+private noncomputable local instance scheduledRowBase : DecidableEq X.Base := Classical.decEq _
+variable {side : Bool}
+
+variable (R : MapRowSource X sel side m level term) (i : Fin (order X side site).length)
+ (I : LocalHistory.EntryInput B)
+
+local notation "entryPair" => MapResidentRows.entry X side site i
+local notation "z" => demandGrid B demandMass_pos I.demand
+local notation "key" => Prod.mk (z) I.party
+local notation "route" => routeEvents X sel side site m level term R i
+local notation "src" => rowCursor X sel side site m level term R i
+local notation "reg" => S.headerReg common
+
+variable {jobMotif : X.packingData.Motif}
+ (J : ShrinkPartyNative.Job (a := G.a) (b := G.b) (g := g) X B ready sel jobMotif I.party w)
+ (hw : MapConstants.widthThreshold B ≤ w) (P : Fin 5 → Word w)
+ (W : Workspace F demandMass_pos I) (oldScratch : DFS.Scratch w endAddr)
+
+local notation "st" => rowOrdinalWord (w := w) (a := G.a) (g := g) X side site i
+
+variable {absolute : Word w} {T U : IncidenceDirectory w} {origin layer pitch : ℕ}
+ {heads : SlotLevel.Heads}
+
+set_option maxHeartbeats 4000000 in
+-- Align the selected row's grid, dependent motif fields and program embeddings.
+include link mapApart gatherApart in
+theorem row_native (positive : 0 < w) (outside : ∀ b, common b ≠ tmp)
+ (dfSafe : ∀ j, Protected S common tmp (dfs j))
+ (pubSafe : ∀ j : Fin 5, Protected S common tmp (F.inputs dfs saved common (key) j.castSucc))
+ (stateSource : F.inputs dfs saved common (key) (Fin.last 5) = (reg) 6)
+ (layoutChoice : side = selectedLayout X B sel)
+ (party : (entryPair).2 = I.party) (grid : rowGrid (B := B) X side site i = (z))
+ (allowed : ℕ → Prop) (sites : ∀ c k, (J.row c k).ReadSafe
+ (ShrinkPartyNative.setups (G.operands (key)) (G.node (key)) G.a G.b I.party
+ (selectedLayout X B sel) c k)
+ allowed P (st) m)
+ (old : J.OldPublished (G.operands (key)) P (st) m level T origin)
+ (next : J.SupplyPublished (G.operands (key)) (G.node (key)) P (st) m heads
+ absolute U layer pitch)
+ (c : Config w p r) (start : c.pc = inputPC F (corePC F G pc) (.inr 0))
+ (cursor : (c.reg ((reg) 2)).val = (src)) (head : c.reg ((reg) 0) = level)
+ (base : c.reg ((reg) 4) = term) (stride : c.reg ((reg) 5) = 10) (one : c.reg ((reg) 10) = 1)
+ (inputs : ∀ j : Fin 5, c.reg (F.inputs dfs saved common (key) j.castSucc) = P j)
+ (packets : J.Packets endAddr c.privateMem)
+ (incoming : DFS.scratch endAddr c.privateMem = oldScratch)
+ (readyCall : ∀ out : Config w p r, J.Assembled c.privateMem out.privateMem →
+ MapHandlerOperand.pub F demandMass_pos I dfs saved common out = P →
+ MapHandlerOperand.state F demandMass_pos I dfs saved common out = (st) →
+ Prepared F demandMass_pos I dfs saved common out m W)
+ (room : Bounds F demandMass_pos I W endAddr (PhaseRecipe.Expr.eval P (st) m (F.base (key))))
+ (histBefore : ∀ l : Fin t, ((W.hist + l.val : ℕ) : Word w).val < J.scratch.staging) :
+ match rowAction F G X sel site m level term R i I J hw P W oldScratch with
+ | none => ∀ bs, ¬ DFS.Returns M c m bs
+ | some (es, updated) => ∃ out, Prefix M m c out [] es ∧
+ out.pc = loopPC F (corePC F G pc) true ∧ ShrinkRole.Frame dfs endAddr c out ∧
+ (∀ j, out.reg (dfs j) = c.reg (dfs j)) ∧
+ (∀ j, Protected S common tmp (common j) → out.reg (common j) = c.reg (common j)) ∧
+ (∀ q, q.val < J.scratch.staging →
+ q.val < (PhaseRecipe.Expr.eval P (st) m (F.base (key))).val ∨
+ (PhaseRecipe.Expr.eval P (st) m (F.base (key))).val +
+ Fintype.card ShrinkCallFields.Arg ≤ q.val →
+ MapCallSetup.Outside (F.layout (key)).core
+ ((F.layout (key)).corePC (F.layout (key)).locations) W q →
+ out.privateMem q = c.privateMem q) ∧
+ (∀ l : Fin t, out.privateMem ((W.hist + l.val : ℕ) : Word w) =
+ c.privateMem ((W.hist + l.val : ℕ) : Word w) +
+ (((names F demandMass_pos I).getD []).count l : Word w)) ∧
+ DFS.scratch endAddr out.privateMem = updated := by
+ obtain ⟨mid, pre, entry, ordinalReg, _, frozen, memEq, perEq⟩ :=
+ enterGather F G S pc dfs saved common own gatherReg tmp ret M link X sel side site m level term
+ R i positive outside c start cursor head base stride one
+ have f (q) (hq : Protected S common tmp q) := frozen q hq.1 hq.2.1 hq.2.2
+ have frame : ShrinkRole.Frame dfs endAddr c mid :=
+ ⟨fun j _ ↦ f _ (dfSafe j), fun q _ ↦ congrFun memEq q, perEq⟩
+ have atG : mid.pc = G.entry (gatherPC F G pc) (writer F G pc) (z) I.party
+ (selectedLayout X B sel) :=
+ entry.trans (congr (congr (congrArg (G.entry (gatherPC F G pc) (writer F G pc)) grid)
+ party) layoutChoice)
+ have stateReg : mid.reg (F.inputs dfs saved common (key) (Fin.last 5)) = (st) := by
+ rw [stateSource]
+ apply Fin.ext
+ exact ordinalReg.trans (Nat.mod_eq_of_lt (ordinalReg ▸ (mid.reg ((reg) 6)).isLt)).symm
+ have middle := gathered_native F G S pc dfs saved common own gatherReg tmp ret M link mapApart
+ gatherApart I J hw P (st) m W oldScratch allowed sites old next mid atG
+ (fun j ↦ (f _ (pubSafe j)).trans (inputs j)) stateReg (memEq ▸ packets)
+ ((congrArg (DFS.scratch endAddr) memEq).trans incoming)
+ (fun out staged ↦ readyCall out (memEq ▸ staged)) room histBefore
+ cases h : gatheredAction F G I J hw P (st) m W oldScratch with
+ | none =>
+ rw [h] at middle
+ simp only [rowAction, h, Option.map_none]
+ exact fun bs returns ↦ middle bs ((pre.returns bs).mp returns)
+ | some pair =>
+ obtain ⟨es, updated⟩ := pair
+ rw [h] at middle
+ obtain ⟨out, run, atEnd, mf, df, _, cf, memory, hist, us⟩ := middle
+ simp only [rowAction, h, Option.map_some]
+ refine ⟨out, pre.trans run, atEnd, frame.trans mf, fun j ↦ (df j).trans (f _ (dfSafe j)),
+ fun j safe ↦ (cf j).trans (f _ safe), ?_, ?_, us⟩
+ · intro q lo away ext
+ exact (memory q lo away ext).trans (congrFun memEq q)
+ · intro l
+ exact (hist l).trans (congrArg (fun v : Word w ↦ v + _) (congrFun memEq _))
+
+end PairSimulation.ShrinkMapImage.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationSliceReads.lean b/lean/OAI/Computability/VPVNP/PairSimulationSliceReads.lean
new file mode 100644
index 0000000000..7a50e2d47c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationSliceReads.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.CompressorRegisterSetupTrace
+import OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+/-!
+# External cells read by operand setup and private slice transfers
+
+The native setup reads only the cells reached by its evaluated load expressions.
+The slice header always reads its length and reads its offsets only for a nonempty
+intersection. The private bit loop adds no external reads.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.PhaseRecipe
+
+open BurstRAM
+
+theorem Expr.ReadsFrom.mono {w : ℕ} {data data' : ℕ → Prop} {pub : Fin 5 → Word w}
+ {state : Word w} {mem : Memory w} {e : Expr} (h : e.ReadsFrom data pub state mem)
+ (incl : ∀ i, data i → data' i) : e.ReadsFrom data' pub state mem := by
+ induction e with
+ | lit | state | publicWord => trivial
+ | load e ih => exact ⟨ih h.1, incl _ h.2⟩
+ | binary op a b ha hb => exact ⟨ha h.1, hb h.2⟩
+
+end CompressorRecords.PhaseRecipe
+
+namespace CompressorRecords.RegisterSetup
+
+open BurstRAM BurstRAM.PrivateRAM PhaseRecipe RowRecipe SourceTransport
+
+variable {w p r k n : ℕ} (f : Fin n → Expr) (inputs : Fin 6 → Fin r)
+ (vm : Fin (regCount f) ↪ Fin r)
+
+/-- The actual continuation trace of a linked setup reads only the cells visited by
+its evaluated load expressions, including nested loads that compute later addresses. -/
+theorem execute_setup_trace_reads (M : Machine w p r k) (m : Memory w) (pc : ℕ → Fin p)
+ (link : Linked vm inputs M pc (lines f)) (safe : ∀ i j, vm i ≠ inputs j)
+ (c : Config w p r) (hpc : c.pc = pc 0) (data : ℕ → Prop)
+ (allowed : ∀ i, (f i).ReadsFrom data (fun j : Fin 5 => c.reg (inputs j.castSucc))
+ (c.reg (inputs (Fin.last 5))) m) :
+ let pub := fun i : Fin 5 => c.reg (inputs i.castSucc)
+ let state := c.reg (inputs (Fin.last 5))
+ ∃ events d, Reads data events ∧ events.length = (lines f).length ∧
+ countProbes events = ∑ i, (f i).loads ∧ choiceBits events = [] ∧ d.pc = pc (lines f).length ∧
+ d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧
+ (∀ i, d.reg (vm (output f i)) = (f i).eval pub state m) ∧
+ (∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j) ∧
+ ∀ fuel bs, execute M.program (fuel + events.length) c m bs =
+ (execute M.program fuel d m bs).map (fun rep => ⟨events ++ rep.events, rep.result⟩) := by
+ intro pub state
+ let rs := fun i => c.reg (vm i)
+ let events := (evaluate pub state m (lines f) rs).1
+ obtain ⟨d, exitData⟩ := execute_setup_raw f inputs vm M m pc link safe c hpc
+ exact ⟨events, d, lines_reads f data pub state m allowed rs, exitData⟩
+
+end CompressorRecords.RegisterSetup
+
+namespace PairSimulation
+
+open BurstRAM CompressorRecords CompressorRecords.PhaseRecipe CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+variable {w : ℕ} {data : ℕ → Prop}
+
+/-- Guesses and copies within the private bit loop read no external cell. -/
+theorem PrivateFields.events_reads (mode : PrivateFields.Mode) (bs : List Bool) :
+ Reads data (PrivateFields.events (w := w) mode bs) :=
+ (FlowFootprint.bounds_of_noProbes data data (PrivateFields.events_work mode bs).2).1
+
+/-- The physical frame reads its length on every branch. Its offsets are needed
+only if that length is nonzero, even when the external cells contain stale values. -/
+theorem PrivateSlices.frameEvents_reads_iff (m : Memory w) (f : Word w) (bs : List Bool) :
+ Reads data (PrivateSlices.frameEvents m f bs) ↔
+ data (f + 1 + 1).val ∧ (m (f + 1 + 1).val ≠ 0 → data f.val ∧ data (f + 1).val) := by
+ have copy : Reads data (if bs.isEmpty then [] else PrivateFields.events (w := w) .copy bs) := by
+ split
+ · simp [Reads]
+ · exact PrivateFields.events_reads .copy bs
+ have header : Reads data (PrivateSlices.frameEvents m f bs) ↔
+ Reads data (PrivateSlices.headerEvents m f) := by
+ constructor
+ · exact fun h a v hv => h a v (List.mem_append_left _ hv)
+ · intro h a v hv
+ exact (List.mem_append.mp hv).elim (h a v) (copy a v)
+ rw [header]
+ by_cases empty : m (f + 1 + 1).val = 0
+ · simp [PrivateSlices.headerEvents, empty, Reads]
+ · simp [PrivateSlices.headerEvents, empty, Reads, or_imp, forall_and]
+
+theorem PrivateSlices.frameEvents_reads (m : Memory w) (f : Word w) (bs : List Bool)
+ (src : data f.val) (dst : data (f + 1).val) (len : data (f + 1 + 1).val) :
+ Reads data (PrivateSlices.frameEvents m f bs) :=
+ (PrivateSlices.frameEvents_reads_iff m f bs).mpr ⟨len, fun _ => ⟨src, dst⟩⟩
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationStackCalls.lean b/lean/OAI/Computability/VPVNP/PairSimulationStackCalls.lean
new file mode 100644
index 0000000000..905ef71d1b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationStackCalls.lean
@@ -0,0 +1,215 @@
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Data.Fintype.Card
+
+/-!
+# Exact branch streams of a bounded bit-stack call
+
+A stack call consumes one supplied bit at each binary choice. A halting
+instruction returns its status, stack bank, remaining instruction fuel and
+unused suffix. Section 13 can therefore run the next local test on the same
+stream. The complete accepted words form a finite set of cardinality exactly
+the bounded accepting path count of the stack code.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open RAMTape
+
+variable {K Q : Type*} [DecidableEq K]
+
+/-- State at a genuine halt. The final halt itself has spent one unit of fuel. -/
+structure Exit (K Q : Type*) where
+ /-- Boolean status of the halt reached by the bounded stack call. -/
+ accept : Bool
+ /-- Stack-code control state at which the halt instruction was executed. -/
+ state : Q
+ /-- Contents of each named bit stack when the call halted. -/
+ bank : Stacks K
+ /-- Suffix of the input choice stream left unconsumed at the halt. -/
+ rest : List Bool
+ /-- Instruction fuel remaining after charging the final halt instruction. -/
+ unused : ℕ
+
+/-- A binary choice reads one bit, including when its two successors coincide.
+Running out of fuel or choices before a halt returns `none`. -/
+def parse (code : StackCode K Q) : ℕ → Q → Stacks K → List Bool → Option (Exit K Q)
+ | 0, _, _, _ => none
+ | fuel + 1, q, s, bits =>
+ match code q with
+ | .push k b next => parse code fuel next (Function.update s k (b :: s k)) bits
+ | .pop k next => parse code fuel (next (s k).head?) (Function.update s k (s k).tail) bits
+ | .goto next => parse code fuel next s bits
+ | .choose low high =>
+ match bits with
+ | [] => none
+ | b :: more => parse code fuel (if b then high else low) s more
+ | .halt b => some ⟨b, q, s, bits, fuel⟩
+
+/-- Keep the suffix of a call which halted with the required status. -/
+def haltPrefix (b : Bool) (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K)
+ (bits : List Bool) : Option (List Bool) :=
+ match parse code fuel q s bits with
+ | none => none
+ | some x => if x.accept = b then some x.rest else none
+
+/-- Return the unused choice suffix when bounded stack execution reaches an accepting halt, and
+return `none` otherwise. -/
+abbrev acceptPrefix := @haltPrefix K Q _ true
+
+private def tag (b : Bool) : List Bool ↪ List Bool :=
+ ⟨List.cons b, fun _ _ h => (List.cons.inj h).2⟩
+
+private theorem disjoint_tags (low high : Finset (List Bool)) :
+ Disjoint (low.map (tag false)) (high.map (tag true)) := by
+ refine Finset.disjoint_left.mpr fun word hl hh => ?_
+ obtain ⟨a, _, rfl⟩ := Finset.mem_map.mp hl
+ obtain ⟨b, _, e⟩ := Finset.mem_map.mp hh
+ exact Bool.noConfusion (List.cons.inj e).1
+
+/-- Complete streams halting with the selected status. A one-bit tag keeps
+the two branch slots disjoint even when both continue at the same state. -/
+def haltWords (status : Bool) (code : StackCode K Q) : ℕ → Q → Stacks K → Finset (List Bool)
+ | 0, _, _ => ∅
+ | fuel + 1, q, s =>
+ match code q with
+ | .push k b next => haltWords status code fuel next (Function.update s k (b :: s k))
+ | .pop k next => haltWords status code fuel (next (s k).head?) (Function.update s k (s k).tail)
+ | .goto next => haltWords status code fuel next s
+ | .choose low high =>
+ (haltWords status code fuel low s).map (tag false) ∪
+ (haltWords status code fuel high s).map (tag true)
+ | .halt b => if b = status then {[]} else ∅
+
+/-- Finite set of exact choice words that lead from the supplied control state and stack bank
+to an accepting halt within the fuel bound. -/
+abbrev acceptedWords := @haltWords K Q _ true
+
+theorem acceptedWords_card (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K) :
+ (acceptedWords code fuel q s).card = stackPaths code fuel q s := by
+ induction fuel generalizing q s with
+ | zero => rfl
+ | succ fuel ih =>
+ cases hc : code q with
+ | push | pop | goto => simpa only [acceptedWords, haltWords, stackPaths, hc] using ih _ _
+ | choose low high =>
+ simp only [acceptedWords, haltWords, stackPaths, hc, Finset.card_union_of_disjoint
+ (disjoint_tags _ _), Finset.card_map]
+ exact congrArg₂ (· + ·) (ih low s) (ih high s)
+ | halt b => cases b <;> simp [acceptedWords, haltWords, stackPaths, hc]
+
+private theorem tag_prefix {b : Bool} {words : Finset (List Bool)} {bits rest : List Bool} :
+ (∃ pre ∈ words.map (tag b), bits = pre ++ rest) ↔
+ ∃ pre ∈ words, bits = b :: (pre ++ rest) := by
+ constructor
+ · rintro ⟨w, hw, rfl⟩
+ obtain ⟨pre, hpre, rfl⟩ := Finset.mem_map.mp hw
+ exact ⟨pre, hpre, rfl⟩
+ · rintro ⟨pre, hpre, rfl⟩
+ exact ⟨tag b pre, Finset.mem_map_of_mem _ hpre, rfl⟩
+
+/-- Every accepting or rejecting halt reads exactly one complete word for
+its status. The suffix can begin immediately with another stack call. -/
+theorem haltPrefix_iff (status : Bool) (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K)
+ (bits rest : List Bool) :
+ haltPrefix status code fuel q s bits = some rest ↔
+ ∃ pre ∈ haltWords status code fuel q s, bits = pre ++ rest := by
+ induction fuel generalizing q s bits with
+ | zero => simp [haltPrefix, parse, haltWords]
+ | succ fuel ih =>
+ cases hc : code q with
+ | push | pop | goto => simpa only [haltPrefix, parse, haltWords, hc] using ih _ _ _
+ | choose low high =>
+ simp only [haltWords, hc, Finset.mem_union, or_and_right, exists_or, tag_prefix]
+ cases bits with
+ | nil => simp [haltPrefix, parse, hc]
+ | cons b bits => cases b <;> simpa [haltPrefix, parse, hc] using ih _ s bits
+ | halt b =>
+ by_cases h : b = status <;> simp [haltPrefix, parse, haltWords, hc, h]
+
+theorem acceptPrefix_iff (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K)
+ (bits rest : List Bool) :
+ acceptPrefix code fuel q s bits = some rest ↔
+ ∃ pre ∈ acceptedWords code fuel q s, bits = pre ++ rest :=
+ haltPrefix_iff true code fuel q s bits rest
+
+/-- Distinct words accepted with an empty remaining suffix. -/
+abbrev CompleteStreams (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K) :=
+ {bs : List Bool // acceptPrefix code fuel q s bs = some []}
+
+private def streamEquiv (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K) :
+ CompleteStreams code fuel q s ≃ ↥(acceptedWords code fuel q s) :=
+ Equiv.subtypeEquivRight fun bs => by simp [acceptPrefix_iff]
+
+instance (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K) :
+ Fintype (CompleteStreams code fuel q s) :=
+ Fintype.ofEquiv _ (streamEquiv code fuel q s).symm
+
+theorem completeStreams_card (code : StackCode K Q) (fuel : ℕ) (q : Q) (s : Stacks K) :
+ Fintype.card (CompleteStreams code fuel q s) = stackPaths code fuel q s :=
+ (Fintype.card_congr (streamEquiv code fuel q s)).trans <|
+ (Fintype.card_coe _).trans (acceptedWords_card code fuel q s)
+
+/-- An extension of a halted input changes only the unused suffix. In
+particular, the stack bank and fuel handed to the next subroutine are the
+ones obtained by running the complete consumed word in isolation. -/
+theorem parse_append {code : StackCode K Q} {fuel : ℕ} {q : Q} {s : Stacks K}
+ {bits : List Bool} {x : Exit K Q} (h : parse code fuel q s bits = some x)
+ (more : List Bool) :
+ parse code fuel q s (bits ++ more) = some {x with rest := x.rest ++ more} := by
+ induction fuel generalizing q s bits with
+ | zero => simp [parse] at h
+ | succ fuel ih =>
+ cases hc : code q with
+ | push | pop | goto =>
+ simpa only [parse, hc] using ih (by simpa only [parse, hc] using h)
+ | choose low high =>
+ cases bits with
+ | nil => simp [parse, hc] at h
+ | cons b bits =>
+ simpa only [parse, hc, List.cons_append] using ih (by simpa only [parse, hc] using h)
+ | halt status =>
+ simp only [parse, hc, Option.some.injEq] at h ⊢
+ subst x
+ rfl
+
+/-- Recover the complete consumed word and the exact exit configuration
+from an arbitrary halted stream. -/
+theorem parse_split {code : StackCode K Q} {fuel : ℕ} {q : Q} {s : Stacks K}
+ {bits : List Bool} {x : Exit K Q} (h : parse code fuel q s bits = some x) :
+ ∃ pre, bits = pre ++ x.rest ∧
+ parse code fuel q s pre = some {x with rest := []} := by
+ induction fuel generalizing q s bits with
+ | zero => simp [parse] at h
+ | succ fuel ih =>
+ cases hc : code q with
+ | push | pop | goto =>
+ simpa only [parse, hc] using ih (by simpa only [parse, hc] using h)
+ | choose low high =>
+ cases bits with
+ | nil => simp [parse, hc] at h
+ | cons b bits =>
+ obtain ⟨pre, e, done⟩ := ih (by simpa only [parse, hc] using h)
+ exact ⟨b :: pre, congrArg (b :: ·) e, by simpa only [parse, hc] using done⟩
+ | halt status =>
+ simp only [parse, hc, Option.some.injEq] at h
+ subst x
+ exact ⟨[], rfl, by simp [parse, hc]⟩
+
+/-- A deterministic stack segment leaves the branch stream untouched and
+hands all remaining fuel to its successor. -/
+theorem parse_runs {code : StackCode K Q} {n q s next out}
+ (h : StackRuns code n q s next out) (fuel : ℕ) (bits : List Bool) :
+ parse code (fuel + n) q s bits = parse code fuel next out bits := by
+ induction h with
+ | nil => rfl
+ | cons hs _ ih => cases hs <;> simp_all [parse]
+
+end PairSimulation.StackMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationStackFootprint.lean b/lean/OAI/Computability/VPVNP/PairSimulationStackFootprint.lean
new file mode 100644
index 0000000000..ac4b5a310c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationStackFootprint.lean
@@ -0,0 +1,237 @@
+import OAI.Computability.VPVNP.PairSimulationStackNativeCalls
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Exact private writes of a stack nomination
+
+Popping a bit moves the top pointer and leaves its private cell intact. A
+later push can overwrite that same cell. The virtual leaf therefore keeps
+the entire ordered list of private writes, even when the final logical
+stack is empty. This list and the native tick/choice trace depend only on
+the source stack execution.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open RAMTape BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedCounter.GuessWord
+open StackCompiler (Reach)
+
+variable {w : ℕ}
+
+/-- A stack execution's chronological native events and private cell writes, including pushes
+whose cells may subsequently be popped or overwritten. -/
+structure Footprint (w : ℕ) where
+ /-- The native ticks and choice events generated by the bounded stack execution, in execution
+ order. -/
+ events : List (Event w)
+ /-- The sequence of private address and value pairs written by pushes, in the order they
+ update memory. -/
+ writes : List (Word w × Word w)
+
+/-- The machine's private cells after all pushes, in chronological order. -/
+def Footprint.applyWrites (f : Footprint w) (m : Word w → Word w) : Word w → Word w :=
+ f.writes.foldl (fun mem write => Function.update mem write.1 write.2) m
+
+/-- The updated cell depends only on the same input cell and the sequence
+of pushes. In particular a caller can apply the footprint to its scratch
+subarray without looking at the memory below it. -/
+theorem Footprint.applyWrites_congr (f : Footprint w) {m m' : Word w → Word w}
+ (a : Word w) (agree : m a = m' a) : f.applyWrites m a = f.applyWrites m' a := by
+ obtain ⟨es, writes⟩ := f
+ unfold applyWrites
+ dsimp only
+ induction writes generalizing m m' with
+ | nil => exact agree
+ | cons write writes ih =>
+ simp only [List.foldl_cons]
+ apply ih
+ by_cases h : a = write.1 <;> simp [h, agree]
+
+/-- Prefix the tail footprint with the earlier instruction's events and writes, preserving
+chronological order in both lists. -/
+def Footprint.prepend (tail : Footprint w) (events : List (Event w)) (writes : List (Word w × Word w)) :
+ Footprint w := ⟨events ++ tail.events, writes ++ tail.writes⟩
+
+variable {K Q : Type} [DecidableEq K]
+
+/-- Compute the native trace and private write list during bounded source
+interpretation. On a short choice stream the three padding ticks precede
+the missing choice. -/
+def footprint (L : Layout K w) (code : StackCode K Q) : ℕ → Q → Stacks K → List Bool → Footprint w
+ | 0, _, _, _ => ⟨[], []⟩
+ | fuel + 1, q, s, bits =>
+ match code q with
+ | .push k b next =>
+ (footprint L code fuel next (Function.update s k (b :: s k)) bits).prepend
+ (List.replicate 4 .tick) [(L.address k (s k).length, encodeBit w b)]
+ | .pop k next =>
+ (footprint L code fuel (next (s k).head?) (Function.update s k (s k).tail) bits).prepend
+ (List.replicate 4 .tick) []
+ | .goto next => (footprint L code fuel next s bits).prepend (List.replicate 4 .tick) []
+ | .choose low high =>
+ match bits with
+ | [] => ⟨List.replicate 3 .tick, []⟩
+ | b :: more => (footprint L code fuel (if b then high else low) s more).prepend
+ [.tick, .tick, .tick, .choice b] []
+ | .halt b => ⟨if b then [.tick] else [], []⟩
+
+/-- The stack instructions only touch private cells on every execution,
+including unfinished and rejected prefixes. -/
+theorem footprint_probes (L : Layout K w) (code : StackCode K Q) (fuel : ℕ)
+ (q : Q) (s : Stacks K) (bits : List Bool) :
+ countProbes (footprint L code fuel q s bits).events = 0 := by
+ have ticks (es : List (Event w)) : countProbes (List.replicate 4 .tick ++ es) = countProbes es := rfl
+ have choose (b : Bool) (es : List (Event w)) :
+ countProbes ([.tick, .tick, .tick, .choice b] ++ es) = countProbes es := rfl
+ induction fuel generalizing q s bits with
+ | zero => rfl
+ | succ fuel ih =>
+ cases hop : code q with
+ | push | pop | goto => simpa only [footprint, hop, Footprint.prepend, ticks] using ih _ _ _
+ | choose low high =>
+ cases bits with
+ | nil => simp only [footprint, hop]; rfl
+ | cons b more => simpa only [footprint, hop, Footprint.prepend, choose] using ih _ s more
+ | halt b => cases b <;> simp [footprint, hop, countProbes]
+
+/-- The native choice events are exactly the consumed prefix, and every
+continuing instruction has four transitions, followed by the halt jump. -/
+theorem footprint_parse (L : Layout K w) {code : StackCode K Q} {fuel : ℕ} {q : Q} {s : Stacks K}
+ {bits : List Bool} {x : Exit K Q} (h : parse code fuel q s bits = some x) (ok : x.accept = true) :
+ bits = choiceBits (footprint L code fuel q s bits).events ++ x.rest ∧
+ (footprint L code fuel q s bits).events.length + 4 * x.unused + 3 = 4 * fuel := by
+ induction fuel generalizing q s bits with
+ | zero => simp [parse] at h
+ | succ fuel ih =>
+ cases hop : code q with
+ | push | pop | goto =>
+ simp only [parse, hop] at h
+ obtain ⟨words, time⟩ := ih h
+ simp only [footprint, hop, Footprint.prepend, Flow.choiceBits_append, List.length_append,
+ List.length_replicate, show choiceBits (List.replicate 4 (.tick : Event w)) = [] from rfl, List.nil_append]
+ exact ⟨words, by omega⟩
+ | choose low high =>
+ cases bits with
+ | nil => simp [parse, hop] at h
+ | cons b more =>
+ simp only [parse, hop] at h
+ obtain ⟨words, time⟩ := ih h
+ simp only [footprint, hop, Footprint.prepend, choiceBits,
+ List.cons_append, List.nil_append, List.length_cons]
+ exact ⟨congrArg (b :: ·) words, by omega⟩
+ | halt status =>
+ simp only [parse, hop, Option.some.injEq] at h
+ subst x
+ change status = true at ok
+ subst status
+ simp [footprint, hop, choiceBits, Nat.mul_succ]
+ omega
+
+/-- The native code does not inspect extra source bits after an accepted
+halt. The chronological writes also stay fixed under extension. -/
+theorem footprint_append (L : Layout K w) {code : StackCode K Q} {fuel : ℕ} {q : Q} {s : Stacks K}
+ {bits : List Bool} {x : Exit K Q} (h : parse code fuel q s bits = some x) (more : List Bool) :
+ footprint L code fuel q s (bits ++ more) = footprint L code fuel q s bits := by
+ induction fuel generalizing q s bits with
+ | zero => simp [parse] at h
+ | succ fuel ih =>
+ cases hop : code q with
+ | push | pop | goto =>
+ simp only [parse, hop] at h
+ simp only [footprint, hop, ih h]
+ | choose low high =>
+ cases bits with
+ | nil => simp [parse, hop] at h
+ | cons b bs =>
+ simp only [parse, hop] at h
+ simp only [List.cons_append, footprint, hop, ih h]
+ | halt status => simp only [footprint, hop]
+
+variable {p r k : ℕ} {M : Machine w p r k} {code : StackCode K Q} {pc : Q → Fin 7 → Fin p}
+ {reg : Register K ↪ Fin r} {done : Fin p} {L : Layout K w}
+
+private theorem realized_from {start q : Q} {initial s : Stacks K}
+ (linked : Linked M code pc reg done) (hw : 0 < w)
+ (space : ∀ ⦃v u⦄, Reach code start initial v u → ∀ j, (u j).length ≤ L.capacity)
+ (reach : Reach code start initial q s) {fuel : ℕ} {bits : List Bool} {x : Exit K Q}
+ (parsed : parse code fuel q s bits = some x) (ok : x.accept = true)
+ (c : Config w p r) (atPC : c.pc = pc q 0) (rep : Represents L reg c s) :
+ let f := footprint L code fuel q s bits
+ ∃ out, Prefix M c f.events out ∧ out.pc = done ∧ Represents L reg out x.bank ∧
+ out.privateMem = f.applyWrites c.privateMem ∧ Frame L reg c out := by
+ induction fuel generalizing q s c bits with
+ | zero => simp [parse] at parsed
+ | succ fuel ih =>
+ have cont {next : Q} {st : Stacks K} {more : List Bool} {d : Config w p r}
+ {ev : List (Event w)} {writes : List (Word w × Word w)}
+ (reached : Reach code start initial next st) (hparse : parse code fuel next st more = some x)
+ (pref : Prefix M c ev d) (label : d.pc = pc next 0) (hr : Represents L reg d st)
+ (mem : d.privateMem = (Footprint.mk ev writes).applyWrites c.privateMem) (fr : Frame L reg c d) :
+ let f := (footprint L code fuel next st more).prepend ev writes
+ ∃ out, Prefix M c f.events out ∧ out.pc = done ∧ Represents L reg out x.bank ∧
+ out.privateMem = f.applyWrites c.privateMem ∧ Frame L reg c out := by
+ obtain ⟨out, run, endPC, hbank, last, frame⟩ := ih reached hparse d label hr
+ refine ⟨out, pref.append run, endPC, hbank, ?_, fr.trans frame⟩
+ rw [last, mem]
+ simp [Footprint.applyWrites, Footprint.prepend]
+ cases hop : code q with
+ | push a b next =>
+ have reached := reach.step (.push hop)
+ have room := space reached a
+ simp only [Function.update_self, List.length_cons] at room
+ obtain ⟨d, run, label, hr, mem, frame⟩ :=
+ push_prefix_memory linked hop atPC rep (space reach) (by omega)
+ simp only [parse, hop] at parsed
+ simp only [footprint, hop]
+ exact cont reached parsed run label hr mem frame
+ | pop a next =>
+ obtain ⟨d, run, label, hr, mem, frame⟩ := pop_prefix_memory linked hop atPC rep hw (space reach a)
+ simp only [parse, hop] at parsed
+ simp only [footprint, hop]
+ exact cont (reach.step (.pop hop)) parsed run label hr mem frame
+ | goto next =>
+ obtain ⟨d, run, label, hr, mem, frame⟩ := goto_prefix_memory linked hop atPC rep
+ simp only [parse, hop] at parsed
+ simp only [footprint, hop]
+ exact cont (reach.step (.goto hop)) parsed run label hr mem frame
+ | choose low high =>
+ cases bits with
+ | nil => simp [parse, hop] at parsed
+ | cons b more =>
+ obtain ⟨d, run, label, hr, mem, frame⟩ := choose_prefix_memory linked hop atPC rep b
+ have reached : Reach code start initial (if b then high else low) s := by
+ cases b with
+ | false => exact .low reach hop
+ | true => exact .high reach hop
+ simp only [parse, hop] at parsed
+ simp only [footprint, hop]
+ exact cont reached parsed run label hr mem frame
+ | halt b =>
+ simp only [parse, hop, Option.some.injEq] at parsed
+ subst x
+ change b = true at ok
+ subst b
+ simpa only [footprint, hop, ↓reduceIte, Footprint.applyWrites, List.foldl_nil] using
+ halt_prefix_memory linked hop atPC rep
+
+/-- Realize the computed tick/choice trace and the entire final private
+memory, including overwritten or stale cells. The prefix theorem allows
+any continuation and external memory. -/
+theorem footprint_native {q : Q} {s : Stacks K} (linked : Linked M code pc reg done)
+ (hw : 0 < w) (space : ∀ ⦃v u⦄, Reach code q s v u → ∀ j, (u j).length ≤ L.capacity)
+ {fuel : ℕ} {bits : List Bool} {x : Exit K Q} (parsed : parse code fuel q s bits = some x)
+ (ok : x.accept = true) (c : Config w p r) (atPC : c.pc = pc q 0) (rep : Represents L reg c s) :
+ let f := footprint L code fuel q s bits
+ ∃ out, Prefix M c f.events out ∧ out.pc = done ∧ Represents L reg out x.bank ∧
+ out.privateMem = f.applyWrites c.privateMem ∧ Frame L reg c out :=
+ realized_from linked hw space .initial parsed ok c atPC rep
+
+end PairSimulation.StackMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationStackMemory.lean b/lean/OAI/Computability/VPVNP/PairSimulationStackMemory.lean
new file mode 100644
index 0000000000..ba9fc695fb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationStackMemory.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.PairSimulationStackTable
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+
+/-!
+# Private bit-stack storage of the virtual validator
+
+Each finite port has a disjoint private interval. Its empty pointer is
+the interval base and its top pointer is the exclusive end of the occupied
+cells. The top-first bit list occupies those cells in reverse order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open RAMTape BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {K : Type} {w p r : ℕ}
+
+/-- Private memory layout for named bit stacks, with a base for each stack and a common
+capacity whose disjoint intervals and exclusive ends fit the machine address space. -/
+structure Layout (K : Type) (w : ℕ) where
+ /-- Natural address of the first private bit cell reserved for each named stack. -/
+ base : K → ℕ
+ /-- Number of private bit cells reserved for each stack. -/
+ capacity : ℕ
+ fits : ∀ a, base a + capacity < 2^w
+ apart : ∀ a b, a ≠ b → base a + capacity ≤ base b ∨ base b + capacity ≤ base a
+
+/-- Machine-word address of the cell at offset `i` from the base of stack `a`. -/
+def Layout.address (L : Layout K w) (a : K) (i : ℕ) : Word w := ((L.base a+i : ℕ) : Word w)
+
+theorem Layout.address_val (L : Layout K w) (a : K) {i : ℕ} (hi : i ≤ L.capacity) :
+ (L.address a i).val = L.base a+i :=
+ Nat.mod_eq_of_lt ((Nat.add_le_add_left hi _).trans_lt (L.fits a))
+
+/-- Cell at offset equal to the length of the suffix after this bit. -/
+def Layout.Contents (L : Layout K w) (mem : Word w → Word w) (s : Stacks K) : Prop :=
+ ∀ a pre bit tail, s a = pre ++ bit :: tail → mem (L.address a tail.length) = encodeBit w bit
+
+/-- The RAM configuration realizes the logical stack bank by holding zero and one, the base and
+exclusive top pointers, and the occupied cells in bottom-to-top order. -/
+structure Represents (L : Layout K w) (reg : Register K ↪ Fin r) (c : Config w p r) (s : Stacks K) : Prop where
+ unit : c.reg (reg .one) = 1
+ zero : c.reg (reg .zero) = 0
+ bases : ∀ a, c.reg (reg (.base a)) = L.address a 0
+ tops : ∀ a, c.reg (reg (.top a)) = L.address a (s a).length
+ cells : L.Contents c.privateMem s
+
+theorem Layout.contents_of_reverse (L : Layout K w) (mem : Word w → Word w) (s : Stacks K)
+ (h : ∀ a (i : Fin (s a).reverse.length), mem (L.address a i.val) = encodeBit w ((s a).reverse[i.val])) :
+ L.Contents mem s := by
+ intro a pre b tail eq
+ have hi : tail.length < (s a).reverse.length := by simp [eq]
+ have hc := h a ⟨tail.length,hi⟩
+ simpa [eq,List.reverse_append,List.reverse_cons,List.append_assoc] using hc
+
+theorem Layout.contents_push [DecidableEq K] (L : Layout K w) (mem : Word w → Word w)
+ (s : Stacks K) (k : K) (bit : Bool) (old : L.Contents mem s)
+ (fit : ∀ a, (s a).length ≤ L.capacity) (space : (s k).length < L.capacity) :
+ L.Contents (Function.update mem (L.address k (s k).length) (encodeBit w bit))
+ (Function.update s k (bit :: s k)) := by
+ intro a pre b tail h
+ by_cases hk : a = k
+ · subst a
+ rw [Function.update_self] at h
+ cases pre with
+ | nil =>
+ obtain ⟨rfl,rfl⟩ := List.cons.inj h
+ exact Function.update_self ..
+ | cons x pre =>
+ have hs : s k = pre ++ b :: tail := (List.cons.inj h).2
+ have hlen : tail.length < (s k).length := by rw [hs]; simp; omega
+ have hne : L.address k tail.length ≠ L.address k (s k).length := by
+ intro haddr
+ have he := congrArg Fin.val haddr
+ rw [L.address_val _ (hlen.le.trans space.le), L.address_val _ space.le] at he
+ omega
+ rw [Function.update_of_ne hne]
+ exact old k pre b tail hs
+ · rw [Function.update_of_ne hk] at h
+ have hlen : tail.length < (s a).length := by rw [h]; simp; omega
+ have hne : L.address a tail.length ≠ L.address k (s k).length := by
+ intro haddr
+ have he := congrArg Fin.val haddr
+ rw [L.address_val _ (hlen.le.trans (fit a)), L.address_val _ space.le] at he
+ rcases L.apart a k hk with sep | sep <;> have := fit a <;> omega
+ rw [Function.update_of_ne hne]
+ exact old a pre b tail h
+
+theorem Layout.contents_pop [DecidableEq K] (L : Layout K w) (mem : Word w → Word w)
+ (s : Stacks K) (k : K) (old : L.Contents mem s) :
+ L.Contents mem (Function.update s k (s k).tail) := by
+ intro a pre b tail h
+ by_cases hk : a = k
+ · subst a
+ rw [Function.update_self] at h
+ cases he : s k with
+ | nil => simp [he] at h
+ | cons x xs =>
+ have hs : s k = (x::pre) ++ b :: tail := by simpa [he] using congrArg (x::·) h
+ exact old k (x::pre) b tail hs
+ · rw [Function.update_of_ne hk] at h
+ exact old a pre b tail h
+
+end PairSimulation.StackMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationStackNativeCalls.lean b/lean/OAI/Computability/VPVNP/PairSimulationStackNativeCalls.lean
new file mode 100644
index 0000000000..00ff119d73
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationStackNativeCalls.lean
@@ -0,0 +1,256 @@
+import OAI.Computability.VPVNP.PairSimulationStackCalls
+import OAI.Computability.VPVNP.PairSimulationStackSteps
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+import OAI.Computability.VPVNP.RAMTapeSpace
+import Mathlib.SetTheory.Cardinal.Finite
+
+/-!
+# Running a virtual stack call inside the native pair simulation
+
+The private RAM rows consume exactly the source branch prefix, ending with
+the same stack bank. The caller may use every bit left over. Closing the call
+with an accepting continuation recovers exactly the bounded stack path count,
+including coincident successors of a choice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open RAMTape BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord
+open StackCompiler (Reach)
+
+variable {K Q : Type} [DecidableEq K] {w p r k : ℕ}
+ {M : Machine w p r k} {code : StackCode K Q} {pc : Q → Fin 7 → Fin p}
+ {reg : Register K ↪ Fin r} {done : Fin p} {L : Layout K w}
+
+/-- The exact native prefix of an accepted call and the interpreter's
+behavior on every other stream. Each continuing stack row costs four
+native instructions and a true halt costs one. Thus three instructions
+from the final row are available to its continuation. -/
+def NativeCall (M : Machine w p r k) (L : Layout K w) (reg : Register K ↪ Fin r)
+ (done : Fin p) (extra clock : ℕ) (c : Config w p r) (m : Memory w) (bits : List Bool)
+ (result : Option (Exit K Q)) : Prop :=
+ match result with
+ | some x =>
+ if x.accept then ∃ es out, Prefix M c es out ∧ out.pc = done ∧
+ Represents L reg out x.bank ∧ Frame L reg c out ∧
+ bits = choiceBits es ++ x.rest ∧ es.length + 4 * x.unused + 3 = clock
+ else execute M.program (extra + clock) c m bits = none
+ | none => execute M.program (extra + clock) c m bits = none
+
+omit [DecidableEq K] in
+private theorem prepend {c d : Config w p r} {es : List (Event w)}
+ {extra clock : ℕ} {m : Memory w} {bits : List Bool} {res : Option (Exit K Q)}
+ (pref : Prefix M c es d) (frame : Frame L reg c d)
+ (tail : NativeCall M L reg done extra clock d m bits res) :
+ NativeCall M L reg done extra (clock + es.length) c m (choiceBits es ++ bits) res := by
+ cases res with
+ | none =>
+ change execute M.program (extra + (clock + es.length)) c m _ = none
+ rw [← Nat.add_assoc, pref.execute, tail]
+ rfl
+ | some x =>
+ by_cases hx : x.accept = true <;> simp only [NativeCall, hx, ↓reduceIte] at tail ⊢
+ · obtain ⟨fs, out, run, hout, rep, fr, hbits, time⟩ := tail
+ refine ⟨es ++ fs, out, pref.append run, hout, rep, frame.trans fr, ?_, ?_⟩
+ · simp only [PrimedInputRAM.Flow.choiceBits_append, List.append_assoc, hbits]
+ · rw [List.length_append]
+ omega
+ · rw [← Nat.add_assoc, pref.execute, tail]
+ rfl
+
+private theorem parse_native_from {start q : Q} {initial s : Stacks K}
+ (linked : Linked M code pc reg done) (hw : 0 < w)
+ (space : ∀ ⦃v u⦄, Reach code start initial v u → ∀ j, (u j).length ≤ L.capacity)
+ (reach : Reach code start initial q s) (fuel extra : ℕ)
+ (cutoff : extra = 0 ∨ StopsWithin code fuel q s)
+ (c : Config w p r) (atPC : c.pc = pc q 0) (rep : Represents L reg c s)
+ (m : Memory w) (bits : List Bool) :
+ NativeCall M L reg done extra (4 * fuel) c m bits (parse code fuel q s bits) := by
+ induction fuel generalizing q s c bits with
+ | zero =>
+ obtain rfl := cutoff.resolve_right (by simp [StopsWithin])
+ rfl
+ | succ fuel ih =>
+ have cont {next : Q} {out : Stacks K} {d : Config w p r} {es : List (Event w)}
+ {more : List Bool} (reached : Reach code start initial next out)
+ (cuts : extra = 0 ∨ StopsWithin code fuel next out)
+ (step : Prefix M c es d) (label : d.pc = pc next 0) (hr : Represents L reg d out)
+ (fr : Frame L reg c d) (used : bits = choiceBits es ++ more) (ticks : es.length = 4) :
+ NativeCall M L reg done extra (4 * (fuel + 1)) c m bits (parse code fuel next out more) := by
+ simpa only [Nat.mul_succ, ← used, ticks] using
+ prepend step fr (ih reached cuts d label hr more)
+ cases hop : code q with
+ | push a b next =>
+ have reached := reach.step (.push hop)
+ have capacity := space reached a
+ simp only [Function.update_self, List.length_cons] at capacity
+ obtain ⟨d, run, label, hr, frame⟩ :=
+ push_prefix linked hop atPC rep (space reach) (by omega)
+ simp only [parse, hop]
+ exact cont reached (cutoff.imp_right fun h => by simpa only [StopsWithin, hop] using h)
+ run label hr frame rfl rfl
+ | pop a next =>
+ obtain ⟨d, run, label, hr, frame⟩ := pop_prefix linked hop atPC rep hw (space reach a)
+ simp only [parse, hop]
+ exact cont (reach.step (.pop hop)) (cutoff.imp_right fun h => by simpa only [StopsWithin, hop] using h)
+ run label hr frame rfl rfl
+ | goto next =>
+ obtain ⟨d, run, label, hr, frame⟩ := goto_prefix linked hop atPC rep
+ simp only [parse, hop]
+ exact cont (reach.step (.goto hop)) (cutoff.imp_right fun h => by simpa only [StopsWithin, hop] using h)
+ run label hr frame rfl rfl
+ | choose low high =>
+ cases bits with
+ | nil =>
+ simp only [parse, hop, NativeCall]
+ obtain ⟨_, run, _⟩ := choose_prefix linked hop atPC rep false
+ exact run.execute_short _ m [] [] false rfl
+ | cons b more =>
+ obtain ⟨d, run, label, hr, frame⟩ := choose_prefix linked hop atPC rep b
+ have reached : Reach code start initial (if b then high else low) s := by
+ cases b with
+ | false => exact .low reach hop
+ | true => exact .high reach hop
+ have cuts := cutoff.imp_right fun h => by
+ simp only [StopsWithin, hop] at h
+ exact (show StopsWithin code fuel (if b then high else low) s from
+ by cases b <;> first | exact h.1 | exact h.2)
+ simp only [parse, hop]
+ exact cont reached cuts run label hr frame rfl rfl
+ | halt b =>
+ cases b with
+ | false =>
+ simp only [parse, hop, NativeCall, Bool.false_eq_true, ↓reduceIte]
+ rw [Nat.mul_succ, show extra + (4 * fuel + 4) = (extra + 4 * fuel + 3) + 1 by omega]
+ simp [execute, halt_reject linked hop atPC]
+ | true =>
+ obtain ⟨d, run, label, hr, frame⟩ := halt_prefix linked hop atPC rep
+ simp only [parse, hop, NativeCall, ↓reduceIte]
+ exact ⟨_, d, run, label, hr, frame, rfl, by simp [Nat.mul_succ]; omega⟩
+
+/-- A bounded source run needs at most one additional cell per source
+instruction on each stack. This gives an interval size when a separate
+space estimate is unavailable. -/
+theorem reachable_capacity {q : Q} {s : Stacks K} {fuel cap : ℕ}
+ (halt : StopsWithin code fuel q s) (fit : ∀ j, (s j).length + fuel ≤ cap)
+ {v : Q} {u : Stacks K} (path : Reach code q s v u) (j : K) :
+ (u j).length ≤ cap := by
+ have carries : ∃ t, StopsWithin code t v u ∧ ∀ i, (u i).length + t ≤ cap := by
+ induction path with
+ | initial => exact ⟨fuel, halt, fit⟩
+ | step _ move ih =>
+ obtain ⟨t, stops, room⟩ := ih
+ cases t with
+ | zero => exact stops.elim
+ | succ t =>
+ cases move with
+ | push h =>
+ refine ⟨t, by simpa only [StopsWithin, h] using stops, fun i => ?_⟩
+ have hi := room i
+ rw [Function.update_apply]
+ split_ifs with e
+ · subst i; simp only [List.length_cons]; omega
+ · omega
+ | pop h =>
+ refine ⟨t, by simpa only [StopsWithin, h] using stops, fun i => ?_⟩
+ have hi := room i
+ rw [Function.update_apply]
+ split_ifs with e
+ · subst i; simp only [List.length_tail]; omega
+ · omega
+ | goto h =>
+ refine ⟨t, by simpa only [StopsWithin, h] using stops, fun i => ?_⟩
+ have := room i
+ omega
+ | low _ h ih | high _ h ih =>
+ obtain ⟨t, stops, room⟩ := ih
+ cases t with
+ | zero => exact stops.elim
+ | succ t =>
+ simp only [StopsWithin, h] at stops
+ refine ⟨t, ?_, fun i => (Nat.le_add_right _ 1).trans (room i)⟩
+ first | exact stops.1 | exact stops.2
+ obtain ⟨t, _, room⟩ := carries
+ exact (Nat.le_add_right _ _).trans (room j)
+
+/-- Every branch of the private RAM stack fragment agrees with the source
+interpreter. At the exact native cutoff no source termination premise is
+needed. A source stopping bound also permits arbitrary extra native fuel. -/
+theorem parse_native {q : Q} {s : Stacks K} (linked : Linked M code pc reg done) (hw : 0 < w)
+ (space : ∀ ⦃v u⦄, Reach code q s v u → ∀ j, (u j).length ≤ L.capacity)
+ (fuel extra : ℕ) (cutoff : extra = 0 ∨ StopsWithin code fuel q s)
+ (c : Config w p r) (atPC : c.pc = pc q 0) (rep : Represents L reg c s)
+ (m : Memory w) (bits : List Bool) :
+ NativeCall M L reg done extra (4 * fuel) c m bits (parse code fuel q s bits) :=
+ parse_native_from linked hw space .initial fuel extra cutoff c atPC rep m bits
+
+/-- For a true source halt, the caller resumes from the actual native
+configuration, with arbitrary continuation fuel and the entire unused suffix. -/
+theorem execute_continuation {q : Q} {s : Stacks K} (linked : Linked M code pc reg done)
+ (hw : 0 < w) (space : ∀ ⦃v u⦄, Reach code q s v u → ∀ j, (u j).length ≤ L.capacity)
+ {fuel : ℕ} {bits : List Bool} {x : Exit K Q} (accepted : parse code fuel q s bits = some x)
+ (ok : x.accept = true) (c : Config w p r) (atPC : c.pc = pc q 0) (rep : Represents L reg c s)
+ (m : Memory w) :
+ ∃ es out, out.pc = done ∧ Represents L reg out x.bank ∧ Frame L reg c out ∧
+ bits = choiceBits es ++ x.rest ∧ es.length + 4 * x.unused + 3 = 4 * fuel ∧
+ ∀ t, execute M.program (t + es.length) c m bits =
+ (execute M.program t out m x.rest).map (fun r => ⟨es ++ r.events, r.result⟩) := by
+ have h := parse_native linked hw space fuel 0 (.inl rfl) c atPC rep m bits
+ simp only [accepted, NativeCall, ok, ↓reduceIte] at h
+ obtain ⟨es, out, pref, label, hr, frame, used, time⟩ := h
+ exact ⟨es, out, label, hr, frame, used, time, fun t => by rw [used]; exact pref.execute t m x.rest⟩
+
+/-- Closing with the native accept instruction consumes exactly one of
+the complete successful source words. This holds even with coincident
+choice successors and early halts. -/
+theorem execute_accept_iff {q : Q} {s : Stacks K} (linked : Linked M code pc reg done)
+ (close : M.code done = .accept) (hw : 0 < w)
+ (space : ∀ ⦃v u⦄, Reach code q s v u → ∀ j, (u j).length ≤ L.capacity)
+ (fuel extra : ℕ) (cutoff : extra = 0 ∨ StopsWithin code fuel q s)
+ (c : Config w p r) (atPC : c.pc = pc q 0) (rep : Represents L reg c s)
+ (m : Memory w) (bits : List Bool) :
+ (execute M.program (extra + 4 * fuel) c m bits).isSome = true ↔
+ acceptPrefix code fuel q s bits = some [] := by
+ have call := parse_native linked hw space fuel extra cutoff c atPC rep m bits
+ cases hx : parse code fuel q s bits with
+ | none =>
+ simp only [hx, NativeCall] at call
+ simp [call, acceptPrefix, haltPrefix, hx]
+ | some x =>
+ cases ok : x.accept with
+ | false =>
+ simp only [hx, NativeCall, ok, Bool.false_eq_true, ↓reduceIte] at call
+ simp [call, acceptPrefix, haltPrefix, hx, ok]
+ | true =>
+ simp only [hx, NativeCall, ok, ↓reduceIte] at call
+ obtain ⟨es, out, pref, label, _, _, used, time⟩ := call
+ have step : M.program.step out = .finish none := by simp [Machine.program, label, close, Instr.run]
+ simp only [acceptPrefix, haltPrefix, hx, ok, ↓reduceIte, Option.some.injEq]
+ rw [show extra + 4 * fuel = (extra + 4 * x.unused + 2 + 1) + es.length by omega,
+ used, pref.execute, execute, step]
+ by_cases hrest : x.rest = [] <;> simp [hrest]
+
+/-- The native private RAM call has the same multiplicity as the capped
+stack machine. All initial banks obeying the representation and every
+external memory give the same equality. -/
+theorem nativeStreams_card {q : Q} {s : Stacks K} (linked : Linked M code pc reg done)
+ (close : M.code done = .accept) (hw : 0 < w)
+ (space : ∀ ⦃v u⦄, Reach code q s v u → ∀ j, (u j).length ≤ L.capacity)
+ (fuel extra : ℕ) (cutoff : extra = 0 ∨ StopsWithin code fuel q s)
+ (c : Config w p r) (atPC : c.pc = pc q 0) (rep : Represents L reg c s) (m : Memory w) :
+ Nat.card {bs : List Bool // (execute M.program (extra + 4 * fuel) c m bs).isSome = true} =
+ stackPaths code fuel q s := by
+ let same : {bs : List Bool // (execute M.program (extra + 4 * fuel) c m bs).isSome = true} ≃
+ CompleteStreams code fuel q s := Equiv.subtypeEquivRight fun bs =>
+ execute_accept_iff linked close hw space fuel extra cutoff c atPC rep m bs
+ rw [Nat.card_congr same, Nat.card_eq_fintype_card, completeStreams_card]
+
+end PairSimulation.StackMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationStackScratch.lean b/lean/OAI/Computability/VPVNP/PairSimulationStackScratch.lean
new file mode 100644
index 0000000000..3d935482f5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationStackScratch.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairSimulationStackFootprint
+import OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+/-!
+# A stack leaf inside the private DFS workspace
+
+The live pending descriptor addresses lie below the private stack intervals.
+A source rejection precludes a successful native call at every instruction
+budget. On acceptance the ordered writes define an update of the caller's
+scratch, including stale cells above the current stack tops.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open RAMTape BurstRAM BurstRAM.PrivateRAM
+open StackCompiler (Reach)
+open scoped Fin.CommRing
+open private guessed_addFuel from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+variable {w p r k : ℕ} {K Q : Type} {L : Layout K w}
+ {reg : Register K ↪ Fin r} {c out : Config w p r}
+
+/-- Update the scratch cells using the complete ordered sequence of pushes.
+The value supplied for addresses below the scratch is immaterial. -/
+def Footprint.applyScratch (f : Footprint w) (endAddr : ℕ) (s : DFS.Scratch w endAddr) :
+ DFS.Scratch w endAddr :=
+ fun a => f.applyWrites (fun b => if h : endAddr ≤ b.val then s ⟨b, h⟩ else 0) a.val
+
+theorem Footprint.scratch_applyWrites (f : Footprint w) (endAddr : ℕ) (m : Word w → Word w) :
+ DFS.scratch endAddr (f.applyWrites m) = f.applyScratch endAddr (DFS.scratch endAddr m) := by
+ funext a
+ apply f.applyWrites_congr
+ simp [DFS.scratch, a.property]
+
+/-- Every descriptor below the workspace boundary survives the virtual
+stack execution at its exact pending address. -/
+theorem Frame.keepsPending (frame : Frame L reg c out) {endAddr top : ℕ} {pending : List (Word w)}
+ (above : ∀ j, endAddr ≤ L.base j) (htop : top + pending.length = endAddr)
+ (pendingRep : DFS.Represents c.privateMem top pending) :
+ DFS.Represents out.privateMem top pending := by
+ refine ⟨pendingRep.1, fun i => ?_⟩
+ refine (frame.memory _ fun j => Or.inl ?_).trans (pendingRep.2 i)
+ change ((top + i.val : ℕ) : Word w).val < L.base j
+ have h := pendingRep.1
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt (by have := i.isLt; omega)]
+ have := above j
+ have := i.isLt
+ omega
+
+/-- Preserve each dispatcher register under the two disjoint assignments
+of physical registers. -/
+theorem Frame.dfsReg (frame : Frame L reg c out) (dfs : Fin 9 ↪ Fin r)
+ (apart : ∀ i j, dfs i ≠ reg j) (i : Fin 9) : out.reg (dfs i) = c.reg (dfs i) :=
+ frame.regs _ (fun ⟨j, h⟩ => apart i j h.symm)
+
+variable [DecidableEq K] {M : Machine w p r k} {code : StackCode K Q} {pc : Q → Fin 7 → Fin p}
+ {done : Fin p} {q : Q} {s : Stacks K} {fuel : ℕ}
+
+/-- Missing source choices and rejecting source halts both rule out any
+successful native execution, including one with a smaller budget than
+the stack simulation's advertised clock. -/
+theorem rejects_returns (linked : Linked M code pc reg done) (hw : 0 < w)
+ (space : ∀ ⦃v u⦄, Reach code q s v u → ∀ j, (u j).length ≤ L.capacity)
+ (stops : StopsWithin code fuel q s) (c : Config w p r) (atPC : c.pc = pc q 0)
+ (rep : Represents L reg c s) (m : Memory w) (bits : List Bool)
+ (bad : acceptPrefix code fuel q s bits = none) : ¬DFS.Returns M c m bits := by
+ rintro ⟨f, report, ran⟩
+ obtain ⟨trace, correct, consumed⟩ := execute_iff.mp ran
+ have large := execute_iff.mpr ⟨guessed_addFuel trace (4 * fuel), correct, consumed⟩
+ rw [Nat.add_comm (4 * fuel) f] at large
+ have call := parse_native linked hw space fuel f (.inr stops) c atPC rep m bits
+ cases h : parse code fuel q s bits with
+ | none => simp [NativeCall, h, large] at call
+ | some x => cases ok : x.accept with
+ | true => simp [acceptPrefix, haltPrefix, h, ok] at bad
+ | false => simp [NativeCall, h, ok, large] at call
+
+end PairSimulation.StackMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationStackSpace.lean b/lean/OAI/Computability/VPVNP/PairSimulationStackSpace.lean
new file mode 100644
index 0000000000..0ad977527f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationStackSpace.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.PairSimulationStackMemory
+import OAI.Computability.VPVNP.PairSimulationLeafCount
+import OAI.Computability.VPVNP.RAMProcessorPhysicalClock
+
+/-!
+# Space and instruction bounds for private simulation of a virtual cursor leaf
+
+Stack ports occupy consecutive, equal-sized intervals in private memory. At a
+virtual site the initial stacks contain only public operand bits, unary clocks,
+and the site's incident data. One additional bit per simulated step suffices
+even when a malformed candidate uses its entire clock.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open BurstRAM Filter
+
+variable {K : Type} {w : ℕ}
+
+/-- Consecutive port intervals, each with one-past-top pointer representable. -/
+def Layout.consecutive {ports : ℕ} (ord : K ↪ Fin ports) (start cap : ℕ)
+ (fit : start + ports * cap < 2^w) : Layout K w where
+ base i := start + (ord i).val * cap
+ capacity := cap
+ fits i := by
+ have h := Nat.mul_le_mul_right cap (ord i).isLt
+ rw [Nat.succ_mul] at h
+ omega
+ apart a b ne := by
+ have h : (ord a).val ≠ (ord b).val := fun he => ne (ord.injective (Fin.ext he))
+ rcases lt_or_gt_of_ne h with lt | gt
+ · left
+ have h := Nat.mul_le_mul_right cap lt
+ rw [Nat.succ_mul] at h; omega
+ · right
+ have h := Nat.mul_le_mul_right cap gt
+ rw [Nat.succ_mul] at h; omega
+
+/-- A fixed polynomial-size scratch arena, after any polynomial-size prefix,
+fits in a live RAM word. -/
+theorem eventually_port_space {B : ℕ} (hB : 1 ≤ B) (ports offsetExp capExp : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ start cap : ℕ, start ≤ n^offsetExp → cap ≤ n^capExp →
+ start + ports*cap < 2^CursorBounds.wordBits B n := by
+ let e := max offsetExp capExp
+ filter_upwards [eventually_ge_atTop (ports+1), eventually_polynomial_lt_wordModulus (e+1)] with n hn hw
+ intro start cap hs hc
+ have h₁ : 1 ≤ n := by omega
+ have ho := hs.trans (Nat.pow_le_pow_right h₁ (le_max_left offsetExp capExp))
+ have hp := hc.trans (Nat.pow_le_pow_right h₁ (le_max_right offsetExp capExp))
+ apply lt_of_le_of_lt _ (hw _ (log2_le_addressWidth hB n))
+ calc
+ _ ≤ n^e + ports*n^e := Nat.add_le_add ho (Nat.mul_le_mul_left _ hp)
+ _ = (ports+1)*n^e := by ring
+ _ ≤ n*n^e := Nat.mul_le_mul_right _ hn
+ _ = n^(e+1) := (pow_succ' ..).symm
+
+end PairSimulation.StackMachine
+
+namespace PairSimulation.LeafStartup
+
+open RAMTape RAMTape.SiteProcessor RAMTape.SiteProcessorPorts BurstRAM RAMLayout Filter
+
+variable {d e w n k : ℕ} (x : VirtualSite.Input d e w) (r : ℕ)
+
+/-- The complete source interpreter clock of this leaf, uniformly in the
+address and all input bits. It includes nomination, execution and sorting. -/
+theorem eventually_steps (r : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ d e w (x : VirtualSite.Input d e w),
+ ProcessorBudget n d e w → x.fuel ≤ n^10 → steps r x ≤ n^39 := by
+ let c := 2000*(r+1)
+ filter_upwards [eventually_stack_clock 10 c (1000*(r+1)), eventually_ge_atTop 4000010] with n clock hn
+ intro d e w x budget hf
+ let N := (n+1)^11
+ have h₁ : 1 ≤ n := by omega
+ have hw := budget.word_le
+ have hd : d ≤ n := by have := budget.phase_le; omega
+ have hH := budget.bucket_le
+ have hnN : n+1 ≤ N := Nat.le_self_pow (by decide : 11 ≠ 0) _
+ have hn₁₀ : n ≤ n^10 := Nat.le_self_pow (by decide) _
+ have hn₁₁ : n^11 ≤ N := Nat.pow_le_pow_left (Nat.le_succ _) _
+ have hnom : choiceBound e w x.fuel ≤ 8*N := calc
+ 2*(2^e)*(x.fuel+w) ≤ (4*n)*(2*n^10) :=
+ Nat.mul_le_mul (by omega) (by omega)
+ _ = 8*n^11 := by rw [pow_succ n 10]; ring
+ _ ≤ _ := Nat.mul_le_mul_left _ hn₁₁
+ have guard := Successors.steps_le d w (decide (0 < x.v.val))
+ have hr : r*(8*w+3) ≤ 11*r*N := by
+ rw [show 11*r*N = r*(11*N) by ring]
+ exact Nat.mul_le_mul_left _ (by omega)
+ have post := SitePost.budget_le (d := d) (e := e) hn hH (by have := budget.phase_le; omega) hw
+ apply clock w (2^e) x.fuel (c*N) (SitePost.budget d e w 0)
+ (perCallEstimate r w (2^e) x.fuel) (steps r x) hw hH hf le_rfl post (perCallEstimate_le ..)
+ simp only [steps, perChoiceBudget, SiteCutBank.graphBudget]
+ dsimp only [c]
+ rw [show 2000*(r+1)*N = 2000*(r*N) + 2000*N by ring]
+ rw [show 11*r*N = 11*(r*N) by ring] at hr
+ omega
+
+/-- Initial stack lengths, including the routing fields and all public
+operands, fit a single polynomial bound before the first stack instruction. -/
+theorem bank_length_le (hn : 128 ≤ n) (budget : ProcessorBudget n d e w)
+ (hf : x.fuel ≤ n^10) (pub : Fin k → Word w) (a : Port r k) :
+ (bank r x pub a).length ≤ n^12 := by
+ have h₁ : 1 ≤ n := by omega
+ have hw := budget.word_le
+ have hd : d+1 ≤ n := by have := budget.phase_le; omega
+ have hH := budget.bucket_le
+ have h₁₀ : n ≤ n^10 := Nat.le_self_pow (by decide) _
+ have h₁₂ := Nat.pow_le_pow_right h₁ (by decide : 10 ≤ 12)
+ have hnom : choiceBound e w x.fuel ≤ n^12 := calc
+ 2*(2^e)*(x.fuel+w) ≤ (4*n)*(2*n^10) := Nat.mul_le_mul (by omega) (by omega)
+ _ = 8*n^11 := by rw [pow_succ n 10]; ring
+ _ ≤ n^12 := by rw [pow_succ' n 11]; exact Nat.mul_le_mul_right _ (by omega)
+ have hslots : 8*n ≤ n^12 := calc
+ _ ≤ n*n := Nat.mul_le_mul_right _ (by omega)
+ _ = n^2 := (pow_two _).symm
+ _ ≤ n^12 := Nat.pow_le_pow_right h₁ (by decide)
+ have hc : (d+1).choose 2 ≤ n^2 := by
+ rw [Nat.choose_two_right]
+ exact (Nat.div_le_self _ _).trans (by rw [pow_two]; gcongr; omega)
+ have hi : width d (2^e) w ≤ n^12 := calc
+ _ ≤ 16*n + 40*(2*n)*n*(n^2) := by rw [width_eq]; gcongr
+ _ ≤ 96*n^4 := by
+ have h := Nat.le_self_pow (by decide : 4 ≠ 0) n
+ rw [show 40*(2*n)*n*(n^2) = 80*n^4 by ring]; omega
+ _ ≤ n^5 := by rw [pow_succ' n 4]; exact Nat.mul_le_mul_right _ (by omega)
+ _ ≤ n^12 := Nat.pow_le_pow_right h₁ (by decide)
+ change (fieldBits x pub (field a)).length ≤ _
+ cases field a <;> simp [fieldBits] <;> omega
+
+/-- One interval per stack suffices on every path of the actual processor,
+including the closing halt and a full initial incident bank. -/
+theorem eventually_bank_and_clock (r : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ d e w (x : VirtualSite.Input d e w),
+ ProcessorBudget n d e w → x.fuel ≤ n^10 → ∀ (pub : Fin k → Word w) a,
+ (bank r x pub a).length + steps r x ≤ n^40 ∧ 4*steps r x + 47 ≤ n^40 := by
+ filter_upwards [eventually_steps r, eventually_ge_atTop 128] with n clock hn
+ intro d e w x budget hf pub a
+ have ht := clock d e w x budget hf
+ have hb := bank_length_le x r hn budget hf pub a
+ have h₁ : 1 ≤ n := by omega
+ have hp := Nat.pow_le_pow_right h₁ (by decide : 12 ≤ 39)
+ have hh := Nat.one_le_pow 39 n h₁
+ have hh' : 51*n^39 ≤ n^40 := by rw [pow_succ' n 39]; exact Nat.mul_le_mul_right _ (by omega)
+ omega
+
+end PairSimulation.LeafStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationStackSteps.lean b/lean/OAI/Computability/VPVNP/PairSimulationStackSteps.lean
new file mode 100644
index 0000000000..4a95746c19
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationStackSteps.lean
@@ -0,0 +1,251 @@
+import OAI.Computability.VPVNP.PairSimulationStackMemory
+
+/-! # Native realization of each elementary bit-stack instruction -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open RAMTape BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {K Q : Type} {w p r k : ℕ}
+ {M : Machine w p r k} {code : StackCode K Q} {pc : Q → Fin 7 → Fin p}
+ {reg : Register K ↪ Fin r} {done : Fin p} (linked : Linked M code pc reg done)
+
+/-- Frame condition across a native stack step, preserving the persistent state, registers
+outside the stack bank, and private cells outside all stack intervals. -/
+structure Frame (L : Layout K w) (reg : Register K ↪ Fin r) (c d : Config w p r) : Prop where
+ persistent : d.persistent = c.persistent
+ regs : ∀ i, i ∉ Set.range reg → d.reg i = c.reg i
+ memory : ∀ a, (∀ j, a.val < L.base j ∨ L.base j+L.capacity ≤ a.val) → d.privateMem a = c.privateMem a
+
+theorem Frame.trans {L : Layout K w} {c d e : Config w p r} (h : Frame L reg c d) (g : Frame L reg d e) :
+ Frame L reg c e :=
+ ⟨g.persistent.trans h.persistent,fun i hi => (g.regs i hi).trans (h.regs i hi),
+ fun a ha => (g.memory a ha).trans (h.memory a ha)⟩
+
+theorem Frame.refl (L : Layout K w) (c : Config w p r) : Frame L reg c c :=
+ ⟨rfl,fun _ _ => rfl,fun _ _ => rfl⟩
+
+private theorem pass_step {c : Config w p r} {next : Fin p}
+ (hs : M.code c.pc = .copy (reg .tmp) (reg .tmp) next) :
+ M.program.step c = .localStep {c with pc := next} := by
+ simp [Machine.program,hs,Instr.run,Config.put,Function.update_eq_self]
+
+variable [DecidableEq K] {L : Layout K w} {q : Q} {c : Config w p r} {s : Stacks K}
+
+include linked
+
+theorem push_prefix_memory {a : K} {bit : Bool} {next : Q} (hop : code q = .push a bit next)
+ (atPC : c.pc = pc q 0) (rep : Represents L reg c s) (fit : ∀ j, (s j).length ≤ L.capacity)
+ (space : (s a).length < L.capacity) :
+ ∃ d, Prefix M c (List.replicate 4 .tick) d ∧ d.pc = pc next 0 ∧
+ Represents L reg d (Function.update s a (bit :: s a)) ∧ d.privateMem = Function.update c.privateMem (L.address a (s a).length) (encodeBit w bit) ∧ Frame L reg c d := by
+ let b := encodeBit w bit
+ let ptr := L.address a (s a).length
+ let c₁ := c.put (pc q 1) (reg .tmp) b
+ let c₂ := c₁.store (pc q 2) ptr b
+ let c₃ := c₂.put (pc q 3) (reg (.top a)) (ptr+1)
+ let d := {c₃ with pc := pc next 0}
+ have st₀ : M.program.step c = .localStep c₁ := by rw [linked.step c q 0 atPC]; simp [instruction,hop,Instr.run,c₁,b,encodeBit]
+ have st₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [linked.step c₁ q 1 rfl]
+ simp [instruction,hop,Instr.run,c₂,c₁,ptr,Config.put,rep.tops]
+ have st₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [linked.step c₂ q 2 rfl]
+ simp [instruction,hop,Instr.run,c₃,c₂,c₁,ptr,Config.put,Config.store,rep.unit,rep.tops,BinaryOp.eval]
+ have st₃ : M.program.step c₃ = .localStep d := by
+ apply pass_step (reg := reg)
+ change M.code (pc q 3) = _
+ rw [linked q 3]; simp [instruction,hop]
+ refine ⟨d,.tick st₀ (.tick st₁ (.tick st₂ (.tick st₃ (.nil _)))),rfl,?_,rfl,?_⟩
+ · refine ⟨?_,?_,?_,?_,L.contents_push c.privateMem s a bit rep.cells fit space⟩
+ · simp [d,c₃,c₂,c₁,Config.put,Config.store,rep.unit]
+ · simp [d,c₃,c₂,c₁,Config.put,Config.store,rep.zero]
+ · intro j; simp [d,c₃,c₂,c₁,Config.put,Config.store,rep.bases]
+ · intro j
+ by_cases h : j = a
+ · subst j; simp [d,c₃,c₂,c₁,ptr,Config.put,Config.store,Layout.address,add_assoc]
+ · simp [d,c₃,c₂,c₁,Config.put,Config.store,h,rep.tops]
+ · refine ⟨rfl,?_,?_⟩
+ · intro i hi
+ have ne (j : Register K) : i ≠ reg j := fun e => hi ⟨j,e.symm⟩
+ simp [d,c₃,c₂,c₁,Config.put,Config.store,Function.update_of_ne (ne _)]
+ · intro i hi
+ have ne : i ≠ ptr := by
+ intro e
+ have hev := congrArg Fin.val e
+ rw [show ptr = L.address a (s a).length from rfl,L.address_val a space.le] at hev
+ rcases hi a with hlo | hhi <;> omega
+ simp [d,c₃,c₂,c₁,Config.put,Config.store,Function.update_of_ne ne]
+
+theorem push_prefix {a : K} {bit : Bool} {next : Q} (hop : code q = .push a bit next)
+ (atPC : c.pc = pc q 0) (rep : Represents L reg c s) (fit : ∀ j, (s j).length ≤ L.capacity)
+ (space : (s a).length < L.capacity) :
+ ∃ d, Prefix M c (List.replicate 4 .tick) d ∧ d.pc = pc next 0 ∧
+ Represents L reg d (Function.update s a (bit :: s a)) ∧ Frame L reg c d := by
+ obtain ⟨d,run,dst,repr,_,frame⟩ := push_prefix_memory linked hop atPC rep fit space
+ exact ⟨d,run,dst,repr,frame⟩
+
+theorem pop_prefix_memory {a : K} {next : Option Bool → Q} (hop : code q = .pop a next)
+ (atPC : c.pc = pc q 0) (rep : Represents L reg c s) (hw : 0 < w) (fit : (s a).length ≤ L.capacity) :
+ ∃ d, Prefix M c (List.replicate 4 .tick) d ∧ d.pc = pc (next (s a).head?) 0 ∧
+ Represents L reg d (Function.update s a (s a).tail) ∧ d.privateMem = c.privateMem ∧ Frame L reg c d := by
+ cases eq : s a with
+ | nil =>
+ let pos (i : Fin 7) := {c with pc := pc q i}
+ let d := {c with pc := pc (next none) 0}
+ have st₀ : M.program.step c = .localStep (pos 4) := by
+ rw [linked.step c q 0 atPC]
+ simp [instruction,hop,Instr.run,rep.tops,rep.bases,eq,pos]
+ have st₄ : M.program.step (pos 4) = .localStep (pos 5) := by
+ apply pass_step (reg := reg); change M.code (pc q 4) = _; rw [linked q 4]; simp [instruction,hop]
+ have st₅ : M.program.step (pos 5) = .localStep (pos 6) := by
+ apply pass_step (reg := reg); change M.code (pc q 5) = _; rw [linked q 5]; simp [instruction,hop]
+ have st₆ : M.program.step (pos 6) = .localStep d := by
+ apply pass_step (reg := reg); change M.code (pc q 6) = _; rw [linked q 6]; simp [instruction,hop]
+ have same : Function.update s a (s a).tail = s := by rw [eq]; change Function.update s a [] = s; rw [← eq,Function.update_eq_self]
+ refine ⟨d,.tick st₀ (.tick st₄ (.tick st₅ (.tick st₆ (.nil _)))),by simp [d],?_,rfl,⟨rfl,fun _ _ => rfl,fun _ _ => rfl⟩⟩
+ rw [← eq,same]
+ exact ⟨rep.unit,rep.zero,rep.bases,rep.tops,rep.cells⟩
+ | cons b tail =>
+ let c₁ := {c with pc := pc q 1}
+ let ptr := L.address a tail.length
+ let c₂ := c₁.put (pc q 2) (reg (.top a)) ptr
+ let c₃ := c₂.put (pc q 3) (reg .tmp) (encodeBit w b)
+ let d := {c₃ with pc := pc (next (some b)) 0}
+ have hn : c.reg (reg (.top a)) ≠ c.reg (reg (.base a)) := by
+ rw [rep.tops,rep.bases]
+ intro h
+ have he := congrArg Fin.val h
+ rw [L.address_val a fit,L.address_val a (Nat.zero_le _),eq] at he
+ simp at he
+ have st₀ : M.program.step c = .localStep c₁ := by
+ rw [linked.step c q 0 atPC]; simp [instruction,hop,Instr.run,hn,c₁]
+ have st₁ : M.program.step c₁ = .localStep c₂ := by
+ rw [linked.step c₁ q 1 rfl]
+ simp [instruction,hop,Instr.run,c₂,c₁,ptr,rep.tops,rep.unit,eq,Layout.address,← add_assoc,BinaryOp.eval]
+ have st₂ : M.program.step c₂ = .localStep c₃ := by
+ rw [linked.step c₂ q 2 rfl]
+ have cell := rep.cells a [] b tail eq
+ simp [instruction,hop,Instr.run,c₃,c₂,c₁,ptr,Config.put,cell]
+ have st₃ : M.program.step c₃ = .localStep d := by
+ rw [linked.step c₃ q 3 rfl]
+ have hone : (1 : Word w) ≠ 0 := by
+ intro h
+ have hv := congrArg Fin.val h
+ simp [Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')] at hv
+ cases b <;> simp [instruction,hop,Instr.run,d,c₃,c₂,c₁,Config.put,encodeBit,rep.zero,hone]
+ refine ⟨d,.tick st₀ (.tick st₁ (.tick st₂ (.tick st₃ (.nil _)))),rfl,?_,rfl,?_⟩
+ · refine ⟨?_,?_,?_,?_,?_⟩
+ · simp [d,c₃,c₂,c₁,Config.put,rep.unit]
+ · simp [d,c₃,c₂,c₁,Config.put,rep.zero]
+ · intro j; simp [d,c₃,c₂,c₁,Config.put,rep.bases]
+ · intro j
+ by_cases h : j = a
+ · subst j; simp [d,c₃,c₂,c₁,ptr,Config.put]
+ · simp [d,c₃,c₂,c₁,Config.put,h,rep.tops]
+ · change L.Contents c.privateMem (Function.update s a (b::tail).tail)
+ simpa only [eq] using L.contents_pop c.privateMem s a rep.cells
+ · refine ⟨rfl,?_,fun _ _ => rfl⟩
+ intro i hi
+ have ne (j : Register K) : i ≠ reg j := fun e => hi ⟨j,e.symm⟩
+ simp [d,c₃,c₂,c₁,Config.put,Function.update_of_ne (ne _)]
+
+
+theorem pop_prefix {a : K} {next : Option Bool → Q} (hop : code q = .pop a next)
+ (atPC : c.pc = pc q 0) (rep : Represents L reg c s) (hw : 0 < w) (fit : (s a).length ≤ L.capacity) :
+ ∃ d, Prefix M c (List.replicate 4 .tick) d ∧ d.pc = pc (next (s a).head?) 0 ∧
+ Represents L reg d (Function.update s a (s a).tail) ∧ Frame L reg c d := by
+ obtain ⟨d,run,dst,repr,_,frame⟩ := pop_prefix_memory linked hop atPC rep hw fit
+ exact ⟨d,run,dst,repr,frame⟩
+
+omit [DecidableEq K] linked in
+private theorem three_passes (atPC : c.pc = pc q 0)
+ (op₀ : M.code (pc q 0) = .copy (reg .tmp) (reg .tmp) (pc q 1))
+ (op₁ : M.code (pc q 1) = .copy (reg .tmp) (reg .tmp) (pc q 2))
+ (op₂ : M.code (pc q 2) = .copy (reg .tmp) (reg .tmp) (pc q 3)) :
+ Prefix M c [.tick,.tick,.tick] {c with pc := pc q 3} := by
+ refine .tick (pass_step (reg := reg) (atPC ▸ op₀)) ?_
+ refine .tick (pass_step (reg := reg) op₁) ?_
+ exact .tick (pass_step (reg := reg) op₂) (.nil _)
+
+omit [DecidableEq K] in
+theorem goto_prefix_memory {next : Q} (hop : code q = .goto next) (atPC : c.pc = pc q 0)
+ (rep : Represents L reg c s) :
+ ∃ d, Prefix M c (List.replicate 4 .tick) d ∧ d.pc = pc next 0 ∧
+ Represents L reg d s ∧ d.privateMem = c.privateMem ∧ Frame L reg c d := by
+ have pad := three_passes (reg := reg) (M := M) atPC
+ (by rw [linked q 0]; simp [instruction,hop])
+ (by rw [linked q 1]; simp [instruction,hop])
+ (by rw [linked q 2]; simp [instruction,hop])
+ let d := {c with pc := pc next 0}
+ have last : M.program.step {c with pc := pc q 3} = .localStep d := by
+ apply pass_step (reg := reg)
+ change M.code (pc q 3) = _
+ rw [linked q 3]; simp [instruction,hop]
+ exact ⟨d,pad.append (.tick last (.nil _)),rfl,⟨rep.unit,rep.zero,rep.bases,rep.tops,rep.cells⟩,rfl,
+ ⟨rfl,fun _ _ => rfl,fun _ _ => rfl⟩⟩
+
+omit [DecidableEq K] in
+theorem goto_prefix {next : Q} (hop : code q = .goto next) (atPC : c.pc = pc q 0)
+ (rep : Represents L reg c s) :
+ ∃ d, Prefix M c (List.replicate 4 .tick) d ∧ d.pc = pc next 0 ∧
+ Represents L reg d s ∧ Frame L reg c d := by
+ obtain ⟨d,run,dst,repr,_,frame⟩ := goto_prefix_memory linked hop atPC rep
+ exact ⟨d,run,dst,repr,frame⟩
+
+omit [DecidableEq K] in
+theorem choose_prefix_memory {lo hi : Q} (hop : code q = .choose lo hi) (atPC : c.pc = pc q 0)
+ (rep : Represents L reg c s) (b : Bool) :
+ ∃ d, Prefix M c [.tick,.tick,.tick,.choice b] d ∧ d.pc = pc (if b then hi else lo) 0 ∧
+ Represents L reg d s ∧ d.privateMem = c.privateMem ∧ Frame L reg c d := by
+ have pad := three_passes (reg := reg) (M := M) atPC
+ (by rw [linked q 0]; simp [instruction,hop])
+ (by rw [linked q 1]; simp [instruction,hop])
+ (by rw [linked q 2]; simp [instruction,hop])
+ let d (t : Bool) := {c with pc := pc (if t then hi else lo) 0}
+ have last : M.program.step {c with pc := pc q 3} = .branch d := by
+ rw [linked.step _ q 3 rfl]; simp [instruction,hop,Instr.run,d]
+ funext t; cases t <;> rfl
+ exact ⟨d b,pad.append (.choice last (.nil _)),rfl,⟨rep.unit,rep.zero,rep.bases,rep.tops,rep.cells⟩,rfl,
+ ⟨rfl,fun _ _ => rfl,fun _ _ => rfl⟩⟩
+
+omit [DecidableEq K] in
+theorem choose_prefix {lo hi : Q} (hop : code q = .choose lo hi) (atPC : c.pc = pc q 0)
+ (rep : Represents L reg c s) (b : Bool) :
+ ∃ d, Prefix M c [.tick,.tick,.tick,.choice b] d ∧ d.pc = pc (if b then hi else lo) 0 ∧
+ Represents L reg d s ∧ Frame L reg c d := by
+ obtain ⟨d,run,dst,repr,_,frame⟩ := choose_prefix_memory linked hop atPC rep b
+ exact ⟨d,run,dst,repr,frame⟩
+
+omit [DecidableEq K] in
+theorem halt_prefix_memory (hop : code q = .halt true) (atPC : c.pc = pc q 0)
+ (rep : Represents L reg c s) :
+ ∃ d, Prefix M c [.tick] d ∧ d.pc = done ∧ Represents L reg d s ∧ d.privateMem = c.privateMem ∧ Frame L reg c d := by
+ let d := {c with pc := done}
+ have st : M.program.step c = .localStep d := by
+ apply pass_step (reg := reg); rw [atPC,linked q 0]; simp [instruction,hop]
+ exact ⟨d,.tick st (.nil _),rfl,⟨rep.unit,rep.zero,rep.bases,rep.tops,rep.cells⟩,rfl,
+ ⟨rfl,fun _ _ => rfl,fun _ _ => rfl⟩⟩
+
+omit [DecidableEq K] in
+theorem halt_prefix (hop : code q = .halt true) (atPC : c.pc = pc q 0)
+ (rep : Represents L reg c s) :
+ ∃ d, Prefix M c [.tick] d ∧ d.pc = done ∧ Represents L reg d s ∧ Frame L reg c d := by
+ obtain ⟨d,run,dst,repr,_,frame⟩ := halt_prefix_memory linked hop atPC rep
+ exact ⟨d,run,dst,repr,frame⟩
+
+omit [DecidableEq K] in
+theorem halt_reject (hop : code q = .halt false) (atPC : c.pc = pc q 0) :
+ M.program.step c = .reject := by
+ rw [linked.step c q 0 atPC]; simp [instruction,hop,Instr.run]
+
+end PairSimulation.StackMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationStackTable.lean b/lean/OAI/Computability/VPVNP/PairSimulationStackTable.lean
new file mode 100644
index 0000000000..40ee09f939
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationStackTable.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.RAMTapeStacks
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Finite private RAM table for a named bit-stack program
+
+Each continuing stack instruction uses exactly four native transitions.
+Stack top and base pointers are retained in separate registers. No opcode
+accesses external memory. The true halt jumps to the caller's continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.StackMachine
+
+open RAMTape BurstRAM BurstRAM.PrivateRAM
+
+/-- Logical registers of the bit-stack machine, with a base and exclusive top pointer per stack
+and shared zero, one, and temporary registers. -/
+inductive Register (K : Type) where
+ | top (k : K)
+ | base (k : K)
+ | zero
+ | one
+ | tmp
+ deriving DecidableEq, Fintype
+
+variable {K Q : Type} {w p r k : ℕ}
+
+/-- Unused instruction slots reject. Empty and nonempty pops have separate
+three-transition continuations after the initial pointer comparison. -/
+def instruction (code : StackCode K Q) (pc : Q → Fin 7 → Fin p)
+ (reg : Register K ↪ Fin r) (done : Fin p) (q : Q) (i : Fin 7) : Instr w p r k :=
+ let pass (dst : Fin p) : Instr w p r k := .copy (reg .tmp) (reg .tmp) dst
+ match code q with
+ | .push a b next => ![.constant (reg .tmp) (if b then 1 else 0) (pc q 1),
+ .storePrivate (reg (.top a)) (reg .tmp) (pc q 2),
+ .binary .add (reg (.top a)) (reg (.top a)) (reg .one) (pc q 3),
+ pass (pc next 0), .reject, .reject, .reject] i
+ | .pop a next => ![.jumpEq (reg (.top a)) (reg (.base a)) (pc q 4) (pc q 1),
+ .binary .sub (reg (.top a)) (reg (.top a)) (reg .one) (pc q 2),
+ .loadPrivate (reg .tmp) (reg (.top a)) (pc q 3),
+ .jumpEq (reg .tmp) (reg .zero) (pc (next (some false)) 0) (pc (next (some true)) 0),
+ pass (pc q 5),pass (pc q 6),pass (pc (next none) 0)] i
+ | .goto next => ![pass (pc q 1),pass (pc q 2),pass (pc q 3),pass (pc next 0),.reject,.reject,.reject] i
+ | .choose lo hi => ![pass (pc q 1),pass (pc q 2),pass (pc q 3),.choose (pc hi 0) (pc lo 0),.reject,.reject,.reject] i
+ | .halt b => if b && i == 0 then pass done else .reject
+
+/-- The host instruction table implements all seven slots for every stack-code state with the
+specified register allocation and accepting continuation. -/
+def Linked (M : Machine w p r k) (code : StackCode K Q) (pc : Q → Fin 7 → Fin p)
+ (reg : Register K ↪ Fin r) (done : Fin p) : Prop :=
+ ∀ q i, M.code (pc q i) = instruction code pc reg done q i
+
+theorem resize_instruction (code : StackCode K Q) (pc : Q → Fin 7 → Fin p)
+ (reg : Register K ↪ Fin r) (done : Fin p) (q : Q) (i : Fin 7) :
+ (instruction (w := 1) (k := k) code pc reg done q i).resize w = instruction code pc reg done q i := by
+ cases h : code q with
+ | push a b n =>
+ cases b <;> fin_cases i <;> simp [instruction,h,Instr.resize]
+ rfl
+ | pop | goto | choose => fin_cases i <;> simp [instruction,h,Instr.resize]
+ | halt b => cases b <;> fin_cases i <;> simp [instruction,h,Instr.resize]
+
+theorem Linked.step {M : Machine w p r k} {code : StackCode K Q} {pc : Q → Fin 7 → Fin p}
+ {reg : Register K ↪ Fin r} {done : Fin p} (hl : Linked M code pc reg done)
+ (c : Config w p r) (q : Q) (i : Fin 7) (hc : c.pc = pc q i) :
+ M.program.step c = (instruction code pc reg done q i).run M.publicData c := by
+ simp [Machine.program,hc,hl q i]
+
+section Standalone
+
+variable [Fintype Q] [Fintype K]
+
+/-- Standalone stack program addresses, consisting of seven instruction slots for each control
+state and one accepting exit. -/
+abbrev PC (Q : Type) := (Q × Fin 7) ⊕ Unit
+
+/-- Numbered machine program counter for instruction slot `i` in the compiled row of stack-code
+state `q`. -/
+noncomputable def rowPC (q : Q) (i : Fin 7) : Fin (Fintype.card (PC Q)) :=
+ Fintype.equivFin (PC Q) (.inl (q,i))
+
+/-- Numbered accepting continuation of the standalone stack program. -/
+noncomputable def donePC (Q : Type) [Fintype Q] : Fin (Fintype.card (PC Q)) :=
+ Fintype.equivFin (PC Q) (.inr ())
+
+/-- Embed the named stack registers in the standalone machine's consecutively numbered register
+file. -/
+noncomputable def register (K : Type) [Fintype K] : Register K ↪ Fin (Fintype.card (Register K)) :=
+ (Fintype.equivFin _).toEmbedding
+
+/-- A finite complete table, before instantiating its word width. -/
+noncomputable def table (code : StackCode K Q) (start : Q) :
+ Template (Fintype.card (PC Q)) (Fintype.card (Register K)) 0 where
+ literalWidth := 1
+ entry := rowPC start 0
+ code i := match (Fintype.equivFin (PC Q)).symm i with
+ | .inl (q,j) => instruction code rowPC (register K) (donePC Q) q j
+ | .inr _ => .accept
+
+theorem table_linked (code : StackCode K Q) (start : Q) (pub : Fin 0 → Word w) :
+ Linked ((table code start).instantiate w pub) code rowPC (register K) (donePC Q) := by
+ intro q i
+ simpa [Template.instantiate,table,rowPC] using resize_instruction (w := w) (k := 0)
+ code rowPC (register K) (donePC Q) q i
+
+theorem table_done (code : StackCode K Q) (start : Q) (pub : Fin 0 → Word w) :
+ ((table code start).instantiate w pub).code (donePC Q) = .accept := by
+ simp [Template.instantiate,table,donePC,Instr.resize]
+
+end Standalone
+end PairSimulation.StackMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalBlocks.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalBlocks.lean
new file mode 100644
index 0000000000..4232c1c851
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalBlocks.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalFive
+import OAI.Computability.VPVNP.PairSimulationTerminalPhaseBuild
+
+/-!
+# Native phase blocks at the terminal workspace
+
+Three deterministic phases set up the row and role metadata. The following
+shared-bit phase changes the memory on which the vertex traversal runs.
+The complete block includes the physical reports, supplied choices and
+final memory so all three can be used at the next phase.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+open BurstRAM LiveProgram CompressorRecords
+
+variable {w : ℕ} (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap : ℕ)
+
+/-- All completed native blocks for one selected phase at one physical memory. -/
+abbrev CompletedPhase (e : Entry w) (m : Memory w) :=
+ {x : Block w // Phase workers pub cap e m x.choices x.logs x.memory}
+
+variable {workers pub cap} in
+/-- A proved source execution realizes a concrete completed block in the
+physical memory, including its dispatch and final transfer. -/
+def completedBlock (f : ℕ) (e : Entry w) (src phy : Memory w) (bs : List (List Bool))
+ (raws : List (Report w)) (room : f+30 ≤ cap)
+ (agree : SourceTransport.Agree (workerCell (header pub)) src phy)
+ (reads : SourceTransport.Reads (workerCell (header pub)) (eventLog raws))
+ (run : runSegment (source workers e.stage pub) f (some e.state) src bs = some raws)
+ (halt : endState (some e.state) raws = none) : CompletedPhase workers pub cap e phy :=
+ ⟨⟨bs,stageLogs e raws,after phy (eventLog (stageReports (header pub) e raws))⟩,
+ closed_phase workers pub f cap e src phy bs raws room agree reads run halt⟩
+
+/-- The first three completed terminal phases in sequence, with each call taking an empty
+choice tape and each phase starting in the preceding phase's output memory. -/
+structure QuietPrefix (m : Memory w) where
+ /-- Completed bootstrap phase starting at the terminal controller's initial entry and
+ supplied memory. -/
+ boot : CompletedPhase workers pub cap .initial m
+ /-- Completed prefix-row phase resumed at state zero in the memory left by bootstrap. -/
+ prefixRows : CompletedPhase workers pub cap (.resume Stage.prefixRows 0) boot.val.memory
+ /-- Completed traversal-row phase resumed at state zero in the memory left by the prefix-row
+ phase. -/
+ traversalRows : CompletedPhase workers pub cap (.resume Stage.traversalRows 0) prefixRows.val.memory
+ bootQuiet : ∀ b ∈ boot.val.choices, b = []
+ prefixQuiet : ∀ b ∈ prefixRows.val.choices, b = []
+ traversalQuiet : ∀ b ∈ traversalRows.val.choices, b = []
+
+variable {workers pub cap} {m : Memory w}
+
+/-- Completed shared-bit phase beginning at state zero after the three deterministic terminal
+phases. -/
+abbrev QuietPrefix.BitPaths (p : QuietPrefix workers pub cap m) :=
+ CompletedPhase workers pub cap (.resume Stage.sharedBits 0) p.traversalRows.val.memory
+
+/-- Completed vertex phase beginning at state zero in the memory produced by the given
+shared-bit phase. -/
+abbrev QuietPrefix.VertexPaths (p : QuietPrefix workers pub cap m) (bits : p.BitPaths) :=
+ CompletedPhase workers pub cap (.resume Stage.vertices 0) bits.val.memory
+
+/-- Assemble the bootstrap, prefix-row, traversal-row, shared-bit, and vertex completions into
+one certified five-phase execution trace. -/
+def QuietPrefix.trace (p : QuietPrefix workers pub cap m) (bits : p.BitPaths) (vertices : p.VertexPaths bits) :
+ FiveTrace workers pub cap m :=
+ ⟨p.boot.val,p.prefixRows.val,p.traversalRows.val,bits.val,vertices.val,
+ p.boot.prop,p.prefixRows.prop,p.traversalRows.prop,bits.prop,vertices.prop⟩
+
+theorem QuietPrefix.trace_choices (p : QuietPrefix workers pub cap m) (bits : p.BitPaths) (vertices : p.VertexPaths bits) :
+ (p.trace bits vertices).choices = p.boot.val.choices ++ (p.prefixRows.val.choices ++
+ (p.traversalRows.val.choices ++ (bits.val.choices ++ vertices.val.choices))) := rfl
+
+theorem QuietPrefix.trace_logs (p : QuietPrefix workers pub cap m) (bits : p.BitPaths) (vertices : p.VertexPaths bits) :
+ (p.trace bits vertices).logs = p.boot.val.logs ++ (p.prefixRows.val.logs ++
+ (p.traversalRows.val.logs ++ (bits.val.logs ++ vertices.val.logs))) := rfl
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalBody.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalBody.lean
new file mode 100644
index 0000000000..ccaf9271b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalBody.lean
@@ -0,0 +1,151 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalLink
+
+/-!
+# Exact finite-fuel semantics inside a terminal worker
+
+The protected registers hold the restored worker state, its two header
+addresses and the marker one. Ordinary instructions simulate one source
+instruction each. On a continuing exit the controller records the next
+worker and its entire word. Every insufficient fuel or unused choice
+stream is accounted for by the same interpreter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+variable {r w : ℕ} {pcs : Stage → ℕ}
+
+/-- The worker and persistent word selected by a successful exit. -/
+def target (s : Stage) : Option (Word w) → Option (Stage × Word w)
+ | some v => some (s,v)
+ | none => (next s).map (fun t => (t,0))
+
+/-- Instructions that publish the next stage and its persistent word. -/
+def exitEvents (addr : Word w) (s : Stage) (v : Word w) : List (Event w) :=
+ [.tick,.tick,.write addr (tagWord w s),.write (addr+31) v]
+
+/-- Extend the worker's report by the control writes at a continuing exit. -/
+def exitReport (addr : Word w) (s : Stage) (rep : Report w) : Report w :=
+ match target s rep.result with
+ | none => rep
+ | some (t,v) => ⟨rep.events++exitEvents addr t v, some 1⟩
+
+/-- Check that the worker and its control writes fit in the remaining fuel. -/
+def boundedExit (addr : Word w) (s : Stage) (f : ℕ) (rep : Report w) : Option (Report w) :=
+ let out := exitReport addr s rep
+ if out.events.length < f then some out else none
+
+theorem exitReport_prepend (addr : Word w) (s : Stage) (rep : Report w) (e : Event w) :
+ exitReport addr s (rep.prepend e) = (exitReport addr s rep).prepend e := by
+ unfold exitReport Report.prepend
+ cases h : target s rep.result <;> rfl
+
+private theorem bind_prepend (addr : Word w) (s : Stage) (f : ℕ) (ev : Event w) (rep : Option (Report w)) :
+ (rep.bind (boundedExit addr s f)).map (Report.prepend ev) =
+ (rep.map (Report.prepend ev)).bind (boundedExit addr s (f+1)) := by
+ cases rep with
+ | none => rfl
+ | some x =>
+ simp only [Option.bind_some,Option.map_some,boundedExit]
+ rw [exitReport_prepend]
+ simp only [Report.prepend,List.length_cons,Nat.add_lt_add_iff_right]
+ split <;> rfl
+
+private theorem update_ordinary (small : Fin r → Word w) (tail : Fin 6 → Word w) (j : Fin r) (v : Word w) :
+ Function.update (Fin.append small tail) (ordinary j) v = Fin.append (Function.update small j v) tail := by
+ funext i
+ cases i using Fin.addCases with
+ | left i => by_cases h : i = j <;> simp [ordinary,Function.update,h]
+ | right i =>
+ have ne : i.natAdd r ≠ j.castAdd 6 := by intro e; have := congrArg Fin.val e; simp at this; omega
+ simp [ordinary,Function.update,ne]
+
+private def mapAction {A B : Type} (g : A → B) : CallAction w A → CallAction w B
+ | .localStep c => .localStep (g c)
+ | .branch f => .branch (g ∘ f)
+ | .read a f => .read a (g ∘ f)
+ | .write a v c => .write a v (g c)
+ | .reject => .reject
+ | .finish x => .finish x
+
+private def terminal {p : ℕ} : Instr w p r 11 → Bool
+ | .returnState _ | .accept => true
+ | _ => false
+
+variable (T : (s : Stage) → Template (pcs s) r 11) (pub : Fin 11 → Word w)
+
+private theorem body_step (s : Stage) (host addr tag tmp : Word w) (c : Config w (pcs s) r)
+ (h : terminal (((T s).instantiate w pub).code c.pc) = false) :
+ (machine T pub).program.step (bodyConfig s host addr tag tmp c) =
+ mapAction (bodyConfig s host addr tag tmp) (((T s).instantiate w pub).program.step c) := by
+ change ((machine T pub).code (bodyPC pcs s c.pc)).run pub _ = _
+ rw [code_body]
+ change (bodyInstr s _).run pub _ = mapAction _ ((((T s).instantiate w pub).code c.pc).run pub c)
+ generalize he : ((T s).instantiate w pub).code c.pc = op at h ⊢
+ cases op <;> simp only [terminal, Bool.true_eq_false,bodyInstr,mapAction,Instr.run,bodyConfig,
+ Config.put,Config.store,Function.comp_def,Fin.append_left,Fin.append_right,update_ordinary] at *
+ all_goals first | contradiction | rfl | (split <;> rfl) | (congr 1; funext b; cases b <;> rfl)
+
+private theorem body_return (s : Stage) (host addr tag tmp : Word w) (c : Config w (pcs s) r)
+ (a : Fin r) (h : ((T s).instantiate w pub).code c.pc = .returnState a) (fuel : ℕ)
+ (m : Memory w) (bits : List Bool) :
+ execute (machine T pub).program fuel (bodyConfig s host addr tag tmp c) m bits =
+ (execute ((T s).instantiate w pub).program fuel c m bits).bind (boundedExit addr s fuel) := by
+ rcases fuel with _|_|_|_|_|f <;> cases bits <;>
+ simp [execute,Machine.program,code_body,h,bodyInstr,Instr.run,bodyConfig,Config.put,
+ ordinary,extras,phaseAddress,savedAddress,stateValue,phaseValue,unitReg,extra,saveInstr,
+ boundedExit,exitReport,target,exitEvents,Report.prepend]
+
+private theorem body_accept (s : Stage) (host addr tag tmp : Word w) (c : Config w (pcs s) r)
+ (h : ((T s).instantiate w pub).code c.pc = .accept) (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute (machine T pub).program fuel (bodyConfig s host addr tag tmp c) m bits =
+ (execute ((T s).instantiate w pub).program fuel c m bits).bind (boundedExit addr s fuel) := by
+ cases n : next s with
+ | none =>
+ cases fuel <;> cases bits <;> simp [execute,Machine.program,code_body,h,bodyInstr,n,Instr.run,
+ bodyConfig,boundedExit,exitReport,target]
+ | some dst =>
+ rcases fuel with _|_|_|_|_|f <;> cases bits <;>
+ simp [execute,Machine.program,code_body,h,bodyInstr,n,Instr.run,bodyConfig,Config.put,
+ extras,phaseAddress,savedAddress,stateValue,phaseValue,unitReg,extra,saveInstr,
+ boundedExit,exitReport,target,exitEvents,Report.prepend]
+
+/-- Exact success and failure of a worker with the real exit protocol.
+This equality is valid for all fuel, registers, private memory, external
+memory and binary streams. -/
+theorem execute_body (s : Stage) (host addr tag tmp : Word w) (fuel : ℕ) (c : Config w (pcs s) r)
+ (m : Memory w) (bits : List Bool) :
+ execute (machine T pub).program fuel (bodyConfig s host addr tag tmp c) m bits =
+ (execute ((T s).instantiate w pub).program fuel c m bits).bind (boundedExit addr s fuel) := by
+ induction fuel generalizing c m bits with
+ | zero => rfl
+ | succ fuel ih =>
+ by_cases last : terminal (((T s).instantiate w pub).code c.pc) = true
+ · cases he : ((T s).instantiate w pub).code c.pc with
+ | accept => exact body_accept T pub s host addr tag tmp c he _ m bits
+ | returnState a => exact body_return T pub s host addr tag tmp c a he _ m bits
+ | _ => simp [he,terminal] at last
+ · rw [execute,body_step T pub s host addr tag tmp c (Bool.eq_false_iff.mpr last),execute]
+ cases hs : ((T s).instantiate w pub).program.step c with
+ | localStep x => simp only [mapAction,ih]; exact bind_prepend ..
+ | branch f =>
+ cases bits <;> simp only [mapAction,Function.comp_apply,ih,Option.bind_none]
+ exact bind_prepend ..
+ | read a f => simp only [mapAction,Function.comp_apply,ih]; exact bind_prepend ..
+ | write a v x => simp only [mapAction,ih]; exact bind_prepend ..
+ | reject => rfl
+ | finish z =>
+ change ((((T s).instantiate w pub).code c.pc).run pub c) = _ at hs
+ cases he : ((T s).instantiate w pub).code c.pc <;> simp_all [terminal,Instr.run]
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalCall.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalCall.lean
new file mode 100644
index 0000000000..3e1f977877
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalCall.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalReports
+
+/-!
+# Projecting a native terminal call onto its original worker
+
+The linked table spends the entry trace before the worker and, when needed,
+writes the two header cells after the worker. A successful call determines
+the worker's native report at the remaining cap, including the same choice
+stream. Conversely a worker run with room for the controller yields exactly
+the linked report.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM LiveProgram
+
+variable {w : ℕ}
+variable (workers : Stage → PairTable) (pub : Fin 11 → Word w)
+
+/-- Execute one original worker with the common eleven public operands. -/
+abbrev source (workers : Stage → PairTable) (s : Stage) (pub : Fin 11 → Word w) :=
+ ((workers s).table.instantiate w pub).program
+
+/-- The full linked RAM program instantiated with the same public operands. -/
+abbrev program := ((table workers).table.instantiate w pub).program
+
+/-- Projected execution at the cap left by the entry prefix. Its exit fits
+exactly when the worker's report and the optional header writes fit. -/
+def localCall (cap : ℕ) (e : Entry w) (m : Memory w) (bs : List Bool) : Option (Report w) :=
+ let addr := header pub
+ let fuel := cap - (e.prefixEvents addr).length
+ let S := source workers e.stage pub
+ ((execute S fuel (S.start e.state) m bs).bind (boundedExit addr e.stage fuel)).map
+ (LiveStageLink.prependLog (e.prefixEvents addr))
+
+private theorem execute_original (s : Stage) (f : ℕ) (state : Word w) (m : Memory w) (bs : List Bool) :
+ let L := ((component workers s).instantiate w pub).program
+ let S := source workers s pub
+ execute L f (L.start state) m bs = execute S f (S.start state) m bs :=
+ LiveStageLink.execute_widen_start (workers s).table (embedding workers s) id pub f state m bs
+
+private theorem execute_prefix (e : Entry w) (f : ℕ) (m : Memory w) (bs : List Bool)
+ (hfit : 5 ≤ 2^w) (valid : e.Valid (header pub) m) :
+ let L := program workers pub
+ let S := source workers e.stage pub
+ let es := e.prefixEvents (header pub)
+ execute L (f+es.length) (L.start e.marker) m bs =
+ ((execute S f (S.start e.state) m bs).bind (boundedExit (header pub) e.stage f)).map
+ (LiveStageLink.prependLog es) := by
+ change execute (machine (component workers) pub).program (f+(e.prefixEvents (header pub)).length)
+ ((machine (component workers) pub).program.start e.marker) m bs = _
+ cases e with
+ | initial =>
+ simp only [Entry.prefixEvents,Entry.marker,Entry.stage,Entry.state]
+ rw [enter_initial (component workers) pub,execute_body,execute_original]
+ | resume s x =>
+ simp only [Entry.prefixEvents,Entry.marker,Entry.stage,Entry.state]
+ rw [enter_resume (component workers) pub s hfit x f m valid.1 valid.2 bs,execute_body,execute_original]
+
+/-- Every choice stream has the same outcome as the original worker followed
+by the bounded exit, with the entry events prepended. -/
+theorem execute_entry (cap : ℕ) (e : Entry w) (m : Memory w) (bs : List Bool)
+ (hfit : 5 ≤ 2^w) (hcap : 26 ≤ cap) (valid : e.Valid (header pub) m) :
+ let L := program workers pub
+ execute L cap (L.start e.marker) m bs = localCall workers pub cap e m bs := by
+ have hp := (prefix_length_le (header pub) e).trans hcap
+ simpa only [Nat.sub_add_cancel hp,localCall] using
+ execute_prefix workers pub e (cap-(e.prefixEvents (header pub)).length) m bs hfit valid
+
+/-- Invert a successful call into its actual worker report, its exact cap
+test and its complete controller trace. -/
+theorem recover_call (cap : ℕ) (e : Entry w) (m : Memory w) (bs : List Bool)
+ (hfit : 5 ≤ 2^w) (hcap : 26 ≤ cap) (valid : e.Valid (header pub) m) (out : Report w) :
+ let L := program workers pub
+ let S := source workers e.stage pub
+ let f := cap - (e.prefixEvents (header pub)).length
+ execute L cap (L.start e.marker) m bs = some out ↔
+ ∃ raw, execute S f (S.start e.state) m bs = some raw ∧
+ (exitReport (header pub) e.stage raw).events.length < f ∧ out = report (header pub) e raw := by
+ dsimp only
+ rw [execute_entry workers pub cap e m bs hfit hcap valid]
+ unfold localCall
+ dsimp only
+ cases hr : execute (source workers e.stage pub) (cap - (e.prefixEvents (header pub)).length)
+ ((source workers e.stage pub).start e.state) m bs with
+ | none => simp
+ | some raw =>
+ by_cases hf : (exitReport (header pub) e.stage raw).events.length < cap - (e.prefixEvents (header pub)).length
+ · simp [boundedExit,hf,report,eq_comm]
+ · simp [boundedExit,hf]
+
+/-- Attach the genuine prefix and exit to a worker execution that passes
+the exact exit-cap test. -/
+theorem call_ok (cap : ℕ) (e : Entry w) (m : Memory w) (bs : List Bool)
+ (hfit : 5 ≤ 2^w) (hcap : 26 ≤ cap) (valid : e.Valid (header pub) m) (raw : Report w)
+ (hr : execute (source workers e.stage pub) (cap - (e.prefixEvents (header pub)).length)
+ ((source workers e.stage pub).start e.state) m bs = some raw)
+ (hf : (exitReport (header pub) e.stage raw).events.length < cap - (e.prefixEvents (header pub)).length) :
+ let L := program workers pub
+ execute L cap (L.start e.marker) m bs = some (report (header pub) e raw) :=
+ (recover_call workers pub cap e m bs hfit hcap valid _).mpr ⟨raw,hr,hf,rfl⟩
+
+/-- Thirty spare dispatches suffice uniformly for a successful worker, including
+all five comparisons and a continuing exit. -/
+theorem call_of_room (cap : ℕ) (e : Entry w) (m : Memory w) (bs : List Bool)
+ (hfit : 5 ≤ 2^w) (valid : e.Valid (header pub) m) (f : ℕ) (raw : Report w)
+ (hr : execute (source workers e.stage pub) f ((source workers e.stage pub).start e.state) m bs = some raw)
+ (room : f+30 ≤ cap) :
+ let L := program workers pub
+ execute L cap (L.start e.marker) m bs = some (report (header pub) e raw) := by
+ have hp := prefix_length_le (header pub) e
+ have small := (execute_spec hr).1.length_lt
+ have hl := report_length_le (header pub) e raw
+ change ((e.prefixEvents (header pub)) ++ (exitReport (header pub) e.stage raw).events).length ≤ _ at hl
+ rw [List.length_append] at hl
+ have run := execute_extend hr (cap-(e.prefixEvents (header pub)).length-f)
+ rw [show f + (cap-(e.prefixEvents (header pub)).length-f) = cap-(e.prefixEvents (header pub)).length by omega] at run
+ exact call_ok workers pub cap e m bs hfit (by omega) valid raw run (by omega)
+
+/-- A successful call supplies a valid source entry even when its marker and
+header were given as arbitrary input words. -/
+theorem entry_of_success (cap : ℕ) (host : Word w) (m : Memory w) (bs : List Bool)
+ (hfit : 5 ≤ 2^w) (out : Report w)
+ (hr : execute (program workers pub) cap ((program workers pub).start host) m bs = some out) :
+ ∃ e : Entry w, e.marker = host ∧ e.Valid (header pub) m := by
+ by_cases hz : host = 0
+ · exact ⟨.initial,hz.symm,trivial⟩
+ by_cases ho : host = 1
+ · subst host
+ by_cases ht : ∃ s : Stage, m (header pub).val = tagWord w s
+ · obtain ⟨s,hs⟩ := ht
+ exact ⟨.resume s (m (header pub+31).val),rfl,hs,rfl⟩
+ · have bad := enter_bad_tag (component workers) pub hfit cap m (fun s h => ht ⟨s,h⟩) bs
+ exact (Option.some_ne_none _ (hr.symm.trans bad)).elim
+ · have bad := enter_bad_marker (component workers) pub host hz ho cap m bs
+ exact (Option.some_ne_none _ (hr.symm.trans bad)).elim
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalDataComplete.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalDataComplete.lean
new file mode 100644
index 0000000000..9b5f34ac08
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalDataComplete.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.PairSimulationTraceJobs
+
+/-! # Reconstructing the trace of every selected branch and terminal witness -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords Compression BurstRAM BurstRAM.PrivateRAM
+open scoped Classical
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A}
+
+open private AllData finalParsers_cast from OAI.Computability.VPVNP.PairSimulationTraceJobs
+open private castScans from OAI.Computability.VPVNP.PairSimulationScanTrace
+open private transportReaders from OAI.Computability.VPVNP.PairSimulationAssembly
+open private transportWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+
+private theorem allData_of_traces {N : Network} (H : History A N) (K : H.KernelWitnesses κ) (r : Readers H K)
+ (scan : ScanPhases H) (P : SiteParsers κ N) (ok : Phases → Prop)
+ (good : let enc := scanTrace H K r scan P.factors P.witnesses P.read
+ ∀ q : enc.Trace, ok (enc.phases q)) : AllData H K r scan P (fun phases _ => ok phases) := by
+ induction H generalizing ok with
+ | stop =>
+ intro x
+ exact good ⟨x.arcs,fun v => (P.read v _).completeEquiv (x.choices v)⟩
+ | branch s tail ih =>
+ intro i
+ obtain ⟨b,rfl⟩ := r.1.completeEquiv.symm.surjective i
+ let i := r.1.completeEquiv.symm b
+ let parser : TermParsers κ (s.term i) := ⟨r.2.1 i,r.2.2.1,K.1 i,r.2.2.2.1 i⟩
+ let sub := parser.push P
+ apply ih i (K.2 i) (r.2.2.2.2 i) (scan i) sub (fun p => ok (Phases.prepend (r.1.encode i) p))
+ intro enc q
+ have hcode : r.1.encode i = b.val := congrArg Subtype.val (r.1.completeEquiv.apply_symm_apply b)
+ rw [hcode]
+ exact good ⟨b,q⟩
+
+private theorem allData_uncast {N Y : Network} (e : N=Y) (H : History A N) (K : H.KernelWitnesses κ)
+ (r : Readers H K) (scan : ScanPhases H) (P : SiteParsers κ Y) (ok : Phases → (L → ℕ) → Prop)
+ (h : AllData (e ▸ H) (transportWitnesses e H K) (transportReaders e H K r) (castScans e H scan) P ok) :
+ AllData H K r scan (e.symm ▸ P) ok := by cases e; exact h
+
+variable {a g w p r k : ℕ} (X : State a g)
+ (M : Machine w p r k) (pc : Fin 10 → Fin p) (reg : Fin 2 ↪ Fin r) (base : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg base done) (he : M.entry = pc 0) (low : ℕ)
+ (pub : M.publicData base = FinalBits.cursor w low 0) (extra : ℕ)
+
+private theorem at_data {b n : ℕ} (E : StateExecution A b n X) (W : E.MapWitnesses κ)
+ (r : ExecutionReaders E W) (rec : E.Records) (P : SiteParsers κ X.network) (memory : E.Choices → Memory w)
+ (fit : ∀ z, low + (E.finalState z).totalWidth < 2^w) (ok : Phases → (L → ℕ) → Prop)
+ (h : AllData E.history (E.historyWitnesses W) (executionHistoryReaders E W r)
+ (executionScanPhases X M pc reg base done hl he low pub extra E memory fit) P ok) :
+ ∀ z, let scan := stateScanPhase (E.finalState z) M pc reg base done hl he low pub (memory z) extra (fit z)
+ ∀ x : TerminalData scan (terminalSites E W r rec P z),
+ ok (x.phases (siteOrder (E.finalState z)) (selectorCodes E W r z)) x.exponents := by
+ induction E generalizing ok with
+ | done X => rintro ⟨⟩; exact h
+ | more p tail ih =>
+ rintro ⟨i,z⟩
+ let nextP := (r.1.termParsers i).push P
+ let nextOK := fun phases powers => ok (Phases.prepend (r.1.select.encode i) phases) powers
+ have sub := allData_uncast (p.output_eq i).symm (tail i).history ((tail i).historyWitnesses (W.2 i))
+ (executionHistoryReaders (tail i) (W.2 i) (r.2 i))
+ (executionScanPhases (p.next i) M pc reg base done hl he low pub extra (tail i)
+ (fun z => memory ⟨i,z⟩) (fun z => fit ⟨i,z⟩)) nextP nextOK (h i)
+ have hsub := ih i (W.2 i) (r.2 i) (rec.2 i) ((p.output_eq i) ▸ nextP) (fun z => memory ⟨i,z⟩)
+ (fun z => fit ⟨i,z⟩) nextOK sub z
+ have same : terminalSites (.more p tail) W r rec P ⟨i,z⟩ =
+ terminalSites (tail i) (W.2 i) (r.2 i) (rec.2 i) ((p.output_eq i) ▸ nextP) z :=
+ finalParsers_cast (p.output_eq i).symm _ _ nextP
+ rw [same]
+ exact hsub
+
+/-- Every chosen descriptor branch, legal shared-arc tape and independent
+family of site choices emits a trace, in chronological phase order. -/
+theorem terminalData_emits {b n : ℕ} (E : StateExecution A b n X) (W : E.MapWitnesses κ)
+ (r : ExecutionReaders E W) (rec : E.Records) (P : SiteParsers κ X.network) (memory : E.Choices → Memory w)
+ (fit : ∀ z, low + (E.finalState z).totalWidth < 2^w) :
+ let enc := scanTrace E.history (E.historyWitnesses W) (executionHistoryReaders E W r)
+ (executionScanPhases X M pc reg base done hl he low pub extra E memory fit) P.factors P.witnesses P.read
+ ∀ z, let scan := stateScanPhase (E.finalState z) M pc reg base done hl he low pub (memory z) extra (fit z)
+ ∀ x : TerminalData scan (terminalSites E W r rec P z),
+ x.phases (siteOrder (E.finalState z)) (selectorCodes E W r z) ∈ Set.range enc.phases := by
+ intro enc
+ apply at_data X M pc reg base done hl he low pub extra E W r rec P memory fit (fun phases _ => phases ∈ Set.range enc.phases)
+ apply allData_of_traces
+ exact fun q => ⟨q,rfl⟩
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalDataPaths.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalDataPaths.lean
new file mode 100644
index 0000000000..04f7185ff0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalDataPaths.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalBlocks
+import OAI.Computability.VPVNP.PairSimulationTerminalTraceEquiv
+import OAI.Computability.VPVNP.PairSimulationTerminalPhaseBuild
+import OAI.Computability.VPVNP.PairSimulationTraceJobs
+
+/-!
+# Terminal payloads and site witnesses in the five native phases
+
+The three setup blocks are forced by their empty choice tapes. A shared
+payload therefore selects exactly one fourth block and determines the memory
+for the last block. Independent site witnesses in that selected payload
+classify the final vertex block. The resulting path has the unabridged five
+streams and all of their physical reports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+open BurstRAM LiveProgram NetworkKernel LocalHistory CompressorRecords
+
+variable {w : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w} {cap : ℕ}
+
+private theorem quiet_block {e m} (known : CompletedPhase workers pub cap e m)
+ (quiet : ∀ b ∈ known.val.choices, b=[]) (other : Block w)
+ (phase : Phase workers pub cap e m other.choices other.logs other.memory) : other = known.val := by
+ obtain ⟨choices,logs,memory⟩ := known.prop.force_quiet quiet phase
+ cases known with | mk known _ =>
+ cases known
+ cases other
+ simp_all only
+
+variable {m : Memory w}
+
+private theorem trace_injective (q : QuietPrefix workers pub cap m) :
+ Function.Injective (fun x : Σ a : q.BitPaths, q.VertexPaths a => q.trace x.1 x.2) := by
+ rintro ⟨a,x⟩ ⟨b,y⟩ eq
+ have ab : a=b := Subtype.ext (congrArg FiveTrace.sharedBits eq)
+ subst b
+ exact congrArg (Sigma.mk a) (Subtype.ext (congrArg FiveTrace.vertices eq))
+
+private theorem trace_surjective (q : QuietPrefix workers pub cap m) :
+ Function.Surjective (fun x : Σ a : q.BitPaths, q.VertexPaths a => q.trace x.1 x.2) := by
+ rintro ⟨u,v,z,b,x,hu,hv,hz,hb,hx⟩
+ obtain rfl := quiet_block q.boot q.bootQuiet u hu
+ obtain rfl := quiet_block q.prefixRows q.prefixQuiet v hv
+ obtain rfl := quiet_block q.traversalRows q.traversalQuiet z hz
+ exact ⟨⟨⟨b,hb⟩,⟨x,hx⟩⟩,rfl⟩
+
+/-- Every accepting terminal trace consists of the three known blocks
+followed by two independently classified blocks, with dependent memory. -/
+noncomputable def QuietPrefix.blocksEquiv (q : QuietPrefix workers pub cap m) :
+ (Σ a : q.BitPaths, q.VertexPaths a) ≃ FiveTrace workers pub cap m :=
+ Equiv.ofBijective (fun x => q.trace x.1 x.2) ⟨trace_injective q,trace_surjective q⟩
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {N : Network}
+variable {sc : ScanPhase N} {P : SiteParsers κ N} (q : QuietPrefix workers pub cap m)
+variable (bits : sc.Path ≃ q.BitPaths)
+variable (jobs : ∀ a : sc.Path,
+ (∀ v, (P.witnesses v (WireTensor.edgeAssignment N.src N.dst (sc.payload a) v)).Choice) ≃ q.VertexPaths (bits a))
+
+/-- Each shared arc assignment and its site jobs give the five actual
+physical blocks, and every five-block trace recovers this data. -/
+noncomputable def QuietPrefix.dataTrace : TerminalData sc P ≃ FiveTrace workers pub cap m :=
+ let split : TerminalData sc P ≃ (Σ a : sc.Path,
+ ∀ v, (P.witnesses v (WireTensor.edgeAssignment N.src N.dst (sc.payload a) v)).Choice) :=
+ ⟨fun x => ⟨x.arcs,x.choices⟩, fun x => ⟨x.1,x.2⟩, fun _ => rfl, fun _ => rfl⟩
+ split.trans ((Equiv.sigmaCongr (β₂ := q.VertexPaths) bits jobs).trans q.blocksEquiv)
+
+theorem QuietPrefix.dataTrace_eq (x : TerminalData sc P) :
+ q.dataTrace bits jobs x = q.trace (bits x.arcs) (jobs x.arcs x.choices) := rfl
+
+/-- The five-stage source program counts the actual shared arc and vertex
+witnesses, with an arbitrary cap that holds for every produced trace. -/
+noncomputable def QuietPrefix.dataPaths (fit : 32 ≤ 2^w) (enough : 26 ≤ cap)
+ (ok : List (Report w) → Prop)
+ (bounded : ∀ x : TerminalData sc P, ok (reports (header pub) (q.dataTrace bits jobs x).logs)) :
+ TerminalData sc P ≃ ActualPaths (program workers pub) cap 0 m ok :=
+ let e := q.dataTrace bits jobs
+ let restrict : FiveTrace workers pub cap m ≃ {t : FiveTrace workers pub cap m // ok (reports (header pub) t.logs)} :=
+ (Equiv.subtypeUnivEquiv (fun t => by obtain ⟨x,rfl⟩ := e.surjective t; exact bounded x)).symm
+ e.trans (restrict.trans (fiveTraceEquiv workers pub cap m ok fit enough))
+
+theorem QuietPrefix.dataPaths_tapes (fit : 32 ≤ 2^w) (enough : 26 ≤ cap) (ok : List (Report w) → Prop)
+ (bounded : ∀ x : TerminalData sc P, ok (reports (header pub) (q.dataTrace bits jobs x).logs))
+ (x : TerminalData sc P) :
+ (q.dataPaths bits jobs fit enough ok bounded x).val =
+ (q.trace (bits x.arcs) (jobs x.arcs x.choices)).choices := rfl
+
+theorem FiveTrace.after_reports (t : FiveTrace workers pub cap m) :
+ after m (eventLog (reports (header pub) t.logs)) = t.vertices.memory := by
+ have join (mem : Memory w) (x y : List (Log w)) :
+ after mem (eventLog (reports (header pub) (x++y))) =
+ after (after mem (eventLog (reports (header pub) x))) (eventLog (reports (header pub) y)) := by
+ simp only [reports,List.map_append,eventLog,List.flatMap_append,after,List.foldl_append]
+ rw [FiveTrace.logs,join,t.bootRun.final_memory,join,t.prefixRun.final_memory,join,t.rowRun.final_memory,
+ join,t.bitRun.final_memory,t.vertexRun.final_memory]
+
+theorem QuietPrefix.dataPaths_logs (fit : 32 ≤ 2^w) (enough : 26 ≤ cap) (ok : List (Report w) → Prop)
+ (bounded : ∀ x : TerminalData sc P, ok (reports (header pub) (q.dataTrace bits jobs x).logs))
+ (x : TerminalData sc P) :
+ (q.dataPaths bits jobs fit enough ok bounded x).property.choose =
+ reports (header pub) (q.trace (bits x.arcs) (jobs x.arcs x.choices)).logs := by
+ let tr := q.trace (bits x.arcs) (jobs x.arcs x.choices)
+ have actual := (q.dataPaths bits jobs fit enough ok bounded x).property.choose_spec.1
+ apply Option.some.inj (actual.symm.trans _)
+ exact tr.visits.native workers pub cap fit enough (by rintro e he; cases he; trivial)
+
+theorem QuietPrefix.dataPaths_after (fit : 32 ≤ 2^w) (enough : 26 ≤ cap) (ok : List (Report w) → Prop)
+ (bounded : ∀ x : TerminalData sc P, ok (reports (header pub) (q.dataTrace bits jobs x).logs))
+ (x : TerminalData sc P) :
+ after m (eventLog (q.dataPaths bits jobs fit enough ok bounded x).property.choose) =
+ (jobs x.arcs x.choices).val.memory := by
+ rw [dataPaths_logs]
+ exact FiveTrace.after_reports _
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalDeterministic.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalDeterministic.lean
new file mode 100644
index 0000000000..5eca0e3ccc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalDeterministic.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalFive
+import OAI.Computability.VPVNP.LiveHeaderProtectedCore
+
+/-!
+# Recovering deterministic terminal stages on arbitrary accepting tapes
+
+For a known ordinary worker segment with only empty choice strings, transport
+its reads into the actual memory before comparing each physical call. This
+proves the actual segment has the same report, choices and final worker memory
+even when its caller supplies an arbitrary candidate tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM LiveProgram CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w} {cap : ℕ}
+
+theorem Phase.reports_eq {e m bs ls final} (h : Phase workers pub cap e m bs ls final) :
+ reports (header pub) ls = stageReports (header pub) e (ls.map Prod.snd) := by
+ induction h with
+ | last => rfl
+ | more _ _ returned _ ih => simp [reports,stageReports,returned] at ih ⊢; exact ih
+
+theorem Phase.final_memory {e m bs ls final} (h : Phase workers pub cap e m bs ls final) :
+ after m (eventLog (reports (header pub) ls)) = final := by
+ induction h with
+ | last => simp [eventLog,reports]
+ | more _ _ _ _ ih =>
+ simpa only [eventLog,reports,List.map_cons,List.flatMap_cons,after,List.foldl_append] using ih
+
+private theorem after_agree (addr : Word w) (e : Entry w) (raw : Report w) (src phy : Memory w)
+ (h : SourceTransport.Agree (workerCell addr) src phy) :
+ SourceTransport.Agree (workerCell addr) (after src raw.events) (after phy (report addr e raw).events) := by
+ rw [report_after]
+ cases ht : target e.stage raw.result with
+ | none => exact h.after _
+ | some sv =>
+ obtain ⟨t,x⟩ := sv
+ intro i hi
+ simpa only [writeMemory,ite_eq_right hi.1,ite_eq_right hi.2] using h.after raw.events i hi
+
+private theorem force_head {C : Type*} {P : BurstRAM.Program w C} {f g : ℕ} {c : C} {phy src : Memory w}
+ {bits : List Bool} {raw known : Report w} {data : ℕ → Prop}
+ (call : execute P g c phy bits = some raw) (expected : execute P f c src [] = some known)
+ (agree : SourceTransport.Agree data src phy) (reads : SourceTransport.Reads data known.events) :
+ bits = [] ∧ raw = known := by
+ obtain ⟨path,ok,choices⟩ := execute_spec expected
+ have replay : execute P f c phy [] = some known :=
+ execute_iff.mpr ⟨path,SourceTransport.correct agree reads ok,choices⟩
+ exact execute_empty_forces_anyFuel replay call
+
+/-- The witness needs a read bound only for the supplied deterministic
+reference reports. The arbitrary candidate is taken directly from the
+complete native path, with no hypothesis on its read addresses. -/
+theorem Phase.force_empty {e phy bs ls final} (h : Phase workers pub cap e phy bs ls final)
+ (src : Memory w) (n f : ℕ) (known : List (Report w))
+ (expected : runSegment (source workers e.stage pub) f (some e.state) src (List.replicate n []) = some known)
+ (halt : endState (some e.state) known = none)
+ (agree : SourceTransport.Agree (workerCell (header pub)) src phy)
+ (reads : SourceTransport.Reads (workerCell (header pub)) (eventLog known)) :
+ bs = List.replicate n [] ∧ ls.map Prod.snd = known ∧
+ SourceTransport.Agree (workerCell (header pub)) (after src (eventLog known)) final := by
+ induction h generalizing n src known with
+ | @last e phy b raw call room closed =>
+ cases n with
+ | zero =>
+ have hk : known = [] := by simpa [runSegment] using expected.symm
+ simp [hk,endState] at halt
+ | succ n =>
+ cases hc : execute (source workers e.stage pub) f ((source workers e.stage pub).start e.state) src [] with
+ | none => simp [List.replicate_succ,runSegment,hc] at expected
+ | some head =>
+ simp only [List.replicate_succ,runSegment,hc,Option.map_eq_some_iff] at expected
+ obtain ⟨tail,rest,rfl⟩ := expected
+ have readHead : SourceTransport.Reads _ head.events := fun a v hv =>
+ reads a v (List.mem_append_left (eventLog tail) hv)
+ obtain ⟨rfl,rfl⟩ := force_head call hc agree readHead
+ rw [closed] at rest
+ cases n with
+ | zero =>
+ have ht : tail = [] := (Option.some.inj rest).symm
+ subst tail
+ exact ⟨rfl,rfl,by simpa [eventLog] using after_agree (header pub) e raw src phy agree⟩
+ | succ n => simp [List.replicate_succ,runSegment] at rest
+ | @more e phy b more raw x ls final call room returned next ih =>
+ cases n with
+ | zero =>
+ have hk : known = [] := by simpa [runSegment] using expected.symm
+ simp [hk,endState] at halt
+ | succ n =>
+ cases hc : execute (source workers e.stage pub) f ((source workers e.stage pub).start e.state) src [] with
+ | none => simp [List.replicate_succ,runSegment,hc] at expected
+ | some head =>
+ simp only [List.replicate_succ,runSegment,hc,Option.map_eq_some_iff] at expected
+ obtain ⟨tail,rest,rfl⟩ := expected
+ have readHead : SourceTransport.Reads _ head.events := fun a v hv =>
+ reads a v (List.mem_append_left (eventLog tail) hv)
+ have readTail : SourceTransport.Reads _ (eventLog tail) := fun a v hv =>
+ reads a v (List.mem_append_right head.events hv)
+ obtain ⟨rfl,rfl⟩ := force_head call hc agree readHead
+ rw [returned] at rest
+ change endState raw.result tail = none at halt
+ rw [returned] at halt
+ obtain ⟨ht,hr,ha⟩ := ih (after src raw.events) n tail rest halt (after_agree (header pub) e raw src phy agree) readTail
+ exact ⟨by simp [List.replicate_succ,ht],by simp [hr],
+ by simpa only [eventLog,List.flatMap_cons,after,List.foldl_append] using ha⟩
+
+/-- Every completed phase from the same physical entry agrees with a
+completed phase that consumed only empty choice strings. -/
+theorem Phase.force_quiet {e phy qs ls out qs' ls' out'}
+ (known : Phase workers pub cap e phy qs ls out) (quiet : ∀ b ∈ qs, b = [])
+ (candidate : Phase workers pub cap e phy qs' ls' out') :
+ qs' = qs ∧ ls' = ls ∧ out' = out := by
+ induction known generalizing qs' ls' out' with
+ | @last e phy b raw call room closed =>
+ have empty := quiet b (by simp)
+ subst b
+ cases candidate with
+ | last act _ _ =>
+ obtain ⟨rfl,rfl⟩ := execute_empty_forces_anyFuel call act
+ exact ⟨rfl,rfl,rfl⟩
+ | more act _ returned _ =>
+ obtain ⟨rfl,rfl⟩ := execute_empty_forces_anyFuel call act
+ simp [closed] at returned
+ | @more e phy b bs raw x ls out call room returned later ih =>
+ have empty := quiet b (by simp)
+ subst b
+ cases candidate with
+ | last act _ closed =>
+ obtain ⟨rfl,rfl⟩ := execute_empty_forces_anyFuel call act
+ simp [closed] at returned
+ | more act _ ret tail =>
+ obtain ⟨rfl,rfl⟩ := execute_empty_forces_anyFuel call act
+ rw [returned] at ret
+ obtain rfl := Option.some.inj ret
+ obtain ⟨rfl,rfl,rfl⟩ := ih (fun s hs => quiet s (List.mem_cons_of_mem _ hs)) tail
+ exact ⟨rfl,rfl,rfl⟩
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalEnter.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalEnter.lean
new file mode 100644
index 0000000000..bd37c1580e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalEnter.lean
@@ -0,0 +1,315 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalLink
+import OAI.Computability.VPVNP.LiveStageLinkRun
+import OAI.Computability.VPVNP.LiveHeaderProtectedCore
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Exact entry paths of the compressed-pair terminal controller
+
+A zero marker initializes the bootstrap worker from an empty private workspace.
+A one marker reloads the selected worker and its private cursor from the two
+header cells. The scan and both header reads are included in the native trace.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+variable {w r : ℕ} {pcs : Stage → ℕ}
+variable (T : (s : Stage) → Template (pcs s) r 11) (pub : Fin 11 → Word w)
+
+/-- Administrative steps before the first bootstrap call. -/
+def initialEvents (w : ℕ) : List (Event w) := List.replicate 13 .tick
+
+/-- Header reads and stage comparisons before a resumed worker call. -/
+def dispatchEvents (addr state : Word w) (s : Stage) : List (Event w) :=
+ List.replicate 14 .tick ++ [.read addr (tagWord w s), .read (addr+31) state] ++
+ List.replicate (2*(s.val+1)) .tick
+
+@[simp] theorem length_initialEvents : (initialEvents w).length = 13 := by simp [initialEvents]
+@[simp] theorem length_dispatchEvents (addr state : Word w) (s : Stage) :
+ (dispatchEvents addr state s).length = 16 + 2*(s.val+1) := by simp [dispatchEvents]; omega
+
+private def bank (a b c d e f : Word w) : Fin (r+6) → Word w :=
+ Fin.append (fun _ => 0) ![a,b,c,d,e,f]
+
+private def ctrl (pc : Fin (codeSize pcs)) (host a b c d e f : Word w) : Config w (codeSize pcs) (r+6) :=
+ ⟨pc,host,bank a b c d e f,fun _ => 0⟩
+
+private theorem bank_at (a b c d e f : Word w) (i : Fin 6) :
+ bank a b c d e f (extra r i) = ![a,b,c,d,e,f] i := by simp [bank,extra]
+
+private theorem bank_update (a b c d e f v : Word w) (j : Fin 6) :
+ Function.update (bank a b c d e f) (extra r j) v =
+ bank (if 0=j then v else a) (if 1=j then v else b) (if 2=j then v else c)
+ (if 3=j then v else d) (if 4=j then v else e) (if 5=j then v else f) := by
+ funext i
+ cases i using Fin.addCases with
+ | left i =>
+ have h : i.castAdd 6 ≠ j.natAdd r := by
+ intro he
+ have := congrArg Fin.val he
+ simp at this
+ omega
+ simp [bank,extra,Function.update,h]
+ | right i => fin_cases i <;> simp [bank,extra,Function.update]
+
+private theorem ctrl_start (host : Word w) :
+ (machine T pub).program.start host = ctrl (enter pcs 0) host 0 0 0 0 0 0 := by
+ change Config.mk _ _ (fun _ => 0) _ = Config.mk _ _ _ _
+ congr 1
+ funext i
+ cases i using Fin.addCases with
+ | left i => simp [bank]
+ | right i => fin_cases i <;> simp [bank]
+
+private theorem step_enter (i : Fin 17) (host a b c d e f : Word w) :
+ (machine T pub).program.step (ctrl (enter pcs i) host a b c d e f) =
+ (enterInstr T w i).run pub (ctrl (enter pcs i) host a b c d e f) := by
+ change ((machine T pub).code (enter pcs i)).run pub _ = _
+ rw [code_enter]
+
+private def setup (host : Word w) : Fin 13 → Config w (codeSize pcs) (r+6) :=
+ let a := pub 2
+ let d := pub 7
+ let z := BinaryOp.shiftLeft.eval 1 d
+ let h := header pub
+ ![ctrl (enter pcs 0) host 0 0 0 0 0 0,
+ ctrl (enter pcs 1) host a 0 0 0 0 0,
+ ctrl (enter pcs 2) host a 0 0 d 0 0,
+ ctrl (enter pcs 3) host a 0 0 d 0 1,
+ ctrl (enter pcs 4) host a 0 0 d z 1,
+ ctrl (enter pcs 5) host a 0 0 d (z*z) 1,
+ ctrl (enter pcs 6) host (a+z*z) 0 0 d (z*z) 1,
+ ctrl (enter pcs 7) host (a+z*z) 0 0 d 32 1,
+ ctrl (enter pcs 8) host h 0 0 d 32 1,
+ ctrl (enter pcs 9) host h 0 0 d 31 1,
+ ctrl (enter pcs 10) host h (h+31) 0 d 31 1,
+ ctrl (enter pcs 11) host h (h+31) 0 d host 1,
+ ctrl (enter pcs 12) host h (h+31) 0 d host 1]
+
+private theorem setup_step (host : Word w) (i : Fin 12) :
+ (machine T pub).program.step (setup pub host i.castSucc) =
+ .localStep (setup pub host i.succ) := by
+ fin_cases i
+ all_goals
+ change (machine T pub).program.step (ctrl (enter pcs _) _ _ _ _ _ _ _) =
+ .localStep (ctrl (enter pcs _) _ _ _ _ _ _ _)
+ rw [step_enter]
+ change CallAction.localStep _ = _
+ simp only [Config.put, ctrl, bank_update, bank_at]
+ rfl
+
+private theorem ticks_prefix {p q k : ℕ} {M : Machine w p q k} {n : ℕ}
+ (cs : Fin (n+1) → Config w p q)
+ (hs : ∀ i : Fin n, M.program.step (cs i.castSucc) = .localStep (cs i.succ)) :
+ PrimedCounter.GuessWord.Prefix M (cs 0) (List.replicate n .tick) (cs (Fin.last n)) := by
+ induction n with
+ | zero => exact .nil _
+ | succ n ih =>
+ rw [List.replicate_succ]
+ exact .tick (hs 0) (ih (fun j => cs j.succ) (fun i => hs i.succ))
+
+private theorem enter_common (host : Word w) (f : ℕ) (m : Memory w) (bits : List Bool) :
+ let L := (machine T pub).program
+ execute L (f+12) (L.start host) m bits =
+ (execute L f (ctrl (enter pcs 12) host (header pub) (header pub+31) 0 (pub 7) host 1) m bits).map
+ (LiveStageLink.prependLog (List.replicate 12 .tick)) := by
+ dsimp only
+ rw [ctrl_start]
+ exact (ticks_prefix (setup pub host) (setup_step T pub host)).execute f m bits
+
+
+private abbrev ready (pc : Fin (codeSize pcs)) (host addr state tag tmp : Word w) :
+ Config w (codeSize pcs) (r+6) := ctrl pc host addr (addr+31) state tag tmp 1
+
+private theorem marker_zero_step (host : Word w) :
+ (machine T pub).program.step (ready (enter pcs 12) host (header pub) 0 (pub 7) host) =
+ .localStep (ready (if host = 0 then bodyPC pcs 0 (T 0).entry else enter pcs 13)
+ host (header pub) 0 (pub 7) host) := by
+ rw [step_enter]
+ change (Instr.jumpEq (temporary r) (stateValue r) _ _).run pub _ = _
+ simp only [Instr.run, ready, ctrl, bank_at]
+ rfl
+
+private theorem marker_one_step (host : Word w) :
+ (machine T pub).program.step (ready (enter pcs 13) host (header pub) 0 (pub 7) host) =
+ .localStep (ready (if host = 1 then enter pcs 14 else enter pcs 16)
+ host (header pub) 0 (pub 7) host) := by
+ rw [step_enter]
+ change (Instr.jumpEq (temporary r) (unitReg r) _ _).run pub _ = _
+ simp only [Instr.run, ready, ctrl, bank_at]
+ rfl
+
+private theorem phase_read_step :
+ (machine T pub).program.step (ready (enter pcs 14) 1 (header pub) 0 (pub 7) 1) =
+ .read (header pub) (fun tag => ready (enter pcs 15) 1 (header pub) 0 tag 1) := by
+ rw [step_enter]
+ change (Instr.readExternal (phaseValue r) (phaseAddress r) _).run pub _ = _
+ simp only [Instr.run, ready, ctrl, Config.put, bank_update, bank_at]
+ rfl
+
+private theorem state_read_step (tag : Word w) :
+ (machine T pub).program.step (ready (enter pcs 15) 1 (header pub) 0 tag 1) =
+ .read (header pub+31) (fun state => ready (scan pcs 0) 1 (header pub) state tag 1) := by
+ rw [step_enter]
+ change (Instr.readExternal (stateValue r) (savedAddress r) _).run pub _ = _
+ simp only [Instr.run, ready, ctrl, Config.put, bank_update, bank_at]
+ rfl
+
+private theorem scan_step (s : Stage) (host addr state tag tmp : Word w) :
+ (machine T pub).program.step (ready (scan pcs s.castSucc) host addr state tag tmp) =
+ .localStep (ready (compare pcs s) host addr state tag (tagWord w s)) := by
+ simp only [Machine.program,ready,ctrl,code_scan,Instr.run,Config.put,bank_update]
+ rfl
+
+private theorem compare_step (s : Stage) (host addr state tag : Word w) :
+ (machine T pub).program.step (ready (compare pcs s) host addr state tag (tagWord w s)) =
+ .localStep (ready (if tag = tagWord w s then bodyPC pcs s (T s).entry else scan pcs s.succ)
+ host addr state tag (tagWord w s)) := by
+ simp only [Machine.program,ready,ctrl,code_compare,Instr.run,bank_at]
+ rfl
+
+private theorem scan_pair (s : Stage) (host addr state tag tmp : Word w)
+ (f : ℕ) (m : Memory w) (bits : List Bool) :
+ let L := (machine T pub).program
+ let dest := if tag = tagWord w s then bodyPC pcs s (T s).entry else scan pcs s.succ
+ execute L (f+2) (ready (scan pcs s.castSucc) host addr state tag tmp) m bits =
+ (execute L f (ready dest host addr state tag (tagWord w s)) m bits).map
+ (LiveStageLink.prependLog [.tick,.tick]) := by
+ dsimp only
+ simp only [execute,scan_step,compare_step,Option.map_map]
+ rfl
+
+private theorem scan_run (s : Stage) (hfits : 5 ≤ 2^w) (host addr state : Word w)
+ (f : ℕ) (m : Memory w) (bits : List Bool) (u : ℕ) (j : Stage) (hj : j.val+u=s.val) (tmp : Word w) :
+ let L := (machine T pub).program
+ execute L (f+2*(u+1)) (ready (scan pcs j.castSucc) host addr state (tagWord w s) tmp) m bits =
+ (execute L f (ready (bodyPC pcs s (T s).entry) host addr state (tagWord w s) (tagWord w s)) m bits).map
+ (LiveStageLink.prependLog (List.replicate (2*(u+1)) .tick)) := by
+ dsimp only
+ induction u generalizing j tmp with
+ | zero =>
+ have he : j = s := Fin.ext (by omega)
+ subst j
+ simpa using scan_pair T pub s host addr state (tagWord w s) tmp f m bits
+ | succ u ih =>
+ have lt : j.val < s.val := by omega
+ let j' : Stage := ⟨j.val+1, by have := s.isLt; omega⟩
+ have ne : tagWord w s ≠ tagWord w j := by
+ intro he
+ have := congrArg Fin.val he
+ simp [tagWord,Nat.mod_eq_of_lt (s.isLt.trans_le hfits),Nat.mod_eq_of_lt (j.isLt.trans_le hfits)] at this
+ omega
+ rw [show f + 2*(u+1+1) = (f+2*(u+1))+2 by omega, scan_pair, ite_eq_right ne,
+ show j.succ = j'.castSucc from rfl, ih j' (by dsimp [j']; omega), Option.map_map]
+ congr 1
+
+private theorem enter_reads (hne : (1 : Word w) ≠ 0) (f : ℕ) (m : Memory w) (bits : List Bool) :
+ let L := (machine T pub).program
+ let addr := header pub
+ execute L (f+16) (L.start 1) m bits =
+ (execute L f (ready (scan pcs 0) 1 addr (m (addr+31).val) (m addr.val) 1) m bits).map
+ (LiveStageLink.prependLog (List.replicate 14 .tick ++ [.read addr (m addr.val),.read (addr+31) (m (addr+31).val)])) := by
+ dsimp only
+ rw [show f+16 = (f+4)+12 by omega, enter_common]
+ simp only [execute,marker_zero_step,ite_eq_right hne,marker_one_step,↓reduceIte,
+ phase_read_step,state_read_step,Option.map_map]
+ rfl
+
+/-- A fresh call consumes thirteen local instructions and enters the bootstrap
+worker with local state zero. -/
+theorem enter_initial (f : ℕ) (m : Memory w) (bits : List Bool) :
+ let L := (machine T pub).program
+ let S := ((T 0).instantiate w pub).program
+ execute L (f+(initialEvents w).length) (L.start 0) m bits =
+ (execute L f (bodyConfig 0 0 (header pub) (pub 7) 0 (S.start 0)) m bits).map
+ (LiveStageLink.prependLog (initialEvents w)) := by
+ dsimp only
+ rw [length_initialEvents,show f+13=(f+1)+12 by omega,enter_common,execute,marker_zero_step,ite_eq_left rfl,
+ Option.map_map]
+ rfl
+
+private theorem marker_ne_zero (hfits : 5 ≤ 2^w) : (1 : Word w) ≠ 0 := by
+ intro he
+ have hv := congrArg Fin.val he
+ change 1 % (2^w) = 0 at hv
+ rw [Nat.mod_eq_of_lt (by omega)] at hv
+ contradiction
+
+/-- A continuation fetches its full cursor and scans to the chosen worker,
+preserving the remaining instruction fuel and the complete choice stream. -/
+theorem enter_resume (s : Stage) (hfits : 5 ≤ 2^w) (state : Word w) (f : ℕ) (m : Memory w)
+ (htag : m (header pub).val = tagWord w s) (hstate : m (header pub+31).val = state) (bits : List Bool) :
+ let L := (machine T pub).program
+ let S := ((T s).instantiate w pub).program
+ let es := dispatchEvents (header pub) state s
+ execute L (f+es.length) (L.start 1) m bits =
+ (execute L f (bodyConfig s 1 (header pub) (tagWord w s) (tagWord w s) (S.start state)) m bits).map
+ (LiveStageLink.prependLog es) := by
+ dsimp only
+ have hne := marker_ne_zero hfits
+ rw [length_dispatchEvents, show f + (16+2*(s.val+1)) = (f+2*(s.val+1))+16 by omega,
+ enter_reads T pub hne, htag, hstate]
+ have hr := scan_run T pub s hfits 1 (header pub) state f m bits s.val 0 (by simp) 1
+ rw [show (0 : Stage).castSucc = 0 from rfl] at hr
+ dsimp only at hr
+ rw [hr,Option.map_map]
+ congr 1
+
+
+/-- Every marker other than zero and one is rejected before a header probe. -/
+theorem enter_bad_marker (host : Word w) (hzero : host ≠ 0) (hone : host ≠ 1)
+ (f : ℕ) (m : Memory w) (bits : List Bool) :
+ let L := (machine T pub).program
+ execute L f (L.start host) m bits = none := by
+ dsimp only
+ cases h : execute (machine T pub).program f ((machine T pub).program.start host) m bits with
+ | none => rfl
+ | some q =>
+ have long := execute_extend h 15
+ rw [show f+15 = (f+3)+12 by omega, enter_common] at long
+ have stop : (machine T pub).program.step (ready (enter pcs 16) host (header pub) 0 (pub 7) host) = .reject := by
+ rw [step_enter]
+ rfl
+ simp only [execute,marker_zero_step,ite_eq_right hzero,marker_one_step,ite_eq_right hone,stop,
+ Option.map_none,reduceCtorEq] at long
+
+private theorem scan_bad (host addr state tag : Word w) (hbad : ∀ s : Stage, tag ≠ tagWord w s)
+ (f : ℕ) (m : Memory w) (bits : List Bool) (u : ℕ) (j : Fin 6) (hj : j.val+u=5) (tmp : Word w) :
+ execute (machine T pub).program (f+2*u+1) (ready (scan pcs j) host addr state tag tmp) m bits = none := by
+ induction u generalizing j tmp with
+ | zero =>
+ have he : j = Fin.last 5 := Fin.ext (by simp; omega)
+ subst j
+ simp only [execute,Machine.program,ready,ctrl,code_scan_end,Instr.run]
+ | succ u ih =>
+ let s : Stage := ⟨j.val, by omega⟩
+ rw [show j = s.castSucc from Fin.ext rfl, show f+2*(u+1)+1 = (f+2*u+1)+2 by omega,
+ scan_pair, ite_eq_right (hbad s), ih s.succ (by simp [s]; omega), Option.map_none]
+
+/-- If the header does not name a worker, its scan reaches the reject opcode.
+This rules out a successful call at every cap and for every choice stream. -/
+theorem enter_bad_tag (hfits : 5 ≤ 2^w) (f : ℕ) (m : Memory w)
+ (hbad : ∀ s : Stage, m (header pub).val ≠ tagWord w s) (bits : List Bool) :
+ let L := (machine T pub).program
+ execute L f (L.start 1) m bits = none := by
+ dsimp only
+ cases h : execute (machine T pub).program f ((machine T pub).program.start 1) m bits with
+ | none => rfl
+ | some q =>
+ have long := execute_extend h 27
+ rw [show f+27 = (f+2*5+1)+16 by omega, enter_reads T pub (marker_ne_zero hfits),
+ scan_bad T pub 1 (header pub) _ _ hbad f m bits 5 0 (by decide) 1, Option.map_none] at long
+ contradiction
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalFive.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalFive.lean
new file mode 100644
index 0000000000..9c1468eca5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalFive.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalSplit
+
+/-!
+# The five terminal segments in every accepting pair traversal
+
+An accepting path splits at the unique first accepting exit of each worker.
+Conversely, the five completed physical segments join with the original
+choice strings in their original order. No normalization or padding of
+branch strings occurs at the stage boundaries.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM LiveProgram
+
+variable {w : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w} {cap : ℕ}
+
+theorem Phase.append_visits {e m bs ls final} (h : Phase workers pub cap e m bs ls final)
+ {more rest} (tail : Visits workers pub cap (handoff e.stage) final more rest) :
+ Visits workers pub cap (some e) m (bs++more) (ls++rest) := by
+ induction h with
+ | @last e m b raw call room accepted =>
+ have step : e.follow raw = handoff e.stage := by
+ cases hn : next e.stage <;> simp [Entry.follow,target,accepted,handoff,hn]
+ exact .cons call room (step ▸ tail)
+ | @more e m b bs raw x ls final call room returned _ ih =>
+ have step : e.follow raw = some (.resume e.stage x) := by simp [Entry.follow,target,returned]
+ exact .cons call room (step ▸ ih tail)
+
+theorem Phase.finish_append {e m bs ls final} (h : Phase workers pub cap e m bs ls final)
+ (rest : List (Log w)) : finish (some e) (ls++rest) = finish (handoff e.stage) rest := by
+ induction h with
+ | @last e m b raw call room accepted =>
+ cases hn : next e.stage <;> simp [finish,Entry.follow,target,accepted,handoff,hn]
+ | @more e m b bs raw x ls final call room returned _ ih =>
+ simpa only [List.cons_append,finish,Entry.follow,target,returned,Option.map_some,Entry.stage] using ih
+
+/-- The private choices, worker reports and physical exit memory of one stage. -/
+structure Block (w : ℕ) where
+ /-- Ordered private choice stream for each call of this stage. -/
+ choices : List (List Bool)
+ /-- Entry and original worker report for each call. -/
+ logs : List (Log w)
+ /-- Physical memory after the final call of the stage. -/
+ memory : Memory w
+
+/-- The five completed native worker phases and their consecutive physical memories. -/
+structure FiveTrace (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap : ℕ) (initialMemory : Memory w) where
+ /-- Trace of the terminal-header setup. -/
+ bootstrap : Block w
+ /-- Trace of the final width-prefix scan. -/
+ prefixRows : Block w
+ /-- Trace of the traversal-row and role-tag construction. -/
+ traversalRows : Block w
+ /-- Trace of the shared wire-bit scan. -/
+ sharedBits : Block w
+ /-- Trace of the ascending vertex calls and final ordinal check. -/
+ vertices : Block w
+ bootRun : Phase workers pub cap .initial initialMemory bootstrap.choices bootstrap.logs bootstrap.memory
+ prefixRun : Phase workers pub cap (.resume Stage.prefixRows 0) bootstrap.memory prefixRows.choices prefixRows.logs prefixRows.memory
+ rowRun : Phase workers pub cap (.resume Stage.traversalRows 0) prefixRows.memory traversalRows.choices traversalRows.logs traversalRows.memory
+ bitRun : Phase workers pub cap (.resume Stage.sharedBits 0) traversalRows.memory sharedBits.choices sharedBits.logs sharedBits.memory
+ vertexRun : Phase workers pub cap (.resume Stage.vertices 0) sharedBits.memory vertices.choices vertices.logs vertices.memory
+
+variable {m : Memory w}
+
+/-- All call choice strings in physical order. -/
+def FiveTrace.choices (t : FiveTrace workers pub cap m) :=
+ t.bootstrap.choices ++ (t.prefixRows.choices ++ (t.traversalRows.choices ++ (t.sharedBits.choices ++ t.vertices.choices)))
+
+/-- All tagged worker reports in physical order. -/
+def FiveTrace.logs (t : FiveTrace workers pub cap m) :=
+ t.bootstrap.logs ++ (t.prefixRows.logs ++ (t.traversalRows.logs ++ (t.sharedBits.logs ++ t.vertices.logs)))
+
+theorem FiveTrace.visits (t : FiveTrace workers pub cap m) :
+ Visits workers pub cap (some .initial) m t.choices t.logs := by
+ apply t.bootRun.append_visits
+ apply t.prefixRun.append_visits
+ apply t.rowRun.append_visits
+ apply t.bitRun.append_visits
+ change Visits workers pub cap (some (.resume Stage.vertices 0)) _ _ _
+ simpa only [List.append_nil] using t.vertexRun.append_visits (.nil _ _)
+
+theorem FiveTrace.closed (t : FiveTrace workers pub cap m) : finish (some .initial) t.logs = none := by
+ unfold FiveTrace.logs
+ rw [t.bootRun.finish_append]
+ change finish (some (.resume Stage.prefixRows 0)) _ = none
+ rw [t.prefixRun.finish_append]
+ change finish (some (.resume Stage.traversalRows 0)) _ = none
+ rw [t.rowRun.finish_append]
+ change finish (some (.resume Stage.sharedBits 0)) _ = none
+ rw [t.bitRun.finish_append]
+ change finish (some (.resume Stage.vertices 0)) _ = none
+ have last : handoff (w := w) Stage.vertices = none := rfl
+ simpa only [List.append_nil,Entry.stage,last,finish] using t.vertexRun.finish_append []
+
+theorem recover_five {bs : List (List Bool)} {ls : List (Log w)}
+ (h : Visits workers pub cap (some .initial) m bs ls) (closed : finish (some .initial) ls = none) :
+ ∃ t : FiveTrace workers pub cap m, bs = t.choices ∧ ls = t.logs := by
+ obtain ⟨b0,bs1,r0,rs1,m1,hb0,hr0,p0,v1,c1⟩ := split_stage workers pub cap .initial m bs ls h closed
+ obtain ⟨b1,bs2,r1,rs2,m2,hb1,hr1,p1,v2,c2⟩ :=
+ split_stage workers pub cap (.resume Stage.prefixRows 0) m1 bs1 rs1 v1 c1
+ obtain ⟨b2,bs3,r2,rs3,m3,hb2,hr2,p2,v3,c3⟩ :=
+ split_stage workers pub cap (.resume Stage.traversalRows 0) m2 bs2 rs2 v2 c2
+ obtain ⟨b3,bs4,r3,rs4,m4,hb3,hr3,p3,v4,c4⟩ :=
+ split_stage workers pub cap (.resume Stage.sharedBits 0) m3 bs3 rs3 v3 c3
+ obtain ⟨b4,bs5,r4,rs5,m5,hb4,hr4,p4,v5,_⟩ :=
+ split_stage workers pub cap (.resume Stage.vertices 0) m4 bs4 rs4 v4 c4
+ change Visits workers pub cap none m5 bs5 rs5 at v5
+ cases v5
+ refine ⟨⟨⟨b0,r0,m1⟩,⟨b1,r1,m2⟩,⟨b2,r2,m3⟩,⟨b3,r3,m4⟩,⟨b4,r4,m5⟩,p0,p1,p2,p3,p4⟩,
+ by simp [FiveTrace.choices,hb0,hb1,hb2,hb3,hb4],
+ by simp [FiveTrace.logs,hr0,hr1,hr2,hr3,hr4]⟩
+
+/-- A physical accepted branch string has all five completed stage runs.
+Its cap applies to the physical reports after dispatch and handoff. -/
+theorem accepts_five (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap : ℕ)
+ (m : Memory w) (bs : List (List Bool)) (ok : List (Report w) → Prop) (fit : 32 ≤ 2^w) (hcap : 26 ≤ cap) :
+ (∃ rs, runSegment (program workers pub) cap (some 0) m bs = some rs ∧ endState (some 0) rs = none ∧ ok rs) ↔
+ ∃ t : FiveTrace workers pub cap m, bs = t.choices ∧ ok (reports (header pub) t.logs) := by
+ rw [actual_iff workers pub cap m bs ok fit hcap]
+ constructor
+ · rintro ⟨ls,visits,closed,approved⟩
+ obtain ⟨t,he,rfl⟩ := recover_five visits closed
+ exact ⟨t,he,approved⟩
+ · rintro ⟨t,rfl,approved⟩
+ exact ⟨_,t.visits,t.closed,approved⟩
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalLink.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalLink.lean
new file mode 100644
index 0000000000..8a73aeb526
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalLink.lean
@@ -0,0 +1,230 @@
+import OAI.Computability.VPVNP.LiveProgram
+import OAI.Computability.VPVNP.LiveStageOperands
+
+/-!
+# The fixed eleven-operand terminal controller for compressed pairs
+
+The entry word zero starts the descriptor bootstrap unconditionally. Every
+continuation returns the marker one and writes its worker ordinal and full
+persistent word into the terminal header. Thus an ordinary zero returned by
+a worker is a valid local cursor. An accepting worker advances to the next
+worker with local state zero, except at the final vertex stage, where it
+accepts the whole terminal program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM LiveProgram
+open scoped Fin.CommRing
+
+/-- The five successive workers in a compressed pair's terminal computation. -/
+abbrev Stage := Fin 5
+namespace Stage
+/-- The worker that publishes the terminal header. -/
+abbrev bootstrap : Stage := 0
+/-- The worker that computes the prefix sums of final wire widths. -/
+abbrev prefixRows : Stage := 1
+/-- The worker that writes role tags and child rows for the selected layers. -/
+abbrev traversalRows : Stage := 2
+/-- The worker that chooses the final shared wire values. -/
+abbrev sharedBits : Stage := 3
+/-- The worker that processes the final vertices in increasing ordinal order. -/
+abbrev vertices : Stage := 4
+end Stage
+
+/-- The stage entered after this worker accepts, if another worker remains. -/
+def next (s : Stage) : Option Stage := if h : s.val+1 < 5 then some ⟨s.val+1,h⟩ else none
+
+/-- Fixed worker bank, sharing the low registers and retaining the complete
+eleven-word live pair ABI in each relocated instruction. -/
+def registers (workers : Stage → PairTable) := Finset.univ.sup fun s => (workers s).regs
+
+/-- Place a worker's registers in the common register bank. -/
+def embedding (workers : Stage → PairTable) (s : Stage) : Fin (workers s).regs ↪ Fin (registers workers) :=
+ ⟨fun i => i.castLE (Finset.le_sup (Finset.mem_univ s)), fun _ _ h => Fin.ext (congrArg (fun x : Fin (registers workers) => x.val) h)⟩
+
+/-- Relocate a worker to the shared register bank, preserving its public operands. -/
+def component (workers : Stage → PairTable) (s : Stage) :=
+ LiveStageLink.widen (workers s).table (embedding workers s) id
+
+/-- Control locations for entry, stage comparisons, worker bodies and return instructions. -/
+abbrev Label (pcs : Stage → ℕ) :=
+ Fin 17 ⊕ (Fin 6 ⊕ (Stage ⊕ (((s : Stage) × Fin (pcs s)) ⊕ (Stage ⊕ Fin 3))))
+
+/-- Number of instructions after placing the five workers and their dispatch code. -/
+def codeSize (pcs : Stage → ℕ) := 17+(6+(5+((∑ i,pcs i)+(5+3))))
+
+/-- Number the controller and worker labels in their physical instruction order. -/
+def labels (pcs : Stage → ℕ) : Label pcs ≃ Fin (codeSize pcs) :=
+ ((Equiv.refl _).sumCongr (((Equiv.refl _).sumCongr (((Equiv.refl _).sumCongr
+ ((finSigmaFinEquiv.sumCongr finSumFinEquiv).trans finSumFinEquiv)).trans finSumFinEquiv)).trans
+ finSumFinEquiv)).trans finSumFinEquiv
+
+/-- Address of an instruction in the terminal entry sequence. -/
+def enter (pcs : Stage → ℕ) (i : Fin 17) := labels pcs (.inl i)
+/-- Address of a stage-tag load or the exhausted-scan rejection. -/
+def scan (pcs : Stage → ℕ) (i : Fin 6) := labels pcs (.inr (.inl i))
+/-- Address of the comparison that selects a particular worker. -/
+def compare (pcs : Stage → ℕ) (s : Stage) := labels pcs (.inr (.inr (.inl s)))
+/-- Physical address of an instruction in the selected worker. -/
+def bodyPC (pcs : Stage → ℕ) (s : Stage) (i : Fin (pcs s)) := labels pcs (.inr (.inr (.inr (.inl ⟨s,i⟩))))
+/-- Address of the instruction that stages a tag for the next call. -/
+def storeTag (pcs : Stage → ℕ) (s : Stage) := labels pcs (.inr (.inr (.inr (.inr (.inl s)))))
+/-- Address of a control-word write or the return to the host. -/
+def save (pcs : Stage → ℕ) (i : Fin 3) := labels pcs (.inr (.inr (.inr (.inr (.inr i)))))
+
+variable {r w : ℕ} {pcs : Stage → ℕ}
+
+/-- Physical index of a register used by the worker. -/
+abbrev ordinary (i : Fin r) : Fin (r+6) := i.castAdd 6
+/-- Physical index of a register reserved by the terminal controller. -/
+abbrev extra (r : ℕ) (i : Fin 6) : Fin (r+6) := i.natAdd r
+/-- Register containing the address of the stage-tag cell. -/
+abbrev phaseAddress (r : ℕ) := extra r 0
+/-- Register containing the address of the saved worker state. -/
+abbrev savedAddress (r : ℕ) := extra r 1
+/-- Register holding the persistent word supplied to the worker. -/
+abbrev stateValue (r : ℕ) := extra r 2
+/-- Register holding the current or next stage tag. -/
+abbrev phaseValue (r : ℕ) := extra r 3
+/-- Register used in computing the header and comparing stage tags. -/
+abbrev temporary (r : ℕ) := extra r 4
+/-- Register containing the continuation marker one. -/
+abbrev unitReg (r : ℕ) := extra r 5
+
+/-- Values of the six controller registers while the worker executes. -/
+def extras (addr state tag tmp : Word w) : Fin 6 → Word w := ![addr,addr+31,state,tag,tmp,1]
+
+/-- Relocate the worker's current instruction and registers, retaining its private memory. -/
+def bodyConfig (s : Stage) (host addr tag tmp : Word w) (c : Config w (pcs s) r) : Config w (codeSize pcs) (r+6) :=
+ ⟨bodyPC pcs s c.pc,host,Fin.append c.reg (extras addr c.persistent tag tmp),c.privateMem⟩
+
+/-- Address of the first of the 32 terminal-header words in the pair workspace. -/
+def header (pub : Fin 11 → Word w) : Word w :=
+ let radix := BinaryOp.shiftLeft.eval 1 (pub 7)
+ pub 2 + radix*radix-32
+
+/-- Machine-word representation of the stage ordinal. -/
+def tagWord (w : ℕ) (s : Stage) : Word w := (s.val : Word w)
+
+/-- Translate a worker instruction, including restoration of its state and handling of its exit. -/
+def bodyInstr (s : Stage) : Instr w (pcs s) r 11 → Instr w (codeSize pcs) (r+6) 11
+ | .constant a v j => .constant (ordinary a) v (bodyPC pcs s j)
+ | .publicWord a i j => .publicWord (ordinary a) i (bodyPC pcs s j)
+ | .stateWord a j => .copy (ordinary a) (stateValue r) (bodyPC pcs s j)
+ | .copy a b j => .copy (ordinary a) (ordinary b) (bodyPC pcs s j)
+ | .binary op a b c j => .binary op (ordinary a) (ordinary b) (ordinary c) (bodyPC pcs s j)
+ | .loadPrivate a b j => .loadPrivate (ordinary a) (ordinary b) (bodyPC pcs s j)
+ | .storePrivate a b j => .storePrivate (ordinary a) (ordinary b) (bodyPC pcs s j)
+ | .jumpEq a b y n => .jumpEq (ordinary a) (ordinary b) (bodyPC pcs s y) (bodyPC pcs s n)
+ | .jumpLt a b y n => .jumpLt (ordinary a) (ordinary b) (bodyPC pcs s y) (bodyPC pcs s n)
+ | .choose y n => .choose (bodyPC pcs s y) (bodyPC pcs s n)
+ | .readExternal a b j => .readExternal (ordinary a) (ordinary b) (bodyPC pcs s j)
+ | .writeExternal a b j => .writeExternal (ordinary a) (ordinary b) (bodyPC pcs s j)
+ | .returnState a => .copy (stateValue r) (ordinary a) (storeTag pcs s)
+ | .reject => .reject
+ | .accept => match next s with
+ | none => .accept
+ | some t => .constant (stateValue r) 0 (storeTag pcs t)
+
+variable (T : (s : Stage) → Template (pcs s) r 11)
+
+/-- A width sufficient for the controller literals and every worker literal. -/
+def literalWidth := max 6 (Finset.univ.sup fun s => (T s).literalWidth)
+
+/-- Compute header addresses, check the host marker and enter or resume the terminal program. -/
+def enterInstr (W : ℕ) : Fin 17 → Instr W (codeSize pcs) (r+6) 11 :=
+ ![.publicWord (phaseAddress r) 2 (enter pcs 1),.publicWord (phaseValue r) 7 (enter pcs 2),
+ .constant (unitReg r) 1 (enter pcs 3),
+ .binary .shiftLeft (temporary r) (unitReg r) (phaseValue r) (enter pcs 4),
+ .binary .mul (temporary r) (temporary r) (temporary r) (enter pcs 5),
+ .binary .add (phaseAddress r) (phaseAddress r) (temporary r) (enter pcs 6),
+ .constant (temporary r) 32 (enter pcs 7),
+ .binary .sub (phaseAddress r) (phaseAddress r) (temporary r) (enter pcs 8),
+ .constant (temporary r) 31 (enter pcs 9),
+ .binary .add (savedAddress r) (phaseAddress r) (temporary r) (enter pcs 10),
+ .stateWord (temporary r) (enter pcs 11),
+ .constant (stateValue r) 0 (enter pcs 12),
+ .jumpEq (temporary r) (stateValue r) (bodyPC pcs 0 (T 0).entry) (enter pcs 13),
+ .jumpEq (temporary r) (unitReg r) (enter pcs 14) (enter pcs 16),
+ .readExternal (phaseValue r) (phaseAddress r) (enter pcs 15),
+ .readExternal (stateValue r) (savedAddress r) (scan pcs 0),.reject]
+
+/-- Write the stage and worker state, then return the host continuation marker. -/
+def saveInstr (W : ℕ) : Fin 3 → Instr W (codeSize pcs) (r+6) 11 :=
+ ![.writeExternal (phaseAddress r) (phaseValue r) (save pcs 1),
+ .writeExternal (savedAddress r) (stateValue r) (save pcs 2), .returnState (unitReg r)]
+
+/-- The instruction assigned to each physical controller or worker label. -/
+def instruction : Label pcs → Instr (literalWidth T) (codeSize pcs) (r+6) 11
+ | .inl i => enterInstr T _ i
+ | .inr (.inl i) => if h : i.val < 5 then .constant (temporary r) (tagWord _ ⟨i.val,h⟩) (compare pcs ⟨i.val,h⟩) else .reject
+ | .inr (.inr (.inl s)) => .jumpEq (phaseValue r) (temporary r) (bodyPC pcs s (T s).entry) (scan pcs s.succ)
+ | .inr (.inr (.inr (.inl ⟨s,i⟩))) => bodyInstr s (((T s).code i).resize _)
+ | .inr (.inr (.inr (.inr (.inl s)))) => .constant (phaseValue r) (tagWord _ s) (save pcs 0)
+ | .inr (.inr (.inr (.inr (.inr i)))) => saveInstr _ i
+
+/-- Static eleven-operand template linking the five relocated workers. -/
+def linked : Template (codeSize pcs) (r+6) 11 where
+ literalWidth := literalWidth T
+ entry := enter pcs 0
+ code j := instruction T ((labels pcs).symm j)
+
+/-- Finite terminal table obtained from the supplied numerical worker tables. -/
+def table (workers : Stage → PairTable) : PairTable :=
+ ⟨_, _, linked (component workers)⟩
+
+variable (pub : Fin 11 → Word w)
+
+/-- Instantiate the terminal template at the host word width and public input. -/
+abbrev machine := (linked T).instantiate w pub
+
+private theorem width_ge : 6 ≤ literalWidth T := le_max_left _ _
+
+@[simp] theorem code_enter (i : Fin 17) : (machine T pub).code (enter pcs i) = enterInstr T w i := by
+ have h : 32 < 2^literalWidth T := (by decide : 32 < 2^6).trans_le (Nat.pow_le_pow_right (by decide) (width_ge T))
+ simp only [machine,linked,Template.instantiate,enter,Equiv.symm_apply_apply,instruction]
+ have one : 1 < 2^literalWidth T := by omega
+ have thirty : 31 < 2^literalWidth T := by omega
+ fin_cases i <;> first | rfl | (simp [enterInstr,Instr.resize,Nat.mod_eq_of_lt h,Nat.mod_eq_of_lt one,Nat.mod_eq_of_lt thirty])
+
+private theorem tag_fits (s : Stage) : s.val < 2^literalWidth T :=
+ s.isLt.trans ((by decide : 5 < 2^6).trans_le (Nat.pow_le_pow_right (by decide) (width_ge T)))
+
+@[simp] theorem code_scan (s : Stage) : (machine T pub).code (scan pcs s.castSucc) =
+ .constant (temporary r) (tagWord w s) (compare pcs s) := by
+ simp [machine,linked,Template.instantiate,scan,instruction,s.isLt,tagWord,Instr.resize,Nat.mod_eq_of_lt (tag_fits T s)]
+
+@[simp] theorem code_scan_end : (machine T pub).code (scan pcs (Fin.last 5)) = .reject := by
+ simp [machine,linked,Template.instantiate,scan,instruction,Instr.resize]
+
+@[simp] theorem code_compare (s : Stage) : (machine T pub).code (compare pcs s) =
+ .jumpEq (phaseValue r) (temporary r) (bodyPC pcs s (T s).entry) (scan pcs s.succ) := by
+ simp [machine,linked,Template.instantiate,compare,instruction,Instr.resize]
+
+@[simp] theorem code_tag (s : Stage) : (machine T pub).code (storeTag pcs s) =
+ .constant (phaseValue r) (tagWord w s) (save pcs 0) := by
+ simp [machine,linked,Template.instantiate,storeTag,instruction,Instr.resize,tagWord,Nat.mod_eq_of_lt (tag_fits T s)]
+
+@[simp] theorem code_save (i : Fin 3) : (machine T pub).code (save pcs i) = saveInstr w i := by
+ simp only [machine,linked,Template.instantiate,save,Equiv.symm_apply_apply,instruction]
+ fin_cases i <;> rfl
+
+@[simp] theorem code_body (s : Stage) (i : Fin (pcs s)) :
+ (machine T pub).code (bodyPC pcs s i) = bodyInstr s (((T s).instantiate w pub).code i) := by
+ have le : (T s).literalWidth ≤ literalWidth T := (Finset.le_sup (f := fun s => (T s).literalWidth) (Finset.mem_univ s)).trans (le_max_right _ _)
+ simp only [machine,linked,Template.instantiate,bodyPC,Equiv.symm_apply_apply,instruction]
+ generalize (T s).code i = op
+ have hc (a : Word (T s).literalWidth) : a.val < 2^literalWidth T :=
+ a.isLt.trans_le (Nat.pow_le_pow_right (by decide) le)
+ cases op <;> cases h : next s <;> simp [bodyInstr,Instr.resize,h,Nat.mod_eq_of_lt (hc _)]
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalPartialFrames.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalPartialFrames.lean
new file mode 100644
index 0000000000..762261a403
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalPartialFrames.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PairSimulationWorkerControl
+import OAI.Computability.VPVNP.LiveDeterministicReachable
+
+/-!
+# Physical terminal frames on partial nondeterministic paths
+
+A successful shared-bit call can return to its worker or finish that phase.
+At a finishing call, the already traversed prefix and the last report form a
+completed fourth block. Its actual final memory initializes the vertex phase.
+A later rejecting vertex has no effect on this classification of the prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+open BurstRAM LiveProgram CompressorRecords
+variable {w : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w} {cap : ℕ}
+
+/-- Every completion from the current fourth-stage state can be prepended
+by the actual successful earlier calls of this same stage. -/
+private def BitPrefix (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap : ℕ) (initial : Memory w)
+ (st : Word w) (m : Memory w) := ∀ {bs ls final},
+ Phase workers pub cap (.resume Stage.sharedBits st) m bs ls final →
+ ∃ bs' ls', Phase workers pub cap (.resume Stage.sharedBits 0) initial bs' ls' final
+
+private theorem BitPrefix.start (m : Memory w) : BitPrefix workers pub cap m 0 m :=
+ fun {_ _ _} h => ⟨_,_,h⟩
+
+private theorem BitPrefix.continue {initial m : Memory w} {st st' : Word w} {b : List Bool} {r : Report w}
+ (earlier : BitPrefix workers pub cap initial st m)
+ (call : execute (source workers Stage.sharedBits pub) (rawFuel pub cap (.resume Stage.sharedBits st))
+ ((source workers Stage.sharedBits pub).start st) m b = some r)
+ (room : (exitReport (header pub) Stage.sharedBits r).events.length < rawFuel pub cap (.resume Stage.sharedBits st))
+ (cont : r.result = some st') :
+ BitPrefix workers pub cap initial st' (after m (report (header pub) (.resume Stage.sharedBits st) r).events) :=
+ fun {_ _ _} h => earlier (Phase.more call room cont h)
+
+private theorem BitPrefix.finish {initial m : Memory w} {st : Word w} {b : List Bool} {r : Report w}
+ (earlier : BitPrefix workers pub cap initial st m)
+ (call : execute (source workers Stage.sharedBits pub) (rawFuel pub cap (.resume Stage.sharedBits st))
+ ((source workers Stage.sharedBits pub).start st) m b = some r)
+ (room : (exitReport (header pub) Stage.sharedBits r).events.length < rawFuel pub cap (.resume Stage.sharedBits st))
+ (halt : r.result = none) :
+ ∃ q : CompletedPhase workers pub cap (.resume Stage.sharedBits 0) initial,
+ q.val.memory = after m (report (header pub) (.resume Stage.sharedBits st) r).events := by
+ obtain ⟨choices,logs,ph⟩ := earlier (Phase.last call room halt)
+ exact ⟨⟨⟨choices,logs,_⟩,ph⟩,rfl⟩
+
+variable {a : ℕ} {initial : Memory w} (bit : WorkerControl workers pub cap Stage.sharedBits a initial)
+variable (vertex : ∀ q : CompletedPhase workers pub cap (.resume Stage.sharedBits 0) initial,
+ WorkerControl workers pub cap Stage.vertices a q.val.memory)
+
+private inductive Progress : Entry w → Memory w → Prop
+ | bits {st mem} : bit.inv st mem → BitPrefix workers pub cap initial st mem →
+ Progress (.resume Stage.sharedBits st) mem
+ | site (q : CompletedPhase workers pub cap (.resume Stage.sharedBits 0) initial) {st mem} :
+ (vertex q).inv st mem → Progress (.resume Stage.vertices st) mem
+
+private theorem follow_return (e : Entry w) (raw : Report w) {x : Word w} (h : raw.result = some x) :
+ e.follow raw = some (.resume e.stage x) := by simp [Entry.follow,target,h]
+
+private theorem next_live {e j : Entry w} {raw : Report w} {m : Memory w} (fit : 32 ≤ 2^w)
+ (h : e.follow raw = some j) :
+ j.Valid (header pub) (after m (report (header pub) e raw).events) := next_valid _ _ _ _ _ fit h
+
+private theorem progress_step {e : Entry w} {m : Memory w} (fit : 32 ≤ 2^w) (hcap : 26 ≤ cap)
+ (h : Progress bit vertex e m) (valid : e.Valid (header pub) m) {bs out}
+ (run : execute (program workers pub) cap ((program workers pub).start e.marker) m bs = some out) :
+ after m out.events a = m a ∧ ∀ st', out.result = some st' →
+ ∃ j : Entry w, j.marker = st' ∧ j.Valid (header pub) (after m out.events) ∧
+ Progress bit vertex j (after m out.events) := by
+ obtain ⟨r,call,room,rfl⟩ := (recover_call workers pub cap e m bs (by omega) hcap valid out).mp run
+ cases h with
+ | @bits st mem inv prefix₀ =>
+ obtain ⟨frame,advance⟩ := bit.advance st m bs r inv call
+ refine ⟨frame,?_⟩
+ intro st' returned
+ cases rr : r.result with
+ | some y =>
+ have h := follow_return (.resume Stage.sharedBits st) r rr
+ rw [report_result,h] at returned
+ obtain rfl := Option.some.inj returned
+ exact ⟨_,rfl,next_live fit h,.bits (advance y rr) (prefix₀.continue call room rr)⟩
+ | none =>
+ have h : (Entry.resume Stage.sharedBits st).follow r = some (.resume Stage.vertices 0) := by
+ simp only [Entry.follow,Entry.stage,target,rr]
+ rfl
+ rw [report_result,h] at returned
+ obtain rfl := Option.some.inj returned
+ obtain ⟨q,hq⟩ := prefix₀.finish call room rr
+ exact ⟨_,rfl,next_live fit h,.site q (hq ▸ (vertex q).ready)⟩
+ | @site q st mem inv =>
+ obtain ⟨frame,advance⟩ := (vertex q).advance st m bs r inv call
+ refine ⟨frame,?_⟩
+ intro st' returned
+ cases rr : r.result with
+ | some y =>
+ have h := follow_return (.resume Stage.vertices st) r rr
+ rw [report_result,h] at returned
+ obtain rfl := Option.some.inj returned
+ exact ⟨_,rfl,next_live fit h,.site q (advance y rr)⟩
+ | none =>
+ have h : (Entry.resume Stage.vertices st).follow r = none := by simp only [Entry.follow,Entry.stage,target,rr]; rfl
+ rw [report_result,h] at returned
+ contradiction
+
+include bit vertex in
+/-- Every successful report, including the terminal accepting exit, on
+every reached physical prefix from the shared-bit entry preserves the word.
+The statement places no requirement on whether a later burst will accept. -/
+theorem shared_vertices_safe (fit : 32 ≤ 2^w) (hcap : 26 ≤ cap)
+ (valid : (Entry.resume Stage.sharedBits (0 : Word w)).Valid (header pub) initial) :
+ ∀ {st mem bs out}, Reached (program workers pub) cap (Entry.resume Stage.sharedBits (0 : Word w)).marker initial st mem →
+ execute (program workers pub) cap ((program workers pub).start st) mem bs = some out →
+ after mem out.events a = mem a := by
+ have inv {st mem} (reach : Reached (program workers pub) cap (Entry.resume Stage.sharedBits (0 : Word w)).marker initial st mem) :
+ ∃ e : Entry w, e.marker = st ∧ e.Valid (header pub) mem ∧ Progress bit vertex e mem := by
+ induction reach with
+ | start => exact ⟨_,rfl,valid,.bits bit.ready (BitPrefix.start _)⟩
+ | more prev run cont ih =>
+ obtain ⟨e,rfl,hvalid,progress⟩ := ih
+ exact (progress_step bit vertex fit hcap progress hvalid run).2 _ cont
+ intro st mem bs out reach run
+ obtain ⟨e,rfl,hvalid,progress⟩ := inv reach
+ exact (progress_step bit vertex fit hcap progress hvalid run).1
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalPhaseBuild.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalPhaseBuild.lean
new file mode 100644
index 0000000000..e492f613e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalPhaseBuild.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalDeterministic
+
+/-!
+# Constructing the five terminal phases from native worker runs
+
+Pair each original report with its genuine entry state and use the read
+footprint to execute the worker on the physical memory. At an ordinary
+return the next entry uses the returned word, including when that word is
+zero. At acceptance the phase ends at the actual memory after the handoff.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM LiveProgram CompressorRecords
+
+variable {w : ℕ}
+
+/-- The worker's report list annotated with the state at each call. -/
+def stageLogs : Entry w → List (Report w) → List (Log w)
+ | _, [] => []
+ | e, raw :: rs => (e,raw) :: stageLogs (.resume e.stage (raw.result.getD 0)) rs
+
+@[simp] theorem stageLogs_raw (e : Entry w) (raws : List (Report w)) :
+ (stageLogs e raws).map Prod.snd = raws := by
+ induction raws generalizing e <;> simp_all [stageLogs]
+
+theorem reports_stageLogs (addr : Word w) (e : Entry w) (raws : List (Report w)) :
+ reports addr (stageLogs e raws) = stageReports addr e raws := by
+ induction raws generalizing e <;> simp_all [stageLogs,reports,stageReports]
+
+theorem stageLogs_eq {workers : Stage → PairTable} {pub : Fin 11 → Word w}
+ {cap e m bs ls final} (h : Phase workers pub cap e m bs ls final) :
+ ls = stageLogs e (ls.map Prod.snd) := by
+ induction h with
+ | last => rfl
+ | more _ _ returned _ ih =>
+ simp only [List.map_cons,stageLogs,returned,Option.getD_some]
+ rw [← ih]
+
+variable (workers : Stage → PairTable) (pub : Fin 11 → Word w)
+
+/-- A closed one-call phase executes on exactly the given physical memory,
+including any reads or writes of the controller cells inside the worker. -/
+theorem single_phase (f cap : ℕ) (e : Entry w) (m : Memory w) (bs : List Bool) (raw : Report w)
+ (room : f+30 ≤ cap)
+ (run : execute (source workers e.stage pub) f ((source workers e.stage pub).start e.state) m bs = some raw)
+ (halt : raw.result = none) :
+ Phase workers pub cap e m [bs] [(e,raw)] (after m (report (header pub) e raw).events) := by
+ have pre := prefix_length_le (header pub) e
+ have len := report_length_le (header pub) e raw
+ change ((e.prefixEvents (header pub)) ++ (exitReport (header pub) e.stage raw).events).length ≤ _ at len
+ rw [List.length_append] at len
+ have small := (execute_spec run).1.length_lt
+ have hf : f ≤ rawFuel pub cap e := by unfold rawFuel; omega
+ exact .last (Nat.add_sub_of_le hf ▸ execute_extend run (rawFuel pub cap e-f))
+ (by unfold rawFuel; omega) halt
+
+theorem initial_phase (f cap : ℕ) (m : Memory w) (raw : Report w) (room : f+30 ≤ cap)
+ (run : execute (source workers Stage.bootstrap pub) f ((source workers Stage.bootstrap pub).start 0) m [] = some raw)
+ (halt : raw.result = none) :
+ Phase workers pub cap .initial m [[]] [(.initial,raw)] (after m (report (header pub) .initial raw).events) :=
+ single_phase workers pub f cap .initial m [] raw room run halt
+
+/-- Build an actual completed phase from the ordinary worker's finite
+execution. The caller may place arbitrary values in both control cells. -/
+theorem closed_phase (f cap : ℕ) (e : Entry w) (src phy : Memory w) (bs : List (List Bool))
+ (raws : List (Report w)) (room : f+30 ≤ cap)
+ (agree : SourceTransport.Agree (workerCell (header pub)) src phy)
+ (reads : SourceTransport.Reads (workerCell (header pub)) (eventLog raws))
+ (run : runSegment (source workers e.stage pub) f (some e.state) src bs = some raws)
+ (halt : endState (some e.state) raws = none) :
+ Phase workers pub cap e phy bs (stageLogs e raws) (after phy (eventLog (stageReports (header pub) e raws))) := by
+ induction bs generalizing e src phy raws with
+ | nil =>
+ have h : raws = [] := by simpa [runSegment] using run.symm
+ simp [h,endState] at halt
+ | cons b bs ih =>
+ cases hc : execute (source workers e.stage pub) f ((source workers e.stage pub).start e.state) src b with
+ | none => simp [runSegment,hc] at run
+ | some raw =>
+ simp only [runSegment,hc,Option.map_eq_some_iff] at run
+ obtain ⟨rs,tail,rfl⟩ := run
+ have readHead : SourceTransport.Reads (workerCell (header pub)) raw.events :=
+ fun a v h => reads a v (List.mem_append_left (eventLog rs) h)
+ have readTail : SourceTransport.Reads (workerCell (header pub)) (eventLog rs) :=
+ fun a v h => reads a v (List.mem_append_right raw.events h)
+ obtain ⟨path,correct,bits⟩ := execute_spec hc
+ have hp : execute _ f _ phy b = some raw :=
+ execute_iff.mpr ⟨path,SourceTransport.correct agree readHead correct,bits⟩
+ have pre := prefix_length_le (header pub) e
+ have length := report_length_le (header pub) e raw
+ change ((e.prefixEvents (header pub)) ++ (exitReport (header pub) e.stage raw).events).length ≤ _ at length
+ rw [List.length_append] at length
+ have small := path.length_lt
+ have fuel : f ≤ rawFuel pub cap e := by unfold rawFuel; omega
+ have fits : (exitReport (header pub) e.stage raw).events.length < rawFuel pub cap e := by unfold rawFuel; omega
+ have full := Nat.add_sub_of_le fuel ▸ execute_extend hp (rawFuel pub cap e-f)
+ change endState raw.result rs = none at halt
+ cases hr : raw.result with
+ | none =>
+ rw [hr] at tail
+ cases bs with
+ | cons b bs => simp [runSegment] at tail
+ | nil =>
+ obtain rfl := Option.some.inj tail
+ simpa [stageLogs,stageReports,eventLog,after] using Phase.last full fits hr
+ | some x =>
+ rw [hr] at tail halt
+ have frame : SourceTransport.Agree (workerCell (header pub)) (after src raw.events)
+ (after phy (report (header pub) e raw).events) := by
+ rw [report_after]
+ simp only [target,hr]
+ intro i hi
+ simpa only [writeMemory,ite_eq_right hi.1,ite_eq_right hi.2] using agree.after raw.events i hi
+ have rest := ih (.resume e.stage x) (after src raw.events) _ rs frame readTail tail halt
+ have appended := Phase.more full fits hr rest
+ simpa only [stageLogs,stageReports,hr,Option.getD_some,eventLog,List.flatMap_cons,after,List.foldl_append]
+ using appended
+
+/-- Implicit-parameter form for constructing a phase in a larger traversal. -/
+theorem Phase.of_source_segment {workers : Stage → PairTable} {pub : Fin 11 → Word w}
+ {f cap : ℕ} {e : Entry w} {src phy : Memory w} {bs : List (List Bool)} {rs : List (Report w)}
+ (room : f+30 ≤ cap) (agree : SourceTransport.Agree (workerCell (header pub)) src phy)
+ (reads : SourceTransport.Reads (workerCell (header pub)) (eventLog rs))
+ (run : runSegment (source workers e.stage pub) f (some e.state) src bs = some rs)
+ (halt : endState (some e.state) rs = none) :
+ Phase workers pub cap e phy bs (stageLogs e rs) (after phy (eventLog (stageReports (header pub) e rs))) :=
+ closed_phase workers pub f cap e src phy bs rs room agree reads run halt
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalProgram.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalProgram.lean
new file mode 100644
index 0000000000..9aec1f2c6d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalProgram.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalFive
+import OAI.Computability.VPVNP.PairTraversalTerminalBootstrap
+import OAI.Computability.VPVNP.PairTerminalPrefixWorker
+import OAI.Computability.VPVNP.PairTraversalControllerCode
+import OAI.Computability.VPVNP.PairSimulationFinalBitWorker
+import OAI.Computability.VPVNP.PairVertexSiteSegments
+
+/-!
+# Terminal program of the compressed pair
+
+The first four stages are the actual metadata, prefix, traversal-row and
+shared-bit tables. The final stage is the numerical image of the finite
+vertex segments, with its ordinal guard and return table. The program has
+the eleven public words of the enclosing compressed pair.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM CompressorRecords TerminalLink
+open LiveProgram (PairTable)
+
+set_option maxRecDepth 4096
+
+private def pack {p r : ℕ} (t : Template p r 11) : PairTable := ⟨p,r,t⟩
+
+variable (F : DescriptorSpace.Shape) (limit : ℕ) (S : VertexImage.Part → VertexImage.Segment)
+
+/-- Static opcode tables in the physical order of execution. -/
+noncomputable def workers : Stage → PairTable :=
+ ![pack (TerminalBootstrap.table F limit), pack TerminalPrefix.Worker.table,
+ pack TraversalController.Native.table, pack FinalBits.Worker.table, pack (VertexImage.template S)]
+
+/-- The fixed terminal program linking metadata, scans, traversal rows and vertex code. -/
+noncomputable def table : PairTable := TerminalLink.table (workers F limit S)
+
+theorem bootstrap_table : workers F limit S Stage.bootstrap = pack (TerminalBootstrap.table F limit) := rfl
+theorem prefix_table : workers F limit S Stage.prefixRows = pack TerminalPrefix.Worker.table := rfl
+theorem row_table : workers F limit S Stage.traversalRows = pack TraversalController.Native.table := rfl
+theorem shared_table : workers F limit S Stage.sharedBits = pack FinalBits.Worker.table := rfl
+theorem vertex_table : workers F limit S Stage.vertices = pack (VertexImage.template S) := rfl
+
+/-- The physical instruction image with the actual two endpoint guards and
+bootstrap/return segments, parametrized only by the five remaining vertex
+code segments installed in the role dispatcher. -/
+noncomputable def siteProgram (geometry rootFields leaf shrink refresh : VertexImage.Segment) : PairTable :=
+ table F limit (VertexImage.segments geometry rootFields leaf shrink refresh)
+
+variable {w : ℕ} (pub : Fin 11 → Word w) (cap : ℕ)
+
+/-- Full forward and reverse semantics, preserving the user's arbitrary cap
+on the native reports and the exact branch strings of the five-stage table. -/
+theorem accepts_iff (m : Memory w) (bs : List (List Bool)) (ok : List (Report w) → Prop)
+ (fit : 32 ≤ 2^w) (hcap : 26 ≤ cap) :
+ (∃ rs, runSegment (((table F limit S).table.instantiate w pub).program) cap (some 0) m bs = some rs ∧
+ endState (some 0) rs = none ∧ ok rs) ↔
+ ∃ ls, Visits (workers F limit S) pub cap (some .initial) m bs ls ∧ finish (some .initial) ls = none ∧
+ ok (reports (header pub) ls) :=
+ actual_iff (workers F limit S) pub cap m bs ok fit hcap
+
+/-- An accepting terminal path contains one completed phase for each of
+the five actual workers, in the table's physical order. -/
+theorem accepts_five (m : Memory w) (bs : List (List Bool)) (ok : List (Report w) → Prop)
+ (fit : 32 ≤ 2^w) (hcap : 26 ≤ cap) :
+ (∃ rs, runSegment (((table F limit S).table.instantiate w pub).program) cap (some 0) m bs = some rs ∧
+ endState (some 0) rs = none ∧ ok rs) ↔
+ ∃ t : FiveTrace (workers F limit S) pub cap m, bs = t.choices ∧ ok (reports (header pub) t.logs) :=
+ TerminalLink.accepts_five (workers F limit S) pub cap m bs ok fit hcap
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalReports.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalReports.lean
new file mode 100644
index 0000000000..f84fa993e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalReports.lean
@@ -0,0 +1,161 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalEnter
+import OAI.Computability.VPVNP.PairSimulationTerminalBody
+import OAI.Computability.VPVNP.LiveStageLinkPaths
+
+/-!
+# Observable terminal calls and their resource charges
+
+A terminal worker is entered either at bootstrap or with a restored state.
+The report keeps each source choice in order, charges at most four additional
+probes and thirty additional events, and determines both header cells used by
+the next call. The final successful exit leaves the source memory result.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+open private probe_append bits_append ticks after_ticks from OAI.Computability.VPVNP.LiveStageLinkPaths
+
+variable {w : ℕ}
+
+/-- A fresh terminal invocation or a resumed stage with its saved state. -/
+inductive Entry (w : ℕ)
+ | initial
+ | resume (stage : Stage) (state : Word w)
+ deriving DecidableEq
+
+/-- Worker selected by this entry. -/
+def Entry.stage : Entry w → Stage
+ | .initial => 0
+ | .resume s _ => s
+
+/-- Persistent word passed to the selected worker. -/
+def Entry.state : Entry w → Word w
+ | .initial => 0
+ | .resume _ x => x
+
+/-- Persistent word received by the enclosing terminal program. -/
+def Entry.marker : Entry w → Word w
+ | .initial => 0
+ | .resume .. => 1
+
+/-- Physical events that enter the selected worker. -/
+def Entry.prefixEvents (addr : Word w) : Entry w → List (Event w)
+ | .initial => initialEvents w
+ | .resume s x => dispatchEvents addr x s
+
+/-- The external stage and state cells encode a resumed entry. -/
+def Entry.Valid (addr : Word w) (m : Memory w) : Entry w → Prop
+ | .initial => True
+ | .resume s x => m addr.val = tagWord w s ∧ m (addr+31).val = x
+
+/-- Number of external reads used to enter this worker. -/
+def Entry.reads : Entry w → ℕ
+ | .initial => 0
+ | .resume .. => 2
+
+/-- Next terminal entry after the worker's report. -/
+def Entry.follow (e : Entry w) (rep : Report w) : Option (Entry w) :=
+ (target e.stage rep.result).map fun (s,v) => .resume s v
+
+/-- Complete physical report, including entry and exit events. -/
+def report (addr : Word w) (e : Entry w) (rep : Report w) :=
+ LiveStageLink.prependLog (e.prefixEvents addr) (exitReport addr e.stage rep)
+
+theorem prefix_length_le (addr : Word w) (e : Entry w) : (e.prefixEvents addr).length ≤ 26 := by
+ cases e with
+ | initial => simp [Entry.prefixEvents]
+ | resume s x => simp [Entry.prefixEvents]; have := s.isLt; omega
+
+private theorem prefix_bits (addr : Word w) (e : Entry w) : choiceBits (e.prefixEvents addr) = [] := by
+ cases e <;> simp [Entry.prefixEvents,initialEvents,dispatchEvents,choiceBits,(ticks (w := w) _).2]
+
+private theorem prefix_probes (addr : Word w) (e : Entry w) : countProbes (e.prefixEvents addr) = e.reads := by
+ cases e <;> simp [Entry.prefixEvents,Entry.reads,initialEvents,dispatchEvents,countProbes,(ticks (w := w) _).1]
+
+private theorem after_append (m : Memory w) (a b : List (Event w)) : after m (a++b) = after (after m a) b :=
+ List.foldl_append
+
+private theorem after_prefix (addr : Word w) (e : Entry w) (m : Memory w) : after m (e.prefixEvents addr) = m := by
+ cases e with
+ | initial => exact after_ticks 13 m
+ | resume s x =>
+ rw [Entry.prefixEvents,dispatchEvents,after_append,after_append,after_ticks]
+ change after m (List.replicate _ .tick) = _
+ exact after_ticks _ m
+
+theorem report_bits (addr : Word w) (e : Entry w) (rep : Report w) :
+ choiceBits (report addr e rep).events = choiceBits rep.events := by
+ simp only [report,LiveStageLink.prependLog,bits_append,prefix_bits,List.nil_append]
+ unfold exitReport
+ cases h : target e.stage rep.result with
+ | none => rfl
+ | some p => cases p; simp [exitEvents,bits_append,choiceBits]
+
+theorem report_probes (addr : Word w) (e : Entry w) (rep : Report w) :
+ (report addr e rep).probes = rep.probes+e.reads+(if (e.follow rep).isSome then 2 else 0) := by
+ simp only [report,Report.probes,LiveStageLink.prependLog,probe_append,prefix_probes]
+ unfold exitReport Entry.follow
+ cases h : target e.stage rep.result with
+ | none => simp [Nat.add_comm]
+ | some p => cases p; simp [exitEvents,probe_append,countProbes]; omega
+
+theorem report_probes_le (addr : Word w) (e : Entry w) (rep : Report w) :
+ (report addr e rep).probes ≤ rep.probes+4 := by
+ rw [report_probes]
+ cases e <;> simp only [Entry.reads] <;> split <;> omega
+
+theorem report_length_le (addr : Word w) (e : Entry w) (rep : Report w) :
+ (report addr e rep).events.length ≤ rep.events.length+30 := by
+ have h := prefix_length_le addr e
+ simp only [report,LiveStageLink.prependLog,List.length_append]
+ unfold exitReport
+ cases v : target e.stage rep.result with
+ | none => change (e.prefixEvents addr).length + rep.events.length ≤ _; omega
+ | some p => cases p; simp [exitEvents]; omega
+
+theorem report_result (addr : Word w) (e : Entry w) (rep : Report w) :
+ (report addr e rep).result = (e.follow rep).map Entry.marker := by
+ cases hr : rep.result <;> cases hn : next e.stage <;>
+ simp [report,LiveStageLink.prependLog,exitReport,Entry.follow,target,Entry.marker,hr,hn]
+
+theorem report_after (addr : Word w) (e : Entry w) (rep : Report w) (m : Memory w) :
+ after m (report addr e rep).events =
+ match target e.stage rep.result with
+ | none => after m rep.events
+ | some (s,v) => writeMemory (writeMemory (after m rep.events) addr (tagWord w s)) (addr+31) v := by
+ rw [report,LiveStageLink.prependLog,after_append,after_prefix]
+ unfold exitReport
+ cases ht : target e.stage rep.result with
+ | none => rfl
+ | some p => cases p; rw [after_append]; rfl
+
+theorem next_valid (addr : Word w) (e e' : Entry w) (rep : Report w) (m : Memory w)
+ (fit : 32 ≤ 2^w) (step : e.follow rep = some e') :
+ e'.Valid addr (after m (report addr e rep).events) := by
+ have ne : addr.val ≠ (addr+31).val := by
+ intro eq
+ have he : addr+31 = addr+0 := (Fin.ext eq.symm).trans (add_zero _).symm
+ have hz := congrArg Fin.val (add_left_cancel he : (31 : Word w) = 0)
+ change 31 % 2^w = 0 at hz
+ rw [Nat.mod_eq_of_lt (by omega)] at hz
+ contradiction
+ unfold Entry.follow at step
+ cases h : target e.stage rep.result with
+ | none => simp [h] at step
+ | some p =>
+ obtain ⟨s,v⟩ := p
+ have he : e' = .resume s v := by simpa [h] using step.symm
+ subst e'
+ simp [Entry.Valid,report_after,h,writeMemory,ne]
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGather.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGather.lean
new file mode 100644
index 0000000000..9e40184bad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGather.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherBoot
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherHeader
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherScan
+
+/-! # Loading the root packet before the native DFS
+
+One fixed segment reads the actual outgoing and incoming incidence directories,
+then gathers the shared payloads into the site's private descriptor. The
+destination memory formula gives the value at every private word, including
+the DFS stack and the histogram outside the packet.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalRootGather
+
+open BurstRAM PrivateRAM CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+variable {w p r : ℕ} {M : Machine w p r 11} {pc : PC → Fin p} {reg : Reg ↪ Fin r} {done : Fin p}
+
+/-- Execute the complete finite gather. Both passes use the same external
+memory and branch suffix, and each writes exactly its packed private words. -/
+theorem run_reads (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (fit : L.Fits m)
+ (c : Config w p r) (hc : c.pc=pc (.boot 0)) (saved : Saved L reg c)
+ (hn : M.publicData 6=(L.n : Word w))
+ (stride : c.privateMem (c.privateMem (L.n : Word w)+7)=(L.stride : Word w))
+ (P : ℕ → Prop) (readable : L.Readable m P) :
+ ∃ out es, out.pc=done ∧ Frame reg c out ∧
+ out.privateMem=Layout.placed L.dest (L.packet m) c.privateMem ∧
+ Cost es (15+21*L.degree+5*(L.packet m).length) (5*L.degree+(L.packet m).length) ∧
+ Reads P es ∧ Prefix M m c es out := by
+ have headers : HeadersReads P L M m pc reg := by
+ intro b j hj cur hpc h hs
+ obtain ⟨out,es,ho,hf,hm,hsrc,hend,hr,hlen,hprobes,hafter,hchoices,hreads,hex⟩ :=
+ header_run_reads hl L m fit b j hj cur hpc h hs P readable
+ exact ⟨out,es,ho,hf,hm,hsrc,hend,hr,⟨hlen,hprobes,hafter,hchoices⟩,hreads,hex⟩
+ let xs := (L.fields m false).flatten
+ let ys := (L.fields m true).flatten
+ have len : (L.packet m).length=xs.length+ys.length := List.length_append
+ have room := fit.destEnd
+ rw [len] at room
+ obtain ⟨boot,hboot,fboot,pboot,hd,ho,hi,hstop,hfirst,rboot⟩ := boot_run hl L m fit c hc saved hn stride
+ obtain ⟨left,levents,hreset,fleft,pleft,leftCur,cleft,leftReads,rleft⟩ :=
+ scan_run_reads hl L m fit P readable headers false L.degree 0 L.dest
+ (Nat.zero_add _) (by rw [suffix_full]; change L.dest+xs.length < _; omega) boot hboot
+ (saved.transport fboot) ⟨hd,ho,hi,hstop,hfirst⟩
+ rw [suffix_full] at pleft leftCur cleft
+ obtain ⟨mid,hmid,fmid,pmid,midCur,rmid⟩ := reset_run hl L m left hreset L.degree (L.dest+xs.length) leftCur
+ obtain ⟨out,revents,hdone,fright,pright,_,cright,rightReads,rright⟩ :=
+ scan_run_reads hl L m fit P readable headers true L.degree 0 (L.dest+xs.length) (Nat.zero_add _)
+ (by rw [suffix_full]; change L.dest+xs.length+ys.length < _; omega)
+ mid hmid (saved.transport ((fboot.trans fleft).trans fmid)) midCur
+ rw [suffix_full] at pright cright
+ refine ⟨out,_,hdone,((fboot.trans fleft).trans fmid).trans fright,?_,?_,
+ (((Reads.replicate_tick P 12).append leftReads).append (Reads.replicate_tick P 1)).append rightReads,
+ ((rboot.trans rleft).trans rmid).trans rright⟩
+ · rw [pright,pmid,pleft,pboot,Layout.placed_append]; rfl
+ · have cost := (((Cost.replicate_tick (w:=w) 12).append cleft).append Cost.tick).append cright
+ rw [len]
+ convert cost using 1 <;> first | rfl | (simp only [xs,ys,Bool.false_eq_true,↓reduceIte,Nat.mul_add]; omega)
+
+theorem run (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (fit : L.Fits m)
+ (c : Config w p r) (hc : c.pc=pc (.boot 0)) (saved : Saved L reg c)
+ (hn : M.publicData 6=(L.n : Word w))
+ (stride : c.privateMem (c.privateMem (L.n : Word w)+7)=(L.stride : Word w)) :
+ ∃ out es, out.pc=done ∧ Frame reg c out ∧
+ out.privateMem=Layout.placed L.dest (L.packet m) c.privateMem ∧
+ Cost es (15+21*L.degree+5*(L.packet m).length) (5*L.degree+(L.packet m).length) ∧ Prefix M m c es out := by
+ obtain ⟨out, es, hp, hf, hm, cost, _, exec⟩ :=
+ run_reads hl L m fit c hc saved hn stride (fun _ ↦ True) (L.readable_true m)
+ exact ⟨out, es, hp, hf, hm, cost, exec⟩
+
+end PairSimulation.TerminalRootGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherBoot.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherBoot.lean
new file mode 100644
index 0000000000..3d54efdec7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherBoot.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherCode
+
+/-!
+# Native boot of the terminal root gather
+
+Twelve local instructions fetch the private descriptor stride, locate the
+root's argument buffer and initialize the endpoints of the vertex's slot
+interval. Both arithmetic products are ordinary machine-word products.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalRootGather
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+variable {w p r : ℕ} {M : Machine w p r 11} {pc : PC → Fin p} {reg : Reg ↪ Fin r} {done : Fin p}
+
+theorem boot_run (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (fit : L.Fits m)
+ (c : Config w p r) (hc : c.pc = pc (.boot 0)) (h : Saved L reg c)
+ (hn : M.publicData 6 = (L.n : Word w))
+ (stride : c.privateMem (c.privateMem (L.n : Word w)+7) = (L.stride : Word w)) :
+ ∃ out, out.pc = pc (.scan false) ∧ Frame reg c out ∧ out.privateMem = c.privateMem ∧
+ out.reg (reg (tmp 2)) = (L.dest : Word w) ∧ out.reg (reg (tmp 3)) = 1 ∧
+ out.reg (reg (tmp 5)) = (L.index 0 : Word w) ∧ out.reg (reg (tmp 6)) = (L.index L.degree : Word w) ∧
+ out.reg (reg (tmp 7)) = (L.index 0 : Word w) ∧ Prefix M m c (List.replicate 12 .tick) out := by
+ let labels := blockPC (pc ∘ PC.boot) (pc (.scan false))
+ let v := TerminalSiteStart.eval (M.publicData ∘ id) c.persistent m bootLines (c.reg ∘ reg) c.privateMem
+ obtain ⟨out,hpc,hstate,hregs,hpriv,hframe,run⟩ :=
+ TerminalSiteStart.linear_run_framed M reg id m bootLines labels (linked_boot hl) c (by exact hc)
+ have get (j : Reg) : out.reg (reg j) = v.2.1 j := congrFun hregs j
+ have hdiv : BinaryOp.div.eval (c.reg (reg (save VertexImage.slots))) (c.reg (reg (save VertexImage.finalSites))) =
+ (L.degree : Word w) := by
+ rw [h.slots,h.sites]
+ change Fin.ofNat (2^w) ((L.slots % (2^w))/(L.sites % (2^w))) = _
+ rw [Nat.mod_eq_of_lt fit.slots,Nat.mod_eq_of_lt fit.sites]
+ rfl
+ have start : v.2.1 (tmp 7) = (L.index 0 : Word w) := by
+ change c.reg (reg (save VertexImage.ordinal)) * BinaryOp.div.eval (c.reg (reg (save VertexImage.slots))) (c.reg (reg (save VertexImage.finalSites))) = _
+ rw [h.ordinal,hdiv]; simp [Layout.index]
+ have hp : labels (Fin.last bootLines.length) = pc (.scan false) := by simp [labels,blockPC]
+ refine ⟨out,hpc.trans hp,⟨hstate,?_⟩,hpriv,?_,?_,?_,?_,?_,run⟩
+ · intro j hj
+ by_cases inRange : ∃ i, reg i = j
+ · obtain ⟨i,rfl⟩ := inRange
+ cases i with
+ | inl i => exact (hj i rfl).elim
+ | inr i => exact get (.inr i)
+ · exact hframe j (fun i hi => inRange ⟨i,hi⟩)
+ · rw [get]
+ change M.publicData 6 + c.privateMem (c.privateMem (M.publicData 6)+7)*c.reg (reg (save VertexImage.root)) = _
+ rw [hn,stride,h.root]
+ simp [Layout.dest,mul_comm]
+ · exact get _
+ · exact (get _).trans start
+ · rw [get]
+ change v.2.1 (tmp 7) + BinaryOp.div.eval (c.reg (reg (save VertexImage.slots))) (c.reg (reg (save VertexImage.finalSites))) = _
+ rw [start,hdiv]; simp [Layout.index]
+ · exact (get _).trans start
+
+end PairSimulation.TerminalRootGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherCode.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherCode.lean
new file mode 100644
index 0000000000..92480b7657
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherCode.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherLayout
+import OAI.Computability.VPVNP.PairSimulationTerminalSiteLinear
+import OAI.Computability.VPVNP.PairVertexImage
+
+/-! # Relocatable terminal endpoint gather
+
+Each incoming slot first reads its matching outgoing slot. Both passes then
+read the width and exclusive prefix of that outgoing slot and copy the
+corresponding shared wire words to the site's private argument buffer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalRootGather
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+/-- Symbolic register names shared with the site bootstrap. The gather maps the first nine
+names to its own temporaries, the next eleven to saved fields and the final three to DFS
+registers. -/
+abbrev Reg := TerminalSiteStart.Reg
+/-- Straight-line instruction format used for the gather's initialization and per-slot
+directory reads. -/
+abbrev Line := TerminalSiteStart.Line
+/-- Names one of the nine gather temporaries used for wire addresses, the private destination,
+and slot loop bounds. -/
+abbrev tmp := TerminalSiteStart.dfs
+/-- Names a bootstrap register from which the gather reads the site ordinal, root, slot counts
+or endpoint array heads. -/
+abbrev save := TerminalSiteStart.saved
+
+/-- Twelve instructions that load the private argument stride, compute the root's destination
+address and set the first slot, exclusive limit and unit increment for the outgoing scan. -/
+def bootLines : List Line :=
+ [.pub (tmp 8) 6, .load (tmp 0) (tmp 8), .lit (tmp 3) 7,
+ .bin .add (tmp 0) (tmp 0) (tmp 3), .load (tmp 0) (tmp 0),
+ .bin .mul (tmp 0) (tmp 0) (save VertexImage.root), .bin .add (tmp 2) (tmp 8) (tmp 0),
+ .bin .div (tmp 0) (save VertexImage.slots) (save VertexImage.finalSites),
+ .bin .mul (tmp 7) (save VertexImage.ordinal) (tmp 0), .bin .add (tmp 6) (tmp 7) (tmp 0),
+ .copy (tmp 5) (tmp 7), .lit (tmp 3) 1]
+
+instance : NeZero bootLines.length := ⟨by decide⟩
+
+/-- Reads a slot's width and exclusive prefix to compute its source interval in the wire bank.
+The incoming pass first reads the matched outgoing slot from the inverse incidence table. -/
+def headerLines (b : Bool) : List Line :=
+ (if b then [.bin .add (tmp 4) (save VertexImage.incoming) (tmp 5), .read (tmp 0) (tmp 4)]
+ else [.copy (tmp 0) (tmp 5)]) ++
+ [.bin .add (tmp 4) (save VertexImage.widths) (tmp 0), .read (tmp 1) (tmp 4),
+ .bin .add (tmp 4) (save VertexImage.prefixBase) (tmp 0), .read (tmp 0) (tmp 4),
+ .bin .add (tmp 0) (save VertexImage.wires) (tmp 0), .bin .add (tmp 1) (tmp 1) (tmp 0)]
+
+/-- Labels for gather initialization and the two slot scans. Each pass has a loop test,
+directory reads, a wire-copy loop and a slot increment, with a cursor reset between passes. -/
+inductive PC where
+ | boot (i : Fin bootLines.length)
+ | scan (b : Bool)
+ | header (b : Bool) (i : Fin (headerLines b).length)
+ | bits (b : Bool) (i : Fin 5)
+ | advance (b : Bool)
+ | reset
+ deriving DecidableEq, Fintype
+
+/-- Index of the first directory instruction for a slot in the selected scan direction. -/
+def firstHeader (b : Bool) : Fin (headerLines b).length := ⟨0, by cases b <;> decide⟩
+
+/-- Extends the labels of a straight-line gather block by one position holding its
+continuation, so the last instruction can target the next phase. -/
+def blockPC {n p : ℕ} (pc : Fin n → Fin p) (done : Fin p) : Fin (n+1) → Fin p := Fin.lastCases done pc
+
+/-- Emits the gather instruction at a symbolic label. The outgoing pass resets the slot cursor
+for the incoming pass, which transfers to the supplied continuation after its last slot. -/
+def rows {w p r : ℕ} (pc : PC → Fin p) (reg : Reg → Fin r) (br : Fin 5 ↪ Fin r) (done : Fin p) :
+ PC → Instr w p r 11
+ | .boot i => (bootLines[i]).emit reg id (blockPC (pc ∘ PC.boot) (pc (.scan false)) i.succ)
+ | .scan b => .jumpEq (reg (tmp 5)) (reg (tmp 6))
+ (if b then done else pc .reset) (pc (.header b (firstHeader b)))
+ | .header b i => ((headerLines b)[i]).emit reg id (blockPC (pc ∘ PC.header b) (pc (.bits b 0)) i.succ)
+ | .bits b i => EndpointBits.instruction (pc ∘ PC.bits b) br (pc (.advance b)) i
+ | .advance b => .binary .add (reg (tmp 5)) (reg (tmp 5)) (reg (tmp 3)) (pc (.scan b))
+ | .reset => .copy (reg (tmp 5)) (reg (tmp 7)) (pc (.scan true))
+
+variable {w p r : ℕ}
+
+/-- Assigns the first five gather temporaries to the endpoint copy loop as source cursor,
+exclusive end, destination cursor, unit increment and transfer word. -/
+def bitRegs (reg : Reg ↪ Fin r) : Fin 5 ↪ Fin r := (Fin.castAddEmb 4).trans (Function.Embedding.inl.trans reg)
+
+/-- Requires the machine to contain every gather instruction at its assigned label, with the
+specified register bank and final continuation. -/
+def Linked (M : Machine w p r 11) (pc : PC → Fin p) (reg : Reg ↪ Fin r) (done : Fin p) :=
+ ∀ i, M.code (pc i) = rows pc reg (bitRegs reg) done i
+
+/-- Resolves gather register names into the segment's nine private temporaries, the eleven
+saved bootstrap registers and the first three host DFS registers. -/
+def regMap (dfs : Fin 9 ↪ Fin r) (saved : Fin 11 ↪ Fin r) (work : Fin 9 ↪ Fin r) : Reg → Fin r :=
+ Sum.elim work (Sum.elim saved (fun i => dfs (Fin.castAdd 6 i)))
+
+/-- Finite vertex-image segment for gathering the terminal root's endpoint packet. It enters at
+initialization and allocates nine private temporaries for both scan directions. -/
+noncomputable def segment : VertexImage.Segment where
+ count := Fintype.card PC
+ privateRegs := 9
+ entry := Fintype.equivFin PC (.boot 0)
+ row pc dfs saved work done i :=
+ rows (pc ∘ Fintype.equivFin PC) (regMap dfs saved work) ((Fin.castAddEmb 4).trans work) done
+ ((Fintype.equivFin PC).symm i)
+
+theorem resize_rows (pc : PC → Fin p) (reg : Reg → Fin r) (br : Fin 5 ↪ Fin r) (done : Fin p) (i : PC) :
+ (rows (w := 5) pc reg br done i).resize w = rows pc reg br done i := by
+ cases i with
+ | boot i | header _ i => exact TerminalSiteStart.Line.resize_emit ..
+ | bits b i => fin_cases i <;> rfl
+ | _ => rfl
+
+/-- Saved fields read by this segment. The private geometry pointer and
+stride are initialized by the previous stage. -/
+structure Saved (L : Layout) (reg : Reg ↪ Fin r) (c : Config w p r) : Prop where
+ ordinal : c.reg (reg (save VertexImage.ordinal)) = (L.vertex : Word w)
+ root : c.reg (reg (save VertexImage.root)) = (L.root : Word w)
+ sites : c.reg (reg (save VertexImage.finalSites)) = (L.sites : Word w)
+ slots : c.reg (reg (save VertexImage.slots)) = (L.slots : Word w)
+ widths : c.reg (reg (save VertexImage.widths)) = (L.widthHead : Word w)
+ incoming : c.reg (reg (save VertexImage.incoming)) = (L.incomingHead : Word w)
+ prefixBase : c.reg (reg (save VertexImage.prefixBase)) = (L.prefixHead : Word w)
+ wires : c.reg (reg (save VertexImage.wires)) = (L.wires : Word w)
+
+/-- Register frame for a gather run. The two configurations agree on the persistent word and on
+every register outside the nine gather temporaries. -/
+def Frame (reg : Reg ↪ Fin r) (c out : Config w p r) :=
+ out.persistent = c.persistent ∧ ∀ j, (∀ i, reg (tmp i) ≠ j) → out.reg j = c.reg j
+
+/-- For any remaining fuel and choice bits, execution from the initial configuration produces
+the given event prefix followed by the continuation from the final configuration on the
+same external memory. -/
+def Prefix (M : Machine w p r 11) (m : Memory w) (c : Config w p r) (es : List (Event w)) (out : Config w p r) :=
+ ∀ fuel bs, execute M.program (fuel+es.length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep => ⟨es ++ rep.events,rep.result⟩)
+
+theorem linked_boot {M : Machine w p r 11} {pc : PC → Fin p} {reg : Reg ↪ Fin r} {done : Fin p}
+ (hl : Linked M pc reg done) (i : Fin bootLines.length) :
+ let labels := blockPC (pc ∘ PC.boot) (pc (.scan false))
+ M.code (labels i.castSucc) = (bootLines[i]).emit reg id (labels i.succ) := by
+ simpa only [rows, blockPC, Fin.lastCases_castSucc,Function.comp_apply] using hl (.boot i)
+
+theorem linked_header {M : Machine w p r 11} {pc : PC → Fin p} {reg : Reg ↪ Fin r} {done : Fin p}
+ (hl : Linked M pc reg done) (b : Bool) (i : Fin (headerLines b).length) :
+ let labels := blockPC (pc ∘ PC.header b) (pc (.bits b 0))
+ M.code (labels i.castSucc) = ((headerLines b)[i]).emit reg id (labels i.succ) := by
+ simpa only [rows, blockPC, Fin.lastCases_castSucc,Function.comp_apply] using hl (.header b i)
+
+end PairSimulation.TerminalRootGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherHeader.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherHeader.lean
new file mode 100644
index 0000000000..b1ba2c9411
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherHeader.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherCode
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherReads
+
+/-! # Native endpoint headers for outgoing and incoming terminal slots -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalRootGather
+
+open BurstRAM PrivateRAM CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+variable {w p r : ℕ}
+
+private theorem address_val {x y : ℕ} (h : x+y < 2^w) :
+ ((x : Word w)+(y : Word w)).val = x+y := by
+ rw [← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt h]
+
+/-- The header selects the edge, fetches its width and exclusive prefix, and
+leaves the source interval ready for the bit loop. Only the incoming pass
+needs an inverse incidence read. -/
+theorem header_run_reads {M : Machine w p r 11} {pc : PC → Fin p} {reg : Reg ↪ Fin r} {done : Fin p}
+ (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (fit : L.Fits m)
+ (b : Bool) (j : ℕ) (hj : j < L.degree) (c : Config w p r)
+ (hc : c.pc = pc (.header b (firstHeader b))) (h : Saved L reg c)
+ (hslot : c.reg (reg (tmp 5)) = (L.index j : Word w)) (P : ℕ → Prop) (readable : L.Readable m P) :
+ ∃ out es, out.pc = pc (.bits b 0) ∧ Frame reg c out ∧ out.privateMem = c.privateMem ∧
+ out.reg (reg (tmp 0)) = (L.start m b j : Word w) ∧
+ out.reg (reg (tmp 1)) = ((L.start m b j + L.width m b j : ℕ) : Word w) ∧
+ (∀ i : Fin 9, i ≠ 0 → i ≠ 1 → i ≠ 4 → out.reg (reg (tmp i)) = c.reg (reg (tmp i))) ∧
+ es.length = (if b then 8 else 7) ∧ countProbes es = (if b then 3 else 2) ∧
+ (∀ m', after m' es = m') ∧ choiceBits es = [] ∧ Reads P es ∧ Prefix M m c es out := by
+ let bank := c.reg ∘ reg
+ let v := TerminalSiteStart.eval (M.publicData ∘ id) c.persistent m (headerLines b) bank c.privateMem
+ let labels := blockPC (pc ∘ PC.header b) (pc (.bits b 0))
+ have entry : c.pc = labels 0 := by cases b <;> exact hc
+ obtain ⟨out, hp, hper, hregs, hpriv, hframe, hrun⟩ :=
+ TerminalSiteStart.linear_run_framed M reg id m (headerLines b) labels (linked_header hl b) c entry
+ have bank_eq (i : Reg) : out.reg (reg i) = v.2.1 i := congrFun hregs i
+ have kept (i : Reg) (h0 : i ≠ tmp 0) (h1 : i ≠ tmp 1) (h4 : i ≠ tmp 4) :
+ out.reg (reg i) = c.reg (reg i) := by
+ rw [bank_eq]
+ cases b <;> simp [v, bank, headerLines, TerminalSiteStart.eval, h0, h1, h4]
+ let edge : Word w := if b then m (bank (save VertexImage.incoming) + bank (tmp 5)).val else bank (tmp 5)
+ let start := bank (save VertexImage.wires) + m (bank (save VertexImage.prefixBase) + edge).val
+ let width := m (bank (save VertexImage.widths) + edge).val
+ have edge_eq : edge = (L.edge m b j : Word w) := by
+ cases b with
+ | false => exact hslot
+ | true =>
+ change m (c.reg (reg (save VertexImage.incoming)) + c.reg (reg (tmp 5))).val = _
+ rw [h.incoming, hslot, address_val (fit.inverseAddr j hj)]
+ exact (Fin.ofNat_val_eq_self _).symm
+ have start_eq : start = (L.start m b j : Word w) := by
+ change c.reg (reg (save VertexImage.wires)) + m (c.reg (reg (save VertexImage.prefixBase)) + edge).val = _
+ rw [h.wires, h.prefixBase, edge_eq, address_val (fit.prefixAddr b j hj), Layout.start, Nat.cast_add]
+ exact congrArg _ (Fin.ofNat_val_eq_self _).symm
+ have width_eq : width = (L.width m b j : Word w) := by
+ change m (c.reg (reg (save VertexImage.widths)) + edge).val = _
+ rw [h.widths, edge_eq, address_val (fit.widthAddr b j hj)]
+ exact (Fin.ofNat_val_eq_self _).symm
+ have hstart : v.2.1 (tmp 0) = start := by cases b <;> rfl
+ have hend : v.2.1 (tmp 1) = width+start := by cases b <;> rfl
+ refine ⟨out, v.1, ?_, ⟨hper,?_⟩, ?_, (bank_eq _).trans (hstart.trans start_eq), ?_, ?_, ?_, ?_, ?_, ?_, ?_, hrun⟩
+ · simpa only [labels, blockPC, Fin.lastCases_last] using hp
+ · intro a ha
+ by_cases hin : a ∈ Set.range reg
+ · obtain ⟨i,rfl⟩ := hin
+ apply kept i <;> intro he <;> subst i <;> exact ha _ rfl
+ · exact hframe a (fun i eqn => hin ⟨i,eqn⟩)
+ · cases b <;> exact hpriv
+ · rw [bank_eq, hend, width_eq, start_eq, Nat.cast_add, add_comm]
+ · intro i h0 h1 h4
+ apply kept <;> simpa only [tmp, TerminalSiteStart.dfs, ne_eq, Sum.inl.injEq]
+ · cases b <;> rfl
+ · cases b <;> rfl
+ · intro m'; cases b <;> rfl
+ · cases b <;> rfl
+ · let wa := bank (save VertexImage.widths) + edge
+ let pa := bank (save VertexImage.prefixBase) + edge
+ let ia := bank (save VertexImage.incoming) + bank (tmp 5)
+ have hw : P wa.val := by
+ change P (c.reg (reg (save VertexImage.widths)) + edge).val
+ rw [h.widths, edge_eq, address_val (fit.widthAddr b j hj)]
+ exact readable.widths b j hj
+ have hp' : P pa.val := by
+ change P (c.reg (reg (save VertexImage.prefixBase)) + edge).val
+ rw [h.prefixBase, edge_eq, address_val (fit.prefixAddr b j hj)]
+ exact readable.prefixes b j hj
+ have hi : P ia.val := by
+ change P (c.reg (reg (save VertexImage.incoming)) + c.reg (reg (tmp 5))).val
+ rw [h.incoming, hslot, address_val (fit.inverseAddr j hj)]
+ exact readable.incoming j hj
+ intro a value member
+ cases b with
+ | false =>
+ change Event.read a value ∈ [.tick, .tick, .read wa (m wa.val), .tick, .read pa (m pa.val),
+ .tick, .tick] at member
+ simp only [List.mem_cons, List.not_mem_nil, reduceCtorEq, Event.read.injEq, false_or, or_false] at member
+ rcases member with ⟨rfl,_⟩ | ⟨rfl,_⟩
+ · exact hw
+ · exact hp'
+ | true =>
+ change Event.read a value ∈ [.tick, .read ia (m ia.val), .tick, .read wa (m wa.val),
+ .tick, .read pa (m pa.val), .tick, .tick] at member
+ simp only [List.mem_cons, List.not_mem_nil, reduceCtorEq, Event.read.injEq, false_or, or_false] at member
+ rcases member with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩
+ · exact hi
+ · exact hw
+ · exact hp'
+
+theorem header_run {M : Machine w p r 11} {pc : PC → Fin p} {reg : Reg ↪ Fin r} {done : Fin p}
+ (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (fit : L.Fits m)
+ (b : Bool) (j : ℕ) (hj : j < L.degree) (c : Config w p r)
+ (hc : c.pc = pc (.header b (firstHeader b))) (h : Saved L reg c)
+ (hslot : c.reg (reg (tmp 5)) = (L.index j : Word w)) :
+ ∃ out es, out.pc = pc (.bits b 0) ∧ Frame reg c out ∧ out.privateMem = c.privateMem ∧
+ out.reg (reg (tmp 0)) = (L.start m b j : Word w) ∧
+ out.reg (reg (tmp 1)) = ((L.start m b j + L.width m b j : ℕ) : Word w) ∧
+ (∀ i : Fin 9, i ≠ 0 → i ≠ 1 → i ≠ 4 → out.reg (reg (tmp i)) = c.reg (reg (tmp i))) ∧
+ es.length = (if b then 8 else 7) ∧ countProbes es = (if b then 3 else 2) ∧
+ (∀ m', after m' es = m') ∧ choiceBits es = [] ∧ Prefix M m c es out := by
+ obtain ⟨out, es, hp, hf, hm, hs, he, hr, ht, hq, ha, hb, _, run⟩ :=
+ header_run_reads hl L m fit b j hj c hc h hslot (fun _ ↦ True) (L.readable_true m)
+ exact ⟨out, es, hp, hf, hm, hs, he, hr, ht, hq, ha, hb, run⟩
+
+end PairSimulation.TerminalRootGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherImage.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherImage.lean
new file mode 100644
index 0000000000..cd9a1cb545
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherImage.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGather
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherLinked
+
+/-! # Executing the installed root gather in the final-vertex call -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalRootGather
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+variable {S : VertexImage.Part → VertexImage.Segment} {w p r : ℕ}
+
+/-- The installed gather reads only its three directory columns and the shared
+bits of the selected site's outgoing and incoming fields. -/
+theorem image_run_reads (A : VertexImage.Placement S p r) (hfield : S .rootFields = segment)
+ (M : Machine w p r 11) (contains : VertexImage.Contains A M) (L : Layout) (mem : Memory w)
+ (fit : L.Fits mem) (c : Config w p r) (hc : c.pc = A.entry .rootFields)
+ (saved : Saved L (imageRegs A hfield) c) (hn : M.publicData 6 = (L.n : Word w))
+ (stride : c.privateMem (c.privateMem (L.n : Word w)+7) = (L.stride : Word w))
+ (P : ℕ → Prop) (readable : L.Readable mem P) :
+ ∃ out es, out.pc=A.dfsPC 0 ∧ out.persistent=c.persistent ∧
+ (∀ i, out.reg (A.dfs i) = c.reg (A.dfs i)) ∧
+ (∀ i, out.reg (A.saved i) = c.reg (A.saved i)) ∧
+ Frame (imageRegs A hfield) c out ∧
+ out.privateMem = Layout.placed L.dest (L.packet mem) c.privateMem ∧
+ Cost es (15+21*L.degree+5*(L.packet mem).length) (5*L.degree+(L.packet mem).length) ∧
+ CompressorRecords.SourceTransport.Reads P es ∧ Prefix M mem c es out := by
+ obtain ⟨out,es,hdone,frame,priv,cost,reads,exec⟩ := run_reads (image_linked A hfield contains) L mem fit c
+ (hc.trans (image_entry A hfield).symm) saved hn stride P readable
+ refine ⟨out,es,hdone,frame.1,fun i => frame.2 _ (fun j => ?_),fun i => frame.2 _ (fun j => ?_),
+ frame,priv,cost,reads,exec⟩
+ · apply A.reg.injective.ne; exact Sum.inr_ne_inl
+ · apply A.reg.injective.ne
+ intro h
+ exact Sum.inr_ne_inl (Sum.inr.inj h)
+
+theorem image_run (A : VertexImage.Placement S p r) (hfield : S .rootFields = segment)
+ (M : Machine w p r 11) (contains : VertexImage.Contains A M) (L : Layout) (mem : Memory w)
+ (fit : L.Fits mem) (c : Config w p r) (hc : c.pc = A.entry .rootFields)
+ (saved : Saved L (imageRegs A hfield) c) (hn : M.publicData 6 = (L.n : Word w))
+ (stride : c.privateMem (c.privateMem (L.n : Word w)+7) = (L.stride : Word w)) :
+ ∃ out es, out.pc=A.dfsPC 0 ∧ out.persistent=c.persistent ∧
+ (∀ i, out.reg (A.dfs i) = c.reg (A.dfs i)) ∧
+ (∀ i, out.reg (A.saved i) = c.reg (A.saved i)) ∧
+ Frame (imageRegs A hfield) c out ∧
+ out.privateMem = Layout.placed L.dest (L.packet mem) c.privateMem ∧
+ Cost es (15+21*L.degree+5*(L.packet mem).length) (5*L.degree+(L.packet mem).length) ∧
+ Prefix M mem c es out := by
+ obtain ⟨out,es,pc,persistent,dfs,savedRegs,frame,priv,cost,_,exec⟩ :=
+ image_run_reads A hfield M contains L mem fit c hc saved hn stride _ (L.readable_true mem)
+ exact ⟨out,es,pc,persistent,dfs,savedRegs,frame,priv,cost,exec⟩
+
+end PairSimulation.TerminalRootGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherLayout.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherLayout.lean
new file mode 100644
index 0000000000..d5521710a4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherLayout.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.PairSimulationEndpointBits
+import OAI.Computability.VPVNP.PairNodeArguments
+
+/-! # Addresses and words gathered by a terminal vertex
+
+The final slot count includes all sites. Its quotient by the number of sites
+is the actual number of slots per site. Outgoing slots address the width and
+prefix tables directly. Each incoming slot first selects its matched outgoing
+slot from the inverse incidence table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalRootGather
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+/-- Addresses and sizes used to gather one final site's incident wire words from external
+memory into the private argument block for its DFS root. -/
+structure Layout where
+ /-- Ordinal of the selected final site, used to locate its contiguous interval of incidence
+ slots. -/
+ vertex : ℕ
+ /-- Number of final sites sharing the slot table. Dividing the total slot count by this value
+ gives the scan length for one site. -/
+ sites : ℕ
+ /-- Total number of slots across all final sites in one direction of the incidence table. -/
+ slots : ℕ
+ /-- External base of the table giving the number of wire words for each outgoing slot. -/
+ widthHead : ℕ
+ /-- External base of the inverse incidence table mapping each incoming slot to the outgoing
+ slot of its wire. -/
+ incomingHead : ℕ
+ /-- External base of the exclusive width-prefix table. Its entry for an outgoing slot is that
+ wire's offset from the wire bank base. -/
+ prefixHead : ℕ
+ /-- External base address of the packed wire words addressed by the slot prefix table. -/
+ wires : ℕ
+ /-- Private argument bank base supplied in public word six. The gather adds the root's stride
+ offset to obtain its packet destination. -/
+ n : ℕ
+ /-- Descriptor address of the selected site's DFS root, used as the index of its private
+ argument block. -/
+ root : ℕ
+ /-- Number of private words between argument blocks for successive descriptor addresses,
+ loaded from the geometry header at startup. -/
+ stride : ℕ
+
+namespace Layout
+
+variable {w : ℕ}
+
+/-- Slots scanned in each direction at one final site, computed by dividing the total slot
+count by the site count. -/
+def degree (L : Layout) := L.slots / L.sites
+/-- Global slot index at offset `j` in the selected site's interval. At the site degree it
+gives the exclusive loop bound. -/
+def index (L : Layout) (j : ℕ) := L.vertex*L.degree+j
+/-- Outgoing slot that owns the wire at a local endpoint. Outgoing slots use their global index
+directly, while incoming slots read their partner from the inverse incidence table. -/
+def edge (L : Layout) (mem : Memory w) (dir : Bool) (j : ℕ) :=
+ if dir then (mem (L.incomingHead+L.index j)).val else L.index j
+
+/-- Length in words of the selected endpoint field, read from the width table using its
+outgoing slot index. -/
+def width (L : Layout) (mem : Memory w) (dir : Bool) (j : ℕ) := (mem (L.widthHead+L.edge mem dir j)).val
+/-- First external address of the endpoint field, obtained by adding its outgoing slot's
+exclusive prefix to the wire bank base. -/
+def start (L : Layout) (mem : Memory w) (dir : Bool) (j : ℕ) := L.wires+(mem (L.prefixHead+L.edge mem dir j)).val
+
+/-- Contiguous wire words of one selected slot in increasing external address order, including
+the empty list for a zero-width slot. -/
+def field (L : Layout) (mem : Memory w) (dir : Bool) (j : ℕ) : List (Word w) :=
+ List.ofFn fun i : Fin (L.width mem dir j) => mem (L.start mem dir j+i.val)
+
+/-- Endpoint fields for all slots of the chosen site and direction in local slot order,
+retaining their individual field boundaries. -/
+def fields (L : Layout) (mem : Memory w) (dir : Bool) : List (List (Word w)) :=
+ List.ofFn fun j : Fin L.degree => L.field mem dir j.val
+
+/-- Root argument packet in copy order, with all outgoing fields concatenated before all
+incoming fields. -/
+def packet (L : Layout) (mem : Memory w) := (L.fields mem false).flatten ++ (L.fields mem true).flatten
+/-- First private address of the root packet, equal to the argument bank base plus the root
+descriptor address times the stride. -/
+def dest (L : Layout) := L.n + L.root*L.stride
+
+/-- Exactly the words whose addresses or endpoints must fit in a native
+register. The source and destination cursors also hold the exclusive end. -/
+structure Fits (L : Layout) (mem : Memory w) : Prop where
+ sites : L.sites < 2^w
+ slots : L.slots < 2^w
+ lastIndex : L.index L.degree < 2^w
+ inverseAddr : ∀ j < L.degree, L.incomingHead+L.index j < 2^w
+ widthAddr : ∀ b j, j < L.degree → L.widthHead+L.edge mem b j < 2^w
+ prefixAddr : ∀ b j, j < L.degree → L.prefixHead+L.edge mem b j < 2^w
+ sourceEnd : ∀ b j, j < L.degree → L.start mem b j+L.width mem b j < 2^w
+ destEnd : L.dest+(L.packet mem).length < 2^w
+
+@[simp] theorem field_length (L : Layout) (mem : Memory w) (dir : Bool) (j : ℕ) :
+ (L.field mem dir j).length = L.width mem dir j := by simp [field]
+
+theorem packet_length (L : Layout) (mem : Memory w) : (L.packet mem).length =
+ (∑ j : Fin L.degree, L.width mem false j) + ∑ j : Fin L.degree, L.width mem true j := by
+ simp [packet,fields,List.length_flatten,List.sum_ofFn,Function.comp_def]
+
+/-- Closed form of the private block written by the endpoint gather. -/
+def placed (base : ℕ) (xs : List (Word w)) (old : Word w → Word w) (a : Word w) : Word w :=
+ if base ≤ a.val then xs[a.val-base]?.getD (old a) else old a
+
+theorem placed_inside {base : ℕ} (xs : List (Word w)) (old : Word w → Word w) (i : Fin xs.length)
+ (h : base+xs.length ≤ 2^w) : placed base xs old (Fin.ofNat _ (base+i.val)) = xs[i.val] := by
+ have hi : base+i.val < 2^w := (Nat.add_lt_add_left i.isLt _).trans_le h
+ have hv : (Fin.ofNat (2^w) (base+i.val)).val = base+i.val := Nat.mod_eq_of_lt hi
+ unfold placed
+ rw [hv]
+ simp
+
+theorem placed_outside (base : ℕ) (xs : List (Word w)) (old : Word w → Word w) (a : Word w)
+ (h : a.val < base ∨ base+xs.length ≤ a.val) : placed base xs old a = old a := by
+ rcases h with h|h
+ · simp [placed,Nat.not_le_of_lt h]
+ · have hi : xs.length ≤ a.val-base := by omega
+ simp [placed,List.getElem?_eq_none hi]
+
+theorem placed_append (base : ℕ) (xs ys : List (Word w)) (old : Word w → Word w) :
+ placed (base+xs.length) ys (placed base xs old) = placed base (xs++ys) old := by
+ funext a
+ by_cases h : base+xs.length ≤ a.val
+ · have hb : base ≤ a.val := by omega
+ have hi : xs.length ≤ a.val-base := by omega
+ simp only [placed,h,hb,ite_true,List.getElem?_append_right hi,List.getElem?_eq_none hi,Option.getD_none]
+ rw [Nat.sub_sub]
+ · have hi : a.val-base < xs.length ∨ a.val < base := by omega
+ rcases hi with hi|hi
+ · simp [placed,h,List.getElem?_append_left hi]
+ · simp [placed,h,Nat.not_le_of_lt hi]
+
+theorem copy_field (L : Layout) (mem : Memory w) (dir : Bool) (j dst : ℕ) (old : Word w → Word w) :
+ EndpointBits.copySlice mem (L.start mem dir j) dst (L.width mem dir j) old =
+ placed dst (L.field mem dir j) old := by
+ funext a
+ by_cases h : dst ≤ a.val ∧ a.val < dst+L.width mem dir j
+ · have hi : a.val-dst < L.width mem dir j := by omega
+ simp [EndpointBits.copySlice,h,placed,field,hi]
+ · have hi : a.val < dst ∨ dst+(L.field mem dir j).length ≤ a.val := by rw [field_length]; omega
+ rw [placed_outside _ _ _ _ hi]; simp [EndpointBits.copySlice,h]
+
+end Layout
+
+end PairSimulation.TerminalRootGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherLinked.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherLinked.lean
new file mode 100644
index 0000000000..e1da4dda16
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherLinked.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherCode
+
+/-!
+# Installing the terminal root gather in the vertex image
+
+The gather occupies the image's root-fields segment. Its nine temporaries
+belong to that segment's private register bank. The eleven saved registers
+are shared with the bootstrap, and the other three slots refer to the first
+three DFS registers. The final exit enters DFS row zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalRootGather
+open BurstRAM PrivateRAM
+
+variable {S : VertexImage.Part → VertexImage.Segment} {w p r : ℕ}
+
+private noncomputable def slotsPC {s : VertexImage.Segment} (h : s = segment) (i : Fin segment.count) : Fin s.count :=
+ Fin.cast (congrArg VertexImage.Segment.count h.symm) i
+
+private noncomputable def slotsWork {s : VertexImage.Segment} (h : s = segment) (work : Fin s.privateRegs ↪ Fin r) :
+ Fin 9 ↪ Fin r := (Fin.castOrderIso (congrArg VertexImage.Segment.privateRegs h.symm)).toEquiv.toEmbedding.trans work
+
+variable (A : VertexImage.Placement S p r) (hfield : S .rootFields = segment)
+
+/-- Physical program counter of a gather label in the vertex image's root-fields segment,
+obtained from the finite numbering of gather instructions. -/
+noncomputable def imagePC (i : PC) : Fin p := A.stage .rootFields (slotsPC hfield (Fintype.equivFin PC i))
+
+/-- Embedding of the nine gather temporaries into the host registers allocated to the
+root-fields segment. -/
+noncomputable def imageWork : Fin 9 ↪ Fin r := slotsWork hfield (A.localRegs .rootFields)
+
+private noncomputable def registerIndex : Reg → VertexImage.Reg S
+ | .inl i => .inr (.inr (.inr ⟨.rootFields, Fin.cast (congrArg VertexImage.Segment.privateRegs hfield.symm) i⟩))
+ | .inr (.inl i) => .inr (.inl i)
+ | .inr (.inr i) => .inl (Fin.castAdd 6 i)
+
+/-- Actual placement of the three register groups in the image. -/
+noncomputable def imageRegs : Reg ↪ Fin r :=
+ (⟨registerIndex hfield, by
+ rintro (x | x | x) (y | y | y) he <;> simp [registerIndex] at he ⊢
+ all_goals first | exact he | (have hv := congrArg Fin.val he; exact Fin.ext hv)⟩ :
+ Reg ↪ VertexImage.Reg S).trans A.reg
+
+@[simp] theorem imageRegs_tmp (i : Fin 9) : imageRegs A hfield (tmp i) = imageWork A hfield i := rfl
+
+@[simp] theorem imageRegs_saved (i : Fin 11) : imageRegs A hfield (save i) = A.saved i := rfl
+
+@[simp] theorem imageRegs_dfs (i : Fin 3) :
+ imageRegs A hfield (TerminalSiteStart.work i) = A.dfs (Fin.castAdd 6 i) := rfl
+
+theorem image_entry : imagePC A hfield (.boot 0) = A.entry .rootFields := by
+ apply congrArg (A.stage .rootFields)
+ apply Fin.ext
+ exact (congrArg (fun s : VertexImage.Segment => s.entry.val) hfield).symm
+
+private theorem installed_row {s : VertexImage.Segment} (h : s = segment)
+ (lab : Fin s.count → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Fin 11 ↪ Fin r)
+ (work : Fin s.privateRegs ↪ Fin r) (done : Fin p) (i : PC) :
+ (s.row lab dfs saved work done (slotsPC h (Fintype.equivFin PC i))).resize w =
+ rows (fun j => lab (slotsPC h (Fintype.equivFin PC j))) (regMap dfs saved (slotsWork h work))
+ ((Fin.castAddEmb 4).trans (slotsWork h work)) done i := by
+ subst s
+ change (rows (lab ∘ Fintype.equivFin PC) (regMap dfs saved work) ((Fin.castAddEmb 4).trans work) done
+ ((Fintype.equivFin PC).symm (Fintype.equivFin PC i))).resize w = _
+ rw [Equiv.symm_apply_apply,resize_rows]
+ rfl
+
+/-- Every instruction of the installed segment has the linked labels, live
+registers and DFS continuation of the gather proof. -/
+theorem image_linked {M : Machine w p r 11} (h : VertexImage.Contains A M) :
+ Linked M (imagePC A hfield) (imageRegs A hfield) (A.dfsPC 0) := by
+ intro i
+ have regEq : ⇑(imageRegs A hfield) = regMap A.dfs A.saved (imageWork A hfield) := by
+ funext j; rcases j with j | j | j <;> rfl
+ have bitEq : bitRegs (imageRegs A hfield) = (Fin.castAddEmb 4).trans (imageWork A hfield) := by
+ ext j; rfl
+ rw [regEq,bitEq]
+ exact (VertexImage.stage_linked A M h .rootFields (slotsPC hfield (Fintype.equivFin PC i))).trans
+ (installed_row (w := w) hfield (A.stage .rootFields) A.dfs A.saved (A.localRegs .rootFields) (A.dfsPC 0) i)
+
+end PairSimulation.TerminalRootGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherReads.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherReads.lean
new file mode 100644
index 0000000000..cddfc9b5f8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherReads.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherLayout
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-! # External read addresses of the terminal endpoint gather -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.SourceTransport
+
+open BurstRAM
+
+theorem Reads.append {w : ℕ} {P : ℕ → Prop} {xs ys : List (Event w)}
+ (hx : Reads P xs) (hy : Reads P ys) : Reads P (xs ++ ys) :=
+ fun a v read ↦ (List.mem_append.mp read).elim (hx a v) (hy a v)
+
+theorem Reads.replicate_tick {w : ℕ} (P : ℕ → Prop) (n : ℕ) :
+ Reads P (List.replicate n (.tick : Event w)) := by
+ intro a v read
+ cases List.eq_of_mem_replicate read
+
+end CompressorRecords.SourceTransport
+
+namespace PairSimulation.TerminalRootGather
+
+open BurstRAM CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+/-- Allowed external addresses for this vertex's incoming-edge lookup, outgoing
+edge metadata and shared bit intervals. The incoming lookup precedes the width
+and prefix reads, so those two bounds depend on the actual entry memory. -/
+structure Layout.Readable {w : ℕ} (L : Layout) (m : Memory w) (P : ℕ → Prop) : Prop where
+ incoming : ∀ j < L.degree, P (L.incomingHead + L.index j)
+ widths : ∀ d j, j < L.degree → P (L.widthHead + L.edge m d j)
+ prefixes : ∀ d j, j < L.degree → P (L.prefixHead + L.edge m d j)
+ wire : ∀ d j, j < L.degree → ∀ i < L.width m d j, P (L.start m d j + i)
+
+theorem Layout.readable_true {w : ℕ} (L : Layout) (m : Memory w) : L.Readable m (fun _ ↦ True) :=
+ ⟨fun _ _ ↦ trivial, fun _ _ _ ↦ trivial, fun _ _ _ ↦ trivial, fun _ _ _ _ _ ↦ trivial⟩
+
+/-- The bit-copy loop reads exactly within the chosen source interval. -/
+theorem arc_reads {w : ℕ} (m : Memory w) (P : ℕ → Prop) (s n : ℕ)
+ (fit : s+n < 2^w) (allowed : ∀ i < n, P (s+i)) :
+ Reads P (EndpointBits.events m s n) := by
+ induction n generalizing s with
+ | zero => exact Reads.replicate_tick P 1
+ | succ n ih =>
+ apply Reads.append _ (ih (s+1) (by omega) (fun i hi ↦ by
+ simpa only [Nat.add_assoc, Nat.add_comm 1 i] using allowed (i+1) (by omega)))
+ intro a v h
+ simp only [List.mem_cons,List.not_mem_nil,Event.read.injEq,reduceCtorEq,false_or,or_false] at h
+ rw [h.1, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ simpa using allowed 0 (by omega)
+
+end PairSimulation.TerminalRootGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherScan.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherScan.lean
new file mode 100644
index 0000000000..cce9d9b669
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalRootGatherScan.lean
@@ -0,0 +1,291 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherCode
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherReads
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+
+/-! # Execution of both terminal slot scans
+
+The slot cursor counts empty slots as well as positive-width slots. It reads
+the shared directory, copies exactly one external word per wire bit, and
+preserves the private memory outside its destination interval.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalRootGather
+
+open BurstRAM PrivateRAM CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+variable {w p r : ℕ} {M : Machine w p r 11} {pc : PC → Fin p} {reg : Reg ↪ Fin r}
+ {done : Fin p} {m : Memory w} {c d e : Config w p r}
+
+theorem Prefix.trans {xs ys : List (Event w)} (hx : Prefix M m c xs d) (hy : Prefix M m d ys e) :
+ Prefix M m c (xs++ys) e := by
+ intro f bs
+ rw [List.length_append,show f+(xs.length+ys.length)=(f+ys.length)+xs.length by omega,hx,hy]
+ simp [Option.map_map,Function.comp_def]
+
+theorem Prefix.tick (h : M.program.step c = .localStep d) : Prefix M m c [.tick] d := by
+ intro f bs
+ simp only [List.length_cons,List.length_nil,zero_add,execute,h]
+ rfl
+
+theorem Frame.trans (h₁ : Frame reg c d) (h₂ : Frame reg d e) : Frame reg c e :=
+ ⟨h₂.1.trans h₁.1,fun i h => (h₂.2 i h).trans (h₁.2 i h)⟩
+
+theorem Saved.transport {L : Layout} (h : Saved L reg c) (f : Frame reg c d) : Saved L reg d := by
+ have stable (i : Fin 11) : d.reg (reg (save i)) = c.reg (reg (save i)) :=
+ f.2 _ (fun j => reg.injective.ne (Sum.inl_ne_inr : tmp j ≠ save i))
+ exact ⟨(stable _).trans h.ordinal,(stable _).trans h.root,(stable _).trans h.sites,
+ (stable _).trans h.slots,(stable _).trans h.widths,(stable _).trans h.incoming,
+ (stable _).trans h.prefixBase,(stable _).trans h.wires⟩
+
+/-- Certifies the exact event count and external probe count of a gather trace, together with
+preservation of external memory and an empty choice-bit trace. -/
+structure Cost (es : List (Event w)) (ticks reads : ℕ) : Prop where
+ time : es.length = ticks
+ probes : countProbes es = reads
+ after_eq : ∀ mem, after mem es = mem
+ bits : choiceBits es = []
+
+theorem Cost.append {xs ys : List (Event w)} {t₁ t₂ r₁ r₂ : ℕ} (hx : Cost xs t₁ r₁) (hy : Cost ys t₂ r₂) :
+ Cost (xs++ys) (t₁+t₂) (r₁+r₂) := by
+ refine ⟨by simp [hx.time,hy.time],by rw [countProbes_append,hx.probes,hy.probes],?_,?_⟩
+ · intro mem
+ rw [after,List.foldl_append]
+ change after (after mem xs) ys = mem
+ rw [hx.after_eq,hy.after_eq]
+ · rw [PrimedInputRAM.Flow.choiceBits_append,hx.bits,hy.bits]; rfl
+
+theorem Cost.tick : Cost ([.tick] : List (Event w)) 1 0 := ⟨rfl,rfl,fun _ => rfl,rfl⟩
+
+theorem Cost.replicate_tick (n : ℕ) : Cost (List.replicate n (.tick : Event w)) n 0 := by
+ induction n with
+ | zero => exact ⟨rfl,rfl,fun _ => rfl,rfl⟩
+ | succ n ih => simpa only [List.replicate_succ,Nat.one_add, Nat.zero_add,List.singleton_append] using Cost.tick.append ih
+
+theorem arc_cost (mem : Memory w) (s n : ℕ) : Cost (EndpointBits.events mem s n) (5*n+1) n := by
+ induction n generalizing s with
+ | zero => exact Cost.tick
+ | succ n ih =>
+ have h : Cost ([.tick,.read (s : Word w) (mem s),.tick,.tick,.tick] : List (Event w)) 5 1 :=
+ ⟨rfl,rfl,fun _ => rfl,rfl⟩
+ simpa only [EndpointBits.events,show 5 + (5*n+1) = 5*(n+1)+1 by omega,Nat.one_add] using h.append (ih (s+1))
+
+/-- Slot-loop invariant for the next field to gather. It records the private write cursor, the
+unit increment, and the current, first and exclusive-end slot indices. -/
+structure Cursor (L : Layout) (reg : Reg ↪ Fin r) (c : Config w p r) (j dst : ℕ) : Prop where
+ dest : c.reg (reg (tmp 2)) = (dst : Word w)
+ one : c.reg (reg (tmp 3)) = 1
+ slot : c.reg (reg (tmp 5)) = (L.index j : Word w)
+ stop : c.reg (reg (tmp 6)) = (L.index L.degree : Word w)
+ first : c.reg (reg (tmp 7)) = (L.index 0 : Word w)
+
+/-- Postcondition for the two straight-line directory-read blocks. -/
+def Headers (L : Layout) (M : Machine w p r 11) (m : Memory w) (pc : PC → Fin p) (reg : Reg ↪ Fin r) :=
+ ∀ b j, j < L.degree → ∀ c : Config w p r, c.pc = pc (.header b (firstHeader b)) →
+ Saved L reg c → c.reg (reg (tmp 5)) = (L.index j : Word w) → ∃ out es,
+ out.pc = pc (.bits b 0) ∧ Frame reg c out ∧ out.privateMem = c.privateMem ∧
+ out.reg (reg (tmp 0)) = (L.start m b j : Word w) ∧
+ out.reg (reg (tmp 1)) = ((L.start m b j+L.width m b j : ℕ) : Word w) ∧
+ (∀ i : Fin 9, i ≠ 0 → i ≠ 1 → i ≠ 4 → out.reg (reg (tmp i)) = c.reg (reg (tmp i))) ∧
+ Cost es (if b then 8 else 7) (if b then 3 else 2) ∧ Prefix M m c es out
+
+/-- Directory-read postcondition including the addresses of the same execution. -/
+def HeadersReads (P : ℕ → Prop) (L : Layout) (M : Machine w p r 11) (m : Memory w)
+ (pc : PC → Fin p) (reg : Reg ↪ Fin r) :=
+ ∀ b j, j < L.degree → ∀ c : Config w p r, c.pc = pc (.header b (firstHeader b)) →
+ Saved L reg c → c.reg (reg (tmp 5)) = (L.index j : Word w) → ∃ out es,
+ out.pc = pc (.bits b 0) ∧ Frame reg c out ∧ out.privateMem = c.privateMem ∧
+ out.reg (reg (tmp 0)) = (L.start m b j : Word w) ∧
+ out.reg (reg (tmp 1)) = ((L.start m b j+L.width m b j : ℕ) : Word w) ∧
+ (∀ i : Fin 9, i ≠ 0 → i ≠ 1 → i ≠ 4 → out.reg (reg (tmp i)) = c.reg (reg (tmp i))) ∧
+ Cost es (if b then 8 else 7) (if b then 3 else 2) ∧ Reads P es ∧ Prefix M m c es out
+
+private theorem headersReads_true {L : Layout} (h : Headers L M m pc reg) :
+ HeadersReads (fun _ ↦ True) L M m pc reg := by
+ intro b j hj cur hc saved slot
+ obtain ⟨out,es,hpc,hf,hm,hs,he,hr,hcost,run⟩ := h b j hj cur hc saved slot
+ exact ⟨out,es,hpc,hf,hm,hs,he,hr,hcost,fun _ _ _ ↦ trivial,run⟩
+
+private theorem step_at (hl : Linked M pc reg done) (i : PC) (hc : c.pc=pc i) :
+ M.program.step c = (rows pc reg (bitRegs reg) done i).run M.publicData c := by
+ simp only [Machine.program,hc,hl i]
+
+/-- A nonempty slot scan iteration, including its cursor comparison and increment.
+The bit loop still performs an exit comparison when the selected width is zero. -/
+theorem field_run_reads (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (fit : L.Fits m)
+ (P : ℕ → Prop) (readable : L.Readable m P) (headers : HeadersReads P L M m pc reg)
+ (b : Bool) (j dst : ℕ) (hj : j < L.degree)
+ (hd : dst+L.width m b j < 2^w) (c : Config w p r) (hc : c.pc=pc (.scan b))
+ (saved : Saved L reg c) (cur : Cursor L reg c j dst) :
+ ∃ out es, out.pc=pc (.scan b) ∧ Frame reg c out ∧
+ out.privateMem = Layout.placed dst (L.field m b j) c.privateMem ∧
+ Cursor L reg out (j+1) (dst+L.width m b j) ∧
+ Cost es ((if b then 11 else 10)+5*L.width m b j) (L.width m b j+(if b then 3 else 2)) ∧
+ Reads P es ∧ Prefix M m c es out := by
+ let head := {c with pc := pc (.header b (firstHeader b))}
+ have hlt : L.index j < L.index L.degree := Nat.add_lt_add_left hj _
+ have hne : c.reg (reg (tmp 5)) ≠ c.reg (reg (tmp 6)) := by
+ rw [cur.slot,cur.stop]
+ intro eqn
+ have vals := congrArg Fin.val eqn
+ change L.index j % (2^w) = L.index L.degree % (2^w) at vals
+ rw [Nat.mod_eq_of_lt (hlt.trans fit.lastIndex),Nat.mod_eq_of_lt fit.lastIndex] at vals
+ exact hlt.ne vals
+ have first : Prefix M m c [.tick] head := Prefix.tick (by
+ rw [step_at hl _ hc]; simp [rows,Instr.run,hne,head])
+ have fhead : Frame reg c head := ⟨rfl,fun _ _ => rfl⟩
+ obtain ⟨pre,hs,hpc,hframe,hpriv,src,hend,rest,hcost,hreads,hprefix⟩ :=
+ headers b j hj head rfl (saved.transport fhead) cur.slot
+ have br : EndpointBits.Linked M (pc ∘ PC.bits b) (bitRegs reg) (pc (.advance b)) := fun i => hl (.bits b i)
+ obtain ⟨post,hpost,hpersist,_,dest,other,priv,executeBits⟩ :=
+ EndpointBits.execute_arc br pre hpc m (L.start m b j) dst (L.width m b j)
+ (fit.sourceEnd b j hj) hd src hend ((rest 2 (by decide) (by decide) (by decide)).trans cur.dest)
+ ((rest 3 (by decide) (by decide) (by decide)).trans cur.one)
+ have postFrame : Frame reg pre post :=
+ ⟨hpersist,fun i hi => other _ (hi 0).symm (hi 2).symm (hi 4).symm⟩
+ have bitCost := arc_cost m (L.start m b j) (L.width m b j)
+ have runBits : Prefix M m pre (EndpointBits.events m (L.start m b j) (L.width m b j)) post := by
+ intro f bs
+ rw [bitCost.time,← Nat.add_assoc]
+ exact executeBits f bs
+ have keep (i : Fin 9) (h0 : i≠0) (h1 : i≠1) (h2 : i≠2) (h4 : i≠4) :
+ post.reg (reg (tmp i))=c.reg (reg (tmp i)) := by
+ apply (other _ ?_ ?_ ?_).trans (rest i h0 h1 h4)
+ · exact reg.injective.ne (Sum.inl_injective.ne h0)
+ · exact reg.injective.ne (Sum.inl_injective.ne h2)
+ · exact reg.injective.ne (Sum.inl_injective.ne h4)
+ let out := post.put (pc (.scan b)) (reg (tmp 5)) (post.reg (reg (tmp 5))+post.reg (reg (tmp 3)))
+ have last : Prefix M m post [.tick] out := Prefix.tick (by rw [step_at hl _ hpost]; rfl)
+ have outFrame : Frame reg post out := ⟨rfl,fun i hi => Function.update_of_ne (hi 5).symm ..⟩
+ have frame : Frame reg c out := Frame.trans (c:=c) hframe (postFrame.trans outFrame)
+ have outKeep (i : Fin 9) (h : i≠5) : out.reg (reg (tmp i)) = post.reg (reg (tmp i)) :=
+ Function.update_of_ne (reg.injective.ne (Sum.inl_injective.ne h)) ..
+ have postKeep (i : Fin 9) (h : i=3 ∨ i=5 ∨ i=6 ∨ i=7) : post.reg (reg (tmp i))=c.reg (reg (tmp i)) := by
+ rcases h with rfl|rfl|rfl|rfl <;> apply keep <;> decide
+ let es := [.tick] ++ hs ++ EndpointBits.events m (L.start m b j) (L.width m b j) ++ [.tick]
+ refine ⟨out,es,rfl,frame,?_,?_,?_,?_,((first.trans hprefix).trans runBits).trans last⟩
+ · change post.privateMem = _
+ rw [priv,hpriv,L.copy_field]
+ · refine ⟨(outKeep 2 (by decide)).trans dest,(outKeep 3 (by decide)).trans ((postKeep 3 (by decide)).trans cur.one),?_,
+ (outKeep 6 (by decide)).trans ((postKeep 6 (by decide)).trans cur.stop),
+ (outKeep 7 (by decide)).trans ((postKeep 7 (by decide)).trans cur.first)⟩
+ simp only [out,Config.put,Function.update_self,postKeep 5 (by decide),postKeep 3 (by decide),cur.slot,cur.one,
+ Layout.index,Nat.cast_add,Nat.cast_one,add_assoc]
+ · have co := ((Cost.tick.append hcost).append bitCost).append Cost.tick
+ cases b <;> simpa only [Bool.false_eq_true,↓reduceIte,es,show ∀ x, 1+7+(5*x+1)+1=10+5*x by omega,
+ show ∀ x, 1+8+(5*x+1)+1=11+5*x by omega,zero_add,add_zero,Nat.add_comm 2,Nat.add_comm 3] using co
+ · exact (((Reads.replicate_tick P 1).append hreads).append
+ (arc_reads m P _ _ (fit.sourceEnd b j hj) (readable.wire b j hj))).append (Reads.replicate_tick P 1)
+
+theorem field_run (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (fit : L.Fits m)
+ (headers : Headers L M m pc reg) (b : Bool) (j dst : ℕ) (hj : j < L.degree)
+ (hd : dst+L.width m b j < 2^w) (c : Config w p r) (hc : c.pc=pc (.scan b))
+ (saved : Saved L reg c) (cur : Cursor L reg c j dst) :
+ ∃ out es, out.pc=pc (.scan b) ∧ Frame reg c out ∧
+ out.privateMem = Layout.placed dst (L.field m b j) c.privateMem ∧
+ Cursor L reg out (j+1) (dst+L.width m b j) ∧
+ Cost es ((if b then 11 else 10)+5*L.width m b j) (L.width m b j+(if b then 3 else 2)) ∧
+ Prefix M m c es out := by
+ obtain ⟨out, es, hp, hf, hm, hcur, cost, _, run⟩ :=
+ field_run_reads hl L m fit (fun _ ↦ True) (L.readable_true m) (headersReads_true headers)
+ b j dst hj hd c hc saved cur
+ exact ⟨out, es, hp, hf, hm, hcur, cost, run⟩
+
+/-- The remaining fields of one half of the argument packet. -/
+def suffix (L : Layout) (mem : Memory w) (b : Bool) (j left : ℕ) :=
+ (List.ofFn fun i : Fin left => L.field mem b (j+i.val)).flatten
+
+theorem suffix_succ (L : Layout) (mem : Memory w) (b : Bool) (j left : ℕ) :
+ suffix L mem b j (left+1) = L.field mem b j ++ suffix L mem b (j+1) left := by
+ simp only [suffix,List.ofFn_succ,Fin.val_zero,Nat.add_zero,List.flatten_cons,Fin.val_succ]
+ congr 3
+ funext i
+ rw [show j+(i.val+1) = j+1+i.val by omega]
+
+theorem suffix_full (L : Layout) (mem : Memory w) (b : Bool) :
+ suffix L mem b 0 L.degree = (L.fields mem b).flatten := by simp [suffix,Layout.fields]
+
+theorem scan_run_reads (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (fit : L.Fits m)
+ (P : ℕ → Prop) (readable : L.Readable m P) (headers : HeadersReads P L M m pc reg)
+ (b : Bool) (left j dst : ℕ) (lastSlot : j+left=L.degree)
+ (hd : dst+(suffix L m b j left).length < 2^w) (c : Config w p r) (hc : c.pc=pc (.scan b))
+ (saved : Saved L reg c) (cur : Cursor L reg c j dst) :
+ let words := suffix L m b j left
+ ∃ out es, out.pc=(if b then done else pc .reset) ∧ Frame reg c out ∧
+ out.privateMem=Layout.placed dst words c.privateMem ∧
+ Cursor L reg out L.degree (dst+words.length) ∧
+ Cost es ((if b then 11 else 10)*left+5*words.length+1)
+ (words.length+(if b then 3 else 2)*left) ∧ Reads P es ∧ Prefix M m c es out := by
+ induction left generalizing j dst c with
+ | zero =>
+ have hj : j=L.degree := by omega
+ have eqn : c.reg (reg (tmp 5))=c.reg (reg (tmp 6)) := cur.slot.trans (hj ▸ cur.stop.symm)
+ let out := {c with pc := if b then done else pc .reset}
+ have ht : Prefix M m c [.tick] out := Prefix.tick (by rw [step_at hl _ hc]; simp [rows,Instr.run,eqn,out])
+ have nil : suffix L m b j 0 = [] := by simp [suffix]
+ dsimp only
+ rw [nil]
+ refine ⟨out,[.tick],rfl,⟨rfl,fun _ _ => rfl⟩,?_,?_,by simpa using (Cost.tick (w:=w)),Reads.replicate_tick P 1,ht⟩
+ · funext a
+ simp [out,Layout.placed]
+ · rw [List.length_nil,Nat.add_zero,← hj]
+ exact ⟨cur.dest,cur.one,cur.slot,cur.stop,cur.first⟩
+ | succ left ih =>
+ let tail := suffix L m b (j+1) left
+ have len : (suffix L m b j (left+1)).length=L.width m b j+tail.length := by
+ rw [suffix_succ,List.length_append,Layout.field_length]
+ have headFit : dst+L.width m b j < 2^w := by rw [len] at hd; omega
+ obtain ⟨next,hs,hpc,hframe,hpriv,hcur,hcost,hreads,hprefix⟩ := field_run_reads hl L m fit P readable headers b j dst
+ (by omega) headFit c hc saved cur
+ obtain ⟨out,ts,hend,tframe,tpriv,tcur,tcost,treads,tprefix⟩ :=
+ ih (j+1) (dst+L.width m b j) (by omega) (by rw [len] at hd; change _ + tail.length < _; omega)
+ next hpc (saved.transport hframe) hcur
+ dsimp only
+ refine ⟨out,hs++ts,hend,hframe.trans tframe,?_,?_,?_,hreads.append treads,hprefix.trans tprefix⟩
+ · rw [tpriv,hpriv,suffix_succ,← Layout.field_length L m b j,Layout.placed_append]
+ · rw [len,← Nat.add_assoc]
+ exact tcur
+ · have h := hcost.append tcost
+ change Cost _ _ (L.width m b j+_+(tail.length+_)) at h
+ rw [len]
+ convert h using 1 <;> dsimp only [tail] <;> cases b <;> simp only [Bool.false_eq_true,↓reduceIte,Nat.mul_add,Nat.mul_one] <;> omega
+
+theorem scan_run (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (fit : L.Fits m)
+ (headers : Headers L M m pc reg) (b : Bool) (left j dst : ℕ) (lastSlot : j+left=L.degree)
+ (hd : dst+(suffix L m b j left).length < 2^w) (c : Config w p r) (hc : c.pc=pc (.scan b))
+ (saved : Saved L reg c) (cur : Cursor L reg c j dst) :
+ let words := suffix L m b j left
+ ∃ out es, out.pc=(if b then done else pc .reset) ∧ Frame reg c out ∧
+ out.privateMem=Layout.placed dst words c.privateMem ∧
+ Cursor L reg out L.degree (dst+words.length) ∧
+ Cost es ((if b then 11 else 10)*left+5*words.length+1)
+ (words.length+(if b then 3 else 2)*left) ∧ Prefix M m c es out := by
+ obtain ⟨out, es, hp, hf, hm, hcur, cost, _, run⟩ :=
+ scan_run_reads hl L m fit (fun _ ↦ True) (L.readable_true m) (headersReads_true headers)
+ b left j dst lastSlot hd c hc saved cur
+ exact ⟨out, es, hp, hf, hm, hcur, cost, run⟩
+
+/-- The intermediate row returns the slot counter to the site's first slot,
+leaving the destination cursor immediately after the outgoing payloads. -/
+theorem reset_run (hl : Linked M pc reg done) (L : Layout) (m : Memory w) (c : Config w p r)
+ (hc : c.pc=pc .reset) (j dst : ℕ) (cur : Cursor L reg c j dst) :
+ ∃ out, out.pc=pc (.scan true) ∧ Frame reg c out ∧ out.privateMem=c.privateMem ∧
+ Cursor L reg out 0 dst ∧ Prefix M m c [.tick] out := by
+ let out := c.put (pc (.scan true)) (reg (tmp 5)) (c.reg (reg (tmp 7)))
+ have keep (i : Fin 9) (h : i≠5) : out.reg (reg (tmp i))=c.reg (reg (tmp i)) :=
+ Function.update_of_ne (reg.injective.ne (Sum.inl_injective.ne h)) ..
+ refine ⟨out,rfl,⟨rfl,fun i hi => Function.update_of_ne (hi 5).symm ..⟩,rfl,
+ ⟨(keep 2 (by decide)).trans cur.dest,(keep 3 (by decide)).trans cur.one,?_,
+ (keep 6 (by decide)).trans cur.stop,(keep 7 (by decide)).trans cur.first⟩,
+ Prefix.tick (by rw [step_at hl _ hc]; rfl)⟩
+ simp only [out,Config.put,Function.update_self,cur.first]
+
+end PairSimulation.TerminalRootGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalSiteLinear.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSiteLinear.lean
new file mode 100644
index 0000000000..982b449469
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSiteLinear.lean
@@ -0,0 +1,164 @@
+import OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+/-! # Straight-line rows for initializing a final site's private DFS stack -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalSiteStart
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.read ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+/-- Logical registers for the terminal-site entry code, partitioned into nine DFS slots, eleven
+saved bootstrap slots and three working slots. -/
+abbrev Reg := Fin 9 ⊕ (Fin 11 ⊕ Fin 3)
+
+/-- Selects a DFS register in the site-entry bank. The bootstrap uses this bank to set the
+stack top and end for the pending root visit. -/
+abbrev dfs (i : Fin 9) : Reg := .inl i
+/-- Selects a bootstrap register holding values needed by later stages, including the site
+ordinal, root descriptor and endpoint table addresses. -/
+abbrev saved (i : Fin 11) : Reg := .inr (.inl i)
+/-- Selects one of the three working registers available for intermediate site-entry
+calculations such as header offsets and the root row address. -/
+abbrev work (i : Fin 3) : Reg := .inr (.inr i)
+
+/-- One straight-line operation on the symbolic site-entry registers. Operations include public
+and state inputs, word arithmetic, external reads and private loads or stores. -/
+inductive Line where
+ | lit (dst : Reg) (value : Fin 32)
+ | pub (dst : Reg) (i : Fin 11)
+ | state (dst : Reg)
+ | copy (dst src : Reg)
+ | bin (op : BinaryOp) (dst lhs rhs : Reg)
+ | read (dst addr : Reg)
+ | load (dst addr : Reg)
+ | store (addr src : Reg)
+
+variable {w p r k : ℕ}
+
+/-- Translates one symbolic line to a native RAM instruction using the supplied physical
+registers, public ports and successor label. -/
+def Line.emit (reg : Reg → Fin r) (pub : Fin 11 → Fin k) (next : Fin p) : Line → Instr w p r k
+ | .lit i n => .constant (reg i) (n.val : Word w) next
+ | .pub i j => .publicWord (reg i) (pub j) next
+ | .state i => .stateWord (reg i) next
+ | .copy i j => .copy (reg i) (reg j) next
+ | .bin op i x y => .binary op (reg i) (reg x) (reg y) next
+ | .read i a => .readExternal (reg i) (reg a) next
+ | .load i a => .loadPrivate (reg i) (reg a) next
+ | .store a i => .storePrivate (reg a) (reg i) next
+
+theorem Line.resize_emit (reg : Reg → Fin r) (pub : Fin 11 → Fin k) (next : Fin p) (l : Line) :
+ (Line.emit (w := 5) reg pub next l).resize w = Line.emit reg pub next l := by
+ cases l <;> try rfl
+ rename_i n
+ change Instr.constant _ (Fin.ofNat _ (n.val % 32)) _ = Instr.constant _ (n.val : Word w) _
+ rw [Nat.mod_eq_of_lt n.isLt]; rfl
+
+/-- Evaluate a straight-line fragment with the same address reads and private stores as the RAM. -/
+def eval (pub : Fin 11 → Word w) (st : Word w) (m : Memory w) :
+ List Line → (Reg → Word w) → (Word w → Word w) → List (Event w) × (Reg → Word w) × (Word w → Word w)
+ | [], b, priv => ([], b, priv)
+ | op :: ops, b, priv =>
+ let (e, bank, mem) := match op with
+ | .lit i n => (Event.tick, Function.update b i (n.val : Word w), priv)
+ | .pub i j => (.tick, Function.update b i (pub j), priv)
+ | .state i => (.tick, Function.update b i st, priv)
+ | .copy i j => (.tick, Function.update b i (b j), priv)
+ | .bin f i x y => (.tick, Function.update b i (f.eval (b x) (b y)), priv)
+ | .read i a => (.read (b a) (m (b a).val), Function.update b i (m (b a).val), priv)
+ | .load i a => (.tick, Function.update b i (priv (b a)), priv)
+ | .store a i => (.tick, b, Function.update priv (b a) (b i))
+ let (es, out, mem') := eval pub st m ops bank mem
+ (e :: es, out, mem')
+
+private theorem update_comp (reg : Reg ↪ Fin r) (b : Fin r → Word w) (i : Reg) (v : Word w) :
+ Function.update b (reg i) v ∘ reg = Function.update (b ∘ reg) i v := by
+ funext j
+ by_cases h : j = i <;> simp [Function.comp_apply, h]
+
+/-- Execute the emitted rows at arbitrary labels, leaving the live bank and
+private memory computed by `eval`. -/
+private theorem linear_walk (M : Machine w p r k) (reg : Reg ↪ Fin r) (pub : Fin 11 → Fin k) (m : Memory w)
+ (ls : List Line) (pc : Fin (ls.length+1) → Fin p)
+ (hl : ∀ i : Fin ls.length, M.code (pc i.castSucc) = Line.emit reg pub (pc i.succ) ls[i])
+ (c : Config w p r) (hc : c.pc = pc 0) :
+ let v := eval (M.publicData ∘ pub) c.persistent m ls (c.reg ∘ reg) c.privateMem
+ ∃ out, out.pc = pc (Fin.last ls.length) ∧ out.persistent = c.persistent ∧
+ out.reg ∘ reg = v.2.1 ∧ out.privateMem = v.2.2 ∧
+ (∀ j, (∀ i, reg i ≠ j) → out.reg j = c.reg j) ∧ ReadPrefix M m c v.1 out := by
+ induction ls generalizing c with
+ | nil => exact ⟨c, hc, rfl, rfl, rfl, fun _ _ => rfl, ReadPrefix.nil _⟩
+ | cons op ops ih =>
+ let next := pc (Fin.succ 0)
+ have row := hl 0
+ change M.code (pc 0) = Line.emit reg pub next op at row
+ have hs : M.program.step c = (Line.emit reg pub next op).run M.publicData c := by
+ simp only [Machine.program, hc, row]
+ have tail (mid : Config w p r) (hn : mid.pc = next) :=
+ ih (fun i => pc i.succ) (fun i => hl i.succ) mid hn
+ cases op
+ case store a i =>
+ let mid := c.store next (c.reg (reg a)) (c.reg (reg i))
+ obtain ⟨out, hpc, hp, hr, hm, hf, h⟩ := tail mid rfl
+ exact ⟨out,hpc,hp,hr,hm,hf,ReadPrefix.tick hs h⟩
+ case read i a =>
+ let mid := c.put next (reg i) (m (c.reg (reg a)).val)
+ obtain ⟨out, hpc, hp, hr, hm, hf, h⟩ := tail mid rfl
+ refine ⟨out,hpc,hp,?_,?_,?_,?_⟩
+ · simpa only [mid, Config.put, update_comp, eval, Function.comp_apply] using hr
+ · simpa only [mid, Config.put, update_comp, eval, Function.comp_apply] using hm
+ · intro j hj
+ exact (hf j hj).trans (Function.update_of_ne (hj i).symm ..)
+ · simpa only [mid, Config.put, update_comp, eval, Function.comp_apply] using ReadPrefix.read (c.reg (reg a)) hs h
+ case' lit i n => let mid := c.put next (reg i) (n.val : Word w)
+ case' pub i j => let mid := c.put next (reg i) (M.publicData (pub j))
+ case' state i => let mid := c.put next (reg i) c.persistent
+ case' copy i j => let mid := c.put next (reg i) (c.reg (reg j))
+ case' load i a => let mid := c.put next (reg i) (c.privateMem (c.reg (reg a)))
+ case' bin f i x y => let mid := c.put next (reg i) (f.eval (c.reg (reg x)) (c.reg (reg y)))
+ all_goals
+ have step : M.program.step c = .localStep mid := hs
+ obtain ⟨out,hpc,hp,hr,hm,hf,h⟩ := tail mid rfl
+ refine ⟨out,hpc,hp,?_,?_,?_,?_⟩
+ · simpa only [mid, Config.put, update_comp, eval, Function.comp_apply] using hr
+ · simpa only [mid, Config.put, update_comp, eval, Function.comp_apply] using hm
+ · intro j hj
+ exact (hf j hj).trans (Function.update_of_ne (hj i).symm ..)
+ · simpa only [mid, Config.put, update_comp, eval, Function.comp_apply] using ReadPrefix.tick step h
+
+theorem linear_run_framed (M : Machine w p r k) (reg : Reg ↪ Fin r) (pub : Fin 11 → Fin k) (m : Memory w)
+ (ls : List Line) (pc : Fin (ls.length+1) → Fin p)
+ (hl : ∀ i : Fin ls.length, M.code (pc i.castSucc) = Line.emit reg pub (pc i.succ) ls[i])
+ (c : Config w p r) (hc : c.pc = pc 0) :
+ let v := eval (M.publicData ∘ pub) c.persistent m ls (c.reg ∘ reg) c.privateMem
+ ∃ out, out.pc = pc (Fin.last ls.length) ∧ out.persistent = c.persistent ∧
+ out.reg ∘ reg = v.2.1 ∧ out.privateMem = v.2.2 ∧
+ (∀ j, (∀ i, reg i ≠ j) → out.reg j = c.reg j) ∧ ∀ fuel bs,
+ execute M.program (fuel+v.1.length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep => ⟨v.1 ++ rep.events, rep.result⟩) := by
+ obtain ⟨out, hp, hst, hr, hm, hf, h⟩ := linear_walk M reg pub m ls pc hl c hc
+ exact ⟨out,hp,hst,hr,hm,hf,ReadPrefix.execute h⟩
+
+theorem linear_run (M : Machine w p r k) (reg : Reg ↪ Fin r) (pub : Fin 11 → Fin k) (m : Memory w)
+ (ls : List Line) (pc : Fin (ls.length+1) → Fin p)
+ (hl : ∀ i : Fin ls.length, M.code (pc i.castSucc) = Line.emit reg pub (pc i.succ) ls[i])
+ (c : Config w p r) (hc : c.pc = pc 0) :
+ let v := eval (M.publicData ∘ pub) c.persistent m ls (c.reg ∘ reg) c.privateMem
+ ∃ out, out.pc = pc (Fin.last ls.length) ∧ out.persistent = c.persistent ∧
+ out.reg ∘ reg = v.2.1 ∧ out.privateMem = v.2.2 ∧ ∀ fuel bs,
+ execute M.program (fuel+v.1.length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep => ⟨v.1 ++ rep.events, rep.result⟩) := by
+ obtain ⟨out, hp, hst, hr, hm, _, h⟩ := linear_walk M reg pub m ls pc hl c hc
+ exact ⟨out,hp,hst,hr,hm,ReadPrefix.execute h⟩
+
+end PairSimulation.TerminalSiteStart
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalSiteRun.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSiteRun.lean
new file mode 100644
index 0000000000..5e5ca80ec1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSiteRun.lean
@@ -0,0 +1,246 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalSiteStart
+import OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+/-! # Exact traces and private stack for the terminal-site guard -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalSiteStart
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+open private guessed_addFuel from OAI.Computability.VPVNP.PairSimulationDFSDecode
+open private field from OAI.Computability.VPVNP.PairSimulationTerminalSiteStart
+
+variable {w p r k : ℕ}
+
+private theorem pre_eval (pub : Fin 11 → Word w) (st : Word w) (m : Memory w)
+ (b : Reg → Word w) (priv : Word w → Word w) :
+ let h := headerWord pub
+ let v := eval pub st m pre b priv
+ v.1 = guardTrace m h ∧ GuardReady h st m v.2.1 ∧ v.2.2 = priv := by
+ refine ⟨?_, ⟨?_,?_,?_,?_⟩,?_⟩ <;> rfl
+
+private theorem boot_eval (pub : Fin 11 → Word w) (st h : Word w) (m : Memory w)
+ (b : Reg → Word w) (priv : Word w → Word w) (g : GuardReady h st m b) :
+ let v := eval pub st m boot b priv
+ v.1 = bootTrace m h ∧ BootReady (pub 6) h st m v.2.1 ∧
+ v.2.2 = Function.update priv (pub 6-1) (m (h+6).val + m (h+15).val * st) := by
+ dsimp only
+ refine ⟨?_, ⟨⟨?_,?_,?_,?_⟩,?_,?_,?_,?_,?_,?_,?_,?_,?_⟩, ?_⟩ <;>
+ simp [boot,field,eval,bootTrace,fieldTrace,BinaryOp.eval,
+ g.header,g.ordinal,g.sites,g.one]
+
+variable {M : Machine w p r k} {pc : Stage → Fin p} {reg : Reg ↪ Fin r} {pub : Fin 11 → Fin k}
+variable {geometry : Fin p}
+
+/-- A deterministic prefix has the indicated exact trace for every subsequent
+fuel and choice suffix. Its external memory is available to the continuation. -/
+def Continues (M : Machine w p r k) (m : Memory w) (c out : Config w p r) (es : List (Event w)) :=
+ ∀ fuel bs, execute M.program (fuel+es.length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep => ⟨es ++ rep.events, rep.result⟩)
+
+private theorem continues_tick {m : Memory w} {c out : Config w p r}
+ (s : M.program.step c = .localStep out) : Continues M m c out [.tick] := by
+ intro fuel bs
+ change execute M.program (fuel+1) c m bs = _
+ rw [execute,s]
+ rfl
+
+private theorem continues_trans {m : Memory w} {a b c : Config w p r} {es fs : List (Event w)}
+ (he : Continues M m a b es) (hf : Continues M m b c fs) : Continues M m a c (es++fs) := by
+ intro fuel bs
+ rw [List.length_append,show fuel+(es.length+fs.length) = (fuel+fs.length)+es.length by omega,
+ he _ _,hf _ _]
+ simp [Option.map_map,Function.comp_def,List.append_assoc]
+
+private theorem target_castSucc {n : ℕ} (label : Fin n → Fin p) (done : Fin p) (i : Fin n) :
+ target label done i.castSucc = label i := by simp [target,i.isLt]
+
+private theorem target_last {n : ℕ} (label : Fin n → Fin p) (done : Fin p) :
+ target label done (Fin.last n) = done := by simp [target]
+
+private theorem pre_run (link : StartLinked M pc reg pub geometry) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc entry) :
+ let h := headerWord (M.publicData ∘ pub)
+ ∃ out, out.pc = pc .equal ∧ out.persistent = c.persistent ∧ GuardReady h c.persistent m (out.reg ∘ reg) ∧
+ out.privateMem = c.privateMem ∧ Continues M m c out (guardTrace m h) := by
+ let atPc := target (pc ∘ Stage.pre) (pc .equal)
+ have rows (i : Fin pre.length) : M.code (atPc i.castSucc) = Line.emit reg pub (atPc i.succ) pre[i] := by
+ rw [show atPc i.castSucc = pc (.pre i) from target_castSucc .., link _ rfl]
+ rfl
+ obtain ⟨out, hp, hs, hr, hm, he⟩ := linear_run M reg pub m pre atPc rows c (by exact hc)
+ have ⟨et, ready, priv⟩ := pre_eval (M.publicData ∘ pub) c.persistent m (c.reg ∘ reg) c.privateMem
+ rw [et] at he
+ exact ⟨out,hp.trans (target_last ..),hs,hr.symm ▸ ready,hm.trans priv,he⟩
+
+private theorem boot_run (link : StartLinked M pc reg pub geometry) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc (.boot 0)) (h : Word w) (g : GuardReady h c.persistent m (c.reg ∘ reg)) :
+ let n := M.publicData (pub 6)
+ ∃ out, out.pc = geometry ∧ out.persistent = c.persistent ∧ BootReady n h c.persistent m (out.reg ∘ reg) ∧
+ out.privateMem = Function.update c.privateMem (n-1) (m (h+6).val + m (h+15).val * c.persistent) ∧
+ Continues M m c out (bootTrace m h) := by
+ let atPc := target (pc ∘ Stage.boot) geometry
+ have rows (i : Fin boot.length) : M.code (atPc i.castSucc) = Line.emit reg pub (atPc i.succ) boot[i] := by
+ rw [show atPc i.castSucc = pc (.boot i) from target_castSucc .., link _ rfl]
+ rfl
+ obtain ⟨out, hp, hs, hr, hm, he⟩ := linear_run M reg pub m boot atPc rows c (by exact hc)
+ have ⟨et,ready,priv⟩ := boot_eval (M.publicData ∘ pub) c.persistent h m (c.reg ∘ reg) c.privateMem g
+ rw [et] at he
+ exact ⟨out,hp.trans (target_last ..),hs,hr.symm ▸ ready,hm.trans priv,he⟩
+
+private theorem step_at (link : StartLinked M pc reg pub geometry) (j : Stage) (hj : j.bootstrap = true) (c : Config w p r)
+ (hc : c.pc = pc j) : M.program.step c = (instruction pc reg pub geometry j).run M.publicData c := by
+ simp only [Machine.program,hc,link j hj]
+
+/-- An active site supplies its exact root and both endpoint arrays to the geometry initializer. -/
+theorem active_run (link : StartLinked M pc reg pub geometry) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc entry) (ha : c.persistent < m (headerWord (M.publicData ∘ pub)+7).val) :
+ let h := headerWord (M.publicData ∘ pub)
+ let n := M.publicData (pub 6)
+ ∃ out, out.pc = geometry ∧ out.persistent = c.persistent ∧ BootReady n h c.persistent m (out.reg ∘ reg) ∧
+ out.privateMem = Function.update c.privateMem (n-1) (m (h+6).val + m (h+15).val * c.persistent) ∧
+ Continues M m c out (guardTrace m h ++ [.tick,.tick] ++ bootTrace m h) := by
+ let h := headerWord (M.publicData ∘ pub)
+ obtain ⟨a,hp,hs,g,hm,he⟩ := pre_run link m c hc
+ have ho : a.reg (reg (saved 2)) = c.persistent := g.ordinal
+ have hf : a.reg (reg (saved 5)) = m (h+7).val := g.sites
+ let b := {a with pc := pc .less}
+ let d := {a with pc := pc (.boot 0)}
+ have s₁ : M.program.step a = .localStep b := by
+ rw [step_at link .equal rfl _ hp]; simp [instruction,Instr.run,ho,hf,ne_of_lt ha,b,h]
+ have s₂ : M.program.step b = .localStep d := by
+ rw [step_at link .less rfl _ rfl]; simp [instruction,Instr.run,b,d,ho,hf,ha,h]
+ have hd : GuardReady h d.persistent m (d.reg ∘ reg) := hs.symm ▸ g
+ obtain ⟨out,hpc,hper,ready,hpriv,hboot⟩ := boot_run link m d rfl h hd
+ have run := continues_trans (continues_trans he (continues_trans (continues_tick s₁) (continues_tick s₂))) hboot
+ refine ⟨out,hpc,hper.trans hs,?_,?_,run⟩
+ · simpa only [d,hs,h] using ready
+ · simpa only [d,hm,hs,h] using hpriv
+
+/-- Reaching the terminal ordinal accepts on the next test, consuming no choices. -/
+theorem equal_run (link : StartLinked M pc reg pub geometry) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc entry) (ha : c.persistent = m (headerWord (M.publicData ∘ pub)+7).val)
+ (fuel : ℕ) (bs : List Bool) :
+ let h := headerWord (M.publicData ∘ pub)
+ execute M.program (fuel+15) c m bs = if bs = [] then some ⟨guardTrace m h ++ [.tick],none⟩ else none := by
+ obtain ⟨a,hp,_,g,_,he⟩ := pre_run link m c hc
+ let d := {a with pc := pc .accept}
+ have eq : a.reg (reg (saved 2)) = a.reg (reg (saved 5)) := g.ordinal.trans (ha.trans g.sites.symm)
+ have s : M.program.step a = .localStep d := by
+ rw [step_at link .equal rfl _ hp]; simp [instruction,Instr.run,eq,d]
+ have fin : M.program.step d = .finish none := step_at link .accept rfl _ rfl
+ change execute M.program ((fuel+2)+(guardTrace m (headerWord (M.publicData ∘ pub))).length) c m bs = _
+ rw [he (fuel.succ.succ) bs]
+ simp only [execute,s,fin]
+ split <;> rfl
+
+/-- An ordinal past the last site takes the rejecting branch. -/
+theorem late_run (link : StartLinked M pc reg pub geometry) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc entry) (ha : m (headerWord (M.publicData ∘ pub)+7).val < c.persistent)
+ (fuel : ℕ) (bs : List Bool) : execute M.program (fuel+16) c m bs = none := by
+ obtain ⟨a,hp,_,g,_,he⟩ := pre_run link m c hc
+ have lt : a.reg (reg (saved 5)) < a.reg (reg (saved 2)) := by
+ change (a.reg ∘ reg) (saved 5) < (a.reg ∘ reg) (saved 2)
+ rwa [g.sites,g.ordinal]
+ let b := {a with pc := pc .less}
+ let d := {a with pc := pc .reject}
+ have s : M.program.step a = .localStep b := by
+ rw [step_at link .equal rfl _ hp]; simp [instruction,Instr.run,ne_of_gt lt,b]
+ have s' : M.program.step b = .localStep d := by
+ rw [step_at link .less rfl _ rfl]; simp [instruction,Instr.run,b,d,not_lt_of_gt lt]
+ have fin : M.program.step d = .reject := step_at link .reject rfl _ rfl
+ change execute M.program ((fuel+3)+(guardTrace m (headerWord (M.publicData ∘ pub))).length) c m bs = none
+ rw [he (fuel.succ.succ.succ) bs]
+ simp only [execute,s,s',fin,Option.map_none]
+
+/-- Sufficient fuel cannot turn a malformed ordinal into a returning path. -/
+theorem late_reject (link : StartLinked M pc reg pub geometry) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc entry) (ha : m (headerWord (M.publicData ∘ pub)+7).val < c.persistent)
+ (bs : List Bool) : ¬ DFS.Returns M c m bs := by
+ rintro ⟨f,rep,he⟩
+ obtain ⟨hg,hmem,hbits⟩ := execute_iff.mp he
+ have big := execute_iff.mpr ⟨guessed_addFuel hg 16,hmem,hbits⟩
+ rw [Nat.add_comm 16 f,late_run link m c hc ha] at big
+ contradiction
+
+/-- The terminal ordinal has exactly its empty-choice accepting path. -/
+theorem equal_terminal (link : StartLinked M pc reg pub geometry) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc entry) (ha : c.persistent = m (headerWord (M.publicData ∘ pub)+7).val)
+ (bs : List Bool) : DFS.Returns M c m bs ↔ bs = [] := by
+ constructor
+ · rintro ⟨f,rep,he⟩
+ obtain ⟨hg,hmem,hbits⟩ := execute_iff.mp he
+ have big := execute_iff.mpr ⟨guessed_addFuel hg 15,hmem,hbits⟩
+ rw [Nat.add_comm 15 f,equal_run link m c hc ha] at big
+ split at big <;> simp_all
+ · rintro rfl
+ exact ⟨15, _, by simpa using equal_run link m c hc ha 0 []⟩
+
+private theorem finish_step (link : FinishLinked M pc reg pub geometry) (j : Stage) (hj : j.bootstrap = false)
+ (c : Config w p r) (hc : c.pc = pc j) : M.program.step c = (instruction pc reg pub geometry j).run M.publicData c :=
+ by simp only [Machine.program,hc,link j hj]
+
+/-- After the histogram flush, read the original ordinal afresh and return
+its successor. All four rows work with arbitrary registers and private cells. -/
+theorem finish_run (link : FinishLinked M pc reg pub geometry) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc .increment) (fuel : ℕ) (bs : List Bool) :
+ execute M.program fuel c m bs = if 4 ≤ fuel ∧ bs = [] then
+ some ⟨[.tick,.tick,.tick],some (c.persistent+1)⟩ else none := by
+ let a := c.put (pc .unit) (reg (saved 2)) c.persistent
+ let b := a.put (pc .add) (reg (work 0)) 1
+ let d := b.put (pc .finish) (reg (saved 2)) (c.persistent+1)
+ have hs : M.program.step c = .localStep a := finish_step link .increment rfl _ hc
+ have hs' : M.program.step a = .localStep b := finish_step link .unit rfl _ rfl
+ have hs'' : M.program.step b = .localStep d := by
+ rw [finish_step link .add rfl _ rfl]; simp [instruction,Instr.run,BinaryOp.eval,d,b,a,Config.put]
+ have hfin : M.program.step d = .finish (some (c.persistent+1)) := by
+ rw [finish_step link .finish rfl _ rfl]; simp [instruction,Instr.run,d]
+ rcases fuel with _|(_|(_|(_|f))) <;>
+ simp only [execute,hs,hs',hs'',hfin,Option.map_none] <;>
+ first | rfl | (simp [show 4 ≤ f+1+1+1+1 by omega]; split <;> rfl)
+
+theorem finish_terminal (link : FinishLinked M pc reg pub geometry) (m : Memory w) (c : Config w p r)
+ (hc : c.pc = pc .increment) (bs : List Bool) : DFS.Returns M c m bs ↔ bs = [] := by
+ constructor
+ · rintro ⟨f,rep,hr⟩
+ rw [finish_run link m c hc] at hr
+ split at hr <;> simp_all
+ · rintro rfl
+ exact ⟨4, _, by simpa using finish_run link m c hc 4 []⟩
+
+/-- The entry trace and continuation trace have fixed local and external costs. -/
+theorem active_caps (m : Memory w) (h : Word w) :
+ let es := guardTrace m h ++ [.tick,.tick] ++ bootTrace m h
+ es.length = 44 ∧ countProbes es = 9 ∧ choiceBits es = [] := by
+ exact ⟨rfl,rfl,rfl⟩
+
+/-- A fresh burst starts with zero private cells. At geometry entry its one
+pending descriptor is the root and all other cells still have value zero. -/
+theorem fresh_stack (link : StartLinked M pc reg pub geometry) (m : Memory w) (st : Word w)
+ (hc : M.entry = pc entry) (ha : st < m (headerWord (M.publicData ∘ pub)+7).val)
+ (n : ℕ) (hn : M.publicData (pub 6) = (n : Word w)) (npos : 0 < n) (nfit : n < 2^w) :
+ let h := headerWord (M.publicData ∘ pub)
+ let root := m (h+6).val + m (h+15).val * st
+ ∃ out, out.pc = geometry ∧ out.persistent = st ∧ BootReady (n : Word w) h st m (out.reg ∘ reg) ∧
+ DFS.Represents out.privateMem (n-1) [root] ∧ out.privateMem = Function.update (fun _ => 0) ((n-1 : ℕ) : Word w) root ∧
+ Continues M m (M.program.start st) out (guardTrace m h ++ [.tick,.tick] ++ bootTrace m h) := by
+ obtain ⟨out,hp,hs,ready,hm,hr⟩ := active_run link m (M.program.start st) hc ha
+ have sub : (n : Word w) - 1 = ((n-1 : ℕ) : Word w) := by
+ obtain ⟨j,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : n ≠ 0)
+ simp
+ rw [hn,sub] at hm
+ refine ⟨out,hp,hs,hn ▸ ready,⟨by simp; omega,?_⟩,hm,hr⟩
+ intro i
+ have hz : i.val = 0 := by have hi : i.val < 1 := i.isLt; omega
+ have hi : i = 0 := Fin.ext hz
+ subst i
+ simp [hm, Machine.program]
+
+end PairSimulation.TerminalSiteStart
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalSiteStart.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSiteStart.lean
new file mode 100644
index 0000000000..eb305aebcb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSiteStart.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalSiteLinear
+
+/-!
+# The final-site ordinal guard and DFS entry
+
+The persistent word selects a final vertex. Its row address and the endpoint
+array heads are read from the header in the pair workspace. The private
+stack is initialized with just that vertex's descriptor before entering the
+geometry initializer. The flush continuation returns the next ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalSiteStart
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+variable {w p r k : ℕ}
+
+/-- Form the pair-workspace header, then fetch the final vertex count. -/
+def pre : List Line :=
+ [.lit (dfs 3) 1, .pub (saved 4) 2, .pub (work 0) 7,
+ .bin .shiftLeft (work 0) (dfs 3) (work 0), .bin .mul (work 0) (work 0) (work 0),
+ .bin .add (saved 4) (saved 4) (work 0), .lit (work 0) 16, .bin .add (work 0) (work 0) (work 0),
+ .bin .sub (saved 4) (saved 4) (work 0), .state (saved 2),
+ .lit (work 0) 7, .bin .add (work 0) (saved 4) (work 0), .read (saved 5) (work 0)]
+
+private def field (i : Fin 32) (dst : Reg) : List Line :=
+ [.lit (work 0) i, .bin .add (work 0) (saved 4) (work 0), .read dst (work 0)]
+
+/-- Fetch the endpoint array heads, form the root row, and store its address
+as the only pending DFS visit. -/
+def boot : List Line :=
+ field 6 (saved 3) ++ field 8 (saved 6) ++ field 9 (saved 7) ++ field 10 (saved 8) ++
+ field 11 (saved 9) ++ field 13 (saved 10) ++ field 14 (saved 0) ++ field 15 (work 1) ++
+ [.bin .mul (work 1) (work 1) (saved 2), .bin .add (saved 3) (saved 3) (work 1),
+ .pub (dfs 6) 6, .bin .sub (dfs 5) (dfs 6) (dfs 3), .store (dfs 5) (saved 3)]
+
+/-- Instruction labels for the site ordinal guard, initialization of its DFS root and the flush
+continuation that returns the next ordinal. -/
+inductive Stage where
+ | pre (i : Fin 13) | equal | less | accept | reject | boot (i : Fin 29)
+ | increment | unit | add | finish
+ deriving DecidableEq, Fintype
+
+/-- First instruction of the site guard, where the bootstrap begins preparing the header and
+ordinal comparison. -/
+abbrev entry : Stage := .pre 0
+
+/-- Resolves the next position in a straight-line block to its instruction label, using the
+supplied continuation at the position just past the block. -/
+def target {n : ℕ} (label : Fin n → Fin p) (done : Fin p) (i : Fin (n+1)) : Fin p :=
+ if hi : i.val < n then label ⟨i.val, hi⟩ else done
+
+/-- Relocate the site entry and the flush continuation into the finite vertex table. -/
+def instruction (pc : Stage → Fin p) (reg : Reg → Fin r) (pub : Fin 11 → Fin k) (geometry : Fin p) :
+ Stage → Instr w p r k
+ | .pre i => Line.emit reg pub (target (pc ∘ Stage.pre) (pc .equal) i.succ) pre[i]
+ | .equal => .jumpEq (reg (saved 2)) (reg (saved 5)) (pc .accept) (pc .less)
+ | .less => .jumpLt (reg (saved 2)) (reg (saved 5)) (pc (.boot 0)) (pc .reject)
+ | .accept => .accept
+ | .reject => .reject
+ | .boot i => Line.emit reg pub (target (pc ∘ Stage.boot) geometry i.succ) boot[i]
+ | .increment => .stateWord (reg (saved 2)) (pc .unit)
+ | .unit => .constant (reg (work 0)) 1 (pc .add)
+ | .add => .binary .add (reg (saved 2)) (reg (saved 2)) (reg (work 0)) (pc .finish)
+ | .finish => .returnState (reg (saved 2))
+
+theorem resize_instruction (pc : Stage → Fin p) (reg : Reg → Fin r) (pub : Fin 11 → Fin k)
+ (geometry : Fin p) (i : Stage) :
+ (instruction (w := 5) pc reg pub geometry i).resize w = instruction pc reg pub geometry i := by
+ cases i <;> first | exact Line.resize_emit .. | rfl
+
+/-- Requires all bootstrap and flush instructions to be installed at their stage labels with
+the specified registers, public ports and geometry entry. -/
+def Linked (M : Machine w p r k) (pc : Stage → Fin p) (reg : Reg → Fin r)
+ (pub : Fin 11 → Fin k) (geometry : Fin p) : Prop :=
+ ∀ j, M.code (pc j) = instruction pc reg pub geometry j
+
+/-- Classifies guard and initialization labels as bootstrap rows and the four ordinal-return
+instructions as flush rows, allowing each part to be linked separately. -/
+def Stage.bootstrap : Stage → Bool
+ | .increment | .unit | .add | .finish => false
+ | _ => true
+
+/-- Only entry and guard rows are required before transferring to the geometry code. -/
+def StartLinked (M : Machine w p r k) (pc : Stage → Fin p) (reg : Reg → Fin r)
+ (pub : Fin 11 → Fin k) (geometry : Fin p) : Prop :=
+ ∀ j, j.bootstrap = true → M.code (pc j) = instruction pc reg pub geometry j
+
+/-- The flush continuation uses exactly its four designated labels. -/
+def FinishLinked (M : Machine w p r k) (pc : Stage → Fin p) (reg : Reg → Fin r)
+ (pub : Fin 11 → Fin k) (geometry : Fin p) : Prop :=
+ ∀ j, j.bootstrap = false → M.code (pc j) = instruction pc reg pub geometry j
+
+/-- The numerical header address before interpreting its words. -/
+def headerWord (pub : Fin 11 → Word w) : Word w :=
+ let R := BinaryOp.shiftLeft.eval 1 (pub 7)
+ pub 2 + R * R - (16 + 16)
+
+/-- On well-sized words the computed header is the address allocated by the terminal calendar. -/
+theorem headerWord_eq (pub : Fin 11 → Word w) (base r : ℕ) (hb : pub 2 = (base : Word w))
+ (hr : (pub 7).val = r) (hrw : r < w) (h32 : 32 ≤ base + 2^r * 2^r) :
+ headerWord pub = ((base + 2^r*2^r-32 : ℕ) : Word w) := by
+ have one : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega))
+ have hp : BinaryOp.shiftLeft.eval (1 : Word w) (pub 7) = ((2^r : ℕ) : Word w) := by
+ simp only [BinaryOp.eval,hr,ite_eq_left hrw,one,Nat.one_shiftLeft,Fin.ofNat_eq_cast]
+ rw [headerWord, hp, hb, Nat.cast_sub h32,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat]
+ ring
+
+/-- Header-relative physical read and the preceding address instructions. -/
+def fieldTrace (m : Memory w) (h : Word w) (i : ℕ) : List (Event w) :=
+ [.tick, .tick, .read (h + (i : Word w)) (m (h + (i : Word w)).val)]
+
+/-- Trace before the site ordinal comparison, with ten setup ticks followed by address
+calculation and the external read of the final site count at header offset seven. -/
+def guardTrace (m : Memory w) (h : Word w) : List (Event w) :=
+ List.replicate 10 .tick ++ fieldTrace m h 7
+
+/-- Trace for an active site's DFS initialization. Eight header field reads supply the root and
+layout data, followed by five ticks that compute the root address and push it onto the
+private stack. -/
+def bootTrace (m : Memory w) (h : Word w) : List (Event w) :=
+ [6,8,9,10,11,13,14,15].flatMap (fieldTrace m h) ++ List.replicate 5 .tick
+
+/-- Bank before branching on the ordinal. -/
+structure GuardReady (h st : Word w) (m : Memory w) (b : Reg → Word w) : Prop where
+ one : b (dfs 3) = 1
+ header : b (saved 4) = h
+ ordinal : b (saved 2) = st
+ sites : b (saved 5) = m (h+7).val
+
+/-- The local bank passed to the private geometry initializer. -/
+structure BootReady (n h st : Word w) (m : Memory w) (b : Reg → Word w) : Prop extends GuardReady h st m b where
+ root : b (saved 3) = m (h+6).val + m (h+15).val * st
+ slots : b (saved 6) = m (h+8).val
+ widths : b (saved 7) = m (h+9).val
+ incoming : b (saved 8) = m (h+10).val
+ prefixPtr : b (saved 9) = m (h+11).val
+ wires : b (saved 10) = m (h+13).val
+ roleOffset : b (saved 0) = m (h+14).val
+ top : b (dfs 5) = n-1
+ stackEnd : b (dfs 6) = n
+
+end PairSimulation.TerminalSiteStart
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalSplice.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSplice.lean
new file mode 100644
index 0000000000..1da4bb69fe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSplice.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalCall
+import OAI.Computability.VPVNP.CompressorSourceTransport
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+
+/-!
+# Splicing ordinary worker stages into the terminal table
+
+A closed stage can be run from a physical memory that differs from its source
+memory on the two terminal control cells. Source reads avoid those cells.
+Worker writes propagate to both memories, and the terminal controller updates
+the stage and saved word between calls. The final accepting call either starts
+the next worker at zero or halts the terminal table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM LiveProgram CompressorRecords
+
+variable {w : ℕ}
+
+/-- An external address outside the two terminal-controller cells. -/
+def workerCell (addr : Word w) (i : ℕ) : Prop := i ≠ addr.val ∧ i ≠ (addr+31).val
+
+/-- Entry state selected by the final accepting call of a worker. -/
+def handoff (s : Stage) : Option (Entry w) := (next s).map (fun t => .resume t 0)
+
+/-- Attach each call's entry and exit events, restoring the cursor returned
+by the preceding call. A closed source stage has one accepting call at its end. -/
+def stageReports (addr : Word w) : Entry w → List (Report w) → List (Report w)
+ | _, [] => []
+ | e, raw :: more => report addr e raw :: stageReports addr (.resume e.stage (raw.result.getD 0)) more
+
+@[simp] theorem length_stageReports (addr : Word w) (e : Entry w) (raws : List (Report w)) :
+ (stageReports addr e raws).length = raws.length := by
+ induction raws generalizing e <;> simp_all [stageReports]
+
+private theorem after_cons (m : Memory w) (raw : Report w) (rs : List (Report w)) :
+ after m (eventLog (raw::rs)) = after (after m raw.events) (eventLog rs) := List.foldl_append
+
+private theorem report_agree (addr : Word w) (e : Entry w) (raw : Report w) (src phy : Memory w)
+ (agree : SourceTransport.Agree (workerCell addr) src phy) :
+ SourceTransport.Agree (workerCell addr) (after src raw.events) (after phy (report addr e raw).events) := by
+ rw [report_after]
+ cases ht : target e.stage raw.result with
+ | none => exact agree.after _
+ | some sv =>
+ obtain ⟨s,v⟩ := sv
+ intro i hi
+ simpa [writeMemory,hi.1,hi.2] using agree.after raw.events i hi
+
+variable (workers : Stage → PairTable) (pub : Fin 11 → Word w)
+
+/-- The native reports, persistent handoff and the memory conditions needed to
+splice the next stage at the end of this particular closed stage. -/
+structure StageRun (cap : ℕ) (e : Entry w) (src phy : Memory w) (bs : List (List Bool)) (raws : List (Report w)) : Prop where
+ run : runSegment (program workers pub) cap (some e.marker) phy bs =
+ some (stageReports (header pub) e raws)
+ state : endState (some e.marker) (stageReports (header pub) e raws) = (handoff e.stage).map Entry.marker
+ agree : SourceTransport.Agree (workerCell (header pub)) (after src (eventLog raws))
+ (after phy (eventLog (stageReports (header pub) e raws)))
+ valid : ∀ t, handoff e.stage = some t → t.Valid (header pub) (after phy (eventLog (stageReports (header pub) e raws)))
+
+/-- Replay the worker's own choices in the terminal machine. Correctness of
+each source read is transported through memory agreement before executing that
+call, and agreement is re-established after its physical exit. -/
+theorem closed_stage_run (f cap : ℕ) (e : Entry w) (src phy : Memory w) (bs : List (List Bool))
+ (raws : List (Report w)) (fit : 32 ≤ 2^w) (room : f+30 ≤ cap) (valid : e.Valid (header pub) phy)
+ (agree : SourceTransport.Agree (workerCell (header pub)) src phy)
+ (reads : SourceTransport.Reads (workerCell (header pub)) (eventLog raws))
+ (run : runSegment (source workers e.stage pub) f (some e.state) src bs = some raws)
+ (halt : endState (some e.state) raws = none) :
+ StageRun workers pub cap e src phy bs raws := by
+ induction bs generalizing e src phy raws with
+ | nil =>
+ have he : raws = [] := by simpa [runSegment] using run.symm
+ simp [he,endState] at halt
+ | cons b bs ih =>
+ cases hraw : execute (source workers e.stage pub) f ((source workers e.stage pub).start e.state) src b with
+ | none => simp [runSegment,hraw] at run
+ | some raw =>
+ simp only [runSegment,hraw,Option.map_eq_some_iff] at run
+ obtain ⟨rs,tail,rfl⟩ := run
+ have readHead : SourceTransport.Reads (workerCell (header pub)) raw.events :=
+ fun a v h => reads a v (List.mem_append_left (eventLog rs) h)
+ have readTail : SourceTransport.Reads (workerCell (header pub)) (eventLog rs) :=
+ fun a v h => reads a v (List.mem_append_right raw.events h)
+ obtain ⟨guessed,correct,bits⟩ := execute_spec hraw
+ have physical : execute (source workers e.stage pub) f ((source workers e.stage pub).start e.state) phy b =
+ some raw := execute_iff.mpr ⟨guessed,SourceTransport.correct agree readHead correct,bits⟩
+ have linkedRun := call_of_room workers pub cap e phy b (by omega) valid f raw physical room
+ have cells := report_agree (header pub) e raw src phy agree
+ change endState raw.result rs = none at halt
+ cases hx : raw.result with
+ | none =>
+ rw [hx] at tail
+ cases bs with
+ | cons b bs => simp [runSegment] at tail
+ | nil =>
+ have hrs : rs = [] := by simpa [runSegment] using tail.symm
+ subst rs
+ have hnext : e.follow raw = handoff e.stage := by
+ simp [Entry.follow,handoff,target,hx,Option.map_map,Function.comp_def]
+ constructor
+ · simp [runSegment,linkedRun,stageReports]
+ · simp [stageReports,endState,report_result,hnext]
+ · simpa [stageReports,eventLog,after] using cells
+ · intro t ht
+ have hvalid := next_valid (header pub) e t raw phy fit (hnext.trans ht)
+ simpa [stageReports,eventLog,after] using hvalid
+ | some v =>
+ let e' : Entry w := .resume e.stage v
+ have follows : e.follow raw = some e' := by simp [Entry.follow,target,hx,e']
+ have live := next_valid (header pub) e e' raw phy fit follows
+ have endWord : (report (header pub) e raw).result = some e'.marker := by rw [report_result,follows]; rfl
+ rw [hx] at tail halt
+ have rest := ih (e := e') (src := after src raw.events) (phy := after phy (report (header pub) e raw).events)
+ (raws := rs) live cells readTail tail halt
+ constructor
+ · simp only [runSegment,linkedRun,endWord,rest.run,stageReports,hx,Option.getD_some,Option.map_some,e']
+ · simpa only [stageReports,hx,Option.getD_some,endState,endWord,e',Entry.stage] using rest.state
+ · simpa only [stageReports,hx,Option.getD_some,after_cons] using rest.agree
+ · simpa only [stageReports,hx,Option.getD_some,after_cons,e',Entry.stage] using rest.valid
+
+/-- Continuing a linked execution consumes the stage's entire branch prefix
+and resumes from its exact physical memory and marker. -/
+theorem StageRun.append {workers : Stage → PairTable} {pub : Fin 11 → Word w} {cap : ℕ} {e : Entry w}
+ {src phy : Memory w} {bs : List (List Bool)} {raws : List (Report w)}
+ (h : StageRun workers pub cap e src phy bs raws) (tail : List (List Bool)) :
+ let L := program workers pub
+ let out := stageReports (header pub) e raws
+ runSegment L cap (some e.marker) phy (bs++tail) =
+ (runSegment L cap ((handoff e.stage).map Entry.marker) (after phy (eventLog out)) tail).map (out++·) := by
+ dsimp only
+ rw [PrimedSchedule.runSegment_append,h.run,Option.bind_some,h.state]
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalSplit.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSplit.lean
new file mode 100644
index 0000000000..ce93fc4b4a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalSplit.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalVisits
+import OAI.Computability.VPVNP.PairSimulationTerminalSplice
+
+/-!
+# Recovering each terminal stage from an accepted native traversal
+
+Split at the first accepting exit of the currently selected worker.
+A worker return stays within the same stage with its exact returned word.
+The split preserves the remaining DFS calls, their memory and their bit
+strings. Away from the two controller cells the recovered worker can be
+replayed as an ordinary RAM segment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM LiveProgram CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ} (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap : ℕ)
+
+/-- All calls of one worker up to and including its accepting exit. -/
+inductive Phase : Entry w → Memory w → List (List Bool) → List (Log w) → Memory w → Prop
+ | last {e m bs raw}
+ (call : execute (source workers e.stage pub) (rawFuel pub cap e)
+ ((source workers e.stage pub).start e.state) m bs = some raw)
+ (room : (exitReport (header pub) e.stage raw).events.length < rawFuel pub cap e)
+ (accepted : raw.result = none) :
+ Phase e m [bs] [(e,raw)] (after m (report (header pub) e raw).events)
+ | more {e m b bs raw x ls final}
+ (call : execute (source workers e.stage pub) (rawFuel pub cap e)
+ ((source workers e.stage pub).start e.state) m b = some raw)
+ (room : (exitReport (header pub) e.stage raw).events.length < rawFuel pub cap e)
+ (returned : raw.result = some x)
+ (tail : Phase (.resume e.stage x) (after m (report (header pub) e raw).events) bs ls final) :
+ Phase e m (b::bs) ((e,raw)::ls) final
+
+private theorem follow_halt (e : Entry w) (raw : Report w) (h : raw.result = none) :
+ e.follow raw = handoff e.stage := by cases hn : next e.stage <;> simp [Entry.follow,target,h,handoff,hn]
+
+private theorem follow_return (e : Entry w) (raw : Report w) {x : Word w} (h : raw.result = some x) :
+ e.follow raw = some (.resume e.stage x) := by simp [Entry.follow,target,h]
+
+theorem split_stage (e : Entry w) (m : Memory w) (bs : List (List Bool)) (ls : List (Log w))
+ (visits : Visits workers pub cap (some e) m bs ls) (closed : finish (some e) ls = none) :
+ ∃ first more rs rest final, bs = first++more ∧ ls = rs++rest ∧
+ Phase workers pub cap e m first rs final ∧ Visits workers pub cap (handoff e.stage) final more rest ∧
+ finish (handoff e.stage) rest = none := by
+ induction bs generalizing e m ls with
+ | nil => cases visits; contradiction
+ | cons b bs ih =>
+ cases visits with
+ | @cons _ _ _ _ raw tail hc room later =>
+ change finish (e.follow raw) tail = none at closed
+ cases h : raw.result with
+ | none =>
+ rw [follow_halt e raw h] at later closed
+ exact ⟨[b],bs,[(e,raw)],tail,_,rfl,rfl,.last hc room h,later,closed⟩
+ | some x =>
+ rw [follow_return e raw h] at later closed
+ obtain ⟨first,more,rs,rest,final, hb,hl,ph,remaining,last⟩ :=
+ ih (.resume e.stage x) _ tail later closed
+ exact ⟨b::first,more,(e,raw)::rs,rest,final,by rw [hb]; rfl,by rw [hl]; rfl,
+ .more hc room h ph,remaining,last⟩
+
+private theorem transfer_call {C : Type*} {P : BurstRAM.Program w C} {f : ℕ} {c : C} {m m' : Memory w}
+ {bs : List Bool} {raw : Report w} {data : ℕ → Prop}
+ (run : execute P f c m bs = some raw) (agree : SourceTransport.Agree data m m')
+ (reads : SourceTransport.Reads data raw.events) : execute P f c m' bs = some raw := by
+ obtain ⟨path,correct,choices⟩ := execute_spec run
+ exact execute_iff.mpr ⟨path,SourceTransport.correct agree reads correct,choices⟩
+
+private theorem agree_report (addr : Word w) (e : Entry w) (raw : Report w) (src phy : Memory w)
+ (agree : SourceTransport.Agree (workerCell addr) src phy) :
+ SourceTransport.Agree (workerCell addr) (after src raw.events) (after phy (report addr e raw).events) := by
+ intro i hi
+ rw [report_after]
+ cases ht : target e.stage raw.result with
+ | none => exact agree.after raw.events i hi
+ | some x =>
+ cases x
+ simpa only [writeMemory,ite_eq_right hi.2,ite_eq_right hi.1] using agree.after raw.events i hi
+
+/-- Recover the completed original worker, with every header transfer
+removed from its output memory and every genuine branch string retained. -/
+theorem Phase.source_segment {e m bs ls final} (ph : Phase workers pub cap e m bs ls final)
+ (src : Memory w) (agree : SourceTransport.Agree (workerCell (header pub)) src m)
+ (reads : SourceTransport.Reads (workerCell (header pub)) (eventLog (ls.map Prod.snd))) :
+ runSegment (source workers e.stage pub) cap (some e.state) src bs = some (ls.map Prod.snd) ∧
+ endState (some e.state) (ls.map Prod.snd) = none ∧
+ SourceTransport.Agree (workerCell (header pub)) (after src (eventLog (ls.map Prod.snd))) final := by
+ induction ph generalizing src with
+ | @last e m b raw run _ accepted =>
+ have rr : SourceTransport.Reads (workerCell (header pub)) raw.events := by simpa [eventLog] using reads
+ have rawRun := transfer_call run (fun i hi => (agree i hi).symm) rr
+ have hle : rawFuel pub cap e ≤ cap := Nat.sub_le ..
+ have full : execute _ cap _ src b = some raw :=
+ Nat.add_sub_of_le hle ▸ execute_extend rawRun (cap-rawFuel pub cap e)
+ exact ⟨by simp [runSegment,full],by simp [endState,accepted],
+ by simpa [eventLog] using agree_report (header pub) e raw src m agree⟩
+ | @more e m b bs raw x ls final run _ returned tail ih =>
+ change SourceTransport.Reads _ (raw.events++eventLog (ls.map Prod.snd)) at reads
+ have headRead : SourceTransport.Reads _ raw.events := fun a v h => reads a v (List.mem_append_left _ h)
+ have tailRead : SourceTransport.Reads _ (eventLog (ls.map Prod.snd)) := fun a v h => reads a v (List.mem_append_right _ h)
+ have hr := transfer_call run (fun i hi => (agree i hi).symm) headRead
+ have hle : rawFuel pub cap e ≤ cap := Nat.sub_le ..
+ have full : execute _ cap _ src b = some raw :=
+ Nat.add_sub_of_le hle ▸ execute_extend hr (cap-rawFuel pub cap e)
+ obtain ⟨hs,hend,ha⟩ := ih (after src raw.events) (agree_report (header pub) e raw src m agree) tailRead
+ change runSegment (source workers e.stage pub) cap (some x) _ _ = _ at hs
+ refine ⟨by simp [runSegment,full,returned,hs],by simpa [endState,returned,Entry.state] using hend,?_⟩
+ simpa only [List.map_cons,eventLog,List.flatMap_cons,after,List.foldl_append] using ha
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalTraceEquiv.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalTraceEquiv.lean
new file mode 100644
index 0000000000..21636aff84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalTraceEquiv.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalFive
+
+/-!
+# Uniqueness of the five terminal phases
+
+The accepting exit of each worker uniquely determines its block of physical
+calls. Concatenating the five blocks therefore gives a bijection with the
+native accepted paths, for any predicate on the full sequence of reports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM LiveProgram
+
+variable {w : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w} {cap : ℕ}
+
+/-- Two complete runs of the same worker on prefixes of a common call stream
+consume the same prefix and leave the same reports, memory and suffix. -/
+theorem Phase.unique_prefix {e m xs ls final}
+ (left : Phase workers pub cap e m xs ls final)
+ {ys rs nextMemory} (right : Phase workers pub cap e m ys rs nextMemory)
+ {a b : List (List Bool)} (same : xs ++ a = ys ++ b) :
+ xs = ys ∧ ls = rs ∧ final = nextMemory ∧ a = b := by
+ induction left generalizing ys rs nextMemory with
+ | @last e m x raw called room accepted =>
+ cases right with
+ | @last _ _ y out called' room' accepted' =>
+ obtain ⟨rfl, hab⟩ := List.cons.inj same
+ obtain rfl := Option.some.inj (called.symm.trans called')
+ exact ⟨rfl, rfl, rfl, hab⟩
+ | @more _ _ y ys out j rs nextMemory called' room' returned' later =>
+ obtain ⟨rfl, _⟩ := List.cons.inj same
+ obtain rfl := Option.some.inj (called.symm.trans called')
+ rw [accepted] at returned'
+ contradiction
+ | @more e m x xs raw i ls final called room returned tail ih =>
+ cases right with
+ | @last _ _ y out called' room' accepted' =>
+ obtain ⟨rfl, _⟩ := List.cons.inj same
+ obtain rfl := Option.some.inj (called.symm.trans called')
+ rw [accepted'] at returned
+ contradiction
+ | @more _ _ y ys out j rs nextMemory called' room' returned' later =>
+ obtain ⟨rfl, rest⟩ := List.cons.inj same
+ obtain rfl := Option.some.inj (called.symm.trans called')
+ obtain rfl := Option.some.inj (returned.symm.trans returned')
+ obtain ⟨rfl, rfl, rfl, hab⟩ := ih later rest
+ exact ⟨rfl, rfl, rfl, hab⟩
+
+/-- The terminal cut determines the full block and its remaining choice stream. -/
+theorem Phase.block_eq_suffix {e m} {x y : Block w}
+ (hx : Phase workers pub cap e m x.choices x.logs x.memory)
+ (hy : Phase workers pub cap e m y.choices y.logs y.memory)
+ {a b : List (List Bool)} (same : x.choices ++ a = y.choices ++ b) :
+ x = y ∧ a = b := by
+ obtain ⟨choices, logs, mem, suffix⟩ := hx.unique_prefix hy same
+ cases x
+ cases y
+ exact ⟨by congr, suffix⟩
+
+/-- The entire five-phase trace, including the reports and each intermediate
+memory, is uniquely determined by the sequence of native branch strings. -/
+theorem FiveTrace.choices_injective {m : Memory w} :
+ Function.Injective (FiveTrace.choices (workers := workers) (pub := pub) (cap := cap) (m := m)) := by
+ rintro ⟨x₀, x₁, x₂, x₃, x₄, p₀, p₁, p₂, p₃, p₄⟩ ⟨y₀, y₁, y₂, y₃, y₄, q₀, q₁, q₂, q₃, q₄⟩ h
+ change x₀.choices ++ (x₁.choices ++ (x₂.choices ++ (x₃.choices ++ x₄.choices))) =
+ y₀.choices ++ (y₁.choices ++ (y₂.choices ++ (y₃.choices ++ y₄.choices))) at h
+ obtain ⟨rfl, h₁⟩ := Phase.block_eq_suffix p₀ q₀ h
+ obtain ⟨rfl, h₂⟩ := Phase.block_eq_suffix p₁ q₁ h₁
+ obtain ⟨rfl, h₃⟩ := Phase.block_eq_suffix p₂ q₂ h₂
+ obtain ⟨rfl, h₄⟩ := Phase.block_eq_suffix p₃ q₃ h₃
+ obtain ⟨rfl, _⟩ := Phase.block_eq_suffix p₄ q₄ (a := []) (b := []) (by simpa using h₄)
+ rfl
+
+/-- Concatenate the choices of the five admissible phases to obtain the
+corresponding accepting path of the linked native program. -/
+noncomputable def fiveTraceEquiv (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap : ℕ)
+ (m : Memory w) (ok : List (Report w) → Prop) (fit : 32 ≤ 2 ^ w) (hcap : 26 ≤ cap) :
+ {t : FiveTrace workers pub cap m // ok (reports (header pub) t.logs)} ≃
+ ActualPaths (program workers pub) cap 0 m ok := by
+ let join : {t : FiveTrace workers pub cap m // ok (reports (header pub) t.logs)} →
+ ActualPaths (program workers pub) cap 0 m ok := fun t =>
+ ⟨t.val.choices, (accepts_five workers pub cap m _ ok fit hcap).mpr ⟨t.val, rfl, t.property⟩⟩
+ refine Equiv.ofBijective join ⟨?_, ?_⟩
+ · intro a b h
+ exact Subtype.ext (FiveTrace.choices_injective (congrArg Subtype.val h))
+ · intro b
+ obtain ⟨t, ht, accepted⟩ := (accepts_five workers pub cap m b.val ok fit hcap).mp b.property
+ exact ⟨⟨t, accepted⟩, Subtype.ext ht.symm⟩
+
+@[simp] theorem fiveTraceEquiv_apply_val {m : Memory w} {ok : List (Report w) → Prop}
+ (fit : 32 ≤ 2 ^ w) (hcap : 26 ≤ cap)
+ (t : {t : FiveTrace workers pub cap m // ok (reports (header pub) t.logs)}) :
+ (fiveTraceEquiv workers pub cap m ok fit hcap t).val = t.val.choices := rfl
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTerminalVisits.lean b/lean/OAI/Computability/VPVNP/PairSimulationTerminalVisits.lean
new file mode 100644
index 0000000000..0cbde0fe72
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTerminalVisits.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalCall
+
+/-!
+# Exact call sequences of the terminal controller
+
+The same list of private branch strings is used by the terminal image and
+the individual workers. Each continuing report determines the stage and local
+state of the next genuine call. After the last stage accepts the sequence
+cannot contain any further calls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM LiveProgram
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The worker entry together with its original report. -/
+abbrev Log (w : ℕ) := Entry w × Report w
+
+/-- The chronological physical reports generated by the logged worker calls. -/
+def reports (addr : Word w) (ls : List (Log w)) : List (Report w) :=
+ ls.map fun (e,r) => report addr e r
+
+/-- Persistent host marker for an entry, or termination after the final worker. -/
+def hostState (q : Option (Entry w)) := q.map Entry.marker
+
+/-- Every pending entry is consistent with the two controller cells. -/
+def StateValid (addr : Word w) (m : Memory w) (q : Option (Entry w)) := ∀ e ∈ q, e.Valid addr m
+
+variable (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap : ℕ)
+
+/-- Fuel remaining for the worker and its exit after the entry instructions. -/
+def rawFuel (e : Entry w) := cap-(e.prefixEvents (header pub)).length
+
+/-- One derivation step is a successful call of the original component.
+The source clock includes the space needed for its selected native exit. -/
+inductive Visits : Option (Entry w) → Memory w → List (List Bool) → List (Log w) → Prop
+ | nil (q m) : Visits q m [] []
+ | cons {e m bs more raw tail}
+ (called : execute (source workers e.stage pub) (rawFuel pub cap e)
+ ((source workers e.stage pub).start e.state) m bs = some raw)
+ (room : (exitReport (header pub) e.stage raw).events.length < rawFuel pub cap e)
+ (later : Visits (e.follow raw) (after m (report (header pub) e raw).events) more tail) :
+ Visits (some e) m (bs::more) ((e,raw)::tail)
+
+private theorem next_state_valid (e : Entry w) (raw : Report w) (m : Memory w) (fit : 32 ≤ 2^w) :
+ StateValid (header pub) (after m (report (header pub) e raw).events) (e.follow raw) := by
+ intro j hj
+ exact next_valid _ e j raw m fit hj
+
+theorem Visits.native {q m bs ls} (h : Visits workers pub cap q m bs ls)
+ (fit : 32 ≤ 2^w) (hcap : 26 ≤ cap) (valid : StateValid (header pub) m q) :
+ runSegment (program workers pub) cap (hostState q) m bs = some (reports (header pub) ls) := by
+ induction h with
+ | nil => rfl
+ | @cons e m bs more raw tail call room _ ih =>
+ have head := call_ok workers pub cap e m bs (by omega) hcap (valid e rfl) raw call room
+ change (match execute (program workers pub) cap ((program workers pub).start e.marker) m bs with
+ | none => none | some v => (runSegment (program workers pub) cap v.result (after m v.events) more).map (v::·)) = _
+ rw [head]
+ dsimp only
+ rw [report_result,← hostState]
+ rw [ih (next_state_valid pub e raw m fit)]
+ rfl
+
+/-- Inverse at every finite prefix, recovering exactly the worker call and
+its actual branch stream. In particular an additional call after final
+acceptance has no derivation. -/
+theorem recover_visits (q : Option (Entry w)) (m : Memory w) (bs : List (List Bool))
+ (out : List (Report w)) (fit : 32 ≤ 2^w) (hcap : 26 ≤ cap)
+ (valid : StateValid (header pub) m q)
+ (run : runSegment (program workers pub) cap (hostState q) m bs = some out) :
+ ∃ ls, Visits workers pub cap q m bs ls ∧ out = reports (header pub) ls := by
+ induction bs generalizing q m out with
+ | nil =>
+ exact ⟨[],.nil _ _,(Option.some.inj run).symm⟩
+ | cons bs more ih =>
+ cases q with
+ | none => contradiction
+ | some e =>
+ change (match execute (program workers pub) cap ((program workers pub).start e.marker) m bs with
+ | none => none | some v => (runSegment (program workers pub) cap v.result (after m v.events) more).map (v::·)) =
+ some out at run
+ cases head : execute (program workers pub) cap ((program workers pub).start e.marker) m bs with
+ | none => simp [head] at run
+ | some v =>
+ obtain ⟨raw,call,room,hv⟩ := (recover_call workers pub cap e m bs (by omega) hcap (valid e rfl) v).mp head
+ subst v
+ rw [head,Option.map_eq_some_iff] at run
+ obtain ⟨rest,continued,rfl⟩ := run
+ rw [report_result] at continued
+ obtain ⟨tail,visits,rfl⟩ := ih (e.follow raw) _ rest (next_state_valid pub e raw m fit) continued
+ exact ⟨(e,raw)::tail,.cons call room visits,rfl⟩
+
+theorem visits_iff (q : Option (Entry w)) (m : Memory w) (bs : List (List Bool)) (out : List (Report w))
+ (fit : 32 ≤ 2^w) (hcap : 26 ≤ cap) (valid : StateValid (header pub) m q) :
+ runSegment (program workers pub) cap (hostState q) m bs = some out ↔
+ ∃ ls, Visits workers pub cap q m bs ls ∧ out = reports (header pub) ls :=
+ ⟨recover_visits workers pub cap q m bs out fit hcap valid,
+ fun ⟨_,h,e⟩ => e ▸ Visits.native workers pub cap h fit hcap valid⟩
+
+theorem Visits.length {q m bs ls} (h : Visits workers pub cap q m bs ls) : ls.length = bs.length := by
+ induction h with | nil => rfl | cons _ _ _ ih => simp [ih]
+
+theorem Visits.branch_strings {q m bs ls} (h : Visits workers pub cap q m bs ls) :
+ branchPaths (reports (header pub) ls) = bs := by
+ induction h with
+ | nil => rfl
+ | cons call _ _ ih =>
+ simpa only [reports,List.map_cons,branchPaths,report_bits,(execute_spec call).2.2] using
+ congrArg (fun x => _ :: x) ih
+
+/-- A closed visit sequence ending at a worker halt has exactly the host
+terminal marker specified by that final call. -/
+def finish : Option (Entry w) → List (Log w) → Option (Entry w)
+ | q, [] => q
+ | _, (e,raw)::more => finish (e.follow raw) more
+
+theorem finish_host (addr : Word w) (q : Option (Entry w)) (ls : List (Log w)) :
+ endState (hostState q) (reports addr ls) = hostState (finish q ls) := by
+ induction ls generalizing q with
+ | nil => rfl
+ | cons p ls ih =>
+ obtain ⟨e,r⟩ := p
+ simp only [reports,List.map_cons,endState,finish,report_result]
+ exact ih (e.follow r)
+
+theorem Visits.unique {q m bs l₁ l₂}
+ (h₁ : Visits workers pub cap q m bs l₁) (h₂ : Visits workers pub cap q m bs l₂) : l₁ = l₂ := by
+ induction h₁ generalizing l₂ with
+ | nil => cases h₂; rfl
+ | cons hc _ _ ih =>
+ cases h₂ with
+ | cons hc' _ ht =>
+ obtain rfl := Option.some.inj (hc.symm.trans hc')
+ rw [ih ht]
+
+/-- Exactly the complete genuine call strings, preserving any caller cap
+on physical reports. The proof works in both directions on the same input. -/
+theorem actual_iff (m : Memory w) (bs : List (List Bool)) (ok : List (Report w) → Prop)
+ (fit : 32 ≤ 2^w) (hcap : 26 ≤ cap) :
+ (∃ out, runSegment (program workers pub) cap (some 0) m bs = some out ∧ endState (some 0) out = none ∧ ok out) ↔
+ ∃ ls, Visits workers pub cap (some .initial) m bs ls ∧ finish (some .initial) ls = none ∧ ok (reports (header pub) ls) := by
+ have valid : StateValid (header pub) m (some (.initial : Entry w)) := by
+ intro e he; cases he; trivial
+ have term (ls : List (Log w)) :
+ endState (some (0 : Word w)) (reports (header pub) ls) = none ↔ finish (some .initial) ls = none := by
+ change endState (hostState (some .initial)) _ = none ↔ _
+ rw [finish_host]; simp [hostState]
+ constructor
+ · rintro ⟨out,hr,ht,hv⟩
+ obtain ⟨ls,h,rfl⟩ := recover_visits workers pub cap (some .initial) m bs out fit hcap valid hr
+ exact ⟨ls,h,(term ls).mp ht,hv⟩
+ · rintro ⟨ls,h,ht,hv⟩
+ exact ⟨_,Visits.native workers pub cap h fit hcap valid,(term ls).mpr ht,hv⟩
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTickTerminal.lean b/lean/OAI/Computability/VPVNP/PairSimulationTickTerminal.lean
new file mode 100644
index 0000000000..b3df742ccc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTickTerminal.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+
+/-!
+# Uniqueness of the tick count at a terminal instruction
+
+Starting at the same native configuration, two runs consisting entirely of
+local ticks take the same number of ticks to reach a terminal instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.GuessWord.Prefix
+
+open BurstRAM PrivateRAM
+
+variable {w p r k n m : ℕ} {M : Machine w p r k} {c d e : Config w p r}
+
+private theorem ticks_unique_of_no_local
+ (run : Prefix M c (List.replicate n .tick) d)
+ (other : Prefix M c (List.replicate m .tick) e)
+ (hd : ∀ next, M.program.step d ≠ .localStep next)
+ (he : ∀ next, M.program.step e ≠ .localStep next) : n = m ∧ d = e := by
+ induction n generalizing c m with
+ | zero =>
+ cases run
+ cases m with
+ | zero => cases other; exact ⟨rfl, rfl⟩
+ | succ m =>
+ rw [List.replicate_succ] at other
+ cases other with
+ | tick step _ => exact (hd _ step).elim
+ | succ n ih =>
+ rw [List.replicate_succ] at run
+ cases run with
+ | tick step tail =>
+ cases m with
+ | zero => cases other; exact (he _ step).elim
+ | succ m =>
+ rw [List.replicate_succ] at other
+ cases other with
+ | tick step' tail' =>
+ cases CallAction.localStep.inj (step.symm.trans step')
+ obtain ⟨hlen, hout⟩ := ih tail tail'
+ exact ⟨congrArg Nat.succ hlen, hout⟩
+
+/-- Two tick prefixes from one configuration that end in rejection or a
+finished call have the same length and the same terminal configuration. -/
+theorem ticks_terminal_unique
+ (run : Prefix M c (List.replicate n .tick) d)
+ (other : Prefix M c (List.replicate m .tick) e)
+ (hd : M.program.step d = .reject ∨ ∃ result, M.program.step d = .finish result)
+ (he : M.program.step e = .reject ∨ ∃ result, M.program.step e = .finish result) :
+ n = m ∧ d = e := by
+ apply ticks_unique_of_no_local run other
+ · rcases hd with h | ⟨result, h⟩ <;> simp [h]
+ · rcases he with h | ⟨result, h⟩ <;> simp [h]
+
+end PrimedCounter.GuessWord.Prefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationTraceJobs.lean b/lean/OAI/Computability/VPVNP/PairSimulationTraceJobs.lean
new file mode 100644
index 0000000000..7c108e4a2c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationTraceJobs.lean
@@ -0,0 +1,257 @@
+import OAI.Computability.VPVNP.PairSimulationScanTrace
+import OAI.Computability.VPVNP.PairSimulationVertexJobs
+
+/-!
+# Recovering the selected vertex jobs from an emitted trace
+
+The selector words, the native shared-arc call list, and all vertex strings
+in a complete trace come from one branch and one edge assignment. Each
+vertex string therefore has the preorder job decomposition for that same
+branch, and their exponent increments add to the decoded monomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords Compression BurstRAM BurstRAM.PrivateRAM
+open scoped Classical
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {N Y : Network}
+
+/-- The native shared scan supplies the incident values of every vertex
+before the independent site witnesses are chosen. -/
+structure TerminalData (scan : ScanPhase N) (P : SiteParsers κ N) where
+ /-- Path of the shared-arc scan that fixes the wire payload incident at every terminal site. -/
+ arcs : scan.Path
+ /-- For each terminal site, a local monomial witness choice evaluated on the half-wire
+ assignment from the shared-arc path. -/
+ choices : ∀ v, (P.witnesses v (WireTensor.edgeAssignment N.src N.dst (scan.payload arcs) v)).Choice
+
+/-- Build the three choice-stream lists from the supplied selector tapes, the shared-arc path's
+calls, and each terminal site's encoded witness in site order. -/
+def TerminalData.phases {scan : ScanPhase N} {P : SiteParsers κ N} (x : TerminalData scan P)
+ (sites : Order N.Site) (sels : List (List Bool)) : Phases :=
+ ⟨sels, scan.calls x.arcs, List.ofFn fun j =>
+ let v := sites.entries j
+ (P.read v (WireTensor.edgeAssignment N.src N.dst (scan.payload x.arcs) v)).encode (x.choices v)⟩
+
+/-- Total exponent of a parameter label in the terminal monomial, obtained by summing its local
+witness exponent over all sites of the shared arc assignment. -/
+def TerminalData.exponents {scan : ScanPhase N} {P : SiteParsers κ N} (x : TerminalData scan P) (l : L) :=
+ ∑ v, (P.witnesses v (WireTensor.edgeAssignment N.src N.dst (scan.payload x.arcs) v)).exponents (x.choices v) l
+
+private def AllData {N : Network} (H : History A N) : (K : H.KernelWitnesses κ) → Readers H K → ScanPhases H →
+ SiteParsers κ N → (Phases → (L → ℕ) → Prop) → Prop :=
+ match H with
+ | .stop => fun _ r scan P ok => ∀ x : TerminalData scan P, ok (x.phases r.2.1 []) x.exponents
+ | .branch s tail => fun K r scan P ok => ∀ i,
+ let parser : TermParsers κ (s.term i) := ⟨r.2.1 i, r.2.2.1, K.1 i, r.2.2.2.1 i⟩
+ AllData (tail i) (K.2 i) (r.2.2.2.2 i) (scan i) (parser.push P)
+ (fun phases powers => ok (Phases.prepend (r.1.encode i) phases) powers)
+
+private theorem trace_allData {N : Network} (H : History A N) (K : H.KernelWitnesses κ) (r : Readers H K)
+ (scan : ScanPhases H) (P : SiteParsers κ N) (ok : Phases → (L → ℕ) → Prop) (h : AllData H K r scan P ok) :
+ let encoded := scanTrace H K r scan P.factors P.witnesses P.read
+ ∀ q : encoded.Trace, ok (encoded.phases q) ((H.expandedWitness K P.factors P.witnesses).exponents (encoded.decode q)) := by
+ induction H generalizing ok with
+ | @stop N =>
+ intro enc q
+ let x : TerminalData scan P := ⟨q.1, fun v =>
+ (P.read v (WireTensor.edgeAssignment N.src N.dst (scan.payload q.1) v)).completeEquiv.symm (q.2 v)⟩
+ have same : x.phases r.2.1 [] = enc.phases q := by
+ change Phases.mk [] _ _ = Phases.mk [] _ _
+ congr 1
+ apply congrArg List.ofFn
+ funext j
+ let v := r.2.1.entries j
+ let leaf := P.read v (WireTensor.edgeAssignment N.src N.dst (scan.payload q.1) v)
+ exact congrArg Subtype.val (leaf.completeEquiv.apply_symm_apply (q.2 v))
+ rw [← same]
+ exact h x
+ | @branch N s tail ih =>
+ intro enc q
+ let i := r.1.completeEquiv.symm q.1
+ let parser : TermParsers κ (s.term i) := ⟨r.2.1 i, r.2.2.1, K.1 i, r.2.2.2.1 i⟩
+ let Q := parser.push P
+ let next := fun phases powers => ok (Phases.prepend (r.1.encode i) phases) powers
+ have hpart : AllData (tail i) (K.2 i) (r.2.2.2.2 i) (scan i) Q next := h i
+ have it := ih i (K.2 i) (r.2.2.2.2 i) (scan i) Q next hpart
+ let rest := scanTrace (tail i) (K.2 i) (r.2.2.2.2 i) (scan i) Q.factors Q.witnesses Q.read
+ let sub : rest.Trace := q.2
+ have hi := it sub
+ have hx := congrArg Subtype.val (r.1.completeEquiv.apply_symm_apply q.1)
+ change r.1.encode i = q.1.val at hx
+ dsimp only [next] at hi
+ rw [hx] at hi
+ let whole := History.branch s tail
+ have decode : enc.decode q = (History.branchChoice s tail K P.factors P.witnesses).symm ⟨i, rest.decode sub⟩ := rfl
+ have hp : (whole.expandedWitness K P.factors P.witnesses).exponents (enc.decode q) =
+ ((tail i).expandedWitness (K.2 i) Q.factors Q.witnesses).exponents (rest.decode sub) := by
+ funext label
+ rw [decode]
+ exact History.branchChoice_exponents s tail K P.factors P.witnesses i (rest.decode sub) label
+ change ok (Phases.prepend q.1.val (rest.phases sub)) ((whole.expandedWitness K P.factors P.witnesses).exponents (enc.decode q))
+ rw [hp]
+ exact hi
+
+open private castScans from OAI.Computability.VPVNP.PairSimulationScanTrace
+open private transportReaders from OAI.Computability.VPVNP.PairSimulationAssembly
+open private transportWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+open private castParsers from OAI.Computability.VPVNP.PairSimulationAssemblyBounds
+
+private theorem allData_cast {N Y : Network} (e : N = Y) (H : History A N) (K : H.KernelWitnesses κ)
+ (r : Readers H K) (scan : ScanPhases H) (P : SiteParsers κ Y) (ok : Phases → (L → ℕ) → Prop)
+ (h : AllData H K r scan (e.symm ▸ P) ok) :
+ AllData (e ▸ H) (transportWitnesses e H K) (transportReaders e H K r) (castScans e H scan) P ok := by
+ cases e
+ exact h
+
+private theorem finalParsers_cast {N Y Z : Network} (e : N = Y) (c : TermChain A N Z) (r : ChainParsers κ c)
+ (P : SiteParsers κ Y) : finalParsers (e ▸ c) (castParsers e c r) P = finalParsers c r (e.symm ▸ P) := by
+ cases e
+ rfl
+
+/-- Site parsers on the final network of the selected execution branch, formed by pushing the
+initial parsers through the chosen terms in order. -/
+noncomputable abbrev terminalSites {a g b n : ℕ} {X : State a g} (E : StateExecution A b n X)
+ (W : E.MapWitnesses κ) (r : ExecutionReaders E W) (rec : E.Records) (P : SiteParsers κ X.network) (z : E.Choices) :=
+ finalParsers (E.termChain rec z) (branchParsers E W r rec z) P
+
+section Execution
+
+variable {a g w p r k : ℕ} (X : State a g)
+ (M : Machine w p r k) (pc : Fin 10 → Fin p) (reg : Fin 2 ↪ Fin r) (base : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg base done) (he : M.entry = pc 0) (low : ℕ)
+ (pub : M.publicData base = FinalBits.cursor w low 0) (extra : ℕ)
+
+private theorem execution_allData {b n : ℕ} (E : StateExecution A b n X) (W : E.MapWitnesses κ)
+ (r : ExecutionReaders E W) (rec : E.Records) (P : SiteParsers κ X.network) (memory : E.Choices → Memory w)
+ (fit : ∀ z, low + (E.finalState z).totalWidth < 2^w) (ok : Phases → (L → ℕ) → Prop)
+ (h : ∀ z, let scan := stateScanPhase (E.finalState z) M pc reg base done hl he low pub (memory z) extra (fit z)
+ ∀ x : TerminalData scan (terminalSites E W r rec P z),
+ ok (x.phases (siteOrder (E.finalState z)) (selectorCodes E W r z)) x.exponents) :
+ AllData E.history (E.historyWitnesses W) (executionHistoryReaders E W r)
+ (executionScanPhases X M pc reg base done hl he low pub extra E memory fit) P ok := by
+ induction E generalizing ok with
+ | done X => exact h ()
+ | more p tail ih =>
+ intro i
+ let nextP := (r.1.termParsers i).push P
+ let nextOK := fun phases powers => ok (Phases.prepend (r.1.select.encode i) phases) powers
+ apply allData_cast (p.output_eq i).symm (tail i).history ((tail i).historyWitnesses (W.2 i))
+ (executionHistoryReaders (tail i) (W.2 i) (r.2 i))
+ (executionScanPhases (p.next i) M pc reg base done hl he low pub extra (tail i)
+ (fun z => memory ⟨i,z⟩) (fun z => fit ⟨i,z⟩)) nextP nextOK
+ apply ih i (W.2 i) (r.2 i) (rec.2 i) ((p.output_eq i) ▸ nextP) (fun z => memory ⟨i,z⟩)
+ (fun z => fit ⟨i,z⟩) nextOK
+ intro z
+ have eqSites : terminalSites (.more p tail) W r rec P ⟨i,z⟩ =
+ terminalSites (tail i) (W.2 i) (r.2 i) (rec.2 i) ((p.output_eq i) ▸ nextP) z :=
+ finalParsers_cast (p.output_eq i).symm _ _ nextP
+ have hz := h ⟨i,z⟩
+ rw [eqSites] at hz
+ exact hz
+
+/-- A single branch, one native shared scan, and actual terminal witnesses
+recover all three observable phases and every parameter exponent at once. -/
+theorem executionTrace_jobs {b n : ℕ} (E : StateExecution A b n X) (W : E.MapWitnesses κ)
+ (r : ExecutionReaders E W) (rec : E.Records) (P : SiteParsers κ X.network) (memory : E.Choices → Memory w)
+ (fit : ∀ z, low + (E.finalState z).totalWidth < 2^w) :
+ let enc := scanTrace E.history (E.historyWitnesses W) (executionHistoryReaders E W r)
+ (executionScanPhases X M pc reg base done hl he low pub extra E memory fit) P.factors P.witnesses P.read
+ ∀ q : Set.range enc.phases, ∃ z : E.Choices,
+ let scan := stateScanPhase (E.finalState z) M pc reg base done hl he low pub (memory z) extra (fit z)
+ ∃ x : TerminalData scan (terminalSites E W r rec P z),
+ q.val = x.phases (siteOrder (E.finalState z)) (selectorCodes E W r z) ∧
+ (E.history.expandedWitness (E.historyWitnesses W) P.factors P.witnesses).exponents (enc.emitted q) = x.exponents := by
+ intro enc q
+ let ok (phases : Phases) (powers : L → ℕ) := ∃ z : E.Choices,
+ let scan := stateScanPhase (E.finalState z) M pc reg base done hl he low pub (memory z) extra (fit z)
+ ∃ x : TerminalData scan (terminalSites E W r rec P z),
+ phases = x.phases (siteOrder (E.finalState z)) (selectorCodes E W r z) ∧ powers = x.exponents
+ let t := (Equiv.ofInjective enc.phases enc.phases_injective).symm q
+ have ht := trace_allData E.history (E.historyWitnesses W) (executionHistoryReaders E W r)
+ (executionScanPhases X M pc reg base done hl he low pub extra E memory fit) P ok
+ (execution_allData X M pc reg base done hl he low pub extra E W r rec P memory fit ok (fun z x => ⟨z,x,rfl,rfl⟩)) t
+ change ok q.val _
+ change ok (enc.phases t) _ at ht
+ rw [show enc.phases t = q.val from Equiv.apply_ofInjective_symm enc.phases_injective q] at ht
+ exact ht
+
+end Execution
+
+/-- The individual preorder jobs belonging to the witness at one of the
+terminal sites, with both incident halves drawn from the same native scan. -/
+def TerminalData.jobs {scan : ScanPhase N} {P : SiteParsers κ N} (x : TerminalData scan P)
+ (jobs : JobsFor P) (v : N.Site) : List (VertexJob L) :=
+ jobs v (WireTensor.edgeAssignment N.src N.dst (scan.payload x.arcs) v) (x.choices v)
+
+theorem TerminalData.jobBits {scan : ScanPhase N} {P : SiteParsers κ N} (x : TerminalData scan P)
+ (trees : N.Site → DFS.VertexTree) (jobs : JobsFor P) (hs : JobsSpec P trees jobs) (o : Order N.Site) (sels) :
+ (x.phases o sels).vertices = List.ofFn (fun j => (x.jobs jobs (o.entries j)).flatMap VertexJob.bits) := by
+ apply congrArg List.ofFn
+ funext j
+ exact (hs.bits _ _ _).symm
+
+theorem TerminalData.jobPowers {scan : ScanPhase N} {P : SiteParsers κ N} (x : TerminalData scan P)
+ (trees : N.Site → DFS.VertexTree) (jobs : JobsFor P) (hs : JobsSpec P trees jobs) (l : L) :
+ x.exponents l = ∑ v, ((x.jobs jobs v).map (fun j => j.increment l)).sum :=
+ Finset.sum_congr rfl fun v _ => (hs.increments v _ _ l).symm
+
+section Cursor
+
+open CursorNetwork CursorRouting
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {D e w p r k' b l : ℕ} [NeZero D]
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ (M : Machine w p r k') (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) (labels : Fin D ≃ Fin b ⊕ Fin l) (hD : 1 < D)
+ (T : ℕ) (hT : T * S.laneBits ≤ l)
+ {ww pp rr kk : ℕ} (N : Machine ww pp rr kk) (pc : Fin 10 → Fin pp) (reg : Fin 2 ↪ Fin rr)
+ (base : Fin kk) (done : Fin pp) (hl : FinalBits.Linked N pc reg base done) (he : N.entry = pc 0)
+ (low : ℕ) (pub : N.publicData base = FinalBits.cursor ww low 0) (extra : ℕ)
+ (memory : (B.execute f hf T hT (scanInput labels hD S e w)).Choices → Memory ww)
+ (fit : ∀ z : (B.execute f hf T hT (scanInput labels hD S e w)).Choices,
+ low + ((B.execute f hf T hT (scanInput labels hD S e w)).finalState z).totalWidth < 2 ^ ww)
+
+/-- Every phase triple in the counted RAM family has one selected branch
+and shared native arc path whose concrete site jobs produce its vertex
+bit strings and whose local increments produce its decoded exponents. -/
+theorem compressedTrace_jobs :
+ let X := scanInput labels hD S e w
+ let E := B.execute f hf T hT X
+ let r := repeatReaders (blockReaders B f hf) _ T l (Nat.add_sub_of_le hT).symm X
+ let P := cursorSiteParsers M fuel initial header hw hc labels hD (Nat.add_sub_of_le S.degree_bounds.1) f
+ let W := compressedRAMCount B f hf M fuel initial header hw hc labels hD T hT
+ let enc := compressedScanTrace B f hf M fuel initial header hw hc labels hD T hT N pc reg base done hl he low pub extra memory fit
+ ∀ q : Set.range enc.phases, ∃ z : E.Choices,
+ let Y := E.finalState z
+ let scan := stateScanPhase Y N pc reg base done hl he low pub (memory z) extra (fit z)
+ let c := E.termChain (B.records f hf T hT X) z
+ let site := selectedParsers B f hf T hT X z
+ ∃ x : TerminalData scan (finalParsers c site P),
+ q.val.selectors = selectorCodes E _ r z ∧ q.val.arcCalls = scan.calls x.arcs ∧
+ ∀ (ptr : RowPointers c) (leaves : X.network.Site → ℕ × ℕ),
+ let jobs := vertexJobs c site ptr P leaves
+ q.val.vertices = List.ofFn (fun j => (x.jobs jobs ((siteOrder Y).entries j)).flatMap VertexJob.bits) ∧
+ ∀ label, W.exponents (enc.emitted q) label = ∑ v, ((x.jobs jobs v).map (fun j => j.increment label)).sum := by
+ intro X E r P W enc q
+ obtain ⟨z,x,hph,hpow⟩ := executionTrace_jobs X N pc reg base done hl he low pub extra E _ r
+ (B.records f hf T hT X) P memory fit q
+ refine ⟨z,x,congrArg Phases.selectors hph,congrArg Phases.arcCalls hph,fun ptr leaves => ?_⟩
+ let c := E.termChain (B.records f hf T hT X) z
+ let r' := selectedParsers B f hf T hT X z
+ let hs := vertexJobs_spec c r' ptr P leaves
+ exact ⟨(congrArg Phases.vertices hph).trans (x.jobBits _ _ hs _ _),
+ fun label => (congrFun hpow label).trans (x.jobPowers _ _ hs label)⟩
+
+end Cursor
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationVertexControlFrame.lean b/lean/OAI/Computability/VPVNP/PairSimulationVertexControlFrame.lean
new file mode 100644
index 0000000000..149629cb40
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationVertexControlFrame.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.PairSimulationWorkerControl
+import OAI.Computability.VPVNP.PairVertexOrdinalPhase
+
+/-! # The vertex memory frame along successful prefixes of the terminal program -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM CompressorRecords TerminalLink
+open scoped Fin.CommRing
+
+variable {w n g cap base grammar : ℕ} {pub : Fin 11 → Word w} {D : IndexedSites n g}
+ {geometry rootFields leaf shrink refresh : Segment}
+local notation "S" => segments geometry rootFields leaf shrink refresh
+local notation "P" => Machine.program (Template.instantiate (template S) w pub)
+local notation "Frame" => VertexFrame.Linked (TerminalLink.header pub) base grammar g
+
+/-- Each successful vertex call preserves the protected address, including on a
+prefix that never reaches the closing ordinal. A continuing call advances the
+ordinal and preserves the linked frame after the controller stores its result. -/
+def ordinalWorkerControl (F : DescriptorSpace.Shape) (limit : ℕ) (ref phy : Memory w) (a : ℕ)
+ (H : ActiveCalls D P cap base grammar (Frame ref))
+ (close : Closes P cap n pub (Frame ref))
+ (outside : a < base + grammar ∨ base + grammar + g ≤ a)
+ (cell : workerCell (TerminalLink.header pub) a) (ready : Frame ref 0 phy) :
+ WorkerControl (TerminalProgram.workers F limit S) pub cap .vertices a phy where
+ inv st m := ∃ j : ℕ, j ≤ n ∧ st = (j : Word w) ∧ Frame ref j m
+ ready := ⟨0, Nat.zero_le _, rfl, ready⟩
+ advance st m bits raw inv run := by
+ obtain ⟨j, le, rfl, linked⟩ := inv
+ let e := Entry.resume Stage.vertices (j : Word w)
+ have full := execute_extend run (cap - rawFuel pub cap e)
+ rw [Nat.add_sub_of_le (show rawFuel pub cap e ≤ cap from Nat.sub_le ..)] at full
+ change execute P cap (Program.start P (j : Word w)) m bits = some raw at full
+ rcases lt_or_eq_of_le le with lt | rfl
+ · let i : Fin n := ⟨j, lt⟩
+ obtain ⟨x, rfl⟩ := H.recover i m linked bits raw full
+ obtain ⟨rep, call, next, flush⟩ := H.emit i m linked x
+ obtain rfl := Option.some.inj (full.symm.trans call)
+ have post := linked.report e raw (D.powers i x) flush
+ refine ⟨(post a outside cell).trans (linked a outside cell).symm, ?_⟩
+ intro st' returned
+ exact ⟨j + 1, lt, Option.some.inj (returned.symm.trans next), post⟩
+ · rw [close m linked] at full
+ split at full
+ · obtain rfl := Option.some.inj full
+ have post := VertexFrame.Linked.after_report (raw := closingReport pub m) e
+ (closingReport_after pub m ▸ linked)
+ exact ⟨(post a outside cell).trans (linked a outside cell).symm, fun _ h => nomatch h⟩
+ · contradiction
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationVertexJobs.lean b/lean/OAI/Computability/VPVNP/PairSimulationVertexJobs.lean
new file mode 100644
index 0000000000..6889170249
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationVertexJobs.lean
@@ -0,0 +1,261 @@
+import OAI.Computability.VPVNP.PairTraversalHistory
+import OAI.Computability.VPVNP.PairSimulationDFSHooks
+
+/-!
+# Local choices and exponent increments in DFS visit order
+
+For a fixed final vertex and a choice in its expansion, each descriptor
+visit consumes the old half-wire choices and the local kernel choices
+once. Its children then use those very half-wires. Splitting the binary
+stream this way aligns the row addresses with native depth-first traversal
+and the local parameter increments with the final vertex's monomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords Compression DFS
+open scoped Classical
+open private addTree from OAI.Computability.VPVNP.PairTraversalHistory
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {N Y : Network}
+
+/-- One depth-first descriptor visit, carrying its row address, the local witness tape it
+consumes, and its contribution to each parameter exponent. -/
+structure VertexJob (L : Type) where
+ /-- Address of the descriptor row visited by this job. -/
+ address : ℕ
+ /-- The segment of the vertex choice stream consumed at this descriptor visit. -/
+ bits : List Bool
+ /-- The contribution of this visit's local witness to the exponent of each parameter label. -/
+ increment : L → ℕ
+
+/-- Per-site jobs indexed by the incoming half-wires and the selected
+local monomial occurrence. -/
+abbrev JobsFor (P : SiteParsers κ N) :=
+ ∀ v z, (P.witnesses v z).Choice → List (VertexJob L)
+
+private theorem order_encode {I : Type} (o : Order I) {α : I → Type} (read : ∀ i, ChoiceReader (α i))
+ (x : ∀ i, α i) : ((o.reader read).encode x) = (List.ofFn fun j => (read (o.entries j)).encode (x (o.entries j))).flatten := by
+ unfold Order.reader ChoiceReader.reindex
+ dsimp only
+ rw [ChoiceReader.vector_encode]
+ rfl
+
+/-- The old halves of every child and the local kernel assignment in the
+same order in which the push reader consumes them. -/
+noncomputable def TermParsers.nodeBits {t : Term A N} (r : TermParsers κ t) (v : t.output.Site)
+ (a : Placed t.place N.Half v) (z : t.output.Half v) (x : (r.witness v a z).Choice) : List Bool :=
+ (fiber t.place v (r.order.children v) (fun u => half N u (r.order.outgoing u) (r.order.incoming u) r.payload)).encode a ++
+ (r.read v a z).encode x
+
+private theorem push_encode {t : Term A N} (r : TermParsers κ t) (P : SiteParsers κ N)
+ (v : t.output.Site) (z : t.output.Half v) (x : ((r.push P).witnesses v z).Choice) :
+ let q := t.pushChoice P.factors P.witnesses r.witness v z x
+ let o := r.order.children v
+ ((r.push P).read v z).encode x = r.nodeBits v q.1 z q.2.2 ++
+ (List.ofFn fun j => let u := o.entries j; (P.read u.val (q.1 u.val u.prop)).encode (q.2.1 u)).flatten := by
+ intro q o
+ change _ ++ (_ ++ (o.reader (fun u => P.read u.val (q.1 u.val u.prop))).encode q.2.1) = (_ ++ _) ++ _
+ rw [order_encode, List.append_assoc]
+ rfl
+
+/-- Each input vertex makes one visit. Its job carries precisely the
+factor witness supplied by that input parser. -/
+def leafJobs (P : SiteParsers κ N) (ptr : N.Site → ℕ × ℕ) : JobsFor P :=
+ fun v z p => [⟨(ptr v).1, (P.read v z).encode p, (P.witnesses v z).exponents p⟩]
+
+/-- Build the pushed site's jobs by emitting its own descriptor visit first, then the chosen
+child jobs in the term parser's child order. -/
+noncomputable def pushJobs {t : Term A N} (r : TermParsers κ t) (ptr : t.output.Site → ℕ × ℕ)
+ (P : SiteParsers κ N) (jobs : JobsFor P) : JobsFor (r.push P) :=
+ fun v z p =>
+ let q := t.pushChoice P.factors P.witnesses r.witness v z p
+ let children := r.order.children v
+ ⟨(ptr v).1, r.nodeBits v q.1 z q.2.2, (r.witness v q.1 z).exponents q.2.2⟩ ::
+ (List.ofFn fun j => let u := children.entries j; jobs u.val (q.1 u.val u.prop) (q.2.1 u)).flatten
+
+/-- Agreement of a site's jobs with its tree and parser. The addresses follow preorder, the
+concatenated tapes encode the witness, and the increments sum to its exponents. -/
+structure JobsSpec (P : SiteParsers κ N) (trees : N.Site → VertexTree) (jobs : JobsFor P) : Prop where
+ addresses : ∀ v z p, (jobs v z p).map VertexJob.address = (trees v).preorder
+ bits : ∀ v z p, (jobs v z p).flatMap VertexJob.bits = (P.read v z).encode p
+ increments : ∀ v z p l, ((jobs v z p).map (fun j => j.increment l)).sum = (P.witnesses v z).exponents p l
+
+private theorem leafJobs_spec (P : SiteParsers κ N) (ptr : N.Site → ℕ × ℕ) :
+ JobsSpec P (fun v => leafTree (ptr v)) (leafJobs P ptr) where
+ addresses v z p := rfl
+ bits v z p := by simp [leafJobs]
+ increments v z p l := by simp [leafJobs]
+
+private theorem flatten_flatMap_eq {I J : Type} (ls : List (List I)) (f : I → List J) :
+ ls.flatten.flatMap f = (ls.map fun xs => xs.flatMap f).flatten := by
+ induction ls with
+ | nil => rfl
+ | cons xs ls ih => simp [List.flatMap_append, ih]
+
+private theorem pushJobs_spec {t : Term A N} (r : TermParsers κ t) (ptr : t.output.Site → ℕ × ℕ)
+ (P : SiteParsers κ N) (trees : N.Site → VertexTree) (jobs : JobsFor P) (h : JobsSpec P trees jobs) :
+ JobsSpec (r.push P) (addTree r ptr trees) (pushJobs r ptr P jobs) where
+ addresses v z p := by
+ simp only [pushJobs, List.map_cons, List.map_flatten, List.map_ofFn, Function.comp_def, h.addresses,
+ addTree, VertexTree.preorder]
+ bits v z p := by
+ rw [push_encode]
+ simp only [pushJobs, List.flatMap_cons, flatten_flatMap_eq, List.map_ofFn, Function.comp_def, h.bits]
+ increments v z p l := by
+ let q := t.pushChoice P.factors P.witnesses r.witness v z p
+ let o := r.order.children v
+ simp only [pushJobs, List.map_cons, List.sum_cons, List.map_flatten, List.map_ofFn, List.sum_flatten,
+ Function.comp_def, List.sum_ofFn, h.increments]
+ change (r.witness v q.1 z).exponents q.2.2 l + (∑ j, (P.witnesses (o.entries j).val
+ (q.1 (o.entries j).val (o.entries j).prop)).exponents (q.2.1 (o.entries j)) l) =
+ (∑ u : t.Preimage v, (P.witnesses u.val (q.1 u.val u.prop)).exponents (q.2.1 u) l) + _
+ rw [Nat.add_comm]
+ exact congrArg (· + _) (o.entries.sum_comp (fun u => (P.witnesses u.val (q.1 u.val u.prop)).exponents (q.2.1 u) l))
+
+/-- Follow the selected terms, retaining the local split into descriptor
+visits at every stage. -/
+noncomputable def chainJobs {N Y : Network} (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ptr : RowPointers c) (P : SiteParsers κ N) (jobs : JobsFor P) : JobsFor (finalParsers c r P) := by
+ induction c with
+ | done => exact jobs
+ | more _ _ _ ih => exact ih r.2 ptr.2 (r.1.push P) (pushJobs r.1 ptr.1 P jobs)
+
+private theorem chainJobs_spec (c : TermChain A N Y) (r : ChainParsers κ c) (ptr : RowPointers c)
+ (P : SiteParsers κ N) (trees : N.Site → VertexTree) (jobs : JobsFor P) (h : JobsSpec P trees jobs) :
+ JobsSpec (finalParsers c r P) (chainTrees c r ptr trees) (chainJobs c r ptr P jobs) := by
+ induction c with
+ | done => exact h
+ | more _ _ _ ih => exact ih r.2 ptr.2 _ _ _ (pushJobs_spec r.1 ptr.1 P trees jobs h)
+
+/-- Jobs for each final site of a selected term chain, obtained by starting with one visit per
+input leaf and applying the successive term parsers. -/
+noncomputable def vertexJobs (c : TermChain A N Y) (r : ChainParsers κ c) (ptr : RowPointers c)
+ (P : SiteParsers κ N) (leaves : N.Site → ℕ × ℕ) : JobsFor (finalParsers c r P) :=
+ chainJobs c r ptr P (leafJobs P leaves)
+
+theorem vertexJobs_spec (c : TermChain A N Y) (r : ChainParsers κ c) (ptr : RowPointers c)
+ (P : SiteParsers κ N) (leaves : N.Site → ℕ × ℕ) :
+ JobsSpec (finalParsers c r P) (chainTrees c r ptr (fun v => leafTree (leaves v))) (vertexJobs c r ptr P leaves) :=
+ chainJobs_spec c r ptr P _ _ (leafJobs_spec P leaves)
+
+section Cursor
+
+open CursorNetwork CursorRouting BurstRAM BurstRAM.PrivateRAM
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {D e w p r k' base lanes : ℕ} [NeZero D]
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ (M : Machine w p r k') (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2^D * 2^e < 2^w) (labels : Fin D ≃ Fin base ⊕ Fin lanes) (hD : 1 < D)
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+
+/-- The selected cursor leaves consume their validator strings and add zero
+to every parameter count. -/
+theorem cursor_leafJobs (hd : 2 + (S.baseDegree - 2) = 2 ^ S.degreeExponent 0)
+ (leaves : (cursorState labels hD hd (ramFieldBits (2^e) w : RAMSystem D → ℕ)).network.Site → ℕ × ℕ) :
+ let P := cursorSiteParsers M fuel initial header hw hc labels hD hd f
+ ∀ v z p, leafJobs P leaves v z p = [⟨(leaves v).1, (P.read v z).encode p, fun _ => 0⟩] := fun _ _ _ => rfl
+
+/-- The visit lists for the original machine specialize all three
+identities to the compressor's actual records and branch choice. -/
+theorem selectedCursor_jobs :
+ let hpad := Nat.add_sub_of_le S.degree_bounds.1
+ let X := cursorState labels hD hpad (ramFieldBits (2^e) w : RAMSystem D → ℕ)
+ let E := B.execute f hf T hT X
+ let P := cursorSiteParsers M fuel initial header hw hc labels hD hpad f
+ ∀ z : E.Choices, let c := E.termChain (B.records f hf T hT X) z
+ let r := selectedParsers B f hf T hT X z
+ ∀ (ptr : RowPointers c) (leaves : X.network.Site → ℕ × ℕ),
+ JobsSpec (finalParsers c r P) (chainTrees c r ptr (fun v => leafTree (leaves v)))
+ (vertexJobs c r ptr P leaves) := by
+ intro hpad X E P z c r ptr leaves
+ exact vertexJobs_spec c r ptr P leaves
+
+end Cursor
+
+section Native
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+open private copyRegs from OAI.Computability.VPVNP.PairSimulationDFS
+
+variable {w endAddr : ℕ}
+
+/-- The observable obligations for the native path of a single visit.
+The extracted histogram may depend on the private scratch layout. -/
+structure RealizesJob (hist : Scratch w endAddr → L → ℕ) (semantic : VertexJob L)
+ (native : VisitPath w endAddr) : Prop where
+ address : native.node = (semantic.address : Word w)
+ bits : choiceBits native.trace = semantic.bits
+ counts : ∀ s, native.enabled s → ∀ l, hist (native.update s) l = hist s l + semantic.increment l
+
+omit [Fintype L] in
+private theorem realized_addresses {hist : Scratch w endAddr → L → ℕ} {js ps}
+ (h : List.Forall₂ (RealizesJob hist) js ps) : ps.map VisitPath.node = js.map (fun j => (j.address : Word w)) := by
+ induction h with
+ | nil => rfl
+ | cons h _ ih => simp [h.address, ih]
+
+omit [Fintype L] in
+private theorem realized_bits {hist : Scratch w endAddr → L → ℕ} {js ps}
+ (h : List.Forall₂ (RealizesJob hist) js ps) :
+ ps.flatMap (fun p => choiceBits p.trace) = js.flatMap VertexJob.bits := by
+ induction h with
+ | nil => rfl
+ | cons h _ ih => simp [h.bits, ih]
+
+omit [Fintype L] in
+private theorem realized_counts {hist : Scratch w endAddr → L → ℕ} {js ps}
+ (h : List.Forall₂ (RealizesJob hist) js ps) (s : Scratch w endAddr) (ready : Ready ps s) (l : L) :
+ hist (ps.foldl (fun t p => p.update t) s) l = hist s l + (js.map (fun j => j.increment l)).sum := by
+ induction h generalizing s with
+ | nil => simp
+ | cons h _ ih =>
+ rw [List.foldl_cons, ih _ ready.2, h.counts _ ready.1]
+ simp [Nat.add_assoc]
+
+/-- Link a native path at each listed job to one complete final-site
+expansion. The resulting burst reads exactly that witness's binary code
+and increments each histogram component by that witness's exponent. -/
+theorem execute_vertexJobs {p r k : ℕ} {M : Machine w p r k} {pc : Fin 9 → Fin p} {arcPC : Fin 5 → Fin p}
+ {reg : Fin 9 ↪ Fin r} {visit done : Fin p}
+ (hl : DFS.Linked M pc reg visit (arcPC 0) done) (ha : EndpointBits.Linked M arcPC (copyRegs reg) (pc 0))
+ (P : SiteParsers κ N) (trees : N.Site → VertexTree) (jobs : JobsFor P) (hs : JobsSpec P trees jobs)
+ (v : N.Site) (z : N.Half v) (x : (P.witnesses v z).Choice)
+ {m : Memory w} {pending : List (Word w)} {control : List (Event w)}
+ (visits : Visits m endAddr pending ((trees v).preorder.map (fun a : ℕ => (a : Word w))) control)
+ (native : List (VisitPath w endAddr)) (hist : Scratch w endAddr → L → ℕ)
+ (realized : List.Forall₂ (RealizesJob hist) (jobs v z x) native)
+ (hook : ∀ j ∈ native, j.Linked M visit (pc 3) reg m)
+ (c : Config w p r) (hc : c.pc = pc 0) (top : ℕ) (hstack : Represents c.privateMem top pending)
+ (hptr : top + pending.length = endAddr) (ht : c.reg (reg 5) = (top : Word w))
+ (he : c.reg (reg 6) = (endAddr : Word w)) (h1 : c.reg (reg 3) = 1)
+ (ready : Ready native (scratch endAddr c.privateMem)) :
+ ∃ out es, out.pc = done ∧ out.persistent = c.persistent ∧
+ choiceBits es = (P.read v z).encode x ∧
+ (∀ l, hist (scratch endAddr out.privateMem) l = hist (scratch endAddr c.privateMem) l + (P.witnesses v z).exponents x l) ∧
+ es.length = control.length + (native.map fun j => j.trace.length).sum ∧
+ countProbes es = countProbes control + (native.map fun j => countProbes j.trace).sum ∧
+ ∀ fuel bs, execute M.program (fuel + es.length) c m ((P.read v z).encode x ++ bs) =
+ (execute M.program fuel out m bs).map (fun q => ⟨es ++ q.events, q.result⟩) := by
+ have nodes : native.map VisitPath.node = (trees v).preorder.map (fun a : ℕ => (a : Word w)) := by
+ rw [← hs.addresses v z x, List.map_map]
+ exact realized_addresses realized
+ obtain ⟨out, es, hpc, hst, hout, hbs, hlen, hp, hrun⟩ :=
+ DFS.execute_linked_visits hl ha visits native nodes hook c hc top hstack hptr ht he h1 ready
+ have bits := hbs.trans ((realized_bits realized).trans (hs.bits v z x))
+ refine ⟨out, es, hpc, hst, bits, fun l => ?_, hlen, hp, ?_⟩
+ · rw [hout, realized_counts realized _ ready l, hs.increments v z x l]
+ · rw [← bits]
+ exact hrun
+
+end Native
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationVertexReportBudget.lean b/lean/OAI/Computability/VPVNP/PairSimulationVertexReportBudget.lean
new file mode 100644
index 0000000000..fb7c8e2e29
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationVertexReportBudget.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairTraversalTraffic
+import OAI.Computability.VPVNP.PairTraversalCost
+import OAI.Computability.VPVNP.CursorBranchCommunication
+
+/-!
+# Charging a final vertex's actual report against its transcript caps
+
+The report starts with bootstrap and geometry, loads the final incident bits,
+visits the stored DFS row and flushes the private histogram. The local calls
+may use a bounded number of header scans per occurrence; this is the only
+polylogarithmic factor in their external communication allowance.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexReportBudget
+
+open NetworkKernel Compression BurstRAM CursorNetwork Filter
+
+variable {A : Type*} {N : Network} {a g w : ℕ} (Y : State a g)
+ (chain : TermChain A N Y.network) (v : Y.network.Site)
+
+/-- `setup` bounds the geometry stage, `scan` bounds prologue and directory
+traffic per occurrence, and `fields` and `maps` bound the actual probe costs
+of field jobs and map-argument writers. All four constants are fixed. -/
+def coefficient (degree labels setup scan fields maps : ℕ) : ℕ :=
+ 32 + 5 * degree + 2 * labels + setup + scan + fields + maps
+
+/-- The report decomposition uses the real DFS visit proof and the actual
+bit incidence at the chosen output position. A role-dispatch probe and
+one original leaf header probe are both charged even when a leaf is a transit site. -/
+theorem probes_le (n q degree labels setup scan fields maps : ℕ) (mem : Memory w)
+ (root : Word w) (top : ℕ) (nodes : List (Word w)) (control : List (Event w))
+ (visited : DFS.Visits mem top [root] nodes control)
+ (hnodes : nodes.length ≤ chain.occurrences (fun _ ↦ 1) v)
+ (geometry hook fieldReads mapReads : ℕ) (rep : Report w) (hgeom : geometry ≤ setup)
+ (hfield : fieldReads ≤ chain.occurrences (fun _ ↦ 1) v * fields)
+ (hmap : mapReads ≤ chain.occurrences (fun _ ↦ 1) v * maps)
+ (hhook : hook ≤ 2 * nodes.length + fieldReads + mapReads +
+ scan * (chain.occurrences (fun _ ↦ 1) v * (n.log2 + 1) ^ q))
+ (hrep : rep.probes ≤ 9 + geometry + (5 * degree + incidentBits Y v) + countProbes control +
+ hook + 2 * labels) :
+ 1 + rep.probes ≤
+ siteAccesses Y chain (coefficient degree labels setup scan fields maps) q n v := by
+ let o := chain.occurrences (fun _ ↦ 1) v
+ let big := o * (n.log2 + 1) ^ q
+ let den := 1 + incidentBits Y v + big
+ let C := coefficient degree labels setup scan fields maps
+ have h₁ : 1 ≤ (n.log2 + 1) ^ q := Nat.one_le_pow q _ (by omega)
+ have hob : o ≤ big := Nat.le_mul_of_pos_right _ h₁
+ have hd : big ≤ den := Nat.le_add_left ..
+ have hi : incidentBits Y v ≤ den := by dsimp [den]; omega
+ have hn : nodes.length ≤ den := hnodes.trans (hob.trans hd)
+ have ho : o ≤ den := hob.trans hd
+ have hc : countProbes control ≤ 3 * den := by
+ have h := visited.cost.1
+ have hmul := Nat.mul_le_mul_left 3 hn
+ omega
+ have hden : 1 ≤ den := by dsimp [den]; omega
+ have hfix : 10 + setup + 5 * degree + 2 * labels ≤ (10 + setup + 5 * degree + 2 * labels) * den :=
+ Nat.le_mul_of_pos_right _ hden
+ have hf := hfield.trans ((Nat.mul_le_mul_right _ ho).trans_eq (Nat.mul_comm den fields))
+ have hm := hmap.trans ((Nat.mul_le_mul_right _ ho).trans_eq (Nat.mul_comm den maps))
+ have hs := Nat.mul_le_mul_left scan hd
+ change hook ≤ 2 * nodes.length + fieldReads + mapReads + scan * big at hhook
+ change 1 + rep.probes ≤ C * den
+ dsimp [C, coefficient]
+ ring_nf at hfix hf hm hs ⊢
+ omega
+
+set_option exponentiation.threshold 10000 in
+-- This is the explicit live private exponent in Section 13.
+/-- The native report contains the exact DFS control and local visit events.
+The other terms count the bootstrap, final-bit gather, histogram and finish.
+The 107-tick margin is available to the enclosing live call. -/
+theorem steps_le_45 {n degree labels geometry hook : ℕ} (hn : 2048 ≤ n)
+ (hdeg : degree ≤ n) (hlab : labels ≤ n) (hgeom : geometry ≤ n ^ 3)
+ (hinc : incidentBits Y v ≤ 2 * degree * n) (hvisits : chain.occurrences (fun _ ↦ 1) v ≤ n)
+ (mem : Memory w) (root : Word w) (top : ℕ) (nodes : List (Word w)) (control : List (Event w))
+ (visited : DFS.Visits mem top [root] nodes control)
+ (hnodes : nodes.length ≤ chain.occurrences (fun _ ↦ 1) v)
+ (hhook : hook ≤ n ^ 44) (rep : Report w)
+ (hrep : rep.events.length ≤ 44 + geometry + (15 + 21 * degree + 5 * incidentBits Y v) +
+ control.length + hook + 7 * labels + 14) : rep.events.length + 107 ≤ n ^ 45 := by
+ have h₁ : 1 ≤ n ^ 44 := Nat.one_le_pow _ _ (by omega)
+ have hₙ : n ≤ n ^ 44 := Nat.le_self_pow (by decide) n
+ have h₂ : n ^ 2 ≤ n ^ 44 := Nat.pow_le_pow_right (by omega) (by decide)
+ have h₃ : n ^ 3 ≤ n ^ 44 := Nat.pow_le_pow_right (by omega) (by decide)
+ have hi := hinc.trans (Nat.mul_le_mul_right n (Nat.mul_le_mul_left 2 hdeg))
+ rw [show 2 * n * n = 2 * n ^ 2 by ring] at hi
+ have hctrl := visited.cost.2
+ have hnode := hnodes.trans hvisits
+ have hfit : rep.events.length + 107 ≤ 300 * n ^ 44 := by omega
+ have hwide : 300 * n ^ 44 ≤ n ^ 45 := by
+ rw [pow_succ' n 44]; exact Nat.mul_le_mul_right _ (by omega)
+ exact hfit.trans hwide
+
+set_option exponentiation.threshold 10000 in
+-- This is the explicit live private exponent in Section 13.
+/-- Section 13's private clock follows from the stronger polynomial report bound. -/
+theorem steps_le {n degree labels geometry hook : ℕ} (hn : 2048 ≤ n)
+ (hdeg : degree ≤ n) (hlab : labels ≤ n) (hgeom : geometry ≤ n ^ 3)
+ (hinc : incidentBits Y v ≤ 2 * degree * n) (hvisits : chain.occurrences (fun _ ↦ 1) v ≤ n)
+ (mem : Memory w) (root : Word w) (top : ℕ) (nodes : List (Word w)) (control : List (Event w))
+ (visited : DFS.Visits mem top [root] nodes control)
+ (hnodes : nodes.length ≤ chain.occurrences (fun _ ↦ 1) v)
+ (hhook : hook ≤ n ^ 44) (rep : Report w)
+ (hrep : rep.events.length ≤ 44 + geometry + (15 + 21 * degree + 5 * incidentBits Y v) +
+ control.length + hook + 7 * labels + 14) : rep.events.length + 107 ≤ n ^ 10000 := by
+ exact (steps_le_45 Y chain v hn hdeg hlab hgeom hinc hvisits mem root top nodes control visited
+ hnodes hhook rep hrep).trans (Nat.pow_le_pow_right (by omega) (by decide))
+
+end PairSimulation.VertexReportBudget
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationWorkerControl.lean b/lean/OAI/Computability/VPVNP/PairSimulationWorkerControl.lean
new file mode 100644
index 0000000000..3d8a85bbc3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationWorkerControl.lean
@@ -0,0 +1,32 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalBlocks
+
+/-! # Single-worker frames at native terminal burst boundaries -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+open BurstRAM LiveProgram CompressorRecords
+
+variable {w : ℕ} (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap : ℕ)
+
+/-- Address frame for every successful single worker burst, with the actual
+controller writes applied before the next burst. -/
+structure WorkerControl (s : Stage) (a : ℕ) (m : Memory w) where
+ /-- Invariant on a worker's persistent state word and memory at burst boundaries, established
+ at state zero and propagated by returning bursts after controller writes. -/
+ inv : Word w → Memory w → Prop
+ ready : inv 0 m
+ advance : ∀ (st : Word w) (mem : Memory w) (bits : List Bool) (rep : Report w),
+ inv st mem →
+ execute (source workers s pub) (rawFuel pub cap (.resume s st)) ((source workers s pub).start st) mem bits =
+ some rep →
+ let out := after mem (report (header pub) (.resume s st) rep).events
+ out a = mem a ∧ ∀ st', rep.result = some st' → inv st' out
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationWorkerCut.lean b/lean/OAI/Computability/VPVNP/PairSimulationWorkerCut.lean
new file mode 100644
index 0000000000..0a0a4eb39f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationWorkerCut.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.PairSimulationSelectorRow
+import OAI.Computability.VPVNP.CompressorOnlineOrdinalForward
+import OAI.Computability.VPVNP.CompressorOnlineBranchCut
+
+/-! # The native term-worker cut at a physical calendar boundary
+
+Build every branch's source row from its encoded tapes and the actual
+reports returned by the term worker. The same boundary certificate
+recovers arbitrary accepting streams. The successor memory contains the
+records written by the recovered term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords CompressorRecords.SelectedTerms NetworkKernel BurstRAM
+open CompressorRecords.Schedule CompressorRecords.Schedule.Online
+open scoped Fin.CommRing
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {B : S.Templates}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w : ℕ} {X : State a g} {p : StatePass A X b n} {o : PassOrigin B f hf p}
+ {d initial phases cap : ℕ} {C : Catalog d} {plan : Config C initial phases} {ports : Ports w} {m : Memory w}
+
+/-- Instantiate the catalog worker named at the current calendar row with the directory words
+computed from that row's phase and memory. -/
+def RowStartTable (entry : Run.RowStart plan ports cap m) : ProgramTable w :=
+ let x := rowInput plan ports m entry.phase
+ ⟨_,((C entry.worker).table.instantiate w (Directory.words C ports entry.worker x)).program⟩
+
+/-- Calendar step for a semantic term choice, recording the entry phase, worker and fuel
+together with the per-motif worker tapes and reports from the selected run. -/
+noncomputable def WorkerInput.selectedStep (I : WorkerInput o w) (entry : Run.RowStart plan ports cap m)
+ (i : p.step.Choice) : Run.Step d (initial+phases) w :=
+ ⟨entry.phase,⟨rowInput plan ports m entry.phase,entry.worker,entry.fuel,List.ofFn (workerTapes o w i),(I.selected_run i).choose⟩⟩
+
+theorem WorkerInput.selectedStep_valid (I : WorkerInput o w) (entry : Run.RowStart plan ports cap m)
+ (live : m ports.ordinal.val < m ports.rows.val) (installed : RowStartTable entry = I.table)
+ (fuel : entry.fuel = I.fuel) (start : Directory.start C ports (rowInput plan ports m entry.phase) = 0)
+ (stop : (Directory.bound C ports (rowInput plan ports m entry.phase)).val = o.motifCount)
+ (memory : Directory.prepared C ports (rowInput plan ports m entry.phase) = I.memory) (i : p.step.Choice) :
+ (I.selectedStep entry i).Valid plan ports cap m := by
+ let G := grid o
+ let x := rowInput plan ports m entry.phase
+ let st := Directory.start C ports x
+ let bound := Directory.bound C ports x
+ let pub := Directory.words C ports entry.worker x
+ let bank := Directory.prepared C ports x
+ let cursor (j : ℕ) : Word w := j
+ let tapes := List.ofFn (workerTapes o w i)
+ let logs := (I.selected_run i).choose
+ have hrun := (I.selected_run i).choose_spec.1
+ have run : runSegment (RowStartTable entry).2 entry.fuel (some st) bank tapes = some logs := by
+ have h := congrArg (fun T : ProgramTable w => runSegment T.2 I.fuel (some 0) I.memory tapes) installed
+ change st = 0 at start
+ change bank = I.memory at memory
+ rw [fuel,start,memory]
+ exact h.trans hrun
+ refine ⟨entry.calendarPhase,live,rfl,⟨by simp [selectedStep,rowInput,writeMemory],
+ entry.liveRow,entry.positiveFuel,run,?_⟩,entry.recipeCap,entry.dataCap⟩
+ have hfit : o.motifCount < 2^w := stop ▸ bound.isLt
+ have ha (j : ℕ) (hj : j execute T.2 entry.fuel (T.2.start (cursor j)) mem b) installed
+ have native := hsame.symm.trans h
+ let a : Fin o.motifCount := ⟨j,hj⟩
+ obtain ⟨hs,ht⟩ := I.addresses a
+ have hsrc := hs.symm ▸ I.layout.sourceFits a
+ have hdst := ht.symm ▸ I.layout.termFits a
+ have inc := (TermWorker.Footprint.call G.block G.demandOrder.entries G.supplyOrder.entries I.addr
+ (cursor j) mem entry.fuel b rep hsrc hdst native).1
+ simpa only [cursor,Nat.cast_add,Nat.cast_one] using inc
+ have enough : entry.fuel ≤ cap := by have h := entry.dataCap; omega
+ change ValidTrace C entry.worker ports pub bound st bank logs
+ have inv := entry.initialInv
+ change entry.invariant st bank at inv
+ change st = 0 at start
+ rw [start] at run inv ⊢
+ exact ordinalFrame entry.dataStep enough cursor ha hc advance 0 tapes bank logs
+ (by simp [tapes]) entry.ready inv run
+
+/-- Every semantic term has one actual native row and every accepting
+continuation of the table contains one of these full row prefixes. -/
+noncomputable def WorkerInput.selectorCut (I : WorkerInput o w) (entry : Run.RowStart plan ports cap m)
+ (controls : Run.ControlBounds plan cap (w := w)) (state : Word w)
+ (tag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d (initial+phases)))
+ (live : m ports.ordinal.val < m ports.rows.val) (installed : RowStartTable entry = I.table)
+ (fuel : entry.fuel = I.fuel) (start : Directory.start C ports (rowInput plan ports m entry.phase) = 0)
+ (stop : (Directory.bound C ports (rowInput plan ports m entry.phase)).val = o.motifCount)
+ (memory : Directory.prepared C ports (rowInput plan ports m entry.phase) = I.memory) :
+ BranchSegments.Cut (program plan ports) cap (some state) m p.step.Choice := by
+ apply Run.selectorCut plan ports controls tag entry live (I.selectedStep entry)
+ (I.selectedStep_valid entry live installed fuel start stop memory) ?_ o.motifCount ?_ ?_
+ · intro s valid hp hw hf
+ have x := valid.input.trans (congrArg (rowInput plan ports m) hp)
+ have same : sourceTable C ports s.row = I.table := by
+ let installedAt (j : Fin d) : ProgramTable w :=
+ ⟨_,((C j).table.instantiate w (Directory.words C ports j (rowInput plan ports m entry.phase))).program⟩
+ have eq := (congrArg installedAt hw).trans installed
+ simpa only [sourceTable,x] using eq
+ obtain ⟨_,i,hi,_⟩ := I.validRow_unique s.row valid.source same (hf.trans fuel)
+ (x ▸ start) (x ▸ stop) (by simpa only [Directory.Row.dataMemory,x] using memory)
+ exact ⟨i,hi⟩
+ · exact fun _ => List.length_ofFn
+ · intro i j h
+ exact I.termEquiv.injective (Subtype.ext (List.ofFn_inj.mp h))
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationWorkerPhaseEquiv.lean b/lean/OAI/Computability/VPVNP/PairSimulationWorkerPhaseEquiv.lean
new file mode 100644
index 0000000000..94bc4e1b17
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationWorkerPhaseEquiv.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalBlocks
+import OAI.Computability.VPVNP.PairSimulationTerminalPhaseBuild
+import OAI.Computability.VPVNP.PairSimulationTerminalTraceEquiv
+import OAI.Computability.VPVNP.CompressorOnlineWorkerInversion
+
+/-!
+# Relocating all accepted source worker paths to their terminal phase
+
+The source executes on memory agreeing with the physical bank away from the
+two terminal controller cells. Known paths replay forward after the clock is
+reduced by the dispatch allowance. Conversely every completed physical block
+can be recovered at the full source clock. The chosen memory readback agrees
+at every worker address, including the dense histogram.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+open BurstRAM LiveProgram CompressorRecords
+
+private theorem reclock {w f g : ℕ} {K : Type*} {P : BurstRAM.Program w K} {s : Option (Word w)} {m : Memory w}
+ {bs : List (List Bool)} {rs : List (Report w)}
+ (h : runSegment P f s m bs = some rs) (room : ∀ r ∈ rs, r.events.length < g) :
+ runSegment P g s m bs = some rs := by
+ induction bs generalizing s m rs with
+ | nil => exact h
+ | cons b bs ih =>
+ cases s with
+ | none => contradiction
+ | some st =>
+ cases run : execute P f (P.start st) m b with
+ | none => simp [runSegment,run] at h
+ | some r =>
+ simp only [runSegment,run,Option.map_eq_some_iff] at h
+ obtain ⟨tail,ht,rfl⟩ := h
+ obtain ⟨hr,rest⟩ := List.forall_mem_cons.mp room
+ simp only [runSegment,execute_at_cap run hr,ih ht rest,Option.map_some]
+
+variable {w : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w} {cap : ℕ}
+variable {e : Entry w} {src phy : Memory w}
+
+/-- Obligations for the actual worker reports under the terminal controller. -/
+structure WorkerFrame (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap : ℕ)
+ (e : Entry w) (src phy : Memory w) where
+ clock : 30 ≤ cap
+ agree : SourceTransport.Agree (workerCell (header pub)) src phy
+ sourceReads : ∀ p : ActualPaths (source workers e.stage pub) cap e.state src (fun _ => True),
+ SourceTransport.Reads (workerCell (header pub)) (eventLog p.property.choose)
+ sourceRoom : ∀ p : ActualPaths (source workers e.stage pub) cap e.state src (fun _ => True),
+ ∀ r ∈ p.property.choose, r.events.length < cap-30
+ phaseReads : ∀ q : CompletedPhase workers pub cap e phy,
+ SourceTransport.Reads (workerCell (header pub)) (eventLog (q.val.logs.map Prod.snd))
+
+namespace WorkerFrame
+variable (F : WorkerFrame workers pub cap e src phy)
+
+/-- Transport a completed source-worker path to a physical terminal phase, adding the
+controller reports and computing the resulting physical memory from their events. -/
+noncomputable def block (p : ActualPaths (source workers e.stage pub) cap e.state src (fun _ => True)) :
+ CompletedPhase workers pub cap e phy :=
+ let rs := p.property.choose
+ ⟨⟨p.val,stageLogs e rs,after phy (eventLog (stageReports (header pub) e rs))⟩,
+ closed_phase workers pub (cap-30) cap e src phy p.val rs (Nat.sub_add_cancel F.clock).le F.agree
+ (F.sourceReads p) (reclock p.property.choose_spec.1 (F.sourceRoom p)) p.property.choose_spec.2.1⟩
+
+/-- All actual physical completions, including arbitrary incoming tape
+lengths, are obtained from the original worker at the selected memory. -/
+noncomputable def sourceBlockEquiv :
+ ActualPaths (source workers e.stage pub) cap e.state src (fun _ => True) ≃ CompletedPhase workers pub cap e phy :=
+ Equiv.ofBijective F.block ⟨fun _ _ h => Subtype.ext (congrArg (fun q => q.val.choices) h),by
+ intro q
+ obtain ⟨hr,hh,_⟩ := q.prop.source_segment workers pub cap src F.agree (F.phaseReads q)
+ let p : ActualPaths (source workers e.stage pub) cap e.state src (fun _ => True) :=
+ ⟨q.val.choices,q.val.logs.map Prod.snd,hr,hh,trivial⟩
+ refine ⟨p,Subtype.ext ?_⟩
+ exact ((F.block p).prop.block_eq_suffix q.prop (a := []) (b := []) rfl).1⟩
+
+theorem sourceBlock_choices (p : ActualPaths (source workers e.stage pub) cap e.state src (fun _ => True)) :
+ (F.sourceBlockEquiv p).val.choices = p.val := rfl
+
+theorem sourceBlock_reports (p : ActualPaths (source workers e.stage pub) cap e.state src (fun _ => True)) :
+ (F.sourceBlockEquiv p).val.logs = stageLogs e p.property.choose := rfl
+
+theorem sourceBlock_memory (p : ActualPaths (source workers e.stage pub) cap e.state src (fun _ => True)) :
+ SourceTransport.Agree (workerCell (header pub)) (after src (eventLog p.property.choose))
+ (F.sourceBlockEquiv p).val.memory := by
+ let q := F.sourceBlockEquiv p
+ have h := (q.prop.source_segment workers pub cap src F.agree (F.phaseReads q)).2.2
+ simpa only [q,sourceBlock_reports,stageLogs_raw] using h
+
+end WorkerFrame
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationWorkerRebase.lean b/lean/OAI/Computability/VPVNP/PairSimulationWorkerRebase.lean
new file mode 100644
index 0000000000..9806827bb6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationWorkerRebase.lean
@@ -0,0 +1,36 @@
+import OAI.Computability.VPVNP.CompressorSourceTransport
+import OAI.Computability.VPVNP.PairSimulationSelectorReindex
+
+/-! # Transport of worker inputs across changes to scheduler memory -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords CompressorRecords.SelectedTerms NetworkKernel BurstRAM
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {B : S.Templates}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w : ℕ} {X : State a g} {p : StatePass A X b n} {o : PassOrigin B f hf p}
+
+/-- Run a worker from a new memory agreeing on the region containing its demand rows. -/
+noncomputable def WorkerInput.rebase (I : WorkerInput o w) (m : Memory w) (lo : ℕ)
+ (readable : ∀ i, lo ≤ (I.layout.source i).val)
+ (agree : SourceTransport.Agree (lo ≤ ·) I.memory m) : WorkerInput o w :=
+ { I with
+ memory := m
+ inputs := by
+ intro i
+ funext x
+ obtain ⟨j, rfl⟩ := (grid o).demandOrder.entries.surjective x
+ have h := congrFun (I.inputs i) ((grid o).demandOrder.entries j)
+ rw [DemandPreparation.demandAt_address _ _ _ (I.layout.sourceFits i)] at h ⊢
+ exact (congrArg Fin.val (agree _ ((readable i).trans (Nat.le_add_right ..)))).symm.trans h }
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationWorkspacePrefix.lean b/lean/OAI/Computability/VPVNP/PairSimulationWorkspacePrefix.lean
new file mode 100644
index 0000000000..f500ad2076
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationWorkspacePrefix.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.PairSimulationWorkspaceWorkerCut
+import OAI.Computability.VPVNP.CompressorPrefixFrames
+
+/-! # Protected addresses on arbitrary partial terminal-selector tapes
+
+A prefix ending between two motifs can be successful even when no choice
+exists for a later motif. Each actual data call writes only in its placed
+row. Once the closing guard is reached, the complete source tape decodes
+to a mathematical term and the following calls belong to its continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords CompressorRecords.SelectedTerms NetworkKernel BurstRAM
+open CompressorRecords.Schedule CompressorRecords.Schedule.Online
+open DescriptorSpace BlockPlanner SourceTransport
+open scoped Fin.CommRing
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {B : S.Templates}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w cap : ℕ} {X : State a g} {p : StatePass A X b n} {o : PassOrigin B f hf p}
+
+variable (I : WorkerInput o w) (script : Script) (L : DescriptorSpace.Layout) (pub : Fin 11 → Word w)
+local notation "pt" => Workspace.ports (arity script.catalog) (pub 2)
+local notation "H" => levelStart L 0
+
+open BranchSegments
+open private workerLow workerBanks from OAI.Computability.VPVNP.PairSimulationWorkspaceWorkerCut
+
+variable {m : Memory w} (entry : Run.RowStart script.plan (OnlineWorkspace.ports (C := script.catalog) pub) cap m)
+ (controls : Run.ControlBounds script.plan cap (w := w)) (state : Word w)
+ (tag : m (OnlineWorkspace.ports (C := script.catalog) pub).tag.val = LiveStageLink.tagWord w (calendarIndex script.size script.size))
+ (live : m (OnlineWorkspace.ports (C := script.catalog) pub).ordinal.val < m (OnlineWorkspace.ports (C := script.catalog) pub).rows.val) (installed : RowStartTable entry = I.table)
+ (fuel : entry.fuel = I.fuel) (start : Directory.start script.catalog (OnlineWorkspace.ports (C := script.catalog) pub) (rowInput script.plan (OnlineWorkspace.ports (C := script.catalog) pub) m entry.phase) = 0)
+ (stop : (Directory.bound script.catalog (OnlineWorkspace.ports (C := script.catalog) pub) (rowInput script.plan (OnlineWorkspace.ports (C := script.catalog) pub) m entry.phase)).val = o.motifCount)
+ (memory : Directory.prepared script.catalog (OnlineWorkspace.ports (C := script.catalog) pub) (rowInput script.plan (OnlineWorkspace.ports (C := script.catalog) pub) m entry.phase) = I.memory)
+ (hg : arity script.catalog = L.shape.arity) (hb : (pub 2).val = L.base) (fit : levelStart L 0 < 2^w)
+ (bank : Workspace.Installed (arity script.catalog) (pub 2) m)
+ (room : (m (OnlineWorkspace.ports (C := script.catalog) pub).ordinal.val).val < directoryRows L) (placement : ∀ i, levelStart L 0 ≤ (I.layout.base i).val)
+local notation "cut" => I.workspaceSelectorCut script L pub entry controls state tag live installed fuel
+ start stop memory hg hb fit bank room placement
+local notation "row" => I.selectedStep entry
+
+/-- Invert every submitted prefix, including prefixes with no accepting
+extension. The scheduler can pass control beyond this row only after the
+actual choice tape has identified one of the mathematical terms. -/
+theorem WorkerInput.workspaceSelectorCut_prefixFrame :
+ (cut).PrefixFrame ((pub 2).val+6) := by
+ constructor
+ · exact I.workspaceSelectorCut_stable script L pub entry controls state tag live installed fuel start stop memory
+ hg hb fit bank room placement
+ · intro bits logs run
+ let x := rowInput script.plan pt m entry.phase
+ let prep : Segment (program script.plan pt) cap (some state) m :=
+ ⟨List.replicate 3 [], preparation script.plan pt m entry.phase, by
+ change runSegment _ _ _ _ ([] :: [] :: [] :: []) = _
+ rw [prepare_segment script.plan pt state m entry.phase tag controls.tags live entry.calendarPhase entry.liveRow
+ controls.calendar entry.recipeCap controls.launch []]
+ simp [runSegment]⟩
+ have stable := SourceBankFrame.preparation_stable script L (pub 2) hg hb fit m entry.phase room
+ let framed := OnlineWorkspace.framedSegment script.plan pub prep (stable.banks bank)
+ have keep : SourceBankFrame.Stable ((pub 2).val+6) m framed.logs := stable.framed _
+ rcases Cut.deterministic_prefix framed 3 rfl keep run with short | ⟨tail,rfl⟩
+ · exact Or.inl short
+ rw [PrimedSchedule.runSegment_append, framed.run] at run
+ change (runSegment _ _ framed.state framed.memory tail).map _ = some logs at run
+ obtain ⟨reps,suffix,rfl⟩ := Option.map_eq_some_iff.mp run
+ obtain ⟨ps,pm⟩ := preparation_effect script.plan pt state m entry.phase
+ have stateEq : framed.state = some (Directory.start script.catalog pt x) :=
+ (OnlineWorkspace.framedSegment_state script.plan pub prep _).trans ps
+ have memoryEq : framed.memory = Directory.prepared script.catalog pt x :=
+ (OnlineWorkspace.framedSegment_memory script.plan pub prep _).trans pm
+ rw [stateEq,memoryEq] at suffix
+ have prepared := stable.installed bank (preparation script.plan pt m entry.phase).length
+ rw [List.take_length,pm] at prepared
+ have low : (pub 2).val+6 ≤ H := by
+ simp only [hb,levelStart,levelsBase,Nat.zero_mul,Nat.add_zero,directoryBase,plannerTag,frameBase]
+ omega
+ have apart := fun i => low.trans (placement i)
+ rcases OnlineWorkspace.workerPrefixCases script.plan pub entry.worker _ _ cap entry.fuel entry.invariant
+ entry.dataStep (workerBanks I script pub entry installed stop apart) ((pub 2).val+6)
+ (fun st mem bs rep _ live run => workerLow I script pub entry installed stop apart st mem bs rep live run)
+ controls.tags _ _ entry.ready entry.initialInv prepared tail reps suffix with ⟨hprefix,_⟩ | ⟨db,rest,raw,hb,hr,hv⟩
+ · left
+ apply keep.append
+ change SourceBankFrame.Stable ((pub 2).val+6) framed.memory reps
+ rw [memoryEq]
+ exact hprefix
+ · let recovered : Directory.Row script.size w := ⟨x,entry.worker,entry.fuel,db,raw⟩
+ have valid : recovered.Valid script.catalog pt :=
+ ⟨by simp [recovered,x,rowInput,writeMemory],entry.liveRow,entry.positiveFuel,hr,hv⟩
+ obtain ⟨_,term,he,_⟩ := I.validRow_unique recovered valid installed fuel start stop memory
+ right
+ refine ⟨term,rest,?_⟩
+ change [] :: [] :: [] :: tail = [] :: [] :: [] :: ((List.ofFn (workerTapes o w term) ++ [[]]) ++ rest)
+ rw [hb,show db = List.ofFn (workerTapes o w term) from he,List.append_assoc]
+ rfl
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationWorkspaceSelectorInterval.lean b/lean/OAI/Computability/VPVNP/PairSimulationWorkspaceSelectorInterval.lean
new file mode 100644
index 0000000000..c832667fd5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationWorkspaceSelectorInterval.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.CompressorPassIntervalData
+import OAI.Computability.VPVNP.PairSimulationWorkspacePrefix
+
+/-! # The physical selector interval and its row-specific source clock -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords CompressorRecords.SelectedTerms NetworkKernel BurstRAM
+open CompressorRecords.Schedule CompressorRecords.Schedule.Online
+open DescriptorSpace BlockPlanner SourceTransport
+open scoped Fin.CommRing
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {B : S.Templates}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w cap : ℕ} {X : State a g} {p : StatePass A X b n} {o : PassOrigin B f hf p}
+
+variable (I : WorkerInput o w) (script : Script) (L : DescriptorSpace.Layout) (pub : Fin 11 → Word w)
+local notation "pt" => Workspace.ports (arity script.catalog) (pub 2)
+local notation "H" => levelStart L 0
+
+open BranchSegments
+
+variable {m : Memory w} (entry : Run.RowStart script.plan (OnlineWorkspace.ports (C := script.catalog) pub) cap m)
+ (controls : Run.ControlBounds script.plan cap (w := w)) (state : Word w)
+ (tag : m (OnlineWorkspace.ports (C := script.catalog) pub).tag.val = LiveStageLink.tagWord w (calendarIndex script.size script.size))
+ (live : m (OnlineWorkspace.ports (C := script.catalog) pub).ordinal.val < m (OnlineWorkspace.ports (C := script.catalog) pub).rows.val) (installed : RowStartTable entry = I.table)
+ (fuel : entry.fuel = I.fuel) (start : Directory.start script.catalog (OnlineWorkspace.ports (C := script.catalog) pub) (rowInput script.plan (OnlineWorkspace.ports (C := script.catalog) pub) m entry.phase) = 0)
+ (stop : (Directory.bound script.catalog (OnlineWorkspace.ports (C := script.catalog) pub) (rowInput script.plan (OnlineWorkspace.ports (C := script.catalog) pub) m entry.phase)).val = o.motifCount)
+ (memory : Directory.prepared script.catalog (OnlineWorkspace.ports (C := script.catalog) pub) (rowInput script.plan (OnlineWorkspace.ports (C := script.catalog) pub) m entry.phase) = I.memory)
+ (hg : arity script.catalog = L.shape.arity) (hb : (pub 2).val = L.base) (fit : levelStart L 0 < 2^w)
+ (bank : Workspace.Installed (arity script.catalog) (pub 2) m)
+ (room : (m (OnlineWorkspace.ports (C := script.catalog) pub).ordinal.val).val < directoryRows L) (placement : ∀ i, levelStart L 0 ≤ (I.layout.base i).val)
+local notation "framedCut" => I.workspaceSelectorCut script L pub entry controls state tag live installed fuel
+ start stop memory hg hb fit bank room placement
+local notation "selected" => I.selectedStep entry
+
+
+variable {small : ℕ} (smallBounds : Run.ControlBounds script.plan small (w := w))
+ (recipeClock : (script.plan.recipes entry.phase).2.code.length+1+2*N script.size script.size+5 ≤ small)
+ (dataClock : entry.fuel+3+4*((script.catalog entry.worker).params+1)+2*N script.size script.size+5 ≤ small)
+
+/-- The physical selector at the outer clock, with the exact same inner row
+reports verified at the smaller computational clock used for charging. -/
+noncomputable def WorkerInput.workspaceSelectorInterval :
+ ScheduledTrace.SelectorInterval script pub cap small (some state) m p.step.Choice where
+ cut := framedCut
+ frame := I.workspaceSelectorCut_prefixFrame script L pub entry controls state tag live installed fuel start stop memory
+ hg hb fit bank room placement
+ state := I.workspaceSelectorCut_state script L pub entry controls state tag live installed fuel start stop memory
+ hg hb fit bank room placement
+ source i :=
+ let s := (selected) i
+ let valid := I.selectedStep_valid entry live installed fuel start stop memory i
+ let short : s.Valid script.plan pt small m := ⟨valid.phase,valid.active,valid.input,valid.source,recipeClock,dataClock⟩
+ ⟨rowLog script.plan pt m s.phase s.row, (Run.oneRow script.plan pt (state := state) smallBounds tag s short).run,rfl⟩
+
+local notation "interval" => I.workspaceSelectorInterval script L pub entry controls state tag live installed fuel
+ start stop memory hg hb fit bank room placement smallBounds recipeClock dataClock
+
+/-- Exact cost of this interval in terms of its native term-worker reports,
+the active arity and the recipe metadata reads. -/
+theorem WorkerInput.workspaceSelectorInterval_cost (i : p.step.Choice) :
+ let raw := (I.selected_run i).choose
+ RAMBuckets.cost Report.probes ((interval).source i).logs =
+ RAMBuckets.cost Report.probes raw + raw.length*((script.catalog entry.worker).params+2) +
+ (script.plan.recipes entry.phase).2.reads + 3*arity script.catalog + (script.catalog entry.worker).params + 26 :=
+ row_cost script.plan pt m entry.phase ((selected) i).row
+ (I.selectedStep_valid entry live installed fuel start stop memory i).source
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationWorkspaceSelectorPost.lean b/lean/OAI/Computability/VPVNP/PairSimulationWorkspaceSelectorPost.lean
new file mode 100644
index 0000000000..4c667e7fa9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationWorkspaceSelectorPost.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.CompressorBlockProgram
+import OAI.Computability.VPVNP.CompressorSelectorGroupPost
+import OAI.Computability.VPVNP.PairSimulationSelectorStart
+import OAI.Computability.VPVNP.PairSimulationWorkspaceSelectorInterval
+
+/-! # The selected term packet at its physical workspace boundary
+
+The script's selector occurrence determines the native worker input and
+the private clock. Its workspace interval consumes the term's worker tapes.
+A source packet with those tapes therefore describes the memory and cost
+of that particular branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CompressorRecords.ScheduledTrace
+
+open BurstRAM Compression DescriptorSpace Schedule SourceTransport PairSimulation.LocalHistory
+open scoped Fin.CommRing
+attribute [local irreducible] BlockProgram.script
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w : ℕ} {X : State a g} {p : StatePass A X b n}
+
+/-- Inputs and clock bounds at the actual calendar occurrence of the native term selector. -/
+structure SelectorSite (o : PassOrigin B f hf p) (L : Layout) (pub : Fin 11 → Word w)
+ (cap small : ℕ) (m : Memory w) (script : BlockPlanner.Script := BlockProgram.script B) where
+ /-- Native worker input for the term selector at this occurrence in the scheduled block. -/
+ I : WorkerInput o w
+ /-- Index of this term-selector occurrence in the block planner's script. -/
+ j : Fin script.size
+ /-- Certificate that the selected calendar occurrence starts this worker on its intended row,
+ with the recorded table, fuel, bounds, and input memory. -/
+ start : I.SelectorBoundary script (pub 2) m cap j
+ placement : ∀ i, levelStart L 0 ≤ (I.layout.base i).val
+ recipeClock : (script.plan.recipes start.entry.phase).2.code.length + 1 + 2 * Online.N script.size script.size + 5 ≤ small
+ dataClock : start.entry.fuel + 3 + 4 * ((script.catalog start.entry.worker).params + 1) + 2 * Online.N script.size script.size + 5 ≤ small
+
+namespace SelectorSite
+
+variable {o : PassOrigin B f hf p} {L : Layout} {pub : Fin 11 → Word w} {cap small : ℕ} {m : Memory w}
+
+variable {script : BlockPlanner.Script}
+
+variable (site : SelectorSite o L pub cap small m script)
+ (bounds : Online.Run.ControlBounds script.plan cap (w := w))
+ (smallBounds : Online.Run.ControlBounds script.plan small (w := w))
+ (hg : arity script.catalog = L.shape.arity) (hb : (pub 2).val = L.base)
+ (fit : levelStart L 0 < 2 ^ w) (bank : Workspace.Installed (arity script.catalog) (pub 2) m)
+ (tag : m (Workspace.ports (arity script.catalog) (pub 2)).tag.val = LiveStageLink.tagWord w (Online.calendarIndex script.size script.size)) (live : m (Workspace.ports (arity script.catalog) (pub 2)).ordinal.val < m (Workspace.ports (arity script.catalog) (pub 2)).rows.val)
+ (room : (m (Workspace.ports (arity script.catalog) (pub 2)).ordinal.val).val < directoryRows L)
+
+/-- Execute the installed selector from calendar state zero at its two clocks. -/
+noncomputable def interval : SelectorInterval script pub cap small (some 0) m p.step.Choice :=
+ site.I.workspaceSelectorInterval script L pub site.start.entry bounds 0 tag live
+ site.start.table site.start.fuel site.start.start site.start.stop site.start.memory
+ hg hb fit bank room site.placement smallBounds site.recipeClock site.dataClock
+
+local notation "out" => site.interval bounds smallBounds hg hb fit bank tag live room
+
+/-- A physical branch consumes the entering control tapes, one worker tape per motif,
+and the empty return tape. -/
+theorem interval_bits (i : p.step.Choice) :
+ ((out).cut.part i).bits = [] :: [] :: [] :: (List.ofFn (workerTapes o w i) ++ [[]]) := rfl
+
+/-- Identify the memory and private-clock work of this physical branch with its source packet. -/
+theorem interval_post (i : p.step.Choice) (pkt : SourceOnline.Packet script w)
+ {raw : Memory w} {ordinal total : ℕ}
+ (group : SourceOnline.Group script L (pub 2) small ordinal total raw [pkt])
+ (tapes : pkt.stage.choices = List.ofFn (workerTapes o w i)) (totalRoom : total ≤ directoryRows L)
+ (agree : Agree (levelStart L 0 ≤ ·) raw m)
+ (ord : (m (Workspace.ports (arity script.catalog) (pub 2)).ordinal.val).val = ordinal) (rows : (m (Workspace.ports (arity script.catalog) (pub 2)).rows.val).val = total)
+ (stride : m ((Workspace.ports (arity script.catalog) (pub 2)).directory - 1).val = (levelWords L : Word w)) :
+ let mem := ((out).cut.part i).memory
+ Agree (levelStart L 0 ≤ ·) pkt.output mem ∧ Workspace.Installed (arity script.catalog) (pub 2) mem ∧
+ mem (Workspace.ports (arity script.catalog) (pub 2)).tag.val = LiveStageLink.tagWord w (Online.calendarIndex script.size script.size) ∧ (mem (Workspace.ports (arity script.catalog) (pub 2)).ordinal.val).val = ordinal + 1 ∧
+ (mem (Workspace.ports (arity script.catalog) (pub 2)).rows.val).val = total ∧ mem ((Workspace.ports (arity script.catalog) (pub 2)).directory - 1).val = (levelWords L : Word w) ∧
+ RAMBuckets.cost Report.probes ((out).source i).logs ≤ groupCost script [pkt] := by
+ apply selectorGroupPost out i pkt group _ smallBounds hg hb fit _ totalRoom agree bank tag ord rows stride
+ · rw [tapes]
+ exact site.interval_bits bounds smallBounds hg hb fit bank tag live room i
+ · exact ord ▸ rows ▸ Fin.lt_def.mp live
+
+end SelectorSite
+end CompressorRecords.ScheduledTrace
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairSimulationWorkspaceWorkerCut.lean b/lean/OAI/Computability/VPVNP/PairSimulationWorkspaceWorkerCut.lean
new file mode 100644
index 0000000000..31d6f8f982
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairSimulationWorkspaceWorkerCut.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.PairSimulationWorkerCut
+import OAI.Computability.VPVNP.CompressorWorkspaceIntervals
+
+/-! # Recovering a semantic term from the physical workspace-framed selector -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression CompressorRecords CompressorRecords.SelectedTerms NetworkKernel BurstRAM
+open CompressorRecords.Schedule CompressorRecords.Schedule.Online
+open DescriptorSpace BlockPlanner SourceTransport
+open scoped Fin.CommRing
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {B : S.Templates}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {a g b n w cap : ℕ} {X : State a g} {p : StatePass A X b n} {o : PassOrigin B f hf p}
+
+variable (I : WorkerInput o w) (script : Script) (L : DescriptorSpace.Layout) (pub : Fin 11 → Word w)
+local notation "pt" => Workspace.ports (arity script.catalog) (pub 2)
+local notation "H" => levelStart L 0
+
+/-- The actual term-table call, including an arbitrary choice tape, writes
+only above the six framing pointers. -/
+private theorem workerLow {m : Memory w} (entry : Run.RowStart script.plan pt cap m)
+ (installed : RowStartTable entry = I.table)
+ (stop : (Directory.bound script.catalog pt (rowInput script.plan pt m entry.phase)).val = o.motifCount)
+ (apart : ∀ i, (pub 2).val+6 ≤ (I.layout.base i).val) :
+ let x := rowInput script.plan pt m entry.phase
+ let P := (RowStartTable entry).2
+ ∀ cursor mem bs rep, cursor < Directory.bound script.catalog pt x →
+ execute P cap (P.start cursor) mem bs = some rep →
+ ∀ a < (pub 2).val+6, after mem rep.events a = mem a := by
+ intro x P cursor mem bs rep live run
+ have hi : cursor.val < o.motifCount := (Fin.lt_def.mp live).trans_eq stop
+ let i : Fin o.motifCount := ⟨cursor.val,hi⟩
+ have eqn : (i.val : Word w) = cursor := Fin.ofNat_val_eq_self _
+ have same := congrArg (fun T : ProgramTable w => execute T.2 cap (T.2.start cursor) mem bs) installed
+ have native := same.symm.trans run
+ rw [← eqn] at native
+ let G := grid o
+ obtain ⟨hs,ht⟩ := I.addresses i
+ have writes := (TermWorker.Footprint.call G.block G.demandOrder.entries G.supplyOrder.entries I.addr
+ (i.val : Word w) mem cap bs rep (hs.symm ▸ I.layout.sourceFits i) (ht.symm ▸ I.layout.termFits i) native).2.2
+ rw [ht] at writes
+ intro a ha
+ exact after_outside mem writes (fun hw => (not_lt_of_ge ((apart i).trans hw.1)) ha)
+
+private theorem workerBanks {m : Memory w} (entry : Run.RowStart script.plan pt cap m)
+ (installed : RowStartTable entry = I.table)
+ (stop : (Directory.bound script.catalog pt (rowInput script.plan pt m entry.phase)).val = o.motifCount)
+ (apart : ∀ i, (pub 2).val+6 ≤ (I.layout.base i).val) :
+ let x := rowInput script.plan pt m entry.phase
+ OnlineWorkspace.WorkerBanks pub entry.worker (Directory.words script.catalog pt entry.worker x)
+ (Directory.bound script.catalog pt x) cap entry.invariant := by
+ intro x cursor mem bs rep _ live bank run
+ apply bank.preserve
+ intro s
+ apply workerLow I script pub entry installed stop apart cursor mem bs rep live run
+ exact (Nat.mod_le _ _).trans_lt (Nat.add_lt_add_left ((Nat.mod_le _ _).trans_lt s.isLt) _)
+
+private theorem selected_writes (term : p.step.Choice) (placement : ∀ i, H ≤ (I.layout.base i).val) :
+ Writes (H ≤ ·) (eventLog (I.selected_run term).choose) := by
+ let G := grid o
+ exact (TermWorker.Footprint.segment G.block G.demandOrder.entries G.supplyOrder.entries I.layout I.addr
+ I.addresses (fun _ => True) (H ≤ ·) (fun _ _ _ _ => trivial) (fun _ => trivial)
+ (fun i _ lo _ => (placement i).trans lo) 0 I.fuel I.memory (List.ofFn (workerTapes o w term))
+ (I.selected_run term).choose (by simp) (I.selected_run term).choose_spec.1).2
+
+/-- Every accepting run through the Fin-11 selector reaches exactly one
+mathematical term. The selected prefix retains every framing report and the
+computed continuation memory. -/
+noncomputable def WorkerInput.workspaceSelectorCut {m : Memory w} (entry : Run.RowStart script.plan pt cap m)
+ (controls : Run.ControlBounds script.plan cap (w := w)) (state : Word w)
+ (tag : m (pt).tag.val = LiveStageLink.tagWord w (calendarIndex script.size script.size))
+ (live : m (pt).ordinal.val < m (pt).rows.val) (installed : RowStartTable entry = I.table)
+ (fuel : entry.fuel = I.fuel) (start : Directory.start script.catalog pt (rowInput script.plan pt m entry.phase) = 0)
+ (stop : (Directory.bound script.catalog pt (rowInput script.plan pt m entry.phase)).val = o.motifCount)
+ (memory : Directory.prepared script.catalog pt (rowInput script.plan pt m entry.phase) = I.memory)
+ (hg : arity script.catalog = L.shape.arity) (hb : (pub 2).val = L.base) (fit : H < 2^w)
+ (bank : Workspace.Installed (arity script.catalog) (pub 2) m)
+ (room : (m (pt).ordinal.val).val < directoryRows L) (placement : ∀ i, H ≤ (I.layout.base i).val) :
+ BranchSegments.Cut (OnlineWorkspace.program script.plan pub) (cap+24) (some state) m p.step.Choice := by
+ have stable := SourceBankFrame.preparation_stable script L (pub 2) hg hb fit m entry.phase room
+ have prepared := stable.installed bank (preparation script.plan pt m entry.phase).length
+ rw [List.take_length,(preparation_effect script.plan pt state m entry.phase).2] at prepared
+ have low : (pub 2).val+6 ≤ H := by
+ simp only [hb,levelStart,levelsBase,Nat.zero_mul,Nat.add_zero,directoryBase,plannerTag,frameBase]
+ omega
+ have valid := I.selectedStep_valid entry live installed fuel start stop memory
+ apply OnlineWorkspace.selectorCut script.plan pub controls tag entry live (stable.banks bank) prepared
+ (workerBanks I script pub entry installed stop (fun i => low.trans (placement i))) (I.selectedStep entry)
+ valid ?_ ?_ o.motifCount ?_ ?_
+ · intro term
+ exact (SourceBankFrame.row_stable script L (pub 2) hg hb fit m _ _ room (valid term).input (valid term).source
+ (selected_writes I L term placement)).banks bank
+ · intro s hs hp hw hfuel
+ have x := hs.input.trans (congrArg (rowInput script.plan pt m) hp)
+ have same : sourceTable script.catalog pt s.row = I.table := by
+ let installedAt (j : Fin script.size) : ProgramTable w :=
+ ⟨_,((script.catalog j).table.instantiate w
+ (Directory.words script.catalog pt j (rowInput script.plan pt m entry.phase))).program⟩
+ have eqn := (congrArg installedAt hw).trans installed
+ simpa only [sourceTable,x] using eqn
+ obtain ⟨_,term,he,_⟩ := I.validRow_unique s.row hs.source same (hfuel.trans fuel)
+ (x ▸ start) (x ▸ stop) (by simpa only [Directory.Row.dataMemory,x] using memory)
+ exact ⟨term,he⟩
+ · exact fun _ => List.length_ofFn
+ · intro i j h
+ exact I.termEquiv.injective (Subtype.ext (List.ofFn_inj.mp h))
+
+section Endpoints
+
+variable {m : Memory w} (entry : Run.RowStart script.plan (OnlineWorkspace.ports (C := script.catalog) pub) cap m)
+ (controls : Run.ControlBounds script.plan cap (w := w)) (state : Word w)
+ (tag : m (OnlineWorkspace.ports (C := script.catalog) pub).tag.val = LiveStageLink.tagWord w (calendarIndex script.size script.size))
+ (live : m (OnlineWorkspace.ports (C := script.catalog) pub).ordinal.val < m (OnlineWorkspace.ports (C := script.catalog) pub).rows.val) (installed : RowStartTable entry = I.table)
+ (fuel : entry.fuel = I.fuel) (start : Directory.start script.catalog (OnlineWorkspace.ports (C := script.catalog) pub) (rowInput script.plan (OnlineWorkspace.ports (C := script.catalog) pub) m entry.phase) = 0)
+ (stop : (Directory.bound script.catalog (OnlineWorkspace.ports (C := script.catalog) pub) (rowInput script.plan (OnlineWorkspace.ports (C := script.catalog) pub) m entry.phase)).val = o.motifCount)
+ (memory : Directory.prepared script.catalog (OnlineWorkspace.ports (C := script.catalog) pub) (rowInput script.plan (OnlineWorkspace.ports (C := script.catalog) pub) m entry.phase) = I.memory)
+ (hg : arity script.catalog = L.shape.arity) (hb : (pub 2).val = L.base) (fit : levelStart L 0 < 2^w)
+ (bank : Workspace.Installed (arity script.catalog) (pub 2) m)
+ (room : (m (OnlineWorkspace.ports (C := script.catalog) pub).ordinal.val).val < directoryRows L) (placement : ∀ i, levelStart L 0 ≤ (I.layout.base i).val)
+local notation "cut" => I.workspaceSelectorCut script L pub entry controls state tag live installed fuel
+ start stop memory hg hb fit bank room placement
+local notation "row" => I.selectedStep entry
+
+@[simp] theorem WorkerInput.workspaceSelectorCut_bits (i : p.step.Choice) :
+ ((cut).part i).bits = rowChoices ((row) i).row := rfl
+
+@[simp] theorem WorkerInput.workspaceSelectorCut_state (i : p.step.Choice) :
+ ((cut).part i).state = some 0 :=
+ ((OnlineWorkspace.framed_effect (pub 2) m (rowLog script.plan pt m entry.phase ((row) i).row) (some state)).1).trans
+ (row_effect script.plan pt m entry.phase ((row) i).row rfl
+ (I.selectedStep_valid entry live installed fuel start stop memory i).source state).2
+
+@[simp] theorem WorkerInput.workspaceSelectorCut_memory (i : p.step.Choice) :
+ ((cut).part i).memory = post script.catalog script.size pt ((row) i).row :=
+ ((OnlineWorkspace.framed_effect (pub 2) m (rowLog script.plan pt m entry.phase ((row) i).row) (some state)).2.1).trans
+ (row_effect script.plan pt m entry.phase ((row) i).row rfl
+ (I.selectedStep_valid entry live installed fuel start stop memory i).source state).1
+
+/-- Every intermediate call in the selected prefix also preserves the words
+preceding the workspace, including the enclosing machine's stage tag. -/
+theorem WorkerInput.workspaceSelectorCut_stable (i : p.step.Choice) :
+ SourceBankFrame.Stable ((pub 2).val+6) m ((cut).part i).logs := by
+ have valid := I.selectedStep_valid entry live installed fuel start stop memory i
+ exact (SourceBankFrame.row_stable script L (pub 2) hg hb fit m _ _ room valid.input valid.source
+ (selected_writes I L i placement)).framed _
+
+/-- The term index, repetition count, and supply coordinates written by the
+selected motif remain readable after the worker returns to the calendar. -/
+theorem WorkerInput.workspaceSelectorCut_fields (i : p.step.Choice) (j : Fin o.motifCount) :
+ TermRecordScan.Fields (grid o).block (grid o).supplyOrder.entries (grid o).pPos
+ ((batch o i).demand j) ((batch o i).choice j).val (I.layout.base j) ((cut).part i).memory := by
+ rw [I.workspaceSelectorCut_memory]
+ have agree := OnlineFootprint.post script L (pub 2) hg hb fit ((row) i).row
+ have fields : TermRecordScan.Fields (grid o).block (grid o).supplyOrder.entries (grid o).pPos
+ ((batch o i).demand j) ((batch o i).choice j).val (I.layout.base j)
+ (((row) i).row.endMemory script.catalog pt) := by
+ change TermRecordScan.Fields _ _ _ _ _ _
+ (after (Directory.prepared script.catalog pt (rowInput script.plan pt m entry.phase))
+ (eventLog (I.selected_run i).choose))
+ rw [memory]
+ exact (I.selected_run i).choose_spec.2.1 j
+ have atWord (off : ℕ) := agree ((I.layout.base j).val+off)
+ ((placement j).trans (Nat.le_add_right _ _))
+ refine ⟨?_,?_,fun l => ?_⟩
+ · rw [← agree _ (placement j)]; exact fields.1
+ · rw [← atWord 1]; exact fields.2.1
+ · rw [Nat.add_assoc,← atWord (2+l.val),← Nat.add_assoc]
+ exact fields.2.2 l
+
+end Endpoints
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalBootstrapReplay.lean b/lean/OAI/Computability/VPVNP/PairTerminalBootstrapReplay.lean
new file mode 100644
index 0000000000..862f69f4ee
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalBootstrapReplay.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.PairTerminalQuietFrame
+
+/-!
+# Packed addresses in the first two terminal phases
+
+The 21 bootstrap stores, width column, prefix table and linked control cells
+all lie at or above the workspace base. This supplies the protected-address
+frame of those stages even on a terminal run with a rejecting suffix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM Compression CompressorRecords DescriptorSpace TerminalPrefix TerminalPrefix.Linked
+open scoped Fin.CommRing
+
+variable {w a g : ℕ} {workers : Stage → LiveProgram.PairTable} {pub : Fin 11 → Word w}
+
+/-- Discharge all source and linker address conditions for the first two
+stages from the actual packed layout and bootstrap data. -/
+theorem QuietPrefix.replayFrame_packedStart
+ (L : Layout) (last : Fin L.levels) (tab : Fin L.shape.tables)
+ (hdr : TerminalBootstrap.Header L last) (limit r cap : ℕ)
+ (X : State a g) (input : Memory w) (rs : List (Report w))
+ (ready : TerminalBootstrap.Ready L last hdr pub input)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ L.base + 2 ^ r * 2 ^ r)
+ (room : L.base + 2 ^ r * 2 ^ r ≤ 2 ^ w)
+ (above : endAddress L ≤ TerminalBootstrap.address L.base r)
+ (slots : arcCount X ≤ slotCapacity L)
+ (q : QuietPrefix workers pub cap input)
+ (start : Start workers pub cap (TerminalBootstrap.cost L.shape limit + 1) X
+ (packedIncidence L w last (arcCount X)) (tableBase L last tab) input
+ (TerminalBootstrap.report L.shape limit pub 0 input) rs)
+ (clock₀ : TerminalBootstrap.cost L.shape limit + 1 + 30 ≤ cap) (clock₁ : 60 ≤ cap)
+ (x : ℕ) (hx : x < L.base)
+ (third : ReplayFrame x q.prefixRows.val.memory
+ (reports (header pub) q.traversalRows.val.logs)) : ReplayFrame x input q.reportList := by
+ let H := TerminalBootstrap.address L.base r
+ have hhead : (header pub).val = H :=
+ header_val L pub r ready.workspace exp hr reserve room
+ have fits : H + 32 ≤ 2 ^ w := by unfold H TerminalBootstrap.address; omega
+ have xbase : L.base ≤ endAddress L := by
+ simp only [endAddress,levelStart,levelsBase,directoryBase,plannerTag,frameBase]
+ omega
+ have low : x < H := hx.trans_le (xbase.trans above)
+ have saved : (header pub + 31).val = H + 31 := by
+ rw [Fin.val_add,hhead,show (31 : Word w).val = 31 % (2 ^ w) from rfl,
+ Nat.mod_eq_of_lt (by omega : 31 < 2 ^ w),Nat.mod_eq_of_lt (by omega)]
+ have away : workerCell (header pub) x := ⟨hhead ▸ low.ne,by omega⟩
+ have outside := (TerminalBootstrap.native L last hdr limit pub input 0 ready r exp hr
+ reserve room).2.2.2.1
+ apply q.replayFrame_of_start start clock₀ clock₁ x away (outside x (.inl low)) _ third
+ have fit : endAddress L < 2 ^ w := above.trans_lt (by omega)
+ have widthEnd := packed_incidence_room L fit last slots
+ have startsEnd := (tableEnd_le_nextLevel L last tab).trans (levelStart_mono L last.isLt)
+ have widthFit : incidenceBase L last (arcCount X) 5 < 2 ^ w := by
+ change incidenceStart L last + 5 * arcCount X < 2 ^ w
+ omega
+ change tableBase L last tab + tableWords L ≤ endAddress L at startsEnd
+ have startsFit : tableBase L last tab < 2 ^ w := by omega
+ have widths : (packedIncidence L w last (arcCount X)).width.val =
+ incidenceBase L last (arcCount X) 5 := Nat.mod_eq_of_lt widthFit
+ have starts : (tableBase L last tab : Word w).val = tableBase L last tab :=
+ Nat.mod_eq_of_lt startsFit
+ unfold Segment.probeRegion
+ rw [show (Worker.header pub).val = H from hhead,widths,starts]
+ simp only [tableBase,arrayBase,incidenceBase,incidenceStart,levelStart,
+ levelsBase,directoryBase,plannerTag,frameBase]
+ omega
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalCalendarBoundary.lean b/lean/OAI/Computability/VPVNP/PairTerminalCalendarBoundary.lean
new file mode 100644
index 0000000000..cc0e8871ee
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalCalendarBoundary.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.PairTerminalSelectedReady
+import OAI.Computability.VPVNP.CompressorCurrentResident
+
+/-!
+# The terminal bootstrap and prefix from the completed calendar boundary
+
+The selected graph, placement history, saved cursor parameters and online
+row count all belong to the same final boundary. The four initial visits
+establish this invariant for zero compression blocks. Each executed substep
+extends it with the new graph and its placement directory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalPrefix.Linked
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TerminalBootstrap TerminalLink ScheduledTrace
+open scoped Fin.CommRing
+
+variable {w : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ}
+variable (T : ℕ) (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+variable (positions baseBits laneBits width inputN : ℕ) (pub : Fin 11 → Word w)
+set_option quotPrecheck false in
+local notation "L" => BlockProgram.layout B (pub 2).val positions T
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "saved" => CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L))
+ (CursorRAM.encode w 1) baseBits laneBits (S.degreeExponent 0) width (incidenceStart L 0)
+set_option quotPrecheck false in
+local notation "resident" => CurrentResident.resident B f hf ⟨leafLayer (siteOrder X), .cursor⟩
+ L (endAddress L) inputN saved
+set_option quotPrecheck false in
+local notation "tab" => (⟨0, by change 0 < 6; decide⟩ : Fin (L).shape.tables)
+set_option quotPrecheck false in
+local notation "Aₜ" => fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab
+
+private theorem slot_count {a l : ℕ} (state : State a l) :
+ IncidenceDirectory.slotCount state = arcCount state := by
+ rw [Segment.arc_count_positions]
+ change Fintype.card state.Base * 2 ^ l * 2 ^ a = Fintype.card (state.Base × BitWord l) * 2 ^ a
+ rw [Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv l), Fintype.card_fin]
+
+/-- The actual online path's transfer writes the terminal tag below the
+workspace. Its final memory agrees at every address required by the terminal stage. -/
+theorem handoff_of_transfer {m phy : Memory w} {addr value : Word w}
+ (post : phy = writeMemory m addr value) (tag : addr.val < (pub 2).val + 6) :
+ SourceTransport.Agree ((pub 2).val + 6 ≤ ·) m phy := by
+ intro x hx
+ rw [post, writeMemory, ite_eq_right (by omega : x ≠ addr.val)]
+
+/-- Read the exact initial and final header operands at the physical terminal
+handoff. The suffix agreement allows an outer controller store below the
+online workspace control fields. -/
+theorem boundary_inputs (m phy : Memory w)
+ (boundary : Boundary resident pub (levelWords L : Word w) (directoryRows L)
+ (directoryRows L) (vs) (Y) m)
+ (handoff : SourceTransport.Agree ((pub 2).val + 6 ≤ ·) m phy)
+ (fit : endAddress L < 2 ^ w) (slots : arcCount (Y) ≤ slotCapacity L) :
+ Nonempty (SelectedDirectoryHistory.Retained B f hf T hT X z L (endAddress L) phy) ∧
+ Ready L (ls).dropLast.length (Aₜ) pub phy ∧
+ (packedIncidence L w (ls).dropLast.length (arcCount (Y))).ActualColumns (Y) phy := by
+ have size : (L).levels = T * (S.steps + 1) + 1 := by
+ rw [BlockProgram.actual_level_count, Nat.mul_comm, Nat.add_comm]
+ have wide : 30 ≤ (L).shape.scalarFields := by change 30 ≤ 54; decide
+ have idx := selected_last_index B f hf T hT X z
+ have nlast := selected_prior_length B f hf T hT X z
+ have base : (L).base = (pub 2).val := rfl
+ have first : (L).base + 11 + (L).shape.arity ≤ levelStart L 0 := by
+ simp only [levelStart, levelsBase, directoryBase, plannerTag, frameBase]
+ omega
+ have firstFit := (levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit
+ have agree : SourceTransport.Agree (levelStart L 0 ≤ ·) m phy :=
+ fun x hx => handoff x (by omega)
+ have arcs := slot_count (Y)
+ have state := CurrentResident.transfer boundary.stored (by omega) fit (by omega)
+ (arcs.le.trans slots) agree
+ obtain ⟨⟨⟨history⟩, _⟩, cur, frame⟩ := state
+ have hval (i : ℕ) (hi : i ≤ 11 + (L).shape.arity) :
+ (pub 2 + (i : Word w)).val = (pub 2).val + i := by
+ have small : (pub 2).val + i < 2 ^ w := by omega
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : i < 2 ^ w),
+ Nat.mod_eq_of_lt small]
+ have rows : phy (pub 2 + 8).val = (directoryRows L : Word w) := by
+ have val := boundary.totalValue
+ change (m (pub 2 + 8).val).val = directoryRows L at val
+ have haddr : (pub 2 + 8).val = (pub 2).val + 8 := hval 8 (by omega)
+ apply Fin.ext
+ rw [← handoff _ (by rw [haddr]; omega), Fin.val_natCast, ← val,
+ Nat.mod_eq_of_lt (m _).isLt]
+ have pitch : phy (pub 2 + ((10 + (L).shape.arity : ℕ) : Word w)).val =
+ (levelWords L : Word w) := by
+ have word : (Workspace.ports (Schedule.arity (BlockProgram.script B).catalog) (pub 2)).directory
+ - 1 = pub 2 + ((10 + (L).shape.arity : ℕ) : Word w) := by
+ change pub 2 + ((11 + (L).shape.arity : ℕ) : Word w) - 1 = _
+ rw [show 11 + (L).shape.arity = (10 + (L).shape.arity) + 1 by omega, Nat.cast_add]
+ rw [Nat.cast_one, ← add_assoc, add_sub_cancel_right]
+ exact (handoff _ (by rw [hval _ (by omega)]; omega)).symm.trans (word ▸ boundary.stride)
+ have count : phy (levelStart L 0 + 28) = ((L).levels : Word w) := by
+ apply Fin.ext
+ rw [Fin.val_natCast, ← cur.startup.levels, Nat.mod_eq_of_lt (phy _).isLt]
+ have headCount : IncidenceDirectory.slotCount (Y) = (Y).positions * 2 ^ (S.degreeExponent 0) :=
+ arcs.trans (Segment.arc_count_positions (Y))
+ refine ⟨⟨history⟩, selected_ready B f hf T hT X z L baseBits laneBits tab rfl pub phy phy
+ base.symm rows pitch size wide fit (fun _ _ => rfl) count history ?_ ?_ ?_
+ (CursorRAM.encode w (directoryBase L)) (CursorRAM.encode w 1) (S.degreeExponent 0) width
+ (incidenceStart L 0) frame, ?_⟩
+ · rw [idx]
+ exact cur.terminal
+ · intro c
+ rw [idx, ← headCount]
+ exact cur.heads.incidence c
+ · rw [idx]
+ exact cur.heads.tables tab
+ · rw [idx, ← arcs]
+ exact cur.incidence.actual
+
+/-- Run the first two actual terminal workers from the selected final
+boundary. No separate assumptions on the row pointers, retained cursor
+frame, packed graph or header publications are needed. -/
+theorem run_boundary (segments : VertexImage.Part → VertexImage.Segment) (r cap : ℕ)
+ (m phy : Memory w)
+ (boundary : Boundary resident pub (levelWords L : Word w) (directoryRows L)
+ (directoryRows L) (vs) (Y) m)
+ (handoff : SourceTransport.Agree ((pub 2).val + 6 ≤ ·) m phy)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ (L).base + 2 ^ r * 2 ^ r)
+ (room : (L).base + 2 ^ r * 2 ^ r ≤ 2 ^ w)
+ (above : endAddress L ≤ TerminalBootstrap.address (L).base r)
+ (slots : arcCount (Y) ≤ slotCapacity L) (cells : arcCount (Y) ≤ tableWords L)
+ (totalFit : (Y).totalWidth < 2 ^ w)
+ (clock₀ : TerminalBootstrap.cost (L).shape B.recordLimit + 1 + 30 ≤ cap) (clock₁ : 60 ≤ cap) :
+ let last := (ls).dropLast.length
+ let rawBoot := TerminalBootstrap.report (L).shape B.recordLimit pub 0 phy
+ let D := packedIncidence L w last (arcCount (Y))
+ let workers := TerminalProgram.workers (L).shape B.recordLimit segments
+ Nonempty (SelectedDirectoryHistory.Retained B f hf T hT X z L (endAddress L) phy) ∧
+ Ready L last (Aₜ) pub phy ∧
+ ∃ rs, Start workers pub cap (TerminalBootstrap.cost (L).shape B.recordLimit + 1) (Y) D
+ (tableBase L last tab) phy rawBoot rs ∧
+ prefixMemory pub phy rawBoot rs (header pub + 14).val =
+ ((words B.recordLimit (ls) + (Y).totalWidth : ℕ) : Word w) := by
+ have fit : endAddress L < 2 ^ w := by unfold TerminalBootstrap.address at above; omega
+ obtain ⟨history, ready, inc⟩ := boundary_inputs B f hf T hT X z positions baseBits laneBits
+ width inputN pub m phy boundary handoff fit slots
+ have size : (L).levels = T * (S.steps + 1) + 1 := by
+ rw [BlockProgram.actual_level_count, Nat.mul_comm, Nat.add_comm]
+ exact ⟨history, ready, run_selected B f hf T hT X z L baseBits laneBits tab segments r cap pub
+ phy phy size ready exp hr reserve room above slots cells totalFit (fun _ _ => rfl) inc
+ clock₀ clock₁⟩
+
+end PairSimulation.TerminalPrefix.Linked
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalFootprint.lean b/lean/OAI/Computability/VPVNP/PairTerminalFootprint.lean
new file mode 100644
index 0000000000..6bcedac9a7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalFootprint.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PairVertexActiveGeometry
+import OAI.Computability.VPVNP.PairSimulationTerminalSplice
+
+/-! # Source reads outside the two online terminal-controller cells -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalFootprint
+
+open BurstRAM PrivateRAM CompressorRecords.SourceTransport TerminalLink
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+theorem header_val (H : Word w) (fit : H.val+31 < 2^w) {j : ℕ} (hj : j ≤ 31) :
+ (H+(j : Word w)).val = H.val+j := by
+ rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j < 2^w),Nat.mod_eq_of_lt (by omega)]
+
+theorem below (H : Word w) (fit : H.val+31 < 2^w) {i : ℕ} (before : i < H.val) : workerCell H i := by
+ change i ≠ H.val ∧ i ≠ (H+(31 : Word w)).val
+ rw [show (H+(31 : Word w)).val = H.val+31 from header_val H fit (j := 31) le_rfl]; omega
+
+theorem headerField (H : Word w) (fit : H.val+31 < 2^w) {j : ℕ} (lo : 0 < j) (hi : j < 31) :
+ workerCell H (H+(j : Word w)).val := by
+ unfold workerCell
+ rw [header_val H fit hi.le,show (H+(31 : Word w)).val = H.val+31 from header_val H fit (j := 31) le_rfl]
+ omega
+
+theorem reads_append {allow : ℕ → Prop} {es fs : List (Event w)} (left : Reads allow es) (right : Reads allow fs) :
+ Reads allow (es++fs) := fun a v h => (List.mem_append.mp h).elim (left a v) (right a v)
+
+theorem reads_ticks (allow : ℕ → Prop) (n : ℕ) : Reads allow (List.replicate n (.tick : Event w)) := by
+ intro a v h
+ have eq : (.read a v : Event w) = .tick := List.eq_of_mem_replicate h
+ cases eq
+
+theorem reads_mono {allow allow' : ℕ → Prop} {es : List (Event w)}
+ (reads : Reads allow es) (h : ∀ i, allow i → allow' i) : Reads allow' es :=
+ fun a v read => h a.val (reads a v read)
+
+private theorem field (H : Word w) (fit : H.val+31 < 2^w) (m : Memory w) {j : ℕ}
+ (lo : 0 < j) (hi : j < 31) : Reads (workerCell H) (TerminalSiteStart.fieldTrace m H j) := by
+ intro a v h
+ simp only [TerminalSiteStart.fieldTrace,List.mem_cons,List.not_mem_nil,reduceCtorEq,false_or,or_false,
+ Event.read.injEq] at h
+ exact h.1 ▸ headerField H fit lo hi
+
+end PairSimulation.TerminalFootprint
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM CompressorRecords.SourceTransport TerminalFootprint TerminalLink TerminalSiteStart
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- All fifteen reads of the active ordinal guard and the geometry initializer
+avoid the phase word and the worker-state word. -/
+theorem active_geometry_reads (m : Memory w) (H : Word w) (degree t : ℕ) (fit : H.val+31 < 2^w) :
+ Reads (workerCell H) (startTrace m H ++ (NativeFrame.events degree H m ++ List.replicate (t+2) .tick)) := by
+ apply reads_append
+ · apply reads_append
+ · exact reads_append (reads_append (reads_ticks _ 10) (TerminalFootprint.field H fit m (by decide) (by decide)))
+ (reads_ticks _ 2)
+ · apply reads_append
+ · intro a v h
+ obtain ⟨j,member,read⟩ := List.mem_flatMap.mp h
+ have lo : 0 < j := by
+ simp only [List.mem_cons,List.not_mem_nil,or_false] at member
+ omega
+ have hi : j < 31 := by
+ simp only [List.mem_cons,List.not_mem_nil,or_false] at member
+ omega
+ exact TerminalFootprint.field H fit m lo hi a v read
+ · exact reads_ticks _ 5
+ · refine reads_append (es := NativeFrame.events degree H m) ?_ (reads_ticks _ (t+2))
+ refine reads_mono (NativeFrame.events_reads degree H m) ?_
+ rintro i ⟨j,rfl⟩
+ exact headerField H fit (by fin_cases j <;> decide) (by fin_cases j <;> decide)
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalGatherGeometry.lean b/lean/OAI/Computability/VPVNP/PairTerminalGatherGeometry.lean
new file mode 100644
index 0000000000..3bf17933b6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalGatherGeometry.lean
@@ -0,0 +1,313 @@
+import OAI.Computability.VPVNP.PairTerminalPrefix
+import OAI.Computability.VPVNP.PairNodeArguments
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherLayout
+
+/-!
+# Terminal site arguments from the shared final-arc array
+
+The physical source of each outgoing field is its own port. Incoming fields
+follow the actual inverse slot permutation. Both copies of a loop therefore
+use the same shared payload, at their separate positions in the root argument.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalGatherGeometry
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords LocalHistory
+open scoped Fin.CommRing
+open private actualWidth payloadBits from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+variable {a g w : ℕ} (X : State a g)
+
+/-- Ordinal of an outgoing arc in the final shared scan. -/
+abbrev number := (edgeOrder X).entries.symm
+
+/-- The same equivalence used by the final scan phase of the history. -/
+noncomputable def payload := FinalBits.payloads (TerminalPrefix.width X) X.network (number X) (payloadBits X)
+
+/-- The local half-wire assignment at a final site induced by splitting the shared bit string
+into the terminal arc payloads. -/
+noncomputable def half (f : Fin (∑ i, TerminalPrefix.width X i) → Bool) (v : X.network.Site) :=
+ WireTensor.edgeAssignment X.network.src X.network.dst (payload X f) v
+
+/-- The successful native scan of these bits decodes to this very payload
+in the chronological history trace. -/
+theorem phase_payload {p r k : ℕ} (M : Machine w p r k) (pc : Fin 10 → Fin p)
+ (reg : Fin 2 ↪ Fin r) (base : Fin k) (done : Fin p)
+ (hl : FinalBits.Linked M pc reg base done) (he : M.entry = pc 0)
+ (low : ℕ) (pub : M.publicData base = FinalBits.cursor w low 0) (m : Memory w) (extra : ℕ)
+ (fit : low + X.totalWidth < 2 ^ w) (f : Fin (∑ i, TerminalPrefix.width X i) → Bool) :
+ (stateScanPhase X M pc reg base done hl he low pub m extra fit).payload
+ (FinalBits.scanEquiv hl he low (∑ i, TerminalPrefix.width X i)
+ (by rwa [TerminalPrefix.width_sum]) pub m extra f) = payload X f := by
+ change payload X ((FinalBits.scanEquiv hl he low _ _ pub m extra).symm
+ (FinalBits.scanEquiv hl he low _ _ pub m extra f)) = _
+ rw [Equiv.symm_apply_apply]
+
+/-- Source arc underlying an endpoint slot. -/
+def arc (v : X.network.Site) (dir : Bool) (j : Fin (2 ^ a)) : X.network.Edge :=
+ if dir then X.slots.actualGraph.target.symm (v, j) else (v, j)
+
+theorem scan_width (e : X.network.Edge) :
+ TerminalPrefix.width X (number X e) = actualWidth X e :=
+ congrArg (actualWidth X) ((edgeOrder X).entries.apply_symm_apply e)
+
+theorem slot_width (v : X.network.Site) (dir : Bool) (j : Fin (2 ^ a)) :
+ TerminalPrefix.width X (number X (arc X v dir j)) = X.halfWidth v dir j := by
+ rw [scan_width]
+ cases dir <;> rfl
+
+private theorem transportedBit {s t : ℕ} (h : s = t) (z : Fin t → Bool) (i : Fin s) :
+ ((congrArg (fun n ↦ (Fin t → Bool) ≃ (Fin n → Bool)) h).mpr (Equiv.refl _)) z i =
+ z (Fin.cast h i) := by
+ cases h
+ rfl
+
+private theorem payload_bit (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (e : X.network.Edge) (i : Fin (actualWidth X e)) :
+ payload X f e i = f (FinalBits.index (TerminalPrefix.width X) (number X e)
+ (Fin.cast (scan_width X e).symm i)) := by
+ let j := Fin.cast (scan_width X e).symm i
+ have hs := FinalBits.payloads_bit (TerminalPrefix.width X) X.network (number X) (payloadBits X) f e j
+ exact (transportedBit (scan_width X e) (payload X f e) j).symm.trans hs
+
+/-- Every bit in a declared node field equals its physical shared-array bit,
+including incoming slots matched to a different source ordinal. -/
+theorem field_readback (low : ℕ) (fit : low + X.totalWidth < 2 ^ w)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool) (initial : Memory w)
+ (v : X.network.Site) (dir : Bool) (j : Fin (2 ^ a)) (i : Fin (X.halfWidth v dir j)) :
+ let e := number X (arc X v dir j)
+ after initial (eventLog (FinalBits.reports w low f))
+ (low + EndpointBits.offset (TerminalPrefix.width X) e + i.val) =
+ PrivateFields.bitValue w (NodeArguments.fieldBits X v (half X f v) dir j i) := by
+ let e := arc X v dir j
+ let k := Fin.cast (slot_width X v dir j).symm i
+ let idx := FinalBits.index (TerminalPrefix.width X) (number X e) k
+ have loc : low + EndpointBits.offset (TerminalPrefix.width X) (number X e) + i.val =
+ low + idx.val := by rw [FinalBits.index_val, Nat.add_assoc]; rfl
+ dsimp only
+ change after initial _ (low + EndpointBits.offset _ (number X e) + i.val) = _
+ rw [loc, FinalBits.readback low (by rwa [TerminalPrefix.width_sum])]
+ congr 1
+ cases dir with
+ | false => exact (payload_bit X f (v,j) i).symm
+ | true => exact (payload_bit X f (X.slots.actualGraph.target.symm (v,j)) i).symm
+
+open TerminalRootGather
+
+variable (L : Layout)
+
+/-- Physical numbering of the current vertex and the whole terminal graph. -/
+structure Numbering (v : X.network.Site) : Prop where
+ vertex : L.vertex = ((siteOrder X).entries.symm v).val
+ sites : L.sites = (siteOrder X).length
+ slots : L.slots = TerminalPrefix.arcCount X
+
+theorem Numbering.degree {v : X.network.Site} (h : Numbering X L v) : L.degree = 2 ^ a := by
+ have pos := ((siteOrder X).entries.symm v).isLt
+ rw [Layout.degree, h.sites, h.slots]
+ change (siteOrder X).length * 2 ^ a / (siteOrder X).length = _
+ exact Nat.mul_div_cancel_left _ (by omega)
+
+theorem Numbering.index {v : X.network.Site} (h : Numbering X L v) (j : Fin (2 ^ a)) :
+ L.index j.val = (number X (v,j)).val := by
+ rw [Layout.index, h.vertex, h.degree]
+ change _ = j.val + 2 ^ a * ((siteOrder X).entries.symm v).val
+ ring
+
+/-- The gather accesses only these three directory columns. -/
+structure Rows (mem : Memory w) : Prop where
+ inverse : ∀ e : X.network.Edge, (mem (L.incomingHead + (number X e).val)).val =
+ (number X (X.slots.actualGraph.target.symm e)).val
+ widths : ∀ i : Fin (TerminalPrefix.arcCount X),
+ (mem (L.widthHead + i.val)).val = TerminalPrefix.width X i
+ starts : ∀ i : Fin (TerminalPrefix.arcCount X),
+ (mem (L.prefixHead + i.val)).val = EndpointBits.offset (TerminalPrefix.width X) i
+
+/-- The physical heads and the separation of the inverse column from the
+two destinations of the prefix worker. -/
+structure PrefixLayout (T : IncidenceDirectory w) (base total : Word w) : Prop where
+ incoming : L.incomingHead = T.actualIn.val
+ widths : L.widthHead = T.width.val
+ starts : L.prefixHead = base.val
+ inverseFit : L.incomingHead + TerminalPrefix.arcCount X ≤ 2 ^ w
+ totalApart : total.val < L.incomingHead ∨ L.incomingHead + TerminalPrefix.arcCount X ≤ total.val
+ startsApart : L.incomingHead + TerminalPrefix.arcCount X ≤ base.val ∨
+ base.val + TerminalPrefix.arcCount X ≤ L.incomingHead
+
+theorem rows_of_prefix {T : IncidenceDirectory w} {base total : Word w} {initial final : Memory w}
+ (hl : PrefixLayout X L T base total) (hc : T.ActualColumns X initial)
+ (hs : TerminalPrefix.Stored X T base total initial final) : Rows X L final := by
+ refine ⟨fun e ↦ ?_, fun i ↦ hl.widths ▸ hs.widths i, fun i ↦ hl.starts ▸ hs.start i⟩
+ have hi := (number X e).isLt
+ change (number X e).val < TerminalPrefix.arcCount X at hi
+ have hFit := hl.inverseFit
+ have hTotal := hl.totalApart
+ have hStarts := hl.startsApart
+ rw [hs.outside _ (by omega) (by omega)]
+ have hcol := congrArg Fin.val (hc.actualIn e)
+ have ht := (number X (X.slots.actualGraph.target.symm e)).isLt
+ change (number X (X.slots.actualGraph.target.symm e)).val < TerminalPrefix.arcCount X at ht
+ rw [TerminalPrefix.actualPort_eq X e, TerminalPrefix.actualPort_eq X (X.slots.actualGraph.target.symm e)] at hcol
+ simp only [Fin.val_add, Fin.val_natCast] at hcol
+ rw [← hl.incoming, Nat.mod_eq_of_lt (by omega : (number X e).val < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega : L.incomingHead + (number X e).val < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega : (number X (X.slots.actualGraph.target.symm e)).val < 2 ^ w)] at hcol
+ exact hcol
+
+/-- Arbitrary intervening work can transfer these facts by preserving the
+three arrays at their live ordinals. -/
+theorem Rows.transfer {before after : Memory w} (h : Rows X L before)
+ (keep : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead],
+ ∀ i : Fin (TerminalPrefix.arcCount X), after (head + i.val) = before (head + i.val)) :
+ Rows X L after := by
+ refine ⟨fun e ↦ ?_, fun i ↦ ?_, fun i ↦ ?_⟩
+ · rw [keep _ (by simp), h.inverse]
+ · rw [keep _ (by simp), h.widths]
+ · rw [keep _ (by simp), h.starts]
+
+theorem Rows.after_reports {before : Memory w} (h : Rows X L before)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool) (fit : L.wires + X.totalWidth < 2 ^ w)
+ (apart : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead],
+ head + TerminalPrefix.arcCount X ≤ L.wires ∨ L.wires + X.totalWidth ≤ head) :
+ Rows X L (after before (eventLog (FinalBits.reports w L.wires f))) := by
+ apply h.transfer
+ intro head hh i
+ apply FinalBits.outside _ (by rwa [TerminalPrefix.width_sum])
+ have hsep := apart head hh
+ have hi := i.isLt
+ rw [TerminalPrefix.width_sum]
+ omega
+
+variable {X L} {v : X.network.Site} {mem : Memory w}
+
+theorem edge_eq (num : Numbering X L v) (rows : Rows X L mem) (dir : Bool) (j : Fin (2 ^ a)) :
+ L.edge mem dir j.val = (number X (arc X v dir j)).val := by
+ rw [Layout.edge, num.index]
+ cases dir with
+ | false => rfl
+ | true => exact rows.inverse _
+
+theorem width_eq (num : Numbering X L v) (rows : Rows X L mem) (dir : Bool) (j : Fin (2 ^ a)) :
+ L.width mem dir j.val = X.halfWidth v dir j := by
+ rw [Layout.width, edge_eq num rows, rows.widths, slot_width]
+
+theorem start_eq (num : Numbering X L v) (rows : Rows X L mem) (dir : Bool) (j : Fin (2 ^ a)) :
+ L.start mem dir j.val = L.wires +
+ EndpointBits.offset (TerminalPrefix.width X) (number X (arc X v dir j)) := by
+ rw [Layout.start, edge_eq num rows, rows.starts]
+
+/-- All words that the native gather reads, in the root's descriptor order. -/
+theorem packet_eq (num : Numbering X L v) (rows : Rows X L mem)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (bits : ∀ i, mem (L.wires+i.val) = PrivateFields.bitValue w (f i)) :
+ L.packet mem = (NodeArguments.packed X v (half X f v)).map (PrivateFields.bitValue w) := by
+ have one (dir : Bool) (j : Fin (2 ^ a)) : L.field mem dir j.val =
+ List.ofFn (fun i ↦ PrivateFields.bitValue w (NodeArguments.fieldBits X v (half X f v) dir j i)) := by
+ apply List.ext_getElem (by rw [Layout.field_length, width_eq num rows, List.length_ofFn])
+ intro k hk hk'
+ have hwidth : k < X.halfWidth v dir j := by simpa only [List.length_ofFn] using hk'
+ simp only [Layout.field, List.getElem_ofFn, start_eq num rows]
+ let j' := Fin.cast (slot_width X v dir j).symm ⟨k,hwidth⟩
+ let idx := FinalBits.index (TerminalPrefix.width X) (number X (arc X v dir j)) j'
+ have hi : L.wires + EndpointBits.offset (TerminalPrefix.width X) (number X (arc X v dir j)) + k =
+ L.wires + idx.val := by rw [FinalBits.index_val, Nat.add_assoc]; rfl
+ rw [hi,bits]
+ congr 1
+ cases dir with
+ | false => exact (payload_bit X f (v,j) ⟨k,hwidth⟩).symm
+ | true => exact (payload_bit X f (X.slots.actualGraph.target.symm (v,j)) ⟨k,hwidth⟩).symm
+ have side (dir : Bool) : L.fields mem dir =
+ (NodeArguments.fields X v (half X f v) dir).map (List.map (PrivateFields.bitValue w)) := by
+ simp only [Layout.fields, NodeArguments.fields, List.map_ofFn]
+ apply List.ext_getElem (by simp only [List.length_ofFn]; exact num.degree)
+ intro j _ hj
+ have hj' : j < 2 ^ a := by simpa only [List.length_ofFn] using hj
+ simp only [List.getElem_ofFn, Function.comp_apply, List.map_ofFn]
+ exact one dir ⟨j,hj'⟩
+ simp only [Layout.packet, NodeArguments.packed, List.map_append, List.map_flatten, side]
+
+theorem packet_after_reports (num : Numbering X L v) {initial : Memory w}
+ (rows : Rows X L initial) (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (fit : L.wires + X.totalWidth < 2 ^ w)
+ (apart : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead],
+ head + TerminalPrefix.arcCount X ≤ L.wires ∨ L.wires + X.totalWidth ≤ head) :
+ L.packet (after initial (eventLog (FinalBits.reports w L.wires f))) =
+ (NodeArguments.packed X v (half X f v)).map (PrivateFields.bitValue w) :=
+ packet_eq num (rows.after_reports X L f fit apart) f
+ (FinalBits.readback L.wires (by rwa [TerminalPrefix.width_sum]) f initial)
+
+/-- The loop bounds and the exclusive source and destination cursors fit
+from whole-array bounds and the size of the typed private argument. -/
+theorem fits (num : Numbering X L v) (rows : Rows X L mem)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (bits : ∀ i, mem (L.wires+i.val) = PrivateFields.bitValue w (f i))
+ (countFit : TerminalPrefix.arcCount X < 2 ^ w)
+ (headFit : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead],
+ head + TerminalPrefix.arcCount X ≤ 2 ^ w)
+ (sharedFit : L.wires + X.totalWidth < 2 ^ w)
+ (privateFit : L.dest + (∑ dir : Bool, ∑ j, X.halfWidth v dir j) < 2 ^ w) :
+ L.Fits mem := by
+ have count : TerminalPrefix.arcCount X = (siteOrder X).length * 2 ^ a := rfl
+ have hpos : 0 < 2 ^ a := pow_pos (by decide) _
+ have hsite := ((siteOrder X).entries.symm v).isLt
+ have addresses (d : Bool) (j : Fin (2 ^ a)) :
+ L.edge mem d j.val < TerminalPrefix.arcCount X := by
+ rw [edge_eq num rows]
+ exact (number X _).isLt
+ refine ⟨?_, num.slots.trans_lt countFit, ?_, ?_, ?_, ?_, ?_, ?_⟩
+ · rw [num.sites]
+ rw [count] at countFit
+ exact (Nat.le_mul_of_pos_right _ hpos).trans_lt countFit
+ · rw [Layout.index,num.vertex,num.degree, ← Nat.succ_mul]
+ exact (Nat.mul_le_mul_right _ hsite).trans_lt (count ▸ countFit)
+ · intro j hj
+ rw [num.degree] at hj
+ rw [num.index X L ⟨j,hj⟩]
+ exact (Nat.add_lt_add_left (number X (v,⟨j,hj⟩)).isLt _).trans_le (headFit _ (by simp))
+ · intro d j hj
+ rw [num.degree] at hj
+ exact (Nat.add_lt_add_left (addresses d ⟨j,hj⟩) _).trans_le (headFit _ (by simp))
+ · intro d j hj
+ rw [num.degree] at hj
+ exact (Nat.add_lt_add_left (addresses d ⟨j,hj⟩) _).trans_le (headFit _ (by simp))
+ · intro d j hj
+ rw [num.degree] at hj
+ let k : Fin (2 ^ a) := ⟨j,hj⟩
+ rw [start_eq num rows d k, width_eq num rows d k, ← slot_width, Nat.add_assoc]
+ have bound := EndpointBits.arc_fits (TerminalPrefix.width X) (number X (arc X v d k))
+ rw [TerminalPrefix.width_sum] at bound
+ exact (Nat.add_le_add_left bound _).trans_lt sharedFit
+ · rwa [packet_eq num rows f bits, List.length_map, NodeArguments.packed_length]
+
+/-- The gather's actual private writes are the semantic descriptor store,
+including preservation of all words outside the root's private interval. -/
+theorem placed_packet (num : Numbering X L v) (rows : Rows X L mem)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (bits : ∀ i, mem (L.wires+i.val) = PrivateFields.bitValue w (f i))
+ (fit : L.Fits mem) (old : Word w → Word w) :
+ Layout.placed L.dest (L.packet mem) old =
+ PrivateFields.storeBits L.dest (NodeArguments.packed X v (half X f v)) old := by
+ let bs := NodeArguments.packed X v (half X f v)
+ have hlen : (L.packet mem).length = bs.length := by rw [packet_eq num rows f bits, List.length_map]
+ have room : L.dest + bs.length ≤ 2 ^ w := hlen ▸ fit.destEnd.le
+ funext x
+ by_cases hx : L.dest ≤ x.val ∧ x.val < L.dest + bs.length
+ · let i : Fin bs.length := ⟨x.val-L.dest, by omega⟩
+ have hv : L.dest + i.val = x.val := by dsimp [i]; omega
+ have hw : Fin.ofNat (2 ^ w) (L.dest+i.val) = x := by rw [hv]; exact Fin.ofNat_val_eq_self x
+ rw [← hw, Layout.placed_inside _ old ⟨i.val, i.isLt.trans_eq hlen.symm⟩ fit.destEnd.le]
+ refine Eq.trans ?_ (PrivateFields.storeBits_read _ bs old room i).symm
+ simp only [packet_eq num rows f bits,List.getElem_map]
+ rfl
+ · rw [Layout.placed_outside _ _ _ _ (by omega)]
+ exact (PrivateFields.storeBits_outside L.dest bs old x room (by omega)).symm
+
+end PairSimulation.TerminalGatherGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalGatherNative.lean b/lean/OAI/Computability/VPVNP/PairTerminalGatherNative.lean
new file mode 100644
index 0000000000..9c2a15595d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalGatherNative.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.PairTerminalGatherGeometry
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGather
+
+/-!
+# Native terminal gathers in the selected wire geometry
+
+Each vertex reads the final shared bits into its actual root argument before
+DFS. The same bit is read at both endpoints. The directory lookups add five
+probes per outgoing slot when summed over the whole graph.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalGatherNative
+
+open BurstRAM BurstRAM.PrivateRAM Compression LocalHistory TerminalRootGather TerminalGatherGeometry
+open scoped Fin.CommRing
+
+variable {a g w p r : ℕ}
+
+/-- Number of bits in a final site's argument packet, summed over all outgoing and incoming
+slots. -/
+def argumentSize (X : State a g) (v : X.network.Site) := ∑ d : Bool, ∑ j, X.halfWidth v d j
+
+variable {M : Machine w p r 11} {pc : PC → Fin p} {reg : Reg ↪ Fin r} {done : Fin p}
+variable {L : Layout} {X : State a g} {v : X.network.Site}
+
+/-- The actual linked table fills the root store and passes control and the
+unconsumed branch stream to its continuation. -/
+theorem run (hl : Linked M pc reg done) (mem : Memory w) (num : Numbering X L v)
+ (rows : Rows X L mem) (fit : L.Fits mem) (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (bits : ∀ i, mem (L.wires+i.val) = PrivateFields.bitValue w (f i))
+ (c : Config w p r) (hc : c.pc = pc (.boot 0)) (saved : Saved L reg c)
+ (hn : M.publicData 6 = (L.n : Word w))
+ (stride : c.privateMem (c.privateMem (L.n : Word w)+7) = (L.stride : Word w)) :
+ ∃ out es, out.pc = done ∧ Frame reg c out ∧
+ out.privateMem = PrivateFields.storeBits L.dest (NodeArguments.packed X v (half X f v)) c.privateMem ∧
+ Cost es (15+21*2^a+5*argumentSize X v) (5*2^a+argumentSize X v) ∧ Prefix M mem c es out := by
+ obtain ⟨out,es,ret,frame,priv,cost,exec⟩ := TerminalRootGather.run hl L mem fit c hc saved hn stride
+ refine ⟨out,es,ret,frame,priv.trans (placed_packet num rows f bits fit _),?_,exec⟩
+ simpa only [num.degree, packet_eq num rows f bits, List.length_map,
+ NodeArguments.packed_length, argumentSize] using cost
+
+/-- Run the gather in the memory actually written by the shared bit scan. -/
+theorem run_after_reports (hl : Linked M pc reg done) (initial : Memory w) (num : Numbering X L v)
+ (rows : Rows X L initial) (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (countFit : TerminalPrefix.arcCount X < 2 ^ w)
+ (headsFit : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead],
+ head + TerminalPrefix.arcCount X ≤ 2 ^ w)
+ (apart : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead],
+ head + TerminalPrefix.arcCount X ≤ L.wires ∨ L.wires + X.totalWidth ≤ head)
+ (sharedFit : L.wires + X.totalWidth < 2 ^ w) (privateFit : L.dest + argumentSize X v < 2 ^ w)
+ (c : Config w p r) (hc : c.pc = pc (.boot 0)) (saved : Saved L reg c)
+ (hn : M.publicData 6 = (L.n : Word w))
+ (stride : c.privateMem (c.privateMem (L.n : Word w)+7) = (L.stride : Word w)) :
+ let mem := after initial (eventLog (FinalBits.reports w L.wires f))
+ ∃ out es, out.pc = done ∧ Frame reg c out ∧
+ out.privateMem = PrivateFields.storeBits L.dest (NodeArguments.packed X v (half X f v)) c.privateMem ∧
+ Cost es (15+21*2^a+5*argumentSize X v) (5*2^a+argumentSize X v) ∧ Prefix M mem c es out := by
+ let mem := after initial (eventLog (FinalBits.reports w L.wires f))
+ have fields := rows.after_reports X L f sharedFit apart
+ have bits (i) : mem (L.wires+i.val) = PrivateFields.bitValue w (f i) :=
+ FinalBits.readback L.wires (by rwa [TerminalPrefix.width_sum]) f initial i
+ exact run hl mem num fields (fits num fields f bits countFit headsFit sharedFit privateFit)
+ f bits c hc saved hn stride
+
+private theorem sum_side (X : State a g) (d : Bool) :
+ ∑ v : X.network.Site, ∑ j, X.halfWidth v d j = X.totalWidth := by
+ let target : X.network.Edge ≃ X.network.Edge := if d then X.slots.actualGraph.target.symm else Equiv.refl _
+ let ws (e : X.network.Edge) := TerminalPrefix.width X (number X e)
+ have eq (v : X.network.Site) (j : Fin (2^a)) : X.halfWidth v d j = ws (target (v,j)) := by
+ cases d <;> exact (slot_width X v _ j).symm
+ calc
+ _ = ∑ e : X.network.Edge, ws (target e) := by
+ change _ = ∑ e : X.network.Site × Fin (2^a), ws (target e)
+ rw [Fintype.sum_prod_type]; simp_rw [eq]; rfl
+ _ = ∑ e : X.network.Edge, ws e := target.sum_comp ws
+ _ = ∑ j, TerminalPrefix.width X j := (number X).sum_comp (TerminalPrefix.width X)
+ _ = X.totalWidth := TerminalPrefix.width_sum X
+
+theorem argumentSize_total (X : State a g) : ∑ v : X.network.Site, argumentSize X v = 2*X.totalWidth := by
+ simp only [argumentSize, Fintype.sum_bool, Finset.sum_add_distrib, sum_side, two_mul]
+
+/-- Exact external traffic of all the actual gather prefixes, including
+both occurrences of a loop and each of the five directory probes per arc. -/
+theorem probes_total (X : State a g) (es : X.network.Site → List (Event w))
+ (cost : ∀ v, Cost (es v) (15+21*2^a+5*argumentSize X v) (5*2^a+argumentSize X v)) :
+ ∑ v : X.network.Site, countProbes (es v) = 5*TerminalPrefix.arcCount X + 2*X.totalWidth := by
+ have card : Fintype.card X.network.Site = (siteOrder X).length := by
+ simpa only [Fintype.card_fin] using Fintype.card_congr (siteOrder X).entries.symm
+ simp only [(cost _).probes, Finset.sum_add_distrib, argumentSize_total, Finset.sum_const, Finset.card_univ,
+ nsmul_eq_mul, card]
+ change _ = 5 * ((siteOrder X).length * 2 ^ a) + _
+ simp only [Nat.cast_id]
+ ring
+
+end PairSimulation.TerminalGatherNative
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalGatherReadSafety.lean b/lean/OAI/Computability/VPVNP/PairTerminalGatherReadSafety.lean
new file mode 100644
index 0000000000..5618ddf954
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalGatherReadSafety.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherReads
+import OAI.Computability.VPVNP.PairSimulationFieldReadSafety
+import OAI.Computability.VPVNP.PairTerminalGatherGeometry
+
+/-! # External read bounds of the terminal root gather
+
+The inverse mate, width and prefix reads all use genuine arc ordinals. Each
+bit read lies in its arc's interval in the shared array. When these arrays
+end below the terminal header, every read belongs to the worker memory
+that agrees between the source execution and its linked replay.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalGatherGeometry
+
+open BurstRAM BurstRAM.PrivateRAM Compression TerminalRootGather
+open scoped Fin.CommRing
+
+variable {a g w : ℕ} {X : State a g} {L : Layout} {u : X.network.Site} {m : Memory w}
+
+/-- The three incidence arrays and the entire shared-bit interval suffice
+to locate every individual read performed by the native root gather. -/
+theorem worker_readable (num : Numbering X L u) (rows : Rows X L m) (H : Word w)
+ (fit : H.val + 31 < 2^w)
+ (heads : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead], head + TerminalPrefix.arcCount X ≤ H.val)
+ (wires : L.wires + X.totalWidth ≤ H.val) :
+ L.Readable m (TerminalLink.workerCell H) := by
+ have addressed (d : Bool) (j : Fin (2^a)) : L.edge m d j.val < TerminalPrefix.arcCount X := by
+ rw [edge_eq num rows]
+ exact (number X _).isLt
+ constructor
+ · intro j hj
+ rw [num.degree] at hj
+ apply TerminalLink.workerCell_of_lt fit
+ rw [num.index X L ⟨j,hj⟩]
+ exact (Nat.add_lt_add_left (number X (u,⟨j,hj⟩)).isLt _).trans_le (heads _ (by simp))
+ · intro d j hj
+ rw [num.degree] at hj
+ exact TerminalLink.workerCell_of_lt fit
+ ((Nat.add_lt_add_left (addressed d ⟨j,hj⟩) _).trans_le (heads _ (by simp)))
+ · intro d j hj
+ rw [num.degree] at hj
+ exact TerminalLink.workerCell_of_lt fit
+ ((Nat.add_lt_add_left (addressed d ⟨j,hj⟩) _).trans_le (heads _ (by simp)))
+ · intro d j hj i hi
+ rw [num.degree] at hj
+ let k : Fin (2^a) := ⟨j,hj⟩
+ apply TerminalLink.workerCell_of_lt fit
+ apply (Nat.add_lt_add_left hi _).trans_le
+ rw [start_eq num rows d k, width_eq num rows d k, ← slot_width, Nat.add_assoc]
+ have bound := EndpointBits.arc_fits (TerminalPrefix.width X) (number X (arc X u d k))
+ rw [TerminalPrefix.width_sum] at bound
+ exact (Nat.add_le_add_left bound _).trans wires
+
+end PairSimulation.TerminalGatherGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalLayout.lean b/lean/OAI/Computability/VPVNP/PairTerminalLayout.lean
new file mode 100644
index 0000000000..35142570a2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalLayout.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.PairSimulationLeafArena
+import OAI.Computability.VPVNP.PairSimulationNodeFieldSpace
+import OAI.Computability.VPVNP.PairTraversalRows
+import OAI.Computability.VPVNP.CompressorDescriptorSquare
+
+/-!
+# Physical terminal layout of the compressed pair
+
+The final 32 words of the live pair workspace hold the terminal controller
+header. The selected traversal rows, final bit interval and role words lie
+below it. A private burst uses a node's absolute descriptor address for its
+argument buffer. The first unused node buffer begins the private histogram.
+A twelve-word geometry directory follows that histogram, and a 38-word
+operand cache precedes the local verifier stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLayout
+
+open Compression CursorBounds CursorNetwork CompressorRecords Filter TraversalRows
+
+/-- Beginning of the terminal controller header inside the live pair workspace. -/
+def headerBase (workspace r : ℕ) : ℕ := workspace + (2 ^ r)^2 - 32
+
+/-- The program-wide argument, histogram, cache and stack intervals. -/
+def privateRegions (degree n rowEnd labelCount : ℕ) : LeafArena.Regions :=
+ ⟨⟨n, NodeArguments.frameStride degree n⟩, rowEnd, labelCount, n^5⟩
+
+/-- Immutable words reloaded by cursor leaves and the map dispatch after
+the DFS has popped their node address. Cell `n` points at this array. -/
+def geometry (R : LeafArena.Regions)
+ (rowBase rowStride radixB radixL shadow span roleOffset n : ℕ) :
+ Fin 12 → ℕ :=
+ ![rowBase,rowStride,radixB,radixL,shadow,span,R.arguments.start,R.arguments.stride,
+ R.cacheBase,n,roleOffset,R.histBase]
+
+theorem regions_formulas (degree n rowEnd labels : ℕ) :
+ let R := privateRegions degree n rowEnd labels
+ R.histBase = n + rowEnd * (2 * degree * n + 1) ∧
+ R.cacheBase = R.histBase + labels + n^5 ∧ R.stackBase = R.cacheBase + 38 := ⟨rfl,rfl,rfl⟩
+
+private theorem positiveEnd (L : DescriptorSpace.Layout) : 0 < DescriptorSpace.endAddress L := by
+ rw [DescriptorSpace.endAddress_eq, DescriptorSpace.Shape.fixedWords]
+ omega
+
+/-- Every real node buffer starts above the private cell that points to
+the immutable geometry. This includes the initial cursor layer. -/
+theorem geometryPointer_before_node {n degree rowEnd labels node : ℕ}
+ (L : DescriptorSpace.Layout) (h : DescriptorSpace.endAddress L ≤ node) :
+ n < (privateRegions degree n rowEnd labels).arguments.base node := by
+ have hn := (positiveEnd L).trans_le h
+ change n < n + node*(2*degree*n+1)
+ exact Nat.lt_add_of_pos_right (Nat.mul_pos hn (Nat.succ_pos _))
+
+/-- All simultaneous external and private regions fit on every selected
+cursor branch. The untouched high header and the private pointer cell are
+separated from their adjacent live arrays. -/
+theorem eventually_fitWithReserve {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (F : DescriptorSpace.Shape)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hstart : PolynomiallyBounded start)
+ (ports : ℕ) (extra : ℕ → ℕ) (hextra : PolynomiallyBounded extra) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ let L := DescriptorSpace.cursorLayout F b S.steps u.θ (start n) n
+ let rowBase := DescriptorSpace.endAddress L
+ let H := headerBase (start n) (addressBits b n)
+ ∀ z : E.Choices,
+ let Y := E.finalState z
+ let rows := words B.recordLimit (selectedLayers B f hf T hT X z)
+ let R := privateRegions (slotDegree S) n (rowBase+rows) (Fintype.card B.Entry)
+ rowBase + 2*rows + Y.totalWidth < H ∧ H + 32 ≤ 2^(wordBits b n) ∧
+ R.histBase + R.histWords + 12 ≤ R.cacheBase ∧
+ R.stackBase + ports*n^40 + extra n < 2^(wordBits b n) := by
+ let K := 2*(B.recordLimit+2)+33
+ let P := initialPositions b
+ let maxEnd n := start n + (P n)^2
+ let maxPrivate n := (privateRegions (slotDegree S) n (maxEnd n) (Fintype.card B.Entry)).stackBase
+ + ports*n^40 + extra n
+ have hmax : PolynomiallyBounded maxEnd := hstart.add ((CursorRAM.bounded_positions b).pow 2)
+ have hprivate : PolynomiallyBounded maxPrivate := by
+ dsimp only [maxPrivate, privateRegions, LeafArena.Regions.stackBase,
+ LeafArena.Regions.cacheBase, LeafArena.Regions.histBase, NodeArguments.Arena.base]
+ have frame := PolynomiallyBounded.id.add
+ (hmax.mul (NodeArguments.frameStride_bounded (slotDegree S)))
+ have hist := frame.add (PolynomiallyBounded.const (Fintype.card B.Entry))
+ have cache := hist.add (PolynomiallyBounded.id.pow 5)
+ exact ((cache.add (PolynomiallyBounded.const 38)).add
+ ((PolynomiallyBounded.const ports).mul (PolynomiallyBounded.id.pow 40))).add hextra
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ filter_upwards [DescriptorSpace.eventually_selected_square F B u b hb K,
+ CursorRAM.eventual_word_room b hb' hmax, CursorRAM.eventual_word_room b hb' hprivate,
+ eventually_ge_atTop 3] with n hs hmax hprivate hn
+ intro base lanes labels hD hT A _ f hf X T E L rowBase H z Y rows R
+ have foot := selected_words_le B f hf T hT X z
+ change rows ≤ (B.recordLimit+2)*Y.positions*B.growthConstant^T at foot
+ have square := hs (start n) labels hD hT A f hf z
+ have far : rowBase + 2*rows + Y.totalWidth + 32 < start n + (processorCount b n)^2 := by
+ apply lt_of_le_of_lt _ square
+ change rowBase+2*rows+Y.totalWidth+32 ≤
+ rowBase+K*(X.positions+processorCount b n+Y.positions*B.growthConstant^T+Y.totalWidth)+1
+ have hp := X.positions_pos
+ dsimp only [K]
+ nlinarith only [foot, hp,
+ Nat.zero_le (B.recordLimit*(X.positions+processorCount b n+Y.totalWidth))]
+ have hR : processorCount b n ≤ P n :=
+ (Nat.pow_le_pow_right Nat.zero_lt_two (addressBits_le_virtualBits b n hn)).trans
+ (Nat.le_mul_of_pos_right _ (by omega : 0 < virtualBits b n))
+ have hEnd : start n + (processorCount b n)^2 ≤ maxEnd n := Nat.add_le_add_left
+ (Nat.pow_le_pow_left hR 2) _
+ have hpos : rowBase+rows ≤ maxEnd n := (by omega :
+ rowBase+rows ≤ start n + (processorCount b n)^2).trans hEnd
+ change rowBase+2*rows+Y.totalWidth < start n+(processorCount b n)^2-32 ∧
+ start n+(processorCount b n)^2-32+32 ≤ 2^(wordBits b n) ∧ _ ∧ _
+ refine ⟨by omega, (by omega : _ ≤ start n+(processorCount b n)^2).trans (hEnd.trans hmax.le),
+ ?_, ?_⟩
+ · change R.histBase + Fintype.card B.Entry + 12 ≤ R.histBase + Fintype.card B.Entry + n^5
+ exact Nat.add_le_add_left ((by decide : 12 ≤ 3^5).trans (Nat.pow_le_pow_left hn 5)) _
+ · apply lt_of_le_of_lt _ hprivate
+ dsimp only [maxPrivate, R, privateRegions, LeafArena.Regions.stackBase,
+ LeafArena.Regions.cacheBase, LeafArena.Regions.histBase, NodeArguments.Arena.base]
+ gcongr
+
+/-- The selected private region through the last virtual verifier stack. -/
+theorem eventually_fit {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (F : DescriptorSpace.Shape)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hstart : PolynomiallyBounded start)
+ (ports : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ let L := DescriptorSpace.cursorLayout F b S.steps u.θ (start n) n
+ let rowBase := DescriptorSpace.endAddress L
+ let H := headerBase (start n) (addressBits b n)
+ ∀ z : E.Choices,
+ let Y := E.finalState z
+ let rows := words B.recordLimit (selectedLayers B f hf T hT X z)
+ let R := privateRegions (slotDegree S) n (rowBase+rows) (Fintype.card B.Entry)
+ rowBase + 2*rows + Y.totalWidth < H ∧ H + 32 ≤ 2^(wordBits b n) ∧
+ R.histBase + R.histWords + 12 ≤ R.cacheBase ∧
+ R.stackBase + ports*n^40 < 2^(wordBits b n) := by
+ simpa only [Nat.add_zero] using
+ eventually_fitWithReserve B u F b hb hstart ports (fun _ => 0) (PolynomiallyBounded.const 0)
+
+end PairSimulation.TerminalLayout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalLowCells.lean b/lean/OAI/Computability/VPVNP/PairTerminalLowCells.lean
new file mode 100644
index 0000000000..b6852abae4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalLowCells.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.PairTerminalPrefixLinked
+import OAI.Computability.VPVNP.PairTerminalFootprint
+import OAI.Computability.VPVNP.PairSimulationPhysicalScanData
+import OAI.Computability.VPVNP.LiveCompressedPairFrames
+import OAI.Computability.VPVNP.PairTerminalShadowChronology
+
+/-!
+# Preservation of the low counter addresses before vertex evaluation
+
+The terminal bootstrap writes its high header. The prefix scan writes its
+offset array and the total and role fields in that header. The row builder
+preserves lower addresses, and the shared scan writes only the final wire
+bank. This leaves the live grammar and motif words available to the first
+vertex burst.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalPrefix.Linked
+open BurstRAM Compression LiveProgram CompressorRecords SourceTransport TerminalLink
+open scoped Fin.CommRing
+
+variable {w a g cap f : ℕ} {workers : TerminalLink.Stage → PairTable} {ports : Fin 11 → Word w} {X : State a g}
+ {dir : IncidenceDirectory w} {starts : Word w} {input : Memory w} {raw : Report w} {rs : List (Report w)}
+
+theorem Start.prefix_below (s : Start workers ports cap f X dir starts input raw rs)
+ (room : (header ports).val+32 ≤ 2^w) (i : ℕ) (low : i < (header ports).val)
+ (before : i < starts.val) (boot : after input raw.events i = input i) :
+ prefixMemory ports input raw rs i = input i := by
+ have fit : (header ports).val+31 < 2^w := by omega
+ have cell := TerminalFootprint.below (header ports) fit low
+ have h12 : i ≠ (Worker.header ports+12).val := by
+ change i ≠ (header ports + (12 : Word w)).val
+ have eq : (header ports + (12 : Word w)).val = (header ports).val + 12 :=
+ TerminalFootprint.header_val _ fit (j := 12) (by decide)
+ rw [eq]
+ omega
+ have h14 : i ≠ (Worker.header ports+14).val := by
+ change i ≠ (header ports + (14 : Word w)).val
+ have eq : (header ports + (14 : Word w)).val = (header ports).val + 14 :=
+ TerminalFootprint.header_val _ fit (j := 14) (by decide)
+ rw [eq]
+ omega
+ have agree := (s.scan.agree i cell).symm
+ change prefixMemory ports input raw rs i = after (after input raw.events) (eventLog rs) i at agree
+ rw [agree,s.rawScan.stored.outside i h12 (Or.inl before)]
+ simpa only [writeMemory,ite_eq_right h14] using boot
+
+end PairSimulation.TerminalPrefix.Linked
+
+namespace PairSimulation.SharedBitPhase
+open BurstRAM CompressorRecords SourceTransport TerminalLink
+
+theorem below_bank {w : ℕ} (shape : DescriptorSpace.Shape) (limit : ℕ) (S : VertexImage.Part → VertexImage.Segment)
+ (ports : Fin 11 → Word w) (cap : ℕ) (src phy : Memory w) {lo count : ℕ}
+ (layout : FinalBits.Worker.Layout ports src lo count) (clock : 54 ≤ cap)
+ (room : (header ports).val+32 ≤ 2^w) (below : lo+count ≤ (header ports).val)
+ (agree : Agree (workerCell (header ports)) src phy)
+ (valid : (Entry.resume Stage.sharedBits (0 : Word w)).Valid (header ports) phy)
+ (f : Fin count → Bool) (i : ℕ) (hi : i < lo) :
+ (equiv shape limit S ports cap src phy layout clock room below agree f).val.memory i = phy i := by
+ have cell : workerCell (header ports) i := TerminalFootprint.below _ (by omega) (by omega)
+ exact ((memory_image shape limit S ports cap src phy layout clock room below agree valid f) i cell).symm.trans
+ ((FinalBits.outside lo layout.fits f src i (Or.inl hi)).trans (agree i cell))
+
+
+/-- The vertex worker can replay its source on the post-scan physical
+memory. At addresses below the workspace the bootstrap, prefix, row,
+shared-bit and replay steps all preserve the original input word. -/
+theorem vertex_source_below {w a g f₀ : ℕ} (shape : DescriptorSpace.Shape) (limit : ℕ)
+ (S : VertexImage.Part → VertexImage.Segment) (ports : Fin 11 → Word w) (cap : ℕ)
+ {X : Compression.State a g} {dir : IncidenceDirectory w} {starts : Word w}
+ {input : Memory w} {boot : Report w} {prefixRows : List (Report w)}
+ (start : TerminalPrefix.Linked.Start (TerminalProgram.workers shape limit S) ports cap f₀ X dir starts input boot prefixRows)
+ (src phy : Memory w) {lo : ℕ}
+ (layout : FinalBits.Worker.Layout ports src lo X.totalWidth) (clock : 54 ≤ cap)
+ (room : (header ports).val+32 ≤ 2^w) (below : lo+X.totalWidth ≤ (header ports).val)
+ (agree : Agree (workerCell (header ports)) src phy)
+ (valid : (Entry.resume Stage.sharedBits (0 : Word w)).Valid (header ports) phy)
+ (bits : Fin X.totalWidth → Bool) (vertexSrc : Memory w)
+ (atVertex : Agree (workerCell (header ports)) vertexSrc
+ (equiv shape limit S ports cap src phy layout clock room below agree bits).val.memory)
+ (i : ℕ) (wireLow : i < lo) (indexLow : i < starts.val)
+ (bootCell : after input boot.events i = input i)
+ (rowCell : phy i = TerminalPrefix.Linked.prefixMemory ports input boot prefixRows i) :
+ vertexSrc i = input i := by
+ have hH : i < (header ports).val := by omega
+ have cell := TerminalFootprint.below (header ports) (by omega) hH
+ exact (atVertex i cell).trans ((below_bank shape limit S ports cap src phy layout clock room below agree valid bits i wireLow).trans
+ (rowCell.trans (start.prefix_below room i hH indexLow bootCell)))
+
+end PairSimulation.SharedBitPhase
+
+namespace LiveProgram.CompressedPair
+open BurstRAM Compression PairSimulation CompressorRecords SourceTransport
+open PairStages.Group PairStages.Group.CompressedPaths
+
+/-- Every live counter lies below the auxiliary shadow and the compression
+workspace. The low part of the word-address layout fits without wraparound. -/
+theorem counter_before_pairTag (G : PairStages.Group) (fit : Auxiliary.shadowBase G < 2^G.w)
+ (a : Fin (labelCount G)) :
+ Auxiliary.counterBase G + a.val < (PairTag.address (publicWords G)).val := by
+ rw [show PairTag.address (publicWords G) = Pieces.word G.g G.lit (.geometry (Layout.oldState G.constants)) from
+ tag_address G.constants G.g G.lit]
+ have old : (Layout.oldState G.constants).eval G.g < 2^G.w := (Auxiliary.counter_end_le_shadow G).trans_lt fit
+ change Auxiliary.counterBase G + a.val < (Layout.oldState G.constants).eval G.g % 2^G.w
+ rw [Nat.mod_eq_of_lt old]
+ exact Nat.add_lt_add_left a.isLt _
+
+
+/-- The source word handed to the terminal bootstrap at a live counter
+equals the original prepared nomination or zero motif word. -/
+theorem online_counter_initial {d initial phases : ℕ} {C : Schedule.Catalog d}
+ (b : Bootstrap) (plan : Schedule.Online.Config C initial phases) (terminal : PairTable)
+ (G : PairStages.Group) (B n : ℕ) (m : Memory G.w)
+ (runs : TransferredStartup.Runs (bootstrapRows b initial phases) d
+ (startupLayout b initial phases B n ((publicWords G) 2).val) B n b.degreeBits b.lanesPerBlock b.steps
+ (publicWords G) (PairTag.address (publicWords G)) m)
+ {clock : ℕ} (path : StagePaths b plan terminal (publicWords G) clock Stage.online
+ (afterStartup b (publicWords G) B n m initial phases d))
+ (rs : List (Report G.w))
+ (reported : LiveStageLink.ordinaryReports path = OnlineWorkspace.framed ((publicWords G) 2)
+ (afterStartup b (publicWords G) B n m initial phases d) rs)
+ (stable : SourceBankFrame.Stable (((publicWords G) 2).val+6)
+ (afterStartup b (publicWords G) B n m initial phases d) rs)
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w) (a : Fin (labelCount G)) :
+ onlinePost path (Auxiliary.counterBase G+a.val) = m (Auxiliary.counterBase G+a.val) := by
+ let c := G.constants
+ let g := G.g
+ have sh : (Layout.shadow c).eval g < (Layout.pairWorkspace c).eval g :=
+ Nat.lt_add_of_pos_right (Nat.two_pow_pos _)
+ have tag := counter_before_pairTag G (sh.trans fit) a
+ have ws : ((publicWords G) 2).val = (Layout.pairWorkspace c).eval g := Nat.mod_eq_of_lt fit
+ have low : Auxiliary.counterBase G+a.val < ((publicWords G) 2).val := by
+ rw [ws]
+ exact ((Nat.add_lt_add_left a.isLt _).trans_le (Auxiliary.counter_end_le_shadow G)).trans sh
+ exact onlinePost_after_startup_below b plan terminal (publicWords G) B n m runs path rs reported stable _ low tag.ne
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalNativeTable.lean b/lean/OAI/Computability/VPVNP/PairTerminalNativeTable.lean
new file mode 100644
index 0000000000..e44b06a06a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalNativeTable.lean
@@ -0,0 +1,48 @@
+import OAI.Computability.VPVNP.PairTerminalVertexBank
+import OAI.Computability.VPVNP.PairShrinkVertexImage
+import OAI.Computability.VPVNP.PairRefreshVertexRun
+
+/-!
+# The complete fixed opcode table for a compressed pair's terminal phase
+
+The same parameter numbering is used in every shrinking matrix and every
+refresh matrix. The refresh tie and slice ordering comes from the actual
+block planner. All five terminal workers share the eleven public operands of
+the enclosing pair. Their finite instruction and register counts depend only
+on the schedule, the fixed live constants and the label enumeration.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open Compression CompressorRecords LiveProgram
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+variable (c : Constants) (p q : ℕ) {labels : ℕ} (order : B.Entry ≃ Fin labels)
+
+/-- The actual map, leaf, shared-wire, geometry and DFS segments on one
+fixed register allocation. -/
+noncomputable def nativeSegments : VertexImage.Part → VertexImage.Segment :=
+ installedSegments c S p q (ShrinkVertexImage.shrinkSegment B order)
+ (RefreshVertex.refreshSegment B (RefreshBlockPlan.order B)
+ (RefreshBlockPlan.shape B).stride order)
+
+/-- The input-independent terminal table in the paper's live pair machine. -/
+noncomputable def nativeTable : PairTable :=
+ table (BlockProgram.allocationShape B) B.recordLimit (nativeSegments B c p q order)
+
+/-- Its instruction image is the actual five-stage program for each packed
+level directory, with the concrete finite role handlers installed. -/
+theorem nativeTable_eq (base positions blocks : ℕ) :
+ table (BlockProgram.layout B base positions blocks).shape B.recordLimit
+ (nativeSegments B c p q order) = nativeTable B c p q order :=
+ congrArg TerminalLink.table (TerminalLayout.packed_workers B base positions blocks _)
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPackedBudget.lean b/lean/OAI/Computability/VPVNP/PairTerminalPackedBudget.lean
new file mode 100644
index 0000000000..9ef961b24d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPackedBudget.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.PairTerminalLayout
+import OAI.Computability.VPVNP.PairTraversalControllerOrdinal
+import OAI.Computability.VPVNP.PairTerminalSelectedHeaders
+import OAI.Computability.VPVNP.PairSimulationTerminalProgram
+import OAI.Computability.VPVNP.CompressorBlockCapacity
+import OAI.Computability.VPVNP.LiveCompressedPairHandoff
+import OAI.Computability.VPVNP.LiveProgramCompressedPairPaths
+
+/-!
+# Resource bounds for the packed physical terminal directory
+
+The native startup reserves the actual number of calendar rows. The first DFS
+address is the end of that packed directory. The fixed instruction table reads
+its dynamic dimensions from memory and uses the same compiled layout constants
+at every input length. The room here includes the private map staging region
+after all cursor verifier stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLayout
+
+open BurstRAM PrivateRAM Compression CursorNetwork CursorBounds CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles Filter
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+private theorem calculation_congr (F G : Shape) (limit : ℕ)
+ (arity : F.arity = G.arity) (scalars : F.scalarFields = G.scalarFields) :
+ TerminalBootstrap.calculation F limit = TerminalBootstrap.calculation G limit := by
+ rcases F with ⟨a,i,l,s,f,t,d,k⟩
+ rcases G with ⟨b,j,m,v,g,u,e,n⟩
+ change a = b at arity
+ change f = g at scalars
+ subst b
+ subst g
+ rfl
+
+private theorem bank_congr (F G : Shape) (limit : ℕ)
+ (segments : VertexImage.Part → VertexImage.Segment)
+ (arity : F.arity = G.arity) (scalars : F.scalarFields = G.scalarFields) :
+ TerminalProgram.workers F limit segments = TerminalProgram.workers G limit segments := by
+ unfold TerminalProgram.workers TerminalBootstrap.table
+ rw [calculation_congr F G limit arity scalars]
+
+/-- The bootstrap has a fixed source instruction count independent of the
+number of rows in the chronological directory. -/
+theorem packed_bootCost (B : S.Templates) (base positions blocks : ℕ) :
+ TerminalBootstrap.cost (BlockProgram.layout B base positions blocks).shape B.recordLimit =
+ TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit := by
+ exact congrArg (fun d => d.recipe.code.length)
+ (calculation_congr (BlockProgram.layout B base positions blocks).shape
+ (BlockProgram.allocationShape B) B.recordLimit rfl rfl)
+
+/-- The initial row count and the per-level directory length vary, while the
+code of the terminal worker bank is the fixed code chosen with the templates. -/
+theorem packed_workers (B : S.Templates) (base positions blocks : ℕ)
+ (segments : VertexImage.Part → VertexImage.Segment) :
+ TerminalProgram.workers (BlockProgram.layout B base positions blocks).shape
+ B.recordLimit segments =
+ TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit segments :=
+ bank_congr _ _ _ _ rfl rfl
+
+/-- Dispatch of the live pair and its inner terminal phase consumes forty-one
+units of the enclosing processor clock before the worker's private cut. -/
+theorem pair_clock (G : LiveProgram.PairStages.Group) :
+ LiveProgram.CompressedPair.clockAt (LiveProgram.PairStages.Group.CompressedPaths.publicWords G)
+ (LiveProgram.PairStages.Group.CompressedPaths.fuel G)
+ LiveProgram.CompressedPair.Stage.terminal =
+ G.clock - 41 := by
+ change (G.clock-14)-5-22 = G.clock-41
+ omega
+
+set_option exponentiation.threshold 10000 in
+/-- The live pair clock supplies all fixed controller and linker margins. -/
+theorem eventually_pair_clock (K : ℕ) : ∀ᶠ n : ℕ in atTop,
+ ∀ G : LiveProgram.PairStages.Group, n^10000 ≤ G.clock →
+ K ≤ LiveProgram.CompressedPair.clockAt
+ (LiveProgram.PairStages.Group.CompressedPaths.publicWords G)
+ (LiveProgram.PairStages.Group.CompressedPaths.fuel G)
+ LiveProgram.CompressedPair.Stage.terminal := by
+ filter_upwards [eventually_ge_atTop (K+41)] with n hn
+ intro G hg
+ rw [pair_clock]
+ have h := Nat.le_self_pow (by decide : 10000 ≠ 0) n
+ omega
+
+/-- Simultaneous numerical room for the actual branch. The term choice,
+field assignment, register contents and optional map work are outside the
+choice of the length threshold. -/
+theorem eventually_packedFit (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hstart : PolynomiallyBounded start)
+ (ports : ℕ) (extra : ℕ → ℕ) (hextra : PolynomiallyBounded extra) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let w := wordBits b n
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ let L := BlockProgram.layout B (start n) (initialPositions b n) T
+ let H := headerBase (start n) (addressBits b n)
+ ∀ z : E.Choices,
+ let Y := E.finalState z
+ let rows := words B.recordLimit (selectedLayers B f hf T hT X z)
+ let tags := selected B f hf T hT X z
+ let R := privateRegions (slotDegree S) n (endAddress L+rows) (Fintype.card B.Entry)
+ endAddress L + 2*rows + Y.totalWidth < H ∧ H+32 ≤ 2^w ∧
+ R.histBase + R.histWords + 12 ≤ R.cacheBase ∧
+ R.stackBase + ports*n^40 + extra n < 2^w ∧
+ 2*tags.length*(X.positions+1) < 2^w := by
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ filter_upwards [eventually_fitWithReserve B u (BlockProgram.allocationShape B) b hb hstart
+ ports extra hextra, TraversalControllerOrdinal.eventually_selected_fit B u b hb'] with n h hO
+ intro base lanes labels hD hT A _ f hf w X T E L H z Y rows tags R
+ let upper := cursorLayout (BlockProgram.allocationShape B) b S.steps u.θ (start n) n
+ let U := privateRegions (slotDegree S) n (endAddress upper+rows) (Fintype.card B.Entry)
+ have eqn := BlockProgram.allocation_end B (start n) (initialPositions b n) T
+ change endAddress L ≤ endAddress upper at eqn
+ have ⟨ext,head,hist,stack⟩ := h labels hD hT A f hf z
+ change endAddress upper+2*rows+Y.totalWidth < H at ext
+ change U.histBase + U.histWords + 12 ≤ U.cacheBase at hist
+ change U.stackBase+ports*n^40+extra n < 2^w at stack
+ have hlen : tags.length = (executeLevels B f hf T hT X z).length+1 := by
+ simp only [tags,selected,List.length_cons,List.length_map]
+ refine ⟨by omega,head,?_,?_,?_⟩
+ · change R.histBase + Fintype.card B.Entry + 12 ≤ R.histBase + Fintype.card B.Entry + n^5
+ change U.histBase + Fintype.card B.Entry + 12 ≤ U.histBase + Fintype.card B.Entry + n^5 at hist
+ omega
+ · apply lt_of_le_of_lt _ stack
+ dsimp only [R,U,privateRegions,LeafArena.Regions.stackBase,LeafArena.Regions.cacheBase,
+ LeafArena.Regions.histBase,NodeArguments.Arena.base]
+ gcongr
+ · rw [hlen]
+ exact hO labels hD hT A f hf z
+
+end PairSimulation.TerminalLayout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPackedPrefix.lean b/lean/OAI/Computability/VPVNP/PairTerminalPackedPrefix.lean
new file mode 100644
index 0000000000..37defbf3a6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPackedPrefix.lean
@@ -0,0 +1,306 @@
+import OAI.Computability.VPVNP.PairTerminalCalendarBoundary
+import OAI.Computability.VPVNP.PairTraversalResidentHandoff
+import OAI.Computability.VPVNP.PairTerminalSelectedPrefix
+import OAI.Computability.VPVNP.PairTerminalVertexMemory
+import OAI.Computability.VPVNP.PairSimulationSharedBitPhase
+import OAI.Computability.VPVNP.CompressorDetailedResident
+
+/-!
+# Selected calendar data at the physical vertex entry
+
+The packed calendar supplies the terminal bootstrap, width-prefix scan and
+traversal construction. Each shared-wire assignment then determines one
+physical bit block. At its exit, the earlier parser tables and the final
+incidence bank still read their producing values. The final prefix table
+reads the computed arc offsets, and the vertex worker sees the actual DFS
+rows, role tags and wire bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TraversalControllerInputs TerminalPrefix TerminalPrefix.Linked TerminalLink
+open scoped Fin.CommRing
+
+variable {w : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable {n : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "rowsSize" => words B.recordLimit (ls)
+local notation "last" => List.length (List.dropLast (ls))
+
+private theorem move_directories {base H first pitch offset floor : ℕ} {pub : Fin 11 → Word w}
+ {src vertex : Memory w} (ds : (i : Fin (vs).length) → LevelDirectory vs[i] src base)
+ (d : Resident pub src H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers (vs) ds))
+ (lower : ∀ i, floor ≤ ((ds i).pub 1).val)
+ (heads : ∀ j ≤ (vs).length, first+j*pitch+28 ≤ base)
+ (frame : ∀ x < base, vertex x = src x)
+ (same : ∀ j ∈ terminalScalars, vertex (H+j) = src (H+j)) :
+ ∃ ds' : (i : Fin (vs).length) → LevelDirectory vs[i] vertex base,
+ (∀ i, floor ≤ ((ds' i).pub 1).val) ∧ Resident pub vertex H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers (vs) ds') := by
+ let nextDirs (i : Fin (vs).length) : LevelDirectory vs[i] vertex base :=
+ (ds i).transport fun x hx => (frame x ((ds i).cells_interval hx).2).symm
+ have banks : levelFibers (vs) nextDirs = levelFibers (vs) ds := rfl
+ refine ⟨nextDirs,lower,?_⟩
+ rw [banks]
+ exact d.transfer (by simpa only [levelFibers,List.length_ofFn] using heads) frame same
+
+/-- Readback of the selected parser history and the native DFS data after
+the four linked stages, for one assignment of the shared bits. -/
+structure VertexEntry (L : Layout) (tab : Fin L.shape.tables) (baseBits laneBits : ℕ)
+ (pub : Fin 11 → Word w) (calendar vertex : Memory w) (bits : Fin (Y).totalWidth → Bool) : Prop where
+ boundedDirectories : ∃ ds : (i : Fin (vs).length) → LevelDirectory vs[i] vertex (endAddress L),
+ (∀ i, levelsBase L ≤ ((ds i).pub 1).val) ∧ Resident pub vertex (header pub).val (levelStart L 0) (levelWords L) (rowsSize+(Y).totalWidth)
+ B.recordLimit (endAddress L) ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers (vs) ds)
+ valid : (Entry.resume Stage.vertices (0 : Word w)).Valid (header pub) vertex
+ rows : AllRows w vertex B.recordLimit (endAddress L) (endAddress L) (ls)
+ roles : Reads w vertex (rowsSize + (Y).totalWidth) B.recordLimit (endAddress L) (tags)
+ wires : ∀ i, vertex (endAddress L+rowsSize+i.val) = PrimedInputRAM.encodeBit w (bits i)
+ offsets : ∀ i : Fin (arcCount (Y)), (vertex (tableBase L last tab + i.val)).val =
+ EndpointBits.offset (width (Y)) i
+ raw : ∀ x < endAddress L, x < tableBase L last tab ∨ tableBase L last tab + arcCount (Y) ≤ x →
+ vertex x = calendar x
+ headers : ∀ j : Fin 21, 0 < j.val → j.val ≠ 12 → j.val ≠ 14 →
+ vertex ((header pub).val+j.val) = TerminalBootstrap.values L last
+ (TerminalBootstrap.fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab)
+ B.recordLimit pub calendar j
+ total : (vertex ((header pub).val+12)).val = (Y).totalWidth
+ offset : vertex ((header pub).val+14) = ((rowsSize + (Y).totalWidth : ℕ) : Word w)
+
+variable {B f hf T hT X z} in
+/-- Every selected placement directory is present in the entry memory. -/
+theorem VertexEntry.directories {L : Layout} {tab : Fin L.shape.tables}
+ {baseBits laneBits : ℕ} {pub : Fin 11 → Word w} {calendar vertex : Memory w}
+ {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits pub calendar vertex bits) :
+ ∃ ds : (i : Fin (vs).length) → LevelDirectory vs[i] vertex (endAddress L),
+ Resident pub vertex (header pub).val (levelStart L 0) (levelWords L) (rowsSize+(Y).totalWidth)
+ B.recordLimit (endAddress L) ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers (vs) ds) := by
+ obtain ⟨ds,_,d⟩ := entry.boundedDirectories
+ exact ⟨ds,d⟩
+
+/-- The native level locator uses the packed origin and pitch still present
+in the terminal header at vertex entry. -/
+theorem VertexEntry.level_head {L : Layout} {tab : Fin L.shape.tables} {baseBits laneBits : ℕ}
+ {pub : Fin 11 → Word w} {calendar vertex : Memory w} {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits pub calendar vertex bits) (j : ℕ) :
+ levelHead pub vertex j = (levelStart L j : Word w) := by
+ obtain ⟨ds,d⟩ := entry.directories
+ rw [levelHead, terminal_read d 16 (by decide), terminal_read d 17 (by decide), d.firstHead,
+ d.levelPitch, ← Nat.cast_mul, ← Nat.cast_add]
+ simp only [levelStart,Nat.zero_mul,Nat.add_zero]
+
+theorem VertexEntry.level_head_val {L : Layout} {tab : Fin L.shape.tables} {baseBits laneBits : ℕ}
+ {pub : Fin 11 → Word w} {calendar vertex : Memory w} {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits pub calendar vertex bits)
+ (j : ℕ) (hj : j ≤ (vs).length) : (levelHead pub vertex j).val = levelStart L j := by
+ obtain ⟨ds,d⟩ := entry.directories
+ have fit := d.levelFits j (by simpa only [levelFibers,List.length_ofFn] using hj)
+ rw [entry.level_head B f hf T hT X z j, Fin.val_natCast, Nat.mod_eq_of_lt]
+ simp only [levelStart,Nat.zero_mul,Nat.add_zero] at fit ⊢
+ omega
+
+/-- Recover every producing snapshot, including the final pass's successor
+incidence. Only addresses before the last scratch bank are used. -/
+theorem VertexEntry.payload {L : Layout} {tab : Fin L.shape.tables} {baseBits laneBits : ℕ}
+ {pub : Fin 11 → Word w} {calendar vertex : Memory w} {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits pub calendar vertex bits)
+ (hl : last < L.levels) {data : SelectedPayloadHistory.Data (w := w) B f hf}
+ (past : SelectedPayloadHistory.Past B f hf L data (vs) calendar) :
+ SelectedPayloadHistory.Past B f hf L data (vs) vertex := by
+ have idx := TerminalBootstrap.selected_last_index B f hf T hT X z
+ have upper : tableBase L last tab + tableWords L ≤ endAddress L :=
+ (tableEnd_le_nextLevel L last tab).trans (levelStart_mono L hl)
+ apply past.transfer
+ intro x _ hx
+ rw [← idx] at hx
+ have before : x < tableBase L last tab := hx.trans_le (Nat.le_add_right ..)
+ exact entry.raw x (by omega) (.inl before)
+
+variable (positions baseBits laneBits initialWidth inputN : ℕ) (pub : Fin 11 → Word w)
+set_option quotPrecheck false in
+local notation "L" => BlockProgram.layout B (pub 2).val positions T
+set_option quotPrecheck false in
+local notation "tab" => (⟨0,by change 0 < 6; decide⟩ : Fin (L).shape.tables)
+local notation "saved" => CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L))
+ (CursorRAM.encode w 1) baseBits laneBits (S.degreeExponent 0) initialWidth (incidenceStart L 0)
+set_option quotPrecheck false in
+local notation "resident" => CurrentResident.resident B f hf ⟨leafLayer (siteOrder X), .cursor⟩
+ L (endAddress L) inputN saved
+
+set_option maxHeartbeats 800000 in
+/-- From the completed selected calendar, construct the three deterministic
+blocks and the equivalence between wire assignments and all legal fourth
+blocks. Each block leads to the selected vertex readback. -/
+theorem packed_prefix (segments : VertexImage.Part → VertexImage.Segment) (r cap : ℕ)
+ (m phy : Memory w)
+ (boundary : ScheduledTrace.Boundary resident pub (levelWords L : Word w) (directoryRows L)
+ (directoryRows L) (vs) (Y) m)
+ (handoff : SourceTransport.Agree ((pub 2).val+6 ≤ ·) m phy)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ (L).base+2^r*2^r)
+ (room : (L).base+2^r*2^r ≤ 2^w)
+ (below : endAddress L + 2*rowsSize + (Y).totalWidth ≤ TerminalBootstrap.address (L).base r)
+ (ordinal : 2*(tags).length*(X.positions+1) < 2^w)
+ (slots : arcCount (Y) ≤ slotCapacity L) (cells : arcCount (Y) ≤ tableWords L)
+ (totalFit : (Y).totalWidth < 2^w)
+ (clock₀ : TerminalBootstrap.cost (L).shape B.recordLimit+1+30 ≤ cap) (clock₁ : 60 ≤ cap)
+ (clock₂ : TraversalController.callFuel B.recordLimit+30 ≤ cap) :
+ let bank := workers (L).shape B.recordLimit segments
+ ∃ q : QuietPrefix bank pub cap phy, ∃ bitPaths : (Fin (Y).totalWidth → Bool) ≃ q.BitPaths,
+ q.boot.val.choices = [[]] ∧
+ q.prefixRows.val.choices = List.replicate (arcCount (Y)+1) [] ∧
+ q.traversalRows.val.choices =
+ List.replicate (2*((ls).map Layer.count).sum+2*(tags).length+1) [] ∧
+ FinalBits.Worker.Layout pub q.traversalRows.val.memory (endAddress L+rowsSize) (Y).totalWidth ∧
+ ∀ bits, (bitPaths bits).val.choices = FinalBits.calls bits ++ [[]] ∧
+ VertexEntry B f hf T hT X z L tab baseBits laneBits pub phy (bitPaths bits).val.memory bits := by
+ intro bank
+ let H := TerminalBootstrap.address (L).base r
+ let rowBase := endAddress L
+ let Aₜ := TerminalBootstrap.fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab
+ let boot := TerminalBootstrap.report (L).shape B.recordLimit pub 0 phy
+ have above : rowBase ≤ H := by dsimp only [rowBase,H]; omega
+ obtain ⟨⟨history⟩,ready,rs,start,_⟩ := run_boundary B f hf T hT X z positions baseBits laneBits
+ initialWidth inputN pub segments r cap m phy boundary handoff exp hr reserve room above slots
+ cells totalFit clock₀ clock₁
+ let src := prefixMemory pub phy boot rs
+ have wide : 28 ≤ (L).shape.scalarFields := by change 28 ≤ 54; decide
+ have hl : last < (L).levels := by
+ rw [TerminalBootstrap.selected_prior_length,BlockProgram.actual_level_count, Nat.mul_comm T]; omega
+ have fields := TraversalResidentHandoff.fields_of_start L last hl tab Aₜ B.recordLimit r (Y)
+ pub phy src ready exp hr reserve room above wide cells rs start start.handoff_rows.1
+ have residentData := TraversalResidentHandoff.selected_resident B f hf T hT X z
+ L baseBits laneBits tab history fields hl wide
+ let ds := residentData.choose
+ have residentFields := residentData.choose_spec.2.1
+ have heads := residentData.choose_spec.2.2
+ obtain ⟨q,hboot,hpref,hrows,_,valid,rows,roles,low,high⟩ :=
+ selectedQuietPrefix B f hf T hT X z bank pub cap _ rowBase H (levelStart L 0) (levelWords L)
+ _ _ phy boot rs rfl clock₀ clock₁ clock₂ start ds residentFields heads below ordinal
+ let mid := q.traversalRows.val.memory
+ have hv : (header pub).val = H := header_val L pub r ready.workspace exp hr reserve room
+ have fits := fields.fits
+ have pos (j : ℕ) (hj : j < 32) : (header pub+(j : Word w)).val = H+j := by
+ rw [Fin.val_add,hv,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j < 2^w),Nat.mod_eq_of_lt (by omega)]
+ have headFit : (header pub).val+32 ≤ 2^w := hv ▸ fits
+ have liveRows := TerminalBootstrap.selected_rowWords B f hf T hT X z L baseBits laneBits tab
+ have middle (j : ℕ) (hj : 0 < j) (hj' : j < 31) : mid (H+j) = src (H+j) := high j hj hj'
+ have baseValue : FinalBits.Worker.base pub mid = ((rowBase+rowsSize : ℕ) : Word w) := by
+ change mid (header pub+13).val = _
+ rw [show (header pub+13).val = H+13 from pos 13 (by decide),middle 13 (by decide) (by decide)]
+ have x := fields.headerFields 13 (by decide) (by decide) (by decide)
+ change src (H+13) = ((rowBase+Aₜ.rowWords B.recordLimit : ℕ) : Word w) at x
+ exact x.trans (congrArg (fun d : ℕ => ((rowBase+d : ℕ) : Word w)) liveRows)
+ have totalValue : FinalBits.Worker.total pub mid = ((Y).totalWidth : Word w) := by
+ change mid (header pub+12).val = _
+ rw [show (header pub+12).val = H+12 from pos 12 (by decide),middle 12 (by decide) (by decide)]
+ exact Fin.ext (fields.total.trans (Nat.mod_eq_of_lt totalFit).symm)
+ have bitEnd : rowBase+rowsSize+(Y).totalWidth ≤ (header pub).val := by
+ rw [hv]; change endAddress L+rowsSize+(Y).totalWidth ≤ TerminalBootstrap.address (L).base r; omega
+ have layout := FinalBits.Worker.Layout.ofBelow baseValue totalValue bitEnd headFit
+ have self : SourceTransport.Agree (workerCell (header pub)) mid mid := fun _ _ => rfl
+ let bitPaths := SharedBitPhase.equiv (L).shape B.recordLimit segments pub cap mid mid layout
+ (by omega) headFit bitEnd self
+ refine ⟨q,bitPaths,hboot,hpref,hrows,layout,fun bits => ⟨rfl,?_⟩⟩
+ let vertex := (bitPaths bits).val.memory
+ have layers := selected_layers B f hf T hT X z
+ have rows' : AllRows w mid B.recordLimit rowBase rowBase ((tags).map TaggedLayer.layer) := layers ▸ rows
+ obtain ⟨run,vr,vt,wire,lv,hvtx⟩ := TerminalLayout.linked_vertexMemory bank rfl pub mid mid cap
+ B.recordLimit rowBase (Y).totalWidth (tags) bits (layers ▸ selected_capacity B f hf T hT X z)
+ (layers ▸ layout) headFit (by rw [hv,layers]; exact below) (by omega) valid self rows' (layers ▸ roles)
+ have tableEnd : tableBase L last tab + tableWords L ≤ endAddress L :=
+ (tableEnd_le_nextLevel L last tab).trans (levelStart_mono L hl)
+ have tableFit : tableBase L last tab < 2^w := by
+ change endAddress L ≤ H at above
+ omega
+ have pointer : (tableBase L last tab : Word w).val = tableBase L last tab := Nat.mod_eq_of_lt tableFit
+ have beforeHeader : (tableBase L last tab : Word w).val + arcCount (Y) ≤ (header pub).val := by
+ rw [pointer,hv]; change endAddress L ≤ H at above; omega
+ have offsetCells := (start.physical_readback headFit beforeHeader).2.2
+ have frame (x : ℕ) (hx : x < rowBase) : vertex x = src x := (lv x hx).trans (low x hx)
+ have head (j : ℕ) (hj : 0 < j) (hj' : j < 31) : vertex (H+j) = src (H+j) := by
+ exact (pos j (by omega) ▸ hvtx j hj hj').trans (high j hj hj')
+ have sameHeads (j : ℕ) (hj : j ∈ terminalScalars) : vertex (H+j) = src (H+j) := by
+ simp only [terminalScalars,Finset.mem_insert,Finset.mem_singleton] at hj
+ exact head j (by omega) (by omega)
+ have lower (i : Fin (vs).length) : levelsBase L ≤ ((ds i).pub 1).val := by
+ change levelsBase L ≤ ((residentData.choose i).pub 1).val
+ rw [residentData.choose_spec.1 i]
+ exact history.lower i
+ have vertexDirs := move_directories B f hf T hT X z ds residentFields lower heads frame sameHeads
+ refine ⟨?_,run.valid _ rfl,layers ▸ vr,layers ▸ vt,layers ▸ wire,
+ ?_,?_,?_,?_,?_⟩
+ · rw [hv]
+ exact vertexDirs
+ · intro i
+ have hi := i.isLt
+ have bound : tableBase L last tab+i.val < rowBase := by change _ < endAddress L; omega
+ exact (congrArg Fin.val (frame _ bound)).trans (pointer ▸ offsetCells i)
+ · intro x hx hs
+ exact (frame x hx).trans (fields.tableFrame x (hx.trans_le above) hs)
+ · intro j hj hn hm
+ rw [hv]
+ exact (head j.val hj (by have := j.isLt; omega)).trans (fields.headerFields j hj hn hm)
+ · rw [hv]
+ exact (congrArg Fin.val (head 12 (by decide) (by decide))).trans fields.total
+ · rw [hv]
+ exact (head 14 (by decide) (by decide)).trans (fields.offset.trans
+ (congrArg (fun d : ℕ => ((d+(Y).totalWidth : ℕ) : Word w)) liveRows))
+
+/-- The same selected parser snapshots that were recorded by the detailed
+calendar are available in every physical vertex-entry memory. -/
+theorem packed_detailed_prefix (data : SelectedPayloadHistory.Data (w := w) B f hf)
+ (segments : VertexImage.Part → VertexImage.Segment) (r cap : ℕ) (m phy : Memory w)
+ (boundary : ScheduledTrace.Boundary
+ (DetailedResident.resident B f hf ⟨leafLayer (siteOrder X), .cursor⟩ L (endAddress L) inputN saved data)
+ pub (levelWords L : Word w) (directoryRows L) (directoryRows L) (vs) (Y) m)
+ (handoff : SourceTransport.Agree ((pub 2).val+6 ≤ ·) m phy)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ (L).base+2^r*2^r)
+ (room : (L).base+2^r*2^r ≤ 2^w)
+ (below : endAddress L + 2*rowsSize + (Y).totalWidth ≤ TerminalBootstrap.address (L).base r)
+ (ordinal : 2*(tags).length*(X.positions+1) < 2^w)
+ (slots : arcCount (Y) ≤ slotCapacity L) (cells : arcCount (Y) ≤ tableWords L)
+ (totalFit : (Y).totalWidth < 2^w)
+ (clock₀ : TerminalBootstrap.cost (L).shape B.recordLimit+1+30 ≤ cap) (clock₁ : 60 ≤ cap)
+ (clock₂ : TraversalController.callFuel B.recordLimit+30 ≤ cap) :
+ let bank := workers (L).shape B.recordLimit segments
+ ∃ q : QuietPrefix bank pub cap phy, ∃ bitPaths : (Fin (Y).totalWidth → Bool) ≃ q.BitPaths,
+ q.boot.val.choices = [[]] ∧
+ q.prefixRows.val.choices = List.replicate (arcCount (Y)+1) [] ∧
+ q.traversalRows.val.choices =
+ List.replicate (2*((ls).map Layer.count).sum+2*(tags).length+1) [] ∧
+ FinalBits.Worker.Layout pub q.traversalRows.val.memory (endAddress L+rowsSize) (Y).totalWidth ∧
+ ∀ bits, (bitPaths bits).val.choices = FinalBits.calls bits ++ [[]] ∧
+ VertexEntry B f hf T hT X z L tab baseBits laneBits pub phy (bitPaths bits).val.memory bits ∧
+ SelectedPayloadHistory.Past B f hf L data (vs) (bitPaths bits).val.memory := by
+ obtain ⟨q,paths,h₀,h₁,h₂,layout,each⟩ := packed_prefix B f hf T hT X z positions baseBits
+ laneBits initialWidth inputN pub segments r cap m phy (DetailedResident.currentBoundary boundary)
+ handoff exp hr reserve room below ordinal slots cells totalFit clock₀ clock₁ clock₂
+ have hl : last < (L).levels := by
+ rw [TerminalBootstrap.selected_prior_length,BlockProgram.actual_level_count,Nat.mul_comm T]; omega
+ have past : SelectedPayloadHistory.Past B f hf L data (vs) phy := by
+ apply (DetailedResident.payloads boundary.stored).transfer
+ intro x lower _
+ have low : (pub 2).val+6 ≤ levelsBase L := by
+ unfold levelsBase directoryBase plannerTag frameBase
+ change (pub 2).val+6 ≤ (pub 2).val+9+_+1+_
+ omega
+ exact (handoff x (low.trans lower)).symm
+ exact ⟨q,paths,h₀,h₁,h₂,layout,fun bits =>
+ ⟨(each bits).1,(each bits).2,(each bits).2.payload B f hf T hT X z hl past⟩⟩
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPackedReplay.lean b/lean/OAI/Computability/VPVNP/PairTerminalPackedReplay.lean
new file mode 100644
index 0000000000..1f6b985b88
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPackedReplay.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.PairTerminalPackedPrefix
+import OAI.Computability.VPVNP.PairTerminalPreludeBudget
+import OAI.Computability.VPVNP.PairTerminalBootstrapReplay
+import OAI.Computability.VPVNP.PairTraversalLowReplay
+
+/-!
+# Low words throughout the physical deterministic terminal prefix
+
+The completed calendar supplies the retained inputs for all three native
+phases. Their per-report frames include the linked stage changes and the
+closing calls, and apply before any shared-bit or site choices are made.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TerminalPrefix TerminalPrefix.Linked TerminalLink
+open scoped Fin.CommRing
+
+variable {w lanes : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "rowsSize" => words B.recordLimit (ls)
+local notation "last" => List.length (List.dropLast (ls))
+
+variable (positions baseBits laneBits initialWidth inputN : ℕ) (pub : Fin 11 → Word w)
+set_option quotPrecheck false in
+local notation "L" => BlockProgram.layout B (pub 2).val positions T
+set_option quotPrecheck false in
+local notation "tab" => (⟨0,by change 0 < 6; decide⟩ : Fin (L).shape.tables)
+local notation "saved" => CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L))
+ (CursorRAM.encode w 1) baseBits laneBits (S.degreeExponent 0) initialWidth (incidenceStart L 0)
+
+/-- Every report in the three forced phases preserves words below the live workspace. -/
+theorem packed_prefix_frame (data : SelectedPayloadHistory.Data (w := w) B f hf)
+ (segments : VertexImage.Part → VertexImage.Segment) (r cap : ℕ) (m phy : Memory w)
+ (boundary : ScheduledTrace.Boundary
+ (DetailedResident.resident B f hf ⟨leafLayer (siteOrder X), .cursor⟩ L
+ (endAddress L) inputN saved data)
+ pub (levelWords L : Word w) (directoryRows L) (directoryRows L) (vs) (Y) m)
+ (handoff : SourceTransport.Agree ((pub 2).val + 6 ≤ ·) m phy)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ (L).base + 2 ^ r * 2 ^ r)
+ (room : (L).base + 2 ^ r * 2 ^ r ≤ 2 ^ w)
+ (below : endAddress L + 2 * rowsSize + (Y).totalWidth ≤ TerminalBootstrap.address (L).base r)
+ (ordinal : 2 * (tags).length * (X.positions + 1) < 2 ^ w)
+ (slots : arcCount (Y) ≤ slotCapacity L) (cells : arcCount (Y) ≤ tableWords L)
+ (totalFit : (Y).totalWidth < 2 ^ w)
+ (clock₀ : TerminalBootstrap.cost (L).shape B.recordLimit + 1 + 30 ≤ cap) (clock₁ : 60 ≤ cap)
+ (clock₂ : TraversalController.callFuel B.recordLimit + 30 ≤ cap)
+ (q : QuietPrefix (workers (L).shape B.recordLimit segments) pub cap phy)
+ (x : ℕ) (hx : x < (pub 2).val) : ReplayFrame x phy q.reportList := by
+ let boot := TerminalBootstrap.report (L).shape B.recordLimit pub 0 phy
+ have above : endAddress L ≤ TerminalBootstrap.address (L).base r := by omega
+ obtain ⟨⟨history⟩,ready,rs,start,_⟩ := run_boundary B f hf T hT X z positions baseBits laneBits
+ initialWidth inputN pub segments r cap m phy (DetailedResident.currentBoundary boundary)
+ handoff exp hr reserve room above slots cells totalFit clock₀ clock₁
+ let src := prefixMemory pub phy boot rs
+ let hdr := TerminalBootstrap.fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab
+ have wide : 28 ≤ (L).shape.scalarFields := by change 28 ≤ 54; decide
+ have hl : last < (L).levels := by
+ rw [TerminalBootstrap.selected_prior_length,BlockProgram.actual_level_count,Nat.mul_comm T]
+ omega
+ have fields := TraversalResidentHandoff.fields_of_start L last hl tab hdr B.recordLimit r (Y)
+ pub phy src ready exp hr reserve room above wide cells rs start start.handoff_rows.1
+ have retained := TraversalResidentHandoff.selected_resident B f hf T hT X z
+ L baseBits laneBits tab history fields hl wide
+ let ds := retained.choose
+ have stored := retained.choose_spec.2.1
+ have heads := retained.choose_spec.2.2
+ have head := q.force_start start clock₀ clock₁
+ have e : q.prefixRows.val.memory = src := head.2.2.2
+ have xbase : x < endAddress L := by
+ have first : (L).base ≤ endAddress L := by
+ simp only [endAddress,levelStart,levelsBase,directoryBase,plannerTag,frameBase]
+ omega
+ exact hx.trans_le first
+ have cand : Phase _ pub cap (.resume Stage.traversalRows 0) src
+ q.traversalRows.val.choices q.traversalRows.val.logs q.traversalRows.val.memory :=
+ (congrArg (fun m' => Phase _ pub cap (.resume Stage.traversalRows 0) m'
+ q.traversalRows.val.choices q.traversalRows.val.logs q.traversalRows.val.memory) e).mp
+ q.traversalRows.prop
+ have third := TraversalController.selected_linked_low_replay B f hf T hT X z
+ (endAddress L) src ds pub (Y).totalWidth (TerminalBootstrap.address (L).base r)
+ (levelStart L 0) (levelWords L) stored heads below ordinal
+ (workers (L).shape B.recordLimit segments) cap rfl clock₂ cand x xbase
+ apply q.replayFrame_packedStart L ⟨last,hl⟩ tab hdr B.recordLimit r cap (Y) phy rs
+ ready exp hr reserve room above slots start clock₀ clock₁ x hx
+ exact (congrArg (fun m' => ReplayFrame x m'
+ (reports (header pub) q.traversalRows.val.logs)) e).mpr third
+
+end PairSimulation.TerminalProgram
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TerminalPrefix TerminalLink CursorBounds CursorNetwork Filter
+open LiveProgram.PairStages.Group.CompressedPaths (publicWords fuel)
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+set_option exponentiation.threshold 10000 in
+/-- A common length threshold gives the entire chronological low-word frame
+for each selected descriptor path on the fixed live worker bank. -/
+theorem eventually_packed_prefix_frame (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hstart : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop, ∀ (G : LiveProgram.PairStages.Group)
+ (_ : G.w = wordBits b n) (_ : ((publicWords G) 2).val = start n)
+ (_ : ((publicWords G) 7).val = addressBits b n) (_ : n ^ 10000 ≤ G.clock)
+ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let L := BlockProgram.layout B ((publicWords G) 2).val X.positions T
+ let E := B.execute f hf T hT X
+ let cap := LiveProgram.CompressedPair.clockAt (publicWords G) (fuel G)
+ LiveProgram.CompressedPair.Stage.terminal
+ ∀ (z : E.Choices) (baseBits laneBits initialWidth inputN : ℕ)
+ (data : SelectedPayloadHistory.Data (w := G.w) B f hf)
+ (segments : VertexImage.Part → VertexImage.Segment) (m phy : Memory G.w),
+ let saved := CursorRAM.ScheduleInit.inputs (CursorRAM.encode G.w (directoryBase L))
+ (CursorRAM.encode G.w 1) baseBits laneBits (S.degreeExponent 0) initialWidth
+ (incidenceStart L 0)
+ ScheduledTrace.Boundary
+ (DetailedResident.resident B f hf ⟨leafLayer (siteOrder X), .cursor⟩ L
+ (endAddress L) inputN saved data)
+ (publicWords G) (levelWords L : Word G.w) (directoryRows L) (directoryRows L)
+ (executeLevels B f hf T hT X z) (E.finalState z) m →
+ SourceTransport.Agree (((publicWords G) 2).val + 6 ≤ ·) m phy →
+ ∀ q : QuietPrefix (workers (BlockProgram.allocationShape B) B.recordLimit segments)
+ (publicWords G) cap phy,
+ ∀ x < ((publicWords G) 2).val, ReplayFrame x phy q.reportList := by
+ filter_upwards [TerminalLayout.eventually_preludeRoom B u b hb hstart] with n fit
+ intro G hw baseWord exp clock base lanes labels hD hT A _ f hf X T L E cap z baseBits laneBits
+ initialWidth inputN data segments m phy saved boundary handoff
+ have geometry := fit labels hD hT A f hf z G clock
+ dsimp only at geometry
+ rw [← baseWord,← hw] at geometry
+ obtain ⟨hr,reserve,room,below,ordinal,slots,cells,totalFit,clock₀,clock₁,clock₂⟩ := geometry
+ have bank := TerminalLayout.packed_workers B ((publicWords G) 2).val X.positions T segments
+ change ∀ q : QuietPrefix (workers (BlockProgram.allocationShape B) B.recordLimit segments)
+ (publicWords G) cap phy, ∀ x < ((publicWords G) 2).val, ReplayFrame x phy q.reportList
+ rw [← bank]
+ exact packed_prefix_frame B f hf T hT X z X.positions baseBits laneBits initialWidth inputN
+ (publicWords G) data segments (addressBits b n) cap m phy boundary handoff exp hr reserve
+ room below ordinal slots cells totalFit clock₀ clock₁ clock₂
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPrefix.lean b/lean/OAI/Computability/VPVNP/PairTerminalPrefix.lean
new file mode 100644
index 0000000000..4b3d626d2c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPrefix.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.PairSimulationScanTrace
+import OAI.Computability.VPVNP.PairSimulationEndpointBits
+import OAI.Computability.VPVNP.CompressorSlicePreparation
+import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout
+
+/-!
+# Publishing final arc offsets and total bit width
+
+The terminal prefix worker reads the final state's outgoing widths in physical
+base, lane and slot order. The running total before each arc is precisely the
+offset expected by the endpoint reader. The accumulator after the last arc
+holds the exclusive end of the shared bit array, relative to its base.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalPrefix
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords Compression LocalHistory PrimedStackRAM
+open scoped Fin.CommRing
+open private actualWidth scanWidth scanWidth_sum from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+variable {a g w : ℕ}
+
+/-- The edge order used by both the terminal bit scan and the physical incidence directory. -/
+abbrev arcCount (X : State a g) := (edgeOrder X).length
+
+/-- Width of the final arc at this ordinal in the terminal prefix scan's physical order. -/
+def width (X : State a g) (i : Fin (arcCount X)) := scanWidth X i
+
+theorem width_sum (X : State a g) : ∑ i, width X i = X.totalWidth := scanWidth_sum X
+
+theorem actualPort_eq (X : State a g) (e : X.network.Edge) :
+ IncidenceDirectory.actualPort (w := w) X e =
+ (((edgeOrder X).entries.symm e).val : Word w) :=
+ IncidenceDirectory.actualPort_number X e
+
+/-- Three physical operands of the standard one-arc prefix worker. -/
+def operands (T : IncidenceDirectory w) (prefixBase totalCell : Word w) : Fin 3 → Word w :=
+ ![T.width, prefixBase, totalCell]
+
+/-- Prefix-sum instruction template for the terminal width array, entered with an initial zero
+running total. -/
+abbrev table := template SliceRAM.prefixOps 0
+
+private theorem take_sum {n : ℕ} (values : Fin n → ℕ) (j : Fin n) :
+ ((List.ofFn values).take j.val).sum = EndpointBits.offset values j := by
+ have h : (List.ofFn values).take j.val =
+ List.ofFn (fun i : Fin j.val => values (i.castLE j.isLt.le)) := by
+ apply List.ext_getElem
+ · simp [j.isLt.le]
+ · intro i hi hi'
+ simp
+ rw [h, List.sum_ofFn, EndpointBits.offset]
+
+/-- Every live start cell, the running total and the unchanged memory around the
+two output regions. These facts also apply to an empty final graph. -/
+structure Stored (X : State a g) (T : IncidenceDirectory w) (prefixBase totalCell : Word w)
+ (initial final : Memory w) : Prop where
+ start : ∀ i : Fin (arcCount X),
+ (final (prefixBase.val + i.val)).val = EndpointBits.offset (width X) i
+ total : (final totalCell.val).val = X.totalWidth
+ widths : ∀ i : Fin (arcCount X), (final (T.width.val + i.val)).val = width X i
+ outside : ∀ x, x ≠ totalCell.val →
+ (x < prefixBase.val ∨ prefixBase.val + arcCount X ≤ x) → final x = initial x
+
+private theorem width_cells (X : State a g) (T : IncidenceDirectory w) (m : Memory w)
+ (rep : T.ActualColumns X m) (room : T.width.val + arcCount X ≤ 2 ^ w)
+ (totalFit : X.totalWidth < 2 ^ w) (i : Fin (arcCount X)) :
+ (m (T.width.val + i.val)).val = width X i := by
+ let e := (edgeOrder X).entries i
+ have port : IncidenceDirectory.actualPort (w := w) X e = (i.val : Word w) := by
+ simp only [e, actualPort_eq, Equiv.symm_apply_apply]
+ have bound := Finset.single_le_sum (f := width X) (fun j _ => Nat.zero_le (width X j))
+ (Finset.mem_univ i)
+ have small : width X i < 2 ^ w := bound.trans_lt ((width_sum X).trans_lt totalFit)
+ have hv := congrArg Fin.val (rep.width e)
+ rw [port] at hv
+ have loc : (T.width + (i.val : Word w)).val = T.width.val + i.val := by
+ have hi := i.isLt
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : i.val < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega : T.width.val + i.val < 2 ^ w)]
+ rw [loc] at hv
+ exact hv.trans (Nat.mod_eq_of_lt small)
+
+/-- Execute one call per outgoing arc. The word-indexed incidence column is the
+source. The start and total cells are the only cells the execution can change. -/
+theorem run (X : State a g) (T : IncidenceDirectory w) (m : Memory w)
+ (rep : T.ActualColumns X m) (prefixBase totalCell : Word w)
+ (regions : SliceRAM.PrefixRegions (operands T prefixBase totalCell) (arcCount X))
+ (countFit : arcCount X < 2 ^ w) (totalFit : X.totalWidth < 2 ^ w)
+ (zero : m totalCell.val = 0) :
+ let M := table.instantiate w (operands T prefixBase totalCell)
+ ∃ rs, runSegment M.program 14 (some 0) m (List.replicate (arcCount X) []) = some rs ∧
+ Stored X T prefixBase totalCell m (after m (eventLog rs)) ∧
+ endState (some 0) rs = some (arcCount X : Word w) ∧ rs.length = arcCount X ∧
+ ∀ r ∈ rs, r.probes = 4 ∧ r.events.length = 13 := by
+ let pub := operands T prefixBase totalCell
+ let ws := List.ofFn (width X)
+ have hlen : ws.length = arcCount X := List.length_ofFn
+ have hsum : ws.sum = X.totalWidth := List.sum_ofFn.trans (width_sum X)
+ have values (i : ℕ) (hi : i < ws.length) : (m ((pub 0).val + i)).val = ws[i] := by
+ change (m (T.width.val + i)).val = _
+ simpa only [ws, List.getElem_ofFn] using width_cells X T m rep regions.widthsFit totalFit
+ ⟨i, hlen ▸ hi⟩
+ obtain ⟨rs, executed, filled, ended, calls, traffic⟩ := SliceRAM.prefixPass_run
+ (pub := pub) (ws := ws) (hlen ▸ regions) (hlen.trans_lt countFit) (hsum.trans_lt totalFit)
+ values (by rw [show pub 2 = totalCell from rfl, zero]; rfl)
+ refine ⟨rs, hlen ▸ executed, ⟨?_, ?_, ?_, ?_⟩, hlen ▸ ended, calls.trans hlen, ?_⟩
+ · intro i
+ exact (filled.starts i.val (i.isLt.trans_eq hlen.symm)).trans (take_sum (width X) i)
+ · change (after m (eventLog rs) (pub 2).val).val = _
+ simpa only [List.take_length, hsum] using filled.total
+ · intro i
+ change (after m (eventLog rs) ((pub 0).val + i.val)).val = _
+ simpa only [ws, List.getElem_ofFn] using filled.widths i.val (i.isLt.trans_eq hlen.symm)
+ · exact fun x hx outside => filled.outside x hx (hlen ▸ outside)
+ · intro r hr
+ obtain ⟨hp, ht⟩ := traffic r hr
+ exact ⟨hp, by omega⟩
+
+end PairSimulation.TerminalPrefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPrefixBudget.lean b/lean/OAI/Computability/VPVNP/PairTerminalPrefixBudget.lean
new file mode 100644
index 0000000000..46c66adb11
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPrefixBudget.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairTerminalPrefixSegment
+import OAI.Computability.VPVNP.CursorBranchCommunication
+import OAI.Computability.VPVNP.PairLinkSlack
+
+/-!
+# Communication budget of the live terminal-prefix worker
+
+The final outgoing directory has one entry for each slot of each final site.
+The prefix stage visits exactly those entries and makes one closing call.
+Including fixed linker costs on every call, these reports fit every positive
+fraction of the live group's communication allowance uniformly over branches.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalPrefix.Segment
+
+open Compression CursorNetwork CursorBounds Filter BurstRAM CompressorRecords LocalHistory
+
+/-- The physical outgoing-arc directory has one entry for each site and slot. -/
+theorem arc_count_positions {a g : ℕ} (Y : State a g) : arcCount Y = Y.positions * 2 ^ a := by
+ have sites := Fintype.card_congr (siteOrder Y).entries
+ rw [Fintype.card_fin] at sites
+ exact congrArg (· * 2 ^ a) sites
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+/-- A common size threshold gives both the per-burst allowances and the
+total charge bound, including the linker margin on the closing report. -/
+theorem eventually_budget (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) {ε : ℝ} (hε : 0 < ε)
+ (probeMargin : ℕ := 2) (tickMargin : ℕ := 47) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {bases lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin bases ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ let w := wordBits b n
+ ∀ (z : E.Choices) (pub : Fin 11 → Word w) (dir : IncidenceDirectory w)
+ (base : Word w) (m : Memory w) (rs : List (Report w)),
+ let Y := E.finalState z
+ Run pub Y dir base m rs →
+ arcCount Y = Y.positions * S.baseDegree ∧
+ (∀ r ∈ rs, 1 + r.probes + probeMargin ≤ liveBucket u.δ n ∧
+ r.events.length + tickMargin ≤ n) ∧
+ ((RAMBuckets.cost Report.probes rs + probeMargin * rs.length : ℕ) : ℝ) <
+ ε * (processorCount b n : ℝ) * liveBucket u.δ n := by
+ let C := (8 + probeMargin) * (S.baseDegree + 1)
+ filter_upwards [eventually_pairAccesses B u b hb C 0 hε,
+ eventually_pairBurstSlack u (8 + probeMargin), eventually_ge_atTop (29 + tickMargin)]
+ with n budget slack hn
+ intro bases lanes labels hD hT A _ f hf X T E w z pub dir base m rs Y run
+ have count : arcCount Y = Y.positions * S.baseDegree := arc_count_positions Y
+ have bucket : 8 + probeMargin ≤ liveBucket u.δ n := by
+ have hn₀ : 0 ≤ (n : ℝ) ^ (1 / 2 : ℝ) := Real.rpow_nonneg (Nat.cast_nonneg n) _
+ exact_mod_cast (le_add_of_nonneg_left hn₀).trans slack
+ refine ⟨count, fun r hr => ?_, ?_⟩
+ · obtain ⟨hp, ht⟩ := run.bounds r hr
+ omega
+ · let chain := E.termChain (B.records f hf T hT X) z
+ apply lt_of_le_of_lt _ (budget labels hD hT A f hf z).1
+ apply Nat.cast_le.mpr
+ change _ ≤ branchAccesses X Y chain C 0 n
+ rw [run.charge, run.calls, count, branchAccesses_eq]
+ apply le_trans _ (Nat.mul_le_mul_left C (show Y.positions ≤ _ by omega))
+ calc
+ _ ≤ (8 + probeMargin) * (Y.positions * S.baseDegree) +
+ (8 + probeMargin) * Y.positions := by
+ have close := Nat.le_mul_of_pos_right (8 + probeMargin) Y.positions_pos
+ rw [Nat.mul_add, Nat.mul_one, Nat.add_mul]
+ omega
+ _ = C * Y.positions := by dsimp [C]; ring
+
+end PairSimulation.TerminalPrefix.Segment
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPrefixLayout.lean b/lean/OAI/Computability/VPVNP/PairTerminalPrefixLayout.lean
new file mode 100644
index 0000000000..60f2ce8d8a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPrefixLayout.lean
@@ -0,0 +1,161 @@
+import OAI.Computability.VPVNP.PairTerminalPrefixSegment
+import OAI.Computability.VPVNP.PairTraversalTerminalBootstrap
+
+/-!
+# Terminal width scan in the actual descriptor workspace
+
+The last reserved level's packed width column precedes its prefix table.
+The high header contains the total and role offset, above every live table.
+The terminal bootstrap supplies the scan's operands and zero accumulator
+while preserving the actual incidence columns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalPrefix
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DescriptorSpace
+open scoped Fin.CommRing
+
+variable {w a g : ℕ}
+
+open private eval_high from OAI.Computability.VPVNP.PairTraversalTerminalBootstrap
+
+/-- The master link and the terminal bootstrap compute the same high header. -/
+theorem header_val (L : Layout) (pub : Fin 11 → Word w) (r : ℕ)
+ (workspace : (pub 2).val = L.base) (exp : (pub 7).val = r) (hr : r < w)
+ (reserve : 32 ≤ L.base + 2 ^ r * 2 ^ r) (room : L.base + 2 ^ r * 2 ^ r ≤ 2 ^ w) :
+ (Worker.header pub).val = TerminalBootstrap.address L.base r := by
+ have h : Worker.header pub = (TerminalBootstrap.address L.base r : Word w) :=
+ eval_high L pub (fun _ => 0) workspace 0 (by omega) r exp hr reserve
+ rw [h, Fin.val_natCast, Nat.mod_eq_of_lt]
+ unfold TerminalBootstrap.address
+ omega
+
+/-- The prefix table and high accumulator obey both the scalar scan's range
+conditions and the terminal worker's header separation conditions. -/
+theorem packed_layout (L : Layout) (last : Fin L.levels) (tab : Fin L.shape.tables)
+ (pub : Fin 11 → Word w) (n : ℕ) (cap : n ≤ slotCapacity L) (cells : n ≤ tableWords L)
+ (above : endAddress L ≤ (Worker.header pub).val)
+ (room : (Worker.header pub).val + 15 ≤ 2 ^ w) :
+ let T := packedIncidence L w last n
+ let start := (tableBase L last tab : Word w)
+ Segment.HeaderLayout pub T start n ∧
+ SliceRAM.PrefixRegions (operands T start (Worker.header pub + 12)) n := by
+ let H := (Worker.header pub).val
+ have ht := (Nat.add_le_add_left cells (tableBase L last tab)).trans
+ ((tableEnd_le_nextLevel L last tab).trans ((levelStart_mono L last.isLt).trans above))
+ obtain ⟨hw, _, hf⟩ := prefix_bounds L (w := w) last tab n H cap cells above (by omega)
+ have hp : (tableBase L last tab : Word w).val = tableBase L last tab :=
+ Nat.mod_eq_of_lt (by omega)
+ have htotal : (Worker.header pub + 12).val = H + 12 := by
+ change (H + 12 % (2 ^ w)) % (2 ^ w) = _
+ rw [Nat.mod_eq_of_lt (by omega : 12 < 2 ^ w), Nat.mod_eq_of_lt (by omega)]
+ have s : Segment.HeaderLayout pub (packedIncidence L w last n) (tableBase L last tab) n :=
+ ⟨room, Or.inl (by rw [hp]; exact ht), Or.inl (hw.trans ((Nat.le_add_right _ _).trans ht))⟩
+ refine ⟨s, ?_⟩
+ change SliceRAM.PrefixRegions ![_, (tableBase L last tab : Word w), Worker.header pub + 12] n
+ refine ⟨(hw.trans (Nat.le_add_right _ _)).trans hf.le, ?_, Or.inl ?_, Or.inr ?_, Or.inr ?_⟩
+ · change (tableBase L last tab : Word w).val + n ≤ _
+ rw [hp]
+ exact hf.le
+ · change _ ≤ (tableBase L last tab : Word w).val
+ rw [hp]
+ exact hw
+ · change _ ≤ (Worker.header pub + 12).val
+ rw [htotal]
+ exact (hw.trans ((Nat.le_add_right _ _).trans ht)).trans (Nat.le_add_right _ _)
+ · change (tableBase L last tab : Word w).val + n ≤ (Worker.header pub + 12).val
+ rw [hp, htotal]
+ exact ht.trans (Nat.le_add_right _ _)
+
+open private incidence_end_le from OAI.Computability.VPVNP.CompressorDescriptorSpace
+
+private theorem transfer_incidence (L : Layout) (last : Fin L.levels) (X : State a g)
+ (n : ℕ) (hn : n = arcCount X) (cap : n ≤ slotCapacity L) {H : ℕ}
+ (above : endAddress L ≤ H) (room : H < 2 ^ w) {m m' : Memory w}
+ (old : (packedIncidence L w last n).ActualColumns X m)
+ (before : ∀ x < H, m' x = m x) : (packedIncidence L w last n).ActualColumns X m' := by
+ let T := packedIncidence L w last n
+ have port (c : Fin 6) (e : X.network.Edge) :
+ (T.column c + IncidenceDirectory.actualPort X e).val < H := by
+ let i := (LocalHistory.edgeOrder X).entries.symm e
+ have index : i.val < n := hn ▸ i.isLt
+ have bounds := (incidence_bounds L last n cap c ⟨i.val, index⟩).2
+ have endLe : arrayBase L last ≤ endAddress L :=
+ (incidence_end_le L last).trans (levelStart_mono L last.isLt)
+ have small : incidenceBase L last n c + i.val < H := bounds.trans_le (endLe.trans above)
+ rw [packed_column, actualPort_eq]
+ change (incidenceBase L last n c % (2 ^ w) + i.val % (2 ^ w)) % (2 ^ w) < H
+ rw [Nat.mod_eq_of_lt (by omega : incidenceBase L last n c < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega : i.val < 2 ^ w), Nat.mod_eq_of_lt (small.trans room)]
+ exact small
+ exact ⟨fun e => (before _ (port 3 e)).trans (old.actualOut e),
+ fun e => (before _ (port 4 e)).trans (old.actualIn e),
+ fun e => (before _ (port 5 e)).trans (old.width e)⟩
+
+/-- Run the terminal bootstrap followed by the complete prefix worker stage on
+the same selected final state. The role offset and bit width are the actual
+traversal storage size and total width of that state. -/
+theorem run_after_bootstrap (L : Layout) (last : Fin L.levels) (tab : Fin L.shape.tables)
+ (A : TerminalBootstrap.Header L last) (cap r : ℕ) (pub : Fin 11 → Word w)
+ (s : Word w) (m : Memory w) (X : State a g)
+ (ready : TerminalBootstrap.Ready L last A pub m)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ L.base + 2 ^ r * 2 ^ r)
+ (room : L.base + 2 ^ r * 2 ^ r ≤ 2 ^ w)
+ (above : endAddress L ≤ TerminalBootstrap.address L.base r)
+ (nslots : A.sites * A.degree = arcCount X)
+ (wh : A.widthHead = incidenceBase L last (arcCount X) 5)
+ (sh : A.prefixBase = tableBase L last tab) (slots : arcCount X ≤ slotCapacity L)
+ (cells : arcCount X ≤ tableWords L) (totalFit : X.totalWidth < 2 ^ w)
+ (incidence : (packedIncidence L w last (arcCount X)).ActualColumns X m) :
+ let M := (TerminalBootstrap.table L.shape cap).instantiate w pub
+ let rep := TerminalBootstrap.report L.shape cap pub s m
+ let boot := after m rep.events
+ let T := packedIncidence L w last (arcCount X)
+ execute M.program (TerminalBootstrap.cost L.shape cap + 1) (M.program.start s) m [] =
+ some rep ∧ ∃ rs, Segment.Run pub X T (tableBase L last tab) boot rs ∧
+ after boot (eventLog rs) (Worker.header pub + 14).val =
+ ((A.rowWords cap + X.totalWidth : ℕ) : Word w) := by
+ let H := TerminalBootstrap.address L.base r
+ let boot := after m (TerminalBootstrap.report L.shape cap pub s m).events
+ have hv := header_val L pub r ready.workspace exp hr reserve room
+ have high : H + 32 ≤ 2 ^ w := by dsimp [H, TerminalBootstrap.address]; omega
+ obtain ⟨run, _, header, keep, _⟩ := TerminalBootstrap.native L last A cap pub m s
+ ready r exp hr reserve room
+ have fields (j : Fin 21) : boot (Worker.header pub + (j.val : Word w)).val =
+ TerminalBootstrap.values L last A cap pub m j := by
+ have hj := j.isLt
+ rw [Fin.val_add, hv, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : j.val < 2 ^ w),
+ Nat.mod_eq_of_lt (by change H + j.val < 2 ^ w; omega)]
+ exact header j
+ obtain ⟨layout, regions⟩ := packed_layout L last tab pub (arcCount X) slots cells
+ (hv ▸ above) (by rw [hv]; change H + 15 ≤ 2 ^ w; omega)
+ have rep := transfer_incidence L last X (arcCount X) rfl slots above
+ (by change H < 2 ^ w; omega) incidence (fun x hx => keep x (Or.inl hx))
+ have fit : arcCount X < 2 ^ w := by
+ have hb := regions.startsFit
+ have hh := layout.startsApart
+ rcases hh with hh | hh
+ · have hhead := layout.fits
+ omega
+ · have hhead := layout.fits
+ change (tableBase L last tab : Word w).val + arcCount X ≤ 2 ^ w at hb
+ omega
+ obtain ⟨rs, scan⟩ := Segment.run pub X _ (tableBase L last tab) boot rep layout regions fit
+ totalFit ((fields 8).trans (congrArg (fun n : ℕ => (n : Word w)) nslots))
+ ((fields 9).trans (congrArg (fun n : ℕ => (n : Word w)) wh))
+ ((fields 11).trans (congrArg (fun n : ℕ => (n : Word w)) sh)) (fields 12)
+ refine ⟨run, rs, scan, ?_⟩
+ exact scan.role.trans (by
+ unfold Segment.roleValue
+ rw [show boot (Worker.header pub + 5).val = (A.rowWords cap : Word w) from fields 5]
+ simp only [Nat.cast_add])
+
+end PairSimulation.TerminalPrefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPrefixLinked.lean b/lean/OAI/Computability/VPVNP/PairTerminalPrefixLinked.lean
new file mode 100644
index 0000000000..84d2baf1a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPrefixLinked.lean
@@ -0,0 +1,271 @@
+import OAI.Computability.VPVNP.PairTerminalPrefixLayout
+import OAI.Computability.VPVNP.PairTerminalStageReverse
+
+/-!
+# The first two stages of the linked terminal pair program
+
+The bootstrap runs directly on the calendar's physical output memory. Its
+accepting exit switches the controller to the prefix worker and resets the
+saved ordinal. The prefix worker's own reads avoid those two control words.
+Consequently its physical calls compute the same offsets, total width and
+role displacement as the standalone final-state scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalPrefix.Linked
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords TerminalLink
+open scoped Fin.CommRing
+open LiveProgram (PairTable)
+
+variable {w a g : ℕ}
+
+/-- Package the terminal bootstrap instructions as a pair worker for the given descriptor shape
+and record limit. -/
+abbrev bootstrapWorker (F : DescriptorSpace.Shape) (limit : ℕ) : PairTable :=
+ ⟨_, _, TerminalBootstrap.table F limit⟩
+
+/-- The linked pair worker that visits final arcs and publishes their exclusive width prefixes. -/
+abbrev prefixWorker : PairTable := ⟨_, _, Worker.table⟩
+
+/-- External memory after replaying the wrapped initial bootstrap report at the pair's terminal
+header. -/
+def bootMemory (pub : Fin 11 → Word w) (m : Memory w) (raw : Report w) : Memory w :=
+ after m (report (header pub) .initial raw).events
+
+/-- No read-transport condition is required at the initial call, which runs
+on exactly the input memory of the physical terminal table. -/
+theorem initial_oneShot (workers : Stage → PairTable) (pub : Fin 11 → Word w)
+ (f cap : ℕ) (m : Memory w) (raw : Report w) (fit : 32 ≤ 2 ^ w) (room : f + 30 ≤ cap)
+ (call : execute (source workers Stage.bootstrap pub) f
+ ((source workers Stage.bootstrap pub).start 0) m [] = some raw) (halt : raw.result = none) :
+ StageRun workers pub cap .initial m m [[]] [raw] := by
+ let e : Entry w := .initial
+ have nextEntry : e.follow raw = some (.resume Stage.prefixRows 0) := by
+ rw [Entry.follow, halt]
+ rfl
+ have nextHandoff : handoff (w := w) e.stage = some (.resume Stage.prefixRows 0) := rfl
+ have physical := call_of_room workers pub cap e m [] (by omega) trivial f raw call room
+ constructor
+ · change runSegment (program workers pub) cap (some e.marker) m [[]] =
+ some [report (header pub) e raw]
+ simp only [runSegment, physical, Option.map_some]
+ · change (report (header pub) e raw).result = (handoff e.stage).map Entry.marker
+ rw [report_result, nextEntry, nextHandoff]
+ · simp only [stageReports, eventLog, List.flatMap_cons, List.flatMap_nil, List.append_nil]
+ change SourceTransport.Agree (workerCell (header pub)) (after m raw.events)
+ (after m (report (header pub) e raw).events)
+ rw [report_after, show e.stage = Stage.bootstrap from rfl, halt]
+ intro j hj
+ change after m raw.events j = writeMemory (writeMemory (after m raw.events)
+ (header pub) (tagWord w Stage.prefixRows)) (header pub + 31) 0 j
+ simp only [writeMemory, ite_eq_right hj.1, ite_eq_right hj.2]
+ · intro t ht
+ change handoff e.stage = some t at ht
+ rw [nextHandoff] at ht
+ obtain rfl := Option.some.inj ht
+ simpa only [stageReports, eventLog, List.flatMap_cons, List.flatMap_nil, List.append_nil]
+ using next_valid (header pub) e _ raw m fit nextEntry
+
+/-- Standalone final-state reports run at the physical prefix entry, where only
+the stage and saved ordinal may differ from their standalone values. -/
+theorem prefix_stage (workers : Stage → PairTable) (bank : workers Stage.prefixRows = prefixWorker)
+ (pub : Fin 11 → Word w) (cap : ℕ) (X : State a g) (T : IncidenceDirectory w)
+ (base : Word w) (src phy : Memory w) (rs : List (Report w))
+ (scan : Segment.Run pub X T base src rs) (room : 60 ≤ cap)
+ (fits : (header pub).val + 32 ≤ 2 ^ w) (widths : T.width.val + arcCount X ≤ (header pub).val)
+ (starts : base.val + arcCount X ≤ (header pub).val)
+ (valid : (Entry.resume Stage.prefixRows (0 : Word w)).Valid (header pub) phy)
+ (agree : SourceTransport.Agree (workerCell (header pub)) src phy) :
+ StageRun workers pub cap (.resume Stage.prefixRows 0) src phy
+ (List.replicate (arcCount X + 1) []) rs := by
+ apply closed_stage_run workers pub 30 cap _ src phy _ rs (by omega) room valid agree
+ (scan.controller_frame fits widths starts).1
+ · change runSegment ((workers Stage.prefixRows).table.instantiate w pub).program 30
+ (some 0) src _ = some rs
+ rw [bank]
+ exact scan.native
+ · exact scan.halt
+
+/-- Both physical stage runs and their underlying source computations. -/
+structure Start (workers : Stage → PairTable) (pub : Fin 11 → Word w) (cap f : ℕ)
+ (X : State a g) (T : IncidenceDirectory w) (base : Word w) (m : Memory w)
+ (raw : Report w) (rs : List (Report w)) : Prop where
+ bootCall : execute (source workers Stage.bootstrap pub) f
+ ((source workers Stage.bootstrap pub).start 0) m [] = some raw
+ bootHalt : raw.result = none
+ rawScan : Segment.Run pub X T base (after m raw.events) rs
+ prefixBank : workers Stage.prefixRows = prefixWorker
+ reads : SourceTransport.Reads (workerCell (header pub)) (eventLog rs)
+ boot : StageRun workers pub cap .initial m m [[]] [raw]
+ scan : StageRun workers pub cap (.resume Stage.prefixRows 0) (after m raw.events)
+ (bootMemory pub m raw) (List.replicate (arcCount X + 1) []) rs
+
+/-- Compose the actual two workers into the terminal controller. -/
+theorem start (workers : Stage → PairTable) (bank : workers Stage.prefixRows = prefixWorker)
+ (pub : Fin 11 → Word w) (cap f : ℕ) (X : State a g) (T : IncidenceDirectory w)
+ (base : Word w) (m : Memory w) (raw : Report w) (rs : List (Report w))
+ (bootCall : execute (source workers Stage.bootstrap pub) f
+ ((source workers Stage.bootstrap pub).start 0) m [] = some raw) (bootHalt : raw.result = none)
+ (scan : Segment.Run pub X T base (after m raw.events) rs) (clock : f + 30 ≤ cap)
+ (room : 60 ≤ cap) (fits : (header pub).val + 32 ≤ 2 ^ w)
+ (widths : T.width.val + arcCount X ≤ (header pub).val)
+ (starts : base.val + arcCount X ≤ (header pub).val) :
+ Start workers pub cap f X T base m raw rs := by
+ have boot := initial_oneShot workers pub f cap m raw (by omega) clock bootCall bootHalt
+ have valid : (Entry.resume Stage.prefixRows (0 : Word w)).Valid (header pub)
+ (bootMemory pub m raw) := by
+ simpa only [bootMemory, stageReports, eventLog, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil]
+ using boot.valid (.resume Stage.prefixRows 0) rfl
+ have agree : SourceTransport.Agree (workerCell (header pub)) (after m raw.events)
+ (bootMemory pub m raw) := by
+ simpa only [bootMemory, stageReports, eventLog, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil]
+ using boot.agree
+ exact ⟨bootCall, bootHalt, scan, bank, (scan.controller_frame fits widths starts).1, boot,
+ prefix_stage workers bank pub cap X T base (after m raw.events) (bootMemory pub m raw) rs
+ scan room fits widths starts valid agree⟩
+
+open DescriptorSpace
+
+/-- The bootstrap and prefix stage of the actual packed terminal workspace.
+The physical memory on exit agrees with the raw scan outside the controller's
+phase and saved-state cells, and is a valid entry to traversal-row construction. -/
+theorem run_packed (workers : Stage → PairTable) (L : Layout) (last : Fin L.levels)
+ (tab : Fin L.shape.tables) (A : TerminalBootstrap.Header L last) (limit r cap : ℕ)
+ (bank₀ : workers Stage.bootstrap = bootstrapWorker L.shape limit)
+ (bank₁ : workers Stage.prefixRows = prefixWorker) (pub : Fin 11 → Word w)
+ (m : Memory w) (X : State a g) (ready : TerminalBootstrap.Ready L last A pub m)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ L.base + 2 ^ r * 2 ^ r)
+ (room : L.base + 2 ^ r * 2 ^ r ≤ 2 ^ w)
+ (above : endAddress L ≤ TerminalBootstrap.address L.base r)
+ (nslots : A.sites * A.degree = arcCount X)
+ (wh : A.widthHead = incidenceBase L last (arcCount X) 5)
+ (sh : A.prefixBase = tableBase L last tab) (slots : arcCount X ≤ slotCapacity L)
+ (cells : arcCount X ≤ tableWords L) (totalFit : X.totalWidth < 2 ^ w)
+ (incidence : (packedIncidence L w last (arcCount X)).ActualColumns X m)
+ (clock₀ : TerminalBootstrap.cost L.shape limit + 1 + 30 ≤ cap) (clock₁ : 60 ≤ cap) :
+ let raw := TerminalBootstrap.report L.shape limit pub 0 m
+ let T := packedIncidence L w last (arcCount X)
+ let f := TerminalBootstrap.cost L.shape limit + 1
+ ∃ rs, Start workers pub cap f X T (tableBase L last tab) m raw rs ∧
+ after (after m raw.events) (eventLog rs) (header pub + 14).val =
+ ((A.rowWords limit + X.totalWidth : ℕ) : Word w) := by
+ let raw := TerminalBootstrap.report L.shape limit pub 0 m
+ let T := packedIncidence L w last (arcCount X)
+ let f := TerminalBootstrap.cost L.shape limit + 1
+ obtain ⟨boot, rs, scan, role⟩ := run_after_bootstrap L last tab A limit r pub 0 m X
+ ready exp hr reserve room above nslots wh sh slots cells totalFit incidence
+ have call : execute (source workers Stage.bootstrap pub) f
+ ((source workers Stage.bootstrap pub).start 0) m [] = some raw := by
+ unfold source
+ rw [bank₀]
+ exact boot
+ have hv := header_val L pub r ready.workspace exp hr reserve room
+ have fits : (header pub).val + 32 ≤ 2 ^ w := by
+ rw [hv, TerminalBootstrap.address]
+ omega
+ have ht : tableBase L last tab + arcCount X ≤ (header pub).val :=
+ (Nat.add_le_add_left cells _).trans ((tableEnd_le_nextLevel L last tab).trans
+ ((levelStart_mono L last.isLt).trans (above.trans_eq hv.symm)))
+ have baseVal : ((tableBase L last tab : ℕ) : Word w).val = tableBase L last tab :=
+ Nat.mod_eq_of_lt (by omega)
+ have widths : T.width.val + arcCount X ≤ (header pub).val :=
+ (prefix_bounds L (w := w) last tab (arcCount X) (header pub).val slots cells
+ (above.trans_eq hv.symm) (by omega)).1.trans
+ ((Nat.le_add_right _ _).trans ht)
+ have starts : ((tableBase L last tab : ℕ) : Word w).val + arcCount X ≤ (header pub).val := by
+ rw [baseVal]
+ exact ht
+ exact ⟨rs, start workers bank₁ pub cap f X T _ m raw rs call rfl scan clock₀ clock₁ fits
+ widths starts, role⟩
+
+variable {workers : Stage → PairTable} {pub : Fin 11 → Word w} {cap f : ℕ}
+variable {X : State a g} {T : IncidenceDirectory w} {base : Word w}
+variable {m : Memory w} {raw : Report w} {rs : List (Report w)}
+
+/-- The exact physical state after both deterministic stages. -/
+def prefixMemory (pub : Fin 11 → Word w) (m : Memory w) (raw : Report w)
+ (rs : List (Report w)) : Memory w :=
+ after (bootMemory pub m raw)
+ (eventLog (stageReports (header pub) (.resume Stage.prefixRows 0) rs))
+
+theorem Start.handoff_rows (s : Start workers pub cap f X T base m raw rs) :
+ SourceTransport.Agree (workerCell (header pub)) (after (after m raw.events) (eventLog rs))
+ (prefixMemory pub m raw rs) ∧
+ (Entry.resume Stage.traversalRows (0 : Word w)).Valid (header pub)
+ (prefixMemory pub m raw rs) :=
+ ⟨s.scan.agree, s.scan.valid _ rfl⟩
+
+/-- The two canonical forward phases can be inserted directly in a five-stage trace. -/
+theorem Start.phases (s : Start workers pub cap f X T base m raw rs)
+ (clock₀ : f + 30 ≤ cap) (clock₁ : 60 ≤ cap) :
+ Phase workers pub cap .initial m [[]] [(.initial, raw)] (bootMemory pub m raw) ∧
+ Phase workers pub cap (.resume Stage.prefixRows 0) (bootMemory pub m raw)
+ (List.replicate (arcCount X + 1) []) (stageLogs (.resume Stage.prefixRows 0) rs)
+ (prefixMemory pub m raw rs) := by
+ refine ⟨initial_phase workers pub f cap m raw clock₀ s.bootCall s.bootHalt, ?_⟩
+ have agree : SourceTransport.Agree (workerCell (header pub)) (after m raw.events)
+ (bootMemory pub m raw) := by
+ simpa only [bootMemory, stageReports, eventLog, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil] using s.boot.agree
+ apply Phase.of_source_segment (workers := workers) (e := .resume Stage.prefixRows 0)
+ (f := 30) clock₁ agree s.reads _ s.rawScan.halt
+ change runSegment ((workers Stage.prefixRows).table.instantiate w pub).program 30
+ (some 0) (after m raw.events) _ = some rs
+ rw [s.prefixBank]
+ exact s.rawScan.native
+
+/-- An arbitrary accepted trace has the canonical empty tapes, exact tagged
+worker reports, and exact physical output memory at both early stage boundaries. -/
+theorem Start.force (s : Start workers pub cap f X T base m raw rs)
+ (t : FiveTrace workers pub cap m) :
+ t.bootstrap.choices = [[]] ∧ t.bootstrap.logs = [(.initial, raw)] ∧
+ t.bootstrap.memory = bootMemory pub m raw ∧
+ t.prefixRows.choices = List.replicate (arcCount X + 1) [] ∧
+ t.prefixRows.logs = stageLogs (.resume Stage.prefixRows 0) rs ∧
+ t.prefixRows.memory = prefixMemory pub m raw rs := by
+ apply t.canonical_start s.bootCall s.bootHalt (g := 30) _ s.rawScan.halt s.reads
+ change runSegment ((workers Stage.prefixRows).table.instantiate w pub).program 30
+ (some 0) (after m raw.events) _ = some rs
+ rw [s.prefixBank]
+ exact s.rawScan.native
+
+/-- Read the exclusive total, the role displacement, and every arc offset
+from the physical memory that is actually handed to the traversal-row stage. -/
+theorem Start.physical_readback (s : Start workers pub cap f X T base m raw rs)
+ (fits : (header pub).val + 32 ≤ 2 ^ w) (below : base.val + arcCount X ≤ (header pub).val) :
+ let out := prefixMemory pub m raw rs
+ (out (header pub + 12).val).val = X.totalWidth ∧
+ out (header pub + 14).val = Segment.roleValue pub X (after m raw.events) ∧
+ ∀ i : Fin (arcCount X), (out (base.val + i.val)).val = EndpointBits.offset (width X) i := by
+ have pos (j : ℕ) (hj : j < 32) :
+ (header pub + (j : Word w)).val = (header pub).val + j := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : j < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega)]
+ have saved : (header pub + 31).val = (header pub).val + 31 := pos 31 (by decide)
+ have away (j : ℕ) (hj : 0 < j) (hs : j < 31) : workerCell (header pub)
+ (header pub + (j : Word w)).val := by
+ unfold workerCell
+ rw [pos j (by omega), saved]
+ omega
+ have agree := s.handoff_rows.1
+ refine ⟨(congrArg Fin.val (agree _ (away 12 (by decide) (by decide))).symm).trans
+ s.rawScan.stored.total, (agree _ (away 14 (by decide) (by decide))).symm.trans s.rawScan.role,
+ fun i => ?_⟩
+ have idx : workerCell (header pub) (base.val + i.val) := by
+ have hi := i.isLt
+ unfold workerCell
+ rw [saved]
+ omega
+ exact (congrArg Fin.val (agree _ idx).symm).trans (s.rawScan.stored.start i)
+
+end PairSimulation.TerminalPrefix.Linked
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPrefixSegment.lean b/lean/OAI/Computability/VPVNP/PairTerminalPrefixSegment.lean
new file mode 100644
index 0000000000..1eebcbc22c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPrefixSegment.lean
@@ -0,0 +1,443 @@
+import OAI.Computability.VPVNP.CompressorSliceAdjacency
+import OAI.Computability.VPVNP.PairTerminalPrefixWorker
+import OAI.Computability.VPVNP.LiveHeaderUnique
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-!
+# Execution of the live terminal-prefix pass
+
+The width and start pointers and the arc count are reloaded from the terminal
+header on each reset-entry call. The scan leaves them intact. When the cursor
+reaches the stored count, the closing call writes the descriptor displacement
+plus the accumulated bit width to the role-offset cell.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalPrefix.Segment
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords Compression
+open scoped Fin.CommRing
+
+variable {w a g : ℕ}
+
+/-- The header words used by the prefix stage fit in memory. The two arc arrays
+are disjoint from these header words. -/
+structure HeaderLayout (pub : Fin 11 → Word w) (T : IncidenceDirectory w)
+ (base : Word w) (n : ℕ) : Prop where
+ fits : (Worker.header pub).val + 15 ≤ 2 ^ w
+ startsApart : base.val + n ≤ (Worker.header pub).val ∨ (Worker.header pub).val + 15 ≤ base.val
+ widthsApart : T.width.val + n ≤ (Worker.header pub).val ∨
+ (Worker.header pub).val + 15 ≤ T.width.val
+
+private theorem header_addr {h : Word w} {j : ℕ} (fit : h.val + 15 ≤ 2 ^ w) (hj : j < 15) :
+ (h + (j : Word w)).val = h.val + j := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : j < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega)]
+
+/-- The active width and start intervals and the live header words used by this
+stage. This set bounds all external probes before any disjointness condition
+on the controller's own cells is imposed. -/
+def probeRegion (pub : Fin 11 → Word w) (T : IncidenceDirectory w) (base : Word w)
+ (n x : ℕ) : Prop :=
+ ((Worker.header pub).val + 5 ≤ x ∧ x < (Worker.header pub).val + 15) ∨
+ (T.width.val ≤ x ∧ x < T.width.val + n) ∨ (base.val ≤ x ∧ x < base.val + n)
+
+/-- Read and write addresses of a report are both in the stage's data region. -/
+def footprint (pub : Fin 11 → Word w) (T : IncidenceDirectory w) (base : Word w)
+ (n : ℕ) (r : Report w) : Prop :=
+ SourceTransport.Reads (probeRegion pub T base n) r.events ∧
+ SourceTransport.Writes (probeRegion pub T base n) r.events
+
+open private pre read from OAI.Computability.VPVNP.PairTerminalPrefixWorker
+
+private theorem read_eq (m : Memory w) (a : Word w) :
+ (read m a : Event w) = .read a (m a.val) := rfl
+
+private theorem active_footprint {pub : Fin 11 → Word w} {T : IncidenceDirectory w} {base : Word w}
+ {n : ℕ} (layout : HeaderLayout pub T base n)
+ (regions : SliceRAM.PrefixRegions (operands T base (Worker.header pub + 12)) n)
+ {i : Word w} (hi : i.val < n) (m : Memory w)
+ (widthHead : m (Worker.header pub + 9).val = T.width)
+ (startHead : m (Worker.header pub + 11).val = base) :
+ footprint pub T base n (Worker.activeReport pub i m) := by
+ have header (j : ℕ) (hlo : 5 ≤ j) (hhi : j < 15) :
+ probeRegion pub T base n (Worker.header pub + (j : Word w)).val := by
+ left
+ rw [header_addr layout.fits hhi]
+ omega
+ have widths : probeRegion pub T base n (T.width + i).val := by
+ right; left
+ have hfit : T.width.val + n ≤ 2 ^ w := regions.widthsFit
+ rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ omega
+ have starts : probeRegion pub T base n (base + i).val := by
+ right; right
+ have hfit : base.val + n ≤ 2 ^ w := regions.startsFit
+ rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)]
+ omega
+ constructor <;> intro a v mem
+ · simp only [Worker.activeReport, pre, read_eq, List.mem_append, List.mem_replicate,
+ List.mem_cons, List.not_mem_nil, Event.read.injEq, reduceCtorEq, and_false, false_or,
+ or_false] at mem
+ rcases mem with ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩
+ · exact header 8 (by decide) (by decide)
+ · exact header 9 (by decide) (by decide)
+ · rwa [widthHead]
+ · exact header 11 (by decide) (by decide)
+ · exact header 12 (by decide) (by decide)
+ · simp only [Worker.activeReport, pre, read_eq, List.mem_append, List.mem_replicate,
+ List.mem_cons, List.not_mem_nil, Event.write.injEq, reduceCtorEq, and_false, false_or,
+ or_false] at mem
+ rcases mem with ⟨rfl, _⟩ | ⟨rfl, _⟩
+ · rwa [startHead]
+ · exact header 12 (by decide) (by decide)
+
+private theorem close_footprint {pub : Fin 11 → Word w} {T : IncidenceDirectory w} {base : Word w}
+ {n : ℕ} (layout : HeaderLayout pub T base n) (i : Word w) (m : Memory w) :
+ footprint pub T base n (Worker.closeReport pub i m) := by
+ have header (j : ℕ) (hlo : 5 ≤ j) (hhi : j < 15) :
+ probeRegion pub T base n (Worker.header pub + (j : Word w)).val := by
+ left
+ rw [header_addr layout.fits hhi]
+ omega
+ constructor <;> intro a v mem
+ · simp only [Worker.closeReport, pre, read_eq, List.mem_append, List.mem_replicate,
+ List.mem_cons, List.not_mem_nil, Event.read.injEq, reduceCtorEq, and_false, false_or,
+ or_false] at mem
+ rcases mem with ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩
+ · exact header 8 (by decide) (by decide)
+ · exact header 5 (by decide) (by decide)
+ · exact header 12 (by decide) (by decide)
+ · simp only [Worker.closeReport, pre, read_eq, List.mem_append, List.mem_replicate,
+ List.mem_cons, List.not_mem_nil, Event.write.injEq, reduceCtorEq, and_false, false_or,
+ or_false] at mem
+ obtain ⟨rfl, _⟩ := mem
+ exact header 14 (by decide) (by decide)
+
+open private prefixAt_step from OAI.Computability.VPVNP.CompressorSlicePrefix
+
+private theorem header_read {pub : Fin 11 → Word w} {T : IncidenceDirectory w} {base : Word w}
+ {ws : List ℕ} (layout : HeaderLayout pub T base ws.length) {k : ℕ} (hk : k ≤ ws.length)
+ {initial m : Memory w}
+ (h : SliceRAM.PrefixAt (operands T base (Worker.header pub + 12)) ws initial m k)
+ (j : ℕ) (hj : j < 15) (hn : j ≠ 12) :
+ m (Worker.header pub + (j : Word w)).val = initial (Worker.header pub + (j : Word w)).val := by
+ apply h.outside
+ · change _ ≠ (Worker.header pub + 12).val
+ have ht : (Worker.header pub + 12).val = (Worker.header pub).val + 12 := by
+ simpa only [Nat.cast_ofNat] using header_addr (j := 12) layout.fits (by decide)
+ rw [header_addr layout.fits hj, ht]
+ omega
+ · change _ < base.val ∨ base.val + k ≤ _
+ rw [header_addr layout.fits hj]
+ have := layout.startsApart
+ omega
+
+/-- Run any remaining portion of the active scan. Its memory invariant is the
+one for the three-operand width scan, although the eleven-operand table obtains
+the pointer values through external probes on every call. -/
+private theorem active_from (pub : Fin 11 → Word w) (T : IncidenceDirectory w) (base : Word w)
+ (ws : List ℕ) (initial : Memory w) (layout : HeaderLayout pub T base ws.length)
+ (regions : SliceRAM.PrefixRegions (operands T base (Worker.header pub + 12)) ws.length)
+ (countFit : ws.length < 2 ^ w) (sumFit : ws.sum < 2 ^ w)
+ (count : initial (Worker.header pub + 8).val = (ws.length : Word w))
+ (widthHead : initial (Worker.header pub + 9).val = T.width)
+ (startHead : initial (Worker.header pub + 11).val = base)
+ {k : ℕ} {m : Memory w}
+ (progress : SliceRAM.PrefixAt (operands T base (Worker.header pub + 12)) ws initial m k)
+ (steps : ℕ) (bound : k + steps ≤ ws.length) :
+ let P := (Worker.table.instantiate w pub).program
+ ∃ rs, runSegment P 30 (some (k : Word w)) m (List.replicate steps []) = some rs ∧
+ SliceRAM.PrefixAt (operands T base (Worker.header pub + 12)) ws initial
+ (after m (eventLog rs)) (k + steps) ∧
+ endState (some (k : Word w)) rs = some ((k + steps : ℕ) : Word w) ∧
+ rs.length = steps ∧ ∀ r ∈ rs, (r.probes = 7 ∧ r.events.length = 29) ∧
+ footprint pub T base ws.length r := by
+ dsimp only
+ induction steps generalizing k m with
+ | zero => exact ⟨[], rfl, progress, rfl, rfl, by simp⟩
+ | succ steps ih =>
+ have same := header_read layout (k := k) (by omega) progress
+ have hd : Worker.data pub m = operands T base (Worker.header pub + 12) := by
+ funext j
+ fin_cases j
+ · exact (same 9 (by decide) (by decide)).trans widthHead
+ · exact (same 11 (by decide) (by decide)).trans startHead
+ · rfl
+ have hcount : m (Worker.header pub + 8).val = (ws.length : Word w) :=
+ (same 8 (by decide) (by decide)).trans count
+ have hval : (k : Word w).val = k := Nat.mod_eq_of_lt (by omega)
+ have active : (k : Word w) ≠ m (Worker.header pub + 8).val := by
+ rw [hcount]
+ intro he
+ have := congrArg Fin.val he
+ rw [hval, Fin.val_natCast, Nat.mod_eq_of_lt countFit] at this
+ omega
+ let rep := Worker.activeReport pub (k : Word w) m
+ have stepped := prefixAt_step regions sumFit (i := (k : Word w)) (by omega) (hval ▸ progress)
+ rw [hval, ← hd, ← Worker.active_image] at stepped
+ have next : SliceRAM.PrefixAt (operands T base (Worker.header pub + 12)) ws initial
+ (after m rep.events) (k + 1) := by rwa [hd] at stepped
+ obtain ⟨rs, run, filled, ended, calls, cost⟩ := ih next (by omega)
+ refine ⟨rep :: rs, ?_, ?_, ?_, by simp [calls], ?_⟩
+ · rw [List.replicate_succ, runSegment, Worker.active pub _ m active]
+ simp only [Worker.active_result, ← Nat.cast_one (R := Word w), ← Nat.cast_add]
+ rw [show runSegment (Worker.table.instantiate w pub).program 30 (some ((k + 1 : ℕ) : Word w))
+ (after m rep.events) (List.replicate steps []) = some rs from run]
+ rfl
+ · rw [show after m (eventLog (rep :: rs)) = after (after m rep.events) (eventLog rs)
+ from List.foldl_append, show k + (steps + 1) = k + 1 + steps by omega]
+ exact filled
+ · change endState (some ((k : Word w) + 1)) rs = _
+ simpa only [Nat.cast_add, Nat.cast_one, show k + (steps + 1) = k + 1 + steps by omega]
+ using ended
+ · intro r hr
+ rcases List.mem_cons.mp hr with rfl | hr
+ · refine ⟨Worker.active_cost .., active_footprint layout regions (by omega) m ?_ ?_⟩
+ · exact (same 9 (by decide) (by decide)).trans widthHead
+ · exact (same 11 (by decide) (by decide)).trans startHead
+ · exact cost r hr
+
+open private width_cells take_sum from OAI.Computability.VPVNP.PairTerminalPrefix
+
+/-- The native scan returns the arc count as its persistent state. Its last
+accumulator and its stored starts have their exact natural-number values. -/
+theorem run_active (pub : Fin 11 → Word w) (X : State a g) (T : IncidenceDirectory w)
+ (base : Word w) (m : Memory w) (rep : T.ActualColumns X m)
+ (layout : HeaderLayout pub T base (arcCount X))
+ (regions : SliceRAM.PrefixRegions (operands T base (Worker.header pub + 12)) (arcCount X))
+ (countFit : arcCount X < 2 ^ w) (totalFit : X.totalWidth < 2 ^ w)
+ (count : m (Worker.header pub + 8).val = (arcCount X : Word w))
+ (widthHead : m (Worker.header pub + 9).val = T.width)
+ (startHead : m (Worker.header pub + 11).val = base)
+ (zero : m (Worker.header pub + 12).val = 0) :
+ let P := (Worker.table.instantiate w pub).program
+ ∃ rs, runSegment P 30 (some 0) m (List.replicate (arcCount X) []) = some rs ∧
+ Stored X T base (Worker.header pub + 12) m (after m (eventLog rs)) ∧
+ endState (some 0) rs = some (arcCount X : Word w) ∧ rs.length = arcCount X ∧
+ ∀ r ∈ rs, (r.probes = 7 ∧ r.events.length = 29) ∧ footprint pub T base (arcCount X) r := by
+ let ws := List.ofFn (width X)
+ let h := Worker.header pub
+ have hlen : ws.length = arcCount X := List.length_ofFn
+ have hsum : ws.sum = X.totalWidth := List.sum_ofFn.trans (width_sum X)
+ have init : SliceRAM.PrefixAt (operands T base (h + 12)) ws m m 0 := by
+ refine ⟨?_, fun _ h => by omega, ?_, fun _ _ _ => rfl⟩
+ · intro i hi
+ change (m (T.width.val + i)).val = ws[i]
+ simpa only [ws, List.getElem_ofFn] using
+ width_cells X T m rep regions.widthsFit totalFit ⟨i, hlen ▸ hi⟩
+ · change (m (h + 12).val).val = (ws.take 0).sum
+ rw [zero]; rfl
+ obtain ⟨rs, executed, filled, ended, calls, cost⟩ := active_from pub T base ws m
+ (hlen ▸ layout) (hlen ▸ regions) (hlen.trans_lt countFit) (hsum.trans_lt totalFit)
+ (hlen ▸ count) widthHead startHead init ws.length (by omega)
+ simp only [Nat.cast_zero, Nat.zero_add, hlen] at executed ended calls cost
+ refine ⟨rs, executed, ⟨?_, ?_, ?_, ?_⟩, ended, calls, cost⟩
+ · intro i
+ exact (filled.starts i.val (by simpa only [Nat.zero_add, hlen] using i.isLt)).trans
+ (take_sum (width X) i)
+ · change (after m (eventLog rs) (operands T base (Worker.header pub + 12) 2).val).val = _
+ simpa only [Nat.zero_add, List.take_length, hsum] using filled.total
+ · intro i
+ change (after m (eventLog rs)
+ ((operands T base (Worker.header pub + 12) 0).val + i.val)).val = _
+ simpa only [ws, List.getElem_ofFn] using filled.widths i.val (i.isLt.trans_eq hlen.symm)
+ · intro x hx hx'
+ apply filled.outside x hx
+ change x < base.val ∨ base.val + (0 + ws.length) ≤ x
+ simpa only [Nat.zero_add, hlen] using hx'
+
+/-- The role-tag displacement published by the closing call. -/
+def roleValue (pub : Fin 11 → Word w) (X : State a g) (m : Memory w) : Word w :=
+ m (Worker.header pub + 5).val + (X.totalWidth : Word w)
+
+/-- Complete native execution, including the accepting call. The frame of the
+stored prefix is relative to the initial memory with the role cell updated. -/
+structure Run (pub : Fin 11 → Word w) (X : State a g) (T : IncidenceDirectory w)
+ (base : Word w) (m : Memory w) (rs : List (Report w)) : Prop where
+ native : runSegment (Worker.table.instantiate w pub).program 30 (some 0) m
+ (List.replicate (arcCount X + 1) []) = some rs
+ halt : endState (some 0) rs = none
+ calls : rs.length = arcCount X + 1
+ probes : (rs.map Report.probes).sum = 7 * arcCount X + 4
+ instructions : (rs.map (fun r => r.events.length + 1)).sum = 30 * arcCount X + 24
+ bounds : ∀ r ∈ rs, r.probes ≤ 7 ∧ r.events.length ≤ 29
+ stored : Stored X T base (Worker.header pub + 12)
+ (writeMemory m (Worker.header pub + 14) (roleValue pub X m)) (after m (eventLog rs))
+ accesses : ∀ r ∈ rs, footprint pub T base (arcCount X) r
+ role : after m (eventLog rs) (Worker.header pub + 14).val = roleValue pub X m
+
+private theorem stored_header_read {pub : Fin 11 → Word w} {X : State a g}
+ {T : IncidenceDirectory w} {base : Word w} {m ready : Memory w}
+ (layout : HeaderLayout pub T base (arcCount X))
+ (stored : Stored X T base (Worker.header pub + 12) m ready)
+ (j : ℕ) (hj : j < 15) (hn : j ≠ 12) :
+ ready (Worker.header pub + (j : Word w)).val = m (Worker.header pub + (j : Word w)).val := by
+ have ht : (Worker.header pub + 12).val = (Worker.header pub).val + 12 := by
+ simpa only [Nat.cast_ofNat] using header_addr (j := 12) layout.fits (by decide)
+ apply stored.outside
+ · rw [header_addr layout.fits hj, ht]
+ omega
+ · rw [header_addr layout.fits hj]
+ have := layout.startsApart
+ omega
+
+private theorem store_role {pub : Fin 11 → Word w} {X : State a g}
+ {T : IncidenceDirectory w} {base : Word w} {m ready : Memory w}
+ (layout : HeaderLayout pub T base (arcCount X))
+ (stored : Stored X T base (Worker.header pub + 12) m ready) (v : Word w) :
+ Stored X T base (Worker.header pub + 12) (writeMemory m (Worker.header pub + 14) v)
+ (writeMemory ready (Worker.header pub + 14) v) := by
+ let h := Worker.header pub
+ have ht : (h + 12).val = h.val + 12 := by
+ simpa only [Nat.cast_ofNat] using header_addr (j := 12) layout.fits (by decide)
+ have hr : (h + 14).val = h.val + 14 := by
+ simpa only [Nat.cast_ofNat] using header_addr (j := 14) layout.fits (by decide)
+ refine ⟨?_, ?_, ?_, ?_⟩
+ · intro i
+ have := layout.startsApart
+ have hi := i.isLt
+ have hx : base.val + i.val ≠ (h + 14).val := by dsimp only [h] at hr ⊢; omega
+ dsimp only [h] at hx
+ simpa only [writeMemory, ite_eq_right hx] using stored.start i
+ · have hx : (h + 12).val ≠ (h + 14).val := by omega
+ dsimp only [h] at hx
+ simpa only [writeMemory, ite_eq_right hx] using stored.total
+ · intro i
+ have := layout.widthsApart
+ have hi := i.isLt
+ have hx : T.width.val + i.val ≠ (h + 14).val := by dsimp only [h] at hr ⊢; omega
+ dsimp only [h] at hx
+ simpa only [writeMemory, ite_eq_right hx] using stored.widths i
+ · intro x htotal hstart
+ simp only [writeMemory, stored.outside x htotal hstart]
+
+open private sum_constant_cost from OAI.Computability.VPVNP.CompressorSlicePreparation
+
+/-- All active arc visits and the accepting role-offset publication form a
+single reset-entry run, including for a final network with no arcs. -/
+theorem run (pub : Fin 11 → Word w) (X : State a g) (T : IncidenceDirectory w)
+ (base : Word w) (m : Memory w) (rep : T.ActualColumns X m)
+ (layout : HeaderLayout pub T base (arcCount X))
+ (regions : SliceRAM.PrefixRegions (operands T base (Worker.header pub + 12)) (arcCount X))
+ (countFit : arcCount X < 2 ^ w) (totalFit : X.totalWidth < 2 ^ w)
+ (count : m (Worker.header pub + 8).val = (arcCount X : Word w))
+ (widthHead : m (Worker.header pub + 9).val = T.width)
+ (startHead : m (Worker.header pub + 11).val = base)
+ (zero : m (Worker.header pub + 12).val = 0) :
+ ∃ rs, Run pub X T base m rs := by
+ obtain ⟨rs, native, stored, ended, calls, cost⟩ := run_active pub X T base m rep layout
+ regions countFit totalFit count widthHead startHead zero
+ let ready := after m (eventLog rs)
+ let n := arcCount X
+ let h := Worker.header pub
+ let last := Worker.closeReport pub (n : Word w) ready
+ have hcount : (n : Word w) = ready (h + 8).val := by
+ have hc := stored_header_read layout stored 8 (by decide) (by decide)
+ simpa only [Nat.cast_ofNat] using count.symm.trans hc.symm
+ have close := Worker.close pub (n : Word w) ready hcount
+ have total : ready (h + 12).val = (X.totalWidth : Word w) := by
+ apply Fin.ext
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt totalFit]
+ exact stored.total
+ have hdesc : ready (h + 5).val = m (h + 5).val := by
+ simpa only [Nat.cast_ofNat] using stored_header_read layout stored 5 (by decide) (by decide)
+ have image : after m (eventLog (rs ++ [last])) =
+ writeMemory ready (h + 14) (roleValue pub X m) := by
+ have hm : after m (eventLog (rs ++ [last])) = after ready last.events := by
+ simp only [eventLog, List.flatMap_append, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil, after, List.foldl_append, ready]
+ rw [hm, Worker.close_image, roleValue, hdesc, total]
+ have lastCost := Worker.close_cost pub (n : Word w) ready
+ refine ⟨rs ++ [last], ⟨?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, native]
+ dsimp only [n, ready] at close
+ simp only [Option.bind_some, ended, runSegment, close, Option.map_some]
+ rfl
+ · rw [endState_append]
+ rfl
+ · simp [calls]
+ · simp only [List.map_append, List.sum_append, List.map_cons, List.map_nil, List.sum_cons,
+ List.sum_nil, Nat.add_zero]
+ rw [sum_constant_cost Report.probes rs 7 (fun r hr => (cost r hr).1.1), calls]
+ exact congrArg _ lastCost.1
+ · simp only [List.map_append, List.sum_append, List.map_cons, List.map_nil, List.sum_cons,
+ List.sum_nil, Nat.add_zero]
+ rw [sum_constant_cost (fun r : Report w => r.events.length + 1) rs 30
+ (fun r hr => by rw [(cost r hr).1.2]), calls]
+ rw [show last.events.length = 23 from lastCost.2]
+ · intro r hr
+ rcases List.mem_append.mp hr with hr | hr
+ · obtain ⟨hp, ht⟩ := (cost r hr).1
+ exact ⟨hp.le, ht.le⟩
+ · obtain rfl := List.mem_singleton.mp hr
+ exact ⟨lastCost.1.le.trans (by decide), lastCost.2.le.trans (by decide)⟩
+ · rw [image]
+ exact store_role layout stored _
+ · intro r hr
+ rcases List.mem_append.mp hr with hr | hr
+ · exact (cost r hr).2
+ · obtain rfl := List.mem_singleton.mp hr
+ exact close_footprint layout _ _
+ · rw [image]
+ simp only [writeMemory, h, ↓reduceIte]
+
+/-- The terminating stage admits precisely its canonical sequence of empty
+choice streams, with the same reports on every accepting execution. -/
+theorem Run.unique {pub : Fin 11 → Word w} {X : State a g} {T : IncidenceDirectory w}
+ {base : Word w} {m : Memory w} {rs ts : List (Report w)} (run : Run pub X T base m rs)
+ {bits : List (List Bool)} (native : runSegment (Worker.table.instantiate w pub).program 30
+ (some 0) m bits = some ts) (halt : endState (some 0) ts = none) :
+ bits = List.replicate (arcCount X + 1) [] ∧ ts = rs :=
+ accepted_empty_unique run.native run.halt native halt
+
+/-- Total charged work counts one unit for starting each call in addition to
+its external probes. -/
+theorem Run.charge {pub : Fin 11 → Word w} {X : State a g} {T : IncidenceDirectory w}
+ {base : Word w} {m : Memory w} {rs : List (Report w)} (run : Run pub X T base m rs) :
+ RAMBuckets.cost Report.probes rs = 8 * arcCount X + 5 := by
+ rw [SliceRAM.adjCost_eq_length_add_probes, run.calls, run.probes]
+ omega
+
+/-- Every read and write in the entire completed segment avoids the linked
+controller's phase cell and saved-state cell. -/
+theorem Run.controller_frame {pub : Fin 11 → Word w} {X : State a g} {T : IncidenceDirectory w}
+ {base : Word w} {m : Memory w} {rs : List (Report w)} (run : Run pub X T base m rs)
+ (fits : (Worker.header pub).val + 32 ≤ 2 ^ w)
+ (widthsBelow : T.width.val + arcCount X ≤ (Worker.header pub).val)
+ (startsBelow : base.val + arcCount X ≤ (Worker.header pub).val) :
+ let away := fun x => x ≠ (Worker.header pub).val ∧ x ≠ (Worker.header pub + 31).val
+ SourceTransport.Reads away (eventLog rs) ∧ SourceTransport.Writes away (eventLog rs) := by
+ have small : 31 < 2 ^ w := by omega
+ have saved : (Worker.header pub + 31).val = (Worker.header pub).val + 31 := by
+ change ((Worker.header pub).val + (31 % 2 ^ w)) % (2 ^ w) = _
+ rw [Nat.mod_eq_of_lt small, Nat.mod_eq_of_lt (by omega)]
+ have safe (x : ℕ) (h : probeRegion pub T base (arcCount X) x) :
+ x ≠ (Worker.header pub).val ∧ x ≠ (Worker.header pub + 31).val := by
+ rw [saved]
+ unfold probeRegion at h
+ omega
+ constructor <;> intro a v mem
+ · obtain ⟨r, hr, he⟩ := List.mem_flatMap.mp mem
+ exact safe _ ((run.accesses r hr).1 a v he)
+ · obtain ⟨r, hr, he⟩ := List.mem_flatMap.mp mem
+ exact safe _ ((run.accesses r hr).2 a v he)
+
+/-- With room for the descriptor words and final bits together, the published
+word is their ordinary natural-number sum. -/
+theorem Run.role_val {pub : Fin 11 → Word w} {X : State a g} {T : IncidenceDirectory w}
+ {base : Word w} {m : Memory w} {rs : List (Report w)} (run : Run pub X T base m rs)
+ (fit : (m (Worker.header pub + 5).val).val + X.totalWidth < 2 ^ w) :
+ (after m (eventLog rs) (Worker.header pub + 14).val).val =
+ (m (Worker.header pub + 5).val).val + X.totalWidth := by
+ rw [run.role, roleValue, Fin.val_add, Fin.val_natCast,
+ Nat.mod_eq_of_lt (by omega : X.totalWidth < 2 ^ w), Nat.mod_eq_of_lt fit]
+
+end PairSimulation.TerminalPrefix.Segment
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPrefixWorker.lean b/lean/OAI/Computability/VPVNP/PairTerminalPrefixWorker.lean
new file mode 100644
index 0000000000..55be824a19
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPrefixWorker.lean
@@ -0,0 +1,203 @@
+import OAI.Computability.VPVNP.PairTerminalPrefix
+import OAI.Computability.VPVNP.PairSimulationTerminalLink
+
+/-!
+# Live terminal-prefix instruction table
+
+The terminal header is recovered from the workspace and size exponent in the
+eleven public operands. Every active call takes its width and prefix table
+heads from that header, advances one arc, and returns the successor ordinal.
+The closing call publishes the role-table displacement and accepts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalPrefix.Worker
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Terminal header at the high end of the pair workspace. -/
+abbrev header (pub : Fin 11 → Word w) : Word w := TerminalLink.header pub
+
+/-- Width-array head, prefix-array head, and running-total address loaded from the terminal
+header for the prefix worker. -/
+def data (pub : Fin 11 → Word w) (m : Memory w) : Fin 3 → Word w :=
+ let h := header pub
+ ![m (h + 9).val, m (h + 11).val, h + 12]
+
+/-- The 41 native instructions that recover the terminal header, process one arc's width, or
+publish the closing displacement. -/
+def instruction (w : ℕ) : Fin 41 → Instr w 41 7 11 :=
+ ![.publicWord 1 7 1, .constant 2 1 2, .binary .shiftLeft 1 2 1 3, .binary .mul 1 1 1 4,
+ .publicWord 3 2 5, .binary .add 1 3 1 6, .constant 3 32 7, .binary .sub 1 1 3 8,
+ .stateWord 0 9, .constant 3 8 10, .binary .add 3 1 3 11, .readExternal 3 3 12,
+ .jumpEq 0 3 30 13,
+ .constant 3 9 14, .binary .add 3 1 3 15, .readExternal 3 3 16, .binary .add 3 3 0 17,
+ .readExternal 3 3 18, .constant 4 11 19, .binary .add 4 1 4 20, .readExternal 4 4 21,
+ .binary .add 4 4 0 22, .constant 5 12 23, .binary .add 5 1 5 24, .readExternal 6 5 25,
+ .writeExternal 4 6 26, .binary .add 6 6 3 27, .writeExternal 5 6 28, .binary .add 0 0 2 29,
+ .returnState 0,
+ .constant 3 5 31, .binary .add 3 1 3 32, .readExternal 3 3 33, .constant 4 12 34,
+ .binary .add 4 1 4 35, .readExternal 4 4 36, .binary .add 3 3 4 37, .constant 4 14 38,
+ .binary .add 4 1 4 39, .writeExternal 4 3 40, .accept]
+
+/-- Resizable terminal prefix worker table, assembled at six-bit word width with entry at
+instruction zero. -/
+def table : Template 41 7 11 := ⟨6, 0, instruction 6⟩
+
+set_option maxRecDepth 4096 in
+theorem resize_instruction (w : ℕ) (pc : Fin 41) :
+ (instruction 6 pc).resize w = instruction w pc := by fin_cases pc <;> rfl
+
+private def read (m : Memory w) (addr : Word w) := Event.read addr (m addr.val)
+
+private def pre (pub : Fin 11 → Word w) (m : Memory w) : List (Event w) :=
+ List.replicate 11 .tick ++ [read m (header pub + 8), .tick]
+
+/-- Report for arc ordinal i. It writes the current total into that arc's prefix cell, adds the
+arc width, and returns the next ordinal. -/
+def activeReport (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) : Report w :=
+ let h := header pub
+ let width := m (h + 9).val + i
+ let dst := m (h + 11).val + i
+ let total := m (h + 12).val
+ ⟨pre pub m ++ [.tick, .tick, read m (h + 9), .tick, read m width, .tick, .tick,
+ read m (h + 11), .tick, .tick, .tick, read m (h + 12), .write dst total, .tick,
+ .write (h + 12) (total + m width.val), .tick], some (i + 1)⟩
+
+/-- Final prefix report that adds the accumulated terminal width to the DFS row count, stores
+the role-table displacement, and accepts. -/
+def closeReport (pub : Fin 11 → Word w) (_i : Word w) (m : Memory w) : Report w :=
+ let h := header pub
+ ⟨pre pub m ++ [.tick, .tick, read m (h + 5), .tick, .tick, read m (h + 12),
+ .tick, .tick, .tick, .write (h + 14) (m (h + 5).val + m (h + 12).val)], none⟩
+
+@[simp] theorem active_result (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) :
+ (activeReport pub i m).result = some (i + 1) := rfl
+
+@[simp] theorem close_result (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) :
+ (closeReport pub i m).result = none := rfl
+
+theorem active_cost (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) :
+ (activeReport pub i m).probes = 7 ∧ (activeReport pub i m).events.length = 29 := ⟨rfl, rfl⟩
+
+theorem close_cost (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) :
+ (closeReport pub i m).probes = 4 ∧ (closeReport pub i m).events.length = 23 := ⟨rfl, rfl⟩
+
+theorem active_image (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) :
+ after m (activeReport pub i m).events = after m (SliceRAM.prefixEvents (data pub m) i m) :=
+ rfl
+
+theorem close_image (pub : Fin 11 → Word w) (i : Word w) (m : Memory w) :
+ let h := header pub
+ after m (closeReport pub i m).events =
+ writeMemory m (h + 14) (m (h + 5).val + m (h + 12).val) := rfl
+
+private theorem step (pub : Fin 11 → Word w) (c : Config w 41 7) :
+ (table.instantiate w pub).program.step c = (instruction w c.pc).run pub c := by
+ change ((instruction 6 c.pc).resize w).run pub c = _
+ rw [resize_instruction]
+
+
+private theorem step_at (pub : Fin 11 → Word w) (j : Fin 41) {c : Config w 41 7} (pc : c.pc = j) :
+ (table.instantiate w pub).program.step c = (instruction w j).run pub c :=
+ (step pub c).trans (by rw [pc])
+
+private theorem jump_no (pub : Fin 11 → Word w) {c : Config w 41 7} (pc : c.pc = 12)
+ (ne : c.reg 0 ≠ c.reg 3) :
+ (table.instantiate w pub).program.step c = .localStep {c with pc := 13} := by
+ rw [step_at pub 12 pc]
+ change CallAction.localStep {c with pc := if c.reg 0 = c.reg 3 then 30 else 13} = _
+ rw [ite_eq_right ne]
+
+private theorem jump_yes (pub : Fin 11 → Word w) {c : Config w 41 7} (pc : c.pc = 12)
+ (eq : c.reg 0 = c.reg 3) :
+ (table.instantiate w pub).program.step c = .localStep {c with pc := 30} := by
+ rw [step_at pub 12 pc]
+ change CallAction.localStep {c with pc := if c.reg 0 = c.reg 3 then 30 else 13} = _
+ rw [ite_eq_left eq]
+
+set_option maxRecDepth 4096 in
+/-- Exact native execution of the one-arc visit. -/
+theorem active (pub : Fin 11 → Word w) (i : Word w) (m : Memory w)
+ (hi : i ≠ m (header pub + 8).val) :
+ let M := table.instantiate w pub
+ execute M.program 30 (M.program.start i) m [] = some (activeReport pub i m) := by
+ apply execute_iff.mpr
+ refine ⟨?_, ?_, rfl⟩
+ · apply Guessed.step (step_at pub 0 rfl)
+ apply Guessed.step (step_at pub 1 rfl)
+ apply Guessed.step (step_at pub 2 rfl)
+ apply Guessed.step (step_at pub 3 rfl)
+ apply Guessed.step (step_at pub 4 rfl)
+ apply Guessed.step (step_at pub 5 rfl)
+ apply Guessed.step (step_at pub 6 rfl)
+ apply Guessed.step (step_at pub 7 rfl)
+ apply Guessed.step (step_at pub 8 rfl)
+ apply Guessed.step (step_at pub 9 rfl)
+ apply Guessed.step (step_at pub 10 rfl)
+ apply Guessed.read (step_at pub 11 rfl)
+ apply Guessed.step (jump_no pub rfl hi)
+ apply Guessed.step (step_at pub 13 rfl)
+ apply Guessed.step (step_at pub 14 rfl)
+ apply Guessed.read (step_at pub 15 rfl)
+ apply Guessed.step (step_at pub 16 rfl)
+ apply Guessed.read (step_at pub 17 rfl)
+ apply Guessed.step (step_at pub 18 rfl)
+ apply Guessed.step (step_at pub 19 rfl)
+ apply Guessed.read (step_at pub 20 rfl)
+ apply Guessed.step (step_at pub 21 rfl)
+ apply Guessed.step (step_at pub 22 rfl)
+ apply Guessed.step (step_at pub 23 rfl)
+ apply Guessed.read (step_at pub 24 rfl)
+ apply Guessed.write (step_at pub 25 rfl)
+ apply Guessed.step (step_at pub 26 rfl)
+ apply Guessed.write (step_at pub 27 rfl)
+ apply Guessed.step (step_at pub 28 rfl)
+ exact Guessed.done (step_at pub 29 rfl)
+ · simp [activeReport, pre, read, Correct, update]
+
+set_option maxRecDepth 4096 in
+/-- Exact native execution of the terminal role-offset publication. -/
+theorem close (pub : Fin 11 → Word w) (i : Word w) (m : Memory w)
+ (hi : i = m (header pub + 8).val) :
+ let M := table.instantiate w pub
+ execute M.program 30 (M.program.start i) m [] = some (closeReport pub i m) := by
+ apply execute_iff.mpr
+ refine ⟨?_, ?_, rfl⟩
+ · apply Guessed.step (step_at pub 0 rfl)
+ apply Guessed.step (step_at pub 1 rfl)
+ apply Guessed.step (step_at pub 2 rfl)
+ apply Guessed.step (step_at pub 3 rfl)
+ apply Guessed.step (step_at pub 4 rfl)
+ apply Guessed.step (step_at pub 5 rfl)
+ apply Guessed.step (step_at pub 6 rfl)
+ apply Guessed.step (step_at pub 7 rfl)
+ apply Guessed.step (step_at pub 8 rfl)
+ apply Guessed.step (step_at pub 9 rfl)
+ apply Guessed.step (step_at pub 10 rfl)
+ apply Guessed.read (step_at pub 11 rfl)
+ apply Guessed.step (jump_yes pub rfl hi)
+ apply Guessed.step (step_at pub 30 rfl)
+ apply Guessed.step (step_at pub 31 rfl)
+ apply Guessed.read (step_at pub 32 rfl)
+ apply Guessed.step (step_at pub 33 rfl)
+ apply Guessed.step (step_at pub 34 rfl)
+ apply Guessed.read (step_at pub 35 rfl)
+ apply Guessed.step (step_at pub 36 rfl)
+ apply Guessed.step (step_at pub 37 rfl)
+ apply Guessed.step (step_at pub 38 rfl)
+ apply Guessed.write (step_at pub 39 rfl)
+ exact Guessed.done (step_at pub 40 rfl)
+ · simp [closeReport, pre, read, Correct, update]
+
+end PairSimulation.TerminalPrefix.Worker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPreludeBudget.lean b/lean/OAI/Computability/VPVNP/PairTerminalPreludeBudget.lean
new file mode 100644
index 0000000000..b53688b613
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPreludeBudget.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairTerminalPackedBudget
+import OAI.Computability.VPVNP.PairTerminalVertexPackedThreshold
+import OAI.Computability.VPVNP.PairTraversalControllerSelectedRun
+
+/-!
+# Uniform numerical conditions of the packed terminal prefix
+
+The actual live processor clock, the selected block layout and the two
+compressor exponents supply every numerical cut used in the bootstrap,
+width, traversal, and shared-bit stages. The threshold precedes the selected
+level directories, the worker data and the assignments to their coefficients.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLayout
+
+open BurstRAM Compression CursorBounds CursorNetwork CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles Filter
+
+set_option exponentiation.threshold 10000 in
+/-- Room for the selected prelude and its closing dispatches on the actual
+nested live pair clock. No clock or memory cut is assumed of the workers. -/
+theorem eventually_preludeRoom {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {start : ℕ → ℕ} (hstart : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let w := wordBits b n
+ let r := addressBits b n
+ let T := blockCount (u.θ : ℝ) n
+ let X := pairInput S labels hD
+ let E := B.execute f hf T hT X
+ let L := BlockProgram.layout B (start n) X.positions T
+ ∀ (z : E.Choices) (G : LiveProgram.PairStages.Group), n^10000 ≤ G.clock →
+ let Y := E.finalState z
+ let ls := selectedLayers B f hf T hT X z
+ let tags := selected B f hf T hT X z
+ let cap := LiveProgram.CompressedPair.clockAt
+ (LiveProgram.PairStages.Group.CompressedPaths.publicWords G)
+ (LiveProgram.PairStages.Group.CompressedPaths.fuel G)
+ LiveProgram.CompressedPair.Stage.terminal
+ r < w ∧ 32 ≤ L.base + 2^r*2^r ∧ L.base + 2^r*2^r ≤ 2^w ∧
+ endAddress L + 2*words B.recordLimit ls + Y.totalWidth ≤
+ TerminalBootstrap.address L.base r ∧
+ 2*tags.length*(X.positions+1) < 2^w ∧
+ TerminalPrefix.arcCount Y ≤ slotCapacity L ∧ TerminalPrefix.arcCount Y ≤ tableWords L ∧
+ Y.totalWidth < 2^w ∧ TerminalBootstrap.cost L.shape B.recordLimit+1+30 ≤ cap ∧
+ 60 ≤ cap ∧ TraversalController.callFuel B.recordLimit+30 ≤ cap := by
+ let K := TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit+1+30 + 60 +
+ (TraversalController.callFuel B.recordLimit+30)
+ filter_upwards [eventually_packedFit B u b hb hstart 0 (fun _ => 0) (PolynomiallyBounded.const 0),
+ eventually_pair_clock K] with n hfit hclock
+ intro base lanes labels hD hT A _ f hf w r T X E L z G hc Y ls tags cap
+ have hp := pairInput_positions S labels hD
+ change X.positions = initialPositions b n at hp
+ have fit := hfit labels hD hT A f hf z
+ rw [← hp] at fit
+ have room := fit.2.1
+ have low := fit.1
+ change L.base+(2^r)^2-32+32 ≤ 2^w at room
+ change endAddress L + 2*words B.recordLimit ls + Y.totalWidth < L.base+(2^r)^2-32 at low
+ rw [pow_two] at room low
+ have caps := hclock G hc
+ change K ≤ cap at caps
+ have tables := LiveProgram.PairStages.Group.Auxiliary.selected_table_capacity
+ B f hf T hT X z (start n)
+ have bootCost := packed_bootCost B (start n) X.positions T
+ change TerminalBootstrap.cost L.shape B.recordLimit = _ at bootCost
+ have rword : r < w := (by omega : r < r+10).trans_le (Nat.le_self_pow (by decide : 4 ≠ 0) _)
+ refine ⟨rword,by omega,by omega,low.le,fit.2.2.2.2,tables.1,tables.2,by omega,?_,?_,?_⟩
+ all_goals dsimp only [K] at caps; omega
+
+end PairSimulation.TerminalLayout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalPreludeUnique.lean b/lean/OAI/Computability/VPVNP/PairTerminalPreludeUnique.lean
new file mode 100644
index 0000000000..f39c097626
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalPreludeUnique.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalBlocks
+import OAI.Computability.VPVNP.PairSimulationTerminalTraceEquiv
+import OAI.Computability.VPVNP.PairSimulationTerminalDeterministic
+
+/-!
+# Uniqueness of independently verified terminal setup records
+
+The three mandatory setup stages force every supplied choice to be empty.
+Consequently their complete chronological records, including all physical
+memories, agree across independent proofs of the prelude. A shared-bit
+record at that boundary is then determined by its native call list.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+open BurstRAM LiveProgram
+
+variable {w cap : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w} {m : Memory w}
+
+theorem CompletedPhase.eq_of_choices {e : Entry w} (x y : CompletedPhase workers pub cap e m)
+ (equal : x.val.choices = y.val.choices) : x = y :=
+ Subtype.ext ((x.prop.block_eq_suffix y.prop (a := []) (b := []) (by rw [equal])).1)
+
+theorem QuietPrefix.unique (p q : QuietPrefix workers pub cap m) : p=q := by
+ obtain ⟨b,u,v,qb,qu,qv⟩ := p
+ obtain ⟨b',u',v',_,_,_⟩ := q
+ obtain rfl : b=b' := CompletedPhase.eq_of_choices b b' (b.prop.force_quiet qb b'.prop).1.symm
+ obtain rfl : u=u' := CompletedPhase.eq_of_choices u u' (u.prop.force_quiet qu u'.prop).1.symm
+ obtain rfl : v=v' := CompletedPhase.eq_of_choices v v' (v.prop.force_quiet qv v'.prop).1.symm
+ rfl
+
+theorem QuietPrefix.bitPaths_eq {I : Type*} (q : QuietPrefix workers pub cap m) (x y : I ≃ q.BitPaths)
+ (equal : ∀ f, (x f).val.choices = (y f).val.choices) : x=y :=
+ Equiv.ext fun f => CompletedPhase.eq_of_choices _ _ (equal f)
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalProgramControl.lean b/lean/OAI/Computability/VPVNP/PairTerminalProgramControl.lean
new file mode 100644
index 0000000000..136ab1a4ff
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalProgramControl.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.PairTerminalReachableFrame
+import OAI.Computability.VPVNP.PairSimulationSharedBitControl
+import OAI.Computability.VPVNP.PairSimulationVertexControlFrame
+import OAI.Computability.VPVNP.LiveTerminalReachableFrame
+
+/-!
+# Reachable frames of the actual terminal bit and vertex workers
+
+The bit cursor preserves every word outside its wire bank and controller.
+A finishing bit prefix supplies a full assignment, which selects the
+genuine vertex calls. At each active ordinal the vertex worker writes only
+the histogram, even if another ordinal later has no accepting choice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+open BurstRAM LiveProgram CompressorRecords SourceTransport TerminalLink VertexImage
+open scoped Fin.CommRing
+
+variable {w cap n g base grammar : ℕ} (F : DescriptorSpace.Shape) (limit : ℕ)
+ {geometry rootFields leaf shrink refresh : VertexImage.Segment} (pub : Fin 11 → Word w)
+ (m : Memory w)
+
+local notation "segments₀" => VertexImage.segments geometry rootFields leaf shrink refresh
+local notation "workers₀" => TerminalProgram.workers F limit segments₀
+
+/-- This statement concerns every physically reached boundary in the entire
+five-stage fixed instruction table, including successful partial histories.
+The data in `active` classify one original site burst and its native effects. -/
+theorem preservesCell {I : Type*} (q : QuietPrefix workers₀ pub cap m) (arc : I ≃ q.BitPaths)
+ (word : ℕ) (wide : 32 ≤ 2^w) (clock : 26 ≤ cap)
+ (first : ReplayFrame word m q.reportList)
+ (entered : (Entry.resume TerminalLink.Stage.sharedBits (0 : Word w)).Valid (header pub) q.traversalRows.val.memory)
+ {lo count : ℕ} (src : Memory w) (layout : FinalBits.Worker.Layout pub src lo count)
+ (room : (header pub).val+32 ≤ 2^w) (agree : Agree (workerCell (header pub)) src q.traversalRows.val.memory)
+ (wire : word < lo ∨ lo+count ≤ word)
+ (cell : workerCell (header pub) word)
+ (D : I → IndexedSites n g) (ref : I → Memory w)
+ (active : ∀ i, ActiveCalls (D i) ((VertexImage.template segments₀).instantiate w pub).program cap base grammar
+ (VertexFrame.Linked (header pub) base grammar g (ref i)))
+ (stored : ∀ i mem, VertexFrame.Linked (header pub) base grammar g (ref i) n mem →
+ mem (TerminalSiteStart.headerWord pub+7).val = (n : Word w))
+ (initial : ∀ i, VertexFrame.Linked (header pub) base grammar g (ref i) 0 (arc i).val.memory)
+ (counter : word < base+grammar ∨ base+grammar+g ≤ word) :
+ BurstRAM.PreservesCell (TerminalLink.program workers₀ pub) cap 0 m word := by
+ apply q.preservesCell word wide clock first entered
+ · exact FinalBits.Worker.control workers₀ rfl cap word src _ layout room agree wire cell
+ · intro b
+ let i := arc.symm b
+ have h : b = arc i := (arc.apply_symm_apply b).symm
+ rw [h]
+ apply VertexImage.ordinalWorkerControl F limit (ref i) (arc i).val.memory word (active i)
+ · exact template_closes (pub := pub) (by omega : 15 ≤ cap) (stored i)
+ · exact counter
+ · exact cell
+ · exact initial i
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalQuietFrame.lean b/lean/OAI/Computability/VPVNP/PairTerminalQuietFrame.lean
new file mode 100644
index 0000000000..f9b94825ad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalQuietFrame.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.PairTerminalPrefixLinked
+import OAI.Computability.VPVNP.PairTerminalReachableFrame
+import OAI.Computability.VPVNP.PairTraversalControllerMemory
+
+/-!
+# The low-memory frame of the linked bootstrap and width scan
+
+Each canonical terminal burst is replayed on its own physical input memory.
+The terminal controller writes the phase and the saved state above the packed
+workspace. The width scan's own stores are confined to its live directory and
+header words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM CompressorRecords Compression TerminalPrefix.Linked TraversalRoles
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- A source frame at one address survives the two linker stores, even when
+the linked worker starts with different values at its control cells. -/
+theorem replayFrame_stage (h : Word w) (e : Entry w) {x : ℕ} (away : workerCell h x)
+ (rs : List (Report w)) (src phy : Memory w) (equal : src x = phy x)
+ (frame : ReplayFrame x src rs) : ReplayFrame x phy (stageReports h e rs) := by
+ induction rs generalizing src phy e with
+ | nil => trivial
+ | cons r rs ih =>
+ have linked : after phy (report h e r).events x = after src r.events x := by
+ rw [report_after]
+ cases ht : target e.stage r.result with
+ | none => exact ControllerMemory.after_at equal.symm _
+ | some pair =>
+ obtain ⟨s,v⟩ := pair
+ simp only [writeMemory,ite_eq_right away.1,ite_eq_right away.2]
+ exact ControllerMemory.after_at equal.symm _
+ exact ⟨linked.trans (frame.1.trans equal), ih _ _ _ linked.symm frame.2⟩
+
+private theorem appendReplay {x : ℕ} {m : Memory w} (as bs : List (Report w))
+ (first : ReplayFrame x m as) (next : ReplayFrame x (after m (eventLog as)) bs) :
+ ReplayFrame x m (as ++ bs) := by
+ induction as generalizing m with
+ | nil => exact next
+ | cons r rs ih =>
+ rw [show after m (eventLog (r :: rs)) = after (after m r.events) (eventLog rs) from
+ List.foldl_append] at next
+ exact ⟨first.1, ih first.2 next⟩
+
+variable {a g : ℕ} {workers : Stage → LiveProgram.PairTable} {pub : Fin 11 → Word w}
+variable {cap fuel : ℕ} {Y : State a g} {inc : IncidenceDirectory w} {starts : Word w}
+variable {input : Memory w} {boot : Report w} {rs : List (Report w)}
+
+/-- Recover the physical first two stages from any forced three-stage
+prelude, including a prelude for which all later paths reject. -/
+theorem QuietPrefix.force_start (q : QuietPrefix workers pub cap input)
+ (s : Start workers pub cap fuel Y inc starts input boot rs)
+ (clock₀ : fuel + 30 ≤ cap) (clock₁ : 60 ≤ cap) :
+ q.boot.val.logs = [(.initial,boot)] ∧ q.boot.val.memory = bootMemory pub input boot ∧
+ q.prefixRows.val.logs = stageLogs (.resume Stage.prefixRows 0) rs ∧
+ q.prefixRows.val.memory = prefixMemory pub input boot rs := by
+ obtain ⟨first,second⟩ := s.phases clock₀ clock₁
+ obtain ⟨_,log₀,mem₀⟩ := first.force_quiet (by simp) q.boot.prop
+ rw [← mem₀] at second
+ obtain ⟨_,log₁,mem₁⟩ :=
+ second.force_quiet (fun _ h => List.eq_of_mem_replicate h) q.prefixRows.prop
+ exact ⟨log₀,mem₀,log₁,mem₁⟩
+
+/-- Join the two canonical initialization phases to the frame for the actual
+third-stage reports. All memories in the conclusion are the successive
+physical memories of the selected three-stage trace. -/
+theorem QuietPrefix.replayFrame_of_start (q : QuietPrefix workers pub cap input)
+ (s : Start workers pub cap fuel Y inc starts input boot rs)
+ (clock₀ : fuel + 30 ≤ cap) (clock₁ : 60 ≤ cap)
+ (x : ℕ) (away : workerCell (header pub) x)
+ (bootLow : after input boot.events x = input x)
+ (prefixLow : ¬ TerminalPrefix.Segment.probeRegion pub inc starts
+ (TerminalPrefix.arcCount Y) x)
+ (third : ReplayFrame x q.prefixRows.val.memory
+ (reports (header pub) q.traversalRows.val.logs)) :
+ ReplayFrame x input q.reportList := by
+ obtain ⟨logs₀,_,logs₁,_⟩ := q.force_start s clock₀ clock₁
+ have raw : ∀ (m : Memory w) (ss : List (Report w)), (∀ r ∈ ss, r ∈ rs) → ReplayFrame x m ss := by
+ intro m ss
+ induction ss generalizing m with
+ | nil => intro _; trivial
+ | cons r ss ih =>
+ intro contained
+ have stores := (s.rawScan.accesses r (contained r (by simp))).2
+ exact ⟨SourceTransport.after_outside _ stores prefixLow,
+ ih _ (fun r hr => contained r (List.mem_cons_of_mem _ hr))⟩
+ have frames₀ : ReplayFrame x input (reports (header pub) q.boot.val.logs) := by
+ rw [logs₀]
+ exact replayFrame_stage (header pub) .initial away [boot] input input rfl ⟨bootLow,trivial⟩
+ have frames₁ : ReplayFrame x q.boot.val.memory (reports (header pub) q.prefixRows.val.logs) := by
+ rw [logs₁,reports_stageLogs]
+ apply replayFrame_stage (header pub) _ away _ q.boot.val.memory q.boot.val.memory rfl
+ exact raw _ _ (fun _ h => h)
+ change ReplayFrame x input (reports (header pub)
+ (q.boot.val.logs ++ (q.prefixRows.val.logs ++ q.traversalRows.val.logs)))
+ simp only [reports,List.map_append]
+ apply appendReplay _ _ frames₀
+ rw [q.boot.prop.final_memory]
+ apply appendReplay _ _ frames₁
+ rw [q.prefixRows.prop.final_memory]
+ exact third
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalQuietHandoff.lean b/lean/OAI/Computability/VPVNP/PairTerminalQuietHandoff.lean
new file mode 100644
index 0000000000..4353850003
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalQuietHandoff.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalBlocks
+
+/-! # Controller validity after a completed physical terminal phase -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM LiveProgram
+
+variable {w cap : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w}
+
+open private follow_halt from OAI.Computability.VPVNP.PairSimulationTerminalSplit
+
+/-- A completed phase writes the actual next-stage tag and its zero cursor
+before the following phase. The original worker can start from arbitrary
+values at both controller addresses. -/
+theorem Phase.handoffValid {e : Entry w} {m final : Memory w} {bs : List (List Bool)}
+ {ls : List (Log w)}
+ (phase : Phase workers pub cap e m bs ls final) (wide : 32 ≤ 2 ^ w) :
+ ∀ next : Entry w, handoff e.stage = some next → next.Valid (header pub) final := by
+ induction phase with
+ | @last e m bs raw call room accepted =>
+ intro next follows
+ exact next_valid (header pub) e next raw m wide ((follow_halt e raw accepted).trans follows)
+ | @more e m b bs raw x ls final call room returned tail ih =>
+ intro next follows
+ exact ih next follows
+
+/-- Every completed deterministic prefix provides the actual entry to the
+shared-bit stage, regardless of which vertex paths subsequently succeed. -/
+theorem QuietPrefix.valid_sharedBits {m : Memory w} (q : QuietPrefix workers pub cap m)
+ (wide : 32 ≤ 2 ^ w) :
+ (Entry.resume Stage.sharedBits (0 : Word w)).Valid (header pub) q.traversalRows.val.memory :=
+ q.traversalRows.prop.handoffValid wide _ rfl
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalQuietPrefix.lean b/lean/OAI/Computability/VPVNP/PairTerminalQuietPrefix.lean
new file mode 100644
index 0000000000..9e7934c220
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalQuietPrefix.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalBlocks
+import OAI.Computability.VPVNP.PairTraversalControllerTerminal
+import OAI.Computability.VPVNP.PairTerminalPrefixLinked
+import OAI.Computability.VPVNP.PairTraversalControllerSelectedRun
+
+/-!
+# Deterministic terminal stages before the shared wire guesses
+
+The first three blocks use the source bootstrap, prefix scan and selected
+traversal-controller reports. Each block runs on the physical memory left by
+the preceding block. Their only branch strings are empty. The shared-bit
+worker starts on the resulting physical memory, with the linked handoff cells
+excluded from the equality with the ordinary traversal memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords TerminalLink TerminalPrefix.Linked
+open LiveProgram (PairTable)
+
+variable {w a g : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w}
+variable {cap fuel : ℕ} {Y : State a g} {inc : IncidenceDirectory w} {starts : Word w}
+variable {input : Memory w} {boot : Report w} {prefixRows : List (Report w)}
+
+/-- Compose the native row-construction burst sequence with the actual
+bootstrap and final-width scans. Its physical post-memory agrees with the
+row and tag construction on every cell available to the shared-bit worker. -/
+noncomputable def quietPrefixOfRows
+ (start : Start workers pub cap fuel Y inc starts input boot prefixRows)
+ (clock₀ : fuel + 30 ≤ cap) (clock₁ : 60 ≤ cap) (wide : 32 ≤ 2 ^ w)
+ (rowBank : workers Stage.traversalRows = ⟨_, _, TraversalController.Native.table⟩)
+ (limit calls probes : ℕ) (arena : Memory w) (rowReports : List (Report w))
+ (clock₂ : TraversalController.callFuel limit + 30 ≤ cap) :
+ let src₂ := prefixMemory pub input boot prefixRows
+ TraversalController.Segment (TraversalController.Native.machine pub).program
+ (TraversalController.callFuel limit) (some 0) none src₂ arena calls probes rowReports →
+ SourceTransport.Reads (workerCell (header pub)) (eventLog rowReports) →
+ { q : QuietPrefix workers pub cap input //
+ q.boot.val.choices = [[]] ∧
+ q.prefixRows.val.choices = List.replicate (TerminalPrefix.arcCount Y+1) [] ∧
+ q.traversalRows.val.choices = List.replicate calls [] ∧
+ q.traversalRows.val.logs = stageLogs (.resume Stage.traversalRows 0) rowReports ∧
+ SourceTransport.Agree (workerCell (header pub)) arena q.traversalRows.val.memory ∧
+ (Entry.resume Stage.sharedBits (0 : Word w)).Valid
+ (header pub) q.traversalRows.val.memory } := by
+ intro src₂ rows read
+ let src₁ := after input boot.events
+ let b₀ : CompletedPhase workers pub cap .initial input :=
+ ⟨⟨[[]],[(.initial,boot)],bootMemory pub input boot⟩,
+ initial_phase workers pub fuel cap input boot clock₀ start.bootCall start.bootHalt⟩
+ have source₁ : runSegment (source workers Stage.prefixRows pub) 30 (some 0) src₁
+ (List.replicate (TerminalPrefix.arcCount Y+1) []) = some prefixRows := by
+ unfold source
+ rw [start.prefixBank]
+ exact start.rawScan.native
+ have ag₁ : SourceTransport.Agree (workerCell (header pub)) src₁ b₀.val.memory := by
+ change SourceTransport.Agree (workerCell (header pub)) (after input boot.events)
+ (after input (report (header pub) .initial boot).events)
+ simpa only [stageReports,eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil]
+ using start.boot.agree
+ let e₁ := Entry.resume Stage.prefixRows (0 : Word w)
+ let e₂ := Entry.resume Stage.traversalRows (0 : Word w)
+ let b₁ := completedBlock (workers := workers) (pub := pub) (cap := cap) 30
+ e₁ src₁ b₀.val.memory _ prefixRows clock₁ ag₁ start.reads source₁ start.rawScan.halt
+ have ag₂ := start.handoff_rows
+ obtain ⟨run₂,phase₂,eq₂⟩ := TraversalController.linked_stage workers pub rowBank rows read
+ clock₂ wide ag₂.2 (fun _ _ => rfl)
+ let b₂ : CompletedPhase workers pub cap e₂ b₁.val.memory :=
+ ⟨⟨List.replicate calls [], stageLogs e₂ rowReports,
+ after b₁.val.memory (eventLog (stageReports (header pub) e₂ rowReports))⟩,phase₂⟩
+ let q : QuietPrefix workers pub cap input :=
+ ⟨b₀,b₁,b₂,by simp [b₀],fun _ h => List.eq_of_mem_replicate h,
+ fun _ h => List.eq_of_mem_replicate h⟩
+ exact ⟨q,rfl,rfl,rfl,rfl,eq₂,run₂.valid _ rfl⟩
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalReachableFrame.lean b/lean/OAI/Computability/VPVNP/PairTerminalReachableFrame.lean
new file mode 100644
index 0000000000..086bddfe3e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalReachableFrame.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalPartialFrames
+import OAI.Computability.VPVNP.PairSimulationTerminalDeterministic
+import OAI.Computability.VPVNP.LiveTerminalReachableFrame
+
+/-!
+# Protecting a live word on every reached call of the terminal program
+
+The forced startup, prefix and traversal blocks reach the physical bit-scan
+memory. The remaining two worker controls apply to every successful call,
+including histories which a later site rejects.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+open BurstRAM LiveProgram
+
+variable {w : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w} {cap : ℕ} {m : Memory w}
+
+/-- All branch tapes supplied to the three deterministic setup phases, in call order. -/
+def QuietPrefix.choices (q : QuietPrefix workers pub cap m) :=
+ q.boot.val.choices ++ (q.prefixRows.val.choices ++ q.traversalRows.val.choices)
+
+/-- The original worker reports paired with their terminal-controller entries. -/
+def QuietPrefix.logs (q : QuietPrefix workers pub cap m) :=
+ q.boot.val.logs ++ (q.prefixRows.val.logs ++ q.traversalRows.val.logs)
+
+/-- The physical reports after the controller has wrapped every setup call. -/
+def QuietPrefix.reportList (q : QuietPrefix workers pub cap m) := reports (header pub) q.logs
+
+private theorem QuietPrefix.empty_choices (q : QuietPrefix workers pub cap m) :
+ q.choices = List.replicate q.choices.length [] := by
+ apply List.ext_getElem
+ · simp
+ · intro j hj hj'
+ rw [List.getElem_replicate]
+ have mem := List.getElem_mem (l := q.choices) hj
+ change _ ∈ q.boot.val.choices ++ (q.prefixRows.val.choices ++ q.traversalRows.val.choices) at mem
+ rcases List.mem_append.mp mem with hb | rest
+ · exact q.bootQuiet _ hb
+ rcases List.mem_append.mp rest with hp | hr
+ · exact q.prefixQuiet _ hp
+ · exact q.traversalQuiet _ hr
+
+theorem QuietPrefix.replay (q : QuietPrefix workers pub cap m) (fit : 32 ≤ 2^w) (enough : 26 ≤ cap) :
+ runSegment (program workers pub) cap (some 0) m (List.replicate q.choices.length []) = some q.reportList := by
+ have visits : Visits workers pub cap (some .initial) m q.choices q.logs := by
+ apply q.boot.prop.append_visits
+ apply q.prefixRows.prop.append_visits
+ change Visits workers pub cap (some (.resume Stage.traversalRows 0)) _ _ _
+ simpa only [List.append_nil] using q.traversalRows.prop.append_visits (.nil _ _)
+ rw [← q.empty_choices]
+ exact visits.native workers pub cap fit enough (by rintro e h; cases h; trivial)
+
+theorem QuietPrefix.endSetup (q : QuietPrefix workers pub cap m) :
+ endState (some 0) q.reportList = some (Entry.resume Stage.sharedBits (0 : Word w)).marker := by
+ change endState (hostState (some .initial)) (reports (header pub) q.logs) = _
+ rw [finish_host,QuietPrefix.logs,q.boot.prop.finish_append]
+ change hostState (finish (some (.resume Stage.prefixRows 0)) _) = _
+ rw [q.prefixRows.prop.finish_append]
+ change hostState (finish (some (.resume Stage.traversalRows 0)) q.traversalRows.val.logs) = _
+ have last := q.traversalRows.prop.finish_append []
+ rw [List.append_nil] at last
+ rw [last]
+ rfl
+
+theorem QuietPrefix.after_setup (q : QuietPrefix workers pub cap m) :
+ after m (eventLog q.reportList) = q.traversalRows.val.memory := by
+ have append (start : Memory w) (xs ys : List (Log w)) :
+ after start (eventLog (reports (header pub) (xs++ys))) =
+ after (after start (eventLog (reports (header pub) xs))) (eventLog (reports (header pub) ys)) := by
+ simp only [reports,List.map_append,eventLog,List.flatMap_append,after,List.foldl_append]
+ rw [QuietPrefix.reportList,QuietPrefix.logs,append,q.boot.prop.final_memory,append,
+ q.prefixRows.prop.final_memory,q.traversalRows.prop.final_memory]
+
+/-- The protected-address property includes both continuing calls and the
+last accepting exit. The setup frame is measured on its actual memory at
+each report. The vertex invariant may depend on the fourth block. -/
+theorem QuietPrefix.preservesCell (q : QuietPrefix workers pub cap m) (a : ℕ)
+ (fit : 32 ≤ 2^w) (enough : 26 ≤ cap)
+ (prefixFrame : ReplayFrame a m q.reportList)
+ (valid : (Entry.resume Stage.sharedBits (0 : Word w)).Valid (header pub) q.traversalRows.val.memory)
+ (bit : WorkerControl workers pub cap Stage.sharedBits a q.traversalRows.val.memory)
+ (vertex : ∀ b : q.BitPaths, WorkerControl workers pub cap Stage.vertices a b.val.memory) :
+ PreservesCell (program workers pub) cap 0 m a := by
+ apply preservesCell_after_replayed_prefix (q.replay fit enough) q.endSetup prefixFrame
+ rw [q.after_setup]
+ exact shared_vertices_safe bit vertex fit enough valid
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalSelectedHeaders.lean b/lean/OAI/Computability/VPVNP/PairTerminalSelectedHeaders.lean
new file mode 100644
index 0000000000..6cef2368da
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalSelectedHeaders.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.PairTraversalTerminalBootstrap
+import OAI.Computability.VPVNP.CompressorBlockMetadata
+import OAI.Computability.VPVNP.CompressorLevelOrder
+
+/-!
+# Reading terminal bootstrap data from the selected level headers
+
+The first-level parameter frame, final scalar and pointer publications, and the
+row-base recurrence give all data used by the one-shot terminal bootstrap.
+The reconstructed row count includes the last layer and also applies when
+there are no elementary compression passes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalBootstrap
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DescriptorSpace TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+variable {w a g : ℕ}
+
+/-- Telescoping native scalar-14 updates in a single word. No site count or layer
+ordinal is embedded in the worker code. -/
+theorem row_prefix (heads : ℕ → Word w) (cap base : ℕ) (rows : List TaggedLayer)
+ (start : heads 0 = (base : Word w))
+ (advance : ∀ i (h : i < rows.length), heads (i+1) = heads i+((cap+2 : ℕ) : Word w)*(rows[i].layer.count : Word w))
+ (i : ℕ) (hi : i ≤ rows.length) : heads i = (layerBase cap base rows i : Word w) := by
+ induction i with
+ | zero => simpa only [layerBase_zero] using start
+ | succ i ih =>
+ have h : i < rows.length := hi
+ rw [advance i h,ih h.le]
+ exact BlockMetadata.next_layerBase cap base rows ⟨i,h⟩
+
+/-- Physical header values of a final state with the indicated preceding DFS layers. -/
+noncomputable def fromState (L : Layout) (prior : List Layer) (cap baseBits laneBits : ℕ)
+ (Y : State a g) (table : Fin L.shape.tables) : Header L prior.length :=
+ let N := Y.positions*2^a
+ ⟨words cap prior,Fintype.card Y.Base,2^g,2^a,incidenceBase L prior.length N 5,
+ incidenceBase L prior.length N 4,tableBase L prior.length table,2^baseBits,2^laneBits⟩
+
+theorem fromState_sites (L : Layout) (prior : List Layer) (cap baseBits laneBits : ℕ)
+ (Y : State a g) (table : Fin L.shape.tables) : (fromState L prior cap baseBits laneBits Y table).sites = Y.positions := by
+ change Fintype.card Y.Base * 2^g = Fintype.card (Y.Base × BitWord g)
+ rw [Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv g),Fintype.card_fin]
+
+theorem fromState_rowWords (L : Layout) (prior : List Layer) (cap baseBits laneBits : ℕ) (Y : State a g)
+ (table : Fin L.shape.tables) (last : Layer) (hl : last.count = Y.positions) :
+ (fromState L prior cap baseBits laneBits Y table).rowWords cap = words cap (prior ++ [last]) := by
+ rw [Header.rowWords,fromState_sites,← hl]
+ change words cap prior + last.count*(cap+2) = _
+ simp [words,Nat.mul_add,Nat.mul_comm]
+
+/-- Convert the actual published values and the immutable cursor parameter frame
+into the terminal table's input condition. The directory heads refer to their final
+packed rows. The saved base and lane radices can differ from the final radices. -/
+theorem ready_of_published (L : Layout) (prior : List Layer) (cap baseBits laneBits : ℕ)
+ (Y : State a g) (table : Fin L.shape.tables) (zero : table.val = 0)
+ (pub : Fin 11 → Word w) (m : Memory w)
+ (workspace : (pub 2).val = L.base) (rows : m (pub 2+8).val = (directoryRows L : Word w))
+ (pitch : m (pub 2+((10+L.shape.arity : ℕ) : Word w)).val = (levelWords L : Word w))
+ (size : L.levels = prior.length+1) (wide : 30 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w)
+ (levelCount : m (levelStart L 0+28) = (L.levels : Word w))
+ (arena : m (levelStart L 0+14) = (endAddress L : Word w))
+ (rowStart : m (levelStart L prior.length+14) = ((endAddress L+words cap prior : ℕ) : Word w))
+ (current : Scalars.Present (.terminal a) (Fintype.card Y.Base) g (levelStart L prior.length : Word w) m)
+ (columns : ∀ c : Fin 6, m (incidenceHead L prior.length c) = (incidenceBase L prior.length (Y.positions*2^a) c : Word w))
+ (tables : m (tableHead L prior.length table) = (tableBase L prior.length table : Word w))
+ (p q : Word w) (degree width firstColumn : ℕ) (saved : Frame.data ((levelStart L 0 : Word w)+6) m =
+ CursorRAM.ScheduleInit.inputs p q baseBits laneBits degree width firstColumn) :
+ Ready L prior.length (fromState L prior cap baseBits laneBits Y table) pub m := by
+ have limit (i off : ℕ) (hl : i < L.levels) (ho : off < levelWords L) : levelStart L i + off < 2^w :=
+ (show levelStart L i + off < levelStart L (i+1) by simp [levelStart,Nat.succ_mul]; omega).trans
+ (level_room L fit ⟨i,hl⟩)
+ have hspan : L.shape.scalarFields + 6 + L.shape.tables ≤ levelWords L := by
+ simp only [levelWords,levelHeaderWords]; omega
+ have old (j : ℕ) (hj : j < 30) : atCell m (levelStart L 0) j = m (levelStart L 0+j) := by
+ rw [atCell,Fin.val_natCast,Nat.mod_eq_of_lt (limit _ _ (by omega) (by omega))]
+ have last (j : ℕ) (hj : j < L.shape.scalarFields+6+L.shape.tables) :
+ atCell m (levelStart L prior.length) j = m (levelStart L prior.length+j) := by
+ rw [atCell,Fin.val_natCast,Nat.mod_eq_of_lt (limit _ _ (by omega) (hj.trans_le hspan))]
+ have rd (j : Fin 6) : atCell m (levelStart L prior.length) j.val = (Scalars.values (.terminal a) (Fintype.card Y.Base) g j : Word w) := by
+ rw [atCell,Nat.cast_add]
+ apply Fin.ext
+ have e := current j
+ change (m ((levelStart L prior.length : Word w)+(j.val : Word w)).val).val = _ at e
+ exact e.trans (Nat.mod_eq_of_lt (e ▸ (m ((levelStart L prior.length : Word w)+(j.val : Word w)).val).isLt)).symm
+ have frame (j : Fin 8) : atCell m (levelStart L 0) (6+j.val) = CursorRAM.ScheduleInit.inputs p q baseBits laneBits degree width firstColumn j := by
+ rw [atCell,Nat.cast_add,Nat.cast_add,← add_assoc]
+ exact congrFun saved j
+ refine ⟨workspace,rows,pitch,(old 28 (by decide)).trans (size ▸ levelCount),
+ (old 14 (by decide)).trans arena,(last 14 (by omega)).trans rowStart,rd 0,rd 2,rd 1,?_,?_,?_,frame 4,frame 5⟩
+ · exact (last _ (by omega)).trans (by simpa [fromState,incidenceHead,Nat.add_assoc] using columns 5)
+ · exact (last _ (by omega)).trans (by simpa [fromState,incidenceHead,Nat.add_assoc] using columns 4)
+ · have n := table.isLt
+ exact (last _ (by omega)).trans (by simpa [fromState,tableHead,zero,Nat.add_assoc] using tables)
+
+open LocalHistory
+open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+
+private theorem collect_sizes {a g b n : ℕ} {X : State a g} (E : StateExecution A b n X)
+ (W : E.MapWitnesses f) (r : ExecutionReaders E W) (o : PassOrigins B f hf E) (z : E.Choices) :
+ X.positions :: (collectLevels B f hf E W r o z).map SelectedLevel.outputSites =
+ (collectLevels B f hf E W r o z).map (fun v ↦ v.input.positions) ++ [(E.finalState z).positions] := by
+ induction E with
+ | done => rfl
+ | more p tail ih =>
+ exact congrArg (_ :: ·) (ih z.1 (W.2 z.1) (r.2 z.1) (o.2 z.1) z.2)
+
+variable {n : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+
+/-- Every fixed elementary kernel of every block contributes one level on each
+selected branch. The last header can be located without consulting any choices. -/
+theorem selected_prior_length : (ls).dropLast.length = T*(S.steps+1) := by
+ have counts := congrArg List.length (selected_layer_counts B f hf T hT X z)
+ simp only [List.length_cons,List.length_map] at counts
+ have order := congrArg List.length (executeLevels_order B f hf T hT X z)
+ rw [List.length_map] at order
+ have flat (l : List ℕ) (t : ℕ) : (List.replicate t l).flatten.length = t*l.length := by
+ induction t with
+ | zero => simp
+ | succ t ih => simp [List.replicate_succ,ih,Nat.succ_mul,Nat.add_comm]
+ rw [flat,List.length_range] at order
+ rw [List.length_dropLast,counts,order]; omega
+
+/-- Read the actual number of DFS rows, from the chronological input sites and
+all sites of the terminal state. This includes the zero-block case. -/
+theorem selected_counts : (ls).map Layer.count = (vs).map (fun v ↦ v.input.positions) ++ [(Y).positions] :=
+ (selected_layer_counts B f hf T hT X z).trans (collect_sizes B f hf _ _ _ _ z)
+
+theorem selected_rowWords (L : Layout) (baseBits laneBits : ℕ) (table : Fin L.shape.tables) :
+ (fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) table).rowWords B.recordLimit =
+ words B.recordLimit (ls) := by
+ rw [Header.rowWords,fromState_sites]
+ change words B.recordLimit (ls).dropLast + (Y).positions*(B.recordLimit+2) = _
+ simp only [words,List.map_dropLast,selected_counts B f hf T hT X z,List.dropLast_concat,List.sum_append,
+ List.sum_cons,List.sum_nil,Nat.add_zero,Nat.mul_add]
+ ring
+
+end PairSimulation.TerminalBootstrap
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalSelectedPrefix.lean b/lean/OAI/Computability/VPVNP/PairTerminalSelectedPrefix.lean
new file mode 100644
index 0000000000..9393506c22
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalSelectedPrefix.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.PairTerminalQuietPrefix
+import OAI.Computability.VPVNP.PairTerminalSharedBits
+import OAI.Computability.VPVNP.PairTraversalControllerMemory
+
+/-!
+# Three forced terminal phases on an actual compressed branch
+
+The physical level directories determine the complete deterministic prefix of
+the terminal program. The returned block sequence ends with the selected DFS
+rows and role tags available for the shared-bit and vertex interpreters.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords TerminalLink TerminalPrefix.Linked
+open TraversalRows TraversalRoles TraversalControllerInputs DirectoryRun LocalHistory
+open scoped Fin.CommRing
+
+variable {w lanes : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+
+/-- Native construction and readback of the deterministic part of the actual
+terminal program. The selected placement witnesses are read from the retained
+level directories on the same memory where the preceding prefix scan ended. -/
+theorem selectedQuietPrefix (workers : Stage → LiveProgram.PairTable) (pub : Fin 11 → Word w)
+ (cap fuel base H first pitch : ℕ) (inc : IncidenceDirectory w) (starts : Word w)
+ (input : Memory w) (boot : Report w) (prefixRows : List (Report w))
+ (bank : workers Stage.traversalRows = ⟨_, _, TraversalController.Native.table⟩)
+ (clock₀ : fuel + 30 ≤ cap) (clock₁ : 60 ≤ cap)
+ (clock₂ : TraversalController.callFuel B.recordLimit + 30 ≤ cap) :
+ let Y := (B.execute f hf T hT X).finalState z
+ let src := prefixMemory pub input boot prefixRows
+ let ls := selectedLayers B f hf T hT X z
+ let size := words B.recordLimit ls
+ let off := size+Y.totalWidth
+ let vs := executeLevels B f hf T hT X z
+ let tags := selected B f hf T hT X z
+ let arena := build B.recordLimit base base ls (writeTags off B.recordLimit base tags src)
+ Start workers pub cap fuel Y inc starts input boot prefixRows →
+ ∀ ds : (i : Fin vs.length) → LevelDirectory vs[i] src base,
+ Resident pub src H first pitch off B.recordLimit base ⟨leafLayer (siteOrder X),.cursor⟩
+ (levelFibers vs ds) →
+ (∀ j ≤ vs.length, first+j*pitch+28 ≤ base) →
+ base+2*size+Y.totalWidth ≤ H → 2*tags.length*(X.positions+1) < 2^w →
+ ∃ q : QuietPrefix workers pub cap input,
+ let ready := q.traversalRows.val.memory
+ q.boot.val.choices = [[]] ∧
+ q.prefixRows.val.choices = List.replicate (TerminalPrefix.arcCount Y+1) [] ∧
+ q.traversalRows.val.choices =
+ List.replicate (2*(ls.map Layer.count).sum+2*tags.length+1) [] ∧
+ SourceTransport.Agree (workerCell (header pub)) arena ready ∧
+ (Entry.resume Stage.sharedBits (0 : Word w)).Valid (header pub) ready ∧
+ AllRows w ready B.recordLimit base base ls ∧ Reads w ready off B.recordLimit base tags ∧
+ (∀ x < base, ready x = src x) ∧
+ ∀ j : ℕ, 0 < j → j < 31 → ready (H+j) = src (H+j) := by
+ intro Y src ls size off vs tags arena start ds resident heads below ordinal
+ obtain ⟨ts,rs,out,_,_,seg,_,_,tagOK,rowOK,low,_,reads,_⟩ :=
+ TraversalController.selected_run_with_reads B f hf T hT X z base src ds pub Y.totalWidth
+ H first pitch resident heads below ordinal
+ have wide : 32 ≤ 2^w := by have := resident.headerFits; omega
+ obtain ⟨q,h₀,h₁,h₂,_,agree,valid⟩ := quietPrefixOfRows start clock₀ clock₁ wide bank
+ B.recordLimit _ _ arena out clock₂ seg reads
+ let ready := q.traversalRows.val.memory
+ have head : (header pub).val = H := by
+ change (terminalHead pub).val = H
+ rw [resident.header,Fin.val_natCast,Nat.mod_eq_of_lt (by have := resident.headerFits; omega)]
+ have last : (header pub + 31).val = H+31 := by
+ change ((header pub).val+31%(2^w))%(2^w) = _
+ rw [head,Nat.mod_eq_of_lt (by omega : 31 < 2^w),
+ Nat.mod_eq_of_lt (by have := resident.headerFits; omega)]
+ have data (x : ℕ) (hx : x < H) : workerCell (header pub) x := ⟨by omega,by omega⟩
+ have equal : ControllerMemory.AgreeBelow H ready (after src (eventLog out)) := by
+ intro x hx
+ exact (agree x (data x hx)).symm.trans (congrFun seg.memory.symm x)
+ have tagSize : tagWords B.recordLimit tags = size := by
+ rw [tagWords, show tags.map TaggedLayer.layer = ls from selected_layers B f hf T hT X z]
+ refine ⟨q,h₀,h₁,h₂,agree,valid,ControllerMemory.allRows_below ls equal (by omega)
+ (selected_capacity B f hf T hT X z) rowOK,
+ ControllerMemory.reads_below tags equal (by rw [tagSize]; dsimp only [off]; omega) tagOK,
+ fun x hx => (equal x (hx.trans_le (by omega))).trans (low x hx),?_⟩
+ intro j hj hj'
+ have high : workerCell (header pub) (H+j) := ⟨by omega,by omega⟩
+ apply (agree _ high).symm.trans
+ change build B.recordLimit base base ls (writeTags off B.recordLimit base tags src) _ = _
+ rw [← show tags.map TaggedLayer.layer = ls from selected_layers B f hf T hT X z]
+ simpa only [tagSize,off] using
+ TerminalLayout.arena_above B.recordLimit base Y.totalWidth tags src (H+j)
+ (by rw [tagSize]; omega)
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalSelectedPrefixCosts.lean b/lean/OAI/Computability/VPVNP/PairTerminalSelectedPrefixCosts.lean
new file mode 100644
index 0000000000..8852d714da
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalSelectedPrefixCosts.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.PairTerminalSelectedPrefix
+
+/-! # The first three terminal source charges on every accepted physical trace -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords TerminalLink TerminalPrefix.Linked
+open TraversalRows TraversalRoles TraversalControllerInputs DirectoryRun LocalHistory
+
+variable {w lanes : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+
+/-- Recover the *source* report lists of bootstrap, width-prefix scan and
+both history-directory passes on the same five-stage trace used by the
+live pair. Determinism of the empty-tape phases supplies the equalities
+even when the candidate trace is described using another witness. -/
+theorem selected_prefix_costs (workers : Stage → LiveProgram.PairTable) (pub : Fin 11 → Word w)
+ (cap fuel base H first pitch : ℕ) (inc : IncidenceDirectory w) (starts : Word w)
+ (input : Memory w) (boot : Report w) (prefixRows : List (Report w))
+ (bank : workers Stage.traversalRows = ⟨_,_,TraversalController.Native.table⟩)
+ (clock₂ : TraversalController.callFuel B.recordLimit+30 ≤ cap) :
+ let Y := (B.execute f hf T hT X).finalState z
+ let src := prefixMemory pub input boot prefixRows
+ let ls := selectedLayers B f hf T hT X z
+ let size := words B.recordLimit ls
+ let off := size+Y.totalWidth
+ let vs := executeLevels B f hf T hT X z
+ let tags := selected B f hf T hT X z
+ Start workers pub cap fuel Y inc starts input boot prefixRows →
+ ∀ ds : (i : Fin vs.length) → LevelDirectory vs[i] src base,
+ Resident pub src H first pitch off B.recordLimit base ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers vs ds) →
+ (∀ j ≤ vs.length, first+j*pitch+28 ≤ base) →
+ base+2*size+Y.totalWidth ≤ H → 2*tags.length*(X.positions+1) < 2^w →
+ ∀ t : FiveTrace workers pub cap input,
+ t.bootstrap.logs.map Prod.snd = [boot] ∧
+ TerminalPrefix.Segment.Run pub Y inc starts (after input boot.events) (t.prefixRows.logs.map Prod.snd) ∧
+ RAMBuckets.cost Report.probes (t.traversalRows.logs.map Prod.snd) ≤
+ (2*B.recordLimit+1294)*(((S.steps+1)*T+1)*X.positions) ∧
+ ∀ r ∈ t.traversalRows.logs.map Prod.snd, r.probes ≤ r.events.length ∧
+ r.events.length < TraversalController.callFuel B.recordLimit := by
+ intro Y src ls size off vs tags start ds resident heads below ordinal t
+ obtain ⟨_,_,out,_,_,seg,cost,per,_,_,_,_,reads,_⟩ :=
+ TraversalController.selected_run_with_reads B f hf T hT X z base src ds pub Y.totalWidth
+ H first pitch resident heads below ordinal
+ have wide : 32 ≤ 2^w := by have := resident.headerFits; omega
+ obtain ⟨_,bootLogs,_,_,prefixLogs,mem⟩ := start.force t
+ have cand := t.rowRun
+ rw [mem] at cand
+ obtain ⟨_,known,_⟩ := TraversalController.linked_stage workers pub bank seg reads clock₂ wide
+ start.handoff_rows.2 (fun _ _ => rfl)
+ obtain ⟨_,arenaLogs,_⟩ := known.force_quiet (fun _ h => List.eq_of_mem_replicate h) cand
+ rw [bootLogs,prefixLogs,arenaLogs,stageLogs_raw,stageLogs_raw]
+ exact ⟨rfl,start.rawScan,cost,per⟩
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalSelectedReady.lean b/lean/OAI/Computability/VPVNP/PairTerminalSelectedReady.lean
new file mode 100644
index 0000000000..dbf552b13b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalSelectedReady.lean
@@ -0,0 +1,214 @@
+import OAI.Computability.VPVNP.CompressorSelectedDirectoryHistory
+import OAI.Computability.VPVNP.PairTerminalSelectedHeaders
+import OAI.Computability.VPVNP.PairTerminalPrefixLinked
+import OAI.Computability.VPVNP.PairTerminalPrefixBudget
+import OAI.Computability.VPVNP.PairSimulationTerminalProgram
+
+/-!
+# Entering the terminal program after a selected compression schedule
+
+The final level is indexed by the number of executed elementary passes. Its
+published scalar 14 counts exactly the traversal rows before the final layer.
+Agreement on the level - data suffix carries the selected headers and final
+incidence columns from the raw calendar walk to its physical output memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalBootstrap
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles LocalHistory
+open scoped Fin.CommRing
+
+variable {w : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ}
+variable (T : ℕ) (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+
+/-- The last level index agrees with the retained directory history, including
+when there are no compression blocks. -/
+theorem selected_last_index : (ls).dropLast.length = (vs).length := by
+ simp only [← selected_layers B f hf T hT X z, selected, List.length_dropLast, List.length_map,
+ List.length_cons, Nat.add_sub_cancel]
+
+theorem selected_last_base (base : ℕ) : layerBase B.recordLimit base (tags) (ls).dropLast.length =
+ base + words B.recordLimit (ls).dropLast := by
+ rw [layerBase, List.map_take, selected_layers B f hf T hT X z, List.length_dropLast,
+ List.dropLast_eq_take]
+
+/-- Reconstruct the bootstrap operands in the physical online output memory
+from the final raw scalar and pointer publications and the retained row - base
+fields. The row - count and pitch control words come from the online run. -/
+theorem selected_ready (L : Layout) (baseBits laneBits : ℕ) (tab : Fin L.shape.tables)
+ (zero : tab.val = 0) (pub : Fin 11 → Word w) (raw phy : Memory w)
+ (workspace : (pub 2).val = L.base) (rows : phy (pub 2 + 8).val = (directoryRows L : Word w))
+ (pitch : phy (pub 2 + ((10 + L.shape.arity : ℕ) : Word w)).val = (levelWords L : Word w))
+ (size : L.levels = T * (S.steps + 1) + 1) (wide : 30 ≤ L.shape.scalarFields)
+ (fit : endAddress L < 2 ^ w)
+ (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) raw phy)
+ (levelCount : raw (levelStart L 0 + 28) = (L.levels : Word w))
+ (history : SelectedDirectoryHistory.Retained B f hf T hT X z L (endAddress L) raw)
+ (current : Scalars.Present (.terminal (S.degreeExponent 0)) (Fintype.card (Y).Base)
+ (n - T * S.laneBits) (levelStart L (ls).dropLast.length : Word w) raw)
+ (columns : ∀ c : Fin 6, raw (incidenceHead L (ls).dropLast.length c) =
+ (incidenceBase L (ls).dropLast.length ((Y).positions * 2 ^ (S.degreeExponent 0)) c : Word w))
+ (table : raw (tableHead L (ls).dropLast.length tab) =
+ (tableBase L (ls).dropLast.length tab : Word w))
+ (p q : Word w) (degree width firstColumn : ℕ)
+ (saved : Frame.data ((levelStart L 0 : Word w) + 6) raw =
+ CursorRAM.ScheduleInit.inputs p q baseBits laneBits degree width firstColumn) :
+ Ready L (ls).dropLast.length
+ (fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab) pub phy := by
+ let last := (ls).dropLast.length
+ have heads (j : ℕ) (hj : j ≤ (vs).length) : raw (levelStart L j + 14) =
+ (layerBase B.recordLimit (endAddress L) (tags) j : Word w) := history.current j hj
+ have size' : L.levels = last + 1 :=
+ size.trans (congrArg (· + 1) (selected_prior_length B f hf T hT X z).symm)
+ have bound (i j : ℕ) (hi : i < L.levels) (hj : j < levelWords L) : levelStart L i + j < 2 ^ w :=
+ (show levelStart L i + j < levelStart L (i + 1) by simp [levelStart, Nat.succ_mul]; omega).trans
+ (level_room L fit ⟨i, hi⟩)
+ have below (i j : ℕ) : levelStart L 0 ≤ levelStart L i + j :=
+ (levelStart_mono L (Nat.zero_le i)).trans (Nat.le_add_right ..)
+ have cell (i j : ℕ) (hi : i < L.levels) (hj : j < levelWords L) :
+ phy ((levelStart L i : Word w) + (j : Word w)).val =
+ raw ((levelStart L i : Word w) + (j : Word w)).val := by
+ rw [← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt (bound i j hi hj)]
+ exact (agree _ (below i j)).symm
+ have span : L.shape.scalarFields ≤ levelWords L := by
+ simp only [levelWords, levelHeaderWords]; omega
+ refine ready_of_published L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab zero pub phy
+ workspace rows pitch size' wide fit ?_ ?_ ?_ ?_ ?_ ?_ p q degree width firstColumn ?_
+ · exact (agree _ (below 0 28)).symm.trans levelCount
+ · rw [← agree _ (below 0 14), heads 0 (Nat.zero_le _), layerBase_zero]
+ · rw [← agree _ (below last 14), heads _ (selected_last_index B f hf T hT X z).le,
+ selected_last_base B f hf T hT X z]
+ · intro j
+ change (phy ((levelStart L last : Word w) + (j.val : Word w)).val).val = _
+ rw [cell last j.val (by omega) (by have := j.isLt; omega)]
+ exact current j
+ · intro c
+ have lo : levelStart L 0 ≤ incidenceHead L last c := by
+ simpa only [incidenceHead, Nat.add_assoc] using below last (L.shape.scalarFields + c.val)
+ exact (agree _ lo).symm.trans (columns c)
+ · have lo : levelStart L 0 ≤ tableHead L last tab := by
+ simpa only [tableHead, Nat.add_assoc] using below last (L.shape.scalarFields + 6 + tab.val)
+ exact (agree _ lo).symm.trans table
+ · funext j
+ have mem : phy (((levelStart L 0 : Word w) + 6) + (j.val : Word w)).val =
+ raw (((levelStart L 0 : Word w) + 6) + (j.val : Word w)).val := by
+ simpa only [Nat.cast_add, Nat.cast_ofNat, add_assoc] using
+ cell 0 (6 + j.val) (by omega) (by have := j.isLt; omega)
+ exact mem.trans (congrFun saved j)
+
+end PairSimulation.TerminalBootstrap
+
+namespace PairSimulation.TerminalPrefix.Linked
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace LocalHistory TraversalRows
+open TerminalBootstrap TerminalLink
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Transfer the actual edge columns along the same level-data agreement as the
+header publications. Each address is in the packed suffix, even for parallel
+arcs and fixed loops. -/
+theorem packed_actual_online {a g : ℕ} (L : Layout) (last : Fin L.levels) (Y : State a g)
+ (slots : arcCount Y ≤ slotCapacity L) (fit : endAddress L < 2 ^ w) (raw phy : Memory w)
+ (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) raw phy)
+ (old : (packedIncidence L w last (arcCount Y)).ActualColumns Y raw) :
+ (packedIncidence L w last (arcCount Y)).ActualColumns Y phy := by
+ let T := packedIncidence L w last (arcCount Y)
+ have low (c : Fin 6) (e : Y.network.Edge) :
+ levelStart L 0 ≤ (T.column c + IncidenceDirectory.actualPort Y e).val := by
+ let i := (edgeOrder Y).entries.symm e
+ have bounds := incidence_bounds L last (arcCount Y) slots c i
+ have top := packed_incidence_room L fit last slots
+ have small : incidenceBase L last (arcCount Y) c + i.val < 2 ^ w := by
+ have h := Nat.mul_le_mul_right (arcCount Y) c.isLt
+ rw [Nat.succ_mul] at h
+ have hi : i.val < arcCount Y := i.isLt
+ unfold incidenceBase
+ omega
+ rw [packed_column, actualPort_eq]
+ change levelStart L 0 ≤
+ (incidenceBase L last (arcCount Y) c % (2 ^ w) + i.val % (2 ^ w)) % (2 ^ w)
+ rw [Nat.mod_eq_of_lt (by omega : incidenceBase L last (arcCount Y) c < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega : i.val < 2 ^ w), Nat.mod_eq_of_lt small]
+ exact (levelStart_mono L (Nat.zero_le last.val)).trans
+ ((Nat.le_add_right .. : levelStart L last ≤ incidenceStart L last).trans bounds.1)
+ exact ⟨fun e => (agree _ (low 3 e)).symm.trans (old.actualOut e),
+ fun e => (agree _ (low 4 e)).symm.trans (old.actualIn e),
+ fun e => (agree _ (low 5 e)).symm.trans (old.width e)⟩
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ}
+variable (T : ℕ) (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+
+/-- The actual five-stage terminal table, started in the post-calendar physical
+memory, builds every offset and the role displacement for this selected branch. -/
+theorem run_selected (L : Layout) (baseBits laneBits : ℕ) (tab : Fin L.shape.tables)
+ (segments : VertexImage.Part → VertexImage.Segment) (r cap : ℕ)
+ (pub : Fin 11 → Word w) (raw phy : Memory w) (size : L.levels = T * (S.steps + 1) + 1)
+ (ready : Ready L (ls).dropLast.length
+ (fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab) pub phy)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ L.base + 2 ^ r * 2 ^ r)
+ (room : L.base + 2 ^ r * 2 ^ r ≤ 2 ^ w)
+ (above : endAddress L ≤ TerminalBootstrap.address L.base r)
+ (slots : arcCount (Y) ≤ slotCapacity L) (cells : arcCount (Y) ≤ tableWords L)
+ (totalFit : (Y).totalWidth < 2 ^ w)
+ (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) raw phy)
+ (old : (packedIncidence L w (ls).dropLast.length (arcCount (Y))).ActualColumns (Y) raw)
+ (clock₀ : TerminalBootstrap.cost L.shape B.recordLimit + 1 + 30 ≤ cap) (clock₁ : 60 ≤ cap) :
+ let last := (ls).dropLast.length
+ let rawBoot := TerminalBootstrap.report L.shape B.recordLimit pub 0 phy
+ let D := packedIncidence L w last (arcCount (Y))
+ let workers := TerminalProgram.workers L.shape B.recordLimit segments
+ ∃ rs, Start workers pub cap (TerminalBootstrap.cost L.shape B.recordLimit + 1) (Y) D
+ (tableBase L last tab) phy rawBoot rs ∧
+ prefixMemory pub phy rawBoot rs (header pub + 14).val =
+ ((words B.recordLimit (ls) + (Y).totalWidth : ℕ) : Word w) := by
+ have len := selected_prior_length B f hf T hT X z
+ let last : Fin L.levels := ⟨(ls).dropLast.length, by omega⟩
+ let A := fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab
+ have fit : endAddress L < 2 ^ w := by unfold TerminalBootstrap.address at above; omega
+ have arcs := Segment.arc_count_positions (Y)
+ have sites : A.sites * A.degree = arcCount (Y) := by
+ rw [show A.sites = (Y).positions from fromState_sites .., arcs]
+ rfl
+ have wh : A.widthHead = incidenceBase L last (arcCount (Y)) 5 := by rw [arcs]; rfl
+ obtain ⟨rs, start, role⟩ := run_packed (TerminalProgram.workers L.shape B.recordLimit segments)
+ L last tab A B.recordLimit r cap rfl rfl pub phy (Y) ready exp hr reserve room above
+ sites wh rfl slots cells totalFit (packed_actual_online L last (Y) slots fit raw phy agree old)
+ clock₀ clock₁
+ have hv := header_val L pub r ready.workspace exp hr reserve room
+ have fitH : (header pub).val + 32 ≤ 2 ^ w := by rw [hv, TerminalBootstrap.address]; omega
+ have H14 : (header pub + 14).val = (header pub).val + 14 := by
+ change ((header pub).val + 14 % (2 ^ w)) % (2 ^ w) = _
+ rw [Nat.mod_eq_of_lt (by omega : 14 < 2 ^ w), Nat.mod_eq_of_lt (by omega)]
+ have H31 : (header pub + 31).val = (header pub).val + 31 := by
+ change ((header pub).val + 31 % (2 ^ w)) % (2 ^ w) = _
+ rw [Nat.mod_eq_of_lt (by omega : 31 < 2 ^ w), Nat.mod_eq_of_lt (by omega)]
+ have cell : workerCell (header pub) (header pub + 14).val := by
+ unfold workerCell
+ rw [H14, H31]
+ omega
+ refine ⟨rs, start, (start.handoff_rows.1 _ cell).symm.trans ?_⟩
+ exact role.trans (congrArg (fun d : ℕ => ((d + (Y).totalWidth : ℕ) : Word w))
+ (selected_rowWords B f hf T hT X z L baseBits laneBits tab))
+
+end PairSimulation.TerminalPrefix.Linked
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalSelectedStartCharges.lean b/lean/OAI/Computability/VPVNP/PairTerminalSelectedStartCharges.lean
new file mode 100644
index 0000000000..5f7e78aad3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalSelectedStartCharges.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.PairTerminalPackedPrefix
+import OAI.Computability.VPVNP.PairTerminalPreludeBudget
+import OAI.Computability.VPVNP.LiveCompressedPairPreludeCosts
+
+/-!
+# Charges on the terminal trace reached from the detailed descriptor boundary
+
+The bootstrap, prefix and traversal reports are taken from the same accepted
+terminal trace. Their bounds use the fixed bootstrap table and record limit,
+even when the selected calendar length and its resident directories vary.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TerminalPrefix TerminalPrefix.Linked TerminalLink
+open scoped Fin.CommRing
+
+variable {w lanes : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "rowsSize" => words B.recordLimit (ls)
+local notation "last" => List.length (List.dropLast (ls))
+
+variable (positions baseBits laneBits initialWidth inputN : ℕ) (pub : Fin 11 → Word w)
+set_option quotPrecheck false in
+local notation "L" => BlockProgram.layout B (pub 2).val positions T
+set_option quotPrecheck false in
+local notation "tab" => (⟨0,by change 0 < 6; decide⟩ : Fin (L).shape.tables)
+local notation "saved" => CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L))
+ (CursorRAM.encode w 1) baseBits laneBits (S.degreeExponent 0) initialWidth (incidenceStart L 0)
+
+theorem packed_prefix_costs (data : SelectedPayloadHistory.Data (w := w) B f hf)
+ (segments : VertexImage.Part → VertexImage.Segment) (r cap : ℕ) (m phy : Memory w)
+ (boundary : ScheduledTrace.Boundary
+ (DetailedResident.resident B f hf ⟨leafLayer (siteOrder X), .cursor⟩ L (endAddress L) inputN saved data)
+ pub (levelWords L : Word w) (directoryRows L) (directoryRows L) (vs) (Y) m)
+ (handoff : SourceTransport.Agree ((pub 2).val+6 ≤ ·) m phy)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ (L).base+2^r*2^r)
+ (room : (L).base+2^r*2^r ≤ 2^w)
+ (below : endAddress L + 2*rowsSize + (Y).totalWidth ≤ TerminalBootstrap.address (L).base r)
+ (ordinal : 2*(tags).length*(X.positions+1) < 2^w)
+ (slots : arcCount (Y) ≤ slotCapacity L) (cells : arcCount (Y) ≤ tableWords L)
+ (totalFit : (Y).totalWidth < 2^w)
+ (clock₀ : TerminalBootstrap.cost (L).shape B.recordLimit+1+30 ≤ cap) (clock₁ : 60 ≤ cap)
+ (clock₂ : TraversalController.callFuel B.recordLimit+30 ≤ cap)
+ (t : FiveTrace (workers (L).shape B.recordLimit segments) pub cap phy) :
+ Nonempty (LiveProgram.CompressedPair.PreludeCosts X (Y) pub t S.steps B.recordLimit T
+ (TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit+1)) := by
+ let boot := TerminalBootstrap.report (L).shape B.recordLimit pub 0 phy
+ have above : endAddress L ≤ TerminalBootstrap.address (L).base r := by omega
+ obtain ⟨⟨history⟩,ready,rs,start,_⟩ := run_boundary B f hf T hT X z positions baseBits laneBits
+ initialWidth inputN pub segments r cap m phy (DetailedResident.currentBoundary boundary)
+ handoff exp hr reserve room above slots cells totalFit clock₀ clock₁
+ let src := prefixMemory pub phy boot rs
+ let hdr := TerminalBootstrap.fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab
+ have wide : 28 ≤ (L).shape.scalarFields := by change 28 ≤ 54; decide
+ have hl : last < (L).levels := by
+ rw [TerminalBootstrap.selected_prior_length,BlockProgram.actual_level_count,Nat.mul_comm T]; omega
+ have fields := TraversalResidentHandoff.fields_of_start L last hl tab hdr B.recordLimit r (Y)
+ pub phy src ready exp hr reserve room above wide cells rs start start.handoff_rows.1
+ have retained := TraversalResidentHandoff.selected_resident B f hf T hT X z
+ L baseBits laneBits tab history fields hl wide
+ let ds := retained.choose
+ have stored := retained.choose_spec.2.1
+ have heads := retained.choose_spec.2.2
+ have ⟨initialRow,scan,total,each⟩ := selected_prefix_costs B f hf T hT X z _ pub cap _
+ (endAddress L) (TerminalBootstrap.address (L).base r) (levelStart L 0) (levelWords L) _ _ phy boot rs
+ rfl clock₂ start ds stored heads below ordinal t
+ have work := (execute_spec start.bootCall).1.length_lt
+ change boot.events.length < TerminalBootstrap.cost (L).shape B.recordLimit+1 at work
+ rw [TerminalLayout.packed_bootCost] at work
+ exact ⟨⟨boot,initialRow,work.le,_,_,_,scan,total,each⟩⟩
+
+end PairSimulation.TerminalProgram
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TerminalPrefix TerminalLink CursorBounds CursorNetwork Filter
+open LiveProgram.PairStages.Group.CompressedPaths (publicWords fuel)
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+set_option exponentiation.threshold 10000 in
+/-- At a threshold fixed before the scalar assignment and the descriptor path,
+each accepted terminal trace has its charged prefix on the physical memory at
+the end of that path. The worker code is the fixed allocation-shape bank. -/
+theorem eventually_packed_prefix_costs (B : S.Templates) (u : PairExponents B.growthConstant)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hstart : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop, ∀ (G : LiveProgram.PairStages.Group)
+ (_ : G.w = wordBits b n) (_ : ((publicWords G) 2).val = start n)
+ (_ : ((publicWords G) 7).val = addressBits b n) (_ : n^10000 ≤ G.clock)
+ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n*S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let L := BlockProgram.layout B ((publicWords G) 2).val X.positions T
+ let E := B.execute f hf T hT X
+ let cap := LiveProgram.CompressedPair.clockAt (publicWords G) (fuel G) LiveProgram.CompressedPair.Stage.terminal
+ ∀ (z : E.Choices) (baseBits laneBits initialWidth inputN : ℕ)
+ (data : SelectedPayloadHistory.Data (w := G.w) B f hf)
+ (segments : VertexImage.Part → VertexImage.Segment) (m phy : Memory G.w),
+ let saved := CursorRAM.ScheduleInit.inputs (CursorRAM.encode G.w (directoryBase L))
+ (CursorRAM.encode G.w 1) baseBits laneBits (S.degreeExponent 0) initialWidth (incidenceStart L 0)
+ ScheduledTrace.Boundary
+ (DetailedResident.resident B f hf ⟨leafLayer (siteOrder X), .cursor⟩ L (endAddress L) inputN saved data)
+ (publicWords G) (levelWords L : Word G.w) (directoryRows L) (directoryRows L)
+ (executeLevels B f hf T hT X z) (E.finalState z) m →
+ SourceTransport.Agree (((publicWords G) 2).val+6 ≤ ·) m phy →
+ ∀ t : FiveTrace (workers (BlockProgram.allocationShape B) B.recordLimit segments) (publicWords G) cap phy,
+ Nonempty (LiveProgram.CompressedPair.PreludeCosts X (E.finalState z) (publicWords G) t
+ S.steps B.recordLimit T (TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit+1)) := by
+ filter_upwards [TerminalLayout.eventually_preludeRoom B u b hb hstart] with n fit
+ intro G hw baseWord exp clock base lanes labels hD hT A _ f hf X T L E cap z baseBits laneBits
+ initialWidth inputN data segments m phy saved boundary handoff t
+ have geometry := fit labels hD hT A f hf z G clock
+ dsimp only at geometry
+ rw [← baseWord,← hw] at geometry
+ obtain ⟨hr,reserve,room,below,ordinal,slots,cells,totalFit,clock₀,clock₁,clock₂⟩ := geometry
+ have bank := TerminalLayout.packed_workers B ((publicWords G) 2).val X.positions T segments
+ revert t
+ change ∀ t : FiveTrace (workers (BlockProgram.allocationShape B) B.recordLimit segments) _ cap phy,
+ Nonempty (LiveProgram.CompressedPair.PreludeCosts X (E.finalState z) (publicWords G) t S.steps B.recordLimit T
+ (TerminalBootstrap.cost (BlockProgram.allocationShape B) B.recordLimit+1))
+ rw [← bank]
+ exact packed_prefix_costs B f hf T hT X z X.positions baseBits laneBits initialWidth inputN
+ (publicWords G) data segments (addressBits b n) cap m phy boundary handoff exp hr reserve room below
+ ordinal slots cells totalFit clock₀ clock₁ clock₂
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalShadowChronology.lean b/lean/OAI/Computability/VPVNP/PairTerminalShadowChronology.lean
new file mode 100644
index 0000000000..8707156fe7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalShadowChronology.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.PairTerminalShadowTransfer
+import OAI.Computability.VPVNP.LiveCompressedPairStartupFootprint
+import OAI.Computability.VPVNP.CompressorSourceBankFrame
+
+/-!
+# The prepared shadow at the terminal handoff
+
+The eight startup reports preserve cells below the compression workspace,
+apart from the pair tag. The framed online reports have the memory effect of
+their raw calendar reports. Their low-cell frame and the separate tag write
+at handoff preserve both the histogram descriptor and each shadow word read
+by the terminal evaluator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM CompressorRecords Schedule LiveStageLink
+
+variable {w d initial phases : ℕ} {C : Catalog d}
+
+/-- Online's incoming memory after the actual eight startup calls. -/
+noncomputable abbrev afterStartup (b : Bootstrap) (pub : Fin 11 → Word w) (B n : ℕ)
+ (m : Memory w) (initial phases d : ℕ) :=
+ after m (eventLog (cursorStartupLogs b pub B n (pub 2).val m initial phases d))
+
+/-- A protected address below the startup workspace survives the raw online
+calendar, its six-pointer framing, and the transfer to the terminal stage. -/
+theorem onlinePost_after_startup_below (b : Bootstrap) (plan : Online.Config C initial phases)
+ (finalTable : PairTable) (pub : Fin 11 → Word w) (B n : ℕ) (m : Memory w)
+ (runs : TransferredStartup.Runs (bootstrapRows b initial phases) d
+ (startupLayout b initial phases B n (pub 2).val) B n b.degreeBits b.lanesPerBlock b.steps pub
+ (PairTag.address pub) m)
+ {clock : ℕ} (a : StagePaths b plan finalTable pub clock Stage.online (afterStartup b pub B n m initial phases d))
+ (rs : List (Report w))
+ (reported : ordinaryReports a = OnlineWorkspace.framed (pub 2) (afterStartup b pub B n m initial phases d) rs)
+ (stable : SourceBankFrame.Stable ((pub 2).val+6) (afterStartup b pub B n m initial phases d) rs)
+ (x : ℕ) (below : x < (pub 2).val) (apart : x ≠ (PairTag.address pub).val) :
+ onlinePost a x = m x := by
+ let start := afterStartup b pub B n m initial phases d
+ have raw : after start (eventLog rs) x = start x := by
+ simpa only [List.take_length] using stable.take_eq rs.length x (by omega)
+ rw [onlinePost, show next Stage.online = some Stage.terminal from rfl, transferMemory, writeMemory, ite_eq_right apart,
+ reported, (OnlineWorkspace.framed_effect (pub 2) start rs none).2.1, raw]
+ exact cursorStartup_after_below b pub B n (pub 2).val m runs x below apart
+
+end LiveProgram.CompressedPair
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM PrimedInputRAM LiveAuxiliaryHeaders PairSimulation CompressorRecords Schedule LiveStageLink
+open scoped Fin.CommRing
+
+/-- The pair tag is the first old-state word, strictly before the shadow. -/
+theorem pairTag_lt_shadow (G : Group) (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w) :
+ (PairTag.address (terminalOperands G)).val < (terminalOperands G 3).val := by
+ have low : (Layout.oldState G.constants).eval G.g < shadowBase G := by
+ simp only [shadowBase,Layout.shadow,Layout.orderMap,Layout.packedPrefix,Layout.adviceFrames,
+ Layout.transitionScratch,Layout.newState,eval_add]
+ change _ < _ + _ + _ + 5 + 24 + _ + _
+ omega
+ have high : shadowBase G ≤ (Layout.pairWorkspace G.constants).eval G.g := by
+ change _ ≤ shadowBase G + _
+ omega
+ rw [CompressedPair.tag_address]
+ exact lt_of_eq_of_lt (Nat.mod_eq_of_lt (low.trans (high.trans_lt fit)))
+ (lt_of_lt_of_eq low (Nat.mod_eq_of_lt (high.trans_lt fit)).symm)
+
+/-- A virtual header fitting the number of virtual sites ends before the
+online workspace. The address-fit hypothesis recovers the natural addresses
+from their machine-word representations. -/
+theorem shadow_span_room (G : Group) (i : Fin (2^(sizes G).h))
+ (hn : 1 ≤ G.g.n) (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w)
+ (capacity : span (pairLengths G i) (histLength G) ≤ 2^(virtualSiteExponent G.g.d G.g.n)) :
+ (terminalOperands G 3).val+span (pairLengths G i) (histLength G) ≤ (terminalOperands G 2).val := by
+ have total : (Layout.pairWorkspace G.constants).eval G.g =
+ shadowBase G + 2^(virtualSiteExponent G.g.d G.g.n) := by
+ change shadowBase G + 2^(Layout.virtualSiteBits.eval G.g) = _
+ rw [Layout.virtualSiteBits_eq G.g hn]
+ have shadowFit : shadowBase G < 2^G.w := by omega
+ have shadowVal : (terminalOperands G 3).val = shadowBase G := Nat.mod_eq_of_lt shadowFit
+ have workspaceVal : (terminalOperands G 2).val = (Layout.pairWorkspace G.constants).eval G.g := Nat.mod_eq_of_lt fit
+ rw [shadowVal, workspaceVal, total]
+ exact Nat.add_le_add_left capacity _
+
+variable {G : Group} {m : Memory G.w} {i : Fin (2^(sizes G).h)}
+ {hdr : Header (pairLengths G i) → Bool}
+ {N : Indexed G Stage.nominations m (Nominations.Nom G)} {μ : Nominations.Nom G}
+ {d initial phases : ℕ} {C : Catalog d} {b : CompressedPair.Bootstrap}
+ {plan : Online.Config C initial phases} {finalTable : PairTable} {clock : ℕ}
+
+variable (B : PreparedBranch G m i hdr N μ) (blocks n : ℕ)
+variable (runs : TransferredStartup.Runs (CompressedPair.bootstrapRows b initial phases) d
+ (CompressedPair.startupLayout b initial phases blocks n (terminalOperands G 2).val)
+ blocks n b.degreeBits b.lanesPerBlock b.steps (terminalOperands G)
+ (PairTag.address (terminalOperands G)) (B.copy.memory ()))
+variable (a : CompressedPair.StagePaths b plan finalTable (terminalOperands G) clock CompressedPair.Stage.online
+ (CompressedPair.afterStartup b (terminalOperands G) blocks n (B.copy.memory ()) initial phases d))
+variable (rs : List (Report G.w))
+variable (reported : ordinaryReports a = OnlineWorkspace.framed (terminalOperands G 2)
+ (CompressedPair.afterStartup b (terminalOperands G) blocks n (B.copy.memory ()) initial phases d) rs)
+variable (stable : SourceBankFrame.Stable ((terminalOperands G 2).val+6)
+ (CompressedPair.afterStartup b (terminalOperands G) blocks n (B.copy.memory ()) initial phases d) rs)
+
+include runs reported stable in
+/-- The terminal bootstrap computes the original header and histogram span
+on the actual post-memory of the completed online path. -/
+theorem PreparedBranch.shadowSpan_onlinePost
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w) :
+ TerminalBootstrap.shadowSpan (terminalOperands G) (CompressedPair.onlinePost a) =
+ ((span (pairLengths G i) (histLength G) : ℕ) : Word G.w) := by
+ apply B.shadowSpan_of_cell
+ exact CompressedPair.onlinePost_after_startup_below b plan finalTable (terminalOperands G)
+ blocks n _ runs a rs reported stable _ (histogramTarget_lt_workspace G fit) (histogramCell_lt_tag G fit).ne
+
+include runs reported stable in
+/-- Every populated or padded word within the shadow span reads as the
+original auxiliary header or histogram at the terminal handoff. -/
+theorem PreparedBranch.shadowRead_onlinePost
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w)
+ (room : (terminalOperands G 3).val+span (pairLengths G i) (histLength G) ≤ (terminalOperands G 2).val)
+ (j : ℕ) (hj : j < span (pairLengths G i) (histLength G)) :
+ CompressedPair.onlinePost a ((terminalOperands G 3).val+j) =
+ headerMemory (pairLengths G i) hdr (histogram G μ) j := by
+ have before := pairTag_lt_shadow G fit
+ exact (CompressedPair.onlinePost_after_startup_below b plan finalTable (terminalOperands G)
+ blocks n _ runs a rs reported stable _ (by omega) (by omega)).trans (B.shadowRead j)
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalShadowSpan.lean b/lean/OAI/Computability/VPVNP/PairTerminalShadowSpan.lean
new file mode 100644
index 0000000000..973eb27423
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalShadowSpan.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.LiveProgramPairPreparation
+import OAI.Computability.VPVNP.PairTraversalTerminalBootstrap
+
+/-! # The auxiliary header length recovered by the terminal pair program
+
+The histogram target is the third word of the seventh auxiliary descriptor.
+Subtracting the shadow base from that target recovers the reserved bit-header
+length, including both padded exterior cuts. The pair operand supplying the
+histogram length completes the span used to bound a leaf's external read.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM PrimedInputRAM LiveAuxiliaryHeaders PairSimulation
+open scoped Fin.CommRing
+
+/-- The eleven public words supplied to the terminal pair program. -/
+abbrev terminalOperands (G : Group) := Pieces.word G.g G.lit ∘ StageOperands.pair G.constants
+
+/-- The word preceding the counter base is the histogram's descriptor target. -/
+theorem histogramTargetAddress (G : Group) :
+ terminalOperands G 4 - 1 = LiveHeaderCopyDispatch.address (desc G) 6 2 := by
+ change ((counterBase G : ℕ) : Word G.w) - 1 = ((tableBase G : ℕ) : Word G.w) + 20
+ rw [← (geometry_order G).2.2.1, Nat.cast_add, Nat.cast_ofNat]
+ ring
+
+variable {G : Group} {m : Memory G.w} {i : Fin (2^(sizes G).h)}
+ {hdr : Header (pairLengths G i) → Bool}
+ {N : Indexed G Stage.nominations m (Nominations.Nom G)} {μ : Nominations.Nom G}
+
+/-- Actual word computed by the eleven-operand terminal bootstrap on the
+memory returned by the native auxiliary initializer and copy sweep. -/
+theorem PreparedBranch.shadowSpan (B : PreparedBranch G m i hdr N μ) :
+ TerminalBootstrap.shadowSpan (terminalOperands G) (B.copy.memory ()) =
+ ((span (pairLengths G i) (histLength G) : ℕ) : Word G.w) := by
+ unfold TerminalBootstrap.shadowSpan
+ rw [histogramTargetAddress, B.descriptorFrame, B.copyPrepared.descriptors.targets]
+ change (((shadow G).val + Header.count (pairLengths G i) : ℕ) : Word G.w) - shadow G +
+ (histLength G : Word G.w) = ((Header.count (pairLengths G i) + histLength G : ℕ) : Word G.w)
+ rw [Nat.cast_add, Nat.cast_add]
+ have word : ((shadow G).val : Word G.w) = shadow G := Fin.cast_val_eq_self _
+ rw [word]
+ abel
+
+/-- The histogram descriptor is strictly below the compression workspace. -/
+theorem histogramTarget_lt_workspace (G : Group)
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w) :
+ (terminalOperands G 4 - 1).val < (terminalOperands G 2).val := by
+ have hw : (terminalOperands G 2).val = (Layout.pairWorkspace G.constants).eval G.g :=
+ Nat.mod_eq_of_lt fit
+ have hp : shadowBase G ≤ (Layout.pairWorkspace G.constants).eval G.g := by
+ change _ ≤ shadowBase G + _
+ omega
+ obtain ⟨_,_,he,hs⟩ := geometry_order G
+ rw [histogramTargetAddress, hw]
+ have hd : (desc G).val = tableBase G := Nat.mod_eq_of_lt (show tableBase G < 2^G.w by omega)
+ rw [LiveAuxiliaryDescriptorInit.address_val _ (by omega), hd]
+ change tableBase G + 20 < _
+ omega
+
+/-- Changes confined to the compression workspace preserve the recovered span. -/
+theorem PreparedBranch.shadowSpan_of_frame (B : PreparedBranch G m i hdr N μ)
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w) {mem : Memory G.w}
+ (frame : ∀ a < (terminalOperands G 2).val, mem a = B.copy.memory () a) :
+ TerminalBootstrap.shadowSpan (terminalOperands G) mem =
+ ((span (pairLengths G i) (histLength G) : ℕ) : Word G.w) := by
+ rw [← B.shadowSpan]
+ unfold TerminalBootstrap.shadowSpan
+ rw [frame _ (histogramTarget_lt_workspace G fit)]
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalShadowTransfer.lean b/lean/OAI/Computability/VPVNP/PairTerminalShadowTransfer.lean
new file mode 100644
index 0000000000..5e5a6771ae
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalShadowTransfer.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.PairTerminalShadowSpan
+import OAI.Computability.VPVNP.LiveProgramCompressedPair
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-! # Preservation of the histogram descriptor through actual pair-stage transfers
+
+A completed native stage can write the pair tag below the workspace. The
+tag follows the grammar and motif counter arrays, whereas the auxiliary
+histogram descriptor immediately precedes those arrays. Thus neither a tag
+transfer nor a write in the compression workspace changes the shadow length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM PrimedInputRAM LiveAuxiliaryHeaders PairSimulation
+open CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+/-- Physical address of the auxiliary histogram descriptor's target word. -/
+abbrev histogramCell (G : Group) := (terminalOperands G 4 - 1).val
+
+theorem histogramCell_lt_tag (G : Group)
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w) :
+ histogramCell G < (PairTag.address (terminalOperands G)).val := by
+ have hp : shadowBase G ≤ (Layout.pairWorkspace G.constants).eval G.g := by
+ change _ ≤ shadowBase G + _
+ omega
+ have hcs := counter_end_le_shadow G
+ obtain ⟨_,_,ht,_⟩ := geometry_order G
+ have hd : (desc G).val = tableBase G := Nat.mod_eq_of_lt (show tableBase G < 2^G.w by omega)
+ have hv : (Pieces.word G.g G.lit (.geometry (Layout.oldState G.constants))).val =
+ counterBase G + G.constants.labels.eval G.g := Nat.mod_eq_of_lt (show counterBase G + G.constants.labels.eval G.g < 2^G.w by omega)
+ unfold histogramCell
+ rw [histogramTargetAddress, LiveAuxiliaryDescriptorInit.address_val _ (by omega), hd,
+ CompressedPair.tag_address, hv]
+ change tableBase G + 20 < _
+ omega
+
+/-- Literal report emitted by the outer pair linker, including its transfer
+when a source stage accepts. -/
+theorem histogramCell_report (G : Group)
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w) (stage : CompressedPair.Stage)
+ (rep : Report G.w) (m : Memory G.w) (source : after m rep.events (histogramCell G) = m (histogramCell G)) :
+ after m (CompressedPair.report (terminalOperands G) stage rep).events (histogramCell G) =
+ m (histogramCell G) := by
+ rw [(CompressedPair.report_effect (terminalOperands G) stage rep m).2.2.2]
+ cases rep.result <;> cases CompressedPair.next stage <;> first
+ | exact source
+ | exact (ite_eq_right (histogramCell_lt_tag G fit).ne).trans source
+
+/-- Each source report writes in the workspace. The actual chronological
+sequence may transfer the pair tag arbitrarily many times. -/
+theorem histogramCell_reports (G : Group)
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w)
+ (rs : List (CompressedPair.Stage × Report G.w)) (m : Memory G.w)
+ (source : ∀ q ∈ rs, Writes ((terminalOperands G 2).val ≤ ·) q.2.events) :
+ after m (eventLog (rs.map (fun q => CompressedPair.report (terminalOperands G) q.1 q.2))) (histogramCell G) =
+ m (histogramCell G) := by
+ induction rs generalizing m with
+ | nil => rfl
+ | cons q rest ih =>
+ rw [List.map_cons, eventLog, List.flatMap_cons, after, List.foldl_append]
+ refine (ih _ (fun r hr => source r (.tail _ hr))).trans ?_
+ exact histogramCell_report G fit q.1 q.2 m
+ (after_outside m (source q (.head _)) (histogramTarget_lt_workspace G fit).not_ge)
+
+variable {G : Group} {m : Memory G.w} {i : Fin (2^(sizes G).h)}
+ {hdr : Header (pairLengths G i) → Bool}
+ {N : Indexed G Stage.nominations m (Nominations.Nom G)} {μ : Nominations.Nom G}
+
+theorem PreparedBranch.shadowSpan_of_cell (B : PreparedBranch G m i hdr N μ) {mem : Memory G.w}
+ (cell : mem (histogramCell G) = B.copy.memory () (histogramCell G)) :
+ TerminalBootstrap.shadowSpan (terminalOperands G) mem =
+ ((span (pairLengths G i) (histLength G) : ℕ) : Word G.w) := by
+ rw [← B.shadowSpan]
+ unfold TerminalBootstrap.shadowSpan
+ rw [cell]
+
+theorem PreparedBranch.shadowSpan_after_reports (B : PreparedBranch G m i hdr N μ)
+ (fit : (Layout.pairWorkspace G.constants).eval G.g < 2^G.w)
+ (rs : List (CompressedPair.Stage × Report G.w))
+ (source : ∀ q ∈ rs, Writes ((terminalOperands G 2).val ≤ ·) q.2.events) :
+ TerminalBootstrap.shadowSpan (terminalOperands G)
+ (after (B.copy.memory ()) (eventLog (rs.map (fun q => CompressedPair.report (terminalOperands G) q.1 q.2)))) =
+ ((span (pairLengths G i) (histLength G) : ℕ) : Word G.w) :=
+ B.shadowSpan_of_cell (histogramCell_reports G fit rs _ source)
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalSharedBits.lean b/lean/OAI/Computability/VPVNP/PairTerminalSharedBits.lean
new file mode 100644
index 0000000000..ae48df29db
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalSharedBits.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.PairTerminalLayout
+import OAI.Computability.VPVNP.PairTraversalArena
+import OAI.Computability.VPVNP.PairTerminalPrefixLayout
+import OAI.Computability.VPVNP.PairSimulationFinalBitScan
+
+/-!
+# The shared-bit worker on the selected terminal layout
+
+The high header is beyond the stored row, wire and role intervals on every
+selected branch. The tag and row writers preserve that header. After the
+shared choices, its contents and the stored descriptor rows remain available
+to each vertex, while both endpoints of each wire read the same chosen bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLayout
+
+open BurstRAM BurstRAM.PrivateRAM Compression CursorNetwork CursorBounds CompressorRecords
+open Filter TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+private theorem address_lt_word (b n : ℕ) : addressBits b n < wordBits b n :=
+ (by omega : addressBits b n < addressBits b n+10).trans_le
+ (Nat.le_self_pow (by decide : 4 ≠ 0) _)
+
+/-- The two arrays used to assemble the descriptor arena preserve every
+external header or control word above the last role. -/
+theorem arena_above {w : ℕ} (cap base F : ℕ) (roles : List TaggedLayer) (m : Memory w)
+ (x : ℕ) (h : base + 2 * tagWords cap roles + F ≤ x) :
+ build cap base base (roles.map TaggedLayer.layer)
+ (writeTags (tagWords cap roles+F) cap base roles m) x = m x := by
+ rw [build_outside _ _ _ _ _ _ (Or.inr (by change base+tagWords cap roles ≤ x; omega)),
+ write_tags_outside _ _ _ _ _ _ (Or.inr (by omega))]
+
+/-- Actual live header words and the selected final width suffice for the
+physical shared-bit scan. Its numerical range is derived at the uniform
+threshold, including the controller's two saved cells. -/
+theorem eventually_sharedBits {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (F : DescriptorSpace.Shape)
+ (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start : ℕ → ℕ} (hstart : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ}
+ (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n)
+ (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let w := wordBits b n
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ let L := DescriptorSpace.cursorLayout F b S.steps u.θ (start n) n
+ let rowBase := DescriptorSpace.endAddress L
+ ∀ (z : E.Choices) (pub : Fin 11 → Word w),
+ let Y := E.finalState z
+ let rows := words B.recordLimit (selectedLayers B f hf T hT X z)
+ let lo := rowBase+rows
+ let H := (TerminalLink.header pub).val
+ (pub 2).val = start n → (pub 7).val = addressBits b n →
+ lo + Y.totalWidth < H ∧ H + 32 ≤ 2^w ∧
+ ∀ (m : Memory w), FinalBits.Worker.base pub m = (lo : Word w) →
+ FinalBits.Worker.total pub m = (Y.totalWidth : Word w) →
+ FinalBits.Worker.Layout pub m lo Y.totalWidth := by
+ filter_upwards [eventually_fit B u F b hb hstart 0] with n fit
+ intro base lanes labels hD hT A _ f hf w X T E L rowBase z pub Y rows lo H ws exponent
+ have bound := fit labels hD hT A f hf z
+ change rowBase + 2*rows + Y.totalWidth < headerBase (start n) (addressBits b n) ∧
+ headerBase (start n) (addressBits b n)+32 ≤ 2^w ∧ _ at bound
+ let r := addressBits b n
+ have reserve : 32 ≤ L.base+2^r*2^r := by
+ have pos := bound.1
+ change rowBase+2*rows+Y.totalWidth < L.base + (2^r)^2 - 32 at pos
+ rw [pow_two] at pos
+ omega
+ have room : L.base+2^r*2^r ≤ 2^w := by
+ have h := bound.2.1
+ change L.base+(2^r)^2-32+32 ≤ 2^w at h
+ rwa [pow_two, Nat.sub_add_cancel reserve] at h
+ have hdr := TerminalPrefix.header_val L pub r ws exponent (address_lt_word b n) reserve room
+ change H = L.base + 2^r*2^r - 32 at hdr
+ have heq : H = headerBase (start n) (addressBits b n) := by
+ change H = L.base + (2^r)^2 - 32
+ rw [pow_two]
+ exact hdr
+ have below : lo+Y.totalWidth < H := by
+ rw [heq]
+ dsimp only [lo]
+ omega
+ have hroom : H+32 ≤ 2^w := heq ▸ bound.2.1
+ exact ⟨below,hroom,fun _ hb ht => FinalBits.Worker.Layout.ofBelow hb ht below.le hroom⟩
+
+end PairSimulation.TerminalLayout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalSiteDirectories.lean b/lean/OAI/Computability/VPVNP/PairTerminalSiteDirectories.lean
new file mode 100644
index 0000000000..c5fb49e818
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalSiteDirectories.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.PairTerminalPackedPrefix
+import OAI.Computability.VPVNP.PairTerminalVertexFramePacked
+
+/-!
+# Placement and traversal operands on a physical vertex call
+
+The counter updater can change the low workspace between two vertex calls.
+The selected directories and the operand fields remain in the packed levels
+or in the high header. Their two physical frames suffice for every site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles TraversalControllerInputs TerminalLink
+open scoped Fin.CommRing
+
+variable {w : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f} {n T : ℕ}
+variable {hT : T*S.laneBits ≤ n} {X : State (S.degreeExponent 0) n}
+variable {z : (B.execute f hf T hT X).Choices}
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+
+private theorem resident_data_frame {pub : Fin 11 → Word w} {H first pitch offset cap base : ℕ}
+ {leaf : TaggedLayer} {fibers : List (Fiber w)} {vertex site : Memory w}
+ (d : Resident pub vertex H first pitch offset cap base leaf fibers)
+ (headerCells : ∀ j ∈ terminalScalars, site (H+j) = vertex (H+j))
+ (levelCells : ∀ j ≤ fibers.length, ∀ o < 28, site (first+j*pitch+o) = vertex (first+j*pitch+o)) :
+ Resident pub site H first pitch offset cap base leaf fibers := by
+ refine ⟨d.header,d.headerFits,d.levelFits,(headerCells 16 (by decide)).trans d.firstHead,
+ (headerCells 17 (by decide)).trans d.levelPitch,(congrArg Fin.val (headerCells 1 (by decide))).trans d.levels,
+ (headerCells 14 (by decide)).trans d.roleOffset,(headerCells 15 (by decide)).trans d.rowStride,
+ fun j h => (levelCells j h 14 (by decide)).trans (d.currentBase j h),
+ fun j => (levelCells j.val (by simpa using j.isLt) 27 (by decide)).trans (d.role j),
+ ?_,fun h => (congrArg Fin.val (headerCells 7 (by decide))).trans (d.terminalSites h),
+ fun i => (congrArg Fin.val (levelCells i.val i.isLt.le 22 (by decide))).trans (d.produced i),
+ fun i => (levelCells i.val i.isLt.le 24 (by decide)).trans (d.childCounts i),
+ fun i => (levelCells i.val i.isLt.le 25 (by decide)).trans (d.childLists i),
+ fun i => (levelCells i.val i.isLt.le 26 (by decide)).trans (d.childCapacity i)⟩
+ intro h
+ have same := levelCells 0 (Nat.zero_le _) 21 (by decide)
+ simp only [Nat.zero_mul,Nat.add_zero] at same
+ exact (congrArg Fin.val same).trans (d.initial h)
+
+variable {L : Layout} {tab : Fin L.shape.tables} {baseBits laneBits : ℕ}
+variable {pub : Fin 11 → Word w} {calendar vertex site : Memory w}
+
+/-- The same indexed native directories, with the full traversal resident
+header, on the physical input memory of an arbitrary later vertex call. -/
+theorem VertexEntry.site_directories
+ {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits pub calendar vertex bits)
+ (live : (vs).length < L.levels) (wide : 28 ≤ L.shape.scalarFields)
+ (dataFrame : ∀ x, levelsBase L ≤ x → x < endAddress L → site x = vertex x)
+ (headerFrame : ∀ j ∈ terminalScalars, site ((header pub).val+j) = vertex ((header pub).val+j)) :
+ ∃ ds : (i : Fin (vs).length) → LevelDirectory vs[i] site (endAddress L),
+ Resident pub site (header pub).val (levelStart L 0) (levelWords L)
+ (words B.recordLimit (ls)+(Y).totalWidth) B.recordLimit (endAddress L)
+ ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers (vs) ds) := by
+ obtain ⟨dirs,lower,d⟩ := entry.boundedDirectories
+ let ds (i : Fin (vs).length) : LevelDirectory vs[i] site (endAddress L) :=
+ (dirs i).transport fun x hx => (dataFrame x ((lower i).trans ((dirs i).cells_interval hx).1)
+ ((dirs i).cells_interval hx).2).symm
+ have banks : levelFibers (vs) ds = levelFibers (vs) dirs := rfl
+ refine ⟨ds,?_⟩
+ rw [banks]
+ apply resident_data_frame d headerFrame
+ intro j hj o ho
+ have before := TraversalResidentHandoff.headers_before L live wide j
+ (by simpa only [levelFibers,List.length_ofFn] using hj)
+ apply dataFrame
+ · simp only [levelStart,Nat.zero_mul,Nat.add_zero]
+ omega
+ · omega
+
+/-- Natural and word addresses of every live level at a later site. -/
+theorem VertexEntry.site_level_head
+ {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits pub calendar vertex bits)
+ (live : (vs).length < L.levels) (wide : 28 ≤ L.shape.scalarFields)
+ (dataFrame : ∀ x, levelsBase L ≤ x → x < endAddress L → site x = vertex x)
+ (headerFrame : ∀ j ∈ terminalScalars, site ((header pub).val+j) = vertex ((header pub).val+j))
+ (j : ℕ) (hj : j ≤ (vs).length) :
+ levelHead pub site j = (levelStart L j : Word w) ∧ (levelHead pub site j).val = levelStart L j := by
+ obtain ⟨ds,d⟩ := entry.site_directories live wide dataFrame headerFrame
+ have loc : levelHead pub site j = (levelStart L j : Word w) := by
+ rw [levelHead,terminal_read d 16 (by decide),terminal_read d 17 (by decide),
+ d.firstHead,d.levelPitch,← Nat.cast_mul,← Nat.cast_add]
+ simp only [levelStart,Nat.zero_mul,Nat.add_zero]
+ refine ⟨loc,?_⟩
+ have fit := d.levelFits j (by simpa only [levelFibers,List.length_ofFn] using hj)
+ rw [loc,Fin.val_natCast,Nat.mod_eq_of_lt]
+ simp only [levelStart,Nat.zero_mul,Nat.add_zero] at fit ⊢
+ omega
+
+end PairSimulation.TerminalProgram
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM Compression CompressorRecords DescriptorSpace PairSimulation
+open LocalHistory TraversalRows TraversalRoles TraversalControllerInputs TerminalProgram
+open scoped Fin.CommRing
+
+variable {G : Group} {L : Layout} {cap width ord : ℕ} {roles : List TaggedLayer}
+variable {vertex site : Memory G.w}
+
+private theorem levelFloor (L : Layout) : L.base ≤ levelsBase L := by
+ unfold levelsBase directoryBase plannerTag frameBase
+ omega
+
+/-- The two operand frames at the actual site's physical entry. -/
+theorem VertexPacked.traversal_frames (P : VertexPacked G L cap roles width)
+ (frame : LinkedVertexMemory G vertex ord site) :
+ (∀ x, levelsBase L ≤ x → x < endAddress L → site x = vertex x) ∧
+ ∀ j ∈ terminalScalars, site ((vertexHeader G).val+j) = vertex ((vertexHeader G).val+j) := by
+ refine ⟨fun _ lo hi => P.directory frame ((levelFloor L).trans lo) hi,?_⟩
+ intro j hj
+ simp only [terminalScalars,Finset.mem_insert,Finset.mem_singleton] at hj
+ have h := P.header frame j (by omega) (by omega)
+ have fit := P.room
+ have addr : (vertexHeader G+(j : Word G.w)).val = (vertexHeader G).val+j := by
+ change ((vertexHeader G).val+j % (2^G.w)) % (2^G.w) = (vertexHeader G).val+j
+ rw [Nat.mod_eq_of_lt (by omega : j < 2^G.w),Nat.mod_eq_of_lt (by omega)]
+ rwa [addr] at h
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f} {n T : ℕ}
+variable {hT : T*S.laneBits ≤ n} {X : State (S.degreeExponent 0) n}
+variable {z : (B.execute f hf T hT X).Choices}
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+variable {tab : Fin L.shape.tables} {baseBits laneBits : ℕ} {calendar : Memory G.w}
+
+/-- The directory and parser snapshot witnesses coexist in the memory used
+by a real site, after any preceding motif counter flushes. -/
+theorem VertexPacked.site_operands (P : VertexPacked G L cap roles width)
+ (frame : LinkedVertexMemory G vertex ord site)
+ {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits (terminalOperands G) calendar vertex bits)
+ (live : (vs).length < L.levels) (wide : 28 ≤ L.shape.scalarFields)
+ {data : SelectedPayloadHistory.Data (w := G.w) B f hf}
+ (past : SelectedPayloadHistory.Past B f hf L data (vs) vertex) :
+ (∃ ds : (i : Fin (vs).length) → LevelDirectory vs[i] site (endAddress L),
+ Resident (terminalOperands G) site (vertexHeader G).val (levelStart L 0) (levelWords L)
+ (words B.recordLimit (ls)+(Y).totalWidth) B.recordLimit (endAddress L)
+ ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers (vs) ds)) ∧
+ SelectedPayloadHistory.Past B f hf L data (vs) site := by
+ obtain ⟨low,high⟩ := P.traversal_frames frame
+ refine ⟨entry.site_directories live wide low high,past.transfer ?_⟩
+ have upper : DescriptorSpace.tableBase L (vs).length tab + tableWords L ≤ endAddress L :=
+ (tableEnd_le_nextLevel L (vs).length tab).trans (levelStart_mono L live)
+ intro x lo hx
+ have before : x < DescriptorSpace.tableBase L (vs).length tab := hx.trans_le (Nat.le_add_right ..)
+ exact low x lo (by omega)
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalStageReverse.lean b/lean/OAI/Computability/VPVNP/PairTerminalStageReverse.lean
new file mode 100644
index 0000000000..d30519e0cf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalStageReverse.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.PairSimulationTerminalPhaseBuild
+
+/-!
+# Identifying the first two stages of an arbitrary accepting terminal trace
+
+The bootstrap executes once from the original memory. Its empty-tape
+execution fixes the entire report even at a different fuel allowance.
+The following deterministic prefix is recovered across the two controller
+cells, retaining each actual entry tag and the final physical memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM PrivateRAM LiveProgram CompressorRecords
+open scoped Fin.CommRing
+
+variable {w cap : ℕ} {workers : Stage → PairTable} {pub : Fin 11 → Word w}
+
+/-- On identical starting memory a single accepting empty-tape call determines
+the whole stage, including its physical exit. No read footprint is required. -/
+theorem Phase.force_oneShot {e m bs ls final} (h : Phase workers pub cap e m bs ls final)
+ {f : ℕ} {raw : Report w}
+ (run : execute (source workers e.stage pub) f ((source workers e.stage pub).start e.state)
+ m [] = some raw) (halt : raw.result = none) :
+ bs = [[]] ∧ ls = [(e, raw)] ∧ final = after m (report (header pub) e raw).events := by
+ cases h with
+ | last call _ _ =>
+ obtain ⟨rfl, rfl⟩ := execute_empty_forces_anyFuel run call
+ exact ⟨rfl, rfl, rfl⟩
+ | more call _ returned _ =>
+ obtain ⟨_, rfl⟩ := execute_empty_forces_anyFuel run call
+ rw [halt] at returned
+ contradiction
+
+/-- A closed empty-tape reference determines every tagged report of the stage.
+Its linked writes and controller handoffs determine the exact physical image. -/
+theorem Phase.canonical_empty {e phy bs ls final} (h : Phase workers pub cap e phy bs ls final)
+ {f n : ℕ} {src : Memory w} {raws : List (Report w)}
+ (run : runSegment (source workers e.stage pub) f (some e.state) src (List.replicate n []) =
+ some raws) (halt : endState (some e.state) raws = none)
+ (agree : SourceTransport.Agree (workerCell (header pub)) src phy)
+ (reads : SourceTransport.Reads (workerCell (header pub)) (eventLog raws)) :
+ bs = List.replicate n [] ∧ ls = stageLogs e raws ∧
+ final = after phy (eventLog (stageReports (header pub) e raws)) := by
+ obtain ⟨choices, reports, _⟩ := h.force_empty src n f raws run halt agree reads
+ exact ⟨choices, reports ▸ stageLogs_eq h, by rw [← h.final_memory, h.reports_eq, reports]⟩
+
+open private agree_report from OAI.Computability.VPVNP.PairSimulationTerminalSplit
+
+/-- Identify the bootstrap and prefix blocks of an actual five-stage accepting
+trace using ordinary workers at their own fuel budgets. The bootstrap's
+controller handoff supplies the memory agreement needed by the prefix. -/
+theorem FiveTrace.canonical_start {m : Memory w} (t : FiveTrace workers pub cap m)
+ {boot : Report w} {rows : List (Report w)} {f g n : ℕ}
+ (bootRun : execute (source workers Stage.bootstrap pub) f
+ ((source workers Stage.bootstrap pub).start 0) m [] = some boot) (closed : boot.result = none)
+ (prefixRun : runSegment (source workers Stage.prefixRows pub) g (some 0) (after m boot.events)
+ (List.replicate n []) = some rows) (halt : endState (some 0) rows = none)
+ (reads : SourceTransport.Reads (workerCell (header pub)) (eventLog rows)) :
+ let phy := after m (report (header pub) .initial boot).events
+ let prefixEntry : Entry w := .resume Stage.prefixRows 0
+ t.bootstrap.choices = [[]] ∧ t.bootstrap.logs = [(.initial, boot)] ∧
+ t.bootstrap.memory = phy ∧ t.prefixRows.choices = List.replicate n [] ∧
+ t.prefixRows.logs = stageLogs prefixEntry rows ∧
+ t.prefixRows.memory = after phy (eventLog (stageReports (header pub) prefixEntry rows)) := by
+ obtain ⟨bs, ls, mem⟩ := t.bootRun.force_oneShot bootRun closed
+ have agree := agree_report (header pub) .initial boot m m (fun _ _ => rfl)
+ rw [← mem] at agree
+ obtain ⟨ps, logs, final⟩ := t.prefixRun.canonical_empty prefixRun halt agree reads
+ exact ⟨bs, ls, mem, ps, logs, by simpa only [mem] using final⟩
+
+end PairSimulation.TerminalLink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalVertexBank.lean b/lean/OAI/Computability/VPVNP/PairTerminalVertexBank.lean
new file mode 100644
index 0000000000..ca2e6bf3d2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalVertexBank.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.PairTerminalPackedBudget
+import OAI.Computability.VPVNP.PairVertexGeometrySegment
+import OAI.Computability.VPVNP.PairSimulationLeafRole
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherCode
+
+/-!
+# Fixed terminal code with the live leaf and endpoint registers
+
+The descriptor bootstrap, width scan, traversal controller and shared-bit
+worker precede a single vertex image. Its geometry segment reconstructs the
+argument, histogram, cache and interpreter addresses from the eleven public
+operands. The root gather reads both endpoints, and the cursor leaf executes
+the virtual coefficient machine. The two map segments occupy the remaining
+role entries of that same image.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM Compression CompressorRecords LiveProgram
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+
+/-- The register-sharing segments of the physical per-vertex burst. -/
+noncomputable def installedSegments (c : Constants) (S : BlockSchedule k) (p q : ℕ)
+ (shrink refresh : VertexImage.Segment) : VertexImage.Part → VertexImage.Segment :=
+ VertexImage.segments (VertexGeometry.segment c (slotDegree S) p q)
+ TerminalRootGather.segment LeafRole.segment shrink refresh
+
+/-- All opcodes and register counts are fixed before the length, coefficient
+assignment and selected branches. -/
+noncomputable def installedTable (B : S.Templates) (c : Constants) (p q : ℕ)
+ (shrink refresh : VertexImage.Segment) : PairTable :=
+ table (BlockProgram.allocationShape B) B.recordLimit (installedSegments c S p q shrink refresh)
+
+/-- The exact same instruction bank executes against the packed chronological
+directory emitted at any length by the calendar. -/
+theorem installed_at_layout (B : S.Templates) (c : Constants) (p q base positions blocks : ℕ)
+ (shrink refresh : VertexImage.Segment) :
+ table (BlockProgram.layout B base positions blocks).shape B.recordLimit
+ (installedSegments c S p q shrink refresh) = installedTable B c p q shrink refresh :=
+ congrArg TerminalLink.table (TerminalLayout.packed_workers B base positions blocks _)
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalVertexFrame.lean b/lean/OAI/Computability/VPVNP/PairTerminalVertexFrame.lean
new file mode 100644
index 0000000000..637af141fd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalVertexFrame.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.PairSimulationCounters
+import OAI.Computability.VPVNP.PairTerminalGatherGeometry
+import OAI.Computability.VPVNP.PairTraversalRoleExecution
+
+/-!
+# External memory throughout the final-site traversal
+
+The site's successful flush changes only its motif-counter suffix. The same
+typed root packet, child rows, role words, auxiliary input, grammar choices
+and header fields can consequently be read at each later ordinal. The bounds
+used for the live machine are those of its eleven public operands.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexFrame
+
+open BurstRAM PrivateRAM Compression CompressorRecords TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+variable {w base grammar g : ℕ} {reference m : Memory w} {ord : ℕ}
+
+/-- Only the contiguous motif counter suffix may differ from the shared-bit
+stage's output. The ordinal index matches the ascending vertex interpreter. -/
+def Stable (base grammar g : ℕ) (reference : Memory w) (_ord : ℕ) (m : Memory w) : Prop :=
+ ∀ a, a < base+grammar ∨ base+grammar+g ≤ a → m a = reference a
+
+theorem initial (base grammar g ord : ℕ) (reference : Memory w) :
+ Stable base grammar g reference ord reference := fun _ _ => rfl
+
+theorem Stable.preserve (h : Stable base grammar g reference ord m) (powers : Fin g → ℕ) :
+ Stable base grammar g reference (ord+1) (Counters.addHistogram base grammar powers m) :=
+ fun a ha => (Counters.addHistogram_outside base grammar powers m a ha).trans (h a ha)
+
+theorem Stable.visit {V : Type*} (h : Stable base grammar g reference ord m)
+ (hist : V → Fin g → ℕ) (sites : List V) :
+ Stable base grammar g reference (ord+sites.length) (Counters.visit base grammar hist sites m) :=
+ fun a ha => (Counters.visit_outside base grammar hist sites m a ha).trans (h a ha)
+
+theorem Stable.grammarCell (h : Stable base grammar g reference ord m) (j : Fin grammar) :
+ m (base+j.val) = reference (base+j.val) := h _ (.inl (Nat.add_lt_add_left j.isLt _))
+
+theorem Stable.above (h : Stable base grammar g reference ord m) {lo : ℕ}
+ (sep : base+grammar+g ≤ lo) (j : ℕ) : m (lo+j) = reference (lo+j) :=
+ h _ (.inr (sep.trans (Nat.le_add_right _ _)))
+
+theorem Stable.header (h : Stable base grammar g reference ord m) (head : Word w)
+ (sep : base+grammar+g ≤ head.val) (room : head.val+32 ≤ 2^w) (j : ℕ) (hj : j < 32) :
+ m (head+(j : Word w)).val = reference (head+(j : Word w)).val := by
+ rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j<2^w),Nat.mod_eq_of_lt (by omega)]
+ exact h.above sep j
+
+theorem Stable.rows (h : Stable base grammar g reference ord m) {cap previous first : ℕ}
+ (sep : base+grammar+g ≤ first) (ls : List Layer) (rows : AllRows w reference cap previous first ls) :
+ AllRows w m cap previous first ls := by
+ induction ls generalizing previous first with
+ | nil => trivial
+ | cons L ls ih =>
+ refine ⟨fun i => ?_,ih (sep.trans (Nat.le_add_right _ _)) rows.2⟩
+ let node := address cap first i.val
+ have low : base+grammar+g ≤ node := sep.trans (Nat.le_add_right _ _)
+ obtain ⟨hn,hn1,hs,h0,h1,hj⟩ := rows.1 i
+ exact ⟨hn,hn1,hs,(h _ (.inr low)).trans h0,(h.above low 1).trans h1,
+ fun j => (h.above (low.trans (Nat.le_add_right node 2)) j.val).trans (hj j)⟩
+
+open private reads_above from OAI.Computability.VPVNP.PairTraversalRoleExecution
+
+theorem Stable.roles (h : Stable base grammar g reference ord m) {offset cap first : ℕ}
+ (sep : base+grammar+g ≤ offset+first) {ls : List TaggedLayer} (tags : Reads w reference offset cap first ls) :
+ Reads w m offset cap first ls := reads_above tags (fun x hx => h x (.inr (sep.trans hx)))
+
+theorem Stable.gatherRows (h : Stable base grammar g reference ord m) {a labels : ℕ} (X : State a labels)
+ (L : TerminalRootGather.Layout) (rows : TerminalGatherGeometry.Rows X L reference)
+ (sep : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead], base+grammar+g ≤ head) :
+ TerminalGatherGeometry.Rows X L m := rows.transfer X L (fun head hh i => h.above (sep head hh) i.val)
+
+theorem Stable.packet (h : Stable base grammar g reference ord m) {a labels : ℕ} (X : State a labels)
+ (L : TerminalRootGather.Layout) (v : X.network.Site) (num : TerminalGatherGeometry.Numbering X L v)
+ (rows : TerminalGatherGeometry.Rows X L reference)
+ (sep : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead,L.wires], base+grammar+g ≤ head)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (bits : ∀ i, reference (L.wires+i.val) = PrivateFields.bitValue w (f i)) :
+ L.packet m = (NodeArguments.packed X v (TerminalGatherGeometry.half X f v)).map (PrivateFields.bitValue w) := by
+ apply TerminalGatherGeometry.packet_eq num
+ (h.gatherRows X L rows (fun head hh => sep head (List.mem_append_left [L.wires] hh))) f
+ exact fun j => (h.above (sep _ (by simp)) j.val).trans (bits j)
+
+end PairSimulation.VertexFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalVertexFrameLinked.lean b/lean/OAI/Computability/VPVNP/PairTerminalVertexFrameLinked.lean
new file mode 100644
index 0000000000..76a53a5993
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalVertexFrameLinked.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.PairTerminalVertexFrame
+import OAI.Computability.VPVNP.PairSimulationTerminalSplice
+import OAI.Computability.VPVNP.PairTraversalControllerMemory
+
+/-!
+# Final-site memory under physical terminal dispatch
+
+The controller writes its stage and saved ordinal after each continuing
+call. Excluding exactly those two addresses from the motif-counter invariant
+allows the next worker to read the selected compressor records, the shared
+bits and its immutable header fields directly from the actual memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexFrame
+
+open BurstRAM PrivateRAM Compression CompressorRecords TraversalRows TraversalRoles TerminalLink
+open scoped Fin.CommRing
+
+variable {w base grammar g ord : ℕ} {reference m : Memory w} {addr : Word w}
+
+/-- The physical memory agrees with the shared-bit result outside the
+motif-counter suffix and the two terminal controller cells. -/
+def Linked (addr : Word w) (base grammar g : ℕ) (reference : Memory w) (_ord : ℕ) (phy : Memory w) : Prop :=
+ ∀ a, (a < base+grammar ∨ base+grammar+g ≤ a) → workerCell addr a → phy a = reference a
+
+theorem linked_initial (addr : Word w) (base grammar g ord : ℕ) (ref : Memory w) :
+ Linked addr base grammar g ref ord ref := fun _ _ _ => rfl
+
+theorem linked_of_agree (h : SourceTransport.Agree (workerCell addr) reference m) (ord base grammar g : ℕ) :
+ Linked addr base grammar g reference ord m := fun i _ hi => (h i hi).symm
+
+theorem Stable.linked (h : Stable base grammar g reference ord m) (addr : Word w) :
+ Linked addr base grammar g reference ord m := fun i hi _ => h i hi
+
+theorem Linked.preserve (h : Linked addr base grammar g reference ord m) (powers : Fin g → ℕ) :
+ Linked addr base grammar g reference (ord+1) (Counters.addHistogram base grammar powers m) :=
+ fun i hi hc => (Counters.addHistogram_outside base grammar powers m i hi).trans (h i hi hc)
+
+/-- The worker may terminate or resume. In both cases the actual physical
+entry and exit report preserve every selected operand outside the counter suffix. -/
+theorem Linked.after_report {raw : Report w} (e : Entry w) {n : ℕ}
+ (post : Linked addr base grammar g reference n (after m raw.events)) :
+ Linked addr base grammar g reference n (after m (TerminalLink.report addr e raw).events) := by
+ rw [report_after]
+ cases ht : target e.stage raw.result with
+ | none => exact post
+ | some p =>
+ obtain ⟨s,x⟩ := p
+ intro i hi hc
+ simpa only [writeMemory,ite_eq_right hc.1,ite_eq_right hc.2] using post i hi hc
+
+theorem Linked.report (h : Linked addr base grammar g reference ord m) (e : Entry w) (raw : Report w)
+ (powers : Fin g → ℕ) (flush : after m raw.events = Counters.addHistogram base grammar powers m) :
+ Linked addr base grammar g reference (ord+1) (after m (TerminalLink.report addr e raw).events) :=
+ Linked.after_report e (flush ▸ h.preserve powers)
+
+private theorem at_offset (addr : Word w) (room : addr.val+32 ≤ 2^w) (j : ℕ) (hj : j<32) :
+ (addr+(j : Word w)).val = addr.val+j := by
+ rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j<2^w),Nat.mod_eq_of_lt (by omega)]
+
+theorem Linked.below (h : Linked addr base grammar g reference ord m) (room : addr.val+32 ≤ 2^w)
+ {x : ℕ} (lo : base+grammar+g ≤ x) (hi : x < addr.val) : m x = reference x := by
+ have last : (addr+31).val = addr.val+31 := at_offset addr room 31 (by decide)
+ exact h x (.inr lo) ⟨hi.ne,by omega⟩
+
+/-- At every real counter address the linked report applies precisely the
+worker's histogram increment. The two controller stores are outside the array. -/
+theorem report_motif {raw : Report w} (e : Entry w) (room : addr.val+32 ≤ 2^w)
+ (low : base+grammar+g ≤ addr.val) (powers : Fin g → ℕ)
+ (flush : after m raw.events = Counters.addHistogram base grammar powers m) (i : Fin g) :
+ after m (TerminalLink.report addr e raw).events (base+grammar+i.val) =
+ m (base+grammar+i.val) + ((powers i : ℕ) : Word w) := by
+ have last : (addr+31).val = addr.val+31 := at_offset addr room 31 (by decide)
+ have ix := i.isLt
+ have h0 : base+grammar+i.val ≠ addr.val := by omega
+ have h31 : base+grammar+i.val ≠ (addr+31).val := by omega
+ rw [report_after,flush]
+ cases h : target e.stage raw.result with
+ | none => exact Counters.addHistogram_at base grammar powers m i
+ | some p =>
+ obtain ⟨s,x⟩ := p
+ simpa only [writeMemory,ite_eq_right h0,ite_eq_right h31] using Counters.addHistogram_at base grammar powers m i
+
+theorem Linked.grammarCell (h : Linked addr base grammar g reference ord m) (room : addr.val+32 ≤ 2^w)
+ (low : base+grammar ≤ addr.val) (i : Fin grammar) : m (base+i.val) = reference (base+i.val) := by
+ have last : (addr+31).val = addr.val+31 := at_offset addr room 31 (by decide)
+ have hi := i.isLt
+ exact h _ (.inl (by omega)) ⟨by omega,by omega⟩
+
+theorem Linked.header (h : Linked addr base grammar g reference ord m) (room : addr.val+32 ≤ 2^w)
+ (low : base+grammar+g ≤ addr.val) (j : ℕ) (hj : 0 if i = addr.val ∨ i = (addr+31).val then ref i else m i
+
+private theorem Linked.restored (h : Linked addr base grammar g reference ord m) :
+ Stable base grammar g reference ord (restore addr reference m) := by
+ intro i hi
+ unfold restore
+ split
+ · rfl
+ · rename_i hn
+ exact h i hi (not_or.mp hn)
+
+private theorem restore_below (room : addr.val+32 ≤ 2^w) :
+ ControllerMemory.AgreeBelow addr.val m (restore addr reference m) := by
+ intro i hi
+ have last : (addr+31).val = addr.val+31 := at_offset addr room 31 (by decide)
+ have notControl : ¬ (i=addr.val ∨ i=(addr+31).val) := by omega
+ exact (ite_eq_right notControl).symm
+
+theorem Linked.rows (h : Linked addr base grammar g reference ord m) (room : addr.val+32 ≤ 2^w)
+ {cap previous first : ℕ} {ls : List Layer} (lo : base+grammar+g ≤ first)
+ (hi : first + words cap ls ≤ addr.val) (capacity : ∀ L ∈ ls, ∀ i, (L.ids i).length ≤ cap)
+ (data : AllRows w reference cap previous first ls) : AllRows w m cap previous first ls :=
+ ControllerMemory.allRows_below ls (restore_below room) hi capacity (h.restored.rows lo ls data)
+
+theorem Linked.roles (h : Linked addr base grammar g reference ord m) (room : addr.val+32 ≤ 2^w)
+ {offset cap first : ℕ} {ls : List TaggedLayer} (lo : base+grammar+g ≤ offset+first)
+ (hi : offset+first+tagWords cap ls ≤ addr.val) (tags : Reads w reference offset cap first ls) :
+ Reads w m offset cap first ls :=
+ ControllerMemory.reads_below ls (restore_below room) hi (h.restored.roles lo tags)
+
+theorem Linked.packet (h : Linked addr base grammar g reference ord m) (room : addr.val+32 ≤ 2^w)
+ {a k : ℕ} (X : State a k) (L : TerminalRootGather.Layout) (v : X.network.Site)
+ (num : TerminalGatherGeometry.Numbering X L v) (rows : TerminalGatherGeometry.Rows X L reference)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (bits : ∀ i, reference (L.wires+i.val) = PrivateFields.bitValue w (f i))
+ (bounds : ∀ head ∈ [L.incomingHead,L.widthHead,L.prefixHead],
+ base+grammar+g ≤ head ∧ head+TerminalPrefix.arcCount X ≤ addr.val)
+ (wires : base+grammar+g ≤ L.wires ∧ L.wires+X.totalWidth ≤ addr.val) :
+ L.packet m = (NodeArguments.packed X v (TerminalGatherGeometry.half X f v)).map (PrivateFields.bitValue w) := by
+ apply TerminalGatherGeometry.packet_eq num
+ · apply rows.transfer X L
+ intro head hh i
+ obtain ⟨low,high⟩ := bounds head hh
+ exact h.below room (low.trans (Nat.le_add_right _ _)) ((Nat.add_lt_add_left i.isLt _).trans_le high)
+ · intro j
+ have hj := j.isLt.trans_eq (TerminalPrefix.width_sum X)
+ exact (h.below room (wires.1.trans (Nat.le_add_right _ _)) ((Nat.add_lt_add_left hj _).trans_le wires.2)).trans (bits j)
+
+end PairSimulation.VertexFrame
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalVertexFramePacked.lean b/lean/OAI/Computability/VPVNP/PairTerminalVertexFramePacked.lean
new file mode 100644
index 0000000000..474f97537c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalVertexFramePacked.lean
@@ -0,0 +1,214 @@
+import OAI.Computability.VPVNP.PairTerminalVertexFrameLinked
+import OAI.Computability.VPVNP.PairTerminalVertexMemory
+import OAI.Computability.VPVNP.PairNativeFrameGroup
+import OAI.Computability.VPVNP.PairTerminalShadowChronology
+
+/-!
+# Vertex readback in the packed live workspace
+
+A site flush adds to the motif suffix and the terminal dispatcher saves its
+state in two high words. The geometry of the selected descriptor arena places
+each packed table, child row, role word and shared payload outside both write
+regions. The grammar nominations and the prepared auxiliary shadow can be
+recovered from the same physical memory throughout the traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace PairSimulation
+open TraversalRows TraversalRoles VertexFrame PrimedInputRAM LiveAuxiliaryHeaders
+open scoped Fin.CommRing
+
+/-- Address of the terminal controller in the group’s actual pair workspace. -/
+abbrev vertexHeader (G : Group) := TerminalLink.header (terminalOperands G)
+
+/-- Equality with the shared-bit post-memory outside the two controller words
+and the motif suffix incremented at each site. -/
+abbrev LinkedVertexMemory (G : Group) :=
+ Linked (vertexHeader G) (terminalOperands G 4).val (terminalOperands G 5).val G.constants.motifLabels
+
+/-- Bounds of the selected arena, expressed at the actual live public operands. -/
+structure VertexPacked (G : Group) (D : DescriptorSpace.Layout) (cap : ℕ)
+ (roles : List TaggedLayer) (width : ℕ) : Prop where
+ fit : (LiveProgram.Layout.pairWorkspace G.constants).eval G.g < 2^G.w
+ workspace : D.base = (terminalOperands G 2).val
+ room : (vertexHeader G).val+32 ≤ 2^G.w
+ arena : endAddress D + 2*tagWords cap roles + width ≤ (vertexHeader G).val
+
+variable {G : Group} {D : DescriptorSpace.Layout} {cap width ord : ℕ} {roles : List TaggedLayer}
+variable {reference m : Memory G.w}
+
+local notation "pub" => terminalOperands G
+local notation "H" => vertexHeader G
+local notation "rowBase" => endAddress D
+local notation "rowSize" => tagWords cap roles
+local notation "counterEnd" => Fin.val (terminalOperands G 4) + Fin.val (terminalOperands G 5) + G.constants.motifLabels
+
+private theorem base_le_level (D : DescriptorSpace.Layout) (level : ℕ) : D.base ≤ levelStart D level := by
+ simp only [levelStart, levelsBase, directoryBase, plannerTag, frameBase]
+ omega
+
+theorem VertexPacked.counter_shadow (P : VertexPacked G D cap roles width) :
+ counterEnd ≤ (pub 3).val := (physical_counter_end G P.fit).1
+
+theorem VertexPacked.counter_base (P : VertexPacked G D cap roles width) :
+ counterEnd ≤ D.base := P.workspace ▸ (P.counter_shadow.trans (physical_counter_end G P.fit).2.1)
+
+theorem VertexPacked.counter_rows (P : VertexPacked G D cap roles width) :
+ counterEnd ≤ rowBase := P.counter_base.trans (base_le_level D D.levels)
+
+theorem VertexPacked.counter_header (P : VertexPacked G D cap roles width) :
+ counterEnd ≤ (H).val := by
+ have lo := P.counter_rows
+ have hi := P.arena
+ omega
+
+theorem VertexPacked.directory (P : VertexPacked G D cap roles width)
+ (frame : LinkedVertexMemory G reference ord m) {x : ℕ} (lo : D.base ≤ x) (hi : x < rowBase) :
+ m x = reference x := by
+ have stop := P.arena
+ exact frame.below P.room (P.counter_base.trans lo) (by omega)
+
+/-- The numerical addresses passed to the gather are the final two incidence
+columns and the start of the selected prefix table. All three lie wholly in
+the descriptor interval, including on an empty scan. -/
+theorem VertexPacked.heads (P : VertexPacked G D cap roles width)
+ (last : Fin D.levels) (tab : Fin D.shape.tables) (slots : ℕ)
+ (capacity : slots ≤ slotCapacity D) (cells : slots ≤ tableWords D) :
+ ∀ head ∈ [incidenceBase D last slots 4, incidenceBase D last slots 5, DescriptorSpace.tableBase D last tab],
+ counterEnd ≤ head ∧ head + slots ≤ rowBase := by
+ have ht : DescriptorSpace.tableBase D last tab + slots ≤ rowBase :=
+ (Nat.add_le_add_left cells (DescriptorSpace.tableBase D last tab)).trans
+ ((tableEnd_le_nextLevel D last tab).trans (levelStart_mono D last.isLt))
+ have low : counterEnd ≤ incidenceStart D last :=
+ (P.counter_base.trans (base_le_level D last)).trans (Nat.le_add_right _ _)
+ have hc := Nat.mul_le_mul_left 6 capacity
+ have table : DescriptorSpace.tableBase D last tab = incidenceStart D last + 6*slotCapacity D +
+ tab.val * tableWords D := rfl
+ intro h hh
+ have choices : h = incidenceBase D last slots 4 ∨ h = incidenceBase D last slots 5 ∨ h = DescriptorSpace.tableBase D last tab := by simpa using hh
+ rcases choices with rfl | rfl | rfl
+ · change counterEnd ≤ incidenceStart D last + 4*slots ∧ incidenceStart D last + 4*slots+slots ≤ _
+ omega
+ · change counterEnd ≤ incidenceStart D last + 5*slots ∧ incidenceStart D last + 5*slots+slots ≤ _
+ omega
+ · exact ⟨by omega,ht⟩
+
+theorem VertexPacked.rows (P : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord m)
+ (capacity : ∀ l ∈ roles.map TaggedLayer.layer, ∀ i, (l.ids i).length ≤ cap)
+ (rows : AllRows G.w reference cap rowBase rowBase (roles.map TaggedLayer.layer)) :
+ AllRows G.w m cap rowBase rowBase (roles.map TaggedLayer.layer) := by
+ have hi := P.arena
+ exact frame.rows P.room P.counter_rows (by change rowBase+rowSize ≤ (H).val; omega) capacity rows
+
+theorem VertexPacked.roleWords (P : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord m)
+ (stored : Reads G.w reference (rowSize+width) cap rowBase roles) :
+ Reads G.w m (rowSize+width) cap rowBase roles := by
+ have lo := P.counter_rows
+ have hi := P.arena
+ exact frame.roles P.room (by omega) (by omega) stored
+
+theorem VertexPacked.bits (P : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord m)
+ (f : Fin width → Bool)
+ (bits : ∀ i, reference (rowBase+rowSize+i.val) = PrivateFields.bitValue G.w (f i)) :
+ ∀ i, m (rowBase+rowSize+i.val) = PrivateFields.bitValue G.w (f i) := by
+ intro i
+ have lo := P.counter_rows
+ have hi := P.arena
+ have ix := i.isLt
+ exact (frame.below P.room (by omega) (by omega)).trans (bits i)
+
+theorem VertexPacked.header (P : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord m)
+ (j : ℕ) (lo : 0 < j) (hi : j < 31) : m (H+(j : Word G.w)).val = reference (H+(j : Word G.w)).val :=
+ frame.header P.room P.counter_header j lo hi
+
+theorem VertexPacked.geometry (P : VertexPacked G D cap roles width)
+ (frame : LinkedVertexMemory G reference ord m) {first size stride baseRadix laneRadix : ℕ} {span : Word G.w}
+ (stored : NativeFrame.Readback reference H first size stride baseRadix laneRadix span) :
+ NativeFrame.Readback m H first size stride baseRadix laneRadix span := by
+ apply stored.transfer
+ intro j hj
+ have choices : j=4 ∨ j=5 ∨ j=15 ∨ j=18 ∨ j=19 ∨ j=20 := by simpa using hj
+ exact P.header frame j (by omega) (by omega)
+
+theorem VertexPacked.nominations (P : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord m)
+ (μ : Nominations.Nom G)
+ (stored : ∀ i, reference ((pub 4).val+i.val) = Fin.ofNat _ (μ i).val) :
+ ∀ i, m ((pub 4).val+i.val) = Fin.ofNat _ (μ i).val := by
+ intro i
+ have stop := P.counter_header
+ have histFit : histLength G < 2^G.w := by
+ have endLe := counter_end_le_shadow G
+ change counterBase G + (histLength G + G.constants.motifLabels) ≤ shadowBase G at endLe
+ have ws : shadowBase G ≤ (LiveProgram.Layout.pairWorkspace G.constants).eval G.g := by
+ change shadowBase G ≤ shadowBase G+_
+ omega
+ have := P.fit
+ omega
+ have len : (pub 5).val = histLength G := Nat.mod_eq_of_lt histFit
+ have hi : i.val < (pub 5).val := len ▸ i.isLt
+ exact (frame.grammarCell P.room (by omega) ⟨i.val,hi⟩).trans (stored i)
+
+theorem VertexPacked.shadow (P : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord m)
+ (i : Fin (2^(sizes G).h)) (hn : 1 ≤ G.g.n)
+ (capacity : span (pairLengths G i) (histLength G) ≤ 2^(virtualSiteExponent G.g.d G.g.n))
+ {j : ℕ} (hj : j < span (pairLengths G i) (histLength G)) :
+ m ((pub 3).val+j) = reference ((pub 3).val+j) := by
+ have limit := shadow_span_room G i hn P.fit capacity
+ have ws := P.workspace
+ have row : D.base ≤ rowBase := base_le_level D D.levels
+ have bound := P.arena
+ exact frame.below P.room (P.counter_shadow.trans (Nat.le_add_right _ _)) (by omega)
+
+/-- Every scalar, pointer, and table entry retained by an earlier compressor
+level survives at its original address throughout the vertex phase. -/
+theorem VertexPacked.levelWord (P : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord m)
+ (level : Fin D.levels) (j : Fin (levelWords D)) :
+ m (levelStart D level+j.val) = reference (levelStart D level+j.val) := by
+ have next : levelStart D (level.val+1) = levelStart D level+levelWords D := by
+ simp only [levelStart,Nat.succ_mul,Nat.add_assoc]
+ apply P.directory frame ((base_le_level D level).trans (Nat.le_add_right _ _))
+ exact ((Nat.add_lt_add_left j.isLt _).trans_eq next.symm).trans_le (levelStart_mono D level.isLt)
+
+/-- The final pair substage has no outgoing substage tag. Its dispatch
+preserves the terminal worker's physical memory effect at every vertex. -/
+theorem LinkedVertexMemory.pairReport (frame : LinkedVertexMemory G reference ord m)
+ (entry : TerminalLink.Entry G.w) (raw : Report G.w) (powers : Fin G.constants.motifLabels → ℕ)
+ (flush : after m raw.events = Counters.addHistogram (pub 4).val (pub 5).val powers m) :
+ LinkedVertexMemory G reference (ord+1) (after m (CompressedPair.report pub CompressedPair.Stage.terminal
+ (TerminalLink.report H entry raw)).events) := by
+ let wrapped := TerminalLink.report H entry raw
+ have post : after m (CompressedPair.report pub CompressedPair.Stage.terminal wrapped).events =
+ after m wrapped.events := by
+ rw [(CompressedPair.report_effect pub CompressedPair.Stage.terminal wrapped m).2.2.2,
+ show CompressedPair.next CompressedPair.Stage.terminal = none from rfl]
+ cases wrapped.result <;> rfl
+ rw [post]
+ exact frame.report entry raw powers flush
+
+variable {a k : ℕ} (X : State a k)
+
+theorem VertexPacked.gatherRows (P : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord m)
+ (L : TerminalRootGather.Layout) (last : Fin D.levels) (tab : Fin D.shape.tables)
+ (capacity : TerminalPrefix.arcCount X ≤ slotCapacity D) (cells : TerminalPrefix.arcCount X ≤ tableWords D)
+ (incoming : L.incomingHead = incidenceBase D last (TerminalPrefix.arcCount X) 4)
+ (widths : L.widthHead = incidenceBase D last (TerminalPrefix.arcCount X) 5)
+ (starts : L.prefixHead = DescriptorSpace.tableBase D last tab)
+ (rows : TerminalGatherGeometry.Rows X L reference) : TerminalGatherGeometry.Rows X L m := by
+ apply rows.transfer X L
+ intro head hh i
+ rw [incoming,widths,starts] at hh
+ obtain ⟨low,high⟩ := P.heads last tab _ capacity cells head hh
+ have bound := P.arena
+ have ix := i.isLt
+ exact frame.below P.room (low.trans (Nat.le_add_right _ _)) (by omega)
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalVertexMemory.lean b/lean/OAI/Computability/VPVNP/PairTerminalVertexMemory.lean
new file mode 100644
index 0000000000..1d691496b8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalVertexMemory.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PairTerminalSharedBits
+import OAI.Computability.VPVNP.PairTraversalControllerMemory
+import OAI.Computability.VPVNP.PairSimulationTerminalProgram
+
+/-!
+# Readback at the actual entry of the terminal vertex phase
+
+The linked bit stage writes the shared interval and hands off through the two
+controller cells. Its physical post-memory carries the selected DFS child rows,
+role words and the same bit assignment. Earlier level descriptors and all
+noncontrol header fields are still readable by the native vertex interpreter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLayout
+
+open BurstRAM PrivateRAM Compression CompressorRecords TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+open private reads_above from OAI.Computability.VPVNP.PairTraversalRoleExecution
+
+variable {w : ℕ}
+
+private theorem high_offset (h : Word w) (fit : h.val + 32 ≤ 2 ^ w) (j : ℕ) (hj : j < 32) :
+ (h+(j : Word w)).val = h.val+j := by
+ rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j < 2^w),Nat.mod_eq_of_lt (by omega)]
+
+/-- All data read by the DFS and endpoint gather after the linked shared
+scan. The range of preserved header fields excludes the two stage controls. -/
+theorem linked_vertexMemory (workers : TerminalLink.Stage → LiveProgram.PairTable)
+ (bank : workers TerminalLink.Stage.sharedBits = ⟨28, 5, FinalBits.Worker.table⟩)
+ (pub : Fin 11 → Word w) (src phy : Memory w) (fuel cap base F : ℕ)
+ (roles : List TaggedLayer) (bits : Fin F → Bool)
+ (capacity : ∀ L ∈ roles.map TaggedLayer.layer, ∀ i, (L.ids i).length ≤ cap) :
+ let ls := roles.map TaggedLayer.layer
+ let size := words cap ls
+ let lo := base+size
+ let H := TerminalLink.header pub
+ let stage := TerminalLink.Entry.resume TerminalLink.Stage.sharedBits (0 : Word w)
+ let raw := FinalBits.Worker.reports pub 0 src bits
+ let linked := TerminalLink.stageReports H stage raw
+ let mem := after phy (eventLog linked)
+ FinalBits.Worker.Layout pub src lo F → H.val+32 ≤ 2^w → base+2*size+F ≤ H.val →
+ 54 ≤ fuel → stage.Valid H phy → SourceTransport.Agree (TerminalLink.workerCell H) src phy →
+ AllRows w src cap base base ls → Reads w src (size+F) cap base roles →
+ TerminalLink.StageRun workers pub fuel stage src phy (FinalBits.calls bits ++ [[]]) raw ∧
+ AllRows w mem cap base base ls ∧ Reads w mem (size+F) cap base roles ∧
+ (∀ i : Fin F, mem (lo+i) = PrimedInputRAM.encodeBit w (bits i)) ∧
+ (∀ x < base, mem x = src x) ∧
+ ∀ j : ℕ, 0 < j → j < 31 → mem (H+(j : Word w)).val = src (H+(j : Word w)).val := by
+ intro ls size lo H stage raw linked mem layout room above clock valid agree rows tags
+ have below : lo+F ≤ H.val := by dsimp only [lo]; omega
+ have run := FinalBits.Worker.stageRun workers bank pub src phy layout bits fuel clock room below
+ valid agree
+ have last : (H+31).val = H.val+31 := high_offset H room 31 (by decide)
+ have area (x : ℕ) (hx : x < H.val) : TerminalLink.workerCell H x :=
+ ⟨hx.ne,(by omega : x ≠ (H+31).val)⟩
+ have low (x : ℕ) (hx : x < lo) : mem x = src x := by
+ exact (run.agree x (area x (hx.trans_le (Nat.le_add_right lo F |>.trans below)))).symm.trans
+ (FinalBits.Worker.outside pub src layout bits x (Or.inl hx))
+ let rawOut := after src (eventLog raw)
+ have rawTags : Reads w rawOut (size+F) cap base roles :=
+ reads_above tags (fun x hx => FinalBits.Worker.outside pub src layout bits x
+ (Or.inr (by change base+size+F ≤ x; omega)))
+ refine ⟨run,ControllerMemory.allRows_below ls low le_rfl capacity rows,
+ ControllerMemory.reads_below roles (fun x hx => (run.agree x (area x hx)).symm)
+ (by change size+F+base+size ≤ H.val; omega) rawTags, ?_, ?_, ?_⟩
+ · intro i
+ have hi := i.isLt
+ exact (run.agree (lo+i) (area _ (by omega))).symm.trans
+ (FinalBits.Worker.readback pub src layout bits i)
+ · intro x hx
+ exact low x (hx.trans_le (Nat.le_add_right _ _))
+ · intro j hj hj'
+ have atJ := high_offset H room j (by omega)
+ have data : TerminalLink.workerCell H (H+(j : Word w)).val := ⟨by omega,by omega⟩
+ exact (run.agree _ data).symm.trans
+ (FinalBits.Worker.outside pub src layout bits _ (Or.inr (by omega)))
+
+end PairSimulation.TerminalLayout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedGather.lean b/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedGather.lean
new file mode 100644
index 0000000000..64482affc7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedGather.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.PairTerminalVertexFramePacked
+import OAI.Computability.VPVNP.PairVertexRootFields
+import OAI.Computability.VPVNP.PairTerminalPrefixBudget
+
+/-!
+# Root-gather operands at every physical site
+
+The terminal worker reloads the current vertex ordinal and six header words,
+including the live width, inverse, and prefix pointers. Its root layout
+agrees with the layout read from the physical shared-bit post-memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM PrivateRAM PairSimulation Compression CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles LocalHistory
+open scoped Fin.CommRing
+
+variable {G : Group} {D : DescriptorSpace.Layout} {cap width ord : ℕ} {roles : List TaggedLayer}
+variable {reference m : Memory G.w}
+local notation "pub" => terminalOperands G
+local notation "H" => vertexHeader G
+local notation "size" => tagWords cap roles
+local notation "first" => endAddress D
+local notation "lay" => TerminalRootGather.Layout.ofHeader
+
+theorem VertexPacked.gatherLayout (P : VertexPacked G D cap roles width)
+ (frame : LinkedVertexMemory G reference ord m) (degree : ℕ) (state : Word G.w) :
+ lay degree pub H state m = lay degree pub H state reference := by
+ simp only [TerminalRootGather.Layout.ofHeader, NativeFrame.fromHeader, NativeFrame.regions]
+ have h (j : ℕ) (hj : 0 < j) (hj' : j < 31) := P.header frame j hj hj'
+ have h7 : m (H+7).val = reference (H+7).val := h 7 (by decide) (by decide)
+ have h8 : m (H+8).val = reference (H+8).val := h 8 (by decide) (by decide)
+ have h9 : m (H+9).val = reference (H+9).val := h 9 (by decide) (by decide)
+ have h10 : m (H+10).val = reference (H+10).val := h 10 (by decide) (by decide)
+ have h11 : m (H+11).val = reference (H+11).val := h 11 (by decide) (by decide)
+ have h13 : m (H+13).val = reference (H+13).val := h 13 (by decide) (by decide)
+ have h6 : m (H+6).val = reference (H+6).val := h 6 (by decide) (by decide)
+ have h15 : m (H+15).val = reference (H+15).val := h 15 (by decide) (by decide)
+ rw [h7,h8,h9,h10,h11,h13,h6,h15]
+
+theorem VertexPacked.headerNumbering (P : VertexPacked G D cap roles width)
+ (frame : LinkedVertexMemory G reference ord m) {a k : ℕ} (X : State a k) (v : X.network.Site)
+ (degree : ℕ) (state : Word G.w) (index : state.val = ((siteOrder X).entries.symm v).val)
+ (sites : (reference (H+7).val).val = (siteOrder X).length)
+ (slots : (reference (H+8).val).val = TerminalPrefix.arcCount X) :
+ TerminalGatherGeometry.Numbering X (lay degree pub H state m) v := by
+ rw [P.gatherLayout frame degree state]
+ exact ⟨index,sites,slots⟩
+
+/-- Inputs consumed by the concrete gather's DFS handoff. Its private end
+fit is supplied by the site's argument arena. All external fits and the
+typed shared-bit and row equalities are recovered from the packed layout. -/
+theorem VertexPacked.gather (P : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord m)
+ {a k : ℕ} (X : State a k) (v : X.network.Site) (degree : ℕ) (state : Word G.w)
+ (last : Fin D.levels) (tab : Fin D.shape.tables) (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (width_eq : width = X.totalWidth)
+ (capacity : TerminalPrefix.arcCount X ≤ slotCapacity D) (cells : TerminalPrefix.arcCount X ≤ tableWords D)
+ (index : state.val = ((siteOrder X).entries.symm v).val)
+ (sites : (reference (H+7).val).val = (siteOrder X).length)
+ (slots : (reference (H+8).val).val = TerminalPrefix.arcCount X)
+ (incoming : (reference (H+10).val).val = incidenceBase D last (TerminalPrefix.arcCount X) 4)
+ (widths : (reference (H+9).val).val = incidenceBase D last (TerminalPrefix.arcCount X) 5)
+ (starts : (reference (H+11).val).val = DescriptorSpace.tableBase D last tab)
+ (wires : (reference (H+13).val).val = first+size)
+ (rows : TerminalGatherGeometry.Rows X (lay degree pub H state reference) reference)
+ (bits : ∀ i, reference (first+size+i.val) = PrivateFields.bitValue G.w (f i))
+ (privateFit : (lay degree pub H state reference).dest + (∑ dir : Bool, ∑ j, X.halfWidth v dir j) < 2^G.w) :
+ let L := lay degree pub H state m
+ TerminalGatherGeometry.Numbering X L v ∧ TerminalGatherGeometry.Rows X L m ∧
+ (∀ i, m (L.wires+i.val) = PrivateFields.bitValue G.w (f i)) ∧ L.Fits m ∧
+ L.packet m = (NodeArguments.packed X v (TerminalGatherGeometry.half X f v)).map (PrivateFields.bitValue G.w) := by
+ intro L
+ dsimp only [L]
+ rw [P.gatherLayout frame degree state]
+ let L₀ := lay degree pub H state reference
+ have num : TerminalGatherGeometry.Numbering X L₀ v := ⟨index,sites,slots⟩
+ have dir := P.gatherRows X frame L₀ last tab capacity cells incoming widths starts rows
+ have hi := P.arena
+ have lo := P.counter_rows
+ have room := P.room
+ have hw : L₀.wires = first+size := wires
+ have wb : ∀ i, m (L₀.wires+i.val) = PrivateFields.bitValue G.w (f i) := by
+ intro i
+ have ix := i.isLt.trans_eq (TerminalPrefix.width_sum X)
+ rw [hw]
+ exact (frame.below room (by omega) (by omega)).trans (bits i)
+ have heads (head : ℕ) (hh : head ∈ [L₀.incomingHead,L₀.widthHead,L₀.prefixHead]) :
+ head+TerminalPrefix.arcCount X ≤ 2^G.w := by
+ change head ∈ [(reference (H+10).val).val,(reference (H+9).val).val,(reference (H+11).val).val] at hh
+ rw [incoming,widths,starts] at hh
+ have upper := (P.heads last tab _ capacity cells head hh).2
+ omega
+ have count := (P.heads last tab _ capacity cells (DescriptorSpace.tableBase D last tab) (by simp)).2
+ exact ⟨num,dir,wb,TerminalGatherGeometry.fits num dir f wb (by omega) heads
+ (by rw [hw]; omega) privateFit,TerminalGatherGeometry.packet_eq num dir f wb⟩
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedHeaders.lean b/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedHeaders.lean
new file mode 100644
index 0000000000..0557555da2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedHeaders.lean
@@ -0,0 +1,169 @@
+import OAI.Computability.VPVNP.PairTerminalVertexPackedStage
+import OAI.Computability.VPVNP.PairTerminalSelectedHeaders
+import OAI.Computability.VPVNP.PairTerminalVertexPackedGather
+import OAI.Computability.VPVNP.PairTerminalPrefixLinked
+import OAI.Computability.VPVNP.PairTraversalControllerTerminal
+
+/-!
+# Terminal bootstrap fields at the native vertex handoff
+
+The prefix scan changes the total and role displacement. The traversal writes
+the selected rows and tags, and the shared-bit scan writes the selected bit
+bank. All three physical phases preserve the bootstrap values used by the
+root gather and by the per-site geometry initializer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalPrefix.Linked
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace TerminalLink
+open scoped Fin.CommRing
+
+variable {w a g : ℕ} {workers : TerminalLink.Stage → LiveProgram.PairTable}
+variable {pub : Fin 11 → Word w} {cap fuel : ℕ} {X : State a g} {T : IncidenceDirectory w}
+variable {base : Word w} {calendar : Memory w} {rs : List (Report w)}
+
+open private at_offset from OAI.Computability.VPVNP.PairTerminalVertexFrameLinked
+
+/-- Only the running total, the role offset and the two terminal controls
+can differ from the bootstrap image inside the header. -/
+theorem Start.prefixField {raw : Report w} (s : Start workers pub cap fuel X T base calendar raw rs)
+ (room : (header pub).val+32 ≤ 2^w) (below : base.val + arcCount X ≤ (header pub).val)
+ (j : ℕ) (lo : 0 terminalOperands G
+local notation "H" => vertexHeader G
+local notation "size" => tagWords limit roles
+local notation "first" => endAddress D
+
+open private at_offset from OAI.Computability.VPVNP.PairTerminalVertexFrameLinked
+
+/-- The traversal controller's physical handoff preserves all high data
+fields. The raw memory image comes from its verified native Segment. -/
+theorem VertexPacked.traversalField (P : VertexPacked G D limit roles width)
+ (workers : TerminalLink.Stage → PairTable) (fuel cap calls probes : ℕ) (src phy : Memory G.w)
+ (out : List (Report G.w))
+ (segment : TraversalController.Segment (TraversalController.Native.machine pub).program fuel
+ (some 0) none src (build limit first first (roles.map TaggedLayer.layer)
+ (writeTags (size+width) limit first roles src)) calls probes out)
+ (stage : StageRun workers pub cap (.resume TerminalLink.Stage.traversalRows 0) src phy
+ (List.replicate calls []) out)
+ (j : ℕ) (lo : 0 terminalOperands G
+local notation "H" => vertexHeader G
+local notation "size" => tagWords cap roles
+local notation "first" => endAddress D
+
+open private at_offset from OAI.Computability.VPVNP.PairTerminalVertexFrameLinked
+
+theorem VertexPacked.traversalBelow (P : VertexPacked G D cap roles width)
+ (workers : TerminalLink.Stage → PairTable) (fuel outer calls probes : ℕ) (src phy : Memory G.w)
+ (out : List (Report G.w))
+ (segment : TraversalController.Segment (TraversalController.Native.machine pub).program fuel
+ (some 0) none src (build cap first first (roles.map TaggedLayer.layer)
+ (writeTags (size+width) cap first roles src)) calls probes out)
+ (stage : StageRun workers pub outer (.resume TerminalLink.Stage.traversalRows 0) src phy
+ (List.replicate calls []) out)
+ (x : ℕ) (hx : x < first) :
+ after phy (eventLog (stageReports H (.resume TerminalLink.Stage.traversalRows 0) out)) x = src x := by
+ have at31 : (H+31).val = (H).val+31 := at_offset _ P.room 31 (by decide)
+ have hi := P.arena
+ have safe : workerCell H x := ⟨by omega,by omega⟩
+ have agree := (stage.agree x safe).symm
+ rw [segment.memory,build_outside _ _ _ _ _ _ (.inl hx),
+ write_tags_outside _ _ _ _ _ _ (.inl (hx.trans_le (Nat.le_add_left _ _)))] at agree
+ exact agree
+
+variable {i : Fin (2^(sizes G).h)} {before reference m bootMem : Memory G.w}
+variable {N : Indexed G LiveProgram.Stage.nominations before (Nominations.Nom G)} {μ : Nominations.Nom G}
+variable {hdr : Header (pairLengths G i) → Bool}
+
+/-- The native vertex's immutable geometry and shadow suffice for the actual
+typed auxiliary leaf, including the original nominal production words. -/
+theorem VertexPacked.leafOperands (P : VertexPacked G D cap roles width)
+ (frame : LinkedVertexMemory G reference ord m) (B : PreparedBranch G before i hdr N μ)
+ (Q : PrimedInputRAM.Layout (pairLengths G i) G.g.n G.g.d G.g.H G.w) (degree : Fin G.g.n)
+ (root : Fin (states G)) (slotDegree : ℕ) (role : Word G.w) {b l : ℕ}
+ (read : NativeFrame.Readback reference H first size (cap+2) (2^b) (2^l)
+ (TerminalBootstrap.shadowSpan pub bootMem))
+ (descriptor : bootMem (histogramCell G) = B.copy.memory () (histogramCell G))
+ (stored : ∀ j < span (pairLengths G i) (histLength G),
+ reference ((pub 3).val+j) = headerMemory (pairLengths G i) hdr (histogram G μ) j)
+ (hn : 1 ≤ G.g.n) (capacity : span (pairLengths G i) (histLength G) ≤ 2^(virtualSiteExponent G.g.d G.g.n))
+ {p r k : ℕ} (pc : LeafImage.Label → Fin p) (reg : LeafImage.Reg ↪ Fin r)
+ (operand : LeafImage.Pub → Fin k) (ret : Fin p) (M : Machine G.w p r k)
+ (assigned : M.publicData ∘ operand = leafWords slotDegree pub H role m ∘ LeafGeometryLoad.slot)
+ (sizeFit : G.g.n < 2^G.w) (shapeFit : max (cap+2) (max (2^b) (2^l)) < 2^G.w) :
+ LeafFront.Operands (LeafImage.front pc reg operand ret) M m
+ (Data.ofNomination Q degree root hdr (nominationEquiv G μ)) (fromHeader slotDegree pub H m) b l cap ∧
+ M.publicData (operand .size) = (G.g.n : Word G.w) := by
+ have shadowFit : shadowBase G < 2^G.w := by
+ have baseFit := P.fit
+ change shadowBase G + _ < 2^G.w at baseFit
+ omega
+ have baseVal : (pub 3).val = shadowBase G := Nat.mod_eq_of_lt shadowFit
+ have room := shadow_span_room G i hn P.fit capacity
+ have extent : shadowBase G + span (pairLengths G i) (histLength G) ≤ 2^G.w :=
+ baseVal ▸ (room.trans (pub 2).isLt.le)
+ apply B.leafOperands Q degree root slotDegree H role bootMem m (P.geometry frame read) descriptor
+ _ pc reg operand ret M assigned P.fit sizeFit shapeFit extent
+ intro j hj
+ exact ((P.shadow frame i hn capacity hj).trans (stored j hj)).trans (B.shadowRead j).symm
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedStage.lean b/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedStage.lean
new file mode 100644
index 0000000000..fa8e5fdfa6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedStage.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.PairTerminalVertexFramePacked
+
+/-!
+# From the native shared scan to each packed vertex
+
+Every subsequent site sees the exact rows, role tags and shared choices
+of the accepted bit worker. It also sees the earlier level arrays and the
+noncontrol header cells from that worker's input. The two control words
+may be rewritten at each site handoff.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM PrivateRAM PairSimulation Compression CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles TerminalLink
+open scoped Fin.CommRing
+
+variable {G : Group} {D : DescriptorSpace.Layout} {limit width : ℕ} {roles : List TaggedLayer}
+local notation "pub" => terminalOperands G
+local notation "H" => vertexHeader G
+local notation "size" => tagWords limit roles
+local notation "first" => endAddress D
+local notation "lo" => endAddress D + tagWords limit roles
+
+/-- A single true shared-bit stage supplies the reference memory for all
+subsequent ordinals. Its data include the exact branch bit at every wire. -/
+theorem VertexPacked.shared (P : VertexPacked G D limit roles width)
+ (workers : TerminalLink.Stage → PairTable) (bank : workers TerminalLink.Stage.sharedBits = ⟨28,5,FinalBits.Worker.table⟩)
+ (src phy : Memory G.w) (fuel : ℕ) (clock : 54 ≤ fuel) (bits : Fin width → Bool)
+ (layout : FinalBits.Worker.Layout pub src lo width)
+ (valid : (Entry.resume TerminalLink.Stage.sharedBits (0 : Word G.w)).Valid H phy)
+ (agree : SourceTransport.Agree (workerCell H) src phy)
+ (capacity : ∀ l ∈ roles.map TaggedLayer.layer, ∀ i, (l.ids i).length ≤ limit)
+ (rows : AllRows G.w src limit first first (roles.map TaggedLayer.layer))
+ (tags : Reads G.w src (size+width) limit first roles) :
+ let stage := Entry.resume TerminalLink.Stage.sharedBits (0 : Word G.w)
+ let raw := FinalBits.Worker.reports pub 0 src bits
+ let post := after phy (eventLog (stageReports H stage raw))
+ StageRun workers pub fuel stage src phy (FinalBits.calls bits ++ [[]]) raw ∧
+ ∀ {ord : ℕ} {m : Memory G.w}, LinkedVertexMemory G post ord m →
+ AllRows G.w m limit first first (roles.map TaggedLayer.layer) ∧
+ Reads G.w m (size+width) limit first roles ∧
+ (∀ i, m (lo+i.val) = PrivateFields.bitValue G.w (bits i)) ∧
+ (∀ x, D.base ≤ x → x < first → m x = src x) ∧
+ ∀ j : ℕ, 0 < j → j < 31 → m (H+(j : Word G.w)).val = src (H+(j : Word G.w)).val := by
+ intro stage raw post
+ obtain ⟨run, child, role, stored, lower, upper⟩ := TerminalLayout.linked_vertexMemory workers bank
+ pub src phy fuel limit first width roles bits capacity layout P.room P.arena clock valid agree rows tags
+ refine ⟨run,fun {ord} {m} frame => ?_⟩
+ exact ⟨P.rows frame capacity child,P.roleWords frame role,P.bits frame bits stored,
+ fun x hx hx' => (P.directory frame hx hx').trans (lower x hx'),
+ fun j hj hj' => (P.header frame j hj hj').trans (upper j hj hj')⟩
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedThreshold.lean b/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedThreshold.lean
new file mode 100644
index 0000000000..1c3d4d6b96
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTerminalVertexPackedThreshold.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.PairTerminalVertexFramePacked
+import OAI.Computability.VPVNP.PairTerminalPrefixBudget
+import OAI.Computability.VPVNP.CompressorBlockCapacity
+
+/-!
+# Selected vertex arenas in the chronological block allocation
+
+The public header bounds hold at one length threshold before the coordinate
+split, coefficient specialization and compressor choices. The chronological
+directory used by the native calendar lies inside the reserved rectangle.
+The terminal state's incidence and prefix tables fit even at zero blocks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.PairStages.Group.Auxiliary
+
+open BurstRAM PairSimulation Compression CompressorRecords DescriptorSpace
+open CursorBounds CursorNetwork Filter TraversalRoles TraversalRows
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+
+theorem selected_table_capacity {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f)
+ {l : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ l) (X : State (S.degreeExponent 0) l)
+ (z : (B.execute f hf T hT X).Choices) (workspace : ℕ) :
+ let D := BlockProgram.layout B workspace X.positions T
+ let Y := (B.execute f hf T hT X).finalState z
+ TerminalPrefix.arcCount Y ≤ slotCapacity D ∧ TerminalPrefix.arcCount Y ≤ tableWords D := by
+ intro D Y
+ have positions : Y.positions ≤ X.positions :=
+ (Nat.le_mul_of_pos_left _ (Nat.pow_pos (by have := S.positionFactor_gt_two; omega))).trans_eq
+ (B.branch_bounds f hf T hT X z).1.symm
+ have degree : 2^S.degreeExponent 0 ≤ slotDegree S :=
+ (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ 0)).trans
+ (le_max_right _ _)
+ have slots : TerminalPrefix.arcCount Y ≤ slotCapacity D := by
+ rw [TerminalPrefix.Segment.arc_count_positions]
+ exact Nat.mul_le_mul positions degree
+ exact ⟨slots,slots.trans (Nat.le_mul_of_pos_right _ (by change 0 < max _ _+3; omega))⟩
+
+/-- The actual terminal header and all external arrays of a selected branch
+in the live group. The site ordinal plays no role in the threshold. -/
+theorem eventually_vertexPacked (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ {start : ℕ → ℕ} (hstart : PolynomiallyBounded start) :
+ ∀ᶠ n : ℕ in atTop, ∀ (G : Group) (_ : G.w = wordBits b n)
+ (_ : (LiveProgram.Layout.pairWorkspace G.constants).eval G.g = start n)
+ (_ : (terminalOperands G 7).val = addressBits b n)
+ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n*S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ let D := BlockProgram.layout B (start n) X.positions T
+ ∀ z : E.Choices, VertexPacked G D B.recordLimit (selected B f hf T hT X z) (E.finalState z).totalWidth := by
+ filter_upwards [TerminalLayout.eventually_fit B u (BlockProgram.allocationShape B) b hb hstart 0,
+ CursorRAM.eventual_word_room b ((by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)) hstart]
+ with n full startFit
+ intro G hw workspace exp base lanes labels hD hT A _ f hf X T E D z
+ let r := addressBits b n
+ let Y := E.finalState z
+ let rows := words B.recordLimit (selectedLayers B f hf T hT X z)
+ let bound := cursorLayout (BlockProgram.allocationShape B) b S.steps u.θ (start n) n
+ have whole := full labels hD hT A f hf z
+ change endAddress bound + 2*rows + Y.totalWidth < (start n + (2^r)^2 - 32) ∧
+ start n + (2^r)^2 - 32 + 32 ≤ 2^(wordBits b n) ∧ _ at whole
+ have count := pairInput_positions S labels hD
+ change X.positions = initialPositions b n at count
+ have actual : endAddress D ≤ endAddress bound := by
+ change endAddress (BlockProgram.layout B (start n) X.positions T) ≤ _
+ rw [count]
+ exact BlockProgram.allocation_end B (start n) (initialPositions b n) T
+ have wsFit : (LiveProgram.Layout.pairWorkspace G.constants).eval G.g < 2^G.w := by
+ rwa [workspace,hw]
+ have ws : (terminalOperands G 2).val = D.base := by
+ change (LiveProgram.Layout.pairWorkspace G.constants).eval G.g % (2^G.w) = start n
+ rw [Nat.mod_eq_of_lt wsFit, workspace]
+ have rwFit : r < G.w := hw ▸ ((by omega : r < r+10).trans_le
+ (Nat.le_self_pow (by decide : 4 ≠ 0) _))
+ have high := whole.1
+ have room := whole.2.1
+ rw [pow_two] at high room
+ have reserve : 32 ≤ D.base + 2^r*2^r := by change 32 ≤ start n + 2^r*2^r; omega
+ have word : D.base+2^r*2^r ≤ 2^G.w := by change start n+2^r*2^r ≤ 2^G.w; rw [hw]; omega
+ have head : (vertexHeader G).val = start n+2^r*2^r-32 :=
+ TerminalPrefix.header_val D (terminalOperands G) r ws exp rwFit reserve word
+ have size : tagWords B.recordLimit (selected B f hf T hT X z) = rows :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ refine ⟨wsFit,ws.symm,by rw [head,hw]; exact room,?_⟩
+ rw [head,size]
+ exact (Nat.add_le_add_right (Nat.add_le_add_right actual (2*rows)) Y.totalWidth).trans high.le
+
+end LiveProgram.PairStages.Group.Auxiliary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalArena.lean b/lean/OAI/Computability/VPVNP/PairTraversalArena.lean
new file mode 100644
index 0000000000..a039a644b0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalArena.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.PairTraversalDirectoryRun
+import OAI.Computability.VPVNP.PairTraversalLevelDirectories
+import OAI.Computability.VPVNP.PairTraversalRoleDispatch
+
+/-!
+# Native traversal arena for a selected compressor branch
+
+The actual level-indexed placement scans feed a fixed leaf worker followed by
+a fixed fiber worker. A fixed tag writer marks the same selected layers from
+their retained pass origins. The programs share one external memory, and
+their writes preserve the final-arc bit words between rows and tags.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRoles
+
+open BurstRAM CompressorRecords TraversalRows DirectoryRun LocalHistory Compression
+open scoped Fin.CommRing
+
+variable {w : ℕ} {k A : Type*} [Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ}
+variable (T : ℕ) (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+
+private theorem one_probe_each (rs : List (Report w)) (h : ∀ r ∈ rs, r.probes = 1) :
+ countProbes (eventLog rs) = rs.length := by
+ induction rs with
+ | nil => rfl
+ | cons r tail ih =>
+ change countProbes (r.events ++ eventLog tail) = tail.length + 1
+ rw [BurstRAM.countProbes_append, show countProbes r.events = 1 from h r List.mem_cons_self,
+ ih (fun t ht => h t (List.mem_cons_of_mem _ ht)), Nat.add_comm]
+
+/-- Construct the selected descriptor arena in a shared native memory. Its
+DFS rows and role words are read back at their actual native addresses and
+every final bit remains available. Each worker costs a bounded number of
+probes and bursts per selected row, independently of all wire widths. -/
+theorem native_arena (base F : ℕ) (m : Memory w)
+ (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] m base)
+ (fit : base + 2 * words B.recordLimit (selectedLayers B f hf T hT X z) + F < 2 ^ w) :
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ords := branchOrders E data z
+ let old := siteOrder X
+ let cap := B.recordLimit
+ let ls := selectedLayers B f hf T hT X z
+ let offset := words cap ls + F
+ let roles := selected B f hf T hT X z
+ let dirs := selectedDirectories B f hf T hT X z m base ds
+ let rowJobs := Worker.leaf cap base old.length ::
+ workers c ords old dirs cap base (address cap base old.length)
+ ∃ ts rs, RolePasses offset cap base roles m ts ∧
+ Segments rowJobs (after m (eventLog ts)) rs ∧
+ let final := after m (eventLog (ts ++ rs))
+ final = build cap base base ls (writeTags offset cap base roles m) ∧
+ Reads w final offset cap base roles ∧ AllRows w final cap base base ls ∧
+ (∀ i < F, final (base + words cap ls + i) = m (base + words cap ls + i)) ∧
+ ts.length + rs.length ≤ 2 * (((S.steps + 1) * T + 1) * X.positions) ∧
+ countProbes (eventLog (ts ++ rs)) ≤
+ (2 * cap + 4) * (((S.steps + 1) * T + 1) * X.positions) := by
+ intro E data c ords old cap ls offset roles dirs rowJobs
+ let visits := ((S.steps + 1) * T + 1) * X.positions
+ let size := words cap ls
+ have room : base + size < 2 ^ w := by change base + 2 * size + F < _ at fit; omega
+ obtain ⟨ts, ht, tagMem, _, tagCalls, tagCost, _⟩ := native_selected_roles B f hf T hT X z
+ base F m fit.le
+ let tagged := after m (eventLog ts)
+ have ag (x : ℕ) (hx : x < base) : tagged x = m x := by
+ dsimp only [tagged]
+ rw [tagMem]
+ exact write_tags_outside offset cap base roles m x (Or.inl (hx.trans_le (Nat.le_add_left _ _)))
+ obtain ⟨rs, hr, mem, calls, probes⟩ := DirectoryRun.selected_run B f hf T hT X z base m
+ tagged ag room dirs
+ let final := after m (eventLog (ts ++ rs))
+ have hfinal : final = build cap base base ls (writeTags offset cap base roles m) := by
+ change after m (eventLog (ts ++ rs)) = _
+ rw [show after m (eventLog (ts ++ rs)) = after tagged (eventLog rs) from by
+ simp only [eventLog, List.flatMap_append, after, List.foldl_append, tagged], mem]
+ exact congrArg (build cap base base ls) tagMem
+ obtain ⟨reads, bits, rows⟩ := selected_tags_and_rows B f hf T hT X z base F m room
+ have visitsBound : (ls.map Layer.count).sum ≤ visits := selected_count_sum_le B f hf T hT X z
+ have tc := one_probe_each ts (fun t ht => (tagCost t ht).2)
+ refine ⟨ts, rs, ht, hr, hfinal, ?_, ?_, ?_, ?_, ?_⟩
+ · change Reads w final offset cap base roles
+ rw [hfinal]
+ exact reads
+ · change AllRows w final cap base base ls
+ rw [hfinal]
+ exact rows
+ · change ∀ i < F, final _ = _
+ rw [hfinal]
+ exact bits
+ · have h := calls.trans_le visitsBound
+ change ts.length ≤ visits at tagCalls
+ omega
+ · change countProbes (eventLog (ts ++ rs)) ≤ (2 * cap + 4) * visits
+ simp only [eventLog, List.flatMap_append, BurstRAM.countProbes_append]
+ change countProbes (eventLog ts) + countProbes (eventLog rs) ≤ _
+ have h := Nat.add_le_add (tc.trans_le tagCalls)
+ (probes.trans (Nat.mul_le_mul_left _ visitsBound))
+ exact h.trans_eq (by change visits + (2 * cap + 3) * visits = _; ring)
+
+end PairSimulation.TraversalRoles
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalBuildExecution.lean b/lean/OAI/Computability/VPVNP/PairTraversalBuildExecution.lean
new file mode 100644
index 0000000000..e88f972609
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalBuildExecution.lean
@@ -0,0 +1,197 @@
+import OAI.Computability.VPVNP.PairTraversalLayerExecution
+
+/-!
+# Native construction of all depth-first traversal rows
+
+The raw preimage records from Appendix E are translated layer by layer.
+Every native pass reads identifiers below the descriptor arena, and writes
+only the live words of its own row. Consequently the raw inputs and the
+completed older layers survive. The final memory is precisely the image
+used by the depth-first traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open BurstRAM CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Locations of the count and old-site identifier list for each site. -/
+structure Source (w : ℕ) (L : Layer) where
+ /-- External address of the cell holding the number of old-site identifiers for each site of
+ this layer. -/
+ counts : Fin L.count → Word w
+ /-- External address of the first identifier in each site's list of preimages in the
+ preceding layer. -/
+ starts : Fin L.count → Word w
+
+/-- The Appendix E records lie below the fresh traversal arena. -/
+structure Source.Ready {L : Layer} (r : Source w L) (mem : Memory w) (limit : ℕ) : Prop where
+ rows : ∀ i, rowRepresents mem (r.counts i) (r.starts i)
+ ((L.ids i).map (fun j : ℕ => (j : Word w)))
+ countBefore : ∀ i, (r.counts i).val < limit
+ sourceBefore : ∀ i, (r.starts i).val + (L.ids i).length ≤ limit
+
+/-- The shared zero word can supply the zero count for every cursor leaf. -/
+def leafSource {I : Type} (ord : LocalHistory.Order I) (zero : Word w) :
+ Source w (leafLayer ord) := ⟨fun _ => zero, fun _ => zero⟩
+
+theorem leafSource_ready {I : Type} (ord : LocalHistory.Order I) (zero : Word w) (mem : Memory w)
+ {limit : ℕ} (hzero : mem zero.val = 0) (hbelow : zero.val < limit) :
+ (leafSource ord zero).Ready mem limit := by
+ refine ⟨fun _ => ⟨?_, fun i => Fin.elim0 i⟩, fun _ => hbelow, fun _ => hbelow.le⟩
+ change (mem zero.val).val = 0
+ rw [hzero]
+ rfl
+
+/-- The raw record directories, in increasing compressor-stage order. -/
+def Sources (w : ℕ) : List Layer → Type
+ | [] => PUnit
+ | L :: ls => Source w L × Sources w ls
+
+/-- Each layer's source directory describes the correct old-site identifier lists in memory,
+with all count cells and live identifier cells below `limit`. -/
+def SourcesReady (mem : Memory w) (limit : ℕ) : (ls : List Layer) → Sources w ls → Prop
+ | [], _ => True
+ | _ :: ls, r => r.1.Ready mem limit ∧ SourcesReady mem limit ls r.2
+
+private theorem transfer_ready (ls : List Layer) (sources : Sources w ls) {mem mem' : Memory w}
+ {limit limit' : ℕ} (le : limit ≤ limit') (below : ∀ x < limit, mem' x = mem x)
+ (h : SourcesReady mem limit ls sources) : SourcesReady mem' limit' ls sources := by
+ induction ls with
+ | nil => trivial
+ | cons L ls ih =>
+ have hc := h.1.countBefore
+ have hs := h.1.sourceBefore
+ refine ⟨⟨fun i => ?_, fun i => (hc i).trans_le le, fun i => (hs i).trans le⟩,
+ ih sources.2 h.2⟩
+ have r := h.1.rows i
+ refine ⟨(congrArg Fin.val (below _ (hc i))).trans r.1, fun j => ?_⟩
+ have hj : j.val < (L.ids i).length := by simpa only [List.length_map] using j.isLt
+ exact (below _ ((Nat.add_lt_add_left hj _).trans_le (hs i))).trans (r.2 j)
+
+/-- Each layer's actual scan begins with the memory left by its predecessor.
+The trace lists concatenate the native instruction events in that order. -/
+inductive BuildPasses (cap : ℕ) (state : Word w) (priv : Word w → Word w) :
+ (previous base : ℕ) → (ls : List Layer) → Sources w ls → Memory w → List (Event w) → Prop
+ | nil (previous base : ℕ) (sources : Sources w []) (m : Memory w) :
+ BuildPasses cap state priv previous base [] sources m []
+ | cons {previous base : ℕ} {L : Layer} {ls : List Layer} {sources : Sources w (L :: ls)}
+ {m : Memory w} {es tail : List (Event w)}
+ (stage : LayerPasses L cap previous base state priv sources.1.counts sources.1.starts
+ (List.finRange L.count) m es)
+ (rest : BuildPasses cap state priv base (endPos cap base L) ls sources.2 (after m es) tail) :
+ BuildPasses cap state priv previous base (L :: ls) sources m (es ++ tail)
+
+/-- Two probes for each identifier, plus three probes for each header. -/
+def Layer.probeCount (L : Layer) : ℕ := (2 * ∑ i, (L.ids i).length) + 3 * L.count
+
+theorem probes_le (ls : List Layer) (cap : ℕ) (hc : ∀ L ∈ ls, ∀ i, (L.ids i).length ≤ cap) :
+ (ls.map Layer.probeCount).sum ≤ (2 * cap + 3) * (ls.map Layer.count).sum := by
+ induction ls with
+ | nil => simp
+ | cons L ls ih =>
+ have hi := Finset.sum_le_sum (s := Finset.univ) (fun i _ => hc L List.mem_cons_self i)
+ have hsum : (∑ i, (L.ids i).length) ≤ L.count * cap := by simpa using hi
+ have hL : L.probeCount ≤ (2 * cap + 3) * L.count := by
+ unfold Layer.probeCount
+ exact (Nat.add_le_add_right (Nat.mul_le_mul_left 2 hsum) _).trans_eq (by ring)
+ simpa [Nat.mul_add] using Nat.add_le_add hL (ih (fun l hl => hc l (List.mem_cons_of_mem _ hl)))
+
+private theorem countProbes_append (x y : List (Event w)) :
+ countProbes (x ++ y) = countProbes x + countProbes y := by
+ induction x with
+ | nil => simp [countProbes]
+ | cons e x ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+/-- Construct all layers from their live raw count and identifier records.
+The proof executes each native pass and obtains the exact descriptor image
+as its post-memory. -/
+theorem native_build (ls : List Layer) (cap previous base : ℕ) (state : Word w)
+ (priv : Word w → Word w) (sources : Sources w ls) (mem : Memory w)
+ (ready : SourcesReady mem base ls sources) (hc : ∀ L ∈ ls, ∀ i, (L.ids i).length ≤ cap)
+ (fit : base + words cap ls < 2 ^ w) :
+ ∃ es, BuildPasses cap state priv previous base ls sources mem es ∧
+ after mem es = build cap previous base ls mem ∧
+ countProbes es = (ls.map Layer.probeCount).sum := by
+ induction ls generalizing previous base mem with
+ | nil => exact ⟨[], .nil _ _ _ _, rfl, rfl⟩
+ | cons L ls ih =>
+ let next := endPos cap base L
+ have hfit : next + words cap ls < 2 ^ w := by
+ simpa [next, endPos, address, words, Nat.mul_add, Nat.add_assoc] using fit
+ obtain ⟨ss, stage, hmem, probes⟩ := native_layer L cap previous base state priv
+ sources.1.counts sources.1.starts mem ready.1.rows ready.1.countBefore ready.1.sourceBefore
+ (hc L List.mem_cons_self) ((Nat.le_add_right _ _).trans_lt hfit)
+ have hbefore (x : ℕ) (hx : x < base) : after mem ss x = mem x := by
+ rw [hmem]
+ apply writeLayer_unchanged
+ rintro ⟨i, h, _⟩
+ exact hx.not_ge ((Nat.le_add_right base _).trans h)
+ have hr := transfer_ready ls sources.2 (limit' := next) (Nat.le_add_right _ _) hbefore ready.2
+ obtain ⟨es, tail, hm, hp⟩ := ih base next sources.2 (after mem ss) hr
+ (fun L hL => hc L (List.mem_cons_of_mem _ hL)) hfit
+ refine ⟨ss ++ es, .cons stage tail, ?_, ?_⟩
+ · rw [show after mem (ss ++ es) = after (after mem ss) es from List.foldl_append, hm, hmem]
+ rfl
+ · rw [countProbes_append, hp, probes]
+ rfl
+
+section Selected
+
+open LocalHistory NetworkKernel Compression
+
+variable {k A : Type*} [Field k] [CommRing A] {S : BlockSchedule k} (B : S.Templates)
+variable (f : B.Entry → A) (hf : B.IsSolution f) {lanes : ℕ} (T : ℕ)
+variable (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+
+theorem selected_capacity :
+ ∀ L ∈ selectedLayers B f hf T hT X z, ∀ i, (L.ids i).length ≤ B.recordLimit := by
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ have hb := Procedure.repeat_recordBounds (B.recordBounds f hf) _ T lanes
+ (Nat.add_sub_of_le hT).symm X
+ exact chainLayers_capacity (E.termChain data z) (selectedParsers B f hf T hT X z)
+ (branchOrders E data z) (siteOrder X) (E.termChain_bounded data hb.1 z)
+
+/-- On an actual selected compressor branch, the native builder passes their
+post-memory directly to the ordered DFS. The two probe counts measure the
+whole build and a single final vertex's traversal respectively. -/
+theorem selected_native_traversal (base : ℕ) (state : Word w) (priv : Word w → Word w)
+ (sources : Sources w (selectedLayers B f hf T hT X z)) (mem : Memory w)
+ (ready : SourcesReady mem base _ sources)
+ (fit : base + words B.recordLimit (selectedLayers B f hf T hT X z) < 2 ^ w) :
+ let ls := selectedLayers B f hf T hT X z
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let chain := E.termChain data z
+ let ptr := chainPointers B.recordLimit chain (branchOrders E data z)
+ (address B.recordLimit base (siteOrder X).length)
+ let leaf := sitePointers B.recordLimit base (siteOrder X)
+ let trees := chainTrees chain (selectedParsers B f hf T hT X z) ptr (fun v => leafTree (leaf v))
+ ∃ es, BuildPasses B.recordLimit state priv base base ls sources mem es ∧
+ after mem es = build B.recordLimit base base ls mem ∧
+ countProbes es ≤ (2 * B.recordLimit + 3) * (ls.map Layer.count).sum ∧
+ ∀ v, ∃ log, DFS.Visits (after mem es) (B.growthConstant ^ T) [((trees v).address : Word w)]
+ ((trees v).preorder.map (fun n : ℕ => (n : Word w))) log ∧
+ countProbes log < 3 * chain.occurrences (fun _ => 1) v ∧
+ log.length ≤ 15 * chain.occurrences (fun _ => 1) v + 1 := by
+ have hc := selected_capacity B f hf T hT X z
+ obtain ⟨es, hpass, hm, hcost⟩ := native_build _ _ base base state priv sources mem ready hc fit
+ refine ⟨es, hpass, hm, hcost.trans_le (probes_le _ _ hc), ?_⟩
+ rw [hm]
+ exact selected_memory_traversal B f hf T hT X z base mem fit
+
+end Selected
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerBody.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerBody.lean
new file mode 100644
index 0000000000..d7ea05036f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerBody.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.PairTraversalControllerFormula
+
+/-!
+# Replaying the existing descriptor workers inside the traversal controller
+
+The controller reads each parameter bank from live memory. When these words
+match the completed level directory, each embedded body has the exact report
+of its standalone reset-entry worker. In particular the controller adds no
+write to those of the actual descriptor or role pass.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM TraversalRows
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- One traversal pass over a specified number of sites. A tag pass writes roles, a leaf pass
+writes empty child headers, and a fiber pass translates child identifiers using its
+capacity bound. -/
+inductive Pass (w : ℕ) where
+ | tag (params : Fin 4 → Word w) (count : ℕ)
+ | leaf (params : Fin 2 → Word w) (count : ℕ)
+ | fiber (params : Fin 6 → Word w) (cap count : ℕ)
+
+/-- Number of site-worker bursts scheduled for this pass. -/
+def Pass.count : Pass w → ℕ
+ | .tag _ n | .leaf _ n | .fiber _ _ n => n
+
+/-- Fuel per reference burst, fixed at 12 for tagging, 14 for leaf headers and `7 * cap + 25`
+for fiber rows. -/
+def Pass.clock : Pass w → ℕ
+ | .tag .. => 12
+ | .leaf .. => 14
+ | .fiber _ c _ => 7 * c + 25
+
+/-- Instantiate the standalone tag, leaf or fiber worker with this pass's parameter words and
+package its RAM program with its configuration type. -/
+def Pass.spec : Pass w → Σ C : Type, BurstRAM.Program w C
+ | .tag p _ => ⟨_, ((template TraversalRoles.Native.visit 0).instantiate w p).program⟩
+ | .leaf p _ => ⟨_, ((LeafWorker.program.template (some 0)).instantiate w p).program⟩
+ | .fiber p _ _ => ⟨_, ((SiteWorker.program.template (some 6)).instantiate w p).program⟩
+
+/-- A single reference burst started at site word `i` in memory `m` finishes within the pass
+clock on an empty choice tape and returns `rep`. -/
+def Pass.At (P : Pass w) (i : Word w) (m : Memory w) (rep : Report w) : Prop :=
+ execute P.spec.2 P.clock (P.spec.2.start i) m [] = some rep
+
+/-- Starting at site zero in `m`, the reference program produces the given reports across the
+pass's scheduled bursts, each with its own empty choice tape. -/
+def Pass.Run (P : Pass w) (m : Memory w) (rs : List (Report w)) : Prop :=
+ runSegment P.spec.2 P.clock (some 0) m (List.replicate P.count []) = some rs
+
+open private ops from OAI.Computability.VPVNP.PairTraversalLeafWorker
+open private finishOps from OAI.Computability.VPVNP.PairTraversalSiteWorker
+
+private theorem leaf_return {pub : Fin 2 → Word w} {site : Word w} {m m' : Memory w}
+ {rs out : Regs w 4} {es : List (Event w)}
+ (run : Flow.Exec pub site LeafWorker.program rs m es out m') :
+ out 0 = site + 1 := by
+ have h := (PrimedCounter.Admin.exec_lines_iff_trace _).mp run
+ have e := congrArg (Option.map (fun v : List (Event w) × Regs w 4 × Memory w => v.2.1 0)) h
+ simpa (config := { decide := true }) [ops, trace, Op.effect, BinaryOp.eval, Function.update]
+ using e.symm
+
+private theorem fiber_return {pub : Fin 6 → Word w} {site : Word w} {m m' : Memory w}
+ {rs out : Regs w 7} {es : List (Event w)}
+ (run : Flow.Exec pub site SiteWorker.program rs m es out m') :
+ out 6 = site + 1 := by
+ cases run with
+ | seq _ tail =>
+ cases tail with
+ | seq _ final =>
+ have h := (PrimedCounter.Admin.exec_lines_iff_trace _).mp final
+ have e := congrArg (Option.map (fun v : List (Event w) × Regs w 7 × Memory w => v.2.1 6)) h
+ simpa (config := { decide := true }) [finishOps, trace, Op.effect, BinaryOp.eval,
+ Function.update] using e.symm
+
+/-- A successful standalone reference burst always returns the successor site. -/
+theorem Pass.next {P : Pass w} {site : Word w} {m : Memory w} {rep : Report w}
+ (h : P.At site m rep) : rep.result = some (site + 1) := by
+ cases P with
+ | tag pub _ =>
+ have e := Option.some.inj (h.symm.trans (TraversalRoles.Native.visit_native pub site m))
+ exact congrArg Report.result e
+ | leaf pub _ =>
+ obtain ⟨out, _, run, hr, _, _⟩ := (Flow.template_execute_iff LeafWorker.program (some 0)
+ pub site (fun _ => 0) (fun _ => 0) m _ [] rep).mp h
+ exact hr.trans (congrArg some (leaf_return run))
+ | fiber pub _ _ =>
+ obtain ⟨out, _, run, hr, _, _⟩ := (Flow.template_execute_iff SiteWorker.program (some 6)
+ pub site (fun _ => 0) (fun _ => 0) m _ [] rep).mp h
+ exact hr.trans (congrArg some (fiber_return run))
+
+open private replay_exec from OAI.Computability.VPVNP.PairTraversalRowExecution
+
+/-- The three parameter banks are computed by the same fixed expression setup. -/
+def Pass.Bank (rs : Regs w R) : Pass w → Prop
+ | .tag pub _ => rs ∘ roleAlloc.words (by decide) = pub
+ | .leaf pub _ => rs ∘ leafAlloc.words (by decide) = pub
+ | .fiber pub _ _ => rs ∘ fiberAlloc.bank = pub
+
+/-- Select the embedded role, leaf-header or fiber-row instruction flow that replays the
+standalone worker inside the traversal controller. -/
+def Pass.body : Pass w → Flow R 11
+ | .tag .. => roleAlloc.role
+ | .leaf .. => leafAlloc.leaf
+ | .fiber .. => fiberAlloc.fiber
+
+/-- Lift an actual standalone report, including its writes, into the common
+word-width-independent controller. Every operand and output register outside
+the seven worker temporaries is preserved. -/
+theorem Pass.lift {P : Pass w} {i : Word w} {m : Memory w} {rep : Report w}
+ (h : P.At i m rep) (pub : Fin 11 → Word w) (state : Word w) (rs : Regs w R)
+ (hp : P.Bank rs) (hi : rs (value 0) = i) (zero : ∀ j, rs (scratchRegs j) = 0) :
+ ∃ out, Flow.Exec pub state P.body rs m rep.events out (after m rep.events) ∧
+ choiceBits rep.events = [] ∧ rep.events.length < P.clock ∧
+ ∀ j, j ∉ Set.range scratchRegs → out j = rs j := by
+ cases P with
+ | tag p n =>
+ have e := Option.some.inj (h.symm.trans (TraversalRoles.Native.visit_native p i m))
+ obtain ⟨out, run, _, _, len, bits, frame⟩ := roleAlloc.role_exec pub state i rs m p hp hi
+ cases e
+ exact ⟨out, run, bits, by change _ < 12; rw [len]; decide, frame⟩
+ | leaf p n =>
+ obtain ⟨out, m', run, _, len, bits⟩ := (Flow.template_execute_iff LeafWorker.program (some 0)
+ p i (fun _ => 0) (fun _ => 0) m _ [] rep).mp h
+ have small : rs ∘ leafAlloc.regs (by decide : 4 ≤ 7) = fun _ => 0 := funext fun _ => zero _
+ have no (j) : leafAlloc.words (by decide : 2 ≤ 6) j ∉
+ Set.range (leafAlloc.regs (by decide : 4 ≤ 7)) :=
+ fun ⟨b, eb⟩ => leafAlloc.bankOutside _ ⟨_, eb⟩
+ have arg : leafAlloc.site ∉ Set.range (leafAlloc.regs (by decide : 4 ≤ 7)) :=
+ fun ⟨b, eb⟩ => leafAlloc.siteOutside ⟨_, eb⟩
+ obtain ⟨rs', body, _, frame⟩ := OnlineWorker.liftExec _ _ _ no arg pub run rs small hp hi
+ (state := state)
+ refine ⟨rs', (replay_exec run).symm ▸ body, bits, len, fun j hj => frame j ?_⟩
+ exact fun ⟨b, eb⟩ => hj ⟨_, eb⟩
+ | fiber p cap n =>
+ obtain ⟨out, m', run, _, len, bits⟩ := (Flow.template_execute_iff SiteWorker.program (some 6)
+ p i (fun _ => 0) (fun _ => 0) m _ [] rep).mp h
+ have small : rs ∘ fiberAlloc.scratch = fun _ => 0 := funext zero
+ obtain ⟨rs', body, _, frame⟩ := OnlineWorker.liftExec _ _ _ fiberAlloc.bankOutside
+ fiberAlloc.siteOutside pub run rs small hp hi (state := state)
+ exact ⟨rs', (replay_exec run).symm ▸ body, bits, len, frame⟩
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerCode.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerCode.lean
new file mode 100644
index 0000000000..e6a60f3b87
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerCode.lean
@@ -0,0 +1,237 @@
+import OAI.Computability.VPVNP.PairTraversalControllerFormula
+
+/-!
+# Native dispatcher for traversal table construction
+
+Each reset entry loads the square base, radix exponent and persistent ordinal,
+then computes the fixed operand formulas. Four comparisons dispatch to a role
+write, a leaf header, a fiber translation, a phase reset or final acceptance.
+All three workers return to the common successor-ordinal instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController.Native
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+private abbrev nSetup := (RegisterSetup.lines formulas).length
+private abbrev nRole := roleAlloc.role.length
+private abbrev nLeaf := leafAlloc.leaf.length
+private abbrev nFiber := fiberAlloc.fiber.length
+
+/-- Total program-counter count for the traversal controller's prelude, setup, guard, three
+worker blocks, and four exits. -/
+abbrev P := 3 + (nSetup + (4 + (nRole + (nLeaf + (nFiber + 4)))))
+private abbrev Address := Fin 3 ⊕ Fin nSetup ⊕ Fin 4 ⊕ Fin nRole ⊕ Fin nLeaf ⊕ Fin nFiber ⊕ Fin 4
+
+private def join {X : Type} {a b : ℕ} (e : X ≃ Fin b) : Fin a ⊕ X ≃ Fin (a + b) :=
+ ((Equiv.refl _).sumCongr e).trans finSumFinEquiv
+
+private def book : Address ≃ Fin P := join (join (join (join (join (join (Equiv.refl _))))))
+
+/-- Place the traversal controller's three prelude instructions at their physical addresses. -/
+def preludePC (i : Fin 3) : Fin P := book (.inl i)
+/-- Program counters of the guard that chooses the current traversal worker or an exit. -/
+def guardPC (i : Fin 4) : Fin P := book (.inr (.inr (.inl i)))
+
+/-- Place a register-setup instruction by its ordinal, falling through to the first guard when
+setup is complete. -/
+def setupPC (n : ℕ) : Fin P :=
+ if h : n < nSetup then book (.inr (.inl ⟨n, h⟩)) else guardPC 0
+
+/-- Physical instruction address in the role-tag writer's linked worker block. -/
+def rolePC (i : roleAlloc.role.Label) : Fin P :=
+ book (.inr (.inr (.inr (.inl (roleAlloc.role.labels i)))))
+
+/-- Physical instruction address in the leaf-row writer's linked worker block. -/
+def leafPC (i : leafAlloc.leaf.Label) : Fin P :=
+ book (.inr (.inr (.inr (.inr (.inl (leafAlloc.leaf.labels i))))))
+
+/-- Physical instruction address in the worker that writes a site's selected placement fiber. -/
+def fiberPC (i : fiberAlloc.fiber.Label) : Fin P :=
+ book (.inr (.inr (.inr (.inr (.inr (.inl (fiberAlloc.fiber.labels i)))))))
+
+private def exitPC (i : Fin 4) : Fin P := book (.inr (.inr (.inr (.inr (.inr (.inr i))))))
+
+/-- Exit returning the controller state for the next active site. -/
+def nextPC := exitPC 0
+/-- Exit that resets the site ordinal and advances to the next phase-level. -/
+def resetPC := exitPC 1
+/-- Accepting exit of the completed traversal controller. -/
+def acceptPC := exitPC 2
+/-- Rejection exit reserved in the traversal controller's instruction table. -/
+def rejectPC := exitPC 3
+
+private def preludeCode {w : ℕ} : Fin 3 → Instr w P R 11
+ | 0 => .publicWord (extra 7) 2 (preludePC 1)
+ | 1 => .publicWord (extra 8) 7 (preludePC 2)
+ | 2 => .stateWord (extra 9) (setupPC 0)
+
+private def guardCode {w : ℕ} : Fin 4 → Instr w P R 11
+ | 0 => .jumpLt (value 1) (value 3) (guardPC 1) acceptPC
+ | 1 => .jumpLt (value 0) (value 4) (guardPC 2) resetPC
+ | 2 => .jumpLt (value 1) (value 2) (rolePC roleAlloc.role.entry) (guardPC 3)
+ | 3 => .jumpEq (value 5) (value 6) (leafPC leafAlloc.leaf.entry) (fiberPC fiberAlloc.fiber.entry)
+
+private def exitCode {w : ℕ} : Fin 4 → Instr w P R 11
+ | 0 => .returnState (value 7)
+ | 1 => .returnState (value 8)
+ | 2 => .accept
+ | 3 => .reject
+
+private def blockText (f : Flow R 11) (pc : f.Label → Fin P) (i : Fin f.length) : Instr 2 P R 11 :=
+ (((f.code (f.labels.symm i)).map (fun l => (l.map pc).getD nextPC)).emit rejectPC)
+
+private def text : Address → Instr 2 P R 11
+ | .inl i => preludeCode i
+ | .inr (.inl i) => RegisterSetup.instruction vm inputs
+ (RegisterSetup.lines formulas)[i.val] (setupPC (i.val + 1))
+ | .inr (.inr (.inl i)) => guardCode i
+ | .inr (.inr (.inr (.inl i))) => blockText roleAlloc.role rolePC i
+ | .inr (.inr (.inr (.inr (.inl i)))) => blockText leafAlloc.leaf leafPC i
+ | .inr (.inr (.inr (.inr (.inr (.inl i))))) => blockText fiberAlloc.fiber fiberPC i
+ | .inr (.inr (.inr (.inr (.inr (.inr i))))) => exitCode i
+
+/-- One finite template for all inputs, word widths, layer counts and term choices. -/
+def table : Template P R 11 where
+ literalWidth := 2
+ entry := preludePC 0
+ code i := text (book.symm i)
+
+variable {w : ℕ} (pub : Fin 11 → Word w)
+
+/-- Instantiate the fixed traversal controller template at the supplied word width and eleven
+public operands. -/
+def machine := table.instantiate w pub
+
+private theorem atAddress (a : Address) : (machine pub).code (book a) = (text a).resize w := by
+ simp only [machine, Template.instantiate, table, Equiv.symm_apply_apply]
+
+theorem setup_end : setupPC (RegisterSetup.lines formulas).length = guardPC 0 := by
+ simp only [setupPC, nSetup, lt_self_iff_false, ↓reduceDIte]
+
+theorem linked_setup :
+ RegisterSetup.Linked vm inputs (machine pub) setupPC (RegisterSetup.lines formulas) := by
+ intro i
+ rw [setupPC, dite_eq_left i.isLt, atAddress]
+ exact RegisterSetup.resize_instruction vm inputs _ _
+
+theorem linked_role : Flow.Linked (machine pub) roleAlloc.role rolePC nextPC rejectPC := by
+ constructor
+ intro i
+ simp only [rolePC, atAddress, text, blockText, Equiv.symm_apply_apply]
+
+theorem linked_leaf : Flow.Linked (machine pub) leafAlloc.leaf leafPC nextPC rejectPC := by
+ constructor
+ intro i
+ simp only [leafPC, atAddress, text, blockText, Equiv.symm_apply_apply]
+
+theorem linked_fiber : Flow.Linked (machine pub) fiberAlloc.fiber fiberPC nextPC rejectPC := by
+ constructor
+ intro i
+ simp only [fiberPC, atAddress, text, blockText, Equiv.symm_apply_apply]
+
+theorem code_next : (machine pub).code nextPC = .returnState (value 7) := atAddress pub _
+theorem code_reset : (machine pub).code resetPC = .returnState (value 8) := atAddress pub _
+theorem code_accept : (machine pub).code acceptPC = .accept := atAddress pub _
+theorem code_reject : (machine pub).code rejectPC = .reject := atAddress pub _
+
+private theorem code_pre (i : Fin 3) : (machine pub).code (preludePC i) = preludeCode i := by
+ rw [preludePC, atAddress]
+ fin_cases i <;> rfl
+
+private theorem code_guard (i : Fin 4) : (machine pub).code (guardPC i) = guardCode i := by
+ rw [guardPC, atAddress]
+ fin_cases i <;> rfl
+
+/-- Configuration received by the formula evaluator immediately after reset. -/
+def loaded (s : Word w) : Config w P R :=
+ ⟨setupPC 0, s, Function.update (Function.update (Function.update (fun _ => 0)
+ (extra 7) (pub 2)) (extra 8) (pub 7)) (extra 9) s, fun _ => 0⟩
+
+theorem loaded_inputs (s : Word w) (j : Fin 5) :
+ (loaded pub s).reg (inputs j.castSucc) = recipePub pub j := by
+ fin_cases j <;> simp (config := { decide := true }) [loaded, inputs, extra, recipePub]
+
+theorem loaded_state (s : Word w) : (loaded pub s).reg (inputs (Fin.last 5)) = s := by
+ simp (config := { decide := true }) [loaded, inputs]
+
+/-- The prelude takes exactly three ticks and reaches the first setup instruction
+with its public and persistent inputs in registers. -/
+theorem enter (s : Word w) (m : Memory w) (bits : List Bool) (fuel : ℕ) :
+ let M := machine pub
+ execute M.program (fuel + 3) (M.program.start s) m bits =
+ (execute M.program fuel (loaded pub s) m bits).map
+ (Flow.prependEvents [.tick, .tick, .tick]) := by
+ change execute (machine pub).program (fuel + 3)
+ ⟨preludePC 0, s, fun _ => 0, fun _ => 0⟩ m bits = _
+ simp only [execute, Machine.program, code_pre, preludeCode, Instr.run, Config.put, Option.map_map]
+ rfl
+
+/-- Destination selected by the native tests after the formula evaluator. -/
+inductive Route where
+ | accept | reset | role | leaf | fiber
+ deriving DecidableEq
+
+/-- Choose acceptance, phase reset, or the role, leaf, or fiber worker from the decoded
+phase-level and site bounds. -/
+def route (rs : Regs w R) : Route :=
+ if rs (value 1) < rs (value 3) then
+ if rs (value 0) < rs (value 4) then
+ if rs (value 1) < rs (value 2) then .role
+ else if rs (value 5) = rs (value 6) then .leaf else .fiber
+ else .reset
+ else .accept
+
+/-- Program counter entered after the guard has determined the traversal route. -/
+def Route.pc : Route → Fin P
+ | .accept => acceptPC
+ | .reset => resetPC
+ | .role => rolePC roleAlloc.role.entry
+ | .leaf => leafPC leafAlloc.leaf.entry
+ | .fiber => fiberPC fiberAlloc.fiber.entry
+
+/-- Number of guard ticks before reaching the selected worker or exit, ranging from one at
+acceptance to four at a descriptor worker. -/
+def Route.ticks : Route → ℕ
+ | .accept => 1
+ | .reset => 2
+ | .role => 3
+ | .leaf | .fiber => 4
+
+/-- Every guard contributes one tick and leaves the operand bank and both
+memories available to the selected worker or exit instruction. -/
+theorem dispatch (state : Word w) (rs : Regs w R) (priv : Word w → Word w) (m : Memory w)
+ (bits : List Bool) (fuel : ℕ) :
+ let M := machine pub
+ let dest := route rs
+ execute M.program (fuel + dest.ticks) ⟨guardPC 0, state, rs, priv⟩ m bits =
+ (execute M.program fuel ⟨dest.pc, state, rs, priv⟩ m bits).map
+ (Flow.prependEvents (List.replicate dest.ticks .tick)) := by
+ dsimp only
+ unfold route
+ split <;> rename_i h₀
+ · split <;> rename_i h₁
+ · split <;> rename_i h₂
+ · simp only [Route.ticks, Route.pc, execute, Machine.program, code_guard, guardCode,
+ Instr.run, h₀, h₁, h₂, ↓reduceIte, Option.map_map]
+ rfl
+ · split <;> rename_i h₃ <;>
+ simp only [Route.ticks, Route.pc, execute, Machine.program, code_guard, guardCode,
+ Instr.run, h₀, h₁, h₂, h₃, ↓reduceIte, Option.map_map] <;> rfl
+ · simp only [Route.ticks, Route.pc, execute, Machine.program, code_guard, guardCode,
+ Instr.run, h₀, h₁, ↓reduceIte, Option.map_map]
+ rfl
+ · simp only [Route.ticks, Route.pc, execute, Machine.program, code_guard, guardCode,
+ Instr.run, h₀, ↓reduceIte]
+ rfl
+
+end PairSimulation.TraversalController.Native
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerFormula.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerFormula.lean
new file mode 100644
index 0000000000..ea296aac16
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerFormula.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+import OAI.Computability.VPVNP.PairTraversalOnlineWorker
+
+/-!
+# Runtime operands for the post-calendar traversal controller
+
+One persistent word encodes the phase, physical level and site number. The
+first pass writes every role. The second pass writes every descriptor. Each
+burst reads its operands directly from the terminal and level headers.
+All expression trees are fixed and use the repository's native compiler.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords PhaseRecipe TraversalRows OnlineWorker
+open scoped Fin.CommRing
+
+/-- The virtual five-word recipe ABI names the public square base and its
+radix exponent. The last of the six input registers holds the true state word. -/
+def recipePub {w : ℕ} (pub : Fin 11 → Word w) : Fin 5 → Word w :=
+ ![pub 2, pub 7, pub 2, pub 2, pub 2]
+
+/-- Recover the high terminal header by adding the square workspace size to its base and
+subtracting the 32-word header reservation. -/
+def terminal : Expr :=
+ let radix := Expr.binary .shiftLeft (.lit 1) (.publicWord 1)
+ ((Expr.publicWord 0).add (radix.mul radix)).sub (.lit 32)
+
+/-- Read the specified scalar word from the terminal header computed by the traversal recipe. -/
+def term (field : ℕ) : Expr := .load (terminal.add (.lit field))
+/-- Read a field from level j using the terminal header's first-level pointer and level pitch. -/
+def level (j : Expr) (field : ℕ) : Expr :=
+ .load (((term 16).add (j.mul (term 17))).add (.lit field))
+
+/-- The terminal-header expression for the number of physical traversal levels. -/
+def levels : Expr := term 1
+
+/-- Initial site count used by the controller, with the terminal site count selected when the
+directory contains only the initial level. -/
+def initialSites : Expr :=
+ let initial := level (.lit 0) 21
+ initial.add (((Expr.lit 1).div levels).mul ((term 7).sub initial))
+
+/-- Width of one phase-level block in the persistent state encoding, one larger than the
+initial site count. -/
+def pitch : Expr := initialSites.add (.lit 1)
+/-- Decode the combined traversal phase and level ordinal by dividing the persistent state by
+the phase-level pitch. -/
+def phaseLevel : Expr := Expr.state.div pitch
+/-- Decode the within-level site ordinal as the remainder of the persistent state modulo the
+pitch. -/
+def site : Expr := Expr.state.mod pitch
+/-- Physical level ordinal obtained by reducing the combined phase-level number modulo the
+level count. -/
+def index : Expr := phaseLevel.mod levels
+/-- Word-valued nonzero test on the current level ordinal, implemented by division by itself. -/
+def positiveIndex : Expr := index.div index
+/-- Preceding level ordinal, saturating at zero so the initial level remains a valid header
+address. -/
+def previous : Expr := index.sub positiveIndex
+
+/-- Select the current level's site count from the initial count or the preceding pass's output
+count. -/
+def count : Expr := initialSites.add (positiveIndex.mul ((level previous 22).sub initialSites))
+
+/-- Register order for control comparisons, state returns, and the three workers. -/
+def formulas : Fin 18 → Expr :=
+ ![site, phaseLevel, levels, levels.add levels, count, index, .lit 0, Expr.state.add (.lit 1),
+ (phaseLevel.add (.lit 1)).mul pitch, term 14, level index 14, term 15, level index 27,
+ level (.lit 0) 14, level previous 24, level previous 25, level previous 26, level previous 14]
+
+/-- Registers for the setup compiler followed by seven worker scratch words
+and three readonly public/state inputs. -/
+abbrev R := RegisterSetup.regCount formulas + 10
+
+/-- Embed the expression-evaluation registers in the leading portion of the traversal
+controller register bank. -/
+def vm : Fin (RegisterSetup.regCount formulas) ↪ Fin R := Fin.castAddEmb 10
+/-- Register containing the evaluated result of the given traversal operand formula. -/
+def value (i : Fin 18) : Fin R := vm (RegisterSetup.output formulas i)
+/-- A register beyond the formula evaluator, indexed among the ten extra traversal worker and
+input registers. -/
+def extra (i : Fin 10) : Fin R := i.natAdd (RegisterSetup.regCount formulas)
+/-- Assign the five public recipe operands and persistent state input to the extra controller
+registers, reusing the workspace base where prescribed. -/
+def inputs : Fin 6 → Fin R := ![extra 7, extra 8, extra 7, extra 7, extra 7, extra 9]
+
+theorem inputs_apart (i : Fin 6) (j : Fin (RegisterSetup.regCount formulas)) : inputs i ≠ vm j := by
+ have apart (t : Fin 10) : extra t ≠ vm j := by
+ intro e
+ have h := congrArg Fin.val e
+ change RegisterSetup.regCount formulas + t.val = j.val at h
+ omega
+ fin_cases i <;> apply apart
+
+/-- Embed the seven worker scratch registers in the controller bank after the register
+evaluator. -/
+def scratchRegs : Fin 7 ↪ Fin R := (Fin.castAddEmb 3).trans (Fin.natAddEmb _)
+
+private theorem value_outside (i : Fin 18) : value i ∉ Set.range scratchRegs := by
+ rintro ⟨j, h⟩
+ have he := congrArg Fin.val h
+ change RegisterSetup.regCount formulas + j.val = (RegisterSetup.output formulas i).val at he
+ have := (RegisterSetup.output formulas i).isLt
+ omega
+
+/-- Construct the worker's register allocation from the designated formula outputs for its
+public bank and current site. -/
+def allocation (fields : Fin 6 → Fin 18) : Allocation R where
+ scratch := scratchRegs
+ bank := value ∘ fields
+ site := value 0
+ bankOutside := fun i => value_outside (fields i)
+ siteOutside := value_outside _
+
+/-- Formula-output indices supplying the role writer's offset, row base, pitch, role code, and
+unused zero fields. -/
+def roleFields : Fin 6 → Fin 18 := ![9, 10, 11, 12, 6, 6]
+/-- Formula-output indices supplying the leaf-row writer's base and pitch, with zero values in
+unused fields. -/
+def leafFields : Fin 6 → Fin 18 := ![13, 11, 6, 6, 6, 6]
+/-- Formula-output indices supplying the fiber count and row arrays, row capacity, preceding
+row base, current row base, and pitch. -/
+def fiberFields : Fin 6 → Fin 18 := ![14, 15, 16, 17, 10, 11]
+
+/-- The role-tag worker's register allocation using its selected traversal formula outputs. -/
+abbrev roleAlloc := allocation roleFields
+/-- The leaf-row worker's register allocation using the initial layer base and row pitch. -/
+abbrev leafAlloc := allocation leafFields
+/-- The fiber-row worker's register allocation using the selected placement directory and old
+and new row bases. -/
+abbrev fiberAlloc := allocation fiberFields
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerInputs.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerInputs.lean
new file mode 100644
index 0000000000..5f8fe9c18b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerInputs.lean
@@ -0,0 +1,435 @@
+import OAI.Computability.VPVNP.PairTraversalArena
+
+/-!
+# Reading traversal workers from the resident terminal header
+
+The cursor layer precedes the outputs of the chosen compression passes. Each
+output layer uses its producing pass's preimage directory and the DFS bases
+of that pass's input and output states. Tags refer to the output state's
+producing role, including the final state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalControllerInputs
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords LocalHistory NetworkKernel Compression
+open TraversalRows DirectoryRun TraversalRoles
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The last 32 words of the pair's square workspace are the terminal header. -/
+def terminalHead (pub : Fin 11 → Word w) : Word w :=
+ let radix := BinaryOp.shiftLeft.eval 1 (pub 7)
+ pub 2 + radix * radix - 32
+
+/-- The word address equals the natural square-workspace formula whenever
+the public address width fits the shift and the 32-word header fits the square. -/
+theorem terminalHead_eq_nat (pub : Fin 11 → Word w) (hw : (pub 7).val < w)
+ (h32 : 32 ≤ (pub 2).val + 2 ^ (pub 7).val * 2 ^ (pub 7).val) :
+ terminalHead pub = (((pub 2).val + 2 ^ (pub 7).val * 2 ^ (pub 7).val - 32 : ℕ) : Word w) := by
+ have hone : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by omega))
+ have radix : BinaryOp.shiftLeft.eval 1 (pub 7) = ((2 ^ (pub 7).val : ℕ) : Word w) := by
+ simp only [BinaryOp.eval,hw,ite_true,hone,Nat.shiftLeft_eq,Nat.one_mul,Fin.ofNat_eq_cast]
+ simp only [terminalHead,radix,Nat.cast_sub h32,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat]
+ have hb : ((pub 2).val : Word w) = pub 2 := Fin.ext (Nat.mod_eq_of_lt (pub 2).isLt)
+ rw [hb]
+
+/-- Read a terminal-header field at its machine-word offset in the supplied external memory. -/
+def terminalField (pub : Fin 11 → Word w) (m : Memory w) (field : ℕ) : Word w :=
+ m (terminalHead pub + (field : Word w)).val
+
+/-- Compute the physical head of level j from the first-level word and the level pitch saved in
+the terminal header. -/
+def levelHead (pub : Fin 11 → Word w) (m : Memory w) (j : ℕ) : Word w :=
+ terminalField pub m 16 + (j : Word w) * terminalField pub m 17
+
+/-- Read a selected level-header field using the terminal header's runtime level geometry. -/
+def levelField (pub : Fin 11 → Word w) (m : Memory w) (j field : ℕ) : Word w :=
+ m (levelHead pub m j + (field : Word w)).val
+
+/-- The input site's count comes from its first pass, or from the terminal
+site count when there are no passes. Later counts come from their producer. -/
+def siteCount (pub : Fin 11 → Word w) (m : Memory w) : ℕ → Word w
+ | 0 => if (terminalField pub m 1).val = 1 then terminalField pub m 7 else levelField pub m 0 21
+ | j+1 => levelField pub m j 22
+
+/-- Assemble the four role-tag parameters from the terminal displacement, current row base, row
+pitch, and stored producing role. -/
+def tagParams (pub : Fin 11 → Word w) (m : Memory w) (j : ℕ) : Fin 4 → Word w :=
+ ![terminalField pub m 14, levelField pub m j 14, terminalField pub m 15, levelField pub m j 27]
+
+/-- Read the initial row base and row pitch for writing cursor leaf rows. -/
+def leafParams (pub : Fin 11 → Word w) (m : Memory w) : Fin 2 → Word w :=
+ ![levelField pub m 0 14, terminalField pub m 15]
+
+/-- Fiber worker for pass `i` writes the rows of state `i+1`. -/
+def fiberParams (pub : Fin 11 → Word w) (m : Memory w) (i : ℕ) : Fin 6 → Word w :=
+ ![levelField pub m i 24, levelField pub m i 25, levelField pub m i 26,
+ levelField pub m i 14, levelField pub m (i+1) 14, terminalField pub m 15]
+
+/-- A fiber is the tagged output together with the corresponding raw
+placement directory's six public words. -/
+abbrev Fiber (w : ℕ) := TaggedLayer × (Fin 6 → Word w)
+
+/-- Chronological translation of tagged output levels into native row workers. -/
+def fiberWorkers (cap : ℕ) (previous base : ℕ) : List (Fiber w) → List (Worker w)
+ | [] => []
+ | (l, p) :: ls => .fiber p cap previous base l.layer.count ::
+ fiberWorkers cap base (endPos cap base l.layer) ls
+
+theorem fiberWorkers_length (cap previous base : ℕ) (ls : List (Fiber w)) :
+ (fiberWorkers cap previous base ls).length = ls.length := by
+ induction ls generalizing previous base with
+ | nil => rfl
+ | cons h ls ih => simp [fiberWorkers, ih]
+
+/-- The `i`-th fiber connects states `i` and `i+1`. The last fiber uses
+its output state header by precisely the same formula. -/
+theorem fiberWorkers_at (cap base : ℕ) (old : TaggedLayer) (ls : List (Fiber w))
+ (i : Fin ls.length) :
+ (fiberWorkers cap base (endPos cap base old.layer) ls)[i.val]? = some (.fiber ls[i].2 cap
+ (layerBase cap base (old :: ls.map Prod.fst) i.val)
+ (layerBase cap base (old :: ls.map Prod.fst) (i.val+1)) ls[i].1.layer.count) := by
+ induction ls generalizing old base with
+ | nil => exact Fin.elim0 i
+ | cons l ls ih =>
+ cases i using Fin.cases with
+ | zero => simp [fiberWorkers, layerBase_zero, layerBase_cons]
+ | succ i =>
+ simpa only [Fin.getElem_fin, Fin.val_succ, fiberWorkers, List.getElem?_cons_succ,
+ List.getElem_cons_succ, List.map_cons, layerBase_cons] using ih (endPos cap base old.layer) l.1 i
+
+/-- The full schedule has one leaf worker before the fiber workers. -/
+def rowWorkers (cap base : ℕ) (old : TaggedLayer) (ls : List (Fiber w)) : List (Worker w) :=
+ Worker.leaf cap base old.layer.count :: fiberWorkers cap base (endPos cap base old.layer) ls
+
+/-- Physical header cells for one finished compressor branch. Addresses here
+are ordinary natural addresses, independent of the controller's word arithmetic. -/
+structure Resident (pub : Fin 11 → Word w) (m : Memory w) (H first pitch offset cap base : ℕ)
+ (old : TaggedLayer) (ls : List (Fiber w)) : Prop where
+ header : terminalHead pub = (H : Word w)
+ headerFits : H + 32 ≤ 2 ^ w
+ levelFits : ∀ j ≤ ls.length, first + j * pitch + 28 ≤ 2 ^ w
+ firstHead : m (H+16) = (first : Word w)
+ levelPitch : m (H+17) = (pitch : Word w)
+ levels : (m (H+1)).val = ls.length + 1
+ roleOffset : m (H+14) = (offset : Word w)
+ rowStride : m (H+15) = ((cap + 2 : ℕ) : Word w)
+ currentBase : ∀ j ≤ ls.length, m (first + j*pitch + 14) =
+ (layerBase cap base (old :: ls.map Prod.fst) j : Word w)
+ role : ∀ j : Fin (old :: ls.map Prod.fst).length,
+ m (first + j.val*pitch + 27) = ((old :: ls.map Prod.fst)[j].role.code : Word w)
+ initial : ls ≠ [] → (m (first+21)).val = old.layer.count
+ terminalSites : ls = [] → (m (H+7)).val = old.layer.count
+ produced : ∀ i : Fin ls.length, (m (first + i.val*pitch + 22)).val = ls[i].1.layer.count
+ childCounts : ∀ i : Fin ls.length, m (first + i.val*pitch + 24) = ls[i].2 3
+ childLists : ∀ i : Fin ls.length, m (first + i.val*pitch + 25) = ls[i].2 5
+ childCapacity : ∀ i : Fin ls.length, m (first + i.val*pitch + 26) = ls[i].2 4
+
+variable {pub : Fin 11 → Word w} {m : Memory w} {H first pitch offset cap base : ℕ}
+variable {old : TaggedLayer} {ls : List (Fiber w)}
+variable (d : Resident pub m H first pitch offset cap base old ls)
+
+include d in
+theorem terminal_read (field : ℕ) (h : field < 32) :
+ terminalField pub m field = m (H+field) := by
+ simp only [terminalField,d.header,← Nat.cast_add,Fin.val_natCast]
+ rw [Nat.mod_eq_of_lt ((Nat.add_lt_add_left h H).trans_le d.headerFits)]
+
+include d in
+theorem level_read (j field : ℕ) (hj : j ≤ ls.length) (h : field < 28) :
+ levelField pub m j field = m (first+j*pitch+field) := by
+ simp only [levelField,levelHead,terminal_read d 16 (by decide),terminal_read d 17 (by decide),
+ d.firstHead,d.levelPitch,← Nat.cast_mul,← Nat.cast_add,Fin.val_natCast]
+ rw [Nat.mod_eq_of_lt ((Nat.add_lt_add_left h _).trans_le (d.levelFits j hj))]
+
+include d in
+theorem count_zero : (siteCount pub m 0).val = old.layer.count := by
+ simp only [siteCount,terminal_read d 1 (by decide),d.levels,terminal_read d 7 (by decide),
+ level_read d 0 21 (Nat.zero_le _) (by decide),Nat.zero_mul,Nat.add_zero]
+ by_cases h : ls = []
+ · simp [h,d.terminalSites h]
+ · have hl : ls.length ≠ 0 := fun e => h (List.length_eq_zero_iff.mp e)
+ simp [hl,d.initial h]
+
+include d in
+theorem count_succ (i : Fin ls.length) : (siteCount pub m (i.val+1)).val = ls[i].1.layer.count :=
+ (congrArg Fin.val (level_read d i.val 22 i.isLt.le (by decide))).trans (d.produced i)
+
+include d in
+theorem fiber_params (i : Fin ls.length) :
+ fiberParams pub m i.val = workerData ls[i].2 cap
+ (layerBase cap base (old :: ls.map Prod.fst) i.val)
+ (layerBase cap base (old :: ls.map Prod.fst) (i.val+1)) := by
+ simp only [fiberParams,workerData,level_read d i.val 24 i.isLt.le (by decide), d.childCounts i,
+ level_read d i.val 25 i.isLt.le (by decide),d.childLists i,
+ level_read d i.val 26 i.isLt.le (by decide),d.childCapacity i,
+ level_read d i.val 14 i.isLt.le (by decide),d.currentBase _ i.isLt.le,
+ level_read d (i.val+1) 14 i.isLt (by decide),d.currentBase _ i.isLt,
+ terminal_read d 15 (by decide),d.rowStride]
+
+include d in
+theorem leaf_params : leafParams pub m = LeafWorker.directory w cap base := by
+ simp only [leafParams,LeafWorker.directory,level_read d 0 14 (Nat.zero_le _) (by decide),
+ d.currentBase 0 (Nat.zero_le _),layerBase_zero,terminal_read d 15 (by decide),d.rowStride]
+
+include d in
+theorem tag_params (j : Fin (old :: ls.map Prod.fst).length) :
+ tagParams pub m j.val = Native.params offset cap (layerBase cap base (old :: ls.map Prod.fst) j.val)
+ ((old :: ls.map Prod.fst)[j].role.code : Word w) := by
+ have hj : j.val ≤ ls.length := by simpa only [List.length_cons,List.length_map,Nat.lt_succ_iff] using j.isLt
+ simp only [tagParams,Native.params,terminal_read d 14 (by decide),d.roleOffset,
+ level_read d j.val 14 hj (by decide),d.currentBase _ hj,terminal_read d 15 (by decide),
+ d.rowStride,level_read d j.val 27 hj (by decide),d.role j]
+
+/-- Lookup of a row worker supplies its exact count and public operand bank. -/
+def RowAt (pub : Fin 11 → Word w) (m : Memory w) (j : ℕ) : Worker w → Prop
+ | .leaf cap base count => j = 0 ∧ (siteCount pub m j).val = count ∧
+ leafParams pub m = LeafWorker.directory w cap base
+ | .fiber p cap previous base count => ∃ i, j = i+1 ∧ (siteCount pub m j).val = count ∧
+ fiberParams pub m i = workerData p cap previous base
+
+/-- The controller has one pair of row/tag stages per state level. Every
+admitted ordinal selects the exact chronological worker and role. -/
+structure Schedule (pub : Fin 11 → Word w) (m : Memory w) (offset cap base : ℕ)
+ (tags : List TaggedLayer) (jobs : List (Worker w)) : Prop where
+ total : (terminalField pub m 1).val = tags.length
+ jobs_length : jobs.length = tags.length
+ lookup : ∀ j : Fin tags.length,
+ (siteCount pub m j.val).val = tags[j].layer.count ∧
+ tagParams pub m j.val = Native.params offset cap (layerBase cap base tags j.val)
+ (tags[j].role.code : Word w) ∧ RowAt pub m j.val (jobs[j.val]'(jobs_length.symm ▸ j.isLt))
+
+include d in
+theorem resident_schedule : Schedule pub m offset cap base (old :: ls.map Prod.fst) (rowWorkers cap base old ls) := by
+ have len : (rowWorkers cap base old ls).length = (old :: ls.map Prod.fst).length := by
+ simp [rowWorkers,fiberWorkers_length]
+ refine ⟨by simpa only [terminal_read d 1 (by decide), List.length_cons,List.length_map] using d.levels,
+ len,fun j => ⟨?_,tag_params d j,?_⟩⟩
+ · cases j using Fin.cases with
+ | zero => exact count_zero d
+ | succ i =>
+ let i' : Fin ls.length := ⟨i.val,by simpa using i.isLt⟩
+ simpa only [Fin.getElem_fin,Fin.val_succ,List.getElem_cons_succ,List.getElem_map] using count_succ d i'
+ · cases j using Fin.cases with
+ | zero => exact ⟨rfl,count_zero d,leaf_params d⟩
+ | succ i =>
+ let i' : Fin ls.length := ⟨i.val,by simpa using i.isLt⟩
+ have e := fiberWorkers_at cap base old ls i'
+ rw [List.getElem?_eq_getElem (by rw [fiberWorkers_length]; exact i'.isLt),Option.some.injEq] at e
+ have hi : i.val < (fiberWorkers cap base (endPos cap base old.layer) ls).length := by
+ rw [fiberWorkers_length]
+ exact i'.isLt
+ change RowAt pub m (i.val+1) ((fiberWorkers cap base (endPos cap base old.layer) ls)[i.val]'hi)
+ rw [e]
+ exact ⟨i.val,rfl,count_succ d i',fiber_params d i'⟩
+
+variable {A k : Type*} [CommRing A] [Field k] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f}
+
+open private castOrders from OAI.Computability.VPVNP.PairTraversalSelectedOrder
+open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels
+open private castDirectories collectDirectories from OAI.Computability.VPVNP.PairTraversalLevelDirectories
+
+omit [CommRing A] in
+private theorem workers_cast {N M Y : Network} (e : N = M) (c : TermChain A M Y)
+ (ords : ChainOrders c) (old : Order M.Site) {m : Memory w} {limit : ℕ}
+ (dirs : Directories m limit c ords old) (cap previous base : ℕ) :
+ workers (e.symm ▸ c : TermChain A N Y) (castOrders e c ords) (e.symm ▸ old)
+ (castDirectories e c ords old m limit dirs) cap previous base =
+ workers c ords old dirs cap previous base := by cases e; rfl
+
+private noncomputable def taggedLevel (v : SelectedLevel B f hf) : TaggedLayer :=
+ ⟨levelLayer B f hf v, tagLevel B f hf v⟩
+
+/-- The typed directory list keeps the address of every occurrence of a
+selected level, even when two levels have equal mathematical data. -/
+noncomputable def levelFibers (vs : List (SelectedLevel B f hf)) {m : Memory w} {limit : ℕ}
+ (ds : (i : Fin vs.length) → LevelDirectory vs[i] m limit) : List (Fiber w) :=
+ List.ofFn fun i => (taggedLevel vs[i], (ds i).pub)
+
+private theorem levelFibers_cons (v : SelectedLevel B f hf) (vs : List (SelectedLevel B f hf))
+ {m : Memory w} {limit : ℕ} (ds : (i : Fin (v :: vs).length) → LevelDirectory (v :: vs)[i] m limit) :
+ levelFibers (v :: vs) ds = (taggedLevel v, (ds 0).pub) ::
+ levelFibers vs (fun i => ds i.succ) :=
+ List.ofFn_succ
+
+set_option maxHeartbeats 800000 in
+private theorem collect_workers {a g b n : ℕ} {X : State a g}
+ (E : StateExecution A b n X) (W : E.MapWitnesses f) (r : ExecutionReaders E W)
+ (o : PassOrigins B f hf E) (data : E.Records) (z : E.Choices) {m : Memory w} {limit : ℕ}
+ (ds : let vs := collectLevels B f hf E W r o z
+ (i : Fin vs.length) → LevelDirectory vs[i] m limit) (cap previous base : ℕ) :
+ workers (E.termChain data z) (branchOrders E data z) (siteOrder X)
+ (collectDirectories E W r o data z m limit ds) cap previous base =
+ fiberWorkers cap previous base (levelFibers (collectLevels B f hf E W r o z) ds) := by
+ induction E generalizing previous base with
+ | done => rfl
+ | @more a₀ g₀ a₁ g₁ X₀ p tail ih =>
+ let v : SelectedLevel B f hf := ⟨a₀,g₀,a₁,g₁,X₀,p,o.1,z.1,r.1.select.encode z.1⟩
+ let E' := tail z.1
+ let vs := collectLevels B f hf E' (W.2 z.1) (r.2 z.1) (o.2 z.1) z.2
+ let rest (i : Fin vs.length) : LevelDirectory vs[i] m limit := ds i.succ
+ let data' := data.2 z.1
+ let c := E'.termChain data' z.2
+ let ords := branchOrders E' data' z.2
+ let old := siteOrder (p.next z.1)
+ let d := collectDirectories E' (W.2 z.1) (r.2 z.1) (o.2 z.1) data' z.2 m limit rest
+ change _ = fiberWorkers cap previous base (levelFibers (v :: vs) ds)
+ rw [levelFibers_cons v vs ds]
+ apply congrArg (List.cons (Worker.fiber (ds ⟨0,Nat.zero_lt_succ _⟩).pub cap previous base
+ (taggedLevel v).layer.count))
+ exact (workers_cast (p.output_eq z.1) c ords old d _ _ _).trans
+ (ih z.1 (W.2 z.1) (r.2 z.1) (o.2 z.1) data' z.2 rest _ _)
+
+theorem levelFibers_tags (vs : List (SelectedLevel B f hf)) {raw : Memory w} {limit : ℕ}
+ (ds : (i : Fin vs.length) → LevelDirectory vs[i] raw limit) :
+ (levelFibers vs ds).map Prod.fst = vs.map (fun v => ⟨levelLayer B f hf v,tagLevel B f hf v⟩) := by
+ simp only [levelFibers,List.map_ofFn,Function.comp_def,taggedLevel]
+ simpa only [Fin.getElem_fin] using List.ofFn_getElem_eq_map vs
+ (fun v => (⟨levelLayer B f hf v,tagLevel B f hf v⟩ : TaggedLayer))
+
+private theorem collect_first_sites {a g b n : ℕ} {X : State a g}
+ (E : StateExecution A b n X) (W : E.MapWitnesses f) (r : ExecutionReaders E W)
+ (o : PassOrigins B f hf E) (z : E.Choices) :
+ let vs := collectLevels B f hf E W r o z
+ ∀ i : Fin vs.length, i.val = 0 → (siteOrder vs[i].input).length = (siteOrder X).length := by
+ cases E with
+ | done => exact fun i => Fin.elim0 i
+ | more p tail =>
+ intro vs i hi
+ obtain ⟨j,hj⟩ := i
+ change j = 0 at hi
+ subst j
+ rfl
+
+variable (B f hf) {n : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices) (base : ℕ) (raw : Memory w)
+variable (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] raw base)
+
+/-- Exactly the worker list executed by the selected traversal-arena build. -/
+noncomputable def selectedJobs : List (Worker w) :=
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ords := branchOrders E data z
+ let old := siteOrder X
+ let dirs := selectedDirectories B f hf T hT X z raw base ds
+ .leaf B.recordLimit base old.length ::
+ workers c ords old dirs B.recordLimit base (address B.recordLimit base old.length)
+
+theorem selectedJobs_eq : selectedJobs B f hf T hT X z base raw ds =
+ rowWorkers B.recordLimit base ⟨leafLayer (siteOrder X),.cursor⟩
+ (levelFibers (executeLevels B f hf T hT X z) ds) := by
+ apply congrArg (List.cons _)
+ apply collect_workers
+
+/-- Physical fields for the initial state and each selected pass provide all
+the operands of the native workers, with the precise chronological schedule. -/
+theorem selected_schedule {H first pitch offset : ℕ} {pub : Fin 11 → Word w} {m : Memory w}
+ (fields : Resident pub m H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers (executeLevels B f hf T hT X z) ds)) :
+ Schedule pub m offset B.recordLimit base (TraversalRoles.selected B f hf T hT X z)
+ (selectedJobs B f hf T hT X z base raw ds) := by
+ have hs := resident_schedule fields
+ rw [levelFibers_tags] at hs
+ rw [selectedJobs_eq]
+ exact hs
+
+/-- Read the public placement words from the real directory for each
+occurrence of a selected pass. The count cells are identified with the
+mathematical site counts by that directory's old/new count witnesses. -/
+theorem selected_resident_of_directory_fields {H first pitch offset : ℕ} {pub : Fin 11 → Word w}
+ {m : Memory w}
+ (head : terminalHead pub = (H : Word w)) (hfHead : H + 32 ≤ 2^w)
+ (firstCell : m (H+16) = (first : Word w)) (pitchCell : m (H+17) = (pitch : Word w))
+ (offsetCell : m (H+14) = (offset : Word w)) (strideCell : m (H+15) = ((B.recordLimit+2 : ℕ) : Word w)) :
+ let vs := executeLevels B f hf T hT X z
+ let tags := TraversalRoles.selected B f hf T hT X z
+ (m (H+1)).val = vs.length+1 →
+ (∀ j ≤ vs.length, first+j*pitch+28 ≤ 2^w) →
+ (∀ j ≤ vs.length, m (first+j*pitch+14) = (layerBase B.recordLimit base tags j : Word w)) →
+ (∀ j : Fin tags.length, m (first+j.val*pitch+27) = (tags[j].role.code : Word w)) →
+ (∀ i : Fin vs.length, i.val = 0 → m (first+21) = (ds i).pub 0) →
+ (vs = [] → (m (H+7)).val = X.positions) →
+ (∀ i : Fin vs.length, m (first+i.val*pitch+22) = (ds i).pub 2 ∧
+ m (first+i.val*pitch+24) = (ds i).pub 3 ∧
+ m (first+i.val*pitch+25) = (ds i).pub 5 ∧ m (first+i.val*pitch+26) = (ds i).pub 4) →
+ Resident pub m H first pitch offset B.recordLimit base ⟨leafLayer (siteOrder X),.cursor⟩
+ (levelFibers vs ds) := by
+ intro vs tags levels fits cur role oldCount terminalSites directory
+ let fibers := levelFibers vs ds
+ let leaf : TaggedLayer := ⟨leafLayer (siteOrder X),.cursor⟩
+ have len : fibers.length = vs.length := List.length_ofFn
+ have tagEq : leaf :: fibers.map Prod.fst = tags := by
+ rw [show fibers = levelFibers vs ds from rfl,levelFibers_tags]
+ rfl
+ have countX : (siteOrder X).length = X.positions := by
+ change (siteOrder X).length = Fintype.card X.network.Site
+ simpa only [Fintype.card_fin] using Fintype.card_congr (siteOrder X).entries
+ have cell (i : Fin fibers.length) :
+ fibers[i] = (taggedLevel vs[i.cast len],(ds (i.cast len)).pub) := by
+ exact List.get_ofFn (fun j : Fin vs.length => (taggedLevel vs[j], (ds j).pub)) i
+ change Resident pub m H first pitch offset B.recordLimit base leaf fibers
+ refine ⟨head,hfHead,fun j hj => fits j (len ▸ hj),firstCell,pitchCell,levels.trans (congrArg (·+1) len.symm),
+ offsetCell,strideCell,fun j hj => tagEq ▸ cur j (len ▸ hj),?_,?_,?_,?_,?_,?_,?_⟩
+ · let P (xs : List TaggedLayer) := ∀ j : Fin xs.length,
+ m (first+j.val*pitch+27) = (xs[j].role.code : Word w)
+ exact (congrArg P tagEq).mpr role
+ · intro nonempty
+ have pos : 0 < fibers.length := List.length_pos_iff.mpr nonempty
+ let i : Fin vs.length := ⟨0,len ▸ pos⟩
+ have hi : (siteOrder vs[i].input).length = (siteOrder X).length :=
+ collect_first_sites (B := B) (f := f) (hf := hf) (B.execute f hf T hT X)
+ _ _ _ z i rfl
+ exact (congrArg Fin.val (oldCount i rfl)).trans ((ds i).oldCount.trans hi)
+ · intro h
+ have vsnil : vs = [] := List.length_eq_zero_iff.mp (len.symm.trans (by rw [h]; rfl))
+ exact (terminalSites vsnil).trans countX.symm
+ · intro i
+ rw [cell i]
+ exact (congrArg Fin.val (directory (i.cast len)).1).trans (ds (i.cast len)).newCount
+ · intro i
+ rw [cell i]
+ exact (directory (i.cast len)).2.1
+ · intro i
+ rw [cell i]
+ exact (directory (i.cast len)).2.2.1
+ · intro i
+ rw [cell i]
+ exact (directory (i.cast len)).2.2.2
+
+/-- The physical directory fields select exactly the workers of the reference
+arena construction, including the final output layer. -/
+theorem selected_schedule_of_directory_fields {H first pitch offset : ℕ} {pub : Fin 11 → Word w}
+ {m : Memory w}
+ (head : terminalHead pub = (H : Word w)) (hfHead : H + 32 ≤ 2^w)
+ (firstCell : m (H+16) = (first : Word w)) (pitchCell : m (H+17) = (pitch : Word w))
+ (offsetCell : m (H+14) = (offset : Word w)) (strideCell : m (H+15) = ((B.recordLimit+2 : ℕ) : Word w)) :
+ let vs := executeLevels B f hf T hT X z
+ let tags := TraversalRoles.selected B f hf T hT X z
+ (m (H+1)).val = vs.length+1 →
+ (∀ j ≤ vs.length, first+j*pitch+28 ≤ 2^w) →
+ (∀ j ≤ vs.length, m (first+j*pitch+14) = (layerBase B.recordLimit base tags j : Word w)) →
+ (∀ j : Fin tags.length, m (first+j.val*pitch+27) = (tags[j].role.code : Word w)) →
+ (∀ i : Fin vs.length, i.val = 0 → m (first+21) = (ds i).pub 0) →
+ (vs = [] → (m (H+7)).val = X.positions) →
+ (∀ i : Fin vs.length, m (first+i.val*pitch+22) = (ds i).pub 2 ∧
+ m (first+i.val*pitch+24) = (ds i).pub 3 ∧
+ m (first+i.val*pitch+25) = (ds i).pub 5 ∧ m (first+i.val*pitch+26) = (ds i).pub 4) →
+ Schedule pub m offset B.recordLimit base tags (selectedJobs B f hf T hT X z base raw ds) := by
+ intro vs tags levels fits cur role oldCount terminalSites directory
+ exact selected_schedule B f hf T hT X z base raw ds
+ (selected_resident_of_directory_fields B f hf T hT X z base raw ds head hfHead firstCell pitchCell
+ offsetCell strideCell levels fits cur role oldCount terminalSites directory)
+
+end PairSimulation.TraversalControllerInputs
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerLocation.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerLocation.lean
new file mode 100644
index 0000000000..e23bb0cf26
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerLocation.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PairTraversalControllerStep
+import OAI.Computability.VPVNP.PairTraversalControllerReference
+
+/-!
+# Every reference job occupies the online dispatcher's selected layer
+
+The tag and row lists have one entry for each physical state level. Their
+concatenation is exactly the phase-level schedule decoded from the persistent
+word, including both passes over the last state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalControllerInputs
+
+open BurstRAM TraversalController TraversalRoles TraversalRows DirectoryRun
+open scoped Fin.CommRing
+
+variable {w : ℕ} {pub : Fin 11 → Word w} {m : Memory w} {offset cap base : ℕ}
+variable {tags : List TaggedLayer} {rows : List (Worker w)}
+
+theorem Schedule.located (h : Schedule pub m offset cap base tags rows)
+ (p : Fin (tagJobs w offset cap base tags ++ rows.map rowJob).length) :
+ let jobs := tagJobs w offset cap base tags ++ rows.map rowJob
+ (jobs[p]).Located pub m tags.length p.val := by
+ intro jobs
+ have length : jobs.length = 2 * tags.length := by simp [jobs, h.jobs_length]; omega
+ have bound : p.val < 2 * tags.length := p.isLt.trans_eq length
+ by_cases first : p.val < tags.length
+ · let j : Fin tags.length := ⟨p.val, first⟩
+ obtain ⟨count, fields, _⟩ := h.lookup j
+ have entry := tagJobs_at w offset cap base tags j
+ have htag : p.val < (tagJobs w offset cap base tags).length := by simpa using first
+ have hp : jobs[p] = .tag (TraversalRoles.Native.params offset cap
+ (layerBase cap base tags j.val) (tags[j].role.code : Word w)) tags[j].layer.count := by
+ change (tagJobs w offset cap base tags ++ rows.map rowJob)[p.val] = _
+ rw [List.getElem_append_left htag]
+ exact Option.some.inj ((List.getElem?_eq_getElem htag).symm.trans entry)
+ rw [hp]
+ change p.val < tags.length ∧ tagParams pub m (p.val % tags.length) = _ ∧
+ (siteCount pub m (p.val % tags.length)).val = _
+ rw [Nat.mod_eq_of_lt first]
+ exact ⟨first, fields, count⟩
+ · have lo : tags.length ≤ p.val := Nat.le_of_not_lt first
+ let j : Fin tags.length := ⟨p.val - tags.length, by omega⟩
+ have modEq : p.val % tags.length = j.val := by
+ have add : p.val = tags.length + j.val := by dsimp [j]; omega
+ rw [add, Nat.add_mod_left, Nat.mod_eq_of_lt j.isLt]
+ have hj : j.val < rows.length := h.jobs_length.symm ▸ j.isLt
+ obtain ⟨_, _, row⟩ := h.lookup j
+ have hp : jobs[p] = rowJob (rows[j.val]'hj) := by
+ change (tagJobs w offset cap base tags ++ rows.map rowJob)[p.val] = _
+ rw [List.getElem_append_right (by simpa using lo), List.getElem_map]
+ simp only [tagJobs_length, j]
+ rw [hp]
+ generalize eqn : rows[j.val] = worker at row ⊢
+ cases worker with
+ | leaf capacity layer n =>
+ obtain ⟨zero, count, params⟩ := row
+ exact ⟨lo, modEq.trans zero, params, modEq ▸ count⟩
+ | fiber params capacity previous layer n =>
+ obtain ⟨i, succ, count, vals⟩ := row
+ have positive : p.val % tags.length ≠ 0 := by omega
+ have pred : p.val % tags.length - 1 = i := by omega
+ exact ⟨lo, positive, pred ▸ vals, modEq ▸ count⟩
+
+/-- Both passes use precisely the actual count of the represented state level. -/
+theorem Schedule.pass_count (h : Schedule pub m offset cap base tags rows)
+ (p : Fin (tagJobs w offset cap base tags ++ rows.map rowJob).length) :
+ let jobs := tagJobs w offset cap base tags ++ rows.map rowJob
+ (jobs[p]).count = (siteCount pub m (p.val % tags.length)).val := by
+ intro jobs
+ let job := jobs[p]
+ have loc : job.Located pub m tags.length p.val := h.located p
+ change job.count = _
+ cases eqn : job with
+ | tag fields n => rw [eqn] at loc; exact loc.2.2.symm
+ | leaf fields n => rw [eqn] at loc; exact loc.2.2.2.symm
+ | fiber fields c n => rw [eqn] at loc; exact loc.2.2.2.symm
+
+end PairSimulation.TraversalControllerInputs
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerMemory.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerMemory.lean
new file mode 100644
index 0000000000..707d81174a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerMemory.lean
@@ -0,0 +1,445 @@
+import OAI.Computability.VPVNP.PairTraversalArena
+import OAI.Computability.VPVNP.PairTraversalControllerFormula
+
+/-!
+# Memory and call accounting for the two traversal-directory passes
+
+The controller processes all role layers, then all descriptor layers. Its
+administrative reads and its writes to terminal header cells at or above
+`H` preserve the worker writes below `H`. This region contains the raw
+placement directories, the descriptor rows, the final bits, and the tags.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRoles.ControllerMemory
+
+open BurstRAM TraversalRows LocalHistory Compression CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Equality on the protected prefix of external memory. -/
+abbrev AgreeBelow (H : ℕ) (m n : Memory w) := ∀ x < H, m x = n x
+
+theorem write_above {H : ℕ} (m : Memory w) (a v : Word w) (ha : H ≤ a.val) :
+ AgreeBelow H (writeMemory m a v) m := fun _ hx => ite_eq_right (hx.trans_le ha).ne
+
+/-- A terminal header word, including the outer dispatcher's ordinal cell
+at displacement 31, preserves the entire lower memory interval. -/
+theorem write_header (H d : ℕ) (m : Memory w) (v : Word w) (fit : H + d < 2 ^ w) :
+ AgreeBelow H (writeMemory m ((H + d : ℕ) : Word w) v) m :=
+ write_above m _ _ ((Nat.le_add_right H d).trans_eq (Nat.mod_eq_of_lt fit).symm)
+
+private def isProtectedWrite (H : ℕ) : Event w → Bool
+ | .write a _ => decide (a.val < H)
+ | _ => false
+
+/-- The ordered external writes visible below the control header. -/
+def writesBelow (H : ℕ) (es : List (Event w)) : List (Event w) := es.filter (isProtectedWrite H)
+
+@[simp] theorem writesBelow_append (H : ℕ) (es fs : List (Event w)) :
+ writesBelow H (es ++ fs) = writesBelow H es ++ writesBelow H fs := List.filter_append _ _
+
+theorem writesBelow_header (H d : ℕ) (v : Word w) (fit : H + d < 2 ^ w) :
+ writesBelow H [.write ((H+d : ℕ) : Word w) v] = [] := by
+ have ha : ¬ ((H + d : ℕ) : Word w).val < H := by
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt fit]
+ omega
+ simp only [writesBelow, List.filter_cons, isProtectedWrite, decide_eq_false ha,
+ Bool.false_eq_true, ↓reduceIte, List.filter_nil]
+
+@[simp] theorem writesBelow_header_add (H d : ℕ) (v : Word w) (fit : H + d < 2 ^ w) :
+ writesBelow H [.write ((H : Word w) + (d : Word w)) v] = [] := by
+ simpa only [Nat.cast_add] using writesBelow_header H d v fit
+
+@[simp] theorem writesBelow_tick (H : ℕ) (es : List (Event w)) :
+ writesBelow H (.tick :: es) = writesBelow H es := rfl
+
+@[simp] theorem writesBelow_read (H : ℕ) (a v : Word w) (es : List (Event w)) :
+ writesBelow H (.read a v :: es) = writesBelow H es := rfl
+
+@[simp] theorem writesBelow_choice (H : ℕ) (b : Bool) (es : List (Event w)) :
+ writesBelow H (.choice b :: es) = writesBelow H es := rfl
+
+@[simp] theorem writesBelow_high (H : ℕ) (a v : Word w) (es : List (Event w)) (hi : H ≤ a.val) :
+ writesBelow H (.write a v :: es) = writesBelow H es := by
+ simp only [writesBelow, List.filter_cons, isProtectedWrite, decide_eq_false hi.not_gt,
+ Bool.false_eq_true, ↓reduceIte]
+
+private theorem update_at {m n : Memory w} {x : ℕ} (hx : m x = n x) (e : Event w) :
+ update m e x = update n e x := by
+ cases e <;> simp only [update, writeMemory, hx]
+
+theorem after_at {m n : Memory w} {x : ℕ} (hx : m x = n x) (es : List (Event w)) :
+ after m es x = after n es x := by
+ induction es generalizing m n with
+ | nil => exact hx
+ | cons e es ih => exact ih (update_at hx e)
+
+private theorem replay_filtered (H : ℕ) (m : Memory w) (es : List (Event w)) :
+ AgreeBelow H (after m es) (after m (writesBelow H es)) := by
+ induction es generalizing m with
+ | nil => exact fun _ _ => rfl
+ | cons e es ih =>
+ intro x hx
+ apply (ih (update m e) x hx).trans
+ cases e with
+ | write a v =>
+ by_cases ha : a.val < H
+ · simp [writesBelow, isProtectedWrite, ha, after, update]
+ · simp only [writesBelow, List.filter_cons, isProtectedWrite, decide_eq_false ha,
+ Bool.false_eq_true, ↓reduceIte]
+ exact after_at (write_above m a v (Nat.le_of_not_gt ha) x hx) _
+ | tick | choice | read => rfl
+
+/-- Two executions with the same visible writes agree below the controller's
+header even when they insert different read, control, or high-address events. -/
+theorem replay_below {H : ℕ} {m n : Memory w} (h : AgreeBelow H m n)
+ {es fs : List (Event w)} (hw : writesBelow H es = writesBelow H fs) :
+ AgreeBelow H (after m es) (after n fs) := by
+ intro x hx
+ refine (replay_filtered H m es x hx).trans ?_
+ rw [hw]
+ exact (after_at (h x hx) _).trans (replay_filtered H n fs x hx).symm
+
+/-- The model of a single role write only consults the previous value of
+the same cell. This holds for padding and for arbitrary prior memory. -/
+theorem tag_at {m n : Memory w} {x : ℕ} (hx : m x = n x) (offset cap base count : ℕ)
+ (tag : Word w) : Native.image offset cap base count tag m x =
+ Native.image offset cap base count tag n x := by
+ simp only [Native.image, hx]
+
+/-- Descriptor writes have the same pointwise property. Child addresses
+come from the selected placement, and padding comes from this cell of memory. -/
+theorem row_at {m n : Memory w} {x : ℕ} (hx : m x = n x) (cap previous base : ℕ) (L : Layer) :
+ writeLayer cap previous base L m x = writeLayer cap previous base L n x := by
+ simp only [writeLayer, hx]
+
+theorem tags_at {m n : Memory w} {x : ℕ} (hx : m x = n x) (offset cap base : ℕ)
+ (ls : List TaggedLayer) :
+ writeTags offset cap base ls m x = writeTags offset cap base ls n x := by
+ induction ls generalizing m n base with
+ | nil => exact hx
+ | cons L ls ih => exact ih (tag_at hx _ _ _ _ _) _
+
+theorem rows_at {m n : Memory w} {x : ℕ} (hx : m x = n x) (cap previous base : ℕ)
+ (ls : List Layer) : build cap previous base ls m x = build cap previous base ls n x := by
+ induction ls generalizing m n previous base with
+ | nil => exact hx
+ | cons L ls ih => exact ih (row_at hx _ _ _ _) _ _
+
+/-- A high header write commutes, as a full memory equality, with the two
+passes below it. The row and tag regions may have unused cells. -/
+theorem header_commute (offset cap base : ℕ) (ls : List TaggedLayer) (m : Memory w)
+ (a v : Word w) (ha : offset + base + tagWords cap ls ≤ a.val) :
+ build cap base base (ls.map TaggedLayer.layer)
+ (writeTags offset cap base ls (writeMemory m a v)) =
+ writeMemory (build cap base base (ls.map TaggedLayer.layer) (writeTags offset cap base ls m))
+ a v := by
+ funext x
+ by_cases he : x = a.val
+ · subst x
+ rw [build_outside _ _ _ _ _ _ (Or.inr (show base + tagWords cap ls ≤ a.val by omega)),
+ write_tags_outside _ _ _ _ _ _ (Or.inr ha)]
+ simp [writeMemory]
+ · rw [writeMemory, ite_eq_right he]
+ apply rows_at
+ apply tags_at
+ exact ite_eq_right he
+
+open private row_end_le from OAI.Computability.VPVNP.PairTraversalRows
+
+theorem allRows_below {m n : Memory w} {H cap previous base : ℕ} (ls : List Layer)
+ (ag : AgreeBelow H m n) (room : base + words cap ls ≤ H)
+ (hc : ∀ L ∈ ls, ∀ i, (L.ids i).length ≤ cap)
+ (rows : AllRows w n cap previous base ls) : AllRows w m cap previous base ls := by
+ induction ls generalizing previous base with
+ | nil => trivial
+ | cons L ls ih =>
+ have he : endPos cap base L + words cap ls ≤ H := by
+ simpa [words, endPos, address, Nat.mul_add, Nat.add_assoc] using room
+ refine ⟨fun i => ?_, ih he (fun l hl => hc l (List.mem_cons_of_mem _ hl)) rows.2⟩
+ let node := address cap base i.val
+ have hend : node + (cap+2) ≤ endPos cap base L := row_end_le _ _ _ _
+ have hlen : (childWords w cap previous L i).length ≤ cap := by
+ simpa only [childWords, List.length_map] using hc L List.mem_cons_self i
+ obtain ⟨hn, hn1, hs, h0, h1, hj⟩ := rows.1 i
+ refine ⟨hn, hn1, hs, (ag node (by omega)).trans h0, (ag (node+1) (by omega)).trans h1,
+ fun j => (ag (node+2+j.val) ?_).trans (hj j)⟩
+ have := j.isLt
+ omega
+
+theorem reads_below {m n : Memory w} {H offset cap base : ℕ} (ls : List TaggedLayer)
+ (ag : AgreeBelow H m n) (room : offset + base + tagWords cap ls ≤ H)
+ (reads : Reads w n offset cap base ls) : Reads w m offset cap base ls := by
+ induction ls generalizing base with
+ | nil => trivial
+ | cons L ls ih =>
+ have he : offset + endPos cap base L.layer + tagWords cap ls ≤ H := by
+ simpa [tagWords, words, endPos, address, Nat.mul_add, Nat.add_assoc] using room
+ refine ⟨fun i => ?_, ih he reads.2⟩
+ have h : address cap base i.val < endPos cap base L.layer :=
+ Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_left i.isLt (by omega)) _
+ exact (ag _ ((Nat.add_lt_add_left h offset).trans_le ((Nat.le_add_right _ _).trans he))).trans
+ (reads.1 i)
+
+/-- Reports of one pass in layer order. Each layer has one additional call
+that returns the first site of the next layer. -/
+def passReports (ls : List TaggedLayer)
+ (sites : (i : Fin ls.length) → Fin ls[i].layer.count → Report w)
+ (reset : Fin ls.length → Report w) : List (Report w) :=
+ (List.ofFn fun i => List.ofFn (sites i) ++ [reset i]).flatten
+
+private theorem sum_layer_counts (ls : List TaggedLayer) :
+ (∑ i : Fin ls.length, ls[i].layer.count) = (ls.map (fun l => l.layer.count)).sum := by
+ rw [← List.sum_ofFn]
+ congr 1
+ exact List.ext_getElem (by simp) (fun _ _ _ => by simp)
+
+theorem pass_calls (ls : List TaggedLayer)
+ (sites : (i : Fin ls.length) → Fin ls[i].layer.count → Report w)
+ (reset : Fin ls.length → Report w) :
+ (passReports ls sites reset).length = (ls.map (fun l => l.layer.count)).sum + ls.length := by
+ simp only [passReports, List.length_flatten, List.map_ofFn, Function.comp_apply,
+ List.length_append, List.length_ofFn, List.length_singleton, List.sum_ofFn,
+ Finset.sum_add_distrib]
+ rw [sum_layer_counts]
+ simp
+
+private theorem cost_ofFn {m : ℕ} (r : Fin m → Report w) :
+ RAMBuckets.cost Report.probes (List.ofFn r) = ∑ i, (1 + (r i).probes) := by
+ induction m with
+ | zero => simp [RAMBuckets.cost]
+ | succ n ih => rw [List.ofFn_succ, RAMBuckets.cost, ih, Fin.sum_univ_succ]
+
+private theorem cost_layers {m : ℕ} (stages : Fin m → List (Report w)) :
+ RAMBuckets.cost Report.probes (List.ofFn stages).flatten =
+ ∑ i, RAMBuckets.cost Report.probes (stages i) := by
+ induction m with
+ | zero => simp [RAMBuckets.cost]
+ | succ n ih =>
+ rw [List.ofFn_succ, List.flatten_cons, RAMBuckets.cost_append, ih, Fin.sum_univ_succ]
+
+/-- Exact native cost, including every reset and all reported operand reads. -/
+theorem pass_cost (ls : List TaggedLayer)
+ (sites : (i : Fin ls.length) → Fin ls[i].layer.count → Report w)
+ (reset : Fin ls.length → Report w) :
+ RAMBuckets.cost Report.probes (passReports ls sites reset) =
+ ∑ i, ((∑ j, (1 + (sites i j).probes)) + (1 + (reset i).probes)) := by
+ simp only [passReports, cost_layers, RAMBuckets.cost_append, cost_ofFn, RAMBuckets.cost,
+ Nat.add_zero]
+
+/-- Bound a pass by the measured probe allowance for active calls and its
+separate reset allowance. The terminal acceptance is accounted for separately. -/
+theorem pass_cost_le (ls : List TaggedLayer)
+ (sites : (i : Fin ls.length) → Fin ls[i].layer.count → Report w)
+ (reset : Fin ls.length → Report w) {active resetReads : ℕ}
+ (hs : ∀ i j, (sites i j).probes ≤ active) (hr : ∀ i, (reset i).probes ≤ resetReads) :
+ RAMBuckets.cost Report.probes (passReports ls sites reset) ≤
+ (1 + active) * (ls.map (fun l => l.layer.count)).sum + (1 + resetReads) * ls.length := by
+ rw [pass_cost]
+ calc
+ _ ≤ ∑ i : Fin ls.length, ((∑ _j : Fin ls[i].layer.count, (1 + active)) + (1 + resetReads)) :=
+ Finset.sum_le_sum fun i _ => Nat.add_le_add
+ (Finset.sum_le_sum fun j _ => Nat.add_le_add_left (hs i j) 1) (Nat.add_le_add_left (hr i) 1)
+ _ = _ := by
+ simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul,
+ Finset.sum_add_distrib, ← Finset.sum_mul]
+ simp only [Nat.cast_id, sum_layer_counts]
+ ring
+
+/-- All tags, all rows, and the accepting controller call. The exact count
+charges two resets for every layer and a final acceptance even at zero blocks. -/
+theorem controller_calls (ls : List TaggedLayer)
+ (tags rows : (i : Fin ls.length) → Fin ls[i].layer.count → Report w)
+ (tagReset rowReset : Fin ls.length → Report w) (done : Report w) :
+ (passReports ls tags tagReset ++ passReports ls rows rowReset ++ [done]).length =
+ 2 * (ls.map (fun l => l.layer.count)).sum + 2 * ls.length + 1 := by
+ rw [List.length_append, List.length_append, List.length_singleton, pass_calls, pass_calls]
+ omega
+
+/-- With a fixed operand setup cost on every burst, a role costs one
+additional probe. A leaf costs two and a fiber costs two per child plus
+three header probes. The resets and the accepting call use setup alone. -/
+theorem controller_cost_le (ls : List TaggedLayer) (setup cap : ℕ)
+ (tags rows : (i : Fin ls.length) → Fin ls[i].layer.count → Report w)
+ (tagReset rowReset : Fin ls.length → Report w) (done : Report w)
+ (tag : ∀ i j, (tags i j).probes ≤ setup + 1)
+ (row : ∀ i j, (rows i j).probes ≤ setup +
+ if i.val = 0 then 2 else 2 * (ls[i].layer.ids j).length + 3)
+ (capacity : ∀ (i : Fin ls.length) (j : Fin ls[i].layer.count), (ls[i].layer.ids j).length ≤ cap)
+ (tr : ∀ i, (tagReset i).probes ≤ setup) (rr : ∀ i, (rowReset i).probes ≤ setup)
+ (terminal : done.probes ≤ setup) :
+ RAMBuckets.cost Report.probes (passReports ls tags tagReset ++ passReports ls rows rowReset ++
+ [done]) ≤ (2 * setup + 2 * cap + 6) * (ls.map (fun l => l.layer.count)).sum +
+ 2 * (setup + 1) * ls.length + (setup + 1) := by
+ have row' i j : (rows i j).probes ≤ setup + 2 * cap + 3 := by
+ have h := row i j
+ have bound := capacity i j
+ split at h <;> omega
+ have ht := pass_cost_le ls tags tagReset tag tr
+ have hr := pass_cost_le ls rows rowReset row' rr
+ simp only [RAMBuckets.cost_append, RAMBuckets.cost, Nat.add_zero]
+ exact (Nat.add_le_add (Nat.add_le_add ht hr) (Nat.add_le_add_left terminal 1)).trans_eq (by ring)
+
+/-- Insert a reset after each stage. No protected write is added if the
+active wrapper agrees with its worker on those writes and the reset only
+reads or writes above the header. -/
+theorem pass_writes (H : ℕ) (ls : List TaggedLayer)
+ (sites workers : (i : Fin ls.length) → Fin ls[i].layer.count → Report w)
+ (reset : Fin ls.length → Report w)
+ (hs : ∀ i j, writesBelow H (sites i j).events = writesBelow H (workers i j).events)
+ (hr : ∀ i, writesBelow H (reset i).events = []) :
+ writesBelow H (eventLog (passReports ls sites reset)) =
+ writesBelow H (eventLog (List.ofFn fun i => List.ofFn (workers i)).flatten) := by
+ have flatten {n : ℕ} (f g : Fin n → List (Report w))
+ (equal : ∀ i, writesBelow H (eventLog (f i)) = writesBelow H (eventLog (g i))) :
+ writesBelow H (eventLog (List.ofFn f).flatten) =
+ writesBelow H (eventLog (List.ofFn g).flatten) := by
+ induction n with
+ | zero => rfl
+ | succ n ih =>
+ simp only [List.ofFn_succ, List.flatten_cons, eventLog, List.flatMap_append,
+ writesBelow_append]
+ exact congrArg₂ List.append (equal 0)
+ (ih (fun i => f i.succ) (fun i => g i.succ) (fun i => equal i.succ))
+ apply flatten
+ intro i
+ have site_eq {n : ℕ} (f g : Fin n → Report w)
+ (equal : ∀ j, writesBelow H (f j).events = writesBelow H (g j).events) :
+ writesBelow H (eventLog (List.ofFn f)) = writesBelow H (eventLog (List.ofFn g)) := by
+ induction n with
+ | zero => rfl
+ | succ n ih =>
+ simp only [List.ofFn_succ, eventLog, List.flatMap_cons, writesBelow_append]
+ exact congrArg₂ List.append (equal 0)
+ (ih (fun j => f j.succ) (fun j => g j.succ) (fun j => equal j.succ))
+ simpa only [eventLog, List.flatMap_append, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil, writesBelow_append, hr] using site_eq (sites i) (workers i) (hs i)
+
+variable {k A : Type*} [Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ} (T : ℕ)
+variable (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+
+/-- Evaluating the actual register setup counts repeated header loads in each
+of its eighteen output expressions. -/
+theorem controller_setup_loads : (∑ i, (TraversalController.formulas i).loads) = 257 := by decide
+
+/-- With those setup reads included on every burst, the cost of the complete
+two-pass controller is linear in the initial site count times the stage count.
+The constant includes the resets and final acceptance. -/
+theorem selected_controller_cost :
+ let ls := selected B f hf T hT X z
+ let cap := B.recordLimit
+ let setup := ∑ i, (TraversalController.formulas i).loads
+ ∀ (tags rows : (i : Fin ls.length) → Fin ls[i].layer.count → Report w)
+ (tagReset rowReset : Fin ls.length → Report w) (done : Report w),
+ (∀ i j, (tags i j).probes ≤ setup + 1) →
+ (∀ i j, (rows i j).probes ≤ setup +
+ if i.val = 0 then 2 else 2 * (ls[i].layer.ids j).length + 3) →
+ (∀ i, (tagReset i).probes ≤ setup) → (∀ i, (rowReset i).probes ≤ setup) →
+ done.probes ≤ setup →
+ RAMBuckets.cost Report.probes (passReports ls tags tagReset ++ passReports ls rows rowReset ++
+ [done]) ≤ (2 * cap + 1294) * (((S.steps + 1) * T + 1) * X.positions) := by
+ intro ls cap setup tags rows tagReset rowReset done ht hr tr rr terminal
+ have layers := selected_layers B f hf T hT X z
+ change ls.map TaggedLayer.layer = _ at layers
+ have hc (i : Fin ls.length) (j : Fin ls[i].layer.count) : (ls[i].layer.ids j).length ≤ cap := by
+ apply selected_capacity B f hf T hT X z
+ rw [← layers]
+ exact List.mem_map_of_mem (List.getElem_mem i.isLt)
+ have hs : (ls.map (fun l => l.layer.count)).sum ≤ ((S.steps + 1) * T + 1) * X.positions := by
+ have h := selected_count_sum_le B f hf T hT X z
+ rw [← layers, List.map_map] at h
+ exact h
+ let visits := ((S.steps + 1) * T + 1) * X.positions
+ have hp : 0 < X.positions := X.positions_pos
+ have hbound : (S.steps + 1) * T + 1 ≤ visits := Nat.le_mul_of_pos_right _ hp
+ have hl : ls.length ≤ visits := by
+ have h := executeLevels_length B f hf T hT X z
+ simp only [ls, selected, List.length_cons, List.length_map]
+ exact (Nat.succ_le_succ h).trans hbound
+ have hv : 1 ≤ visits := (Nat.succ_pos _).trans_le hbound
+ have hz : setup = 257 := controller_setup_loads
+ calc
+ _ ≤ _ := controller_cost_le ls setup cap tags rows tagReset rowReset done
+ ht hr hc tr rr terminal
+ _ ≤ (2 * setup + 2 * cap + 6) * visits + 2 * (setup + 1) * visits + (setup + 1) * visits :=
+ Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ hs) (Nat.mul_le_mul_left _ hl))
+ (Nat.le_mul_of_pos_right _ hv)
+ _ = _ := by rw [hz]; change _ = (2 * cap + 1294) * visits; ring
+
+/-- All protected data needed by the DFS survives the control-cell updates:
+the selected role words and ordered placement rows, the final-bit gap, and
+every raw input below the descriptor base. -/
+theorem selected_readback (base F H : ℕ) (raw final : Memory w)
+ (boundary : base + 2 * words B.recordLimit (selectedLayers B f hf T hT X z) + F ≤ H)
+ (ag : let ls := selectedLayers B f hf T hT X z
+ let size := words B.recordLimit ls
+ AgreeBelow H final (build B.recordLimit base base ls
+ (writeTags (size + F) B.recordLimit base (selected B f hf T hT X z) raw)))
+ (rowFit : base + words B.recordLimit (selectedLayers B f hf T hT X z) < 2 ^ w) :
+ let ls := selectedLayers B f hf T hT X z
+ let roles := selected B f hf T hT X z
+ let cap := B.recordLimit
+ let size := words cap ls
+ Reads w final (size + F) cap base roles ∧ AllRows w final cap base base ls ∧
+ (∀ x < base, final x = raw x) ∧
+ ∀ i < F, final (base + size + i) = raw (base + size + i) := by
+ intro ls roles cap size
+ have hroles : tagWords cap roles = size := by
+ rw [tagWords, show roles.map TaggedLayer.layer = ls from selected_layers B f hf T hT X z]
+ let tagged := writeTags (size + F) cap base roles raw
+ let reference := build cap base base ls tagged
+ have equal : AgreeBelow H final reference := ag
+ change base + 2 * size + F ≤ H at boundary
+ obtain ⟨rolesOK, bitsOK, rowsOK⟩ := selected_tags_and_rows B f hf T hT X z base F raw rowFit
+ refine ⟨reads_below roles equal (by rw [hroles]; omega) rolesOK,
+ allRows_below ls equal (by change base + size ≤ H; omega)
+ (selected_capacity B f hf T hT X z) rowsOK, ?_, ?_⟩
+ · intro x hx
+ exact (equal x (by omega)).trans ((build_outside ls cap base base tagged x (Or.inl hx)).trans
+ (write_tags_outside _ _ _ roles raw x (Or.inl (hx.trans_le (Nat.le_add_left _ _)))))
+ · intro i hi
+ exact (equal _ (by omega)).trans (bitsOK i hi)
+
+/-- Select native workers on the actual branch. Any controller log with the
+same visible writes reproduces their complete memory below the header. -/
+theorem selected_native_replay (base F H : ℕ) (raw : Memory w)
+ (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] raw base)
+ (room : base + 2 * words B.recordLimit (selectedLayers B f hf T hT X z) + F ≤ H)
+ (fit : H < 2 ^ w) :
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ords := branchOrders E data z
+ let old := siteOrder X
+ let cap := B.recordLimit
+ let ls := selectedLayers B f hf T hT X z
+ let offset := words cap ls + F
+ let roles := selected B f hf T hT X z
+ let dirs := selectedDirectories B f hf T hT X z raw base ds
+ let rowJobs := DirectoryRun.Worker.leaf cap base old.length ::
+ DirectoryRun.workers c ords old dirs cap base (address cap base old.length)
+ ∃ ts rs, RolePasses offset cap base roles raw ts ∧
+ DirectoryRun.Segments rowJobs (after raw (eventLog ts)) rs ∧
+ ∀ (m : Memory w) (controller : List (Report w)), AgreeBelow H m raw →
+ writesBelow H (eventLog controller) = writesBelow H (eventLog (ts ++ rs)) →
+ AgreeBelow H (after m (eventLog controller))
+ (build cap base base ls (writeTags offset cap base roles raw)) := by
+ intro E data c ords old cap ls offset roles dirs jobs
+ obtain ⟨ts, rs, tags, rows, image, _⟩ :=
+ native_arena B f hf T hT X z base F raw ds (room.trans_lt fit)
+ refine ⟨ts, rs, tags, rows, fun m controller ag hw x hx => ?_⟩
+ exact (replay_below ag hw x hx).trans (congrFun image x)
+
+end PairSimulation.TraversalRoles.ControllerMemory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerOrdinal.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerOrdinal.lean
new file mode 100644
index 0000000000..131ed7ec80
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerOrdinal.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.PairSimulationRouteWord
+import OAI.Computability.VPVNP.PairTraversalStageSize
+import OAI.Computability.VPVNP.CompressorDescriptorBranchSpace
+
+/-!
+# The persistent traversal controller ordinal
+
+Both the role pass and the row pass use the same radix for site ordinals.
+The radix reserves one more digit than the initial number of sites, so the
+end of any layer is represented even if that layer has the maximum count.
+The final return at phase-level twice the number of layers also fits the
+word, uniformly over the selected compressor branches.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalControllerOrdinal
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+variable {w L initialSites phaseLevel site : ℕ}
+
+/-- Numerical encoding of the phase-level and the current site. -/
+def pack (initialSites phaseLevel site : ℕ) : ℕ := phaseLevel * (initialSites + 1) + site
+
+theorem pack_lt (phase : phaseLevel < 2 * L) (digit : site ≤ initialSites) :
+ pack initialSites phaseLevel site < 2 * L * (initialSites + 1) := by
+ calc
+ _ < phaseLevel * (initialSites + 1) + (initialSites + 1) :=
+ Nat.add_lt_add_left (Nat.lt_succ_of_le digit) _
+ _ = (phaseLevel + 1) * (initialSites + 1) := (Nat.succ_mul ..).symm
+ _ ≤ _ := Nat.mul_le_mul_right _ phase
+
+private theorem quotient {a b : ℕ} (ha : a < 2 ^ w) (hb : b < 2 ^ w) :
+ BinaryOp.div.eval (a : Word w) (b : Word w) = ((a / b : ℕ) : Word w) := by
+ change Fin.ofNat _ ((a % (2^w)) / (b % (2^w))) = _
+ rw [Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb]
+ rfl
+
+private theorem remainder {a b : ℕ} (ha : a < 2 ^ w) (hb : b < 2 ^ w) :
+ BinaryOp.mod.eval (a : Word w) (b : Word w) = ((a % b : ℕ) : Word w) := by
+ change Fin.ofNat _ ((a % (2^w)) % (b % (2^w))) = _
+ rw [Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb]
+ rfl
+
+/-- The site and phase-level reads, including at an empty layer. -/
+theorem decode_of_fit (digit : site ≤ initialSites) (fit : pack initialSites phaseLevel site < 2 ^ w)
+ (radixFit : initialSites + 1 < 2 ^ w) :
+ let st := (pack initialSites phaseLevel site : Word w)
+ let pitch := ((initialSites + 1 : ℕ) : Word w)
+ BinaryOp.div.eval st pitch = (phaseLevel : Word w) ∧
+ BinaryOp.mod.eval st pitch = (site : Word w) := by
+ dsimp only
+ rw [quotient fit radixFit, remainder fit radixFit]
+ have d : site < initialSites + 1 := Nat.lt_succ_of_le digit
+ simp only [pack, Nat.mul_comm phaseLevel (initialSites + 1), Nat.mul_add_div (Nat.succ_pos _),
+ Nat.div_eq_of_lt d, Nat.add_zero, Nat.mul_add_mod, Nat.mod_eq_of_lt d, and_self]
+
+theorem decode (phase : phaseLevel < 2 * L) (digit : site ≤ initialSites)
+ (fit : 2 * L * (initialSites + 1) < 2 ^ w) :
+ let st := (pack initialSites phaseLevel site : Word w)
+ let pitch := ((initialSites + 1 : ℕ) : Word w)
+ BinaryOp.div.eval st pitch = (phaseLevel : Word w) ∧
+ BinaryOp.mod.eval st pitch = (site : Word w) :=
+ decode_of_fit digit ((pack_lt phase digit).trans fit)
+ ((Nat.le_mul_of_pos_left _ (Nat.zero_lt_of_lt phase)).trans_lt fit)
+
+/-- The terminal sentinel decodes to phase-level twice the number of layers. -/
+theorem decode_stop (hL : 0 < L) (fit : 2 * L * (initialSites + 1) < 2 ^ w) :
+ let st := (pack initialSites (2 * L) 0 : Word w)
+ let pitch := ((initialSites + 1 : ℕ) : Word w)
+ BinaryOp.div.eval st pitch = ((2 * L : ℕ) : Word w) ∧ BinaryOp.mod.eval st pitch = 0 := by
+ exact decode_of_fit (Nat.zero_le _) (by simpa [pack] using fit)
+ ((Nat.le_mul_of_pos_left _ (Nat.mul_pos (by decide) hL)).trans_lt fit)
+
+/-- A level count of one selects the terminal site's count. -/
+theorem one_div_levels (hL : 0 < L) (fit : L < 2 ^ w) :
+ BinaryOp.div.eval (1 : Word w) (L : Word w) = if L = 1 then 1 else 0 := by
+ rw [show (1 : Word w) = ((1 : ℕ) : Word w) from rfl, quotient (lt_of_le_of_lt hL fit) fit]
+ by_cases h : L = 1
+ · subst L; rfl
+ · rw [ite_eq_right h, Nat.div_eq_of_lt (show 1 < L by omega)]
+ rfl
+
+/-- The level, its nonzero flag, and its predecessor with saturation at zero. -/
+theorem index_words (hL : 0 < L) (fitL : L < 2 ^ w) (fitPhase : phaseLevel < 2 ^ w) :
+ let j := BinaryOp.mod.eval (phaseLevel : Word w) (L : Word w)
+ let nz := BinaryOp.div.eval j j
+ j = ((phaseLevel % L : ℕ) : Word w) ∧
+ nz = (if phaseLevel % L = 0 then 0 else 1) ∧
+ BinaryOp.sub.eval j nz = ((phaseLevel % L - 1 : ℕ) : Word w) := by
+ dsimp only
+ rw [remainder fitPhase fitL, RouteWord.div_self ((Nat.mod_lt _ hL).trans fitL)]
+ by_cases h : phaseLevel % L = 0
+ · simp only [h, ite_eq_left, Nat.zero_sub, Nat.cast_zero, BinaryOp.eval, sub_self, and_self]
+ · simp only [ite_eq_right h, true_and]
+ exact RouteWord.sub_cast (Nat.pos_of_ne_zero h)
+
+/-- Advancing within the current layer adds one to the packed word. -/
+theorem next_site (phase : phaseLevel < 2 * L) (active : site < initialSites)
+ (fit : 2 * L * (initialSites + 1) < 2 ^ w) :
+ let next := BinaryOp.add.eval (pack initialSites phaseLevel site : Word w) 1
+ next.val = pack initialSites phaseLevel (site + 1) := by
+ have eq : BinaryOp.add.eval (pack initialSites phaseLevel site : Word w) 1 =
+ (pack initialSites phaseLevel (site + 1) : Word w) := by
+ simp only [BinaryOp.eval, pack, Nat.cast_add, Nat.cast_one, add_assoc]
+ dsimp only
+ rw [eq, Fin.val_natCast, Nat.mod_eq_of_lt ((pack_lt phase active).trans fit)]
+
+/-- Skipping to the next layer resets the site digit, including the final
+transition to the terminal sentinel. -/
+theorem next_level (phase : phaseLevel < 2 * L) (fit : 2 * L * (initialSites + 1) < 2 ^ w) :
+ let next := BinaryOp.mul.eval (BinaryOp.add.eval (phaseLevel : Word w) 1)
+ ((initialSites + 1 : ℕ) : Word w)
+ next.val = pack initialSites (phaseLevel + 1) 0 := by
+ have eq : BinaryOp.mul.eval (BinaryOp.add.eval (phaseLevel : Word w) 1)
+ ((initialSites + 1 : ℕ) : Word w) = (pack initialSites (phaseLevel + 1) 0 : Word w) := by
+ simp only [BinaryOp.eval, pack, Nat.add_zero, Nat.cast_mul, Nat.cast_add, Nat.cast_one]
+ dsimp only
+ rw [eq, Fin.val_natCast, Nat.mod_eq_of_lt]
+ simpa only [pack, Nat.add_zero] using (Nat.mul_le_mul_right (initialSites + 1) phase).trans_lt fit
+
+open CompressorRecords CursorBounds CursorNetwork Compression Filter
+open private bounded_blockCount from OAI.Computability.VPVNP.CompressorDescriptorSpace
+
+/-- The controller's two full passes and the terminal sentinel fit one host
+word at a common threshold preceding all choices of specialization and branch. -/
+theorem eventually_selected_fit {k : Type*} [Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (b : ℕ) (hb : 1 ≤ b) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let T := blockCount (u.θ : ℝ) n
+ let X := pairInput S labels hD
+ ∀ z : (B.execute f hf T hT X).Choices,
+ 2 * ((executeLevels B f hf T hT X z).length + 1) * (X.positions + 1) < 2 ^ wordBits b n := by
+ have hθ : (u.θ : ℝ) ≤ 1 := by
+ have := (Rat.cast_lt (K := ℝ)).mpr u.theta_lt
+ norm_num at this
+ linarith
+ let levels := ((PolynomiallyBounded.const (S.steps + 1)).mul (bounded_blockCount hθ)).add
+ (PolynomiallyBounded.const 1)
+ have cap := ((PolynomiallyBounded.const 2).mul levels).mul
+ ((CursorRAM.bounded_positions b).add (PolynomiallyBounded.const 1))
+ filter_upwards [CursorRAM.eventual_word_room b hb cap] with n hn
+ intro base lanes labels hD hT A _ f hf T X z
+ have hp : X.positions = initialPositions b n := pairInput_positions S labels hD
+ rw [hp]
+ exact (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left 2
+ (Nat.succ_le_succ (executeLevels_length B f hf T hT X z)))).trans_lt hn
+
+end PairSimulation.TraversalControllerOrdinal
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerPersistence.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerPersistence.lean
new file mode 100644
index 0000000000..383cdfbb91
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerPersistence.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairTraversalControllerInputs
+
+/-!
+# Persistent traversal parameters during the role and row scans
+
+Only six terminal scalars are used by the traversal workers. Their level
+scalars all precede the row arena. Agreement on these words therefore
+preserves each chronological worker's count, role and parameter bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalControllerInputs
+
+open BurstRAM CompressorRecords LocalHistory Compression TraversalRows TraversalRoles
+
+variable {w : ℕ} {pub : Fin 11 → Word w} {m m' : Memory w} {H first pitch offset cap base : ℕ}
+variable {old : TaggedLayer} {ls : List (Fiber w)}
+
+/-- The terminal words read by the traversal stage. -/
+def terminalScalars : Finset ℕ := {1, 7, 14, 15, 16, 17}
+
+/-- Transfer resident scalars after any partial scan. Only the terminal
+words read by the controller need survive writes in the high header. -/
+theorem Resident.transfer (d : Resident pub m H first pitch offset cap base old ls)
+ (headersBefore : ∀ j ≤ ls.length, first + j*pitch + 28 ≤ base)
+ (below : ∀ x < base, m' x = m x)
+ (terminal : ∀ f ∈ terminalScalars, m' (H+f) = m (H+f)) :
+ Resident pub m' H first pitch offset cap base old ls := by
+ have atLevel (j field : ℕ) (hj : j ≤ ls.length) (hf : field < 28) :
+ m' (first+j*pitch+field) = m (first+j*pitch+field) :=
+ below _ ((Nat.add_lt_add_left hf _).trans_le (headersBefore j hj))
+ refine ⟨d.header,d.headerFits,d.levelFits,
+ (terminal 16 (by decide)).trans d.firstHead,(terminal 17 (by decide)).trans d.levelPitch,
+ (congrArg Fin.val (terminal 1 (by decide))).trans d.levels,
+ (terminal 14 (by decide)).trans d.roleOffset,(terminal 15 (by decide)).trans d.rowStride,
+ fun j hj => (atLevel j 14 hj (by decide)).trans (d.currentBase j hj),
+ fun j => (atLevel j.val 27 (by simpa using j.isLt) (by decide)).trans (d.role j),
+ ?_, fun h => (congrArg Fin.val (terminal 7 (by decide))).trans (d.terminalSites h),
+ fun i => (congrArg Fin.val (atLevel i.val 22 i.isLt.le (by decide))).trans (d.produced i),
+ fun i => (atLevel i.val 24 i.isLt.le (by decide)).trans (d.childCounts i),
+ fun i => (atLevel i.val 25 i.isLt.le (by decide)).trans (d.childLists i),
+ fun i => (atLevel i.val 26 i.isLt.le (by decide)).trans (d.childCapacity i)⟩
+ intro h
+ have same := atLevel 0 21 (Nat.zero_le _) (by decide)
+ simp only [Nat.zero_mul,Nat.add_zero] at same
+ exact (congrArg Fin.val same).trans (d.initial h)
+
+variable {k A : Type*} [Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ} (T : ℕ)
+variable (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices) (raw : Memory w)
+variable (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] raw base)
+
+/-- Every reference prefix sees the same selected schedule and initial
+site count when its row and tag writes preserve the resident headers. -/
+theorem selected_prefix_schedule
+ (d : Resident pub m H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers (executeLevels B f hf T hT X z) ds))
+ (headersBefore : ∀ j ≤ (executeLevels B f hf T hT X z).length, first+j*pitch+28 ≤ base)
+ (refs : List (Report w))
+ (below : ∀ q ≤ refs.length, ∀ x < base, after m (eventLog (refs.take q)) x = m x)
+ (terminal : ∀ q ≤ refs.length, ∀ f ∈ terminalScalars,
+ after m (eventLog (refs.take q)) (H+f) = m (H+f)) :
+ ∀ q ≤ refs.length, let m' := after m (eventLog (refs.take q))
+ Schedule pub m' offset B.recordLimit base (selected B f hf T hT X z)
+ (selectedJobs B f hf T hT X z base raw ds) ∧ (siteCount pub m' 0).val = X.positions := by
+ intro q hq m'
+ have d' := d.transfer (by simpa only [levelFibers,List.length_ofFn] using headersBefore)
+ (below q hq) (terminal q hq)
+ refine ⟨selected_schedule B f hf T hT X z base raw ds d', (count_zero d').trans ?_⟩
+ change (siteOrder X).length = Fintype.card X.network.Site
+ simpa only [Fintype.card_fin] using Fintype.card_congr (siteOrder X).entries
+
+end PairSimulation.TraversalControllerInputs
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerPrepare.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerPrepare.lean
new file mode 100644
index 0000000000..d48ef46520
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerPrepare.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.PairTraversalControllerCode
+
+/-!
+# The complete read-only traversal dispatcher prefix
+
+From the native reset state, the controller reaches a unique destination using
+only ticks and reads. Every computed operand is evaluated on the entry memory.
+The worker scratch registers are zero at that point. The log may be replayed
+against any memory, and its exact probe count is independent of the ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController.Native
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.execute from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+open private execute_lines lines_probes no_choices emit_list
+ from OAI.Computability.VPVNP.CompressorRecordRegisterSetup
+open private eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe
+
+variable {w : ℕ}
+
+private theorem readOnly {M : Machine w P R 11} {m : Memory w} {c d : Config w P R}
+ {es : List (Event w)} (he : ReadPrefix M m c es d) (n : Memory w) :
+ (∀ a v, Event.write a v ∉ es) ∧ after n es = n := by
+ induction he with
+ | nil => exact ⟨by simp, rfl⟩
+ | tick _ _ ih | read _ _ _ ih =>
+ exact ⟨fun a v => by simp [ih.1 a v], ih.2⟩
+
+private theorem scratch_apart (i : Fin 7) (j : Fin (RegisterSetup.regCount formulas)) :
+ scratchRegs i ≠ vm j := by
+ intro eqn
+ have := congrArg Fin.val eqn
+ change RegisterSetup.regCount formulas + i.val = j.val at this
+ omega
+
+private theorem scratch_zero (pub : Fin 11 → Word w) (s : Word w) (i : Fin 7) :
+ (loaded pub s).reg (scratchRegs i) = 0 := by
+ have outside (t : Fin 10) (ht : 7 ≤ t.val) : scratchRegs i ≠ extra t := by
+ intro e
+ have := congrArg Fin.val e
+ change RegisterSetup.regCount formulas + i.val = RegisterSetup.regCount formulas + t.val at this
+ omega
+ simp only [loaded, Function.update_of_ne (outside 9 (by decide)),
+ Function.update_of_ne (outside 8 (by decide)), Function.update_of_ne (outside 7 (by decide))]
+
+private theorem tick_cost (n : ℕ) : countProbes (List.replicate n (.tick : Event w)) = 0 ∧
+ choiceBits (List.replicate n (.tick : Event w)) = [] ∧
+ ∀ m : Memory w, after m (List.replicate n .tick) = m := by
+ induction n with
+ | zero => exact ⟨rfl, rfl, fun _ => rfl⟩
+ | succ n ih => simpa only [List.replicate_succ, countProbes, choiceBits, after, List.foldl_cons,
+ BurstRAM.update] using ih
+
+/-- Chronological log of the register setup and guard instructions. -/
+def prefixTrace (pub : Fin 11 → Word w) (state : Word w) (m : Memory w) (rs : Regs w R) :
+ List (Event w) :=
+ [.tick, .tick, .tick] ++ (RowRecipe.evaluate (recipePub pub) state m
+ (RegisterSetup.lines formulas) ((loaded pub state).reg ∘ vm)).1 ++
+ List.replicate (route rs).ticks .tick
+
+set_option maxRecDepth 8192 in
+/-- Exact native setup and guard traversal, with all operand values, the
+read-only prefix and the continuation at the selected machine label. -/
+theorem prepare_trace (pub : Fin 11 → Word w) (state : Word w) (m : Memory w) :
+ ∃ (es : List (Event w)) (rs : Regs w R),
+ (∀ i, rs (value i) = (formulas i).eval (recipePub pub) state m) ∧
+ (∀ i, rs (scratchRegs i) = 0) ∧
+ es.length = 3 + (RegisterSetup.lines formulas).length + (route rs).ticks ∧
+ countProbes es = ∑ i, (formulas i).loads ∧ choiceBits es = [] ∧
+ (∀ a v, Event.write a v ∉ es) ∧ (∀ n : Memory w, after n es = n) ∧
+ (∀ fuel bits, execute (machine pub).program (fuel + es.length)
+ ((machine pub).program.start state) m bits =
+ (execute (machine pub).program fuel ⟨(route rs).pc, state, rs, fun _ => 0⟩ m bits).map
+ (Flow.prependEvents es)) ∧ es = prefixTrace pub state m rs := by
+ let c := loaded pub state
+ let start := c.reg ∘ vm
+ let eval := RowRecipe.evaluate (recipePub pub) state m (RegisterSetup.lines formulas) start
+ obtain ⟨d, run, endPC, mem, pers, vals, frame⟩ := execute_lines vm inputs (machine pub) m
+ (RegisterSetup.lines formulas) (fun i j => (inputs_apart j i).symm) (recipePub pub) state
+ start setupPC (linked_setup pub) c rfl (loaded_inputs pub state) (loaded_state pub state)
+ (fun _ => rfl)
+ let guards := List.replicate (route d.reg).ticks (.tick : Event w)
+ let pre : List (Event w) := [.tick, .tick, .tick]
+ let es := pre ++ eval.1 ++ guards
+ have length : eval.1.length = (RegisterSetup.lines formulas).length :=
+ (eval_cost (recipePub pub) state m (RegisterSetup.lines formulas) start).1
+ have probes : countProbes eval.1 = ∑ i, (formulas i).loads := lines_probes formulas ..
+ have bits : choiceBits eval.1 = [] := no_choices ..
+ have readonly (n : Memory w) := readOnly run n
+ have hguards := tick_cost (w := w) (route d.reg).ticks
+ refine ⟨es, d.reg, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, rfl⟩
+ · intro i
+ have output := emit_list formulas (recipePub pub) state m (List.finRange 18) start i
+ exact (vals _).trans (output.trans (ite_eq_left (List.mem_finRange i)))
+ · intro i
+ exact (frame _ (scratch_apart i)).trans (scratch_zero pub state i)
+ · simp [es, pre, guards, length]
+ omega
+ · simp only [es, countProbes_append, show countProbes pre = 0 from rfl, probes, guards,
+ hguards.1, Nat.zero_add, Nat.add_zero]
+ · simp only [es, Flow.choiceBits_append, show choiceBits pre = [] from rfl, bits, guards,
+ hguards.2.1, List.nil_append]
+ · intro a v
+ have noGuard : Event.write a v ∉ guards := by
+ intro h
+ have eqn : Event.write a v = .tick := List.eq_of_mem_replicate h
+ cases eqn
+ simpa [es, pre, noGuard] using (show Event.write a v ∉ eval.1 from (readonly m).1 a v)
+ · intro n
+ have ha : after n eval.1 = n := (readonly n).2
+ simp only [es, after, List.foldl_append, show pre.foldl BurstRAM.update n = n from rfl]
+ change after (after n eval.1) guards = n
+ rw [ha]
+ exact hguards.2.2 n
+ · intro fuel bs
+ have he := ReadPrefix.execute run (fuel + (route d.reg).ticks) bs
+ have hd : d = ⟨guardPC 0, state, d.reg, fun _ => 0⟩ := by
+ have pc := endPC.trans setup_end
+ cases d
+ simp_all only [c, loaded]
+ change execute (machine pub).program (fuel + es.length)
+ ((machine pub).program.start state) m bs = _
+ rw [show fuel + es.length = fuel + (route d.reg).ticks + eval.1.length + 3 by
+ simp [es, pre, guards]; omega, enter, he]
+ have hg := dispatch pub state d.reg (fun _ => 0) m bs fuel
+ rw [← hd] at hg
+ rw [hg, Option.map_map, Option.map_map]
+ congr 1
+ funext rep
+ simp [Function.comp_def, Flow.prependEvents, es, pre, guards, eval, List.append_assoc]
+
+/-- Prepare the worker at its selected label with its complete read-only prefix. -/
+theorem prepare (pub : Fin 11 → Word w) (state : Word w) (m : Memory w) :
+ ∃ (es : List (Event w)) (rs : Regs w R),
+ (∀ i, rs (value i) = (formulas i).eval (recipePub pub) state m) ∧
+ (∀ i, rs (scratchRegs i) = 0) ∧
+ es.length = 3 + (RegisterSetup.lines formulas).length + (route rs).ticks ∧
+ countProbes es = ∑ i, (formulas i).loads ∧ choiceBits es = [] ∧
+ (∀ a v, Event.write a v ∉ es) ∧ (∀ n : Memory w, after n es = n) ∧
+ ∀ fuel bits, execute (machine pub).program (fuel + es.length)
+ ((machine pub).program.start state) m bits =
+ (execute (machine pub).program fuel ⟨(route rs).pc, state, rs, fun _ => 0⟩ m bits).map
+ (Flow.prependEvents es) := by
+ obtain ⟨es, rs, fields, zero, length, probes, bits, writes, memory, run, _⟩ :=
+ prepare_trace pub state m
+ exact ⟨es, rs, fields, zero, length, probes, bits, writes, memory, run⟩
+
+end PairSimulation.TraversalController.Native
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerRead.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerRead.lean
new file mode 100644
index 0000000000..00f8e8d3fd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerRead.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.PairTraversalControllerFormula
+import OAI.Computability.VPVNP.PairTraversalControllerInputs
+import OAI.Computability.VPVNP.PairTraversalControllerOrdinal
+
+/-!
+# Readback of the traversal controller's loaded register bank
+
+The register formulas read the level headers with the packed persistent
+ordinal. Their two branchless count selections use self-division and
+subtraction in the word ring. This also accounts for the initial-only
+schedule and for the final controller sentinel.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM PrivateRAM CompressorRecords PhaseRecipe
+open TraversalControllerInputs TraversalControllerOrdinal
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The meanings of the eighteen loaded registers. The fiber worker executes
+at a positive layer index. Its four producer fields are loaded also at index zero. -/
+structure Readback (pub : Fin 11 → Word w) (m : Memory w) (L N p i : ℕ)
+ (rs : Fin R → Word w) : Prop where
+ site : rs (value 0) = (i : Word w)
+ phase : rs (value 1) = (p : Word w)
+ levels : rs (value 2) = (L : Word w)
+ twice : rs (value 3) = ((2 * L : ℕ) : Word w)
+ count : rs (value 4) = siteCount pub m (p % L)
+ index : rs (value 5) = ((p % L : ℕ) : Word w)
+ zero : rs (value 6) = 0
+ next : rs (value 7) = (pack N p (i + 1) : Word w)
+ reset : rs (value 8) = (pack N (p + 1) 0 : Word w)
+ role : rs ∘ roleAlloc.words (by decide : 4 ≤ 6) = tagParams pub m (p % L)
+ leaf : rs ∘ leafAlloc.words (by decide : 2 ≤ 6) = leafParams pub m
+ fiberHeader : ∀ j : Fin 4, rs (fiberAlloc.bank (j.castLE (by decide))) =
+ fiberParams pub m (p % L - 1) (j.castLE (by decide))
+ fiber : p % L ≠ 0 → rs ∘ fiberAlloc.bank = fiberParams pub m (p % L - 1)
+
+/-- Reading the operand bank from the terminal and level headers gives every
+dispatch operand and worker parameter, including the next-state words. -/
+theorem readback (pub : Fin 11 → Word w) (m : Memory w) (L N p i : ℕ)
+ (rs : Fin R → Word w) (hLevels : (terminalField pub m 1).val = L)
+ (hSites : (siteCount pub m 0).val = N) (hPos : 0 < L) (hDigit : i ≤ N)
+ (hPitch : N + 1 < 2 ^ w) (hState : pack N p i < 2 ^ w)
+ (loaded : ∀ t, rs (value t) = (formulas t).eval (recipePub pub) (pack N p i : Word w) m) :
+ Readback pub m L N p i rs := by
+ let ev := Expr.eval (recipePub pub) (pack N p i : Word w) m
+ have hterm (d : ℕ) : ev (term d) = terminalField pub m d := rfl
+ have hlevel {j : Expr} {n : ℕ} (hj : ev j = (n : Word w)) (d : ℕ) :
+ ev (level j d) = levelField pub m n d := by
+ change m (terminalField pub m 16 + ev j * terminalField pub m 17 + (d : Word w)).val = _
+ rw [hj]
+ rfl
+ have hlevelZero := @hlevel (.lit 0) 0 rfl
+ have hL : ev levels = (L : Word w) := by
+ change terminalField pub m 1 = _
+ rw [← hLevels]
+ exact (Fin.ofNat_val_eq_self _).symm
+ have fitL : L < 2 ^ w := hLevels ▸ (terminalField pub m 1).isLt
+ have hN : ev initialSites = siteCount pub m 0 := by
+ change ev (level (.lit 0) 21) + BinaryOp.div.eval 1 (ev levels) *
+ (ev (term 7) - ev (level (.lit 0) 21)) = _
+ rw [hlevelZero, hL, one_div_levels hPos fitL, hterm, siteCount, hLevels]
+ by_cases h : L = 1 <;> simp [h]
+ have hNcast : ev initialSites = (N : Word w) := by
+ rw [hN, ← hSites]
+ exact (Fin.ofNat_val_eq_self _).symm
+ have hpitch : ev pitch = ((N + 1 : ℕ) : Word w) := by
+ change ev initialSites + 1 = _
+ rw [hNcast, Nat.cast_add, Nat.cast_one]
+ obtain ⟨hquot, hrem⟩ := decode_of_fit hDigit hState hPitch
+ have hphase : ev phaseLevel = (p : Word w) := by
+ change BinaryOp.div.eval (pack N p i : Word w) (ev pitch) = _
+ rwa [hpitch]
+ have hsite : ev site = (i : Word w) := by
+ change BinaryOp.mod.eval (pack N p i : Word w) (ev pitch) = _
+ rwa [hpitch]
+ have fitP : p < 2 ^ w := ((Nat.le_mul_of_pos_right p (Nat.succ_pos N)).trans
+ (Nat.le_add_right _ i)).trans_lt hState
+ obtain ⟨hidx, hflag, hprev⟩ := index_words hPos fitL fitP
+ have hj : ev index = ((p % L : ℕ) : Word w) := by
+ change BinaryOp.mod.eval (ev phaseLevel) (ev levels) = _
+ rwa [hphase, hL]
+ have hnz : ev positiveIndex = if p % L = 0 then 0 else 1 := by
+ change BinaryOp.div.eval (BinaryOp.mod.eval (ev phaseLevel) (ev levels))
+ (BinaryOp.mod.eval (ev phaseLevel) (ev levels)) = _
+ rwa [hphase, hL]
+ have hp : ev previous = ((p % L - 1 : ℕ) : Word w) := by
+ change BinaryOp.sub.eval (BinaryOp.mod.eval (ev phaseLevel) (ev levels))
+ (BinaryOp.div.eval (BinaryOp.mod.eval (ev phaseLevel) (ev levels))
+ (BinaryOp.mod.eval (ev phaseLevel) (ev levels))) = _
+ rwa [hphase, hL]
+ have hc : ev count = siteCount pub m (p % L) := by
+ change ev initialSites + ev positiveIndex * (ev (level previous 22) - ev initialSites) = _
+ rw [hN, hnz, hlevel hp]
+ cases h : p % L with
+ | zero => simp
+ | succ j => simp [siteCount]
+ have ht : ev (levels.add levels) = ((2 * L : ℕ) : Word w) := by
+ change ev levels + ev levels = _
+ rw [hL, two_mul, Nat.cast_add]
+ have hnext : ev (Expr.state.add (.lit 1)) = (pack N p (i + 1) : Word w) := by
+ change (pack N p i : Word w) + 1 = _
+ simp [pack, add_assoc]
+ have hreset : ev ((phaseLevel.add (.lit 1)).mul pitch) = (pack N (p + 1) 0 : Word w) := by
+ change (ev phaseLevel + 1) * ev pitch = _
+ rw [hphase, hpitch]
+ simp [pack]
+ refine ⟨(loaded 0).trans hsite, (loaded 1).trans hphase, (loaded 2).trans hL,
+ (loaded 3).trans ht, (loaded 4).trans hc, (loaded 5).trans hj, loaded 6,
+ (loaded 7).trans hnext, (loaded 8).trans hreset, ?_, ?_, ?_, ?_⟩
+ · funext j
+ apply (loaded (roleFields (j.castLE (by decide)))).trans
+ fin_cases j <;> first | exact hterm _ | exact hlevel hj _
+ · funext j
+ apply (loaded (leafFields (j.castLE (by decide)))).trans
+ fin_cases j <;> first | exact hterm _ | exact hlevelZero _
+ · intro j
+ apply (loaded (fiberFields (j.castLE (by decide)))).trans
+ fin_cases j <;> exact hlevel hp _
+ · intro hpos
+ have he : p % L - 1 + 1 = p % L := by omega
+ funext j
+ apply (loaded (fiberFields j)).trans
+ fin_cases j <;> first | exact hlevel hp _ | exact hterm _ | skip
+ change ev (level index 14) = levelField pub m (p % L - 1 + 1) 14
+ rw [he]
+ exact hlevel hj 14
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerReference.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerReference.lean
new file mode 100644
index 0000000000..2cc8c75e49
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerReference.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.PairTraversalControllerBody
+import OAI.Computability.VPVNP.PairTraversalRoleExecution
+import OAI.Computability.VPVNP.PairTraversalDirectoryRun
+
+/-!
+# Chronological traversal passes and their reset-entry calls
+
+The reference jobs write one layer of role tags at a time, then the leaf
+and each successive fiber layer. A site's call uses exactly the memory
+left by earlier sites of its own pass and all preceding passes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM BurstRAM.PrivateRAM TraversalRows
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Role jobs advance the descriptor base after every layer. -/
+def tagJobs (w offset cap base : ℕ) : List TraversalRoles.TaggedLayer → List (Pass w)
+ | [] => []
+ | l :: ls => .tag (TraversalRoles.Native.params offset cap base (l.role.code : Word w)) l.layer.count ::
+ tagJobs w offset cap (endPos cap base l.layer) ls
+
+@[simp] theorem tagJobs_length (w offset cap base : ℕ) (ls : List TraversalRoles.TaggedLayer) :
+ (tagJobs w offset cap base ls).length = ls.length := by
+ induction ls generalizing base with
+ | nil => rfl
+ | cons l ls ih => simp only [tagJobs, List.length_cons, ih]
+
+/-- The indexed job uses the same descriptor base as the controller's
+tag-parameter lookup. -/
+theorem tagJobs_at (w offset cap base : ℕ) (ls : List TraversalRoles.TaggedLayer) (i : Fin ls.length) :
+ (tagJobs w offset cap base ls)[i.val]? = some (.tag (TraversalRoles.Native.params offset cap
+ (TraversalRoles.layerBase cap base ls i.val) (ls[i.val].role.code : Word w)) ls[i.val].layer.count) := by
+ induction ls generalizing base with
+ | nil => exact i.elim0
+ | cons l ls ih =>
+ induction i using Fin.cases with
+ | zero => simp only [tagJobs, Fin.val_zero, List.getElem?_cons_zero, List.getElem_cons_zero,
+ TraversalRoles.layerBase_zero]
+ | succ j => simpa only [tagJobs, Fin.val_succ, List.getElem?_cons_succ, List.getElem_cons_succ,
+ TraversalRoles.layerBase_cons] using ih (endPos cap base l.layer) j
+
+/-- The row job uses the exact public directory of its original worker. -/
+def rowJob : DirectoryRun.Worker w → Pass w
+ | .leaf cap base count => .leaf (LeafWorker.directory w cap base) count
+ | .fiber pub cap previous base count => .fiber (workerData pub cap previous base) cap count
+
+/-- Consecutive passes start at ordinal zero and retain external memory. -/
+inductive Reference : List (Pass w) → Memory w → List (Report w) → Prop
+ | nil (m : Memory w) : Reference [] m []
+ | cons {P : Pass w} {tail : List (Pass w)} {m : Memory w} {rs ss : List (Report w)}
+ (run : P.Run m rs) (rest : Reference tail (after m (eventLog rs)) ss) :
+ Reference (P :: tail) m (rs ++ ss)
+
+private theorem append_memory (m : Memory w) (rs ss : List (Report w)) :
+ after m (eventLog (rs ++ ss)) = after (after m (eventLog rs)) (eventLog ss) := by
+ simp only [eventLog, List.flatMap_append, after, List.foldl_append]
+
+theorem Reference.append {xs ys : List (Pass w)} {m : Memory w} {rs ss : List (Report w)}
+ (first : Reference xs m rs) (second : Reference ys (after m (eventLog rs)) ss) :
+ Reference (xs ++ ys) m (rs ++ ss) := by
+ induction first with
+ | nil m => exact second
+ | @cons P tail m localRs rest hr ht ih =>
+ rw [append_memory] at second
+ simpa only [List.cons_append, List.append_assoc] using Reference.cons hr (ih second)
+
+theorem Reference.of_tags {offset cap base : ℕ} {ls : List TraversalRoles.TaggedLayer}
+ {m : Memory w} {rs : List (Report w)} (h : TraversalRoles.RolePasses offset cap base ls m rs) :
+ Reference (tagJobs w offset cap base ls) m rs := by
+ induction h with
+ | nil => exact .nil _
+ | cons hr _ ih => exact .cons hr ih
+
+theorem Reference.of_rows {xs : List (DirectoryRun.Worker w)} {m : Memory w} {rs : List (Report w)}
+ (h : DirectoryRun.Segments xs m rs) : Reference (xs.map rowJob) m rs := by
+ induction h with
+ | nil => exact .nil _
+ | @cons head tail m rs ss hr ht ih =>
+ apply Reference.cons _ ih
+ cases head <;> exact hr
+
+theorem Reference.of_passes {offset cap base : ℕ} {ls : List TraversalRoles.TaggedLayer}
+ {xs : List (DirectoryRun.Worker w)} {m : Memory w} {tags rows : List (Report w)}
+ (ht : TraversalRoles.RolePasses offset cap base ls m tags)
+ (hr : DirectoryRun.Segments xs (after m (eventLog tags)) rows) :
+ Reference (tagJobs w offset cap base ls ++ xs.map rowJob) m (tags ++ rows) :=
+ (of_tags ht).append (of_rows hr)
+
+namespace Pass
+
+variable {P : Pass w} {m : Memory w} {rs : List (Report w)}
+
+theorem Run.branchPaths (h : P.Run m rs) : BurstRAM.branchPaths rs = List.replicate P.count [] :=
+ ((runSegment_iff ..).mp h).2.2
+
+theorem Run.length (h : P.Run m rs) : rs.length = P.count := by
+ simpa only [BurstRAM.branchPaths, List.length_map, List.length_replicate] using
+ congrArg List.length h.branchPaths
+
+/-- Each step retains its full trace and uses the incremented site ordinal. -/
+inductive Sites (P : Pass w) : Word w → Memory w → List (Report w) → Prop
+ | nil (site : Word w) (m : Memory w) : Sites P site m []
+ | cons {site : Word w} {m : Memory w} {r : Report w} {rs : List (Report w)}
+ (step : P.At site m r) (rest : Sites P (site+1) (after m r.events) rs) :
+ Sites P site m (r :: rs)
+
+private theorem sites_from {site : Word w} {n : ℕ}
+ (run : runSegment P.spec.2 P.clock (some site) m (List.replicate n []) = some rs) :
+ Sites P site m rs := by
+ induction n generalizing site m rs with
+ | zero =>
+ have : rs = [] := Option.some.inj run.symm
+ subst rs
+ exact .nil _ _
+ | succ n ih =>
+ rw [List.replicate_succ, runSegment] at run
+ cases he : execute P.spec.2 P.clock (P.spec.2.start site) m [] with
+ | none => simp only [he, reduceCtorEq] at run
+ | some r =>
+ rw [he] at run
+ obtain ⟨ss,hs,rfl⟩ := Option.map_eq_some_iff.mp run
+ have step : P.At site m r := he
+ rw [Pass.next step] at hs
+ exact .cons step (ih hs)
+
+theorem Run.sites (h : P.Run m rs) : Sites P 0 m rs := sites_from h
+
+private theorem Sites.atSite {site : Word w} (h : Sites P site m rs) (i : Fin rs.length) :
+ P.At (site + (i.val : Word w)) (after m (eventLog (rs.take i.val))) rs[i.val] := by
+ induction h with
+ | nil => exact i.elim0
+ | @cons site m r rs step _ ih =>
+ induction i using Fin.cases with
+ | zero =>
+ change P.At (site + ((0 : ℕ) : Word w)) m r
+ simpa only [Nat.cast_zero, add_zero] using step
+ | succ j =>
+ have mem : after m (eventLog ((r :: rs).take (j.val + 1))) =
+ after (after m r.events) (eventLog (rs.take j.val)) := by
+ simp only [List.take_succ_cons, eventLog, List.flatMap_cons, after, List.foldl_append]
+ simpa only [Fin.val_succ, mem, List.getElem_cons_succ, Nat.cast_add, Nat.cast_one,
+ add_assoc, add_comm (1 : Word w)] using ih j
+
+theorem Run.atSite (h : P.Run m rs) (i : Fin rs.length) :
+ P.At (i.val : Word w) (after m (eventLog (rs.take i.val))) rs[i.val] := by
+ simpa only [zero_add] using h.sites.atSite i
+
+theorem Run.atSite_next (h : P.Run m rs) (i : Fin rs.length) :
+ rs[i.val].result = some ((i.val + 1 : ℕ) : Word w) := by
+ simpa only [Nat.cast_add, Nat.cast_one] using Pass.next (h.atSite i)
+
+end Pass
+
+theorem Reference.length {xs : List (Pass w)} {m : Memory w} {rs : List (Report w)}
+ (h : Reference xs m rs) : rs.length = (xs.map Pass.count).sum := by
+ induction h with
+ | nil => rfl
+ | cons hr _ ih => simp only [List.length_append, hr.length, ih, List.map_cons, List.sum_cons]
+
+theorem Reference.branchPaths {xs : List (Pass w)} {m : Memory w} {rs : List (Report w)}
+ (h : Reference xs m rs) : BurstRAM.branchPaths rs = List.replicate (xs.map Pass.count).sum [] := by
+ induction h with
+ | nil => rfl
+ | @cons P tail m rs ss hr _ ih =>
+ rw [show BurstRAM.branchPaths (rs ++ ss) = BurstRAM.branchPaths rs ++ BurstRAM.branchPaths ss
+ from List.map_append, hr.branchPaths, ih]
+ simp only [List.map_cons, List.sum_cons, List.replicate_add]
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerRoute.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerRoute.lean
new file mode 100644
index 0000000000..96a8420f16
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerRoute.lean
@@ -0,0 +1,44 @@
+import OAI.Computability.VPVNP.PairTraversalControllerRead
+import OAI.Computability.VPVNP.PairTraversalControllerCode
+
+/-!
+# Natural-number decisions of the traversal dispatcher
+
+The finite-word tests choose the worker prescribed by the phase and the
+current layer. The layer-end digit selects the reset instruction, and the
+terminal phase-level selects acceptance.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM TraversalControllerInputs
+open scoped Fin.CommRing
+
+theorem Readback.route_eq {w : ℕ} {pub : Fin 11 → Word w} {m : Memory w} {L N p i : ℕ}
+ {rs : Fin R → Word w} (h : Readback pub m L N p i rs) (hL : 0 < L)
+ (phase : p ≤ 2 * L) (digit : i ≤ N) (fit : 2 * L * (N + 1) < 2 ^ w) :
+ Native.route rs =
+ if p < 2 * L then
+ if i < (siteCount pub m (p % L)).val then
+ if p < L then .role else if p % L = 0 then .leaf else .fiber
+ else .reset
+ else .accept := by
+ have limitFit := (Nat.le_mul_of_pos_right (2 * L) (Nat.succ_pos N)).trans_lt fit
+ have phaseFit := phase.trans_lt limitFit
+ have layerFit : L < 2 ^ w := (Nat.le_mul_of_pos_left L (by decide : 0 < 2)).trans_lt limitFit
+ have indexFit := (Nat.mod_lt p hL).trans layerFit
+ have pitchFit := (Nat.le_mul_of_pos_left (N + 1) (Nat.mul_pos (by decide) hL)).trans_lt fit
+ have siteFit := digit.trans_lt ((Nat.lt_succ_self N).trans pitchFit)
+ simp only [Native.route, h.phase, h.twice, h.site, h.count, h.levels, h.index, h.zero,
+ Fin.lt_def, Fin.ext_iff, Fin.val_natCast, Fin.val_zero, Nat.mod_eq_of_lt limitFit,
+ Nat.mod_eq_of_lt phaseFit, Nat.mod_eq_of_lt siteFit, Nat.mod_eq_of_lt layerFit, Nat.mod_eq_of_lt indexFit]
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerRun.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerRun.lean
new file mode 100644
index 0000000000..74212ecfe8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerRun.lean
@@ -0,0 +1,267 @@
+import OAI.Computability.VPVNP.PairTraversalControllerReference
+import OAI.Computability.VPVNP.PairTraversalControllerStep
+import OAI.Computability.VPVNP.LiveHeaderUnique
+
+/-!
+# Chronological execution of the traversal controller
+
+The active site calls advance the packed persistent ordinal by one. The
+extra call at the end of each layer resets the site digit and starts the
+next phase-level. The final sentinel accepts. Every call receives the
+post-memory of the preceding call, including across reset boundaries.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM TraversalControllerOrdinal TraversalControllerInputs
+open scoped Fin.CommRing
+
+variable {w : ℕ} {C : Type*}
+
+/-- A native interval of deterministic controller calls, with its complete
+post-memory, returned ordinal, and external probe total. -/
+structure Segment (P : BurstRAM.Program w C) (fuel : ℕ) (first last : Option (Word w))
+ (before final : Memory w) (calls probes : ℕ) (rs : List (Report w)) : Prop where
+ run : runSegment P fuel first before (List.replicate calls []) = some rs
+ endAt : endState first rs = last
+ memory : after before (eventLog rs) = final
+ length : rs.length = calls
+ cost : countProbes (eventLog rs) = probes
+
+private theorem replay_append (m : Memory w) (xs ys : List (Report w)) :
+ after m (eventLog (xs ++ ys)) = after (after m (eventLog xs)) (eventLog ys) := by
+ simp only [after, eventLog, List.flatMap_append, List.foldl_append]
+
+private theorem cost_append (xs ys : List (Report w)) :
+ countProbes (eventLog (xs ++ ys)) = countProbes (eventLog xs) + countProbes (eventLog ys) := by
+ simp only [eventLog, List.flatMap_append, countProbes_append]
+
+variable {P : BurstRAM.Program w C} {fuel : ℕ}
+
+private theorem Segment.empty (s : Option (Word w)) (m : Memory w) :
+ Segment P fuel s s m m 0 0 [] := ⟨rfl, rfl, rfl, rfl, rfl⟩
+
+private theorem Segment.one {s : Word w} {m : Memory w} {r : Report w}
+ (he : execute P fuel (P.start s) m [] = some r) :
+ Segment P fuel (some s) r.result m (after m r.events) 1 r.probes [r] := by
+ refine ⟨?_, rfl, ?_, rfl, ?_⟩
+ · simp only [List.replicate_succ, List.replicate_zero, runSegment, he, Option.map_some]
+ · simp only [eventLog, List.flatMap_cons, List.flatMap_nil, List.append_nil]
+ · simp only [eventLog, List.flatMap_cons, List.flatMap_nil, List.append_nil, Report.probes]
+
+private theorem Segment.join {s t u : Option (Word w)} {m n o : Memory w}
+ {a b c d : ℕ} {rs ss : List (Report w)}
+ (h : Segment P fuel s t m n a c rs) (k : Segment P fuel t u n o b d ss) :
+ Segment P fuel s u m o (a+b) (c+d) (rs++ss) := by
+ refine ⟨?_, ?_, ?_, ?_, ?_⟩
+ · rw [List.replicate_add, PrimedSchedule.runSegment_append, h.run]
+ simp only [Option.bind_some, h.endAt, h.memory, k.run, Option.map_some]
+ · rw [endState_append, h.endAt, k.endAt]
+ · rw [replay_append, h.memory, k.memory]
+ · rw [List.length_append, h.length, k.length]
+ · rw [cost_append, h.cost, k.cost]
+
+/-- Lift all active calls of a single layer, using the actual pre-memory
+of each reference report. A zero-site layer has the empty active segment. -/
+private theorem lift_sites (key : ℕ → Word w) (setup : ℕ) (m : Memory w) (refs : List (Report w))
+ (good : Report w → Prop) (active : ∀ i : Fin refs.length,
+ let entry := after m (eventLog (refs.take i.val))
+ ∃ r, execute P fuel (P.start (key i.val)) entry [] = some r ∧
+ r.result = some (key (i.val + 1)) ∧
+ after entry r.events = after entry refs[i].events ∧ r.probes = setup + refs[i].probes ∧
+ good r) :
+ ∃ out, Segment P fuel (some (key 0)) (some (key refs.length))
+ m (after m (eventLog refs)) refs.length (setup * refs.length + countProbes (eventLog refs))
+ out ∧ ∀ r ∈ out, good r := by
+ have partialRun (k : ℕ) (hk : k ≤ refs.length) :
+ ∃ rs, Segment P fuel (some (key 0)) (some (key k)) m
+ (after m (eventLog (refs.take k))) k (setup*k + countProbes (eventLog (refs.take k)))
+ rs ∧ ∀ r ∈ rs, good r := by
+ induction k with
+ | zero => exact ⟨[], Segment.empty (some (key 0)) m, by simp⟩
+ | succ k ih =>
+ let i : Fin refs.length := ⟨k, hk⟩
+ let entry := after m (eventLog (refs.take k))
+ obtain ⟨rs, h, earlier⟩ := ih (Nat.le_of_succ_le hk)
+ obtain ⟨r, he, hs, hm, hp, latest⟩ := active i
+ have one := Segment.one he
+ rw [hs, hm, hp] at one
+ have joined := h.join one
+ refine ⟨rs ++ [r], ?_, fun a ha => (List.mem_append.mp ha).elim (earlier a)
+ (fun h => List.mem_singleton.mp h ▸ latest)⟩
+ rw [List.take_succ_eq_append_getElem hk, replay_append, cost_append, Nat.mul_succ]
+ simpa only [i, Fin.getElem_fin, eventLog, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil, Report.probes, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm] using joined
+ simpa only [List.take_length] using partialRun refs.length le_rfl
+
+/-- At every prefix, the resident schedule still supplies the same layer
+counts and worker operands. -/
+def AtPrefixes (ready : Memory w → Prop) (m : Memory w) (refs : List (Report w)) : Prop :=
+ ∀ k ≤ refs.length, ready (after m (eventLog (refs.take k)))
+
+private theorem AtPrefixes.split {ready : Memory w → Prop} {m : Memory w} {xs ys : List (Report w)}
+ (h : AtPrefixes ready m (xs ++ ys)) :
+ AtPrefixes ready m xs ∧ AtPrefixes ready (after m (eventLog xs)) ys := by
+ constructor
+ · intro i hi
+ have hh := h i (by rw [List.length_append]; omega)
+ rwa [List.take_append_of_le_length hi] at hh
+ · intro j hj
+ have hh := h (xs.length+j) (by simpa using hj)
+ rwa [List.take_length_add_append, replay_append] at hh
+
+/-- Successful native execution and report conditions for every active site of this traversal
+pass from a ready memory. -/
+def ActiveCalls (P : BurstRAM.Program w C) (fuel N phase setup : ℕ) (job : Pass w)
+ (ready : Memory w → Prop) (sourceOK good : Report w → Prop) : Prop :=
+ ∀ (i : Fin job.count) (m : Memory w) (small : Report w), ready m →
+ job.At (i.val : Word w) m small → sourceOK small →
+ ∃ r, execute P fuel (P.start (pack N phase i.val : Word w)) m [] = some r ∧
+ r.result = some (pack N phase (i.val+1) : Word w) ∧
+ after m r.events = after m small.events ∧ r.probes = setup + small.probes ∧ good r
+
+/-- Native execution and report conditions for the closing call after the traversal pass has
+processed its last site. -/
+def ClosingCall (P : BurstRAM.Program w C) (fuel N phase setup : ℕ) (job : Pass w)
+ (ready : Memory w → Prop) (good : Report w → Prop) : Prop :=
+ ∀ (m : Memory w), ready m →
+ ∃ r, execute P fuel (P.start (pack N phase job.count : Word w)) m [] = some r ∧
+ r.result = some (pack N (phase+1) 0 : Word w) ∧ after m r.events = m ∧
+ r.probes = setup ∧ good r
+
+/-- Concatenate every physical pass with its own reset. The zero-size case
+still executes that reset. Each wrapped site has the same post-memory as its
+reference site, so the very next call reads the correct live data. -/
+theorem lift_passes {jobs : List (Pass w)} {m : Memory w} {refs : List (Report w)}
+ (ref : Reference jobs m refs) (N phase setup : ℕ) (ready : Memory w → Prop)
+ (stable : AtPrefixes ready m refs) (sourceOK good : Report w → Prop)
+ (sources : ∀ r ∈ refs, sourceOK r)
+ (active : ∀ j : Fin jobs.length,
+ ActiveCalls P fuel N (phase+j.val) setup jobs[j] ready sourceOK good)
+ (close : ∀ j : Fin jobs.length, ClosingCall P fuel N (phase+j.val) setup jobs[j] ready good) :
+ ∃ rs, Segment P fuel (some (pack N phase 0 : Word w))
+ (some (pack N (phase + jobs.length) 0 : Word w)) m (after m (eventLog refs))
+ (refs.length + jobs.length)
+ (setup * (refs.length + jobs.length) + countProbes (eventLog refs)) rs ∧
+ ∀ r ∈ rs, good r := by
+ induction ref generalizing phase with
+ | nil =>
+ exact ⟨[], Segment.empty (some (pack N phase 0 : Word w)) _, by simp⟩
+ | @cons job tail m localRefs restRefs run rest ih =>
+ let mid := after m (eventLog localRefs)
+ obtain ⟨here, later⟩ := stable.split
+ have act : ActiveCalls P fuel N phase setup job ready sourceOK good := active 0
+ have ending : ClosingCall P fuel N phase setup job ready good := close 0
+ obtain ⟨ss, hs, goodSites⟩ := lift_sites (P := P) (fuel := fuel)
+ (fun i => (pack N phase i : Word w))
+ setup m localRefs good (fun i =>
+ act ⟨i.val, i.isLt.trans_eq run.length⟩ _ _ (here _ i.isLt.le) (run.atSite i)
+ (sources _ (List.mem_append_left restRefs (List.getElem_mem i.isLt))))
+ have hm : ready mid := by simpa only [List.take_length, mid] using here _ le_rfl
+ obtain ⟨stop, stopped, returned, same, probes, goodStop⟩ := ending mid hm
+ have hstop := Segment.one stopped
+ rw [returned, same, probes, ← run.length] at hstop
+ have hpass := hs.join hstop
+ have inc (j : Fin tail.length) : phase + j.succ.val = phase + 1 + j.val := by
+ simp only [Fin.val_succ]; omega
+ obtain ⟨rr, hr, goodTail⟩ := ih (phase+1) later
+ (fun r h => sources r (List.mem_append_right localRefs h))
+ (fun j => inc j ▸ active j.succ) (fun j => inc j ▸ close j.succ)
+ have joined := hpass.join hr
+ refine ⟨ss ++ [stop] ++ rr, ?_, ?_⟩
+ rotate_left
+ · intro r h
+ rcases List.mem_append.mp h with before | last
+ · exact (List.mem_append.mp before).elim (goodSites r)
+ (fun h => List.mem_singleton.mp h ▸ goodStop)
+ · exact goodTail r last
+ rw [replay_append, cost_append, List.length_append, List.length_cons]
+ rw [show phase + (tail.length + 1) = phase + 1 + tail.length by omega,
+ show localRefs.length + restRefs.length + (tail.length + 1) =
+ localRefs.length + 1 + (restRefs.length + tail.length) by omega]
+ convert joined using 1
+ ring
+
+/-- A resident header supplies every actual worker lookup throughout the
+prefixes of the selected reference run. -/
+structure RunInputs (pub : Fin 11 → Word w) (L N : ℕ) (jobs : List (Pass w))
+ (m : Memory w) : Prop where
+ levels : (terminalField pub m 1).val = L
+ initial : (siteCount pub m 0).val = N
+ located : ∀ j : Fin jobs.length, jobs[j].Located pub m L j.val
+
+private theorem located_count {pub : Fin 11 → Word w} {m : Memory w} {L p : ℕ} {job : Pass w}
+ (h : job.Located pub m L p) : (siteCount pub m (p % L)).val = job.count := by
+ cases job with
+ | tag => exact h.2.2
+ | leaf | fiber => exact h.2.2.2
+
+/-- The single finite controller runs every reference burst in chronological
+order. The final report accepts, the external memory is exactly the native
+arena image, and the probe overhead counts every setup, reset and acceptance. -/
+theorem run_reference (pub : Fin 11 → Word w) (L N fuel : ℕ)
+ {jobs : List (Pass w)} {m : Memory w} {refs : List (Report w)}
+ (ref : Reference jobs m refs) (levels : jobs.length = 2 * L) (positive : 0 < L)
+ (fit : 2 * L * (N + 1) < 2 ^ w) (counts : ∀ j : Fin jobs.length, jobs[j].count ≤ N)
+ (clock : ∀ j : Fin jobs.length, setupLen + 7 + jobs[j].clock ≤ fuel)
+ (adminClock : setupLen + 8 ≤ fuel) (stable : AtPrefixes (RunInputs pub L N jobs) m refs) :
+ let calls := refs.length + jobs.length + 1
+ ∃ reports, Segment (Native.machine pub).program fuel (some 0) none m
+ (after m (eventLog refs)) calls (257 * calls + countProbes (eventLog refs)) reports := by
+ let P := (Native.machine pub).program
+ let ready := RunInputs pub L N jobs
+ have phase (j : Fin jobs.length) : j.val < 2 * L := j.isLt.trans_eq levels
+ have active (j : Fin jobs.length) :
+ ActiveCalls P fuel N (0 + j.val) 257 jobs[j] ready (fun _ => True) (fun _ => True) := by
+ rw [Nat.zero_add]
+ intro i entry small ok h _
+ obtain ⟨pre, admin, call⟩ := active_step pub entry L N j.val i.val ok.levels ok.initial
+ positive (phase j) (i.isLt.le.trans (counts j)) fit _ (ok.located j) i.isLt small h
+ refine ⟨_, call fuel (clock j), rfl, ?_, ?_, trivial⟩
+ · change after entry (pre ++ small.events) = _
+ rw [show after entry (pre ++ small.events) = after (after entry pre) small.events from
+ List.foldl_append, admin.replay]
+ · exact (countProbes_append pre small.events).trans (congrArg (· + small.probes) admin.probes)
+ have reset (j : Fin jobs.length) : ClosingCall P fuel N (0 + j.val) 257 jobs[j] ready
+ (fun _ => True) := by
+ rw [Nat.zero_add]
+ intro entry ok
+ obtain ⟨pre, admin, call⟩ := reset_step pub entry L N j.val jobs[j].count ok.levels ok.initial
+ positive (phase j) (counts j) fit (located_count (ok.located j)).symm
+ exact ⟨_, call fuel adminClock, rfl, admin.replay entry, admin.probes, trivial⟩
+ obtain ⟨rs, stages, _⟩ := lift_passes ref N 0 257 ready stable (fun _ => True) (fun _ => True)
+ (fun _ _ => trivial) active reset
+ let final := after m (eventLog refs)
+ have lastReady : ready final := by simpa only [List.take_length, final] using stable _ le_rfl
+ obtain ⟨pre, admin, stop⟩ := stop_step pub final L N lastReady.levels lastReady.initial
+ positive fit
+ have sentinel := Segment.one (stop fuel adminClock)
+ change Segment P fuel (some (pack N (2 * L) 0 : Word w)) none final
+ (after final pre) 1 (countProbes pre) [⟨pre, none⟩] at sentinel
+ rw [admin.replay, admin.probes, ← levels] at sentinel
+ rw [Nat.zero_add] at stages
+ have joined := stages.join sentinel
+ refine ⟨rs ++ [⟨pre, none⟩], ?_⟩
+ have hzero : (pack N 0 0 : Word w) = 0 := by simp [pack]
+ rw [hzero] at joined
+ convert joined using 1
+ ring
+
+/-- Every accepting tape for this deterministic controller gives the same
+reports as the chronological run, including the reset and acceptance calls. -/
+theorem Segment.accepted_unique {s : Option (Word w)} {m final : Memory w}
+ {calls probes : ℕ} {rs : List (Report w)} (h : Segment P fuel s none m final calls probes rs)
+ {bits : List (List Bool)} {out : List (Report w)}
+ (actual : runSegment P fuel s m bits = some out) (done : endState s out = none) :
+ bits = List.replicate calls [] ∧ out = rs :=
+ accepted_empty_unique h.run h.endAt actual done
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerRunReads.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerRunReads.lean
new file mode 100644
index 0000000000..9dfb821d95
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerRunReads.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.PairTraversalControllerRun
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-!
+# Read footprint of a complete traversal-controller execution
+
+At each active ordinal the wrapper reads only its operand bank and the
+words read by the corresponding reference report. The resets and the
+final acceptance read only their operand banks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM CompressorRecords TraversalControllerOrdinal TraversalControllerInputs
+open scoped Fin.CommRing
+open private Segment.one Segment.join located_count
+ from OAI.Computability.VPVNP.PairTraversalControllerRun
+
+variable {w : ℕ}
+
+/-- Transfer the read footprint of the reference body and every live
+register setup to the unique accepting native execution. -/
+theorem Segment.reads (pub : Fin 11 → Word w) (L N fuel : ℕ) (data : ℕ → Prop)
+ {jobs : List (Pass w)} {m : Memory w} {refs out : List (Report w)}
+ {calls probes : ℕ} {final : Memory w}
+ (completed : Segment (Native.machine pub).program fuel (some 0) none m final calls probes out)
+ (ref : Reference jobs m refs) (levels : jobs.length = 2 * L) (positive : 0 < L)
+ (fit : 2 * L * (N + 1) < 2 ^ w) (counts : ∀ j : Fin jobs.length, jobs[j].count ≤ N)
+ (clock : ∀ j : Fin jobs.length, setupLen + 7 + jobs[j].clock ≤ fuel)
+ (adminClock : setupLen + 8 ≤ fuel) (stable : AtPrefixes (RunInputs pub L N jobs) m refs)
+ (refReads : SourceTransport.Reads data (eventLog refs))
+ (setupReads : ∀ q ≤ refs.length, ∀ s regs, SourceTransport.Reads data
+ (Native.prefixTrace pub s (after m (eventLog (refs.take q))) regs)) :
+ SourceTransport.Reads data (eventLog out) := by
+ let P := (Native.machine pub).program
+ let good (r : Report w) := SourceTransport.Reads data r.events
+ let ready (mem : Memory w) := RunInputs pub L N jobs mem ∧
+ ∀ s regs, SourceTransport.Reads data (Native.prefixTrace pub s mem regs)
+ have allSources (r : Report w) (hr : r ∈ refs) : good r :=
+ fun a v ha => refReads a v (List.mem_flatMap.mpr ⟨r, hr, ha⟩)
+ have allReady : AtPrefixes ready m refs := fun q hq => ⟨stable q hq, setupReads q hq⟩
+ have phase (j : Fin jobs.length) : j.val < 2 * L := j.isLt.trans_eq levels
+ have active (j : Fin jobs.length) :
+ ActiveCalls P fuel N (0 + j.val) 257 jobs[j] ready good good := by
+ rw [Nat.zero_add]
+ intro i entry small ok source smallReads
+ obtain ⟨pre, admin, ⟨regs, trace⟩, call⟩ := active_step_trace pub entry L N j.val i.val
+ ok.1.levels ok.1.initial positive (phase j) (i.isLt.le.trans (counts j)) fit _
+ (ok.1.located j) i.isLt small source
+ refine ⟨_, call fuel (clock j), rfl, ?_, ?_, ?_⟩
+ · change after entry (pre ++ small.events) = _
+ rw [show after entry (pre ++ small.events) = after (after entry pre) small.events from
+ List.foldl_append, admin.replay]
+ · exact (countProbes_append pre small.events).trans (congrArg (· + small.probes) admin.probes)
+ · intro a v h
+ exact (List.mem_append.mp h).elim
+ (fun h => ok.2 _ regs a v (trace ▸ h)) (smallReads a v)
+ have reset (j : Fin jobs.length) : ClosingCall P fuel N (0 + j.val) 257 jobs[j] ready good := by
+ rw [Nat.zero_add]
+ intro entry ok
+ obtain ⟨pre, admin, ⟨regs, trace⟩, call⟩ := reset_step_trace pub entry L N j.val jobs[j].count
+ ok.1.levels ok.1.initial positive (phase j) (counts j) fit
+ (located_count (ok.1.located j)).symm
+ exact ⟨_, call fuel adminClock, rfl, admin.replay entry, admin.probes, trace ▸ ok.2 _ regs⟩
+ obtain ⟨rs, stages, passed⟩ := lift_passes ref N 0 257 ready allReady good good allSources
+ active reset
+ let last := after m (eventLog refs)
+ have ok : ready last := by simpa only [List.take_length, last] using allReady _ le_rfl
+ obtain ⟨pre, admin, ⟨regs, trace⟩, stop⟩ := stop_step_trace pub last L N ok.1.levels ok.1.initial
+ positive fit
+ let sentinel : Report w := ⟨pre, none⟩
+ have endReads : good sentinel := by
+ change SourceTransport.Reads data pre
+ rw [trace]
+ exact ok.2 _ regs
+ have accept : Segment P fuel (some (pack N (2 * L) 0 : Word w)) none last (after last pre)
+ 1 sentinel.probes [sentinel] := Segment.one (stop fuel adminClock)
+ rw [← levels] at accept
+ rw [Nat.zero_add] at stages
+ have complete := Segment.join stages accept
+ rw [show (pack N 0 0 : Word w) = 0 by simp [pack]] at complete
+ obtain ⟨_, eqn⟩ := complete.accepted_unique completed.run completed.endAt
+ rw [eqn]
+ intro a v h
+ obtain ⟨r, hr, hcell⟩ := List.mem_flatMap.mp h
+ rcases List.mem_append.mp hr with earlier | final
+ · exact passed r earlier a v hcell
+ · obtain rfl := List.mem_singleton.mp final
+ exact endReads a v hcell
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerSelectedRun.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerSelectedRun.lean
new file mode 100644
index 0000000000..2ca29257b8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerSelectedRun.lean
@@ -0,0 +1,257 @@
+import OAI.Computability.VPVNP.PairTraversalControllerRunReads
+import OAI.Computability.VPVNP.PairTraversalControllerSetupReads
+import OAI.Computability.VPVNP.PairTraversalReferenceReads
+import OAI.Computability.VPVNP.PairTraversalControllerLocation
+import OAI.Computability.VPVNP.PairTraversalReferenceFootprint
+import OAI.Computability.VPVNP.PairArenaBudget
+import OAI.Computability.VPVNP.CompressorOrdinalProgress
+
+/-!
+# Native traversal-controller execution on the selected compression branch
+
+The terminal header points to the completed placement directories. These
+physical inputs suffice for one fixed native controller to write the whole
+arena, preserve the shared-bit interval, and accept on a unique tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM Compression CompressorRecords LocalHistory TraversalRows DirectoryRun
+open TraversalRoles TraversalControllerInputs
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- All controller bursts, including the largest fiber scan, fit this bound. -/
+def callFuel (cap : ℕ) : ℕ := setupLen + 7 + (7 * cap + 25)
+
+private theorem tags_info (offset cap base : ℕ) (ls : List TaggedLayer) :
+ (tagJobs w offset cap base ls).map Pass.count = ls.map (fun l => l.layer.count) ∧
+ ∀ t ∈ tagJobs w offset cap base ls, t.clock = 12 := by
+ induction ls generalizing base with
+ | nil => exact ⟨rfl, by simp [tagJobs]⟩
+ | cons l ls ih =>
+ obtain ⟨counts, clocks⟩ := ih (endPos cap base l.layer)
+ refine ⟨congrArg (List.cons l.layer.count) counts, ?_⟩
+ intro t ht
+ exact (List.mem_cons.mp ht).elim (fun h => h ▸ rfl) (clocks t)
+
+private theorem fibers_info (cap previous base : ℕ) (ls : List (Fiber w)) :
+ (fiberWorkers cap previous base ls).map (Pass.count ∘ rowJob) =
+ ls.map (fun l => l.1.layer.count) ∧
+ ∀ t ∈ fiberWorkers cap previous base ls, (rowJob t).clock = 7 * cap + 25 := by
+ induction ls generalizing previous base with
+ | nil => exact ⟨rfl, by simp [fiberWorkers]⟩
+ | cons l ls ih =>
+ obtain ⟨counts, clocks⟩ := ih base (endPos cap base l.1.layer)
+ refine ⟨congrArg (List.cons l.1.layer.count) counts, ?_⟩
+ intro t ht
+ exact (List.mem_cons.mp ht).elim (fun h => h ▸ rfl) (clocks t)
+
+variable {k A : Type*} [Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ} (T : ℕ)
+variable (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices) (base : ℕ) (raw : Memory w)
+variable (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] raw base)
+
+private theorem selected_jobs_info :
+ let tags := selected B f hf T hT X z
+ let rows := selectedJobs B f hf T hT X z base raw ds
+ (rows.map (Pass.count ∘ rowJob)) = tags.map (fun l => l.layer.count) ∧
+ ∀ t ∈ rows, (rowJob t).clock ≤ 7 * B.recordLimit + 25 := by
+ let cap := B.recordLimit
+ let ls := levelFibers (executeLevels B f hf T hT X z) ds
+ let old := leafLayer (siteOrder X)
+ obtain ⟨counts, clocks⟩ := fibers_info cap base (endPos cap base old) ls
+ rw [selectedJobs_eq]
+ constructor
+ · change old.count :: (fiberWorkers cap base (endPos cap base old) ls).map _ = _
+ rw [counts]
+ have h := congrArg (List.map (fun l : TaggedLayer => l.layer.count)) (levelFibers_tags _ ds)
+ exact congrArg (List.cons old.count) (by simpa only [List.map_map, Function.comp_def] using h)
+ · intro t ht
+ rcases List.mem_cons.mp ht with rfl | h
+ · change 14 ≤ 7 * cap + 25; omega
+ · exact (clocks t h).le
+
+open private probes_le from OAI.Computability.VPVNP.PairArenaBudget
+
+/-- The selected raw scans and resident header instantiate the complete native
+controller. Its charges include both resets at every level and the sentinel. -/
+theorem selected_run_with_reads (pub : Fin 11 → Word w) (F H first pitch : ℕ)
+ (d : Resident pub raw H first pitch (words B.recordLimit (selectedLayers B f hf T hT X z) + F)
+ B.recordLimit base ⟨leafLayer (siteOrder X), .cursor⟩
+ (levelFibers (executeLevels B f hf T hT X z) ds))
+ (headersBefore : ∀ j ≤ (executeLevels B f hf T hT X z).length, first + j * pitch + 28 ≤ base)
+ (belowHeader : base + 2 * words B.recordLimit (selectedLayers B f hf T hT X z) + F ≤ H)
+ (ordinalFit : 2 * (selected B f hf T hT X z).length * (X.positions + 1) < 2 ^ w) :
+ let cap := B.recordLimit
+ let ls := selectedLayers B f hf T hT X z
+ let size := words cap ls
+ let off := size + F
+ let tags := selected B f hf T hT X z
+ let rowJobs := selectedJobs B f hf T hT X z base raw ds
+ let calls := 2 * (ls.map Layer.count).sum + 2 * tags.length + 1
+ let arena := build cap base base ls (writeTags off cap base tags raw)
+ let program := (Native.machine pub).program
+ ∃ ts rs out, RolePasses off cap base tags raw ts ∧
+ DirectoryRun.Segments rowJobs (after raw (eventLog ts)) rs ∧
+ Segment program (callFuel cap) (some 0) none raw arena calls
+ (257 * calls + countProbes (eventLog (ts ++ rs))) out ∧
+ RAMBuckets.cost Report.probes out ≤ (2 * cap + 1294) *
+ (((S.steps + 1) * T + 1) * X.positions) ∧
+ (∀ r ∈ out, r.probes ≤ r.events.length ∧ r.events.length < callFuel cap) ∧
+ Reads w (after raw (eventLog out)) off cap base tags ∧
+ AllRows w (after raw (eventLog out)) cap base base ls ∧
+ (∀ x < base, after raw (eventLog out) x = raw x) ∧
+ (∀ i < F, after raw (eventLog out) (base + size + i) = raw (base + size + i)) ∧
+ SourceTransport.Reads (TerminalLink.workerCell (TerminalLink.header pub)) (eventLog out) ∧
+ ∀ (bits : List (List Bool)) (other : List (Report w)),
+ runSegment program (callFuel cap) (some 0) raw bits = some other →
+ endState (some 0) other = none → bits = List.replicate calls [] ∧ other = out := by
+ intro cap ls size off tags rowJobs calls arena program
+ let jobs := tagJobs w off cap base tags ++ rowJobs.map rowJob
+ let visits := ((S.steps+1)*T+1) * X.positions
+ change base + 2 * size + F ≤ H at belowHeader
+ have hh : H < 2^w := by have := d.headerFits; omega
+ have fit : base + 2 * size + F < 2 ^ w := belowHeader.trans_lt hh
+ obtain ⟨ts, rs, ht, hr, image, tagsOK, rowsOK, bitsOK, refCalls, refProbes⟩ :=
+ native_arena B f hf T hT X z base F raw ds fit
+ have typed : Reference jobs raw (ts ++ rs) := Reference.of_passes ht hr
+ have layers : tags.map TaggedLayer.layer = ls := selected_layers B f hf T hT X z
+ have hsize : tagWords cap tags = size := congrArg (words cap) layers
+ have below : off + base + tagWords cap tags ≤ H := by rw [hsize]; dsimp only [off]; omega
+ have headers := selected_reference_schedule B f hf T hT X z base raw ds d headersBefore
+ ts rs ht hr below
+ have schedule : Schedule pub raw off cap base tags rowJobs := (headers 0 (Nat.zero_le _)).1
+ have phases : jobs.length = 2 * tags.length := by simp [jobs, schedule.jobs_length, two_mul]
+ have positive : 0 < tags.length := Nat.succ_pos _
+ have capCount (j : Fin jobs.length) : jobs[j].count ≤ X.positions := by
+ let layer : Fin tags.length := ⟨j.val % tags.length, Nat.mod_lt _ positive⟩
+ have hc := (schedule.lookup layer).1
+ rw [show jobs[j].count = _ from schedule.pass_count j, hc]
+ apply selected_layer_count_le B f hf T hT X z
+ change tags[layer].layer ∈ ls
+ rw [← layers]
+ exact List.mem_map_of_mem (List.getElem_mem layer.isLt)
+ obtain ⟨tagCounts, tagClock⟩ := tags_info (w := w) off cap base tags
+ obtain ⟨rowCounts, rowClock⟩ := selected_jobs_info B f hf T hT X z base raw ds
+ have clock (j : Fin jobs.length) : setupLen + 7 + jobs[j].clock ≤ callFuel cap := by
+ apply Nat.add_le_add_left
+ have hj := List.getElem_mem (l := jobs) j.isLt
+ rcases List.mem_append.mp hj with h | h
+ · exact (tagClock _ h).trans_le (by omega)
+ · obtain ⟨row, hw, he⟩ := List.mem_map.mp h
+ exact he ▸ rowClock row hw
+ have stable : AtPrefixes (RunInputs pub tags.length X.positions jobs) raw (ts ++ rs) := by
+ intro q hq
+ obtain ⟨sched, site⟩ := headers q hq
+ exact ⟨sched.total, site, sched.located⟩
+ obtain ⟨out, run⟩ := run_reference pub tags.length X.positions (callFuel cap) typed phases
+ positive
+ ordinalFit capCount clock (by unfold callFuel; omega) stable
+ have rawReads := selected_reference_reads B f hf T hT X z base raw ds off ts rs ht hr
+ (below.trans_lt hh)
+ have header : TerminalLink.header pub = (H : Word w) := d.header
+ have h32 := d.headerFits
+ have headVal : (TerminalLink.header pub).val = H := by
+ rw [header, Fin.val_natCast, Nat.mod_eq_of_lt hh]
+ have lastVal : (TerminalLink.header pub + 31).val = H + 31 := by
+ rw [header, show (31 : Word w) = ((31 : ℕ) : Word w) from rfl, ← Nat.cast_add,
+ Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ have bodyReads : SourceTransport.Reads (TerminalLink.workerCell (TerminalLink.header pub))
+ (eventLog (ts ++ rs)) := by
+ intro a v read
+ have := rawReads a v read
+ simp only [TerminalLink.workerCell, headVal, lastVal]
+ omega
+ have readFrame := Segment.reads pub tags.length X.positions (callFuel cap) _ run typed phases
+ positive ordinalFit capCount clock (by unfold callFuel; omega) stable bodyReads
+ (selected_prefix_setup_reads B f hf T hT X z base raw ds d headersBefore ts rs ht hr below)
+ have counts : (tags.map (fun l => l.layer.count)).sum = (ls.map Layer.count).sum := by
+ rw [← layers, List.map_map]
+ rfl
+ have num : (ts ++ rs).length = 2 * (ls.map Layer.count).sum := by
+ rw [typed.length]
+ change ((tagJobs w off cap base tags ++ rowJobs.map rowJob).map Pass.count).sum = _
+ rw [List.map_append, List.sum_append, tagCounts, List.map_map, rowCounts, counts, two_mul]
+ have hc : (ts ++ rs).length + jobs.length + 1 = calls := by rw [num, phases]
+ change after raw (eventLog (ts ++ rs)) = arena at image
+ rw [hc, image] at run
+ have rawPreserved : ∀ x < base, arena x = raw x := by
+ intro x hx
+ exact (build_outside ls cap base base _ x (Or.inl hx)).trans
+ (write_tags_outside off cap base tags raw x (Or.inl (hx.trans_le (Nat.le_add_left _ _))))
+ refine ⟨ts, rs, out, ht, hr, run, ?_, ?_, ?_, ?_, ?_, ?_, readFrame,
+ fun _ _ => run.accepted_unique⟩
+ · rw [SourceOnline.packet_cost, run.length, run.cost]
+ have hL : tags.length ≤ (S.steps + 1) * T + 1 := by
+ simp only [tags, selected, List.length_cons, List.length_map]
+ exact Nat.succ_le_succ (executeLevels_length B f hf T hT X z)
+ have hl : tags.length ≤ visits := hL.trans (Nat.le_mul_of_pos_right _ X.positions_pos)
+ have hv : 1 ≤ visits := (Nat.succ_pos _).trans_le (Nat.le_mul_of_pos_right _ X.positions_pos)
+ have hcBound : calls ≤ 5 * visits := by
+ change ts.length + rs.length ≤ 2 * visits at refCalls
+ rw [← hc, List.length_append, phases]; omega
+ change countProbes (eventLog (ts++rs)) ≤ (2*cap+4)*visits at refProbes
+ calc _ ≤ 5*visits + (257*(5*visits) + (2*cap+4)*visits) :=
+ Nat.add_le_add hcBound (Nat.add_le_add (Nat.mul_le_mul_left _ hcBound) refProbes)
+ _ = _ := by change _ = (2*cap+1294)*visits; ring
+ · intro r hm
+ exact ⟨probes_le _, localSegment_event_bound ((runSegment_iff ..).mp run.run).1 _ hm⟩
+ · rw [run.memory, ← image]
+ exact tagsOK
+ · rw [run.memory, ← image]
+ exact rowsOK
+ · rw [run.memory]
+ exact rawPreserved
+ · rw [run.memory, ← image]
+ exact bitsOK
+
+/-- The selected raw scans and resident header instantiate the complete native
+controller. Its charges include both resets at every level and the sentinel. -/
+theorem selected_run (pub : Fin 11 → Word w) (F H first pitch : ℕ)
+ (d : Resident pub raw H first pitch (words B.recordLimit (selectedLayers B f hf T hT X z) + F)
+ B.recordLimit base ⟨leafLayer (siteOrder X), .cursor⟩
+ (levelFibers (executeLevels B f hf T hT X z) ds))
+ (headersBefore : ∀ j ≤ (executeLevels B f hf T hT X z).length, first + j * pitch + 28 ≤ base)
+ (belowHeader : base + 2 * words B.recordLimit (selectedLayers B f hf T hT X z) + F ≤ H)
+ (ordinalFit : 2 * (selected B f hf T hT X z).length * (X.positions + 1) < 2 ^ w) :
+ let cap := B.recordLimit
+ let ls := selectedLayers B f hf T hT X z
+ let size := words cap ls
+ let off := size + F
+ let tags := selected B f hf T hT X z
+ let rowJobs := selectedJobs B f hf T hT X z base raw ds
+ let calls := 2 * (ls.map Layer.count).sum + 2 * tags.length + 1
+ let arena := build cap base base ls (writeTags off cap base tags raw)
+ let program := (Native.machine pub).program
+ ∃ ts rs out, RolePasses off cap base tags raw ts ∧
+ DirectoryRun.Segments rowJobs (after raw (eventLog ts)) rs ∧
+ Segment program (callFuel cap) (some 0) none raw arena calls
+ (257 * calls + countProbes (eventLog (ts ++ rs))) out ∧
+ RAMBuckets.cost Report.probes out ≤ (2 * cap + 1294) *
+ (((S.steps + 1) * T + 1) * X.positions) ∧
+ (∀ r ∈ out, r.probes ≤ r.events.length ∧ r.events.length < callFuel cap) ∧
+ Reads w (after raw (eventLog out)) off cap base tags ∧
+ AllRows w (after raw (eventLog out)) cap base base ls ∧
+ (∀ x < base, after raw (eventLog out) x = raw x) ∧
+ (∀ i < F, after raw (eventLog out) (base + size + i) = raw (base + size + i)) ∧
+ ∀ (bits : List (List Bool)) (other : List (Report w)),
+ runSegment program (callFuel cap) (some 0) raw bits = some other →
+ endState (some 0) other = none → bits = List.replicate calls [] ∧ other = out := by
+ obtain ⟨ts, rs, out, ht, hr, seg, cost, per, roles, rows, rawOK, bitsOK, _, unique⟩ :=
+ selected_run_with_reads B f hf T hT X z base raw ds pub F H first pitch d headersBefore
+ belowHeader ordinalFit
+ exact ⟨ts, rs, out, ht, hr, seg, cost, per, roles, rows, rawOK, bitsOK, unique⟩
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerSetupReads.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerSetupReads.lean
new file mode 100644
index 0000000000..9c7c4a54c5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerSetupReads.lean
@@ -0,0 +1,189 @@
+import OAI.Computability.VPVNP.CompressorRegisterSetupTrace
+import OAI.Computability.VPVNP.PairSimulationTerminalSplice
+import OAI.Computability.VPVNP.PairTraversalControllerOrdinal
+import OAI.Computability.VPVNP.PairTraversalReferenceFootprint
+import OAI.Computability.VPVNP.PairTraversalControllerPrepare
+
+/-!
+# External addresses read by the native traversal setup
+
+The register bank loads six terminal scalars and seven kinds of level scalar.
+Even when the persistent state is the final sentinel, taking its phase-level
+modulo the resident level count selects an allocated level. Its predecessor
+saturates at zero. The entry and dispatch ticks introduce no further reads.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM PrivateRAM CompressorRecords PhaseRecipe TraversalControllerInputs TraversalRoles
+open scoped Fin.CommRing
+
+variable {w : ℕ} {pub : Fin 11 → Word w} {m : Memory w}
+variable {H first stride offset cap base : ℕ} {old : TaggedLayer} {ls : List (Fiber w)}
+
+/-- Scalar fields loaded from the initial, current or preceding level. -/
+def levelScalars : Finset ℕ := {14, 21, 22, 24, 25, 26, 27}
+
+private theorem levelScalar_lt {f : ℕ} (hf : f ∈ levelScalars) : f < 28 := by
+ simp only [levelScalars, Finset.mem_insert, Finset.mem_singleton] at hf
+ omega
+
+private theorem terminalScalar_bounds {f : ℕ} (hf : f ∈ terminalScalars) : 0 < f ∧ f < 31 := by
+ simp only [terminalScalars, Finset.mem_insert, Finset.mem_singleton] at hf
+ omega
+
+/-- The resident positive level count confines all formula loads, including
+those issued while computing another load's address, to the designated scalars. -/
+theorem formulas_reads (d : Resident pub m H first stride offset cap base old ls)
+ (data : ℕ → Prop) (terms : ∀ f ∈ terminalScalars, data (H + f))
+ (fields : ∀ j ≤ ls.length, ∀ f ∈ levelScalars, data (first + j * stride + f)) (s : Word w)
+ (t : Fin 18) : (formulas t).ReadsFrom data (recipePub pub) s m := by
+ let safe := Expr.ReadsFrom data (recipePub pub) s m
+ let ev := Expr.eval (recipePub pub) s m
+ have terminalSafe : safe terminal := by
+ simp [safe, terminal, Expr.add, Expr.mul, Expr.sub, Expr.ReadsFrom]
+ have termSafe (f : ℕ) (hf : f ∈ terminalScalars) : safe (term f) := by
+ refine ⟨⟨terminalSafe, trivial⟩, ?_⟩
+ change data (terminalHead pub + (f : Word w)).val
+ rw [d.header, ← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt]
+ · exact terms f hf
+ · have := terminalScalar_bounds hf
+ have := d.headerFits
+ omega
+ have levelSafe (x : Expr) (j : ℕ) (read : safe x) (val : ev x = (j : Word w))
+ (hj : j ≤ ls.length) (f : ℕ) (hf : f ∈ levelScalars) : safe (level x f) := by
+ refine ⟨⟨⟨termSafe 16 (by decide), read, termSafe 17 (by decide)⟩, trivial⟩, ?_⟩
+ change data (terminalField pub m 16 + ev x * terminalField pub m 17 + (f : Word w)).val
+ rw [val, terminal_read d 16 (by decide), terminal_read d 17 (by decide), d.firstHead,
+ d.levelPitch, ← Nat.cast_mul, ← Nat.cast_add, ← Nat.cast_add, Fin.val_natCast,
+ Nat.mod_eq_of_lt]
+ · exact fields j hj f hf
+ · exact (Nat.add_lt_add_left (levelScalar_lt hf) _).trans_le (d.levelFits j hj)
+ have initialField := levelSafe (.lit 0) 0 trivial rfl (Nat.zero_le _)
+ have layers : safe levels := termSafe 1 (by decide)
+ have sites : safe initialSites :=
+ ⟨initialField 21 (by decide), ⟨trivial, layers⟩,
+ termSafe 7 (by decide), initialField 21 (by decide)⟩
+ have radix : safe pitch := ⟨sites, trivial⟩
+ have phase : safe phaseLevel := ⟨trivial, radix⟩
+ have current : safe index := ⟨phase, layers⟩
+ have pos : safe positiveIndex := ⟨current, current⟩
+ have predSafe : safe previous := ⟨current, pos⟩
+ let L := ls.length + 1
+ let p := (ev phaseLevel).val
+ have hL : (ev levels).val = L :=
+ (congrArg Fin.val (terminal_read d 1 (by decide))).trans d.levels
+ have heL : ev levels = (L : Word w) := hL ▸ (Fin.ofNat_val_eq_self _).symm
+ have heP : ev phaseLevel = (p : Word w) := (Fin.ofNat_val_eq_self _).symm
+ have positive : 0 < L := Nat.succ_pos _
+ have fit := hL ▸ (ev levels).isLt
+ obtain ⟨idx, _, pred⟩ := TraversalControllerOrdinal.index_words positive fit (ev phaseLevel).isLt
+ have currentVal : ev index = ((p % L : ℕ) : Word w) := by
+ change BinaryOp.mod.eval (ev phaseLevel) (ev levels) = _
+ rw [heP, heL]
+ exact idx
+ have predVal : ev previous = ((p % L - 1 : ℕ) : Word w) := by
+ change BinaryOp.sub.eval (BinaryOp.mod.eval (ev phaseLevel) (ev levels))
+ (BinaryOp.div.eval (BinaryOp.mod.eval (ev phaseLevel) (ev levels))
+ (BinaryOp.mod.eval (ev phaseLevel) (ev levels))) = _
+ rw [heP, heL]
+ exact pred
+ have bound : p % L ≤ ls.length := Nat.lt_succ_iff.mp (Nat.mod_lt p positive)
+ have currentField := levelSafe index _ current currentVal bound
+ have predField := levelSafe previous _ predSafe predVal ((Nat.sub_le ..).trans bound)
+ have num : safe count := ⟨sites, pos, predField 22 (by decide), sites⟩
+ have siteSafe : safe site := ⟨trivial, radix⟩
+ have twice : safe (levels.add levels) := ⟨layers, layers⟩
+ have next : safe (Expr.state.add (.lit 1)) := ⟨trivial, trivial⟩
+ have reset : safe ((phaseLevel.add (.lit 1)).mul pitch) := ⟨⟨phase, trivial⟩, radix⟩
+ fin_cases t <;> first
+ | exact siteSafe | exact phase | exact layers | exact twice | exact num | exact current
+ | exact next | exact reset | trivial
+ | exact termSafe _ (by decide) | exact initialField _ (by decide)
+ | exact currentField _ (by decide) | exact predField _ (by decide)
+
+/-- The two terminal control cells are excluded when each physical level
+header precedes the terminal header. The conclusion holds for every state word. -/
+theorem formulas_worker_reads (d : Resident pub m H first stride offset cap base old ls)
+ (beforeH : ∀ j ≤ ls.length, first + j * stride + 28 ≤ H) (s : Word w) (t : Fin 18) :
+ (formulas t).ReadsFrom (TerminalLink.workerCell (TerminalLink.header pub))
+ (recipePub pub) s m := by
+ have header : TerminalLink.header pub = (H : Word w) := d.header
+ have fit := d.headerFits
+ have hval : (TerminalLink.header pub).val = H := by
+ rw [header, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ have last : (TerminalLink.header pub + 31).val = H + 31 := by
+ rw [header, show (31 : Word w) = ((31 : ℕ) : Word w) from rfl, ← Nat.cast_add, Fin.val_natCast,
+ Nat.mod_eq_of_lt (by omega)]
+ apply formulas_reads d
+ · intro f hf
+ have := terminalScalar_bounds hf
+ simp only [TerminalLink.workerCell, hval, last]
+ omega
+ · intro j hj f hf
+ have := beforeH j hj
+ have := levelScalar_lt hf
+ simp only [TerminalLink.workerCell, hval, last]
+ omega
+
+/-- All reads in the actual native setup and guard trace avoid both terminal
+control cells. The worker that follows the setup uses the resulting bank. -/
+theorem Native.prefixTrace_reads (d : Resident pub m H first stride offset cap base old ls)
+ (beforeH : ∀ j ≤ ls.length, first + j * stride + 28 ≤ H)
+ (s : Word w) (rs : PrimedStackRAM.Regs w R) :
+ SourceTransport.Reads (TerminalLink.workerCell (TerminalLink.header pub))
+ (Native.prefixTrace pub s m rs) := by
+ have safe := RegisterSetup.lines_reads formulas _ (recipePub pub) s m
+ (formulas_worker_reads d beforeH s) ((Native.loaded pub s).reg ∘ vm)
+ intro a v read
+ simp only [Native.prefixTrace, List.mem_append, List.mem_cons, List.not_mem_nil, reduceCtorEq,
+ false_or, List.mem_replicate] at read
+ exact safe a v (by simpa using read)
+
+open Compression LocalHistory TraversalRows DirectoryRun
+
+variable {k A : Type*} [Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ} (T : ℕ)
+variable (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices) (base : ℕ) (raw : Memory w)
+variable (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] raw base)
+
+/-- Every native setup issued on the selected reference run reads worker
+cells, also after any prefix of tag and row writes. -/
+theorem selected_prefix_setup_reads
+ (d : Resident pub raw H first stride offset B.recordLimit base
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers (executeLevels B f hf T hT X z) ds))
+ (headersBefore : ∀ j ≤ (executeLevels B f hf T hT X z).length, first + j * stride + 28 ≤ base)
+ (ts rs : List (Report w))
+ (tags : RolePasses offset B.recordLimit base (selected B f hf T hT X z) raw ts)
+ (rows : Segments (selectedJobs B f hf T hT X z base raw ds) (after raw (eventLog ts)) rs)
+ (belowHeader : offset + base + tagWords B.recordLimit (selected B f hf T hT X z) ≤ H) :
+ ∀ q ≤ (ts ++ rs).length, ∀ s regs,
+ SourceTransport.Reads (TerminalLink.workerCell (TerminalLink.header pub))
+ (Native.prefixTrace pub s (after raw (eventLog ((ts ++ rs).take q))) regs) := by
+ have hh : H < 2 ^ w := by have := d.headerFits; omega
+ have frame := selected_reference_frame B f hf T hT X z base raw ds offset ts rs tags rows
+ (belowHeader.trans_lt hh)
+ have size := congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ change offset + base + words B.recordLimit ((selected B f hf T hT X z).map TaggedLayer.layer) ≤ H
+ at belowHeader
+ rw [size] at belowHeader
+ have headers : ∀ j ≤ (levelFibers (executeLevels B f hf T hT X z) ds).length,
+ first + j * stride + 28 ≤ base := by
+ simpa only [levelFibers, List.length_ofFn] using headersBefore
+ intro q hq s regs
+ have d' := d.transfer headers (fun x hx =>
+ frame q hq x (Or.inl (hx.trans_le (Nat.le_add_left _ _))) (Or.inl hx))
+ (fun field _ => frame q hq _ (Or.inr (by omega)) (Or.inr (by omega)))
+ exact Native.prefixTrace_reads d' (fun j hj => (headers j hj).trans (by omega)) s regs
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerStep.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerStep.lean
new file mode 100644
index 0000000000..d86e89399e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerStep.lean
@@ -0,0 +1,237 @@
+import OAI.Computability.VPVNP.PairTraversalControllerPrepare
+import OAI.Computability.VPVNP.PairTraversalControllerRoute
+import OAI.Computability.VPVNP.PairTraversalControllerBody
+import OAI.Computability.VPVNP.PairTraversalControllerMemory
+
+/-!
+# Native active, reset and terminal bursts of the descriptor controller
+
+The live operand and dispatch trace contains only reads and ticks. An active
+call then replays the exact reference worker trace and returns the encoded
+successor site. The two boundary cases leave the external memory untouched.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM CompressorRecords
+open TraversalControllerInputs TraversalControllerOrdinal TraversalRows
+set_option maxRecDepth 12000
+
+open scoped Fin.CommRing
+open private value_outside from OAI.Computability.VPVNP.PairTraversalControllerFormula
+
+variable {w : ℕ}
+
+/-- A reference worker occupies the physical layer selected by the controller. -/
+def Pass.Located (pub : Fin 11 → Word w) (m : Memory w) (L p : ℕ) : Pass w → Prop
+ | .tag fields n => p < L ∧ tagParams pub m (p % L) = fields ∧ (siteCount pub m (p % L)).val = n
+ | .leaf fields n => L ≤ p ∧ p % L = 0 ∧ leafParams pub m = fields ∧
+ (siteCount pub m (p % L)).val = n
+ | .fiber fields _ n => L ≤ p ∧ p % L ≠ 0 ∧ fiberParams pub m (p % L - 1) = fields ∧
+ (siteCount pub m (p % L)).val = n
+
+/-- The controller route that runs the worker appropriate to a tag, leaf-row, or
+placement-fiber pass. -/
+def Pass.route : Pass w → Native.Route
+ | .tag .. => .role
+ | .leaf .. => .leaf
+ | .fiber .. => .fiber
+
+/-- Translate the chosen pass's local worker labels into the corresponding native controller
+addresses. -/
+def Pass.labels (P : Pass w) : P.body.Label → Fin Native.P :=
+ match P with
+ | .tag .. => Native.rolePC
+ | .leaf .. => Native.leafPC
+ | .fiber .. => Native.fiberPC
+
+private theorem Pass.linked (P : Pass w) (pub : Fin 11 → Word w) :
+ Flow.Linked (Native.machine pub) P.body P.labels Native.nextPC Native.rejectPC := by
+ cases P with
+ | tag => exact Native.linked_role pub
+ | leaf => exact Native.linked_leaf pub
+ | fiber => exact Native.linked_fiber pub
+
+private theorem Pass.start_label (P : Pass w) : P.route.pc = P.labels P.body.entry := by
+ cases P <;> rfl
+
+private theorem Pass.at_route {pub : Fin 11 → Word w} {m : Memory w} {L N p i : ℕ}
+ {rs : Regs w R} {P : Pass w} (read : Readback pub m L N p i rs) (hloc : P.Located pub m L p)
+ (level : 0 < L) (phase : p < 2 * L) (digit : i ≤ N) (active : i < P.count)
+ (fit : 2 * L * (N + 1) < 2 ^ w) : Native.route rs = P.route ∧ P.Bank rs := by
+ rw [read.route_eq level phase.le digit fit, ite_eq_left phase]
+ cases P with
+ | tag fields n =>
+ change i < n at active
+ obtain ⟨hp, hbank, hc⟩ := hloc
+ exact ⟨by rw [hc, ite_eq_left active, ite_eq_left hp]; rfl, read.role.trans hbank⟩
+ | leaf fields n =>
+ change i < n at active
+ obtain ⟨hp, hj, hbank, hc⟩ := hloc
+ exact ⟨by rw [hc, ite_eq_left active, ite_eq_right (Nat.not_lt_of_ge hp), ite_eq_left hj]; rfl,
+ read.leaf.trans hbank⟩
+ | fiber fields cap n =>
+ change i < n at active
+ obtain ⟨hp, hj, hbank, hc⟩ := hloc
+ exact ⟨by rw [hc, ite_eq_left active, ite_eq_right (Nat.not_lt_of_ge hp), ite_eq_right hj]; rfl,
+ (read.fiber hj).trans hbank⟩
+
+/-- Number of register-setup instructions needed to evaluate the controller's traversal
+formulas. -/
+def setupLen : ℕ := (RegisterSetup.lines formulas).length
+
+/-- Bounds and read-only behavior of the administrative event prefix before a worker, including
+its exact probe count and empty choice tape. -/
+structure Admin (es : List (Event w)) : Prop where
+ clock : es.length ≤ setupLen + 7
+ probes : countProbes es = 257
+ bits : choiceBits es = []
+ readOnly : ∀ a v, Event.write a v ∉ es
+ replay : ∀ m : Memory w, after m es = m
+
+private theorem prepare_step (pub : Fin 11 → Word w) (m : Memory w) (L N p i : ℕ)
+ (hL : (terminalField pub m 1).val = L) (hN : (siteCount pub m 0).val = N)
+ (level : 0 < L) (digit : i ≤ N) (fit : 2 * L * (N + 1) < 2 ^ w)
+ (stFit : pack N p i < 2 ^ w) :
+ let st := (pack N p i : Word w)
+ let M := Native.machine pub
+ ∃ es rs, Admin es ∧ Readback pub m L N p i rs ∧ (∀ j, rs (scratchRegs j) = 0) ∧
+ es = Native.prefixTrace pub st m rs ∧
+ ∀ fuel, execute M.program (fuel + es.length) (M.program.start st) m [] =
+ (execute M.program fuel ⟨(Native.route rs).pc, st, rs, fun _ => 0⟩ m []).map
+ (Flow.prependEvents es) := by
+ obtain ⟨es, rs, vals, zeros, len, probes, bits, writes, replay, run, origin⟩ :=
+ Native.prepare_trace pub (pack N p i : Word w) m
+ have pitchFit : N + 1 < 2 ^ w := (Nat.le_mul_of_pos_left _ (by omega : 0 < 2 * L)).trans_lt fit
+ have ticks : (Native.route rs).ticks ≤ 4 := by cases Native.route rs <;> decide
+ have lim : es.length ≤ setupLen + 7 := by
+ change _ ≤ (RegisterSetup.lines formulas).length + 7
+ omega
+ exact ⟨es, rs, ⟨lim, probes.trans TraversalRoles.ControllerMemory.controller_setup_loads,
+ bits, writes, replay⟩, readback pub m L N p i rs hL hN level digit pitchFit stFit vals,
+ zeros, origin, fun fuel => run fuel []⟩
+
+private theorem finish_next (pub : Fin 11 → Word w) (st : Word w) (rs : Regs w R) (m : Memory w)
+ (extra : ℕ) : execute (Native.machine pub).program (extra + 1)
+ ⟨Native.nextPC, st, rs, fun _ => 0⟩ m [] = some ⟨[], some (rs (value 7))⟩ := by
+ simp [execute, Machine.program, Native.code_next, Instr.run]
+
+/-- A complete active burst adds the fixed read-only operand prefix to the
+actual native tag or row report and advances by exactly one site. -/
+theorem active_step_trace (pub : Fin 11 → Word w) (m : Memory w) (L N p i : ℕ)
+ (hL : (terminalField pub m 1).val = L) (hN : (siteCount pub m 0).val = N)
+ (level : 0 < L) (phase : p < 2 * L) (digit : i ≤ N) (fit : 2 * L * (N + 1) < 2 ^ w)
+ (P : Pass w) (hloc : P.Located pub m L p) (active : i < P.count) (small : Report w)
+ (reference : P.At (i : Word w) m small) :
+ ∃ es, Admin es ∧ (∃ rs, es = Native.prefixTrace pub (pack N p i : Word w) m rs) ∧
+ ∀ fuel, setupLen + 7 + P.clock ≤ fuel →
+ execute (Native.machine pub).program fuel
+ ((Native.machine pub).program.start (pack N p i : Word w)) m [] =
+ some ⟨es ++ small.events, some (pack N p (i + 1) : Word w)⟩ := by
+ let M := Native.machine pub
+ let st := (pack N p i : Word w)
+ have stFit := (pack_lt phase digit).trans fit
+ obtain ⟨es, rs, admin, read, zero, origin, enter⟩ :=
+ prepare_step pub m L N p i hL hN level digit fit stFit
+ obtain ⟨route, bank⟩ := Pass.at_route read hloc level phase digit active fit
+ obtain ⟨out, body, bits, clock, frame⟩ := Pass.lift reference pub st rs bank read.site zero
+ have next : out (value 7) = (pack N p (i + 1) : Word w) :=
+ (frame _ (value_outside 7)).trans read.next
+ refine ⟨es, admin, ⟨rs, origin⟩, fun fuel enough => ?_⟩
+ let extra := fuel - es.length - small.events.length - 1
+ have exactFuel : fuel = (small.events.length + (extra + 1)) + es.length := by
+ have := admin.clock
+ dsimp only [extra]
+ omega
+ have work := body.execute (P.linked pub) (Native.code_reject pub) (fun _ => 0) (extra + 1) []
+ rw [bits, List.nil_append, finish_next, next] at work
+ rw [exactFuel, enter, route, Pass.start_label, work]
+ simp [Flow.prependEvents]
+
+theorem active_step (pub : Fin 11 → Word w) (m : Memory w) (L N p i : ℕ)
+ (hL : (terminalField pub m 1).val = L) (hN : (siteCount pub m 0).val = N)
+ (level : 0 < L) (phase : p < 2 * L) (digit : i ≤ N) (fit : 2 * L * (N + 1) < 2 ^ w)
+ (P : Pass w) (hloc : P.Located pub m L p) (active : i < P.count) (small : Report w)
+ (reference : P.At (i : Word w) m small) :
+ ∃ es, Admin es ∧ ∀ fuel, setupLen + 7 + P.clock ≤ fuel →
+ execute (Native.machine pub).program fuel
+ ((Native.machine pub).program.start (pack N p i : Word w)) m [] =
+ some ⟨es ++ small.events, some (pack N p (i + 1) : Word w)⟩ := by
+ obtain ⟨es, admin, _, run⟩ := active_step_trace
+ pub m L N p i hL hN level phase digit fit P hloc active small reference
+ exact ⟨es, admin, run⟩
+
+/-- Closing a level costs one read-only burst. The next level starts at zero
+and the final level advances to the terminal sentinel. -/
+theorem reset_step_trace (pub : Fin 11 → Word w) (m : Memory w) (L N p i : ℕ)
+ (hL : (terminalField pub m 1).val = L) (hN : (siteCount pub m 0).val = N)
+ (level : 0 < L) (phase : p < 2 * L) (digit : i ≤ N) (fit : 2 * L * (N + 1) < 2 ^ w)
+ (endSite : i = (siteCount pub m (p % L)).val) :
+ ∃ es, Admin es ∧ (∃ rs, es = Native.prefixTrace pub (pack N p i : Word w) m rs) ∧
+ ∀ fuel, setupLen + 8 ≤ fuel →
+ execute (Native.machine pub).program fuel
+ ((Native.machine pub).program.start (pack N p i : Word w)) m [] =
+ some ⟨es, some (pack N (p + 1) 0 : Word w)⟩ := by
+ obtain ⟨es, rs, admin, read, _, origin, enter⟩ := prepare_step pub m L N p i hL hN level digit fit
+ ((pack_lt phase digit).trans fit)
+ have hr := read.route_eq level phase.le digit fit
+ rw [ite_eq_left phase, ite_eq_right (by omega)] at hr
+ refine ⟨es, admin, ⟨rs, origin⟩, fun fuel enough => ?_⟩
+ let extra := fuel - es.length - 1
+ have exactFuel : fuel = extra + 1 + es.length := by have := admin.clock; dsimp only [extra]; omega
+ rw [exactFuel, enter, hr]
+ simp [Native.Route.pc, execute, Machine.program, Native.code_reset, Instr.run, read.reset,
+ Flow.prependEvents]
+
+theorem reset_step (pub : Fin 11 → Word w) (m : Memory w) (L N p i : ℕ)
+ (hL : (terminalField pub m 1).val = L) (hN : (siteCount pub m 0).val = N)
+ (level : 0 < L) (phase : p < 2 * L) (digit : i ≤ N) (fit : 2 * L * (N + 1) < 2 ^ w)
+ (endSite : i = (siteCount pub m (p % L)).val) :
+ ∃ es, Admin es ∧ ∀ fuel, setupLen + 8 ≤ fuel →
+ execute (Native.machine pub).program fuel
+ ((Native.machine pub).program.start (pack N p i : Word w)) m [] =
+ some ⟨es, some (pack N (p + 1) 0 : Word w)⟩ := by
+ obtain ⟨es, admin, _, run⟩ := reset_step_trace
+ pub m L N p i hL hN level phase digit fit endSite
+ exact ⟨es, admin, run⟩
+
+/-- Accept once after both complete passes, with all worker memory intact. -/
+theorem stop_step_trace (pub : Fin 11 → Word w) (m : Memory w) (L N : ℕ)
+ (hL : (terminalField pub m 1).val = L) (hN : (siteCount pub m 0).val = N)
+ (level : 0 < L) (fit : 2 * L * (N + 1) < 2 ^ w) :
+ ∃ es, Admin es ∧ (∃ rs, es = Native.prefixTrace pub (pack N (2 * L) 0 : Word w) m rs) ∧
+ ∀ fuel, setupLen + 8 ≤ fuel →
+ execute (Native.machine pub).program fuel
+ ((Native.machine pub).program.start (pack N (2 * L) 0 : Word w)) m [] =
+ some ⟨es, none⟩ := by
+ obtain ⟨es, rs, admin, read, _, origin, enter⟩ := prepare_step pub m L N (2 * L) 0 hL hN level
+ (Nat.zero_le _) fit (by simpa [pack] using fit)
+ have hr := read.route_eq level le_rfl (Nat.zero_le _) fit
+ rw [ite_eq_right (Nat.lt_irrefl _)] at hr
+ refine ⟨es, admin, ⟨rs, origin⟩, fun fuel enough => ?_⟩
+ let extra := fuel - es.length - 1
+ have exactFuel : fuel = extra + 1 + es.length := by have := admin.clock; dsimp only [extra]; omega
+ rw [exactFuel, enter, hr]
+ simp [Native.Route.pc, execute, Machine.program, Native.code_accept, Instr.run,
+ Flow.prependEvents]
+
+theorem stop_step (pub : Fin 11 → Word w) (m : Memory w) (L N : ℕ)
+ (hL : (terminalField pub m 1).val = L) (hN : (siteCount pub m 0).val = N)
+ (level : 0 < L) (fit : 2 * L * (N + 1) < 2 ^ w) :
+ ∃ es, Admin es ∧ ∀ fuel, setupLen + 8 ≤ fuel →
+ execute (Native.machine pub).program fuel
+ ((Native.machine pub).program.start (pack N (2 * L) 0 : Word w)) m [] =
+ some ⟨es, none⟩ := by
+ obtain ⟨es, admin, _, run⟩ := stop_step_trace
+ pub m L N hL hN level fit
+ exact ⟨es, admin, run⟩
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalControllerTerminal.lean b/lean/OAI/Computability/VPVNP/PairTraversalControllerTerminal.lean
new file mode 100644
index 0000000000..9c17f36d59
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalControllerTerminal.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.PairTraversalControllerRun
+import OAI.Computability.VPVNP.PairSimulationTerminalProgram
+import OAI.Computability.VPVNP.PairSimulationTerminalPhaseBuild
+
+/-!
+# Entering the native traversal controller in the terminal machine
+
+Stage two starts its local ordinal at zero. Its ordinary worker reports are
+lifted to the terminal instruction image, which saves the returned ordinal
+on intermediate calls and hands off to the shared-bit phase on acceptance.
+All row, tag, input, and final-bit words agree with the selected native arena.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords TerminalLink
+open LiveProgram (PairTable)
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Lift the verified closed traversal segment into the five-stage image.
+The final agreement applies to every word except the two terminal controls. -/
+theorem linked_stage (workers : Stage → PairTable) (pub : Fin 11 → Word w)
+ (bank : workers Stage.traversalRows = ⟨Native.P, R, Native.table⟩)
+ {src phy final : Memory w} {fuel outer calls probes : ℕ} {out : List (Report w)}
+ (segment : Segment (Native.machine pub).program fuel (some 0) none src final calls probes out)
+ (reads : SourceTransport.Reads (workerCell (header pub)) (eventLog out))
+ (room : fuel + 30 ≤ outer) (wide : 32 ≤ 2 ^ w)
+ (valid : (Entry.resume Stage.traversalRows (0 : Word w)).Valid (header pub) phy)
+ (agree : SourceTransport.Agree (workerCell (header pub)) src phy) :
+ let entry := Entry.resume Stage.traversalRows (0 : Word w)
+ let bs : List (List Bool) := List.replicate calls []
+ let physical := after phy (eventLog (stageReports (header pub) entry out))
+ StageRun workers pub outer entry src phy bs out ∧
+ Phase workers pub outer entry phy bs (stageLogs entry out) physical ∧
+ SourceTransport.Agree (workerCell (header pub)) final physical := by
+ intro entry bs physical
+ have sourceRun : runSegment (source workers entry.stage pub) fuel (some entry.state) src bs =
+ some out := by
+ change runSegment (source workers Stage.traversalRows pub) fuel (some 0) src bs = some out
+ unfold source
+ rw [bank]
+ exact segment.run
+ have h := closed_stage_run workers pub fuel outer entry src phy bs out wide room valid agree reads
+ sourceRun segment.endAt
+ exact ⟨h, closed_phase workers pub fuel outer entry src phy bs out room agree reads sourceRun
+ segment.endAt, segment.memory ▸ h.agree⟩
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalCost.lean b/lean/OAI/Computability/VPVNP/PairTraversalCost.lean
new file mode 100644
index 0000000000..d063aace20
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalCost.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.PairSimulationDFS
+
+/-!
+# Native depth-first visits of an ordered placement tree
+
+A node stores the absolute address of its descriptor and the address of
+its ordered child list. Visiting a forest pushes the listed children ahead
+of the pending suffix. The total number of child reads is the number of
+non-root nodes in the forest, even if some addresses recur.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.DFS
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+open private headerEvents from OAI.Computability.VPVNP.PairSimulationDFS
+
+variable {w : ℕ}
+
+/-- One node of an actual local expansion, with its ordered placement fiber. -/
+inductive VertexTree where
+ | node (address src count : ℕ) (children : Fin count → VertexTree)
+
+namespace VertexTree
+
+/-- The absolute DFS node address stored at the root of this selected vertex tree. -/
+def address : VertexTree → ℕ
+ | .node addr _ _ _ => addr
+
+/-- All descriptor addresses in the order visited by the downward-growing stack. -/
+def preorder : VertexTree → List ℕ
+ | .node addr _ _ kids => addr :: (List.ofFn fun i => preorder (kids i)).flatten
+
+theorem preorder_nonempty (t : VertexTree) : 1 ≤ t.preorder.length := by
+ cases t
+ simp [preorder]
+
+/-- Contents of the native descriptor table, including the pointer and
+count of an empty child list at each leaf. -/
+def rows (w : ℕ) (m : Memory w) : VertexTree → Prop
+ | .node addr src _ kids =>
+ addr < 2^w ∧ Row m addr src (List.ofFn fun i => ((kids i).address : Word w)) ∧
+ ∀ i, rows w m (kids i)
+
+private theorem forest_length (trees : List VertexTree) :
+ trees.length ≤ (trees.flatMap preorder).length := by
+ induction trees with
+ | nil => rfl
+ | cons t tail ih =>
+ simp only [List.length_cons, List.flatMap_cons, List.length_append]
+ have := preorder_nonempty t
+ omega
+
+private def CanPrepend (m : Memory w) (top : ℕ) (t : VertexTree) : Prop :=
+ ∀ (pending nodes : List (Word w)) (es : List (Event w)), Visits m top pending nodes es →
+ t.preorder.length + pending.length ≤ top →
+ ∃ out, Visits m top ((t.address : Word w) :: pending)
+ (t.preorder.map (fun n : ℕ => (n : Word w)) ++ nodes) out
+
+private theorem prepend_forest {m : Memory w} {top : ℕ} (trees : List VertexTree)
+ (h : ∀ t ∈ trees, CanPrepend m top t) {pending nodes : List (Word w)} {es : List (Event w)}
+ (v : Visits m top pending nodes es)
+ (hsize : (trees.flatMap preorder).length + pending.length ≤ top) :
+ ∃ out, Visits m top (trees.map (fun t => (t.address : Word w)) ++ pending)
+ ((trees.flatMap preorder).map (fun n : ℕ => (n : Word w)) ++ nodes) out := by
+ induction trees with
+ | nil => exact ⟨es, v⟩
+ | cons t tail ih =>
+ have hsum : t.preorder.length + (tail.flatMap preorder).length + pending.length ≤ top := by
+ simpa only [List.flatMap_cons, List.length_append] using hsize
+ obtain ⟨log, run⟩ := ih (fun t ht => h t (List.mem_cons_of_mem _ ht)) (by omega)
+ have hrest := forest_length tail
+ have hspace : t.preorder.length +
+ (tail.map (fun t => (t.address : Word w)) ++ pending).length ≤ top := by
+ simp only [List.length_append, List.length_map]
+ omega
+ obtain ⟨out, run'⟩ := h t List.mem_cons_self _ _ _ run hspace
+ exact ⟨out, by simpa only [List.map_cons, List.cons_append, List.flatMap_cons,
+ List.map_append, List.append_assoc] using run'⟩
+
+private theorem prepend (t : VertexTree) (m : Memory w) (top : ℕ) (h : rows w m t) :
+ CanPrepend m top t := by
+ induction t with
+ | node addr src count kids ih =>
+ intro pending nodes es old space
+ obtain ⟨ha, hr, hk⟩ := h
+ let ts := List.ofFn kids
+ have hm : ts.flatMap preorder = (List.ofFn fun i => preorder (kids i)).flatten := by
+ rw [List.flatMap_def, List.map_ofFn]
+ rfl
+ have hsum : (ts.flatMap preorder).length + pending.length < top := by
+ simpa only [preorder, List.length_cons, hm, Nat.succ_add, Nat.succ_le_iff] using space
+ have hchildren : ∀ child ∈ ts, CanPrepend m top child := by
+ intro child hc
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hc
+ exact ih i (hk i)
+ obtain ⟨log, run⟩ := prepend_forest ts hchildren old hsum.le
+ have hfit : (ts.map (fun t => (t.address : Word w))).length + pending.length ≤ top := by
+ rw [List.length_map]
+ exact (Nat.add_le_add_right (forest_length ts) _).trans hsum.le
+ have hr' : Row m (addr : Word w).val src (ts.map fun t => (t.address : Word w)) := by
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt ha, ts, List.map_ofFn,
+ Function.comp_def] using hr
+ exact ⟨_, by simpa only [address, preorder, ← hm, List.map_cons, List.cons_append] using
+ (Visits.cons hr' hfit run)⟩
+
+/-- The fixed native traversal executes the serialized placement tree, in
+the selected order, in a stack with one word per node. -/
+theorem visits {m : Memory w} (t : VertexTree) (top : ℕ) (hrows : rows w m t)
+ (hsize : t.preorder.length ≤ top) :
+ ∃ es, Visits m top [(t.address : Word w)] (t.preorder.map (fun n : ℕ => (n : Word w))) es := by
+ obtain ⟨es, hv⟩ := prepend t m top hrows [] [] _ Visits.nil (by simpa using hsize)
+ exact ⟨es, by simpa using hv⟩
+
+end VertexTree
+
+/-- The DFS control code reads two header words per visit and one word
+per child. Its event length also includes the pop, loop, and stack-copy
+instructions, and the final empty-stack test. -/
+theorem Visits.cost {m : Memory w} {top : ℕ} {pending nodes : List (Word w)} {es : List (Event w)}
+ (h : Visits m top pending nodes es) :
+ countProbes es + pending.length = 3 * nodes.length ∧
+ es.length + 5 * pending.length = 15 * nodes.length + 1 := by
+ have append (xs ys : List (Event w)) :
+ countProbes (xs ++ ys) = countProbes xs + countProbes ys := by
+ induction xs with
+ | nil => simp [countProbes]
+ | cons x xs ih => cases x <;> simp [countProbes, ih, Nat.add_comm, Nat.add_left_comm]
+ have len (src n : ℕ) : (EndpointBits.events m src n).length = 5*n+1 := by
+ induction n generalizing src with
+ | zero => rfl
+ | succ n ih => simp [EndpointBits.events, ih]; omega
+ induction h with
+ | nil => exact ⟨rfl, rfl⟩
+ | @cons node pending kids nodes src es row fits rest ih =>
+ obtain ⟨hp, hl⟩ := ih
+ rw [List.length_append] at hp hl
+ simp only [append, List.length_append, List.length_cons, List.length_nil, len]
+ have hhead : countProbes (headerEvents w node.val src kids.length) = 2 := rfl
+ have hzero : countProbes ([.tick,.tick,.tick] : List (Event w)) = 0 := rfl
+ rw [hzero, hhead, EndpointBits.probes]
+ change _ ∧ 3 + 6 + (5*kids.length+1) + es.length + 5*(pending.length+1) =
+ 15*(nodes.length+1)+1
+ omega
+
+end PairSimulation.DFS
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalDirectories.lean b/lean/OAI/Computability/VPVNP/PairTraversalDirectories.lean
new file mode 100644
index 0000000000..0d1d8b6165
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalDirectories.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.PairTraversalBuildExecution
+import OAI.Computability.VPVNP.PairTraversalNativeLayer
+import OAI.Computability.VPVNP.PairTraversalSelectedOrder
+import OAI.Computability.VPVNP.PairTraversalStageSize
+
+/-!
+# Connecting the placement directories to the native traversal table
+
+The native Appendix E scan records each old identifier under its placed new
+site. Those directories, a common zero count for the leaves, and the end of
+the raw arena supply all inputs to the traversal-table writer. The source
+records retain the physical numbering of the chosen compression branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open BurstRAM CompressorRecords LocalHistory NetworkKernel Compression
+open scoped Fin.CommRing
+
+variable {w : ℕ} {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+variable {N Y : Network}
+
+/-- A completed numerical placement pass with its concrete raw memory regions.
+The native owner map is the term's actual placement in the two site orders. -/
+structure Directory {N : Network} (t : Term A N) (old : Order N.Site) (next : Order t.output.Site)
+ (mem : Memory w) (limit : ℕ) where
+ /-- Six public directory words locating the old-site, output-site, count, and preimage row
+ data for a selected pass. -/
+ pub : Fin 6 → Word w
+ oldCount : (pub 0).val = old.length
+ newCount : (pub 2).val = next.length
+ regions : RowRegions pub
+ inputEnd : (pub 5).val + (pub 2).val * (pub 4).val ≤ limit
+ collected : PreimagesAt pub (encodedPlacement old.entries.symm next.entries.symm t.place)
+ mem old.length
+ capacity : ∀ v : Word w, v < pub 2 →
+ (preimagePrefix (encodedPlacement old.entries.symm next.entries.symm t.place) v
+ old.length).length ≤ (pub 4).val
+
+/-- Expose the per-site child count and preimage-row start as source pointers for the selected
+directory reader. -/
+def Directory.source {t : Term A N} {old : Order N.Site} {next : Order t.output.Site}
+ {mem : Memory w} {limit : ℕ} (dir : Directory t old next mem limit) (r : TermParsers κ t) :
+ Source w (stepLayer old next r) :=
+ ⟨fun i => countAt dir.pub (i.val : Word w), fun i => rowAt dir.pub (i.val : Word w)⟩
+
+open Classical in
+theorem Directory.ready {t : Term A N} {old : Order N.Site} {next : Order t.output.Site}
+ {mem : Memory w} {limit : ℕ} (dir : Directory t old next mem limit) (r : TermParsers κ t)
+ (ho : ∀ v, r.order.children v = old.restrict (fun u => v = t.place u)) :
+ (dir.source r).Ready mem limit := by
+ let physical : Word w → Word w := encodedPlacement old.entries.symm next.entries.symm t.place
+ have hfit₀ : old.length ≤ 2 ^ w := dir.oldCount ▸ (dir.pub 0).isLt.le
+ have hfit₁ : next.length ≤ 2 ^ w := dir.newCount ▸ (dir.pub 2).isLt.le
+ have rows := raw_rows_of_preimages old next r physical
+ (encodedPlacement_represents old next t.place hfit₀ hfit₁) ho dir.pub mem dir.oldCount
+ dir.newCount dir.collected
+ have hv (i : Fin next.length) : (i.val : Word w) < dir.pub 2 := by
+ change i.val % (2 ^ w) < (dir.pub 2).val
+ rw [Nat.mod_eq_of_lt (i.isLt.trans_le hfit₁), dir.newCount]
+ exact i.isLt
+ have before (i : Fin next.length) := preimage_input_before dir.regions dir.inputEnd (hv i)
+ refine ⟨rows, fun i => (before i).1, fun i => ?_⟩
+ have hlen := (rows i).1.symm.trans (dir.collected.rows _ (hv i)).1
+ rw [List.length_map] at hlen
+ exact (Nat.add_le_add_left (hlen.trans_le (dir.capacity _ (hv i))) _).trans (before i).2
+
+/-- Persistent directories of all non-leaf terms on this particular branch. -/
+def Directories (mem : Memory w) (limit : ℕ) {N Y : Network} (c : TermChain A N Y)
+ (ords : ChainOrders c) (old : Order N.Site) : Type :=
+ match c with
+ | .done _ => PUnit
+ | .more t _ tail => Directory t old ords.1 mem limit × Directories mem limit tail ords.2 ords.1
+
+/-- Collect the child-count and preimage-row source pointers along the chain of selected
+compression directories. -/
+noncomputable def directorySources {mem : Memory w} {limit : ℕ} {N Y : Network}
+ (c : TermChain A N Y)
+ (r : ChainParsers κ c) (ords : ChainOrders c) (old : Order N.Site)
+ (dirs : Directories mem limit c ords old) : Sources w (stepLayers c r ords old) := by
+ induction c with
+ | done => exact PUnit.unit
+ | more t data tail ih => exact ⟨dirs.1.source r.1, ih r.2 ords.2 ords.1 dirs.2⟩
+
+theorem directories_ready {mem : Memory w} {limit : ℕ} (c : TermChain A N Y)
+ (r : ChainParsers κ c) (ords : ChainOrders c) (old : Order N.Site)
+ (dirs : Directories mem limit c ords old) (ho : OrderedChildren c r ords old) :
+ SourcesReady mem limit (stepLayers c r ords old) (directorySources c r ords old dirs) := by
+ induction c with
+ | done => trivial
+ | more _ _ _ ih => exact ⟨dirs.1.ready r.1 ho.1, ih r.2 ords.2 ords.1 dirs.2 ho.2⟩
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) (f : B.Entry → A)
+variable (hf : B.IsSolution f) {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+variable (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+
+/-- The source-count and source-list pointers of an actual selected branch
+satisfy all the native writer's preconditions. -/
+theorem selected_sources_ready (mem : Memory w) (base : ℕ) (zero : Word w)
+ (hzero : mem zero.val = 0) (hz : zero.val < base) :
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let parsers := selectedParsers B f hf T hT X z
+ let ords := branchOrders E data z
+ ∀ dirs : Directories mem base c ords (siteOrder X),
+ SourcesReady mem base (selectedLayers B f hf T hT X z)
+ ⟨leafSource (siteOrder X) zero, directorySources c parsers ords (siteOrder X) dirs⟩ := by
+ intro E data c parsers ords dirs
+ exact ⟨leafSource_ready _ _ _ hzero hz, directories_ready c parsers ords _ dirs
+ (selectedParsers_ordered B f hf T hT X z)⟩
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalDirectoryRun.lean b/lean/OAI/Computability/VPVNP/PairTraversalDirectoryRun.lean
new file mode 100644
index 0000000000..6db855ba31
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalDirectoryRun.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.PairTraversalDirectories
+import OAI.Computability.VPVNP.PairTraversalLayerSegment
+import OAI.Computability.VPVNP.PairTraversalLeafWorker
+
+/-!
+# Reset-entry construction of a selected branch's traversal descriptors
+
+The cursor-leaf pass writes the two header words directly. Each subsequent
+pass translates one of the completed Appendix E placement directories using
+one native burst per new site. Registers are reset on entry, and the persistent
+site counter is initialized to zero at the beginning of each layer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows.DirectoryRun
+
+open BurstRAM CompressorRecords NetworkKernel LocalHistory Compression
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Public parameters for one of the two fixed descriptor workers. -/
+inductive Worker (w : ℕ) where
+ | leaf (cap base count : ℕ)
+ | fiber (pub : Fin 6 → Word w) (cap previous base count : ℕ)
+
+/-- A layer is evaluated from the first site using zero-initialized private registers. -/
+def Worker.Run (m : Memory w) (rs : List (Report w)) : Worker w → Prop
+ | .leaf cap base count =>
+ let P := (LeafWorker.program.template (some 0)).instantiate w (LeafWorker.directory w cap base)
+ runSegment P.program 14 (some 0) m (List.replicate count []) = some rs
+ | .fiber pub cap previous base count =>
+ let P := (SiteWorker.program.template (some 6)).instantiate w (workerData pub cap previous base)
+ runSegment P.program (7 * cap + 25) (some 0) m (List.replicate count []) = some rs
+
+/-- The memory output of each stage is the memory input of the next. -/
+inductive Segments : List (Worker w) → Memory w → List (Report w) → Prop
+ | nil (m : Memory w) : Segments [] m []
+ | cons {head : Worker w} {tail : List (Worker w)} {m : Memory w} {rs ss : List (Report w)}
+ (run : head.Run m rs) (rest : Segments tail (after m (eventLog rs)) ss) :
+ Segments (head :: tail) m (rs ++ ss)
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+variable {N Y : Network}
+
+/-- Six public words per term identify the live raw records. Consecutive
+layers use contiguous rows and point into their predecessor's rows. -/
+def workers {N Y : Network} {raw : Memory w} {limit : ℕ} (c : TermChain A N Y)
+ (ords : ChainOrders c)
+ (old : Order N.Site) (dirs : Directories raw limit c ords old) (cap previous base : ℕ) :
+ List (Worker w) :=
+ match c with
+ | .done _ => []
+ | .more _ _ tail => .fiber dirs.1.pub cap previous base ords.1.length ::
+ workers tail ords.2 ords.1 dirs.2 cap base (address cap base ords.1.length)
+
+private theorem append_memory (m : Memory w) (rs ss : List (Report w)) :
+ after m (eventLog (rs ++ ss)) = after (after m (eventLog rs)) (eventLog ss) := by
+ simp only [eventLog, List.flatMap_append, after, List.foldl_append]
+
+private theorem append_probes (rs ss : List (Report w)) :
+ countProbes (eventLog (rs ++ ss)) = countProbes (eventLog rs) + countProbes (eventLog ss) := by
+ simp only [eventLog, List.flatMap_append, BurstRAM.countProbes_append]
+
+/-- All native input words below the raw directory boundary survive updates
+to the traversal arena. -/
+private theorem ready_under {L : Layer} {r : Source w L} {raw m : Memory w} {limit base : ℕ}
+ (hr : r.Ready raw limit) (ag : ∀ x < limit, m x = raw x) (below : limit ≤ base) :
+ r.Ready m base := by
+ refine ⟨fun i => ?_, fun i => (hr.countBefore i).trans_le below,
+ fun i => (hr.sourceBefore i).trans below⟩
+ refine ⟨(congrArg Fin.val (ag _ (hr.countBefore i))).trans (hr.rows i).1, fun j => ?_⟩
+ have h : j.val < (L.ids i).length := by simpa only [List.length_map] using j.isLt
+ exact (ag _ ((Nat.add_lt_add_left h _).trans_le (hr.sourceBefore i))).trans ((hr.rows i).2 j)
+
+private theorem write_below (L : Layer) (cap previous base : ℕ) (m : Memory w) (x : ℕ)
+ (hx : x < base) : writeLayer cap previous base L m x = m x := by
+ apply writeLayer_unchanged
+ rintro ⟨i, hlo, _⟩
+ exact hx.not_ge ((Nat.le_add_right base ((cap + 2) * i.val)).trans hlo)
+
+/-- Realize every non-leaf layer directly from the actual branch directories. -/
+theorem run_fibers {raw : Memory w} {limit : ℕ} (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (old : Order N.Site) (dirs : Directories raw limit c ords old)
+ (ho : OrderedChildren c r ords old) (cap previous base : ℕ) (m : Memory w)
+ (below : limit ≤ base) (ag : ∀ x < limit, m x = raw x)
+ (hc : ∀ L ∈ stepLayers c r ords old, ∀ i, (L.ids i).length ≤ cap)
+ (fit : base + words cap (stepLayers c r ords old) < 2 ^ w) :
+ let ls := stepLayers c r ords old
+ ∃ rs, Segments (workers c ords old dirs cap previous base) m rs ∧
+ after m (eventLog rs) = build cap previous base ls m ∧
+ rs.length = (ls.map Layer.count).sum ∧
+ countProbes (eventLog rs) = (ls.map Layer.probeCount).sum := by
+ induction c generalizing previous base m with
+ | done => exact ⟨[], .nil _, rfl, rfl, rfl⟩
+ | more t data tail ih =>
+ let L := stepLayer old ords.1 r.1
+ let rest := stepLayers tail r.2 ords.2 ords.1
+ let next := endPos cap base L
+ have hf : next + words cap rest < 2 ^ w := by
+ simpa [next, L, rest, stepLayers, endPos, address, words, Nat.mul_add,
+ Nat.add_assoc] using fit
+ have room : next < 2 ^ w := (Nat.le_add_right _ _).trans_lt hf
+ have hcap : ∀ i, (L.ids i).length ≤ cap := hc L List.mem_cons_self
+ have hr := ready_under (dirs.1.ready r.1 ho.1) ag below
+ obtain ⟨rs, run, _, mem, probes, calls, _⟩ := run_numbered_layer _ _ L cap previous base _ _ m
+ (directory_worker dirs.1.pub L cap previous base hr.sourceBefore hcap room)
+ hr.rows hr.countBefore hr.sourceBefore hcap room
+ have hn : limit ≤ next := below.trans (Nat.le_add_right _ _)
+ have ag' (x : ℕ) (hx : x < limit) : after m (eventLog rs) x = raw x := by
+ rw [mem, write_below L cap previous base m x (hx.trans_le below), ag x hx]
+ obtain ⟨ss, runs, mem', calls', probes'⟩ := ih r.2 ords.2 ords.1 dirs.2 ho.2 base next
+ (after m (eventLog rs)) hn ag' (fun l hl => hc l (List.mem_cons_of_mem _ hl)) hf
+ refine ⟨rs ++ ss, .cons (head := .fiber dirs.1.pub cap previous base ords.1.length) run runs,
+ ?_, ?_, ?_⟩
+ · rw [append_memory, mem', mem]
+ rfl
+ · rw [List.length_append, calls, calls']
+ rfl
+ · rw [append_probes, probes, probes']
+ rfl
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) (f : B.Entry → A)
+variable (hf : B.IsSolution f) {n : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n)
+variable (X : State (S.degreeExponent 0) n) (z : (B.execute f hf T hT X).Choices)
+
+/-- A full native construction on the selected compressor branch. The leaf
+worker writes both header words itself. No preinitialized zero cell is needed.
+The total number of bursts is the exact selected row count. -/
+theorem selected_run (base : ℕ) (raw m : Memory w) (ag : ∀ x < base, m x = raw x)
+ (fit : base + words B.recordLimit (selectedLayers B f hf T hT X z) < 2 ^ w) :
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ords := branchOrders E data z
+ let old := siteOrder X
+ let cap := B.recordLimit
+ let ls := selectedLayers B f hf T hT X z
+ ∀ dirs : Directories raw base c ords old,
+ ∃ rs, Segments (.leaf cap base old.length ::
+ workers c ords old dirs cap base (address cap base old.length)) m rs ∧
+ after m (eventLog rs) = build cap base base ls m ∧
+ rs.length = (ls.map Layer.count).sum ∧
+ countProbes (eventLog rs) ≤ (2 * cap + 3) * (ls.map Layer.count).sum := by
+ intro E data c ords old cap ls dirs
+ let r := selectedParsers B f hf T hT X z
+ let L := leafLayer old
+ let rest := stepLayers c r ords old
+ let next := endPos cap base L
+ have eq : ls = L :: rest := rfl
+ have hcap := selected_capacity B f hf T hT X z
+ have hf' : next + words cap rest < 2 ^ w := by
+ change base + words cap (L :: rest) < 2 ^ w at fit
+ simpa [next, endPos, address, words, Nat.mul_add,
+ Nat.add_assoc] using fit
+ obtain ⟨rs, run, _, mem, calls, probes, _⟩ := LeafWorker.run_layer old cap base base m 14
+ ((Nat.le_add_right _ _).trans_lt hf') (by decide)
+ have hn : base ≤ next := Nat.le_add_right _ _
+ have ag' (x : ℕ) (hx : x < base) : after m (eventLog rs) x = raw x := by
+ rw [mem, write_below _ cap base base m x hx, ag x hx]
+ obtain ⟨ss, runs, mem', calls', probes'⟩ := run_fibers c r ords old dirs
+ (selectedParsers_ordered B f hf T hT X z) cap base next _ hn ag'
+ (fun l hl => hcap l (List.mem_cons_of_mem L hl)) hf'
+ refine ⟨rs ++ ss, .cons (head := .leaf cap base old.length) run runs, ?_, ?_, ?_⟩
+ · rw [append_memory, mem', mem]
+ rfl
+ · rw [List.length_append, calls, calls', eq]
+ rfl
+ · apply le_trans _ (probes_le ls cap hcap)
+ rw [append_probes, probes, probes', eq, List.map_cons, List.sum_cons]
+ have h : 2 * old.length ≤ L.probeCount := by simp [L, Layer.probeCount, leafLayer]; omega
+ exact Nat.add_le_add_right h _
+
+end PairSimulation.TraversalRows.DirectoryRun
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalDisjoint.lean b/lean/OAI/Computability/VPVNP/PairTraversalDisjoint.lean
new file mode 100644
index 0000000000..14cd3ca8fc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalDisjoint.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PairTraversalRows
+import Mathlib.Data.List.Nodup
+import Mathlib.Data.List.OfFn
+
+/-!
+# Distinct argument frames in a selected vertex history
+
+Every old site is placed at a single new site. Distinct placement fibers
+therefore contribute disjoint old subtrees, and their new headers occupy
+the next row layer. As a result each node address occurs only once during
+the traversal, and the pending siblings use distinct argument intervals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open LocalHistory NetworkKernel Compression DFS
+open private addTree from OAI.Computability.VPVNP.PairTraversalHistory
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {N Y : Network}
+
+/-- Each selected tree's preorder has distinct addresses, different roots have disjoint
+preorders, and all visited addresses lie below the stated bound. -/
+structure ForestBelow {I : Type} (bound : ℕ) (trees : I → VertexTree) : Prop where
+ unique : ∀ u, (trees u).preorder.Nodup
+ owner : ∀ u v x, x ∈ (trees u).preorder → x ∈ (trees v).preorder → u = v
+ below : ∀ u x, x ∈ (trees u).preorder → x < bound
+
+private theorem ptr_injective {I : Type} (o : Order I) (cap base : ℕ) :
+ Function.Injective (fun v => (sitePointers cap base o v).1) := by
+ intro u v h
+ change base + (cap+2)*(o.entries.symm u).val = base + (cap+2)*(o.entries.symm v).val at h
+ exact o.entries.symm.injective
+ (Fin.ext (Nat.eq_of_mul_eq_mul_left (by omega) (Nat.add_left_cancel h)))
+
+private theorem ptr_bounds {I : Type} (o : Order I) (cap base : ℕ) (u : I) :
+ base ≤ (sitePointers cap base o u).1 ∧
+ (sitePointers cap base o u).1 < address cap base o.length := by
+ exact ⟨Nat.le_add_right _ _, Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_left
+ (o.entries.symm u).isLt (by omega)) _⟩
+
+private theorem leafBelow {I : Type} (o : Order I) (cap base : ℕ) :
+ ForestBelow (address cap base o.length) (fun u => leafTree (sitePointers cap base o u)) := by
+ have eqn u : (leafTree (sitePointers cap base o u)).preorder =
+ [(sitePointers cap base o u).1] := rfl
+ refine ⟨fun u => by simp [eqn], fun u v x hu hv => ?_, fun u x hx => ?_⟩
+ · rw [eqn, List.mem_singleton] at hu hv
+ exact ptr_injective o cap base (hu.symm.trans hv)
+ · rw [eqn, List.mem_singleton] at hx
+ exact hx ▸ (ptr_bounds o cap base u).2
+
+private theorem pushBelow {t : Term A N} (r : TermParsers κ t) (cap base : ℕ)
+ (o : Order t.output.Site) (trees : N.Site → VertexTree) (old : ForestBelow base trees) :
+ ForestBelow (address cap base o.length) (addTree r (sitePointers cap base o) trees) := by
+ let kids v := List.ofFn fun i => (trees ((r.order.children v).entries i).val).preorder
+ let root v := (sitePointers cap base o v).1
+ have pre v : (addTree r (sitePointers cap base o) trees v).preorder =
+ root v :: (kids v).flatten := rfl
+ have mem {v x} : x ∈ (kids v).flatten ↔ ∃ u : t.Preimage v, x ∈ (trees u.val).preorder := by
+ rw [List.mem_flatten]
+ constructor
+ · rintro ⟨xs, hs, hx⟩
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hs
+ exact ⟨_, hx⟩
+ · rintro ⟨u, hx⟩
+ exact ⟨_, List.mem_ofFn.mpr ⟨(r.order.children v).entries.symm u, by simp⟩, hx⟩
+ have low {v x} (hx : x ∈ (kids v).flatten) : x < base := by
+ obtain ⟨u, hu⟩ := mem.mp hx
+ exact old.below _ _ hu
+ have separated (v) : (kids v).Pairwise List.Disjoint := by
+ apply List.pairwise_ofFn.mpr
+ intro i j hij x hi hj
+ have eqn := old.owner _ _ x hi hj
+ exact hij.ne ((r.order.children v).entries.injective (Subtype.ext eqn))
+ refine ⟨fun v => ?_, fun u v x hu hv => ?_, fun v x hx => ?_⟩
+ · rw [pre, List.nodup_cons, List.nodup_flatten]
+ refine ⟨fun h => (low h).not_ge (ptr_bounds o cap base v).1, ?_, separated v⟩
+ intro xs hxs
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hxs
+ exact old.unique _
+ · rw [pre, List.mem_cons] at hu hv
+ rcases hu with h | h <;> rcases hv with h' | h'
+ · exact ptr_injective o cap base (h.symm.trans h')
+ · exact False.elim ((low h').not_ge (h ▸ (ptr_bounds o cap base u).1))
+ · exact False.elim ((low h).not_ge (h' ▸ (ptr_bounds o cap base v).1))
+ · obtain ⟨p, hp⟩ := mem.mp h
+ obtain ⟨q, hq⟩ := mem.mp h'
+ exact p.property.trans ((congrArg t.place (old.owner _ _ x hp hq)).trans q.property.symm)
+ · rw [pre, List.mem_cons] at hx
+ rcases hx with h | h
+ · exact h ▸ (ptr_bounds o cap base v).2
+ · exact (low h).trans_le (Nat.le_add_right _ _)
+
+/-- Appending every selected stage preserves the partition into disjoint
+trees and the absence of repeated addresses within each tree. -/
+theorem chainTrees_unique (cap : ℕ) (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (base : ℕ) (trees : N.Site → VertexTree) (old : ForestBelow base trees) :
+ ∃ bound, ForestBelow bound (chainTrees c r (chainPointers cap c ords base) trees) := by
+ induction c generalizing base with
+ | done => exact ⟨base,old⟩
+ | more t rec tail ih =>
+ exact ih r.2 ords.2 (address cap base ords.1.length) _
+ (pushBelow r.1 cap base ords.1 trees old)
+
+/-- No two simultaneous child or sibling argument buffers of a selected
+cursor branch can refer to the same row. Each final vertex visits every
+descendant once and distinct final vertices visit disjoint descendants. -/
+theorem selected_preorders {k : Type*} [Field k] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {lanes : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) (base : ℕ) :
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ptr := chainPointers B.recordLimit c (branchOrders E data z)
+ (address B.recordLimit base (siteOrder X).length)
+ let trees := chainTrees c (selectedParsers B f hf T hT X z) ptr
+ (fun v => leafTree (sitePointers B.recordLimit base (siteOrder X) v))
+ (∀ v, (trees v).preorder.Nodup) ∧
+ ∀ u v j, j ∈ (trees u).preorder → j ∈ (trees v).preorder → u = v := by
+ intro E data c ptr trees
+ obtain ⟨_, ok⟩ := chainTrees_unique B.recordLimit c (selectedParsers B f hf T hT X z)
+ (branchOrders E data z) _ _ (leafBelow (siteOrder X) B.recordLimit base)
+ exact ⟨ok.unique, ok.owner⟩
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalHistory.lean b/lean/OAI/Computability/VPVNP/PairTraversalHistory.lean
new file mode 100644
index 0000000000..e329cd8baa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalHistory.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.PairTraversalCost
+import OAI.Computability.VPVNP.PairSimulationAssemblyBounds
+
+/-!
+# Placement histories in the native descriptor traversal
+
+On each selected shrinking or refresh term, the children of an output
+vertex are exactly the placed old vertices, in the actual reader's order.
+The following construction retains these vertices recursively down to
+the routed cursor input. The depth-first code visits the resulting tree
+in that order, using the stored row addresses of the selected stages.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel CompressorRecords Compression BurstRAM BurstRAM.PrivateRAM DFS
+open scoped Fin.CommRing
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {N Y : Network}
+
+/-- The header address and child-list pointer at each stage of a chosen history. -/
+def RowPointers {N Y : Network} : TermChain A N Y → Type
+ | .done _ => PUnit
+ | .more t _ tail => (t.output.Site → ℕ × ℕ) × RowPointers tail
+
+/-- Child IDs in the stored order, with their absolute addresses in the preceding layer. -/
+def rowsAt {N Y : Network} {w : ℕ} (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ptr : RowPointers c) (m : Memory w) (previous : N.Site → ℕ) : Prop :=
+ match c with
+ | .done _ => True
+ | .more _ _ tail =>
+ (∀ v, (ptr.1 v).1 < 2 ^ w ∧ Row m (ptr.1 v).1 (ptr.1 v).2
+ (List.ofFn fun j => (previous ((r.1.order.children v).entries j).val : Word w))) ∧
+ rowsAt tail r.2 ptr.2 m (fun v => (ptr.1 v).1)
+
+/-- A cursor leaf tree with the supplied node and source pointers and an empty family of
+children. -/
+def leafTree (ptr : ℕ × ℕ) : VertexTree :=
+ .node ptr.1 ptr.2 0 Fin.elim0
+
+private def addTree {t : Term A N} (r : TermParsers κ t) (p : t.output.Site → ℕ × ℕ)
+ (input : N.Site → VertexTree) (v : t.output.Site) : VertexTree :=
+ let order := r.order.children v
+ .node (p v).1 (p v).2 order.length fun j => input (order.entries j).val
+
+/-- Build the selected final vertex tree by following each term's actual
+finite placement fibers. The initial vertices may already carry subtrees. -/
+def chainTrees {N Y : Network} (c : TermChain A N Y) (r : ChainParsers κ c) (ptr : RowPointers c)
+ (input : N.Site → VertexTree) : Y.Site → VertexTree :=
+ match c with
+ | .done _ => input
+ | .more _ _ tail => chainTrees tail r.2 ptr.2 (addTree r.1 ptr.1 input)
+
+open scoped Classical in
+private theorem addTree_length {t : Term A N} (r : TermParsers κ t) (p : t.output.Site → ℕ × ℕ)
+ (input : N.Site → VertexTree) (v : t.output.Site) :
+ (addTree r p input v).preorder.length =
+ 1 + ∑ u : t.Preimage v, (input u.val).preorder.length := by
+ let o := r.order.children v
+ change ((p v).1 :: (List.ofFn fun i : Fin o.length =>
+ (input (o.entries i).val).preorder).flatten).length = _
+ rw [List.length_cons, List.length_flatten, List.map_ofFn, List.sum_ofFn]
+ rw [Nat.add_comm 1]
+ congr 1
+ exact o.entries.sum_comp (fun u => (input u.val).preorder.length)
+
+/-- Every visit consumes one of the vertex occurrences counted in
+Theorem 7.1. Field and map occurrences may increase that count further. -/
+theorem chainTrees_length (c : TermChain A N Y) (r : ChainParsers κ c) (ptr : RowPointers c)
+ (input : N.Site → VertexTree) (counts : N.Site → ℕ)
+ (hc : ∀ v, (input v).preorder.length ≤ counts v) :
+ ∀ v, (chainTrees c r ptr input v).preorder.length ≤ c.occurrences counts v := by
+ classical
+ induction c with
+ | done => exact hc
+ | more t rec tail ih =>
+ apply ih r.2 ptr.2 _ (t.pushHistorySize rec counts)
+ intro v
+ rw [addTree_length, Term.pushHistorySize]
+ exact Nat.add_le_add (by unfold SiteRecords.count; omega)
+ (Finset.sum_le_sum fun u _ => hc u.val)
+
+theorem chainTrees_rows {w : ℕ} (c : TermChain A N Y) (r : ChainParsers κ c) (ptr : RowPointers c)
+ (m : Memory w) (input : N.Site → VertexTree) (hs : ∀ v, (input v).rows w m)
+ (hr : rowsAt c r ptr m (fun v => (input v).address)) :
+ ∀ v, (chainTrees c r ptr input v).rows w m := by
+ induction c with
+ | done => exact hs
+ | more t rec tail ih =>
+ exact ih r.2 ptr.2 (addTree r.1 ptr.1 input) (fun v =>
+ ⟨(hr.1 v).1, (hr.1 v).2, fun i => hs _⟩) hr.2
+
+/-- The cursor leaves have an empty list in the first descriptor layer. -/
+theorem leafTree_rows {w : ℕ} {m : Memory w} {p : ℕ × ℕ} (hp : p.1 < 2 ^ w)
+ (h : Row m p.1 p.2 []) : (leafTree p).rows w m :=
+ ⟨hp, by simpa only [List.ofFn_zero] using h, fun i => i.elim0⟩
+
+/-- On every selected branch, the native DFS log reads at most three
+words and uses at most fifteen word instructions per vertex occurrence,
+plus the empty-stack test. The ordered node sequence is the actual
+placement tree of that branch. -/
+theorem selectedTraversal {k : Type*} [Field k] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {lanes : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices)
+ (ptr : RowPointers ((B.execute f hf T hT X).termChain (B.records f hf T hT X) z))
+ (leaves : X.network.Site → ℕ × ℕ) {w : ℕ} (m : Memory w)
+ (hl : ∀ v, (leaves v).1 < 2 ^ w ∧ Row m (leaves v).1 (leaves v).2 [])
+ (hr : rowsAt _ (selectedParsers B f hf T hT X z) ptr m (fun v => (leaves v).1)) :
+ let c := (B.execute f hf T hT X).termChain (B.records f hf T hT X) z
+ let trees := chainTrees c (selectedParsers B f hf T hT X z) ptr (fun v => leafTree (leaves v))
+ ∀ v, ∃ es, Visits m (B.growthConstant^T) [((trees v).address : Word w)]
+ ((trees v).preorder.map (fun n : ℕ => (n : Word w))) es ∧
+ countProbes es < 3 * c.occurrences (fun _ => 1) v ∧
+ es.length ≤ 15 * c.occurrences (fun _ => 1) v + 1 := by
+ intro c trees v
+ have len := chainTrees_length c (selectedParsers B f hf T hT X z) ptr
+ (fun u => leafTree (leaves u)) (fun _ => 1) (fun _ => le_rfl) v
+ have rows := chainTrees_rows c (selectedParsers B f hf T hT X z) ptr m
+ (fun u => leafTree (leaves u)) (fun u => leafTree_rows (hl u).1 (hl u).2) hr v
+ have bound := (B.branch_bounds f hf T hT X z).2.2.2.1 v
+ obtain ⟨es, visit⟩ := (trees v).visits (B.growthConstant^T) rows (len.trans bound)
+ obtain ⟨probes, ticks⟩ := visit.cost
+ simp only [List.length_map, List.length_cons, List.length_nil] at probes ticks
+ change (trees v).preorder.length ≤ c.occurrences (fun _ => 1) v at len
+ exact ⟨es, visit, by omega, by omega⟩
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalLayerExecution.lean b/lean/OAI/Computability/VPVNP/PairTraversalLayerExecution.lean
new file mode 100644
index 0000000000..74f34816ad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalLayerExecution.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.PairTraversalRows
+import OAI.Computability.VPVNP.PairTraversalRowExecution
+
+/-!
+# Native identifier translation over a complete descriptor layer
+
+Scan and header routines are run once per site. All counts and source lists are
+below the destination layer. Each call writes just its two header words and its
+live children, so source records survive every visit and row padding retains
+its initial contents.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open BurstRAM CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The two native routines for every site in the supplied order, passing the
+actual external memory and concatenating their emitted events. -/
+inductive LayerPasses (L : Layer) (cap previous base : ℕ) (state : Word w)
+ (priv : Word w → Word w) (counts starts : Fin L.count → Word w) :
+ List (Fin L.count) → Memory w → List (Event w) → Prop
+ | nil (m : Memory w) : LayerPasses L cap previous base state priv counts starts [] m []
+ | cons {i is m ss es}
+ (site : DescriptorRows.NativePass Fin.elim0 state priv m
+ (address cap base i.val) (starts i).val (address cap base i.val + 2)
+ (counts i) (previous : Word w) ((cap + 2 : ℕ) : Word w)
+ ((L.ids i).map (fun j : ℕ => (j : Word w))) ss)
+ (tail : LayerPasses L cap previous base state priv counts starts is (after m ss) es) :
+ LayerPasses L cap previous base state priv counts starts (i :: is) m (ss ++ es)
+
+private def live (L : Layer) (cap base : ℕ) (i : Fin L.count) (x : ℕ) : Prop :=
+ address cap base i.val ≤ x ∧ x < address cap base i.val + 2 + (L.ids i).length
+
+private theorem agree_row {m m' : Memory w} {n : ℕ} {kids : List (Word w)}
+ (h : DFS.Row m n (n + 2) kids) (h' : DFS.Row m' n (n + 2) kids)
+ (x : ℕ) (lo : n ≤ x) (hi : x < n + 2 + kids.length) : m x = m' x := by
+ rcases Nat.eq_or_lt_of_le lo with rfl | hx
+ · exact h.2.2.1.trans h'.2.2.1.symm
+ rcases Nat.eq_or_lt_of_le hx with rfl | hx
+ · exact h.2.2.2.1.trans h'.2.2.2.1.symm
+ let j : Fin kids.length := ⟨x - (n + 2), by omega⟩
+ have eqn : n + 2 + j.val = x := by dsimp [j]; omega
+ exact eqn ▸ (h.2.2.2.2 j).trans (h'.2.2.2.2 j).symm
+
+private theorem pass_outside {L : Layer} {cap previous base : ℕ} {state : Word w}
+ {priv : Word w → Word w} {m : Memory w} {i : Fin L.count} {start : ℕ} {count : Word w}
+ {ss : List (Event w)}
+ (h : DescriptorRows.NativePass Fin.elim0 state priv m
+ (address cap base i.val) start (address cap base i.val + 2) count
+ (previous : Word w) ((cap + 2 : ℕ) : Word w) ((L.ids i).map (fun j : ℕ => (j : Word w))) ss)
+ (x : ℕ) (hx : ¬ live L cap base i x) : after m ss x = m x := by
+ let n := address cap base i.val
+ have hn : n + 1 < 2 ^ w := h.row.1
+ change ¬ (n ≤ x ∧ x < n + 2 + (L.ids i).length) at hx
+ rw [h.memory]
+ change DescriptorRows.passMemory m n start (n + 2) count _ _ _ x = m x
+ simp only [DescriptorRows.passMemory, DescriptorRows.rowMemory, writeMemory, Fin.val_natCast,
+ Nat.mod_eq_of_lt hn, Nat.mod_eq_of_lt (by omega : n < 2 ^ w), List.length_map,
+ ite_eq_right (by omega : x ≠ n), ite_eq_right (by omega : x ≠ n + 1),
+ ite_eq_right (by omega : ¬ (n + 2 ≤ x ∧ x < n + 2 + (L.ids i).length))]
+
+private theorem scanned_addresses (L : Layer) (i : Fin L.count) (cap previous : ℕ) :
+ ((L.ids i).map (fun j : ℕ => (j : Word w))).map
+ (DescriptorRows.address (previous : Word w) ((cap + 2 : ℕ) : Word w)) =
+ childWords w cap previous L i := by
+ unfold childWords
+ rw [List.map_map]
+ congr 1
+ funext j
+ simp only [DescriptorRows.address, Function.comp_apply, address, Nat.cast_add, Nat.cast_mul,
+ Nat.cast_ofNat]
+ ring
+
+private theorem append_probes (ss es : List (Event w)) :
+ countProbes (ss ++ es) = countProbes ss + countProbes es := by
+ induction ss with
+ | nil => simp [countProbes]
+ | cons e ss ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+open private row_end_le from OAI.Computability.VPVNP.PairTraversalRows
+
+/-- Running the identifier and header routines in site-number order constructs
+the specified memory image. The scan spends two probes per child and three
+per output site. -/
+theorem native_layer (L : Layer) (cap previous base : ℕ) (state : Word w)
+ (priv : Word w → Word w) (counts starts : Fin L.count → Word w) (mem : Memory w)
+ (hrow : ∀ i, rowRepresents mem (counts i) (starts i)
+ ((L.ids i).map (fun j : ℕ => (j : Word w))))
+ (countBefore : ∀ i, (counts i).val < base)
+ (sourceBefore : ∀ i, (starts i).val + (L.ids i).length ≤ base)
+ (hc : ∀ i, (L.ids i).length ≤ cap) (fit : endPos cap base L < 2 ^ w) :
+ ∃ es, LayerPasses L cap previous base state priv counts starts (List.finRange L.count) mem es ∧
+ after mem es = writeLayer cap previous base L mem ∧
+ countProbes es = 2 * (∑ i, (L.ids i).length) + 3 * L.count := by
+ classical
+ let target := writeLayer cap previous base L mem
+ have rows := writeLayer_rows cap previous base L mem hc fit
+ have run (xs : List (Fin L.count)) (m : Memory w)
+ (source : ∀ x < base, m x = mem x) :
+ ∃ es, LayerPasses L cap previous base state priv counts starts xs m es ∧
+ (∀ x, (∃ i ∈ xs, live L cap base i x) → after m es x = target x) ∧
+ (∀ x, (∀ i ∈ xs, ¬ live L cap base i x) → after m es x = m x) ∧
+ countProbes es = 2 * (xs.map (fun i => (L.ids i).length)).sum + 3 * xs.length := by
+ induction xs generalizing m with
+ | nil => exact ⟨[], .nil m, by simp, fun _ _ => rfl, by simp [countProbes]⟩
+ | cons i xs ih =>
+ let n := address cap base i.val
+ let ids := (L.ids i).map (fun j : ℕ => (j : Word w))
+ have hids : ids.length = (L.ids i).length := List.length_map _
+ have lower : base ≤ n := Nat.le_add_right _ _
+ have upper : n + (cap + 2) ≤ endPos cap base L := row_end_le _ _ _ _
+ have capacity := hc i
+ have represented : rowRepresents m (counts i) ((starts i).val : Word w) ids := by
+ have start : ((starts i).val : Word w) = starts i :=
+ Fin.ext (Nat.mod_eq_of_lt (starts i).isLt)
+ rw [start]
+ obtain ⟨hcount, hcells⟩ := hrow i
+ refine ⟨(congrArg Fin.val (source _ (countBefore i))).trans hcount, fun j => ?_⟩
+ have hj := Nat.add_lt_add_left (j.isLt.trans_eq hids) (starts i).val
+ exact (source _ (hj.trans_le (sourceBefore i))).trans (hcells j)
+ obtain ⟨ss, pass⟩ := DescriptorRows.native_pass Fin.elim0 state priv m n (starts i).val
+ (n + 2) (counts i) (previous : Word w) ((cap + 2 : ℕ) : Word w) ids represented
+ (by rw [hids]; have := sourceBefore i; omega) (by have := countBefore i; omega)
+ (by omega) (by rw [hids]; omega)
+ have skip (x : ℕ) (hx : ¬ live L cap base i x) : after m ss x = m x := pass_outside pass x hx
+ have mid (x : ℕ) (hx : x < base) : after m ss x = mem x :=
+ (skip x (fun live => hx.not_ge (lower.trans live.1))).trans (source x hx)
+ have same (x : ℕ) (hx : live L cap base i x) : after m ss x = target x := by
+ have exactRow : DFS.Row (after m ss) n (n + 2) (childWords w cap previous L i) :=
+ (scanned_addresses L i cap previous) ▸ pass.row
+ apply agree_row exactRow (rows i).2 x hx.1
+ simpa only [childWords, List.length_map] using hx.2
+ obtain ⟨es, tail, applied, outside, probes⟩ := ih (after m ss) mid
+ have replay : after m (ss ++ es) = after (after m ss) es := List.foldl_append
+ refine ⟨ss ++ es, .cons pass tail, ?_, ?_, ?_⟩
+ · intro x h
+ rw [replay]
+ by_cases later : ∃ j ∈ xs, live L cap base j x
+ · exact applied x later
+ · rw [outside x (by simpa only [not_exists, not_and] using later)]
+ obtain ⟨j, hj, hl⟩ := h
+ rcases List.mem_cons.mp hj with rfl | hj
+ · exact same _ hl
+ · exact (later ⟨j, hj, hl⟩).elim
+ · intro x h
+ rw [replay, outside x (fun j hj => h j (List.mem_cons_of_mem _ hj))]
+ exact skip x (h i List.mem_cons_self)
+ · rw [append_probes, pass.probes, hids, probes, List.map_cons, List.sum_cons,
+ List.length_cons]
+ omega
+ obtain ⟨es, runs, applied, outside, probes⟩ := run (List.finRange L.count) mem (fun _ _ => rfl)
+ refine ⟨es, runs, ?_, ?_⟩
+ · funext x
+ by_cases h : ∃ i, live L cap base i x
+ · obtain ⟨i, hi⟩ := h
+ exact applied x ⟨i, List.mem_finRange _, hi⟩
+ · rw [outside x (fun i _ hi => h ⟨i, hi⟩)]
+ exact (writeLayer_unchanged cap previous base L mem x h).symm
+ · simpa only [← List.ofFn_eq_map, List.sum_ofFn, List.length_finRange] using probes
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalLayerSegment.lean b/lean/OAI/Computability/VPVNP/PairTraversalLayerSegment.lean
new file mode 100644
index 0000000000..8f71d62a99
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalLayerSegment.lean
@@ -0,0 +1,208 @@
+import OAI.Computability.VPVNP.PairTraversalNativeLayer
+import OAI.Computability.VPVNP.PairTraversalSiteWorker
+
+/-!
+# Consecutive reset-entry calls for one traversal layer
+
+The persistent word counts the sites already translated. Every call starts
+with fresh private registers and memory and reads the raw rows that remain
+below the descriptor arena. The sequence constructs the exact descriptor
+image used by the traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open BurstRAM CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ} {C : Type*}
+
+/-- The native site worker reads one row from its directory, publishes its
+descriptor, and returns the successor cursor. -/
+def SiteWorkerRun (P : BurstRAM.Program w C) (fuel : ℕ) (L : Layer) (cap previous base : ℕ)
+ (counts starts : Fin L.count → Word w) : Prop :=
+ ∀ (i : Fin L.count) (mem : Memory w), rowRepresents mem (counts i) (starts i)
+ ((L.ids i).map (fun j : ℕ => (j : Word w))) →
+ ∃ es, execute P fuel (P.start (i.val : Word w)) mem [] =
+ some ⟨es, some ((i.val : Word w) + 1)⟩ ∧
+ after mem es = DescriptorRows.passMemory mem (address cap base i.val) (starts i).val
+ (address cap base i.val + 2) (counts i) (previous : Word w) ((cap + 2 : ℕ) : Word w)
+ (L.ids i).length ∧
+ countProbes es = 2 * (L.ids i).length + 3 ∧ es.length = 7 * (L.ids i).length + 24
+
+private theorem finRange_numbers (n : ℕ) : (List.finRange n).map Fin.val = List.range' 0 n := by
+ rw [← List.range_eq_range']
+ apply List.ext_getElem
+ · simp
+ · intro j hj hk
+ simp
+
+open private pass_outside live append_probes from OAI.Computability.VPVNP.PairTraversalLayerExecution
+
+private theorem realize_passes {L : Layer} {cap previous base : ℕ} {state : Word w}
+ {priv : Word w → Word w} {counts starts : Fin L.count → Word w}
+ {P : BurstRAM.Program w C} {fuel : ℕ}
+ (worker : SiteWorkerRun P fuel L cap previous base counts starts)
+ (countBefore : ∀ i, (counts i).val < base)
+ (sourceBefore : ∀ i, (starts i).val + (L.ids i).length ≤ base)
+ {xs : List (Fin L.count)} {mem : Memory w} {es : List (Event w)}
+ (passes : LayerPasses L cap previous base state priv counts starts xs mem es)
+ (row : ∀ i, rowRepresents mem (counts i) (starts i) ((L.ids i).map (fun j : ℕ => (j : Word w))))
+ (start : ℕ) (order : xs.map Fin.val = List.range' start xs.length) :
+ ∃ rs, runSegment P fuel (some (start : Word w)) mem (List.replicate xs.length []) = some rs ∧
+ endState (some (start : Word w)) rs = some ((start + xs.length : ℕ) : Word w) ∧
+ after mem (eventLog rs) = after mem es ∧ countProbes (eventLog rs) = countProbes es ∧
+ List.Forall₂ (fun (rep : Report w) (i : Fin L.count) =>
+ rep.probes = 2 * (L.ids i).length + 3 ∧ rep.events.length = 7 * (L.ids i).length + 24)
+ rs xs := by
+ induction passes generalizing start with
+ | nil m => exact ⟨[], rfl, by simp [endState], rfl, rfl, .nil⟩
+ | @cons i is m ss es site tail ih =>
+ simp only [List.map_cons, List.length_cons, List.range'_succ, List.cons.injEq] at order
+ rcases order with ⟨rfl, remaining⟩
+ obtain ⟨ev, executeSite, image, probes, steps⟩ := worker i m (row i)
+ let rep : Report w := ⟨ev, some ((i.val : Word w) + 1)⟩
+ have equalMemory : after m ev = after m ss := by
+ rw [image, site.memory, List.length_map]
+ have same (x : ℕ) (h : x < base) : after m ss x = m x := by
+ apply pass_outside site x
+ intro inside
+ exact h.not_ge ((Nat.le_add_right base _).trans inside.1)
+ have rowsNext (j : Fin L.count) : rowRepresents (after m ss) (counts j) (starts j)
+ ((L.ids j).map (fun a : ℕ => (a : Word w))) := by
+ refine ⟨(congrArg Fin.val (same _ (countBefore j))).trans (row j).1, fun p => ?_⟩
+ have hp : p.val < (L.ids j).length := by simpa only [List.length_map] using p.isLt
+ exact (same _ ((Nat.add_lt_add_left hp _).trans_le (sourceBefore j))).trans ((row j).2 p)
+ obtain ⟨rs, segment, final, replay, cost, calls⟩ := ih rowsNext (i.val + 1) remaining
+ have next : some ((i.val : Word w) + 1) = some ((i.val + 1 : ℕ) : Word w) := by simp
+ refine ⟨rep :: rs, ?_, ?_, ?_, ?_, .cons ⟨probes, steps⟩ calls⟩
+ · rw [List.length_cons, List.replicate_succ, runSegment, executeSite]
+ change (runSegment P fuel (some ((i.val : Word w) + 1)) (after m ev)
+ (List.replicate is.length [])).map (rep :: ·) = _
+ rw [equalMemory, next, segment]
+ rfl
+ · change endState (some ((i.val : Word w) + 1)) rs = _
+ rw [next, final, List.length_cons, Nat.add_right_comm, Nat.add_assoc]
+ · change after m (ev ++ eventLog rs) = after m (ss ++ es)
+ rw [show after m (ev ++ eventLog rs) = after (after m ev) (eventLog rs)
+ from List.foldl_append,
+ show after m (ss ++ es) = after (after m ss) es from List.foldl_append, equalMemory]
+ exact replay
+ · change countProbes (ev ++ eventLog rs) = countProbes (ss ++ es)
+ rw [append_probes, append_probes, cost, probes, site.probes, List.length_map]
+
+/-- Run one call for every site from cursor zero. Each report's instruction and
+probe counts are tied to that site's actual number of children. -/
+theorem run_numbered_layer (P : BurstRAM.Program w C) (fuel : ℕ) (L : Layer) (cap previous base : ℕ)
+ (counts starts : Fin L.count → Word w) (mem : Memory w)
+ (worker : SiteWorkerRun P fuel L cap previous base counts starts)
+ (rows : ∀ i, rowRepresents mem (counts i) (starts i)
+ ((L.ids i).map (fun j : ℕ => (j : Word w))))
+ (countBefore : ∀ i, (counts i).val < base)
+ (sourceBefore : ∀ i, (starts i).val + (L.ids i).length ≤ base)
+ (capacity : ∀ i, (L.ids i).length ≤ cap) (fit : endPos cap base L < 2 ^ w) :
+ ∃ rs, runSegment P fuel (some 0) mem (List.replicate L.count []) = some rs ∧
+ endState (some 0) rs = some (L.count : Word w) ∧
+ after mem (eventLog rs) = writeLayer cap previous base L mem ∧
+ countProbes (eventLog rs) = 2 * (∑ i, (L.ids i).length) + 3 * L.count ∧
+ rs.length = L.count ∧
+ List.Forall₂ (fun (rep : Report w) (i : Fin L.count) =>
+ rep.probes = 2 * (L.ids i).length + 3 ∧ rep.events.length = 7 * (L.ids i).length + 24)
+ rs (List.finRange L.count) := by
+ obtain ⟨es, passes, image, cost⟩ := native_layer L cap previous base 0 (fun _ => 0)
+ counts starts mem rows countBefore sourceBefore capacity fit
+ obtain ⟨rs, run, final, replay, probes, calls⟩ := realize_passes worker countBefore sourceBefore
+ passes rows 0 (by simpa only [List.length_finRange] using finRange_numbers L.count)
+ exact ⟨rs, by simpa using run, by simpa using final, replay.trans image, probes.trans cost,
+ calls.length_eq.trans List.length_finRange, calls⟩
+
+/-- The first three words address the raw counts and preimage array. The
+remaining words address the old and new descriptor layers at their common stride. -/
+def workerData (pub : Fin 6 → Word w) (cap previous base : ℕ) : Fin 6 → Word w :=
+ ![pub 3, pub 5, pub 4, (previous : Word w), (base : Word w), ((cap + 2 : ℕ) : Word w)]
+
+open private row_end_le from OAI.Computability.VPVNP.PairTraversalRows
+
+/-- The same six-parameter instruction table realizes every site in a directory. -/
+theorem directory_worker (pub : Fin 6 → Word w) (L : Layer) (cap previous base : ℕ)
+ (sourceBefore : ∀ i : Fin L.count, (rowAt pub (i.val : Word w)).val + (L.ids i).length ≤ base)
+ (capacity : ∀ i, (L.ids i).length ≤ cap) (fit : endPos cap base L < 2 ^ w) :
+ let M := (SiteWorker.program.template (some 6)).instantiate w (workerData pub cap previous base)
+ SiteWorkerRun M.program (7 * cap + 25) L cap previous base
+ (fun i => countAt pub (i.val : Word w)) (fun i => rowAt pub (i.val : Word w)) := by
+ let data := workerData pub cap previous base
+ dsimp only
+ intro i mem row
+ let src := (rowAt pub (i.val : Word w)).val
+ let node := address cap base i.val
+ have hs : SiteWorker.source data (i.val : Word w) = (src : Word w) :=
+ Fin.ext (Nat.mod_eq_of_lt (rowAt pub (i.val : Word w)).isLt).symm
+ have hn : SiteWorker.node data (i.val : Word w) = (node : Word w) := by
+ change (base : Word w) + (i.val : Word w) * ((cap + 2 : ℕ) : Word w) =
+ ((base + (cap + 2) * i.val : ℕ) : Word w)
+ simp only [Nat.cast_add, Nat.cast_mul]
+ rw [mul_comm]
+ have cnt : (mem (SiteWorker.counter data (i.val : Word w)).val).val = (L.ids i).length := by
+ change (mem (countAt pub (i.val : Word w)).val).val = _
+ simpa only [List.length_map] using row.1
+ have within : node + 2 + (L.ids i).length < 2 ^ w := by
+ have := row_end_le cap base L i
+ have := capacity i
+ dsimp only [node]
+ omega
+ exact SiteWorker.native data (i.val : Word w) mem src node (L.ids i).length (7 * cap + 25)
+ hs hn cnt ((sourceBefore i).trans (Nat.le_add_right _ _)) within (by have := capacity i; omega)
+
+open NetworkKernel LocalHistory
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+variable {N : Network} {t : Term A N}
+
+open private valid_owner from OAI.Computability.VPVNP.PairTraversalNativeLayer
+
+open Classical in
+/-- The fixed site worker runs from cursor zero through a selected term's entire
+output layer, with one reset-entry call per new site. -/
+theorem run_step_layer (old : Order N.Site) (next : Order t.output.Site) (r : TermParsers κ t)
+ (physical : Word w → Word w) (realizes : RepresentsPlacement old next t.place physical)
+ (hchildren : ∀ v, r.order.children v = old.restrict (fun u => v = t.place u))
+ (pub : Fin 6 → Word w) (mem : Memory w) (oldCount : (pub 0).val = old.length)
+ (newCount : (pub 2).val = next.length) (collected : PreimagesAt pub physical mem old.length)
+ (cap previous base : ℕ) (regions : RowRegions pub)
+ (inputEnd : (pub 5).val + (pub 2).val * (pub 4).val ≤ base)
+ (capacity : ∀ i, ((stepLayer old next r).ids i).length ≤ min (pub 4).val cap)
+ (fit : endPos cap base (stepLayer old next r) < 2 ^ w) :
+ let L := stepLayer old next r
+ let M := (SiteWorker.program.template (some 6)).instantiate w (workerData pub cap previous base)
+ ∃ rs, runSegment M.program (7 * cap + 25) (some 0) mem (List.replicate next.length []) =
+ some rs ∧
+ endState (some 0) rs = some (next.length : Word w) ∧
+ after mem (eventLog rs) = writeLayer cap previous base L mem ∧
+ countProbes (eventLog rs) = 2 * old.length + 3 * next.length ∧ rs.length = next.length ∧
+ List.Forall₂ (fun (rep : Report w) (i : Fin next.length) =>
+ rep.probes = 2 * (L.ids i).length + 3 ∧ rep.events.length = 7 * (L.ids i).length + 24)
+ rs (List.finRange next.length) := by
+ let L := stepLayer old next r
+ have before (i : Fin L.count) := preimage_input_before regions inputEnd (valid_owner newCount i)
+ have hs (i : Fin L.count) : (rowAt pub (i.val : Word w)).val + (L.ids i).length ≤ base :=
+ (Nat.add_le_add_left ((le_min_iff.mp (capacity i)).1) _).trans (before i).2
+ have hc (i : Fin L.count) : (L.ids i).length ≤ cap := (le_min_iff.mp (capacity i)).2
+ obtain ⟨rs, run, final, image, probes, count, calls⟩ := run_numbered_layer _ _ L cap previous base
+ _ _ mem (directory_worker pub L cap previous base hs hc fit)
+ (raw_rows_of_preimages old next r physical realizes hchildren pub mem oldCount newCount
+ collected)
+ (fun i => (before i).1) hs hc fit
+ refine ⟨rs, run, final, image, ?_, count, calls⟩
+ have h : ∑ i : Fin L.count, (L.ids i).length = old.length := stepLayer_sum_ids_length old next r
+ rw [probes, h]
+ rfl
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalLeafWorker.lean b/lean/OAI/Computability/VPVNP/PairTraversalLeafWorker.lean
new file mode 100644
index 0000000000..d9f05d0593
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalLeafWorker.lean
@@ -0,0 +1,183 @@
+import OAI.Computability.VPVNP.PairTraversalRows
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+
+/-!
+# Writing the source-free leaf headers
+
+The initial layer has no children. Its fixed worker computes the header address
+from the site cursor, base and descriptor stride. It writes the pointer and a
+zero count directly. Padding and other external words keep their old contents.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows.LeafWorker
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM PrimedCounter LocalHistory
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private def ops : List (Op 4 2) :=
+ [.stateWord 0, .publicWord 1 1, .binary .mul 1 1 0, .publicWord 2 0,
+ .binary .add 1 2 1, .constant 2 2, .binary .add 2 1 2, .write 1 2,
+ .constant 2 1, .binary .add 1 1 2, .constant 3 0, .write 1 3, .binary .add 0 0 2]
+
+/-- Fixed native instruction program that writes the empty child row for one cursor leaf. -/
+def program : Flow 4 2 := lines ops (by decide)
+
+/-- Encode the leaf layer's row base and per-site pitch as the worker's two directory words. -/
+def directory (w cap base : ℕ) : Fin 2 → Word w :=
+ ![(base : Word w), ((cap + 2 : ℕ) : Word w)]
+
+private def events (node : Word w) : List (Event w) :=
+ [.tick, .tick, .tick, .tick, .tick, .tick, .tick, .write node (node + 2),
+ .tick, .tick, .tick, .write (node + 1) 0, .tick]
+
+/-- From the reset entry, emit exactly the two leaf header writes. -/
+theorem native (cap base j fuel : ℕ) (mem : Memory w) (clock : 13 < fuel) :
+ let pub := directory w cap base
+ let M := (program.template (some 0)).instantiate w pub
+ let node := (address cap base j : Word w)
+ execute M.program fuel (M.program.start (j : Word w)) mem [] =
+ some ⟨events node, some ((j + 1 : ℕ) : Word w)⟩ := by
+ let pub := directory w cap base
+ let node := (address cap base j : Word w)
+ have h : ∃ rs, Flow.Exec pub (j : Word w) program (fun _ => 0) mem (events node) rs
+ (writeMemory (writeMemory mem node (node + 2)) (node + 1) 0) ∧
+ rs 0 = ((j + 1 : ℕ) : Word w) := by
+ simp only [program, Admin.exec_lines_iff_trace]
+ simp (config := { decide := true }) [ops, trace, Op.effect, BinaryOp.eval, Function.update,
+ pub, node, directory, address, Nat.cast_add, Nat.cast_mul, events]
+ obtain ⟨rs, run, ret⟩ := h
+ apply (Flow.template_execute_iff program (some 0) pub (j : Word w) (fun _ => 0) (fun _ => 0)
+ mem fuel [] _).mpr
+ exact ⟨rs, _, run, by simp only [Option.map_some, ret], clock, rfl⟩
+
+open private cell layer_at row_end_le from OAI.Computability.VPVNP.PairTraversalRows
+
+private theorem padding {I : Type} (old : Order I) (cap previous base : ℕ) (mem : Memory w)
+ (i : Fin old.length) (x : ℕ) (lo : address cap base i.val + 2 ≤ x)
+ (hi : x < address cap base (i.val + 1)) :
+ writeLayer cap previous base (leafLayer old) mem x = mem x := by
+ let n := address cap base i.val
+ have bound : x < n + (cap + 2) := by simpa only [n, address, Nat.mul_succ, Nat.add_assoc] using hi
+ obtain ⟨z, hz⟩ := Nat.exists_eq_add_of_le lo
+ have eqn : x = address cap base i.val + (z + 2) := by omega
+ rw [eqn, layer_at cap previous base (leafLayer old) mem i (z + 2)
+ (by change x < address cap base i.val + (cap + 2) at bound; omega)]
+ simp [cell, childWords, leafLayer]
+
+/-- A complete leaf pass from site zero on arbitrary initial external memory. -/
+theorem run_layer {I : Type} (initial : Order I) (cap previous base : ℕ)
+ (mem : Memory w) (fuel : ℕ) (fit : endPos cap base (leafLayer initial) < 2 ^ w)
+ (clock : 13 < fuel) :
+ let M := (program.template (some 0)).instantiate w (directory w cap base)
+ ∃ rs, runSegment M.program fuel (some 0) mem (List.replicate initial.length []) = some rs ∧
+ endState (some 0) rs = some (initial.length : Word w) ∧
+ after mem (eventLog rs) = writeLayer cap previous base (leafLayer initial) mem ∧
+ rs.length = initial.length ∧ countProbes (eventLog rs) = 2 * initial.length ∧
+ ∀ rep ∈ rs, rep.probes = 2 ∧ rep.events.length = 13 := by
+ let M := (program.template (some 0)).instantiate w (directory w cap base)
+ let L := leafLayer initial
+ let target := writeLayer cap previous base L mem
+ change endPos cap base L < 2 ^ w at fit
+ have rows : L.Rows w target cap previous base :=
+ writeLayer_rows cap previous base L mem (fun _ => Nat.zero_le _) fit
+ have work (k : ℕ) (hk : k ≤ initial.length) :
+ ∃ rs, runSegment M.program fuel (some 0) mem (List.replicate k []) = some rs ∧
+ endState (some 0) rs = some (k : Word w) ∧
+ (∀ x, after mem (eventLog rs) x =
+ if x < address cap base k then target x else mem x) ∧
+ rs.length = k ∧ countProbes (eventLog rs) = 2 * k ∧
+ ∀ rep ∈ rs, rep.probes = 2 ∧ rep.events.length = 13 := by
+ induction k with
+ | zero =>
+ refine ⟨[], rfl, rfl, ?_, rfl, rfl, by simp⟩
+ intro x
+ change mem x = _
+ by_cases hx : x < base
+ · rw [ite_eq_left (by simpa [address] using hx)]
+ apply (writeLayer_unchanged cap previous base L mem x _).symm
+ rintro ⟨i, lo, _⟩
+ exact hx.not_ge ((Nat.le_add_right _ _).trans lo)
+ · rw [ite_eq_right (by simpa [address] using hx)]
+ | succ k ih =>
+ obtain ⟨rs, prev, endAt, contents, calls, probes, per⟩ := ih (Nat.le_of_succ_le hk)
+ let m := after mem (eventLog rs)
+ let n := address cap base k
+ let i : Fin initial.length := ⟨k, hk⟩
+ let next := address cap base (k + 1)
+ let rep : Report w := ⟨events (n : Word w), some ((k + 1 : ℕ) : Word w)⟩
+ have nativeCall : execute M.program fuel (M.program.start (k : Word w))
+ (after mem (eventLog rs)) [] = some rep := native cap base k fuel m clock
+ have inc : next = n + (cap + 2) := by simp [next, n, address, Nat.mul_succ, Nat.add_assoc]
+ have room : n + (cap + 2) ≤ endPos cap base L := row_end_le cap base L i
+ have nodeVal : (n : Word w).val = n := Nat.mod_eq_of_lt (by omega)
+ have nextVal : ((n : Word w) + 1).val = n + 1 := by
+ rw [← Nat.cast_one (R := Word w), ← Nat.cast_add]
+ exact Nat.mod_eq_of_lt (by omega)
+ refine ⟨rs ++ [rep], ?_, ?_, ?_, by simp [calls], ?_, ?_⟩
+ · rw [List.replicate_succ', PrimedSchedule.runSegment_append, prev]
+ simp only [Option.bind_some, endAt, runSegment, nativeCall, Option.map_some]
+ · rw [endState_append]
+ rfl
+ · intro x
+ have replay : after mem (eventLog (rs ++ [rep])) = after m rep.events := by
+ simp only [eventLog, List.flatMap_append, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil, after, List.foldl_append, m]
+ rw [replay]
+ change writeMemory (writeMemory m (n : Word w) ((n : Word w) + 2))
+ ((n : Word w) + 1) 0 x = if x < next then target x else mem x
+ have row := (rows i).2
+ by_cases h₁ : x = n + 1
+ · subst x
+ rw [ite_eq_left (by omega), writeMemory, nextVal, ite_eq_left rfl]
+ exact row.2.2.2.1.symm
+ rw [writeMemory, nextVal, ite_eq_right h₁]
+ by_cases h₀ : x = n
+ · subst x
+ rw [ite_eq_left (by omega), writeMemory, nodeVal, ite_eq_left rfl]
+ simpa only [Nat.cast_add, Nat.cast_ofNat] using row.2.2.1.symm
+ rw [writeMemory, nodeVal, ite_eq_right h₀, show m x = _ from contents x]
+ by_cases below : x < n
+ · rw [ite_eq_left below, ite_eq_left (by omega)]
+ · rw [ite_eq_right below]
+ split
+ · rename_i inside
+ exact (padding initial cap previous base mem i x
+ (by change n + 2 ≤ x; omega) inside).symm
+ · rfl
+ · have es : eventLog (rs ++ [rep]) = eventLog rs ++ rep.events := by
+ simp [eventLog]
+ rw [es, countProbes_append, probes]
+ change 2 * k + 2 = 2 * (k + 1)
+ omega
+ · intro r hr
+ rcases List.mem_append.mp hr with hr | hr
+ · exact per _ hr
+ · obtain rfl := List.mem_singleton.mp hr
+ exact ⟨rfl, rfl⟩
+ obtain ⟨rs, run, endAt, contents, calls, probes, per⟩ := work initial.length le_rfl
+ refine ⟨rs, run, endAt, ?_, calls, probes, per⟩
+ funext x
+ rw [contents]
+ split
+ · rfl
+ · rename_i beyond
+ apply (writeLayer_unchanged cap previous base L mem x _).symm
+ rintro ⟨i, _, last⟩
+ have room := row_end_le cap base L i
+ change x < address cap base i.val + 2 + 0 at last
+ change address cap base i.val + (cap + 2) ≤ address cap base initial.length at room
+ omega
+
+end PairSimulation.TraversalRows.LeafWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalLevelDirectories.lean b/lean/OAI/Computability/VPVNP/PairTraversalLevelDirectories.lean
new file mode 100644
index 0000000000..148aaf0b7b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalLevelDirectories.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.PairTraversalDirectories
+
+/-!
+# Transferring physical preimage directories to the selected term chain
+
+The shrink and refresh scanners retain their level number in the public table
+layout. A directory for each selected level therefore gives the directories
+of the selected chain, with the same physical old- and new-site numbering.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open CompressorRecords NetworkKernel LocalHistory Compression BurstRAM
+
+variable {w : ℕ} {k A : Type*} [Field k] [CommRing A] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f}
+
+/-- The completed placement scan attached to one concrete compressor level. -/
+abbrev LevelDirectory (v : SelectedLevel B f hf) (raw : Memory w) (limit : ℕ) :=
+ Directory (v.pass.step.term v.term) (siteOrder v.input)
+ ((v.pass.output_eq v.term).symm ▸ siteOrder (v.pass.next v.term)) raw limit
+
+open private castOrders from OAI.Computability.VPVNP.PairTraversalSelectedOrder
+open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels
+
+omit [CommRing A] in
+private def castDirectories {N M Y : Network} (h : N = M) (c : TermChain A M Y)
+ (ord : ChainOrders c) (old : Order M.Site) (raw : Memory w) (limit : ℕ)
+ (dirs : Directories raw limit c ord old) :
+ Directories raw limit (h.symm ▸ c : TermChain A N Y) (castOrders h c ord) (h.symm ▸ old) := by
+ cases h
+ exact dirs
+
+private noncomputable def collectDirectories {a g b n : ℕ} {X : State a g}
+ (E : StateExecution A b n X) (W : E.MapWitnesses f) (r : ExecutionReaders E W)
+ (o : PassOrigins B f hf E) (data : E.Records) (z : E.Choices) (raw : Memory w) (limit : ℕ)
+ (ds : let vs := collectLevels B f hf E W r o z
+ (i : Fin vs.length) → LevelDirectory vs[i] raw limit) :
+ Directories raw limit (E.termChain data z) (branchOrders E data z) (siteOrder X) := by
+ induction E with
+ | done => exact PUnit.unit
+ | more p tail ih =>
+ let E' := tail z.1
+ let data' := data.2 z.1
+ let vs := collectLevels B f hf E' (W.2 z.1) (r.2 z.1) (o.2 z.1) z.2
+ let old' := siteOrder (p.next z.1)
+ let c := E'.termChain data' z.2
+ let ords := branchOrders E' data' z.2
+ have rest (i : Fin vs.length) : LevelDirectory vs[i] raw limit := ds i.succ
+ exact ⟨ds ⟨0, Nat.zero_lt_succ _⟩, castDirectories (p.output_eq z.1) c ords old' raw limit
+ (ih z.1 (W.2 z.1) (r.2 z.1) (o.2 z.1) data' z.2 rest)⟩
+
+variable (B f hf) {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+variable (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+
+/-- Transfer every indexed scan output to the corresponding DFS row worker.
+Using the actual list index also covers repeated, equal level records at
+different physical addresses. -/
+noncomputable def selectedDirectories (raw : Memory w) (limit : ℕ)
+ (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] raw limit) :
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ Directories raw limit (E.termChain data z) (branchOrders E data z) (siteOrder X) :=
+ collectDirectories _ _ _ _ _ _ raw limit ds
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalLowReplay.lean b/lean/OAI/Computability/VPVNP/PairTraversalLowReplay.lean
new file mode 100644
index 0000000000..82775afa4a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalLowReplay.lean
@@ -0,0 +1,219 @@
+import OAI.Computability.VPVNP.PairTraversalControllerSelectedRun
+import OAI.Computability.VPVNP.PairTraversalControllerTerminal
+import OAI.Computability.VPVNP.PairTerminalQuietFrame
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-!
+# Low-address preservation in each selected traversal report
+
+The reference traversal preserves the low workspace after each tag, leaf and
+fiber call. The controller inserts read-only setup and reset reports between
+these calls. Its actual traversal therefore retains the low word at every
+call boundary, including the final sentinel.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM CompressorRecords Compression LocalHistory TraversalRows DirectoryRun TraversalRoles
+open TraversalControllerOrdinal TraversalControllerInputs
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private def Holds (x : ℕ) (v : Word w) (r : Report w) : Prop :=
+ ∀ mem : Memory w, mem x = v → after mem r.events x = v
+
+private theorem holds_of_prefixes {x : ℕ} {m : Memory w} {rs : List (Report w)}
+ (stable : ∀ i ≤ rs.length, after m (eventLog (rs.take i)) x = m x) :
+ ∀ r ∈ rs, Holds x (m x) r := by
+ intro r hr mem hv
+ obtain ⟨i, hi, rfl⟩ := List.getElem_of_mem hr
+ let entry := after m (eventLog (rs.take i))
+ have eq : mem x = entry x := hv.trans (stable i hi.le).symm
+ have next := stable (i + 1) hi
+ rw [List.take_succ_eq_append_getElem hi] at next
+ simp only [eventLog, List.flatMap_append, List.flatMap_cons, List.flatMap_nil,
+ List.append_nil, after, List.foldl_append] at next
+ exact (ControllerMemory.after_at eq rs[i].events).trans next
+
+private theorem replay_of_holds {x : ℕ} {v : Word w} {m : Memory w} {rs : List (Report w)}
+ (start : m x = v) (each : ∀ r ∈ rs, Holds x v r) : ReplayFrame x m rs := by
+ induction rs generalizing m with
+ | nil => trivial
+ | cons r rs ih =>
+ have next := each r List.mem_cons_self m start
+ exact ⟨next.trans start.symm, ih next (fun t ht => each t (List.mem_cons_of_mem r ht))⟩
+
+open private Segment.one Segment.join located_count
+ from OAI.Computability.VPVNP.PairTraversalControllerRun
+
+/-- The controller lifts a word preserved at all reference-call boundaries
+to a word preserved at every controller-call boundary. -/
+theorem Segment.replay_of_reference (pub : Fin 11 → Word w) (L N fuel x : ℕ)
+ {jobs : List (Pass w)} {m final : Memory w} {refs out : List (Report w)} {calls probes : ℕ}
+ (completed : Segment (Native.machine pub).program fuel (some 0) none m final calls probes out)
+ (ref : Reference jobs m refs) (levels : jobs.length = 2 * L) (positive : 0 < L)
+ (fit : 2 * L * (N + 1) < 2 ^ w) (counts : ∀ j : Fin jobs.length, jobs[j].count ≤ N)
+ (clock : ∀ j : Fin jobs.length, setupLen + 7 + jobs[j].clock ≤ fuel)
+ (adminClock : setupLen + 8 ≤ fuel) (stable : AtPrefixes (RunInputs pub L N jobs) m refs)
+ (rawFrame : ∀ i ≤ refs.length, after m (eventLog (refs.take i)) x = m x) :
+ ReplayFrame x m out := by
+ let P := (Native.machine pub).program
+ let good := Holds x (m x)
+ let ready := RunInputs pub L N jobs
+ have phase (j : Fin jobs.length) : j.val < 2 * L := j.isLt.trans_eq levels
+ have active (j : Fin jobs.length) :
+ ActiveCalls P fuel N (0 + j.val) 257 jobs[j] ready good good := by
+ rw [Nat.zero_add]
+ intro i entry small ok source keeps
+ obtain ⟨pre, admin, call⟩ := active_step pub entry L N j.val i.val ok.levels ok.initial
+ positive (phase j) (i.isLt.le.trans (counts j)) fit _ (ok.located j) i.isLt small source
+ have replay (mem : Memory w) : after mem (pre ++ small.events) = after mem small.events := by
+ change (pre ++ small.events).foldl update mem = _
+ rw [List.foldl_append, ← show after mem pre = pre.foldl update mem from rfl, admin.replay]
+ rfl
+ exact ⟨_, call fuel (clock j), rfl, replay entry,
+ (countProbes_append pre small.events).trans (congrArg (· + small.probes) admin.probes),
+ fun mem hv => (congrFun (replay mem) x).trans (keeps mem hv)⟩
+ have reset (j : Fin jobs.length) : ClosingCall P fuel N (0 + j.val) 257 jobs[j] ready good := by
+ rw [Nat.zero_add]
+ intro entry ok
+ obtain ⟨pre, admin, call⟩ := reset_step pub entry L N j.val jobs[j].count ok.levels ok.initial
+ positive (phase j) (counts j) fit (located_count (ok.located j)).symm
+ exact ⟨_, call fuel adminClock, rfl, admin.replay entry, admin.probes,
+ fun mem hv => (congrFun (admin.replay mem) x).trans hv⟩
+ obtain ⟨rs, stages, each⟩ := lift_passes ref N 0 257 ready stable good good
+ (holds_of_prefixes rawFrame) active reset
+ let last := after m (eventLog refs)
+ have ok : ready last := by simpa only [List.take_length] using stable _ le_rfl
+ obtain ⟨pre, admin, stop⟩ := stop_step pub last L N ok.levels ok.initial positive fit
+ let sentinel : Report w := ⟨pre, none⟩
+ have accept : Segment P fuel (some (pack N (2 * L) 0 : Word w)) none last (after last pre)
+ 1 sentinel.probes [sentinel] := Segment.one (stop fuel adminClock)
+ rw [← levels] at accept
+ rw [Nat.zero_add] at stages
+ have complete := Segment.join stages accept
+ rw [show (pack N 0 0 : Word w) = 0 by simp [pack]] at complete
+ obtain ⟨_, rfl⟩ := complete.accepted_unique completed.run completed.endAt
+ apply replay_of_holds (v := m x) rfl
+ intro r hr
+ rcases List.mem_append.mp hr with inside | endReport
+ · exact each r inside
+ · obtain rfl := List.mem_singleton.mp endReport
+ exact fun mem hv => (congrFun (admin.replay mem) x).trans hv
+
+open private tags_info selected_jobs_info
+ from OAI.Computability.VPVNP.PairTraversalControllerSelectedRun
+
+variable {k A : Type*} [Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ} (T : ℕ)
+variable (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices) (base : ℕ) (src : Memory w)
+variable (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] src base)
+variable (pub : Fin 11 → Word w) (F H first pitch : ℕ)
+variable (resident : Resident pub src H first pitch
+ (words B.recordLimit (selectedLayers B f hf T hT X z) + F) B.recordLimit base
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers (executeLevels B f hf T hT X z) ds))
+variable (heads : ∀ j ≤ (executeLevels B f hf T hT X z).length, first + j * pitch + 28 ≤ base)
+variable (below : base + 2 * words B.recordLimit (selectedLayers B f hf T hT X z) + F ≤ H)
+variable (ordinal : 2 * (selected B f hf T hT X z).length * (X.positions + 1) < 2 ^ w)
+
+include resident heads below ordinal
+
+/-- Each native controller report in the selected traversal preserves every
+address below the row base, on its actual input memory. -/
+theorem selected_low_replay {tags rows out : List (Report w)} {final : Memory w} {calls probes : ℕ}
+ (ht : RolePasses (words B.recordLimit (selectedLayers B f hf T hT X z) + F) B.recordLimit
+ base (selected B f hf T hT X z) src tags)
+ (hr : DirectoryRun.Segments (selectedJobs B f hf T hT X z base src ds)
+ (after src (eventLog tags)) rows)
+ (completed : Segment (Native.machine pub).program (callFuel B.recordLimit) (some 0) none
+ src final calls probes out) (x : ℕ) (hx : x < base) : ReplayFrame x src out := by
+ let cap := B.recordLimit
+ let tagLayers := selected B f hf T hT X z
+ let layerList := selectedLayers B f hf T hT X z
+ let bankSize := words cap layerList
+ let offset := bankSize + F
+ let directoryJobs := selectedJobs B f hf T hT X z base src ds
+ change base + 2 * bankSize + F ≤ H at below
+ change 2 * tagLayers.length * (X.positions + 1) < 2 ^ w at ordinal
+ let jobs := tagJobs w offset cap base tagLayers ++ directoryJobs.map rowJob
+ have tagSize : tagWords cap tagLayers = bankSize :=
+ congrArg (words cap) (selected_layers B f hf T hT X z)
+ have top : offset + base + tagWords cap tagLayers ≤ H := by
+ rw [tagSize]
+ dsimp only [offset]
+ omega
+ have headers := selected_reference_schedule B f hf T hT X z base src ds resident heads
+ tags rows ht hr top
+ have sched : Schedule pub src offset cap base tagLayers directoryJobs :=
+ (headers 0 (Nat.zero_le _)).1
+ have positive : 0 < tagLayers.length := Nat.succ_pos _
+ have layerEq : tagLayers.map TaggedLayer.layer = layerList := selected_layers B f hf T hT X z
+ have counts (j : Fin jobs.length) : jobs[j].count ≤ X.positions := by
+ let layer : Fin tagLayers.length := ⟨j.val % tagLayers.length, Nat.mod_lt _ positive⟩
+ rw [show jobs[j].count = _ from sched.pass_count j, (sched.lookup layer).1]
+ apply selected_layer_count_le B f hf T hT X z
+ change tagLayers[layer].layer ∈ layerList
+ rw [← layerEq]
+ exact List.mem_map_of_mem (List.getElem_mem layer.isLt)
+ have clock (j : Fin jobs.length) : setupLen + 7 + jobs[j].clock ≤ callFuel cap := by
+ apply Nat.add_le_add_left
+ rcases List.mem_append.mp (List.getElem_mem (l := jobs) j.isLt) with h | h
+ · exact ((tags_info (w := w) offset cap base tagLayers).2 _ h).trans_le (by omega)
+ · obtain ⟨j, hj, e⟩ := List.mem_map.mp h
+ exact e ▸ (selected_jobs_info B f hf T hT X z base src ds).2 j hj
+ have typed : Reference jobs src (tags ++ rows) := Reference.of_passes ht hr
+ have levels : jobs.length = 2 * tagLayers.length := by simp [jobs, sched.jobs_length, two_mul]
+ apply Segment.replay_of_reference pub tagLayers.length X.positions (callFuel cap) x completed
+ typed levels positive ordinal counts clock (by unfold callFuel; omega)
+ · intro i hi
+ obtain ⟨schedule, sites⟩ := headers i hi
+ exact ⟨schedule.total, sites, schedule.located⟩
+ · intro i hi
+ exact selected_reference_frame B f hf T hT X z base src ds offset tags rows ht hr
+ (top.trans_lt (by have := resident.headerFits; omega)) i hi x (Or.inl (by omega)) (Or.inl hx)
+
+open TerminalLink
+
+/-- Any completed physical traversal-row phase has the selected raw reports
+with precisely their terminal dispatch and handoff writes. Every report
+preserves the requested low word, on the memory supplied to that call. -/
+theorem selected_linked_low_replay (workers : Stage → LiveProgram.PairTable) (outer : ℕ)
+ (bank : workers Stage.traversalRows = ⟨Native.P, R, Native.table⟩)
+ (room : callFuel B.recordLimit + 30 ≤ outer)
+ {bs ls mem} (cand : Phase workers pub outer (.resume Stage.traversalRows 0) src bs ls mem)
+ (x : ℕ) (hx : x < base) : ReplayFrame x src (reports (header pub) ls) := by
+ have native :=
+ selected_run_with_reads B f hf T hT X z base src ds pub F H first pitch resident heads
+ below ordinal
+ dsimp only at native
+ obtain ⟨tags, rows, out, ht, hr, seg, _, _, _, _, _, _, reads, _⟩ := native
+ have known := Phase.of_source_segment (workers := workers) (pub := pub)
+ (e := Entry.resume Stage.traversalRows (0 : Word w)) room (fun _ _ => rfl) reads
+ (by
+ unfold source
+ rw [show (Entry.resume Stage.traversalRows (0 : Word w)).stage = Stage.traversalRows from rfl,
+ bank]
+ exact seg.run) seg.endAt
+ obtain ⟨_, hl, _⟩ := known.force_quiet (fun _ h => List.eq_of_mem_replicate h) cand
+ rw [hl, reports_stageLogs]
+ have head : (header pub).val = H := by
+ change (terminalHead pub).val = H
+ rw [resident.header, Fin.val_natCast, Nat.mod_eq_of_lt (by have := resident.headerFits; omega)]
+ have away : workerCell (header pub) x := TerminalFootprint.below _
+ (by rw [head]; have := resident.headerFits; omega) (by rw [head]; omega)
+ exact replayFrame_stage (header pub) _ away out src src rfl
+ (selected_low_replay B f hf T hT X z base src ds pub F H first pitch resident heads below
+ ordinal ht hr seg x hx)
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalNativeLayer.lean b/lean/OAI/Computability/VPVNP/PairTraversalNativeLayer.lean
new file mode 100644
index 0000000000..974e5d3b90
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalNativeLayer.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PairTraversalNativeRows
+import OAI.Computability.VPVNP.PairTraversalLayerExecution
+
+/-!
+# Translating the complete preimage directory of a selected term
+
+Every old position occurs in one placement fiber. After the placement scan
+has collected those fibers in old-site order, the descriptor builder reads
+and translates each identifier once and publishes one header per new site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open NetworkKernel LocalHistory BurstRAM CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ} {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+variable {N : Network} {t : Term A N}
+
+private theorem valid_owner {n : ℕ} {pub : Fin 6 → Word w}
+ (h : (pub 2).val = n) (i : Fin n) : (i.val : Word w) < pub 2 := by
+ change i.val % (2 ^ w) < (pub 2).val
+ have hi : i.val < (pub 2).val := h ▸ i.isLt
+ rw [Nat.mod_eq_of_lt (hi.trans (pub 2).isLt)]
+ exact hi
+
+open Classical in
+/-- All source rows expected by the native layer builder occur in the completed
+placement directory. The order of each row is the selected local reader's order. -/
+theorem raw_rows_of_preimages (old : Order N.Site) (next : Order t.output.Site)
+ (r : TermParsers κ t) (physical : Word w → Word w)
+ (realizes : RepresentsPlacement old next t.place physical)
+ (hchildren : ∀ v, r.order.children v = old.restrict (fun u => v = t.place u))
+ (pub : Fin 6 → Word w) (mem : Memory w)
+ (oldCount : (pub 0).val = old.length) (newCount : (pub 2).val = next.length)
+ (collected : PreimagesAt pub physical mem old.length) :
+ ∀ i : Fin next.length, rowRepresents mem (countAt pub (i.val : Word w))
+ (rowAt pub (i.val : Word w))
+ (((stepLayer old next r).ids i).map (fun j : ℕ => (j : Word w))) := by
+ intro i
+ have ho : old.length ≤ 2 ^ w := oldCount ▸ (pub 0).isLt.le
+ have hn : next.length ≤ 2 ^ w := newCount ▸ (pub 2).isLt.le
+ have eqn := preimagePrefix_eq_orderedIds old next t.place physical realizes ho hn (next.entries i)
+ rw [← hchildren] at eqn
+ simp only [siteWord, Equiv.symm_apply_apply, Fin.ofNat_eq_cast] at eqn
+ have row := collected.rows (i.val : Word w) (valid_owner newCount i)
+ rw [eqn] at row
+ convert row using 1
+ simp only [stepLayer, List.map_ofFn, orderedIds]
+ congr 1
+
+open private countAt_val rowAt_val from OAI.Computability.VPVNP.CompressorRecordPreimageScan
+
+/-- The whole source row, including any unused slots, is below the next layer's base.
+The corresponding count is strictly below that base even if the row capacity is zero. -/
+theorem preimage_input_before {pub : Fin 6 → Word w} {base : ℕ} (regions : RowRegions pub)
+ (inputEnd : (pub 5).val + (pub 2).val * (pub 4).val ≤ base) {v : Word w}
+ (hv : v < pub 2) : (countAt pub v).val < base ∧ (rowAt pub v).val + (pub 4).val ≤ base := by
+ rw [countAt_val regions hv, rowAt_val regions hv]
+ have before := regions.countsBeforeRows
+ have room := Nat.mul_le_mul_right (pub 4).val (show v.val + 1 ≤ (pub 2).val from hv)
+ rw [Nat.succ_mul] at room
+ change v.val < (pub 2).val at hv
+ omega
+
+/-- The placement fibers partition the old positions. -/
+theorem stepLayer_sum_ids_length (old : Order N.Site)
+ (next : Order t.output.Site) (r : TermParsers κ t) :
+ ∑ i : Fin next.length, ((stepLayer old next r).ids i).length = old.length := by
+ classical
+ simp only [stepLayer, List.length_ofFn]
+ calc
+ _ = ∑ v : t.output.Site, Fintype.card (t.Preimage v) :=
+ Fintype.sum_equiv next.entries _ _ (fun i => by
+ simpa only [Fintype.card_fin] using
+ Fintype.card_congr (r.order.children (next.entries i)).entries)
+ _ = Fintype.card N.Site := by
+ rw [← Fintype.card_sigma]
+ apply Fintype.card_congr
+ exact
+ { toFun := fun p => p.2.val
+ invFun := fun u => ⟨t.place u, ⟨u, rfl⟩⟩
+ left_inv := fun ⟨v, ⟨u, h⟩⟩ => by cases h; rfl
+ right_inv := fun _ => rfl }
+ _ = old.length := by simpa only [Fintype.card_fin] using Fintype.card_congr old.entries.symm
+
+open Classical in
+/-- Build one selected term's descriptor layer from its completed preimage pass.
+Every old site costs one read and one write, and every new site costs three
+header probes. The capacity bounds apply separately to the source directory
+and to the reserved destination rows. -/
+theorem native_step_layer (old : Order N.Site) (next : Order t.output.Site)
+ (r : TermParsers κ t) (physical : Word w → Word w)
+ (realizes : RepresentsPlacement old next t.place physical)
+ (hchildren : ∀ v, r.order.children v = old.restrict (fun u => v = t.place u))
+ (pub : Fin 6 → Word w) (mem : Memory w)
+ (oldCount : (pub 0).val = old.length) (newCount : (pub 2).val = next.length)
+ (collected : PreimagesAt pub physical mem old.length)
+ (state : Word w) (priv : Word w → Word w) (cap previous base : ℕ) (regions : RowRegions pub)
+ (inputEnd : (pub 5).val + (pub 2).val * (pub 4).val ≤ base)
+ (capacity : ∀ i, ((stepLayer old next r).ids i).length ≤ min (pub 4).val cap)
+ (fit : endPos cap base (stepLayer old next r) < 2 ^ w) :
+ let L := stepLayer old next r
+ let counts := fun i : Fin next.length => countAt pub (i.val : Word w)
+ let starts := fun i : Fin next.length => rowAt pub (i.val : Word w)
+ ∃ es, LayerPasses L cap previous base state priv counts starts (List.finRange next.length)
+ mem es ∧ after mem es = writeLayer cap previous base L mem ∧
+ countProbes es = 2 * old.length + 3 * next.length := by
+ let L := stepLayer old next r
+ have before (i : Fin next.length) :=
+ preimage_input_before regions inputEnd (valid_owner newCount i)
+ obtain ⟨es, run, image, probes⟩ :=
+ native_layer L cap previous base state priv _ _ mem
+ (raw_rows_of_preimages old next r physical realizes hchildren pub mem oldCount newCount
+ collected)
+ (fun i => (before i).1)
+ (fun i => (Nat.add_le_add_left ((le_min_iff.mp (capacity i)).1) _).trans (before i).2)
+ (fun i => (le_min_iff.mp (capacity i)).2) fit
+ refine ⟨es, run, image, ?_⟩
+ have total : ∑ i : Fin L.count, (L.ids i).length = old.length :=
+ stepLayer_sum_ids_length old next r
+ rw [probes, total]
+ rfl
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalNativeRows.lean b/lean/OAI/Computability/VPVNP/PairTraversalNativeRows.lean
new file mode 100644
index 0000000000..23035bb006
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalNativeRows.lean
@@ -0,0 +1,174 @@
+import OAI.Computability.VPVNP.PairTraversalRows
+import OAI.Computability.VPVNP.CompressorRecordPlacement
+import OAI.Computability.VPVNP.PairTraversalRowExecution
+
+/-!
+# From the native placement scan to the ordered children of a site
+
+The descriptor scan enumerates numerical identifiers in increasing order. The
+local history reader restricts that same order to the placement fiber. Equality
+of these lists keeps their indices aligned even when the placement is many to
+one or its fiber is empty.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open NetworkKernel LocalHistory CompressorRecords BurstRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ} {I J : Type}
+
+/-- The numerical site identifier stored in a word. -/
+def siteWord (w : ℕ) (o : Order I) (x : I) : Word w := Fin.ofNat (2 ^ w) (o.entries.symm x).val
+
+theorem siteWord_injective (o : Order I) (fit : o.length ≤ 2 ^ w) :
+ Function.Injective (siteWord w o) := by
+ intro x y e
+ apply o.entries.symm.injective
+ apply Fin.ext
+ simpa only [siteWord, Fin.val_ofNat, Nat.mod_eq_of_lt ((o.entries.symm x).isLt.trans_le fit),
+ Nat.mod_eq_of_lt ((o.entries.symm y).isLt.trans_le fit)] using congrArg Fin.val e
+
+/-- Each stored owner agrees with the placement on the represented old sites. -/
+def RepresentsPlacement (old : Order I) (next : Order J) (place : I → J)
+ (physical : Word w → Word w) : Prop :=
+ ∀ u, physical (siteWord w old u) = siteWord w next (place u)
+
+theorem encodedPlacement_represents (old : Order I) (next : Order J) (place : I → J)
+ (ho : old.length ≤ 2 ^ w) (hn : next.length ≤ 2 ^ w) :
+ RepresentsPlacement old next place
+ (encodedPlacement (w := w) old.entries.symm next.entries.symm place) := by
+ intro u
+ apply Fin.ext
+ rw [siteWord, encodedPlacement_eq _ _ _ ho hn, Equiv.symm_symm, Equiv.apply_symm_apply]
+ exact (Nat.mod_eq_of_lt ((next.entries.symm _).isLt.trans_le hn)).symm
+
+private theorem preimagePrefix_sorted (place : Word w → Word w) (v : Word w)
+ {k : ℕ} (fit : k ≤ 2 ^ w) : (preimagePrefix place v k).SortedLT := by
+ apply List.Pairwise.sortedLT
+ apply List.Pairwise.filter
+ apply List.pairwise_map.mpr
+ refine List.pairwise_lt_range.imp_of_mem ?_
+ intro i j hi hj hij
+ change i % (2 ^ w) < j % (2 ^ w)
+ rwa [Nat.mod_eq_of_lt ((List.mem_range.mp hi).trans_le fit),
+ Nat.mod_eq_of_lt ((List.mem_range.mp hj).trans_le fit)]
+
+private theorem restrict_mono (o : Order I) (P : I → Prop) [Fintype (Subtype P)] :
+ StrictMono fun j => o.entries.symm ((o.restrict P).entries j).val := by
+ let _ := LinearOrder.lift' (fun x : Subtype P => o.entries.symm x.val)
+ (o.entries.symm.injective.comp Subtype.val_injective)
+ exact (Fintype.orderIsoFinOfCardEq (Subtype P) rfl).strictMono
+
+/-- The old identifiers in the order chosen by the site's local history reader. -/
+def orderedIds (w : ℕ) (old : Order I) (P : I → Prop)
+ (children : Order (Subtype P)) : List (Word w) :=
+ List.ofFn fun j => siteWord w old (children.entries j).val
+
+/-- The native identifier list equals the restricted order entry by entry. -/
+theorem preimagePrefix_eq_orderedIds (old : Order I) (next : Order J) (place : I → J)
+ (physical : Word w → Word w) (realizes : RepresentsPlacement old next place physical)
+ (ho : old.length ≤ 2 ^ w) (hn : next.length ≤ 2 ^ w) (v : J)
+ [Fintype {u // v = place u}] :
+ preimagePrefix physical (siteWord w next v) old.length =
+ orderedIds w old (fun u => v = place u) (old.restrict _) := by
+ let P := fun u => v = place u
+ let ord := old.restrict P
+ apply (preimagePrefix_sorted physical _ ho).eq_of_mem_iff
+ · apply List.sortedLT_ofFn_iff.mpr
+ intro i j hij
+ change (old.entries.symm (ord.entries i).val).val % (2 ^ w) <
+ (old.entries.symm (ord.entries j).val).val % (2 ^ w)
+ rw [Nat.mod_eq_of_lt ((old.entries.symm _).isLt.trans_le ho),
+ Nat.mod_eq_of_lt ((old.entries.symm _).isLt.trans_le ho)]
+ exact restrict_mono old P hij
+ · intro x
+ simp only [preimagePrefix, List.mem_filter, List.mem_map, List.mem_range,
+ beq_iff_eq, orderedIds, List.mem_ofFn]
+ constructor
+ · rintro ⟨⟨k, hk, rfl⟩, hv⟩
+ let u := old.entries ⟨k, hk⟩
+ have hcode : siteWord w old u = Fin.ofNat _ k := by simp [siteWord, u]
+ have hu : v = place u := siteWord_injective next hn (hv.symm.trans ((hcode ▸ realizes u)))
+ let child : Subtype P := ⟨u, hu⟩
+ refine ⟨ord.entries.symm child, ?_⟩
+ change siteWord w old (ord.entries (ord.entries.symm child)).val = _
+ rw [Equiv.apply_symm_apply]
+ exact hcode
+ · rintro ⟨j, rfl⟩
+ let child := ord.entries j
+ exact ⟨⟨(old.entries.symm child.val).val, (old.entries.symm child.val).isLt, rfl⟩,
+ (realizes child.val).trans (congrArg (siteWord w next) child.prop.symm)⟩
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+variable {N : Network} {t : Term A N}
+
+private theorem address_ids (old : Order N.Site) (next : Order t.output.Site)
+ (r : TermParsers κ t) (cap previous : ℕ) (i : Fin next.length) :
+ (orderedIds w old _ (r.order.children (next.entries i))).map
+ (DescriptorRows.address (previous : Word w) ((cap + 2 : ℕ) : Word w)) =
+ childWords w cap previous (stepLayer old next r) i := by
+ simp only [orderedIds, childWords, stepLayer, List.map_ofFn]
+ congr 1
+ funext j
+ simp only [Function.comp_apply, DescriptorRows.address, siteWord, Fin.ofNat_eq_cast, address,
+ Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+ ring
+
+open Classical in
+/-- Apply the native row and header routines to a completed placement scan for a
+selected term. The resulting DFS descriptor uses the local parser's exact
+child list, with each identifier converted to its preceding-layer address. -/
+theorem native_step_row (old : Order N.Site) (next : Order t.output.Site)
+ (r : TermParsers κ t) (i : Fin next.length) (physical : Word w → Word w)
+ (realizes : RepresentsPlacement old next t.place physical)
+ (hchildren : r.order.children (next.entries i) =
+ old.restrict (fun u => next.entries i = t.place u))
+ (pub : Fin 6 → Word w) (mem : Memory w)
+ (oldCount : (pub 0).val = old.length) (newCount : (pub 2).val = next.length)
+ (collected : PreimagesAt pub physical mem old.length)
+ (state : Word w) (priv : Word w → Word w) (cap previous base : ℕ)
+ (sourceBefore : (rowAt pub (siteWord w next (next.entries i))).val +
+ ((stepLayer old next r).ids i).length ≤ address cap base i.val + 2)
+ (countBefore : (countAt pub (siteWord w next (next.entries i))).val <
+ address cap base i.val + 2)
+ (fit : address cap base i.val + 2 + ((stepLayer old next r).ids i).length < 2 ^ w) :
+ let owner := siteWord w next (next.entries i)
+ let node := address cap base i.val
+ let ids := orderedIds w old _ (r.order.children (next.entries i))
+ ∃ es, DescriptorRows.NativePass Fin.elim0 state priv mem node (rowAt pub owner).val
+ (node + 2) (countAt pub owner) (previous : Word w) ((cap + 2 : ℕ) : Word w) ids es ∧
+ DFS.Row (after mem es) node (node + 2)
+ (childWords w cap previous (stepLayer old next r) i) := by
+ let owner := siteWord w next (next.entries i)
+ let ids := orderedIds w old _ (r.order.children (next.entries i))
+ let node := address cap base i.val
+ have ho : old.length ≤ 2 ^ w := oldCount ▸ (pub 0).isLt.le
+ have hn : next.length ≤ 2 ^ w := newCount ▸ (pub 2).isLt.le
+ have valid : owner < pub 2 := by
+ change (next.entries.symm (next.entries i)).val % (2 ^ w) < (pub 2).val
+ rw [Equiv.symm_apply_apply, Nat.mod_eq_of_lt (i.isLt.trans_le hn), newCount]
+ exact i.isLt
+ have hids : preimagePrefix physical owner old.length = ids := by
+ unfold ids
+ rw [hchildren]
+ exact preimagePrefix_eq_orderedIds old next t.place physical realizes ho hn (next.entries i)
+ have hrow := collected.rows owner valid
+ rw [hids] at hrow
+ have len : ids.length = ((stepLayer old next r).ids i).length := by
+ simp only [ids, orderedIds, stepLayer, List.length_ofFn]
+ obtain ⟨es, pass⟩ := DescriptorRows.native_pass Fin.elim0 state priv mem node
+ (rowAt pub owner).val (node + 2) (countAt pub owner) (previous : Word w)
+ ((cap + 2 : ℕ) : Word w) ids (by simpa using hrow) (len ▸ sourceBefore)
+ countBefore (by omega) (len ▸ fit)
+ exact ⟨es, pass, (address_ids old next r cap previous i) ▸ pass.row⟩
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalNodeBounds.lean b/lean/OAI/Computability/VPVNP/PairTraversalNodeBounds.lean
new file mode 100644
index 0000000000..7b25a85a3a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalNodeBounds.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.PairTraversalDisjoint
+import Mathlib.Data.List.Chain
+
+/-!
+# Addresses of the selected placement trees
+
+The leaf and intermediate layers occupy consecutive row intervals in increasing
+stage order. Every header read in a final vertex's preorder lies below the end
+of these layers. A stored child pointer recovers the exact address of its row
+in the preceding layer when the table fits in memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open LocalHistory NetworkKernel Compression DFS BurstRAM
+open scoped Fin.CommRing
+open private leafBelow pushBelow from OAI.Computability.VPVNP.PairTraversalDisjoint
+
+variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} {N Y : Network}
+
+/-- Advancing the base through the same rows as the builder gives the sum
+of the preceding layer sizes. -/
+theorem endPos_fold (cap start : ℕ) (layers : List Layer) :
+ layers.foldl (endPos cap) start = start + words cap layers := by
+ induction layers generalizing start with
+ | nil => simp [words]
+ | cons l ls ih => simp [ih, endPos, address, words, Nat.mul_add, Nat.add_assoc]
+
+/-- Every row in a layer after the preceding layers has its header inside the
+allocated descriptor interval. -/
+theorem layerNode_bounds (cap start : ℕ) (before : List Layer) (l : Layer)
+ (suffix : List Layer) (i : Fin l.count) :
+ start ≤ address cap (start + words cap before) i.val ∧
+ address cap (start + words cap before) i.val <
+ start + words cap (before ++ l :: suffix) := by
+ have hi := Nat.mul_lt_mul_of_pos_left i.isLt (by omega : 0 < cap + 2)
+ simp only [address, words, List.map_append, List.sum_append, List.map_cons, List.sum_cons,
+ Nat.mul_add]
+ omega
+
+/-- The site identifiers of the later layer are row indices in the earlier layer. -/
+def Layer.ChildrenIn (previous next : Layer) : Prop :=
+ ∀ i, ∀ j ∈ next.ids i, j < previous.count
+
+private theorem stepLayers_childrenIn (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (initial : Order N.Site) (previous : Layer)
+ (hcount : previous.count = initial.length) :
+ (previous :: stepLayers c r ords initial).IsChain Layer.ChildrenIn := by
+ induction c generalizing previous with
+ | done => exact List.IsChain.singleton _
+ | more t data tail ih =>
+ apply List.isChain_cons_cons.mpr
+ exact ⟨fun i j hj => hcount ▸ stepLayer_ids_lt initial ords.1 r.1 i j hj,
+ ih r.2 ords.2 ords.1 _ rfl⟩
+
+/-- The child-index range property holds at every pair of consecutive selected layers. -/
+theorem chainLayers_childrenIn (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (initial : Order N.Site) :
+ (chainLayers c r ords initial).IsChain Layer.ChildrenIn :=
+ stepLayers_childrenIn c r ords initial _ rfl
+
+/-- Reading a row's child pointer words gives exactly the preceding-layer
+row addresses in order, including when the row has no children. -/
+theorem childWords_val (cap start : ℕ) {w : ℕ} (before : List Layer) (previous next : Layer)
+ (suffix : List Layer) (i : Fin next.count) (hids : previous.ChildrenIn next)
+ (fit : start + words cap (before ++ previous :: next :: suffix) ≤ 2 ^ w) :
+ (childWords w cap (start + words cap before) next i).map Fin.val =
+ (next.ids i).map (address cap (start + words cap before)) := by
+ simp only [childWords, List.map_map]
+ apply List.map_congr_left
+ intro j hj
+ have hn := (layerNode_bounds cap start before previous (next :: suffix)
+ ⟨j, hids i j hj⟩).2
+ exact Nat.mod_eq_of_lt (hn.trans_le fit)
+
+/-- Specialize exact child pointer decoding to any consecutive layers in
+the actual parser chain, without assuming a bound on the raw child indices. -/
+theorem chain_childWords_val (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (initial : Order N.Site) (cap start : ℕ) {w : ℕ}
+ {before suffix : List Layer} {previous next : Layer}
+ (h : chainLayers c r ords initial = before ++ previous :: next :: suffix)
+ (fit : start + words cap (chainLayers c r ords initial) ≤ 2 ^ w) (i : Fin next.count) :
+ (childWords w cap (start + words cap before) next i).map Fin.val =
+ (next.ids i).map (address cap (start + words cap before)) :=
+ childWords_val cap start before previous next suffix i
+ (List.isChain_iff_forall_rel_of_append_cons_cons.mp (chainLayers_childrenIn c r ords initial)
+ h) (h ▸ fit)
+
+/-- The precise upper end of the forest after storing the remaining stages. -/
+theorem chainTrees_below (cap : ℕ) (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (initial : Order N.Site) (base : ℕ) (trees : N.Site → VertexTree)
+ (old : ForestBelow base trees) :
+ ForestBelow (base + words cap (stepLayers c r ords initial))
+ (chainTrees c r (chainPointers cap c ords base) trees) := by
+ induction c generalizing base with
+ | done => simpa [stepLayers, words, chainTrees] using old
+ | more t data tail ih =>
+ have h := ih r.2 ords.2 ords.1 (address cap base ords.1.length) _
+ (pushBelow r.1 cap base ords.1 trees old)
+ simpa only [stepLayers, stepLayer, words, List.map_cons, List.sum_cons, Nat.mul_add,
+ address, Nat.add_assoc, chainTrees, chainPointers] using h
+
+/-- Start the forest with one leaf at each actual initial site. -/
+theorem chainForest_below (cap : ℕ) (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (initial : Order N.Site) (base : ℕ) :
+ ForestBelow (base + words cap (chainLayers c r ords initial))
+ (chainTrees c r (chainPointers cap c ords (address cap base initial.length))
+ (fun u => leafTree (sitePointers cap base initial u))) := by
+ simpa only [chainLayers, leafLayer, words, List.map_cons, List.sum_cons, Nat.mul_add,
+ address, Nat.add_assoc] using
+ chainTrees_below cap c r ords initial _ _ (leafBelow initial cap base)
+
+section Selected
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+variable (f : B.Entry → A) (hf : B.IsSolution f) {lanes : ℕ} (T : ℕ)
+variable (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices) (base : ℕ)
+
+/-- Actual placement trees visited after building this branch's row directory. -/
+noncomputable abbrev selectedTrees :
+ ((B.execute f hf T hT X).finalState z).network.Site → VertexTree :=
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ptr := chainPointers B.recordLimit c (branchOrders E data z)
+ (address B.recordLimit base (siteOrder X).length)
+ chainTrees c (selectedParsers B f hf T hT X z) ptr
+ (fun u => leafTree (sitePointers B.recordLimit base (siteOrder X) u))
+
+/-- Every visited node lies strictly below the exclusive end of the actual
+descriptor region of the selected branch. -/
+theorem selectedTrees_below (v : ((B.execute f hf T hT X).finalState z).network.Site)
+ {node : ℕ} (hn : node ∈ (selectedTrees B f hf T hT X z base v).preorder) :
+ node < base + words B.recordLimit (selectedLayers B f hf T hT X z) :=
+ (chainForest_below B.recordLimit _ (selectedParsers B f hf T hT X z) _ (siteOrder X)
+ base).below v node hn
+
+end Selected
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalOnlineWorker.lean b/lean/OAI/Computability/VPVNP/PairTraversalOnlineWorker.lean
new file mode 100644
index 0000000000..c82749a7b4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalOnlineWorker.lean
@@ -0,0 +1,322 @@
+import OAI.Computability.VPVNP.CompressorFlowRebase
+import OAI.Computability.VPVNP.PairTraversalLeafWorker
+import OAI.Computability.VPVNP.PairTraversalSiteWorker
+import OAI.Computability.VPVNP.PairTraversalRoleNative
+
+/-!
+# Running traversal workers with the selected layer's directory words
+
+A leaf, a placement fiber and a role tag are written by fixed programs. At
+their online entry the current site ordinal and the layout words are in
+registers. Each former parameter or state load becomes a single private copy.
+The emitted events, memory image and branch bits agree with the original
+worker, including every iteration of the fiber scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows.OnlineWorker
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM PrimedCounter
+open scoped Fin.CommRing
+
+variable {w r k R : ℕ}
+
+private def opAt (reg : Fin r ↪ Fin R) (bank : Fin k → Fin R) (arg : Fin R) :
+ Op r k → Op R 11
+ | .publicWord dst i => .copy (reg dst) (bank i)
+ | op => CompressorRecords.Rebased.opAt reg (fun _ => 0) arg op
+
+open private restrict_update from OAI.Computability.VPVNP.PrimedCounterRename
+
+private theorem effect (reg : Fin r ↪ Fin R) (bank : Fin k → Fin R) (arg : Fin R) (op : Op r k)
+ (data : Fin 11 → Word w) (state : Word w) (rs : Regs w R) (mem : Memory w) :
+ ((opAt reg bank arg op).effect data state rs mem).map (fun (e, r', m') => (e, r' ∘ reg, m')) =
+ op.effect (rs ∘ bank) (rs arg) (rs ∘ reg) mem := by
+ cases op <;> simp [opAt, CompressorRecords.Rebased.opAt, renameOp, Op.effect,
+ restrict_update, Function.comp_apply]
+
+/-- Replace the component's public inputs and persistent input with register reads. -/
+def code (reg : Fin r ↪ Fin R) (bank : Fin k → Fin R) (arg : Fin R) : Flow r k → Flow R 11
+ | .line op => .line (opAt reg bank arg op)
+ | .seq a b => .seq (code reg bank arg a) (code reg bank arg b)
+ | .ifEq x y a b => .ifEq (reg x) (reg y) (code reg bank arg a) (code reg bank arg b)
+ | .ifLt x y a b => .ifLt (reg x) (reg y) (code reg bank arg a) (code reg bank arg b)
+ | .branch a b => .branch (code reg bank arg a) (code reg bank arg b)
+ | .whileLt x y a => .whileLt (reg x) (reg y) (code reg bank arg a)
+
+private theorem line_outside (reg : Fin r ↪ Fin R) (bank : Fin k → Fin R) (arg : Fin R)
+ (op : Op r k) (data : Fin 11 → Word w) (state : Word w) (rs : Regs w R) (mem : Memory w)
+ {e out m'} (he : (opAt reg bank arg op).effect data state rs mem = some (e, out, m'))
+ (j : Fin R) (hj : j ∉ Set.range reg) : out j = rs j := by
+ have hn (i : Fin r) : j ≠ reg i := fun hh => hj ⟨i, hh.symm⟩
+ cases op <;> simp only [opAt, CompressorRecords.Rebased.opAt, renameOp, Op.effect] at he
+ all_goals first | split at he | skip
+ all_goals first | contradiction | (cases Option.some.inj he; simp [Function.update_of_ne (hn _)])
+
+/-- Lift a worker derivation to a call with runtime directory words. The
+outer machine retains its persistent state and every register outside the scratch bank. -/
+theorem liftExec (reg : Fin r ↪ Fin R) (bank : Fin k → Fin R) (arg : Fin R)
+ (hbank : ∀ j, bank j ∉ Set.range reg) (harg : arg ∉ Set.range reg)
+ (data : Fin 11 → Word w) {params : Fin k → Word w} {state site : Word w}
+ {a : Flow r k} {small m es out m'}
+ (he : Flow.Exec params site a small m es out m') (rs : Regs w R)
+ (hr : rs ∘ reg = small) (hp : rs ∘ bank = params) (hs : rs arg = site) :
+ ∃ rs', Flow.Exec data state (code reg bank arg a) rs m es rs' m' ∧
+ rs' ∘ reg = out ∧ ∀ j, j ∉ Set.range reg → rs' j = rs j := by
+ induction he generalizing rs with
+ | @line op small m e small' m' h =>
+ have hx := effect reg bank arg op data state rs m
+ rw [hr, hp, hs, h] at hx
+ obtain ⟨⟨ev, rs', m''⟩, hh, heq⟩ := Option.map_eq_some_iff.mp hx
+ obtain ⟨rfl, heq, rfl⟩ := Prod.mk.inj heq
+ exact ⟨rs', .line hh, rfl, line_outside reg bank arg op data state rs m hh⟩
+ | seq _ _ ih₁ ih₂ =>
+ obtain ⟨mid, hm, he, ho⟩ := ih₁ rs hr hp hs
+ obtain ⟨out, hrun, he', ho'⟩ := ih₂ mid he
+ ((funext fun j => ho (bank j) (hbank j)).trans hp) ((ho arg harg).trans hs)
+ exact ⟨out, .seq hm hrun, he', fun j hj => (ho' j hj).trans (ho j hj)⟩
+ | ifEqYes ht _ ih | ifEqNo ht _ ih | ifLtYes ht _ ih | ifLtNo ht _ ih =>
+ obtain ⟨out, ho, he, hh⟩ := ih rs hr hp hs
+ rw [← hr] at ht
+ first | exact ⟨out, .ifEqYes ht ho, he, hh⟩ | exact ⟨out, .ifEqNo ht ho, he, hh⟩
+ | exact ⟨out, .ifLtYes ht ho, he, hh⟩ | exact ⟨out, .ifLtNo ht ho, he, hh⟩
+ | branchYes _ ih | branchNo _ ih =>
+ obtain ⟨out, ho, he, hh⟩ := ih rs hr hp hs
+ first | exact ⟨out, .branchYes ho, he, hh⟩ | exact ⟨out, .branchNo ho, he, hh⟩
+ | whileDone ht =>
+ rw [← hr] at ht
+ exact ⟨rs, .whileDone ht, hr, fun _ _ => rfl⟩
+ | whileStep ht _ _ ih₁ ih₂ =>
+ obtain ⟨mid, hb, he, ho⟩ := ih₁ rs hr hp hs
+ obtain ⟨out, hrun, he', ho'⟩ := ih₂ mid he
+ ((funext fun j => ho (bank j) (hbank j)).trans hp) ((ho arg harg).trans hs)
+ rw [← hr] at ht
+ exact ⟨out, .whileStep ht hb hrun, he', fun j hj => (ho' j hj).trans (ho j hj)⟩
+
+/-- Conversely, every successful enclosing execution restricts to a genuine
+execution of the original program. Both directions include the exact event log. -/
+theorem restrictExec (reg : Fin r ↪ Fin R) (bank : Fin k → Fin R) (arg : Fin R)
+ (hbank : ∀ j, bank j ∉ Set.range reg) (outside : arg ∉ Set.range reg) (data : Fin 11 → Word w)
+ {state : Word w} (a : Flow r k) {rs m es out m'}
+ (he : Flow.Exec data state (code reg bank arg a) rs m es out m') :
+ Flow.Exec (rs ∘ bank) (rs arg) a (rs ∘ reg) m es (out ∘ reg) m' ∧
+ ∀ j, j ∉ Set.range reg → out j = rs j := by
+ generalize hcmd : code reg bank arg a = cmd at he
+ induction he generalizing a with
+ | @line op rs m e out m' h =>
+ cases a <;> simp only [code, reduceCtorEq, Flow.line.injEq] at hcmd
+ subst op
+ constructor
+ · apply Flow.Exec.line
+ rw [← effect reg bank arg _ data state rs m, h]
+ rfl
+ · exact line_outside reg bank arg _ data state rs m h
+ | seq _ _ ih₁ ih₂ =>
+ cases a <;> simp only [code, reduceCtorEq, Flow.seq.injEq] at hcmd
+ obtain ⟨ha, hb⟩ := hcmd
+ obtain ⟨h₁, o₁⟩ := ih₁ _ ha
+ obtain ⟨h₂, o₂⟩ := ih₂ _ hb
+ rw [o₁ arg outside, show _ ∘ bank = _ ∘ bank from funext (fun j => o₁ (bank j) (hbank j))] at h₂
+ exact ⟨.seq h₁ h₂, fun j hj => (o₂ j hj).trans (o₁ j hj)⟩
+ | ifEqYes ht _ ih | ifEqNo ht _ ih | ifLtYes ht _ ih | ifLtNo ht _ ih =>
+ cases a <;> simp only [code, reduceCtorEq, Flow.ifEq.injEq, Flow.ifLt.injEq] at hcmd
+ obtain ⟨rfl, rfl, ha, hb⟩ := hcmd
+ first
+ | obtain ⟨h, ho⟩ := ih _ ha; exact ⟨.ifEqYes ht h, ho⟩
+ | obtain ⟨h, ho⟩ := ih _ hb; exact ⟨.ifEqNo ht h, ho⟩
+ | obtain ⟨h, ho⟩ := ih _ ha; exact ⟨.ifLtYes ht h, ho⟩
+ | obtain ⟨h, ho⟩ := ih _ hb; exact ⟨.ifLtNo ht h, ho⟩
+ | branchYes _ ih | branchNo _ ih =>
+ cases a <;> simp only [code, reduceCtorEq, Flow.branch.injEq] at hcmd
+ obtain ⟨ha, hb⟩ := hcmd
+ first
+ | obtain ⟨h, ho⟩ := ih _ ha; exact ⟨.branchYes h, ho⟩
+ | obtain ⟨h, ho⟩ := ih _ hb; exact ⟨.branchNo h, ho⟩
+ | whileDone ht =>
+ cases a <;> simp only [code, reduceCtorEq, Flow.whileLt.injEq] at hcmd
+ obtain ⟨rfl, rfl, _⟩ := hcmd
+ exact ⟨.whileDone ht, fun _ _ => rfl⟩
+ | whileStep ht _ _ ih₁ ih₂ =>
+ cases a <;> simp only [code, reduceCtorEq, Flow.whileLt.injEq] at hcmd
+ obtain ⟨rfl, rfl, rfl⟩ := hcmd
+ obtain ⟨h₁, o₁⟩ := ih₁ _ rfl
+ obtain ⟨h₂, o₂⟩ := ih₂ (.whileLt _ _ _) rfl
+ rw [o₁ arg outside, show _ ∘ bank = _ ∘ bank from funext (fun j => o₁ (bank j) (hbank j))] at h₂
+ exact ⟨.whileStep ht h₁ h₂, fun j hj => (o₂ j hj).trans (o₁ j hj)⟩
+
+/-- The three workers share at most seven scratch registers, six directory
+words and the site cursor. The enclosing machine can reserve more registers. -/
+structure Allocation (R : ℕ) where
+ /-- Embed the seven registers available for a traversal worker's scratch calculations. -/
+ scratch : Fin 7 ↪ Fin R
+ /-- Assign each of the worker's six runtime bank words to its enclosing register. -/
+ bank : Fin 6 → Fin R
+ /-- Register holding the current site ordinal for the installed worker. -/
+ site : Fin R
+ bankOutside : ∀ j, bank j ∉ Set.range scratch
+ siteOutside : site ∉ Set.range scratch
+
+namespace Allocation
+
+/-- Scratch registers occupy positions 0 through 6. The six layout words
+occupy positions 7 through 12 and the site cursor occupies position 13. -/
+def «prefix» (room : 14 ≤ R) : Allocation R where
+ scratch := Fin.castLEEmb (by omega)
+ bank j := ⟨7 + j.val, by have := j.isLt; omega⟩
+ site := ⟨13, by omega⟩
+ bankOutside j := by
+ rintro ⟨i, e⟩
+ have := congrArg Fin.val e
+ change i.val = 7 + j.val at this
+ omega
+ siteOutside := by
+ rintro ⟨i, e⟩
+ have := congrArg Fin.val e
+ change i.val = 13 at this
+ omega
+
+variable (A : Allocation R)
+
+/-- Restrict the seven-register scratch embedding to the smaller bank required by a particular
+worker. -/
+def regs {n : ℕ} (h : n ≤ 7) : Fin n ↪ Fin R := (Fin.castLEEmb h).trans A.scratch
+
+/-- Select a prefix of the six runtime bank words for a worker with fewer parameters. -/
+def words {n : ℕ} (h : n ≤ 6) : Fin n → Fin R := A.bank ∘ Fin.castLE h
+
+/-- Install the leaf-row writer with its allocated scratch registers, directory words, and site
+ordinal. -/
+def leaf : Flow R 11 :=
+ code (A.regs (by decide)) (A.words (by decide)) A.site LeafWorker.program
+
+/-- Install the preimage-fiber row writer using the full scratch and public parameter banks. -/
+def fiber : Flow R 11 := code A.scratch A.bank A.site SiteWorker.program
+
+/-- Install the role-tag writer for a single selected site using the corresponding smaller
+register banks. -/
+def role : Flow R 11 := code (A.regs (by decide)) (A.words (by decide)) A.site
+ (lines TraversalRoles.Native.visit (by decide))
+
+private theorem regs_outside {n : ℕ} (h : n ≤ 7) {j : Fin R} (hj : j ∉ Set.range A.scratch) :
+ j ∉ Set.range (A.regs h) := fun ⟨i, hi⟩ => hj ⟨i.castLE h, hi⟩
+
+private theorem small_lift {n k : ℕ} (hn : n ≤ 7) (hk : k ≤ 6) (data : Fin 11 → Word w)
+ {pub : Fin k → Word w} {state site : Word w} {a : Flow n k} {m es out m'} (rs : Regs w R)
+ (hp : rs ∘ A.words hk = pub) (hs : rs A.site = site)
+ (he : Flow.Exec pub site a (rs ∘ A.regs hn) m es out m') :
+ ∃ rs', Flow.Exec data state (code (A.regs hn) (A.words hk) A.site a) rs m es rs' m' ∧
+ rs' ∘ A.regs hn = out ∧ ∀ j, j ∉ Set.range A.scratch → rs' j = rs j := by
+ obtain ⟨rs', run, endAt, unchanged⟩ := liftExec (A.regs hn) (A.words hk) A.site
+ (fun i => A.regs_outside hn (A.bankOutside (i.castLE hk))) (A.regs_outside hn A.siteOutside)
+ data he rs rfl hp hs
+ exact ⟨rs', run, endAt, fun j hj => unchanged j (A.regs_outside hn hj)⟩
+
+open private events ops from OAI.Computability.VPVNP.PairTraversalLeafWorker
+
+/-- The two header writes in chronological order, with their private ticks. -/
+def leafEvents (node : Word w) : List (Event w) := events node
+
+/-- The linked leaf body accepts arbitrary scratch contents and uses the
+runtime base and stride. Its successor is in scratch register zero. -/
+theorem leaf_exec (data : Fin 11 → Word w) (state : Word w) (rs : Regs w R)
+ (m : Memory w) (cap base i : ℕ)
+ (hp : rs ∘ A.words (by decide) = LeafWorker.directory w cap base)
+ (hs : rs A.site = (i : Word w)) :
+ let n : Word w := (address cap base i : Word w)
+ ∃ out, Flow.Exec data state A.leaf rs m (leafEvents n) out
+ (writeMemory (writeMemory m n (n + 2)) (n + 1) 0) ∧
+ out (A.scratch 0) = ((i + 1 : ℕ) : Word w) ∧
+ countProbes (leafEvents n) = 2 ∧ (leafEvents n).length = 13 ∧
+ choiceBits (leafEvents n) = [] ∧ ∀ j, j ∉ Set.range A.scratch → out j = rs j := by
+ intro n
+ have body : ∃ out, Flow.Exec (LeafWorker.directory w cap base) (i : Word w)
+ LeafWorker.program (rs ∘ A.regs (by decide)) m (leafEvents n) out
+ (writeMemory (writeMemory m n (n + 2)) (n + 1) 0) ∧
+ out 0 = ((i + 1 : ℕ) : Word w) := by
+ simp only [LeafWorker.program, Admin.exec_lines_iff_trace]
+ simp (config := { decide := true }) [ops, trace, Op.effect, BinaryOp.eval, Function.update,
+ LeafWorker.directory, address, n, Nat.cast_add, Nat.cast_mul, leafEvents, events]
+ obtain ⟨small, he, ret⟩ := body
+ obtain ⟨out, run, hregs, ho⟩ := A.small_lift (by decide) (by decide) data rs hp hs he
+ exact ⟨out, run, (congrFun hregs 0).trans ret, rfl, rfl, rfl, ho⟩
+
+/-- The tag worker writes the computed role address and advances scratch
+register zero. The preloaded tag can vary between sites. -/
+theorem role_exec (data : Fin 11 → Word w) (state site : Word w) (rs : Regs w R)
+ (m : Memory w) (pub : Fin 4 → Word w) (hp : rs ∘ A.words (by decide) = pub)
+ (hs : rs A.site = site) :
+ let es := TraversalRoles.Native.events pub site
+ ∃ out, Flow.Exec data state A.role rs m es out (after m es) ∧
+ out (A.scratch 0) = site + 1 ∧ countProbes es = 1 ∧ es.length = 11 ∧
+ choiceBits es = [] ∧ ∀ j, j ∉ Set.range A.scratch → out j = rs j := by
+ intro es
+ have body : ∃ out, Flow.Exec pub site (lines TraversalRoles.Native.visit (by decide))
+ (rs ∘ A.regs (by decide)) m es out (after m es) ∧ out 0 = site + 1 := by
+ simp only [Admin.exec_lines_iff_trace]
+ simp (config := { decide := true }) [TraversalRoles.Native.visit, TraversalRoles.Native.events,
+ es, trace, Op.effect, BinaryOp.eval, Function.update, after, BurstRAM.update]
+ obtain ⟨small, he, ret⟩ := body
+ obtain ⟨out, run, hregs, ho⟩ := A.small_lift (by decide) (by decide) data rs hp hs he
+ exact ⟨out, run, (congrFun hregs 0).trans ret, rfl, rfl, rfl, ho⟩
+
+open private worker_exec headerMemory from OAI.Computability.VPVNP.PairTraversalSiteWorker
+
+/-- Translate the complete current placement fiber. The node headers cost
+three probes and every child contributes one read and one write. -/
+theorem fiber_exec (data : Fin 11 → Word w) (state site : Word w) (rs : Regs w R)
+ (m : Memory w) (pub : Fin 6 → Word w) (hp : rs ∘ A.bank = pub) (hsite : rs A.site = site)
+ (src node count : ℕ) (hs : SiteWorker.source pub site = (src : Word w))
+ (hn : SiteWorker.node pub site = (node : Word w))
+ (hc : (m (SiteWorker.counter pub site).val).val = count)
+ (before : src + count ≤ node) (fit : node + 2 + count < 2 ^ w) :
+ let image := DescriptorRows.passMemory m node src (node + 2) (SiteWorker.counter pub site)
+ (pub 3) (pub 5) count
+ ∃ es out, Flow.Exec data state A.fiber rs m es out image ∧ out (A.scratch 6) = site + 1 ∧
+ countProbes es = 2 * count + 3 ∧ es.length = 7 * count + 24 ∧ choiceBits es = [] ∧
+ ∀ j, j ∉ Set.range A.scratch → out j = rs j := by
+ intro image
+ obtain ⟨es, small, body, ret, probes, steps, bits⟩ := worker_exec pub site m src node count
+ hs hn hc before fit (rs ∘ A.scratch)
+ obtain ⟨out, run, hregs, ho⟩ := liftExec A.scratch A.bank A.site A.bankOutside A.siteOutside data
+ body rs rfl hp hsite (state := state)
+ refine ⟨es, out, ?_, (congrFun hregs 6).trans ret, probes, steps, bits, ho⟩
+ have hi : DescriptorRows.rowMemory src (node + 2) count (pub 3) (pub 5)
+ (headerMemory pub site m) = image := by
+ change DescriptorRows.rowMemory _ _ _ _ _ (writeMemory (writeMemory m (SiteWorker.node pub site)
+ (SiteWorker.node pub site + 2)) (SiteWorker.node pub site + 1)
+ (m (SiteWorker.counter pub site).val)) = image
+ rw [hn]
+ simpa only [Nat.cast_add, Nat.cast_ofNat, Nat.cast_one, image] using
+ DescriptorRows.headers_then_scan m node src (SiteWorker.counter pub site) (pub 3) (pub 5)
+ count before fit
+ rw [← hi]
+ exact run
+
+end Allocation
+
+/-- Compile the worker followed by the caller's continuation in one instruction
+table. The continuation receives exactly the worker's final registers, external
+memory, unused fuel and unused choice bits. -/
+theorem execute_then (body tail : Flow R 11) (ret : Option (Fin R))
+ (pub : Fin 11 → Word w) (state : Word w) (priv : Word w → Word w) {rs m es out m'}
+ (run : Flow.Exec pub state body rs m es out m') (bits : List Bool) (fuel : ℕ) :
+ let whole := body.seq tail
+ let M := (whole.template ret).instantiate w pub
+ execute M.program (es.length + fuel) ⟨M.entry, state, rs, priv⟩ m (choiceBits es ++ bits) =
+ (execute M.program fuel ⟨whole.pc (.inr tail.entry), state, out, priv⟩ m' bits).map
+ (Flow.prependEvents es) := by
+ let whole := body.seq tail
+ let M := (whole.template ret).instantiate w pub
+ have linked := (Flow.template_linked whole ret pub).seqLeft
+ have reject : M.code whole.rejectPC = .reject := by
+ simp [M, Template.instantiate, Flow.template_reject, Instr.resize]
+ exact run.execute linked reject priv fuel bits
+
+end PairSimulation.TraversalRows.OnlineWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalPreorderBounds.lean b/lean/OAI/Computability/VPVNP/PairTraversalPreorderBounds.lean
new file mode 100644
index 0000000000..00d51cb7f6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalPreorderBounds.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.PairTraversalArena
+import OAI.Computability.VPVNP.PairTraversalNodeBounds
+import OAI.Computability.VPVNP.PairTraversalReadFootprint
+
+/-!
+# Physical child-list bounds for every selected DFS visit
+
+Each node in the final preorder originates in a row of its own compression
+level. Reading that row gives its actual child pointer and length. Both
+header reads and the entire child list fit in the allocated descriptor arena.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open BurstRAM LocalHistory NetworkKernel Compression DFS
+open scoped Fin.CommRing
+open private row_end_le from OAI.Computability.VPVNP.PairTraversalRows
+open private addTree from OAI.Computability.VPVNP.PairTraversalHistory
+
+variable {w : ℕ} {A : Type*} [CommRing A] {Label : Type} [Fintype Label]
+variable {κ : Label → A} {N Y : Network}
+
+private def rowBounds (m : Memory w) (limit node : ℕ) : Prop :=
+ node+2 ≤ limit ∧ (m node).val + (m (node+1)).val ≤ limit
+
+private theorem layer_bounds {m : Memory w} {cap previous base limit : ℕ} {l : Layer}
+ (rows : l.Rows w m cap previous base) (capacity : ∀ i, (l.ids i).length ≤ cap)
+ (space : endPos cap base l ≤ limit) (i : Fin l.count) :
+ rowBounds m limit (address cap base i.val) := by
+ let node := address cap base i.val
+ obtain ⟨_, _, fit, ptr, len, _⟩ := rows i
+ have small := (row_end_le cap base l i).trans space
+ change node+2+(childWords w cap previous l i).length < 2^w at fit
+ change m node = ((node+2 : ℕ) : Word w) at ptr
+ change m (node+1) = ((childWords w cap previous l i).length : Word w) at len
+ have maxLen := capacity i
+ simp only [childWords,List.length_map] at fit len
+ unfold rowBounds
+ change node+2 ≤ limit ∧ (m node).val + (m (node+1)).val ≤ limit
+ rw [ptr, len, Fin.val_natCast, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : node+2 < 2^w),
+ Nat.mod_eq_of_lt (by omega : (l.ids i).length < 2^w)]
+ change node+(cap+2) ≤ limit at small
+ omega
+
+private theorem chain_bounds (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (initial : Order N.Site) (cap previous base limit : ℕ)
+ (m : Memory w) (trees : N.Site → VertexTree)
+ (rows : AllRows w m cap previous base (stepLayers c r ords initial))
+ (capacity : ∀ l ∈ stepLayers c r ords initial, ∀ i, (l.ids i).length ≤ cap)
+ (space : base + words cap (stepLayers c r ords initial) ≤ limit)
+ (old : ∀ v, ∀ x ∈ (trees v).preorder, rowBounds m limit x) :
+ ∀ v, ∀ x ∈ (chainTrees c r (chainPointers cap c ords base) trees v).preorder,
+ rowBounds m limit x := by
+ induction c generalizing previous base with
+ | done => exact old
+ | more t data tail ih =>
+ let l := stepLayer initial ords.1 r.1
+ let ls := stepLayers tail r.2 ords.2 ords.1
+ change base + words cap (l :: ls) ≤ limit at space
+ have next : endPos cap base l + words cap ls ≤ limit := by
+ simpa only [endPos,address,words,List.map_cons,List.sum_cons,Nat.mul_add,Nat.add_assoc] using space
+ apply ih r.2 ords.2 ords.1 base (endPos cap base l)
+ (addTree r.1 (sitePointers cap base ords.1) trees) rows.2
+ (fun L h => capacity L (List.mem_cons_of_mem _ h)) next
+ intro v x hx
+ change x ∈ (sitePointers cap base ords.1 v).1 ::
+ (List.ofFn (fun i => (trees ((r.1.order.children v).entries i).val).preorder)).flatten at hx
+ rcases List.mem_cons.mp hx with rfl | hk
+ · exact layer_bounds rows.1 (capacity l List.mem_cons_self) ((Nat.le_add_right _ _).trans next) (ords.1.entries.symm v)
+ · obtain ⟨xs, hi, hm⟩ := List.mem_flatten.mp hk
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hi
+ exact old _ _ hm
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates)
+variable (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ} (T : ℕ)
+variable (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices) (base limit : ℕ) (m : Memory w)
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "trees" => selectedTrees B f hf T hT X z base
+
+/-- The two scalar reads and every child-word read in each selected
+placement tree lie below the given exclusive bound. -/
+theorem selected_preorder_row_bounds (rows : AllRows w m B.recordLimit base base (ls))
+ (space : base + words B.recordLimit (ls) ≤ limit) :
+ ∀ v, ∀ x ∈ (trees v).preorder,
+ x+2 ≤ limit ∧ (m x).val + (m (x+1)).val ≤ limit := by
+ let E := B.execute f hf T hT X
+ let c := E.termChain (B.records f hf T hT X) z
+ let r := selectedParsers B f hf T hT X z
+ let ords := branchOrders E (B.records f hf T hT X) z
+ let initial := siteOrder X
+ let leaf := leafLayer initial
+ let rest := stepLayers c r ords initial
+ have cap := selected_capacity B f hf T hT X z
+ change base + words B.recordLimit (leaf :: rest) ≤ limit at space
+ have next : endPos B.recordLimit base leaf + words B.recordLimit rest ≤ limit := by
+ simpa only [endPos,address,words,List.map_cons,List.sum_cons,Nat.mul_add,Nat.add_assoc] using space
+ apply chain_bounds c r ords initial B.recordLimit base (endPos B.recordLimit base leaf) limit m
+ (fun u => leafTree (sitePointers B.recordLimit base initial u)) rows.2
+ (fun l hl => cap l (List.mem_cons_of_mem _ hl)) next
+ intro v x hx
+ change x ∈ [(sitePointers B.recordLimit base initial v).1] at hx
+ rw [List.mem_singleton] at hx
+ exact hx ▸ layer_bounds rows.1 (cap leaf List.mem_cons_self) ((Nat.le_add_right _ _).trans next) (initial.entries.symm v)
+
+/-- Word-encoded visits in the DFS event log recover the same bounds. -/
+theorem selected_preorder_word_bounds (rows : AllRows w m B.recordLimit base base (ls))
+ (space : base + words B.recordLimit (ls) ≤ limit) (fit : limit ≤ 2^w) :
+ ∀ v, ∀ node ∈ (trees v).preorder.map (fun n : ℕ => (n : Word w)),
+ node.val+2 ≤ limit ∧ (m node.val).val + (m (node.val+1)).val ≤ limit := by
+ intro v node h
+ obtain ⟨n,hn,rfl⟩ := List.mem_map.mp h
+ have bounds := selected_preorder_row_bounds B f hf T hT X z base limit m rows space v n hn
+ rwa [Fin.val_natCast,Nat.mod_eq_of_lt (by omega : n < 2^w)]
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalReadFootprint.lean b/lean/OAI/Computability/VPVNP/PairTraversalReadFootprint.lean
new file mode 100644
index 0000000000..47378eaf0b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalReadFootprint.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.PairSimulationDFS
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-! # External read addresses of the native placement-tree traversal -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open BurstRAM TerminalFootprint CompressorRecords.SourceTransport
+open private headerEvents from OAI.Computability.VPVNP.PairSimulationDFS
+
+variable {w : ℕ}
+
+/-- A descriptor's child pointers occupy consecutive words. -/
+theorem EndpointBits.events_reads {src n : ℕ} (m : Memory w) (fit : src+n < 2^w)
+ {allow : ℕ → Prop} (cells : ∀ i : Fin n, allow (src+i.val)) : Reads allow (events m src n) := by
+ induction n generalizing src with
+ | zero =>
+ intro a v read
+ simp [events] at read
+ | succ n ih =>
+ intro a v read
+ rcases List.mem_append.mp read with head | rest
+ · simp only [List.mem_cons, List.not_mem_nil, reduceCtorEq, Event.read.injEq, false_or, or_false] at head
+ have eq : a.val = src := (congrArg Fin.val head.1).trans (Nat.mod_eq_of_lt (by omega))
+ rw [eq]
+ exact cells 0
+ · refine ih (src := src+1) (by omega) ?_ a v rest
+ intro i
+ have h := cells ⟨i.val+1, by omega⟩
+ simpa only [Nat.add_assoc, Nat.add_comm 1] using h
+
+/-- Read addresses use the stored count and pointer of the current row.
+Only rows visited by the selected preorder need to lie below the bound. -/
+theorem DFS.Visits.reads_of_row_bounds {m : Memory w} {endAddr limit : ℕ}
+ {pending nodes : List (Word w)} {es : List (Event w)} (walk : DFS.Visits m endAddr pending nodes es)
+ (bounds : ∀ node ∈ nodes, node.val+2 ≤ limit ∧ (m node.val).val+(m (node.val+1)).val ≤ limit) :
+ Reads (· < limit) es := by
+ induction walk with
+ | nil =>
+ intro a v read
+ simp at read
+ | @cons node pending kids nodes src es row fits rest ih =>
+ have current := bounds node List.mem_cons_self
+ have ha : node.val+1 < 2^w := row.1
+ have hs : src+kids.length < 2^w := row.2.1
+ have hptr : (m node.val).val = src := (congrArg Fin.val row.2.2.1).trans (Nat.mod_eq_of_lt (by omega))
+ have hlen : (m (node.val+1)).val = kids.length :=
+ (congrArg Fin.val row.2.2.2.1).trans (Nat.mod_eq_of_lt (by omega))
+ refine reads_append (es := _ ++ _ ++ _) ?_ (ih (fun v hv => bounds v (List.mem_cons_of_mem _ hv)))
+ refine reads_append (es := _ ++ _) ?_ (EndpointBits.events_reads m hs ?_)
+ · refine reads_append (es := [.tick,.tick,.tick]) (reads_ticks _ 3) ?_
+ intro a v read
+ simp only [headerEvents, List.mem_cons, List.not_mem_nil, reduceCtorEq, Event.read.injEq,
+ false_or, or_false] at read
+ rcases read with h | h
+ · have eq : a.val = node.val := (congrArg Fin.val h.1).trans (Nat.mod_eq_of_lt node.isLt)
+ omega
+ · have eq : a.val = node.val+1 := (congrArg Fin.val h.1).trans (Nat.mod_eq_of_lt ha)
+ omega
+ · intro i
+ have := i.isLt
+ omega
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalReferenceFootprint.lean b/lean/OAI/Computability/VPVNP/PairTraversalReferenceFootprint.lean
new file mode 100644
index 0000000000..70ed9f662f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalReferenceFootprint.lean
@@ -0,0 +1,302 @@
+import OAI.Computability.VPVNP.PairTraversalControllerReference
+import OAI.Computability.VPVNP.PairTraversalControllerPersistence
+
+/-!
+# Memory preserved by every prefix of the native traversal passes
+
+A tag call writes its own tag. A leaf call writes its two header words.
+A fiber call also writes its child row, whose length is the count in the
+retained raw directory. The scan leaves those input directories intact.
+These bounds apply after each reference call, including inside a layer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM PrivateRAM CompressorRecords LocalHistory Compression NetworkKernel
+open TraversalRows TraversalRoles DirectoryRun TraversalControllerInputs
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Only addresses in the half-open interval can differ after a prefix. -/
+def PrefixFrame (lo hi : ℕ) (m : Memory w) (rs : List (Report w)) : Prop :=
+ ∀ q ≤ rs.length, ∀ x, x < lo ∨ hi ≤ x → after m (eventLog (rs.take q)) x = m x
+
+variable {lo hi : ℕ} {m : Memory w} {rs ss : List (Report w)}
+
+private theorem replay_append' (m : Memory w) (rs ss : List (Report w)) :
+ after m (eventLog (rs ++ ss)) = after (after m (eventLog rs)) (eventLog ss) := by
+ simp only [after,eventLog,List.flatMap_append,List.foldl_append]
+
+theorem PrefixFrame.full (h : PrefixFrame lo hi m rs) (x : ℕ) (hx : x < lo ∨ hi ≤ x) :
+ after m (eventLog rs) x = m x := by simpa only [List.take_length] using h rs.length le_rfl x hx
+
+theorem PrefixFrame.widen {a b : ℕ} (h : PrefixFrame lo hi m rs) (hl : a ≤ lo) (hh : hi ≤ b) :
+ PrefixFrame a b m rs := fun q hq x hx => h q hq x (hx.imp (·.trans_le hl) (hh.trans ·))
+
+private theorem PrefixFrame.nil (lo hi : ℕ) (m : Memory w) : PrefixFrame lo hi m [] := by
+ intro q hq x hx
+ simp [eventLog,after]
+
+theorem PrefixFrame.append_at {a b : ℕ} (h : PrefixFrame lo hi m rs)
+ (h' : PrefixFrame a b (after m (eventLog rs)) ss) (q : ℕ) (hq : q ≤ (rs++ss).length)
+ (x : ℕ) (hx : x < lo ∨ hi ≤ x) (hx' : x < a ∨ b ≤ x) :
+ after m (eventLog ((rs++ss).take q)) x = m x := by
+ rw [List.take_append]
+ by_cases le : q ≤ rs.length
+ · simpa only [Nat.sub_eq_zero_of_le le,List.take_zero,List.append_nil] using h q le x hx
+ · rw [List.take_of_length_le (by omega),replay_append']
+ exact (h' (q-rs.length) (by rw [List.length_append] at hq; omega) x hx').trans
+ (h.full x hx)
+
+theorem PrefixFrame.append (h : PrefixFrame lo hi m rs)
+ (h' : PrefixFrame lo hi (after m (eventLog rs)) ss) : PrefixFrame lo hi m (rs++ss) :=
+ fun q hq x hx => h.append_at h' q hq x hx hx
+
+private theorem prefixFrame_of_step (step : ∀ i : Fin rs.length,
+ let before := after m (eventLog (rs.take i.val))
+ (∀ x, x < lo ∨ hi ≤ x → before x = m x) →
+ ∀ x, x < lo ∨ hi ≤ x → after before rs[i.val].events x = before x) : PrefixFrame lo hi m rs := by
+ intro q hq
+ induction q with
+ | zero => exact fun _ _ => rfl
+ | succ q ih =>
+ let i : Fin rs.length := ⟨q,hq⟩
+ have h := ih (Nat.le_of_succ_le hq)
+ intro x hx
+ rw [List.take_succ_eq_append_getElem hq,replay_append']
+ simpa only [i,eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] using
+ (step i h x hx).trans (h x hx)
+
+open private events from OAI.Computability.VPVNP.PairTraversalLeafWorker
+
+/-- Prefixes of the leaf scan are confined to the leaf row interval. -/
+theorem leaf_prefix (cap base count : ℕ) (m : Memory w) (rs : List (Report w))
+ (run : (Pass.leaf (LeafWorker.directory w cap base) count).Run m rs)
+ (fit : address cap base count < 2^w) : PrefixFrame base (address cap base count) m rs := by
+ apply prefixFrame_of_step
+ intro i entry _ x hx
+ let n := address cap base i.val
+ have bound : i.val < count := i.isLt.trans_eq run.length
+ have low : base ≤ n := Nat.le_add_right _ _
+ have high : n + 2 ≤ address cap base count := calc
+ _ ≤ address cap base (i.val+1) := by simp only [n,address,Nat.mul_succ]; omega
+ _ ≤ _ := Nat.add_le_add_left (Nat.mul_le_mul_left _ bound) _
+ have ev := LeafWorker.native cap base i.val 14 entry (by decide)
+ have eq := Option.some.inj ((run.atSite i).symm.trans ev)
+ rw [eq]
+ have hn : (n : Word w).val = n := Nat.mod_eq_of_lt (by omega)
+ have hn' : ((n : Word w)+1).val = n+1 := by
+ rw [← Nat.cast_one (R := Word w),← Nat.cast_add]
+ exact Nat.mod_eq_of_lt (by omega)
+ change after entry (events (n : Word w)) x = _
+ simp only [events,after,List.foldl_cons,List.foldl_nil,BurstRAM.update,writeMemory,hn,hn',
+ ite_eq_right (by omega : x ≠ n),ite_eq_right (by omega : x ≠ n+1)]
+
+/-- Every tag report writes within the current tag interval. -/
+theorem tag_prefix (offset cap base count : ℕ) (tag : Word w) (m : Memory w) (rs : List (Report w))
+ (run : (Pass.tag (Native.params offset cap base tag) count).Run m rs)
+ (fit : offset + address cap base count ≤ 2^w) :
+ PrefixFrame (offset+base) (offset+address cap base count) m rs := by
+ apply prefixFrame_of_step
+ intro i entry _ x hx
+ let a := offset + address cap base i.val
+ have bound : i.val < count := i.isLt.trans_eq run.length
+ have low : offset+base ≤ a := Nat.add_le_add_left (Nat.le_add_right _ _) _
+ have high : a < offset+address cap base count := Nat.add_lt_add_left
+ (Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_left bound (by omega)) _) _
+ let p := Native.params offset cap base tag
+ have eq := Option.some.inj ((run.atSite i).symm.trans (Native.visit_native p (i.val : Word w) entry))
+ have atWord : p 0 + p 1 + p 2 * (i.val : Word w) = (a : Word w) := by
+ simp only [p,Native.params,a,address,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat,add_assoc]
+ rfl
+ rw [eq]
+ change after entry (Native.events p (i.val : Word w)) x = _
+ simp only [Native.events,after,List.foldl_cons,List.foldl_nil,BurstRAM.update,writeMemory,atWord,
+ Fin.val_natCast,Nat.mod_eq_of_lt (high.trans_le fit),ite_eq_right (by omega : x ≠ a)]
+
+open private row_end_le from OAI.Computability.VPVNP.PairTraversalRows
+open private ready_under from OAI.Computability.VPVNP.PairTraversalDirectoryRun
+
+/-- A fiber call only updates the two row headers and the bounded live
+identifier list. The counts for every subsequent call remain readable. -/
+theorem fiber_prefix (p : Fin 6 → Word w) (cap previous base : ℕ) (L : Layer)
+ (raw m : Memory w) (limit : ℕ)
+ (ready : (⟨fun i => countAt p (i.val : Word w),fun i => rowAt p (i.val : Word w)⟩ :
+ Source w L).Ready raw limit)
+ (ag : ∀ x < limit, m x = raw x) (below : limit ≤ base)
+ (capacity : ∀ i, (L.ids i).length ≤ cap) (fit : endPos cap base L < 2^w)
+ (rs : List (Report w)) (run : (Pass.fiber (workerData p cap previous base) cap L.count).Run m rs) :
+ PrefixFrame base (endPos cap base L) m rs := by
+ apply prefixFrame_of_step
+ intro i entry prev x hx
+ let j : Fin L.count := ⟨i.val,i.isLt.trans_eq run.length⟩
+ have hr := ready_under ready (m := entry)
+ (fun y hy => (prev y (Or.inl (hy.trans_le below))).trans (ag y hy)) below
+ obtain ⟨es,run',image,_,_⟩ := directory_worker p L cap previous base hr.sourceBefore capacity fit
+ j entry (hr.rows j)
+ have eq := Option.some.inj ((run.atSite i).symm.trans run')
+ rw [eq]
+ change after entry es x = entry x
+ rw [image]
+ let n := address cap base j.val
+ have lower : base ≤ n := Nat.le_add_right _ _
+ have upper : n+2+(L.ids j).length ≤ endPos cap base L := by
+ have h := row_end_le cap base L j
+ have c := capacity j
+ dsimp only [n]
+ simp only [address] at h ⊢
+ omega
+ have hn : ((n : ℕ) : Word w).val = n := Nat.mod_eq_of_lt (by omega)
+ have hn' : ((n+1 : ℕ) : Word w).val = n+1 := Nat.mod_eq_of_lt (by omega)
+ change DescriptorRows.passMemory entry n _ (n+2) _ _ _ (L.ids j).length x = _
+ simp only [DescriptorRows.passMemory,DescriptorRows.rowMemory,writeMemory,hn,hn',
+ ite_eq_right (by omega : x ≠ n),ite_eq_right (by omega : x ≠ n+1),
+ ite_eq_right (by omega : ¬ (n+2 ≤ x ∧ x < n+2+(L.ids j).length))]
+
+/-- Every reference prefix of all tag jobs stays in their consecutive arena. -/
+theorem tag_chain_prefix {offset cap base : ℕ} {ls : List TaggedLayer}
+ {m : Memory w} {rs : List (Report w)} (run : RolePasses offset cap base ls m rs)
+ (fit : offset+base+tagWords cap ls ≤ 2^w) :
+ PrefixFrame (offset+base) (offset+base+tagWords cap ls) m rs := by
+ induction run with
+ | nil => exact PrefixFrame.nil _ _ _
+ | @cons base l ls m rs ss one rest ih =>
+ let next := endPos cap base l.layer
+ have bound : offset+base+tagWords cap (l::ls) = offset+next+tagWords cap ls := by
+ simp [next,endPos,address,tagWords,words,Nat.mul_add,Nat.add_assoc]
+ rw [bound] at fit ⊢
+ have h₁ : PrefixFrame (offset+base) (offset+next) m rs := tag_prefix offset cap base
+ l.layer.count (l.role.code : Word w) m rs one ((Nat.le_add_right _ _).trans fit)
+ exact (h₁.widen le_rfl (Nat.le_add_right _ _)).append ((ih fit).widen
+ (Nat.add_le_add_left (Nat.le_add_right _ _) _) le_rfl)
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+variable {N Y : Network}
+
+private theorem Segments.head_tail {job : Worker w} {jobs : List (Worker w)}
+ (run : DirectoryRun.Segments (job::jobs) m rs) :
+ ∃ one rest, rs = one++rest ∧ job.Run m one ∧
+ DirectoryRun.Segments jobs (after m (eventLog one)) rest := by
+ cases run with
+ | cons hr ht => exact ⟨_,_,rfl,hr,ht⟩
+
+/-- Native directory workers preserve all addresses outside the selected
+fiber layers, even partway through the current layer. -/
+theorem fiber_chain_prefix (raw : Memory w) (limit : ℕ) (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (old : Order N.Site) (dirs : Directories raw limit c ords old)
+ (ho : OrderedChildren c r ords old) (cap previous base : ℕ) (m : Memory w)
+ (below : limit ≤ base) (ag : ∀ x < limit, m x = raw x)
+ (hc : ∀ L ∈ stepLayers c r ords old, ∀ i, (L.ids i).length ≤ cap)
+ (fit : base+words cap (stepLayers c r ords old) < 2^w)
+ (rs : List (Report w)) (run : DirectoryRun.Segments (workers c ords old dirs cap previous base) m rs) :
+ PrefixFrame base (base+words cap (stepLayers c r ords old)) m rs := by
+ induction c generalizing previous base m rs with
+ | done => cases run; exact PrefixFrame.nil _ _ _
+ | more t data tail ih =>
+ let L := stepLayer old ords.1 r.1
+ let ls := stepLayers tail r.2 ords.2 ords.1
+ let next := endPos cap base L
+ have bound : base+words cap (stepLayers (.more t data tail) r ords old) = next+words cap ls := by
+ simp [L,ls,next,stepLayers,endPos,address,words,Nat.mul_add,Nat.add_assoc]
+ obtain ⟨one,rest,rfl,hr,ht⟩ := Segments.head_tail run
+ rw [bound] at fit ⊢
+ have h₁ : PrefixFrame base next m one := fiber_prefix dirs.1.pub cap previous base L raw m limit
+ (dirs.1.ready r.1 ho.1) ag below (hc _ List.mem_cons_self)
+ ((Nat.le_add_right _ _).trans_lt fit) one hr
+ have nextge : base ≤ next := Nat.le_add_right _ _
+ have h₂ := ih r.2 ords.2 ords.1 dirs.2 ho.2 base next (after m (eventLog one))
+ (below.trans nextge) (fun x hx => (h₁.full x (Or.inl (hx.trans_le below))).trans (ag x hx))
+ (fun l hl => hc l (List.mem_cons_of_mem L hl)) fit rest ht
+ exact (h₁.widen le_rfl (Nat.le_add_right _ _)).append (h₂.widen nextge le_rfl)
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) (f : B.Entry → A)
+variable (hf : B.IsSolution f) {n : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ n)
+variable (X : State (S.degreeExponent 0) n) (z : (B.execute f hf T hT X).Choices)
+variable (base : ℕ) (raw : Memory w)
+variable (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] raw base)
+
+/-- All intermediate descriptor-row memories have the same raw headers and
+the same higher words as the row pass's entry memory. -/
+theorem selected_rows_prefix (m : Memory w) (ag : ∀ x < base, m x = raw x)
+ (rs : List (Report w)) (run : DirectoryRun.Segments (selectedJobs B f hf T hT X z base raw ds) m rs)
+ (fit : base+words B.recordLimit (selectedLayers B f hf T hT X z) < 2^w) :
+ PrefixFrame base (base+words B.recordLimit (selectedLayers B f hf T hT X z)) m rs := by
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ords := branchOrders E data z
+ let old := siteOrder X
+ let r := selectedParsers B f hf T hT X z
+ let dirs := selectedDirectories B f hf T hT X z raw base ds
+ let cap := B.recordLimit
+ let L := leafLayer old
+ let ls := stepLayers c r ords old
+ let next := endPos cap base L
+ have bound : base+words B.recordLimit (selectedLayers B f hf T hT X z) = next+words cap ls := by
+ change base+words cap (L::ls) = _
+ simp [next,endPos,address,words,Nat.mul_add,Nat.add_assoc]
+ rw [bound] at fit ⊢
+ change DirectoryRun.Segments (.leaf cap base old.length :: workers c ords old dirs cap base next) m rs at run
+ obtain ⟨one,rest,rfl,hr,ht⟩ := Segments.head_tail run
+ have h₁ : PrefixFrame base next m one :=
+ leaf_prefix cap base old.length m one hr ((Nat.le_add_right _ _).trans_lt fit)
+ have nextge : base ≤ next := Nat.le_add_right _ _
+ have h₂ := fiber_chain_prefix raw base c r ords old dirs (selectedParsers_ordered B f hf T hT X z)
+ cap base next _ nextge (fun x hx => (h₁.full x (Or.inl hx)).trans (ag x hx))
+ (fun l hl => selected_capacity B f hf T hT X z l (List.mem_cons_of_mem L hl)) fit rest ht
+ exact (h₁.widen le_rfl (Nat.le_add_right _ _)).append (h₂.widen nextge le_rfl)
+
+/-- Every reference prefix preserves each address outside both arenas,
+including the final arc bits in the gap between descriptor rows and tags. -/
+theorem selected_reference_frame (offset : ℕ) (ts rs : List (Report w))
+ (ht : RolePasses offset B.recordLimit base (selected B f hf T hT X z) raw ts)
+ (hr : DirectoryRun.Segments (selectedJobs B f hf T hT X z base raw ds) (after raw (eventLog ts)) rs)
+ (fit : offset+base+tagWords B.recordLimit (selected B f hf T hT X z) < 2^w) :
+ let size := words B.recordLimit (selectedLayers B f hf T hT X z)
+ ∀ q ≤ (ts++rs).length, ∀ x,
+ (x < offset+base ∨ offset+base+size ≤ x) → (x < base ∨ base+size ≤ x) →
+ after raw (eventLog ((ts++rs).take q)) x = raw x := by
+ intro size q hq x htag hrow
+ have eqSize : tagWords B.recordLimit (selected B f hf T hT X z) = size :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ have frameTags := tag_chain_prefix ht fit.le
+ rw [eqSize] at fit frameTags
+ have frameRows := selected_rows_prefix B f hf T hT X z base raw ds (after raw (eventLog ts))
+ (fun x hx => frameTags.full x (Or.inl (hx.trans_le (Nat.le_add_left _ _)))) rs hr
+ (show base+size < 2^w by omega)
+ exact frameTags.append_at frameRows q hq x htag hrow
+
+/-- The resident scheduler fields survive every partial scan of the actual
+selected tag and row workers. The protected low interval contains the raw
+level scalars and the high interval starts at the terminal header. -/
+theorem selected_reference_schedule {pub : Fin 11 → Word w} {H first pitch offset : ℕ}
+ (d : Resident pub raw H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X),.cursor⟩ (levelFibers (executeLevels B f hf T hT X z) ds))
+ (headersBefore : ∀ j ≤ (executeLevels B f hf T hT X z).length, first+j*pitch+28 ≤ base)
+ (ts rs : List (Report w))
+ (ht : RolePasses offset B.recordLimit base (selected B f hf T hT X z) raw ts)
+ (hr : DirectoryRun.Segments (selectedJobs B f hf T hT X z base raw ds) (after raw (eventLog ts)) rs)
+ (belowHeader : offset+base+tagWords B.recordLimit (selected B f hf T hT X z) ≤ H) :
+ ∀ q ≤ (ts++rs).length, let entry := after raw (eventLog ((ts++rs).take q))
+ Schedule pub entry offset B.recordLimit base (selected B f hf T hT X z)
+ (selectedJobs B f hf T hT X z base raw ds) ∧ (siteCount pub entry 0).val = X.positions := by
+ have hfH : H < 2^w := by have := d.headerFits; omega
+ have frame := selected_reference_frame B f hf T hT X z base raw ds offset ts rs ht hr (belowHeader.trans_lt hfH)
+ have eqSize := congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ change offset+base+words B.recordLimit ((selected B f hf T hT X z).map TaggedLayer.layer) ≤ H at belowHeader
+ rw [eqSize] at belowHeader
+ exact selected_prefix_schedule B f hf T hT X z raw ds d headersBefore (ts++rs)
+ (fun q hq x hx => frame q hq x (Or.inl (hx.trans_le (Nat.le_add_left _ _))) (Or.inl hx))
+ (fun q hq j _ => frame q hq _ (Or.inr (by omega)) (Or.inr (by omega)))
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalReferenceReads.lean b/lean/OAI/Computability/VPVNP/PairTraversalReferenceReads.lean
new file mode 100644
index 0000000000..7535cdb82c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalReferenceReads.lean
@@ -0,0 +1,218 @@
+import OAI.Computability.VPVNP.PairTraversalReferenceFootprint
+import OAI.Computability.VPVNP.PairTraversalSiteReads
+
+/-!
+# Raw input addresses of the selected traversal passes
+
+The tag and leaf workers only write. Each fiber worker reads a count and the
+corresponding identifiers from the retained placement directory. Every prefix
+of the descriptor scan preserves these raw inputs, including between two
+sites of the same layer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalController
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords LocalHistory Compression NetworkKernel
+open TraversalRows TraversalRoles DirectoryRun TraversalControllerInputs
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem reads_append {data : ℕ → Prop} {rs ss : List (Report w)}
+ (h : SourceTransport.Reads data (eventLog rs)) (k : SourceTransport.Reads data (eventLog ss)) :
+ SourceTransport.Reads data (eventLog (rs ++ ss)) := by
+ intro a v mem
+ rw [show eventLog (rs ++ ss) = eventLog rs ++ eventLog ss from List.flatMap_append] at mem
+ exact (List.mem_append.mp mem).elim (h a v) (k a v)
+
+private theorem reads_of_calls {data : ℕ → Prop} {rs : List (Report w)}
+ (h : ∀ i : Fin rs.length, SourceTransport.Reads data rs[i.val].events) :
+ SourceTransport.Reads data (eventLog rs) := by
+ intro a v mem
+ obtain ⟨r, hr, he⟩ := List.mem_flatMap.mp mem
+ obtain ⟨i, hi, rfl⟩ := List.mem_iff_getElem.mp hr
+ exact h ⟨i,hi⟩ a v he
+
+open private events from OAI.Computability.VPVNP.PairTraversalLeafWorker
+
+/-- Every tag worker has an empty external read set. -/
+theorem tag_reads {p : Fin 4 → Word w} {count : ℕ} {m : Memory w} {rs : List (Report w)}
+ (h : (Pass.tag p count).Run m rs) (data : ℕ → Prop) :
+ SourceTransport.Reads data (eventLog rs) := by
+ apply reads_of_calls
+ intro i a v mem
+ have eqn := Option.some.inj ((h.atSite i).symm.trans (Native.visit_native p _ _))
+ rw [eqn] at mem
+ simp [Native.events] at mem
+
+/-- Every leaf worker has an empty external read set, including its header writes. -/
+theorem leaf_reads (cap base count : ℕ) {m : Memory w} {rs : List (Report w)}
+ (h : (Pass.leaf (LeafWorker.directory w cap base) count).Run m rs) (data : ℕ → Prop) :
+ SourceTransport.Reads data (eventLog rs) := by
+ apply reads_of_calls
+ intro i a v mem
+ let entry := after m (eventLog (rs.take i.val))
+ have native := LeafWorker.native cap base i.val 14 entry (by decide)
+ have eqn := Option.some.inj ((h.atSite i).symm.trans native)
+ rw [eqn] at mem
+ simp [events] at mem
+
+open private ready_under from OAI.Computability.VPVNP.PairTraversalDirectoryRun
+open private row_end_le from OAI.Computability.VPVNP.PairTraversalRows
+
+/-- Every site in a fiber layer reads its retained count and source identifiers
+strictly below the original raw-directory limit. -/
+theorem fiber_reads (p : Fin 6 → Word w) (cap previous base : ℕ) (L : Layer)
+ (raw m : Memory w) (limit : ℕ)
+ (ready : (⟨fun i => countAt p (i.val : Word w), fun i => rowAt p (i.val : Word w)⟩ :
+ Source w L).Ready raw limit)
+ (ag : ∀ x < limit, m x = raw x) (below : limit ≤ base)
+ (capacity : ∀ i, (L.ids i).length ≤ cap) (fit : endPos cap base L < 2 ^ w)
+ (rs : List (Report w))
+ (run : (Pass.fiber (workerData p cap previous base) cap L.count).Run m rs) :
+ SourceTransport.Reads (· < limit) (eventLog rs) := by
+ have frame := fiber_prefix p cap previous base L raw m limit ready ag below capacity fit rs run
+ apply reads_of_calls
+ intro i
+ let j : Fin L.count := ⟨i.val, i.isLt.trans_eq run.length⟩
+ let entry := after m (eventLog (rs.take i.val))
+ let data := workerData p cap previous base
+ let src := (rowAt p (i.val : Word w)).val
+ let node := address cap base i.val
+ have seen : ∀ x < limit, entry x = raw x := fun x hx =>
+ (frame i.val i.isLt.le x (Or.inl (hx.trans_le below))).trans (ag x hx)
+ have rows := (ready_under ready seen le_rfl).rows j
+ have hs : SiteWorker.source data (i.val : Word w) = (src : Word w) :=
+ Fin.ext (Nat.mod_eq_of_lt (rowAt p (i.val : Word w)).isLt).symm
+ have hn : SiteWorker.node data (i.val : Word w) = (node : Word w) := by
+ change (base : Word w) + (i.val : Word w) * ((cap + 2 : ℕ) : Word w) =
+ ((base + (cap + 2) * i.val : ℕ) : Word w)
+ simp only [Nat.cast_add, Nat.cast_mul]
+ rw [mul_comm]
+ have hc : (entry (SiteWorker.counter data (i.val : Word w)).val).val = (L.ids j).length := by
+ change (entry (countAt p (i.val : Word w)).val).val = _
+ simpa only [List.length_map] using rows.1
+ have srcBelow : src + (L.ids j).length ≤ limit := ready.sourceBefore j
+ have cntBelow : (SiteWorker.counter data (i.val : Word w)).val < limit := ready.countBefore j
+ have within : node + 2 + (L.ids j).length < 2 ^ w := by
+ have := row_end_le cap base L j
+ have := capacity j
+ dsimp only [node, j] at *
+ omega
+ have one := SiteWorker.native_reads data (i.val : Word w) entry src node (L.ids j).length
+ (7 * cap + 25) hs hn hc (srcBelow.trans (below.trans (Nat.le_add_right _ _))) within
+ (by have := capacity j; omega) (run.atSite i)
+ intro a v mem
+ rcases one a v mem with atCount | inRow
+ · exact atCount ▸ cntBelow
+ · exact inRow.2.trans_le srcBelow
+
+/-- Tagging any number of layers uses no external reads. -/
+theorem tag_chain_reads {offset cap base : ℕ} {ls : List TaggedLayer}
+ {m : Memory w} {rs : List (Report w)} (h : RolePasses offset cap base ls m rs)
+ (data : ℕ → Prop) :
+ SourceTransport.Reads data (eventLog rs) := by
+ induction h with
+ | nil => exact fun _ _ he => (List.not_mem_nil he).elim
+ | cons one _ ih => exact reads_append (tag_reads one data) ih
+
+open private Segments.head_tail from OAI.Computability.VPVNP.PairTraversalReferenceFootprint
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+variable {N Y : Network}
+
+/-- The same raw-directory limit applies to every later fiber layer, even as
+the base of the new descriptors advances. -/
+theorem fiber_chain_reads (raw : Memory w) (limit : ℕ) (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ords : ChainOrders c) (old : Order N.Site) (dirs : Directories raw limit c ords old)
+ (ho : OrderedChildren c r ords old) (cap previous base : ℕ) (m : Memory w)
+ (below : limit ≤ base) (ag : ∀ x < limit, m x = raw x)
+ (hc : ∀ L ∈ stepLayers c r ords old, ∀ i, (L.ids i).length ≤ cap)
+ (fit : base + words cap (stepLayers c r ords old) < 2 ^ w)
+ (rs : List (Report w))
+ (run : DirectoryRun.Segments (workers c ords old dirs cap previous base) m rs) :
+ SourceTransport.Reads (· < limit) (eventLog rs) := by
+ induction c generalizing previous base m rs with
+ | done => cases run; exact fun _ _ he => (List.not_mem_nil he).elim
+ | more t data tail ih =>
+ let L := stepLayer old ords.1 r.1
+ let ls := stepLayers tail r.2 ords.2 ords.1
+ let next := endPos cap base L
+ have bound : base + words cap (stepLayers (.more t data tail) r ords old) =
+ next + words cap ls := by
+ simp [L, ls, next, stepLayers, endPos, address, words, Nat.mul_add, Nat.add_assoc]
+ obtain ⟨one, rest, rfl, hr, ht⟩ := Segments.head_tail run
+ rw [bound] at fit
+ have within : next < 2 ^ w := (Nat.le_add_right _ _).trans_lt fit
+ have ready := dirs.1.ready r.1 ho.1
+ have head := fiber_reads dirs.1.pub cap previous base L raw m limit ready ag below
+ (hc _ List.mem_cons_self) within one hr
+ have frame := fiber_prefix dirs.1.pub cap previous base L raw m limit ready ag below
+ (hc _ List.mem_cons_self) within one hr
+ apply reads_append head
+ exact ih r.2 ords.2 ords.1 dirs.2 ho.2 base next (after m (eventLog one))
+ (below.trans (Nat.le_add_right _ _))
+ (fun x hx => (frame.full x (Or.inl (hx.trans_le below))).trans (ag x hx))
+ (fun l hl => hc l (List.mem_cons_of_mem L hl)) fit rest ht
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (f : B.Entry → A)
+variable (hf : B.IsSolution f) {n : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n)
+variable (X : State (S.degreeExponent 0) n) (z : (B.execute f hf T hT X).Choices)
+variable (base : ℕ) (raw : Memory w)
+variable (ds : let vs := executeLevels B f hf T hT X z
+ (i : Fin vs.length) → LevelDirectory vs[i] raw base)
+
+/-- Complete reference read footprint of the selected tag and descriptor
+passes, starting from the retained branch directories. -/
+theorem selected_reference_reads (offset : ℕ) (ts rs : List (Report w))
+ (tags : RolePasses offset B.recordLimit base (selected B f hf T hT X z) raw ts)
+ (rows : DirectoryRun.Segments (selectedJobs B f hf T hT X z base raw ds)
+ (after raw (eventLog ts)) rs)
+ (fit : offset + base + tagWords B.recordLimit (selected B f hf T hT X z) < 2 ^ w) :
+ SourceTransport.Reads (· < base) (eventLog (ts ++ rs)) := by
+ refine reads_append (tag_chain_reads tags (· < base)) ?_
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ords := branchOrders E data z
+ let old := siteOrder X
+ let r := selectedParsers B f hf T hT X z
+ let dirs := selectedDirectories B f hf T hT X z raw base ds
+ let cap := B.recordLimit
+ let L := leafLayer old
+ let ls := stepLayers c r ords old
+ let next := endPos cap base L
+ let m := after raw (eventLog ts)
+ have tagFrame := tag_chain_prefix tags fit.le
+ have ag (x : ℕ) (hx : x < base) : m x = raw x :=
+ tagFrame.full x (Or.inl (hx.trans_le (Nat.le_add_left _ _)))
+ have eqSize : tagWords cap (selected B f hf T hT X z) =
+ words cap (selectedLayers B f hf T hT X z) :=
+ congrArg (words cap) (selected_layers B f hf T hT X z)
+ have size : base + words cap (selectedLayers B f hf T hT X z) < 2 ^ w := by
+ change offset + base + tagWords cap (selected B f hf T hT X z) < _ at fit
+ rw [eqSize] at fit
+ omega
+ have bound : base + words cap (selectedLayers B f hf T hT X z) = next + words cap ls := by
+ change base + words cap (L :: ls) = _
+ simp [next, endPos, address, words, Nat.mul_add, Nat.add_assoc]
+ rw [bound] at size
+ change DirectoryRun.Segments (.leaf cap base old.length ::
+ workers c ords old dirs cap base next) m rs at rows
+ obtain ⟨one, rest, rfl, hr, ht⟩ := Segments.head_tail rows
+ have leaf := leaf_prefix cap base old.length m one hr ((Nat.le_add_right _ _).trans_lt size)
+ refine reads_append (leaf_reads cap base old.length hr (· < base)) ?_
+ exact fiber_chain_reads raw base c r ords old dirs (selectedParsers_ordered B f hf T hT X z)
+ cap base next _ (Nat.le_add_right _ _)
+ (fun x hx => (leaf.full x (Or.inl hx)).trans (ag x hx))
+ (fun l hl => selected_capacity B f hf T hT X z l (List.mem_cons_of_mem L hl)) size rest ht
+
+end PairSimulation.TraversalController
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalResidentHandoff.lean b/lean/OAI/Computability/VPVNP/PairTraversalResidentHandoff.lean
new file mode 100644
index 0000000000..373d9a06be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalResidentHandoff.lean
@@ -0,0 +1,252 @@
+import OAI.Computability.VPVNP.PairTerminalPrefixLinked
+import OAI.Computability.VPVNP.PairTerminalPrefixBudget
+import OAI.Computability.VPVNP.PairTerminalSelectedHeaders
+import OAI.Computability.VPVNP.CompressorSelectedDirectoryHistory
+
+/-!
+# Traversal operands at the prefix-to-row boundary
+
+The final prefix table is above all previous pass directories and the scalar
+fields of the final level. The prefix worker changes the high-header total
+and role offset, while the linker uses its phase and saved ordinal. This
+separation preserves the chronological directories and supplies the operand
+words to the first traversal call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalResidentHandoff
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles TraversalControllerInputs TerminalPrefix TerminalPrefix.Linked
+open scoped Fin.CommRing
+
+variable {w a g : ℕ}
+
+/-- The scalar operands of every live pass end before the DFS arena. -/
+theorem headers_before (L : Layout) {last : ℕ} (hl : last < L.levels)
+ (wide : 28 ≤ L.shape.scalarFields) (j : ℕ) (hj : j ≤ last) :
+ levelStart L 0 + j * levelWords L + 28 ≤ endAddress L := by
+ have span : 28 ≤ levelWords L := by unfold levelWords levelHeaderWords; omega
+ have next := levelStart_mono L (show j+1 ≤ L.levels by omega)
+ simpa only [levelStart, Nat.succ_mul, Nat.zero_mul, Nat.add_zero, endAddress,
+ Nat.add_assoc] using (Nat.add_le_add_left span (levelStart L j)).trans (by
+ simpa only [levelStart, Nat.succ_mul, Nat.add_assoc] using next)
+
+/-- Calendar cells strictly before the last scalar-header boundary are
+retained. The remaining traversal operands have the values written by the
+bootstrap or by the prefix worker's closing call. -/
+structure Fields (L : Layout) (last : ℕ) (tab : Fin L.shape.tables) (A : TerminalBootstrap.Header L last)
+ (cap H : ℕ) (Y : State a g) (pub : Fin 11 → Word w) (calendar out : Memory w) : Prop where
+ head : terminalHead pub = (H : Word w)
+ fits : H + 32 ≤ 2 ^ w
+ levelFrame : ∀ x < levelStart L last + 28, out x = calendar x
+ tableFrame : ∀ x < H, x < tableBase L last tab ∨ tableBase L last tab + arcCount Y ≤ x →
+ out x = calendar x
+ headerFields : ∀ i : Fin 21, 0 < i.val → i.val ≠ 12 → i.val ≠ 14 →
+ out (H+i.val) = TerminalBootstrap.values L last A cap pub calendar i
+ total : (out (H+12)).val = Y.totalWidth
+ arenaFits : endAddress L ≤ H
+ levelCountFit : last+1 < 2 ^ w
+ finalSitesFit : Y.positions < 2 ^ w
+ levels : out (H+1) = ((last+1 : ℕ) : Word w)
+ sites : out (H+7) = (A.sites : Word w)
+ offset : out (H+14) = ((A.rowWords cap + Y.totalWidth : ℕ) : Word w)
+ stride : out (H+15) = ((cap+2 : ℕ) : Word w)
+ first : out (H+16) = (levelStart L 0 : Word w)
+ pitch : out (H+17) = (levelWords L : Word w)
+
+/-- Read the operands from any memory agreeing with the standalone prefix
+reports off the two linker control cells. The physical prefix exit satisfies
+this agreement by `Start.handoff_rows`. -/
+theorem fields_of_start (L : Layout) (last : ℕ) (hl : last < L.levels)
+ (tab : Fin L.shape.tables) (A : TerminalBootstrap.Header L last) (limit r : ℕ)
+ {workers : TerminalLink.Stage → LiveProgram.PairTable} {clock fuel : ℕ}
+ (Y : State a g) (pub : Fin 11 → Word w) (calendar out : Memory w)
+ (ready : TerminalBootstrap.Ready L last A pub calendar)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ L.base + 2 ^ r * 2 ^ r)
+ (room : L.base + 2 ^ r * 2 ^ r ≤ 2 ^ w)
+ (above : endAddress L ≤ TerminalBootstrap.address L.base r)
+ (wide : 28 ≤ L.shape.scalarFields) (cells : arcCount Y ≤ tableWords L)
+ (rs : List (Report w)) :
+ let boot := TerminalBootstrap.report L.shape limit pub 0 calendar
+ let dir := packedIncidence L w last (arcCount Y)
+ Start workers pub clock fuel Y dir (tableBase L last tab) calendar boot rs →
+ SourceTransport.Agree (TerminalLink.workerCell (TerminalLink.header pub))
+ (after (after calendar boot.events) (eventLog rs)) out →
+ Fields L last tab A limit (TerminalBootstrap.address L.base r) Y pub calendar out := by
+ intro boot dir start agree
+ let H := TerminalBootstrap.address L.base r
+ let h := TerminalLink.header pub
+ let src := after calendar boot.events
+ let scan := after src (eventLog rs)
+ let ptr := (tableBase L last tab : Word w)
+ have hv : h.val = H := header_val L pub r ready.workspace exp hr reserve room
+ have fits : H + 32 ≤ 2 ^ w := by dsimp only [H, TerminalBootstrap.address]; omega
+ have pos (i : ℕ) (hi : i < 32) : (h + (i : Word w)).val = H + i := by
+ rw [Fin.val_add, hv, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : i < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega)]
+ have before := (tableEnd_le_nextLevel L last tab).trans ((levelStart_mono L hl).trans above)
+ have ptrVal : ptr.val = tableBase L last tab := Nat.mod_eq_of_lt (by omega)
+ have prefixEnd : ptr.val + arcCount Y ≤ H := by rw [ptrVal]; omega
+ have saved : (h+31).val = H+31 := pos 31 (by decide)
+ have data (x : ℕ) (x₀ : x ≠ H) (x₁ : x ≠ H+31) :
+ TerminalLink.workerCell h x := by
+ change x ≠ h.val ∧ x ≠ (h+31).val
+ rwa [hv,saved,and_iff_right x₀]
+ obtain ⟨_, _, stored, keep, _⟩ := TerminalBootstrap.native L last A limit pub calendar 0
+ ready r exp hr reserve room
+ have totalPos : (h+12).val = H+12 := pos 12 (by decide)
+ have rolePos : (h+14).val = H+14 := pos 14 (by decide)
+ have outside (x : ℕ) (h₁ : x ≠ H+12) (h₂ : x ≠ H+14)
+ (hx : x < ptr.val ∨ ptr.val + arcCount Y ≤ x) : scan x = src x := by
+ have frame := start.rawScan.stored.outside x (totalPos ▸ h₁) hx
+ change scan x = writeMemory src (h+14) _ x at frame
+ simpa only [writeMemory, rolePos, ite_eq_right h₂] using frame
+ have read (i : Fin 21) (hi : 0 < i.val) (ht : i.val ≠ 12) (hr : i.val ≠ 14) :
+ out (H+i.val) = TerminalBootstrap.values L last A limit pub calendar i := by
+ have small := i.isLt
+ exact (agree _ (data _ (by omega) (by omega))).symm.trans
+ ((outside _ (by omega) (by omega) (.inr (by omega))).trans (stored i))
+ have low : levelStart L last + 28 ≤ ptr.val := by
+ rw [ptrVal]
+ unfold tableBase arrayBase incidenceStart levelHeaderWords
+ omega
+ have head : terminalHead pub = (H : Word w) := by
+ simpa only [ready.workspace,exp,H,TerminalBootstrap.address] using
+ terminalHead_eq_nat pub (exp ▸ hr) (by rwa [ready.workspace,exp])
+ have pitchPos : 0 < levelWords L := by unfold levelWords levelHeaderWords; omega
+ have bound : last+1 ≤ endAddress L := by
+ apply (Nat.le_mul_of_pos_right (last+1) pitchPos).trans
+ exact (Nat.le_add_left ..).trans (levelStart_mono L hl)
+ have sitesLe : Y.positions ≤ arcCount Y := by
+ rw [Segment.arc_count_positions]
+ exact Nat.le_mul_of_pos_right _ (by positivity)
+ have frame (x : ℕ) (hx : x < H) (ht : x < ptr.val ∨ ptr.val + arcCount Y ≤ x) :
+ out x = calendar x :=
+ (agree _ (data _ (by omega) (by omega))).symm.trans
+ ((outside x (by omega) (by omega) ht).trans (keep x (.inl hx)))
+ refine ⟨head, fits, ?_, ?_, read, ?_, above, by omega, by omega,
+ read 1 (by decide) (by decide) (by decide), read 7 (by decide) (by decide) (by decide), ?_,
+ read 15 (by decide) (by decide) (by decide), read 16 (by decide) (by decide) (by decide),
+ read 17 (by decide) (by decide) (by decide)⟩
+ · intro x hx
+ have below := hx.trans_le low
+ exact frame x (by omega) (.inl below)
+ · simpa only [ptrVal] using frame
+ · exact (congrArg Fin.val (agree _ (data (H+12) (by omega) (by omega))).symm).trans
+ (totalPos ▸ start.rawScan.stored.total)
+ · have role := start.rawScan.role
+ change scan (h+14).val = src (h+5).val + (Y.totalWidth : Word w) at role
+ rw [rolePos, show (h+5).val = H+5 from pos 5 (by decide),
+ show src (H+5) = (A.rowWords limit : Word w) from stored 5] at role
+ exact (agree _ (data _ (by omega) (by omega))).symm.trans (role.trans (Nat.cast_add ..).symm)
+
+open LocalHistory SelectedDirectoryHistory
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable {n : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+local notation "vs" => executeLevels B f hf T hT X z
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+
+/-- The same directories that were produced by the selected pass executions
+supply the traversal workers on the prefix exit memory. -/
+theorem selected_resident (L : Layout) (baseBits laneBits : ℕ) (tab : Fin L.shape.tables)
+ {H : ℕ} {pub : Fin 11 → Word w} {calendar out : Memory w}
+ (D : Retained B f hf T hT X z L (endAddress L) calendar)
+ (fields : Fields L (ls).dropLast.length tab
+ (TerminalBootstrap.fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab)
+ B.recordLimit H (Y) pub calendar out)
+ (hl : (ls).dropLast.length < L.levels) (wide : 28 ≤ L.shape.scalarFields) :
+ ∃ ds : (i : Fin (vs).length) → LevelDirectory vs[i] out (endAddress L),
+ (∀ i, (ds i).pub = (D.dirs i).pub) ∧
+ Resident pub out H (levelStart L 0) (levelWords L)
+ (words B.recordLimit (ls) + (Y).totalWidth) B.recordLimit (endAddress L)
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers (vs) ds) ∧
+ ∀ j ≤ (vs).length, levelStart L 0 + j * levelWords L + 28 ≤ endAddress L := by
+ have last : (ls).dropLast.length = (vs).length := by
+ simp only [List.length_dropLast, selectedLayers_eq_levels, List.length_cons, List.length_map,
+ Nat.add_sub_cancel]
+ let kept := D.transport (raw' := out) (fun x _ hx => fields.levelFrame x (last ▸ hx))
+ have before (j : ℕ) (hj : j ≤ (vs).length) :=
+ headers_before L hl wide j (last ▸ hj)
+ have count : (out (H+1)).val = (vs).length+1 := by
+ rw [fields.levels, Fin.val_natCast, Nat.mod_eq_of_lt fields.levelCountFit, last]
+ have off := fields.offset
+ rw [TerminalBootstrap.selected_rowWords] at off
+ have addr (j : ℕ) : levelStart L 0 + j * levelWords L = levelStart L j := by
+ simp [levelStart]
+ refine ⟨kept.dirs,fun _ => rfl,?_,before⟩
+ apply selected_resident_of_directory_fields B f hf T hT X z (endAddress L) out kept.dirs
+ fields.head fields.fits fields.first fields.pitch off fields.stride count
+ · intro j hj
+ have bound := before j hj
+ have fh := fields.fits
+ have lower := fields.arenaFits
+ omega
+ · intro j hj
+ rw [addr]
+ exact kept.current j hj
+ · intro j
+ rw [addr]
+ exact kept.role j
+ · intro i hi
+ simpa only [hi] using kept.old i
+ · intro empty
+ have sizes := (TerminalBootstrap.selected_counts B f hf T hT X z).symm.trans
+ (selected_layer_counts B f hf T hT X z)
+ have same : (Y).positions = X.positions := by simpa only [empty, List.map_nil, List.nil_append,
+ List.cons.injEq, and_true] using sizes
+ rw [fields.sites, TerminalBootstrap.fromState_sites, Fin.val_natCast,
+ Nat.mod_eq_of_lt fields.finalSitesFit, same]
+ · intro i
+ rw [addr]
+ exact kept.directory i
+
+/-- The physical entry to traversal-row construction has exactly the operand
+banks of the selected calendar. The calendar's online control words may have
+changed between the raw pass run and the terminal bootstrap. -/
+theorem selected_physical (L : Layout) (baseBits laneBits : ℕ) (tab : Fin L.shape.tables)
+ {workers : TerminalLink.Stage → LiveProgram.PairTable} {clock fuel : ℕ}
+ (r : ℕ) (pub : Fin 11 → Word w) (raw calendar : Memory w)
+ (D : Retained B f hf T hT X z L (endAddress L) raw)
+ (online : SourceTransport.Agree (levelStart L 0 ≤ ·) raw calendar)
+ (size : L.levels = T * (S.steps + 1) + 1) (wide : 28 ≤ L.shape.scalarFields)
+ (ready : TerminalBootstrap.Ready L (ls).dropLast.length
+ (TerminalBootstrap.fromState L (ls).dropLast B.recordLimit baseBits laneBits (Y) tab) pub calendar)
+ (exp : (pub 7).val = r) (hr : r < w) (reserve : 32 ≤ L.base + 2 ^ r * 2 ^ r)
+ (room : L.base + 2 ^ r * 2 ^ r ≤ 2 ^ w)
+ (above : endAddress L ≤ TerminalBootstrap.address L.base r)
+ (cells : arcCount (Y) ≤ tableWords L) (rs : List (Report w)) :
+ let last := (ls).dropLast.length
+ let boot := TerminalBootstrap.report L.shape B.recordLimit pub 0 calendar
+ let dir := packedIncidence L w last (arcCount (Y))
+ let out := prefixMemory pub calendar boot rs
+ Start workers pub clock fuel (Y) dir (tableBase L last tab) calendar boot rs →
+ ∃ ds : (i : Fin (vs).length) → LevelDirectory vs[i] out (endAddress L),
+ (∀ i, (ds i).pub = (D.dirs i).pub) ∧
+ Resident pub out (TerminalBootstrap.address L.base r) (levelStart L 0) (levelWords L)
+ (words B.recordLimit (ls) + (Y).totalWidth) B.recordLimit (endAddress L)
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers (vs) ds) ∧
+ ∀ j ≤ (vs).length, levelStart L 0 + j * levelWords L + 28 ≤ endAddress L := by
+ intro last boot dir out start
+ have hl : last < L.levels := by
+ change (ls).dropLast.length < L.levels
+ rw [TerminalBootstrap.selected_prior_length, size]
+ omega
+ let dc := D.transport (raw' := calendar) (fun x hx _ =>
+ (online x (by simpa only [levelStart,Nat.zero_mul,Nat.add_zero] using hx)).symm)
+ have h := fields_of_start L last hl tab _ B.recordLimit r (Y) pub calendar out ready
+ exp hr reserve room above wide cells rs start start.handoff_rows.1
+ exact selected_resident B f hf T hT X z L baseBits laneBits tab dc h hl wide
+
+end PairSimulation.TraversalResidentHandoff
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalRoleDispatch.lean b/lean/OAI/Computability/VPVNP/PairTraversalRoleDispatch.lean
new file mode 100644
index 0000000000..d0845e6832
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalRoleDispatch.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.PairTraversalRoleExecution
+import OAI.Computability.VPVNP.PairNodeDispatch
+
+/-!
+# The native dispatch opcode reads the selected pass's role
+
+The DFS uses a word-valued node address. The table uses the same absolute
+address plus a fixed public offset. The full tag-region bound proves there
+is no wraparound for any selected node.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRoles
+
+open BurstRAM TraversalRows Compression LocalHistory CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Case labels used in the native router. -/
+def Role.dispatch : Role → NodeDispatch.Role
+ | .cursor => .leaf
+ | .shrink => .shrink
+ | .refresh => .refresh
+
+theorem Role.decode (r : Role) (fit : 2 < 2 ^ w) :
+ NodeDispatch.role (r.code : Word w) = r.dispatch := by
+ have h1 : (1 : Word w) ≠ 0 := by
+ intro e
+ have h := congrArg Fin.val e
+ change 1 % (2 ^ w) = 0 at h
+ rw [Nat.mod_eq_of_lt (by omega)] at h
+ omega
+ have h2 : (2 : Word w) ≠ 0 := by
+ intro e
+ have h := congrArg Fin.val e
+ change 2 % (2 ^ w) = 0 at h
+ rw [Nat.mod_eq_of_lt fit] at h
+ omega
+ have h21 : (2 : Word w) ≠ 1 := by
+ intro e
+ have h := congrArg Fin.val e
+ change 2 % (2 ^ w) = 1 % (2 ^ w) at h
+ rw [Nat.mod_eq_of_lt fit, Nat.mod_eq_of_lt (by omega)] at h
+ omega
+ cases r <;> simp [Role.code, Role.dispatch, NodeDispatch.role, h1, h2, h21]
+
+private theorem layerAddress_lt (cap base : ℕ) (ls : List TaggedLayer) (i : Fin ls.length)
+ (j : Fin ls[i].layer.count) : address cap (layerBase cap base ls i.val) j.val <
+ base + tagWords cap ls := by
+ induction ls generalizing base with
+ | nil => exact Fin.elim0 i
+ | cons L ls ih =>
+ have bound : base + tagWords cap (L :: ls) = endPos cap base L.layer + tagWords cap ls := by
+ simp [endPos, address, tagWords, words, Nat.mul_add, Nat.add_assoc]
+ rw [bound]
+ cases i using Fin.cases with
+ | zero =>
+ change address cap (layerBase cap base (L :: ls) 0) j.val < _
+ rw [layerBase_zero]
+ exact (Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_left j.isLt (by omega)) _).trans_le
+ (Nat.le_add_right _ _)
+ | succ i =>
+ simpa only [Fin.getElem_fin, Fin.val_succ, List.getElem_cons_succ, layerBase_cons] using
+ ih (endPos cap base L.layer) i j
+
+/-- At any selected layer and site, the machine's one external read dispatches
+to precisely the handler corresponding to the retained pass origin. -/
+theorem Reads.dispatch {m : Memory w} {offset cap base : ℕ} {ls : List TaggedLayer}
+ (hr : Reads w m offset cap base ls) (codes : 2 < 2 ^ w)
+ (fit : offset + base + tagWords cap ls ≤ 2 ^ w) (i : Fin ls.length)
+ (j : Fin ls[i].layer.count) :
+ let node := address cap (layerBase cap base ls i.val) j.val
+ NodeDispatch.role (m (((offset : Word w) + (node : Word w)).val)) = ls[i].role.dispatch := by
+ intro node
+ have room : offset + node < 2 ^ w := by
+ have h := Nat.add_lt_add_left (layerAddress_lt cap base ls i j) offset
+ simpa only [Nat.add_assoc] using h.trans_le (Nat.add_assoc .. ▸ fit)
+ rw [probe_word_add offset node m room, hr.at_layer i j]
+ exact Role.decode _ codes
+
+end PairSimulation.TraversalRoles
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalRoleExecution.lean b/lean/OAI/Computability/VPVNP/PairTraversalRoleExecution.lean
new file mode 100644
index 0000000000..dbf93413e7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalRoleExecution.lean
@@ -0,0 +1,199 @@
+import OAI.Computability.VPVNP.PairTraversalRoles
+import OAI.Computability.VPVNP.PairTraversalBuildExecution
+
+/-!
+# Native role directory for the selected history
+
+One pass per physical level writes the cursor, shrink, or refresh tag at the
+public offset from each live descriptor header. Each pass starts with the
+memory left by its predecessor. A separate final-bit interval can occupy
+the gap between the descriptor region and these sparse tags.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRoles
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression TraversalRows LocalHistory
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Post-memory of the per-layer writes. -/
+noncomputable def writeTags (offset cap base : ℕ) : List TaggedLayer → Memory w → Memory w
+ | [], m => m
+ | L :: ls, m => writeTags offset cap (endPos cap base L.layer) ls
+ (Native.image offset cap base L.layer.count (L.role.code : Word w) m)
+
+/-- The word region occupied by these tags has the same extent as the
+corresponding row region, translated by the public offset. -/
+def tagWords (cap : ℕ) (ls : List TaggedLayer) : ℕ := words cap (ls.map TaggedLayer.layer)
+
+private theorem tagWords_cons (cap : ℕ) (L : TaggedLayer) (ls : List TaggedLayer) :
+ tagWords cap (L :: ls) = (cap + 2) * L.layer.count + tagWords cap ls := by
+ simp [tagWords, words, Nat.mul_add]
+
+/-- Tag writing cannot alter any earlier descriptor, final bit, or memory cell
+outside its own layer intervals. -/
+theorem write_tags_outside (offset cap base : ℕ) (ls : List TaggedLayer) (m : Memory w) (x : ℕ)
+ (hx : x < offset + base ∨ offset + base + tagWords cap ls ≤ x) :
+ writeTags offset cap base ls m x = m x := by
+ induction ls generalizing base m with
+ | nil => rfl
+ | cons L ls ih =>
+ let next := endPos cap base L.layer
+ have hn : base ≤ next := Nat.le_add_right _ _
+ have he : offset + base + tagWords cap (L :: ls) = offset + next + tagWords cap ls := by
+ simp [next, endPos, address, tagWords_cons, Nat.add_assoc]
+ have ht : x < offset + next ∨ offset + next + tagWords cap ls ≤ x := by omega
+ apply (ih next _ ht).trans
+ apply Native.image_outside
+ intro i hi
+ have hlo : base ≤ address cap base i := Nat.le_add_right _ _
+ have hhi : address cap base i < next := by
+ exact Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_left hi (by omega)) _
+ omega
+
+/-- Every selected layer's role can be read back at each site's actual header
+address. -/
+theorem writeTags_reads (offset cap base : ℕ) (ls : List TaggedLayer) (m : Memory w) :
+ Reads w (writeTags offset cap base ls m) offset cap base ls := by
+ induction ls generalizing base m with
+ | nil => trivial
+ | cons L ls ih =>
+ let next := endPos cap base L.layer
+ let memory := Native.image offset cap base L.layer.count (L.role.code : Word w) m
+ refine ⟨fun i => ?_, ih next memory⟩
+ have h : address cap base i.val < next :=
+ Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_left i.isLt (by omega)) _
+ exact (write_tags_outside offset cap next ls memory _ (Or.inl (Nat.add_lt_add_left h _))).trans
+ (Native.image_at offset cap base L.layer.count _ m i.isLt)
+
+/-- Replay of the fixed-width-independent role worker over all selected layers. -/
+inductive RolePasses (offset cap : ℕ) : ℕ → List TaggedLayer → Memory w → List (Report w) → Prop
+ | nil (base : ℕ) (m : Memory w) : RolePasses offset cap base [] m []
+ | cons {base : ℕ} {L : TaggedLayer} {ls : List TaggedLayer} {m : Memory w}
+ {rs rest : List (Report w)}
+ (run : let p := Native.params offset cap base (L.role.code : Word w)
+ let M := (template Native.visit 0).instantiate w p
+ runSegment M.program 12 (some 0) m (List.replicate L.layer.count []) = some rs)
+ (next : RolePasses offset cap (endPos cap base L.layer) ls (after m (eventLog rs)) rest) :
+ RolePasses offset cap base (L :: ls) m (rs ++ rest)
+
+/-- Exactly one burst and one external write per stored role. The final memory
+agrees with the directory read by the visit dispatcher. -/
+theorem native_write_tags (offset cap base : ℕ) (ls : List TaggedLayer) (m : Memory w)
+ (fit : offset + base + tagWords cap ls ≤ 2 ^ w) :
+ ∃ rs, RolePasses offset cap base ls m rs ∧
+ after m (eventLog rs) = writeTags offset cap base ls m ∧
+ rs.length = (ls.map (fun L => L.layer.count)).sum ∧
+ (∀ r ∈ rs, r.events.length = 11 ∧ r.probes = 1) ∧
+ RAMBuckets.cost Report.probes rs = 2 * (ls.map (fun L => L.layer.count)).sum := by
+ induction ls generalizing base m with
+ | nil => exact ⟨[], .nil _ _, rfl, rfl, by simp, rfl⟩
+ | cons L ls ih =>
+ let next := endPos cap base L.layer
+ have hfit : offset + next + tagWords cap ls ≤ 2 ^ w := by
+ simpa [next, endPos, address, tagWords_cons, Nat.add_assoc] using fit
+ obtain ⟨rs, run, memory, calls, each, cost⟩ := Native.run_layer offset cap base L.layer
+ (L.role.code : Word w) m ((Nat.le_add_right _ _).trans hfit)
+ obtain ⟨tail, runs, hmem, hc, heach, hcost⟩ := ih next (after m (eventLog rs)) hfit
+ refine ⟨rs ++ tail, .cons run runs, ?_, ?_, ?_, ?_⟩
+ · have happ : eventLog (rs ++ tail) = eventLog rs ++ eventLog tail := by simp [eventLog]
+ rw [happ, show after m (eventLog rs ++ eventLog tail) = after (after m (eventLog rs))
+ (eventLog tail) from List.foldl_append, hmem, memory]
+ rfl
+ · simp only [List.length_append, calls, hc, List.map_cons, List.sum_cons]
+ · intro r hr
+ exact (List.mem_append.mp hr).elim (each r) (heach r)
+ · simp only [RAMBuckets.cost_append, cost, hcost, List.map_cons, List.sum_cons, Nat.mul_add]
+
+/-- The arithmetic performed by the dispatcher reads the same natural address
+as the tag directory when the public offset and node pointer fit together. -/
+theorem probe_word_add (offset node : ℕ) (m : Memory w) (fit : offset + node < 2 ^ w) :
+ m (((offset : Word w) + (node : Word w)).val) = m (offset + node) := by
+ rw [← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt fit]
+
+private theorem reads_above {ls : List TaggedLayer} {offset cap base : ℕ} {m m' : Memory w}
+ (hr : Reads w m offset cap base ls) (agree : ∀ x ≥ offset + base, m' x = m x) :
+ Reads w m' offset cap base ls := by
+ induction ls generalizing base with
+ | nil => trivial
+ | cons L ls ih =>
+ refine ⟨fun i => (agree _ (Nat.add_le_add_left (Nat.le_add_right _ _) _)).trans (hr.1 i), ?_⟩
+ apply ih hr.2
+ intro x hx
+ exact agree x ((Nat.add_le_add_left (Nat.le_add_right _ _) _).trans hx)
+
+variable {k R : Type*} [Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates)
+variable (f : B.Entry → R) (hf : B.IsSolution f) {n : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n)
+variable (X : State (S.degreeExponent 0) n) (z : (B.execute f hf T hT X).Choices)
+
+/-- Build the tags and the DFS descriptors in disjoint intervals of the same
+memory. With `F` final-bit words between the intervals, all `F` cells retain
+their original contents. The pointer offset used by the dispatcher is exactly
+`rowWords + F`. -/
+theorem selected_tags_and_rows (base F : ℕ) (m : Memory w)
+ (fit : base + words B.recordLimit (selectedLayers B f hf T hT X z) < 2 ^ w) :
+ let ls := selectedLayers B f hf T hT X z
+ let offset := words B.recordLimit ls + F
+ let tagged := writeTags offset B.recordLimit base (selected B f hf T hT X z) m
+ let final := build B.recordLimit base base ls tagged
+ Reads w final offset B.recordLimit base (selected B f hf T hT X z) ∧
+ (∀ i < F, final (base + words B.recordLimit ls + i) = m (base + words B.recordLimit ls + i)) ∧
+ AllRows w final B.recordLimit base base ls := by
+ let ls := selectedLayers B f hf T hT X z
+ let taggedLayers := selected B f hf T hT X z
+ let size := words B.recordLimit ls
+ let offset := size + F
+ let tagged := writeTags offset B.recordLimit base taggedLayers m
+ have hr := writeTags_reads offset B.recordLimit base taggedLayers m
+ refine ⟨reads_above hr (fun x hx => build_outside ls _ _ _ tagged x (Or.inr (by
+ change offset + base ≤ x at hx
+ change base + size ≤ x
+ dsimp only [offset] at hx
+ omega))), fun i hi => ?_, ?_⟩
+ · let addr := base + size + i
+ have h := build_outside ls B.recordLimit base base tagged addr
+ (Or.inr (show base + size ≤ addr from Nat.le_add_right _ _))
+ exact h.trans (write_tags_outside offset B.recordLimit base taggedLayers m addr
+ (Or.inl (by dsimp only [addr, offset]; omega)))
+ · exact build_rows ls B.recordLimit base base tagged (selected_capacity B f hf T hT X z) fit
+
+/-- Initialize the selected branch's role tags using one native write per site.
+The running time and probe cost use the actual number of compressor stages. -/
+theorem native_selected_roles (base F : ℕ) (m : Memory w)
+ (fit : base + 2 * words B.recordLimit (selectedLayers B f hf T hT X z) + F ≤ 2 ^ w) :
+ let ls := selected B f hf T hT X z
+ let offset := words B.recordLimit (selectedLayers B f hf T hT X z) + F
+ ∃ rs, RolePasses offset B.recordLimit base ls m rs ∧
+ after m (eventLog rs) = writeTags offset B.recordLimit base ls m ∧
+ Reads w (after m (eventLog rs)) offset B.recordLimit base ls ∧
+ rs.length ≤ ((S.steps + 1) * T + 1) * X.positions ∧
+ (∀ r ∈ rs, r.events.length = 11 ∧ r.probes = 1) ∧
+ RAMBuckets.cost Report.probes rs ≤ 2 * (((S.steps + 1) * T + 1) * X.positions) := by
+ let ls := selected B f hf T hT X z
+ let size := words B.recordLimit (selectedLayers B f hf T hT X z)
+ let offset := size + F
+ have hsize : tagWords B.recordLimit ls = size := by
+ rw [tagWords, show ls.map TaggedLayer.layer = _ from selected_layers B f hf T hT X z]
+ obtain ⟨rs, run, hm, hc, he, hp⟩ := native_write_tags offset B.recordLimit base ls m (by
+ rw [hsize]
+ change base + 2 * size + F ≤ _ at fit
+ dsimp only [offset]
+ omega)
+ have bound : (ls.map (fun l => l.layer.count)).sum ≤ ((S.steps + 1) * T + 1) * X.positions := by
+ have h := selected_count_sum_le B f hf T hT X z
+ rw [← selected_layers B f hf T hT X z, List.map_map] at h
+ exact h
+ refine ⟨rs, run, hm, ?_, hc.trans_le bound, he, hp.trans_le (Nat.mul_le_mul_left 2 bound)⟩
+ rw [hm]
+ exact writeTags_reads offset B.recordLimit base ls m
+
+end PairSimulation.TraversalRoles
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalRoleNative.lean b/lean/OAI/Computability/VPVNP/PairTraversalRoleNative.lean
new file mode 100644
index 0000000000..8f800c311b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalRoleNative.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.PairTraversalRows
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+
+/-!
+# Native writes of the role tags used by the descriptor dispatcher
+
+A fixed burst reads the offset, layer base, row stride, and tag from its
+public parameters. Its persistent state is the current site number. Each
+burst writes one tag and increments the site number. A full layer scan
+changes exactly the words indexed by its descriptor headers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRoles.Native
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM TraversalRows
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Public directory words for one layer. -/
+def params (offset cap base : ℕ) (tag : Word w) : Fin 4 → Word w :=
+ ![(offset : Word w), (base : Word w), ((cap + 2 : ℕ) : Word w), tag]
+
+/-- Use the site's persistent index to compute its absolute role-table address. -/
+def visit : List (Op 3 4) :=
+ [.stateWord 0, .publicWord 1 0, .publicWord 2 1, .binary .add 1 1 2,
+ .publicWord 2 2, .binary .mul 2 2 0, .binary .add 1 1 2, .publicWord 2 3,
+ .write 1 2, .constant 1 1, .binary .add 0 0 1]
+
+/-- Chronological role-worker events, including the external write of the selected role code at
+the site's displaced row address. -/
+def events (p : Fin 4 → Word w) (i : Word w) : List (Event w) :=
+ [.tick, .tick, .tick, .tick, .tick, .tick, .tick, .tick,
+ .write (p 0 + p 1 + p 2 * i) (p 3), .tick, .tick]
+
+theorem visit_native (p : Fin 4 → Word w) (i : Word w) (m : Memory w) :
+ let M := (template visit 0).instantiate w p
+ execute M.program 12 (M.program.start i) m [] = some ⟨events p i, some (i+1)⟩ := by
+ change execute ((template visit 0).instantiate w p).program (1 + visit.length)
+ ⟨_, i, fun _ => 0, fun _ => 0⟩ m [] = _
+ rw [execute_template, run_eq_trace]
+ rfl
+
+open Classical in
+/-- The image of the first `count` sites of the role table. -/
+noncomputable def image (offset cap base count : ℕ) (tag : Word w) (m : Memory w) : Memory w :=
+ fun x => if ∃ j < count, x = offset + address cap base j then tag else m x
+
+theorem image_at (offset cap base count : ℕ) (tag : Word w) (m : Memory w) {i : ℕ}
+ (hi : i < count) : image offset cap base count tag m (offset + address cap base i) = tag :=
+ ite_eq_left ⟨i, hi, rfl⟩
+
+theorem image_outside (offset cap base count : ℕ) (tag : Word w) (m : Memory w) (x : ℕ)
+ (hx : ∀ i < count, x ≠ offset + address cap base i) :
+ image offset cap base count tag m x = m x :=
+ ite_eq_right (by simpa only [not_exists, not_and] using hx)
+
+private theorem after_site (offset cap base k : ℕ) (tag : Word w) (m : Memory w)
+ (fit : offset + address cap base k < 2 ^ w) :
+ after (image offset cap base k tag m) (events (params offset cap base tag) (k : Word w)) =
+ image offset cap base (k + 1) tag m := by
+ let a := offset + address cap base k
+ have ha : ((offset : Word w) + (base : Word w) + ((cap + 2 : ℕ) : Word w) * (k : Word w)) =
+ (a : Word w) := by simp only [a, address, Nat.cast_add, Nat.cast_mul, add_assoc]
+ change writeMemory (image offset cap base k tag m) _ tag = _
+ rw [show (params offset cap base tag 0 + params offset cap base tag 1 +
+ params offset cap base tag 2 * (k : Word w)) = (a : Word w) from ha]
+ have hval : (a : Word w).val = a := Nat.mod_eq_of_lt fit
+ funext x
+ by_cases he : x = a
+ · subst x
+ rw [image_at offset cap base (k + 1) tag m (Nat.lt_succ_self k)]
+ exact ite_eq_left hval.symm
+ · rw [writeMemory, hval, ite_eq_right he]
+ have eqn : (∃ j < k, x = offset + address cap base j) ↔
+ ∃ j < k + 1, x = offset + address cap base j := by
+ constructor
+ · rintro ⟨j, hj, hx⟩
+ exact ⟨j, hj.trans (Nat.lt_succ_self k), hx⟩
+ · rintro ⟨j, hj, hx⟩
+ have hj' : j ≠ k := fun e => he (by simpa only [a, e] using hx)
+ exact ⟨j, by omega, hx⟩
+ simp only [image, eqn]
+
+private theorem run_suffix (offset cap base : ℕ) (L : Layer) (tag : Word w) (m : Memory w)
+ (fit : offset + endPos cap base L ≤ 2 ^ w) (k n : ℕ) (hk : k + n ≤ L.count) :
+ let p := params offset cap base tag
+ let M := (template visit 0).instantiate w p
+ let start := image offset cap base k tag m
+ ∃ rs, runSegment M.program 12 (some (k : Word w)) start (List.replicate n []) = some rs ∧
+ after start (eventLog rs) = image offset cap base (k+n) tag m ∧
+ rs.length = n ∧ (∀ r ∈ rs, r.events.length = 11 ∧ r.probes = 1) ∧
+ RAMBuckets.cost Report.probes rs = 2 * n := by
+ let p := params offset cap base tag
+ let M := (template visit 0).instantiate w p
+ induction n generalizing k with
+ | zero => exact ⟨[], rfl, rfl, rfl, by simp, rfl⟩
+ | succ n ih =>
+ let start := image offset cap base k tag m
+ let r : Report w := ⟨events p (k : Word w), some ((k : Word w)+1)⟩
+ have hlt : k < L.count := by omega
+ have ha : offset + address cap base k < 2^w := by
+ have h := Nat.mul_lt_mul_of_pos_left hlt (by omega : 0 < cap + 2)
+ unfold endPos address at *
+ omega
+ have hm := after_site offset cap base k tag m ha
+ have hs : (k : Word w) + 1 = ((k + 1 : ℕ) : Word w) := by rw [Nat.cast_add, Nat.cast_one]
+ obtain ⟨rs, hrun, hpost, hlen, hper, hcost⟩ := ih (k+1) (by omega)
+ refine ⟨r :: rs, ?_, ?_, ?_, ?_, ?_⟩
+ · change runSegment M.program 12 (some (k : Word w)) start (List.replicate (n+1) []) = _
+ rw [List.replicate_succ, runSegment, visit_native]
+ simp only [M, hs, start, p, hm, hrun, Option.map_some, r]
+ · change (r.events ++ eventLog rs).foldl BurstRAM.update start = _
+ rw [List.foldl_append]
+ change after (after (image offset cap base k tag m) (events p (k : Word w))) (eventLog rs) = _
+ rw [hm, hpost, show k + 1 + n = k + (n + 1) by omega]
+ · simp [hlen]
+ · intro q hq
+ rcases List.mem_cons.mp hq with rfl | hq
+ · exact ⟨rfl, rfl⟩
+ · exact hper q hq
+ · rw [RAMBuckets.cost, show r.probes = 1 from rfl, hcost, Nat.mul_succ]
+ omega
+
+/-- Run the fixed role-writing worker on every site in one actual descriptor
+layer. The report cost includes one burst invocation and one external write. -/
+theorem run_layer (offset cap base : ℕ) (L : Layer) (tag : Word w) (m : Memory w)
+ (fit : offset + endPos cap base L ≤ 2 ^ w) :
+ let p := params offset cap base tag
+ let M := (template visit 0).instantiate w p
+ ∃ rs, runSegment M.program 12 (some 0) m (List.replicate L.count []) = some rs ∧
+ after m (eventLog rs) = image offset cap base L.count tag m ∧
+ rs.length = L.count ∧ (∀ r ∈ rs, r.events.length = 11 ∧ r.probes = 1) ∧
+ RAMBuckets.cost Report.probes rs = 2 * L.count := by
+ have hzero : image offset cap base 0 tag m = m := by funext x; simp [image]
+ simpa only [Nat.cast_zero, hzero, Nat.zero_add] using
+ run_suffix offset cap base L tag m fit 0 L.count (Nat.zero_add _).le
+
+end PairSimulation.TraversalRoles.Native
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalRoles.lean b/lean/OAI/Computability/VPVNP/PairTraversalRoles.lean
new file mode 100644
index 0000000000..9f596c7102
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalRoles.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.PairTraversalStageSize
+import OAI.Computability.VPVNP.PairTraversalRoleNative
+
+/-!
+# Routing local vertex visits by their actual compressor pass
+
+A cursor input is visited as a leaf. Each later descriptor belongs to the
+output of a particular selected shrinking or refresh pass. Its tag comes from
+that pass's origin before the state and its term are erased to a history.
+The resulting tagged layers retain the same order and placement fibers as the
+selected local parsers used by the native depth-first traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRoles
+
+open CompressorRecords Compression LocalHistory TraversalRows BurstRAM
+open scoped Fin.CommRing
+
+/-- The three cases of a vertex visit. -/
+inductive Role where
+ | cursor
+ | shrink
+ | refresh
+ deriving DecidableEq
+
+/-- Numerical DFS dispatch tag, assigning zero to a cursor leaf, one to a shrink, and two to a
+refresh. -/
+def Role.code : Role → ℕ
+ | .cursor => 0
+ | .shrink => 1
+ | .refresh => 2
+
+theorem Role.code_le_two (r : Role) : r.code ≤ 2 := by cases r <;> decide
+
+theorem Role.word_injective (w : ℕ) (fit : 2 < 2 ^ w) :
+ Function.Injective (fun r : Role => (r.code : Word w)) := by
+ intro r t h
+ have hr := r.code_le_two.trans_lt fit
+ have ht := t.code_le_two.trans_lt fit
+ have eq := congrArg Fin.val h
+ simp only [Fin.val_natCast, Nat.mod_eq_of_lt hr, Nat.mod_eq_of_lt ht] at eq
+ cases r <;> cases t <;> simp_all [Role.code]
+
+/-- Row identifiers and the visit operation for one layer. -/
+structure TaggedLayer where
+ /-- The selected DFS layer of site rows and their child ordinals. -/
+ layer : Layer
+ /-- Producing role used to dispatch visits to the rows of this tagged layer. -/
+ role : Role
+
+/-- Header bases in the tag table use the exact prefix of selected output sizes. -/
+def layerBase (cap base : ℕ) (ls : List TaggedLayer) (i : ℕ) : ℕ :=
+ base + words cap ((ls.take i).map TaggedLayer.layer)
+
+theorem layerBase_zero (cap base : ℕ) (ls : List TaggedLayer) : layerBase cap base ls 0 = base := by
+ simp [layerBase, words]
+
+theorem layerBase_cons (cap base : ℕ) (L : TaggedLayer) (ls : List TaggedLayer) (i : ℕ) :
+ layerBase cap base (L :: ls) (i + 1) = layerBase cap (endPos cap base L.layer) ls i := by
+ simp [layerBase, words, endPos, address, Nat.mul_add, Nat.add_assoc]
+
+/-- Tags live at a fixed public offset from descriptor headers. -/
+def Reads (w : ℕ) (m : Memory w) (offset cap base : ℕ) : List TaggedLayer → Prop
+ | [] => True
+ | L :: ls => (∀ i : Fin L.layer.count,
+ m (offset + address cap base i.val) = (L.role.code : Word w)) ∧
+ Reads w m offset cap (endPos cap base L.layer) ls
+
+theorem Reads.at_layer {w : ℕ} {m : Memory w} {offset cap base : ℕ} {ls : List TaggedLayer}
+ (h : Reads w m offset cap base ls) (i : Fin ls.length) (j : Fin (ls[i].layer.count)) :
+ m (offset + address cap (layerBase cap base ls i.val) j.val) = (ls[i].role.code : Word w) := by
+ induction ls generalizing base with
+ | nil => exact Fin.elim0 i
+ | cons L ls ih =>
+ cases i using Fin.cases with
+ | zero =>
+ simpa only [Fin.getElem_fin, Fin.val_zero, List.getElem_cons_zero, layerBase_zero] using h.1 j
+ | succ i =>
+ simpa only [Fin.getElem_fin, Fin.val_succ, List.getElem_cons_succ, layerBase_cons] using
+ (ih h.2 i j)
+
+variable {k R : Type*} [Field k] [CommRing R] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → R} {hf : B.IsSolution f}
+
+/-- Pattern-match on the actual scheduled pass, including its input state and
+proof that it is the corresponding shrinking or refresh operation. -/
+def ofOrigin {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} :
+ PassOrigin B f hf p → Role
+ | .shrink _ _ _ => .shrink
+ | .refresh _ => .refresh
+
+variable (B f hf)
+
+/-- Recover a selected output layer's role from the origin of its elementary compression pass. -/
+def tagLevel (v : SelectedLevel B f hf) : Role := ofOrigin v.origin
+
+variable {n : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+
+/-- One tag per physical layer. The initial layer is the cursor. Subsequent
+layers are indexed by the real, branch-specific `SelectedLevel` records. -/
+noncomputable def selected : List TaggedLayer :=
+ ⟨leafLayer (siteOrder X), .cursor⟩ :: (executeLevels B f hf T hT X z).map
+ (fun v => ⟨levelLayer B f hf v, tagLevel B f hf v⟩)
+
+/-- Dropping just the tag gives precisely the layers consumed by the selected
+parsers, including every old-site identifier in the order of the true fiber. -/
+theorem selected_layers : (selected B f hf T hT X z).map TaggedLayer.layer =
+ selectedLayers B f hf T hT X z := by
+ simp only [selectedLayers_eq_levels, selected, List.map_cons, List.map_map, Function.comp_def]
+
+/-- Reading a concrete output tag routes to the selected shrink or refresh pass
+that supplied that position's kernel reader. -/
+theorem reads_selected_level {w : ℕ} (m : Memory w) (offset base : ℕ)
+ (hr : Reads w m offset B.recordLimit base (selected B f hf T hT X z))
+ (i : Fin (executeLevels B f hf T hT X z).length)
+ (j : Fin ((executeLevels B f hf T hT X z)[i].outputSites)) :
+ m (offset + address B.recordLimit (layerBase B.recordLimit base (selected B f hf T hT X z)
+ (i.val + 1)) j.val) =
+ ((tagLevel B f hf (executeLevels B f hf T hT X z)[i]).code : Word w) := by
+ let stage : Fin (selected B f hf T hT X z).length := ⟨i.val + 1, by simp [selected]⟩
+ have count : ((selected B f hf T hT X z)[stage]).layer.count =
+ ((executeLevels B f hf T hT X z)[i]).outputSites := by
+ simp [stage, selected, levelLayer_count]
+ let row : Fin (selected B f hf T hT X z)[stage].layer.count :=
+ ⟨j.val, by rw [count]; exact j.isLt⟩
+ have h := Reads.at_layer (base := base) (h := hr) stage row
+ simpa [row, stage, selected] using h
+
+/-- The cursor leaves always select the initial-vertex reader. -/
+theorem reads_cursor {w : ℕ} (m : Memory w) (offset base : ℕ)
+ (hr : Reads w m offset B.recordLimit base (selected B f hf T hT X z)) (v : X.network.Site) :
+ m (offset + (sitePointers B.recordLimit base (siteOrder X) v).1) = 0 :=
+ hr.1 ((siteOrder X).entries.symm v)
+
+end PairSimulation.TraversalRoles
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalRootAddress.lean b/lean/OAI/Computability/VPVNP/PairTraversalRootAddress.lean
new file mode 100644
index 0000000000..209e359d4e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalRootAddress.lean
@@ -0,0 +1,180 @@
+import OAI.Computability.VPVNP.PairTraversalNodeBounds
+import OAI.Computability.VPVNP.PairVertexRootFields
+import OAI.Computability.VPVNP.PairTerminalPackedPrefix
+
+/-!
+# Root row of a selected placement tree
+
+The selected tree ends at the row numbered by its final state's site order.
+The terminal bootstrap publishes the base of that layer and its row stride
+in header cells 6 and 15. Their native multiply-add recovers the same address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open LocalHistory NetworkKernel Compression DFS BurstRAM
+open scoped Fin.CommRing
+
+variable {A : Type*}
+
+private def finalOrder {N Y : Network} (c : TermChain A N Y) (ords : ChainOrders c)
+ (initial : Order N.Site) : Order Y.Site :=
+ match c with
+ | .done _ => initial
+ | .more _ _ tail => finalOrder tail ords.2 ords.1
+
+open private castOrders from OAI.Computability.VPVNP.PairTraversalSelectedOrder
+
+private theorem cast_finalOrder {N M Y : Network} (e : N = M) (c : TermChain A M Y)
+ (ords : ChainOrders c) (initial : Order M.Site) :
+ finalOrder (e.symm ▸ c : TermChain A N Y) (castOrders e c ords) (e.symm ▸ initial) =
+ finalOrder c ords initial := by cases e; rfl
+
+variable [CommRing A]
+
+private theorem branch_finalOrder {a g b n : ℕ} {X : State a g} (E : StateExecution A b n X)
+ (data : E.Records) (z : E.Choices) :
+ finalOrder (E.termChain data z) (branchOrders E data z) (siteOrder X) =
+ siteOrder (E.finalState z) := by
+ induction E with
+ | done => rfl
+ | more p tail ih =>
+ let c := (tail z.1).termChain (data.2 z.1) z.2
+ let ords := branchOrders (tail z.1) (data.2 z.1) z.2
+ exact (cast_finalOrder (p.output_eq z.1) c ords (siteOrder (p.next z.1))).trans
+ (ih z.1 (data.2 z.1) z.2)
+
+open private addTree from OAI.Computability.VPVNP.PairTraversalHistory
+
+private theorem chain_root_address {N Y : Network} {L : Type} [Fintype L] {κ : L → A}
+ (c : TermChain A N Y) (r : ChainParsers κ c) (ords : ChainOrders c)
+ (initial : Order N.Site) (cap base : ℕ) (prior : Layer) (count : prior.count = initial.length)
+ (input : N.Site → VertexTree)
+ (atRow : ∀ u, (input u).address = address cap base (initial.entries.symm u).val) (v : Y.Site) :
+ (chainTrees c r (chainPointers cap c ords (address cap base initial.length)) input v).address =
+ address cap (base + words cap (prior :: stepLayers c r ords initial).dropLast)
+ ((finalOrder c ords initial).entries.symm v).val := by
+ induction c generalizing base prior with
+ | done =>
+ change (input v).address = address cap (base + words cap []) (initial.entries.symm v).val
+ rw [show words cap [] = 0 by simp [words], Nat.add_zero]
+ exact atRow v
+ | more t data tail ih =>
+ let next := address cap base initial.length
+ let layer := stepLayer initial ords.1 r.1
+ have h := ih r.2 ords.2 ords.1 next layer rfl
+ (addTree r.1 (sitePointers cap next ords.1) input) (fun _ => rfl)
+ refine (h v).trans ?_
+ simp only [stepLayers, finalOrder, List.dropLast_cons_cons, words, List.map_cons, List.sum_cons,
+ Nat.mul_add, next, layer, address, count, Nat.add_assoc]
+ rfl
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+variable (f : B.Entry → A) (hf : B.IsSolution f) {n : ℕ} (T : ℕ)
+variable (hT : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+variable (z : (B.execute f hf T hT X).Choices)
+
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "ls" => selectedLayers B f hf T hT X z
+
+/-- Every final site has its root in the last row layer at its actual numerical ordinal. -/
+theorem selectedTrees_address (base : ℕ) (v : (Y).network.Site) :
+ (selectedTrees B f hf T hT X z base v).address =
+ address B.recordLimit (base + words B.recordLimit (ls).dropLast)
+ ((siteOrder (Y)).entries.symm v).val := by
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ords := branchOrders E data z
+ let r := selectedParsers B f hf T hT X z
+ let old := siteOrder X
+ have h := chain_root_address c r ords old B.recordLimit base (leafLayer old) rfl
+ (fun u => leafTree (sitePointers B.recordLimit base old u)) (fun _ => rfl) v
+ rw [show finalOrder c ords old = siteOrder (Y) from branch_finalOrder E data z] at h
+ exact h
+
+variable {w : ℕ}
+
+/-- The terminal gather computes the selected root using the live last-layer base
+and row stride. Fit of the selected arena suffices for the native multiply-add. -/
+theorem selectedTrees_address_ofHeader (base : ℕ) (v : (Y).network.Site) (degree : ℕ)
+ (pub : Fin 11 → Word w) (H ordinal : Word w) (m : Memory w)
+ (ord : ordinal.val = ((siteOrder (Y)).entries.symm v).val)
+ (lastBase : m (H + 6).val = ((base + words B.recordLimit (ls).dropLast : ℕ) : Word w))
+ (stride : m (H + 15).val = ((B.recordLimit + 2 : ℕ) : Word w))
+ (fit : base + words B.recordLimit (ls) ≤ 2 ^ w) :
+ (selectedTrees B f hf T hT X z base v).address =
+ (TerminalRootGather.Layout.ofHeader degree pub H ordinal m).root := by
+ let tree := selectedTrees B f hf T hT X z base v
+ have mem : tree.address ∈ tree.preorder := by
+ cases tree
+ exact List.mem_cons_self
+ have bound := (selectedTrees_below B f hf T hT X z base v mem).trans_le fit
+ have eqn := selectedTrees_address B f hf T hT X z base v
+ rw [eqn, address, ← ord] at bound ⊢
+ change _ = (m (H + 6).val + m (H + 15).val * ordinal).val
+ have hword : (ordinal.val : Word w) = ordinal := Fin.ext (Nat.mod_eq_of_lt ordinal.isLt)
+ rw [lastBase, stride]
+ calc
+ _ = (((base + words B.recordLimit (ls).dropLast + (B.recordLimit + 2) * ordinal.val : ℕ) :
+ Word w)).val := (Nat.mod_eq_of_lt bound).symm
+ _ = _ := by simp only [Nat.cast_add, Nat.cast_mul, hword]
+
+/-- The physical header fields published by the selected terminal bootstrap supply
+both address operands of the root gather. -/
+theorem selectedTrees_address_ofBootstrap (D : CompressorRecords.DescriptorSpace.Layout)
+ (baseBits laneBits : ℕ) (tab : Fin D.shape.tables) (v : (Y).network.Site) (degree : ℕ)
+ (pub : Fin 11 → Word w) (H ordinal : Word w) (m calendar : Memory w)
+ (ord : ordinal.val = ((siteOrder (Y)).entries.symm v).val)
+ (fields : ∀ j : Fin 21, j.val = 6 ∨ j.val = 15 →
+ m (H + (j.val : Word w)).val =
+ TerminalBootstrap.values D (ls).dropLast.length
+ (TerminalBootstrap.fromState D (ls).dropLast B.recordLimit baseBits laneBits (Y) tab)
+ B.recordLimit pub calendar j)
+ (fit : CompressorRecords.DescriptorSpace.endAddress D + words B.recordLimit (ls) ≤ 2 ^ w) :
+ (selectedTrees B f hf T hT X z (CompressorRecords.DescriptorSpace.endAddress D) v).address =
+ (TerminalRootGather.Layout.ofHeader degree pub H ordinal m).root :=
+ selectedTrees_address_ofHeader B f hf T hT X z _ v degree pub H ordinal m ord
+ (fields 6 (Or.inl rfl)) (fields 15 (Or.inr rfl)) fit
+
+end PairSimulation.TraversalRows
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory TraversalRows TerminalLink
+open scoped Fin.CommRing
+
+variable {w : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f} {n T : ℕ}
+variable {hT : T * S.laneBits ≤ n} {X : State (S.degreeExponent 0) n}
+variable {z : (B.execute f hf T hT X).Choices}
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+
+/-- At the physical vertex entry, the root gather reads the row for the
+selected final site from the bootstrap fields preserved by the linked stages. -/
+theorem VertexEntry.gather_root {D : Layout} {tab : Fin D.shape.tables} {baseBits laneBits : ℕ}
+ {pub : Fin 11 → Word w} {calendar vertex : Memory w} {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B f hf T hT X z D tab baseBits laneBits pub calendar vertex bits)
+ (v : (Y).network.Site) (degree : ℕ) (ordinal : Word w)
+ (ord : ordinal.val = ((siteOrder (Y)).entries.symm v).val)
+ (headerFit : (header pub).val + 32 ≤ 2 ^ w)
+ (rowFit : endAddress D + words B.recordLimit (selectedLayers B f hf T hT X z) ≤ 2 ^ w) :
+ (selectedTrees B f hf T hT X z (endAddress D) v).address =
+ (TerminalRootGather.Layout.ofHeader degree pub (header pub) ordinal vertex).root := by
+ apply selectedTrees_address_ofBootstrap B f hf T hT X z D baseBits laneBits tab v degree pub
+ (header pub) ordinal vertex calendar ord _ rowFit
+ intro j hj
+ have bound := j.isLt
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : j.val < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega)]
+ exact entry.headers j (by omega) (by omega) (by omega)
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalRowExecution.lean b/lean/OAI/Computability/VPVNP/PairTraversalRowExecution.lean
new file mode 100644
index 0000000000..54f3564f60
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalRowExecution.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.PairSimulationDescriptorRows
+
+/-!
+# Executing a descriptor row from its represented preimage list
+
+The scan replaces identifiers by absolute child descriptor addresses. The
+header routine then reads the stored count and publishes the pointer and count.
+Both runs use the same external memory, with the header starting from the
+writes actually emitted by the scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.DescriptorRows
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Registers at entry to the identifier scan. -/
+def scanRegs (src dst count : ℕ) (base stride : Word w) : Regs w 7 :=
+ ![(src : Word w), ((src + count : ℕ) : Word w), (dst : Word w), base, stride, 1, 0]
+
+/-- Registers at entry to the descriptor header routine. -/
+def headerRegs (node dst : ℕ) (countCell : Word w) : Regs w 5 :=
+ ![countCell, (dst : Word w), (node : Word w), 1, 0]
+
+/-- The external memory after the identifier translation and the two header writes. -/
+def passMemory (mem : Memory w) (node src dst : ℕ) (countCell base stride : Word w)
+ (count : ℕ) : Memory w :=
+ writeMemory (writeMemory (rowMemory src dst count base stride mem) (node : Word w) (dst : Word w))
+ ((node + 1 : ℕ) : Word w) (mem countCell.val)
+
+/-- Two native runs, including their actual memory handoff, event costs,
+and ordered children as read by the DFS. -/
+structure NativePass (pub : Fin 0 → Word w) (state : Word w) (priv : Word w → Word w)
+ (mem : Memory w) (node src dst : ℕ) (countCell base stride : Word w)
+ (ids : List (Word w)) (es : List (Event w)) : Prop where
+ runs :
+ let S := (scan.template none).instantiate w pub
+ let H := (template header 4).instantiate w pub
+ ∃ ss hs, es = ss ++ hs ∧
+ execute S.program (7 * ids.length + 2)
+ ⟨S.entry, state, scanRegs src dst ids.length base stride, priv⟩ mem [] = some ⟨ss, none⟩ ∧
+ execute H.program 5 ⟨H.entry, state, headerRegs node dst countCell, priv⟩ (after mem ss) [] =
+ some ⟨hs, some (mem countCell.val)⟩
+ probes : countProbes es = 2 * ids.length + 3
+ steps : es.length = 7 * ids.length + 5
+ bits : choiceBits es = []
+ memory : after mem es = passMemory mem node src dst countCell base stride ids.length
+ row : DFS.Row (after mem es) node dst (ids.map (address base stride))
+
+private theorem replay_exec {r k : ℕ} {pub : Fin k → Word w} {state : Word w} {a : Flow r k}
+ {rs m es rs' m'} (run : Flow.Exec pub state a rs m es rs' m') : after m es = m' := by
+ induction run with
+ | @line op _ _ _ _ _ h =>
+ cases op <;> simp only [Op.effect] at h
+ all_goals first | split at h | skip
+ all_goals first | contradiction | (cases Option.some.inj h; rfl)
+ | seq _ _ h₁ h₂ | whileStep _ _ _ h₁ h₂ =>
+ simpa only [after, List.foldl_cons, update, List.foldl_append] using
+ (congrArg (fun m => after m _) h₁).trans h₂
+ | ifEqYes _ _ h | ifEqNo _ _ h | ifLtYes _ _ h | ifLtNo _ _ h | branchYes _ h | branchNo _ h =>
+ exact h
+ | whileDone => rfl
+
+private theorem count_append (ss hs : List (Event w)) :
+ countProbes (ss ++ hs) = countProbes ss + countProbes hs := by
+ induction ss with
+ | nil => simp [countProbes]
+ | cons e ss ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+/-- Translate the represented source identifiers and publish the resulting row.
+The count may overlap the source or either header cell: it is read before the
+header writes, and the translation writes strictly above it. -/
+theorem native_pass (pub : Fin 0 → Word w) (state : Word w) (priv : Word w → Word w)
+ (mem : Memory w) (node src dst : ℕ) (countCell base stride : Word w)
+ (ids : List (Word w)) (hrow : rowRepresents mem countCell (src : Word w) ids)
+ (sourceBefore : src + ids.length ≤ dst) (countBefore : countCell.val < dst)
+ (headerBefore : node + 1 < dst) (fit : dst + ids.length < 2 ^ w) :
+ ∃ es, NativePass pub state priv mem node src dst countCell base stride ids es := by
+ let regs := scanRegs src dst ids.length base stride
+ let mid := rowMemory src dst ids.length base stride mem
+ obtain ⟨ss, out, scanRun, probes, steps, bits⟩ :=
+ scan_exec pub state regs mem src dst ids.length base stride
+ rfl rfl rfl rfl rfl rfl fit sourceBefore
+ have replay : after mem ss = mid := replay_exec scanRun
+ have count : mid countCell.val = mem countCell.val := by simp [mid, rowMemory, countBefore.not_ge]
+ let S := (scan.template none).instantiate w pub
+ have reject : S.code scan.rejectPC = .reject := by
+ change ((scan.template none).code scan.rejectPC).resize w = _
+ rw [Flow.template_reject]
+ rfl
+ have stop : S.program.step ⟨scan.exitPC, state, out, priv⟩ = .finish none := by
+ change (((scan.template none).code scan.exitPC).resize w).run pub
+ ⟨scan.exitPC, state, out, priv⟩ = _
+ rw [Flow.template_exit]
+ rfl
+ have nativeScan : execute S.program (7 * ids.length + 2) ⟨S.entry, state, regs, priv⟩ mem [] =
+ some ⟨ss, none⟩ := by
+ have e := scanRun.execute (Flow.template_linked scan none pub) reject priv 1 []
+ change execute S.program (ss.length + 1) ⟨S.entry, state, regs, priv⟩ mem
+ (choiceBits ss ++ []) =
+ (execute S.program 1 ⟨scan.exitPC, state, out, priv⟩ mid []).map (Flow.prependEvents ss) at e
+ rw [bits, List.nil_append, steps] at e
+ have halt : execute S.program 1 ⟨scan.exitPC, state, out, priv⟩ mid [] = some ⟨[], none⟩ := by
+ rw [execute, stop]
+ rfl
+ simpa only [halt, Option.map_some, Flow.prependEvents, List.append_nil] using e
+ let hs : List (Event w) := [.read countCell (mem countCell.val),
+ .write (node : Word w) (dst : Word w), .tick,
+ .write ((node + 1 : ℕ) : Word w) (mem countCell.val)]
+ let H := (template header 4).instantiate w pub
+ have nativeHeader : execute H.program 5 ⟨H.entry, state, headerRegs node dst countCell, priv⟩
+ (after mem ss) [] = some ⟨hs, some (mem countCell.val)⟩ := by
+ rw [replay]
+ have h := header_native pub state (headerRegs node dst countCell) mid priv
+ change execute H.program 5 _ mid [] = some ⟨[.read countCell (mid countCell.val),
+ .write (node : Word w) (dst : Word w), .tick,
+ .write ((node : Word w) + 1) (mid countCell.val)],
+ some (mid countCell.val)⟩ at h
+ simpa only [hs, Nat.cast_add, Nat.cast_one, count] using h
+ have final : after mem (ss ++ hs) =
+ passMemory mem node src dst countCell base stride ids.length := by
+ rw [show after mem (ss ++ hs) = after (after mem ss) hs from List.foldl_append, replay]
+ rfl
+ refine ⟨ss ++ hs, ⟨⟨ss, hs, rfl, nativeScan, nativeHeader⟩, ?_, ?_, ?_, final, ?_⟩⟩
+ · rw [count_append, probes]
+ rfl
+ · rw [List.length_append, steps]
+ change 7 * ids.length + 1 + 4 = _
+ omega
+ · rw [Flow.choiceBits_append, bits]
+ rfl
+ · rw [final]
+ exact represents_DFS_row mem node src dst countCell base stride ids hrow (by omega)
+ fit headerBefore
+
+end PairSimulation.DescriptorRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalRows.lean b/lean/OAI/Computability/VPVNP/PairTraversalRows.lean
new file mode 100644
index 0000000000..fe9689cbfd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalRows.lean
@@ -0,0 +1,446 @@
+import OAI.Computability.VPVNP.PairTraversalHistory
+
+/-!
+# Storing placement-fiber rows for the depth-first traversal
+
+In Section 13 and Appendix E of *VP and VNP differ over every field*, each
+position has a bounded row listing its immediate old positions. Here the
+first two words of a row store its child-list address and count. The remaining
+cells hold the actual older descriptor addresses in the reader's order.
+Successive layers occupy disjoint intervals, and every row fits in the same
+fixed stride, regardless of the wire widths or the chosen branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel Compression
+
+variable {R : Type*}
+
+/-- The actual numerical order of sites at the output of each selected term. -/
+def ChainOrders {N Y : Network} : TermChain R N Y → Type
+ | .done _ => PUnit
+ | .more t _ tail => Order t.output.Site × ChainOrders tail
+
+/-- Site numbers at each stage come from that state's base and lane coordinates. -/
+noncomputable def branchOrders [CommSemiring R] {a g b n : ℕ} {X : State a g}
+ (E : StateExecution R b n X) (data : E.Records) (z : E.Choices) :
+ ChainOrders (E.termChain data z) := by
+ induction E with
+ | done => exact PUnit.unit
+ | more p tail ih =>
+ let e := p.output_eq z.1
+ let c := (tail z.1).termChain (data.2 z.1) z.2
+ have transport {N M Y : Network} (h : N = M) (c : TermChain R M Y) (r : ChainOrders c) :
+ ChainOrders (h.symm ▸ c : TermChain R N Y) := by cases h; exact r
+ exact ⟨e.symm ▸ siteOrder (p.next z.1), transport e c (ih z.1 (data.2 z.1) z.2)⟩
+
+end PairSimulation.LocalHistory
+
+namespace PairSimulation.TraversalRows
+
+open BurstRAM BurstRAM.PrivateRAM NetworkKernel LocalHistory Compression
+open scoped Fin.CommRing
+
+/-- A layer in numerical site order. Child identifiers refer to the preceding
+layer's site numbers, before translation to absolute word addresses. -/
+structure Layer where
+ /-- Number of site rows in a single DFS layer. -/
+ count : ℕ
+ /-- The list of old-site child ordinals for each row of this layer. -/
+ ids : Fin count → List ℕ
+
+/-- Absolute address of a site's DFS row given the layer base and its capacity-plus-two word
+pitch. -/
+def address (cap base id : ℕ) : ℕ := base + (cap + 2) * id
+
+/-- Exclusive end of a layer's DFS rows, obtained from its site count and fixed row pitch. -/
+def endPos (cap base : ℕ) (L : Layer) : ℕ := address cap base L.count
+
+/-- Child identifiers have the exact order in which the local history reader
+visits the placement fiber. -/
+def stepLayer {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+ {N : Network} {t : Term A N} (old : Order N.Site) (next : Order t.output.Site)
+ (r : TermParsers κ t) : Layer :=
+ ⟨next.length, fun i => List.ofFn fun j =>
+ (old.entries.symm (((r.order.children (next.entries i)).entries j).val)).val⟩
+
+/-- The initial cursor layer with one childless DFS row per site in the chosen initial order. -/
+def leafLayer {I : Type} (initial : Order I) : Layer := ⟨initial.length, fun _ => []⟩
+
+theorem stepLayer_ids_lt {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+ {N : Network} {t : Term A N} (old : Order N.Site) (next : Order t.output.Site)
+ (r : TermParsers κ t) (i : Fin next.length) :
+ ∀ j ∈ (stepLayer old next r).ids i, j < old.length := by
+ intro j hj
+ obtain ⟨l, rfl⟩ := List.mem_ofFn.mp hj
+ exact (old.entries.symm (((r.order.children (next.entries i)).entries l).val)).isLt
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+variable {N Y : Network}
+
+/-- The chronological output DFS layers of the selected term chain, using each pass's placement
+fibers and site order. -/
+def stepLayers {N Y : Network} (c : TermChain A N Y) (r : ChainParsers κ c) (ords : ChainOrders c)
+ (initial : Order N.Site) : List Layer :=
+ match c with
+ | .done _ => []
+ | .more _ _ tail => stepLayer initial ords.1 r.1 :: stepLayers tail r.2 ords.2 ords.1
+
+/-- The complete selected row layout formed by prepending the initial cursor leaf layer to the
+pass output layers. -/
+def chainLayers (c : TermChain A N Y) (r : ChainParsers κ c) (ords : ChainOrders c)
+ (initial : Order N.Site) : List Layer := leafLayer initial :: stepLayers c r ords initial
+
+/-- The substep record limit bounds the number of stored words in every
+child list, including on branches with parallel arcs or empty placement fibers. -/
+theorem stepLayers_capacity (c : TermChain A N Y) (r : ChainParsers κ c) (ords : ChainOrders c)
+ (initial : Order N.Site) {cap W : ℕ} (hb : c.Bounded cap W) :
+ ∀ L ∈ stepLayers c r ords initial, ∀ i, (L.ids i).length ≤ cap := by
+ classical
+ induction c generalizing W with
+ | done => simp [stepLayers]
+ | more t data tail ih =>
+ intro L hL
+ rcases List.mem_cons.mp hL with rfl | ht
+ · intro i
+ let v := ords.1.entries i
+ have hs := Fintype.card_congr (r.1.order.children v).entries
+ rw [Fintype.card_fin] at hs
+ change (List.ofFn _).length ≤ cap
+ rw [List.length_ofFn]
+ exact hs.trans_le ((Nat.le_add_left _ _).trans (hb.1 v))
+ · exact ih r.2 ords.2 ords.1 hb.2.2 L ht
+
+theorem chainLayers_capacity (c : TermChain A N Y) (r : ChainParsers κ c) (ords : ChainOrders c)
+ (initial : Order N.Site) {cap W : ℕ} (hb : c.Bounded cap W) :
+ ∀ L ∈ chainLayers c r ords initial, ∀ i, (L.ids i).length ≤ cap := by
+ intro L hL
+ rcases List.mem_cons.mp hL with rfl | ht
+ · exact fun _ => Nat.zero_le _
+ · exact stepLayers_capacity c r ords initial hb _ ht
+
+variable {w : ℕ}
+
+/-- The finite list of absolute child descriptor addresses. -/
+def childWords (w cap previous : ℕ) (L : Layer) (i : Fin L.count) : List (Word w) :=
+ (L.ids i).map fun j => (address cap previous j : Word w)
+
+/-- Memory contains each site's row header and its child addresses at the designated
+fixed-pitch location, with the header address representable as a word. -/
+def Layer.Rows (L : Layer) (w : ℕ) (m : Memory w) (cap previous base : ℕ) : Prop :=
+ ∀ i : Fin L.count, let node := address cap base i.val
+ node < 2 ^ w ∧ DFS.Row m node (node + 2) (childWords w cap previous L i)
+
+/-- Populate the header and live children. Unused reserved cells retain
+their original contents. -/
+private def cell (cap previous base : ℕ) (L : Layer) (i : Fin L.count) (other : Word w) :
+ ℕ → Word w
+ | 0 => ((address cap base i.val + 2 : ℕ) : Word w)
+ | 1 => ((L.ids i).length : Word w)
+ | j + 2 => ((childWords w cap previous L i)[j]?).getD other
+
+/-- The memory image of one layer over arbitrary contents at other addresses. -/
+def writeLayer (cap previous base : ℕ) (L : Layer) (m : Memory w) : Memory w := fun x =>
+ if h : base ≤ x ∧ (x - base) / (cap + 2) < L.count then
+ cell cap previous base L ⟨_, h.2⟩ (m x) ((x - base) % (cap + 2))
+ else m x
+
+private theorem layer_at (cap previous base : ℕ) (L : Layer) (m : Memory w) (i : Fin L.count)
+ (slot : ℕ) (hs : slot < cap + 2) :
+ writeLayer cap previous base L m (address cap base i.val + slot) =
+ cell cap previous base L i (m (address cap base i.val + slot)) slot := by
+ have hsub : address cap base i.val + slot - base = slot + (cap + 2) * i.val := by
+ unfold address
+ omega
+ have hdiv : (slot + (cap + 2) * i.val) / (cap + 2) = i.val := by
+ rw [Nat.add_mul_div_left _ _ (by omega), Nat.div_eq_of_lt hs, Nat.zero_add]
+ have hmod : (slot + (cap + 2) * i.val) % (cap + 2) = slot := by
+ rw [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hs]
+ have hbase : base ≤ address cap base i.val + slot := by unfold address; omega
+ simp only [writeLayer, hsub, hdiv, hmod, hbase, i.isLt, and_self, ↓reduceDIte]
+
+/-- A word belongs to a live header or payload of this layer. Reserved padding
+and cells outside the layer are excluded. -/
+def Layer.Live (L : Layer) (cap base x : ℕ) : Prop :=
+ ∃ i : Fin L.count, address cap base i.val ≤ x ∧ x < address cap base i.val + 2 + (L.ids i).length
+
+theorem writeLayer_unchanged (cap previous base : ℕ) (L : Layer) (m : Memory w) (x : ℕ)
+ (h : ¬ L.Live cap base x) : writeLayer cap previous base L m x = m x := by
+ unfold writeLayer
+ split
+ · rename_i hi
+ let i : Fin L.count := ⟨_, hi.2⟩
+ let off := (x - base) % (cap + 2)
+ change cell cap previous base L i (m x) off = m x
+ have hreconstruct : address cap base i.val + off = x := by
+ change base + (cap + 2) * ((x - base) / (cap + 2)) + off = x
+ have he := Nat.div_add_mod (x - base) (cap + 2)
+ dsimp only [off] at *
+ omega
+ have hpad : 2 + (L.ids i).length ≤ off := by
+ by_contra! hlt
+ exact h ⟨i, by omega, by omega⟩
+ obtain ⟨j, hj⟩ := Nat.exists_eq_add_of_le (by omega : 2 ≤ off)
+ have hlen : (childWords w cap previous L i).length ≤ j := by
+ simpa [childWords] using (show (L.ids i).length ≤ j by omega)
+ rw [hj, Nat.add_comm 2 j]
+ simp [cell, List.getElem?_eq_none hlen]
+ · rfl
+
+private theorem row_end_le (cap base : ℕ) (L : Layer) (i : Fin L.count) :
+ address cap base i.val + (cap + 2) ≤ endPos cap base L := by
+ have h := Nat.mul_le_mul_left (cap + 2) i.isLt
+ rw [Nat.mul_succ] at h
+ unfold endPos address
+ omega
+
+/-- A complete row, including the exclusive-end bound required by the
+native child-copy loop. -/
+theorem writeLayer_rows (cap previous base : ℕ) (L : Layer) (m : Memory w)
+ (hc : ∀ i, (L.ids i).length ≤ cap) (fit : endPos cap base L < 2 ^ w) :
+ L.Rows w (writeLayer cap previous base L m) cap previous base := by
+ intro i
+ let node := address cap base i.val
+ have hrow : node + (cap + 2) ≤ endPos cap base L := row_end_le _ _ _ _
+ have hlen : (childWords w cap previous L i).length ≤ cap := by simpa [childWords] using hc i
+ refine ⟨by omega, by omega, by omega, ?_, ?_, ?_⟩
+ · exact layer_at cap previous base L m i 0 (by omega)
+ · simpa only [cell, childWords, List.length_map] using
+ layer_at cap previous base L m i 1 (by omega)
+ · intro j
+ have hj := j.isLt
+ have he := layer_at cap previous base L m i (j.val + 2) (by omega)
+ change writeLayer cap previous base L m (node + 2 + j.val) = _
+ rw [show node + 2 + j.val = address cap base i.val + (j.val + 2) by dsimp [node]; omega]
+ simpa only [cell, List.getElem?_eq_getElem hj, Option.getD_some] using he
+
+/-- Total row storage has a fixed number of words per position at each layer. -/
+def words (cap : ℕ) (layers : List Layer) : ℕ := (cap + 2) * (layers.map Layer.count).sum
+
+/-- Build all layers in increasing stage order, preserving older rows. -/
+def build (cap previous base : ℕ) : List Layer → Memory w → Memory w
+ | [], m => m
+ | L :: ls, m => build cap base (endPos cap base L) ls (writeLayer cap previous base L m)
+
+/-- Consecutive layers satisfy the row memory predicate with each new layer starting at the
+exclusive end of the preceding layer. -/
+def AllRows (w : ℕ) (m : Memory w) (cap previous base : ℕ) : List Layer → Prop
+ | [] => True
+ | L :: ls => L.Rows w m cap previous base ∧ AllRows w m cap base (endPos cap base L) ls
+
+private theorem build_below (ls : List Layer) (cap previous base : ℕ) (m : Memory w)
+ {x : ℕ} (hx : x < base) : build cap previous base ls m x = m x := by
+ induction ls generalizing previous base m with
+ | nil => rfl
+ | cons L ls ih =>
+ have he : x < endPos cap base L := hx.trans_le (Nat.le_add_right _ _)
+ exact (ih base (endPos cap base L) _ he).trans (dite_eq_right (fun h => hx.not_ge h.1))
+
+theorem build_rows (ls : List Layer) (cap previous base : ℕ) (m : Memory w)
+ (hc : ∀ L ∈ ls, ∀ i, (L.ids i).length ≤ cap) (fit : base + words cap ls < 2 ^ w) :
+ AllRows w (build cap previous base ls m) cap previous base ls := by
+ induction ls generalizing previous base m with
+ | nil => trivial
+ | cons L ls ih =>
+ let old := writeLayer cap previous base L m
+ let next := endPos cap base L
+ have hf : next + words cap ls < 2 ^ w := by simpa [next, endPos, address, words, Nat.mul_add,
+ Nat.add_assoc] using fit
+ have hcap i := hc L List.mem_cons_self i
+ have hgood := writeLayer_rows cap previous base L m hcap ((Nat.le_add_right _ _).trans_lt hf)
+ refine ⟨?_, ih base next old (fun L hL => hc L (List.mem_cons_of_mem _ hL)) hf⟩
+ intro i
+ let node := address cap base i.val
+ have he : node + (cap + 2) ≤ next := row_end_le cap base L i
+ obtain ⟨hn, hn1, hs, h0, h1, hj⟩ := hgood i
+ refine ⟨hn, hn1, hs, ?_, ?_, ?_⟩
+ · exact (build_below ls cap base next old (by omega : node < next)).trans h0
+ · exact (build_below ls cap base next old (by omega : node + 1 < next)).trans h1
+ · intro j
+ have hlen : (childWords w cap previous L i).length ≤ cap := by simpa [childWords] using hcap i
+ have hj' := j.isLt
+ exact (build_below ls cap base next old (by omega : node + 2 + j.val < next)).trans (hj j)
+
+/-- Base pointer and child-list pointer of a site in a specified layer. -/
+def sitePointers {I : Type} (cap base : ℕ) (ord : Order I) (v : I) : ℕ × ℕ :=
+ let node := address cap base (ord.entries.symm v).val
+ (node, node + 2)
+
+/-- Pointers to every output site of a selected term. The argument `base` is
+where the first output layer starts, immediately after the input layer. -/
+def chainPointers (cap : ℕ) {N Y : Network} (c : TermChain A N Y) (ords : ChainOrders c)
+ (base : ℕ) : RowPointers c :=
+ match c with
+ | .done _ => PUnit.unit
+ | .more _ _ tail => ⟨sitePointers cap base ords.1,
+ chainPointers cap tail ords.2 (address cap base ords.1.length)⟩
+
+/-- The table representation agrees with the descriptor row read by the native
+traversal, including the ordering of the children. -/
+theorem chainPointers_rowsAt (c : TermChain A N Y) (r : ChainParsers κ c) (ords : ChainOrders c)
+ (initial : Order N.Site) (cap previous base : ℕ) (m : Memory w)
+ (hrows : AllRows w m cap previous base (stepLayers c r ords initial)) :
+ rowsAt c r (chainPointers cap c ords base) m
+ (fun v => (sitePointers cap previous initial v).1) := by
+ induction c generalizing previous base with
+ | done => trivial
+ | more t data tail ih =>
+ refine ⟨fun v => ?_, ih r.2 ords.2 ords.1 base (address cap base ords.1.length) hrows.2⟩
+ obtain ⟨i, rfl⟩ := ords.1.entries.surjective v
+ have hv := hrows.1 i
+ simpa only [chainPointers, sitePointers, childWords, stepLayer, List.map_ofFn,
+ Function.comp_def,
+ Equiv.symm_apply_apply] using hv
+
+/-- Initial leaf headers and all later descriptors are simultaneously present
+in the same memory, built on any initial contents. -/
+theorem chain_memory_rows (c : TermChain A N Y) (r : ChainParsers κ c) (ords : ChainOrders c)
+ (initial : Order N.Site) (cap base : ℕ) (m : Memory w) {W : ℕ} (hb : c.Bounded cap W)
+ (fit : base + words cap (chainLayers c r ords initial) < 2 ^ w) :
+ let image := build cap base base (chainLayers c r ords initial) m
+ let leaf := sitePointers cap base initial
+ (∀ v, (leaf v).1 < 2 ^ w ∧ DFS.Row image (leaf v).1 (leaf v).2 []) ∧
+ rowsAt c r (chainPointers cap c ords (address cap base initial.length)) image
+ (fun v => (leaf v).1) := by
+ have hr := build_rows (chainLayers c r ords initial) cap base base m
+ (chainLayers_capacity c r ords initial hb) fit
+ exact ⟨fun v => hr.1 (initial.entries.symm v), chainPointers_rowsAt c r ords initial _ _ _ _ hr.2⟩
+
+/-- Building the descriptor region leaves the rest of memory available to
+other pair-simulation phases. -/
+theorem build_outside (ls : List Layer) (cap previous base : ℕ) (m : Memory w) (x : ℕ)
+ (hx : x < base ∨ base + words cap ls ≤ x) : build cap previous base ls m x = m x := by
+ rcases hx with hx | hx
+ · exact build_below _ _ _ _ _ hx
+ · induction ls generalizing previous base m with
+ | nil => rfl
+ | cons L ls ih =>
+ have he : endPos cap base L + words cap ls ≤ x := by
+ simpa [endPos, address, words, Nat.mul_add, Nat.add_assoc] using hx
+ have he' : endPos cap base L ≤ x := (Nat.le_add_right _ _).trans he
+ have hdiv : L.count ≤ (x - base) / (cap + 2) := by
+ apply (Nat.le_div_iff_mul_le (by omega)).mpr
+ rw [Nat.mul_comm]
+ unfold endPos address at he'
+ omega
+ exact (ih base (endPos cap base L) _ he).trans (dite_eq_right (fun h => hdiv.not_gt h.2))
+
+omit [CommRing A] in
+private theorem count_le_push {t : Term A N} (data : t.output.Site → SiteRecords)
+ (counts : N.Site → ℕ) : Fintype.card t.output.Site + ∑ u, counts u ≤
+ ∑ v, t.pushHistorySize data counts v := by
+ classical
+ let e : ((v : t.output.Site) × t.Preimage v) ≃ N.Site :=
+ { toFun := fun p => p.2.val
+ invFun := fun u => ⟨t.place u, ⟨u, rfl⟩⟩
+ left_inv := fun ⟨v, ⟨u, h⟩⟩ => by cases h; rfl
+ right_inv := fun _ => rfl }
+ have hsum : ∑ v, ∑ u : t.Preimage v, counts u.val = ∑ u, counts u := by
+ rw [← Fintype.sum_sigma' (fun v (u : t.Preimage v) => counts u.val)]
+ exact Fintype.sum_equiv e _ _ (fun _ => rfl)
+ rw [show (∑ v, t.pushHistorySize data counts v) =
+ (∑ v, (data v).count) + ∑ v, ∑ u : t.Preimage v, counts u.val by
+ simp only [Term.pushHistorySize, Finset.sum_add_distrib], hsum]
+ have hc := Finset.sum_le_sum (s := Finset.univ) (fun v _ =>
+ show 1 ≤ (data v).count by unfold SiteRecords.count; omega)
+ simpa using Nat.add_le_add_right hc (∑ u, counts u)
+
+/-- Every old position is assigned to exactly one successor. Thus the number
+of rows, summed over the levels, is at most the total history size across the
+final positions. This gives a word bound without inspecting intermediate sites. -/
+theorem count_stepLayers_le (c : TermChain A N Y) (r : ChainParsers κ c) (ords : ChainOrders c)
+ (initial : Order N.Site) (counts : N.Site → ℕ) :
+ ((stepLayers c r ords initial).map Layer.count).sum + ∑ u, counts u ≤
+ ∑ v, c.occurrences counts v := by
+ classical
+ induction c with
+ | done => simp [stepLayers, TermChain.occurrences]
+ | more t data tail ih =>
+ have ho : ords.1.length = Fintype.card t.output.Site := by
+ simpa only [Fintype.card_fin] using Fintype.card_congr ords.1.entries
+ have h := ih r.2 ords.2 ords.1 (t.pushHistorySize data counts)
+ have hp := count_le_push (t := t) data counts
+ simp only [stepLayers, stepLayer, List.map_cons, List.sum_cons, TermChain.occurrences, ho]
+ omega
+
+section Selected
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) (f : B.Entry → A)
+variable (hf : B.IsSolution f) {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+variable (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+
+/-- Exact row counts and old IDs determined by an admissible branch of the
+actual compressor. The site numbers of every intermediate state are used. -/
+noncomputable def selectedLayers : List Layer :=
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ chainLayers (E.termChain data z) (selectedParsers B f hf T hT X z) (branchOrders E data z)
+ (siteOrder X)
+
+/-- The selected descriptor region fits in the product of the fixed stride,
+final order and history allowance. This gives a sufficient address-space test
+without enumerating the rows. -/
+theorem selected_words_le :
+ words B.recordLimit (selectedLayers B f hf T hT X z) ≤
+ (B.recordLimit + 2) * ((B.execute f hf T hT X).finalState z).positions *
+ B.growthConstant ^ T := by
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let r := selectedParsers B f hf T hT X z
+ let ords := branchOrders E data z
+ let initial := siteOrder X
+ have hi : initial.length = Fintype.card X.network.Site := by
+ simpa only [Fintype.card_fin] using Fintype.card_congr initial.entries
+ have h₁ := count_stepLayers_le c r ords initial (fun _ => 1)
+ have h₂ := Finset.sum_le_sum (s := Finset.univ)
+ (fun v _ => (B.branch_bounds f hf T hT X z).2.2.2.1 v)
+ change (B.recordLimit + 2) *
+ (initial.length + ((stepLayers c r ords initial).map Layer.count).sum) ≤ _
+ rw [Nat.mul_assoc]
+ apply Nat.mul_le_mul_left
+ rw [hi, Nat.add_comm]
+ have hsum : ((stepLayers c r ords initial).map Layer.count).sum + Fintype.card X.network.Site ≤
+ ∑ v, c.occurrences (fun _ => 1) v := by simpa using h₁
+ have heq : Fintype.card (E.finalState z).network.Site = (E.finalState z).positions := rfl
+ rw [← heq]
+ exact hsum.trans (by simpa [c, E, data] using h₂)
+
+/-- In the memory constructed for this branch the native DFS reads precisely
+the actual placement tree. No hypotheses about the contents of headers or
+child lists are required. -/
+theorem selected_memory_traversal (base : ℕ) (m : Memory w)
+ (fit : base + words B.recordLimit (selectedLayers B f hf T hT X z) < 2 ^ w) :
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let ptr := chainPointers B.recordLimit c (branchOrders E data z)
+ (address B.recordLimit base (siteOrder X).length)
+ let leaves := sitePointers B.recordLimit base (siteOrder X)
+ let trees := chainTrees c (selectedParsers B f hf T hT X z) ptr (fun v => leafTree (leaves v))
+ let image := build B.recordLimit base base (selectedLayers B f hf T hT X z) m
+ ∀ v, ∃ es, DFS.Visits image (B.growthConstant ^ T) [((trees v).address : Word w)]
+ ((trees v).preorder.map (fun n : ℕ => (n : Word w))) es ∧
+ countProbes es < 3 * c.occurrences (fun _ => 1) v ∧
+ es.length ≤ 15 * c.occurrences (fun _ => 1) v + 1 := by
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ have hbound := Procedure.repeat_recordBounds (B.recordBounds f hf) _ T lanes
+ (Nat.add_sub_of_le hT).symm X
+ have hb := E.termChain_bounded data hbound.1 z
+ have hr := chain_memory_rows (E.termChain data z) (selectedParsers B f hf T hT X z)
+ (branchOrders E data z) (siteOrder X) B.recordLimit base m hb fit
+ exact selectedTraversal B f hf T hT X z _ _ _ hr.1 hr.2
+
+end Selected
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalScanDirectory.lean b/lean/OAI/Computability/VPVNP/PairTraversalScanDirectory.lean
new file mode 100644
index 0000000000..bb1a807307
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalScanDirectory.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairTraversalLevelDirectories
+
+/-!
+# Directory witnesses from native placement scans
+
+The physical owner computation may implement the selected placement by a
+different function on unused word values. On all live identifiers the two
+ordered scans agree, giving the exact input directory to the row worker.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open BurstRAM CompressorRecords LocalHistory NetworkKernel Compression
+open scoped Fin.CommRing
+
+variable {w : ℕ} {A : Type*} [CommRing A] {N : Network} (t : Term A N)
+
+private theorem siteWord_entry {I : Type} (o : Order I) (x : Word w) (h : x.val < o.length) :
+ siteWord w o (o.entries ⟨x.val, h⟩) = x := by
+ apply Fin.ext
+ simp [siteWord]
+
+open Classical in
+/-- A native scan of a word-level placement that agrees on every actual site
+gives exactly the directory of the mathematical term. -/
+def Directory.ofPhysical (old : Order N.Site) (next : Order t.output.Site) (pub : Fin 6 → Word w)
+ (raw : Memory w) (limit : ℕ) (h₀ : (pub 0).val = old.length) (h₁ : (pub 2).val = next.length)
+ (regions : RowRegions pub) (bounds : (pub 5).val + (pub 2).val * (pub 4).val ≤ limit)
+ (p : Word w → Word w) (hp : RepresentsPlacement old next t.place p)
+ (hs : PreimagesAt pub p raw old.length)
+ (capacity : ∀ v, Fintype.card (t.Preimage v) ≤ (pub 4).val) :
+ Directory t old next raw limit := by
+ let actual : Word w → Word w := encodedPlacement old.entries.symm next.entries.symm t.place
+ have ho : old.length ≤ 2 ^ w := h₀ ▸ (pub 0).isLt.le
+ have hn : next.length ≤ 2 ^ w := h₁ ▸ (pub 2).isLt.le
+ have ha := encodedPlacement_represents old next t.place (w := w) ho hn
+ have fiberRow (v : Word w) (hv : v < pub 2) (q : Word w → Word w)
+ (hq : RepresentsPlacement old next t.place q) :
+ let y := next.entries ⟨v.val, (show v.val < (pub 2).val from hv).trans_eq h₁⟩
+ preimagePrefix q v old.length =
+ orderedIds w old (fun u => y = t.place u) (old.restrict _) := by
+ let y := next.entries ⟨v.val, (show v.val < (pub 2).val from hv).trans_eq h₁⟩
+ have h := preimagePrefix_eq_orderedIds old next t.place q hq ho hn y
+ rwa [siteWord_entry next v _] at h
+ refine ⟨pub, h₀, h₁, regions, bounds, ⟨fun i hi => ?_, fun v hv => ?_⟩, fun v hv => ?_⟩
+ · let u := old.entries ⟨i.val, (show i.val < (pub 0).val from hi).trans_eq h₀⟩
+ have eq := (hp u).trans (ha u).symm
+ rw [siteWord_entry old i _] at eq
+ exact (hs.owners i hi).trans eq
+ · rw [fiberRow v hv actual ha, ← fiberRow v hv p hp]
+ exact hs.rows v hv
+ · let y := next.entries ⟨v.val, (show v.val < (pub 2).val from hv).trans_eq h₁⟩
+ rw [fiberRow v hv actual ha, orderedIds, List.length_ofFn]
+ have card := Fintype.card_congr (old.restrict (fun u => y = t.place u)).entries
+ rw [Fintype.card_fin] at card
+ exact card.trans_le (capacity y)
+
+open private placementLayer from OAI.Computability.VPVNP.PairTraversalStageSize
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) (f : B.Entry → A)
+variable (hf : B.IsSolution f) {n : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ n)
+variable (X : State (S.degreeExponent 0) n) (z : (B.execute f hf T hT X).Choices)
+
+open Classical in
+/-- The selected record limit bounds each actual placement fiber, including
+fibers of size zero. It therefore supplies the raw scanner's capacity. -/
+theorem selected_fiber_capacity (v : SelectedLevel B f hf) (hv : v ∈ executeLevels B f hf T hT X z)
+ (y : (v.pass.step.term v.term).output.Site) :
+ Fintype.card ((v.pass.step.term v.term).Preimage y) ≤ B.recordLimit := by
+ classical
+ let t := v.pass.step.term v.term
+ let old := siteOrder v.input
+ let next : Order t.output.Site := (v.pass.output_eq v.term).symm ▸ siteOrder (v.pass.next v.term)
+ have hm : levelLayer B f hf v ∈ selectedLayers B f hf T hT X z := by
+ rw [selectedLayers_eq_levels]
+ exact List.mem_cons_of_mem _ (List.mem_map_of_mem hv)
+ have h := selected_capacity B f hf T hT X z _ hm (next.entries.symm y)
+ simp only [levelLayer, placementLayer, List.length_ofFn] at h
+ change (old.restrict (fun u => next.entries (next.entries.symm y) = t.place u)).length ≤ _ at h
+ rw [Equiv.apply_symm_apply] at h
+ have card := Fintype.card_congr (old.restrict (fun u => y = t.place u)).entries
+ rw [Fintype.card_fin] at card
+ exact card.symm.trans_le h
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalSelectedOrder.lean b/lean/OAI/Computability/VPVNP/PairTraversalSelectedOrder.lean
new file mode 100644
index 0000000000..5e5c65b898
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalSelectedOrder.lean
@@ -0,0 +1,205 @@
+import OAI.Computability.VPVNP.PairTraversalRows
+
+/-!
+# The order of placement fibers throughout a selected compressor branch
+
+The shrink and refresh readers both enumerate children in the numerical order
+of the preceding state. Joining procedures and repeating the compression block
+preserve these orders along each branch of the selected kernel history.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel Compression
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {κ : L → R}
+
+open Classical in
+/-- Every child list uses the restriction of the numbering at its input layer. -/
+def OrderedChildren {N Y : Network} (c : TermChain R N Y) (r : ChainParsers κ c)
+ (orders : ChainOrders c) (old : Order N.Site) : Prop :=
+ match c with
+ | .done _ => True
+ | .more t _ tail =>
+ (∀ v, r.1.order.children v = old.restrict (fun u => v = t.place u)) ∧
+ OrderedChildren tail r.2 orders.2 orders.1
+
+open Classical in
+/-- The local descriptor uses the actual child, outgoing, and incoming orders of its source state. -/
+def PassOrders {a g b n : ℕ} {X : State a g} {p : StatePass R X b n}
+ {W : p.MapWitnesses κ} (r : PassReaders p W) : Prop :=
+ (∀ i v, (r.order i).children v = (siteOrder X).restrict (fun u => v = (p.step.term i).place u)) ∧
+ (∀ i u, (r.order i).outgoing u = outgoingOrder X u) ∧
+ ∀ i u, (r.order i).incoming u = incomingOrder X u
+
+/-- Orders at all stages and all choices of this execution. -/
+def ExecutionOrders {a g b n : ℕ} {X : State a g} :
+ (E : StateExecution R b n X) → (W : E.MapWitnesses κ) → ExecutionReaders E W → Prop
+ | .done _, _, _ => True
+ | .more _ tail, W, r => PassOrders r.1 ∧ ∀ i, ExecutionOrders (tail i) (W.2 i) (r.2 i)
+
+open private castParsers from OAI.Computability.VPVNP.PairSimulationAssemblyBounds
+
+private def castOrders {N M Y : Network} (h : N = M) (c : TermChain R M Y) (r : ChainOrders c) :
+ ChainOrders (h.symm ▸ c : TermChain R N Y) := by cases h; exact r
+
+private theorem branch_ordered {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X)
+ (W : E.MapWitnesses κ) (r : ExecutionReaders E W) (rec : E.Records) (z : E.Choices)
+ (h : ExecutionOrders E W r) :
+ OrderedChildren (E.termChain rec z) (branchParsers E W r rec z)
+ (branchOrders E rec z) (siteOrder X) := by
+ induction E with
+ | done => trivial
+ | more p tail ih =>
+ refine ⟨h.1.1 z.1, ?_⟩
+ have htail := ih z.1 (W.2 z.1) (r.2 z.1) (rec.2 z.1) z.2 (h.2 z.1)
+ let c := (tail z.1).termChain (rec.2 z.1) z.2
+ let parsers := branchParsers (tail z.1) (W.2 z.1) (r.2 z.1) (rec.2 z.1) z.2
+ let orders := branchOrders (tail z.1) (rec.2 z.1) z.2
+ have transport {N M Y : Network} (e : N = M) (d : TermChain R M Y)
+ (pars : ChainParsers κ d) (ord : ChainOrders d) (s : Order M.Site)
+ (hd : OrderedChildren d pars ord s) :
+ OrderedChildren (e.symm ▸ d : TermChain R N Y) (castParsers e.symm d pars)
+ (castOrders e d ord) (e.symm ▸ s) := by
+ cases e
+ exact hd
+ exact transport (p.output_eq z.1) c parsers orders (siteOrder (p.next z.1)) htail
+
+private theorem executionOrdered_bind {a g b n b' n' : ℕ} {X : State a g}
+ (E : StateExecution R b n X)
+ (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z))
+ (W : E.MapWitnesses κ) (V : ∀ z, (f z).MapWitnesses κ)
+ (r : ExecutionReaders E W) (s : ∀ z, ExecutionReaders (f z) (V z))
+ (h : ExecutionOrders E W r) (hs : ∀ z, ExecutionOrders (f z) (V z) (s z)) :
+ ExecutionOrders (E.bind f) _ (bindReaders E f W V r s) := by
+ induction E with
+ | done => exact hs ()
+ | more _ _ ih =>
+ exact ⟨h.1, fun i => ih i _ (W.2 i) _ (r.2 i) _ (h.2 i) (fun z => hs ⟨i, z⟩)⟩
+
+variable {a b l d : ℕ} {μ : ℝ}
+
+private abbrev procedureOrdered {P : Procedure R a b l d μ} {W : P.MapWitnesses κ}
+ (r : ProcedureReaders P W) : Prop :=
+ ∀ g n h X, ExecutionOrders (P.run g n h X) _ (r g n h X)
+
+private theorem procedureOrdered_id (a : ℕ) (κ : L → R) :
+ procedureOrdered (ProcedureReaders.id a κ) := by
+ intro g n h X
+ have eqn := h.trans (Nat.zero_add g)
+ subst g
+ trivial
+
+private theorem procedureOrdered_ofPass {A : ℝ} (hd : 0 < d) (hμ : 0 ≤ μ) (hA : 0 ≤ A)
+ (f : ∀ g (X : State a (l + g)), StatePass R X b g)
+ (hc : ∀ g X (i : (f g X).step.Choice), X.positions = d * ((f g X).next i).positions)
+ (he : ∀ g X (i : (f g X).step.Choice),
+ ((f g X).next i).energy ≤ μ * X.energy + A * (X.positions : ℝ) ^ 2)
+ (W : ∀ g X, (f g X).MapWitnesses κ) (r : ∀ g X, PassReaders (f g X) (W g X))
+ (hr : ∀ g X, PassOrders (r g X)) :
+ procedureOrdered (ProcedureReaders.ofPass hd hμ hA f hc he W r) := by
+ intro g n h X
+ subst n
+ exact ⟨hr g X, fun _ => trivial⟩
+
+private theorem procedureOrdered_seq {c l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ}
+ {Q : Procedure R b c l' d' ν} {W : P.MapWitnesses κ} {V : Q.MapWitnesses κ}
+ {r : ProcedureReaders P W} {s : ProcedureReaders Q V}
+ (hr : procedureOrdered r) (hs : procedureOrdered s) : procedureOrdered (r.seq s) :=
+ fun g n eqn X =>
+ let E := P.run (l' + g) n (eqn.trans (Nat.add_assoc l l' g)) X
+ executionOrdered_bind E _ _ _ _ _ (hr _ _ _ X) (fun z => hs _ _ _ (E.finalState z))
+
+private theorem procedureOrdered_reindex {a' b' l' d' : ℕ} {μ' : ℝ} {P : Procedure R a b l d μ}
+ {W : P.MapWitnesses κ} {r : ProcedureReaders P W} (hr : procedureOrdered r)
+ {ha : a = a'} {hb : b = b'} {hl : l = l'} {hd : d = d'} {hμ : μ = μ'} :
+ procedureOrdered (r.reindex (ha := ha) (hb := hb) (hl := hl) (hd := hd) (hμ := hμ)) := by
+ subst a' b' l' d' μ'
+ exact hr
+
+open private prefixReaders from OAI.Computability.VPVNP.PairSimulationAssembly
+open private prefixWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory
+
+variable {k : Type*} [Field k] (S : BlockSchedule k)
+
+private theorem prefix_ordered (shrink : S.ShrinkProcedures R)
+ (W : ∀ i, (shrink i).MapWitnesses κ) (r : ∀ i, ProcedureReaders (shrink i) (W i))
+ (hr : ∀ i, procedureOrdered (r i)) (j : ℕ) (hj : j ≤ S.steps) :
+ procedureOrdered (prefixReaders S shrink W r j hj) := by
+ induction j with
+ | zero =>
+ simp only [prefixReaders, prefixWitnesses, BlockSchedule.shrinkPrefix]
+ exact procedureOrdered_reindex (procedureOrdered_id _ κ)
+ | succ j ih =>
+ simp only [prefixReaders, prefixWitnesses, BlockSchedule.shrinkPrefix]
+ exact procedureOrdered_reindex (procedureOrdered_seq (ih (Nat.le_of_succ_le hj))
+ (procedureOrdered_reindex (hr ⟨j, hj⟩)))
+
+private theorem assemble_ordered (shrink : S.ShrinkProcedures R) (refresh : S.RefreshProcedure R)
+ (W : ∀ i, (shrink i).MapWitnesses κ) (V : refresh.MapWitnesses κ)
+ (r : ∀ i, ProcedureReaders (shrink i) (W i)) (s : ProcedureReaders refresh V)
+ (h : ∀ i, procedureOrdered (r i)) (hs : procedureOrdered s) :
+ procedureOrdered (assembleReaders S shrink refresh W V r s) := by
+ unfold assembleReaders
+ exact procedureOrdered_reindex (procedureOrdered_seq
+ (procedureOrdered_reindex (prefix_ordered S shrink W r h S.steps le_rfl)) hs)
+
+private theorem repeat_ordered {P : Procedure R a a l d μ} {W : P.MapWitnesses κ}
+ {r : ProcedureReaders P W} (hr : procedureOrdered r) (g T n : ℕ)
+ (h : n = T * l + g) (X : State a n) :
+ ExecutionOrders (P.repeatExecution g T n h X) _ (repeatReaders r g T n h X) := by
+ induction T generalizing n with
+ | zero =>
+ have hn : n = g := by simpa using h
+ subst g
+ trivial
+ | succ t ih =>
+ let E := P.run (t * l + g) n (by rw [h, Nat.succ_mul]; omega) X
+ exact executionOrdered_bind E _ _ _ _ _ (hr _ _ _ X) (fun z => ih _ rfl (E.finalState z))
+
+variable {S} (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+
+private theorem shrinkPass_ordered (i : Fin S.steps) {g n : ℕ}
+ (h : n = packingLaneBits (S.degreeExponent i.castSucc) g)
+ (X : State (S.degreeExponent i.castSucc) n) :
+ PassOrders (shrinkPassReaders B f hf i h X) := by
+ subst n
+ exact ⟨fun _ _ => rfl,fun _ _ => rfl,fun _ _ => rfl⟩
+
+private theorem block_ordered : procedureOrdered (blockReaders B f hf) := by
+ apply assemble_ordered
+ · intro i
+ apply procedureOrdered_ofPass
+ exact fun g X => shrinkPass_ordered B f hf i (packingLaneBits_add _ g) X
+ · apply procedureOrdered_ofPass
+ intro g X
+ exact ⟨fun _ _ => rfl,fun _ _ => rfl,fun _ _ => rfl⟩
+
+/-- The actual slot orders on both sides of every visit, through all
+repetitions of the shrinking and degree-refresh block. -/
+theorem execute_readerOrders {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n)
+ (X : State (S.degreeExponent 0) n) :
+ ExecutionOrders (B.execute f hf T h X) _
+ (repeatReaders (blockReaders B f hf) _ T n (Nat.add_sub_of_le h).symm X) :=
+ repeat_ordered (block_ordered B f hf) _ T n (Nat.add_sub_of_le h).symm X
+
+/-- In the actual repeated compressor, each local reader visits old positions in the
+same order as a scan by their numerical identifiers. -/
+theorem selectedParsers_ordered {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n)
+ (X : State (S.degreeExponent 0) n) (z : (B.execute f hf T h X).Choices) :
+ let E := B.execute f hf T h X
+ let recs := B.records f hf T h X
+ OrderedChildren (E.termChain recs z) (selectedParsers B f hf T h X z)
+ (branchOrders E recs z) (siteOrder X) :=
+ branch_ordered _ _ _ _ _
+ (execute_readerOrders B f hf T h X)
+
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalSiteReads.lean b/lean/OAI/Computability/VPVNP/PairTraversalSiteReads.lean
new file mode 100644
index 0000000000..33e3a82395
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalSiteReads.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.PairTraversalSiteWorker
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-!
+# External read addresses of a placement-fiber worker
+
+The setup probes the count cell once. Every iteration reads its current
+source identifier, then advances the source cursor by one. The translated
+addresses and the two new header cells are written without being read.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows.SiteWorker
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM PrimedCounter CompressorRecords
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+private theorem unique_lines {r k : ℕ} {ops : List (Op r k)} {nonempty : ops ≠ []}
+ {pub : Fin k → Word w} {state : Word w} {rs m es out m' fs out' m''}
+ (first : Flow.Exec pub state (lines ops nonempty) rs m es out m')
+ (second : Flow.Exec pub state (lines ops nonempty) rs m fs out' m'') :
+ es = fs ∧ out = out' ∧ m' = m'' := by
+ have e := (Admin.exec_lines_iff_trace nonempty).mp first
+ have f := (Admin.exec_lines_iff_trace nonempty).mp second
+ simpa only [Option.some.injEq, Prod.mk.injEq] using e.symm.trans f
+
+open private advance events body_exec from OAI.Computability.VPVNP.PairSimulationDescriptorRows
+
+private def loopOps : List (Op 7 0) :=
+ [.read 6 0, .binary .mul 6 6 4, .binary .add 6 6 3, .write 2 6, .binary .add 0 0 5,
+ .binary .add 2 2 5]
+
+/-- In every successful loop derivation the sole read of an iteration is
+at its current source address. -/
+private theorem scan_reads (pub : Fin 0 → Word w) (state : Word w) (src count : ℕ)
+ {rs m es out m'} (run : Flow.Exec pub state DescriptorRows.scan rs m es out m')
+ (start : (rs 0).val = src) (stop : (rs 1).val = src + count) (unit : rs 5 = 1) :
+ SourceTransport.Reads (fun x => src ≤ x ∧ x < src + count) es := by
+ induction count generalizing src rs m es with
+ | zero =>
+ cases run with
+ | whileDone => intro a v hv; simp at hv
+ | whileStep lt _ _ =>
+ have h : (rs 0).val < (rs 1).val := lt
+ omega
+ | succ n ih =>
+ cases run with
+ | whileDone => intro a v hv; simp at hv
+ | @whileStep _ _ _ _ _ head mid mem' tail _ _ _ body later =>
+ have hb : Flow.Exec pub state (lines loopOps (by decide)) rs m head mid mem' := body
+ obtain ⟨traceEq, regsEq, _⟩ := unique_lines hb (body_exec pub state rs m)
+ have bound : src + (n + 1) < 2 ^ w := stop ▸ (rs 1).isLt
+ have start' : (mid 0).val = src + 1 := by
+ rw [regsEq]
+ simp (config := { decide := true }) [advance, Function.update, Fin.val_add, start, unit,
+ Nat.mod_eq_of_lt (by omega : src + 1 < 2 ^ w)]
+ have stop' : (mid 1).val = src + 1 + n := by
+ rw [regsEq]
+ simp (config := { decide := true }) [advance, Function.update, stop]
+ omega
+ have unit' : mid 5 = 1 := by
+ rw [regsEq]
+ simp (config := { decide := true }) [advance, Function.update, unit]
+ have ht := ih (src + 1) later start' stop' unit'
+ intro a v hv
+ simp only [List.mem_cons, reduceCtorEq, false_or, List.mem_append] at hv
+ rcases hv with h | h
+ · rw [traceEq] at h
+ simp only [events, List.mem_cons, List.not_mem_nil, reduceCtorEq, or_false,
+ Event.read.injEq] at h
+ rw [h.1, start]
+ omega
+ · have bounds := ht a v h
+ omega
+
+open private setupOps setup_exec finish_exec from OAI.Computability.VPVNP.PairTraversalSiteWorker
+
+private theorem setup_reads {pub : Fin 6 → Word w} {i : Word w} {rs m es out m'}
+ (run : Flow.Exec pub i (lines setupOps (by decide)) rs m es out m') :
+ SourceTransport.Reads (fun x => x = (counter pub i).val) es := by
+ have h := (Admin.exec_lines_iff_trace (by decide)).mp run
+ simp (config := { decide := true }) only [setupOps, Fin.isValue, trace, Op.effect, BinaryOp.eval,
+ Nat.reducePow, Fin.coe_ofNat_eq_mod, Nat.reduceMod, Fin.ofNat_eq_cast, Nat.cast_ofNat,
+ Nat.one_mod, Nat.cast_one, Prod.mk.eta, Option.pure_def, Option.bind_eq_bind, Option.bind_some,
+ Function.update, ↓reduceDIte, Function.update_idem, Option.some.injEq, Prod.mk.injEq] at h
+ rw [← h.1]
+ intro a v ha
+ simp only [List.mem_cons, List.not_mem_nil, reduceCtorEq, Event.read.injEq, false_or,
+ or_false] at ha
+ exact congrArg Fin.val ha.1
+
+/-- A successful native worker reads only its own count cell and its occupied
+source row. The result applies to the report returned by the machine. -/
+theorem native_reads (pub : Fin 6 → Word w) (i : Word w) (m : Memory w)
+ (src nodeAddr count fuel : ℕ) (hs : source pub i = (src : Word w))
+ (_hn : node pub i = (nodeAddr : Word w)) (hc : (m (counter pub i).val).val = count)
+ (before : src + count ≤ nodeAddr) (fit : nodeAddr + 2 + count < 2 ^ w)
+ (_clock : 7 * count + 24 < fuel) {rep : Report w}
+ (exec : let M := (program.template (some 6)).instantiate w pub
+ execute M.program fuel (M.program.start i) m [] = some rep) :
+ SourceTransport.Reads (fun x => x = (counter pub i).val ∨ src ≤ x ∧ x < src + count)
+ rep.events := by
+ obtain ⟨out, m', run, _, _, _⟩ := (Flow.template_execute_iff program (some 6) pub i
+ (fun _ => 0) (fun _ => 0) m fuel [] rep).mp exec
+ generalize h : rep.events = es at run ⊢
+ cases run with
+ | @seq _ _ _ _ ss rs mid ts _ _ setup tail =>
+ obtain ⟨ss', rs', first, h0, h1, _, _, _, h5, _, _, _⟩ := setup_exec pub i m (fun _ => 0)
+ obtain ⟨_, regsEq, _⟩ := unique_lines setup first
+ have heads := setup_reads setup
+ cases tail with
+ | @seq _ _ _ _ loopEs last mem' endEs _ _ renamed finish =>
+ obtain ⟨loop, _⟩ := restrictExec (Function.Embedding.refl (Fin 7)) Fin.elim0 pub
+ DescriptorRows.scan renamed
+ have start : (rs 0).val = src := by
+ rw [regsEq, h0, hs]
+ exact Nat.mod_eq_of_lt (by omega)
+ have stop : (rs 1).val = src + count := by
+ rw [regsEq, h1, Fin.val_add, show (source pub i).val = src from h0 ▸ regsEq ▸ start, hc]
+ exact Nat.mod_eq_of_lt (by omega)
+ have ids := scan_reads (pub ∘ Fin.elim0) i src count loop start stop (regsEq ▸ h5)
+ obtain ⟨last', ending, _⟩ := finish_exec pub i mem' last
+ have hEnd := (unique_lines finish ending).1
+ intro a v hv
+ rcases List.mem_append.mp hv with h | h
+ · exact Or.inl (heads a v h)
+ rcases List.mem_append.mp h with h | h
+ · exact Or.inr (ids a v h)
+ · rw [hEnd] at h
+ simp at h
+
+end PairSimulation.TraversalRows.SiteWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalSiteWorker.lean b/lean/OAI/Computability/VPVNP/PairTraversalSiteWorker.lean
new file mode 100644
index 0000000000..e507e68efa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalSiteWorker.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PairTraversalWorkerMemory
+import OAI.Computability.VPVNP.PrimedCounterRenameRun
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+
+/-!
+# Uniform site worker for the traversal descriptor table
+
+One burst starts with zero registers and the site number in persistent state.
+Six public words specify the counts, identifier rows and two descriptor layers.
+The worker fetches its count, writes the two header words, translates its row
+of identifiers, and returns the next site number.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows.SiteWorker
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Address of the selected site's preimage-count word in the traversal worker's public count
+array. -/
+def counter (pub : Fin 6 → Word w) (i : Word w) := pub 0 + i
+/-- Start address of the selected site's fixed-pitch preimage list in the source directory. -/
+def source (pub : Fin 6 → Word w) (i : Word w) := pub 1 + i * pub 2
+/-- Destination DFS row address for the current site in the new traversal layer. -/
+def node (pub : Fin 6 → Word w) (i : Word w) := pub 4 + i * pub 5
+
+private def setupOps : List (Op 7 6) :=
+ [.stateWord 6, .publicWord 0 2, .binary .mul 0 6 0, .publicWord 1 1,
+ .binary .add 0 1 0, .publicWord 1 0, .binary .add 1 1 6, .read 1 1,
+ .publicWord 4 5, .binary .mul 6 6 4, .publicWord 2 4, .binary .add 6 2 6,
+ .constant 5 2, .binary .add 2 6 5, .write 6 2, .constant 5 1,
+ .binary .add 6 6 5, .write 6 1, .binary .add 1 0 1, .publicWord 3 3]
+
+private def finishOps : List (Op 7 6) :=
+ [.stateWord 6, .constant 5 1, .binary .add 6 6 5]
+
+/-- The instruction table has fixed shape for every word width and every layer size. -/
+def program : Flow 7 6 :=
+ .seq (lines setupOps (by decide)) <|
+ .seq (renameFlow (Function.Embedding.refl (Fin 7)) Fin.elim0 DescriptorRows.scan)
+ (lines finishOps (by decide))
+
+private def headerMemory (pub : Fin 6 → Word w) (i : Word w) (m : Memory w) : Memory w :=
+ writeMemory (writeMemory m (node pub i) (node pub i + 2)) (node pub i + 1)
+ (m (counter pub i).val)
+
+private theorem setup_exec (pub : Fin 6 → Word w) (i : Word w) (m : Memory w) (input : Regs w 7) :
+ ∃ es rs, Flow.Exec pub i (lines setupOps (by decide)) input m es rs
+ (headerMemory pub i m) ∧
+ rs 0 = source pub i ∧ rs 1 = source pub i + m (counter pub i).val ∧
+ rs 2 = node pub i + 2 ∧ rs 3 = pub 3 ∧ rs 4 = pub 5 ∧ rs 5 = 1 ∧
+ countProbes es = 3 ∧ es.length = 20 ∧ choiceBits es = [] := by
+ simp only [Admin.exec_lines_iff_trace]
+ simp (config := { decide := true }) [setupOps, trace, Op.effect, BinaryOp.eval, Function.update,
+ counter, source, node, headerMemory, countProbes, choiceBits]
+
+private theorem finish_exec (pub : Fin 6 → Word w) (i : Word w) (m : Memory w) (rs : Regs w 7) :
+ ∃ out, Flow.Exec pub i (lines finishOps (by decide)) rs m [.tick, .tick, .tick] out m ∧
+ out 6 = i + 1 := by
+ simp only [Admin.exec_lines_iff_trace]
+ simp (config := { decide := true }) [finishOps, trace, Op.effect, BinaryOp.eval, Function.update]
+
+open private replay_exec count_append from OAI.Computability.VPVNP.PairTraversalRowExecution
+
+private theorem worker_exec (pub : Fin 6 → Word w) (i : Word w) (mem : Memory w)
+ (src nodeAddr count : ℕ) (hs : source pub i = (src : Word w))
+ (hn : node pub i = (nodeAddr : Word w)) (hc : (mem (counter pub i).val).val = count)
+ (before : src + count ≤ nodeAddr) (fit : nodeAddr + 2 + count < 2 ^ w)
+ (input : Regs w 7 := fun _ => 0) :
+ let image := DescriptorRows.rowMemory src (nodeAddr + 2) count (pub 3) (pub 5)
+ (headerMemory pub i mem)
+ ∃ es out, Flow.Exec pub i program input mem es out image ∧ out 6 = i + 1 ∧
+ countProbes es = 2 * count + 3 ∧ es.length = 7 * count + 24 ∧ choiceBits es = [] := by
+ intro image
+ obtain ⟨ss, rs, setup, h0, h1, h2, h3, h4, h5, sp, sl, sb⟩ := setup_exec pub i mem input
+ have countWord : mem (counter pub i).val = (count : Word w) := by
+ apply Fin.ext
+ exact hc.trans (Nat.mod_eq_of_lt (by omega)).symm
+ have stop : rs 1 = ((src + count : ℕ) : Word w) := by rw [h1, hs, countWord, Nat.cast_add]
+ have dst : rs 2 = ((nodeAddr + 2 : ℕ) : Word w) := by rw [h2, hn, Nat.cast_add, Nat.cast_ofNat]
+ obtain ⟨ts, last, loop, probes, steps, bits⟩ := DescriptorRows.scan_exec
+ (pub ∘ Fin.elim0) i rs (headerMemory pub i mem) src (nodeAddr + 2) count (pub 3) (pub 5)
+ (h0.trans hs) stop dst h3 h4 h5 fit (by omega)
+ obtain ⟨afterScan, lifted, _, _⟩ :=
+ liftExec (Function.Embedding.refl (Fin 7)) Fin.elim0 pub loop rs rfl
+ obtain ⟨out, advance, ret⟩ := finish_exec pub i image afterScan
+ let fs : List (Event w) := [.tick, .tick, .tick]
+ refine ⟨ss ++ (ts ++ fs), out, setup.seq (lifted.seq advance), ret, ?_, ?_, ?_⟩
+ · rw [count_append, count_append, sp, probes]
+ change 3 + (2 * count + 0) = _
+ omega
+ · simp only [List.length_append, sl, steps, fs, List.length_cons, List.length_nil]
+ omega
+ · simp only [Flow.choiceBits_append, sb, bits, List.nil_append]
+ rfl
+
+/-- One native call computes every address from the current site and its six
+layout words. It costs two probes per identifier and three for the header. -/
+theorem native (pub : Fin 6 → Word w) (i : Word w) (mem : Memory w)
+ (src nodeAddr count fuel : ℕ) (hs : source pub i = (src : Word w))
+ (hn : node pub i = (nodeAddr : Word w)) (hc : (mem (counter pub i).val).val = count)
+ (before : src + count ≤ nodeAddr) (fit : nodeAddr + 2 + count < 2 ^ w)
+ (clock : 7 * count + 24 < fuel) :
+ let M := (program.template (some 6)).instantiate w pub
+ ∃ es, execute M.program fuel (M.program.start i) mem [] = some ⟨es, some (i + 1)⟩ ∧
+ after mem es = DescriptorRows.passMemory mem nodeAddr src (nodeAddr + 2)
+ (counter pub i) (pub 3) (pub 5) count ∧
+ countProbes es = 2 * count + 3 ∧ es.length = 7 * count + 24 := by
+ obtain ⟨es, out, run, ret, probes, steps, bits⟩ :=
+ worker_exec pub i mem src nodeAddr count hs hn hc before fit
+ refine ⟨es, ?_, ?_, probes, steps⟩
+ · apply (Flow.template_execute_iff program (some 6) pub i (fun _ => 0) (fun _ => 0) mem
+ fuel [] _).mpr
+ exact ⟨out, _, run, by simp only [Option.map_some, ret], steps.trans_lt clock, bits⟩
+ · rw [replay_exec run]
+ simpa only [headerMemory, hn, Nat.cast_add, Nat.cast_ofNat, Nat.cast_one] using
+ DescriptorRows.headers_then_scan mem nodeAddr src (counter pub i) (pub 3) (pub 5) count
+ before fit
+
+end PairSimulation.TraversalRows.SiteWorker
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalStageSize.lean b/lean/OAI/Computability/VPVNP/PairTraversalStageSize.lean
new file mode 100644
index 0000000000..e5e178142a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalStageSize.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.PairTraversalSelectedOrder
+import OAI.Computability.VPVNP.CompressorLevelCounts
+
+/-!
+# Descriptor storage along the compression schedule
+
+The descriptor arena begins with the cursor input sites, followed by one row
+for every output site of every selected elementary pass. The selected pass
+origins identify those counts with the actual shrink and refresh outputs.
+Neither pass increases the number of sites.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open NetworkKernel LocalHistory Compression CompressorRecords
+
+variable {A : Type*} [CommRing A] {Label : Type} [Fintype Label] {κ : Label → A}
+
+open Classical in
+private noncomputable def placementLayer {N : Network} (t : Term A N) (old : Order N.Site)
+ (next : Order t.output.Site) : Layer :=
+ ⟨next.length, fun i =>
+ let children := old.restrict (fun u => next.entries i = t.place u)
+ List.ofFn fun j => (old.entries.symm (children.entries j).val).val⟩
+
+private noncomputable def placementLayers {N Y : Network} (c : TermChain A N Y)
+ (orders : ChainOrders c) (initial : Order N.Site) : List Layer :=
+ match c with
+ | .done _ => []
+ | .more t _ tail => placementLayer t initial orders.1 :: placementLayers tail orders.2 orders.1
+
+private theorem stepLayers_ordered {N Y : Network} (c : TermChain A N Y) (r : ChainParsers κ c)
+ (orders : ChainOrders c) (initial : Order N.Site) (h : OrderedChildren c r orders initial) :
+ stepLayers c r orders initial = placementLayers c orders initial := by
+ induction c with
+ | done => rfl
+ | more t data tail ih =>
+ refine congrArg₂ List.cons ?_ (ih r.2 orders.2 orders.1 h.2)
+ unfold stepLayer placementLayer
+ congr 1
+ funext i
+ let v := orders.1.entries i
+ exact congrArg (fun (s : Order (t.Preimage v)) =>
+ List.ofFn fun j => (initial.entries.symm (s.entries j).val).val) (h.1 v)
+
+open private castOrders from OAI.Computability.VPVNP.PairTraversalSelectedOrder
+open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels
+
+omit [CommRing A] in
+private theorem cast_placementLayers {N M Y : Network} (e : N = M) (c : TermChain A M Y)
+ (orders : ChainOrders c) (initial : Order M.Site) :
+ placementLayers (e.symm ▸ c : TermChain A N Y) (castOrders e c orders) (e.symm ▸ initial) =
+ placementLayers c orders initial := by cases e; rfl
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+variable (f : B.Entry → A) (hf : B.IsSolution f)
+
+/-- Read the actual placement of this scheduled term in increasing old-site
+order for each output position. -/
+noncomputable def levelLayer (v : SelectedLevel B f hf) : Layer :=
+ placementLayer (v.pass.step.term v.term) (siteOrder v.input)
+ ((v.pass.output_eq v.term).symm ▸ siteOrder (v.pass.next v.term))
+
+theorem levelLayer_count (v : SelectedLevel B f hf) :
+ (levelLayer B f hf v).count = v.outputSites := by
+ change ((v.pass.output_eq v.term).symm ▸ siteOrder (v.pass.next v.term) :
+ Order (v.pass.step.term v.term).output.Site).length = v.outputSites
+ have h {N M : Network} (e : N = M) (s : Order M.Site) :
+ (e.symm ▸ s : Order N.Site).length = s.length := by cases e; rfl
+ rw [h (v.pass.output_eq v.term)]
+ change (siteOrder (v.pass.next v.term)).length = Fintype.card (v.pass.next v.term).network.Site
+ simpa only [Fintype.card_fin] using Fintype.card_congr (siteOrder (v.pass.next v.term)).entries
+
+private theorem collect_placementLayers {a g b n : ℕ} {X : State a g} (E : StateExecution A b n X)
+ (W : E.MapWitnesses f) (r : ExecutionReaders E W) (o : PassOrigins B f hf E)
+ (data : E.Records) (z : E.Choices) :
+ placementLayers (E.termChain data z) (branchOrders E data z) (siteOrder X) =
+ (collectLevels B f hf E W r o z).map (levelLayer B f hf) := by
+ induction E with
+ | done => rfl
+ | more p tail ih =>
+ let c := (tail z.1).termChain (data.2 z.1) z.2
+ let orders := branchOrders (tail z.1) (data.2 z.1) z.2
+ let next := siteOrder (p.next z.1)
+ let e := p.output_eq z.1
+ refine congrArg₂ List.cons rfl ?_
+ exact (cast_placementLayers e c orders next).trans
+ (ih z.1 (W.2 z.1) (r.2 z.1) (o.2 z.1) (data.2 z.1) z.2)
+
+variable {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+variable (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+
+/-- Every row and every child identifier, in scan order, is determined by
+the corresponding concrete level of the compressor. -/
+theorem selectedLayers_eq_levels :
+ selectedLayers B f hf T hT X z =
+ leafLayer (siteOrder X) :: (executeLevels B f hf T hT X z).map (levelLayer B f hf) := by
+ apply congrArg (List.cons (leafLayer (siteOrder X)))
+ exact (stepLayers_ordered _ _ _ _ (selectedParsers_ordered B f hf T hT X z)).trans
+ (collect_placementLayers B f hf _ _ _ _ _ _)
+
+/-- The count in each actual layer agrees with the selected state's site count. -/
+theorem selected_layer_counts :
+ (selectedLayers B f hf T hT X z).map Layer.count =
+ X.positions :: (executeLevels B f hf T hT X z).map SelectedLevel.outputSites := by
+ simp only [selectedLayers_eq_levels, List.map_cons, leafLayer, List.map_map, Function.comp_def,
+ levelLayer_count]
+ congr 1
+ change (siteOrder X).length = Fintype.card X.network.Site
+ simpa only [Fintype.card_fin] using Fintype.card_congr (siteOrder X).entries
+
+/-- Every layer, including the initial leaves and the intermediate shrink
+and refresh layers, has at most as many sites as the input. -/
+theorem selected_layer_count_le (L : Layer) (hL : L ∈ selectedLayers B f hf T hT X z) :
+ L.count ≤ X.positions := by
+ have hm := List.mem_map_of_mem (f := Layer.count) hL
+ rw [selected_layer_counts] at hm
+ rcases List.mem_cons.mp hm with h | h
+ · exact h.le
+ · obtain ⟨v, hv, he⟩ := List.mem_map.mp h
+ exact he ▸ v.outputSites_le.trans (executeLevels_limits B f hf T hT X z v hv).1
+
+/-- The leaf stage and at most one stage per elementary compression pass
+bound the total number of rows reserved by Appendix E. -/
+theorem selected_count_sum_le :
+ ((selectedLayers B f hf T hT X z).map Layer.count).sum ≤
+ ((S.steps + 1) * T + 1) * X.positions := by
+ let sizes := (selectedLayers B f hf T hT X z).map Layer.count
+ have hc : ∀ n ∈ sizes, n ≤ X.positions := by
+ intro n hn
+ obtain ⟨L, hL, rfl⟩ := List.mem_map.mp hn
+ exact selected_layer_count_le B f hf T hT X z L hL
+ have hl : sizes.length ≤ (S.steps + 1) * T + 1 := by
+ simp only [sizes, selected_layer_counts, List.length_cons, List.length_map]
+ exact Nat.succ_le_succ (executeLevels_length B f hf T hT X z)
+ exact (List.sum_le_length_nsmul sizes X.positions hc).trans (Nat.mul_le_mul_right _ hl)
+
+/-- The number of words in the selected native descriptor arena, with its
+two header words and fixed child-list capacity per row. -/
+theorem selected_words_le_stages :
+ words B.recordLimit (selectedLayers B f hf T hT X z) ≤
+ (B.recordLimit + 2) * ((S.steps + 1) * T + 1) * X.positions := by
+ rw [Nat.mul_assoc]
+ exact Nat.mul_le_mul_left _ (selected_count_sum_le B f hf T hT X z)
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalTerminalBootstrap.lean b/lean/OAI/Computability/VPVNP/PairTraversalTerminalBootstrap.lean
new file mode 100644
index 0000000000..544e4e5786
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalTerminalBootstrap.lean
@@ -0,0 +1,242 @@
+import OAI.Computability.VPVNP.CompressorHistoryArenaBase
+import OAI.Computability.VPVNP.CompressorDescriptorTableFits
+
+/-!
+# Terminal pair bootstrap after the descriptor calendar
+
+The first and last stored traversal-row bases give the exact accumulated row size.
+A single fixed eleven-operand burst reads the persistent level headers and the last
+auxiliary descriptor, initializes the terminal header and leaves every other cell intact.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalBootstrap
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords DescriptorSpace PhaseRecipe RowRecipe
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Workspace base, grammar counter base, address width, auxiliary shadow and grammar length. -/
+def operand : Fin 5 → Fin 11 := ![2,4,7,3,5]
+
+private def workspace : Expr := .publicWord 0
+private def cell (base : Expr) (j : ℕ) : Expr := .load (base.add (.lit j))
+private def first (F : Shape) := DescriptorParameters.firstLevel F.arity
+private def pitch (F : Shape) := cell workspace (10+F.arity)
+private def levels (F : Shape) := cell (first F) 28
+private def lastLevel (F : Shape) := (first F).add (((levels F).sub (.lit 1)).mul (pitch F))
+private def radix := Expr.binary .shiftLeft (.lit 1) (.publicWord 2)
+private def high := (workspace.add (radix.mul radix)).sub (.lit 32)
+
+/-- The histogram begins after all reserved auxiliary fields, including both padded exterior cuts. -/
+def shadowSpan {w : ℕ} (pub : Fin 11 → Word w) (m : Memory w) : Word w := m (pub 4-1).val - pub 3 + pub 5
+private def spanExpr := (((Expr.load ((.publicWord 1 : Expr).sub (.lit 1))).sub (.publicWord 3)).add (.publicWord 4))
+
+/-- The terminal bootstrap header begins 32 words before the end of the square workspace of
+radix two to the address exponent. -/
+def address (base r : ℕ) := base + 2^r*2^r - 32
+
+/-- Initialize all twenty-one public terminal header fields. The phase and both counters
+start at zero. The final-width pass subsequently supplies the total and role offset. -/
+def calculation (F : Shape) (cap : ℕ) : FormulaRow 18 :=
+ let head := lastLevel F
+ let arena := cell (first F) 14
+ let finalRows := cell head 14
+ let sites := (cell head 0).mul (cell head 2)
+ let slots := sites.mul (cell head 1)
+ let step : Expr := .lit (cap+2)
+ let words := (finalRows.sub arena).add (sites.mul step)
+ ⟨high, ![.lit 0, levels F, .lit 0, arena, arena, words, finalRows, sites, slots,
+ cell head (F.scalarFields+5), cell head (F.scalarFields+4), cell head (F.scalarFields+6), .lit 0,
+ arena.add words, .lit 0, step, first F, pitch F, cell (first F) 10, cell (first F) 11, spanExpr]⟩
+
+/-- The fixed table has no dependence on the input size or the selected compression branch. -/
+def table (F : Shape) (cap : ℕ) := LiveStageLink.widen (calculation F cap).recipe.acceptTable
+ (Function.Embedding.refl _) operand
+
+/-- Native instruction cost of the terminal bootstrap's compiled header calculation at the
+chosen descriptor shape and record capacity. -/
+def cost (F : Shape) (cap : ℕ) := (calculation F cap).recipe.code.length
+
+/-- The bootstrap worker's report contains the calculation's external events and closes without
+a successor state. -/
+def report (F : Shape) (cap : ℕ) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) : Report w :=
+ ⟨((calculation F cap).recipe.report (pub ∘ operand) s m).events,none⟩
+
+/-- The table accepts exactly the empty choice string, from every incoming persistent state. -/
+theorem execute_table (F : Shape) (cap : ℕ) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w)
+ (bits : List Bool) (fuel : ℕ) (budget : cost F cap < fuel) :
+ let M := (table F cap).instantiate w pub
+ execute M.program fuel (M.program.start s) m bits =
+ if bits = [] then some (report F cap pub s m) else none :=
+ (LiveStageLink.execute_widen_start ..).trans (execute_accept (calculation F cap).recipe (pub ∘ operand) s m bits fuel budget)
+
+/-- Stored values needed at the calendar's terminal exit. `priorWords` counts all
+traversal rows strictly before the final level, with their fixed row stride. -/
+structure Header (L : Layout) (last : ℕ) where
+ /-- Total words occupied by all DFS row layers before the final layer. -/
+ priorWords : ℕ
+ /-- Number of final base vertices before expanding their lane assignments. -/
+ vertices : ℕ
+ /-- Number of lane assignments per final base vertex. -/
+ lanes : ℕ
+ /-- Number of numbered final outgoing slots per site. -/
+ degree : ℕ
+ /-- Head of the final outgoing arc-width column used by the terminal prefix scan. -/
+ widthHead : ℕ
+ /-- Head of the inverse incidence column used to gather the incoming final half-wires. -/
+ incomingHead : ℕ
+ /-- Base address of the terminal prefix array used to locate each final arc's shared bits. -/
+ prefixBase : ℕ
+ /-- Saved initial base radix used by the terminal cursor-leaf decoder. -/
+ baseRadix : ℕ
+ /-- Saved initial lane radix used by the terminal cursor-leaf decoder. -/
+ laneRadix : ℕ
+
+/-- Read the external cell at a natural base and offset after conversion to the runtime word
+address. -/
+def atCell (m : Memory w) (head offset : ℕ) := m (((head+offset : ℕ) : Word w).val)
+
+/-- The physical workspace, level geometry, row counts, final incidence heads, and saved
+radices have the values required by terminal bootstrap. -/
+structure Ready (L : Layout) (last : ℕ) (A : Header L last) (pub : Fin 11 → Word w) (m : Memory w) : Prop where
+ workspace : (pub 2).val = L.base
+ rows : m (pub 2+8).val = (directoryRows L : Word w)
+ pitch : m (pub 2+((10+L.shape.arity : ℕ) : Word w)).val = (levelWords L : Word w)
+ levels : atCell m (levelStart L 0) 28 = ((last+1 : ℕ) : Word w)
+ firstBase : atCell m (levelStart L 0) 14 = (endAddress L : Word w)
+ lastBase : atCell m (levelStart L last) 14 = ((endAddress L+A.priorWords : ℕ) : Word w)
+ vertices : atCell m (levelStart L last) 0 = (A.vertices : Word w)
+ lanes : atCell m (levelStart L last) 2 = (A.lanes : Word w)
+ degree : atCell m (levelStart L last) 1 = (A.degree : Word w)
+ widthHead : atCell m (levelStart L last) (L.shape.scalarFields+5) = (A.widthHead : Word w)
+ incomingHead : atCell m (levelStart L last) (L.shape.scalarFields+4) = (A.incomingHead : Word w)
+ prefixBase : atCell m (levelStart L last) (L.shape.scalarFields+6) = (A.prefixBase : Word w)
+ baseRadix : atCell m (levelStart L 0) 10 = (A.baseRadix : Word w)
+ laneRadix : atCell m (levelStart L 0) 11 = (A.laneRadix : Word w)
+
+private theorem word_eq {x : Word w} {n : ℕ} (h : x.val = n) : x = (n : Word w) := by
+ apply Fin.ext
+ exact h.trans (Nat.mod_eq_of_lt (h ▸ x.isLt)).symm
+
+variable (L : Layout) (last : ℕ) (A : Header L last) (cap : ℕ) (pub : Fin 11 → Word w) (m : Memory w)
+
+/-- Total number of final sites, including every combination of base vertex and remaining lane
+assignment. -/
+def Header.sites {L last} (A : Header L last) := A.vertices*A.lanes
+/-- Total words reserved for DFS rows, including the final sites at their capacity-plus-two
+word pitch. -/
+def Header.rowWords {L last} (A : Header L last) (cap : ℕ) := A.priorWords + A.sites*(cap+2)
+
+/-- The 21 terminal bootstrap header words computed from the descriptor layout, selected final
+state, row geometry, and public shadow data. -/
+def values : Fin 21 → Word w :=
+ ![0,((last+1 : ℕ) : Word w),0,(endAddress L : Word w),(endAddress L : Word w),(A.rowWords cap : Word w),
+ ((endAddress L+A.priorWords : ℕ) : Word w),(A.sites : Word w),((A.sites*A.degree : ℕ) : Word w),
+ (A.widthHead : Word w),(A.incomingHead : Word w),(A.prefixBase : Word w),0,
+ ((endAddress L+A.rowWords cap : ℕ) : Word w),0,((cap+2 : ℕ) : Word w),(levelStart L 0 : Word w),
+ (levelWords L : Word w),(A.baseRadix : Word w),(A.laneRadix : Word w),shadowSpan pub m]
+
+private theorem eval_high (hbase : (pub 2).val = L.base) (s : Word w) (hw : 0 < w) (r : ℕ)
+ (hr : (pub 7).val = r) (hrw : r < w) (h32 : 32 ≤ L.base+2^r*2^r) :
+ high.eval (pub ∘ operand) s m = (address L.base r : Word w) := by
+ have one : (1 : Word w).val = 1 := Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')
+ have pow : radix.eval (pub ∘ operand) s m = ((2^r : ℕ) : Word w) := by
+ change (if (pub 7).val < w then Fin.ofNat _ ((1 : Word w).val <<< (pub 7).val) else 0) = _
+ rw [hr,ite_eq_left hrw,one,Nat.shiftLeft_eq,Nat.one_mul]
+ rfl
+ change pub 2 + radix.eval (pub ∘ operand) s m * radix.eval (pub ∘ operand) s m - 32 = _
+ rw [pow,word_eq hbase,address,Nat.cast_sub h32,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat]
+
+set_option maxRecDepth 4096 in
+private theorem eval_values (s : Word w) (h : Ready L last A pub m) (i : Fin 21) :
+ ((calculation L.shape cap).fields i).eval (pub ∘ operand) s m = values L last A cap pub m i := by
+ let p := pub ∘ operand
+ have head : (first L.shape).eval p s m = (levelStart L 0 : Word w) := by
+ change pub 2 + ((11+L.shape.arity : ℕ) : Word w) + m (pub 2+8).val * ((L.shape.arity+3 : ℕ) : Word w) = _
+ rw [h.rows,word_eq h.workspace]
+ simp only [levelStart, Nat.zero_mul, Nat.add_zero, levelsBase, directoryBase, plannerTag, frameBase,
+ Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, Nat.cast_one]
+ ring
+ have read {e : Expr} {x : ℕ} (eqn : e.eval p s m = (x : Word w)) (j : ℕ) :
+ (cell e j).eval p s m = atCell m x j := by
+ change m (e.eval p s m+(j : Word w)).val = m (((x+j : ℕ) : Word w).val)
+ rw [eqn,Nat.cast_add]
+ have len : (levels L.shape).eval p s m = ((last+1 : ℕ) : Word w) := (read head 28).trans h.levels
+ have pt : (pitch L.shape).eval p s m = (levelWords L : Word w) := h.pitch
+ have finalHead : (lastLevel L.shape).eval p s m = (levelStart L last : Word w) := by
+ change (first L.shape).eval p s m + ((levels L.shape).eval p s m-1)*(pitch L.shape).eval p s m = _
+ rw [head,len,pt,Nat.cast_add_one,add_sub_cancel_right]
+ simp only [levelStart,Nat.zero_mul,Nat.add_zero,Nat.cast_add,Nat.cast_mul]
+ have rv := (read finalHead 0).trans h.vertices
+ have rl := (read finalHead 2).trans h.lanes
+ have rd := (read finalHead 1).trans h.degree
+ have rb := (read head 14).trans h.firstBase
+ have re := (read finalHead 14).trans h.lastBase
+ have sites : ((cell (lastLevel L.shape) 0).mul (cell (lastLevel L.shape) 2)).eval p s m = (A.sites : Word w) := by
+ change (cell (lastLevel L.shape) 0).eval p s m * (cell (lastLevel L.shape) 2).eval p s m = _
+ rw [rv,rl,Header.sites,Nat.cast_mul]
+ have size : (((cell (lastLevel L.shape) 14).sub (cell (first L.shape) 14)).add
+ (((cell (lastLevel L.shape) 0).mul (cell (lastLevel L.shape) 2)).mul (.lit (cap+2)))).eval p s m =
+ (A.rowWords cap : Word w) := by
+ change (cell (lastLevel L.shape) 14).eval p s m - (cell (first L.shape) 14).eval p s m +
+ ((cell (lastLevel L.shape) 0).mul (cell (lastLevel L.shape) 2)).eval p s m * ((cap+2 : ℕ) : Word w) = _
+ simp only [re,rb,sites,Header.rowWords,Nat.cast_add,Nat.cast_mul]; ring
+ fin_cases i
+ · rfl
+ · exact len
+ · rfl
+ · exact rb
+ · exact rb
+ · exact size
+ · exact re
+ · exact sites
+ · change ((cell (lastLevel L.shape) 0).mul (cell (lastLevel L.shape) 2)).eval p s m * (cell (lastLevel L.shape) 1).eval p s m = ((A.sites*A.degree : ℕ) : Word w)
+ rw [sites,rd,Nat.cast_mul]
+ · exact (read finalHead _).trans h.widthHead
+ · exact (read finalHead _).trans h.incomingHead
+ · exact (read finalHead _).trans h.prefixBase
+ · rfl
+ · change (cell (first L.shape) 14).eval p s m + _ = ((endAddress L+A.rowWords cap : ℕ) : Word w)
+ rw [rb,size,Nat.cast_add]
+ · rfl
+ · rfl
+ · exact head
+ · exact pt
+ · exact (read head _).trans h.baseRadix
+ · exact (read head _).trans h.laneRadix
+ · rfl
+
+/-- The one-shot native table is ready for a terminal phase linker. It performs a fixed
+number of probes and ticks and does not use a choice bit. -/
+theorem native (s : Word w) (h : Ready L last A pub m) (r : ℕ) (hr : (pub 7).val = r)
+ (hrw : r < w) (h32 : 32 ≤ L.base+2^r*2^r) (room : L.base+2^r*2^r ≤ 2^w) :
+ let M := (table L.shape cap).instantiate w pub
+ let rep := report L.shape cap pub s m
+ execute M.program (cost L.shape cap+1) (M.program.start s) m [] = some rep ∧ rep.result = none ∧
+ (∀ i : Fin 21, after m rep.events (address L.base r+i.val) = values L last A cap pub m i) ∧
+ (∀ x, x < address L.base r ∨ address L.base r+21 ≤ x → after m rep.events x = m x) ∧
+ rep.events.length = cost L.shape cap ∧ rep.probes = (calculation L.shape cap).recipe.reads+21 ∧
+ choiceBits rep.events = [] := by
+ intro M rep
+ let R := calculation L.shape cap
+ have hi : address L.base r+21 ≤ 2^w := by dsimp [address]; omega
+ have hd : (R.dest.eval (pub ∘ operand) s m).val = address L.base r := by
+ rw [show R.dest.eval (pub ∘ operand) s m = (address L.base r : Word w) from
+ eval_high L pub m h.workspace s (by omega) r hr hrw h32,Fin.val_natCast,Nat.mod_eq_of_lt (by omega)]
+ obtain ⟨_,_,store,keep,work⟩ := R.execute (pub ∘ operand) s m (hd ▸ hi)
+ refine ⟨execute_table L.shape cap pub s m [] _ (Nat.lt_succ_self _),rfl,?_,?_,work⟩
+ · intro i
+ exact (hd ▸ store i).trans (eval_values L last A cap pub m s h i)
+ · intro x hx
+ exact keep x (hd ▸ hx)
+
+end PairSimulation.TerminalBootstrap
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalTraffic.lean b/lean/OAI/Computability/VPVNP/PairTraversalTraffic.lean
new file mode 100644
index 0000000000..d3d87521d3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalTraffic.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PairSimulationEndpointBits
+import OAI.Computability.VPVNP.PairSimulationCounters
+import OAI.Computability.VPVNP.CursorBranchCommunication
+
+/-!
+# Native traffic for the shared bits and final history visits
+
+The final-arc writer, the two incidence readers, the DFS control code,
+and the component-counter updates have concrete reports. Their costs
+are compared here with the same selected branch used in the energy
+estimate. A descriptor address and an empty field each retain their
+own native loop tests.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open BurstRAM BurstRAM.PrivateRAM Compression NetworkKernel CursorNetwork
+
+variable {a g w : ℕ}
+
+/-- All final incidence read events of one vertex, in outgoing then
+incoming slot order. -/
+def incidenceEvents (Y : State a g) (v : Y.network.Site) (mem : Memory w)
+ (src : Bool → Fin (2 ^ a) → ℕ) : List (Event w) :=
+ (List.ofFn fun j => EndpointBits.events mem (src false j) (Y.halfWidth v false j)).flatten ++
+ (List.ofFn fun j => EndpointBits.events mem (src true j) (Y.halfWidth v true j)).flatten
+
+private theorem append_probes (xs ys : List (Event w)) :
+ countProbes (xs ++ ys) = countProbes xs + countProbes ys := by
+ induction xs with
+ | nil => simp [countProbes]
+ | cons x xs ih => cases x <;> simp [countProbes, ih, Nat.add_comm, Nat.add_left_comm]
+
+private theorem ofFn_probes {n : ℕ} (f : Fin n → List (Event w)) :
+ countProbes (List.ofFn f).flatten = ∑ i, countProbes (f i) := by
+ induction n with
+ | zero => simp [countProbes]
+ | succ n ih => rw [List.ofFn_succ, List.flatten_cons, append_probes, Fin.sum_univ_succ, ih]
+
+theorem incidenceEvents_probes (Y : State a g) (v : Y.network.Site) (mem : Memory w)
+ (src : Bool → Fin (2 ^ a) → ℕ) :
+ countProbes (incidenceEvents Y v mem src) = CursorNetwork.incidentBits Y v := by
+ simp only [incidenceEvents, append_probes, ofFn_probes, EndpointBits.probes,
+ CursorNetwork.incidentBits, Fintype.sum_bool]
+ omega
+
+theorem incidenceEvents_length (Y : State a g) (v : Y.network.Site) (mem : Memory w)
+ (src : Bool → Fin (2 ^ a) → ℕ) :
+ (incidenceEvents Y v mem src).length = 5 * CursorNetwork.incidentBits Y v + 2 * 2 ^ a := by
+ have len (s n : ℕ) : (EndpointBits.events mem s n).length = 5*n+1 := by
+ induction n generalizing s with
+ | zero => rfl
+ | succ n ih => simp [EndpointBits.events, ih]; omega
+ simp only [incidenceEvents, List.length_append, List.length_flatten, List.map_ofFn, List.sum_ofFn,
+ Function.comp_def, len, Finset.sum_add_distrib, ← Finset.mul_sum, Finset.sum_const,
+ Finset.card_univ, Fintype.card_fin, nsmul_eq_mul, mul_one,
+ CursorNetwork.incidentBits, Fintype.sum_bool]
+ norm_cast
+ ring
+
+/-- Native logs of the endpoint reads, ordered DFS control and fixed
+componentwise flush. Other private computations occur at the DFS hook. -/
+def finalControlEvents (Y : State a g) (v : Y.network.Site) (m : Memory w)
+ (src : Bool → Fin (2 ^ a) → ℕ) (dfsLog : List (Event w))
+ (priv : Word w → Word w) (privateBase counterBase labels : ℕ) : List (Event w) :=
+ incidenceEvents Y v m src ++ dfsLog ++ Counters.events priv m privateBase counterBase labels
+
+theorem finalControlEvents_cost (Y : State a g) (v : Y.network.Site) (m : Memory w)
+ (src : Bool → Fin (2 ^ a) → ℕ) (dfsLog : List (Event w))
+ (priv : Word w → Word w) (privateBase counterBase labels : ℕ) :
+ let es := finalControlEvents Y v m src dfsLog priv privateBase counterBase labels
+ countProbes es = CursorNetwork.incidentBits Y v + countProbes dfsLog + 2 * labels ∧
+ es.length =
+ 5 * CursorNetwork.incidentBits Y v + 2 * 2 ^ a + dfsLog.length + 7 * labels + 1 := by
+ simp only [finalControlEvents, append_probes, incidenceEvents_probes, List.length_append,
+ incidenceEvents_length, (Counters.events_cost priv m privateBase counterBase labels).1,
+ (Counters.events_cost priv m privateBase counterBase labels).2.1, Nat.add_assoc, and_self]
+
+/-- Count the startup of each final burst, its actual control log, and
+every binary write in the genuine final-bit writer's reports. -/
+theorem finalControl_cost_le {A : Type*} {a₀ g₀ : ℕ}
+ (X : State a₀ g₀) (Y : State a g) (chain : TermChain A X.network Y.network)
+ (n labels : ℕ) (m : Memory w) (src : Y.network.Site → Bool → Fin (2 ^ a) → ℕ)
+ (logs : Y.network.Site → List (Event w))
+ (hdfs : ∀ v, countProbes (logs v) ≤ 3 * chain.occurrences (fun _ => 1) v)
+ (priv : Y.network.Site → Word w → Word w) (privateBase counterBase low : ℕ)
+ (bits : Fin Y.totalWidth → Bool) :
+ let C := 2 * labels + 4
+ let charge v := 1 + countProbes
+ (finalControlEvents Y v m (src v) (logs v) (priv v) privateBase counterBase labels)
+ (∀ v, charge v ≤ siteAccesses Y chain C 0 n v) ∧
+ RAMBuckets.cost Report.probes (FinalBits.reports w low bits) + ∑ v, charge v ≤
+ branchAccesses X Y chain C 0 n := by
+ intro C charge
+ have hc v : charge v ≤ siteAccesses Y chain C 0 n v := by
+ dsimp only [charge, C, siteAccesses, pow_zero, Nat.mul_one]
+ rw [(finalControlEvents_cost ..).1]
+ have h := hdfs v
+ nlinarith only [h, Nat.zero_le (CursorNetwork.incidentBits Y v),
+ Nat.zero_le (labels * CursorNetwork.incidentBits Y v),
+ Nat.zero_le (labels * chain.occurrences (fun _ => 1) v)]
+ refine ⟨hc, ?_⟩
+ rw [(FinalBits.scan_cost low Y.totalWidth bits).2]
+ apply Nat.add_le_add _ (Finset.sum_le_sum fun v _ => hc v)
+ simp only [pow_zero, Nat.mul_one]
+ dsimp [C]
+ nlinarith only [Nat.zero_le (labels * X.positions), Nat.zero_le (labels * Y.totalWidth)]
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTraversalWorkerMemory.lean b/lean/OAI/Computability/VPVNP/PairTraversalWorkerMemory.lean
new file mode 100644
index 0000000000..a129152176
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTraversalWorkerMemory.lean
@@ -0,0 +1,44 @@
+import OAI.Computability.VPVNP.PairTraversalRowExecution
+
+/-!
+# Publishing a descriptor header before the identifier scan
+
+The site's source identifiers lie below the header, and the translated row
+starts immediately after the two header words. Thus the header writes and
+the scan can be interchanged, even if the count was read from a header word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.DescriptorRows
+
+open BurstRAM
+open scoped Fin.CommRing
+
+/-- Writing the two saved header values first gives the same complete external
+memory as publishing them after the scan. -/
+theorem headers_then_scan {w : ℕ} (m : Memory w) (node src : ℕ)
+ (countCell base stride : Word w) (count : ℕ)
+ (sourceBefore : src + count ≤ node) (fit : node + 2 + count < 2 ^ w) :
+ rowMemory src (node + 2) count base stride
+ (writeMemory (writeMemory m (node : Word w) ((node + 2 : ℕ) : Word w))
+ ((node + 1 : ℕ) : Word w) (m countCell.val)) =
+ passMemory m node src (node + 2) countCell base stride count := by
+ have nodeVal : (node : Word w).val = node := Nat.mod_eq_of_lt (by omega)
+ have nextVal : ((node + 1 : ℕ) : Word w).val = node + 1 := Nat.mod_eq_of_lt (by omega)
+ funext i
+ simp only [passMemory, rowMemory, writeMemory, nodeVal, nextVal]
+ by_cases inside : node + 2 ≤ i ∧ i < node + 2 + count
+ · have source : src + (i - (node + 2)) < node := by omega
+ simp only [ite_eq_left inside, ite_eq_right (by omega : i ≠ node),
+ ite_eq_right (by omega : i ≠ node + 1), ite_eq_right source.ne,
+ ite_eq_right (by omega : src + (i - (node + 2)) ≠ node + 1)]
+ · simp only [ite_eq_right inside]
+
+end PairSimulation.DescriptorRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTreeDecodeDomain.lean b/lean/OAI/Computability/VPVNP/PairTreeDecodeDomain.lean
new file mode 100644
index 0000000000..c6725f056b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTreeDecodeDomain.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.PairTreeNodeReaders
+
+/-! # Reachability of every role visit on arbitrary private streams -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NetworkKernel CompressorRecords LocalHistory NodeArguments
+open scoped Fin.CommRing
+open private addTree from OAI.Computability.VPVNP.PairTraversalHistory
+open private push_subtrees from OAI.Computability.VPVNP.PairTreeDecoder
+
+variable {W endAddr : ℕ} (hook : HookParser W endAddr)
+ (valid : List Packet → Scratch W endAddr → Prop)
+ (domain : Word W → Scratch W endAddr → Prop)
+
+/-- A failing visit can stop the stream in the middle of any one child.
+The later siblings need to be prepared only after that entire child succeeds. -/
+private theorem valid_append (xs ys : List (Word W)) (s : Scratch W endAddr) (bits : List Bool)
+ (first : hook.ValidAlong domain xs s bits)
+ (later : ∀ mid tail, hook.decode xs s bits = some (mid,tail) → hook.ValidAlong domain ys mid tail) :
+ hook.ValidAlong domain (xs++ys) s bits := by
+ induction xs generalizing s bits with
+ | nil => exact later s bits rfl
+ | cons node ns ih =>
+ refine ⟨first.1,?_⟩
+ intro job more hit
+ exact ih (job.update s) more (first.2 job more hit) (fun mid tail run =>
+ later mid tail (by simp only [HookParser.decode,hit]; exact run))
+
+/-- The decoder remains in its admitted domain at every node of this block when the block's
+argument packets precede the pending suffix. -/
+def AlongBlock (args : List Packet) (nodes : List (Word W)) : Prop :=
+ ∀ pending s bits, valid (args++pending) s → hook.ValidAlong domain nodes s bits
+
+private theorem forest_along (n : ℕ) (α : Fin n → Type) (packet : Fin n → Packet)
+ (nodes : Fin n → List (Word W)) (code : ∀ i, α i → List Bool)
+ (child : ∀ i, ExactBlock hook valid [packet i] (nodes i) (code i))
+ (along : ∀ i, AlongBlock hook valid domain [packet i] (nodes i)) :
+ AlongBlock hook valid domain (List.ofFn packet) (List.ofFn nodes).flatten := by
+ induction n with
+ | zero =>
+ intro _ _ _ _
+ simp [HookParser.ValidAlong]
+ | succ n ih =>
+ intro pending s bits prepared
+ let rest := List.ofFn (fun i : Fin n => packet i.succ)
+ let ns := (List.ofFn fun i : Fin n => nodes i.succ).flatten
+ have pkts : List.ofFn packet = packet 0 :: rest := List.ofFn_succ
+ have addresses : (List.ofFn nodes).flatten = nodes 0 ++ ns := by rw [List.ofFn_succ]; rfl
+ rw [pkts] at prepared
+ rw [addresses]
+ apply valid_append hook domain _ _ _ _ (along 0 (rest++pending) s bits prepared)
+ intro mid tail success
+ have next := ((child 0).sound (rest++pending) s bits mid tail prepared success).2
+ exact ih (fun i => α i.succ) (fun i => packet i.succ) (fun i => nodes i.succ)
+ (fun i => code i.succ) (fun i => child i.succ) (fun i => along i.succ) pending mid tail next
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R} {N Y : Network}
+
+/-- The prepared frontier entails the native role domain of its first
+packet. The domain may retain geometry words, old half-wires and headers. -/
+def HeadDomain : Prop :=
+ ∀ (q : Packet) pending s, valid (q::pending) s → domain (q.node : Word W) s
+
+/-- The admitted-domain condition holds along each selected subtree's full word-encoded
+preorder starting from its root packet. -/
+def SubtreeAlong (trees : N.Site → VertexTree) (pack : Packets N) : Prop :=
+ ∀ v z, AlongBlock hook valid domain [pack v z] ((trees v).preorder.map (fun n : ℕ => (n : Word W)))
+
+theorem leaf_along (ptr : N.Site → ℕ × ℕ) (pack : Packets N)
+ (address : ∀ v z, (pack v z).node = (ptr v).1) (head : HeadDomain valid domain) :
+ SubtreeAlong hook valid domain (fun v => leafTree (ptr v)) pack := by
+ intro v z pending s bits prepared
+ have h := head (pack v z) pending s prepared
+ rw [address] at h
+ exact ⟨h,fun _ _ _ => trivial⟩
+
+private theorem push_along {t : Term R N} (r : TermParsers f t) (ptr : t.output.Site → ℕ × ℕ)
+ (P : SiteParsers f N) (trees : N.Site → VertexTree) (before : Packets N) (next : Packets t.output)
+ (old : Subtrees hook valid P trees before) (along : SubtreeAlong hook valid domain trees before)
+ (step : NodeStep hook valid r ptr before next) (address : ∀ v z, (next v z).node = (ptr v).1)
+ (head : HeadDomain valid domain) :
+ SubtreeAlong hook valid domain (addTree r ptr trees) next := by
+ intro v z pending s bits prepared
+ let o := r.order.children v
+ let ns (i : Fin o.length) := (trees (o.entries i).val).preorder.map (fun n : ℕ => (n : Word W))
+ have order : ((addTree r ptr trees v).preorder.map (fun n : ℕ => (n : Word W))) =
+ ((ptr v).1 : Word W) :: (List.ofFn ns).flatten := by
+ change List.map _ ((ptr v).1 :: (List.ofFn fun i => (trees (o.entries i).val).preorder).flatten) = _
+ simp [ns,List.map_flatten,Function.comp_def]
+ rw [order]
+ have dom := head (next v z) pending s prepared
+ rw [address] at dom
+ refine ⟨dom,?_⟩
+ intro job more hit
+ obtain ⟨a,_,_,frame⟩ := step.sound v z pending s bits job more prepared hit
+ let α := fun i : Fin o.length => let u := o.entries i; (P.witnesses u.val (a u.val u.prop)).Choice
+ let code (i : Fin o.length) (x : α i) := let u := o.entries i; (P.read u.val (a u.val u.prop)).encode x
+ let ch := fun i : Fin o.length => let u := o.entries i; before u.val (a u.val u.prop)
+ exact forest_along hook valid domain o.length α ch ns code (fun i => old _ _) (fun i => along _ _)
+ pending (job.update s) more frame
+
+/-- The address component of each level's half-wire packet is the numeric
+header pointer of that level. -/
+def PointerLayers {N Y : Network} (c : TermChain R N Y) (ptr : RowPointers c)
+ (layers : PacketLayers c) : Prop :=
+ match c with
+ | .done _ => True
+ | .more _ _ tail => (∀ v z, (layers.1 v z).node = (ptr.1 v).1) ∧ PointerLayers tail ptr.2 layers.2
+
+/-- All native calls visited before the first failed read have their actual
+input domain. This includes malformed, short, and extra incoming streams. -/
+theorem chain_along {N Y : Network} (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (layers : PacketLayers c) (P : SiteParsers f N) (trees : N.Site → VertexTree) (input : Packets N)
+ (initial : Subtrees hook valid P trees input) (along : SubtreeAlong hook valid domain trees input)
+ (steps : StepLayers hook valid c r ptr layers input) (addr : PointerLayers c ptr layers)
+ (head : HeadDomain valid domain) :
+ SubtreeAlong hook valid domain (chainTrees c r ptr trees) (finalPackets c layers input) := by
+ induction c with
+ | done => exact along
+ | more t rec tail ih =>
+ exact ih r.2 ptr.2 layers.2 (r.1.push P) (addTree r.1 ptr.1 trees) layers.1
+ (push_subtrees hook valid r.1 ptr.1 P trees input layers.1 initial steps.1)
+ (push_along hook valid domain r.1 ptr.1 P trees input layers.1 initial along steps.1 addr.1 head)
+ steps.2 addr.2
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTreeDecoder.lean b/lean/OAI/Computability/VPVNP/PairTreeDecoder.lean
new file mode 100644
index 0000000000..3e8bea13f3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTreeDecoder.lean
@@ -0,0 +1,222 @@
+import OAI.Computability.VPVNP.PairTypedVertexJobs
+
+/-!
+# Exact private-bit decoding through the selected term tree
+
+A term visit selects its placed half-wires and a local kernel occurrence.
+Its children then run on these precise half-wires, in the stored order.
+Every successful subtree consumes the code of a factor occurrence, and
+every occurrence runs with any following suffix. Both statements maintain
+the argument packets belonging to the other pending visits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NetworkKernel CompressorRecords LocalHistory NodeArguments
+open scoped Fin.CommRing
+open private push_encode from OAI.Computability.VPVNP.PairSimulationVertexJobs
+open private addTree from OAI.Computability.VPVNP.PairTraversalHistory
+
+variable {W endAddr : ℕ} (hook : HookParser W endAddr)
+variable (valid : List Packet → Scratch W endAddr → Prop)
+
+private theorem decode_append (xs ys : List (Word W)) (s : Scratch W endAddr) (bits : List Bool) :
+ hook.decode (xs++ys) s bits = (hook.decode xs s bits).bind fun pair =>
+ hook.decode ys pair.1 pair.2 := by
+ induction xs generalizing s bits with
+ | nil => rfl
+ | cons x xs ih =>
+ cases h : hook.read x s bits with
+ | none => simp [HookParser.decode,h]
+ | some pair => simp [HookParser.decode,h,ih]
+
+/-- A list of prepared packet arguments and native addresses realizes one
+prefix code. On success the older pending suffix is still prepared. -/
+structure ExactBlock {α : Type*} (args : List Packet) (nodes : List (Word W)) (encode : α → List Bool) : Prop where
+ sound : ∀ pending s bits out tail, valid (args++pending) s →
+ hook.decode nodes s bits = some (out,tail) → (∃ x, bits = encode x ++ tail) ∧ valid pending out
+ complete : ∀ pending s x tail, valid (args++pending) s →
+ ∃ out, hook.decode nodes s (encode x ++ tail) = some (out,tail)
+
+theorem ExactBlock.iff {α : Type*} {args nodes} {encode : α → List Bool}
+ (h : ExactBlock hook valid args nodes encode) {pending s} (prepared : valid (args++pending) s)
+ (bits tail : List Bool) :
+ (∃ out, hook.decode nodes s bits = some (out,tail)) ↔ ∃ x, bits = encode x ++ tail := by
+ constructor
+ · rintro ⟨out,hr⟩
+ exact (h.sound pending s bits out tail prepared hr).1
+ · rintro ⟨x,rfl⟩
+ exact h.complete pending s x tail prepared
+
+/-- Decode all children in order, including an empty fiber, passing along
+the scratch produced by each preceding child. -/
+private theorem forest (n : ℕ) (α : Fin n → Type) (packet : Fin n → Packet)
+ (nodes : Fin n → List (Word W)) (code : ∀ i, α i → List Bool)
+ (child : ∀ i, ExactBlock hook valid [packet i] (nodes i) (code i)) :
+ ExactBlock hook valid (List.ofFn packet) (List.ofFn nodes).flatten
+ (fun x : ∀ i, α i => (List.ofFn fun i => code i (x i)).flatten) := by
+ induction n with
+ | zero =>
+ constructor
+ · intro pending s bits out tail prepared run
+ have pair : s = out ∧ bits = tail := by simpa [HookParser.decode] using run
+ obtain ⟨rfl,rfl⟩ := pair
+ exact ⟨⟨fun i => i.elim0,by simp⟩,by simpa using prepared⟩
+ · intro pending s x tail _
+ exact ⟨s,by simp [HookParser.decode]⟩
+ | succ n ih =>
+ let rest := List.ofFn (fun i : Fin n => packet i.succ)
+ let tailNodes := (List.ofFn (fun i : Fin n => nodes i.succ)).flatten
+ let tailCode (x : ∀ i : Fin n, α i.succ) := (List.ofFn fun i => code i.succ (x i)).flatten
+ have tailRun : ExactBlock hook valid rest tailNodes tailCode :=
+ ih (fun i => α i.succ) (fun i => packet i.succ) (fun i => nodes i.succ)
+ (fun i => code i.succ) (fun i => child i.succ)
+ have packets : List.ofFn packet = packet 0 :: rest := List.ofFn_succ
+ have addresses : (List.ofFn nodes).flatten = nodes 0 ++ tailNodes := by rw [List.ofFn_succ]; rfl
+ have codes (x : ∀ i, α i) :
+ (List.ofFn fun i => code i (x i)).flatten = code 0 (x 0) ++ tailCode (fun i => x i.succ) := by
+ rw [List.ofFn_succ]; rfl
+ constructor
+ · intro pending s bits out tail prepared run
+ rw [packets] at prepared
+ rw [addresses,decode_append] at run
+ obtain ⟨⟨mid,more⟩,first,later⟩ := Option.bind_eq_some_iff.mp run
+ obtain ⟨⟨x,hx⟩,frame⟩ := (child 0).sound (rest++pending) s bits mid more prepared first
+ obtain ⟨⟨xs,hxs⟩,done⟩ := tailRun.sound pending mid more out tail frame later
+ refine ⟨⟨Fin.cons x xs,?_⟩,done⟩
+ rw [codes,hx,hxs]
+ simp only [Fin.cons_zero,Fin.cons_succ,List.append_assoc]
+ · intro pending s x tail prepared
+ rw [packets] at prepared
+ rw [addresses,codes,List.append_assoc,decode_append]
+ let more := tailCode (fun i => x i.succ) ++ tail
+ obtain ⟨mid,first⟩ := (child 0).complete (rest++pending) s (x 0) more prepared
+ have frame := ((child 0).sound (rest++pending) s _ mid more prepared first).2
+ obtain ⟨out,later⟩ := tailRun.complete pending mid (fun i => x i.succ) tail frame
+ exact ⟨out,Option.bind_eq_some_iff.mpr ⟨(mid,more),first,later⟩⟩
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R} {N Y : Network}
+
+/-- The concrete pointer and ordered private half-wire words for a site. -/
+abbrev Packets (N : Network) := ∀ v, N.Half v → Packet
+
+/-- Each selected subtree decodes precisely the corresponding site's encoded choice tape while
+preserving the pending packet suffix. -/
+def Subtrees (P : SiteParsers f N) (trees : N.Site → VertexTree) (pack : Packets N) : Prop :=
+ ∀ v z, ExactBlock hook valid [pack v z] ((trees v).preorder.map (fun n : ℕ => (n : Word W)))
+ (P.read v z).encode
+
+/-- Child packets of a selected term at one output site, enumerated in the parser's order of
+the placement preimage. -/
+noncomputable def children {t : Term R N} (r : TermParsers f t) (pack : Packets N)
+ (v : t.output.Site) (a : Placed t.place N.Half v) : List Packet :=
+ List.ofFn fun i => let u := (r.order.children v).entries i; pack u.val (a u.val u.prop)
+
+/-- The only term-specific obligations concern the single popped row.
+Its successful reads determine the placed half-wires and local factor,
+and its native updates prepare the genuine child buffers. -/
+structure NodeStep {t : Term R N} (r : TermParsers f t) (ptr : t.output.Site → ℕ × ℕ)
+ (before : Packets N) (next : Packets t.output) : Prop where
+ sound : ∀ v z pending s bits job tail, valid (next v z :: pending) s →
+ hook.read ((ptr v).1 : Word W) s bits = some (job,tail) →
+ ∃ a k, bits = r.nodeBits v a z k ++ tail ∧ valid (children r before v a ++ pending) (job.update s)
+ complete : ∀ v z pending s a k tail, valid (next v z :: pending) s →
+ ∃ job, hook.read ((ptr v).1 : Word W) s (r.nodeBits v a z k ++ tail) = some (job,tail) ∧
+ valid (children r before v a ++ pending) (job.update s)
+
+private theorem push_subtrees {t : Term R N} (r : TermParsers f t) (ptr : t.output.Site → ℕ × ℕ)
+ (P : SiteParsers f N) (trees : N.Site → VertexTree) (before : Packets N) (next : Packets t.output)
+ (old : Subtrees hook valid P trees before) (step : NodeStep hook valid r ptr before next) :
+ Subtrees hook valid (r.push P) (addTree r ptr trees) next := by
+ intro v z
+ let o := r.order.children v
+ let address := ((ptr v).1 : Word W)
+ let ns (i : Fin o.length) := (trees (o.entries i).val).preorder.map (fun n : ℕ => (n : Word W))
+ have order : ((addTree r ptr trees v).preorder.map (fun n : ℕ => (n : Word W))) =
+ address :: (List.ofFn ns).flatten := by
+ change List.map _ ((ptr v).1 :: (List.ofFn fun i => (trees (o.entries i).val).preorder).flatten) = _
+ simp [ns,address,List.map_flatten,Function.comp_def]
+ let alpha (a : Placed t.place N.Half v) (i : Fin o.length) :=
+ let u := o.entries i; (P.witnesses u.val (a u.val u.prop)).Choice
+ let code (a : Placed t.place N.Half v) (i : Fin o.length) (x : alpha a i) :=
+ let u := o.entries i; (P.read u.val (a u.val u.prop)).encode x
+ let ch (a : Placed t.place N.Half v) := fun i : Fin o.length =>
+ let u := o.entries i; before u.val (a u.val u.prop)
+ let codes (a : Placed t.place N.Half v) (x : ∀ i, alpha a i) := (List.ofFn fun i => code a i (x i)).flatten
+ have sub (a : Placed t.place N.Half v) :
+ ExactBlock hook valid (children r before v a) (List.ofFn ns).flatten (codes a) :=
+ forest hook valid o.length (alpha a) (ch a) ns (code a) (fun i => old _ _)
+ let e := t.pushChoice P.factors P.witnesses r.witness v z
+ let fam (a : Placed t.place N.Half v) := fun u : t.Preimage v => (P.witnesses u.val (a u.val u.prop)).Choice
+ let index (a : Placed t.place N.Half v) := Equiv.piCongrLeft (fam a) o.entries
+ have split (x : ((r.push P).witnesses v z).Choice) :
+ ((r.push P).read v z).encode x = r.nodeBits v (e x).1 z (e x).2.2 ++
+ codes (e x).1 (fun i => (e x).2.1 (o.entries i)) := push_encode r P v z x
+ constructor
+ · intro pending s bits out tail prepared run
+ rw [order,HookParser.decode] at run
+ obtain ⟨⟨job,more⟩,atNode,below⟩ := Option.bind_eq_some_iff.mp run
+ obtain ⟨a,k,head,frame⟩ := step.sound v z pending s bits job more prepared atNode
+ obtain ⟨⟨xs,tailBits⟩,after⟩ := (sub a).sound pending _ more out tail frame below
+ let selected : ((r.push P).witnesses v z).Choice := e.symm ⟨a,(index a xs,k)⟩
+ have selected_eq : e selected = ⟨a,(index a xs,k)⟩ := e.apply_symm_apply _
+ refine ⟨⟨selected,?_⟩,after⟩
+ rw [split selected,selected_eq,head,tailBits,List.append_assoc]
+ congr 2
+ change codes a xs = codes a (fun i => (index a xs) (o.entries i))
+ apply congrArg (codes a)
+ funext i
+ exact (Equiv.piCongrLeft_apply_apply (fam a) o.entries xs i).symm
+ · intro pending s x tail prepared
+ let a := (e x).1
+ let xs := fun i => (e x).2.1 (o.entries i)
+ let more := codes a xs ++ tail
+ obtain ⟨job,atNode,frame⟩ := step.complete v z pending s a (e x).2.2 more prepared
+ obtain ⟨out,below⟩ := (sub a).complete pending _ xs tail frame
+ refine ⟨out,?_⟩
+ rw [order,HookParser.decode,split x,List.append_assoc]
+ exact Option.bind_eq_some_iff.mpr ⟨(job,more),atNode,below⟩
+
+/-- The sequence of packet assignments to output sites along a selected term chain. -/
+def PacketLayers {N Y : Network} : TermChain R N Y → Type
+ | .done _ => PUnit
+ | .more t _ tail => Packets t.output × PacketLayers tail
+
+/-- Propagate the packet assignments down the selected chain and return the packets at the
+final output sites. -/
+def finalPackets {N Y : Network} (c : TermChain R N Y) (layers : PacketLayers c) (input : Packets N) :
+ Packets Y :=
+ match c with
+ | .done _ => input
+ | .more _ _ tail => finalPackets tail layers.2 layers.1
+
+/-- Node-step correctness holds at each selected layer, relating the incoming packets to that
+layer's output packets and row pointers. -/
+def StepLayers {N Y : Network} (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (layers : PacketLayers c) (input : Packets N) : Prop :=
+ match c with
+ | .done _ => True
+ | .more _ _ tail => NodeStep hook valid r.1 ptr.1 input layers.1 ∧
+ StepLayers tail r.2 ptr.2 layers.2 layers.1
+
+/-- Exact decoding, including failure, for every selected term chain.
+Local implementation proofs are needed only for individual role rows. -/
+theorem chain_exact {N Y : Network} (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (layers : PacketLayers c) (P : SiteParsers f N) (trees : N.Site → VertexTree) (input : Packets N)
+ (initial : Subtrees hook valid P trees input) (steps : StepLayers hook valid c r ptr layers input) :
+ Subtrees hook valid (finalParsers c r P) (chainTrees c r ptr trees) (finalPackets c layers input) := by
+ induction c with
+ | done => exact initial
+ | more t rec tail ih =>
+ exact ih r.2 ptr.2 layers.2 (r.1.push P) (addTree r.1 ptr.1 trees) layers.1
+ (push_subtrees hook valid r.1 ptr.1 P trees input layers.1 initial steps.1) steps.2
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTreeEmissions.lean b/lean/OAI/Computability/VPVNP/PairTreeEmissions.lean
new file mode 100644
index 0000000000..81808b6a80
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTreeEmissions.lean
@@ -0,0 +1,153 @@
+import OAI.Computability.VPVNP.PairTreeNodeReaders
+
+/-!
+# Realizing each compressed occurrence by its physical preorder jobs
+
+The local native map path contributes the selected kernel's label counts.
+The remaining paths are supplied by the old sites in the real placement
+fiber. The construction preserves pending arguments and any required
+property of each native trace, including its linkage and read footprint.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NetworkKernel CompressorRecords LocalHistory NodeArguments
+open scoped Fin.CommRing
+
+variable {W endAddr : ℕ} {L : Type}
+ (valid : List Packet → Scratch W endAddr → Prop) (hist : Scratch W endAddr → L → ℕ)
+ (guard : VisitPath W endAddr → Prop)
+
+private theorem ready_append (xs ys : List (VisitPath W endAddr)) (s : Scratch W endAddr)
+ (first : Ready xs s) (later : Ready ys (xs.foldl (fun old j => j.update old) s)) :
+ Ready (xs++ys) s := by
+ induction xs generalizing s with
+ | nil => exact later
+ | cons x xs ih => exact ⟨first.1,ih _ first.2 later⟩
+
+/-- Actual local paths with the specified exponent increments and private
+word codes. The guard can include the exact native link and all allowed
+external reads, so these facts hold for each path in the produced list. -/
+structure Effects (s : Scratch W endAddr) (pending : List Packet) (semantic : List (VertexJob L))
+ (native : List (VisitPath W endAddr)) : Prop where
+ realized : List.Forall₂ (RealizesJob hist) semantic native
+ ready : Ready native s
+ framed : ∀ j ∈ native, guard j
+ remaining : valid pending (native.foldl (fun old j => j.update old) s)
+
+private theorem Effects.join {s : Scratch W endAddr} {pending mid : List Packet}
+ {a b : List (VertexJob L)} {x y : List (VisitPath W endAddr)}
+ (first : Effects valid hist guard s mid a x)
+ (second : Effects valid hist guard (x.foldl (fun old j => j.update old) s) pending b y) :
+ Effects valid hist guard s pending (a++b) (x++y) := by
+ refine ⟨List.rel_append first.realized second.realized,ready_append _ _ _ first.ready second.ready,?_,?_⟩
+ · intro j hj
+ exact (List.mem_append.mp hj).elim (first.framed j) (second.framed j)
+ · simpa only [List.foldl_append] using second.remaining
+
+private theorem forest_effects (n : ℕ) (pack : Fin n → Packet) (jobs : Fin n → List (VertexJob L))
+ (child : ∀ i pending s, valid (pack i::pending) s →
+ ∃ xs, Effects valid hist guard s pending (jobs i) xs)
+ (pending : List Packet) (s : Scratch W endAddr) (ready : valid (List.ofFn pack ++ pending) s) :
+ ∃ xs, Effects valid hist guard s pending (List.ofFn jobs).flatten xs := by
+ induction n generalizing pending s with
+ | zero =>
+ exact ⟨[],⟨by simp, trivial,by simp,by simpa using ready⟩⟩
+ | succ n ih =>
+ let rest := List.ofFn (fun i : Fin n => pack i.succ)
+ have ps : List.ofFn pack = pack 0 :: rest := List.ofFn_succ
+ rw [ps] at ready
+ obtain ⟨xs,first⟩ := child 0 (rest++pending) s ready
+ obtain ⟨ys,later⟩ := ih (fun i => pack i.succ) (fun i => jobs i.succ) (fun i => child i.succ)
+ pending _ first.remaining
+ exact ⟨xs++ys,by rw [List.ofFn_succ]; exact first.join valid hist guard later⟩
+
+variable {R : Type*} [CommRing R] [Fintype L] {f : L → R} {N Y : Network}
+
+/-- Each occurrence is realized by the ordered path list supplied by this
+layer, on every scratch preparing its packet and every pending suffix. -/
+def Emits (P : SiteParsers f N) (input : Packets N) (jobs : JobsFor P) : Prop :=
+ ∀ v z x pending s, valid (input v z::pending) s →
+ ∃ native, Effects valid hist guard s pending (jobs v z x) native
+
+/-- One visit supplies its own monomial increment and the old packets for
+its children. No claim about the later subtree is a local hypothesis. -/
+def EmitsNode {t : Term R N} (r : TermParsers f t) (ptr : t.output.Site → ℕ × ℕ)
+ (before : Packets N) (next : Packets t.output) : Prop :=
+ ∀ v z a k pending s, valid (next v z::pending) s →
+ ∃ job, RealizesJob hist ⟨(ptr v).1,r.nodeBits v a z k,(r.witness v a z).exponents k⟩ job ∧
+ job.enabled s ∧ guard job ∧ valid (children r before v a++pending) (job.update s)
+
+/-- The concrete term-row reader and its label effect give the native
+per-node path used by the positive induction. -/
+theorem emitsNode_of_read {t : Term R N} (hook : HookParser W endAddr) (r : TermParsers f t)
+ (ptr : t.output.Site → ℕ × ℕ) (before : Packets N) (next : Packets t.output)
+ (steps : NodeStep hook valid r ptr before next)
+ (effect : ∀ v z a k pending s job, valid (next v z::pending) s →
+ hook.read ((ptr v).1 : Word W) s (r.nodeBits v a z k) = some (job,[]) →
+ RealizesJob hist ⟨(ptr v).1,r.nodeBits v a z k,(r.witness v a z).exponents k⟩ job ∧
+ job.enabled s ∧ guard job) :
+ EmitsNode valid hist guard r ptr before next := by
+ intro v z a k pending s h
+ obtain ⟨j,hit,frame⟩ := steps.complete v z pending s a k [] h
+ rw [List.append_nil] at hit
+ obtain ⟨real,en,g⟩ := effect v z a k pending s j h hit
+ exact ⟨j,real,en,g,frame⟩
+
+theorem leaf_emits (P : SiteParsers f N) (input : Packets N) (ptr : N.Site → ℕ × ℕ)
+ (each : ∀ v z x pending s, valid (input v z::pending) s → ∃ j,
+ RealizesJob hist ⟨(ptr v).1,(P.read v z).encode x,(P.witnesses v z).exponents x⟩ j ∧
+ j.enabled s ∧ guard j ∧ valid pending (j.update s)) :
+ Emits valid hist guard P input (leafJobs P ptr) := by
+ intro v z x pending s h
+ obtain ⟨j,real,en,g,remaining⟩ := each v z x pending s h
+ exact ⟨[j],⟨.cons real .nil,⟨en,trivial⟩,fun _ m => (List.mem_singleton.mp m) ▸ g,remaining⟩⟩
+
+private theorem push_emits {t : Term R N} (r : TermParsers f t) (ptr : t.output.Site → ℕ × ℕ)
+ (P : SiteParsers f N) (before : Packets N) (next : Packets t.output) (jobs : JobsFor P)
+ (old : Emits valid hist guard P before jobs) (step : EmitsNode valid hist guard r ptr before next) :
+ Emits valid hist guard (r.push P) next (pushJobs r ptr P jobs) := by
+ intro v z x pending s ready
+ let q := t.pushChoice P.factors P.witnesses r.witness v z x
+ let o := r.order.children v
+ let ch (i : Fin o.length) := let u := o.entries i; before u.val (q.1 u.val u.prop)
+ let below (i : Fin o.length) := let u := o.entries i; jobs u.val (q.1 u.val u.prop) (q.2.1 u)
+ obtain ⟨head,real,en,g,prep⟩ := step v z q.1 q.2.2 pending s ready
+ obtain ⟨rest,eff⟩ := forest_effects valid hist guard o.length ch below
+ (fun i => old _ _ _) pending (head.update s) prep
+ refine ⟨head::rest,⟨.cons real eff.realized,⟨en,eff.ready⟩,?_,eff.remaining⟩⟩
+ intro j hj
+ rcases List.mem_cons.mp hj with eqn | later
+ · exact eqn ▸ g
+ · exact eff.framed j later
+
+/-- Each selected layer's node visits emit the required histogram increments under the guard
+and pending-packet invariant. -/
+def EmissionLayers {N Y : Network} (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (layers : PacketLayers c) (input : Packets N) : Prop :=
+ match c with
+ | .done _ => True
+ | .more _ _ tail => EmitsNode valid hist guard r.1 ptr.1 input layers.1 ∧
+ EmissionLayers tail r.2 ptr.2 layers.2 layers.1
+
+/-- From the actual leaf paths and individual term-row paths, produce the
+entire ordered native job list for any selected final-site occurrence. -/
+theorem chain_emits {N Y : Network} (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (layers : PacketLayers c) (P : SiteParsers f N) (input : Packets N) (jobs : JobsFor P)
+ (initial : Emits valid hist guard P input jobs) (steps : EmissionLayers valid hist guard c r ptr layers input) :
+ Emits valid hist guard (finalParsers c r P) (finalPackets c layers input) (chainJobs c r ptr P jobs) := by
+ induction c with
+ | done => exact initial
+ | more t rec tail ih =>
+ exact ih r.2 ptr.2 layers.2 (r.1.push P) layers.1 (pushJobs r.1 ptr.1 P jobs)
+ (push_emits valid hist guard r.1 ptr.1 P input layers.1 jobs initial steps.1) steps.2
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTreeFrontier.lean b/lean/OAI/Computability/VPVNP/PairTreeFrontier.lean
new file mode 100644
index 0000000000..2b28028cb8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTreeFrontier.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.PairTreeDecodeDomain
+
+/-!
+# Prepared packets and the unvisited descriptor subtrees
+
+Distinct current addresses alone would allow a pending sibling to occupy
+a child's address. The frontier therefore records the numerical preorders
+of the entire remaining subtrees. Popping a row and exposing its children
+removes precisely one address from this list, regardless of the guessed
+half-wire values and regardless of whether a later visit accepts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NodeArguments
+open scoped Fin.CommRing
+
+variable {W endAddr : ℕ}
+
+/-- Preorder address list of a packet's subtree, beginning with its node followed by the
+recorded descendant addresses. -/
+def subtreeAddresses (desc : ℕ → List ℕ) (q : Packet) := q.node :: desc q.node
+
+private theorem roots_sublist (desc : ℕ → List ℕ) (pending : List Packet) :
+ (pending.map Packet.node).Sublist (pending.flatMap (subtreeAddresses desc)) := by
+ induction pending with
+ | nil => exact List.Sublist.refl _
+ | cons q qs ih =>
+ exact .cons_cons _ (ih.trans (List.sublist_append_right (desc q.node) _))
+
+/-- The whole private state outside live argument packets is constrained
+only by the supplied stability predicate, for instance the resident geometry
+and operand cache. The typed format accepts arbitrary old half-wire values. -/
+structure Frontier (arena : Arena) (format : Packet → Prop) (stable : Scratch W endAddr → Prop)
+ (desc : ℕ → List ℕ) (pending : List Packet) (s : Scratch W endAddr) : Prop where
+ frame : stable s
+ prepared : PreparedPackets arena format pending s
+ disjoint : (pending.flatMap (subtreeAddresses desc)).Nodup
+
+variable {arena : Arena} {format : Packet → Prop} {stable : Scratch W endAddr → Prop}
+ {desc : ℕ → List ℕ}
+
+theorem Frontier.singleton {q : Packet} {s : Scratch W endAddr} (frame : stable s)
+ (type : format q) (fits : q.Fits arena W endAddr) (stored : q.Stored arena s)
+ (tree : (subtreeAddresses desc q).Nodup) :
+ Frontier arena format stable desc [q] s := by
+ refine ⟨frame,⟨by simp,?_⟩,by simpa using tree⟩
+ intro p hp
+ obtain rfl := List.mem_singleton.mp hp
+ exact ⟨type,fits,stored⟩
+
+theorem Frontier.head {q : Packet} {pending : List Packet} {s : Scratch W endAddr}
+ (h : Frontier arena format stable desc (q::pending) s) :
+ stable s ∧ format q ∧ q.Fits arena W endAddr ∧ q.Stored arena s :=
+ ⟨h.frame,h.prepared.2 q List.mem_cons_self⟩
+
+/-- The actual typed role domain only needs the first prepared packet,
+its numerical address and its physical scratch. -/
+theorem frontier_headDomain (domain : Word W → Scratch W endAddr → Prop)
+ (ready : ∀ (q : Packet) s, stable s → format q → q.Fits arena W endAddr →
+ q.Stored arena s → domain (q.node : Word W) s) :
+ HeadDomain (Frontier arena format stable desc) domain :=
+ fun q _ s h => ready q s h.head.1 h.head.2.1 h.head.2.2.1 h.head.2.2.2
+
+/-- A leaf may change its own private workspace. No old pending packet is
+lost if its fitted interval remains stored and the common frame persists. -/
+theorem Frontier.pop {head : Packet} {pending : List Packet} {s out : Scratch W endAddr}
+ (h : Frontier arena format stable desc (head::pending) s) (frame : stable out)
+ (keep : ∀ q ∈ pending, q.Fits arena W endAddr → q.Stored arena s → q.Stored arena out) :
+ Frontier arena format stable desc pending out := by
+ have disjoint := (List.sublist_append_right (subtreeAddresses desc head)
+ (pending.flatMap (subtreeAddresses desc))).nodup h.disjoint
+ refine ⟨frame,⟨(roots_sublist desc pending).nodup disjoint,?_⟩,disjoint⟩
+ intro q hq
+ obtain ⟨type,fits,stored⟩ := h.prepared.2 q (List.mem_cons_of_mem _ hq)
+ exact ⟨type,fits,keep q hq fits stored⟩
+
+/-- The children are precisely the next packets in the row's stored
+placement order. Their regions cannot collide with any older pending
+sibling, because all these subtrees already belonged to a disjoint forest. -/
+theorem Frontier.push {head : Packet} {children pending : List Packet} {s out : Scratch W endAddr}
+ (h : Frontier arena format stable desc (head::pending) s)
+ (shape : desc head.node = children.flatMap (subtreeAddresses desc)) (frame : stable out)
+ (types : ∀ q ∈ children, format q ∧ q.Fits arena W endAddr)
+ (agree : ∀ q ∈ children++pending, ∀ i : Fin q.bits.length,
+ rawScratch out ((arena.base q.node+i.val : ℕ) : Word W) =
+ rawScratch (writePackets arena children s) ((arena.base q.node+i.val : ℕ) : Word W)) :
+ Frontier arena format stable desc (children++pending) out := by
+ have disjoint : ((children++pending).flatMap (subtreeAddresses desc)).Nodup := by
+ have hd := h.disjoint
+ change (head.node :: (desc head.node ++ pending.flatMap (subtreeAddresses desc))).Nodup at hd
+ rw [shape] at hd
+ simpa only [List.flatMap_append] using (List.nodup_cons.mp hd).2
+ exact ⟨frame,preparedPackets_push arena format head children pending s out h.prepared types
+ ((roots_sublist desc (children++pending)).nodup disjoint) agree,disjoint⟩
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTreeFrontierBudget.lean b/lean/OAI/Computability/VPVNP/PairTreeFrontierBudget.lean
new file mode 100644
index 0000000000..c7304eb4f6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTreeFrontierBudget.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.PairTreeFrontier
+
+/-!
+# Word headroom for every pending vertex
+
+Each remaining vertex can add at most `nodeCap` to any one label counter.
+The total allowance decreases by exactly one vertex when a row exposes its
+children, including a leaf with no children. This bounds every intermediate
+counter on arbitrary accepting prefixes, before the native word addition.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NodeArguments
+open scoped Fin.CommRing
+
+variable {W endAddr : ℕ} {Label : Type*}
+variable {arena : Arena} {format : Packet → Prop} {stable : Scratch W endAddr → Prop}
+ {desc : ℕ → List ℕ} {hist : Scratch W endAddr → Label → ℕ} {nodeCap limit : ℕ}
+
+/-- Count the unvisited vertices, including descendants of pending roots. -/
+def remaining (desc : ℕ → List ℕ) (pending : List Packet) : ℕ :=
+ (pending.flatMap (subtreeAddresses desc)).length
+
+theorem remaining_step {head : Packet} {children pending : List Packet}
+ (shape : desc head.node = children.flatMap (subtreeAddresses desc)) :
+ remaining desc (head :: pending) = remaining desc (children ++ pending) + 1 := by
+ simp [remaining,subtreeAddresses,List.flatMap_append,← shape,Nat.add_comm,
+ Nat.add_left_comm]
+
+/-- The bound applies to each label separately, also when a later node
+reads a field that was not reached on a successful whole-site path. -/
+structure Budgeted (arena : Arena) (format : Packet → Prop) (stable : Scratch W endAddr → Prop)
+ (desc : ℕ → List ℕ) (hist : Scratch W endAddr → Label → ℕ) (nodeCap limit : ℕ)
+ (pending : List Packet) (s : Scratch W endAddr) : Prop where
+ frontier : Frontier arena format stable desc pending s
+ room : ∀ l, hist s l + remaining desc pending * nodeCap ≤ limit
+
+theorem Budgeted.singleton {q : Packet} {s : Scratch W endAddr}
+ (front : Frontier arena format stable desc [q] s) (zero : ∀ l, hist s l = 0)
+ (fit : (subtreeAddresses desc q).length * nodeCap ≤ limit) :
+ Budgeted arena format stable desc hist nodeCap limit [q] s := by
+ refine ⟨front,fun l => ?_⟩
+ simpa only [zero l,Nat.zero_add,remaining,
+ List.flatMap_cons,List.flatMap_nil,List.append_nil] using fit
+
+/-- A nonempty frontier always has room for the local update, before its
+value is represented modulo the machine's word size. -/
+theorem Budgeted.headRoom {head : Packet} {pending : List Packet} {s : Scratch W endAddr}
+ (h : Budgeted arena format stable desc hist nodeCap limit (head :: pending) s) (l : Label) :
+ hist s l + nodeCap ≤ limit := by
+ have one : 1 ≤ remaining desc (head :: pending) := by simp [remaining,subtreeAddresses]
+ have step := Nat.mul_le_mul_right nodeCap one
+ rw [Nat.one_mul] at step
+ exact (Nat.add_le_add_left step _).trans (h.room l)
+
+theorem Budgeted.word_add {head : Packet} {pending : List Packet} {s : Scratch W endAddr}
+ (h : Budgeted arena format stable desc hist nodeCap limit (head :: pending) s)
+ (wordFit : limit < 2 ^ W) (l : Label) {delta : ℕ} (small : delta ≤ nodeCap) :
+ ((hist s l : Word W) + (delta : Word W)).val = hist s l + delta := by
+ have lt := ((Nat.add_le_add_left small (hist s l)).trans (h.headRoom l)).trans_lt wordFit
+ rw [← Nat.cast_add,Fin.val_natCast,Nat.mod_eq_of_lt lt]
+
+theorem Budgeted.advance {head : Packet} {children pending : List Packet}
+ {s out : Scratch W endAddr}
+ (h : Budgeted arena format stable desc hist nodeCap limit (head :: pending) s)
+ (shape : desc head.node = children.flatMap (subtreeAddresses desc))
+ (front : Frontier arena format stable desc (children ++ pending) out)
+ (localBound : ∀ l, hist out l ≤ hist s l + nodeCap) :
+ Budgeted arena format stable desc hist nodeCap limit (children ++ pending) out := by
+ refine ⟨front,fun l => ?_⟩
+ have old := h.room l
+ rw [remaining_step shape,Nat.add_mul,Nat.one_mul] at old
+ have step := Nat.add_le_add_right (localBound l) (remaining desc (children ++ pending)*nodeCap)
+ omega
+
+theorem Budgeted.pop {head : Packet} {pending : List Packet} {s out : Scratch W endAddr}
+ (h : Budgeted arena format stable desc hist nodeCap limit (head :: pending) s)
+ (leaf : desc head.node = []) (frame : stable out)
+ (keep : ∀ q ∈ pending, q.Fits arena W endAddr → q.Stored arena s → q.Stored arena out)
+ (zero : ∀ l, hist out l = hist s l) :
+ Budgeted arena format stable desc hist nodeCap limit pending out := by
+ exact h.advance (children := []) leaf (h.frontier.pop frame keep)
+ (fun l => (zero l).le.trans (Nat.le_add_right _ _))
+
+theorem Budgeted.push {head : Packet} {children pending : List Packet} {s out : Scratch W endAddr}
+ (h : Budgeted arena format stable desc hist nodeCap limit (head :: pending) s)
+ (shape : desc head.node = children.flatMap (subtreeAddresses desc)) (frame : stable out)
+ (types : ∀ q ∈ children, format q ∧ q.Fits arena W endAddr)
+ (agree : ∀ q ∈ children ++ pending, ∀ i : Fin q.bits.length,
+ rawScratch out ((arena.base q.node+i.val : ℕ) : Word W) =
+ rawScratch (writePackets arena children s) ((arena.base q.node+i.val : ℕ) : Word W))
+ (localBound : ∀ l, hist out l ≤ hist s l + nodeCap) :
+ Budgeted arena format stable desc hist nodeCap limit (children ++ pending) out :=
+ h.advance shape (h.frontier.push shape frame types agree) localBound
+
+theorem budgeted_headDomain (domain : Word W → Scratch W endAddr → Prop)
+ (ready : ∀ (q : Packet) s, stable s → format q → q.Fits arena W endAddr → q.Stored arena s →
+ (∀ l, hist s l + nodeCap ≤ limit) → domain (q.node : Word W) s) :
+ HeadDomain (Budgeted arena format stable desc hist nodeCap limit) domain :=
+ fun q _ s h => ready q s h.frontier.head.1 h.frontier.head.2.1 h.frontier.head.2.2.1
+ h.frontier.head.2.2.2 h.headRoom
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTreeNodeReaders.lean b/lean/OAI/Computability/VPVNP/PairTreeNodeReaders.lean
new file mode 100644
index 0000000000..32d7f61645
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTreeNodeReaders.lean
@@ -0,0 +1,111 @@
+import OAI.Computability.VPVNP.PairTreeDecoder
+
+/-! # Local role-reader contracts for exact traversal of a selected term tree -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NetworkKernel CompressorRecords LocalHistory NodeArguments
+open scoped Fin.CommRing
+
+variable {W endAddr : ℕ} (hook : HookParser W endAddr)
+ (valid : List Packet → Scratch W endAddr → Prop)
+ {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R} {N : Network}
+
+private theorem suffix_some {α β : Type*} {native : Option (β × List Bool)} (C : ChoiceReader α)
+ {bits tail : List Bool} (same : native.map Prod.snd = (C.read bits).map Prod.snd) :
+ (∃ j, native = some (j,tail)) ↔ ∃ x, bits = C.encode x ++ tail := by
+ constructor
+ · rintro ⟨j,read⟩
+ rw [read,Option.map_some] at same
+ obtain ⟨⟨x,rest⟩,hit,rfl⟩ := Option.map_eq_some_iff.mp same.symm
+ exact ⟨x,(C.read_iff bits x rest).mp hit⟩
+ · rintro ⟨x,hx⟩
+ rw [(C.read_iff _ _ _).mpr hx,Option.map_some] at same
+ obtain ⟨⟨j,rest⟩,hit,rfl⟩ := Option.map_eq_some_iff.mp same
+ exact ⟨j,hit⟩
+
+/-- This is the local part of the term's reader: first the independent
+child half-wires, then that term's own checked kernel choices. -/
+noncomputable def nodeReader {t : Term R N} (r : TermParsers f t) (v : t.output.Site) (z : t.output.Half v) :
+ ChoiceReader ((a : Placed t.place N.Half v) × (r.witness v a z).Choice) :=
+ (fiber t.place v (r.order.children v) (fun u => half N u (r.order.outgoing u) (r.order.incoming u) r.payload)).sigma
+ (fun a => r.read v a z)
+
+theorem nodeReader_encode {t : Term R N} (r : TermParsers f t) (v : t.output.Site) (z : t.output.Half v)
+ (a : Placed t.place N.Half v) (k : (r.witness v a z).Choice) :
+ (nodeReader r v z).encode ⟨a,k⟩ = r.nodeBits v a z k := rfl
+
+/-- Suffix equality and the effect of the native writes suffice for both
+directions of the term-row contract. The write effect is required only for
+the exact placed assignment and local kernel occurrence read by that row. -/
+theorem nodeStep_of_suffix {t : Term R N} (r : TermParsers f t) (ptr : t.output.Site → ℕ × ℕ)
+ (before : Packets N) (next : Packets t.output)
+ (suffix : ∀ v z pending s bits, valid (next v z::pending) s →
+ (hook.read ((ptr v).1 : Word W) s bits).map Prod.snd = ((nodeReader r v z).read bits).map Prod.snd)
+ (write : ∀ v z pending s bits job tail a k, valid (next v z::pending) s →
+ hook.read ((ptr v).1 : Word W) s bits = some (job,tail) → bits = r.nodeBits v a z k ++ tail →
+ valid (children r before v a ++ pending) (job.update s)) :
+ NodeStep hook valid r ptr before next := by
+ constructor
+ · intro v z pending s bits job tail ready hit
+ obtain ⟨⟨a,k⟩,eqn⟩ := (suffix_some (nodeReader r v z) (suffix v z pending s bits ready)).mp ⟨job,hit⟩
+ exact ⟨a,k,eqn,write v z pending s bits job tail a k ready hit eqn⟩
+ · intro v z pending s a k tail ready
+ let bits := r.nodeBits v a z k ++ tail
+ obtain ⟨job,hit⟩ := (suffix_some (nodeReader r v z) (suffix v z pending s bits ready)).mpr ⟨⟨a,k⟩,rfl⟩
+ exact ⟨job,hit,write v z pending s bits job tail a k ready hit rfl⟩
+
+/-- With the state parser's actual half-wire order the child packet list is
+literally the one built by the selected term's native argument pass. -/
+theorem children_childPackets {t : Term R N} (r : TermParsers f t) (addr : N.Site → ℕ)
+ (v : t.output.Site) (a : Placed t.place N.Half v) :
+ children r (fun u z => ⟨addr u, r.halfBits u z⟩) v a = r.childPackets addr v a := rfl
+
+/-- The physical leaf's suffix equality with its cursor reader and its
+preservation of the pending packets give the initial subtree induction. -/
+theorem leaf_subtrees (P : SiteParsers f N) (ptr : N.Site → ℕ × ℕ) (pack : Packets N)
+ (suffix : ∀ v z pending s bits, valid (pack v z::pending) s →
+ (hook.read ((ptr v).1 : Word W) s bits).map Prod.snd = ((P.read v z).read bits).map Prod.snd)
+ (frame : ∀ v z pending s bits job tail, valid (pack v z::pending) s →
+ hook.read ((ptr v).1 : Word W) s bits = some (job,tail) → valid pending (job.update s)) :
+ Subtrees hook valid P (fun v => leafTree (ptr v)) pack := by
+ intro v z
+ have order : ((leafTree (ptr v)).preorder.map (fun n : ℕ => (n : Word W))) = [((ptr v).1 : Word W)] := rfl
+ constructor
+ · intro pending s bits out tail ready run
+ rw [order,HookParser.decode] at run
+ obtain ⟨⟨job,rest⟩,hit,done⟩ := Option.bind_eq_some_iff.mp run
+ obtain ⟨rfl,rfl⟩ := Prod.mk.inj (Option.some.inj done : (job.update s,rest) = (out,tail)).symm
+ exact ⟨(suffix_some (P.read v z) (suffix v z pending s bits ready)).mp ⟨job,hit⟩,
+ frame v z pending s bits job _ ready hit⟩
+ · intro pending s x tail ready
+ let bits := (P.read v z).encode x ++ tail
+ obtain ⟨job,hit⟩ := (suffix_some (P.read v z) (suffix v z pending s bits ready)).mpr ⟨x,rfl⟩
+ refine ⟨job.update s,?_⟩
+ rw [order,HookParser.decode]
+ exact Option.bind_eq_some_iff.mpr ⟨(job,tail),hit,rfl⟩
+
+/-- The selected occurrence is unique for any exact native suffix, including
+the empty suffix used by the actual burst return. -/
+theorem ExactBlock.unique {α : Type*} {args nodes} (C : ChoiceReader α)
+ (h : ExactBlock hook valid args nodes C.encode) {pending s} (prepared : valid (args++pending) s)
+ (bits tail : List Bool) :
+ (∃ out, hook.decode nodes s bits = some (out,tail)) ↔ ∃! x, bits = C.encode x ++ tail := by
+ rw [h.iff hook valid prepared]
+ constructor
+ · rintro ⟨x,hx⟩
+ refine ⟨x,hx,?_⟩
+ intro y hy
+ exact congrArg Prod.fst (Option.some.inj (((C.read_iff bits y tail).mpr hy).symm.trans
+ ((C.read_iff bits x tail).mpr hx)))
+ · rintro ⟨x,hx,_⟩; exact ⟨x,hx⟩
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTreePacketLayers.lean b/lean/OAI/Computability/VPVNP/PairTreePacketLayers.lean
new file mode 100644
index 0000000000..a73c1ce3bd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTreePacketLayers.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.PairTreeDecodeDomain
+
+/-! # Canonical ordered packets of all layers of the selected compression -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM DFS NetworkKernel CompressorRecords LocalHistory NodeArguments
+open Compression
+open scoped Fin.CommRing
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R} {N Y : Network}
+
+/-- A nonterminal layer uses the half-wire layout of the next real term.
+The final layer uses the endpoint collector's root half-wire layout. -/
+noncomputable def fromRows {N Y : Network} (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (addr : N.Site → ℕ) (finalBits : ∀ v, Y.Half v → List Bool) : Packets N × PacketLayers c :=
+ match c with
+ | .done _ => (fun v z => ⟨addr v,finalBits v z⟩,PUnit.unit)
+ | .more _ _ tail =>
+ let later := fromRows tail r.2 ptr.2 (fun v => (ptr.1 v).1) finalBits
+ (fun u z => ⟨addr u,r.1.halfBits u z⟩,(later.1,later.2))
+
+theorem fromRows_inputAddress (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (addr : N.Site → ℕ) (finalBits : ∀ v, Y.Half v → List Bool) (u : N.Site) (z : N.Half u) :
+ ((fromRows c r ptr addr finalBits).1 u z).node = addr u := by cases c <;> rfl
+
+theorem fromRows_pointers (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (addr : N.Site → ℕ) (finalBits : ∀ v, Y.Half v → List Bool) :
+ PointerLayers c ptr (fromRows c r ptr addr finalBits).2 := by
+ induction c with
+ | done => trivial
+ | more t rec tail ih =>
+ exact ⟨fromRows_inputAddress tail r.2 ptr.2 (fun v => (ptr.1 v).1) finalBits,
+ ih r.2 ptr.2 (fun v => (ptr.1 v).1) finalBits⟩
+
+/-- At the singleton final root this gives the exact packet prepared by
+the external endpoint gather, independent of the branch's depth. -/
+theorem fromRows_final (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (addr : N.Site → ℕ) (finalBits : ∀ v, Y.Half v → List Bool) :
+ finalPackets c (fromRows c r ptr addr finalBits).2 (fromRows c r ptr addr finalBits).1 =
+ fun v z => ⟨lastRowAddresses c ptr addr v,finalBits v z⟩ := by
+ induction c with
+ | done => rfl
+ | more t rec tail ih => exact ih r.2 ptr.2 (fun v => (ptr.1 v).1) finalBits
+
+/-- The list of half-wire buffers used by the local row is exactly
+the list prepared by its physical child-field pass. -/
+theorem fromRows_children {t : Term R N} {rec : t.output.Site → SiteRecords} (tail : TermChain R t.output Y)
+ (r : ChainParsers f (.more t rec tail)) (ptr : RowPointers (.more t rec tail))
+ (addr : N.Site → ℕ) (finalBits : ∀ v, Y.Half v → List Bool) (v : t.output.Site)
+ (a : Placed t.place N.Half v) :
+ children r.1 (fromRows (.more t rec tail) r ptr addr finalBits).1 v a =
+ r.1.childPackets addr v a := rfl
+
+/-- On a real state the incoming layer of the pass is in the arena's exact
+outgoing-then-incoming slot layout. -/
+theorem fromRows_packed {degree lanes : ℕ} (X : State degree lanes) {t : Term R X.network}
+ {rec : t.output.Site → SiteRecords} (tail : TermChain R t.output Y) (r : ChainParsers f (.more t rec tail))
+ (ptr : RowPointers (.more t rec tail)) (addr : X.network.Site → ℕ)
+ (finalBits : ∀ v, Y.Half v → List Bool) (hp : r.1.payload = statePayload X)
+ (ho : ∀ u, r.1.order.outgoing u = outgoingOrder X u)
+ (hi : ∀ u, r.1.order.incoming u = incomingOrder X u)
+ (u : X.network.Site) (z : X.network.Half u) :
+ (fromRows (.more t rec tail) r ptr addr finalBits).1 u z = ⟨addr u, packed X u z⟩ := by
+ change Packet.mk (addr u) (r.1.halfBits u z) = _
+ simp [TermParsers.halfBits,hp,ho,hi,packed_eq_encode]
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTreeSelectedFrontier.lean b/lean/OAI/Computability/VPVNP/PairTreeSelectedFrontier.lean
new file mode 100644
index 0000000000..1bbf49d1ee
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTreeSelectedFrontier.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.PairTreeFrontier
+import OAI.Computability.VPVNP.PairSelectedPacketOrders
+import OAI.Computability.VPVNP.PairTraversalDisjoint
+
+/-!
+# Descendant address lists of the actual selected descriptor rows
+
+Each new layer uses a fresh interval of row addresses. Assign its placed
+children's complete preorders there, while keeping all earlier row values.
+This gives one address-indexed function for all leaves and intermediate
+rows, valid for every assignment of the private half-wire packets.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open DFS NetworkKernel CompressorRecords LocalHistory NodeArguments Compression TraversalRows
+open private ptr_bounds ptr_injective from OAI.Computability.VPVNP.PairTraversalDisjoint
+open private addTree from OAI.Computability.VPVNP.PairTraversalHistory
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R} {N Y : Network}
+
+/-- Concatenate each selected child's root address and descendants in the local parser's child
+order. -/
+def childAddresses {t : Term R N} (r : TermParsers f t) (addr : N.Site → ℕ)
+ (desc : ℕ → List ℕ) (v : t.output.Site) : List ℕ :=
+ (List.ofFn fun i => let u := (r.order.children v).entries i; addr u.val :: desc (addr u.val)).flatten
+
+/-- These are the descendant addresses in precisely the native child
+packet list, independently of its guessed half-wire values. -/
+theorem children_addresses {t : Term R N} (r : TermParsers f t) (before : Packets N)
+ (addr : N.Site → ℕ) (num : ∀ v z, (before v z).node = addr v)
+ (desc : ℕ → List ℕ) (v : t.output.Site) (a : Placed t.place N.Half v) :
+ (children r before v a).flatMap (subtreeAddresses desc) = childAddresses r addr desc v := by
+ simp [children,childAddresses,List.flatMap_def,subtreeAddresses,Function.comp_def,num]
+
+/-- At every selected layer, a parent's descendant list is exactly the concatenation of its
+ordered child subtrees. -/
+def DescLayers {N Y : Network} (c : TermChain R N Y) (r : ChainParsers f c)
+ (ptr : RowPointers c) (addr : N.Site → ℕ) (desc : ℕ → List ℕ) : Prop :=
+ match c with
+ | .done _ => True
+ | .more _ _ tail => (∀ v, desc (ptr.1 v).1 = childAddresses r.1 addr desc v) ∧
+ DescLayers tail r.2 ptr.2 (fun v => (ptr.1 v).1) desc
+
+private theorem extendLayers (c : TermChain R N Y) (r : ChainParsers f c)
+ (orders : ChainOrders c) (cap base : ℕ) (addr : N.Site → ℕ) (below : ∀ v, addr v < base)
+ (old : ℕ → List ℕ) :
+ ∃ desc, (∀ k < base, desc k = old k) ∧ DescLayers c r (chainPointers cap c orders base) addr desc := by
+ induction c generalizing base old with
+ | done => exact ⟨old,fun _ _ => rfl,trivial⟩
+ | more t rec tail ih =>
+ let o := orders.1
+ let row := fun v => (sitePointers cap base o v).1
+ let top := address cap base o.length
+ let table := Function.extend row (childAddresses r.1 addr old) old
+ have hit (v : t.output.Site) : table (row v) = childAddresses r.1 addr old v :=
+ (ptr_injective o cap base).extend_apply _ _ v
+ have under (k : ℕ) (hk : k < base) : table k = old k :=
+ Function.extend_apply' _ _ _ (by rintro ⟨v,rfl⟩; exact hk.not_ge (ptr_bounds o cap base v).1)
+ have bounds (v : t.output.Site) : base ≤ row v ∧ row v < top := ptr_bounds o cap base v
+ obtain ⟨desc,earlier,tailRows⟩ := ih r.2 orders.2 top row (fun v => (bounds v).2) table
+ have low (k : ℕ) (hk : k < base) : desc k = old k := by
+ have ht : base ≤ top := Nat.le_add_right _ _
+ exact (earlier k (hk.trans_le ht)).trans (under k hk)
+ refine ⟨desc,low,⟨?_,tailRows⟩⟩
+ intro v
+ change desc (row v) = childAddresses r.1 addr desc v
+ rw [earlier _ (bounds v).2,hit]
+ simp [childAddresses,fun u => low (addr u) (below u)]
+
+theorem descendant_preorder (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c)
+ (addr : N.Site → ℕ) (desc : ℕ → List ℕ) (trees : N.Site → VertexTree)
+ (old : ∀ v, (trees v).preorder = addr v :: desc (addr v)) (rows : DescLayers c r ptr addr desc) :
+ ∀ v, ((chainTrees c r ptr trees) v).preorder =
+ lastRowAddresses c ptr addr v :: desc (lastRowAddresses c ptr addr v) := by
+ induction c with
+ | done => exact old
+ | more t rec tail ih =>
+ apply ih r.2 ptr.2 (fun v => (ptr.1 v).1) (addTree r.1 ptr.1 trees) _ rows.2
+ intro v
+ change (ptr.1 v).1 :: (List.ofFn fun i => (trees ((r.1.order.children v).entries i).val).preorder).flatten =
+ (ptr.1 v).1 :: desc (ptr.1 v).1
+ rw [rows.1]
+ simp [childAddresses,old]
+
+/-- A single consistent descendant lookup suffices for the frozen selected
+execution. It gives empty leaf lists and the full root preorder on all rows. -/
+theorem selected_descendants {k : Type*} [Field k] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → R) (hκ : B.IsSolution κ) {n : ℕ} (T : ℕ)
+ (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n)
+ (z : (B.execute κ hκ T hT X).Choices) (base : ℕ) :
+ let E := B.execute κ hκ T hT X
+ let records := B.records κ hκ T hT X
+ let c := E.termChain records z
+ let r := selectedParsers B κ hκ T hT X z
+ let first := sitePointers B.recordLimit base (siteOrder X)
+ let ptr := chainPointers B.recordLimit c (branchOrders E records z)
+ (address B.recordLimit base (siteOrder X).length)
+ let roots := lastRowAddresses c ptr (fun v => (first v).1)
+ ∃ desc, (∀ v, desc (first v).1 = []) ∧ DescLayers c r ptr (fun v => (first v).1) desc ∧
+ ∀ v, ((chainTrees c r ptr (fun u => leafTree (first u))) v).preorder = roots v :: desc (roots v) ∧
+ (roots v :: desc (roots v)).Nodup := by
+ intro E records c r first ptr roots
+ obtain ⟨desc,initial,rows⟩ := extendLayers c r (branchOrders E records z) B.recordLimit
+ (address B.recordLimit base (siteOrder X).length) (fun v => (first v).1)
+ (fun v => (ptr_bounds (siteOrder X) B.recordLimit base v).2) (fun _ => [])
+ have leaf (v : X.network.Site) : desc (first v).1 = [] :=
+ initial _ (ptr_bounds (siteOrder X) B.recordLimit base v).2
+ have eqn := descendant_preorder c r ptr (fun v => (first v).1) desc (fun v => leafTree (first v))
+ (fun v => by rw [leaf]; rfl) rows
+ refine ⟨desc,leaf,rows,fun v => ⟨eqn v,?_⟩⟩
+ rw [← eqn v]
+ exact (selected_preorders B κ hκ T hT X z base).1 v
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairTypedVertexJobs.lean b/lean/OAI/Computability/VPVNP/PairTypedVertexJobs.lean
new file mode 100644
index 0000000000..abeaf6e383
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairTypedVertexJobs.lean
@@ -0,0 +1,364 @@
+import OAI.Computability.VPVNP.PairSimulationVertexJobs
+import OAI.Computability.VPVNP.PairPendingArguments
+import OAI.Computability.VPVNP.PairTraversalDisjoint
+
+/-!
+# Half-wire packets in the selected vertex traversal
+
+At a visit the input packet names the current row and contains its actual
+outgoing and incoming half-wire bits. Its children receive the old halves
+chosen by this occurrence, in placement-fiber order. Running the resulting
+jobs in preorder consumes the root and preserves every pending suffix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open NetworkKernel Compression NodeArguments
+open scoped Fin.CommRing
+
+variable {L : Type}
+
+/-- A visit guesses all child half-wires before reading the local kernel bits.
+At a cursor leaf, the local bits are the original validator's private choices. -/
+structure TypedVertexJob (L : Type) where
+ /-- The pending input packet consumed by this typed vertex job. -/
+ input : Packet
+ /-- Child argument packets produced by the job in the order expected by the DFS traversal. -/
+ children : List Packet
+ /-- Additional choice bits consumed locally by this job after its children's argument fields. -/
+ localBits : List Bool
+ /-- Histogram increment per parameter label contributed by this typed vertex job. -/
+ increment : L → ℕ
+
+/-- Erase the packet types to a plain vertex job while preserving the input node, concatenated
+child and local bits, and label increments. -/
+def TypedVertexJob.erase (j : TypedVertexJob L) : VertexJob L where
+ address := j.input.node
+ bits := j.children.flatMap Packet.bits ++ j.localBits
+ increment := j.increment
+
+/-- Consume the packet at the head of the frontier and prepend that visit's
+child packets. Equality of packets includes every bit of the old half-wires. -/
+inductive PacketVisits {L : Type} : List Packet → List (TypedVertexJob L) → List Packet → Prop
+ | nil (pending) : PacketVisits pending [] pending
+ | cons (j : TypedVertexJob L) {rest jobs final}
+ (tail : PacketVisits (j.children ++ rest) jobs final) :
+ PacketVisits (j.input :: rest) (j :: jobs) final
+
+theorem PacketVisits.append {u v w : List Packet} {xs ys : List (TypedVertexJob L)}
+ (h : PacketVisits u xs v) (g : PacketVisits v ys w) : PacketVisits u (xs ++ ys) w := by
+ induction h with
+ | nil => exact g
+ | cons j _ ih => exact .cons j (ih g)
+
+private theorem PacketVisits.forest {I : Type} (indices : List I) (packet : I → Packet)
+ (run : I → List (TypedVertexJob L))
+ (h : ∀ i rest, PacketVisits (packet i :: rest) (run i) rest) (suffix : List Packet) :
+ PacketVisits (indices.map packet ++ suffix) (indices.flatMap run) suffix := by
+ induction indices with
+ | nil => exact .nil _
+ | cons i rest ih => exact (h i _).append ih
+
+/-- Every currently pending packet occurs in order among the unvisited jobs
+and the untouched final suffix. -/
+theorem PacketVisits.pending_sublist {pending final : List Packet} {jobs : List (TypedVertexJob L)}
+ (h : PacketVisits pending jobs final) :
+ pending.Sublist (jobs.map TypedVertexJob.input ++ final) := by
+ induction h with
+ | nil => exact List.Sublist.refl _
+ | @cons j rest jobs final tail ih =>
+ exact .cons_cons _ ((List.sublist_append_right j.children rest).trans ih)
+
+/-- Readiness of the typed inputs before the corresponding native updates. -/
+def StoredVisits {w endAddr : ℕ} (A : Arena)
+ (update : TypedVertexJob L → DFS.Scratch w endAddr → DFS.Scratch w endAddr) :
+ List (TypedVertexJob L) → DFS.Scratch w endAddr → Prop
+ | [], _ => True
+ | j :: js, s => j.input.Stored A s ∧ StoredVisits A update js (update j s)
+
+/-- A hook may change any other private cells. Its updates agree with the
+child writes precisely on the intervals that are live after each visit. -/
+def PacketVisits.WritesAgree {w endAddr : ℕ} (A : Arena)
+ (update : TypedVertexJob L → DFS.Scratch w endAddr → DFS.Scratch w endAddr)
+ {pending final : List Packet} {jobs : List (TypedVertexJob L)}
+ (h : PacketVisits pending jobs final) (s : DFS.Scratch w endAddr) : Prop :=
+ match jobs, pending with
+ | [], _ => True
+ | j :: js, _ :: rest =>
+ (∀ q ∈ j.children ++ rest, ∀ i : Fin q.bits.length,
+ rawScratch (update j s) ((A.base q.node + i.val : ℕ) : BurstRAM.Word w) =
+ rawScratch (writePackets A j.children s) ((A.base q.node + i.val : ℕ) : BurstRAM.Word w)) ∧
+ @WritesAgree w endAddr A update (j.children ++ rest) final js
+ (by cases h with | cons _ tail => exact tail) (update j s)
+ | _ :: _, [] => False
+
+/-- The native update reads the exact input at every job and preserves the
+stored values of all pending siblings, including the final suffix. -/
+theorem PacketVisits.preparedAlong {pending final : List Packet} {jobs : List (TypedVertexJob L)}
+ {w endAddr : ℕ} (h : PacketVisits pending jobs final) (A : Arena)
+ (update : TypedVertexJob L → DFS.Scratch w endAddr → DFS.Scratch w endAddr)
+ (s : DFS.Scratch w endAddr) (format : Packet → Prop)
+ (hf : ∀ q ∈ jobs.map TypedVertexJob.input ++ final, format q ∧ q.Fits A w endAddr)
+ (hn : ((jobs.map TypedVertexJob.input ++ final).map Packet.node).Nodup)
+ (hs : PreparedPackets A format pending s) (ha : h.WritesAgree A update s) :
+ StoredVisits A update jobs s ∧
+ PreparedPackets A format final (jobs.foldl (fun old j => update j old) s) := by
+ induction h generalizing s with
+ | nil => exact ⟨trivial, hs⟩
+ | @cons j rest jobs final tail ih =>
+ have fit := fun q (hq : q ∈ jobs.map TypedVertexJob.input ++ final) =>
+ hf q (List.mem_cons_of_mem _ hq)
+ have nd := (List.nodup_cons.mp hn).2
+ have front := tail.pending_sublist
+ have childFit (q : Packet) (hq : q ∈ j.children) :=
+ fit q (front.subset (List.mem_append_left _ hq))
+ have next := preparedPackets_push A format j.input j.children rest s (update j s)
+ hs childFit ((front.map Packet.node).nodup nd) ha.1
+ obtain ⟨steps, last⟩ := ih (update j s) fit nd next ha.2
+ exact ⟨⟨(hs.2 _ List.mem_cons_self).2.2, steps⟩, last⟩
+
+variable {A : Type*} [CommRing A] [Fintype L] {κ : L → A} {N Y : Network}
+
+/-- Encode one old vertex's half-wires in the term parser's slot order. -/
+noncomputable def TermParsers.halfBits {t : Term A N} (r : TermParsers κ t) (u : N.Site)
+ (z : N.Half u) : List Bool :=
+ (half N u (r.order.outgoing u) (r.order.incoming u) r.payload).encode z
+
+/-- A packet for each old site in this particular placement fiber. The halves
+in the packet are those selected by this visit's placed assignment. -/
+noncomputable def TermParsers.childPackets {t : Term A N} (r : TermParsers κ t)
+ (previous : N.Site → ℕ) (v : t.output.Site) (a : Placed t.place N.Half v) : List Packet :=
+ List.ofFn fun j => let u := (r.order.children v).entries j
+ ⟨previous u.val, r.halfBits u.val (a u.val u.prop)⟩
+
+theorem TermParsers.childPackets_nodes {t : Term A N} (r : TermParsers κ t)
+ (previous : N.Site → ℕ) (v : t.output.Site) (a : Placed t.place N.Half v) :
+ (r.childPackets previous v a).map Packet.node =
+ List.ofFn fun j => previous ((r.order.children v).entries j).val := by
+ simp [TermParsers.childPackets, Function.comp_def]
+
+/-- For a state-indexed term parser this is the private arena's outgoing-then-
+incoming bit layout, with each incoming width taken at its matched source. -/
+theorem TermParsers.childPackets_state {d g : ℕ} (X : State d g) {t : Term A X.network}
+ (r : TermParsers κ t) (hp : r.payload = statePayload X)
+ (ho : ∀ u, r.order.outgoing u = outgoingOrder X u)
+ (hi : ∀ u, r.order.incoming u = incomingOrder X u)
+ (previous : X.network.Site → ℕ) (v : t.output.Site) (a : Placed t.place X.network.Half v) :
+ r.childPackets previous v a = List.ofFn fun j =>
+ let u := (r.order.children v).entries j
+ ⟨previous u.val, packed X u.val (a u.val u.prop)⟩ := by
+ unfold childPackets
+ congr 1
+ funext j
+ simp only [halfBits, hp, ho, hi, packed_eq_encode]
+
+open private fiber_encode from OAI.Computability.VPVNP.PairNodeArguments
+
+theorem TermParsers.nodeBits_eq_childPackets {t : Term A N} (r : TermParsers κ t)
+ (previous : N.Site → ℕ) (v : t.output.Site) (a : Placed t.place N.Half v)
+ (z : t.output.Half v) (x : (r.witness v a z).Choice) :
+ r.nodeBits v a z x =
+ (r.childPackets previous v a).flatMap Packet.bits ++ (r.read v a z).encode x := by
+ rw [TermParsers.nodeBits, fiber_encode]
+ simp [childPackets, halfBits, List.flatMap_def, Function.comp_def]
+
+/-- The supplied bits at the root of a subtree come from the parent or from the
+shared final wires. All internal packets are constructed from the selected halves. -/
+abbrev TypedJobsFor (P : SiteParsers κ N) :=
+ ∀ v z, List Bool → (P.witnesses v z).Choice → List (TypedVertexJob L)
+
+private def typedLeafJobs (P : SiteParsers κ N) (ptr : N.Site → ℕ × ℕ) : TypedJobsFor P :=
+ fun v z input p =>
+ [⟨⟨(ptr v).1, input⟩, [], (P.read v z).encode p, (P.witnesses v z).exponents p⟩]
+
+private noncomputable def typedPushJobs {t : Term A N} (r : TermParsers κ t)
+ (previous : N.Site → ℕ) (ptr : t.output.Site → ℕ × ℕ)
+ (P : SiteParsers κ N) (jobs : TypedJobsFor P) : TypedJobsFor (r.push P) :=
+ fun v z input p =>
+ let q := t.pushChoice P.factors P.witnesses r.witness v z p
+ ⟨⟨(ptr v).1, input⟩, r.childPackets previous v q.1, (r.read v q.1 z).encode q.2.2,
+ (r.witness v q.1 z).exponents q.2.2⟩ ::
+ (List.ofFn fun j => let u := (r.order.children v).entries j
+ let h := q.1 u.val u.prop
+ jobs u.val h (r.halfBits u.val h) (q.2.1 u)).flatten
+
+private structure TypedJobsSpec (P : SiteParsers κ N) (addr : N.Site → ℕ)
+ (typed : TypedJobsFor P) (jobs : JobsFor P) : Prop where
+ erases : ∀ v z input p, (typed v z input p).map TypedVertexJob.erase = jobs v z p
+ visits : ∀ v z input p suffix, PacketVisits (⟨addr v, input⟩ :: suffix) (typed v z input p) suffix
+
+private theorem typedLeafJobs_spec (P : SiteParsers κ N) (ptr : N.Site → ℕ × ℕ) :
+ TypedJobsSpec P (fun v => (ptr v).1) (typedLeafJobs P ptr) (leafJobs P ptr) where
+ erases _ _ _ _ := rfl
+ visits v z input p suffix :=
+ .cons ⟨⟨(ptr v).1, input⟩, [], (P.read v z).encode p, (P.witnesses v z).exponents p⟩
+ (.nil suffix)
+
+private theorem typedPushJobs_spec {t : Term A N} (r : TermParsers κ t)
+ (previous : N.Site → ℕ) (ptr : t.output.Site → ℕ × ℕ) (P : SiteParsers κ N)
+ (typed : TypedJobsFor P) (jobs : JobsFor P) (h : TypedJobsSpec P previous typed jobs) :
+ TypedJobsSpec (r.push P) (fun v => (ptr v).1) (typedPushJobs r previous ptr P typed)
+ (pushJobs r ptr P jobs) where
+ erases v z input p := by
+ simp only [typedPushJobs, pushJobs, List.map_cons, TypedVertexJob.erase,
+ ← r.nodeBits_eq_childPackets previous, List.map_flatten, List.map_ofFn, Function.comp_def,
+ h.erases]
+ visits v z input p suffix := by
+ let q := t.pushChoice P.factors P.witnesses r.witness v z p
+ let u := (r.order.children v).entries
+ let packet : Fin (r.order.children v).length → Packet := fun j =>
+ ⟨previous (u j).val, r.halfBits (u j).val (q.1 (u j).val (u j).prop)⟩
+ let run := fun j => typed (u j).val (q.1 (u j).val (u j).prop) (packet j).bits (q.2.1 (u j))
+ apply PacketVisits.cons ⟨⟨(ptr v).1, input⟩, List.ofFn packet, (r.read v q.1 z).encode q.2.2,
+ (r.witness v q.1 z).exponents q.2.2⟩
+ have result := PacketVisits.forest (List.ofFn id) packet run
+ (fun j rest => h.visits (u j).val _ _ _ rest) suffix
+ simpa only [List.flatMap_def, List.map_ofFn, Function.comp_id] using result
+
+private noncomputable def chainTypedJobs (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ptr : RowPointers c) (P : SiteParsers κ N) (addr : N.Site → ℕ) (typed : TypedJobsFor P) :
+ TypedJobsFor (finalParsers c r P) := by
+ induction c with
+ | done => exact typed
+ | more _ _ _ ih =>
+ exact ih r.2 ptr.2 (r.1.push P) (fun v => (ptr.1 v).1) (typedPushJobs r.1 addr ptr.1 P typed)
+
+/-- Addresses of the last selected rows, including the zero-step case. -/
+def lastRowAddresses {N Y : Network} (c : TermChain A N Y) (ptr : RowPointers c)
+ (initial : N.Site → ℕ) : Y.Site → ℕ :=
+ match c with
+ | .done _ => initial
+ | .more _ _ tail => lastRowAddresses tail ptr.2 (fun v => (ptr.1 v).1)
+
+private theorem chainTypedJobs_spec (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ptr : RowPointers c) (P : SiteParsers κ N) (addr : N.Site → ℕ)
+ (typed : TypedJobsFor P) (jobs : JobsFor P) (h : TypedJobsSpec P addr typed jobs) :
+ TypedJobsSpec (finalParsers c r P) (lastRowAddresses c ptr addr)
+ (chainTypedJobs c r ptr P addr typed) (chainJobs c r ptr P jobs) := by
+ induction c with
+ | done => exact h
+ | more _ _ _ ih => exact ih r.2 ptr.2 _ _ _ _ (typedPushJobs_spec r.1 addr ptr.1 P typed jobs h)
+
+/-- Construct the selected branch's typed vertex jobs by composing the cursor leaf jobs with
+all scheduled term layers and their row pointers. -/
+noncomputable def typedVertexJobs (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ptr : RowPointers c) (P : SiteParsers κ N) (leaves : N.Site → ℕ × ℕ) :
+ TypedJobsFor (finalParsers c r P) :=
+ chainTypedJobs c r ptr P (fun u => (leaves u).1) (typedLeafJobs P leaves)
+
+theorem typedVertexJobs_erases (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ptr : RowPointers c) (P : SiteParsers κ N) (leaves : N.Site → ℕ × ℕ) (v z input p) :
+ (typedVertexJobs c r ptr P leaves v z input p).map TypedVertexJob.erase =
+ vertexJobs c r ptr P leaves v z p :=
+ (chainTypedJobs_spec c r ptr P _ _ _ (typedLeafJobs_spec P leaves)).erases v z input p
+
+theorem typedVertexJobs_visits (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ptr : RowPointers c) (P : SiteParsers κ N) (leaves : N.Site → ℕ × ℕ) (v z input p suffix) :
+ PacketVisits (⟨lastRowAddresses c ptr (fun u => (leaves u).1) v, input⟩ :: suffix)
+ (typedVertexJobs c r ptr P leaves v z input p) suffix :=
+ (chainTypedJobs_spec c r ptr P _ _ _ (typedLeafJobs_spec P leaves)).visits v z input p suffix
+
+theorem typedVertexJobs_addresses (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ptr : RowPointers c) (P : SiteParsers κ N) (leaves : N.Site → ℕ × ℕ) (v z input p) :
+ (typedVertexJobs c r ptr P leaves v z input p).map (fun j => j.input.node) =
+ (chainTrees c r ptr (fun u => leafTree (leaves u)) v).preorder := by
+ have h := (vertexJobs_spec c r ptr P leaves).addresses v z p
+ rw [← typedVertexJobs_erases c r ptr P leaves v z input p, List.map_map] at h
+ exact h
+
+open private addTree from OAI.Computability.VPVNP.PairTraversalHistory
+
+theorem lastRowAddresses_eq_address (c : TermChain A N Y) (r : ChainParsers κ c)
+ (ptr : RowPointers c) (trees : N.Site → DFS.VertexTree) (v : Y.Site) :
+ lastRowAddresses c ptr (fun u => (trees u).address) v =
+ (chainTrees c r ptr trees v).address := by
+ induction c with
+ | done => rfl
+ | more _ _ _ ih => exact ih r.2 ptr.2 (addTree r.1 ptr.1 trees) v
+
+/-- With the actual stage-row addresses the native readiness theorem needs
+only disjointness from the externally supplied suffix. Within the selected
+tree all row addresses are distinct by the placement partition. -/
+theorem selectedTypedJobs_prepared {k : Type*} [Field k] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) {lanes : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) (base : ℕ) (P : SiteParsers f X.network) :
+ let E := B.execute f hf T hT X
+ let data := B.records f hf T hT X
+ let c := E.termChain data z
+ let r := selectedParsers B f hf T hT X z
+ let ptr := TraversalRows.chainPointers B.recordLimit c (branchOrders E data z)
+ (TraversalRows.address B.recordLimit base (siteOrder X).length)
+ let leaves := TraversalRows.sitePointers B.recordLimit base (siteOrder X)
+ ∀ v h, let bytes := packed (E.finalState z) v h
+ let tree := chainTrees c r ptr (fun u => leafTree (leaves u)) v
+ ∀ (p : ((finalParsers c r P).witnesses v h).Choice) (suffix : List Packet),
+ let jobs := typedVertexJobs c r ptr P leaves v h bytes p
+ let run := typedVertexJobs_visits c r ptr P leaves v h bytes p suffix
+ ∀ {w endAddr : ℕ} (A : Arena)
+ (update : TypedVertexJob B.Entry → DFS.Scratch w endAddr → DFS.Scratch w endAddr)
+ (s : DFS.Scratch w endAddr) (format : Packet → Prop),
+ List.Disjoint tree.preorder (suffix.map Packet.node) →
+ (∀ q ∈ jobs.map TypedVertexJob.input ++ suffix, format q ∧ q.Fits A w endAddr) →
+ PreparedPackets A format (⟨tree.address, bytes⟩ :: suffix) s →
+ run.WritesAgree A update s →
+ StoredVisits A update jobs s ∧
+ PreparedPackets A format suffix (jobs.foldl (fun old j => update j old) s) := by
+ intro E data c r ptr leaves v h bytes tree p suffix jobs run w endAddr arena update s fmt
+ hd hv hs ha
+ have same := lastRowAddresses_eq_address c r ptr (fun u => leafTree (leaves u)) v
+ change lastRowAddresses c ptr (fun u => (leaves u).1) v = tree.address at same
+ rw [← same] at hs
+ apply run.preparedAlong arena update s fmt hv _ hs ha
+ rw [List.map_append, List.map_map]
+ change (jobs.map (fun j => j.input.node) ++ suffix.map Packet.node).Nodup
+ rw [typedVertexJobs_addresses]
+ exact ((TraversalRows.selected_preorders B f hf T hT X z base).1 v).append
+ (List.nodup_cons.mp hs.1).2 hd
+
+section Cursor
+
+open CursorNetwork CursorRouting BurstRAM BurstRAM.PrivateRAM
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} {D e w p r k' base lanes : ℕ} [NeZero D]
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ (M : Machine w p r k') (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w)
+ (labels : Fin D ≃ Fin base ⊕ Fin lanes) (hD : 1 < D)
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+
+/-- The final network supplies one common payload per edge. Each final
+site starts with its actual packed halves, and thereafter each child uses
+exactly the old halves its own parent guessed. -/
+theorem selectedCursor_typedJobs :
+ let hpad := Nat.add_sub_of_le S.degree_bounds.1
+ let X := cursorState labels hD hpad (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ)
+ let E := B.execute f hf T hT X
+ let P := cursorSiteParsers M fuel initial header hw hc labels hD hpad f
+ ∀ z : E.Choices, let c := E.termChain (B.records f hf T hT X) z
+ let r := selectedParsers B f hf T hT X z
+ let Y := E.finalState z
+ ∀ (ptr : RowPointers c) (leaves : X.network.Site → ℕ × ℕ)
+ (edges : ∀ e : Y.network.Edge, Y.network.Payload e) (v : Y.network.Site),
+ let h := WireTensor.edgeAssignment Y.network.src Y.network.dst edges v
+ let bytes := packed Y v h
+ let tree := chainTrees c r ptr (fun u => leafTree (leaves u)) v
+ ∀ p : ((finalParsers c r P).witnesses v h).Choice,
+ let jobs := typedVertexJobs c r ptr P leaves v h bytes p
+ jobs.map TypedVertexJob.erase = vertexJobs c r ptr P leaves v h p ∧
+ ∀ suffix, PacketVisits (⟨tree.address, bytes⟩ :: suffix) jobs suffix := by
+ intro hpad X E P z c r Y ptr leaves edges v h bytes tree p jobs
+ refine ⟨typedVertexJobs_erases c r ptr P leaves v h bytes p, fun suffix => ?_⟩
+ rw [← lastRowAddresses_eq_address c r ptr (fun u => leafTree (leaves u)) v]
+ exact typedVertexJobs_visits c r ptr P leaves v h bytes p suffix
+
+end Cursor
+end PairSimulation.LocalHistory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexActiveGeometry.lean b/lean/OAI/Computability/VPVNP/PairVertexActiveGeometry.lean
new file mode 100644
index 0000000000..532d715894
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexActiveGeometry.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.PairVertexGeometryRun
+import OAI.Computability.VPVNP.PairNativeFrameFootprint
+import OAI.Computability.VPVNP.PairVertexSiteSegments
+
+/-! # Starting an actual nonterminal-ordinal call of the assembled vertex RAM -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM LiveProgram PrimedInputRAM TerminalSiteStart NativeOperands
+open scoped Fin.CommRing
+
+variable {W : ℕ}
+
+/-- Events of the active vertex entry, from testing the site ordinal through the two control
+ticks and the terminal site bootstrap. -/
+def startTrace (m : Memory W) (h : Word W) :=
+ guardTrace m h ++ [.tick,.tick] ++ bootTrace m h
+
+theorem start_cost (m : Memory W) (h : Word W) :
+ (startTrace m h).length = 44 ∧ countProbes (startTrace m h) = 9 ∧
+ choiceBits (startTrace m h) = [] ∧ after m (startTrace m h) = m := by
+ exact ⟨rfl,rfl,rfl,rfl⟩
+
+private theorem tick_after (m : Memory W) (n : ℕ) : after m (List.replicate n .tick) = m := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa only [List.replicate_succ,after,List.foldl_cons,update] using ih
+
+/-- The three observable quantities of the bootstrap and private operand
+initialization. All genuine external accesses in these two stages are reads. -/
+theorem active_geometry_cost (degree t : ℕ) (m : Memory W) (h : Word W) :
+ let es := startTrace m h ++ (NativeFrame.events degree h m ++ List.replicate (t+2) .tick)
+ es.length = t+degree+187 ∧ countProbes es = 15 ∧ choiceBits es = [] ∧ after m es = m := by
+ intro es
+ have s := start_cost m h
+ have g := VertexGeometry.charges degree h m t
+ refine ⟨?_,?_,?_,?_⟩
+ · rw [show es = _ from rfl,List.length_append,s.1,g.1]; omega
+ · rw [show es = _ from rfl,countProbes_append,s.2.1,g.2.1]
+ · rw [show es = _ from rfl,Flow.choiceBits_append,s.2.2.1,g.2.2]; rfl
+ · have app (mem : Memory W) (xs ys : List (Event W)) : after mem (xs++ys) = after (after mem xs) ys := List.foldl_append
+ rw [show es = _ from rfl,app,s.2.2.2,app,NativeFrame.events_after,tick_after]
+
+variable (c : Constants) (degree a b : ℕ) {p r : ℕ} {rootFields leaf shrink refresh : Segment}
+ (A : Placement (segments (VertexGeometry.segment c degree a b) rootFields leaf shrink refresh) p r)
+ {prog : UniversalMachine.Program} {B n H : ℕ} {i : Fin (2^(n^c.chainPower-1))}
+
+local notation "W₀" => CursorBounds.wordBits B n
+local notation "D₀" => CursorBounds.virtualBits B n
+local notation "E₀" => roundedUp 1 4 n
+local notation "g₀" => AssemblerPublic.geometry B n H
+
+variable (Q : PrimedInputRAM.Layout (CounterPublic.spec prog c |>.lengths n i)
+ n (addressWidth B n) H (CursorBounds.wordBits B n))
+ (D : PrimedCounter.Data Q (n^(c.circuitExponent+5)))
+
+/-- The ordinal guard, root-address load and complete geometry/cache
+initialization run from the real bootstrap entry. The unused tape, the
+pending root, and all saved coordinates are passed to the field gather. -/
+theorem active_geometry (hb : 0 < b) (hB : 1 ≤ B) (hn : 3 ≤ n) (hH : H = 2^roundedUp a b n)
+ (fit : PairNativeGeometry.Fits a b n W₀) (hp : Q.program = prog) (hbase : Q.scratchBase = 2^D₀)
+ (hf : D.Fits) (hroot : D.root.val = 0) (hw : 2 ≤ W₀) (hc : 2^D₀*2^E₀ < 2^W₀)
+ (M : Machine W₀ p r 11) (pub : M.publicData = Pieces.word g₀ (CounterPublic.actualPrefix prog) ∘ StageOperands.pair c)
+ (link : Contains A M) (m : Memory W₀) (start : Config W₀ p r)
+ (here : start.pc = A.entry .bootstrap)
+ (active : start.persistent < m (headerWord M.publicData+7).val)
+ (before : (M.publicData 6).val < NativeFrame.frameBase (NativeFrame.fromHeader degree M.publicData
+ (headerWord M.publicData) m))
+ (room : (NativeFrame.fromHeader degree M.publicData (headerWord M.publicData) m).cacheBase+38 ≤ 2^W₀) :
+ let h := headerWord M.publicData
+ ∃ t ≤ work (NativeCache.args c) a b g₀+76, ∃ boot out,
+ boot.persistent = start.persistent ∧
+ BootReady (M.publicData 6) h start.persistent m (boot.reg ∘ bootBank A) ∧
+ boot.privateMem = Function.update start.privateMem (M.publicData 6-1) (m (h+6).val + m (h+15).val*start.persistent) ∧
+ VertexGeometry.Ready c degree a b A m M.publicData boot out (LeafVisit.cacheWords D D₀ E₀) ∧
+ TerminalSiteStart.Continues M m start out
+ (startTrace m h ++ (NativeFrame.events degree h m ++ List.replicate (t+2) .tick)) := by
+ intro h
+ obtain ⟨boot,entry,persist,ready,mem,run⟩ := TerminalSiteStart.active_run (boot_startLinked A M link)
+ m start here active
+ have word : boot.reg (A.saved header) = h := ready.header
+ obtain ⟨t,ht,out,result,next⟩ := VertexGeometry.segment_run c degree a b A Q D hb hB hn hH fit hp hbase hf
+ hroot hw hc M pub link m boot entry (word ▸ before) (word ▸ room)
+ refine ⟨t,ht,boot,out,persist,ready,mem,result,?_⟩
+ have bootRun : TerminalSiteStart.Continues M m start boot (startTrace m h) := run
+ have len := (VertexGeometry.charges degree h m t).1
+ intro fuel bits
+ rw [List.length_append,Nat.add_comm (startTrace m h).length,← Nat.add_assoc,bootRun,len]
+ rw [show fuel + (t+degree+143) = fuel+t+degree+143 by omega,next,word]
+ simp only [Option.map_map,Function.comp_def,Flow.prependEvents,List.append_assoc]
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexActiveOccurrence.lean b/lean/OAI/Computability/VPVNP/PairVertexActiveOccurrence.lean
new file mode 100644
index 0000000000..9eae153250
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexActiveOccurrence.lean
@@ -0,0 +1,222 @@
+import OAI.Computability.VPVNP.PairVertexBurstReadback
+import OAI.Computability.VPVNP.PairVertexSelectedReport
+import OAI.Computability.VPVNP.PairVertexSelectedControl
+import OAI.Computability.VPVNP.PairSelectedRowChecks
+
+/-! # Exact transcripts of a complete active terminal vertex call -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM Compression DFS LocalHistory NetworkKernel NodeArguments TreeDecode
+ TraversalRows
+open CompressorRecords.SourceTransport TerminalFootprint
+open scoped Fin.CommRing
+
+variable {k K : Type*} [Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → K) (hκ : B.IsSolution κ) {lanes : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute κ hκ T hT X).Choices) (rowBase : ℕ)
+ {geometry rootFields leaf shrink refresh : Segment} {p r w g endAddr : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r) (M : Machine w p r 11)
+ (m : Memory w) (G offset : Word w) (base grammar src : ℕ) (order : Fin g ≃ B.Entry)
+ (P : SiteParsers κ X.network) (valid : List Packet → Scratch w endAddr → Prop)
+ (domain : Word w → Scratch w endAddr → Prop) (handlers : NodeDispatch.Role → HookParser w
+ endAddr)
+ (cost : VisitPath w endAddr → Prop)
+
+local notation "exec₀" => B.execute κ hκ T hT X
+local notation "data₀" => B.records κ hκ T hT X
+local notation "chain₀" => StateExecution.termChain (exec₀) (data₀) z
+local notation "readers₀" => selectedParsers B κ hκ T hT X z
+local notation "passes₀" =>
+ repeatReaders (blockReaders B κ hκ) _ T lanes (Eq.symm (Nat.add_sub_of_le hT)) X
+local notation "ptr₀" => selectedPointers B κ hκ T hT X z rowBase
+local notation "leaves₀" => sitePointers B.recordLimit rowBase (siteOrder X)
+local notation "trees₀" => selectedTrees B κ hκ T hT X z rowBase
+local notation "H₀" => TerminalLink.header M.publicData
+local notation "allow₀" => TerminalLink.workerCell (H₀)
+local notation "hook₀" => dispatcher handlers m offset
+local notation "hist₀" => privateHistogram order src
+local notation "guard₀" => JobGuard A M m (allow₀) cost
+local notation "final₀" => finalParsers (chain₀) (readers₀) P
+local notation "leafPackets₀" => (fun v y => Packet.mk (Prod.fst ((leaves₀) v)) (packed X v y))
+local notation "frames₀" =>
+ fromRows (chain₀) (readers₀) (ptr₀) (fun v => (Prod.fst ((leaves₀) v))) (packed
+ (StateExecution.finalState (exec₀) z))
+
+/-- Row obligations for the selected compressor execution, expressed in its
+actual states, address order, and packed half-wire buffers. -/
+structure SelectedChecks : Prop where
+ resident : ∀ node s, domain node s → ResidentGeometry s G offset (src : Word w)
+ remaining : ∀ s, valid [] s → ResidentGeometry s G offset (src : Word w)
+ head : HeadDomain valid domain
+ nativeRole : ∀ role, (handlers role).ExactOn
+ (fun node s => domain node s ∧ NodeDispatch.role (m (offset + node).val) = role)
+ M (A.entry (rolePart role)) (A.dfsPC 3) A.dfs m
+ leafDecode : Subtrees (hook₀) valid P (fun u => leafTree ((leaves₀) u)) (leafPackets₀)
+ leafEmit : Emits valid (hist₀) (guard₀) P (leafPackets₀) (leafJobs P (leaves₀))
+ passes : ExecutionChecks (hook₀) valid (hist₀) (guard₀) (exec₀) _ (passes₀) (data₀) z (ptr₀)
+ (fun u => ((leaves₀) u).1)
+
+private theorem sum_le_size {J : Type*} (f : J → ℕ) (xs : List J) (cap : ℕ) (h : ∀ x ∈ xs, f x ≤
+ cap) :
+ (xs.map f).sum ≤ xs.length * cap := by
+ induction xs with
+ | nil => simp
+ | cons x xs ih =>
+ simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.succ_mul]
+ exact (Nat.add_le_add (h _ List.mem_cons_self) (ih (fun i hi => h i (List.mem_cons_of_mem _
+ hi)))).trans_eq
+ (Nat.add_comm _ _)
+
+variable (linked : Contains A M)
+ (check : SelectedChecks B κ hκ T hT X z rowBase A M m G offset src order P valid domain
+ handlers cost)
+ (u : (((B.execute κ hκ T hT X)).finalState z).network.Site) (y : (((B.execute κ hκ T hT
+ X)).finalState z).network.Half u)
+ (start cfg : Config w p r) (pre : List (Event w))
+ (pref : TerminalSiteStart.Continues M m start cfg pre) (noChoice : choiceBits pre = [])
+ (noWrite : after m pre = m) (prefixReads : Reads ((TerminalLink.workerCell
+ ((TerminalLink.header M.publicData)))) pre) (persistent : cfg.persistent = start.persistent)
+ (atRoot : cfg.pc = A.dfsPC 0) (top : ℕ) (stack : Represents cfg.privateMem top
+ [((((selectedTrees B κ hκ T hT X z rowBase)) u).address : Word w)])
+ (endTop : top + 1 = endAddr) (sp : cfg.reg (A.dfs 5) = (top : Word w)) (endReg : cfg.reg
+ (A.dfs 6)
+ = (endAddr : Word w))
+ (one : cfg.reg (A.dfs 3) = 1) (zero : ∀ l, (privateHistogram order src) (scratch endAddr
+ cfg.privateMem) l = 0)
+ (prepared : valid [⟨(((selectedTrees B κ hκ T hT X z rowBase)) u).address, packed (((B.execute
+ κ hκ T hT X)).finalState z) u y⟩] (scratch endAddr cfg.privateMem))
+ (rows : AllRows w m B.recordLimit rowBase rowBase (selectedLayers B κ hκ T hT X z))
+ (space : rowBase + words B.recordLimit (selectedLayers B κ hκ T hT X z) ≤ ((TerminalLink.header
+ M.publicData)).val)
+ (hfit : (TerminalLink.header M.publicData).val + 31 < 2 ^ w)
+ (capacity : B.growthConstant ^ T ≤ endAddr)
+ (above : endAddr ≤ src) (hsrc : src + g < 2 ^ w) (hdst : base + grammar + g < 2 ^ w)
+ (cells : ∀ i : Fin g, TerminalLink.workerCell (TerminalLink.header M.publicData)
+ (base + grammar + i.val))
+ (hbase : M.publicData 4 = (base : Word w)) (hgrammar : M.publicData 5 = (grammar : Word w))
+ (hg : M.publicData 9 = (g : Word w))
+
+include linked check pref atRoot stack endTop sp endReg one prepared rows space hfit capacity
+
+/-- Starting at the bootstrap, any successful raw stream is the unique
+encoding of an occurrence. This covers arbitrary public cutoffs and all
+short, malformed, or surplus private choice tapes. -/
+theorem active_recover (fuel : ℕ) (bits : List Bool) (observed : Report w)
+ (returned : execute M.program fuel start m bits = some observed) :
+ ∃! x, bits = ((final₀).read u y).encode x := by
+ obtain ⟨control,visits,_,_,_,_⟩ := selected_control B κ hκ T hT X z rowBase m (H₀) endAddr
+ rows space hfit capacity u
+ have leafEq : (frames₀).1 = leafPackets₀ := by
+ funext v z'
+ exact selected_inputPacked B κ hκ T hT X z (ptr₀) _ v z'
+ obtain ⟨steps,_⟩ := execution_checks (hook₀) valid (hist₀) (guard₀) (exec₀) _ (passes₀) (data₀) z
+ (ptr₀) _ (execute_readerOrders B κ hκ T hT X) check.passes
+ have accept := returns_iff_occurrence A M linked G offset (src : Word w) m domain valid
+ check.resident check.head handlers check.nativeRole (chain₀) (readers₀) (ptr₀) (frames₀).2
+ P (leaves₀) (frames₀).1 (fun v z' => fromRows_inputAddress _ _ _ _ _ v z') (fromRows_pointers
+ ..) (leafEq ▸ check.leafDecode) steps
+ u y cfg atRoot top (((trees₀) u).address : Word w) stack endTop sp endReg one control visits
+ ((selected_rootPacket B κ hκ T hT X z rowBase u y).symm ▸ prepared)
+ exact (prefix_occurrences _ pref accept bits).mp ⟨fuel,observed,returned⟩
+
+include noChoice noWrite prefixReads persistent zero above hsrc hdst cells hbase hgrammar hg
+
+/-- The whole source call executes the chosen occurrence and flushes its
+actual exponents. The clock bound uses the number of rows of this selected
+tree and the time bound of each local body. The read support excludes the
+two cells written by the enclosing phase controller. -/
+theorem active_occurrence_costs (maxTicks fuel : ℕ) (small : ∀ j, cost j → j.trace.length ≤
+ maxTicks)
+ (room : pre.length + (15 + maxTicks) * (chain₀).occurrences (fun _ => 1) u + 7 * g + 46 ≤ fuel)
+ (x : ((final₀).witnesses u y).Choice) :
+ let code := ((final₀).read u y).encode x
+ let powers := fun j : Fin g => ((final₀).witnesses u y).exponents x (order j)
+ ∃ rep : Report w, execute M.program fuel start m code = some rep ∧
+ rep.result = some (start.persistent + 1) ∧ choiceBits rep.events = code ∧
+ after m rep.events = Counters.addHistogram base grammar powers m ∧
+ Reads (allow₀) rep.events ∧ rep.events.length + 31 ≤ fuel ∧
+ ∃ native : List (VisitPath w endAddr),
+ native.length = ((trees₀) u).preorder.length ∧ (∀ j ∈ native, cost j) ∧
+ countProbes rep.events + 1 = countProbes pre + 3 * native.length +
+ (native.map (fun j => countProbes j.trace)).sum + 2 * g ∧
+ rep.events.length + 4 = pre.length + 15 * native.length +
+ (native.map (fun j => j.trace.length)).sum + 7 * g + 14 := by
+ intro code powers
+ obtain ⟨control,visits,reads,nodes,time,probes⟩ := selected_control B κ hκ T hT X z rowBase m
+ (H₀) endAddr
+ rows space hfit capacity u
+ have leafEq : (frames₀).1 = leafPackets₀ := by
+ funext v z'
+ exact selected_inputPacked B κ hκ T hT X z (ptr₀) _ v z'
+ obtain ⟨_,layers⟩ := execution_checks (hook₀) valid (hist₀) (guard₀) (exec₀) _ (passes₀) (data₀) z
+ (ptr₀) _ (execute_readerOrders B κ hκ T hT X) check.passes
+ obtain ⟨native,rep,effects,result,bits,memory,ticks,bodyProbes,support,run⟩ :=
+ occurrence_report A M linked m (allow₀) cost valid order base grammar src G offset (chain₀)
+ (readers₀)
+ (ptr₀) (frames₀).2 P (frames₀).1 (leaves₀) (leafEq ▸ check.leafEmit) layers u y x cfg atRoot
+ top
+ (((trees₀) u).address : Word w) stack endTop sp endReg one control visits
+ ((selected_rootPacket B κ hκ T hT X z rowBase u y).symm ▸ prepared) check.remaining zero
+ reads cells
+ above hsrc hdst hbase hgrammar hg
+ have addr := (vertexJobs_spec (chain₀) (readers₀) (ptr₀) P (leaves₀)).addresses u y x
+ have len : native.length = ((trees₀) u).preorder.length :=
+ effects.realized.length_eq.symm.trans (by simpa using congrArg List.length addr)
+ have sizes : ∀ j ∈ native, cost j := fun j hj => (effects.framed j hj).2.2.2
+ have sum := sum_le_size (fun j : VisitPath w endAddr => j.trace.length) native maxTicks (fun j
+ hj => small j (sizes j hj))
+ have total : pre.length + rep.events.length + 31 ≤ fuel := by
+ rw [len] at sum
+ calc
+ _ ≤ pre.length + (15 + maxTicks) * ((trees₀) u).preorder.length + 7 * g + 46 := by
+ rw [Nat.add_mul, Nat.mul_comm maxTicks _]
+ omega
+ _ ≤ pre.length + (15 + maxTicks) * (chain₀).occurrences (fun _ => 1) u + 7 * g + 46 := by
+ gcongr
+ _ ≤ fuel := room
+ have emit := emit_at_cutoff pref noWrite noChoice rep code bits run fuel (by omega)
+ refine ⟨⟨pre ++ rep.events,rep.result⟩,emit.1,result.trans (by rw [persistent]),emit.2.1,
+ emit.2.2.1.trans memory,reads_append prefixReads support,by simpa only [List.length_append]
+ using total,
+ native,len,sizes,?_,?_⟩
+ · change countProbes (pre ++ rep.events) + 1 = _
+ rw [countProbes_append,bodyProbes,len]
+ omega
+ · change (pre ++ rep.events).length + 4 = _
+ rw [List.length_append,ticks,len]
+ omega
+
+/-- The successful source report at the caller's public cutoff. -/
+theorem active_occurrence (maxTicks fuel : ℕ) (small : ∀ j, cost j → j.trace.length ≤ maxTicks)
+ (room : pre.length + (15 + maxTicks) * (chain₀).occurrences (fun _ => 1) u + 7 * g + 46 ≤ fuel)
+ (x : ((final₀).witnesses u y).Choice) :
+ let code := ((final₀).read u y).encode x
+ let powers := fun j : Fin g => ((final₀).witnesses u y).exponents x (order j)
+ ∃ rep : Report w, execute M.program fuel start m code = some rep ∧
+ rep.result = some (start.persistent + 1) ∧ choiceBits rep.events = code ∧
+ after m rep.events = Counters.addHistogram base grammar powers m ∧
+ Reads (allow₀) rep.events ∧ rep.events.length + 31 ≤ fuel ∧
+ ∃ native : List (VisitPath w endAddr),
+ native.length = ((trees₀) u).preorder.length ∧ (∀ j ∈ native, cost j) ∧
+ countProbes rep.events + 1 = countProbes pre + 3 * native.length +
+ (native.map (fun j => countProbes j.trace)).sum + 2 * g := by
+ obtain ⟨rep,run,result,bits,memory,reads,space,native,len,sizes,probes,_⟩ :=
+ active_occurrence_costs B κ hκ T hT X z rowBase A M m G offset base grammar src order P valid
+ domain handlers cost linked check u y start cfg pre pref noChoice noWrite prefixReads
+ persistent
+ atRoot top stack endTop sp endReg one zero prepared rows space hfit capacity above hsrc hdst
+ cells
+ hbase hgrammar hg maxTicks fuel small room x
+ exact ⟨rep,run,result,bits,memory,reads,space,native,len,sizes,probes⟩
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexActiveRoot.lean b/lean/OAI/Computability/VPVNP/PairVertexActiveRoot.lean
new file mode 100644
index 0000000000..9f69cbf59c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexActiveRoot.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PairVertexRootFieldsReady
+import OAI.Computability.VPVNP.PairVertexActiveGeometry
+import OAI.Computability.VPVNP.PairTerminalGatherReadSafety
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-!
+# The active vertex call reaches DFS with the terminal root
+
+This prefix uses the concrete bootstrap, geometry/cache initializer and
+root gather in a single installed table. The wire bits are supplied by the
+shared scan. All external actions of this prefix read memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM LiveProgram PrimedInputRAM NativeOperands Compression
+open TerminalSiteStart TerminalRootGather LeafSourceLoad CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+variable (c : Constants) (degree a b : ℕ) {p r : ℕ} {leaf shrink refresh : Segment}
+ (A : Placement (segments (VertexGeometry.segment c degree a b) TerminalRootGather.segment leaf shrink refresh) p r)
+ {prog : UniversalMachine.Program} {B n H : ℕ} {i : Fin (2^(n^c.chainPower-1))}
+
+local notation "W₀" => CursorBounds.wordBits B n
+local notation "D₀" => CursorBounds.virtualBits B n
+local notation "E₀" => roundedUp 1 4 n
+local notation "g₀" => AssemblerPublic.geometry B n H
+
+variable (Q : PrimedInputRAM.Layout (CounterPublic.spec prog c |>.lengths n i)
+ n (addressWidth B n) H (CursorBounds.wordBits B n))
+ (D : PrimedCounter.Data Q (n^(c.circuitExponent+5))) (M : Machine (CursorBounds.wordBits B n) p r 11)
+ (m : Memory (CursorBounds.wordBits B n)) (start : Config (CursorBounds.wordBits B n) p r) {ex lanes : ℕ} (X : State ex lanes) (u : X.network.Site)
+ (f : Fin (∑ j, TerminalPrefix.width X j) → Bool)
+
+local notation "hdr" => headerWord M.publicData
+local notation "N" => Fin.val (M.publicData 6)
+local notation "area" => NativeFrame.fromHeader degree M.publicData hdr m
+local notation "lay" => TerminalRootGather.Layout.ofHeader degree M.publicData hdr start.persistent m
+local notation "packet" => VertexRootPacket.packet X lay u f
+local notation "role" => m (Fin.val (hdr+14))
+local notation "cache" => LeafVisit.cacheWords D D₀ E₀
+
+/-- The linked register bank, typed root argument and private resident fields
+at the first DFS instruction. Its specification uses the physical word width
+and operand values directly. -/
+structure ActiveRootState {S : Part → Segment} {W p r : ℕ} (A : Placement S p r) (out : Config W p r)
+ (ordinal endWord roleWord : Word W) (R : LeafArena.Regions) (q : NodeArguments.Packet)
+ (leafWords : Fin 10 → Word W) (fields : Fin 12 → Word W) (vals : LeafSourceLoad.Static 34 → Word W) : Prop where
+ pc : out.pc = A.dfsPC 0
+ persistent : out.persistent = ordinal
+ one : out.reg (A.dfs 3) = 1
+ top : out.reg (A.dfs 5) = endWord-1
+ endReg : out.reg (A.dfs 6) = endWord
+ roleOffset : out.reg (A.saved VertexImage.roleOffset) = roleWord
+ histogram : out.reg (A.saved histBase) = (R.histBase : Word W)
+ fits : q.Fits R.arguments W endWord.val
+ stored : q.Stored R.arguments (DFS.scratch endWord.val out.privateMem)
+ resident : VertexRootFields.Resident R endWord.val (endWord.val-1) [(q.node : Word W)]
+ leafWords fields vals out.privateMem
+
+attribute [local irreducible] NativeOperands.capacity NativeOperands.saved VertexGeometry.segment
+ CursorBounds.wordBits CursorBounds.virtualBits TerminalRootGather.segment
+
+theorem active_root (hb : 0 < b) (hB : 1 ≤ B) (hn : 3 ≤ n) (hH : H = 2^roundedUp a b n)
+ (fit : PairNativeGeometry.Fits a b n W₀) (hp : Q.program = prog) (hbase : Q.scratchBase = 2^D₀)
+ (hf : D.Fits) (hroot : D.root.val = 0) (hw : 2 ≤ W₀) (hc : 2^D₀*2^E₀ < 2^W₀)
+ (pub : M.publicData = Pieces.word g₀ (CounterPublic.actualPrefix prog) ∘ StageOperands.pair c)
+ (link : Contains A M) (here : start.pc = A.entry .bootstrap) (fresh : start.privateMem = fun _ => 0)
+ (active : start.persistent < m (hdr+7).val) (rootPos : 0 < (lay).root)
+ (rootBound : (lay).root < (area).nodes) (room : (area).cacheBase+38 ≤ 2^W₀)
+ (num : TerminalGatherGeometry.Numbering X lay u) (rows : TerminalGatherGeometry.Rows X lay m)
+ (bits : ∀ j, m ((lay).wires+j.val) = PrivateFields.bitValue W₀ (f j))
+ (gatherFit : (lay).Fits m) (deg : 2^ex ≤ degree) (width : X.maxWireWidth ≤ N)
+ (headerFit : (headerWord M.publicData).val + 31 < 2^W₀)
+ (heads : ∀ h ∈ [(lay).incomingHead,(lay).widthHead,(lay).prefixHead], h+TerminalPrefix.arcCount X ≤ (hdr).val)
+ (wires : (lay).wires+X.totalWidth ≤ (hdr).val) :
+ ∃ t ≤ work (NativeCache.args c) a b g₀+76, ∃ out : Config W₀ p r, ∃ es : List (Event W₀),
+ ActiveRootState A out start.persistent (M.publicData 6) role area packet
+ (NativeFrame.leafWords degree M.publicData hdr role m) (NativeFrame.fields degree M.publicData hdr role m) cache ∧
+ es.length = t+degree+187+(15+21*(2^ex)+5*(packet).bits.length) ∧
+ countProbes es = 15+(5*(2^ex)+(packet).bits.length) ∧
+ choiceBits es = [] ∧ after m es = m ∧ Reads (TerminalLink.workerCell hdr) es ∧
+ Prefix M m start es out := by
+ have hnval : N = n := by rw [pub]; exact Nat.mod_eq_of_lt (PrimedInputRAM.Opcodes.pubNat_lt Q hf.assembler 1)
+ have hnpos : 0 < N := by rw [hnval]; omega
+ have before : N < NativeFrame.frameBase area := by
+ have h₁ : N < (lay).dest := Nat.lt_add_of_pos_right (Nat.mul_pos rootPos (Nat.succ_pos _))
+ have h₂ := (area).node_before rootBound
+ change (lay).dest+(area).arguments.stride ≤ (area).histBase at h₂
+ change N < (area).histBase+(area).histWords; omega
+ obtain ⟨t,ht,boot,geo,persist,booted,bootMem,prepared,headRun⟩ :=
+ active_geometry c degree a b A Q D hb hB hn hH fit hp hbase hf hroot hw hc M pub link m start here active before room
+ have support := TerminalGatherGeometry.worker_readable num rows hdr headerFit heads wires
+ obtain ⟨out,tail,done,st,dfs,saved,_,placed,cost,readTail,runTail⟩ :=
+ image_run_reads A rfl M link lay m gatherFit geo prepared.pc (VertexRootFields.saved booted prepared)
+ (Fin.cast_val_eq_self _).symm (VertexRootFields.stride booted prepared) _ support
+ obtain ⟨packetFit,stored,resident⟩ := VertexRootFields.ready_of_placed f booted prepared (fresh ▸ bootMem)
+ num rows bits gatherFit hnpos rootPos rootBound deg width room out placed
+ have hrole : boot.reg (A.saved VertexImage.roleOffset) = role := booted.roleOffset
+ have hhead : boot.reg (A.saved header) = hdr := booted.header
+ rw [hrole] at resident
+ have readyState : ActiveRootState A out start.persistent (M.publicData 6) role area packet
+ (NativeFrame.leafWords degree M.publicData hdr role m) (NativeFrame.fields degree M.publicData hdr role m) cache := by
+ refine ⟨done,st.trans (prepared.persistent.trans persist),(dfs 3).trans ((prepared.dfs 3).trans booted.one),
+ (dfs 5).trans ((prepared.dfs 5).trans booted.top),(dfs 6).trans ((prepared.dfs 6).trans booted.stackEnd),
+ (saved _).trans ((prepared.saved _ (by decide)).trans hrole),?_,packetFit,stored,resident⟩
+ exact (saved histBase).trans (hhead ▸ prepared.hist)
+ let pre := startTrace m hdr ++ (NativeFrame.events degree hdr m ++ List.replicate (t+2) .tick)
+ obtain ⟨hTime,hProbe,hBits,hMem⟩ := active_geometry_cost degree t m hdr
+ have hread := active_geometry_reads m hdr degree t headerFit
+ have len : ((lay).packet m).length = (packet).bits.length := by
+ rw [TerminalGatherGeometry.packet_eq num rows f bits,List.length_map]; rfl
+ have head : Prefix M m start pre geo := headRun
+ refine ⟨t,ht,out,pre++tail,readyState,?_,?_,?_,?_,TerminalFootprint.reads_append hread readTail,head.trans runTail⟩
+ · rw [List.length_append,hTime,cost.time,num.degree,len]
+ · rw [countProbes_append,hProbe,cost.probes,num.degree,len]
+ · rw [Flow.choiceBits_append,hBits,cost.bits]; rfl
+ · rw [after,List.foldl_append]
+ change after (after m pre) tail = m
+ rw [hMem,cost.after_eq]
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexAscendingCosts.lean b/lean/OAI/Computability/VPVNP/PairVertexAscendingCosts.lean
new file mode 100644
index 0000000000..ce9d5421b7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexAscendingCosts.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.PairVertexOrdinalPhase
+
+/-! # Occurrence-specific bounds on the physical ordinal report sequence -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM CompressorRecords TerminalLink NetworkKernel LocalHistory
+open scoped Fin.CommRing
+open private closedRun closedRun_cons from OAI.Computability.VPVNP.PairVertexAscendingPaths
+
+variable {w n g fuel base grammar : ℕ} {D : IndexedSites n g} {C : Type*} {P : BurstRAM.Program w C}
+ {pub : Fin 11 → Word w} {Frame : ℕ → Memory w → Prop}
+
+private theorem checked_suffix (H : ActiveCalls D P fuel base grammar Frame) (close : Closes P fuel n pub Frame)
+ (ok : (i : Fin n) → D.Choice i → Report w → Prop)
+ (check : ∀ i m, Frame i.val m → ∀ x r,
+ execute P fuel (P.start (i.val : Word w)) m (D.encode i x) = some r → ok i x r)
+ {k start : ℕ} (site : Fin k → Fin n) (aligned : ∀ i, (site i).val=start+i.val) (ending : start+k=n)
+ (m : Memory w) (hm : Frame start m) (x : ∀ i, D.Choice (site i)) :
+ let last := Counters.visit base grammar id (List.ofFn fun i => D.powers (site i) (x i)) m
+ ∃ reps : Fin k → Report w, (∀ i, ok (site i) (x i) (reps i)) ∧
+ closedRun P fuel start m ((List.ofFn fun i => D.encode (site i) (x i)) ++ [[]])
+ (List.ofFn reps ++ [closingReport pub last]) last := by
+ induction k generalizing start m with
+ | zero =>
+ simp only [Nat.add_zero] at ending
+ subst start
+ have call := close m hm []
+ simp only [ite_true] at call
+ refine ⟨Fin.elim0,fun i => Fin.elim0 i,?_⟩
+ simp [closedRun,runSegment,call,endState,eventLog,Counters.visit,closingReport_after]
+ rfl
+ | succ k ih =>
+ have hz : (site 0).val = start := by simpa using aligned 0
+ obtain ⟨head,call,next,mem⟩ := H.emit (site 0) m (hz ▸ hm) (x 0)
+ have good := check (site 0) m (hz ▸ hm) (x 0) head call
+ have keep := H.preserve (site 0) m (hz ▸ hm) (x 0)
+ rw [hz,←mem] at keep
+ rw [hz] at call next
+ obtain ⟨tail,ht,run⟩ := ih (fun i => site i.succ)
+ (fun i => by rw [aligned,Fin.val_succ]; omega) (by omega) (after m head.events) keep (fun i => x i.succ)
+ refine ⟨Fin.cons head tail,Fin.cases good (fun j => ht j),?_⟩
+ simp only [List.ofFn_succ,List.cons_append,Fin.cons_zero,Fin.cons_succ,Counters.visit,List.foldl_cons,id_eq]
+ rw [←mem]
+ exact closedRun_cons call next run
+
+/-- The exact emitted list can be indexed by its natural ordinal, so the
+cost certificate for each report can depend on that very site's occurrence. -/
+theorem ascending_checked (H : ActiveCalls D P fuel base grammar Frame) (close : Closes P fuel n pub Frame)
+ (ok : (i : Fin n) → D.Choice i → Report w → Prop)
+ (check : ∀ i m, Frame i.val m → ∀ x r,
+ execute P fuel (P.start (i.val : Word w)) m (D.encode i x) = some r → ok i x r)
+ (m : Memory w) (hm : Frame 0 m) (x : ∀ i, D.Choice i) :
+ ∃ reps : Fin n → Report w, (∀ i, ok i (x i) (reps i)) ∧ runSegment P fuel (some 0) m (D.calls x) =
+ some (List.ofFn reps ++ [closingReport pub (D.finalMemory base grammar m x)]) := by
+ obtain ⟨reps,h,run⟩ := checked_suffix H close ok check id (fun _ => by simp) (Nat.zero_add n) m hm x
+ exact ⟨reps,h,by simpa only [Nat.cast_zero,id_eq,IndexedSites.calls,IndexedSites.finalMemory] using run.1⟩
+
+variable {R : Type*} [CommRing R] {Label : Type} [Fintype Label] {κ : Label → R} {N : Network}
+ (parsers : SiteParsers κ N) (order : Fin n ≃ N.Site) (names : Fin g ≃ Label) (half : ∀ v, N.Half v)
+ (F : DescriptorSpace.Shape) (limit : ℕ) {geometry rootFields leaf shrink refresh : Segment}
+ (src phy : Memory w)
+local notation "site" => siteOrdinals parsers order names half
+local notation "body" => segments geometry rootFields leaf shrink refresh
+local notation "worker" => Machine.program (Template.instantiate (template body) w pub)
+
+/-- The completed physical vertex block contains exactly the same reports
+as the ordinal-indexed source workers, plus their terminal guard. -/
+theorem physicalSite_rows (native : ActiveCalls site worker fuel base grammar Frame) (clock : 15 ≤ fuel)
+ (ready : Frame 0 src) (stored : ∀ m, Frame n m → m (TerminalSiteStart.headerWord pub+7).val = (n : Word w))
+ (transport : WorkerFrame (TerminalProgram.workers F limit body) pub fuel (.resume Stage.vertices 0) src phy)
+ (x : ∀ v, (parsers.witnesses v (half v)).Choice)
+ (ok : N.Site → Report w → Prop)
+ (check : ∀ i m, Frame i.val m → ∀ (c : (site).Choice i) r,
+ execute worker fuel ((worker).start (i.val : Word w)) m ((site).encode i c) = some r → ok (order i) r) :
+ let block := sitePhysical parsers order names half F limit src phy native clock ready stored transport x
+ ∃ reps : N.Site → Report w, (∀ v, ok v (reps v)) ∧ block.val.logs.map Prod.snd =
+ (List.ofFn fun i => reps (order i)) ++ [closingReport pub ((site).finalMemory base grammar src (fun i => x (order i)))] := by
+ intro block
+ let p := sitePathsEquiv parsers order names half native clock stored src ready x
+ obtain ⟨reps,checked,run⟩ := ascending_checked native (template_closes clock stored)
+ (fun i _ r => ok (order i) r) check src ready (fun i => x (order i))
+ have eqn := Option.some.inj (p.property.choose_spec.1.symm.trans run)
+ refine ⟨fun v => reps (order.symm v),fun v => by simpa only [Equiv.apply_symm_apply] using checked (order.symm v),?_⟩
+ change (stageLogs (.resume Stage.vertices 0) p.property.choose).map Prod.snd = _
+ exact (stageLogs_raw _ _).trans (eqn.trans (by simp only [Equiv.symm_apply_apply]))
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexAscendingPaths.lean b/lean/OAI/Computability/VPVNP/PairVertexAscendingPaths.lean
new file mode 100644
index 0000000000..6a00b490ae
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexAscendingPaths.lean
@@ -0,0 +1,349 @@
+import OAI.Computability.VPVNP.PairVertexSiteSegments
+import OAI.Computability.VPVNP.PairSimulationHistoryBounds
+import OAI.Computability.VPVNP.PairSimulationTerminalSplice
+
+/-!
+# Ascending calls of the final vertex worker
+
+Each physical vertex ordinal consumes one occurrence tape and adds the occurrence's
+exponents to the external histogram. A final empty call checks the exhausted ordinal.
+This fold retains the actual reports and excludes incomplete or overlong call lists.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM LocalHistory NetworkKernel
+open scoped Fin.CommRing
+
+variable {w n g : ℕ} {C : Type*}
+
+/-- Occurrence types, tapes and dense exponent coordinates in physical site order. -/
+structure IndexedSites (n g : ℕ) where
+ /-- The type of local computation choices at each final site ordinal. -/
+ Choice : Fin n → Type
+ /-- Encode a choice at one site as the part of the choice tape consumed by that vertex. -/
+ encode : (i : Fin n) → Choice i → List Bool
+ injective : ∀ i, Function.Injective (encode i)
+ /-- Histogram exponents contributed by a site's choice, indexed by the common parameter
+ labels. -/
+ powers : (i : Fin n) → Choice i → Fin g → ℕ
+
+/-- Native facts for one active ordinal on the fixed arc assignment. The frame
+carries the descriptor words and the invariant needed for the next call. -/
+structure ActiveCalls (D : IndexedSites n g) (P : BurstRAM.Program w C) (fuel base grammar : ℕ)
+ (Frame : ℕ → Memory w → Prop) : Prop where
+ emit : ∀ i m, Frame i.val m → ∀ x : D.Choice i, ∃ rep,
+ execute P fuel (P.start (i.val : Word w)) m (D.encode i x) = some rep ∧
+ rep.result = some ((i.val + 1 : ℕ) : Word w) ∧
+ after m rep.events = Counters.addHistogram base grammar (D.powers i x) m
+ recover : ∀ i m, Frame i.val m → ∀ bs rep,
+ execute P fuel (P.start (i.val : Word w)) m bs = some rep → ∃ x, bs = D.encode i x
+ preserve : ∀ i m, Frame i.val m → ∀ x, Frame (i.val + 1)
+ (Counters.addHistogram base grammar (D.powers i x) m)
+
+/-- Report produced by the equal-ordinal branch, including its header read. -/
+def closingReport (pub : Fin 11 → Word w) (m : Memory w) : Report w :=
+ ⟨TerminalSiteStart.guardTrace m (TerminalSiteStart.headerWord pub) ++ [.tick], none⟩
+
+theorem closingReport_after (pub : Fin 11 → Word w) (m : Memory w) :
+ after m (closingReport pub m).events = m := rfl
+
+variable {D : IndexedSites n g} {P : BurstRAM.Program w C} {fuel base grammar : ℕ}
+ {Frame : ℕ → Memory w → Prop} (H : ActiveCalls D P fuel base grammar Frame)
+ {pub : Fin 11 → Word w}
+
+/-- The native sentinel's unique tape and report at the specified call clock. -/
+def Closes (P : BurstRAM.Program w C) (fuel n : ℕ) (pub : Fin 11 → Word w)
+ (Frame : ℕ → Memory w → Prop) : Prop :=
+ ∀ m, Frame n m → ∀ bs, execute P fuel (P.start (n : Word w)) m bs =
+ if bs = [] then some (closingReport pub m) else none
+
+variable {geometry rootFields leaf shrink refresh : Segment}
+local notation "S" => segments geometry rootFields leaf shrink refresh
+
+/-- The assembled worker's bootstrap supplies the closing call at every fuel ≥ 15. -/
+theorem template_closes (room : 15 ≤ fuel)
+ (stored : ∀ m, Frame n m → m (TerminalSiteStart.headerWord pub + 7).val = (n : Word w)) :
+ Closes (((template S).instantiate w pub).program) fuel n pub Frame := by
+ intro m hm bs
+ let M := (template S).instantiate w pub
+ let A := placement S
+ let c := M.program.start (n : Word w)
+ have eqn := TerminalSiteStart.equal_run
+ (boot_startLinked A M (template_contains S pub)) m c rfl (stored m hm).symm (fuel - 15) bs
+ dsimp only at eqn
+ rw [Nat.sub_add_cancel room] at eqn
+ rw [eqn]
+ split <;> rfl
+
+private def closedRun (P : BurstRAM.Program w C) (fuel ord : ℕ) (m : Memory w)
+ (bs : List (List Bool)) (rs : List (Report w)) (last : Memory w) : Prop :=
+ runSegment P fuel (some (ord : Word w)) m bs = some rs ∧
+ endState (some (ord : Word w)) rs = none ∧ after m (eventLog rs) = last
+
+private theorem closedRun_cons {i : ℕ} {m last : Memory w} {b : List Bool}
+ {bs : List (List Bool)} {r : Report w} {rs : List (Report w)}
+ (call : execute P fuel (P.start (i : Word w)) m b = some r)
+ (next : r.result = some ((i + 1 : ℕ) : Word w))
+ (tail : closedRun P fuel (i + 1) (after m r.events) bs rs last) :
+ closedRun P fuel i m (b :: bs) (r :: rs) last := by
+ obtain ⟨run,halt,mem⟩ := tail
+ refine ⟨by simp only [runSegment, call, next, run, Option.map_some], by simpa only [endState, next] using halt, ?_⟩
+ change after m (r.events ++ eventLog rs) = last
+ exact (List.foldl_append ..).trans mem
+
+include H in
+private theorem emit_suffix (close : Closes P fuel n pub Frame)
+ (ok : Report w → Prop)
+ (checks : ∀ i m, Frame i.val m → ∀ (x : D.Choice i) r,
+ execute P fuel (P.start (i.val : Word w)) m (D.encode i x) = some r → ok r)
+ {k start : ℕ} (site : Fin k → Fin n)
+ (aligned : ∀ j, (site j).val = start + j.val) (endOrd : start + k = n)
+ (m : Memory w) (hm : Frame start m) (x : ∀ j, D.Choice (site j)) :
+ let last := Counters.visit base grammar id (List.ofFn fun j => D.powers (site j) (x j)) m
+ ∃ rs : List (Report w), rs.length = k ∧ (∀ r ∈ rs, ok r) ∧ closedRun P fuel start m
+ ((List.ofFn fun j => D.encode (site j) (x j)) ++ [[]]) (rs ++ [closingReport pub last]) last := by
+ induction k generalizing start m with
+ | zero =>
+ simp only [Nat.add_zero] at endOrd
+ subst start
+ have call := close m hm []
+ simp only [ite_true] at call
+ exact ⟨[],rfl,by simp,by simp [closedRun,runSegment,call,endState,eventLog,Counters.visit,closingReport_after]; rfl⟩
+ | succ k ih =>
+ have hz : (site 0).val = start := by simpa using aligned 0
+ obtain ⟨rep,call,next,mem⟩ := H.emit (site 0) m (hz ▸ hm) (x 0)
+ have accepted := checks (site 0) m (hz ▸ hm) (x 0) rep call
+ rw [hz] at call next
+ have step := H.preserve (site 0) m (hz ▸ hm) (x 0)
+ rw [hz, ← mem] at step
+ obtain ⟨rs,hlen,checked,run⟩ := ih (fun j => site j.succ)
+ (fun j => by rw [aligned, Fin.val_succ]; omega) (by omega) (after m rep.events) step (fun j => x j.succ)
+ refine ⟨rep :: rs,by simp [hlen],List.forall_mem_cons.mpr ⟨accepted,checked⟩,?_⟩
+ simp only [List.ofFn_succ, List.cons_append, Counters.visit, List.foldl_cons, id_eq]
+ rw [← mem]
+ exact closedRun_cons call next run
+
+include H in
+private theorem recover_suffix (close : Closes P fuel n pub Frame)
+ {k start : ℕ} (site : Fin k → Fin n)
+ (aligned : ∀ j, (site j).val = start + j.val) (endOrd : start + k = n)
+ (m : Memory w) (hm : Frame start m) {bs : List (List Bool)} {rs : List (Report w)}
+ (run : runSegment P fuel (some (start : Word w)) m bs = some rs)
+ (halt : endState (some (start : Word w)) rs = none) :
+ ∃ x : ∀ j, D.Choice (site j), bs = (List.ofFn fun j => D.encode (site j) (x j)) ++ [[]] := by
+ induction k generalizing start m bs rs with
+ | zero =>
+ simp only [Nat.add_zero] at endOrd
+ subst start
+ cases bs with
+ | nil =>
+ obtain rfl : rs = [] := (Option.some.inj run).symm
+ contradiction
+ | cons b bs =>
+ rw [runSegment, close m hm] at run
+ by_cases empty : b = []
+ · subst b
+ simp only [ite_true] at run
+ cases bs with
+ | nil => exact ⟨fun j => Fin.elim0 j, by simp⟩
+ | cons c cs => contradiction
+ · simp [empty] at run
+ | succ k ih =>
+ cases bs with
+ | nil =>
+ obtain rfl : rs = [] := (Option.some.inj run).symm
+ contradiction
+ | cons b bs =>
+ cases call : execute P fuel (P.start (start : Word w)) m b with
+ | none => simp only [runSegment,call,reduceCtorEq] at run
+ | some rep =>
+ rw [runSegment,call,Option.map_eq_some_iff] at run
+ obtain ⟨rs,tail,rfl⟩ := run
+ change endState rep.result rs = none at halt
+ have hz : (site 0).val = start := by simpa using aligned 0
+ obtain ⟨x₀,rfl⟩ := H.recover (site 0) m (hz ▸ hm) b rep (hz ▸ call)
+ obtain ⟨out,exec,next,mem⟩ := H.emit (site 0) m (hz ▸ hm) x₀
+ rw [hz] at exec next
+ obtain rfl := Option.some.inj (exec.symm.trans call)
+ have step := H.preserve (site 0) m (hz ▸ hm) x₀
+ rw [hz, ← mem] at step
+ rw [next] at tail halt
+ obtain ⟨xs,hs⟩ := ih (fun j => site j.succ)
+ (fun j => by rw [aligned, Fin.val_succ]; omega) (by omega) _ step tail halt
+ refine ⟨Fin.cons x₀ xs,?_⟩
+ simp only [List.ofFn_succ, Fin.cons_zero, Fin.cons_succ, List.cons_append]
+ exact congrArg (_ :: ·) hs
+
+/-- All site tapes in order, followed by the mandatory exhausted call. -/
+def IndexedSites.calls (D : IndexedSites n g) (x : ∀ j, D.Choice j) : List (List Bool) :=
+ (List.ofFn fun j => D.encode j (x j)) ++ [[]]
+
+/-- External memory after all active ordinals. -/
+def IndexedSites.finalMemory (D : IndexedSites n g) (base grammar : ℕ)
+ (m : Memory w) (x : ∀ j, D.Choice j) : Memory w :=
+ Counters.visit base grammar id (List.ofFn fun j => D.powers j (x j)) m
+
+theorem IndexedSites.finalMemory_at (D : IndexedSites n g) (base grammar : ℕ)
+ (m : Memory w) (x : ∀ j, D.Choice j) (l : Fin g) :
+ D.finalMemory base grammar m x (base + grammar + l) =
+ m (base + grammar + l) + ((∑ j, D.powers j (x j) l : ℕ) : Word w) := by
+ rw [IndexedSites.finalMemory, Counters.visit_at, List.map_ofFn, List.sum_ofFn]
+ rfl
+
+include H in
+/-- The native report list has one active call per site and the exact final
+header report. Its external effect is the sum of the selected exponent vectors. -/
+theorem ascending_reports (close : Closes P fuel n pub Frame)
+ (m : Memory w) (hm : Frame 0 m) (x : ∀ j, D.Choice j) :
+ let last := D.finalMemory base grammar m x
+ ∃ rs : List (Report w), rs.length = n ∧
+ runSegment P fuel (some 0) m (D.calls x) = some (rs ++ [closingReport pub last]) ∧
+ endState (some 0) (rs ++ [closingReport pub last]) = none ∧
+ after m (eventLog (rs ++ [closingReport pub last])) = last := by
+ obtain ⟨rs, len, _, run⟩ := emit_suffix H close (fun _ => True) (fun _ _ _ _ _ _ => trivial)
+ id (fun _ => by simp) (Nat.zero_add n) m hm x
+ exact ⟨rs, len, by simpa only [Nat.cast_zero, id_eq, closedRun, IndexedSites.finalMemory, IndexedSites.calls] using run⟩
+
+include H in
+/-- A bijection with the accepted native tapes at a fixed shared arc assignment. -/
+noncomputable def ascendingEquiv (close : Closes P fuel n pub Frame)
+ (m : Memory w) (hm : Frame 0 m) :
+ (∀ j, D.Choice j) ≃ ActualPaths P fuel 0 m (fun _ => True) := by
+ let path (x : ∀ j, D.Choice j) : ActualPaths P fuel 0 m (fun _ => True) :=
+ ⟨D.calls x, by obtain ⟨rs, _, run, halt, _⟩ := ascending_reports H close m hm x
+ exact ⟨_, run, halt, trivial⟩⟩
+ refine Equiv.ofBijective path ⟨?_,?_⟩
+ · intro x y h
+ have ht := List.ofFn_inj.mp (List.append_cancel_right (congrArg Subtype.val h))
+ exact funext fun i => D.injective i (congrFun ht i)
+ · intro q
+ obtain ⟨rs,run,halt,_⟩ := q.property
+ obtain ⟨x,hx⟩ := recover_suffix H close id (fun _ => by simp) (Nat.zero_add n) m hm
+ (by simpa using run) (by simpa using halt)
+ exact ⟨x,Subtype.ext hx.symm⟩
+
+theorem ascendingEquiv_calls (close : Closes P fuel n pub Frame) (m : Memory w)
+ (hm : Frame 0 m) (x : ∀ j, D.Choice j) :
+ (ascendingEquiv H close m hm x).val = D.calls x := rfl
+
+open CompressorRecords.SourceTransport TerminalLink
+
+theorem headerWord_eq_header (pub : Fin 11 → Word w) :
+ TerminalSiteStart.headerWord pub = TerminalLink.header pub := by
+ dsimp only [TerminalSiteStart.headerWord, TerminalLink.header]
+ exact congrArg (fun k : Word w => _ - k) (Nat.cast_add (R := Word w) 16 16).symm
+
+/-- The only exhausted-call read is header field seven, and the clock charge is fifteen. -/
+theorem closingReport_checks (pub : Fin 11 → Word w) (m : Memory w)
+ (room : (TerminalLink.header pub).val + 32 ≤ 2 ^ w) :
+ Reads (workerCell (TerminalLink.header pub)) (closingReport pub m).events ∧
+ (closingReport pub m).events.length + 1 = 15 := by
+ refine ⟨?_,rfl⟩
+ intro a v ha
+ simp only [closingReport, TerminalSiteStart.guardTrace, TerminalSiteStart.fieldTrace,
+ List.mem_append, List.mem_replicate, List.mem_cons, List.not_mem_nil, Event.read.injEq,
+ reduceCtorEq, and_false, false_or, or_false] at ha
+ obtain ⟨rfl,_⟩ := ha
+ rw [headerWord_eq_header]
+ have offset (k : ℕ) (hk : k < 32) : (TerminalLink.header pub + (k : Word w)).val = (TerminalLink.header pub).val + k := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (show k < 2^w by omega),
+ Nat.mod_eq_of_lt (by omega)]
+ change (TerminalLink.header pub + 7).val ≠ (TerminalLink.header pub).val ∧ (TerminalLink.header pub + 7).val ≠ (TerminalLink.header pub + 31).val
+ rw [show (TerminalLink.header pub + 7).val = _ from offset 7 (by decide),
+ show (TerminalLink.header pub + 31).val = _ from offset 31 (by decide)]
+ omega
+
+include H in
+/-- Reads and clock bounds on the encoded site calls hold on every closed native
+source path, including its exhausted call. The report list is the computed one. -/
+theorem ascending_report_checks (close : Closes P fuel n pub Frame) {clock : ℕ}
+ (room : (TerminalLink.header pub).val + 32 ≤ 2 ^ w) (minClock : 15 ≤ clock)
+ (checks : ∀ i m, Frame i.val m → ∀ (x : D.Choice i) r,
+ execute P fuel (P.start (i.val : Word w)) m (D.encode i x) = some r →
+ Reads (workerCell (TerminalLink.header pub)) r.events ∧ r.events.length + 1 ≤ clock)
+ (m : Memory w) (hm : Frame 0 m) {bs rs}
+ (run : runSegment P fuel (some 0) m bs = some rs) (halt : endState (some 0) rs = none) :
+ Reads (workerCell (TerminalLink.header pub)) (eventLog rs) ∧ ∀ r ∈ rs, r.events.length + 1 ≤ clock := by
+ obtain ⟨x,rfl⟩ := recover_suffix H close id (fun _ => by simp) (Nat.zero_add n) m hm
+ (by simpa using run) (by simpa using halt)
+ obtain ⟨active,_,safe,calls,_,_⟩ := emit_suffix H close
+ (fun r => Reads (workerCell (TerminalLink.header pub)) r.events ∧ r.events.length + 1 ≤ clock) checks
+ id (fun _ => by simp) (Nat.zero_add n) m hm x
+ rw [Nat.cast_zero] at calls
+ obtain rfl := Option.some.inj (run.symm.trans calls)
+ have each : ∀ r ∈ active ++ [closingReport pub (D.finalMemory base grammar m x)],
+ Reads (workerCell (TerminalLink.header pub)) r.events ∧ r.events.length + 1 ≤ clock := by
+ intro r hr
+ rcases List.mem_append.mp hr with ha | hc
+ · exact safe r ha
+ · obtain rfl := List.mem_singleton.mp hc
+ have ⟨read,len⟩ := closingReport_checks pub (D.finalMemory base grammar m x) room
+ exact ⟨read,len ▸ minClock⟩
+ refine ⟨?_,fun r hr => (each r hr).2⟩
+ intro a v hv
+ obtain ⟨r,hr,hit⟩ := List.mem_flatMap.mp hv
+ exact (each r hr).1 a v hit
+
+section SiteParsers
+
+variable {R : Type*} [CommRing R] {Label : Type} [Fintype Label] {κ : Label → R}
+ {N : Network} (parsers : SiteParsers κ N) (order : Fin n ≃ N.Site)
+ (labels : Fin g ≃ Label) (half : ∀ v, N.Half v)
+
+/-- Index the actual monomial occurrences and their readers by the worker's ordinals. -/
+def siteOrdinals : IndexedSites n g where
+ Choice j := (parsers.witnesses (order j) (half (order j))).Choice
+ encode j := (parsers.read (order j) (half (order j))).encode
+ injective j _ _ eqn := (parsers.read (order j) _).completeEquiv.injective (Subtype.ext eqn)
+ powers j x l := (parsers.witnesses (order j) (half (order j))).exponents x (labels l)
+
+local notation "sites" => siteOrdinals parsers order labels half
+local notation "worker" => Machine.program (Template.instantiate (template S) w pub)
+
+variable (active : ActiveCalls (siteOrdinals parsers order labels half)
+ (((template (segments geometry rootFields leaf shrink refresh)).instantiate w pub).program) fuel base grammar Frame)
+ (room : 15 ≤ fuel)
+ (stored : ∀ m, Frame n m → m (TerminalSiteStart.headerWord pub + 7).val = (n : Word w))
+
+/-- Visit the monomial choices in physical ordinal order and close the actual vertex template. -/
+noncomputable def sitePathsEquiv (active : ActiveCalls (sites) (worker) fuel base grammar Frame)
+ (room : 15 ≤ fuel) (stored : ∀ m, Frame n m →
+ m (TerminalSiteStart.headerWord pub + 7).val = (n : Word w)) (m : Memory w) (hm : Frame 0 m) :
+ (∀ v, (parsers.witnesses v (half v)).Choice) ≃ ActualPaths (worker) fuel 0 m (fun _ => True) := by
+ exact (Equiv.piCongrLeft (fun v => (parsers.witnesses v (half v)).Choice) order).symm.trans
+ (ascendingEquiv active (template_closes room stored) m hm)
+
+theorem sitePathsEquiv_calls (m : Memory w) (hm : Frame 0 m) (x : ∀ v, (parsers.witnesses v (half v)).Choice) :
+ (sitePathsEquiv parsers order labels half active room stored m hm x).val =
+ (List.ofFn fun j => (parsers.read (order j) (half (order j))).encode (x (order j))) ++ [[]] := rfl
+
+include active room stored in
+/-- Read back a selected histogram from the source worker's own event log. -/
+theorem sitePaths_histogram (m : Memory w) (hm : Frame 0 m) (x : ∀ v, (parsers.witnesses v (half v)).Choice) :
+ let path := sitePathsEquiv parsers order labels half active room stored m hm x
+ ∃ rs, runSegment (worker) fuel (some 0) m path.val = some rs ∧
+ (∀ l : Fin g, after m (eventLog rs) (base + grammar + l) = m (base + grammar + l) +
+ ((∑ v, (parsers.witnesses v (half v)).exponents (x v) (labels l) : ℕ) : Word w)) ∧
+ ∀ a, a < base + grammar ∨ base + grammar + g ≤ a → after m (eventLog rs) a = m a := by
+ obtain ⟨rs,_,run,_,mem⟩ := ascending_reports active (template_closes room stored) m hm (fun j => x (order j))
+ refine ⟨_,run,?_,?_⟩
+ · intro l
+ rw [mem, IndexedSites.finalMemory_at (sites) base grammar m (fun j => x (order j)) l]
+ exact congrArg (fun e : ℕ => m (base + grammar + l) + (e : Word w))
+ (order.sum_comp fun v => (parsers.witnesses v (half v)).exponents (x v) (labels l))
+ · intro a ha
+ rw [mem]
+ exact Counters.visit_outside _ _ _ _ _ _ ha
+
+end SiteParsers
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexBurstReadback.lean b/lean/OAI/Computability/VPVNP/PairVertexBurstReadback.lean
new file mode 100644
index 0000000000..a3fbfd3511
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexBurstReadback.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+import OAI.Computability.VPVNP.PairVertexSiteReport
+import OAI.Computability.VPVNP.PairVertexOccurrence
+import OAI.Computability.VPVNP.PairSimulationTerminalSiteRun
+
+/-!
+# Returning one terminal vertex at the burst cutoff
+
+The prefix enters the DFS after preparing the actual root argument. The
+native occurrence supplies the choice events and the histogram update.
+Conversely, every returning input must pass the same deterministic prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM DFS LocalHistory
+
+variable {w p r k : ℕ} {M : Machine w p r k} {m : Memory w}
+ {start cfg : Config w p r} {es : List (Event w)}
+
+open private returns_prefix from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+/-- Pull a complete accepting word back through the native bootstrap,
+geometry and gather prefixes. Empty words are allowed. -/
+theorem prefix_occurrences {X : Type*} (encode : X → List Bool)
+ (pre : TerminalSiteStart.Continues M m start cfg es)
+ (decode : ∀ bits, Returns M cfg m bits ↔ ∃! x, bits = encode x) (bits : List Bool) :
+ Returns M start m bits ↔ ∃! x, bits = encode x := by
+ exact (returns_prefix (fun f => pre f bits)).trans (decode bits)
+
+/-- When the actual report fits the public clock, the reported output
+includes exactly the prefix events and preserves the semantic update of the
+DFS and flush. The clock may have arbitrary spare instructions. -/
+theorem emit_at_cutoff (pre : TerminalSiteStart.Continues M m start cfg es)
+ (readOnly : after m es = m) (det : choiceBits es = [])
+ (rep : Report w) (bits : List Bool) (choice : choiceBits rep.events = bits)
+ (run : ∀ extra, execute M.program (extra + rep.events.length + 1) cfg m bits = some rep)
+ (fuel : ℕ) (enough : es.length + rep.events.length + 1 ≤ fuel) :
+ let whole : Report w := ⟨es ++ rep.events, rep.result⟩
+ execute M.program fuel start m bits = some whole ∧ choiceBits whole.events = bits ∧
+ after m whole.events = after m rep.events ∧
+ countProbes whole.events = countProbes es + countProbes rep.events := by
+ intro whole
+ have clock : fuel = (fuel-(es.length+rep.events.length+1)+rep.events.length+1)+es.length := by omega
+ refine ⟨?_,?_,?_,?_⟩
+ · rw [clock,pre,run]
+ rfl
+ · exact (PrimedInputRAM.Flow.choiceBits_append ..).trans (by rw [det,choice,List.nil_append])
+ · exact (show after m (es ++ rep.events) = after (after m es) rep.events from List.foldl_append).trans
+ (congrArg (fun a => after a rep.events) readOnly)
+ · exact countProbes_append ..
+
+/-- Uniqueness and external readback also hold for an arbitrary observed
+return, including a report first supplied by the burst interpreter. -/
+theorem observed_at_cutoff {X : Type*} (encode : X → List Bool) (update : X → Memory w)
+ (next : Word w) (fuel : ℕ)
+ (decode : ∀ bits, Returns M start m bits ↔ ∃! x, bits = encode x)
+ (emit : ∀ x, ∃ rep, execute M.program fuel start m (encode x) = some rep ∧
+ rep.result = some next ∧ after m rep.events = update x)
+ (bits : List Bool) (observed : Report w) (run : execute M.program fuel start m bits = some observed) :
+ ∃! x, bits = encode x ∧ observed.result = some next ∧ after m observed.events = update x := by
+ obtain ⟨x,word,unique⟩ := (decode bits).mp ⟨fuel,observed,run⟩
+ obtain ⟨rep,hr,state,memory⟩ := emit x
+ rw [←word,run] at hr
+ cases Option.some.inj hr
+ exact ⟨x,⟨word,state,memory⟩,fun y hy => unique y hy.1⟩
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexCompiledPayload.lean b/lean/OAI/Computability/VPVNP/PairVertexCompiledPayload.lean
new file mode 100644
index 0000000000..223a968cf7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexCompiledPayload.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairTerminalPackedPrefix
+import OAI.Computability.VPVNP.PairTerminalVertexFramePacked
+import OAI.Computability.VPVNP.CompressorCompiledResident
+
+/-!
+# Reading a compiled pass payload in the current physical vertex memory
+
+Each producing pass retains its input level and the successor pointer and
+incidence bank. Even for the last pass, this bank ends at the final array base,
+before the terminal program's offset table. Earlier physical vertices can
+update counters and terminal control words without changing any retained cell.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open BurstRAM Compression CompressorRecords DescriptorSpace PairSimulation
+open LocalHistory TerminalProgram TraversalRows TraversalRoles LiveProgram.PairStages
+open LiveProgram.PairStages.Group.Auxiliary
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f} {lanes T : ℕ}
+variable {hT : T * S.laneBits ≤ lanes} {X : State (S.degreeExponent 0) lanes}
+variable {z : (B.execute f hf T hT X).Choices}
+variable {G : Group} {positions cap width ord baseBits laneBits : ℕ} {roles : List TaggedLayer}
+
+local notation "pub" => terminalOperands G
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "last" => List.length (List.dropLast (selectedLayers B f hf T hT X z))
+set_option quotPrecheck false in
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val positions T
+
+variable {calendar reference phy : Memory G.w}
+private theorem cells_before_offset {L : DescriptorSpace.Layout} {i final x : ℕ}
+ (t : Fin L.shape.tables) (prev : i < final) (live : final < L.levels)
+ (cell : SelectedPayloadHistory.Cells L i x) :
+ L.base ≤ x ∧ x < endAddress L ∧ x < DescriptorSpace.tableBase L final t := by
+ obtain ⟨lo, hi⟩ := SelectedPayloadHistory.cells_interval prev cell
+ have floor : L.base ≤ levelsBase L := by
+ unfold levelsBase directoryBase plannerTag frameBase
+ omega
+ have before : x < DescriptorSpace.tableBase L final t := hi.trans_le (Nat.le_add_right ..)
+ have stop := (tableEnd_le_nextLevel L final t).trans (levelStart_mono L live)
+ exact ⟨floor.trans lo, (before.trans_le (Nat.le_add_right ..)).trans_le stop, before⟩
+
+private theorem final_live : last < (D).levels := by
+ rw [TerminalBootstrap.selected_prior_length B f hf T hT X z, BlockProgram.actual_level_count]
+ rw [Nat.mul_comm T, Nat.one_add]
+ exact Nat.lt_succ_self _
+
+attribute [local irreducible] BlockProgram.layout BlockSchedule.Templates.execute
+ StateExecution.finalState executeLevels CompiledResident.payload SelectedPayloadHistory.Past
+
+set_option maxHeartbeats 800000 in
+-- Elaborate the physical word and pass types indexed by this branch of the compressor.
+/-- The complete footprint of a selected pass has its calendar value at this
+physical site, including every column of the successor incidence bank. -/
+theorem PairSimulation.TerminalProgram.VertexEntry.packedPayloadWindow
+ {table : Fin (D).shape.tables}
+ {wireBits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (entry : VertexEntry (w := G.w) B f hf T hT X z D table baseBits laneBits
+ (terminalOperands G) calendar reference wireBits)
+ (packed : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord phy)
+ (j : Fin (passes).length) :
+ SourceTransport.Agree (w := G.w) (SelectedPayloadHistory.Cells D j.val) calendar phy := by
+ have prev : j.val < last := j.isLt.trans_eq (TerminalBootstrap.selected_last_index
+ B f hf T hT X z).symm
+ have live : last < (D).levels := final_live
+ intro x cell
+ obtain ⟨lo, hi, before⟩ := cells_before_offset (L := D) table prev live cell
+ exact ((packed.directory frame lo hi).trans (entry.raw x hi (.inl before))).symm
+
+variable {inputLength : ℕ}
+local notation "data" => CompiledResident.payload (w := G.w) B f hf (pub 2) positions T inputLength
+
+set_option maxHeartbeats 800000 in
+-- Elaborate the physical word and pass types indexed by this branch of the compressor.
+/-- Read a pass of either kind at its chronological index in physical memory. -/
+theorem CompressorRecords.CompiledResident.read_vertex
+ {table : Fin (D).shape.tables}
+ {wireBits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past (w := G.w) B f hf D data passes calendar)
+ (entry : VertexEntry (w := G.w) B f hf T hT X z D table baseBits laneBits
+ (terminalOperands G) calendar reference wireBits)
+ (packed : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord phy)
+ (j : Fin (passes).length) : data j.val passes[j] phy :=
+ CompiledResident.payload_transfer (B := B) (f := f) (hf := hf) (workspace := pub 2)
+ (positions := positions) (blocks := T) (n := inputLength) (cur := j.val) (v := passes[j])
+ (CompiledResident.read (B := B) (f := f) (hf := hf) (workspace := pub 2)
+ (positions := positions) (blocks := T) (n := inputLength) history j)
+ (entry.packedPayloadWindow packed frame j)
+
+set_option maxHeartbeats 800000 in
+-- Elaborate the physical word and pass types indexed by this branch of the compressor.
+/-- All native shrinking sources, header words, selected term and child
+directory of the specified occurrence are present in the current site memory. -/
+theorem CompressorRecords.CompiledResident.shrink_vertex
+ {table : Fin (D).shape.tables}
+ {wireBits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past (w := G.w) B f hf D data passes calendar)
+ (entry : VertexEntry (w := G.w) B f hf T hT X z D table baseBits laneBits
+ (terminalOperands G) calendar reference wireBits)
+ (packed : VertexPacked G D cap roles width) (frame : LinkedVertexMemory G reference ord phy)
+ (j : Fin (passes).length) {i : Fin S.steps} {g : ℕ}
+ {Y : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)}
+ {sel : SelectedScore.Selection B Y} {tape : List Bool}
+ (occurrence : passes[j] = ⟨_, _, _, _, Y, _, .shrink i rfl Y, sel, tape⟩) :
+ CompiledResident.ShrinkPayload (w := G.w) B (pub 2) positions T inputLength
+ j.val i Y sel phy := by
+ have current := CompiledResident.read_vertex (G := G) (inputLength := inputLength)
+ history entry packed frame j
+ rw [occurrence] at current
+ exact (CompiledResident.shrink_payload B f hf (pub 2) positions T inputLength j.val i Y sel
+ tape phy).mp current
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexControl.lean b/lean/OAI/Computability/VPVNP/PairVertexControl.lean
new file mode 100644
index 0000000000..f73c88bd09
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexControl.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.PairVertexImage
+import OAI.Computability.VPVNP.PairPendingArguments
+
+/-! # Executing the private geometry, role-dispatch and counter rows -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM DFS PrimedCounter.GuessWord NodeArguments
+open scoped Fin.CommRing
+
+variable {W p r : ℕ} {S : Part → Segment} {A : Placement S p r} {M : Machine W p r 11}
+
+theorem geometry_run {pc : Fin 3 → Fin p} {endReg dst tmp : Fin r} {offset : Word W} {done : Fin p}
+ (linked : ∀ i, M.code (pc i) = geometryRows pc endReg dst tmp offset done i)
+ (apart : dst ≠ tmp) (c : Config W p r) (hc : c.pc = pc 0) :
+ ∃ out, Prefix M c (List.replicate 3 .tick) out ∧ out.pc = done ∧
+ out.reg dst = c.privateMem (c.reg endReg) + offset ∧
+ (∀ j, j ≠ dst → j ≠ tmp → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ have step (i : Fin 3) (d : Config W p r) (hd : d.pc = pc i) :
+ M.program.step d = (geometryRows pc endReg dst tmp offset done i).run M.publicData d := by
+ change (M.code d.pc).run _ _ = _
+ rw [hd,linked]
+ let c₁ := c.put (pc 1) dst (c.privateMem (c.reg endReg))
+ let c₂ := c₁.put (pc 2) tmp offset
+ let out := c₂.put done dst (c₂.reg dst + c₂.reg tmp)
+ have run : Prefix M c (List.replicate 3 .tick) out :=
+ .tick (step 0 c hc) (.tick (step 1 c₁ rfl) (.tick (step 2 c₂ rfl) (.nil out)))
+ exact ⟨out, run, rfl, by simp [out,c₂,c₁,Config.put,Function.update_of_ne apart],
+ fun j hd ht => by simp [out,c₂,c₁,Config.put,Function.update_of_ne hd,Function.update_of_ne ht],rfl,rfl⟩
+
+/-- The dispatcher and flush reread these two slots from scratch. Only the
+words at the designated addresses matter to their operation. -/
+structure ResidentGeometry {endAddr : ℕ} (s : Scratch W endAddr) (G offset hist : Word W) : Prop where
+ endFit : endAddr < 2^W
+ roleAbove : endAddr ≤ (G+10).val
+ histAbove : endAddr ≤ (G+11).val
+ pointer : rawScratch s (endAddr : Word W) = G
+ role : rawScratch s (G+10) = offset
+ histogram : rawScratch s (G+11) = hist
+
+private theorem resident_read {endAddr : ℕ} (mem : Word W → Word W) (G offset hist : Word W)
+ (stored : ResidentGeometry (scratch endAddr mem) G offset hist) :
+ mem (endAddr : Word W) = G ∧ mem (G+10) = offset ∧ mem (G+11) = hist := by
+ have h : endAddr ≤ (endAddr : Word W).val := (Nat.mod_eq_of_lt stored.endFit).ge
+ exact ⟨by simpa only [rawScratch,dite_eq_left h,scratch] using stored.pointer,
+ by simpa [rawScratch,scratch,stored.roleAbove] using stored.role,
+ by simpa [rawScratch,scratch,stored.histAbove] using stored.histogram⟩
+
+/-- The three private geometry-load ticks followed by the external role-word dispatch for a
+popped node. -/
+def dispatchEvents (m : Memory W) (offset node : Word W) : List (Event W) :=
+ List.replicate 3 .tick ++ NodeDispatch.events m offset node
+
+theorem dispatchEvents_cost (m : Memory W) (offset node : Word W) :
+ countProbes (dispatchEvents m offset node) = 1 ∧ (dispatchEvents m offset node).length ≤ 9 ∧
+ choiceBits (dispatchEvents m offset node) = [] := by
+ obtain ⟨probes,time,choices⟩ := NodeDispatch.events_cost m offset node
+ exact ⟨probes, by simp only [dispatchEvents,List.length_append,List.length_replicate]; omega, choices⟩
+
+/-- One actual external tag probe selects the same handler as the recorded
+role. The geometry pointer and both data words come from the private packet
+domain, so every unused host register may hold arbitrary data. -/
+theorem dispatch_run (linked : Contains A M) {endAddr : ℕ} (G offset hist : Word W)
+ (c : Config W p r) (hc : c.pc = A.core (.roleBase 0)) (h1 : c.reg (A.dfs 3) = 1)
+ (hend : c.reg (A.dfs 6) = (endAddr : Word W))
+ (stored : ResidentGeometry (scratch endAddr c.privateMem) G offset hist) (m : Memory W) :
+ let node := c.reg (A.dfs 7)
+ ∃ out, out.pc = A.entry (rolePart (NodeDispatch.role (m (offset+node).val))) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ (∀ j, j ≠ A.dfs 0 → j ≠ A.dfs 1 → out.reg j = c.reg j) ∧
+ ∀ fuel bs, execute M.program (fuel+(dispatchEvents m offset node).length) c m bs =
+ (execute M.program fuel out m bs).map (fun rep => ⟨dispatchEvents m offset node ++ rep.events,rep.result⟩) := by
+ intro node
+ obtain ⟨pointer,role,_⟩ := resident_read c.privateMem G offset hist stored
+ obtain ⟨mid,pre,pc,addr,regs,mem,persist⟩ := geometry_run (roleBase_linked A M linked)
+ (A.dfs.injective.ne (by decide)) c hc
+ have head : M.program.step mid = .localStep (mid.put (A.rolePC 1) (A.dfs 0) offset) := by
+ change (M.code mid.pc).run _ _ = _
+ rw [pc,dispatch_linked A M linked]
+ change CallAction.localStep (mid.put (A.rolePC 1) (A.dfs 0) (mid.privateMem (mid.reg (A.dfs 0)))) = _
+ rw [addr,hend,pointer,mem,role]
+ have tail (i : Fin 6) (hi : i ≠ 0) :
+ M.code (A.rolePC i) = NodeDispatch.instruction A.rolePC A.dfs 0 (A.entry ∘ rolePart) i := by
+ rw [dispatch_linked A M linked, dispatchRows, ite_eq_right hi]
+ have unit := (regs _ (A.dfs.injective.ne (by decide : (3:Fin 9) ≠ 0))
+ (A.dfs.injective.ne (by decide : (3:Fin 9) ≠ 1))).trans h1
+ obtain ⟨out,hd,hm,hs,keep,run⟩ := NodeDispatch.enter_loaded offset mid head tail unit m
+ have num : mid.reg (A.dfs 7) = node :=
+ regs _ (A.dfs.injective.ne (by decide)) (A.dfs.injective.ne (by decide))
+ rw [num] at hd run
+ refine ⟨out,hd,hm.trans mem,hs.trans persist,fun j h0 h1 => (keep _ h0 h1).trans (regs _ h0 h1),?_⟩
+ intro fuel bs
+ have start := pre.execute (fuel+(NodeDispatch.events m offset node).length) m bs
+ change execute M.program (fuel+(NodeDispatch.events m offset node).length+3) c m bs = _ at start
+ rw [dispatchEvents,List.length_append,List.length_replicate,show fuel+(3+(NodeDispatch.events m offset node).length) = fuel+(NodeDispatch.events m offset node).length+3 by omega,start,run]
+ simp only [Option.map_map,Function.comp_def,List.append_assoc]
+
+/-- The remaining seven flush-setup rows load the three public sizes and
+the private histogram pointer. The seven counter-loop rows then perform
+the actual shared read/add/write sequence on every template component. -/
+theorem flush_run_events (linked : Contains A M) {endAddr g : ℕ} (G offset : Word W)
+ (c : Config W p r) (hc : c.pc = A.core (.histBase 0)) (hend : c.reg (A.dfs 6) = (endAddr : Word W))
+ (base grammar src : ℕ) (stored : ResidentGeometry (scratch endAddr c.privateMem) G offset (src : Word W))
+ (hbase : M.publicData 4 = (base : Word W)) (hgrammar : M.publicData 5 = (grammar : Word W))
+ (hg : M.publicData 9 = (g : Word W)) (h : Fin g → ℕ)
+ (hpriv : ∀ i : Fin g, c.privateMem ((src+i.val : ℕ) : Word W) = (h i : Word W))
+ (hsrc : src+g < 2^W) (hdst : base+grammar+g < 2^W) (m : Memory W) :
+ ∃ out es, out.pc = A.entry .finish ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ es = List.replicate 10 .tick ++ Counters.events c.privateMem m src (base+grammar) g ∧
+ es.length = 7*g+11 ∧ countProbes es = 2*g ∧ choiceBits es = [] ∧
+ after m es = Counters.addHistogram base grammar h m ∧
+ ∀ fuel bs, execute M.program (fuel+7*g+11) c m bs =
+ (execute M.program fuel out (Counters.addHistogram base grammar h m) bs).map
+ (fun rep => ⟨es ++ rep.events,rep.result⟩) := by
+ obtain ⟨pointer,_,hist⟩ := resident_read c.privateMem G offset (src : Word W) stored
+ obtain ⟨mid,geom,hpc,addr,_,mem,persist⟩ := geometry_run (histBase_linked A M linked)
+ (A.counter.injective.ne (by decide)) c hc
+ let pc := A.flushStartPC
+ let reg := A.counter
+ have step (i : Fin 7) (d : Config W p r) (hd : d.pc = pc i) :
+ M.program.step d = (flushStartRows pc reg (A.flushPC 0) i).run M.publicData d := by
+ change (M.code d.pc).run _ _ = _
+ rw [hd,flushStart_linked A M linked]
+ let c₁ := mid.put (pc 1) (reg 0) (M.publicData 4)
+ let c₂ := c₁.put (pc 2) (reg 4) (M.publicData 5)
+ let c₃ := c₂.put (pc 3) (reg 0) (c₂.reg (reg 0)+c₂.reg (reg 4))
+ let c₄ := c₃.put (pc 4) (reg 1) (M.publicData 9)
+ let c₅ := c₄.put (pc 5) (reg 1) (c₄.reg (reg 0)+c₄.reg (reg 1))
+ let c₆ := c₅.put (pc 6) (reg 2) (c₅.privateMem (c₅.reg (reg 2)))
+ let start := c₆.put (A.flushPC 0) (reg 3) 1
+ have init : Prefix M mid (List.replicate 7 .tick) start :=
+ .tick (step 0 mid hpc) (.tick (step 1 c₁ rfl) (.tick (step 2 c₂ rfl) (.tick (step 3 c₃ rfl)
+ (.tick (step 4 c₄ rfl) (.tick (step 5 c₅ rfl) (.tick (step 6 c₆ rfl) (.nil _)))))))
+ have pre : Prefix M c (List.replicate 10 .tick) start := geom.append init
+ have hr : start.reg (reg 0) = ((base+grammar : ℕ) : Word W) := by
+ simp [start,c₆,c₅,c₄,c₃,c₂,c₁,Config.put,hbase,hgrammar]
+ have he : start.reg (reg 1) = ((base+grammar+g : ℕ) : Word W) := by
+ simp [start,c₆,c₅,c₄,c₃,c₂,c₁,Config.put,hbase,hgrammar,hg]
+ have ptr : mid.reg (reg 2) = G+11 := by rw [addr,hend,pointer]
+ have hs : start.reg (reg 2) = (src : Word W) := by
+ simp [start,c₆,c₅,c₄,c₃,c₂,c₁,Config.put,ptr,mem,hist]
+ obtain ⟨out,es,dst,hmem,st,logs,len,probes,choices,upd,run⟩ :=
+ Counters.execute_vertex_events (core_linked A M linked).2.2 start rfl base grammar src h
+ (by intro i; change mid.privateMem _ = _; rw [mem]; exact hpriv i)
+ hsrc hdst hr he hs (by change start.reg (reg 3) = 1; simp [start,Config.put]) m
+ refine ⟨out,List.replicate 10 .tick ++ es,dst,hmem.trans mem,st.trans persist,
+ by rw [logs]; change _ ++ Counters.events mid.privateMem _ _ _ _ = _; rw [mem],
+ by simp [len],probes,choices,upd,?_⟩
+ intro fuel bs
+ have lead := pre.execute (fuel+7*g+1) m bs
+ change execute M.program (fuel+7*g+1+10) c m bs = _ at lead
+ rw [show fuel+7*g+11=fuel+7*g+1+10 by omega,lead,run]
+ simp only [Option.map_map,Function.comp_def,List.append_assoc]
+
+theorem flush_run (linked : Contains A M) {endAddr g : ℕ} (G offset : Word W)
+ (c : Config W p r) (hc : c.pc = A.core (.histBase 0)) (hend : c.reg (A.dfs 6) = (endAddr : Word W))
+ (base grammar src : ℕ) (stored : ResidentGeometry (scratch endAddr c.privateMem) G offset (src : Word W))
+ (hbase : M.publicData 4 = (base : Word W)) (hgrammar : M.publicData 5 = (grammar : Word W))
+ (hg : M.publicData 9 = (g : Word W)) (h : Fin g → ℕ)
+ (hpriv : ∀ i : Fin g, c.privateMem ((src+i.val : ℕ) : Word W) = (h i : Word W))
+ (hsrc : src+g < 2^W) (hdst : base+grammar+g < 2^W) (m : Memory W) :
+ ∃ out es, out.pc = A.entry .finish ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧
+ es.length = 7*g+11 ∧ countProbes es = 2*g ∧ choiceBits es = [] ∧
+ after m es = Counters.addHistogram base grammar h m ∧
+ ∀ fuel bs, execute M.program (fuel+7*g+11) c m bs =
+ (execute M.program fuel out (Counters.addHistogram base grammar h m) bs).map
+ (fun rep => ⟨es ++ rep.events,rep.result⟩) := by
+ obtain ⟨out, es, pc, mem, state, _, rest⟩ :=
+ flush_run_events linked G offset c hc hend base grammar src stored hbase hgrammar hg h hpriv hsrc hdst m
+ exact ⟨out, es, pc, mem, state, rest⟩
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexCursorDomain.lean b/lean/OAI/Computability/VPVNP/PairVertexCursorDomain.lean
new file mode 100644
index 0000000000..5f016aabba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexCursorDomain.lean
@@ -0,0 +1,42 @@
+import OAI.Computability.VPVNP.PairVertexFrameData
+
+/-! # Physical leaf domain for a stored cursor packet -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafRole
+
+open BurstRAM PrivateRAM CursorRouting CursorNetwork DFS NodeArguments
+open TreeDecode LeafHandler LocalHistory NetworkKernel CompressorRecords
+open scoped Fin.CommRing
+
+/-- A typed first-layer packet and its resident private frame provide all
+the physical inputs required by the leaf reader, on any pending suffix. -/
+theorem domain_of_packet {w endAddr : ℕ} {L : PrimedInputRAM.Lengths} {n a H s : ℕ}
+ {Q : PrimedInputRAM.Layout L n a H w} (D : PrimedCounter.Data Q s)
+ {b l e degree pad : ℕ} (hD : 1 < b+l) (hd : 2+pad = 2^degree)
+ {R : LeafArena.Regions} {data : Fin 10 → Word w} {offset : Word w} {cap : ℕ}
+ {q : Packet} {saved : Scratch w endAddr}
+ (typed : ∃ u z, q = ⟨(TraversalRows.sitePointers cap ((addressFields data) .base).val
+ (siteOrder (LeafArguments.state hD hd (2^e) w)) u).1, packed (LeafArguments.state hD hd (2^e) w) u z⟩)
+ (within : q.node < R.nodes) (word : q.node < 2^w)
+ (fits : q.Fits R.arguments w endAddr) (stored : q.Stored R.arguments saved)
+ (frame : VertexFrameData R data offset (LeafVisit.cacheWords D (b+l) e) saved) :
+ Domain (e := e) data D hD hd R cap (NativeFrame.frameBase R) (q.node : Word w) saved := by
+ have exactNode : (q.node : Word w).val = q.node := Nat.mod_eq_of_lt word
+ refine ⟨⟨by rw [exactNode]; exact within,frame.cached,?_⟩,frame.record⟩
+ obtain ⟨u,z,rfl⟩ := typed
+ obtain ⟨v,rfl⟩ := (lanePositions (cursorCoordinateLabels b l)).surjective u
+ refine ⟨v,z,exactNode,?_,?_⟩
+ · rw [exactNode]
+ exact fits
+ · rw [exactNode]
+ exact stored
+
+end PairSimulation.LeafRole
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexDispatch.lean b/lean/OAI/Computability/VPVNP/PairVertexDispatch.lean
new file mode 100644
index 0000000000..1b56dc84c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexDispatch.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.PairVertexControl
+
+/-! # The exact DFS hook of the assembled three-role image -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM DFS
+open scoped Fin.CommRing
+open private returns_prefix from OAI.Computability.VPVNP.PairSimulationDFSDecode
+
+variable {W endAddr p r : ℕ} {S : Part → Segment} {A : Placement S p r} {M : Machine W p r 11}
+
+/-- Add the dispatcher's tag lookup to a role path on the scratch from
+which it was selected. The role body still performs the scratch update. -/
+def dispatchJob (m : Memory W) (offset node : Word W) (saved : Scratch W endAddr)
+ (body : VisitPath W endAddr) : VisitPath W endAddr :=
+ ⟨body.node, dispatchEvents m offset node ++ body.trace,
+ fun old => old = saved ∧ body.enabled old, body.update⟩
+
+/-- The enabling scratch fixes the stored geometry used by this call as
+well as the role's own local argument precondition. -/
+def dispatcher (handlers : NodeDispatch.Role → HookParser W endAddr) (m : Memory W)
+ (offset : Word W) : HookParser W endAddr where
+ read node saved bits :=
+ let role := NodeDispatch.role (m (offset + node).val)
+ ((handlers role).read node saved bits).map fun (job, tail) =>
+ (dispatchJob m offset node saved job, tail)
+
+/-- Compose a linked role path with the actual geometry and role-tag rows. -/
+theorem dispatchJob_linked (linked : Contains A M) {G offset hist node : Word W} {m : Memory W}
+ {saved : Scratch W endAddr} {role : NodeDispatch.Role} {body : VisitPath W endAddr}
+ (resident : ResidentGeometry saved G offset hist)
+ (tag : NodeDispatch.role (m (offset + node).val) = role)
+ (nodeEq : body.node = node)
+ (runBody : body.Linked M (A.entry (rolePart role)) (A.dfsPC 3) A.dfs m) :
+ (dispatchJob m offset node saved body).Linked M (A.core (.roleBase 0)) (A.dfsPC 3) A.dfs m := by
+ intro c top pending enabled hc hn hs hend ht he h1
+ have original : scratch endAddr c.privateMem = saved := enabled.1
+ rw [← original] at resident
+ obtain ⟨mid, pc, mem, persist, frame, prefixRun⟩ :=
+ dispatch_run linked G offset hist c hc h1 he resident m
+ change c.reg (A.dfs 7) = body.node at hn
+ rw [hn, nodeEq] at pc prefixRun
+ rw [tag] at pc
+ have reg (i : Fin 9) (hi : i ≠ 0) (hj : i ≠ 1) :=
+ frame (A.dfs i) (A.dfs.injective.ne hi) (A.dfs.injective.ne hj)
+ obtain ⟨out, hpc, nodeReg, topReg, endReg, unit, state, stack, scratchEq, run⟩ :=
+ runBody mid top pending (mem ▸ enabled.2) pc ((reg 7 (by decide) (by decide)).trans hn)
+ (mem ▸ hs) hend
+ ((reg 5 (by decide) (by decide)).trans ht)
+ ((reg 6 (by decide) (by decide)).trans he) ((reg 3 (by decide) (by decide)).trans h1)
+ refine ⟨out, hpc, nodeReg, topReg, endReg, unit, state.trans persist, stack, mem ▸ scratchEq, ?_⟩
+ intro fuel more
+ change execute M.program (fuel + (dispatchEvents m offset node ++ body.trace).length) c m
+ (choiceBits (dispatchEvents m offset node ++ body.trace) ++ more) = _
+ rw [PrimedInputRAM.Flow.choiceBits_append,
+ (dispatchEvents_cost m offset node).2.2,
+ List.nil_append,
+ List.length_append, show fuel + ((dispatchEvents m offset node).length + body.trace.length) =
+ (fuel + body.trace.length) + (dispatchEvents m offset node).length by omega, prefixRun, run]
+ simp only [dispatchJob, Option.map_map, Function.comp_def, List.append_assoc]
+
+/-- The private geometry and the external role tag are read again on
+every visit. Both success and rejection hold for arbitrary unused
+registers and for every stream suffix. -/
+theorem dispatch_exactOn (linked : Contains A M) (G offset hist : Word W) (m : Memory W)
+ (domain : Word W → Scratch W endAddr → Prop)
+ (geometry : ∀ node saved, domain node saved → ResidentGeometry saved G offset hist)
+ (handlers : NodeDispatch.Role → HookParser W endAddr)
+ (exactRole : ∀ role, (handlers role).ExactOn
+ (fun node saved => domain node saved ∧ NodeDispatch.role (m (offset + node).val) = role)
+ M (A.entry (rolePart role)) (A.dfsPC 3) A.dfs m) :
+ (dispatcher handlers m offset).ExactOn domain M (A.core (.roleBase 0)) (A.dfsPC 3) A.dfs m := by
+ constructor
+ · intro node saved hd bits job tail hit
+ let role := NodeDispatch.role (m (offset + node).val)
+ obtain ⟨⟨body, rest⟩, read, eqn⟩ := Option.map_eq_some_iff.mp hit
+ cases eqn
+ obtain ⟨nodeEq, en, word, runBody⟩ :=
+ (exactRole role).success node saved ⟨hd, rfl⟩ bits body tail read
+ refine ⟨nodeEq, ⟨rfl, en⟩, ?_, ?_⟩
+ · simpa only [dispatchJob, PrimedInputRAM.Flow.choiceBits_append,
+ (dispatchEvents_cost m offset node).2.2,
+ List.nil_append] using word
+ · exact dispatchJob_linked linked (geometry node saved hd) rfl nodeEq runBody
+ · intro node bits c top pending hd hc hn hs hend ht he h1 fail
+ let role := NodeDispatch.role (m (offset + node).val)
+ have read : (handlers role).read node (scratch endAddr c.privateMem) bits = none :=
+ Option.map_eq_none_iff.mp fail
+ obtain ⟨mid, pc, mem, _, frame, run⟩ :=
+ dispatch_run linked G offset hist c hc h1 he (geometry _ _ hd) m
+ rw [hn] at pc run
+ have reg (i : Fin 9) (hi : i ≠ 0) (hj : i ≠ 1) :=
+ frame (A.dfs i) (A.dfs.injective.ne hi) (A.dfs.injective.ne hj)
+ have reject := (exactRole role).reject node bits mid top pending ⟨mem ▸ hd, rfl⟩ pc
+ ((reg 7 (by decide) (by decide)).trans hn) (mem ▸ hs) hend
+ ((reg 5 (by decide) (by decide)).trans ht)
+ ((reg 6 (by decide) (by decide)).trans he) ((reg 3 (by decide) (by decide)).trans h1)
+ (mem ▸ read)
+ exact fun ok => reject ((returns_prefix (fun fuel => run fuel bits)).mp ok)
+
+/-- Removing the recorded private geometry ticks and tag probe from a
+successful dispatch leaves exactly the selected native handler's suffix. -/
+theorem dispatcher_suffix (handlers : NodeDispatch.Role → HookParser W endAddr) (m : Memory W)
+ (offset node : Word W) (saved : Scratch W endAddr) (bits : List Bool) :
+ ((dispatcher handlers m offset).read node saved bits).map Prod.snd =
+ ((handlers (NodeDispatch.role (m (offset + node).val))).read node saved bits).map
+ Prod.snd := by
+ simp [dispatcher, Option.map_map, Function.comp_def]
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexFrameData.lean b/lean/OAI/Computability/VPVNP/PairVertexFrameData.lean
new file mode 100644
index 0000000000..5ab0a863a5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexFrameData.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PairVertexActiveRoot
+import OAI.Computability.VPVNP.PairTreeFrontierBudget
+import OAI.Computability.VPVNP.PairSimulationLeafRoleHandler
+
+/-! # The geometry and validator words retained throughout one vertex call -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM PrivateRAM NodeArguments DFS VertexImage LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {w endAddr : ℕ}
+
+/-- These words are shared by all roles of the current vertex. The argument
+buffers and running histogram occupy their own private intervals. -/
+structure VertexFrameData (R : LeafArena.Regions) (data : Fin 10 → Word w)
+ (offset : Word w) (vals : Static 34 → Word w) (s : Scratch w endAddr) : Prop where
+ record : LeafGeometryLoad.Stored endAddr (NativeFrame.frameBase R) (rawScratch s) data
+ resident : ResidentGeometry s ((NativeFrame.frameBase R : ℕ) : Word w) offset
+ (R.histBase : Word w)
+ cached : Cached R.cacheBase (rawScratch s) vals
+
+variable {R : LeafArena.Regions} {data : Fin 10 → Word w} {offset : Word w}
+ {vals : Static 34 → Word w} {s out : Scratch w endAddr}
+
+private theorem word_add_nat (x i : ℕ) : ((x+i : ℕ) : Word w) = (x : Word w)+(i : Word w) :=
+ Nat.cast_add ..
+
+/-- An arbitrary kernel can update its child arguments, temporary words and
+histogram while retaining the three parts of the common private frame. -/
+theorem VertexFrameData.transfer (h : VertexFrameData R data offset vals s)
+ (pointer : rawScratch out (endAddr : Word w) = rawScratch s (endAddr : Word w))
+ (fields : ∀ i : Fin 12, rawScratch out ((NativeFrame.frameBase R+i.val : ℕ) : Word w) =
+ rawScratch s ((NativeFrame.frameBase R+i.val : ℕ) : Word w))
+ (cache : ∀ j : Static 34, rawScratch out ((R.cacheBase+j.offset : ℕ) : Word w) =
+ rawScratch s ((R.cacheBase+j.offset : ℕ) : Word w)) :
+ VertexFrameData R data offset vals out := by
+ refine ⟨⟨pointer.trans h.record.pointer,
+ fun i => (fields (i.castLE (by decide))).trans (h.record.values_at i)⟩,
+ ⟨h.resident.endFit,h.resident.roleAbove,h.resident.histAbove,
+ pointer.trans h.resident.pointer,?_,?_⟩,
+ fun j => (cache j).trans (h.cached j)⟩
+ · have cell : rawScratch out ((NativeFrame.frameBase R+10 : ℕ) : Word w) =
+ rawScratch s ((NativeFrame.frameBase R+10 : ℕ) : Word w) := fields 10
+ rw [word_add_nat, Nat.cast_ofNat] at cell
+ exact cell.trans h.resident.role
+ · have cell : rawScratch out ((NativeFrame.frameBase R+11 : ℕ) : Word w) =
+ rawScratch s ((NativeFrame.frameBase R+11 : ℕ) : Word w) := fields 11
+ rw [word_add_nat, Nat.cast_ofNat] at cell
+ exact cell.trans h.resident.histogram
+
+/-- The actual bootstrap and gather produce the private frame in the same
+scratch on which the role decoders run. -/
+theorem frame_of_root {S : Part → Segment} {p r : ℕ} {A : Placement S p r} {cfg : Config w p r}
+ {ordinal endWord roleWord : Word w} {q : Packet} {fields : Fin 12 → Word w}
+ (root : ActiveRootState A cfg ordinal endWord roleWord R q data fields vals)
+ (offsetAt : fields 10 = offset) (histAt : fields 11 = (R.histBase : Word w))
+ (above : endWord.val ≤ NativeFrame.frameBase R)
+ (frameFit : NativeFrame.frameBase R + 12 ≤ 2 ^ w) (beforeCache : endWord.val ≤ R.cacheBase)
+ (cacheFit : R.cacheBase + 38 ≤ 2 ^ w) :
+ VertexFrameData R data offset vals (scratch endWord.val cfg.privateMem) := by
+ have geom := root.resident.residentGeometry above frameFit
+ rw [offsetAt,histAt] at geom
+ refine ⟨⟨geom.pointer,?_⟩,geom,root.resident.cacheScratch beforeCache cacheFit⟩
+ intro i
+ have hf : NativeFrame.frameBase R+i.val < 2 ^ w := by have := i.isLt; omega
+ have live : endWord.val ≤ ((NativeFrame.frameBase R+i.val : ℕ) : Word w).val := by
+ rw [Fin.val_natCast,Nat.mod_eq_of_lt hf]
+ exact above.trans (Nat.le_add_right _ _)
+ rw [rawScratch,dite_eq_left live]
+ exact root.resident.geometry.values_at i
+
+/-- At the root the selected histogram is still zero. Its full remaining
+subtree charge establishes the invariant required by every later prefix. -/
+theorem budget_of_root {S : Part → Segment} {p r : ℕ} {A : Placement S p r} {cfg : Config w p r}
+ {ordinal endWord roleWord : Word w} {q : Packet} {fields : Fin 12 → Word w}
+ (root : ActiveRootState A cfg ordinal endWord roleWord R q data fields vals)
+ (offsetAt : fields 10 = offset) (histAt : fields 11 = (R.histBase : Word w))
+ (above : endWord.val ≤ R.histBase) (frameFit : NativeFrame.frameBase R + 12 ≤ 2 ^ w)
+ (cacheFit : R.cacheBase + 38 ≤ 2 ^ w) (format : Packet → Prop) (type : format q)
+ (desc : ℕ → List ℕ) (distinct : (subtreeAddresses desc q).Nodup)
+ {L : Type} (order : Fin R.histWords ≃ L) (nodeCap limit : ℕ)
+ (capacity : (subtreeAddresses desc q).length * nodeCap ≤ limit) :
+ Budgeted R.arguments format (VertexFrameData R data offset vals) desc
+ (privateHistogram order R.histBase) nodeCap limit [q]
+ (scratch endWord.val cfg.privateMem) := by
+ have frameAbove : endWord.val ≤ NativeFrame.frameBase R := above.trans (Nat.le_add_right ..)
+ have beforeCache : endWord.val ≤ R.cacheBase := frameAbove.trans R.hist_before
+ exact Budgeted.singleton (Frontier.singleton
+ (frame_of_root root offsetAt histAt frameAbove frameFit beforeCache cacheFit)
+ type root.fits root.stored distinct)
+ (root.resident.zeroHistogram order above (by omega)) capacity
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexFrameWrites.lean b/lean/OAI/Computability/VPVNP/PairVertexFrameWrites.lean
new file mode 100644
index 0000000000..a6c6d1fa17
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexFrameWrites.lean
@@ -0,0 +1,41 @@
+import OAI.Computability.VPVNP.PairVertexFrameData
+
+/-! # Preserving the common frame while running the cursor's private stack -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open BurstRAM NodeArguments DFS VertexImage LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {w endAddr : ℕ} {R : LeafArena.Regions} {data : Fin 10 → Word w} {offset : Word w}
+ {vals : Static 34 → Word w} {s out : Scratch w endAddr}
+
+/-- The leaf writes only its virtual stacks. Each common geometry or cache
+operand is physically below their first cell. -/
+theorem VertexFrameData.of_below_stack (h : VertexFrameData R data offset vals s)
+ (endBefore : endAddr < R.stackBase)
+ (preserve : ∀ i : {a : Word w // endAddr ≤ a.val}, i.val.val < R.stackBase → out i = s i) :
+ VertexFrameData R data offset vals out := by
+ have keep (n : ℕ) (before : n < R.stackBase) :
+ rawScratch out (n : Word w) = rawScratch s (n : Word w) := by
+ unfold rawScratch
+ split
+ · exact preserve _ ((Nat.mod_le _ _).trans_lt before)
+ · rfl
+ refine h.transfer (keep _ endBefore) (fun i => keep _ ?_) (fun j => keep _ ?_)
+ · have width := R.hist_before
+ have hi := i.isLt
+ unfold NativeFrame.frameBase LeafArena.Regions.stackBase
+ omega
+ · have hi : j.offset < 38 := by cases j <;> simp [Static.offset]; omega
+ exact Nat.add_lt_add_left hi _
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexGeometryResident.lean b/lean/OAI/Computability/VPVNP/PairVertexGeometryResident.lean
new file mode 100644
index 0000000000..c21a9c98af
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexGeometryResident.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.PairVertexGeometryRun
+
+/-! # The DFS stack and immutable leaf inputs after vertex initialization -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexGeometry.Ready
+
+open BurstRAM PrivateRAM LiveProgram VertexImage DFS NodeArguments LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {c : Constants} {degree a b p r w : ℕ} {rootFields leaf shrink refresh : Segment}
+ {A : VertexImage.Placement (segments (segment c degree a b) rootFields leaf shrink refresh) p r}
+ {m : Memory w} {pub : Fin 11 → Word w} {st out : Config w p r} {vals : Static 34 → Word w}
+ (h : Ready c degree a b A m pub st out vals)
+
+local notation "R" => NativeFrame.fromHeader degree pub (st.reg (A.saved header)) m
+local notation "G" => NativeFrame.frameBase R
+
+include h in
+theorem stack {top : ℕ} {xs : List (Word w)} (represented : Represents st.privateMem top xs)
+ (ends : top+xs.length ≤ (pub 6).val) (before : (pub 6).val < G) :
+ Represents out.privateMem top xs := by
+ refine ⟨represented.1,fun i => ?_⟩
+ have value : ((top+i.val : ℕ) : Word w).val = top+i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans represented.1)
+ have lt : top+i.val < (pub 6).val := (Nat.add_lt_add_left i.isLt _).trans_le ends
+ have sep : G ≤ (R).cacheBase := (R).hist_before
+ exact (h.outside _ (fun eq => lt.ne (value.symm.trans (congrArg Fin.val eq)))
+ (.inl (value.trans_lt (lt.trans before))) (.inl (value.trans_lt ((lt.trans before).trans_le sep)))).trans
+ (represented.2 i)
+
+include h in
+theorem resident (before : (pub 6).val < G) (fit : G+12 ≤ 2^w) :
+ ResidentGeometry (scratch (pub 6).val out.privateMem) (G : Word w) (st.reg (A.saved roleOffset))
+ ((R).histBase : Word w) := by
+ have bound (i : Fin 12) : G+i.val < 2^w := by have := i.isLt; omega
+ have atField (i : Fin 12) :
+ rawScratch (scratch (pub 6).val out.privateMem) ((G+i.val : ℕ) : Word w) =
+ NativeFrame.fields degree pub (st.reg (A.saved header)) (st.reg (A.saved roleOffset)) m i := by
+ have above : (pub 6).val ≤ ((G+i.val : ℕ) : Word w).val := by
+ change _ ≤ (G+i.val)%_; rw [Nat.mod_eq_of_lt (bound i)]; omega
+ rw [rawScratch,dite_eq_left above]
+ exact h.fields i
+ have addr (j : ℕ) (hj : j < 12) : ((G : Word w)+(j : Word w)).val = G+j := by
+ rw [← Nat.cast_add,Fin.val_natCast,Nat.mod_eq_of_lt (bound ⟨j,hj⟩)]
+ refine ⟨(pub 6).isLt,?_,?_,?_,?_,?_⟩
+ · rw [show (10 : Word w) = ((10 : ℕ) : Word w) from rfl,addr 10 (by decide)]; omega
+ · rw [show (11 : Word w) = ((11 : ℕ) : Word w) from rfl,addr 11 (by decide)]; omega
+ · have v : (pub 6).val ≤ (((pub 6).val : ℕ) : Word w).val := by rw [Fin.cast_val_eq_self]
+ rw [rawScratch,dite_eq_left v]; exact h.geometry.pointer
+ · have word := atField (10 : Fin 12)
+ change rawScratch (scratch (pub 6).val out.privateMem) ((G+10 : ℕ) : Word w) = st.reg (A.saved roleOffset) at word
+ simpa only [Nat.cast_add,Nat.cast_ofNat] using word
+ · have word := atField (11 : Fin 12)
+ change rawScratch (scratch (pub 6).val out.privateMem) ((G+11 : ℕ) : Word w) = ((R).histBase : Word w) at word
+ simpa only [Nat.cast_add,Nat.cast_ofNat] using word
+
+include h in
+theorem cacheScratch (before : (pub 6).val < G) (room : (R).cacheBase+38 ≤ 2^w) :
+ Cached (R).cacheBase (rawScratch (scratch (pub 6).val out.privateMem)) vals := by
+ intro j
+ have hj : j.offset < 38 := by cases j <;> simp [Static.offset]; omega
+ have sep : G ≤ (R).cacheBase := (R).hist_before
+ have above : (pub 6).val ≤ (((R).cacheBase+j.offset : ℕ) : Word w).val := by
+ change _ ≤ ((R).cacheBase+j.offset)%_
+ rw [Nat.mod_eq_of_lt (by omega)]
+ omega
+ rw [rawScratch,dite_eq_left above]
+ exact h.cache j
+
+end PairSimulation.VertexGeometry.Ready
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexGeometryRun.lean b/lean/OAI/Computability/VPVNP/PairVertexGeometryRun.lean
new file mode 100644
index 0000000000..e25055c09f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexGeometryRun.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PairVertexGeometrySegment
+import OAI.Computability.VPVNP.PairNativeLeafSetupRun
+import OAI.Computability.VPVNP.PairNativeCacheClock
+
+/-! # Geometry-to-root-fields execution in the actual terminal vertex image -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexGeometry
+
+open BurstRAM PrivateRAM LiveProgram PrimedInputRAM NativeOperands VertexImage LeafSourceLoad
+open scoped Fin.CommRing
+
+attribute [local irreducible] NativeOperands.capacity NativeOperands.saved
+
+variable (c : Constants) (degree a b : ℕ) {p r : ℕ}
+ {rootFields leaf shrink refresh : Segment}
+local notation "S" => segments (segment c degree a b) rootFields leaf shrink refresh
+variable (A : VertexImage.Placement (segments (segment c degree a b) rootFields leaf shrink refresh) p r)
+local notation "K" => block c degree a b A
+
+private theorem dfs_disjoint {T : Part → Segment} (V : VertexImage.Placement T p r)
+ (s : Fin 9) (j : Fin (T Part.geometry).privateRegs) : V.dfs s ≠ V.localRegs .geometry j :=
+ V.reg.injective.ne (by simp)
+
+private theorem saved_disjoint {T : Part → Segment} (V : VertexImage.Placement T p r)
+ (s : Saved) (j : Fin (T Part.geometry).privateRegs) : V.saved s ≠ V.localRegs .geometry j :=
+ V.reg.injective.ne (by simp)
+
+/-- The execution preserves the genuine DFS stack registers and every saved
+bootstrap word apart from the histogram pointer it publishes. -/
+structure Ready {w : ℕ} (m : Memory w) (pub : Fin 11 → Word w) (st out : Config w p r)
+ (cacheWords : Static 34 → Word w) : Prop where
+ pc : out.pc = A.entry .rootFields
+ persistent : out.persistent = st.persistent
+ dfs : ∀ j, out.reg (A.dfs j) = st.reg (A.dfs j)
+ saved : ∀ j ≠ histBase, out.reg (A.saved j) = st.reg (A.saved j)
+ hist : out.reg (A.saved histBase) =
+ ((NativeFrame.fromHeader degree pub (st.reg (A.saved header)) m).histBase : Word w)
+ geometry : let R := NativeFrame.fromHeader degree pub (st.reg (A.saved header)) m
+ LeafGeometryLoad.Stored (pub 6).val (NativeFrame.frameBase R) out.privateMem
+ (NativeFrame.leafWords degree pub (st.reg (A.saved header)) (st.reg (A.saved roleOffset)) m)
+ fields : ∀ j : Fin 12, let R := NativeFrame.fromHeader degree pub (st.reg (A.saved header)) m
+ out.privateMem ((NativeFrame.frameBase R+j.val : ℕ) : Word w) =
+ NativeFrame.fields degree pub (st.reg (A.saved header)) (st.reg (A.saved roleOffset)) m j
+ cache : Cached (NativeFrame.fromHeader degree pub (st.reg (A.saved header)) m).cacheBase out.privateMem cacheWords
+ outside : ∀ key : Word w, let R := NativeFrame.fromHeader degree pub (st.reg (A.saved header)) m
+ key ≠ pub 6 → (key.val < NativeFrame.frameBase R ∨ NativeFrame.frameBase R+12 ≤ key.val) →
+ (key.val < R.cacheBase ∨ R.cacheBase+38 ≤ key.val) → out.privateMem key = st.privateMem key
+
+/-- Exactly six header probes and no binary choices are charged before root-field gathering. -/
+theorem charges {w : ℕ} (header : Word w) (m : Memory w) (t : ℕ) :
+ let es := NativeFrame.events degree header m ++ List.replicate (t+2) .tick
+ es.length = t+degree+143 ∧ countProbes es = 6 ∧ choiceBits es = [] := by
+ intro es
+ obtain ⟨length,probes,bits⟩ := NativeFrame.events_cost degree header m
+ obtain ⟨tp,tb⟩ := NativeFrame.tick_cost (w := w) (t+2)
+ refine ⟨?_,?_,?_⟩
+ · simp only [es,List.length_append,List.length_replicate,length]; omega
+ · rw [show es = _ from rfl,countProbes_append,probes,tp,Nat.add_zero]
+ · rw [show es = _ from rfl,Flow.choiceBits_append,bits,tb,List.nil_append]
+
+/-- The per-vertex initializer has a linear private clock at large input
+lengths, uniformly in the group's live bucket size. -/
+theorem eventually_cost (B : ℕ) : ∀ᶠ n : ℕ in Filter.atTop, ∀ H,
+ work (NativeCache.args c) a b (AssemblerPublic.geometry B n H)+76+degree+143 ≤ 2*n := by
+ filter_upwards [NativeCache.eventually_work_le c a b B,Filter.eventually_ge_atTop (degree+143)]
+ with n workFit large H
+ have bound := workFit H
+ omega
+
+variable {prog : UniversalMachine.Program} {B n H : ℕ} {i : Fin (2^(n^c.chainPower-1))}
+local notation "W" => CursorBounds.wordBits B n
+local notation "D₀" => CursorBounds.virtualBits B n
+local notation "E₀" => roundedUp 1 4 n
+local notation "g" => AssemblerPublic.geometry B n H
+
+variable (Q : Layout (CounterPublic.spec prog c |>.lengths n i) n (addressWidth B n) H (CursorBounds.wordBits B n))
+ (D : PrimedCounter.Data Q (n^(c.circuitExponent+5)))
+
+theorem segment_run (hb : 0 < b) (hB : 1 ≤ B) (hn : 3 ≤ n) (hH : H = 2^roundedUp a b n)
+ (fit : PairNativeGeometry.Fits a b n W) (hp : Q.program = prog) (hbase : Q.scratchBase = 2^D₀)
+ (hf : D.Fits) (hroot : D.root.val = 0) (hw : 2 ≤ W) (hc : 2^D₀*2^E₀ < 2^W)
+ (M : Machine W p r 11) (hpub : M.publicData = Pieces.word g (CounterPublic.actualPrefix prog) ∘ StageOperands.pair c)
+ (install : Contains A M) (m : Memory W) (st : Config W p r) (enter : st.pc = A.entry .geometry)
+ (before : (M.publicData 6).val < NativeFrame.frameBase (NativeFrame.fromHeader degree M.publicData (st.reg (A.saved header)) m))
+ (room : (NativeFrame.fromHeader degree M.publicData (st.reg (A.saved header)) m).cacheBase+38 ≤ 2^W) :
+ ∃ t ≤ work (NativeCache.args c) a b g+76, ∃ out,
+ Ready c degree a b A m M.publicData st out (LeafVisit.cacheWords D D₀ E₀) ∧
+ ∀ fuel bits, execute M.program (fuel+t+degree+143) st m bits =
+ (execute M.program fuel out m bits).map
+ (Flow.prependEvents (NativeFrame.events degree (st.reg (A.saved header)) m ++ List.replicate (t+2) .tick)) := by
+ let emb := placement c degree a b A
+ let ret := ret c degree a b A
+ obtain ⟨t,ht,mid,stop,persist,hist,geom,fields,cache,rest,regs,run⟩ :=
+ NativeLeafSetup.paper_run K Q D hb hB hn hH fit hp hbase hf hroot hw hc M hpub
+ emb ret (linked c degree a b A M install) m st (enter.trans (entry_eq c degree a b A).symm) before room
+ let out := {mid with pc := A.entry .rootFields}
+ have finish : M.program.step mid = .localStep out := by
+ change (M.code mid.pc).run M.publicData mid = _
+ rw [stop, linked c degree a b A M install]
+ rw [NativeLeafSetup.done,NativeLeafSetup.cache_row,NativeCacheTable.row_done]
+ simp only [VertexGeometry.ret,Instr.resize,Instr.run,ite_self,out,VertexImage.Placement.returns]
+ refine ⟨t,ht,out,⟨rfl,persist,?_,?_,hist,geom,fields,cache,rest⟩,?_⟩
+ · intro j
+ apply regs
+ · rintro ⟨k,e⟩; exact dfs_disjoint A j _ e.symm
+ · exact A.reg.injective.ne (by simp)
+ · rintro ⟨k,e⟩; exact dfs_disjoint A j _ e.symm
+ · intro j hj
+ apply regs
+ · rintro ⟨k,e⟩; exact saved_disjoint A j _ e.symm
+ · exact A.saved.injective.ne hj
+ · rintro ⟨k,e⟩; exact saved_disjoint A j _ e.symm
+ · intro fuel bits
+ have go := run (fuel+1) bits
+ change execute M.program ((fuel+1)+t+degree+142) st m bits = _ at go
+ rw [show fuel+t+degree+143 = (fuel+1)+t+degree+142 by omega, go,execute,finish,Option.map_map]
+ congr 1
+ funext rep
+ simp only [Function.comp_apply,Flow.prependEvents,Report.prepend,List.replicate_succ',List.append_assoc]
+ rfl
+
+end PairSimulation.VertexGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexGeometrySegment.lean b/lean/OAI/Computability/VPVNP/PairVertexGeometrySegment.lean
new file mode 100644
index 0000000000..1da092f600
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexGeometrySegment.lean
@@ -0,0 +1,193 @@
+import OAI.Computability.VPVNP.PairNativeLeafSetupTable
+import OAI.Computability.VPVNP.PairVertexSiteSegments
+
+/-! # Installing the combined geometry and cache in the terminal vertex image
+
+The segment uses the caller's saved header, role, and histogram registers.
+Its two instruction ranges and its two private register ranges are disjoint.
+Renaming the arithmetic and operand flows preserves both instruction counts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexGeometry
+
+open BurstRAM PrivateRAM LiveProgram PrimedInputRAM NativeOperands VertexImage
+open scoped Fin.CommRing
+
+attribute [local irreducible] NativeOperands.capacity NativeOperands.saved
+
+variable (c : Constants) (degree a b : ℕ)
+
+/-- Geometry instruction count before relocation. -/
+def frameCount := 2 + (NativeFrame.reads.length + (NativeFrame.arithmetic degree).length) + 29
+/-- Instruction count of the finite cache computation and its 38 stores. -/
+def cacheCount := (NativeCache.block c a b).length + 2*NativeCacheTable.count + 2
+/-- Total number of program-counter slots used by the geometry segment. -/
+def count := frameCount degree + cacheCount c a b
+/-- Size of the segment's private register bank. -/
+abbrev regs := 24 + NativeCache.bankSize c
+
+variable {p r : ℕ}
+
+/-- The first 24 private registers, used by the geometry reader. -/
+def workBank (rs : Fin (regs c) ↪ Fin r) := (Fin.castAddEmb (NativeCache.bankSize c)).trans rs
+/-- Private registers following the geometry reader's register bank. -/
+def cacheBank (rs : Fin (regs c) ↪ Fin r) := (Fin.natAddEmb 24).trans rs
+
+private theorem frame_length (ws : Fin 24 ↪ Fin r) (head role : Fin r) :
+ NativeFrame.Table.size (NativeFrame.prelude degree ws head role) = frameCount degree := by
+ simp only [NativeFrame.Table.size,NativeFrame.prelude,Flow.length,PrimedCounter.rename_length,frameCount]
+
+private theorem cache_length (cs : Fin (NativeCache.bankSize c) ↪ Fin r) :
+ NativeCacheTable.size (NativeCache.code c a b cs) = cacheCount c a b := by
+ simp only [NativeCacheTable.size,NativeCache.code,NativeCache.relocated,PrimedCounter.rename_length,cacheCount]
+
+variable (pc : Fin (count c degree a b) → Fin p) (bank : Saved ↪ Fin r) (rs : Fin (regs c) ↪ Fin r)
+ (finish : Fin p)
+
+private abbrev f := NativeFrame.prelude degree (workBank c rs) (bank header) (bank roleOffset)
+private abbrev cacheCode := NativeCache.code c a b (cacheBank c rs)
+
+private theorem length_eq : NativeFrame.Table.size (f c degree bank rs) + NativeCacheTable.size (cacheCode c a b rs)
+ = count c degree a b := by rw [frame_length,cache_length,count]
+
+/-- Two-bit opcodes are padded to the vertex image's five-bit literal type. -/
+def text (j : Fin (count c degree a b)) : Instr 5 p r 11 :=
+ let F := f c degree bank rs
+ let C := cacheCode c a b rs
+ let address := pc ∘ Fin.cast (length_eq c degree a b bank rs)
+ let front (i : Fin (NativeFrame.Table.size F)) := address (i.castAdd (NativeCacheTable.size C))
+ let tail (i : Fin (NativeCacheTable.size C)) := address (i.natAdd (NativeFrame.Table.size F))
+ let start := tail (NativeCacheTable.label C C.entry)
+ let dest := (cacheBank c rs) (saved (NativeCache.args c))
+ let transfer : Instr 2 p r 11 := .jumpEq dest dest start start
+ let ret : Instr 2 p r 11 := .jumpEq (bank histBase) (bank histBase) finish finish
+ let emit : Fin (NativeFrame.Table.size F + NativeCacheTable.size C) → Instr 2 p r 11 :=
+ Fin.addCases (NativeFrame.Table.row F (workBank c rs) (bank histBase) dest front transfer)
+ (NativeCacheTable.row C (NativeCache.storeSrc c (cacheBank c rs)) (NativeCache.ptr c (cacheBank c rs))
+ (NativeCache.one c (cacheBank c rs)) tail ret)
+ (emit (Fin.cast (length_eq c degree a b bank rs).symm j)).resize 5
+
+/-- Geometry component installed between the ordinal guard and the root gather. -/
+def segment : Segment where
+ count := count c degree a b
+ privateRegs := regs c
+ entry := ⟨0,by unfold count frameCount; omega⟩
+ row pc _ bank rs finish := text c degree a b pc bank rs finish
+
+private theorem disjoint {S : Part → Segment} {p r : ℕ} (A : VertexImage.Placement S p r)
+ (s : Saved) (i : Fin (S Part.geometry).privateRegs) :
+ A.saved s ≠ A.localRegs Part.geometry i := by
+ change A.reg (.inr (.inl s)) ≠ A.reg (.inr (.inr (.inr ⟨.geometry,i⟩)))
+ exact A.reg.injective.ne (by simp)
+
+variable {rootFields leaf shrink refresh : Segment}
+local notation "S" => segments (segment c degree a b) rootFields leaf shrink refresh
+variable (A : VertexImage.Placement (segments (segment c degree a b) rootFields leaf shrink refresh) p r)
+
+private theorem allocated : (S .geometry).privateRegs = regs c := rfl
+private theorem labels : (S .geometry).count = count c degree a b := rfl
+
+attribute [local irreducible] segments segment
+
+/-- The combined geometry and cache registers in the actual linked vertex image. -/
+noncomputable def bankFor : Fin (regs c) ↪ Fin r :=
+ (Fin.castLEEmb (allocated (rootFields := rootFields) (leaf := leaf) (shrink := shrink) (refresh := refresh)
+ c degree a b).ge).trans (A.localRegs .geometry)
+
+/-- Locate a geometry opcode in the enclosing vertex program. -/
+noncomputable def labelsFor (j : Fin (count c degree a b)) : Fin p :=
+ A.stage .geometry (j.cast (labels (rootFields := rootFields) (leaf := leaf) (shrink := shrink) (refresh := refresh)
+ c degree a b).symm)
+
+/-- Construct the native initialization block from disjoint saved and private registers. -/
+def placedBlock (banks : ∀ s j, bank s ≠ rs j) : NativeLeafSetup.Block c r where
+ degree := degree
+ numerator := a
+ denominator := b
+ frame := ⟨workBank c rs, bank header, bank roleOffset, bank histBase,
+ (cacheBank c rs) (saved (NativeCache.args c)), banks _ _, banks _ _, banks _ _⟩
+ cache := cacheBank c rs
+ basePort := rfl
+ histogramPort := by rintro ⟨j,hj⟩; exact banks _ _ hj.symm
+
+/-- Initialization block with the actual caller's header, role and histogram registers. -/
+noncomputable def block : NativeLeafSetup.Block c r :=
+ placedBlock c degree a b A.saved (bankFor c degree a b A) (fun s j =>
+ disjoint A s ((Fin.castLEEmb (allocated (rootFields := rootFields) (leaf := leaf)
+ (shrink := shrink) (refresh := refresh) c degree a b).ge) j))
+
+local notation "K" => block c degree a b A
+
+/-- Physical address of an instruction in the combined native block. -/
+noncomputable def placement (j : Fin (NativeLeafSetup.size K)) : Fin p :=
+ labelsFor c degree a b A (Fin.cast (length_eq c degree a b A.saved (bankFor c degree a b A)) j)
+
+theorem entry_eq : placement c degree a b A (NativeLeafSetup.entry K) = A.entry .geometry := by
+ apply congrArg (A.stage .geometry)
+ apply Fin.ext
+ unfold segments segment
+ rfl
+
+/-- Unconditional jump from the last cache instruction to the root-field gather. -/
+noncomputable def ret : Instr 2 p r 11 := .jumpEq (A.saved histBase) (A.saved histBase) (A.returns .geometry) (A.returns .geometry)
+
+variable {w : ℕ} (M : Machine w p r 11)
+
+private theorem resize (op : Instr 2 p r 11) : (op.resize 5).resize w = op.resize w := by
+ cases op <;> try rfl
+ case constant _ val _ => simp only [Instr.resize, resize_literal (by decide : 2 ≤ 5)]
+
+attribute [local irreducible] NativeFrame.Table.row NativeCacheTable.row NativeFrame.prelude PrimedCounter.renameFlow NativeOperands.vector
+
+private theorem text_at (banks : ∀ s j, bank s ≠ rs j)
+ (j : Fin (NativeLeafSetup.size (placedBlock c degree a b bank rs banks))) :
+ text c degree a b pc bank rs finish (Fin.cast (length_eq c degree a b bank rs) j) =
+ (NativeLeafSetup.row (placedBlock c degree a b bank rs banks)
+ (pc ∘ Fin.cast (length_eq c degree a b bank rs))
+ (.jumpEq (bank histBase) (bank histBase) finish finish) j).resize 5 := by
+ unfold text NativeLeafSetup.row
+ rfl
+
+attribute [local irreducible] text count frameCount cacheCount
+
+private theorem transfer {T : Part → Segment} (V : VertexImage.Placement T p r)
+ (N : Machine w p r 11) (hi : Contains V N) (seg : Segment) (he : T .geometry = seg)
+ (j : Fin seg.count) :
+ N.code (V.stage .geometry (j.cast (congrArg Segment.count he).symm)) =
+ (seg.row (fun i => V.stage .geometry (i.cast (congrArg Segment.count he).symm))
+ V.dfs V.saved ((Fin.castLEEmb (congrArg Segment.privateRegs he).ge).trans (V.localRegs .geometry))
+ (V.returns .geometry) j).resize w := by
+ subst seg
+ exact stage_linked V N hi .geometry j
+
+attribute [local semireducible] segment
+
+private theorem text_link (h : Contains A M) (j : Fin (count c degree a b)) :
+ M.code (labelsFor c degree a b A j) =
+ (text c degree a b (labelsFor c degree a b A) A.saved (bankFor c degree a b A)
+ (A.returns .geometry) j).resize w := by
+ have he : (S .geometry) = segment c degree a b := by unfold segments; rfl
+ have hrow := transfer A M h (segment c degree a b) he
+ have e : labelsFor c degree a b A =
+ fun j => A.stage .geometry (j.cast (congrArg Segment.count he).symm) := rfl
+ rw [e]
+ simpa only [segment,bankFor] using hrow j
+
+/-- Actual opcode at every geometry and cache PC in the full linked image. -/
+theorem linked (h : Contains A M) (j : Fin (NativeLeafSetup.size K)) :
+ M.code (placement c degree a b A j) =
+ (NativeLeafSetup.row K (placement c degree a b A) (ret c degree a b A) j).resize w := by
+ change M.code (labelsFor c degree a b A _) = _
+ rw [text_link c degree a b A M h, text_at c degree a b (labelsFor c degree a b A) A.saved
+ (bankFor c degree a b A) (A.returns .geometry) (fun s j => disjoint A s _) j, resize]
+ rfl
+
+end PairSimulation.VertexGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexImage.lean b/lean/OAI/Computability/VPVNP/PairVertexImage.lean
new file mode 100644
index 0000000000..34bacb68a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexImage.lean
@@ -0,0 +1,254 @@
+import OAI.Computability.VPVNP.PairNodeDispatch
+import OAI.Computability.VPVNP.PairSimulationCounters
+
+/-!
+# The finite native image of a final-vertex call
+
+The site bootstrap and final-wire loader enter a common nine-row DFS.
+Its role router and histogram flush obtain their branch-dependent bases
+from a private geometry table. The three native role bodies return to the
+same child-list header. All labels and registers of the table are finite
+and independent of the input length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM
+open scoped Fin.CommRing
+
+/-- Stable bootstrap registers, in the terminal caller's order. -/
+abbrev Saved := Fin 11
+/-- Saved register holding the displacement from DFS node addresses to their role words. -/
+def roleOffset : Saved := 0
+/-- Saved register for the base address of the private histogram counters. -/
+def histBase : Saved := 1
+/-- Saved register for the ordinal of the final site being processed. -/
+def ordinal : Saved := 2
+/-- Saved register for the selected final site's root DFS node address. -/
+def root : Saved := 3
+/-- Saved register holding the external terminal header address. -/
+def header : Saved := 4
+/-- Saved register holding the number of final sites from the terminal header. -/
+def finalSites : Saved := 5
+/-- Saved register holding the count of numbered final arc slots. -/
+def slots : Saved := 6
+/-- Saved register pointing to the final arc-width column. -/
+def widths : Saved := 7
+/-- Saved register pointing to the final incoming incidence column. -/
+def incoming : Saved := 8
+/-- Saved register pointing to the terminal width-prefix column. -/
+def prefixBase : Saved := 9
+/-- Saved register pointing to the shared final wire-bit interval. -/
+def wires : Saved := 10
+
+/-- A relocated block has its own labels and private registers. The common
+DFS and bootstrap registers are explicit arguments. Five literal bits cover
+the constants of the full cursor-leaf program. -/
+structure Segment where
+ /-- Number of instructions owned by this linked vertex segment. -/
+ count : ℕ
+ /-- Number of local registers required by the segment in addition to the DFS and saved banks. -/
+ privateRegs : ℕ
+ /-- Local instruction ordinal at which control enters the segment. -/
+ entry : Fin count
+ /-- Instruction generator for this segment under the given program-counter and register
+ placements and continuation. -/
+ row : ∀ {p r : ℕ}, (Fin count → Fin p) → (Fin 9 ↪ Fin r) → (Saved ↪ Fin r) →
+ (Fin privateRegs ↪ Fin r) → Fin p → Fin count → Instr 5 p r 11
+
+/-- The installed components of a terminal vertex computation, from bootstrap and geometry to
+the three role handlers and the final return. -/
+inductive Part where
+ | bootstrap | geometry | rootFields | leaf | shrink | refresh | finish
+ deriving DecidableEq
+
+instance : Fintype Part :=
+ ⟨{.bootstrap,.geometry,.rootFields,.leaf,.shrink,.refresh,.finish}, fun i => by cases i <;> decide⟩
+
+/-- Choose the leaf, shrink, or refresh instruction segment for a decoded node role. -/
+def rolePart : NodeDispatch.Role → Part
+ | .leaf => .leaf
+ | .shrink => .shrink
+ | .refresh => .refresh
+
+/-- Labels of the shared vertex control code, including DFS, packet copying, role dispatch, and
+histogram flushing. -/
+inductive CorePC where
+ | dfs (i : Fin 9)
+ | copy (i : Fin 5)
+ | roleBase (i : Fin 3)
+ | dispatch (i : Fin 6)
+ | histBase (i : Fin 3)
+ | flushStart (i : Fin 7)
+ | flush (i : Fin 7)
+ | accept
+ deriving DecidableEq, Fintype
+
+variable (S : Part → Segment)
+
+/-- A vertex instruction address is either a shared control label or an instruction ordinal
+inside one named segment. -/
+abbrev PC := CorePC ⊕ (i : Part) × Fin (S i).count
+/-- The vertex register space combines the DFS, saved, and counter banks with a separate local
+bank for each segment. -/
+abbrev Reg := Fin 9 ⊕ Saved ⊕ Fin 6 ⊕ (i : Part) × Fin (S i).privateRegs
+
+/-- An enclosing program can install the image among its other opcodes. -/
+structure Placement (p r : ℕ) where
+ /-- Inject the shared and per-segment instruction addresses into the enclosing machine's
+ program counters. -/
+ pc : PC S ↪ Fin p
+ /-- Inject the vertex's named register banks into the enclosing machine's registers. -/
+ reg : Reg S ↪ Fin r
+
+namespace Placement
+
+variable {S} {p r : ℕ} (A : Placement S p r)
+
+/-- Place a shared vertex control label at its host program counter. -/
+def core (i : CorePC) := A.pc (.inl i)
+/-- Place a local instruction ordinal of a named segment at its host program counter. -/
+def stage (i : Part) (j : Fin (S i).count) := A.pc (.inr ⟨i,j⟩)
+/-- The host program counter of a named segment's designated entry instruction. -/
+def entry (i : Part) := A.stage i (S i).entry
+/-- Embedding of the nine DFS registers into the host machine. -/
+def dfs : Fin 9 ↪ Fin r := Function.Embedding.inl.trans A.reg
+/-- Embedding of the vertex operands that remain available across segment calls. -/
+def saved : Saved ↪ Fin r := Function.Embedding.inl.trans (Function.Embedding.inr.trans A.reg)
+/-- Embedding of the six registers used by the vertex counter and flush operations. -/
+def counter : Fin 6 ↪ Fin r :=
+ Function.Embedding.inl.trans (Function.Embedding.inr.trans (Function.Embedding.inr.trans A.reg))
+
+/-- Embed one named segment's private register bank in the enclosing vertex register space. -/
+def localRegs (i : Part) : Fin (S i).privateRegs ↪ Fin r where
+ toFun j := A.reg (.inr (.inr (.inr ⟨i,j⟩)))
+ inj' _ _ h := by simpa only [A.reg.injective.eq_iff,Sum.inr.injEq,Sigma.mk.injEq,heq_eq_eq,true_and] using h
+
+/-- Host program counter of one instruction in the common DFS controller. -/
+def dfsPC (i : Fin 9) := A.core (.dfs i)
+/-- Host program counter of one instruction in the packet-copy control block. -/
+def copyPC (i : Fin 5) := A.core (.copy i)
+/-- Host program counter of one instruction in the node-role dispatcher. -/
+def rolePC (i : Fin 6) := A.core (.dispatch i)
+/-- Host program counter of one instruction in the histogram flush loop. -/
+def flushPC (i : Fin 7) := A.core (.flush i)
+/-- Host program counter of one instruction that prepares the histogram flush. -/
+def flushStartPC (i : Fin 7) := A.core (.flushStart i)
+/-- Use the first five DFS registers as the register bank of the private copy loop. -/
+def copyRegs : Fin 5 ↪ Fin r := (Fin.castAddEmb 4).trans A.dfs
+
+/-- Continuation address after each vertex segment, linking bootstrap to geometry, geometry to
+root fields, and the role handlers back to DFS. -/
+def returns : Part → Fin p
+ | .bootstrap => A.entry .geometry
+ | .geometry => A.entry .rootFields
+ | .rootFields => A.dfsPC 0
+ | .leaf | .shrink | .refresh => A.dfsPC 3
+ | .finish => A.core .accept
+
+end Placement
+
+/-- Read the private geometry pointer from the word at the DFS stack's
+exclusive end, then form the address of a fixed geometry field. -/
+def geometryRows {p r W : ℕ} (pc : Fin 3 → Fin p) (endReg dst tmp : Fin r)
+ (offset : Word W) (done : Fin p) : Fin 3 → Instr W p r 11 :=
+ ![.loadPrivate dst endReg (pc 1), .constant tmp offset (pc 2),
+ .binary .add dst dst tmp done]
+
+/-- The role offset is a private word in the terminal header. The rest of
+the router is the common six-row role decoder. -/
+def dispatchRows {p r W : ℕ} (pc : Fin 6 → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (entry : NodeDispatch.Role → Fin p) (i : Fin 6) : Instr W p r 11 :=
+ if i = 0 then .loadPrivate (dfs 0) (dfs 0) (pc 1) else NodeDispatch.instruction pc dfs 0 entry i
+
+/-- Public words 4, 5 and 9 give the external counter base, production
+count and template count. Register 2 initially addresses the private
+geometry slot containing the histogram base. -/
+def flushStartRows {p r W : ℕ} (pc : Fin 7 → Fin p) (reg : Fin 6 ↪ Fin r)
+ (loop : Fin p) (i : Fin 7) : Instr W p r 11 :=
+ if i = 5 then .loadPrivate (reg 2) (reg 2) (pc 6) else
+ Counters.entryCode pc reg ![4,5,9,0] loop i
+
+variable {S} {p r : ℕ} (A : Placement S p r)
+
+/-- All parts share one opcode array and one physical register space. -/
+def rows : PC S → Instr 5 p r 11
+ | .inl (.dfs i) => DFS.instruction A.dfsPC A.dfs (A.core (.roleBase 0)) (A.copyPC 0) (A.core (.histBase 0)) i
+ | .inl (.copy i) => EndpointBits.instruction A.copyPC A.copyRegs (A.dfsPC 0) i
+ | .inl (.roleBase i) => geometryRows (fun j => A.core (.roleBase j)) (A.dfs 6) (A.dfs 0) (A.dfs 1) 10 (A.rolePC 0) i
+ | .inl (.dispatch i) => dispatchRows A.rolePC A.dfs (A.entry ∘ rolePart) i
+ | .inl (.histBase i) => geometryRows (fun j => A.core (.histBase j)) (A.dfs 6) (A.counter 2) (A.counter 5) 11 (A.flushStartPC 0) i
+ | .inl (.flushStart i) => flushStartRows A.flushStartPC A.counter (A.flushPC 0) i
+ | .inl (.flush i) => Counters.instruction A.flushPC A.counter (A.entry .finish) i
+ | .inl .accept => .accept
+ | .inr ⟨i,j⟩ => (S i).row (A.stage i) A.dfs A.saved (A.localRegs i) (A.returns i) j
+
+variable {W : ℕ} (M : Machine W p r 11)
+
+/-- The host machine contains every placed vertex instruction at its width-resized encoding. -/
+def Contains : Prop := ∀ loc, M.code (A.pc loc) = (rows A loc).resize W
+
+/-- The exact rows used by the DFS and both physical copy/flush loops. -/
+theorem core_linked (h : Contains A M) :
+ DFS.Linked M A.dfsPC A.dfs (A.core (.roleBase 0)) (A.copyPC 0) (A.core (.histBase 0)) ∧
+ EndpointBits.Linked M A.copyPC A.copyRegs (A.dfsPC 0) ∧
+ Counters.Linked M A.flushPC A.counter (A.entry .finish) := by
+ refine ⟨fun i => (h (.inl (.dfs i))).trans ?_,fun i => (h (.inl (.copy i))).trans ?_,
+ fun i => (h (.inl (.flush i))).trans ?_⟩
+ all_goals fin_cases i <;> rfl
+
+theorem dispatch_linked (h : Contains A M) : ∀ i, M.code (A.rolePC i) =
+ dispatchRows A.rolePC A.dfs (A.entry ∘ rolePart) i := by
+ intro i
+ apply (h (.inl (.dispatch i))).trans
+ fin_cases i <;> rfl
+
+theorem flushStart_linked (h : Contains A M) : ∀ i, M.code (A.flushStartPC i) =
+ flushStartRows A.flushStartPC A.counter (A.flushPC 0) i := by
+ intro i
+ apply (h (.inl (.flushStart i))).trans
+ fin_cases i <;> rfl
+
+theorem roleBase_linked (h : Contains A M) : ∀ i, M.code (A.core (.roleBase i)) =
+ geometryRows (fun j => A.core (.roleBase j)) (A.dfs 6) (A.dfs 0) (A.dfs 1) 10 (A.rolePC 0) i := by
+ intro i
+ apply (h (.inl (.roleBase i))).trans
+ fin_cases i <;> rfl
+
+theorem histBase_linked (h : Contains A M) : ∀ i, M.code (A.core (.histBase i)) =
+ geometryRows (fun j => A.core (.histBase j)) (A.dfs 6) (A.counter 2) (A.counter 5) 11 (A.flushStartPC 0) i := by
+ intro i
+ apply (h (.inl (.histBase i))).trans
+ fin_cases i <;> rfl
+
+theorem stage_linked (h : Contains A M) (i : Part) (j : Fin (S i).count) :
+ M.code (A.stage i j) = ((S i).row (A.stage i) A.dfs A.saved (A.localRegs i) (A.returns i) j).resize W :=
+ h (.inr ⟨i,j⟩)
+
+variable (S)
+
+/-- Canonical numerical labels of the assembled width-independent table. -/
+noncomputable def placement : Placement S (Fintype.card (PC S)) (Fintype.card (Reg S)) :=
+ ⟨(Fintype.equivFin _).toEmbedding,(Fintype.equivFin _).toEmbedding⟩
+
+/-- Assemble the numbered vertex instructions into a five-bit template entered at the bootstrap
+segment. -/
+noncomputable def template : Template (Fintype.card (PC S)) (Fintype.card (Reg S)) 11 where
+ literalWidth := 5
+ entry := (placement S).entry .bootstrap
+ code i := rows (placement S) ((Fintype.equivFin _).symm i)
+
+theorem template_contains (pub : Fin 11 → Word W) :
+ Contains (placement S) ((template S).instantiate W pub) := by
+ intro loc
+ simp [template,Template.instantiate,placement]
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexLevelBoot.lean b/lean/OAI/Computability/VPVNP/PairVertexLevelBoot.lean
new file mode 100644
index 0000000000..57a62e0a9b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexLevelBoot.lean
@@ -0,0 +1,170 @@
+import OAI.Computability.VPVNP.PairVertexLevelBounds
+import OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+/-! # Hosted initialization of the descending traversal-level scan -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexLevel
+
+open BurstRAM BurstRAM.PrivateRAM TraversalControllerInputs
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.tick ReadPrefix.read ReadPrefix.nil ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r : ℕ}
+
+/-- Copy the popped row address, form the terminal header and read the first
+level header, pitch, stride and number of levels. Start at the last level. -/
+def boot (pc : Fin 24 → Fin p) (reg : Fin 14 ↪ Fin r) (src : Fin r) (next : Fin p) :
+ Fin 24 → Instr w p r 11 :=
+ ![.copy (reg 0) src (pc 1),
+ .constant (reg 8) 1 (pc 2),
+ .publicWord (reg 1) 2 (pc 3),
+ .publicWord (reg 9) 7 (pc 4),
+ .binary .shiftLeft (reg 9) (reg 8) (reg 9) (pc 5),
+ .binary .mul (reg 9) (reg 9) (reg 9) (pc 6),
+ .binary .add (reg 1) (reg 1) (reg 9) (pc 7),
+ .constant (reg 9) 16 (pc 8),
+ .binary .sub (reg 1) (reg 1) (reg 9) (pc 9),
+ .binary .sub (reg 1) (reg 1) (reg 9) (pc 10),
+ .binary .add (reg 9) (reg 1) (reg 9) (pc 11),
+ .readExternal (reg 4) (reg 9) (pc 12),
+ .constant (reg 9) 17 (pc 13),
+ .binary .add (reg 9) (reg 1) (reg 9) (pc 14),
+ .readExternal (reg 2) (reg 9) (pc 15),
+ .constant (reg 9) 15 (pc 16),
+ .binary .add (reg 9) (reg 1) (reg 9) (pc 17),
+ .readExternal (reg 6) (reg 9) (pc 18),
+ .binary .add (reg 9) (reg 1) (reg 8) (pc 19),
+ .readExternal (reg 3) (reg 9) (pc 20),
+ .binary .sub (reg 3) (reg 3) (reg 8) (pc 21),
+ .binary .mul (reg 9) (reg 3) (reg 2) (pc 22),
+ .binary .add (reg 4) (reg 4) (reg 9) (pc 23),
+ .constant (reg 10) 14 next]
+
+theorem resize_boot (pc : Fin 24 → Fin p) (reg : Fin 14 ↪ Fin r) (src : Fin r) (next : Fin p)
+ (i : Fin 24) : (boot (w := 5) pc reg src next i).resize w = boot pc reg src next i := by
+ fin_cases i <;> rfl
+
+/-- The 24 locator-bootstrap events, including reads of the first level, level pitch, row
+pitch, and level count in the terminal header. -/
+def bootEvents (pub : Fin 11 → Word w) (m : Memory w) : List (Event w) :=
+ let read (i : ℕ) := Event.read (terminalHead pub + (i : Word w)) (terminalField pub m i)
+ List.replicate 11 .tick ++ [read 16, .tick, .tick, read 17, .tick, .tick, read 15,
+ .tick, read 1, .tick, .tick, .tick, .tick]
+
+theorem bootEvents_cost (pub : Fin 11 → Word w) (m : Memory w) :
+ (bootEvents pub m).length = 24 ∧ countProbes (bootEvents pub m) = 4 ∧
+ choiceBits (bootEvents pub m) = [] := ⟨rfl, rfl, rfl⟩
+
+/-- The four header probes leave the shared memory unchanged. -/
+theorem bootEvents_after (pub : Fin 11 → Word w) (m : Memory w) :
+ after m (bootEvents pub m) = m := rfl
+
+/-- Register and control state delivered by the locator bootstrap before the descending level
+scan. -/
+structure BootResult (pub : Fin 11 → Word w) (m : Memory w) (reg : Fin 14 ↪ Fin r)
+ (src : Fin r) (next : Fin p) (c out : Config w p r) : Prop where
+ pc : out.pc = next
+ node : out.reg (reg 0) = c.reg src
+ header : out.reg (reg 1) = terminalHead pub
+ pitch : out.reg (reg 2) = terminalField pub m 17
+ index : out.reg (reg 3) = terminalField pub m 1 - 1
+ current : out.reg (reg 4) = terminalField pub m 16 +
+ (terminalField pub m 1 - 1) * terminalField pub m 17
+ stride : out.reg (reg 6) = terminalField pub m 15
+ one : out.reg (reg 8) = 1
+ offset14 : out.reg (reg 10) = 14
+ outside : ∀ j, (∀ i, j ≠ reg i) → out.reg j = c.reg j
+ privateMem : out.privateMem = c.privateMem
+ persistent : out.persistent = c.persistent
+
+variable {M : Machine w p r 11} {pc : Fin 24 → Fin p} {reg : Fin 14 ↪ Fin r}
+variable {src : Fin r} {next : Fin p}
+
+set_option maxHeartbeats 2000000 in
+-- The complete trace normalizes register updates for all 24 linked instructions.
+/-- All 24 instructions execute on the actual host, preserving private memory,
+persistent state, and all registers outside the work bank. -/
+theorem boot_run (linked : ∀ i, M.code (pc i) = boot pc reg src next i)
+ (c : Config w p r) (hc : c.pc = pc 0) (m : Memory w) :
+ ∃ out, BootResult M.publicData m reg src next c out ∧ ∀ fuel bs,
+ execute M.program (fuel + 24) c m bs =
+ (execute M.program fuel out m bs).map
+ (fun rep => ⟨bootEvents M.publicData m ++ rep.events, rep.result⟩) := by
+ let radix := BinaryOp.shiftLeft.eval 1 (M.publicData 7)
+ let upper := M.publicData 2 + radix * radix
+ let head := terminalHead M.publicData
+ let field := terminalField M.publicData m
+ let last := field 1 - 1
+ let c1 := c.put (pc 1) (reg 0) (c.reg src)
+ let c2 := c1.put (pc 2) (reg 8) 1
+ let c3 := c2.put (pc 3) (reg 1) (M.publicData 2)
+ let c4 := c3.put (pc 4) (reg 9) (M.publicData 7)
+ let c5 := c4.put (pc 5) (reg 9) radix
+ let c6 := c5.put (pc 6) (reg 9) (radix * radix)
+ let c7 := c6.put (pc 7) (reg 1) upper
+ let c8 := c7.put (pc 8) (reg 9) 16
+ let c9 := c8.put (pc 9) (reg 1) (upper - 16)
+ let c10 := c9.put (pc 10) (reg 1) head
+ let c11 := c10.put (pc 11) (reg 9) (head + 16)
+ let c12 := c11.put (pc 12) (reg 4) (field 16)
+ let c13 := c12.put (pc 13) (reg 9) 17
+ let c14 := c13.put (pc 14) (reg 9) (head + 17)
+ let c15 := c14.put (pc 15) (reg 2) (field 17)
+ let c16 := c15.put (pc 16) (reg 9) 15
+ let c17 := c16.put (pc 17) (reg 9) (head + 15)
+ let c18 := c17.put (pc 18) (reg 6) (field 15)
+ let c19 := c18.put (pc 19) (reg 9) (head + 1)
+ let c20 := c19.put (pc 20) (reg 3) (field 1)
+ let c21 := c20.put (pc 21) (reg 3) last
+ let c22 := c21.put (pc 22) (reg 9) (last * field 17)
+ let c23 := c22.put (pc 23) (reg 4) (field 16 + last * field 17)
+ let c24 := c23.put next (reg 10) 14
+ have step (i : Fin 24) (d : Config w p r) (hd : d.pc = pc i) {act}
+ (row : (boot pc reg src next i).run M.publicData d = act) : M.program.step d = act := by
+ change (M.code d.pc).run M.publicData d = _
+ rw [hd, linked]
+ exact row
+ have path : ReadPrefix M m c (bootEvents M.publicData m) c24 := by
+ refine ReadPrefix.tick (d := c1) (step 0 c hc ?_) <|
+ ReadPrefix.tick (d := c2) (step 1 c1 rfl ?_) <|
+ ReadPrefix.tick (d := c3) (step 2 c2 rfl ?_) <|
+ ReadPrefix.tick (d := c4) (step 3 c3 rfl ?_) <|
+ ReadPrefix.tick (d := c5) (step 4 c4 rfl ?_) <|
+ ReadPrefix.tick (d := c6) (step 5 c5 rfl ?_) <|
+ ReadPrefix.tick (d := c7) (step 6 c6 rfl ?_) <|
+ ReadPrefix.tick (d := c8) (step 7 c7 rfl ?_) <|
+ ReadPrefix.tick (d := c9) (step 8 c8 rfl ?_) <|
+ ReadPrefix.tick (d := c10) (step 9 c9 rfl ?_) <|
+ ReadPrefix.tick (d := c11) (step 10 c10 rfl ?_) <|
+ ReadPrefix.read (g := fun v => c11.put (pc 12) (reg 4) v) (head + 16) (step 11 c11 rfl ?_) <|
+ ReadPrefix.tick (d := c13) (step 12 c12 rfl ?_) <|
+ ReadPrefix.tick (d := c14) (step 13 c13 rfl ?_) <|
+ ReadPrefix.read (g := fun v => c14.put (pc 15) (reg 2) v) (head + 17) (step 14 c14 rfl ?_) <|
+ ReadPrefix.tick (d := c16) (step 15 c15 rfl ?_) <|
+ ReadPrefix.tick (d := c17) (step 16 c16 rfl ?_) <|
+ ReadPrefix.read (g := fun v => c17.put (pc 18) (reg 6) v) (head + 15) (step 17 c17 rfl ?_) <|
+ ReadPrefix.tick (d := c19) (step 18 c18 rfl ?_) <|
+ ReadPrefix.read (g := fun v => c19.put (pc 20) (reg 3) v) (head + 1) (step 19 c19 rfl ?_) <|
+ ReadPrefix.tick (d := c21) (step 20 c20 rfl ?_) <|
+ ReadPrefix.tick (d := c22) (step 21 c21 rfl ?_) <|
+ ReadPrefix.tick (d := c23) (step 22 c22 rfl ?_) <|
+ ReadPrefix.tick (d := c24) (step 23 c23 rfl ?_) <|
+ ReadPrefix.nil _
+ all_goals first | rfl | simp (config := { zetaDelta := true, decide := true })
+ [boot, Instr.run, Config.put, reg.injective.eq_iff, BinaryOp.eval, terminalHead,
+ sub_sub, show (16 : Word w) + 16 = 32 by ring]
+ refine ⟨c24, ⟨rfl, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_, rfl, rfl⟩, ReadPrefix.execute path⟩
+ all_goals first | intro j hj | skip
+ all_goals simp (config := { zetaDelta := true, decide := true })
+ [Config.put, reg.injective.eq_iff, Function.update_of_ne, *]
+
+end PairSimulation.VertexLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexLevelBounds.lean b/lean/OAI/Computability/VPVNP/PairVertexLevelBounds.lean
new file mode 100644
index 0000000000..02b2705429
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexLevelBounds.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.PairTraversalControllerInputs
+
+/-!
+# Locating the level of a popped traversal node
+
+The DFS node is a row address. The descending scan accepts the first level
+whose published start is at most this address. Its stride quotient recovers
+the exact site ordinal, even when other levels contain no rows.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexLevelBounds
+
+open BurstRAM BurstRAM.PrivateRAM TraversalRows TraversalRoles TraversalControllerInputs
+open scoped Fin.CommRing
+
+/-- The next prefix base is the exclusive end of this layer's rows. -/
+theorem layerBase_succ (cap base : ℕ) (tags : List TaggedLayer) (j : Fin tags.length) :
+ layerBase cap base tags (j.val + 1) =
+ endPos cap (layerBase cap base tags j.val) tags[j].layer := by
+ simp only [layerBase, words, List.take_succ_eq_append_getElem j.isLt,
+ List.map_append, List.map_cons, List.map_nil, List.sum_append, List.sum_cons,
+ List.sum_nil, Nat.add_zero, Nat.mul_add, endPos, address, Nat.add_assoc]
+ rfl
+
+theorem layerBase_mono (cap base : ℕ) (tags : List TaggedLayer) :
+ Monotone (layerBase cap base tags) := by
+ apply monotone_nat_of_le_succ
+ intro i
+ by_cases hi : i < tags.length
+ · rw [layerBase_succ cap base tags ⟨i, hi⟩]
+ exact Nat.le_add_right _ _
+ · simp [layerBase, List.take_of_length_le (Nat.le_of_not_gt hi),
+ List.take_of_length_le (show tags.length ≤ i + 1 by omega)]
+
+/-- The chosen row belongs to its own interval. All earlier exclusive
+ends are below or equal to its address and all later starts are strictly above it. -/
+theorem node_interval (cap base : ℕ) (tags : List TaggedLayer) (j : Fin tags.length)
+ (id : Fin tags[j].layer.count) :
+ let start := layerBase cap base tags
+ let node := address cap (start j.val) id.val
+ start j.val ≤ node ∧ node < start (j.val + 1) ∧
+ (∀ i < j.val, start (i + 1) ≤ node) ∧ (∀ i, j.val < i → node < start i) ∧
+ (node - start j.val) / (cap + 2) = id.val := by
+ intro start node
+ have hlo : start j.val ≤ node := Nat.le_add_right _ _
+ have hhi : node < start (j.val + 1) := by
+ rw [show start (j.val + 1) = _ from layerBase_succ cap base tags j]
+ exact Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_left id.isLt (by omega)) _
+ exact ⟨hlo, hhi, fun i hi => (layerBase_mono cap base tags hi).trans hlo,
+ fun i hi => hhi.trans_le (layerBase_mono cap base tags hi),
+ by simp [node, address, Nat.mul_div_cancel_left _ (by omega : 0 < cap + 2)]⟩
+
+variable {w H first pitch offset cap base : ℕ} {pub : Fin 11 → Word w} {m : Memory w}
+variable {old : TaggedLayer} {ls : List (Fiber w)}
+variable (d : Resident pub m H first pitch offset cap base old ls)
+
+include d in
+/-- The descending scan begins at the actual last level and uses the published header geometry. -/
+theorem resident_geometry :
+ (terminalField pub m 1).val = ls.length + 1 ∧
+ terminalField pub m 15 = ((cap + 2 : ℕ) : Word w) ∧
+ terminalField pub m 16 = (first : Word w) ∧ terminalField pub m 17 = (pitch : Word w) := by
+ simp only [terminal_read d _ (by decide : 1 < 32), terminal_read d _ (by decide : 15 < 32),
+ terminal_read d _ (by decide : 16 < 32), terminal_read d _ (by decide : 17 < 32),
+ d.levels, d.rowStride, d.firstHead, d.levelPitch, and_self]
+
+include d in
+/-- Every live level has a start cell, including the terminal state. -/
+theorem resident_start (i : ℕ) (hi : i ≤ ls.length) :
+ levelField pub m i 14 = (layerBase cap base (old :: ls.map Prod.fst) i : Word w) :=
+ (level_read d i 14 hi (by decide)).trans (d.currentBase i hi)
+
+include d in
+/-- The resident count gives the exclusive end for every level. In particular,
+the terminal level needs no successor header. -/
+theorem resident_end (j : Fin (old :: ls.map Prod.fst).length) :
+ levelField pub m j.val 14 + terminalField pub m 15 * siteCount pub m j.val =
+ (layerBase cap base (old :: ls.map Prod.fst) (j.val + 1) : Word w) := by
+ let tags := old :: ls.map Prod.fst
+ have hj : j.val ≤ ls.length := by simpa using j.isLt
+ have hs := ((resident_schedule d).lookup j).1
+ have count : siteCount pub m j.val = (tags[j].layer.count : Word w) := by
+ rw [← hs]
+ exact Fin.ext (Nat.mod_eq_of_lt (siteCount pub m j.val).isLt).symm
+ rw [resident_start d _ hj, (resident_geometry d).2.1, count, layerBase_succ]
+ simp [endPos, address, tags]
+
+include d in
+/-- Actual header reads give the comparisons of the descending scan and the
+machine's unsigned subtraction and division give the exact owner identifier. -/
+theorem resident_locates (j : Fin (old :: ls.map Prod.fst).length)
+ (id : Fin (old :: ls.map Prod.fst)[j].layer.count) (node : Word w)
+ (hn : node.val = address cap (layerBase cap base (old :: ls.map Prod.fst) j.val) id.val)
+ (fit : layerBase cap base (old :: ls.map Prod.fst) (ls.length + 1) < 2 ^ w) :
+ j.val ≤ (terminalField pub m 1).val - 1 ∧ levelField pub m j.val 14 ≤ node ∧
+ (∀ i, j.val < i → i ≤ (terminalField pub m 1).val - 1 → node < levelField pub m i 14) ∧
+ BinaryOp.div.eval (node - levelField pub m j.val 14) (terminalField pub m 15) =
+ (id.val : Word w) := by
+ let tags := old :: ls.map Prod.fst
+ let start := layerBase cap base tags
+ have hj : j.val ≤ ls.length := by simpa using j.isLt
+ have last : (terminalField pub m 1).val - 1 = ls.length := by rw [(resident_geometry d).1]; omega
+ have starts (i : ℕ) (hi : i ≤ ls.length) : (levelField pub m i 14).val = start i := by
+ rw [resident_start d i hi, Fin.val_natCast]
+ exact Nat.mod_eq_of_lt ((layerBase_mono cap base tags (Nat.le_succ_of_le hi)).trans_lt fit)
+ obtain ⟨hlo, _, _, later, quotient⟩ := node_interval cap base tags j id
+ have le : levelField pub m j.val 14 ≤ node := by
+ change (levelField pub m j.val 14).val ≤ node.val
+ rw [starts _ hj, hn]
+ exact hlo
+ have strideFit : cap + 2 < 2 ^ w := by
+ have positive : 1 ≤ tags[j].layer.count :=
+ Nat.succ_le_of_lt ((Nat.zero_le id.val).trans_lt id.isLt)
+ have bound := Nat.mul_le_mul_left (cap + 2) positive
+ have total := (layerBase_mono cap base tags (Nat.succ_le_succ hj)).trans_lt fit
+ rw [layerBase_succ cap base tags j] at total
+ simp only [Nat.mul_one] at bound
+ unfold endPos address at total
+ omega
+ refine ⟨last ▸ hj, le, ?_, ?_⟩
+ · intro i hi hl
+ change node.val < (levelField pub m i 14).val
+ rw [starts i (last ▸ hl), hn]
+ exact later i hi
+ · change Fin.ofNat _ ((node - levelField pub m j.val 14).val / (terminalField pub m 15).val) = _
+ rw [Fin.sub_val_of_le le, starts j.val hj, hn, (resident_geometry d).2.1,
+ Fin.val_natCast, Nat.mod_eq_of_lt strideFit, quotient]
+ rfl
+
+end PairSimulation.VertexLevelBounds
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexLevelFinish.lean b/lean/OAI/Computability/VPVNP/PairVertexLevelFinish.lean
new file mode 100644
index 0000000000..10c6c2fa1f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexLevelFinish.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairVertexLevelScan
+
+/-!
+# Recovering the selected site's packed ordinal and old header
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexLevel
+
+open BurstRAM BurstRAM.PrivateRAM TraversalControllerInputs NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r : ℕ}
+
+/-- A completed level lookup identifies the successor layer, its row start and owner ordinal,
+and the headers required by the role handler. -/
+structure Located (pub : Fin 11 → Word w) (m : Memory w) (reg : Fin 14 ↪ Fin r)
+ (node : Word w) (oldLevel : ℕ) (owner : Word w) (c : Config w p r) : Prop where
+ state : ScanState pub m reg node (oldLevel + 1) c
+ start : c.reg (reg 5) = levelField pub m (oldLevel + 1) 14
+ owner : c.reg (reg 7) = owner
+ oldHead : c.reg (reg 11) = levelHead pub m oldLevel
+ oldFields : c.reg (reg 12) = levelHead pub m oldLevel + 14
+ stage : c.reg (reg 13) = (oldLevel : Word w)
+
+/-- After the bracketing comparison, five native arithmetic instructions compute
+the old header, its child directory, and the popped row's packed site ordinal. -/
+theorem finish_run {M : Machine w p r 11} {pc : Fin 5 → Fin p} {reg : Fin 14 ↪ Fin r}
+ {done : Fin p} {m : Memory w} {node owner : Word w} {j : ℕ}
+ (link : ∀ i, M.code (pc i) = finish pc reg done i)
+ (c : Config w p r) (hc : c.pc = pc 0) (st : ScanState M.publicData m reg node (j + 1) c)
+ (base : c.reg (reg 5) = levelField M.publicData m (j + 1) 14)
+ (quot : BinaryOp.div.eval (node - levelField M.publicData m (j + 1) 14)
+ (terminalField M.publicData m 15) = owner) :
+ ∃ out, Prefix M m c out [] (List.replicate 5 .tick) ∧ out.pc = done ∧
+ Located M.publicData m reg node j owner out ∧ Frame reg c out := by
+ let a := c.put (pc 1) (reg 13) (j : Word w)
+ let b := a.put (pc 2) (reg 11) (levelHead M.publicData m j)
+ let d := b.put (pc 3) (reg 12) (levelHead M.publicData m j + 14)
+ let e := d.put (pc 4) (reg 9) (node - levelField M.publicData m (j + 1) 14)
+ let out := e.put done (reg 7) owner
+ have atRow (i : Fin 5) (q : Config w p r) (hp : q.pc = pc i) :
+ M.program.step q = (finish pc reg done i).run M.publicData q := by
+ simp only [Machine.program, hp, link]
+ have s₀ : M.program.step c = .localStep a := by
+ rw [atRow 0 c hc]
+ change CallAction.localStep (c.put _ _ (c.reg (reg 3) - c.reg (reg 8))) = _
+ simp [a, st.index, st.one]
+ have s₁ : M.program.step a = .localStep b := by
+ rw [atRow 1 a rfl]
+ change CallAction.localStep (a.put _ _ (a.reg (reg 4) - a.reg (reg 2))) = _
+ simp [a, b, Config.put, st.current, st.pitch, levelHead, add_mul, ← add_assoc]
+ have s₂ : M.program.step b = .localStep d := by
+ rw [atRow 2 b rfl]
+ change CallAction.localStep (b.put _ _ (b.reg (reg 11) + b.reg (reg 10))) = _
+ simp [a, b, d, Config.put, st.offset]
+ have s₃ : M.program.step d = .localStep e := by
+ rw [atRow 3 d rfl]
+ change CallAction.localStep (d.put _ _ (d.reg (reg 0) - d.reg (reg 5))) = _
+ simp [a, b, d, e, Config.put, st.node, base]
+ have s₄ : M.program.step e = .localStep out := by
+ rw [atRow 4 e rfl]
+ change CallAction.localStep (e.put _ _ (BinaryOp.div.eval (e.reg (reg 9)) (e.reg (reg 6)))) = _
+ simp [a, b, d, e, out, Config.put, st.stride, quot]
+ have pre : ReadPrefix M m c (List.replicate 5 .tick) out :=
+ ReadPrefix.tick s₀ (ReadPrefix.tick s₁ (ReadPrefix.tick s₂ (ReadPrefix.tick s₃
+ (ReadPrefix.tick s₄ (ReadPrefix.nil _)))))
+ refine ⟨out, ReadPrefix.execute pre, rfl, ?_, ⟨?_, rfl, rfl⟩⟩
+ · constructor
+ · constructor <;> simp [out, e, d, b, a, Config.put, st.node, st.header, st.pitch,
+ st.index, st.current, st.stride, st.one, st.offset]
+ all_goals simp [out, e, d, b, a, Config.put, base]
+ · intro i hi
+ have h (j : Fin 14) : i ≠ reg j := fun e => hi ⟨j, e.symm⟩
+ simp [out, e, d, b, a, Config.put, Function.update_of_ne (h _)]
+
+end PairSimulation.VertexLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexLevelLocator.lean b/lean/OAI/Computability/VPVNP/PairVertexLevelLocator.lean
new file mode 100644
index 0000000000..16669e5793
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexLevelLocator.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.PairVertexLevelBoot
+import OAI.Computability.VPVNP.PairVertexLevelFinish
+import OAI.Computability.VPVNP.PairVertexImage
+
+/-!
+# The hosted level locator for a nonleaf visit
+
+The popped row selects the level and the packed site. The only shared register read
+by the locator is DFS register seven. Its 35 fixed instructions obtain the old header
+and the child directory from the eleven actual public words and the published tables.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexLevel
+
+open BurstRAM BurstRAM.PrivateRAM TraversalControllerInputs TraversalRoles TraversalRows
+open NodeArguments.ChildScan VertexLevelBounds
+open scoped Fin.CommRing
+
+variable {w p r : ℕ}
+
+/-- Place the 24 bootstrap instructions at the start of the level locator's program-counter
+range. -/
+def bootPC (loc : Fin 35 → Fin p) (i : Fin 24) := loc (i.castAdd 11)
+/-- Place the six descending-scan instructions immediately after the level bootstrap. -/
+def scanPC (loc : Fin 35 → Fin p) (i : Fin 6) := loc ((i.castAdd 5).natAdd 24)
+/-- Place the five locator finishing instructions after both bootstrap and scan. -/
+def finishPC (loc : Fin 35 → Fin p) (i : Fin 5) := loc ((i.natAdd 6).natAdd 24)
+
+/-- The 35-instruction, fourteen-register level locator used by a noninitial DFS role. -/
+def segment : VertexImage.Segment where
+ count := 35
+ privateRegs := 14
+ entry := 0
+ row loc dfs _ reg done i :=
+ Fin.addCases (motive := fun _ => Instr 5 _ _ 11) (boot (bootPC loc) reg (dfs 7) (scanPC loc 0))
+ (fun t => Fin.addCases (motive := fun _ => Instr 5 _ _ 11)
+ (scan (scanPC loc) reg (finishPC loc 0)) (finish (finishPC loc) reg done) t) i
+
+variable (M : Machine w p r 11) (loc : Fin 35 → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (reg : Fin 14 ↪ Fin r) (done : Fin p)
+
+theorem segment_linked (rows : ∀ i, M.code (loc i) =
+ (segment.row loc dfs saved reg done i).resize w) :
+ (∀ i, M.code (bootPC loc i) = boot (bootPC loc) reg (dfs 7) (scanPC loc 0) i) ∧
+ (∀ i, M.code (scanPC loc i) = scan (scanPC loc) reg (finishPC loc 0) i) ∧
+ (∀ i, M.code (finishPC loc i) = finish (finishPC loc) reg done i) := by
+ refine ⟨fun i => ?_, fun i => ?_, fun i => ?_⟩
+ · simpa only [segment, bootPC, Fin.addCases_left, resize_boot] using rows (i.castAdd 11)
+ · simpa only [segment, scanPC, Fin.addCases_right, Fin.addCases_left, resize_scan] using
+ rows ((i.castAdd 5).natAdd 24)
+ · simpa only [segment, finishPC, Fin.addCases_right, resize_finish] using
+ rows ((i.natAdd 6).natAdd 24)
+
+/-- Full trace of a level lookup, combining header initialization, descending tests, and five
+finishing ticks. -/
+def trace (pub : Fin 11 → Word w) (m : Memory w) (level later : ℕ) : List (Event w) :=
+ bootEvents pub m ++ scanEvents pub m level later ++ List.replicate 5 .tick
+
+theorem trace_cost (pub : Fin 11 → Word w) (m : Memory w) (level later : ℕ) :
+ (trace pub m level later).length = 32 + 6 * later ∧
+ countProbes (trace pub m level later) = 5 + later ∧
+ choiceBits (trace pub m level later) = [] := by
+ obtain ⟨bl, bp, bc⟩ := bootEvents_cost pub m
+ simp [trace, bl, bp, bc, CompressorRecords.Greedy.probes_append,
+ PrimedInputRAM.Flow.choiceBits_append, countProbes, choiceBits]
+ omega
+
+/-- On a selected noninitial level, the actual finite locator recovers both indices and
+the exact header. All private cells, all enclosing registers and the pending choice stream
+are preserved. -/
+theorem run (rows : ∀ i, M.code (loc i) = (segment.row loc dfs saved reg done i).resize w)
+ {m : Memory w} {H first pitch offset cap base : ℕ} {old : TaggedLayer} {ls : List (Fiber w)}
+ (d : Resident M.publicData m H first pitch offset cap base old ls)
+ (j : Fin (old :: ls.map Prod.fst).length) (level : ℕ) (hj : j.val = level + 1)
+ (id : Fin (old :: ls.map Prod.fst)[j].layer.count)
+ (c : Config w p r) (hc : c.pc = loc segment.entry)
+ (node : (c.reg (dfs 7)).val = address cap (layerBase cap base (old :: ls.map Prod.fst) j) id)
+ (fit : layerBase cap base (old :: ls.map Prod.fst) (ls.length + 1) < 2 ^ w) :
+ ∃ out, Prefix M m c out [] (trace M.publicData m (level + 1) (ls.length - (level + 1))) ∧
+ out.pc = done ∧ Located M.publicData m reg (c.reg (dfs 7)) level (id.val : Word w) out ∧
+ Frame reg c out := by
+ obtain ⟨hb, hs, hf⟩ := segment_linked M loc dfs saved reg done rows
+ obtain ⟨mid, ready, hbRun⟩ := boot_run hb c hc m
+ obtain ⟨hlen, _, _, _⟩ := resident_geometry d
+ have countEq : terminalField M.publicData m 1 = ((ls.length + 1 : ℕ) : Word w) := by
+ rw [← hlen]
+ exact Fin.ext (Nat.mod_eq_of_lt (terminalField M.publicData m 1).isLt).symm
+ have hcount : terminalField M.publicData m 1 - 1 = (ls.length : Word w) := by
+ simp [countEq]
+ obtain ⟨bound, start, later, quotient⟩ := resident_locates d j id (c.reg (dfs 7)) node fit
+ rw [hlen] at bound later
+ rw [hj] at bound start later
+ conv at quotient => lhs; rw [hj]
+ have eq : level + 1 + (ls.length - (level + 1)) = ls.length := by omega
+ have state : ScanState M.publicData m reg (c.reg (dfs 7)) ls.length mid :=
+ ⟨ready.node, ready.header, ready.pitch, ready.index.trans hcount,
+ by rw [ready.current, hcount]; rfl, ready.stride, ready.one, ready.offset14⟩
+ have bootPre : Prefix M m c mid [] (bootEvents M.publicData m) := by
+ intro fuel bs
+ simpa only [(bootEvents_cost _ _).1, List.nil_append] using hbRun fuel bs
+ have bootFrame : Frame reg c mid := ⟨fun i hi => ready.outside i
+ (fun l e => hi ⟨l, e.symm⟩), ready.privateMem, ready.persistent⟩
+ obtain ⟨endScan, sp, atEnd, value, state', scanFrame⟩ :=
+ scan_run hs (level + 1) (ls.length - (level + 1)) mid ready.pc (by rw [eq]; exact state) start
+ (fun i hi hl => later i hi (by omega))
+ obtain ⟨out, fp, outPC, result, finishFrame⟩ := finish_run hf endScan atEnd state' value quotient
+ exact ⟨out, (bootPre.trans sp).trans fp, outPC, result,
+ bootFrame.trans (scanFrame.trans finishFrame)⟩
+
+end PairSimulation.VertexLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexLevelReads.lean b/lean/OAI/Computability/VPVNP/PairVertexLevelReads.lean
new file mode 100644
index 0000000000..1a7c73b035
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexLevelReads.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.PairVertexLevelLocator
+import OAI.Computability.VPVNP.PairSimulationTerminalSplice
+
+/-! # Read footprint of the traversal-level locator -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexLevel
+
+open BurstRAM CompressorRecords TraversalControllerInputs TraversalRoles
+open scoped Fin.CommRing
+
+variable {w : ℕ} {pub : Fin 11 → Word w} {m : Memory w}
+
+private theorem boot_reads {data : ℕ → Prop}
+ (safe : ∀ i ∈ ({1, 15, 16, 17} : Finset ℕ), data (terminalHead pub + (i : Word w)).val) :
+ SourceTransport.Reads data (bootEvents pub m) := by
+ intro a v h
+ simp only [bootEvents, List.mem_append, List.mem_replicate, List.mem_cons, List.not_mem_nil,
+ reduceCtorEq, Event.read.injEq, and_false, false_or, or_false] at h
+ rcases h with ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩ | ⟨rfl, _⟩
+ · exact safe 16 (by decide)
+ · exact safe 17 (by decide)
+ · exact safe 15 (by decide)
+ · exact safe 1 (by decide)
+
+private theorem scan_reads (j later : ℕ) {data : ℕ → Prop}
+ (safe : ∀ i, j ≤ i → i ≤ j + later → data (levelHead pub m i + 14).val) :
+ SourceTransport.Reads data (scanEvents pub m j later) := by
+ induction later with
+ | zero =>
+ intro a v h
+ simp only [scanEvents, testEvents, List.mem_cons, List.not_mem_nil, reduceCtorEq,
+ Event.read.injEq, false_or, or_false] at h
+ exact h.1 ▸ safe j le_rfl le_rfl
+ | succ n ih =>
+ intro a v h
+ simp only [scanEvents, testEvents, List.mem_append, List.mem_cons, List.not_mem_nil,
+ reduceCtorEq, Event.read.injEq, false_or, or_false] at h
+ rcases h with ⟨rfl, _⟩ | h
+ · exact safe (j + n + 1) (by omega) (by omega)
+ · exact ih (fun i hlo hhi => safe i hlo (by omega)) a v h
+
+/-- The boot reads four terminal fields. Each tested level contributes a
+read of its start cell at offset 14, and the arithmetic exit has no reads. -/
+theorem trace_reads (j later : ℕ) {data : ℕ → Prop}
+ (terminal : ∀ i ∈ ({1, 15, 16, 17} : Finset ℕ), data (terminalHead pub + (i : Word w)).val)
+ (levels : ∀ i, j ≤ i → i ≤ j + later → data (levelHead pub m i + 14).val) :
+ SourceTransport.Reads data (trace pub m j later) := by
+ intro a v h
+ simp only [trace, List.mem_append, List.mem_replicate, reduceCtorEq, and_false, or_false] at h
+ exact h.elim (boot_reads terminal a v) (scan_reads j later levels a v)
+
+/-- All reads avoid the terminal control cells at offsets 0 and 31.
+The level scalars precede the terminal header, and their word addresses
+agree with the natural addresses of their published fields. -/
+theorem trace_worker_reads {H first pitch offset cap base : ℕ} {old : TaggedLayer}
+ {ls : List (Fiber w)} (d : Resident pub m H first pitch offset cap base old ls)
+ (beforeH : ∀ i ≤ ls.length, first + i * pitch + 28 ≤ H)
+ (j later : ℕ) (live : j + later ≤ ls.length) :
+ SourceTransport.Reads (TerminalLink.workerCell (TerminalLink.header pub))
+ (trace pub m j later) := by
+ have head : TerminalLink.header pub = (H : Word w) := d.header
+ have fit := d.headerFits
+ have headVal : (TerminalLink.header pub).val = H := by
+ rw [head, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ have lastVal : (TerminalLink.header pub + 31).val = H + 31 := by
+ rw [head, show (31 : Word w) = ((31 : ℕ) : Word w) from rfl, ← Nat.cast_add,
+ Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ apply trace_reads
+ · intro i hi
+ simp only [Finset.mem_insert, Finset.mem_singleton] at hi
+ simp only [TerminalLink.workerCell, headVal, lastVal, d.header, ← Nat.cast_add,
+ Fin.val_natCast, Nat.mod_eq_of_lt (show H + i < 2 ^ w by omega)]
+ omega
+ · intro i _ hi
+ have hl := hi.trans live
+ have hb := beforeH i hl
+ have addr : (levelHead pub m i + 14).val = first + i * pitch + 14 := by
+ rw [levelHead, terminal_read d 16 (by decide), terminal_read d 17 (by decide),
+ d.firstHead, d.levelPitch, show (14 : Word w) = ((14 : ℕ) : Word w) from rfl,
+ ← Nat.cast_mul, ← Nat.cast_add, ← Nat.cast_add, Fin.val_natCast,
+ Nat.mod_eq_of_lt (by omega)]
+ simp only [TerminalLink.workerCell, headVal, lastVal, addr]
+ omega
+
+end PairSimulation.VertexLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexLevelScan.lean b/lean/OAI/Computability/VPVNP/PairVertexLevelScan.lean
new file mode 100644
index 0000000000..e3ea812fed
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexLevelScan.lean
@@ -0,0 +1,208 @@
+import OAI.Computability.VPVNP.PairVertexLevelBounds
+import OAI.Computability.VPVNP.PairNodeChildLoop
+
+/-!
+# Finding the producing level of a popped DFS node
+
+The native program reads the starting row address of the last level and moves backwards
+until the node lies at or above the current start. It uses one external read per tested
+level. The successful exit computes the previous level header and the packed site number.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexLevel
+
+open BurstRAM BurstRAM.PrivateRAM TraversalControllerInputs NodeArguments.ChildScan
+open scoped Fin.CommRing
+open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.read ReadPrefix.execute
+ from OAI.Computability.VPVNP.PairSimulationPrivateSlices
+
+variable {w p r : ℕ}
+
+/-- Read the candidate level's DFS start, compare it with the popped node, and either finish or
+step back one level. -/
+def scan (pc : Fin 6 → Fin p) (reg : Fin 14 ↪ Fin r) (finish : Fin p) :
+ Fin 6 → Instr w p r 11 :=
+ ![.binary .add (reg 9) (reg 4) (reg 10) (pc 1), .readExternal (reg 5) (reg 9) (pc 2),
+ .jumpLt (reg 0) (reg 5) (pc 3) finish, .binary .sub (reg 4) (reg 4) (reg 2) (pc 4),
+ .binary .sub (reg 3) (reg 3) (reg 8) (pc 5), .jumpEq (reg 8) (reg 8) (pc 0) (pc 0)]
+
+/-- Recover the old level, its child-header address, and the node's site ordinal from the
+successful scan registers. -/
+def finish (pc : Fin 5 → Fin p) (reg : Fin 14 ↪ Fin r) (done : Fin p) :
+ Fin 5 → Instr w p r 11 :=
+ ![.binary .sub (reg 13) (reg 3) (reg 8) (pc 1), .binary .sub (reg 11) (reg 4) (reg 2) (pc 2),
+ .binary .add (reg 12) (reg 11) (reg 10) (pc 3), .binary .sub (reg 9) (reg 0) (reg 5) (pc 4),
+ .binary .div (reg 7) (reg 9) (reg 6) done]
+
+theorem resize_scan (pc : Fin 6 → Fin p) (reg : Fin 14 ↪ Fin r) (exit : Fin p) (j : Fin 6) :
+ (scan (w := 5) pc reg exit j).resize w = scan pc reg exit j := by fin_cases j <;> rfl
+
+theorem resize_finish (pc : Fin 5 → Fin p) (reg : Fin 14 ↪ Fin r) (done : Fin p) (j : Fin 5) :
+ (finish (w := 5) pc reg done j).resize w = finish pc reg done j := by fin_cases j <;> rfl
+
+/-- Events of one descending test, including the read of scalar 14 in the candidate level. -/
+def testEvents (pub : Fin 11 → Word w) (m : Memory w) (j : ℕ) : List (Event w) :=
+ [.tick, .read (levelHead pub m j + 14) (levelField pub m j 14), .tick]
+
+/-- Test the levels from `j + later` down through `j`, including the final test. -/
+def scanEvents (pub : Fin 11 → Word w) (m : Memory w) (j : ℕ) : ℕ → List (Event w)
+ | 0 => testEvents pub m j
+ | n + 1 => testEvents pub m (j + n + 1) ++ [.tick, .tick, .tick] ++ scanEvents pub m j n
+
+@[simp] theorem scanEvents_length (pub : Fin 11 → Word w) (m : Memory w) (j n : ℕ) :
+ (scanEvents pub m j n).length = 6 * n + 3 := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [scanEvents, testEvents, ih]; omega
+
+@[simp] theorem scanEvents_probes (pub : Fin 11 → Word w) (m : Memory w) (j n : ℕ) :
+ countProbes (scanEvents pub m j n) = n + 1 := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [scanEvents, testEvents, countProbes, ih]; omega
+
+@[simp] theorem scanEvents_choices (pub : Fin 11 → Word w) (m : Memory w) (j n : ℕ) :
+ choiceBits (scanEvents pub m j n) = [] := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa [scanEvents, testEvents, choiceBits] using ih
+
+/-- Register invariant of the descending locator, recording the popped node, terminal geometry,
+and the level currently being tested. -/
+structure ScanState (pub : Fin 11 → Word w) (m : Memory w) (reg : Fin 14 ↪ Fin r)
+ (node : Word w) (i : ℕ) (c : Config w p r) : Prop where
+ node : c.reg (reg 0) = node
+ header : c.reg (reg 1) = terminalHead pub
+ pitch : c.reg (reg 2) = terminalField pub m 17
+ index : c.reg (reg 3) = (i : Word w)
+ current : c.reg (reg 4) = levelHead pub m i
+ stride : c.reg (reg 6) = terminalField pub m 15
+ one : c.reg (reg 8) = 1
+ offset : c.reg (reg 10) = 14
+
+/-- Frame condition preserving registers outside the locator bank, private memory, and
+persistent state during level lookup. -/
+structure Frame (reg : Fin 14 ↪ Fin r) (c d : Config w p r) : Prop where
+ outside : ∀ i, i ∉ Set.range reg → d.reg i = c.reg i
+ privateMem : d.privateMem = c.privateMem
+ persistent : d.persistent = c.persistent
+
+theorem Frame.trans {reg : Fin 14 ↪ Fin r} {c d out : Config w p r}
+ (f : Frame reg c d) (g : Frame reg d out) : Frame reg c out :=
+ ⟨fun i hi => (g.outside i hi).trans (f.outside i hi), g.privateMem.trans f.privateMem,
+ g.persistent.trans f.persistent⟩
+
+variable {M : Machine w p r 11} {pc : Fin 6 → Fin p} {reg : Fin 14 ↪ Fin r}
+ {exit : Fin p} {m : Memory w} {node : Word w}
+
+private theorem scan_at (link : ∀ i, M.code (pc i) = scan pc reg exit i)
+ (i : Fin 6) (c : Config w p r) (hc : c.pc = pc i) :
+ M.program.step c = (scan pc reg exit i).run M.publicData c := by
+ simp only [Machine.program, hc, link]
+
+private theorem test (link : ∀ i, M.code (pc i) = scan pc reg exit i)
+ {i : ℕ} (c : Config w p r) (hc : c.pc = pc 0) (st : ScanState M.publicData m reg node i c) :
+ ∃ d, Prefix M m c d [] (testEvents M.publicData m i) ∧
+ d.pc = (if node < levelField M.publicData m i 14 then pc 3 else exit) ∧
+ d.reg (reg 5) = levelField M.publicData m i 14 ∧
+ ScanState M.publicData m reg node i d ∧ Frame reg c d := by
+ let addr := levelHead M.publicData m i + 14
+ let value := levelField M.publicData m i 14
+ let x := c.put (pc 1) (reg 9) addr
+ let y := x.put (pc 2) (reg 5) value
+ let d : Config w p r := {y with pc := if node < value then pc 3 else exit}
+ have hs₀ : M.program.step c = .localStep x := by
+ rw [scan_at link 0 c hc]
+ change CallAction.localStep (c.put _ _ (c.reg (reg 4) + c.reg (reg 10))) = _
+ rw [st.current, st.offset]
+ have hs₁ : M.program.step x = .read addr (fun v => x.put (pc 2) (reg 5) v) := by
+ rw [scan_at link 1 x rfl]
+ change CallAction.read (x.reg (reg 9)) _ = _
+ rw [show x.reg (reg 9) = addr by simp [x]]
+ have hs₂ : M.program.step y = .localStep d := by
+ rw [scan_at link 2 y rfl]
+ change CallAction.localStep {y with pc := if y.reg (reg 0) < y.reg (reg 5) then _ else _} = _
+ simp [d, y, x, Config.put, st.node]
+ have pre : ReadPrefix M m c (testEvents M.publicData m i) d :=
+ ReadPrefix.tick hs₀ (ReadPrefix.read addr hs₁ (ReadPrefix.tick hs₂ (ReadPrefix.nil _)))
+ have same (l : Fin 14) (h₅ : l ≠ 5) (h₉ : l ≠ 9) : d.reg (reg l) = c.reg (reg l) := by
+ simp [d, y, x, Config.put, h₅, h₉]
+ refine ⟨d, ReadPrefix.execute pre, rfl, by simp [d, y, value],
+ ⟨?_, ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩, ⟨?_, rfl, rfl⟩⟩
+ all_goals first | exact (same _ (by decide) (by decide)).trans st.node
+ | exact (same _ (by decide) (by decide)).trans st.header
+ | exact (same _ (by decide) (by decide)).trans st.pitch
+ | exact (same _ (by decide) (by decide)).trans st.index
+ | exact (same _ (by decide) (by decide)).trans st.current
+ | exact (same _ (by decide) (by decide)).trans st.stride
+ | exact (same _ (by decide) (by decide)).trans st.one
+ | exact (same _ (by decide) (by decide)).trans st.offset
+ | skip
+ intro l hl
+ have h₅ : l ≠ reg 5 := fun e => hl ⟨5, e.symm⟩
+ have h₉ : l ≠ reg 9 := fun e => hl ⟨9, e.symm⟩
+ simp [d, y, x, Config.put, Function.update_of_ne h₅, Function.update_of_ne h₉]
+
+private theorem descend (link : ∀ i, M.code (pc i) = scan pc reg exit i)
+ {i : ℕ} (c : Config w p r) (hc : c.pc = pc 3)
+ (st : ScanState M.publicData m reg node (i + 1) c) :
+ ∃ d, Prefix M m c d [] [.tick, .tick, .tick] ∧ d.pc = pc 0 ∧
+ ScanState M.publicData m reg node i d ∧ Frame reg c d := by
+ let x := c.put (pc 4) (reg 4) (levelHead M.publicData m i)
+ let y := x.put (pc 5) (reg 3) (i : Word w)
+ let d : Config w p r := {y with pc := pc 0}
+ have hs₀ : M.program.step c = .localStep x := by
+ rw [scan_at link 3 c hc]
+ change CallAction.localStep (c.put _ _ (c.reg (reg 4) - c.reg (reg 2))) = _
+ rw [st.current, st.pitch]
+ congr 3
+ simp [levelHead, add_mul, ← add_assoc]
+ have hs₁ : M.program.step x = .localStep y := by
+ rw [scan_at link 4 x rfl]
+ change CallAction.localStep (x.put _ _ (x.reg (reg 3) - x.reg (reg 8))) = _
+ simp [y, x, Config.put, st.index, st.one]
+ have hs₂ : M.program.step y = .localStep d := by
+ rw [scan_at link 5 y rfl]
+ change CallAction.localStep {y with pc := if _ then pc 0 else pc 0} = _
+ simp [d]
+ have pre : ReadPrefix M m c [.tick, .tick, .tick] d :=
+ ReadPrefix.tick hs₀ (ReadPrefix.tick hs₁ (ReadPrefix.tick hs₂ (ReadPrefix.nil _)))
+ refine ⟨d, ReadPrefix.execute pre, rfl, ?_, ⟨?_, rfl, rfl⟩⟩
+ · constructor <;> simp [d, y, x, Config.put, st.node, st.header, st.pitch, st.stride,
+ st.one, st.offset]
+ · intro l hl
+ have h₃ : l ≠ reg 3 := fun e => hl ⟨3, e.symm⟩
+ have h₄ : l ≠ reg 4 := fun e => hl ⟨4, e.symm⟩
+ simp [d, y, x, Config.put, Function.update_of_ne h₃, Function.update_of_ne h₄]
+
+/-- Run the descending scan. Empty levels above the selected row are tested normally. -/
+theorem scan_run (link : ∀ i, M.code (pc i) = scan pc reg exit i)
+ (j n : ℕ) (c : Config w p r) (hc : c.pc = pc 0)
+ (st : ScanState M.publicData m reg node (j + n) c)
+ (start : levelField M.publicData m j 14 ≤ node)
+ (later : ∀ i, j < i → i ≤ j + n → node < levelField M.publicData m i 14) :
+ ∃ out, Prefix M m c out [] (scanEvents M.publicData m j n) ∧ out.pc = exit ∧
+ out.reg (reg 5) = levelField M.publicData m j 14 ∧
+ ScanState M.publicData m reg node j out ∧ Frame reg c out := by
+ induction n generalizing c with
+ | zero =>
+ obtain ⟨d, path, pc', base, s, f⟩ := test link c hc st
+ exact ⟨d, path, by simpa [start.not_gt] using pc', base, s, f⟩
+ | succ n ih =>
+ obtain ⟨d, pre, pc', _, s, f⟩ := test link c hc st
+ have lt := later (j + n + 1) (by omega) (by omega)
+ have go : d.pc = pc 3 := by simpa [← Nat.add_assoc, lt] using pc'
+ obtain ⟨y, down, back, state, frame⟩ := descend link d go s
+ obtain ⟨out, path, done, base, so, fo⟩ :=
+ ih y back state (fun i hi bound => later i hi (by omega))
+ exact ⟨out, (pre.trans down).trans path, done, base, so, f.trans (frame.trans fo)⟩
+
+end PairSimulation.VertexLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexLevelSchedule.lean b/lean/OAI/Computability/VPVNP/PairVertexLevelSchedule.lean
new file mode 100644
index 0000000000..76c631dd70
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexLevelSchedule.lean
@@ -0,0 +1,190 @@
+import OAI.Computability.VPVNP.PairVertexLevelLocator
+import OAI.Computability.VPVNP.CompressorLevelOrder
+import OAI.Computability.VPVNP.CompressorDirectoryBudget
+
+/-!
+# The level locator on the selected compression branch
+
+Each block has one shrinking pass at each index, followed by its refresh.
+The locator returns the ordinal of the pass producing the popped row. Its
+remainder within the block selects the degree of the actual kernel reader.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexLevel
+
+open BurstRAM BurstRAM.PrivateRAM CompressorRecords Compression LocalHistory CursorNetwork
+open TraversalRoles TraversalRows TraversalControllerInputs NodeArguments.ChildScan
+open scoped Fin.CommRing
+
+private theorem repeated_range_get (s T i : ℕ)
+ (h : i < (List.replicate T (List.range s)).flatten.length) :
+ (List.replicate T (List.range s)).flatten[i] = i % s := by
+ induction T generalizing i with
+ | zero => simp at h
+ | succ T ih =>
+ simp only [List.replicate_succ, List.flatten_cons] at h ⊢
+ by_cases hi : i < s
+ · rw [List.getElem_append_left (by simpa using hi), List.getElem_range, Nat.mod_eq_of_lt hi]
+ · have le : s ≤ i := Nat.le_of_not_gt hi
+ rw [List.getElem_append_right (by simpa using le), ih, List.length_range,
+ ← Nat.mod_eq_sub_mod le]
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f)
+variable {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices)
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+
+/-- Every block contributes exactly its shrinking passes and one refresh. -/
+theorem selected_pass_count : (passes).length = T * (S.steps + 1) := by
+ simpa [List.length_flatten] using congrArg List.length (executeLevels_order B f hf T hT X z)
+
+/-- Including the cursor input, there is precisely one more traversal level than passes. -/
+theorem selected_level_count : (tags).length = T * (S.steps + 1) + 1 := by
+ simp [TraversalRoles.selected, selected_pass_count B f hf T hT X z]
+
+/-- The block-relative ordinal is the one on the producing pass of the
+mathematical execution, for every occurrence on every choice branch. -/
+theorem selected_pass_ordinal (i : Fin (passes).length) :
+ passes[i].origin.ordinal = i.val % (S.steps + 1) := by
+ have order := executeLevels_order B f hf T hT X z
+ have e := List.getElem_of_eq order (i := i.val) (by simp)
+ rw [List.getElem_map] at e
+ exact e.trans (repeated_range_get _ _ _ _)
+
+private theorem exponent_of_ordinal {a g b n : ℕ} {Y : State a g} {p : StatePass R Y b n}
+ (o : PassOrigin B f hf p) : a = S.exponentAt o.ordinal := by
+ cases o with
+ | shrink i h X => exact (S.exponentAt_castSucc i).symm
+ | refresh X =>
+ simp [PassOrigin.ordinal, BlockSchedule.exponentAt, BlockSchedule.portExponent, Fin.last]
+
+private theorem role_of_ordinal {a g b n : ℕ} {Y : State a g} {p : StatePass R Y b n}
+ (o : PassOrigin B f hf p) :
+ TraversalRoles.ofOrigin o = if o.ordinal = S.steps then .refresh else .shrink := by
+ cases o with
+ | shrink i h X => simp [TraversalRoles.ofOrigin, PassOrigin.ordinal, i.isLt.ne]
+ | refresh X => simp [TraversalRoles.ofOrigin, PassOrigin.ordinal]
+
+/-- The physical old-level ordinal selects exactly the input exponent used
+by the old incidence slots of the true placement-fiber reader. -/
+theorem selected_inputExponent (i : Fin (passes).length) :
+ passes[i].inputExponent = S.exponentAt (i.val % (S.steps + 1)) := by
+ rw [← selected_pass_ordinal B f hf T hT X z i]
+ exact exponent_of_ordinal B f hf passes[i].origin
+
+/-- The unique refresh occupies the last ordinal in the block. -/
+theorem selected_pass_role (i : Fin (passes).length) :
+ tagLevel B f hf passes[i] = if i.val % (S.steps + 1) = S.steps then .refresh else .shrink := by
+ rw [← selected_pass_ordinal B f hf T hT X z i]
+ exact role_of_ordinal B f hf passes[i].origin
+
+variable {w : ℕ}
+
+/-- Upper bounds for a locator call on any actual output level of this branch. -/
+theorem selected_trace_bounds (pub : Fin 11 → Word w) (m : Memory w)
+ (i : Fin (passes).length) :
+ let es := trace pub m (i.val + 1) ((passes).length - (i.val + 1))
+ es.length ≤ 32 + 6 * (T * (S.steps + 1)) ∧ countProbes es ≤ 5 + T * (S.steps + 1) := by
+ intro es
+ obtain ⟨length, probes, _⟩ := trace_cost pub m (i.val + 1) ((passes).length - (i.val + 1))
+ have h := (Nat.sub_le (passes).length (i.val + 1)).trans_eq (selected_pass_count B f hf T hT X z)
+ exact ⟨length.trans_le (Nat.add_le_add_left (Nat.mul_le_mul_left 6 h) 32),
+ probes.trans_le (Nat.add_le_add_left h 5)⟩
+
+open private blocks_le_log from OAI.Computability.VPVNP.CompressorDirectoryBudget
+
+/-- With the paper's genuine block count, both costs are linear in the
+binary logarithm of the input length. The constants depend only on the schedule. -/
+theorem selected_trace_log (u : PairExponents B.growthConstant) {n : ℕ} (hn : 1 ≤ n)
+ (ht : T = blockCount (u.θ : ℝ) n) (pub : Fin 11 → Word w) (m : Memory w)
+ (i : Fin (passes).length) :
+ let es := trace pub m (i.val + 1) ((passes).length - (i.val + 1))
+ es.length ≤ (32 + 6 * (S.steps + 1)) * (n.log2 + 1) ∧
+ countProbes es ≤ (5 + (S.steps + 1)) * (n.log2 + 1) := by
+ intro es
+ have hblocks : T ≤ n.log2 + 1 := ht.trans_le (blocks_le_log B u hn)
+ have h := Nat.mul_le_mul_right (S.steps + 1) hblocks
+ obtain ⟨len, probes⟩ := selected_trace_bounds B f hf T hT X z pub m i
+ constructor
+ · calc
+ es.length ≤ _ := len
+ _ ≤ 32 * (n.log2 + 1) + 6 * ((n.log2 + 1) * (S.steps + 1)) :=
+ Nat.add_le_add (Nat.le_mul_of_pos_right 32 (Nat.succ_pos _)) (Nat.mul_le_mul_left 6 h)
+ _ = _ := by ring
+ · calc
+ countProbes es ≤ _ := probes
+ _ ≤ 5 * (n.log2 + 1) + (n.log2 + 1) * (S.steps + 1) :=
+ Nat.add_le_add (Nat.le_mul_of_pos_right 5 (Nat.succ_pos _)) h
+ _ = _ := by ring
+
+set_option maxHeartbeats 800000 in
+-- Instantiating the locator identifies the selected level in two dependent row lists.
+/-- Execute the linked locator on a row of an actual selected term. The stage
+register supplies the native remainder for the kernel, the owner is the row's
+packed site ordinal, and the trace uses the true number of later levels. -/
+theorem selected_run {p r H first pitch offset base : ℕ} {raw m : Memory w}
+ (ds : (j : Fin (passes).length) → LevelDirectory passes[j] raw base)
+ (M : Machine w p r 11) (loc : Fin 35 → Fin p) (dfs : Fin 9 ↪ Fin r)
+ (saved : VertexImage.Saved ↪ Fin r) (reg : Fin 14 ↪ Fin r) (done : Fin p)
+ (rows : ∀ j, M.code (loc j) = (segment.row loc dfs saved reg done j).resize w)
+ (d : Resident M.publicData m H first pitch offset B.recordLimit base
+ ⟨leafLayer (siteOrder X), .cursor⟩ (levelFibers passes ds))
+ (i : Fin (passes).length) (id : Fin passes[i].outputSites)
+ (c : Config w p r) (hc : c.pc = loc segment.entry)
+ (node : (c.reg (dfs 7)).val = address B.recordLimit
+ (layerBase B.recordLimit base tags (i.val + 1)) id.val)
+ (fit : layerBase B.recordLimit base tags ((passes).length + 1) < 2 ^ w) :
+ ∃ out, Prefix M m c out [] (trace M.publicData m (i.val + 1) ((passes).length - (i.val + 1))) ∧
+ out.pc = done ∧ Located M.publicData m reg (c.reg (dfs 7)) i.val (id.val : Word w) out ∧
+ (BinaryOp.mod.eval (out.reg (reg 13)) ((S.steps + 1 : ℕ) : Word w)).val =
+ passes[i].origin.ordinal ∧
+ Frame reg c out := by
+ let old : TaggedLayer := ⟨leafLayer (siteOrder X), .cursor⟩
+ let fibers := levelFibers passes ds
+ have length : fibers.length = (passes).length := by simp [fibers, levelFibers]
+ have layers : old :: fibers.map Prod.fst = tags := by
+ rw [show fibers.map Prod.fst = _ from levelFibers_tags passes ds]
+ rfl
+ let j : Fin (old :: fibers.map Prod.fst).length := ⟨i.val + 1, by simp [length]⟩
+ have count : (old :: fibers.map Prod.fst)[j].layer.count = passes[i].outputSites := by
+ simp [j, fibers, levelFibers_tags, levelLayer_count]
+ let id' : Fin (old :: fibers.map Prod.fst)[j].layer.count :=
+ ⟨id.val, by rw [count]; exact id.isLt⟩
+ have address' : (c.reg (dfs 7)).val = address B.recordLimit
+ (layerBase B.recordLimit base (old :: fibers.map Prod.fst) j.val) id'.val := by
+ simpa only [layers, j, id'] using node
+ have fit' :
+ layerBase B.recordLimit base (old :: fibers.map Prod.fst) (fibers.length + 1) < 2 ^ w := by
+ rwa [layers, length]
+ obtain ⟨out, runPrefix, atDone, located, frame⟩ :=
+ run M loc dfs saved reg done rows d j i.val rfl id' c hc address' fit'
+ change Prefix M m c out []
+ (trace M.publicData m (i.val + 1) (fibers.length - (i.val + 1))) at runPrefix
+ rw [length] at runPrefix
+ refine ⟨out, runPrefix, atDone, located, ?_, frame⟩
+ have levels : (m (H + 1)).val = (passes).length + 1 := d.levels.trans (congrArg (· + 1) length)
+ have total : (passes).length < 2 ^ w := by have := (m (H + 1)).isLt; omega
+ have ip : i.val < 2 ^ w := i.isLt.trans total
+ have count_eq := selected_pass_count B f hf T hT X z
+ have positive : 0 < T := by
+ by_contra! h
+ have zero : T * (S.steps + 1) = 0 := by rw [Nat.eq_zero_of_le_zero h, Nat.zero_mul]
+ exact Nat.not_lt_zero _ (i.isLt.trans_eq (count_eq.trans zero))
+ have periodFit : S.steps + 1 < 2 ^ w :=
+ (Nat.le_mul_of_pos_left _ positive).trans_lt (count_eq ▸ total)
+ rw [located.stage, selected_pass_ordinal B f hf T hT X z i]
+ change (((i.val % 2 ^ w) % ((S.steps + 1) % 2 ^ w)) % 2 ^ w) = _
+ rw [Nat.mod_eq_of_lt ip, Nat.mod_eq_of_lt periodFit,
+ Nat.mod_eq_of_lt ((Nat.mod_lt _ (Nat.succ_pos _)).trans periodFit)]
+
+end PairSimulation.VertexLevel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexLocatedBody.lean b/lean/OAI/Computability/VPVNP/PairVertexLocatedBody.lean
new file mode 100644
index 0000000000..6cc5e0b843
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexLocatedBody.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.PairVertexStagePrefix
+import OAI.Computability.VPVNP.PairVertexStageSegment
+
+/-!
+# Shared locator registers across stage-specific bodies
+
+Register banks chosen by a matrix table need not have the same numerical ordering as the
+child and hidden routines. Number the complement of the fourteen locator words separately.
+Every stage then uses the shared prefix required by the finite stage dispatcher.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open VertexImage
+
+/-- A vertex segment together with an embedding of the fourteen registers needed to locate its
+active level. -/
+structure LocatedBody where
+ /-- The executable segment of a body that shares a level locator. -/
+ code : Segment
+ /-- Identify the body's fourteen level-locator registers within its private register space. -/
+ locator : Fin 14 ↪ Fin code.privateRegs
+
+namespace LocatedBody
+
+variable (B : LocatedBody)
+
+/-- The body's private registers outside the image of its shared locator embedding. -/
+abbrev Tail := {i : Fin B.code.privateRegs // i ∉ Set.range B.locator}
+/-- Number of additional private registers required beyond the shared locator bank. -/
+noncomputable abbrev tailCount := Nat.card B.Tail
+
+/-- Number the other registers separately and retain the order of the locator. -/
+noncomputable def order : Fin (14 + B.tailCount) ≃ Fin B.code.privateRegs := by
+ classical
+ let other : B.Tail ≃ Fin B.tailCount := Fintype.equivFinOfCardEq Nat.card_eq_fintype_card.symm
+ exact finSumFinEquiv.symm.trans
+ (((Equiv.ofInjective B.locator B.locator.injective).sumCongr other.symm).trans
+ (Equiv.Set.sumCompl (Set.range B.locator)))
+
+theorem order_locator (i : Fin 14) : B.order (i.castAdd B.tailCount) = B.locator i := by
+ classical
+ simp [order]
+ rfl
+
+/-- Only the numerical operand placement changes. The PC and native opcode are identical. -/
+noncomputable def normalized : Segment where
+ count := B.code.count
+ privateRegs := 14 + B.tailCount
+ entry := B.code.entry
+ row loc dfs saved reg done := B.code.row loc dfs saved (B.order.symm.toEmbedding.trans reg) done
+
+/-- Append fresh child registers after every register of the remaining routine. -/
+def withChildren (a : ℕ) : LocatedBody where
+ code := VertexStagePrefix.withChildren a B.code B.locator
+ locator := B.locator.trans
+ (Fin.castAddEmb (NodeArguments.ChildCode.RegisterBank.segment a).privateRegs)
+
+variable {N : ℕ}
+
+/-- One finite image starts with the real level scan and selects the stage within the block. -/
+noncomputable def family (bodies : Fin N → LocatedBody) : Segment :=
+ VertexStageDispatch.locatedFamily (fun i => (bodies i).normalized) (fun i => (bodies i).tailCount)
+ (fun _ => rfl)
+
+end LocatedBody
+
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexLocatedBodyLinks.lean b/lean/OAI/Computability/VPVNP/PairVertexLocatedBodyLinks.lean
new file mode 100644
index 0000000000..a0e79b5e98
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexLocatedBodyLinks.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.PairVertexLocatedBody
+
+/-!
+# The actual PC and register placements of a selected nonleaf stage
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocatedBody
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage VertexStageDispatch
+
+variable {N p r w : ℕ} (B : Fin N → LocatedBody)
+
+/-- Map the instructions of one scheduled body into the normalized family dispatch layout. -/
+noncomputable abbrev stagePC (pc : Fin (family B).count → Fin p) (i : Fin N) :=
+ bodyPC (fun i => (B i).normalized) (familyPC (fun i => (B i).normalized) pc) i
+
+/-- Embed a selected body's original register bank using its locator-first ordering and its own
+tail register block. -/
+noncomputable abbrev stageBank (reg : Fin (family B).privateRegs ↪ Fin r) (i : Fin N) :
+ Fin (B i).code.privateRegs ↪ Fin r :=
+ (B i).order.symm.toEmbedding.trans ((bodyBank (fun i => (B i).normalized)
+ (fun i => (B i).tailCount) (fun _ => rfl) i).trans reg)
+
+/-- Place the single locator bank shared by all normalized stage bodies in the enclosing
+machine. -/
+noncomputable abbrev commonLocator (reg : Fin (family B).privateRegs ↪ Fin r) :=
+ (locatorBank (fun i => (B i).tailCount)).trans reg
+
+/-- Each stage, in its own original register order, reads the same locator registers
+written by the header scan. No register copies or extra labels are required. -/
+theorem shared_locator (reg : Fin (family B).privateRegs ↪ Fin r) (i : Fin N) (j : Fin 14) :
+ stageBank B reg i ((B i).locator j) = commonLocator B reg j := by
+ change reg (bodyBank (fun l => (B l).normalized) (fun l => (B l).tailCount) (fun _ => rfl) i
+ ((B i).order.symm ((B i).locator j))) = reg (locatorBank (fun l => (B l).tailCount) j)
+ rw [← order_locator (B i) j, Equiv.symm_apply_apply]
+ apply congrArg reg
+ exact bodyBank_locator (fun i => (B i).normalized) (fun i => (B i).tailCount) (fun _ => rfl) i j
+
+/-- The source stage sees its original numerical code and the relocated source registers. -/
+theorem stage_rows (M : Machine w p r 11) (pc : Fin (family B).count → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r) (reg : Fin (family B).privateRegs ↪ Fin r)
+ (done : Fin p) (rows : ∀ a, M.code (pc a) = ((family B).row pc dfs saved reg done a).resize w)
+ (i : Fin N) (j : Fin (B i).code.count) :
+ M.code (stagePC B pc i j) =
+ ((B i).code.row (stagePC B pc i) dfs saved (stageBank B reg i) done j).resize w :=
+ (locatedFamily_link (fun i => (B i).normalized) dfs saved done M (fun i => (B i).tailCount)
+ (fun _ => rfl) pc reg rows).2.2 i j
+
+end PairSimulation.LocatedBody
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexOccurrence.lean b/lean/OAI/Computability/VPVNP/PairVertexOccurrence.lean
new file mode 100644
index 0000000000..940edf3023
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexOccurrence.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.PairVertexSiteSegments
+import OAI.Computability.VPVNP.PairTreeDecodeDomain
+
+/-! # The accepting private tapes of an actual assembled final-site burst -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM DFS LocalHistory NetworkKernel NodeArguments TreeDecode
+open scoped Fin.CommRing
+
+variable {geometry rootFields leaf shrink refresh : Segment} {p r W endAddr : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r)
+ (M : Machine W p r 11)
+ {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R} {N Y : Network}
+
+/-- A genuine singleton-root burst returns on precisely one encoding of
+a selected site occurrence. Malformed child tapes and truncated or extra
+bits are covered by the two directions of the equivalence. The hypotheses
+on computation and storage concern the individual row handlers only. -/
+theorem returns_iff_occurrence (linked : Contains A M) (G offset hist : Word W) (m : Memory W)
+ (domain : Word W → Scratch W endAddr → Prop) (valid : List Packet → Scratch W endAddr → Prop)
+ (resident : ∀ node s, domain node s → ResidentGeometry s G offset hist)
+ (head : HeadDomain valid domain)
+ (handlers : NodeDispatch.Role → HookParser W endAddr)
+ (exactRole : ∀ role, (handlers role).ExactOn
+ (fun node saved => domain node saved ∧ NodeDispatch.role (m (offset+node).val) = role)
+ M (A.entry (rolePart role)) (A.dfsPC 3) A.dfs m)
+ (c : TermChain R N Y) (readers : ChainParsers f c) (ptr : RowPointers c)
+ (layers : PacketLayers c) (P : SiteParsers f N) (leaves : N.Site → ℕ × ℕ) (input : Packets N)
+ (leafAddress : ∀ v z, (input v z).node = (leaves v).1) (addresses : PointerLayers c ptr layers)
+ (leafs : Subtrees (dispatcher handlers m offset) valid P (fun v => leafTree (leaves v)) input)
+ (steps : StepLayers (dispatcher handlers m offset) valid c readers ptr layers input)
+ (v : Y.Site) (z : Y.Half v)
+ (cfg : Config W p r) (here : cfg.pc = A.dfsPC 0) (top : ℕ) (root : Word W)
+ (stack : Represents cfg.privateMem top [root]) (length : top+1 = endAddr)
+ (sp : cfg.reg (A.dfs 5) = (top : Word W)) (endReg : cfg.reg (A.dfs 6) = (endAddr : Word W))
+ (one : cfg.reg (A.dfs 3) = 1) (events : List (Event W))
+ (visits : Visits m endAddr [root]
+ (((chainTrees c readers ptr (fun u => leafTree (leaves u))) v).preorder.map (fun n : ℕ => (n : Word W))) events)
+ (ready : valid [finalPackets c layers input v z] (scratch endAddr cfg.privateMem)) (bits : List Bool) :
+ Returns M cfg m bits ↔ ∃! x, bits = ((finalParsers c readers P).read v z).encode x := by
+ let H := dispatcher handlers m offset
+ let init := fun u => leafTree (leaves u)
+ have along := chain_along H valid domain c readers ptr layers P init input leafs
+ (leaf_along H valid domain leaves input leafAddress head) steps addresses head
+ have decode := chain_exact H valid c readers ptr layers P init input leafs steps
+ rw [site_returns linked G offset hist m domain resident handlers exactRole (finish_terminal A M linked)
+ visits cfg here top stack length sp endReg one bits (along v z [] _ bits (by simpa using ready))]
+ simpa only [List.append_nil] using (decode v z).unique H valid ((finalParsers c readers P).read v z)
+ (pending := []) (by simpa using ready) bits []
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexOrdinalLiveCosts.lean b/lean/OAI/Computability/VPVNP/PairVertexOrdinalLiveCosts.lean
new file mode 100644
index 0000000000..635a8cffc1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexOrdinalLiveCosts.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.PairVertexOrdinalReportCosts
+import OAI.Computability.VPVNP.PairNativeCacheClock
+import OAI.Computability.VPVNP.CursorBranchBudget
+
+/-! # A uniform threshold for selected vertex calls in the live circuit -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open Compression CursorNetwork CursorBounds CursorRouting Filter LiveProgram NativeOperands
+open BurstRAM PrivateRAM NetworkKernel
+
+/-- All schedule, cache and history estimates needed by a selected ordinal
+hold before fixing the field realization, compressed branch or vertex. -/
+theorem eventually_ordinal_geometry {k : Type*} [Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (c : Constants) (a b scale degree : ℕ)
+ (hb : max S.laneBits 5 ≤ scale) :
+ ∀ᶠ n : ℕ in atTop, 2048 ≤ n ∧ S.baseDegree ≤ n ∧ Fintype.card B.Entry ≤ n ∧
+ (∀ H t, t ≤ work (NativeCache.args c) a b (AssemblerPublic.geometry scale n H) + 76 →
+ t + degree + 187 ≤ 44 + n ^ 3) ∧
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits scale n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits scale n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ ∀ z : E.Choices, let Y := E.finalState z
+ let chain := E.termChain (B.records f hf T hT X) z
+ Y.maxWireWidth ≤ n ∧ ∀ v, chain.occurrences (fun _ => 1) v ≤ n := by
+ filter_upwards [eventually_pairBranchBounds B u scale hb, NativeCache.eventually_work_le c a b
+ scale,
+ eventually_ge_atTop 2048, eventually_ge_atTop S.baseDegree, eventually_ge_atTop (Fintype.card
+ B.Entry),
+ eventually_ge_atTop degree] with n branch cache hn hd hl hg
+ refine ⟨hn,hd,hl,?_,?_⟩
+ · intro H t ht
+ have small := ht.trans (cache H)
+ have wide : 3 * n ≤ n ^ 3 := calc
+ 3 * n ≤ n * n := Nat.mul_le_mul_right _ (by omega)
+ _ ≤ n ^ 3 := by rw [←pow_two]; exact Nat.pow_le_pow_right (by omega) (by decide)
+ omega
+ · intro base lanes labels hD hT A _ f hf X T E z Y chain
+ have actual := branch.2.2 labels hD hT A f hf z
+ have hpow {x : ℝ} (hx : x ≤ 1) : (n : ℝ) ^ x ≤ n := by
+ simpa using Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast (show 1 ≤ n by omega)) hx
+ exact ⟨Nat.cast_le.mp ((Nat.cast_le.mpr actual.2.2.2.2.1).trans
+ (actual.2.2.2.2.2.1.trans (hpow (by norm_num)))),
+ fun v => Nat.cast_le.mp ((actual.2.2.1 v).trans (hpow (by norm_num)))⟩
+
+/-- The bootstrap, fixed-frame header reads and gather of the physical
+selected root. Its packed payload has precisely its incident wire width. -/
+theorem ordinal_prefix_bounds {w ex lanes : ℕ} (Y : State ex lanes) (v : Y.network.Site)
+ (half : Y.network.Half v) (es : List (Event w)) (t degree n : ℕ)
+ (probes : countProbes es = 15 + (5 * 2 ^ ex + (NodeArguments.packed Y v half).length))
+ (ticks : es.length = t + degree + 187 + (15 + 21 * (2 ^ ex) + 5 * (NodeArguments.packed Y v
+ half).length))
+ (cache : t + degree + 187 ≤ 44 + n ^ 3) :
+ countProbes es ≤ 9 + 6 + 5 * 2 ^ ex + incidentBits Y v ∧
+ es.length ≤ 44 + n ^ 3 + (15 + 21 * (2 ^ ex) + 5 * incidentBits Y v) := by
+ have size : (NodeArguments.packed Y v half).length = incidentBits Y v :=
+ NodeArguments.packed_length Y v half
+ rw [size] at probes ticks
+ omega
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexOrdinalPhase.lean b/lean/OAI/Computability/VPVNP/PairVertexOrdinalPhase.lean
new file mode 100644
index 0000000000..a81fb005b6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexOrdinalPhase.lean
@@ -0,0 +1,202 @@
+import OAI.Computability.VPVNP.PairVertexAscendingPaths
+import OAI.Computability.VPVNP.PairSimulationWorkerPhaseEquiv
+import OAI.Computability.VPVNP.PairSimulationTerminalProgram
+import OAI.Computability.VPVNP.PairTerminalVertexFrameLinked
+
+/-!
+# The completed physical vertex phase
+
+The terminal controller's two writes preserve the vertex frame. Recover each
+source call from its reduced physical clock and advance its natural ordinal.
+This proves the read footprint on arbitrary completed physical traces.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM CompressorRecords SourceTransport TerminalLink
+open LiveProgram (PairTable)
+open scoped Fin.CommRing
+
+variable {w n g cap base grammar : ℕ} {pub : Fin 11 → Word w} {D : IndexedSites n g}
+ {workers : Stage → PairTable} {stage : Stage} {Frame : ℕ → Memory w → Prop}
+
+private theorem classifyCall
+ (H : ActiveCalls D (source workers stage pub) cap base grammar Frame)
+ (close : Closes (source workers stage pub) cap n pub Frame) (room : (TerminalLink.header pub).val+32 ≤ 2^w)
+ (checks : ∀ i m, Frame i.val m → ∀ (x : D.Choice i) r,
+ execute (source workers stage pub) cap ((source workers stage pub).start (i.val : Word w)) m (D.encode i x) =
+ some r → Reads (workerCell (TerminalLink.header pub)) r.events)
+ {j : ℕ} (le : j ≤ n) {m : Memory w} (ready : Frame j m)
+ {bs : List Bool} {raw : Report w}
+ (run : execute (source workers stage pub) cap ((source workers stage pub).start (j : Word w)) m bs = some raw) :
+ Reads (workerCell (TerminalLink.header pub)) raw.events ∧
+ (∀ st, raw.result = some st → st = ((j+1 : ℕ) : Word w) ∧ j+1 ≤ n ∧ Frame (j+1) (after m raw.events)) := by
+ rcases lt_or_eq_of_le le with lt | rfl
+ · let i : Fin n := ⟨j,lt⟩
+ obtain ⟨x,rfl⟩ := H.recover i m ready bs raw run
+ obtain ⟨rep,call,next,mem⟩ := H.emit i m ready x
+ obtain rfl := Option.some.inj (run.symm.trans call)
+ refine ⟨checks i m ready x raw run, fun st returned => ?_⟩
+ exact ⟨Option.some.inj (returned.symm.trans next),lt,mem ▸ H.preserve i m ready x⟩
+ · rw [close m ready] at run
+ split at run
+ · obtain rfl := Option.some.inj run
+ exact ⟨(closingReport_checks pub m room).1, fun _ h => nomatch h⟩
+ · contradiction
+
+/-- Classify all successful raw calls in a completed physical phase, with the
+two controller writes applied before classifying the next call. -/
+theorem ordinal_phase_reads
+ (H : ActiveCalls D (source workers stage pub) cap base grammar Frame)
+ (close : Closes (source workers stage pub) cap n pub Frame) (room : (TerminalLink.header pub).val+32 ≤ 2^w)
+ (checks : ∀ i m, Frame i.val m → ∀ (x : D.Choice i) r,
+ execute (source workers stage pub) cap ((source workers stage pub).start (i.val : Word w)) m (D.encode i x) =
+ some r → Reads (workerCell (TerminalLink.header pub)) r.events)
+ (post : ∀ j e m raw, Frame j (after m raw.events) →
+ Frame j (after m (TerminalLink.report (TerminalLink.header pub) e raw).events))
+ {e m bs ls final} (ph : Phase workers pub cap e m bs ls final)
+ (hs : e.stage = stage) {j : ℕ} (state : e.state = (j : Word w)) (le : j ≤ n) (hm : Frame j m) :
+ Reads (workerCell (TerminalLink.header pub)) (eventLog (ls.map Prod.snd)) := by
+ have head {e : Entry w} {j : ℕ} {m b r} (hs : e.stage = stage) (state : e.state = (j : Word w))
+ (le : j ≤ n) (hm : Frame j m)
+ (called : execute (source workers e.stage pub) (rawFuel pub cap e)
+ ((source workers e.stage pub).start e.state) m b = some r) :
+ Reads (workerCell (TerminalLink.header pub)) r.events ∧
+ (∀ st, r.result = some st → st = ((j+1 : ℕ) : Word w) ∧ j+1 ≤ n ∧ Frame (j+1) (after m r.events)) := by
+ have full := execute_extend called (cap - rawFuel pub cap e)
+ have hle : rawFuel pub cap e ≤ cap := Nat.sub_le ..
+ rw [Nat.add_sub_of_le hle,hs,state] at full
+ exact classifyCall H close room checks le hm full
+ induction ph generalizing j with
+ | last call _ _ =>
+ simpa only [List.map_cons, List.map_nil, eventLog, List.flatMap_cons, List.flatMap_nil, List.append_nil]
+ using (head hs state le hm call).1
+ | @more e m b bs raw x ls final call _ returned _ ih =>
+ obtain ⟨read,step⟩ := head hs state le hm call
+ obtain ⟨rfl,next,frame⟩ := step x returned
+ intro a v ha
+ change Event.read a v ∈ raw.events ++ eventLog (ls.map Prod.snd) at ha
+ rcases List.mem_append.mp ha with hh | ht
+ · exact read a v hh
+ · exact ih hs rfl next (post _ e m raw frame) a v ht
+
+variable {geometry rootFields leaf shrink refresh : Segment}
+local notation "segments₀" => segments geometry rootFields leaf shrink refresh
+
+/-- The same stored final ordinal closes the vertex phase before and after
+any number of physical histogram updates and terminal dispatches. -/
+theorem linked_finalSites (reference : Memory w) (room : (TerminalLink.header pub).val + 32 ≤ 2^w)
+ (below : base + grammar + g ≤ (TerminalLink.header pub).val)
+ (sites : reference (TerminalLink.header pub + 7).val = (n : Word w))
+ (m : Memory w) (frame : VertexFrame.Linked (TerminalLink.header pub) base grammar g reference n m) :
+ m (TerminalSiteStart.headerWord pub + 7).val = (n : Word w) := by
+ rw [headerWord_eq_header]
+ exact (frame.header room below 7 (by decide) (by decide)).trans sites
+
+/-- Construct the vertex worker's relocation proof from the per-ordinal source
+facts, using the actual physical frame at every call on the reverse path. -/
+theorem ordinalWorkerFrame
+ (F : DescriptorSpace.Shape) (limit : ℕ) (ref src phy : Memory w)
+ (H : ActiveCalls D (((template segments₀).instantiate w pub).program) cap base grammar
+ (VertexFrame.Linked (TerminalLink.header pub) base grammar g ref))
+ (close : Closes (((template segments₀).instantiate w pub).program) cap n pub
+ (VertexFrame.Linked (TerminalLink.header pub) base grammar g ref))
+ (room : (TerminalLink.header pub).val + 32 ≤ 2^w) (clock : 45 ≤ cap)
+ (checks : ∀ i m, VertexFrame.Linked (TerminalLink.header pub) base grammar g ref i.val m →
+ ∀ (x : D.Choice i) r,
+ execute (((template segments₀).instantiate w pub).program) cap
+ (((template segments₀).instantiate w pub).program.start (i.val : Word w)) m (D.encode i x) = some r →
+ Reads (workerCell (TerminalLink.header pub)) r.events ∧ r.events.length + 1 ≤ cap-30)
+ (hs : VertexFrame.Linked (TerminalLink.header pub) base grammar g ref 0 src)
+ (hp : VertexFrame.Linked (TerminalLink.header pub) base grammar g ref 0 phy)
+ (agree : Agree (workerCell (TerminalLink.header pub)) src phy) :
+ WorkerFrame (TerminalProgram.workers F limit segments₀) pub cap (.resume Stage.vertices 0) src phy := by
+ have safe (p : ActualPaths (((template segments₀).instantiate w pub).program) cap 0 src (fun _ => True)) :=
+ ascending_report_checks H close room (by omega : 15 ≤ cap-30) checks src hs
+ p.property.choose_spec.1 p.property.choose_spec.2.1
+ refine ⟨by omega,agree,fun p => (safe p).1, fun p r hr => (safe p).2 r hr, ?_⟩
+ intro q
+ apply ordinal_phase_reads (stage := Stage.vertices) (D := D) H close room
+ (fun i m h x r run => (checks i m h x r run).1)
+ (fun _ e _ _ h => VertexFrame.Linked.after_report e h) q.property rfl (j := 0)
+ (by simp [Entry.state]) (Nat.zero_le _) hp
+
+section PhysicalSites
+
+open NetworkKernel LocalHistory
+
+variable {R : Type*} [CommRing R] {Label : Type} [Fintype Label] {κ : Label → R}
+ {N : Network} (parsers : SiteParsers κ N) (order : Fin n ≃ N.Site)
+ (labels : Fin g ≃ Label) (half : ∀ v, N.Half v)
+ (F : DescriptorSpace.Shape) (limit : ℕ) (src phy : Memory w)
+ (native : ActiveCalls (siteOrdinals parsers order labels half)
+ (((template (segments geometry rootFields leaf shrink refresh)).instantiate w pub).program)
+ cap base grammar Frame)
+ (clock : 15 ≤ cap) (ready : Frame 0 src)
+ (stored : ∀ m, Frame n m → m (TerminalSiteStart.headerWord pub + 7).val = (n : Word w))
+ (transport : WorkerFrame (TerminalProgram.workers F limit (segments geometry rootFields leaf shrink refresh))
+ pub cap (.resume Stage.vertices 0) src phy)
+
+/-- Choose one final-site monomial at every vertex and obtain exactly the
+completed physical vertex block on the fixed shared assignment. -/
+noncomputable def sitePhysical (native : ActiveCalls (siteOrdinals parsers order labels half)
+ (((template (segments geometry rootFields leaf shrink refresh)).instantiate w pub).program)
+ cap base grammar Frame) (clock : 15 ≤ cap) (ready : Frame 0 src)
+ (stored : ∀ m, Frame n m → m (TerminalSiteStart.headerWord pub + 7).val = (n : Word w))
+ (transport : WorkerFrame (TerminalProgram.workers F limit segments₀) pub cap (.resume Stage.vertices 0) src phy) :
+ (∀ v, (parsers.witnesses v (half v)).Choice) ≃ CompletedPhase (TerminalProgram.workers F limit segments₀)
+ pub cap (.resume Stage.vertices 0) phy :=
+ (sitePathsEquiv parsers order labels half native clock stored src ready).trans transport.sourceBlockEquiv
+
+theorem physicalSite_calls (x : ∀ v, (parsers.witnesses v (half v)).Choice) :
+ (sitePhysical parsers order labels half F limit src phy native clock ready stored transport x).val.choices =
+ (List.ofFn fun j => (parsers.read (order j) (half (order j))).encode (x (order j))) ++ [[]] := rfl
+
+/-- Exact terminal memory agreement on all worker addresses. In particular
+each counter cell contains its old value plus the sum of the selected powers. -/
+theorem physicalSite_memory (x : ∀ v, (parsers.witnesses v (half v)).Choice) :
+ Agree (workerCell (TerminalLink.header pub)) ((siteOrdinals parsers order labels half).finalMemory
+ base grammar src (fun j => x (order j)))
+ (sitePhysical parsers order labels half F limit src phy native clock ready stored transport x).val.memory := by
+ let p := sitePathsEquiv parsers order labels half native clock stored src ready x
+ have same : Agree (workerCell (TerminalLink.header pub)) (after src (eventLog p.property.choose))
+ (transport.sourceBlockEquiv p).val.memory := transport.sourceBlock_memory p
+ obtain ⟨rs, _, run, _, mem⟩ := ascending_reports native (template_closes clock stored) src ready (fun j => x (order j))
+ have hr := Option.some.inj (p.property.choose_spec.1.symm.trans run)
+ rw [hr,mem] at same
+ exact same
+
+theorem physicalSite_histogram (x : ∀ v, (parsers.witnesses v (half v)).Choice) (l : Fin g)
+ (cell : workerCell (TerminalLink.header pub) (base + grammar + l)) :
+ (sitePhysical parsers order labels half F limit src phy native clock ready stored transport x).val.memory
+ (base + grammar + l) = src (base + grammar + l) +
+ ((∑ v, (parsers.witnesses v (half v)).exponents (x v) (labels l) : ℕ) : Word w) := by
+ rw [← physicalSite_memory parsers order labels half F limit src phy native clock ready stored transport x _ cell,
+ IndexedSites.finalMemory_at (siteOrdinals parsers order labels half) base grammar src (fun j => x (order j)) l]
+ exact congrArg (fun k : ℕ => src (base + grammar + l) + (k : Word w))
+ (order.sum_comp fun v => (parsers.witnesses v (half v)).exponents (x v) (labels l))
+
+/-- When the accumulated count fits the word, reading its natural value gives
+the integer sum of the occurrence exponents. -/
+theorem physicalSite_histogram_val (x : ∀ v, (parsers.witnesses v (half v)).Choice) (l : Fin g)
+ (cell : workerCell (TerminalLink.header pub) (base + grammar + l))
+ (fit : (src (base + grammar + l)).val +
+ ∑ v, (parsers.witnesses v (half v)).exponents (x v) (labels l) < 2 ^ w) :
+ ((sitePhysical parsers order labels half F limit src phy native clock ready stored transport x).val.memory
+ (base + grammar + l)).val = (src (base + grammar + l)).val +
+ ∑ v, (parsers.witnesses v (half v)).exponents (x v) (labels l) := by
+ have part : (∑ v, (parsers.witnesses v (half v)).exponents (x v) (labels l)) < 2 ^ w := by omega
+ rw [physicalSite_histogram parsers order labels half F limit src phy native clock ready stored transport x l cell,
+ Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt part, Nat.mod_eq_of_lt fit]
+
+end PhysicalSites
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexOrdinalReportCosts.lean b/lean/OAI/Computability/VPVNP/PairVertexOrdinalReportCosts.lean
new file mode 100644
index 0000000000..bbacde4cc7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexOrdinalReportCosts.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.PairVertexSelectedPaths
+import OAI.Computability.VPVNP.PairSimulationVertexReportBudget
+
+/-! # Time and probes of the actual selected vertex worker -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM Compression DFS LocalHistory NetworkKernel NodeArguments TreeDecode
+ TraversalRows
+open CompressorRecords SourceTransport TerminalLink
+open scoped Fin.CommRing
+
+variable {k R : Type*} [Field k] [CommRing R] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → R) (hκ : B.IsSolution κ) {lanes : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute κ hκ T hT X).Choices) (rowBase : ℕ)
+ {geometry rootFields leaf shrink refresh : Segment} {p r w g : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r) (M : Machine w p r 11)
+ (base grammar : ℕ) (order : Fin g ≃ B.Entry) (P : SiteParsers κ X.network)
+
+local notation "exec₀" => B.execute κ hκ T hT X
+local notation "data₀" => B.records κ hκ T hT X
+local notation "chain₀" => StateExecution.termChain (exec₀) (data₀) z
+local notation "readers₀" => selectedParsers B κ hκ T hT X z
+local notation "trees₀" => selectedTrees B κ hκ T hT X z rowBase
+local notation "Y" => StateExecution.finalState (exec₀) z
+local notation "ord₀" => siteOrder (Y)
+local notation "final₀" => finalParsers (chain₀) (readers₀) P
+local notation "head₀" => TerminalLink.header (Machine.publicData M)
+local notation "allow₀" => workerCell (head₀)
+
+variable (half : ∀ u, ((B.execute κ hκ T hT X).finalState z).network.Half u)
+
+local notation "selected₀" => siteOrdinals (final₀) (Order.entries (ord₀)) order half
+
+variable {cap : ℕ} {m : Memory w} {i : Fin (siteOrder ((B.execute κ hκ T hT X).finalState
+ z)).length}
+
+local notation "rows₀" => OrdinalRows B κ hκ T hT X z rowBase A M base grammar order P half cap m i
+
+open CursorNetwork
+
+private theorem sum_jobs_le {J : Type*} (charge : J → ℕ) (js : List J) (rate : ℕ)
+ (each : ∀ j ∈ js, charge j ≤ rate) : (js.map charge).sum ≤ js.length * rate := by
+ induction js with
+ | nil => simp
+ | cons j js ih =>
+ simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.succ_mul]
+ exact (Nat.add_le_add (each j List.mem_cons_self) (ih fun t ht => each t (List.mem_cons_of_mem
+ _ ht))).trans_eq
+ (Nat.add_comm _ _)
+
+/-- Charge a returning native ordinal against its own incident wires and DFS
+occurrences. The local cost predicate comes from the installed role handlers.
+The directory coefficient, schedule degree and number of parameter labels
+are independent of the input length and of the choice at the site. -/
+theorem OrdinalRows.ordinalChecks (row : rows₀) (linked : Contains A M) (n power setup scan : ℕ)
+ (hn : 2048 ≤ n) (degree : S.baseDegree ≤ n) (labels : Fintype.card B.Entry ≤ n)
+ (width : (Y).maxWireWidth ≤ n) (visits : (chain₀).occurrences (fun _ => 1) ((ord₀).entries i)
+ ≤ n)
+ (preProbes : countProbes row.pre ≤ 9 + setup + 5 * S.baseDegree + incidentBits (Y)
+ ((ord₀).entries i))
+ (preTicks : row.pre.length ≤ 44 + n ^ 3 + (15 + 21 * S.baseDegree + 5 * incidentBits (Y)
+ ((ord₀).entries i)))
+ (jobProbes : ∀ j, row.cost j → countProbes j.trace ≤ scan * (n.log2 + 1) ^ power)
+ (jobTicks : row.maxTicks ≤ n ^ 43) (x : (selected₀).Choice i) (rep : Report w)
+ (returned : execute M.program cap (M.program.start (i.val : Word w)) m ((selected₀).encode i
+ x) = some rep) :
+ 1 + rep.probes ≤ siteAccesses (Y) (chain₀)
+ (VertexReportBudget.coefficient S.baseDegree (Fintype.card B.Entry) setup scan 0 0)
+ power n ((ord₀).entries i) ∧ rep.events.length + 107 ≤ n ^ 45 := by
+ let v := (ord₀).entries i
+ let tree := (trees₀) v
+ let nodes := tree.preorder.map (fun a : ℕ => (a : Word w))
+ let o := (chain₀).occurrences (fun _ => 1) v
+ obtain ⟨control,run,_,hnodes,ctrlTicks,ctrlProbes⟩ :=
+ selected_control B κ hκ T hT X z rowBase m (head₀) row.endAddr
+ row.rows row.space row.hfit row.capacity v
+ obtain ⟨out,call,_,_,_,_,_,jobs,size,valid,probes,ticks⟩ :=
+ active_occurrence_costs B κ hκ T hT X z rowBase A M m row.G row.offset base grammar row.src
+ order P
+ row.valid row.domain row.handlers row.cost linked row.selected v (half v)
+ (M.program.start (i.val : Word w)) row.cfg row.pre row.pref row.noChoice row.noWrite
+ row.prefixReads
+ row.persistent row.atRoot row.top row.stack row.endTop row.sp row.endReg row.one row.zero
+ row.prepared
+ row.rows row.space row.hfit row.capacity row.above row.hsrc row.hdst row.cells row.hbase
+ row.hgrammar
+ row.hg row.maxTicks cap row.small row.room x
+ have same : out = rep := Option.some.inj (call.symm.trans returned)
+ subst out
+ have hlabels : g = Fintype.card B.Entry := (Fintype.card_fin g).symm.trans (Fintype.card_congr
+ order)
+ have length : nodes.length ≤ o := by simpa only [nodes, List.length_map] using hnodes
+ have nJobs : jobs.length ≤ o := size.trans_le hnodes
+ have incident : incidentBits (Y) v ≤ 2 * S.baseDegree * n :=
+ (incidentBits_le (Y) v).trans (Nat.mul_le_mul_left _ width)
+ let traffic := (jobs.map (fun j => countProbes j.trace)).sum
+ let work := (jobs.map (fun j => j.trace.length)).sum
+ have trafficBound : traffic ≤ scan * (o * (n.log2 + 1) ^ power) := calc
+ _ ≤ jobs.length * (scan * (n.log2 + 1) ^ power) :=
+ sum_jobs_le _ jobs _ (fun j hj => jobProbes j (valid j hj))
+ _ ≤ o * (scan * (n.log2 + 1) ^ power) := Nat.mul_le_mul_right _ nJobs
+ _ = _ := by ring
+ have workBound : work ≤ n ^ 44 := calc
+ _ ≤ jobs.length * row.maxTicks :=
+ sum_jobs_le _ jobs _ (fun j hj => row.small j (valid j hj))
+ _ ≤ n * n ^ 43 := Nat.mul_le_mul (nJobs.trans visits) jobTicks
+ _ = _ := (pow_succ' n 43).symm
+ change countProbes rep.events + 1 = countProbes row.pre + 3 * jobs.length +
+ traffic + 2 * g at probes
+ change rep.events.length + 4 = row.pre.length + 15 * jobs.length + work + 7 * g + 14 at ticks
+ rw [← size] at ctrlTicks ctrlProbes
+ constructor
+ · rw [← hlabels]
+ refine VertexReportBudget.probes_le (Y) (chain₀) v n power S.baseDegree g setup scan 0 0 m
+ (tree.address : Word w) row.endAddr nodes control run length setup traffic 0 0 rep le_rfl
+ (by simp) (by simp) ?_ ?_
+ · change traffic ≤ 2 * nodes.length + 0 + 0 + scan * (o * (n.log2 + 1) ^ power)
+ exact trafficBound.trans (Nat.le_add_left _ _)
+ · change countProbes rep.events ≤ _
+ change countProbes row.pre ≤ 9 + setup + 5 * S.baseDegree + incidentBits (Y) v at preProbes
+ omega
+ · refine VertexReportBudget.steps_le_45 (Y) (chain₀) v (geometry := n ^ 3) (hook := work)
+ hn degree (hlabels ▸ labels) le_rfl incident visits m (tree.address : Word w) row.endAddr
+ nodes control
+ run length workBound rep ?_
+ change row.pre.length ≤ 44 + n ^ 3 +
+ (15 + 21 * S.baseDegree + 5 * incidentBits (Y) v) at preTicks
+ omega
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexOrdinalRoleCost.lean b/lean/OAI/Computability/VPVNP/PairVertexOrdinalRoleCost.lean
new file mode 100644
index 0000000000..7b42ddcc5e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexOrdinalRoleCost.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.PairVertexSelectedReport
+import OAI.Computability.VPVNP.CompressorSourceTransport
+
+/-! # A common cost bound for the installed terminal roles -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM DFS LocalHistory NetworkKernel NodeArguments TreeDecode
+
+variable {geometry rootFields leaf shrink refresh : Segment} {p regs w endAddr : ℕ}
+ {A : Placement (segments geometry rootFields leaf shrink refresh) p regs} {M : Machine w p regs
+ 11}
+ {m : Memory w} {allow : ℕ → Prop} {cost bound : VisitPath w endAddr → Prop}
+
+/-- Transfer a local role estimate without losing the actual machine link,
+external memory update or read footprint. -/
+theorem JobGuard.withCost (le : ∀ j, cost j → bound j) {j : VisitPath w endAddr}
+ (guard : JobGuard A M m allow cost j) : JobGuard A M m allow bound j :=
+ ⟨guard.1,guard.2.1,guard.2.2.1,le j guard.2.2.2⟩
+
+variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {κ : L → R} {N : Network}
+ {valid : List Packet → Scratch w endAddr → Prop} {hist : Scratch w endAddr → L → ℕ}
+
+/-- The same native leaf jobs and semantic exponent increments satisfy
+any common upper bound on their observed costs. -/
+theorem emits_withCost {P : SiteParsers κ N} {input : Packets N} {jobs : JobsFor P}
+ (native : Emits valid hist (JobGuard A M m allow cost) P input jobs)
+ (le : ∀ j, cost j → bound j) :
+ Emits valid hist (JobGuard A M m allow bound) P input jobs := by
+ intro v z x pending s ready
+ obtain ⟨js,run⟩ := native v z x pending s ready
+ exact ⟨js,run.realized,run.ready,fun j hj => (run.framed j hj).withCost le,run.remaining⟩
+
+/-- Use a shared role allowance on each selected shrink or refresh pass. -/
+theorem emitsNode_withCost {t : Term R N} {r : TermParsers κ t} {ptr : t.output.Site → ℕ × ℕ}
+ {before : Packets N} {next : Packets t.output}
+ (native : EmitsNode valid hist (JobGuard A M m allow cost) r ptr before next)
+ (le : ∀ j, cost j → bound j) :
+ EmitsNode valid hist (JobGuard A M m allow bound) r ptr before next := by
+ intro v z a k pending s ready
+ obtain ⟨j,job,enabled,guard,later⟩ := native v z a k pending s ready
+ exact ⟨j,job,enabled,guard.withCost le,later⟩
+
+/-- Bound used on an individual role report in the selected vertex call. -/
+def ordinalJobCost (n power scan : ℕ) (j : VisitPath w endAddr) : Prop :=
+ countProbes j.trace ≤ scan * (n.log2 + 1) ^ power ∧ j.trace.length ≤ n ^ 43
+
+/-- In the installed cursor leaf, the dispatch and optional virtual-header
+read together make at most two probes. The private role already includes
+its reload and auxiliary computation. -/
+theorem leaf_ordinal_cost {n power scan : ℕ} (hn : 1 ≤ n) (hs : 2 ≤ scan)
+ {j : VisitPath w endAddr}
+ (localCost : countProbes j.trace ≤ 2 ∧ j.trace.length + 17 ≤ n ^ 40) :
+ ordinalJobCost n power scan j := by
+ have hL : 1 ≤ (n.log2 + 1) ^ power := Nat.one_le_pow _ _ (by omega)
+ exact ⟨localCost.1.trans (hs.trans (Nat.le_mul_of_pos_right _ hL)),
+ (Nat.le_add_right j.trace.length 17).trans
+ (localCost.2.trans (Nat.pow_le_pow_right hn (by decide)))⟩
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexPaperRatedSelection.lean b/lean/OAI/Computability/VPVNP/PairVertexPaperRatedSelection.lean
new file mode 100644
index 0000000000..f98baef909
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexPaperRatedSelection.lean
@@ -0,0 +1,169 @@
+import OAI.Computability.VPVNP.PairVertexRatedBoundarySelection
+import OAI.Computability.VPVNP.PairVertexRatedRoles
+import OAI.Computability.VPVNP.PairVirtualDescriptorHistory
+import OAI.Computability.VPVNP.LiveVirtualPairQuietPrelude
+
+/-! # The rated terminal branch of the actual finite-model descriptor -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalLink
+
+open BurstRAM LiveProgram
+
+variable {w cap : ℕ} {old new : Stage → PairTable} {pub : Fin 11 → Word w} {m : Memory w}
+ (q : QuietPrefix old pub cap m) (same : old = new)
+
+/-- Identify the fixed prelude under an equality of the installed instruction banks. -/
+def QuietPrefix.reindexWorkers : QuietPrefix new pub cap m := same ▸ q
+
+theorem QuietData.reindexWorkers {lo width pref rows : ℕ}
+ {post : (Fin width → Bool) → Memory w → Prop}
+ (d : QuietData q lo width pref rows post) :
+ QuietData (q.reindexWorkers same) lo width pref rows post := by
+ cases same
+ exact d
+
+end PairSimulation.TerminalLink
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM PrivateRAM
+open CompressorRecords DescriptorSpace
+open PairSimulation LocalHistory NetworkKernel LiveProgram CompressedPair TerminalLink
+open CutSchedule ExponentTrace
+open PairStages.Group.Auxiliary PairStages.Group.CompressedPaths SourceTransport
+open TraversalRows TraversalRoles
+
+open scoped Fin.CommRing
+set_option quotPrecheck false
+attribute [local irreducible] VertexImage.template VertexImage.placement PhysicalScanData.physical
+ TerminalProgram.workers BlockSchedule.Templates.execute BlockProgram.layout
+ CursorNetwork.cursorState CursorBounds.wordBits stateScanPhase
+ onlinePost QuietPrefix.reindexWorkers
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {u : PairExponents B.growthConstant} {n : ℕ} {hn : 2 ≤ n}
+ {ht : 21 ≤ 2 ^ (D.geometry n).w} {hc : 44 ≤ n ^ 10000} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn D.constants.circuitExponent)}
+ {data : D.ScalarData B hn M} {V : D.VirtualPairs B u hn D.constants.circuitExponent}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n ^ D.constants.deltaPower)} {i : D.groupIndices n}
+ {μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht hc)}
+ (scan : CanonicalScan data V ξ i (physicalNomination rfl μ)) (z : (V.selection (M := M)).Choices)
+ {hg : D.constants.motifLabels = Fintype.card B.Entry}
+ (num : D.numerator = (liveRatio u).num) (den : D.denominator = (liveRatio u).den)
+
+local notation "G" => D.executionGroup n ht hc
+local notation "ww" => wordBits D.addressFactor n
+local notation "pub" => terminalOperands (G)
+local notation "cap" => clockAt (publicWords (G)) (fuel (G)) CompressedPair.Stage.terminal
+local notation "X" => V.scanState
+local notation "Y" => (V.selection (M := M)).finalState z
+local notation "κ" => B.compressorValues hn M
+local notation "ok" => B.compressorValues_solution hn M
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "pos" => initialPositions D.addressFactor n
+local notation "baseBits" => virtualBits D.addressFactor n - reservedLanes B u n
+local notation "laneBits" => reservedLanes B u n
+local notation "start" => (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+local notation "names" => entryOrdinal B D.constants hg
+local notation "parts" => paperSegments B u D.constants hg
+local notation "code" =>
+ TerminalProgram.nativeSegments B D.constants D.numerator D.denominator names
+local notation "old" => TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit parts
+local notation "new" => TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit code
+
+include num den in
+/-- The physical role bank selected by the paper parameters. -/
+theorem paper_native_workers : (old) = (new) := by rw [num, den]; rfl
+
+variable {rate : ℕ} {input : Memory (wordBits D.addressFactor n)}
+ (desc : V.PaperDescriptor (B.compressorValues hn M) (B.compressorValues_solution hn M)
+ D.constants hg ((LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n))
+ (fuel (D.executionGroup n ht hc)) rate (terminalOperands (D.executionGroup n ht hc)) input)
+ (q : QuietPrefix (TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit
+ (paperSegments B u D.constants hg)) (terminalOperands (D.executionGroup n ht hc))
+ (clockAt (publicWords (D.executionGroup n ht hc)) (fuel (D.executionGroup n ht hc))
+ CompressedPair.Stage.terminal)
+ (onlinePost (desc.paths z)))
+ (quiet : VirtualPairs.PaperDescriptor.QuietData desc z q)
+
+local notation "same" => paper_native_workers (B := B) (hg := hg) num den
+local notation "q₀" => q.reindexWorkers (same)
+local notation "quiet₀" => quiet.reindexWorkers q (same)
+local notation "L" => BlockProgram.layout B start pos T
+local notation "tab" =>
+ (⟨0, by unfold BlockProgram.layout; change 0 < 6; decide⟩ : Fin (L).shape.tables)
+local notation "layers" => selectedLayers B κ ok T le_rfl (X) z
+local notation "lo" => endAddress (L) + words B.recordLimit (layers)
+local notation "snap₀" =>
+ CompiledResident.payload (w := ww) B κ ok (start : BurstRAM.Word ww) pos T n
+local notation "vs" => executeLevels B κ ok T le_rfl (X) z
+local notation "calendar" => onlinePost (desc.paths z)
+local notation "scanRate" => VertexImage.RatedRoles.scan B names
+local notation "enter" =>
+ TerminalProgram.VertexEntry B κ ok T le_rfl (X) z (L) tab baseBits laneBits
+ (pub) (calendar)
+local notation "past" => SelectedPayloadHistory.Past B κ ok (L) (snap₀) (vs)
+
+private theorem sameReads {w : ℕ} (h : BurstRAM.Word w) (m : Memory w) :
+ Agree (workerCell h) m m := fun _ _ => rfl
+
+local notation "identityReads" => sameReads (header (pub)) (q₀).traversalRows.val.memory
+
+
+/-- The native vertex rows selected from this literal descriptor, with its quiet prefix,
+actual memory and scan rate. -/
+def VirtualPairs.PaperDescriptor.RatedTerminalRows : Prop :=
+ RatedSelection scan z names (endAddress (L)) (pub 4).val (pub 5).val (cap) (pub) (q₀) (lo)
+ (q₀).traversalRows.val.memory (quiet₀).layout (quiet₀).clock (quiet₀).headerFit (quiet₀).below
+ (identityReads) 1 scanRate
+
+set_option maxHeartbeats 2000000 in
+-- The workspace equality is transported through the four dependent vertex-entry indices.
+/-- The selected native branch starts at the literal descriptor's calendar exit.
+The same quiet prefix supplies its wire layout, historical rows and role data. -/
+theorem VirtualPairs.PaperDescriptor.ratedSelection (large : 128 ≤ n)
+ (workspace : (pub 2).val = start) (tag : (PairTag.address (pub)).val < (pub 2).val + 6)
+ (rated : ∀ m₀ m₁ reference m : Memory ww,
+ V.RatedAtBoundary data.advice ξ i μ names κ ok scan.leafSites z baseBits laneBits
+ (initialWidth D.addressFactor n) n 1 scanRate m₀ m₁ reference m)
+ (roles : ∀ bits reference, ((enter) reference bits) → ((past) reference) →
+ ∀ (j : Fin (siteOrder (Y)).length) m, LinkedVertexMemory (G) reference j.val m →
+ V.SelectedRowsAt data.advice ξ i μ names κ ok scan.leafSites z m 1 scanRate) :
+ VirtualPairs.PaperDescriptor.RatedTerminalRows scan z num den desc q quiet := by
+ unfold VirtualPairs.PaperDescriptor.RatedTerminalRows
+ have positions : (X).positions = pos := by
+ rw [V.scanState_pairInput]
+ exact pairInput_positions S _ _
+ let L' := BlockProgram.layout B (pub 2).val (X).positions T
+ have alloc : L' = (L) := by dsimp only [L']; rw [workspace, positions]
+ have raw := desc.current_at_online z workspace
+ have handoff := TerminalPrefix.Linked.handoff_of_transfer (pub) (desc.post z) tag
+ apply (congrArg (fun base =>
+ RatedSelection scan z names base (pub 4).val (pub 5).val (cap) (pub) (q₀) (lo)
+ (q₀).traversalRows.val.memory (quiet₀).layout (quiet₀).clock (quiet₀).headerFit (quiet₀).below
+ (identityReads) 1 scanRate) (congrArg endAddress alloc)).mp
+ apply scan.ratedSelection_of_boundary z names (quiet₀).layout (quiet₀).clock (quiet₀).headerFit
+ (quiet₀).below 1 scanRate large (payload := snap₀)
+ · exact raw
+ · exact handoff
+ · intro bits a tape
+ have chosen : ((enter) a.val.memory bits) ∧ ((past) a.val.memory) :=
+ (quiet₀).entry bits a tape
+ refine ⟨chosen.1.changeLayout alloc.symm rfl, ?_⟩
+ simpa only [workspace, positions] using chosen.2
+ · exact rated _ _
+ · intro bits a entry retained j m later
+ apply roles bits a.val.memory _ _ j m later
+ · exact entry.changeLayout alloc rfl
+ · simpa only [workspace, positions] using retained
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRatedBoundarySelection.lean b/lean/OAI/Computability/VPVNP/PairVertexRatedBoundarySelection.lean
new file mode 100644
index 0000000000..1ae7a4d127
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRatedBoundarySelection.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.PairVertexRatedSelection
+import OAI.Computability.VPVNP.PairVertexRatedEntry
+import OAI.Computability.VPVNP.PairVertexRatedTerminalClock
+import OAI.Computability.VPVNP.PairVirtualOrdinalCalls
+import OAI.Computability.VPVNP.PairVirtualRootPayload
+
+/-! # Certified vertex rows on the physical shared-bit path of the selected calendar -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+
+/-- Transport a checked vertex entry to the same packed directory and table index. -/
+theorem VertexEntry.changeLayout {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+ {B : S.Templates} {f : B.Entry → A} {ok : B.IsSolution f} {lanes T : ℕ}
+ {hT : T * S.laneBits ≤ lanes} {X : State (S.degreeExponent 0) lanes}
+ {z : (B.execute f ok T hT X).Choices} {L L' : Layout} {tab : Fin L.shape.tables}
+ {tab' : Fin L'.shape.tables} {b l w : ℕ} {pub : Fin 11 → BurstRAM.Word w}
+ {m m' : Memory w} {bits : Fin ((B.execute f ok T hT X).finalState z).totalWidth → Bool}
+ (entry : VertexEntry B f ok T hT X z L tab b l pub m m' bits)
+ (same : L = L') (index : tab.val = tab'.val) :
+ VertexEntry B f ok T hT X z L' tab' b l pub m m' bits := by
+ subst L'
+ exact (Fin.ext index : tab = tab') ▸ entry
+
+end PairSimulation.TerminalProgram
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM PrivateRAM
+open CompressorRecords DescriptorSpace
+open PairSimulation LocalHistory NetworkKernel LiveProgram CompressedPair TerminalLink
+open CutSchedule ExponentTrace
+open PairStages.Group.Auxiliary PairStages.Group.CompressedPaths SourceTransport TraversalRows
+
+open scoped Fin.CommRing
+open private scanWords scanMachine capacity from OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+
+set_option quotPrecheck false
+attribute [local irreducible] VertexImage.template VertexImage.placement PhysicalScanData.physical
+ TerminalProgram.workers BlockSchedule.Templates.execute BlockProgram.layout
+ CursorBounds.wordBits CursorNetwork.cursorState stateScanPhase
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {u : PairExponents B.growthConstant} {n : ℕ} {hn : 2 ≤ n}
+ {ht : 21 ≤ 2 ^ (D.geometry n).w} {hc : 44 ≤ n ^ 10000} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn D.constants.circuitExponent)}
+ {data : D.ScalarData B hn M} {V : D.VirtualPairs B u hn D.constants.circuitExponent}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n ^ D.constants.deltaPower)} {i : D.groupIndices n}
+ {μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht hc)}
+ (scan : CanonicalScan data V ξ i (physicalNomination rfl μ)) (z : (V.selection (M := M)).Choices)
+ (names : B.Entry ≃ Fin D.constants.motifLabels)
+
+local notation "G" => D.executionGroup n ht hc
+local notation "ww" => wordBits D.addressFactor n
+local notation "pub" => terminalOperands (G)
+local notation "cap" => clockAt (publicWords (G)) (fuel (G)) CompressedPair.Stage.terminal
+local notation "X" => V.scanState
+local notation "Y" => (V.selection (M := M)).finalState z
+local notation "κ" => B.compressorValues hn M
+local notation "ok" => B.compressorValues_solution hn M
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "L" => BlockProgram.layout B (pub 2).val (X).positions T
+local notation "tab" =>
+ (⟨0, by unfold BlockProgram.layout; change 0 < 6; decide⟩ : Fin (L).shape.tables)
+local notation "code" =>
+ TerminalProgram.nativeSegments B D.constants D.numerator D.denominator names
+local notation "bank" => TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit code
+local notation "vs" => executeLevels B κ ok T le_rfl (X) z
+local notation "shape" => BlockProgram.allocationShape B
+local notation "ref" => scanMachine ww
+local notation "link" => FinalBits.template_linked (scanWords ww)
+local notation "fit" => capacity scan z
+
+variable {baseBits laneBits initialWidth inputN : ℕ}
+ {online calendar : Memory (wordBits D.addressFactor n)}
+ {payload : SelectedPayloadHistory.Data (w := wordBits D.addressFactor n) B
+ (B.compressorValues hn M) (B.compressorValues_solution hn M)}
+ {q : QuietPrefix (TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit
+ (TerminalProgram.nativeSegments B D.constants D.numerator D.denominator names))
+ (terminalOperands (D.executionGroup n ht hc))
+ (clockAt (publicWords (D.executionGroup n ht hc)) (fuel (D.executionGroup n ht hc))
+ CompressedPair.Stage.terminal) calendar} {lo : ℕ}
+ (layout : FinalBits.Worker.Layout (terminalOperands (D.executionGroup n ht hc))
+ q.traversalRows.val.memory lo ((V.selection (M := M)).finalState z).totalWidth)
+ (clock : 54 ≤ clockAt (publicWords (D.executionGroup n ht hc)) (fuel (D.executionGroup n ht hc))
+ CompressedPair.Stage.terminal)
+ (room : (header (terminalOperands (D.executionGroup n ht hc))).val + 32 ≤
+ 2 ^ (wordBits D.addressFactor n))
+ (below : lo + ((V.selection (M := M)).finalState z).totalWidth ≤
+ (header (terminalOperands (D.executionGroup n ht hc))).val)
+
+local notation "saved" => CursorRAM.ScheduleInit.inputs (CursorRAM.encode ww (directoryBase (L)))
+ (CursorRAM.encode ww 1) baseBits laneBits (S.degreeExponent 0) initialWidth (incidenceStart (L) 0)
+local notation "resident" => CurrentResident.resident B κ ok ⟨leafLayer (siteOrder (X)), .cursor⟩
+ (L) (endAddress (L)) inputN (saved)
+local notation "enter" =>
+ TerminalProgram.VertexEntry B κ ok T le_rfl (X) z (L) tab baseBits laneBits
+ (pub) calendar
+local notation "past" => SelectedPayloadHistory.Past B κ ok (L) payload (vs)
+local notation "linked" => LinkedVertexMemory (G)
+local notation "phys" =>
+ PhysicalScanData.physical (Y) (ref) Fin.castSucc (Function.Embedding.refl _)
+ 0 10 link rfl 0 rfl (fun _ => 0) 0 fit shape B.recordLimit code (pub) (cap)
+ q.traversalRows.val.memory q.traversalRows.val.memory lo layout clock room below (fun _ _ => rfl)
+
+/-- Transport the retained rows and the measured role contracts along the
+actual shared-bit tape used by each canonical arc assignment. The later
+site frames use precisely this path's physical post-memory. -/
+theorem CanonicalScan.ratedSelection_of_boundary (power scanRate : ℕ) (large : 128 ≤ n)
+ (boundary : ScheduledTrace.Boundary (resident) (pub) (levelWords (L) : BurstRAM.Word ww)
+ (directoryRows (L)) (directoryRows (L)) (vs) (Y) online)
+ (handoff : Agree ((pub 2).val + 6 ≤ ·) online calendar)
+ (picked : ∀ bits (a : q.BitPaths), a.val.choices = FinalBits.calls bits ++ [[]] →
+ ((enter) a.val.memory bits) ∧ ((past) a.val.memory))
+ (rated : ∀ reference m, V.RatedAtBoundary data.advice ξ i μ names κ ok scan.leafSites z
+ baseBits laneBits initialWidth inputN power scanRate online calendar reference m)
+ (roles : ∀ bits (a : q.BitPaths), ((enter) a.val.memory bits) → ((past) a.val.memory) →
+ ∀ (j : Fin (siteOrder (Y)).length) m, ((linked) a.val.memory j.val m) →
+ V.SelectedRowsAt data.advice ξ i μ names κ ok scan.leafSites z m power scanRate) :
+ RatedSelection scan z names (endAddress (L)) (pub 4).val (pub 5).val cap (pub)
+ q lo q.traversalRows.val.memory layout clock room below (fun _ _ => rfl) power scanRate := by
+ have fromPath (x : (scan.arc z).Path) :
+ ((enter) ((phys) x).val.memory (scan.sharedBits z x)) ∧ ((past) ((phys) x).val.memory) := by
+ apply picked
+ exact (PhysicalScanData.physical_choices ..).trans
+ (congrArg (· ++ [[]]) (PhysicalScanData.calls (Y) (ref) Fin.castSucc
+ (Function.Embedding.refl _)
+ 0 10 link rfl 0 rfl (fun _ => 0) 0 fit x))
+ refine ⟨fun x => (fromPath x).1.storedOrdinal room, ?_⟩
+ intro x j m later
+ have ⟨entry, retained⟩ := fromPath x
+ have checks := roles _ ((phys) x) entry retained j m later
+ have row := rated _ m boundary handoff _ entry j later checks (cap)
+ (terminal_ordinal_room (G) large rfl)
+ have fields := PhysicalScanData.payload (Y) (ref) Fin.castSucc (Function.Embedding.refl _)
+ 0 10 link rfl 0 rfl (fun _ => 0) 0 fit x
+ have same : TerminalGatherGeometry.half (Y)
+ (fun t => scan.sharedBits z x (Fin.cast (TerminalPrefix.width_sum (Y)) t)) =
+ WireTensor.edgeAssignment (Y).network.src (Y).network.dst ((scan.arc z).payload x) :=
+ congrArg (WireTensor.edgeAssignment (Y).network.src (Y).network.dst) fields.symm
+ rw [← same]
+ exact row
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRatedClock.lean b/lean/OAI/Computability/VPVNP/PairVertexRatedClock.lean
new file mode 100644
index 0000000000..b851d42e16
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRatedClock.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.PairVertexSelectedClock
+import OAI.Computability.VPVNP.PairVertexOrdinalLiveCosts
+import OAI.Computability.VPVNP.LiveVirtualPairCursorBoundary
+
+/-! # A single length threshold for the native selected root and its jobs -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression CompressorRecords CursorNetwork CursorBounds Filter LiveProgram
+open PairSimulation VertexImage NativeOperands
+
+set_option exponentiation.threshold 10000 in
+/-- The native geometry, cache initialization and active DFS clock estimates
+hold simultaneously before the coefficient realization or branch is chosen.
+Each job receives the same private allowance as in the measured ordinal row. -/
+theorem eventually_rated_root_clock {K : Type*} [_root_.Field K] {S : BlockSchedule K}
+ (D : FixedProgramDiagonal.Program) (B : S.Templates) (u : PairExponents B.growthConstant)
+ (haddr : max S.laneBits 5 ≤ D.addressFactor) (C : ℕ) :
+ ∀ᶠ n : ℕ in atTop, 2048 ≤ n ∧ S.baseDegree ≤ n ∧ Fintype.card B.Entry ≤ n ∧
+ (∀ t ≤ work (NativeCache.args D.constants) D.numerator D.denominator (D.geometry n)+76,
+ t+slotDegree S+187 ≤ 44+n^3) ∧
+ ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C) (A : Type*) [CommRing A]
+ (f : B.Entry → A) (ok : B.IsSolution f),
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f ok T le_rfl X
+ B.growthConstant^T ≤ n ∧ ∀ z : E.Choices,
+ let Y := E.finalState z
+ let chain := E.termChain (B.records f ok T le_rfl X) z
+ Y.maxWireWidth ≤ n ∧ ∀ v : Y.network.Site,
+ chain.occurrences (fun _ => 1) v ≤ n ∧
+ ∀ (half : Y.network.Half v) t,
+ t ≤ work (NativeCache.args D.constants) D.numerator D.denominator (D.geometry n)+76 →
+ t+slotDegree S+187+(15+21*S.baseDegree+5*(NodeArguments.packed Y v half).length)+
+ (15+n^43)*chain.occurrences (fun _ => 1) v+7*Fintype.card B.Entry+46 ≤ n^9999 := by
+ have slots : 2^(S.degreeExponent 0) ≤ slotDegree S :=
+ (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ 0)).trans
+ (le_max_right _ _)
+ filter_upwards [eventually_ordinal_geometry B u D.constants D.numerator D.denominator
+ D.addressFactor (slotDegree S) haddr,
+ eventually_active_clock B u D.constants D.numerator D.denominator D.addressFactor haddr
+ (slotDegree S) slots]
+ with n geo budget
+ refine ⟨geo.1,geo.2.1,geo.2.2.1,geo.2.2.2.1 (D.geometry n).H,?_⟩
+ intro hn V A inst f ok
+ dsimp only
+ rw [V.scanState_pairInput]
+ let labels := laneLabels _ _ V.lanes
+ have schedule := geo.2.2.2.2 labels V.dimension le_rfl A f ok
+ have clock := budget labels V.dimension le_rfl A f ok
+ refine ⟨clock.1,?_⟩
+ intro z
+ refine ⟨(schedule z).1,fun v => ⟨(schedule z).2 v,?_⟩⟩
+ intro half t ht
+ exact clock.2 z v half (D.geometry n).H t (n ^ 43) ht
+ (Nat.pow_le_pow_right (by omega) (by decide : (43 : ℕ) ≤ 9000))
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRatedEntry.lean b/lean/OAI/Computability/VPVNP/PairVertexRatedEntry.lean
new file mode 100644
index 0000000000..f3f1182197
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRatedEntry.lean
@@ -0,0 +1,47 @@
+import OAI.Computability.VPVNP.PairTerminalPackedPrefix
+
+/-! # The final ordinal stored by the actual selected terminal prefix -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace LocalHistory TerminalLink
+ TraversalRows
+open scoped Fin.CommRing
+
+variable {w : ℕ} {k K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ {B : S.Templates} {κ : B.Entry → K} {hκ : B.IsSolution κ} {lanes T : ℕ}
+ {hT : T * S.laneBits ≤ lanes} {X : State (S.degreeExponent 0) lanes} {z : (B.execute κ hκ T hT
+ X).Choices}
+ {L : Layout} {tab : Fin L.shape.tables} {baseBits laneBits : ℕ} {pub : Fin 11 → Word w}
+ {calendar vertex : Memory w}
+local notation "Y" => StateExecution.finalState (B.execute κ hκ T hT X) z
+local notation "layers" => selectedLayers B κ hκ T hT X z
+
+/-- The active site's closing ordinal is read from header word seven of
+the post-scan memory. -/
+theorem VertexEntry.storedOrdinal {bits : Fin (Y).totalWidth → Bool}
+ (entry : VertexEntry B κ hκ T hT X z L tab baseBits laneBits pub calendar vertex bits)
+ (room : (header pub).val + 32 ≤ 2 ^ w) :
+ vertex (header pub + 7).val = ((siteOrder (Y)).length : Word w) := by
+ let source := TerminalBootstrap.fromState L (List.dropLast (layers)) B.recordLimit baseBits
+ laneBits (Y) tab
+ have raw := entry.headers (7 : Fin 21) (by decide) (by decide) (by decide)
+ change vertex ((header pub).val + 7) = (source.sites : Word w) at raw
+ have h7 : (7 : Word w).val = 7 := Nat.mod_eq_of_lt (show (7 : ℕ) < 2 ^ w by omega)
+ have atSeven : (header pub + 7).val = (header pub).val + 7 := by
+ rw [Fin.val_add,h7,Nat.mod_eq_of_lt (by omega)]
+ have sites : source.sites = (Y).positions := TerminalBootstrap.fromState_sites ..
+ have order : (siteOrder (Y)).length = (Y).positions := by
+ change (siteOrder (Y)).length = Fintype.card (Y).network.Site
+ simpa only [Fintype.card_fin] using Fintype.card_congr (siteOrder (Y)).entries
+ rw [atSeven,raw,sites,order]
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRatedRoles.lean b/lean/OAI/Computability/VPVNP/PairVertexRatedRoles.lean
new file mode 100644
index 0000000000..fb4c97b081
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRatedRoles.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.PairShrinkScanCoefficient
+import OAI.Computability.VPVNP.PairShrinkNodeRates
+import OAI.Computability.VPVNP.PairShrinkPrologueBudget
+import OAI.Computability.VPVNP.PairRefreshHookBudget
+import OAI.Computability.VPVNP.PairSelectedLevelChecks
+
+/-! # A single probe coefficient for the installed terminal role programs -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RatedRoles
+
+open BurstRAM PrivateRAM Compression CompressorRecords DFS LocalHistory
+open NetworkKernel NodeArguments TreeDecode
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {labels : ℕ}
+ (names : B.Entry ≃ Fin labels)
+
+/-- Each entry is the probe rate for the native program at its role tag.
+The shrinking entry includes the full resident map loop and its prologue. -/
+noncomputable def roleRate : NodeDispatch.Role → ℕ
+ | .leaf => 2
+ | .shrink => ShrinkNodeCost.probeRate S (ShrinkRole.MapWitness.scanCoefficient B names)
+ (ShrinkNodeCost.prologueCoefficient B)
+ | .refresh =>
+ RefreshHook.Site.scan B (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride names
+
+/-- This coefficient is fixed by the templates and their label ordering. -/
+noncomputable def scan : ℕ :=
+ max 2 (max (roleRate B names .shrink) (roleRate B names .refresh))
+
+theorem role_le (role : NodeDispatch.Role) : roleRate B names role ≤ scan B names := by
+ cases role with
+ | leaf => exact le_max_left ..
+ | shrink => exact (le_max_left ..).trans (le_max_right ..)
+ | refresh => exact (le_max_right ..).trans (le_max_right ..)
+
+variable {w endAddr n : ℕ}
+
+/-- The local job bound is preserved for the same events and scratch update. -/
+theorem job (role : NodeDispatch.Role) (j : VisitPath w endAddr)
+ (checked : ordinalJobCost n 1 (roleRate B names role) j) :
+ ordinalJobCost n 1 (scan B names) j :=
+ ⟨checked.1.trans (Nat.mul_le_mul_right _ (role_le B names role)),checked.2⟩
+
+variable {geometry rootFields leaf shrink refresh : Segment} {p regs : ℕ}
+ {A : Placement (segments geometry rootFields leaf shrink refresh) p regs}
+ {M : Machine w p regs 11}
+ {m : Memory w} {allow : ℕ → Prop} {R : Type*} [CommRing R] {f : B.Entry → R}
+ {valid : List Packet → Scratch w endAddr → Prop} {hist : Scratch w endAddr → B.Entry → ℕ}
+
+/-- The decoded jobs, their exponents and their complete source reports stay
+together under the common scan allowance. -/
+theorem emits (role : NodeDispatch.Role) {N : Network} {P : SiteParsers f N}
+ {input : Packets N} {jobs : JobsFor P}
+ (native : Emits valid hist (JobGuard A M m allow
+ (ordinalJobCost n 1 (roleRate B names role))) P input jobs) :
+ Emits valid hist (JobGuard A M m allow (ordinalJobCost n 1 (scan B names))) P input jobs :=
+ emits_withCost native (job B names role)
+
+/-- The observed two-probe leaf bound and its measured private clock give
+the common allowance on every emitted leaf visit. -/
+theorem leafEmits {N : Network} {P : SiteParsers f N}
+ {input : Packets N} {jobs : JobsFor P}
+ (hn : 1 ≤ n) (native : Emits valid hist (JobGuard A M m allow
+ (fun j => countProbes j.trace ≤ 2 ∧ j.trace.length + 17 ≤ n ^ 40)) P input jobs) :
+ Emits valid hist (JobGuard A M m allow (ordinalJobCost n 1 (scan B names))) P input jobs :=
+ emits_withCost native (fun _ h => leaf_ordinal_cost hn (role_le B names .leaf) h)
+
+/-- The selected pass keeps its row, parser and emitted jobs when its
+role-specific rate is charged to the common coefficient. -/
+theorem levelChecks (role : NodeDispatch.Role) {hf : B.IsSolution f} {hook : HookParser w endAddr}
+ {cap base : ℕ} {v : SelectedLevel B f hf}
+ (native : LevelChecks B f hf hook valid hist (JobGuard A M m allow
+ (ordinalJobCost n 1 (roleRate B names role))) cap base v) :
+ LevelChecks B f hf hook valid hist (JobGuard A M m allow
+ (ordinalJobCost n 1 (scan B names))) cap base v :=
+ ⟨native.1,emitsNode_withCost native.2 (job B names role)⟩
+
+end PairSimulation.VertexImage.RatedRoles
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRatedRoot.lean b/lean/OAI/Computability/VPVNP/PairVertexRatedRoot.lean
new file mode 100644
index 0000000000..dae4de716f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRatedRoot.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PairVertexRatedRow
+import OAI.Computability.VPVNP.PairVertexOrdinalRoleCost
+import OAI.Computability.VPVNP.PairVertexOrdinalLiveCosts
+import OAI.Computability.VPVNP.PairVertexRootOrdinal
+import OAI.Computability.VPVNP.PairVirtualVertexRoot
+
+/-! # Measured ordinal calls initialized by the physical root gather -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM Compression DFS LocalHistory NodeArguments TraversalRows TreeDecode
+open CompressorRecords.SourceTransport LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {k K : Type*} [Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → K) (hκ : B.IsSolution κ) {lanes : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute κ hκ T hT X).Choices) (rowBase : ℕ)
+ {geometry rootFields leaf shrink refresh : Segment} {p r w g : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r) (M : Machine w p r 11)
+ (m : Memory w) (base grammar : ℕ) (order : Fin g ≃ B.Entry) (P : SiteParsers κ X.network)
+ (half : ∀ u, ((B.execute κ hκ T hT X).finalState z).network.Half u)
+ (cap : ℕ) (i : Fin (siteOrder ((B.execute κ hκ T hT X).finalState z)).length)
+ (degree bound n power scan nodeCap : ℕ) (vals : Static 34 → Word w)
+ (format : Packet → Prop) (desc : ℕ → List ℕ)
+ (domain : Word w → Scratch w (M.publicData 6).val → Prop)
+ (handlers : NodeDispatch.Role → HookParser w (M.publicData 6).val)
+
+local notation "E₀" => B.execute κ hκ T hT X
+local notation "Y₀" => StateExecution.finalState (E₀) z
+local notation "v₀" => Order.entries (siteOrder (Y₀)) i
+local notation "tree₀" => selectedTrees B κ hκ T hT X z rowBase (v₀)
+local notation "packet₀" => Packet.mk (VertexTree.address (tree₀)) (packed (Y₀) (v₀) (half (v₀)))
+local notation "chain₀" => StateExecution.termChain (E₀) (B.records κ hκ T hT X) z
+local notation "N₀" => Fin.val (Machine.publicData M 6)
+local notation "H₀" => TerminalLink.header (Machine.publicData M)
+local notation "role₀" => m (Fin.val ((H₀) + 14))
+local notation "area₀" => NativeFrame.fromHeader degree (Machine.publicData M) (H₀) m
+local notation "leaf₀" => NativeFrame.leafWords degree (Machine.publicData M) (H₀) (role₀) m
+local notation "fields₀" => NativeFrame.fields degree (Machine.publicData M) (H₀) (role₀) m
+local notation "valid₀" => Budgeted (LeafArena.Regions.arguments (area₀)) format
+ (VertexFrameData (area₀) (leaf₀) (role₀) vals) desc
+ (privateHistogram order (LeafArena.Regions.histBase (area₀))) nodeCap ((N₀) * nodeCap)
+
+/-- A successful gather and verified selected role programs give a row
+whose clock and probe estimates refer to that same physical execution. -/
+theorem RootRun.ratedOrdinal
+ (root : RootRun A M m (i.val : Word w) degree (S.degreeExponent 0) bound (packet₀) vals)
+ (checked : SelectedChecks B κ hκ T hT X z rowBase A M m
+ ((NativeFrame.frameBase (area₀)) : Word w) (role₀) (LeafArena.Regions.histBase (area₀))
+ order P (valid₀) domain handlers (ordinalJobCost n power scan))
+ (type : format (packet₀)) (children : subtreeAddresses desc (packet₀) = (tree₀).preorder)
+ (rows : AllRows w m B.recordLimit rowBase rowBase (selectedLayers B κ hκ T hT X z))
+ (space : rowBase + words B.recordLimit (selectedLayers B κ hκ T hT X z) ≤ (H₀).val)
+ (headerFit : (H₀).val + 31 < 2 ^ w)
+ (cacheFit : (area₀).cacheBase + 38 ≤ 2 ^ w)
+ (capacity : B.growthConstant ^ T ≤ N₀) (external : base + grammar + g ≤ (H₀).val)
+ (hbase : M.publicData 4 = (base : Word w)) (hgrammar : M.publicData 5 = (grammar : Word w))
+ (hg : M.publicData 9 = (g : Word w))
+ (cacheTime : ∀ t ≤ bound, t + degree + 187 ≤ 44 + n ^ 3)
+ (clock : ∀ t ≤ bound,
+ t + degree + 187 + (15 + 21 * S.baseDegree + 5 * (packet₀).bits.length) +
+ (15 + n ^ 43) * (chain₀).occurrences (fun _ => 1) (v₀) + 7 * g + 46 ≤ cap) :
+ Nonempty (RatedOrdinal B κ hκ T hT X z rowBase A M base grammar order P
+ half cap m i n power scan) := by
+ obtain ⟨t,ht,cfg,pre,ready,ticks,probes,det,same,reads,run⟩ := root.run
+ have labelCount : (area₀).histWords = g := by
+ change (M.publicData 9).val = g
+ rw [hg,Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ subst g
+ have positive : 0 < N₀ :=
+ lt_of_lt_of_le (pow_pos (by have := B.growthConstant_ge_two; omega) _) capacity
+ have above : N₀ ≤ (area₀).histBase := Nat.le_add_right _ _
+ have measure := ordinal_prefix_bounds (Y₀) (v₀) (half (v₀)) pre t degree n
+ probes ticks (cacheTime t ht)
+ let row := OrdinalRows.ofRoot B κ hκ T hT X z rowBase A M m base grammar order P half cap i
+ (area₀) (leaf₀) (fields₀) vals (role₀) nodeCap (n ^ 43) format desc
+ domain handlers
+ (ordinalJobCost n power scan) checked cfg pre ready run det same reads rfl rfl rfl
+ positive above cacheFit type children rows space headerFit capacity external hbase hgrammar hg
+ (fun _ h => h.2) (ticks ▸ clock t ht)
+ exact ⟨row,measure.1,measure.2,fun _ h => h.1,le_rfl⟩
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRatedRow.lean b/lean/OAI/Computability/VPVNP/PairVertexRatedRow.lean
new file mode 100644
index 0000000000..ec53c99ac8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRatedRow.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.PairVertexOrdinalReportCosts
+
+/-! # A selected ordinal with the measurements of its physical root and role jobs -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM Compression DFS LocalHistory NetworkKernel NodeArguments TreeDecode
+ TraversalRows
+open CompressorRecords SourceTransport TerminalLink
+open scoped Fin.CommRing
+
+variable {k R : Type*} [Field k] [CommRing R] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → R) (hκ : B.IsSolution κ) {lanes : ℕ}
+ (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute κ hκ T hT X).Choices) (rowBase : ℕ)
+ {geometry rootFields leaf shrink refresh : Segment} {p r w g : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r) (M : Machine w p r 11)
+ (base grammar : ℕ) (order : Fin g ≃ B.Entry) (P : SiteParsers κ X.network)
+
+local notation "exec₀" => B.execute κ hκ T hT X
+local notation "data₀" => B.records κ hκ T hT X
+local notation "chain₀" => StateExecution.termChain (exec₀) (data₀) z
+local notation "readers₀" => selectedParsers B κ hκ T hT X z
+local notation "trees₀" => selectedTrees B κ hκ T hT X z rowBase
+local notation "Y" => StateExecution.finalState (exec₀) z
+local notation "ord₀" => siteOrder (Y)
+local notation "final₀" => finalParsers (chain₀) (readers₀) P
+local notation "head₀" => TerminalLink.header (Machine.publicData M)
+local notation "allow₀" => workerCell (head₀)
+
+variable (half : ∀ u, ((B.execute κ hκ T hT X).finalState z).network.Half u)
+
+local notation "selected₀" => siteOrdinals (final₀) (Order.entries (ord₀)) order half
+
+variable (cap : ℕ) (m : Memory w) (i : Fin (siteOrder ((B.execute κ hκ T hT X).finalState
+ z)).length)
+
+local notation "rows₀" => OrdinalRows B κ hκ T hT X z rowBase A M base grammar order P half cap m i
+
+open CursorNetwork
+
+
+/-- Retains the measured prefix and the native local-role allowance on the
+same memory and half-wire assignment as the classified returning paths. -/
+structure RatedOrdinal (n power scan : ℕ) where
+ /-- The selected ordinal's concrete vertex rows and parser inputs carried alongside their
+ cost bounds. -/
+ row : rows₀
+ preProbes : countProbes row.pre ≤ 9 + 6 + 5 * S.baseDegree + incidentBits (Y) ((ord₀).entries i)
+ preTicks : row.pre.length ≤ 44 + n ^ 3 + (15 + 21 * S.baseDegree + 5 * incidentBits (Y)
+ ((ord₀).entries i))
+ jobProbes : ∀ j, row.cost j → countProbes j.trace ≤ scan * (n.log2 + 1) ^ power
+ jobTicks : row.maxTicks ≤ n ^ 43
+
+variable {B κ hκ T hT X z rowBase A M base grammar order P half cap m i} {n power scan : ℕ}
+
+/-- The bound for a specific successful source report, including the
+margin for both physical controllers. -/
+theorem RatedOrdinal.report_cost (q : RatedOrdinal B κ hκ T hT X z rowBase A M base grammar order P
+ half cap m i n power scan) (link : Contains A M)
+ (hn : 2048 ≤ n) (degree : S.baseDegree ≤ n) (labels : Fintype.card B.Entry ≤ n)
+ (width : (Y).maxWireWidth ≤ n) (visits : (chain₀).occurrences (fun _ => 1) ((ord₀).entries i)
+ ≤ n)
+ (x : (selected₀).Choice i) (r : Report w) (run : execute M.program cap
+ (M.program.start (i.val : Word w)) m ((selected₀).encode i x) = some r) :
+ 1 + r.probes ≤ siteAccesses (Y) (chain₀)
+ (VertexReportBudget.coefficient S.baseDegree (Fintype.card B.Entry) 6 scan 0 0)
+ power n ((ord₀).entries i) ∧ r.events.length + 107 ≤ n ^ 45 :=
+ q.row.ordinalChecks B κ hκ T hT X z rowBase A M base grammar order P half link n power 6 scan
+ hn degree labels width visits q.preProbes q.preTicks q.jobProbes q.jobTicks x r run
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRatedSelection.lean b/lean/OAI/Computability/VPVNP/PairVertexRatedSelection.lean
new file mode 100644
index 0000000000..144c3e22b4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRatedSelection.lean
@@ -0,0 +1,178 @@
+import OAI.Computability.VPVNP.PairVertexRatedRow
+import OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+import OAI.Computability.VPVNP.LiveCompressedPairVertexAssembly
+import OAI.Computability.VPVNP.LiveCompressedPairBranchCharge
+import OAI.Computability.VPVNP.PairTerminalNativeTable
+
+/-! # The physical vertex phase and its site charges on a canonical virtual pair -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM PrivateRAM CompressorRecords
+ SourceTransport
+open PairSimulation LocalHistory NetworkKernel LiveProgram CompressedPair TerminalLink CutSchedule
+ ExponentTrace
+open scoped Fin.CommRing
+set_option quotPrecheck false
+set_option genSizeOf false
+attribute [local irreducible] VertexImage.template VertexImage.segments PhysicalScanData.physical
+ TerminalProgram.workers
+ BlockSchedule.Templates.execute CursorNetwork.cursorState CursorBounds.wordBits stateScanPhase
+ VertexImage.placement
+open private scanWords scanMachine capacity from OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+
+variable {k : Type} [Field k] {S : BlockSchedule k} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {model : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ {data : D.ScalarData B hn model} {u : PairExponents B.growthConstant} {V : D.VirtualPairs B u
+ hn C}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n ^ D.constants.deltaPower)} {i : D.groupIndices n} {μ :
+ D.pairNom n C}
+ (scan : CanonicalScan data V ξ i μ) (z : (V.selection (M := model)).Choices)
+
+local notation "w" => CursorBounds.wordBits D.addressFactor n
+local notation "Y" => (V.selection (M := model)).finalState z
+local notation "κ" => B.compressorValues hn model
+local notation "hf" => B.compressorValues_solution hn model
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "ord" => (siteOrder (Y)).entries
+local notation "scanM" => scanMachine w
+local notation "sl" => FinalBits.template_linked (scanWords w)
+local notation "bitFit" => capacity scan z
+local notation "shape" => BlockProgram.allocationShape B
+
+variable {g : ℕ} (names : B.Entry ≃ Fin g) (rowBase counter grammar cap : ℕ)
+ (pub : Fin 11 → BurstRAM.Word (CursorBounds.wordBits D.addressFactor n))
+ {mem : Memory (CursorBounds.wordBits D.addressFactor n)}
+
+local notation "geo" => VertexGeometry.segment D.constants (slotDegree S) D.numerator D.denominator
+local notation "shr" => ShrinkVertexImage.shrinkSegment B names
+local notation "ref" =>
+ RefreshVertex.refreshSegment B (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride names
+local notation "code" =>
+ VertexImage.segments geo TerminalRootGather.segment LeafRole.segment shr ref
+local notation "worker" => (VertexImage.template code).instantiate w pub
+local notation "W" => TerminalProgram.workers shape B.recordLimit code
+
+variable (q : QuietPrefix (TerminalProgram.workers (BlockProgram.allocationShape B) B.recordLimit
+ (TerminalProgram.nativeSegments B D.constants D.numerator D.denominator names)) pub cap mem)
+ (lo : ℕ) (before : Memory (CursorBounds.wordBits D.addressFactor n))
+ (layout : FinalBits.Worker.Layout pub before lo ((V.selection (M := model)).finalState
+ z).totalWidth)
+ (clock : 54 ≤ cap) (headerFit : (header pub).val + 32 ≤ 2 ^ (CursorBounds.wordBits
+ D.addressFactor n))
+ (below : lo + ((V.selection (M := model)).finalState z).totalWidth ≤ (header pub).val)
+ (agree : Agree (workerCell (header pub)) before q.traversalRows.val.memory)
+
+local notation "arc" => scan.arc z
+local notation "parsers" => scan.sites z
+local notation "fields" x =>
+ WireTensor.edgeAssignment (Y).network.src (Y).network.dst ((arc).payload x)
+local notation "physical" =>
+ PhysicalScanData.physical (Y) scanM Fin.castSucc (Function.Embedding.refl _) 0 10
+ sl rfl 0 rfl (fun _ => 0) 0 bitFit shape B.recordLimit code pub cap before
+ q.traversalRows.val.memory
+ lo layout clock headerFit below agree
+local notation "mem₀" x => ((physical) x).val.memory
+local notation "frame" x => VertexFrame.Linked (header pub) counter grammar g (mem₀ x)
+local notation "row₀" => VertexImage.RatedOrdinal B κ hf T le_rfl V.scanState z rowBase
+ (VertexImage.placement code) worker counter grammar names.symm scan.leafSites
+
+/-- The chosen physical shared-bit output supplies the reference for every
+later site. Only the stored ordinal and the individual initialized root
+rows, including their installed role costs, are required. -/
+def RatedSelection (power scanRate : ℕ) : Prop :=
+ (∀ x : (arc).Path, (mem₀ x) (header pub + 7).val = ((siteOrder (Y)).length : BurstRAM.Word w)) ∧
+ ∀ (x : (arc).Path) (j : Fin (siteOrder (Y)).length) (m : Memory w),
+ (frame x) j.val m → Nonempty (row₀ (fields x) cap m j n power scanRate)
+
+variable {power scanRate : ℕ}
+ (R : RatedSelection scan z names rowBase counter grammar cap pub q lo before layout clock
+ headerFit
+ below agree power scanRate)
+ (counterEnd : counter + grammar + g ≤ (header pub).val)
+
+local notation "visit" x =>
+ SelectedSites (Y) scanM Fin.castSucc (Function.Embedding.refl _) 0 10 sl rfl
+ 0 rfl (fun _ => 0) 0 bitFit (parsers) ord names.symm shape B.recordLimit pub q lo before layout
+ clock headerFit below agree counter grammar x
+
+/-- Use the same initialized row for forward execution, raw-tape decoding
+and source report checks. The source and physical executions start on the
+actual post-scan memory. -/
+noncomputable def RatedSelection.selectedSites (x : (arc).Path) : visit x := by
+ have localRows (j : Fin (siteOrder (Y)).length) (m : Memory w) (h : (frame x) j.val m) :=
+ (R.2 x j m h).elim fun r => (show Nonempty (VertexImage.OrdinalRows B κ hf T le_rfl
+ V.scanState z
+ rowBase (VertexImage.placement code) worker counter grammar names.symm scan.leafSites
+ (fields x)
+ cap m j) from ⟨r.row⟩)
+ let checked := VertexImage.selectedCalls B κ hf T le_rfl V.scanState z rowBase
+ (VertexImage.placement code) worker counter grammar names.symm scan.leafSites (fields x)
+ (mem₀ x) (VertexImage.template_contains code pub) localRows
+ exact {
+ reference := mem₀ x
+ sourceMem := mem₀ x
+ active := checked.1
+ checks := checked.2
+ stored := VertexImage.linked_finalSites (mem₀ x) headerFit counterEnd (R.1 x)
+ sourceReady := VertexFrame.linked_initial (header pub) counter grammar g 0 (mem₀ x)
+ physicalReady := VertexFrame.linked_initial (header pub) counter grammar g 0 (mem₀ x)
+ agree := fun _ _ => rfl }
+
+
+local notation "visit₀" =>
+ R.selectedSites scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd
+
+/-- The source branch associated with this certified family of physical
+ordinal rows. Its vertex path uses the assignment of its own bit path. -/
+noncomputable abbrev RatedSelection.branch :=
+ selectedTerminalBranch (Y) scanM Fin.castSucc (Function.Embedding.refl _) 0 10 sl rfl 0 rfl
+ (fun _ => 0)
+ 0 bitFit (parsers) ord names.symm shape B.recordLimit pub q lo before layout clock headerFit
+ below
+ agree counter grammar (visit₀)
+
+local notation "branch₀" => R.branch scan z names rowBase counter grammar cap pub q lo before layout
+ clock headerFit below agree counterEnd
+local notation "C₀" =>
+ VertexReportBudget.coefficient S.baseDegree (Fintype.card B.Entry) 6 scanRate 0 0
+
+/-- Both raw phase lists and the measured bound at every individual site,
+on the exact same accepted five-phase trace. -/
+theorem RatedSelection.chosenRows (hn₀ : 2048 ≤ n) (degree : S.baseDegree ≤ n)
+ (labels : Fintype.card B.Entry ≤ n) (width : (Y).maxWireWidth ≤ n)
+ (depth : ∀ v, (selectedChain (V := V) (M := model) z).occurrences (fun _ => 1) v ≤ n)
+ (x : TerminalData (arc) (parsers)) :
+ ∃ (bitMemory last : Memory w) (bits : Fin (Y).totalWidth → Bool) (reps : (Y).network.Site →
+ Report w),
+ ((branch₀).chosenTrace x).sharedBits.logs.map Prod.snd = FinalBits.Worker.reports pub 0
+ bitMemory bits ∧
+ ((branch₀).chosenTrace x).vertices.logs.map Prod.snd = (List.ofFn fun j => reps (ord j)) ++
+ [VertexImage.closingReport pub last] ∧
+ ∀ v, 1 + (reps v).probes ≤ siteAccesses (Y) (selectedChain (V := V) (M := model) z) C₀ power
+ n v ∧
+ (reps v).events.length + 107 ≤ n ^ 45 := by
+ let ok := fun v (r : Report w) => 1 + r.probes ≤
+ siteAccesses (Y) (selectedChain (V := V) (M := model) z) C₀ power n v ∧ r.events.length + 107
+ ≤ n ^ 45
+ obtain ⟨bits, reps, measured, vertices⟩ :=
+ selectedTerminalBranch_rows (Y) scanM Fin.castSucc (Function.Embedding.refl _) 0 10 sl rfl 0 rfl
+ (fun _ => 0) 0 bitFit (parsers) ord names.symm shape B.recordLimit pub q lo before layout
+ clock headerFit below agree counter grammar (visit₀) x.arcs x.choices ok
+ (fun j m h y r run => (R.2 x.arcs j m h).elim fun q =>
+ q.report_cost (VertexImage.template_contains code pub) hn₀ degree labels width (depth _) y
+ r run)
+ exact ⟨before,_,_,reps,bits,vertices,measured⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRatedTerminalClock.lean b/lean/OAI/Computability/VPVNP/PairVertexRatedTerminalClock.lean
new file mode 100644
index 0000000000..ae86c4f666
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRatedTerminalClock.lean
@@ -0,0 +1,32 @@
+import OAI.Computability.VPVNP.LiveCompressedPairSourceCaps
+import OAI.Computability.VPVNP.LiveCompressedPairHandoff
+import OAI.Computability.VPVNP.LiveProgramCompressedPairPaths
+
+/-! # The reduced terminal cutoff covers the selected physical ordinal -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram.CompressedPair
+
+open BurstRAM LiveStageLink PairStages.Group.CompressedPaths
+
+set_option exponentiation.threshold 10000 in
+/-- The inner terminal dispatcher and the enclosing live-pair dispatcher
+both consume ticks before entering the vertex phase. -/
+theorem terminal_ordinal_room (G : PairStages.Group) {n : ℕ} (hn : 128 ≤ n)
+ (clock : G.clock = n ^ 10000) : n ^ 9999 ≤ clockAt (publicWords G) (fuel G) Stage.terminal := by
+ have outer : n ^ 9999 + 107 ≤ fuel G := private_clock_room G hn clock
+ have dispatch : (LiveStageLink.dispatchEvents (PairTag.address (publicWords G))
+ Stage.terminal).length ≤ 22 := by
+ simp only [LiveStageLink.dispatchEvents,List.length_cons,List.length_replicate]
+ decide
+ unfold clockAt
+ omega
+
+end LiveProgram.CompressedPair
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexReturns.lean b/lean/OAI/Computability/VPVNP/PairVertexReturns.lean
new file mode 100644
index 0000000000..bdf6fc3e42
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexReturns.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.PairVertexDispatch
+
+/-! # Exact consumption of the final vertex call through the histogram flush -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM DFS PrimedCounter.GuessWord
+open scoped Fin.CommRing
+open private guessed_addFuel from OAI.Computability.VPVNP.PairSimulationDFSDecode
+open private execute_component nextConfig word componentEvents from OAI.Computability.VPVNP.PairSimulationCounters
+
+variable {W p r k : ℕ} {M : Machine W p r k}
+
+private theorem returns_after {c d : Config W p r} {m m' : Memory W} {bits tail : List Bool}
+ {cost : ℕ} {extend : Report W → Report W}
+ (step : ∀ fuel, execute M.program (fuel+cost) c m bits = (execute M.program fuel d m' tail).map extend) :
+ Returns M c m bits ↔ Returns M d m' tail := by
+ constructor
+ · rintro ⟨f,rep,h⟩
+ obtain ⟨path,correct,consumed⟩ := execute_iff.mp h
+ have big := execute_iff.mpr ⟨guessed_addFuel path cost,correct,consumed⟩
+ rw [Nat.add_comm cost f,step] at big
+ obtain ⟨out,run,_⟩ := Option.map_eq_some_iff.mp big
+ exact ⟨f,out,run⟩
+ · rintro ⟨f,out,run⟩
+ exact ⟨f+cost,extend out,by rw [step,run]; rfl⟩
+
+/-- The word-arithmetic counter loop terminates even when an arbitrary
+incoming private address wraps at the word boundary. The public count is
+one word, and the loop advances the external cursor exactly that many times. -/
+theorem counters_terminal {pc : Fin 7 → Fin p} {reg : Fin 6 ↪ Fin r} {done : Fin p}
+ (linked : Counters.Linked M pc reg done)
+ (finish : ∀ (c : Config W p r) m bits, c.pc = done → (Returns M c m bits ↔ bits = []))
+ (n : ℕ) (fit : n < 2^W) (c : Config W p r) (m : Memory W) (bits : List Bool)
+ (here : c.pc = pc 0) (unit : c.reg (reg 3) = 1) (endWord : c.reg (reg 1) = c.reg (reg 0) + (n : Word W)) :
+ Returns M c m bits ↔ bits = [] := by
+ induction n generalizing c m with
+ | zero =>
+ have stop : c.reg (reg 0) = c.reg (reg 1) := by simpa using endWord.symm
+ let out := {c with pc := done}
+ have hs : M.program.step c = .localStep out := by
+ change (M.code c.pc).run _ _ = _
+ rw [here,linked]
+ change CallAction.localStep {c with pc := if c.reg (reg 0)=c.reg (reg 1) then done else _} = _
+ rw [ite_eq_left stop]
+ exact (returns_after (cost := 1) (extend := Report.prepend .tick)
+ (fun f => by simp only [execute,hs])).trans (finish out m bits rfl)
+ | succ n ih =>
+ have diff : c.reg (reg 0) ≠ c.reg (reg 1) := by
+ intro eqn
+ have z : ((n+1 : ℕ) : Word W) = 0 := (add_eq_left.mp (endWord.symm.trans eqn.symm))
+ have nat := congrArg Fin.val z
+ change (n+1) % 2^W = 0 at nat
+ rw [Nat.mod_eq_of_lt fit] at nat
+ omega
+ let src := (c.reg (reg 2)).val
+ let dst := (c.reg (reg 0)).val
+ have srcEq : c.reg (reg 2) = word W src := by simp [word,src]
+ have dstEq : c.reg (reg 0) = word W dst := by simp [word,dst]
+ let mid := nextConfig c pc reg src dst (m dst)
+ let mm := writeMemory m (word W dst) (m dst+c.privateMem (word W src))
+ have step := returns_after (fun f => execute_component linked c here src dst
+ (c.reg (reg 0)).isLt srcEq dstEq unit diff f m bits)
+ have endMid : mid.reg (reg 1) = mid.reg (reg 0) + (n : Word W) := by
+ simp [mid,nextConfig,word,Config.put,dst,endWord,add_comm,add_assoc]
+ exact step.trans (ih (by omega) mid mm rfl (by simpa [mid,nextConfig,Config.put] using unit) endMid)
+
+variable {S : Part → Segment} {A : Placement S p r} {N : Machine W p r 11}
+
+/-- Flush terminality uses no validity premise for the incoming private
+memory. This supplies the arbitrary-configuration terminal case of the
+DFS equivalence, as well as the case of a successfully prepared histogram. -/
+theorem flush_terminal (linked : Contains A N)
+ (finish : ∀ (c : Config W p r) m bits, c.pc = A.entry .finish → (Returns N c m bits ↔ bits = []))
+ (c : Config W p r) (m : Memory W) (bits : List Bool) (hc : c.pc = A.core (.histBase 0)) :
+ Returns N c m bits ↔ bits = [] := by
+ obtain ⟨mid,geom,hpc,_,_,_,_⟩ := geometry_run (histBase_linked A N linked)
+ (A.counter.injective.ne (by decide)) c hc
+ let pc := A.flushStartPC
+ let reg := A.counter
+ have step (i : Fin 7) (d : Config W p r) (hd : d.pc = pc i) :
+ N.program.step d = (flushStartRows pc reg (A.flushPC 0) i).run N.publicData d := by
+ change (N.code d.pc).run _ _ = _
+ rw [hd,flushStart_linked A N linked]
+ let c₁ := mid.put (pc 1) (reg 0) (N.publicData 4)
+ let c₂ := c₁.put (pc 2) (reg 4) (N.publicData 5)
+ let c₃ := c₂.put (pc 3) (reg 0) (c₂.reg (reg 0)+c₂.reg (reg 4))
+ let c₄ := c₃.put (pc 4) (reg 1) (N.publicData 9)
+ let c₅ := c₄.put (pc 5) (reg 1) (c₄.reg (reg 0)+c₄.reg (reg 1))
+ let c₆ := c₅.put (pc 6) (reg 2) (c₅.privateMem (c₅.reg (reg 2)))
+ let start := c₆.put (A.flushPC 0) (reg 3) 1
+ have init : Prefix N mid (List.replicate 7 .tick) start :=
+ .tick (step 0 mid hpc) (.tick (step 1 c₁ rfl) (.tick (step 2 c₂ rfl) (.tick (step 3 c₃ rfl)
+ (.tick (step 4 c₄ rfl) (.tick (step 5 c₅ rfl) (.tick (step 6 c₆ rfl) (.nil _)))))))
+ have pre : Prefix N c (List.replicate 10 .tick) start := geom.append init
+ apply (returns_after (fun fuel => pre.execute fuel m bits)).trans
+ apply counters_terminal (core_linked A N linked).2.2 finish (N.publicData 9).val (N.publicData 9).isLt start m bits rfl
+ · change start.reg (reg 3) = 1
+ simp [start,Config.put]
+ · change start.reg (reg 1) = start.reg (reg 0) + _
+ simp [start,c₆,c₅,c₄,c₃,c₂,c₁,Config.put]
+
+/-- The assembled per-site control returns exactly on those streams
+accepted by the ordered role visits, with the empty suffix at the flush. -/
+theorem site_returns {endAddr : ℕ} (linked : Contains A N) (G offset hist : Word W) (m : Memory W)
+ (domain : Word W → Scratch W endAddr → Prop)
+ (geometry : ∀ node saved, domain node saved → ResidentGeometry saved G offset hist)
+ (handlers : NodeDispatch.Role → HookParser W endAddr)
+ (exactRole : ∀ role, (handlers role).ExactOn
+ (fun node saved => domain node saved ∧ NodeDispatch.role (m (offset+node).val) = role)
+ N (A.entry (rolePart role)) (A.dfsPC 3) A.dfs m)
+ (finish : ∀ (c : Config W p r) m bits, c.pc = A.entry .finish → (Returns N c m bits ↔ bits = []))
+ {pending nodes : List (Word W)} {events : List (Event W)} (visits : Visits m endAddr pending nodes events)
+ (c : Config W p r) (here : c.pc = A.dfsPC 0) (top : ℕ) (stack : Represents c.privateMem top pending)
+ (length : top+pending.length = endAddr) (sp : c.reg (A.dfs 5) = (top : Word W))
+ (endReg : c.reg (A.dfs 6) = (endAddr : Word W)) (one : c.reg (A.dfs 3) = 1) (bits : List Bool)
+ (valid : (dispatcher handlers m offset).ValidAlong domain nodes (scratch endAddr c.privateMem) bits) :
+ Returns N c m bits ↔ ∃ out, (dispatcher handlers m offset).decode nodes (scratch endAddr c.privateMem) bits = some (out,[]) := by
+ obtain ⟨dfs,copy,_⟩ := core_linked A N linked
+ exact returns_iff_decode_on dfs copy visits _ (dispatch_exactOn linked G offset hist m domain geometry handlers exactRole)
+ (fun cfg bs h => flush_terminal linked finish cfg m bs h) c here top stack length sp endReg one bits valid
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRoleDomains.lean b/lean/OAI/Computability/VPVNP/PairVertexRoleDomains.lean
new file mode 100644
index 0000000000..aec6c018f7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRoleDomains.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.PairSelectedPacketFormat
+import OAI.Computability.VPVNP.PairVertexFrameData
+
+/-!
+# Physical domains at the three vertex entries
+
+A popped packet supplies its own independent half assignment. Its address
+and the published role word identify the original cursor or the selected
+output occurrence. The latter carries the current histogram headroom into
+the shrinking or refresh reader.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open BurstRAM DFS TreeDecode NodeArguments Compression TraversalRows TraversalRoles CompressorRecords LocalHistory
+
+open scoped Fin.CommRing
+
+variable {k K : Type*} [Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f}
+variable {w endAddr a g : ℕ} (X : State a g) (cap base : ℕ)
+ (passes : List (SelectedLevel B f hf)) (R : LeafArena.Regions) (data : Fin 10 → Word w)
+ (offset : Word w) (vals : LeafSourceLoad.Static 34 → Word w)
+ (hist : Scratch w endAddr → B.Entry → ℕ) (nodeCap limit : ℕ)
+
+local notation "leaf₀" => (TaggedLayer.mk (leafLayer (siteOrder X)) TraversalRoles.Role.cursor)
+local notation "tags₀" => (leaf₀) :: ShrinkRoleDirectory.outputTags passes
+local notation "stable₀" => VertexFrameData R data offset vals
+
+/-- The literal output packet of a selected chronological row. -/
+noncomputable def outputPacket (x : ShrinkRoleDirectory.Site passes)
+ (z : (passes[x.1].pass.step.term passes[x.1].term).output.Half x.2) : Packet :=
+ ⟨ShrinkRoleDirectory.address cap base (leaf₀) passes x,
+ pullBits (passes[x.1].pass.output_eq passes[x.1].term) (packed (passes[x.1].pass.next passes[x.1].term)) x.2 z⟩
+
+/-- The saved frame, local counter credit and independently stored half fields
+at a selected output row. -/
+structure Output (x : ShrinkRoleDirectory.Site passes) (s : Scratch w endAddr) : Prop where
+ frame : stable₀ s
+ credit : ∀ l, hist s l + nodeCap ≤ limit
+ packet : ∃ z, (outputPacket X cap base passes x z).Fits R.arguments w endAddr ∧
+ (outputPacket X cap base passes x z).Stored R.arguments s
+
+/-- A cursor address with its actual original half assignment and physical
+private-memory representation. -/
+structure Leaf (node : Word w) (s : Scratch w endAddr) : Prop where
+ within : node.val < R.nodes
+ frame : stable₀ s
+ packet : ∃ (v : X.network.Site) (z : X.network.Half v),
+ let q := Packet.mk (sitePointers cap base (siteOrder X) v).1 (packed X v z)
+ node.val = q.node ∧ q.Fits R.arguments w endAddr ∧ q.Stored R.arguments s
+
+local notation "out₀" => Output X cap base passes R data offset vals hist nodeCap limit
+
+/-- The input domain of each native role at this physical vertex. -/
+def Domain : NodeDispatch.Role → Word w → Scratch w endAddr → Prop
+ | .leaf => Leaf X cap base R data offset vals
+ | .shrink => ShrinkRoleDirectory.Domain cap base (leaf₀) passes fun x s => out₀ x.val s
+ | .refresh => fun node s => ∃ x : ShrinkRoleDirectory.Site passes,
+ tagLevel B f hf passes[x.1] = .refresh ∧ node.val = ShrinkRoleDirectory.address cap base (leaf₀) passes x ∧ out₀ x s
+
+private theorem output_role (v : SelectedLevel B f hf) :
+ tagLevel B f hf v = .shrink ∨ tagLevel B f hf v = .refresh := by
+ rcases v with ⟨_,_,_,_,_,_,origin,_,_⟩
+ cases origin <;> simp [tagLevel,ofOrigin]
+
+/-- Reading the physical tag at the popped address always produces its
+corresponding typed domain, including on arbitrary later choice tapes. -/
+theorem domainsReady (m : Memory w)
+ (tags : TraversalRoles.Reads w m offset.val cap base (tags₀))
+ (codes : 2 < 2^w) (fit : offset.val+base+tagWords cap (tags₀) ≤ 2^w)
+ (nodes : base+tagWords cap (tags₀) ≤ R.nodes)
+ (q : Packet) (s : Scratch w endAddr) (frame : stable₀ s)
+ (typed : PacketFormat X cap base (leaf₀) passes q)
+ (fits : q.Fits R.arguments w endAddr) (stored : q.Stored R.arguments s)
+ (credit : ∀ l, hist s l + nodeCap ≤ limit) :
+ Domain X cap base passes R data offset vals hist nodeCap limit
+ (NodeDispatch.role (m (offset+(q.node : Word w)).val)) (q.node : Word w) s := by
+ have len : (tags₀).length = passes.length+1 := by simp [ShrinkRoleDirectory.outputTags]
+ have bound := typed.node_lt (by rfl)
+ rw [← len,layerBase,List.take_length] at bound
+ change q.node < base + tagWords cap (tags₀) at bound
+ have room : offset.val+q.node < 2^w := by omega
+ have nodeFit : (q.node : Word w).val = q.node := Nat.mod_eq_of_lt (by omega)
+ have offsetWord : (offset.val : Word w) = offset := Fin.ext (Nat.mod_eq_of_lt offset.isLt)
+ rcases typed.cases with ⟨v,z,eqn⟩ | ⟨x,z,eqn⟩
+ · subst q
+ have tag := tags.1 ((siteOrder X).entries.symm v)
+ change m (offset.val + (sitePointers cap base (siteOrder X) v).1) = 0 at tag
+ have role : NodeDispatch.role (m (offset+(((sitePointers cap base (siteOrder X) v).1 : ℕ) : Word w)).val) = .leaf := by
+ rw [← offsetWord,probe_word_add _ _ m room,tag]; rfl
+ rw [role]
+ exact ⟨by rw [nodeFit]; exact bound.trans_le nodes,frame,v,z,nodeFit,fits,stored⟩
+ · subst q
+ have tag := ShrinkRoleDirectory.dispatch_at_site cap base (leaf₀) passes tags codes fit
+ ((ShrinkRoleDirectory.address cap base (leaf₀) passes x : ℕ) : Word w) x nodeFit
+ rw [offsetWord] at tag
+ rw [tag]
+ have ready : out₀ x s := ⟨frame,credit,z,fits,stored⟩
+ rcases output_role passes[x.1] with shrink | refresh
+ · rw [shrink]; exact ⟨⟨x,shrink⟩,nodeFit,ready⟩
+ · rw [refresh]; exact ⟨x,refresh,nodeFit,ready⟩
+
+end PairSimulation.VertexImage.RoleDomains
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRoleHandlers.lean b/lean/OAI/Computability/VPVNP/PairVertexRoleHandlers.lean
new file mode 100644
index 0000000000..1bb8f9a39c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRoleHandlers.lean
@@ -0,0 +1,25 @@
+import OAI.Computability.VPVNP.PairVertexDispatch
+
+/-! # The three readers reached through the stored native vertex tag -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open DFS
+
+/-- Use the parser at the selected native entry, in the same role order as
+the decoder of the published tag word. -/
+def handlers {w n : ℕ} (leaf shrink refresh : HookParser w n) :
+ NodeDispatch.Role → HookParser w n
+ | .leaf => leaf
+ | .shrink => shrink
+ | .refresh => refresh
+
+end PairSimulation.VertexImage.RoleDomains
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRoleNativeLeaf.lean b/lean/OAI/Computability/VPVNP/PairVertexRoleNativeLeaf.lean
new file mode 100644
index 0000000000..73f1de71f3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRoleNativeLeaf.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.PairVertexRoleDomains
+import OAI.Computability.VPVNP.PairVertexCursorDomain
+import OAI.Computability.VPVNP.PairSimulationLeafSegment
+
+/-! # Exact native cursor execution on the selected vertex domain -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open BurstRAM BurstRAM.PrivateRAM DFS NodeArguments LocalHistory TreeDecode LeafStartup NativeFrame CursorNetwork
+open scoped Fin.CommRing
+
+variable {w endAddr : ℕ} {L : PrimedInputRAM.Lengths} {n a H count : ℕ}
+ {Q : PrimedInputRAM.Layout L n a H w} (D : PrimedCounter.Data Q count)
+ {b l e degree pad : ℕ} (hD : 1 < b+l) (hd : 2+pad = 2^degree)
+
+local notation "X₀" => LeafArguments.state hD hd (2^e) w
+local notation "vals₀" => LeafVisit.cacheWords D (b+l) e
+
+/-- A cursor packet in the selected domain supplies the exact private inputs
+of the leaf verification table, including its geometry and public operands. -/
+theorem Leaf.toRole {R : LeafArena.Regions} {data : Fin 10 → Word w} {offset node : Word w}
+ {cap base : ℕ} {s : Scratch w endAddr} (address : base = ((LeafRole.addressFields data) .base).val)
+ (leaf : Leaf (X₀) cap base R data offset (vals₀) node s) :
+ LeafRole.Domain (e := e) data D hD hd R cap (frameBase R) node s := by
+ obtain ⟨u,z,atNode,fits,stored⟩ := leaf.packet
+ let packet := Packet.mk (TraversalRows.sitePointers cap base (siteOrder (X₀)) u).1 (packed (X₀) u z)
+ change node.val = packet.node at atNode
+ have same : (packet.node : Word w) = node := by
+ rw [← atNode]; exact Fin.ext (Nat.mod_eq_of_lt node.isLt)
+ have typed : ∃ v h, packet = ⟨(TraversalRows.sitePointers cap ((LeafRole.addressFields data) .base).val
+ (siteOrder (X₀)) v).1, packed (X₀) v h⟩ := ⟨u,z,by simp only [packet,← address]⟩
+ have verified := LeafRole.domain_of_packet (e := e) D hD hd typed (atNode ▸ leaf.within)
+ (atNode ▸ node.isLt) fits stored leaf.frame
+ simpa only [same] using verified
+
+/-- Restrict a proved native parser to its actual physical input domain. -/
+theorem restrict {p r k : ℕ} {M : Machine w p r k} {pc ret : Fin p} {regs : Fin 9 ↪ Fin r}
+ {m : Memory w} {domain sub : Word w → Scratch w endAddr → Prop} {parser : HookParser w endAddr}
+ (exactRole : parser.ExactOn domain M pc ret regs m) (ready : ∀ node s, sub node s → domain node s) :
+ parser.ExactOn sub M pc ret regs m where
+ success node s h := exactRole.success node s (ready node s h)
+ reject node bits cfg top pending h := exactRole.reject node bits cfg top pending (ready _ _ h)
+
+variable [NeZero (b+l)] {geometry rootFields shrink refresh : Segment} {p r : ℕ}
+ (V : Placement (segments geometry rootFields LeafRole.segment shrink refresh) p r)
+ (M : Machine w p r 11) (budget : ProcessorBudget n (b+l) e w)
+ (m : Memory w) (header offset : Word w) (arity cap clock base : ℕ)
+
+local notation "regions₀" => fromHeader arity M.publicData header m
+local notation "data₀" => leafWords arity M.publicData header offset m
+
+/-- Success and rejection at the physical cursor entry, for arbitrary
+nomination tapes at any selected first-layer packet. -/
+theorem nativeLeaf (fit : (regions₀).stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ (link : Contains V M) (address : base = ((LeafRole.addressFields (data₀)) .base).val)
+ (stride : (m (header+15).val).val = cap+2) (rb : (m (header+18).val).val = 2^b)
+ (rl : (m (header+19).val).val = 2^l)
+ (span : (m (header+20).val).val = LiveAuxiliaryHeaders.span L D.hist.length)
+ (shadowFit : (M.publicData 3).val + (m (header+20).val).val ≤ 2^w)
+ (headers : ∀ i < (m (header+20).val).val, (m ((M.publicData 3).val+i)).val = (D.initial i).val)
+ (size : (M.publicData 6).val = n)
+ (time : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w),
+ steps 52 (auxiliary D budget.tags budget.capFits v buf) ≤ clock)
+ (room : ∀ (v : Position (b+l)) (buf : Buffers (b+l) (2^e) w) j,
+ (auxiliaryBank D budget.tags budget.capFits v buf j).length + clock ≤ n^40) :
+ (LeafRole.parser (endAddr := n) (data₀) D budget (regions₀) fit m clock).ExactOn
+ (Leaf (X₀) cap base (regions₀) (data₀) offset (vals₀)) M (V.entry .leaf) (V.dfsPC 3) V.dfs m :=
+ restrict (LeafRole.site_exact V M D hD hd budget m header offset arity cap clock fit link stride rb rl
+ span shadowFit headers size time room) fun _ _ h => Leaf.toRole D hD hd address h
+
+end PairSimulation.VertexImage.RoleDomains
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRoleNativeRefresh.lean b/lean/OAI/Computability/VPVNP/PairVertexRoleNativeRefresh.lean
new file mode 100644
index 0000000000..d84e39713f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRoleNativeRefresh.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedDomain
+import OAI.Computability.VPVNP.PairRefreshSelectedPublished
+import OAI.Computability.VPVNP.PairVertexRoleNativeLeaf
+
+/-! # Exact native refresh execution on the selected vertex domain -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace LocalHistory TraversalRows TraversalRoles
+open DFS TerminalProgram RefreshHook.SelectedRows
+open LiveProgram LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary
+open scoped Fin.CommRing
+
+variable {k : Type} {K : Type*} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f) {lanes : ℕ}
+
+section Installed
+
+variable (blocks : ℕ) (budget : blocks * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (branch : (B.execute f hf blocks budget X).Choices) (n hist w start positions : ℕ)
+local notation "passes" => executeLevels B f hf blocks budget X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "tags" => TraversalRoles.selected B f hf blocks budget X branch
+local notation "first" => endAddress (BlockProgram.layout B start positions blocks)
+local notation "rows" => tagWords B.recordLimit tags
+local notation "width" => State.totalWidth (StateExecution.finalState (B.execute f hf blocks budget X) branch)
+local notation "region" => TerminalLayout.privateRegions (slotDegree S) n (first + rows) hist
+
+/-- Every selected refresh packet is accepted or rejected by the installed
+reader exactly as its selected chronological row specifies. -/
+theorem nativeRefresh_installed (room : Rooms n hist w start positions blocks (leaf₀) passes)
+ (order : B.Entry ≃ Fin hist) (m : Memory w)
+ (fit : layerBase B.recordLimit first tags ((passes).length + 1) ≤ 2 ^ w)
+ (constants : Constants) (p q : ℕ) {pcs regs : ℕ}
+ (V : Placement (TerminalProgram.nativeSegments B constants p q order) pcs regs)
+ (M : Machine w pcs regs 11) (contains : Contains V M)
+ (published : ∀ x : RefreshHook.SelectedRows.Row passes, (rowSite n hist w start positions blocks width (leaf₀) passes room x).Published
+ (RefreshBlockPlan.order B) (PortRefresh.LevelRecipe.Shape.stride (RefreshBlockPlan.shape B)) M.publicData m)
+ {data : Fin 10 → Word w} {vals : LeafSourceLoad.Static 34 → Word w}
+ {counts : Scratch w n → B.Entry → ℕ} {nodeCap limit : ℕ} :
+ (RefreshHook.SelectedRows.parser n hist w start positions blocks width (leaf₀) passes room order M.publicData m).ExactOn
+ (Domain X B.recordLimit first passes region data ((rows + width : ℕ) : Word w) vals counts nodeCap limit .refresh)
+ M (V.entry .refresh) (V.dfsPC 3) V.dfs m :=
+ restrict (RefreshHook.SelectedRows.exactOn n hist w start positions blocks width (leaf₀) passes room
+ order m fit constants p q V M contains published)
+ fun _ _ h => prepared_of_domain B f hf blocks budget X branch n hist w start positions room h
+
+end Installed
+
+section Physical
+
+variable {n hist : ℕ} (G : LiveProgram.PairStages.Group) (workspace : Word G.w) (positions blocks : ℕ)
+ (budget : blocks * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (branch : (B.execute f hf blocks budget X).Choices)
+local notation "layout" => BlockProgram.layout B workspace.val positions blocks
+local notation "passes" => executeLevels B f hf blocks budget X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "tags" => TraversalRoles.selected B f hf blocks budget X branch
+local notation "rows" => tagWords B.recordLimit tags
+local notation "width" => State.totalWidth (StateExecution.finalState (B.execute f hf blocks budget X) branch)
+local notation "region" => TerminalLayout.privateRegions (slotDegree S) n (endAddress layout + rows) hist
+
+/-- The current linked vertex memory supplies all row publications from
+the physical entry and the selected calendar history. -/
+theorem nativeRefresh {tab : Fin (layout).shape.tables} {baseBits laneBits ordinal : ℕ}
+ {calendar vertex current : Memory G.w} {wireBits : Fin width → Bool}
+ (entry : VertexEntry B f hf blocks budget X branch layout tab baseBits laneBits (terminalOperands G)
+ calendar vertex wireBits)
+ (history : SelectedPayloadHistory.Past B f hf layout (CompiledResident.payload B f hf workspace positions blocks n)
+ passes calendar)
+ (packed : VertexPacked G layout B.recordLimit tags width) (frame : LinkedVertexMemory G vertex ordinal current)
+ (room : Rooms n hist G.w workspace.val positions blocks (leaf₀) passes)
+ (p q : ℕ) (order : B.Entry ≃ Fin hist) {data : Fin 10 → Word G.w}
+ {vals : LeafSourceLoad.Static 34 → Word G.w} {counts : Scratch G.w n → B.Entry → ℕ} {nodeCap limit : ℕ} :
+ let segments := TerminalProgram.nativeSegments B G.constants p q order
+ let V := placement segments
+ let M := (template segments).instantiate G.w (terminalOperands G)
+ (RefreshHook.SelectedRows.parser n hist G.w workspace.val positions blocks width (leaf₀) passes room order
+ (terminalOperands G) current).ExactOn
+ (Domain X B.recordLimit (endAddress layout) passes region data ((rows + width : ℕ) : Word G.w)
+ vals counts nodeCap limit .refresh) M (V.entry .refresh) (V.dfsPC 3) V.dfs current :=
+ restrict (exact_at_site B f hf G workspace positions blocks budget X branch entry history packed frame room p q order)
+ fun _ _ h => prepared_of_domain B f hf blocks budget X branch n hist G.w workspace.val positions room h
+
+end Physical
+
+end PairSimulation.VertexImage.RoleDomains
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRoleNativeShrink.lean b/lean/OAI/Computability/VPVNP/PairVertexRoleNativeShrink.lean
new file mode 100644
index 0000000000..146abcc565
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRoleNativeShrink.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.PairShrinkSelectedParent
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalReader
+
+/-! # Native shrinking reader on every selected chronological output row -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open BurstRAM PrivateRAM DFS NodeArguments TreeDecode Compression CompressorRecords LocalHistory
+open TraversalRows TraversalRoles ShrinkRoleDirectory
+
+variable {k : Type} {K : Type*} [Field k] [CommRing K] {S : BlockSchedule k} {B : S.Templates}
+ {f : B.Entry → K} {hf : B.IsSolution f}
+variable {w n t a g : ℕ} (X : State a g) (cap base : ℕ)
+ (passes : List (SelectedLevel B f hf)) (R : LeafArena.Regions) (data : Fin 10 → Word w)
+ (offset : Word w) (vals : LeafSourceLoad.Static 34 → Word w)
+ (hist : Scratch w n → B.Entry → ℕ) (nodeCap limit : ℕ)
+
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "tags₀" => (leaf₀) :: outputTags passes
+
+/-- The selected site's original kernel determines the types of its native
+address, packed fields, row sources and matrix-job operands. -/
+abbrev SiteBank := (x : ShrinkSite passes) →
+ ShrinkRole.CanonicalSite B x.occurrence.i x.occurrence.state x.occurrence.selection x.occurrence.site w n t
+
+variable (sites : SiteBank (w := w) (n := n) (t := t) passes) (ord : B.Entry → Fin t)
+
+/-- Read the chronological parent address before running its concrete
+shrinking kernel with the recovered independent output half. -/
+noncomputable def shrinkHandler : HookParser w n :=
+ ShrinkRoleDirectory.parser cap base (leaf₀) passes fun x => ShrinkRole.canonicalParent (sites x) ord f hf
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence ShrinkRole.canonicalFamily ShrinkRole.canonicalActions
+ ShrinkRole.parentParser
+
+set_option maxHeartbeats 1500000 in
+/-- The exact native family at each stored parent supplies the complete
+selected shrinking reader on both accepting and rejecting tapes. -/
+theorem nativeShrink {p r : ℕ} (M : Machine w p r 11) (visit ret : Fin p)
+ (dfs : Fin 9 ↪ Fin r) (m : Memory w) (positive : 0 < w)
+ (fit : layerBase cap base (tags₀) (passes.length+1) ≤ 2^w)
+ (arena : ∀ x, (TerminalLayout.privateRegions (slotDegree S) n (sites x).rowEnd
+ (Fintype.card B.Entry)).arguments = R.arguments)
+ (actual : ∀ (x : ShrinkSite passes) (z : x.occurrence.nextState.network.Half x.occurrence.site), (ShrinkRole.canonicalFamily (sites x) ord f hf z).ExactOn
+ (fun node s => node.val = ShrinkRoleDirectory.address cap base (leaf₀) passes x.val ∧
+ Parent X cap base passes R data offset vals hist nodeCap limit x z s) M visit ret dfs m) :
+ (shrinkHandler X cap base passes sites ord).ExactOn
+ (Domain X cap base passes R data offset vals hist nodeCap limit .shrink) M visit ret dfs m := by
+ apply ShrinkRoleDirectory.exactOn cap base (leaf₀) passes M visit ret dfs m _ _ fit
+ intro x
+ dsimp only [ShrinkRole.canonicalParent]
+ rw [arena x]
+ exact parent_exact X cap base passes R data offset vals hist nodeCap limit x M visit ret dfs m
+ positive _ (actual x)
+
+end PairSimulation.VertexImage.RoleDomains
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRootEntry.lean b/lean/OAI/Computability/VPVNP/PairVertexRootEntry.lean
new file mode 100644
index 0000000000..da44aab1ea
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRootEntry.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.PairTerminalVertexPackedHeaders
+import OAI.Computability.VPVNP.PairTraversalRootAddress
+import OAI.Computability.VPVNP.PairVertexRootPacket
+import OAI.Computability.VPVNP.PairVertexRootInputs
+
+/-!
+# The root argument at a selected physical vertex
+
+The current ordinal reads the row of the selected tree in the final layer.
+All addresses and counts used by the bootstrap and gather come from the
+physical terminal header. Earlier vertex calls preserve those header fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM Compression CompressorRecords DescriptorSpace TraversalRows TraversalRoles
+open LocalHistory LiveProgram PairStages.Group.Auxiliary
+open scoped Fin.CommRing
+
+variable {G : PairStages.Group} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+ {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f} {l T : ℕ} {hT : T*S.laneBits ≤ l}
+ {X : State (S.degreeExponent 0) l} {z : (B.execute f hf T hT X).Choices}
+
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "ls" => selectedLayers B f hf T hT X z
+local notation "tags" => selected B f hf T hT X z
+local notation "size" => words B.recordLimit (ls)
+local notation "pub" => terminalOperands G
+local notation "hdr" => vertexHeader G
+local notation "degree" => slotDegree S
+
+variable {D : DescriptorSpace.Layout} {tab : Fin D.shape.tables} {baseBits laneBits : ℕ}
+ {calendar reference m : Memory G.w} {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool} {ord : ℕ}
+ (P : VertexPacked G D B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (entry : VertexEntry B f hf T hT X z D tab baseBits laneBits (terminalOperands G) calendar reference bits)
+ (later : LinkedVertexMemory G reference ord m)
+
+attribute [local irreducible] BlockSchedule.Templates.execute TerminalBootstrap.fromState
+
+local notation "R" => NativeFrame.fromHeader degree pub hdr m
+local notation "L" => TerminalRootGather.Layout.ofHeader degree pub hdr
+local notation "data" => TerminalBootstrap.fromState D (List.dropLast (ls)) B.recordLimit baseBits laneBits (Y) tab
+
+private theorem cast_offset {w : ℕ} (H : Word w) (room : H.val+32 ≤ 2^w) (j : Fin 21) :
+ (H+(j.val : Word w)).val = H.val+j.val := by
+ have hj := j.isLt
+ rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j.val < 2^w),Nat.mod_eq_of_lt (by omega)]
+
+include P entry in
+theorem VertexEntry.packedField (j : Fin 21) (lo : 0 < j.val) (t : j.val ≠ 12) (r : j.val ≠ 14) :
+ reference (hdr + (j.val : Word G.w)).val =
+ TerminalBootstrap.values D (ls).dropLast.length data B.recordLimit pub calendar j := by
+ rw [cast_offset _ P.room j]; exact entry.headers j lo t r
+
+include P entry later in
+theorem VertexEntry.selected_regions (n labels : ℕ) (hn : (pub 6).val=n) (hl : (pub 9).val=labels) :
+ R = TerminalLayout.privateRegions degree n (endAddress D+size) labels := by
+ have eqn := TerminalBootstrap.selected_rowWords B f hf T hT X z D baseBits laneBits tab
+ have row := entry.packedField P 4 (by decide) (by decide) (by decide)
+ have cell := entry.packedField P 5 (by decide) (by decide) (by decide)
+ change reference (hdr+4).val = (endAddress D : Word G.w) at row
+ change reference (hdr+5).val = ((data).rowWords B.recordLimit : Word G.w) at cell
+ have nr := P.header later 4 (by decide) (by decide)
+ have nc := P.header later 5 (by decide) (by decide)
+ change m (hdr+4).val = reference (hdr+4).val at nr
+ change m (hdr+5).val = reference (hdr+5).val at nc
+ have arena := P.arena
+ have room := P.room
+ have hs : tagWords B.recordLimit tags = size :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ rw [hs] at arena
+ rw [NativeFrame.fromHeader,nr,nc,row,cell,eqn,Fin.val_natCast,Fin.val_natCast,
+ Nat.mod_eq_of_lt (by omega : endAddress D < 2^G.w),Nat.mod_eq_of_lt (by omega : size < 2^G.w),hn,hl]
+ exact NativeFrame.regions_eq ..
+
+open private positiveEnd from OAI.Computability.VPVNP.PairTerminalLayout
+
+include P entry later in
+theorem VertexEntry.rootInputs (n labels : ℕ) (hn : (pub 6).val=n) (hl : (pub 9).val=labels)
+ (width : (Y).maxWireWidth ≤ n)
+ (stack : (TerminalLayout.privateRegions degree n (endAddress D+size) labels).stackBase < 2^G.w)
+ (v : (Y).network.Site) (state : Word G.w) (index : state.val = ((siteOrder (Y)).entries.symm v).val)
+ (level : Fin D.levels) (levelEq : level.val = (ls).dropLast.length)
+ (capacity : TerminalPrefix.arcCount (Y) ≤ slotCapacity D) (cells : TerminalPrefix.arcCount (Y) ≤ tableWords D)
+ (rawRows : TerminalGatherGeometry.Rows (Y) (L state reference) reference) :
+ RootInputs (Y) v degree pub hdr state m (fun j => bits (Fin.cast (TerminalPrefix.width_sum (Y)) j)) := by
+ let actual := fun j => bits (Fin.cast (TerminalPrefix.width_sum (Y)) j)
+ have reg := entry.selected_regions P later n labels hn hl
+ have hs : tagWords B.recordLimit tags = size := congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ have arena := P.arena
+ have hr := P.room
+ rw [hs] at arena
+ have eqn := TerminalBootstrap.selected_rowWords B f hf T hT X z D baseBits laneBits tab
+ have ⟨sites,slots,incoming,widths,starts,wires⟩ := P.gatherValues (Y) (ls).dropLast level tab levelEq
+ baseBits laneBits reference calendar capacity cells (eqn.trans hs.symm) (by
+ intro j hj
+ simp only [List.mem_cons,List.not_mem_nil,or_false] at hj
+ exact entry.packedField P j (by omega) (by omega) (by omega))
+ have root := entry.gather_root v degree state index hr (by omega)
+ have regRef := entry.selected_regions P (VertexFrame.linked_initial _ _ _ _ 0 reference) n labels hn hl
+ have below : (L state reference).root < (NativeFrame.fromHeader degree pub hdr reference).nodes := by
+ rw [regRef,←root]
+ apply selectedTrees_below B f hf T hT X z _ v
+ cases selectedTrees B f hf T hT X z (endAddress D) v
+ exact List.mem_cons_self
+ have pos : 0 < (L state reference).root := by
+ rw [←root,selectedTrees_address,TraversalRows.address]
+ have hp := positiveEnd D
+ omega
+ have same := P.gatherLayout later degree state
+ have deg : 2^(S.degreeExponent 0) ≤ degree :=
+ (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ 0)).trans (le_max_right _ _)
+ have ws : (Y).maxWireWidth ≤ (L state reference).n := width.trans_eq hn.symm
+ have sizeBound := VertexRootPacket.length_le_stride (Y) (L state reference) v actual degree deg ws
+ have rootEnd := (NativeFrame.fromHeader degree pub hdr reference).node_before below
+ change (L state reference).dest + NodeArguments.frameStride degree (pub 6).val ≤ _ at rootEnd
+ have hist := (NativeFrame.fromHeader degree pub hdr reference).hist_before
+ have small : (NativeFrame.fromHeader degree pub hdr reference).cacheBase+38 < 2^G.w := regRef ▸ stack
+ have argumentFit : (L state reference).dest + (∑ dir : Bool, ∑ j, (Y).halfWidth v dir j) < 2^G.w := by
+ change (NodeArguments.packed (Y) v _).length ≤ _ at sizeBound
+ rw [NodeArguments.packed_length] at sizeBound
+ change (∑ dir : Bool, ∑ j, (Y).halfWidth v dir j) ≤ NodeArguments.frameStride degree (pub 6).val at sizeBound
+ omega
+ have dataBits (j : Fin (∑ j, TerminalPrefix.width (Y) j)) :
+ reference (endAddress D+tagWords B.recordLimit tags+j.val) = PrivateFields.bitValue G.w (actual j) := by
+ rw [hs]; exact entry.wires (Fin.cast (TerminalPrefix.width_sum (Y)) j)
+ obtain ⟨num,rows,bank,fits,_⟩ := P.gather later (Y) v degree state level tab actual rfl capacity cells
+ index sites slots incoming widths starts wires rawRows dataBits argumentFit
+ have active : state < m (hdr+7).val := by
+ change state.val < (L state m).sites
+ rw [num.sites,index]
+ exact ((siteOrder (Y)).entries.symm v).isLt
+ have headerFit : (hdr).val+31 < 2^G.w := by omega
+ refine ⟨active,same ▸ pos,?_,?_,num,rows,bank,fits,deg,width.trans_eq hn.symm,headerFit,?_,?_⟩
+ · rw [same,reg,←regRef]; exact below
+ · exact reg ▸ stack.le
+ · rw [same]
+ intro h hh
+ change h ∈ [(reference (hdr+10).val).val,(reference (hdr+9).val).val,(reference (hdr+11).val).val] at hh
+ rw [incoming,widths,starts] at hh
+ exact ((P.heads level tab _ capacity cells h hh).2).trans (by omega)
+ · rw [same]
+ change (reference (hdr+13).val).val + _ ≤ _
+ rw [wires,hs]
+ omega
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRootEntryRows.lean b/lean/OAI/Computability/VPVNP/PairVertexRootEntryRows.lean
new file mode 100644
index 0000000000..5a86511ad8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRootEntryRows.lean
@@ -0,0 +1,183 @@
+import OAI.Computability.VPVNP.PairTerminalPackedPrefix
+import OAI.Computability.VPVNP.PairVertexRootFields
+import OAI.Computability.VPVNP.PairSimulationPhysicalRootRows
+
+/-!
+# The three terminal gather arrays at vertex entry
+
+The final packed incidence bank supplies the inverse and width columns.
+The prefix worker fills the disjoint offset array. Header slots 9, 10 and
+11 point to these very arrays in the layout read by the root gather.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory TraversalRows
+open TerminalGatherGeometry TerminalLink
+open scoped Fin.CommRing
+
+set_option maxHeartbeats 1600000
+
+variable {w : ℕ}
+attribute [local irreducible] BlockSchedule.Templates.execute
+
+open private width_cells from OAI.Computability.VPVNP.PairTerminalPrefix
+
+/-- Recover the gather rows in any handoff memory that retains the final
+incidence columns and the freshly computed start offsets. -/
+theorem gather_rows_of_columns {a g : ℕ} (Y : State a g) (D : Layout) (last : Fin D.levels)
+ (tab : Fin D.shape.tables) (L : TerminalRootGather.Layout) {calendar src : Memory w}
+ (incoming : L.incomingHead = incidenceBase D last (TerminalPrefix.arcCount Y) 4)
+ (widths : L.widthHead = incidenceBase D last (TerminalPrefix.arcCount Y) 5)
+ (starts : L.prefixHead = tableBase D last tab)
+ (columns : (packedIncidence D w last (TerminalPrefix.arcCount Y)).ActualColumns Y calendar)
+ (fit : endAddress D < 2^w) (slots : TerminalPrefix.arcCount Y ≤ slotCapacity D)
+ (totalFit : Y.totalWidth < 2^w)
+ (raw : ∀ x < endAddress D, x < tableBase D last tab → src x = calendar x)
+ (offsets : ∀ i : Fin (TerminalPrefix.arcCount Y),
+ (src (tableBase D last tab+i.val)).val = EndpointBits.offset (TerminalPrefix.width Y) i) :
+ Rows Y L src := by
+ let count := TerminalPrefix.arcCount Y
+ let T := packedIncidence D w last count
+ have upto : tableBase D last tab ≤ endAddress D :=
+ (Nat.le_add_right ..).trans ((tableEnd_le_nextLevel D last tab).trans (levelStart_mono D last.isLt))
+ have bounds (c : Fin 6) (i : Fin count) : incidenceBase D last count c+i.val < tableBase D last tab :=
+ (incidence_bounds D last count slots c i).2.trans_le (Nat.le_add_right ..)
+ have room := packed_incidence_room D fit last slots
+ have hhead (c : Fin 6) : (T.column c).val = incidenceBase D last count c := by
+ rw [packed_column]
+ apply Nat.mod_eq_of_lt
+ have mul := Nat.mul_le_mul_right count c.isLt.le
+ change incidenceStart D last + c.val*count < 2^w
+ exact (Nat.add_le_add_left mul _).trans_lt room
+ have atColumn (c : Fin 6) (i : Fin count) : src (incidenceBase D last count c+i.val) =
+ calendar (incidenceBase D last count c+i.val) := raw _ ((bounds c i).trans_le upto) (bounds c i)
+ constructor
+ · intro e
+ let i := number Y e
+ let j := number Y (Y.slots.actualGraph.target.symm e)
+ have ibound := ((bounds 4 i).trans_le upto).trans fit
+ have jbound := ((bounds 4 j).trans_le upto).trans fit
+ have hi : i.val < 2^w := (Nat.le_add_left ..).trans_lt ibound
+ have hj : j.val < 2^w := (Nat.le_add_left ..).trans_lt jbound
+ have loc : (T.actualIn+IncidenceDirectory.actualPort Y e).val = incidenceBase D last count 4+i.val := by
+ rw [TerminalPrefix.actualPort_eq, Fin.val_add, show T.actualIn.val = _ from hhead 4]
+ change (incidenceBase D last count 4+(i.val%(2^w)))%(2^w) = _
+ rw [Nat.mod_eq_of_lt hi,Nat.mod_eq_of_lt ibound]
+ have col := congrArg Fin.val (columns.actualIn e)
+ change (calendar (T.actualIn+IncidenceDirectory.actualPort Y e).val).val = _ at col
+ rw [loc] at col
+ have target := congrArg Fin.val (TerminalPrefix.actualPort_eq (w := w) Y (Y.slots.actualGraph.target.symm e))
+ rw [incoming,atColumn 4 i]
+ exact col.trans (target.trans (Nat.mod_eq_of_lt hj))
+ · intro i
+ have hr : T.width.val + count ≤ 2^w := by
+ rw [show T.width.val = _ from hhead 5]
+ change incidenceStart D last + 5*count + count ≤ 2^w
+ omega
+ rw [widths,atColumn 5 i,← show T.width.val = _ from hhead 5]
+ exact width_cells Y T calendar columns hr totalFit i
+ · intro i
+ rw [starts]; exact offsets i
+
+variable {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f}
+variable {n T : ℕ} {hT : T*S.laneBits ≤ n} {X : State (S.degreeExponent 0) n}
+variable {z : (B.execute f hf T hT X).Choices}
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "last" => List.length (List.dropLast (selectedLayers B f hf T hT X z))
+variable {L : Layout} {tab : Fin L.shape.tables} {baseBits laneBits : ℕ} {pub : Fin 11 → Word w}
+ {calendar vertex : Memory w} {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+variable (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits pub calendar vertex bits)
+local notation "H" => header pub
+local notation "count" => TerminalPrefix.arcCount Y
+include entry
+
+/-- The native header loads resolve to the two final incidence columns and
+the selected prefix table, uniformly over the current site ordinal. -/
+theorem VertexEntry.gather_heads (degree : ℕ) (state : Word w) (hl : last < L.levels)
+ (fit : endAddress L < 2^w) (slots : count ≤ slotCapacity L) (headFit : (H).val+12 ≤ 2^w) :
+ let G := TerminalRootGather.Layout.ofHeader degree pub H state vertex
+ G.incomingHead = incidenceBase L last count 4 ∧
+ G.widthHead = incidenceBase L last count 5 ∧ G.prefixHead = tableBase L last tab := by
+ let lastFin : Fin L.levels := ⟨last,hl⟩
+ have incFit := packed_incidence_room L fit lastFin slots
+ have inc (c : Fin 6) : incidenceBase L last count c < 2^w :=
+ (Nat.add_le_add_left (Nat.mul_le_mul_right count c.isLt.le) _).trans_lt incFit
+ have tableFit : tableBase L last tab < 2^w := (Nat.le_add_right ..).trans_lt
+ ((tableEnd_le_nextLevel L last tab).trans_lt (level_room L fit lastFin))
+ have addr (j : ℕ) (hj : j < 12) : (H+(j : Word w)).val = (H).val+j := by
+ rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j < 2^w),Nat.mod_eq_of_lt (by omega)]
+ have arcEq := TerminalPrefix.Segment.arc_count_positions Y
+ have hi := entry.headers (10 : Fin 21) (by decide) (by decide) (by decide)
+ have hw := entry.headers (9 : Fin 21) (by decide) (by decide) (by decide)
+ have hs := entry.headers (11 : Fin 21) (by decide) (by decide) (by decide)
+ change vertex ((H).val+10) = ((incidenceBase L last _ 4 : ℕ) : Word w) at hi
+ change vertex ((H).val+9) = ((incidenceBase L last _ 5 : ℕ) : Word w) at hw
+ change vertex ((H).val+11) = ((tableBase L last tab : ℕ) : Word w) at hs
+ rw [← arcEq] at hi hw
+ change (vertex (H+10).val).val = _ ∧ (vertex (H+9).val).val = _ ∧ (vertex (H+11).val).val = _
+ rw [show (H+10).val = _ from addr 10 (by decide),show (H+9).val = _ from addr 9 (by decide),
+ show (H+11).val = _ from addr 11 (by decide),hi,hw,hs]
+ exact ⟨Nat.mod_eq_of_lt (inc 4),Nat.mod_eq_of_lt (inc 5),Nat.mod_eq_of_lt tableFit⟩
+
+/-- The selected packed calendar supplies the gather rows in the actual
+vertex-entry memory, through the header's loaded addresses. -/
+theorem VertexEntry.gather_rows (degree : ℕ) (state : Word w) (hl : last < L.levels)
+ (fit : endAddress L < 2^w) (slots : count ≤ slotCapacity L) (headFit : (H).val+12 ≤ 2^w)
+ (cols : (packedIncidence L w last count).ActualColumns Y calendar) :
+ Rows Y (TerminalRootGather.Layout.ofHeader degree pub H state vertex) vertex := by
+ obtain ⟨i,b,s⟩ := entry.gather_heads degree state hl fit slots headFit
+ exact gather_rows_of_columns Y L ⟨last,hl⟩ tab _ i b s cols fit slots
+ (entry.total ▸ (vertex ((H).val+12)).isLt) (fun x hx h => entry.raw x hx (.inl h)) entry.offsets
+
+end PairSimulation.TerminalProgram
+
+
+namespace PairSimulation.TerminalPrefix.Linked
+
+open BurstRAM Compression CompressorRecords DescriptorSpace TerminalGatherGeometry TerminalLink
+open scoped Fin.CommRing
+
+variable {w a g fuel cap : ℕ} {Y : State a g} {workers : Stage → LiveProgram.PairTable}
+ {pub : Fin 11 → Word w} {input quiet : Memory w} {boot : Report w} {rs : List (Report w)}
+local notation "H" => header pub
+
+/-- The quiet traversal-row builder leaves all three endpoint arrays in place.
+This supplies the physical row input before the shared-wire choice is made. -/
+theorem Start.quiet_gather_rows (D : Layout) (last : Fin D.levels) (tab : Fin D.shape.tables)
+ (degree : ℕ) (state : Word w)
+ (s : Start workers pub cap fuel Y (packedIncidence D w last (arcCount Y))
+ (tableBase D last tab : Word w) input boot rs)
+ (columns : (packedIncidence D w last (arcCount Y)).ActualColumns Y (after input boot.events))
+ (keep : ∀ j < endAddress D, quiet j = prefixMemory pub input boot rs j)
+ (end_le : endAddress D ≤ (H).val) (room : (H).val+32 ≤ 2^w)
+ (slots : arcCount Y ≤ slotCapacity D) (cells : arcCount Y ≤ tableWords D)
+ (inverse : (quiet (H+10).val).val = incidenceBase D last (arcCount Y) 4)
+ (widths : (quiet (H+9).val).val = incidenceBase D last (arcCount Y) 5)
+ (starts : (quiet (H+11).val).val = tableBase D last tab) :
+ Rows Y (TerminalRootGather.Layout.ofHeader degree pub H state quiet) quiet := by
+ let L := TerminalRootGather.Layout.ofHeader degree pub H state quiet
+ have rows := PhysicalScanData.prefix_rows Y L D last tab pub (after input boot.events) rs
+ end_le room slots cells inverse widths starts columns s.rawScan
+ have bounds := PhysicalScanData.packed_heads D last tab {L with wires := endAddress D} (arcCount Y)
+ slots cells inverse widths starts le_rfl
+ have saved : (H+31).val = (H).val+31 := by
+ change ((H).val+31%(2^w))%(2^w) = _
+ rw [Nat.mod_eq_of_lt (by omega : 31 < 2^w),Nat.mod_eq_of_lt (by omega)]
+ apply rows.transfer
+ intro h hh i
+ have bound : h + arcCount Y ≤ endAddress D := bounds h hh
+ have hj : h+i.val < endAddress D := (Nat.add_lt_add_left i.isLt _).trans_le bound
+ have away : workerCell H (h+i.val) := by unfold workerCell; rw [saved]; omega
+ exact (keep _ hj).trans (s.handoff_rows.1 _ away).symm
+
+end PairSimulation.TerminalPrefix.Linked
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRootFields.lean b/lean/OAI/Computability/VPVNP/PairVertexRootFields.lean
new file mode 100644
index 0000000000..534157a148
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRootFields.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.PairVertexGeometryRun
+import OAI.Computability.VPVNP.PairVertexSiteSegments
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherImage
+import OAI.Computability.VPVNP.PairTerminalGatherGeometry
+
+/-!
+# Entering the root gather from the actual bootstrap and geometry stages
+
+The root row, vertex ordinal and directory heads come from the saved
+bootstrap registers. The argument stride comes from the geometry word
+at offset seven of the freshly published private frame.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation
+
+open BurstRAM PrivateRAM LiveProgram
+open scoped Fin.CommRing
+
+namespace TerminalRootGather.Layout
+
+variable {w : ℕ}
+
+/-- Decode the terminal header and public operands into the gather layout for the specified
+final site ordinal. -/
+def ofHeader (degree : ℕ) (pub : Fin 11 → Word w) (hdr ordinal : Word w) (m : Memory w) : TerminalRootGather.Layout where
+ vertex := ordinal.val
+ sites := (m (hdr+7).val).val
+ slots := (m (hdr+8).val).val
+ widthHead := (m (hdr+9).val).val
+ incomingHead := (m (hdr+10).val).val
+ prefixHead := (m (hdr+11).val).val
+ wires := (m (hdr+13).val).val
+ n := (pub 6).val
+ root := (m (hdr+6).val + m (hdr+15).val * ordinal).val
+ stride := (NativeFrame.fromHeader degree pub hdr m).arguments.stride
+
+theorem dest_eq (degree : ℕ) (pub : Fin 11 → Word w) (hdr ordinal : Word w) (m : Memory w) :
+ (ofHeader degree pub hdr ordinal m).dest = (NativeFrame.fromHeader degree pub hdr m).arguments.base
+ (ofHeader degree pub hdr ordinal m).root := rfl
+
+end TerminalRootGather.Layout
+
+namespace VertexRootFields
+
+open VertexImage TerminalSiteStart TerminalRootGather LeafSourceLoad
+
+variable {c : Constants} {degree a b p r w : ℕ} {leaf shrink refresh : VertexImage.Segment}
+local notation "S" => segments (VertexGeometry.segment c degree a b) TerminalRootGather.segment leaf shrink refresh
+variable {A : Placement (segments (VertexGeometry.segment c degree a b) TerminalRootGather.segment leaf shrink refresh) p r}
+ {M : Machine w p r 11} {m : Memory w} {hdr ord : Word w} {boot geo : Config w p r}
+ {vals : Static 34 → Word w}
+
+local notation "L" => TerminalRootGather.Layout.ofHeader degree M.publicData hdr ord m
+
+private theorem cast_val (x : Word w) : (x.val : Word w) = x := Fin.ext (Nat.mod_eq_of_lt x.isLt)
+
+theorem saved (hb : BootReady (M.publicData 6) hdr ord m (boot.reg ∘ bootBank A))
+ (hg : VertexGeometry.Ready c degree a b A m M.publicData boot geo vals) :
+ TerminalRootGather.Saved L (imageRegs A rfl) geo := by
+ have keep (i : VertexImage.Saved) (hi : i ≠ histBase) :
+ geo.reg (imageRegs A (rfl : S .rootFields = TerminalRootGather.segment) (save i)) = boot.reg (A.saved i) :=
+ (imageRegs_saved A (rfl : S .rootFields = TerminalRootGather.segment) i) ▸ hg.saved i hi
+ constructor
+ · exact (keep ordinal (by decide)).trans (hb.ordinal.trans (cast_val _).symm)
+ · exact (keep root (by decide)).trans (hb.root.trans (cast_val _).symm)
+ · exact (keep finalSites (by decide)).trans (hb.sites.trans (cast_val _).symm)
+ · exact (keep slots (by decide)).trans (hb.slots.trans (cast_val _).symm)
+ · exact (keep widths (by decide)).trans (hb.widths.trans (cast_val _).symm)
+ · exact (keep incoming (by decide)).trans (hb.incoming.trans (cast_val _).symm)
+ · exact (keep prefixBase (by decide)).trans (hb.prefixPtr.trans (cast_val _).symm)
+ · exact (keep wires (by decide)).trans (hb.wires.trans (cast_val _).symm)
+
+theorem stride (hb : BootReady (M.publicData 6) hdr ord m (boot.reg ∘ bootBank A))
+ (hg : VertexGeometry.Ready c degree a b A m M.publicData boot geo vals) :
+ geo.privateMem (geo.privateMem ((L).n : Word w)+7) = ((L).stride : Word w) := by
+ have hh : boot.reg (A.saved header) = hdr := hb.header
+ have ptr := hg.geometry.pointer
+ rw [hh] at ptr
+ have cell := hg.fields (7 : Fin 12)
+ rw [hh] at cell
+ change geo.privateMem (geo.privateMem (((M.publicData 6).val : ℕ) : Word w)+7) = _
+ rw [ptr,← Nat.cast_ofNat (R := Word w) (n := 7),← Nat.cast_add]
+ exact cell
+
+/-- Execute the gather at its installed image rows using the booted saved
+bank and the stride installed by the geometry segment. -/
+theorem gather (contains : Contains A M) (hb : BootReady (M.publicData 6) hdr ord m (boot.reg ∘ bootBank A))
+ (hg : VertexGeometry.Ready c degree a b A m M.publicData boot geo vals) (fit : (L).Fits m) :
+ ∃ out es, out.pc = A.dfsPC 0 ∧ out.persistent = geo.persistent ∧
+ (∀ i, out.reg (A.dfs i) = geo.reg (A.dfs i)) ∧ (∀ i, out.reg (A.saved i) = geo.reg (A.saved i)) ∧
+ Frame (imageRegs A (rfl : S .rootFields = TerminalRootGather.segment)) geo out ∧
+ out.privateMem = TerminalRootGather.Layout.placed (L).dest ((L).packet m) geo.privateMem ∧
+ Cost es (15+21*(L).degree+5*((L).packet m).length) (5*(L).degree+((L).packet m).length) ∧ Prefix M m geo es out :=
+ image_run A rfl M contains L m fit geo hg.pc (saved hb hg) (cast_val _).symm (stride hb hg)
+
+end VertexRootFields
+end PairSimulation
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRootFieldsReady.lean b/lean/OAI/Computability/VPVNP/PairVertexRootFieldsReady.lean
new file mode 100644
index 0000000000..78fe61a7cf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRootFieldsReady.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.PairVertexRootFields
+import OAI.Computability.VPVNP.PairVertexRootPacket
+import OAI.Computability.VPVNP.PairVertexRootGatherResident
+
+/-!
+# Root packet and DFS state at the end of the terminal gather
+
+The bootstrap pushes the root address onto an initially zero private memory.
+The gather installs the actual terminal vertex's two half-wire lists in its
+node interval. At DFS row zero the pending root, vertex-wide geometry, all
+38 cached leaf inputs and the zero histogram are resident together.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexRootFields
+
+open BurstRAM PrivateRAM LiveProgram Compression VertexImage TerminalSiteStart TerminalRootGather LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {c : Constants} {degree a b p r w : ℕ} {leaf shrink refresh : VertexImage.Segment}
+local notation "S" => segments (VertexGeometry.segment c degree a b) TerminalRootGather.segment leaf shrink refresh
+variable {A : Placement (segments (VertexGeometry.segment c degree a b) TerminalRootGather.segment leaf shrink refresh) p r}
+ {M : Machine w p r 11} {m : Memory w} {hdr ord : Word w} {boot geo : Config w p r}
+ {vals : Static 34 → Word w}
+
+local notation "lay" => TerminalRootGather.Layout.ofHeader degree M.publicData hdr ord m
+local notation "area" => NativeFrame.fromHeader degree M.publicData hdr m
+local notation "N" => Fin.val (M.publicData 6)
+local notation "G" => NativeFrame.frameBase (NativeFrame.fromHeader degree M.publicData hdr m)
+local notation "role" => boot.reg (A.saved roleOffset)
+local notation "rootWord" => (m (Fin.val (hdr+6)) + m (Fin.val (hdr+15)) * ord)
+
+private theorem predecessor (n : Word w) (hn : 0 < n.val) : ((n.val-1 : ℕ) : Word w) = n-1 := by
+ rw [Nat.cast_sub hn,Nat.cast_one,Fin.cast_val_eq_self]
+
+/-- The concrete boot store gives exactly the singleton stack below the
+geometry pointer, even when the payload word is zero. -/
+theorem singleton {priv : Word w → Word w} (mem : boot.privateMem =
+ Function.update priv (M.publicData 6-1) rootWord) (hn : 0 < N) :
+ DFS.Represents boot.privateMem (N-1) [((lay).root : Word w)] := by
+ have hmod := (M.publicData 6).isLt
+ refine ⟨by simp only [List.length_singleton]; omega,?_⟩
+ intro i
+ have hi : i.val = 0 := by have := i.isLt; simp only [List.length_singleton] at this; omega
+ have he : i = (⟨0,by simp⟩ : Fin [((lay).root : Word w)].length) := Fin.ext hi
+ subst i
+ change boot.privateMem ((N-1+0 : ℕ) : Word w) = ((lay).root : Word w)
+ rw [mem,Nat.add_zero,predecessor _ hn,Function.update_self]
+ exact (Fin.cast_val_eq_self rootWord).symm
+
+private theorem boot_histogram (mem : boot.privateMem =
+ Function.update (fun _ => 0) (M.publicData 6-1) rootWord) (hn : 0 < N)
+ (histAfter : N < (area).histBase) (cacheFit : (area).cacheBase+38 ≤ 2^w)
+ (i : Fin (area).histWords) : boot.privateMem (((area).histBase+i.val : ℕ) : Word w) = 0 := by
+ have hbound := (Nat.add_lt_add_left i.isLt (area).histBase).trans_le (area).hist_before
+ have val : ((((area).histBase+i.val : ℕ) : Word w)).val = (area).histBase+i.val := Nat.mod_eq_of_lt (by omega)
+ have nfit := (M.publicData 6).isLt
+ have prev : (M.publicData 6-1).val = N-1 := by
+ rw [← predecessor (M.publicData 6) hn]; exact Nat.mod_eq_of_lt (by omega)
+ rw [mem,Function.update_of_ne]
+ intro eq
+ have hv := congrArg Fin.val eq
+ rw [val,prev] at hv
+ omega
+
+variable {ex lanes : ℕ} {X : State ex lanes} {u : X.network.Site}
+variable (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+
+local notation "q₀" => VertexRootPacket.packet X lay u f
+
+theorem ready_of_placed (hb : BootReady (M.publicData 6) hdr ord m (boot.reg ∘ bootBank A))
+ (hg : VertexGeometry.Ready c degree a b A m M.publicData boot geo vals)
+ (fresh : boot.privateMem = Function.update (fun _ => 0) (M.publicData 6-1) rootWord)
+ (num : TerminalGatherGeometry.Numbering X lay u) (rows : TerminalGatherGeometry.Rows X lay m)
+ (bits : ∀ i, m ((lay).wires+i.val) = PrivateFields.bitValue w (f i))
+ (fit : (lay).Fits m) (hn : 0 < N) (rootPos : 0 < (lay).root) (rootBound : (lay).root < (area).nodes)
+ (deg : 2^ex ≤ degree) (width : X.maxWireWidth ≤ N) (cacheFit : (area).cacheBase+38 ≤ 2^w) (out : Config w p r)
+ (placed : out.privateMem = TerminalRootGather.Layout.placed (lay).dest ((lay).packet m) geo.privateMem) :
+ (q₀).Fits (area).arguments w N ∧ (q₀).Stored (area).arguments (DFS.scratch N out.privateMem) ∧
+ Resident area N (N-1) [((lay).root : Word w)] (NativeFrame.leafWords degree M.publicData hdr role m)
+ (NativeFrame.fields degree M.publicData hdr role m) vals out.privateMem := by
+ have size := VertexRootPacket.length_le_stride X lay u f degree deg width
+ obtain ⟨qfit,stored,bound⟩ := VertexRootPacket.of_gather num rows f bits fit area rfl rfl rootBound size geo out placed
+ have len : ((lay).packet m).length = (q₀).bits.length := by
+ rw [TerminalGatherGeometry.packet_eq num rows f bits,List.length_map]; rfl
+ have packetEnd : (lay).dest + ((lay).packet m).length ≤ (area).histBase := by rw [len]; exact bound
+ have pointerBelow : N < (lay).dest := by
+ change N < N+(lay).root*(2*degree*N+1)
+ exact Nat.lt_add_of_pos_right (Nat.mul_pos rootPos (Nat.succ_pos _))
+ have histAfter : N < (area).histBase := pointerBelow.trans_le ((Nat.le_add_right _ _).trans packetEnd)
+ have before := singleton (degree := degree) (m := m) (hdr := hdr) (ord := ord) fresh hn
+ have ends : N-1 + [((lay).root : Word w)].length ≤ N := by simp only [List.length_singleton]; omega
+ have hh : boot.reg (A.saved header) = hdr := hb.header
+ have resident := Resident.of_ready hg before ends (hh ▸ histAfter) (hh ▸ cacheFit)
+ (by rw [hh]; exact boot_histogram fresh hn histAfter cacheFit)
+ rw [hh] at resident
+ have gh := (area).hist_before
+ have room : G+12 ≤ 2^w := by change (area).histBase+(area).histWords+12 ≤ _; omega
+ exact ⟨qfit,stored,resident.after_gather placed ends pointerBelow packetEnd room cacheFit⟩
+
+theorem gather_ready (contains : Contains A M) (hb : BootReady (M.publicData 6) hdr ord m (boot.reg ∘ bootBank A))
+ (hg : VertexGeometry.Ready c degree a b A m M.publicData boot geo vals)
+ (fresh : boot.privateMem = Function.update (fun _ => 0) (M.publicData 6-1) rootWord)
+ (num : TerminalGatherGeometry.Numbering X lay u) (rows : TerminalGatherGeometry.Rows X lay m)
+ (bits : ∀ i, m ((lay).wires+i.val) = PrivateFields.bitValue w (f i))
+ (fit : (lay).Fits m) (hn : 0 < N) (rootPos : 0 < (lay).root) (rootBound : (lay).root < (area).nodes)
+ (deg : 2^ex ≤ degree) (width : X.maxWireWidth ≤ N) (cacheFit : (area).cacheBase+38 ≤ 2^w) :
+ ∃ out es, out.pc = A.dfsPC 0 ∧ out.persistent = geo.persistent ∧
+ (∀ i, out.reg (A.dfs i) = geo.reg (A.dfs i)) ∧ (∀ i, out.reg (A.saved i) = geo.reg (A.saved i)) ∧
+ Frame (imageRegs A (rfl : S .rootFields = TerminalRootGather.segment)) geo out ∧
+ out.privateMem = TerminalRootGather.Layout.placed (lay).dest ((lay).packet m) geo.privateMem ∧
+ (q₀).Fits (area).arguments w N ∧ (q₀).Stored (area).arguments (DFS.scratch N out.privateMem) ∧
+ Resident area N (N-1) [((lay).root : Word w)] (NativeFrame.leafWords degree M.publicData hdr role m)
+ (NativeFrame.fields degree M.publicData hdr role m) vals out.privateMem ∧
+ Cost es (15+21*(lay).degree+5*((lay).packet m).length) (5*(lay).degree+((lay).packet m).length) ∧
+ Prefix M m geo es out := by
+ obtain ⟨out,es,done,st,dfs,saved,frame,placed,cost,pre⟩ := gather contains hb hg fit
+ obtain ⟨qfit,stored,resident⟩ := ready_of_placed f hb hg fresh num rows bits fit hn rootPos rootBound
+ deg width cacheFit out placed
+ exact ⟨out,es,done,st,dfs,saved,frame,placed,qfit,stored,resident,cost,pre⟩
+
+end PairSimulation.VertexRootFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRootGatherResident.lean b/lean/OAI/Computability/VPVNP/PairVertexRootGatherResident.lean
new file mode 100644
index 0000000000..e2d4a12571
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRootGatherResident.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.PairVertexGeometryResident
+import OAI.Computability.VPVNP.PairSimulationTerminalRootGatherLayout
+import OAI.Computability.VPVNP.PairVertexSiteReport
+
+/-!
+# Private vertex state preserved by the terminal root gather
+
+The DFS stack and its geometry pointer are below the root packet. The
+histogram, the twelve-word frame and the scalar cache lie beyond the packet.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexRootFields
+
+open BurstRAM PrivateRAM LiveProgram LeafSourceLoad TerminalRootGather VertexImage
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The private data needed to enter DFS after the root argument has been filled. -/
+structure Resident (R : LeafArena.Regions) (endAddr top : ℕ) (xs : List (Word w))
+ (leaf : Fin 10 → Word w) (fields : Fin 12 → Word w) (vals : Static 34 → Word w)
+ (priv : Word w → Word w) : Prop where
+ stack : DFS.Represents priv top xs
+ geometry : LeafGeometryLoad.Stored endAddr (NativeFrame.frameBase R) priv leaf
+ fields_at : ∀ j : Fin 12, priv ((NativeFrame.frameBase R+j.val : ℕ) : Word w) = fields j
+ cache : Cached R.cacheBase priv vals
+ histogram : ∀ i : Fin R.histWords, priv ((R.histBase+i.val : ℕ) : Word w) = 0
+
+namespace Resident
+
+variable {R : LeafArena.Regions} {L : Layout} {endAddr top : ℕ} {xs : List (Word w)}
+ {leaf : Fin 10 → Word w} {fields : Fin 12 → Word w} {vals : Static 34 → Word w}
+ {old out : Word w → Word w} {mem : Memory w}
+
+local notation "G" => NativeFrame.frameBase R
+
+/-- Replacing the root packet preserves the DFS stack and every vertex-wide
+private field, including every initially zero histogram component. -/
+theorem after_gather (h : Resident R endAddr top xs leaf fields vals old)
+ (placed : out = Layout.placed L.dest (L.packet mem) old)
+ (stackEnd : top+xs.length ≤ endAddr) (pointerBelow : endAddr < L.dest)
+ (packetEnd : L.dest+(L.packet mem).length ≤ R.histBase)
+ (frameFit : G+12 ≤ 2^w) (cacheFit : R.cacheBase+38 ≤ 2^w) :
+ Resident R endAddr top xs leaf fields vals out := by
+ have before (z : ℕ) (hz : z < L.dest) : out (z : Word w) = old (z : Word w) := by
+ rw [placed]
+ exact Layout.placed_outside _ _ _ _ (.inl ((Nat.mod_le z _).trans_lt hz))
+ have after (z : ℕ) (hz : R.histBase ≤ z) (fit : z < 2^w) : out (z : Word w) = old (z : Word w) := by
+ rw [placed]
+ apply Layout.placed_outside _ _ _ _ (.inr ?_)
+ change _ ≤ z%(2^w)
+ rw [Nat.mod_eq_of_lt fit]
+ exact packetEnd.trans hz
+ have frame (j : Fin 12) : out ((G+j.val : ℕ) : Word w) = old ((G+j.val : ℕ) : Word w) := by
+ have hj := j.isLt
+ exact after _ (Nat.le_add_right _ R.histWords |>.trans (Nat.le_add_right _ _)) (by omega)
+ refine ⟨⟨h.stack.1,fun i ↦ ?_⟩,⟨(before endAddr pointerBelow).trans h.geometry.pointer,fun i ↦ ?_⟩,
+ fun i ↦ (frame i).trans (h.fields_at i),?_,?_⟩
+ · exact (before (top+i.val) (((Nat.add_lt_add_left i.isLt _).trans_le stackEnd).trans pointerBelow)).trans
+ (h.stack.2 i)
+ · exact (frame (i.castLE (by decide))).trans (h.geometry.values_at i)
+ · intro j
+ have hj : j.offset < 38 := by cases j <;> simp [Static.offset]; omega
+ have low : R.histBase ≤ R.cacheBase := (Nat.le_add_right ..).trans R.hist_before
+ exact (after (R.cacheBase+j.offset) (low.trans (Nat.le_add_right _ _)) (by omega)).trans (h.cache j)
+ · intro i
+ have hi : R.histBase+i.val < G := Nat.add_lt_add_left i.isLt _
+ exact (after (R.histBase+i.val) (Nat.le_add_right ..) (by omega)).trans (h.histogram i)
+
+private theorem scratchAt {priv : Word w → Word w} {z : ℕ} (above : endAddr ≤ z) (fit : z < 2^w) :
+ NodeArguments.rawScratch (DFS.scratch endAddr priv) (z : Word w) = priv (z : Word w) := by
+ have h : endAddr ≤ (z : Word w).val := by change _ ≤ z%(2^w); rwa [Nat.mod_eq_of_lt fit]
+ rw [NodeArguments.rawScratch,dite_eq_left h]
+ rfl
+
+/-- The dispatcher and flush can read their two fields through DFS scratch. -/
+theorem residentGeometry (h : Resident R endAddr top xs leaf fields vals old)
+ (above : endAddr ≤ G) (fit : G+12 ≤ 2^w) :
+ ResidentGeometry (DFS.scratch endAddr old) (G : Word w) (fields 10) (fields 11) := by
+ have hf (i : Fin 12) : G+i.val < 2^w := by have := i.isLt; omega
+ have addr (j : ℕ) (hj : j < 12) : ((G : Word w)+(j : Word w)).val = G+j := by
+ rw [← Nat.cast_add,Fin.val_natCast,Nat.mod_eq_of_lt (hf ⟨j,hj⟩)]
+ have atField (i : Fin 12) := (scratchAt (priv := old) (above.trans (Nat.le_add_right G i.val)) (hf i)).trans
+ (h.fields_at i)
+ refine ⟨by omega,?_,?_,(scratchAt le_rfl (by omega)).trans h.geometry.pointer,?_,?_⟩
+ · rw [show (10 : Word w) = ((10 : ℕ) : Word w) from rfl,addr 10 (by decide)]; omega
+ · rw [show (11 : Word w) = ((11 : ℕ) : Word w) from rfl,addr 11 (by decide)]; omega
+ · have hj := atField (10 : Fin 12)
+ change NodeArguments.rawScratch _ ((G+10 : ℕ) : Word w) = _ at hj
+ simpa only [Nat.cast_add,Nat.cast_ofNat] using hj
+ · have hj := atField (11 : Fin 12)
+ change NodeArguments.rawScratch _ ((G+11 : ℕ) : Word w) = _ at hj
+ simpa only [Nat.cast_add,Nat.cast_ofNat] using hj
+
+/-- The leaf verifier sees all 38 unchanged scalar operands in its scratch. -/
+theorem cacheScratch (h : Resident R endAddr top xs leaf fields vals old)
+ (above : endAddr ≤ R.cacheBase) (fit : R.cacheBase+38 ≤ 2^w) :
+ Cached R.cacheBase (NodeArguments.rawScratch (DFS.scratch endAddr old)) vals := by
+ intro j
+ have hj : j.offset < 38 := by cases j <;> simp [Static.offset]; omega
+ exact (scratchAt (above.trans (Nat.le_add_right _ _)) (by omega)).trans (h.cache j)
+
+/-- Every labeled counter seen by the site report starts at zero. -/
+theorem zeroHistogram {Label : Type} (order : Fin R.histWords ≃ Label)
+ (h : Resident R endAddr top xs leaf fields vals old)
+ (above : endAddr ≤ R.histBase) (fit : G ≤ 2^w) (label : Label) :
+ privateHistogram order R.histBase (DFS.scratch endAddr old) label = 0 := by
+ let i := order.symm label
+ have hi : R.histBase+i.val < G := Nat.add_lt_add_left i.isLt _
+ change (NodeArguments.rawScratch _ ((R.histBase+i.val : ℕ) : Word w)).val = 0
+ rw [scratchAt (above.trans (Nat.le_add_right ..)) (hi.trans_le fit), h.histogram i]
+ rfl
+
+variable {c : Constants} {degree a b p r : ℕ} {rootFields leafSeg shrink refresh : Segment}
+ {A : Placement (segments (VertexGeometry.segment c degree a b) rootFields leafSeg shrink refresh) p r}
+ {pub : Fin 11 → Word w} {st geo : Config w p r}
+
+local notation "R₀" => NativeFrame.fromHeader degree pub (st.reg (A.saved header)) mem
+local notation "role₀" => st.reg (A.saved roleOffset)
+local notation "header₀" => st.reg (A.saved header)
+
+/-- A geometry run supplies the resident state from a booted stack and an
+initially zero histogram. Its private stores are outside the histogram. -/
+theorem of_ready (h : VertexGeometry.Ready c degree a b A mem pub st geo vals)
+ (stack : DFS.Represents st.privateMem top xs) (ends : top+xs.length ≤ (pub 6).val)
+ (histAfter : (pub 6).val < (R₀).histBase) (cacheFit : (R₀).cacheBase+38 ≤ 2^w)
+ (zero : ∀ i : Fin (R₀).histWords, st.privateMem (((R₀).histBase+i.val : ℕ) : Word w) = 0) :
+ Resident R₀ (pub 6).val top xs (NativeFrame.leafWords degree pub header₀ role₀ mem)
+ (NativeFrame.fields degree pub header₀ role₀ mem) vals geo.privateMem := by
+ have histBelow : (R₀).histBase ≤ NativeFrame.frameBase R₀ := Nat.le_add_right ..
+ refine ⟨h.stack stack ends (histAfter.trans_le histBelow),h.geometry,h.fields,h.cache,?_⟩
+ intro i
+ have addr := Nat.add_lt_add_left i.isLt (R₀).histBase
+ have below : (R₀).histBase+i.val < (R₀).cacheBase := addr.trans_le (R₀).hist_before
+ have hv : ((((R₀).histBase+i.val : ℕ) : Word w)).val = (R₀).histBase+i.val := Nat.mod_eq_of_lt (by omega)
+ apply (h.outside _ ?_ (.inl (hv.trans_lt addr)) (.inl (hv.trans_lt below))).trans (zero i)
+ intro eq
+ have e := congrArg Fin.val eq
+ rw [hv] at e
+ omega
+
+end Resident
+
+end PairSimulation.VertexRootFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRootInputs.lean b/lean/OAI/Computability/VPVNP/PairVertexRootInputs.lean
new file mode 100644
index 0000000000..de8dbd9afe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRootInputs.lean
@@ -0,0 +1,39 @@
+import OAI.Computability.VPVNP.PairVertexRootFields
+
+/-! # Physical inputs of the terminal root at one ordinal -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM Compression
+open scoped Fin.CommRing
+
+/-- Native gather and bootstrap inputs at a physical ordinal. -/
+structure RootInputs {w a g : ℕ} (Y : State a g) (v : Y.network.Site) (degree : ℕ)
+ (pub : Fin 11 → Word w) (hdr state : Word w) (m : Memory w)
+ (bits : Fin (∑ j, TerminalPrefix.width Y j) → Bool) : Prop where
+ active : state < m (hdr+7).val
+ rootPos : 0 < (TerminalRootGather.Layout.ofHeader degree pub hdr state m).root
+ rootBound : (TerminalRootGather.Layout.ofHeader degree pub hdr state m).root <
+ (NativeFrame.fromHeader degree pub hdr m).nodes
+ cache : (NativeFrame.fromHeader degree pub hdr m).cacheBase+38 ≤ 2^w
+ numbering : TerminalGatherGeometry.Numbering Y (TerminalRootGather.Layout.ofHeader degree pub hdr state m) v
+ rows : TerminalGatherGeometry.Rows Y (TerminalRootGather.Layout.ofHeader degree pub hdr state m) m
+ bank : ∀ i, m ((TerminalRootGather.Layout.ofHeader degree pub hdr state m).wires+i.val) = PrivateFields.bitValue w (bits i)
+ fits : (TerminalRootGather.Layout.ofHeader degree pub hdr state m).Fits m
+ deg : 2^a ≤ degree
+ width : Y.maxWireWidth ≤ (pub 6).val
+ header : hdr.val + 31 < 2^w
+ heads : ∀ h ∈ [(TerminalRootGather.Layout.ofHeader degree pub hdr state m).incomingHead,
+ (TerminalRootGather.Layout.ofHeader degree pub hdr state m).widthHead,
+ (TerminalRootGather.Layout.ofHeader degree pub hdr state m).prefixHead], h+TerminalPrefix.arcCount Y ≤ hdr.val
+ wires : (TerminalRootGather.Layout.ofHeader degree pub hdr state m).wires + Y.totalWidth ≤ hdr.val
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRootOrdinal.lean b/lean/OAI/Computability/VPVNP/PairVertexRootOrdinal.lean
new file mode 100644
index 0000000000..b44177395e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRootOrdinal.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.PairVertexSelectedPaths
+import OAI.Computability.VPVNP.PairVertexFrameData
+import OAI.Computability.VPVNP.PairTreeSelectedFrontier
+
+/-! # An initialized physical root supplies the active ordinal worker -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM Compression DFS LocalHistory NodeArguments TraversalRows TreeDecode
+open CompressorRecords.SourceTransport LeafSourceLoad
+open scoped Fin.CommRing
+
+variable {k K : Type*} [Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → K) (hκ : B.IsSolution κ) {lanes : ℕ}
+ (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute κ hκ T hT X).Choices) (rowBase : ℕ)
+ {geometry rootFields leaf shrink refresh : Segment} {p r w g : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r) (M : Machine w p r 11)
+ (m : Memory w) (base grammar : ℕ) (order : Fin g ≃ B.Entry) (P : SiteParsers κ X.network)
+ (half : ∀ u, ((B.execute κ hκ T hT X).finalState z).network.Half u)
+ (cap : ℕ) (i : Fin (siteOrder ((B.execute κ hκ T hT X).finalState z)).length)
+ (R : LeafArena.Regions) (data : Fin 10 → Word w) (fields : Fin 12 → Word w) (vals : Static 34 → Word w)
+ (offset : Word w) (nodeCap maxTicks : ℕ) (format : Packet → Prop) (desc : ℕ → List ℕ)
+ (domain : Word w → Scratch w (M.publicData 6).val → Prop)
+ (handlers : NodeDispatch.Role → HookParser w (M.publicData 6).val)
+ (cost : VisitPath w (M.publicData 6).val → Prop)
+
+local notation "E₀" => B.execute κ hκ T hT X
+local notation "Y₀" => StateExecution.finalState (E₀) z
+local notation "tree₀" => selectedTrees B κ hκ T hT X z rowBase
+local notation "site₀" => Order.entries (siteOrder (Y₀)) i
+local notation "q₀" => Packet.mk (VertexTree.address ((tree₀) (site₀))) (packed (Y₀) (site₀) (half (site₀)))
+local notation "word₀" => Machine.publicData M 6
+local notation "N₀" => Fin.val (word₀)
+local notation "H₀" => TerminalLink.header (Machine.publicData M)
+local notation "G₀" => NativeFrame.frameBase R
+local notation "stable₀" => VertexFrameData R data offset vals
+local notation "valid₀" => Budgeted R.arguments format (stable₀) desc (privateHistogram order R.histBase) nodeCap ((N₀)*nodeCap)
+
+/-- The checked physical gather initializes every state component used by
+the ascending vertex interpreter. The layer checks concern the fixed role
+programs, and the size and read bounds concern their selected public rows. -/
+noncomputable def OrdinalRows.ofRoot
+ (checked : SelectedChecks B κ hκ T hT X z rowBase A M m ((G₀) : Word w) offset R.histBase
+ order P (valid₀) domain handlers cost)
+ (cfg : Config w p r) (es : List (Event w)) (root : ActiveRootState A cfg (i.val : Word w) (word₀)
+ offset R (q₀) data fields vals)
+ (run : TerminalRootGather.Prefix M m (M.program.start (i.val : Word w)) es cfg)
+ (det : choiceBits es = []) (same : after m es = m) (reads : Reads (TerminalLink.workerCell (H₀)) es)
+ (labelCount : R.histWords = g) (offsetAt : fields 10 = offset) (histAt : fields 11 = (R.histBase : Word w))
+ (positive : 0 < N₀) (above : N₀ ≤ R.histBase) (cacheFit : R.cacheBase+38 ≤ 2^w)
+ (type : format (q₀)) (children : subtreeAddresses desc (q₀) = ((tree₀) (site₀)).preorder)
+ (rows : AllRows w m B.recordLimit rowBase rowBase (selectedLayers B κ hκ T hT X z))
+ (space : rowBase+words B.recordLimit (selectedLayers B κ hκ T hT X z) ≤ (H₀).val)
+ (headerFit : (H₀).val+31 < 2^w) (capacity : B.growthConstant^T ≤ N₀)
+ (external : base+grammar+g ≤ (H₀).val)
+ (hbase : M.publicData 4 = (base : Word w)) (hgrammar : M.publicData 5 = (grammar : Word w))
+ (hg : M.publicData 9 = (g : Word w))
+ (small : ∀ j, cost j → j.trace.length ≤ maxTicks)
+ (time : es.length+(15+maxTicks)*((E₀).termChain (B.records κ hκ T hT X) z).occurrences
+ (fun _ => 1) (site₀)+7*g+46 ≤ cap) :
+ OrdinalRows B κ hκ T hT X z rowBase A M base grammar order P half cap m i := by
+ subst g
+ have frameFit : G₀ + 12 ≤ 2^w := by
+ have := R.hist_before
+ unfold NativeFrame.frameBase
+ omega
+ have distinct : (subtreeAddresses desc (q₀)).Nodup := children ▸ (selected_preorders B κ hκ T hT X z rowBase).1 (site₀)
+ have count := chainTrees_length ((E₀).termChain (B.records κ hκ T hT X) z) (selectedParsers B κ hκ T hT X z)
+ (selectedPointers B κ hκ T hT X z rowBase) (fun v => leafTree (sitePointers B.recordLimit rowBase (siteOrder X) v))
+ (fun _ => 1) (fun _ => le_rfl) (site₀)
+ have size : ((tree₀) (site₀)).preorder.length ≤ N₀ :=
+ count.trans (((B.branch_bounds κ hκ T hT X z).2.2.2.1 (site₀)).trans capacity)
+ have prepared := budget_of_root root offsetAt histAt above frameFit cacheFit format type desc distinct order nodeCap
+ ((N₀)*nodeCap) (by rw [children]; exact Nat.mul_le_mul_right _ size)
+ have nonzero : word₀ ≠ 0 := fun h => by rw [h] at positive; exact (Nat.lt_irrefl _ positive)
+ have wordTop : word₀-1 = (((N₀)-1 : ℕ) : Word w) := Fin.ext <| by
+ rw [Fin.val_sub_one_of_ne_zero nonzero,Fin.val_natCast,Nat.mod_eq_of_lt (by have := (word₀).isLt; omega)]
+ exact {
+ endAddr := N₀, src := R.histBase, G := ((G₀) : Word w), offset := offset
+ valid := Budgeted R.arguments format (VertexFrameData R data offset vals) desc
+ (privateHistogram order R.histBase) nodeCap ((N₀)*nodeCap)
+ domain := domain, handlers := handlers, cost := cost, selected := checked
+ cfg := cfg, pre := es, pref := run, noChoice := det, noWrite := same, prefixReads := reads
+ persistent := root.persistent, atRoot := root.pc, top := (N₀)-1, stack := root.resident.stack
+ endTop := by omega, sp := root.top.trans wordTop, endReg := root.endReg.trans (Fin.cast_val_eq_self _).symm
+ one := root.one, zero := root.resident.zeroHistogram order above (by omega), prepared := prepared
+ rows := rows, space := space, hfit := headerFit, capacity := capacity, above := above
+ hsrc := by have := R.hist_before; omega
+ hdst := by omega, cells := fun j => TerminalFootprint.below (H₀) headerFit (by have := j.isLt; omega)
+ hbase := hbase, hgrammar := hgrammar, hg := hg, maxTicks := maxTicks, small := small, room := time }
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexRootPacket.lean b/lean/OAI/Computability/VPVNP/PairVertexRootPacket.lean
new file mode 100644
index 0000000000..51d5869b10
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexRootPacket.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.PairPendingArguments
+import OAI.Computability.VPVNP.PairTerminalGatherGeometry
+import OAI.Computability.VPVNP.PairTerminalLayout
+
+/-!
+# The typed root argument after the native terminal gather
+
+The root packet records the selected vertex's outgoing and incoming half-wire
+bits in DFS order. Its private interval starts at the destination computed by
+the terminal gather and ends before the common histogram.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexRootPacket
+
+open BurstRAM PrivateRAM Compression TerminalRootGather
+open scoped Fin.CommRing
+
+variable {a g w p r : ℕ}
+
+/-- The root argument packet pairing the final site's DFS address with its packed half-wire
+assignment from the shared bit array. -/
+noncomputable def packet (X : State a g) (L : Layout) (u : X.network.Site)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool) : NodeArguments.Packet :=
+ ⟨L.root, NodeArguments.packed X u (TerminalGatherGeometry.half X f u)⟩
+
+/-- The physical frame stride covers both half-wire lists of the terminal
+vertex, including repeated endpoints of a loop. -/
+theorem length_le_stride (X : State a g) (L : Layout) (u : X.network.Site)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool) (degree : ℕ)
+ (deg : 2^a ≤ degree) (width : X.maxWireWidth ≤ L.n) :
+ (packet X L u f).bits.length ≤ NodeArguments.frameStride degree L.n :=
+ (NodeArguments.packed_length_le X u _).trans
+ ((Nat.mul_le_mul (Nat.mul_le_mul_left 2 deg) width).trans (Nat.le_succ _))
+
+variable {X : State a g} {L : Layout} {u : X.network.Site} {m : Memory w}
+
+/-- Translate the private-memory equality produced by the installed gather
+into the packet invariant at the first DFS instruction. -/
+theorem of_gather (num : TerminalGatherGeometry.Numbering X L u) (rows : TerminalGatherGeometry.Rows X L m)
+ (f : Fin (∑ i, TerminalPrefix.width X i) → Bool)
+ (bits : ∀ i, m (L.wires+i.val) = PrivateFields.bitValue w (f i)) (fit : L.Fits m)
+ (R : LeafArena.Regions) (start : L.n = R.arguments.start) (stride : L.stride = R.arguments.stride)
+ (root : L.root < R.nodes) (size : (packet X L u f).bits.length ≤ R.arguments.stride)
+ (c out : Config w p r)
+ (native : out.privateMem = Layout.placed L.dest (L.packet m) c.privateMem) :
+ let q := packet X L u f
+ q.Fits R.arguments w L.n ∧ q.Stored R.arguments (DFS.scratch L.n out.privateMem) ∧
+ R.arguments.base q.node + q.bits.length ≤ R.histBase := by
+ let q := packet X L u f
+ have dest : L.dest = R.arguments.base q.node := by
+ change L.n + L.root*L.stride = R.arguments.start + L.root*R.arguments.stride
+ rw [start, stride]
+ have len : (L.packet m).length = q.bits.length := by
+ rw [TerminalGatherGeometry.packet_eq num rows f bits, List.length_map]
+ rfl
+ have below := (Nat.add_le_add_left size (R.arguments.base q.node)).trans (R.node_before root)
+ have hq : q.Fits R.arguments w L.n :=
+ ⟨start ▸ Nat.le_add_right .., size, by simpa only [dest,len] using fit.destEnd.le⟩
+ have stored : out.privateMem = PrivateFields.storeBits (R.arguments.base q.node) q.bits c.privateMem := by
+ rw [native, TerminalGatherGeometry.placed_packet num rows f bits fit, dest]
+ rfl
+ refine ⟨hq, ?_, below⟩
+ intro i
+ let addr : Word w := ((R.arguments.base q.node + i.val : ℕ) : Word w)
+ have value : addr.val = R.arguments.base q.node + i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt _).trans_le hq.2.2)
+ have high : L.n ≤ addr.val := value ▸ hq.1.trans (Nat.le_add_right ..)
+ change NodeArguments.rawScratch (DFS.scratch L.n out.privateMem) addr = _
+ rw [NodeArguments.rawScratch, dite_eq_left high, DFS.scratch, stored]
+ exact PrivateFields.storeBits_read (R.arguments.base q.node) q.bits c.privateMem hq.2.2 i
+
+end PairSimulation.VertexRootPacket
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSegmentChain.lean b/lean/OAI/Computability/VPVNP/PairVertexSegmentChain.lean
new file mode 100644
index 0000000000..2502172113
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSegmentChain.lean
@@ -0,0 +1,62 @@
+import OAI.Computability.VPVNP.PairVertexImage
+
+/-!
+# Sequencing native vertex segments
+
+The two code ranges are consecutive. The first segment's successful continuation
+is the entry of the second. Register placements are explicit so a preparation block
+can fill the operands of its successor and disjoint scratch banks can be framed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.Segment
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {p r n w : ℕ}
+
+/-- Program counters for the first segment in a consecutive two-segment instruction range. -/
+def leftPC (A B : Segment) (loc : Fin (A.count + B.count) → Fin p) (j : Fin A.count) :=
+ loc (j.castAdd B.count)
+
+/-- Program counters for the second segment, shifted past all instructions of the first. -/
+def rightPC (A B : Segment) (loc : Fin (A.count + B.count) → Fin p) (j : Fin B.count) :=
+ loc (j.natAdd A.count)
+
+/-- The two segments may use the same register for an explicit operand handoff. -/
+def thenWith (A B : Segment) (lhs : Fin A.privateRegs ↪ Fin n)
+ (rhs : Fin B.privateRegs ↪ Fin n) : Segment where
+ count := A.count + B.count
+ privateRegs := n
+ entry := A.entry.castAdd B.count
+ row loc dfs saved reg done := Fin.addCases
+ (A.row (leftPC A B loc) dfs saved (lhs.trans reg) (rightPC A B loc B.entry))
+ (B.row (rightPC A B loc) dfs saved (rhs.trans reg) done)
+
+/-- Separate the two private register files while keeping the shared DFS and saved registers. -/
+def seq (A B : Segment) := thenWith A B (Fin.castAddEmb B.privateRegs) (Fin.natAddEmb A.privateRegs)
+
+variable (A B : Segment) (lhs : Fin A.privateRegs ↪ Fin n) (rhs : Fin B.privateRegs ↪ Fin n)
+ (loc : Fin (A.count + B.count) → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin n ↪ Fin r) (done : Fin p) (M : Machine w p r 11)
+
+theorem split_link (rows : ∀ j, M.code (loc j) =
+ ((thenWith A B lhs rhs).row loc dfs saved reg done j).resize w) :
+ (∀ j, M.code (leftPC A B loc j) =
+ (A.row (leftPC A B loc) dfs saved (lhs.trans reg) (rightPC A B loc B.entry) j).resize w) ∧
+ (∀ j, M.code (rightPC A B loc j) =
+ (B.row (rightPC A B loc) dfs saved (rhs.trans reg) done j).resize w) := by
+ constructor
+ · intro j
+ simpa only [thenWith, Fin.addCases_left, leftPC] using rows (j.castAdd B.count)
+ · intro j
+ simpa only [thenWith, Fin.addCases_right, rightPC] using rows (j.natAdd A.count)
+
+end PairSimulation.VertexImage.Segment
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSelectedClock.lean b/lean/OAI/Computability/VPVNP/PairVertexSelectedClock.lean
new file mode 100644
index 0000000000..85bec34786
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSelectedClock.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.CursorBranchBudget
+import OAI.Computability.VPVNP.PairNativeCacheClock
+import OAI.Computability.VPVNP.PairSimulationNodeFieldSpace
+import OAI.Computability.VPVNP.CompressorLevelCounts
+
+/-! # Private clock of a terminal vertex on a selected compressor branch -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open Compression CursorNetwork CursorBounds CursorRouting Filter LiveProgram NativeOperands
+
+private theorem time_estimate {n degree slots g t packet occurrences maxTicks big : ℕ}
+ (hn : 256 ≤ n) (deg : degree ≤ n) (slot : slots ≤ degree) (labels : g ≤ n)
+ (cache : t ≤ n) (width : packet ≤ 2*slots*n) (depth : occurrences ≤ n)
+ (job : maxTicks ≤ big) (large : n*n ≤ big) :
+ t+degree+187+(15+21*slots+5*packet)+(15+maxTicks)*occurrences+7*g+46 ≤ big*n*n := by
+ have hp : packet ≤ 2*n*n := width.trans (Nat.mul_le_mul_right n (Nat.mul_le_mul_left 2 (slot.trans deg)))
+ have hj := Nat.mul_le_mul (Nat.add_le_add_left job 15) depth
+ have hn' : n ≤ n*n := Nat.le_mul_of_pos_right _ (by omega)
+ have hbig : big ≤ big*n := Nat.le_mul_of_pos_right _ (by omega)
+ have hroom := Nat.mul_le_mul_left (big*n) (show 64 ≤ n by omega)
+ nlinarith only [cache,deg,slot,labels,hp,hj,hn',large,hbig,hroom,hn]
+
+set_option exponentiation.threshold 10000 in
+/-- On the actual cursor network, uniform estimates for the field widths,
+number of occurrences and cache initialization suffice for the complete
+native active-site clock, including its phase-controller allowance. -/
+theorem eventually_active_clock {k : Type*} [Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (c : Constants) (a b scale : ℕ)
+ (hb : max S.laneBits 5 ≤ scale) (degree : ℕ) (slots : 2^(S.degreeExponent 0) ≤ degree) :
+ ∀ᶠ n : ℕ in atTop, ∀ {base lanes : ℕ} (labels : Fin (virtualBits scale n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits scale n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (κ : B.Entry → A) (hκ : B.IsSolution κ),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute κ hκ T hT X
+ B.growthConstant^T ≤ n ∧ ∀ z : E.Choices,
+ let Y := E.finalState z
+ let chain := E.termChain (B.records κ hκ T hT X) z
+ ∀ (v : Y.network.Site) (half : Y.network.Half v) (H t maxTicks : ℕ),
+ t ≤ work (NativeCache.args c) a b (AssemblerPublic.geometry scale n H)+76 →
+ maxTicks ≤ n^9000 →
+ t+degree+187+(15+21*2^(S.degreeExponent 0)+5*(NodeArguments.packed Y v half).length) +
+ (15+maxTicks)*chain.occurrences (fun _ => 1) v + 7*Fintype.card B.Entry+46 ≤ n^9999 := by
+ filter_upwards [eventually_pairBranchBounds B u scale hb, NativeCache.eventually_work_le c a b scale,
+ eventually_ge_atTop 256, eventually_ge_atTop degree, eventually_ge_atTop (Fintype.card B.Entry)]
+ with n branch cache hn deg labelsCount
+ intro base lanes labels hD hT A _ κ hκ X T E
+ have hpow {x : ℝ} (h : x ≤ 1) : (n : ℝ)^x ≤ n := by
+ simpa using Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast (show 1 ≤ n by omega)) h
+ have hg := history_pow_blockCount_le
+ (show (1 : ℝ) ≤ B.growthConstant by exact_mod_cast (show 1 ≤ B.growthConstant from (by decide : 1 ≤ 2).trans B.growthConstant_ge_two))
+ (show (0 : ℝ) ≤ u.θ by exact_mod_cast u.theta_pos.le) (show 1 ≤ n by omega) u.growth
+ have capacity : B.growthConstant^T ≤ n := by
+ exact_mod_cast hg.trans (hpow (by norm_num))
+ refine ⟨capacity,?_⟩
+ intro z Y chain v half H t maxTicks ht hj
+ have actual := branch.2.2 labels hD hT A κ hκ z
+ have depth : chain.occurrences (fun _ => 1) v ≤ n :=
+ Nat.cast_le.mp ((actual.2.2.1 v).trans (hpow (by norm_num)))
+ have width : Y.maxWireWidth ≤ n := Nat.cast_le.mp
+ ((Nat.cast_le.mpr actual.2.2.2.2.1).trans (actual.2.2.2.2.2.1.trans (hpow (by norm_num))))
+ have packet := (NodeArguments.packed_length_le Y v half).trans (Nat.mul_le_mul_left _ width)
+ have large : n*n ≤ n^9000 := (by rw [←pow_two]; exact Nat.pow_le_pow_right (by omega) (by decide))
+ have small := time_estimate hn deg slots labelsCount (ht.trans (cache H)) packet depth hj large
+ calc
+ _ ≤ n^9000*n*n := small
+ _ = n^9002 := by rw [show (9002:ℕ)=9000+2 by decide,pow_add,pow_two,Nat.mul_assoc]
+ _ ≤ n^9999 := Nat.pow_le_pow_right (by omega) (by decide)
+
+set_option exponentiation.threshold 10000 in
+/-- Credit for all remaining vertices of one root fits in a private word.
+It applies to every prefix even if a later kernel rejects its input. -/
+theorem eventually_histogram_credit (b : ℕ) (hb : 1 ≤ b) :
+ ∀ᶠ n : ℕ in atTop, n*n^9000 < 2^(wordBits b n) := by
+ filter_upwards [BurstRAM.eventually_polynomial_lt_wordModulus 9001] with n h
+ rw [← pow_succ' n 9000]
+ exact h _ (BurstRAM.log2_le_addressWidth hb n)
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSelectedControl.lean b/lean/OAI/Computability/VPVNP/PairVertexSelectedControl.lean
new file mode 100644
index 0000000000..5d251d110b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSelectedControl.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.PairTraversalPreorderBounds
+import OAI.Computability.VPVNP.PairTraversalReadFootprint
+import OAI.Computability.VPVNP.PairSelectedPacketOrders
+
+/-! # Control and root packets on the actual selected descriptor layers -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TraversalRows
+
+open BurstRAM DFS Compression LocalHistory NetworkKernel TreeDecode
+open CompressorRecords.SourceTransport TerminalFootprint
+open scoped Fin.CommRing
+open private addTree from OAI.Computability.VPVNP.PairTraversalHistory
+
+variable {k A : Type*} [Field k] [CommRing A] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → A) (hκ : B.IsSolution κ) {lanes : ℕ}
+ (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute κ hκ T hT X).Choices) (base : ℕ)
+
+/-- The branch-specific chain of DFS row pointers after the initial layer, using the actual
+selected site orders and record pitch. -/
+noncomputable abbrev selectedPointers :=
+ let E := B.execute κ hκ T hT X
+ let recs := B.records κ hκ T hT X
+ chainPointers B.recordLimit (E.termChain recs z) (branchOrders E recs z)
+ (address B.recordLimit base (siteOrder X).length)
+
+private theorem root_address {L : Type} [Fintype L] {f : L → A} {N Y : Network}
+ (c : TermChain A N Y) (r : ChainParsers f c) (ptr : RowPointers c) (trees : N.Site → VertexTree)
+ (v : Y.Site) : (chainTrees c r ptr trees v).address = lastRowAddresses c ptr (fun u => (trees u).address) v := by
+ induction c with
+ | done => rfl
+ | more t rec tail ih => exact ih r.2 ptr.2 (addTree r.1 ptr.1 trees) v
+
+/-- The packet consumed at the physical final root has the selected address
+and the actual independent half-wire bits in numerical slot order. -/
+theorem selected_rootPacket :
+ let E := B.execute κ hκ T hT X
+ let c := E.termChain (B.records κ hκ T hT X) z
+ let r := selectedParsers B κ hκ T hT X z
+ let ptr := selectedPointers B κ hκ T hT X z base
+ let leaf := sitePointers B.recordLimit base (siteOrder X)
+ let frames := fromRows c r ptr (fun v => (leaf v).1) (NodeArguments.packed (E.finalState z))
+ ∀ v y, finalPackets c frames.2 frames.1 v y =
+ ⟨(selectedTrees B κ hκ T hT X z base v).address, NodeArguments.packed (E.finalState z) v y⟩ := by
+ intro E c r ptr leaf frames v y
+ rw [show finalPackets c frames.2 frames.1 = _ from fromRows_final c r ptr _ _]
+ exact congrArg (fun a => NodeArguments.Packet.mk a _) (root_address c r ptr (fun u => leafTree (leaf u)) v).symm
+
+/-- The real preimage table supplies a DFS visit on the caller's stack.
+Its exact control trace fits the worker address space and visits at most
+the occurrence budget of the selected compression branch. -/
+theorem selected_control {w : ℕ} (m : Memory w) (H : Word w) (stack : ℕ)
+ (rows : AllRows w m B.recordLimit base base (selectedLayers B κ hκ T hT X z))
+ (space : base+words B.recordLimit (selectedLayers B κ hκ T hT X z) ≤ H.val)
+ (fit : H.val+31 < 2^w) (capacity : B.growthConstant^T ≤ stack) :
+ let E := B.execute κ hκ T hT X
+ let c := E.termChain (B.records κ hκ T hT X) z
+ let trees := selectedTrees B κ hκ T hT X z base
+ ∀ v, ∃ es, Visits m stack [((trees v).address : Word w)]
+ ((trees v).preorder.map (fun a : ℕ => (a : Word w))) es ∧
+ Reads (TerminalLink.workerCell H) es ∧ (trees v).preorder.length ≤ c.occurrences (fun _ => 1) v ∧
+ es.length + 5 = 15*(trees v).preorder.length+1 ∧ countProbes es + 1 = 3*(trees v).preorder.length := by
+ intro E c trees v
+ let r := selectedParsers B κ hκ T hT X z
+ let ptr := selectedPointers B κ hκ T hT X z base
+ let initial := siteOrder X
+ let leaf := sitePointers B.recordLimit base initial
+ let old := fun u => leafTree (leaf u)
+ have hl : ∀ u, (old u).rows w m := fun u => leafTree_rows (rows.1 (initial.entries.symm u)).1
+ (rows.1 (initial.entries.symm u)).2
+ have hr := chainPointers_rowsAt c r (branchOrders E (B.records κ hκ T hT X) z) initial
+ B.recordLimit base (address B.recordLimit base initial.length) m rows.2
+ have len := chainTrees_length c r ptr old (fun _ => 1) (fun _ => le_rfl) v
+ have room := (B.branch_bounds κ hκ T hT X z).2.2.2.1 v
+ obtain ⟨es,run⟩ := (trees v).visits stack (chainTrees_rows c r ptr m old hl hr v) (len.trans (room.trans capacity))
+ have support := run.reads_of_row_bounds (selected_preorder_word_bounds B κ hκ T hT X z base H.val m
+ rows space H.isLt.le v)
+ obtain ⟨probes,time⟩ := run.cost
+ exact ⟨es, run, reads_mono support (fun _ => below H fit), len, by simpa using time, by simpa using probes⟩
+
+end PairSimulation.TraversalRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSelectedDesc.lean b/lean/OAI/Computability/VPVNP/PairVertexSelectedDesc.lean
new file mode 100644
index 0000000000..a17b2c6890
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSelectedDesc.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.PairSelectedPacketGeometry
+import OAI.Computability.VPVNP.PairSelectedRowShape
+import OAI.Computability.VPVNP.PairVertexSelectedControl
+
+/-! # The common descendant count for all calls on a selected branch -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TreeDecode
+
+open Compression NetworkKernel LocalHistory DFS NodeArguments TraversalRows
+open private root_address from OAI.Computability.VPVNP.PairVertexSelectedControl
+
+variable {k K : Type*} [Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → K) (hκ : B.IsSolution κ) {lanes : ℕ}
+ (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute κ hκ T hT X).Choices) (rowBase : ℕ)
+
+/-- The descendant addresses are determined by the selected row pointers. -/
+noncomputable def selectedDesc : ℕ → List ℕ :=
+ (selected_descendants B κ hκ T hT X z rowBase).choose
+
+theorem selectedDesc_leaf (v : X.network.Site) :
+ selectedDesc B κ hκ T hT X z rowBase (sitePointers B.recordLimit rowBase (siteOrder X) v).1 = [] :=
+ (selected_descendants B κ hκ T hT X z rowBase).choose_spec.1 v
+
+theorem selectedDesc_level :
+ let passes := CompressorRecords.executeLevels B κ hκ T hT X z
+ let pos := TraversalRoles.layerBase B.recordLimit rowBase (TraversalRoles.selected B κ hκ T hT X z)
+ ∀ i : Fin passes.length, LevelShape B κ hκ (selectedDesc B κ hκ T hT X z rowBase)
+ B.recordLimit (pos i.val) (pos (i.val+1)) passes[i] :=
+ selected_rowShape B κ hκ (selectedDesc B κ hκ T hT X z rowBase) T hT X z rowBase
+ (selected_descendants B κ hκ T hT X z rowBase).choose_spec.2.1
+
+theorem selectedDesc_root :
+ let Y := (B.execute κ hκ T hT X).finalState z
+ let trees := selectedTrees B κ hκ T hT X z rowBase
+ ∀ (v : Y.network.Site) (h : Y.network.Half v), subtreeAddresses (selectedDesc B κ hκ T hT X z rowBase)
+ ⟨(trees v).address,packed Y v h⟩ = (trees v).preorder := by
+ intro Y trees v h
+ let c := (B.execute κ hκ T hT X).termChain (B.records κ hκ T hT X) z
+ let r := selectedParsers B κ hκ T hT X z
+ let ptr := selectedPointers B κ hκ T hT X z rowBase
+ let leaf := sitePointers B.recordLimit rowBase (siteOrder X)
+ have eqn : (trees v).address = lastRowAddresses c ptr (fun u => (leaf u).1) v :=
+ root_address c r ptr (fun u => leafTree (leaf u)) v
+ change (trees v).address :: selectedDesc B κ hκ T hT X z rowBase (trees v).address = _
+ rw [eqn]
+ exact ((selected_descendants B κ hκ T hT X z rowBase).choose_spec.2.2 v).1.symm
+
+end PairSimulation.TreeDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSelectedPaths.lean b/lean/OAI/Computability/VPVNP/PairVertexSelectedPaths.lean
new file mode 100644
index 0000000000..db54599bcd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSelectedPaths.lean
@@ -0,0 +1,203 @@
+import OAI.Computability.VPVNP.PairVertexActiveOccurrence
+import OAI.Computability.VPVNP.PairVertexOrdinalPhase
+
+/-!
+# Accepted vertex paths of a selected compressor execution
+
+Use the native role proofs and the initialized DFS frame at each reached
+ordinal to classify the complete physical phase. The site data refer to the
+selected term chain and the same fixed half-wire arguments throughout.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM Compression DFS LocalHistory NetworkKernel NodeArguments TreeDecode TraversalRows
+open CompressorRecords SourceTransport TerminalLink
+open scoped Fin.CommRing
+
+variable {k R : Type*} [Field k] [CommRing R] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → R) (hκ : B.IsSolution κ) {lanes : ℕ}
+ (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute κ hκ T hT X).Choices) (rowBase : ℕ)
+ {geometry rootFields leaf shrink refresh : Segment} {p r w g : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r) (M : Machine w p r 11)
+ (base grammar : ℕ) (order : Fin g ≃ B.Entry) (P : SiteParsers κ X.network)
+
+local notation "exec₀" => B.execute κ hκ T hT X
+local notation "data₀" => B.records κ hκ T hT X
+local notation "chain₀" => StateExecution.termChain (exec₀) (data₀) z
+local notation "readers₀" => selectedParsers B κ hκ T hT X z
+local notation "trees₀" => selectedTrees B κ hκ T hT X z rowBase
+local notation "Y" => StateExecution.finalState (exec₀) z
+local notation "ord₀" => siteOrder (Y)
+local notation "final₀" => finalParsers (chain₀) (readers₀) P
+local notation "head₀" => TerminalLink.header (Machine.publicData M)
+local notation "allow₀" => workerCell (head₀)
+
+variable (half : ∀ u, ((B.execute κ hκ T hT X).finalState z).network.Half u)
+
+local notation "selected₀" => siteOrdinals (final₀) (Order.entries (ord₀)) order half
+
+/-- Operand, row and stack facts at an active physical ordinal. These describe
+the individual installed roles and the deterministic root prefix. -/
+structure OrdinalRows (cap : ℕ) (m : Memory w) (i : Fin (ord₀).length) where
+ /-- End of the DFS stack interval separating stack addresses from private scratch for this
+ final-site visit. -/
+ endAddr : ℕ
+ /-- Private histogram base whose counters are initialized to zero at the beginning of this
+ vertex traversal. -/
+ src : ℕ
+ /-- Machine-word address of the resident private geometry record for this vertex. -/
+ G : Word w
+ /-- Role-table displacement used to dispatch the popped DFS nodes during the selected visit. -/
+ offset : Word w
+ /-- Predicate relating the pending node packets to the contents of the private scratch image. -/
+ valid : List Packet → Scratch w endAddr → Prop
+ /-- Entry predicate on a popped node and scratch image for the local role parser. -/
+ domain : Word w → Scratch w endAddr → Prop
+ /-- The leaf, shrink, and refresh hook parsers available at this ordinal's DFS nodes. -/
+ handlers : NodeDispatch.Role → HookParser w endAddr
+ /-- Cost predicate required of the local visit path used in the ordinal's resource bound. -/
+ cost : VisitPath w endAddr → Prop
+ selected : SelectedChecks B κ hκ T hT X z rowBase A M m G offset src order P valid domain handlers cost
+ /-- Native vertex machine configuration reached by the ordinal's initial prefix. -/
+ cfg : Config w p r
+ /-- Events of the native prefix leading to this ordinal's vertex computation. -/
+ pre : List (Event w)
+ pref : TerminalSiteStart.Continues M m (M.program.start (i.val : Word w)) cfg pre
+ noChoice : choiceBits pre = []
+ noWrite : after m pre = m
+ prefixReads : Reads (allow₀) pre
+ persistent : cfg.persistent = (M.program.start (i.val : Word w)).persistent
+ atRoot : cfg.pc = A.dfsPC 0
+ /-- DFS stack top at the start of the ordinal's local traversal. -/
+ top : ℕ
+ stack : Represents cfg.privateMem top [(((trees₀) ((ord₀).entries i)).address : Word w)]
+ endTop : top + 1 = endAddr
+ sp : cfg.reg (A.dfs 5) = (top : Word w)
+ endReg : cfg.reg (A.dfs 6) = (endAddr : Word w)
+ one : cfg.reg (A.dfs 3) = 1
+ zero : ∀ l, privateHistogram order src (scratch endAddr cfg.privateMem) l = 0
+ prepared : valid [⟨((trees₀) ((ord₀).entries i)).address,
+ packed (Y) ((ord₀).entries i) (half ((ord₀).entries i))⟩] (scratch endAddr cfg.privateMem)
+ rows : AllRows w m B.recordLimit rowBase rowBase (selectedLayers B κ hκ T hT X z)
+ space : rowBase + words B.recordLimit (selectedLayers B κ hκ T hT X z) ≤ (head₀).val
+ hfit : (head₀).val + 31 < 2^w
+ capacity : B.growthConstant^T ≤ endAddr
+ above : endAddr ≤ src
+ hsrc : src + g < 2^w
+ hdst : base + grammar + g < 2^w
+ cells : ∀ j : Fin g, (allow₀) (base + grammar + j.val)
+ hbase : M.publicData 4 = (base : Word w)
+ hgrammar : M.publicData 5 = (grammar : Word w)
+ hg : M.publicData 9 = (g : Word w)
+ /-- Upper bound on the instruction ticks assigned to this vertex visit. -/
+ maxTicks : ℕ
+ small : ∀ j, cost j → j.trace.length ≤ maxTicks
+ room : pre.length + (15 + maxTicks) * (chain₀).occurrences (fun _ => 1) ((ord₀).entries i) + 7*g+46 ≤ cap
+
+variable {B κ hκ T hT X z rowBase A M base grammar order P half}
+variable {cap : ℕ} {m : Memory w} {i : Fin (siteOrder ((B.execute κ hκ T hT X).finalState z)).length}
+
+local notation "rows₀" => OrdinalRows B κ hκ T hT X z rowBase A M base grammar order P half cap m i
+
+/-- The complete native call and its probes, indexed by the selected
+preorder visits. This retains the individual role costs for physical charging. -/
+theorem OrdinalRows.report (q : rows₀) (linked : Contains A M) (x : (selected₀).Choice i) :
+ ∃ rep, execute M.program cap (M.program.start (i.val : Word w)) m ((selected₀).encode i x) = some rep ∧
+ rep.result = some ((i.val + 1 : ℕ) : Word w) ∧ choiceBits rep.events = (selected₀).encode i x ∧
+ after m rep.events = Counters.addHistogram base grammar ((selected₀).powers i x) m ∧
+ Reads (allow₀) rep.events ∧ rep.events.length + 31 ≤ cap ∧
+ ∃ native : List (VisitPath w q.endAddr), native.length = ((trees₀) ((ord₀).entries i)).preorder.length ∧
+ (∀ j ∈ native, q.cost j) ∧ countProbes rep.events + 1 =
+ countProbes q.pre + 3*native.length + (native.map (fun j => countProbes j.trace)).sum + 2*g := by
+ obtain ⟨rep,run,next,bits,flush,read,room,native⟩ :=
+ active_occurrence B κ hκ T hT X z rowBase A M m q.G q.offset base grammar q.src order P q.valid q.domain
+ q.handlers q.cost linked q.selected ((ord₀).entries i) (half ((ord₀).entries i))
+ (M.program.start (i.val : Word w)) q.cfg q.pre q.pref q.noChoice q.noWrite q.prefixReads q.persistent
+ q.atRoot q.top q.stack q.endTop q.sp q.endReg q.one q.zero q.prepared q.rows q.space q.hfit q.capacity
+ q.above q.hsrc q.hdst q.cells q.hbase q.hgrammar q.hg q.maxTicks cap q.small q.room x
+ refine ⟨rep,run,?_,bits,flush,read,room,native⟩
+ change rep.result = some ((i.val : Word w) + 1) at next
+ simpa only [Nat.cast_add, Nat.cast_one] using next
+
+/-- The selected call has room for its physical terminal dispatch and reads
+only worker addresses. -/
+theorem OrdinalRows.emit (q : rows₀) (linked : Contains A M) (x : (selected₀).Choice i) :
+ ∃ rep, execute M.program cap (M.program.start (i.val : Word w)) m ((selected₀).encode i x) = some rep ∧
+ rep.result = some ((i.val + 1 : ℕ) : Word w) ∧
+ after m rep.events = Counters.addHistogram base grammar ((selected₀).powers i x) m ∧
+ Reads (allow₀) rep.events ∧ rep.events.length + 1 ≤ cap-30 := by
+ obtain ⟨rep,run,next,_,flush,read,room,_⟩ := q.report linked x
+ exact ⟨rep,run,next,flush,read,by omega⟩
+
+/-- Decode arbitrary actual tapes on the selected row image. -/
+theorem OrdinalRows.recover (q : rows₀) (linked : Contains A M) (bs : List Bool) (rep : Report w)
+ (run : execute M.program cap (M.program.start (i.val : Word w)) m bs = some rep) :
+ ∃ x : (selected₀).Choice i, bs = (selected₀).encode i x := by
+ exact (active_recover B κ hκ T hT X z rowBase A M m q.G q.offset q.src order P q.valid q.domain q.handlers
+ q.cost linked q.selected ((ord₀).entries i) (half ((ord₀).entries i))
+ (M.program.start (i.val : Word w)) q.cfg q.pre q.pref q.atRoot q.top q.stack q.endTop q.sp q.endReg q.one
+ q.prepared q.rows q.space q.hfit q.capacity cap bs rep run).exists
+
+variable (B κ hκ T hT X z rowBase A M base grammar order P half)
+
+/-- Discharge both the ascending interpreter and its active-report checks
+from the local selected rows and their deterministic root preparations. -/
+theorem selectedCalls (ref : Memory w) (linked : Contains A M)
+ (localRows : ∀ i m, VertexFrame.Linked (head₀) base grammar g ref i.val m →
+ Nonempty (OrdinalRows B κ hκ T hT X z rowBase A M base grammar order P half cap m i)) :
+ ActiveCalls (selected₀) M.program cap base grammar (VertexFrame.Linked (head₀) base grammar g ref) ∧
+ ∀ i m, VertexFrame.Linked (head₀) base grammar g ref i.val m → ∀ (x : (selected₀).Choice i) r,
+ execute M.program cap (M.program.start (i.val : Word w)) m ((selected₀).encode i x) = some r →
+ Reads (allow₀) r.events ∧ r.events.length + 1 ≤ cap-30 := by
+ constructor
+ · constructor
+ · intro i m frame x
+ obtain ⟨q⟩ := localRows i m frame
+ obtain ⟨r,call,next,flush,_,_⟩ := q.emit linked x
+ exact ⟨r,call,next,flush⟩
+ · intro i m frame bits r run
+ obtain ⟨q⟩ := localRows i m frame
+ exact q.recover linked bits r run
+ · intro i m frame x
+ exact frame.preserve _
+ · intro i m frame x r run
+ obtain ⟨q⟩ := localRows i m frame
+ obtain ⟨out,call,_,_,support,room⟩ := q.emit linked x
+ obtain rfl := Option.some.inj (run.symm.trans call)
+ exact ⟨support,room⟩
+
+local notation "image₀" => segments geometry rootFields leaf shrink refresh
+
+/-- Construct the native worker frame of this selected compressor branch.
+All successful source and physical paths are classified by the local rows. -/
+theorem selectedWorkerFrame (F : DescriptorSpace.Shape) (limit : ℕ) (ops : Fin 11 → Word w)
+ (ref src phy : Memory w)
+ (localRows : ∀ i m, VertexFrame.Linked (TerminalLink.header ops) base grammar g ref i.val m →
+ Nonempty (OrdinalRows B κ hκ T hT X z rowBase (placement image₀) ((template image₀).instantiate w ops)
+ base grammar order P half cap m i))
+ (room : (TerminalLink.header ops).val + 32 ≤ 2^w) (clock : 45 ≤ cap)
+ (below : base+grammar+g ≤ (TerminalLink.header ops).val)
+ (sites : ref (TerminalLink.header ops + 7).val = ((ord₀).length : Word w))
+ (hs : VertexFrame.Linked (TerminalLink.header ops) base grammar g ref 0 src)
+ (hp : VertexFrame.Linked (TerminalLink.header ops) base grammar g ref 0 phy)
+ (agree : Agree (workerCell (TerminalLink.header ops)) src phy) :
+ ActiveCalls (selected₀) (((template image₀).instantiate w ops).program) cap base grammar
+ (VertexFrame.Linked (TerminalLink.header ops) base grammar g ref) ∧
+ WorkerFrame (TerminalProgram.workers F limit image₀) ops cap (.resume Stage.vertices 0) src phy := by
+ obtain ⟨active,checks⟩ :=
+ selectedCalls B κ hκ T hT X z rowBase (placement image₀) ((template image₀).instantiate w ops) base grammar
+ order P half ref (template_contains image₀ ops) localRows
+ exact ⟨active, ordinalWorkerFrame F limit ref src phy active
+ (template_closes (by omega) (linked_finalSites ref room below sites)) room clock checks hs hp agree⟩
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSelectedReport.lean b/lean/OAI/Computability/VPVNP/PairVertexSelectedReport.lean
new file mode 100644
index 0000000000..a3127ec55e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSelectedReport.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.PairVertexSiteReport
+import OAI.Computability.VPVNP.PairTreeEmissions
+
+/-! # One native report per occurrence, from the local row proofs -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM DFS LocalHistory NetworkKernel NodeArguments TreeDecode
+open CompressorRecords.SourceTransport (Reads)
+open scoped Fin.CommRing
+
+variable {geometry rootFields leaf shrink refresh : Segment} {p regs W endAddr g : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p regs)
+ (M : Machine W p regs 11)
+ {R : Type*} [CommRing R] {L : Type} [Fintype L] {f : L → R} {N Y : Network}
+
+/-- The rows of each role return to the DFS header and preserve external
+data. Their public read footprints and cost facts can depend on their
+recorded addresses. -/
+def JobGuard (m : Memory W) (allow : ℕ → Prop) (cost : VisitPath W endAddr → Prop)
+ (j : VisitPath W endAddr) : Prop :=
+ j.Linked M (A.core (.roleBase 0)) (A.dfsPC 3) A.dfs m ∧ after m j.trace = m ∧
+ Reads allow j.trace ∧ cost j
+
+/-- Only the individual kernel and leaf effects are inputs here. The native
+preorder, monomial multiplicities, final private histogram, scratch frame,
+external read footprint and physical burst result are assembled from them. -/
+theorem occurrence_report (linked : Contains A M) (m : Memory W) (allow : ℕ → Prop)
+ (cost : VisitPath W endAddr → Prop) (valid : List Packet → Scratch W endAddr → Prop)
+ (order : Fin g ≃ L) (base grammar src : ℕ) (G offset : Word W)
+ (c : TermChain R N Y) (r : ChainParsers f c) (ptr : RowPointers c) (layers : PacketLayers c)
+ (P : SiteParsers f N) (input : Packets N) (leaves : N.Site → ℕ × ℕ)
+ (initial : Emits valid (privateHistogram order src) (JobGuard A M m allow cost) P input (leafJobs P leaves))
+ (localEffects : EmissionLayers valid (privateHistogram order src) (JobGuard A M m allow cost) c r ptr layers input)
+ (v : Y.Site) (z : Y.Half v) (x : ((finalParsers c r P).witnesses v z).Choice)
+ (cfg : Config W p regs) (here : cfg.pc = A.dfsPC 0) (top : ℕ) (root : Word W)
+ (stack : Represents cfg.privateMem top [root]) (length : top+1=endAddr)
+ (sp : cfg.reg (A.dfs 5) = (top : Word W)) (endReg : cfg.reg (A.dfs 6) = (endAddr : Word W))
+ (one : cfg.reg (A.dfs 3) = 1) (control : List (Event W))
+ (visits : Visits m endAddr [root]
+ (((chainTrees c r ptr (fun u => leafTree (leaves u))) v).preorder.map (fun n : ℕ => (n : Word W))) control)
+ (prepared : valid [finalPackets c layers input v z] (scratch endAddr cfg.privateMem))
+ (geometryEnd : ∀ s, valid [] s → ResidentGeometry s G offset (src : Word W))
+ (zero : ∀ l, privateHistogram order src (scratch endAddr cfg.privateMem) l = 0)
+ (ctrl : Reads allow control) (cells : ∀ i : Fin g, allow (base+grammar+i.val))
+ (above : endAddr ≤ src) (hsrc : src+g < 2^W) (hdst : base+grammar+g < 2^W)
+ (hbase : M.publicData 4 = (base : Word W)) (hgrammar : M.publicData 5 = (grammar : Word W))
+ (hg : M.publicData 9 = (g : Word W)) :
+ let final := finalParsers c r P
+ let semantic := vertexJobs c r ptr P leaves v z x
+ let powers := fun i : Fin g => (final.witnesses v z).exponents x (order i)
+ ∃ (native : List (VisitPath W endAddr)) (rep : Report W),
+ Effects valid (privateHistogram order src) (JobGuard A M m allow cost)
+ (scratch endAddr cfg.privateMem) [] semantic native ∧
+ rep.result = some (cfg.persistent+1) ∧ choiceBits rep.events = (final.read v z).encode x ∧
+ after m rep.events = Counters.addHistogram base grammar powers m ∧
+ rep.events.length = control.length + (native.map fun j => j.trace.length).sum + 7*g+14 ∧
+ countProbes rep.events = countProbes control + (native.map fun j => countProbes j.trace).sum + 2*g ∧
+ Reads allow rep.events ∧
+ ∀ extra, execute M.program (extra+rep.events.length+1) cfg m ((final.read v z).encode x) = some rep := by
+ intro final semantic powers
+ obtain ⟨native,paths⟩ := chain_emits valid (privateHistogram order src) (JobGuard A M m allow cost) c r ptr
+ layers P input (leafJobs P leaves) initial localEffects v z x [] _ prepared
+ obtain ⟨rep,result,bits,after,time,probes,reads,run⟩ :=
+ vertex_report_supported A M linked final (chainTrees c r ptr (fun u => leafTree (leaves u)))
+ (vertexJobs c r ptr P leaves) (vertexJobs_spec c r ptr P leaves) v z x order base grammar src G offset m
+ visits native paths.realized (fun j hj => (paths.framed j hj).1) (fun j hj => (paths.framed j hj).2.1)
+ cfg here top stack length sp endReg one paths.ready (geometryEnd _ paths.remaining) zero above hsrc hdst
+ hbase hgrammar hg
+ exact ⟨native,rep,paths,result,bits,after,time,probes,
+ reads allow ctrl (fun j hj => (paths.framed j hj).2.2.1) cells,run⟩
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSelectedRoleLayout.lean b/lean/OAI/Computability/VPVNP/PairVertexSelectedRoleLayout.lean
new file mode 100644
index 0000000000..95dccc31d2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSelectedRoleLayout.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.PairVertexRootEntry
+
+/-! # The selected argument region and role bank in the current site memory -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.TerminalProgram
+
+open BurstRAM PrivateRAM LiveProgram LiveProgram.PairStages.Group.Auxiliary
+open Compression CompressorRecords LocalHistory NodeArguments TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+variable {k K : Type} [_root_.Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+ (G : PairStages.Group) (n labels : ℕ) (baseBits laneBits : ℕ) (ord : ℕ)
+
+local notation "pub" => terminalOperands G
+local notation "hdr" => vertexHeader G
+local notation "tags" => selected B f hf T hT X z
+variable {layout : DescriptorSpace.Layout}
+local notation "base" => DescriptorSpace.endAddress layout
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "width" => State.totalWidth (Y)
+local notation "size" => tagWords B.recordLimit (tags)
+local notation "offset" => (((size) + (width) : ℕ) : Word G.w)
+local notation "area" => TerminalLayout.privateRegions (slotDegree S) n ((base) + (size)) labels
+variable {calendar reference : Memory G.w} (m : Memory G.w)
+ {bits : Fin ((B.execute f hf T hT X).finalState z).totalWidth → Bool}
+ {tab : Fin layout.shape.tables}
+ (pack : VertexPacked G layout B.recordLimit (selected B f hf T hT X z)
+ ((B.execute f hf T hT X).finalState z).totalWidth)
+ (entry : VertexEntry B f hf T hT X z layout tab baseBits laneBits (terminalOperands G)
+ calendar reference bits)
+ (later : LinkedVertexMemory G reference ord m)
+
+include pack entry later in
+/-- Both role offsets and the complete private geometry remain those of
+the selected physical table after earlier vertices have flushed. -/
+theorem VertexEntry.role_layout (length : (pub 6).val = n) (count : (pub 9).val = labels) :
+ NativeFrame.fromHeader (slotDegree S) pub hdr m = (area) ∧
+ m (hdr + 14).val = (offset) ∧
+ Reads G.w (m) ((offset).val) B.recordLimit (base) (tags) := by
+ have rowEq : (size) = words B.recordLimit (selectedLayers B f hf T hT X z) :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ have room := pack.room
+ have bound := pack.arena
+ have addr : (hdr + 14).val = (hdr).val + 14 := by
+ change ((hdr).val + 14 % (2 ^ G.w)) % (2 ^ G.w) = (hdr).val + 14
+ rw [Nat.mod_eq_of_lt (by omega : 14 < 2 ^ G.w), Nat.mod_eq_of_lt (by omega)]
+ have role := pack.header later 14 (by decide) (by decide)
+ change m (hdr + 14).val = reference (hdr + 14).val at role
+ refine ⟨?_, role.trans ?_, ?_⟩
+ · rw [rowEq]
+ exact entry.selected_regions pack later n labels length count
+ · rw [addr, rowEq]
+ exact entry.offset
+ · rw [Fin.val_natCast, Nat.mod_eq_of_lt (by omega : (size) + (width) < 2 ^ G.w)]
+ apply pack.roleWords later
+ rw [rowEq]
+ exact entry.roles
+
+end PairSimulation.TerminalProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSelectedRoles.lean b/lean/OAI/Computability/VPVNP/PairVertexSelectedRoles.lean
new file mode 100644
index 0000000000..c4cb9887a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSelectedRoles.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PairVertexActiveOccurrence
+import OAI.Computability.VPVNP.PairVertexFrameData
+import OAI.Computability.VPVNP.PairSelectedPacketFormat
+
+/-! # Dispatching the three installed handlers on true selected packets -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM Compression DFS LocalHistory NodeArguments TraversalRows TreeDecode
+open CompressorRecords SourceTransport LeafSourceLoad NetworkKernel
+open scoped Fin.CommRing
+open private collected_checks from OAI.Computability.VPVNP.PairSelectedLevelChecks
+
+variable {w endAddr : ℕ}
+
+/-- The physical role tag chooses the local input condition at this
+descriptor address. All three choices share the initialized geometry bank. -/
+def roleDomain (R : LeafArena.Regions) (data : Fin 10 → Word w) (offset : Word w) (vals : Static 34 → Word w)
+ (domains : NodeDispatch.Role → Word w → Scratch w endAddr → Prop) (m : Memory w)
+ (node : Word w) (saved : Scratch w endAddr) : Prop :=
+ VertexFrameData R data offset vals saved ∧ domains (NodeDispatch.role (m (offset+node).val)) node saved
+
+private theorem exactOn_mono {p r k : ℕ} {M : Machine w p r k} {pc ret : Fin p} {regs : Fin 9 ↪ Fin r}
+ {m : Memory w} {domain domain' : Word w → Scratch w endAddr → Prop} {hook : HookParser w endAddr}
+ (checked : hook.ExactOn domain M pc ret regs m) (small : ∀ a s, domain' a s → domain a s) :
+ hook.ExactOn domain' M pc ret regs m where
+ success a s h := checked.success a s (small _ _ h)
+ reject a bits c top pending h := checked.reject a bits c top pending (small _ _ h)
+
+variable {k K : Type*} [Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (κ : B.Entry → K) (hκ : B.IsSolution κ) {lanes : ℕ}
+ (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute κ hκ T hT X).Choices) (rowBase : ℕ)
+ {geometry rootFields leaf shrink refresh : Segment} {p r g : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r) (M : Machine w p r 11)
+ (m : Memory w) (R : LeafArena.Regions) (offset : Word w) (data : Fin 10 → Word w) (vals : Static 34 → Word w)
+ (order : Fin g ≃ B.Entry) (P : SiteParsers κ X.network) (desc : ℕ → List ℕ) (nodeCap limit : ℕ)
+ (handlers : NodeDispatch.Role → HookParser w endAddr) (domains : NodeDispatch.Role → Word w → Scratch w endAddr → Prop)
+ (cost : VisitPath w endAddr → Prop)
+
+local notation "head₀" => TerminalLink.header (Machine.publicData M)
+local notation "stable₀" => VertexFrameData R data offset vals
+local notation "format₀" => SelectedPacketFormat B κ hκ T hT X z rowBase
+local notation "hist₀" => privateHistogram order (LeafArena.Regions.histBase R)
+local notation "valid₀" => Budgeted R.arguments (format₀) (stable₀) desc (hist₀) nodeCap limit
+local notation "domain₀" => roleDomain R data offset vals domains m
+local notation "hook₀" => dispatcher handlers m offset
+local notation "guard₀" => JobGuard A M m (TerminalLink.workerCell (head₀)) cost
+local notation "leaves₀" => sitePointers B.recordLimit rowBase (siteOrder X)
+local notation "leafPackets₀" => (fun u y => Packet.mk (Prod.fst ((leaves₀) u)) (packed X u y))
+
+/-- Exact local role runs at each genuine typed row supply all forward and
+inverse obligations for the ascending worker. A role may reject on any
+suffix or input half-buffer permitted by its own prepared row. -/
+theorem SelectedChecks.ofRoleRows
+ (ready : ∀ (q : Packet) s, stable₀ s → format₀ q → q.Fits R.arguments w endAddr → q.Stored R.arguments s →
+ (∀ l, hist₀ s l + nodeCap ≤ limit) → domains (NodeDispatch.role (m (offset+(q.node : Word w)).val)) (q.node : Word w) s)
+ (roleRuns : ∀ role, (handlers role).ExactOn (domains role) M (A.entry (rolePart role)) (A.dfsPC 3) A.dfs m)
+ (cursor : Subtrees (hook₀) (valid₀) P (fun u => leafTree ((leaves₀) u)) (leafPackets₀) ∧
+ Emits (valid₀) (hist₀) (guard₀) P (leafPackets₀) (leafJobs P (leaves₀)))
+ (levels : let passes := executeLevels B κ hκ T hT X z
+ let tags := TraversalRoles.selected B κ hκ T hT X z
+ ∀ i : Fin passes.length, LevelChecks B κ hκ (hook₀) (valid₀) (hist₀) (guard₀) B.recordLimit
+ (TraversalRoles.layerBase B.recordLimit rowBase tags i.val) passes[i]) :
+ SelectedChecks B κ hκ T hT X z rowBase A M m ((NativeFrame.frameBase R : ℕ) : Word w) offset
+ R.histBase order P (valid₀) (domain₀) handlers cost := by
+ refine ⟨fun _ _ h => h.1.resident,fun _ h => h.frontier.frame.resident,
+ budgeted_headDomain _ (fun q s frame type fits stored room => ⟨frame,ready q s frame type fits stored room⟩),
+ ?_,cursor.1,cursor.2,?_⟩
+ · intro role
+ exact exactOn_mono (roleRuns role) (fun _ _ h => h.2 ▸ h.1.2)
+ · let E := B.execute κ hκ T hT X
+ let readers := repeatReaders (blockReaders B κ hκ) _ T lanes (Nat.add_sub_of_le hT).symm X
+ let origins := executeOrigins B κ hκ T hT X
+ exact collected_checks B κ hκ (hook₀) (valid₀) (hist₀) (guard₀) E _ readers origins (B.records κ hκ T hT X)
+ z B.recordLimit rowBase (execute_originReaders B κ hκ T hT X)
+ (selected_indexed B κ hκ (hook₀) (valid₀) (hist₀) (guard₀) T hT X z rowBase levels)
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexShrinkAtSite.lean b/lean/OAI/Computability/VPVNP/PairVertexShrinkAtSite.lean
new file mode 100644
index 0000000000..d65b0acdd0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexShrinkAtSite.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.PairVertexShrinkFamilies
+import OAI.Computability.VPVNP.PairShrinkPhysicalSiteBank
+import OAI.Computability.VPVNP.PairShrinkTraversalAtVertex
+import OAI.Computability.VPVNP.PairVertexRootEntry
+import OAI.Computability.VPVNP.PairTerminalNativeTable
+
+/-! # The shrinking handler at one linked vertex of the live pair machine -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open BurstRAM PrivateRAM DFS Compression CompressorRecords DescriptorSpace LocalHistory
+open TraversalRows TraversalRoles ShrinkRoleDirectory TerminalProgram NativeFrame NodeArguments
+open LiveProgram PairStages PairStages.Group.Auxiliary
+open scoped Fin.CommRing
+
+variable {k K : Type} [Field k] [CommRing K] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes T : ℕ} (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) {G : Group} {n limit : ℕ}
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence BlockProgram.layout
+ BlockSchedule.Templates.execute StateExecution.finalState executeLevels ShrinkRole.canonicalFamily
+ ShrinkRole.parentParser ShrinkRole.canonicalActions
+set_option quotPrecheck false
+
+local notation "pub₀" => terminalOperands G
+local notation "layout₀" => BlockProgram.layout B (pub₀ 2).val X.positions T
+local notation "passes₀" => executeLevels B f hf T hT X z
+local notation "tags₀" => selected B f hf T hT X z
+local notation "Y₀" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "base₀" => endAddress (layout₀)
+local notation "rows₀" => tagWords B.recordLimit (tags₀)
+local notation "rowEnd₀" => (base₀)+words B.recordLimit (selectedLayers B f hf T hT X z)
+local notation "count₀" => Fintype.card B.Entry
+local notation "R₀" => TerminalLayout.privateRegions (slotDegree S) n ((base₀)+(rows₀)) (count₀)
+local notation "off₀" => (((rows₀)+(Y₀).totalWidth : ℕ) : Word G.w)
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables} {baseBits laneBits ordinal : ℕ}
+ {calendar reference phy : Memory G.w} {wireBits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n) (executeLevels B f hf T hT X z) calendar)
+ (entry : VertexEntry B f hf T hT X z (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ table baseBits laneBits (terminalOperands G) calendar reference wireBits)
+ (packed : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (selected B f hf T hT X z) (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ordinal phy)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+ (fits : ∀ (x : ShrinkSite (executeLevels B f hf T hT X z)) motif, ShrinkRole.canonicalFits B x.occurrence.i x.occurrence.state
+ x.occurrence.selection (w := G.w) (Fintype.card B.Entry) n ((endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T))+words B.recordLimit (selectedLayers B f hf T hT X z))
+ (layerBase B.recordLimit (endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T)) (selected B f hf T hT X z) x.val.1.val) limit motif)
+
+local notation "bank₀" => ShrinkRole.physicalSiteBank B f hf hT X z history entry packed frame width fits
+local notation "H₀" => vertexHeader G
+local notation "data₀" => leafWords (slotDegree S) (pub₀) (H₀) (off₀) phy
+
+variable (p q : ℕ) (order : B.Entry ≃ Fin (Fintype.card B.Entry))
+local notation "seg₀" => nativeSegments B G.constants p q order
+local notation "V₀" => placement (seg₀)
+local notation "M₀" => (template (seg₀)).instantiate G.w (pub₀)
+
+set_option maxHeartbeats 2000000 in
+/-- The current eleven-operand image executes the actual bank of selected
+shrinking sites. Its directory locator, length, geometry and cache word all
+come from the linked vertex memory and the fixed public operands. -/
+theorem nativeShrink_at_vertex (size : (pub₀ 6).val = n) (labels : (pub₀ 9).val = (count₀))
+ {vals : LeafSourceLoad.Static 34 → Word G.w} {counts : Scratch G.w n → B.Entry → ℕ}
+ {nodeCap wordLimit : ℕ}
+ (facts : ∀ (x : ShrinkSite (passes₀)), ShrinkRole.CanonicalSiteData ((bank₀) x) (M₀) f hf T hT X z
+ x.val.1 (siteId B f hf T hT X z x) (base₀))
+ (maps : ∀ (x : ShrinkSite (passes₀)) (parent : x.occurrence.nextState.network.Half x.occurrence.site),
+ ShrinkRole.CanonicalMapData ((bank₀) x) (H₀) parent) :
+ (shrinkHandler X B.recordLimit (base₀) (passes₀) (bank₀) order).ExactOn
+ (Domain X B.recordLimit (base₀) (passes₀) (R₀) (data₀) (off₀) vals counts nodeCap wordLimit .shrink)
+ (M₀) ((V₀).entry .shrink) ((V₀).dfsPC 3) (V₀).dfs phy := by
+ have rowsEq : (rows₀) = words B.recordLimit (selectedLayers B f hf T hT X z) :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ have reg := entry.selected_regions packed frame n (count₀) size labels
+ rw [← rowsEq] at reg
+ have cache : (data₀) 8 = ((R₀).cacheBase : Word G.w) := by
+ change ((fromHeader (slotDegree S) (pub₀) (H₀) phy).cacheBase : Word G.w) = _
+ rw [reg]
+ have length : (data₀) 9 = (n : Word G.w) := by
+ change (pub₀) 6 = (n : Word G.w)
+ rw [← size]
+ exact (Fin.cast_val_eq_self _).symm
+ have bankRegion (x : ShrinkSite (passes₀)) :
+ TerminalLayout.privateRegions (slotDegree S) n ((bank₀) x).rowEnd (count₀) = (R₀) := by
+ change TerminalLayout.privateRegions (slotDegree S) n (rowEnd₀) (count₀) = (R₀)
+ rw [rowsEq]
+ have bankMemory (x : ShrinkSite (passes₀)) : ((bank₀) x).mem = phy := rfl
+ obtain ⟨ds,resident⟩ := entry.shrinkLocator packed frame
+ have checked := selectedFamilies B f hf T hT X z order (VertexGeometry.segment G.constants (slotDegree S) p q)
+ TerminalRootGather.segment LeafRole.segment
+ (RefreshVertex.refreshSegment B (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride order)
+ (V₀) (M₀) (template_contains (seg₀) (pub₀)) (bank₀) (base₀) (R₀) (data₀) (off₀) vals counts
+ nodeCap wordLimit phy ds resident bankRegion bankMemory cache length (H₀) facts maps
+ have wordSpace : 1 < 2^G.w := by have room := packed.room; omega
+ have live : 0 < G.w := by
+ by_contra! zero
+ rw [show G.w=0 by omega] at wordSpace
+ norm_num at wordSpace
+ have endFit : layerBase B.recordLimit (base₀) (tags₀) ((passes₀).length+1) ≤ 2^G.w := by
+ have len : (tags₀).length = (passes₀).length+1 := by simp [selected]
+ rw [← len,layerBase,List.take_length]
+ change (base₀)+(rows₀) ≤ 2^G.w
+ have arena := packed.arena
+ have top := packed.room
+ omega
+ exact nativeShrink X B.recordLimit (base₀) (passes₀) (R₀) (data₀) (off₀) vals counts
+ nodeCap wordLimit (bank₀) order (M₀) ((V₀).entry .shrink) ((V₀).dfsPC 3) (V₀).dfs phy
+ live endFit (fun x => congrArg LeafArena.Regions.arguments (bankRegion x)) checked
+
+end PairSimulation.VertexImage.RoleDomains
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexShrinkFamilies.lean b/lean/OAI/Computability/VPVNP/PairVertexShrinkFamilies.lean
new file mode 100644
index 0000000000..08d786003d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexShrinkFamilies.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PairShrinkSiteOrdinal
+import OAI.Computability.VPVNP.PairVertexRoleNativeShrink
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalExecution
+import OAI.Computability.VPVNP.PairShrinkCallFrameStores
+
+/-! # Canonical shrinking families at the actual selected directory addresses -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open BurstRAM PrivateRAM DFS Compression CompressorRecords LocalHistory TraversalRows TraversalRoles
+open ShrinkRoleDirectory ShrinkVertexImage TraversalControllerInputs NodeArguments TreeDecode
+open scoped Fin.CommRing
+
+set_option quotPrecheck false
+attribute [local irreducible] ShrinkRoleDirectory.occurrence BlockProgram.layout
+ BlockSchedule.Templates.execute StateExecution.finalState executeLevels ShrinkRole.canonicalFamily
+
+variable {k : Type} [Field k] {S : BlockSchedule k} (B : S.Templates)
+ {K : Type*} [CommRing K] (f : B.Entry → K) (hf : B.IsSolution f)
+ {lanes : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (branch : (B.execute f hf T hT X).Choices)
+
+local notation "passes₀" => executeLevels B f hf T hT X branch
+local notation "leaf₀" => TaggedLayer.mk (leafLayer (siteOrder X)) Role.cursor
+local notation "labels₀" => Fintype.card B.Entry
+
+variable {w n p r : ℕ} (ord : B.Entry → Fin (Fintype.card B.Entry))
+ (geometry rootFields leaf refresh : Segment)
+ (V : Placement (vertexParts B ord geometry rootFields leaf refresh) p r)
+ (M : Machine w p r 11) (installed : Contains V M)
+ (sites : SiteBank (w := w) (n := n) (t := (Fintype.card B.Entry)) (executeLevels B f hf T hT X branch))
+ (base : ℕ) (R : LeafArena.Regions) (data : Fin 10 → Word w)
+ (offset : Word w) (vals : LeafSourceLoad.Static 34 → Word w)
+ (hist : Scratch w n → B.Entry → ℕ) (nodeCap limit : ℕ) (m : Memory w)
+
+local notation "regAt" => (fun x : ShrinkSite (passes₀) => TerminalLayout.privateRegions (slotDegree S) n (sites x).rowEnd (labels₀))
+local notation "rowAt" => (fun x : ShrinkSite (passes₀) => ShrinkRoleDirectory.address B.recordLimit base (leaf₀) (passes₀) x.val)
+local notation "par₀" => Parent X B.recordLimit base (passes₀) R data offset vals hist nodeCap limit
+
+include installed in
+set_option maxHeartbeats 2500000 in
+/-- The published native level and map rows instantiate the exact family for
+every independent parent. Its private handoff reads the common geometry
+already present in the popped packet's scratch memory. -/
+theorem selectedFamilies {raw : Memory w} {publicH first pitch roleBase : ℕ}
+ (ds : (j : Fin (passes₀).length) → LevelDirectory (passes₀)[j] raw base)
+ (resident : Resident M.publicData m publicH first pitch roleBase B.recordLimit base (leaf₀)
+ (levelFibers (passes₀) ds))
+ (regionEq : ∀ x, (regAt) x = R) (memEq : ∀ x, (sites x).mem = m)
+ (cache : data 8 = (R.cacheBase : Word w)) (length : data 9 = (n : Word w)) (H : Word w)
+ (facts : ∀ (x : ShrinkSite (passes₀)), ShrinkRole.CanonicalSiteData (sites x) M f hf T hT X branch x.val.1
+ (siteId B f hf T hT X branch x) base)
+ (maps : ∀ (x : ShrinkSite (passes₀)) (parent : x.occurrence.nextState.network.Half x.occurrence.site),
+ ShrinkRole.CanonicalMapData (sites x) H parent) :
+ ∀ (x : ShrinkSite (passes₀)) (parent : x.occurrence.nextState.network.Half x.occurrence.site),
+ (ShrinkRole.canonicalFamily (sites x) ord f hf parent).ExactOn
+ (fun node s => node.val = (rowAt) x ∧ (par₀) x parent s) M (V.entry .shrink) (V.dfsPC 3) V.dfs m := by
+ intro x parent
+ let P := (par₀) x parent
+ have fd := facts x
+ have source : Resident M.publicData (sites x).mem publicH first pitch roleBase B.recordLimit base (leaf₀)
+ (levelFibers (passes₀) ds) := by rw [memEq x]; exact resident
+ have prepare (priv : Word w → Word w) (h : P (scratch n priv)) :
+ ShrinkCallFrameLive.Stored ((regAt) x) n priv := by
+ rw [regionEq x]
+ exact ShrinkCallFrameLive.of_vertex h.frame cache length ((regionEq x) ▸ fd.above) ((regionEq x) ▸ fd.frameRoom)
+ have packet s (h : P s) := h.stored
+ have addrEq := rowAddress_siteId B f hf T hT X branch base x
+ have regEq : TerminalLayout.privateRegions (slotDegree S) n (sites x).rowEnd (Fintype.card B.Entry) = R :=
+ regionEq x
+ have run := ShrinkRole.canonicalFamily_exactOn (sites x) ord geometry rootFields leaf refresh V M
+ f hf T hT X branch x.val.1 (siteId B f hf T hT X branch x) base ds source installed fd H parent
+ (maps x parent) P prepare (fun s h => by rw [fd.siteAddr,← addrEq,regEq]; exact packet s h)
+ simpa only [← addrEq,memEq x,P] using run
+
+end PairSimulation.VertexImage.RoleDomains
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSiteReport.lean b/lean/OAI/Computability/VPVNP/PairVertexSiteReport.lean
new file mode 100644
index 0000000000..9332e734e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSiteReport.lean
@@ -0,0 +1,166 @@
+import OAI.Computability.VPVNP.PairVertexSiteSegments
+import OAI.Computability.VPVNP.PairSimulationVertexJobs
+import OAI.Computability.VPVNP.PairCounterReadFootprint
+
+/-!
+# The actual report of a selected final vertex
+
+The DFS follows the chosen jobs, the physical flush reads their accumulated
+private histogram, and the last four rows return the next persistent ordinal.
+The resulting external memory adds precisely that vertex's monomial powers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM DFS LocalHistory NodeArguments NetworkKernel
+open CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+open private realized_counts realized_bits realized_addresses from OAI.Computability.VPVNP.PairSimulationVertexJobs
+open private probes_append from OAI.Computability.VPVNP.PairSimulationDFSHooks
+
+variable {geometry rootFields leaf shrink refresh : Segment} {p r W endAddr g : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r)
+ (M : Machine W p r 11)
+ {Label : Type} [Fintype Label] {R : Type*} [CommRing R] {f : Label → R} {N : Network}
+
+/-- Read a typed counter from the fixed private histogram interval. -/
+def privateHistogram (order : Fin g ≃ Label) (src : ℕ) (s : Scratch W endAddr) (label : Label) : ℕ :=
+ (rawScratch s ((src + (order.symm label).val : ℕ) : Word W)).val
+
+/-- On the genuine assembled image every realized site occurrence produces
+one exact successful report. Its external effect, choices and costs are
+the ones of this occurrence and its actual linked hook calls. -/
+theorem vertex_report_supported (linked : Contains A M) (P : SiteParsers f N) (trees : N.Site → VertexTree)
+ (jobs : JobsFor P) (spec : JobsSpec P trees jobs) (v : N.Site) (z : N.Half v)
+ (x : (P.witnesses v z).Choice) (order : Fin g ≃ Label)
+ (base grammar src : ℕ) (G offset : Word W) (m : Memory W)
+ {pending : List (Word W)} {control : List (Event W)}
+ (visits : Visits m endAddr pending ((trees v).preorder.map (fun n : ℕ => (n : Word W))) control)
+ (native : List (VisitPath W endAddr))
+ (realized : List.Forall₂ (RealizesJob (privateHistogram order src)) (jobs v z x) native)
+ (hook : ∀ j ∈ native, j.Linked M (A.core (.roleBase 0)) (A.dfsPC 3) A.dfs m)
+ (readOnly : ∀ j ∈ native, after m j.trace = m)
+ (c : Config W p r) (here : c.pc = A.dfsPC 0) (top : ℕ) (stack : Represents c.privateMem top pending)
+ (length : top+pending.length = endAddr) (sp : c.reg (A.dfs 5) = (top : Word W))
+ (endReg : c.reg (A.dfs 6) = (endAddr : Word W)) (one : c.reg (A.dfs 3) = 1)
+ (ready : Ready native (scratch endAddr c.privateMem))
+ (resident : ResidentGeometry (native.foldl (fun s j => j.update s) (scratch endAddr c.privateMem))
+ G offset (src : Word W))
+ (zero : ∀ l, privateHistogram order src (scratch endAddr c.privateMem) l = 0)
+ (above : endAddr ≤ src) (hsrc : src+g < 2^W) (hdst : base+grammar+g < 2^W)
+ (hbase : M.publicData 4 = (base : Word W)) (hgrammar : M.publicData 5 = (grammar : Word W))
+ (hg : M.publicData 9 = (g : Word W)) :
+ let powers := fun i : Fin g => (P.witnesses v z).exponents x (order i)
+ ∃ rep : Report W, rep.result = some (c.persistent+1) ∧
+ choiceBits rep.events = (P.read v z).encode x ∧ after m rep.events = Counters.addHistogram base grammar powers m ∧
+ rep.events.length = control.length + (native.map fun j => j.trace.length).sum + 7*g+14 ∧
+ countProbes rep.events = countProbes control + (native.map fun j => countProbes j.trace).sum + 2*g ∧
+ (∀ allow, Reads allow control → (∀ j ∈ native, Reads allow j.trace) →
+ (∀ i : Fin g, allow (base+grammar+i.val)) → Reads allow rep.events) ∧
+ ∀ extra, execute M.program (extra+rep.events.length+1) c m ((P.read v z).encode x) = some rep := by
+ intro powers
+ have names : native.map VisitPath.node = (trees v).preorder.map (fun n : ℕ => (n : Word W)) := by
+ rw [← spec.addresses v z x, List.map_map]
+ exact realized_addresses realized
+ obtain ⟨dfs,copy,_⟩ := core_linked A M linked
+ obtain ⟨mid,body,atFlush,state,spEnd,noWrites,support,finalScratch,bodyBits,bodyTime,bodyProbes,bodyRun⟩ :=
+ execute_linked_visits_supported dfs copy visits native names hook c here top stack length sp endReg one ready
+ have exactBits := bodyBits.trans ((realized_bits realized).trans (spec.bits v z x))
+ have hist (i : Fin g) : mid.privateMem ((src+i.val : ℕ) : Word W) = (powers i : Word W) := by
+ have atCell := realized_counts realized (scratch endAddr c.privateMem) ready (order i)
+ rw [← finalScratch,zero,Nat.zero_add,spec.increments] at atCell
+ unfold privateHistogram at atCell
+ rw [Equiv.symm_apply_apply] at atCell
+ have addr : ((src+i.val : ℕ) : Word W).val = src+i.val :=
+ Nat.mod_eq_of_lt ((Nat.add_lt_add_left i.isLt src).trans hsrc)
+ have ok : endAddr ≤ ((src+i.val : ℕ) : Word W).val := by rw [addr]; exact above.trans (Nat.le_add_right _ _)
+ simp only [rawScratch,dite_eq_left ok,scratch] at atCell
+ simpa only [Fin.cast_val_eq_self] using congrArg (fun n : ℕ => (n : Word W)) atCell
+ obtain ⟨out,flush,atFinish,_,persistent,flushLog,flushTime,flushProbes,flushBits,flushAfter,flushRun⟩ :=
+ flush_run_events linked G offset mid atFlush spEnd base grammar src (finalScratch ▸ resident)
+ hbase hgrammar hg powers hist hsrc hdst m
+ let close : List (Event W) := [.tick,.tick,.tick]
+ let events := body ++ flush ++ close
+ let rep : Report W := ⟨events,some (c.persistent+1)⟩
+ have runFinish (extra : ℕ) : execute M.program (extra+4) out (Counters.addHistogram base grammar powers m) [] =
+ some ⟨close,some (c.persistent+1)⟩ := by
+ rw [TerminalSiteStart.finish_run (finish_finishLinked A M linked) _ _ atFinish]
+ simp [close,persistent,state]
+ refine ⟨rep,rfl,?_,?_,?_,?_,?_,?_⟩
+ · change choiceBits events = _
+ simp [events,close,PrimedInputRAM.Flow.choiceBits_append,exactBits,flushBits,choiceBits]
+ · change after m events = _
+ have app (mem : Memory W) (xs ys : List (Event W)) : after mem (xs++ys) = after (after mem xs) ys :=
+ List.foldl_append
+ change after m ((body ++ flush) ++ close) = _
+ rw [app,app,noWrites readOnly,flushAfter]
+ rfl
+ · change events.length = _
+ simp [events,close,bodyTime,flushTime,Nat.add_assoc]
+ · change countProbes events = _
+ simp [events,close,probes_append,bodyProbes,flushProbes,countProbes]
+ · intro allow ctrl calls cells a v mem
+ change .read a v ∈ (body ++ flush) ++ close at mem
+ rcases List.mem_append.mp mem with h | h
+ · rcases List.mem_append.mp h with h | h
+ · rcases support _ h with hc | ⟨j, hj, he⟩
+ · exact ctrl a v hc
+ · exact calls j hj a v he
+ · rw [flushLog] at h
+ rcases List.mem_append.mp h with head | rest
+ · have eq : (.read a v : Event W) = .tick := List.eq_of_mem_replicate head
+ cases eq
+ · exact Counters.events_reads _ _ _ _ _ hdst allow cells a v rest
+ · simp [close] at h
+ · intro extra
+ have a := bodyRun (extra+4+7*g+11) []
+ rw [List.append_nil,exactBits] at a
+ have b := flushRun (extra+4) []
+ rw [runFinish] at b
+ change execute M.program (extra+events.length+1) c m _ = _
+ have len : extra+events.length+1 = extra+4+7*g+11+body.length := by
+ simp [events,close,flushTime]; omega
+ rw [len,a,b]
+ simp [rep,events,List.append_assoc]
+
+theorem vertex_report (linked : Contains A M) (P : SiteParsers f N) (trees : N.Site → VertexTree)
+ (jobs : JobsFor P) (spec : JobsSpec P trees jobs) (v : N.Site) (z : N.Half v)
+ (x : (P.witnesses v z).Choice) (order : Fin g ≃ Label)
+ (base grammar src : ℕ) (G offset : Word W) (m : Memory W)
+ {pending : List (Word W)} {control : List (Event W)}
+ (visits : Visits m endAddr pending ((trees v).preorder.map (fun n : ℕ => (n : Word W))) control)
+ (native : List (VisitPath W endAddr))
+ (realized : List.Forall₂ (RealizesJob (privateHistogram order src)) (jobs v z x) native)
+ (hook : ∀ j ∈ native, j.Linked M (A.core (.roleBase 0)) (A.dfsPC 3) A.dfs m)
+ (readOnly : ∀ j ∈ native, after m j.trace = m)
+ (c : Config W p r) (here : c.pc = A.dfsPC 0) (top : ℕ) (stack : Represents c.privateMem top pending)
+ (length : top+pending.length = endAddr) (sp : c.reg (A.dfs 5) = (top : Word W))
+ (endReg : c.reg (A.dfs 6) = (endAddr : Word W)) (one : c.reg (A.dfs 3) = 1)
+ (ready : Ready native (scratch endAddr c.privateMem))
+ (resident : ResidentGeometry (native.foldl (fun s j => j.update s) (scratch endAddr c.privateMem))
+ G offset (src : Word W))
+ (zero : ∀ l, privateHistogram order src (scratch endAddr c.privateMem) l = 0)
+ (above : endAddr ≤ src) (hsrc : src+g < 2^W) (hdst : base+grammar+g < 2^W)
+ (hbase : M.publicData 4 = (base : Word W)) (hgrammar : M.publicData 5 = (grammar : Word W))
+ (hg : M.publicData 9 = (g : Word W)) :
+ let powers := fun i : Fin g => (P.witnesses v z).exponents x (order i)
+ ∃ rep : Report W, rep.result = some (c.persistent+1) ∧
+ choiceBits rep.events = (P.read v z).encode x ∧ after m rep.events = Counters.addHistogram base grammar powers m ∧
+ rep.events.length = control.length + (native.map fun j => j.trace.length).sum + 7*g+14 ∧
+ countProbes rep.events = countProbes control + (native.map fun j => countProbes j.trace).sum + 2*g ∧
+ ∀ extra, execute M.program (extra+rep.events.length+1) c m ((P.read v z).encode x) = some rep := by
+ obtain ⟨rep, result, bits, effect, time, probes, _, run⟩ :=
+ vertex_report_supported A M linked P trees jobs spec v z x order base grammar src G offset m
+ visits native realized hook readOnly c here top stack length sp endReg one ready resident
+ zero above hsrc hdst hbase hgrammar hg
+ exact ⟨rep, result, bits, effect, time, probes, run⟩
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexSiteSegments.lean b/lean/OAI/Computability/VPVNP/PairVertexSiteSegments.lean
new file mode 100644
index 0000000000..da929f4425
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexSiteSegments.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.PairVertexReturns
+import OAI.Computability.VPVNP.PairSimulationTerminalSiteRun
+
+/-! # Installing the actual ordinal guard and persistent return in the vertex image -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM TerminalSiteStart DFS
+open scoped Fin.CommRing
+
+/-- The entry guard, exit tests, and site bootstrap labels installed before the geometry
+segment. -/
+inductive BootstrapLabel where
+ | pre (i : Fin 13) | equal | less | accept | reject | boot (i : Fin 29)
+ deriving DecidableEq, Fintype
+
+/-- Interpret a local bootstrap instruction label as its stage in the terminal site program. -/
+def BootstrapLabel.stage : BootstrapLabel → Stage
+ | .pre i => .pre i
+ | .equal => .equal
+ | .less => .less
+ | .accept => .accept
+ | .reject => .reject
+ | .boot i => .boot i
+
+/-- Map a terminal site stage into the bootstrap's program counters, using the supplied
+fallback for stages outside this block. -/
+def bootstrapPC {p : ℕ} (pc : BootstrapLabel → Fin p) (unused : Fin p) : Stage → Fin p
+ | .pre i => pc (.pre i)
+ | .equal => pc .equal
+ | .less => pc .less
+ | .accept => pc .accept
+ | .reject => pc .reject
+ | .boot i => pc (.boot i)
+ | .increment | .unit | .add | .finish => unused
+
+/-- Resolve bootstrap registers from the DFS, saved-operand, and local working banks. -/
+def bootstrapReg {r : ℕ} (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r) (work : Fin 3 ↪ Fin r) :
+ TerminalSiteStart.Reg → Fin r := Sum.elim dfs (Sum.elim saved work)
+
+/-- Number the finite set of bootstrap labels to place the site-entry instructions in a
+segment. -/
+noncomputable abbrev bootLabels := Fintype.equivFin BootstrapLabel
+
+/-- Install the terminal site guard and bootstrap instructions with three local working
+registers before entering geometry. -/
+noncomputable def bootstrapSegment : Segment where
+ count := Fintype.card BootstrapLabel
+ privateRegs := 3
+ entry := bootLabels (.pre 0)
+ row pc dfs saved work geometry i := TerminalSiteStart.instruction
+ (bootstrapPC (pc ∘ bootLabels) geometry) (bootstrapReg dfs saved work) id geometry (bootLabels.symm i).stage
+
+/-- The four return rows reload the genuine persistent ordinal, increment
+it and return the resulting word. -/
+def finishSegment : Segment where
+ count := 4
+ privateRegs := 3
+ entry := 0
+ row pc _ saved work _ :=
+ ![.stateWord (saved ordinal) (pc 1),.constant (work 0) 1 (pc 2),
+ .binary .add (saved ordinal) (saved ordinal) (work 0) (pc 3),.returnState (saved ordinal)]
+
+/-- Assign concrete segments to all named vertex parts, including the fixed bootstrap and
+finishing blocks. -/
+noncomputable def segments (geometry rootFields leaf shrink refresh : Segment) : Part → Segment
+ | .bootstrap => bootstrapSegment
+ | .geometry => geometry
+ | .rootFields => rootFields
+ | .leaf => leaf
+ | .shrink => shrink
+ | .refresh => refresh
+ | .finish => finishSegment
+
+variable {geometry rootFields leaf shrink refresh : Segment} {p r W : ℕ}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r)
+ (M : Machine W p r 11)
+
+/-- Host program counter of a terminal site-bootstrap label in the assembled vertex. -/
+noncomputable def sitePC (j : BootstrapLabel) := A.stage .bootstrap (bootLabels j)
+/-- Host program counter of a local finishing instruction in the assembled vertex. -/
+noncomputable def finishPC (i : Fin 4) := A.stage .finish i
+
+theorem bootstrap_linked (linked : Contains A M) (j : BootstrapLabel) :
+ M.code (sitePC A j) = TerminalSiteStart.instruction
+ (bootstrapPC (sitePC A) (A.entry .geometry)) (bootstrapReg A.dfs A.saved (A.localRegs .bootstrap))
+ id (A.entry .geometry) j.stage := by
+ apply (stage_linked A M linked .bootstrap (bootLabels j)).trans
+ change (TerminalSiteStart.instruction (bootstrapPC (sitePC A) (A.entry .geometry)) _
+ id (A.entry .geometry) (bootLabels.symm (bootLabels j)).stage).resize W = _
+ rw [Equiv.symm_apply_apply,TerminalSiteStart.resize_instruction]
+
+theorem finish_linked (linked : Contains A M) (i : Fin 4) :
+ M.code (finishPC A i) = ![Instr.stateWord (A.saved ordinal) (finishPC A 1),
+ .constant (A.localRegs .finish (0 : Fin 3)) 1 (finishPC A 2),
+ .binary .add (A.saved ordinal) (A.saved ordinal) (A.localRegs .finish (0 : Fin 3)) (finishPC A 3),
+ .returnState (A.saved ordinal)] i := by
+ apply (stage_linked A M linked .finish i).trans
+ fin_cases i <;> rfl
+
+/-- The bootstrap and return fragments use their own temporaries, alongside
+the same DFS and stable register banks. -/
+noncomputable def siteBank (part : Part)
+ (localMap : Fin 3 ↪ Fin ((segments geometry rootFields leaf shrink refresh) part).privateRegs) :
+ TerminalSiteStart.Reg ↪ Fin r :=
+ let work := (localMap.trans (Function.Embedding.sigmaMk (β := fun j => Fin ((segments geometry rootFields leaf shrink refresh) j).privateRegs) part)).trans Function.Embedding.inr
+ (Function.Embedding.sumMap (Function.Embedding.refl (Fin 9))
+ (Function.Embedding.sumMap (Function.Embedding.refl Saved) work)).trans A.reg
+
+/-- Register assignment for site-bootstrap instructions using the bootstrap segment's three
+work registers. -/
+noncomputable abbrev bootBank := siteBank A .bootstrap (Function.Embedding.refl (Fin 3))
+/-- Register assignment for final site-return instructions using the finishing segment's three
+work registers. -/
+noncomputable abbrev finishBank := siteBank A .finish (Function.Embedding.refl (Fin 3))
+
+/-- Resolve the terminal site's increment, unit, add, and return stages to the installed
+finishing code. -/
+noncomputable def returnPC : Stage → Fin p
+ | .increment => finishPC A 0
+ | .unit => finishPC A 1
+ | .add => finishPC A 2
+ | .finish => finishPC A 3
+ | _ => A.core .accept
+
+theorem boot_startLinked (linked : Contains A M) :
+ TerminalSiteStart.StartLinked M (bootstrapPC (sitePC A) (A.entry .geometry)) (bootBank A) id (A.entry .geometry) := by
+ have eqn : (bootBank A : TerminalSiteStart.Reg → Fin r) = bootstrapReg A.dfs A.saved (A.localRegs .bootstrap) := by
+ funext j
+ obtain x | s | w := j <;> rfl
+ rw [eqn]
+ intro j hj
+ cases j <;> first | contradiction | (solve | apply bootstrap_linked A M linked (.pre _)) |
+ (solve | apply bootstrap_linked A M linked .equal) | (solve | apply bootstrap_linked A M linked .less) |
+ (solve | apply bootstrap_linked A M linked .accept) | (solve | apply bootstrap_linked A M linked .reject) |
+ (solve | apply bootstrap_linked A M linked (.boot _))
+
+theorem finish_finishLinked (linked : Contains A M) :
+ TerminalSiteStart.FinishLinked M (returnPC A) (finishBank A) id (A.core .accept) := by
+ intro j hj
+ cases j <;> first | contradiction | exact finish_linked A M linked 0 | exact finish_linked A M linked 1 |
+ exact finish_linked A M linked 2 | exact finish_linked A M linked 3
+
+theorem finish_terminal (linked : Contains A M) (c : Config W p r) (m : Memory W) (bits : List Bool)
+ (here : c.pc = A.entry .finish) : Returns M c m bits ↔ bits = [] :=
+ TerminalSiteStart.finish_terminal (finish_finishLinked A M linked) m c here bits
+
+end PairSimulation.VertexImage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexStageChildren.lean b/lean/OAI/Computability/VPVNP/PairVertexStageChildren.lean
new file mode 100644
index 0000000000..cc3de1ab93
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexStageChildren.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.PairVertexStagePrefix
+
+/-!
+# The complete child prefix in the hosted shrink and refresh images
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexStagePrefix
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage NodeArguments NodeArguments.ChildScan
+open Compression CompressorRecords DFS TraversalRows
+open scoped Fin.CommRing
+
+variable {p r w a g : ℕ} (body : Segment) (locator : Fin 14 ↪ Fin body.privateRegs)
+ (M : Machine w p r 11) (loc : Fin (withChildren a body locator).count → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (withChildren a body locator).privateRegs ↪ Fin r) (done : Fin p)
+
+/-- Private register embedding for the child-argument scan preceding a located body. -/
+abbrev childBank := Preparation.phaseRegs (ChildCode.RegisterBank.segment a) body reg
+/-- Recover the body's shared level-locator registers through the child-preparation layout. -/
+abbrev locatorRegs := locator.trans
+ (Preparation.bodyRegs (ChildCode.RegisterBank.segment a) body reg)
+
+variable {X : State a g} {T : IncidenceDirectory w} {A : Arena} {older cap : ℕ} {m : Memory w}
+variable (installed : ∀ i, M.code (loc i) =
+ ((withChildren a body locator).row loc dfs saved reg done i).resize w)
+ (rep : T.ActualColumns X m) (xs : List (Child X)) (src : ℕ) (c : Config w p r)
+ (entry : c.pc = loc (withChildren a body locator).entry)
+ (stored : (directory a older cap A T).Stored m (c.reg (locatorRegs body locator reg 12)))
+ (row : Row m (c.reg (locatorRegs body locator reg 0)).val src
+ (xs.map fun x => (childNode X older cap x.site : Word w)))
+ (strideFit : cap + 2 < 2 ^ w) (nodes : ∀ x ∈ xs, childNode X older cap x.site < 2 ^ w)
+ (packets : ∀ x ∈ xs, A.base (childNode X older cap x.site) + (x.payload X).length < 2 ^ w)
+
+private theorem setup_apart (i : Fin 16) (j : Fin 14) :
+ ChildCode.RegisterBank.regs (childBank body locator reg) i ≠ locatorRegs body locator reg j :=
+ Preparation.disjoint reg _ _
+
+include installed rep entry stored row strideFit nodes packets
+
+/-- Copy the two actual locator outputs and scan every outgoing and incoming child field.
+The remaining routine's whole bank stays available after all packet writes. -/
+theorem child_run :
+ let qs := xs.map (Child.packet X older cap)
+ let es := List.replicate 2 .tick ++ (List.replicate (2 ^ a) .tick ++
+ (ChildHeader.events m (c.reg (locatorRegs body locator reg 0))
+ (c.reg (locatorRegs body locator reg 12)) ++ ChildScan.events X T m src xs))
+ ∃ d, d.pc = (childPreparation a body locator).bodyPC loc body.entry ∧
+ d.persistent = c.persistent ∧ d.privateMem = storePackets A qs c.privateMem ∧
+ (∀ endAddr, scratch endAddr d.privateMem = writePackets A qs (scratch endAddr c.privateMem)) ∧
+ (∀ i, i ∉ Set.range (childBank body locator reg) → d.reg i = c.reg i) ∧
+ Prefix M m c d (qs.flatMap Packet.bits) es := by
+ let ps := childBank body locator reg
+ let child := ChildCode.RegisterBank.regs ps
+ obtain ⟨load, init, bodyCode, _⟩ := child_rows a body locator M loc dfs saved reg done installed
+ obtain ⟨mid, pre, pc', hn, hf, unchanged, hm, hp⟩ :=
+ VertexLevel.childHandoff_run load (setup_apart body locator reg 7 12) c entry m
+ obtain ⟨d, stop, persist, mem, upper, frame, path⟩ :=
+ ChildCode.RegisterBank.native_stage init bodyCode (ChildCode.RegisterBank.bank_apart ps)
+ rep xs src mid pc' (hf ▸ stored) (hn ▸ row) strideFit nodes packets
+ rw [hn, hf] at path
+ rw [hm] at mem upper
+ refine ⟨d, stop, persist.trans hp, mem, upper, ?_, pre.trans path⟩
+ intro i outside
+ have off (j : Fin 16) : i ≠ child j := fun h => outside ⟨_, h.symm⟩
+ have noBank : i ∉ Set.range (ChildCode.RegisterBank.bank ps) :=
+ fun ⟨_, h⟩ => outside ⟨_, h⟩
+ have noMut : i ∉ mutableRegs child := by simp [mutableRegs, off]
+ exact (frame i noBank (fun j _ => off j) noMut).trans (unchanged i (off 7) (off 8))
+
+/-- The short-tape case rejects even when the caller supplies arbitrarily much fuel. -/
+theorem child_reject (bs : List Bool) (short : bs.length < (xs.flatMap (Child.payload X)).length) :
+ ¬ Returns M c m bs := by
+ let ps := childBank body locator reg
+ obtain ⟨load, init, bodyCode, _⟩ := child_rows a body locator M loc dfs saved reg done installed
+ obtain ⟨mid, pre, pc', hn, hf, _, _, _⟩ :=
+ VertexLevel.childHandoff_run load (setup_apart body locator reg 7 12) c entry m
+ have no := ChildCode.RegisterBank.reject_stage init bodyCode
+ (ChildCode.RegisterBank.bank_apart ps)
+ rep xs src mid pc' (hf ▸ stored) (hn ▸ row) strideFit nodes packets bs short
+ exact fun accepted => no ((pre.returns bs).mp accepted)
+
+end PairSimulation.VertexStagePrefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexStageDispatch.lean b/lean/OAI/Computability/VPVNP/PairVertexStageDispatch.lean
new file mode 100644
index 0000000000..cedbee9696
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexStageDispatch.lean
@@ -0,0 +1,262 @@
+import OAI.Computability.VPVNP.PairSimulationInlineLiteral
+import OAI.Computability.VPVNP.PairSimulationRouteRange
+import OAI.Computability.VPVNP.PairNodeChildLoop
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# Native dispatch on the producing shrink stage
+
+The preceding level locator supplies the zero-based ordinal of the producing
+stage. Each compressor block has `N` shrinking stages followed by a refresh.
+This finite program constructs the period `N+1` from zero and one, takes the
+native word remainder, and tests the `N` shrink ordinals in sequence.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexStageDispatch
+
+open BurstRAM PrivateRAM PrimedCounter.GuessWord
+open scoped Fin.CommRing
+
+variable {N w p r : ℕ}
+
+/-- Instruction labels of the scheduled-stage selector, including ordinal comparison, per-stage
+tests, and rejection. -/
+abbrev Address (N : ℕ) := Fin (N + 3) ⊕ Fin 3 ⊕ (Fin N × Bool) ⊕ Fin 1
+
+/-- Total number of instructions reserved for selecting among the fixed number of scheduled
+stage bodies. -/
+def count (N : ℕ) := (N + 3) + (3 + (N * 2 + 1))
+
+/-- The constant loader, three preparation rows, two rows per shrink stage,
+and the rejection row occupy consecutive ranges. -/
+def address (N : ℕ) : Address N ≃ Fin (count N) :=
+ let tests := ((Equiv.refl (Fin N)).prodCongr finTwoEquiv.symm).trans finProdFinEquiv
+ let tail := (tests.sumCongr (Equiv.refl (Fin 1))).trans finSumFinEquiv
+ let body := ((Equiv.refl (Fin 3)).sumCongr tail).trans finSumFinEquiv
+ ((Equiv.refl _).sumCongr body).trans finSumFinEquiv
+
+/-- First instruction label of the stage-selection table. -/
+def entry (N : ℕ) := address N (.inl 0)
+
+private abbrev prep (j : Fin 3) : Address N := .inr (.inl j)
+private abbrev test (j : Fin N) (b : Bool) : Address N := .inr (.inr (.inl (j,b)))
+private abbrev reject : Address N := .inr (.inr (.inr 0))
+
+private def scanAt (j : ℕ) : Address N :=
+ if h : j < N then test ⟨j,h⟩ false else reject
+
+private def litPC (pc : Address N → Fin p) : Fin ((N + 1) + 3) → Fin p :=
+ Fin.lastCases (pc (prep 0)) (fun j ↦ pc (.inl j))
+
+private def native (W : ℕ) (pc : Address N → Fin p) (scratch : Fin 4 ↪ Fin r)
+ (src : Fin r) (jump : Fin N → Fin p) : Address N → Instr W p r 11
+ | .inl j => InlinePublic.literalInstruction W (N + 1) (N + 1) (litPC pc)
+ (scratch 0) (scratch 1) j
+ | .inr (.inl j) => (![.binary .mod (scratch 2) src (scratch 1) (pc (prep 1)),
+ .constant (scratch 3) 0 (pc (prep 2)),
+ .constant (scratch 0) 1 (pc (scanAt 0))] : Fin 3 → Instr W p r 11) j
+ | .inr (.inr (.inl (j,false))) => .jumpEq (scratch 2) (scratch 3) (jump j) (pc (test j true))
+ | .inr (.inr (.inl (j,true))) =>
+ .binary .add (scratch 3) (scratch 3) (scratch 0) (pc (scanAt (j.val + 1)))
+ | .inr (.inr (.inr _)) => .reject
+
+/-- Relocatable native selector rows with five literal bits, for all block lengths. -/
+def row (N : ℕ) (loc : Fin (count N) → Fin p) (scratch : Fin 4 ↪ Fin r)
+ (src : Fin r) (jump : Fin N → Fin p) (j : Fin (count N)) : Instr 5 p r 11 :=
+ native 5 (loc ∘ address N) scratch src jump ((address N).symm j)
+
+private theorem resize_native (pc : Address N → Fin p) (scratch : Fin 4 ↪ Fin r)
+ (src : Fin r) (jump : Fin N → Fin p) (j : Address N) :
+ (native 5 pc scratch src jump j).resize w = native w pc scratch src jump j := by
+ rcases j with j | j | ⟨j,b⟩ | j
+ · simp only [native, InlinePublic.literalInstruction]
+ split_ifs <;> rfl
+ · fin_cases j <;> rfl
+ · cases b <;> rfl
+ · rfl
+
+variable (M : Machine w p r 11) (loc : Fin (count N) → Fin p) (scratch : Fin 4 ↪ Fin r)
+ (src : Fin r) (jump : Fin N → Fin p)
+
+/-- The host contains every width-resized stage-selector instruction under the supplied
+placements and jumps. -/
+def Linked := ∀ j, M.code (loc j) = (row N loc scratch src jump j).resize w
+
+private theorem atCode (link : Linked M loc scratch src jump) (j : Address N) :
+ M.code (loc (address N j)) = native w (loc ∘ address N) scratch src jump j := by
+ simpa only [row, Equiv.symm_apply_apply, resize_native] using link (address N j)
+
+variable {M loc scratch src jump}
+
+private theorem atStep (link : Linked M loc scratch src jump) (j : Address N)
+ (c : Config w p r) (hc : c.pc = loc (address N j)) :
+ M.program.step c = (native w (loc ∘ address N) scratch src jump j).run M.publicData c := by
+ simp only [Machine.program, hc, atCode _ _ _ _ _ link]
+
+/-- The stage selector preserves the machine state outside its designated scratch registers. -/
+abbrev Frame (scratch : Fin 4 ↪ Fin r) (c d : Config w p r) :=
+ RouteRange.Frame (fun i ↦ i ∉ Set.range scratch) c d
+
+private theorem prepare (link : Linked M loc scratch src jump) (fresh : src ∉ Set.range scratch)
+ (c : Config w p r) (hc : c.pc = loc (entry N)) (hN : N + 1 < 2 ^ w) :
+ ∃ d, Prefix M c (List.replicate (N + 6) .tick) d ∧ d.pc = loc (address N (scanAt 0)) ∧
+ d.reg (scratch 2) = ((c.reg src).val % (N + 1) : ℕ) ∧ d.reg (scratch 3) = 0 ∧
+ d.reg (scratch 0) = 1 ∧ Frame scratch c d := by
+ let pc := loc ∘ address N
+ have start : c.pc = litPC pc 0 := by
+ rw [show (0 : Fin ((N + 1) + 3)) = (0 : Fin ((N + 1) + 2)).castSucc from rfl,
+ litPC, Fin.lastCases_castSucc]
+ exact hc
+ have lit (i : Fin ((N + 1) + 2)) : M.code (litPC pc i.castSucc) =
+ InlinePublic.literalInstruction w (N + 1) (N + 1) (litPC pc) (scratch 0) (scratch 1) i := by
+ rw [litPC, Fin.lastCases_castSucc]
+ exact atCode _ _ _ _ _ link (.inl i)
+ obtain ⟨a, pre, ha, modulus, outside, mem, persist⟩ :=
+ InlinePublic.literal_prefix (scratch.injective.ne (by decide)) le_rfl lit c start
+ rw [litPC, Fin.lastCases_last] at ha
+ have ne (i : Fin r) (h : i ∉ Set.range scratch) (j : Fin 4) : i ≠ scratch j :=
+ fun e ↦ h ⟨j,e.symm⟩
+ let z : Word w := ((c.reg src).val % (N + 1) : ℕ)
+ let b := a.put (pc (prep 1)) (scratch 2) z
+ let e := b.put (pc (prep 2)) (scratch 3) 0
+ let d := e.put (pc (scanAt 0)) (scratch 0) 1
+ have h₀ : M.program.step a = .localStep b := by
+ rw [atStep link (prep 0) a ha]
+ change CallAction.localStep (a.put _ _ (BinaryOp.mod.eval (a.reg src) (a.reg (scratch 1)))) = _
+ rw [outside src (ne _ fresh _) (ne _ fresh _), modulus]
+ simp only [BinaryOp.eval, Fin.val_natCast, Nat.mod_eq_of_lt hN]
+ rfl
+ have h₁ : M.program.step b = .localStep e := atStep link (prep 1) b rfl
+ have h₂ : M.program.step e = .localStep d := atStep link (prep 2) e rfl
+ have boot : Prefix M a (List.replicate 3 .tick) d := .tick h₀ (.tick h₁ (.tick h₂ (.nil _)))
+ have f : Frame scratch c a := ⟨fun i hi ↦ outside _ (ne _ hi _) (ne _ hi _), mem, persist⟩
+ refine ⟨d, ?_, rfl, ?_, ?_, ?_, ((f.put _ _ _ (fun i h ↦ ne i h _)).put _ _ _
+ (fun i h ↦ ne i h _)).put _ _ _ (fun i h ↦ ne i h _)⟩
+ · simpa only [← List.replicate_add] using pre.append boot
+ all_goals simp [d, e, b, Config.put, z]
+
+private theorem scanTo (link : Linked M loc scratch src jump) (hN : N + 1 < 2 ^ w)
+ (c : Config w p r) (hc : c.pc = loc (address N (scanAt 0))) (target : ℕ)
+ (ht : target ≤ N) (residue : c.reg (scratch 2) = (target : Word w))
+ (start : c.reg (scratch 3) = 0) (one : c.reg (scratch 0) = 1) (j : ℕ) (hj : j ≤ target) :
+ ∃ d, Prefix M c (List.replicate (2 * j) .tick) d ∧ d.pc = loc (address N (scanAt j)) ∧
+ d.reg (scratch 2) = (target : Word w) ∧ d.reg (scratch 3) = (j : Word w) ∧
+ d.reg (scratch 0) = 1 ∧ Frame scratch c d := by
+ induction j with
+ | zero => exact ⟨c, by simpa using Prefix.nil (M := M) c, hc, residue, by simpa using start,
+ one, RouteRange.Frame.refl c⟩
+ | succ j ih =>
+ obtain ⟨mid, pre, hp, hr, hj', hu, frame⟩ := ih (by omega)
+ let i : Fin N := ⟨j, by omega⟩
+ have atI : scanAt j = test i false := dite_eq_left i.isLt
+ rw [atI] at hp
+ let miss := {mid with pc := loc (address N (test i true))}
+ let d := miss.put (loc (address N (scanAt (j + 1)))) (scratch 3) ((j + 1 : ℕ) : Word w)
+ have unequal : (target : Word w) ≠ (j : Word w) := by
+ intro he
+ have h := congrArg Fin.val he
+ rw [Fin.val_natCast, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : target < 2 ^ w),
+ Nat.mod_eq_of_lt (by omega : j < 2 ^ w)] at h
+ omega
+ have step₀ : M.program.step mid = .localStep miss := by
+ rw [atStep link (test i false) mid hp]
+ change CallAction.localStep {mid with pc := if mid.reg _ = mid.reg _ then _ else _} = _
+ rw [hr, hj', ite_eq_right unequal]
+ rfl
+ have step₁ : M.program.step miss = .localStep d := by
+ rw [atStep link (test i true) miss rfl]
+ change CallAction.localStep (miss.put _ _ (mid.reg (scratch 3) + mid.reg (scratch 0))) = _
+ simp only [hj', hu, Nat.cast_add, Nat.cast_one, d, i, Function.comp_apply]
+ have tail : Prefix M mid (List.replicate 2 .tick) d := .tick step₀ (.tick step₁ (.nil _))
+ have f : Frame scratch c miss := ⟨frame.regs, frame.memory, frame.persistent⟩
+ refine ⟨d, ?_, rfl, ?_, ?_, ?_, f.put _ _ _ (fun t h e ↦ h ⟨3,e.symm⟩)⟩
+ · simpa only [← List.replicate_add, Nat.mul_succ] using pre.append tail
+ all_goals simp [d, miss, Config.put, hr, hu]
+
+/-- The old stage ordinal leads to its actual shrink entry. The only events
+are the fixed literal setup, three arithmetic rows and the bounded stage scan. -/
+theorem run (link : Linked M loc scratch src jump) (fresh : src ∉ Set.range scratch)
+ (hN : N + 1 < 2 ^ w) (stage : ℕ) (hs : stage < 2 ^ w) (i : Fin N)
+ (selects : stage % (N + 1) = i.val) (c : Config w p r) (hc : c.pc = loc (entry N))
+ (source : c.reg src = (stage : Word w)) :
+ ∃ out, Prefix M c (List.replicate (N + 7 + 2 * i.val) .tick) out ∧
+ out.pc = jump i ∧ Frame scratch c out := by
+ obtain ⟨a, first, hp, hr, hz, hu, f⟩ := prepare link fresh c hc hN
+ rw [source, Fin.val_natCast, Nat.mod_eq_of_lt hs, selects] at hr
+ obtain ⟨b, second, hb, hr', hi, _, g⟩ := scanTo link hN a hp i.val i.isLt.le hr hz hu i.val le_rfl
+ rw [scanAt, dite_eq_left i.isLt] at hb
+ let out := {b with pc := jump i}
+ have last : M.program.step b = .localStep out := by
+ rw [atStep link (test i false) b hb]
+ change CallAction.localStep {b with pc := if b.reg _ = b.reg _ then _ else _} = _
+ rw [hr', hi, ite_eq_left rfl]
+ have htail : Prefix M b (List.replicate 1 .tick) out := .tick last (.nil _)
+ have events := (first.append second).append htail
+ rw [← List.replicate_add, ← List.replicate_add] at events
+ have g' : Frame scratch a out := ⟨g.regs, g.memory, g.persistent⟩
+ exact ⟨out, by convert events using 2; omega, rfl, f.trans g'⟩
+
+/-- The refresh ordinal reaches the physical rejection row of the shrink dispatcher. -/
+theorem run_reject (link : Linked M loc scratch src jump) (fresh : src ∉ Set.range scratch)
+ (hN : N + 1 < 2 ^ w) (stage : ℕ) (hs : stage < 2 ^ w)
+ (refresh : stage % (N + 1) = N) (c : Config w p r) (hc : c.pc = loc (entry N))
+ (source : c.reg src = (stage : Word w)) :
+ ∃ out, Prefix M c (List.replicate (N + 6 + 2 * N) .tick) out ∧
+ M.program.step out = .reject ∧ Frame scratch c out := by
+ obtain ⟨a, first, hp, hr, hz, hu, f⟩ := prepare link fresh c hc hN
+ rw [source, Fin.val_natCast, Nat.mod_eq_of_lt hs, refresh] at hr
+ obtain ⟨b, second, hb, _, _, _, g⟩ := scanTo link hN a hp N le_rfl hr hz hu N le_rfl
+ rw [scanAt, dite_eq_right (Nat.lt_irrefl _)] at hb
+ exact ⟨b, by simpa only [← List.replicate_add] using first.append second,
+ atStep link reject b hb, f.trans g⟩
+
+private theorem tickLog (t : ℕ) :
+ countProbes (List.replicate t (.tick : Event w)) = 0 ∧
+ choiceBits (List.replicate t (.tick : Event w)) = [] := by
+ induction t with
+ | zero => exact ⟨rfl,rfl⟩
+ | succ t ih => simpa only [List.replicate_succ, countProbes, choiceBits] using ih
+
+theorem trace_cost (i : Fin N) :
+ N + 7 + 2 * i.val ≤ 3 * N + 5 ∧
+ countProbes (List.replicate (N + 7 + 2 * i.val) (.tick : Event w)) = 0 ∧
+ choiceBits (List.replicate (N + 7 + 2 * i.val) (.tick : Event w)) = [] := by
+ exact ⟨by have := i.isLt; omega, tickLog _⟩
+
+/-- The tick-only prefix composes with the surrounding depth-first parser
+on every external memory and unconsumed binary suffix. -/
+theorem run_prefix (link : Linked M loc scratch src jump) (fresh : src ∉ Set.range scratch)
+ (hN : N + 1 < 2 ^ w) (stage : ℕ) (hs : stage < 2 ^ w) (i : Fin N)
+ (selects : stage % (N + 1) = i.val) (c : Config w p r) (hc : c.pc = loc (entry N))
+ (source : c.reg src = (stage : Word w)) (m : Memory w) :
+ ∃ out, NodeArguments.ChildScan.Prefix M m c out []
+ (List.replicate (N + 7 + 2 * i.val) .tick) ∧ out.pc = jump i ∧ Frame scratch c out := by
+ obtain ⟨out, h, pc, frame⟩ := run link fresh hN stage hs i selects c hc source
+ exact ⟨out, fun fuel tail ↦ by simpa only [(trace_cost i).2.2] using h.execute fuel m tail,
+ pc, frame⟩
+
+/-- A refresh residue has no successful continuation through the shrink
+dispatcher, at any fuel bound or on any pending choice stream. -/
+theorem reject_noReturns (link : Linked M loc scratch src jump) (fresh : src ∉ Set.range scratch)
+ (hN : N + 1 < 2 ^ w) (stage : ℕ) (hs : stage < 2 ^ w)
+ (refresh : stage % (N + 1) = N) (c : Config w p r) (hc : c.pc = loc (entry N))
+ (source : c.reg src = (stage : Word w)) (m : Memory w) (bs : List Bool) :
+ ¬ DFS.Returns M c m bs := by
+ obtain ⟨out, h, bad, _⟩ := run_reject link fresh hN stage hs refresh c hc source
+ have pre : NodeArguments.ChildScan.Prefix M m c out [] (List.replicate (N + 6 + 2 * N) .tick) :=
+ fun fuel tail ↦ by simpa only [(tickLog _).2] using h.execute fuel m tail
+ intro success
+ obtain ⟨fuel, rep, ran⟩ := (pre.returns bs).mp success
+ cases fuel with
+ | zero => simp [execute] at ran
+ | succ f => simp [execute, bad] at ran
+
+end PairSimulation.VertexStageDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexStagePrefix.lean b/lean/OAI/Computability/VPVNP/PairVertexStagePrefix.lean
new file mode 100644
index 0000000000..bf1868d840
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexStagePrefix.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.PairNodeChildSegment
+import OAI.Computability.VPVNP.PairShrinkRoleHandoff
+
+/-!
+# Preparing and linking the argument stages of a nonleaf visit
+
+A preparation block can read the locator retained in the following routine's register
+bank and initialize a separate argument-reader bank. The same construction links the
+child stage on both roles and the absorbed-field stage on a shrinking role.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexStagePrefix
+
+open BurstRAM BurstRAM.PrivateRAM VertexImage NodeArguments
+open scoped Fin.CommRing
+
+variable {p r w : ℕ}
+
+/-- Fixed instructions transferring operands to a phase before it starts. -/
+structure Preparation (phase body : Segment) where
+ /-- Number of instructions in the operand preparation that runs ahead of a phase and its
+ continuation. -/
+ count : ℕ
+ /-- Entry ordinal of the setup portion of the preparation. -/
+ entry : Fin count
+ /-- Native instruction generator for the preparation under the supplied DFS, saved, local
+ register, and continuation placements. -/
+ row : ∀ {p r : ℕ}, (Fin count → Fin p) → (Fin 9 ↪ Fin r) → (Saved ↪ Fin r) →
+ (Fin phase.privateRegs ↪ Fin r) → (Fin body.privateRegs ↪ Fin r) →
+ Fin p → Fin count → Instr 5 p r 11
+
+namespace Preparation
+
+variable {phase body : Segment} (X : Preparation phase body)
+
+/-- Total instruction count after concatenating setup, prepared phase, and continuation body. -/
+abbrev size := X.count + (phase.count + body.count)
+/-- Total private registers in the combined phase and continuation, with separate banks for
+each. -/
+abbrev registers (phase body : Segment) := body.privateRegs + phase.privateRegs
+
+/-- Relocate a setup instruction from the initial block of the combined table to the program
+address supplied by the placement function. -/
+def setupPC (loc : Fin X.size → Fin p) (i : Fin X.count) := loc (i.castAdd _)
+
+/-- Relocate an instruction of the prepared phase, adding the setup block length before
+applying the program-address function. -/
+def phasePC (loc : Fin X.size → Fin p) (i : Fin phase.count) :=
+ loc ((i.castAdd body.count).natAdd X.count)
+
+/-- Relocate a body instruction, adding the lengths of the setup and phase blocks before
+applying the program-address function. -/
+def bodyPC (loc : Fin X.size → Fin p) (i : Fin body.count) :=
+ loc ((i.natAdd phase.count).natAdd X.count)
+
+/-- Embed phase registers in the combined bank after the continuation's reserved registers. -/
+def phaseRegs (phase body : Segment) (reg : Fin (registers phase body) ↪ Fin r) :
+ Fin phase.privateRegs ↪ Fin r := (Fin.natAddEmb body.privateRegs).trans reg
+
+/-- Embed continuation-body registers in the leading portion of the combined bank. -/
+def bodyRegs (phase body : Segment) (reg : Fin (registers phase body) ↪ Fin r) :
+ Fin body.privateRegs ↪ Fin r := (Fin.castAddEmb phase.privateRegs).trans reg
+
+theorem disjoint (reg : Fin (registers phase body) ↪ Fin r) (i : Fin phase.privateRegs)
+ (j : Fin body.privateRegs) : phaseRegs phase body reg i ≠ bodyRegs phase body reg j := by
+ apply reg.injective.ne
+ intro h
+ have e := congrArg Fin.val h
+ change body.privateRegs + i.val = j.val at e
+ omega
+
+/-- Prepare the phase's inputs, run it, and return directly into the next body. -/
+def assemble : Segment where
+ count := X.size
+ privateRegs := registers phase body
+ entry := X.entry.castAdd _
+ row loc dfs saved reg done i :=
+ let ps := phaseRegs phase body reg
+ let bs := bodyRegs phase body reg
+ Fin.addCases (motive := fun _ => Instr 5 _ _ 11)
+ (X.row (X.setupPC loc) dfs saved ps bs (X.phasePC loc phase.entry))
+ (fun j => Fin.addCases (motive := fun _ => Instr 5 _ _ 11)
+ (phase.row (X.phasePC loc) dfs saved ps (X.bodyPC loc body.entry))
+ (body.row (X.bodyPC loc) dfs saved bs done) j) i
+
+theorem links (M : Machine w p r 11) (loc : Fin X.size → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r) (reg : Fin (registers phase body) ↪ Fin r)
+ (done : Fin p) (installed : ∀ i, M.code (loc i) =
+ (X.assemble.row loc dfs saved reg done i).resize w) :
+ (∀ i, M.code (X.setupPC loc i) = (X.row (X.setupPC loc) dfs saved
+ (phaseRegs phase body reg) (bodyRegs phase body reg)
+ (X.phasePC loc phase.entry) i).resize w) ∧
+ (∀ i, M.code (X.phasePC loc i) = (phase.row (X.phasePC loc) dfs saved
+ (phaseRegs phase body reg) (X.bodyPC loc body.entry) i).resize w) ∧
+ (∀ i, M.code (X.bodyPC loc i) = (body.row (X.bodyPC loc) dfs saved
+ (bodyRegs phase body reg) done i).resize w) := by
+ refine ⟨fun i => ?_, fun i => ?_, fun i => ?_⟩
+ · apply (installed _).trans
+ simp only [assemble, Fin.addCases_left]
+ · apply (installed _).trans
+ simp only [assemble, Fin.addCases_left, Fin.addCases_right]
+ · apply (installed _).trans
+ simp only [assemble, Fin.addCases_right]
+
+end Preparation
+
+/-- The old-level child header reader receives the popped node and the old field table
+head from the locator. Its ordinal bank has its own registers. -/
+def childPreparation (a : ℕ) (body : Segment) (locator : Fin 14 ↪ Fin body.privateRegs) :
+ Preparation (ChildCode.RegisterBank.segment a) body where
+ count := 2
+ entry := 0
+ row pc _ _ ps bs next := VertexLevel.childHandoff pc (locator.trans bs)
+ (ChildCode.RegisterBank.regs ps) next
+
+/-- Assemble the child argument preparation and the supplied located body into one vertex
+segment. -/
+def withChildren (a : ℕ) (body : Segment) (locator : Fin 14 ↪ Fin body.privateRegs) :=
+ (childPreparation a body locator).assemble
+
+theorem child_rows (a : ℕ) (body : Segment) (locator : Fin 14 ↪ Fin body.privateRegs)
+ (M : Machine w p r 11) (loc : Fin (withChildren a body locator).count → Fin p)
+ (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (withChildren a body locator).privateRegs ↪ Fin r)
+ (done : Fin p) (installed : ∀ i, M.code (loc i) =
+ ((withChildren a body locator).row loc dfs saved reg done i).resize w) :
+ let X := childPreparation a body locator
+ let ps := Preparation.phaseRegs (ChildCode.RegisterBank.segment a) body reg
+ let bs := Preparation.bodyRegs (ChildCode.RegisterBank.segment a) body reg
+ (∀ i, M.code (X.setupPC loc i) = VertexLevel.childHandoff (X.setupPC loc)
+ (locator.trans bs) (ChildCode.RegisterBank.regs ps)
+ (X.phasePC loc (ChildCode.RegisterBank.segment a).entry) i) ∧
+ ChildBankInit.Linked M (ChildCode.RegisterBank.initPC (X.phasePC loc))
+ (ChildCode.RegisterBank.bank ps)
+ (ChildCode.headerPC (ChildCode.RegisterBank.loc (X.phasePC loc)) 0) ∧
+ (∀ i, M.code (ChildCode.RegisterBank.loc (X.phasePC loc) i) =
+ ChildCode.RegisterBank.instruction (ChildCode.RegisterBank.loc (X.phasePC loc))
+ (ChildCode.RegisterBank.regs ps) (ChildCode.RegisterBank.bank ps)
+ (X.bodyPC loc body.entry) i) ∧
+ (∀ i, M.code (X.bodyPC loc i) = (body.row (X.bodyPC loc) dfs saved bs done i).resize w) := by
+ let X := childPreparation a body locator
+ obtain ⟨pre, phase, next⟩ := X.links M loc dfs saved reg done installed
+ obtain ⟨init, rows⟩ := ChildCode.RegisterBank.segment_linked M _ dfs saved _ _ phase
+ exact ⟨fun i => (pre i).trans (VertexLevel.resize_childHandoff ..), init, rows, next⟩
+
+end PairSimulation.VertexStagePrefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexStageRun.lean b/lean/OAI/Computability/VPVNP/PairVertexStageRun.lean
new file mode 100644
index 0000000000..712882c237
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexStageRun.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.PairVertexStageSegment
+import OAI.Computability.VPVNP.PairVertexLevelSchedule
+
+/-!
+# Native prefix through the level locator and shrink-stage selector
+
+Starting at a popped nonleaf, the full segment first recovers the old level
+and packed site. It then transfers to the matching shrink handler with every
+locator operand still available in that handler's shared prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexStageDispatch
+
+open BurstRAM PrivateRAM VertexImage TraversalControllerInputs TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+variable {N w p r : ℕ}
+
+/-- The located header and owner depend only on the fourteen locator registers. -/
+theorem retainLocated {pub : Fin 11 → Word w} {m : Memory w} {locator : Fin 14 ↪ Fin r}
+ {node owner : Word w} {stage : ℕ} {a b : Config w p r}
+ (h : VertexLevel.Located pub m locator node stage owner a)
+ (same : ∀ i, b.reg (locator i) = a.reg (locator i)) :
+ VertexLevel.Located pub m locator node stage owner b := by
+ obtain ⟨⟨node, head, pitch, index, current, stride, one, offset⟩, start, owner, old, fields,
+ ordinal⟩ := h
+ constructor
+ · constructor <;> rwa [same]
+ all_goals rwa [same]
+
+variable (B : Fin N → Segment) (tail : Fin N → ℕ) (split : ∀ i, (B i).privateRegs = 14 + tail i)
+variable (loc : Fin (locatedCount B) → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin (bankCount tail) ↪ Fin r) (done : Fin p) (M : Machine w p r 11)
+
+private theorem placed_disjoint (j : Fin 14) :
+ (locatorBank tail).trans reg j ∉ Set.range ((scratchBank tail).trans reg) := by
+ rintro ⟨s,h⟩
+ exact locator_disjoint_scratch tail j ⟨s, reg.injective h⟩
+
+/-- The genuine linked trace reaches the indicated handler PC. The two
+private register banks account for its entire frame and the producing
+level's fields survive at the selected handler's shared register prefix. -/
+theorem locatedFamily_run
+ (rows : ∀ j, M.code (loc j) =
+ ((locatedFamily B tail split).row loc dfs saved reg done j).resize w)
+ {m : Memory w} {H first pitch offset cap base : ℕ} {old : TaggedLayer} {ls : List (Fiber w)}
+ (d : Resident M.publicData m H first pitch offset cap base old ls)
+ (j : Fin (old :: ls.map Prod.fst).length) (stage : ℕ) (hj : j.val = stage + 1)
+ (id : Fin (old :: ls.map Prod.fst)[j].layer.count) (i : Fin N)
+ (hN : N + 1 < 2 ^ w) (selects : stage % (N + 1) = i.val)
+ (c : Config w p r) (hc : c.pc = loc (locatedFamily B tail split).entry)
+ (node : (c.reg (dfs 7)).val = TraversalRows.address cap
+ (layerBase cap base (old :: ls.map Prod.fst) j) id)
+ (fit : layerBase cap base (old :: ls.map Prod.fst) (ls.length + 1) < 2 ^ w) :
+ let lr := (locatorBank tail).trans reg
+ let sr := (scratchBank tail).trans reg
+ ∃ out, NodeArguments.ChildScan.Prefix M m c out []
+ (VertexLevel.trace M.publicData m (stage + 1) (ls.length - (stage + 1)) ++
+ List.replicate (N + 7 + 2 * i.val) .tick) ∧
+ out.pc = bodyPC B (familyPC B loc) i (B i).entry ∧
+ VertexLevel.Located M.publicData m lr (c.reg (dfs 7)) stage (id.val : Word w) out ∧
+ RouteRange.Frame (fun a ↦ a ∉ Set.range lr ∧ a ∉ Set.range sr) c out := by
+ intro lr sr
+ obtain ⟨front, selector, _⟩ := locatedFamily_link B dfs saved done M tail split loc reg rows
+ obtain ⟨mid, pre, atSel, info, fr⟩ := VertexLevel.run M (locatorPC B loc) dfs saved lr
+ (selectorPC B (familyPC B loc) (entry N)) front d j stage hj id c hc node fit
+ have hword : ls.length + 1 < 2 ^ w := by
+ rw [← (VertexLevelBounds.resident_geometry d).1]
+ exact (terminalField M.publicData m 1).isLt
+ have hstage : stage < 2 ^ w := by
+ have := j.isLt
+ simp only [List.length_cons, List.length_map] at this
+ omega
+ have safe (t : Fin 14) : lr t ∉ Set.range sr := placed_disjoint tail reg t
+ obtain ⟨out, dispatch, entryPC, rest⟩ := run_prefix selector (safe 13) hN stage hstage i
+ selects mid atSel info.stage m
+ refine ⟨out, pre.trans dispatch, entryPC, retainLocated info (fun t ↦ rest.regs _ (safe t)), ?_⟩
+ exact ⟨fun a ha ↦ (rest.regs a ha.2).trans (fr.outside a ha.1),
+ rest.memory.trans fr.privateMem, rest.persistent.trans fr.persistent⟩
+
+section Schedule
+
+open Compression CompressorRecords LocalHistory
+
+variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k}
+variable (Tmpl : S.Templates) (f : Tmpl.Entry → R) (hf : Tmpl.IsSolution f)
+variable {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (Tmpl.execute f hf T hT X).Choices)
+local notation "levels" => executeLevels Tmpl f hf T hT X z
+
+/-- On a genuine selected shrinking pass, the stage reached by the native
+dispatcher is the pass's block index and has its actual input degree exponent. -/
+theorem scheduled_run {M : Machine w p r 11} {addr : Fin (count S.steps) → Fin p}
+ {scratch : Fin 4 ↪ Fin r} {src : Fin r} {jump : Fin S.steps → Fin p}
+ (rows : Linked M addr scratch src jump) (fresh : src ∉ Set.range scratch)
+ (hN : S.steps + 1 < 2 ^ w) (j : Fin (levels).length) (fits : j.val < 2 ^ w)
+ (shrink : tagLevel Tmpl f hf levels[j] = .shrink)
+ (c : Config w p r) (start : c.pc = addr (entry S.steps)) (source : c.reg src = (j.val : Word w))
+ (m : Memory w) :
+ ∃ i : Fin S.steps, levels[j].origin.ordinal = i.val ∧
+ levels[j].inputExponent = S.degreeExponent i.castSucc ∧
+ ∃ out, NodeArguments.ChildScan.Prefix M m c out []
+ (List.replicate (S.steps + 7 + 2 * i.val) .tick) ∧
+ out.pc = jump i ∧ Frame scratch c out := by
+ have hr : j.val % (S.steps + 1) ≠ S.steps := by
+ intro he
+ rw [VertexLevel.selected_pass_role Tmpl f hf T hT X z j, ite_eq_left he] at shrink
+ cases shrink
+ have hi : j.val % (S.steps + 1) < S.steps := by
+ have : j.val % (S.steps + 1) < S.steps + 1 := Nat.mod_lt _ (Nat.succ_pos S.steps)
+ omega
+ let i : Fin S.steps := ⟨j.val % (S.steps + 1), hi⟩
+ refine ⟨i, VertexLevel.selected_pass_ordinal Tmpl f hf T hT X z j, ?_,
+ run_prefix rows fresh hN j.val fits i rfl c start source m⟩
+ exact (VertexLevel.selected_inputExponent Tmpl f hf T hT X z j).trans (S.exponentAt_castSucc i)
+
+end Schedule
+
+end PairSimulation.VertexStageDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVertexStageSegment.lean b/lean/OAI/Computability/VPVNP/PairVertexStageSegment.lean
new file mode 100644
index 0000000000..0ef1e65d2f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVertexStageSegment.lean
@@ -0,0 +1,190 @@
+import OAI.Computability.VPVNP.PairVertexStageDispatch
+import OAI.Computability.VPVNP.PairVertexLevelLocator
+import OAI.Computability.VPVNP.PairVertexSegmentChain
+
+/-!
+# Linking the stage selector to a heterogeneous family of shrink handlers
+
+The selector and each handler have separate code ranges. The locator and every
+handler share the same fourteen-word header bank. The selector's scratch words
+and the variable-length handler tails occupy disjoint ranges.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexStageDispatch
+
+open VertexImage BurstRAM PrivateRAM
+
+variable {N n p r w : ℕ}
+
+/-- Size of the scheduled dispatch family, including the selector table and every stage body's
+instructions. -/
+def familyCount (B : Fin N → Segment) := count N + ∑ i, (B i).count
+
+/-- Place stage-selection instructions before the concatenated bodies of the dispatch family. -/
+def selectorPC (B : Fin N → Segment) (loc : Fin (familyCount B) → Fin p)
+ (j : Fin (count N)) := loc (j.castAdd (∑ i, (B i).count))
+
+/-- Place an instruction of a particular scheduled body using its dependent ordinal in the
+concatenated family. -/
+def bodyPC (B : Fin N → Segment) (loc : Fin (familyCount B) → Fin p)
+ (i : Fin N) (j : Fin (B i).count) :=
+ loc ((finSigmaFinEquiv (n := fun i ↦ (B i).count) ⟨i,j⟩).natAdd (count N))
+
+/-- Any explicit bank placement can host the family. Every selected handler
+returns to the enclosing role continuation. -/
+def family (B : Fin N → Segment) (locator : Fin 14 ↪ Fin n) (scratch : Fin 4 ↪ Fin n)
+ (bank : ∀ i, Fin (B i).privateRegs ↪ Fin n) : Segment where
+ count := familyCount B
+ privateRegs := n
+ entry := (entry N).castAdd (∑ i, (B i).count)
+ row loc dfs saved reg done := Fin.addCases
+ (row N (selectorPC B loc) (scratch.trans reg) (reg (locator 13))
+ (fun i ↦ bodyPC B loc i (B i).entry))
+ (fun j ↦ let z := (finSigmaFinEquiv (n := fun i ↦ (B i).count)).symm j
+ (B z.1).row (bodyPC B loc z.1) dfs saved ((bank z.1).trans reg) done z.2)
+
+variable (B : Fin N → Segment) (locator : Fin 14 ↪ Fin n) (scratch : Fin 4 ↪ Fin n)
+ (bank : ∀ i, Fin (B i).privateRegs ↪ Fin n)
+ (loc : Fin (familyCount B) → Fin p) (dfs : Fin 9 ↪ Fin r) (saved : Saved ↪ Fin r)
+ (reg : Fin n ↪ Fin r) (done : Fin p) (M : Machine w p r 11)
+
+/-- Split the concrete image into its selector table and its individually
+relocated branch bodies, with the exact native jump destinations. -/
+theorem family_link (rows : ∀ j, M.code (loc j) =
+ ((family B locator scratch bank).row loc dfs saved reg done j).resize w) :
+ Linked M (selectorPC B loc) (scratch.trans reg) (reg (locator 13))
+ (fun i ↦ bodyPC B loc i (B i).entry) ∧
+ ∀ i j, M.code (bodyPC B loc i j) =
+ ((B i).row (bodyPC B loc i) dfs saved ((bank i).trans reg) done j).resize w := by
+ constructor
+ · intro j
+ simpa only [family, selectorPC, Fin.addCases_left] using rows (j.castAdd (∑ i, (B i).count))
+ · intro i j
+ let E := finSigmaFinEquiv (n := fun i ↦ (B i).count)
+ let emit (z : (i : Fin N) × Fin (B i).count) :=
+ ((B z.1).row (bodyPC B loc z.1) dfs saved ((bank z.1).trans reg) done z.2).resize w
+ calc
+ M.code (bodyPC B loc i j) = emit (E.symm (E ⟨i,j⟩)) := by
+ have hh := rows ((E ⟨i,j⟩).natAdd (count N))
+ simp only [family, Fin.addCases_right] at hh
+ exact hh
+ _ = _ := congrArg emit (E.symm_apply_apply ⟨i,j⟩)
+
+section Canonical
+
+variable (tail : Fin N → ℕ)
+
+/-- The shared locator prefix is followed by four selector scratch words
+and by the private tails in increasing order of shrink stage. -/
+def bankCount := 14 + (4 + ∑ i, tail i)
+
+/-- Number the shared locator and selector scratch registers followed by each body's private
+tail bank. -/
+def bankIndex : (Fin 14 ⊕ Fin 4 ⊕ (i : Fin N) × Fin (tail i)) ≃ Fin (bankCount tail) :=
+ let rest := ((Equiv.refl (Fin 4)).sumCongr finSigmaFinEquiv).trans finSumFinEquiv
+ ((Equiv.refl (Fin 14)).sumCongr rest).trans finSumFinEquiv
+
+/-- Embed the common fourteen-register locator bank in the dispatch family's register layout. -/
+def locatorBank := Function.Embedding.inl.trans (bankIndex tail).toEmbedding
+
+/-- Embed the selector's four scratch registers beside the common locator bank. -/
+def scratchBank := Function.Embedding.inl.trans
+ (Function.Embedding.inr.trans (bankIndex tail).toEmbedding)
+
+/-- Embed only the indicated stage's tail registers in the dependent family of private tail
+banks. -/
+def tailBank (i : Fin N) := (Function.Embedding.sigmaMk (β := fun i ↦ Fin (tail i)) i).trans
+ (Function.Embedding.inr.trans (Function.Embedding.inr.trans (bankIndex tail).toEmbedding))
+
+variable (split : ∀ i, (B i).privateRegs = 14 + tail i)
+
+/-- A handler sees the locator in its first fourteen registers and sees
+only its own tail in the remaining registers. -/
+def bodyBank (i : Fin N) : Fin (B i).privateRegs ↪ Fin (bankCount tail) :=
+ let blocks := (finCongr (split i)).trans finSumFinEquiv.symm
+ let suffix := (Function.Embedding.sigmaMk (β := fun i ↦ Fin (tail i)) i).trans
+ (Function.Embedding.inr (α := Fin 4))
+ blocks.toEmbedding.trans ((Function.Embedding.sumMap (.refl (Fin 14)) suffix).trans
+ (bankIndex tail).toEmbedding)
+
+theorem bodyBank_locator (i : Fin N) (j : Fin 14) :
+ bodyBank B tail split i ((j.castAdd (tail i)).cast (split i).symm) = locatorBank tail j := by
+ change (bankIndex tail) (Sum.map _ _ (finSumFinEquiv.symm _)) = (bankIndex tail) (.inl j)
+ rw [show (finCongr (split i)) ((j.castAdd (tail i)).cast (split i).symm) =
+ finSumFinEquiv (.inl j : Fin 14 ⊕ Fin (tail i)) from rfl, Equiv.symm_apply_apply]
+ rfl
+
+theorem bodyBank_tail (i : Fin N) (j : Fin (tail i)) :
+ bodyBank B tail split i ((j.natAdd 14).cast (split i).symm) = tailBank tail i j := by
+ change (bankIndex tail) (Sum.map _ _ (finSumFinEquiv.symm _)) =
+ (bankIndex tail) (.inr (.inr ⟨i,j⟩))
+ rw [show (finCongr (split i)) ((j.natAdd 14).cast (split i).symm) =
+ finSumFinEquiv (.inr j : Fin 14 ⊕ Fin (tail i)) from rfl, Equiv.symm_apply_apply]
+ rfl
+
+theorem locator_disjoint_scratch (j : Fin 14) :
+ locatorBank tail j ∉ Set.range (scratchBank tail) := by
+ rintro ⟨s,eqn⟩
+ have eq : (Sum.inr (Sum.inl s)) = (Sum.inl j) := (bankIndex tail).injective eqn
+ cases eq
+
+theorem scratch_disjoint_body (i : Fin N) (j : Fin (B i).privateRegs) :
+ bodyBank B tail split i j ∉ Set.range (scratchBank tail) := by
+ rintro ⟨s,eqn⟩
+ obtain ⟨j | j, rfl⟩ := (((finCongr (split i)).trans finSumFinEquiv.symm).symm).surjective j
+ · exact locator_disjoint_scratch tail j ⟨s, eqn.trans (bodyBank_locator B tail split i j)⟩
+ · have eq := eqn.trans (bodyBank_tail B tail split i j)
+ have e : (Sum.inr (Sum.inl s) : Fin 14 ⊕ Fin 4 ⊕ (i : Fin N) × Fin (tail i)) =
+ Sum.inr (Sum.inr ⟨i,j⟩) := (bankIndex tail).injective eq
+ injection e with h
+ cases h
+
+/-- The full shrink role starts by recovering its level and then dispatches
+its zero-based producing ordinal to the selected handler. -/
+def locatedFamily : Segment :=
+ Segment.thenWith VertexLevel.segment
+ (family B (locatorBank tail) (scratchBank tail) (bodyBank B tail split))
+ (locatorBank tail) (.refl _)
+
+/-- Total instruction count of a family preceded by the level locator. -/
+abbrev locatedCount := VertexLevel.segment.count + familyCount B
+
+/-- Program counters of the locator at the beginning of the combined locator-and-dispatch
+image. -/
+def locatorPC (where_ : Fin (locatedCount B) → Fin p) (j : Fin 35) :=
+ where_ (j.castAdd (familyCount B))
+
+/-- Program counters of the dispatch family after the locator's 35 instructions. -/
+def familyPC (where_ : Fin (locatedCount B) → Fin p) (j : Fin (familyCount B)) :=
+ where_ (j.natAdd 35)
+
+/-- Both the 35 locator rows and every selector and stage-body row occur at
+their indicated PCs in the single hosted role. -/
+theorem locatedFamily_link (where_ : Fin (locatedCount B) → Fin p)
+ (reg : Fin (bankCount tail) ↪ Fin r)
+ (rows : ∀ j, M.code (where_ j) =
+ ((locatedFamily B tail split).row where_ dfs saved reg done j).resize w) :
+ (∀ j, M.code (locatorPC B where_ j) =
+ (VertexLevel.segment.row (locatorPC B where_) dfs saved ((locatorBank tail).trans reg)
+ (selectorPC B (familyPC B where_) (entry N)) j).resize w) ∧
+ Linked M (selectorPC B (familyPC B where_)) ((scratchBank tail).trans reg)
+ (reg (locatorBank tail 13)) (fun i ↦ bodyPC B (familyPC B where_) i (B i).entry) ∧
+ ∀ i j, M.code (bodyPC B (familyPC B where_) i j) =
+ ((B i).row (bodyPC B (familyPC B where_) i) dfs saved
+ ((bodyBank B tail split i).trans reg) done j).resize w := by
+ obtain ⟨headRows, familyRows⟩ := Segment.split_link VertexLevel.segment
+ (family B (locatorBank tail) (scratchBank tail) (bodyBank B tail split))
+ (locatorBank tail) (.refl _) where_ dfs saved reg done M rows
+ exact ⟨headRows, family_link B (locatorBank tail) (scratchBank tail) (bodyBank B tail split)
+ (familyPC B where_) dfs saved reg done M familyRows⟩
+
+end Canonical
+end PairSimulation.VertexStageDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualActiveChecks.lean b/lean/OAI/Computability/VPVNP/PairVirtualActiveChecks.lean
new file mode 100644
index 0000000000..f8bb99a17b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualActiveChecks.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PairSelectedRefreshRows
+import OAI.Computability.VPVNP.PairSelectedShrinkRows
+import OAI.Computability.VPVNP.PairVirtualSelectedRoles
+import OAI.Computability.VPVNP.PairVirtualCursorLeafNumbered
+
+/-! # The three native readers on the same selected vertex burst -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords DescriptorSpace CursorNetwork CursorBounds LocalHistory TraversalRows
+open TraversalRoles VertexImage CutSchedule ExponentTrace TreeDecode NetworkKernel DFS
+open scoped Fin.CommRing
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ {D : FixedProgramDiagonal.Program} {B : S.Templates} {u : PairExponents B.growthConstant}
+ {n : ℕ} {hn : 2 ≤ n} {ht : 21 ≤ 2 ^ (D.geometry n).w} {clk : 44 ≤ n ^ 10000}
+ (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (adv : Bits (n ^ D.constants.advicePower))
+ (ξ : Exterior (D.chainHeight n) (n ^ D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+ {labels : ℕ} (order : B.Entry ≃ Fin labels) (f : B.Entry → A) (ok : B.IsSolution f)
+ (sites : SiteParsers f V.scanState.network)
+ (z : (B.execute f ok (blockCount (u.θ : ℝ) n) le_rfl V.scanState).Choices)
+ (baseBits laneBits ord : ℕ)
+
+local notation "group" => D.executionGroup n ht clk
+local notation "pub" => terminalOperands (group)
+local notation "hdr" => vertexHeader (group)
+local notation "w₀" => Geometry.w (D.geometry n)
+local notation "T₀" => blockCount (u.θ : ℝ) n
+local notation "X₀" => VirtualPairs.scanState V
+local notation "exec₀" => B.execute f ok (T₀) le_rfl (X₀)
+local notation "Y₀" => StateExecution.finalState (exec₀) z
+local notation "L₀" => BlockProgram.layout B (Fin.val (pub 2)) (State.positions (X₀)) (T₀)
+local notation "base" => endAddress (L₀)
+local notation "tags" => selected B f ok (T₀) le_rfl (X₀) z
+local notation "passes" => executeLevels B f ok (T₀) le_rfl (X₀) z
+local notation "first" => TaggedLayer.mk (leafLayer (siteOrder (X₀))) Role.cursor
+local notation "size" => tagWords B.recordLimit (tags)
+local notation "width" => State.totalWidth (Y₀)
+local notation "tagWord" => (((size) + (width) : ℕ) : BurstRAM.Word w₀)
+local notation "image" => TerminalProgram.nativeSegments B D.constants D.numerator
+ D.denominator order
+local notation "V₀" => VertexImage.placement (image)
+local notation "M₀" => PrivateRAM.Template.instantiate (VertexImage.template (image)) w₀ pub
+local notation "vals₀" => LeafVisit.cacheWords (V.data adv ξ i (physicalNomination rfl μ))
+ (virtualBits D.addressFactor n) (roundedUp 1 4 n)
+local notation "rate" => RatedRoles.scan B order
+
+attribute [local irreducible] VertexImage.placement VertexImage.template BlockProgram.layout
+ BlockSchedule.Templates.execute CursorNetwork.cursorState CursorBounds.wordBits
+ selectedDesc ordinalJobCost
+
+set_option maxHeartbeats 1200000 in
+-- Unifying the three dependent row domains traverses the entire selected state history.
+/-- Choose each frozen role reader once. Its native code and its selected
+monomial paths then use exactly the same reader and the same argument frame
+in the combined private burst. -/
+theorem VirtualPairs.activeChecks {calendar reference : Memory w₀} (m : Memory w₀)
+ {bits : Fin (Y₀).totalWidth → Bool} {tab : Fin (L₀).shape.tables}
+ (pack : VertexPacked (group) (L₀) B.recordLimit (tags) (width))
+ (entry : TerminalProgram.VertexEntry B f ok (T₀) le_rfl (X₀) z (L₀) tab baseBits laneBits
+ pub calendar reference bits)
+ (later : LinkedVertexMemory (group) reference ord m)
+ (length : (pub 6).val = n) (count : (pub 9).val = labels)
+ (shrinking : TerminalProgram.ShrinkRows B f ok (group) n D.numerator D.denominator order
+ (T₀) le_rfl (X₀) z m)
+ (refreshing : TerminalProgram.RefreshRows B f ok (group) n D.numerator D.denominator order
+ (T₀) le_rfl (X₀) z m)
+ (cursor : let area := NativeFrame.fromHeader (slotDegree S) pub hdr m
+ let offset := m (hdr + 14).val
+ let data := NativeFrame.leafWords (slotDegree S) pub hdr offset m
+ let fmt := SelectedPacketFormat B f ok (T₀) le_rfl (X₀) z (base)
+ let desc := selectedDesc B f ok (T₀) le_rfl (X₀) z (base)
+ ∃ leaf : HookParser w₀ n,
+ leaf.ExactOn (RoleDomains.Leaf (X₀) B.recordLimit (base) area data offset (vals₀))
+ (M₀) ((V₀).entry .leaf) ((V₀).dfsPC 3) (V₀).dfs m ∧
+ ∀ shrink refresh : HookParser w₀ n, SelectedCursorLeaf.Rows (V₀) (M₀)
+ (RoleDomains.handlers leaf shrink refresh) m offset area data (vals₀) B.recordLimit
+ (base) fmt desc order.symm (TerminalLink.workerCell hdr) (n ^ 9000) (n * n ^ 9000)
+ 1 (rate) (X₀) sites) :
+ V.SelectedRowsAt adv ξ i μ order f ok sites z m 1 (rate) := by
+ obtain ⟨geom, offset, _⟩ := entry.role_layout B f ok (T₀) le_rfl (X₀) z (group) n labels
+ baseBits laneBits ord m pack later length count
+ obtain ⟨s, shr⟩ := shrinking
+ obtain ⟨r, ref⟩ := refreshing
+ obtain ⟨leaf, leafNative, leafRows⟩ := cursor
+ let sr := ShrinkRoleDirectory.parser B.recordLimit (base) (first) (passes) s
+ let handlers := RoleDomains.handlers leaf sr r
+ have both := leafRows sr r
+ rw [geom, offset] at leafNative both
+ obtain ⟨shrNative, shrLevels⟩ := shr (vals₀)
+ obtain ⟨refNative, refLevels⟩ := ref (vals₀)
+ apply V.rowsAt_of_layout adv ξ i μ order f ok sites z baseBits laneBits ord 1 (rate) m
+ pack entry later length count _ handlers
+ apply TerminalProgram.VertexEntry.native_checks B f ok (T₀) le_rfl (X₀) z (group)
+ D.numerator D.denominator n labels order baseBits laneBits ord 1 (rate) m pack entry
+ later (vals₀) leaf s r sites length count
+ · intro role
+ cases role with
+ | leaf => exact leafNative
+ | shrink => exact shrNative
+ | refresh => exact refNative
+ · exact both
+ · exact shrLevels leaf r
+ · exact refLevels leaf sr
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualCursorLeaf.lean b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeaf.lean
new file mode 100644
index 0000000000..603f29eec3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeaf.lean
@@ -0,0 +1,186 @@
+import OAI.Computability.VPVNP.PairVirtualCursorLeafNumbered
+import OAI.Computability.VPVNP.PairVirtualCursorLeafHeader
+import OAI.Computability.VPVNP.PairVirtualCursorLeafArena
+import OAI.Computability.VPVNP.PairVirtualPreparedRoot
+import OAI.Computability.VPVNP.PairVertexRoleHandlers
+import OAI.Computability.VPVNP.PairVertexSelectedDesc
+
+/-! # Native cursor leaves of the canonical virtual-pair scan -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+ CompressorRecords
+open CursorNetwork CursorBounds VertexImage TreeDecode LocalHistory TraversalRows DFS CutSchedule
+ ExponentTrace Filter
+open scoped Fin.CommRing
+set_option quotPrecheck false
+set_option maxRecDepth 12000
+
+attribute [local irreducible] CursorBounds.wordBits CursorBounds.virtualBits BurstRAM.addressWidth
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {D : FixedProgramDiagonal.Program}
+ {u : PairExponents B.growthConstant} {n : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {model : LabelEvaluator.Model p (B.compressorDegree n) (B.compressorEquations hn
+ D.constants.circuitExponent)}
+ {ht : 21 ≤ 2 ^ (D.geometry n).w} {clk : 44 ≤ n ^ 10000}
+ [NeZero (virtualBits D.addressFactor n)]
+ (V : D.VirtualPairs B u hn D.constants.circuitExponent) (scalar : D.ScalarData B hn model)
+ (ξ : Exterior (D.chainHeight n) (n ^ D.constants.deltaPower)) (i : D.groupIndices n)
+ (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+ {g : ℕ} (order : B.Entry ≃ Fin g)
+
+local notation "group₀" => D.executionGroup n ht clk
+local notation "pub" => terminalOperands group₀
+local notation "header₀" => vertexHeader group₀
+local notation "w₀" => (D.geometry n).w
+local notation "dim₀" => virtualBits D.addressFactor n
+local notation "lanes₀" => reservedLanes B u n
+local notation "baseBits₀" => dim₀ - lanes₀
+local notation "X₀" => V.scanState
+local notation "T₀" => blockCount (u.θ : ℝ) n
+local notation "κ" => B.compressorValues hn model
+local notation "ok" => B.compressorValues_solution hn model
+local notation "L₀" => BlockProgram.layout B (pub 2).val (X₀).positions T₀
+local notation "base₀" => DescriptorSpace.endAddress (L₀)
+local notation "seg₀" => TerminalProgram.nativeSegments B D.constants D.numerator D.denominator
+ order
+local notation "V₀" => VertexImage.placement (seg₀)
+local notation "M₀" => PrivateRAM.Template.instantiate (VertexImage.template (seg₀)) w₀ pub
+local notation "aux" => V.data scalar.advice ξ i (physicalNomination (D := D) (n := n) (ht := ht)
+ (hf := clk) rfl μ)
+
+variable (m : Memory (D.geometry n).w)
+local notation "region" => NativeFrame.fromHeader (slotDegree S) pub header₀ m
+local notation "offset" => m (header₀ + 14).val
+local notation "words" => NativeFrame.leafWords (slotDegree S) pub header₀ offset m
+
+/-- The concrete handler executes the selected nomination with the full
+virtual dimension and its actual private fuel. -/
+noncomputable abbrev VirtualPairs.cursorLeafParser
+ (fit : (region).stackBase + Fintype.card LeafStartup.ScalarPort * n ^ 40 < 2 ^ w₀) :
+ HookParser w₀ n :=
+ @LeafRole.parser w₀ n words (D.pairLengths i) n (D.geometry n).d (D.geometry n).H
+ (n ^ (D.constants.circuitExponent + 5)) (V.layout i) aux dim₀ 0 (roundedUp 1 4 n)
+ (inferInstanceAs (NeZero dim₀)) V.cap region fit m (n ^ 39)
+
+variable {V scalar ξ i μ} (A : CanonicalScan scalar V ξ i (physicalNomination (D := D) (n := n)
+ (ht := ht) (hf := clk) rfl μ))
+ (z : (V.selection (M := model)).Choices) (power scan : ℕ)
+
+local notation "format" => SelectedPacketFormat B κ ok T₀ le_rfl X₀ z (base₀)
+local notation "desc" => selectedDesc B κ ok T₀ le_rfl X₀ z (base₀)
+local notation "guard" => TerminalLink.workerCell header₀
+local notation "histVals" => LeafVisit.cacheWords aux dim₀ (roundedUp 1 4 n)
+
+attribute [local irreducible] BlockSchedule.Templates.execute VertexImage.placement
+ VertexImage.template
+ CursorNetwork.cursorState NativeOperands.saved NativeOperands.capacity
+
+/-- The initial packets of the mathematical scan execute on the installed
+vertex table and use the common cost bound of its shrink and refresh roles. -/
+theorem CanonicalScan.cursorRows (large : 2048 ≤ n) (two : 2 ≤ scan)
+ (resources : LeafVisit.CursorLeafBounds aux V.cap)
+ (head : V.CursorLeafHeader scalar.advice ξ i μ m)
+ (arena : V.CursorLeafArena (ht := ht) (clk := clk) κ ok z m g)
+ (shrink refresh : HookParser w₀ n) :
+ SelectedCursorLeaf.Rows V₀ M₀
+ (RoleDomains.handlers (V.cursorLeafParser scalar ξ i μ m arena.fit) shrink refresh)
+ m offset region words histVals B.recordLimit (base₀) format desc order.symm guard
+ (n ^ 9000) (n * n ^ 9000) power scan X₀ A.leafSites := by
+ have shadow (site : BurstRAM.Word (group₀).w) (within : site < LeafRole.addressFields
+ (words) .span) :
+ TerminalLink.workerCell header₀ (LeafRole.addressFields (words) .shadow + site).val := by
+ change site.val < (m (header₀ + 20).val).val at within
+ change TerminalLink.workerCell header₀ ((pub 3) + site).val
+ have room : (pub 3).val + site.val < 2 ^ (group₀).w :=
+ (Nat.add_lt_add_left within (pub 3).val).trans_le head.shadowRoom
+ rw [Fin.val_add, Nat.mod_eq_of_lt room]
+ exact head.shadowSafe site.val within
+ exact SelectedCursorLeaf.numberedRows (S := S) V₀ M₀ aux (Nat.sub_add_cancel V.lanes).symm
+ V.dimension V.cap κ A.clock m header₀ offset (slotDegree S) B.recordLimit (base₀)
+ (template_contains (seg₀) pub) arena.fit resources large head.stride head.radixB head.radixL
+ head.span
+ head.shadowRoom head.shadowData arena.size arena.address
+ (RoleDomains.handlers (V.cursorLeafParser scalar ξ i μ m arena.fit) shrink refresh) rfl
+ guard shadow arena.tag arena.tagRead format desc arena.typed order.symm arena.histWords.ge
+ (n ^ 9000) (n * n ^ 9000) power scan two (selectedDesc_leaf B κ ok T₀ le_rfl X₀ z (base₀))
+
+local notation "Y₀" => (V.selection (M := model)).finalState z
+local notation "tags₀" => TraversalRoles.selected B κ ok T₀ le_rfl X₀ z
+
+/-- At any chronological site after the packed traversal, the real private
+arena is large enough for the handler and its cursor packets have the exact
+native effects used by the ordinal computation. -/
+def CanonicalScan.CursorLeafCalls : Prop :=
+ ∀ {initial : Memory w₀} {N : PairStages.Group.Indexed group₀ Stage.nominations initial
+ (PairStages.Group.Nominations.Nom group₀)}
+ (prepared : PreparedBranch group₀ initial (physicalPairIndex i)
+ ((physicalPairLengths (ht := ht) (hf := clk) i).symm ▸ PairedChain.headers scalar.advice ξ
+ i) N μ)
+ {calendar reference : Memory w₀} {tab : Fin (L₀).shape.tables} {bits : Fin (Y₀).totalWidth
+ → Bool}
+ {ord : ℕ},
+ TerminalProgram.VertexEntry B κ ok T₀ le_rfl X₀ z (L₀) tab baseBits₀ lanes₀ pub calendar
+ reference bits →
+ LinkedVertexMemory group₀ reference ord m →
+ (∀ x < (pub 2).val, x ≠ (PairTag.address pub).val → calendar x = prepared.copy.memory () x) →
+ ∃ fit : (region).stackBase + Fintype.card LeafStartup.ScalarPort * n ^ 40 < 2 ^ w₀,
+ ∀ shrink refresh : HookParser w₀ n,
+ SelectedCursorLeaf.Rows V₀ M₀
+ (RoleDomains.handlers (V.cursorLeafParser scalar ξ i μ m fit) shrink refresh)
+ m offset region words histVals B.recordLimit (base₀) format desc order.symm guard
+ (n ^ 9000) (n * n ^ 9000) power scan X₀ A.leafSites
+
+/-- One threshold supplies the interpreter, all virtual stacks, the packed
+vertex, and every native leaf of every selected occurrence. -/
+theorem eventually_virtualCursorLeafCalls (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (order : B.Entry ≃ Fin g)
+ (hg : D.constants.motifLabels = Fintype.card B.Entry) (haddr : max S.laneBits 5 ≤
+ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ [NeZero (virtualBits D.addressFactor n)] (ht : 21 ≤ 2 ^ (D.geometry n).w)
+ (clk : 44 ≤ n ^ 10000)
+ {p : Nat.Primes} {model : LabelEvaluator.Model p (B.compressorDegree n)
+ (B.compressorEquations hn D.constants.circuitExponent)}
+ (scalar : D.ScalarData B hn model) (ξ : Exterior (D.chainHeight n)
+ (n ^ D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+ (A : CanonicalScan scalar V ξ i (physicalNomination (D := D) (n := n) (ht := ht)
+ (hf := clk) rfl μ)) (z : (V.selection (M := model)).Choices)
+ (m : Memory (D.geometry n).w) (power scan : ℕ), 2 ≤ scan → A.CursorLeafCalls order m z power
+ scan := by
+ filter_upwards [eventually_ge_atTop 2048, eventually_virtualCursorLeafBounds D B u,
+ eventually_selectedRootBudget D B u haddr hnum hden D.constants.circuitExponent,
+ eventually_virtualCursorStackBudget D B u haddr hnum hden D.constants.circuitExponent]
+ with n large clocks roots stackBudgets
+ intro hn V nz ht clk p model scalar ξ i μ A z m power scan two initial N prepared calendar
+ reference tab bits ord entry later low
+ have hf := roots hn V ht clk model.algebra (B.compressorValues hn model)
+ (B.compressorValues_solution hn model)
+ have pack := (hf.2.2.2 z).1
+ have card : Fintype.card B.Entry = g := (Fintype.card_congr order).trans (Fintype.card_fin g)
+ have count := (physical_counter_end (D.executionGroup n ht clk) pack.fit).2.2.trans
+ (hg.trans card)
+ have cap := stackBudgets hn V ht clk model.algebra (B.compressorValues hn model)
+ (B.compressorValues_solution hn model) z
+ rw [card] at cap
+ have arena := V.cursorLeafArena (B.compressorValues hn model) (B.compressorValues_solution hn
+ model)
+ z m g pack entry later hf.2.2.1 count cap
+ have head := V.cursorLeafHeader scalar.advice ξ i μ prepared pack entry later low
+ refine ⟨arena.fit, fun shrink refresh => ?_⟩
+ exact A.cursorRows order m z power scan large two (clocks hn V scalar.advice ξ i μ) head arena
+ shrink refresh
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafArena.lean b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafArena.lean
new file mode 100644
index 0000000000..dde92d67c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafArena.lean
@@ -0,0 +1,187 @@
+import OAI.Computability.VPVNP.PairVirtualRootBudget
+import OAI.Computability.VPVNP.PairVertexRootEntry
+import OAI.Computability.VPVNP.PairSelectedPacketGeometry
+import OAI.Computability.VPVNP.PairSimulationLeafRoleHandler
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-!
+# Cursor rows in the live virtual pair arena
+
+The shared-bit handoff publishes the first row and the role displacement.
+Earlier ordinals preserve both fields and the selected role table, so every
+cursor read uses the original row address and stays below the terminal header.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+section
+
+open BurstRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords DescriptorSpace CursorNetwork CursorBounds Filter TraversalRows
+
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant)
+
+attribute [local irreducible] BlockSchedule.Templates.execute BlockProgram.layout
+ CursorNetwork.cursorState
+
+/-- All private cursor stacks for a selected virtual branch fit at one input-length threshold. -/
+theorem eventually_virtualCursorStackBudget (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) (C : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C) (ht : 21 ≤ 2 ^ (D.geometry n).w)
+ (clk : 44 ≤ n ^ 10000) (A : Type*) [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f),
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f ok T le_rfl X
+ let pub := terminalOperands (D.executionGroup n ht clk)
+ let L := BlockProgram.layout B (pub 2).val X.positions T
+ ∀ z : E.Choices,
+ let rows := words B.recordLimit (selectedLayers B f ok T le_rfl X z)
+ (TerminalLayout.privateRegions (slotDegree S) n (endAddress L + rows)
+ (Fintype.card B.Entry)).stackBase +
+ Fintype.card LeafStartup.ScalarPort * n ^ 40 < 2 ^ (D.geometry n).w := by
+ let start := fun n => (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ have poly : PolynomiallyBounded start := by
+ have eqn : start = fun n => (LiveProgram.Layout.pairWorkspace D.constants).eval
+ (paperGeometry D.addressFactor (liveCapacity u) n) := by
+ funext n
+ change (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n) = _
+ rw [paperGeometry_eq D B u hnum hden n]
+ rw [eqn]
+ exact CompressedPair.startup_workspace_polynomial _ D.address_pos (liveCapacity_polynomial u)
+ filter_upwards [CompressedPair.eventually_startup_inputs D.constants D.address_pos
+ (liveCapacity_polynomial u),
+ TerminalLayout.eventually_packedFit B u D.addressFactor haddr poly
+ (Fintype.card LeafStartup.ScalarPort) (fun _ => 0) (PolynomiallyBounded.const 0)]
+ with n hwords hstack
+ intro hn V ht clk A inst f ok
+ dsimp only
+ rw [V.scanState_pairInput]
+ let G := D.executionGroup n ht clk
+ let coords := laneLabels _ _ V.lanes
+ have pub := hwords (CounterPublic.actualPrefix D.literal)
+ rw [← paperGeometry_eq D B u hnum hden n] at pub
+ have workspace : (terminalOperands G 2).val = start n := pub.1
+ intro z
+ have bound := (hstack coords V.dimension le_rfl A f ok z).2.2.2.1
+ change (TerminalLayout.privateRegions _ _
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val _ _) + _) _).stackBase + _ < _
+ rw [workspace, pairInput_positions]
+ simp only [Nat.add_zero] at bound
+ exact bound
+
+end
+
+open BurstRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression CompressorRecords
+open DescriptorSpace CursorNetwork LocalHistory TraversalRows TraversalRoles TreeDecode
+open scoped Fin.CommRing
+
+variable {K A : Type*} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ {B : S.Templates} {u : PairExponents B.growthConstant} {D : FixedProgramDiagonal.Program}
+ {n C : ℕ} {hn : 2 ≤ n} {ht : 21 ≤ 2 ^ (D.geometry n).w} {clk : 44 ≤ n ^ 10000}
+ (V : D.VirtualPairs B u hn C) (f : B.Entry → A) (ok : B.IsSolution f)
+
+local notation "G₀" => D.executionGroup n ht clk
+local notation "pub" => terminalOperands G₀
+local notation "hdr" => vertexHeader G₀
+local notation "w₀" => Geometry.w (D.geometry n)
+local notation "T₀" => blockCount (u.θ : ℝ) n
+local notation "X₀" => V.scanState
+local notation "L₀" => BlockProgram.layout B (Fin.val (pub 2)) (State.positions X₀) T₀
+local notation "first₀" => endAddress (L₀)
+local notation "leaves₀" => sitePointers B.recordLimit (first₀) (siteOrder X₀)
+
+variable (z : (B.execute f ok (blockCount (u.θ : ℝ) n) le_rfl V.scanState).Choices)
+ (m : Memory (D.geometry n).w)
+
+local notation "Y₀" => StateExecution.finalState (B.execute f ok T₀ le_rfl X₀) z
+local notation "layers₀" => selectedLayers B f ok T₀ le_rfl X₀ z
+local notation "rows₀" => words B.recordLimit (layers₀)
+local notation "tags₀" => selected B f ok T₀ le_rfl X₀ z
+local notation "R₀" => NativeFrame.fromHeader (slotDegree S) pub hdr m
+local notation "offset₀" => m (Fin.val (hdr + 14))
+local notation "data₀" => NativeFrame.leafWords (slotDegree S) pub hdr (offset₀) m
+
+attribute [local irreducible] BlockSchedule.Templates.execute BlockProgram.layout
+ CursorNetwork.cursorState CursorBounds.wordBits CursorBounds.virtualBits
+
+/-- The actual public cursor tags and private arena used at an ordinal. -/
+structure VirtualPairs.CursorLeafArena (labels : ℕ) : Prop where
+ fit : (R₀).stackBase + Fintype.card LeafStartup.ScalarPort * n ^ 40 < 2 ^ w₀
+ size : (pub 6).val = n
+ address : (first₀) = (LeafRole.addressFields (data₀) .base).val
+ nodes : (R₀).nodes = (first₀) + (rows₀)
+ histWords : (R₀).histWords = labels
+ typed : ∀ q, SelectedPacketFormat B f ok T₀ le_rfl X₀ z (first₀) q →
+ q.node < (R₀).nodes ∧ q.node < 2 ^ w₀
+ tag : ∀ u, m ((offset₀) + (((leaves₀) u).1 : Word w₀)).val = 0
+ tagRead : ∀ u, TerminalLink.workerCell hdr ((offset₀) + (((leaves₀) u).1 : Word w₀)).val
+
+open private ptr_bounds from OAI.Computability.VPVNP.PairTraversalDisjoint
+
+/-- The packed descriptor interval, surviving header publications and the
+allocated scalar stacks supply every cursor address and tag bound. -/
+theorem VirtualPairs.cursorLeafArena (labels : ℕ)
+ {tab : Fin (L₀).shape.tables} {baseBits laneBits ord : ℕ}
+ {calendar reference : Memory w₀} {bits : Fin (Y₀).totalWidth → Bool}
+ (pack : VertexPacked G₀ (L₀) B.recordLimit (tags₀) (Y₀).totalWidth)
+ (entry : TerminalProgram.VertexEntry B f ok T₀ le_rfl X₀ z (L₀) tab baseBits laneBits
+ pub calendar reference bits)
+ (later : LinkedVertexMemory G₀ reference ord m)
+ (length : (pub 6).val = n) (count : (pub 9).val = labels)
+ (stack : (TerminalLayout.privateRegions (slotDegree S) n ((first₀) + (rows₀)) labels).stackBase
+ + Fintype.card LeafStartup.ScalarPort * n ^ 40 < 2 ^ w₀) :
+ V.CursorLeafArena (ht := ht) (clk := clk) f ok z m labels := by
+ have sizeEq : tagWords B.recordLimit (tags₀) = (rows₀) :=
+ congrArg (words B.recordLimit) (selected_layers B f ok T₀ le_rfl X₀ z)
+ have arena := pack.arena
+ rw [sizeEq] at arena
+ have room : (hdr).val + 32 ≤ 2 ^ w₀ := pack.room
+ have headRoom : (hdr).val + 31 < 2 ^ w₀ := by omega
+ have reg := entry.selected_regions pack later n labels length count
+ have firstField := entry.packedField pack 4 (by decide) (by decide) (by decide)
+ change reference (hdr + 4).val = ((first₀) : Word w₀) at firstField
+ have rowField : m (hdr + 4).val = ((first₀) : Word w₀) :=
+ (pack.header later 4 (by decide) (by decide)).trans firstField
+ have displacement : (offset₀).val = (rows₀) + (Y₀).totalWidth := by
+ have phys := pack.header later 14 (by decide) (by decide)
+ change m (hdr + 14).val = reference (hdr + 14).val at phys
+ have field : (hdr + 14).val = (hdr).val + 14 :=
+ TerminalFootprint.header_val hdr headRoom (j := 14) (by decide)
+ rw [phys, field,
+ entry.offset, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ have tags := pack.roleWords later (sizeEq ▸ entry.roles)
+ have cursor (u : (X₀).network.Site) :
+ m ((offset₀) + (((leaves₀) u).1 : Word w₀)).val = 0 ∧
+ TerminalLink.workerCell hdr ((offset₀) + (((leaves₀) u).1 : Word w₀)).val := by
+ have leafEnd : address B.recordLimit (first₀) (siteOrder X₀).length ≤ (first₀) + (rows₀) := by
+ rw [selectedLayers_eq_levels B f ok T₀ le_rfl X₀ z]
+ simp only [address, words, List.map_cons, leafLayer, List.sum_cons, Nat.mul_add]
+ exact Nat.add_le_add_left (Nat.le_add_right _ _) _
+ have row := (ptr_bounds (siteOrder X₀) B.recordLimit (first₀) u).2.trans_le leafEnd
+ have below : (offset₀).val + ((leaves₀) u).1 < (hdr).val := by omega
+ have atTag : ((offset₀) + (((leaves₀) u).1 : Word w₀)).val =
+ (offset₀).val + ((leaves₀) u).1 := by
+ rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : ((leaves₀) u).1 < 2 ^ w₀),
+ Nat.mod_eq_of_lt (by omega)]
+ rw [atTag]
+ refine ⟨?_, TerminalFootprint.below hdr headRoom below⟩
+ rw [displacement]
+ exact reads_cursor B f ok T₀ le_rfl X₀ z m _ _ (sizeEq ▸ tags) u
+ refine ⟨reg ▸ stack, length, ?_, congrArg LeafArena.Regions.nodes reg,
+ congrArg LeafArena.Regions.histWords reg, ?_, fun u => (cursor u).1, fun u => (cursor u).2⟩
+ · change (first₀) = (m (hdr + 4).val).val
+ rw [rowField, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)]
+ · intro q hq
+ have h := selected_packet_node B f ok T₀ le_rfl X₀ z (first₀) hq
+ exact ⟨reg ▸ h, by omega⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafBounds.lean b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafBounds.lean
new file mode 100644
index 0000000000..bacd7ff5d3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafBounds.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.LiveVirtualPairContinuation
+import OAI.Computability.VPVNP.PairSimulationLeafBootClock
+import OAI.Computability.VPVNP.PairSimulationLeafImageHandler
+import OAI.Computability.VPVNP.PairSimulationNominationAssembly
+
+/-! # Resource bounds for the native leaves of a virtual pair -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LeafVisit
+
+open BurstRAM CursorNetwork CursorRouting LeafStartup LocalHistory
+
+variable {n d e w a H s : ℕ} [NeZero d] {L : PrimedInputRAM.Lengths}
+ {Q : PrimedInputRAM.Layout L n a H w}
+
+/-- The native cursor decoder, stack interpreter and initializer use the
+same dimensions and private fuel as the selected auxiliary counter. -/
+structure CursorLeafBounds (aux : PrimedCounter.Data Q s) (cap : ProcessorBudget n d e w) : Prop where
+ clock : NominationClock aux cap.tags cap.capFits (n^39)
+ width : d ≤ w
+ time : ∀ (v : Position d) (buf : Buffers d (2^e) w),
+ steps 52 (auxiliary aux cap.tags cap.capFits v buf) ≤ n^39
+ room : ∀ (v : Position d) (buf : Buffers d (2^e) w) j,
+ (auxiliaryBank aux cap.tags cap.capFits v buf j).length + n^39 ≤ n^40
+ boot : ∀ (v : Site d) (buf : Buffers d (2^e) w),
+ LeafBoot.ticks aux cap.tags cap.capFits v buf ≤ n^15
+
+end PairSimulation.LeafVisit
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM Compression CursorBounds CursorNetwork CutSchedule ExponentTrace Filter LiveProgram
+open PairSimulation
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant)
+
+/-- A single input-length threshold applies to every physical nomination,
+pair index, site and independently supplied half-wire buffer. -/
+theorem eventually_virtualCursorLeafBounds :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ [NeZero (virtualBits D.addressFactor n)] {ht : 21 ≤ 2^(D.geometry n).w} {clk : 44 ≤ n^10000}
+ (adv : Bits (n^D.constants.advicePower)) (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk)),
+ LeafVisit.CursorLeafBounds (V.data adv ξ i (physicalNomination rfl μ)) V.cap := by
+ filter_upwards [LeafVisit.eventually_resources, LeafBoot.eventually_ticks] with n resources boot
+ intro hn V inst ht clk adv ξ i μ
+ let nom := physicalNomination rfl μ
+ let aux := V.data adv ξ i nom
+ have work := (V.counts i (PairedChain.headers adv ξ i) nom).privateWork
+ change 6 * aux.fuel ≤ n^10 at work
+ have fuel : aux.fuel ≤ n^10 := (Nat.le_mul_of_pos_left _ (by decide : 0 < 6)).trans work
+ have h := resources _ _ _ V.cap _ _ _ _ (V.layout i) aux fuel
+ have fit := V.cap.capFits
+ rw [← pow_add] at fit
+ have dim := (Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp fit
+ exact ⟨fun v z => (h v (halfBuffers v z)).1, (Nat.le_add_right ..).trans dim.le,
+ fun v buf => (h v buf).1, fun v buf => (h v buf).2,
+ fun v buf => boot aux V.cap.tags V.cap.capFits v buf V.cap fuel⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafExact.lean b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafExact.lean
new file mode 100644
index 0000000000..ea9c04d9dd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafExact.lean
@@ -0,0 +1,175 @@
+import OAI.Computability.VPVNP.PairVirtualCursorLeaf
+import OAI.Computability.VPVNP.PairVertexRoleNativeLeaf
+
+/-! # Native leaf execution on the virtual pair's scan state -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage.RoleDomains
+
+open BurstRAM PrivateRAM CursorNetwork CursorRouting Compression DFS TreeDecode LeafStartup NativeFrame LocalHistory
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+open scoped Fin.CommRing
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+ {geometry rootFields shrink refresh : Segment} {p r w : ℕ}
+ (V : Placement (segments geometry rootFields LeafRole.segment shrink refresh) p r)
+ (M : Machine w p r 11) {L : PrimedInputRAM.Lengths} {n a H s : ℕ}
+ {Q : PrimedInputRAM.Layout L n a H w} (aux : PrimedCounter.Data Q s)
+ {d b l e : ℕ} [NeZero d] (split : d = b+l) (dim : 1 < d) (cap : ProcessorBudget n d e w)
+ (m : Memory w) (header offset : Word w) (arity rowCap rowBase : ℕ)
+
+local notation "region" => fromHeader arity M.publicData header m
+local notation "words" => leafWords arity M.publicData header offset m
+local notation "numbering" => Equiv.trans (finCongr split) (cursorCoordinateLabels b l)
+local notation "X" => scanInput numbering dim S e w
+
+/-- On the scan's original coordinate numbering, the leaf handler accepts
+and rejects exactly as its machine entry does on every stored cursor packet. -/
+theorem nativeNumberedLeaf (link : Contains V M)
+ (fit : (region).stackBase + Fintype.card ScalarPort*n^40 < 2^w)
+ (resources : LeafVisit.CursorLeafBounds aux cap)
+ (address : rowBase = (LeafRole.addressFields words .base).val)
+ (stride : (m (header+15).val).val = rowCap+2)
+ (radixB : (m (header+18).val).val = 2^b) (radixL : (m (header+19).val).val = 2^l)
+ (span : (m (header+20).val).val = LiveAuxiliaryHeaders.span L aux.hist.length)
+ (shadowFit : (M.publicData 3).val + (m (header+20).val).val ≤ 2^w)
+ (headers : ∀ j < (m (header+20).val).val, (m ((M.publicData 3).val+j)).val = (aux.initial j).val)
+ (size : (M.publicData 6).val = n) :
+ (LeafRole.parser (endAddr := n) (b := d) (l := 0) words aux cap region fit m (n^39)).ExactOn
+ (Leaf X rowCap rowBase region words offset (LeafVisit.cacheWords aux d e))
+ M (V.entry .leaf) (V.dfsPC 3) V.dfs m := by
+ subst d
+ exact nativeLeaf aux dim (Nat.add_sub_of_le S.degree_bounds.1) V M cap m header offset
+ arity rowCap (n^39) rowBase fit link address stride radixB radixL span shadowFit headers
+ size resources.time resources.room
+
+end PairSimulation.VertexImage.RoleDomains
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression CompressorRecords
+open CursorNetwork CursorBounds VertexImage TreeDecode DFS CutSchedule ExponentTrace Filter LocalHistory TraversalRows
+open scoped Fin.CommRing
+set_option quotPrecheck false
+set_option maxRecDepth 12000
+set_option maxHeartbeats 1400000
+
+attribute [local irreducible] CursorBounds.wordBits CursorBounds.virtualBits BurstRAM.addressWidth
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {D : FixedProgramDiagonal.Program}
+ {u : PairExponents B.growthConstant} {n : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {model : LabelEvaluator.Model p (B.compressorDegree n) (B.compressorEquations hn D.constants.circuitExponent)}
+ {ht : 21 ≤ 2^(D.geometry n).w} {clk : 44 ≤ n^10000}
+ [NeZero (virtualBits D.addressFactor n)]
+ (V : D.VirtualPairs B u hn D.constants.circuitExponent) (scalar : D.ScalarData B hn model)
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n)
+ (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+ {g : ℕ} (order : B.Entry ≃ Fin g) (z : (V.selection (M := model)).Choices)
+ (m : Memory (D.geometry n).w)
+
+local notation "group₀" => D.executionGroup n ht clk
+local notation "pub" => terminalOperands group₀
+local notation "header₀" => vertexHeader group₀
+local notation "w₀" => (D.geometry n).w
+local notation "dim₀" => virtualBits D.addressFactor n
+local notation "lanes₀" => reservedLanes B u n
+local notation "T₀" => blockCount (u.θ : ℝ) n
+local notation "κ" => B.compressorValues hn model
+local notation "ok" => B.compressorValues_solution hn model
+local notation "L₀" => BlockProgram.layout B (pub 2).val V.scanState.positions T₀
+local notation "rowBase" => DescriptorSpace.endAddress (L₀)
+local notation "seg₀" => TerminalProgram.nativeSegments B D.constants D.numerator D.denominator order
+local notation "V₀" => VertexImage.placement (seg₀)
+local notation "M₀" => PrivateRAM.Template.instantiate (VertexImage.template (seg₀)) w₀ pub
+local notation "aux" => V.data scalar.advice ξ i (physicalNomination (D := D) (n := n) (ht := ht) (hf := clk) rfl μ)
+local notation "region" => NativeFrame.fromHeader (slotDegree S) pub header₀ m
+local notation "offset" => m (header₀+14).val
+local notation "words" => NativeFrame.leafWords (slotDegree S) pub header₀ offset m
+local notation "cache" => LeafVisit.cacheWords aux dim₀ (roundedUp 1 4 n)
+local notation "domain" => RoleDomains.Leaf V.scanState B.recordLimit (rowBase) region words offset cache
+
+attribute [local irreducible] BlockSchedule.Templates.execute VertexImage.placement VertexImage.template
+ CursorNetwork.cursorState NativeOperands.saved NativeOperands.capacity
+
+/-- Success and rejection for the installed vertex machine at any leaf packet
+of the selected virtual pair. Its cache contains the actual auxiliary data. -/
+theorem VirtualPairs.cursorLeafExact (resources : LeafVisit.CursorLeafBounds aux V.cap)
+ (head : V.CursorLeafHeader scalar.advice ξ i μ m)
+ (arena : V.CursorLeafArena (ht := ht) (clk := clk) κ ok z m g) :
+ (V.cursorLeafParser scalar ξ i μ m arena.fit).ExactOn
+ domain
+ M₀ ((V₀).entry .leaf) ((V₀).dfsPC 3) (V₀).dfs m :=
+ RoleDomains.nativeNumberedLeaf (S := S) (Q := V.layout i) (d := dim₀) (b := dim₀-lanes₀)
+ (l := lanes₀) (e := roundedUp 1 4 n) V₀ M₀ aux (Nat.sub_add_cancel V.lanes).symm
+ V.dimension V.cap m header₀ offset (slotDegree S) B.recordLimit (rowBase)
+ (template_contains (seg₀) pub) arena.fit resources arena.address head.stride
+ head.radixB head.radixL head.span head.shadowRoom head.shadowData arena.size
+
+variable {V scalar ξ i μ} (A : CanonicalScan scalar V ξ i (physicalNomination (D := D) (n := n)
+ (ht := ht) (hf := clk) rfl μ)) (power scan : ℕ)
+
+local notation "Y₀" => (V.selection (M := model)).finalState z
+local notation "format" => SelectedPacketFormat B κ ok T₀ le_rfl V.scanState z (rowBase)
+local notation "desc" => selectedDesc B κ ok T₀ le_rfl V.scanState z (rowBase)
+local notation "guard" => TerminalLink.workerCell header₀
+
+/-- At each reached vertex, the same private arena supplies both exact
+execution on arbitrary nomination tapes and the selected cursor jobs. -/
+def CanonicalScan.CursorLeafExactCalls : Prop :=
+ ∀ {initial : Memory w₀} {N : PairStages.Group.Indexed group₀ Stage.nominations initial
+ (PairStages.Group.Nominations.Nom group₀)}
+ (prepared : PreparedBranch group₀ initial (physicalPairIndex i)
+ ((physicalPairLengths (ht := ht) (hf := clk) i).symm ▸ PairedChain.headers scalar.advice ξ i) N μ)
+ {calendar reference : Memory w₀} {tab : Fin (L₀).shape.tables} {bits : Fin (Y₀).totalWidth → Bool}
+ {ord : ℕ},
+ TerminalProgram.VertexEntry B κ ok T₀ le_rfl V.scanState z (L₀) tab (dim₀-lanes₀) lanes₀
+ pub calendar reference bits →
+ LinkedVertexMemory group₀ reference ord m →
+ (∀ x < (pub 2).val, x ≠ (PairTag.address pub).val → calendar x = prepared.copy.memory () x) →
+ ∃ fit : (region).stackBase + Fintype.card LeafStartup.ScalarPort*n^40 < 2^w₀,
+ (V.cursorLeafParser scalar ξ i μ m fit).ExactOn domain M₀ ((V₀).entry .leaf) ((V₀).dfsPC 3) (V₀).dfs m ∧
+ ∀ shrink refresh : HookParser w₀ n,
+ SelectedCursorLeaf.Rows V₀ M₀
+ (RoleDomains.handlers (V.cursorLeafParser scalar ξ i μ m fit) shrink refresh)
+ m offset region words cache B.recordLimit (rowBase) format desc order.symm guard
+ (n^9000) (n*n^9000) power scan V.scanState A.leafSites
+
+/-- One threshold supplies the exact native cursor handler and its selected
+row effects for every nomination and chronological vertex of the fixed pair. -/
+theorem eventually_virtualCursorLeafExactCalls (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (order : B.Entry ≃ Fin g)
+ (hg : D.constants.motifLabels = Fintype.card B.Entry) (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ [NeZero (virtualBits D.addressFactor n)] (ht : 21 ≤ 2^(D.geometry n).w) (clk : 44 ≤ n^10000)
+ {p : Nat.Primes} {model : LabelEvaluator.Model p (B.compressorDegree n) (B.compressorEquations hn D.constants.circuitExponent)}
+ (scalar : D.ScalarData B hn model) (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+ (A : CanonicalScan scalar V ξ i (physicalNomination (D := D) (n := n) (ht := ht) (hf := clk) rfl μ))
+ (z : (V.selection (M := model)).Choices)
+ (m : Memory (D.geometry n).w) (power scan : ℕ), 2 ≤ scan → A.CursorLeafExactCalls order z m power scan := by
+ filter_upwards [eventually_ge_atTop 2048, eventually_virtualCursorLeafBounds D B u,
+ eventually_selectedRootBudget D B u haddr hnum hden D.constants.circuitExponent,
+ eventually_virtualCursorStackBudget D B u haddr hnum hden D.constants.circuitExponent] with n large clocks roots stackBudgets
+ intro hn V inst ht clk p model scalar ξ i μ A z m power scan two initial N prepared calendar reference tab bits ord entry later low
+ have resources := clocks hn V scalar.advice ξ i μ
+ have hf := roots hn V ht clk model.algebra (B.compressorValues hn model) (B.compressorValues_solution hn model)
+ have pack := (hf.2.2.2 z).1
+ have card : Fintype.card B.Entry = g := (Fintype.card_congr order).trans (Fintype.card_fin g)
+ have count := (physical_counter_end (D.executionGroup n ht clk) pack.fit).2.2.trans (hg.trans card)
+ have cap := stackBudgets hn V ht clk model.algebra (B.compressorValues hn model) (B.compressorValues_solution hn model) z
+ rw [card] at cap
+ have arena := V.cursorLeafArena (B.compressorValues hn model) (B.compressorValues_solution hn model)
+ z m g pack entry later hf.2.2.1 count cap
+ have head := V.cursorLeafHeader scalar.advice ξ i μ prepared pack entry later low
+ exact ⟨arena.fit, V.cursorLeafExact scalar ξ i μ order z m resources head arena,
+ A.cursorRows order m z power scan large two resources head arena⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafHeader.lean b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafHeader.lean
new file mode 100644
index 0000000000..765010005a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafHeader.lean
@@ -0,0 +1,313 @@
+import OAI.Computability.VPVNP.LiveVirtualPairOccurrence
+import OAI.Computability.VPVNP.LiveVirtualPairPaperDescriptor
+import OAI.Computability.VPVNP.LiveVirtualPairShadowCapacity
+import OAI.Computability.VPVNP.PairTerminalVertexPackedShadow
+import OAI.Computability.VPVNP.PairVertexRootEntry
+import OAI.Computability.VPVNP.PairTerminalFootprint
+
+/-! # The cursor leaf's header and auxiliary reset words at a selected vertex -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords DescriptorSpace CursorNetwork CursorBounds LocalHistory TraversalRows
+open CutSchedule ExponentTrace
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {u : PairExponents B.growthConstant}
+ {n : ℕ} {hn : 2 ≤ n} {ht : 21 ≤ 2 ^ (D.geometry n).w} {clk : 44 ≤ n ^ 10000}
+ (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (adv : Bits (n ^ D.constants.advicePower))
+ (ξ : Exterior (D.chainHeight n) (n ^ D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+
+local notation "grp" => D.executionGroup n ht clk
+local notation "pub" => terminalOperands grp
+local notation "H" => vertexHeader grp
+local notation "W" => (D.geometry n).w
+local notation "aux" => V.data adv ξ i (physicalNomination rfl μ)
+local notation "l" => reservedLanes B u n
+local notation "b" => virtualBits D.addressFactor n - reservedLanes B u n
+
+/-- The actual header words loaded at a site, and the range and contents of its
+shadow bank. Every address read by a cursor leaf avoids both terminal controls. -/
+structure VirtualPairs.CursorLeafHeader (m : Memory W) : Prop where
+ stride : (m (H + 15).val).val = B.recordLimit + 2
+ radixB : (m (H + 18).val).val = 2 ^ b
+ radixL : (m (H + 19).val).val = 2 ^ l
+ span : (m (H + 20).val).val = LiveAuxiliaryHeaders.span (D.pairLengths i) (aux).hist.length
+ shadowRoom : (pub 3).val + (m (H + 20).val).val ≤ 2 ^ W
+ shadowData : ∀ j < (m (H + 20).val).val, (m ((pub 3).val + j)).val = ((aux).initial j).val
+ shadowSafe : ∀ j < (m (H + 20).val).val, TerminalLink.workerCell H ((pub 3).val + j)
+
+/-- The ten operands reloaded from the site's private geometry carry the same
+shadow, radix and stride facts into the native leaf front. -/
+theorem VirtualPairs.CursorLeafHeader.operands
+ {m : Memory W} (h : V.CursorLeafHeader adv ξ i μ m) (role : BurstRAM.Word W)
+ {p r k : ℕ} (pc : LeafImage.Label → Fin p) (reg : LeafImage.Reg ↪ Fin r)
+ (port : LeafImage.Pub → Fin k) (ret : Fin p) (M : PrivateRAM.Machine W p r k)
+ (assigned : M.publicData ∘ port = NativeFrame.leafWords (slotDegree S) pub H role m ∘
+ LeafGeometryLoad.slot) (length : (pub 6).val = n) :
+ LeafFront.Operands (LeafImage.front pc reg port ret) M m aux
+ (NativeFrame.fromHeader (slotDegree S) pub H m) b l B.recordLimit ∧
+ M.publicData (port .size) = (n : BurstRAM.Word W) :=
+ NativeFrame.leaf_operands (slotDegree S) pub H role m pc reg port ret M assigned aux
+ b l B.recordLimit h.stride h.radixB h.radixL h.span h.shadowRoom h.shadowData length
+
+local notation "X" => V.scanState
+local notation "T" => blockCount (u.θ : ℝ) n
+variable {A : Type*} [CommRing A] {f : B.Entry → A} {ok : B.IsSolution f}
+ {z : (B.execute f ok (blockCount (u.θ : ℝ) n) le_rfl V.scanState).Choices}
+ {L : DescriptorSpace.Layout} {tab : Fin L.shape.tables}
+ {ord : ℕ} {calendar reference m : Memory (D.geometry n).w}
+local notation "Y" => (B.execute f ok T le_rfl X).finalState z
+local notation "ls" => selectedLayers B f ok T le_rfl X z
+local notation "tags" => TraversalRoles.selected B f ok T le_rfl X z
+
+attribute [local irreducible] BlockSchedule.Templates.execute CursorNetwork.cursorState
+ CursorBounds.wordBits
+
+local notation "phySpan" => LiveAuxiliaryHeaders.span
+ (PairStages.Group.Auxiliary.pairLengths grp (physicalPairIndex i)) (histLength grp)
+
+set_option maxHeartbeats 1200000 in
+-- Elaborating the selected execution identifies its physical and virtual word widths.
+/-- The preserved post-copy descriptor and shadow at calendar entry suffice for
+all selected vertex ordinals, including after prior motif counter updates. -/
+theorem VirtualPairs.cursorLeafHeader_of_calendar
+ {bits : Fin (Y).totalWidth → Bool}
+ (P : VertexPacked grp L B.recordLimit tags (Y).totalWidth)
+ (entry : TerminalProgram.VertexEntry B f ok T le_rfl X z L tab b l pub
+ calendar reference bits)
+ (later : LinkedVertexMemory grp reference ord m)
+ (descriptor : TerminalBootstrap.shadowSpan pub calendar =
+ ((phySpan : ℕ) : BurstRAM.Word W))
+ (reset : ∀ j < phySpan,
+ calendar ((pub 3).val + j) = (aux).initial j) :
+ V.CursorLeafHeader adv ξ i μ m := by
+ have vd := V.cap.capFits
+ rw [← pow_add] at vd
+ have dw : virtualBits D.addressFactor n + roundedUp 1 4 n < W :=
+ (Nat.pow_lt_pow_iff_right Nat.one_lt_two).mp vd
+ have lanes := V.lanes
+ have bFit := Nat.pow_lt_pow_right Nat.one_lt_two (show b < W by omega)
+ have lFit := Nat.pow_lt_pow_right Nat.one_lt_two (show l < W by omega)
+ have pos : 0 < (siteOrder X).length :=
+ (show 0 < Fintype.card (X).network.Site from (X).positions_pos).trans_eq
+ ((Fintype.card_congr (siteOrder X).entries).symm.trans (Fintype.card_fin _))
+ have strideLe : B.recordLimit + 2 ≤ TraversalRoles.tagWords B.recordLimit tags := by
+ apply Nat.le_mul_of_pos_right
+ simp only [TraversalRoles.selected, List.map_cons, List.sum_cons]
+ exact Nat.add_pos_left pos _
+ let len := phySpan
+ have hn₁ : 1 ≤ (grp).g.n := by change 1 ≤ n; omega
+ have cap := V.shadowCapacity (ht := ht) (hf := clk) rfl (physicalPairIndex i)
+ rw [LiveProgram.Layout.virtualSiteBits_eq (D.geometry n) (show 1 ≤ n by omega)] at cap
+ have extent : (pub 3).val + len ≤ (pub 2).val := shadow_span_room grp _ hn₁ P.fit cap
+ have small : len < 2 ^ W := (Nat.le_add_left len _).trans_lt (extent.trans_lt (pub 2).isLt)
+ have hist : (aux).hist.length = histLength grp :=
+ List.length_ofFn.trans (physicalGrammarCount (ht := ht) (hf := clk) (D := D) rfl).symm
+ have size : len = LiveAuxiliaryHeaders.span (D.pairLengths i) (aux).hist.length := by
+ rw [hist,← physicalPairLengths (ht := ht) (hf := clk) i]
+ let data := TerminalBootstrap.fromState L (ls).dropLast B.recordLimit b l (Y) tab
+ have field (j : Fin 21) (lo : 0 < j.val) (t : j.val ≠ 12) (r : j.val ≠ 14) :
+ m (H + (j.val : BurstRAM.Word (grp).g.w)).val =
+ TerminalBootstrap.values L (ls).dropLast.length data B.recordLimit pub calendar j :=
+ (P.header later _ lo (j.isLt.trans (by decide))).trans (entry.packedField P j lo t r)
+ have pitch : m (H + 15).val = ((B.recordLimit + 2 : ℕ) : BurstRAM.Word W) :=
+ field 15 (by decide) (by decide) (by decide)
+ have base : m (H + 18).val = ((2 ^ b : ℕ) : BurstRAM.Word W) :=
+ field 18 (by decide) (by decide) (by decide)
+ have lane : m (H + 19).val = ((2 ^ l : ℕ) : BurstRAM.Word W) :=
+ field 19 (by decide) (by decide) (by decide)
+ have count : m (H + 20).val = TerminalBootstrap.shadowSpan pub calendar :=
+ field 20 (by decide) (by decide) (by decide)
+ have countVal : (m (H + 20).val).val = len :=
+ (congrArg Fin.val (count.trans descriptor)).trans (Nat.mod_eq_of_lt small)
+ have wordVal {j : ℕ} {v : BurstRAM.Word W} (eqn : v = (j : BurstRAM.Word W))
+ (bound : j < 2 ^ W) :
+ v.val = j := eqn ▸ Nat.mod_eq_of_lt bound
+ have lower (j : ℕ) : L.base ≤ levelStart L j := by
+ simp only [levelStart, levelsBase, directoryBase, plannerTag, frameBase]
+ omega
+ have first : L.base ≤ endAddress L := lower L.levels
+ have bank : L.base ≤ DescriptorSpace.tableBase L (ls).dropLast.length tab := by
+ apply (lower (ls).dropLast.length).trans
+ simp only [DescriptorSpace.tableBase, arrayBase, incidenceStart]
+ omega
+ have room : (H).val + 32 ≤ 2 ^ W := P.room
+ have arena := P.arena
+ have ws := P.workspace
+ refine ⟨wordVal pitch (by omega), wordVal base bFit, wordVal lane lFit, countVal.trans size,
+ countVal ▸ (extent.trans (pub 2).isLt.le), ?_, ?_⟩
+ · intro j hj
+ rw [countVal] at hj
+ have low : (pub 3).val + j < L.base := by omega
+ have old := entry.raw _ (low.trans_le first) (.inl (low.trans_le bank))
+ exact congrArg Fin.val (((P.shadow later _ hn₁ cap hj).trans old).trans (reset j hj))
+ · intro j hj
+ rw [countVal] at hj
+ apply TerminalFootprint.below H
+ · change (H).val + 31 < 2 ^ W
+ omega
+ · omega
+
+variable {initial : Memory (D.geometry n).w}
+ {N : PairStages.Group.Indexed (D.executionGroup n ht clk) Stage.nominations initial
+ (PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))}
+
+set_option maxHeartbeats 1200000 in
+-- Elaborating the selected execution identifies its physical and virtual word widths.
+/-- Instantiate the cursor header from the real sparse-copy branch and the
+low-address frame of the startup and online calendar. -/
+theorem VirtualPairs.cursorLeafHeader
+ (prepared : PreparedBranch grp initial (physicalPairIndex i)
+ ((physicalPairLengths (ht := ht) (hf := clk) i).symm ▸ PairedChain.headers adv ξ i) N μ)
+ {bits : Fin (Y).totalWidth → Bool}
+ (P : VertexPacked grp L B.recordLimit tags (Y).totalWidth)
+ (entry : TerminalProgram.VertexEntry B f ok T le_rfl X z L tab b l pub
+ calendar reference bits)
+ (later : LinkedVertexMemory grp reference ord m)
+ (low : ∀ x < (pub 2).val, x ≠ (PairTag.address pub).val →
+ calendar x = prepared.copy.memory () x) :
+ V.CursorLeafHeader adv ξ i μ m := by
+ apply V.cursorLeafHeader_of_calendar adv ξ i μ P entry later
+ · exact prepared.shadowSpan_of_cell
+ (low _ (histogramTarget_lt_workspace grp P.fit) (histogramCell_lt_tag grp P.fit).ne)
+ · intro j hj
+ have hn₁ : 1 ≤ (grp).g.n := by change 1 ≤ n; omega
+ have cap := V.shadowCapacity (ht := ht) (hf := clk) rfl (physicalPairIndex i)
+ rw [LiveProgram.Layout.virtualSiteBits_eq (D.geometry n) (show 1 ≤ n by omega)] at cap
+ have range := shadow_span_room grp (physicalPairIndex i) hn₁ P.fit cap
+ have before := pairTag_lt_shadow grp P.fit
+ exact (low _ (by omega) (by omega)).trans (V.shadow_initial rfl adv ξ i μ prepared j)
+
+end FixedProgramDiagonal.Program
+
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds BurstRAM LiveProgram CompressedPair CompressorRecords
+set_option quotPrecheck false
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {u : PairExponents B.growthConstant} {D : FixedProgramDiagonal.Program} {C n : ℕ} {hn : 2 ≤ n}
+ {V : D.VirtualPairs B u hn C} {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f}
+ {c : Constants} {labels : c.motifLabels = Fintype.card B.Entry} {base clk rate : ℕ}
+ {pub : Fin 11 → Word (wordBits D.addressFactor n)} {m : Memory (wordBits D.addressFactor n)}
+
+local notation "boot" => paperBootstrap B u
+local notation "A" => BlockProgram.script B
+local notation "entry" => after m (eventLog (cursorStartupLogs boot pub D.addressFactor n base m
+ (A).initial.length (A).block.length (A).size))
+
+attribute [local irreducible] BlockProgram.script BlockProgram.layout CursorNetwork.cursorState
+ CompressedPair.stages CompressedPair.regs PairSimulation.TerminalProgram.workers
+
+/-- At the selected online handoff, the startup and calendar preserve each low
+word except the pair tag written by the stage transfer. -/
+theorem VirtualPairs.PaperDescriptor.post_below
+ (Y : V.PaperDescriptor f hf c labels base clk rate pub m)
+ (runs : TransferredStartup.Runs (bootstrapRows boot (A).initial.length (A).block.length)
+ (A).size (startupLayout boot (A).initial.length (A).block.length D.addressFactor n base)
+ D.addressFactor n (S.degreeExponent 0) S.laneBits S.steps pub (PairTag.address pub) m)
+ (workspace : (pub 2).val = base)
+ (z : (B.execute f hf (blockCount (u.θ : ℝ) n) le_rfl V.scanState).Choices)
+ (x : ℕ) (below : x < (pub 2).val) (apart : x ≠ (PairTag.address pub).val) :
+ onlinePost (Y.paths z) x = m x := by
+ let initial := Y.cursor.interval
+ let whole := (initial.withTrace Y.result.trace).part z
+ have stable := initial.withTrace_stable Y.result.trace Y.result.frame whole.run
+ have keep : whole.memory x = entry x := by
+ simpa only [BranchSegments.Segment.memory, List.take_length] using
+ stable.take_eq whole.logs.length x (by omega)
+ rw [Y.post z, writeMemory, ite_eq_right apart, ← initial.withTrace_memory Y.result.trace z]
+ exact keep.trans
+ (cursorStartup_after_below boot pub D.addressFactor n base m runs x (workspace ▸ below) apart)
+
+end FixedProgramDiagonal.Program
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM LiveProgram LocalCount
+open PairStages PairStages.Group PairStages.Group.CompressedPaths CompressedPair
+open PairStages.Group.Auxiliary
+open PairSimulation PairSimulation.LocalHistory CompressorRecords
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {D : FixedProgramDiagonal.Program} {n : ℕ}
+ {ht : 21 ≤ 2 ^ (D.geometry n).w} {hc : 44 ≤ n ^ 10000}
+ {K : Type} [Field K] {S : BlockSchedule K} {B : S.Templates} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn D.constants.circuitExponent)}
+ {u : PairExponents B.growthConstant} (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (data : D.ScalarData B hn M)
+
+local notation "G" => D.executionGroup n ht hc
+variable (W : Conditions (D.executionGroup n ht hc) (2 ^ (D.geometry n).d) (D.geometry n).H)
+ (P : PairStageConditions (D.executionGroup n ht hc) (2 ^ (D.geometry n).d) (D.geometry n).H)
+ (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (cut : 1 + B.denseCount n D.constants.circuitExponent * D.counterWidth n ≤
+ n ^ D.constants.deltaPower)
+ (I : VirtualPairs.PhysicalInput data W P rfl hg cut)
+
+local notation "ext" => VirtualPairs.exterior data W P rfl hg cut I
+local notation "idx" => VirtualPairs.modelIndex data W P rfl hg cut I
+local notation "src" => I.branch.copy.memory ()
+local notation "ws" => (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+local notation "ports" => publicWords G
+local notation "f" => B.compressorValues hn M
+local notation "ok" => B.compressorValues_solution hn M
+local notation "T" => blockCount (u.θ : ℝ) n
+local notation "X" => V.scanState
+local notation "E" => B.execute f ok T le_rfl X
+local notation "L" => BlockProgram.layout B ws (initialPositions D.addressFactor n) T
+local notation "boot" => paperBootstrap B u
+local notation "A" => BlockProgram.script B
+local notation "l" => reservedLanes B u n
+local notation "b" => virtualBits D.addressFactor n - reservedLanes B u n
+
+set_option maxHeartbeats 1200000 in
+-- The selected native descriptor and physical input share several dependent indices.
+/-- The native leaf at a selected vertex reads the nominated input's reset words. -/
+theorem VirtualPairs.cursorLeafHeader_of_paperDescriptor
+ {rate : ℕ} (Y : V.PaperDescriptor f ok D.constants hg ws (fuel G) rate ports src)
+ (setup : TransferredStartup.Runs (bootstrapRows boot (A).initial.length (A).block.length)
+ (A).size
+ (startupLayout boot (A).initial.length (A).block.length D.addressFactor n ws)
+ D.addressFactor n (S.degreeExponent 0) S.laneBits S.steps ports (PairTag.address ports) src)
+ (z : (E).Choices) {tab : Fin (L).shape.tables} {ord : ℕ} {reference m : Memory (G).w}
+ {bits : Fin ((E).finalState z).totalWidth → Bool}
+ (packed : VertexPacked G L B.recordLimit (TraversalRoles.selected B f ok T le_rfl X z)
+ ((E).finalState z).totalWidth)
+ (entry : TerminalProgram.VertexEntry B f ok T le_rfl X z L tab b l ports
+ (onlinePost (Y.paths z)) reference bits)
+ (later : LinkedVertexMemory G reference ord m) :
+ V.CursorLeafHeader data.advice ext idx I.μ m := by
+ have workspace : (ports 2).val = ws := Nat.mod_eq_of_lt packed.fit
+ apply V.cursorLeafHeader_of_calendar data.advice ext idx I.μ packed entry later
+ · exact I.branch.shadowSpan_of_cell (Y.post_below setup workspace z _
+ (histogramTarget_lt_workspace G packed.fit) (histogramCell_lt_tag G packed.fit).ne)
+ · intro j hj
+ have hn₁ : 1 ≤ (G).g.n := by change 1 ≤ n; omega
+ have cap := V.shadowCapacity (ht := ht) (hf := hc) rfl (physicalPairIndex idx)
+ rw [LiveProgram.Layout.virtualSiteBits_eq (D.geometry n) (show 1 ≤ n by omega)] at cap
+ have extent := shadow_span_room G (physicalPairIndex idx) hn₁ packed.fit cap
+ have before := pairTag_lt_shadow G packed.fit
+ exact (Y.post_below setup workspace z ((terminalOperands G 3).val + j)
+ ((Nat.add_lt_add_left hj _).trans_le extent)
+ (before.trans_le (Nat.le_add_right _ _)).ne').trans
+ (V.input_shadow data W P rfl hg cut I j)
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafNumbered.lean b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafNumbered.lean
new file mode 100644
index 0000000000..b2d8e58659
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafNumbered.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PairSelectedCursorLeaf
+import OAI.Computability.VPVNP.PairVirtualCursorLeafBounds
+import OAI.Computability.VPVNP.PairVirtualCursorLeafTransfer
+import OAI.Computability.VPVNP.PairVertexOrdinalRoleCost
+
+/-! # Cursor leaf checks in the numbered lanes of the live processor -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.SelectedCursorLeaf
+
+open BurstRAM PrivateRAM DFS CursorNetwork CursorRouting LeafStartup
+open TreeDecode LocalHistory LeafHandler NodeArguments NetworkKernel CompressorRecords NativeFrame
+ VertexImage
+open CompressorRecords.SourceTransport Compression TraversalRows
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+open scoped Fin.CommRing
+
+set_option maxRecDepth 10000
+
+/-- The two leaf-row obligations consumed by the selected role assembly,
+using the common private frame and the ordinal worker's cost bound. -/
+def Rows {w n p r g ex lanes : ℕ} {K : Type*} [CommRing K] {Label : Type} [Fintype Label]
+ {κ : Label → K} {geometry rootFields leaf shrink refresh : Segment}
+ (A : Placement (segments geometry rootFields leaf shrink refresh) p r) (M : Machine w p r 11)
+ (handlers : NodeDispatch.Role → HookParser w n) (m : Memory w) (offset : Word w)
+ (R : LeafArena.Regions)
+ (data : Fin 10 → Word w) (vals : LeafSourceLoad.Static 34 → Word w) (cap base : ℕ)
+ (format : Packet → Prop) (desc : ℕ → List ℕ) (order : Fin g ≃ Label) (allow : ℕ → Prop)
+ (nodeCap limit power scan : ℕ) (X : State ex lanes) (sites : SiteParsers κ X.network) : Prop :=
+ let leaves := sitePointers cap base (siteOrder X)
+ let input := fun u z => Packet.mk (leaves u).1 (packed X u z)
+ let hist := privateHistogram order R.histBase
+ let valid := Budgeted R.arguments format (VertexFrameData R data offset vals) desc hist nodeCap
+ limit
+ Subtrees (dispatcher handlers m offset) valid sites (fun u => leafTree (leaves u)) input ∧
+ Emits valid hist (JobGuard A M m allow (ordinalJobCost n power scan)) sites input
+ (leafJobs sites leaves)
+
+variable {k : Type*} [_root_.Field k] {S : BlockSchedule k}
+ {geometry rootFields shrink refresh : Segment} {p r w : ℕ}
+ (V : Placement (segments geometry rootFields LeafRole.segment shrink refresh) p r)
+ (M : Machine w p r 11) {L : PrimedInputRAM.Lengths} {n a H s : ℕ}
+ {Q : PrimedInputRAM.Layout L n a H w}
+ (aux : PrimedCounter.Data Q s) {d b l e : ℕ} [NeZero d] (split : d = b + l)
+ (dim : 1 < d) (cap : ProcessorBudget n d e w)
+ {K : Type*} [CommRing K] {Label : Type} [Fintype Label] (κ : Label → K)
+ (clock : NominationClock aux cap.tags cap.capFits (n ^ 39)) (m : Memory w)
+ (header offset : Word w)
+ (arity rowCap rowBase : ℕ)
+
+local notation "region" => fromHeader arity M.publicData header m
+local notation "words" => leafWords arity M.publicData header offset m
+local notation "fields" => LeafRole.addressFields words
+local notation "numbering" => Equiv.trans (finCongr split) (cursorCoordinateLabels b l)
+local notation "X" => scanInput numbering dim S e w
+local notation "leaves" => sitePointers rowCap rowBase (siteOrder X)
+local notation "sites" => nominationSites aux cap.tags cap.capFits numbering dim
+ (Nat.add_sub_of_le (And.left (BlockSchedule.degree_bounds S))) κ (n ^ 39) clock
+
+/-- Splitting the processor's coordinate numbering into its base and lane
+blocks preserves the actual occurrence readers and all physical leaf jobs. -/
+theorem numberedRows (link : Contains V M) (fit : (region).stackBase + Fintype.card ScalarPort * n
+ ^ 40 < 2 ^ w)
+ (resources : LeafVisit.CursorLeafBounds aux cap) (hn : 2048 ≤ n)
+ (stride : (m (header + 15).val).val = rowCap + 2) (rb : (m (header + 18).val).val = 2 ^ b)
+ (rl : (m (header + 19).val).val = 2 ^ l) (span : (m (header + 20).val).val =
+ LiveAuxiliaryHeaders.span L aux.hist.length)
+ (shadowFit : (M.publicData 3).val + (m (header + 20).val).val ≤ 2 ^ w)
+ (headers : ∀ i < (m (header + 20).val).val, (m ((M.publicData 3).val + i)).val =
+ (aux.initial i).val)
+ (size : (M.publicData 6).val = n) (baseAt : rowBase = (fields .base).val)
+ (handlers : NodeDispatch.Role → HookParser w n)
+ (leaf : handlers .leaf = LeafRole.parser (b := d) (l := 0) words aux cap region fit m (n ^ 39))
+ (allow : ℕ → Prop) (shadow : ∀ site : Word w, site < fields .span → allow
+ (fields .shadow + site).val)
+ (tag : ∀ u, m (offset + ((leaves u).1 : Word w)).val = 0)
+ (tagRead : ∀ u, allow (offset + ((leaves u).1 : Word w)).val)
+ (format : Packet → Prop) (desc : ℕ → List ℕ)
+ (typed : ∀ q, format q → q.node < (region).nodes ∧ q.node < 2 ^ w)
+ {g : ℕ} (order : Fin g ≃ Label) (hcount : g ≤ (region).histWords)
+ (nodeCap limit power scan : ℕ) (scanTwo : 2 ≤ scan) (shape : ∀ u, desc (leaves u).1 = []) :
+ Rows V M handlers m offset region words (LeafVisit.cacheWords aux d e) rowCap rowBase format
+ desc order
+ allow nodeCap limit power scan X sites := by
+ subst d rowBase
+ have low : n ≤ (region).arguments.start := size.ge
+ have before : n < (region).stackBase := by
+ unfold LeafArena.Regions.stackBase LeafArena.Regions.cacheBase LeafArena.Regions.histBase
+ Arena.base
+ omega
+ have out := checksBudgeted V M aux dim (Nat.add_sub_of_le S.degree_bounds.1) cap κ clock m
+ header offset arity
+ rowCap link fit hn resources.width stride rb rl span shadowFit headers size resources.time
+ resources.room
+ resources.boot handlers leaf allow shadow tag tagRead format
+ (VertexFrameData region words offset (LeafVisit.cacheWords aux (b + l) e)) desc typed
+ (fun _ h => h.cached)
+ (fun _ h => h.record) (fun _ h => h.resident) (fun _ _ h => h.of_below_stack before) order
+ hcount nodeCap limit shape
+ exact ⟨out.1, emits_withCost out.2 (fun _ h => leaf_ordinal_cost (by omega) scanTwo h)⟩
+
+end PairSimulation.SelectedCursorLeaf
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafTransfer.lean b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafTransfer.lean
new file mode 100644
index 0000000000..616a673bfe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualCursorLeafTransfer.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+import OAI.Computability.VPVNP.PairSimulationLeafArguments
+
+/-! # Transferring physical cursor leaves to the virtual pair
+
+The lane labels of the virtual scan include a cast from its address dimension
+to the sum of its base and lane dimensions. Identifying these dimensions
+transports the state together with the nomination parser on its network.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.LocalHistory
+
+open Compression BurstRAM CursorNetwork CursorRouting
+open private scanInput from OAI.Computability.VPVNP.PairSimulationScanTrace
+
+variable {d b l e w n a H s : ℕ} [NeZero d] [NeZero (b+l)]
+ {L : PrimedInputRAM.Lengths} {Q : PrimedInputRAM.Layout L n a H w}
+ (D : PrimedCounter.Data Q s) {k : Type*} [Field k] (S : BlockSchedule k)
+ {R : Type*} [CommRing R] {Label : Type} [Fintype Label] (f : Label → R)
+ (t : ℕ)
+
+/-- The nomination clock holds at the split physical dimension. -/
+theorem cursorLaneClock (split : d = b+l)
+ (virtual : ProcessorBudget n d e w) (physical : ProcessorBudget n (b+l) e w)
+ (vclock : NominationClock D virtual.tags virtual.capFits t) :
+ NominationClock D physical.tags physical.capFits t := by
+ subst d
+ exact vclock
+
+/-- Transfer a dependent property of the cursor state and its site parsers
+from the physical coordinates to the lane labels of the scan. -/
+theorem cursorLaneTransfer (split : d = b+l) (dim : 1 < d) (sum : 1 < b+l)
+ (virtual : ProcessorBudget n d e w) (physical : ProcessorBudget n (b+l) e w)
+ (vclock : NominationClock D virtual.tags virtual.capFits t)
+ (pclock : NominationClock D physical.tags physical.capFits t)
+ (G : (X : State (S.degreeExponent 0) l) → SiteParsers f X.network → Prop)
+ (tested : G (LeafArguments.state sum (Nat.add_sub_of_le S.degree_bounds.1) (2^e) w)
+ (nominationSites D physical.tags physical.capFits (cursorCoordinateLabels b l)
+ sum (Nat.add_sub_of_le S.degree_bounds.1) f t pclock)) :
+ G (scanInput ((finCongr split).trans (cursorCoordinateLabels b l)) dim S e w)
+ (nominationSites D virtual.tags virtual.capFits ((finCongr split).trans (cursorCoordinateLabels b l))
+ dim (Nat.add_sub_of_le S.degree_bounds.1) f t vclock) := by
+ subst d
+ exact tested
+
+end PairSimulation.LocalHistory
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LabelEvaluator BurstRAM CutSchedule ExponentTrace
+open PairSimulation PairSimulation.LocalHistory NetworkKernel LiveProgram
+
+variable {K : Type*} [Field K] {S : BlockSchedule K} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ {data : D.ScalarData B hn M} {u : PairExponents B.growthConstant} {V : D.VirtualPairs B u hn C}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)} {i : D.groupIndices n} {μ : D.pairNom n C}
+ (A : CanonicalScan data V ξ i μ)
+
+local notation "l" => reservedLanes B u n
+local notation "b" => virtualBits D.addressFactor n - reservedLanes B u n
+local notation "κ" => B.compressorValues hn M
+local notation "e" => roundedUp 1 4 n
+local notation "w" => CursorBounds.wordBits D.addressFactor n
+local notation "sourceData" => V.data data.advice ξ i μ
+
+include A in
+/-- The canonical scan supplies the clock for the physical cursor parser. -/
+theorem CanonicalScan.physicalCursorClock [NeZero (b+l)] (budget : ProcessorBudget n (b+l) e w) :
+ NominationClock sourceData budget.tags budget.capFits (n^39) :=
+ cursorLaneClock sourceData (n^39) (Nat.sub_add_cancel V.lanes).symm V.cap budget A.clock
+
+/-- A property established on the physical leaves of the selected cursor
+holds for the virtual pair's scan state and its canonical leaf readers. -/
+theorem CanonicalScan.physicalCursorTransfer [NeZero (b+l)] (sum : 1 < b+l)
+ (budget : ProcessorBudget n (b+l) e w)
+ (clock : NominationClock sourceData budget.tags budget.capFits (n^39))
+ (G : (X : State (S.degreeExponent 0) l) → SiteParsers κ X.network → Prop)
+ (tested : G (LeafArguments.state sum (Nat.add_sub_of_le S.degree_bounds.1) (2^e) w)
+ (nominationSites sourceData budget.tags budget.capFits (cursorCoordinateLabels b l) sum
+ (Nat.add_sub_of_le S.degree_bounds.1) κ (n^39) clock)) :
+ G V.scanState A.leafSites :=
+ cursorLaneTransfer sourceData S κ (n^39) (Nat.sub_add_cancel V.lanes).symm V.dimension sum
+ V.cap budget A.clock clock G tested
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualDescriptorHistory.lean b/lean/OAI/Computability/VPVNP/PairVirtualDescriptorHistory.lean
new file mode 100644
index 0000000000..aff0980b4d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualDescriptorHistory.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.LiveVirtualPairPaperDescriptor
+import OAI.Computability.VPVNP.PairTerminalCalendarBoundary
+import OAI.Computability.VPVNP.PairShrinkSiteHistory
+import OAI.Computability.VPVNP.LiveCompressedPairStartupInputs
+import OAI.Computability.VPVNP.FixedProgramOperandFits
+
+/-! # Recovering the selected parser records from the actual online stage -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorBounds CursorNetwork BurstRAM LiveProgram CompressedPair
+open PairStages.Group.CompressedPaths CompressorRecords ScheduledTrace DescriptorSpace
+open PairSimulation LocalHistory TraversalRows TraversalRoles
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates} {u : PairExponents B.growthConstant}
+ {D : FixedProgramDiagonal.Program} {C n : ℕ} {hn : 2 ≤ n} {V : D.VirtualPairs B u hn C}
+ {A : Type*} [CommRing A] {f : B.Entry → A} {ok : B.IsSolution f}
+ {c : Constants} {labels : c.motifLabels = Fintype.card B.Entry} {base clk rate : ℕ}
+ {pub : Fin 11 → Word (wordBits D.addressFactor n)} {m : Memory (wordBits D.addressFactor n)}
+ (desc : V.PaperDescriptor f ok c labels base clk rate pub m)
+ (z : (B.execute f ok (blockCount (u.θ : ℝ) n) le_rfl V.scanState).Choices)
+
+local notation "T₀" => blockCount (u.θ : ℝ) n
+local notation "X₀" => VirtualPairs.scanState V
+local notation "w₀" => wordBits D.addressFactor n
+local notation "pos₀" => State.positions (X₀)
+local notation "L₀" => BlockProgram.layout B (Fin.val (pub 2)) (pos₀) (T₀)
+local notation "data₀" => CompiledResident.payload (w := w₀) B f ok (pub 2) (pos₀) (T₀) n
+local notation "passes₀" => executeLevels B f ok (T₀) le_rfl (X₀) z
+
+/-- The detailed descriptor result contains the payload of every selected
+pass, with exactly the workspace word used by the physical pair program. -/
+theorem VirtualPairs.PaperDescriptor.past_online (workspace : (pub 2).val = base) :
+ SelectedPayloadHistory.Past B f ok (L₀) (data₀) (passes₀) (desc.result.trace.cut.part z).memory := by
+ have positions : (X₀).positions = initialPositions D.addressFactor n := by
+ rw [V.scanState_pairInput]
+ exact pairInput_positions S _ _
+ have word : (base : Word w₀) = pub 2 := workspace ▸ Fin.cast_val_eq_self _
+ have h := DetailedResident.payloads (desc.result.final z).stored
+ rw [positions,workspace,←word]
+ exact h
+
+/-- The sole write at the online-to-terminal handoff changes the scheduler
+tag. Every recorded graph, term and argument field is above this address. -/
+theorem VirtualPairs.PaperDescriptor.past_calendar (workspace : (pub 2).val = base)
+ (tag : (PairTag.address pub).val < (pub 2).val+6) :
+ SelectedPayloadHistory.Past B f ok (L₀) (data₀) (passes₀) (onlinePost (desc.paths z)) := by
+ have handoff := TerminalPrefix.Linked.handoff_of_transfer pub (desc.post z) tag
+ apply (desc.past_online z workspace).transfer
+ intro x lo _
+ have start : (pub 2).val+6 ≤ levelsBase (L₀) := by
+ unfold levelsBase directoryBase plannerTag frameBase
+ change (pub 2).val+6 ≤ (pub 2).val+9+_+1+_
+ omega
+ exact (handoff x (start.trans lo)).symm
+
+/-- The graph part of that same postcondition supplies the terminal
+bootstrap's actual online boundary. -/
+theorem VirtualPairs.PaperDescriptor.current_at_online (workspace : (pub 2).val = base) :
+ let b := virtualBits D.addressFactor n - reservedLanes B u n
+ let lanes := reservedLanes B u n
+ let frame := cursorFrame (L₀) (S.degreeExponent 0) b lanes (initialWidth D.addressFactor n)
+ let current := CurrentResident.resident B f ok ⟨leafLayer (siteOrder (X₀)),.cursor⟩ (L₀) (endAddress (L₀)) n frame
+ Boundary current pub (levelWords (L₀) : Word w₀) (directoryRows (L₀)) (directoryRows (L₀))
+ (passes₀) ((B.execute f ok T₀ le_rfl (X₀)).finalState z) (desc.result.trace.cut.part z).memory := by
+ have positions : (X₀).positions = initialPositions D.addressFactor n := by
+ rw [V.scanState_pairInput]; exact pairInput_positions S _ _
+ intro b lanes frame current
+ change Boundary (CurrentResident.resident B f ok _ (L₀) _ n _) _ _ _ _ _ _ _
+ dsimp only [frame]
+ rw [positions,workspace]
+ exact DetailedResident.currentBoundary (desc.result.final z)
+
+section Site
+
+open PairStages.Group.Auxiliary
+
+variable {ht : 21 ≤ 2^(D.geometry n).w} {dispatch : 44 ≤ n^10000}
+local notation "G₀" => D.executionGroup n ht dispatch
+local notation "Y₀" => StateExecution.finalState (B.execute f ok (T₀) le_rfl (X₀)) z
+
+/-- Every later site can still retrieve those selected shrink and refresh
+rows after the shared-bit scan and preceding histogram flushes. -/
+theorem VirtualPairs.PaperDescriptor.past_site (workspace : (pub 2).val = base)
+ (tag : (PairTag.address pub).val < (pub 2).val+6)
+ (actual : pub = terminalOperands G₀) {tab : Fin (L₀).shape.tables} {baseBits laneBits j : ℕ}
+ {bits : Fin (Y₀).totalWidth → Bool} {reference site : Memory w₀}
+ (entry : TerminalProgram.VertexEntry B f ok T₀ le_rfl (X₀) z (L₀) tab baseBits laneBits pub
+ (onlinePost (desc.paths z)) reference bits)
+ (fit : VertexPacked G₀ (L₀) B.recordLimit (selected B f ok T₀ le_rfl (X₀) z) (Y₀).totalWidth)
+ (later : LinkedVertexMemory G₀ reference j site) :
+ SelectedPayloadHistory.Past B f ok (L₀) (data₀) (passes₀) site := by
+ subst pub
+ exact entry.packedSitePayload fit later (desc.past_calendar z workspace tag)
+
+end Site
+
+open Filter
+
+/-- The actual group workspace and online tag bounds hold before choosing
+any program parameters or selected path at the given length. -/
+theorem eventually_descriptor_history (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (C : ℕ) (hnum : D.numerator = (liveRatio u).num)
+ (hden : D.denominator = (liveRatio u).den) (labels : D.constants.motifLabels = Fintype.card B.Entry) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C)
+ (ht : 21 ≤ 2^(D.geometry n).w) (hc : 44 ≤ n^10000) (A : Type*) [CommRing A]
+ (f : B.Entry → A) (ok : B.IsSolution f) (rate : ℕ) (m : Memory (D.geometry n).w),
+ let G := D.executionGroup n ht hc
+ let pub := publicWords G
+ let base := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ let T := blockCount (u.θ : ℝ) n
+ let X := V.scanState
+ let L := BlockProgram.layout B (pub 2).val X.positions T
+ let data := CompiledResident.payload B f ok (pub 2) X.positions T n
+ ∀ desc : V.PaperDescriptor f ok D.constants labels base (fuel G) rate pub m,
+ ∀ z : (B.execute f ok T le_rfl X).Choices,
+ SelectedPayloadHistory.Past B f ok L data (executeLevels B f ok T le_rfl X z) (onlinePost (desc.paths z)) := by
+ filter_upwards [eventually_startup_inputs D.constants D.address_pos (liveCapacity_polynomial u)] with n valid
+ intro hn V ht hc A _ f ok rate m G pub base T X L data desc z
+ have geometry := paperGeometry_eq D B u hnum hden n
+ obtain ⟨space,_,_,tag⟩ := valid G.lit
+ rw [← geometry] at space tag
+ change (pub 2).val = base at space
+ change (PairTag.address pub).val < (pub 2).val at tag
+ exact desc.past_calendar z space (tag.trans_le (Nat.le_add_right _ _))
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualEventualChecks.lean b/lean/OAI/Computability/VPVNP/PairVirtualEventualChecks.lean
new file mode 100644
index 0000000000..eba085d6fc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualEventualChecks.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PairVirtualActiveChecks
+import OAI.Computability.VPVNP.PairVirtualCursorLeafExact
+import OAI.Computability.VPVNP.PairVirtualRefreshChecks
+import OAI.Computability.VPVNP.PairVirtualShrinkRows
+
+/-! # All selected virtual-pair vertex calls on the installed program -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords DescriptorSpace CursorNetwork CursorBounds Filter LocalHistory
+open TraversalRows TraversalRoles VertexImage CutSchedule ExponentTrace TreeDecode NetworkKernel
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant) {labels : ℕ}
+ (order : B.Entry ≃ Fin labels)
+
+attribute [local irreducible] VertexImage.placement VertexImage.template BlockProgram.layout
+ BlockSchedule.Templates.execute CursorNetwork.cursorState CursorBounds.wordBits
+ selectedDesc ordinalJobCost
+
+set_option maxHeartbeats 1600000 in
+-- The physical site, model and lane numbering identify the three dependent role domains.
+/-- The length threshold precedes the auxiliary nomination, coefficient
+realization, selected branch, shared wire values and current site. Every
+worker reads the true retained parser records and executes the same table. -/
+theorem eventually_activeChecks (hlabels : D.constants.motifLabels = Fintype.card B.Entry)
+ (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ [NeZero (virtualBits D.addressFactor n)]
+ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clk : 44 ≤ n ^ 10000)
+ {p : Nat.Primes} {model : LabelEvaluator.Model p (B.compressorDegree n)
+ (B.compressorEquations hn D.constants.circuitExponent)}
+ (scalar : D.ScalarData B hn model)
+ (ξ : Exterior (D.chainHeight n) (n ^ D.constants.deltaPower)) (i : D.groupIndices n),
+ let G := D.executionGroup n ht clk
+ let ops := terminalOperands G
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ let l := reservedLanes B u n
+ let b := virtualBits D.addressFactor n - l
+ let L := BlockProgram.layout B (ops 2).val X.positions T
+ let f := B.compressorValues hn model
+ let ok := B.compressorValues_solution hn model
+ ∀ (μ : PairStages.Group.Nominations.Nom G)
+ (A : CanonicalScan scalar V ξ i (physicalNomination rfl μ))
+ (z : (V.selection (M := model)).Choices)
+ {initial : Memory G.w} {N : PairStages.Group.Indexed G Stage.nominations initial
+ (PairStages.Group.Nominations.Nom G)}
+ (prepared : PreparedBranch G initial (physicalPairIndex i)
+ ((physicalPairLengths (ht := ht) (hf := clk) i).symm ▸
+ PairedChain.headers scalar.advice ξ i) N μ)
+ {calendar reference m : Memory G.w} {tab : Fin L.shape.tables}
+ {bits : Fin ((V.selection (M := model)).finalState z).totalWidth → Bool} {ord : ℕ},
+ TerminalProgram.VertexEntry B f ok T le_rfl X z L tab b l ops calendar reference bits →
+ SelectedPayloadHistory.Past B f ok L
+ (CompiledResident.payload B f ok (ops 2) X.positions T n)
+ (executeLevels B f ok T le_rfl X z) calendar →
+ LinkedVertexMemory G reference ord m →
+ (∀ x < (ops 2).val, x ≠ (PairTag.address ops).val →
+ calendar x = prepared.copy.memory () x) →
+ V.SelectedRowsAt scalar.advice ξ i μ order f ok A.leafSites z m 1
+ (RatedRoles.scan B order) := by
+ filter_upwards [eventually_selectedRootBudget D B u haddr hnum hden D.constants.circuitExponent,
+ eventually_virtualCursorLeafExactCalls D B u order hlabels haddr hnum hden,
+ eventually_virtualRefreshChecks D B u order haddr hnum hden,
+ eventually_virtualShrinkChecks D B u order hlabels haddr hnum hden]
+ with n roots cursors refreshes shrinks
+ intro hn V inst ht clk p model scalar ξ i G ops X T l b L f ok μ A z initial N prepared
+ calendar reference m tab bits ord entry history later low
+ have all := roots hn V ht clk model.algebra f ok
+ let pack := (all.2.2.2 z).1
+ have names : Fintype.card B.Entry = labels :=
+ (Fintype.card_congr order).trans (Fintype.card_fin labels)
+ have count := (physical_counter_end G pack.fit).2.2.trans (hlabels.trans names)
+ obtain ⟨fit, exactLeaf, leaves⟩ := cursors hn V ht clk scalar ξ i μ A z m 1
+ (RatedRoles.scan B order) (RatedRoles.role_le B order .leaf) prepared entry later low
+ exact V.activeChecks scalar.advice ξ i μ order f ok A.leafSites z b l ord m pack entry later
+ all.2.2.1 count (shrinks hn V ht clk model.algebra f ok z entry history later)
+ (refreshes hn V ht clk model.algebra f ok z entry history later)
+ ⟨V.cursorLeafParser scalar ξ i μ m fit, exactLeaf, leaves⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualOrdinalCalls.lean b/lean/OAI/Computability/VPVNP/PairVirtualOrdinalCalls.lean
new file mode 100644
index 0000000000..d2fcc0f0a5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualOrdinalCalls.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.PairVirtualPreparedRoot
+import OAI.Computability.VPVNP.PairVertexRatedClock
+import OAI.Computability.VPVNP.PairVertexRatedRoot
+import OAI.Computability.VPVNP.PairVertexSelectedDesc
+import OAI.Computability.VPVNP.PairVertexSelectedRoles
+
+/-! # Measured ordinal calls of the installed pair program -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords DescriptorSpace CursorNetwork CursorBounds Filter LocalHistory TraversalRows
+open VertexImage CutSchedule ExponentTrace TreeDecode TraversalRoles
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {u : PairExponents B.growthConstant}
+ {n : ℕ} {hn : 2 ≤ n} {ht : 21 ≤ 2^(D.geometry n).w} {clk : 44 ≤ n^10000}
+ (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (adv : Bits (n^D.constants.advicePower)) (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+ {labels : ℕ} (order : B.Entry ≃ Fin labels)
+
+local notation "G₀" => D.executionGroup n ht clk
+local notation "pub" => terminalOperands G₀
+local notation "hdr" => vertexHeader G₀
+local notation "degree" => slotDegree S
+local notation "T₀" => blockCount (u.θ : ℝ) n
+local notation "X₀" => V.scanState
+local notation "S₀" => TerminalProgram.nativeSegments B D.constants D.numerator D.denominator order
+local notation "V₀" => VertexImage.placement S₀
+local notation "M₀" => PrivateRAM.Template.instantiate (VertexImage.template S₀) (Geometry.w (D.geometry n)) pub
+local notation "aux" => V.data adv ξ i (physicalNomination rfl μ)
+local notation "W₀" => Geometry.w (D.geometry n)
+local notation "vals₀" => LeafVisit.cacheWords aux (virtualBits D.addressFactor n) (roundedUp 1 4 n)
+
+attribute [local irreducible] BlockSchedule.Templates.execute BlockProgram.layout VertexImage.template
+ VertexImage.placement CursorNetwork.cursorState CursorBounds.wordBits NativeOperands.capacity NativeOperands.saved
+
+/-- The local role contracts on one selected physical memory. Every
+packet type and address comes from this same execution. -/
+def VirtualPairs.SelectedRowsAt {A : Type*} [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f)
+ (P : SiteParsers f (X₀).network) (z : (B.execute f ok T₀ le_rfl X₀).Choices)
+ (m : Memory W₀) (power scan : ℕ) : Prop :=
+ let rowBase := endAddress (BlockProgram.layout B (pub 2).val (X₀).positions T₀)
+ let R := NativeFrame.fromHeader degree pub hdr m
+ let role := m (hdr+14).val
+ let data := NativeFrame.leafWords degree pub hdr role m
+ let format := SelectedPacketFormat B f ok T₀ le_rfl X₀ z rowBase
+ let desc := selectedDesc B f ok T₀ le_rfl X₀ z rowBase
+ let valid : List NodeArguments.Packet → DFS.Scratch W₀ (pub 6).val → Prop := Budgeted R.arguments format (VertexFrameData R data role vals₀) desc
+ (privateHistogram order.symm R.histBase) (n^9000) ((pub 6).val*n^9000)
+ ∃ domain handlers, SelectedChecks B f ok T₀ le_rfl X₀ z rowBase V₀ M₀ m
+ ((NativeFrame.frameBase R : ℕ) : BurstRAM.Word W₀) role R.histBase order.symm P valid domain handlers
+ (ordinalJobCost n power scan)
+
+/-- The calendar boundary, published traversal rows and complete shared
+bit scan feed every subsequent active ordinal on the linked memory. -/
+def VirtualPairs.RatedAtBoundary {A : Type*} [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f)
+ (P : SiteParsers f (X₀).network) (z : (B.execute f ok T₀ le_rfl X₀).Choices)
+ (baseBits laneBits initialWidth inputN power scan : ℕ) (online calendar reference m : Memory W₀) : Prop :=
+ let X := X₀
+ let E := B.execute f ok T₀ le_rfl X
+ let Y := E.finalState z
+ let L := BlockProgram.layout B (pub 2).val X.positions T₀
+ let tab : Fin L.shape.tables := ⟨0, by unfold L BlockProgram.layout; change 0 < 6; decide⟩
+ let saved := CursorRAM.ScheduleInit.inputs (CursorRAM.encode W₀ (directoryBase L))
+ (CursorRAM.encode W₀ 1) baseBits laneBits (S.degreeExponent 0) initialWidth (incidenceStart L 0)
+ let resident := CurrentResident.resident B f ok ⟨leafLayer (siteOrder X),.cursor⟩ L (endAddress L) inputN saved
+ ScheduledTrace.Boundary resident pub (levelWords L : BurstRAM.Word W₀) (directoryRows L) (directoryRows L)
+ (executeLevels B f ok T₀ le_rfl X z) Y online →
+ SourceTransport.Agree ((pub 2).val+6 ≤ ·) online calendar →
+ ∀ bits : Fin Y.totalWidth → Bool,
+ TerminalProgram.VertexEntry B f ok T₀ le_rfl X z L tab baseBits laneBits pub calendar reference bits →
+ ∀ j : Fin (siteOrder Y).length, LinkedVertexMemory G₀ reference j.val m →
+ V.SelectedRowsAt adv ξ i μ order f ok P z m power scan →
+ let half := TerminalGatherGeometry.half Y (fun p => bits (Fin.cast (TerminalPrefix.width_sum Y) p))
+ ∀ cap, n^9999 ≤ cap → Nonempty (RatedOrdinal B f ok T₀ le_rfl X z (endAddress L) V₀ M₀
+ (pub 4).val (pub 5).val order.symm P half cap m j n power scan)
+
+set_option maxHeartbeats 1000000 in
+set_option exponentiation.threshold 10000 in
+/-- The threshold precedes the virtual layout, exterior assignment,
+nomination, coefficient realization, selected compression and bit scan. -/
+theorem eventually_rated_at_boundary (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den)
+ (hlabels : D.constants.motifLabels = Fintype.card B.Entry) {labels : ℕ} (order : B.Entry ≃ Fin labels) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2^(D.geometry n).w) (clk : 44 ≤ n^10000)
+ (adv : Bits (n^D.constants.advicePower)) (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+ (A : Type*) [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f) (P : SiteParsers f V.scanState.network)
+ (z : (B.execute f ok (blockCount (u.θ : ℝ) n) le_rfl V.scanState).Choices)
+ (baseBits laneBits initialWidth inputN power scan : ℕ) (online calendar reference m : Memory (D.geometry n).w),
+ V.RatedAtBoundary adv ξ i μ order f ok P z baseBits laneBits initialWidth inputN power scan online calendar reference m := by
+ filter_upwards [eventually_selectedRootBudget D B u haddr hnum hden D.constants.circuitExponent,
+ eventually_rated_root_clock D B u haddr D.constants.circuitExponent] with n budget clocks
+ intro hn V ht clk adv ξ i μ A _ f ok P z baseBits laneBits initialWidth inputN power scan online calendar reference m
+ let G := D.executionGroup n ht clk
+ let ops := terminalOperands G
+ let H := vertexHeader G
+ let T := blockCount (u.θ : ℝ) n
+ let X := V.scanState
+ let E := B.execute f ok T le_rfl X
+ let Y := E.finalState z
+ let L := BlockProgram.layout B (ops 2).val X.positions T
+ let ls := selectedLayers B f ok T le_rfl X z
+ let tags := TraversalRoles.selected B f ok T le_rfl X z
+ let parts := TerminalProgram.nativeSegments B D.constants D.numerator D.denominator order
+ let host := (VertexImage.template parts).instantiate (D.geometry n).w ops
+ have card : labels = Fintype.card B.Entry := (Fintype.card_fin labels).symm.trans (Fintype.card_congr order.symm)
+ obtain ⟨large,geometry,length,branches⟩ := budget hn V ht clk A f ok
+ obtain ⟨fit,width,stack⟩ := branches z
+ obtain ⟨capacity,weights⟩ := clocks.2.2.2.2 hn V A f ok
+ have actual := V.root_at_boundary adv ξ i μ order f ok z baseBits laneBits initialWidth inputN
+ online calendar reference m hlabels large geometry length fit width stack
+ unfold VirtualPairs.RatedAtBoundary
+ intro _ _ _ _ tab saved resident boundary handoff bits entry j later checks half cap room
+ obtain ⟨domain,handlers,checked⟩ := checks
+ let v := (siteOrder Y).entries j
+ have run := actual boundary handoff bits entry j later
+ have wordsEq : tagWords B.recordLimit tags = words B.recordLimit ls :=
+ congrArg (words B.recordLimit) (selected_layers B f ok T le_rfl X z)
+ have arena := fit.arena
+ rw [wordsEq] at arena
+ change endAddress L + 2*words B.recordLimit ls + Y.totalWidth ≤ H.val at arena
+ have headerFit : H.val+32 ≤ 2^(D.geometry n).w := fit.room
+ have tightHeader : H.val+31 < 2^(D.geometry n).w := by omega
+ have rowBounds : endAddress L+words B.recordLimit ls ≤ H.val := by omega
+ have selectedRows : AllRows (D.geometry n).w m B.recordLimit (endAddress L) (endAddress L) ls := by
+ have layerEq : tags.map TaggedLayer.layer = ls := selected_layers B f ok T le_rfl X z
+ rw [← layerEq]
+ apply fit.rows later
+ · rw [layerEq]; exact selected_capacity B f ok T le_rfl X z
+ · rw [layerEq]; exact entry.rows
+ have labelCount : (ops 9).val = Fintype.card B.Entry := (physical_counter_end G fit.fit).2.2.trans hlabels
+ have regions := entry.selected_regions fit later n (Fintype.card B.Entry) length labelCount
+ have cache : (NativeFrame.fromHeader (slotDegree S) ops H m).cacheBase+38 ≤ 2^(D.geometry n).w := by
+ rw [regions]; exact stack.le
+ have ext : (ops 4).val + (ops 5).val + labels ≤ H.val := by
+ have counter := fit.counter_rows
+ change (ops 4).val + (ops 5).val + D.constants.motifLabels ≤ endAddress L at counter
+ rw [hlabels,←card] at counter
+ omega
+ let format := SelectedPacketFormat B f ok T le_rfl X z (endAddress L)
+ let desc := selectedDesc B f ok T le_rfl X z (endAddress L)
+ apply RootRun.ratedOrdinal B f ok T le_rfl X z (endAddress L) (VertexImage.placement parts)
+ host m (ops 4).val (ops 5).val order.symm P half cap j (slotDegree S) _ n power scan (n^9000)
+ _ format desc domain handlers run checked (selected_root_format B f ok T le_rfl X z _ v _)
+ (selectedDesc_root B f ok T le_rfl X z _ v _) selectedRows rowBounds tightHeader cache
+ (capacity.trans_eq length.symm) ext (Fin.cast_val_eq_self _).symm (Fin.cast_val_eq_self _).symm
+ ((Fin.cast_val_eq_self _).symm.trans (congrArg (fun x : ℕ => (x : BurstRAM.Word (D.geometry n).w)) (labelCount.trans card.symm)))
+ clocks.2.2.2.1
+ intro t ht'
+ have tick := (weights z).2 v |>.2 (half v) t ht'
+ rw [← card] at tick
+ exact tick.trans room
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualPaperPreparedInput.lean b/lean/OAI/Computability/VPVNP/PairVirtualPaperPreparedInput.lean
new file mode 100644
index 0000000000..e029702d48
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualPaperPreparedInput.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.LiveVirtualPairOccurrence
+
+/-! # The native copy stage in the paper's pair coordinates -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork LabelEvaluator BurstRAM LiveProgram LocalCount
+open PairStages PairStages.Group PairStages.Group.Auxiliary ExponentTrace CutSchedule
+
+open private headers_cast from OAI.Computability.VPVNP.LiveVirtualPairOccurrence
+
+variable {D : FixedProgramDiagonal.Program} {n : ℕ}
+ {ht : 21 ≤ 2 ^ (D.geometry n).w} {hc : 44 ≤ n ^ 10000}
+ {K : Type*} [Field K] {S : BlockSchedule K} {B : S.Templates} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn D.constants.circuitExponent)}
+ (data : D.ScalarData B hn M)
+ (W : Conditions (D.executionGroup n ht hc) (2 ^ (D.geometry n).d) (D.geometry n).H)
+ (P : PairStageConditions (D.executionGroup n ht hc) (2 ^ (D.geometry n).d) (D.geometry n).H)
+ (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (cut : 1 + B.denseCount n D.constants.circuitExponent * D.counterWidth n ≤
+ n ^ D.constants.deltaPower)
+ (I : VirtualPairs.PhysicalInput data W P rfl hg cut)
+
+/-- The checked physical branch gives the paper-indexed prepared branch with exactly
+the same copy-stage output memory. -/
+theorem VirtualPairs.paperPreparedInput :
+ let G := D.executionGroup n ht hc
+ let i := VirtualPairs.modelIndex data W P rfl hg cut I
+ let ξ := VirtualPairs.exterior data W P rfl hg cut I
+ let N := Nominations.indexed G I.nominationFits (memory I.trace) I.trace.tag
+ ∃ prepared : PreparedBranch G (memory I.trace) (physicalPairIndex i)
+ ((physicalPairLengths (ht := ht) (hf := hc) i).symm ▸ PairedChain.headers data.advice ξ i)
+ N I.μ,
+ prepared.copy.memory () = I.branch.copy.memory () := by
+ let i := VirtualPairs.modelIndex data W P rfl hg cut I
+ let ξ := VirtualPairs.exterior data W P rfl hg cut I
+ let hdr : PrimedInputRAM.Header (D.pairLengths i) → Bool := PairedChain.headers data.advice ξ i
+ have eq := headers_cast heights deltas adviceSizes data.advice I.exterior I.i
+ (physicalPairLengths (ht := ht) (hf := hc) i)
+ change ((physicalPairLengths (ht := ht) (hf := hc) i).symm ▸ hdr) =
+ PairedChain.headers (cast (congrArg Bits adviceSizes) data.advice) I.exterior I.i at eq
+ dsimp only
+ rw [eq]
+ exact ⟨I.branch, rfl⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualPaperRoleBoundary.lean b/lean/OAI/Computability/VPVNP/PairVirtualPaperRoleBoundary.lean
new file mode 100644
index 0000000000..94c0bde9b4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualPaperRoleBoundary.lean
@@ -0,0 +1,204 @@
+import OAI.Computability.VPVNP.PairVirtualDescriptorHistory
+import OAI.Computability.VPVNP.PairVirtualPaperPreparedInput
+import OAI.Computability.VPVNP.PairVirtualEventualChecks
+import OAI.Computability.VPVNP.PairVertexRatedBoundarySelection
+import OAI.Computability.VPVNP.LiveCompressedPairOnlineWord
+
+/-! # Role checks at the terminal boundary of a physical pair -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM CursorBounds CursorNetwork Compression LabelEvaluator LiveProgram LocalCount
+open PairStages PairStages.Group PairStages.Group.Auxiliary PairStages.Group.CompressedPaths
+open CompressedPair PairSimulation LocalHistory CompressorRecords DescriptorSpace
+open TraversalRows TraversalRoles CutSchedule ExponentTrace NetworkKernel
+open scoped Fin.CommRing
+set_option quotPrecheck false
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {u : PairExponents B.growthConstant} {n : ℕ} {hn : 2 ≤ n}
+ {ht : 21 ≤ 2 ^ (D.geometry n).w} {clk : 44 ≤ n ^ 10000} {p : Nat.Primes}
+ {model : Model p (B.compressorDegree n) (B.compressorEquations hn D.constants.circuitExponent)}
+ {data : D.ScalarData B hn model} {V : D.VirtualPairs B u hn D.constants.circuitExponent}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n ^ D.constants.deltaPower)} {i : D.groupIndices n}
+ {μ : Nominations.Nom (D.executionGroup n ht clk)}
+ (scan : CanonicalScan data V ξ i (physicalNomination rfl μ))
+ {hg : D.constants.motifLabels = Fintype.card B.Entry} {rate : ℕ}
+ {input : Memory (wordBits D.addressFactor n)}
+
+local notation "G₀" => D.executionGroup n ht clk
+local notation "start₀" => (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+local notation "pub₀" => publicWords (G₀)
+local notation "κ₀" => B.compressorValues hn model
+local notation "ok₀" => B.compressorValues_solution hn model
+local notation "T₀" => blockCount (u.θ : ℝ) n
+local notation "X₀" => V.scanState
+local notation "pos₀" => initialPositions D.addressFactor n
+local notation "L₀" => BlockProgram.layout B (start₀) (pos₀) (T₀)
+local notation "base₀" => virtualBits D.addressFactor n - reservedLanes B u n
+local notation "lanes₀" => reservedLanes B u n
+local notation "order₀" => entryOrdinal B D.constants hg
+local notation "boot₀" => paperBootstrap B u
+local notation "script₀" => BlockProgram.script B
+
+variable (receipt : V.PaperDescriptor (B.compressorValues hn model)
+ (B.compressorValues_solution hn model) D.constants hg
+ ((LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n))
+ (fuel (D.executionGroup n ht clk)) rate (publicWords (D.executionGroup n ht clk)) input)
+ (z : (V.selection (M := model)).Choices)
+
+attribute [local irreducible] TerminalProgram.workers CompressedPair.regs BlockProgram.script
+ BlockProgram.layout VertexImage.template VertexImage.placement BlockSchedule.Templates.execute
+ CursorNetwork.cursorState CursorBounds.wordBits
+
+/-- All three roles at every site of the selected branch, in the order used
+by the fixed terminal instruction table. -/
+abbrev CanonicalScan.PaperRoleBoundary : Prop :=
+ let tab : Fin (L₀).shape.tables := ⟨0, by unfold BlockProgram.layout; change 0 < 6; decide⟩
+ let Y := (V.selection (M := model)).finalState z
+ let payload := CompiledResident.payload (w := (D.geometry n).w) B κ₀ ok₀
+ ((start₀ : ℕ) : BurstRAM.Word (D.geometry n).w) pos₀ T₀ n
+ ∀ bits reference, TerminalProgram.VertexEntry B κ₀ ok₀ T₀ le_rfl X₀ z L₀ tab
+ base₀ lanes₀ pub₀ (onlinePost (receipt.paths z)) reference bits →
+ SelectedPayloadHistory.Past B κ₀ ok₀ L₀ payload
+ (executeLevels B κ₀ ok₀ T₀ le_rfl X₀ z) reference →
+ ∀ (j : Fin (siteOrder Y).length) m, LinkedVertexMemory G₀ reference j.val m →
+ V.SelectedRowsAt data.advice ξ i μ order₀ κ₀ ok₀ scan.leafSites z m 1
+ (VertexImage.RatedRoles.scan B order₀)
+
+omit [NeZero (virtualBits D.addressFactor n)] in
+/-- The real startup and calendar preserve the prepared input words read by the leaf reader. -/
+theorem VirtualPairs.PaperDescriptor.calendar_input_below
+ (setup : TransferredStartup.Runs
+ (bootstrapRows boot₀ (script₀).initial.length (script₀).block.length) (script₀).size
+ (startupLayout boot₀ (script₀).initial.length (script₀).block.length D.addressFactor n start₀)
+ D.addressFactor n (S.degreeExponent 0) S.laneBits S.steps pub₀ (PairTag.address pub₀) input)
+ (workspace : (pub₀ 2).val = start₀) (tag : (PairTag.address pub₀).val < (pub₀ 2).val)
+ (x : ℕ) (low : x < (pub₀ 2).val) (apart : x ≠ (PairTag.address pub₀).val) :
+ onlinePost (receipt.paths z) x = input x := by
+ have below : (PairTag.address pub₀).val < (pub₀ 2).val + 6 := by omega
+ exact (receipt.protectedOnline below).after_startup_word D.addressFactor n start₀ input setup
+ receipt.init (receipt.paths z) x (low.trans_eq workspace) apart
+ (receipt.online_word below x (by omega))
+
+open Filter
+
+private theorem eventually_role_startup (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant)
+ (lanes : S.laneBits ≤ D.addressFactor)
+ (num : D.numerator = (liveRatio u).num) (den : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clk : 44 ≤ n ^ 10000),
+ let G := D.executionGroup n ht clk
+ let pub := publicWords G
+ let ws := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ let boot := paperBootstrap B u
+ let script := BlockProgram.script B
+ (pub 2).val = ws ∧ (PairTag.address pub).val < (pub 2).val ∧ ∀ m,
+ TransferredStartup.Runs (bootstrapRows boot script.initial.length script.block.length)
+ script.size (startupLayout boot script.initial.length script.block.length
+ D.addressFactor n ws) D.addressFactor n (S.degreeExponent 0) S.laneBits S.steps
+ pub (PairTag.address pub) m := by
+ let base := fun n => (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ have bounds : PolynomiallyBounded base := by
+ have eqn : base = fun n => (LiveProgram.Layout.pairWorkspace D.constants).eval
+ (paperGeometry D.addressFactor (liveCapacity u) n) := by
+ funext n
+ change (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n) = _
+ rw [paperGeometry_eq D B u num den n]
+ rw [eqn]
+ exact startup_workspace_polynomial _ D.address_pos (liveCapacity_polynomial u)
+ have frac : ((blockRatio u).num : ℝ) / (blockRatio u).den ≤ 1 := by
+ rw [(blockRatio u).value]
+ exact_mod_cast (le_trans u.theta_lt.le (by norm_num))
+ let boot := paperBootstrap B u
+ let script := BlockProgram.script B
+ have arity : 7 ≤ boot.shape.arity := (by decide : 7 ≤ 11).trans (InitialTransferred.arity B)
+ have scalars : 30 ≤ boot.shape.scalarFields := by change 30 ≤ 54; decide
+ have phases : 0 < (bootstrapRows boot script.initial.length script.block.length).phaseRows := by
+ unfold script BlockProgram.script
+ exact InitialTransferred.phases_pos B
+ have runs := TransferredStartup.eventually_run
+ (bootstrapRows boot script.initial.length script.block.length) script.size boot.shape
+ D.addressFactor (S.degreeExponent 0) S.laneBits S.steps D.address_pos (blockRatio u).den_pos
+ phases frac lanes arity scalars bounds
+ filter_upwards [runs, eventually_startup_inputs D.constants D.address_pos
+ (liveCapacity_polynomial u)] with n started ready
+ intro ht clk G pub ws boot' script'
+ have actual := ready G.lit
+ rw [← paperGeometry_eq D B u num den n] at actual
+ obtain ⟨workspace, length, width, tag⟩ := actual
+ change (pub 2).val = ws at workspace
+ change (PairTag.address pub).val < (pub 2).val at tag
+ exact ⟨workspace, tag, started pub (PairTag.address pub) workspace length width
+ (tag.trans_eq workspace)⟩
+
+set_option maxHeartbeats 900000 in
+-- The branch, the prepared header and the dependent directory must agree simultaneously.
+/-- One threshold supplies the terminal role readers for every physical nomination,
+selected compressor path and reached site in every realization at that length. -/
+theorem eventually_paperRoleBoundary (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant)
+ (labels : D.constants.motifLabels = Fintype.card B.Entry)
+ (addr : max S.laneBits 5 ≤ D.addressFactor)
+ (num : D.numerator = (liveRatio u).num) (den : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ [NeZero (virtualBits D.addressFactor n)]
+ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clk : 44 ≤ n ^ 10000)
+ {p : Nat.Primes} {model : Model p (B.compressorDegree n)
+ (B.compressorEquations hn D.constants.circuitExponent)}
+ (data : D.ScalarData B hn model),
+ let G := D.executionGroup n ht clk
+ let sites := 2 ^ (D.geometry n).d
+ let cap := (D.geometry n).H
+ ∀ (W : Conditions G sites cap) (P : PairStageConditions G sites cap)
+ (cut : 1 + B.denseCount n D.constants.circuitExponent * D.counterWidth n ≤
+ n ^ D.constants.deltaPower)
+ (I : VirtualPairs.PhysicalInput data W P rfl labels cut),
+ let ext := VirtualPairs.exterior data W P rfl labels cut I
+ let idx := VirtualPairs.modelIndex data W P rfl labels cut I
+ let start := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ let f := B.compressorValues hn model
+ let ok := B.compressorValues_solution hn model
+ ∀ (A : CanonicalScan data V ext idx (physicalNomination rfl I.μ)) (rate : ℕ)
+ (receipt : V.PaperDescriptor f ok D.constants labels start (fuel G) rate
+ (publicWords G) (I.branch.copy.memory ())) (z : (V.selection (M := model)).Choices),
+ A.PaperRoleBoundary receipt z := by
+ let order := entryOrdinal B D.constants labels
+ filter_upwards [eventually_activeChecks D B u order labels addr num den,
+ eventually_role_startup D B u ((Nat.le_max_left _ _).trans addr) num den]
+ with n checks startup
+ intro hn V inst ht clk p model data G sites cap W P cut I ext idx start f ok A rate receipt z
+ bits reference entry _ j m later
+ obtain ⟨workspace, tag, setup⟩ := startup ht clk
+ obtain ⟨prepared, copy⟩ := VirtualPairs.paperPreparedInput data W P labels cut I
+ have positions : V.scanState.positions = initialPositions D.addressFactor n := by
+ rw [V.scanState_pairInput]
+ exact pairInput_positions S _ _
+ have history := receipt.past_calendar z workspace (tag.trans_le (Nat.le_add_right _ _))
+ have ws : (terminalOperands G 2).val = start := workspace
+ apply checks hn V ht clk data ext idx I.μ A z prepared
+ (tab := ⟨0, by unfold BlockProgram.layout; change 0 < 6; decide⟩)
+ (bits := bits) (reference := reference) (ord := j.val)
+ (calendar := onlinePost (receipt.paths z))
+ · let blocks := blockCount (u.θ : ℝ) n
+ have same : BlockProgram.layout B start (initialPositions D.addressFactor n) blocks =
+ BlockProgram.layout B (terminalOperands G 2).val V.scanState.positions blocks := by
+ rw [ws, positions]
+ exact entry.changeLayout same
+ (tab' := ⟨0, by unfold BlockProgram.layout; change 0 < 6; decide⟩) rfl
+ · exact history
+ · exact later
+ · intro x low apart
+ exact (receipt.calendar_input_below z (setup _) workspace tag x low apart).trans
+ (congrFun copy.symm x)
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualPhysicalMapData.lean b/lean/OAI/Computability/VPVNP/PairVirtualPhysicalMapData.lean
new file mode 100644
index 0000000000..833ead1056
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualPhysicalMapData.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.PairShrinkPhysicalMapData
+import OAI.Computability.VPVNP.PairVirtualShrinkCapacity
+
+/-!
+# Virtual-pair packet capacities at the physical map bank
+
+The virtual bounds number the DFS arena by its tagged layers. The physical
+site bank counts the same rows in the selected execution. Identifying those
+two row counts places each virtual packet bound at exactly the canonical
+job of the physical vertex.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression CompressorRecords DescriptorSpace LocalHistory
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TraversalRows TraversalRoles
+open FixedProgramDiagonal.Program
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+variable {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f hf T hT X).Choices) {G : Group} {n : ℕ}
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence BlockProgram.layout
+ BlockSchedule.Templates.execute StateExecution.finalState executeLevels
+set_option quotPrecheck false
+local notation "pub" => terminalOperands G
+set_option quotPrecheck false in
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val X.positions T
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "rowEnd" => endAddress D + words B.recordLimit (selectedLayers B f hf T hT X z)
+local notation "before" j => layerBase B.recordLimit (endAddress D) tags j
+local notation "area" => TerminalLayout.privateRegions (slotDegree S) n rowEnd
+ (Fintype.card B.Entry)
+set_option quotPrecheck false in
+local notation "lim" => ShrinkCallABI.hiddenBase area n + ShrinkCallCapacity.extent
+ (X.positions * slotDegree S) n
+local notation "sites" => ShrinkRoleDirectory.ShrinkSite passes
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ {baseBits laneBits ord : ℕ} {calendar reference phy : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n)
+ (executeLevels B f hf T hT X z) calendar)
+ (entry : TerminalProgram.VertexEntry (w := G.w) B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+ (packed : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ord phy)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+
+set_option maxHeartbeats 1800000 in
+-- Align the packed packet types at the chronological occurrence and the common terminal row end.
+/-- The packet field of the virtual-pair bound supplies the complete physical
+map-data contract for any parent assignment at this shrinking vertex. -/
+theorem physicalSiteMapData_virtual
+ (fits : ∀ x : sites, ∀ m, canonicalFits B x.occurrence.i x.occurrence.state
+ x.occurrence.selection (w := G.w) (Fintype.card B.Entry) n rowEnd (before x.val.1.val) lim m)
+ (x : sites)
+ (numeric : VirtualShrink.Maps B x (pub 2) X.positions T n (endAddress D) tags)
+ (parent : x.occurrence.nextState.network.Half x.occurrence.site) :
+ CanonicalMapData
+ (physicalSiteBank B f hf hT X z history entry packed frame width fits x) (vertexHeader G)
+ parent := by
+ refine physicalSiteMapData B f hf hT X z history entry packed frame width fits x ?_ parent
+ intro m party bounds old localParent
+ have rowEq : tagWords B.recordLimit tags = words B.recordLimit (selectedLayers B f hf T hT X z) :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ have bound := numeric.packets m party bounds old localParent
+ rw [rowEq] at bound
+ exact bound
+
+end PairSimulation.ShrinkRole
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualPreparedRoot.lean b/lean/OAI/Computability/VPVNP/PairVirtualPreparedRoot.lean
new file mode 100644
index 0000000000..e7e44489b7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualPreparedRoot.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.PairVirtualRootBudget
+import OAI.Computability.VPVNP.PairVirtualVertexRoot
+import OAI.Computability.VPVNP.PairVertexRootEntry
+import OAI.Computability.VPVNP.PairVertexRootEntryRows
+
+/-!
+# The selected calendar reaches its actual native root
+
+Every ordinal in the physical shared-bit post-memory enters the selected
+root row. Its cache uses the real nomination. The private argument is the
+two half-wire lists in the same site and edge order as the compressed path.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords DescriptorSpace CursorNetwork CursorBounds Filter LocalHistory TraversalRows
+open VertexImage CutSchedule ExponentTrace
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {u : PairExponents B.growthConstant}
+ {n : ℕ} {hn : 2 ≤ n} {ht : 21 ≤ 2^(D.geometry n).w} {clk : 44 ≤ n^10000}
+ (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (adv : Bits (n^D.constants.advicePower)) (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+ {labels : ℕ} (order : B.Entry ≃ Fin labels)
+
+local notation "G₀" => D.executionGroup n ht clk
+local notation "pub" => terminalOperands G₀
+local notation "hdr" => vertexHeader G₀
+local notation "degree" => slotDegree S
+local notation "T₀" => blockCount (u.θ : ℝ) n
+local notation "X₀" => V.scanState
+local notation "S₀" => TerminalProgram.nativeSegments B D.constants D.numerator D.denominator order
+local notation "M₀" => PrivateRAM.Template.instantiate (VertexImage.template S₀) (Geometry.w (D.geometry n)) pub
+local notation "aux" => V.data adv ξ i (physicalNomination rfl μ)
+local notation "W₀" => Geometry.w (D.geometry n)
+
+attribute [local irreducible] BlockSchedule.Templates.execute BlockProgram.layout VertexImage.template
+ VertexImage.placement CursorNetwork.cursorState CursorBounds.wordBits NativeOperands.capacity NativeOperands.saved
+
+/-- The native root result on an actual online boundary, its terminal handoff and the
+shared-bit memory. All active ordinals use the same selected table image. -/
+def VirtualPairs.SelectedRootCalls {A : Type*} [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f)
+ (z : (B.execute f ok T₀ le_rfl X₀).Choices) (baseBits laneBits initialWidth inputN : ℕ)
+ (online calendar reference m : Memory W₀) : Prop :=
+ let X := X₀
+ let T := T₀
+ let E := B.execute f ok T le_rfl X
+ let Y := E.finalState z
+ let L := BlockProgram.layout B (pub 2).val X.positions T
+ let tab : Fin L.shape.tables := ⟨0, by unfold L BlockProgram.layout; change 0 < 6; decide⟩
+ let saved := CursorRAM.ScheduleInit.inputs (CursorRAM.encode W₀ (directoryBase L))
+ (CursorRAM.encode W₀ 1) baseBits laneBits (S.degreeExponent 0) initialWidth (incidenceStart L 0)
+ let resident := CurrentResident.resident B f ok ⟨leafLayer (siteOrder X),.cursor⟩ L (endAddress L) inputN saved
+ ScheduledTrace.Boundary resident pub (levelWords L : BurstRAM.Word W₀) (directoryRows L) (directoryRows L)
+ (executeLevels B f ok T le_rfl X z) Y online →
+ SourceTransport.Agree ((pub 2).val+6 ≤ ·) online calendar →
+ ∀ bits : Fin Y.totalWidth → Bool,
+ TerminalProgram.VertexEntry B f ok T le_rfl X z L tab baseBits laneBits pub calendar reference bits →
+ ∀ j : Fin (siteOrder Y).length, LinkedVertexMemory G₀ reference j.val m →
+ let v := (siteOrder Y).entries j
+ let bitData := fun p => bits (Fin.cast (TerminalPrefix.width_sum Y) p)
+ let packet : NodeArguments.Packet := ⟨(selectedTrees B f ok T le_rfl X z (endAddress L) v).address,
+ NodeArguments.packed Y v (TerminalGatherGeometry.half Y bitData v)⟩
+ VertexImage.RootRun (VertexImage.placement S₀) M₀ m (j.val : BurstRAM.Word W₀) degree (S.degreeExponent 0)
+ (NativeOperands.work (NativeCache.args D.constants) D.numerator D.denominator (D.geometry n)+76)
+ packet (LeafVisit.cacheWords aux (CursorBounds.virtualBits D.addressFactor n) (roundedUp 1 4 n))
+
+/-- One real selected site, from the online boundary and physical shared-bit
+entry. The retained private packet names the actual selected tree root. -/
+theorem VirtualPairs.root_at_boundary {A : Type*} [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f)
+ (z : (B.execute f ok T₀ le_rfl X₀).Choices) (baseBits laneBits initialWidth inputN : ℕ)
+ (online calendar reference m : Memory W₀) (hg : D.constants.motifLabels = Fintype.card B.Entry)
+ (large : 3 ≤ n) (fit : PairNativeGeometry.Fits D.numerator D.denominator n W₀)
+ (length : (pub 6).val = n) :
+ let X := X₀
+ let T := T₀
+ let E := B.execute f ok T le_rfl X
+ let Y := E.finalState z
+ let L := BlockProgram.layout B (pub 2).val X.positions T
+ let ls := selectedLayers B f ok T le_rfl X z
+ let tags := TraversalRoles.selected B f ok T le_rfl X z
+ VertexPacked G₀ L B.recordLimit tags Y.totalWidth → Y.maxWireWidth ≤ n →
+ (TerminalLayout.privateRegions degree n (endAddress L+words B.recordLimit ls) (Fintype.card B.Entry)).stackBase < 2^W₀ →
+ V.SelectedRootCalls adv ξ i μ order f ok z baseBits laneBits initialWidth inputN online calendar reference m := by
+ intro X T E Y L ls tags P width stack
+ unfold VirtualPairs.SelectedRootCalls
+ intro _ _ _ _ _ tab saved resident boundary handoff bits entry j later v bitData packet
+ have ⟨slots,cells⟩ := selected_table_capacity B f ok T le_rfl X z (pub 2).val
+ have levelFit : ls.dropLast.length < L.levels := by
+ rw [show ls.dropLast.length = T*(S.steps+1) from TerminalBootstrap.selected_prior_length ..,
+ show L.levels = 1+(S.steps+1)*T from BlockProgram.actual_level_count ..,Nat.mul_comm T]
+ omega
+ let last : Fin L.levels := ⟨ls.dropLast.length,levelFit⟩
+ have arena := P.arena
+ have room := P.room
+ have endFit : endAddress L < 2^W₀ := by change (hdr).val+32 ≤ 2^W₀ at room; omega
+ have cols := (TerminalPrefix.Linked.boundary_inputs B f ok T le_rfl X z X.positions baseBits laneBits initialWidth inputN
+ pub online calendar boundary handoff endFit slots).2.2
+ let state : BurstRAM.Word W₀ := (j.val : BurstRAM.Word W₀)
+ have rows := entry.gather_rows degree state levelFit endFit slots (by
+ change (hdr).val+12 ≤ 2^W₀; change (hdr).val+32 ≤ 2^W₀ at room; omega) cols
+ have jFit : j.val < 2^W₀ := by
+ have h := (P.heads last tab _ slots cells (DescriptorSpace.tableBase L last tab) (by simp)).2
+ have count : (siteOrder Y).length ≤ TerminalPrefix.arcCount Y :=
+ Nat.le_mul_of_pos_right _ (Nat.two_pow_pos (S.degreeExponent 0))
+ exact j.isLt.trans_le (count.trans ((Nat.le_add_left ..).trans (h.trans endFit.le)))
+ have index : state.val = ((siteOrder Y).entries.symm v).val := by
+ change j.val % (2^W₀) = ((siteOrder Y).entries.symm ((siteOrder Y).entries j)).val
+ rw [Nat.mod_eq_of_lt jFit,Equiv.symm_apply_apply]
+ have labelCount : (pub 9).val = Fintype.card B.Entry := (physical_counter_end G₀ P.fit).2.2.trans hg
+ have inputs := entry.rootInputs P later n (Fintype.card B.Entry) length labelCount width stack
+ v state index last rfl slots cells rows
+ have run := V.active_root adv ξ i μ order Y v m state bitData inputs large fit
+ have sizeEq : TraversalRoles.tagWords B.recordLimit tags = words B.recordLimit ls :=
+ congrArg (words B.recordLimit) (TraversalRoles.selected_layers B f ok T le_rfl X z)
+ rw [sizeEq] at arena
+ have rowFit : endAddress L + words B.recordLimit ls ≤ 2^W₀ := by
+ change (hdr).val+32 ≤ 2^W₀ at room
+ omega
+ have root := entry.gather_root v degree state index room rowFit
+ have same := P.gatherLayout later degree state
+ have eqPacket : VertexRootPacket.packet Y (TerminalRootGather.Layout.ofHeader degree pub hdr state m) v bitData = packet := by
+ rw [same]
+ exact congrArg (fun k => NodeArguments.Packet.mk k (NodeArguments.packed Y v (TerminalGatherGeometry.half Y bitData v))) root.symm
+ rw [eqPacket] at run
+ exact run
+
+
+/-- The auxiliary shadow and every selected root on the same physical
+nomination, uniformly in the scalar assignment and all selected choices. -/
+theorem eventually_preparedRoots (D : FixedProgramDiagonal.Program) (B : S.Templates)
+ (u : PairExponents B.growthConstant) (order : B.Entry ≃ Fin labels)
+ (hg : D.constants.motifLabels = Fintype.card B.Entry) (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2^(D.geometry n).w) (clk : 44 ≤ n^10000) (adv : Bits (n^D.constants.advicePower))
+ (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)) (i : D.groupIndices n),
+ let G := D.executionGroup n ht clk
+ ∀ (μ : PairStages.Group.Nominations.Nom G) {initial : Memory G.w}
+ {N : PairStages.Group.Indexed G Stage.nominations initial (PairStages.Group.Nominations.Nom G)}
+ (P : PreparedBranch G initial (physicalPairIndex i)
+ ((physicalPairLengths (ht := ht) (hf := clk) i).symm ▸ PairedChain.headers adv ξ i) N μ)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f),
+ (∀ x, P.copy.memory () ((shadow G).val+x) = (V.data adv ξ i (physicalNomination rfl μ)).initial x) ∧
+ ∀ (z : (B.execute f ok (blockCount (u.θ : ℝ) n) le_rfl V.scanState).Choices)
+ (baseBits laneBits initialWidth inputN : ℕ) (online calendar reference m : Memory G.w),
+ V.SelectedRootCalls adv ξ i μ order f ok z baseBits laneBits initialWidth inputN online calendar reference m := by
+ filter_upwards [eventually_selectedRootBudget D B u haddr hnum hden D.constants.circuitExponent]
+ with n ready hn V ht clk adv ξ i G μ initial N P A inst f ok
+ have ⟨large,fit,length,branches⟩ := ready hn V ht clk A f ok
+ refine ⟨V.shadow_initial rfl adv ξ i μ P,?_⟩
+ intro z baseBits laneBits initialWidth inputN online calendar reference m
+ have ⟨packed,width,stack⟩ := branches z
+ exact V.root_at_boundary adv ξ i μ order f ok z baseBits laneBits initialWidth inputN online calendar reference m
+ hg large fit length packed width stack
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualRefreshChecks.lean b/lean/OAI/Computability/VPVNP/PairVirtualRefreshChecks.lean
new file mode 100644
index 0000000000..15edbc5573
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualRefreshChecks.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.PairRefreshOriginLevel
+import OAI.Computability.VPVNP.PairRefreshSelectedLevelMemory
+import OAI.Computability.VPVNP.PairVertexRoleNativeRefresh
+import OAI.Computability.VPVNP.PairVertexRatedRoles
+import OAI.Computability.VPVNP.PairVirtualRefreshRoom
+import OAI.Computability.VPVNP.PairSelectedRefreshRows
+import OAI.Computability.VPVNP.PairVertexSelectedClock
+
+/-! # The complete refresh role of the physical virtual-pair program -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords DescriptorSpace CursorNetwork CursorBounds Filter LocalHistory
+open TraversalRows TraversalRoles VertexImage TreeDecode
+open private blocks_le_log from OAI.Computability.VPVNP.CompressorDirectoryBudget
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant) {labels : ℕ} (order : B.Entry ≃ Fin labels)
+
+attribute [local irreducible] VertexImage.placement VertexImage.template BlockProgram.layout
+ BlockSchedule.Templates.execute RefreshHook.SelectedRows.parser CursorNetwork.cursorState
+ CursorBounds.wordBits selectedDesc ordinalJobCost
+
+set_option maxHeartbeats 1200000 in
+-- The selected branch fixes the dependent argument state at every kernel visit.
+set_option exponentiation.threshold 10000 in
+/-- All selected refresh rows of the actual virtual pair share a length
+threshold and the same installed reader, including in memories reached
+after an arbitrary number of preceding vertex calls. -/
+theorem eventually_virtualRefreshChecks (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clock : 44 ≤ n ^ 10000)
+ (A : Type) [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f),
+ let G := D.executionGroup n ht clock
+ let ops := terminalOperands G
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f ok T le_rfl X
+ let L := BlockProgram.layout B (ops 2).val X.positions T
+ ∀ (z : E.Choices) {baseBits laneBits ord : ℕ} {tab : Fin L.shape.tables}
+ {calendar reference m : Memory G.w} {bits : Fin (E.finalState z).totalWidth → Bool},
+ TerminalProgram.VertexEntry B f ok T le_rfl X z L tab baseBits laneBits ops
+ calendar reference bits →
+ SelectedPayloadHistory.Past B f ok L
+ (CompiledResident.payload B f ok (ops 2) X.positions T n)
+ (executeLevels B f ok T le_rfl X z) calendar →
+ LinkedVertexMemory G reference ord m →
+ TerminalProgram.RefreshRows B f ok G n D.numerator D.denominator order T le_rfl X z m := by
+ filter_upwards [eventually_virtualRefreshRooms D B u labels haddr hnum hden,
+ eventually_selectedRootBudget D B u haddr hnum hden D.constants.circuitExponent,
+ eventually_histogram_credit D.addressFactor D.address_pos,
+ RefreshHook.SelectedRows.eventually_levelChecks B order D.constants
+ D.numerator D.denominator]
+ with n rooms roots credit checks
+ intro hn V ht clock A _ f ok G ops X T E L z baseBits laneBits ord tab calendar reference m
+ bits entry history frame
+ let passes := executeLevels B f ok T le_rfl X z
+ let leaf : TaggedLayer := ⟨leafLayer (siteOrder X), .cursor⟩
+ let tags := selected B f ok T le_rfl X z
+ let width := (E.finalState z).totalWidth
+ let size := tagWords B.recordLimit tags
+ let region := TerminalLayout.privateRegions (slotDegree S) n (endAddress L + size) labels
+ let room := rooms hn V ht clock A f ok z
+ let refresh := RefreshHook.SelectedRows.parser n labels G.w (ops 2).val X.positions T width leaf
+ passes room order ops m
+ let segments := TerminalProgram.nativeSegments B D.constants D.numerator D.denominator order
+ let place := placement segments
+ let host := (template segments).instantiate G.w ops
+ obtain ⟨_, _, _, root⟩ := roots hn V ht clock A f ok
+ obtain ⟨packed, _, stack⟩ := root z
+ have rowsEq : size = words B.recordLimit (selectedLayers B f ok T le_rfl X z) :=
+ congrArg (words B.recordLimit) (selected_layers B f ok T le_rfl X z)
+ have labelsEq : labels = Fintype.card B.Entry :=
+ (Fintype.card_fin labels).symm.trans (Fintype.card_congr order.symm)
+ have fits : region.stackBase ≤ 2 ^ G.w := by
+ change (TerminalLayout.privateRegions (slotDegree S) n
+ (endAddress L + size) labels).stackBase ≤ _
+ rw [rowsEq, labelsEq]
+ exact stack.le
+ have memory := RefreshHook.SelectedRows.levelMemory_at B f ok G n labels T le_rfl X z room
+ entry history packed frame fits (blocks_le_log B u (by omega))
+ refine ⟨refresh, fun vals => ?_⟩
+ constructor
+ · exact RoleDomains.nativeRefresh B f ok G (ops 2) X.positions T le_rfl X z
+ entry history packed frame room
+ D.numerator D.denominator order
+ · intro old shr i tag
+ have cap : n ≤ n ^ 9000 :=
+ (Nat.pow_one n).symm.le.trans (Nat.pow_le_pow_right (by omega) (by decide))
+ exact checks f ok T le_rfl X z G.w (ops 2).val X.positions width room place host m
+ (template_contains segments ops) memory _ vals (n ^ 9000) (n * n ^ 9000) 1
+ (RatedRoles.scan B order) cap credit le_rfl (RatedRoles.role_le B order .refresh)
+ (RoleDomains.handlers old shr refresh) rfl i tag
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualRefreshRoom.lean b/lean/OAI/Computability/VPVNP/PairVirtualRefreshRoom.lean
new file mode 100644
index 0000000000..0e52fa1976
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualRefreshRoom.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.PairRefreshSelectedRoom
+import OAI.Computability.VPVNP.PairVirtualRootBudget
+
+/-! # Capacity of all chronological refresh rows in the virtual pair -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords CursorNetwork CursorBounds Filter LocalHistory TraversalRows TraversalRoles
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k}
+ (D : FixedProgramDiagonal.Program) (B : S.Templates) (u : PairExponents B.growthConstant)
+
+attribute [local irreducible] BlockSchedule.Templates.execute BlockProgram.layout
+ CursorNetwork.cursorState
+
+/-- The same private capacity threshold applies to the true scan state and
+the public workspace of every nomination and every compressor branch. -/
+theorem eventually_virtualRefreshRooms (labels : ℕ) (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clock : 44 ≤ n ^ 10000)
+ (A : Type) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let G := D.executionGroup n ht clock
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ ∀ z : (B.execute f hf T le_rfl X).Choices,
+ RefreshHook.SelectedRows.Rooms n labels G.w (terminalOperands G 2).val X.positions T
+ ⟨leafLayer (siteOrder X), .cursor⟩ (executeLevels B f hf T le_rfl X z) := by
+ let start n := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ have poly : PolynomiallyBounded start := by
+ have eqn : start = fun n => (LiveProgram.Layout.pairWorkspace D.constants).eval
+ (paperGeometry D.addressFactor (liveCapacity u) n) := by
+ funext n
+ exact congrArg (PublicExpr.eval · (LiveProgram.Layout.pairWorkspace D.constants))
+ (paperGeometry_eq D B u hnum hden n)
+ rw [eqn]
+ exact CompressedPair.startup_workspace_polynomial _ D.address_pos (liveCapacity_polynomial u)
+ filter_upwards [RefreshHook.SelectedRows.eventually_rooms B u D.addressFactor haddr poly labels,
+ CompressedPair.eventually_startup_inputs D.constants D.address_pos (liveCapacity_polynomial u)]
+ with n room inputs
+ intro hn V ht clock A _ f hf
+ dsimp only
+ rw [V.scanState_pairInput]
+ let G := D.executionGroup n ht clock
+ have ports := inputs (CounterPublic.actualPrefix D.literal)
+ rw [← paperGeometry_eq D B u hnum hden n] at ports
+ have startEq : (terminalOperands G 2).val = start n := ports.1
+ rw [startEq, pairInput_positions]
+ exact room (laneLabels _ _ V.lanes) V.dimension le_rfl A f hf
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualRootBudget.lean b/lean/OAI/Computability/VPVNP/PairVirtualRootBudget.lean
new file mode 100644
index 0000000000..c8a2cdc6c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualRootBudget.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.FixedProgramOperandFits
+import OAI.Computability.VPVNP.LiveCertificateAssembly
+import OAI.Computability.VPVNP.LiveVirtualPairCursorBoundary
+import OAI.Computability.VPVNP.PairTerminalVertexPackedThreshold
+import OAI.Computability.VPVNP.PairTerminalPackedBudget
+import OAI.Computability.VPVNP.LiveCompressedPairStartupInputs
+import OAI.Computability.VPVNP.PairNativeGeometry
+
+/-!
+# The physical root bounds before the selected branch
+
+One length threshold gives the terminal workspace, private cache fit and
+maximum field width for all branches of the actual virtual pair. The
+workspace has the tight chronological level count emitted by the calendar.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords DescriptorSpace CursorNetwork CursorBounds Filter
+
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant)
+
+/-- Public terminal slots six and nine carry the input length and the fixed motif count.
+The two values fit without word reduction beyond one threshold, uniformly over groups. -/
+theorem eventually_terminalOperandSizes {labels : ℕ} (hlabels : D.constants.motifLabels = labels) :
+ ∀ᶠ n : ℕ in atTop, ∀ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clk : 44 ≤ n ^ 10000),
+ let G := D.executionGroup n ht clk
+ (terminalOperands G 6).val = n ∧ (terminalOperands G 9).val = labels := by
+ filter_upwards [CompressorRecords.CursorRAM.eventual_word_room D.addressFactor D.address_pos
+ PolynomiallyBounded.id, CompressorRecords.CursorRAM.eventual_word_room D.addressFactor D.address_pos
+ (PolynomiallyBounded.const D.constants.motifLabels)] with n length count
+ intro ht clk G
+ exact ⟨Nat.mod_eq_of_lt length, (Nat.mod_eq_of_lt count).trans hlabels⟩
+
+attribute [local irreducible] BlockSchedule.Templates.execute BlockProgram.layout CursorNetwork.cursorState
+
+set_option maxHeartbeats 800000 in
+theorem eventually_selectedRootBudget (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) (C : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C) (ht : 21 ≤ 2^(D.geometry n).w)
+ (hf : 44 ≤ n^10000) (A : Type*) [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f),
+ let G := D.executionGroup n ht hf
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f ok T le_rfl X
+ let L := BlockProgram.layout B (terminalOperands G 2).val X.positions T
+ 3 ≤ n ∧ PairNativeGeometry.Fits D.numerator D.denominator n (D.geometry n).w ∧
+ (terminalOperands G 6).val = n ∧ ∀ z : E.Choices,
+ let Y := E.finalState z
+ let ls := TraversalRows.selectedLayers B f ok T le_rfl X z
+ let tags := TraversalRoles.selected B f ok T le_rfl X z
+ VertexPacked G L B.recordLimit tags Y.totalWidth ∧ Y.maxWireWidth ≤ n ∧
+ (TerminalLayout.privateRegions (slotDegree S) n (endAddress L+TraversalRows.words B.recordLimit ls)
+ (Fintype.card B.Entry)).stackBase < 2^(D.geometry n).w := by
+ let start := fun n => (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ have poly : PolynomiallyBounded start := by
+ have eqn : start = fun n => (LiveProgram.Layout.pairWorkspace D.constants).eval
+ (paperGeometry D.addressFactor (liveCapacity u) n) := by
+ funext n
+ change (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n) = _
+ rw [paperGeometry_eq D B u hnum hden n]
+ rw [eqn]
+ exact CompressedPair.startup_workspace_polynomial _ D.address_pos (liveCapacity_polynomial u)
+ filter_upwards [eventually_ge_atTop 3,
+ PairNativeGeometry.eventually_fits D.numerator D.denominator D.addressFactor D.address_pos,
+ CompressedPair.eventually_startup_inputs D.constants D.address_pos (liveCapacity_polynomial u),
+ eventually_vertexPacked B u D.addressFactor haddr poly,
+ TerminalLayout.eventually_packedFit B u D.addressFactor haddr poly 0 (fun _ => 0) (PolynomiallyBounded.const 0),
+ eventually_pairBranchBounds B u D.addressFactor haddr] with n hn₃ hgeo hwords hpack hstack hbranch
+ intro hn V ht hf A inst f ok
+ dsimp only
+ rw [V.scanState_pairInput]
+ let G := D.executionGroup n ht hf
+ let coords := laneLabels _ _ V.lanes
+ have words := hwords (CounterPublic.actualPrefix D.literal)
+ rw [←paperGeometry_eq D B u hnum hden n] at words
+ have length : (terminalOperands G 6).val = n := words.2.1
+ have exp : (terminalOperands G 7).val = addressBits D.addressFactor n := words.2.2.1
+ have workspace : (terminalOperands G 2).val = start n := words.1
+ refine ⟨hn₃,hgeo,length,?_⟩
+ intro z
+ have pack := hpack G rfl rfl exp coords V.dimension le_rfl A f ok z
+ have s := hstack coords V.dimension le_rfl A f ok z
+ have bound := hbranch.2.2 coords V.dimension le_rfl A f ok z
+ have hpow {x : ℝ} (h : x ≤ 1) : (n : ℝ)^x ≤ n := by
+ simpa using Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast (show 1 ≤ n by omega)) h
+ have width := Nat.cast_le.mp ((Nat.cast_le.mpr bound.2.2.2.2.1).trans (bound.2.2.2.2.2.1.trans (hpow (by norm_num))))
+ change VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val _ _) _ _ _ ∧ _ ∧ _
+ rw [workspace]
+ refine ⟨pack,width,?_⟩
+ rw [pairInput_positions]
+ have h := s.2.2.2.1
+ simp only [Nat.zero_mul,Nat.add_zero] at h
+ exact h
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualRootPayload.lean b/lean/OAI/Computability/VPVNP/PairVirtualRootPayload.lean
new file mode 100644
index 0000000000..7051876d85
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualRootPayload.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+import OAI.Computability.VPVNP.PairSimulationPhysicalScanData
+import OAI.Computability.VPVNP.PairVertexRootPacket
+
+/-!
+# Root wire arguments of the canonical compressed occurrence
+
+The flat bits selected in the native shared scan are grouped by the same
+outgoing arcs as the canonical pair path. Both its incoming and outgoing
+root fields therefore agree in the native DFS packet.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM CursorBounds CursorNetwork Compression LabelEvaluator
+open PairSimulation PairSimulation.LocalHistory NetworkKernel CutSchedule ExponentTrace
+open private scanMachine capacity from OAI.Computability.VPVNP.LiveVirtualPairCanonicalScan
+
+variable {K : Type*} [_root_.Field K] {S : BlockSchedule K} {D : FixedProgramDiagonal.Program}
+ {B : S.Templates} {n C : ℕ} {hn : 2 ≤ n} {p : Nat.Primes}
+ {M : Model p (B.compressorDegree n) (B.compressorEquations hn C)}
+ {data : D.ScalarData B hn M} {u : PairExponents B.growthConstant} {V : D.VirtualPairs B u hn C}
+ [NeZero (virtualBits D.addressFactor n)]
+ {ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower)} {i : D.groupIndices n} {μ : D.pairNom n C}
+ (A : CanonicalScan data V ξ i μ)
+
+local notation "W₀" => wordBits D.addressFactor n
+local notation "sel" => V.selection (M := M)
+local notation "linked" => FinalBits.template_linked (fun _ : Fin 1 => FinalBits.cursor W₀ 0 0)
+
+/-- Reindex the canonical final-bit scan by the native shared worker's
+complete assignment. -/
+noncomputable abbrev CanonicalScan.sharedBits (z : (sel).Choices) :
+ (A.arc z).Path ≃ (Fin ((sel).finalState z).totalWidth → Bool) :=
+ PhysicalScanData.assignment ((sel).finalState z) (scanMachine W₀) Fin.castSucc (Function.Embedding.refl _)
+ 0 10 linked rfl 0 rfl (fun _ => 0) 0 (capacity A z)
+
+theorem CanonicalScan.rootHalf (z : (sel).Choices) (x : TerminalData (A.arc z) (A.sites z))
+ (v : ((sel).finalState z).network.Site) :
+ let Y := (sel).finalState z
+ TerminalGatherGeometry.half Y (fun j => A.sharedBits z x.arcs (Fin.cast (TerminalPrefix.width_sum Y) j)) v =
+ WireTensor.edgeAssignment Y.network.src Y.network.dst ((A.arc z).payload x.arcs) v := by
+ intro Y
+ have payload := PhysicalScanData.payload Y (scanMachine W₀) Fin.castSucc (Function.Embedding.refl _)
+ 0 10 linked rfl 0 rfl (fun _ => 0) 0 (capacity A z) x.arcs
+ exact congrArg (fun f => WireTensor.edgeAssignment Y.network.src Y.network.dst f v) payload.symm
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualSelectedRoles.lean b/lean/OAI/Computability/VPVNP/PairVirtualSelectedRoles.lean
new file mode 100644
index 0000000000..7050880712
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualSelectedRoles.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.PairVirtualOrdinalCalls
+import OAI.Computability.VPVNP.PairSelectedNativeRoles
+
+/-!
+# Transport of the installed vertex contracts to the virtual pair
+
+The private regions and role offset used in the packed per-level proofs
+are exactly the geometry read from the current ordinal's memory. The
+machine's end-of-stack word has the actual input length as its value.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression
+open CompressorRecords DescriptorSpace CursorNetwork CursorBounds LocalHistory TraversalRows
+open VertexImage CutSchedule ExponentTrace TreeDecode NetworkKernel
+open scoped Fin.CommRing
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ {D : FixedProgramDiagonal.Program} {B : S.Templates} {u : PairExponents B.growthConstant}
+ {n : ℕ} {hn : 2 ≤ n} {ht : 21 ≤ 2 ^ (D.geometry n).w} {clk : 44 ≤ n ^ 10000}
+ (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (adv : Bits (n ^ D.constants.advicePower))
+ (ξ : Exterior (D.chainHeight n) (n ^ D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht clk))
+ {labels : ℕ} (order : B.Entry ≃ Fin labels) (f : B.Entry → A) (ok : B.IsSolution f)
+ (sites : SiteParsers f V.scanState.network)
+ (z : (B.execute f ok (blockCount (u.θ : ℝ) n) le_rfl V.scanState).Choices)
+ (baseBits laneBits ord power scan : ℕ)
+
+local notation "group" => D.executionGroup n ht clk
+local notation "pub" => terminalOperands (group)
+local notation "hdr" => vertexHeader (group)
+local notation "w₀" => Geometry.w (D.geometry n)
+local notation "T₀" => blockCount (u.θ : ℝ) n
+local notation "X₀" => VirtualPairs.scanState V
+local notation "exec₀" => B.execute f ok (T₀) le_rfl (X₀)
+local notation "Y₀" => StateExecution.finalState (exec₀) z
+local notation "L₀" => BlockProgram.layout B (Fin.val (pub 2)) (State.positions (X₀)) (T₀)
+local notation "base" => endAddress (L₀)
+local notation "tags" => TraversalRoles.selected B f ok (T₀) le_rfl (X₀) z
+local notation "size" => TraversalRoles.tagWords B.recordLimit (tags)
+local notation "width" => State.totalWidth (Y₀)
+local notation "offset" => (((size) + (width) : ℕ) : BurstRAM.Word w₀)
+local notation "area" => TerminalLayout.privateRegions (slotDegree S) n ((base) + (size)) labels
+local notation "image" => TerminalProgram.nativeSegments B D.constants D.numerator
+ D.denominator order
+local notation "placement₀" => VertexImage.placement (image)
+local notation "M₀" => PrivateRAM.Template.instantiate (VertexImage.template (image)) w₀ pub
+local notation "vals₀" => LeafVisit.cacheWords (V.data adv ξ i (physicalNomination rfl μ))
+ (virtualBits D.addressFactor n) (roundedUp 1 4 n)
+
+attribute [local irreducible] VertexImage.placement VertexImage.template BlockProgram.layout
+ BlockSchedule.Templates.execute CursorNetwork.cursorState CursorBounds.wordBits
+ selectedDesc ordinalJobCost
+
+/-- Replace the typed role table's common frame by the twelve words
+actually initialized in the current private burst. -/
+theorem VirtualPairs.rowsAt_of_layout {calendar reference : Memory w₀} (m : Memory w₀)
+ {bits : Fin (Y₀).totalWidth → Bool} {tab : Fin (L₀).shape.tables}
+ (pack : VertexPacked (group) (L₀) B.recordLimit (tags) (width))
+ (entry : TerminalProgram.VertexEntry B f ok (T₀) le_rfl (X₀) z (L₀) tab baseBits laneBits
+ pub calendar reference bits)
+ (later : LinkedVertexMemory (group) reference ord m)
+ (length : (pub 6).val = n) (count : (pub 9).val = labels)
+ (domain : BurstRAM.Word w₀ → DFS.Scratch w₀ n → Prop)
+ (handlers : NodeDispatch.Role → DFS.HookParser w₀ n)
+ (rows : let data := NativeFrame.leafWords (slotDegree S) pub hdr (offset) m
+ let fmt := SelectedPacketFormat B f ok (T₀) le_rfl (X₀) z (base)
+ let desc := selectedDesc B f ok (T₀) le_rfl (X₀) z (base)
+ let valid := Budgeted (W := w₀) (endAddr := n) (area).arguments fmt
+ (VertexFrameData (area) data (offset) (vals₀)) desc
+ (privateHistogram order.symm (area).histBase) (n ^ 9000) (n * n ^ 9000)
+ SelectedChecks B f ok (T₀) le_rfl (X₀) z (base) (placement₀) (M₀) m
+ ((NativeFrame.frameBase (area) : ℕ) : BurstRAM.Word w₀) (offset) (area).histBase order.symm
+ sites valid domain handlers (ordinalJobCost n power scan)) :
+ V.SelectedRowsAt adv ξ i μ order f ok sites z m power scan := by
+ obtain ⟨geometry, role, _⟩ := entry.role_layout B f ok (T₀) le_rfl (X₀) z (group) n labels
+ baseBits laneBits ord m pack later length count
+ unfold VirtualPairs.SelectedRowsAt
+ rw [geometry, role, length]
+ exact ⟨domain, handlers, rows⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualShrinkCapacity.lean b/lean/OAI/Computability/VPVNP/PairVirtualShrinkCapacity.lean
new file mode 100644
index 0000000000..75843cec4f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualShrinkCapacity.lean
@@ -0,0 +1,211 @@
+import OAI.Computability.VPVNP.PairVirtualShrinkRowBounds
+import OAI.Computability.VPVNP.PairVirtualShrinkHiddenSpace
+import OAI.Computability.VPVNP.PairShrinkSelectedOccurrence
+import OAI.Computability.VPVNP.PairShrinkCanonicalWorkspaceFit
+import OAI.Computability.VPVNP.PairShrinkRoleHiddenCapacity
+import OAI.Computability.VPVNP.PairShrinkPackedPackets
+import OAI.Computability.VPVNP.PairSimulationMapConstants
+
+/-!
+# Capacity of a physical shrinking site in the virtual pair
+
+The popped row determines a chronological shrinking occurrence, its
+selected terms and its packed output site. The word bound applies to the
+actual terminal workspace, old and new row bases, and private map reserve.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression CompressorRecords
+open DescriptorSpace CursorBounds CursorNetwork Filter LocalHistory
+open TraversalRows TraversalRoles ShrinkRoleDirectory
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K}
+variable (D : FixedProgramDiagonal.Program) (B : S.Templates) (u : PairExponents B.growthConstant)
+
+namespace VirtualShrink
+
+variable {A : Type*} [CommRing A] {f : B.Entry → A} {ok : B.IsSolution f}
+ {passes : List (SelectedLevel B f ok)} (x : ShrinkSite passes)
+ {w : ℕ} (workspace : Word w) (positions blocks n firstRow rowWords : ℕ) (tags : List TaggedLayer)
+local notation "o" => ShrinkSite.occurrence x
+local notation "cur" => Fin.val (Sigma.fst (Subtype.val x))
+local notation "rowEnd" => firstRow + rowWords
+local notation "area" =>
+ TerminalLayout.privateRegions (slotDegree S) n (rowEnd) (Fintype.card B.Entry)
+local notation "lim" =>
+ ShrinkCallABI.hiddenBase area n + ShrinkCallCapacity.extent (positions * slotDegree S) n
+local notation "oldBase" => layerBase B.recordLimit firstRow tags cur
+local notation "newBase" => layerBase B.recordLimit firstRow tags (cur + 1)
+
+open Classical in
+/-- The actual map, hidden read and child packet capacities of a decoded
+shrinking site. All three use the same private area and published rows. -/
+structure MapsAt : Prop where
+ fit : ∀ m : (o).state.packingData.Motif,
+ ShrinkRole.canonicalFits B (o).i (o).state (o).selection (w := w)
+ (Fintype.card B.Entry) n rowEnd oldBase lim m
+ hidden : ∀ mem : Memory w, CompiledResident.ShrinkPayload B workspace positions blocks n cur
+ (o).i (o).state (o).selection mem →
+ ShrinkRole.PackedHidden.Facts B (o).i (o).state (o).selection workspace positions blocks
+ cur n area (o).site mem
+ packets : ∀ (m : (o).state.packingData.Motif) (party : Fin 6)
+ (sp : ShrinkResidentSources.Bounds B (o).i (o).state workspace positions blocks cur)
+ (old : ShrinkCallDemandCells.Old (o).state
+ (ShrinkSlots.selectedLayout (o).state B.shrink (o).selection) m party)
+ (parent : (o).nextState.network.Half ((o).state.packingData.shrinkPartySite
+ (ShrinkSlots.selectedLayout (o).state B.shrink (o).selection) m party)),
+ let J := ShrinkCanonicalJob.job B (o).i (o).state (S.shrink (o).i) (o).selection m party
+ workspace positions blocks cur sp n rowEnd oldBase newBase old parent
+ ShrinkCanonicalJob.PacketSpace B (o).i (o).state (o).selection m party J n lim
+ width : MapConstants.widthThreshold B.shrink ≤ w
+
+/-- The row length is the size of the actually selected tagged layers. -/
+abbrev Maps := MapsAt B x workspace positions blocks n firstRow (tagWords B.recordLimit tags) tags
+
+end VirtualShrink
+
+attribute [local irreducible] BlockSchedule.Templates.execute BlockProgram.layout
+ CursorNetwork.cursorState ShrinkRoleDirectory.occurrence ShrinkCanonicalJob.job
+ TraversalRoles.layerBase ShrinkCallCapacity.extent
+
+set_option maxHeartbeats 1200000 in
+-- The packet and hidden-row types depend on the state decoded at the selected site.
+/-- A single threshold supplies the private map and packet bounds for all
+coefficient specializations, executions and decoded shrinking rows of the
+actual virtual scan. -/
+theorem eventually_virtualShrinkMaps (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clock : 44 ≤ n ^ 10000) (A : Type) [CommRing A]
+ (f : B.Entry → A) (ok : B.IsSolution f),
+ let G := D.executionGroup n ht clock
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ let workspace := terminalOperands G 2
+ let L := BlockProgram.layout B workspace.val X.positions T
+ ∀ (z : (B.execute f ok T le_rfl X).Choices)
+ (x : ShrinkSite (executeLevels B f ok T le_rfl X z)),
+ VirtualShrink.Maps B x workspace X.positions T n (endAddress L)
+ (selected B f ok T le_rfl X z) := by
+ classical
+ let start n := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ have poly : PolynomiallyBounded start := by
+ have eqn : start = fun n => (LiveProgram.Layout.pairWorkspace D.constants).eval
+ (paperGeometry D.addressFactor (liveCapacity u) n) := by
+ funext n
+ exact congrArg (PublicExpr.eval · (LiveProgram.Layout.pairWorkspace D.constants))
+ (paperGeometry_eq D B u hnum hden n)
+ rw [eqn]
+ exact CompressedPair.startup_workspace_polynomial _ D.address_pos (liveCapacity_polynomial u)
+ filter_upwards [ShrinkCallCapacity.eventually_packed_occurrence B u D.addressFactor haddr poly,
+ ShrinkRole.PackedHidden.eventually_hidden B u D.addressFactor haddr poly,
+ ShrinkCanonicalJob.eventually_packets B u D.addressFactor haddr poly,
+ MapConstants.eventually_width B.shrink D.addressFactor D.address_pos,
+ CompressedPair.eventually_startup_inputs D.constants D.address_pos (liveCapacity_polynomial u)]
+ with n fits hidden packets width inputs
+ intro hn V ht clock A _ f ok G X T workspace L
+ dsimp only [L,X]
+ rw [V.scanState_pairInput]
+ let labels := laneLabels _ _ V.lanes
+ let initial := pairInput S labels V.dimension
+ let count := initialPositions D.addressFactor n
+ have pos : initial.positions = count := pairInput_positions S labels V.dimension
+ have portsRead := inputs (CounterPublic.actualPrefix D.literal)
+ rw [← paperGeometry_eq D B u hnum hden n] at portsRead
+ have startEq : workspace.val = start n := portsRead.1
+ let firstRow := endAddress (BlockProgram.layout B (start n) count T)
+ change ∀ (z : (B.execute f ok T le_rfl initial).Choices)
+ (x : ShrinkSite (executeLevels B f ok T le_rfl initial z)),
+ VirtualShrink.Maps B x workspace initial.positions T n
+ (endAddress (BlockProgram.layout B workspace.val initial.positions T))
+ (selected B f ok T le_rfl initial z)
+ rw [pos, startEq]
+ intro z x
+ let tags := selected B f ok T le_rfl initial z
+ let o := x.occurrence
+ let j := x.val.1
+ have occ := o.selected
+ have sizes : tagWords B.recordLimit tags =
+ words B.recordLimit (selectedLayers B f ok T le_rfl initial z) :=
+ congrArg (words B.recordLimit) (selected_layers B f ok T le_rfl initial z)
+ let layers := selectedLayers B f ok T le_rfl initial z
+ let region := NativeFrame.regions (slotDegree S) n firstRow (words B.recordLimit layers)
+ (Fintype.card B.Entry)
+ let limit := ShrinkCallCapacity.mapBase region (Fintype.card LeafStartup.ScalarPort) n +
+ ShrinkCallCapacity.extent (count * slotDegree S) n
+ change VirtualShrink.MapsAt B x workspace count T n firstRow (tagWords B.recordLimit tags) tags
+ apply (congrArg
+ (fun size => VirtualShrink.MapsAt B x workspace count T n firstRow size tags) sizes).mpr
+ refine ⟨?_, ?_, ?_, width⟩
+ · intro m
+ have cap := fits labels V.dimension le_rfl A f ok z j o.i o.state o.selection _ occ m
+ have converted := ShrinkRole.canonicalFits_of_selected B o.i o.state o.selection
+ (b := D.addressFactor) (n := n) (firstRow := firstRow)
+ (rowWords := words B.recordLimit layers)
+ (older := layerBase B.recordLimit firstRow tags j.val) (limit := limit) m cap
+ exact converted
+ · intro mem payload
+ have cap := hidden labels V.dimension le_rfl A f ok z j o.i o.state o.selection _ occ
+ workspace mem payload o.site
+ exact cap
+ · intro m party sp old parent
+ have cap := packets labels V.dimension le_rfl A f ok z j o.i o.state o.selection _ occ m party
+ workspace sp old parent startEq
+ exact cap
+
+namespace VirtualShrink
+
+variable {A : Type} [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f)
+ (G : PairStages.Group) (n T : ℕ) {lanes : ℕ} (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f ok T hT X).Choices)
+ (x : ShrinkSite (executeLevels B f ok T hT X z))
+
+local notation "tags" => selected B f ok T hT X z
+local notation "workspace" => terminalOperands G 2
+local notation "lay" => BlockProgram.layout B (Fin.val workspace) X.positions T
+local notation "rowEnd" => endAddress lay + tagWords B.recordLimit tags
+
+/-- The maps, packets, hidden widths and row addresses of the same selected
+site in the physical execution. -/
+structure Capacity : Prop where
+ maps : Maps B x workspace X.positions T n (endAddress lay) tags
+ hiddenSpace : HiddenSpace B x n G.w (rowEnd)
+ rows : ShrinkRole.OccurrenceRowBounds B f ok G n T hT X z x
+
+end VirtualShrink
+
+/-- The physical shrinking-site bounds hold at one threshold chosen before
+the coefficient assignment, all term selections and the popped site. -/
+theorem eventually_virtualShrinkCapacity (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clock : 44 ≤ n ^ 10000) (A : Type) [CommRing A]
+ (f : B.Entry → A) (ok : B.IsSolution f),
+ let G := D.executionGroup n ht clock
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ ∀ (z : (B.execute f ok T le_rfl X).Choices)
+ (x : ShrinkSite (executeLevels B f ok T le_rfl X z)),
+ VirtualShrink.Capacity B f ok G n T le_rfl X z x := by
+ filter_upwards [eventually_virtualShrinkMaps D B u haddr hnum hden,
+ eventually_virtualShrinkHiddenSpace D B u haddr hnum hden,
+ eventually_virtualShrinkRowBounds D B u haddr hnum hden] with n maps hidden rows
+ intro hn V ht clock A _ f ok G X T z x
+ exact ⟨maps hn V ht clock A f ok z x, hidden hn V ht clock A f ok z x,
+ rows hn V ht clock A f ok z x⟩
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualShrinkHiddenSpace.lean b/lean/OAI/Computability/VPVNP/PairVirtualShrinkHiddenSpace.lean
new file mode 100644
index 0000000000..2d70346457
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualShrinkHiddenSpace.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.PairVirtualRootBudget
+import OAI.Computability.VPVNP.PairShrinkSelectedOccurrence
+import OAI.Computability.VPVNP.PairShrinkPackedCapacity
+import OAI.Computability.VPVNP.PairShrinkPreparedCall
+import OAI.Computability.VPVNP.PairShrinkCallABI
+
+/-! # Private hidden-field capacity at a decoded shrinking site of the virtual pair -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression CompressorRecords
+open DescriptorSpace CursorBounds CursorNetwork Filter LocalHistory TraversalRows TraversalRoles
+open ShrinkRoleDirectory ShrinkCallCapacity Compression.ShrinkMotif
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K}
+ (D : FixedProgramDiagonal.Program) (B : S.Templates) (u : PairExponents B.growthConstant)
+
+namespace VirtualShrink
+
+variable {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f}
+ {passes : List (SelectedLevel B f hf)} (x : ShrinkSite passes)
+local notation "o" => ShrinkSite.occurrence x
+
+open Classical in
+/-- Each hidden field fits one square slot, and the slots for all hidden identifiers
+of the selected input fit in the private region following the leaf stacks. -/
+structure HiddenSpace (n w rowEnd : ℕ) : Prop where
+ width : ∀ motif t, ShrinkPreparedCall.width B.shrink (o).state (o).selection motif
+ (!ShrinkSlots.selectedLayout (o).state B.shrink (o).selection, t) ≤ n ^ 2
+ capacity : ShrinkCallABI.hiddenBase
+ (TerminalLayout.privateRegions (slotDegree S) n rowEnd (Fintype.card B.Entry)) n +
+ (ShrinkHistoryRows.hiddenOrder (o).state).length * n ^ 2 ≤ 2 ^ w
+
+end VirtualShrink
+
+attribute [local irreducible] BlockSchedule.Templates.execute BlockProgram.layout
+ CursorNetwork.cursorState
+
+set_option maxHeartbeats 1500000 in
+-- The selected pass carries the dependent state, motif and directory indices.
+/-- A single length threshold covers all shrinking occurrences of all virtual scans,
+using the row end of the actual selected branch. -/
+theorem eventually_virtualShrinkHiddenSpace (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clock : 44 ≤ n ^ 10000)
+ (A : Type) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let G := D.executionGroup n ht clock
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ let L := BlockProgram.layout B (terminalOperands G 2).val X.positions T
+ ∀ (z : (B.execute f hf T le_rfl X).Choices)
+ (x : ShrinkSite (executeLevels B f hf T le_rfl X z)),
+ VirtualShrink.HiddenSpace B x n G.w (endAddress L +
+ tagWords B.recordLimit (selected B f hf T le_rfl X z)) := by
+ classical
+ let start n := (LiveProgram.Layout.pairWorkspace D.constants).eval (D.geometry n)
+ have poly : PolynomiallyBounded start := by
+ have eqn : start = fun n => (LiveProgram.Layout.pairWorkspace D.constants).eval
+ (paperGeometry D.addressFactor (liveCapacity u) n) := by
+ funext n
+ exact congrArg (PublicExpr.eval · (LiveProgram.Layout.pairWorkspace D.constants))
+ (paperGeometry_eq D B u hnum hden n)
+ rw [eqn]
+ exact CompressedPair.startup_workspace_polynomial _ D.address_pos (liveCapacity_polynomial u)
+ filter_upwards [eventually_packed_handoff B u D.addressFactor haddr poly,
+ eventually_levels B u D.addressFactor haddr (fieldFactor B.shrink),
+ CompressedPair.eventually_startup_inputs D.constants D.address_pos (liveCapacity_polynomial u)]
+ with n handoff levels inputs
+ intro hn V ht clock A _ f hf G X T L
+ dsimp only [L, X]
+ rw [V.scanState_pairInput]
+ let labels := laneLabels _ _ V.lanes
+ let initial := pairInput S labels V.dimension
+ let P := initialPositions D.addressFactor n
+ have pos : initial.positions = P := pairInput_positions S labels V.dimension
+ have ports := inputs (CounterPublic.actualPrefix D.literal)
+ rw [← paperGeometry_eq D B u hnum hden n] at ports
+ have startEq : (terminalOperands G 2).val = start n := ports.1
+ let firstRow := endAddress (BlockProgram.layout B (start n) P T)
+ change ∀ (z : (B.execute f hf T le_rfl initial).Choices)
+ (x : ShrinkSite (executeLevels B f hf T le_rfl initial z)), VirtualShrink.HiddenSpace B x n G.w
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val initial.positions T) +
+ tagWords B.recordLimit (selected B f hf T le_rfl initial z))
+ rw [pos, startEq]
+ intro z x
+ let vs := executeLevels B f hf T le_rfl initial z
+ let j := x.val.1
+ let o := x.occurrence
+ obtain ⟨positions, wide⟩ :=
+ levels labels V.dimension le_rfl A f hf z vs[j] (List.getElem_mem j.isLt)
+ change vs[j].input.positions ≤ P at positions
+ change fieldFactor B.shrink * (vs[j].input.maxWireWidth + 1) ≤ n at wide
+ have selectedAt : vs[j] =
+ ShrinkRoleDirectory.shrinkLevel o.i o.state o.selection vs[j].selector :=
+ o.selected
+ rw [selectedAt] at positions wide
+ have degree := vs[j].oldDegree_le
+ rw [selectedAt] at degree
+ have count := motif_count o.state positions degree
+ constructor
+ · intro motif t
+ have field := o.state.packingData.shrinkTerm_bounds (State.two_le_packingColors _)
+ (Nat.two_pow_pos _) o.state.shrinkNumber o.state.packingWidth
+ (fun _ => o.state.width_le_maxWireWidth _) B.shrink motif (o.selection motif)
+ rw [pow_two]
+ exact ((field.2 _).2.trans wide).trans (Nat.le_mul_of_pos_right _ (by omega))
+ · let tags := selected B f hf T le_rfl initial z
+ have sizes : tagWords B.recordLimit tags =
+ words B.recordLimit (selectedLayers B f hf T le_rfl initial z) :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T le_rfl initial z)
+ change ShrinkCallABI.hiddenBase (TerminalLayout.privateRegions (slotDegree S) n
+ (firstRow + tagWords B.recordLimit tags) (Fintype.card B.Entry)) n +
+ (ShrinkHistoryRows.hiddenOrder o.state).length * n ^ 2 ≤ 2 ^ (wordBits D.addressFactor n)
+ rw [sizes]
+ have bound := (handoff labels V.dimension le_rfl A f hf z).1
+ have occupied : (ShrinkHistoryRows.hiddenOrder o.state).length * n ^ 2 ≤
+ 4 * (P * slotDegree S) * n ^ 2 := by
+ change (ShrinkTermInputs.motifCount o.state * 4) * n ^ 2 ≤ _
+ rw [Nat.mul_comm (ShrinkTermInputs.motifCount o.state) 4]
+ exact Nat.mul_le_mul_right _ (Nat.mul_le_mul_left 4 count)
+ apply le_trans (Nat.add_le_add_left (occupied.trans ?_) _) bound.le
+ change 4 * (P * slotDegree S) * n ^ 2 ≤ extent (P * slotDegree S) n
+ unfold extent
+ omega
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualShrinkLevelChecks.lean b/lean/OAI/Computability/VPVNP/PairVirtualShrinkLevelChecks.lean
new file mode 100644
index 0000000000..a4ce7615d8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualShrinkLevelChecks.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.PairVirtualShrinkPhysics
+import OAI.Computability.VPVNP.PairVirtualShrinkPhysicalCost
+import OAI.Computability.VPVNP.PairShrinkSelectedFootprint
+import OAI.Computability.VPVNP.PairShrinkRoleCanonicalLevelChecks
+import OAI.Computability.VPVNP.PairSelectedShrinkRows
+
+/-!
+# Shrinking level checks for the physical site readers of a virtual pair
+
+The directory used by the installed shrinking hook selects the same site
+bank as the level-check proof. The chronological occurrence identifies the
+child order, histogram increment, protected-memory reads and clock charge
+of each accepted row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.VirtualShrink
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary Compression CompressorRecords
+open DescriptorSpace DFS TerminalProgram TraversalRows TraversalRoles VertexImage NodeArguments
+open LocalHistory TreeDecode ShrinkRole
+open scoped Fin.CommRing
+
+variable {k A : Type} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) (G : PairStages.Group)
+ (n p q : ℕ) (order : B.Entry ≃ Fin (Fintype.card B.Entry)) {lanes : ℕ} (T : ℕ)
+ (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) (m : Memory G.w)
+
+attribute [local irreducible] BlockProgram.layout BlockSchedule.Templates.execute executeLevels
+ StateExecution.finalState VertexImage.template VertexImage.placement
+ ShrinkRoleDirectory.occurrence selectedDesc canonicalParent physicalSiteBank
+
+set_option quotPrecheck false
+local notation "pub" => terminalOperands G
+local notation "L" => BlockProgram.layout B (pub 2).val X.positions T
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "rows" => selectedLayers B f hf T hT X z
+local notation "sites" => ShrinkRoleDirectory.ShrinkSite passes
+local notation "first" => (⟨leafLayer (siteOrder X), .cursor⟩ : TaggedLayer)
+local notation "base" => endAddress L
+local notation "size" => tagWords B.recordLimit tags
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "width" => State.totalWidth Y
+local notation "offset" => ((size+width : ℕ) : Word G.w)
+local notation "area" => TerminalLayout.privateRegions (slotDegree S) n (base+size)
+ (Fintype.card B.Entry)
+local notation "tableArea" => TerminalLayout.privateRegions (slotDegree S) n
+ (base+words B.recordLimit rows) (Fintype.card B.Entry)
+local notation "hdr" => vertexHeader G
+local notation "data" => NativeFrame.leafWords (slotDegree S) pub hdr offset m
+local notation "image" => nativeSegments B G.constants p q order
+local notation "place" => placement image
+local notation "host" => PrivateRAM.Template.instantiate (template image) G.w pub
+local notation "hist" => privateHistogram (W := G.w) (endAddr := n) order.symm (area).histBase
+local notation "typed" vals => Budgeted (W := G.w) (endAddr := n) (area).arguments
+ (SelectedPacketFormat B f hf T hT X z base) (VertexFrameData area data offset vals)
+ (selectedDesc B f hf T hT X z base) hist (n^9000) (n*n^9000)
+local notation "earlier" j => layerBase B.recordLimit base tags j
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ {baseBits laneBits ord limit : ℕ} {calendar reference : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n)
+ (executeLevels B f hf T hT X z) calendar)
+ (entry : TerminalProgram.VertexEntry (w := G.w) B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+ (packed : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ord m)
+ (wide : MapConstants.widthThreshold B.shrink ≤ G.w)
+
+variable (fits : ∀ x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z),
+ ∀ m, canonicalFits B x.occurrence.i x.occurrence.state x.occurrence.selection (w := G.w)
+ (Fintype.card B.Entry) n
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T) +
+ words B.recordLimit (selectedLayers B f hf T hT X z))
+ (layerBase B.recordLimit
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T))
+ (TraversalRoles.selected B f hf T hT X z) x.val.1.val) limit m)
+local notation "bank" => physicalSiteBank (G := G) (n := n) (T := T)
+ B f hf hT X z history entry packed frame wide fits
+local notation "shrinkHook" => ShrinkRoleDirectory.parser B.recordLimit base first passes
+ (fun x => canonicalParent (bank x) order f hf)
+
+set_option maxHeartbeats 2400000 in
+-- The physical and chronological packet formats have dependent site and half types.
+/-- Every shrinking index in the selected physical bank meets the terminal contract
+for every saved static frame and every choice of leaf and refresh handlers. -/
+theorem levelChecks_at (phy : Physics B f hf G n order T hT X z m)
+ (info : ∀ x : sites, CanonicalSiteData (bank x) host f hf T hT X z x.val.1
+ (RoleDomains.siteId B f hf T hT X z x) base)
+ (maps : ∀ (x : sites) parent, CanonicalMapData (bank x) hdr parent)
+ (vals : LeafSourceLoad.Static 34 → Word G.w)
+ (native : (shrinkHook).ExactOn
+ (RoleDomains.Domain X B.recordLimit base passes area data offset vals hist
+ (n^9000) (n*n^9000) .shrink)
+ host ((place).entry .shrink) ((place).dfsPC 3) (place).dfs m)
+ (leaf refresh : HookParser G.w n) (i : Fin (passes).length)
+ (shrinking : tagLevel B f hf (passes)[i] = .shrink) :
+ LevelChecks B f hf (dispatcher (RoleDomains.handlers leaf shrinkHook refresh) m offset)
+ (typed vals) hist
+ (JobGuard place host m (TerminalLink.workerCell hdr)
+ (ordinalJobCost n 1 (RatedRoles.scan B order)))
+ B.recordLimit (earlier i.val) (passes)[i] := by
+ have region : tableArea = area := congrArg
+ (fun count => TerminalLayout.privateRegions (slotDegree S) n (base + count)
+ (Fintype.card B.Entry))
+ phy.rowEq.symm
+ have checked := canonicalLevelChecks (w := G.w) (n := n) B f hf T hT X z base i shrinking
+ place host m (size+width) data vals order
+ (n^9000) (n*n^9000) 1 (RatedRoles.scan B order) bank
+ (RoleDomains.handlers leaf shrinkHook refresh) rfl
+ (template_contains image pub) phy.published phy.codes phy.tagEnd phy.headerFit
+ le_rfl le_rfl (by rw [region]; exact phy.histFit) le_rfl phy.budget.width
+ phy.budget.credit (by rw [region]; exact native)
+ (fun _ => by unfold physicalSiteBank; rfl) (fun _ => by unfold physicalSiteBank; rfl) info maps
+ (phy.budget.label_count f hf hT z i shrinking) (fun x s tape tail job hit => by
+ have guard := physicalSiteBank_rowTrace (G := G) (n := n) (T := T)
+ B f hf hT X z history entry packed frame wide fits x order s tape job tail hit
+ have cost := physical_rates (G := G) (n := n) (T := T)
+ B f hf hT X z order phy.budget history entry packed frame wide fits x
+ (ShrinkRoleDirectory.address B.recordLimit base first passes x.val : Word G.w)
+ s tape tail job hit
+ exact ⟨guard.1, guard.2, cost⟩)
+ have headerEq : TerminalLink.header (host).publicData = hdr := rfl
+ simpa only [region, headerEq, List.get_eq_getElem, Fin.getElem_fin] using checked
+
+end PairSimulation.VirtualShrink
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualShrinkPhysicalCost.lean b/lean/OAI/Computability/VPVNP/PairVirtualShrinkPhysicalCost.lean
new file mode 100644
index 0000000000..fb6859b5c7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualShrinkPhysicalCost.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.PairVirtualShrinkRowCost
+import OAI.Computability.VPVNP.PairShrinkPhysicalSiteBank
+import OAI.Computability.VPVNP.PairShrinkHookActionRates
+
+/-!
+# The native probe and instruction charges at a shrinking occurrence
+
+The level locator, old wires and child order are those of the history
+published for this vertex. The raw row includes room for the dispatch
+probe and its nine instructions. The dispatched job satisfies the single
+rate used by the complete terminal reader.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression CompressorRecords DescriptorSpace DFS LocalHistory
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TraversalRows TraversalRoles
+open VertexImage
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ {lanes T : ℕ} (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) {G : Group} {n limit : ℕ}
+ (order : B.Entry ≃ Fin (Fintype.card B.Entry)) (budget : RowBudget B order X n G.w T)
+
+set_option quotPrecheck false
+local notation "pub" => terminalOperands G
+local notation "L" => BlockProgram.layout B (pub 2).val X.positions T
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+local notation "Y" => StateExecution.finalState (B.execute f hf T hT X) z
+local notation "rowEnd" => endAddress L+words B.recordLimit (selectedLayers B f hf T hT X z)
+local notation "earlier" j => layerBase B.recordLimit (endAddress L) tags j
+local notation "sites" => ShrinkRoleDirectory.ShrinkSite passes
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ {baseBits laneBits ord : ℕ} {calendar reference m : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n)
+ (executeLevels B f hf T hT X z) calendar)
+ (entry : TerminalProgram.VertexEntry (w := G.w) B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+ (pack : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ord m)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+
+variable (fits : ∀ x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z),
+ ∀ m, canonicalFits B x.occurrence.i x.occurrence.state x.occurrence.selection (w := G.w)
+ (Fintype.card B.Entry) n
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T) +
+ words B.recordLimit (selectedLayers B f hf T hT X z))
+ (layerBase B.recordLimit
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T))
+ (TraversalRoles.selected B f hf T hT X z) x.val.1.val) limit m)
+variable (x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z))
+local notation "physical" => physicalSiteBank B f hf hT X z history entry pack frame width fits x
+
+attribute [local irreducible] executeLevels ShrinkRoleDirectory.occurrence canonicalParent
+ BlockProgram.layout BlockSchedule.Templates.execute StateExecution.finalState
+include budget in
+theorem physical_rates (node : Word G.w) (s : Scratch G.w n) (bs tail : List Bool)
+ (body : VisitPath G.w n)
+ (hit : (canonicalParent physical order f hf).read node s bs = some (body, tail)) :
+ countProbes body.trace + 1 ≤ RatedRoles.scan B order * (n.log2 + 1)^1 ∧
+ body.trace.length + 9 ≤ n^43 := by
+ have wire := budget.old_width f hf hT z x.val.1
+ have eqn := congrArg (fun v : SelectedLevel B f hf => v.input.maxWireWidth) x.occurrence.selected
+ have typed : x.occurrence.state.maxWireWidth ≤ n := eqn.symm.le.trans wire
+ obtain ⟨probes, ticks⟩ := canonicalParent_rates physical order f hf node rfl s bs tail body
+ budget.rate (budget.later f hf hT z x.val.1) typed hit
+ rw [pow_one]
+ exact ⟨probes.trans (Nat.mul_le_mul_right _ (RatedRoles.role_le B order .shrink)), ticks⟩
+
+include budget in
+theorem physical_ordinal_cost (offset node : Word G.w) (s : Scratch G.w n) (bs tail : List Bool)
+ (body : VisitPath G.w n)
+ (hit : (canonicalParent physical order f hf).read node s bs = some (body, tail)) :
+ ordinalJobCost n 1 (RatedRoles.scan B order) (dispatchJob m offset node s body) := by
+ have h := physical_rates B f hf hT X z order budget history entry pack frame width fits x
+ node s bs tail body hit
+ exact ShrinkNodeCost.dispatched_ordinal_cost m offset node s body
+ (by simpa only [pow_one] using h.1) h.2
+
+end PairSimulation.ShrinkRole
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualShrinkPhysics.lean b/lean/OAI/Computability/VPVNP/PairVirtualShrinkPhysics.lean
new file mode 100644
index 0000000000..24563e11d4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualShrinkPhysics.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PairVirtualShrinkRowCost
+import OAI.Computability.VPVNP.PairVertexSelectedRoleLayout
+import OAI.Computability.VPVNP.PairSelectedPacketGeometry
+
+/-! # Addresses and public tags for shrinking in the linked vertex memory
+
+All site readers at one selected vertex see the same role image. Its tag
+offset is the selected row count plus the total final-wire width. The
+private buffers, histogram and node array use the corresponding packed
+terminal allocation, including after previous vertices have updated their
+counter words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VirtualShrink
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary Compression CompressorRecords
+open DescriptorSpace TerminalProgram TraversalRows TraversalRoles NodeArguments LocalHistory
+
+variable {k A : Type} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) (G : PairStages.Group)
+ (n : ℕ) {labels : ℕ} (order : B.Entry ≃ Fin labels) {lanes : ℕ} (T : ℕ)
+ (hT : T * S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+ (z : (B.execute f hf T hT X).Choices) (m : Memory G.w)
+
+local notation "pub" => terminalOperands G
+local notation "L" => BlockProgram.layout B (Fin.val (pub 2)) X.positions T
+local notation "tags" => selected B f hf T hT X z
+local notation "passes" => executeLevels B f hf T hT X z
+local notation "rows" => selectedLayers B f hf T hT X z
+local notation "base" => endAddress L
+local notation "size" => tagWords B.recordLimit tags
+local notation "width" => State.totalWidth (StateExecution.finalState (B.execute f hf T hT X) z)
+local notation "area" => TerminalLayout.privateRegions (slotDegree S) n (base+size) labels
+local notation "hdr" => vertexHeader G
+
+/-- The selected shrinking rows' budget, their published role words in linked memory,
+and the address bounds for the role table, vertex header, frames, histogram and nodes. -/
+structure Physics : Prop where
+ budget : ShrinkRole.RowBudget B order X n G.w T
+ rowEq : size = words B.recordLimit rows
+ published : Reads G.w m (size+width) B.recordLimit base tags
+ codes : 2 < 2^G.w
+ tagEnd : size+width+base+size ≤ (hdr).val
+ headerFit : (hdr).val+31 < 2^G.w
+ start : n ≤ (area).arguments.start
+ stride : frameStride (slotDegree S) n ≤ (area).arguments.stride
+ histFit : (area).histBase ≤ 2^G.w
+ nodes : base+words B.recordLimit rows ≤ (area).nodes
+ layerFit : layerBase B.recordLimit base tags ((passes).length+1) < 2^G.w
+
+theorem physics {baseBits laneBits ordinal : ℕ} {tab : Fin (L).shape.tables}
+ {calendar reference : Memory G.w} {bits : Fin width → Bool}
+ (budget : ShrinkRole.RowBudget B order X n G.w T)
+ (pack : VertexPacked G L B.recordLimit tags width)
+ (entry : VertexEntry B f hf T hT X z L tab baseBits laneBits pub calendar reference bits)
+ (later : LinkedVertexMemory G reference ordinal m)
+ (stack : (area).stackBase ≤ 2 ^ G.w) : Physics B f hf G n order T hT X z m := by
+ have rowEq : size = words B.recordLimit rows :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ have tagsAt : Reads G.w m (size+width) B.recordLimit base tags := by
+ apply pack.roleWords later
+ rw [rowEq]; exact entry.roles
+ have head := pack.room
+ have region := pack.arena
+ have hist : (area).histBase ≤ (area).stackBase :=
+ (Nat.le_add_right _ labels).trans ((Nat.le_add_right _ (n^5)).trans (Nat.le_add_right _ 38))
+ refine ⟨budget,rowEq,tagsAt,by omega,by omega,by omega,le_rfl,le_rfl,hist.trans stack,?_,?_⟩
+ · change base + words B.recordLimit rows ≤ base+size
+ rw [rowEq]
+ · rw [TreeDecode.selected_endBase,← rowEq]
+ have mod := (hdr).isLt
+ omega
+
+end PairSimulation.VirtualShrink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualShrinkRowBounds.lean b/lean/OAI/Computability/VPVNP/PairVirtualShrinkRowBounds.lean
new file mode 100644
index 0000000000..39250da2e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualShrinkRowBounds.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.PairVirtualRootBudget
+import OAI.Computability.VPVNP.PairShrinkAdjacentRows
+import OAI.Computability.VPVNP.PairShrinkSelectedOccurrence
+import OAI.Computability.VPVNP.PairShrinkOldHalfAddresses
+import OAI.Computability.VPVNP.PairShrinkCallCapacity
+
+/-! # Physical row bounds for every selected virtual shrinking site
+
+Each child lies in the occurrence's input layer and precedes its selected
+output row. The argument area and reload frame are the ones reserved by
+the terminal program for the complete chronological branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.ShrinkRole
+
+open Compression BurstRAM LiveProgram PairStages.Group.Auxiliary CompressorRecords DescriptorSpace
+open NodeArguments.ChildScan TraversalRows TraversalRoles PortRefresh.ArgumentAddress
+
+/-- Address and width bounds consumed by the native shrinking row handler. -/
+structure RowBounds {a g : ℕ} (Z : State a g) (regions : LeafArena.Regions)
+ (w n cap rowEnd endLayer older parent : ℕ) : Prop where
+ wire : Z.maxWireWidth ≤ n
+ frameRoom : NativeFrame.frameBase regions + 12 ≤ 2^w
+ above : n ≤ NativeFrame.frameBase regions
+ strideFit : cap + 2 < 2^w
+ fit : endLayer < 2^w
+ oldNodes : ∀ v, childNode Z older cap v < rowEnd
+ parentFit : parent < rowEnd
+ earlier : ∀ v, childNode Z older cap v < parent
+ abovePointer : ∀ v, n < regions.arguments.base (childNode Z older cap v)
+
+variable {k A : Type} [_root_.Field k] [CommRing A] {S : BlockSchedule k}
+variable (B : S.Templates) (f : B.Entry → A) (ok : B.IsSolution f) (G : PairStages.Group) (n T : ℕ)
+variable {lanes : ℕ} (hT : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes)
+variable (z : (B.execute f ok T hT X).Choices)
+variable (x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f ok T hT X z))
+local notation "vs" => executeLevels B f ok T hT X z
+local notation "tags" => selected B f ok T hT X z
+local notation "layers" => selectedLayers B f ok T hT X z
+local notation "layout" => BlockProgram.layout B (Fin.val (terminalOperands G 2)) X.positions T
+local notation "firstRow" => endAddress layout
+local notation "rowEnd" => firstRow + tagWords B.recordLimit tags
+local notation "area" => TerminalLayout.privateRegions (slotDegree S) n (rowEnd) (Fintype.card B.Entry)
+local notation "older" => layerBase B.recordLimit firstRow tags (Fin.val (Sigma.fst (Subtype.val x)))
+local notation "later" => layerBase B.recordLimit firstRow tags ((Fin.val (Sigma.fst (Subtype.val x)))+1)
+
+/-- Instantiate the row bounds at the input and output of the recovered occurrence. -/
+noncomputable abbrev OccurrenceRowBounds : Prop :=
+ let o := x.occurrence
+ RowBounds o.state area G.w n B.recordLimit (rowEnd)
+ (layerBase B.recordLimit firstRow tags ((vs).length+1)) (older)
+ ((later)+(B.recordLimit+2)*siteOrdinal o.nextState o.site)
+
+private theorem of_packed (pack : VertexPacked G layout B.recordLimit tags
+ ((B.execute f ok T hT X).finalState z).totalWidth)
+ (stack : (TerminalLayout.privateRegions (slotDegree S) n (firstRow+words B.recordLimit layers)
+ (Fintype.card B.Entry)).stackBase < 2^G.w) (wire : x.occurrence.state.maxWireWidth ≤ n) :
+ OccurrenceRowBounds B f ok G n T hT X z x := by
+ let o := x.occurrence
+ let p := (vs)[x.val.1]
+ have occ : p = TraversalRows.shrinkLevel B f ok o.i o.state o.selection p.selector := o.selected
+ have rowsEq : tagWords B.recordLimit tags = words B.recordLimit layers :=
+ congrArg (words B.recordLimit) (selected_layers B f ok T hT X z)
+ have stackFit : (area).stackBase < 2^G.w := by rw [rowsEq]; exact stack
+ have rowsFit : rowEnd < 2^G.w :=
+ (show rowEnd ≤ firstRow + 2*tagWords B.recordLimit tags +
+ ((B.execute f ok T hT X).finalState z).totalWidth by omega).trans_lt (pack.arena.trans_lt (vertexHeader G).isLt)
+ have one : 1 ≤ ((layers).map Layer.count).sum := by
+ rw [selected_layer_counts B f ok T hT X z,List.sum_cons]
+ exact (Nat.succ_le_of_lt X.positions_pos).trans (Nat.le_add_right ..)
+ have stride : B.recordLimit+2 ≤ tagWords B.recordLimit tags := by
+ rw [rowsEq, words]
+ simpa only [Nat.mul_one] using Nat.mul_le_mul_left (B.recordLimit+2) one
+ have tagLength : (tags).length = (vs).length+1 := by simp [selected]
+ have frame : NativeFrame.frameBase area ≤ (area).cacheBase := (area).hist_before
+ have cache : (area).cacheBase+12 ≤ (area).stackBase := Nat.add_le_add_left (by decide : 12 ≤ 38) _
+ refine ⟨wire, ((Nat.add_le_add_right frame 12).trans cache).trans stackFit.le, ?_,
+ (stride.trans (Nat.le_add_left ..)).trans_lt rowsFit, ?_, ?_, ?_, ?_, ?_⟩
+ · change n ≤ (n + (rowEnd)*(2*slotDegree S*n+1)) + Fintype.card B.Entry
+ exact (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+ · rw [← tagLength,layerBase,List.take_length]; exact rowsFit
+ · intro v
+ rw [ShrinkOldHalves.Physical.childNode_eq, rowsEq]
+ exact ShrinkPackedRows.packed_shrink_address B f ok T hT X z (terminalOperands G 2).val
+ x.val.1 o.i o.state o.selection p.selector occ v
+ · rw [rowsEq]
+ exact ShrinkPackedRows.packed_parent_address B f ok T hT X z (terminalOperands G 2).val
+ x.val.1 o.i o.state o.selection p.selector occ o.site
+ · intro v
+ rw [ShrinkOldHalves.Physical.childNode_eq]
+ exact ShrinkPackedRows.packed_child_before_parent B f ok T hT X z (terminalOperands G 2).val
+ x.val.1 o.i o.state o.selection p.selector occ v o.site
+ · intro v
+ apply TerminalLayout.geometryPointer_before_node layout
+ rw [ShrinkOldHalves.Physical.childNode_eq]
+ exact (Nat.le_add_right ..).trans (Nat.le_add_right ..)
+
+end PairSimulation.ShrinkRole
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression CompressorRecords
+open CursorNetwork CursorBounds DescriptorSpace Filter
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (D : FixedProgramDiagonal.Program)
+variable (B : S.Templates) (u : PairExponents B.growthConstant)
+
+attribute [local irreducible] BlockSchedule.Templates.execute BlockProgram.layout CursorNetwork.cursorState
+
+/-- One threshold works for all nominations, specializations and selected
+shrinking sites in the virtual pair's actual chronological execution. -/
+theorem eventually_virtualShrinkRowBounds (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2^(D.geometry n).w) (clock : 44 ≤ n^10000)
+ (A : Type) [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f),
+ let T := blockCount (u.θ : ℝ) n
+ let X := V.scanState
+ ∀ (z : (B.execute f ok T le_rfl X).Choices)
+ (x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f ok T le_rfl X z)),
+ ShrinkRole.OccurrenceRowBounds B f ok (D.executionGroup n ht clock) n T le_rfl X z x := by
+ filter_upwards [D.eventually_selectedRootBudget B u haddr hnum hden D.constants.circuitExponent,
+ ShrinkCallCapacity.eventually_levels B u D.addressFactor haddr 1] with n budget limits
+ intro hn V ht clock A _ f ok
+ have raw := budget hn V ht clock A f ok
+ dsimp only at raw ⊢
+ rw [V.scanState_pairInput] at raw ⊢
+ intro z x
+ obtain ⟨pack,_,stack⟩ := raw.2.2.2 z
+ apply ShrinkRole.of_packed _ _ _ _ _ _ _ _ _ _ pack stack
+ let passes := executeLevels B f ok _ le_rfl _ z
+ have width := (limits (laneLabels _ _ V.lanes) V.dimension le_rfl A f ok z
+ (passes[x.val.1]) (List.getElem_mem x.val.1.isLt)).2
+ rw [x.occurrence.selected, Nat.one_mul] at width
+ exact (Nat.le_succ _).trans width
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualShrinkRowCost.lean b/lean/OAI/Computability/VPVNP/PairVirtualShrinkRowCost.lean
new file mode 100644
index 0000000000..320d6b7e61
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualShrinkRowCost.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.LiveVirtualPairCursorBoundary
+import OAI.Computability.VPVNP.PairShrinkHookRates
+import OAI.Computability.VPVNP.PairShrinkSelectedExponentBound
+import OAI.Computability.VPVNP.PairVertexRatedRoles
+import OAI.Computability.VPVNP.PairVertexSelectedClock
+
+/-!
+# Resource bounds for shrinking rows of an actual virtual pair
+
+The input-length threshold comes before the virtual pair, coefficients
+and selected execution. Its wire-width envelope covers every input level.
+A shrinking row can add at most a quadratic number of copies of any one
+coefficient label. The complete histogram credit fits a machine word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace PairSimulation.ShrinkRole
+
+open BurstRAM Compression Compression.ShrinkMotif CompressorRecords LocalHistory VertexImage
+open TraversalRoles ShrinkNodeCost
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (B : S.Templates)
+ {labels : ℕ} (order : B.Entry ≃ Fin labels)
+ {lanes : ℕ} (X : State (S.degreeExponent 0) lanes)
+
+/-- Size and cost bounds for selected shrink rows of a virtual pair. They control the block
+count, wire widths, available word credit, traversal rates and the number of resident field
+copies. -/
+structure RowBudget (n w T : ℕ) : Prop where
+ positive : 1 ≤ n
+ blocks : T ≤ n.log2+1
+ width : B.growthConstant^T*(X.maxWireWidth+1) ≤ n
+ credit : n*n^9000 < 2^w
+ rate : RateRoom S (selectedHeaderLength B) (MapWitness.scanCoefficient B order)
+ (prologueCoefficient B) n
+ copies : ∀ j : Fin S.steps,
+ 2 * (MapResidentRows.capacity (S.degreeExponent j.castSucc) * fieldFactor B.shrink) ≤ n
+
+variable {B order X} {n w T : ℕ} (budget : RowBudget B order X n w T)
+variable {A : Type*} [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f)
+ (hT : T * S.laneBits ≤ lanes) (z : (B.execute f ok T hT X).Choices)
+local notation "passes" => executeLevels B f ok T hT X z
+local notation "reader" v => originReader B f ok (SelectedLevel.origin v) (SelectedLevel.term v)
+
+include budget
+
+theorem RowBudget.later (i : Fin (passes).length) :
+ (passes).length-(i.val+1) ≤ (S.steps+1)*(n.log2+1) :=
+ selected_later_le_log B f ok T hT X z budget.blocks i.val
+
+theorem RowBudget.old_width (i : Fin (passes).length) : (passes)[i].input.maxWireWidth ≤ n :=
+ ((executeLevels_limits B f ok T hT X z _ (List.getElem_mem i.isLt)).2).trans budget.width
+
+set_option exponentiation.threshold 10000 in
+theorem RowBudget.label_count (i : Fin (passes).length)
+ (shrinking : tagLevel B f ok (passes)[i] = .shrink) :
+ ∀ u b a k l, ((reader ((passes).get i)).witness u a b).exponents k l ≤ n^9000 := by
+ intro u b a k l
+ have count := selected_exponent_le_square B f ok T hT X z i shrinking budget.positive
+ budget.width budget.copies u b a k l
+ exact count.trans
+ (Nat.pow_le_pow_right budget.positive (by decide : 2 ≤ 9000))
+
+end PairSimulation.ShrinkRole
+
+namespace FixedProgramDiagonal.Program
+
+open Compression CursorNetwork CursorBounds LiveProgram PairSimulation PairSimulation.VertexImage
+open PairSimulation.ShrinkRole PairSimulation.ShrinkNodeCost Filter
+open private blocks_le_log from OAI.Computability.VPVNP.CompressorDirectoryBudget
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant) {labels : ℕ}
+ (order : B.Entry ≃ Fin labels)
+
+attribute [local irreducible] BlockSchedule.Templates.execute CursorNetwork.cursorState
+
+/-- The uniform shrinking allowance on the actual cursor input of each virtual pair. -/
+theorem eventually_virtualShrinkRowCost (hb : max S.laneBits 5 ≤ D.addressFactor) (C : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn C) (A : Type*) [CommRing A]
+ (f : B.Entry → A) (ok : B.IsSolution f)
+ (_z : (B.execute f ok (blockCount (u.θ : ℝ) n) le_rfl V.scanState).Choices),
+ RowBudget B order V.scanState n (D.geometry n).w (blockCount (u.θ : ℝ) n) := by
+ filter_upwards [eventually_pairBranchBounds B u D.addressFactor hb,
+ eventually_histogram_credit D.addressFactor D.address_pos,MapWitness.eventually_row_constants B,
+ eventually_job_rate_room S (selectedHeaderLength B) (MapWitness.scanCoefficient B order)
+ (prologueCoefficient B)]
+ with n branch credit copies rate
+ intro hn V A _ f ok
+ rw [V.scanState_pairInput]
+ intro z
+ have field := (branch.2.2 (laneLabels _ _ V.lanes) V.dimension le_rfl A f ok z).2.2.2.2.2.1
+ have size : (n : ℝ)^(3/10 : ℝ) ≤ n := by
+ simpa using Real.rpow_le_rpow_of_exponent_le (Nat.one_le_cast.mpr copies.1)
+ (by norm_num : (3/10 : ℝ) ≤ 1)
+ exact ⟨copies.1, blocks_le_log B u copies.1, Nat.cast_le (α := ℝ) |>.mp (field.trans size),
+ credit, rate, copies.2⟩
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualShrinkRows.lean b/lean/OAI/Computability/VPVNP/PairVirtualShrinkRows.lean
new file mode 100644
index 0000000000..d3be5dbd0b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualShrinkRows.lean
@@ -0,0 +1,177 @@
+import OAI.Computability.VPVNP.PairSelectedShrinkRows
+import OAI.Computability.VPVNP.PairVirtualShrinkPhysics
+import OAI.Computability.VPVNP.PairVirtualShrinkLevelChecks
+import OAI.Computability.VPVNP.PairVirtualShrinkSiteData
+import OAI.Computability.VPVNP.PairVirtualPhysicalMapData
+import OAI.Computability.VPVNP.PairVertexShrinkAtSite
+import OAI.Computability.VPVNP.PairVirtualRootBudget
+
+/-! # Native shrinking rows of the selected virtual pair
+
+The chronological shrinking occurrences determine one bank of physical
+readers. Each reader obtains its own selected terms, child directory and
+map rows from the actual stored history. The same bank accounts for every
+accepted path's monomial and every possible rejecting nomination tape,
+including calls made after earlier counter flushes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation
+open Compression CompressorRecords DescriptorSpace CursorNetwork CursorBounds Filter
+open TraversalRows TraversalRoles VertexImage LocalHistory NodeArguments TreeDecode
+open scoped Fin.CommRing
+
+variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (D : FixedProgramDiagonal.Program)
+ (B : S.Templates) (u : PairExponents B.growthConstant) {labels : ℕ}
+ (order : B.Entry ≃ Fin labels)
+
+attribute [local irreducible] VertexImage.placement VertexImage.template BlockProgram.layout
+ BlockSchedule.Templates.execute CursorNetwork.cursorState selectedDesc ordinalJobCost
+ ShrinkRoleDirectory.occurrence ShrinkRole.physicalSiteBank StateExecution.finalState executeLevels
+
+set_option maxHeartbeats 1200000 in
+-- The selected sites carry dependent parser and native program types indexed by the full branch.
+/-- The selected shrinking reader is native on every active chronological
+row, uniformly in the ring, compression solution and complete branch. -/
+theorem eventually_virtualShrinkChecks_of_public (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clock : 44 ≤ n ^ 10000)
+ (A : Type) [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f),
+ let G := D.executionGroup n ht clock
+ let ops := terminalOperands G
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f ok T le_rfl X
+ let L := BlockProgram.layout B (ops 2).val X.positions T
+ ∀ (z : E.Choices) {baseBits laneBits ord : ℕ} {tab : Fin L.shape.tables}
+ {calendar reference m : Memory G.w} {bits : Fin (E.finalState z).totalWidth → Bool},
+ (ops 6).val = n → (ops 9).val = labels →
+ TerminalProgram.VertexEntry B f ok T le_rfl X z L tab baseBits laneBits ops
+ calendar reference bits →
+ SelectedPayloadHistory.Past B f ok L
+ (CompiledResident.payload B f ok (ops 2) X.positions T n)
+ (executeLevels B f ok T le_rfl X z) calendar →
+ LinkedVertexMemory G reference ord m →
+ TerminalProgram.ShrinkRows B f ok G n D.numerator D.denominator order T le_rfl X z m := by
+ classical
+ have lab : labels = Fintype.card B.Entry :=
+ (Fintype.card_fin labels).symm.trans (Fintype.card_congr order.symm)
+ subst labels
+ filter_upwards [eventually_virtualShrinkCapacity D B u haddr hnum hden,
+ eventually_virtualShrinkRowCost D B u order haddr D.constants.circuitExponent,
+ eventually_selectedRootBudget D B u haddr hnum hden D.constants.circuitExponent,
+ MapConstants.eventually_width B.shrink D.addressFactor D.address_pos] with
+ n capacities costs roots word
+ intro hn V ht clock A _ f ok G ops X T E L z baseBits laneBits ord tab calendar reference m bits
+ length count entry history frame
+ let passes := executeLevels B f ok T le_rfl X z
+ let tags := TraversalRoles.selected B f ok T le_rfl X z
+ let base := endAddress L
+ let rows := selectedLayers B f ok T le_rfl X z
+ let rowEnd := base + words B.recordLimit rows
+ let region := TerminalLayout.privateRegions (slotDegree S) n rowEnd (Fintype.card B.Entry)
+ let limit := ShrinkCallABI.hiddenBase region n +
+ ShrinkCallCapacity.extent (X.positions * slotDegree S) n
+ let before (j : ℕ) := layerBase B.recordLimit base tags j
+ let host := (VertexImage.template (TerminalProgram.nativeSegments B D.constants D.numerator
+ D.denominator order)).instantiate G.w ops
+ have eqn : tagWords B.recordLimit tags = words B.recordLimit rows :=
+ congrArg (words B.recordLimit) (selected_layers B f ok T le_rfl X z)
+ obtain ⟨_, _, _, room⟩ := roots hn V ht clock A f ok
+ obtain ⟨pack, _, stack⟩ := room z
+ have budget := costs hn V A f ok z
+ have width : MapConstants.widthThreshold B.shrink ≤ G.w := word
+ have capacity := capacities hn V ht clock A f ok z
+ have fits (x : ShrinkRoleDirectory.ShrinkSite passes) (j : x.occurrence.state.packingData.Motif) :
+ ShrinkRole.canonicalFits B x.occurrence.i x.occurrence.state x.occurrence.selection
+ (w := G.w) (Fintype.card B.Entry) n rowEnd (before x.val.1.val) limit j := by
+ have got := (capacity x).maps.fit j
+ change ShrinkRole.canonicalFits B x.occurrence.i x.occurrence.state x.occurrence.selection
+ (w := G.w) (Fintype.card B.Entry) n (base + tagWords B.recordLimit tags) (before x.val.1.val)
+ (ShrinkCallABI.hiddenBase (TerminalLayout.privateRegions (slotDegree S) n
+ (base + tagWords B.recordLimit tags) (Fintype.card B.Entry)) n +
+ ShrinkCallCapacity.extent (X.positions * slotDegree S) n) j at got
+ rw [eqn] at got
+ exact got
+ let bank := ShrinkRole.physicalSiteBank B f ok le_rfl X z history entry pack frame width fits
+ have info (x : ShrinkRoleDirectory.ShrinkSite passes) :
+ ShrinkRole.CanonicalSiteData (bank x) host f ok T le_rfl X z x.val.1
+ (RoleDomains.siteId B f ok T le_rfl X z x) base := by
+ exact VirtualShrink.Capacity.siteData (G := G) (n := n) (T := T) (limit := limit) (phy := m)
+ B f ok le_rfl X z history entry pack frame width fits x
+ host rfl (capacity x)
+ have maps (x : ShrinkRoleDirectory.ShrinkSite passes)
+ (parent : x.occurrence.nextState.network.Half x.occurrence.site) :
+ ShrinkRole.CanonicalMapData (bank x) (vertexHeader G) parent :=
+ ShrinkRole.physicalSiteMapData_virtual (G := G) (n := n) (T := T) (phy := m)
+ B f ok le_rfl X z history entry pack frame width fits x
+ (capacity x).maps parent
+ have stackFit : (TerminalLayout.privateRegions (slotDegree S) n
+ (base + tagWords B.recordLimit tags) (Fintype.card B.Entry)).stackBase ≤ 2 ^ G.w := by
+ rw [eqn]
+ exact stack.le
+ have phy := PairSimulation.VirtualShrink.physics B f ok G n order T le_rfl X z m
+ budget pack entry frame stackFit
+ refine ⟨fun x => ShrinkRole.canonicalParent (bank x) order f ok, fun vals => ?_⟩
+ let hist := privateHistogram (W := G.w) (endAddr := n) order.symm
+ (TerminalLayout.privateRegions (slotDegree S) n (base + tagWords B.recordLimit tags)
+ (Fintype.card B.Entry)).histBase
+ have native := RoleDomains.nativeShrink_at_vertex (G := G) (n := n) (T := T) (limit := limit)
+ (phy := m) (vals := vals) (counts := hist) (nodeCap := n ^ 9000)
+ (wordLimit := n * n ^ 9000) B f ok le_rfl X z history entry pack frame width fits
+ D.numerator D.denominator order length count info maps
+ refine ⟨native, ?_⟩
+ intro leaf refresh i isShrink
+ exact PairSimulation.VirtualShrink.levelChecks_at (limit := limit) B f ok G n
+ D.numerator D.denominator order T le_rfl X z m history entry pack frame width fits
+ phy info maps vals native leaf refresh i isShrink
+
+/-- Every linked vertex call of a sufficiently large virtual pair uses the
+same native shrinking reader for both its path multiplicities and its resource
+checks, for all scalar assignments and selected branches at that length. -/
+theorem eventually_virtualShrinkChecks (hlabels : D.constants.motifLabels = Fintype.card B.Entry)
+ (haddr : max S.laneBits 5 ≤ D.addressFactor)
+ (hnum : D.numerator = (liveRatio u).num) (hden : D.denominator = (liveRatio u).den) :
+ ∀ᶠ n : ℕ in atTop, ∀ (hn : 2 ≤ n) (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ (ht : 21 ≤ 2 ^ (D.geometry n).w) (clock : 44 ≤ n ^ 10000)
+ (A : Type) [CommRing A] (f : B.Entry → A) (ok : B.IsSolution f),
+ let G := D.executionGroup n ht clock
+ let ops := terminalOperands G
+ let X := V.scanState
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f ok T le_rfl X
+ let L := BlockProgram.layout B (ops 2).val X.positions T
+ ∀ (z : E.Choices) {baseBits laneBits ord : ℕ} {tab : Fin L.shape.tables}
+ {calendar reference m : Memory G.w} {bits : Fin (E.finalState z).totalWidth → Bool},
+ TerminalProgram.VertexEntry B f ok T le_rfl X z L tab baseBits laneBits ops
+ calendar reference bits →
+ SelectedPayloadHistory.Past B f ok L
+ (CompiledResident.payload B f ok (ops 2) X.positions T n)
+ (executeLevels B f ok T le_rfl X z) calendar →
+ LinkedVertexMemory G reference ord m →
+ TerminalProgram.ShrinkRows B f ok G n D.numerator D.denominator order T le_rfl X z m := by
+ classical
+ have lab : D.constants.motifLabels = labels :=
+ hlabels.trans ((Fintype.card_congr order).trans (Fintype.card_fin labels))
+ filter_upwards [eventually_virtualShrinkChecks_of_public D B u order haddr hnum hden,
+ D.eventually_terminalOperandSizes lab] with n checks sizes
+ intro hn V ht clock A _ f ok G ops X T E L z b l j tab calendar reference m bits
+ entry history frame
+ have operandSizes := sizes ht clock
+ exact checks hn V ht clock A f ok z operandSizes.1 operandSizes.2 entry history frame
+
+end FixedProgramDiagonal.Program
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualShrinkSiteData.lean b/lean/OAI/Computability/VPVNP/PairVirtualShrinkSiteData.lean
new file mode 100644
index 0000000000..f031952f91
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualShrinkSiteData.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PairVirtualShrinkCapacity
+import OAI.Computability.VPVNP.PairShrinkPhysicalSiteData
+
+/-!
+# The virtual pair's selected shrinking operands
+
+The per-site capacity on the tagged traversal and the packed compressor payload
+refer to the same node reservation. Together they furnish every operand of the
+physical shrinking reader.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace FixedProgramDiagonal.Program.VirtualShrink
+
+open BurstRAM BurstRAM.PrivateRAM Compression CompressorRecords DescriptorSpace
+open PairSimulation PairSimulation.ShrinkRole LocalHistory
+open LiveProgram.PairStages LiveProgram.PairStages.Group.Auxiliary TraversalRows TraversalRoles
+open NodeArguments NodeArguments.ChildScan TraversalControllerInputs
+open scoped Fin.CommRing
+
+variable {K A : Type} [_root_.Field K] [CommRing A] {S : BlockSchedule K}
+ (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f)
+ {G : Group} {n T limit lanes : ℕ} (hT : T * S.laneBits ≤ lanes)
+ (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices)
+
+attribute [local irreducible] ShrinkRoleDirectory.occurrence BlockProgram.layout
+ BlockSchedule.Templates.execute StateExecution.finalState executeLevels
+
+set_option quotPrecheck false
+local notation "pub" => terminalOperands G
+local notation "D" => BlockProgram.layout B (terminalOperands G 2).val X.positions T
+local notation "tags" => TraversalRoles.selected B f hf T hT X z
+
+variable {table : Fin (BlockProgram.layout B (terminalOperands G 2).val X.positions T).shape.tables}
+ {baseBits laneBits ord : ℕ} {calendar reference phy : Memory G.w}
+ {bits : Fin (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth → Bool}
+ (history : SelectedPayloadHistory.Past B f hf
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ (CompiledResident.payload B f hf (terminalOperands G 2) X.positions T n)
+ (executeLevels B f hf T hT X z) calendar)
+ (entry : TerminalProgram.VertexEntry (w := G.w) B f hf T hT X z
+ (BlockProgram.layout B (terminalOperands G 2).val X.positions T) table baseBits laneBits
+ (terminalOperands G) calendar reference bits)
+ (packed : VertexPacked G (BlockProgram.layout B (terminalOperands G 2).val X.positions T)
+ B.recordLimit (TraversalRoles.selected B f hf T hT X z)
+ (StateExecution.finalState (B.execute f hf T hT X) z).totalWidth)
+ (frame : LinkedVertexMemory G reference ord phy)
+ (width : MapConstants.widthThreshold B.shrink ≤ G.w)
+ (fits : ∀ x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z), ∀ m,
+ canonicalFits B x.occurrence.i x.occurrence.state x.occurrence.selection (w := G.w)
+ (Fintype.card B.Entry) n
+ (endAddress (BlockProgram.layout B (terminalOperands G 2).val X.positions T) +
+ words B.recordLimit (selectedLayers B f hf T hT X z))
+ (layerBase B.recordLimit (endAddress (BlockProgram.layout B (terminalOperands G 2).val
+ X.positions T)) (TraversalRoles.selected B f hf T hT X z) x.val.1.val) limit m)
+ (x : ShrinkRoleDirectory.ShrinkSite (executeLevels B f hf T hT X z))
+
+local notation "o" => x.occurrence
+local notation "site" => physicalSiteBank B f hf hT X z history entry packed frame width fits x
+local notation "id" => VertexImage.RoleDomains.siteId B f hf T hT X z x
+set_option maxHeartbeats 1500000 in
+-- The two row counts index the same selected pass and its dependent job and packet types.
+/-- The true physical operand bank of the popped row satisfies its complete site
+contract at every later vertex in the terminal scan. -/
+theorem Capacity.siteData {p r : ℕ} (M : Machine G.w p r 11) (publicWords : M.publicData = pub)
+ (capacity : Capacity B f hf G n T hT X z x) :
+ CanonicalSiteData site M f hf T hT X z x.val.1 id (endAddress D) := by
+ let j := x.val.1
+ have payload := CompiledResident.shrink_vertex (G := G) history entry packed frame j (o).selected
+ have same : tagWords B.recordLimit tags = words B.recordLimit (selectedLayers B f hf T hT X z) :=
+ congrArg (words B.recordLimit) (selected_layers B f hf T hT X z)
+ have hidden := capacity.maps.hidden phy payload
+ have free := capacity.hiddenSpace.capacity
+ have room := capacity.rows.frameRoom
+ rw [same] at hidden free room
+ have older := capacity.rows.earlier
+ rw [shrinkSiteOrdinal_eq B (o).i (o).state (o).selection (o).site] at older
+ exact physicalSiteData B f hf hT X z history entry packed frame width fits x M publicWords
+ capacity.rows.wire room older capacity.hiddenSpace.width free hidden
+
+end FixedProgramDiagonal.Program.VirtualShrink
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairVirtualVertexRoot.lean b/lean/OAI/Computability/VPVNP/PairVirtualVertexRoot.lean
new file mode 100644
index 0000000000..70071b82c3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairVirtualVertexRoot.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.PairVertexRootInputs
+import OAI.Computability.VPVNP.PairTerminalVertexFramePacked
+import OAI.Computability.VPVNP.PairVertexActiveRoot
+import OAI.Computability.VPVNP.PairVertexAscendingPaths
+import OAI.Computability.VPVNP.PairTerminalNativeTable
+import OAI.Computability.VPVNP.LiveVirtualPairReadback
+
+/-!
+# The actual virtual counter at the native terminal root
+
+The eleven words and the code at the site entry belong to the fixed live
+group. The primed machine initialized by the cache is the same one selected
+for the exterior assignment, pair index and nomination.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairSimulation.VertexImage
+
+open BurstRAM PrivateRAM LiveProgram Compression CompressorRecords.SourceTransport
+open scoped Fin.CommRing
+
+/-- A bounded execution from the vertex entry to the active root state. Its event trace has the
+prescribed length and probe count, reads the worker header cell, consumes no choice bits
+and restores the incoming memory. -/
+structure RootRun {S : Part → Segment} {w p r : ℕ} (A : Placement S p r) (M : Machine w p r 11)
+ (m : Memory w) (ordinal : Word w) (degree exponent bound : ℕ) (packet : NodeArguments.Packet)
+ (vals : LeafSourceLoad.Static 34 → Word w) : Prop where
+ run : ∃ t ≤ bound, ∃ out : Config w p r, ∃ es : List (Event w),
+ ActiveRootState A out ordinal (M.publicData 6) (m (TerminalLink.header M.publicData+14).val)
+ (NativeFrame.fromHeader degree M.publicData (TerminalLink.header M.publicData) m) packet
+ (NativeFrame.leafWords degree M.publicData (TerminalLink.header M.publicData)
+ (m (TerminalLink.header M.publicData+14).val) m)
+ (NativeFrame.fields degree M.publicData (TerminalLink.header M.publicData)
+ (m (TerminalLink.header M.publicData+14).val) m) vals ∧
+ es.length = t+degree+187+(15+21*(2^exponent)+5*packet.bits.length) ∧
+ countProbes es = 15+(5*(2^exponent)+packet.bits.length) ∧ choiceBits es = [] ∧ after m es = m ∧
+ Reads (TerminalLink.workerCell (TerminalLink.header M.publicData)) es ∧
+ TerminalRootGather.Prefix M m (M.program.start ordinal) es out
+
+end PairSimulation.VertexImage
+
+namespace FixedProgramDiagonal.Program
+
+open BurstRAM PrivateRAM LiveProgram PairStages.Group.Auxiliary PairSimulation Compression CompressorRecords
+open CursorNetwork VertexImage CutSchedule ExponentTrace Filter
+open scoped Fin.CommRing
+
+variable {K : Type} [_root_.Field K] {S : BlockSchedule K} {B : S.Templates}
+ {u : PairExponents B.growthConstant} {D : FixedProgramDiagonal.Program} {n : ℕ}
+ {hn : 2 ≤ n} (V : D.VirtualPairs B u hn D.constants.circuitExponent)
+ {ht : 21 ≤ 2^(D.geometry n).w} {hf : 44 ≤ n^10000}
+ (adv : Bits (n^D.constants.advicePower)) (ξ : Exterior (D.chainHeight n) (n^D.constants.deltaPower))
+ (i : D.groupIndices n) (μ : PairStages.Group.Nominations.Nom (D.executionGroup n ht hf))
+ {labels : ℕ} (order : B.Entry ≃ Fin labels)
+
+local notation "G₀" => D.executionGroup n ht hf
+local notation "S₀" => TerminalProgram.nativeSegments B D.constants D.numerator D.denominator order
+local notation "A₀" => VertexImage.placement S₀
+local notation "pub" => terminalOperands G₀
+local notation "hdr" => vertexHeader G₀
+local notation "M₀" => PrivateRAM.Template.instantiate (VertexImage.template S₀) (Geometry.w (D.geometry n)) pub
+local notation "degree" => slotDegree S
+local notation "aux" => V.data adv ξ i (physicalNomination rfl μ)
+
+attribute [local irreducible] VertexImage.placement VertexImage.template NativeOperands.capacity
+ NativeOperands.saved VertexGeometry.segment CursorBounds.wordBits CursorBounds.virtualBits
+ TerminalRootGather.segment
+
+/-- Execute the concrete arithmetic, cache and root gather for the chosen
+physical nomination. The only per-site inputs are the header and bit bank
+obtained from the selected calendar. -/
+theorem VirtualPairs.active_root {ex lanes : ℕ} (Y : State ex lanes) (v : Y.network.Site)
+ (m : Memory (D.geometry n).w) (state : BurstRAM.Word (D.geometry n).w)
+ (bits : Fin (∑ j, TerminalPrefix.width Y j) → Bool)
+ (inputs : TerminalProgram.RootInputs Y v degree pub hdr state m bits)
+ (large : 3 ≤ n) (fit : PairNativeGeometry.Fits D.numerator D.denominator n (D.geometry n).w) :
+ VertexImage.RootRun A₀ M₀ m state degree ex
+ (NativeOperands.work (NativeCache.args D.constants) D.numerator D.denominator (D.geometry n)+76)
+ (VertexRootPacket.packet Y (TerminalRootGather.Layout.ofHeader degree pub hdr state m) v bits)
+ (LeafVisit.cacheWords aux (CursorBounds.virtualBits D.addressFactor n) (roundedUp 1 4 n)) := by
+ have hfitted := (V.counts i (PairedChain.headers adv ξ i) (physicalNomination rfl μ)).fits
+ let M := M₀
+ let A := A₀
+ let start := M.program.start state
+ have heads : TerminalSiteStart.headerWord M.publicData = hdr := headerWord_eq_header _
+ have input : TerminalProgram.RootInputs Y v degree M.publicData (TerminalSiteStart.headerWord M.publicData) state m bits :=
+ heads ▸ inputs
+ have mem : start.privateMem = fun _ => 0 := rfl
+ have here : start.pc = A.entry .bootstrap := by
+ unfold start M A VertexImage.template
+ rfl
+ let A' : Placement (segments (VertexGeometry.segment D.constants degree D.numerator D.denominator)
+ TerminalRootGather.segment LeafRole.segment (ShrinkVertexImage.shrinkSegment B order)
+ (RefreshVertex.refreshSegment B (RefreshBlockPlan.order B) (RefreshBlockPlan.shape B).stride order))
+ (Fintype.card (PC S₀)) (Fintype.card (Reg S₀)) := A
+ have proof := VertexImage.active_root D.constants degree D.numerator D.denominator A' (V.layout i) aux M m start Y v bits
+ D.denominator_pos D.address_pos large rfl fit (V.literal i) (V.scratch i) hfitted rfl V.cap.tags V.cap.capFits rfl
+ (template_contains S₀ pub) here mem input.active input.rootPos input.rootBound input.cache input.numbering input.rows
+ input.bank input.fits input.deg input.width input.header input.heads input.wires
+ simp only [headerWord_eq_header] at proof
+ obtain ⟨t,ht₀,out,es,ready,time,probes,det,stable,reads,run⟩ := proof
+ have geom : AssemblerPublic.geometry D.addressFactor n (D.geometry n).H = D.geometry n := rfl
+ have st : start.persistent = state := rfl
+ have words : M.publicData = pub := rfl
+ rw [geom] at ht₀
+ simp only [st,words] at ready time probes reads
+ exact ⟨t,ht₀,out,es,ready,time,probes,det,stable,reads,run⟩
+
+end FixedProgramDiagonal.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairWorkspace.lean b/lean/OAI/Computability/VPVNP/PairWorkspace.lean
new file mode 100644
index 0000000000..8eaaf02d2b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairWorkspace.lean
@@ -0,0 +1,175 @@
+import OAI.Computability.VPVNP.CursorBranchBudget
+import OAI.Computability.VPVNP.CompressorRecordsCursorCoordinates
+
+/-!
+# Lane choice and physical addresses of the compressed pair
+
+Use the first virtual address bits for the base, and precisely the last
+block coordinates for compression. A fixed polynomial amount of scratch
+space per live processor fits in the quartic live word length. The
+threshold is chosen before any descriptor or final path is selected.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CursorNetwork
+
+open CursorBounds Compression Filter
+
+/-- The executable cursor's bit reversal inside each of the two coordinate
+blocks is included in the choice of labels. -/
+def scheduledLabels (D lanes : ℕ) (h : lanes ≤ D) : Fin D ≃ Fin (D-lanes) ⊕ Fin lanes :=
+ (finCongr (Nat.sub_add_cancel h).symm).trans (cursorCoordinateLabels (D-lanes) lanes)
+
+/-- Polynomially many scratch cells per live site, with fixed logarithmic
+overhead, can all be represented by distinct live word addresses. -/
+theorem eventually_pairWorkspaceFits (b : ℕ) (hb : 1 ≤ b) (C degree logPower : ℕ) :
+ ∀ᶠ n : ℕ in atTop,
+ C * processorCount b n * n^degree * (n.log2+1)^logPower + 1 < 2 ^ wordBits b n := by
+ let K := C.size + degree + logPower + 2
+ filter_upwards [eventually_ge_atTop (2^K)] with n hn
+ let c := Nat.clog 2 n
+ let r := addressBits b n
+ have hc : K ≤ c := by
+ simpa [c, Nat.clog_pow _ _ (by decide : 1 < 2)] using Nat.clog_mono_right 2 hn
+ have hcr : c ≤ r := Nat.le_mul_of_pos_left _ hb
+ have hr : K ≤ r := hc.trans hcr
+ have hn' : 0 < n := (Nat.two_pow_pos _).trans_le hn
+ have hs : n.log2+1 ≤ n := (Nat.log2_lt hn'.ne').mpr Nat.lt_two_pow_self
+ have hn2 : n ≤ 2^c := Nat.le_pow_clog (by decide) _
+ have hsize : C ≤ 2^C.size := (Nat.lt_size_self C).le
+ have hdegree : degree + logPower ≤ r := by dsimp [K] at hr; omega
+ have hword : C.size + r + c*(degree+logPower) + 1 < (r+10)^4 := by
+ have ht := Nat.mul_le_mul hcr hdegree
+ have hs' : C.size ≤ r := by dsimp [K] at hr; omega
+ nlinarith only [ht, hs', Nat.zero_le r, Nat.zero_le (r^3), Nat.zero_le (r^4)]
+ have hwork : C * processorCount b n * n^degree * (n.log2+1)^logPower ≤
+ 2^(C.size+r+c*(degree+logPower)) := by
+ calc _ ≤ 2^C.size * 2^r * (2^c)^degree * (2^c)^logPower :=
+ Nat.mul_le_mul (Nat.mul_le_mul (Nat.mul_le_mul_right _ hsize)
+ (Nat.pow_le_pow_left hn2 _)) (Nat.pow_le_pow_left (hs.trans hn2) _)
+ _ = _ := by rw [← pow_mul, ← pow_mul, ← pow_add, ← pow_add, ← pow_add]; ring_nf
+ have htwo := Nat.pow_lt_pow_right (by decide : 1 < 2) hword
+ apply lt_of_le_of_lt _ htwo
+ rw [pow_succ]
+ have := Nat.two_pow_pos (C.size + r + c * (degree+logPower))
+ omega
+
+/-- A fixed coefficient and the two logarithmic factors in the cursor
+directory are eventually absorbed by the live site's quadratic arena. -/
+theorem eventually_pairWorkspace_lt_square (b : ℕ) (hb : 5 ≤ b) (C : ℕ) :
+ ∀ᶠ n : ℕ in atTop,
+ C * processorCount b n * n^2 * (n.log2+1)^2 + 1 < (processorCount b n)^2 := by
+ filter_upwards [BurstRAM.eventually_polylog_le (C+1) 2, eventually_ge_atTop 2] with n hc hn
+ let R := processorCount b n
+ let L := (n.log2+1)^2
+ have hR : 0 < R := Nat.two_pow_pos _
+ have hL : 0 < L := pow_pos (Nat.succ_pos _) _
+ have h5 : n^5 ≤ R := pow_five_le_processorCount n hb
+ change (C+1)*L ≤ n at hc
+ change C*R*n^2*L+1 < R^2
+ calc _ ≤ (C+1)*L*(R*n^2) := by
+ nlinarith only [Nat.mul_pos (Nat.mul_pos hR (pow_pos (by omega : 0 < n) 2)) hL]
+ _ ≤ n*(R*n^2) := Nat.mul_le_mul_right _ hc
+ _ = R*n^3 := by ring
+ _ < R*n^5 := Nat.mul_lt_mul_of_pos_left (Nat.pow_lt_pow_right (by omega) (by decide)) hR
+ _ ≤ R^2 := by rw [pow_two]; exact Nat.mul_le_mul_left _ h5
+
+set_option maxHeartbeats 1200000 in
+-- The branch carries the dependent cursor state through the real-to-integer size comparisons.
+/-- The initial cursor directory, live header block, expanded placement rows
+and final bit array fit simultaneously. The fixed multiplier can cover the
+constant record strides and the fixed number of arrays. -/
+theorem eventually_pairArenaFitBoth {k : Type*} [Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ (K : ℕ) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ ∀ z : E.Choices, let Y := E.finalState z
+ K * (X.positions + processorCount b n + Y.positions * B.growthConstant^T + Y.totalWidth)
+ + 1 < min (2 ^ wordBits b n) ((processorCount b n)^2) := by
+ let p := 2*(b+2)
+ have hb' : 1 ≤ b := (by decide : 1 ≤ 5).trans ((le_max_right _ _).trans hb)
+ have hθ : 0 < (u.θ : ℝ) := Rat.cast_pos.mpr u.theta_pos
+ have hg : 1 ≤ (B.growthConstant : ℝ) := by
+ exact_mod_cast (show 1 ≤ B.growthConstant by linarith [B.growthConstant_ge_two])
+ filter_upwards [eventually_pairBranchBounds B u b hb,
+ eventually_pairWorkspaceFits b hb' (K*(2*p+2)) 2 2,
+ eventually_pairWorkspace_lt_square b ((le_max_right _ _).trans hb) (K*(2*p+2)),
+ eventually_ge_atTop 2] with n h hfit hsquare hn
+ intro base lanes labels hD hT A _ f hf X T E z Y
+ have hbranch := h.2.2 labels hD hT A f hf z
+ have hn1 : 1 ≤ (n : ℝ) := by exact_mod_cast (show 1 ≤ n by omega)
+ have hn1' : 1 ≤ n := by omega
+ have hfrac {x : ℝ} (hx : x ≤ 1) : (n : ℝ)^x ≤ n := by
+ simpa using Real.rpow_le_rpow_of_exponent_le hn1 hx
+ have hG : B.growthConstant ^ T ≤ n := by
+ have h := (history_pow_blockCount_le hg hθ.le hn1' u.growth).trans (hfrac (by norm_num))
+ exact_mod_cast h
+ let R := processorCount b n
+ let L := (n.log2+1)^2
+ have hp : initialPositions b n ≤ p*R*n*L := by
+ have h₀ := initialPositions_bound b n hn
+ have h₁ := hfrac (by norm_num : (3/4 : ℝ) ≤ 1)
+ have h₂ : (initialPositions b n : ℝ) ≤
+ 2*((b : ℝ)+2)*(processorCount b n : ℝ)*n*((n.log2 : ℝ)+1)^2 := by
+ exact h₀.trans (mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left h₁ (by positivity))
+ (sq_nonneg _))
+ dsimp only [p, R, L]
+ exact_mod_cast h₂
+ have hw : Y.totalWidth ≤ R*n := by
+ have h := hbranch.2.1.trans
+ (mul_le_mul_of_nonneg_left (hfrac (by linarith)) (Nat.cast_nonneg _))
+ exact_mod_cast h
+ have hx := pairInput_positions S labels hD
+ change X.positions = initialPositions b n at hx
+ have hl : 1 ≤ L := Nat.one_le_pow _ _ (Nat.succ_pos _)
+ let scale := R*n^2*L
+ have hRn : R*n ≤ scale := by
+ dsimp [scale]
+ exact (Nat.mul_le_mul_left R (by nlinarith only [hn1'])).trans (Nat.le_mul_of_pos_right _ hl)
+ have hR : R ≤ scale := (Nat.le_mul_of_pos_right _ hn1').trans hRn
+ have hP : initialPositions b n ≤ p*scale := by
+ apply hp.trans
+ dsimp [scale]
+ rw [pow_two]
+ nlinarith only [Nat.le_mul_of_pos_right (p*R*n*L) hn1']
+ have hhist : Y.positions * B.growthConstant ^ T ≤ p*scale := by
+ exact (Nat.mul_le_mul (hbranch.1.trans hp) hG).trans_eq (by dsimp [scale]; ring)
+ have ht : X.positions + R + Y.positions * B.growthConstant^T + Y.totalWidth ≤ (2*p+2)*scale := by
+ rw [hx]; nlinarith only [hP,hR,hhist,hw.trans hRn]
+ apply lt_of_le_of_lt _ (lt_min hfit hsquare)
+ change K * (X.positions + R + Y.positions * B.growthConstant ^ T + Y.totalWidth) + 1 ≤
+ K*(2*p+2)*R*n^2*L + 1
+ exact Nat.add_le_add_right ((Nat.mul_le_mul_left K ht).trans_eq (by dsimp [scale]; ring)) 1
+
+/-- The arena bound in the native word-address format. -/
+theorem eventually_pairArenaFits {k : Type*} [Field k] {S : BlockSchedule k}
+ (B : S.Templates) (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b)
+ (K : ℕ) :
+ ∀ᶠ n : ℕ in atTop,
+ ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes)
+ (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes)
+ (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f),
+ let X := pairInput S labels hD
+ let T := blockCount (u.θ : ℝ) n
+ let E := B.execute f hf T hT X
+ ∀ z : E.Choices, let Y := E.finalState z
+ K * (X.positions + processorCount b n + Y.positions * B.growthConstant^T + Y.totalWidth)
+ + 1 < 2 ^ wordBits b n := by
+ filter_upwards [eventually_pairArenaFitBoth B u b hb K] with n h
+ intro base lanes labels hD hT A _ f hf X T E z Y
+ exact (h labels hD hT A f hf z).trans_le (min_le_left _ _)
+
+end CursorNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairedChain.lean b/lean/OAI/Computability/VPVNP/PairedChain.lean
new file mode 100644
index 0000000000..a5b9f90a9f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairedChain.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.ExponentTrace
+import OAI.Computability.VPVNP.GrammarDiagonal
+import OAI.Computability.VPVNP.PrimedInputRAMRows
+
+/-!
+# The two contractions of the primed chain
+
+Equation (9.2) uses consecutive pairs of groups of length `2^h` pairs.
+Each pair has two complete processor groups. Even cuts are shared with
+neighboring pairs; its odd cut and all communication sends in its two groups
+are private to that pair. The four header bits on a site contain its group's
+actual one-based number, the advice, and the incident cut bits. This numbering
+is independent of the live group which later simulates the pair.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PairedChain
+
+open CutSchedule ExponentTrace PrimedInputRAM MvPolynomial
+open scoped Classical
+
+private theorem width_le (H Δ i : ℕ) : CutSchedule.width H Δ i ≤ H * Δ := by
+ unfold CutSchedule.width
+ split_ifs
+ · exact Nat.mul_le_mul_right _ (Nat.sub_le _ _)
+ · exact Nat.zero_le _
+
+/-- The pair's exterior cuts are `2i` and `2i+2` and its interior cut is
+`2i+1`, using a zero-based pair index `i`. -/
+def lengths (h Δ adviceLength : ℕ) (i : Fin (2 ^ h)) : Lengths where
+ index := h + 2
+ advice := adviceLength
+ leftCut := CutSchedule.width (h + 1) Δ (2 * i.val)
+ middleCut := CutSchedule.width (h + 1) Δ (2 * i.val + 1)
+ rightCut := CutSchedule.width (h + 1) Δ (2 * (i.val + 1))
+ cutCapacity := (h + 1) * Δ
+ leftFit := width_le ..
+ rightFit := width_le ..
+
+/-- The `H+1`-bit literal encoding of the primed group's own one-based number. -/
+def groupIndex {h : ℕ} (i : Fin (2 ^ h)) (g : Fin 2) : BurstRAM.Word (h + 2) :=
+ ⟨2 * i.val + g.val + 1, by
+ have hi := i.isLt
+ have hg := g.isLt
+ rw [pow_add]
+ norm_num
+ omega⟩
+
+/-- The fixed literal and exterior fields supplied to both groups of a pair.
+The full bit string at a site is built by `PrimedInputRAM.input`. -/
+def headers {h Δ a : ℕ} (advice : Bits a) (exterior : Exterior h Δ)
+ (i : Fin (2 ^ h)) : Header (lengths h Δ a i) → Bool
+ | .group g k => RAMSerialization.wordBits _ (groupIndex i g) k
+ | .advice k => advice k
+ | .leftCut k => exterior i.castSucc k
+ | .rightCut k => exterior i.succ k
+
+/-- A Boolean assignment to the internal wires of the paired-chain instance at the specified
+chain index and RAM parameters. -/
+abbrev PairBits (h Δ a r bucket w : ℕ) (i : Fin (2 ^ h)) :=
+ Internal (lengths h Δ a i) r bucket w → Bool
+
+/-- Full literal-and-wire input of a primed site. Communication bits are
+summed even when they do not form a valid RAM transcript. -/
+def siteInput {n h Δ a r bucket w : ℕ} (program : UniversalMachine.Program)
+ (hfit : BurstRAM.ProcessorInput.Fits program n r bucket w) (advice : Bits a)
+ (exterior : Exterior h Δ) (i : Fin (2 ^ h)) (s : PairBits h Δ a r bucket w i)
+ (v : Site r) : Fin n → Bool :=
+ input program hfit (headers advice exterior i) s v
+
+/-- The integer contraction (9.2), with the shared bit assignments indexed
+by the even cuts and the independent internal bits of every pair. -/
+noncomputable def original {n h Δ a r bucket w : ℕ} (program : UniversalMachine.Program)
+ (hfit : BurstRAM.ProcessorInput.Fits program n r bucket w) (advice : Bits a) : ℕ :=
+ Diagonal.originalContraction (fun (ξ : Exterior h Δ) i s v =>
+ acceptingCount (siteInput program hfit advice ξ i s v))
+
+/-- The formal joint polynomial of equations (9.3) and (9.5), leaving the
+integer production labels as variables until the contraction is evaluated. -/
+noncomputable def primed {n h Δ a r bucket w : ℕ} {H : Type*} [Fintype H]
+ (program : UniversalMachine.Program) (hfit : BurstRAM.ProcessorInput.Fits program n r bucket w)
+ (advice : Bits a) (d : Fin n) (head : H) : MvPolynomial (GrammarLabel (Fin n × Bool) H n) ℤ :=
+ ∑ ξ : Exterior h Δ, ∏ i : Fin (2 ^ h),
+ PairCoefficient.jointPolynomial d head (siteInput program hfit advice ξ i)
+
+/-- Equation (9.3) for the paper's actual bit sharing, `Uₙ`, and `Bₓ`.
+Equation (8.1) at each site replaces a grammar query by the path count of
+the very same input string. -/
+theorem primed_eq_original {n h Δ a r bucket w : ℕ} {H A : Type*} [Fintype H] [CommRing A]
+ (program : UniversalMachine.Program) (hfit : BurstRAM.ProcessorInput.Fits program n r bucket w)
+ (advice : Bits a) (d : Fin n) (head : H) (value : GrammarLabel (Fin n × Bool) H n → A)
+ (hlabels : ∀ x, eval₂Hom (Int.castRingHom A) value (labelQuery d head x) = (acceptingCount x : A)) :
+ eval₂Hom (Int.castRingHom A) value (primed (h := h) (Δ := Δ) program hfit advice d head) =
+ (original (h := h) (Δ := Δ) program hfit advice : A) := by
+ unfold primed original Diagonal.originalContraction PairCoefficient.jointPolynomial
+ simp only [map_sum, map_prod, hlabels]
+ simp_rw [Fintype.prod_sum]
+ push_cast
+ rfl
+
+end PairedChain
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairedEvaluatorContradiction.lean b/lean/OAI/Computability/VPVNP/PairedEvaluatorContradiction.lean
new file mode 100644
index 0000000000..a0428bf545
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairedEvaluatorContradiction.lean
@@ -0,0 +1,148 @@
+import OAI.Computability.VPVNP.CompressorEvaluatorChain
+import OAI.Computability.VPVNP.FixedLabelReadback
+
+/-!
+# Proposition 9.1 for the joint compressor evaluator
+
+The label assignment, scalar field and normalized functional all come from
+one slice model of the actual grammar and compressor equations. The two
+machine-count inputs are the weighted path identity for each primed pair and
+the modular path count of the evaluator on its initial exponent tape. The
+integer count used for the contradiction is the original paired chain.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.BlockSchedule.Templates
+
+open MvPolynomial JointLabelSystem LabelEvaluator CutSchedule ExponentTrace UniversalMachine
+open scoped Classical
+
+local instance pairedPrimeFact (p : Nat.Primes) : Fact p.val.Prime := ⟨p.property⟩
+/-- Finite enumeration of the slice ground field used to instantiate the paired evaluator's
+matrix-coordinate arguments. -/
+noncomputable local instance pairedGroundFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _
+
+/-- The algebra structure on the ambient field induced by the designated embedding of the
+finite slice ground field. -/
+noncomputable local instance pairedGroundAlgebra (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) :=
+ (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra
+/-- Classical equality of productions for the finite choices and coefficient comparisons of the
+paired evaluator argument. -/
+noncomputable local instance pairedProductionDecEq (n c : ℕ) : DecidableEq (Production n c) := Classical.decEq _
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+variable {n c : ℕ}
+
+/-- One cell of the physical increment array in dense parser order, followed
+by compressor occurrence counts in the fixed motif order. -/
+noncomputable def denseExponent (μ : Production n c → ℕ) (ν : B.Entry → ℕ)
+ (i : Fin (FixedRows.productionCount n c + Fintype.card B.Entry)) : ℕ :=
+ (finSumFinEquiv.symm i).elim (μ ∘ (PrimedStackRAM.labelIndex n n _).symm)
+ (ν ∘ (Fintype.equivFin B.Entry).symm)
+
+/-- Applying the dense-to-formal coordinate permutation recovers the corresponding
+production or compressor count in the joint assignment. -/
+theorem denseExponent_labelOrder (μ : Production n c → ℕ) (ν : B.Entry → ℕ)
+ (i : Fin (FixedRows.productionCount n c + Fintype.card B.Entry)) :
+ joinAssignment μ ν (FixedRows.labelOrder B.Entry n c i) = B.denseExponent μ ν i := by
+ obtain ⟨(v | v), rfl⟩ := finSumFinEquiv.surjective i <;>
+ simp [FixedRows.labelOrder, joinAssignment, denseExponent]
+
+/-- The decoded order-advice word names the formal coordinate at which the
+evaluator must receive this dense exponent. -/
+theorem denseExponent_orderAdvice (μ : Production n c → ℕ) (ν : B.Entry → ℕ)
+ (i : Fin (FixedRows.productionCount n c + Fintype.card B.Entry)) :
+ let w := ((RAMSerialization.arrayBits _ _).symm (FixedRows.orderAdvice B.Entry n c) i).val
+ ∃ j : Fin (B.compressorLabelCount c n), j.val = w ∧
+ joinAssignment μ ν j = B.denseExponent μ ν i := by
+ exact ⟨FixedRows.labelOrder B.Entry n c i, (FixedRows.orderAdvice_lookup ..).symm,
+ B.denseExponent_labelOrder μ ν i⟩
+
+/-- Groupwise exponent accumulation commutes with numbering the joint label list. -/
+theorem sum_joinedExponents {I : Type*} [Fintype I] (μ : I → Production n c → ℕ) (ν : I → B.Entry → ℕ) :
+ (fun j => ∑ i, joinAssignment (μ i) (ν i) j) =
+ joinAssignment (fun v => ∑ i, μ i v) (fun v => ∑ i, ν i v) := by
+ funext j
+ obtain ⟨(v | v), rfl⟩ := (Fintype.equivFin (Production n c ⊕ B.Entry)).surjective j <;>
+ simp [joinAssignment]
+
+/-- The parser nominates every production using exactly the paper's `2r` bits. -/
+abbrev PairNomination (n c r : ℕ) := Production n c → Fin (2 ^ (2*r))
+
+private theorem pairSum_lt {h r Z : ℕ} (hZ : h + 2*r ≤ Z) (v : Fin (2^h) → ℕ)
+ (hb : ∀ i, v i < 2^(2*r)) : (∑ i, v i) < 2^Z := by
+ calc
+ (∑ i, v i) < ∑ _ : Fin (2^h), 2^(2*r) :=
+ Finset.sum_lt_sum_of_nonempty Finset.univ_nonempty (fun i _ => hb i)
+ _ = 2^(h+2*r) := by simp [pow_add]
+ _ ≤ 2^Z := Nat.pow_le_pow_right (by decide) hZ
+
+variable {h Δ a r bucket w Z : ℕ} {p : Nat.Primes} (hn : 2 ≤ n)
+variable (M : Model p (B.compressorDegree n) (B.compressorEquations hn c))
+variable (program : UniversalMachine.Program) (hfit : BurstRAM.ProcessorInput.Fits program n r bucket w) (advice : Bits a)
+variable {Path : Exterior h Δ → Fin (2^h) → PairNomination n c r → Type*}
+variable [∀ ξ i μ, Fintype (Path ξ i μ)]
+
+/-- An actual tail evaluator cannot satisfy the physical live-count identity
+alongside the weighted compressor identities of Section 12. The original
+primed site labels and the evaluation functional are read out of the chosen
+model of the integer equations. -/
+theorem pairedEvaluatorContradiction (hR : 4 * n ≤ 2^r) (hZ : h + 2*r ≤ Z)
+ (ν : ∀ ξ i μ, Path ξ i μ → B.Entry → ℕ)
+ (hν : ∀ ξ i μ q v, ν ξ i μ q v < 2^(2*r))
+ (hpair : ∀ ξ i μ, ∑ q : Path ξ i μ, ∏ v, (B.compressorValues hn M v) ^ ν ξ i μ q v =
+ (GrammarDiagonal.multiplicity (⟨n-1, by omega⟩ : Fin n)
+ (⟨0, pow_pos (by omega) _⟩ : Fin (n^(c+5))) (PairedChain.siteInput program hfit advice ξ i) μ : M.algebra))
+ (E : UniversalMachine.Program) (initial : (Fin (B.compressorLabelCount c n) → ℕ) → Config E.extra)
+ (htail : ∀ e, (∀ j, e j < 2^Z) → (paths E (2^h) (initial e) : ZMod p.val) =
+ (M.presentation.branchCount p.val Z e : ZMod p.val))
+ (hlive : PairedChain.original (h := h) (Δ := Δ) program hfit advice = 1 +
+ ∑ ξ : Exterior h Δ, ∑ μ : Fin (2^h) → PairNomination n c r, ∑ q : (i : Fin (2^h)) → Path ξ i (μ i),
+ paths E (2^h) (initial (fun j => ∑ i, joinAssignment (fun v => (μ i v).val) (ν ξ i (μ i) (q i)) j))) : False := by
+ let d : Fin n := ⟨n-1, by omega⟩
+ let head : Fin (n^(c+5)) := ⟨0, pow_pos (by omega) _⟩
+ let label (μ : PairNomination n c r) := ∏ v, (B.productionValues hn M v) ^ (μ v).val
+ let coeff (ξ : Exterior h Δ) (i : Fin (2^h)) (μ : PairNomination n c r) : ℕ := GrammarDiagonal.multiplicity d head (PairedChain.siteInput program hfit advice ξ i) μ
+ let gadget (ξ : Exterior h Δ) (i : Fin (2^h)) (μ : PairNomination n c r) (q : Path ξ i μ) := ∏ v, (B.compressorValues hn M v) ^ ν ξ i μ q v
+ apply Diagonal.pairedChainCriterion (PairedChain.original program hfit advice) M.functional M.functional_one
+ label coeff gadget hpair
+ · rw [← B.compressorEvaluator_primed hn M program hfit advice]
+ change (∑ ξ, ∏ i, ∑ μ, label μ * (coeff ξ i μ : M.algebra)) =
+ eval₂Hom (Int.castRingHom M.algebra) (B.productionValues hn M)
+ (∑ ξ : Exterior h Δ, ∏ i, PairCoefficient.jointPolynomial d head (PairedChain.siteInput program hfit advice ξ i))
+ simp only [map_sum, map_prod]
+ apply Finset.sum_congr rfl
+ intro ξ _
+ apply Finset.prod_congr rfl
+ intro i _
+ apply (PairCoefficient.evaluate_by_nominations d head _ _ (2*r) _).symm
+ simpa only [PrimedInputRAM.Site, Fintype.card_prod, Fintype.card_fin, d] using
+ PairCoefficient.pair_counter_capacity r n (by omega) hR
+ · rw [hlive, Nat.cast_add, Nat.cast_one, Diagonal.evaluationMode]
+ push_cast
+ congr 1
+ apply Finset.sum_congr rfl
+ intro ξ _
+ apply Finset.sum_congr rfl
+ intro μ _
+ apply Finset.sum_congr rfl
+ intro q _
+ let μ' i v := (μ i v).val
+ let ν' i v := ν ξ i (μ i) (q i) v
+ have hμsum (v) := pairSum_lt hZ (fun i => μ' i v) (fun i => (μ i v).isLt)
+ have hνsum (v) := pairSum_lt hZ (fun i => ν' i v) (fun i => hν ξ i (μ i) (q i) v)
+ rw [B.sum_joinedExponents μ' ν', htail]
+ · exact B.compressorEvaluator_pair_product hn M Z μ' ν' hμsum hνsum
+ · intro j
+ obtain ⟨(v | v), rfl⟩ := (Fintype.equivFin (Production n c ⊕ B.Entry)).surjective j
+ · simpa [joinAssignment] using hμsum v
+ · simpa [joinAssignment] using hνsum v
+
+end Compression.BlockSchedule.Templates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PairedFamily.lean b/lean/OAI/Computability/VPVNP/PairedFamily.lean
new file mode 100644
index 0000000000..77cd73fcca
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PairedFamily.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.ChoiceWitness
+import Mathlib.RingTheory.MvPolynomial.Homogeneous
+
+/-!
+# Paired variables for the universal counting polynomial
+
+In equation (1.1) of *VP and VNP differ over every field*, the monomial for a word
+`x` takes precisely one variable from each pair, with the second index recording its bit.
+The coefficient and degree calculations hold for every coefficient function over a
+commutative semiring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+variable {n : ℕ} {R : Type*} [CommSemiring R]
+
+/-- The exponent vector for the word `x` in the paired variables. -/
+noncomputable def pairedExponent (x : Fin n → Bool) : (Fin n × Bool) →₀ ℕ :=
+ ∑ j, Finsupp.single (j, x j) 1
+
+@[simp] theorem pairedExponent_apply (x : Fin n → Bool) (i : Fin n) (b : Bool) :
+ pairedExponent x (i, b) = if x i = b then 1 else 0 := by
+ classical
+ rw [pairedExponent, Finsupp.finsetSum_apply, Finset.sum_eq_single i]
+ · simp [Finsupp.single_apply]
+ · intro j _ hji
+ simp [hji]
+ · simp
+
+theorem pairedExponent_injective : Function.Injective (@pairedExponent n) := by
+ intro x y h
+ funext i
+ have e := DFunLike.congr_fun h (i, y i)
+ simpa [pairedExponent_apply] using e
+
+/-- The polynomial in (1.1), with `u` providing its coefficients. -/
+noncomputable def pairedPolynomial (u : (Fin n → Bool) → R) : MvPolynomial (Fin n × Bool) R :=
+ ∑ x, C (u x) * ∏ j, X (j, x j)
+
+theorem pairedPolynomial_eq_sum_monomial (u : (Fin n → Bool) → R) :
+ pairedPolynomial u = ∑ x, monomial (pairedExponent x) (u x) := by
+ simp only [pairedPolynomial, pairedExponent, monomial_sum_index, X]
+
+/-- The coefficient of the monomial indexed by `x` recovers the value at `x`. -/
+@[simp] theorem coeff_pairedPolynomial (u : (Fin n → Bool) → R) (x : Fin n → Bool) :
+ (pairedPolynomial u).coeff (pairedExponent x) = u x := by
+ classical
+ simp [pairedPolynomial_eq_sum_monomial, coeff_monomial,
+ pairedExponent_injective.eq_iff]
+
+theorem pairedPolynomial_isHomogeneous (u : (Fin n → Bool) → R) :
+ (pairedPolynomial u).IsHomogeneous n := by
+ rw [pairedPolynomial_eq_sum_monomial]
+ apply IsHomogeneous.sum
+ intro x _
+ apply isHomogeneous_monomial
+ simp [pairedExponent, Finsupp.degree_single]
+
+/-- Each individual variable has degree at most one, including in positive characteristic. -/
+theorem pairedPolynomial_multilinear (u : (Fin n → Bool) → R) (z : Fin n × Bool) :
+ (pairedPolynomial u).degreeOf z ≤ 1 := by
+ classical
+ rw [pairedPolynomial_eq_sum_monomial]
+ refine (degreeOf_sum_le _ _ _).trans (Finset.sup_le fun x _ ↦ ?_)
+ by_cases h : u x = 0
+ · simp [h]
+ · rcases z with ⟨i, b⟩
+ rw [degreeOf_monomial_eq _ _ h, pairedExponent_apply]
+ split <;> decide
+
+theorem map_pairedPolynomial {S : Type*} [CommSemiring S] (f : R →+* S)
+ (u : (Fin n → Bool) → R) :
+ MvPolynomial.map f (pairedPolynomial u) = pairedPolynomial (f ∘ u) := by
+ simp [pairedPolynomial]
+
+theorem pairedPolynomial_totalDegree (u : (Fin n → Bool) → R) (x : Fin n → Bool)
+ (hx : u x ≠ 0) : (pairedPolynomial u).totalDegree = n := by
+ apply (pairedPolynomial_isHomogeneous u).totalDegree
+ intro h
+ apply hx
+ rw [← coeff_pairedPolynomial u x, h]
+ rfl
+
+/-- Equation (1.1) over the integers, using the clocked table encoding from §1.1. -/
+noncomputable def P (n : ℕ) : MvPolynomial (Fin n × Bool) ℤ :=
+ pairedPolynomial (fun x ↦ (acceptingCount x : ℤ))
+
+/-- Interpretation of the integer polynomial in a commutative ring. -/
+theorem map_P {S : Type*} [CommRing S] (n : ℕ) :
+ MvPolynomial.map (Int.castRingHom S) (P n) =
+ pairedPolynomial (fun x ↦ (acceptingCount x : S)) := by
+ rw [P, map_pairedPolynomial]
+ simp [Function.comp_def]
+
+/-- Expansion over input words and their canonical machine-choice strings. The verifier
+in this identity is the deterministic Boolean function `verifiesInput`. -/
+theorem map_P_eq_sum_witnesses {S : Type*} [CommRing S] (n : ℕ) :
+ MvPolynomial.map (Int.castRingHom S) (P n) =
+ ∑ x : Fin n → Bool, ∑ w : Fin (n ^ clockExponent) → Bool,
+ (if verifiesInput x w then 1 else 0) *
+ ∏ j, (X (j, x j) : MvPolynomial (Fin n × Bool) S) := by
+ rw [map_P, pairedPolynomial]
+ apply Finset.sum_congr rfl
+ intro x _
+ rw [acceptingCount_eq_sum_witnesses, map_sum, Finset.sum_mul]
+ simp [apply_ite C]
+
+@[simp] theorem coeff_P (x : Fin n → Bool) :
+ (P n).coeff (pairedExponent x) = (acceptingCount x : ℤ) :=
+ coeff_pairedPolynomial _ _
+
+theorem P_isHomogeneous (n : ℕ) : (P n).IsHomogeneous n :=
+ pairedPolynomial_isHomogeneous _
+
+theorem P_multilinear (n : ℕ) (z : Fin n × Bool) : (P n).degreeOf z ≤ 1 :=
+ pairedPolynomial_multilinear _ _
+
+/-- The formal total degree remains exactly `n` after base change, including in positive
+characteristic. For positive lengths, the all-zero input has exactly one accepting path. -/
+theorem totalDegree_map_P {S : Type*} [CommRing S] [Nontrivial S] (n : ℕ) :
+ (MvPolynomial.map (Int.castRingHom S) (P n)).totalDegree = n := by
+ rw [map_P]
+ by_cases hn : n = 0
+ · subst n
+ exact Nat.le_zero.mp (pairedPolynomial_isHomogeneous _).totalDegree_le
+ · apply pairedPolynomial_totalDegree _ (fun _ ↦ false)
+ simp [acceptingCount_allFalse (Nat.pos_of_ne_zero hn)]
+
+theorem P_totalDegree (n : ℕ) : (P n).totalDegree = n := by
+ by_cases hn : n = 0
+ · subst n
+ exact Nat.le_zero.mp (P_isHomogeneous 0).totalDegree_le
+ · apply pairedPolynomial_totalDegree _ (fun _ ↦ false)
+ simp [acceptingCount_allFalse (Nat.pos_of_ne_zero hn)]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PaperPairParameters.lean b/lean/OAI/Computability/VPVNP/PaperPairParameters.lean
new file mode 100644
index 0000000000..a130c2886f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PaperPairParameters.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.CursorBranchBudget
+import OAI.Computability.VPVNP.CompressorRecordsCursorCoordinates
+import OAI.Computability.VPVNP.RAMApplications
+import OAI.Computability.VPVNP.PolynomialBounds
+
+/-!
+# Integer parameters of the fixed live and virtual machines
+
+The rational exponents chosen by the compressor have fixed positive
+numerators and denominators. Using them in the integer floor and ceiling
+algorithms gives exactly the analytic block and bucket counts of §9.1 at
+every length. After choosing the address exponent, one threshold supplies
+the live and virtual word capacities, the exponent no-overflow margin,
+and enough fresh lane coordinates.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace LiveProgram
+universe v
+
+open Compression CursorBounds CursorNetwork BurstRAM Filter
+
+/-- A positive rational strictly below one in the fixed program's operand format. -/
+structure Ratio (x : ℝ) where
+ /-- Positive integer numerator in the program's representation of a ratio between zero and
+ one. -/
+ num : ℕ
+ /-- Positive integer denominator, strictly larger than the numerator, used by the program's
+ rounded integer arithmetic. -/
+ den : ℕ
+ num_pos : 0 < num
+ den_pos : 0 < den
+ less : num < den
+ value : (num : ℝ) / den = x
+
+/-- Encodes a positive rational below one by its natural numerator and denominator, preserving
+its value as a real number. -/
+def Ratio.ofRat (x : ℚ) (hp : 0 < x) (hl : x < 1) : Ratio (x : ℝ) := by
+ have hnum := Rat.num_pos.mpr hp
+ have hcast : (x.num.toNat : ℝ) = (x.num : ℝ) := by exact_mod_cast Int.toNat_of_nonneg hnum.le
+ have hden : 0 < (x.den : ℝ) := by exact_mod_cast x.den_pos
+ have hv : (x.num.toNat : ℝ) / x.den = (x : ℝ) := by rw [hcast, Rat.cast_def]
+ have hlt : (x.num.toNat : ℝ) / x.den < 1 := by rw [hv]; exact_mod_cast hl
+ have hlt' := (div_lt_iff₀ hden).mp hlt
+ rw [one_mul] at hlt'
+ exact ⟨x.num.toNat,x.den,by omega,x.den_pos,by exact_mod_cast hlt',hv⟩
+
+variable {C₂ : ℕ}
+
+/-- Operand pair representing the block exponent θ in the fixed program. -/
+def blockRatio (u : PairExponents C₂) : Ratio (u.θ : ℝ) :=
+ Ratio.ofRat u.θ u.theta_pos (lt_trans u.theta_lt (by norm_num))
+
+/-- Operand pair representing the live-bucket exponent 1 − δ in the fixed program. -/
+def liveRatio (u : PairExponents C₂) : Ratio (1-(u.δ : ℝ)) := by
+ have h : (1-(u.δ : ℝ)) = ((1-u.δ : ℚ) : ℝ) := by norm_num
+ rw [h]
+ exact Ratio.ofRat (1-u.δ) (by linarith [u.delta_lt,u.theta_lt]) (by linarith [u.delta_pos])
+
+theorem blockRatio_floor (u : PairExponents C₂) (n : ℕ) :
+ roundedDown (blockRatio u).num (blockRatio u).den n = blockCount (u.θ : ℝ) n := by
+ rw [roundedDown_eq, (blockRatio u).value]
+
+theorem liveRatio_ceil (u : PairExponents C₂) (n : ℕ) :
+ roundedUp (liveRatio u).num (liveRatio u).den n = bucketExponent (1-(u.δ : ℝ)) n := by
+ rw [roundedUp_eq, (liveRatio u).value]
+
+/-- The power of two obtained by rounding (1 − δ) log₂ n upward to an integer using the
+live-ratio operands. -/
+def liveCapacity (u : PairExponents C₂) (n : ℕ) :=
+ 2^(roundedUp (liveRatio u).num (liveRatio u).den n)
+
+theorem liveCapacity_eq (u : PairExponents C₂) (n : ℕ) : liveCapacity u n = liveBucket (u.δ : ℝ) n := by
+ rw [liveCapacity, liveRatio_ceil]
+ rfl
+
+theorem liveCapacity_polynomial (u : PairExponents C₂) : PolynomiallyBounded (liveCapacity u) := by
+ have hd : 0 ≤ (u.δ : ℝ) := by exact_mod_cast u.delta_pos.le
+ have hd' : (u.δ : ℝ) ≤ 1 := by exact_mod_cast (show u.δ ≤ 1 by linarith [u.theta_lt,u.delta_lt])
+ obtain ⟨N,hN⟩ := eventually_atTop.mp (eventually_bothProcessorBudgets (B := 1) (by decide) hd hd')
+ exact ((PolynomiallyBounded.const 2).mul PolynomiallyBounded.id).of_eventually_le N
+ (fun n hn => by rw [liveCapacity, liveRatio_ceil]; exact (hN n hn).1.bucket_le)
+
+/-- Any fixed number of probes fits the live bucket at sufficiently large lengths. -/
+theorem eventually_liveCapacity_ge (u : PairExponents C₂) (M : ℕ) :
+ ∀ᶠ n : ℕ in atTop, M ≤ liveCapacity u n := by
+ let x := liveRatio u
+ filter_upwards [eventually_ge_atTop ((2^x.den)^M+1)] with n hn
+ have hn0 : 0 < n := by omega
+ have hbase : 1 < 2^x.den := Nat.one_lt_two_pow x.den_pos.ne'
+ have hpow : n ≤ n^x.num := by simpa using Nat.pow_le_pow_right hn0 x.num_pos
+ have hcl : M < Nat.clog (2^x.den) (n^x.num) := (Nat.lt_clog_iff_pow_lt hbase).mpr (hn.trans hpow)
+ exact Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_right (by decide) hcl.le)
+
+private theorem n_pow_le_sites (B n : ℕ) : n^B ≤ processorCount B n := by
+ calc
+ _ ≤ (2^(Nat.clog 2 n))^B := Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) n) B
+ _ = _ := by rw [← pow_mul, Nat.mul_comm]; rfl
+
+/-- Address/counter and geometry premises in the physical local certificate,
+before any particular algebra, path or prime is chosen. -/
+theorem eventually_numeric {k : Type v} [Field k] {S : BlockSchedule k} (T : S.Templates)
+ (u : PairExponents T.growthConstant) (B a : ℕ) (hB : max S.laneBits 5 ≤ B) (ha : 1 ≤ a) :
+ ∀ᶠ n : ℕ in atTop,
+ 4 ≤ wordBits B n ∧ processorCount B n * liveCapacity u n < 2^wordBits B n ∧
+ 4*n ≤ processorCount B n ∧ n^a-1+2*addressBits B n ≤ 2*n^a ∧
+ 1 < virtualBits B n ∧ blockCount (u.θ : ℝ) n * S.laneBits ≤ virtualBits B n := by
+ have hd : 0 ≤ (u.δ : ℝ) := by exact_mod_cast u.delta_pos.le
+ have hd' : (u.δ : ℝ) ≤ 1 := by exact_mod_cast (show u.δ ≤ 1 by linarith [u.theta_lt,u.delta_lt])
+ have h5 : 5 ≤ B := (le_max_right ..).trans hB
+ filter_upwards [eventually_bothProcessorBudgets (B := B) (by omega) hd hd',
+ eventually_pairBranchBounds.{v,0} T u B hB, eventually_polylog_le (2*B) 1,
+ eventually_ge_atTop 4] with n budgets branch hsmall hn
+ have hn0 : 0 < n := by omega
+ have hrs : 2*addressBits B n ≤ n := calc
+ _ = (2*B)*Nat.clog 2 n := by rw [addressBits, addressWidth, Nat.mul_assoc]
+ _ ≤ (2*B)*(n.log2+1) := Nat.mul_le_mul_left _ (clog_le_log2_succ n)
+ _ ≤ n := by simpa only [pow_one] using hsmall
+ have height : n ≤ n^a := by simpa using Nat.pow_le_pow_right hn0 ha
+ have hR : 4*n ≤ processorCount B n := calc
+ _ ≤ n*n := Nat.mul_le_mul_right n hn
+ _ = n^2 := (sq n).symm
+ _ ≤ n^B := Nat.pow_le_pow_right hn0 (by omega)
+ _ ≤ processorCount B n := n_pow_le_sites B n
+ have hw : 4 ≤ wordBits B n := by
+ change 4 ≤ (addressBits B n+10)^4
+ nlinarith [Nat.pow_le_pow_left (by omega : 1 ≤ addressBits B n + 10) 4,
+ Nat.pow_le_pow_right (by omega : 0 < addressBits B n+10) (by decide : 1 ≤ 4)]
+ have hc := budgets.1.capFits
+ rw [liveCapacity, liveRatio_ceil]
+ exact ⟨hw,hc,hR,by omega,branch.1,branch.2.1⟩
+
+/-- Number the reserved lane coordinates after the base coordinates, using
+exactly the number consumed by the selected blocks. -/
+def laneLabels (D lanes : ℕ) (h : lanes ≤ D) : Fin D ≃ Fin (D-lanes) ⊕ Fin lanes :=
+ (finCongr (Nat.sub_add_cancel h).symm).trans (CursorNetwork.cursorCoordinateLabels (D-lanes) lanes)
+
+end LiveProgram
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseCoefficients.lean b/lean/OAI/Computability/VPVNP/ParseCoefficients.lean
new file mode 100644
index 0000000000..7313d16d23
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseCoefficients.lean
@@ -0,0 +1,157 @@
+import Mathlib.Algebra.MvPolynomial.Basic
+import Mathlib.Data.Finset.Powerset
+import Mathlib.Data.Fintype.Perm
+
+/-!
+# Extracting squarefree coefficients of parse products
+
+In §8.1 of *VP and VNP differ over every field*, each queried monomial uses each
+of its variables once. A product gate partitions those variables between its two
+ordered children. For a product of linear forms this amounts to assigning each
+leaf one queried variable, using every queried variable exactly once.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+variable {σ ι κ R : Type*} [CommSemiring R]
+
+/-- The exponent vector of the squarefree monomial supported on `s`. -/
+noncomputable def squarefreeDegree (s : Finset σ) : σ →₀ ℕ :=
+ ∑ j ∈ s, Finsupp.single j 1
+
+@[simp] theorem squarefreeDegree_apply [DecidableEq σ] (s : Finset σ) (j : σ) :
+ squarefreeDegree s j = if j ∈ s then 1 else 0 := by
+ simp [squarefreeDegree, Finsupp.finsetSum_apply, Finsupp.single_apply]
+
+@[simp] theorem support_squarefreeDegree (s : Finset σ) : (squarefreeDegree s).support = s := by
+ classical
+ ext j
+ by_cases hj : j ∈ s <;> simp [Finsupp.mem_support_iff, hj]
+
+private theorem split_squarefreeDegree [DecidableEq σ] {s : Finset σ} {a b : σ →₀ ℕ}
+ (h : a + b = squarefreeDegree s) :
+ a.support ⊆ s ∧ squarefreeDegree a.support = a ∧ squarefreeDegree (s \ a.support) = b := by
+ have hj (j : σ) : a j + b j = if j ∈ s then 1 else 0 := by
+ simpa using DFunLike.congr_fun h j
+ refine ⟨?_, Finsupp.ext fun j ↦ ?_, Finsupp.ext fun j ↦ ?_⟩
+ · intro j hj'
+ have hnon := Finsupp.mem_support_iff.mp hj'
+ by_contra hjs
+ simpa [hjs, hnon] using hj j
+ · simp only [squarefreeDegree_apply, Finsupp.mem_support_iff]
+ have := hj j
+ split at this <;> split <;> omega
+ · simp only [squarefreeDegree_apply, Finset.mem_sdiff, Finsupp.mem_support_iff]
+ have := hj j
+ by_cases hjs : j ∈ s <;> simp [hjs] at this ⊢ <;> (try split_ifs) <;> omega
+
+/-- The coefficient at a squarefree monomial of a product is a sum over subsets.
+The first factor uses exactly that subset and the second factor uses its complement. -/
+theorem coeff_mul_squarefree [DecidableEq σ] (p q : MvPolynomial σ R) (s : Finset σ) :
+ (p * q).coeff (squarefreeDegree s) =
+ ∑ t ∈ s.powerset, p.coeff (squarefreeDegree t) * q.coeff (squarefreeDegree (s \ t)) := by
+ rw [coeff_mul]
+ symm
+ refine Finset.sum_bij (fun t _ ↦ (squarefreeDegree t, squarefreeDegree (s \ t)))
+ ?_ ?_ ?_ (fun _ _ ↦ rfl)
+ · intro t ht
+ apply Finset.mem_antidiagonal.mpr
+ apply Finsupp.ext
+ intro j
+ by_cases hjt : j ∈ t
+ · simp [hjt, Finset.mem_powerset.mp ht hjt]
+ · simp [hjt]
+ · intro t _ u _ h
+ simpa using congrArg (fun x : (σ →₀ ℕ) × (σ →₀ ℕ) ↦ x.1.support) h
+ · rintro ⟨a,b⟩ h
+ obtain ⟨hsub, ha, hb⟩ := split_squarefreeDegree (Finset.mem_antidiagonal.mp h)
+ exact ⟨a.support, Finset.mem_powerset.mpr hsub, Prod.ext ha hb⟩
+
+private theorem assignment_degree_eq_iff [Fintype ι] (s : Finset σ) (f : ι → σ) :
+ (∑ i, Finsupp.single (f i) 1) = squarefreeDegree s ↔
+ ∃ e : ι ≃ ↥s, ∀ i, (e i : σ) = f i := by
+ classical
+ constructor
+ · intro h
+ have hcount (j : σ) :
+ (Finset.univ.filter (fun i ↦ f i = j)).card = if j ∈ s then 1 else 0 := by
+ have hj := DFunLike.congr_fun h j
+ simpa [squarefreeDegree_apply, Finsupp.finsetSum_apply, Finsupp.single_apply] using hj
+ have hmem (i : ι) : f i ∈ s := by
+ by_contra hnot
+ have hzero : (Finset.univ.filter (fun k ↦ f k = f i)).card = 0 := by
+ simpa [hnot] using hcount (f i)
+ have hempty := Finset.card_eq_zero.mp hzero
+ have hi : i ∈ Finset.univ.filter (fun k ↦ f k = f i) := by simp
+ simp [hempty] at hi
+ have hone (j : ↥s) : ∃! i, f i = j.val := by
+ have hc : (Finset.univ.filter (fun i ↦ f i = j.val)).card = 1 := by
+ simpa [j.property] using hcount j.val
+ simpa using Finset.card_eq_one_iff_existsUnique.mp hc
+ let g (i : ι) : ↥s := ⟨f i, hmem i⟩
+ have hb : Function.Bijective g := by
+ constructor
+ · intro a b hab
+ exact (hone (g b)).unique (congrArg Subtype.val hab) rfl
+ · intro j
+ obtain ⟨i, hi⟩ := (hone j).exists
+ exact ⟨i, Subtype.ext hi⟩
+ exact ⟨Equiv.ofBijective g hb, fun _ ↦ rfl⟩
+ · rintro ⟨e, he⟩
+ simp_rw [← he]
+ calc
+ ∑ i, Finsupp.single ((e i).val) 1 =
+ ∑ j : ↥s, Finsupp.single j.val 1 :=
+ e.sum_comp (fun j ↦ Finsupp.single j.val (1 : ℕ))
+ _ = squarefreeDegree s := by
+ simpa only [squarefreeDegree, Finset.attach_eq_univ] using
+ Finset.sum_attach s (fun j ↦ Finsupp.single j (1 : ℕ))
+
+/-- A squarefree coefficient of a product of linear forms is the sum of the
+weights of all bijections from the factors to the selected variables. -/
+theorem coeff_prod_linearForms [Fintype σ] [Fintype ι] [DecidableEq σ] [DecidableEq ι]
+ (s : Finset σ) (a : ι → σ → R) :
+ (∏ i, ∑ j, C (a i j) * X j).coeff (squarefreeDegree s) =
+ ∑ e : ι ≃ ↥s, ∏ i, a i (e i).val := by
+ classical
+ simp_rw [C_mul_X_eq_monomial]
+ rw [Fintype.prod_sum, coeff_sum]
+ simp_rw [← monomial_sum_prod, coeff_monomial]
+ rw [← Finset.sum_filter]
+ symm
+ apply Finset.sum_bij (fun (e : ι ≃ ↥s) _ ↦ fun i ↦ (e i).val)
+ · intro e _
+ exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, (assignment_degree_eq_iff _ _).mpr
+ ⟨e, fun _ ↦ rfl⟩⟩
+ · intro e _ e' _ h
+ exact Equiv.ext fun i ↦ Subtype.ext (congrFun h i)
+ · intro f hf
+ obtain ⟨e, he⟩ := (assignment_degree_eq_iff s f).mp (Finset.mem_filter.mp hf).2
+ exact ⟨e, Finset.mem_univ _, funext he⟩
+ · intro _ _
+ rfl
+
+/-- Indexed form of the leaf-bijection rule in §8.1. The query is an embedding,
+so every chosen variable occurs once even when a leaf could choose any variable
+of the ambient polynomial ring. -/
+theorem coeff_prod_linearForms_query [Fintype σ] [Fintype ι] [Fintype κ]
+ [DecidableEq σ] [DecidableEq ι] [DecidableEq κ] (query : κ ↪ σ) (a : ι → σ → R) :
+ (∏ i, ∑ j, C (a i j) * X j).coeff (∑ j, Finsupp.single (query j) 1) =
+ ∑ e : ι ≃ κ, ∏ i, a i (query (e i)) := by
+ let s := Finset.univ.map query
+ have hd : squarefreeDegree s = ∑ j, Finsupp.single (query j) 1 := by
+ simp [s, squarefreeDegree]
+ rw [← hd, coeff_prod_linearForms]
+ let u : κ ≃ ↥(Finset.univ : Finset κ) :=
+ ⟨fun j ↦ ⟨j, Finset.mem_univ j⟩, Subtype.val, fun _ ↦ rfl, fun _ ↦ rfl⟩
+ let e := u.trans (Finset.equivMap query Finset.univ)
+ exact ((Equiv.equivCongr (Equiv.refl ι) e).sum_comp
+ (fun f : ι ≃ ↥s ↦ ∏ i, a i (f i).val)).symm
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseEventBounds.lean b/lean/OAI/Computability/VPVNP/ParseEventBounds.lean
new file mode 100644
index 0000000000..c8fb231891
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseEventBounds.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.ParseIncidenceDefs
+import Mathlib.Data.Fintype.EquivFin
+import Mathlib.Data.Fintype.Prod
+import Mathlib.Data.Fintype.Sum
+
+/-! # Finite Boolean coordinates for ordered parse occurrences
+
+The coordinates bound the start, layer and binary split independently. This rectangular
+index set includes candidate productions which may be ruled out by the local grammar
+conditions. Its cardinality is polynomial in the degree cutoff and the alphabet sizes.
+A Boolean word specifies a finite table by its characteristic function on these coordinates.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+/-- An occurrence fits the coordinate table if all its numerical fields are below `D`. -/
+def ParseEvent.Bounded {V H : Type*} (e : ParseEvent V H) (D : ℕ) : Prop :=
+ e.start < D ∧ e.layer < D ∧ match e.production with
+ | .inl _ => True
+ | .inr (b, _, _) => b < D
+
+theorem ParseEvent.bounded_of_wellFormed {V H : Type*} (e : ParseEvent V H)
+ (h : e.WellFormed) {D : ℕ} (hs : e.start < D) (hl : e.layer < D) : e.Bounded D := by
+ refine ⟨hs, hl, ?_⟩
+ cases hp : e.production with
+ | inl v => trivial
+ | inr s =>
+ rcases s with ⟨b, i, j⟩
+ have hb : b < e.layer := by simpa [ParseEvent.WellFormed, hp] using h
+ exact hb.trans hl
+
+/-- A candidate event has an interval, parent state and either a terminal or a split
+together with the two ordered child states. -/
+abbrev EventCode (V H : Type*) (D : ℕ) :=
+ Fin D × Fin D × H × (V ⊕ (Fin D × H × H))
+
+namespace EventCode
+
+variable {V H : Type*} {D : ℕ}
+
+/-- Decode a candidate event by taking the natural values of its start, layer and binary split
+indices. -/
+def event (c : EventCode V H D) : ParseEvent V H :=
+ ⟨c.1, c.2.1, c.2.2.1, c.2.2.2.map id (fun (b, i, j) => (b.val, i, j))⟩
+
+theorem event_bounded (c : EventCode V H D) : c.event.Bounded D := by
+ rcases c with ⟨l, d, h, v | ⟨b, i, j⟩⟩
+ · exact ⟨l.isLt, d.isLt, trivial⟩
+ · exact ⟨l.isLt, d.isLt, b.isLt⟩
+
+/-- The coordinate tuple is recovered from the natural-valued event and its bounds. -/
+def ofEvent (e : ParseEvent V H) (he : e.Bounded D) : EventCode V H D :=
+ (⟨e.start, he.1⟩, ⟨e.layer, he.2.1⟩, e.state, match hp : e.production with
+ | .inl v => .inl v
+ | .inr (b, i, j) => .inr (⟨b, by simpa [hp] using he.2.2⟩, i, j))
+
+@[simp] theorem event_ofEvent (e : ParseEvent V H) (he : e.Bounded D) :
+ (ofEvent e he).event = e := by
+ rcases e with ⟨l, d, h, v | ⟨b, i, j⟩⟩ <;> rfl
+
+@[simp] theorem ofEvent_event (c : EventCode V H D) : ofEvent c.event (event_bounded c) = c := by
+ rcases c with ⟨l, d, h, v | ⟨b, i, j⟩⟩ <;> rfl
+
+/-- The bijection between event codes with indices in `Fin D` and parse events whose start,
+layer and binary split are below `D`. -/
+def boundedEquiv : EventCode V H D ≃ {e : ParseEvent V H // e.Bounded D} where
+ toFun c := ⟨c.event, c.event_bounded⟩
+ invFun e := ofEvent e.1 e.2
+ left_inv := ofEvent_event
+ right_inv e := Subtype.ext (event_ofEvent e.1 e.2)
+
+theorem event_injective : Function.Injective (event (V := V) (H := H) (D := D)) :=
+ fun _ _ h => boundedEquiv.injective (Subtype.ext h)
+
+variable (V H) [Fintype V] [Fintype H] (D : ℕ)
+
+theorem card : Fintype.card (EventCode V H D) =
+ D * D * Fintype.card H * (Fintype.card V + D * Fintype.card H * Fintype.card H) := by
+ simp [EventCode, Nat.mul_assoc]
+
+/-- Enumerate the rectangular coordinate set with a single finite address. -/
+noncomputable def enumerate (i : Fin (Fintype.card (EventCode V H D))) : ParseEvent V H :=
+ event ((Fintype.equivFin (EventCode V H D)).symm i)
+
+theorem enumerate_injective : Function.Injective (enumerate V H D) :=
+ event_injective.comp (Fintype.equivFin _).symm.injective
+
+theorem enumerate_bounded (i : Fin (Fintype.card (EventCode V H D))) :
+ (enumerate V H D i).Bounded D := event_bounded _
+
+theorem exists_enumerate_iff (e : ParseEvent V H) :
+ (∃ i, enumerate V H D i = e) ↔ e.Bounded D := by
+ constructor
+ · rintro ⟨i, rfl⟩
+ exact enumerate_bounded V H D i
+ · intro he
+ refine ⟨Fintype.equivFin _ (ofEvent e he), ?_⟩
+ simp [enumerate]
+
+/-- Table of all occurrences whose enumerated Boolean flags are set. -/
+noncomputable def selected (x : Fin (Fintype.card (EventCode V H D)) → Bool) :
+ Finset (ParseEvent V H) := by
+ classical
+ exact (Finset.univ.filter (fun i => x i = true)).image (enumerate V H D)
+
+theorem mem_selected (x : Fin (Fintype.card (EventCode V H D)) → Bool) (e : ParseEvent V H) :
+ e ∈ selected V H D x ↔ ∃ i, x i = true ∧ enumerate V H D i = e := by
+ classical
+ simp [selected]
+
+@[simp] theorem enumerate_mem_selected (x : Fin (Fintype.card (EventCode V H D)) → Bool)
+ (i : Fin (Fintype.card (EventCode V H D))) :
+ enumerate V H D i ∈ selected V H D x ↔ x i = true := by
+ rw [mem_selected]
+ constructor
+ · rintro ⟨j, hj, h⟩
+ exact (enumerate_injective V H D h) ▸ hj
+ · exact fun hi => ⟨i, hi, rfl⟩
+
+/-- Boolean words and bounded occurrence tables are in bijection, without additional
+bits for unused events or auxiliary witnesses. -/
+noncomputable def selectedEquiv : (Fin (Fintype.card (EventCode V H D)) → Bool) ≃
+ {T : Finset (ParseEvent V H) // ∀ e ∈ T, e.Bounded D} := by
+ classical
+ exact {
+ toFun := fun x => ⟨selected V H D x, fun e he =>
+ let ⟨i, _, hi⟩ := (mem_selected V H D x e).mp he
+ hi ▸ enumerate_bounded V H D i⟩
+ invFun := fun T i => decide (enumerate V H D i ∈ T.1)
+ left_inv := fun x => by
+ funext i
+ simp
+ right_inv := fun T => by
+ apply Subtype.ext
+ ext e
+ rw [mem_selected]
+ constructor
+ · rintro ⟨i, hi, rfl⟩
+ simpa using hi
+ · intro he
+ obtain ⟨i, hi⟩ := (exists_enumerate_iff V H D e).mpr (T.2 e he)
+ exact ⟨i, by simpa [hi] using he, hi⟩ }
+
+@[simp] theorem selectedEquiv_apply (x : Fin (Fintype.card (EventCode V H D)) → Bool) :
+ (selectedEquiv V H D x).1 = selected V H D x := rfl
+
+end EventCode
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseEventValidity.lean b/lean/OAI/Computability/VPVNP/ParseEventValidity.lean
new file mode 100644
index 0000000000..5a5322d402
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseEventValidity.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.ParseEvents
+
+/-! # Local incidence validity of an ordered parse tree
+
+Each non-root occurrence is requested by its parent, and each binary occurrence
+requests exactly the roots of its two ordered subtrees. Their disjoint leaf
+intervals give uniqueness at every occupied interval.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar.OrderedParse
+
+variable {V H : Type*}
+
+private theorem node_unique [DecidableEq V] [DecidableEq H] {r : ParseEvent V H}
+ {L R : Finset (ParseEvent V H)} {l d b : ℕ} {i j : H}
+ (hl : IsParseTable L l b i) (hr : IsParseTable R (l + b + 1) (d - b) j)
+ (hrl : r.layer = d + 1) (hb : b ≤ d)
+ (boundsL : ∀ e ∈ L, e.start + e.layer ≤ l + b ∧ e.layer ≤ b)
+ (boundsR : ∀ e ∈ R, l + b + 1 ≤ e.start ∧ e.layer ≤ d - b) :
+ ∀ e ∈ insert r (L ∪ R), ∀ f ∈ insert r (L ∪ R),
+ e.start = f.start → e.layer = f.layer → e = f := by
+ intro e he f hf hs hd
+ simp only [Finset.mem_insert, Finset.mem_union] at he hf
+ rcases he with rfl | he | he <;> rcases hf with rfl | hf | hf
+ · rfl
+ · have := (boundsL f hf).2
+ omega
+ · have := (boundsR f hf).2
+ omega
+ · have := (boundsL e he).2
+ omega
+ · exact hl.unique e he f hf hs hd
+ · have := (boundsL e he).1
+ have := (boundsR f hf).1
+ omega
+ · have := (boundsR e he).2
+ omega
+ · have := (boundsR e he).1
+ have := (boundsL f hf).1
+ omega
+ · exact hr.unique e he f hf hs hd
+
+private theorem table_node {V H : Type*} [DecidableEq V] [DecidableEq H]
+ {L R : Finset (ParseEvent V H)} {l d b : ℕ} {h i j : H}
+ (hb : b ≤ d) (hl : IsParseTable L l b i) (hr : IsParseTable R (l + b + 1) (d - b) j)
+ (boundsL : ∀ e ∈ L, e.start + e.layer ≤ l + b ∧ e.layer ≤ b)
+ (boundsR : ∀ e ∈ R, l + b + 1 ≤ e.start ∧ e.layer ≤ d - b) :
+ IsParseTable (insert ⟨l, d + 1, h, .inr (b, i, j)⟩ (L ∪ R)) l (d + 1) h := by
+ let r : ParseEvent V H := ⟨l, d + 1, h, .inr (b, i, j)⟩
+ let T := insert r (L ∪ R)
+ have rootMem : r ∈ T := Finset.mem_insert_self _ _
+ have leftSub : L ⊆ T := fun _ he => Finset.mem_insert_of_mem (Finset.mem_union_left _ he)
+ have rightSub : R ⊆ T := fun _ he => Finset.mem_insert_of_mem (Finset.mem_union_right _ he)
+ have splitMem (e : ParseEvent V H) (he : e ∈ T) : e = r ∨ e ∈ L ∨ e ∈ R := by
+ simpa only [T, Finset.mem_insert, Finset.mem_union] using he
+ have req (x k : ℕ) (a : H) : r.Requests x k a ↔
+ (x = l ∧ k = b ∧ a = i) ∨ (x = l + b + 1 ∧ k = d - b ∧ a = j) := by
+ simp only [r, ParseEvent.Requests, show d + 1 - b - 1 = d - b by omega]
+ refine ⟨⟨r, rootMem, ⟨rfl, rfl, rfl⟩⟩, ?_, ?_, ?_, ?_⟩
+ · intro e he
+ rcases splitMem e he with rfl | he | he
+ · exact Nat.lt_succ_of_le hb
+ · exact hl.typed e he
+ · exact hr.typed e he
+ · exact node_unique hl hr rfl hb boundsL boundsR
+ · intro e he x k a ha
+ rcases splitMem e he with rfl | he | he
+ · rcases (req x k a).mp ha with ⟨rfl, rfl, rfl⟩ | ⟨rfl, rfl, rfl⟩
+ · obtain ⟨f, hf, hm⟩ := hl.root
+ exact ⟨f, leftSub hf, hm⟩
+ · obtain ⟨f, hf, hm⟩ := hr.root
+ exact ⟨f, rightSub hf, hm⟩
+ · obtain ⟨f, hf, hm⟩ := hl.children e he x k a ha
+ exact ⟨f, leftSub hf, hm⟩
+ · obtain ⟨f, hf, hm⟩ := hr.children e he x k a ha
+ exact ⟨f, rightSub hf, hm⟩
+ · intro e he
+ rcases splitMem e he with rfl | he | he
+ · exact Or.inl ⟨rfl, rfl, rfl⟩
+ · right
+ rcases hl.parent e he with hm | ⟨f, hf, hm⟩
+ · exact ⟨r, rootMem, (req _ _ _).mpr (Or.inl hm)⟩
+ · exact ⟨f, leftSub hf, hm⟩
+ · right
+ rcases hr.parent e he with hm | ⟨f, hf, hm⟩
+ · exact ⟨r, rootMem, (req _ _ _).mpr (Or.inr hm)⟩
+ · exact ⟨f, rightSub hf, hm⟩
+
+/-- The interval occurrences of an ordered parse satisfy all local table conditions. -/
+theorem events_isParseTable {V H : Type*} {d : ℕ} (t : OrderedParse V H d) (l : ℕ) (h : H) :
+ IsParseTable (t.events l h) l d h := by
+ classical
+ induction t generalizing l h with
+ | leaf v =>
+ let r := (leaf v : OrderedParse V H 0).rootEvent l h
+ have mem {e : ParseEvent V H} (he : e ∈ (leaf v).events l h) : e = r := by
+ simpa only [events, Finset.mem_singleton] using he
+ refine ⟨⟨r, rootEvent_mem _ _ _, rootEvent_matches _ _ _⟩, ?_, ?_, ?_, ?_⟩
+ · intro e he
+ rw [mem he]
+ rfl
+ · intro e he f hf _ _
+ exact (mem he).trans (mem hf).symm
+ · intro e he x k a ha
+ rw [mem he] at ha
+ exact False.elim ha
+ · intro e he
+ rw [mem he]
+ exact Or.inl (rootEvent_matches _ _ _)
+ | node b i j left right ih₁ ih₂ =>
+ apply table_node (Nat.le_of_lt_succ b.isLt) (ih₁ l i) (ih₂ (l + b.val + 1) j)
+ · intro e he
+ have := left.event_bounds l i he
+ omega
+ · intro e he
+ have := right.event_bounds (l + b.val + 1) j he
+ omega
+
+end ParseGrammar.OrderedParse
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseEventWeightedCNF.lean b/lean/OAI/Computability/VPVNP/ParseEventWeightedCNF.lean
new file mode 100644
index 0000000000..14087ff2d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseEventWeightedCNF.lean
@@ -0,0 +1,53 @@
+import OAI.Computability.VPVNP.HardnessWeights
+import OAI.Computability.VPVNP.ParseEventWeights
+import OAI.Computability.VPVNP.ParseTreeBits
+
+/-! # Weighted CNF for a grammar state
+
+The incidence clauses select one Boolean assignment per ordered parse. The
+product of its selected coordinates counts every production scalar and every
+terminal variable with the multiplicity of that occurrence in the tree.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+open HardnessCNF MvPolynomial
+open scoped Classical
+
+variable {R V H : Type*} {D : ℕ}
+variable [CommSemiring R] [Fintype V] [Fintype H]
+
+private theorem weightedCNF_eq_sum_subtype {k : ℕ} (φ : CNF k) (w : Fin k → R) :
+ weightedCNF φ w = ∑ x : {x // Satisfies φ x}, ∏ i, if x.val i then w i else 1 := by
+ rw [weightedCNF, ← Finset.sum_filter]
+ exact Finset.sum_subtype _ (fun x => by simp) _
+
+private theorem prod_selected_events (w : ParseEvent V H → R)
+ (x : Fin (Fintype.card (EventCode V H D)) → Bool) :
+ ∏ e ∈ EventCode.selected V H D x, w e =
+ ∏ i, if x i then w (EventCode.enumerate V H D i) else 1 := by
+ rw [EventCode.selected, Finset.prod_image (EventCode.enumerate_injective V H D).injOn,
+ Finset.prod_filter]
+
+/-- Reindex the grammar polynomial's parse expansion by satisfying Boolean
+assignments to the incidence clauses. -/
+theorem eval_eq_weightedCNF (G : ParseGrammar R V H D) (d : Fin D) (h : H) :
+ G.eval d h = weightedCNF (incidenceCNF (EventCode.enumerate V H D) 0 d.val h)
+ (fun i => C (G.eventScalar (EventCode.enumerate V H D i)) *
+ (EventCode.enumerate V H D i).leafValue X) := by
+ rw [G.eval_eq_sum_eventWeights d h 0, weightedCNF_eq_sum_subtype,
+ ← (EventCode.satisfyingEquiv V H D d h).sum_comp]
+ apply Finset.sum_congr rfl
+ intro x _
+ rw [EventCode.events_satisfyingEquiv]
+ exact prod_selected_events _ x.val
+
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseEventWeights.lean b/lean/OAI/Computability/VPVNP/ParseEventWeights.lean
new file mode 100644
index 0000000000..05dd5f9ad2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseEventWeights.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.Classes
+import OAI.Computability.VPVNP.ParseEvents
+import OAI.Computability.VPVNP.ParseGrammar
+
+/-! # Weights of the interval events in an ordered parse
+
+Each production occurrence contributes its grammar scalar. Each leaf also contributes
+its input value. The interval coordinate distinguishes repeated occurrences of the same
+production. Consequently a product over the finite event table counts these repetitions
+with the same multiplicity as the recursive parse weight.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+open MvPolynomial OrderedParse
+
+variable {R S V H : Type*} {n : ℕ} [CommSemiring R]
+
+/-- Scalar of a terminal or binary production. A binary coordinate outside the
+layer or split bounds of the grammar receives zero. -/
+def eventScalar (G : ParseGrammar R V H n) (e : ParseEvent V H) : R :=
+ match e.production with
+ | .inl v => G.terminal e.state v
+ | .inr (b, i, j) =>
+ if hd : e.layer < n then
+ if hb : b < e.layer then G.binary ⟨e.layer, hd⟩ e.state ⟨b, hb⟩ i j else 0
+ else 0
+
+/-- Optional variable supplied by a leaf production. -/
+def ParseEvent.leafVariable? (e : ParseEvent V H) : Option V :=
+ e.production.elim some (fun _ => none)
+
+/-- A terminal contributes its input value, and a binary production contributes one. -/
+def ParseEvent.leafValue [One S] (e : ParseEvent V H) (input : V → S) : S :=
+ e.leafVariable?.elim 1 input
+
+/-- Multiplying the selected production scalars recovers the recursively defined
+parse weight, independently of the left endpoint of the root interval. -/
+theorem prod_eventScalar (G : ParseGrammar R V H n) {d : ℕ} (t : OrderedParse V H d)
+ (hd : d < n) (l : ℕ) (h : H) :
+ ∏ e ∈ t.events l h, G.eventScalar e = G.weight ⟨d, hd⟩ h t := by
+ classical
+ induction t generalizing l h with
+ | leaf v => simp [events, rootEvent, eventScalar]
+ | @node k b i j left right ih₁ ih₂ =>
+ rw [events, Finset.prod_insert (rootEvent_notMem_children b i j left right l h),
+ Finset.prod_union (disjoint_childEvents b i j left right l), weight_node]
+ have hleft := (leftDegree ⟨k + 1, hd⟩ b).isLt
+ have hright := (rightDegree ⟨k + 1, hd⟩ b).isLt
+ rw [ih₁ hleft, ih₂ hright]
+ simp [eventScalar, rootEvent, hd, b.isLt, mul_assoc, leftDegree, rightDegree]
+
+/-- The product of the leaf inputs over the event table is the product of the
+parse's left-to-right list of leaves. -/
+theorem prod_leafValue [CommMonoid S] (input : V → S) {d : ℕ} (t : OrderedParse V H d)
+ (l : ℕ) (h : H) :
+ ∏ e ∈ t.events l h, e.leafValue input = (t.leaves.map input).prod := by
+ classical
+ induction t generalizing l h with
+ | leaf v => simp [events, rootEvent, ParseEvent.leafValue, ParseEvent.leafVariable?, leaves]
+ | node b i j left right ih₁ ih₂ =>
+ rw [events, Finset.prod_insert (rootEvent_notMem_children b i j left right l h),
+ Finset.prod_union (disjoint_childEvents b i j left right l), ih₁, ih₂]
+ simp [rootEvent, ParseEvent.leafValue, ParseEvent.leafVariable?, leaves]
+
+variable [CommSemiring S]
+
+/-- Local scalar and leaf factors can be multiplied at each selected event. -/
+theorem prod_eventWeights (G : ParseGrammar R V H n) (scalar : R →+* S) (input : V → S)
+ (d : Fin n) (h : H) (t : OrderedParse V H d.val) (l : ℕ) :
+ ∏ e ∈ t.events l h, scalar (G.eventScalar e) * e.leafValue input =
+ scalar (G.weight d h t) * (t.leaves.map input).prod := by
+ rw [Finset.prod_mul_distrib, ← map_prod, prod_eventScalar G t d.isLt, prod_leafValue]
+
+/-- Evaluating the grammar is a sum of products over canonical finite event tables. -/
+theorem eval₂_eq_sum_eventWeights [Fintype V] [Fintype H] (G : ParseGrammar R V H n)
+ (scalar : R →+* S) (input : V → S) (d : Fin n) (h : H) (l : ℕ) :
+ eval₂Hom scalar input (G.eval d h) = ∑ t : OrderedParse V H d.val,
+ ∏ e ∈ t.events l h, scalar (G.eventScalar e) * e.leafValue input := by
+ rw [G.eval₂_eq_sum]
+ simp only [G.prod_eventWeights]
+
+/-- The formal state polynomial is the weighted sum of its finite event tables. -/
+theorem eval_eq_sum_eventWeights [Fintype V] [Fintype H] (G : ParseGrammar R V H n)
+ (d : Fin n) (h : H) (l : ℕ) :
+ G.eval d h = ∑ t : OrderedParse V H d.val,
+ ∏ e ∈ t.events l h, C (G.eventScalar e) * e.leafValue X := by
+ rw [G.eval_eq_sum]
+ simp only [G.prod_eventWeights]
+
+/-- In the Boolean witness sum, an output variable remains formal and a witness
+variable contributes its chosen bit as a field constant at each leaf. -/
+theorem witnessValue_eval_eq_sum_eventWeights {F : Type*} [Field F] {X W : Type}
+ [Fintype X] [Fintype W] [Fintype H] (G : ParseGrammar F (X ⊕ W) H n)
+ (bits : W → Bool) (d : Fin n) (h : H) (l : ℕ) :
+ witnessValue bits (G.eval d h) = ∑ t : OrderedParse (X ⊕ W) H d.val,
+ ∏ e ∈ t.events l h, C (G.eventScalar e) *
+ e.leafValue (Sum.elim MvPolynomial.X (fun w => C (if bits w then 1 else 0))) :=
+ G.eval₂_eq_sum_eventWeights ..
+
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseEvents.lean b/lean/OAI/Computability/VPVNP/ParseEvents.lean
new file mode 100644
index 0000000000..d257c44fc6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseEvents.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.OrderedParse
+import OAI.Computability.VPVNP.ParseIncidenceDefs
+
+/-! # Canonical interval tables of ordered parses -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar.OrderedParse
+
+variable {V H : Type*} {d : ℕ}
+
+/-- The occurrence at the root interval, including its production choice. -/
+def rootEvent : {d : ℕ} → OrderedParse V H d → ℕ → H → ParseEvent V H
+ | _, .leaf v, l, h => ⟨l, 0, h, .inl v⟩
+ | _ + 1, .node (d := d) b i j _ _, l, h => ⟨l, d + 1, h, .inr (b.val, i, j)⟩
+
+@[simp] theorem rootEvent_matches (t : OrderedParse V H d) (l : ℕ) (h : H) :
+ (t.rootEvent l h).Matches l d h := by cases t <;> exact ⟨rfl, rfl, rfl⟩
+
+open scoped Classical
+
+/-- Include the root and concatenate the two children in their leaf intervals. -/
+noncomputable def events : {d : ℕ} → OrderedParse V H d → ℕ → H → Finset (ParseEvent V H)
+ | _, .leaf v, l, h => {(.leaf v : OrderedParse V H 0).rootEvent l h}
+ | _, .node b i j left right, l, h =>
+ insert ((.node b i j left right : OrderedParse V H _).rootEvent l h)
+ (left.events l i ∪ right.events (l + b.val + 1) j)
+
+@[simp] theorem rootEvent_mem (t : OrderedParse V H d) (l : ℕ) (h : H) :
+ t.rootEvent l h ∈ t.events l h := by cases t <;> simp [events]
+
+/-- Every occupied interval is contained in the leaf interval of its ancestor. -/
+theorem event_bounds (t : OrderedParse V H d) (l : ℕ) (h : H) {e : ParseEvent V H}
+ (he : e ∈ t.events l h) : l ≤ e.start ∧ e.start + e.layer ≤ l + d := by
+ induction t generalizing l h with
+ | leaf v =>
+ simp only [events, Finset.mem_singleton] at he
+ subst e
+ simp [rootEvent]
+ | node b i j left right ih₁ ih₂ =>
+ simp only [events, Finset.mem_insert, Finset.mem_union] at he
+ rcases he with rfl | h₁ | h₂
+ · simp [rootEvent]
+ · have := ih₁ l i h₁
+ have := b.isLt
+ omega
+ · have := ih₂ (l + b.val + 1) j h₂
+ have := b.isLt
+ omega
+
+/-- The left and right subtrees have disjoint occurrences. -/
+theorem disjoint_childEvents {k : ℕ} (b : Fin (k + 1)) (i j : H)
+ (left : OrderedParse V H b.val) (right : OrderedParse V H (k - b.val)) (l : ℕ) :
+ Disjoint (left.events l i) (right.events (l + b.val + 1) j) := by
+ rw [Finset.disjoint_left]
+ intro e h₁ h₂
+ have := left.event_bounds l i h₁
+ have := right.event_bounds (l + b.val + 1) j h₂
+ omega
+
+theorem rootEvent_notMem_children {k : ℕ} (b : Fin (k + 1)) (i j : H)
+ (left : OrderedParse V H b.val) (right : OrderedParse V H (k - b.val)) (l : ℕ) (h : H) :
+ (.node b i j left right : OrderedParse V H _).rootEvent l h ∉
+ left.events l i ∪ right.events (l + b.val + 1) j := by
+ intro he
+ rcases Finset.mem_union.mp he with he | he
+ · have := left.event_bounds l i he
+ simp only [rootEvent] at this
+ have := b.isLt
+ omega
+ · have := right.event_bounds (l + b.val + 1) j he
+ simp only [rootEvent] at this
+ omega
+
+end ParseGrammar.OrderedParse
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseGrammar.lean b/lean/OAI/Computability/VPVNP/ParseGrammar.lean
new file mode 100644
index 0000000000..c7067bd302
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseGrammar.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.OrderedParse
+import Mathlib.RingTheory.MvPolynomial.Homogeneous
+
+/-!
+# Graded parse tables for arithmetic circuits
+
+Section 8.1 of *VP and VNP differ over every field* uses an ordered binary grammar to
+record a homogeneous component of a circuit output. Here the layer index `d : Fin n`
+represents degree `d.val + 1`. Each production has its own scalar, including a separate
+scalar for each choice of terminal variable.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+/-- Scalar labels on all terminals and ordered binary productions through degree `n`. -/
+structure ParseGrammar (R V H : Type*) (n : ℕ) where
+ /-- The scalar weight for emitting terminal variable `v` from state `h` in degree one. -/
+ terminal : H → V → R
+ /-- The scalar weight for a binary production at layer `d`, given its parent state, split and
+ ordered child states. -/
+ binary : (d : Fin n) → H → Fin d.val → H → H → R
+
+namespace ParseGrammar
+
+variable {R V H : Type*} {n : ℕ}
+
+/-- Layer of the left child at split `b`. Its degree is `b.val + 1`. -/
+def leftDegree (d : Fin n) (b : Fin d.val) : Fin n :=
+ ⟨b.val, b.isLt.trans d.isLt⟩
+
+/-- Layer of the right child. Its degree is the remaining `d.val - b.val`. -/
+def rightDegree (d : Fin n) (b : Fin d.val) : Fin n :=
+ ⟨d.val - 1 - b.val, by have := b.isLt; have := d.isLt; omega⟩
+
+theorem leftDegree_lt (d : Fin n) (b : Fin d.val) : (leftDegree d b).val < d.val :=
+ b.isLt
+
+theorem rightDegree_lt (d : Fin n) (b : Fin d.val) : (rightDegree d b).val < d.val := by
+ change d.val - 1 - b.val < d.val
+ have := b.isLt
+ omega
+
+theorem split_degrees (d : Fin n) (b : Fin d.val) :
+ ((leftDegree d b).val + 1) + ((rightDegree d b).val + 1) = d.val + 1 := by
+ change b.val + 1 + (d.val - 1 - b.val + 1) = d.val + 1
+ have := b.isLt
+ omega
+
+variable [Fintype V] [Fintype H] [CommSemiring R]
+
+/-- Evaluate a grammar state as a formal polynomial by multiplying the two ordered
+children of each binary production and summing over all productions. -/
+noncomputable def eval (G : ParseGrammar R V H n) (d : Fin n) (h : H) : MvPolynomial V R :=
+ if d.val = 0 then ∑ v, C (G.terminal h v) * X v
+ else ∑ b, ∑ i, ∑ j,
+ C (G.binary d h b i j) * G.eval (leftDegree d b) i * G.eval (rightDegree d b) j
+termination_by d.val
+decreasing_by
+ all_goals first | exact leftDegree_lt _ _ | exact rightDegree_lt _ _
+
+theorem eval_terminal (G : ParseGrammar R V H n) {d : Fin n} (hd : d.val = 0) (h : H) :
+ G.eval d h = ∑ v, C (G.terminal h v) * X v := by
+ rw [eval]; simp [hd]
+
+theorem eval_binary (G : ParseGrammar R V H n) {d : Fin n} (hd : d.val ≠ 0) (h : H) :
+ G.eval d h = ∑ b, ∑ i, ∑ j,
+ C (G.binary d h b i j) * G.eval (leftDegree d b) i * G.eval (rightDegree d b) j := by
+ rw [eval]; simp [hd]
+
+/-- The recursive evaluation agrees with every state table that satisfies the grammar
+equations, simultaneously for all states and positive degrees through `n`. -/
+theorem eval_eq_of_recurrence (G : ParseGrammar R V H n) (f : Fin n → H → MvPolynomial V R)
+ (hterminal : ∀ d h, d.val = 0 → f d h = ∑ v, C (G.terminal h v) * X v)
+ (hbinary : ∀ d h, d.val ≠ 0 → f d h = ∑ b, ∑ i, ∑ j,
+ C (G.binary d h b i j) * f (leftDegree d b) i * f (rightDegree d b) j)
+ (d : Fin n) (h : H) : G.eval d h = f d h := by
+ induction d using (measure (fun d : Fin n ↦ d.val)).wf.induction generalizing h with
+ | h d ih =>
+ by_cases hd : d.val = 0
+ · rw [eval_terminal _ hd, hterminal _ _ hd]
+ · rw [eval_binary _ hd, hbinary _ _ hd]
+ refine Finset.sum_congr rfl fun b _ ↦ Finset.sum_congr rfl fun i _ ↦
+ Finset.sum_congr rfl fun j _ ↦ ?_
+ rw [ih _ (leftDegree_lt d b) i, ih _ (rightDegree_lt d b) j]
+
+/-- Every state polynomial is homogeneous in the input variables of its declared degree. -/
+theorem eval_isHomogeneous (G : ParseGrammar R V H n) (d : Fin n) (h : H) :
+ (G.eval d h).IsHomogeneous (d.val + 1) := by
+ induction d using (measure (fun d : Fin n ↦ d.val)).wf.induction generalizing h with
+ | h d ih =>
+ by_cases hd : d.val = 0
+ · rw [eval_terminal _ hd, hd]
+ refine IsHomogeneous.sum _ _ _ fun v _ ↦ ?_
+ simpa using (isHomogeneous_C V (G.terminal h v)).mul (isHomogeneous_X R v)
+ · rw [eval_binary _ hd]
+ refine IsHomogeneous.sum _ _ _ fun b _ ↦ IsHomogeneous.sum _ _ _ fun i _ ↦
+ IsHomogeneous.sum _ _ _ fun j _ ↦ ?_
+ simpa [split_degrees] using
+ ((isHomogeneous_C V (G.binary d h b i j)).mul (ih _ (leftDegree_lt d b) i)).mul
+ (ih _ (rightDegree_lt d b) j)
+
+
+variable (G : ParseGrammar R V H n)
+
+/-- Multiply the terminal and internal scalar labels occurring in this ordered parse. -/
+def weight (G : ParseGrammar R V H n) (d : Fin n) (h : H) (p : OrderedParse V H d.val) : R :=
+ match d, p with
+ | ⟨0, _⟩, .leaf v => G.terminal h v
+ | ⟨k + 1, hk⟩, .node b i j l r =>
+ G.binary ⟨k + 1, hk⟩ h b i j *
+ G.weight (leftDegree ⟨k + 1, hk⟩ b) i l *
+ G.weight (rightDegree ⟨k + 1, hk⟩ b) j r
+termination_by d.val
+decreasing_by
+ all_goals first | exact leftDegree_lt _ _ | exact rightDegree_lt _ _
+
+omit [Fintype V] [Fintype H] in
+@[simp] theorem weight_leaf (hn : 0 < n) (h : H) (v : V) :
+ G.weight ⟨0, hn⟩ h (.leaf v) = G.terminal h v := by
+ rw [weight]
+
+omit [Fintype V] [Fintype H] in
+@[simp] theorem weight_node {k : ℕ} (hk : k + 1 < n) (h : H) (b : Fin (k + 1))
+ (i j : H) (l : OrderedParse V H b.val) (r : OrderedParse V H (k - b.val)) :
+ G.weight ⟨k + 1, hk⟩ h (.node b i j l r) =
+ G.binary ⟨k + 1, hk⟩ h b i j *
+ G.weight (leftDegree ⟨k + 1, hk⟩ b) i l *
+ G.weight (rightDegree ⟨k + 1, hk⟩ b) j r := by
+ rw [weight]
+
+/-- Expansion of the state polynomial as a sum over the actual ordered parse trees.
+The multiplicative terminal monomial reads the leaves in their left-to-right order. -/
+theorem eval_eq_sum (d : Fin n) (h : H) :
+ G.eval d h = ∑ p : OrderedParse V H d.val,
+ C (G.weight d h p) * (p.leaves.map (X (R := R))).prod := by
+ classical
+ apply G.eval_eq_of_recurrence
+ (fun d h ↦ ∑ p : OrderedParse V H d.val, C (G.weight d h p) * (p.leaves.map X).prod)
+ · rintro ⟨d, hd⟩ h rfl
+ rw [← (OrderedParse.leafEquiv (V := V) (H := H)).symm.sum_comp]
+ refine Finset.sum_congr rfl fun v _ ↦ ?_
+ change C (G.weight ⟨0, hd⟩ h (.leaf v)) * (List.map X [v]).prod = _
+ simp
+ · rintro ⟨k, hk⟩ h hpos
+ cases k with
+ | zero => exact (hpos rfl).elim
+ | succ k =>
+ rw [← (OrderedParse.nodeEquiv (V := V) (H := H) k).symm.sum_comp]
+ simp only [Fintype.sum_sigma, Fintype.sum_prod_type, Finset.mul_sum, Finset.sum_mul]
+ refine Finset.sum_congr rfl fun b _ ↦ Finset.sum_congr rfl fun i _ ↦
+ Finset.sum_congr rfl fun j _ ↦ ?_
+ rw [Finset.sum_comm]
+ refine Finset.sum_congr rfl fun r _ ↦ Finset.sum_congr rfl fun l _ ↦ ?_
+ change C (G.weight ⟨k+1, hk⟩ h (.node b i j l r)) *
+ (List.map X (l.leaves ++ r.leaves)).prod = _
+ simp only [weight_node, map_mul, List.map_append, List.prod_append]
+ ac_rfl
+
+/-- Evaluate the parse expansion with arbitrary terminal values and a change of scalars. -/
+theorem eval₂_eq_sum {S : Type*} [CommSemiring S] (scalar : R →+* S) (input : V → S)
+ (d : Fin n) (h : H) :
+ eval₂Hom scalar input (G.eval d h) = ∑ p : OrderedParse V H d.val,
+ scalar (G.weight d h p) * (p.leaves.map input).prod := by
+ rw [G.eval_eq_sum]
+ simp only [map_sum, map_mul, eval₂Hom_C, map_list_prod, List.map_map]
+ simp [Function.comp_def]
+
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseHistogram.lean b/lean/OAI/Computability/VPVNP/ParseHistogram.lean
new file mode 100644
index 0000000000..549fe07815
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseHistogram.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.GrammarLabels
+import OAI.Computability.VPVNP.ParseQuery
+
+/-!
+# Production histograms for ordered grammar parses
+
+In §§8.1 and 9.3 of *VP and VNP differ over every field*, each occurrence of a production
+adds one to its label's exponent. The paired-word coefficient counts an ordered tree
+together with a bijection from its leaves to the positions of the queried word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+open MvPolynomial
+
+variable {V H : Type*} {n m : ℕ}
+
+/-- The exponent of each terminal or binary production label in a given ordered parse. -/
+noncomputable def histogram (d : Fin n) (h : H) (p : OrderedParse V H d.val) :
+ GrammarLabel V H n →₀ ℕ :=
+ match d, p with
+ | ⟨0, _⟩, .leaf v => Finsupp.single (.inl (h, v)) 1
+ | ⟨k + 1, hk⟩, .node b i j left right =>
+ Finsupp.single (.inr ⟨⟨k + 1, hk⟩, h, b, i, j⟩) 1 +
+ histogram (leftDegree ⟨k + 1, hk⟩ b) i left +
+ histogram (rightDegree ⟨k + 1, hk⟩ b) j right
+termination_by d.val
+decreasing_by
+ all_goals first | exact leftDegree_lt _ _ | exact rightDegree_lt _ _
+
+/-- Every occurrence contributes its own label, and multiplication adds the occurrences. -/
+theorem universalGrammar_weight_eq_histogram (d : Fin n) (h : H) (p : OrderedParse V H d.val) :
+ (universalGrammar V H n).weight d h p = monomial (histogram d h p) (1 : ℤ) := by
+ induction d using (measure (fun d : Fin n => d.val)).wf.induction generalizing h with
+ | h d ih =>
+ obtain ⟨k, hk⟩ := d
+ cases k with
+ | zero =>
+ cases p with
+ | leaf v =>
+ rw [histogram, weight_leaf]
+ rfl
+ | succ k =>
+ cases p with
+ | node b i j l r =>
+ let d : Fin n := ⟨k + 1, hk⟩
+ rw [histogram, weight_node,
+ ih (leftDegree d b) (leftDegree_lt d b) i l,
+ ih (rightDegree d b) (rightDegree_lt d b) j r]
+ simp [universalGrammar, X, d]
+
+/-- A parse with `d.val + 1` leaves uses `d.val` internal labels and one terminal label per leaf. -/
+theorem histogram_degree (d : Fin n) (h : H) (p : OrderedParse V H d.val) :
+ (histogram d h p).degree = 2 * d.val + 1 := by
+ classical
+ have hom := universalGrammar_weight_isHomogeneous d h p
+ rw [universalGrammar_weight_eq_histogram] at hom
+ apply (hom.degree_eq_sum_deg_support (s := histogram d h p) ?_).symm
+ simp
+
+theorem histogram_sum [Fintype V] [Fintype H] (d : Fin n) (h : H) (p : OrderedParse V H d.val) :
+ ∑ label, histogram d h p label = 2 * d.val + 1 := by
+ rw [← Finsupp.degree_eq_sum, histogram_degree]
+
+/-- One of the choices counted in the coefficient query, retaining the ordered tree
+and its bijective assignment to the paired bit positions. -/
+abbrev ParseChoice (H : Type*) (d : Fin n) (x : Fin m → Bool) :=
+ Σ p : OrderedParse (Fin m × Bool) H d.val, LeafBijection p.leaves (fun i => (i, x i))
+
+/-- The query polynomial `Bₓ` is the integer sum of the histogram monomials of its parses. -/
+theorem labelQuery_eq_sum_histogram [Fintype H] (d : Fin n) (h : H) (x : Fin m → Bool) :
+ labelQuery d h x = ∑ a : ParseChoice H d x, monomial (histogram d h a.1) 1 := by
+ rw [labelQuery, coeff_eval_paired_bijections, Fintype.sum_sigma]
+ simp_rw [universalGrammar_weight_eq_histogram]
+
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseIncidence.lean b/lean/OAI/Computability/VPVNP/ParseIncidence.lean
new file mode 100644
index 0000000000..d74d6517a2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseIncidence.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.ParseEventValidity
+import Mathlib.Data.Finset.Lattice.Fold
+
+/-! # Reconstructing ordered parses from their incidence tables
+
+Starting at a selected event, follow the two child requests to build a parse. Child
+layers decrease strictly. Conversely, every selected event has a chain of parents
+ending at the root. This rules out disconnected selections and makes the encoding
+parsimonious.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+variable {V H : Type*}
+
+private theorem exists_subtree {T : Finset (ParseEvent V H)}
+ (htyped : ∀ e ∈ T, e.WellFormed)
+ (hchildren : ∀ e ∈ T, ∀ l d h, e.Requests l d h → ∃ f ∈ T, f.Matches l d h)
+ (d l : ℕ) (h : H) (hex : ∃ e ∈ T, e.Matches l d h) :
+ ∃ t : OrderedParse V H d, t.events l h ⊆ T := by
+ classical
+ induction d using Nat.strong_induction_on generalizing l h with
+ | h d ih =>
+ obtain ⟨⟨l', d', h', rule⟩, he, hm⟩ := hex
+ obtain ⟨rfl, rfl, rfl⟩ := hm
+ have hform := htyped _ he
+ rcases rule with v | ⟨b, i, j⟩
+ · change d' = 0 at hform
+ subst d'
+ exact ⟨.leaf v, by simpa [OrderedParse.events, OrderedParse.rootEvent] using he⟩
+ · change b < d' at hform
+ cases d' with
+ | zero => omega
+ | succ k =>
+ let left := hchildren _ he l' b i (Or.inl ⟨rfl, rfl, rfl⟩)
+ have rlayer : k + 1 - b - 1 = k - b := by omega
+ let right := hchildren _ he (l' + b + 1) (k - b) j (Or.inr ⟨rfl, rlayer.symm, rfl⟩)
+ obtain ⟨t₁, ht₁⟩ := ih b hform l' i left
+ obtain ⟨t₂, ht₂⟩ := ih (k - b) (by change k - b < k + 1; omega) (l' + b + 1) j right
+ refine ⟨.node ⟨b, hform⟩ i j t₁ t₂, ?_⟩
+ simpa [OrderedParse.events, OrderedParse.rootEvent] using
+ (Finset.insert_subset_iff.mpr ⟨he, Finset.union_subset ht₁ ht₂⟩)
+
+private theorem subtree_unique {T : Finset (ParseEvent V H)}
+ (hunique : ∀ e ∈ T, ∀ f ∈ T, e.start = f.start → e.layer = f.layer → e = f)
+ {d : ℕ} (t u : OrderedParse V H d) (l : ℕ) (h : H)
+ (ht : t.events l h ⊆ T) (hu : u.events l h ⊆ T) : t = u := by
+ classical
+ induction t generalizing l h with
+ | leaf v =>
+ cases u with
+ | leaf w =>
+ have eq := hunique _ (ht (OrderedParse.rootEvent_mem _ _ _)) _
+ (hu (OrderedParse.rootEvent_mem _ _ _)) rfl rfl
+ have hv := congrArg ParseEvent.production eq
+ simpa [OrderedParse.rootEvent] using hv
+ | @node k b i j left right ih₁ ih₂ =>
+ cases u with
+ | node b' i' j' left' right' =>
+ have eq := hunique _ (ht (OrderedParse.rootEvent_mem _ _ _)) _
+ (hu (OrderedParse.rootEvent_mem _ _ _)) rfl rfl
+ have hs := congrArg ParseEvent.production eq
+ simp only [OrderedParse.rootEvent, Sum.inr.injEq, Prod.mk.injEq] at hs
+ obtain ⟨hb, rfl, rfl⟩ := hs
+ have hb' : b = b' := Fin.ext hb
+ subst b'
+ simp only [OrderedParse.events, Finset.insert_subset_iff, Finset.union_subset_iff] at ht hu
+ rw [ih₁ left' l i ht.2.1 hu.2.1, ih₂ right' (l + b.val + 1) j ht.2.2 hu.2.2]
+
+private theorem requested_layer_lt {e : ParseEvent V H} (hw : e.WellFormed)
+ {l d : ℕ} {h : H} (hr : e.Requests l d h) : d < e.layer := by
+ rcases e with ⟨l', d', h', v | ⟨b, i, j⟩⟩
+ · exact hr.elim
+ · change b < d' at hw
+ obtain ⟨_, rfl, _⟩ | ⟨_, rfl, _⟩ := hr <;> dsimp <;> omega
+
+/-- If two locally valid tables have the same root and one is contained in the other,
+they coincide. Ascending parent links ends at the root because the table is finite. -/
+private theorem eq_of_valid_subset {S T : Finset (ParseEvent V H)} {l d : ℕ} {h : H}
+ (hS : IsParseTable S l d h) (hT : IsParseTable T l d h) (hst : S ⊆ T) : S = T := by
+ classical
+ apply Finset.Subset.antisymm hst
+ intro e he
+ induction e using (measure fun e : ParseEvent V H ↦ T.sup ParseEvent.layer - e.layer).wf.induction with
+ | h e ih =>
+ rcases hT.parent e he with hr | ⟨f, hf, hreq⟩
+ · obtain ⟨g, hg, hgr⟩ := hS.root
+ exact (hT.unique _ (hst hg) _ he (hgr.1.trans hr.1.symm) (hgr.2.1.trans hr.2.1.symm)) ▸ hg
+ · have hlt := requested_layer_lt (hT.typed f hf) hreq
+ have hmax := Finset.le_sup (f := ParseEvent.layer) hf
+ have hparent : f ∈ S := ih f (by change T.sup ParseEvent.layer - f.layer < T.sup ParseEvent.layer - e.layer; omega) hf
+ obtain ⟨g, hg, hgm⟩ := hS.children f hparent _ _ _ hreq
+ exact (hT.unique _ (hst hg) _ he hgm.1 hgm.2.1) ▸ hg
+
+/-- Local incidence tests give exactly one ordered parse, with one event for each
+terminal or binary production occurrence. -/
+theorem IsParseTable.existsUnique_parse {T : Finset (ParseEvent V H)} {l d : ℕ} {h : H}
+ (hT : IsParseTable T l d h) : ∃! t : OrderedParse V H d, t.events l h = T := by
+ obtain ⟨t, ht⟩ := exists_subtree hT.typed hT.children d l h hT.root
+ have heq : t.events l h = T := eq_of_valid_subset (t.events_isParseTable l h) hT ht
+ refine ⟨t, heq, fun u hu ↦ subtree_unique hT.unique u t l h ?_ ht⟩
+ rw [hu]
+
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseIncidenceCNF.lean b/lean/OAI/Computability/VPVNP/ParseIncidenceCNF.lean
new file mode 100644
index 0000000000..6189ee6aba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseIncidenceCNF.lean
@@ -0,0 +1,239 @@
+import OAI.Computability.VPVNP.ParseIncidenceDefs
+import OAI.Computability.VPVNP.HardnessCNF
+
+/-! # Boolean clauses for the local incidence of an ordered parse
+
+Each candidate production has one selection bit. Clauses require a root and both children
+of each selected split, exclude ill-typed or conflicting events, and give every nonroot
+production a parent. The clauses refer only to selection bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+open HardnessCNF
+
+variable {k : ℕ} {V H : Type*}
+
+private noncomputable def positives (p : Fin k → Prop) : List (Literal k) := by
+ classical exact ((List.finRange k).filter (fun i => decide (p i))).map (fun i => (i, true))
+
+private noncomputable def whenClause (p : Prop) (c : List (Literal k)) : CNF k := by
+ classical exact if p then [c] else []
+
+private def targets (e : ParseEvent V H) : List (ℕ × ℕ × H) :=
+ match e.production with
+ | .inl _ => []
+ | .inr (b, i, j) => [(e.start, b, i), (e.start + b + 1, e.layer - b - 1, j)]
+
+private theorem mem_targets (e : ParseEvent V H) (l d : ℕ) (h : H) :
+ (l, d, h) ∈ targets e ↔ e.Requests l d h := by
+ rcases e with ⟨a, t, s, v | ⟨b,i,j⟩⟩ <;> simp [targets, ParseEvent.Requests]
+
+/-- Clauses for a designated root and a finite enumeration of candidate productions. -/
+noncomputable def incidenceCNF (event : Fin k → ParseEvent V H) (l d : ℕ) (h : H) : CNF k :=
+ [positives (fun i => (event i).Matches l d h)] ++
+ (List.finRange k).flatMap fun i =>
+ whenClause (¬ (event i).WellFormed) [(i, false)] ++
+ ((List.finRange k).flatMap fun j =>
+ whenClause ((event i).start = (event j).start ∧ (event i).layer = (event j).layer ∧
+ event i ≠ event j) [(i, false), (j, false)]) ++
+ ((targets (event i)).map fun t =>
+ (i, false) :: positives fun j => (event j).Matches t.1 t.2.1 t.2.2) ++
+ whenClause (¬ (event i).Matches l d h) ((i, false) :: positives fun j =>
+ (event j).Requests (event i).start (event i).layer (event i).state)
+
+/-- The table whose events have selected flags. -/
+noncomputable def selectedEvents (event : Fin k → ParseEvent V H) (x : Fin k → Bool) :
+ Finset (ParseEvent V H) := by
+ classical exact (Finset.univ.filter fun i => x i = true).image event
+
+@[simp] theorem mem_selectedEvents (event : Fin k → ParseEvent V H) (x : Fin k → Bool)
+ (e : ParseEvent V H) : e ∈ selectedEvents event x ↔ ∃ i, x i = true ∧ event i = e := by
+ classical simp [selectedEvents]
+
+private def satClause (x : Fin k → Bool) (c : List (Literal k)) : Prop :=
+ ∃ a ∈ c, x a.1 = a.2
+
+private theorem sat_positives (p : Fin k → Prop) (x : Fin k → Bool) :
+ satClause x (positives p) ↔ ∃ i, p i ∧ x i = true := by
+ classical simp [satClause, positives]
+
+private theorem sat_cons_neg (i : Fin k) (c : List (Literal k)) (x : Fin k → Bool) :
+ satClause x ((i, false) :: c) ↔ (x i = true → satClause x c) := by
+ cases h : x i <;> simp [satClause, h]
+
+private theorem sat_append (p q : CNF k) (x : Fin k → Bool) :
+ Satisfies (p ++ q) x ↔ Satisfies p x ∧ Satisfies q x := by
+ simp [Satisfies]; aesop
+
+private theorem sat_flatMap {α : Type*} (s : List α) (f : α → CNF k) (x : Fin k → Bool) :
+ Satisfies (s.flatMap f) x ↔ ∀ a ∈ s, Satisfies (f a) x := by
+ simp [Satisfies]; aesop
+
+private theorem sat_map {α : Type*} (s : List α) (f : α → List (Literal k))
+ (x : Fin k → Bool) : Satisfies (s.map f) x ↔ ∀ a ∈ s, satClause x (f a) := by
+ simp [Satisfies, satClause]
+
+private theorem sat_single (c : List (Literal k)) (x : Fin k → Bool) :
+ Satisfies [c] x ↔ satClause x c := by simp [Satisfies, satClause]
+
+private theorem sat_when (p : Prop) (c : List (Literal k)) (x : Fin k → Bool) :
+ Satisfies (whenClause p c) x ↔ (p → satClause x c) := by
+ classical by_cases h : p <;> simp [whenClause, h, Satisfies, satClause]
+
+/-- The satisfying assignments select exactly the locally valid tables with the given root. -/
+theorem satisfies_incidenceCNF_iff (event : Fin k → ParseEvent V H) (l d : ℕ) (h : H)
+ (x : Fin k → Bool) :
+ Satisfies (incidenceCNF event l d h) x ↔ IsParseTable (selectedEvents event x) l d h := by
+ classical
+ simp only [incidenceCNF, sat_append, sat_flatMap, sat_map, sat_single, sat_when,
+ sat_cons_neg, sat_positives, List.mem_finRange, true_implies]
+ have empty : ¬ satClause x [] := by simp [satClause]
+ constructor
+ · rintro ⟨⟨r, hr, xr⟩, hy⟩
+ constructor
+ · exact ⟨event r, (mem_selectedEvents ..).mpr ⟨r, xr, rfl⟩, hr⟩
+ · intro e he
+ obtain ⟨i, xi, rfl⟩ := (mem_selectedEvents ..).mp he
+ exact Classical.byContradiction fun hn => empty ((hy i).1.1.1 hn xi)
+ · intro e he f hf hs ht
+ obtain ⟨i, xi, rfl⟩ := (mem_selectedEvents ..).mp he
+ obtain ⟨j, xj, rfl⟩ := (mem_selectedEvents ..).mp hf
+ exact Classical.byContradiction fun hn => empty ((hy i).1.1.2 j ⟨hs, ht, hn⟩ xi xj)
+ · intro e he a t v req
+ obtain ⟨i, xi, rfl⟩ := (mem_selectedEvents ..).mp he
+ obtain ⟨j, hj, xj⟩ := (hy i).1.2 (a,t,v) ((mem_targets ..).mpr req) xi
+ exact ⟨event j, (mem_selectedEvents ..).mpr ⟨j, xj, rfl⟩, hj⟩
+ · intro e he
+ obtain ⟨i, xi, rfl⟩ := (mem_selectedEvents ..).mp he
+ by_cases hr : (event i).Matches l d h
+ · exact Or.inl hr
+ · obtain ⟨j, hj, xj⟩ := (hy i).2 hr xi
+ exact Or.inr ⟨event j, (mem_selectedEvents ..).mpr ⟨j, xj, rfl⟩, hj⟩
+ · intro table
+ obtain ⟨e, he, hr⟩ := table.root
+ obtain ⟨i, xi, rfl⟩ := (mem_selectedEvents ..).mp he
+ refine ⟨⟨i, hr, xi⟩, fun i => ?_⟩
+ have mem (j : Fin k) (xj : x j = true) := (mem_selectedEvents event x (event j)).mpr ⟨j, xj, rfl⟩
+ refine ⟨⟨⟨?_, ?_⟩, ?_⟩, ?_⟩
+ · intro hn xi
+ exact (hn (table.typed _ (mem _ xi))).elim
+ · rintro j ⟨hs, ht, hn⟩ xi xj
+ exact (hn (table.unique _ (mem _ xi) _ (mem _ xj) hs ht)).elim
+ · rintro ⟨a,t,v⟩ hreq xi
+ obtain ⟨f, hf, hm⟩ := table.children _ (mem _ xi) a t v ((mem_targets ..).mp hreq)
+ obtain ⟨j, xj, rfl⟩ := (mem_selectedEvents ..).mp hf
+ exact ⟨j, hm, xj⟩
+ · intro hn xi
+ obtain ⟨f, hf, hr⟩ := (table.parent _ (mem _ xi)).resolve_left hn
+ obtain ⟨j, xj, rfl⟩ := (mem_selectedEvents ..).mp hf
+ exact ⟨j, hr, xj⟩
+
+
+
+@[simp] private theorem literalCount_zero : literalCount ([] : CNF k) = 0 := rfl
+
+@[simp] private theorem literalCount_singleton (c : List (Literal k)) : literalCount [c] = c.length := by
+ simp [literalCount]
+
+private theorem literalCount_append (p q : CNF k) :
+ literalCount (p ++ q) = literalCount p + literalCount q := by
+ simp [literalCount]
+
+private theorem literalCount_flatMap_le {α : Type*} (xs : List α) (f : α → CNF k) (M : ℕ)
+ (h : ∀ a ∈ xs, literalCount (f a) ≤ M) :
+ literalCount (xs.flatMap f) ≤ xs.length * M := by
+ induction xs with
+ | nil => simp
+ | cons a xs ih =>
+ have ha := h a List.mem_cons_self
+ have hx := ih (fun x hx => h x (List.mem_cons_of_mem a hx))
+ simpa [literalCount_append, Nat.succ_mul, Nat.add_comm] using Nat.add_le_add ha hx
+
+private theorem positives_length_le (p : Fin k → Prop) : (positives p).length ≤ k := by
+ classical
+ simp only [positives, List.length_map]
+ simpa using List.length_filter_le (fun i => decide (p i)) (List.finRange k)
+
+private theorem when_count_le (p : Prop) (c : List (Literal k)) :
+ literalCount (whenClause p c) ≤ c.length := by
+ classical by_cases h : p <;> simp [whenClause, h]
+
+private theorem child_count_le (e : ParseEvent V H) (i : Fin k)
+ (p : ℕ × ℕ × H → Fin k → Prop) :
+ literalCount ((targets e).map fun t => (i, false) :: positives (p t)) ≤ 2 * (k + 1) := by
+ cases he : e.production with
+ | inl _ => simp [targets, he]
+ | inr v =>
+ obtain ⟨b, j, j'⟩ := v
+ simp only [targets, he, List.map_cons, List.map_nil, literalCount, List.length_cons,
+ List.sum_cons, List.sum_nil, Nat.add_zero]
+ have h₁ := positives_length_le (p (e.start, b, j))
+ have h₂ := positives_length_le (p (e.start + b + 1, e.layer - b - 1, j'))
+ omega
+
+/-- Quadratic bound on the number of literal occurrences read by the query program. -/
+theorem literalCount_incidenceCNF_le (event : Fin k → ParseEvent V H) (l d : ℕ) (h : H) :
+ literalCount (incidenceCNF event l d h) ≤ k + k * (5 * k + 4) := by
+ classical
+ rw [incidenceCNF, literalCount_append, literalCount_singleton]
+ apply Nat.add_le_add (positives_length_le _)
+ refine (literalCount_flatMap_le _ _ (5 * k + 4) ?_).trans (by simp)
+ intro i _
+ simp only [literalCount_append]
+ have h₁ := when_count_le (¬ (event i).WellFormed) [(i, false)]
+ have h₂ := literalCount_flatMap_le (List.finRange k) (fun j =>
+ whenClause ((event i).start = (event j).start ∧ (event i).layer = (event j).layer ∧
+ event i ≠ event j) [(i, false), (j, false)]) 2
+ (fun j _ => when_count_le _ _)
+ have h₃ := child_count_le (event i) i (fun t j => (event j).Matches t.1 t.2.1 t.2.2)
+ have h₄ := when_count_le (¬ (event i).Matches l d h) ((i, false) :: positives fun j =>
+ (event j).Requests (event i).start (event i).layer (event i).state)
+ have h₅ := positives_length_le (fun j => (event j).Requests (event i).start
+ (event i).layer (event i).state)
+ simp only [List.length_cons, List.length_nil, List.length_finRange] at h₁ h₂ h₄
+ omega
+
+private theorem length_flatMap_le {α β : Type*} (xs : List α) (f : α → List β) (M : ℕ)
+ (h : ∀ a ∈ xs, (f a).length ≤ M) : (xs.flatMap f).length ≤ xs.length * M := by
+ induction xs with
+ | nil => simp
+ | cons a xs ih =>
+ have hx := ih (fun x hx => h x (List.mem_cons_of_mem a hx))
+ simpa [Nat.succ_mul, Nat.add_comm] using Nat.add_le_add (h a List.mem_cons_self) hx
+
+private theorem when_length_le (p : Prop) (c : List (Literal k)) : (whenClause p c).length ≤ 1 := by
+ classical by_cases h : p <;> simp [whenClause, h]
+
+/-- Guarding each clause costs at most this many extra literals. -/
+theorem length_incidenceCNF_le (event : Fin k → ParseEvent V H) (l d : ℕ) (h : H) :
+ (incidenceCNF event l d h).length ≤ 1 + k * (k + 4) := by
+ classical
+ rw [incidenceCNF, List.length_append]
+ apply Nat.add_le_add_left
+ refine (length_flatMap_le _ _ (k + 4) ?_).trans (by simp)
+ intro i _
+ simp only [List.length_append, List.length_map]
+ have h₁ := when_length_le (¬ (event i).WellFormed) [(i, false)]
+ have h₂ := length_flatMap_le (List.finRange k) (fun j =>
+ whenClause ((event i).start = (event j).start ∧ (event i).layer = (event j).layer ∧
+ event i ≠ event j) [(i, false), (j, false)]) 1
+ (fun j _ => when_length_le _ _)
+ have h₃ : (targets (event i)).length ≤ 2 := by
+ cases he : (event i).production with
+ | inl _ => simp [targets, he]
+ | inr v => obtain ⟨b,u,v⟩ := v; simp [targets, he]
+ have h₄ := when_length_le (¬ (event i).Matches l d h) ((i, false) :: positives fun j =>
+ (event j).Requests (event i).start (event i).layer (event i).state)
+ simp only [List.length_finRange, Nat.mul_one] at h₂
+ omega
+
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseIncidenceDefs.lean b/lean/OAI/Computability/VPVNP/ParseIncidenceDefs.lean
new file mode 100644
index 0000000000..364f67e53c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseIncidenceDefs.lean
@@ -0,0 +1,63 @@
+import Mathlib.Data.Finset.Basic
+
+/-! # Local incidence conditions for ordered grammar parses
+
+An event names a half-open interval of leaves by its starting offset and its length
+minus one. A binary event requests precisely its two ordered child intervals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+/-- A candidate production occurrence in an ordered parse, recording a leaf interval, the state
+at its root and the production used there. -/
+structure ParseEvent (V H : Type*) where
+ /-- The zero-based offset of the first leaf in the occurrence. -/
+ start : ℕ
+ /-- The length of the occurrence's leaf interval minus one. -/
+ layer : ℕ
+ /-- The grammar state at the root of the occurrence. -/
+ state : H
+ /-- The terminal variable emitted by a leaf, or the left child's layer and the ordered pair
+ of child states at a binary node. -/
+ production : V ⊕ (ℕ × H × H)
+ deriving DecidableEq
+
+variable {V H : Type*}
+
+/-- A terminal has one leaf. A binary split has two positive child lengths. -/
+def ParseEvent.WellFormed (e : ParseEvent V H) : Prop :=
+ match e.production with
+ | .inl _ => e.layer = 0
+ | .inr (b, _, _) => b < e.layer
+
+/-- An occurrence matches a requested interval and state when its start, layer and root state
+agree with all three arguments. -/
+def ParseEvent.Matches (e : ParseEvent V H) (l d : ℕ) (h : H) : Prop :=
+ e.start = l ∧ e.layer = d ∧ e.state = h
+
+/-- A binary occurrence requests its two ordered child intervals and their states. A terminal
+occurrence has no child requests. -/
+def ParseEvent.Requests (e : ParseEvent V H) (l d : ℕ) (h : H) : Prop :=
+ match e.production with
+ | .inl _ => False
+ | .inr (b, i, j) => (l = e.start ∧ d = b ∧ h = i) ∨
+ (l = e.start + b + 1 ∧ d = e.layer - b - 1 ∧ h = j)
+
+/-- Exactly one production at every occupied interval, with the designated root and
+both children of each binary production. Every other event has an incoming request. -/
+structure IsParseTable (T : Finset (ParseEvent V H)) (l d : ℕ) (h : H) : Prop where
+ root : ∃ e ∈ T, e.Matches l d h
+ typed : ∀ e ∈ T, e.WellFormed
+ unique : ∀ e ∈ T, ∀ f ∈ T, e.start = f.start → e.layer = f.layer → e = f
+ children : ∀ e ∈ T, ∀ l d h, e.Requests l d h → ∃ f ∈ T, f.Matches l d h
+ parent : ∀ e ∈ T, e.Matches l d h ∨ ∃ f ∈ T, f.Requests e.start e.layer e.state
+
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseOracleCircuit.lean b/lean/OAI/Computability/VPVNP/ParseOracleCircuit.lean
new file mode 100644
index 0000000000..a083cbc9a4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseOracleCircuit.lean
@@ -0,0 +1,187 @@
+import OAI.Computability.VPVNP.ParseOracleFlags
+import OAI.Computability.VPVNP.OracleTallyCircuit
+import OAI.Computability.VPVNP.OracleBinaryTarget
+import OAI.Computability.VPVNP.OracleCNFExpr
+import OAI.Computability.VPVNP.VerifierMachineSplice
+
+/-!
+# A polynomial-size Boolean checker for coefficient queries
+
+The query contains the input word and a fixed-width binary exponent at each
+label address. Guess bits select events. Static advice supplies the incidence
+clauses and the terminal and label tags of each event. The circuit accepts
+exactly those flags whose leaf and production tallies match the query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseOracle
+
+open ParseGrammar VerifierNetwork HardnessCNF
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit (Expr.eval Expr.size)
+open scoped Classical
+
+variable {m D k L W : ℕ} {H : Type} [Fintype H]
+/-- A paired input variable indexed by a word position and one of its two Boolean values. -/
+abbrev Var (m : ℕ) := Fin m × Bool
+/-- A terminal or binary production label for the grammar on the paired input variables through
+degree `D`. -/
+abbrev Label (m D : ℕ) (H : Type) := GrammarLabel (Var m) H D
+/-- A tally row indexed by either a paired input variable or a grammar production label. -/
+abbrev Row (m D : ℕ) (H : Type) := Var m ⊕ Label m D H
+/-- The checker input addresses for the public word and packed label exponents, followed by a
+separate address space for the guessed event flags. -/
+abbrev Input (m L W k : ℕ) := Fin (m + L * W) ⊕ Fin k
+
+/-- Public query layout, with the word first and little-endian label exponents next. -/
+def query (x : Fin m → Bool) (z : Fin L → ℕ) (W : ℕ) : Fin (m + L * W) → Bool :=
+ Fin.append x fun j ↦ let ij := finProdFinEquiv.symm j; (z ij.1).testBit ij.2.val
+
+/-- Test whether the candidate event at a flag address carries the terminal or production tag
+counted by the given row. -/
+noncomputable def mask (M : ParseOracleMetadata (Var m) H D k) :
+ Row m D H → Fin k → Bool
+ | .inl v, i => decide (M.terminal i = some v)
+ | .inr l, i => decide (M.label i = some l)
+
+/-- The queried count at each terminal and production. -/
+noncomputable def wanted (addr : Label m D H → Fin L) (x : Fin m → Bool)
+ (z : Fin L → ℕ) : Row m D H → ℕ :=
+ Sum.elim (pairedExponent x) (z ∘ addr)
+
+private def targetExpr (addr : Label m D H → Fin L) (r : Row m D H) (j : Fin (k+1)) :
+ Expr (Input m L W k) :=
+ match r with
+ | .inl (i, b) =>
+ let x : Expr (Input m L W k) := .input (.inl (Fin.castAdd (L*W) i))
+ let matchingBit := if b then x else .not x
+ if j.val = 0 then .not matchingBit else if j.val = 1 then matchingBit else .const false
+ | .inr l =>
+ OracleBinaryTarget.expr (fun t : Fin W ↦ .inl (Fin.natAdd m (finProdFinEquiv (addr l, t)))) j.val
+
+omit [Fintype H] in
+private theorem target_eval (addr : Label m D H → Fin L) (x : Fin m → Bool) (z : Fin L → ℕ)
+ (hz : ∀ l, z (addr l) < 2^W) (flags : Fin k → Bool) (r : Row m D H) (j : Fin (k+1)) :
+ (targetExpr addr r j).eval (Sum.elim (query x z W) flags) = decide (wanted addr x z r = j.val) := by
+ rcases r with ⟨i,b⟩ | l
+ · cases b <;> cases hx : x i <;> by_cases h₀ : j.val = 0 <;> by_cases h₁ : j.val = 1 <;>
+ simp [targetExpr, wanted, pairedExponent_apply, query, Expr.eval, hx, h₀, h₁] <;> omega
+ · apply OracleBinaryTarget.expr_eval _ _ _ (hz l)
+ intro i
+ simp only [Sum.elim_inl, query, Fin.append_right, Equiv.symm_apply_apply]
+
+private def initExpr (addr : Label m D H → Fin L) :
+ OracleTally.Input (Row m D H) k → Expr (Input m L W k)
+ | .inl i => .input (.inr i)
+ | .inr (r,j) => targetExpr addr r j
+
+private noncomputable def tallyInput (addr : Label m D H → Fin L) (W k : ℕ) :
+ Frame (Input m L W k) (OracleTally.Input (Row m D H) k) :=
+ (Frame.initial id).step (initExpr addr)
+
+private noncomputable def tallyFrame (M : ParseOracleMetadata (Var m) H D k)
+ (addr : Label m D H → Fin L) (W : ℕ) : Frame (Input m L W k) Unit :=
+ (OracleTally.frame (mask M)).subst (tallyInput addr W k)
+
+private def finish (M : ParseOracleMetadata (Var m) H D k) (_ : Unit) :
+ Expr (Input m L W k ⊕ Unit) :=
+ .and (.input (.inr ())) (OracleCNFExpr.formula (fun i ↦ .inl (.inr i)) M.clauses)
+
+/-- The query evaluator is independent of all actual queried exponent and word values. -/
+noncomputable def frame (M : ParseOracleMetadata (Var m) H D k)
+ (addr : Label m D H → Fin L) (W : ℕ) : Frame (Input m L W k) Unit :=
+ (tallyFrame M addr W).withInput.step (finish M)
+
+omit [Fintype H] in
+private theorem rowCount_mask (M : ParseOracleMetadata (Var m) H D k)
+ (flags : Fin k → Bool) (r : Row m D H) :
+ OracleTally.rowCount (mask M) flags r =
+ Sum.elim (tallyFlags M.terminal flags) (tallyFlags M.label flags) r := by
+ cases r <;> simp only [OracleTally.rowCount, mask, Sum.elim_inl, Sum.elim_inr,
+ tallyFlags_apply, Finset.card_filter, Bool.and_eq_true, decide_eq_true_eq, and_comm]
+
+theorem frame_eval_iff (M : ParseOracleMetadata (Var m) H D k)
+ (addr : Label m D H → Fin L) (x : Fin m → Bool) (z : Fin L → ℕ) (hz : ∀ l, z (addr l) < 2^W)
+ (e : Label m D H →₀ ℕ) (he : ∀ l, z (addr l) = e l) (flags : Fin k → Bool) :
+ (frame M addr W).eval (Sum.elim (query x z W) flags) () = true ↔
+ M.Accepts (pairedExponent x) e flags := by
+ let bits := Sum.elim (query x z W) flags
+ have hi : (tallyInput addr W k).eval bits =
+ Sum.elim flags (Function.uncurry fun r j ↦ decide (wanted addr x z r = j.val)) := by
+ funext i
+ cases i with
+ | inl i => simp [tallyInput, initExpr, Expr.eval, bits]
+ | inr ij =>
+ have hi0 : (Frame.initial (id : Input m L W k → _)).eval bits = bits :=
+ funext fun _ ↦ Frame.initial_eval ..
+ rw [tallyInput, Frame.step_eval, hi0]
+ exact target_eval addr x z hz flags ij.1 ij.2
+ change (frame M addr W).eval bits () = true ↔ _
+ rw [frame, Frame.step_eval]
+ simp only [finish, Expr.eval, Bool.and_eq_true, Frame.withInput_eval_inr, OracleCNFExpr.formula_eval_iff]
+ have hflags : (tallyFrame M addr W).withInput.eval bits ∘ (fun i : Fin k ↦ .inl (.inr i)) = flags := by
+ funext i
+ simp [bits]
+ rw [hflags, tallyFrame, Frame.subst_eval, hi, OracleTally.frame_eval_iff,
+ OracleTally.rowCountsOK_oneHot_iff]
+ simp only [rowCount_mask, wanted, Sum.forall, Sum.elim_inl, Sum.elim_inr,
+ Function.comp_apply, he, ParseOracleMetadata.Accepts, DFunLike.ext_iff]
+ tauto
+
+omit [Fintype H] in
+private theorem init_size_le (addr : Label m D H → Fin L) (u : OracleTally.Input (Row m D H) k) :
+ (initExpr (W := W) addr u).size ≤ W*3 + 3 := by
+ rcases u with i | ⟨r,j⟩
+ · change 1 ≤ _; omega
+ · cases r with
+ | inl v =>
+ rcases v with ⟨i,b⟩
+ cases b <;> by_cases h₀ : j.val = 0 <;> by_cases h₁ : j.val = 1 <;>
+ simp [initExpr, targetExpr, h₀, h₁, Expr.size]
+ | inr l => exact (OracleBinaryTarget.expr_size_le _ _).trans (by omega)
+
+/-- The frame size is polynomial in the static flag count, row count, exponent
+word width, and length of the incidence formula. -/
+theorem frame_size_le (M : ParseOracleMetadata (Var m) H D k)
+ (addr : Label m D H → Fin L) (W : ℕ) :
+ let r := Fintype.card (Row m D H)
+ (frame M addr W).size ≤
+ ((k + r*(k+1))*(W*3+3) + (k + r*(k+1)) + k*((k+r*(k+1))*8) +
+ (r*(k+1)*10+2) + (3*literalCount M.clauses + 3*M.clauses.length+4)) := by
+ have hinit := Frame.step_size_le (Frame.initial (id : Input m L W k → _)) (initExpr addr)
+ (W*3+3) (fun u ↦ init_size_le addr u)
+ have hin : Fintype.card (OracleTally.Input (Row m D H) k) =
+ k + Fintype.card (Row m D H)*(k+1) := by
+ change Fintype.card (Fin k ⊕ Row m D H × Fin (k+1)) = _
+ rw [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin, Fintype.card_fin]
+ rw [Frame.initial_size, zero_add, hin] at hinit
+ change (tallyInput addr W k).size ≤ _ at hinit
+ have hscan := OracleTally.frame_size_le (mask M)
+ have hfinish := Frame.step_size_le (tallyFrame M addr W).withInput (finish M)
+ (3*literalCount M.clauses+3*M.clauses.length+4) (by
+ intro i
+ have h := OracleCNFExpr.formula_size_le (W := Input m L W k ⊕ Unit) (fun j ↦ .inl (.inr j)) M.clauses
+ change 1 + _ + 1 ≤ _
+ omega)
+ simp only [Frame.withInput_size, tallyFrame, Frame.subst_size,
+ Fintype.card_unit, one_mul] at hfinish
+ change (frame M addr W).size ≤ _ at hfinish
+ omega
+
+/-- The circuit size is polynomial in the static flag count, row count, exponent
+word width, and length of the incidence formula. -/
+theorem circuitSize_le (M : ParseOracleMetadata (Var m) H D k)
+ (addr : Label m D H → Fin L) (W : ℕ) :
+ let r := Fintype.card (Row m D H)
+ (frame M addr W).circuitSize () ≤ 4 *
+ ((k + r*(k+1))*(W*3+3) + (k + r*(k+1)) + k*((k+r*(k+1))*8) +
+ (r*(k+1)*10+2) + (3*literalCount M.clauses + 3*M.clauses.length+4)) :=
+ ((frame M addr W).circuitSize_le ()).trans (Nat.mul_le_mul_left _ (frame_size_le M addr W))
+
+end ParseOracle
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseOracleFlags.lean b/lean/OAI/Computability/VPVNP/ParseOracleFlags.lean
new file mode 100644
index 0000000000..62cae21803
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseOracleFlags.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.GrammarCoefficientBounds
+import OAI.Computability.VPVNP.ParseTreeBits
+import OAI.Computability.VPVNP.ParseEventWeights
+
+/-!
+# A fixed flag table for the integer label coefficient oracle
+
+In §8.1 each coefficient of `Bₓ` counts ordered parses with the requested leaves
+and production multiplicities. The same incidence clauses and the same two columns
+of event tags work for every word `x` and every nominated exponent vector.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+open OrderedParse HardnessCNF
+open scoped Classical
+
+variable {V H α : Type*} {D m k : ℕ}
+
+/-- One unit of multiplicity for a tag, or zero for an absent tag. -/
+noncomputable def tagUnit (tag : Option α) : α →₀ ℕ :=
+ tag.elim 0 (fun a ↦ Finsupp.single a 1)
+
+/-- Count occurrences by scanning the selected coordinates of a single tag column. -/
+noncomputable def tallyFlags (tags : Fin k → Option α) (flags : Fin k → Bool) : α →₀ ℕ :=
+ ∑ i, if flags i then tagUnit (tags i) else 0
+
+/-- At each coordinate the tally is the number of selected flags carrying that tag. -/
+theorem tallyFlags_apply [DecidableEq α] (tags : Fin k → Option α) (flags : Fin k → Bool) (a : α) :
+ tallyFlags tags flags a = (Finset.univ.filter fun i ↦ flags i = true ∧ tags i = some a).card := by
+ rw [tallyFlags, Finsupp.finsetSum_apply, Finset.card_filter]
+ refine Finset.sum_congr rfl fun i _ ↦ ?_
+ cases flags i <;> cases tags i <;> simp [tagUnit, Finsupp.single_apply]
+
+/-- Production label of an event in the finite rectangular table. A binary event
+outside the degree or split range has no label. -/
+def ParseEvent.grammarLabel? (D : ℕ) (event : ParseEvent V H) : Option (GrammarLabel V H D) :=
+ match event.production with
+ | .inl v => some (.inl (event.state, v))
+ | .inr (b, i, j) =>
+ if hd : event.layer < D then
+ if hb : b < event.layer then some (.inr ⟨⟨event.layer, hd⟩, event.state, ⟨b, hb⟩, i, j⟩)
+ else none
+ else none
+
+/-- The fixed advice used for the flag count. The two tag columns depend only on
+the candidate event. The clauses additionally fix the root layer and state. -/
+structure ParseOracleMetadata (V H : Type*) (D k : ℕ) where
+ /-- The fixed CNF constraints on candidate event flags used to check parse incidence. -/
+ clauses : CNF k
+ /-- The optional terminal-variable tag counted when the flag at this address is selected. -/
+ terminal : Fin k → Option V
+ /-- The optional grammar production label counted when the flag at this address is selected. -/
+ label : Fin k → Option (GrammarLabel V H D)
+
+/-- Incidence plus the two queried multiplicities. No auxiliary Boolean witnesses
+are introduced by the two counts. -/
+def ParseOracleMetadata.Accepts (M : ParseOracleMetadata V H D k) (input : V →₀ ℕ)
+ (e : GrammarLabel V H D →₀ ℕ) (flags : Fin k → Bool) : Prop :=
+ Satisfies M.clauses flags ∧ tallyFlags M.terminal flags = input ∧ tallyFlags M.label flags = e
+
+/-- Enumerate candidate events and attach their terminal and production tags, with incidence
+clauses rooted at offset zero, layer `d` and state `h`. -/
+noncomputable def parseOracleMetadata (V H : Type*) [Fintype V] [Fintype H] (D : ℕ)
+ (d : Fin D) (h : H) : ParseOracleMetadata V H D (Fintype.card (EventCode V H D)) where
+ clauses := incidenceCNF (EventCode.enumerate V H D) 0 d.val h
+ terminal i := (EventCode.enumerate V H D i).leafVariable?
+ label i := (EventCode.enumerate V H D i).grammarLabel? D
+
+private theorem sum_terminal_events {t : ℕ} (p : OrderedParse V H t) (l : ℕ) (h : H) :
+ ∑ e ∈ p.events l h, tagUnit e.leafVariable? = (p.leaves.map fun v ↦ Finsupp.single v 1).sum := by
+ induction p generalizing l h with
+ | leaf v => simp [events, rootEvent, leaves, ParseEvent.leafVariable?, tagUnit]
+ | node b i j left right ih₁ ih₂ =>
+ rw [events, Finset.sum_insert (rootEvent_notMem_children b i j left right l h),
+ Finset.sum_union (disjoint_childEvents b i j left right l), ih₁, ih₂]
+ simp [rootEvent, leaves, ParseEvent.leafVariable?, tagUnit]
+
+private theorem sum_label_events {t : ℕ} (p : OrderedParse V H t) (hd : t < D) (l : ℕ) (h : H) :
+ ∑ e ∈ p.events l h, tagUnit (e.grammarLabel? D) = histogram ⟨t, hd⟩ h p := by
+ induction p generalizing l h with
+ | leaf v => simp [events, rootEvent, histogram, ParseEvent.grammarLabel?, tagUnit]
+ | @node t b i j left right ih₁ ih₂ =>
+ rw [events, Finset.sum_insert (rootEvent_notMem_children b i j left right l h),
+ Finset.sum_union (disjoint_childEvents b i j left right l), histogram]
+ rw [ih₁ (leftDegree ⟨t+1, hd⟩ b).isLt, ih₂ (rightDegree ⟨t+1, hd⟩ b).isLt]
+ simp [rootEvent, ParseEvent.grammarLabel?, tagUnit, hd, b.isLt, leftDegree, rightDegree,
+ add_assoc]
+
+variable [Fintype V] [Fintype H]
+
+private theorem tally_enumerate (tags : ParseEvent V H → Option α)
+ (z : Fin (Fintype.card (EventCode V H D)) → Bool) :
+ tallyFlags (fun i ↦ tags (EventCode.enumerate V H D i)) z =
+ ∑ e ∈ EventCode.selected V H D z, tagUnit (tags e) := by
+ rw [EventCode.selected, Finset.sum_image (EventCode.enumerate_injective V H D).injOn,
+ Finset.sum_filter]
+ rfl
+
+private theorem tally_satisfying (d : Fin D) (h : H)
+ (z : {z // Satisfies (incidenceCNF (EventCode.enumerate V H D) 0 d.val h) z}) :
+ let p := EventCode.satisfyingEquiv V H D d h z
+ let M := parseOracleMetadata V H D d h
+ tallyFlags M.terminal z.val = (p.leaves.map fun v ↦ Finsupp.single v 1).sum ∧
+ tallyFlags M.label z.val = histogram d h p := by
+ dsimp only [parseOracleMetadata]
+ rw [tally_enumerate, tally_enumerate, ← EventCode.events_satisfyingEquiv V H D d h z]
+ exact ⟨sum_terminal_events _ _ _, sum_label_events _ d.isLt _ _⟩
+
+/-- The integer coefficient equals the count of passing flag words, with one such
+word for each matching ordered parse. The metadata are fixed independently of both
+arguments of the oracle, `x` and `e`. -/
+theorem coeff_labelQuery_eq_flagCount (d : Fin D) (h : H) (x : Fin m → Bool)
+ (e : GrammarLabel (Fin m × Bool) H D →₀ ℕ) :
+ (labelQuery d h x).coeff e =
+ ((Finset.univ.filter ((parseOracleMetadata (Fin m × Bool) H D d h).Accepts
+ (pairedExponent x) e)).card : ℤ) := by
+ let V := Fin m × Bool
+ let E := EventCode.satisfyingEquiv V H D d h
+ let M := parseOracleMetadata V H D d h
+ have hcheck (z : {z // Satisfies M.clauses z}) : M.Accepts (pairedExponent x) e z.val ↔
+ ((E z).leaves : Multiset V) = (List.ofFn (fun i ↦ (i, x i)) : Multiset V) ∧
+ histogram d h (E z) = e := by
+ obtain ⟨ht, hl⟩ := tally_satisfying d h z
+ change (Satisfies M.clauses z.val ∧ tallyFlags M.terminal z.val = pairedExponent x ∧
+ tallyFlags M.label z.val = e) ↔ _
+ rw [ht, hl, pairedExponent, terminalExponents_eq_query_iff]
+ exact and_iff_right z.property
+ rw [coeff_labelQuery_eq_card]
+ congr 1
+ symm
+ refine Finset.card_bij
+ (fun z hz ↦ E ⟨z, (Finset.mem_filter.mp hz).2.1⟩) ?_ ?_ ?_
+ · intro z hz
+ have ha := (Finset.mem_filter.mp hz).2
+ exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, (hcheck ⟨z, ha.1⟩).mp ha⟩
+ · intro z _ w _ heq
+ exact congrArg Subtype.val (E.injective heq)
+ · intro p hp
+ let z := E.symm p
+ have hpass : M.Accepts (pairedExponent x) e z.val := by
+ apply (hcheck z).mpr
+ simpa [z] using (Finset.mem_filter.mp hp).2
+ exact ⟨z.val, Finset.mem_filter.mpr ⟨Finset.mem_univ _, hpass⟩, E.apply_symm_apply p⟩
+
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseOracleResources.lean b/lean/OAI/Computability/VPVNP/ParseOracleResources.lean
new file mode 100644
index 0000000000..4b8543a7a2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseOracleResources.lean
@@ -0,0 +1,202 @@
+import OAI.Computability.VPVNP.ParseOracleRun
+import OAI.Computability.VPVNP.GrammarSize
+import OAI.Computability.VPVNP.SpaceRunMonotone
+
+/-!
+# Resource bounds for the grammar coefficient checker
+
+At length `n` the grammar of §8.1 has `n^(C+5)` states at each positive degree.
+The bounds below are uniform over the root state and layer and over the placement
+of grammar labels in the joint parameter list. The word and exponent values are
+runtime inputs. They do not contribute to the advice length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseOracle
+
+open ParseGrammar UniversalCountStack
+
+/-- The `n^(C+5)` states available at each positive degree of the length-`n` parse grammar. -/
+abbrev States (C n : ℕ) := Fin (n ^ (C + 5))
+
+/-- Number of independently enumerated event flags, including invalid events that
+the fixed incidence clauses force to zero. -/
+def flagCount (C n : ℕ) : ℕ :=
+ let S := n ^ (C + 5)
+ n * n * S * (n * 2 + n * S * S)
+
+theorem flags_eq_flagCount (C n : ℕ) : Flags n n (States C n) = flagCount C n := by
+ simpa only [States, Var, Fintype.card_prod, Fintype.card_bool, Fintype.card_fin, flagCount] using
+ EventCode.card (Var n) (States C n) n
+
+/-- There is one tally row for each terminal variable and each grammar label. -/
+def rowBound (C n : ℕ) : ℕ :=
+ let S := n ^ (C + 5)
+ n * 2 + (S * (n * 2) + n ^ 2 * S ^ 3)
+
+theorem card_row_le (C n : ℕ) : Fintype.card (Row n n (States C n)) ≤ rowBound C n := by
+ change Fintype.card (Var n ⊕ Label n n (States C n)) ≤ _
+ rw [Fintype.card_sum]
+ apply Nat.add_le_add
+ · simp [Var]
+ · simpa only [States, Var, Fintype.card_prod, Fintype.card_bool, Fintype.card_fin] using
+ card_grammarLabel_le (Var n) (States C n) n
+
+/-- Bound on the AND/NOT circuit gates for the queried exponent width. -/
+def gateBound (C n W : ℕ) : ℕ :=
+ let k := flagCount C n
+ let r := rowBound C n
+ let wires := k + r * (k+1)
+ 4 * (wires * (W*3+3) + wires + k*(wires*8) + (r*(k+1)*10+2) +
+ (3*(k+k*(5*k+4)) + 3*(1+k*(k+4)) + 4))
+
+/-- Length of the compiled gate stream, including its unary addresses. -/
+def adviceBound (C n L W : ℕ) : ℕ :=
+ let g := gateBound C n W
+ (g+2) * (2*(g+(n+L*W)+flagCount C n+2)+3)
+
+/-- Uniform instruction budget for one choice of the event flags. -/
+def choiceBound (C n L W : ℕ) : ℕ :=
+ let k := flagCount C n
+ 32 * (adviceBound C n L W + (gateBound C n W+2) + (n+L*W) + k + 1) + 8*k + 9
+
+/-- Bounds the height of every stack throughout enumeration. -/
+def stackBound (C n L W : ℕ) : ℕ :=
+ (n+L*W) + adviceBound C n L W + (flagCount C n+1) + choiceBound C n L W
+
+/-- A polynomial exponent bounding the time to enumerate all flags. -/
+def timeExponent (C n L W : ℕ) : ℕ := flagCount C n + choiceBound C n L W
+
+variable {C n L : ℕ} (d : Fin n) (h : States C n)
+ (addr : Label n n (States C n) → Fin L) (W : ℕ)
+
+theorem checker_frame_size_le :
+ 4 * (frame (parseOracleMetadata (Var n) (States C n) n d h) addr W).size ≤
+ gateBound C n W := by
+ let M := parseOracleMetadata (Var n) (States C n) n d h
+ apply (Nat.mul_le_mul_left 4 (frame_size_le M addr W)).trans
+ have hl : HardnessCNF.literalCount M.clauses ≤
+ flagCount C n + flagCount C n * (5 * flagCount C n + 4) := by
+ rw [← flags_eq_flagCount]
+ exact literalCount_incidenceCNF_le _ _ _ _
+ have hc : M.clauses.length ≤ 1 + flagCount C n * (flagCount C n + 4) := by
+ rw [← flags_eq_flagCount]
+ exact length_incidenceCNF_le _ _ _ _
+ dsimp only [gateBound]
+ have hk : Fintype.card (EventCode (Var n) (States C n) n) ≤ flagCount C n := (flags_eq_flagCount ..).le
+ gcongr <;> exact card_row_le ..
+
+theorem checker_gates_le :
+ (frame (parseOracleMetadata (Var n) (States C n) n d h) addr W).circuitSize () ≤
+ gateBound C n W :=
+ ((frame (parseOracleMetadata (Var n) (States C n) n d h) addr W).circuitSize_le ()).trans
+ (checker_frame_size_le d h addr W)
+
+theorem checker_advice_le : (AdviceCircuit.encode (AdviceCircuit.compile (checker d h addr W))).length ≤
+ adviceBound C n L W := by
+ apply (AdviceCircuit.compile_size _).trans
+ dsimp only [adviceBound]
+ change (_+2) * (2*(_+(n+L*W)+Flags n n (States C n)+2)+3) ≤ _
+ rw [flags_eq_flagCount]
+ gcongr <;> exact checker_gates_le d h addr W
+
+theorem checker_perChoice_le : perChoice (checker d h addr W) ≤ choiceBound C n L W := by
+ dsimp only [perChoice, choiceBound]
+ rw [AdviceCircuit.compile_length]
+ have hk : Fintype.card (EventCode (Var n) (States C n) n) ≤ flagCount C n := (flags_eq_flagCount ..).le
+ have ha := checker_advice_le d h addr W
+ have hg := checker_gates_le d h addr W
+ omega
+
+theorem checker_stackLimit_le : stackLimit (checker d h addr W) ≤ stackBound C n L W := by
+ have ha := checker_advice_le d h addr W
+ have hc := checker_perChoice_le d h addr W
+ dsimp only [stackLimit, stackBound]
+ have hk : Fintype.card (EventCode (Var n) (States C n) n) ≤ flagCount C n := (flags_eq_flagCount ..).le
+ omega
+
+theorem checker_time_le :
+ 2^(Flags n n (States C n)) * perChoice (checker d h addr W) ≤ 2^(timeExponent C n L W) := by
+ conv_rhs => rw [timeExponent, pow_add]
+ exact Nat.mul_le_mul (Nat.pow_le_pow_right (by decide) (flags_eq_flagCount C n).le)
+ ((checker_perChoice_le d h addr W).trans Nat.lt_two_pow_self.le)
+
+/-- Run the actual checker on the joint query, with bounds independent of the
+choice of layer, root state, address map, and queried values. -/
+theorem coefficient_query_runs_bounded (x : Fin n → Bool) (z : Fin L → ℕ)
+ (hz : ∀ l, z (addr l) < 2^W) (e : Label n n (States C n) →₀ ℕ)
+ (he : ∀ l, z (addr l) = e l) :
+ let c := checker d h addr W
+ let k := Flags n n (States C n)
+ let aux := scalarInputs c (query x z W)
+ ∃ t ≤ 2^(timeExponent C n L W),
+ SpaceRun countCircuit.standalone (stackBound C n L W) t (some countCircuit.entry)
+ (bank aux (digits k 0) (digits (k+1) 0) [] []) none
+ (bank aux (digits k 0) (digits (k+1) ((labelQuery d h x).coeff e).toNat) [] []) := by
+ obtain ⟨t, ht, hr⟩ := coefficient_query_runs d h addr x z hz e he
+ exact ⟨t, ht.trans (checker_time_le d h addr W), hr.mono_cap (checker_stackLimit_le d h addr W)⟩
+
+theorem flagCount_polynomial (C : ℕ) : PolynomiallyBounded (flagCount C) := by
+ let hn := PolynomiallyBounded.id
+ let hS := hn.pow (C+5)
+ exact ((hn.mul hn).mul hS).mul ((hn.mul (.const 2)).add ((hn.mul hS).mul hS))
+
+theorem rowBound_polynomial (C : ℕ) : PolynomiallyBounded (rowBound C) := by
+ let hn := PolynomiallyBounded.id
+ let hS := hn.pow (C+5)
+ let hV := hn.mul (.const 2)
+ exact hV.add ((hS.mul hV).add ((hn.pow 2).mul (hS.pow 3)))
+
+variable {width labels : ℕ → ℕ}
+
+theorem gateBound_polynomial (C : ℕ) (hW : PolynomiallyBounded width) :
+ PolynomiallyBounded (fun n ↦ gateBound C n (width n)) := by
+ let hk := flagCount_polynomial C
+ let hr := rowBound_polynomial C
+ let cells := hr.mul (hk.add (.const 1))
+ let wires := hk.add cells
+ let hLit := hk.add (hk.mul (((PolynomiallyBounded.const 5).mul hk).add (.const 4)))
+ let hLen := (PolynomiallyBounded.const 1).add (hk.mul (hk.add (.const 4)))
+ let hCNF := (((PolynomiallyBounded.const 3).mul hLit).add
+ ((PolynomiallyBounded.const 3).mul hLen)).add (.const 4)
+ exact (PolynomiallyBounded.const 4).mul
+ (((((wires.mul ((hW.mul (.const 3)).add (.const 3))).add wires).add
+ (hk.mul (wires.mul (.const 8)))).add ((cells.mul (.const 10)).add (.const 2))).add hCNF)
+
+theorem adviceBound_polynomial (C : ℕ) (hL : PolynomiallyBounded labels)
+ (hW : PolynomiallyBounded width) :
+ PolynomiallyBounded (fun n ↦ adviceBound C n (labels n) (width n)) := by
+ let hg := gateBound_polynomial C hW
+ let hu := PolynomiallyBounded.id.add (hL.mul hW)
+ let total := ((hg.add hu).add (flagCount_polynomial C)).add (.const 2)
+ exact (hg.add (.const 2)).mul (((PolynomiallyBounded.const 2).mul total).add (.const 3))
+
+theorem choiceBound_polynomial (C : ℕ) (hL : PolynomiallyBounded labels)
+ (hW : PolynomiallyBounded width) :
+ PolynomiallyBounded (fun n ↦ choiceBound C n (labels n) (width n)) := by
+ let hk := flagCount_polynomial C
+ let hu := PolynomiallyBounded.id.add (hL.mul hW)
+ let ha := adviceBound_polynomial C hL hW
+ let hg := (gateBound_polynomial C hW).add (.const 2)
+ exact (((PolynomiallyBounded.const 32).mul ((((ha.add hg).add hu).add hk).add (.const 1))).add
+ ((PolynomiallyBounded.const 8).mul hk)).add (.const 9)
+
+theorem stackBound_polynomial (C : ℕ) (hL : PolynomiallyBounded labels)
+ (hW : PolynomiallyBounded width) :
+ PolynomiallyBounded (fun n ↦ stackBound C n (labels n) (width n)) :=
+ (((PolynomiallyBounded.id.add (hL.mul hW)).add (adviceBound_polynomial C hL hW)).add
+ ((flagCount_polynomial C).add (.const 1))).add (choiceBound_polynomial C hL hW)
+
+theorem timeExponent_polynomial (C : ℕ) (hL : PolynomiallyBounded labels)
+ (hW : PolynomiallyBounded width) :
+ PolynomiallyBounded (fun n ↦ timeExponent C n (labels n) (width n)) :=
+ (flagCount_polynomial C).add (choiceBound_polynomial C hL hW)
+
+end ParseOracle
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseOracleRun.lean b/lean/OAI/Computability/VPVNP/ParseOracleRun.lean
new file mode 100644
index 0000000000..62a5fea30a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseOracleRun.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.ParseOracleCircuit
+import OAI.Computability.VPVNP.UniversalCountQuery
+
+/-!
+# Deterministic stack execution of the grammar coefficient query
+
+One fixed bit-stack control enumerates event flags and evaluates the advised circuit
+on the word and binary histogram coordinates. The output stack contains the full
+integer coefficient in little-endian binary. The supplied advice depends on the
+table dimensions, root and coordinate ordering, independently of the queried values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseOracle
+
+open ParseGrammar UniversalCountStack RAMTape
+
+variable {m D L W : ℕ} {H : Type} [Fintype H]
+open scoped Classical
+
+/-- The number of candidate event flags, one for each bounded event code on the paired
+variables and grammar states. -/
+abbrev Flags (m D : ℕ) (H : Type) [Fintype H] := Fintype.card (EventCode (Var m) H D)
+
+/-- Circuit supplied as advice. Its ordered gate stream is independent of both
+the input word and the queried monomial. -/
+noncomputable def checker (d : Fin D) (h : H) (addr : Label m D H → Fin L) (W : ℕ) :=
+ (frame (parseOracleMetadata (Var m) H D d h) addr W).circuit ()
+
+theorem count_checker (d : Fin D) (h : H) (addr : Label m D H → Fin L)
+ (x : Fin m → Bool) (z : Fin L → ℕ) (hz : ∀ l, z (addr l) < 2^W)
+ (e : Label m D H →₀ ℕ) (he : ∀ l, z (addr l) = e l) :
+ (∑ flags, ((checker d h addr W).eval (Sum.elim (query x z W) flags)).toNat) =
+ ((labelQuery d h x).coeff e).toNat := by
+ let M := parseOracleMetadata (Var m) H D d h
+ rw [coeff_labelQuery_eq_flagCount, Int.toNat_natCast, Finset.card_filter]
+ refine Finset.sum_congr rfl fun flags _ ↦ ?_
+ have ok : (checker d h addr W).eval (Sum.elim (query x z W) flags) = true ↔
+ M.Accepts (pairedExponent x) e flags := by
+ rw [checker, VerifierNetwork.Frame.circuit_eval]
+ exact frame_eval_iff M addr x z hz e he flags
+ cases hb : (checker d h addr W).eval (Sum.elim (query x z W) flags) <;> simp [hb] at ok
+ · simp only [M] at ok; simp [ok]
+ · simp only [M] at ok; simp [ok]
+
+/-- Space and per-candidate time hold along every intermediate machine step.
+The accepting flags are counted once each, including when several have the
+same histogram. -/
+theorem coefficient_query_runs (d : Fin D) (h : H) (addr : Label m D H → Fin L)
+ (x : Fin m → Bool) (z : Fin L → ℕ) (hz : ∀ l, z (addr l) < 2^W)
+ (e : Label m D H →₀ ℕ) (he : ∀ l, z (addr l) = e l) :
+ let c := checker d h addr W
+ let k := Flags m D H
+ let aux := scalarInputs c (query x z W)
+ ∃ t ≤ 2^k * perChoice c,
+ SpaceRun countCircuit.standalone (stackLimit c) t (some countCircuit.entry)
+ (bank aux (digits k 0) (digits (k+1) 0) [] []) none
+ (bank aux (digits k 0) (digits (k+1) ((labelQuery d h x).coeff e).toNat) [] []) := by
+ simpa only [count_checker d h addr x z hz e he] using
+ countCircuit_runs (checker d h addr W) (query x z W)
+
+/-- The result bits represent the full integer, since the number of satisfying flag
+words is at most two to the width of the enumeration. -/
+theorem coefficient_query_value (d : Fin D) (h : H) (x : Fin m → Bool) (e : Label m D H →₀ ℕ) :
+ (TapeWord.value (digits (Flags m D H+1) ((labelQuery d h x).coeff e).toNat) : ℤ) =
+ (labelQuery d h x).coeff e := by
+ classical
+ rw [coeff_labelQuery_eq_flagCount, Int.toNat_natCast, value_digits, Nat.mod_eq_of_lt]
+ have h := Finset.card_filter_le (Finset.univ : Finset (Fin (Flags m D H) → Bool))
+ ((parseOracleMetadata (Var m) H D d h).Accepts (pairedExponent x) e)
+ simp only [Finset.card_univ, Fintype.card_fun, Fintype.card_bool, Fintype.card_fin] at h
+ exact h.trans_lt (by rw [pow_succ]; have := Nat.pow_pos (n := Flags m D H) (by decide : 0 < 2); omega)
+
+end ParseOracle
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseQuery.lean b/lean/OAI/Computability/VPVNP/ParseQuery.lean
new file mode 100644
index 0000000000..bfb56d4f6e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseQuery.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.LeafBijection
+import OAI.Computability.VPVNP.ParseGrammar
+import OAI.Computability.VPVNP.PairedFamily
+import Mathlib.Data.Finsupp.Multiset
+import Mathlib.Data.Fintype.Perm
+
+/-!
+# Querying a grammar coefficient by leaf assignments
+
+In equation (8.1) of *VP and VNP differ over every field*, the queried monomial
+contains one distinct variable for each bit position. Its coefficient is the sum of
+the parse weights, counting each bijective assignment of terminal occurrences to
+matching query positions once.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar
+
+open MvPolynomial
+variable {V R H : Type*} {n m : ℕ} [CommSemiring R]
+
+/-- A list of terminals contributes one copy of each listed variable. -/
+theorem list_prod_X_eq_monomial (l : List V) :
+ (l.map (X (R := R))).prod =
+ monomial ((l.map (fun v ↦ Finsupp.single v 1)).sum) 1 := by
+ induction l with
+ | nil => simp
+ | cons v l ih =>
+ simp only [List.map_cons, List.prod_cons, List.sum_cons, ih, X, monomial_mul_monomial, one_mul]
+
+private theorem terminalExponents_eq_multiset [DecidableEq V] (l : List V) :
+ (l.map (fun v ↦ Finsupp.single v (1 : ℕ))).sum = (l : Multiset V).toFinsupp := by
+ induction l with
+ | nil => simp
+ | cons v l ih =>
+ simp only [List.map_cons, List.sum_cons, ih]
+ rw [← Multiset.toFinsupp_singleton, ← map_add]
+ rfl
+
+/-- The terminal exponent vector matches the queried monomial exactly when the two
+words have the same multiset of variables. -/
+theorem terminalExponents_eq_query_iff (l : List V) (q : Fin m → V) :
+ (l.map (fun v ↦ Finsupp.single v (1 : ℕ))).sum = ∑ i, Finsupp.single (q i) 1 ↔
+ (l : Multiset V) = (List.ofFn q : Multiset V) := by
+ classical
+ have he : ∑ i, Finsupp.single (q i) 1 =
+ ((List.ofFn q).map (fun v ↦ Finsupp.single v (1 : ℕ))).sum := by
+ simp [List.map_ofFn, List.sum_ofFn, Function.comp_def]
+ rw [he]
+ rw [terminalExponents_eq_multiset, terminalExponents_eq_multiset]
+ exact Multiset.toFinsupp.injective.eq_iff
+
+variable [Fintype V] [Fintype H]
+open scoped Classical
+
+/-- Extract the coefficient by comparing multisets of terminal variables. -/
+theorem coeff_eval_query_multiset (G : ParseGrammar R V H n) (d : Fin n) (h : H)
+ (q : Fin m → V) :
+ (G.eval d h).coeff (∑ i, Finsupp.single (q i) 1) =
+ ∑ p : OrderedParse V H d.val,
+ if (p.leaves : Multiset V) = (List.ofFn q : Multiset V) then G.weight d h p else 0 := by
+ rw [G.eval_eq_sum, coeff_sum]
+ refine Finset.sum_congr rfl fun p _ ↦ ?_
+ rw [list_prod_X_eq_monomial, C_mul_monomial, coeff_monomial]
+ simp [terminalExponents_eq_query_iff]
+
+/-- For an injective query this coefficient counts one weight for each parse and each
+bijective, label-preserving assignment of its leaves to the queried positions. -/
+theorem coeff_eval_query_bijections (G : ParseGrammar R V H n) (d : Fin n) (h : H)
+ (q : Fin m → V) (hq : Function.Injective q) :
+ (G.eval d h).coeff (∑ i, Finsupp.single (q i) 1) =
+ ∑ p : OrderedParse V H d.val, ∑ _ : LeafBijection p.leaves q, G.weight d h p := by
+ rw [G.coeff_eval_query_multiset]
+ refine Finset.sum_congr rfl fun p _ ↦ ?_
+ let := LeafBijection.subsingleton_of_injective p.leaves hq
+ by_cases hmatch : (p.leaves : Multiset V) = (List.ofFn q : Multiset V)
+ · obtain ⟨e⟩ := (LeafBijection.nonempty_iff _ _).mpr hmatch
+ let : Unique (LeafBijection p.leaves q) := ⟨⟨e⟩, fun _ ↦ Subsingleton.elim _ _⟩
+ simp [hmatch]
+ · have : IsEmpty (LeafBijection p.leaves q) :=
+ not_nonempty_iff.mp (fun he ↦ hmatch ((LeafBijection.nonempty_iff _ _).mp he))
+ simp [hmatch]
+
+/-- The query of (8.1) pairs the position index with the requested bit.
+Distinct first coordinates make the query injective over every coefficient semiring. -/
+theorem coeff_eval_paired_bijections (G : ParseGrammar R (Fin m × Bool) H n)
+ (d : Fin n) (h : H) (x : Fin m → Bool) :
+ (G.eval d h).coeff (pairedExponent x) =
+ ∑ p : OrderedParse (Fin m × Bool) H d.val,
+ ∑ _ : LeafBijection p.leaves (fun i ↦ (i, x i)), G.weight d h p := by
+ refine (G.coeff_eval_query_bijections d h (fun i ↦ (i, x i)) fun _ _ e ↦
+ congrArg Prod.fst e).trans ?_
+ refine Finset.sum_congr rfl fun p _ ↦ Finset.sum_congr ?_ fun _ _ ↦ rfl
+ ext
+ simp
+
+end ParseGrammar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ParseTreeBits.lean b/lean/OAI/Computability/VPVNP/ParseTreeBits.lean
new file mode 100644
index 0000000000..88e436ef00
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ParseTreeBits.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.ParseEventBounds
+import OAI.Computability.VPVNP.ParseIncidence
+import OAI.Computability.VPVNP.ParseEventValidity
+import OAI.Computability.VPVNP.ParseIncidenceCNF
+
+/-! # Parsimonious Boolean encoding of an ordered parse
+
+The flags selected by a satisfying assignment are precisely the occurrences of
+one tree. Conversely, the characteristic function of a tree's occurrences
+satisfies every incidence clause. Thus summation over accepted Boolean witnesses
+counts each ordered tree exactly once.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace ParseGrammar.EventCode
+
+variable (V H : Type*) [Fintype V] [Fintype H] (D : ℕ) (d : Fin D) (h : H)
+
+/-- The finite Boolean word recording exactly the occurrences of the parse. -/
+noncomputable def treeBits (t : OrderedParse V H d.val) :
+ Fin (Fintype.card (EventCode V H D)) → Bool :=
+ (selectedEquiv V H D).symm ⟨t.events 0 h, fun e he => by
+ have hb := t.event_bounds 0 h he
+ have hd := d.isLt
+ exact e.bounded_of_wellFormed ((t.events_isParseTable 0 h).typed e he) (by omega) (by omega)⟩
+
+@[simp] theorem selected_treeBits (t : OrderedParse V H d.val) :
+ selected V H D (treeBits V H D d h t) = t.events 0 h :=
+ congrArg Subtype.val ((selectedEquiv V H D).apply_symm_apply _)
+
+theorem treeBits_satisfies (t : OrderedParse V H d.val) :
+ HardnessCNF.Satisfies (incidenceCNF (enumerate V H D) 0 d.val h) (treeBits V H D d h t) := by
+ apply (satisfies_incidenceCNF_iff ..).mpr
+ change IsParseTable (selected V H D (treeBits V H D d h t)) 0 d.val h
+ rw [selected_treeBits]
+ exact t.events_isParseTable 0 h
+
+private theorem unique_tree
+ (x : {x // HardnessCNF.Satisfies (incidenceCNF (enumerate V H D) 0 d.val h) x}) :
+ ∃! t : OrderedParse V H d.val, t.events 0 h = selected V H D x.1 :=
+ ((satisfies_incidenceCNF_iff ..).mp x.2).existsUnique_parse
+
+/-- For a fixed root degree and state, the accepting words are in bijection
+with the ordered parse trees. -/
+noncomputable def satisfyingEquiv :
+ {x // HardnessCNF.Satisfies (incidenceCNF (enumerate V H D) 0 d.val h) x} ≃
+ OrderedParse V H d.val where
+ toFun x := (unique_tree V H D d h x).exists.choose
+ invFun t := ⟨treeBits V H D d h t, treeBits_satisfies V H D d h t⟩
+ left_inv x := by
+ apply Subtype.ext
+ apply (selectedEquiv V H D).injective
+ apply Subtype.ext
+ rw [selectedEquiv_apply, selectedEquiv_apply, selected_treeBits]
+ exact (unique_tree V H D d h x).exists.choose_spec
+ right_inv t := by
+ let x := (⟨treeBits V H D d h t, treeBits_satisfies V H D d h t⟩ :
+ {x // HardnessCNF.Satisfies (incidenceCNF (enumerate V H D) 0 d.val h) x})
+ exact (unique_tree V H D d h x).unique (unique_tree V H D d h x).exists.choose_spec
+ (selected_treeBits V H D d h t).symm
+
+theorem events_satisfyingEquiv
+ (x : {x // HardnessCNF.Satisfies (incidenceCNF (enumerate V H D) 0 d.val h) x}) :
+ (satisfyingEquiv V H D d h x).events 0 h = selected V H D x.val :=
+ (unique_tree V H D d h x).exists.choose_spec
+
+end ParseGrammar.EventCode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentClauseChoices.lean b/lean/OAI/Computability/VPVNP/PermanentClauseChoices.lean
new file mode 100644
index 0000000000..72536e9f0c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentClauseChoices.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.ExactOneOccurrences
+import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise
+
+/-!
+# Clause choices in the cycle-cover reduction
+
+In an exact-one assignment each clause has a unique chosen occurrence. Conversely,
+matching all chosen occurrences against the active arcs of the variable rings forces
+that assignment to satisfy the exact-one conditions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open HardnessCNF ExactOne
+
+variable {k m c : ℕ}
+
+/-- Each clause chooses an occurrence which belongs to it. -/
+def ownerOK (occ : Fin m → Fin k × Fin c × Bool) (y : Fin c → Fin m) : Prop :=
+ ∀ a, (occ (y a)).2.1 = a
+
+/-- The occurrence numbered `j` is the choice of its clause. -/
+def selected (occ : Fin m → Fin k × Fin c × Bool) (y : Fin c → Fin m) (j : Fin m) : Prop :=
+ y (occ j).2.1 = j
+
+private def compatible (occ : Fin m → Fin k × Fin c × Bool)
+ (x : Fin k → Bool) (y : Fin c → Fin m) : Prop :=
+ ownerOK occ y ∧ ∀ j, selected occ y j ↔ x (occ j).1 = (occ j).2.2
+
+private theorem unique_in_clause (occ : Fin m → Fin k × Fin c × Bool)
+ (x : Fin k → Bool) (y : Fin c → Fin m) (hy : compatible occ x y) (a : Fin c) :
+ ∃! j, (occ j).2.1 = a ∧ x (occ j).1 = (occ j).2.2 := by
+ refine ⟨y a, ⟨hy.1 a, (hy.2 _).mp ?_⟩, ?_⟩
+ · exact congrArg y (hy.1 a)
+ · rintro j ⟨hj, h⟩
+ have hs := (hy.2 j).mpr h
+ simpa [selected, hj] using hs.symm
+
+private theorem unique_selection (occ : Fin m → Fin k × Fin c × Bool)
+ (x : Fin k → Bool)
+ (h : ∀ a, ∃! j, (occ j).2.1 = a ∧ x (occ j).1 = (occ j).2.2) :
+ ∃! y, compatible occ x y := by
+ classical
+ choose y hy hu using h
+ have hcomp : compatible occ x y := by
+ refine ⟨fun a => (hy a).1, fun j => ?_⟩
+ constructor
+ · intro hj
+ have ha := (hy (occ j).2.1).2
+ rwa [hj] at ha
+ · intro hj
+ exact (hu (occ j).2.1 j ⟨rfl, hj⟩).symm
+ refine ⟨y, hcomp, ?_⟩
+ intro z hz
+ funext a
+ apply hu a (z a)
+ exact ⟨hz.1 a, (hz.2 _).mp (congrArg z (hz.1 a))⟩
+
+open scoped Classical in
+/-- The clause selector contributes precisely one copy of a compatible weight. -/
+theorem sum_clause_choices {R : Type*} [CommSemiring R]
+ (φ : CNF k) (x : Fin k → Bool) (weight : R) :
+ (∑ y : Fin φ.length → Fin (literalCount φ),
+ if (∀ a, (occurrences φ (y a)).2.1 = a) ∧
+ (∀ j, y (occurrences φ j).2.1 = j ↔ x (occurrences φ j).1 = (occurrences φ j).2.2)
+ then weight else 0) = if Holds φ x then weight else 0 := by
+ classical
+ trans (∑ y, if compatible (occurrences φ) x y then weight else 0)
+ · apply Finset.sum_congr rfl
+ intro y _
+ by_cases hy : compatible (occurrences φ) x y <;>
+ simp only [compatible, ownerOK, selected] at hy ⊢ <;> simp [hy]
+ by_cases h : Holds φ x
+ · obtain ⟨y, hy, hu⟩ := unique_selection (occurrences φ) x ((holds_iff_unique_occurrence φ x).mp h)
+ have eq_choice (z : Fin φ.length → Fin (literalCount φ)) :
+ compatible (occurrences φ) x z ↔ z = y := ⟨hu z, fun hz => hz ▸ hy⟩
+ simp [eq_choice, h]
+ · have no_choice (y : Fin φ.length → Fin (literalCount φ)) :
+ ¬ compatible (occurrences φ) x y := fun hy =>
+ h ((holds_iff_unique_occurrence φ x).mpr (unique_in_clause _ _ y hy))
+ simp [no_choice, h]
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentCoefficient.lean b/lean/OAI/Computability/VPVNP/PermanentCoefficient.lean
new file mode 100644
index 0000000000..44920c1a9e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentCoefficient.lean
@@ -0,0 +1,73 @@
+import Mathlib.Algebra.MvPolynomial.Basic
+import Mathlib.LinearAlgebra.Matrix.Permanent
+
+/-!
+# The permanent as a squarefree column coefficient
+
+In a product of row forms, a summand chooses one column in each row. It contributes
+to the monomial using every column once precisely when the choices form a permutation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+open scoped BigOperators
+
+variable {V R : Type*} [Fintype V] [DecidableEq V] [CommSemiring R]
+
+/-- One occurrence of each column. -/
+noncomputable def fullDegree (V : Type*) [Fintype V] : V →₀ ℕ :=
+ ∑ j : V, Finsupp.single j 1
+
+@[simp] theorem fullDegree_apply (j : V) : fullDegree V j = 1 := by
+ simp [fullDegree, Finsupp.finsetSum_apply, Finsupp.single_apply]
+
+theorem degrees_eq_full_iff (f : V → V) :
+ (∑ i, Finsupp.single (f i) 1) = fullDegree V ↔ Function.Bijective f := by
+ constructor
+ · intro h
+ apply (Fintype.bijective_iff_surjective_and_card _).mpr
+ refine ⟨?_, rfl⟩
+ intro j
+ by_contra! hmiss
+ have hj := DFunLike.congr_fun h j
+ simp [Finsupp.finsetSum_apply, hmiss] at hj
+ · intro hf
+ exact (Equiv.ofBijective f hf).sum_comp (fun j => Finsupp.single j 1)
+
+omit [Fintype V] [DecidableEq V] in
+theorem prod_monomials {I : Type*} (s : Finset I) (d : I → V →₀ ℕ) (a : I → R) :
+ (∏ i ∈ s, monomial (d i) (a i)) = monomial (∑ i ∈ s, d i) (∏ i ∈ s, a i) := by
+ classical
+ induction s using Finset.induction_on with
+ | empty => simp
+ | insert i s hi ih => simp [hi, ih]
+
+/-- The product of the row forms over an arbitrary finite index type. -/
+noncomputable def rowProduct (M : Matrix V V R) : MvPolynomial V R :=
+ ∏ i, ∑ j, C (M i j) * X j
+
+theorem coeff_rowProduct (M : Matrix V V R) : (rowProduct M).coeff (fullDegree V) = M.permanent := by
+ classical
+ simp only [rowProduct, Fintype.prod_sum, C_mul_X_eq_monomial, prod_monomials, coeff_sum,
+ coeff_monomial, degrees_eq_full_iff]
+ rw [← Finset.sum_filter]
+ have hsub := Finset.sum_subtype (p := Function.Bijective (α := V) (β := V))
+ (F := inferInstance)
+ (Finset.univ.filter Function.Bijective) (fun x => Finset.mem_filter.trans (and_iff_right (Finset.mem_univ x)))
+ (fun f : V → V => ∏ i, M i (f i))
+ rw [hsub]
+ calc
+ _ = ∑ e : Equiv.Perm V, ∏ i, M i (e i) :=
+ Equiv.bijectiveEquiv.sum_comp (fun e : Equiv.Perm V => ∏ i, M i (e i))
+ _ = M.permanent := Matrix.permanent_transpose M
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentCompleteness.lean b/lean/OAI/Computability/VPVNP/PermanentCompleteness.lean
new file mode 100644
index 0000000000..8d0a0afb10
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentCompleteness.lean
@@ -0,0 +1,31 @@
+import Complexity.Computability.Circuit.Arithmetic.Permanent
+import OAI.Computability.VPVNP.ComplexityLib.PermanentNumbering
+import OAI.Computability.VPVNP.ComplexityLib.VNPTransport
+import OAI.Computability.VPVNP.PermanentHardness
+
+/-! # Valiant's completeness theorem for the generic permanent
+
+Ryser's formula supplies the Boolean-sum verifier over every field. The
+permanent reduction uses the inverse of two for its occurrence gadgets.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+/-- The generic permanent belongs to VNP over every field. Numbering its matrix
+entries in row-major order gives the family computed by the Ryser verifier. -/
+theorem permanent_isVNP (F : Type*) [Field F] : IsVNP (permanentPolynomial F) := by
+ apply (ComplexityLib.numbered_mem_VNP_iff (permanentPolynomial F) (fun _ => finProdFinEquiv)).mp
+ rw [ComplexityLib.numbered_permanent]
+ exact Cslib.Circuits.Arithmetic.permFamily_mem_VNP
+
+/-- Over every field of characteristic different from two, the generic permanent
+belongs to VNP and every VNP family is a p-projection of it. -/
+theorem permanent_vnpComplete (F : Type*) [Field F] (q : ℕ) [CharP F q] (hq : q ≠ 2) :
+ VNPComplete (permanentPolynomial F) :=
+ ⟨permanent_isVNP F, fun _ _ g hg => pProjects_permanent_of_isVNP q hq g hg⟩
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentDirect.lean b/lean/OAI/Computability/VPVNP/PermanentDirect.lean
new file mode 100644
index 0000000000..90eae7bbab
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentDirect.lean
@@ -0,0 +1,28 @@
+import OAI.Computability.VPVNP.PermanentGraph
+
+/-!
+# Direct ring edges
+
+An unmarked edge contributes its destination column immediately. A marked edge
+acquires its exterior column when the occurrence gadget uses its ring exit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+
+/-- Product of the exterior column variables contributed by direct ring edges. -/
+noncomputable def directProduct {k m c : ℕ} {R : Type*} [CommSemiring R]
+ (occ : Fin m → Fin k × Fin c × Bool) (a : RingRow k m → Bool) :
+ MvPolynomial (Exterior k m c) R :=
+ ∏ u, if (markedPort occ u (a u)).isSome then 1 else X (.inl (ringTarget u (a u)))
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentEntryProduct.lean b/lean/OAI/Computability/VPVNP/PermanentEntryProduct.lean
new file mode 100644
index 0000000000..dc78422e4b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentEntryProduct.lean
@@ -0,0 +1,49 @@
+import OAI.Computability.VPVNP.PermanentDirect
+import OAI.Computability.VPVNP.PermanentRegroup
+
+/-!
+# Separating exterior ring edges from occurrence ports
+
+A ring row chooses either a direct edge to the next exterior column or an
+edge to the first interior column of its occurrence gadget. Multiplying the
+row choices uses each active occurrence port exactly once.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+
+variable {R : Type*} [CommSemiring R] {k m c : ℕ}
+
+/-- Under the variable-splitting equivalence, ring inputs factor into the
+direct exterior product and one interior variable for each active occurrence. -/
+theorem ringEntry_product (occ : Fin m → Fin k × Fin c × Bool) (a : RingRow k m → Bool) :
+ (∏ u, sumAlgEquiv R (Interior m) (Exterior k m c) (X (ringEntry occ u (a u)))) =
+ C (directProduct (R := R) occ a) *
+ ∏ g, if a (markedPosition occ g) = (occ g).2.2 then X (g, (0 : Fin 3)) else 1 := by
+ let pick (u : RingRow k m) := markedPort occ u (a u)
+ let direct (u : RingRow k m) : MvPolynomial (Exterior k m c) R :=
+ if (pick u).isSome then 1 else X (.inl (ringTarget u (a u)))
+ let port (g : Fin m) : MvPolynomial (Interior m) (MvPolynomial (Exterior k m c) R) := X (g, 0)
+ have entry (u : RingRow k m) :
+ sumAlgEquiv R (Interior m) (Exterior k m c) (X (ringEntry occ u (a u))) =
+ C (direct u) * (pick u).elim 1 port := by
+ cases hp : markedPort occ u (a u) <;> simp [pick, direct, port, ringEntry, hp]
+ have hpick (u : RingRow k m) (g : Fin m) :
+ pick u = some g ↔ u = markedPosition occ g ∧ decide (a (markedPosition occ g) = (occ g).2.2) = true := by
+ simp only [pick, decide_eq_true_eq, markedPort_eq_some]
+ exact and_congr_right fun he => he ▸ Iff.rfl
+ rw [Finset.prod_congr rfl (fun u _ => entry u), Finset.prod_mul_distrib, ← map_prod]
+ congr 1
+ simpa [port] using prod_optional_ports pick (markedPosition occ)
+ (fun g => decide (a (markedPosition occ g) = (occ g).2.2)) hpick port
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentEquality.lean b/lean/OAI/Computability/VPVNP/PermanentEquality.lean
new file mode 100644
index 0000000000..82bbba2d33
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentEquality.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.PermanentCoefficient
+import Mathlib.Algebra.MvPolynomial.CommRing
+import Mathlib.Algebra.CharP.Basic
+import Mathlib.LinearAlgebra.Matrix.Notation
+import Mathlib.Tactic.FinCases
+import Mathlib.Tactic.Ring
+
+/-!
+# An equality gadget for the permanent
+
+The three internal rows have column weights `(-b,-b,b)`, `(-1,-1,1)`,
+and `(1,1,1)`. The first two rows can also exit with weights `A` and `B`.
+Taking the coefficient that fills every internal column exactly once
+cancels the choices that use only one incoming port.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+
+variable {R : Type*} [CommRing R]
+
+/-- Product of the three internal row forms, including the two possible exits. -/
+noncomputable def equalityRows (b A B : R) : MvPolynomial (Fin 3) R :=
+ (-C b * X 0 - C b * X 1 + C b * X 2 + C A) *
+ (-X 0 - X 1 + X 2 + C B) * (X 0 + X 1 + X 2)
+
+/-- Weights of the internal directed edges, in port order. -/
+def equalityMatrix (b : R) : Matrix (Fin 3) (Fin 3) R :=
+ !![-b, -b, b; -1, -1, 1; 1, 1, 1]
+
+/-- Each row chooses an internal column or exits the gadget. -/
+theorem equalityRows_eq_prod (b A B : R) :
+ equalityRows b A B = ∏ i : Fin 3,
+ ((∑ j : Fin 3, C (equalityMatrix b i j) * X j) + C (![A, B, 0] i)) := by
+ rw [Fin.prod_univ_three]
+ simp [equalityRows, equalityMatrix, Fin.sum_univ_three, sub_eq_add_neg]
+
+private theorem eq_fullDegree_three (d : Fin 3 →₀ ℕ) :
+ d = fullDegree (Fin 3) ↔ d 0 = 1 ∧ d 1 = 1 ∧ d 2 = 1 := by
+ constructor
+ · rintro rfl
+ simp
+ · rintro ⟨h₀, h₁, h₂⟩
+ ext j
+ fin_cases j <;> simpa
+
+/-- When neither port enters, the internal cycle covers have total weight
+one. When both enter, the two exits contribute `A * B`. -/
+theorem coeff_equalityRows (b A B : R) (hb : -2 * b = 1) (i₀ i₁ : Bool) :
+ ((if i₀ then X 0 else 1) * (if i₁ then X 1 else 1) *
+ equalityRows b A B).coeff (fullDegree (Fin 3)) =
+ if i₀ then (if i₁ then A * B else 0) else (if i₁ then 0 else 1) := by
+ cases i₀ <;> cases i₁ <;>
+ simp only [Bool.false_eq_true, ite_false, ite_true, one_mul, mul_one] <;>
+ simp only [equalityRows, X, C_apply, sub_eq_add_neg, add_mul, mul_add, neg_mul, mul_neg,
+ monomial_mul_monomial, AddMonoidAlgebra.coeff_add, coeff_neg, coeff_monomial, eq_fullDegree_three,
+ Finsupp.add_apply, Finsupp.zero_apply, Finsupp.single_apply] <;>
+ simp (config := { decide := true })
+ · calc
+ _ = -2 * b := by ring
+ _ = 1 := hb
+ all_goals ring
+
+/-- In a field of characteristic different from two, the required weight
+`b = −1/2` remains normalized after applying any coefficient homomorphism. -/
+theorem map_neg_half_normalized {F : Type*} [Field F] (q : ℕ) [CharP F q]
+ (hq : q ≠ 2) (φ : F →+* R) : -2 * φ (-(2 : F)⁻¹) = 1 := by
+ have h₂ : (2 : F) ≠ 0 := Ring.two_ne_zero (by simpa [ringChar.eq F q] using hq)
+ have h : -(2 : F) * (-(2 : F)⁻¹) = 1 := by simp [h₂]
+ simpa [map_ofNat] using congrArg φ h
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentExpandedTerm.lean b/lean/OAI/Computability/VPVNP/PermanentExpandedTerm.lean
new file mode 100644
index 0000000000..65fe745183
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentExpandedTerm.lean
@@ -0,0 +1,34 @@
+import OAI.Computability.VPVNP.PermanentGraph
+
+/-!
+# Expanding the rows outside the equality gadgets
+
+A term chooses a direction in each variable-ring row and an occurrence in
+each clause row. The internal gadget rows are kept together until their
+three squarefree column coefficients are extracted.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+
+variable {k m c : ℕ} {R : Type*} [CommRing R]
+
+/-- The summand associated to the choices in all exterior rows. -/
+noncomputable def expandedTerm (occ : Fin m → Fin k × Fin c × Bool) (w : Fin k → R)
+ (b : R) (a : RingRow k m → Bool) (y : Fin c → Fin m) :
+ MvPolynomial (Interior m) (MvPolynomial (Exterior k m c) R) :=
+ (∏ g, rename (Prod.mk g) (equalityRows (C b) (X (ringExit occ g)) (X (clauseExit occ g)))) *
+ (∏ u, C (C (ringWeight w u (a u))) *
+ sumAlgEquiv R (Interior m) (Exterior k m c) (X (ringEntry occ u (a u)))) *
+ (∏ i, if (occ (y i)).2.1 = i then X (y i, 1) else 0)
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentExterior.lean b/lean/OAI/Computability/VPVNP/PermanentExterior.lean
new file mode 100644
index 0000000000..607b7a935d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentExterior.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.PermanentDirect
+import OAI.Computability.VPVNP.PermanentExteriorDegree
+import OAI.Computability.VPVNP.PermanentRegroup
+import OAI.Computability.VPVNP.PermanentRingWeight
+
+/-!
+# Exterior columns after matching the two gadget ports
+
+In a compatible choice, each occurrence used by its variable ring is also chosen
+by its clause. Its two exits supply the missing ring and clause columns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+open scoped Classical
+
+variable {k m c : ℕ} {R : Type*} [CommSemiring R]
+variable (occ : Fin m → Fin k × Fin c × Bool) (a : RingRow k m → Bool)
+
+/-- The exits of the active gadgets replace exactly the ring columns omitted
+by the direct edges. -/
+private theorem restore_ring_columns :
+ directProduct (R := R) occ a *
+ (∏ g, if a (markedPosition occ g) = (occ g).2.2 then X (ringExit occ g) else 1) =
+ ∏ u, X (.inl (ringTarget u (a u))) := by
+ let active (g : Fin m) := decide (a (markedPosition occ g) = (occ g).2.2)
+ have hp (u : RingRow k m) (g : Fin m) :
+ markedPort occ u (a u) = some g ↔ u = markedPosition occ g ∧ active g = true := by
+ rw [markedPort_eq_some]
+ simp only [active, decide_eq_true_eq]
+ exact and_congr_right (fun h => h ▸ Iff.rfl)
+ have hr := prod_optional_ports (fun u => markedPort occ u (a u)) (markedPosition occ)
+ active hp (fun g => (X (ringExit occ g) : MvPolynomial (Exterior k m c) R))
+ simp only [active, decide_eq_true_eq] at hr
+ rw [← hr, directProduct, ← Finset.prod_mul_distrib]
+ apply Finset.prod_congr rfl
+ intro u _
+ cases h : markedPort occ u (a u) with
+ | none => simp
+ | some g =>
+ obtain ⟨hpos, hbit⟩ := (markedPort_eq_some occ u (a u) g).mp h
+ simp [ringExit, ← hpos, ← hbit]
+
+/-- A matched term uses every clause column once and the same ring columns as
+the original ring assignment. -/
+theorem matched_exterior_columns (y : Fin c → Fin m)
+ (hy : ∀ z, (occ (y z)).2.1 = z)
+ (hmatch : ∀ g, a (markedPosition occ g) = (occ g).2.2 ↔ y (occ g).2.1 = g) :
+ directProduct (R := R) occ a *
+ (∏ g, if a (markedPosition occ g) = (occ g).2.2
+ then X (ringExit occ g) * X (clauseExit occ g) else 1) =
+ (∏ u, X (.inl (ringTarget u (a u)))) * ∏ z : Fin c, X (.inr z) := by
+ have hsplit :
+ (∏ g, if a (markedPosition occ g) = (occ g).2.2
+ then X (ringExit occ g) * X (clauseExit occ g) else 1) =
+ (∏ g, if a (markedPosition occ g) = (occ g).2.2 then X (ringExit occ g) else 1) *
+ (∏ g, if y (occ g).2.1 = g then (X (clauseExit occ g) : MvPolynomial (Exterior k m c) R)
+ else 1) := by
+ rw [← Finset.prod_mul_distrib]
+ apply Finset.prod_congr rfl
+ intro g _
+ by_cases h : a (markedPosition occ g) = (occ g).2.2
+ · simp [h, (hmatch g).mp h]
+ · simp [h, mt (hmatch g).mpr h]
+ have hc := prod_clause_ports y (fun g => (occ g).2.1) hy
+ (fun g => (X (clauseExit occ g) : MvPolynomial (Exterior k m c) R))
+ rw [hsplit, ← mul_assoc, restore_ring_columns, ← hc]
+ simp [clauseExit, hy]
+
+/-- A matched term supplies the full exterior degree exactly for consistent rings. -/
+theorem coeff_exterior_matched (y : Fin c → Fin m)
+ (hy : ∀ z, (occ (y z)).2.1 = z)
+ (hmatch : ∀ g, a (markedPosition occ g) = (occ g).2.2 ↔ y (occ g).2.1 = g) :
+ (directProduct (R := R) occ a *
+ (∏ g, if a (markedPosition occ g) = (occ g).2.2
+ then X (ringExit occ g) * X (clauseExit occ g) else 1)).coeff
+ (fullDegree (Exterior k m c)) = if ∀ v j, a (v, j) = a (v, 0) then 1 else 0 := by
+ rw [matched_exterior_columns occ a y hy hmatch, coeff_ring_clause_columns]
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentExteriorDegree.lean b/lean/OAI/Computability/VPVNP/PermanentExteriorDegree.lean
new file mode 100644
index 0000000000..591694e187
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentExteriorDegree.lean
@@ -0,0 +1,37 @@
+import OAI.Computability.VPVNP.PermanentGraph
+
+/-!
+# The exterior column coefficient of the exact-one graph
+
+After the internal gadgets have supplied their exits, each clause contributes its
+own column and each ring row contributes the column of its chosen direction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+open scoped BigOperators Classical
+
+/-- The squarefree exterior monomial occurs exactly when every variable ring has
+a single common orientation. -/
+theorem coeff_ring_clause_columns {k m c : ℕ} {R : Type*} [CommSemiring R]
+ (a : RingRow k m → Bool) :
+ ((∏ u : RingRow k m, (X (.inl (ringTarget u (a u))) : MvPolynomial (Exterior k m c) R)) *
+ ∏ z : Fin c, (X (Sum.inr z) : MvPolynomial (Exterior k m c) R)).coeff
+ (fullDegree (Exterior k m c)) =
+ if ∀ v j, a (v, j) = a (v, 0) then 1 else 0 := by
+ let f : Exterior k m c → Exterior k m c := Sum.map (fun u => ringTarget u (a u)) id
+ erw [← Fintype.prod_sum_type (fun u => (X (f u) : MvPolynomial (Exterior k m c) R))]
+ simp only [X, prod_monomials, Finset.prod_const_one, coeff_monomial,
+ degrees_eq_full_iff, f, Sum.map_bijective, Function.bijective_id, and_true,
+ ringTarget_bijective_iff]
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentFactors.lean b/lean/OAI/Computability/VPVNP/PermanentFactors.lean
new file mode 100644
index 0000000000..9707bf47ce
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentFactors.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.PermanentCoefficient
+import Mathlib.Algebra.MvPolynomial.Equiv
+
+/-!
+# Coefficient extraction on disjoint variable blocks
+
+When a product has one factor for each block of variables, each choice of monomials
+in the factors contributes to a different monomial of the product.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+open scoped BigOperators
+
+variable {G J V R : Type*} [CommSemiring R]
+
+private theorem blockDegrees_apply [Fintype G] (d : G → J →₀ ℕ) (g : G) (j : J) :
+ (∑ i, (d i).mapDomain (Prod.mk i)) (g, j) = d g j := by
+ classical
+ rw [Finsupp.finsetSum_apply, Finset.sum_eq_single g]
+ · exact Finsupp.mapDomain_apply_of_injective (Prod.mk_right_injective g) _ _
+ · intro i _ hi
+ apply Finsupp.mapDomain_of_notMem_range
+ rintro ⟨_, he⟩
+ exact hi (congrArg Prod.fst he)
+ · simp
+
+private theorem blockDegrees_eq_full_iff [Fintype G] [DecidableEq G]
+ [Fintype J] [DecidableEq J] (d : G → J →₀ ℕ) :
+ (∑ i, (d i).mapDomain (Prod.mk i)) = fullDegree (G × J) ↔ d = fun _ => fullDegree J := by
+ constructor
+ · intro h
+ funext g
+ ext j
+ simpa only [blockDegrees_apply, fullDegree_apply] using DFunLike.congr_fun h (g, j)
+ · rintro rfl
+ ext ⟨g, j⟩
+ simp only [blockDegrees_apply, fullDegree_apply]
+
+/-- Each block must supply exactly its own squarefree monomial. -/
+theorem coeff_fullDegree_prod_rename [Fintype G] [DecidableEq G] [Fintype J] [DecidableEq J]
+ (f : G → MvPolynomial J R) :
+ (∏ g, rename (Prod.mk g) (f g)).coeff (fullDegree (G × J)) =
+ ∏ g, (f g).coeff (fullDegree J) := by
+ classical
+ have hexp (g : G) : rename (Prod.mk g) (f g) =
+ ∑ d ∈ (f g).support, monomial (d.mapDomain (Prod.mk g)) ((f g).coeff d) := by
+ conv_lhs => rw [(f g).as_sum, map_sum]
+ simp only [rename_monomial]
+ simp only [hexp, Finset.prod_univ_sum, prod_monomials, coeff_sum, coeff_monomial,
+ blockDegrees_eq_full_iff, Finset.sum_ite_eq']
+ split_ifs with h
+ · rfl
+ · simp only [Fintype.mem_piFinset, mem_support_iff, not_forall, not_not] at h
+ obtain ⟨g, hg⟩ := h
+ exact (Finset.prod_eq_zero (Finset.mem_univ g) hg).symm
+
+/-- Squarefree coefficient extraction across a sum of variable types can be performed
+in two steps, first in the left block and then in the right block. -/
+theorem coeff_fullDegree_sum [Fintype J] [DecidableEq J] [Fintype V] [DecidableEq V]
+ (p : MvPolynomial (J ⊕ V) R) :
+ p.coeff (fullDegree (J ⊕ V)) =
+ ((sumAlgEquiv R J V p).coeff (fullDegree J)).coeff (fullDegree V) := by
+ change p.coeff (fullDegree (J ⊕ V)) =
+ (AddMonoidAlgebra.domCongr R R Finsupp.sumFinsuppAddEquivProdFinsupp p).coeff
+ (fullDegree J, fullDegree V)
+ rw [AddMonoidAlgebra.coeff_domCongr]
+ congr 1
+ ext (j | v) <;> simp only [fullDegree_apply, Finsupp.sumFinsuppAddEquivProdFinsupp_symm_inl,
+ Finsupp.sumFinsuppAddEquivProdFinsupp_symm_inr]
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentGraph.lean b/lean/OAI/Computability/VPVNP/PermanentGraph.lean
new file mode 100644
index 0000000000..9c52256137
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentGraph.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PermanentEquality
+import OAI.Computability.VPVNP.PermanentRings
+import Mathlib.Algebra.MvPolynomial.Equiv
+
+/-!
+# The cycle-cover graph for exact-one clauses
+
+For each occurrence `g` there are three internal vertices. Its first port meets the
+arc of the variable ring corresponding to the satisfying literal. Its second port
+meets the loop of its clause. Separate occurrence gadgets distinguish all parallel
+clause loops. One unmarked row on each ring carries the weight of a true assignment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+
+/-- Vertices outside the equality gadgets, consisting of variable-ring rows and clause
+vertices. -/
+abbrev Exterior (k m c : ℕ) := RingRow k m ⊕ Fin c
+/-- The three internal vertices of each literal occurrence's equality gadget. -/
+abbrev Interior (m : ℕ) := Fin m × Fin 3
+/-- The full index set of the permanent matrix, including the equality gadgets, rings, and
+clauses. -/
+abbrev Vertex (k m c : ℕ) := Interior m ⊕ Exterior k m c
+
+variable {k m c : ℕ} (occ : Fin m → Fin k × Fin c × Bool)
+
+/-- The ring row assigned to an occurrence, on the ring of that occurrence's variable. -/
+def markedPosition (g : Fin m) : RingRow k m := ((occ g).1, ⟨g.val, by omega⟩)
+
+/-- The marked arc exists only on the ring of the occurrence's variable and only in
+its satisfying direction. -/
+def markedPort (u : RingRow k m) (choice : Bool) : Option (Fin m) :=
+ if h : u.2.val < m then
+ let g : Fin m := ⟨u.2.val, h⟩
+ if (occ g).1 = u.1 ∧ choice = (occ g).2.2 then some g else none
+ else none
+
+theorem markedPort_eq_some (u : RingRow k m) (a : Bool) (g : Fin m) :
+ markedPort occ u a = some g ↔ u = markedPosition occ g ∧ a = (occ g).2.2 := by
+ rcases u with ⟨v, j⟩
+ by_cases h : j.val < m
+ · let z : Fin m := ⟨j.val, h⟩
+ simp only [markedPort, h, dite_true]
+ change (if (occ z).1 = v ∧ a = (occ z).2.2 then some z else none) = some g ↔ _
+ split_ifs with hz
+ · constructor
+ · rintro hg
+ obtain rfl := Option.some.inj hg
+ exact ⟨Prod.ext hz.1.symm (Fin.ext rfl), hz.2⟩
+ · rintro ⟨hpos, _⟩
+ congr 1
+ exact Fin.ext (congrArg (fun u : RingRow k m => u.2.val) hpos)
+ · simp
+ intro hpos hbit
+ have he : z = g := Fin.ext (congrArg (fun u : RingRow k m => u.2.val) hpos)
+ exact hz ⟨he ▸ (congrArg Prod.fst hpos).symm, he ▸ hbit⟩
+ · simp [markedPort, h]
+ intro hpos _
+ have := congrArg (fun u : RingRow k m => u.2.val) hpos
+ change j.val = g.val at this
+ omega
+
+/-- Destination of a ring arc, before the gadget's internal rows are expanded. -/
+def ringEntry (u : RingRow k m) (a : Bool) : Vertex k m c :=
+ (markedPort occ u a).elim (.inr (.inl (ringTarget u a))) (fun g => .inl (g, 0))
+
+/-- The exterior ring vertex reached when an occurrence gadget takes the satisfying ring
+direction. -/
+def ringExit (g : Fin m) : Exterior k m c := .inl (ringTarget (markedPosition occ g) (occ g).2.2)
+
+/-- The clause vertex connected to the outgoing clause port of this occurrence. -/
+def clauseExit (g : Fin m) : Exterior k m c := .inr (occ g).2.1
+
+/-- A true ring direction uses a variable label only on the dedicated row `m`. -/
+def ringLabel {F : Type*} [One F] (u : RingRow k m) (a : Bool) : Fin k ⊕ F :=
+ if a = true ∧ u.2.val = m then .inl u.1 else .inr 1
+
+/-- Evaluate a ring arc at the supplied weights. Only the true direction on the dedicated row
+`m` contributes the variable weight. -/
+def ringWeight {R : Type*} [One R] (w : Fin k → R) (u : RingRow k m) (a : Bool) : R :=
+ (ringLabel u a).elim w id
+
+/-- The two ring arcs have distinct endpoints, including at a marked occurrence. -/
+theorem ringEntry_ne (u : RingRow k m) : ringEntry occ u false ≠ ringEntry occ u true := by
+ intro he
+ cases h₀ : markedPort occ u false with
+ | none =>
+ cases h₁ : markedPort occ u true with
+ | none =>
+ simp [ringEntry, h₀, h₁, ringTarget] at he
+ have hz : (0 : Fin (m + 2)) = 1 := add_left_cancel (a := u.2)
+ (by simpa using congrArg Prod.snd he)
+ exact zero_ne_one hz
+ | some g => simp [ringEntry, h₀, h₁] at he
+ | some g =>
+ cases h₁ : markedPort occ u true with
+ | none => simp [ringEntry, h₀, h₁] at he
+ | some z =>
+ have eq : g = z := by simpa [ringEntry, h₀, h₁] using he
+ subst z
+ have ha := (markedPort_eq_some occ _ _ _).mp h₀
+ have hb := (markedPort_eq_some occ _ _ _).mp h₁
+ exact Bool.false_ne_true (ha.2.trans hb.2.symm)
+
+/-- Every adjacency entry is a single variable or a single scalar. -/
+def graphLabels {F : Type*} [CommRing F] (b : F) : Vertex k m c → Vertex k m c → Fin k ⊕ F
+ | .inl (g, i), .inl (h, j) => .inr (if g = h then equalityMatrix b i j else 0)
+ | .inl (g, i), .inr v => .inr (if (i = 0 ∧ v = ringExit occ g) ∨
+ (i = 1 ∧ v = clauseExit occ g) then 1 else 0)
+ | .inr (.inl u), v => if v = ringEntry occ u false then ringLabel u false else
+ if v = ringEntry occ u true then ringLabel u true else .inr 0
+ | .inr (.inr a), .inl (g, j) => .inr (if (occ g).2.1 = a ∧ j = 1 then 1 else 0)
+ | .inr (.inr _), .inr _ => .inr 0
+
+/-- The matrix obtained by evaluating all arc labels of the permanent gadget at the specified
+weights and equality-gadget parameter. -/
+def graphMatrix {R : Type*} [CommRing R] (w : Fin k → R) (b : R) : Matrix (Vertex k m c) (Vertex k m c) R :=
+ fun u v => (graphLabels occ b u v).elim w id
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentGraphRows.lean b/lean/OAI/Computability/VPVNP/PermanentGraphRows.lean
new file mode 100644
index 0000000000..5027ae8a24
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentGraphRows.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.PermanentGraph
+
+/-!
+# Row factors of the exact-one cycle-cover graph
+
+Regard the exterior columns as variables of the coefficient ring. Each occurrence
+then supplies its three internal row factors, with the two exits contributing
+exterior column variables. Each variable-ring row chooses one of two directions,
+and each clause row chooses an occurrence in that clause.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+
+variable {k m c : ℕ} {R : Type*} [CommRing R]
+variable (occ : Fin m → Fin k × Fin c × Bool) (w : Fin k → R) (b : R)
+
+private theorem equalityMatrix_map {S : Type*} [CommRing S] (f : R →+* S) (i j : Fin 3) :
+ f (equalityMatrix b i j) = equalityMatrix (f b) i j := by
+ fin_cases i <;> fin_cases j <;> simp [equalityMatrix]
+
+private theorem interiorRow (g : Fin m) (i : Fin 3) :
+ sumAlgEquiv R (Interior m) (Exterior k m c)
+ (∑ v, C (graphMatrix occ w b (.inl (g, i)) v) * X v) =
+ rename (Prod.mk g)
+ ((∑ j : Fin 3, C (equalityMatrix (C b) i j) * X j) +
+ C (![X (ringExit occ g), X (clauseExit occ g), 0] i)) := by
+ rw [Fintype.sum_sum_type]
+ simp only [map_add, map_sum, map_mul, rename_C, rename_X,
+ sumAlgEquiv_X_inl, sumAlgEquiv_X_inr, sumAlgEquiv_C_inl]
+ congr 1
+ · rw [Fintype.sum_prod_type, Finset.sum_comm]
+ simp [graphMatrix, graphLabels, apply_ite, ite_mul, equalityMatrix_map]
+ · fin_cases i <;> simp [graphMatrix, graphLabels, apply_ite, ite_mul]
+
+private theorem ringRow (u : RingRow k m) :
+ sumAlgEquiv R (Interior m) (Exterior k m c)
+ (∑ v, C (graphMatrix occ w b (.inr (.inl u)) v) * X v) =
+ ∑ a : Bool, C (C (ringWeight w u a)) *
+ sumAlgEquiv R (Interior m) (Exterior k m c) (X (ringEntry occ u a)) := by
+ have e (v : Vertex k m c) :
+ graphMatrix occ w b (.inr (.inl u)) v =
+ (if v = ringEntry occ u true then ringWeight w u true else 0) +
+ (if v = ringEntry occ u false then ringWeight w u false else 0) := by
+ by_cases h : v = ringEntry occ u false
+ · subst v
+ simp [graphMatrix, graphLabels, ringWeight, ringEntry_ne]
+ · by_cases ht : v = ringEntry occ u true <;>
+ simp [graphMatrix, graphLabels, h, ht, ringWeight, (ringEntry_ne occ u).symm]
+ simp only [e, Fintype.sum_bool, map_add, add_mul, Finset.sum_add_distrib, apply_ite C,
+ map_zero, ite_mul, zero_mul, Finset.sum_ite_eq', Finset.mem_univ, ite_true, map_mul,
+ sumAlgEquiv_C_inl]
+
+private theorem clauseRow (a : Fin c) :
+ sumAlgEquiv R (Interior m) (Exterior k m c)
+ (∑ v, C (graphMatrix occ w b (.inr (.inr a)) v) * X v) =
+ ∑ g : Fin m, if (occ g).2.1 = a then X (g, 1) else 0 := by
+ simp only [Fintype.sum_sum_type, Fintype.sum_prod_type, map_add, map_sum, map_mul,
+ sumAlgEquiv_X_inl, sumAlgEquiv_X_inr, sumAlgEquiv_C_inl]
+ simp only [graphMatrix, graphLabels, Sum.elim_inr, id_eq, map_zero, zero_mul, Finset.sum_const_zero,
+ add_zero]
+ apply Finset.sum_congr rfl
+ intro g _
+ by_cases hg : (occ g).2.1 = a <;> simp [hg, apply_ite, ite_mul]
+
+/-- Decomposition into one equality factor per occurrence and one choice factor per
+exterior row. The coefficients of the internal polynomials are exterior polynomials. -/
+theorem rowProduct_split :
+ sumAlgEquiv R (Interior m) (Exterior k m c) (rowProduct (graphMatrix occ w b)) =
+ (∏ g, rename (Prod.mk g)
+ (equalityRows (C b) (X (ringExit occ g)) (X (clauseExit occ g)))) *
+ (∏ u : RingRow k m, ∑ a : Bool, C (C (ringWeight w u a)) *
+ sumAlgEquiv R (Interior m) (Exterior k m c) (X (ringEntry occ u a))) *
+ (∏ a : Fin c, ∑ g, if (occ g).2.1 = a then X (g, 1) else 0) := by
+ rw [rowProduct, map_prod]
+ simp only [Fintype.prod_sum_type, Fintype.prod_prod_type, interiorRow, ringRow,
+ clauseRow, equalityRows_eq_prod, map_prod, mul_assoc]
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentHardness.lean b/lean/OAI/Computability/VPVNP/PermanentHardness.lean
new file mode 100644
index 0000000000..0defee1907
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentHardness.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.PermanentWeighted
+import OAI.Computability.VPVNP.ExactOneFamily
+import OAI.Computability.VPVNP.CompletePolynomials
+import OAI.Computability.VPVNP.CompleteFieldDescent
+
+/-!
+# Permanent hardness and the transfer in Corollary 1.2
+
+Each exact-one presentation of a VNP family projects from a permanent of polynomially
+bounded order. The scalar used for an occurrence gadget is available precisely when two
+is invertible in the coefficient field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+variable {F : Type*} [Field F] {V : ℕ → Type} [∀ n, Fintype (V n)]
+
+/-- In characteristic different from two, every VNP family is a literal p-projection of
+the generic permanent family. -/
+theorem pProjects_permanent_of_isVNP (q : ℕ) [CharP F q] (hq : q ≠ 2)
+ (p : Family F V) (hp : IsVNP p) : PProjects p (permanentPolynomial F) := by
+ obtain ⟨k, φ, w, _, hwidth, hclauses, hlits, he⟩ := ExactOne.exists_family_of_isVNP p hp
+ refine ⟨fun n => 3 * HardnessCNF.literalCount (φ n) +
+ k n * (HardnessCNF.literalCount (φ n) + 2) + (φ n).length,
+ (((PolynomiallyBounded.const 3).mul hlits).add (hwidth.mul (hlits.add (.const 2)))).add hclauses, ?_⟩
+ intro n
+ obtain ⟨ρ, hρ⟩ := PermanentReduction.weighted_projection q hq (φ n) (w n)
+ exact ⟨ρ, hρ.trans (he n)⟩
+
+/-- Section 15.1's reduction of the paper's integer family to the permanent. -/
+theorem P_pProjects_permanent (F : Type*) [Field F] (q : ℕ) [CharP F q] (hq : q ≠ 2) :
+ PProjects (fun n => map (Int.castRingHom F) (P n)) (permanentPolynomial F) :=
+ pProjects_permanent_of_isVNP q hq _ (P_isVNP F)
+
+/-- The permanent assertion of Corollary 1.2 follows from the eventual lower bound for
+`P` over one algebraically closed field of the specified characteristic. -/
+theorem permanent_uniform_of_P {K : Type*} [Field K] [IsAlgClosed K]
+ (q : ℕ) [CharP K q] (hq : q ≠ 2)
+ (h : EventuallySuperpolynomial fun n => circuitSize (map (Int.castRingHom K) (P n)))
+ (C : ℕ) :
+ ∃ N, ∀ m ≥ N, ∀ (F : Type*) [Field F] [CharP F q],
+ m ^ C < circuitSize (permanentPolynomial F m) := by
+ obtain ⟨N, hN⟩ := permanent_bound_of_pProjects (P_pProjects_permanent K q hq) h C
+ exact ⟨N, permanentPolynomial_uniform_bound (K := K) q C N hN⟩
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentInterior.lean b/lean/OAI/Computability/VPVNP/PermanentInterior.lean
new file mode 100644
index 0000000000..4ab9e0eb55
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentInterior.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.PermanentExpandedTerm
+import OAI.Computability.VPVNP.PermanentGraphRows
+import OAI.Computability.VPVNP.PermanentPortProduct
+import OAI.Computability.VPVNP.PermanentEntryProduct
+import OAI.Computability.VPVNP.PermanentClauseChoices
+
+/-!
+# The squarefree interior coefficient of a cycle-cover term
+
+Once the directions of the ring rows and the choices of the clause rows
+are fixed, each occurrence gadget sees two incoming bits. Its internal
+rows cancel unless these bits agree. When they agree, the coefficient
+retains the two exit columns precisely for the selected occurrence.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+open scoped Classical
+
+variable {k m c : ℕ} {R : Type*} [CommRing R]
+
+theorem rowProduct_eq_expandedSum (occ : Fin m → Fin k × Fin c × Bool) (w : Fin k → R)
+ (b : R) :
+ sumAlgEquiv R (Interior m) (Exterior k m c) (rowProduct (graphMatrix occ w b)) =
+ ∑ a : RingRow k m → Bool, ∑ y : Fin c → Fin m, expandedTerm occ w b a y := by
+ rw [rowProduct_split]
+ simp only [Fintype.prod_sum, Finset.mul_sum, Finset.sum_mul, expandedTerm]
+ exact Finset.sum_comm
+
+private theorem rearrange {A : Type*} [CommMonoid A] (g s d v z : A) :
+ g * (s * (d * v)) * z = (s * d) * (g * v * z) := by ac_rfl
+
+/-- Extracting the interior coefficient enforces both occurrence ownership and
+agreement between the two incoming ports. -/
+theorem coeff_expandedTerm (occ : Fin m → Fin k × Fin c × Bool) (w : Fin k → R)
+ (b : R) (hb : -2 * b = 1) (a : RingRow k m → Bool) (y : Fin c → Fin m) :
+ (expandedTerm occ w b a y).coeff (fullDegree (Interior m)) =
+ if ownerOK occ y ∧
+ (∀ g, a (markedPosition occ g) = (occ g).2.2 ↔ y (occ g).2.1 = g) then
+ C (∏ u, ringWeight w u (a u)) *
+ (directProduct occ a * ∏ g, if a (markedPosition occ g) = (occ g).2.2
+ then X (ringExit occ g) * X (clauseExit occ g) else 1)
+ else 0 := by
+ by_cases hy : ownerOK occ y
+ · let active (g : Fin m) := decide (a (markedPosition occ g) = (occ g).2.2)
+ let picked (g : Fin m) := decide (y (occ g).2.1 = g)
+ let scalar : MvPolynomial (Exterior k m c) R := C (∏ u, ringWeight w u (a u)) * directProduct occ a
+ have hclause :
+ (∏ i, if (occ (y i)).2.1 = i then X (y i, 1) else 0) =
+ (∏ g, if picked g then X (g, (1 : Fin 3)) else 1 :
+ MvPolynomial (Interior m) (MvPolynomial (Exterior k m c) R)) := by
+ have own (i : Fin c) := hy i
+ simp only [own, ite_true, picked, decide_eq_true_eq]
+ exact prod_clause_ports y (fun g => (occ g).2.1) hy
+ (fun g => (X (g, 1) : MvPolynomial (Interior m) (MvPolynomial (Exterior k m c) R)))
+ have hweight :
+ (∏ u, C (C (ringWeight w u (a u)))) =
+ (C (C (∏ u, ringWeight w u (a u))) :
+ MvPolynomial (Interior m) (MvPolynomial (Exterior k m c) R)) := by
+ simp only [map_prod]
+ have he :
+ expandedTerm occ w b a y =
+ C scalar * ((∏ g, rename (Prod.mk g)
+ (equalityRows (C b) (X (ringExit occ g)) (X (clauseExit occ g)))) *
+ (∏ g, if active g then X (g, (0 : Fin 3)) else 1) *
+ (∏ g, if picked g then X (g, (1 : Fin 3)) else 1)) := by
+ rw [expandedTerm, Finset.prod_mul_distrib, hweight, ringEntry_product, hclause]
+ simp only [scalar, map_mul, active, decide_eq_true_eq]
+ exact rearrange _ _ _ _ _
+ have hb' : -2 * (C b : MvPolynomial (Exterior k m c) R) = 1 := by
+ simpa [map_ofNat] using congrArg (C (σ := Exterior k m c)) hb
+ have hagree : (∀ g, active g = picked g) ↔
+ ∀ g, a (markedPosition occ g) = (occ g).2.2 ↔ y (occ g).2.1 = g := by
+ simp [active, picked]
+ rw [he, coeff_C_mul, coeff_portProduct _ hb']
+ simp only [hagree, active, decide_eq_true_eq, hy, true_and, scalar]
+ split_ifs <;> simp [mul_assoc]
+ · have hbad : ∃ i, (occ (y i)).2.1 ≠ i := not_forall.mp hy
+ obtain ⟨i, hi⟩ := hbad
+ have hzero :
+ (∏ j, if (occ (y j)).2.1 = j then X (y j, (1 : Fin 3)) else 0 :
+ MvPolynomial (Interior m) (MvPolynomial (Exterior k m c) R)) = 0 :=
+ Finset.prod_eq_zero (Finset.mem_univ i) (by simp [hi])
+ simp [expandedTerm, hzero, hy]
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentLabels.lean b/lean/OAI/Computability/VPVNP/PermanentLabels.lean
new file mode 100644
index 0000000000..a485067130
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentLabels.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PermanentPadding
+import OAI.Computability.VPVNP.PermanentGraph
+
+/-!
+# Literal projections of the generic permanent
+
+A weighted directed graph whose edges carry constants or variables gives a
+projection of the permanent. A simultaneous reindexing of both matrix axes
+lets us use any finite vertex type.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+
+/-- Relabeling the vertices bijectively preserves all cycle-cover weights. -/
+theorem permanent_submatrix_equiv_self {I J R : Type*} [Fintype I] [DecidableEq I]
+ [Fintype J] [DecidableEq J] [CommSemiring R] (e : I ≃ J) (M : Matrix J J R) :
+ (M.submatrix e e).permanent = M.permanent := by
+ unfold Matrix.permanent
+ apply Fintype.sum_equiv (Equiv.permCongr e)
+ intro π
+ apply Fintype.prod_equiv e
+ intro i
+ simp
+
+/-- A finite matrix with literal labels is obtained by a projection of the
+generic square matrix of the same order. -/
+theorem exists_permanent_label_projection {V σ F : Type*} [Fintype V] [DecidableEq V]
+ [CommSemiring F] {n : ℕ} (hn : Fintype.card V = n) (label : V → V → σ ⊕ F) :
+ ∃ φ : Projection F (Fin n × Fin n) σ, φ.hom (permanentPolynomial F n) =
+ (Matrix.of fun i j => (label i j).elim X C).permanent := by
+ let e := (Fintype.equivFinOfCardEq hn).symm
+ let φ : Projection F (Fin n × Fin n) σ := fun ij => label (e ij.1) (e ij.2)
+ refine ⟨φ, ?_⟩
+ let M : Matrix V V (MvPolynomial σ F) := Matrix.of fun i j => (label i j).elim X C
+ calc
+ φ.hom (permanentPolynomial F n) = (M.submatrix e e).permanent := by
+ simp [permanentPolynomial, Matrix.permanent, Projection.hom, φ, M]
+ _ = M.permanent := permanent_submatrix_equiv_self e M
+
+variable {k m c : ℕ}
+
+private theorem map_equalityMatrix {F R : Type*} [CommRing F] [CommRing R] (h : F →+* R)
+ (b : F) (i j : Fin 3) : h (equalityMatrix b i j) = equalityMatrix (h b) i j := by
+ fin_cases i <;> fin_cases j <;> simp [equalityMatrix]
+
+private theorem map_ringLabel {F R : Type*} [CommRing F] [CommRing R] (h : F →+* R)
+ (u : RingRow k m) (a : Bool) :
+ (ringLabel (F := F) u a).map id h = ringLabel u a := by
+ unfold ringLabel
+ split <;> simp
+
+/-- Scalar specialization of the graph acts entrywise on its scalar labels. -/
+theorem map_graphLabels {F R : Type*} [CommRing F] [CommRing R] (h : F →+* R)
+ (occ : Fin m → Fin k × Fin c × Bool) (b : F) (u v : Vertex k m c) :
+ (graphLabels occ b u v).map id h = graphLabels occ (h b) u v := by
+ rcases u with ⟨g, i⟩ | (x | a)
+ · rcases v with ⟨g', j⟩ | y
+ · simp [graphLabels, apply_ite h, map_equalityMatrix]
+ · simp [graphLabels, apply_ite h]
+ · simp only [graphLabels]
+ split
+ · exact map_ringLabel h x false
+ · split
+ · exact map_ringLabel h x true
+ · simp
+ · rcases v with ⟨g, j⟩ | y <;> simp [graphLabels, apply_ite h]
+
+theorem card_graphVertex (k m c : ℕ) :
+ Fintype.card (Vertex k m c) = 3 * m + k * (m + 2) + c := by
+ simp only [Vertex, Interior, Exterior, RingRow, Fintype.card_sum, Fintype.card_prod,
+ Fintype.card_fin]
+ omega
+
+/-- Reindex the gadget graph and use each entry as a literal variable or constant
+of the generic permanent. This uses exactly three internal vertices per occurrence,
+one ring of length `m + 2` per variable, and one vertex per clause. -/
+theorem weightedLabelsProjection {F σ : Type*} [CommRing F]
+ (occ : Fin m → Fin k × Fin c × Bool) (w : Projection F (Fin k) σ) (b : F) :
+ ∃ φ : Projection F
+ (Fin (3 * m + k * (m + 2) + c) × Fin (3 * m + k * (m + 2) + c)) σ,
+ φ.hom (permanentPolynomial F (3 * m + k * (m + 2) + c)) =
+ (graphMatrix occ (fun i => (w i).elim X C) (C b)).permanent := by
+ let label (u v : Vertex k m c) : σ ⊕ F := (graphLabels occ b u v).elim w Sum.inr
+ obtain ⟨φ, hp⟩ := exists_permanent_label_projection (card_graphVertex k m c) label
+ refine ⟨φ, hp.trans ?_⟩
+ congr 1
+ ext u v
+ simp only [Matrix.of_apply, graphMatrix, ← map_graphLabels (C : F →+* MvPolynomial σ F),
+ label]
+ cases graphLabels occ b u v <;> rfl
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentPadding.lean b/lean/OAI/Computability/VPVNP/PermanentPadding.lean
new file mode 100644
index 0000000000..8f6d1f7a4f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentPadding.lean
@@ -0,0 +1,47 @@
+import OAI.Computability.VPVNP.Circuits
+import Mathlib.GroupTheory.Perm.Fin
+import Mathlib.LinearAlgebra.Matrix.Permanent
+
+/-!
+# Diagonal padding for the permanent
+
+Section 15.1 of *VP and VNP differ over every field* pads a matrix of
+indeterminates by adjoining one diagonal entry equal to one and setting all
+other entries in its new row and column to zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open Equiv MvPolynomial
+
+/-- The permanent of the generic `m` by `m` matrix. -/
+noncomputable def permanentPolynomial (R : Type*) [CommSemiring R] (m : ℕ) :
+ MvPolynomial (Fin m × Fin m) R :=
+ Matrix.permanent (Matrix.of fun i j => X (i, j))
+
+/-- The row-first formula used in the paper. -/
+theorem permanentPolynomial_eq_sum (R : Type*) [CommSemiring R] (m : ℕ) :
+ permanentPolynomial R m = ∑ π : Perm (Fin m), ∏ i, X (i, π i) := by
+ exact (Matrix.permanent_transpose (Matrix.of fun i j : Fin m => X (R := R) (i, j))).symm
+
+/-- Vertex zero is the new vertex, and `Fin.succ` embeds the old indices. -/
+def permanentPadding (R : Type*) [CommRing R] (m : ℕ) :
+ Projection R (Fin (m + 1) × Fin (m + 1)) (Fin m × Fin m) := fun (i, j) =>
+ Fin.cases (Fin.cases (.inr 1) (fun _ => .inr 0) j)
+ (fun i => Fin.cases (.inr 0) (fun j => .inl (i, j)) j) i
+
+/-- Exactly the permutations fixing the new index survive diagonal padding. -/
+theorem permanentPadding_polynomial (R : Type*) [CommRing R] (m : ℕ) :
+ (permanentPadding R m).hom (permanentPolynomial R (m + 1)) = permanentPolynomial R m := by
+ classical
+ rw [permanentPolynomial_eq_sum, permanentPolynomial_eq_sum, map_sum,
+ Finset.univ_perm_fin_succ, Finset.sum_map, Fintype.sum_prod_type, Fin.sum_univ_succ]
+ simp only [Equiv.toEmbedding_apply, Fin.prod_univ_succ,
+ Equiv.Perm.decomposeFin_symm_apply_zero, Equiv.Perm.decomposeFin_symm_apply_succ]
+ simp [Projection.hom, permanentPadding]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentPortProduct.lean b/lean/OAI/Computability/VPVNP/PermanentPortProduct.lean
new file mode 100644
index 0000000000..f87c3b1e78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentPortProduct.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.PermanentEquality
+import OAI.Computability.VPVNP.PermanentFactors
+
+/-!
+# Coefficient of a product of equality gadgets
+
+Each copy has three private columns. Once the incoming port choices have been
+fixed, the squarefree coefficient factors across copies. A disagreement in a
+single copy makes the entire coefficient vanish.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial
+
+variable {R : Type*} [CommRing R]
+
+/-- All incoming port pairs must agree, and each used pair contributes both
+of its exit weights. -/
+theorem coeff_portProduct {m : ℕ} (b : R) (hb : -2 * b = 1) (A B : Fin m → R)
+ (active picked : Fin m → Bool) :
+ ((∏ g, rename (Prod.mk g) (equalityRows b (A g) (B g))) *
+ (∏ g, if active g then X (g, (0 : Fin 3)) else 1) *
+ (∏ g, if picked g then X (g, (1 : Fin 3)) else 1)).coeff
+ (fullDegree (Fin m × Fin 3)) =
+ if ∀ g, active g = picked g then ∏ g, if active g then A g * B g else 1 else 0 := by
+ let localRows (g : Fin m) : MvPolynomial (Fin 3) R :=
+ (if active g then X 0 else 1) * (if picked g then X 1 else 1) * equalityRows b (A g) (B g)
+ have hprod :
+ (∏ g, rename (Prod.mk g) (equalityRows b (A g) (B g))) *
+ (∏ g, if active g then X (g, (0 : Fin 3)) else 1) *
+ (∏ g, if picked g then X (g, (1 : Fin 3)) else 1) =
+ ∏ g, rename (Prod.mk g) (localRows g) := by
+ rw [← Finset.prod_mul_distrib, ← Finset.prod_mul_distrib]
+ apply Finset.prod_congr rfl
+ intro g _
+ cases ha : active g <;> cases hp : picked g <;> simp [localRows, ha, hp, mul_comm, mul_left_comm, mul_assoc]
+ rw [hprod, coeff_fullDegree_prod_rename]
+ simp only [localRows, coeff_equalityRows b _ _ hb]
+ by_cases h : ∀ g, active g = picked g
+ · rw [ite_eq_left h]
+ apply Finset.prod_congr rfl
+ intro g _
+ rw [h g]
+ cases picked g <;> rfl
+ · rw [ite_eq_right h]
+ obtain ⟨g, hg⟩ := not_forall.mp h
+ apply Finset.prod_eq_zero (Finset.mem_univ g)
+ cases ha : active g <;> cases hp : picked g <;> simp_all
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentRegroup.lean b/lean/OAI/Computability/VPVNP/PermanentRegroup.lean
new file mode 100644
index 0000000000..da4ddd9919
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentRegroup.lean
@@ -0,0 +1,56 @@
+import Mathlib.Algebra.BigOperators.Group.Finset.Basic
+import Mathlib.Data.Fintype.BigOperators
+
+/-!
+# Products indexed by the selected ports
+
+Each marked ring row can use one input port. A clause row chooses one occurrence in that
+clause. Reindexing these products counts the occupied ports once per gadget.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+variable {U G A : Type*} [Fintype U] [Fintype G] [CommMonoid A]
+
+/-- Reindex a product of optional factors by the occupied ports. -/
+theorem prod_optional_ports (pick : U → Option G) (pos : G → U) (active : G → Bool)
+ (hf : ∀ u g, pick u = some g ↔ u = pos g ∧ active g = true) (w : G → A) :
+ (∏ u, (pick u).elim 1 w) = ∏ g, if active g then w g else 1 := by
+ classical
+ calc
+ _ = ∏ u, ∏ g, if pick u = some g then w g else 1 := by
+ apply Finset.prod_congr rfl
+ intro u _
+ cases h : pick u <;> simp
+ _ = ∏ g, ∏ u, if u = pos g ∧ active g = true then w g else 1 := by
+ simp_rw [hf]
+ exact Finset.prod_comm
+ _ = _ := by
+ apply Finset.prod_congr rfl
+ intro g _
+ cases active g <;> simp
+
+/-- Reindex one selected occurrence per clause by the occurrence set. -/
+theorem prod_clause_ports [DecidableEq G] (pick : U → G) (owner : G → U)
+ (howner : ∀ u, owner (pick u) = u) (w : G → A) :
+ (∏ u, w (pick u)) = ∏ g, if pick (owner g) = g then w g else 1 := by
+ classical
+ have hport (u : U) (g : G) : some (pick u) = some g ↔ u = owner g ∧ decide (pick (owner g) = g) = true := by
+ simp only [Option.some.injEq, decide_eq_true_eq]
+ constructor
+ · rintro rfl
+ simp [howner]
+ · rintro ⟨rfl, h⟩
+ exact h
+ simpa using prod_optional_ports (fun u => some (pick u)) owner
+ (fun g => decide (pick (owner g) = g)) hport w
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentRingWeight.lean b/lean/OAI/Computability/VPVNP/PermanentRingWeight.lean
new file mode 100644
index 0000000000..f6f299e025
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentRingWeight.lean
@@ -0,0 +1,36 @@
+import OAI.Computability.VPVNP.PermanentGraph
+
+/-!
+# Weight of a consistent variable ring
+
+Only position `m` of each ring carries the variable weight. Multiplying the
+row weights for a consistent choice therefore contributes one factor for
+each variable assigned true.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+/-- For consistent ring orientations the product of all row weights is the
+weight of the corresponding Boolean assignment. -/
+theorem prod_ringWeight {k m : ℕ} {R : Type*} [CommMonoid R] (w : Fin k → R)
+ (a : RingRow k m → Bool) (x : Fin k → Bool) (hx : ∀ v j, a (v, j) = x v) :
+ (∏ u, ringWeight w u (a u)) = ∏ v, if x v then w v else 1 := by
+ rw [Fintype.prod_prod_type]
+ apply Finset.prod_congr rfl
+ intro v _
+ let j₀ : Fin (m + 2) := ⟨m, by omega⟩
+ rw [Finset.prod_eq_single_of_mem j₀ (Finset.mem_univ _)]
+ · cases hv : x v <;> simp [ringWeight, ringLabel, hx, hv, j₀]
+ · intro j _ hj
+ have hval : j.val ≠ m := fun he => hj (Fin.ext he)
+ simp [ringWeight, ringLabel, hval]
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentRings.lean b/lean/OAI/Computability/VPVNP/PermanentRings.lean
new file mode 100644
index 0000000000..9d19934fc1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentRings.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.PermanentCoefficient
+import Mathlib.Algebra.Group.Fin.Basic
+
+/-!
+# Variable rings in the permanent reduction
+
+Each row of a variable ring chooses its own column or the next column cyclically.
+Covering all columns exactly once forces a common choice throughout each ring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open scoped BigOperators
+
+/-- One ring of length `m + 2` for each of the `k` variables. -/
+abbrev RingRow (k m : ℕ) := Fin k × Fin (m + 2)
+
+variable {k m : ℕ}
+
+/-- The false edge stays in the column of its row. The true edge advances cyclically. -/
+def ringTarget (u : RingRow k m) (b : Bool) : RingRow k m :=
+ (u.1, if b then u.2 + 1 else u.2)
+
+/-- Two consecutive rows of a permutation must make the same choice. -/
+private theorem ringChoice_step (b : RingRow k m → Bool)
+ (hb : Function.Bijective fun u => ringTarget u (b u))
+ (v : Fin k) (j : Fin (m + 1)) :
+ b (v, j.succ) = b (v, j.castSucc) := by
+ cases hj : b (v, j.castSucc) <;> cases hs : b (v, j.succ)
+ · rfl
+ · obtain ⟨⟨v', i⟩, hi⟩ := hb.2 (v, j.succ)
+ have hv : v' = v := congrArg Prod.fst hi
+ subst v'
+ have hc := congrArg Prod.snd hi
+ cases h : b (v, i) with
+ | false =>
+ have e : i = j.succ := by simpa [ringTarget, h] using hc
+ rw [e, hs] at h
+ contradiction
+ | true =>
+ have e : i + 1 = j.castSucc + 1 := by simpa [ringTarget, h, Fin.coeSucc_eq_succ] using hc
+ rw [add_right_cancel e, hj] at h
+ contradiction
+ · have e := hb.1 (a₁ := (v, j.castSucc)) (a₂ := (v, j.succ))
+ (by simp [ringTarget, hj, hs, Fin.coeSucc_eq_succ])
+ exact (Fin.castSucc_lt_succ.ne (congrArg Prod.snd e)).elim
+ · rfl
+
+/-- The destinations permute all ring positions exactly when each variable chooses
+one of its two orientations consistently. -/
+theorem ringTarget_bijective_iff (b : RingRow k m → Bool) :
+ (Function.Bijective fun u => ringTarget u (b u)) ↔
+ ∀ v j, b (v, j) = b (v, 0) := by
+ constructor
+ · intro hb v j
+ induction j using Fin.induction with
+ | zero => rfl
+ | succ j ih => exact (ringChoice_step b hb v j).trans ih
+ · intro h
+ constructor
+ · rintro ⟨v, i⟩ ⟨w, j⟩ he
+ have hw : v = w := congrArg Prod.fst he
+ subst w
+ have hc := congrArg Prod.snd he
+ cases hv : b (v, 0) <;> simpa [ringTarget, h v i, h v j, hv] using hc
+ · rintro ⟨v, i⟩
+ cases hv : b (v, 0) with
+ | false => exact ⟨(v, i), by simp [ringTarget, h v i, hv]⟩
+ | true => exact ⟨(v, i - 1), by simp [ringTarget, h v (i - 1), hv]⟩
+
+/-- The full column monomial selects precisely the consistent ring choices. -/
+theorem ringDegrees_eq_full_iff (b : RingRow k m → Bool) :
+ (∑ u, Finsupp.single (ringTarget u (b u)) 1) = fullDegree (RingRow k m) ↔
+ ∀ v j, b (v, j) = b (v, 0) := by
+ rw [degrees_eq_full_iff, ringTarget_bijective_iff]
+
+/-- Reading the orientation at position zero identifies consistent choices with
+Boolean assignments to the variables. -/
+def ringChoicesEquiv (k m : ℕ) :
+ {b : RingRow k m → Bool // ∀ v j, b (v, j) = b (v, 0)} ≃ (Fin k → Bool) where
+ toFun b v := b.1 (v, 0)
+ invFun x := ⟨fun u => x u.1, fun _ _ => rfl⟩
+ left_inv b := Subtype.ext (funext fun u => (b.2 u.1 u.2).symm)
+ right_inv _ := rfl
+
+open scoped Classical in
+/-- After imposing the full ring-column degree, the sum over row choices counts
+each Boolean assignment once, with its original weight. -/
+theorem sum_ring_choices {A : Type*} [AddCommMonoid A] (weight : (RingRow k m → Bool) → A) :
+ (∑ b, if (∑ u, Finsupp.single (ringTarget u (b u)) 1) = fullDegree (RingRow k m)
+ then weight b else 0) = ∑ x : Fin k → Bool, weight (fun u => x u.1) := by
+ simp_rw [ringDegrees_eq_full_iff]
+ rw [← Finset.sum_filter, Finset.sum_subtype (p := fun b : RingRow k m → Bool =>
+ ∀ v j, b (v, j) = b (v, 0)) _ (by simp)]
+ exact (ringChoicesEquiv k m).symm.sum_comp (fun b => weight b.val) |>.symm
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PermanentWeighted.lean b/lean/OAI/Computability/VPVNP/PermanentWeighted.lean
new file mode 100644
index 0000000000..dd2eae8435
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PermanentWeighted.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.PermanentInterior
+import OAI.Computability.VPVNP.PermanentExterior
+import OAI.Computability.VPVNP.PermanentLabels
+import OAI.Computability.VPVNP.ExactOneWeights
+
+/-!
+# Weighted exact-one assignments as a projection of the permanent
+
+The squarefree interior coefficient enforces the equality gadget for each literal.
+The exterior coefficient enforces consistent orientations of the variable rings. Finally,
+there is exactly one compatible choice in each clause of a satisfying assignment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PermanentReduction
+
+open MvPolynomial HardnessCNF ExactOne
+open scoped Classical
+
+variable {k m c : ℕ} {R : Type*} [CommRing R]
+
+private def compatibleChoices (occ : Fin m → Fin k × Fin c × Bool) (a : RingRow k m → Bool)
+ (y : Fin c → Fin m) : Prop :=
+ ownerOK occ y ∧ ∀ g, a (markedPosition occ g) = (occ g).2.2 ↔ y (occ g).2.1 = g
+
+private theorem coeff_both_blocks (occ : Fin m → Fin k × Fin c × Bool) (w : Fin k → R)
+ (b : R) (hb : -2 * b = 1) (a : RingRow k m → Bool) (y : Fin c → Fin m) :
+ ((expandedTerm occ w b a y).coeff (fullDegree (Interior m))).coeff
+ (fullDegree (Exterior k m c)) =
+ if ∀ v j, a (v, j) = a (v, 0) then
+ if compatibleChoices occ a y then ∏ u, ringWeight w u (a u) else 0
+ else 0 := by
+ rw [coeff_expandedTerm occ w b hb]
+ split
+ next h =>
+ rw [coeff_C_mul, coeff_exterior_matched occ a y h.1 h.2]
+ have h' : compatibleChoices occ a y := h
+ rw [ite_eq_left h']
+ split_ifs <;> simp
+ next h =>
+ have h' : ¬ compatibleChoices occ a y := h
+ simp [h']
+
+/-- The weighted graph computes exactly the generating polynomial of exact-one assignments. -/
+theorem permanent_graph_eq_weighted (φ : CNF k) (w : Fin k → R) (b : R) (hb : -2 * b = 1) :
+ (graphMatrix (occurrences φ) w b).permanent = weightedExactOne φ w := by
+ let occ := occurrences φ
+ let W (a : RingRow k (literalCount φ) → Bool) := ∑ y : Fin φ.length → Fin (literalCount φ),
+ if compatibleChoices occ a y then ∏ u, ringWeight w u (a u) else 0
+ rw [← coeff_rowProduct, coeff_fullDegree_sum, rowProduct_eq_expandedSum]
+ simp only [coeff_sum, coeff_both_blocks _ w b hb]
+ calc
+ _ = ∑ a : RingRow k (literalCount φ) → Bool,
+ if (∑ u, Finsupp.single (ringTarget u (a u)) 1) = fullDegree (RingRow k (literalCount φ))
+ then W a else 0 := by
+ apply Finset.sum_congr rfl
+ intro a _
+ by_cases h : ∀ v j, a (v, j) = a (v, 0) <;> simp [ringDegrees_eq_full_iff, h, W, occ]
+ _ = ∑ x : Fin k → Bool, W (fun u => x u.1) := sum_ring_choices W
+ _ = _ := by
+ unfold weightedExactOne
+ apply Finset.sum_congr rfl
+ intro x _
+ dsimp only [W]
+ rw [prod_ringWeight w (fun u : RingRow k (literalCount φ) => x u.1) x (fun _ _ => rfl)]
+ convert! sum_clause_choices φ x (∏ i, if x i then w i else 1) using 2
+ simp only [compatibleChoices, ownerOK, occ, markedPosition, iff_comm]
+ split_ifs with h
+ · exact ite_eq_left h
+ · exact ite_eq_right h
+
+/-- A p-projection with literal variable-or-constant entries, valid whenever the field's
+characteristic is different from two. -/
+theorem weighted_projection {F σ : Type*} [Field F] (q : ℕ) [CharP F q] (hq : q ≠ 2)
+ (φ : CNF k) (w : Projection F (Fin k) σ) :
+ let m := literalCount φ
+ let n := 3 * m + k * (m + 2) + φ.length
+ ∃ ρ : Projection F (Fin n × Fin n) σ, ρ.hom (permanentPolynomial F n) =
+ weightedExactOne φ (fun i => (w i).elim X C) := by
+ obtain ⟨ρ, hρ⟩ := weightedLabelsProjection (occurrences φ) w (-(2 : F)⁻¹)
+ exact ⟨ρ, hρ.trans (permanent_graph_eq_weighted φ _ _ (map_neg_half_normalized q hq C))⟩
+
+end PermanentReduction
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PerronBounds.lean b/lean/OAI/Computability/VPVNP/PerronBounds.lean
new file mode 100644
index 0000000000..eed66c1f3c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PerronBounds.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.PerronSimplex
+import OAI.Computability.VPVNP.LogBounds
+import OAI.Computability.VPVNP.MacaulayRows
+
+/-!
+# Bit lengths of Perron degrees and Macaulay dimensions
+
+The coefficient count for a Perron relation permits a degree that depends on
+the number of variables. Its binary logarithm remains polynomially bounded
+when the variable count and the input-degree logarithm are polynomially
+bounded. The same holds for the dimensions of the resulting Macaulay matrix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+/-- The multiplier degree allowance obtained by substituting in a Perron
+relation fits the paper's bound `H(d,t) = (2d)^(4(t+2))`. -/
+theorem perronSimplexBound_le_paper_envelope {d t : ℕ} (hd : 3 ≤ d) :
+ 2 * (d + 1) * (perronSimplexBound (t + 1) (d + 1) + 1) ^ 2 ≤
+ (2 * d) ^ (4 * (t + 2)) := by
+ let b := 2 * d
+ have hradix : 2 * (d + 2) ≤ b ^ 2 := by dsimp [b]; nlinarith
+ have hcoef : 2 * (d + 1) ≤ b ^ 2 := by dsimp [b]; nlinarith
+ have hpos : 1 ≤ (2 * (d + 2)) ^ (t + 1) := one_le_pow₀ (by omega)
+ have hbase : perronSimplexBound (t + 1) (d + 1) + 1 ≤ b ^ (2 * (t + 1) + 1) := calc
+ _ ≤ 3 * (2 * (d + 2)) ^ (t + 1) := by
+ change 2 * (2 * (d + 2)) ^ (t + 1) + 1 ≤ _
+ omega
+ _ ≤ b * (b ^ 2) ^ (t + 1) :=
+ Nat.mul_le_mul (by dsimp [b]; omega) (Nat.pow_le_pow_left hradix _)
+ _ = _ := by rw [← pow_mul, pow_succ]; ac_rfl
+ calc
+ _ ≤ b ^ 2 * (b ^ (2 * (t + 1) + 1)) ^ 2 :=
+ Nat.mul_le_mul hcoef (Nat.pow_le_pow_left hbase _)
+ _ = b ^ (4 * (t + 2)) := by rw [← pow_mul, ← pow_add]; congr 1; omega
+
+/-- The Perron degree has polynomial bit length even for input degrees of
+polynomial bit length. -/
+theorem polynomiallyBounded_clog_perronSimplexBound {m d : ℕ → ℕ} (hm : PolynomiallyBounded m)
+ (hd : PolynomiallyBounded (fun n => Nat.clog 2 (d n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (perronSimplexBound (m n) (d n))) := by
+ have hc := PolynomiallyBounded.clog (PolynomiallyBounded.const 2)
+ exact PolynomiallyBounded.clog_mul hc (PolynomiallyBounded.clog_pow (PolynomiallyBounded.clog_mul hc
+ (PolynomiallyBounded.clog_add hd (PolynomiallyBounded.clog (PolynomiallyBounded.const 1)))) hm)
+
+/-- The paper's effective Nullstellensatz multiplier allowance has polynomial bit length. -/
+theorem polynomiallyBounded_clog_paperBound {t d : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hd : PolynomiallyBounded (fun n => Nat.clog 2 (d n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 ((2 * d n) ^ (4 * (t n + 2)))) :=
+ PolynomiallyBounded.clog_pow (PolynomiallyBounded.clog_mul (PolynomiallyBounded.clog (PolynomiallyBounded.const 2)) hd)
+ ((PolynomiallyBounded.const 4).mul (ht.add (PolynomiallyBounded.const 2)))
+
+/-- Bit length of the actual index set of columns in a bounded coefficient matrix. -/
+theorem polynomiallyBounded_clog_boundedMonomial {t D : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hD : PolynomiallyBounded (fun n => Nat.clog 2 (D n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (Fintype.card (BoundedMonomial (t n) (D n)))) :=
+ (PolynomiallyBounded.clog_pow (PolynomiallyBounded.clog_add hD (PolynomiallyBounded.clog (PolynomiallyBounded.const 1))) ht).of_le
+ fun _ => Nat.clog_mono_right _ (card_boundedMonomial_le _ _)
+
+/-- For a Macaulay matrix formed from a certificate of multiplier degree `H`
+and equations of degree `d`, both index sets have polynomial bit length. -/
+theorem polynomiallyBounded_clog_macaulayDimensions {ι : ℕ → Type*} [∀ n, Fintype (ι n)]
+ {t H d : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hι : PolynomiallyBounded (fun n => Nat.clog 2 (Fintype.card (ι n))))
+ (hH : PolynomiallyBounded (fun n => Nat.clog 2 (H n)))
+ (hd : PolynomiallyBounded (fun n => Nat.clog 2 (d n))) :
+ PolynomiallyBounded (fun n => Nat.clog 2 (Fintype.card (ι n × BoundedMonomial (t n) (H n)))) ∧
+ PolynomiallyBounded (fun n => Nat.clog 2 (Fintype.card (BoundedMonomial (t n) (H n + d n)))) := by
+ simp only [Fintype.card_prod]
+ exact ⟨PolynomiallyBounded.clog_mul hι (polynomiallyBounded_clog_boundedMonomial ht hH),
+ polynomiallyBounded_clog_boundedMonomial ht (PolynomiallyBounded.clog_add hH hd)⟩
+
+/-- The bit-length allowance for the prime in the characteristic-zero reduction
+stays polynomial even if the coefficients have singly exponential bit length. -/
+theorem polynomiallyBounded_good_prime_bits {t H d b : ℕ → ℕ} (ht : PolynomiallyBounded t)
+ (hH : PolynomiallyBounded (fun n => Nat.clog 2 (H n)))
+ (hd : PolynomiallyBounded (fun n => Nat.clog 2 (d n)))
+ (hb : PolynomiallyBounded (fun n => Nat.clog 2 (b n))) :
+ PolynomiallyBounded (fun n => let a := Nat.clog 2 (H n + d n + 1) * t n
+ 2 * (a + Nat.clog 2 (a + b n + 2)) + 1) := by
+ have ha := (PolynomiallyBounded.clog_add (PolynomiallyBounded.clog_add hH hd)
+ (PolynomiallyBounded.clog (PolynomiallyBounded.const 1))).mul ht
+ exact ((PolynomiallyBounded.const 2).mul (ha.add
+ (PolynomiallyBounded.clog_add (PolynomiallyBounded.clog_add (PolynomiallyBounded.clog ha) hb)
+ (PolynomiallyBounded.clog (PolynomiallyBounded.const 2))))).add (PolynomiallyBounded.const 1)
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PerronRelation.lean b/lean/OAI/Computability/VPVNP/PerronRelation.lean
new file mode 100644
index 0000000000..7534a2b17b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PerronRelation.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.PerronSimplex
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Algebra.MvPolynomial.Degrees
+import Mathlib.Algebra.MvPolynomial.Eval
+import Mathlib.LinearAlgebra.Dimension.Constructions
+import Mathlib.LinearAlgebra.Dimension.Finite
+
+/-!
+# Perron's quantitative algebraic-dependence argument
+
+Substitute the given polynomials into a finite family of distinct monomials.
+If the coefficient vectors of the images have fewer coordinates than the family
+has elements, their linear dependence gives a nonzero polynomial relation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+open MvPolynomial
+
+variable {E : Type*} [Field E]
+
+private theorem relation_of_count {X Y I J : Type*}
+ [Fintype X] [Fintype I] [Fintype J] (g : X → MvPolynomial Y E)
+ {D b : ℕ} (hg : ∀ i, (g i).totalDegree ≤ D)
+ (s : I → X →₀ ℕ) (hinj : Function.Injective s)
+ (hdeg : ∀ i, ∑ x, s i x ≤ b) (t : J → Y →₀ ℕ)
+ (hcovers : ∀ d : Y →₀ ℕ, d.sum (fun _ n => n) ≤ b * D → ∃ j, t j = d)
+ (hcard : Fintype.card J < Fintype.card I) :
+ ∃ W : MvPolynomial X E, W ≠ 0 ∧ W.totalDegree ≤ b ∧ aeval g W = 0 := by
+ classical
+ let image (i : I) : MvPolynomial Y E := ∏ x, g x ^ s i x
+ have image_deg (i : I) : (image i).totalDegree ≤ b * D := calc
+ _ ≤ ∑ x, (g x ^ s i x).totalDegree := totalDegree_finsetProd _ _
+ _ ≤ ∑ x, s i x * D := Finset.sum_le_sum fun x _ =>
+ (totalDegree_pow _ _).trans (Nat.mul_le_mul_left _ (hg x))
+ _ ≤ b * D := by rw [← Finset.sum_mul]; exact Nat.mul_le_mul_right _ (hdeg i)
+ let vectors (i : I) (j : J) := (image i).coeff (t j)
+ have hdep : ¬ LinearIndependent E vectors := by
+ intro h
+ exact hcard.not_ge (by simpa only [Module.finrank_pi] using h.fintype_card_le_finrank)
+ obtain ⟨a, ha, i, hi⟩ := Fintype.not_linearIndependent_iff.mp hdep
+ let W : MvPolynomial X E := ∑ u, monomial (s u) (a u)
+ have nonzero : W ≠ 0 := by
+ intro hz
+ have h := congrArg (fun p : MvPolynomial X E => p.coeff (s i)) hz
+ exact hi (by simpa [W, coeff_sum, coeff_monomial, hinj.eq_iff] using h)
+ refine ⟨W, nonzero, ?_, ?_⟩
+ · apply totalDegree_finsetSum_le
+ intro u _
+ refine (totalDegree_monomial_le _ _).trans ?_
+ rw [Finsupp.sum_fintype _ _ (fun _ => rfl)]
+ exact hdeg u
+ · have him : aeval g W = ∑ u, a u • image u := by
+ simp only [W, map_sum, aeval_monomial, smul_eq_C_mul, algebraMap_eq]
+ apply Finset.sum_congr rfl
+ intro u _
+ rw [Finsupp.prod_fintype _ _ (by simp)]
+ rw [him]
+ let p := ∑ u, a u • image u
+ change p = 0
+ have hp : p.totalDegree ≤ b * D := totalDegree_finsetSum_le fun u _ =>
+ (totalDegree_smul_le (a u) (image u)).trans (image_deg u)
+ apply MvPolynomial.ext
+ intro d
+ by_cases hmem : d ∈ p.support
+ · obtain ⟨j, rfl⟩ := hcovers d ((le_totalDegree hmem).trans hp)
+ simpa [p, vectors, coeff_sum, coeff_smul, Finset.sum_apply] using congrFun ha j
+ · simpa using not_ne_iff.mp (mt mem_support_iff.mpr hmem)
+
+private noncomputable def sourceDegree {m b : ℕ} (u : Fin (b + 1) × Simplex m b) :
+ Fin (m + 1) →₀ ℕ :=
+ Finsupp.equivFunOnFinite.symm (Fin.cons u.1.val fun i => (u.2.val i).val)
+
+private theorem sourceDegree_injective {m b : ℕ} :
+ Function.Injective (sourceDegree (m := m) (b := b)) := by
+ intro u v h
+ apply Prod.ext
+ · exact Fin.ext (DFunLike.congr_fun h 0)
+ · apply Subtype.ext
+ funext i
+ exact Fin.ext (DFunLike.congr_fun h i.succ)
+
+private theorem sum_sourceDegree_le {m b : ℕ} (u : Fin (b + 1) × Simplex m b) :
+ ∑ x, sourceDegree u x ≤ 2 * b := by
+ rw [Fin.sum_univ_succ, two_mul]
+ exact Nat.add_le_add (Nat.le_of_lt_succ u.1.isLt) u.2.property
+
+private noncomputable def targetDegree {m T : ℕ} (v : Simplex m T) : Fin m →₀ ℕ :=
+ Finsupp.equivFunOnFinite.symm fun i => (v.val i).val
+
+private theorem targetDegree_covers {m T : ℕ} (d : Fin m →₀ ℕ)
+ (h : d.sum (fun _ n => n) ≤ T) : ∃ v : Simplex m T, targetDegree v = d := by
+ rw [Finsupp.sum_fintype _ _ (fun _ => rfl)] at h
+ have hb (i : Fin m) : d i ≤ T :=
+ (Finset.single_le_sum (fun j _ => Nat.zero_le (d j)) (Finset.mem_univ i)).trans h
+ refine ⟨⟨fun i => ⟨d i, Nat.lt_succ_of_le (hb i)⟩, h⟩, ?_⟩
+ ext i
+ rfl
+
+/-- Any `m + 1` polynomials of degree at most `D` in `m` variables satisfy a
+nonzero formal polynomial relation of total degree at most `2 * (2 * (D + 1)) ^ m`. -/
+theorem perron_relation {m D : ℕ} (g : Fin (m + 1) → MvPolynomial (Fin m) E)
+ (hg : ∀ i, (g i).totalDegree ≤ D) :
+ ∃ W : MvPolynomial (Fin (m + 1)) E,
+ W ≠ 0 ∧ W.totalDegree ≤ perronSimplexBound m D ∧ aeval g W = 0 :=
+ relation_of_count g hg (sourceDegree (b := perronRadius m D)) sourceDegree_injective
+ sum_sourceDegree_le targetDegree targetDegree_covers (perron_simplex_card_lt m D)
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PerronSimplex.lean b/lean/OAI/Computability/VPVNP/PerronSimplex.lean
new file mode 100644
index 0000000000..59a61e17a9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PerronSimplex.lean
@@ -0,0 +1,80 @@
+import Mathlib.Data.Fintype.BigOperators
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+import Mathlib.Algebra.BigOperators.Ring.Finset
+
+/-!
+# Counting monomials of bounded total degree for Perron's theorem
+
+Bound the exponent of the first input variable by `B` and the sum of the
+remaining `m` exponents by `B`. Substituting polynomials of degree at most
+`D` gives output monomials of total degree at most `2 * B * D`.
+Dividing each output exponent by `2 * (D + 1)` places the quotients in the
+simplex of degree `B`. The remainders account for at most `B` possibilities
+when `B = (2 * (D + 1)) ^ m`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+/-- Exponents of the monomials of total degree at most `d` in `m` variables. -/
+abbrev Simplex (m d : ℕ) := {e : Fin m → Fin (d + 1) // ∑ i, (e i).val ≤ d}
+
+/-- Degree bound on each of the two input blocks. -/
+def perronRadius (m D : ℕ) : ℕ := (2 * (D + 1)) ^ m
+
+/-- Total degree bound on the resulting polynomial relation. -/
+def perronSimplexBound (m D : ℕ) : ℕ := 2 * perronRadius m D
+
+/-- Divide each exponent by `q`, keeping both quotient and remainder. -/
+private def divideSimplex {m d B q : ℕ} (hq : 0 < q) (hd : d ≤ B * q) :
+ Simplex m d ↪ Simplex m B × (Fin m → Fin q) where
+ toFun e := by
+ have hsum : (∑ i, (e.val i).val / q) ≤ B := by
+ apply Nat.le_of_mul_le_mul_right _ hq
+ rw [Finset.sum_mul]
+ exact (Finset.sum_le_sum fun i _ ↦ Nat.div_mul_le_self (e.val i).val q).trans
+ (e.prop.trans hd)
+ let quotient (i : Fin m) : Fin (B + 1) := ⟨(e.val i).val / q, Nat.lt_succ_of_le
+ ((Finset.single_le_sum (fun j _ ↦ Nat.zero_le ((e.val j).val / q))
+ (Finset.mem_univ i)).trans hsum)⟩
+ exact (⟨quotient, hsum⟩, fun i ↦ ⟨(e.val i).val % q, Nat.mod_lt _ hq⟩)
+ inj' := by
+ intro e f h
+ apply Subtype.ext
+ funext i
+ apply Fin.ext
+ have hdiv : (e.val i).val / q = (f.val i).val / q :=
+ congrArg (fun x : Simplex m B × (Fin m → Fin q) ↦ (x.1.val i).val) h
+ have hmod : (e.val i).val % q = (f.val i).val % q :=
+ congrArg (fun x : Simplex m B × (Fin m → Fin q) ↦ (x.2 i).val) h
+ calc
+ _ = (e.val i).val % q + q * ((e.val i).val / q) := (Nat.mod_add_div _ _).symm
+ _ = _ := by rw [hmod, hdiv, Nat.mod_add_div]
+
+/-- There are strictly more input monomials in the two blocks than there are
+output monomials of the possible substituted degrees. -/
+theorem perron_simplex_card_lt (m D : ℕ) :
+ Fintype.card (Simplex m (perronSimplexBound m D * D)) <
+ Fintype.card (Fin (perronRadius m D + 1) × Simplex m (perronRadius m D)) := by
+ let B := perronRadius m D
+ let q := 2 * (D + 1)
+ have hq : 0 < q := Nat.mul_pos Nat.zero_lt_two (Nat.succ_pos D)
+ have hd : perronSimplexBound m D * D ≤ B * q := by
+ change 2 * B * D ≤ B * (2 * (D + 1))
+ rw [Nat.mul_comm 2 B, Nat.mul_assoc]
+ exact Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ (Nat.le_succ _))
+ have hle := Fintype.card_le_of_embedding (divideSimplex (m := m) hq hd)
+ simp only [Fintype.card_prod, Fintype.card_fun, Fintype.card_fin] at hle ⊢
+ change _ ≤ Fintype.card (Simplex m B) * B at hle
+ have : Nonempty (Simplex m B) := ⟨⟨fun _ ↦ 0, by simp⟩⟩
+ exact hle.trans_lt (by rw [Nat.mul_comm]; exact
+ Nat.mul_lt_mul_of_pos_right (Nat.lt_succ_self B) Fintype.card_pos)
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Pinning.lean b/lean/OAI/Computability/VPVNP/Pinning.lean
new file mode 100644
index 0000000000..5b817e8590
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Pinning.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.Circuits
+import OAI.Computability.VPVNP.PairedFamily
+import OAI.Computability.VPVNP.Hamiltonian
+import Mathlib.Algebra.MvPolynomial.Eval
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Algebra.BigOperators.GroupWithZero.Finset
+
+/-!
+# Pinning the program bits
+
+In §1.1 of *VP and VNP differ over every field*, a fixed prefix selects a
+program, and the remaining bits encode a directed graph. Pinning a prefix
+removes every monomial belonging to a different program. The Hamiltonian
+cycle projection follows whenever the selected program counts each spanning
+cycle once and rejects all other adjacency matrices within the clock.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped BigOperators
+open MvPolynomial
+
+section
+
+variable {E R : Type*} [CommSemiring R] {p k : ℕ}
+
+/-- The projection pins the prefix. Each suffix bit selects either one or its edge variable. -/
+def pinVariables (bits : Fin p → Bool) (edge : Fin k ≃ E) : Projection R (Fin (p + k) × Bool) E :=
+ fun v => Fin.append (fun i ↦ Sum.inr (if v.2 = bits i then 1 else 0))
+ (fun j ↦ if v.2 then Sum.inl (edge j) else Sum.inr 1) v.1
+
+private def appendEdgeBits (edge : Fin k ≃ E) :
+ ((Fin p → Bool) × (E → Bool)) ≃ (Fin (p + k) → Bool) where
+ toFun w := Fin.append w.1 (w.2 ∘ edge)
+ invFun w := (w ∘ Fin.castAdd k, fun e ↦ w (Fin.natAdd p (edge.symm e)))
+ left_inv := by
+ intro w
+ ext i <;> simp [Function.comp_def]
+ right_inv := by
+ intro w
+ simpa [Function.comp_def] using (Fin.append_castAdd_natAdd (f := w))
+
+private theorem pinVariables_product [Fintype E] (bits actual : Fin p → Bool)
+ (edge : Fin k ≃ E) (x : E → Bool) :
+ (∏ j, (pinVariables (R := R) bits edge (j, Fin.append actual (x ∘ edge) j)).elim X C) =
+ if actual = bits then ∏ e, if x e then X e else 1 else 0 := by
+ rw [Fin.prod_univ_add]
+ simp only [pinVariables, Fin.append_left, Fin.append_right, Function.comp_apply,
+ Sum.elim_inr, apply_ite C, map_one, map_zero,
+ apply_ite (fun z : E ⊕ R => z.elim X C), Sum.elim_inl]
+ simp only [Fintype.prod_boole, ← funext_iff]
+ split_ifs
+ · simpa using edge.prod_comp (fun e ↦ (if x e then X e else 1 : MvPolynomial E R))
+ · exact zero_mul _
+
+/-- The coefficient hypothesis concerns only words beginning with the chosen prefix. -/
+theorem pairedPolynomial_pin [Fintype E] [DecidableEq E] (bits : Fin p → Bool)
+ (edge : Fin k ≃ E) (u : (Fin (p + k) → Bool) → R) (w : (E → Bool) → R)
+ (agree : ∀ x, u (Fin.append bits (x ∘ edge)) = w x) :
+ (pinVariables bits edge).hom (pairedPolynomial u) = booleanPolynomial w := by
+ classical
+ simp only [Projection.hom, pairedPolynomial, map_sum, map_mul, eval₂Hom_C, map_prod, eval₂Hom_X']
+ rw [← (appendEdgeBits (p := p) edge).sum_comp, Fintype.sum_prod_type]
+ change (∑ a : Fin p → Bool, ∑ x : E → Bool, C (u (Fin.append a (x ∘ edge))) *
+ ∏ j, (pinVariables bits edge (j, Fin.append a (x ∘ edge) j)).elim X C) = _
+ simp only [pinVariables_product]
+ rw [Finset.sum_eq_single bits]
+ · simp [booleanPolynomial, agree]
+ · intro a _ ha
+ simp [ha]
+ · simp
+
+/-- Pinning a prefix whose coefficients recognize Hamiltonian adjacency matrices
+projects the family member at length `p + m * m` to the directed cycle polynomial. -/
+theorem pairedPolynomial_pin_hamiltonian (bits : Fin p → Bool) (m : ℕ)
+ (u : (Fin (p + m * m) → Bool) → R)
+ (agree : ∀ x : Fin m × Fin m → Bool,
+ u (Fin.append bits (x ∘ finProdFinEquiv.symm)) = cycleIndicator R m x) :
+ (pinVariables bits finProdFinEquiv.symm).hom (pairedPolynomial u) =
+ hamiltonianCyclePolynomial R m :=
+ (pairedPolynomial_pin bits finProdFinEquiv.symm u (cycleIndicator R m) agree).trans
+ (booleanPolynomial_cycleIndicator R m)
+
+/-- The selected integer counts may be recognized before base change to the field. -/
+theorem P_pin_hamiltonian {p : ℕ} (bits : Fin p → Bool) (m : ℕ)
+ (agree : ∀ x : Fin m × Fin m → Bool,
+ acceptingCount (Fin.append bits (x ∘ finProdFinEquiv.symm)) = cycleIndicator ℕ m x)
+ (S : Type*) [CommRing S] :
+ (pinVariables bits finProdFinEquiv.symm).hom
+ (MvPolynomial.map (Int.castRingHom S) (P (p + m * m))) =
+ hamiltonianCyclePolynomial S m := by
+ rw [map_P]
+ apply pairedPolynomial_pin_hamiltonian
+ intro x
+ rw [agree]
+ classical
+ simp [cycleIndicator, Nat.cast_ite]
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PlacedTensor.lean b/lean/OAI/Computability/VPVNP/PlacedTensor.lean
new file mode 100644
index 0000000000..bc272173ef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PlacedTensor.lean
@@ -0,0 +1,165 @@
+import OAI.Computability.VPVNP.WireSpectrum
+import OAI.Computability.VPVNP.StarTensor
+
+/-!
+# Moving local tensor factors to a common party set
+
+Under the placement of roles at parties used in Lemma 2.3 of *VP and VNP differ
+over every field*, independent linear maps on the original roles still act
+locally. At a party that carries several roles their matrix entries multiply.
+Regrouping tensor products, the unit tensor and zero arrays also commute with
+placement.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+universe u v w
+variable {k : Type u} {J : Type v} {R : Type} [Fintype R] [Fintype J]
+
+/-- Place the tensor's original factors on the specified parties. -/
+noncomputable def placeTensor (p : R → J) (T : Tensor.{u,0,w} k R) : Tensor.{u,v,w} k J :=
+ placedTensor p T.Basis T.coeff
+
+/-- A global assignment of the placed indices is the same as an assignment of
+the original indices, including when several roles share a party. -/
+def placedAssignmentEquiv (p : R → J) (B : R → Type w) :
+ ((r : R) → B r) ≃ ((j : J) → (r : R) → j = p r → B r) where
+ toFun x _ r _ := x r
+ invFun y r := y (p r) r rfl
+ left_inv _ := rfl
+ right_inv y := by
+ funext j r h
+ subst j
+ rfl
+
+section LinearMaps
+variable [CommSemiring k]
+
+/-- Local restrictions on the original roles act on their placed factors by
+taking the product of the matrix entries assigned to each party. -/
+theorem Restricts.placeTensor {T U : Tensor.{u,0,w} k R} (h : Restricts T U) (p : R → J) :
+ Restricts (placeTensor p T) (placeTensor p U) := by
+ classical
+ obtain ⟨L, hL⟩ := h
+ let M (j : J) (c : (r : R) → j = p r → U.Basis r)
+ (b : (r : R) → j = p r → T.Basis r) :=
+ ∏ r, if h : j = p r then L r (c r h) (b r h) else 1
+ refine ⟨M, ?_⟩
+ funext c
+ let e := placedAssignmentEquiv p T.Basis
+ let c₀ := fun r ↦ c (p r) r rfl
+ refine Eq.trans ?_ (congrFun hL c₀)
+ change (∑ b : (j : J) → (r : R) → j = p r → T.Basis r, (∏ j, M j (c j) (b j)) * T.coeff (fun r ↦ b (p r) r rfl)) =
+ ∑ b : (r : R) → T.Basis r, (∏ r, L r (c₀ r) (b r)) * T.coeff b
+ apply Fintype.sum_equiv e.symm
+ intro b
+ change (∏ j, M j (c j) (b j)) * T.coeff (fun r ↦ b (p r) r rfl) =
+ (∏ r, L r (c₀ r) (b (p r) r rfl)) * T.coeff (fun r ↦ b (p r) r rfl)
+ congr 1
+ unfold M
+ rw [Finset.prod_comm]
+ apply Finset.prod_congr rfl
+ intro r _
+ rw [Finset.prod_eq_single (p r)]
+ · simp [c₀]
+ · intro j _ hj
+ simp [hj]
+ · simp
+
+/-- Placement respects parallel tensor products up to local basis bijections. -/
+theorem placeTensor_tensorProduct (p : R → J) (T U : Tensor.{u,0,w} k R) :
+ Restricts (placeTensor p (tensorProduct T U)) (tensorProduct (placeTensor p T) (placeTensor p U)) ∧
+ Restricts (tensorProduct (placeTensor p T) (placeTensor p U)) (placeTensor p (tensorProduct T U)) := by
+ let e (j : J) :
+ ((r : R) → j = p r → T.Basis r) × ((r : R) → j = p r → U.Basis r) ≃
+ ((r : R) → j = p r → T.Basis r × U.Basis r) :=
+ { toFun := fun z r h ↦ (z.1 r h, z.2 r h)
+ invFun := fun z ↦ (fun r h ↦ (z r h).1, fun r h ↦ (z r h).2)
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+/-- Placing a unit tensor gives a unit tensor, up to local basis bijections. -/
+theorem placeTensor_unit (p : R → J) :
+ Restricts (unit : Tensor.{u,v,w} k J) (placeTensor p (unit : Tensor.{u,0,w} k R)) ∧
+ Restricts (placeTensor p (unit : Tensor.{u,0,w} k R)) (unit : Tensor.{u,v,w} k J) := by
+ apply restricts_of_reindex (fun j ↦ Equiv.equivPUnit ((r : R) → j = p r → PUnit))
+ intro _
+ rfl
+
+omit [Fintype J] in
+/-- The placed array vanishes exactly when its original array vanishes. -/
+theorem placeTensor_coeff_eq_zero_iff (p : R → J) (T : Tensor.{u,0,w} k R) :
+ (placeTensor p T).coeff = 0 ↔ T.coeff = 0 := by
+ constructor
+ · intro h
+ funext x
+ exact congrFun h (fun _ r _ ↦ x r)
+ · intro h
+ funext x
+ exact congrFun h (fun r ↦ x (p r) r rfl)
+
+/-- Placing the endpoint factors of a wire gives the wire on their image parties,
+including the case where the two endpoints coincide. -/
+theorem placeTensor_wire (p : R → J) (a b : R) (I : Type w) [Fintype I] :
+ Restricts (placeTensor p (wire (k := k) a b I)) (wire (p a) (p b) I) ∧
+ Restricts (wire (k := k) (p a) (p b) I) (placeTensor p (wire a b I)) := by
+ let e (j : J) : ((j = p a → I) × (j = p b → I)) ≃
+ ((r : R) → j = p r → (r = a → I) × (r = b → I)) :=
+ { toFun := fun x r h ↦ (fun h₁ ↦ x.1 (h.trans (congrArg p h₁)),
+ fun h₂ ↦ x.2 (h.trans (congrArg p h₂)))
+ invFun := fun y ↦ (fun h ↦ (y a h).1 rfl, fun h ↦ (y b h).2 rfl)
+ left_inv := fun _ ↦ rfl
+ right_inv := by
+ intro y
+ funext r h
+ apply Prod.ext
+ · funext ha
+ subst r
+ rfl
+ · funext hb
+ subst r
+ rfl }
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+end LinearMaps
+
+section Values
+
+variable {𝕜 : Type u} [Field 𝕜] (F : SpectralPoint 𝕜 J)
+
+namespace SpectralPoint
+
+/-- The spectral value of a placed tensor product is multiplicative. -/
+theorem value_placed_tensorProduct (p : R → J) (T U : Tensor.{u,0,0} 𝕜 R) :
+ F.value (placeTensor p (tensorProduct T U)) = F.value (placeTensor p T) * F.value (placeTensor p U) :=
+ (F.value_eq_of_mutual (placeTensor_tensorProduct p T U)).trans (F.value_tensorProduct _ _)
+
+/-- Placing all factors of a tensor power gives the corresponding power of
+the placed tensor's spectral value. -/
+theorem value_placed_tensorPowerFin (p : R → J) (n : ℕ) (T : Tensor.{u,0,0} 𝕜 R) :
+ F.value (placeTensor p (tensorPowerFin n T)) = F.value (placeTensor p T) ^ n := by
+ let Ts (_ : Fin n) := placeTensor p T
+ let e (j : J) : (Fin n → (r : R) → j = p r → T.Basis r) ≃
+ ((r : R) → j = p r → Fin n → T.Basis r) :=
+ { toFun := fun x r h i ↦ x i r h
+ invFun := fun x i r h ↦ x r h i
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ have h : Restricts (placeTensor p (tensorPowerFin n T)) (tensorFamilyProduct Ts) ∧
+ Restricts (tensorFamilyProduct Ts) (placeTensor p (tensorPowerFin n T)) :=
+ restricts_of_reindex e (fun _ ↦ rfl)
+ rw [F.value_eq_of_mutual h, F.value_tensorFamilyProduct]
+ simp [Ts]
+
+end SpectralPoint
+end Values
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PlacedTensorComposition.lean b/lean/OAI/Computability/VPVNP/PlacedTensorComposition.lean
new file mode 100644
index 0000000000..842759d4a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PlacedTensorComposition.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.PlacedTensor
+
+/-! # Composing placements of tensor legs
+
+Regrouping factors twice gives the same tensor as placing them along the
+composite map. The identity places each original leg back at its own
+party, and the inclusion into `Option J` adds a singleton center leg.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+variable {k : Type*} [CommSemiring k] {R J K : Type}
+ [Fintype R] [Fintype J] [Fintype K]
+
+/-- Two successive placements induce a canonical bijection of the grouped local bases. -/
+theorem placeTensor_comp_mutual (p : R → J) (q : J → K) (T : Tensor k R) :
+ Restricts (placeTensor q (placeTensor p T)) (placeTensor (q ∘ p) T) ∧
+ Restricts (placeTensor (q ∘ p) T) (placeTensor q (placeTensor p T)) := by
+ let e (x : K) : ((r : R) → x = q (p r) → T.Basis r) ≃
+ ((j : J) → x = q j → (r : R) → j = p r → T.Basis r) :=
+ { toFun := fun a _ h r hr ↦ a r (h.trans (congrArg q hr))
+ invFun := fun a r h ↦ a (p r) h r rfl
+ left_inv := fun _ ↦ rfl
+ right_inv := fun a ↦ by
+ funext j h r hr
+ subst j
+ rfl }
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+/-- Placing a tensor at its original parties simply relabels its bases. -/
+theorem placeTensor_id_mutual (T : Tensor k R) :
+ Restricts T (placeTensor id T) ∧ Restricts (placeTensor id T) T := by
+ let e (r : R) : ((s : R) → r = s → T.Basis s) ≃ T.Basis r :=
+ { toFun := fun a ↦ a r rfl
+ invFun := fun a s h ↦ h ▸ a
+ left_inv := fun a ↦ by funext s h; subst s; rfl
+ right_inv := fun _ ↦ rfl }
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+/-- Placing the old parties by the canonical injection into `Option` is the
+trivial extension of the tensor at the added party. -/
+theorem placeTensor_some_mutual (T : Tensor k R) :
+ Restricts (embedOld T) (placeTensor some T) ∧ Restricts (placeTensor some T) (embedOld T) := by
+ let e (j : Option R) : ((r : R) → j = some r → T.Basis r) ≃ (embedOld T).Basis j :=
+ match j with
+ | none =>
+ { toFun := fun _ ↦ PUnit.unit
+ invFun := fun _ _ h ↦ nomatch h
+ left_inv := fun _ ↦ by funext r h; exact nomatch h
+ right_inv := fun _ ↦ rfl }
+ | some s =>
+ { toFun := fun a ↦ a s rfl
+ invFun := fun a r h ↦ (Option.some.inj h) ▸ a
+ left_inv := fun a ↦ by funext r h; obtain rfl := Option.some.inj h; rfl
+ right_inv := fun _ ↦ rfl }
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PolynomialBounds.lean b/lean/OAI/Computability/VPVNP/PolynomialBounds.lean
new file mode 100644
index 0000000000..e485089fc5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PolynomialBounds.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.Classes
+
+/-!
+# Closure properties of nonuniform polynomial bounds
+
+The index of a p-projection may revisit small lengths infinitely often. A global
+bound by a power of `n + 1` handles those lengths when composing two indices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PolynomiallyBounded
+
+variable {f g : ℕ → ℕ}
+
+/-- An eventual upper estimate by a polynomially bounded function suffices. -/
+theorem of_eventually_le (hg : PolynomiallyBounded g) (N : ℕ)
+ (h : ∀ n ≥ N, f n ≤ g n) : PolynomiallyBounded f := by
+ obtain ⟨A, d, M, hM⟩ := hg
+ refine ⟨A, d, max N M, fun n hn => ?_⟩
+ exact (h n ((le_max_left ..).trans hn)).trans (hM n ((le_max_right ..).trans hn))
+
+theorem of_le (hg : PolynomiallyBounded g) (h : ∀ n, f n ≤ g n) : PolynomiallyBounded f :=
+ hg.of_eventually_le 0 fun n _ => h n
+
+theorem const (c : ℕ) : PolynomiallyBounded (fun _ => c) :=
+ ⟨c, 0, 0, fun _ _ => by simp⟩
+
+theorem id : PolynomiallyBounded (fun n => n) :=
+ ⟨1, 1, 0, fun _ _ => by simp⟩
+
+theorem add (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) :
+ PolynomiallyBounded (fun n => f n + g n) := by
+ obtain ⟨A, a, N, hA⟩ := hf
+ obtain ⟨B, b, M, hB⟩ := hg
+ refine ⟨A + B, max a b, max 1 (max N M), fun n hn => ?_⟩
+ have hn₁ : 1 ≤ n := (le_max_left ..).trans hn
+ have hN : N ≤ n := (le_max_left ..).trans ((le_max_right ..).trans hn)
+ have hM : M ≤ n := (le_max_right ..).trans ((le_max_right ..).trans hn)
+ rw [Nat.add_mul]
+ apply Nat.add_le_add
+ · exact (hA n hN).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right hn₁ (le_max_left ..)))
+ · exact (hB n hM).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right hn₁ (le_max_right ..)))
+
+theorem mul (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) :
+ PolynomiallyBounded (fun n => f n * g n) := by
+ obtain ⟨A, a, N, hA⟩ := hf
+ obtain ⟨B, b, M, hB⟩ := hg
+ refine ⟨A * B, a + b, max N M, fun n hn => ?_⟩
+ calc
+ f n * g n ≤ (A * n ^ a) * (B * n ^ b) :=
+ Nat.mul_le_mul (hA n ((le_max_left ..).trans hn)) (hB n ((le_max_right ..).trans hn))
+ _ = (A * B) * n ^ (a + b) := by rw [pow_add]; ac_rfl
+
+theorem pow (hf : PolynomiallyBounded f) (b : ℕ) :
+ PolynomiallyBounded (fun n => f n ^ b) := by
+ obtain ⟨A, a, N, hA⟩ := hf
+ exact ⟨A ^ b, a * b, N, fun n hn =>
+ by simpa only [mul_pow, pow_mul] using Nat.pow_le_pow_left (hA n hn) b⟩
+
+theorem succ : PolynomiallyBounded (fun n => n + 1) := id.add (const 1)
+
+/-- Absorb the finite initial segment of a bounded function into its leading constant. -/
+theorem exists_global_bound (hf : PolynomiallyBounded f) :
+ ∃ A d : ℕ, ∀ n, f n ≤ A * (n + 1) ^ d := by
+ obtain ⟨A, d, N, hA⟩ := hf
+ let B := ∑ i ∈ Finset.range N, f i
+ refine ⟨A + B, d, fun n => ?_⟩
+ by_cases hn : N ≤ n
+ · exact (hA n hn).trans (Nat.mul_le_mul (Nat.le_add_right ..)
+ (Nat.pow_le_pow_left (Nat.le_succ _) d))
+ · have hB : f n ≤ B := Finset.single_le_sum (fun i _ => Nat.zero_le (f i))
+ (Finset.mem_range.mpr (Nat.lt_of_not_ge hn))
+ exact hB.trans ((Nat.le_add_left B A).trans
+ (Nat.le_mul_of_pos_right _ (Nat.pow_pos (Nat.succ_pos _))))
+
+/-- Composition preserves polynomial bounds even for nonmonotone index functions. -/
+theorem comp (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) :
+ PolynomiallyBounded (fun n => f (g n)) := by
+ obtain ⟨A, d, hA⟩ := hf.exists_global_bound
+ exact ((const A).mul ((hg.add (const 1)).pow d)).of_le (fun n => hA (g n))
+
+end PolynomiallyBounded
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PolynomialPowerGap.lean b/lean/OAI/Computability/VPVNP/PolynomialPowerGap.lean
new file mode 100644
index 0000000000..b29e4abe63
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PolynomialPowerGap.lean
@@ -0,0 +1,51 @@
+import Mathlib.Analysis.SpecificLimits.Normed
+
+/-!
+# Polynomial losses in a finite sum of tensor powers
+
+The cut bounds in §4.2 of *VP and VNP differ over every field* have bases strictly
+smaller than the target spectral value. A polynomially growing multiplicity of
+terms across each cut preserves the eventual strict inequality.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open Filter Topology
+
+/-- A fixed polynomial factor times a finite sum of powers with smaller bases is
+eventually strictly smaller than the target power. -/
+theorem eventually_polynomial_weighted_pow_lt_target {ι : Type*} (cuts : Finset ι)
+ (weight base : ι → ℝ) (target : ℝ) (E : ℕ) (ht : 0 < target)
+ (hw : ∀ i ∈ cuts, 0 ≤ weight i) (hb : ∀ i ∈ cuts, 0 ≤ base i ∧ base i < target) :
+ ∀ᶠ h : ℕ in atTop, ((h : ℝ) + 2) ^ E * (∑ i ∈ cuts, weight i * base i ^ h) < target ^ h := by
+ have hi (i : ι) (hic : i ∈ cuts) : Tendsto (fun h : ℕ ↦
+ (3 ^ E * weight i) * ((h : ℝ) ^ E * (base i / target) ^ h)) atTop (𝓝 0) := by
+ have lower := div_nonneg (hb i hic).1 ht.le
+ have upper := (div_lt_one ht).mpr (hb i hic).2
+ simpa using (tendsto_pow_const_mul_const_pow_of_lt_one E lower upper).const_mul
+ (3 ^ E * weight i)
+ have hlim : Tendsto (fun h : ℕ ↦ ∑ i ∈ cuts,
+ (3 ^ E * weight i) * ((h : ℝ) ^ E * (base i / target) ^ h)) atTop (𝓝 0) := by
+ simpa using tendsto_finsetSum cuts hi
+ filter_upwards [eventually_ge_atTop (1 : ℕ), hlim.eventually_lt_const zero_lt_one] with h hh hlt
+ have hone : (1 : ℝ) ≤ h := by exact_mod_cast hh
+ have hshift : (h : ℝ) + 2 ≤ 3 * h := by linarith
+ have hsum : 0 ≤ ∑ i ∈ cuts, weight i * base i ^ h :=
+ Finset.sum_nonneg fun i hic ↦ mul_nonneg (hw i hic) (pow_nonneg (hb i hic).1 h)
+ refine (mul_le_mul_of_nonneg_right (pow_le_pow_left₀ (by positivity) hshift E) hsum).trans_lt ?_
+ apply (div_lt_one (pow_pos ht h)).mp
+ calc
+ (3 * (h : ℝ)) ^ E * (∑ i ∈ cuts, weight i * base i ^ h) / target ^ h =
+ ∑ i ∈ cuts, (3 * (h : ℝ)) ^ E * (weight i * base i ^ h) / target ^ h := by
+ simp only [Finset.mul_sum, div_eq_mul_inv, Finset.sum_mul]
+ _ = ∑ i ∈ cuts, (3 ^ E * weight i) * ((h : ℝ) ^ E * (base i / target) ^ h) := by
+ refine Finset.sum_congr rfl fun i _ ↦ ?_
+ rw [div_pow, mul_pow]
+ ring
+ _ < 1 := hlt
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PortDenominator.lean b/lean/OAI/Computability/VPVNP/PortDenominator.lean
new file mode 100644
index 0000000000..b2cf266a0e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PortDenominator.lean
@@ -0,0 +1,94 @@
+import Mathlib.LinearAlgebra.Matrix.Symmetric
+import Mathlib.Tactic.FieldSimp
+
+/-!
+# Integral multiplicities of a lazy Cesàro walk
+
+In Section 5.3 of *VP and VNP differ over every field*, the normalized
+adjacency matrix of a symmetric `b`-regular multigraph is made lazy and its
+first `t` positive powers are averaged. To realize this matrix on `Q` ports
+per vertex, multiply each entry by `Q`. The resulting natural counts are
+obtained from walks in the original multigraph with `b` extra loops at each
+vertex. The proof works over both the rationals and the reals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {V : Type*} [Fintype V] [DecidableEq V]
+
+private theorem sum_pow_row (B : Matrix V V ℕ) {d : ℕ} (hB : ∀ u, ∑ v, B u v = d)
+ (h : ℕ) (u : V) : ∑ v, (B ^ h) u v = d ^ h := by
+ induction h with
+ | zero => simp [Matrix.one_apply]
+ | succ h ih =>
+ simp only [pow_succ, Matrix.mul_apply]
+ rw [Finset.sum_comm]
+ simp_rw [← Finset.mul_sum, hB]
+ rw [← Finset.sum_mul, ih]
+
+/-- The Section 5.3 lazy transition matrix and its Cesàro average give
+symmetric natural port multiplicities with row sums `Q` whenever the common
+denominator `t * (2*b)^t` divides `Q`. The rational and real specializations
+use the same integer witness. -/
+theorem exists_cesaroPortCounts (K : Type*) [Field K] [CharZero K]
+ (G : Matrix V V ℕ) {b t Q : ℕ} (hb : 0 < b) (ht : 0 < t)
+ (hsym : ∀ u v, G u v = G v u) (hrow : ∀ u, ∑ v, G u v = b)
+ (hdiv : t * (2 * b) ^ t ∣ Q) :
+ let A : Matrix V V K := fun u v ↦ ((if u = v then 1 else 0) + G u v / (b : K)) / 2
+ let S : Matrix V V K := fun u v ↦ (∑ h ∈ Finset.range t, (A ^ (h + 1)) u v) / t
+ ∃ a : Matrix V V ℕ, (∀ u v, a u v = a v u) ∧ (∀ u, ∑ v, a u v = Q) ∧
+ ∀ u v, (a u v : K) = Q * S u v := by
+ intro A S
+ obtain ⟨k, rfl⟩ := hdiv
+ let d := 2 * b
+ let B : Matrix V V ℕ := fun u v ↦ (if u = v then b else 0) + G u v
+ have hBrow (u : V) : ∑ v, B u v = d := by simp [B, d, Finset.sum_add_distrib, hrow, two_mul]
+ have hBsym : B.IsSymm := Matrix.IsSymm.ext fun u v ↦ by
+ simp only [B, hsym v u, @eq_comm _ v u]
+ have hpow (h : ℕ) (hl : h ≤ t) : d ^ (t - h) * d ^ h = d ^ t := by
+ rw [← pow_add, Nat.sub_add_cancel hl]
+ let a : Matrix V V ℕ := fun u v ↦ k * ∑ h ∈ Finset.range t,
+ d ^ (t - (h + 1)) * (B ^ (h + 1)) u v
+ refine ⟨a, ?_, ?_, ?_⟩
+ · intro u v
+ dsimp only [a]
+ congr 1
+ exact Finset.sum_congr rfl fun h _ ↦ congrArg _ ((hBsym.pow _).apply v u)
+ · intro u
+ dsimp only [a]
+ rw [← Finset.mul_sum, Finset.sum_comm]
+ simp_rw [← Finset.mul_sum, sum_pow_row B hBrow]
+ rw [Finset.sum_congr rfl (fun h hh ↦ hpow (h + 1) (Finset.mem_range.mp hh))]
+ simp [d, mul_comm k]
+ · have hbK : (b : K) ≠ 0 := Nat.cast_ne_zero.mpr hb.ne'
+ have htK : (t : K) ≠ 0 := Nat.cast_ne_zero.mpr ht.ne'
+ have hmap : B.map (Nat.castRingHom K) = (d : K) • A := by
+ ext u v
+ change (((if u = v then b else 0) + G u v : ℕ) : K) =
+ ((2 * b : ℕ) : K) * (((if u = v then 1 else 0) + G u v / (b : K)) / 2)
+ split_ifs <;> push_cast <;> field_simp
+ simp
+ have hcast (h : ℕ) (u v : V) : ((B ^ h) u v : K) = (d : K) ^ h * (A ^ h) u v := by
+ change ((B ^ h).map (Nat.castRingHom K)) u v = _
+ rw [Matrix.map_pow, hmap, smul_pow, Matrix.smul_apply, smul_eq_mul]
+ intro u v
+ dsimp only [a, S]
+ push_cast
+ simp_rw [hcast, ← mul_assoc]
+ have hpowK (h : ℕ) (hh : h ∈ Finset.range t) :
+ (d : K) ^ (t - (h + 1)) * (d : K) ^ (h + 1) = (d : K) ^ t := by
+ rw [← pow_add, Nat.sub_add_cancel (Finset.mem_range.mp hh)]
+ rw [Finset.sum_congr rfl (fun h hh ↦ congrArg (· * (A ^ (h + 1)) u v) (hpowK h hh)),
+ ← Finset.mul_sum]
+ simp only [d, Nat.cast_mul, Nat.cast_ofNat]
+ field_simp
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PortMatching.lean b/lean/OAI/Computability/VPVNP/PortMatching.lean
new file mode 100644
index 0000000000..35e5713481
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PortMatching.lean
@@ -0,0 +1,120 @@
+import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise
+import Mathlib.Data.Fintype.BigOperators
+import Mathlib.Data.Fintype.EquivFin
+
+/-!
+# Matching ports with prescribed transition counts
+
+In the replacement construction of Section 5.3 of *VP and VNP differ over
+every field*, vertex `v` gets `Q` ports. Its ports are indexed by a
+destination `w` and an arc number in `Fin (a v w)`. Reversing an arc
+keeps this number, so symmetry of the multiplicity matrix gives an
+involution, with the ports for self-transitions fixed individually.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {V : Type*} [Fintype V] [DecidableEq V] {Q : ℕ}
+
+/-- A symmetric matrix of natural arc multiplicities with row sums `Q` is
+realized by an involution on `Q` ports at each vertex. -/
+theorem exists_portMatching (a : V → V → ℕ)
+ (hsym : ∀ v w, a v w = a w v) (hrow : ∀ v, ∑ w, a v w = Q) :
+ ∃ σ : Equiv.Perm (V × Fin Q), Function.Involutive σ ∧
+ (∀ v w, (Finset.univ.filter (fun k : Fin Q ↦ (σ (v, k)).1 = w)).card = a v w) ∧
+ (∀ p, (σ p).1 = p.1 → σ p = p) := by
+ let label (v : V) : (Σ w, Fin (a v w)) ≃ Fin Q :=
+ Fintype.equivFinOfCardEq (by simpa using hrow v)
+ let reverse (p : V × Fin Q) : V × Fin Q :=
+ let e := (label p.1).symm p.2
+ (e.1, label e.1 ⟨p.1, Fin.cast (hsym p.1 e.1) e.2⟩)
+ have edge (v w : V) (i : Fin (a v w)) :
+ reverse (v, label v ⟨w, i⟩) = (w, label w ⟨v, Fin.cast (hsym v w) i⟩) := by
+ exact congrArg (fun e : Σ u, Fin (a v u) ↦
+ (e.1, label e.1 ⟨v, Fin.cast (hsym v e.1) e.2⟩)) ((label v).symm_apply_apply _)
+ have hinv : Function.Involutive reverse := by
+ rintro ⟨v, k⟩
+ obtain ⟨⟨w, i⟩, rfl⟩ := (label v).surjective k
+ simp [edge]
+ let σ : Equiv.Perm (V × Fin Q) := ⟨reverse, reverse, hinv, hinv⟩
+ refine ⟨σ, hinv, ?_, ?_⟩
+ · intro v w
+ rw [Finset.card_filter]
+ calc
+ _ = ∑ e : Σ u, Fin (a v u), if e.1 = w then 1 else 0 :=
+ Fintype.sum_equiv (label v).symm _ _ (fun _ ↦ rfl)
+ _ = ∑ u, if u = w then a v u else 0 := by
+ rw [Fintype.sum_sigma]
+ apply Finset.sum_congr rfl
+ intro u _
+ by_cases h : u = w <;> simp [h]
+ _ = a v w := by simp
+ · rintro ⟨v, k⟩
+ obtain ⟨⟨w, i⟩, rfl⟩ := (label v).surjective k
+ change (reverse _).1 = v → reverse _ = _
+ rw [edge]
+ intro h
+ change w = v at h
+ subst w
+ rfl
+
+variable {K : Type*} [Fintype K] [DecidableEq K]
+
+/-- The replacement puts the graph on `K` inside each cloud and adds `h`
+copies of each port's matching arc. -/
+def replacementArcs (H : K → K → ℕ) (σ : Equiv.Perm (V × K)) (h : ℕ)
+ (p q : V × K) : ℕ :=
+ (if q.1 = p.1 then H p.2 q.2 else 0) + (if q = σ p then h else 0)
+
+omit [Fintype V] [Fintype K] in
+theorem replacementArcs_symmetric (H : K → K → ℕ) (hs : ∀ i j, H i j = H j i)
+ (σ : Equiv.Perm (V × K)) (hi : Function.Involutive σ) (h : ℕ) (p q : V × K) :
+ replacementArcs H σ h p q = replacementArcs H σ h q p := by
+ have hmatch : q = σ p ↔ p = σ q := ⟨fun e ↦ by rw [e, hi], fun e ↦ by rw [e, hi]⟩
+ simp only [replacementArcs, hmatch, hs p.2 q.2, eq_comm (a := q.1) (b := p.1)]
+
+/-- Each vertex in the replacement has the original degree `2 * h`. -/
+theorem replacementArcs_degree (H : K → K → ℕ) (h : ℕ) (hrow : ∀ i, ∑ j, H i j = h)
+ (σ : Equiv.Perm (V × K)) (p : V × K) : ∑ q, replacementArcs H σ h p q = 2 * h := by
+ simp only [replacementArcs, Finset.sum_add_distrib, Finset.sum_ite_eq', Finset.mem_univ,
+ ite_true, Nat.two_mul]
+ congr 1
+ rw [Fintype.sum_prod_type]
+ calc
+ _ = ∑ v, if v = p.1 then h else 0 := by
+ apply Finset.sum_congr rfl
+ intro v _
+ by_cases hv : v = p.1 <;> simp [hv, hrow]
+ _ = h := by simp
+
+/-- The final graph in Section 5.3 takes each old edge across the two layers
+and adds `b` vertical arcs at each vertex. -/
+def layerArcs (G : V → V → ℕ) (b : ℕ) (p q : V × Bool) : ℕ :=
+ if q.2 = !p.2 then G p.1 q.1 + (if q.1 = p.1 then b else 0) else 0
+
+omit [Fintype V] in
+theorem layerArcs_symmetric (G : V → V → ℕ) (hs : ∀ i j, G i j = G j i)
+ (b : ℕ) (p q : V × Bool) : layerArcs G b p q = layerArcs G b q p := by
+ obtain ⟨u, i⟩ := p
+ obtain ⟨v, j⟩ := q
+ cases i <;> cases j <;> simp [layerArcs, hs u v, eq_comm (a := v) (b := u)]
+
+omit [Fintype V] in
+theorem layerArcs_no_loops (G : V → V → ℕ) (b : ℕ) (p : V × Bool) : layerArcs G b p p = 0 := by
+ cases p with
+ | mk v i => cases i <;> rfl
+
+theorem layerArcs_degree (G : V → V → ℕ) (b : ℕ) (hrow : ∀ u, ∑ v, G u v = b)
+ (p : V × Bool) : ∑ q, layerArcs G b p q = 2 * b := by
+ rw [Fintype.sum_prod_type]
+ simp [layerArcs, Finset.sum_add_distrib, hrow, Nat.two_mul]
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PortWalkRealization.lean b/lean/OAI/Computability/VPVNP/PortWalkRealization.lean
new file mode 100644
index 0000000000..c01ff936f9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PortWalkRealization.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.CloudReplacement
+import OAI.Computability.VPVNP.PortDenominator
+import OAI.Computability.VPVNP.PortMatching
+
+/-!
+# Realizing a lazy Cesàro walk by a matching
+
+Section 5.3 of *VP and VNP differ over every field* takes one matching step
+at a uniform port to implement the averaged old walk exactly. Combining
+integer walk counts with port reversal gives the transition matrix itself.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {V : Type*} [Fintype V] [DecidableEq V]
+
+/-- One involution implements the mixture of the first `t` positive powers
+of the lazy walk of a symmetric regular graph. Self-transitions use fixed ports. -/
+theorem exists_cesaroPortMatching (G : Matrix V V ℕ) {b t Q : ℕ}
+ (hb : 0 < b) (ht : 0 < t) (hQ : 0 < Q)
+ (hs : ∀ v w, G v w = G w v) (hrow : ∀ v, ∑ w, G v w = b)
+ (hdiv : t * (2 * b) ^ t ∣ Q) :
+ ∃ σ : Equiv.Perm (V × Fin Q), Function.Involutive σ ∧
+ portWalk σ = cesaroWalk (lazyWalk (fun v w ↦ (G v w : ℝ) / b)) t ∧
+ (∀ p, (σ p).1 = p.1 → σ p = p) := by
+ obtain ⟨a, hasym, harow, hcounts⟩ := exists_cesaroPortCounts ℝ G hb ht hs hrow hdiv
+ obtain ⟨σ, hinv, hfiber, hfix⟩ := exists_portMatching a hasym harow
+ refine ⟨σ, hinv, ?_, hfix⟩
+ ext v w
+ rw [portWalk, hfiber, Fintype.card_fin]
+ apply (div_eq_iff (Nat.cast_ne_zero.mpr hQ.ne')).mpr
+ rw [mul_comm]
+ exact hcounts v w
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedBudget.lean b/lean/OAI/Computability/VPVNP/PrimedBudget.lean
new file mode 100644
index 0000000000..5fc661600a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedBudget.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.CursorBounds
+
+/-!
+# Capacity of the primed coefficient-counting RAM
+
+The virtual bucket definition includes one growing factor of the rounded
+binary logarithm. It absorbs any fixed constant in the two site scans and
+the preorder traversal, including a single comparison against the nominated
+histogram. The same choice leaves space in every two-address-width counter
+for all productions emitted by the pair.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open Filter CursorBounds Compression
+
+/-- A virtual bucket eventually covers any fixed number of external probes
+plus the startup charge. -/
+theorem eventually_virtualBucket_ge (K : ℕ) :
+ ∀ᶠ n : ℕ in atTop, K ≤ 2^(roundedUp 1 4 n) := by
+ filter_upwards [eventually_ge_atTop (K^4)] with n hn
+ have hp := Nat.le_pow_clog (by decide : 1 < 2^4) (n^1)
+ have h : n ≤ (2^(roundedUp 1 4 n))^4 := by
+ change n ≤ (2^(Nat.clog (2^4) (n^1)))^4
+ rw [← pow_mul, Nat.mul_comm, pow_mul]
+ simpa using hp
+ exact (Nat.pow_le_pow_iff_left (by decide : 4 ≠ 0)).mp (hn.trans h)
+
+/-- `O(Rn)` total probes and the final length-`t` histogram comparison
+fit the exact budget `R′K′`. The coefficient on the right of the work
+estimate is a fixed program constant. -/
+theorem eventually_pairExternalBudget (B K : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ t, t ≤ processorCount B n →
+ K * (processorCount B n * n + t + 1) ≤
+ 2^(virtualBits B n) * 2^(roundedUp 1 4 n) := by
+ filter_upwards [eventually_ge_atTop (2^(3*K)), eventually_ge_atTop 1] with n hn hn' t ht
+ let R := processorCount B n
+ have hR : 1 ≤ R := Nat.two_pow_pos _
+ have hlog : 3*K ≤ Nat.clog 2 n := by
+ have hf := (Nat.le_log2 (by omega : n ≠ 0)).mpr hn
+ rw [Nat.log2_eq_log_two] at hf
+ exact hf.trans (Nat.log_le_clog ..)
+ have hcap := (virtualSiteExponent_le_iff (addressWidth B n) n (virtualBits B n)).mp le_rfl
+ have hRn : R ≤ R*n := Nat.le_mul_of_pos_right _ hn'
+ calc
+ K*(R*n+t+1) ≤ K*(3*(R*n)) := by apply Nat.mul_le_mul_left; change t ≤ R at ht; omega
+ _ = (R*n)*(3*K) := by ac_rfl
+ _ ≤ R*n*Nat.clog 2 n := Nat.mul_le_mul_left _ hlog
+ _ ≤ _ := hcap
+
+/-- The full collection of `2R` trees of `n` leaves uses fewer than
+`2^(2r)` labels, so every individual counter and each intermediate counter
+fits in the advertised two-address-width field. -/
+theorem pairLabels_lt {B n : ℕ} (hB : 2 ≤ B) (hn : 5 ≤ n) :
+ 2 * processorCount B n * (2*n-1) < 2^(2 * addressWidth B n) := by
+ let R := processorCount B n
+ have hs : n^2 ≤ R := by
+ have hb := Nat.le_pow_clog (by decide : 1 < 2) n
+ calc
+ _ ≤ (2^(Nat.clog 2 n))^2 := Nat.pow_le_pow_left hb _
+ _ = 2^(2 * Nat.clog 2 n) := by rw [← pow_mul, Nat.mul_comm]
+ _ ≤ R := Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ hB)
+ have hsmall : 2*(2*n-1) < R := by
+ have h5 : 5*n ≤ n^2 := by rw [pow_two]; exact Nat.mul_le_mul_right _ hn
+ omega
+ rw [show 2 * addressWidth B n = addressWidth B n + addressWidth B n by omega, pow_add]
+ change 2*R*(2*n-1) < R*R
+ rw [show 2*R*(2*n-1) = R*(2*(2*n-1)) by ac_rfl]
+ exact Nat.mul_lt_mul_of_pos_left hsmall (Nat.two_pow_pos _)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterAdmin.lean b/lean/OAI/Computability/VPVNP/PrimedCounterAdmin.lean
new file mode 100644
index 0000000000..39518ffcc8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterAdmin.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.PrimedCounterRename
+import OAI.Computability.VPVNP.PrimedStackRAMNodeRun
+
+/-!
+# Administrative calls of the scheduled pair parser
+
+One clear call resets the leaf mark indexed by register 2. One initialization
+call installs the root in the first frame and sets the depth to one. Each
+comparison reads the dense production count and the corresponding nomination
+word indexed by register 7. Every instruction in these calls is deterministic.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Admin
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+
+/-- Include the eleven stack-parser operands in the first eleven positions of the fourteen-word
+administrative operand table. -/
+abbrev stackPublic (i : Fin 11) : Fin 14 := i.castLE (by decide)
+
+/-- The original mark-clear block installed into the enlarged public-word table. -/
+def clearOps : List (Op 16 14) := clearMark.map (renameOp id stackPublic)
+
+/-- Instructions that write the root degree and state into the first pending frame and set the
+stack depth to one. -/
+def initOps : List (Op 16 14) :=
+ [.publicWord 9 0, .publicWord 0 11, .write 9 0,
+ .publicWord 9 1, .publicWord 1 12, .write 9 1,
+ .publicWord 9 4, .constant 10 1, .write 9 10]
+
+/-- Guard the dense label index, load its accumulated count and nominated count, and require
+their equality. -/
+def compareOps : List (Op 16 14) :=
+ [.publicWord 11 10, .guardLt 7 11,
+ .publicWord 9 3, .binary .add 9 9 7, .read 14 9,
+ .publicWord 9 13, .binary .add 9 9 7, .read 15 9, .guardEq 14 15]
+
+/-- Straight-line routine that clears the mark for one terminal position. -/
+def clear : Flow 16 14 := lines clearOps (by decide)
+/-- Straight-line routine that initializes the pending parse stack at the root of the current
+site. -/
+def init : Flow 16 14 := lines initOps (by decide)
+/-- Straight-line routine checking the histogram count for one production against the
+nomination. -/
+def compare : Flow 16 14 := lines compareOps (by decide)
+
+variable {w : ℕ} (pub : Fin 14 → Word w) (state : Word w) (regs : Regs w 16) (mem : Memory w)
+
+theorem clear_trace (hj : regs 2 < pub 6) :
+ ∃ es rs, trace pub state clearOps regs mem = some (es, rs, writeMemory mem (pub 2 + regs 2) 0) ∧
+ countProbes es = 1 ∧ es.length = 6 ∧ choiceBits es = [] := by
+ change ∃ es rs, trace pub state
+ [.publicWord 11 6, .guardLt 2 11, .publicWord 9 2, .binary .add 9 9 2,
+ .constant 12 0, .write 9 12] regs mem = _ ∧ _
+ simp (config := { decide := true }) [trace, Op.effect, BinaryOp.eval, hj, Function.update,
+ countProbes, choiceBits]
+
+theorem clear_reject (hj : ¬regs 2 < pub 6) : trace pub state clearOps regs mem = none := by
+ change trace pub state
+ [.publicWord 11 6, .guardLt 2 11, .publicWord 9 2, .binary .add 9 9 2,
+ .constant 12 0, .write 9 12] regs mem = _
+ simp (config := { decide := true }) [trace, Op.effect, hj, Function.update]
+
+/-- External memory after storing the root degree, root state and initial stack depth at the
+parser's public addresses. -/
+def rootMemory (pub : Fin 14 → Word w) (mem : Memory w) : Memory w :=
+ writeMemory (writeMemory (writeMemory mem (pub 0) (pub 11)) (pub 1) (pub 12)) (pub 4) 1
+
+theorem init_trace :
+ ∃ es rs, trace pub state initOps regs mem = some (es, rs, rootMemory pub mem) ∧
+ countProbes es = 3 ∧ es.length = 9 ∧ choiceBits es = [] := by
+ simp (config := { decide := true }) [initOps, rootMemory, trace, Op.effect, Function.update,
+ countProbes, choiceBits]
+ rfl
+
+theorem compare_trace (hj : regs 7 < pub 10)
+ (heq : mem (pub 3 + regs 7).val = mem (pub 13 + regs 7).val) :
+ ∃ es rs, trace pub state compareOps regs mem = some (es, rs, mem) ∧
+ countProbes es = 2 ∧ es.length = 9 ∧ choiceBits es = [] := by
+ simp (config := { decide := true }) [compareOps, trace, Op.effect, BinaryOp.eval, hj, heq,
+ Function.update, countProbes, choiceBits]
+
+theorem compare_reject (h : ¬regs 7 < pub 10 ∨ mem (pub 3 + regs 7).val ≠ mem (pub 13 + regs 7).val) :
+ trace pub state compareOps regs mem = none := by
+ rcases h with h | h
+ · simp (config := { decide := true }) [compareOps, trace, Op.effect, Function.update, h]
+ · by_cases hj : regs 7 < pub 10 <;>
+ simp (config := { decide := true }) [compareOps, trace, Op.effect, BinaryOp.eval, Function.update, h, hj]
+
+end PrimedCounter.Admin
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterAdminExec.lean b/lean/OAI/Computability/VPVNP/PrimedCounterAdminExec.lean
new file mode 100644
index 0000000000..57144d8ef8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterAdminExec.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.PrimedCounterCall
+import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete
+import OAI.Computability.VPVNP.PrimedStackRAMNodeTable
+
+/-!
+# Straight-line executions of scheduled calls
+
+A straight-line trace gives the exact events, registers and memory of the corresponding
+structured body. Its instructions consume no choice bits. The scheduled call rejects any
+surplus bits when it compares the next cursor with the total and halts or returns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Admin
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+
+variable {w r k : ℕ} {pub : Fin k → Word w} {state : Word w}
+ {rs out : Regs w r} {m m' : Memory w} {es : List (Event w)}
+
+private theorem trace_cons_iff {op : Op r k} {ops : List (Op r k)} :
+ trace pub state (op :: ops) rs m = some (es, out, m') ↔
+ ∃ e r₁ m₁ fs, op.effect pub state rs m = some (e, r₁, m₁) ∧
+ trace pub state ops r₁ m₁ = some (fs, out, m') ∧ es = e :: fs := by
+ constructor
+ · intro ht
+ cases he : op.effect pub state rs m with
+ | none => simp [trace, he] at ht
+ | some a =>
+ obtain ⟨e, r₁, m₁⟩ := a
+ cases hf : trace pub state ops r₁ m₁ with
+ | none => simp [trace, he, hf] at ht
+ | some a =>
+ obtain ⟨fs, r₂, m₂⟩ := a
+ obtain ⟨rfl, rfl, rfl⟩ := by simpa [trace, he, hf] using ht
+ exact ⟨e, r₁, m₁, fs, rfl, hf, rfl⟩
+ · rintro ⟨e, r₁, m₁, fs, he, hf, rfl⟩
+ simp [trace, he, hf]
+
+private theorem exec_straight_iff_trace (op : Op r k) (ops : List (Op r k)) :
+ Flow.Exec pub state (straight op ops) rs m es out m' ↔
+ trace pub state (op :: ops) rs m = some (es, out, m') := by
+ induction ops generalizing op rs m es with
+ | nil =>
+ constructor
+ · intro h
+ cases h with
+ | line he => simp [trace, he]
+ · intro ht
+ obtain ⟨e, r₁, m₁, fs, he, hf, rfl⟩ := trace_cons_iff.mp ht
+ obtain ⟨rfl, rfl, rfl⟩ := by simpa [trace] using hf
+ exact .line he
+ | cons next rest ih =>
+ constructor
+ · intro h
+ cases h with
+ | seq first last =>
+ cases first with
+ | line he => exact trace_cons_iff.mpr ⟨_, _, _, _, he, (ih next).mp last, rfl⟩
+ · intro ht
+ obtain ⟨e, r₁, m₁, fs, he, hf, rfl⟩ := trace_cons_iff.mp ht
+ exact Flow.Exec.seq (.line he) ((ih next).mpr hf)
+
+/-- Compiling a nonempty list of lines preserves and reflects its entire trace. -/
+theorem exec_lines_iff_trace {ops : List (Op r k)} (hn : ops ≠ []) :
+ Flow.Exec pub state (lines ops hn) rs m es out m' ↔
+ trace pub state ops rs m = some (es, out, m') := by
+ cases ops with
+ | nil => contradiction
+ | cons op ops => exact exec_straight_iff_trace op ops
+
+/-- A successful straight-line trace contains only ticks, reads and writes. -/
+theorem trace_choiceBits {ops : List (Op r k)}
+ (ht : trace pub state ops rs m = some (es, out, m')) : choiceBits es = [] := by
+ induction ops generalizing rs m es with
+ | nil =>
+ have h : [] = es ∧ rs = out ∧ m = m' := by simpa [trace] using ht
+ rw [← h.1]
+ rfl
+ | cons op ops ih =>
+ obtain ⟨e, r₁, m₁, fs, he, hf, rfl⟩ := trace_cons_iff.mp ht
+ change choiceBits ([e] ++ fs) = []
+ rw [Flow.choiceBits_append, Flow.line_choices he, ih hf, List.nil_append]
+
+/-- A call whose body consumes no choices rejects every nonempty tape, for every fuel. -/
+theorem call_reject_nonempty {a : Flow r k} (next total : Fin r) (priv : Word w → Word w)
+ (det : ∀ {es out m'}, Flow.Exec pub state a rs m es out m' → choiceBits es = [])
+ (fuel : ℕ) {bits : List Bool} (hne : bits ≠ []) :
+ let M := (Call.template a next total).instantiate w pub
+ execute M.program fuel ⟨M.entry, state, rs, priv⟩ m bits = none := by
+ let M := (Call.template a next total).instantiate w pub
+ change execute M.program fuel ⟨M.entry, state, rs, priv⟩ m bits = none
+ cases hr : execute M.program fuel ⟨M.entry, state, rs, priv⟩ m bits with
+ | none => rfl
+ | some t =>
+ obtain ⟨es, out, m', left, bs, tail, he, _, hbits, htail, _⟩ :=
+ (Call.linked a next total pub).complete (Call.reject_code a next total pub) state priv rs m fuel bits t hr
+ rw [det he, List.nil_append] at hbits
+ subst bs
+ cases left with
+ | zero => contradiction
+ | succ f =>
+ cases f with
+ | zero =>
+ have hs : M.code (Call.stop a) = .jumpEq next total (Call.accept a) (Call.back a) := by
+ simp [M, Template.instantiate, Call.template, Call.stop, Instr.resize]
+ change execute M.program 1 ⟨Call.stop a, state, out, priv⟩ m' bits = some tail at htail
+ simp [execute, Machine.program, hs, Instr.run] at htail
+ | succ f =>
+ rw [Call.execute_stop] at htail
+ cases bits <;> simp_all
+
+/-- A scheduled straight-line body rejects every nonempty choice tape. -/
+theorem lines_call_reject_nonempty {ops : List (Op r k)} (hn : ops ≠ []) (next total : Fin r)
+ (priv : Word w → Word w) (fuel : ℕ) {bits : List Bool} (hne : bits ≠ []) :
+ let M := (Call.template (lines ops hn) next total).instantiate w pub
+ execute M.program fuel ⟨M.entry, state, rs, priv⟩ m bits = none :=
+ call_reject_nonempty next total priv (fun he => trace_choiceBits ((exec_lines_iff_trace hn).mp he)) fuel hne
+
+end PrimedCounter.Admin
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterAdminFrame.lean b/lean/OAI/Computability/VPVNP/PrimedCounterAdminFrame.lean
new file mode 100644
index 0000000000..29319d0272
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterAdminFrame.lean
@@ -0,0 +1,111 @@
+import OAI.Computability.VPVNP.PrimedStackRAMState
+
+/-!
+# Memory updates at the boundaries of the primed parser
+
+Before each site, the parser clears every location mark and installs a
+singleton root stack. The histogram survives these operations. After the
+last site, the comparison at a dense index reads the count of its unique
+production label.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Admin
+
+open BurstRAM PrimedStackRAM
+open scoped Fin.CommRing Classical
+
+variable {base R n m H w : ℕ} {mem : Memory w}
+variable {x : Fin 2 → Fin R → Fin m → Bool} {st : VisitState n m H}
+
+/-- Typed scratch stores preserve every word in the reserved prefix. -/
+theorem store_below (mem : Memory w) (c : Locations R n m H) (v : Word w)
+ (hf : base + size R n m (labelCount n m H) ≤ 2 ^ w) {a : ℕ} (ha : a < base) :
+ store base mem c v a = mem a := by
+ have hne : a ≠ address base c := by
+ unfold address
+ omega
+ simp [store, writeMemory, Nat.mod_eq_of_lt (address_lt hf c), hne]
+
+/-- One clear call erases exactly the selected location from the logical mark set. -/
+theorem clear_holds (hr : Holds base x st mem) (j : Fin m)
+ (hf : base + size R n m (labelCount n m H) ≤ 2 ^ w) :
+ Holds base x {st with marked := st.marked.erase j}
+ (store base mem (markCell j : Locations R n m H) 0) := by
+ have hview (a : Locations R n m H) (hne : a ≠ markCell j) :
+ view base (store base mem (markCell j : Locations R n m H) 0) a = view base mem a := by
+ rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (fun h => (hne h).elim)]
+ refine ⟨⟨hr.pending.fits, ?_, ?_, ?_⟩, ?_, ?_, ?_⟩
+ · rw [hview _ (by simp [depthCell, markCell])]
+ exact hr.pending.depth
+ · intro i
+ rw [hview _ (by simp [degCell, markCell])]
+ exact hr.pending.degrees i
+ · intro i
+ rw [hview _ (by simp [stateCell, markCell])]
+ exact hr.pending.states i
+ · intro g s i
+ rw [hview _ (by simp [markCell])]
+ exact hr.input g s i
+ · intro i
+ rw [view_store_apply _ _ _ _ _ hf, hr.marked]
+ by_cases hi : i = j <;> simp [markCell, hi]
+ · intro a
+ rw [hview _ (by simp [countCell, markCell])]
+ exact hr.counts a
+
+/-- Install a frame in slot zero and overwrite the old stack depth with one. -/
+def rootStore (base R m : ℕ) (mem : Memory w) (d : Fin n) (root : Fin H) : Memory w :=
+ let slot : Fin n := ⟨0, (Nat.zero_le d.val).trans_lt d.isLt⟩
+ store base (store base (store base mem (degCell slot : Locations R n m H) (d.val : Word w))
+ (stateCell slot : Locations R n m H) (root.val : Word w)) (depthCell : Locations R n m H) 1
+
+/-- The three root stores leave every input bit, mark and production count intact. -/
+theorem root_data (mem : Memory w) (d : Fin n) (root : Fin H)
+ (hf : base + size R n m (labelCount n m H) ≤ 2 ^ w) :
+ DataEq base R n m H mem (rootStore base R m mem d root) := by
+ intro c hc
+ have hne (a : Locations R n m H) (ha : dataCell a = false) : c ≠ a := by
+ rintro rfl
+ simp [ha] at hc
+ simp [rootStore, view_store_apply _ _ _ _ _ hf, hne depthCell rfl,
+ hne (degCell _) rfl, hne (stateCell _) rfl]
+
+/-- The root stores install a singleton stack regardless of the old depth or frame words. -/
+theorem root_rep (mem : Memory w) (d : Fin n) (root : Fin H)
+ (hf : base + size R n m (labelCount n m H) ≤ 2 ^ w) :
+ Represents (R := R) (n := n) (m := m) (H := H) base
+ (rootStore base R m mem d root) (frames w [(d,root)]) := by
+ have hn : 1 ≤ n := (Nat.zero_le d.val).trans_lt d.isLt
+ have hw : 1 < 2 ^ w := hn.trans_lt (capacity_fit base hf)
+ change Represents (R := R) (n := n) (m := m) (H := H) base
+ (rootStore base R m mem d root) [((d.val : Word w), (root.val : Word w))]
+ refine ⟨hn, ?_, ?_, ?_⟩
+ · simp [rootStore, view_store_apply _ _ _ _ _ hf, Nat.mod_eq_of_lt hw]
+ all_goals
+ rintro ⟨i, hi⟩
+ obtain rfl : i = 0 := by simp at hi; omega
+ simp [rootStore, view_store_apply _ _ _ _ _ hf, depthCell, degCell, stateCell, Fin.castLE]
+
+/-- Root initialization installs a singleton pending stack for the new site. -/
+theorem root_holds (hr : Holds base x st mem) (d : Fin n) (root : Fin H)
+ (hf : base + size R n m (labelCount n m H) ≤ 2 ^ w) :
+ Holds base x {st with pending := [(d,root)]} (rootStore base R m mem d root) :=
+ hr.withStack _ (root_data mem d root hf) (root_rep mem d root hf)
+
+/-- The final word comparison tests the exact logical production count. -/
+theorem compare_iff (hr : Holds base x st mem) (j : Fin (labelCount n m H)) (v : Word w) :
+ view base mem (countCell j : Locations R n m H) = v ↔
+ st.counts ((labelIndex n m H).symm j) = v.val := by
+ have hc := hr.counts ((labelIndex n m H).symm j)
+ rw [Equiv.apply_symm_apply] at hc
+ rw [Fin.ext_iff, hc]
+
+end PrimedCounter.Admin
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterAdminInitial.lean b/lean/OAI/Computability/VPVNP/PrimedCounterAdminInitial.lean
new file mode 100644
index 0000000000..2346d0c463
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterAdminInitial.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PrimedCounterAdminFrame
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+
+/-!
+# Initial parser state after the primed input passes
+
+The parser's input rectangle is the output of the second pass. Its stack,
+marks and production counters begin immediately beyond that rectangle. The
+prescribed header memory initializes these scratch cells to zero and stores
+the nominated histogram before the first-pass rectangle.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Admin
+
+open BurstRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {L : Lengths} {n r H s w : ℕ} (Q : Layout L n r H w)
+variable (hdr : Header L → Bool) (bits : Internal L r H w → Bool) (hist : List (Word w))
+
+private theorem assembled_outside (bitWord : Bool → Word w) (initial : Memory w) (a : ℕ)
+ (ha : a < Q.scratchBase ∨ Q.scratchBase + PrimedInputRAM.positions n r + PrimedInputRAM.positions n r ≤ a) :
+ Q.assembled bitWord bits initial a = initial a := by
+ rw [Layout.assembled, secondPass_outside]
+ · apply store_outside
+ intro i _
+ change a ≠ Q.scratchBase + i.val
+ have := i.isLt
+ omega
+ · intro i
+ change a ≠ Q.scratchBase + PrimedInputRAM.positions n r + i.val
+ have := i.isLt
+ omega
+
+/-- Each nomination word remains available at the prescribed histogram offset. -/
+theorem assembled_nomination (hf : Header.count L + hist.length ≤ Q.scratchBase)
+ (j : Fin hist.length) :
+ Q.assembled (encodeBit w) bits (headerMemory L hdr hist) (Header.count L + j.val) = hist[j] := by
+ rw [assembled_outside Q bits _ _ _ (Or.inl (by have := j.isLt; omega)), headerMemory_hist]
+ simp [j.isLt]
+
+/-- After both passes the pending list, marks and accumulated histogram are empty,
+while every terminal read already sees its prescribed input bit. -/
+theorem assembled_holds (hf : Header.count L + hist.length ≤ Q.scratchBase) :
+ Holds (Q.scratchBase + PrimedInputRAM.positions n r)
+ (fun g v j => input Q.program Q.fits hdr bits (g,v) j)
+ (⟨[], ∅, 0⟩ : VisitState n n s)
+ (Q.assembled (encodeBit w) bits (headerMemory L hdr hist)) := by
+ let base := Q.scratchBase + PrimedInputRAM.positions n r
+ let final := Q.assembled (encodeBit w) bits (headerMemory L hdr hist)
+ have hzero (a : ℕ) (ha : base + PrimedInputRAM.positions n r ≤ a) : final a = 0 := by
+ change Q.assembled (encodeBit w) bits (headerMemory L hdr hist) a = _
+ rw [assembled_outside Q bits _ _ _ (Or.inr ha)]
+ have he : Header.count L + (a - Header.count L) = a := by dsimp [base] at ha; omega
+ rw [← he, headerMemory_hist, List.getElem?_eq_none (by dsimp [base] at ha; omega)]
+ rfl
+ refine ⟨⟨by simp [frames], ?_, fun i => i.elim0, fun i => i.elim0⟩, ?_, ?_, ?_⟩
+ · change (final (address base (depthCell : Locations (2^r) n n s))).val = 0
+ rw [depthCell, address_depth, hzero _ (by unfold PrimedInputRAM.positions; omega)]
+ rfl
+ · intro g v j
+ have haddr : (Q.outputAddress (finProdFinEquiv (finProdFinEquiv (g,v), j))).val =
+ address base (.inl ((g,v),j) : Locations (2^r) n n s) := by
+ rw [address_input]
+ change base + (j.val + n * (v.val + 2^r * g.val)) = _
+ ring
+ unfold view
+ rw [← haddr, Q.assembled_input _ bits hdr _ (headerMemory_bits L hdr hist)]
+ cases input Q.program Q.fits hdr bits (g,v) j <;> simp [encodeBit]
+ · intro j
+ change final (address base (markCell j : Locations (2^r) n n s)) = _
+ rw [markCell, address_mark, hzero _ (by unfold PrimedInputRAM.positions; omega)]
+ simp
+ · intro a
+ change (final (address base (countCell (labelIndex n n s a) : Locations (2^r) n n s))).val = _
+ rw [countCell, address_hist, hzero _ (by unfold PrimedInputRAM.positions; omega)]
+ rfl
+
+end PrimedCounter.Admin
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterAdminRun.lean b/lean/OAI/Computability/VPVNP/PrimedCounterAdminRun.lean
new file mode 100644
index 0000000000..d1bb89a7e1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterAdminRun.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.PrimedCounterAdmin
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PrimedCounterAdminFrame
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+
+/-!
+# Logical memory effects of scheduled administrative calls
+
+The enlarged public table embeds the parser's eleven public words and supplies
+the root and the nomination base in its last three entries. The following
+executions apply to any such embedding, including the scratch rectangle after
+input assembly. All writes retain every word in the reserved prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Admin
+
+open BurstRAM PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing Classical
+
+variable {w R n m H base : ℕ} {pub : Fin 14 → Word w}
+variable (hp : pub ∘ stackPublic = publicData w base R n m H)
+variable (hf : base + size R n m (labelCount n m H) ≤ 2^w)
+variable (state : Word w) (regs : Regs w 16) (mem : Memory w)
+
+include hp
+
+private theorem stack_word (i : ℕ) (hi : i < 11 := by decide) :
+ pub (OfNat.ofNat i) = publicData w base R n m H (OfNat.ofNat i) := by
+ have he : (OfNat.ofNat i : Fin 14) = stackPublic (OfNat.ofNat i : Fin 11) := by
+ apply Fin.ext
+ change i % 14 = i % 11
+ rw [Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt (by omega : i < 14)]
+ rw [he]
+ exact congrFun hp _
+
+include hf
+
+/-- Clear one in-range mark and retain the entire prefix below the scratch base. -/
+theorem clear_cell (j : Fin m) (hj : regs 2 = (j.val : Word w)) :
+ let out := store base mem (markCell j : Locations R n m H) 0
+ ∃ es rs, Flow.Exec pub state clear regs mem es rs out ∧
+ countProbes es = 1 ∧ es.length = 6 ∧ choiceBits es = [] ∧ ∀ a < base, out a = mem a := by
+ dsimp only
+ have hm : m < 2^w := by unfold size at hf; omega
+ have hj' : regs 2 < pub 6 := by
+ rw [hj, stack_word hp 6]
+ change (j.val : Word w).val < (m : Word w).val
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt (j.isLt.trans hm), Nat.mod_eq_of_lt hm] using j.isLt
+ obtain ⟨es,rs,ht,hc,hl,hb⟩ := clear_trace pub state regs mem hj'
+ rw [stack_word hp 2, hj, public_mark base j] at ht
+ exact ⟨es,rs,(exec_lines_iff_trace _).mpr ht,hc,hl,hb,fun _ ha => store_below _ _ _ hf ha⟩
+
+omit hf in
+theorem rootMemory_eq (d : Fin n) (root : Fin H) (hd : pub 11 = (d.val : Word w))
+ (hr : pub 12 = (root.val : Word w)) :
+ rootMemory pub mem = rootStore base R m mem d root := by
+ let slot : Fin n := ⟨0, (Nat.zero_le d.val).trans_lt d.isLt⟩
+ have hdeg := public_degree (R := R) (m := m) (H := H) (w := w) base slot
+ have hstate := public_state (R := R) (m := m) (H := H) (w := w) base slot
+ simp only [slot, Nat.cast_zero, add_zero] at hdeg hstate
+ rw [rootMemory, hd, hr, stack_word hp 0, stack_word hp 1, stack_word hp 4, hdeg, hstate, public_depth base]
+ rfl
+
+/-- Initialize the singleton pending stack. Every data cell and every word
+below the scratch rectangle retain their prior values. -/
+theorem init_cell (d : Fin n) (root : Fin H) (hd : pub 11 = (d.val : Word w))
+ (hr : pub 12 = (root.val : Word w)) :
+ let out := rootStore base R m mem d root
+ ∃ es rs, Flow.Exec pub state init regs mem es rs out ∧
+ countProbes es = 3 ∧ es.length = 9 ∧ choiceBits es = [] ∧
+ Represents (R := R) (n := n) (m := m) (H := H) base out (frames w [(d,root)]) ∧
+ DataEq base R n m H mem out ∧ ∀ a < base, out a = mem a := by
+ obtain ⟨es,rs,ht,hc,hl,hb⟩ := init_trace pub state regs mem
+ rw [rootMemory_eq hp mem d root hd hr] at ht
+ refine ⟨es,rs,(exec_lines_iff_trace _).mpr ht,hc,hl,hb,root_rep mem d root hf,root_data mem d root hf,?_⟩
+ intro a ha
+ simp only [rootStore, store_below _ _ _ hf ha]
+
+private theorem count_words (j : Fin (labelCount n m H)) (hj : regs 7 = (j.val : Word w))
+ (L : Lengths) (hn : pub 13 = (Header.count L : Word w))
+ (hprefix : Header.count L + labelCount n m H ≤ base) :
+ regs 7 < pub 10 ∧
+ mem (pub 3 + regs 7).val = view base mem (countCell j : Locations R n m H) ∧
+ mem (pub 13 + regs 7).val = mem (Header.count L + j.val) := by
+ have hT : labelCount n m H < 2^w := by unfold size at hf; omega
+ have ha := Nat.add_lt_add_left j.isLt (Header.count L)
+ have hnom : Header.count L + j.val < 2^w := by omega
+ refine ⟨?_, ?_, ?_⟩
+ · rw [hj, stack_word hp 10]
+ change (j.val : Word w).val < (labelCount n m H : Word w).val
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt (j.isLt.trans hT), Nat.mod_eq_of_lt hT] using j.isLt
+ · rw [hj, stack_word hp 3, public_count base j, Fin.val_natCast, Nat.mod_eq_of_lt (address_lt hf (countCell j))]
+ rfl
+ · rw [hn, hj, ← Nat.cast_add, Fin.val_natCast, Nat.mod_eq_of_lt hnom]
+
+variable {x : Fin 2 → Fin R → Fin m → Bool} {st : VisitState n m H}
+
+/-- The physical comparison succeeds with its two reads precisely when the
+logical count equals the nominated unsigned word. A successful comparison leaves memory intact. -/
+theorem compare_cell (held : Holds base x st mem) (j : Fin (labelCount n m H))
+ (hj : regs 7 = (j.val : Word w)) (L : Lengths) (hn : pub 13 = (Header.count L : Word w))
+ (hprefix : Header.count L + labelCount n m H ≤ base) :
+ let agrees := st.counts ((labelIndex n m H).symm j) = (mem (Header.count L + j.val)).val
+ (agrees → ∃ es rs, Flow.Exec pub state compare regs mem es rs mem ∧
+ countProbes es = 2 ∧ es.length = 9 ∧ choiceBits es = []) ∧
+ (¬ agrees → ∀ es rs out, ¬Flow.Exec pub state compare regs mem es rs out) := by
+ obtain ⟨hbound,hcount,hnom⟩ := count_words hp hf regs mem j hj L hn hprefix
+ have he : mem (pub 3 + regs 7).val = mem (pub 13 + regs 7).val ↔
+ st.counts ((labelIndex n m H).symm j) = (mem (Header.count L + j.val)).val := by
+ rw [hcount, hnom]
+ exact compare_iff held j (mem (Header.count L + j.val))
+ constructor
+ · intro h
+ obtain ⟨es,rs,ht,hc,hl,hb⟩ := compare_trace pub state regs mem hbound (he.mpr h)
+ exact ⟨es,rs,(exec_lines_iff_trace _).mpr ht,hc,hl,hb⟩
+ · intro h es rs out hx
+ have ht := (exec_lines_iff_trace (ops := compareOps) (by decide)).mp hx
+ rw [compare_reject pub state regs mem (Or.inr (fun hh => h (he.mp hh)))] at ht
+ contradiction
+
+end PrimedCounter.Admin
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterBits.lean b/lean/OAI/Computability/VPVNP/PrimedCounterBits.lean
new file mode 100644
index 0000000000..1c6a237d4e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterBits.lean
@@ -0,0 +1,191 @@
+import OAI.Computability.VPVNP.PrimedCounterStack
+import OAI.Computability.VPVNP.RAMWordBits
+
+/-!
+# Fixed-width binary choices for a primed node
+
+The root degree on the stack determines how many words to read. Each location,
+split or child state has one little-endian encoding. A choice word outside its
+required range, or a call with excess or missing bits, is rejected.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open BurstRAM ParseGrammar
+
+variable {n m s w : ℕ}
+
+/-- Canonical little-endian representation of an in-range natural. -/
+def digits (w k : ℕ) : List Bool := wordBits (Fin.ofNat (2^w) k)
+
+/-- Consume a word and check the upper bound on its value. -/
+def takeBounded (w bound : ℕ) (bits : List Bool) : Option (Fin bound × List Bool) := do
+ let (v, tail) ← takeWord w bits
+ if hv : v.val < bound then return (⟨v.val, hv⟩, tail) else none
+
+theorem takeBounded_eq (bound : ℕ) (hfit : bound ≤ 2^w) (bits : List Bool)
+ (i : Fin bound) (tail : List Bool) :
+ takeBounded w bound bits = some (i, tail) ↔ bits = digits w i.val ++ tail := by
+ constructor
+ · intro h
+ cases hr : takeWord w bits with
+ | none => simp [takeBounded, hr] at h
+ | some v =>
+ obtain ⟨v, rest⟩ := v
+ by_cases hv : v.val < bound
+ · simp [takeBounded, hr, hv] at h
+ obtain ⟨rfl, rfl⟩ := h
+ simpa [digits] using (takeWord_eq_some_iff ..).1 hr
+ · simp [takeBounded, hr, hv] at h
+ · rintro rfl
+ let a : Word w := ⟨i.val, i.isLt.trans_le hfit⟩
+ have ha : Fin.ofNat (2^w) i.val = a := Fin.ext (Nat.mod_eq_of_lt a.isLt)
+ have hr : takeWord w (digits w i.val ++ tail) = some (a,tail) :=
+ (takeWord_eq_some_iff ..).2 (by rw [digits, ha])
+ simp [takeBounded, hr, a, i.isLt]
+
+/-- Exactly the branch bits consumed in one node call. No discriminator is guessed. -/
+def encodeToken (w : ℕ) : Token m (Fin s) → List Bool
+ | .terminal j => digits w j.val
+ | .binary b i j => digits w b ++ digits w i.val ++ digits w j.val
+
+theorem length_encodeToken_le (t : Token m (Fin s)) : (encodeToken w t).length ≤ 3 * w := by
+ cases t <;> simp [encodeToken, digits] <;> omega
+
+/-- The dynamic range check at a node. -/
+def Legal (d : ℕ) : Token m (Fin s) → Prop
+ | .terminal _ => d = 0
+ | .binary b _ _ => b < d
+
+/-- Each call must exhaust precisely the choices for its pending node. -/
+def readToken (w m s d : ℕ) (bits : List Bool) : Option (Token m (Fin s)) := do
+ if d = 0 then
+ let (j, rest) ← takeBounded w m bits
+ if rest.isEmpty then return .terminal j else none
+ else
+ let (b, bits) ← takeBounded w d bits
+ let (i, bits) ← takeBounded w s bits
+ let (j, rest) ← takeBounded w s bits
+ if rest.isEmpty then return .binary b.val i j else none
+
+theorem readToken_sound (hm : m ≤ 2^w) (hs : s ≤ 2^w) {d : ℕ} (hd : d ≤ 2^w)
+ {bs : List Bool} {t : Token m (Fin s)} (hr : readToken w m s d bs = some t) :
+ Legal d t ∧ bs = encodeToken w t := by
+ by_cases hz : d = 0
+ · cases hh : takeBounded w m bs with
+ | none => simp [readToken, hz, hh] at hr
+ | some v =>
+ obtain ⟨j, rest⟩ := v
+ simp [readToken, hz, hh] at hr
+ obtain ⟨rfl, rfl⟩ := hr
+ exact ⟨hz, by simpa [encodeToken] using (takeBounded_eq m hm bs j []).1 hh⟩
+ · cases hb : takeBounded w d bs with
+ | none => simp [readToken, hz, hb] at hr
+ | some v =>
+ obtain ⟨b, xs⟩ := v
+ cases hi : takeBounded w s xs with
+ | none => simp [readToken, hz, hb, hi] at hr
+ | some v =>
+ obtain ⟨i, ys⟩ := v
+ cases hj : takeBounded w s ys with
+ | none => simp [readToken, hz, hb, hi, hj] at hr
+ | some v =>
+ obtain ⟨j, rest⟩ := v
+ simp [readToken, hz, hb, hi, hj] at hr
+ obtain ⟨rfl, rfl⟩ := hr
+ rw [(takeBounded_eq d hd bs b xs).1 hb, (takeBounded_eq s hs xs i ys).1 hi,
+ (takeBounded_eq s hs ys j []).1 hj]
+ simp [Legal, encodeToken]
+
+theorem readToken_encode (hm : m ≤ 2^w) (hs : s ≤ 2^w) {d : ℕ} (hd : d ≤ 2^w)
+ (t : Token m (Fin s)) (hl : Legal d t) :
+ readToken w m s d (encodeToken w t) = some t := by
+ cases t with
+ | terminal j =>
+ subst d
+ have hr := (takeBounded_eq m hm (digits w j.val) j []).2 (by simp)
+ simp [readToken, encodeToken, hr]
+ | binary b i j =>
+ let split : Fin d := ⟨b, hl⟩
+ have hz : d ≠ 0 := by change b < d at hl; omega
+ have hb := (takeBounded_eq d hd (encodeToken w (.binary b i j : Token m (Fin s))) split
+ (digits w i.val ++ digits w j.val)).2 (by simp [encodeToken, split, List.append_assoc])
+ have hi := (takeBounded_eq s hs (digits w i.val ++ digits w j.val) i (digits w j.val)).2 rfl
+ have hj := (takeBounded_eq s hs (digits w j.val) j []).2 (by simp)
+ simp [readToken, hz, hb, hi, hj, split]
+
+/-- A successful stack operation requires a legal node choice. -/
+theorem legal_of_step {x : Fin m → Bool} {f : Frame n (Fin s)} {t : Token m (Fin s)}
+ {out : Label n m (Fin s) × List (Frame n (Fin s))} (hh : step x f t = some out) : Legal f.1.val t := by
+ obtain ⟨⟨k, hk⟩, h⟩ := f
+ cases k <;> cases t <;> simp_all [step, Legal]
+ exact hh.choose
+
+/-- Binary decoding and stack traversal together, with one branch-bit list per call. -/
+def decodeVisits (w : ℕ) (x : Fin m → Bool) :
+ List (Frame n (Fin s)) → List (List Bool) → Option (List (Token m (Fin s)))
+ | [], [] => some []
+ | [], _ :: _ | _ :: _, [] => none
+ | f :: stack, bs :: more => do
+ let t ← readToken w m s f.1.val bs
+ let (_, children) ← step x f t
+ let ts ← decodeVisits w x (children ++ stack) more
+ return t :: ts
+
+theorem decodeVisits_sound (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w)
+ (x : Fin m → Bool) (stack : List (Frame n (Fin s))) (bs : List (List Bool))
+ (ts : List (Token m (Fin s))) (hd : decodeVisits w x stack bs = some ts) :
+ bs = ts.map (encodeToken w) ∧ (scan x stack ts).isSome := by
+ induction bs generalizing stack ts with
+ | nil =>
+ cases stack <;> simp [decodeVisits] at hd
+ subst ts
+ exact ⟨rfl, rfl⟩
+ | cons b bs ih =>
+ cases stack with
+ | nil => simp [decodeVisits] at hd
+ | cons f stack =>
+ cases hr : readToken w m s f.1.val b with
+ | none => simp [decodeVisits, hr] at hd
+ | some t =>
+ cases hstep : step x f t with
+ | none => simp [decodeVisits, hr, hstep] at hd
+ | some v =>
+ obtain ⟨a, children⟩ := v
+ cases hrest : decodeVisits w x (children ++ stack) bs with
+ | none => simp [decodeVisits, hr, hstep, hrest] at hd
+ | some rest =>
+ simp [decodeVisits, hr, hstep, hrest] at hd
+ subst ts
+ obtain ⟨he, hscan⟩ := ih _ _ hrest
+ have he' := (readToken_sound hm hs (f.1.isLt.le.trans hn) hr).2
+ refine ⟨by simp [he', he], ?_⟩
+ cases hsc : scan x (children ++ stack) rest <;> simp_all [scan]
+
+theorem decodeVisits_encode (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w)
+ (x : Fin m → Bool) (stack : List (Frame n (Fin s))) (ts : List (Token m (Fin s)))
+ (hsc : (scan x stack ts).isSome) : decodeVisits w x stack (ts.map (encodeToken w)) = some ts := by
+ induction ts generalizing stack with
+ | nil => cases stack <;> simp_all [scan, decodeVisits]
+ | cons t ts ih =>
+ cases stack with
+ | nil => simp [scan] at hsc
+ | cons f stack =>
+ cases hh : step x f t with
+ | none => simp [scan, hh] at hsc
+ | some v =>
+ obtain ⟨a, children⟩ := v
+ have hs' : (scan x (children ++ stack) ts).isSome := by
+ cases h : scan x (children ++ stack) ts <;> simp_all [scan]
+ have hr := readToken_encode hm hs (f.1.isLt.le.trans hn) t (legal_of_step hh)
+ simp [decodeVisits, hr, hh, ih _ hs']
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterCall.lean b/lean/OAI/Computability/VPVNP/PrimedCounterCall.lean
new file mode 100644
index 0000000000..d82550b687
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterCall.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+
+/-!
+# Finite table for a scheduled coefficient-counter call
+
+All scheduled calls use the same structured body and reset their private
+registers at entry. On success the body leaves the next cursor and the total
+number of calls in two designated registers. A single comparison then either
+accepts at the last item or returns the next cursor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Call
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+
+variable {r k w : ℕ} (a : Flow r k)
+
+/-- Embed a label of the scheduled call body into the finite instruction table with its four
+terminal opcodes. -/
+def pc (i : a.Label) : Fin (a.length + 4) := Fin.castAdd 4 (a.labels i)
+/-- Continuation that compares the next cursor with the total call count after a successful
+body exit. -/
+def stop : Fin (a.length + 4) := ⟨a.length, by omega⟩
+/-- Instruction address for a failed guard or rejected call. -/
+def bad : Fin (a.length + 4) := ⟨a.length+1, by omega⟩
+/-- Instruction that returns the next cursor as persistent state for the next scheduled call. -/
+def back : Fin (a.length + 4) := ⟨a.length+2, by omega⟩
+/-- Halting instruction reached when the next cursor equals the total number of calls. -/
+def accept : Fin (a.length + 4) := ⟨a.length+3, by omega⟩
+
+/-- Compilation introduces four terminal opcodes. Neither the input length
+nor the number of calls determines the number of instruction labels. -/
+def template (next total : Fin r) : Template (a.length+4) r k where
+ literalWidth := 2
+ entry := pc a a.entry
+ code i := if hi : i.val < a.length then
+ ((a.code (a.labels.symm ⟨i.val,hi⟩)).map (fun t => (t.map (pc a)).getD (stop a))).emit (bad a)
+ else if i = stop a then .jumpEq next total (accept a) (back a)
+ else if i = back a then .returnState next
+ else if i = accept a then .accept
+ else .reject
+
+variable (next total : Fin r) (pub : Fin k → Word w)
+
+theorem linked : Flow.Linked ((template a next total).instantiate w pub) a (pc a) (stop a) (bad a) := by
+ constructor
+ intro i
+ simp [template, Template.instantiate, pc, (a.labels i).isLt]
+
+theorem reject_code : ((template a next total).instantiate w pub).code (bad a) = .reject := by
+ simp [Template.instantiate, template, bad, stop, back, accept, Fin.ext_iff, Instr.resize, show ¬ a.length+1 < a.length by omega]
+
+/-- Any surplus branch bits after the last opcode reject, even if the
+item itself would have succeeded on a shorter stream. -/
+theorem execute_stop (state : Word w) (regs : Regs w r) (priv : Word w → Word w)
+ (mem : Memory w) (bits : List Bool) (fuel : ℕ) :
+ let M := (template a next total).instantiate w pub
+ execute M.program (fuel+2) ⟨stop a,state,regs,priv⟩ mem bits =
+ if bits.isEmpty then some ⟨[.tick], if regs next = regs total then none else some (regs next)⟩ else none := by
+ let M := (template a next total).instantiate w pub
+ have hs : M.code (stop a) = .jumpEq next total (accept a) (back a) := by
+ simp [M, Template.instantiate, template, stop, Instr.resize]
+ have ha : M.code (accept a) = .accept := by
+ simp [M, Template.instantiate, template, accept, stop, back, Fin.ext_iff, Instr.resize, show ¬ a.length+3 < a.length by omega]
+ have hb : M.code (back a) = .returnState next := by
+ simp [M, Template.instantiate, template, back, stop, Fin.ext_iff, Instr.resize, show ¬ a.length+2 < a.length by omega]
+ change execute M.program (fuel+2) _ mem bits = _
+ cases bits <;> by_cases hh : regs next = regs total <;>
+ simp [execute, Machine.program, hs, ha, hb, Instr.run, hh, Report.prepend]
+
+/-- Exact native execution of a completed body, including the final cursor
+comparison and halt/return and the exact-use check on the branch tape. -/
+theorem execute_body (state : Word w) (regs : Regs w r) (priv : Word w → Word w)
+ (mem : Memory w) {es : List (Event w)} {out : Regs w r} {mem' : Memory w}
+ (hr : Flow.Exec pub state a regs mem es out mem') (extra : List Bool) (fuel : ℕ) :
+ let M := (template a next total).instantiate w pub
+ execute M.program (es.length + (fuel+2)) ⟨M.entry,state,regs,priv⟩ mem (choiceBits es ++ extra) =
+ if extra.isEmpty then some ⟨es ++ [.tick], if out next = out total then none else some (out next)⟩ else none := by
+ let M := (template a next total).instantiate w pub
+ have he := hr.execute (M := M) (linked a next total pub) (reject_code a next total pub) priv (fuel+2) extra
+ change execute M.program _ ⟨pc a a.entry, state, regs, priv⟩ mem _ = _
+ rw [he, execute_stop a next total pub]
+ cases extra <;> simp [Flow.prependEvents]
+
+end PrimedCounter.Call
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterCallPaths.lean b/lean/OAI/Computability/VPVNP/PrimedCounterCallPaths.lean
new file mode 100644
index 0000000000..ea808da2f5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterCallPaths.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.PrimedCounterCall
+import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete
+
+/-!
+# Reading back a native call of the scheduled pair counter
+
+The final tick compares the next cursor with the total count. Recovering
+the structured execution before that tick yields both the consumed binary
+tape and the post-call external memory used by the next scheduled item.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Call
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+
+variable {r k w : ℕ}
+
+private theorem line_memory (pub : Fin k → Word w) (state : Word w) (op : Op r k) (rs : Regs w r)
+ (m : Memory w) {e rs' m'} (he : op.effect pub state rs m = some (e,rs',m')) :
+ after m [e] = m' := by
+ cases op <;> simp only [Op.effect] at he
+ all_goals first | split at he | skip
+ all_goals first | contradiction | (cases Option.some.inj he; rfl)
+
+/-- Report replay has exactly the external-memory effect of the structured body. -/
+theorem exec_memory {pub : Fin k → Word w} {state : Word w} {a : Flow r k} {rs m es rs' m'}
+ (he : Flow.Exec pub state a rs m es rs' m') : after m es = m' := by
+ induction he with
+ | line h => exact line_memory _ _ _ _ _ h
+ | seq _ _ h₁ h₂ =>
+ rw [show ∀ a b : List (Event w), ∀ m, after m (a++b) = after (after m a) b by simp [after], h₁, h₂]
+ | ifEqYes _ _ ih | ifEqNo _ _ ih | ifLtYes _ _ ih | ifLtNo _ _ ih | branchYes _ ih | branchNo _ ih =>
+ exact ih
+ | whileDone => rfl
+ | whileStep _ _ _ h₁ h₂ =>
+ simpa only [after, List.foldl_cons, update, List.foldl_append] using
+ (congrArg (fun m => after m _ ) h₁).trans h₂
+
+private theorem stop_spec (a : Flow r k) (next total : Fin r) (pub : Fin k → Word w)
+ (state : Word w) (regs : Regs w r) (priv : Word w → Word w) (mem : Memory w)
+ (bits : List Bool) (fuel : ℕ) (out : Report w) :
+ let M := (template a next total).instantiate w pub
+ execute M.program fuel ⟨stop a,state,regs,priv⟩ mem bits = some out ↔
+ 2 ≤ fuel ∧ bits = [] ∧ out = ⟨[.tick], if regs next = regs total then none else some (regs next)⟩ := by
+ let M := (template a next total).instantiate w pub
+ change execute M.program fuel _ mem bits = some out ↔ _
+ cases fuel with
+ | zero => simp [execute]
+ | succ fuel =>
+ cases fuel with
+ | zero =>
+ have hc : M.code (stop a) = .jumpEq next total (accept a) (back a) := by
+ simp [M, Template.instantiate, template, stop, Instr.resize]
+ simp [execute, Machine.program, hc, Instr.run]
+ | succ fuel =>
+ rw [execute_stop a next total pub]
+ cases bits <;> simp [eq_comm]
+
+/-- Exact decomposition of a successful native call. The inequality counts
+the body events, the cursor comparison and the terminal return/accept opcode. -/
+theorem execute_iff (a : Flow r k) (next total : Fin r) (pub : Fin k → Word w)
+ (state : Word w) (regs : Regs w r) (priv : Word w → Word w) (mem : Memory w)
+ (bits : List Bool) (fuel : ℕ) (out : Report w) :
+ let M := (template a next total).instantiate w pub
+ execute M.program fuel ⟨M.entry,state,regs,priv⟩ mem bits = some out ↔
+ ∃ es rs' m', Flow.Exec pub state a regs mem es rs' m' ∧ es.length + 2 ≤ fuel ∧
+ choiceBits es = bits ∧ out.events = es ++ [.tick] ∧
+ out.result = (if rs' next = rs' total then none else some (rs' next)) ∧ after mem out.events = m' := by
+ let M := (template a next total).instantiate w pub
+ change execute M.program fuel ⟨pc a a.entry,state,regs,priv⟩ mem bits = some out ↔ _
+ constructor
+ · intro h
+ obtain ⟨es,rs',m',left,rest,tail,he,hf,hbs,ht,hout⟩ :=
+ (linked a next total pub).complete (reject_code a next total pub) state priv regs mem fuel bits out h
+ obtain ⟨hle,rfl,rfl⟩ := (stop_spec a next total pub state rs' priv m' rest left tail).1 ht
+ subst out
+ refine ⟨es, rs', m', he, by omega, by simpa using hbs.symm, rfl, rfl, ?_⟩
+ change after mem (es ++ [.tick]) = m'
+ simpa [after, update] using exec_memory he
+ · rintro ⟨es,rs',m',he,hlen,hb,hev,hr,_⟩
+ let extra := fuel - (es.length + 2)
+ have hx := execute_body a next total pub state regs priv mem he [] extra
+ have hf : es.length + (extra+2) = fuel := by dsimp [extra]; omega
+ rw [hf, List.append_nil, hb] at hx
+ have ho : out = ⟨es ++ [.tick], if rs' next = rs' total then none else some (rs' next)⟩ := by
+ cases out
+ simp_all
+ rw [ho]
+ exact hx
+
+end PrimedCounter.Call
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterChronology.lean b/lean/OAI/Computability/VPVNP/PrimedCounterChronology.lean
new file mode 100644
index 0000000000..41e15719f5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterChronology.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PrimedCounterChronologySlots
+import OAI.Computability.VPVNP.PrimedCounterSiteLoop
+import OAI.Computability.VPVNP.PrimedInputRAMLayoutExecution
+
+/-!
+# Exact coefficient count of chronological pair-counter tapes
+
+The cursor visits the two input rectangles, then the sites in row-major order,
+and finally all nominated histogram entries. A raw path has one list of branch
+bits at every absolute cursor position. Recovering the shared choices at the
+first-pass owners and the parse choices in the node slots is parsimonious.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Chronology
+
+open BurstRAM PrimedInputRAM
+open scoped Classical
+
+variable {L : Lengths} {n r H s w T : ℕ}
+
+/-- An assignment to all internal primed bits shared by the two groups, including bits read at
+several endpoints. -/
+abbrev Bits (L : Lengths) (r H w : ℕ) := Internal L r H w → Bool
+/-- One private choice list per cursor slot across the two input passes, all site parses and
+the final nomination comparisons. -/
+abbrev PairTape (n r T : ℕ) :=
+ Tape (PrimedInputRAM.positions n r + PrimedInputRAM.positions n r) (2 * 2^r) n (2*n-1) T
+
+/-- One singleton at each designated first-pass owner and an empty list at
+every other first-pass position and every copy position. -/
+def inputCalls (Q : Layout L n r H w) (bits : Bits L r H w) :
+ Fin (PrimedInputRAM.positions n r + PrimedInputRAM.positions n r) → List Bool := fun i =>
+ let pass := Q.twoPass (encodeBit w)
+ (pass.ops i).bits (bitAt (pass.assignmentEquiv (Q.assignment bits)) i)
+
+private theorem itemBits_injective {M : ℕ} (ops : Fin M → Item w) :
+ Function.Injective (fun f : Assignment (fun i => (ops i).owns) =>
+ fun i => (ops i).bits (bitAt f i)) := by
+ intro a b h
+ funext i
+ simpa [Item.bits, bitAt, i.property] using congrFun h i.val
+
+theorem inputCalls_injective (Q : Layout L n r H w) : Function.Injective (inputCalls Q) := by
+ intro a b h
+ let pass := Q.twoPass (encodeBit w)
+ have he := (itemBits_injective pass.ops) h
+ have ha := pass.assignmentEquiv.injective he
+ funext i
+ simpa [Layout.assignment] using congrFun ha (Q.internalOwner i)
+
+/-- Primed processor inputs, reindexed in the order of the parse loop. -/
+def rowInput (Q : Layout L n r H w) (hdr : Header L → Bool)
+ (bits : Bits L r H w) (v : Fin (2 * 2^r)) : Fin n → Bool :=
+ input Q.program Q.fits hdr bits (finProdFinEquiv.symm v)
+
+/-- Branch-tape condition tested by the input, site and comparison phases. -/
+def Accepts (Q : Layout L n r H w) (hdr : Header L → Bool)
+ (d : Fin n) (root : Fin s) (μ : Label n n (Fin s) →₀ ℕ) (raw : PairTape n r T) : Prop :=
+ ∃ bits : Bits L r H w, inputPart raw = inputCalls Q bits ∧ AdminEmpty raw ∧
+ runSites w d root (rowInput Q hdr bits) (fun v => List.ofFn (nodePart raw v))
+ (List.finRange (2 * 2^r)) 0 = some μ
+
+private noncomputable def pathFiberEquiv {I : Type*} {S : ℕ} (hn : n ≤ 2^w) (hs : s ≤ 2^w)
+ (d : Fin n) (root : Fin s) (x : I → Fin S → Fin n → Bool)
+ (μ : Label n n (Fin s) →₀ ℕ) :
+ (Σ a : I, {b : (v : Fin S) → SitePaths w (x a v) d root //
+ ∑ v, siteHistogram hn hs hn (x a v) d root (b v) = μ}) ≃
+ {b : PairPaths w d root x // totalHistogram hn hs hn d root x b = μ} where
+ toFun b := ⟨⟨b.1,b.2.val⟩,b.2.property⟩
+ invFun b := ⟨b.val.1,⟨b.val.2,b.property⟩⟩
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+private noncomputable def rowLoopEquiv {K S : ℕ} (hn : n ≤ 2^w) (hs : s ≤ 2^w)
+ (d : Fin n) (root : Fin s) (hK : K = 2*d.val + 1)
+ (x : Fin S → Fin n → Bool) (μ : Label n n (Fin s) →₀ ℕ) :
+ {raw : Fin S → Fin K → List Bool //
+ runSites w d root x (fun v => List.ofFn (raw v)) (List.finRange S) 0 = some μ} ≃
+ {b : (v : Fin S) → SitePaths w (x v) d root //
+ ∑ v, siteHistogram hn hs hn (x v) d root (b v) = μ} := by
+ subst K
+ exact siteLoopEquiv hn hn hs d root x μ
+
+/-- Extract the shared assignment and all local parses from a complete tape.
+The inverse places each choice back at its absolute chronological position. -/
+noncomputable def pathEquiv (Q : Layout L n r H w) (hdr : Header L → Bool)
+ (d : Fin n) (root : Fin s) (hsize : d.val + 1 = n) (hn : n ≤ 2^w) (hs : s ≤ 2^w)
+ (μ : Label n n (Fin s) →₀ ℕ) :
+ {raw : PairTape n r T // Accepts Q hdr d root μ raw} ≃
+ {b : PairPaths w d root (rowInput Q hdr) //
+ totalHistogram hn hs hn d root (rowInput Q hdr) b = μ} := by
+ let e := acceptedSlotsEquiv (m := n) (T := T) (inputCalls Q) (inputCalls_injective Q)
+ (fun bits (nodes : Fin (2 * 2^r) → Fin (2*n-1) → List Bool) =>
+ runSites w d root (rowInput Q hdr bits) (fun v => List.ofFn (nodes v))
+ (List.finRange (2 * 2^r)) 0 = some μ)
+ have hK : 2*n-1 = 2*d.val + 1 := by omega
+ exact (e.trans (Equiv.sigmaCongrRight fun a => rowLoopEquiv hn hs d root hK (rowInput Q hdr a) μ)).trans
+ (pathFiberEquiv hn hs d root (rowInput Q hdr) μ)
+
+/-- The raw path count is the integer coefficient on the actual primed
+inputs of both groups, including all internal bit assignments. -/
+theorem count (Q : Layout L n r H w) (hdr : Header L → Bool)
+ (d : Fin n) (root : Fin s) (hsize : d.val + 1 = n) (hn : n ≤ 2^w) (hs : s ≤ 2^w)
+ (μ : Label n n (Fin s) →₀ ℕ) :
+ (Nat.card {raw : PairTape n r T // Accepts Q hdr d root μ raw} : ℤ) =
+ (PairCoefficient.jointPolynomial d root (input Q.program Q.fits hdr)).coeff μ := by
+ rw [Nat.card_congr (pathEquiv Q hdr d root hsize hn hs μ),
+ pairPath_count hn hs hn d root hsize (rowInput Q hdr) μ]
+ apply congrArg (fun P : MvPolynomial (Label n n (Fin s)) ℤ => P.coeff μ)
+ apply Finset.sum_congr rfl
+ intro a _
+ exact finProdFinEquiv.symm.prod_comp (fun u : Site r => labelQuery d root (input Q.program Q.fits hdr a u))
+
+end PrimedCounter.Chronology
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterChronologySlots.lean b/lean/OAI/Computability/VPVNP/PrimedCounterChronologySlots.lean
new file mode 100644
index 0000000000..ddcf33b1a9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterChronologySlots.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.PrimedCounterCursor
+
+/-!
+# Chronological branch lists of the pair counter
+
+The input and node calls have independent tapes. Clearing the marks, initializing
+a root, and comparing histogram entries consume no branch bits. Reassembling
+the two varying arrays and these empty tapes fixes every absolute cursor slot.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Chronology
+
+variable {A S m K T : ℕ}
+
+/-- A choice-bit list at each absolute position of the input, site and comparison schedule. -/
+abbrev Tape (A S m K T : ℕ) := Fin (Cursor.calls A S m K T) → List Bool
+
+/-- Read the private bit list at an input-assembly slot of the complete tape. -/
+def inputPart (raw : Tape A S m K T) (i : Fin A) : List Bool :=
+ raw (Cursor.index A S m K T (.inl i))
+
+/-- Read the bit list for a given site's node visit after its mark-clearing and
+root-initialization calls. -/
+def nodePart (raw : Tape A S m K T) (u : Fin S) (j : Fin K) : List Bool :=
+ raw (Cursor.index A S m K T (.inr (.inl (u, .inr (.inr j)))))
+
+/-- The three administrative subroutines are deterministic at every call. -/
+def AdminEmpty (raw : Tape A S m K T) : Prop :=
+ (∀ (u : Fin S) (j : Fin m), raw (Cursor.index A S m K T (.inr (.inl (u, .inl j)))) = []) ∧
+ (∀ (u : Fin S) (j : Fin 1), raw (Cursor.index A S m K T (.inr (.inl (u, .inr (.inl j))))) = []) ∧
+ (∀ j : Fin T, raw (Cursor.index A S m K T (.inr (.inr j))) = [])
+
+private def slotValue (inp : Fin A → List Bool) (nodes : Fin S → Fin K → List Bool) :
+ Cursor.Item A S m K T → List Bool
+ | .inl i => inp i
+ | .inr (.inl (u, .inr (.inr j))) => nodes u j
+ | .inr _ => []
+
+private def pack (inp : Fin A → List Bool) (nodes : Fin S → Fin K → List Bool) :
+ Tape A S m K T := slotValue inp nodes ∘ (Cursor.index A S m K T).symm
+
+private theorem pack_admin (inp : Fin A → List Bool) (nodes : Fin S → Fin K → List Bool) :
+ AdminEmpty (pack (m := m) (T := T) inp nodes) := by
+ simp [AdminEmpty, pack, slotValue]
+
+private theorem input_pack (inp : Fin A → List Bool) (nodes : Fin S → Fin K → List Bool) :
+ inputPart (pack (m := m) (T := T) inp nodes) = inp := by
+ funext i
+ simp [inputPart, pack, slotValue]
+
+private theorem node_pack (inp : Fin A → List Bool) (nodes : Fin S → Fin K → List Bool) :
+ nodePart (pack (m := m) (T := T) inp nodes) = nodes := by
+ funext u j
+ simp [nodePart, pack, slotValue]
+
+private theorem pack_parts (raw : Tape A S m K T) (h : AdminEmpty raw) :
+ pack (inputPart raw) (nodePart raw) = raw := by
+ funext t
+ obtain ⟨i,rfl⟩ := (Cursor.index A S m K T).surjective t
+ rcases i with i | (⟨u, j | (j | j)⟩ | j)
+ · simp [pack, slotValue, inputPart]
+ · simpa [pack, slotValue] using (h.1 u j).symm
+ · simpa [pack, slotValue] using (h.2.1 u j).symm
+ · simp [pack, slotValue, nodePart]
+ · simpa [pack, slotValue] using (h.2.2 j).symm
+
+/-- Every admitted input assignment specifies its entire array of input calls.
+An injective input encoding lets us count the independent choices even when
+they yield the same row data. -/
+noncomputable def acceptedSlotsEquiv {α : Type*} (encode : α → Fin A → List Bool)
+ (hinj : Function.Injective encode) (p : α → (Fin S → Fin K → List Bool) → Prop) :
+ {raw : Tape A S m K T // ∃ a, inputPart raw = encode a ∧ AdminEmpty raw ∧ p a (nodePart raw)} ≃
+ (Σ a : α, {nodes : Fin S → Fin K → List Bool // p a nodes}) := by
+ let f (z : Σ a : α, {nodes : Fin S → Fin K → List Bool // p a nodes}) :
+ {raw : Tape A S m K T // ∃ a, inputPart raw = encode a ∧ AdminEmpty raw ∧ p a (nodePart raw)} :=
+ ⟨pack (encode z.1) z.2.val, z.1, input_pack .., pack_admin .., by rw [node_pack]; exact z.2.property⟩
+ refine (Equiv.ofBijective f ⟨?_, ?_⟩).symm
+ · rintro ⟨a,bs⟩ ⟨a',bs'⟩ he
+ have hp := congrArg Subtype.val he
+ change pack (m := m) (T := T) (encode a) bs.val = pack (encode a') bs'.val at hp
+ have h₁ := congrArg inputPart hp
+ rw [input_pack, input_pack] at h₁
+ obtain rfl := hinj h₁
+ have h₂ := congrArg nodePart hp
+ rw [node_pack, node_pack] at h₂
+ exact congrArg (Sigma.mk a) (Subtype.ext h₂)
+ · rintro ⟨raw,a,hi,ha,hn⟩
+ refine ⟨⟨a,nodePart raw,hn⟩, Subtype.ext ?_⟩
+ change pack (encode a) (nodePart raw) = raw
+ rw [← hi, pack_parts raw ha]
+
+end PrimedCounter.Chronology
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterCursor.lean b/lean/OAI/Computability/VPVNP/PrimedCounterCursor.lean
new file mode 100644
index 0000000000..abab044d62
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterCursor.lean
@@ -0,0 +1,98 @@
+import Mathlib.Logic.Equiv.Fin.Basic
+import Mathlib.Tactic.Ring
+
+/-!
+# Absolute cursors of the pair counter
+
+The machine makes one call for each cell in each input pass. It then visits
+each site in row-major order, clearing its marks, initializing its root and
+processing one node per call. The final calls compare all histogram entries.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Cursor
+
+/-- A site occupies one call per clear, one root call, and one call per node. -/
+def span (m nodes : ℕ) := m + (1 + nodes)
+
+/-- Start of the histogram comparisons. -/
+def compareStart (assembly S m nodes : ℕ) := assembly + S * span m nodes
+
+/-- Total number of calls. -/
+def calls (assembly S m nodes T : ℕ) := assembly + (S * span m nodes + T)
+
+/-- The three types of call within one site's parse block, indexed by mark position, root
+initialization or node number. -/
+abbrev LocalItem (m nodes : ℕ) := Fin m ⊕ (Fin 1 ⊕ Fin nodes)
+/-- All calls in the pair schedule, partitioned into input assembly, per-site parser operations
+and final label comparisons. -/
+abbrev Item (assembly S m nodes T : ℕ) :=
+ Fin assembly ⊕ ((Fin S × LocalItem m nodes) ⊕ Fin T)
+
+/-- Number the calls within a site by listing its mark clears first, then its root
+initialization and node visits. -/
+def localIndex (m nodes : ℕ) : LocalItem m nodes ≃ Fin (span m nodes) :=
+ ((Equiv.refl _).sumCongr finSumFinEquiv).trans finSumFinEquiv
+
+/-- All independent slots of the binary branch tape, in chronological order. -/
+def index (assembly S m nodes T : ℕ) : Item assembly S m nodes T ≃ Fin (calls assembly S m nodes T) :=
+ let rows := ((Equiv.refl _).prodCongr (localIndex m nodes)).trans finProdFinEquiv
+ let later := (rows.sumCongr (Equiv.refl _)).trans finSumFinEquiv
+ ((Equiv.refl _).sumCongr later).trans finSumFinEquiv
+
+variable {A S m nodes T : ℕ}
+
+theorem index_input (j : Fin A) : (index A S m nodes T (.inl j)).val = j.val := rfl
+
+theorem index_site (u : Fin S) (i : LocalItem m nodes) :
+ (index A S m nodes T (.inr (.inl (u,i)))).val = A + (u.val * span m nodes + (localIndex m nodes i).val) := by
+ change A + ((localIndex m nodes i).val + span m nodes * u.val) = _
+ rw [Nat.mul_comm, Nat.add_comm (localIndex m nodes i).val]
+
+theorem index_compare (j : Fin T) :
+ (index A S m nodes T (.inr (.inr j))).val = compareStart A S m nodes + j.val := by
+ change A + (S * span m nodes + j.val) = _
+ rw [compareStart, Nat.add_assoc]
+
+@[simp] theorem local_clear (j : Fin m) : (localIndex m nodes (.inl j)).val = j.val := rfl
+@[simp] theorem local_init (u : Fin 1) : (localIndex m nodes (.inr (.inl u))).val = m := by
+ have hu : u.val = 0 := by have := u.isLt; omega
+ change m + u.val = m
+ omega
+@[simp] theorem local_node (j : Fin nodes) : (localIndex m nodes (.inr (.inr j))).val = m+1+j.val := by
+ change m + (1+j.val) = _
+ omega
+
+/-- Word division and remainder in the site phase recover both the physical
+row and its local phase. -/
+theorem unpack_site (u : Fin S) (i : LocalItem m nodes) :
+ let v := (index A S m nodes T (.inr (.inl (u,i)))).val
+ A ≤ v ∧ v < compareStart A S m nodes ∧
+ (v-A) / span m nodes = u.val ∧ (v-A) % span m nodes = (localIndex m nodes i).val := by
+ rw [index_site]
+ dsimp only
+ have h := (localIndex m nodes i).isLt
+ have hp : 0 < span m nodes := by unfold span; omega
+ have hlt : u.val * span m nodes + (localIndex m nodes i).val < S * span m nodes := by
+ calc
+ _ < u.val * span m nodes + span m nodes := Nat.add_lt_add_left h _
+ _ = (u.val+1)*span m nodes := (Nat.succ_mul ..).symm
+ _ ≤ _ := Nat.mul_le_mul_right _ u.isLt
+ simp [compareStart, hlt, Nat.mod_eq_of_lt h]
+ rw [Nat.mul_comm u.val, Nat.mul_add_div hp, Nat.div_eq_of_lt h, Nat.add_zero]
+
+/-- For the paper's `2R` sites, each has exactly `2n−1` nodes. -/
+theorem calls_pair (R n T : ℕ) (hn : 0 < n) :
+ calls (2*(2*R*n)) (2*R) n (2*n-1) T = 10*R*n+T := by
+ have h : span n (2*n-1) = 3*n := by unfold span; omega
+ rw [calls, h]
+ ring
+
+end PrimedCounter.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterData.lean b/lean/OAI/Computability/VPVNP/PrimedCounterData.lean
new file mode 100644
index 0000000000..1c9ee80bad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterData.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.PrimedCounterProgram
+import OAI.Computability.VPVNP.PrimedCounterAdminInitial
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeExecutionLayout
+
+/-!
+# Parameters and initial memory for the uniform coefficient counter
+
+The public table contains dimensions, the literal prefix, the root state and
+the fixed offsets used by the native program. The exterior bits and nominated
+histogram are loaded from the actual initial external memory. The same code
+is used for every pair and for every nomination.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open BurstRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {L : Lengths} {n r H s w : ℕ}
+
+/-- Parameters for counting one primed pair coefficient at the given RAM layout and grammar
+state count. -/
+structure Data (Q : Layout L n r H w) (s : ℕ) where
+ /-- Degree index installed in the pending root frame of every site's parse. -/
+ degree : Fin n
+ /-- Grammar state required at the root of every site's parse. -/
+ root : Fin s
+ /-- The fixed Boolean header data for the two groups, including the exterior fields. -/
+ header : Header L → Bool
+ /-- Requested multiplicity of each terminal and binary production in the pair's aggregate
+ parse histogram. -/
+ nomination : Label n n (Fin s) →₀ ℕ
+
+namespace Data
+
+variable {Q : Layout L n r H w}
+
+/-- Address of the assembled input rectangle and beginning of the parser's working layout,
+immediately after first-pass scratch. -/
+abbrev base (_D : Data Q s) := Q.scratchBase + PrimedInputRAM.positions n r
+/-- Number of scheduled calls in the two input-assembly passes, one per rectangular position
+per pass. -/
+abbrev assembly (_D : Data Q s) := PrimedInputRAM.positions n r + PrimedInputRAM.positions n r
+/-- Number of dense production counters that the final comparison scans. -/
+abbrev labels (_D : Data Q s) := labelCount n n s
+/-- Total number of scheduled calls for both input passes, all site parses and all histogram
+comparisons. -/
+abbrev total (D : Data Q s) := Cursor.calls D.assembly (2 * 2^r) n (2*n-1) D.labels
+/-- Private instruction allowance per call, covering input address computation and the parser's
+word operations. -/
+abbrev fuel (_D : Data Q s) := max (Opcodes.nativeFuel r+20) (12*w+110)
+
+/-- All slots of the actual machine word and both work arrays used by one invocation. -/
+structure Fits (D : Data Q s) : Prop where
+ assembler : Opcodes.ParameterFit Q
+ degree_eq : D.degree.val + 1 = n
+ headers : Header.count L + D.labels ≤ Q.scratchBase
+ scratch : D.base + size (2^r) n n D.labels ≤ 2^w
+ states : s < 2^w
+ word : 2 < 2^w
+ triangle : n^2 ≤ 2^w
+ cursor : D.total < 2^w
+ nomination (a : Label n n (Fin s)) : D.nomination a < 2^w
+
+/-- Fourteen parser operands including scratch layout, root degree, root state and nomination
+base address. -/
+def parserPub (D : Data Q s) : Fin 14 → Word w :=
+ Fin.append (publicData w D.base (2^r) n n s)
+ ![(D.degree.val : Word w), (D.root.val : Word w), (Header.count L : Word w)]
+
+/-- The full public operand vector combining input assembly, parsing and the absolute schedule
+boundaries. -/
+def pub (D : Data Q s) : Fin 34 → Word w :=
+ Program.publicWords (Opcodes.pubWord Q) D.parserPub D.assembly (2*2^r) n (2*n-1) D.labels
+
+/-- The uniform coefficient-counting instruction table instantiated at the selected word width
+and public operands. -/
+abbrev machine (D : Data Q s) := Program.table.instantiate w D.pub
+
+/-- The requested count at a dense label index, encoded as one machine word. -/
+noncomputable def nominatedWord (D : Data Q s) (i : Fin D.labels) : Word w :=
+ Fin.ofNat _ (D.nomination ((labelIndex n n s).symm i))
+
+/-- The nominated counts as a list of machine words in the parser's dense production order. -/
+noncomputable def hist (D : Data Q s) : List (Word w) := List.ofFn D.nominatedWord
+
+/-- Initial external memory with the pair header followed by its nominated histogram. -/
+noncomputable def initial (D : Data Q s) : Memory w := headerMemory L D.header D.hist
+
+/-- The primed processor input bits for a site in either group, assembled from its fixed header
+and the shared internal assignment. -/
+def input (D : Data Q s) (bits : Internal L r H w → Bool) (g : Fin 2) (v : Fin (2^r)) :=
+ PrimedInputRAM.input Q.program Q.fits D.header bits (g,v)
+
+/-- All words in the reserved nomination region have the values prescribed by this pair's
+histogram. -/
+def Nominated (D : Data Q s) (mem : Memory w) := ∀ j, mem (Header.count L+j.val) = D.nominatedWord j
+
+/-- Parser memory relation including the reserved nomination words. -/
+def Holds (D : Data Q s) (bits : Internal L r H w → Bool) (st : VisitState n n s) (mem : Memory w) : Prop :=
+ PrimedStackRAM.Holds D.base (D.input bits) st mem ∧ D.Nominated mem
+
+theorem parserPub_stack (D : Data Q s) : D.parserPub ∘ Admin.stackPublic = publicData w D.base (2^r) n n s := by
+ funext i
+ exact Fin.append_left ..
+
+theorem parserPub_root (D : Data Q s) :
+ D.parserPub 11 = (D.degree.val : Word w) ∧ D.parserPub 12 = (D.root.val : Word w) ∧
+ D.parserPub 13 = (Header.count L : Word w) := by
+ have he (j : Fin 3) : D.parserPub (j.natAdd 11) =
+ (![(D.degree.val : Word w), ↑D.root.val, ↑(Header.count L)] : Fin 3 → Word w) j := Fin.append_right ..
+ exact ⟨he 0, he 1, he 2⟩
+
+/-- The native input passes start the traversal with zero counters, no marks
+and no pending frames, while preserving every nomination word. -/
+theorem assembled_holds (D : Data Q s) (hf : D.Fits) (bits : Internal L r H w → Bool) :
+ D.Holds bits ⟨[], ∅, 0⟩ (Q.assembled (encodeBit w) bits D.initial) := by
+ have hlen : D.hist.length = D.labels := List.length_ofFn
+ have hfit : Header.count L + D.hist.length ≤ Q.scratchBase := hlen ▸ hf.headers
+ refine ⟨Admin.assembled_holds Q D.header bits D.hist hfit, ?_⟩
+ intro j
+ have he := Admin.assembled_nomination Q D.header bits D.hist hfit (j.cast hlen.symm)
+ refine he.trans ?_
+ change (List.ofFn D.nominatedWord)[j.val] = D.nominatedWord j
+ simp only [List.getElem_ofFn]
+
+theorem nominated_value (D : Data Q s) (hf : D.Fits) (j : Fin D.labels) :
+ (D.nominatedWord j).val = D.nomination ((labelIndex n n s).symm j) :=
+ Nat.mod_eq_of_lt (hf.nomination _)
+
+end Data
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterDispatch.lean b/lean/OAI/Computability/VPVNP/PrimedCounterDispatch.lean
new file mode 100644
index 0000000000..10f61ced6f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterDispatch.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.PrimedCounterDispatchRun
+import OAI.Computability.VPVNP.PrimedCounterDispatchSite
+
+/-!
+# The common dispatch on every item of a primed pair
+
+An absolute cursor selects one assembly, clear, initialization, node, or
+comparison routine. The prefix installs the required local operands and the
+call successor and total. Every selected routine preserves the latter two
+registers until the machine's exit instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Dispatch
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM Program
+open scoped Fin.CommRing
+
+variable {w A S m nodes T : ℕ} {pub : Pub → Word w} {state : Word w}
+ {rs : Regs w 52}
+
+/-- Routine selected by an absolute schedule item. -/
+def branch : Cursor.Item A S m nodes T → Program.Code
+ | .inl _ => Program.input
+ | .inr (.inl (_,i)) => siteBranch i
+ | .inr (.inr _) => Program.compare
+
+/-- Register file at the entry of the selected routine. -/
+def prepared (rs : Regs w 52) (i : Cursor.Item A S m nodes T) : Regs w 52 :=
+ let v := (Cursor.index A S m nodes T i).val
+ let U := Cursor.calls A S m nodes T
+ let start := Cursor.compareStart A S m nodes
+ match i with
+ | .inl _ => controlRegs rs v A U
+ | .inr (.inl (u,j)) => siteRegs (laterRegs rs v A U start) u j
+ | .inr (.inr j) => compareRegs rs v A U start j.val
+
+/-- Exact number of ticks before entry to the selected routine. -/
+def overhead : Cursor.Item A S m nodes T → ℕ
+ | .inl _ => 6
+ | .inr (.inl (_,j)) => 8 + siteTicks j
+ | .inr (.inr _) => 9
+
+theorem overhead_le (i : Cursor.Item A S m nodes T) : overhead i ≤ 16 := by
+ rcases i with j | ⟨u,j | j | j⟩ | j <;> norm_num [overhead, siteTicks]
+
+/-- The prefix passes the decoded operands to the selected branch, with no
+choice bits or external probes consumed before that branch starts. -/
+theorem body_pref (hw : ScheduleWords pub A S m nodes T) (hfit : Cursor.calls A S m nodes T < 2^w)
+ (i : Cursor.Item A S m nodes T) :
+ Pref pub (itemState w i) body rs (branch i) (prepared rs i) (overhead i) := by
+ rcases i with j | ⟨u,j⟩ | j
+ · exact input_pref hw hfit j
+ · apply (row_pref (rs := rs) hw hfit u j).trans
+ apply site_pref u j hfit _ _ hw.span hw.marks <;>
+ simp (config := { decide := true }) [laterRegs, controlRegs, Function.update]
+ · exact compare_pref hw hfit j
+
+/-- The final comparison uses the next absolute cursor and the full call count. -/
+theorem prepared_controls (rs : Regs w 52) (i : Cursor.Item A S m nodes T) :
+ prepared rs i 49 = (((Cursor.index A S m nodes T i).val + 1 : ℕ) : Word w) ∧
+ prepared rs i 50 = (Cursor.calls A S m nodes T : Word w) := by
+ rcases i with j | ⟨u,j⟩ | j <;>
+ simp (config := { decide := true }) [prepared, compareRegs, laterRegs, controlRegs, Function.update]
+
+@[simp] theorem prepared_clear_index (rs : Regs w 52) (u : Fin S) (j : Fin m) :
+ prepared rs (.inr (.inl (u,.inl j)) : Cursor.Item A S m nodes T) (parserReg 2) = (j.val : Word w) :=
+ siteRegs_clear_index ..
+
+@[simp] theorem prepared_node_offset (rs : Regs w 52) (u : Fin S) (j : Fin nodes) :
+ prepared rs (.inr (.inl (u,.inr (.inr j))) : Cursor.Item A S m nodes T) (parserReg 5) =
+ ((u.val * m : ℕ) : Word w) :=
+ siteRegs_node_offset ..
+
+@[simp] theorem prepared_compare_index (rs : Regs w 52) (j : Fin T) :
+ prepared rs (.inr (.inr j) : Cursor.Item A S m nodes T) (parserReg 7) = (j.val : Word w) := by
+ simp [prepared, compareRegs, parserReg]
+
+/-- Input dispatch leaves every assembly register at its incoming value. -/
+theorem prepared_input (rs : Regs w 52) (j : Fin A) :
+ prepared rs (.inl j : Cursor.Item A S m nodes T) ∘ inputRegs = rs ∘ inputRegs :=
+ control_input ..
+
+/-- Executing any selected routine leaves the two exit registers alone. -/
+theorem branch_controls (i : Cursor.Item A S m nodes T) {mem mem' : Memory w}
+ {es : List (Event w)} {out : Regs w 52}
+ (he : Flow.Exec pub state (branch i) rs mem es out mem') : out 49 = rs 49 ∧ out 50 = rs 50 := by
+ have frame {r p : ℕ} (reg : Fin r ↪ Reg) (port : Fin p → Pub) (a : Flow r p)
+ (hs : Flow.Exec pub state (renameFlow reg port a) rs mem es out mem')
+ (h : (49 : Reg) ∉ Set.range reg ∧ (50 : Reg) ∉ Set.range reg) : out 49 = rs 49 ∧ out 50 = rs 50 := by
+ have hf := (restrictExec reg port pub a hs).2
+ exact ⟨hf 49 h.1, hf 50 h.2⟩
+ rcases i with j | ⟨u,j⟩ | j
+ · exact frame inputRegs inputPub (Opcodes.dataCall PortCode.program) he input_outside
+ · rcases j with j | j | j
+ · exact frame parserRegs parserPub Admin.clear he parser_outside
+ · exact frame parserRegs parserPub Admin.init he parser_outside
+ · exact frame parserRegs stackPub nodeFlow he parser_outside
+ · exact frame parserRegs parserPub Admin.compare he parser_outside
+
+end PrimedCounter.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterDispatchBounds.lean b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchBounds.lean
new file mode 100644
index 0000000000..61cad86a87
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchBounds.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.PrimedCounterDispatchPrefix
+
+/-!
+# Cursor bounds and the outer dispatch tests
+
+At a legal item, the first five opcodes install the absolute cursor, its
+successor and the public call count. Two unsigned comparisons distinguish the
+input, site and histogram regions without wraparound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Dispatch
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM Program
+open scoped Fin.CommRing
+
+variable {w A S m nodes T : ℕ}
+
+/-- The schedule words used by the actual jump and division opcodes. -/
+structure ScheduleWords (pub : Pub → Word w) (A S m nodes T : ℕ) : Prop where
+ assembly : pub 30 = (A : Word w)
+ span : pub 31 = (Cursor.span m nodes : Word w)
+ compareStart : pub 32 = (Cursor.compareStart A S m nodes : Word w)
+ calls : pub 33 = (Cursor.calls A S m nodes T : Word w)
+ marks : pub (stackPub 6) = (m : Word w)
+
+theorem scheduleWords (inputs : Fin 16 → Word w) (parser : Fin 14 → Word w)
+ (hm : parser (Admin.stackPublic 6) = (m : Word w)) :
+ ScheduleWords (publicWords inputs parser A S m nodes T) A S m nodes T := by
+ obtain ⟨ha, hs, hc, ht⟩ := public_schedule inputs parser A S m nodes T
+ exact ⟨ha, hs, hc, ht, (public_parser inputs parser A S m nodes T _).trans hm⟩
+
+/-- A scheduled input cell, local parser operation or histogram comparison represented before
+conversion to its absolute cursor. -/
+abbrev Item := Cursor.Item A S m nodes T
+
+/-- Persistent word supplied to the common program for this item. -/
+def itemState (w : ℕ) (i : Item (A := A) (S := S) (m := m) (nodes := nodes) (T := T)) : Word w :=
+ ((Cursor.index A S m nodes T i).val : Word w)
+
+/-- Registers after executing the first five literal instructions. -/
+def controlRegs (rs : Regs w 52) (v A U : ℕ) : Regs w 52 :=
+ Function.update (Function.update (Function.update (Function.update (Function.update
+ rs 48 (v : Word w)) 51 1) 49 ((v+1 : ℕ) : Word w)) 50 (U : Word w)) 51 (A : Word w)
+
+/-- Site and histogram regions also retain the absolute histogram start in register 17. -/
+def laterRegs (rs : Regs w 52) (v A U start : ℕ) : Regs w 52 :=
+ Function.update (controlRegs rs v A U) 17 (start : Word w)
+
+/-- Histogram comparison selects label `j` in operand register 7. -/
+def compareRegs (rs : Regs w 52) (v A U start j : ℕ) : Regs w 52 :=
+ Function.update (laterRegs rs v A U start) 7 (j : Word w)
+
+variable {pub : Pub → Word w} {rs : Regs w 52}
+
+private theorem setup_pref (hw : ScheduleWords pub A S m nodes T) (v : ℕ) :
+ Pref pub (v : Word w) body rs (.ifLt 48 51 input afterInputs)
+ (controlRegs rs v A (Cursor.calls A S m nodes T)) 5 := by
+ apply Pref.lines
+ intro mem
+ simp (config := { decide := true }) [dispatchSetup, trace, Op.effect, BinaryOp.eval, controlRegs,
+ Function.update, hw.calls, hw.assembly, Nat.cast_add, List.replicate_succ]
+
+private theorem lt_word {a b : ℕ} (ha : a < 2^w) (hb : b < 2^w) :
+ ((a : Word w) < (b : Word w)) ↔ a < b := by
+ change (a : Word w).val < (b : Word w).val ↔ _
+ rw [Fin.val_natCast, Fin.val_natCast, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb]
+
+private theorem assembly_le_start : A ≤ Cursor.compareStart A S m nodes := by
+ simp [Cursor.compareStart]
+
+private theorem start_le_calls : Cursor.compareStart A S m nodes ≤ Cursor.calls A S m nodes T := by
+ simp [Cursor.compareStart, Cursor.calls, ← Nat.add_assoc]
+
+/-- The input branch starts on its original cursor, with the native successor
+and total installed outside the 48-register assembly operand space. -/
+theorem input_pref (hw : ScheduleWords pub A S m nodes T)
+ (hfit : Cursor.calls A S m nodes T < 2^w) (j : Fin A) :
+ Pref pub (itemState w (.inl j : Cursor.Item A S m nodes T)) body rs input
+ (controlRegs rs j.val A (Cursor.calls A S m nodes T)) 6 := by
+ have ha := (assembly_le_start (A := A) (S := S) (m := m) (nodes := nodes)).trans_lt (start_le_calls.trans_lt hfit)
+ apply (setup_pref (rs := rs) hw j.val).trans (k := 1)
+ apply Pref.ifLtYes
+ simpa (config := { decide := true }) [controlRegs, Function.update] using (lt_word (j.isLt.trans ha) ha).mpr j.isLt
+
+private theorem later_pref (hw : ScheduleWords pub A S m nodes T)
+ (hfit : Cursor.calls A S m nodes T < 2^w) (v : ℕ) (hA : A ≤ v) (hv : v < 2^w) :
+ Pref pub (v : Word w) body rs (.ifLt 48 17 site (.seq (.line (.binary .sub 7 48 17)) compare))
+ (laterRegs rs v A (Cursor.calls A S m nodes T) (Cursor.compareStart A S m nodes)) 7 := by
+ have ha := (assembly_le_start (A := A) (S := S) (m := m) (nodes := nodes)).trans_lt (start_le_calls.trans_lt hfit)
+ have hge : ¬controlRegs rs v A (Cursor.calls A S m nodes T) 48 <
+ controlRegs rs v A (Cursor.calls A S m nodes T) 51 := by
+ simpa (config := { decide := true }) [controlRegs, Function.update, lt_word hv ha] using Nat.not_lt.mpr hA
+ apply ((setup_pref (rs := rs) hw v).trans (Pref.ifLtNo hge)).trans (k := 1)
+ apply Pref.line
+ intro mem
+ simp only [Op.effect, hw.compareStart, laterRegs]
+
+/-- Every site cursor passes both outer phase tests, preserving the exact
+absolute cursor and assembly boundary for the row division. -/
+theorem row_pref (hw : ScheduleWords pub A S m nodes T)
+ (hfit : Cursor.calls A S m nodes T < 2^w) (u : Fin S) (i : Cursor.LocalItem m nodes) :
+ let idx := Cursor.index A S m nodes T (.inr (.inl (u,i)))
+ Pref pub (itemState w (.inr (.inl (u,i)) : Cursor.Item A S m nodes T)) body rs site
+ (laterRegs rs idx.val A (Cursor.calls A S m nodes T) (Cursor.compareStart A S m nodes)) 8 := by
+ dsimp only
+ let idx := Cursor.index A S m nodes T (.inr (.inl (u,i)))
+ obtain ⟨hA, hs, _⟩ := Cursor.unpack_site (A := A) (T := T) u i
+ apply (later_pref (rs := rs) hw hfit idx.val hA (idx.isLt.trans hfit)).trans (k := 1)
+ apply Pref.ifLtYes
+ simpa (config := { decide := true }) [laterRegs, controlRegs, Function.update] using
+ (lt_word (idx.isLt.trans hfit) (start_le_calls.trans_lt hfit)).mpr hs
+
+/-- The last region skips the site, subtracts the histogram start and passes
+the resulting dense label index to the comparison code. -/
+theorem compare_pref (hw : ScheduleWords pub A S m nodes T)
+ (hfit : Cursor.calls A S m nodes T < 2^w) (j : Fin T) :
+ let idx := Cursor.index A S m nodes T (.inr (.inr j))
+ Pref pub (itemState w (.inr (.inr j) : Cursor.Item A S m nodes T)) body rs compare
+ (compareRegs rs idx.val A (Cursor.calls A S m nodes T) (Cursor.compareStart A S m nodes) j.val) 9 := by
+ dsimp only
+ let idx := Cursor.index A S m nodes T (.inr (.inr j))
+ let start := Cursor.compareStart A S m nodes
+ have hj : idx.val = start+j.val := Cursor.index_compare j
+ have hs : start ≤ idx.val := by omega
+ let mid := laterRegs rs idx.val A (Cursor.calls A S m nodes T) start
+ have h48 : mid 48 = (idx.val : Word w) := by
+ simp (config := { decide := true }) [mid, laterRegs, controlRegs, Function.update]
+ have h17 : mid 17 = (start : Word w) := by simp [mid, laterRegs]
+ have hge : ¬mid 48 < mid 17 := by rw [h48, h17, lt_word (idx.isLt.trans hfit) (start_le_calls.trans_lt hfit)]; omega
+ apply ((later_pref (rs := rs) hw hfit idx.val (assembly_le_start.trans hs) (idx.isLt.trans hfit)).trans
+ (Pref.ifLtNo hge)).trans (k := 1)
+ apply Pref.line
+ intro mem
+ change some (Event.tick (w := w), Function.update mid 7 (mid 48 - mid 17), mem) = _
+ have hd : mid 48 - mid 17 = (j.val : Word w) := by rw [h48, h17, hj, Nat.cast_add, add_sub_cancel_left]
+ rw [hd]
+ rfl
+
+end PrimedCounter.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterDispatchNative.lean b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchNative.lean
new file mode 100644
index 0000000000..f3a8438757
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchNative.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PrimedCounterDispatch
+
+/-!
+# Native clear, root, visit and comparison calls
+
+Each cursor reduces to the original small routine on its projected public
+words and prepared local register file. The native call accepts at the last
+item and returns the successor on all earlier successful items.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Dispatch
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM Program
+open scoped Fin.CommRing
+
+variable {w A S m nodes T : ℕ}
+
+/-- Successful native execution on an individual schedule item. -/
+abbrev NativeAt (pub : Pub → Word w) (regs : Regs w 52) (priv : Word w → Word w)
+ (mem : Memory w) (bits : List Bool) (fuel : ℕ) (out : Report w) (i : Cursor.Item A S m nodes T) : Prop :=
+ let M := table.instantiate w pub
+ execute M.program fuel ⟨M.entry,itemState w i,regs,priv⟩ mem bits = some out
+
+/-- Exact local execution and its effect on the report returned by the whole call. -/
+abbrev LocalResult {r p : ℕ} (pub : Fin p → Word w) (small : Flow r p) (rs : Regs w r)
+ (mem : Memory w) (bits : List Bool) (fuel : ℕ) (out : Report w) (i : Cursor.Item A S m nodes T) : Prop :=
+ ∃ es smallOut m', Flow.Exec pub (itemState w i) small rs mem es smallOut m' ∧
+ overhead i + es.length + 2 ≤ fuel ∧ choiceBits es = bits ∧
+ out.events = (List.replicate (overhead i) .tick ++ es) ++ [.tick] ∧
+ out.result = PrimedSchedule.control w (Cursor.calls A S m nodes T) ((Cursor.index A S m nodes T i).val+1) ∧
+ after mem out.events = m'
+
+/-- A scheduled native call is exactly the selected embedded routine with its
+literal dispatch and exit opcodes. -/
+theorem placed_execute_iff {pub : Pub → Word w} (hw : ScheduleWords pub A S m nodes T)
+ (hfit : Cursor.calls A S m nodes T < 2^w) (i : Cursor.Item A S m nodes T)
+ {r p : ℕ} (reg : Fin r ↪ Reg) (port : Fin p → Pub) (small : Flow r p)
+ (hc : branch i = renameFlow reg port small)
+ (houtside : (49 : Reg) ∉ Set.range reg ∧ (50 : Reg) ∉ Set.range reg)
+ (regs : Regs w 52) (priv : Word w → Word w) (mem : Memory w) (bits : List Bool) (fuel : ℕ) (out : Report w) :
+ NativeAt pub regs priv mem bits fuel out i ↔
+ LocalResult (pub ∘ port) small (prepared regs i ∘ reg) mem bits fuel out i := by
+ have hp := body_pref (rs := regs) hw hfit i
+ rw [hc] at hp
+ obtain ⟨h49,h50⟩ := prepared_controls regs i
+ exact execute_pref_iff reg port small hp h49 h50 houtside.1 houtside.2
+ (Cursor.index A S m nodes T i).isLt hfit priv mem bits fuel out
+
+variable (inputs : Fin 16 → Word w) (parser : Fin 14 → Word w)
+ (hm : parser (Admin.stackPublic 6) = (m : Word w)) (hfit : Cursor.calls A S m nodes T < 2^w)
+ (regs : Regs w 52) (priv : Word w → Word w) (mem : Memory w) (bits : List Bool) (fuel : ℕ) (out : Report w)
+
+include hm hfit in
+private theorem admin_iff (i : Cursor.Item A S m nodes T) (small : Flow 16 14)
+ (hc : branch i = renameFlow parserRegs parserPub small) :
+ NativeAt (publicWords inputs parser A S m nodes T) regs priv mem bits fuel out i ↔
+ LocalResult parser small (prepared regs i ∘ parserRegs) mem bits fuel out i := by
+ have hh : publicWords inputs parser A S m nodes T ∘ parserPub = parser :=
+ funext (public_parser inputs parser A S m nodes T)
+ simpa only [hh] using placed_execute_iff (scheduleWords inputs parser hm) hfit i parserRegs parserPub
+ small hc parser_outside regs priv mem bits fuel out
+
+include hm hfit in
+theorem clear_execute_iff (u : Fin S) (j : Fin m) :
+ let i : Cursor.Item A S m nodes T := .inr (.inl (u,.inl j))
+ NativeAt (publicWords inputs parser A S m nodes T) regs priv mem bits fuel out i ↔
+ LocalResult parser Admin.clear (prepared regs i ∘ parserRegs) mem bits fuel out i :=
+ admin_iff inputs parser hm hfit regs priv mem bits fuel out _ _ rfl
+
+include hm hfit in
+theorem init_execute_iff (u : Fin S) (j : Fin 1) :
+ let i : Cursor.Item A S m nodes T := .inr (.inl (u,.inr (.inl j)))
+ NativeAt (publicWords inputs parser A S m nodes T) regs priv mem bits fuel out i ↔
+ LocalResult parser Admin.init (prepared regs i ∘ parserRegs) mem bits fuel out i :=
+ admin_iff inputs parser hm hfit regs priv mem bits fuel out _ _ rfl
+
+include hm hfit in
+theorem node_execute_iff (u : Fin S) (j : Fin nodes) :
+ let i : Cursor.Item A S m nodes T := .inr (.inl (u,.inr (.inr j)))
+ NativeAt (publicWords inputs parser A S m nodes T) regs priv mem bits fuel out i ↔
+ LocalResult (parser ∘ Admin.stackPublic) nodeFlow (prepared regs i ∘ parserRegs) mem bits fuel out i := by
+ have hh : publicWords inputs parser A S m nodes T ∘ stackPub = parser ∘ Admin.stackPublic :=
+ funext fun k => public_parser inputs parser A S m nodes T (Admin.stackPublic k)
+ simpa only [hh] using placed_execute_iff (scheduleWords inputs parser hm) hfit
+ (.inr (.inl (u,.inr (.inr j)))) parserRegs stackPub nodeFlow rfl parser_outside regs priv mem bits fuel out
+
+include hm hfit in
+theorem compare_execute_iff (j : Fin T) :
+ let i : Cursor.Item A S m nodes T := .inr (.inr j)
+ NativeAt (publicWords inputs parser A S m nodes T) regs priv mem bits fuel out i ↔
+ LocalResult parser Admin.compare (prepared regs i ∘ parserRegs) mem bits fuel out i :=
+ admin_iff inputs parser hm hfit regs priv mem bits fuel out _ _ rfl
+
+end PrimedCounter.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterDispatchPrefix.lean b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchPrefix.lean
new file mode 100644
index 0000000000..21babd898d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchPrefix.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PrimedCounterProgram
+
+/-!
+# Deterministic prefixes of scheduled calls
+
+Each dispatch step contributes only ticks, preserves external memory, and
+passes a determined register file to the selected continuation. The relation
+below records both directions for every successful execution and its full log.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Dispatch
+
+open BurstRAM PrimedStackRAM PrimedInputRAM
+
+variable {w r p : ℕ} {pub : Fin p → Word w} {state : Word w}
+
+/-- Removing a deterministic prefix of `k` ticks gives exactly the executions
+of the residual program on its prepared registers. -/
+def Pref (pub : Fin p → Word w) (state : Word w) (a : Flow r p) (rs : Regs w r)
+ (b : Flow r p) (mid : Regs w r) (k : ℕ) : Prop :=
+ ∀ m log out m', Flow.Exec pub state a rs m log out m' ↔
+ ∃ es, log = List.replicate k .tick ++ es ∧ Flow.Exec pub state b mid m es out m'
+
+namespace Pref
+
+variable {a b c : Flow r p} {rs mid last : Regs w r} {j k : ℕ}
+
+theorem refl : Pref pub state a rs a rs 0 := by
+ intro m log out m'
+ simp
+
+theorem trans (h : Pref pub state a rs b mid j) (g : Pref pub state b mid c last k) :
+ Pref pub state a rs c last (j+k) := by
+ intro m log out m'
+ rw [h, List.replicate_add]
+ constructor
+ · rintro ⟨es, rfl, he⟩
+ obtain ⟨fs, rfl, hf⟩ := (g m es out m').mp he
+ exact ⟨fs, (List.append_assoc ..).symm, hf⟩
+ · rintro ⟨es, rfl, he⟩
+ exact ⟨_, List.append_assoc .., (g m _ out m').mpr ⟨es, rfl, he⟩⟩
+
+theorem lines {ops : List (Op r p)} (hn : ops ≠ [])
+ (ht : ∀ m, trace pub state ops rs m = some (List.replicate k .tick, mid, m)) :
+ Pref pub state (.seq (PrimedStackRAM.lines ops hn) b) rs b mid k := by
+ intro m log out m'
+ constructor
+ · intro h
+ cases h with
+ | seq h₁ h₂ =>
+ have he := (Admin.exec_lines_iff_trace hn).mp h₁
+ rw [ht] at he
+ obtain ⟨rfl, rfl, rfl⟩ := by simpa only [Option.some.injEq, Prod.mk.injEq] using he
+ exact ⟨_, rfl, h₂⟩
+ · rintro ⟨es, rfl, he⟩
+ exact .seq ((Admin.exec_lines_iff_trace hn).mpr (ht m)) he
+
+theorem line {op : Op r p} (ht : ∀ m, op.effect pub state rs m = some (.tick, mid, m)) :
+ Pref pub state (.seq (.line op) b) rs b mid 1 := by
+ intro m log out m'
+ constructor
+ · intro h
+ cases h with
+ | seq h₁ h₂ =>
+ cases h₁ with
+ | line he =>
+ rw [ht] at he
+ obtain ⟨rfl, rfl, rfl⟩ := by simpa only [Option.some.injEq, Prod.mk.injEq] using he
+ exact ⟨_, rfl, h₂⟩
+ · rintro ⟨es, rfl, he⟩
+ exact .seq (.line (ht m)) he
+
+theorem ifLtYes {l q : Fin r} (h : rs l < rs q) :
+ Pref pub state (.ifLt l q a b) rs a rs 1 := by
+ intro m log out m'
+ constructor
+ · intro he
+ cases he with
+ | ifLtYes _ he => exact ⟨_, rfl, he⟩
+ | ifLtNo hh _ => contradiction
+ · rintro ⟨es, rfl, he⟩
+ exact .ifLtYes h he
+
+theorem ifLtNo {l q : Fin r} (h : ¬ rs l < rs q) :
+ Pref pub state (.ifLt l q a b) rs b rs 1 := by
+ intro m log out m'
+ constructor
+ · intro he
+ cases he with
+ | ifLtYes hh _ => contradiction
+ | ifLtNo _ he => exact ⟨_, rfl, he⟩
+ · rintro ⟨es, rfl, he⟩
+ exact .ifLtNo h he
+
+theorem ifEqYes {l q : Fin r} (h : rs l = rs q) :
+ Pref pub state (.ifEq l q a b) rs a rs 1 := by
+ intro m log out m'
+ constructor
+ · intro he
+ cases he with
+ | ifEqYes _ he => exact ⟨_, rfl, he⟩
+ | ifEqNo hh _ => contradiction
+ · rintro ⟨es, rfl, he⟩
+ exact .ifEqYes h he
+
+theorem ifEqNo {l q : Fin r} (h : rs l ≠ rs q) :
+ Pref pub state (.ifEq l q a b) rs b rs 1 := by
+ intro m log out m'
+ constructor
+ · intro he
+ cases he with
+ | ifEqYes hh _ => contradiction
+ | ifEqNo _ he => exact ⟨_, rfl, he⟩
+ · rintro ⟨es, rfl, he⟩
+ exact .ifEqNo h he
+
+end Pref
+end PrimedCounter.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterDispatchRun.lean b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchRun.lean
new file mode 100644
index 0000000000..7b1c2cb141
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchRun.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PrimedCounterCallPaths
+import OAI.Computability.VPVNP.PrimedCounterDispatchBounds
+import OAI.Computability.VPVNP.PrimedCounterRenameRun
+
+/-!
+# Executing the dispatched routine in the common table
+
+On success, the native machine consumes the choices of the selected local
+routine. Its log adds the dispatch ticks and the final cursor comparison, and
+the terminal return or accept accounts for one additional fuel unit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Dispatch
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM Program
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+theorem choices_ticks (k : ℕ) : choiceBits (List.replicate k (.tick : Event w)) = [] := by
+ induction k with
+ | zero => rfl
+ | succ k ih => simp [List.replicate_succ, choiceBits, ih]
+
+/-- Dispatch and exit add no external probes. -/
+theorem probes_framed (k : ℕ) (es : List (Event w)) :
+ countProbes ((List.replicate k .tick ++ es) ++ [.tick]) = countProbes es := by
+ have he : countProbes (es ++ [.tick]) = countProbes es := by
+ induction es with
+ | nil => rfl
+ | cons e es ih => cases e <;> simp [countProbes, ih]
+ induction k with
+ | zero => simpa using he
+ | succ k ih => simpa [List.replicate_succ, countProbes] using ih
+
+private theorem exit_control {U v : ℕ} (hfit : U < 2^w) (hv : v < U) :
+ (if ((v+1 : ℕ) : Word w) = (U : Word w) then none else some ((v+1 : ℕ) : Word w)) =
+ PrimedSchedule.control w U (v+1) := by
+ have hn : v+1 < 2^w := by omega
+ have hinj : (((v+1 : ℕ) : Word w) = (U : Word w)) ↔ v+1 = U := by
+ simp only [Fin.ext_iff, Fin.val_natCast, Nat.mod_eq_of_lt hn, Nat.mod_eq_of_lt hfit]
+ simp only [hinj]
+ by_cases hx : v+1 = U
+ · simp [PrimedSchedule.control, hx]
+ · simp [PrimedSchedule.control, hx, show v+1 < U by omega, PrimedSchedule.cursor, Fin.ofNat_eq_cast]
+
+variable {r p : ℕ} {pub : Pub → Word w} {regs mid : Regs w 52}
+ {state : Word w} {k U v : ℕ}
+
+/-- Read a run of the whole native table as a run of its original small
+routine, including the exact event framing and the post-call external memory. -/
+theorem execute_pref_iff (reg : Fin r ↪ Reg) (port : Fin p → Pub) (small : Flow r p)
+ (hp : Pref pub state body regs (renameFlow reg port small) mid k)
+ (h49 : mid 49 = ((v+1 : ℕ) : Word w)) (h50 : mid 50 = (U : Word w))
+ (n49 : (49 : Reg) ∉ Set.range reg) (n50 : (50 : Reg) ∉ Set.range reg)
+ (hv : v < U) (hfit : U < 2^w) (priv : Word w → Word w) (mem : Memory w)
+ (bits : List Bool) (fuel : ℕ) (out : Report w) :
+ let M := table.instantiate w pub
+ execute M.program fuel ⟨M.entry,state,regs,priv⟩ mem bits = some out ↔
+ ∃ es smallOut m', Flow.Exec (pub ∘ port) state small (mid ∘ reg) mem es smallOut m' ∧
+ k + es.length + 2 ≤ fuel ∧ choiceBits es = bits ∧
+ out.events = (List.replicate k .tick ++ es) ++ [.tick] ∧
+ out.result = PrimedSchedule.control w U (v+1) ∧ after mem out.events = m' := by
+ dsimp only
+ have hcall := Call.execute_iff body 49 50 pub state regs priv mem bits fuel out
+ dsimp only at hcall
+ unfold table
+ rw [hcall]
+ constructor
+ · rintro ⟨log, last, m', hr, hlen, hb, he, hc, hm⟩
+ obtain ⟨es, rfl, hbranch⟩ := (hp mem log last m').mp hr
+ obtain ⟨run, frame⟩ := restrictExec reg port pub small hbranch
+ refine ⟨es, _, m', run, by simpa using hlen, ?_, he, ?_, hm⟩
+ · simpa only [Flow.choiceBits_append, choices_ticks, List.nil_append] using hb
+ · rw [hc, frame _ n49, frame _ n50, h49, h50, exit_control hfit hv]
+ · rintro ⟨es, smallOut, m', hr, hlen, hb, he, hc, hm⟩
+ obtain ⟨last, run, _, frame⟩ := liftExec reg port pub hr mid rfl
+ refine ⟨_, last, m', (hp mem _ last m').mpr ⟨es, rfl, run⟩, by simpa using hlen, ?_, he, ?_, hm⟩
+ · simpa only [Flow.choiceBits_append, choices_ticks, List.nil_append] using hb
+ · rw [frame _ n49, frame _ n50, h49, h50, exit_control hfit hv, hc]
+
+private theorem outside_range {r : ℕ} (reg : Fin r ↪ Reg) (h : ∀ i, (reg i).val < 49) :
+ (49 : Reg) ∉ Set.range reg ∧ (50 : Reg) ∉ Set.range reg := by
+ constructor <;> rintro ⟨i, he⟩ <;> have hi := h i <;> rw [he] at hi <;> contradiction
+
+theorem input_outside : (49 : Reg) ∉ Set.range inputRegs ∧ (50 : Reg) ∉ Set.range inputRegs :=
+ outside_range inputRegs fun i => i.isLt.trans (by decide)
+
+theorem parser_outside : (49 : Reg) ∉ Set.range parserRegs ∧ (50 : Reg) ∉ Set.range parserRegs :=
+ outside_range parserRegs fun i => i.isLt.trans (by decide)
+
+theorem control_input (regs : Regs w 52) (v A U : ℕ) :
+ controlRegs regs v A U ∘ inputRegs = regs ∘ inputRegs := by
+ funext i
+ have h (j : Reg) (hj : 48 ≤ j.val) : inputRegs i ≠ j := fun hh => by
+ have hi : (inputRegs i).val < 48 := i.isLt
+ rw [hh] at hi
+ omega
+ simp only [Function.comp_apply, controlRegs, Function.update_of_ne (h 48 (by decide)),
+ Function.update_of_ne (h 49 (by decide)), Function.update_of_ne (h 50 (by decide)),
+ Function.update_of_ne (h 51 (by decide))]
+
+/-- Exact input-item specification on the assembly routine's own register file. -/
+theorem input_execute_iff {A S m nodes T : ℕ} (inputs : Fin 16 → Word w) (parser : Fin 14 → Word w)
+ (hm : parser (Admin.stackPublic 6) = (m : Word w)) (hfit : Cursor.calls A S m nodes T < 2^w)
+ (j : Fin A) (regs : Regs w 52) (priv : Word w → Word w) (mem : Memory w)
+ (bits : List Bool) (fuel : ℕ) (out : Report w) :
+ let M := table.instantiate w (publicWords inputs parser A S m nodes T)
+ execute M.program fuel ⟨M.entry,(j.val : Word w),regs,priv⟩ mem bits = some out ↔
+ ∃ es smallOut m', Flow.Exec inputs (j.val : Word w) (Opcodes.dataCall PortCode.program)
+ (regs ∘ inputRegs) mem es smallOut m' ∧
+ 6 + es.length + 2 ≤ fuel ∧ choiceBits es = bits ∧ out.events = (List.replicate 6 .tick ++ es) ++ [.tick] ∧
+ out.result = PrimedSchedule.control w (Cursor.calls A S m nodes T) (j.val+1) ∧ after mem out.events = m' := by
+ let pub := publicWords inputs parser A S m nodes T
+ have hh : pub ∘ inputPub = inputs := funext (public_input inputs parser A S m nodes T)
+ have hw : ScheduleWords pub A S m nodes T := scheduleWords inputs parser hm
+ have h := execute_pref_iff inputRegs inputPub (Opcodes.dataCall PortCode.program)
+ (input_pref (rs := regs) hw hfit j) (v := j.val) (U := Cursor.calls A S m nodes T)
+ (by simp (config := { decide := true }) [controlRegs, Function.update])
+ (by simp (config := { decide := true }) [controlRegs, Function.update])
+ input_outside.1 input_outside.2 (Cursor.index A S m nodes T (.inl j)).isLt hfit priv mem bits fuel out
+ rw [hh, control_input] at h
+ exact h
+
+end PrimedCounter.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterDispatchSite.lean b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchSite.lean
new file mode 100644
index 0000000000..1df5042aae
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterDispatchSite.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.PrimedCounterDispatchPrefix
+
+/-!
+# Dispatch within a site of the primed pair counter
+
+Dividing the cursor offset by the span of a site gives the row and its local
+cursor. The two comparisons then select a mark clear, root initialization,
+or node visit. This calculation and the preparation of the parser operands
+consume only ticks and preserve the two registers used to finish the call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Dispatch
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {w A S m nodes T : ℕ} {pub : Program.Pub → Word w} {state : Word w}
+ {rs : Regs w 52}
+
+/-- Selected parser routine for each position of a site. -/
+def siteBranch : Cursor.LocalItem m nodes → Program.Code
+ | .inl _ => Program.clear
+ | .inr (.inl _) => Program.init
+ | .inr (.inr _) => Program.node
+
+/-- Five row instructions, one or two comparisons, and any operand preparation. -/
+def siteTicks : Cursor.LocalItem m nodes → ℕ
+ | .inl _ | .inr (.inl _) => 7
+ | .inr (.inr _) => 8
+
+private def rowRegs (rs : Regs w 52) (u : Fin S) (i : Cursor.LocalItem m nodes) : Regs w 52 :=
+ let span := Cursor.span m nodes
+ let localPos := (Cursor.localIndex m nodes i).val
+ let rs := Function.update rs 18 ((u.val * span + localPos : ℕ) : Word w)
+ let rs := Function.update rs 19 (span : Word w)
+ let rs := Function.update rs 20 (u.val : Word w)
+ let rs := Function.update rs 21 (localPos : Word w)
+ Function.update rs 22 (m : Word w)
+
+/-- The branch sees the clear index in register 2 or the row offset in register 5. -/
+def siteRegs (rs : Regs w 52) (u : Fin S) (i : Cursor.LocalItem m nodes) : Regs w 52 :=
+ let mid := rowRegs rs u i
+ match i with
+ | .inl j => Function.update mid 2 (j.val : Word w)
+ | .inr (.inl _) => mid
+ | .inr (.inr _) => Function.update mid 5 ((u.val * m : ℕ) : Word w)
+
+@[simp] theorem siteRegs_clear_index (rs : Regs w 52) (u : Fin S) (j : Fin m) :
+ siteRegs (nodes := nodes) rs u (.inl j) (Program.parserReg 2) = (j.val : Word w) := by
+ simp (config := { decide := true }) [siteRegs, Program.parserReg]
+
+@[simp] theorem siteRegs_node_offset (rs : Regs w 52) (u : Fin S) (j : Fin nodes) :
+ siteRegs (m := m) rs u (.inr (.inr j)) (Program.parserReg 5) = ((u.val * m : ℕ) : Word w) := by
+ simp (config := { decide := true }) [siteRegs, Program.parserReg]
+
+@[simp] theorem siteRegs_next (rs : Regs w 52) (u : Fin S) (i : Cursor.LocalItem m nodes) :
+ siteRegs rs u i 49 = rs 49 := by
+ rcases i with j | j | j <;> simp (config := { decide := true }) [siteRegs, rowRegs, Function.update]
+
+@[simp] theorem siteRegs_total (rs : Regs w 52) (u : Fin S) (i : Cursor.LocalItem m nodes) :
+ siteRegs rs u i 50 = rs 50 := by
+ rcases i with j | j | j <;> simp (config := { decide := true }) [siteRegs, rowRegs, Function.update]
+
+private theorem row_operand (u : Fin S) (i : Cursor.LocalItem m nodes) :
+ rowRegs rs u i 20 = (u.val : Word w) ∧
+ rowRegs rs u i 21 = ((Cursor.localIndex m nodes i).val : Word w) ∧
+ rowRegs rs u i 22 = (m : Word w) := by
+ simp (config := { decide := true }) [rowRegs, Function.update]
+
+private theorem span_fit (u : Fin S) (hfit : Cursor.calls A S m nodes T < 2^w) :
+ Cursor.span m nodes < 2^w := by
+ have hS : 0 < S := u.pos
+ have hmul := Nat.le_mul_of_pos_left (Cursor.span m nodes) hS
+ unfold Cursor.calls at hfit
+ omega
+
+private theorem row_trace (u : Fin S) (i : Cursor.LocalItem m nodes)
+ (hfit : Cursor.calls A S m nodes T < 2^w)
+ (h48 : rs 48 = ((Cursor.index A S m nodes T (.inr (.inl (u,i)))).val : Word w))
+ (h51 : rs 51 = (A : Word w)) (h31 : pub 31 = (Cursor.span m nodes : Word w))
+ (hm : pub (Program.stackPub 6) = (m : Word w)) (mem : Memory w) :
+ trace pub state Program.rowSetup rs mem = some (List.replicate 5 .tick, rowRegs rs u i, mem) := by
+ let span := Cursor.span m nodes
+ let pos := (Cursor.localIndex m nodes i).val
+ have hpos : pos < span := (Cursor.localIndex m nodes i).isLt
+ have hs : 0 < span := by dsimp [span, Cursor.span]; omega
+ have hspan : (span : Word w).val = span := (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt (span_fit u hfit))
+ have hix := (Cursor.index A S m nodes T (.inr (.inl (u,i)))).isLt.trans hfit
+ rw [Cursor.index_site] at hix h48
+ have hoff : ((u.val * span + pos : ℕ) : Word w).val = u.val * span + pos :=
+ (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt (by change A + (u.val * span + pos) < 2^w at hix; omega))
+ have hsub : rs 48 - rs 51 = ((u.val * span + pos : ℕ) : Word w) := by
+ rw [h48, h51, Nat.cast_add, add_sub_cancel_left]
+ have hdiv : (u.val * span + pos) / span = u.val := by
+ rw [Nat.mul_comm, Nat.mul_add_div hs, Nat.div_eq_of_lt hpos, Nat.add_zero]
+ have hmod : (u.val * span + pos) % span = pos := by simp [Nat.mod_eq_of_lt hpos]
+ change pub 31 = (span : Word w) at h31
+ have hd : BinaryOp.div.eval (BinaryOp.sub.eval (rs 48) (rs 51)) (pub 31) = (u.val : Word w) := by
+ change Fin.ofNat _ ((rs 48 - rs 51).val / (pub 31).val) = _
+ rw [hsub, h31, hoff, hspan, hdiv, Fin.ofNat_eq_cast]
+ have hr : BinaryOp.mod.eval (BinaryOp.sub.eval (rs 48) (rs 51)) (pub 31) = (pos : Word w) := by
+ change Fin.ofNat _ ((rs 48 - rs 51).val % (pub 31).val) = _
+ rw [hsub, h31, hoff, hspan, hmod, Fin.ofNat_eq_cast]
+ have hs' : BinaryOp.sub.eval (rs 48) (rs 51) = ((u.val * span + pos : ℕ) : Word w) := hsub
+ simp (config := { decide := true }) [Program.rowSetup, trace, Op.effect, Function.update]
+ rw [hd, hr, hs', h31, hm]
+ rfl
+
+/-- The local dispatch preserves and reflects successful traces, with the exact
+tick count and the physical row and mark operands of the selected parser. -/
+theorem site_pref (u : Fin S) (i : Cursor.LocalItem m nodes)
+ (hfit : Cursor.calls A S m nodes T < 2^w)
+ (h48 : rs 48 = ((Cursor.index A S m nodes T (.inr (.inl (u,i)))).val : Word w))
+ (h51 : rs 51 = (A : Word w)) (h31 : pub 31 = (Cursor.span m nodes : Word w))
+ (hm : pub (Program.stackPub 6) = (m : Word w)) :
+ Pref pub state Program.site rs (siteBranch i) (siteRegs rs u i) (siteTicks i) := by
+ let check : Program.Code := .ifLt 21 22 (.seq (.line (.copy 2 21)) Program.clear)
+ (.ifEq 21 22 Program.init (.seq (.line (.binary .mul 5 20 22)) Program.node))
+ have setup : Pref pub state Program.site rs check (rowRegs rs u i) 5 :=
+ Pref.lines (by decide) (row_trace u i hfit h48 h51 h31 hm)
+ obtain ⟨hu, hi, hm'⟩ := row_operand (rs := rs) u i
+ have hspan := span_fit u hfit
+ have hmlt : m < 2^w := by unfold Cursor.span at hspan; omega
+ have hmv : (m : Word w).val = m := (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt hmlt)
+ have hpos := (Cursor.localIndex m nodes i).isLt.trans hspan
+ have hiv : (rowRegs rs u i 21).val = (Cursor.localIndex m nodes i).val := by
+ rw [hi, Fin.val_natCast, Nat.mod_eq_of_lt hpos]
+ let row := rowRegs (m := m) (nodes := nodes) rs u
+ rcases i with j | j | j
+ · have hlt : row (.inl j) 21 < row (.inl j) 22 := by
+ change (row (.inl j) 21).val < (row (.inl j) 22).val
+ dsimp only [row]
+ rw [hiv, hm', hmv, Cursor.local_clear]
+ exact j.isLt
+ apply setup.trans ((Pref.ifLtYes hlt).trans (Pref.line ?_))
+ intro mem
+ simp only [row, Op.effect, hi, Cursor.local_clear, siteRegs]
+ · have he : row (.inr (.inl j)) 21 = row (.inr (.inl j)) 22 := by
+ dsimp only [row]
+ rw [hi, hm', Cursor.local_init]
+ exact setup.trans ((Pref.ifLtNo (not_lt_of_ge he.ge)).trans (Pref.ifEqYes he))
+ · have hlt : row (.inr (.inr j)) 22 < row (.inr (.inr j)) 21 := by
+ change (row (.inr (.inr j)) 22).val < (row (.inr (.inr j)) 21).val
+ dsimp only [row]
+ rw [hiv, hm', hmv, Cursor.local_node]
+ omega
+ apply setup.trans ((Pref.ifLtNo hlt.not_gt).trans ((Pref.ifEqNo hlt.ne').trans (Pref.line ?_)))
+ intro mem
+ simp only [row, Op.effect, BinaryOp.eval, hu, hm', siteRegs, Nat.cast_mul]
+
+end PrimedCounter.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterFold.lean b/lean/OAI/Computability/VPVNP/PrimedCounterFold.lean
new file mode 100644
index 0000000000..4eba557c1d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterFold.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.PrimedCounterFoldBounds
+import OAI.Computability.VPVNP.PrimedCounterChronologySlots
+import OAI.Computability.VPVNP.PrimedCounterSiteLoop
+
+/-!
+# One logical transition per scheduled parser call
+
+The root initialization overwrites the pending stack. Each of the preceding
+calls erases one mark. Comparison looks up the grammar label corresponding
+to its dense histogram address. All administrative calls consume empty tapes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Fold
+
+open Chronology
+
+variable {n m s w A S K T : ℕ}
+
+/-- One call after input assembly, either a parser operation at a site or a comparison of a
+dense production count. -/
+abbrev PostItem (S m K T : ℕ) := (Fin S × Cursor.LocalItem m K) ⊕ Fin T
+
+/-- Absolute cursor of a post-assembly item in the complete pair schedule. -/
+def slot (i : PostItem S m K T) : Fin (Cursor.calls A S m K T) :=
+ Cursor.index A S m K T (.inr i)
+
+/-- Calls at a given site in execution order, clearing marks, installing its root and then
+visiting its nodes. -/
+def rowItems (u : Fin S) : List (PostItem S m K T) :=
+ (List.finRange m).map (fun j => .inl (u, .inl j)) ++
+ [.inl (u, .inr (.inl 0))] ++ (List.finRange K).map (fun j => .inl (u, .inr (.inr j)))
+
+/-- Chronological list of every site's parser calls followed by all production-count
+comparisons. -/
+def items (S m K T : ℕ) : List (PostItem S m K T) :=
+ (List.finRange S).flatMap rowItems ++ (List.finRange T).map Sum.inr
+
+/-- The current absolute cursor selects a complete local choice tape.
+Clear, initialize and compare reject a nonempty tape. -/
+noncomputable def call (w : ℕ) (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool)
+ (e : Label n m (Fin s) ≃ Fin T) (μ : Label n m (Fin s) →₀ ℕ) (raw : Tape A S m K T)
+ (st : VisitState n m s) (i : PostItem S m K T) : Option (VisitState n m s) :=
+ match i with
+ | .inl (_, .inl j) =>
+ if raw (slot i) = [] then some { st with marked := st.marked.erase j } else none
+ | .inl (_, .inr (.inl _)) =>
+ if raw (slot i) = [] then some { st with pending := [(d,root)] } else none
+ | .inl (u, .inr (.inr _)) => visit w (x u) st (raw (slot i))
+ | .inr j =>
+ if raw (slot i) = [] ∧ st.counts (e.symm j) = μ (e.symm j) then some st else none
+
+end PrimedCounter.Fold
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterFoldAcceptance.lean b/lean/OAI/Computability/VPVNP/PrimedCounterFoldAcceptance.lean
new file mode 100644
index 0000000000..d18cd01182
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterFoldAcceptance.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.PrimedCounterFoldOrder
+
+/-!
+# Acceptance of the absolute-cursor parser loop
+
+Clearing all mark addresses and initializing the root reconstructs the
+per-site start state. The node calls then agree with `visits` for every
+tape. The dense comparisons accept exactly when every nominated component
+agrees with the accumulated histogram.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Fold
+
+open Chronology
+open scoped Classical
+
+variable {n m s w A S K T : ℕ}
+
+private def rowAdmin (raw : Tape A S m K T) (u : Fin S) : Prop :=
+ (∀ j : Fin m, raw (slot (.inl (u, .inl j))) = []) ∧
+ raw (slot (.inl (u, .inr (.inl 0)))) = []
+
+private theorem clear_fold (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool)
+ (e : Label n m (Fin s) ≃ Fin T) (μ : Label n m (Fin s) →₀ ℕ) (raw : Tape A S m K T)
+ (st : VisitState n m s) (u : Fin S) (js : List (Fin m)) :
+ (js.map (fun j => Sum.inl (u, Sum.inl j))).foldlM (call w d root x e μ raw) st =
+ if ∀ j ∈ js, raw (slot (.inl (u, .inl j))) = [] then
+ some {st with marked := st.marked \ js.toFinset} else none := by
+ induction js generalizing st with
+ | nil => simp
+ | cons j js ih =>
+ by_cases hj : raw (slot (.inl (u, .inl j))) = []
+ · have hh : (st.marked.erase j) \ js.toFinset = st.marked \ (j :: js).toFinset := by
+ ext a
+ simp [and_assoc, and_left_comm]
+ simp only [List.map_cons, List.foldlM_cons, call, hj, ↓reduceIte, bind, Option.bind_some,
+ ih, List.mem_cons, forall_eq_or_imp, true_and, hh]
+ · simp [call, hj]
+
+/-- Execute a row, including all of its administrative tape checks. -/
+theorem row_fold (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool)
+ (e : Label n m (Fin s) ≃ Fin T) (μ : Label n m (Fin s) →₀ ℕ) (raw : Tape A S m K T)
+ (st : VisitState n m s) (u : Fin S) (hK : K = 2*d.val+1) :
+ (rowItems u).foldlM (call w d root x e μ raw) st =
+ if rowAdmin raw u then
+ visits w (x u) ⟨[(d,root)],∅,st.counts⟩ (List.ofFn (nodePart raw u)) else none := by
+ let init : VisitState n m s := ⟨[(d,root)],∅,st.counts⟩
+ have hn : nodePrefix w (x u) init (List.ofFn (nodePart raw u)) =
+ visits w (x u) init (List.ofFn (nodePart raw u)) :=
+ nodePrefix_visits _ _ _ (by simp [init, pendingNodes, hK])
+ have hclear : st.marked \ Finset.univ = ∅ := by ext; simp
+ rw [rowItems, List.foldlM_append, List.foldlM_append, clear_fold]
+ by_cases hc : ∀ j : Fin m, raw (slot (.inl (u, .inl j))) = []
+ · by_cases hr : raw (slot (.inl (u, .inr (.inl 0)))) = []
+ · simp [hc, hr, hclear, rowAdmin, call, List.foldlM_map]
+ simpa only [nodePrefix, List.ofFn_eq_map, List.foldlM_map, nodePart, slot, init] using hn
+ · simp [hc, hr, rowAdmin, call]
+ · simp [hc, rowAdmin]
+
+private theorem rows_fold (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool)
+ (e : Label n m (Fin s) ≃ Fin T) (μ : Label n m (Fin s) →₀ ℕ) (raw : Tape A S m K T)
+ (st : VisitState n m s) (rows : List (Fin S)) (hK : K = 2*d.val+1) :
+ ((rows.flatMap rowItems).foldlM (call w d root x e μ raw) st).map VisitState.counts =
+ if ∀ u ∈ rows, rowAdmin raw u then
+ runSites w d root x (fun v => List.ofFn (nodePart raw v)) rows st.counts else none := by
+ induction rows generalizing st with
+ | nil => simp [runSites]
+ | cons u rows ih =>
+ rw [List.flatMap_cons, List.foldlM_append, row_fold d root x e μ raw st u hK]
+ by_cases hu : rowAdmin raw u
+ · cases hv : visits w (x u) ⟨[(d,root)],∅,st.counts⟩ (List.ofFn (nodePart raw u)) with
+ | none =>
+ by_cases ha : ∀ v ∈ rows, rowAdmin raw v <;>
+ simp [hu, ha, hv, runSites]
+ | some next => simp [hu, hv, runSites, ih]
+ · simp [hu]
+
+private theorem compare_fold (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool)
+ (e : Label n m (Fin s) ≃ Fin T) (μ : Label n m (Fin s) →₀ ℕ) (raw : Tape A S m K T)
+ (st : VisitState n m s) (js : List (Fin T)) :
+ (js.map Sum.inr).foldlM (call w d root x e μ raw) st =
+ if ∀ j ∈ js, raw (slot (.inr j)) = [] ∧ st.counts (e.symm j) = μ (e.symm j)
+ then some st else none := by
+ induction js with
+ | nil => simp
+ | cons j js ih =>
+ by_cases hj : raw (slot (.inr j)) = [] ∧ st.counts (e.symm j) = μ (e.symm j) <;>
+ simp [call, hj, ih]
+
+/-- The parser portion of the tape succeeds exactly when the administrative
+slots are empty and the operational site histograms add to the nomination. -/
+theorem accepts_iff (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool)
+ (e : Label n m (Fin s) ≃ Fin T) (μ : Label n m (Fin s) →₀ ℕ) (raw : Tape A S m K T)
+ (st : VisitState n m s) (hK : K = 2*d.val+1) :
+ ((items S m K T).foldlM (call w d root x e μ raw) st).isSome ↔
+ AdminEmpty raw ∧ runSites w d root x (fun u => List.ofFn (nodePart raw u))
+ (List.finRange S) st.counts = some μ := by
+ have ha : AdminEmpty raw ↔ (∀ u, rowAdmin raw u) ∧ ∀ j, raw (slot (.inr j)) = [] := by
+ constructor
+ · intro h
+ exact ⟨fun u => ⟨h.1 u, h.2.1 u 0⟩, h.2.2⟩
+ · rintro ⟨h,h'⟩
+ exact ⟨fun u => (h u).1, fun u j => (Subsingleton.elim j 0) ▸ (h u).2, h'⟩
+ have hr := rows_fold (w := w) d root x e μ raw st (List.finRange S) hK
+ simp only [List.mem_finRange, forall_const] at hr
+ rw [items, List.foldlM_append, ha]
+ cases h : ((List.finRange S).flatMap rowItems).foldlM (call w d root x e μ raw) st with
+ | none =>
+ by_cases hm : ∀ u, rowAdmin raw u
+ · have hs : runSites w d root x (fun u => List.ofFn (nodePart raw u))
+ (List.finRange S) st.counts = none := by simpa [h,hm] using hr.symm
+ simp [hs]
+ · simp [hm]
+ | some out =>
+ have hm : ∀ u, rowAdmin raw u := by by_contra he; simp [h,he] at hr
+ have hs : runSites w d root x (fun u => List.ofFn (nodePart raw u))
+ (List.finRange S) st.counts = some out.counts := by simpa [h,hm] using hr.symm
+ have hh : (∀ j, out.counts (e.symm j) = μ (e.symm j)) ↔ out.counts = μ := by
+ constructor
+ · intro he
+ ext a
+ simpa using he (e a)
+ · rintro rfl
+ simp
+ simp [compare_fold, hm, hs, forall_and, hh]
+
+end PrimedCounter.Fold
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterFoldBounds.lean b/lean/OAI/Computability/VPVNP/PrimedCounterFoldBounds.lean
new file mode 100644
index 0000000000..051a112511
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterFoldBounds.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.PrimedCounterVisit
+
+/-!
+# Bounds on every executed prefix of node calls
+
+The remaining node count drops by one at each successful visit. This makes
+the terminal stack test redundant after exactly the prescribed number of calls.
+Every histogram component can increase by at most the prefix length, including
+prefixes of tapes that fail a later check.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Fold
+
+variable {n m s w : ℕ}
+
+theorem visit_bounds (x : Fin m → Bool) (st out : VisitState n m s) (bs : List Bool)
+ (hv : visit w x st bs = some out) :
+ leafMass out.pending ≤ leafMass st.pending ∧
+ pendingNodes out.pending + 1 = pendingNodes st.pending ∧
+ ∀ a, out.counts a ≤ st.counts a + 1 := by
+ rcases st with ⟨stack, marks, counts⟩
+ cases stack with
+ | nil => simp [visit] at hv
+ | cons f stack =>
+ cases ht : readToken w m s f.1.val bs with
+ | none => simp [visit, ht] at hv
+ | some t =>
+ cases hstep : step x f t with
+ | none => simp [visit, ht, hstep] at hv
+ | some p =>
+ obtain ⟨a, children⟩ := p
+ cases hm : markToken marks t with
+ | none => simp [visit, ht, hstep, hm] at hv
+ | some next =>
+ simp [visit, ht, hstep, hm] at hv
+ subst out
+ have hh := step_bounds x f t a children stack hstep
+ refine ⟨hh.1, hh.2, fun b => ?_⟩
+ classical
+ simp only [Finsupp.add_apply, Finsupp.single_apply]
+ split <;> omega
+
+/-- Run the chosen prefix without testing for end of traversal. -/
+noncomputable def nodePrefix (w : ℕ) (x : Fin m → Bool) (st : VisitState n m s)
+ (bs : List (List Bool)) := bs.foldlM (visit w x) st
+
+theorem nodePrefix_bounds (x : Fin m → Bool) (st out : VisitState n m s) (bs : List (List Bool))
+ (hr : nodePrefix w x st bs = some out) :
+ leafMass out.pending ≤ leafMass st.pending ∧
+ pendingNodes out.pending + bs.length = pendingNodes st.pending ∧
+ ∀ a, out.counts a ≤ st.counts a + bs.length := by
+ induction bs generalizing st with
+ | nil => simp [nodePrefix] at hr; subst out; simp
+ | cons b bs ih =>
+ cases hv : visit w x st b with
+ | none => simp [nodePrefix, hv] at hr
+ | some next =>
+ have htail : nodePrefix w x next bs = some out := by simpa [nodePrefix, hv] using hr
+ obtain ⟨hm, hk, hc⟩ := visit_bounds x st next b hv
+ obtain ⟨hm', hk', hc'⟩ := ih next htail
+ refine ⟨hm'.trans hm, by simp only [List.length_cons]; omega, fun a => ?_⟩
+ specialize hc a
+ specialize hc' a
+ simp only [List.length_cons]
+ omega
+
+/-- A full row has exactly as many node calls as pending nodes at its root. -/
+theorem nodePrefix_visits (x : Fin m → Bool) (st : VisitState n m s) (bs : List (List Bool))
+ (hl : bs.length = pendingNodes st.pending) :
+ nodePrefix w x st bs = visits w x st bs := by
+ induction bs generalizing st with
+ | nil =>
+ cases h : st.pending with
+ | nil => simp [nodePrefix, visits, h]
+ | cons f stack =>
+ simp only [List.length_nil, h] at hl
+ change 0 = 2 * f.1.val + 1 + pendingNodes stack at hl
+ omega
+ | cons b bs ih =>
+ cases hv : visit w x st b with
+ | none => simp [nodePrefix, visits, hv]
+ | some next =>
+ have hh := (visit_bounds x st next b hv).2.1
+ simp only [List.length_cons] at hl
+ simpa [nodePrefix, visits, hv] using ih next (by omega)
+
+end PrimedCounter.Fold
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterFoldChronology.lean b/lean/OAI/Computability/VPVNP/PrimedCounterFoldChronology.lean
new file mode 100644
index 0000000000..82c8944a94
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterFoldChronology.lean
@@ -0,0 +1,36 @@
+import OAI.Computability.VPVNP.PrimedCounterFoldAcceptance
+import OAI.Computability.VPVNP.PrimedCounterChronology
+
+/-!
+# The cursor fold recognizes the coefficient counter's accepting tapes
+
+After the input phase has supplied the shared bits, the concrete loop of
+clear, initialize, visit and compare calls recognizes the same tapes as the
+chronological acceptance condition.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Fold
+
+open BurstRAM PrimedInputRAM Chronology
+
+variable {L : Lengths} {n r H s w T : ℕ}
+
+theorem chronology_iff (Q : Layout L n r H w) (hdr : Header L → Bool)
+ (d : Fin n) (root : Fin s) (hsize : d.val + 1 = n)
+ (e : Label n n (Fin s) ≃ Fin T) (μ : Label n n (Fin s) →₀ ℕ) (raw : PairTape n r T) :
+ Accepts Q hdr d root μ raw ↔
+ ∃ bits : Bits L r H w, inputPart raw = inputCalls Q bits ∧
+ ((items (2*2^r) n (2*n-1) T).foldlM
+ (call w d root (rowInput Q hdr bits) e μ raw) ⟨[],∅,0⟩).isSome := by
+ have hK : 2*n-1 = 2*d.val+1 := by omega
+ simp only [Accepts, accepts_iff d root _ e μ raw _ hK]
+
+end PrimedCounter.Fold
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterFoldOrder.lean b/lean/OAI/Computability/VPVNP/PrimedCounterFoldOrder.lean
new file mode 100644
index 0000000000..75b76db58e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterFoldOrder.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.PrimedCounterFold
+import Mathlib.Data.List.OfFn
+
+/-!
+# Order and prefix capacity of the parser slots
+
+The expanded loops run through all absolute cursor values consecutively.
+Only node calls increase counts. The other calls preserve the histogram,
+and the root initializer reinstates a stack representing at most `n` leaves.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Fold
+
+open Chronology
+
+variable {n m s w A S K T : ℕ}
+
+private theorem row_order (u : Fin S) :
+ (rowItems (m := m) (K := K) (T := T) u).map (fun i => (slot (A := A) i).val) =
+ List.ofFn (fun j : Fin (Cursor.span m K) => A + (u.val * Cursor.span m K + j.val)) := by
+ conv_rhs =>
+ change List.ofFn (fun j : Fin (m + (1 + K)) => A + (u.val * Cursor.span m K + j.val))
+ rw [List.ofFn_add, List.ofFn_add]
+ simp [rowItems, slot, Cursor.index_site, List.ofFn_eq_map,
+ Function.comp_def, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm]
+
+/-- Reading the assembled inputs and then following the logical parser loops
+gives exactly the increasing absolute cursor. -/
+theorem items_order (A S m K T : ℕ) :
+ (List.finRange A).map (fun i => Cursor.index A S m K T (.inl i)) ++
+ (items S m K T).map slot = List.finRange (Cursor.calls A S m K T) := by
+ apply (List.map_injective_iff.mpr Fin.val_injective)
+ conv_rhs =>
+ rw [← List.ofFn_eq_map]
+ change List.ofFn (fun j : Fin (A + (S * Cursor.span m K + T)) => j.val)
+ rw [List.ofFn_add, List.ofFn_add, List.ofFn_mul]
+ simp only [items, List.map_append, List.map_map, List.map_flatMap, Function.comp_def,
+ Cursor.index_input, slot, Cursor.index_compare]
+ simp_rw [show ∀ u : Fin S,
+ List.map (fun i => (Cursor.index A S m K T (.inr i)).val) (rowItems u) =
+ List.ofFn (fun j : Fin (Cursor.span m K) => A + (u.val * Cursor.span m K + j.val)) from
+ fun u => row_order u]
+ simp [List.ofFn_eq_map, List.flatMap_def, Cursor.compareStart, Nat.add_assoc]
+
+/-- Detect the parser-node slots, the only post-assembly calls that can increment production
+counts. -/
+def isNode : PostItem S m K T → Bool
+ | .inl (_, .inr (.inr _)) => true
+ | _ => false
+
+@[simp] theorem rowItems_nodeCount (u : Fin S) :
+ (rowItems (m := m) (K := K) (T := T) u).countP isNode = K := by
+ simp [rowItems, List.countP_append, List.countP_map, Function.comp_def, isNode]
+
+@[simp] theorem items_nodeCount (S m K T : ℕ) :
+ (items S m K T).countP isNode = S*K := by
+ simp [items, List.countP_append, List.countP_flatMap, List.countP_map, Function.comp_def, isNode]
+
+private theorem call_bounds (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool)
+ (e : Label n m (Fin s) ≃ Fin T) (μ : Label n m (Fin s) →₀ ℕ) (raw : Tape A S m K T)
+ (st out : VisitState n m s) (i : PostItem S m K T) (hm : leafMass st.pending ≤ n)
+ (hc : call w d root x e μ raw st i = some out) :
+ leafMass out.pending ≤ n ∧ ∀ a, out.counts a ≤ st.counts a + if isNode i then 1 else 0 := by
+ rcases i with (⟨u, j | (j | j)⟩ | j)
+ · simp only [call] at hc
+ split at hc <;> simp only [Option.some.injEq, reduceCtorEq] at hc
+ subst out
+ simpa only [isNode, Bool.false_eq_true, ↓reduceIte, Nat.add_zero, le_refl, implies_true, and_true] using hm
+ · simp only [call] at hc
+ split at hc <;> simp only [Option.some.injEq, reduceCtorEq] at hc
+ subst out
+ exact ⟨d.isLt, fun _ => le_rfl⟩
+ · have hh := visit_bounds _ _ _ _ hc
+ exact ⟨hh.1.trans hm, hh.2.2⟩
+ · simp only [call] at hc
+ split at hc <;> simp_all [isNode]
+
+/-- Bounds hold for every executed prefix, regardless of later rejection.
+Each component increases by at most the number of node items. -/
+theorem prefix_bounds (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool)
+ (e : Label n m (Fin s) ≃ Fin T) (μ : Label n m (Fin s) →₀ ℕ) (raw : Tape A S m K T)
+ (st out : VisitState n m s) (p : List (PostItem S m K T)) (hm : leafMass st.pending ≤ n)
+ (hc : p.foldlM (call w d root x e μ raw) st = some out) :
+ leafMass out.pending ≤ n ∧ ∀ a, out.counts a ≤ st.counts a + p.countP isNode := by
+ induction p generalizing st with
+ | nil => simp at hc; subst out; simp [hm]
+ | cons i p ih =>
+ cases hi : call w d root x e μ raw st i with
+ | none => simp [hi] at hc
+ | some next =>
+ obtain ⟨hm', hb⟩ := call_bounds d root x e μ raw st next i hm hi
+ obtain ⟨hmo, ho⟩ := ih next hm' (by simpa [hi] using hc)
+ refine ⟨hmo, fun a => ?_⟩
+ specialize ho a
+ specialize hb a
+ rw [List.countP_cons]
+ omega
+
+/-- Immediately before a scheduled node, the next increment is bounded by
+the number of node calls in the whole rectangle. -/
+theorem next_increment_le (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool)
+ (e : Label n m (Fin s) ≃ Fin T) (μ : Label n m (Fin s) →₀ ℕ) (raw : Tape A S m K T)
+ (out : VisitState n m s) (p q : List (PostItem S m K T)) (u : Fin S) (j : Fin K)
+ (he : items S m K T = p ++ .inl (u, .inr (.inr j)) :: q)
+ (hc : p.foldlM (call w d root x e μ raw) ⟨[],∅,0⟩ = some out) :
+ leafMass out.pending ≤ n ∧ ∀ a, out.counts a + 1 ≤ S*K := by
+ obtain ⟨hm, hh⟩ := prefix_bounds d root x e μ raw _ out p (by simp [leafMass]) hc
+ refine ⟨hm, fun a => ?_⟩
+ specialize hh a
+ simp only [Finsupp.zero_apply, zero_add] at hh
+ have he' := congrArg (List.countP isNode) he
+ simp only [items_nodeCount, List.countP_append, List.countP_cons, isNode, ↓reduceIte] at he'
+ omega
+
+end PrimedCounter.Fold
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterGuessFlow.lean b/lean/OAI/Computability/VPVNP/PrimedCounterGuessFlow.lean
new file mode 100644
index 0000000000..0dbddc15b9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterGuessFlow.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.PrimedCounterGuessWord
+import OAI.Computability.VPVNP.PrimedInputRAMFlow
+
+/-!
+# Compiling the word-guess loop in the auxiliary program
+
+The word chooser is a structured block in the same finite control graph as
+the input passes, stack operations, mark checks, and histogram comparison.
+Its native correctness holds at any linked occurrence in that graph.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.GuessWord
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+
+variable {r k p w : ℕ}
+
+/-- Structured representation of the eight instructions for one word. -/
+def flow (reg : Fin 3 ↪ Fin r) : Flow r k :=
+ .seq (.line (.constant (reg 2) 0)) <|
+ .seq (.line (.constant (reg 0) 0)) <|
+ .seq (.line (.constant (reg 1) 1)) <|
+ .whileLt (reg 2) (reg 1) <| .seq
+ (.branch (.line (.binary .add (reg 0) (reg 0) (reg 1)))
+ (.line (.binary .add (reg 0) (reg 0) (reg 2))))
+ (.line (.binary .add (reg 1) (reg 1) (reg 1)))
+
+/-- Local labels in instruction order, from the first constant to the doubling. -/
+def flowLabels (reg : Fin 3 ↪ Fin r) : Fin 8 → (flow (k := k) reg).Label :=
+ ![.inl (), .inr (.inl ()), .inr (.inr (.inl ())), .inr (.inr (.inr (.inl ()))),
+ .inr (.inr (.inr (.inr (.inl (.inl ()))))),
+ .inr (.inr (.inr (.inr (.inl (.inr (.inl ())))))),
+ .inr (.inr (.inr (.inr (.inl (.inr (.inr ())))))),
+ .inr (.inr (.inr (.inr (.inr ()))))]
+
+theorem contains_flow {M : Machine w p r k} {reg : Fin 3 ↪ Fin r}
+ {label : (flow (k := k) reg).Label → Fin p} {done bad : Fin p}
+ (hc : Flow.Linked M (flow reg) label done bad) :
+ Contains M (label ∘ flowLabels reg) reg done := by
+ intro i
+ fin_cases i <;> exact hc.atLabel (flowLabels reg _)
+
+/-- A full word read inside a compiled compound program reaches the next
+linked block with its output register set to the chosen word. -/
+theorem flow_native {M : Machine w p r k} {reg : Fin 3 ↪ Fin r}
+ {label : (flow (k := k) reg).Label → Fin p} {done bad : Fin p}
+ (hc : Flow.Linked M (flow reg) label done bad) (c : Config w p r)
+ (hpc : c.pc = label (flow reg).entry) (v : Word w) :
+ ∃ out es, Prefix M c es out ∧ es.length = 4*w+4 ∧ choiceBits es = wordBits v ∧
+ out.pc = done ∧ out.reg (reg 0) = v ∧ (∀ j, j ∉ Set.range reg → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent :=
+ native M _ reg done (contains_flow hc) c hpc v
+
+theorem flow_native_exact {M : Machine w p r k} {reg : Fin 3 ↪ Fin r}
+ {label : (flow (k := k) reg).Label → Fin p} {done bad : Fin p}
+ (hc : Flow.Linked M (flow reg) label done bad) (c : Config w p r)
+ (hpc : c.pc = label (flow reg).entry) (v : Word w) :
+ Prefix M c (trace v) ⟨done, c.persistent, resultRegs reg c.reg v, c.privateMem⟩ :=
+ native_exact M _ reg done (contains_flow hc) c hpc v
+
+end PrimedCounter.GuessWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterGuessWord.lean b/lean/OAI/Computability/VPVNP/PrimedCounterGuessWord.lean
new file mode 100644
index 0000000000..c175109a55
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterGuessWord.lean
@@ -0,0 +1,282 @@
+import OAI.Computability.VPVNP.RAMUniform
+import OAI.Computability.VPVNP.RAMWordBits
+import Mathlib.Data.ZMod.Defs
+import Mathlib.Tactic.FinCases
+
+/-!
+# Native binary-word choice subroutine
+
+Three registers hold the partial value, the weight of the next bit, and zero.
+Doubling the weight wraps to zero exactly after the last of the machine word's
+bits. The eight-opcode fragment works at every word width, including zero, and
+may be embedded at arbitrary program counters with an arbitrary continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.GuessWord
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {p r k w : ℕ}
+
+/-- A local prefix of genuine native steps. The relation records every consumed
+branch bit and tick, and performs no external probe. -/
+inductive Prefix (M : Machine w p r k) : Config w p r → List (Event w) → Config w p r → Prop
+ | nil (c) : Prefix M c [] c
+ | tick {c next last es} (step : M.program.step c = .localStep next) (tail : Prefix M next es last) :
+ Prefix M c (.tick :: es) last
+ | choice {c g b last es} (step : M.program.step c = .branch g) (tail : Prefix M (g b) es last) :
+ Prefix M c (.choice b :: es) last
+
+variable {M : Machine w p r k} {c c' c'' : Config w p r} {es fs : List (Event w)}
+
+theorem Prefix.append (h : Prefix M c es c') (h' : Prefix M c' fs c'') :
+ Prefix M c (es ++ fs) c'' := by
+ induction h with
+ | nil => exact h'
+ | tick hs _ ih => exact .tick hs (ih h')
+ | choice hs _ ih => exact .choice hs (ih h')
+
+/-- A valid prefix composes with the genuine RAM interpreter on every
+continuation, preserving the external memory and every unconsumed bit. -/
+theorem Prefix.execute (h : Prefix M c es c') (fuel : ℕ) (mem : Memory w) (more : List Bool) :
+ BurstRAM.execute M.program (fuel + es.length) c mem (choiceBits es ++ more) =
+ (BurstRAM.execute M.program fuel c' mem more).map (fun rep => ⟨es ++ rep.events, rep.result⟩) := by
+ induction h with
+ | nil c => cases hh : BurstRAM.execute M.program fuel c mem more <;> simp [choiceBits, hh]
+ | tick hs ht ih | choice hs ht ih =>
+ rw [List.length_cons, ← Nat.add_assoc]
+ simp [choiceBits, BurstRAM.execute, hs, ih, Option.map_map, Function.comp_def, Report.prepend]
+
+/-- A stream that stops before the last required binary choice rejects,
+independently of the continuation and the available instruction fuel. -/
+theorem Prefix.execute_short (h : Prefix M c es c') (fuel : ℕ) (mem : Memory w)
+ (bits rest : List Bool) (b : Bool) (hs : choiceBits es = bits ++ b :: rest) :
+ BurstRAM.execute M.program fuel c mem bits = none := by
+ induction h generalizing bits fuel with
+ | nil =>
+ have hh := congrArg List.length hs
+ simp [choiceBits] at hh
+ | tick hstep _ ih =>
+ cases fuel with
+ | zero => rfl
+ | succ fuel => simp [BurstRAM.execute, hstep, ih fuel bits hs]
+ | @choice c g bit last es hstep htail ih =>
+ cases fuel with
+ | zero => rfl
+ | succ fuel =>
+ cases bits with
+ | nil => simp [BurstRAM.execute, hstep]
+ | cons t bits =>
+ obtain ⟨rfl, he⟩ := List.cons.inj hs
+ simp [BurstRAM.execute, hstep, ih fuel bits he]
+
+/-- Eight fixed instruction slots. Register zero is the result, register one
+is the binary weight, and register two is zero. -/
+def instruction (w : ℕ) (pc : Fin 8 → Fin p) (reg : Fin 3 ↪ Fin r) (done : Fin p) :
+ Fin 8 → Instr w p r k :=
+ ![.constant (reg 2) 0 (pc 1), .constant (reg 0) 0 (pc 2), .constant (reg 1) 1 (pc 3),
+ .jumpLt (reg 2) (reg 1) (pc 4) done, .choose (pc 5) (pc 6),
+ .binary .add (reg 0) (reg 0) (reg 1) (pc 7), .binary .add (reg 0) (reg 0) (reg 2) (pc 7),
+ .binary .add (reg 1) (reg 1) (reg 1) (pc 3)]
+
+/-- The instantiated table embeds the same fragment in any larger program. -/
+theorem resize_instruction (pc : Fin 8 → Fin p) (reg : Fin 3 ↪ Fin r) (done : Fin p) (i : Fin 8) :
+ (instruction (k := k) 1 pc reg done i).resize w = instruction w pc reg done i := by
+ fin_cases i <;> rfl
+
+/-- The host machine implements the eight word-guess instructions at the specified labels and
+registers with the specified continuation. -/
+def Contains (M : Machine w p r k) (pc : Fin 8 → Fin p) (reg : Fin 3 ↪ Fin r) (done : Fin p) : Prop :=
+ ∀ i, M.code (pc i) = instruction w pc reg done i
+
+/-- Value of a little-endian bit string, independently of the RAM word modulus. -/
+def value : List Bool → ℕ
+ | [] => 0
+ | b :: bs => (finTwoEquiv.symm b).val + 2 * value bs
+
+@[simp] private theorem digit_false : (finTwoEquiv.symm false).val = 0 := rfl
+@[simp] private theorem digit_true : (finTwoEquiv.symm true).val = 1 := rfl
+
+private theorem value_ofFn {z : ℕ} (f : Fin z → Bool) :
+ value (List.ofFn f) = ∑ i, (finTwoEquiv.symm (f i)).val * 2 ^ i.val := by
+ induction z with
+ | zero => simp [value]
+ | succ z ih =>
+ rw [List.ofFn_succ, value, Fin.sum_univ_succ, ih]
+ simp only [Fin.val_zero, pow_zero, mul_one, Fin.val_succ, pow_succ, ← Nat.mul_assoc,
+ ← Finset.sum_mul, Nat.mul_comm 2]
+
+@[simp] theorem value_wordBits (v : Word w) : value (wordBits v) = v.val := by
+ rw [wordBits, value_ofFn]
+ exact (finFunctionFinEquiv_apply (fun i => finTwoEquiv.symm (RAMSerialization.wordBits w v i))).symm.trans
+ (congrArg Fin.val ((RAMSerialization.wordBits w).symm_apply_apply v))
+
+/-- Loop events for guessing the supplied little-endian bit sequence, including one choice per
+bit and the final exit tick. -/
+def events {w : ℕ} : List Bool → List (Event w)
+ | [] => [.tick]
+ | b :: bs => [.tick, .choice b, .tick, .tick] ++ events bs
+
+@[simp] theorem length_events (bs : List Bool) : (events (w := w) bs).length = 4 * bs.length + 1 := by
+ induction bs with
+ | nil => rfl
+ | cons b bs ih => simp [events, ih]; omega
+
+@[simp] theorem choiceBits_events (bs : List Bool) : choiceBits (events (w := w) bs) = bs := by
+ induction bs with
+ | nil => rfl
+ | cons b bs ih => simpa [events, choiceBits] using congrArg (b :: ·) ih
+
+private theorem step_at {pc : Fin 8 → Fin p} {reg : Fin 3 ↪ Fin r} {done : Fin p}
+ (hc : Contains M pc reg done) (i : Fin 8) (hpc : c.pc = pc i) :
+ M.program.step c = (instruction w pc reg done i).run M.publicData c := by
+ simp [Machine.program, hpc, hc i]
+
+private theorem next_bit {pc : Fin 8 → Fin p} {reg : Fin 3 ↪ Fin r} {done : Fin p}
+ (hc : Contains M pc reg done) (hpc : c.pc = pc 3) (hz : c.reg (reg 2) = 0)
+ (hplace : c.reg (reg 1) ≠ 0) (b : Bool) :
+ let gain := if b then c.reg (reg 1) else c.reg (reg 2)
+ let ca := c.put (pc 7) (reg 0) (c.reg (reg 0) + gain)
+ let cb := ca.put (pc 3) (reg 1) (ca.reg (reg 1) + ca.reg (reg 1))
+ Prefix M c [.tick, .choice b, .tick, .tick] cb := by
+ dsimp only
+ have ht : M.program.step c = .localStep {c with pc := pc 4} := by
+ rw [step_at hc 3 hpc]
+ change CallAction.localStep {c with pc := if c.reg (reg 2) < c.reg (reg 1) then pc 4 else done} = _
+ have hpos : 0 < c.reg (reg 1) := Fin.pos_iff_ne_zero.mpr hplace
+ simp [hz, hpos]
+ apply Prefix.tick ht
+ let ct := {c with pc := pc 4}
+ have hb : M.program.step ct = .branch (fun b => {ct with pc := if b then pc 5 else pc 6}) :=
+ step_at hc 4 rfl
+ apply Prefix.choice hb
+ cases b with
+ | false =>
+ apply Prefix.tick (step_at hc 6 rfl)
+ exact Prefix.tick (step_at hc 7 rfl) (.nil _)
+ | true =>
+ apply Prefix.tick (step_at hc 5 rfl)
+ exact Prefix.tick (step_at hc 7 rfl) (.nil _)
+
+private theorem weight_ne_zero {i : ℕ} (hi : i < w) : ((2^i : ℕ) : Word w) ≠ 0 := by
+ intro h
+ have he := congrArg Fin.val h
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt (Nat.pow_lt_pow_right (by decide) hi)] at he
+ exact (Nat.two_pow_pos i).ne' he
+
+/-- Execute the exact choices remaining at a loop entry. -/
+private theorem loop {pc : Fin 8 → Fin p} {reg : Fin 3 ↪ Fin r} {done : Fin p}
+ (hc : Contains M pc reg done) (bits : List Bool) (c : Config w p r)
+ (i : ℕ) (hwidth : i + bits.length = w) (hpc : c.pc = pc 3)
+ (hz : c.reg (reg 2) = 0) (hp : c.reg (reg 1) = ((2^i : ℕ) : Word w)) :
+ ∃ out, Prefix M c (events bits) out ∧ out.pc = done ∧
+ out.reg (reg 0) = c.reg (reg 0) + c.reg (reg 1) * (value bits : Word w) ∧
+ (∀ j, j ∉ Set.range reg → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent ∧ out.reg (reg 1) = 0 ∧ out.reg (reg 2) = 0 := by
+ induction bits generalizing i c with
+ | nil =>
+ have he : c.reg (reg 1) = 0 := by
+ simp only [List.length_nil, Nat.add_zero] at hwidth
+ rw [hp, hwidth]
+ exact Fin.ext (Nat.mod_self _)
+ refine ⟨{c with pc := done}, Prefix.tick ?_ (.nil _), rfl, by simp [value], fun _ _ => rfl, rfl, rfl, he, hz⟩
+ rw [step_at hc 3 hpc]
+ change CallAction.localStep {c with pc := if c.reg (reg 2) < c.reg (reg 1) then pc 4 else done} = _
+ simp [he, hz]
+ | cons b bits ih =>
+ let gain := if b then c.reg (reg 1) else c.reg (reg 2)
+ let ca := c.put (pc 7) (reg 0) (c.reg (reg 0) + gain)
+ let cb := ca.put (pc 3) (reg 1) (ca.reg (reg 1) + ca.reg (reg 1))
+ have hv : i < w := by simp only [List.length_cons] at hwidth; omega
+ have pref := next_bit hc hpc hz (hp ▸ weight_ne_zero hv) b
+ have hpow : ((2^(i+1) : ℕ) : Word w) = ((2^i : ℕ) : Word w) + ((2^i : ℕ) : Word w) := by
+ rw [pow_succ, Nat.mul_two, Nat.cast_add]
+ have hplace : cb.reg (reg 1) = ((2^(i+1) : ℕ) : Word w) := by
+ simp [cb, ca, Config.put, hp, hpow]
+ obtain ⟨out, hpref, hdone, hacc, hother, hpriv, hpersist, hzero⟩ := ih cb (i+1)
+ (by simp only [List.length_cons] at hwidth; omega) rfl
+ (by simp [cb, ca, Config.put, hz]) hplace
+ refine ⟨out, pref.append hpref, hdone, ?_, ?_, hpriv, hpersist, hzero⟩
+ · rw [hacc]
+ cases b <;>
+ simp [cb, ca, Config.put, gain, hz, value] <;> ring
+ · intro j hj
+ have hj₀ : j ≠ reg 0 := fun e => hj ⟨0, e.symm⟩
+ have hj₁ : j ≠ reg 1 := fun e => hj ⟨1, e.symm⟩
+ rw [hother j hj]
+ simp [cb, ca, Config.put, Function.update_of_ne hj₀, Function.update_of_ne hj₁]
+
+/-- The complete event list including the three register initializations. -/
+def trace (v : Word w) : List (Event w) := [.tick, .tick, .tick] ++ events (wordBits v)
+
+/-- Exact register file at loop exit. Both temporary registers contain zero. -/
+def resultRegs (reg : Fin 3 ↪ Fin r) (rs : Fin r → Word w) (v : Word w) : Fin r → Word w :=
+ Function.update (Function.update (Function.update rs (reg 2) 0) (reg 1) 0) (reg 0) v
+
+/-- From its entry the native subroutine consumes exactly the canonical bits of
+the output word, uses `4*w+4` private instructions, and returns to its chosen
+continuation. Every external address and every other register is preserved. -/
+theorem native_exact (M : Machine w p r k) (pc : Fin 8 → Fin p) (reg : Fin 3 ↪ Fin r) (done : Fin p)
+ (hc : Contains M pc reg done) (c : Config w p r) (hpc : c.pc = pc 0) (v : Word w) :
+ Prefix M c (trace v) ⟨done, c.persistent, resultRegs reg c.reg v, c.privateMem⟩ := by
+ let z := c.put (pc 1) (reg 2) 0
+ let a := z.put (pc 2) (reg 0) 0
+ let start := a.put (pc 3) (reg 1) 1
+ have hinit : Prefix M c [.tick, .tick, .tick] start :=
+ .tick (step_at hc 0 hpc) (.tick (step_at hc 1 rfl) (.tick (step_at hc 2 rfl) (.nil _)))
+ obtain ⟨out, pref, he, hr, hrest, hp, hs, hw, hz⟩ := loop hc (wordBits v) start 0 (by simp) rfl
+ (by simp [start, a, z, Config.put]) (by simp [start])
+ have hr₀ : out.reg (reg 0) = v := by simpa [start, a, Config.put] using hr
+ have hout : out = ⟨done, c.persistent, resultRegs reg c.reg v, c.privateMem⟩ := by
+ have hregs : out.reg = resultRegs reg c.reg v := by
+ funext j
+ by_cases hj : j ∈ Set.range reg
+ · obtain ⟨i, rfl⟩ := hj
+ fin_cases i <;> simp [resultRegs, hr₀, hw, hz]
+ · have hnot (i : Fin 3) : j ≠ reg i := fun e => hj ⟨i, e.symm⟩
+ rw [hrest j hj]
+ simp [resultRegs, start, a, z, Config.put, Function.update_of_ne (hnot _)]
+ cases out
+ congr
+ rw [← hout]
+ exact hinit.append pref
+
+theorem native (M : Machine w p r k) (pc : Fin 8 → Fin p) (reg : Fin 3 ↪ Fin r) (done : Fin p)
+ (hc : Contains M pc reg done) (c : Config w p r) (hpc : c.pc = pc 0) (v : Word w) :
+ ∃ out es, Prefix M c es out ∧ es.length = 4*w+4 ∧ choiceBits es = wordBits v ∧
+ out.pc = done ∧ out.reg (reg 0) = v ∧ (∀ j, j ∉ Set.range reg → out.reg j = c.reg j) ∧
+ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by
+ refine ⟨_, _, native_exact M pc reg done hc c hpc v, by simp [trace], by simp [trace, choiceBits],
+ rfl, by simp [resultRegs], ?_, rfl, rfl⟩
+ intro j hj
+ have hnot (i : Fin 3) : j ≠ reg i := fun e => hj ⟨i, e.symm⟩
+ simp [resultRegs, Function.update_of_ne (hnot _)]
+
+/-- Every complete word-width string is the encoding of its unique output. -/
+theorem exists_wordBits (bs : List Bool) (h : bs.length = w) : ∃ v : Word w, wordBits v = bs := by
+ let f (i : Fin w) := bs.get (i.cast h.symm)
+ refine ⟨(RAMSerialization.wordBits w).symm f, ?_⟩
+ rw [wordBits, Equiv.apply_symm_apply]
+ apply List.ext_getElem (List.length_ofFn.trans h.symm)
+ intro i hi hi'
+ simp [f]
+
+theorem native_short {M : Machine w p r k} {pc : Fin 8 → Fin p} {reg : Fin 3 ↪ Fin r} {done : Fin p}
+ (hc : Contains M pc reg done) (c : Config w p r) (hpc : c.pc = pc 0) (bits : List Bool)
+ (hs : bits.length < w) (fuel : ℕ) (mem : Memory w) :
+ BurstRAM.execute M.program fuel c mem bits = none := by
+ let tail := List.replicate (w - bits.length - 1) false
+ obtain ⟨v, hv⟩ := exists_wordBits (w := w) (bits ++ false :: tail) (by simp [tail]; omega)
+ obtain ⟨out, es, he, _, hb, _⟩ := native M pc reg done hc c hpc v
+ exact he.execute_short fuel mem bits tail false (hb.trans hv)
+
+end PrimedCounter.GuessWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterHistory.lean b/lean/OAI/Computability/VPVNP/PrimedCounterHistory.lean
new file mode 100644
index 0000000000..893b483130
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterHistory.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.PrimedCounterData
+import OAI.Computability.VPVNP.PrimedCounterFoldOrder
+import OAI.Computability.VPVNP.PrimedScheduleRAM
+
+/-!
+# Lifting a per-call memory invariant through a native RAM history
+
+Consecutive post-assembly items occupy consecutive absolute cursor values.
+A successful item transfers the real external memory (including its reads
+and writes) to the next item. Matching rejection and success at each step
+therefore gives matching rejection and success for the whole scheduled fold.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.History
+
+open BurstRAM PrimedSchedule
+
+variable {U w : ℕ} {I State C : Type*}
+
+/-- Each item in the list has absolute cursor equal to its list index plus the starting offset. -/
+def Ordered (pos : I → Fin U) (k : ℕ) (xs : List I) : Prop :=
+ ∀ j : Fin xs.length, (pos (xs.get j)).val = k + j.val
+
+private theorem Ordered.head {pos : I → Fin U} {k : ℕ} {i : I} {xs : List I}
+ (h : Ordered pos k (i::xs)) : (pos i).val = k := by simpa using h 0
+
+private theorem Ordered.tail {pos : I → Fin U} {k : ℕ} {i : I} {xs : List I}
+ (h : Ordered pos k (i::xs)) : Ordered pos (k+1) xs := by
+ intro j
+ simpa [Nat.add_assoc, Nat.add_comm 1 j.val] using h j.succ
+
+/-- Identify all cursor values after a fixed list of preceding calls. -/
+theorem ordered_after {pos : I → Fin U} (front : List (Fin U)) (xs : List I)
+ (he : front ++ xs.map pos = List.finRange U) : Ordered pos front.length xs := by
+ intro j
+ have hlen := congrArg List.length he
+ simp only [List.length_append, List.length_map, List.length_finRange] at hlen
+ have hpos : front.length + j.val < U := (Nat.add_lt_add_left j.isLt front.length).trans_eq hlen
+ have hx := congrArg (fun l : List (Fin U) => l[front.length+j.val]?) he
+ rw [List.getElem?_append_right (by omega), Nat.add_sub_cancel_left,
+ List.getElem?_eq_getElem (by simp), List.getElem?_eq_getElem (by simpa using hpos)] at hx
+ simpa using congrArg Fin.val (Option.some.inj hx)
+
+/-- Simultaneous rejection, or two successful computations related by their
+results. -/
+inductive Match {α β : Type*} (rel : α → β → Prop) : Option α → Option β → Prop
+ | reject : Match rel none none
+ | accept {a b} (h : rel a b) : Match rel (some a) (some b)
+
+theorem Match.some_iff {α β : Type*} {a : α} {b : β} {rel : α → β → Prop} :
+ Match rel (some a) (some b) ↔ rel a b := by
+ constructor
+ · intro h
+ cases h with
+ | accept h => exact h
+ · exact Match.accept
+
+/-- A single-call proof supplies both directions of execution, the next
+persistent control, the per-call probe bound, and the invariant on real
+post-memory. -/
+abbrev Step (P : BurstRAM.Program w C) (fuel bound : ℕ) (pos : I → Fin U) (bits : I → List Bool)
+ (logical : State → I → Option State) (inv : ℕ → State → Memory w → Prop) :=
+ ∀ (i : I) (s : State) (m : Memory w), inv (pos i).val s m →
+ Match (fun s' (r : Report w) => r.result = control w U ((pos i).val+1) ∧
+ r.probes ≤ bound ∧ inv ((pos i).val+1) s' (after m r.events))
+ (logical s i) (execute P fuel (P.start (cursor w (pos i).val)) m (bits i))
+
+/-- Match the entire parser fold with the genuine successive-call interpreter,
+including exact cursor, memory, report length and individual probe bounds. -/
+theorem fold_run (P : BurstRAM.Program w C) (fuel bound : ℕ) (pos : I → Fin U) (bits : I → List Bool)
+ (logical : State → I → Option State) (inv : ℕ → State → Memory w → Prop)
+ (one : Step P fuel bound pos bits logical inv) (xs : List I) (k : ℕ)
+ (ho : Ordered pos k xs) (s : State) (m : Memory w) (hi : inv k s m) :
+ Match (fun s' (rs : List (Report w)) => rs.length = xs.length ∧
+ endState (control w U k) rs = control w U (k+xs.length) ∧
+ inv (k+xs.length) s' (after m (eventLog rs)) ∧ ∀ r ∈ rs, r.probes ≤ bound)
+ (xs.foldlM logical s) (runSegment P fuel (control w U k) m (xs.map bits)) := by
+ induction xs generalizing k s m with
+ | nil => exact Match.accept ⟨rfl, rfl, hi, fun _ hr => by simp at hr⟩
+ | cons i xs ih =>
+ have hk := ho.head
+ have hlt : k < U := hk ▸ (pos i).isLt
+ have hctrl : PrimedSchedule.control w U k = some (cursor w k) := by simp [PrimedSchedule.control, hlt]
+ have he := one i s m (hk ▸ hi)
+ cases hl : logical s i with
+ | none =>
+ rw [hl, hk] at he
+ cases hv : execute P fuel (P.start (cursor w k)) m (bits i) with
+ | none => simp [hctrl, runSegment, hv, hl, Match.reject]
+ | some r => rw [hv] at he; cases he
+ | some next =>
+ rw [hl, hk] at he
+ cases hv : execute P fuel (P.start (cursor w k)) m (bits i) with
+ | none => rw [hv] at he; cases he
+ | some r =>
+ rw [hv] at he
+ obtain ⟨hr, hb, hm⟩ := Match.some_iff.mp he
+ have htail := ih (k+1) ho.tail next (after m r.events) hm
+ cases hlf : xs.foldlM logical next with
+ | none =>
+ rw [hlf] at htail
+ cases hrf : runSegment P fuel (control w U (k+1)) (after m r.events) (xs.map bits) with
+ | none => simp [hl, hlf, runSegment, hctrl, hv, hr, hrf, Match.reject]
+ | some => rw [hrf] at htail; cases htail
+ | some last =>
+ rw [hlf] at htail
+ cases hrf : runSegment P fuel (control w U (k+1)) (after m r.events) (xs.map bits) with
+ | none => rw [hrf] at htail; cases htail
+ | some rs =>
+ rw [hrf] at htail
+ obtain ⟨hlen,hend,hinv,hbounds⟩ := Match.some_iff.mp htail
+ simp only [List.foldlM_cons, hl, bind, Option.bind_some, hlf, List.map_cons, runSegment,
+ hctrl, hv, hr, hrf, Option.map_some]
+ apply Match.accept
+ have heq : k+(i::xs).length = k+1+xs.length := by simp; omega
+ refine ⟨by simp [hlen], ?_, ?_, ?_⟩
+ · simpa only [endState, hr, heq] using hend
+ · rw [heq]
+ simpa only [eventLog, List.flatMap_cons, after, List.foldl_append] using hinv
+ · intro a ha
+ rcases List.mem_cons.mp ha with rfl | ha
+ · exact hb
+ · exact hbounds _ ha
+
+/-- Convert individual probe bounds and exact report length into the global
+and per-call transcript caps. -/
+theorem within {rs : List (Report w)} {S H bound : ℕ}
+ (hp : ∀ r ∈ rs, r.probes ≤ bound) (hh : 1+bound ≤ H) (ht : (1+bound)*rs.length ≤ S*H) :
+ withinCaps S H rs := by
+ have hsum (ls : List (Report w)) (hs : ∀ r ∈ ls, r.probes ≤ bound) :
+ RAMBuckets.cost Report.probes ls ≤ (1+bound)*ls.length := by
+ induction ls with
+ | nil => simp [RAMBuckets.cost]
+ | cons a l ih =>
+ have h₁ := hs a (List.mem_cons_self ..)
+ have h₂ := ih (fun r hr => hs r (List.mem_cons_of_mem _ hr))
+ rw [RAMBuckets.cost, List.length_cons, Nat.mul_add, Nat.mul_one]
+ omega
+ exact ⟨(hsum rs hp).trans ht, fun r hr => (Nat.add_le_add_left (hp r hr) 1).trans hh⟩
+
+end PrimedCounter.History
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterInputPrefix.lean b/lean/OAI/Computability/VPVNP/PrimedCounterInputPrefix.lean
new file mode 100644
index 0000000000..6329beb939
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterInputPrefix.lean
@@ -0,0 +1,175 @@
+import OAI.Computability.VPVNP.PrimedCounterInputPrefixCall
+import OAI.Computability.VPVNP.PrimedCounterPostHistory
+import OAI.Computability.VPVNP.PrimedCounterLength
+
+/-!
+# The input prefix in the complete coefficient counter
+
+The combined table assembles the two full rectangles before any parser call. Every
+accepted raw tape begins with precisely the choice lists of one internal assignment.
+The reports of this prefix include the combined table's private dispatch ticks and
+carry the assembled memory to the first parser cursor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.InputPrefix
+
+open BurstRAM PrimedInputRAM Opcodes
+
+variable {L : Lengths} {n r H w s : ℕ} {Q : Layout L n r H w}
+
+/-- Every physical assembler report acquires the same private dispatch padding. -/
+theorem reports_padded (D : Data Q s) (F : D.Fits) (g : Fin D.assembly → Bool)
+ (cells : List (Fin D.assembly)) (m : Memory w) :
+ (calls D F).dataReports g cells m = ((physicalSchedule Q F.assembler).dataReports g cells m).map padded := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih =>
+ simp only [ReturningCalls.dataReports, PhysicalSchedule.dataReports, reportList, List.map_cons] at ih ⊢
+ exact congrArg (_ :: ·) (ih _)
+
+private theorem prefix_bounds (D : Data Q s) (F : D.Fits) (g : Fin D.assembly → Bool)
+ (cells : List (Fin D.assembly)) (m : Memory w) (hm : CutMemory L m) :
+ ((calls D F).dataReports g cells m).length = cells.length ∧
+ ∀ p ∈ (calls D F).dataReports g cells m, p.probes ≤ 5 := by
+ induction cells generalizing m with
+ | nil => exact ⟨rfl, fun _ h ↦ False.elim (List.not_mem_nil h)⟩
+ | cons i cells ih =>
+ let R := physicalSchedule Q F.assembler
+ obtain ⟨hlen,hprobes⟩ := ih _ (R.closed i m (g i) hm)
+ refine ⟨congrArg Nat.succ hlen, ?_⟩
+ intro a ha
+ rcases List.mem_cons.mp ha with rfl | ht
+ · change (padded (R.report i m (g i))).probes ≤ 5
+ rw [padded_probes, R.probes _ _ _ hm]
+ have h := Item.report_probes (nativeOps Q i) (encodeBit w) 0 m (g i)
+ rw [Item.probes_eq_probeCount] at h
+ omega
+ · exact hprobes _ ht
+
+private theorem padded_cost (xs : List (Report w)) :
+ RAMBuckets.cost Report.probes (xs.map padded) = RAMBuckets.cost Report.probes xs := by
+ induction xs with
+ | nil => rfl
+ | cons a xs ih => simp [RAMBuckets.cost, ih]
+
+/-- The actual report prefix reaches the grammar cursor with the required memory,
+preserves the header words and costs at most eleven units per tape position. -/
+theorem run (D : Data Q s) (F : D.Fits) (bits : Chronology.Bits L r H w) :
+ let pre := (calls D F).dataReports (cursorBits Q bits) (List.finRange D.assembly) D.initial
+ runSegment D.machine.program D.fuel (some 0) D.initial (List.ofFn (Chronology.inputCalls Q bits)) = some pre ∧
+ endState (some 0) pre = some (cursor Q.cursorFits D.assembly le_rfl) ∧
+ after D.initial (eventLog pre) = Q.assembled (encodeBit w) bits D.initial ∧
+ RAMBuckets.cost Report.probes pre ≤ 11 * PrimedInputRAM.positions n r := by
+ dsimp only
+ let g := cursorBits Q bits
+ let xs := List.finRange D.assembly
+ have hm := cutMemory_header Q D.header D.hist
+ have hrun := (calls D F).splice g D.initial hm []
+ rw [List.append_nil, runSegment, Option.map_some, List.append_nil] at hrun
+ refine ⟨?_, (calls D F).prefix_endState g D.initial hm, ?_, ?_⟩
+ · rw [List.ofFn_eq_map]
+ exact hrun
+ · rw [reports_padded]
+ have same (rs : List (Report w)) (m : Memory w) :
+ after m (eventLog (rs.map padded)) = after m (eventLog rs) := by
+ induction rs generalizing m with
+ | nil => rfl
+ | cons a rs ih =>
+ simp only [eventLog, List.map_cons, List.flatMap_cons, after, List.foldl_append] at ih ⊢
+ exact (ih _).trans (congrArg (fun x ↦ (rs.flatMap Report.events).foldl update x) (padded_memory a m))
+ exact (same _ _).trans (input_prefix Q F.assembler bits D.initial hm).2.2.1
+ · rw [reports_padded, padded_cost]
+ exact (input_prefix Q F.assembler bits D.initial hm).2.2.2
+
+private theorem assignment_of_total (g : Fin (PrimedInputRAM.positions n r + PrimedInputRAM.positions n r) → Bool) :
+ ∃ bits : Chronology.Bits L r H w, Chronology.inputCalls Q bits = fun i ↦ (nativeOps Q i).bits (g i) := by
+ let T := Q.twoPass (encodeBit w)
+ let f : Assignment (fun i ↦ (nativeOps Q i).owns) := fun i ↦ g i.val
+ let a := T.assignmentEquiv.symm f
+ let bits : Chronology.Bits L r H w := a ∘ Q.internalOwner
+ have ha : Q.assignment bits = a := by
+ funext i
+ change a (Q.internalOwner (Q.internalOwner.symm i)) = a i
+ rw [Equiv.apply_symm_apply]
+ refine ⟨bits, ?_⟩
+ funext i
+ change (nativeOps Q i).bits (bitAt (T.assignmentEquiv (Q.assignment bits)) i) = _
+ rw [ha, show T.assignmentEquiv a = f from T.assignmentEquiv.apply_symm_apply f]
+ change (T.ops i).bits (bitAt f i) = (T.ops i).bits (g i)
+ cases h : (T.ops i).owns
+ · simp only [Item.bits, h, Bool.false_eq_true, ↓reduceIte]
+ · have hn : (nativeOps Q i).owns = true := h
+ simp only [Item.bits, bitAt, h, hn, ↓reduceIte]
+ rfl
+
+/-- Complete characterization at the boundary of the input phase, independently
+of every later parser and histogram choice. A malformed data call rejects here. -/
+theorem run_iff (D : Data Q s) (F : D.Fits) (inputTape : Fin D.assembly → List Bool)
+ (rs : List (Report w)) :
+ runSegment D.machine.program D.fuel (some 0) D.initial (List.ofFn inputTape) = some rs ↔
+ ∃ bits : Chronology.Bits L r H w, inputTape = Chronology.inputCalls Q bits ∧
+ rs = (calls D F).dataReports (cursorBits Q bits) (List.finRange D.assembly) D.initial := by
+ constructor
+ · intro hr
+ obtain ⟨g, hg⟩ := (calls D F).choices_of_length D.initial (cutMemory_header Q D.header D.hist)
+ (List.ofFn inputTape) rs hr List.length_ofFn
+ obtain ⟨bits, hb⟩ := assignment_of_total (Q := Q) g
+ have he : inputTape = Chronology.inputCalls Q bits := by
+ apply List.ofFn_injective
+ rw [hb, List.ofFn_eq_map (f := fun i ↦ (nativeOps Q i).bits (g i))]
+ exact hg
+ rw [he] at hr
+ exact ⟨bits, he, Option.some.inj (hr.symm.trans (run D F bits).1)⟩
+ · rintro ⟨bits, rfl, rfl⟩
+ exact (run D F bits).1
+
+/-- After the physical input prefix the entire remaining native run is the parser
+and histogram suffix, including its possible rejection. -/
+theorem full_splice (D : Data Q s) (F : D.Fits) (raw : Chronology.PairTape n r D.labels)
+ (bits : Chronology.Bits L r H w) (he : Chronology.inputPart raw = Chronology.inputCalls Q bits) :
+ ∃ pre : List (Report w),
+ runSegment D.machine.program D.fuel (some 0) D.initial (List.ofFn raw) =
+ (D.postNative bits raw).map (pre ++ ·) ∧
+ pre.length = D.assembly ∧ ∀ rep ∈ pre, rep.probes ≤ 14 := by
+ let xs := List.finRange D.assembly
+ let g := cursorBits Q bits
+ let pre := (calls D F).dataReports g xs D.initial
+ have hm := cutMemory_header Q D.header D.hist
+ have h := (calls D F).splice g D.initial hm (D.postTape raw)
+ have hb := prefix_bounds D F g xs D.initial hm
+ refine ⟨pre, ?_, hb.1.trans List.length_finRange, fun rep hrep ↦ (hb.2 _ hrep).trans (by decide)⟩
+ rw [← D.postTape_append raw, he, List.ofFn_eq_map]
+ unfold Data.postNative
+ rw [show PrimedSchedule.control w D.total D.assembly = some (cursor Q.cursorFits D.assembly le_rfl) by
+ rw [PrimedSchedule.control, ite_eq_left (assembly_lt_total D)]
+ exact congrArg some (Fin.ext (Nat.mod_eq_of_lt Q.cursorFits))]
+ exact h.trans (congrArg (fun m ↦ (runSegment D.machine.program D.fuel
+ (some (cursor Q.cursorFits D.assembly le_rfl)) m (D.postTape raw)).map (pre ++ ·))
+ ((Q.twoPass (encodeBit w)).scheduledMemory_eq _ Q.cursorFits (Q.assignment bits) D.initial))
+
+/-- A successful full native execution forces an internal assignment's exact
+per-cell choice streams in the input portion of the raw tape. -/
+theorem full_recover (D : Data Q s) (F : D.Fits) (raw : Chronology.PairTape n r D.labels)
+ (rs : List (Report w))
+ (hr : runSegment D.machine.program D.fuel (some 0) D.initial (List.ofFn raw) = some rs) :
+ ∃ bits : Chronology.Bits L r H w, Chronology.inputPart raw = Chronology.inputCalls Q bits := by
+ obtain ⟨g, suffix, _, hc, _, _, _⟩ := (calls D F).recover D.initial (cutMemory_header Q D.header D.hist)
+ (List.ofFn raw) rs hr (D.history_end F hr)
+ obtain ⟨bits,hbits⟩ := assignment_of_total (Q := Q) g
+ refine ⟨bits, List.ofFn_injective ?_⟩
+ have ht := congrArg (List.take D.assembly) ((D.postTape_append raw).trans hc)
+ rw [hbits, List.ofFn_eq_map]
+ have takePrefix (f : Fin D.assembly → List Bool) (xs : List (List Bool)) :
+ List.take D.assembly ((List.finRange D.assembly).map f ++ xs) = (List.finRange D.assembly).map f := by
+ convert (List.take_left (l₁ := (List.finRange D.assembly).map f) (l₂ := xs)) using 1; simp
+ simpa only [List.ofFn_eq_map, takePrefix] using ht
+
+end PrimedCounter.InputPrefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterInputPrefixCall.lean b/lean/OAI/Computability/VPVNP/PrimedCounterInputPrefixCall.lean
new file mode 100644
index 0000000000..165fe28b32
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterInputPrefixCall.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.PrimedCounterInputPrefixReset
+import OAI.Computability.VPVNP.PrimedCounterData
+import OAI.Computability.VPVNP.PrimedCounterDispatchRun
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeExecutionPrefix
+
+/-!
+# Input cells in the combined pair-counter table
+
+Each initial cursor of the combined program invokes the two-pass input assembler
+on reset registers. Dispatch contributes six private ticks and the returning
+cursor comparison one more. The cut-length reads and the item itself supply all
+external probes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.InputPrefix
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM Opcodes
+
+open scoped Fin.CommRing
+
+variable {L : Lengths} {n r H w s : ℕ} {Q : Layout L n r H w}
+
+private theorem parser_marks (D : Data Q s) : D.parserPub (Admin.stackPublic 6) = (n : Word w) :=
+ congrFun D.parserPub_stack 6
+
+theorem assembly_lt_total (D : Data Q s) : D.assembly < D.total := by
+ unfold Data.total Cursor.calls Cursor.span
+ have h : 0 < (2 * 2^r) * (n + (1 + (2*n-1))) := Nat.mul_pos (by positivity) (by omega)
+ omega
+
+private theorem state_eq (i : Fin (PrimedInputRAM.positions n r + PrimedInputRAM.positions n r)) :
+ cursor Q.cursorFits i.val i.isLt.le = (i.val : Word w) :=
+ Fin.ext (Nat.mod_eq_of_lt (i.isLt.trans Q.cursorFits)).symm
+
+private theorem successor_eq (i : Fin (PrimedInputRAM.positions n r + PrimedInputRAM.positions n r)) :
+ successor Q.cursorFits i = PrimedSchedule.cursor w (i.val+1) :=
+ Fin.ext (Nat.mod_eq_of_lt ((Nat.succ_le_of_lt i.isLt).trans_lt Q.cursorFits)).symm
+
+/-- Compared to the standalone assembler, the enclosing dispatch contributes
+two more private ticks before the body and one cursor-test tick afterwards. -/
+def padded (a : Report w) : Report w :=
+ ⟨(List.replicate 2 .tick ++ a.events) ++ [.tick], a.result⟩
+
+@[simp] theorem padded_memory (a : Report w) (m : Memory w) :
+ after m (padded a).events = after m a.events := by
+ simp [padded, after, update]
+
+@[simp] theorem padded_probes (a : Report w) : (padded a).probes = a.probes :=
+ Dispatch.probes_framed 2 a.events
+
+/-- Native reports agree exactly after accounting for the additional private
+dispatch ticks. This includes the values of all three cut-length reads. -/
+theorem cell_exec (D : Data Q s) (F : D.Fits) (i : Fin D.assembly)
+ (m : Memory w) (hc : CutMemory L m) (b : Bool) :
+ execute D.machine.program D.fuel (D.machine.program.start (cursor Q.cursorFits i.val i.isLt.le)) m
+ ((nativeOps Q i).bits b) = some (padded ((physicalSchedule Q F.assembler).report i m b)) := by
+ let st := cursor Q.cursorFits i.val i.isLt.le
+ obtain ⟨cost, hcost, hh⟩ := native_body Q F.assembler i m hc (fun _ ↦ 0)
+ obtain ⟨out, hr, hret⟩ := hh b
+ have he := dataEvents_length m cost (nativeOps Q i) b
+ have hne : st ≠ pubWord Q 0 + pubWord Q 0 := by
+ have hn := pubWord_cells Q F.assembler
+ have hv : ((pubWord Q 0) + (pubWord Q 0)).val = D.assembly := by
+ rw [Fin.val_add_eq_of_add_lt (by rw [hn]; exact Q.cursorFits), hn]
+ exact fun eq ↦ i.isLt.ne ((congrArg Fin.val eq).trans hv)
+ have physical := execute_data (pubWord Q) st m (nativeFuel r) hne _ out _ (dataCall_prefixRegs hr)
+ (by unfold nativeFuel; omega)
+ simp only [dataEvents_choices, hret] at physical
+ have report := Option.some.inj (((physicalSchedule Q F.assembler).data i m b hc).symm.trans physical)
+ rw [report, state_eq (Q := Q)]
+ rw [state_eq (Q := Q)] at hr
+ apply (Dispatch.input_execute_iff (pubWord Q) D.parserPub (parser_marks D) F.cursor i
+ (fun _ ↦ 0) (fun _ ↦ 0) m _ D.fuel _).mpr
+ refine ⟨_, out, _, hr, ?_, dataEvents_choices .., rfl, ?_, ?_⟩
+ · have hf : 3*r+165+20 ≤ D.fuel := le_max_left _ _
+ omega
+ · have hs : i.val+1 < D.total := lt_of_le_of_lt i.isLt (assembly_lt_total D)
+ simp only [padded, PrimedSchedule.control, hs, ↓reduceIte, successor_eq (Q := Q)]
+ · rw [padded_memory]
+ change after m (dataEvents m cost (nativeOps Q i) b) = _
+ exact dataEvents_memory ..
+
+/-- Contract of the returning input calls in the genuine pair table. -/
+def calls (D : Data Q s) (F : D.Fits) :
+ ReturningCalls D.machine.program D.fuel (nativeOps Q) (encodeBit w) Q.cursorFits (CutMemory L) where
+ report i m b := padded ((physicalSchedule Q F.assembler).report i m b)
+ data i m b hc := cell_exec D F i m hc b
+ result := (physicalSchedule Q F.assembler).result
+ memory i m b hc := (padded_memory _ _).trans ((physicalSchedule Q F.assembler).memory i m b hc)
+ closed := (physicalSchedule Q F.assembler).closed
+
+end PrimedCounter.InputPrefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterInputPrefixReset.lean b/lean/OAI/Computability/VPVNP/PrimedCounterInputPrefixReset.lean
new file mode 100644
index 0000000000..ff4738c87e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterInputPrefixReset.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeExecutionTable
+
+/-!
+# Private register reset before the embedded input body
+
+The standalone assembler prologue sets registers 4, 5 and 30 before entering
+the input body. The combined pair program instead uses fresh input registers.
+Parameter loading and cursor decoding overwrite these three registers before
+dispatch, and have identical events and post-registers at either entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.InputPrefix
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PrimedInputRAM PrimedInputRAM.Opcodes
+variable {w : ℕ}
+private def straight : PrimedInputRAM.Flow 48 16 → Prop
+ | .line _ => True
+ | .seq a b => straight a ∧ straight b
+ | _ => False
+
+private theorem exec_straight_once {pub : Pub → Word w} {st : Word w} {rs out : Regs w 48}
+ {m m' : Memory w} {es : List (Event w)} {a : Code}
+ (h : Flow.Exec pub st a rs m es out m') (hs : straight a) :
+ Flow.once pub st false a rs m = some (es,out,m') := by
+ induction h with
+ | line he => simp [Flow.once, he]
+ | seq _ _ iha ihb => simp [Flow.once, iha hs.1, ihb hs.2]
+ | ifEqYes | ifEqNo | ifLtYes | ifLtNo | branchYes | branchNo | whileDone | whileStep => contradiction
+
+set_option maxHeartbeats 2000000 in
+private theorem prefixRegs_erased (pub : Pub → Word w) (st : Word w) (m : Memory w) :
+ Flow.once pub st false (.seq loadParameters unpackCursor) (prefixRegs st (pub 0)) m =
+ Flow.once pub st false (.seq loadParameters unpackCursor) (fun _ ↦ 0) m := by
+ simp only [loadParameters, parameterTail, unpackCursor, Opcodes.sequence, Opcodes.bin, Opcodes.set,
+ Opcodes.line, Flow.once,
+ Op.effect, List.foldl_cons, List.foldl_nil, Option.map_some, bind, Option.bind_some, pure]
+ simp only [Option.some.injEq, Prod.mk.injEq, and_true]
+ constructor
+ · simp [prefixRegs]
+ · funext i
+ by_cases h4 : i = 4 <;> by_cases h5 : i = 5 <;> by_cases h30 : i = 30 <;>
+ simp [Function.update_apply, prefixRegs, h4, h5, h30]
+
+theorem dataCall_prefixRegs {pub : Pub → Word w} {st : Word w} {m m' : Memory w}
+ {es : List (Event w)} {out : Regs w 48}
+ (h : Flow.Exec pub st body (fun _ ↦ 0) m es out m') :
+ Flow.Exec pub st body (prefixRegs st (pub 0)) m es out m' := by
+ cases h with | seq he hact =>
+ cases he with | seq he hd =>
+ have hlin : straight (.seq loadParameters unpackCursor) := by
+ simp [straight, loadParameters, parameterTail, unpackCursor, Opcodes.sequence, Opcodes.set,
+ Opcodes.line, Opcodes.bin]
+ have ho := exec_straight_once he hlin
+ rw [← prefixRegs_erased] at ho
+ exact ((Flow.once_sound pub st false _ _ _ ho).1.seq hd).seq hact
+end PrimedCounter.InputPrefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterItemAgreement.lean b/lean/OAI/Computability/VPVNP/PrimedCounterItemAgreement.lean
new file mode 100644
index 0000000000..cfb0335767
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterItemAgreement.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.PrimedCounterDispatchNative
+import OAI.Computability.VPVNP.PrimedCounterFold
+import OAI.Computability.VPVNP.PrimedCounterChronology
+import OAI.Computability.VPVNP.PrimedCounterItemAgreementBlocks
+
+/-!
+# Each native parser call executes its chronological logical transition
+
+The absolute cursor selects the local code and prepares its operands. Row
+division and remainder point the node routine at the corresponding assembled
+tape. Success, rejection and the memory used by the next call agree with the
+logical transition on the same per-call list of branch bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Data
+
+open BurstRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {L : Lengths} {n r H s w : ℕ} {Q : Layout L n r H w}
+
+/-- At a node the pending frames must fit the stack and each counter must
+have room for one increment. The administrative phases use these bounds
+only when the cursor reaches a node. -/
+theorem postItem_agreement (D : Data Q s) (hf : D.Fits) (shared : Internal L r H w → Bool)
+ (st : VisitState n n s) (mem : Memory w) (held : D.Holds shared st mem)
+ (raw : Chronology.PairTape n r D.labels) (i : Fold.PostItem (2*2^r) n (2*n-1) D.labels)
+ (hnode : ∀ u j, i = .inl (u, .inr (.inr j)) →
+ leafMass st.pending ≤ n ∧ ∀ a, st.counts a + 1 < 2^w) :
+ let pos := Fold.slot (A := D.assembly) i
+ ItemAgreement D shared mem (PrimedSchedule.control w D.total (pos.val+1))
+ (Fold.call w D.degree D.root (Chronology.rowInput Q D.header shared)
+ (labelIndex n n s) D.nomination raw st i)
+ (execute D.machine.program D.fuel (D.machine.program.start (pos.val : Word w)) mem (raw pos)) := by
+ have hm : D.parserPub (Admin.stackPublic 6) = (n : Word w) := congrFun D.parserPub_stack 6
+ let regs : Regs w 52 := fun _ => 0
+ let priv : Word w → Word w := fun _ => 0
+ rcases i with ⟨u,j | (j | j)⟩ | j
+ · let it : Cursor.Item D.assembly (2*2^r) n (2*n-1) D.labels := .inr (.inl (u,.inl j))
+ let bs := raw (Cursor.index _ _ _ _ _ it)
+ exact ItemAgreement.clear hf held j (Dispatch.prepared_clear_index regs u j)
+ (fun out => Dispatch.clear_execute_iff (Opcodes.pubWord Q) D.parserPub hm hf.cursor regs priv mem bs D.fuel out u j)
+ · let it : Cursor.Item D.assembly (2*2^r) n (2*n-1) D.labels := .inr (.inl (u,.inr (.inl j)))
+ let bs := raw (Cursor.index _ _ _ _ _ it)
+ exact ItemAgreement.init hf held (fun out =>
+ Dispatch.init_execute_iff (Opcodes.pubWord Q) D.parserPub hm hf.cursor regs priv mem bs D.fuel out u j)
+ · let it : Cursor.Item D.assembly (2*2^r) n (2*n-1) D.labels := .inr (.inl (u,.inr (.inr j)))
+ let bs := raw (Cursor.index _ _ _ _ _ it)
+ let v : Site r := finProdFinEquiv.symm u
+ have hu : u.val = v.1.val*2^r + v.2.val := by
+ have he : (finProdFinEquiv v).val = u.val := congrArg Fin.val (finProdFinEquiv.apply_symm_apply u)
+ change v.2.val + 2^r * v.1.val = _ at he
+ rw [← he, Nat.mul_comm, Nat.add_comm]
+ have hrow : (Dispatch.prepared regs it ∘ Program.parserRegs) 5 =
+ (↑((v.1.val*2^r+v.2.val)*n) : Word w) := by
+ change Dispatch.prepared regs it (Program.parserReg 5) = _
+ rw [Dispatch.prepared_node_offset, hu]
+ obtain ⟨hmass,hcounts⟩ := hnode u j rfl
+ exact ItemAgreement.node hf held v.1 v.2 hrow hmass hcounts (fun out =>
+ Dispatch.node_execute_iff (Opcodes.pubWord Q) D.parserPub hm hf.cursor regs priv mem bs D.fuel out u j)
+ · let it : Cursor.Item D.assembly (2*2^r) n (2*n-1) D.labels := .inr (.inr j)
+ let bs := raw (Cursor.index _ _ _ _ _ it)
+ exact ItemAgreement.compare hf held j (Dispatch.prepared_compare_index regs j) (fun out =>
+ Dispatch.compare_execute_iff (Opcodes.pubWord Q) D.parserPub hm hf.cursor regs priv mem bs D.fuel out j)
+
+end PrimedCounter.Data
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterItemAgreementBlocks.lean b/lean/OAI/Computability/VPVNP/PrimedCounterItemAgreementBlocks.lean
new file mode 100644
index 0000000000..eb50b08be1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterItemAgreementBlocks.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.PrimedCounterItemAgreementCore
+import OAI.Computability.VPVNP.PrimedCounterKernel
+import OAI.Computability.VPVNP.PrimedStackRAMVisit
+import OAI.Computability.VPVNP.PrimedStackRAMFootprint
+
+/-!
+# Agreement of the four parser routines
+
+An administrative routine consumes an empty tape. A node consumes the binary
+words selected by its current pending degree. In both cases the post-memory
+of the routine represents the indicated logical state, and the dispatcher's
+ticks preserve that memory for the next call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.ItemAgreement
+
+open BurstRAM PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {L : Lengths} {n r H s w : ℕ} {Q : Layout L n r H w} {D : Data Q s}
+variable {st : VisitState n n s} {shared : Internal L r H w → Bool} {bits : List Bool}
+variable {mem : Memory w} {native : Option (Report w)} {next : Option (Word w)}
+variable {regs : Regs w 16} {state : Word w}
+
+theorem clear (hf : D.Fits) (held : D.Holds shared st mem) (j : Fin n) (hj : regs 2 = (j.val : Word w))
+ (fr : Framed native next 15 D.fuel D.parserPub state Admin.clear regs mem bits) :
+ ItemAgreement D shared mem next (if bits = [] then some {st with marked := st.marked.erase j} else none) native := by
+ split
+ · rename_i hb
+ obtain ⟨es,rs,he,hp,hl,hbits,ha⟩ := Admin.clear_cell D.parserPub_stack hf.scratch state regs mem j hj
+ apply accept_of_framed fr he _ (hbits.trans hb.symm) hf (Admin.clear_holds held.1 j hf.scratch) held.2 ha
+ · rw [hp]; decide
+ · rw [hl]; unfold Data.fuel; omega
+ · exact reject_nonempty fr ‹bits ≠ []›
+
+theorem init (hf : D.Fits) (held : D.Holds shared st mem)
+ (fr : Framed native next 15 D.fuel D.parserPub state Admin.init regs mem bits) :
+ ItemAgreement D shared mem next (if bits = [] then some {st with pending := [(D.degree,D.root)]} else none) native := by
+ split
+ · rename_i hb
+ obtain ⟨es,rs,he,hp,hl,hbits,_,_,ha⟩ := Admin.init_cell D.parserPub_stack hf.scratch state regs mem
+ D.degree D.root D.parserPub_root.1 D.parserPub_root.2.1
+ apply accept_of_framed fr he _ (hbits.trans hb.symm) hf (Admin.root_holds held.1 D.degree D.root hf.scratch) held.2 ha
+ · rw [hp]; decide
+ · rw [hl]; unfold Data.fuel; omega
+ · exact reject_nonempty fr ‹bits ≠ []›
+
+theorem compare (hf : D.Fits) (held : D.Holds shared st mem) (j : Fin D.labels) (hj : regs 7 = (j.val : Word w))
+ (fr : Framed native next 9 D.fuel D.parserPub state Admin.compare regs mem bits) :
+ ItemAgreement D shared mem next
+ (if bits = [] ∧ st.counts ((labelIndex n n s).symm j) = D.nomination ((labelIndex n n s).symm j)
+ then some st else none) native := by
+ have hpre := hf.headers.trans (Nat.le_add_right Q.scratchBase (PrimedInputRAM.positions n r))
+ obtain ⟨hyes,hno⟩ := Admin.compare_cell D.parserPub_stack hf.scratch state regs mem held.1 j hj L
+ D.parserPub_root.2.2 hpre
+ rw [held.2 j, D.nominated_value hf j] at hyes hno
+ split
+ · rename_i hh
+ obtain ⟨es,rs,he,hp,hl,hbits⟩ := hyes hh.2
+ apply accept_of_framed fr he _ (hbits.trans hh.1.symm) hf held.1 held.2 (fun _ _ => rfl)
+ · rw [hp]; decide
+ · rw [hl]; unfold Data.fuel; omega
+ · rename_i hh
+ by_cases hb : bits = []
+ · apply reject_of_framed fr
+ intro es rs m' hx
+ exact (hno (fun h => hh ⟨hb,h⟩) es rs m' hx).elim
+ · exact reject_nonempty fr hb
+
+theorem node (hf : D.Fits) (held : D.Holds shared st mem) (g : Fin 2) (v : Fin (2^r))
+ (hrow : regs 5 = (↑((g.val*2^r+v.val)*n) : Word w))
+ (hmass : leafMass st.pending ≤ n) (hcounts : ∀ a, st.counts a+1 < 2^w)
+ (fr : Framed native next 16 D.fuel (D.parserPub ∘ Admin.stackPublic) state nodeFlow regs mem bits) :
+ ItemAgreement D shared mem next (visit w (D.input shared g v) st bits) native := by
+ rw [D.parserPub_stack] at fr
+ let pub := publicData w D.base (2^r) n n s
+ have ha := completeNode_visit held.1 g v state regs bits hrow hf.scratch hf.states hf.word
+ (by simpa [pow_two] using hf.triangle) hmass hcounts
+ cases hr : completeNode pub state regs mem bits with
+ | none =>
+ change Agreement D.base (D.input shared) _ (completeNode pub state regs mem bits) at ha
+ rw [hr] at ha
+ cases hv : visit w (D.input shared g v) st bits <;> rw [hv] at ha <;> cases ha
+ apply reject_of_framed fr
+ intro es rs m' hx hb
+ have ht := (completeNode_iff_exec (o := ⟨es,rs,m',[]⟩)).mpr ⟨hx,hb.symm,rfl⟩
+ rw [hr] at ht
+ contradiction
+ | some o =>
+ change Agreement D.base (D.input shared) _ (completeNode pub state regs mem bits) at ha
+ rw [hr] at ha
+ cases hv : visit w (D.input shared g v) st bits <;> rw [hv] at ha <;> cases ha
+ obtain ⟨hx,hbits,_⟩ := completeNode_iff_exec.mp hr
+ have hl := node_refines.bounded (Option.filter_eq_some_iff.mp hr).1
+ exact accept_of_framed fr hx (by unfold Data.fuel; omega) hbits.symm hf (by assumption) held.2
+ (completeNode_below hf.scratch hr) (by assumption)
+
+end PrimedCounter.ItemAgreement
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterItemAgreementCore.lean b/lean/OAI/Computability/VPVNP/PrimedCounterItemAgreementCore.lean
new file mode 100644
index 0000000000..da075c3fde
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterItemAgreementCore.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.PrimedCounterData
+import OAI.Computability.VPVNP.PrimedCounterAdminRun
+import OAI.Computability.VPVNP.PrimedCounterDispatchRun
+
+/-!
+# Native and logical results of a scheduled parser call
+
+The native call emits private ticks before and after the selected routine.
+Replaying its report therefore produces the same memory as the routine. A
+successful call retains the nomination words below the scratch base and its
+probe count charges only reads and writes inside the routine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open BurstRAM PrimedStackRAM PrimedInputRAM
+open scoped Fin.CommRing
+
+variable {L : Lengths} {n r H s w : ℕ} {Q : Layout L n r H w}
+
+/-- The logical and native call reject together or return corresponding parser state and
+memory, with the expected control, preserved lower addresses and at most fourteen probes. -/
+inductive ItemAgreement (D : Data Q s) (shared : Internal L r H w → Bool)
+ (mem : Memory w) (next : Option (Word w)) :
+ Option (VisitState n n s) → Option (Report w) → Prop
+ | reject : ItemAgreement D shared mem next none none
+ | accept {st : VisitState n n s} {out : Report w}
+ (holds : D.Holds shared st (after mem out.events))
+ (prefixWords : ∀ a < D.base, after mem out.events a = mem a)
+ (probes : out.probes ≤ 14) (control : out.result = next) :
+ ItemAgreement D shared mem next (some st) (some out)
+
+namespace ItemAgreement
+
+variable {D : Data Q s} {shared : Internal L r H w → Bool} {k : ℕ}
+variable {pub : Fin k → Word w} {state : Word w} {small : Flow 16 k}
+variable {regs : Regs w 16} {mem : Memory w} {bits : List Bool}
+variable {native : Option (Report w)} {next : Option (Word w)} {overhead fuel : ℕ}
+
+/-- The dispatcher's exact report specification for the selected routine. -/
+def Framed (native : Option (Report w)) (next : Option (Word w)) (overhead fuel : ℕ)
+ (pub : Fin k → Word w) (state : Word w) (small : Flow 16 k)
+ (regs : Regs w 16) (mem : Memory w) (bits : List Bool) : Prop :=
+ ∀ out, native = some out ↔ ∃ es rs m', Flow.Exec pub state small regs mem es rs m' ∧
+ overhead + es.length + 2 ≤ fuel ∧ choiceBits es = bits ∧
+ out.events = (List.replicate overhead .tick ++ es) ++ [.tick] ∧
+ out.result = next ∧ after mem out.events = m'
+
+theorem reject_of_framed (fr : Framed native next overhead fuel pub state small regs mem bits)
+ (he : ∀ es rs m', Flow.Exec pub state small regs mem es rs m' → choiceBits es ≠ bits) :
+ ItemAgreement D shared mem next none native := by
+ cases hn : native with
+ | none => exact .reject
+ | some rep =>
+ obtain ⟨es,rs,m',hx,_,hb,_⟩ := (fr rep).mp hn
+ exact (he es rs m' hx hb).elim
+
+private theorem after_framed (es : List (Event w)) (k : ℕ) (mem : Memory w) :
+ after mem ((List.replicate k .tick ++ es) ++ [.tick]) = after mem es := by
+ induction k with
+ | zero => simp [after, update]
+ | succ k ih => simpa [List.replicate_succ, after, update] using ih
+
+theorem accept_of_framed (fr : Framed native next overhead fuel pub state small regs mem bits)
+ {st : VisitState n n s} {es : List (Event w)} {rs : Regs w 16} {m' : Memory w}
+ (hx : Flow.Exec pub state small regs mem es rs m') (hlen : overhead + es.length + 2 ≤ fuel)
+ (hbits : choiceBits es = bits) (hf : D.Fits) (hheld : PrimedStackRAM.Holds D.base (D.input shared) st m')
+ (hnom : D.Nominated mem) (hbelow : ∀ a < D.base, m' a = mem a) (hp : countProbes es ≤ 14) :
+ ItemAgreement D shared mem next (some st) native := by
+ let rep : Report w := ⟨(List.replicate overhead .tick ++ es) ++ [.tick], next⟩
+ have hm : after mem rep.events = m' := (after_framed ..).trans (Call.exec_memory hx)
+ rw [(fr rep).mpr ⟨es,rs,m',hx,hlen,hbits,rfl,rfl,hm⟩]
+ apply accept
+ · rw [hm]
+ refine ⟨hheld, ?_⟩
+ intro j
+ have hj : Header.count L + j.val < Q.scratchBase := (Nat.add_lt_add_left j.isLt _).trans_le hf.headers
+ rw [hbelow _ (hj.trans_le (Nat.le_add_right ..)), hnom]
+ · rwa [hm]
+ · change countProbes ((List.replicate overhead .tick ++ es) ++ [.tick]) ≤ 14
+ rwa [Dispatch.probes_framed]
+ · rfl
+
+/-- A deterministic administrative routine rejects every surplus tape bit. -/
+theorem reject_nonempty {ops : List (Op 16 k)} {hne : ops ≠ []}
+ (fr : Framed native next overhead fuel pub state (lines ops hne) regs mem bits)
+ (hb : bits ≠ []) : ItemAgreement D shared mem next none native := by
+ apply reject_of_framed fr
+ intro es rs m' hx
+ rw [Admin.trace_choiceBits ((Admin.exec_lines_iff_trace hne).mp hx)]
+ exact Ne.symm hb
+
+end ItemAgreement
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterKernel.lean b/lean/OAI/Computability/VPVNP/PrimedCounterKernel.lean
new file mode 100644
index 0000000000..464d5a08b6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterKernel.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.PrimedCounterKernelExact
+import OAI.Computability.VPVNP.PrimedCounterAdminExec
+import OAI.Computability.VPVNP.PrimedStackRAMChoices
+
+/-!
+# Choice suffixes and structured executions of the preorder counter
+
+The kernel for a node consumes a canonical word for a leaf and three words for
+a binary node. Its remaining choice suffix can be passed to any further block.
+These equivalences describe every successful derivation and every rejecting tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM PrimedInputRAM PrimedCounter
+
+variable {w r k : ℕ}
+
+/-- The kernel realizes exactly the finite executions whose choice prefix is available. -/
+def KernelExec (a : Flow r k) (f : Kernel w r k) : Prop :=
+ ∀ {pub st rs m bits o}, f pub st rs m bits = some o ↔
+ Flow.Exec pub st a rs m o.events o.regs o.mem ∧ bits = choiceBits o.events ++ o.bits
+
+theorem lines_kernel_exec (ops : List (Op r k)) (hn : ops ≠ []) :
+ KernelExec (lines ops hn) (lineKernel (w := w) ops) := by
+ intro pub st rs m bits o
+ constructor
+ · intro h
+ obtain ⟨⟨es,rs',m'⟩, ht, rfl⟩ := Option.map_eq_some_iff.mp h
+ exact ⟨(Admin.exec_lines_iff_trace hn).mpr ht, by simp [Admin.trace_choiceBits ht]⟩
+ · rintro ⟨he,hb⟩
+ have ht := (Admin.exec_lines_iff_trace hn).mp he
+ rw [Admin.trace_choiceBits ht, List.nil_append] at hb
+ simp [lineKernel, ht, hb]
+
+private theorem guess_events_memory (bs : List Bool) (m : Memory w) :
+ after m (GuessWord.events bs) = m := by
+ induction bs with
+ | nil => rfl
+ | cons b bs ih => exact ih
+
+private theorem guess_replays (reg : Fin 3 ↪ Fin r) : Replays (guessKernel (w := w) (k := k) reg) := by
+ intro pub st rs m bits o h
+ obtain ⟨⟨v,t⟩, _, rfl⟩ := Option.map_eq_some_iff.mp h
+ exact guess_events_memory (wordBits v) m
+
+theorem guess_kernel_exec (reg : Fin 3 ↪ Fin r) :
+ KernelExec (GuessWord.flow (k := k) reg) (guessKernel (w := w) reg) := by
+ intro pub st rs m bits o
+ have h := guess_refine (w := w) (k := k) reg
+ have replay : Replays (guessKernel (w := w) (k := k) reg) := guess_replays reg
+ constructor
+ · intro hx
+ obtain ⟨⟨v,t⟩, hv, rfl⟩ := Option.map_eq_some_iff.mp hx
+ have ht : takeWord w (wordBits v) = some (v,[]) := (takeWord_eq_some_iff ..).mpr (by simp)
+ have ho : guessKernel reg pub st rs m (wordBits v) =
+ some ⟨GuessWord.trace v, GuessWord.resultRegs reg rs v, m, []⟩ := by simp [guessKernel, ht]
+ exact ⟨((h.kernel_iff_exec replay ..).mp ho).1,
+ by simpa [GuessWord.trace, choiceBits] using (takeWord_eq_some_iff ..).mp hv⟩
+ · rintro ⟨he,rfl⟩
+ have hx := h.kernel_of_exec replay he
+ obtain ⟨⟨v,t⟩, hv, hout⟩ := Option.map_eq_some_iff.mp hx
+ cases o with
+ | mk es rs' m' tail =>
+ simp only [Output.mk.injEq] at hout
+ obtain ⟨rfl,rfl,rfl,rfl⟩ := hout
+ have ht : takeWord w (choiceBits (GuessWord.trace v) ++ tail) = some (v,tail) :=
+ (takeWord_eq_some_iff ..).mpr (by simp [GuessWord.trace, choiceBits])
+ simp [guessKernel, ht]
+
+theorem KernelExec.seq {a b : Flow r k} {fa fb : Kernel w r k}
+ (ha : KernelExec a fa) (hb : KernelExec b fb) : KernelExec (.seq a b) (seqKernel fa fb) := by
+ intro pub st rs m bits o
+ constructor
+ · intro h
+ simp only [seqKernel, bind, Option.bind_eq_some_iff] at h
+ obtain ⟨x, hx, y, hy, hout⟩ := h
+ cases hout
+ obtain ⟨he,hbits⟩ := ha.mp hx
+ obtain ⟨hf,hrest⟩ := hb.mp hy
+ exact ⟨.seq he hf, by simp [Output.prepend, Flow.choiceBits_append, hbits, hrest]⟩
+ · rintro ⟨he,hbits⟩
+ cases o with
+ | mk es out mem tail =>
+ cases he with
+ | @seq _ _ _ _ es r₁ m₁ fs _ _ he hf =>
+ let rest := choiceBits fs ++ tail
+ have hx : fa pub st rs m bits = some ⟨es,r₁,m₁,rest⟩ := ha.mpr ⟨he, by
+ simpa [Flow.choiceBits_append, List.append_assoc, rest] using hbits⟩
+ have hy : fb pub st r₁ m₁ rest = some ⟨fs,out,mem,tail⟩ := hb.mpr ⟨hf,rfl⟩
+ simp [seqKernel, hx, hy, Output.prepend]
+
+theorem KernelExec.ifEq {a b : Flow r k} {fa fb : Kernel w r k}
+ (l q : Fin r) (ha : KernelExec a fa) (hb : KernelExec b fb) :
+ KernelExec (.ifEq l q a b) (eqKernel l q fa fb) := by
+ intro pub st rs m bits o
+ constructor
+ · intro h
+ unfold eqKernel at h
+ split at h <;> rename_i test <;> obtain ⟨x,hx,rfl⟩ := Option.map_eq_some_iff.mp h
+ · obtain ⟨he,ht⟩ := ha.mp hx
+ exact ⟨.ifEqYes test he, ht⟩
+ · obtain ⟨he,ht⟩ := hb.mp hx
+ exact ⟨.ifEqNo test he, ht⟩
+ · rintro ⟨he, ht⟩
+ cases o with
+ | mk es out mem tail =>
+ cases he with
+ | ifEqYes test he =>
+ have hx : fa pub st rs m bits = some ⟨_,out,mem,tail⟩ := ha.mpr ⟨he,ht⟩
+ simp [eqKernel, test, hx, Output.prepend]
+ | ifEqNo test he =>
+ have hx : fb pub st rs m bits = some ⟨_,out,mem,tail⟩ := hb.mpr ⟨he,ht⟩
+ simp [eqKernel, test, hx, Output.prepend]
+
+/-- The exact node kernel, including the unused suffix and the complete post-state. -/
+theorem node_kernel_iff : KernelExec nodeFlow (nodeKernel (w := w)) :=
+ KernelExec.seq (lines_kernel_exec pop (by decide)) <| KernelExec.ifEq 0 12
+ (KernelExec.seq (guess_kernel_exec _) (lines_kernel_exec leafLines (by decide)))
+ (KernelExec.seq (guess_kernel_exec _) (KernelExec.seq (guess_kernel_exec _)
+ (KernelExec.seq (guess_kernel_exec _) (lines_kernel_exec binaryLines (by decide)))))
+
+/-- A completed node accepts precisely its finite executions that consume the entire tape. -/
+theorem completeNode_iff_exec {pub : Fin 11 → Word w} {st : Word w} {rs : Regs w 16} {m : Memory w}
+ {bits : List Bool} {o : Output w 16} :
+ completeNode pub st rs m bits = some o ↔
+ Flow.Exec pub st nodeFlow rs m o.events o.regs o.mem ∧ bits = choiceBits o.events ∧ o.bits = [] := by
+ rw [completeNode, Option.filter_eq_some_iff, node_kernel_iff]
+ simp only [List.isEmpty_iff]
+ constructor
+ · rintro ⟨⟨he,ht⟩,hb⟩
+ exact ⟨he, by simpa [hb] using ht, hb⟩
+ · rintro ⟨he,ht,hb⟩
+ exact ⟨⟨he,by simpa [hb] using ht⟩,hb⟩
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterKernelExact.lean b/lean/OAI/Computability/VPVNP/PrimedCounterKernelExact.lean
new file mode 100644
index 0000000000..72bd02d99d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterKernelExact.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.PrimedCounterCallPaths
+import OAI.Computability.VPVNP.PrimedStackRAMNodeRun
+
+/-!
+# Observing a bounded kernel through its compiled flow
+
+The standalone accept continuation observes the event log and exact use of the choice tape.
+Returning a designated register observes its final value. External memory is recovered by
+replaying the same log, provided the kernel records its writes faithfully.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedCounter
+
+variable {w r k budget : ℕ} {a : Flow r k} {f : Kernel w r k}
+ {pub : Fin k → Word w} {st : Word w} {rs : Regs w r} {m : Memory w}
+
+/-- A kernel records the actual external-memory effect of each successful run. -/
+def Replays (f : Kernel w r k) : Prop :=
+ ∀ {pub st rs m bits o}, f pub st rs m bits = some o → after m o.events = o.mem
+
+private theorem exit_run (result : Option (Fin r)) (pub : Fin k → Word w) (st : Word w)
+ (rs : Regs w r) (m : Memory w) (bits : List Bool) (fuel : ℕ) :
+ execute ((a.template result).instantiate w pub).program (fuel+1)
+ ⟨a.exitPC,st,rs,fun _ => 0⟩ m bits =
+ if bits = [] then some ⟨[], result.map rs⟩ else none := by
+ cases result <;> cases bits <;>
+ simp [execute, Machine.program, Template.instantiate, Flow.template_exit, Instr.resize, Instr.run]
+
+private theorem Refines.return_run (h : Refines a budget f) (result : Option (Fin r))
+ (pub : Fin k → Word w) (st : Word w) (rs : Regs w r) (m : Memory w)
+ (bits : List Bool) (fuel : ℕ) (hf : budget < fuel) :
+ BurstRAM.execute ((a.template result).instantiate w pub).program fuel ⟨a.pc a.entry,st,rs,fun _ => 0⟩ m bits =
+ (f pub st rs m bits).bind fun o =>
+ if o.bits = [] then some ⟨o.events, result.map o.regs⟩ else none := by
+ let M := (a.template result).instantiate w pub
+ have hb : M.code a.rejectPC = .reject := by
+ simp [M, Template.instantiate, Flow.template_reject, Instr.resize]
+ have hr := h.execute (Flow.template_linked a result pub) hb st rs (fun _ => 0) m bits fuel hf.le
+ rw [hr]
+ change (f pub st rs m bits).bind _ = _
+ cases hs : f pub st rs m bits with
+ | none => rfl
+ | some o =>
+ have hn := h.bounded hs
+ obtain ⟨n, hn⟩ : ∃ n, fuel - o.events.length = n + 1 := ⟨fuel-o.events.length-1, by omega⟩
+ simp only [Option.bind_some, hn, exit_run]
+ split <;> simp_all
+ change (⟨o.events ++ [], _⟩ : Report w) = _
+ simp
+
+/-- On a finite derivation's exact tape, a bounded refining kernel succeeds and returns
+the same events, registers and external memory. -/
+theorem Refines.kernel_of_exec (h : Refines a budget f) (replay : Replays f)
+ {es : List (Event w)} {rs' : Regs w r} {m' : Memory w} (he : Flow.Exec pub st a rs m es rs' m') :
+ f pub st rs m (choiceBits es) = some ⟨es, rs', m', []⟩ := by
+ let fuel := budget + es.length + 1
+ have run (result : Option (Fin r)) :
+ ((f pub st rs m (choiceBits es)).bind fun o =>
+ if o.bits = [] then some (⟨o.events, result.map o.regs⟩ : Report w) else none) =
+ some ⟨es,result.map rs'⟩ := by
+ rw [← h.return_run result pub st rs m _ fuel (by dsimp [fuel]; omega)]
+ exact (Flow.template_execute_iff a result pub st (fun _ => 0) rs m fuel _ _).mpr
+ ⟨rs', m', he, rfl, by dsimp [fuel]; omega, rfl⟩
+ have h₀ := run none
+ cases hx : f pub st rs m (choiceBits es) with
+ | none => simp [hx] at h₀
+ | some x =>
+ have hb : x.bits = [] := by
+ by_contra hn
+ simp [hx, hn] at h₀
+ have hes : x.events = es := by simpa [hx, hb] using h₀
+ have hrs : x.regs = rs' := by
+ funext i
+ have hi := run (some i)
+ simpa [hx, hb, hes] using hi
+ have hm : x.mem = m' := (replay hx).symm.trans (hes ▸ Call.exec_memory he)
+ cases x
+ congr
+
+/-- Exact-use characterization, including rejected tapes. -/
+theorem Refines.kernel_iff_exec (h : Refines a budget f) (replay : Replays f)
+ (bits : List Bool) (es : List (Event w)) (rs' : Regs w r) (m' : Memory w) :
+ f pub st rs m bits = some ⟨es, rs', m', []⟩ ↔
+ Flow.Exec pub st a rs m es rs' m' ∧ bits = choiceBits es := by
+ constructor
+ · intro hx
+ have hr := h.return_run none pub st rs m bits (budget+1) (by omega)
+ simp only [hx, Option.bind_some, ite_true, Option.map_none] at hr
+ obtain ⟨r₁, m₁, he, _, _, hbits⟩ :=
+ (Flow.template_execute_iff a none pub st (fun _ => 0) rs m (budget+1) bits _).mp hr
+ change choiceBits es = bits at hbits
+ have hs := h.kernel_of_exec replay he
+ change f pub st rs m (choiceBits es) = some _ at hs
+ rw [hbits, hx] at hs
+ cases Option.some.inj hs
+ exact ⟨he, hbits.symm⟩
+ · rintro ⟨he,rfl⟩
+ exact h.kernel_of_exec replay he
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterLength.lean b/lean/OAI/Computability/VPVNP/PrimedCounterLength.lean
new file mode 100644
index 0000000000..ae2a918d79
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterLength.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PrimedCounterData
+import OAI.Computability.VPVNP.PrimedCounterDispatchNative
+
+/-!
+# Number of calls in a native pair-counter history
+
+Every successful call returns the next absolute cursor, or accepts at the final
+item. This follows from the code for all five branches, even on arbitrary external
+memory. Consequently a successful history halts exactly at the public call count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedSchedule
+open scoped Fin.CommRing
+
+namespace Dispatch
+
+variable {w A S m nodes T : ℕ} {pub : Program.Pub → Word w}
+
+/-- All five branches preserve the prepared successor and total through the final jump. -/
+theorem native_result (hw : ScheduleWords pub A S m nodes T) (hfit : Cursor.calls A S m nodes T < 2^w)
+ (i : Cursor.Item A S m nodes T) (regs : Regs w 52) (priv : Word w → Word w)
+ (mem : Memory w) (bits : List Bool) (fuel : ℕ) (out : Report w)
+ (hr : NativeAt pub regs priv mem bits fuel out i) :
+ out.result = control w (Cursor.calls A S m nodes T) ((Cursor.index A S m nodes T i).val+1) := by
+ have arm {r p : ℕ} (reg : Fin r ↪ Program.Reg) (port : Fin p → Program.Pub) (small : Flow r p)
+ (hc : branch i = renameFlow reg port small)
+ (hout : (49 : Program.Reg) ∉ Set.range reg ∧ (50 : Program.Reg) ∉ Set.range reg) :
+ out.result = control w (Cursor.calls A S m nodes T) ((Cursor.index A S m nodes T i).val+1) := by
+ obtain ⟨_,_,_,_,_,_,_,hc,_⟩ :=
+ (placed_execute_iff hw hfit i reg port small hc hout regs priv mem bits fuel out).mp hr
+ exact hc
+ rcases i with j | ⟨u,j | j | j⟩ | j
+ · exact arm Program.inputRegs Program.inputPub _ rfl input_outside
+ · exact arm Program.parserRegs Program.parserPub _ rfl parser_outside
+ · exact arm Program.parserRegs Program.parserPub _ rfl parser_outside
+ · exact arm Program.parserRegs Program.stackPub _ rfl parser_outside
+ · exact arm Program.parserRegs Program.parserPub _ rfl parser_outside
+
+end Dispatch
+
+namespace Data
+
+variable {L : Lengths} {w n r H s : ℕ} {Q : Layout L n r H w} (D : Data Q s)
+
+theorem total_pos : 0 < D.total := by
+ have hsites : 0 < 2 * 2^r := by positivity
+ have hspan : 0 < Cursor.span n (2*n-1) := by unfold Cursor.span; omega
+ have := Nat.mul_pos hsites hspan
+ unfold total Cursor.calls
+ omega
+
+private def nativeItem : PrimedSchedule.Item w := fun i m b =>
+ execute D.machine.program D.fuel (D.machine.program.start (cursor w i)) m b
+
+private theorem nativeSchedule (hf : D.Fits) :
+ ScheduleSpec D.machine.program D.fuel D.total D.nativeItem (fun _ _ => True) := by
+ refine ⟨fun _ _ _ _ _ => rfl, ?_⟩
+ intro v hv mem _ bits out he
+ refine ⟨?_,trivial⟩
+ let idx := Cursor.index D.assembly (2*2^r) n (2*n-1) D.labels
+ let i := idx.symm ⟨v,hv⟩
+ have hi : (idx i).val = v := congrArg Fin.val (idx.apply_symm_apply _)
+ have hcur : Dispatch.itemState w i = cursor w v := by
+ change ((idx i).val : Word w) = cursor w v
+ rw [hi, PrimedSchedule.cursor, Fin.ofNat_eq_cast]
+ have hm : D.parserPub (Admin.stackPublic 6) = (n : Word w) := congrFun D.parserPub_stack 6
+ have hwords : Dispatch.ScheduleWords D.pub D.assembly (2*2^r) n (2*n-1) D.labels :=
+ Dispatch.scheduleWords (Opcodes.pubWord Q) D.parserPub hm
+ have hrun : Dispatch.NativeAt D.pub (fun _ => 0) (fun _ => 0) mem bits D.fuel out i := by
+ unfold Dispatch.NativeAt
+ rw [hcur]
+ exact he
+ have hr := Dispatch.native_result hwords hf.cursor i _ _ mem bits D.fuel out hrun
+ change out.result = control w D.total ((idx i).val+1) at hr
+ simpa only [hi] using hr
+
+private theorem first_control : control w D.total 0 = some 0 := by
+ simp [PrimedSchedule.control, D.total_pos, PrimedSchedule.cursor, Fin.ofNat_eq_cast]
+
+private theorem run_eq_items (hf : D.Fits) (m : Memory w) (bs : List (List Bool)) :
+ runSegment D.machine.program D.fuel (some 0) m bs = runItems D.nativeItem D.total 0 m bs := by
+ simpa only [D.first_control] using native_eq_runItems (D.nativeSchedule hf) 0 m trivial bs
+
+/-- A successful partial run halts precisely when its number of supplied call tapes
+equals the public call count. -/
+theorem history_halts_iff (hf : D.Fits) {m : Memory w} {bs : List (List Bool)} {rs : List (Report w)}
+ (hr : runSegment D.machine.program D.fuel (some 0) m bs = some rs) :
+ endState (some 0) rs = none ↔ bs.length = D.total := by
+ rw [D.run_eq_items hf] at hr
+ obtain ⟨_,hle,he⟩ := runItems_progress (D.nativeSchedule hf) 0 m trivial (Nat.zero_le _) hr
+ rw [D.first_control, Nat.zero_add] at he
+ rw [Nat.zero_add] at hle
+ rw [he, PrimedSchedule.control]
+ split <;> rename_i h
+ · simp [Nat.ne_of_lt h]
+ · simp [Nat.le_antisymm hle (Nat.le_of_not_gt h)]
+
+theorem actualPath_length (hf : D.Fits) {m : Memory w} {cap : List (Report w) → Prop}
+ (p : ActualPaths D.machine.program D.fuel 0 m cap) : p.val.length = D.total := by
+ obtain ⟨rs,hr,hh,_⟩ := p.property
+ exact (D.history_halts_iff hf hr).mp hh
+
+/-- Every successful fixed-size tape reaches the accepting state. -/
+theorem history_end (hf : D.Fits) {m : Memory w} {raw : Fin D.total → List Bool} {rs : List (Report w)}
+ (hr : runSegment D.machine.program D.fuel (some 0) m (List.ofFn raw) = some rs) :
+ endState (some 0) rs = none := (D.history_halts_iff hf hr).mpr List.length_ofFn
+
+/-- Read an accepting native history as the unique array of choices at its absolute
+cursors. Reading the array back in order recovers the original history. -/
+noncomputable def historyEquiv (hf : D.Fits) (S K : ℕ) :
+ ActualPaths D.machine.program D.fuel 0 D.initial (withinCaps S K) ≃
+ {raw : Fin D.total → List Bool //
+ ∃ rs, runSegment D.machine.program D.fuel (some 0) D.initial (List.ofFn raw) = some rs ∧
+ withinCaps S K rs} :=
+ (nativeScheduleEquiv (D.nativeSchedule hf) D.total_pos D.initial trivial (withinCaps S K)).trans
+ (Equiv.subtypeEquivRight fun _ => by
+ rw [← D.run_eq_items hf])
+
+end Data
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterNative.lean b/lean/OAI/Computability/VPVNP/PrimedCounterNative.lean
new file mode 100644
index 0000000000..31de2daacb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterNative.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.PrimedCounterInputPrefix
+import OAI.Computability.VPVNP.PrimedCounterLength
+import OAI.Computability.VPVNP.PrimedCounterPostHistory
+
+/-!
+# The exact native path count of the auxiliary RAM
+
+Section 11 realizes the coefficient of the primed pair polynomial on one
+fixed private-RAM instruction table. Each accepting path consists of the
+actual binary choices made at the designated internal endpoints and at the
+ordered parser visits. The full native history satisfies the probe caps
+and ends in an accepting halt.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Data
+
+open BurstRAM PrimedInputRAM PrimedStackRAM
+
+variable {L : Lengths} {n r H s w : ℕ} {Q : Layout L n r H w}
+
+/-- The native run on one complete chronological tape accepts precisely
+when the assembled input bits and the joint production counts pass (9.4).
+The transcript caps admit every such path. -/
+theorem accepts_iff (D : Data Q s) (hf : D.Fits) (S K : ℕ) (hK : 15 ≤ K)
+ (hbudget : 15*D.total ≤ S*K) (raw : Chronology.PairTape n r D.labels) :
+ (∃ rs, runSegment D.machine.program D.fuel (some 0) D.initial (List.ofFn raw) = some rs ∧
+ withinCaps S K rs) ↔ Chronology.Accepts Q D.header D.degree D.root D.nomination raw := by
+ rw [Fold.chronology_iff Q D.header D.degree D.root hf.degree_eq (labelIndex n n s)]
+ change _ ↔ ∃ shared, Chronology.inputPart raw = Chronology.inputCalls Q shared ∧ (D.postLogical shared raw).isSome
+ constructor
+ · rintro ⟨rs,hr,_⟩
+ obtain ⟨shared,he⟩ := InputPrefix.full_recover D hf raw rs hr
+ obtain ⟨front,hsplice,_,_⟩ := InputPrefix.full_splice D hf raw shared he
+ rw [hsplice] at hr
+ obtain ⟨tail,ht,_⟩ := Option.map_eq_some_iff.mp hr
+ exact ⟨shared,he,(D.postRun_isSome hf shared raw).2 (by rw [ht]; rfl)⟩
+ · rintro ⟨shared,he,hok⟩
+ obtain ⟨tail,ht⟩ := Option.isSome_iff_exists.mp ((D.postRun_isSome hf shared raw).1 hok)
+ obtain ⟨front,hsplice,hlen,hfront⟩ := InputPrefix.full_splice D hf raw shared he
+ obtain ⟨_,_,htlen,_,_,htail⟩ := D.postRun_reports hf shared raw tail ht
+ refine ⟨front++tail, by rw [hsplice,ht]; rfl, History.within (bound := 14) ?_ hK ?_⟩
+ · intro rep hrep
+ exact (List.mem_append.mp hrep).elim (hfront rep) (htail rep)
+ · rw [List.length_append, hlen, htlen, D.postItems_length]
+ exact hbudget
+
+/-- Parsimony from complete accepted native paths to the chronological
+tapes recognized by the coefficient counter. -/
+noncomputable def pathEquiv (D : Data Q s) (hf : D.Fits) (S K : ℕ) (hK : 15 ≤ K)
+ (hbudget : 15*D.total ≤ S*K) :
+ ActualPaths D.machine.program D.fuel 0 D.initial (withinCaps S K) ≃
+ {raw : Chronology.PairTape n r D.labels // Chronology.Accepts Q D.header D.degree D.root D.nomination raw} :=
+ (D.historyEquiv hf S K).trans (Equiv.subtypeEquivRight (D.accepts_iff hf S K hK hbudget))
+
+/-- The actual native machine realizes the integer coefficient `f` of
+the primed pair in equation (9.4), with no restrictions on internal bits. -/
+theorem native_count (D : Data Q s) (hf : D.Fits) (S K : ℕ) (hK : 15 ≤ K)
+ (hbudget : 15*D.total ≤ S*K) :
+ (Nat.card (ActualPaths D.machine.program D.fuel 0 D.initial (withinCaps S K)) : ℤ) =
+ (PairCoefficient.jointPolynomial D.degree D.root (PrimedInputRAM.input Q.program Q.fits D.header)).coeff D.nomination := by
+ rw [Nat.card_congr (D.pathEquiv hf S K hK hbudget)]
+ have hn : n ≤ 2^w := (capacity_fit D.base hf.scratch).le
+ exact Chronology.count Q D.header D.degree D.root hf.degree_eq hn hf.states.le D.nomination
+
+end PrimedCounter.Data
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterPostHistory.lean b/lean/OAI/Computability/VPVNP/PrimedCounterPostHistory.lean
new file mode 100644
index 0000000000..484cbad96f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterPostHistory.lean
@@ -0,0 +1,148 @@
+import OAI.Computability.VPVNP.PrimedCounterHistory
+import OAI.Computability.VPVNP.PrimedCounterItemAgreement
+import OAI.Computability.VPVNP.PrimedCounterFoldChronology
+
+/-!
+# Execution of the entire native parser after input assembly
+
+The machine starts with the actual assembled memory and advances one cursor
+slot per clear, root initialization, node visit or histogram comparison. The
+logical and native loops reject together. On success their final histogram,
+mark and stack memories agree, the last report halts, and each call incurs at
+most fourteen probes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Data
+
+open BurstRAM PrimedInputRAM PrimedStackRAM PrimedSchedule
+open scoped Fin.CommRing
+
+variable {L : Lengths} {n r H s w : ℕ} {Q : Layout L n r H w}
+
+/-- The scheduled parser and histogram operations after the two input passes for this pair. -/
+abbrev postItems (D : Data Q s) := Fold.items (2*2^r) n (2*n-1) D.labels
+
+/-- The sequence of private choice lists for the post-assembly operations, read from their
+absolute slots. -/
+def postTape (D : Data Q s) (raw : Chronology.PairTape n r D.labels) : List (List Bool) :=
+ D.postItems.map (fun i => raw (Fold.slot i))
+
+/-- Execute all post-assembly items in the logical parser from empty pending frames, empty
+marks and a zero histogram. -/
+noncomputable def postLogical (D : Data Q s) (shared : Chronology.Bits L r H w)
+ (raw : Chronology.PairTape n r D.labels) : Option (VisitState n n s) :=
+ D.postItems.foldlM (Fold.call w D.degree D.root (Chronology.rowInput Q D.header shared)
+ (labelIndex n n s) D.nomination raw) ⟨[],∅,0⟩
+
+/-- Run the same post-assembly choice lists on the native machine, beginning at the first
+parser cursor with the assembled input memory. -/
+noncomputable def postNative (D : Data Q s) (shared : Chronology.Bits L r H w)
+ (raw : Chronology.PairTape n r D.labels) : Option (List (Report w)) :=
+ runSegment D.machine.program D.fuel (control w D.total D.assembly)
+ (Q.assembled (encodeBit w) shared D.initial) (D.postTape raw)
+
+theorem postItems_length (D : Data Q s) : D.assembly + D.postItems.length = D.total := by
+ have h := congrArg List.length (Fold.items_order D.assembly (2*2^r) n (2*n-1) D.labels)
+ simpa only [List.length_append, List.length_map, List.length_finRange] using h
+
+theorem postTape_append (D : Data Q s) (raw : Chronology.PairTape n r D.labels) :
+ List.ofFn (Chronology.inputPart (A := D.assembly) (S := 2*2^r) (m := n) (K := 2*n-1) (T := D.labels) raw) ++ D.postTape raw = List.ofFn raw := by
+ have h := congrArg (List.map raw) (Fold.items_order D.assembly (2*2^r) n (2*n-1) D.labels)
+ unfold Chronology.inputPart postTape
+ simp only [List.map_append, List.map_map, Function.comp_def] at h
+ simpa only [List.ofFn_eq_map] using h
+
+private def postInv (D : Data Q s) (shared : Chronology.Bits L r H w) (k : ℕ)
+ (st : VisitState n n s) (mem : Memory w) : Prop :=
+ D.Holds shared st mem ∧ leafMass st.pending ≤ n ∧ ∀ a, st.counts a ≤ k
+
+private theorem postStep (D : Data Q s) (hf : D.Fits) (shared : Chronology.Bits L r H w)
+ (raw : Chronology.PairTape n r D.labels) :
+ History.Step D.machine.program D.fuel 14 (Fold.slot (A := D.assembly)) (fun i => raw (Fold.slot i))
+ (Fold.call w D.degree D.root (Chronology.rowInput Q D.header shared) (labelIndex n n s) D.nomination raw)
+ (D.postInv shared) := by
+ intro i st mem hi
+ obtain ⟨held, hm, hb⟩ := hi
+ let pos : Fin D.total := Fold.slot i
+ let logical := Fold.call w D.degree D.root (Chronology.rowInput Q D.header shared)
+ (labelIndex n n s) D.nomination raw
+ let native := execute D.machine.program D.fuel (D.machine.program.start (cursor w pos.val)) mem (raw pos)
+ have ha : ItemAgreement D shared mem (control w D.total (pos.val+1)) (logical st i) native :=
+ D.postItem_agreement hf shared st mem held raw i (fun _ _ _ => ⟨hm, fun a =>
+ ((Nat.add_le_add_right (hb a) 1).trans pos.isLt).trans_lt hf.cursor⟩)
+ change History.Match _ (logical st i) native
+ cases hl : logical st i with
+ | none =>
+ rw [hl] at ha
+ cases hn : native <;> rw [hn] at ha <;> cases ha
+ exact .reject
+ | some next =>
+ rw [hl] at ha
+ cases hn : native with
+ | none => rw [hn] at ha; cases ha
+ | some out =>
+ rw [hn] at ha
+ cases ha with
+ | accept holds _ hp hc =>
+ have hcall : [i].foldlM logical st = some next := by simp [hl]
+ obtain ⟨hm',hb'⟩ := Fold.prefix_bounds D.degree D.root (Chronology.rowInput Q D.header shared)
+ (labelIndex n n s) D.nomination raw st next [i] hm hcall
+ refine .accept ⟨hc,hp,holds,hm',fun a => ?_⟩
+ have hh : [i].countP Fold.isNode ≤ 1 := List.countP_le_length
+ exact (hb' a).trans (Nat.add_le_add (hb a) hh)
+
+private theorem match_mono {α β : Type*} {R R' : α → β → Prop} {a b}
+ (h : History.Match R a b) (f : ∀ x y, R x y → R' x y) : History.Match R' a b := by
+ cases h with
+ | reject => exact .reject
+ | accept h => exact .accept (f _ _ h)
+
+private theorem match_isSome {α β : Type*} {R : α → β → Prop} {a b}
+ (h : History.Match R a b) : a.isSome ↔ b.isSome := by cases h <;> simp
+
+/-- Success and rejection coincide on the entire native suffix. The relation
+records exactly the memory with which the last report leaves the machine. -/
+theorem postRun_match (D : Data Q s) (hf : D.Fits) (shared : Chronology.Bits L r H w)
+ (raw : Chronology.PairTape n r D.labels) :
+ History.Match (fun st rs => rs.length = D.postItems.length ∧
+ endState (control w D.total D.assembly) rs = none ∧
+ D.Holds shared st (after (Q.assembled (encodeBit w) shared D.initial) (eventLog rs)) ∧
+ ∀ r ∈ rs, r.probes ≤ 14)
+ (D.postLogical shared raw) (D.postNative shared raw) := by
+ have ho := History.ordered_after _ _ (Fold.items_order D.assembly (2*2^r) n (2*n-1) D.labels)
+ simp only [List.length_map,List.length_finRange] at ho
+ have hi : D.postInv shared D.assembly ⟨[],∅,0⟩ (Q.assembled (encodeBit w) shared D.initial) :=
+ ⟨D.assembled_holds hf shared, by simp [leafMass], fun _ => Nat.zero_le _⟩
+ have he := History.fold_run D.machine.program D.fuel 14 _ _ _ _ (D.postStep hf shared raw)
+ D.postItems D.assembly ho ⟨[],∅,0⟩ _ hi
+ change History.Match _ (D.postLogical shared raw) (D.postNative shared raw) at he
+ apply match_mono he
+ rintro st rs ⟨hlen,halt,hinv,hprobes⟩
+ rw [D.postItems_length] at halt
+ exact ⟨hlen,by simpa [PrimedSchedule.control] using halt,hinv.1,hprobes⟩
+
+theorem postRun_isSome (D : Data Q s) (hf : D.Fits) (shared : Chronology.Bits L r H w)
+ (raw : Chronology.PairTape n r D.labels) :
+ (D.postLogical shared raw).isSome ↔ (D.postNative shared raw).isSome := by
+ exact match_isSome (D.postRun_match hf shared raw)
+
+theorem postRun_reports (D : Data Q s) (hf : D.Fits) (shared : Chronology.Bits L r H w)
+ (raw : Chronology.PairTape n r D.labels) (rs : List (Report w)) (hr : D.postNative shared raw = some rs) :
+ ∃ st, D.postLogical shared raw = some st ∧ rs.length = D.postItems.length ∧
+ endState (control w D.total D.assembly) rs = none ∧
+ D.Holds shared st (after (Q.assembled (encodeBit w) shared D.initial) (eventLog rs)) ∧
+ ∀ r ∈ rs, r.probes ≤ 14 := by
+ have h := D.postRun_match hf shared raw
+ rw [hr] at h
+ cases hs : D.postLogical shared raw <;> rw [hs] at h <;> cases h
+ exact ⟨_,rfl,by assumption⟩
+
+end PrimedCounter.Data
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterPreorder.lean b/lean/OAI/Computability/VPVNP/PrimedCounterPreorder.lean
new file mode 100644
index 0000000000..abc9b34b1c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterPreorder.lean
@@ -0,0 +1,232 @@
+import OAI.Computability.VPVNP.ParseHistogram
+import Mathlib.Data.List.Nodup
+
+/-!
+# Preorder choices for the coefficient counter
+
+A terminal choice names its input position. The terminal bit comes from that
+position in the assembled word. A binary choice gives the ordered child states
+and their split. Its legal range depends on the pending subtree's degree.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open ParseGrammar
+
+variable {n m : ℕ} {H : Type*}
+
+/-- Branch data at one pending node. The stack determines the required constructor. -/
+inductive Token (m : ℕ) (H : Type*) where
+ | terminal (position : Fin m)
+ | binary (split : ℕ) (leftState rightState : H)
+ deriving DecidableEq
+
+/-- Serialize an ordered parse by visiting the parent before either child. -/
+def preorder {d : ℕ} : OrderedParse (Fin m × Bool) H d → List (Token m H)
+ | .leaf v => [.terminal v.1]
+ | .node b i j left right => .binary b.val i j :: (preorder left ++ preorder right)
+
+@[simp] theorem length_preorder {d : ℕ} (p : OrderedParse (Fin m × Bool) H d) :
+ (preorder p).length = 2 * d + 1 := by
+ induction p with
+ | leaf => rfl
+ | node b _ _ _ _ hl hr =>
+ simp [preorder, hl, hr]
+ have := b.isLt
+ omega
+
+/-- Every terminal of the parse reads the bit in its specified position. -/
+def Agrees (x : Fin m → Bool) {d : ℕ} (p : OrderedParse (Fin m × Bool) H d) : Prop :=
+ ∀ v ∈ p.leaves, v.2 = x v.1
+
+@[simp] theorem agrees_leaf (x : Fin m → Bool) (v : Fin m × Bool) :
+ Agrees x (OrderedParse.leaf (H := H) v) ↔ v.2 = x v.1 := by
+ simp [Agrees, OrderedParse.leaves]
+
+@[simp] theorem agrees_node (x : Fin m → Bool) {d : ℕ} (b : Fin (d + 1)) (i j : H)
+ (left : OrderedParse (Fin m × Bool) H b.val) (right : OrderedParse (Fin m × Bool) H (d - b.val)) :
+ Agrees x (.node b i j left right) ↔ Agrees x left ∧ Agrees x right := by
+ simp [Agrees, OrderedParse.leaves, or_imp, forall_and]
+
+/-- Decode one tree and return the unconsumed choices. -/
+def readTree (x : Fin m → Bool) : (d : ℕ) → List (Token m H) →
+ Option (OrderedParse (Fin m × Bool) H d × List (Token m H))
+ | 0, .terminal j :: more => some (.leaf (j, x j), more)
+ | k + 1, .binary b i j :: more => do
+ if hb : b < k + 1 then
+ let (left, rest) ← readTree x b more
+ let (right, tail) ← readTree x (k - b) rest
+ return (.node ⟨b, hb⟩ i j left right, tail)
+ else none
+ | _, _ => none
+termination_by d _ => d
+decreasing_by all_goals omega
+
+theorem readTree_preorder (x : Fin m → Bool) {d : ℕ} (p : OrderedParse (Fin m × Bool) H d)
+ (hp : Agrees x p) (tail : List (Token m H)) :
+ readTree x d (preorder p ++ tail) = some (p, tail) := by
+ induction p generalizing tail with
+ | leaf v =>
+ rw [agrees_leaf] at hp
+ obtain ⟨j, v⟩ := v
+ change v = x j at hp
+ subst v
+ simp [preorder, readTree]
+ | node b i j left right hl hr =>
+ obtain ⟨hl', hr'⟩ := (agrees_node ..).mp hp
+ simp [preorder, List.append_assoc, readTree, b.isLt, hl hl', hr hr']
+
+theorem readTree_sound (x : Fin m → Bool) (d : ℕ) (ts : List (Token m H))
+ (p : OrderedParse (Fin m × Bool) H d) (tail : List (Token m H))
+ (hr : readTree x d ts = some (p, tail)) :
+ Agrees x p ∧ ts = preorder p ++ tail := by
+ induction d using Nat.strong_induction_on generalizing ts tail with
+ | h d ih =>
+ cases d with
+ | zero =>
+ cases ts with
+ | nil => simp [readTree] at hr
+ | cons t more =>
+ cases t with
+ | binary => simp [readTree] at hr
+ | terminal j =>
+ simp [readTree] at hr
+ obtain ⟨rfl, rfl⟩ := hr
+ simp [preorder]
+ | succ k =>
+ cases ts with
+ | nil => simp [readTree] at hr
+ | cons t more =>
+ cases t with
+ | terminal => simp [readTree] at hr
+ | binary b i j =>
+ by_cases hb : b < k + 1
+ · cases hl : readTree x b more with
+ | none => simp [readTree, hb, hl] at hr
+ | some l =>
+ obtain ⟨left, rest⟩ := l
+ cases hright : readTree x (k - b) rest with
+ | none => simp [readTree, hb, hl, hright] at hr
+ | some r =>
+ obtain ⟨right, endBits⟩ := r
+ simp [readTree, hb, hl, hright] at hr
+ obtain ⟨rfl, rfl⟩ := hr
+ obtain ⟨h₁, e₁⟩ := ih b hb more left rest hl
+ obtain ⟨h₂, e₂⟩ := ih (k - b) (by omega) rest right endBits hright
+ simp [h₁, h₂, preorder, e₁, e₂, List.append_assoc]
+ · simp [readTree, hb] at hr
+
+/-- Leaf locations encountered by the mark array, in visitation order. -/
+def positions (ts : List (Token m H)) : List (Fin m) :=
+ ts.filterMap fun
+ | .terminal j => some j
+ | .binary .. => none
+
+@[simp] theorem positions_preorder {d : ℕ} (p : OrderedParse (Fin m × Bool) H d) :
+ positions (preorder p) = p.leaves.map Prod.fst := by
+ induction p with
+ | leaf => rfl
+ | node b i j l r hl hr =>
+ simpa [positions, preorder, OrderedParse.leaves, List.filterMap_append] using
+ congrArg₂ List.append hl hr
+
+private theorem agrees_of_bijection (x : Fin m → Bool) {d : ℕ} (p : OrderedParse (Fin m × Bool) H d)
+ (e : LeafBijection p.leaves (fun j => (j, x j))) : Agrees x p := by
+ intro v hv
+ obtain ⟨i, rfl⟩ := List.mem_iff_get.mp hv
+ rw [e.property i]
+
+private theorem marks_of_bijection {d : ℕ} (p : OrderedParse (Fin m × Bool) H d)
+ (x : Fin m → Bool) (e : LeafBijection p.leaves (fun j => (j, x j))) :
+ (positions (preorder p)).Nodup := by
+ rw [positions_preorder, List.nodup_iff_injective_getElem]
+ intro i j he
+ let i' : Fin p.leaves.length := ⟨i.val, by simpa using i.isLt⟩
+ let j' : Fin p.leaves.length := ⟨j.val, by simpa using j.isLt⟩
+ have he' : e.val i' = e.val j' := by
+ have hx := congrArg Prod.fst (e.property i')
+ have hy := congrArg Prod.fst (e.property j')
+ refine hx.symm.trans ((Eq.trans ?_ hy))
+ simpa [i', j', List.get_eq_getElem] using he
+ exact Fin.ext (congrArg (fun a : Fin p.leaves.length => a.val) (e.val.injective he'))
+
+private noncomputable def bijectionOfMarks {d : ℕ} (hsize : d + 1 = m)
+ (p : OrderedParse (Fin m × Bool) H d) (x : Fin m → Bool) (ha : Agrees x p)
+ (hn : (positions (preorder p)).Nodup) : LeafBijection p.leaves (fun j => (j, x j)) := by
+ let loc (i : Fin p.leaves.length) := (p.leaves.get i).1
+ have hb : Function.Bijective loc := by
+ apply (Fintype.bijective_iff_injective_and_card loc).2
+ refine ⟨?_, by simp [hsize]⟩
+ rw [positions_preorder, List.nodup_iff_injective_getElem] at hn
+ intro i j hij
+ apply Fin.ext
+ let i' : Fin (p.leaves.map Prod.fst).length := ⟨i.val, by simpa using i.isLt⟩
+ let j' : Fin (p.leaves.map Prod.fst).length := ⟨j.val, by simpa using j.isLt⟩
+ exact congrArg (fun a : Fin (p.leaves.map Prod.fst).length => a.val) (@hn i' j' (by simpa [loc, i', j', List.get_eq_getElem] using hij))
+ refine ⟨Equiv.ofBijective loc hb, fun i => Prod.ext rfl ?_⟩
+ exact ha _ (List.get_mem ..)
+
+/-- Complete decoder with the distinct-position check used by the counter.
+The computation returns the unique decoded parse and rejects trailing tokens. -/
+def checkedTree (x : Fin m → Bool) (d : ℕ) (ts : List (Token m H)) :
+ Option (OrderedParse (Fin m × Bool) H d) := do
+ let (p, tail) ← readTree x d ts
+ if tail.isEmpty && decide (positions ts).Nodup then return p else none
+
+theorem checkedTree_eq_some_iff (x : Fin m → Bool) {d : ℕ} (ts : List (Token m H))
+ (p : OrderedParse (Fin m × Bool) H d) :
+ checkedTree x d ts = some p ↔
+ Agrees x p ∧ ts = preorder p ∧ (positions ts).Nodup := by
+ constructor
+ · intro h
+ cases hr : readTree x d ts with
+ | none => simp [checkedTree, hr] at h
+ | some v =>
+ obtain ⟨q, tail⟩ := v
+ simp [checkedTree, hr] at h
+ obtain ⟨⟨rfl, hn⟩, rfl⟩ := h
+ obtain ⟨ha, he⟩ := readTree_sound x d ts q [] hr
+ exact ⟨ha, by simpa using he, hn⟩
+ · rintro ⟨ha, rfl, hn⟩
+ have hr := readTree_preorder x p ha []
+ rw [List.append_nil] at hr
+ simp [positions_preorder] at hn
+ simp [checkedTree, hr, hn]
+
+/-- Accepting token lists retain every ordered parse and its unique matching
+leaf bijection. The two domain sizes agree since the parse has exactly one
+leaf per bit of the input. -/
+noncomputable def choiceEquiv (d : Fin n) (hsize : d.val + 1 = m) (x : Fin m → Bool) :
+ {ts : List (Token m H) // (checkedTree x d.val ts).isSome} ≃ ParseChoice H d x where
+ toFun t := by
+ let p := (checkedTree x d.val t.val).get t.property
+ have he : checkedTree x d.val t.val = some p := (Option.some_get _).symm
+ have hs := (checkedTree_eq_some_iff ..).1 he
+ exact ⟨p, bijectionOfMarks hsize p x hs.1 (hs.2.1 ▸ hs.2.2)⟩
+ invFun a := ⟨preorder a.1, by
+ rw [(checkedTree_eq_some_iff x _ a.1).2
+ ⟨agrees_of_bijection x a.1 a.2, rfl, marks_of_bijection a.1 x a.2⟩]
+ rfl⟩
+ left_inv t := by
+ apply Subtype.ext
+ exact ((checkedTree_eq_some_iff ..).1 (Option.some_get t.property).symm).2.1.symm
+ right_inv a := by
+ have hs := (checkedTree_eq_some_iff x _ a.1).2
+ ⟨agrees_of_bijection x a.1 a.2, rfl, marks_of_bijection a.1 x a.2⟩
+ have he : (checkedTree x d.val (preorder a.1)).get (by simp [hs]) = a.1 :=
+ Option.some.inj ((Option.some_get _).trans hs)
+ apply Sigma.ext he
+ have := LeafBijection.subsingleton_of_injective a.1.leaves
+ (q := fun j : Fin m => (j, x j)) (fun _ _ h => congrArg Prod.fst h)
+ exact heq_of_eqRec_eq (congrArg (fun t => LeafBijection t.leaves (fun j => (j, x j))) he)
+ (Subsingleton.elim _ _)
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterProgram.lean b/lean/OAI/Computability/VPVNP/PrimedCounterProgram.lean
new file mode 100644
index 0000000000..4f982efe5b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterProgram.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.PrimedCounterAdmin
+import OAI.Computability.VPVNP.PrimedCounterCall
+import OAI.Computability.VPVNP.PrimedCounterCursor
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodes
+import OAI.Computability.VPVNP.PrimedInputRAMPortCode
+
+/-!
+# Fixed native program for one primed pair
+
+The absolute cursor is tested against the end of the two input rectangles,
+then against the end of the site parses. In a site block, division computes
+the row and remainder distinguishes a mark clear, root initialization, or
+node visit. The final region reads and compares one histogram entry per call.
+Four private registers hold the cursor, its successor, the call count, and a
+phase boundary outside the operand ranges of the embedded routines.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Program
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+/-- Structured control flow for the combined counter using 52 private registers and 34 public
+operands. -/
+abbrev Code := PrimedInputRAM.Flow 52 34
+/-- Register indices in the combined counter, including the four registers reserved beyond the
+input assembler. -/
+abbrev Reg := Fin 52
+/-- Indices of the input, parser and schedule operands in the combined public-word vector. -/
+abbrev Pub := Fin 34
+
+/-- Identify each of the 48 input-assembler registers with the same-numbered combined register. -/
+def inputReg (i : Fin 48) : Reg := i.castAdd 4
+/-- Identify each of the sixteen parser registers with the same-numbered combined register. -/
+def parserReg (i : Fin 16) : Reg := i.castAdd 36
+/-- Place the sixteen assembler operands at the beginning of the combined public-word vector. -/
+def inputPub (i : Fin 16) : Pub := i.castAdd 18
+/-- Place the fourteen parser operands after the assembler operands in the combined public-word
+vector. -/
+def parserPub (i : Fin 14) : Pub := (i.castAdd 4).natAdd 16
+/-- Address a stack-parser operand through the parser's block in the combined public-word
+vector. -/
+def stackPub (i : Fin 11) : Pub := parserPub (Admin.stackPublic i)
+
+/-- Injective register placement used to link the input-assembly code into the combined
+counter. -/
+def inputRegs : Fin 48 ↪ Reg := ⟨inputReg, fun _ _ h => Fin.ext (congrArg (fun j : Reg => j.val) h)⟩
+/-- Injective register placement used to link the parser and its administrative routines into
+the combined counter. -/
+def parserRegs : Fin 16 ↪ Reg := ⟨parserReg, fun _ _ h => Fin.ext (congrArg (fun j : Reg => j.val) h)⟩
+
+/-- The whole body is finite and independent of every pair-specific header. -/
+def input : Code := renameFlow inputReg inputPub (Opcodes.dataCall PortCode.program)
+/-- The grammar-node visit routine installed on the combined registers and stack-parser
+operands. -/
+def node : Code := renameFlow parserReg stackPub nodeFlow
+/-- The mark-clearing routine installed in the combined parser code. -/
+def clear : Code := renameFlow parserReg parserPub Admin.clear
+/-- The root-frame initialization routine installed in the combined parser code. -/
+def init : Code := renameFlow parserReg parserPub Admin.init
+/-- The nominated-versus-accumulated production count check installed in the combined parser
+code. -/
+def compare : Code := renameFlow parserReg parserPub Admin.compare
+
+/-- Register 51 contains the end of the assembly calls on entering this block.
+The quotient is the zero-based row number and the remainder is the in-row cursor. -/
+def rowSetup : List (Op 52 34) :=
+ [.binary .sub 18 48 51, .publicWord 19 31, .binary .div 20 18 19,
+ .binary .mod 21 18 19, .publicWord 22 (stackPub 6)]
+
+/-- Decode the site and local slot from the cursor and invoke mark clearing, root setup or the
+grammar-node visit. -/
+def site : Code := .seq (lines rowSetup (by decide)) <|
+ .ifLt 21 22 (.seq (.line (.copy 2 21)) clear) <|
+ .ifEq 21 22 init (.seq (.line (.binary .mul 5 20 22)) node)
+
+/-- Dispatch post-assembly cursors to a site parse or, after the site region ends, a histogram
+comparison. -/
+def afterInputs : Code := .seq (.line (.publicWord 17 32)) <|
+ .ifLt 48 17 site (.seq (.line (.binary .sub 7 48 17)) compare)
+
+/-- Load the current cursor from persistent state, compute its successor and read the total and
+input-assembly boundaries. -/
+def dispatchSetup : List (Op 52 34) :=
+ [.stateWord 48, .constant 51 1, .binary .add 49 48 51, .publicWord 50 33, .publicWord 51 30]
+
+/-- Execute one scheduled counter call by dispatching its absolute cursor to the input or
+post-assembly code. -/
+def body : Code := .seq (lines dispatchSetup (by decide)) (.ifLt 48 51 input afterInputs)
+
+/-- A single table is instantiated at every `n`, degree/state range, group pair
+and nomination. It returns register 49, or accepts when that equals register 50. -/
+def table := Call.template body 49 50
+
+/-- Operand table for the common program. Input parameters, parser parameters,
+and four schedule bounds occupy consecutive fixed slots. -/
+def publicWords {w : ℕ} (inputs : Fin 16 → Word w) (parser : Fin 14 → Word w)
+ (assembly S m nodes T : ℕ) : Pub → Word w :=
+ Fin.append inputs (Fin.append parser
+ ![(assembly : Word w), (Cursor.span m nodes : Word w), (Cursor.compareStart assembly S m nodes : Word w),
+ (Cursor.calls assembly S m nodes T : Word w)])
+
+theorem public_input {w : ℕ} (inputs : Fin 16 → Word w) (parser : Fin 14 → Word w)
+ (A S m nodes T : ℕ) (i : Fin 16) : publicWords inputs parser A S m nodes T (inputPub i) = inputs i :=
+ Fin.append_left ..
+
+theorem public_parser {w : ℕ} (inputs : Fin 16 → Word w) (parser : Fin 14 → Word w)
+ (A S m nodes T : ℕ) (i : Fin 14) : publicWords inputs parser A S m nodes T (parserPub i) = parser i := by
+ rw [publicWords, parserPub, Fin.append_right, Fin.append_left]
+
+theorem public_schedule {w : ℕ} (inputs : Fin 16 → Word w) (parser : Fin 14 → Word w)
+ (A S m nodes T : ℕ) :
+ let pub := publicWords inputs parser A S m nodes T
+ pub 30 = (A : Word w) ∧ pub 31 = (Cursor.span m nodes : Word w) ∧
+ pub 32 = (Cursor.compareStart A S m nodes : Word w) ∧ pub 33 = (Cursor.calls A S m nodes T : Word w) := by
+ dsimp only
+ have hh (j : Fin 4) : publicWords inputs parser A S m nodes T ((j.natAdd 14).natAdd 16) =
+ (![(A : Word w), ↑(Cursor.span m nodes), ↑(Cursor.compareStart A S m nodes),
+ ↑(Cursor.calls A S m nodes T)] : Fin 4 → Word w) j := by
+ rw [publicWords, Fin.append_right, Fin.append_right]
+ exact ⟨hh 0, hh 1, hh 2, hh 3⟩
+
+theorem table_literalWidth : table.literalWidth = 2 := rfl
+
+end PrimedCounter.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterRename.lean b/lean/OAI/Computability/VPVNP/PrimedCounterRename.lean
new file mode 100644
index 0000000000..1b8d0901c4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterRename.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowRun
+
+/-!
+# Register and public-word placement for the pair counter
+
+The input passes and the preorder parser use their own local operand numbers.
+Relabeling the operands embeds each finite block into the common auxiliary
+machine. A native write to a register still has exactly the specified effect
+on the embedded register file.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM
+
+variable {r k R K w : ℕ}
+
+/-- Relocate both operand spaces of a native instruction. -/
+def renameOp (reg : Fin r → Fin R) (pub : Fin k → Fin K) : Op r k → Op R K
+ | .constant dst v => .constant (reg dst) v
+ | .publicWord dst i => .publicWord (reg dst) (pub i)
+ | .copy dst src => .copy (reg dst) (reg src)
+ | .stateWord dst => .stateWord (reg dst)
+ | .binary op dst x y => .binary op (reg dst) (reg x) (reg y)
+ | .read dst a => .read (reg dst) (reg a)
+ | .write a s => .write (reg a) (reg s)
+ | .guardEq x y => .guardEq (reg x) (reg y)
+ | .guardLt x y => .guardLt (reg x) (reg y)
+
+private theorem restrict_update (rs : Regs w R) (reg : Fin r ↪ Fin R) (dst : Fin r) (v : Word w) :
+ (Function.update rs (reg dst) v) ∘ reg = Function.update (rs ∘ reg) dst v := by
+ funext i
+ by_cases hi : i = dst <;> simp [hi, Function.comp_apply]
+
+/-- Restricting the updated large register file gives the same operation as
+executing directly on the small register file. Reads, writes, guard failures
+and the emitted RAM event agree exactly. -/
+theorem effect_rename (reg : Fin r ↪ Fin R) (pub : Fin k → Fin K) (op : Op r k)
+ (data : Fin K → Word w) (state : Word w) (rs : Regs w R) (mem : Memory w) :
+ ((renameOp reg pub op).effect data state rs mem).map (fun (e,r',m') => (e,r' ∘ reg,m')) =
+ op.effect (data ∘ pub) state (rs ∘ reg) mem := by
+ cases op <;> simp [renameOp, Op.effect, restrict_update, Function.comp_apply]
+
+/-- Relabel the operands of an entire structured graph, preserving its branch
+order and all of its loop back edges. -/
+def renameFlow (reg : Fin r → Fin R) (pub : Fin k → Fin K) : Flow r k → Flow R K
+ | .line op => .line (renameOp reg pub op)
+ | .seq a b => .seq (renameFlow reg pub a) (renameFlow reg pub b)
+ | .ifEq x y a b => .ifEq (reg x) (reg y) (renameFlow reg pub a) (renameFlow reg pub b)
+ | .ifLt x y a b => .ifLt (reg x) (reg y) (renameFlow reg pub a) (renameFlow reg pub b)
+ | .branch a b => .branch (renameFlow reg pub a) (renameFlow reg pub b)
+ | .whileLt x y a => .whileLt (reg x) (reg y) (renameFlow reg pub a)
+
+theorem rename_length (reg : Fin r → Fin R) (pub : Fin k → Fin K) (a : Flow r k) :
+ (renameFlow reg pub a).length = a.length := by
+ induction a <;> simp_all [renameFlow, Flow.length]
+
+/-- Instruction labels are transported according to their enclosing blocks. -/
+def renameLabels (reg : Fin r → Fin R) (pub : Fin k → Fin K) :
+ (a : Flow r k) → a.Label ≃ (renameFlow reg pub a).Label
+ | .line _ => Equiv.refl Unit
+ | .seq a b => (renameLabels reg pub a).sumCongr (renameLabels reg pub b)
+ | .ifEq _ _ a b | .ifLt _ _ a b | .branch a b =>
+ (Equiv.refl Unit).sumCongr ((renameLabels reg pub a).sumCongr (renameLabels reg pub b))
+ | .whileLt _ _ a => (Equiv.refl Unit).sumCongr (renameLabels reg pub a)
+
+theorem rename_entry (reg : Fin r → Fin R) (pub : Fin k → Fin K) (a : Flow r k) :
+ renameLabels reg pub a a.entry = (renameFlow reg pub a).entry := by
+ induction a with
+ | seq a b ha _ => exact congrArg Sum.inl ha
+ | _ => rfl
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterRenameRun.lean b/lean/OAI/Computability/VPVNP/PrimedCounterRenameRun.lean
new file mode 100644
index 0000000000..ada57c1fe0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterRenameRun.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.PrimedCounterRename
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-!
+# Executing embedded parser and assembly programs
+
+Relocating operands preserves the complete event sequence and external memory
+of every successful structured execution. This allows the uniform assembly
+and traversal codes to share one private register file.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open BurstRAM PrimedStackRAM PrimedInputRAM
+
+variable {w r k R K : ℕ}
+
+/-- One relocated opcode can only write an embedded register. -/
+private theorem line_outside (reg : Fin r ↪ Fin R) (pub : Fin k → Fin K) (op : Op r k)
+ (data : Fin K → Word w) (state : Word w) (rs : Regs w R) (mem : Memory w)
+ {e out m'} (he : (renameOp reg pub op).effect data state rs mem = some (e,out,m'))
+ (j : Fin R) (hj : j ∉ Set.range reg) : out j = rs j := by
+ have hn (i : Fin r) : j ≠ reg i := fun hh => hj ⟨i, hh.symm⟩
+ cases op <;> simp only [renameOp, Op.effect] at he
+ all_goals first | split at he | skip
+ all_goals first | contradiction | (cases Option.some.inj he; simp [Function.update_of_ne (hn _)])
+
+/-- Lift a finite small-register computation to the enclosing register space.
+All unrelated enclosing registers retain their prior values. -/
+theorem liftExec (reg : Fin r ↪ Fin R) (pub : Fin k → Fin K) (data : Fin K → Word w)
+ {state : Word w} {a : Flow r k} {small m es out m'}
+ (he : Flow.Exec (data ∘ pub) state a small m es out m')
+ (rs : Regs w R) (hr : rs ∘ reg = small) :
+ ∃ rs', Flow.Exec data state (renameFlow reg pub a) rs m es rs' m' ∧
+ rs' ∘ reg = out ∧ ∀ j, j ∉ Set.range reg → rs' j = rs j := by
+ induction he generalizing rs with
+ | @line op small m e small' m' h =>
+ subst small
+ have hx := (effect_rename reg pub op data state rs m).trans h
+ obtain ⟨⟨ev, rs', m''⟩, hh, heq⟩ := Option.map_eq_some_iff.mp hx
+ obtain ⟨rfl, heq, rfl⟩ := Prod.mk.inj heq
+ exact ⟨rs', .line hh, rfl, line_outside reg pub op data state rs m hh⟩
+ | seq _ _ ih₁ ih₂ =>
+ obtain ⟨mid, hm, he, ho⟩ := ih₁ rs hr
+ obtain ⟨out, hrun, he', ho'⟩ := ih₂ mid he
+ exact ⟨out, .seq hm hrun, he', fun j hj => (ho' j hj).trans (ho j hj)⟩
+ | ifEqYes ht _ ih | ifEqNo ht _ ih | ifLtYes ht _ ih | ifLtNo ht _ ih =>
+ obtain ⟨out, ho, he, hh⟩ := ih rs hr
+ subst_vars
+ first | exact ⟨out, .ifEqYes ht ho, rfl, hh⟩ | exact ⟨out, .ifEqNo ht ho, rfl, hh⟩
+ | exact ⟨out, .ifLtYes ht ho, rfl, hh⟩ | exact ⟨out, .ifLtNo ht ho, rfl, hh⟩
+ | branchYes _ ih =>
+ obtain ⟨out, ho, he, hh⟩ := ih rs hr
+ exact ⟨out, .branchYes ho, he, hh⟩
+ | branchNo _ ih =>
+ obtain ⟨out, ho, he, hh⟩ := ih rs hr
+ exact ⟨out, .branchNo ho, he, hh⟩
+ | whileDone ht =>
+ subst_vars
+ exact ⟨rs, .whileDone ht, rfl, fun _ _ => rfl⟩
+ | whileStep ht _ _ ih₁ ih₂ =>
+ obtain ⟨mid, hb, he, ho⟩ := ih₁ rs hr
+ obtain ⟨out, hrun, he', ho'⟩ := ih₂ mid he
+ rw [← hr] at ht
+ exact ⟨out, .whileStep ht hb hrun, he', fun j hj => (ho' j hj).trans (ho j hj)⟩
+
+/-- Conversely, every successful enclosing execution restricts to a genuine
+execution of the original program. Both directions include the exact event log. -/
+theorem restrictExec (reg : Fin r ↪ Fin R) (pub : Fin k → Fin K) (data : Fin K → Word w)
+ {state : Word w} (a : Flow r k) {rs m es out m'}
+ (he : Flow.Exec data state (renameFlow reg pub a) rs m es out m') :
+ Flow.Exec (data ∘ pub) state a (rs ∘ reg) m es (out ∘ reg) m' ∧
+ ∀ j, j ∉ Set.range reg → out j = rs j := by
+ generalize hcmd : renameFlow reg pub a = cmd at he
+ induction he generalizing a with
+ | @line op rs m e out m' h =>
+ cases a <;> simp only [renameFlow, reduceCtorEq, Flow.line.injEq] at hcmd
+ subst op
+ constructor
+ · apply Flow.Exec.line
+ rw [← effect_rename reg pub _ data state rs m, h]
+ rfl
+ · exact line_outside reg pub _ data state rs m h
+ | seq _ _ ih₁ ih₂ =>
+ cases a <;> simp only [renameFlow, reduceCtorEq, Flow.seq.injEq] at hcmd
+ obtain ⟨ha, hb⟩ := hcmd
+ obtain ⟨h₁, o₁⟩ := ih₁ _ ha
+ obtain ⟨h₂, o₂⟩ := ih₂ _ hb
+ exact ⟨.seq h₁ h₂, fun j hj => (o₂ j hj).trans (o₁ j hj)⟩
+ | ifEqYes ht _ ih | ifEqNo ht _ ih | ifLtYes ht _ ih | ifLtNo ht _ ih =>
+ cases a <;> simp only [renameFlow, reduceCtorEq, Flow.ifEq.injEq, Flow.ifLt.injEq] at hcmd
+ obtain ⟨rfl, rfl, ha, hb⟩ := hcmd
+ first
+ | obtain ⟨h, ho⟩ := ih _ ha; exact ⟨.ifEqYes ht h, ho⟩
+ | obtain ⟨h, ho⟩ := ih _ hb; exact ⟨.ifEqNo ht h, ho⟩
+ | obtain ⟨h, ho⟩ := ih _ ha; exact ⟨.ifLtYes ht h, ho⟩
+ | obtain ⟨h, ho⟩ := ih _ hb; exact ⟨.ifLtNo ht h, ho⟩
+ | branchYes _ ih | branchNo _ ih =>
+ cases a <;> simp only [renameFlow, reduceCtorEq, Flow.branch.injEq] at hcmd
+ obtain ⟨ha, hb⟩ := hcmd
+ first
+ | obtain ⟨h, ho⟩ := ih _ ha; exact ⟨.branchYes h, ho⟩
+ | obtain ⟨h, ho⟩ := ih _ hb; exact ⟨.branchNo h, ho⟩
+ | whileDone ht =>
+ cases a <;> simp only [renameFlow, reduceCtorEq, Flow.whileLt.injEq] at hcmd
+ obtain ⟨rfl, rfl, _⟩ := hcmd
+ exact ⟨.whileDone ht, fun _ _ => rfl⟩
+ | whileStep ht _ _ ih₁ ih₂ =>
+ cases a <;> simp only [renameFlow, reduceCtorEq, Flow.whileLt.injEq] at hcmd
+ obtain ⟨rfl, rfl, rfl⟩ := hcmd
+ obtain ⟨h₁, o₁⟩ := ih₁ _ rfl
+ obtain ⟨h₂, o₂⟩ := ih₂ (.whileLt _ _ _) rfl
+ exact ⟨.whileStep ht h₁ h₂, fun j hj => (o₂ j hj).trans (o₁ j hj)⟩
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterResources.lean b/lean/OAI/Computability/VPVNP/PrimedCounterResources.lean
new file mode 100644
index 0000000000..636e79459e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterResources.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.PrimedCounterResourcesSpace
+import OAI.Computability.VPVNP.PrimedCounterResourcesWork
+import OAI.Computability.VPVNP.PrimedInputRAMResources
+import OAI.Computability.VPVNP.PrimedCounterCursor
+
+/-!
+# Simultaneous resource bounds for the scheduled primed pair parser
+
+For every sufficiently large length the same choice of address multiplier
+works for every pair and every grammar whose dense histogram has at most
+the prescribed polynomial size. The work bound includes the absolute-cursor
+dispatch. The external budget includes all clear, initialize, visit and
+comparison calls as well as the two input passes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Resources
+
+open BurstRAM CursorBounds PrimedInputRAM PrimedStackRAM Filter Compression
+
+/-- Exact absolute call count and private instruction allowance of a pair. -/
+def callCount (B n states : ℕ) := 10 * processorCount B n * n + labelCount n n states
+
+/-- Uniform per-call instruction budget, taking the larger of the assembler's address-scan
+bound and the parser's word-processing bound. -/
+def privateFuel (B n : ℕ) :=
+ max (Opcodes.nativeFuel (addressWidth B n) + 20) (12 * CursorBounds.wordBits B n + 110)
+
+/-- Capacity inequalities for scratch storage, parser indices, the absolute cursor and the
+private instruction clock at a chosen input length and address multiplier. -/
+structure Bounds (B n grammarStates scratchBase : ℕ) : Prop where
+ scratch : scratchBase + PrimedInputRAM.positions n (addressWidth B n) +
+ size (processorCount B n) n n (labelCount n n grammarStates) ≤ 2 ^ CursorBounds.wordBits B n
+ triangle : n * n ≤ 2 ^ CursorBounds.wordBits B n
+ states : grammarStates < 2 ^ CursorBounds.wordBits B n
+ labels : labelCount n n grammarStates ≤ processorCount B n
+ cursor : callCount B n grammarStates < 2 ^ CursorBounds.wordBits B n
+ component : 2 * processorCount B n * (2*n-1) < 2 ^ (2 * addressWidth B n)
+ componentWord : 2 ^ (2 * addressWidth B n) ≤ 2 ^ CursorBounds.wordBits B n
+ privateWork : 6 * privateFuel B n ≤ n^10
+ perCall : 15 ≤ 2 ^ roundedUp 1 4 n
+ total : 15 * callCount B n grammarStates ≤ 2 ^ virtualBits B n * 2 ^ roundedUp 1 4 n
+
+/-- The calls counted by the absolute cursor use the exact budget above. -/
+theorem callCount_eq (B n states : ℕ) (hn : 0 < n) :
+ Cursor.calls (2 * PrimedInputRAM.positions n (addressWidth B n)) (2 * processorCount B n)
+ n (2*n-1) (labelCount n n states) = callCount B n states :=
+ Cursor.calls_pair (processorCount B n) n (labelCount n n states) hn
+
+/-- The virtual bucket budget covers every group pair, including endpoint
+pairs with an empty exterior cut. The returned layout uses the live word width. -/
+theorem eventually_layouts (p : UniversalMachine.Program) (a d₁ d₂ C B : ℕ)
+ (hB : max (max (a+1) (a+d₂)) (max d₁ C) + 2 ≤ B) {δ : ℝ} (hδ : 0 < δ) (hδ' : δ ≤ 1) :
+ ∀ᶠ n : ℕ in atTop, ∀ i : Fin (2^(n^a-1)), ∀ states, labelCount n n states ≤ n^C →
+ let L := PairedChain.lengths (n^a-1) (n^d₂) (n^d₁) i
+ ∃ Q : Layout L n (addressWidth B n) (liveBucket δ n) (CursorBounds.wordBits B n),
+ Q.program = p ∧ Q.scratchBase = 2^(virtualBits B n) ∧
+ Header.count L + labelCount n n states ≤ Q.scratchBase ∧ Opcodes.ParameterFit Q ∧
+ Bounds B n states Q.scratchBase := by
+ filter_upwards [eventually_physicalLayouts p a d₁ d₂ C B hB hδ hδ', eventually_privateWork B,
+ eventually_virtualBucket_ge 15, eventually_pairExternalBudget B 150, eventually_ge_atTop 5]
+ with n hQ hw hK htotal hn
+ intro i states hT
+ obtain ⟨Q,hp,hs,hh,hparams,_,_,_⟩ := hQ i (labelCount n n states) hT
+ have ht := labels_le_processors (B := B) (by omega : C ≤ B) (by omega) hT
+ obtain ⟨hspace,hcursor,htri,hword⟩ := space (B := B) (by omega) (by omega) ht
+ have hsize : labelCount n n states < 2 ^ CursorBounds.wordBits B n := by omega
+ have hb := htotal (labelCount n n states) ht
+ refine ⟨Q,hp,hs,hs ▸ hh,hparams,?_⟩
+ rw [hs]
+ refine ⟨hspace, by simpa only [pow_two] using htri, states_fit (by omega) hsize, ht,
+ hcursor, pairLabels_lt (by omega) hn, hword, hw, hK, ?_⟩
+ unfold callCount
+ rw [Nat.mul_assoc 10]
+ omega
+
+end PrimedCounter.Resources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterResourcesData.lean b/lean/OAI/Computability/VPVNP/PrimedCounterResourcesData.lean
new file mode 100644
index 0000000000..12747333d8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterResourcesData.lean
@@ -0,0 +1,63 @@
+import OAI.Computability.VPVNP.PrimedCounterResources
+import OAI.Computability.VPVNP.PrimedCounterData
+
+/-!
+# Instantiating the primed parser with the paper's word widths
+
+Each nomination component has the paper's two-address-width encoding. The
+private words in the parser also hold the absolute cursor and triangular index.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Resources
+
+open BurstRAM CursorBounds PrimedInputRAM PrimedStackRAM Compression
+
+variable {B n states : ℕ} {δ : ℝ} {L : Lengths}
+variable {Q : Layout L n (addressWidth B n) (liveBucket δ n) (CursorBounds.wordBits B n)}
+
+/-- The scheduled body uses the absolute cursor counted in the numerical bounds. -/
+theorem data_total (D : Data Q states) : D.total = callCount B n states := by
+ have hn : 0 < n := (Nat.zero_le D.degree.val).trans_lt D.degree.isLt
+ change Cursor.calls (_ + _) _ _ _ _ = _
+ rw [← two_mul]
+ exact callCount_eq B n states hn
+
+/-- The actual private and external budgets of the instantiated pair call. -/
+theorem Bounds.dataBudget (h : Bounds B n states Q.scratchBase) (D : Data Q states) :
+ 6 * D.fuel ≤ n^10 ∧ 15 * D.total ≤ 2 ^ virtualBits B n * 2 ^ roundedUp 1 4 n := by
+ rw [data_total D]
+ exact ⟨h.privateWork, h.total⟩
+
+/-- A histogram component bounded by the entire traversal can still be
+incremented without wrapping a parser word. -/
+theorem Bounds.increment (h : Bounds B n states Q.scratchBase) {v : ℕ}
+ (hv : v ≤ 2 * processorCount B n * (2*n-1)) :
+ v + 1 < 2 ^ CursorBounds.wordBits B n := by
+ have hbit : 2 * addressWidth B n < CursorBounds.wordBits B n := by
+ change 2 * addressWidth B n < (addressWidth B n + 10)^4
+ calc
+ _ < (addressWidth B n + 10)^2 := by nlinarith [Nat.zero_le (addressWidth B n * addressWidth B n)]
+ _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide)
+ exact (Nat.succ_le_of_lt (hv.trans_lt h.component)).trans_lt (Nat.pow_lt_pow_right (by decide) hbit)
+
+/-- Assemble all hypotheses needed for concrete instruction correctness. -/
+theorem Bounds.dataFits (h : Bounds B n states Q.scratchBase) (D : Data Q states)
+ (hparams : Opcodes.ParameterFit Q) (hd : D.degree.val + 1 = n)
+ (hh : Header.count L + D.labels ≤ Q.scratchBase)
+ (hnom : ∀ a, D.nomination a < 2 ^ (2 * addressWidth B n)) : D.Fits := by
+ have hword : 2 < 2 ^ CursorBounds.wordBits B n := by
+ change 2^1 < 2^((addressWidth B n + 10)^4)
+ apply Nat.pow_lt_pow_right (by decide)
+ exact Nat.one_lt_pow (by decide) (by omega)
+ exact ⟨hparams, hd, hh, h.scratch, h.states, hword, by simpa only [pow_two] using h.triangle,
+ (data_total D) ▸ h.cursor, fun a => (hnom a).trans_le h.componentWord⟩
+
+end PrimedCounter.Resources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterResourcesSpace.lean b/lean/OAI/Computability/VPVNP/PrimedCounterResourcesSpace.lean
new file mode 100644
index 0000000000..c8dc9844db
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterResourcesSpace.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.PrimedInputRAMCapacity
+import OAI.Computability.VPVNP.PrimedStackRAMMemory
+
+/-!
+# Word addresses for the entire primed parser
+
+After the two input passes, the parser keeps its frames, marks, histogram
+and depth word beyond the output rectangle. The same word width fits the
+absolute call cursor and every partial histogram component.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Resources
+
+open BurstRAM CursorBounds PrimedInputRAM PrimedStackRAM
+
+/-- The live processor count absorbs the fixed histogram degree bound. -/
+theorem labels_le_processors {B C n t : ℕ} (hB : C ≤ B) (hn : 0 < n) (ht : t ≤ n^C) :
+ t ≤ processorCount B n := by
+ calc
+ t ≤ n^B := ht.trans (Nat.pow_le_pow_right hn hB)
+ _ ≤ (2^(Nat.clog 2 n))^B := Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) n) _
+ _ = processorCount B n := by
+ rw [← pow_mul, Nat.mul_comm]
+ rfl
+
+/-- Simultaneous address-space bounds at the paper's virtual scratch base. -/
+theorem space {B n t : ℕ} (hB : 1 ≤ B) (hn : 1 ≤ n) (ht : t ≤ processorCount B n) :
+ let r := addressWidth B n
+ let R := processorCount B n
+ let w := CursorBounds.wordBits B n
+ 2^(virtualBits B n) + positions n r + size R n n t ≤ 2^w ∧
+ 10*R*n + t < 2^w ∧ n^2 ≤ 2^w ∧ 2^(2*r) ≤ 2^w := by
+ let r := addressWidth B n
+ let R := processorCount B n
+ let P := 2^(3*r)
+ have hc : Nat.clog 2 n ≤ r := Nat.le_mul_of_pos_left _ hB
+ have hD : virtualBits B n ≤ 3*r := by
+ have h := virtualBits_le B n
+ rw [Nat.add_mul] at h
+ change Nat.clog 2 n ≤ B * Nat.clog 2 n at hc
+ change _ ≤ 3*(B * Nat.clog 2 n)
+ omega
+ have hS : 2^(virtualBits B n) ≤ P := Nat.pow_le_pow_right (by decide) hD
+ have hword : 3*r+4 ≤ (r+10)^4 := by
+ calc
+ 3*r+4 ≤ (r+10)^2 := by nlinarith [Nat.zero_le (r*r)]
+ _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide)
+ have hroom : P*16 ≤ 2^(CursorBounds.wordBits B n) := by
+ have h := Nat.pow_le_pow_right (by decide : 0 < 2) hword
+ rw [pow_add] at h
+ exact h
+ have hnR : n ≤ R := (Nat.le_pow_clog (by decide) n).trans (Nat.pow_le_pow_right (by decide) hc)
+ have hR2 : R * R = 2^(2*r) := by
+ change 2^r * 2^r = 2^(2*r)
+ rw [← pow_add, two_mul]
+ have hP2 : R * R ≤ P := hR2 ▸ (Nat.pow_le_pow_right (by decide : 0<2) (by omega : 2*r ≤ 3*r))
+ have hRn : R*n ≤ P := (Nat.mul_le_mul_left _ hnR).trans hP2
+ have hR : R ≤ P := (Nat.le_mul_of_pos_right _ hn).trans hRn
+ have hnn : n*n ≤ P := (Nat.mul_le_mul_right _ hnR).trans hRn
+ have hP : 0 < P := Nat.two_pow_pos _
+ change _ + positions n r + size R n n t ≤ _ ∧ 10*R*n+t < _ ∧ n^2 ≤ _ ∧ _
+ have hpos : positions n r = 2*(R*n) := by unfold positions; rw [Nat.mul_assoc]; rfl
+ rw [hpos, size, pow_two, ← hR2, Nat.mul_assoc 2 R n, Nat.mul_assoc 10 R n]
+ change t ≤ R at ht
+ omega
+
+/-- Each parser state occurs in a terminal production, so the state bound
+also fits when the dense production array fits. -/
+theorem states_fit {n H w : ℕ} (hn : 1 ≤ n) (ht : labelCount n n H < 2^w) : H < 2^w := by
+ have hmul : H ≤ H*n := Nat.le_mul_of_pos_right _ hn
+ unfold labelCount at ht
+ omega
+
+end PrimedCounter.Resources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterResourcesWork.lean b/lean/OAI/Computability/VPVNP/PrimedCounterResourcesWork.lean
new file mode 100644
index 0000000000..832665869e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterResourcesWork.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.CursorBounds
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeExecutionLayout
+
+/-!
+# Private work of the scheduled pair counter
+
+The two input passes use the live address width, and the parser's word guesses use
+fourth powers of that width. For a fixed address multiplier their dispatched costs
+both fit the auxiliary machine's per-call private-work budget at large lengths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Resources
+
+open Filter BurstRAM PrimedInputRAM.Opcodes
+
+/-- The `n^10` private-work bound includes six elementary operations per instruction
+and the fixed dispatch overhead of the full coefficient counter. -/
+theorem eventually_privateWork (B : ℕ) :
+ ∀ᶠ n : ℕ in atTop, 6 * max (nativeFuel (addressWidth B n) + 20)
+ (12 * CursorBounds.wordBits B n + 110) ≤ n^10 := by
+ filter_upwards [eventually_ge_atTop (B+10), eventually_ge_atTop (6*197)] with n hB hcost
+ have hn : 1 ≤ n := by omega
+ have hlog : Nat.clog 2 n ≤ n := (Nat.clog_le_iff_le_pow Nat.one_lt_two).mpr Nat.lt_two_pow_self.le
+ have hwidth : addressWidth B n + 10 ≤ n^2 := calc
+ addressWidth B n + 10 ≤ B*n + 10*n :=
+ Nat.add_le_add (Nat.mul_le_mul_left B hlog) (Nat.le_mul_of_pos_right 10 hn)
+ _ = (B+10)*n := (Nat.add_mul ..).symm
+ _ ≤ n^2 := by simpa [pow_two] using Nat.mul_le_mul_right n hB
+ have hw : CursorBounds.wordBits B n ≤ n^8 := by
+ simpa only [CursorBounds.wordBits, CursorBounds.addressBits, ← pow_mul] using Nat.pow_le_pow_left hwidth 4
+ have hr := hwidth.trans (Nat.pow_le_pow_right hn (by decide : 2 ≤ 8))
+ have hpow : 1 ≤ n^8 := Nat.one_le_pow _ _ hn
+ calc
+ 6 * max _ _ ≤ 6 * (197*n^8) := by
+ apply Nat.mul_le_mul_left 6 (max_le _ _)
+ · unfold nativeFuel
+ omega
+ · omega
+ _ = (6*197)*n^8 := (Nat.mul_assoc ..).symm
+ _ ≤ n*n^8 := Nat.mul_le_mul_right _ hcost
+ _ = n^9 := (pow_succ' n 8).symm
+ _ ≤ n^10 := Nat.pow_le_pow_right hn (by decide)
+
+end PrimedCounter.Resources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterSiteLoop.lean b/lean/OAI/Computability/VPVNP/PrimedCounterSiteLoop.lean
new file mode 100644
index 0000000000..4f28185c11
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterSiteLoop.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.PrimedCounterVisit
+import Mathlib.Data.List.FinRange
+
+/-!
+# Accumulating all primed sites in one histogram
+
+Every site gets its own empty mark array and its prescribed root frame. The
+histogram passes from one site to the next. After the last site, comparing
+the entire array against the nomination accepts precisely the binary tapes
+whose joint production count equals the nominated histogram.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open ParseGrammar
+open scoped Classical
+
+variable {n m s w : ℕ} {Site : Type*}
+
+/-- Ordered complete site parses, with only the histogram shared between them. -/
+noncomputable def runSites (w : ℕ) (d : Fin n) (root : Fin s) (x : Site → Fin m → Bool)
+ (bs : Site → List (List Bool)) :
+ List Site → (Label n m (Fin s) →₀ ℕ) → Option (Label n m (Fin s) →₀ ℕ)
+ | [], initial => some initial
+ | v :: more, initial => do
+ let st ← visits w (x v) ⟨[(d,root)], ∅, initial⟩ (bs v)
+ runSites w d root x bs more st.counts
+
+/-- Any site reached by a complete successful execution passes its own
+mark and tree checks, even if the incoming histogram is nonzero. -/
+theorem runSites_local (hn : n ≤ 2^w) (hm : m ≤ 2^w) (hs : s ≤ 2^w)
+ (d : Fin n) (root : Fin s) (x : Site → Fin m → Bool) (bs : Site → List (List Bool))
+ (rows : List Site) {initial final : Label n m (Fin s) →₀ ℕ}
+ (he : runSites w d root x bs rows initial = some final) (v : Site) (hv : v ∈ rows) :
+ ∃ ts, decodeVisits w (x v) [(d,root)] (bs v) = some ts ∧ (positions ts).Nodup := by
+ induction rows generalizing initial with
+ | nil => simp at hv
+ | cons u more ih =>
+ cases hrun : visits w (x u) ⟨[(d,root)], ∅, initial⟩ (bs u) with
+ | none => simp [runSites, hrun] at he
+ | some next =>
+ rcases List.mem_cons.mp hv with rfl | ht
+ · exact (visits_accepts (x v) d root initial (bs v) hn hm hs).1 (by rw [hrun]; rfl)
+ · exact ih (by simpa [runSites, hrun] using he) ht
+
+/-- Along arbitrary accepted branch tapes, the online shared histogram sums
+the per-site increments in visit order. -/
+theorem runSites_paths (hn : n ≤ 2^w) (hm : m ≤ 2^w) (hs : s ≤ 2^w)
+ (d : Fin n) (root : Fin s) (x : Site → Fin m → Bool) (b : (v : Site) → SitePaths w (x v) d root)
+ (rows : List Site) (initial : Label n m (Fin s) →₀ ℕ) :
+ runSites w d root x (fun v => (b v).val) rows initial =
+ some (initial + (rows.map (fun v => siteHistogram hm hs hn (x v) d root (b v))).sum) := by
+ induction rows generalizing initial with
+ | nil => simp [runSites]
+ | cons v rows ih =>
+ obtain ⟨marks, hrun⟩ := visits_counts (x v) d root initial (b v) hn hm hs
+ simp [runSites, hrun, ih, add_assoc]
+
+/-- At the final site every dense histogram component must agree with its
+nomination. The linear comparison consumes no binary choice. -/
+noncomputable def compareAll {T : ℕ} (values nominated : Fin T → ℕ) : Bool :=
+ (List.finRange T).all (fun j => decide (values j = nominated j))
+
+theorem compareAll_iff {T : ℕ} (values nominated : Fin T → ℕ) :
+ compareAll values nominated = true ↔ values = nominated := by
+ simp [compareAll, funext_iff]
+
+/-- Each accepted site consumes exactly one word-choice list at each of
+its `2*d+1` preorder visits. -/
+theorem sitePaths_length (hn : n ≤ 2^w) (hm : m ≤ 2^w) (hs : s ≤ 2^w)
+ (x : Fin m → Bool) (d : Fin n) (root : Fin s) (b : SitePaths w x d root) :
+ b.val.length = 2*d.val + 1 := by
+ obtain ⟨hd, hmark⟩ := chosenTokens_spec x d root b
+ obtain ⟨hb, hsc⟩ := decodeVisits_sound hm hs hn _ _ _ _ hd
+ have he := scan_root x d root (chosenTokens x d root b)
+ cases hr : readTree x d.val (chosenTokens x d root b) with
+ | none => simp [he, hr] at hsc
+ | some v =>
+ obtain ⟨p, tail⟩ := v
+ obtain ⟨ha, ht⟩ := readTree_sound _ _ _ _ _ hr
+ cases tail with
+ | nil => simp [hb, ht]
+ | cons t ts => simp [he, hr] at hsc
+
+/-- Convert a path to its fixed-length array of per-node choice lists. -/
+def siteArray (hn : n ≤ 2^w) (hm : m ≤ 2^w) (hs : s ≤ 2^w)
+ (x : Fin m → Bool) (d : Fin n) (root : Fin s) (b : SitePaths w x d root) :
+ Fin (2*d.val+1) → List Bool := fun i => b.val[i.val]'(by rw [sitePaths_length hn hm hs x d root b]; exact i.isLt)
+
+theorem ofFn_siteArray (hn : n ≤ 2^w) (hm : m ≤ 2^w) (hs : s ≤ 2^w)
+ (x : Fin m → Bool) (d : Fin n) (root : Fin s) (b : SitePaths w x d root) :
+ List.ofFn (siteArray hn hm hs x d root b) = b.val := by
+ apply List.ext_getElem (List.length_ofFn.trans (sitePaths_length hn hm hs x d root b).symm)
+ intros
+ simp only [List.getElem_ofFn, siteArray]
+
+/-- The actual loop over the rows, restricted by the final full histogram
+comparison, is parsimonious with the site path model. -/
+noncomputable def siteLoopEquiv {S : ℕ} (hn : n ≤ 2^w) (hm : m ≤ 2^w) (hs : s ≤ 2^w)
+ (d : Fin n) (root : Fin s) (x : Fin S → Fin m → Bool) (μ : Label n m (Fin s) →₀ ℕ) :
+ {raw : Fin S → Fin (2*d.val+1) → List Bool //
+ runSites w d root x (fun v => List.ofFn (raw v)) (List.finRange S) 0 = some μ} ≃
+ {b : (v : Fin S) → SitePaths w (x v) d root //
+ ∑ v, siteHistogram hm hs hn (x v) d root (b v) = μ} where
+ toFun raw := by
+ let b (v : Fin S) : SitePaths w (x v) d root :=
+ ⟨List.ofFn (raw.val v), runSites_local hn hm hs d root x _ _ raw.property v (by simp)⟩
+ refine ⟨b, ?_⟩
+ have he := (runSites_paths hn hm hs d root x b (List.finRange S) 0).symm.trans raw.property
+ simpa [← List.ofFn_eq_map, List.sum_ofFn] using Option.some.inj he
+ invFun b := by
+ let raw (v : Fin S) := siteArray hn hm hs (x v) d root (b.val v)
+ refine ⟨raw, ?_⟩
+ simp only [raw, ofFn_siteArray]
+ rw [runSites_paths hn hm hs d root x b.val, zero_add]
+ simpa [← List.ofFn_eq_map, List.sum_ofFn] using congrArg some b.property
+ left_inv raw := by apply Subtype.ext; funext i j; simp only [siteArray, List.getElem_ofFn]
+ right_inv b := by
+ apply Subtype.ext
+ funext v
+ apply Subtype.ext
+ exact ofFn_siteArray hn hm hs (x v) d root (b.val v)
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterStack.lean b/lean/OAI/Computability/VPVNP/PrimedCounterStack.lean
new file mode 100644
index 0000000000..c4b97fdd5a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterStack.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.PrimedCounterPreorder
+
+/-!
+# Stack execution of the primed parser
+
+At each visit the machine pops the pending frame, produces one histogram label,
+and pushes zero or two frames. The left child is visited first. The executable
+scan below agrees with recursive tree decoding for every continuation stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open ParseGrammar
+
+variable {n m : ℕ} {H : Type*}
+
+/-- One pending grammar node represented by its bounded degree index and nonterminal state. -/
+abbrev Frame (n : ℕ) (H : Type*) := Fin n × H
+/-- A production histogram key for either a terminal position and bit or a binary split with
+its parent and child states. -/
+abbrev Label (n m : ℕ) (H : Type*) := GrammarLabel (Fin m × Bool) H n
+
+/-- Pop one frame. The emitted label identifies the counter to increment, and
+the replacement frames are prepended to the remaining stack. -/
+def step (x : Fin m → Bool) : Frame n H → Token m H → Option (Label n m H × List (Frame n H))
+ | (⟨0, _⟩, h), .terminal j => some (.inl (h, j, x j), [])
+ | (⟨k + 1, hk⟩, h), .binary b i j =>
+ if hb : b < k + 1 then
+ let d : Fin n := ⟨k + 1, hk⟩
+ let split : Fin d.val := ⟨b, hb⟩
+ some (.inr ⟨d, h, split, i, j⟩, [(leftDegree d split, i), (rightDegree d split, j)])
+ else none
+ | _, _ => none
+
+/-- Execute the flat stream of node choices. Completion requires exhausting
+both the input stream and the pending stack at the same visit. -/
+def scan (x : Fin m → Bool) : List (Frame n H) → List (Token m H) → Option (List (Label n m H))
+ | [], [] => some []
+ | [], _ :: _ | _ :: _, [] => none
+ | f :: stack, t :: ts => do
+ let (a, children) ← step x f t
+ let rest ← scan x (children ++ stack) ts
+ return a :: rest
+
+/-- The production labels of a tree in visit order. -/
+def labels (d : Fin n) (h : H) (p : OrderedParse (Fin m × Bool) H d.val) : List (Label n m H) :=
+ match d, p with
+ | ⟨0, _⟩, .leaf v => [.inl (h, v)]
+ | ⟨k + 1, hk⟩, .node b i j l r =>
+ let deg : Fin n := ⟨k + 1, hk⟩
+ .inr ⟨deg, h, b, i, j⟩ :: (labels (leftDegree deg b) i l ++ labels (rightDegree deg b) j r)
+termination_by d.val
+decreasing_by all_goals first | exact leftDegree_lt _ _ | exact rightDegree_lt _ _
+
+/-- The integer counter vector formed by adding one for each visit. -/
+noncomputable def tally (as : List (Label n m H)) : Label n m H →₀ ℕ :=
+ (as.map (fun a => Finsupp.single a 1)).sum
+
+@[simp] theorem tally_append (as bs : List (Label n m H)) : tally (as ++ bs) = tally as + tally bs := by
+ simp [tally]
+
+theorem tally_labels (d : Fin n) (h : H) (p : OrderedParse (Fin m × Bool) H d.val) :
+ tally (labels d h p) = histogram d h p := by
+ induction d using (measure (fun d : Fin n => d.val)).wf.induction generalizing h with
+ | h d ih =>
+ obtain ⟨k, hk⟩ := d
+ cases k with
+ | zero =>
+ cases p
+ simp [labels, histogram, tally]
+ | succ k =>
+ cases p with
+ | node b i j l r =>
+ let d : Fin n := ⟨k + 1, hk⟩
+ rw [labels, histogram]
+ change Finsupp.single (.inr ⟨d, h, b, i, j⟩) 1 +
+ tally (labels (leftDegree d b) i l ++ labels (rightDegree d b) j r) = _
+ rw [tally_append, ih _ (leftDegree_lt d b) i l, ih _ (rightDegree_lt d b) j r]
+ exact (add_assoc ..).symm
+
+/-- Unrolling one root in a continuation stack consumes exactly one encoded
+tree. This also handles malformed or truncated inputs and unused trailing choices. -/
+theorem scan_cons (x : Fin m → Bool) (d : Fin n) (h : H) (stack : List (Frame n H))
+ (ts : List (Token m H)) :
+ scan x ((d, h) :: stack) ts =
+ ((readTree x d.val ts).bind fun (p, tail) =>
+ (scan x stack tail).map (fun rest => labels d h p ++ rest)) := by
+ induction d using (measure (fun d : Fin n => d.val)).wf.induction generalizing h stack ts with
+ | h d ih =>
+ obtain ⟨k, hk⟩ := d
+ cases ts with
+ | nil => cases k <;> simp [scan, readTree]
+ | cons t more =>
+ cases k with
+ | zero =>
+ cases t with
+ | binary => simp [scan, step, readTree]
+ | terminal j =>
+ cases hh : scan x stack more <;> simp [scan, step, readTree, labels, hh]
+ | succ k =>
+ cases t with
+ | terminal => simp [scan, step, readTree]
+ | binary b i j =>
+ by_cases hb : b < k + 1
+ · let d : Fin n := ⟨k + 1, hk⟩
+ let b' : Fin d.val := ⟨b, hb⟩
+ have hl := ih (leftDegree d b') (leftDegree_lt d b') i
+ ((rightDegree d b', j) :: stack) more
+ have hr := ih (rightDegree d b') (rightDegree_lt d b') j stack
+ cases hh₁ : readTree x b more with
+ | none =>
+ simp [leftDegree, hh₁, d, b'] at hl
+ simp [scan, step, readTree, hb, hh₁, hl, leftDegree]
+ | some v =>
+ obtain ⟨l, rest⟩ := v
+ cases hh₂ : readTree x (k - b) rest with
+ | none =>
+ specialize hr rest
+ simp [rightDegree, d, b', hh₂] at hr
+ simp [leftDegree, d, b', hh₁, hr, rightDegree] at hl
+ simp [scan, step, readTree, hb, hh₁, hh₂, hl, leftDegree, rightDegree]
+ | some v =>
+ obtain ⟨r, tail⟩ := v
+ specialize hr rest
+ simp [rightDegree, d, b', hh₂] at hr
+ simp [leftDegree, d, b', hh₁, hr, rightDegree] at hl
+ cases ht : scan x stack tail <;>
+ simp_all [scan, step, readTree, labels, leftDegree, rightDegree, List.append_assoc]
+ · simp [scan, step, readTree, hb]
+
+/-- An empty continuation stack cannot accept trailing choices. -/
+theorem scan_nil (x : Fin m → Bool) (ts : List (Token m H)) :
+ scan (n := n) x [] ts = if ts = [] then some [] else none := by cases ts <;> rfl
+
+/-- Complete traversal from the prescribed root emits exactly the labels of
+the unique parse recovered from this list of choices. -/
+theorem scan_root (x : Fin m → Bool) (d : Fin n) (h : H) (ts : List (Token m H)) :
+ scan x [(d,h)] ts = ((readTree x d.val ts).bind fun (p, tail) =>
+ if tail.isEmpty then some (labels d h p) else none) := by
+ rw [scan_cons]
+ cases hr : readTree x d.val ts with
+ | none => rfl
+ | some v =>
+ obtain ⟨p, tail⟩ := v
+ cases tail <;> simp [scan]
+
+/-- Linear mark checks and the stack traversal have the same acceptance
+predicate as the recursive reader; every accepted tree supplies its histogram. -/
+theorem scan_marked (x : Fin m → Bool) (d : Fin n) (h : H) (ts : List (Token m H)) :
+ (if (positions ts).Nodup then (scan x [(d,h)] ts).map tally else none) =
+ (checkedTree x d.val ts).map (histogram d h) := by
+ rw [scan_root]
+ cases hr : readTree x d.val ts with
+ | none => simp [checkedTree, hr]
+ | some v =>
+ obtain ⟨p, tail⟩ := v
+ cases tail <;> by_cases hn : (positions ts).Nodup <;> simp [checkedTree, hr, hn, tally_labels]
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterStackBounds.lean b/lean/OAI/Computability/VPVNP/PrimedCounterStackBounds.lean
new file mode 100644
index 0000000000..35d09825a7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterStackBounds.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.PrimedCounterTraces
+
+/-!
+# Scratch capacity during the preorder traversal
+
+The pending frames partition the still unread leaves. Their total leaf count
+cannot increase, even if the path is later rejected for repeated positions.
+Replacing a pending internal frame by its children decreases the number of
+nodes still to visit by exactly one. These bounds apply after every prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open ParseGrammar
+variable {n m : ℕ} {H : Type*}
+
+/-- Unvisited leaves represented by the pending subtree roots. -/
+def leafMass (stack : List (Frame n H)) := (stack.map fun f => f.1.val + 1).sum
+
+/-- Nodes remaining in those subtrees, including their pending roots. -/
+def pendingNodes (stack : List (Frame n H)) := (stack.map fun f => 2*f.1.val + 1).sum
+
+private theorem length_le_mass (stack : List (Frame n H)) : stack.length ≤ leafMass stack := by
+ induction stack with
+ | nil => rfl
+ | cons f stack ih =>
+ change stack.length + 1 ≤ f.1.val + 1 + leafMass stack
+ omega
+
+theorem step_bounds (x : Fin m → Bool) (f : Frame n H) (t : Token m H)
+ (a : Label n m H) (children stack : List (Frame n H)) (hs : step x f t = some (a, children)) :
+ leafMass (children ++ stack) ≤ leafMass (f :: stack) ∧
+ pendingNodes (children ++ stack) + 1 = pendingNodes (f :: stack) := by
+ obtain ⟨⟨k, hk⟩, h⟩ := f
+ cases k with
+ | zero =>
+ cases t with
+ | binary => simp [step] at hs
+ | terminal j =>
+ simp [step] at hs
+ obtain ⟨rfl, rfl⟩ := hs
+ simp [leafMass, pendingNodes, Nat.add_comm]
+ | succ k =>
+ cases t with
+ | terminal => simp [step] at hs
+ | binary b i j =>
+ by_cases hb : b < k+1
+ · simp [step, hb] at hs
+ obtain ⟨rfl, rfl⟩ := hs
+ simp [leafMass, pendingNodes, leftDegree, rightDegree]
+ omega
+ · simp [step, hb] at hs
+
+/-- Executing a prefix may leave pending subtrees for the next visit. -/
+def advance (x : Fin m → Bool) : List (Frame n H) → List (Token m H) → Option (List (Frame n H))
+ | stack, [] => some stack
+ | [], _ :: _ => none
+ | f :: stack, t :: ts => do
+ let (_, children) ← step x f t
+ advance x (children ++ stack) ts
+
+/-- Prefix accounting includes malformed paths until their first failed step. -/
+theorem advance_bounds (x : Fin m → Bool) (stack : List (Frame n H)) (ts : List (Token m H))
+ (out : List (Frame n H)) (hs : advance x stack ts = some out) :
+ leafMass out ≤ leafMass stack ∧ ts.length + pendingNodes out = pendingNodes stack := by
+ induction ts generalizing stack with
+ | nil => simp [advance] at hs; subst out; simp
+ | cons t ts ih =>
+ cases stack with
+ | nil => simp [advance] at hs
+ | cons f stack =>
+ cases h : step x f t with
+ | none => simp [advance, h] at hs
+ | some v =>
+ obtain ⟨a, children⟩ := v
+ simp [advance, h] at hs
+ obtain ⟨h₁, h₂⟩ := ih _ hs
+ obtain ⟨b₁, b₂⟩ := step_bounds x f t a children stack h
+ exact ⟨h₁.trans b₁, by simp only [List.length_cons]; omega⟩
+
+/-- A stack plane of one word per possible leaf suffices at every prefix.
+In particular no rejected path accesses an additional frame. -/
+theorem root_bounds (x : Fin m → Bool) (d : Fin n) (h : H) (ts : List (Token m H))
+ (out : List (Frame n H)) (hr : advance x [(d,h)] ts = some out) :
+ out.length ≤ d.val + 1 ∧ ts.length ≤ 2*d.val + 1 := by
+ obtain ⟨h₁, h₂⟩ := advance_bounds x [(d,h)] ts out hr
+ simp only [leafMass, pendingNodes, List.map_singleton, List.sum_singleton] at h₁ h₂
+ exact ⟨(length_le_mass out).trans h₁, h₂ ▸ Nat.le_add_right ..⟩
+
+/-- Test and set the mark of each selected leaf. A fresh parse begins with
+all marks cleared. -/
+def testMarks : Finset (Fin m) → List (Token m H) → Option (Finset (Fin m))
+ | marked, [] => some marked
+ | marked, .terminal j :: more => if j ∈ marked then none else testMarks (insert j marked) more
+ | marked, .binary .. :: more => testMarks marked more
+
+theorem testMarks_eq_some_iff (marked : Finset (Fin m)) (ts : List (Token m H))
+ (out : Finset (Fin m)) : testMarks marked ts = some out ↔
+ (positions ts).Nodup ∧ (∀ j ∈ positions ts, j ∉ marked) ∧ out = marked ∪ (positions ts).toFinset := by
+ induction ts generalizing marked with
+ | nil => simp [testMarks, positions, eq_comm]
+ | cons t ts ih =>
+ cases t with
+ | binary => simpa [testMarks, positions] using ih marked
+ | terminal j =>
+ by_cases hj : j ∈ marked
+ · simp [testMarks, positions, hj]
+ · simp only [testMarks, hj, ↓reduceIte, ih, positions, List.filterMap_cons, List.nodup_cons,
+ List.mem_cons, List.toFinset_cons, Finset.mem_insert, not_or, forall_and, or_imp]
+ simp only [Finset.insert_union, Finset.union_insert]
+ aesop
+
+/-- The linear test-and-set loop implements the decoder's position check. -/
+theorem freshMarks_iff (ts : List (Token m H)) : (testMarks ∅ ts).isSome ↔ (positions ts).Nodup := by
+ rw [Option.isSome_iff_exists]
+ simp [testMarks_eq_some_iff]
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterTraces.lean b/lean/OAI/Computability/VPVNP/PrimedCounterTraces.lean
new file mode 100644
index 0000000000..314f4b71da
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterTraces.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.PrimedCounterBits
+import OAI.Computability.VPVNP.PairCoefficient
+
+/-!
+# The multiplicity of accepting binary preorder traces
+
+For each assignment of the internal primed bits, each site supplies one binary
+choice list for every node call. Marking repeated positions and comparing the
+sum of the emitted histograms with the nomination gives the integer coefficient
+of the primed pair polynomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open ParseGrammar
+open scoped Classical
+
+variable {n m s w : ℕ} {Site Internal : Type*}
+
+private theorem marked_iff (x : Fin m → Bool) (d : Fin n) (h : Fin s)
+ (ts : List (Token m (Fin s))) :
+ (scan x [(d,h)] ts).isSome ∧ (positions ts).Nodup ↔ (checkedTree x d.val ts).isSome := by
+ have he := congrArg Option.isSome (scan_marked x d h ts)
+ by_cases hn : (positions ts).Nodup <;> simpa [hn] using Bool.eq_iff_iff.mp he
+
+/-- Branch tapes accepted by one parse's stack and mark checks. -/
+abbrev SitePaths (w : ℕ) (x : Fin m → Bool) (d : Fin n) (h : Fin s) :=
+ {bs : List (List Bool) // ∃ ts, decodeVisits w x [(d,h)] bs = some ts ∧ (positions ts).Nodup}
+
+/-- Recover the node selections from the consumed binary branches. -/
+def chosenTokens (x : Fin m → Bool) (d : Fin n) (h : Fin s) (b : SitePaths w x d h) :
+ List (Token m (Fin s)) :=
+ (decodeVisits w x [(d,h)] b.val).get (by
+ obtain ⟨ts, he, _⟩ := b.property
+ simp [he])
+
+theorem chosenTokens_spec (x : Fin m → Bool) (d : Fin n) (h : Fin s) (b : SitePaths w x d h) :
+ decodeVisits w x [(d,h)] b.val = some (chosenTokens x d h b) ∧ (positions (chosenTokens x d h b)).Nodup := by
+ have he : decodeVisits w x [(d,h)] b.val = some (chosenTokens x d h b) := (Option.some_get _).symm
+ refine ⟨he, ?_⟩
+ obtain ⟨ts, hr, hn⟩ := b.property
+ rwa [Option.some.inj (he.symm.trans hr)]
+
+/-- Fixed-width branching preserves the exact multiplicity of token streams. -/
+def bitTraceEquiv (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w)
+ (x : Fin m → Bool) (d : Fin n) (h : Fin s) :
+ SitePaths w x d h ≃ {ts : List (Token m (Fin s)) // (checkedTree x d.val ts).isSome} where
+ toFun b := ⟨chosenTokens x d h b, by
+ obtain ⟨hd, hm'⟩ := chosenTokens_spec x d h b
+ exact (marked_iff x d h _).1 ⟨(decodeVisits_sound hm hs hn _ _ _ _ hd).2, hm'⟩⟩
+ invFun t := ⟨t.val.map (encodeToken w), by
+ obtain ⟨hsc, hm'⟩ := (marked_iff x d h _).2 t.property
+ exact ⟨t.val, decodeVisits_encode hm hs hn _ _ _ hsc, hm'⟩⟩
+ left_inv b := Subtype.ext (decodeVisits_sound hm hs hn _ _ _ _ (chosenTokens_spec x d h b).1).1.symm
+ right_inv t := by
+ apply Subtype.ext
+ have hh := decodeVisits_encode hm hs hn _ _ _ ((marked_iff x d h _).2 t.property).1
+ exact Option.some.inj ((Option.some_get _).trans hh)
+
+/-- Complete local parsimony, including malformed code rejection and the
+unique leaf bijection recovered from the position marks. -/
+noncomputable def siteEquiv (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w)
+ (x : Fin m → Bool) (d : Fin n) (h : Fin s) (hsize : d.val + 1 = m) :
+ SitePaths w x d h ≃ ParseChoice (Fin s) d x :=
+ (bitTraceEquiv hm hs hn x d h).trans (choiceEquiv d hsize x)
+
+/-- Counter values emitted by this path's actual sequence of stack updates. -/
+noncomputable def siteHistogram (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w)
+ (x : Fin m → Bool) (d : Fin n) (h : Fin s) (b : SitePaths w x d h) : Label n m (Fin s) →₀ ℕ :=
+ tally ((scan x [(d,h)] (chosenTokens x d h b)).get
+ (decodeVisits_sound hm hs hn _ _ _ _ (chosenTokens_spec x d h b).1).2)
+
+theorem siteHistogram_eq (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w)
+ (x : Fin m → Bool) (d : Fin n) (h : Fin s) (hsize : d.val + 1 = m) (b : SitePaths w x d h) :
+ siteHistogram hm hs hn x d h b = histogram d h (siteEquiv hm hs hn x d h hsize b).1 := by
+ let ts := chosenTokens x d h b
+ have hm' : (positions ts).Nodup := (chosenTokens_spec x d h b).2
+ have hsc : (scan x [(d,h)] ts).isSome := (decodeVisits_sound hm hs hn _ _ _ _ (chosenTokens_spec x d h b).1).2
+ have ht := (marked_iff x d h ts).1 ⟨hsc, hm'⟩
+ have he := scan_marked x d h ts
+ simp only [hm', ↓reduceIte] at he
+ rw [← Option.some_get hsc, ← Option.some_get ht] at he
+ exact Option.some.inj he
+
+/-- One shared internal assignment followed by one complete branch path per site. -/
+abbrev PairPaths (w : ℕ) (d : Fin n) (h : Fin s) (input : Internal → Site → Fin m → Bool) :=
+ (a : Internal) × ((v : Site) → SitePaths w (input a v) d h)
+
+/-- Identify an internal assignment and one accepted binary preorder path at each site with the
+parse choices defining the pair coefficient. -/
+noncomputable def pairEquiv (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w)
+ (d : Fin n) (h : Fin s) (hsize : d.val + 1 = m) (input : Internal → Site → Fin m → Bool) :
+ PairPaths w d h input ≃ PairCoefficient.Choices (Fin s) d input :=
+ Equiv.sigmaCongrRight fun a => Equiv.piCongrRight fun v => siteEquiv hm hs hn (input a v) d h hsize
+
+/-- Counts accumulated in the shared histogram across both primed groups. -/
+noncomputable def totalHistogram [Fintype Site] (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w)
+ (d : Fin n) (h : Fin s) (input : Internal → Site → Fin m → Bool) (b : PairPaths w d h input) :
+ Label n m (Fin s) →₀ ℕ := ∑ v, siteHistogram hm hs hn (input b.1 v) d h (b.2 v)
+
+theorem totalHistogram_eq [Fintype Site] (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w)
+ (d : Fin n) (h : Fin s) (hsize : d.val + 1 = m) (input : Internal → Site → Fin m → Bool)
+ (b : PairPaths w d h input) :
+ totalHistogram hm hs hn d h input b = PairCoefficient.jointHistogram d h input (pairEquiv hm hs hn d h hsize input b) := by
+ apply Finset.sum_congr rfl
+ intro v _
+ exact siteHistogram_eq hm hs hn _ _ _ hsize _
+
+/-- The number of branch tapes surviving the histogram comparison is precisely
+the coefficient of (9.4), including when no tape is accepted. -/
+theorem pairPath_count [Fintype Site] [Fintype Internal]
+ (hm : m ≤ 2^w) (hs : s ≤ 2^w) (hn : n ≤ 2^w) (d : Fin n) (h : Fin s)
+ (hsize : d.val + 1 = m) (input : Internal → Site → Fin m → Bool) (μ : Label n m (Fin s) →₀ ℕ) :
+ (Nat.card {b : PairPaths w d h input // totalHistogram hm hs hn d h input b = μ} : ℤ) =
+ (PairCoefficient.jointPolynomial d h input).coeff μ := by
+ rw [PairCoefficient.coeff_eq_count, ← Nat.card_eq_fintype_card]
+ congr 1
+ exact Nat.card_congr (Equiv.subtypeEquiv (pairEquiv hm hs hn d h hsize input) fun b =>
+ by rw [totalHistogram_eq hm hs hn d h hsize input b])
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterTranscriptCount.lean b/lean/OAI/Computability/VPVNP/PrimedCounterTranscriptCount.lean
new file mode 100644
index 0000000000..a5584c94e7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterTranscriptCount.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.PrimedCounterNative
+import OAI.Computability.VPVNP.PrimedCounterTranscriptCountLabels
+import OAI.Computability.VPVNP.RAMValidatorPaths
+
+/-!
+# The auxiliary RAM transcript computes the primed coefficient
+
+The prescribed header is a word-valued function of site address. The
+transcript validators first initialize RAM from that function. Their joint
+path count, including all guesses at the auxiliary sites, is exactly the
+grammar multiplicity for the original two groups and their exterior bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Data
+
+open BurstRAM PrimedInputRAM
+
+variable {L : Lengths} {n r H s w b d e : ℕ} {Q : Layout L n r H w}
+
+/-- Capped auxiliary paths on the standard initialized header count the
+multiplicity used in the grammar diagonal. -/
+theorem transcript_count (D : Data Q s) (hf : D.Fits) (μ : GrammarDiagonal.Nomination n n b (Fin s))
+ (hnom : D.nomination = GrammarDiagonal.exponents μ) (S K : ℕ) (hK : 15 ≤ K)
+ (hbudget : 15 * D.total ≤ S*K) (hheader : Header.count L + D.labels ≤ S) :
+ Nat.card (ActualPaths D.machine.program D.fuel 0 (RAMMemory.initialMemory S D.initial) (withinCaps S K)) =
+ GrammarDiagonal.multiplicity D.degree D.root (PrimedInputRAM.input Q.program Q.fits D.header) μ := by
+ rw [D.initialMemory_eq hheader]
+ have he := D.native_count hf S K hK hbudget
+ rw [hnom, GrammarDiagonal.coeff_exponents] at he
+ exact_mod_cast he
+
+/-- The product of the actual auxiliary validators' path counts, summed
+over their shared-bit assignments, is the nominated integer coefficient. -/
+theorem incident_count (D : Data Q s) (hf : D.Fits) (μ : GrammarDiagonal.Nomination n n b (Fin s))
+ (hnom : D.nomination = GrammarDiagonal.exponents μ) (hK : 15 ≤ 2^e)
+ (hbudget : 15 * D.total ≤ 2^d * 2^e) (hheader : Header.count L + D.labels ≤ 2^d)
+ (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) :
+ (∑ bits : RawAssignment d e w, ∏ v : Fin (2^d),
+ Nat.card (D.machine.IncidentPaths D.fuel 0 (D.initial v) hw hc v (incidentBits bits v))) =
+ GrammarDiagonal.multiplicity D.degree D.root (PrimedInputRAM.input Q.program Q.fits D.header) μ := by
+ rw [← D.machine.parsimoniousIncidentPaths D.fuel 0 D.initial hw hc]
+ exact D.transcript_count hf μ hnom _ _ hK hbudget hheader
+
+end PrimedCounter.Data
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterTranscriptCountLabels.lean b/lean/OAI/Computability/VPVNP/PrimedCounterTranscriptCountLabels.lean
new file mode 100644
index 0000000000..e37e469087
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterTranscriptCountLabels.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.GrammarDiagonal
+import OAI.Computability.VPVNP.PrimedCounterData
+import OAI.Computability.VPVNP.PrimedInputRAMCapacity
+
+/-!
+# Bounded nominations and initial header words
+
+A fixed-width nomination gives one natural exponent for each grammar label.
+Its finite-support exponent vector is the monomial tested by the pair counter.
+The external-memory initializer supplies its dense word table after the header
+bits and uses zero elsewhere.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace GrammarDiagonal
+
+open scoped Classical
+
+variable {n m w : ℕ} {H Site Bits : Type*} [Fintype H]
+
+/-- The monomial indexed by the complete nomination of label counts. -/
+noncomputable def exponents (μ : Nomination m n w H) : GrammarLabel (Fin m × Bool) H n →₀ ℕ :=
+ Finsupp.equivFunOnFinite.symm (fun a => (μ a).val)
+
+@[simp] theorem exponents_apply (μ : Nomination m n w H) (a : GrammarLabel (Fin m × Bool) H n) :
+ exponents μ a = (μ a).val := by simp [exponents]
+
+/-- Matching the nominated monomial has precisely the multiplicity of (9.4). -/
+theorem coeff_exponents [Fintype Site] [Fintype Bits] (d : Fin n) (h : H) (x : Bits → Site → Fin m → Bool)
+ (μ : Nomination m n w H) :
+ (PairCoefficient.jointPolynomial d h x).coeff (exponents μ) = (multiplicity d h x μ : ℤ) := by
+ rw [PairCoefficient.coeff_eq_count, multiplicity]
+ congr 1
+ exact Fintype.card_congr (Equiv.subtypeEquivRight fun _ => by
+ simp only [DFunLike.ext_iff, exponents_apply])
+
+end GrammarDiagonal
+
+namespace PrimedCounter.Data
+
+open BurstRAM PrimedInputRAM
+
+variable {L : Lengths} {n r H s w b : ℕ} {Q : Layout L n r H w}
+
+/-- Supply every nominated count from its fixed-width field to the parser. -/
+noncomputable def ofNomination (Q : Layout L n r H w) (d : Fin n) (root : Fin s)
+ (hdr : Header L → Bool) (μ : GrammarDiagonal.Nomination n n b (Fin s)) : Data Q s :=
+ ⟨d,root,hdr,GrammarDiagonal.exponents μ⟩
+
+theorem ofNomination_word (d : Fin n) (root : Fin s) (hdr : Header L → Bool)
+ (μ : GrammarDiagonal.Nomination n n b (Fin s)) (j : Fin (PrimedStackRAM.labelCount n n s)) :
+ (ofNomination Q d root hdr μ).nominatedWord j =
+ Fin.ofNat (2^w) (μ ((PrimedStackRAM.labelIndex n n s).symm j)).val := by
+ simp [nominatedWord, ofNomination]
+
+/-- Initializing the native validator's memory from the header-provider words
+recovers all prescribed histogram components and zeros above the header. -/
+theorem initialMemory_eq (D : Data Q s) {S : ℕ} (hfit : Header.count L + D.labels ≤ S) :
+ RAMMemory.initialMemory S D.initial = D.initial := by
+ apply initialMemory_headerMemory
+ simpa only [hist, List.length_ofFn] using hfit
+
+end PrimedCounter.Data
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterTranscriptCountParameters.lean b/lean/OAI/Computability/VPVNP/PrimedCounterTranscriptCountParameters.lean
new file mode 100644
index 0000000000..44e9b3acde
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterTranscriptCountParameters.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.PrimedCounterTranscriptCount
+import OAI.Computability.VPVNP.PrimedCounterResourcesData
+import OAI.Computability.VPVNP.RAMApplications
+
+/-!
+# One coefficient-counting RAM for all sufficiently large primed pairs
+
+A fixed choice of the address multiplier works simultaneously for the pair
+index, exterior header bits, full-degree root and nominated histogram. The
+layout is fixed before the header values and histogram are supplied. The
+same integer is counted by the native RAM and by the product of its local
+validators on the virtual sites.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter.Resources
+
+open BurstRAM CursorBounds PrimedInputRAM PrimedStackRAM Compression Filter
+
+variable {n r H s w d e : ℕ} {L : Lengths} {Q : Layout L n r H w}
+
+/-- The fitted auxiliary machine and both ways of counting its accepted paths. -/
+structure Counts (D : Data Q s) (μ : GrammarDiagonal.Nomination n n (2*r) (Fin s))
+ (cap : ProcessorBudget n d e w) : Prop where
+ fits : D.Fits
+ privateWork : 6 * D.fuel ≤ n^10
+ perCall : 15 ≤ 2^e
+ total : 15 * D.total ≤ 2^d * 2^e
+ native : Nat.card (ActualPaths D.machine.program D.fuel 0 (RAMMemory.initialMemory (2^d) D.initial)
+ (withinCaps (2^d) (2^e))) =
+ GrammarDiagonal.multiplicity D.degree D.root (PrimedInputRAM.input Q.program Q.fits D.header) μ
+ validators : (∑ bits : RawAssignment d e w, ∏ v : Fin (2^d),
+ Nat.card (D.machine.IncidentPaths D.fuel 0 (D.initial v) cap.tags cap.capFits v (incidentBits bits v))) =
+ GrammarDiagonal.multiplicity D.degree D.root (PrimedInputRAM.input Q.program Q.fits D.header) μ
+
+/-- Uniform Section 11 count at the virtual site and bucket parameters. -/
+theorem eventually_counts (p : UniversalMachine.Program) (a d₁ d₂ C B : ℕ)
+ (hB : max (max (a+1) (a+d₂)) (max d₁ C) + 2 ≤ B) {δ : ℝ} (hδ : 0 < δ) (hδ' : δ ≤ 1) :
+ ∀ᶠ n : ℕ in atTop, ∀ i : Fin (2^(n^a-1)), ∀ s, labelCount n n s ≤ n^C →
+ let L := PairedChain.lengths (n^a-1) (n^d₂) (n^d₁) i
+ let r := addressWidth B n
+ let w := CursorBounds.wordBits B n
+ ∃ Q : Layout L n r (liveBucket δ n) w, Q.program = p ∧ Q.scratchBase = 2^(virtualBits B n) ∧
+ ∃ cap : ProcessorBudget n (virtualBits B n) (roundedUp 1 4 n) w,
+ ∀ (degree : Fin n) (root : Fin s) (header : Header L → Bool)
+ (μ : GrammarDiagonal.Nomination n n (2*r) (Fin s)), degree.val + 1 = n →
+ Counts (Data.ofNomination Q degree root header μ) μ cap := by
+ have hpositive : 1 ≤ B := by omega
+ filter_upwards [eventually_layouts p a d₁ d₂ C B hB hδ hδ',
+ eventually_bothProcessorBudgets hpositive hδ.le hδ'] with n hLayout hCaps
+ intro i s hs
+ obtain ⟨Q,hp,hbase,hheader,hparams,hbounds⟩ := hLayout i s hs
+ refine ⟨Q,hp,hbase,hCaps.2,?_⟩
+ intro degree root hdr μ hd
+ let D := Data.ofNomination Q degree root hdr μ
+ have hf : D.Fits := hbounds.dataFits D hparams hd hheader (fun j => by
+ simpa only [D, Data.ofNomination, GrammarDiagonal.exponents_apply] using (μ j).isLt)
+ obtain ⟨hwork,hbudget⟩ := hbounds.dataBudget D
+ rw [hbase] at hheader
+ exact ⟨hf,hwork,hbounds.perCall,hbudget,
+ D.transcript_count hf μ rfl _ _ hbounds.perCall hbudget hheader,
+ D.incident_count hf μ rfl hbounds.perCall hbudget hheader hCaps.2.tags hCaps.2.capFits⟩
+
+end PrimedCounter.Resources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterVirtualFuel.lean b/lean/OAI/Computability/VPVNP/PrimedCounterVirtualFuel.lean
new file mode 100644
index 0000000000..dc55833b8b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterVirtualFuel.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.PrimedCounterData
+import OAI.Computability.VPVNP.PrimedCounterResourcesWork
+import OAI.Computability.VPVNP.LivePublicExpr
+
+/-!
+# The auxiliary verifier's private clock as a width-only operand
+
+At the paper's word widths the parser clock dominates the assembler's
+address-scan clock. The exact clock used by the native coefficient counter
+can therefore be computed inside a virtual leaf from its word width alone.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open BurstRAM PrimedInputRAM LiveProgram
+
+/-- Public operand computing the auxiliary coefficient verifier's instruction allowance as
+twelve times the virtual word width plus 110. -/
+def virtualFuel : PublicExpr := .add (.mul (.lit 12) .w) (.lit 110)
+
+theorem virtualFuel_eval (g : Geometry) : virtualFuel.eval g = 12*g.w+110 := rfl
+
+private theorem width_dominates (r : ℕ) : Opcodes.nativeFuel r+20 ≤ 12*(r+10)^4+110 := by
+ have hs := Nat.pow_le_pow_right (by omega : 0 < r+10) (by decide : 2 ≤ 4)
+ rw [pow_two] at hs
+ unfold Opcodes.nativeFuel
+ nlinarith [Nat.zero_le (r*r)]
+
+theorem Data.fuel_eq_virtualFuel {n r H s : ℕ} {L : Lengths}
+ {Q : Layout L n r H ((r+10)^4)} (D : Data Q s) (g : Geometry) (hw : g.w = (r+10)^4) :
+ D.fuel = virtualFuel.eval g := by
+ rw [virtualFuel_eval,hw]
+ exact max_eq_right (width_dominates r)
+
+private theorem fitsWidth (w : ℕ) (hw : 9 ≤ w) : 12*w+110 < 2^w := by
+ induction w, hw using Nat.le_induction with
+ | base => decide
+ | succ w _ ih => rw [pow_succ]; omega
+
+theorem virtualFuel_fits (g : Geometry) (hw : 9 ≤ g.w) : virtualFuel.Fits g (2^g.w) := by
+ have h := fitsWidth g.w hw
+ simp only [virtualFuel, PublicExpr.Fits, PublicExpr.eval, and_true]
+ omega
+
+theorem eventually_virtualFuel_cap (B : ℕ) :
+ ∀ᶠ n : ℕ in Filter.atTop, 6*(12*CursorBounds.wordBits B n+110) ≤ n^10 := by
+ filter_upwards [Resources.eventually_privateWork B] with n h
+ exact (Nat.mul_le_mul_left 6 (le_max_right _ _)).trans h
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedCounterVisit.lean b/lean/OAI/Computability/VPVNP/PrimedCounterVisit.lean
new file mode 100644
index 0000000000..0dd3354201
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedCounterVisit.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.PrimedCounterStackBounds
+
+/-!
+# Online traversal with a shared histogram
+
+Each binary branch tape belongs to one node visit. The visit pops a frame,
+decodes the choice at its actual degree, checks and sets the selected mark at
+a leaf, pushes the ordered children and increments one shared production
+counter. Successful traversals may start with arbitrary accumulated counts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedCounter
+
+open ParseGrammar
+
+variable {n m s w : ℕ}
+
+/-- Logical state for visiting grammar nodes one at a time while accumulating a production
+histogram shared across sites. -/
+structure VisitState (n m s : ℕ) where
+ /-- Stack of grammar nodes awaiting visits, with the next node at the head. -/
+ pending : List (Frame n (Fin s))
+ /-- Terminal positions already used by the current site's parse. -/
+ marked : Finset (Fin m)
+ /-- Accumulated multiplicity of each production label from the nodes visited so far. -/
+ counts : Label n m (Fin s) →₀ ℕ
+
+/-- The one-bit mark memory accessed at a terminal. -/
+def markToken (marked : Finset (Fin m)) : Token m (Fin s) → Option (Finset (Fin m))
+ | .terminal j => if j ∈ marked then none else some (insert j marked)
+ | .binary .. => some marked
+
+/-- A single node call, including exactly one increment of the nominated
+production's count. -/
+noncomputable def visit (w : ℕ) (x : Fin m → Bool) (st : VisitState n m s) (bits : List Bool) :
+ Option (VisitState n m s) := do
+ let f :: rest := st.pending | none
+ let t ← readToken w m s f.1.val bits
+ let (a, children) ← step x f t
+ let marked ← markToken st.marked t
+ return ⟨children ++ rest, marked, st.counts + Finsupp.single a 1⟩
+
+/-- Consume all node calls. The empty stack is required at completion. -/
+noncomputable def visits (w : ℕ) (x : Fin m → Bool) :
+ VisitState n m s → List (List Bool) → Option (VisitState n m s)
+ | st, [] => if st.pending.isEmpty then some st else none
+ | st, bits :: more => (visit w x st bits).bind (fun st' => visits w x st' more)
+
+private theorem testMarks_cons (marked : Finset (Fin m)) (t : Token m (Fin s)) (ts : List (Token m (Fin s))) :
+ testMarks marked (t::ts) = (markToken marked t).bind (fun next => testMarks next ts) := by
+ cases t <;> simp [testMarks, markToken]
+ split <;> rfl
+
+/-- Online traversal produces the same labels and mark checks as the independent
+stack and branch-stream decoders. Counts from preceding sites are retained. -/
+theorem visits_eq (x : Fin m → Bool) (st : VisitState n m s) (bs : List (List Bool)) :
+ visits w x st bs = (do
+ let ts ← decodeVisits w x st.pending bs
+ let marks ← testMarks st.marked ts
+ let as ← scan x st.pending ts
+ return ⟨[], marks, st.counts + tally as⟩) := by
+ induction bs generalizing st with
+ | nil =>
+ obtain ⟨stack, marked, counts⟩ := st
+ cases stack <;> simp [visits, decodeVisits, testMarks, scan, tally]
+ | cons bits bs ih =>
+ obtain ⟨stack, marked, counts⟩ := st
+ cases stack with
+ | nil => simp [visits, visit, decodeVisits]
+ | cons f stack =>
+ cases ht : readToken w m s f.1.val bits with
+ | none => simp [visits, visit, decodeVisits, ht]
+ | some t =>
+ cases hs : step x f t with
+ | none => simp [visits, visit, decodeVisits, ht, hs]
+ | some val =>
+ obtain ⟨a, cs⟩ := val
+ cases hd : decodeVisits w x (cs ++ stack) bs with
+ | none =>
+ cases hm : markToken marked t <;> simp [visits, visit, decodeVisits, ht, hs, hm, ih, hd]
+ | some ts =>
+ cases hm : markToken marked t with
+ | none => simp [visits, visit, decodeVisits, ht, hs, hm, hd, testMarks_cons]
+ | some next =>
+ cases hmarks : testMarks next ts <;> cases hscan : scan x (cs ++ stack) ts <;>
+ simp [visits, visit, decodeVisits, ht, hs, hm, hd, ih, testMarks_cons, scan,
+ hmarks, hscan, tally, add_assoc]
+
+/-- Accepted complete binary streams are exactly the streams of the parsimonious
+local traversal, including all successful positions of every terminal. -/
+theorem visits_accepts (x : Fin m → Bool) (d : Fin n) (root : Fin s)
+ (counters : Label n m (Fin s) →₀ ℕ) (bs : List (List Bool))
+ (hn : n ≤ 2^w) (hm : m ≤ 2^w) (hs : s ≤ 2^w) :
+ (visits w x ⟨[(d,root)], ∅, counters⟩ bs).isSome ↔
+ ∃ ts, decodeVisits w x [(d,root)] bs = some ts ∧ (positions ts).Nodup := by
+ rw [visits_eq]
+ cases hd : decodeVisits w x [(d,root)] bs with
+ | none => simp
+ | some ts =>
+ have hsc := (decodeVisits_sound hm hs hn _ _ _ _ hd).2
+ have hmarks := freshMarks_iff ts
+ cases hs' : scan x [(d,root)] ts <;> cases hm' : testMarks ∅ ts <;> simp_all
+
+/-- The updated shared counters after a single site equal its incoming counts
+plus the production histogram from the actual binary trace. -/
+theorem visits_counts (x : Fin m → Bool) (d : Fin n) (root : Fin s)
+ (counters : Label n m (Fin s) →₀ ℕ) (b : SitePaths w x d root)
+ (hn : n ≤ 2^w) (hm : m ≤ 2^w) (hs : s ≤ 2^w) :
+ ∃ marks, visits w x ⟨[(d,root)], ∅, counters⟩ b.val =
+ some ⟨[], marks, counters + siteHistogram hm hs hn x d root b⟩ := by
+ rw [visits_eq]
+ let ts := chosenTokens x d root b
+ obtain ⟨hd, hmark⟩ := chosenTokens_spec x d root b
+ obtain ⟨marks, hmarks⟩ := Option.isSome_iff_exists.mp ((freshMarks_iff ts).2 hmark)
+ have hsc := (decodeVisits_sound hm hs hn _ _ _ _ hd).2
+ refine ⟨marks, ?_⟩
+ let as := (scan x [(d,root)] ts).get hsc
+ have hs' : scan x [(d,root)] ts = some as := (Option.some_get hsc).symm
+ change decodeVisits w x [(d,root)] b.val = some ts at hd
+ change _ = some (VisitState.mk [] marks (counters + tally as))
+ simp [hd, hmarks, hs']
+
+end PrimedCounter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAM.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAM.lean
new file mode 100644
index 0000000000..15a582b233
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAM.lean
@@ -0,0 +1,194 @@
+import OAI.Computability.VPVNP.PrimedInputRAMRows
+import OAI.Computability.VPVNP.PrimedInputRAMCopy
+
+/-!
+# Two-pass assembly of the inputs to the primed coefficient counter
+
+The first pass branches at every internal bit's designated physical cell.
+The second pass reads one fixed header or scratch address when needed,
+then writes the resulting bit to a separate rectangular input array. The
+proof identifies the result, at every parse leaf, with the full primed
+coefficient-machine input. No validator is called on any shared bit string.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM
+
+/-- Number of input cells in one rectangular pass, with n bits per site in each of two groups
+of 2^r sites. -/
+abbrev positions (n r : ℕ) := (2 * 2^r) * n
+
+/-- The two rectangular arrays are placed after the auxiliary headers.
+The three supplied cut lengths have addresses 0, 1, 2. The histogram
+may occupy reserved addresses beyond the bit arrays before `scratchBase`. -/
+structure Layout (L : Lengths) (n r H w : ℕ) where
+ /-- Universal-machine program whose literal prefix is embedded in every assembled processor
+ input. -/
+ program : UniversalMachine.Program
+ fits : ProcessorInput.Fits program n r H w
+ middleFits : L.middleCut ≤ 2^r
+ /-- Beginning of the first-pass choice rectangle in external memory. -/
+ scratchBase : ℕ
+ headersFit : Header.count L ≤ scratchBase
+ addressesFit : scratchBase + positions n r + positions n r ≤ 2^w
+
+variable {L : Lengths} {n r H w : ℕ}
+
+namespace Layout
+
+variable (Q : Layout L n r H w)
+
+/-- The loop counters range over row-major cells of the `2R` full tapes. -/
+def coordinates :
+ (Site r × RowField Q.program n r H w) ≃ Fin (positions n r) :=
+ (finProdFinEquiv.prodCongr (rowIndex Q.program Q.fits)).trans finProdFinEquiv
+
+/-- Whether this rectangular position is the designated location that chooses a shared internal
+bit. -/
+def owns (i : Fin (positions n r)) : Bool := cellOwner L (Q.coordinates.symm i)
+
+/-- Exact equivalence between internal summation indices and branch cells
+of the actual flattened first-pass loop. -/
+def internalOwner : Internal L r H w ≃ {i : Fin (positions n r) // Q.owns i = true} :=
+ (ownerEquiv _ _ Q.middleFits).trans (Q.coordinates.subtypeEquiv (by
+ intro c; simp [owns]))
+
+/-- Injective word address of a first-pass scratch cell, obtained by offsetting its rectangular
+index from the scratch base. -/
+def bitAddress : Fin (positions n r) ↪ Word w :=
+ scratchAddress Q.scratchBase (by have := Q.addressesFit; omega)
+
+/-- Injective word address in the second-pass output rectangle immediately following first-pass
+scratch. -/
+def outputAddress : Fin (positions n r) ↪ Word w :=
+ scratchAddress (Q.scratchBase + positions n r) Q.addressesFit
+
+/-- Word address of the specified header field below the scratch rectangle. -/
+def readHeader (j : Header L) : Word w :=
+ ⟨j.address.val, j.address.isLt.trans_le (Q.headersFit.trans (by have := Q.addressesFit; omega))⟩
+
+/-- Inverse of the chosen-address map for the branch stream. -/
+def assignment (bits : Internal L r H w → Bool) : Assignment Q.owns :=
+ bits ∘ Q.internalOwner.symm
+
+/-- All admissible branch streams, including those encoding inconsistent
+primed messages, are enumerated exactly once. -/
+def streamEquiv (bitWord : Bool → Word w) (initial : Memory w) :
+ {bs : List Bool // (firstPass Q.owns Q.bitAddress bitWord bs initial).isSome = true} ≃
+ (Internal L r H w → Bool) :=
+ (admissibleEquiv Q.owns Q.bitAddress bitWord initial).trans
+ (Q.internalOwner.symm.arrowCongr (Equiv.refl _))
+
+private def reference (i : Fin (positions n r)) : Ref L r H w :=
+ cellRef L (UniversalMachine.programPrefix Q.program).get (Q.coordinates.symm i)
+
+/-- Resolve a literal, header reference or shared internal bit to the immediate word or RAM
+address used by the copy pass. -/
+def refSource (bitWord : Bool → Word w) : Ref L r H w → CopySource w
+ | .literal b => .literal (bitWord b)
+ | .header j => .fetch (Q.readHeader j)
+ | .shared b => .fetch (Q.bitAddress (Q.internalOwner b).val)
+
+/-- Source of the second-pass copy for this rectangular input position. -/
+def source (bitWord : Bool → Word w) (i : Fin (positions n r)) : CopySource w :=
+ Q.refSource bitWord (Q.reference i)
+
+private theorem separated (bitWord : Bool → Word w) :
+ CopySeparated Q.outputAddress (Q.source bitWord) := by
+ intro i j a h
+ unfold source at h
+ cases hr : Q.reference i with
+ | literal b => simp [hr, refSource] at h
+ | header k =>
+ simp [hr, refSource] at h
+ subst a
+ intro he
+ have hh := congrArg Fin.val he
+ change k.address.val = Q.scratchBase + positions n r + j.val at hh
+ have := k.address.isLt
+ have := Q.headersFit
+ omega
+ | shared b =>
+ simp [hr, refSource] at h
+ subst a
+ intro he
+ have hh := congrArg Fin.val he
+ change Q.scratchBase + (Q.internalOwner b).val.val = Q.scratchBase + positions n r + j.val at hh
+ have := (Q.internalOwner b).val.isLt
+ omega
+
+/-- Store the chosen bits and perform all deterministic copies. -/
+def assemble (bitWord : Bool → Word w) (bs : List Bool) (initial : Memory w) : Option (Memory w) :=
+ (firstPass Q.owns Q.bitAddress bitWord bs initial).map
+ (secondPass Q.outputAddress (Q.source bitWord))
+
+/-- Final RAM after storing the given internal bit assignment at its owners and copying every
+processor-input cell. -/
+def assembled (bitWord : Bool → Word w) (bits : Internal L r H w → Bool)
+ (initial : Memory w) : Memory w :=
+ secondPass Q.outputAddress (Q.source bitWord)
+ (store Q.bitAddress (bitWord ∘ bitAt (Q.assignment bits)) (owners Q.owns) initial)
+
+theorem assemble_branches (bitWord : Bool → Word w) (bits : Internal L r H w → Bool)
+ (initial : Memory w) :
+ Q.assemble bitWord (branches (Q.assignment bits)) initial = some (Q.assembled bitWord bits initial) := by
+ simp only [assemble, firstPass_branches, Option.map_some, assembled]
+
+private theorem read_ref (bitWord : Bool → Word w) (bits : Internal L r H w → Bool)
+ (hdr : Header L → Bool) (initial : Memory w)
+ (hi : ∀ j, initial j.address.val = bitWord (hdr j)) (ref : Ref L r H w) :
+ CopySource.get (store Q.bitAddress (bitWord ∘ bitAt (Q.assignment bits)) (owners Q.owns) initial)
+ (Q.refSource bitWord ref) = bitWord (ref.value hdr bits) := by
+ cases ref with
+ | literal b => rfl
+ | header j =>
+ change store _ _ _ initial j.address.val = bitWord (hdr j)
+ rw [bitAddress, store_header _ _ _ _ initial (j.address.isLt.trans_le Q.headersFit), hi]
+ | shared b =>
+ have hb := (Q.internalOwner b).property
+ change store _ _ _ initial (Q.bitAddress (Q.internalOwner b).val).val = bitWord (bits b)
+ rw [store_at _ _ _ _ ((mem_owners _ _).mpr hb)]
+ simp [bitAt, hb, assignment]
+
+/-- After the two passes, the grammar parser can fetch the selected leaf bit
+in a single word read. This holds for every internal assignment. -/
+theorem assembled_input (bitWord : Bool → Word w) (bits : Internal L r H w → Bool)
+ (hdr : Header L → Bool) (initial : Memory w)
+ (hi : ∀ j, initial j.address.val = bitWord (hdr j)) (u : Site r) (j : Fin n) :
+ Q.assembled bitWord bits initial (Q.outputAddress (finProdFinEquiv (finProdFinEquiv u,j))).val =
+ bitWord (input Q.program Q.fits hdr bits u j) := by
+ obtain ⟨f,rfl⟩ := (rowIndex Q.program Q.fits).surjective j
+ change Q.assembled bitWord bits initial (Q.outputAddress (Q.coordinates (u,f))).val = _
+ rw [assembled, secondPass_at _ _ _ (Q.separated bitWord), source, read_ref _ _ _ _ _ hi,
+ reference, Equiv.symm_apply_apply, input_at]
+
+/-- Number of calls plus probes of the two passes. The first pass makes at
+most one write per cell. The second makes at most one read and one write. -/
+theorem twoPass_cost (bitWord : Bool → Word w) (bits : Internal L r H w → Bool)
+ (next₁ next₂ : Fin (positions n r) → Word w) (initial : Memory w) :
+ let cells := List.finRange (positions n r)
+ let f := bitAt (Q.assignment bits)
+ let m := store Q.bitAddress (bitWord ∘ f) (owners Q.owns) initial
+ RAMBuckets.cost Report.probes (reports Q.owns Q.bitAddress next₁ bitWord f cells) +
+ RAMBuckets.cost Report.probes (copyReports Q.outputAddress (Q.source bitWord) next₂ cells m) ≤
+ 5 * positions n r := by
+ dsimp only
+ rw [reports_cost, List.length_finRange]
+ have h1 := owners_length_le Q.owns
+ have h2 := copyReports_cost_le Q.outputAddress (Q.source bitWord) next₂ (List.finRange _)
+ (store Q.bitAddress (bitWord ∘ bitAt (Q.assignment bits)) (owners Q.owns) initial)
+ rw [List.length_finRange] at h2
+ change (List.filter Q.owns (List.finRange (positions n r))).length ≤ _ at h1
+ omega
+
+end Layout
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMAddresses.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMAddresses.lean
new file mode 100644
index 0000000000..cb4d325a96
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMAddresses.lean
@@ -0,0 +1,198 @@
+import OAI.Computability.VPVNP.PrimedInputRAMTranscript
+import OAI.Computability.VPVNP.RAMSortCostLayout
+
+/-!
+# Computing the scratch read from a raw incident bit position
+
+The pair counter in Section 11 enumerates input bits by position. A local
+offset in the sorting region determines an exchange number and a direction.
+At most `d` triangular-prefix comparisons recover the site's XOR mask.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open RAMLayout RAMSort
+
+private def triangular (k : ℕ) : IndexExpr :=
+ .div (.mul (.arg k) (.add (.arg k) (.arg 1))) (.arg 2)
+
+private theorem triangular_eq (k : ℕ) : (triangular k).eval = layerCount k := by
+ simp only [triangular, IndexExpr.eval, layerCount, Nat.choose_two_right]
+ rw [Nat.add_sub_cancel, Nat.mul_comm k]
+
+/-- Look for the phase containing the given exchange ordinal. Each iteration
+evaluates a triangular prefix and compares it with the ordinal. In the
+identified phase two subtractions give the XOR bit. -/
+def layerBitLoop : ℕ → ℕ → ℕ × ℕ
+ | 0, _ => (0, 0)
+ | k + 1, i =>
+ let prefixSize := triangular k
+ if i < prefixSize.eval then
+ let r := layerBitLoop k i
+ (r.1, r.2 + prefixSize.work + 1)
+ else (k - (i - prefixSize.eval), prefixSize.work + 3)
+
+theorem layerBitLoop_spec {d : ℕ} (i : Fin (layerCount d)) :
+ (layerBitLoop d i.val).1 = (layerAt d i).siteBit := by
+ induction d with
+ | zero => exact Fin.elim0 i
+ | succ d ih =>
+ by_cases h : i.val < layerCount d
+ · simpa [layerBitLoop, triangular_eq, layerAt, h, Layer.siteBit] using ih ⟨i.val, h⟩
+ · simp [layerBitLoop, triangular_eq, layerAt, h, Layer.siteBit]
+
+theorem layerBitLoop_ordinal {d : ℕ} (l : Layer d) :
+ (layerBitLoop d l.ordinal.val).1 = l.siteBit := by
+ rw [layerBitLoop_spec]
+ exact congrArg Layer.siteBit ((layerEquiv d).left_inv l)
+
+theorem layerBitLoop_work (d i : ℕ) : (layerBitLoop d i).2 ≤ 6 * d := by
+ induction d with
+ | zero => rfl
+ | succ d ih =>
+ rw [layerBitLoop]
+ split <;> simp only [triangular, IndexExpr.work] <;> omega
+
+private def sortWidth (H w : ℕ) : IndexExpr :=
+ .mul (.mul (.mul (.arg 4) (.arg H)) (.arg 5)) (.arg w)
+
+private def chunkIndex (H w k : ℕ) : IndexExpr :=
+ .div (.sub (.arg k) (.mul (.arg 16) (.arg w))) (sortWidth H w)
+
+/-- Compute a source row and offset from the public site and local position.
+The work counter charges arithmetic and comparisons. The final read, when
+there is one, is a separate single external probe. -/
+def rawSource (d H w v k : ℕ) : Option (ℕ × ℕ) × ℕ :=
+ let first := IndexExpr.mul (.arg 8) (.arg w)
+ let base := IndexExpr.mul (.arg 16) (.arg w)
+ let sites := IndexExpr.shl (.arg 1) (.arg d)
+ if k < first.eval then
+ (if v + 1 < sites.eval then some (v, k) else none, first.work + sites.work + 3)
+ else if k < base.eval then
+ (if 0 < v then some (v - 1, k - first.eval) else none, first.work + base.work + 5)
+ else
+ let q := chunkIndex H w k
+ let side := IndexExpr.mod q (.arg 2)
+ let comparisons := first.work + base.work + side.work + 3
+ if side.eval = 0 then (some (v, k), comparisons)
+ else
+ let ordinal := IndexExpr.div q (.arg 2)
+ let bit := layerBitLoop d ordinal.eval
+ let sender := IndexExpr.xor (.arg v) (.shl (.arg 1) (.arg bit.1))
+ let sendOffset := IndexExpr.sub (.arg k) (sortWidth H w)
+ (some (sender.eval, sendOffset.eval), comparisons + ordinal.work + bit.2 + sender.work + sendOffset.work)
+
+private theorem sortWidth_eval (H w : ℕ) : (sortWidth H w).eval = blockBits H w := rfl
+
+private theorem chunkIndex_offset {d H w : ℕ} (l : Layer d) (dir : Fin 2) (j : Fin (blockBits H w)) :
+ (chunkIndex H w (offset d H w (.inr (l, dir, j))).val).eval = 2 * l.ordinal.val + dir.val := by
+ have hp : 0 < blockBits H w := Nat.zero_lt_of_lt j.isLt
+ rw [offset_sort]
+ simp only [chunkIndex, IndexExpr.eval, sortWidth_eval]
+ have h : 16 * w + l.ordinal.val * (2 * blockBits H w) + dir.val * blockBits H w + j.val - 16 * w =
+ blockBits H w * (2 * l.ordinal.val + dir.val) + j.val := by
+ rw [show 16 * w + l.ordinal.val * (2 * blockBits H w) + dir.val * blockBits H w + j.val =
+ 16 * w + (blockBits H w * (2 * l.ordinal.val + dir.val) + j.val) by ring, Nat.add_sub_cancel_left]
+ rw [h, Nat.mul_add_div hp, Nat.div_eq_of_lt j.isLt, Nat.add_zero]
+
+/-- At every actual incident port the linear-address algorithm gives the
+same source as the typed endpoint calculation, including both end clamps. -/
+theorem rawSource_offset {d H w : ℕ} (v : Fin (2 ^ d)) (p : Slot d H w) :
+ (rawSource d H w v.val (offset d H w p).val).1 =
+ (sourcePort (v, p)).map (fun y ↦ (y.1.val, (offset d H w y.2).val)) := by
+ rcases p with ⟨dir, j⟩ | ⟨l, dir, j⟩
+ · fin_cases dir
+ · have hj := j.isLt
+ by_cases hv : v.val + 1 < 2 ^ d <;>
+ simp [rawSource, offset_successor, IndexExpr.eval, Nat.shiftLeft_eq, sourcePort, hj, hv]
+ · have hj := j.isLt
+ have h₁ : ¬ 8 * w + j.val < 8 * w := by omega
+ have h₂ : 8 * w + j.val < 16 * w := by omega
+ by_cases hv : 0 < v.val <;>
+ simp [rawSource, offset_successor, IndexExpr.eval, h₁, h₂, sourcePort, hv]
+ · let k := (offset d H w (.inr (l, dir, j))).val
+ have hk := offset_sort l dir j (d := d)
+ change k = _ at hk
+ have h₁ : ¬ k < 8 * w := by omega
+ have h₂ : ¬ k < 16 * w := by omega
+ have hq : (chunkIndex H w k).eval = 2 * l.ordinal.val + dir.val := chunkIndex_offset l dir j
+ change (rawSource d H w v.val k).1 = _
+ by_cases hd : dir = 0
+ · subst dir
+ change (chunkIndex H w k).eval = 2 * l.ordinal.val + 0 at hq
+ simp [rawSource, IndexExpr.eval, h₁, h₂, hq, sourcePort]
+ rfl
+ · have hdir : dir = 1 := by
+ apply Fin.ext
+ have hn : dir.val ≠ 0 := fun h ↦ hd (Fin.ext h)
+ have := dir.isLt
+ change dir.val = 1
+ omega
+ subst dir
+ change (chunkIndex H w k).eval = 2 * l.ordinal.val + 1 at hq
+ have hdiv : (2 * l.ordinal.val + 1) / 2 = l.ordinal.val := by omega
+ have hmod : (2 * l.ordinal.val + 1) % 2 = 1 := by omega
+ have hsend : k - blockBits H w = (offset d H w (.inr (l, 0, j))).val := by
+ rw [offset_sort]
+ simp at hk ⊢
+ omega
+ simp [rawSource, IndexExpr.eval, h₁, h₂, hq, hmod, hdiv, layerBitLoop_ordinal,
+ Nat.shiftLeft_eq, sortWidth_eval, sourcePort, hsend, Layer.partner, partner]
+
+/-- Correctness for an enumerated linear input position, without an input
+slot supplied by the caller. -/
+theorem rawSource_at {d H w : ℕ} (v : Fin (2 ^ d)) (k : Fin (width d H w)) :
+ (rawSource d H w v.val k.val).1 =
+ (sourcePort (v, (offset d H w).symm k)).map (fun y ↦ (y.1.val, (offset d H w y.2).val)) := by
+ simpa only [Equiv.apply_symm_apply] using rawSource_offset v ((offset d H w).symm k)
+
+/-- The enumerator makes a binary choice precisely when this source lookup
+returns the input position itself. -/
+theorem rawSource_eq_self_iff {d H w : ℕ} (v : Fin (2 ^ d)) (k : Fin (width d H w)) :
+ (rawSource d H w v.val k.val).1 = some (v.val, k.val) ↔
+ designated (v, (offset d H w).symm k) = true := by
+ let x : Endpoint d H w := (v, (offset d H w).symm k)
+ rw [rawSource_at, ← sourcePort_eq_self_iff]
+ change (sourcePort x).map _ = some _ ↔ sourcePort x = some x
+ cases hs : sourcePort x with
+ | none => simp
+ | some y =>
+ simp only [Option.map_some, Option.some.injEq]
+ constructor
+ · intro he
+ apply Prod.ext
+ · exact Fin.ext (congrArg Prod.fst he)
+ · apply (offset d H w).injective
+ change offset d H w y.2 = offset d H w ((offset d H w).symm k)
+ rw [Equiv.apply_symm_apply]
+ exact Fin.ext (congrArg Prod.snd he)
+ · rintro rfl
+ simp [x]
+
+/-- A raw offset lookup uses at most a linear number of word operations in
+the site-address width, irrespective of any scratch or message value. -/
+theorem rawSource_work (d H w v k : ℕ) : (rawSource d H w v k).2 ≤ 6 * d + 32 := by
+ have hb := layerBitLoop_work d ((chunkIndex H w k).eval / 2)
+ by_cases h₁ : k < 8 * w
+ · simp only [rawSource, IndexExpr.eval, h₁, ite_true, IndexExpr.work]
+ omega
+ by_cases h₂ : k < 16 * w
+ · simp only [rawSource, IndexExpr.eval, h₁, ite_false, h₂, ite_true, IndexExpr.work]
+ omega
+ by_cases h₃ : (chunkIndex H w k).eval % 2 = 0
+ · simp only [rawSource, IndexExpr.eval, h₁, h₂, ite_false, h₃, ite_true]
+ change 12 ≤ _
+ omega
+ · simp only [rawSource, IndexExpr.eval, h₁, h₂, h₃, ite_false]
+ change 12 + 7 + (layerBitLoop d ((chunkIndex H w k).eval / 2)).2 + 2 + 4 ≤ _
+ omega
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMCapacity.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMCapacity.lean
new file mode 100644
index 0000000000..c2f0aa7577
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMCapacity.lean
@@ -0,0 +1,153 @@
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+import OAI.Computability.VPVNP.PrimedBudget
+import OAI.Computability.VPVNP.PairedChain
+
+/-!
+# Allocating the pair counter's headers and two rectangles
+
+The bit-valued index, advice and cut arrays and the nominated histogram
+occupy a polynomial number of header addresses independent of `B`. Choosing
+`B` last puts all these addresses below the actual virtual site count `R′`.
+The two rectangles then start at `R′` and their addresses fit the paper's
+prescribed word width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM CursorBounds Compression Filter
+
+private theorem degreeFits (B n : ℕ) : n^B ≤ processorCount B n := by
+ calc
+ n^B ≤ (2^(Nat.clog 2 n))^B := Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) _
+ _ = processorCount B n := by
+ rw [← pow_mul, Nat.mul_comm]
+ rfl
+
+/-- Both row-major rectangles fit above the full virtual header interval. -/
+theorem rectangleAddressSpace (B n : ℕ) (hB : 1 ≤ B) :
+ 2^(virtualBits B n) + positions n (addressWidth B n) + positions n (addressWidth B n) ≤
+ 2^(CursorBounds.wordBits B n) := by
+ let r := addressWidth B n
+ let c := Nat.clog 2 n
+ have hc : c ≤ r := Nat.le_mul_of_pos_left _ hB
+ have hv := virtualBits_le B n
+ have hD : virtualBits B n ≤ 3*r := by
+ change virtualBits B n ≤ (B+2)*c at hv
+ rw [Nat.add_mul] at hv
+ change c ≤ B*c at hc
+ change virtualBits B n ≤ 3*(B*c)
+ omega
+ have hn : n ≤ 2^r := (Nat.le_pow_clog (by decide) n).trans (Nat.pow_le_pow_right (by decide) hc)
+ have hr : 2^r * n ≤ 2^(3*r) := by
+ calc
+ _ ≤ 2^r * 2^r := Nat.mul_le_mul_left _ hn
+ _ = 2^(r+r) := (Nat.pow_add ..).symm
+ _ ≤ _ := Nat.pow_le_pow_right (by decide) (by omega)
+ have hvirt := Nat.pow_le_pow_right (by decide : 0 < 2) hD
+ have hs : positions n r ≤ 2 * 2^(3*r) := by
+ unfold positions
+ rw [Nat.mul_assoc]
+ exact Nat.mul_le_mul_left _ hr
+ have hw : 3*r+3 ≤ (r+10)^4 := by
+ calc
+ _ ≤ (r+10)^2 := by nlinarith [Nat.zero_le (r*r)]
+ _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide : 2 ≤ 4)
+ have hlarge := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ rw [Nat.pow_add] at hlarge
+ change 2^(virtualBits B n) + positions n r + positions n r ≤ 2^((r+10)^4)
+ norm_num1 at hlarge
+ omega
+
+/-- A fixed degree bound for the header data is absorbed by the choice of
+address multiplier `B`; the same capacity covers the middle cut. -/
+theorem headerCapacity {B C n : ℕ} (hn : 3 ≤ n) (hB : C+2 ≤ B) (L : Lengths) (hist : ℕ)
+ (hi : L.index ≤ n^C) (ha : L.advice ≤ n^C) (hc : L.cutCapacity ≤ n^C)
+ (hm : L.middleCut ≤ n^C) (ht : hist ≤ n^C) :
+ Header.count L + hist ≤ 2^(virtualBits B n) ∧ L.middleCut ≤ 2^(addressWidth B n) := by
+ have hp : 1 ≤ n^C := Nat.pow_pos (by omega)
+ have hscale : 9 ≤ n^2 := by nlinarith
+ have hdata : Header.count L + hist ≤ n^(C+2) := by
+ rw [Nat.pow_add]
+ apply le_trans _ (Nat.mul_le_mul_left (n^C) hscale)
+ unfold Header.count
+ omega
+ have hbig : n^(C+2) ≤ processorCount B n :=
+ (Nat.pow_le_pow_right (by omega) hB).trans (degreeFits ..)
+ have hmid := (Nat.pow_le_pow_right (by omega : 0 if own then .branch CellControl.emit else .finish (some next)
+ | .emit b => .write addr (bitWord b) .done
+ | .done => .finish (some next)
+
+@[simp] theorem execute_cell_owner (addr next : Word w) (bitWord : Bool → Word w)
+ (m : Memory w) (b : Bool) :
+ execute (cellCall true addr next bitWord) 3 .visit m [b] =
+ some ⟨[.choice b, .write addr (bitWord b)], some next⟩ := rfl
+
+@[simp] theorem execute_cell_skip (addr next : Word w) (bitWord : Bool → Word w) (m : Memory w) :
+ execute (cellCall false addr next bitWord) 3 .visit m [] = some ⟨[], some next⟩ := rfl
+
+/-- Scan the full endpoint list, retaining an exact branch stream. The address is
+injective across all endpoints. The per-cell reports above implement its memory update. -/
+def scan (own : Fin N → Bool) (addr : Fin N ↪ Word w) (bitWord : Bool → Word w) :
+ List (Fin N) → List Bool → Memory w → Option (Memory w)
+ | [], bits, m => if bits.isEmpty then some m else none
+ | i :: cells, bits, m =>
+ if own i then
+ match bits with
+ | [] => none
+ | b :: bs => scan own addr bitWord cells bs (writeMemory m (addr i) (bitWord b))
+ else scan own addr bitWord cells bits m
+
+/-- Scan the entire input rectangle in order, consuming and storing one branch bit at each
+designated owner and requiring the stream to be exhausted. -/
+def firstPass (own : Fin N → Bool) (addr : Fin N ↪ Word w) (bitWord : Bool → Word w)
+ (bits : List Bool) (m : Memory w) : Option (Memory w) :=
+ scan own addr bitWord (List.finRange N) bits m
+
+private theorem scan_accepts (own : Fin N → Bool) (addr : Fin N ↪ Word w) (bitWord : Bool → Word w)
+ (cells : List (Fin N)) (bits : List Bool) (m : Memory w) :
+ (scan own addr bitWord cells bits m).isSome ↔ bits.length = (cells.filter own).length := by
+ induction cells generalizing bits m with
+ | nil => cases bits <;> simp [scan]
+ | cons i cells ih => cases h : own i <;> cases bits <;> simp [scan, h, ih]
+
+/-- Both a short stream and a stream with extra branch choices reject. -/
+theorem firstPass_accepts (own : Fin N → Bool) (addr : Fin N ↪ Word w) (bitWord : Bool → Word w)
+ (bits : List Bool) (m : Memory w) :
+ (firstPass own addr bitWord bits m).isSome ↔ bits.length = (owners own).length :=
+ scan_accepts ..
+
+/-- Accepted streams are in bijection with all assignments, for arbitrary initial memory. -/
+def admissibleEquiv (own : Fin N → Bool) (addr : Fin N ↪ Word w) (bitWord : Bool → Word w)
+ (m : Memory w) : {bs : List Bool // (firstPass own addr bitWord bs m).isSome} ≃ Assignment own :=
+ (Equiv.subtypeEquivRight (fun bs ↦ firstPass_accepts own addr bitWord bs m)).trans (branchEquiv own)
+
+/-- Each selected position receives its prescribed word, independent of old scratch contents. -/
+def store (addr : Fin N ↪ Word w) (values : Fin N → Word w) :
+ List (Fin N) → Memory w → Memory w
+ | [], m => m
+ | i :: cells, m => store addr values cells (writeMemory m (addr i) (values i))
+
+private theorem scan_assignment (own : Fin N → Bool) (addr : Fin N ↪ Word w) (bitWord : Bool → Word w)
+ (f : Fin N → Bool) (cells : List (Fin N)) (m : Memory w) :
+ scan own addr bitWord cells ((cells.filter own).map f) m =
+ some (store addr (bitWord ∘ f) (cells.filter own) m) := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih => cases h : own i <;> simp [scan, store, h, ih]
+
+theorem firstPass_branches (own : Fin N → Bool) (addr : Fin N ↪ Word w) (bitWord : Bool → Word w)
+ (f : Assignment own) (m : Memory w) :
+ firstPass own addr bitWord (branches f) m = some (store addr (bitWord ∘ bitAt f) (owners own) m) :=
+ scan_assignment ..
+
+/-- Addresses outside the writes keep their original words, including all headers in
+an address range disjoint from the scratch array. -/
+theorem store_outside (addr : Fin N ↪ Word w) (values : Fin N → Word w) (cells : List (Fin N))
+ (m : Memory w) (a : ℕ) (ha : ∀ i ∈ cells, a ≠ (addr i).val) :
+ store addr values cells m a = m a := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih =>
+ rw [store, ih _ (fun j hj ↦ ha j (List.mem_cons_of_mem _ hj))]
+ simp [writeMemory, ha i (List.mem_cons_self ..)]
+
+theorem store_at (addr : Fin N ↪ Word w) (values : Fin N → Word w) (cells : List (Fin N))
+ (m : Memory w) {i : Fin N} (hi : i ∈ cells) : store addr values cells m (addr i).val = values i := by
+ induction cells generalizing m with
+ | nil => simp at hi
+ | cons j cells ih =>
+ by_cases hit : i ∈ cells
+ · exact ih _ hit
+ · have he : i = j := (List.mem_cons.mp hi).resolve_right hit
+ subst j
+ rw [store, store_outside]
+ · simp [writeMemory]
+ · intro j hj h
+ exact hit (addr.injective (Fin.ext h) ▸ hj)
+
+/-- A contiguous rectangular scratch region following the headers. -/
+def scratchAddress (base : ℕ) (fit : base + N ≤ 2 ^ w) : Fin N ↪ Word w where
+ toFun i := ⟨base + i.val, (Nat.add_lt_add_left i.isLt base).trans_le fit⟩
+ inj' _ _ h := Fin.ext (Nat.add_left_cancel (congrArg Fin.val h))
+
+theorem store_header (base : ℕ) (fit : base + N ≤ 2 ^ w) (values : Fin N → Word w)
+ (cells : List (Fin N)) (m : Memory w) {a : ℕ} (ha : a < base) :
+ store (scratchAddress base fit) values cells m a = m a := by
+ apply store_outside
+ intro i _
+ change a ≠ base + i.val
+ omega
+
+/-- A per-cell report, retaining the actual choice even when the overwritten word already
+has the chosen value. `next` allows the caller to supply the encoded successor cursor. -/
+def cellReport (own : Bool) (addr next : Word w) (bitWord : Bool → Word w) (b : Bool) : Report w :=
+ ⟨if own then [.choice b, .write addr (bitWord b)] else [], some next⟩
+
+theorem execute_cellReport (own : Bool) (addr next : Word w) (bitWord : Bool → Word w)
+ (m : Memory w) (b : Bool) :
+ execute (cellCall own addr next bitWord) 3 .visit m (if own then [b] else []) =
+ some (cellReport own addr next bitWord b) := by cases own <;> rfl
+
+/-- Genuine per-cell reports for the first pass in its cursor order. -/
+def reports (own : Fin N → Bool) (addr : Fin N ↪ Word w) (next : Fin N → Word w)
+ (bitWord : Bool → Word w) (f : Fin N → Bool) (cells : List (Fin N)) : List (Report w) :=
+ cells.map (fun i ↦ cellReport (own i) (addr i) (next i) bitWord (f i))
+
+/-- Replaying the actual event reports gives exactly the scratch updates. -/
+theorem after_reports (own : Fin N → Bool) (addr : Fin N ↪ Word w) (next : Fin N → Word w)
+ (bitWord : Bool → Word w) (f : Fin N → Bool) (cells : List (Fin N)) (m : Memory w) :
+ after m ((reports own addr next bitWord f cells).map Report.events).flatten =
+ store addr (bitWord ∘ f) (cells.filter own) m := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih =>
+ cases h : own i <;>
+ simpa [reports, cellReport, h, store, after, update] using ih (m := _)
+
+/-- The paper charges one unit to start every call and one for every scratch write. -/
+theorem reports_cost (own : Fin N → Bool) (addr : Fin N ↪ Word w) (next : Fin N → Word w)
+ (bitWord : Bool → Word w) (f : Fin N → Bool) (cells : List (Fin N)) :
+ RAMBuckets.cost Report.probes (reports own addr next bitWord f cells) =
+ cells.length + (cells.filter own).length := by
+ induction cells with
+ | nil => rfl
+ | cons i cells ih =>
+ cases h : own i <;>
+ simp [reports, cellReport, h, RAMBuckets.cost, Report.probes, countProbes] at ih ⊢ <;> omega
+
+/-- At most one write probe and one call per cell. Unselected cells only use their call. -/
+theorem firstPass_budget (own : Fin N → Bool) :
+ (List.finRange N).length = N ∧ (owners own).length ≤ N ∧
+ (List.finRange N).length + (owners own).length ≤ 2*N := by
+ have := owners_length_le own
+ simp only [List.length_finRange]
+ exact ⟨trivial, this, by omega⟩
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMCopy.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMCopy.lean
new file mode 100644
index 0000000000..80ec8dfd5a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMCopy.lean
@@ -0,0 +1,165 @@
+import OAI.Computability.VPVNP.PrimedInputRAMChoices
+
+/-!
+# Assembling the inputs to the primed parses
+
+The second pass of Section 11 copies the prescribed literal or a word from its designated
+source to each rectangular output position. The first-pass scratch and header addresses
+are separate from the output region. The machine copies the bits even when the assembled
+primed message would fail a validator at a primed site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM
+
+variable {N w : ℕ}
+
+/-- The value of a copied input cell is either an immediate word or a word read from external
+memory. -/
+inductive CopySource (w : ℕ)
+ | literal (value : Word w)
+ | fetch (address : Word w)
+
+/-- Read the indicated word, or take the literal without an external probe. -/
+def CopySource.get (m : Memory w) : CopySource w → Word w
+ | .literal v => v
+ | .fetch a => m a.val
+
+/-- The source addresses carrying choices and headers are disjoint from the output array. -/
+def CopySeparated (dest : Fin N ↪ Word w) (source : Fin N → CopySource w) : Prop :=
+ ∀ i j a, source i = .fetch a → a ≠ dest j
+
+private theorem get_writeMemory (dest : Fin N ↪ Word w) (source : Fin N → CopySource w)
+ (hsep : CopySeparated dest source) (m : Memory w) (i j : Fin N) (v : Word w) :
+ CopySource.get (writeMemory m (dest j) v) (source i) = CopySource.get m (source i) := by
+ cases h : source i with
+ | literal => rfl
+ | fetch a =>
+ have ha : a.val ≠ (dest j).val := fun h' ↦ hsep i j a h (Fin.ext h')
+ simp [CopySource.get, writeMemory, ha]
+
+/-- The copy loop reads each input from the current memory. -/
+def scanCopies (dest : Fin N ↪ Word w) (source : Fin N → CopySource w) :
+ List (Fin N) → Memory w → Memory w
+ | [], m => m
+ | i :: cells, m => scanCopies dest source cells (writeMemory m (dest i) (CopySource.get m (source i)))
+
+/-- Assemble all endpoint positions in ascending rectangular address order. -/
+def secondPass (dest : Fin N ↪ Word w) (source : Fin N → CopySource w) (m : Memory w) : Memory w :=
+ scanCopies dest source (List.finRange N) m
+
+/-- Because the output does not overwrite a source, every read sees the word left by
+initialization or by the first pass. -/
+theorem scanCopies_store (dest : Fin N ↪ Word w) (source : Fin N → CopySource w)
+ (hsep : CopySeparated dest source) (cells : List (Fin N)) (m : Memory w) :
+ scanCopies dest source cells m = store dest (fun i ↦ CopySource.get m (source i)) cells m := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih =>
+ rw [scanCopies, store, ih]
+ congr 1
+ funext j
+ exact get_writeMemory dest source hsep m j i _
+
+theorem secondPass_at (dest : Fin N ↪ Word w) (source : Fin N → CopySource w) (m : Memory w)
+ (hsep : CopySeparated dest source) (i : Fin N) :
+ secondPass dest source m (dest i).val = CopySource.get m (source i) := by
+ rw [secondPass, scanCopies_store dest source hsep]
+ exact store_at _ _ _ _ (by simp)
+
+/-- Every address outside the assembled array keeps its initial value, even in a layout
+where some source addresses overlap with output addresses. -/
+theorem secondPass_outside (dest : Fin N ↪ Word w) (source : Fin N → CopySource w) (m : Memory w)
+ (a : ℕ) (ha : ∀ i, a ≠ (dest i).val) : secondPass dest source m a = m a := by
+ have h (cells : List (Fin N)) (mem : Memory w) : scanCopies dest source cells mem a = mem a := by
+ induction cells generalizing mem with
+ | nil => rfl
+ | cons i cells ih => rw [scanCopies, ih]; simp [writeMemory, ha]
+ exact h _ _
+
+/-- Private control for one item: fetch a source if necessary, write the word, then
+return the next public cursor. -/
+inductive CopyControl (w : ℕ)
+ | visit
+ | write (value : Word w)
+ | done
+
+/-- One deterministic burst that obtains a source word, writes it to the destination and
+returns the next cursor. -/
+def copyCall (src : CopySource w) (dest next : Word w) : Program w (CopyControl w) where
+ start _ := .visit
+ step
+ | .visit => match src with
+ | .literal v => .write dest v .done
+ | .fetch a => .read a CopyControl.write
+ | .write v => .write dest v .done
+ | .done => .finish (some next)
+
+/-- Exact copy trace and successor cursor, including a source read when the word comes from
+memory. -/
+def copyReport (src : CopySource w) (dest next : Word w) (m : Memory w) : Report w :=
+ ⟨match src with
+ | .literal v => [.write dest v]
+ | .fetch a => [.read a (m a.val), .write dest (m a.val)], some next⟩
+
+/-- Each deterministic call finishes in at most three elementary RAM instructions. -/
+theorem execute_copyCall (src : CopySource w) (dest next : Word w) (m : Memory w) :
+ execute (copyCall src dest next) 3 .visit m [] = some (copyReport src dest next m) := by
+ cases src <;> rfl
+
+theorem after_copyReport (src : CopySource w) (dest next : Word w) (m : Memory w) :
+ after m (copyReport src dest next m).events = writeMemory m dest (CopySource.get m src) := by
+ cases src <;> rfl
+
+/-- Reports generated by the actual memory reads and writes of the loop. -/
+def copyReports (dest : Fin N ↪ Word w) (source : Fin N → CopySource w) (next : Fin N → Word w) :
+ List (Fin N) → Memory w → List (Report w)
+ | [], _ => []
+ | i :: cells, m => copyReport (source i) (dest i) (next i) m ::
+ copyReports dest source next cells (writeMemory m (dest i) (CopySource.get m (source i)))
+
+/-- Replaying the reports exactly implements the second-pass memory update. -/
+theorem after_copyReports (dest : Fin N ↪ Word w) (source : Fin N → CopySource w)
+ (next : Fin N → Word w) (cells : List (Fin N)) (m : Memory w) :
+ after m ((copyReports dest source next cells m).map Report.events).flatten =
+ scanCopies dest source cells m := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih =>
+ simp only [copyReports, List.map_cons, List.flatten_cons, scanCopies]
+ rw [show ∀ es tail, after m (es ++ tail) = after (after m es) tail by simp [after]]
+ rw [after_copyReport, ih]
+
+/-- All recorded reads use their actual values in external memory. -/
+theorem correct_copyReports (dest : Fin N ↪ Word w) (source : Fin N → CopySource w)
+ (next : Fin N → Word w) (cells : List (Fin N)) (m : Memory w) :
+ Correct m ((copyReports dest source next cells m).map Report.events).flatten := by
+ induction cells generalizing m with
+ | nil => trivial
+ | cons i cells ih =>
+ cases h : source i <;>
+ simp [copyReports, h, copyReport, CopySource.get, Correct, update, ih]
+
+/-- One call and at most two probes per position, regardless of the copied values. -/
+theorem copyReports_cost_le (dest : Fin N ↪ Word w) (source : Fin N → CopySource w)
+ (next : Fin N → Word w) (cells : List (Fin N)) (m : Memory w) :
+ RAMBuckets.cost Report.probes (copyReports dest source next cells m) ≤ 3 * cells.length := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih =>
+ have h := ih (writeMemory m (dest i) (CopySource.get m (source i)))
+ have hp : (copyReport (source i) (dest i) (next i) m).probes ≤ 2 := by
+ cases source i <;> simp [copyReport, Report.probes, countProbes]
+ simp only [copyReports, RAMBuckets.cost, List.length_cons]
+ omega
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMDispatch.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMDispatch.lean
new file mode 100644
index 0000000000..0581e66154
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMDispatch.lean
@@ -0,0 +1,264 @@
+import OAI.Computability.VPVNP.PrimedInputRAM
+import OAI.Computability.VPVNP.PrimedInputRAMAddresses
+
+/-!
+# Arithmetic dispatch for each position in the pair counter
+
+The two passes of Section 11 enumerate the rectangular input positions in
+row-major order. Division and remainder identify the group, site, and tape
+offset. Comparisons with the public field boundaries decide whether the bit
+is literal, comes from a header word, or must be read at a designated
+scratch address. The same computation marks the first-pass branch sites.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM RAMLayout RAMSerialization
+
+/-- Raw addresses precede conversion to the bounded address word. -/
+inductive RawCopy where
+ | literal (value : Bool)
+ | fetch (address : ℕ)
+
+/-- The group, site and tape bit designate a row-major scratch word. -/
+def rectangleAddress (base n r g v j : ℕ) : ℕ :=
+ base + (2 ^ r * g + v) * n + j
+
+private abbrev Decision := RawCopy × Bool
+
+private def zero : Decision := (.literal false, false)
+
+/-- Decide which of the header and path bits to fetch. The middle cut
+always resides in the outgoing cut slot of group zero. -/
+def dispatchHeader (L : Lengths) (base n r P g v j : ℕ) : Decision :=
+ let middle := RawCopy.fetch (rectangleAddress base n r 0 v (P + r + 3))
+ match j with
+ | 0 => if v < L.index then (.fetch (3 + g * L.index + v), false) else zero
+ | 1 => if v < L.advice then (.fetch (3 + 2 * L.index + v), false) else zero
+ | 2 =>
+ if g = 0 then
+ if v < L.leftCut then (.fetch (3 + 2 * L.index + L.advice + v), false) else zero
+ else if v < L.middleCut then (middle, false) else zero
+ | _ =>
+ if g = 0 then
+ if v < L.middleCut then (middle, true) else zero
+ else if v < L.rightCut then (.fetch (3 + 2 * L.index + L.advice + L.cutCapacity + v), false)
+ else zero
+
+/-- Resolve the transcript part of the row. No parsing is applied to
+the data at the designated location. -/
+def dispatchPort (base n r H w P g v k : ℕ) : Decision × ℕ :=
+ let sender := rawSource r H w v k
+ match sender.1 with
+ | none => (zero, sender.2 + 1)
+ | some (u, t) =>
+ ((.fetch (rectangleAddress base n r g u (P + r + 4 + t)), decide (u = v ∧ t = k)),
+ sender.2 + 14)
+
+/-- Dispatch within one row. The prefix is a private public-data array, and
+the field lengths and widths are public registers. Charges cover boundary
+arithmetic, comparisons, branching, and the calculation of the result. -/
+def dispatchRow (L : Lengths) (n r H w base P : ℕ) (prefixAt : ℕ → Bool) (g v j : ℕ) :
+ Decision × ℕ :=
+ if j < P then ((.literal (prefixAt j), false), 3)
+ else if j < P + r then ((.literal (v.testBit (j - P)), false), 8)
+ else if j < P + r + 4 then (dispatchHeader L base n r P g v (j - (P + r)), 26)
+ else if j < P + r + 4 + width r H w then
+ let result := dispatchPort base n r H w P g v (j - (P + r + 4))
+ (result.1, result.2 + 12)
+ else (zero, 12)
+
+/-- Scalar program, with group, site and within-row bit extracted from the
+enumeration counter. The four quotient/remainder operations and the shift
+constructing `2^r` cost five word steps. -/
+def dispatch (L : Lengths) (n r H w base P : ℕ) (prefixAt : ℕ → Bool) (i : ℕ) :
+ Decision × ℕ :=
+ let row := i / n
+ let result := dispatchRow L n r H w base P prefixAt (row / 2 ^ r) (row % 2 ^ r) (i % n)
+ (result.1, result.2 + 5)
+
+theorem dispatch_work (L : Lengths) (n r H w base P : ℕ) (prefixAt : ℕ → Bool) (i : ℕ) :
+ (dispatch L n r H w base P prefixAt i).2 ≤ 6 * r + 63 := by
+ simp only [dispatch, dispatchRow]
+ split_ifs <;> try omega
+ rename_i hj
+ have h := rawSource_work r H w (i / n % 2 ^ r) (i % n - (P + r + 4))
+ simp only [dispatchPort]
+ split <;> omega
+
+variable {L : Lengths} {n r H w : ℕ}
+
+namespace Layout
+
+variable (Q : Layout L n r H w)
+
+private abbrev P := (UniversalMachine.programPrefix Q.program).length
+
+/-- The prefix table is indexed in private storage and padded by zero. -/
+def prefixAt (j : ℕ) : Bool := (UniversalMachine.programPrefix Q.program)[j]?.getD false
+
+private def rawRef : Ref L r H w → RawCopy
+ | .literal b => .literal b
+ | .header j => .fetch j.address.val
+ | .shared b => .fetch (Q.bitAddress (Q.internalOwner b).val).val
+
+private theorem middle_raw (v : Fin L.middleCut) :
+ Q.rawRef (.shared (.inl v)) =
+ .fetch (rectangleAddress Q.scratchBase n r 0 v.val (Q.P + r + 3)) := by
+ unfold rawRef
+ apply congrArg RawCopy.fetch
+ change Q.scratchBase + (Q.P + (r + 3) + n * (v.val + 2 ^ r * 0)) = _
+ simp [rectangleAddress, Nat.mul_comm, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm]
+
+private theorem port_raw (g : Fin 2) (p : SharedBit r H w) :
+ Q.rawRef (.shared (.inr (g, p))) = .fetch (rectangleAddress Q.scratchBase n r g.val p.val.1.val
+ (Q.P + r + 4 + (offset r H w p.val.2).val)) := by
+ unfold rawRef
+ apply congrArg RawCopy.fetch
+ change Q.scratchBase + (Q.P + (r + (4 + (offset r H w p.val.2).val)) +
+ n * (p.val.1.val + 2 ^ r * g.val)) = _
+ simp [rectangleAddress, Nat.mul_comm, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm]
+
+private theorem dispatchHeader_eq (g : Fin 2) (v : Fin (2 ^ r)) (j : Fin 4) :
+ dispatchHeader L Q.scratchBase n r Q.P g.val v.val j.val =
+ (Q.rawRef (headerRef L g v j), decide (j = 3 ∧ g = 0 ∧ v.val < L.middleCut)) := by
+ fin_cases j <;> fin_cases g <;>
+ simp [dispatchHeader, headerRef, zero] <;>
+ split_ifs <;> (try simp only [middle_raw]) <;> simp_all [rawRef, Header.address, rectangleAddress]
+
+private theorem dispatchPort_eq (g : Fin 2) (v : Fin (2 ^ r)) (p : Slot r H w) :
+ (dispatchPort Q.scratchBase n r H w Q.P g.val v.val (offset r H w p).val).1 =
+ (Q.rawRef (cellRef L (UniversalMachine.programPrefix Q.program).get
+ ((g,v), (.inr (.inr (.inr (.inl p))) : RowField Q.program n r H w))), decide (IsSend (v,p))) := by
+ simp only [cellRef]
+ split
+ · rename_i hs
+ have hd : ¬ IsSend (v, p) := by
+ intro h
+ have he := (sourcePort_eq_self_iff _).mpr ((designated_iff _).mpr h)
+ rw [sourcePort_eq_source, hs] at he
+ contradiction
+ simp [dispatchPort, rawSource_offset, sourcePort_eq_source, hs, zero, rawRef, hd]
+ · rename_i y hs
+ simp only [dispatchPort, rawSource_offset, sourcePort_eq_source, hs, Option.map_some]
+ rw [port_raw]
+ have he : y.1.val = v.val ∧ (offset r H w y.2).val = (offset r H w p).val ↔ IsSend (v, p) := by
+ rw [← designated_iff, ← sourcePort_eq_self_iff, sourcePort_eq_source, hs, Option.some.injEq]
+ constructor
+ · rintro ⟨ha,hb⟩
+ exact Prod.ext (Fin.ext ha) ((offset r H w).injective (Fin.ext hb))
+ · rintro rfl
+ exact ⟨rfl, rfl⟩
+ rw [decide_eq_decide.mpr he]
+
+private theorem testBit_wordBits (v : Word r) (a : Fin r) : v.val.testBit a.val = wordBits r v a := by
+ rw [Nat.testBit_eq_decide_div_mod_eq]
+ change decide (v.val / 2 ^ a.val % 2 = 1) = (finFunctionFinEquiv.symm v a == 1)
+ rw [Bool.eq_iff_iff, decide_eq_true_iff, beq_iff_eq, Fin.ext_iff, finFunctionFinEquiv_symm_apply_val]
+ rfl
+
+private theorem dispatchRow_eq (g : Fin 2) (v : Fin (2 ^ r)) (f : RowField Q.program n r H w) :
+ (dispatchRow L n r H w Q.scratchBase Q.P Q.prefixAt g.val v.val (rowIndex Q.program Q.fits f).val).1 =
+ (Q.rawRef (cellRef L (UniversalMachine.programPrefix Q.program).get ((g,v), f)),
+ cellOwner L ((g,v), f)) := by
+ rcases f with p | (a | (t | (port | pad)))
+ · change (dispatchRow _ _ _ _ _ _ _ _ _ _ p.val).1 = (.literal _, false)
+ have hp : p.val < Q.P := p.isLt
+ simp [dispatchRow, hp, prefixAt]
+ · change (dispatchRow _ _ _ _ _ _ _ _ _ _ (Q.P + a.val)).1 = (.literal (wordBits r v a), false)
+ have ha := a.isLt
+ rw [dispatchRow, ite_eq_right (by omega), ite_eq_left (by omega), Nat.add_sub_cancel_left,
+ testBit_wordBits]
+ · change (dispatchRow _ _ _ _ _ _ _ _ _ _ (Q.P + (r + t.val))).1 = _
+ have ht := t.isLt
+ rw [dispatchRow, ite_eq_right (by omega), ite_eq_right (by omega), ite_eq_left (by omega)]
+ rw [show Q.P + (r + t.val) - (Q.P + r) = t.val by omega]
+ exact Q.dispatchHeader_eq g v t
+ · let k := (offset r H w port).val
+ change (dispatchRow _ _ _ _ _ _ _ _ _ _ (Q.P + (r + (4 + k)))).1 = _
+ have hk : k < width r H w := (offset r H w port).isLt
+ rw [dispatchRow, ite_eq_right (by omega), ite_eq_right (by omega), ite_eq_right (by omega),
+ ite_eq_left (by omega)]
+ rw [show Q.P + (r + (4 + k)) - (Q.P + r + 4) = k by omega]
+ exact Q.dispatchPort_eq g v port
+ · change (dispatchRow _ _ _ _ _ _ _ _ _ _ (Q.P + (r + (4 + (width r H w + pad.val))))).1 = zero
+ rw [dispatchRow, ite_eq_right (by omega), ite_eq_right (by omega), ite_eq_right (by omega),
+ ite_eq_right (by omega)]
+
+private theorem dispatch_coordinates (g : Fin 2) (v : Fin (2 ^ r)) (f : RowField Q.program n r H w) :
+ (PrimedInputRAM.dispatch L n r H w Q.scratchBase Q.P Q.prefixAt (Q.coordinates ((g,v), f)).val).1 =
+ (Q.rawRef (cellRef L (UniversalMachine.programPrefix Q.program).get ((g,v), f)),
+ cellOwner L ((g,v), f)) := by
+ let j := (rowIndex Q.program Q.fits f).val
+ have hj : j < n := (rowIndex Q.program Q.fits f).isLt
+ let row := v.val + 2 ^ r * g.val
+ have hq : (Q.coordinates ((g,v), f)).val = j + n * row := rfl
+ have hrow : (j + n * row) / n = row := by
+ rw [Nat.add_mul_div_left _ _ (by omega), Nat.div_eq_of_lt hj, Nat.zero_add]
+ have hbit : (j + n * row) % n = j := by simp [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hj]
+ have hg : row / 2 ^ r = g.val := by
+ rw [show row = v.val + 2 ^ r * g.val by rfl, Nat.add_mul_div_left _ _ (Nat.two_pow_pos r),
+ Nat.div_eq_of_lt v.isLt, Nat.zero_add]
+ have hv : row % 2 ^ r = v.val := by simp [row, Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt v.isLt]
+ simp only [PrimedInputRAM.dispatch, hq, hrow, hbit, hg, hv]
+ exact Q.dispatchRow_eq g v f
+
+/-- Every header or scratch address returned by the natural-number
+calculation fits the physical address word before the conversion. -/
+theorem dispatch_fetch_lt (i : Fin (positions n r)) {a : ℕ}
+ (ha : (PrimedInputRAM.dispatch L n r H w Q.scratchBase
+ (UniversalMachine.programPrefix Q.program).length Q.prefixAt i.val).1.1 = .fetch a) : a < 2 ^ w := by
+ obtain ⟨⟨⟨g,v⟩, f⟩, rfl⟩ := Q.coordinates.surjective i
+ rw [Q.dispatch_coordinates g v f] at ha
+ cases hr : cellRef L (UniversalMachine.programPrefix Q.program).get ((g,v), f) with
+ | literal b => simp [hr, rawRef] at ha
+ | header j =>
+ simp [hr, rawRef] at ha
+ exact ha ▸ (Q.readHeader j).isLt
+ | shared b =>
+ simp [hr, rawRef] at ha
+ exact ha ▸ (Q.bitAddress (Q.internalOwner b).val).isLt
+
+/-- Convert the arithmetic result into the actual source instruction of a
+bounded-word burst RAM. At every valid position the fetch address fits. -/
+def compileCopy (bitWord : Bool → Word w) : RawCopy → CopySource w
+ | .literal b => .literal (bitWord b)
+ | .fetch a => .fetch (Fin.ofNat (2 ^ w) a)
+
+private theorem compile_rawRef (bitWord : Bool → Word w) (ref : Ref L r H w) :
+ compileCopy bitWord (Q.rawRef ref) = Q.refSource bitWord ref := by
+ cases ref with
+ | literal b => rfl
+ | header j =>
+ apply congrArg CopySource.fetch
+ exact Fin.ext (Nat.mod_eq_of_lt (Q.readHeader j).isLt)
+ | shared b =>
+ apply congrArg CopySource.fetch
+ exact Fin.ext (Nat.mod_eq_of_lt (Q.bitAddress (Q.internalOwner b).val).isLt)
+
+/-- Both instructions needed by the two loops at this flattened position. -/
+def dispatch (bitWord : Bool → Word w) (i : Fin (positions n r)) : CopySource w × Bool :=
+ let d := PrimedInputRAM.dispatch L n r H w Q.scratchBase Q.P Q.prefixAt i.val
+ (compileCopy bitWord d.1.1, d.1.2)
+
+/-- The scalar dispatcher recovers both the second-pass copy source and
+the first-pass owner decision at every position. -/
+theorem dispatch_eq (bitWord : Bool → Word w) (i : Fin (positions n r)) :
+ Q.dispatch bitWord i = (Q.source bitWord i, Q.owns i) := by
+ obtain ⟨⟨⟨g,v⟩, f⟩, rfl⟩ := Q.coordinates.surjective i
+ change (compileCopy bitWord (PrimedInputRAM.dispatch _ _ _ _ _ _ _ _ _).1.1, _) =
+ (Q.refSource bitWord (cellRef L (UniversalMachine.programPrefix Q.program).get
+ (Q.coordinates.symm (Q.coordinates ((g,v),f)))),
+ cellOwner L (Q.coordinates.symm (Q.coordinates ((g,v),f))))
+ rw [Equiv.symm_apply_apply, Q.dispatch_coordinates g v f, Q.compile_rawRef]
+
+end Layout
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMExecution.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMExecution.lean
new file mode 100644
index 0000000000..325a72c6b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMExecution.lean
@@ -0,0 +1,198 @@
+import OAI.Computability.VPVNP.PrimedInputRAMSchedule
+
+/-!
+# Complete native execution of the cursor-controlled input program
+
+Every accepting native path performs the entire public schedule followed by one
+halt call. Its only private branch bits are those at the scheduled choice positions.
+Conversely, every such assignment determines all reads, writes and reports uniquely.
+The prefix theorem allows replacing the terminal call with the grammar parser.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM
+
+variable {M w : ℕ}
+
+/-- Final memory obtained by executing the indicated cursor items. -/
+def scheduledMemory (ops : Fin M → Item w) (bitWord : Bool → Word w) (f : Fin M → Bool) :
+ List (Fin M) → Memory w → Memory w
+ | [], m => m
+ | i :: xs, m => scheduledMemory ops bitWord f xs ((ops i).memory bitWord m (f i))
+
+theorem after_scheduledReports (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w)
+ (f : Fin M → Bool) (xs : List (Fin M)) (m : Memory w) :
+ after m (eventLog (scheduledReports ops bitWord fit f xs m)) = scheduledMemory ops bitWord f xs m := by
+ induction xs generalizing m with
+ | nil => rfl
+ | cons i xs ih =>
+ simp only [scheduledReports, eventLog, List.flatMap_cons, scheduledMemory]
+ rw [show ∀ es tail, after m (es ++ tail) = after (after m es) tail by simp [after]]
+ rw [Item.after_report]
+ exact ih _
+
+/-- The remaining cells form the consecutive suffix beginning at cursor k and ending at the
+exclusive schedule bound. -/
+def Aligned (k : ℕ) (cells : List (Fin M)) : Prop :=
+ cells.map Fin.val = List.range' k cells.length ∧ k + cells.length = M
+
+theorem aligned_all (M : ℕ) : Aligned 0 (List.finRange M) := by
+ constructor
+ · apply List.ext_getElem (by simp)
+ intro i _ _
+ simp
+ · simp
+
+theorem aligned_cons {k : ℕ} {i : Fin M} {xs : List (Fin M)} (ha : Aligned k (i::xs)) :
+ i.val = k ∧ Aligned (k+1) xs := by
+ obtain ⟨he, hl⟩ := ha
+ simp only [List.map_cons, List.length_cons, List.range'_succ, List.cons.injEq] at he
+ exact ⟨he.1, he.2, by simp only [List.length_cons] at hl; omega⟩
+
+theorem aligned_fresh {k : ℕ} {i : Fin M} {xs : List (Fin M)} (ha : Aligned k (i::xs)) :
+ i ∉ xs := by
+ obtain ⟨hi, ht, _⟩ := aligned_cons ha
+ intro hm
+ have hval : i.val ∈ xs.map Fin.val := List.mem_map_of_mem hm
+ rw [ht, List.mem_range'_1, hi] at hval
+ omega
+
+private theorem run_prefix_aux {C : Type*} (P : Program w C) (fuel : ℕ) (ops : Fin M → Item w)
+ (bitWord : Bool → Word w) (fit : M < 2^w)
+ (hstep : ∀ (i : Fin M) (m : Memory w) (b : Bool),
+ execute P fuel (P.start (cursor fit i.val i.isLt.le)) m ((ops i).bits b) =
+ some ((ops i).report bitWord (successor fit i) m b)) (f : Fin M → Bool) (cells : List (Fin M)) (k : ℕ) (hk : k ≤ M) (ha : Aligned k cells)
+ (m : Memory w) (tail : List (List Bool)) :
+ runSegment P fuel (some (cursor fit k hk)) m
+ (cells.map (fun i ↦ (ops i).bits (f i)) ++ tail) =
+ (runSegment P fuel (some (cursor fit M le_rfl))
+ (scheduledMemory ops bitWord f cells m) tail).map
+ (fun ts ↦ scheduledReports ops bitWord fit f cells m ++ ts) := by
+ induction cells generalizing k m with
+ | nil =>
+ have he : k = M := by simpa using ha.2
+ subst k
+ simp [scheduledReports, scheduledMemory]
+ | cons i xs ih =>
+ obtain ⟨hi, ht⟩ := aligned_cons ha
+ subst k
+ simp only [List.map_cons, List.cons_append, runSegment, hstep,
+ Item.after_report, Item.report_result, scheduledReports, scheduledMemory]
+ rw [show successor fit i = cursor fit (i.val+1) i.isLt by rfl, ih _ _ ht]
+ simp only [Option.map_map, Function.comp_def]
+
+/-- Stitch this input stage to any following program with the same data calls. At cursor
+`M` its continuation can start the grammar parser; the prefix fixes its memory and leaves
+its private choice streams untouched. -/
+theorem splice_scheduledPrefix {C : Type*} (P : Program w C) (fuel : ℕ) (ops : Fin M → Item w)
+ (bitWord : Bool → Word w) (fit : M < 2^w)
+ (hstep : ∀ (i : Fin M) (m : Memory w) (b : Bool),
+ execute P fuel (P.start (cursor fit i.val i.isLt.le)) m ((ops i).bits b) =
+ some ((ops i).report bitWord (successor fit i) m b))
+ (f : Fin M → Bool) (m : Memory w) (tail : List (List Bool)) :
+ runSegment P fuel (some 0) m ((List.finRange M).map (fun i ↦ (ops i).bits (f i)) ++ tail) =
+ (runSegment P fuel (some (cursor fit M le_rfl)) (scheduledMemory ops bitWord f (List.finRange M) m)
+ tail).map (fun ts ↦ scheduledReports ops bitWord fit f (List.finRange M) m ++ ts) :=
+ run_prefix_aux P fuel ops bitWord fit hstep f _ 0 (Nat.zero_le _) (aligned_all M) m tail
+
+/-- Execute the data calls and supply an arbitrary continuation from the terminal cursor. -/
+theorem scheduled_prefix (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w)
+ (f : Fin M → Bool) (m : Memory w) (tail : List (List Bool)) :
+ runSegment (scheduledProgram ops bitWord fit) 3 (some 0) m
+ ((List.finRange M).map (fun i ↦ (ops i).bits (f i)) ++ tail) =
+ (runSegment (scheduledProgram ops bitWord fit) 3 (some (cursor fit M le_rfl))
+ (scheduledMemory ops bitWord f (List.finRange M) m) tail).map
+ (fun ts ↦ scheduledReports ops bitWord fit f (List.finRange M) m ++ ts) :=
+ splice_scheduledPrefix _ _ _ _ _ (fun i mem b ↦ by
+ rw [start_item]
+ exact execute_item ops bitWord fit (ops i) (successor fit i) mem b) f m tail
+
+/-- Every scheduled assignment yields its complete native report list. -/
+theorem run_generated (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w)
+ (f : Fin M → Bool) (m : Memory w) :
+ runSegment (scheduledProgram ops bitWord fit) 3 (some 0) m
+ ((List.finRange M).map (fun i ↦ (ops i).bits (f i)) ++ [[]]) =
+ some (scheduledReports ops bitWord fit f (List.finRange M) m ++ [haltReport w]) := by
+ rw [scheduled_prefix, runSegment, start_halt]
+ rfl
+
+theorem unpack_call {C : Type*} (P : Program w C) (fuel : ℕ) (s : Word w) (m : Memory w)
+ (bs : List Bool) (more : List (List Bool)) (rs : List (Report w))
+ (h : runSegment P fuel (some s) m (bs::more) = some rs) :
+ ∃ r ts, execute P fuel (P.start s) m bs = some r ∧
+ runSegment P fuel r.result (after m r.events) more = some ts ∧ rs = r::ts := by
+ rw [runSegment] at h
+ cases he : execute P fuel (P.start s) m bs with
+ | none => simp [he] at h
+ | some r =>
+ simp only [he, Option.map_eq_some_iff] at h
+ obtain ⟨ts, hr, heq⟩ := h
+ exact ⟨r, ts, rfl, hr, heq.symm⟩
+
+private theorem generated_of_run (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w)
+ (cells : List (Fin M)) (k : ℕ) (hk : k ≤ M) (ha : Aligned k cells)
+ (m : Memory w) (bits : List (List Bool)) (rs : List (Report w))
+ (hr : runSegment (scheduledProgram ops bitWord fit) 3 (some (cursor fit k hk)) m bits = some rs)
+ (hend : endState (some (cursor fit k hk)) rs = none) :
+ ∃ f : Fin M → Bool, bits = cells.map (fun i ↦ (ops i).bits (f i)) ++ [[]] := by
+ induction cells generalizing k m bits rs with
+ | nil =>
+ have he : k = M := by simpa using ha.2
+ subst k
+ cases bits with
+ | nil => simp [runSegment] at hr; subst rs; contradiction
+ | cons bs more =>
+ obtain ⟨r, ts, he, ht, rfl⟩ := unpack_call _ 3 _ _ _ _ _ hr
+ rw [start_halt] at he
+ cases bs with
+ | nil =>
+ have heq : haltReport w = r := Option.some.inj he
+ subst r
+ cases more with
+ | nil => exact ⟨fun _ ↦ false, rfl⟩
+ | cons => contradiction
+ | cons => contradiction
+ | cons i xs ih =>
+ obtain ⟨hi, ht⟩ := aligned_cons ha
+ have fresh := aligned_fresh ha
+ subst k
+ cases bits with
+ | nil => simp [runSegment] at hr; subst rs; contradiction
+ | cons bs more =>
+ obtain ⟨r, ts, he, hr', rfl⟩ := unpack_call _ 3 _ _ _ _ _ hr
+ rw [start_item] at he
+ obtain ⟨b, rfl, rfl⟩ := execute_item_only _ _ _ _ _ _ _ _ he
+ simp only [Item.after_report, Item.report_result] at hr'
+ simp only [endState, Item.report_result] at hend
+ obtain ⟨f, rfl⟩ := ih _ i.isLt ht _ _ ts hr' hend
+ refine ⟨fun j ↦ if j = i then b else f j, ?_⟩
+ simp only [List.map_cons, List.cons_append, ↓reduceIte, List.cons.injEq, true_and]
+ congr 1
+ apply List.map_congr_left
+ intro j hj
+ have hne : j ≠ i := fun h ↦ fresh (h ▸ hj)
+ simp [hne]
+
+/-- The native accepting paths consist of the scheduled owner choices, with empty
+private streams for the remaining calls and the terminal halt. -/
+theorem run_accepted_iff (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w)
+ (m : Memory w) (bs : List (List Bool)) :
+ (∃ rs, runSegment (scheduledProgram ops bitWord fit) 3 (some 0) m bs = some rs ∧
+ endState (some 0) rs = none) ↔
+ ∃ f : Fin M → Bool, bs = (List.finRange M).map (fun i ↦ (ops i).bits (f i)) ++ [[]] := by
+ constructor
+ · rintro ⟨rs, hr, hend⟩
+ exact generated_of_run ops bitWord fit _ 0 (Nat.zero_le _) (aligned_all M) m bs rs hr hend
+ · rintro ⟨f, rfl⟩
+ exact ⟨_, run_generated ops bitWord fit f m, by rw [endState_append]; rfl⟩
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMFlow.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlow.lean
new file mode 100644
index 0000000000..162de59484
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlow.lean
@@ -0,0 +1,226 @@
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# Structured finite jump tables for the auxiliary burst RAM
+
+A straight-line instruction, a branch, a sequence and a loop all have
+finite sets of instruction labels. A loop introduces one test and a back
+edge to that test. Neither the width of a word nor the number of iterations
+affects the table size. Compilation maps local labels to ordinary bounded
+program counters of the fixed burst RAM template.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {r k : ℕ}
+
+/-- Fixed program text. A test reads two register words. `branch` makes one
+binary choice even when its two continuations have identical effects. -/
+inductive Flow (r k : ℕ) where
+ | line (op : Op r k)
+ | seq (a b : Flow r k)
+ | ifEq (lhs rhs : Fin r) (yes no : Flow r k)
+ | ifLt (lhs rhs : Fin r) (yes no : Flow r k)
+ | branch (yes no : Flow r k)
+ | whileLt (lhs rhs : Fin r) (body : Flow r k)
+
+namespace Flow
+
+/-- Instruction addresses are local labels. `none` designates the common
+exit and can later be linked to the next block or a return instruction. -/
+inductive Jump (pc : Type) (r k : ℕ) where
+ | line (op : Op r k) (next : pc)
+ | ifEq (lhs rhs : Fin r) (yes no : pc)
+ | ifLt (lhs rhs : Fin r) (yes no : pc)
+ | branch (yes no : pc)
+
+/-- Relabel the successor targets of a jump while preserving its instruction, operands and
+choice branches. -/
+def Jump.map {A B : Type} (f : A → B) : Jump A r k → Jump B r k
+ | .line op next => .line op (f next)
+ | .ifEq l q yes no => .ifEq l q (f yes) (f no)
+ | .ifLt l q yes no => .ifLt l q (f yes) (f no)
+ | .branch yes no => .branch (f yes) (f no)
+
+theorem Jump.map_map {A B C : Type} (f : A → B) (g : B → C) (i : Jump A r k) :
+ (i.map f).map g = i.map (g ∘ f) := by cases i <;> rfl
+
+/-- Compile a jump with bounded program counters to a burst instruction, sending failed guards
+to the supplied rejection address. -/
+def Jump.emit {p : ℕ} (bad : Fin p) : Jump (Fin p) r k → Instr 2 p r k
+ | .line op next => op.emit next bad
+ | .ifEq l q yes no => .jumpEq l q yes no
+ | .ifLt l q yes no => .jumpLt l q yes no
+ | .branch yes no => .choose yes no
+
+/-- Local program-counter type. In a compound block the sum tags identify
+the instruction's enclosing branch, body or test. -/
+def Label : Flow r k → Type
+ | .line _ => Unit
+ | .seq a b => a.Label ⊕ b.Label
+ | .ifEq _ _ a b | .ifLt _ _ a b | .branch a b => Unit ⊕ (a.Label ⊕ b.Label)
+ | .whileLt _ _ a => Unit ⊕ a.Label
+
+/-- Number of labeled instructions in the structured program, counting the tests of branches
+and loops. -/
+def length : Flow r k → ℕ
+ | .line _ => 1
+ | .seq a b => a.length + b.length
+ | .ifEq _ _ a b | .ifLt _ _ a b | .branch a b => 1 + (a.length + b.length)
+ | .whileLt _ _ a => 1 + a.length
+
+private def unitFin : Unit ≃ Fin 1 where
+ toFun _ := 0
+ invFun _ := ()
+ left_inv _ := rfl
+ right_inv i := Subsingleton.elim _ i
+
+/-- Numerical labels for the fixed instruction table. -/
+def labels : (a : Flow r k) → a.Label ≃ Fin a.length
+ | .line _ => unitFin
+ | .seq a b => ((labels a).sumCongr (labels b)).trans finSumFinEquiv
+ | .ifEq _ _ a b | .ifLt _ _ a b | .branch a b =>
+ (unitFin.sumCongr (((labels a).sumCongr (labels b)).trans finSumFinEquiv)).trans finSumFinEquiv
+ | .whileLt _ _ a => (unitFin.sumCongr (labels a)).trans finSumFinEquiv
+
+/-- First label executed when entering the structured control-flow program. -/
+def entry : (a : Flow r k) → a.Label
+ | .line _ => ()
+ | .seq a _ => .inl a.entry
+ | .ifEq .. | .ifLt .. | .branch .. | .whileLt .. => .inl ()
+
+private def link {A B : Type} (f : A → B) (exit : Option B) : Option A → Option B
+ | none => exit
+ | some a => some (f a)
+
+private def branchCode {A B : Type} (test : Jump (Option (Unit ⊕ (A ⊕ B))) r k)
+ (yes : A → Jump (Option A) r k) (no : B → Jump (Option B) r k) :
+ Unit ⊕ (A ⊕ B) → Jump (Option (Unit ⊕ (A ⊕ B))) r k
+ | .inl _ => test
+ | .inr (.inl i) => (yes i).map (Option.map (Sum.inr ∘ Sum.inl))
+ | .inr (.inr j) => (no j).map (Option.map (Sum.inr ∘ Sum.inr))
+
+/-- The complete control graph. Body exits of a loop are wired back to its
+test; exits of the first member of a sequence enter its second member. -/
+def code : (a : Flow r k) → a.Label → Jump (Option a.Label) r k
+ | .line op, _ => .line op none
+ | .seq a b, .inl i => (code a i).map (link Sum.inl (some (.inr b.entry)))
+ | .seq _ b, .inr j => (code b j).map (Option.map Sum.inr)
+ | .ifEq l q a b, i =>
+ branchCode (.ifEq l q (some (.inr (.inl a.entry))) (some (.inr (.inr b.entry))))
+ (code a) (code b) i
+ | .ifLt l q a b, i =>
+ branchCode (.ifLt l q (some (.inr (.inl a.entry))) (some (.inr (.inr b.entry))))
+ (code a) (code b) i
+ | .branch a b, i =>
+ branchCode (.branch (some (.inr (.inl a.entry))) (some (.inr (.inr b.entry))))
+ (code a) (code b) i
+ | .whileLt l q body, .inl _ => .ifLt l q (some (.inr body.entry)) none
+ | .whileLt _ _ body, .inr i => (code body i).map (link Sum.inr (some (.inl ())))
+
+/-- Bounded counter of a real instruction label. -/
+def pc (a : Flow r k) (i : a.Label) : Fin (a.length + 2) :=
+ Fin.castAdd 2 (a.labels i)
+
+/-- Program counter reserved for normal exit from the structured code. -/
+def exitPC (a : Flow r k) : Fin (a.length + 2) := ⟨a.length, by omega⟩
+/-- Program counter reserved for rejecting a failed guard in the structured code. -/
+def rejectPC (a : Flow r k) : Fin (a.length + 2) := ⟨a.length+1, by omega⟩
+
+/-- Translate an optional local successor to its compiled program counter, mapping the absent
+successor to normal exit. -/
+def target (a : Flow r k) : Option a.Label → Fin (a.length + 2)
+ | none => a.exitPC
+ | some i => a.pc i
+
+/-- The table emits exactly one finite private-RAM instruction per label,
+plus a normal exit and a rejecting exit. -/
+def template (a : Flow r k) (result : Option (Fin r)) : Template (a.length+2) r k where
+ literalWidth := 2
+ entry := a.pc a.entry
+ code i :=
+ if h : i.val < a.length then
+ ((a.code (a.labels.symm ⟨i.val,h⟩)).map a.target).emit a.rejectPC
+ else if i = a.exitPC then (match result with | none => .accept | some reg => .returnState reg)
+ else .reject
+
+theorem template_at (a : Flow r k) (result : Option (Fin r)) (i : a.Label) :
+ (a.template result).code (a.pc i) = ((a.code i).map a.target).emit a.rejectPC := by
+ simp [template, pc, (a.labels i).isLt]
+
+theorem template_exit (a : Flow r k) (result : Option (Fin r)) :
+ (a.template result).code a.exitPC = (match result with | none => .accept | some j => .returnState j) := by
+ simp [template, exitPC]
+
+theorem template_reject (a : Flow r k) (result : Option (Fin r)) :
+ (a.template result).code a.rejectPC = .reject := by
+ simp [template, rejectPC, exitPC, Fin.ext_iff, show ¬ a.length+1 < a.length by omega]
+
+/-- A block may occupy labels in a larger table. Its local normal and bad
+exits need not be the enclosing table's own exits. -/
+structure Linked {w p : ℕ} (M : Machine w p r k) (a : Flow r k)
+ (label : a.Label → Fin p) (stop bad : Fin p) : Prop where
+ atLabel : ∀ i, M.code (label i) =
+ (((a.code i).map (fun t ↦ (t.map label).getD stop)).emit bad).resize w
+
+theorem template_linked {w : ℕ} (a : Flow r k) (result : Option (Fin r)) (pub : Fin k → Word w) :
+ Linked ((a.template result).instantiate w pub) a a.pc a.exitPC a.rejectPC := by
+ constructor
+ intro i
+ change ((a.template result).code (a.pc i)).resize w = _
+ rw [template_at]
+ have htarget : a.target = fun t ↦ (t.map a.pc).getD a.exitPC := by funext t; cases t <;> rfl
+ rw [htarget]
+ rfl
+
+theorem Linked.seqLeft {w p : ℕ} {M : Machine w p r k} {a b : Flow r k}
+ {label : (a.seq b).Label → Fin p} {stop bad : Fin p}
+ (h : Linked M (a.seq b) label stop bad) :
+ Linked M a (label ∘ Sum.inl) (label (.inr b.entry)) bad := by
+ constructor
+ intro i
+ change M.code (label (.inl i)) = _
+ rw [h.atLabel (.inl i)]
+ simp only [code, Jump.map_map]
+ congr 3
+ funext t
+ cases t <;> rfl
+
+theorem Linked.seqRight {w p : ℕ} {M : Machine w p r k} {a b : Flow r k}
+ {label : (a.seq b).Label → Fin p} {stop bad : Fin p}
+ (h : Linked M (a.seq b) label stop bad) : Linked M b (label ∘ Sum.inr) stop bad := by
+ constructor
+ intro j
+ change M.code (label (.inr j)) = _
+ rw [h.atLabel (.inr j)]
+ simp only [code, Jump.map_map]
+ congr 3
+ funext t
+ cases t <;> rfl
+
+theorem Linked.loopBody {w p : ℕ} {M : Machine w p r k} {body : Flow r k} {l q : Fin r}
+ {label : (Flow.whileLt l q body).Label → Fin p} {stop bad : Fin p}
+ (h : Linked M (.whileLt l q body) label stop bad) :
+ Linked M body (label ∘ Sum.inr) (label (.inl ())) bad := by
+ constructor
+ intro j
+ change M.code (label (.inr j)) = _
+ rw [h.atLabel (.inr j)]
+ simp only [code, Jump.map_map]
+ congr 3
+ funext t
+ cases t <;> rfl
+
+end Flow
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowComplete.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowComplete.lean
new file mode 100644
index 0000000000..b066995a40
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowComplete.lean
@@ -0,0 +1,189 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-!
+# Recovering structured traces from successful native execution
+
+Every successful run of a linked block has a finite structured execution. The exit
+receives exactly the unused fuel and branch suffix. In a standalone template the exit
+is a single return instruction, so the recovered trace contains the entire event log.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Flow
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w r k p : ℕ}
+
+/-- Successful execution separates into a structured trace and its continuation. -/
+def Exits (M : Machine w p r k) (state : Word w) (priv : Word w → Word w) (stop : Fin p)
+ (a : PrimedInputRAM.Flow r k) (rs : Regs w r) (m : Memory w) (fuel : ℕ) (bits : List Bool)
+ (out : Report w) : Prop :=
+ ∃ es rs' m' left bs tail,
+ Exec M.publicData state a rs m es rs' m' ∧ fuel = es.length + left ∧ bits = choiceBits es ++ bs ∧
+ execute M.program left ⟨stop, state, rs', priv⟩ m' bs = some tail ∧ out = prependEvents es tail
+
+private theorem positive {pub : Fin k → Word w} {state : Word w} {a : PrimedInputRAM.Flow r k} {rs m es rs' m'}
+ (h : Exec pub state a rs m es rs' m') : 0 < es.length := by
+ induction h <;> simp_all
+ omega
+
+private theorem exits_prepend {M : Machine w p r k} {state : Word w} {priv stop a b rs m fuel bits out}
+ {e : Event w} (h : Exits M state priv stop b rs m fuel bits out)
+ (lift : ∀ {es rs' m'}, Exec M.publicData state b rs m es rs' m' →
+ Exec M.publicData state a rs m (e :: es) rs' m') :
+ Exits M state priv stop a rs m (fuel+1) (choiceBits [e] ++ bits) (out.prepend e) := by
+ obtain ⟨es, rs', m', left, bs, tail, hE, rfl, rfl, hrun, rfl⟩ := h
+ refine ⟨e :: es, rs', m', left, bs, tail, lift hE, by simp; omega, ?_, hrun, rfl⟩
+ cases e <;> simp [choiceBits]
+
+private theorem exits_seq {M : Machine w p r k} {state : Word w} {priv stop a b rs m es r₁ m₁ fuel bits out}
+ (first : Exec M.publicData state a rs m es r₁ m₁) (last : Exits M state priv stop b r₁ m₁ fuel bits out) :
+ Exits M state priv stop (.seq a b) rs m (es.length+fuel) (choiceBits es ++ bits) (prependEvents es out) := by
+ obtain ⟨fs, r₂, m₂, left, bs, tail, hE, rfl, rfl, hrun, rfl⟩ := last
+ refine ⟨es ++ fs, r₂, m₂, left, bs, tail, .seq first hE, by simp [Nat.add_assoc],
+ by simp [choiceBits_append], hrun, ?_⟩
+ simp [prependEvents, List.append_assoc]
+
+private theorem exits_loop {M : Machine w p r k} {state : Word w} {priv stop l q a rs m es r₁ m₁ fuel bits out}
+ (ht : rs l < rs q) (first : Exec M.publicData state a rs m es r₁ m₁)
+ (last : Exits M state priv stop (.whileLt l q a) r₁ m₁ fuel bits out) :
+ Exits M state priv stop (.whileLt l q a) rs m (es.length+fuel+1) (choiceBits es ++ bits)
+ ((prependEvents es out).prepend .tick) := by
+ obtain ⟨fs, r₂, m₂, left, bs, tail, hE, rfl, rfl, hrun, rfl⟩ := last
+ refine ⟨.tick :: (es ++ fs), r₂, m₂, left, bs, tail, .whileStep ht first hE, by simp; omega,
+ by simp [choiceBits, choiceBits_append], hrun, ?_⟩
+ simp [Report.prepend, prependEvents, List.append_assoc]
+
+/-- Recover the structured execution from any successful entry, before the normal exit's
+continuation. This applies to arbitrary linked code, even when the enclosing program has
+further branches after the block. -/
+theorem Linked.complete {M : Machine w p r k} {a : PrimedInputRAM.Flow r k}
+ {label : a.Label → Fin p} {stop bad : Fin p} (hl : Linked M a label stop bad)
+ (hb : M.code bad = .reject) (state : Word w) (priv : Word w → Word w)
+ (rs : Regs w r) (m : Memory w) (fuel : ℕ) (bits : List Bool) (out : Report w)
+ (h : BurstRAM.execute M.program fuel ⟨label a.entry,state,rs,priv⟩ m bits = some out) :
+ Exits M state priv stop a rs m fuel bits out := by
+ induction fuel using Nat.strong_induction_on generalizing a stop rs m bits out with
+ | h fuel ih =>
+ induction a generalizing stop rs m bits out with
+ | line op =>
+ cases fuel with
+ | zero => contradiction
+ | succ f =>
+ rw [hl.execute hb state priv (f+1) _ _ _ _] at h
+ simp only [run, code, Jump.run] at h
+ cases he : op.effect M.publicData state rs m with
+ | none => simp [he] at h
+ | some z =>
+ obtain ⟨e, r', m'⟩ := z
+ simp only [he, Option.bind_some, Option.map_eq_some_iff] at h
+ obtain ⟨t, hrun, rfl⟩ := h
+ exact ⟨[e], r', m', f, bits, t, .line he, by simp [Nat.add_comm],
+ by rw [line_choices he]; rfl, hrun, rfl⟩
+ | seq a b ia _ =>
+ obtain ⟨es, r₁, m₁, left, bs, t, he, hf, hbs, ht, hout⟩ := ia hl.seqLeft _ _ _ _ h
+ have hlt : left < fuel := by have := positive he; omega
+ have hr := ih left hlt hl.seqRight r₁ m₁ bs t ht
+ rw [hf, hbs, hout]
+ exact exits_seq he hr
+ | ifEq l q a b ia ib | ifLt l q a b ia ib =>
+ cases fuel with
+ | zero => contradiction
+ | succ f =>
+ first | erw [hl.execute_ifEq state priv f rs m bits] at h
+ | erw [hl.execute_ifLt state priv f rs m bits] at h
+ obtain ⟨t, hrun, rfl⟩ := Option.map_eq_some_iff.mp h
+ split at hrun
+ · rename_i ht
+ first | exact exits_prepend (ih f (by omega) hl.ifEqYes _ _ _ _ hrun) (Exec.ifEqYes ht)
+ | exact exits_prepend (ih f (by omega) hl.ifLtYes _ _ _ _ hrun) (Exec.ifLtYes ht)
+ · rename_i ht
+ first | exact exits_prepend (ih f (by omega) hl.ifEqNo _ _ _ _ hrun) (Exec.ifEqNo ht)
+ | exact exits_prepend (ih f (by omega) hl.ifLtNo _ _ _ _ hrun) (Exec.ifLtNo ht)
+ | branch a b _ _ =>
+ cases fuel with
+ | zero => contradiction
+ | succ f =>
+ cases bits with
+ | nil => erw [hl.execute_branch_nil state priv f rs m] at h; contradiction
+ | cons bit bs =>
+ erw [hl.execute_branch state priv f rs m bit bs] at h
+ obtain ⟨t, hrun, rfl⟩ := Option.map_eq_some_iff.mp h
+ cases bit with
+ | true => exact exits_prepend (ih f (by omega) hl.branchYes _ _ _ _ hrun) Exec.branchYes
+ | false => exact exits_prepend (ih f (by omega) hl.branchNo _ _ _ _ hrun) Exec.branchNo
+ | whileLt l q a _ =>
+ cases fuel with
+ | zero => contradiction
+ | succ f =>
+ erw [hl.execute_whileLt state priv f rs m bits] at h
+ obtain ⟨t, hrun, rfl⟩ := Option.map_eq_some_iff.mp h
+ split at hrun
+ · rename_i ht
+ obtain ⟨es, r₁, m₁, left, bs, u, hE, hf, hbs, hu, hout⟩ := ih f (by omega) hl.loopBody _ _ _ _ hrun
+ have hlt : left < f+1 := by omega
+ have hr := ih left hlt hl r₁ m₁ bs u hu
+ rw [hf, hbs, hout]
+ exact exits_loop ht hE hr
+ · rename_i ht
+ exact ⟨[.tick], rs, m, f, bits, t, .whileDone ht, by simp [Nat.add_comm], rfl, hrun, rfl⟩
+
+private theorem template_exit_run (a : PrimedInputRAM.Flow r k) (result : Option (Fin r))
+ (pub : Fin k → Word w) (state : Word w) (priv : Word w → Word w) (rs : Regs w r) (m : Memory w)
+ (fuel : ℕ) (bits : List Bool) :
+ execute ((a.template result).instantiate w pub).program fuel ⟨a.exitPC,state,rs,priv⟩ m bits =
+ if fuel = 0 ∨ bits ≠ [] then none else some ⟨[], result.map rs⟩ := by
+ cases fuel with
+ | zero => simp [execute]
+ | succ n =>
+ cases result <;> cases bits <;>
+ simp [execute, Machine.program, Template.instantiate, template_exit, Instr.resize, Instr.run]
+
+/-- A standalone compiled template accepts exactly its finite `Exec` derivations with
+all bits consumed, sufficient fuel for the return, and the indicated returned register.
+With `result = none` the exit is an accepting halt. -/
+theorem template_execute_iff (a : PrimedInputRAM.Flow r k) (result : Option (Fin r))
+ (pub : Fin k → Word w) (state : Word w) (priv : Word w → Word w) (rs : Regs w r) (m : Memory w)
+ (fuel : ℕ) (bits : List Bool) (out : Report w) :
+ execute ((a.template result).instantiate w pub).program fuel ⟨a.pc a.entry,state,rs,priv⟩ m bits =
+ some out ↔
+ ∃ rs' m', Exec pub state a rs m out.events rs' m' ∧ out.result = result.map rs' ∧
+ out.events.length < fuel ∧ choiceBits out.events = bits := by
+ have hl := template_linked a result pub
+ have hb : ((a.template result).instantiate w pub).code a.rejectPC = .reject := by
+ simp [Template.instantiate, template_reject, Instr.resize]
+ constructor
+ · intro h
+ obtain ⟨es, r₁, m₁, left, bs, tail, he, hf, hbs, ht, hout⟩ :=
+ hl.complete hb state priv rs m fuel bits out h
+ rw [template_exit_run] at ht
+ split at ht
+ · contradiction
+ · rename_i hremaining
+ obtain ⟨hleft, rfl⟩ := (not_or.mp hremaining).imp_right (fun h ↦ by simpa using h)
+ obtain rfl := Option.some.inj ht
+ subst out
+ simp only [prependEvents, List.append_nil]
+ exact ⟨r₁, m₁, he, rfl, by omega, by simpa using hbs.symm⟩
+ · rintro ⟨r₁, m₁, he, hr, hlen, hbits⟩
+ let left := fuel - out.events.length
+ have hp : 0 < left := Nat.sub_pos_of_lt hlen
+ calc
+ _ = execute ((a.template result).instantiate w pub).program (out.events.length + left)
+ ⟨a.pc a.entry,state,rs,priv⟩ m (choiceBits out.events ++ []) := by
+ simp [left, Nat.add_sub_of_le hlen.le, hbits]
+ _ = _ := he.execute hl hb priv left []
+ _ = some out := by
+ rw [template_exit_run, ite_eq_right (by simp [hp.ne']), Option.map_some]
+ cases out
+ simp_all [prependEvents]
+
+end PrimedInputRAM.Flow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowEval.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowEval.lean
new file mode 100644
index 0000000000..a270f57643
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowEval.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowLinks
+
+/-!
+# Finite executions of structured burst-RAM code
+
+A derivation records the successful elementary instructions of a block and its final
+registers and memory. Every test contributes a tick, every binary choice retains its
+bit, and every visit to a loop test is counted, including the final false test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Flow
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w r k p : ℕ}
+
+/-- Fuel-free successful execution of structured code. A derivation is finite even when
+the program contains a loop. The event-list length is its exact number of instructions. -/
+inductive Exec (pub : Fin k → Word w) (state : Word w) :
+ PrimedInputRAM.Flow r k → Regs w r → Memory w → List (Event w) → Regs w r → Memory w → Prop
+ | line {op rs m e rs' m'} (h : op.effect pub state rs m = some (e, rs', m')) :
+ Exec pub state (.line op) rs m [e] rs' m'
+ | seq {a b rs m es r₁ m₁ fs r₂ m₂}
+ (first : Exec pub state a rs m es r₁ m₁) (last : Exec pub state b r₁ m₁ fs r₂ m₂) :
+ Exec pub state (.seq a b) rs m (es ++ fs) r₂ m₂
+ | ifEqYes {l q a b rs m es rs' m'} (test : rs l = rs q)
+ (body : Exec pub state a rs m es rs' m') : Exec pub state (.ifEq l q a b) rs m (.tick :: es) rs' m'
+ | ifEqNo {l q a b rs m es rs' m'} (test : rs l ≠ rs q)
+ (body : Exec pub state b rs m es rs' m') : Exec pub state (.ifEq l q a b) rs m (.tick :: es) rs' m'
+ | ifLtYes {l q a b rs m es rs' m'} (test : rs l < rs q)
+ (body : Exec pub state a rs m es rs' m') : Exec pub state (.ifLt l q a b) rs m (.tick :: es) rs' m'
+ | ifLtNo {l q a b rs m es rs' m'} (test : ¬ rs l < rs q)
+ (body : Exec pub state b rs m es rs' m') : Exec pub state (.ifLt l q a b) rs m (.tick :: es) rs' m'
+ | branchYes {a b rs m es rs' m'} (body : Exec pub state a rs m es rs' m') :
+ Exec pub state (.branch a b) rs m (.choice true :: es) rs' m'
+ | branchNo {a b rs m es rs' m'} (body : Exec pub state b rs m es rs' m') :
+ Exec pub state (.branch a b) rs m (.choice false :: es) rs' m'
+ | whileDone {l q a rs m} (test : ¬ rs l < rs q) :
+ Exec pub state (.whileLt l q a) rs m [.tick] rs m
+ | whileStep {l q a rs m es r₁ m₁ fs r₂ m₂} (test : rs l < rs q)
+ (body : Exec pub state a rs m es r₁ m₁)
+ (rest : Exec pub state (.whileLt l q a) r₁ m₁ fs r₂ m₂) :
+ Exec pub state (.whileLt l q a) rs m (.tick :: (es ++ fs)) r₂ m₂
+
+theorem choiceBits_append (es fs : List (Event w)) :
+ choiceBits (es ++ fs) = choiceBits es ++ choiceBits fs := by
+ induction es with
+ | nil => rfl
+ | cons e es ih => cases e <;> simp [choiceBits, ih]
+
+/-- A successful straight-line opcode never consumes a binary branch bit. -/
+theorem line_choices {op : Op r k} {pub : Fin k → Word w} {state : Word w}
+ {rs : Regs w r} {m : Memory w} {e rs' m'} (h : op.effect pub state rs m = some (e, rs', m')) :
+ choiceBits [e] = [] := by
+ cases op <;> simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at h
+ all_goals first | rw [← h.1]; rfl | split at h <;> simp only [Option.some.injEq, Prod.mk.injEq, reduceCtorEq] at h
+ all_goals rw [← h.1]; rfl
+
+/-- Attach the actual executed instruction events to the report of the continuation. -/
+def prependEvents (es : List (Event w)) (t : Report w) : Report w := ⟨es ++ t.events, t.result⟩
+
+private theorem line_execute {M : Machine w p r k} {op : Op r k} {label : (Flow.line op).Label → Fin p}
+ {stop bad : Fin p} (hl : Linked M (.line op) label stop bad) (hb : M.code bad = .reject)
+ {state : Word w} (priv : Word w → Word w) {rs m e rs' m'}
+ (he : op.effect M.publicData state rs m = some (e,rs',m')) (fuel : ℕ) (bits : List Bool) :
+ execute M.program ([e].length + fuel) ⟨label (Flow.line op).entry,state,rs,priv⟩ m (choiceBits [e] ++ bits) =
+ (execute M.program fuel ⟨stop,state,rs',priv⟩ m' bits).map (prependEvents [e]) := by
+ rw [line_choices he, List.nil_append, hl.execute hb state priv _ (Flow.line op).entry rs m bits]
+ simp [run, code, Jump.run, he, Nat.one_add]
+ rfl
+
+private theorem prepend_comp (e : Event w) (es : List (Event w)) :
+ Report.prepend e ∘ prependEvents es = prependEvents (e :: es) := rfl
+
+private theorem prependEvents_comp (es fs : List (Event w)) :
+ prependEvents es ∘ prependEvents fs = prependEvents (es ++ fs) := by
+ funext t
+ simp [prependEvents, List.append_assoc]
+
+/-- A finite structured execution runs on the actual machine using exactly one fuel
+unit per event. Its branch bits are the choices in the derivation. It transfers control
+to the linked exit with the remaining fuel and bits and the updated registers and memory. -/
+theorem Exec.execute {M : Machine w p r k} {a : PrimedInputRAM.Flow r k} {state : Word w}
+ {rs m es rs' m'} (h : Exec M.publicData state a rs m es rs' m')
+ {label : a.Label → Fin p} {stop bad : Fin p} (hl : Linked M a label stop bad)
+ (hb : M.code bad = .reject) (priv : Word w → Word w) (fuel : ℕ) (bits : List Bool) :
+ BurstRAM.execute M.program (es.length + fuel) ⟨label a.entry,state,rs,priv⟩ m
+ (choiceBits es ++ bits) =
+ (BurstRAM.execute M.program fuel ⟨stop,state,rs',priv⟩ m' bits).map (prependEvents es) := by
+ induction h generalizing stop fuel bits with
+ | line he => exact line_execute hl hb priv he fuel bits
+ | @seq _ _ _ _ _ _ _ fs _ _ _ _ iha ihb =>
+ have ha := iha hl.seqLeft (fs.length + fuel) (choiceBits fs ++ bits)
+ have hlast := ihb hl.seqRight fuel bits
+ simp only [entry, List.length_append, Nat.add_assoc, choiceBits_append, List.append_assoc]
+ erw [ha, hlast, Option.map_map, prependEvents_comp]
+ | ifEqYes ht _ ih | ifEqNo ht _ ih | ifLtYes ht _ ih | ifLtNo ht _ ih =>
+ first | have hr := ih hl.ifEqYes fuel bits | have hr := ih hl.ifEqNo fuel bits
+ | have hr := ih hl.ifLtYes fuel bits | have hr := ih hl.ifLtNo fuel bits
+ dsimp only [Function.comp_def] at hr
+ simp only [entry, List.length_cons, Nat.succ_add, choiceBits]
+ first | rw [hl.execute_ifEq state priv _ _ _ _] | rw [hl.execute_ifLt state priv _ _ _ _]
+ simp only [ht, ↓reduceIte]
+ erw [hr, Option.map_map]
+ rfl
+ | branchYes _ ih | branchNo _ ih =>
+ first | have hr := ih hl.branchYes fuel bits | have hr := ih hl.branchNo fuel bits
+ dsimp only [Function.comp_def] at hr
+ simp only [entry, List.length_cons, Nat.succ_add, choiceBits, List.cons_append]
+ rw [hl.execute_branch state priv _ _ _ _ _]
+ erw [hr, Option.map_map]
+ rfl
+ | whileDone ht =>
+ simp only [entry, List.length_cons, List.length_nil, Nat.succ_add, Nat.zero_add, choiceBits,
+ List.nil_append]
+ rw [hl.execute_whileLt state priv _ _ _ _, ite_eq_right ht]
+ rfl
+ | @whileStep _ _ _ _ _ _ _ _ fs _ _ ht _ _ ihb ihr =>
+ have hbdy := ihb hl.loopBody (fs.length + fuel) (choiceBits fs ++ bits)
+ have hr := ihr hl fuel bits
+ simp only [entry] at hr
+ simp only [entry, List.length_cons, Nat.succ_add, List.length_append, Nat.add_assoc,
+ choiceBits, choiceBits_append, List.append_assoc]
+ erw [hl.execute_whileLt state priv _ _ _ _, ite_eq_left ht, hbdy, hr, Option.map_map,
+ prepend_comp, Option.map_map, prependEvents_comp, List.cons_append]
+
+end PrimedInputRAM.Flow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowLinks.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowLinks.lean
new file mode 100644
index 0000000000..0d47fd4331
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowLinks.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowRun
+
+/-!
+# Linked conditionals and loop tests of the private RAM
+
+Both arms of a conditional inherit its normal and rejecting exits. The guard executes
+one native opcode, retaining all registers and memory. A deterministic guard emits
+one tick, while a nondeterministic branch emits precisely the bit it consumes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Flow
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w r k p : ℕ} {M : Machine w p r k} {a b : PrimedInputRAM.Flow r k}
+ {l q : Fin r} {stop bad : Fin p}
+
+private theorem linkedArm {whole arm : PrimedInputRAM.Flow r k} {label : whole.Label → Fin p}
+ (hl : Linked M whole label stop bad) (embed : arm.Label → whole.Label)
+ (he : ∀ i, whole.code (embed i) = (arm.code i).map (Option.map embed)) :
+ Linked M arm (label ∘ embed) stop bad := by
+ constructor
+ intro i
+ change M.code (label (embed i)) = _
+ rw [hl.atLabel, he, Jump.map_map]
+ congr 3
+ funext t
+ cases t <;> rfl
+
+theorem Linked.ifEqYes {label : (Flow.ifEq l q a b).Label → Fin p}
+ (hl : Linked M (.ifEq l q a b) label stop bad) :
+ Linked M a (label ∘ Sum.inr ∘ Sum.inl) stop bad :=
+ linkedArm hl _ (fun _ ↦ rfl)
+
+theorem Linked.ifEqNo {label : (Flow.ifEq l q a b).Label → Fin p}
+ (hl : Linked M (.ifEq l q a b) label stop bad) :
+ Linked M b (label ∘ Sum.inr ∘ Sum.inr) stop bad :=
+ linkedArm hl _ (fun _ ↦ rfl)
+
+theorem Linked.ifLtYes {label : (Flow.ifLt l q a b).Label → Fin p}
+ (hl : Linked M (.ifLt l q a b) label stop bad) :
+ Linked M a (label ∘ Sum.inr ∘ Sum.inl) stop bad :=
+ linkedArm hl _ (fun _ ↦ rfl)
+
+theorem Linked.ifLtNo {label : (Flow.ifLt l q a b).Label → Fin p}
+ (hl : Linked M (.ifLt l q a b) label stop bad) :
+ Linked M b (label ∘ Sum.inr ∘ Sum.inr) stop bad :=
+ linkedArm hl _ (fun _ ↦ rfl)
+
+theorem Linked.branchYes {label : (Flow.branch a b).Label → Fin p}
+ (hl : Linked M (.branch a b) label stop bad) :
+ Linked M a (label ∘ Sum.inr ∘ Sum.inl) stop bad :=
+ linkedArm hl _ (fun _ ↦ rfl)
+
+theorem Linked.branchNo {label : (Flow.branch a b).Label → Fin p}
+ (hl : Linked M (.branch a b) label stop bad) :
+ Linked M b (label ∘ Sum.inr ∘ Sum.inr) stop bad :=
+ linkedArm hl _ (fun _ ↦ rfl)
+
+theorem Linked.execute_ifEq {label : (Flow.ifEq l q a b).Label → Fin p}
+ (hl : Linked M (.ifEq l q a b) label stop bad) (state : Word w) (priv : Word w → Word w)
+ (fuel : ℕ) (rs : Regs w r) (m : Memory w) (bits : List Bool) :
+ BurstRAM.execute M.program (fuel+1) ⟨label (.inl ()),state,rs,priv⟩ m bits =
+ (BurstRAM.execute M.program fuel ⟨if rs l = rs q then label (.inr (.inl a.entry))
+ else label (.inr (.inr b.entry)),state,rs,priv⟩ m bits).map (Report.prepend .tick) := by
+ rw [BurstRAM.execute]
+ simp only [Machine.program]
+ rw [hl.atLabel (.inl ())]
+ rfl
+
+theorem Linked.execute_ifLt {label : (Flow.ifLt l q a b).Label → Fin p}
+ (hl : Linked M (.ifLt l q a b) label stop bad) (state : Word w) (priv : Word w → Word w)
+ (fuel : ℕ) (rs : Regs w r) (m : Memory w) (bits : List Bool) :
+ BurstRAM.execute M.program (fuel+1) ⟨label (.inl ()),state,rs,priv⟩ m bits =
+ (BurstRAM.execute M.program fuel ⟨if rs l < rs q then label (.inr (.inl a.entry))
+ else label (.inr (.inr b.entry)),state,rs,priv⟩ m bits).map (Report.prepend .tick) := by
+ rw [BurstRAM.execute]
+ simp only [Machine.program]
+ rw [hl.atLabel (.inl ())]
+ rfl
+
+theorem Linked.execute_branch {label : (Flow.branch a b).Label → Fin p}
+ (hl : Linked M (.branch a b) label stop bad) (state : Word w) (priv : Word w → Word w)
+ (fuel : ℕ) (rs : Regs w r) (m : Memory w) (bit : Bool) (bits : List Bool) :
+ BurstRAM.execute M.program (fuel+1) ⟨label (.inl ()),state,rs,priv⟩ m (bit::bits) =
+ (BurstRAM.execute M.program fuel ⟨if bit then label (.inr (.inl a.entry))
+ else label (.inr (.inr b.entry)),state,rs,priv⟩ m bits).map (Report.prepend (.choice bit)) := by
+ rw [BurstRAM.execute]
+ simp only [Machine.program]
+ rw [hl.atLabel (.inl ())]
+ rfl
+
+theorem Linked.execute_branch_nil {label : (Flow.branch a b).Label → Fin p}
+ (hl : Linked M (.branch a b) label stop bad) (state : Word w) (priv : Word w → Word w)
+ (fuel : ℕ) (rs : Regs w r) (m : Memory w) :
+ BurstRAM.execute M.program (fuel+1) ⟨label (.inl ()),state,rs,priv⟩ m [] = none := by
+ rw [BurstRAM.execute]
+ simp only [Machine.program]
+ rw [hl.atLabel (.inl ())]
+ rfl
+
+theorem Linked.execute_whileLt {label : (Flow.whileLt l q a).Label → Fin p}
+ (hl : Linked M (.whileLt l q a) label stop bad) (state : Word w) (priv : Word w → Word w)
+ (fuel : ℕ) (rs : Regs w r) (m : Memory w) (bits : List Bool) :
+ BurstRAM.execute M.program (fuel+1) ⟨label (.inl ()),state,rs,priv⟩ m bits =
+ (BurstRAM.execute M.program fuel ⟨if rs l < rs q then label (.inr a.entry) else stop,
+ state,rs,priv⟩ m bits).map (Report.prepend .tick) := by
+ rw [BurstRAM.execute]
+ simp only [Machine.program]
+ rw [hl.atLabel (.inl ())]
+ rfl
+
+end PrimedInputRAM.Flow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowRun.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowRun.lean
new file mode 100644
index 0000000000..fb674130c7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMFlowRun.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlow
+
+/-!
+# Execution of a linked structured burst program
+
+The interpreter for a finite control graph consumes one unit of fuel at
+each label. Word operations use the native burst opcodes, and branches use
+the supplied bit stream. The normal exit is a continuation, so the result
+applies both to standalone calls and to blocks inside a larger program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Flow
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w r k : ℕ}
+
+/-- Continuation at a label with its updated registers and memory and the
+remaining branch bits. -/
+abbrev Next (pc : Type) (w r : ℕ) :=
+ pc → Regs w r → Memory w → List Bool → Option (Report w)
+
+/-- Interpret a single labeled jump on the current registers, memory and choice stream, passing
+the result to the selected continuation. -/
+def Jump.run {pc : Type} (pub : Fin k → Word w) (state : Word w) (next : Next pc w r)
+ (i : Jump pc r k) (rs : Regs w r) (m : Memory w) (bits : List Bool) : Option (Report w) :=
+ match i with
+ | .line op dst => (op.effect pub state rs m).bind fun (ev,rs',m') ↦
+ (next dst rs' m' bits).map (Report.prepend ev)
+ | .ifEq l q y n => (next (if rs l = rs q then y else n) rs m bits).map (Report.prepend .tick)
+ | .ifLt l q y n => (next (if rs l < rs q then y else n) rs m bits).map (Report.prepend .tick)
+ | .branch y n =>
+ match bits with
+ | [] => none
+ | b :: bs => (next (if b then y else n) rs m bs).map (Report.prepend (.choice b))
+
+theorem Jump.run_map {A B : Type} (f : A → B) (pub : Fin k → Word w) (state : Word w)
+ (next : Next B w r) (i : Jump A r k) (rs : Regs w r) (m : Memory w) (bits : List Bool) :
+ (i.map f).run pub state next rs m bits = i.run pub state (next ∘ f) rs m bits := by
+ cases i with
+ | line op dst => rfl
+ | ifEq l q y n => by_cases h : rs l = rs q <;> simp [Jump.map, Jump.run, h]
+ | ifLt l q y n => by_cases h : rs l < rs q <;> simp [Jump.map, Jump.run, h]
+ | branch y n => cases bits with
+ | nil => rfl
+ | cons b bs => cases b <;> rfl
+
+/-- Execute a subgraph with a continuation at its normal exit. -/
+def run (a : PrimedInputRAM.Flow r k) (pub : Fin k → Word w) (state : Word w)
+ (exit : ℕ → Regs w r → Memory w → List Bool → Option (Report w)) :
+ ℕ → a.Label → Regs w r → Memory w → List Bool → Option (Report w)
+ | 0, _, _, _, _ => none
+ | fuel+1, i, rs, m, bits =>
+ (a.code i).run pub state (fun t ↦ match t with
+ | none => exit fuel
+ | some j => run a pub state exit fuel j) rs m bits
+
+private theorem execute_bad {p : ℕ} (M : Machine w p r k) (bad : Fin p) (hb : M.code bad = .reject)
+ (fuel : ℕ) (state : Word w) (rs : Regs w r) (priv : Word w → Word w) (m : Memory w)
+ (bits : List Bool) :
+ execute M.program fuel ⟨bad,state,rs,priv⟩ m bits = none := by
+ cases fuel <;> simp [execute, Machine.program, hb, Instr.run]
+
+private theorem execute_jump {p : ℕ} (M : Machine w p r k) (j : Jump (Fin p) r k)
+ (cur bad : Fin p) (hc : M.code cur = (j.emit bad).resize w) (hb : M.code bad = .reject)
+ (fuel : ℕ) (state : Word w) (rs : Regs w r) (priv : Word w → Word w) (m : Memory w)
+ (bits : List Bool) :
+ execute M.program (fuel+1) ⟨cur,state,rs,priv⟩ m bits =
+ j.run M.publicData state (fun q regs mem bs ↦ execute M.program fuel ⟨q,state,regs,priv⟩ mem bs)
+ rs m bits := by
+ cases j with
+ | line op dst =>
+ cases op <;> simp only [execute, Machine.program, hc, Jump.emit, Instr.resize, Jump.run,
+ Op.emit, Op.effect, Instr.run, Config.put, Option.bind_some]
+ all_goals split <;> simp_all
+ all_goals exact execute_bad M bad hb fuel state rs priv m bits
+ | ifEq l q y n | ifLt l q y n =>
+ simp [execute, Machine.program, hc, Jump.emit, Instr.resize, Instr.run, Jump.run]
+ | branch y n =>
+ cases bits <;> simp [execute, Machine.program, hc, Jump.emit, Instr.resize, Instr.run, Jump.run]
+
+/-- The compiled table and the named control graph have the same execution
+on every fuel and branch stream, including rejected and unfinished calls. -/
+theorem Linked.execute {p : ℕ} {M : Machine w p r k} {a : PrimedInputRAM.Flow r k}
+ {label : a.Label → Fin p} {stop bad : Fin p} (hl : Linked M a label stop bad)
+ (hb : M.code bad = .reject) (state : Word w) (priv : Word w → Word w)
+ (fuel : ℕ) (i : a.Label) (rs : Regs w r) (m : Memory w) (bits : List Bool) :
+ execute M.program fuel ⟨label i,state,rs,priv⟩ m bits =
+ run a M.publicData state
+ (fun left regs mem bs ↦ execute M.program left ⟨stop,state,regs,priv⟩ mem bs)
+ fuel i rs m bits := by
+ induction fuel generalizing i rs m bits with
+ | zero => rfl
+ | succ fuel ih =>
+ rw [execute_jump M _ (label i) bad (hl.atLabel i) hb, Jump.run_map, run]
+ congr 1
+ funext t regs mem bs
+ cases t with
+ | none => rfl
+ | some q => exact ih q regs mem bs
+
+/-- Execute from the entry of the compiled template, with freshly zeroed
+registers and private memory. -/
+theorem template_executes (a : PrimedInputRAM.Flow r k) (result : Option (Fin r))
+ (pub : Fin k → Word w) (state : Word w) (mem : Memory w) (bits : List Bool) (fuel : ℕ) :
+ let M := (a.template result).instantiate w pub
+ execute M.program fuel (M.program.start state) mem bits =
+ run a pub state (fun left rs mem' bs => execute M.program left ⟨a.exitPC,state,rs,fun _ => 0⟩ mem' bs)
+ fuel a.entry (fun _ => 0) mem bits := by
+ let M := (a.template result).instantiate w pub
+ have hb : M.code a.rejectPC = .reject := by
+ change ((a.template result).code a.rejectPC).resize w = _
+ rw [template_reject]
+ rfl
+ exact (template_linked a result pub).execute hb state (fun _ => 0) fuel a.entry (fun _ => 0) mem bits
+
+end PrimedInputRAM.Flow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMHeaders.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMHeaders.lean
new file mode 100644
index 0000000000..e3d02e6a43
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMHeaders.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.PrimedInputRAM
+
+/-!
+# Prescribed headers for the auxiliary RAM
+
+The pair's cut lengths occupy words 0, 1 and 2. After them come the two
+fixed-width group index fields, the advice field, and two equal-capacity
+exterior fields. Each bit occupies one word. The nominated histogram
+follows these fields, and all unused header positions are zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM
+
+variable {w : ℕ}
+
+/-- Represent a Boolean header or shared bit by a zero or one RAM word. -/
+def encodeBit (w : ℕ) (b : Bool) : Word w := if b then 1 else 0
+
+@[simp] theorem encodeBit_eq_one (hw : 0 < w) (b : Bool) :
+ encodeBit w b = 1 ↔ b = true := by
+ cases b
+ · have h : 1 < 2^w := Nat.one_lt_two_pow hw.ne'
+ simp [encodeBit, Fin.ext_iff, Nat.mod_eq_of_lt h]
+ · simp [encodeBit]
+
+/-- The left, middle or right cut length stored in the corresponding one of the first three
+header words. -/
+def cutLength (L : Lengths) (i : Fin 3) : ℕ :=
+ if i = 0 then L.leftCut else if i = 1 then L.middleCut else L.rightCut
+
+/-- Lay out the three cut lengths, group indices, advice, exterior bits and nominated histogram
+in external memory, padding the unused cells with zero. -/
+def headerMemory (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w)) (a : ℕ) : Word w :=
+ if h : a < 3 then Fin.ofNat _ (cutLength L ⟨a,h⟩) else
+ if h : a < 3 + L.index then encodeBit w (hdr (.group 0 ⟨a-3, by omega⟩)) else
+ if h : a < 3 + 2*L.index then encodeBit w (hdr (.group 1 ⟨a-3-L.index, by omega⟩)) else
+ if h : a < 3 + 2*L.index + L.advice then
+ encodeBit w (hdr (.advice ⟨a-(3+2*L.index), by omega⟩)) else
+ let base := 3 + 2*L.index + L.advice
+ if h : a < base + L.leftCut then encodeBit w (hdr (.leftCut ⟨a-base, by omega⟩)) else
+ if hcut : a < base + L.cutCapacity then 0 else
+ if h : a < base + L.cutCapacity + L.rightCut then
+ encodeBit w (hdr (.rightCut ⟨a-(base+L.cutCapacity), by omega⟩)) else
+ if a < Header.count L then 0 else hist[a-Header.count L]?.getD 0
+
+@[simp] theorem headerMemory_length (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w))
+ (j : Fin 3) :
+ headerMemory L hdr hist j.val = Fin.ofNat _ (cutLength L j) := by
+ simp [headerMemory, j.isLt]
+
+@[simp] theorem headerMemory_bits (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w))
+ (j : Header L) : headerMemory L hdr hist j.address.val = encodeBit w (hdr j) := by
+ cases j with
+ | group g i =>
+ have hg : g.val = 0 ∨ g.val = 1 := by have := g.isLt; omega
+ rcases hg with hg | hg
+ · obtain rfl : g = 0 := Fin.ext hg
+ simp [Header.address, headerMemory, i.isLt]
+ · obtain rfl : g = 1 := Fin.ext hg
+ have hi := i.isLt
+ simp only [Header.address, Fin.val_one, headerMemory]
+ simp only [Nat.one_mul]
+ split_ifs <;> first | rfl | omega | (congr 4; omega)
+ | advice i =>
+ have hi := i.isLt
+ simp only [Header.address, headerMemory]
+ simp only [Nat.add_sub_cancel_left]
+ split_ifs <;> first | rfl | omega
+ | leftCut i =>
+ have hi := i.isLt
+ simp only [Header.address, headerMemory]
+ simp only [Nat.add_sub_cancel_left]
+ split_ifs <;> first | rfl | omega
+ | rightCut i =>
+ have hi := i.isLt
+ have hc := L.leftFit
+ simp only [Header.address, headerMemory]
+ simp only [Nat.add_sub_cancel_left]
+ split_ifs <;> first | rfl | omega
+
+/-- Read the supplied word for one histogram entry, or zero if it lies beyond the end. -/
+theorem headerMemory_hist (L : Lengths) (hdr : Header L → Bool) (hist : List (Word w)) (j : ℕ) :
+ headerMemory L hdr hist (Header.count L+j) = hist[j]?.getD 0 := by
+ have := L.leftFit
+ have := L.rightFit
+ unfold headerMemory Header.count
+ dsimp only
+ split_ifs <;> first | omega | simp
+
+variable {L : Lengths} {n r H : ℕ}
+
+namespace Layout
+
+/-- The stream obtained from the inverse path-counting equivalence consists
+of exactly the bits consumed by the first pass, in physical order. -/
+theorem streamEquiv_symm (Q : Layout L n r H w) (bitWord : Bool → Word w) (initial : Memory w)
+ (bits : Internal L r H w → Bool) :
+ ((Q.streamEquiv bitWord initial).symm bits).val = branches (Q.assignment bits) := rfl
+
+/-- A parser can read each output bit directly from RAM following any admissible
+first-pass branch sequence. The three cut lengths and the actual bit-valued
+words in the initialization are fixed by the header format above. -/
+theorem assemble_stream (Q : Layout L n r H w) (hdr : Header L → Bool) (hist : List (Word w))
+ (bs : {bs : List Bool //
+ (firstPass Q.owns Q.bitAddress (encodeBit w) bs (headerMemory L hdr hist)).isSome = true}) :
+ let init := headerMemory L hdr hist
+ let bits := Q.streamEquiv (encodeBit w) init bs
+ ∃ final, Q.assemble (encodeBit w) bs.val init = some final ∧
+ ∀ u : Site r, ∀ j : Fin n,
+ final (Q.outputAddress (finProdFinEquiv (finProdFinEquiv u,j))).val =
+ encodeBit w (input Q.program Q.fits hdr bits u j) := by
+ let init := headerMemory L hdr hist
+ let bits := Q.streamEquiv (encodeBit w) init bs
+ have hb : branches (Q.assignment bits) = bs.val :=
+ congrArg Subtype.val ((Q.streamEquiv (encodeBit w) init).symm_apply_apply bs)
+ refine ⟨Q.assembled (encodeBit w) bits init, ?_, ?_⟩
+ · rw [← hb]
+ exact Q.assemble_branches ..
+ · exact Q.assembled_input _ _ _ _ (fun j ↦ headerMemory_bits L hdr hist j)
+
+end Layout
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMLayout.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMLayout.lean
new file mode 100644
index 0000000000..72ba906c8e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMLayout.lean
@@ -0,0 +1,189 @@
+import OAI.Computability.VPVNP.RAMSharedFields
+import OAI.Computability.VPVNP.RAMSerialization
+
+/-!
+# The rectangle of primed input positions
+
+Sections 9.2 and 11 fix two consecutive groups with the same literal program
+prefix. Every row of the rectangle consists of that prefix, the site address,
+four header and cut bits, the incident ports, and zero padding. Only a middle
+cut bit at the first group or an existing send port is a branch location.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open RAMLayout RAMSerialization
+
+/-- Lengths of the pair's supplied header arrays. -/
+structure Lengths where
+ /-- Number of bits in the index of each of the two consecutive groups. -/
+ index : ℕ
+ /-- Number of advice bits supplied in the pair's common header. -/
+ advice : ℕ
+ /-- Number of supplied cut bits on the incoming side of the first group. -/
+ leftCut : ℕ
+ /-- Number of shared cut bits chosen between the first and second groups. -/
+ middleCut : ℕ
+ /-- Number of supplied cut bits on the outgoing side of the second group. -/
+ rightCut : ℕ
+ /-- Number of header words reserved for each of the left and right cut arrays. -/
+ cutCapacity : ℕ
+ leftFit : leftCut ≤ cutCapacity
+ rightFit : rightCut ≤ cutCapacity
+
+/-- Public fixed offsets of one-bit-per-word header fields. -/
+inductive Header (L : Lengths)
+ | group (g : Fin 2) (i : Fin L.index)
+ | advice (i : Fin L.advice)
+ | leftCut (i : Fin L.leftCut)
+ | rightCut (i : Fin L.rightCut)
+ deriving DecidableEq
+
+/-- Size of the reserved header in words. Three cut lengths precede two group indices, the
+advice and two outer cut arrays. -/
+def Header.count (L : Lengths) := 3 + 2*L.index + L.advice + 2*L.cutCapacity
+
+/-- Physical word address of a supplied header bit, using one word per bit and the reserved
+stride between the outer cuts. -/
+def Header.address {L : Lengths} (j : Header L) : Fin (Header.count L) :=
+ match j with
+ | .group g i => ⟨3 + g.val * L.index + i.val, by
+ rcases (show g.val = 0 ∨ g.val = 1 by have := g.isLt; omega) with hg | hg <;>
+ simp [hg, Header.count] <;> omega⟩
+ | .advice i => ⟨3 + 2*L.index + i.val, by unfold Header.count; omega⟩
+ | .leftCut i => ⟨3 + 2*L.index + L.advice + i.val, by have := L.leftFit; unfold Header.count; omega⟩
+ | .rightCut i => ⟨3 + 2*L.index + L.advice + L.cutCapacity + i.val, by have := L.rightFit; unfold Header.count; omega⟩
+
+/-- Index a complete internal assignment, allowing every value on all
+directed transcript bits as well as on the middle cut. -/
+abbrev Internal (L : Lengths) (r H w : ℕ) :=
+ (Fin L.middleCut) ⊕ (Fin 2 × RAMLayout.SharedBit r H w)
+
+/-- A site in the pair of primed groups, identified by its group and its `r`-bit site index. -/
+abbrev Site (r : ℕ) := Fin 2 × Fin (2^r)
+
+/-- The five parts of a row, in the paper's order. -/
+abbrev Field (P r H w pad : ℕ) :=
+ Fin P ⊕ Fin r ⊕ Fin 4 ⊕ RAMLayout.Slot r H w ⊕ Fin pad
+
+/-- One bit position in the input rectangle, specified by a group, a site and a field within
+that site's row. -/
+abbrev Cell (P r H w pad : ℕ) := Site r × Field P r H w pad
+
+/-- The position within a row has exactly the arithmetic offset obtained by
+concatenating its fields. -/
+def fieldIndex (P r H w pad : ℕ) :
+ Field P r H w pad ≃ Fin (P+(r+(4+(width r H w+pad)))) :=
+ let ports := ((offset r H w).sumCongr (Equiv.refl (Fin pad))).trans finSumFinEquiv
+ let header := ((Equiv.refl (Fin 4)).sumCongr ports).trans finSumFinEquiv
+ let address := ((Equiv.refl (Fin r)).sumCongr header).trans finSumFinEquiv
+ ((Equiv.refl (Fin P)).sumCongr address).trans finSumFinEquiv
+
+/-- Row-major flattening for the two groups, all their sites and all their
+bit positions. -/
+def cellIndex (P r H w pad : ℕ) : Cell P r H w pad ≃
+ Fin ((2 * 2^r) * (P+(r+(4+(width r H w+pad))))) :=
+ (finProdFinEquiv.prodCongr (fieldIndex P r H w pad)).trans finProdFinEquiv
+
+variable {P r H w pad : ℕ} {L : Lengths}
+
+/-- Prefix and address are private literals. The only external probes in a
+row position are a prescribed header read or a read at a chosen endpoint. -/
+inductive Ref (L : Lengths) (r H w : ℕ)
+ | literal (value : Bool)
+ | header (j : Header L)
+ | shared (b : Internal L r H w)
+
+/-- Resolve the four bits following the address. Beyond a supplied field's
+length the bit is a literal zero. -/
+def headerRef (L : Lengths) (g : Fin 2) (v : Fin (2^r)) (i : Fin 4) : Ref L r H w :=
+ match i.val with
+ | 0 => if h : v.val < L.index then .header (.group g ⟨v.val,h⟩) else .literal false
+ | 1 => if h : v.val < L.advice then .header (.advice ⟨v.val,h⟩) else .literal false
+ | 2 => if g = 0 then
+ if h : v.val < L.leftCut then .header (.leftCut ⟨v.val,h⟩) else .literal false
+ else if h : v.val < L.middleCut then .shared (.inl ⟨v.val,h⟩) else .literal false
+ | _ => if g = 0 then
+ if h : v.val < L.middleCut then .shared (.inl ⟨v.val,h⟩) else .literal false
+ else if h : v.val < L.rightCut then .header (.rightCut ⟨v.val,h⟩) else .literal false
+
+/-- Resolve a row bit to a literal, a supplied header bit or an internal shared bit. Padding
+and missing ports resolve to zero. -/
+def cellRef (L : Lengths) (prefixBits : Fin P → Bool) (c : Cell P r H w pad) : Ref L r H w :=
+ match c.2 with
+ | .inl p => .literal (prefixBits p)
+ | .inr (.inl a) => .literal (RAMSerialization.wordBits r c.1.2 a)
+ | .inr (.inr (.inl i)) => headerRef L c.1.1 c.1.2 i
+ | .inr (.inr (.inr (.inl port))) =>
+ match hs : source (c.1.2, port) with
+ | none => .literal false
+ | some u => .shared (.inr (c.1.1, ⟨u, source_shared hs⟩))
+ | .inr (.inr (.inr (.inr _))) => .literal false
+
+/-- Read the Boolean value of a row reference using the supplied header and the assignment to
+internal bits. -/
+def Ref.value (hdr : Header L → Bool) (bits : Internal L r H w → Bool) : Ref L r H w → Bool
+ | .literal b => b
+ | .header j => hdr j
+ | .shared j => bits j
+
+/-- Only the outgoing middle-cut slot of group zero and existing send slots
+are visited as binary branches during the first pass. -/
+def cellOwner (L : Lengths) (c : Cell P r H w pad) : Bool :=
+ match c.2 with
+ | .inr (.inr (.inl j)) => decide (j = 3 ∧ c.1.1 = 0 ∧ c.1.2.val < L.middleCut)
+ | .inr (.inr (.inr (.inl port))) => decide (IsSend (c.1.2, port))
+ | _ => false
+
+private def owner (hmid : L.middleCut ≤ 2^r) (b : Internal L r H w) : Cell P r H w pad :=
+ match b with
+ | .inl v => ((0, ⟨v.val, v.isLt.trans_le hmid⟩), .inr (.inr (.inl 3)))
+ | .inr (g, port) => ((g, port.val.1), .inr (.inr (.inr (.inl port.val.2))))
+
+private theorem owner_designated (hmid : L.middleCut ≤ 2^r) (b : Internal L r H w) :
+ cellOwner L (owner (P := P) (pad := pad) hmid b) = true := by
+ rcases b with v | ⟨g, port⟩
+ · simp [owner, cellOwner, v.isLt]
+ · simpa [owner, cellOwner] using port.property
+
+private def ownerBit (c : {c : Cell P r H w pad // cellOwner L c = true}) : Internal L r H w := by
+ rcases c with ⟨⟨⟨g,v⟩, p | (a | (i | (port | padbit)))⟩, hc⟩
+ · simp [cellOwner] at hc
+ · simp [cellOwner] at hc
+ · simp [cellOwner] at hc
+ exact .inl ⟨v.val,hc.2.2⟩
+ · exact .inr (g, ⟨(v,port), by simpa [cellOwner] using hc⟩)
+ · simp [cellOwner] at hc
+
+/-- A bijection, including multiplicities, from the bits in (9.4) to the
+exact cells where the first-pass RAM makes a branch. -/
+def ownerEquiv (P pad : ℕ) (hmid : L.middleCut ≤ 2^r) :
+ Internal L r H w ≃ {c : Cell P r H w pad // cellOwner L c = true} where
+ toFun b := ⟨owner hmid b, owner_designated hmid b⟩
+ invFun := ownerBit
+ left_inv b := by
+ rcases b with v | ⟨g, port⟩
+ · rfl
+ · rfl
+ right_inv c := by
+ rcases c with ⟨⟨⟨g,v⟩, p | (a | (i | (port | padbit)))⟩, hc⟩
+ · simp [cellOwner] at hc
+ · simp [cellOwner] at hc
+ · obtain ⟨rfl,rfl,hv⟩ : i = 3 ∧ g = 0 ∧ v.val < L.middleCut := by simpa [cellOwner] using hc
+ rfl
+ · rfl
+ · simp [cellOwner] at hc
+
+/-- Physical cell that stores one chosen bit, for second-pass random access. -/
+def chosenAddress (P pad : ℕ) (hmid : L.middleCut ≤ 2^r) (b : Internal L r H w) :=
+ cellIndex P r H w pad ((ownerEquiv P pad hmid b).val)
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMLayoutExecution.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMLayoutExecution.lean
new file mode 100644
index 0000000000..8947ac3fb5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMLayoutExecution.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+import OAI.Computability.VPVNP.PrimedInputRAMUniform
+
+/-!
+# Native RAM histories for the two primed input passes
+
+In Section 11 each internal bit has one owner in the first pass. The second
+pass copies the owner's bit to every position that refers to it. For the
+prescribed header memory, the accepting native histories are in bijection
+with all internal assignments, and their reports recover the parser's input
+at every site and bit offset.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Layout
+
+open BurstRAM
+
+variable {L : Lengths} {n r H w : ℕ} (Q : Layout L n r H w)
+
+/-- The public cursor reaches both complete rectangles and the final halt. -/
+theorem cursorFits (Q : Layout L n r H w) : positions n r + positions n r < 2^w := by
+ have h := Q.headersFit
+ have := Q.addressesFit
+ unfold Header.count at h
+ omega
+
+/-- Instantiate the two passes at the addresses of the primed tapes. -/
+def twoPass (bitWord : Bool → Word w) : TwoPass (positions n r) w where
+ own := Q.owns
+ scratch := Q.bitAddress
+ dest := Q.outputAddress
+ source := Q.source bitWord
+
+/-- The burst-RAM program that first chooses shared bits in the layout and then copies the
+resolved input bits into their rows. -/
+def inputProgram (bitWord : Bool → Word w) : Program w (Dispatch w) :=
+ scheduledProgram (Q.twoPass bitWord).ops bitWord Q.cursorFits
+
+/-- Native reports including the terminal call, for an internal assignment. -/
+def inputReports (bitWord : Bool → Word w) (bits : Internal L r H w → Bool)
+ (m : Memory w) : List (Report w) :=
+ (Q.twoPass bitWord).completeReports bitWord Q.cursorFits (Q.assignment bits) m
+
+theorem inputReports_cost (bitWord : Bool → Word w) (bits : Internal L r H w → Bool)
+ (m : Memory w) : RAMBuckets.cost Report.probes (Q.inputReports bitWord bits m) ≤
+ 5 * positions n r + 1 :=
+ (Q.twoPass bitWord).completeReports_cost_le bitWord Q.cursorFits (Q.assignment bits) m
+
+theorem after_inputReports (bitWord : Bool → Word w) (bits : Internal L r H w → Bool)
+ (m : Memory w) : after m (eventLog (Q.inputReports bitWord bits m)) =
+ Q.assembled bitWord bits m :=
+ (Q.twoPass bitWord).after_completeReports bitWord Q.cursorFits (Q.assignment bits) m
+
+/-- All prescribed words below the first scratch address survive both passes. -/
+theorem inputReports_preserve_header (bitWord : Bool → Word w) (bits : Internal L r H w → Bool)
+ (m : Memory w) {a : ℕ} (ha : a < Q.scratchBase) :
+ after m (eventLog (Q.inputReports bitWord bits m)) a = m a := by
+ rw [Q.after_inputReports, assembled, secondPass_outside]
+ · exact store_header _ _ _ _ _ ha
+ · intro i
+ change a ≠ Q.scratchBase + positions n r + i.val
+ omega
+
+/-- Each of the three cut lengths fits in its header word. The exterior
+lengths are bounded by the reserved header capacity and the middle length
+by the number of sites in one rectangle. -/
+theorem cutLength_lt (Q : Layout L n r H w) (j : Fin 3) : cutLength L j < 2 ^ w := by
+ have hfit := Q.fits
+ unfold ProcessorInput.Fits at hfit
+ have hn : 1 ≤ n := by omega
+ have hsites : 2 * 2 ^ r ≤ positions n r := Nat.le_mul_of_pos_right _ hn
+ have hrect := Q.cursorFits
+ have hh := Q.headersFit
+ unfold Header.count at hh
+ have := Q.addressesFit
+ have := Q.middleFits
+ have := L.leftFit
+ have := L.rightFit
+ unfold cutLength
+ split_ifs <;> omega
+
+/-- A fetch of any supplied cut length yields the exact natural number,
+also after the choice and copy phases have run. -/
+theorem inputReports_cutLength (bits : Internal L r H w → Bool) (hdr : Header L → Bool)
+ (hist : List (Word w)) (j : Fin 3) :
+ (after (headerMemory L hdr hist)
+ (eventLog (Q.inputReports (encodeBit w) bits (headerMemory L hdr hist))) j.val).val =
+ cutLength L j := by
+ have hh := Q.headersFit
+ unfold Header.count at hh
+ rw [Q.inputReports_preserve_header _ _ _ (by have := j.isLt; omega), headerMemory_length]
+ exact Nat.mod_eq_of_lt (Q.cutLength_lt j)
+
+/-- The bounded, accepting histories of this RAM enumerate the internal bits
+with their full multiplicity. The site and bucket parameters here are those
+of the auxiliary RAM, which may differ from the primed parameters. -/
+def inputPathEquiv (bitWord : Bool → Word w) (m : Memory w) {S K : ℕ}
+ (hK : 3 ≤ K) (hTotal : 5 * positions n r + 1 ≤ S * K) :
+ ActualPaths (Q.inputProgram bitWord) 3 0 m (withinCaps S K) ≃ (Internal L r H w → Bool) :=
+ ((Q.twoPass bitWord).actualPathEquiv bitWord Q.cursorFits m hK hTotal).trans
+ (Q.internalOwner.symm.arrowCongr (Equiv.refl _))
+
+/-- Every path produces the reports of its decoded internal assignment. -/
+theorem run_inputPath (bitWord : Bool → Word w) (m : Memory w) {S K : ℕ}
+ (hK : 3 ≤ K) (hTotal : 5 * positions n r + 1 ≤ S * K)
+ (p : ActualPaths (Q.inputProgram bitWord) 3 0 m (withinCaps S K)) :
+ runSegment (Q.inputProgram bitWord) 3 (some 0) m p.val =
+ some (Q.inputReports bitWord (Q.inputPathEquiv bitWord m hK hTotal p) m) := by
+ let e := Q.inputPathEquiv bitWord m hK hTotal
+ obtain ⟨bits, rfl⟩ := e.symm.surjective p
+ rw [show Q.inputPathEquiv bitWord m hK hTotal (e.symm bits) = bits from e.apply_symm_apply bits]
+ exact (Q.twoPass bitWord).run_completeReports bitWord Q.cursorFits (Q.assignment bits) m
+
+/-- At every leaf, the words written by the accepting run give the complete
+primed parse input on its assignment, including the exterior header bits. -/
+theorem run_input_bits (hdr : Header L → Bool) (hist : List (Word w)) {S K : ℕ}
+ (hK : 3 ≤ K) (hTotal : 5 * positions n r + 1 ≤ S * K)
+ (p : ActualPaths (Q.inputProgram (encodeBit w)) 3 0 (headerMemory L hdr hist) (withinCaps S K))
+ {rs : List (Report w)}
+ (hr : runSegment (Q.inputProgram (encodeBit w)) 3 (some 0) (headerMemory L hdr hist) p.val =
+ some rs) (u : Site r) (j : Fin n) :
+ after (headerMemory L hdr hist) (eventLog rs)
+ (Q.outputAddress (finProdFinEquiv (finProdFinEquiv u, j))).val =
+ encodeBit w (input Q.program Q.fits hdr
+ (Q.inputPathEquiv (encodeBit w) (headerMemory L hdr hist) hK hTotal p) u j) := by
+ rw [Option.some.inj (hr.symm.trans (Q.run_inputPath _ _ hK hTotal p)), Q.after_inputReports]
+ exact Q.assembled_input _ _ _ _ (headerMemory_bits L hdr hist) u j
+
+end PrimedInputRAM.Layout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOnce.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOnce.lean
new file mode 100644
index 0000000000..131bb23447
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOnce.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-!
+# Running acyclic opcode fragments of the input assembler
+
+These fragments have no internal loop. A supplied Boolean controls any
+explicit choice, and the returned event sequence records its occurrence.
+The implementation below provides executable witnesses for structured
+execution and a static instruction bound on every successful path.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Flow
+
+open BurstRAM PrimedStackRAM
+
+variable {w r k : ℕ}
+
+/-- The event trace, final registers and final memory produced by executing an acyclic code
+fragment. -/
+abbrev Effect (w r : ℕ) := List (Event w) × Regs w r × Memory w
+
+private def leading (e : Event w) (z : Effect w r) : Effect w r := (e :: z.1, z.2)
+
+/-- Execute the branch selected by the register comparison. A loop requires
+its own finite derivation and is excluded from this acyclic evaluator. -/
+def once (pub : Fin k → Word w) (state : Word w) (bit : Bool) :
+ PrimedInputRAM.Flow r k → Regs w r → Memory w → Option (Effect w r)
+ | .line op, rs, m => (op.effect pub state rs m).map fun (e,rs',m') ↦ ([e],rs',m')
+ | .seq a b, rs, m => do
+ let (ea,ra,ma) ← once pub state bit a rs m
+ let (eb,rb,mb) ← once pub state bit b ra ma
+ return (ea++eb,rb,mb)
+ | .ifEq l q yes no, rs, m =>
+ if rs l = rs q then (once pub state bit yes rs m).map (leading .tick)
+ else (once pub state bit no rs m).map (leading .tick)
+ | .ifLt l q yes no, rs, m =>
+ if rs l < rs q then (once pub state bit yes rs m).map (leading .tick)
+ else (once pub state bit no rs m).map (leading .tick)
+ | .branch yes no, rs, m =>
+ if bit then (once pub state bit yes rs m).map (leading (.choice bit))
+ else (once pub state bit no rs m).map (leading (.choice bit))
+ | .whileLt .., _, _ => none
+
+/-- The computed trace is a real finite execution and is bounded by the
+static instruction count. -/
+theorem once_sound (pub : Fin k → Word w) (state : Word w) (bit : Bool) (a : PrimedInputRAM.Flow r k)
+ (rs : Regs w r) (m : Memory w) {es rs' m'}
+ (he : once pub state bit a rs m = some (es,rs',m')) :
+ Exec pub state a rs m es rs' m' ∧ es.length ≤ a.length := by
+ induction a generalizing rs m es rs' m' with
+ | line op =>
+ obtain ⟨⟨e,ra,ma⟩,h,hc⟩ := Option.map_eq_some_iff.mp he
+ cases hc
+ exact ⟨.line h, Nat.le_refl 1⟩
+ | seq a b iha ihb =>
+ simp only [once, bind, Option.bind_eq_some_iff] at he
+ obtain ⟨⟨ea,ra,ma⟩,ha,⟨eb,rb,mb⟩,hb,hc⟩ := he
+ cases hc
+ obtain ⟨hA, cA⟩ := iha _ _ ha
+ obtain ⟨hB, cB⟩ := ihb _ _ hb
+ exact ⟨.seq hA hB, by simpa [length] using Nat.add_le_add cA cB⟩
+ | ifEq l q yes no ihy ihn =>
+ by_cases ht : rs l = rs q
+ · simp only [once, ht, ite_true, Option.map_eq_some_iff] at he
+ obtain ⟨⟨e,ra,ma⟩,h,hc⟩ := he
+ cases hc
+ obtain ⟨hE,c⟩ := ihy _ _ h
+ exact ⟨.ifEqYes ht hE, by simp only [List.length_cons,length]; omega⟩
+ · simp only [once, ht, ite_false, Option.map_eq_some_iff] at he
+ obtain ⟨⟨e,ra,ma⟩,h,hc⟩ := he
+ cases hc
+ obtain ⟨hE,c⟩ := ihn _ _ h
+ exact ⟨.ifEqNo ht hE, by simp only [List.length_cons,length]; omega⟩
+ | ifLt l q yes no ihy ihn =>
+ by_cases ht : rs l < rs q
+ · simp only [once, ht, ite_true, Option.map_eq_some_iff] at he
+ obtain ⟨⟨e,ra,ma⟩,h,hc⟩ := he
+ cases hc
+ obtain ⟨hE,c⟩ := ihy _ _ h
+ exact ⟨.ifLtYes ht hE, by simp only [List.length_cons,length]; omega⟩
+ · simp only [once, ht, ite_false, Option.map_eq_some_iff] at he
+ obtain ⟨⟨e,ra,ma⟩,h,hc⟩ := he
+ cases hc
+ obtain ⟨hE,c⟩ := ihn _ _ h
+ exact ⟨.ifLtNo ht hE, by simp only [List.length_cons,length]; omega⟩
+ | branch yes no ihy ihn =>
+ cases bit
+ · simp only [once, Bool.false_eq_true, ite_false, Option.map_eq_some_iff] at he
+ obtain ⟨⟨e,ra,ma⟩,h,hc⟩ := he
+ cases hc
+ obtain ⟨hE,c⟩ := ihn _ _ h
+ exact ⟨.branchNo hE, by simp only [List.length_cons,length]; omega⟩
+ · simp only [once, ite_true, Option.map_eq_some_iff] at he
+ obtain ⟨⟨e,ra,ma⟩,h,hc⟩ := he
+ cases hc
+ obtain ⟨hE,c⟩ := ihy _ _ h
+ exact ⟨.branchYes hE, by simp only [List.length_cons,length]; omega⟩
+ | whileLt => simp [once] at he
+
+end PrimedInputRAM.Flow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeAct.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeAct.lean
new file mode 100644
index 0000000000..ad15079559
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeAct.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodes
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-!
+# Choice and copy instructions at the end of each data call
+
+The owner flag controls one genuine burst-RAM choice. Nonowner cells of the
+first pass skip the write. Second-pass cells write the literal or the word
+obtained from one read. The next persistent cursor remains in register 29.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ} (pub : Pub → Word w) (state : Word w) (rs : Regs w 48) (m : Memory w)
+
+theorem act_choose (hf : rs 4 < rs 5) (ho : rs 28 = rs 1) (b : Bool) :
+ Flow.Exec pub state act rs m
+ [.tick,.tick,.choice b,.write (rs 30) (if b then rs 1 else rs 0)]
+ rs (writeMemory m (rs 30) (if b then rs 1 else rs 0)) := by
+ apply Flow.Exec.ifLtYes hf
+ apply Flow.Exec.ifEqYes ho
+ cases b
+ · exact .branchNo (.line rfl)
+ · exact .branchYes (.line rfl)
+
+theorem act_skip (hf : rs 4 < rs 5) (ho : rs 28 ≠ rs 1) :
+ Flow.Exec pub state act rs m [.tick,.tick,.tick]
+ (Function.update rs (28 : Reg) (Fin.ofNat _ 0)) m :=
+ .ifLtYes hf (.ifEqNo ho (.line rfl))
+
+theorem act_literal (hf : ¬rs 4 < rs 5) (hl : rs 27 ≠ rs 1) :
+ Flow.Exec pub state act rs m [.tick,.tick,.write (rs 30) (rs 26)]
+ rs (writeMemory m (rs 30) (rs 26)) :=
+ .ifLtNo hf (.ifEqNo hl (.line rfl))
+
+theorem act_fetch (hf : ¬rs 4 < rs 5) (hl : rs 27 = rs 1) :
+ Flow.Exec pub state act rs m [.tick,.tick,.read (rs 26) (m (rs 26).val),
+ .write (rs 30) (m (rs 26).val)] (Function.update rs (26 : Reg) (m (rs 26).val))
+ (writeMemory m (rs 30) (m (rs 26).val)) := by
+ apply Flow.Exec.ifLtNo hf
+ apply Flow.Exec.ifEqYes hl
+ exact Flow.Exec.seq (Flow.Exec.line rfl) (Flow.Exec.line rfl)
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeDispatch.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeDispatch.lean
new file mode 100644
index 0000000000..42f24136ae
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeDispatch.lean
@@ -0,0 +1,231 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodePortResult
+import OAI.Computability.VPVNP.PrimedInputRAMPortRun
+
+/-!
+# Word-level correctness of the rectangular input dispatcher
+
+The opcode table compares each flat position against the prefix, address,
+header and incident-port boundaries. It returns a literal or a source address
+together with the bit's first-pass owner flag. Only private register operations
+are performed between the parameter loads and the final choice or copy.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM RAMLayout
+
+/-- Values required at dispatch entry, including the packed literal prefix
+and the arithmetic bounds for the exclusive ends of the input fields. -/
+structure DispatchInput (L : Lengths) (n r H w base P g v j : ℕ) (prefixAt : ℕ → Bool)
+ (pub : Pub → Word w) (rs : Regs w 48) : Prop where
+ header : HeaderRegisters rs L base n r P g v (rs 25).val
+ sites : (rs 7).val = 2^r
+ incidentWidth : (rs 13).val = width r H w
+ bit : (rs 24).val = j
+ validSite : v < 2^r
+ prefixMatches : ∀ t < P, (rs 17).val.testBit t = prefixAt t
+ boundaryFits : P+r+4+width r H w < 2^w
+ portBlock : (pub 13).val = blockBits H w
+ portFirst : (pub 14).val = 8*w
+ portBase : (pub 15).val = 16*w
+
+/-- Registers 26, 27 and 28 return the payload, fetch flag and owner.
+All registers below 32 other than temporary offset 25 have their specified
+field-result values, including the next cursor and write destination. -/
+def DispatchOutput {w : ℕ} (before after : Regs w 48) (d : RawCopy × Bool) : Prop :=
+ ∀ i : Reg, i.val < 32 → i ≠ 25 → after i = fieldResult before d i
+
+private theorem output_field {w : ℕ} {rs tmp : Regs w 48} (d : RawCopy × Bool)
+ (hp : ∀ i : Reg, i.val < 32 → i ≠ 25 → tmp i = rs i) :
+ DispatchOutput rs (fieldResult tmp d) d := by
+ intro i hi h25
+ by_cases h26 : i = 26
+ · subst i; simp
+ by_cases h27 : i = 27
+ · subst i; simp
+ by_cases h28 : i = 28
+ · subst i; simp
+ rw [fieldResult_other _ _ _ h26 h27 h28, fieldResult_other _ _ _ h26 h27 h28]
+ exact hp i hi h25
+
+private abbrev Ticks {w : ℕ} (pub : Pub → Word w) (state : Word w) (m : Memory w)
+ (a : Code) (rs : Regs w 48) (cost : ℕ) (out : Regs w 48) :=
+ Flow.Exec pub state a rs m (List.replicate cost .tick) out m
+
+private theorem seqTicks {w : ℕ} {pub : Pub → Word w} {state : Word w} {m : Memory w}
+ {a b : Code} {rs middle final : Regs w 48} {x y : ℕ}
+ (ha : Ticks pub state m a rs x middle) (hb : Ticks pub state m b middle y final) :
+ Ticks pub state m (a.seq b) rs (x+y) final := by simpa [Ticks] using ha.seq hb
+
+private theorem yesTicks {w : ℕ} {pub : Pub → Word w} {state : Word w} {m : Memory w}
+ {a b : Code} {rs out : Regs w 48} {t : ℕ} {l q : Reg} (test : rs l < rs q)
+ (ha : Ticks pub state m a rs t out) : Ticks pub state m (.ifLt l q a b) rs (t+1) out :=
+ Flow.Exec.ifLtYes test ha
+
+private theorem noTicks {w : ℕ} {pub : Pub → Word w} {state : Word w} {m : Memory w}
+ {a b : Code} {rs out : Regs w 48} {t : ℕ} {l q : Reg} (test : ¬rs l < rs q)
+ (hb : Ticks pub state m b rs t out) : Ticks pub state m (.ifLt l q a b) rs (t+1) out :=
+ Flow.Exec.ifLtNo test hb
+
+private theorem binTicks {w : ℕ} (pub : Pub → Word w) (state : Word w) (m : Memory w)
+ (op : BinaryOp) (dst lhs rhs : Reg) (rs : Regs w 48) :
+ Ticks pub state m (bin op dst lhs rhs) rs 1
+ (Function.update rs dst (op.eval (rs lhs) (rs rhs))) := .line rfl
+
+private theorem addVal {w : ℕ} (x y : Word w) (h : x.val + y.val < 2^w) :
+ (BinaryOp.add.eval x y).val = x.val + y.val := Fin.val_add_eq_of_add_lt h
+
+private theorem subVal {w : ℕ} (x y : Word w) (h : y.val ≤ x.val) :
+ (BinaryOp.sub.eval x y).val = x.val - y.val := Fin.sub_val_of_le h
+
+private theorem changeHeader {w : ℕ} {rs tmp : Regs w 48} {L : Lengths} {base n r P g v old j : ℕ}
+ (h : HeaderRegisters rs L base n r P g v old)
+ (hp : ∀ i : Reg, i.val < 25 → tmp i = rs i) (hj : (tmp 25).val = j) :
+ HeaderRegisters tmp L base n r P g v j := by
+ rcases h with ⟨h0,h1,h2,h3,hn,hr,hb,hP,hi,ha,hm,hl,hM,hR,hg,hv,_⟩
+ constructor <;> first | exact hj | (rwa [hp _ (by decide)])
+
+private theorem port_exec {w : ℕ} (pub : Pub → Word w) (state : Word w) (rs : Regs w 48)
+ (m : Memory w) {L : Lengths} {n r H base P g v k : ℕ}
+ (ih : HeaderRegisters rs L base n r P g v k) (hR : (rs 7).val = 2^r)
+ (hv : v < 2^r) (hk : k < width r H w) (hb : (pub 13).val = blockBits H w)
+ (h₁ : (pub 14).val = 8*w) (h₂ : (pub 15).val = 16*w) :
+ ∃ cost out, Ticks pub state m (sequence PortCode.program [portResult]) rs cost out ∧
+ cost ≤ 3*r+33 ∧ DispatchOutput rs out (dispatchPort base n r H w P g v k).1 := by
+ let u : Fin (2^r) := ⟨v,hv⟩
+ let i : Fin (width r H w) := ⟨k,hk⟩
+ have hp : PortCode.Input r H u i pub rs :=
+ ⟨ih.zero, ih.one, ih.two, hR, ih.site, ih.offset, hb, h₁, h₂⟩
+ obtain ⟨a,mid,hmid,ha,hm⟩ := PortCode.program_exec (state := state) (m := m) u i rs hp
+ have keep := PortCode.program_preserves hmid
+ have hr : PortResultRegisters mid base n r P g v k := by
+ rcases ih with ⟨hz,ho,_,h3,hn,hs,hbase,hP,_,_,_,_,_,_,hg,hv',hk'⟩
+ constructor <;> rwa [keep _ (by decide)]
+ obtain ⟨b,ht,hout⟩ := exec_portResult pub state mid m hr hm
+ refine ⟨a+b,_,seqTicks hmid hout,by omega,output_field _ (fun j hj _ ↦ keep j hj)⟩
+
+private theorem output_trans {w : ℕ} {rs mid out : Regs w 48} {d : RawCopy × Bool}
+ (h : DispatchOutput mid out d) (hkeep : ∀ i : Reg, i.val < 32 → i ≠ 25 → mid i = rs i) :
+ DispatchOutput rs out d := fun i hi h25 ↦ (h i hi h25).trans (output_field d hkeep i hi h25)
+
+/-- The complete dispatcher computes the paper's scalar decision with
+finite word instructions. Its trace has no external probes and uses only
+private ticks, even at a missing port or on inconsistent message data. -/
+theorem dispatch_exec {w : ℕ} (pub : Pub → Word w) (state : Word w) (rs : Regs w 48) (m : Memory w)
+ {L : Lengths} {n r H base P g v j : ℕ} {prefixAt : ℕ → Bool}
+ (I : DispatchInput L n r H w base P g v j prefixAt pub rs) :
+ ∃ cost out, Flow.Exec pub state (dispatch PortCode.program) rs m (List.replicate cost .tick) out m ∧
+ cost ≤ 3*r+128 ∧ DispatchOutput rs out (dispatchRow L n r H w base P prefixAt g v j).1 := by
+ let ih := I.header
+ have hw : 0 < w := by
+ have h := (rs 1).isLt
+ rw [ih.one] at h
+ by_contra hz
+ have he : w = 0 := by omega
+ simp [he] at h
+ have hone : rs 1 = 1 := by
+ apply Fin.ext
+ simpa [Fin.val_one, Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')] using ih.one
+ have hb := I.boundaryFits
+ by_cases hprefix : j < P
+ · have test : rs 24 < rs 12 := by simpa [Fin.lt_def, I.bit, ih.prefixWidth] using hprefix
+ have hh := exec_literalBit pub state rs m hw hone 17 24
+ rw [I.bit, I.prefixMatches j hprefix] at hh
+ rw [dispatchRow, ite_eq_left hprefix]
+ exact ⟨5,_,Flow.Exec.ifLtYes test hh,by omega,output_field _ (fun _ _ _ ↦ rfl)⟩
+ have testPrefix : ¬ rs 24 < rs 12 := by simpa [Fin.lt_def, I.bit, ih.prefixWidth] using hprefix
+ let a := Function.update rs (35 : Reg) (BinaryOp.add.eval (rs 12) (rs 8))
+ have ha := binTicks pub state m .add 35 12 8 rs
+ have av : (a 35).val = P+r := by
+ change (BinaryOp.add.eval (rs 12) (rs 8)).val = _
+ rw [addVal,ih.prefixWidth,ih.siteBits]
+ rw [ih.prefixWidth,ih.siteBits]; omega
+ by_cases haddr : j < P+r
+ · have test : a 24 < a 35 := by change (rs 24).val < (a 35).val; rw [I.bit,av]; exact haddr
+ let b := Function.update a (25 : Reg) (BinaryOp.sub.eval (a 24) (a 12))
+ have hsub := binTicks pub state m .sub 25 24 12 a
+ have bv : (b 25).val = j-P := by
+ change (BinaryOp.sub.eval (rs 24) (rs 12)).val = _
+ rw [subVal, I.bit, ih.prefixWidth]
+ rw [I.bit, ih.prefixWidth]; omega
+ have hh := exec_literalBit pub state b m hw (show b 1 = 1 from hone) 23 25
+ rw [bv, show (b 23).val = v from ih.site] at hh
+ rw [dispatchRow, ite_eq_right hprefix, ite_eq_left haddr]
+ refine ⟨8,_,noTicks testPrefix (seqTicks ha (yesTicks test (seqTicks hsub hh))),by omega,
+ output_field _ ?_⟩
+ intro i hi h25
+ have h35 : i ≠ 35 := fun he ↦ by subst i; omega
+ simp [a,b,h25,h35]
+ have testAddress : ¬a 24 < a 35 := by
+ change ¬ (rs 24).val < (a 35).val
+ rw [I.bit,av]; exact haddr
+ let b := Function.update a (25 : Reg) (BinaryOp.sub.eval (a 24) (a 35))
+ let c := Function.update b (35 : Reg) (BinaryOp.add.eval (b 35) (b 3))
+ let e := Function.update c (35 : Reg) (BinaryOp.add.eval (c 35) (c 1))
+ have hbc := seqTicks (binTicks pub state m .sub 25 24 35 a) (binTicks pub state m .add 35 35 3 b)
+ have hbe := seqTicks hbc (binTicks pub state m .add 35 35 1 c)
+ have b25 : (b 25).val = j-(P+r) := by
+ change (BinaryOp.sub.eval (rs 24) (a 35)).val = _
+ rw [subVal, I.bit, av]
+ rw [I.bit,av]; omega
+ have c35 : (c 35).val = P+r+3 := by
+ change (BinaryOp.add.eval (a 35) (rs 3)).val = _
+ rw [addVal, av, ih.three]
+ rw [av,ih.three]; omega
+ have e35 : (e 35).val = P+r+4 := by
+ change (BinaryOp.add.eval (c 35) (rs 1)).val = _
+ rw [addVal, c35, ih.one]
+ rw [c35,ih.one]; omega
+ have keepE (i : Reg) (hi : i.val < 32) (h25 : i ≠ 25) : e i = rs i := by
+ have h35 : i ≠ 35 := by intro he; subst i; omega
+ simp [a,b,c,e,h25,h35]
+ by_cases hhead : j < P+r+4
+ · have test : e 24 < e 35 := by change (rs 24).val < _; rw [I.bit,e35]; exact hhead
+ have heh := changeHeader ih
+ (tmp := e) (fun i hi ↦ keepE i (by omega) (fun h ↦ by subst i; omega))
+ (j := j-(P+r)) (show (e 25).val = _ from b25)
+ obtain ⟨t,ht,hh⟩ := exec_headerFields pub state e m heh (by omega)
+ rw [dispatchRow, ite_eq_right hprefix, ite_eq_right haddr, ite_eq_left hhead]
+ have hmax : headerFields.length ≤ 100 := by decide
+ refine ⟨_,_,noTicks testPrefix (seqTicks ha (noTicks testAddress (seqTicks hbe (yesTicks test hh)))),
+ ?_,output_field _ keepE⟩
+ omega
+ have testHeader : ¬e 24 < e 35 := by change ¬ (rs 24).val < _; rw [I.bit,e35]; exact hhead
+ let f := Function.update e (25 : Reg) (BinaryOp.sub.eval (e 24) (e 35))
+ let z := Function.update f (35 : Reg) (BinaryOp.add.eval (f 35) (f 13))
+ have hfz := seqTicks (binTicks pub state m .sub 25 24 35 e) (binTicks pub state m .add 35 35 13 f)
+ have z25 : (z 25).val = j-(P+r+4) := by
+ change (BinaryOp.sub.eval (rs 24) (e 35)).val = _
+ rw [subVal, I.bit, e35]
+ rw [I.bit,e35]; omega
+ have z35 : (z 35).val = P+r+4+width r H w := by
+ change (BinaryOp.add.eval (e 35) (rs 13)).val = _
+ rw [addVal, e35, I.incidentWidth]
+ rw [e35,I.incidentWidth]; exact hb
+ have keepZ (i : Reg) (hi : i.val < 32) (h25 : i ≠ 25) : z i = rs i := by
+ have h35 : i ≠ 35 := by intro he; subst i; omega
+ simp [z,f,h35,h25,keepE i hi h25]
+ by_cases hport : j < P+r+4+width r H w
+ · have test : z 24 < z 35 := by change (rs 24).val < _; rw [I.bit,z35]; exact hport
+ have heh := changeHeader ih
+ (tmp := z) (fun i hi ↦ keepZ i (by omega) (fun h ↦ by subst i; omega)) z25
+ obtain ⟨t,out,hr,ht,hd⟩ := port_exec pub state z m heh (show (z 7).val = _ from I.sites)
+ I.validSite (by omega) I.portBlock I.portFirst I.portBase
+ rw [dispatchRow, ite_eq_right hprefix, ite_eq_right haddr, ite_eq_right hhead, ite_eq_left hport]
+ refine ⟨_,out,noTicks testPrefix (seqTicks ha (noTicks testAddress (seqTicks hbe (noTicks testHeader
+ (seqTicks hfz (yesTicks test hr)))))),?_,output_trans hd keepZ⟩
+ omega
+ · have test : ¬ z 24 < z 35 := by change ¬ (rs 24).val < _; rw [I.bit,z35]; exact hport
+ rw [dispatchRow, ite_eq_right hprefix, ite_eq_right haddr, ite_eq_right hhead, ite_eq_right hport]
+ exact ⟨13,_,noTicks testPrefix (seqTicks ha (noTicks testAddress (seqTicks hbe (noTicks testHeader
+ (seqTicks hfz (noTicks test (exec_literalZero pub state z m))))))),by omega,output_field _ keepZ⟩
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecution.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecution.lean
new file mode 100644
index 0000000000..2608b18191
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecution.lean
@@ -0,0 +1,174 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeDispatch
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeAct
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeLoad
+import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete
+
+/-!
+# Native data calls for the primed input passes
+
+Each call reads the three cut lengths, decodes the persistent cursor and computes the
+source and owner with private word operations. Only the final action may consume a
+branch bit. Its external writes and payload read are the operations of the public
+schedule. The three preceding external reads leave the memory unchanged.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- The first pass uses only the owner bit; the second pass uses the copy source. -/
+def rawItem (first : Bool) (d : RawCopy × Bool) (dest : Word w) : Item w :=
+ if first then if d.2 then .choose dest else .skip
+ else .copy (Layout.compileCopy (encodeBit w) d.1) dest
+
+/-- The skip opcode is a register reset after the two tests. Every other action executes
+the same two tests followed by the public item's data events. -/
+def actEvents (op : Item w) (m : Memory w) (b : Bool) : List (Event w) :=
+ let ticks := match op with | .skip => 3 | _ => 2
+ List.replicate ticks .tick ++ (op.report (encodeBit w) 0 m b).events
+
+private theorem act_raw (pub : Pub → Word w) (state : Word w) (before rs : Regs w 48)
+ (m : Memory w) (first : Bool) (d : RawCopy × Bool) (dest next : Word w) (b : Bool)
+ (hw : 0 < w) (hz : before 0 = 0) (ho : before 1 = 1)
+ (hphase : (before 4 < before 5) ↔ first = true)
+ (hdest : before 30 = dest) (hnext : before 29 = next) (h : DispatchOutput before rs d) :
+ ∃ final, Flow.Exec pub state act rs m (actEvents (rawItem first d dest) m b) final
+ ((rawItem first d dest).memory (encodeBit w) m b) ∧ final 29 = next := by
+ have eqReg (i : Reg) (hi : i.val < 32) (h25 : i ≠ 25) (h26 : i ≠ 26) (h27 : i ≠ 27) (h28 : i ≠ 28) :
+ rs i = before i := (h i hi h25).trans (fieldResult_other before d i h26 h27 h28)
+ have h0 := (eqReg 0 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hz
+ have h1 := (eqReg 1 (by decide) (by decide) (by decide) (by decide) (by decide)).trans ho
+ have h4 := eqReg 4 (by decide) (by decide) (by decide) (by decide) (by decide)
+ have h5 := eqReg 5 (by decide) (by decide) (by decide) (by decide) (by decide)
+ have h29 := (eqReg 29 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hnext
+ have h30 := (eqReg 30 (by decide) (by decide) (by decide) (by decide) (by decide)).trans hdest
+ have howner := (h 28 (by decide) (by decide)).trans (fieldResult_owner before d)
+ have hfetch := (h 27 (by decide) (by decide)).trans (fieldResult_fetch before d)
+ have hval := (h 26 (by decide) (by decide)).trans (fieldResult_payload before d)
+ rw [← h4, ← h5] at hphase
+ rcases d with ⟨src, own⟩
+ cases first with
+ | true =>
+ have hf := hphase.mpr rfl
+ cases own with
+ | true =>
+ have hs : rs 28 = rs 1 := howner.trans h1.symm
+ refine ⟨rs, ?_, h29⟩
+ simpa [actEvents, rawItem, Item.report, cellReport, Item.memory, h0, h1, h30, encodeBit]
+ using act_choose pub state rs m hf hs b
+ | false =>
+ have hs : rs 28 ≠ rs 1 := by
+ rw [howner, h1]; exact fun e ↦ Bool.false_ne_true ((encodeBit_eq_one hw false).mp e)
+ exact ⟨_, act_skip pub state rs m hf hs, h29⟩
+ | false =>
+ have hf : ¬rs 4 < rs 5 := fun e ↦ Bool.false_ne_true (hphase.mp e)
+ cases src with
+ | literal v =>
+ have hl : rs 27 ≠ rs 1 := by
+ rw [hfetch, h1]; exact fun e ↦ Bool.false_ne_true ((encodeBit_eq_one hw false).mp e)
+ refine ⟨rs, ?_, h29⟩
+ simpa [actEvents, rawItem, Layout.compileCopy, Item.report, copyReport, Item.memory,
+ CopySource.get, h30, hval] using act_literal pub state rs m hf hl
+ | fetch a =>
+ have hl : rs 27 = rs 1 := hfetch.trans h1.symm
+ refine ⟨Function.update rs (26 : Reg) (m (rs 26).val), ?_, h29⟩
+ simpa [actEvents, rawItem, Layout.compileCopy, Item.report, copyReport, Item.memory,
+ CopySource.get, h30, hval] using act_fetch pub state rs m hf hl
+
+/-- The reported events record all 28 parameter/coordinate instructions, every private
+dispatch tick, and the final choice or copy. -/
+def dataEvents (m : Memory w) (cost : ℕ) (op : Item w) (b : Bool) : List (Event w) :=
+ (parameterEvents w m ++ List.replicate 7 .tick) ++ List.replicate cost .tick ++ actEvents op m b
+
+private theorem choices_ticks (n : ℕ) : choiceBits (List.replicate n (.tick : Event w)) = [] := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [List.replicate_succ, choiceBits, ih]
+
+private theorem probes_ticks (n : ℕ) : countProbes (List.replicate n (.tick : Event w)) = 0 := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [List.replicate_succ, countProbes, ih]
+
+private theorem probes_append (es fs : List (Event w)) :
+ countProbes (es ++ fs) = countProbes es + countProbes fs := by
+ induction es with
+ | nil => simp [countProbes]
+ | cons e es ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+@[simp] theorem dataEvents_choices (m : Memory w) (cost : ℕ) (op : Item w) (b : Bool) :
+ choiceBits (dataEvents m cost op b) = op.bits b := by
+ simp only [dataEvents, Flow.choiceBits_append, choices_ticks, List.append_nil]
+ change [] ++ choiceBits (actEvents op m b) = _
+ cases op with
+ | skip | choose => rfl
+ | copy src dst => cases src <;> rfl
+
+@[simp] theorem dataEvents_probes (m : Memory w) (cost : ℕ) (op : Item w) (b : Bool) :
+ countProbes (dataEvents m cost op b) = 3 + op.probeCount := by
+ simp only [dataEvents, probes_append, probes_ticks, Nat.add_zero]
+ change 3 + countProbes (actEvents op m b) = _
+ cases op with
+ | skip | choose => rfl
+ | copy src dst => cases src <;> rfl
+
+private theorem after_ticks (m : Memory w) (n : ℕ) : after m (List.replicate n .tick) = m := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simpa [List.replicate_succ, after, update] using ih
+
+@[simp] theorem dataEvents_memory (m : Memory w) (cost : ℕ) (op : Item w) (b : Bool) :
+ after m (dataEvents m cost op b) = op.memory (encodeBit w) m b := by
+ have ap (a : Memory w) (es fs : List (Event w)) : after a (es ++ fs) = after (after a es) fs := by
+ simp [after]
+ simp only [dataEvents, ap, after_ticks]
+ change after m (actEvents op m b) = _
+ cases op with
+ | skip | choose => rfl
+ | copy src dst => cases src <;> rfl
+
+theorem dataEvents_length (m : Memory w) (cost : ℕ) (op : Item w) (b : Bool) :
+ (dataEvents m cost op b).length ≤ cost + 32 := by
+ simp only [dataEvents, List.length_append, List.length_replicate]
+ change 21 + 7 + cost + (actEvents op m b).length ≤ _
+ have ha : (actEvents op m b).length ≤ 4 := by
+ cases op with
+ | skip | choose => simp [actEvents, Item.report, cellReport]
+ | copy src dst => cases src <;> simp [actEvents, Item.report, copyReport]
+ omega
+
+/-- A complete opcode derivation from a decoded dispatch ABI. The dispatch computation
+uses no binary choice, so its tick count can be chosen before the private branch bit. -/
+theorem dataCall_exec {L : Lengths} {n r H base P g v j : ℕ} {prefixAt : ℕ → Bool}
+ (pub : Pub → Word w) (state : Word w) (rs pre : Regs w 48) (m : Memory w)
+ (first : Bool) (dest next : Word w) (hw : 0 < w)
+ (hpre : Flow.Exec pub state (.seq loadParameters unpackCursor) rs m
+ (parameterEvents w m ++ List.replicate 7 .tick) pre m)
+ (I : DispatchInput L n r H w base P g v j prefixAt pub pre)
+ (hphase : pre 4 < pre 5 ↔ first = true) (hdest : pre 30 = dest) (hnext : pre 29 = next) :
+ let d := (dispatchRow L n r H w base P prefixAt g v j).1
+ let op := rawItem first d dest
+ ∃ cost ≤ 3*r+128, ∀ b, ∃ final, Flow.Exec pub state (dataCall PortCode.program) rs m
+ (dataEvents m cost op b) final (op.memory (encodeBit w) m b) ∧ final 29 = next := by
+ dsimp only
+ obtain ⟨cost,out,hr,hc,ho⟩ := dispatch_exec pub state pre m I
+ refine ⟨cost,hc,fun b ↦ ?_⟩
+ have hz : pre 0 = 0 := Fin.ext I.header.zero
+ have hone : pre 1 = 1 := by
+ apply Fin.ext
+ simpa [Fin.val_one, Nat.mod_eq_of_lt (Nat.one_lt_two_pow hw.ne')] using I.header.one
+ obtain ⟨final,ha,hn⟩ := act_raw pub state pre out m first _ dest next b hw hz hone hphase hdest hnext ho
+ exact ⟨final, (hpre.seq hr).seq ha, hn⟩
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionLayout.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionLayout.lean
new file mode 100644
index 0000000000..fdff0666c9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionLayout.lean
@@ -0,0 +1,179 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeExecutionTable
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeParameters
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodePaths
+
+/-!
+# The physical primed input program refines the two-pass schedule
+
+The single finite opcode table runs at the prescribed public parameters. Its data calls
+add precisely three cut-length reads to the public item's probes. The four entry tests
+and all dispatch arithmetic are private. The global correspondence uses only the invariant
+on the three reserved length words, so it also applies to malformed primed message data.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {L : Lengths} {n r H w : ℕ}
+
+/-- The layout's sequence of first-pass bit choices and second-pass copies, using the native
+encoding of a Boolean as a word. -/
+abbrev nativeOps (Q : Layout L n r H w) := (Q.twoPass (encodeBit w)).ops
+/-- Instantiate the fixed two-pass opcode table at the layout's word width and public parameter
+words. -/
+abbrev nativeMachine (Q : Layout L n r H w) := inputTable.instantiate w (pubWord Q)
+
+/-- Per-call instruction allowance for the native input program, equal to `3*r + 165` for an
+`r`-bit site index. -/
+def nativeFuel (r : ℕ) := 3*r + 165
+
+private abbrev Position (n r : ℕ) := Fin (positions n r + positions n r)
+
+private def withinRow {N : ℕ} (i : Fin (N+N)) : Fin N :=
+ ⟨i.val % N, Nat.mod_lt _ (by have := i.isLt; omega)⟩
+
+private def address (Q : Layout L n r H w) (i : Position n r) : Word w :=
+ ⟨Q.scratchBase + i.val, (Nat.add_lt_add_left i.isLt _).trans_le (Nat.add_assoc .. ▸ Q.addressesFit)⟩
+
+private def decision (Q : Layout L n r H w) (i : Position n r) : RawCopy × Bool :=
+ (PrimedInputRAM.dispatch L n r H w Q.scratchBase (UniversalMachine.programPrefix Q.program).length
+ Q.prefixAt (withinRow i).val).1
+
+private theorem scheduled_item (Q : Layout L n r H w) (i : Position n r) :
+ rawItem (decide (i.val < positions n r)) (decision Q i) (address Q i) = nativeOps Q i := by
+ have hr := Q.dispatch_eq (encodeBit w) (withinRow i)
+ have ho := congrArg Prod.snd hr
+ have hs := congrArg Prod.fst hr
+ change (decision Q i).2 = Q.owns (withinRow i) at ho
+ change Layout.compileCopy (encodeBit w) (decision Q i).1 = Q.source (encodeBit w) (withinRow i) at hs
+ cases i using Fin.addCases with
+ | left i =>
+ have he : withinRow (Fin.castAdd (positions n r) i) = i := Fin.ext (Nat.mod_eq_of_lt i.isLt)
+ rw [he] at ho
+ simp only [nativeOps, TwoPass.ops, Fin.append_left, Fin.val_castAdd, i.isLt, decide_true,
+ rawItem, ↓reduceIte, ho]
+ rfl
+ | right i =>
+ have he : withinRow (Fin.natAdd (positions n r) i) = i := by
+ apply Fin.ext
+ simp [withinRow, Nat.mod_eq_of_lt i.isLt]
+ rw [he] at hs
+ simp only [nativeOps, TwoPass.ops, Fin.append_right, Fin.val_natAdd, Nat.not_lt_of_ge (Nat.le_add_right ..),
+ decide_false, rawItem, Bool.false_eq_true, ↓reduceIte, hs, Layout.twoPass]
+ apply congrArg (Item.copy _)
+ apply Fin.ext
+ change Q.scratchBase + (positions n r + i.val) = (Q.scratchBase + positions n r) + i.val
+ omega
+
+private theorem cutMemory_step (Q : Layout L n r H w) (i : Position n r) (m : Memory w)
+ (b : Bool) (hc : CutMemory L m) : CutMemory L ((nativeOps Q i).memory (encodeBit w) m b) := by
+ apply hc.congr
+ intro j
+ have hbase := Q.headersFit
+ unfold Header.count at hbase
+ have haddr : j.val ≠ (address Q i).val := by change j.val ≠ Q.scratchBase + i.val; have := j.isLt; omega
+ rw [← scheduled_item]
+ unfold rawItem
+ split <;> (try split) <;> simp [Item.memory, writeMemory, haddr]
+
+private theorem publicTerminal (Q : Layout L n r H w) (F : ParameterFit Q) :
+ ((pubWord Q 0) + (pubWord Q 0)).val = positions n r + positions n r := by
+ have hn := pubWord_cells Q F
+ rw [Fin.val_add_eq_of_add_lt (by rw [hn]; exact Q.cursorFits), hn]
+
+/-- Execute the input body from arbitrary private registers. This allows the combined
+counter to enter it from its own phase dispatch without changing any public item. -/
+theorem native_body (Q : Layout L n r H w) (F : ParameterFit Q) (i : Position n r)
+ (m : Memory w) (hc : CutMemory L m) (regs : Regs w 48) :
+ let state := cursor Q.cursorFits i.val i.isLt.le
+ ∃ cost ≤ 3*r+128, ∀ b, ∃ final, Flow.Exec (pubWord Q) state body regs m
+ (dataEvents m cost (nativeOps Q i) b) final ((nativeOps Q i).memory (encodeBit w) m b) ∧
+ final 29 = successor Q.cursorFits i := by
+ let st := cursor Q.cursorFits i.val i.isLt.le
+ obtain ⟨pre,hpre,hI⟩ := load_unpack_exec Q F st m regs i.isLt hc
+ have hphase : pre 4 < pre 5 ↔ decide (i.val < positions n r) = true := by
+ rw [Fin.lt_def, hI.stateReg, hI.cells, decide_eq_true_iff]
+ rfl
+ have hdest : pre 30 = address Q i := Fin.ext hI.cursor.dest
+ have hnext : pre 29 = successor Q.cursorFits i := Fin.ext hI.cursor.next
+ have hw : 0 < w := by
+ have hh := Q.headersFit
+ have ha := Q.addressesFit
+ unfold Header.count at hh
+ by_contra! he
+ obtain rfl : w = 0 := by omega
+ simp at ha
+ omega
+ obtain ⟨cost, hcost, runs⟩ := dataCall_exec (pubWord Q) st _ pre m _ _ _ hw hpre hI.dispatch hphase hdest hnext
+ change ∀ b, ∃ final, Flow.Exec _ _ body _ m
+ (dataEvents m cost (rawItem _ (decision Q i) _) b) final ((rawItem _ (decision Q i) _).memory _ m b) ∧ _ at runs
+ rw [scheduled_item] at runs
+ exact ⟨cost, hcost, runs⟩
+
+/-- Each valid data call has its native event list, with one common private dispatch
+cost for both possible values of the selected bit. -/
+theorem native_data (Q : Layout L n r H w) (F : ParameterFit Q) (i : Position n r)
+ (m : Memory w) (hc : CutMemory L m) :
+ let state := cursor Q.cursorFits i.val i.isLt.le
+ ∃ cost ≤ 3*r+128, ∀ b,
+ execute (nativeMachine Q).program (nativeFuel r) ((nativeMachine Q).program.start state) m
+ ((nativeOps Q i).bits b) =
+ some ⟨prefixEvents w ++ dataEvents m cost (nativeOps Q i) b, some (successor Q.cursorFits i)⟩ := by
+ let st := cursor Q.cursorFits i.val i.isLt.le
+ obtain ⟨cost, hcost, runs⟩ := native_body Q F i m hc (prefixRegs st (pubWord Q 0))
+ refine ⟨cost, hcost, fun b ↦ ?_⟩
+ obtain ⟨final,hE,hret⟩ := runs b
+ have hn : st ≠ pubWord Q 0 + pubWord Q 0 := fun h ↦ i.isLt.ne ((congrArg Fin.val h).trans (publicTerminal Q F))
+ have hlen := dataEvents_length m cost (nativeOps Q i) b
+ have hr := execute_data (pubWord Q) st m (nativeFuel r) hn _ final _ hE (by unfold nativeFuel; omega)
+ simpa only [dataEvents_choices, hret] using hr
+
+private def nativeReport (Q : Layout L n r H w) (i : Position n r) (m : Memory w) (b : Bool) : Report w :=
+ (execute (nativeMachine Q).program (nativeFuel r)
+ ((nativeMachine Q).program.start (cursor Q.cursorFits i.val i.isLt.le)) m ((nativeOps Q i).bits b)).getD
+ (haltReport w)
+
+private theorem nativeReport_spec (Q : Layout L n r H w) (F : ParameterFit Q) (i : Position n r)
+ (m : Memory w) (b : Bool) (hc : CutMemory L m) :
+ ∃ cost, nativeReport Q i m b =
+ ⟨prefixEvents w ++ dataEvents m cost (nativeOps Q i) b, some (successor Q.cursorFits i)⟩ := by
+ obtain ⟨cost, _, hr⟩ := native_data Q F i m hc
+ exact ⟨cost, by simp [nativeReport, hr b]⟩
+
+/-- Refinement by the fixed physical program of every scheduled owner and copy call. -/
+def physicalSchedule (Q : Layout L n r H w) (F : ParameterFit Q) :
+ PhysicalSchedule (nativeMachine Q).program (nativeFuel r) (nativeOps Q) (encodeBit w) Q.cursorFits (CutMemory L) where
+ report := nativeReport Q
+ last _ := ⟨prefixEvents w, none⟩
+ data i m b hc := by
+ obtain ⟨cost, _, hr⟩ := native_data Q F i m hc
+ simp only [nativeReport, hr b, Option.getD_some]
+ result i m b hc := by obtain ⟨_, he⟩ := nativeReport_spec Q F i m b hc; rw [he]
+ memory i m b hc := by
+ obtain ⟨cost, he⟩ := nativeReport_spec Q F i m b hc
+ rw [he]
+ change after m (dataEvents m cost (nativeOps Q i) b) = _
+ exact dataEvents_memory ..
+ probes i m b hc := by
+ obtain ⟨cost, he⟩ := nativeReport_spec Q F i m b hc
+ rw [he]
+ change countProbes (dataEvents m cost (nativeOps Q i) b) = _
+ rw [dataEvents_probes, Nat.add_comm]
+ closed := cutMemory_step Q
+ halt m _ := by
+ change execute _ ((3*r+160)+5) _ m [] = _
+ exact execute_terminal _ _ m _ (Fin.ext (publicTerminal Q F).symm)
+ halt_result _ _ := rfl
+ halt_memory _ _ := rfl
+ halt_probes _ _ := rfl
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionPrefix.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionPrefix.lean
new file mode 100644
index 0000000000..8ebe9a3f0c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionPrefix.lean
@@ -0,0 +1,287 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeExecutionLayout
+
+/-!
+# Transferring the physical input prefix to the grammar phase
+
+The data calls of Section 11 return after the second pass with the assembled memory.
+They can be used in a larger program whose data calls are linked to the same opcodes
+and whose terminal cursor enters the parser. The residual stream of parser calls is
+arbitrary and is passed unchanged to that cursor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM
+
+variable {w M : ℕ} {C : Type*} {P : Program w C} {fuel : ℕ} {ops : Fin M → Item w}
+ {bitWord : Bool → Word w} {fit : M < 2^w} {Pre : Memory w → Prop}
+
+/-- Data calls of an enclosing program. Its phase transition can continue in the grammar
+parser, and the extra private ticks of its dispatch may differ from the standalone RAM. -/
+structure ReturningCalls (P : Program w C) (fuel : ℕ) (ops : Fin M → Item w)
+ (bitWord : Bool → Word w) (fit : M < 2^w) (Pre : Memory w → Prop) where
+ /-- Report of one input-stage call in the enclosing program, indexed by the scheduled item,
+ incoming memory and supplied bit. -/
+ report : Fin M → Memory w → Bool → Report w
+ data : ∀ i m b, Pre m → execute P fuel (P.start (cursor fit i.val i.isLt.le)) m
+ ((ops i).bits b) = some (report i m b)
+ result : ∀ i m b, Pre m → (report i m b).result = some (successor fit i)
+ memory : ∀ i m b, Pre m → after m (report i m b).events = (ops i).memory bitWord m b
+ closed : ∀ i m b, Pre m → Pre ((ops i).memory bitWord m b)
+
+/-- Per-item reports before a continuation takes control. -/
+def reportList (ops : Fin M → Item w) (bitWord : Bool → Word w)
+ (report : Fin M → Memory w → Bool → Report w) (g : Fin M → Bool) :
+ List (Fin M) → Memory w → List (Report w)
+ | [], _ => []
+ | i :: xs, m => report i m (g i) :: reportList ops bitWord report g xs ((ops i).memory bitWord m (g i))
+
+namespace ReturningCalls
+
+variable (D : ReturningCalls P fuel ops bitWord fit Pre)
+
+/-- Reports of successive returning input-stage calls, threading each item's memory update into
+the next call. -/
+abbrev dataReports := reportList ops bitWord D.report
+
+private theorem dataReports_end (g : Fin M → Bool) (xs : List (Fin M)) (k : ℕ) (hk : k ≤ M)
+ (ha : Aligned k xs) (m : Memory w) (hm : Pre m) :
+ endState (some (cursor fit k hk)) (D.dataReports g xs m) = some (cursor fit M le_rfl) := by
+ induction xs generalizing k m with
+ | nil =>
+ have he : k = M := by simpa using ha.2
+ subst k
+ rfl
+ | cons i xs ih =>
+ obtain ⟨hi, ht⟩ := aligned_cons ha
+ subst k
+ rw [dataReports, reportList, endState, D.result _ _ _ hm]
+ exact ih _ i.isLt ht _ (D.closed _ _ _ hm)
+
+/-- The actual data reports, taken without the halt, end at the first parser cursor. -/
+theorem prefix_endState (g : Fin M → Bool) (m : Memory w) (hm : Pre m) :
+ endState (some 0) (D.dataReports g (List.finRange M) m) = some (cursor fit M le_rfl) :=
+ D.dataReports_end g _ 0 (Nat.zero_le _) (aligned_all M) m hm
+
+private theorem splice_aux
+ (g : Fin M → Bool) (xs : List (Fin M)) (k : ℕ) (hk : k ≤ M) (ha : Aligned k xs)
+ (m : Memory w) (hm : Pre m) (tail : List (List Bool)) :
+ runSegment P fuel (some (cursor fit k hk)) m (xs.map (fun i ↦ (ops i).bits (g i)) ++ tail) =
+ (runSegment P fuel (some (cursor fit M le_rfl)) (scheduledMemory ops bitWord g xs m) tail).map
+ (D.dataReports g xs m ++ ·) := by
+ induction xs generalizing k m with
+ | nil =>
+ have he : k = M := by simpa using ha.2
+ subst k
+ simp [dataReports, reportList, scheduledMemory]
+ | cons i xs ih =>
+ obtain ⟨hi, ht⟩ := aligned_cons ha
+ subst k
+ simp only [List.map_cons, List.cons_append, runSegment, D.data _ _ _ hm, D.memory _ _ _ hm,
+ D.result _ _ _ hm, dataReports, reportList, scheduledMemory]
+ rw [show successor fit i = cursor fit (i.val+1) i.isLt by rfl, ih _ _ ht _ (D.closed _ _ _ hm)]
+ simp only [Option.map_map, Function.comp_def]
+
+/-- Any enclosing burst program with the physical data-call implementations can resume
+at cursor `M`. Its exit behavior and its remaining private branch streams are unrestricted. -/
+theorem splice
+ (g : Fin M → Bool) (m : Memory w) (hm : Pre m) (tail : List (List Bool)) :
+ runSegment P fuel (some 0) m ((List.finRange M).map (fun i ↦ (ops i).bits (g i)) ++ tail) =
+ (runSegment P fuel (some (cursor fit M le_rfl))
+ (scheduledMemory ops bitWord g (List.finRange M) m) tail).map
+ (D.dataReports g (List.finRange M) m ++ ·) :=
+ D.splice_aux g _ 0 (Nat.zero_le _) (aligned_all M) m hm tail
+
+include D in
+private theorem choices_of_prefix_aux
+ (xs : List (Fin M)) (k : ℕ) (hk : k ≤ M) (ha : Aligned k xs)
+ (m : Memory w) (hm : Pre m) (bits : List (List Bool)) (rs : List (Report w))
+ (hr : runSegment P fuel (some (cursor fit k hk)) m bits = some rs)
+ (hfull : xs.length ≤ bits.length ∨ endState (some (cursor fit k hk)) rs = none) :
+ ∃ g : Fin M → Bool, ∃ suffix, bits = xs.map (fun i ↦ (ops i).bits (g i)) ++ suffix := by
+ induction xs generalizing k m bits rs with
+ | nil => exact ⟨fun _ ↦ false, bits, rfl⟩
+ | cons i xs ih =>
+ obtain ⟨hi, ht⟩ := aligned_cons ha
+ have fresh := aligned_fresh ha
+ subst k
+ cases bits with
+ | nil => simp [runSegment] at hr; subst rs; simp [endState] at hfull
+ | cons bs more =>
+ obtain ⟨a,ts,he,htail,rfl⟩ := unpack_call P fuel _ _ _ _ _ hr
+ obtain ⟨b, rfl⟩ := only_item_choices (ops i) (D.report i m) (fun b ↦ D.data i m b hm) he
+ obtain rfl := Option.some.inj (he.symm.trans (D.data i m b hm))
+ rw [D.result _ _ _ hm, D.memory _ _ _ hm] at htail
+ simp only [List.length_cons, Nat.add_le_add_iff_right, endState, D.result _ _ _ hm] at hfull
+ obtain ⟨g,suffix,rfl⟩ := ih _ i.isLt ht _ (D.closed _ _ _ hm) more ts htail hfull
+ refine ⟨Function.update g i b, suffix, ?_⟩
+ simp only [List.map_cons, List.cons_append, Function.update_self, List.cons.injEq, true_and]
+ congr 1
+ apply List.map_congr_left
+ intro j hj
+ have hne : j ≠ i := fun e ↦ fresh (e ▸ hj)
+ rw [Function.update_of_ne hne]
+
+/-- Conversely, every accepting execution of the enclosing program must pass all the
+input cursors with their prescribed branch streams. Its suffix starts at the grammar
+cursor, consumes the remaining streams, and finishes with an accepting halt. -/
+theorem recover (m : Memory w) (hm : Pre m)
+ (bits : List (List Bool)) (rs : List (Report w))
+ (hr : runSegment P fuel (some 0) m bits = some rs) (hend : endState (some 0) rs = none) :
+ ∃ (g : Fin M → Bool) (suffix : List (List Bool)) (tail : List (Report w)),
+ bits = (List.finRange M).map (fun i ↦ (ops i).bits (g i)) ++ suffix ∧
+ rs = D.dataReports g (List.finRange M) m ++ tail ∧
+ runSegment P fuel (some (cursor fit M le_rfl))
+ (scheduledMemory ops bitWord g (List.finRange M) m) suffix = some tail ∧
+ endState (some (cursor fit M le_rfl)) tail = none := by
+ obtain ⟨g,suffix,rfl⟩ := D.choices_of_prefix_aux _ 0 (Nat.zero_le _) (aligned_all M)
+ m hm bits rs hr (Or.inr hend)
+ rw [D.splice g m hm suffix, Option.map_eq_some_iff] at hr
+ obtain ⟨tail,hcont,rfl⟩ := hr
+ exact ⟨g, suffix, tail, rfl, rfl, hcont, by simpa only [endState_append, D.prefix_endState g m hm] using hend⟩
+
+include D in
+/-- If exactly the data calls have returned, every choice list must have the
+scheduled shape, even when the later program rejects. -/
+theorem choices_of_length (m : Memory w) (hm : Pre m) (bits : List (List Bool))
+ (rs : List (Report w)) (hr : runSegment P fuel (some 0) m bits = some rs)
+ (hlen : bits.length = M) :
+ ∃ g : Fin M → Bool, bits = (List.finRange M).map (fun i ↦ (ops i).bits (g i)) := by
+ obtain ⟨g, suffix, hb⟩ := D.choices_of_prefix_aux _ 0 (Nat.zero_le _) (aligned_all M)
+ m hm bits rs hr (Or.inl (by simp [hlen]))
+ have hs : suffix = [] := by
+ rw [hb, List.length_append, List.length_map, List.length_finRange] at hlen
+ exact List.length_eq_zero_iff.mp (by omega)
+ exact ⟨g, by simpa only [hs, List.append_nil] using hb⟩
+
+end ReturningCalls
+
+namespace PhysicalSchedule
+
+variable (R : PhysicalSchedule P fuel ops bitWord fit Pre)
+
+/-- Reports for the specified physical data calls in order, using the memory produced by each
+preceding item. -/
+abbrev dataReports := reportList ops bitWord R.report
+
+/-- Keep the per-cursor implementations and leave the terminal call to the enclosing
+program. -/
+def returningCalls {C' : Type*} (P' : Program w C') (fuel' : ℕ)
+ (hdata : ∀ i m b, Pre m → execute P' fuel' (P'.start (cursor fit i.val i.isLt.le)) m
+ ((ops i).bits b) = some (R.report i m b)) : ReturningCalls P' fuel' ops bitWord fit Pre :=
+ ⟨R.report, hdata, R.result, R.memory, R.closed⟩
+
+theorem dataReports_matched (g : Fin M → Bool) (xs : List (Fin M)) (m : Memory w) (hm : Pre m) :
+ MatchedReports m (R.dataReports g xs m) (scheduledReports ops bitWord fit g xs m) := by
+ induction xs generalizing m with
+ | nil => exact .nil m
+ | cons i xs ih =>
+ apply MatchedReports.cons
+ · rw [R.result _ _ _ hm, Item.report_result]
+ · rw [R.memory _ _ _ hm, Item.after_report]
+ · simp only [R.probes _ _ _ hm, Item.probes_eq_probeCount, Item.report_result]
+ rfl
+ · rw [Item.after_report]
+ exact ih _ (R.closed _ _ _ hm)
+
+theorem dataReports_cost (g : Fin M → Bool) (xs : List (Fin M)) (m : Memory w) (hm : Pre m) :
+ RAMBuckets.cost Report.probes (R.dataReports g xs m) =
+ RAMBuckets.cost Report.probes (scheduledReports ops bitWord fit g xs m) + 3*xs.length := by
+ induction xs generalizing m with
+ | nil => rfl
+ | cons i xs ih =>
+ have ht := ih _ (R.closed i m (g i) hm)
+ dsimp only [dataReports] at ht
+ simp only [dataReports, reportList, scheduledReports, RAMBuckets.cost, List.length_cons, R.probes _ _ _ hm,
+ Item.probes_eq_probeCount]
+ omega
+
+/-- The actual data reports, taken without the halt, end at the first parser cursor. -/
+theorem prefix_endState (g : Fin M → Bool) (m : Memory w) (hm : Pre m) :
+ endState (some 0) (R.dataReports g (List.finRange M) m) = some (cursor fit M le_rfl) :=
+ (R.returningCalls P fuel R.data).prefix_endState g m hm
+
+/-- Any enclosing burst program with the physical data-call implementations can resume
+at cursor `M`. Its exit behavior and its remaining private branch streams are unrestricted. -/
+theorem splice_data {C' : Type*} (P' : Program w C') (fuel' : ℕ)
+ (hdata : ∀ i m b, Pre m → execute P' fuel' (P'.start (cursor fit i.val i.isLt.le)) m
+ ((ops i).bits b) = some (R.report i m b))
+ (g : Fin M → Bool) (m : Memory w) (hm : Pre m) (tail : List (List Bool)) :
+ runSegment P' fuel' (some 0) m ((List.finRange M).map (fun i ↦ (ops i).bits (g i)) ++ tail) =
+ (runSegment P' fuel' (some (cursor fit M le_rfl))
+ (scheduledMemory ops bitWord g (List.finRange M) m) tail).map
+ (R.dataReports g (List.finRange M) m ++ ·) :=
+ (R.returningCalls P' fuel' hdata).splice g m hm tail
+
+/-- Conversely, every accepting execution of the enclosing program must pass all the
+input cursors with their prescribed branch streams. Its suffix starts at the grammar
+cursor, consumes the remaining streams, and finishes with an accepting halt. -/
+theorem recover_data_prefix {C' : Type*} (P' : Program w C') (fuel' : ℕ)
+ (hdata : ∀ i m b, Pre m → execute P' fuel' (P'.start (cursor fit i.val i.isLt.le)) m
+ ((ops i).bits b) = some (R.report i m b)) (m : Memory w) (hm : Pre m)
+ (bits : List (List Bool)) (rs : List (Report w))
+ (hr : runSegment P' fuel' (some 0) m bits = some rs) (hend : endState (some 0) rs = none) :
+ ∃ (g : Fin M → Bool) (suffix : List (List Bool)) (tail : List (Report w)),
+ bits = (List.finRange M).map (fun i ↦ (ops i).bits (g i)) ++ suffix ∧
+ rs = R.dataReports g (List.finRange M) m ++ tail ∧
+ runSegment P' fuel' (some (cursor fit M le_rfl))
+ (scheduledMemory ops bitWord g (List.finRange M) m) suffix = some tail ∧
+ endState (some (cursor fit M le_rfl)) tail = none :=
+ (R.returningCalls P' fuel' hdata).recover m hm bits rs hr hend
+
+/-- The generated native data calls without the halt. -/
+theorem run_data (g : Fin M → Bool) (m : Memory w) (hm : Pre m) :
+ runSegment P fuel (some 0) m ((List.finRange M).map (fun i ↦ (ops i).bits (g i))) =
+ some (R.dataReports g (List.finRange M) m) := by
+ simpa [runSegment] using R.splice_data P fuel R.data g m hm []
+
+end PhysicalSchedule
+
+namespace Opcodes
+
+variable {L : Lengths} {n r H w : ℕ}
+
+/-- Extend the internal assignment to every cursor; only owner positions consume these bits. -/
+def cursorBits (Q : Layout L n r H w) (bits : Internal L r H w → Bool) :=
+ bitAt ((Q.twoPass (encodeBit w)).assignmentEquiv (Q.assignment bits))
+
+/-- Generated data-call prefix for the actual, finite opcode table. Its cost omits the
+terminal call, and its return cursor and memory are ready for the parser. -/
+theorem input_prefix (Q : Layout L n r H w) (F : ParameterFit Q) (bits : Internal L r H w → Bool)
+ (m : Memory w) (hm : CutMemory L m) :
+ let R := physicalSchedule Q F
+ let g := cursorBits Q bits
+ let cells := List.finRange (positions n r + positions n r)
+ let rs := R.dataReports g cells m
+ runSegment (nativeMachine Q).program (nativeFuel r) (some 0) m
+ (cells.map (fun i ↦ (nativeOps Q i).bits (g i))) = some rs ∧
+ endState (some 0) rs = some (cursor Q.cursorFits _ le_rfl) ∧
+ after m (eventLog rs) = Q.assembled (encodeBit w) bits m ∧
+ RAMBuckets.cost Report.probes rs ≤ 11 * positions n r := by
+ dsimp only
+ let R := physicalSchedule Q F
+ let T := Q.twoPass (encodeBit w)
+ let g := cursorBits Q bits
+ let cells := List.finRange (positions n r + positions n r)
+ refine ⟨R.run_data g m hm, R.prefix_endState g m hm, ?_, ?_⟩
+ · exact ((R.dataReports_matched g cells m hm).after_eq.trans
+ (after_scheduledReports _ _ _ _ _ _)).trans
+ (T.scheduledMemory_eq _ Q.cursorFits (Q.assignment bits) m)
+ · rw [R.dataReports_cost _ _ _ hm, List.length_finRange]
+ have h := T.completeReports_cost_le (encodeBit w) Q.cursorFits (Q.assignment bits) m
+ simp only [TwoPass.completeReports, RAMBuckets.cost_append, haltReport, RAMBuckets.cost,
+ Report.probes, countProbes] at h
+ change RAMBuckets.cost Report.probes (scheduledReports T.ops _ Q.cursorFits g cells m) + _ ≤ _
+ change RAMBuckets.cost Report.probes (scheduledReports T.ops _ Q.cursorFits g cells m) + 1 ≤ 5 * positions n r + 1 at h
+ omega
+
+end Opcodes
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionResult.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionResult.lean
new file mode 100644
index 0000000000..181eaa2ceb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionResult.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeExecutionLayout
+
+/-!
+# The physical input assembler for the two primed groups
+
+The fixed opcode table, started in the prescribed header memory, has one
+accepting native path per internal bit assignment. Every parser leaf receives
+the corresponding tape bit. Three cut-length reads on each of the two visits
+to a rectangular position increase the total cost by exactly six per position.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Layout
+
+open BurstRAM Opcodes
+
+variable {L : Lengths} {n r H w : ℕ} (Q : Layout L n r H w)
+
+/-- The exact cost is the scheduled cost plus three length reads at each data
+call. The same uniform upper bound applies to every assignment and memory. -/
+theorem native_cost_bound (m : Memory w) :
+ scheduledCost (nativeOps Q) + 3 * (positions n r + positions n r) ≤
+ 11 * positions n r + 1 := by
+ have h := (Q.twoPass (encodeBit w)).scheduledCost_le (encodeBit w) Q.cursorFits m
+ change scheduledCost (nativeOps Q) ≤ 5 * positions n r + 1 at h
+ omega
+
+/-- Histories of the actual fixed opcode machine enumerate the shared internal
+bits in the two primed groups. The auxiliary RAM's caps include its header reads. -/
+def nativePathEquiv (F : ParameterFit Q) (m : Memory w) (hc : CutMemory L m) {S K : ℕ}
+ (hK : 6 ≤ K) (hTotal : 11 * positions n r + 1 ≤ S * K) :
+ ActualPaths (nativeMachine Q).program (nativeFuel r) 0 m (withinCaps S K) ≃
+ (Internal L r H w → Bool) :=
+ ((physicalSchedule Q F).pathEquiv m hc hK ((Q.native_cost_bound m).trans hTotal)).trans
+ (Q.inputPathEquiv (encodeBit w) m (by omega) (by omega))
+
+/-- The opcode report list and the semantic input-pass reports carry the same
+memory updates and cursor returns, with three additional probes per data call. -/
+theorem nativeRun_matches (F : ParameterFit Q) (m : Memory w) (hc : CutMemory L m) {S K : ℕ}
+ (hK : 6 ≤ K) (hTotal : 11 * positions n r + 1 ≤ S * K)
+ (p : ActualPaths (nativeMachine Q).program (nativeFuel r) 0 m (withinCaps S K))
+ {rs : List (Report w)} (hr : runSegment (nativeMachine Q).program (nativeFuel r) (some 0) m p.val =
+ some rs) : MatchedReports m rs (Q.inputReports (encodeBit w) (Q.nativePathEquiv F m hc hK hTotal p) m) := by
+ let path := (physicalSchedule Q F).pathEquiv m hc hK ((Q.native_cost_bound m).trans hTotal) p
+ have hg := Q.run_inputPath (encodeBit w) m (by omega : 3 ≤ K)
+ (by omega : 5 * positions n r + 1 ≤ S * K) path
+ have hs := (physicalSchedule Q F).run_matched 0 (Nat.zero_le _) m hc p.val
+ change Option.Rel _ (runSegment (nativeMachine Q).program (nativeFuel r) (some 0) m p.val)
+ (runSegment (Q.inputProgram (encodeBit w)) 3 (some 0) m path.val) at hs
+ rw [hr, hg, Option.rel_some_some] at hs
+ exact hs
+
+theorem nativeRun_memory (F : ParameterFit Q) (m : Memory w) (hc : CutMemory L m) {S K : ℕ}
+ (hK : 6 ≤ K) (hTotal : 11 * positions n r + 1 ≤ S * K)
+ (p : ActualPaths (nativeMachine Q).program (nativeFuel r) 0 m (withinCaps S K))
+ {rs : List (Report w)} (hr : runSegment (nativeMachine Q).program (nativeFuel r) (some 0) m p.val =
+ some rs) : after m (eventLog rs) = Q.assembled (encodeBit w) (Q.nativePathEquiv F m hc hK hTotal p) m :=
+ (Q.nativeRun_matches F m hc hK hTotal p hr).after_eq.trans (Q.after_inputReports ..)
+
+/-- Every address below the scratch rectangle is preserved, including histogram
+entries reserved there and all three cut-length words. -/
+theorem nativeRun_preserves_header (F : ParameterFit Q) (m : Memory w) (hc : CutMemory L m) {S K : ℕ}
+ (hK : 6 ≤ K) (hTotal : 11 * positions n r + 1 ≤ S * K)
+ (p : ActualPaths (nativeMachine Q).program (nativeFuel r) 0 m (withinCaps S K))
+ {rs : List (Report w)} (hr : runSegment (nativeMachine Q).program (nativeFuel r) (some 0) m p.val =
+ some rs) {a : ℕ} (ha : a < Q.scratchBase) : after m (eventLog rs) a = m a := by
+ rw [(Q.nativeRun_matches F m hc hK hTotal p hr).after_eq]
+ exact Q.inputReports_preserve_header _ _ _ ha
+
+/-- Every actual opcode run writes the selected internal assignment's exact
+primed input bit at each physical site and tape offset. -/
+theorem nativeRun_input (F : ParameterFit Q) (hdr : Header L → Bool) (hist : List (Word w)) {S K : ℕ}
+ (hK : 6 ≤ K) (hTotal : 11 * positions n r + 1 ≤ S * K)
+ (p : ActualPaths (nativeMachine Q).program (nativeFuel r) 0 (headerMemory L hdr hist) (withinCaps S K))
+ {rs : List (Report w)} (hr : runSegment (nativeMachine Q).program (nativeFuel r) (some 0)
+ (headerMemory L hdr hist) p.val = some rs) (u : Site r) (j : Fin n) :
+ after (headerMemory L hdr hist) (eventLog rs) (Q.outputAddress (finProdFinEquiv (finProdFinEquiv u,j))).val =
+ encodeBit w (input Q.program Q.fits hdr
+ (Q.nativePathEquiv F _ (cutMemory_header Q hdr hist) hK hTotal p) u j) := by
+ rw [Q.nativeRun_memory F _ (cutMemory_header Q hdr hist) hK hTotal p hr]
+ exact Q.assembled_input _ _ _ _ (headerMemory_bits L hdr hist) u j
+
+/-- Exact and uniform bounds for the native reports of any accepting opcode
+history, without first imposing a cost cap on that history. -/
+theorem nativeRun_cost (F : ParameterFit Q) (m : Memory w) (hc : CutMemory L m)
+ (bits : List (List Bool)) {rs : List (Report w)}
+ (hr : runSegment (nativeMachine Q).program (nativeFuel r) (some 0) m bits = some rs)
+ (hend : endState (some 0) rs = none) :
+ RAMBuckets.cost Report.probes rs = scheduledCost (nativeOps Q) + 6 * positions n r ∧
+ RAMBuckets.cost Report.probes rs ≤ 11 * positions n r + 1 ∧ ∀ call ∈ rs, 1 + call.probes ≤ 6 := by
+ obtain ⟨hs, hp⟩ := (physicalSchedule Q F).accepted_cost m hc bits hr hend
+ have hbound := Q.native_cost_bound m
+ change RAMBuckets.cost Report.probes rs = scheduledCost (nativeOps Q) +
+ 3 * (positions n r + positions n r) at hs
+ exact ⟨by omega, hs.trans_le hbound, hp⟩
+
+end PrimedInputRAM.Layout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionTable.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionTable.lean
new file mode 100644
index 0000000000..9b9b28917b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeExecutionTable.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeExecution
+
+/-!
+# The finite table for the two-pass input RAM
+
+Four private instructions compare the persistent cursor with twice the public rectangle
+size. At the terminal cursor they jump to accept. At each data cursor they jump into the
+compiled input block, whose return instruction supplies the next cursor from register 29.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+/-- Code for one data call. It loads parameters, decodes the cursor, resolves the incident port
+when needed, and performs the scheduled action. -/
+abbrev body := dataCall PortCode.program
+/-- Number of instruction addresses in the input table, including its seven front instructions
+and the data-call body. -/
+abbrev pcCount := 7 + body.length
+
+private def front (i : Fin 7) : Fin pcCount := Fin.castAdd body.length i
+
+/-- Translate a data-call instruction label into its table address after the seven front
+instructions. -/
+def bodyLabel (i : body.Label) : Fin pcCount := Fin.natAdd 7 (body.labels i)
+
+/-- Instruction address that returns register 29 as the next persistent cursor. -/
+def returnPC := front 5
+/-- Address of the input table's rejection instruction. -/
+def badPC := front 6
+
+private def beforeBody : Fin 7 → Instr 2 pcCount 48 16 :=
+ ![.stateWord 4 (front 1), .publicWord 5 0 (front 2), .binary .add 30 5 5 (front 3),
+ .jumpEq 4 30 (front 4) (bodyLabel body.entry), .accept, .returnState 29, .reject]
+
+/-- The same opcode table works for all parameter lengths and word widths. -/
+def inputTable : Template pcCount 48 16 where
+ literalWidth := 2
+ entry := front 0
+ code := Fin.append beforeBody (fun j ↦
+ ((body.code (body.labels.symm j)).map (fun t ↦ (t.map bodyLabel).getD returnPC)).emit badPC)
+
+variable {w : ℕ}
+
+private theorem table_front (pub : Pub → Word w) (i : Fin 7) :
+ (inputTable.instantiate w pub).code (front i) = (beforeBody i).resize w := by
+ simp only [Template.instantiate, inputTable, front, Fin.append_left]
+
+theorem inputTable_linked (pub : Pub → Word w) :
+ Flow.Linked (inputTable.instantiate w pub) body bodyLabel returnPC badPC := by
+ constructor
+ intro i
+ simp only [Template.instantiate, inputTable, bodyLabel, Fin.append_right, Equiv.symm_apply_apply]
+
+theorem inputTable_reject (pub : Pub → Word w) : (inputTable.instantiate w pub).code badPC = .reject := by
+ rw [badPC, table_front]; rfl
+
+/-- The four private ticks spent comparing the persistent cursor with the end of the two
+passes. -/
+def prefixEvents (w : ℕ) : List (Event w) := List.replicate 4 .tick
+
+/-- Registers after the four entry instructions. Registers 4, 5 and 30 hold the cursor, the
+rectangle size and twice that size. -/
+def prefixRegs (state cells : Word w) : Regs w 48 :=
+ Function.update (Function.update (Function.update (fun _ ↦ 0) (4 : Reg) state) (5 : Reg) cells)
+ (30 : Reg) (cells + cells)
+
+/-- Execute the four private prologue opcodes, preserving memory and branch choices. -/
+private theorem execute_prologue (pub : Pub → Word w) (state : Word w) (m : Memory w)
+ (fuel : ℕ) (bs : List Bool) :
+ let M := inputTable.instantiate w pub
+ execute M.program (fuel+4) (M.program.start state) m bs =
+ (execute M.program fuel
+ ⟨if state = pub 0 + pub 0 then front 4 else bodyLabel body.entry,
+ state, prefixRegs state (pub 0), fun _ ↦ 0⟩ m bs).map (Flow.prependEvents (prefixEvents w)) := by
+ let M := inputTable.instantiate w pub
+ have h0 : M.code (front 0) = .stateWord 4 (front 1) := table_front pub 0
+ have h1 : M.code (front 1) = .publicWord 5 0 (front 2) := table_front pub 1
+ have h2 : M.code (front 2) = .binary .add 30 5 5 (front 3) := table_front pub 2
+ have h3 : M.code (front 3) = .jumpEq 4 30 (front 4) (bodyLabel body.entry) := table_front pub 3
+ change execute M.program (fuel+4) ⟨front 0,state,fun _ ↦ 0,fun _ ↦ 0⟩ m bs = _
+ simp only [execute, Machine.program, h0, h1, h2, h3, Instr.run, Config.put, BinaryOp.eval,
+ Option.map_map]
+ rfl
+
+/-- At the terminal cursor the physical RAM accepts after four private ticks. -/
+theorem execute_terminal (pub : Pub → Word w) (state : Word w) (m : Memory w) (fuel : ℕ)
+ (hterm : state = pub 0 + pub 0) :
+ let M := inputTable.instantiate w pub
+ execute M.program (fuel+5) (M.program.start state) m [] = some ⟨prefixEvents w, none⟩ := by
+ dsimp only
+ rw [show fuel+5 = (fuel+1)+4 by omega, execute_prologue, ite_eq_left hterm]
+ have h4 : (inputTable.instantiate w pub).code (front 4) = .accept := table_front pub 4
+ simp only [execute, Machine.program, h4, Instr.run, ↓reduceIte, Option.map_some]
+ rfl
+
+/-- The linked body may start with the prologue's live registers. It returns register 29
+after exactly the structured trace, with the four control ticks included in the report. -/
+theorem execute_data (pub : Pub → Word w) (state : Word w) (m : Memory w) (fuel : ℕ)
+ (hdata : state ≠ pub 0 + pub 0) (es : List (Event w)) (final : Regs w 48) (m' : Memory w)
+ (hE : Flow.Exec pub state body (prefixRegs state (pub 0)) m es final m')
+ (hlen : es.length + 4 < fuel) :
+ let M := inputTable.instantiate w pub
+ execute M.program fuel (M.program.start state) m (choiceBits es) =
+ some ⟨prefixEvents w ++ es, some (final 29)⟩ := by
+ dsimp only
+ let left := fuel - (es.length + 4)
+ have hleft : 0 < left := Nat.sub_pos_of_lt hlen
+ have he := hE.execute (inputTable_linked pub) (inputTable_reject pub) (fun _ ↦ 0) left []
+ simp only [List.append_nil] at he
+ have hout : (inputTable.instantiate w pub).code returnPC = .returnState 29 := table_front pub 5
+ obtain ⟨t,ht⟩ := Nat.exists_eq_succ_of_ne_zero hleft.ne'
+ rw [ht] at he
+ have hret : execute (inputTable.instantiate w pub).program (t+1)
+ ⟨returnPC,state,final,fun _ ↦ 0⟩ m' [] = some ⟨[], some (final 29)⟩ := by
+ simp [execute, Machine.program, hout, Instr.run]
+ rw [hret, Option.map_some] at he
+ rw [show fuel = (es.length+(t+1))+4 by dsimp [left] at ht; omega, execute_prologue, ite_eq_right hdata, he]
+ simp [Flow.prependEvents]
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeFields.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeFields.lean
new file mode 100644
index 0000000000..9d2c0591da
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeFields.lean
@@ -0,0 +1,161 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodes
+import OAI.Computability.VPVNP.PrimedInputRAMDispatch
+import Mathlib.Data.ZMod.Defs
+
+/-!
+# Native word instructions for literals and header fields
+
+The four header fields choose between a literal zero and an address derived from the
+loaded parameters. A middle-cut bit is owned only by the outgoing endpoint of group
+zero. All paths in these blocks update only the payload, fetch flag, and owner flag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Register output common to all field decisions. -/
+def fieldResult (rs : Regs w 48) (d : RawCopy × Bool) : Regs w 48 :=
+ let (value, fetch) := match d.1 with
+ | .literal b => (encodeBit w b, (0 : Word w))
+ | .fetch addr => ((addr : Word w), 1)
+ Function.update (Function.update (Function.update rs (26 : Reg) value) 27 fetch) 28 (encodeBit w d.2)
+
+@[simp] theorem fieldResult_payload (rs : Regs w 48) (d : RawCopy × Bool) :
+ fieldResult rs d 26 = match d.1 with
+ | .literal b => encodeBit w b
+ | .fetch addr => (addr : Word w) := by
+ rcases d with ⟨src, own⟩
+ cases src <;> rfl
+
+@[simp] theorem fieldResult_fetch (rs : Regs w 48) (d : RawCopy × Bool) :
+ fieldResult rs d 27 = match d.1 with
+ | .literal _ => 0
+ | .fetch _ => 1 := by
+ rcases d with ⟨src, own⟩
+ cases src <;> rfl
+
+@[simp] theorem fieldResult_owner (rs : Regs w 48) (d : RawCopy × Bool) :
+ fieldResult rs d 28 = encodeBit w d.2 := by
+ rcases d with ⟨src, own⟩
+ cases src <;> rfl
+
+theorem fieldResult_other (rs : Regs w 48) (d : RawCopy × Bool) (i : Reg)
+ (h26 : i ≠ 26) (h27 : i ≠ 27) (h28 : i ≠ 28) : fieldResult rs d i = rs i := by
+ rcases d with ⟨src, own⟩
+ cases src <;> simp [fieldResult, Function.update_of_ne, h26, h27, h28]
+
+/-- The shift-and-mask implements the mathematical bit, including shifts beyond
+the end of the word. -/
+theorem readBit_word (hw : 0 < w) (x j : Word w) :
+ BinaryOp.bitAnd.eval (BinaryOp.shiftRight.eval x j) 1 = encodeBit w (x.val.testBit j.val) := by
+ have hone := Nat.one_lt_two_pow hw.ne'
+ by_cases hj : j.val < w
+ · have hshift : x.val / 2^j.val < 2^w := (Nat.div_le_self ..).trans_lt x.isLt
+ rcases Nat.mod_two_eq_zero_or_one (x.val / 2^j.val) with hb | hb <;>
+ simp [BinaryOp.eval, hj, Nat.shiftRight_eq_div_pow, Nat.mod_eq_of_lt hshift,
+ Nat.mod_eq_of_lt hone, Nat.testBit_eq_decide_div_mod_eq, hb, encodeBit]
+ · have ht := Nat.testBit_lt_two_pow (x := x.val) (i := j.val)
+ (x.isLt.trans_le (Nat.pow_le_pow_right (by decide) (Nat.le_of_not_gt hj)))
+ simp [BinaryOp.eval, hj, ht, encodeBit]
+
+theorem exec_literalZero (pub : Pub → Word w) (state : Word w) (rs : Regs w 48) (m : Memory w) :
+ Flow.Exec pub state literalZero rs m (List.replicate 3 .tick)
+ (fieldResult rs (.literal false, false)) m :=
+ (Flow.once_sound pub state false literalZero rs m rfl).1
+
+theorem exec_literalBit (pub : Pub → Word w) (state : Word w) (rs : Regs w 48) (m : Memory w)
+ (hw : 0 < w) (hone : rs 1 = 1) (src amount : Reg) :
+ Flow.Exec pub state (literalBit src amount) rs m (List.replicate 4 .tick)
+ (fieldResult rs (.literal ((rs src).val.testBit (rs amount).val), false)) m := by
+ apply (Flow.once_sound pub state false _ rs m ?_).1
+ change some (_, Function.update (Function.update (Function.update (Function.update rs (26 : Reg) _)
+ 26 (BinaryOp.bitAnd.eval (BinaryOp.shiftRight.eval (rs src) (rs amount)) (rs 1))) 27 0) 28 0, m) = _
+ rw [Function.update_idem, hone, readBit_word hw]
+ rfl
+
+/-- Register values after loading the public dimensions and cut lengths and
+decoding the current row's group, site, and header offset. -/
+structure HeaderRegisters (rs : Regs w 48) (L : Lengths) (base n r P g v j : ℕ) : Prop where
+ zero : (rs 0).val = 0
+ one : (rs 1).val = 1
+ two : (rs 2).val = 2
+ three : (rs 3).val = 3
+ rowWidth : (rs 6).val = n
+ siteBits : (rs 8).val = r
+ baseAddr : (rs 11).val = base
+ prefixWidth : (rs 12).val = P
+ indexWidth : (rs 14).val = L.index
+ adviceWidth : (rs 15).val = L.advice
+ cutCapacity : (rs 16).val = L.cutCapacity
+ leftCut : (rs 18).val = L.leftCut
+ middleCut : (rs 19).val = L.middleCut
+ rightCut : (rs 20).val = L.rightCut
+ group : (rs 22).val = g
+ site : (rs 23).val = v
+ offset : (rs 25).val = j
+
+private theorem regCast {x : Word w} {v : ℕ} (h : x.val = v) : x = (v : Word w) := by
+ rw [← h, Fin.cast_val_eq_self]
+
+theorem once_headerFields (pub : Pub → Word w) (state : Word w) (bit : Bool)
+ (rs : Regs w 48) (m : Memory w) {L : Lengths} {base n r P g v j : ℕ}
+ (h : HeaderRegisters rs L base n r P g v j) (hj : j < 4) :
+ ∃ t, Flow.once pub state bit headerFields rs m = some (List.replicate t .tick,
+ fieldResult rs (dispatchHeader L base n r P g v j), m) := by
+ have ej₀ : rs 25 = rs 0 ↔ j = 0 := by rw [Fin.ext_iff, h.offset, h.zero]
+ have ej₁ : rs 25 = rs 1 ↔ j = 1 := by rw [Fin.ext_iff, h.offset, h.one]
+ have ej₂ : rs 25 = rs 2 ↔ j = 2 := by rw [Fin.ext_iff, h.offset, h.two]
+ have eg : rs 22 = rs 0 ↔ g = 0 := by rw [Fin.ext_iff, h.group, h.zero]
+ have vi : rs 23 < rs 14 ↔ v < L.index := by rw [Fin.lt_def, h.site, h.indexWidth]
+ have va : rs 23 < rs 15 ↔ v < L.advice := by rw [Fin.lt_def, h.site, h.adviceWidth]
+ have vl : rs 23 < rs 18 ↔ v < L.leftCut := by rw [Fin.lt_def, h.site, h.leftCut]
+ have vm : rs 23 < rs 19 ↔ v < L.middleCut := by rw [Fin.lt_def, h.site, h.middleCut]
+ have vr : rs 23 < rs 20 ↔ v < L.rightCut := by rw [Fin.lt_def, h.site, h.rightCut]
+ obtain rfl | rfl | rfl | rfl : j = 0 ∨ j = 1 ∨ j = 2 ∨ j = 3 := by omega
+ case' inl =>
+ by_cases hv : v < L.index <;> refine ⟨if v < L.index then 7 else 5, ?_⟩
+ case' inr.inl =>
+ by_cases hv : v < L.advice <;> refine ⟨if v < L.advice then 8 else 6, ?_⟩
+ case' inr.inr.inl =>
+ refine ⟨if g = 0 then (if v < L.leftCut then 11 else 8)
+ else (if v < L.middleCut then 12 else 8), ?_⟩
+ by_cases hg : g = 0 <;> by_cases hv : v < (if g = 0 then L.leftCut else L.middleCut)
+ all_goals simp only [hg, ↓reduceIte] at hv
+ case' inr.inr.inr =>
+ refine ⟨if g = 0 then (if v < L.middleCut then 12 else 8)
+ else (if v < L.rightCut then 12 else 8), ?_⟩
+ by_cases hg : g = 0 <;> by_cases hv : v < (if g = 0 then L.middleCut else L.rightCut)
+ all_goals simp only [hg, ↓reduceIte] at hv
+ all_goals
+ simp (config := { decide := true }) only [headerFields, Flow.once, indexField, adviceField, leftField, middleField,
+ rightField, dispatchHeader, ↓reduceIte, *]
+ all_goals first | rfl |
+ (simp [fetched, adviceBase, sequence, bin, set, line, Flow.once, Op.effect, BinaryOp.eval,
+ fieldResult, rectangleAddress, encodeBit, Function.update_idem, regCast h.group,
+ regCast h.indexWidth, regCast h.adviceWidth, regCast h.cutCapacity, regCast h.site,
+ regCast h.baseAddr, regCast h.rowWidth, regCast h.prefixWidth, regCast h.siteBits,
+ regCast h.two, regCast h.three, add_assoc, add_comm, add_left_comm]; rfl)
+
+/-- Bounded, probe-free execution of all four supplied header fields. -/
+theorem exec_headerFields (pub : Pub → Word w) (state : Word w) (rs : Regs w 48) (m : Memory w)
+ {L : Lengths} {base n r P g v j : ℕ} (h : HeaderRegisters rs L base n r P g v j) (hj : j < 4) :
+ ∃ t ≤ headerFields.length, Flow.Exec pub state headerFields rs m (List.replicate t .tick)
+ (fieldResult rs (dispatchHeader L base n r P g v j)) m := by
+ obtain ⟨t, ht⟩ := once_headerFields pub state false rs m h hj
+ have hs := Flow.once_sound pub state false headerFields rs m ht
+ exact ⟨t, by simpa only [List.length_replicate] using hs.2, hs.1⟩
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeLoad.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeLoad.lean
new file mode 100644
index 0000000000..ab4fc685f7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeLoad.lean
@@ -0,0 +1,151 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodes
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import OAI.Computability.VPVNP.PrimedInputRAMLayoutExecution
+import OAI.Computability.VPVNP.PrimedInputRAMDispatch
+
+/-!
+# Loading the parameters and decoding the persistent rectangle cursor
+
+The three cut-length words are fetched from external memory on every data
+call. Group numbers are only row selectors here: the bits of the actual
+large group index are fetched at the designated header addresses.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+variable {w : ℕ}
+
+private abbrev lit (w k : ℕ) : Word w := Fin.ofNat (2^w) k
+
+/-- Trace of parameter loading, with eighteen private ticks followed by reads of the left,
+middle and right cut lengths at addresses 0, 1 and 2. -/
+def parameterEvents (w : ℕ) (mem : Memory w) : List (Event w) :=
+ List.replicate 18 .tick ++ [.read (lit w 0) (mem (lit w 0).val),
+ .read (lit w 1) (mem (lit w 1).val), .read (lit w 2) (mem (lit w 2).val)]
+
+/-- Register state after the parameter loads. -/
+structure Loaded (pub : Pub → Word w) (state : Word w) (mem : Memory w) (rs : Regs w 48) : Prop where
+ zero : rs 0 = lit w 0
+ one : rs 1 = lit w 1
+ two : rs 2 = lit w 2
+ three : rs 3 = lit w 3
+ cursor : rs 4 = state
+ cells : rs 5 = pub 0
+ rowWidth : rs 6 = pub 1
+ sites : rs 7 = pub 2
+ siteBits : rs 8 = pub 3
+ wordWidth : rs 9 = pub 4
+ bucket : rs 10 = pub 5
+ base : rs 11 = pub 6
+ prefixWidth : rs 12 = pub 7
+ incident : rs 13 = pub 8
+ indexWidth : rs 14 = pub 9
+ adviceWidth : rs 15 = pub 10
+ cutCapacity : rs 16 = pub 11
+ prefixWord : rs 17 = pub 12
+ left : rs 18 = mem (lit w 0).val
+ middle : rs 19 = mem (lit w 1).val
+ right : rs 20 = mem (lit w 2).val
+
+private def loadedRegs (pub : Pub → Word w) (state : Word w) (mem : Memory w) (rs : Regs w 48) : Regs w 48 :=
+ let cells : List (Reg × Word w) :=
+ [(0,lit w 0),(1,lit w 1),(2,lit w 2),(3,lit w 3),(4,state),
+ (5,pub 0),(6,pub 1),(7,pub 2),(8,pub 3),(9,pub 4),(10,pub 5),(11,pub 6),
+ (12,pub 7),(13,pub 8),(14,pub 9),(15,pub 10),(16,pub 11),(17,pub 12),
+ (18,mem (lit w 0).val),(19,mem (lit w 1).val),(20,mem (lit w 2).val)]
+ cells.foldl (fun regs j ↦ Function.update regs j.1 j.2) rs
+
+private theorem extendOps {pub : Pub → Word w} {state : Word w} {rs ra : Regs w 48} {m ma : Memory w}
+ {a : Code} {es : List (Event w)} (h : Flow.Exec pub state a rs m es ra ma)
+ (ops : List (Op 48 16)) {fs rb mb}
+ (ht : trace pub state ops ra ma = some (fs,rb,mb)) :
+ Flow.Exec pub state (ops.foldl (fun c op ↦ .seq c (.line op)) a) rs m (es++fs) rb mb := by
+ induction ops generalizing es a ra ma fs with
+ | nil =>
+ have he : ([],ra,ma) = (fs,rb,mb) := Option.some.inj ht
+ cases he
+ simpa using h
+ | cons o ops ih =>
+ simp only [trace, bind, Option.bind_eq_some_iff] at ht
+ obtain ⟨⟨e,rc,mc⟩,ho,⟨ts,rd,md⟩,hr,hf⟩ := ht
+ cases hf
+ simpa [List.append_assoc] using ih (h.seq (.line ho)) hr
+
+theorem loadParameters_exec (pub : Pub → Word w) (state : Word w) (mem : Memory w) (rs : Regs w 48) :
+ ∃ out, Flow.Exec pub state loadParameters rs mem (parameterEvents w mem) out mem ∧
+ Loaded pub state mem out := by
+ let ra := Function.update rs (0 : Reg) (lit w 0)
+ let out := loadedRegs pub state mem rs
+ have head : Flow.Exec pub state (set 0 0) rs mem [.tick] ra mem := .line rfl
+ have ht : trace pub state parameterTail ra mem =
+ some (List.replicate 17 .tick ++
+ [.read (lit w 0) (mem (lit w 0).val), .read (lit w 1) (mem (lit w 1).val),
+ .read (lit w 2) (mem (lit w 2).val)], out, mem) := rfl
+ exact ⟨out, extendOps head parameterTail ht, by constructor <;> rfl⟩
+
+/-- Register state after decoding the persistent cursor into the rectangle index, row, group,
+site, bit offset, successor cursor and destination address. -/
+def cursorRegs (rs : Regs w 48) : Regs w 48 :=
+ let i := BinaryOp.mod.eval (rs 4) (rs 5)
+ let row := BinaryOp.div.eval i (rs 6)
+ let g := BinaryOp.div.eval row (rs 7)
+ let v := BinaryOp.mod.eval row (rs 7)
+ let j := BinaryOp.mod.eval i (rs 6)
+ let next := BinaryOp.add.eval (rs 4) (rs 1)
+ let dest := BinaryOp.add.eval (rs 11) (rs 4)
+ Function.update (Function.update (Function.update (Function.update (Function.update
+ (Function.update (Function.update rs (21 : Fin 48) i) 31 row) 22 g) 23 v) 24 j) 29 next) 30 dest
+
+theorem unpackCursor_exec (pub : Pub → Word w) (state : Word w) (mem : Memory w) (rs : Regs w 48) :
+ Flow.Exec pub state unpackCursor rs mem (List.replicate 7 .tick) (cursorRegs rs) mem :=
+ (Flow.once_sound pub state false unpackCursor rs mem rfl).1
+
+/-- Rectangle coordinates in the bounded output registers. -/
+structure Cursor (n r base : ℕ) (state : Word w) (rs : Regs w 48) : Prop where
+ index : (rs 21).val = state.val % positions n r
+ group : (rs 22).val = state.val % positions n r / n / (2^r)
+ site : (rs 23).val = state.val % positions n r / n % (2^r)
+ bit : (rs 24).val = state.val % positions n r % n
+ next : (rs 29).val = state.val + 1
+ dest : (rs 30).val = base + state.val
+
+private theorem div_val (x y : Word w) : (BinaryOp.div.eval x y).val = x.val / y.val :=
+ Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.div_le_self ..) x.isLt)
+
+private theorem mod_val (x y : Word w) : (BinaryOp.mod.eval x y).val = x.val % y.val :=
+ Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.mod_le ..) x.isLt)
+
+theorem cursorRegs_spec {n r base : ℕ} (rs : Regs w 48) (state : Word w)
+ (h₁ : (rs 1).val = 1) (hs : rs 4 = state) (hN : (rs 5).val = positions n r)
+ (hn : (rs 6).val = n) (hR : (rs 7).val = 2^r) (hb : (rs 11).val = base)
+ (hnext : state.val + 1 < 2^w) (hdest : base + state.val < 2^w) :
+ Cursor n r base state (cursorRegs rs) := by
+ have hne : (rs 4).val + (rs 1).val < 2^w := by simpa [hs, h₁] using hnext
+ have hde : (rs 11).val + (rs 4).val < 2^w := by simpa [hb, hs] using hdest
+ have addVal (a b : Word w) (h : a.val+b.val < 2^w) :
+ (BinaryOp.add.eval a b).val = a.val + b.val := Fin.val_add_eq_of_add_lt h
+ constructor
+ · change (BinaryOp.mod.eval (rs 4) (rs 5)).val = _
+ rw [mod_val, hs, hN]
+ · change (BinaryOp.div.eval (BinaryOp.div.eval (BinaryOp.mod.eval (rs 4) (rs 5)) (rs 6)) (rs 7)).val = _
+ rw [div_val, div_val, mod_val, hs, hN, hn, hR]
+ · change (BinaryOp.mod.eval (BinaryOp.div.eval (BinaryOp.mod.eval (rs 4) (rs 5)) (rs 6)) (rs 7)).val = _
+ rw [mod_val, div_val, mod_val, hs, hN, hn, hR]
+ · change (BinaryOp.mod.eval (BinaryOp.mod.eval (rs 4) (rs 5)) (rs 6)).val = _
+ rw [mod_val, mod_val, hs, hN, hn]
+ · change (BinaryOp.add.eval (rs 4) (rs 1)).val = _
+ rw [addVal _ _ hne, hs, h₁]
+ · change (BinaryOp.add.eval (rs 11) (rs 4)).val = _
+ rw [addVal _ _ hde, hb, hs]
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeParameters.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeParameters.lean
new file mode 100644
index 0000000000..761956932f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodeParameters.lean
@@ -0,0 +1,209 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeLoad
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeDispatch
+import OAI.Computability.VPVNP.LiveHeaderBits
+import OAI.Computability.VPVNP.CursorBounds
+
+/-!
+# Public words and the register state on entry to the input dispatcher
+
+The fixed program prefix occupies the low bits of one public word. Each call
+loads the dimensions of the two rectangles from the public words, reads the
+three pair-specific cut lengths from RAM, and decodes its persistent cursor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM RAMLayout
+
+variable {L : Lengths} {n r H w : ℕ}
+
+/-- Numeric value of the literal program prefix, least significant bit first. -/
+def packedPrefix (p : UniversalMachine.Program) : Word (UniversalMachine.programPrefix p).length :=
+ (RAMSerialization.wordBits _).symm (UniversalMachine.programPrefix p).get
+
+/-- Dimensions, fixed field widths, and the packed prefix in instruction-table order. -/
+def pubNat (Q : Layout L n r H w) (i : Pub) : ℕ :=
+ match i.val with
+ | 0 => positions n r
+ | 1 => n
+ | 2 => 2^r
+ | 3 => r
+ | 4 => w
+ | 5 => H
+ | 6 => Q.scratchBase
+ | 7 => (UniversalMachine.programPrefix Q.program).length
+ | 8 => width r H w
+ | 9 => L.index
+ | 10 => L.advice
+ | 11 => L.cutCapacity
+ | 12 => (packedPrefix Q.program).val
+ | 13 => blockBits H w
+ | 14 => 8*w
+ | _ => 16*w
+
+/-- Encode a public layout parameter from the opcode table's ordered list as a width-`w` word. -/
+def pubWord (Q : Layout L n r H w) (i : Pub) : Word w := Fin.ofNat _ (pubNat Q i)
+
+/-- Word-fit conditions beyond the tape and address bounds already in the layout. -/
+structure ParameterFit (Q : Layout L n r H w) : Prop where
+ prefixFits : (UniversalMachine.programPrefix Q.program).length ≤ w
+ blockFits : blockBits H w < 2^w
+
+private theorem layoutRow_lt (Q : Layout L n r H w) : n < 2^w := by
+ have hrow : n ≤ positions n r := Nat.le_mul_of_pos_left _ (by positivity)
+ have := Q.cursorFits
+ omega
+
+/-- As soon as the site address is nonempty, the row contains a full sort block. -/
+theorem parameterFit_of_prefix (Q : Layout L n r H w) (hr : 0 < r)
+ (hP : (UniversalMachine.programPrefix Q.program).length ≤ w) : ParameterFit Q := by
+ have hc : 1 ≤ layerCount r := PortCode.layerCount_mono (show 1 ≤ r from hr)
+ have hs : 2 * blockBits H w ≤ layerCount r * (2 * blockBits H w) :=
+ Nat.le_mul_of_pos_left _ hc
+ have ht := Q.fits
+ unfold ProcessorInput.Fits width at ht
+ have hn := layoutRow_lt Q
+ exact ⟨hP, by omega⟩
+
+/-- At every sufficiently large length the fixed prefix and all public fields
+fit the paper's word width, uniformly over all well-formed layouts. -/
+theorem eventually_parameterFit (p : UniversalMachine.Program) {B : ℕ} (hB : 1 ≤ B) :
+ ∀ᶠ n : ℕ in Filter.atTop, ∀ L H (Q : Layout L n (addressWidth B n) H (CursorBounds.wordBits B n)),
+ Q.program = p → ParameterFit Q := by
+ let P := (UniversalMachine.programPrefix p).length
+ filter_upwards [Filter.eventually_ge_atTop (2^(P+1))] with n hn
+ have hn₀ : 0 < n := (Nat.two_pow_pos _).trans_le hn
+ have hlarge := ((Nat.le_log2 hn₀.ne').mpr hn).trans (log2_le_addressWidth hB n)
+ intro L H Q hQ
+ apply parameterFit_of_prefix Q (by omega)
+ rw [hQ]
+ change P ≤ (addressWidth B n + 10)^4
+ exact (show P ≤ addressWidth B n + 10 by omega).trans (Nat.le_self_pow (by decide) _)
+
+theorem pubNat_lt (Q : Layout L n r H w) (F : ParameterFit Q) (i : Pub) : pubNat Q i < 2^w := by
+ have hc := Q.cursorFits
+ have ha := Q.addressesFit
+ have hh := Q.headersFit
+ unfold Header.count at hh
+ have ht := Q.fits
+ unfold ProcessorInput.Fits at ht
+ have hn := layoutRow_lt Q
+ have hpos : 0 < n := by omega
+ have hs : 2 * 2^r ≤ positions n r := Nat.le_mul_of_pos_right _ hpos
+ have h8 : 16*w ≤ width r H w := by unfold width; omega
+ have hw : 0 < w := by
+ by_contra! hz
+ have : w = 0 := by omega
+ simp [this] at hn
+ omega
+ have hH : H ≤ blockBits H w := by
+ have h := Nat.le_mul_of_pos_right (4*H*5) hw
+ unfold blockBits
+ omega
+ have hb := F.blockFits
+ have hp := (packedPrefix Q.program).isLt.trans_le (Nat.pow_le_pow_right (by decide) F.prefixFits)
+ have := Nat.two_pow_pos r
+ fin_cases i
+ · change positions n r < 2^w; omega
+ · exact hn
+ · change 2^r < 2^w; omega
+ · change r < 2^w; omega
+ · change w < 2^w; omega
+ · change H < 2^w; omega
+ · change Q.scratchBase < 2^w; omega
+ · change (UniversalMachine.programPrefix Q.program).length < 2^w; omega
+ · change width r H w < 2^w; omega
+ · change L.index < 2^w; omega
+ · change L.advice < 2^w; omega
+ · change L.cutCapacity < 2^w; omega
+ · exact hp
+ · exact hb
+ · change 8*w < 2^w; omega
+ · change 16*w < 2^w; omega
+
+@[simp] theorem pubWord_val (Q : Layout L n r H w) (F : ParameterFit Q) (i : Pub) :
+ (pubWord Q i).val = pubNat Q i := Nat.mod_eq_of_lt (pubNat_lt Q F i)
+
+theorem pubWord_cells (Q : Layout L n r H w) (F : ParameterFit Q) :
+ (pubWord Q 0).val = positions n r := pubWord_val Q F 0
+
+theorem pubWord_prefixBit (Q : Layout L n r H w) (F : ParameterFit Q) (t : ℕ)
+ (ht : t < (UniversalMachine.programPrefix Q.program).length) :
+ (pubWord Q 12).val.testBit t = Q.prefixAt t := by
+ rw [pubWord_val Q F]
+ let i : Fin (UniversalMachine.programPrefix Q.program).length := ⟨t, ht⟩
+ change (packedPrefix Q.program).val.testBit i.val = _
+ rw [LiveHeader.testBit_wordBits, packedPrefix, Equiv.apply_symm_apply]
+ simp [Layout.prefixAt, ht, i]
+
+/-- Memory invariant for the three cut-length words, independent of the rest of memory. -/
+def CutMemory (L : Lengths) (m : Memory w) : Prop :=
+ ∀ j : Fin 3, (m j.val).val = cutLength L j
+
+theorem cutMemory_header (Q : Layout L n r H w) (hdr : Header L → Bool) (hist : List (Word w)) :
+ CutMemory L (headerMemory L hdr hist) := by
+ intro j
+ rw [headerMemory_length]
+ exact Nat.mod_eq_of_lt (Q.cutLength_lt j)
+
+theorem CutMemory.congr {m m' : Memory w} (hc : CutMemory L m)
+ (h : ∀ j : Fin 3, m' j.val = m j.val) : CutMemory L m' := fun j => (congrArg Fin.val (h j)).trans (hc j)
+
+/-- Exact state reached by the parameter-load and cursor-decoding instructions. -/
+structure Prepared (Q : Layout L n r H w) (state : Word w) (rs : Regs w 48) : Prop where
+ dispatch : DispatchInput L n r H w Q.scratchBase (UniversalMachine.programPrefix Q.program).length
+ (state.val % positions n r / n / (2^r)) (state.val % positions n r / n % (2^r))
+ (state.val % positions n r % n) Q.prefixAt (pubWord Q) rs
+ cursor : Cursor n r Q.scratchBase state rs
+ stateReg : rs 4 = state
+ cells : (rs 5).val = positions n r
+
+private theorem prepared_of_loaded (Q : Layout L n r H w) (F : ParameterFit Q)
+ (state : Word w) (m : Memory w) (rs : Regs w 48) (hstate : state.val < positions n r + positions n r)
+ (hc : CutMemory L m) (hl : Loaded (pubWord Q) state m rs) : Prepared Q state (cursorRegs rs) := by
+ have ht := Q.fits
+ unfold ProcessorInput.Fits at ht
+ have hn := layoutRow_lt Q
+ have hsmall : 3 < 2^w := by omega
+ have small (k : ℕ) (hk : k ≤ 3) : (Fin.ofNat (2^w) k).val = k := Nat.mod_eq_of_lt (by omega)
+ have e0 : (rs 0).val = 0 := (congrArg Fin.val hl.zero).trans (small _ (by decide))
+ have e1 : (rs 1).val = 1 := (congrArg Fin.val hl.one).trans (small _ (by decide))
+ have e2 : (rs 2).val = 2 := (congrArg Fin.val hl.two).trans (small _ (by decide))
+ have e3 : (rs 3).val = 3 := (congrArg Fin.val hl.three).trans (small _ (by decide))
+ have pv {i : Reg} {j : Pub} (h : rs i = pubWord Q j) : (rs i).val = pubNat Q j :=
+ (congrArg Fin.val h).trans (pubWord_val Q F j)
+ have readLength {i : Reg} (j : Fin 3) (h : rs i = m (Fin.ofNat (2^w) j.val).val) :
+ (rs i).val = cutLength L j := by rw [h, small j.val (by have := j.isLt; omega), hc j]
+ have hcur := cursorRegs_spec (n := n) (r := r) (base := Q.scratchBase) rs state e1 hl.cursor
+ (pv hl.cells) (pv hl.rowWidth) (pv hl.sites) (pv hl.base)
+ (by have := Q.cursorFits; omega) (by have := Q.addressesFit; omega)
+ refine ⟨?_, hcur, hl.cursor, pv hl.cells⟩
+ refine ⟨?_, pv hl.sites, pv hl.incident, hcur.bit, Nat.mod_lt _ (Nat.two_pow_pos _), ?_,
+ by omega, pubWord_val Q F 13, pubWord_val Q F 14, pubWord_val Q F 15⟩
+ · exact ⟨e0, e1, e2, e3, pv hl.rowWidth, pv hl.siteBits, pv hl.base, pv hl.prefixWidth,
+ pv hl.indexWidth, pv hl.adviceWidth, pv hl.cutCapacity, readLength 0 hl.left,
+ readLength 1 hl.middle, readLength 2 hl.right, hcur.group, hcur.site, rfl⟩
+ · intro t ht
+ change (rs 17).val.testBit t = _
+ rw [hl.prefixWord]
+ exact pubWord_prefixBit Q F t ht
+
+/-- Every data call reaches the dispatch contract by 18 private loads, three
+header reads and seven cursor arithmetic steps, leaving external memory intact. -/
+theorem load_unpack_exec (Q : Layout L n r H w) (F : ParameterFit Q) (state : Word w)
+ (m : Memory w) (rs : Regs w 48) (hstate : state.val < positions n r + positions n r)
+ (hc : CutMemory L m) :
+ ∃ out, Flow.Exec (pubWord Q) state (.seq loadParameters unpackCursor) rs m
+ (parameterEvents w m ++ List.replicate 7 .tick) out m ∧ Prepared Q state out := by
+ obtain ⟨rs', he, hl⟩ := loadParameters_exec (pubWord Q) state m rs
+ exact ⟨_, he.seq (unpackCursor_exec _ _ _ _), prepared_of_loaded Q F state m rs' hstate hc hl⟩
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodePaths.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodePaths.lean
new file mode 100644
index 0000000000..81a25c7e8a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodePaths.lean
@@ -0,0 +1,304 @@
+import OAI.Computability.VPVNP.PrimedInputRAMRunEquiv
+
+/-!
+# Native path correspondence for the physical primed input passes
+
+Each data call reads three supplied cut lengths before performing its scheduled item.
+The physical machine may take extra private steps. Across the entire input stage its
+branch choices, returned cursors and final memory agree with the schedule.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM
+
+variable {w M : ℕ} {C : Type*}
+
+/-- A successful call consumes its entire choice stream. Appending an unused
+nonempty suffix to that same stream therefore rejects. -/
+theorem execute_extra_choices {P : Program w C} {fuel : ℕ} {c : C} {m : Memory w}
+ {bs : List Bool} {r : Report w} (hr : execute P fuel c m bs = some r)
+ (extra : List Bool) (hne : extra ≠ []) : execute P fuel c m (bs ++ extra) = none := by
+ induction fuel generalizing c m bs r with
+ | zero => simp [execute] at hr
+ | succ fuel ih =>
+ cases hc : P.step c with
+ | reject => simp [execute, hc] at hr
+ | finish v =>
+ cases bs with
+ | nil => simp [execute, hc, hne]
+ | cons => simp [execute, hc] at hr
+ | branch next =>
+ cases bs with
+ | nil => simp [execute, hc] at hr
+ | cons b tail =>
+ obtain ⟨_, he, _⟩ := Option.map_eq_some_iff.mp (by simpa only [execute, hc] using hr)
+ simp only [List.cons_append, execute, hc, ih he, Option.map_none]
+ | localStep next | read _ next | write _ _ next =>
+ obtain ⟨_, he, _⟩ := Option.map_eq_some_iff.mp (by simpa only [execute, hc] using hr)
+ simp only [execute, hc, ih he, Option.map_none]
+
+theorem only_item_choices {P : Program w C} {fuel : ℕ} {c : C} {m : Memory w}
+ (op : Item w) (report : Bool → Report w)
+ (ok : ∀ b, execute P fuel c m (op.bits b) = some (report b))
+ {bs : List Bool} {r : Report w} (hr : execute P fuel c m bs = some r) :
+ ∃ b, bs = op.bits b := by
+ cases h : op.owns with
+ | false =>
+ have he : execute P fuel c m [] = some (report false) := by simpa [Item.bits,h] using ok false
+ by_cases hn : bs = []
+ · exact ⟨false, by simp [Item.bits,h,hn]⟩
+ · have := execute_extra_choices he bs hn
+ simp [hr] at this
+ | true =>
+ have he (b : Bool) : execute P fuel c m [b] = some (report b) := by simpa [Item.bits,h] using ok b
+ cases bs with
+ | nil =>
+ have := execute_extra_choices hr [false] (by simp)
+ simp [he] at this
+ | cons b bs =>
+ by_cases hn : bs = []
+ · exact ⟨b, by simp [Item.bits,h,hn]⟩
+ · have ha := execute_extra_choices (he b) bs hn
+ simp [hr] at ha
+
+private theorem invalid_choices {P : Program w C} {fuel : ℕ} {c : C} {m : Memory w}
+ (op : Item w) (report : Bool → Report w)
+ (ok : ∀ b, execute P fuel c m (op.bits b) = some (report b))
+ {bs : List Bool} (bad : ¬ ∃ b, bs = op.bits b) : execute P fuel c m bs = none := by
+ cases hx : execute P fuel c m bs with
+ | none => rfl
+ | some r => exact False.elim (bad (only_item_choices _ report ok hx))
+
+/-- Local contract of the physical input-stage machine. Only prescribed input
+streams need to be checked; exact use of bits rules out any other path. -/
+structure PhysicalSchedule (P : Program w C) (fuel : ℕ) (ops : Fin M → Item w)
+ (bitWord : Bool → Word w) (fit : M < 2^w) (Pre : Memory w → Prop) where
+ /-- Native report for one scheduled data call at the given incoming memory and choice bit. -/
+ report : Fin M → Memory w → Bool → Report w
+ /-- Native report for the halt call at the cursor just beyond the final data item. -/
+ last : Memory w → Report w
+ data : ∀ i m b, Pre m → execute P fuel (P.start (cursor fit i.val i.isLt.le)) m ((ops i).bits b) =
+ some (report i m b)
+ result : ∀ i m b, Pre m → (report i m b).result = some (successor fit i)
+ memory : ∀ i m b, Pre m → after m (report i m b).events = (ops i).memory bitWord m b
+ probes : ∀ i m b, Pre m → (report i m b).probes = (ops i).probeCount + 3
+ closed : ∀ i m b, Pre m → Pre ((ops i).memory bitWord m b)
+ halt : ∀ m, Pre m → execute P fuel (P.start (cursor fit M le_rfl)) m [] = some (last m)
+ halt_result : ∀ m, Pre m → (last m).result = none
+ halt_memory : ∀ m, Pre m → after m (last m).events = m
+ halt_probes : ∀ m, Pre m → (last m).probes = 0
+
+/-- Agreement of two native histories, including their extra cut-length probes.
+A returning data call incurs three extra probes; the terminal call incurs none. -/
+inductive MatchedReports : Memory w → List (Report w) → List (Report w) → Prop
+ | nil (m) : MatchedReports m [] []
+ | cons {m a b xs ys}
+ (result : a.result = b.result) (memory : after m a.events = after m b.events)
+ (probes : a.probes = b.probes + (if b.result.isSome then 3 else 0))
+ (tail : MatchedReports (after m b.events) xs ys) : MatchedReports m (a :: xs) (b :: ys)
+
+namespace MatchedReports
+
+theorem endState_eq {m : Memory w} {xs ys : List (Report w)} (h : MatchedReports m xs ys)
+ (s : Option (Word w)) : endState s xs = endState s ys := by
+ induction h generalizing s with
+ | nil => rfl
+ | cons he _ _ _ ih => simp only [endState, he, ih]
+
+theorem after_eq {m : Memory w} {xs ys : List (Report w)} (h : MatchedReports m xs ys) :
+ after m (eventLog xs) = after m (eventLog ys) := by
+ induction h with
+ | nil => rfl
+ | cons _ hm _ _ ih =>
+ simp only [eventLog, List.flatMap_cons, after, List.foldl_append] at hm ih ⊢
+ rw [hm, ih]
+
+theorem cost_eq {m : Memory w} {xs ys : List (Report w)} (h : MatchedReports m xs ys) :
+ RAMBuckets.cost Report.probes xs = RAMBuckets.cost Report.probes ys +
+ 3 * (ys.filter fun r ↦ r.result.isSome).length := by
+ induction h with
+ | nil => rfl
+ | @cons m a b xs ys _ _ hp _ ih =>
+ cases he : b.result <;> simp [he, RAMBuckets.cost] at hp ⊢ <;> omega
+
+theorem per_call {m : Memory w} {xs ys : List (Report w)} (h : MatchedReports m xs ys)
+ (hy : ∀ b ∈ ys, 1 + b.probes ≤ 3) : ∀ a ∈ xs, 1 + a.probes ≤ 6 := by
+ induction h with
+ | nil => simp
+ | @cons m a b xs ys _ _ hp _ ih =>
+ intro z hz
+ rcases List.mem_cons.mp hz with rfl | hz
+ · have h₀ := hy b (List.mem_cons_self ..)
+ split at hp <;> omega
+ · exact ih (fun t ht ↦ hy t (List.mem_cons_of_mem _ ht)) z hz
+
+private theorem prepend {m : Memory w} {a b : Report w} {xs ys : Option (List (Report w))}
+ (hr : a.result = b.result) (hm : after m a.events = after m b.events)
+ (hp : a.probes = b.probes + (if b.result.isSome then 3 else 0))
+ (h : Option.Rel (MatchedReports (after m b.events)) xs ys) :
+ Option.Rel (MatchedReports m) (xs.map (a :: ·)) (ys.map (b :: ·)) := by
+ cases h with
+ | none => exact .none
+ | some ht => exact .some (.cons hr hm hp ht)
+
+end MatchedReports
+
+namespace PhysicalSchedule
+
+variable {P : Program w C} {fuel : ℕ} {ops : Fin M → Item w} {bitWord : Bool → Word w}
+ {fit : M < 2^w} {Pre : Memory w → Prop}
+variable (R : PhysicalSchedule P fuel ops bitWord fit Pre)
+
+include R
+
+/-- Run the physical and scheduled interpreters on the same sequence of streams.
+They reject together, or return matching histories, from any valid cursor. -/
+theorem run_matched (k : ℕ) (hk : k ≤ M) (m : Memory w) (hm : Pre m) (bs : List (List Bool)) :
+ Option.Rel (MatchedReports m)
+ (runSegment P fuel (some (cursor fit k hk)) m bs)
+ (runSegment (scheduledProgram ops bitWord fit) 3 (some (cursor fit k hk)) m bs) := by
+ induction bs generalizing k m with
+ | nil => exact .some (.nil m)
+ | cons bits more ih =>
+ by_cases hi : k < M
+ · let i : Fin M := ⟨k,hi⟩
+ have hd (b : Bool) : execute P fuel (P.start (cursor fit k hk)) m ((ops i).bits b) =
+ some (R.report i m b) := R.data i m b hm
+ have hg (b : Bool) :
+ execute (scheduledProgram ops bitWord fit) 3
+ ((scheduledProgram ops bitWord fit).start (cursor fit k hk)) m ((ops i).bits b) =
+ some ((ops i).report bitWord (successor fit i) m b) := by
+ rw [show cursor fit k hk = cursor fit i.val i.isLt.le by rfl, start_item, execute_item]
+ by_cases good : ∃ b, bits = (ops i).bits b
+ · obtain ⟨b,rfl⟩ := good
+ have step := R.memory i m b hm
+ have next := R.result i m b hm
+ have count := R.probes i m b hm
+ simp only [runSegment, hd, hg, next, step, Item.report_result, Item.after_report]
+ apply MatchedReports.prepend (next.trans (Item.report_result ..).symm)
+ (step.trans (Item.after_report ..).symm) (by simp [count])
+ rw [Item.after_report, show successor fit i = cursor fit (k+1) hi by rfl]
+ exact ih (k+1) hi _ (R.closed i m b hm)
+ · simp only [runSegment, invalid_choices _ _ hd good, invalid_choices _ _ hg good,
+ Option.rel_none_none]
+ · have he : k = M := by omega
+ subst k
+ have hp := R.halt m hm
+ have gen : execute (scheduledProgram ops bitWord fit) 3
+ ((scheduledProgram ops bitWord fit).start (cursor fit M le_rfl)) m [] = some (haltReport w) := by
+ rw [start_halt]
+ rfl
+ cases bits with
+ | nil =>
+ cases more with
+ | nil =>
+ simp only [runSegment, hp, gen, Option.map_some, Option.rel_some_some]
+ exact .cons (R.halt_result m hm) (R.halt_memory m hm) (R.halt_probes m hm) (.nil _)
+ | cons =>
+ simp only [runSegment, hp, gen, R.halt_result m hm, haltReport, Option.map_none,
+ Option.rel_none_none]
+ | cons b tail =>
+ have hp' := execute_extra_choices hp (b::tail) (by simp)
+ have hg' := execute_extra_choices gen (b::tail) (by simp)
+ simp only [List.nil_append] at hp' hg'
+ simp only [runSegment, hp', hg', Option.rel_none_none]
+
+/-- Physical acceptance and schedule acceptance coincide before imposing budgets. -/
+theorem accepts_iff (m : Memory w) (hm : Pre m) (bits : List (List Bool)) :
+ (∃ rs, runSegment P fuel (some 0) m bits = some rs ∧ endState (some 0) rs = none) ↔
+ ∃ rs, runSegment (scheduledProgram ops bitWord fit) 3 (some 0) m bits = some rs ∧
+ endState (some 0) rs = none := by
+ have hs := R.run_matched 0 (Nat.zero_le _) m hm bits
+ change Option.Rel _ (runSegment P fuel (some 0) m bits)
+ (runSegment (scheduledProgram ops bitWord fit) 3 (some 0) m bits) at hs
+ cases hP : runSegment P fuel (some 0) m bits <;>
+ cases hQ : runSegment (scheduledProgram ops bitWord fit) 3 (some 0) m bits <;>
+ simp only [hP, hQ, Option.rel_some_some, Option.not_rel_some_none, Option.not_rel_none_some,
+ Option.rel_none_none] at hs <;> try contradiction
+ · simp
+ · simp [hs.endState_eq (some 0)]
+
+omit R in
+private theorem returning_count (g : Fin M → Bool) (cells : List (Fin M)) (m : Memory w) :
+ ((scheduledReports ops bitWord fit g cells m).filter fun r ↦ r.result.isSome).length =
+ cells.length := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i xs ih => simp [scheduledReports, ih]
+
+/-- A complete physical run for every bit assignment, with its exact final memory
+and exact calls-plus-probes cost, including the terminal call. -/
+theorem generated (m : Memory w) (hm : Pre m) (g : Fin M → Bool) :
+ ∃ ps, runSegment P fuel (some 0) m
+ ((List.finRange M).map (fun i ↦ (ops i).bits (g i)) ++ [[]]) = some ps ∧
+ endState (some 0) ps = none ∧
+ after m (eventLog ps) = scheduledMemory ops bitWord g (List.finRange M) m ∧
+ RAMBuckets.cost Report.probes ps = scheduledCost ops + 3*M ∧
+ ∀ p ∈ ps, 1 + p.probes ≤ 6 := by
+ let bits := (List.finRange M).map (fun i ↦ (ops i).bits (g i)) ++ [[]]
+ have hs := R.run_matched 0 (Nat.zero_le _) m hm bits
+ change Option.Rel _ (runSegment P fuel (some 0) m bits)
+ (runSegment (scheduledProgram ops bitWord fit) 3 (some 0) m bits) at hs
+ rw [run_generated ops bitWord fit g m] at hs
+ cases hP : runSegment P fuel (some 0) m bits with
+ | none => simp [hP] at hs
+ | some ps =>
+ rw [hP, Option.rel_some_some] at hs
+ refine ⟨ps, rfl, ?_, ?_, ?_, ?_⟩
+ · rw [hs.endState_eq, endState_append]
+ rfl
+ · rw [hs.after_eq]
+ simp only [eventLog, List.flatMap_append, List.flatMap_cons, haltReport, List.flatMap_nil,
+ List.append_nil]
+ exact after_scheduledReports ..
+ · rw [hs.cost_eq, generated_cost, List.filter_append]
+ simp [haltReport, returning_count]
+ · apply hs.per_call
+ exact (scheduledReports_withinCaps ops bitWord fit g m (S := scheduledCost ops)
+ (H := 3) (by decide) (by omega)).2
+
+/-- For any accepting run, the interpreter's own reports carry the exact total
+cost and respect the six-unit call bound. -/
+theorem accepted_cost (m : Memory w) (hm : Pre m) (bits : List (List Bool)) {ps : List (Report w)}
+ (hP : runSegment P fuel (some 0) m bits = some ps) (hend : endState (some 0) ps = none) :
+ RAMBuckets.cost Report.probes ps = scheduledCost ops + 3*M ∧ ∀ p ∈ ps, 1 + p.probes ≤ 6 := by
+ obtain ⟨g, rfl⟩ := (run_accepted_iff ops bitWord fit m bits).mp
+ ((R.accepts_iff m hm bits).mp ⟨ps,hP,hend⟩)
+ obtain ⟨ts, hr, _, _, hc, hcall⟩ := R.generated m hm g
+ obtain rfl := Option.some.inj (hP.symm.trans hr)
+ exact ⟨hc, hcall⟩
+
+/-- Identity on the supplied per-call branch streams. Both the total budget and
+the individual-call budget refer to the actual reports returned by each program. -/
+def pathEquiv (m : Memory w) (hm : Pre m) {S H : ℕ} (hH : 6 ≤ H)
+ (hTotal : scheduledCost ops + 3*M ≤ S*H) :
+ ActualPaths P fuel 0 m (withinCaps S H) ≃
+ ActualPaths (scheduledProgram ops bitWord fit) 3 0 m (withinCaps S H) := by
+ apply Equiv.subtypeEquivRight
+ intro bits
+ constructor
+ · rintro ⟨ps, hp, he, _⟩
+ obtain ⟨g, rfl⟩ := (run_accepted_iff ops bitWord fit m bits).mp
+ ((R.accepts_iff m hm bits).mp ⟨ps, hp, he⟩)
+ exact ⟨_, run_generated ops bitWord fit g m, by rw [endState_append]; rfl,
+ scheduledReports_withinCaps ops bitWord fit g m (by omega) (by omega)⟩
+ · rintro ⟨qs, hq, he, _⟩
+ obtain ⟨g, rfl⟩ := (run_accepted_iff ops bitWord fit m bits).mp ⟨qs, hq, he⟩
+ obtain ⟨ps, hp, hend, _, hcost, hcall⟩ := R.generated m hm g
+ exact ⟨ps, hp, hend, hcost.trans_le hTotal, fun p hmem ↦ (hcall p hmem).trans hH⟩
+
+@[simp] theorem pathEquiv_val (m : Memory w) (hm : Pre m) {S H : ℕ} (hH : 6 ≤ H)
+ (hTotal : scheduledCost ops + 3*M ≤ S*H) (p : ActualPaths P fuel 0 m (withinCaps S H)) :
+ (R.pathEquiv m hm hH hTotal p).val = p.val := rfl
+
+end PhysicalSchedule
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodePortResult.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodePortResult.lean
new file mode 100644
index 0000000000..ec132111cf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodePortResult.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeFields
+import OAI.Computability.VPVNP.PrimedInputRAMPortCode
+import Mathlib.Tactic.Ring
+
+/-!
+# Converting a transcript sender into the physical scratch address
+
+The routing block returns either an absent port or a sender's site and offset.
+The final arithmetic block computes its row-major scratch address. It marks
+a bit as owned exactly when the current site and offset both match the sender.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ}
+
+/-- Registers carried through the routing block, below its workspace. -/
+structure PortResultRegisters (rs : Regs w 48) (base n r P g v k : ℕ) : Prop where
+ zero : (rs 0).val = 0
+ one : (rs 1).val = 1
+ three : (rs 3).val = 3
+ rowWidth : (rs 6).val = n
+ sites : (rs 7).val = 2^r
+ siteBits : (rs 8).val = r
+ baseAddr : (rs 11).val = base
+ prefixWidth : (rs 12).val = P
+ group : (rs 22).val = g
+ site : (rs 23).val = v
+ offset : (rs 25).val = k
+
+private theorem regCast {x : Word w} {v : ℕ} (h : x.val = v) : x = (v : Word w) := by
+ rw [← h, Fin.cast_val_eq_self]
+
+/-- No copy source yields a clamped zero. A live copy source uses at most 14
+private instructions, including the two comparisons for its owner flag. -/
+theorem once_portResult (pub : Pub → Word w) (state : Word w) (bit : Bool)
+ (rs : Regs w 48) (m : Memory w) {base n r H P g v k : ℕ}
+ (h : PortResultRegisters rs base n r P g v k)
+ (hs : PortCode.result rs = (rawSource r H w v k).1) :
+ ∃ t ≤ 14, Flow.once pub state bit portResult rs m = some (List.replicate t .tick,
+ fieldResult rs (dispatchPort base n r H w P g v k).1, m) := by
+ have present : rs 32 = rs 0 ↔ (rs 32).val = 0 := by rw [Fin.ext_iff, h.zero]
+ rw [dispatchPort, ← hs]
+ by_cases hz : (rs 32).val = 0
+ · refine ⟨4, by decide, ?_⟩
+ simp only [PortCode.result, portResult, Flow.once, present, hz, ↓reduceIte]
+ rfl
+ · have addr :
+ (rs 22 * rs 7 + rs 33) * rs 6 + rs 11 + rs 12 + rs 8 + rs 3 + rs 1 + rs 34 =
+ (rectangleAddress base n r g (rs 33).val (P+r+4+(rs 34).val) : Word w) := by
+ simp only [rectangleAddress, Nat.cast_add, Nat.cast_mul, Nat.cast_pow,
+ Fin.cast_val_eq_self, regCast h.group, regCast h.sites, regCast h.rowWidth,
+ regCast h.baseAddr, regCast h.prefixWidth, regCast h.siteBits, regCast h.three,
+ regCast h.one]
+ ring
+ have siteEq : (rs 33).val = v ↔ rs 23 = rs 33 := by rw [Fin.ext_iff, h.site, eq_comm]
+ have offsetEq : (rs 34).val = k ↔ rs 25 = rs 34 := by rw [Fin.ext_iff, h.offset, eq_comm]
+ by_cases hv : rs 23 = rs 33
+ · refine ⟨14, by decide, ?_⟩
+ by_cases hk : rs 25 = rs 34 <;>
+ simp [PortCode.result, portResult, hz, present, Flow.once, sequence, bin, set, line,
+ Op.effect, BinaryOp.eval, Function.update_idem, fieldResult, siteEq, offsetEq, hv, hk,
+ encodeBit, addr] <;> rfl
+ · refine ⟨13, by decide, ?_⟩
+ simp [PortCode.result, portResult, hz, present, Flow.once, sequence, bin, set, line,
+ Op.effect, BinaryOp.eval, Function.update_idem, fieldResult, siteEq, hv, encodeBit, addr]
+ rfl
+
+/-- Executing the physical block realizes the source and owner returned by
+the scalar port dispatcher and preserves all other registers and memory. -/
+theorem exec_portResult (pub : Pub → Word w) (state : Word w) (rs : Regs w 48) (m : Memory w)
+ {base n r H P g v k : ℕ} (h : PortResultRegisters rs base n r P g v k)
+ (hs : PortCode.result rs = (rawSource r H w v k).1) :
+ ∃ t ≤ 14, Flow.Exec pub state portResult rs m (List.replicate t .tick)
+ (fieldResult rs (dispatchPort base n r H w P g v k).1) m := by
+ obtain ⟨t, ht, he⟩ := once_portResult pub state false rs m h hs
+ exact ⟨t, ht, (Flow.once_sound pub state false _ rs m he).1⟩
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodes.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodes.lean
new file mode 100644
index 0000000000..49f86ff777
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMOpcodes.lean
@@ -0,0 +1,169 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowRun
+import OAI.Computability.VPVNP.PrimedInputRAMHeaders
+
+/-!
+# Fixed word code for the two input passes
+
+The persistent cursor ranges first over the chosen-bit rectangle, then over
+the assembled-input rectangle. A common dispatch computes the bit's source
+and its owner flag. The port arithmetic routine supplies the sender site and
+within-port offset. All other field handling, including the three supplied
+cut lengths, is given by the explicit word instructions below.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.Opcodes
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM
+
+/-- Structured word code for the primed input passes, with 48 private registers and 16 public
+words. -/
+abbrev Code := PrimedInputRAM.Flow 48 16
+/-- Index of a private register in the primed input dispatcher. -/
+abbrev Reg := Fin 48
+/-- Index of a public parameter word of the primed input dispatcher. -/
+abbrev Pub := Fin 16
+
+/-- Code for a single arithmetic or word-memory instruction. -/
+def line (op : Op 48 16) : Code := .line op
+
+/-- Load a two-bit literal into the destination register. -/
+def set (dst : Reg) (value : Word 2) := line (.constant dst value)
+/-- Load the indexed public word into a private register. -/
+def load (dst : Reg) (j : Pub) := line (.publicWord dst j)
+/-- Apply a binary word operation to two registers and store its result in the destination
+register. -/
+def bin (op : BinaryOp) (dst x y : Reg) := line (.binary op dst x y)
+/-- Copy a word by adding the source to register 0, which the parameter loader initializes to
+zero. -/
+def copy (dst src : Reg) := bin .add dst src 0
+/-- Read an external word at the address held in a register into the destination register. -/
+def read (dst addr : Reg) := line (.read dst addr)
+/-- Write the source register's word to the external address held in the address register. -/
+def write (addr src : Reg) := line (.write addr src)
+
+/-- Straight sequence of instructions or structured blocks. -/
+def sequence (first : Code) (rest : List Code) : Code := rest.foldl Flow.seq first
+
+/-- Constants, public geometry, persistent cursor, and the pair-specific
+cut lengths supplied by the three external header words. -/
+def parameterTail : List (Op 48 16) :=
+ [.constant 1 1, .constant 2 2, .constant 3 3, .stateWord 4, .publicWord 5 0,
+ .publicWord 6 1, .publicWord 7 2, .publicWord 8 3, .publicWord 9 4, .publicWord 10 5,
+ .publicWord 11 6, .publicWord 12 7, .publicWord 13 8, .publicWord 14 9, .publicWord 15 10,
+ .publicWord 16 11, .publicWord 17 12, .read 18 0, .read 19 1, .read 20 2]
+
+/-- Initialize the constants, load the persistent cursor and public layout words, then read the
+three cut lengths from external memory. -/
+def loadParameters : Code := parameterTail.foldl (fun a op ↦ .seq a (.line op)) (set 0 0)
+
+/-- Registers 21 through 24 hold the flat index, group, site and within-row
+offset. Register 29 is the next persistent cursor and 30 is the output
+address of the current pass. -/
+def unpackCursor : Code := sequence (bin .mod 21 4 5)
+ [bin .div 31 21 6, bin .div 22 31 7, bin .mod 23 31 7, bin .mod 24 21 6,
+ bin .add 29 4 1, bin .add 30 11 4]
+
+/-- Result registers are 26 (address or bit), 27 (fetch flag), 28 (owner
+flag). Writing all three on each branch also covers a missing or padded bit. -/
+def literalZero : Code := sequence (set 26 0) [set 27 0, set 28 0]
+
+/-- Extract the indicated bit by shifting and masking, then mark the result as a literal
+without a first-pass choice. -/
+def literalBit (src amount : Reg) : Code := sequence (bin .shiftRight 26 src amount)
+ [bin .bitAnd 26 26 1, set 27 0, set 28 0]
+
+/-- Run the supplied address computation and flag the result as a memory fetch, recording
+whether this cell owns a first-pass choice. -/
+def fetched (addressCode : Code) (own : Bool) : Code :=
+ sequence addressCode [set 27 1, set 28 (if own then 1 else 0)]
+
+/-- Fetch the index bit of this very group, with zero beyond the supplied
+fixed length. Header bit arrays start immediately after the length words. -/
+def indexField : Code := .ifLt 23 14
+ (fetched (sequence (bin .mul 26 22 14) [bin .add 26 26 23, bin .add 26 26 3]) false)
+ literalZero
+
+/-- Compute the fixed base `3 + 2*indexLength` of the advice array. -/
+def adviceBase : Code := sequence (bin .mul 26 2 14) [bin .add 26 26 3]
+
+/-- Resolve the site's advice bit to its header address within the supplied advice length, and
+to a literal zero beyond it. -/
+def adviceField : Code := .ifLt 23 15
+ (fetched (sequence adviceBase [bin .add 26 26 23]) false) literalZero
+
+/-- Resolve an incoming outer cut bit using the left cut length and its header offset
+immediately after the advice. -/
+def leftField : Code := .ifLt 23 18
+ (fetched (sequence adviceBase [bin .add 26 26 15, bin .add 26 26 23]) false) literalZero
+
+/-- Resolve an outgoing outer cut bit using the right cut length and its header offset beyond
+the reserved left cut array. -/
+def rightField : Code := .ifLt 23 20
+ (fetched (sequence adviceBase [bin .add 26 26 15, bin .add 26 26 16, bin .add 26 26 23]) false)
+ literalZero
+
+/-- A middle cut bit is read from the first group's outgoing slot. -/
+def middleField (own : Bool) : Code := .ifLt 23 19
+ (fetched (sequence (bin .mul 26 23 6)
+ [bin .add 26 26 11, bin .add 26 26 12, bin .add 26 26 8, bin .add 26 26 3]) own)
+ literalZero
+
+/-- Dispatch the four one-bit fields using their offset in register 25. -/
+def headerFields : Code :=
+ .ifEq 25 0 indexField (.ifEq 25 1 adviceField
+ (.ifEq 25 2 (.ifEq 22 0 leftField (middleField false)) (.ifEq 22 0 (middleField true) rightField)))
+
+/-- Translate a raw transcript sender into its chosen-bit scratch address.
+The port routine sets registers 32 (present), 33 (sender), 34 (offset). -/
+def portResult : Code := .ifEq 32 0 literalZero
+ (sequence (bin .mul 26 22 7) [bin .add 26 26 33, bin .mul 26 26 6, bin .add 26 26 11,
+ bin .add 26 26 12, bin .add 26 26 8, bin .add 26 26 3, bin .add 26 26 1, bin .add 26 26 34,
+ set 27 1, .ifEq 23 33 (.ifEq 25 34 (set 28 1) (set 28 0)) (set 28 0)])
+
+/-- Extract the address bit or identify one of the fixed-width header/port
+intervals by comparisons against their exclusive ends. Register 35 holds
+a temporary boundary; the port block can reuse it after entering. -/
+def dispatch (port : Code) : Code := .ifLt 24 12 (literalBit 17 24)
+ (sequence (bin .add 35 12 8) [
+ .ifLt 24 35 (sequence (bin .sub 25 24 12) [literalBit 23 25])
+ (sequence (bin .sub 25 24 35) [bin .add 35 35 3, bin .add 35 35 1,
+ .ifLt 24 35 headerFields
+ (sequence (bin .sub 25 24 35) [bin .add 35 35 13,
+ .ifLt 24 35 (sequence port [portResult]) literalZero])])])
+
+/-- A designated cell has two different paths even if the stored value
+already equals the chosen value. A nondesignated cell takes only the
+deterministic skip. Second-pass cells always write one output word. -/
+def act : Code := .ifLt 4 5
+ (.ifEq 28 1 (.branch (write 30 1) (write 30 0)) (set 28 0))
+ (.ifEq 27 1 (sequence (read 26 26) [write 30 26]) (write 30 26))
+
+/-- Fixed body of a data call. Its exit register is 29. The terminal cursor
+may enter the next phase of the auxiliary machine. -/
+def dataCall (port : Code) : Code := sequence loadParameters [unpackCursor, dispatch port, act]
+
+/-- A physical opcode table with constant instruction count across lengths
+when the port block is fixed. -/
+def table (port : Code) := (dataCall port).template (some 29)
+
+/-- The template executes the control graph with the true burst interpreter
+for every raw memory and branch stream. -/
+theorem table_executes (port : Code) {w : ℕ} (pub : Pub → Word w) (state : Word w)
+ (mem : Memory w) (bits : List Bool) (fuel : ℕ) :
+ let cmd := dataCall port
+ let M := (table port).instantiate w pub
+ execute M.program fuel (M.program.start state) mem bits =
+ Flow.run cmd pub state
+ (fun left rs mem' bs => execute M.program left ⟨cmd.exitPC,state,rs,fun _ => 0⟩ mem' bs)
+ fuel cmd.entry (fun _ => 0) mem bits :=
+ Flow.template_executes (dataCall port) (some 29) pub state mem bits fuel
+
+end PrimedInputRAM.Opcodes
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMPortCode.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMPortCode.lean
new file mode 100644
index 0000000000..ce97fdbc14
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMPortCode.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowRun
+import OAI.Computability.VPVNP.PrimedInputRAMAddresses
+
+/-!
+# Finite word code for identifying a directed-message sender
+
+This block reads the current site and incident position from registers 23
+and 25. Registers 32, 33 and 34 report whether the port is connected and
+the site and local offset of the sender. The triangular layer search scans
+successive phase sizes using subtraction, so its intermediate counters fit
+in a word whenever the ordinal does.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.PortCode
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM RAMLayout
+
+/-- Structured word code for resolving a message port, with 48 private registers and 16 public
+words. -/
+abbrev Block := Flow 48 16
+
+/-- Emit one register-copy instruction in the port resolver. -/
+def copy (dst src : Fin 48) : Block := .line (.copy dst src)
+/-- Emit one instruction that applies the given binary word operation to two registers. -/
+def binary (op : BinaryOp) (dst a b : Fin 48) : Block := .line (.binary op dst a b)
+/-- Emit one instruction loading a public port-layout word into a private register. -/
+def publicWord (dst : Fin 48) (i : Fin 16) : Block := .line (.publicWord dst i)
+
+/-- One iteration removes the next complete triangular row. -/
+def scanStep : Block := .seq (binary .add 41 41 1) (binary .sub 40 40 41)
+
+/-- Register 40 is the residual exchange ordinal, 41 is the current phase.
+If the residual is at most the phase, the residual itself is the step. -/
+def scan : Block := .whileLt 41 40 scanStep
+
+/-- Resolve a sorting receive port by decoding its triangular exchange ordinal, flipping the
+partner bit of the site index and subtracting one block from the port offset. -/
+def receiveSort : Block :=
+ .seq (binary .div 40 38 2) <|
+ .seq (copy 41 0) <|
+ .seq scan <|
+ .seq (binary .sub 42 41 40) <|
+ .seq (binary .shiftLeft 42 1 42) <|
+ .seq (binary .bitXor 33 23 42) (binary .sub 34 25 37)
+
+/-- Decode the sorting block number from the port offset. An even block uses the sending site,
+while an odd block resolves the corresponding receive port to its sender. -/
+def sort : Block :=
+ .seq (publicWord 37 13) <|
+ .seq (binary .sub 38 25 36) <|
+ .seq (binary .div 38 38 37) <|
+ .seq (binary .mod 39 38 2) (.ifEq 39 0 (copy 32 1) receiveSort)
+
+/-- Test whether the site has a successor. Its outgoing port is connected precisely before the
+last site. -/
+def successorSend : Block :=
+ .seq (binary .sub 37 7 1) (.ifLt 23 37 (copy 32 1) (copy 32 0))
+
+/-- Mark the incoming successor port as disconnected at site zero. At a later site use the
+preceding site and its outgoing port offset. -/
+def successorReceive : Block :=
+ .ifEq 23 0 (copy 32 0) (.seq (binary .sub 33 23 1) (binary .sub 34 25 35))
+
+/-- The instruction table is independent of every word width and loop bound. -/
+def program : Block :=
+ .seq (copy 32 1) <|
+ .seq (copy 33 23) <|
+ .seq (copy 34 25) <|
+ .seq (publicWord 35 14) <|
+ .seq (publicWord 36 15) (.ifLt 25 35 successorSend (.ifLt 25 36 successorReceive sort))
+
+/-- Decode registers 32 through 34 into an optional pair of sender site and local offset. -/
+def result {w : ℕ} (rs : Regs w 48) : Option (ℕ × ℕ) :=
+ if (rs 32).val = 0 then none else some ((rs 33).val, (rs 34).val)
+
+/-- Register contract on entry. The other registers may contain any word. -/
+structure Input {w : ℕ} (d H : ℕ) (v : Fin (2 ^ d)) (k : Fin (width d H w))
+ (pub : Fin 16 → Word w) (rs : Regs w 48) : Prop where
+ zero : (rs 0).val = 0
+ one : (rs 1).val = 1
+ two : (rs 2).val = 2
+ sites : (rs 7).val = 2 ^ d
+ site : (rs 23).val = v.val
+ offset : (rs 25).val = k.val
+ block : (pub 13).val = blockBits H w
+ first : (pub 14).val = 8 * w
+ base : (pub 15).val = 16 * w
+
+theorem layerCount_next (p : ℕ) : layerCount (p+1) = layerCount p + (p+1) := by
+ rw [layerCount, Nat.choose_succ_succ (p+1) 1, Nat.choose_one_right, Nat.add_comm]
+ rfl
+
+theorem layerCount_mono : Monotone layerCount :=
+ fun _ _ h ↦ Nat.choose_le_choose 2 (Nat.succ_le_succ h)
+
+end PrimedInputRAM.PortCode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMPortRun.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMPortRun.lean
new file mode 100644
index 0000000000..8f4437ff1d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMPortRun.lean
@@ -0,0 +1,370 @@
+import OAI.Computability.VPVNP.PrimedInputRAMPortCode
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+
+/-!
+# Private register execution of the primed transcript port block
+
+The triangular scan stops at the unique phase containing the exchange ordinal.
+Every executed instruction produces a tick and leaves external memory untouched.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM.PortCode
+
+open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM RAMLayout
+
+variable {w : ℕ} {pub : Fin 16 → Word w} {state : Word w} {m : Memory w}
+
+/-- The port block executes for exactly `k` private ticks, takes the given initial registers to
+the specified final registers and preserves external memory. -/
+abbrev Ticks (pub : Fin 16 → Word w) (state : Word w) (m : Memory w) (a : Block)
+ (rs : Regs w 48) (k : ℕ) (out : Regs w 48) : Prop :=
+ Flow.Exec pub state a rs m (List.replicate k .tick) out m
+
+private theorem seqTicks {a b : Block} {rs s t : Regs w 48} {j k : ℕ}
+ (x : Ticks pub state m a rs j s) (y : Ticks pub state m b s k t) :
+ Ticks pub state m (.seq a b) rs (j+k) t := by simpa [Ticks] using x.seq y
+
+private theorem copyTicks (pub : Fin 16 → Word w) (state : Word w) (m : Memory w)
+ (dst src : Fin 48) (rs : Regs w 48) :
+ Ticks pub state m (copy dst src) rs 1 (Function.update rs dst (rs src)) :=
+ .line rfl
+
+private theorem opTicks (pub : Fin 16 → Word w) (state : Word w) (m : Memory w)
+ (op : BinaryOp) (dst lhs rhs : Fin 48) (rs : Regs w 48) :
+ Ticks pub state m (binary op dst lhs rhs) rs 1
+ (Function.update rs dst (op.eval (rs lhs) (rs rhs))) := .line rfl
+
+private theorem pubTicks (pub : Fin 16 → Word w) (state : Word w) (m : Memory w)
+ (dst : Fin 48) (j : Fin 16) (rs : Regs w 48) :
+ Ticks pub state m (publicWord dst j) rs 1 (Function.update rs dst (pub j)) :=
+ .line rfl
+
+/-- With `gap` rows still to remove, the loop uses exactly `3*gap+1`
+instructions. It preserves every register outside its two counters. -/
+theorem scan_exec (pub : Fin 16 → Word w) (state : Word w) (m : Memory w)
+ {d : ℕ} (l : Layer d) (gap p : ℕ) (hend : p + gap = l.phase) (rs : Regs w 48)
+ (h₁ : (rs 1).val = 1) (hp : (rs 41).val = p)
+ (hres : layerCount p + (rs 40).val = l.ordinal.val) :
+ ∃ out, Ticks pub state m scan rs (3 * gap + 1) out ∧ (out 41).val = l.phase ∧
+ (out 40).val = l.step ∧ ∀ i : Fin 48, i ≠ 40 → i ≠ 41 → out i = rs i := by
+ change layerCount p + (rs 40).val = layerCount l.phase + l.step at hres
+ induction gap generalizing p rs with
+ | zero =>
+ have hphase : p = l.phase := by omega
+ rw [hphase] at hres
+ have hstep := l.step_le
+ refine ⟨rs, Flow.Exec.whileDone ?_, by omega, by omega, fun _ _ _ ↦ rfl⟩
+ change ¬ (rs 41).val < (rs 40).val
+ omega
+ | succ gap ih =>
+ have hnext : layerCount (p+1) ≤ layerCount l.phase := layerCount_mono (by omega)
+ rw [layerCount_next] at hnext
+ have htest : rs 41 < rs 40 := by change (rs 41).val < (rs 40).val; omega
+ have hadd : (rs 41).val + (rs 1).val < 2 ^ w := by
+ have := (rs 40).isLt
+ omega
+ let a := Function.update rs (41 : Fin 48) (BinaryOp.add.eval (rs 41) (rs 1))
+ let b := Function.update a (40 : Fin 48) (BinaryOp.sub.eval (a 40) (a 41))
+ have ha : (a 41).val = p + 1 := by
+ simp [a, BinaryOp.eval, Fin.val_add_eq_of_add_lt hadd, hp, h₁]
+ have ha40 : a 40 = rs 40 := by simp [a]
+ have hle : a 41 ≤ a 40 := by change (a 41).val ≤ (a 40).val; rw [ha, ha40]; omega
+ have hb : (b 40).val = (rs 40).val - (p + 1) := by
+ rw [show b 40 = a 40 - a 41 by simp [b, BinaryOp.eval], Fin.sub_val_of_le hle, ha40, ha]
+ have hb41 : (b 41).val = p + 1 := by simpa [b, Function.update_apply] using ha
+ have hb1 : (b 1).val = 1 := by simpa [b, a, Function.update_apply] using h₁
+ have hstep : Ticks pub state m scanStep rs 2 b :=
+ seqTicks (opTicks pub state m .add 41 41 1 rs) (opTicks pub state m .sub 40 40 41 a)
+ obtain ⟨out, ho, hphase, hval, hkeep⟩ := ih (p+1) (by omega) b hb1 hb41
+ (by rw [layerCount_next, hb]; omega)
+ refine ⟨out, ?_, hphase, hval, fun i hi hj ↦ ?_⟩
+ · have hrun := Flow.Exec.whileStep htest hstep ho
+ change Flow.Exec pub state scan rs m (List.replicate _ _) out m
+ rw [show 3 * (gap+1) + 1 = (2 + (3 * gap + 1)) + 1 by omega, List.replicate_succ,
+ List.replicate_add]
+ exact hrun
+ · rw [hkeep _ hi hj]
+ simp [b, a, Function.update_of_ne hi, Function.update_of_ne hj]
+
+private theorem div_val (x y : Word w) :
+ (BinaryOp.div.eval x y).val = x.val / y.val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self _ _).trans_lt x.isLt)
+
+private theorem mod_val (x y : Word w) :
+ (BinaryOp.mod.eval x y).val = x.val % y.val :=
+ Nat.mod_eq_of_lt ((Nat.mod_le _ _).trans_lt x.isLt)
+
+private theorem sub_val (x y : Word w) (h : y.val ≤ x.val) :
+ (BinaryOp.sub.eval x y).val = x.val - y.val := Fin.sub_val_of_le h
+
+private theorem receive_exec {d : ℕ} (l : Layer d) (rs : Regs w 48)
+ (hzero : (rs 0).val = 0) (hone : (rs 1).val = 1) (htwo : (rs 2).val = 2)
+ (hord : (rs 38).val / 2 = l.ordinal.val) (hpos : (rs 32).val = 1)
+ (hk : (rs 37).val ≤ (rs 25).val) (hw : d ≤ w) (hv : (rs 23).val < 2 ^ d) :
+ ∃ out, Ticks pub state m receiveSort rs (3 * l.phase + 7) out ∧
+ result out = some (RAMSort.partner l.siteBit (rs 23).val, (rs 25).val - (rs 37).val) := by
+ let a := Function.update rs (40 : Fin 48) (BinaryOp.div.eval (rs 38) (rs 2))
+ let b := Function.update a (41 : Fin 48) (a 0)
+ have hb40 : (b 40).val = l.ordinal.val := by simp [b, a, div_val, htwo, hord]
+ obtain ⟨s,hs,hphase,hstep,hkeep⟩ := scan_exec pub state m l l.phase 0 (by omega) b
+ (by simpa [b, a] using hone) (by simpa [b, a] using hzero)
+ (by change 0 + (b 40).val = _; omega)
+ have keep (i : Fin 48) (h₄₀ : i ≠ 40) (h₄₁ : i ≠ 41) : s i = rs i := by
+ rw [hkeep _ h₄₀ h₄₁]
+ simp [b, a, Function.update_of_ne h₄₀, Function.update_of_ne h₄₁]
+ let c := Function.update s (42 : Fin 48) (BinaryOp.sub.eval (s 41) (s 40))
+ let e := Function.update c (42 : Fin 48) (BinaryOp.shiftLeft.eval (c 1) (c 42))
+ let f := Function.update e (33 : Fin 48) (BinaryOp.bitXor.eval (e 23) (e 42))
+ let out := Function.update f (34 : Fin 48) (BinaryOp.sub.eval (f 25) (f 37))
+ have hle : (s 40).val ≤ (s 41).val := by rw [hphase,hstep]; exact l.step_le
+ have hc42 : (c 42).val = l.siteBit := by simp [c, sub_val _ _ hle, hstep,hphase, Layer.siteBit]
+ have hc1 : (c 1).val = 1 := by simpa [c, keep] using hone
+ have hbit : l.siteBit < w := l.siteBit_lt.trans_le hw
+ have hpow := Nat.pow_lt_pow_right (by decide : 1 < 2) hbit
+ have he42 : (e 42).val = 2 ^ l.siteBit := by
+ simp [e, BinaryOp.eval, hc42, hbit, Nat.shiftLeft_eq, hc1, Nat.mod_eq_of_lt hpow]
+ have he23 : e 23 = rs 23 := by simp [e,c,keep]
+ have hxor : (e 23).val ^^^ (e 42).val < 2 ^ w := by
+ rw [he23,he42]
+ exact Nat.xor_lt_two_pow (hv.trans_le (Nat.pow_le_pow_right (by decide : 0 < 2) hw)) hpow
+ have hf33 : (f 33).val = RAMSort.partner l.siteBit (rs 23).val := by
+ change (BinaryOp.bitXor.eval (e 23) (e 42)).val = _
+ rw [show (BinaryOp.bitXor.eval (e 23) (e 42)).val = (e 23).val ^^^ (e 42).val from Nat.mod_eq_of_lt hxor, he23, he42]
+ rfl
+ have hf25 : f 25 = rs 25 := by simp [f,e,c,keep]
+ have hf37 : f 37 = rs 37 := by simp [f,e,c,keep]
+ have hsub : (f 37).val ≤ (f 25).val := by rwa [hf37,hf25]
+ refine ⟨out, ?_, ?_⟩
+ · have run := seqTicks (opTicks pub state m .div 40 38 2 rs) <|
+ seqTicks (copyTicks pub state m 41 0 a) <|
+ seqTicks hs <| seqTicks (opTicks pub state m .sub 42 41 40 s) <|
+ seqTicks (opTicks pub state m .shiftLeft 42 1 42 c) <|
+ seqTicks (opTicks pub state m .bitXor 33 23 42 e) (opTicks pub state m .sub 34 25 37 f)
+ change Ticks pub state m receiveSort rs (1+(1+((3*l.phase+1)+(1+(1+(1+1)))))) out at run
+ rw [show 3*l.phase+7 = 1+(1+((3*l.phase+1)+(1+(1+(1+1))))) by omega]
+ exact run
+ · have ho32 : (out 32).val = 1 := by simpa [out,f,e,c,keep] using hpos
+ have ho33 : (out 33).val = RAMSort.partner l.siteBit (rs 23).val := by simpa [out] using hf33
+ have ho34 : (out 34).val = (rs 25).val - (rs 37).val := by
+ change (BinaryOp.sub.eval (f 25) (f 37)).val = _
+ rw [sub_val _ _ hsub, hf25,hf37]
+ simp [result, ho32,ho33,ho34]
+
+private structure Prepared {d H : ℕ} {v : Fin (2 ^ d)} {k : Fin (width d H w)}
+ (pub : Fin 16 → Word w) (rs : Regs w 48) : Prop extends Input d H v k pub rs where
+ present : (rs 32).val = 1
+ u : (rs 33).val = v.val
+ t : (rs 34).val = k.val
+ firstReg : (rs 35).val = 8 * w
+ baseReg : (rs 36).val = 16 * w
+
+private theorem sort_exec {d H : ℕ} (v : Fin (2 ^ d)) (l : Layer d) (dir : Fin 2)
+ (j : Fin (blockBits H w)) (rs : Regs w 48)
+ (I : Prepared (H := H) (v := v) (k := offset d H w (.inr (l,dir,j))) pub rs) :
+ ∃ cost out, Ticks pub state m sort rs cost out ∧ cost ≤ 3 * d + 12 ∧
+ result out = some ((if dir = 0 then v else l.partner v).val,
+ (offset d H w (.inr (l,0,j))).val) := by
+ let k := (offset d H w (.inr (l,dir,j))).val
+ have hr : (rs 25).val = k := I.offset
+ have hk : k = 16 * w + l.ordinal.val * (2 * blockBits H w) + dir.val * blockBits H w + j.val :=
+ offset_sort ..
+ have hbase : 16 * w ≤ k := by omega
+ have hsub : k - 16 * w = blockBits H w * (2 * l.ordinal.val + dir.val) + j.val := by
+ rw [hk, show 16 * w + l.ordinal.val * (2 * blockBits H w) + dir.val * blockBits H w + j.val =
+ 16 * w + (blockBits H w * (2 * l.ordinal.val + dir.val) + j.val) by ring, Nat.add_sub_cancel_left]
+ have hchunk : (k - 16 * w) / blockBits H w = 2 * l.ordinal.val + dir.val := by
+ rw [hsub, Nat.mul_add_div (Nat.zero_lt_of_lt j.isLt), Nat.div_eq_of_lt j.isLt, Nat.add_zero]
+ let a := Function.update rs (37 : Fin 48) (pub 13)
+ let b := Function.update a (38 : Fin 48) (BinaryOp.sub.eval (a 25) (a 36))
+ let c := Function.update b (38 : Fin 48) (BinaryOp.div.eval (b 38) (b 37))
+ let s := Function.update c (39 : Fin 48) (BinaryOp.mod.eval (c 38) (c 2))
+ have hle : (a 36).val ≤ (a 25).val := by simpa [a, I.baseReg, hr] using hbase
+ have hb : (b 38).val = k - 16 * w := by
+ change (BinaryOp.sub.eval (a 25) (a 36)).val = _
+ rw [sub_val _ _ hle]
+ simp [a, I.baseReg, hr]
+ have hb37 : (b 37).val = blockBits H w := by simp [a,b,I.block]
+ have hc : (c 38).val = 2 * l.ordinal.val + dir.val := by
+ change (BinaryOp.div.eval (b 38) (b 37)).val = _
+ rw [div_val,hb,hb37,hchunk]
+ have hs39 : (s 39).val = dir.val := by
+ change (BinaryOp.mod.eval (c 38) (c 2)).val = _
+ rw [mod_val, hc, show (c 2).val = 2 by simp [c,b,a,I.two]]
+ omega
+ have hzero : (s 0).val = 0 := by simp [s,c,b,a,I.zero]
+ have hone : (s 1).val = 1 := by simp [s,c,b,a,I.one]
+ have htwo : (s 2).val = 2 := by simp [s,c,b,a,I.two]
+ have hpos : (s 32).val = 1 := by simp [s,c,b,a,I.present]
+ have hsite : (s 23).val = v.val := by simp [s,c,b,a,I.site]
+ have hport : (s 25).val = k := by simp [s,c,b,a,hr]
+ have hblock : (s 37).val = blockBits H w := by simp [s,c,b,a,I.block]
+ have hs38 : (s 38).val = 2 * l.ordinal.val + dir.val := by simpa [s] using hc
+ let prefixRun {out : Regs w 48} {cnt : ℕ}
+ (h : Ticks pub state m (.ifEq 39 0 (copy 32 1) receiveSort) s cnt out) :
+ Ticks pub state m sort rs (1+(1+(1+(1+cnt)))) out :=
+ seqTicks (pubTicks pub state m 37 13 rs) <|
+ seqTicks (opTicks pub state m .sub 38 25 36 a) <|
+ seqTicks (opTicks pub state m .div 38 38 37 b) <|
+ seqTicks (opTicks pub state m .mod 39 38 2 c) h
+ by_cases hd : dir = 0
+ · subst dir
+ let out := Function.update s (32 : Fin 48) (s 1)
+ have he : s 39 = s 0 := Fin.ext (hs39.trans hzero.symm)
+ have run : Ticks pub state m (.ifEq 39 0 (copy 32 1) receiveSort) s 2 out :=
+ .ifEqYes he (copyTicks pub state m 32 1 s)
+ refine ⟨6,out,prefixRun run,by omega,?_⟩
+ have h33 : (out 33).val = v.val := by simp [out,s,c,b,a,I.u]
+ have h34 : (out 34).val = k := by simp [out,s,c,b,a,I.t,k]
+ simp [result, show (out 32).val = 1 by simpa [out] using hone, h33,h34,k]
+ · have hd1 : dir.val = 1 := by
+ have hne : dir.val ≠ 0 := fun h ↦ hd (Fin.ext h)
+ have := dir.isLt
+ omega
+ have he : s 39 ≠ s 0 := fun e ↦ by have := congrArg Fin.val e; omega
+ have hlarge : d ≤ w := by
+ by_contra hn
+ have hh := Nat.pow_le_pow_right (by decide : 0 < 2) (show w ≤ d by omega)
+ have hword := (rs 7).isLt
+ rw [I.sites] at hword
+ omega
+ have hwidth : (s 37).val ≤ (s 25).val := by rw [hblock,hport,hk,hd1,Nat.one_mul]; omega
+ obtain ⟨out,ho,hresult⟩ := receive_exec (pub := pub) (state := state) (m := m) l s hzero hone htwo
+ (by rw [hs38,hd1]; omega) hpos hwidth hlarge (by rw [hsite]; exact v.isLt)
+ have hrun : Ticks pub state m (.ifEq 39 0 (copy 32 1) receiveSort) s (3*l.phase+7+1) out :=
+ .ifEqNo he ho
+ refine ⟨_, out, prefixRun hrun, by have := l.phase_lt; omega, ?_⟩
+ rw [hresult,hsite,hport,hblock,ite_eq_right hd,offset_sort,hk,hd1]
+ simp [Layer.partner, Nat.add_assoc]
+ omega
+
+private abbrev route : Block := .ifLt 25 35 successorSend (.ifLt 25 36 successorReceive sort)
+
+private theorem route_exec {d H : ℕ} (v : Fin (2 ^ d)) (k : Fin (width d H w)) (rs : Regs w 48)
+ (I : Prepared (H := H) (v := v) (k := k) pub rs) :
+ ∃ cost out, Ticks pub state m route rs cost out ∧ cost ≤ 3*d+14 ∧
+ result out = (rawSource d H w v.val k.val).1 := by
+ obtain ⟨p, rfl⟩ := (offset d H w).surjective k
+ rw [rawSource_offset]
+ rcases p with ⟨dir,j⟩ | ⟨l,dir,j⟩
+ · fin_cases dir
+ · have hj := j.isLt
+ have hport : (rs 25).val = j.val := by simpa [offset_successor] using I.offset
+ have hfirst : rs 25 < rs 35 := by change (rs 25).val < (rs 35).val; rw [hport,I.firstReg]; exact hj
+ let a := Function.update rs (37 : Fin 48) (BinaryOp.sub.eval (rs 7) (rs 1))
+ have hle : (rs 1).val ≤ (rs 7).val := by rw [I.one,I.sites]; exact Nat.two_pow_pos d
+ have ha37 : (a 37).val = 2 ^ d - 1 := by
+ change (BinaryOp.sub.eval (rs 7) (rs 1)).val = _
+ rw [sub_val _ _ hle,I.sites,I.one]
+ have ha23 : (a 23).val = v.val := by simpa [a] using I.site
+ have ha33 : (a 33).val = v.val := by simpa [a] using I.u
+ have ha34 : (a 34).val = j.val := by simpa [a,offset_successor] using I.t
+ by_cases hv : v.val + 1 < 2 ^ d
+ · let out := Function.update a (32 : Fin 48) (a 1)
+ have ht : a 23 < a 37 := by change (a 23).val < (a 37).val; omega
+ have hh : Ticks pub state m (.ifLt 23 37 (copy 32 1) (copy 32 0)) a 2 out :=
+ .ifLtYes ht (copyTicks pub state m 32 1 a)
+ refine ⟨4,out,Flow.Exec.ifLtYes hfirst (seqTicks (opTicks pub state m .sub 37 7 1 rs) hh),by omega,?_⟩
+ have ho : (out 32).val = 1 := by simp [out,a,I.one]
+ have ho33 : (out 33).val = v.val := by simpa [out] using ha33
+ have ho34 : (out 34).val = j.val := by simpa [out] using ha34
+ simp [result,ho,sourcePort,hv,ho33,ho34,offset_successor]
+ · let out := Function.update a (32 : Fin 48) (a 0)
+ have ht : ¬ a 23 < a 37 := by change ¬ (a 23).val < (a 37).val; omega
+ have hh : Ticks pub state m (.ifLt 23 37 (copy 32 1) (copy 32 0)) a 2 out :=
+ .ifLtNo ht (copyTicks pub state m 32 0 a)
+ refine ⟨4,out,Flow.Exec.ifLtYes hfirst (seqTicks (opTicks pub state m .sub 37 7 1 rs) hh),by omega,?_⟩
+ have ho : (out 32).val = 0 := by simp [out,a,I.zero]
+ simp [result,ho,sourcePort,hv]
+ · have hj := j.isLt
+ have hport : (rs 25).val = 8*w + j.val := by simpa [offset_successor] using I.offset
+ have hfirst : ¬ rs 25 < rs 35 := by change ¬ (rs 25).val < (rs 35).val; rw [I.firstReg]; omega
+ have hbase : rs 25 < rs 36 := by change (rs 25).val < (rs 36).val; rw [I.baseReg]; omega
+ by_cases hv : 0 < v.val
+ · have ht : rs 23 ≠ rs 0 := fun h ↦ by have := congrArg Fin.val h; rw [I.site,I.zero] at this; omega
+ let a := Function.update rs (33 : Fin 48) (BinaryOp.sub.eval (rs 23) (rs 1))
+ let out := Function.update a (34 : Fin 48) (BinaryOp.sub.eval (a 25) (a 35))
+ have run : Ticks pub state m successorReceive rs 3 out := Flow.Exec.ifEqNo ht
+ (seqTicks (opTicks pub state m .sub 33 23 1 rs) (opTicks pub state m .sub 34 25 35 a))
+ refine ⟨5,out,Flow.Exec.ifLtNo hfirst (Flow.Exec.ifLtYes hbase run),by omega,?_⟩
+ have ho32 : (out 32).val = 1 := by simp [out,a,I.present]
+ have ha33 : (a 33).val = v.val - 1 := by
+ change (BinaryOp.sub.eval (rs 23) (rs 1)).val = _
+ rw [sub_val _ _ (by rw [I.one,I.site]; omega),I.site,I.one]
+ have ha25 : (a 25).val = 8*w + j.val := by simpa [a] using hport
+ have ha35 : (a 35).val = 8*w := by simpa [a] using I.firstReg
+ have ho34 : (out 34).val = j.val := by
+ change (BinaryOp.sub.eval (a 25) (a 35)).val = _
+ rw [sub_val _ _ (by omega),ha25,ha35,Nat.add_sub_cancel_left]
+ have ho33 : (out 33).val = v.val-1 := by simpa [out] using ha33
+ simp [result,ho32,ho33,ho34,sourcePort,hv,offset_successor]
+ · have ht : rs 23 = rs 0 := Fin.ext (by rw [I.site,I.zero]; omega)
+ let out := Function.update rs (32 : Fin 48) (rs 0)
+ have run : Ticks pub state m successorReceive rs 2 out := .ifEqYes ht (copyTicks pub state m 32 0 rs)
+ refine ⟨4,out,Flow.Exec.ifLtNo hfirst (Flow.Exec.ifLtYes hbase run),by omega,?_⟩
+ have ho32 : (out 32).val = 0 := by simp [out,I.zero]
+ simp [result,ho32,sourcePort,hv]
+ · have hk := offset_sort l dir j (d := d)
+ have hfirst : ¬ rs 25 < rs 35 := by change ¬ (rs 25).val < (rs 35).val; rw [I.offset,I.firstReg]; omega
+ have hbase : ¬ rs 25 < rs 36 := by change ¬ (rs 25).val < (rs 36).val; rw [I.offset,I.baseReg]; omega
+ obtain ⟨k,out,run,hcost,ho⟩ := sort_exec (state := state) (m := m) v l dir j rs I
+ refine ⟨k+1+1,out,Flow.Exec.ifLtNo hfirst (Flow.Exec.ifLtNo hbase run),by omega,?_⟩
+ simpa [sourcePort] using ho
+
+/-- The actual fixed register program reaches its normal exit with the
+calculated raw address. Its event trace contains private ticks only. -/
+theorem program_exec {d H : ℕ} (v : Fin (2 ^ d)) (k : Fin (width d H w)) (rs : Regs w 48)
+ (I : Input d H v k pub rs) :
+ ∃ cost out, Ticks pub state m program rs cost out ∧ cost ≤ 3*d+19 ∧
+ result out = (rawSource d H w v.val k.val).1 := by
+ let a := Function.update rs (32 : Fin 48) (rs 1)
+ let b := Function.update a (33 : Fin 48) (a 23)
+ let c := Function.update b (34 : Fin 48) (b 25)
+ let e := Function.update c (35 : Fin 48) (pub 14)
+ let s := Function.update e (36 : Fin 48) (pub 15)
+ have hi : Prepared (H := H) (v := v) (k := k) pub s := by
+ refine ⟨?_, ?_, ?_, ?_, ?_, ?_⟩
+ · rcases I with ⟨h0,h1,h2,h7,h23,h25,h13,h14,h15⟩
+ constructor <;> simp_all [s,e,c,b,a]
+ all_goals simp [s,e,c,b,a,I.one,I.site,I.offset,I.first,I.base]
+ obtain ⟨cnt,out,hr,hc,ho⟩ := route_exec (state := state) (m := m) v k s hi
+ refine ⟨1+(1+(1+(1+(1+cnt)))),out,?_,by omega,ho⟩
+ exact seqTicks (copyTicks pub state m 32 1 rs) <| seqTicks (copyTicks pub state m 33 23 a) <|
+ seqTicks (copyTicks pub state m 34 25 b) <| seqTicks (pubTicks pub state m 35 14 c) <|
+ seqTicks (pubTicks pub state m 36 15 e) hr
+
+private def untouched (i : Fin 48) : Block → Prop
+ | .line op => op.destination ≠ some i
+ | .seq a b | .ifEq _ _ a b | .ifLt _ _ a b | .branch a b => untouched i a ∧ untouched i b
+ | .whileLt _ _ body => untouched i body
+
+private theorem exec_untouched {a : Block} {rs out : Regs w 48} {m' es}
+ (h : Flow.Exec pub state a rs m es out m') (i : Fin 48) (hi : untouched i a) : out i = rs i := by
+ induction h with
+ | @line op regs mem e next final he =>
+ apply trace_preserves (pub := pub) (state := state) (ops := [op]) (i := i) (mem := mem) (m := final) (es := [e])
+ · simpa [untouched] using hi
+ · simp [trace, he]
+ | seq _ _ ih₁ ih₂ => exact (ih₂ hi.2).trans (ih₁ hi.1)
+ | ifEqYes _ _ ih | ifLtYes _ _ ih | branchYes _ ih => exact ih hi.1
+ | ifEqNo _ _ ih | ifLtNo _ _ ih | branchNo _ ih => exact ih hi.2
+ | whileDone _ => rfl
+ | whileStep _ _ _ ih₁ ih₂ => exact (ih₂ hi).trans (ih₁ hi)
+
+/-- All registers below the return registers retain their entry values. -/
+theorem program_preserves {rs out : Regs w 48} {cost : ℕ}
+ (h : Ticks pub state m program rs cost out) (i : Fin 48) (hi : i.val < 32) : out i = rs i := by
+ apply exec_untouched h i
+ simp only [untouched, program, successorSend, successorReceive, sort, receiveSort, scan, scanStep,
+ copy, binary, publicWord, Op.destination, Option.some.injEq, ne_eq, Fin.ext_iff]
+ norm_num
+ omega
+
+end PrimedInputRAM.PortCode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMResources.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMResources.lean
new file mode 100644
index 0000000000..881ae36b84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMResources.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.PrimedInputRAMCapacity
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeExecutionResult
+
+/-!
+# The input passes at the paper's live and virtual parameters
+
+For one fixed choice of the address multiplier, all sufficiently large
+lengths support every primed pair. Its actual fixed opcode table respects
+the auxiliary per-call work and probe caps, and the `R′K′` total budget.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM CursorBounds Compression Opcodes Filter
+
+/-- Six elementary word operations per instruction include dispatch and
+operand handling. The complete private fuel is eventually below the
+auxiliary machine's `n^10` work cap, independently of the pair. -/
+theorem eventually_nativeInputWork (B : ℕ) :
+ ∀ᶠ n : ℕ in atTop, 6 * nativeFuel (addressWidth B n) ≤ n^10 := by
+ filter_upwards [eventually_ge_atTop (6*(3*B+165)), eventually_ge_atTop 1] with n hn hp
+ have hclog : Nat.clog 2 n ≤ n := (Nat.clog_le_iff_le_pow (by decide : 1 < 2)).mpr Nat.lt_two_pow_self.le
+ have hr : addressWidth B n ≤ B*n := Nat.mul_le_mul_left _ hclog
+ have hadd : 165 ≤ 165*n := Nat.le_mul_of_pos_right _ hp
+ calc
+ 6*nativeFuel (addressWidth B n) ≤ 6*((3*B+165)*n) := by
+ rw [Nat.add_mul, Nat.mul_assoc]
+ unfold nativeFuel
+ omega
+ _ = (6*(3*B+165))*n := (Nat.mul_assoc ..).symm
+ _ ≤ n^2 := by simpa [pow_two] using Nat.mul_le_mul_right n hn
+ _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide : 2 ≤ 10)
+
+/-- Simultaneous layout, private word fit and exact auxiliary budgets for the
+physical assembler, uniformly for all group pairs and histogram lengths. -/
+theorem eventually_physicalLayouts (p : UniversalMachine.Program) (a d₁ d₂ C B : ℕ)
+ (hB : max (max (a+1) (a+d₂)) (max d₁ C) + 2 ≤ B) {δ : ℝ} (hδ : 0 < δ) (hδ' : δ ≤ 1) :
+ ∀ᶠ n : ℕ in atTop, ∀ i : Fin (2^(n^a-1)), ∀ t ≤ n^C,
+ let L := PairedChain.lengths (n^a-1) (n^d₂) (n^d₁) i
+ let r := addressWidth B n
+ let S := 2^(virtualBits B n)
+ let K := 2^(roundedUp 1 4 n)
+ ∃ Q : Layout L n r (liveBucket δ n) (CursorBounds.wordBits B n),
+ Q.program = p ∧ Q.scratchBase = S ∧ Header.count L+t ≤ S ∧ ParameterFit Q ∧
+ 6 ≤ K ∧ 11 * positions n r + 1 ≤ S*K ∧ 6*nativeFuel r ≤ n^10 := by
+ have hpos : 1 ≤ B := by omega
+ filter_upwards [eventually_pairedLayouts p a d₁ d₂ C B hB hδ hδ',
+ eventually_parameterFit p hpos, eventually_virtualBucket_ge 6, eventually_pairExternalBudget B 22,
+ eventually_nativeInputWork B] with n hQ hF hK htotal hwork
+ intro i t ht
+ obtain ⟨Q,hp,hs,hh⟩ := hQ i t ht
+ have hx := htotal 0 (Nat.zero_le _)
+ have he : 11 * positions n (addressWidth B n) = 22 * (processorCount B n*n) := by
+ unfold positions processorCount addressBits
+ ring
+ refine ⟨Q,hp,hs,hs ▸ hh,hF _ _ Q hp,hK,?_,hwork⟩
+ rw [he]
+ omega
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMRows.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMRows.lean
new file mode 100644
index 0000000000..0a5a1e1796
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMRows.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.PrimedInputRAMLayout
+import OAI.Computability.VPVNP.RAMSiteInput
+
+/-!
+# Full coefficient-machine inputs of the two primed groups
+
+Resolving the rectangular scratch or header reference at each bit position
+reproduces the exact tape in Section 9.2. The equality is for all shared bit
+assignments. The raw sort and successor messages are never parsed here.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM RAMLayout RAMSerialization
+
+variable {n r H w : ℕ} {L : Lengths}
+
+/-- Number of trailing zero bits after the program prefix, site address, four header bits and
+incident ports in a length-`n` input row. -/
+def padding (p : UniversalMachine.Program) (n r H w : ℕ) : ℕ :=
+ n - ((UniversalMachine.programPrefix p).length + (r + 4 + width r H w))
+
+/-- Positions in a complete primed input row, including the actual program prefix and the
+trailing padding for length `n`. -/
+abbrev RowField (p : UniversalMachine.Program) (n r H w : ℕ) :=
+ Field (UniversalMachine.programPrefix p).length r H w (padding p n r H w)
+
+/-- Identify the typed fields of a fitting primed input row with their bit positions in the
+length-`n` tape. -/
+def rowIndex (p : UniversalMachine.Program) (hf : ProcessorInput.Fits p n r H w) :
+ RowField p n r H w ≃ Fin n :=
+ (fieldIndex ..).trans (finCongr (by unfold padding ProcessorInput.Fits at *; omega))
+
+/-- The untested incident bits of a primed group are precisely its assigned
+sending bits, copied to their matching ports and clamped at missing ports. -/
+def incident (bits : Internal L r H w → Bool) (u : Site r) (j : Fin (width r H w)) : Bool :=
+ (assignmentEquiv r H w (fun t ↦ bits (.inr (u.1,t)))).val (u.2, (offset r H w).symm j)
+
+/-- The four one-bit header fields as they appear on a primed tape. -/
+def siteHeader (hdr : Header L → Bool) (bits : Internal L r H w → Bool) (u : Site r) :
+ ProcessorInput.Header := fun j ↦ (headerRef L u.1 u.2 j).value hdr bits
+
+/-- Full `n`-bit input whose ordered parses occur in (9.4). -/
+def input (p : UniversalMachine.Program) (hf : ProcessorInput.Fits p n r H w) (hdr : Header L → Bool)
+ (bits : Internal L r H w → Bool) (u : Site r) : Fin n → Bool :=
+ ProcessorInput.encode p n u.2 (siteHeader hdr bits u) (incident bits u) hf
+
+private theorem port_value {p : UniversalMachine.Program} (prefixBits : Fin (UniversalMachine.programPrefix p).length → Bool)
+ (hdr : Header L → Bool) (bits : Internal L r H w → Bool) (u : Site r) (port : Slot r H w) :
+ (cellRef (pad := padding p n r H w) L prefixBits
+ (u, .inr (.inr (.inr (.inl port))))).value hdr bits = incident bits u (offset r H w port) := by
+ simp only [incident, Equiv.symm_apply_apply]
+ change _ = ((source (u.2,port)).map _).getD false
+ simp only [cellRef]
+ split
+ · rename_i h
+ rw [h]
+ rfl
+ · rename_i v h
+ conv_rhs => rw [h]
+ change bits (.inr (u.1,⟨v,source_shared h⟩)) =
+ (if hv : IsSend v then bits (.inr (u.1,⟨v,hv⟩)) else false)
+ rw [dite_eq_left (source_shared h)]
+
+private theorem payload_at (p : UniversalMachine.Program) (v : Fin (2^r)) (head : ProcessorInput.Header)
+ (inc : Fin (width r H w) → Bool) {j : ℕ} (hj : j < r + 4 + width r H w) :
+ (ProcessorInput.tape p n v head inc)[(UniversalMachine.programPrefix p).length + j]? =
+ (ProcessorInput.payload v head inc)[j]? := by
+ rw [ProcessorInput.tape, List.getElem?_append_right (by omega), Nat.add_sub_cancel_left,
+ List.getElem?_append_left (by simpa using hj)]
+
+/-- Every position enumerated by the counter agrees with the universal
+machine's actual input, including the literal self-delimiting prefix and all
+trailing padding. -/
+theorem input_at (p : UniversalMachine.Program) (hf : ProcessorInput.Fits p n r H w)
+ (hdr : Header L → Bool) (bits : Internal L r H w → Bool) (u : Site r) (f : RowField p n r H w) :
+ input p hf hdr bits u (rowIndex p hf f) =
+ (cellRef L (UniversalMachine.programPrefix p).get (u, f)).value hdr bits := by
+ let pref := UniversalMachine.programPrefix p
+ let head := siteHeader hdr bits u
+ let inc := incident bits u
+ let i := rowIndex p hf f
+ have he : (ProcessorInput.tape p n u.2 head inc)[i.val]? = some (input p hf hdr bits u i) := by
+ rw [List.getElem?_eq_getElem (by rw [ProcessorInput.length_tape p _ head inc hf]; exact i.isLt)]
+ rfl
+ apply Option.some.inj
+ rw [← he]
+ rcases f with j | (a | (t | (port | pad)))
+ · change (ProcessorInput.tape p n u.2 head inc)[j.val]? = some (pref.get j)
+ rw [ProcessorInput.tape, List.getElem?_append_left j.isLt, List.getElem?_eq_getElem j.isLt]
+ rfl
+ · change (ProcessorInput.tape p n u.2 head inc)[pref.length + a.val]? = some (wordBits r u.2 a)
+ rw [payload_at p u.2 head inc (by have := a.isLt; omega)]
+ exact ProcessorInput.payload_address ..
+ · change (ProcessorInput.tape p n u.2 head inc)[pref.length + (r + t.val)]? = some (head t)
+ rw [payload_at p u.2 head inc (by have := t.isLt; omega)]
+ exact ProcessorInput.payload_header ..
+ · change (ProcessorInput.tape p n u.2 head inc)[pref.length + (r + (4 + (offset r H w port).val))]? =
+ some ((cellRef L pref.get (u, .inr (.inr (.inr (.inl port))))).value hdr bits)
+ rw [port_value (n := n), payload_at p u.2 head inc (by have := (offset r H w port).isLt; omega),
+ ← Nat.add_assoc]
+ exact ProcessorInput.payload_incident ..
+ · change (ProcessorInput.tape p n u.2 head inc)[pref.length + (r + (4 + (width r H w + pad.val)))]? =
+ some false
+ rw [ProcessorInput.tape, List.getElem?_append_right (by change pref.length ≤ _; omega),
+ Nat.add_sub_cancel_left, List.getElem?_append_right (by rw [ProcessorInput.length_payload]; omega),
+ ProcessorInput.length_payload]
+ have hp := pad.isLt
+ change pad.val < padding p n r H w at hp
+ have heq : r + (4 + (width r H w + pad.val)) - (r+4+width r H w) = pad.val := by omega
+ rw [heq, List.getElem?_eq_getElem (by simpa [padding] using hp)]
+ simp
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMRunEquiv.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMRunEquiv.lean
new file mode 100644
index 0000000000..69a1b20f8d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMRunEquiv.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.PrimedInputRAMExecution
+import OAI.Computability.VPVNP.RAMSuccessor
+
+/-!
+# Choice histories of the scheduled primed-input RAM
+
+A native RAM path records one list of branch choices per call. A choose item
+contributes a singleton and every other item contributes the empty list, as
+does the final accepting call. Reading the singleton at each owner recovers
+the chosen assignment even when several branches write equal words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM
+
+variable {M w : ℕ}
+
+/-- The exact choice lists supplied to the item calls and the final call. -/
+def assignmentCalls (ops : Fin M → Item w) (f : Assignment (fun i ↦ (ops i).owns)) :
+ List (List Bool) :=
+ (List.finRange M).map (fun i ↦ (ops i).bits (bitAt f i)) ++ [[]]
+
+/-- Read the first choice of the call at each owner. The defaults make the
+decoder total on malformed streams, which are excluded from `ActualPaths`. -/
+def decodeAssignmentCalls (ops : Fin M → Item w) (bs : List (List Bool)) :
+ Assignment (fun i ↦ (ops i).owns) :=
+ fun i ↦ ((bs[i.val.val]?).getD []).headD false
+
+theorem decode_assignmentCalls (ops : Fin M → Item w) (f : Assignment (fun i ↦ (ops i).owns)) :
+ decodeAssignmentCalls ops (assignmentCalls ops f) = f := by
+ funext i
+ unfold decodeAssignmentCalls assignmentCalls
+ rw [List.getElem?_append_left (by simp),
+ List.getElem?_eq_getElem (by simp)]
+ simp [Item.bits, bitAt, i.property]
+
+/-- Restricting a total bit vector to the choose items produces the same
+choice lists, since deterministic items consume no bits. -/
+theorem assignmentCalls_restrict (ops : Fin M → Item w) (g : Fin M → Bool) :
+ assignmentCalls ops (fun i ↦ g i.val) =
+ (List.finRange M).map (fun i ↦ (ops i).bits (g i)) ++ [[]] := by
+ unfold assignmentCalls
+ congr 1
+ apply List.map_congr_left
+ intro i _
+ cases h : (ops i).owns <;> simp [Item.bits, bitAt, h]
+
+/-- The external probes of each scheduled item, fixed independently of the bits
+and the words fetched from memory. -/
+def Item.probeCount : Item w → ℕ
+ | .skip => 0
+ | .choose _ | .copy (.literal _) _ => 1
+ | .copy (.fetch _) _ => 2
+
+@[simp] theorem Item.probes_eq_probeCount (op : Item w) (bitWord : Bool → Word w)
+ (next : Word w) (m : Memory w) (b : Bool) :
+ (op.report bitWord next m b).probes = op.probeCount := by
+ cases op with
+ | skip | choose => rfl
+ | copy src dst => cases src <;> rfl
+
+/-- Cost of the data calls and the final one-unit halt. -/
+def scheduledCost (ops : Fin M → Item w) : ℕ :=
+ ((List.finRange M).map (fun i ↦ 1 + (ops i).probeCount)).sum + 1
+
+theorem scheduledReports_cost (ops : Fin M → Item w) (bitWord : Bool → Word w)
+ (fit : M < 2^w) (g : Fin M → Bool) (cells : List (Fin M)) (m : Memory w) :
+ RAMBuckets.cost Report.probes (scheduledReports ops bitWord fit g cells m) =
+ (cells.map (fun i ↦ 1 + (ops i).probeCount)).sum := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih => simp [scheduledReports, RAMBuckets.cost, ih]
+
+theorem generated_cost (ops : Fin M → Item w) (bitWord : Bool → Word w)
+ (fit : M < 2^w) (g : Fin M → Bool) (m : Memory w) :
+ RAMBuckets.cost Report.probes (scheduledReports ops bitWord fit g (List.finRange M) m ++
+ [haltReport w]) = scheduledCost ops := by
+ rw [RAMBuckets.cost_append, scheduledReports_cost]
+ rfl
+
+private theorem scheduledReports_probes (ops : Fin M → Item w) (bitWord : Bool → Word w)
+ (fit : M < 2^w) (g : Fin M → Bool) (cells : List (Fin M)) (m : Memory w) :
+ ∀ r ∈ scheduledReports ops bitWord fit g cells m, r.probes ≤ 2 := by
+ induction cells generalizing m with
+ | nil => simp [scheduledReports]
+ | cons i cells ih =>
+ intro r hr
+ rcases List.mem_cons.mp hr with rfl | ht
+ · exact Item.report_probes ..
+ · exact ih _ _ ht
+
+/-- Both caps used by the parsimonious transcript construction hold whenever
+the public cost fits the global budget and each site permits three units. -/
+theorem scheduledReports_withinCaps (ops : Fin M → Item w) (bitWord : Bool → Word w)
+ (fit : M < 2^w) (g : Fin M → Bool) (m : Memory w) {S H : ℕ}
+ (hH : 3 ≤ H) (hTotal : scheduledCost ops ≤ S * H) :
+ withinCaps S H (scheduledReports ops bitWord fit g (List.finRange M) m ++ [haltReport w]) := by
+ constructor
+ · rwa [generated_cost]
+ · intro r hr
+ rcases List.mem_append.mp hr with h | h
+ · have := scheduledReports_probes ops bitWord fit g _ m r h
+ omega
+ · obtain rfl := List.mem_singleton.mp h
+ change 1 + 0 ≤ H
+ omega
+
+/-- The native paths respecting a cap are in bijection with the independent
+bits when all generated report sequences fit the cap. -/
+def scheduledPathEquivOfCap (ops : Fin M → Item w) (bitWord : Bool → Word w)
+ (fit : M < 2^w) (m : Memory w) (cap : List (Report w) → Prop)
+ (hcap : ∀ g : Fin M → Bool, cap (scheduledReports ops bitWord fit g (List.finRange M) m ++
+ [haltReport w])) :
+ ActualPaths (scheduledProgram ops bitWord fit) 3 0 m cap ≃
+ Assignment (fun i ↦ (ops i).owns) where
+ toFun p := decodeAssignmentCalls ops p.val
+ invFun f := ⟨assignmentCalls ops f, by
+ have hr := run_generated ops bitWord fit (bitAt f) m
+ refine ⟨_, hr, ?_, hcap (bitAt f)⟩
+ rw [endState_append]
+ rfl⟩
+ left_inv p := by
+ apply Subtype.ext
+ change assignmentCalls ops (decodeAssignmentCalls ops p.val) = p.val
+ obtain ⟨rs, hr, he, _⟩ := p.property
+ obtain ⟨g, hg⟩ := (run_accepted_iff ops bitWord fit m p.val).mp ⟨rs, hr, he⟩
+ rw [hg.trans (assignmentCalls_restrict ops g).symm, decode_assignmentCalls]
+ right_inv f := decode_assignmentCalls ops f
+
+/-- With no cost filter the interpreter enumerates every assignment once. -/
+def scheduledPathEquiv (ops : Fin M → Item w) (bitWord : Bool → Word w)
+ (fit : M < 2^w) (m : Memory w) :
+ ActualPaths (scheduledProgram ops bitWord fit) 3 0 m (fun _ ↦ True) ≃
+ Assignment (fun i ↦ (ops i).owns) :=
+ scheduledPathEquivOfCap ops bitWord fit m _ (fun _ ↦ trivial)
+
+/-- Exact enumeration by paths under the global and per-call RAM caps. -/
+def scheduledPathEquivWithinCaps (ops : Fin M → Item w) (bitWord : Bool → Word w)
+ (fit : M < 2^w) (m : Memory w) {S H : ℕ}
+ (hH : 3 ≤ H) (hTotal : scheduledCost ops ≤ S * H) :
+ ActualPaths (scheduledProgram ops bitWord fit) 3 0 m (withinCaps S H) ≃
+ Assignment (fun i ↦ (ops i).owns) :=
+ scheduledPathEquivOfCap ops bitWord fit m _ fun g ↦
+ scheduledReports_withinCaps ops bitWord fit g m hH hTotal
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMSchedule.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMSchedule.lean
new file mode 100644
index 0000000000..684f682c29
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMSchedule.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.PrimedInputRAMCopy
+import OAI.Computability.VPVNP.RAMChain
+
+/-!
+# A cursor-controlled burst RAM for the two primed input passes
+
+Each public cursor dispatches one skip, choice-and-write, literal write, or read-and-write.
+Private control is re-created at the beginning of each call. The external memory is read
+only by a `read` instruction. Cursor `M` is an explicit halt, so the `M` data calls can
+also be used as a prefix returning the terminal cursor for the subsequent grammar parse.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM
+
+variable {M w : ℕ}
+
+/-- One input-pass action. It skips a position, stores a chosen bit at an address, or copies a
+literal or fetched word to its destination. -/
+inductive Item (w : ℕ)
+ | skip
+ | choose (addr : Word w)
+ | copy (src : CopySource w) (dest : Word w)
+
+/-- Test whether this schedule item consumes a nondeterministic bit choice. -/
+def Item.owns : Item w → Bool
+ | .choose _ => true
+ | _ => false
+
+/-- The exact choice stream for one item, a singleton for a choice and empty for a skip or
+copy. -/
+def Item.bits (op : Item w) (b : Bool) : List Bool := if op.owns then [b] else []
+
+/-- Events and successor cursor for the scheduled action on the supplied memory and choice bit. -/
+def Item.report (op : Item w) (bitWord : Bool → Word w) (next : Word w) (m : Memory w)
+ (b : Bool) : Report w :=
+ match op with
+ | .skip => ⟨[], some next⟩
+ | .choose a => cellReport true a next bitWord b
+ | .copy src dst => copyReport src dst next m
+
+/-- External memory after a skip, a write of an encoded choice bit, or a copy from the
+indicated source. -/
+def Item.memory (op : Item w) (bitWord : Bool → Word w) (m : Memory w) (b : Bool) : Memory w :=
+ match op with
+ | .skip => m
+ | .choose a => writeMemory m a (bitWord b)
+ | .copy src dst => writeMemory m dst (CopySource.get m src)
+
+@[simp] theorem Item.report_result (op : Item w) (bitWord : Bool → Word w) (next : Word w)
+ (m : Memory w) (b : Bool) : (op.report bitWord next m b).result = some next := by
+ cases op <;> rfl
+
+@[simp] theorem Item.after_report (op : Item w) (bitWord : Bool → Word w) (next : Word w)
+ (m : Memory w) (b : Bool) : after m (op.report bitWord next m b).events = op.memory bitWord m b := by
+ cases op with
+ | skip | choose => rfl
+ | copy src dst => exact after_copyReport src dst next m
+
+theorem Item.report_probes (op : Item w) (bitWord : Bool → Word w) (next : Word w)
+ (m : Memory w) (b : Bool) : (op.report bitWord next m b).probes ≤ 2 := by
+ cases op with
+ | skip | choose => simp [Item.report, Report.probes, cellReport, countProbes]
+ | copy src dst => cases src <;> simp [Item.report, Report.probes, copyReport, countProbes]
+
+/-- Represent a schedule position up to and including the terminal position as a word, using
+the bound on the entire schedule. -/
+def cursor (fit : M < 2^w) (k : ℕ) (hk : k ≤ M) : Word w := ⟨k, hk.trans_lt fit⟩
+
+/-- Cursor returned after executing the item at index `i`, representing position `i + 1`. -/
+def successor (fit : M < 2^w) (i : Fin M) : Word w := cursor fit (i.val+1) i.isLt
+
+/-- Control states of the scheduled input machine for visiting an item, writing its word,
+returning the next cursor, halting or rejecting an invalid cursor. -/
+inductive Dispatch (w : ℕ)
+ | visit (op : Item w) (next : Word w)
+ | write (addr value next : Word w)
+ | finish (next : Word w)
+ | halt
+ | invalid
+
+/-- Execute one schedule item per burst call, branch at each bit choice, and halt when the
+persistent cursor reaches the item count. -/
+def scheduledProgram (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w) :
+ Program w (Dispatch w) where
+ start s := if h : s.val < M then .visit (ops ⟨s.val, h⟩) (successor fit ⟨s.val,h⟩)
+ else if s.val = M then .halt else .invalid
+ step
+ | .visit .skip next => .finish (some next)
+ | .visit (.choose a) next => .branch (fun b ↦ .write a (bitWord b) next)
+ | .visit (.copy (.literal v) dst) next => .write dst v (.finish next)
+ | .visit (.copy (.fetch a) dst) next => .read a (fun v ↦ .write dst v next)
+ | .write a v next => .write a v (.finish next)
+ | .finish next => .finish (some next)
+ | .halt => .finish none
+ | .invalid => .reject
+
+/-- Terminal schedule report with an empty trace and no successor cursor. -/
+def haltReport (w : ℕ) : Report w := ⟨[], none⟩
+
+/-- Reports of a schedule on the designated branch bits, evaluating each fetch against
+memory after the preceding call. The final halt is separate. -/
+def scheduledReports (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w)
+ (f : Fin M → Bool) : List (Fin M) → Memory w → List (Report w)
+ | [], _ => []
+ | i :: xs, m => (ops i).report bitWord (successor fit i) m (f i) ::
+ scheduledReports ops bitWord fit f xs ((ops i).memory bitWord m (f i))
+
+@[simp] theorem start_item (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w)
+ (i : Fin M) : (scheduledProgram ops bitWord fit).start (cursor fit i.val i.isLt.le) =
+ .visit (ops i) (successor fit i) := by simp [scheduledProgram, cursor, i.isLt]
+
+@[simp] theorem start_halt (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w) :
+ (scheduledProgram ops bitWord fit).start (cursor fit M le_rfl) = .halt := by
+ simp [scheduledProgram, cursor]
+
+theorem execute_item (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w)
+ (op : Item w) (next : Word w) (m : Memory w) (b : Bool) :
+ execute (scheduledProgram ops bitWord fit) 3 (.visit op next) m (op.bits b) =
+ some (op.report bitWord next m b) := by
+ cases op with
+ | skip | choose => rfl
+ | copy src dst => cases src <;> rfl
+
+/-- A successful data call consumes one bit precisely at a choice instruction. -/
+theorem execute_item_only (ops : Fin M → Item w) (bitWord : Bool → Word w) (fit : M < 2^w)
+ (op : Item w) (next : Word w) (m : Memory w) (bs : List Bool) (r : Report w)
+ (h : execute (scheduledProgram ops bitWord fit) 3 (.visit op next) m bs = some r) :
+ ∃ b, bs = op.bits b ∧ r = op.report bitWord next m b := by
+ cases op with
+ | skip =>
+ cases bs with
+ | nil => exact ⟨false, rfl, (Option.some.inj h).symm⟩
+ | cons => contradiction
+ | choose a =>
+ cases bs with
+ | nil => contradiction
+ | cons b bs => cases bs with
+ | nil => exact ⟨b, rfl, (Option.some.inj h).symm⟩
+ | cons => contradiction
+ | copy src dst =>
+ cases bs with
+ | nil => cases src <;> exact ⟨false, rfl, (Option.some.inj h).symm⟩
+ | cons => cases src <;> contradiction
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMTranscript.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMTranscript.lean
new file mode 100644
index 0000000000..d99dfccbff
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMTranscript.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.RAMSharedFields
+import Mathlib.Tactic.FinCases
+
+/-!
+# Addressing internal transcript bits for the paired-group counter
+
+Section 11 of *VP and VNP differ over every field* chooses each internal
+directed-message bit at its sending endpoint. The second pass reads this
+bit at either endpoint, while the two absent successor ports return zero.
+The scratch location is the sender site and the sender's local input offset.
+This address calculation uses only public indices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open RAMLayout
+
+variable {d H w : ℕ}
+
+/-- Compute the designated sending endpoint, using only the slot indices. -/
+def sourcePort : Endpoint d H w → Option (Endpoint d H w)
+ | (v, .inl (dir, j)) =>
+ if dir = 0 then
+ if v.val + 1 < 2 ^ d then some (v, .inl (0, j)) else none
+ else
+ if 0 < v.val then some (⟨v.val - 1, by omega⟩, .inl (0, j)) else none
+ | (v, .inr (l, dir, j)) =>
+ some (if dir = 0 then v else l.partner v, .inr (l, 0, j))
+
+theorem sourcePort_eq_source (x : Endpoint d H w) : sourcePort x = source x := by
+ rcases x with ⟨v, ⟨dir, j⟩ | ⟨l, dir, j⟩⟩ <;> fin_cases dir
+ · by_cases hv : v.val + 1 < 2 ^ d <;> simp [sourcePort, source, peer, direction, hv]
+ · by_cases hv : 0 < v.val <;> simp [sourcePort, source, peer, direction, hv]
+ · rfl
+ · rfl
+
+/-- The first pass chooses one bit at each actual successor or sorting send. -/
+def designated : Endpoint d H w → Bool
+ | (v, .inl (dir, _)) => decide (dir = 0 ∧ v.val + 1 < 2 ^ d)
+ | (_, .inr (_, dir, _)) => decide (dir = 0)
+
+theorem designated_iff (x : Endpoint d H w) : designated x = true ↔ IsSend x := by
+ rcases x with ⟨v, ⟨dir, j⟩ | ⟨l, dir, j⟩⟩ <;> fin_cases dir
+ · by_cases hv : v.val + 1 < 2 ^ d <;> simp [designated, IsSend, direction, peer, hv]
+ · simp [designated, IsSend, direction]
+ · simp [designated, IsSend, direction, peer]
+ · simp [designated, IsSend, direction]
+
+/-- The bit-choice domain of the first pass is exactly the primed transcript's
+shared-bit domain. -/
+def designatedEquiv (d H w : ℕ) : {x : Endpoint d H w // designated x = true} ≃ SharedBit d H w :=
+ Equiv.subtypeEquivRight designated_iff
+
+theorem sourcePort_eq_self_iff (x : Endpoint d H w) :
+ sourcePort x = some x ↔ designated x = true := by
+ rw [sourcePort_eq_source, designated_iff]
+ refine ⟨source_shared, ?_⟩
+ rintro ⟨hd, hp⟩
+ cases h : peer x.1 x.2 with
+ | none => simp [h] at hp
+ | some y => simp [source, h, hd]
+
+/-- Every lookup that finds a sender terminates there. -/
+theorem sourcePort_idempotent {x y : Endpoint d H w} (h : sourcePort x = some y) :
+ sourcePort y = some y :=
+ (sourcePort_eq_self_iff y).mpr ((designated_iff y).mpr
+ (source_shared ((sourcePort_eq_source x).symm.trans h)))
+
+/-- Rectangular scratch coordinates within one of the two groups. -/
+abbrev Address (d H w : ℕ) := Fin (2 ^ d) × Fin (width d H w)
+
+/-- Identify a transcript endpoint with its site index and its local bit offset in the
+rectangular scratch array. -/
+def portAddress (d H w : ℕ) : Endpoint d H w ≃ Address d H w :=
+ (Equiv.refl _).prodCongr (offset d H w)
+
+/-- In the first pass only designated cells are assigned a choice bit. -/
+def scratchBits (bits : SharedBit d H w → Bool) (a : Address d H w) : Bool :=
+ let x := (portAddress d H w).symm a
+ if h : designated x = true then bits ((designatedEquiv d H w) ⟨x, h⟩) else false
+
+/-- In the second pass every connected port makes one scratch read.
+A missing connection returns zero without reading the scratch array. -/
+def readPort (bits : SharedBit d H w → Bool) (x : Endpoint d H w) : Bool :=
+ ((sourcePort x).map (fun y ↦ scratchBits bits (portAddress d H w y))).getD false
+
+theorem scratchBits_designated (bits : SharedBit d H w → Bool) (x : SharedBit d H w) :
+ scratchBits bits (portAddress d H w x.val) = bits x := by
+ simp [scratchBits, (designated_iff x.val).mpr x.property, designatedEquiv]
+ rfl
+
+/-- Reading a primed endpoint supplies exactly the bit obtained by identifying
+its transcript ports, for every assignment of sends. -/
+theorem readPort_eq_assignment (bits : SharedBit d H w → Bool) (x : Endpoint d H w) :
+ readPort bits x = ((assignmentEquiv d H w) bits).val x := by
+ unfold readPort
+ rw [sourcePort_eq_source]
+ change _ = ((source x).map _).getD false
+ cases h : source x with
+ | none => rfl
+ | some y =>
+ have hy := source_shared h
+ exact (scratchBits_designated bits ⟨y, hy⟩).trans (by
+ change bits ⟨y, hy⟩ = if h' : IsSend y then bits ⟨y, h'⟩ else false
+ rw [dite_eq_left hy])
+
+/-- Correctness at a linear incident-input offset. No message parser
+participates in this read. -/
+theorem readPort_eq_incident (bits : SharedBit d H w → Bool) (v : Fin (2 ^ d))
+ (k : Fin (width d H w)) :
+ readPort bits (v, (offset d H w).symm k) =
+ incidentBits (sendArraysEquiv d H w bits) v k := by
+ rw [readPort_eq_assignment]
+ simp [incidentBits, incidentEquiv]
+
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedInputRAMUniform.lean b/lean/OAI/Computability/VPVNP/PrimedInputRAMUniform.lean
new file mode 100644
index 0000000000..8f0ce68ccc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedInputRAMUniform.lean
@@ -0,0 +1,220 @@
+import OAI.Computability.VPVNP.PrimedInputRAMRunEquiv
+
+/-!
+# A single burst-RAM program for both primed input passes
+
+The first half of the public cursor range enumerates the designated scratch writes.
+The second half enumerates all output writes, using the memory left by the first
+half. The final halt contributes one extra unit to the calls-plus-probes bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedInputRAM
+
+open BurstRAM
+
+variable {N w : ℕ}
+
+/-- Public data for the two passes, indexed by the rectangular tape positions. -/
+structure TwoPass (N w : ℕ) where
+ /-- Indicate which rectangular positions choose a shared bit in the first pass. -/
+ own : Fin N → Bool
+ /-- Distinct scratch address for each rectangular position, used for the first-pass choice
+ writes. -/
+ scratch : Fin N ↪ Word w
+ /-- Distinct output address for each rectangular position assembled in the second pass. -/
+ dest : Fin N ↪ Word w
+ /-- Literal word or memory address supplying the second-pass copy at each position. -/
+ source : Fin N → CopySource w
+
+namespace TwoPass
+
+variable (T : TwoPass N w)
+
+/-- The cursor visits both full arrays in order. -/
+def ops : Fin (N+N) → Item w :=
+ Fin.append (fun i ↦ if T.own i then .choose (T.scratch i) else .skip)
+ (fun i ↦ .copy (T.source i) (T.dest i))
+
+@[simp] theorem owns_first (i : Fin N) : (T.ops (Fin.castAdd N i)).owns = T.own i := by
+ cases h : T.own i <;> simp [ops, h, Item.owns]
+
+theorem owns_second (i : Fin N) : (T.ops (Fin.natAdd N i)).owns = false := by
+ rw [ops, Fin.append_right]
+ rfl
+
+@[simp] theorem owns_addNat (i : Fin N) : (T.ops (i.addNat N)).owns = false := by
+ simpa only [Fin.natAdd_eq_addNat] using T.owns_second i
+
+/-- Owners are exactly the original designated cells, at their first-pass cursors. -/
+def assignmentEquiv : Assignment T.own ≃ Assignment (fun i ↦ (T.ops i).owns) where
+ toFun f i := Fin.append (bitAt f) (fun _ ↦ false) i.val
+ invFun g i := g ⟨Fin.castAdd N i.val, by simp [i.property]⟩
+ left_inv f := by funext i; simp [bitAt, i.property]
+ right_inv g := by
+ funext ⟨i, hi⟩
+ cases i using Fin.addCases with
+ | left i => simp [bitAt, (T.owns_first i).symm.trans hi]
+ | right i => exact Bool.noConfusion ((T.owns_second i).symm.trans hi)
+
+@[simp] theorem bitAt_first (f : Assignment T.own) (i : Fin N) :
+ bitAt (T.assignmentEquiv f) (Fin.castAdd N i) = bitAt f i := by
+ cases h : T.own i <;> simp [assignmentEquiv, bitAt, h]
+
+private theorem finRange_halves :
+ List.finRange (N + N) =
+ (List.finRange N).map (Fin.castAdd N) ++ (List.finRange N).map (Fin.natAdd N) := by
+ change List.ofFn (id : Fin (N + N) → _) = _
+ rw [List.ofFn_add]
+ simp only [List.ofFn_eq_map, id_eq]
+ rfl
+
+private theorem first_reports_append (bitWord : Bool → Word w) (fit : N+N < 2^w)
+ (g : Fin (N+N) → Bool) (cells : List (Fin N)) (tail : List (Fin (N+N))) (m : Memory w) :
+ scheduledReports T.ops bitWord fit g (cells.map (Fin.castAdd N) ++ tail) m =
+ reports T.own T.scratch (successor fit ∘ Fin.castAdd N) bitWord
+ (g ∘ Fin.castAdd N) cells ++
+ scheduledReports T.ops bitWord fit g tail
+ (store T.scratch (bitWord ∘ g ∘ Fin.castAdd N) (cells.filter T.own) m) := by
+ induction cells generalizing m with
+ | nil => simp [reports, store]
+ | cons i cells ih =>
+ cases h : T.own i <;>
+ simp [scheduledReports, reports, ops, h, Item.report, Item.memory, cellReport,
+ store, Function.comp_def] at ih ⊢ <;> exact ih _
+
+private theorem second_reports (bitWord : Bool → Word w) (fit : N+N < 2^w)
+ (g : Fin (N+N) → Bool) (cells : List (Fin N)) (m : Memory w) :
+ scheduledReports T.ops bitWord fit g (cells.map (Fin.natAdd N)) m =
+ copyReports T.dest T.source (successor fit ∘ Fin.natAdd N) cells m := by
+ induction cells generalizing m with
+ | nil => rfl
+ | cons i cells ih =>
+ simp only [List.map_cons, scheduledReports, copyReports, ops, Fin.append_right, Item.report,
+ Item.memory, Function.comp_apply]
+ exact congrArg (_ :: ·) (ih _)
+
+/-- Native data-call reports coincide with the first-pass and second-pass reports,
+including all fetched values after the scratch writes. -/
+theorem reports_split (bitWord : Bool → Word w) (fit : N+N < 2^w)
+ (f : Assignment T.own) (m : Memory w) :
+ scheduledReports T.ops bitWord fit (bitAt (T.assignmentEquiv f)) (List.finRange _) m =
+ reports T.own T.scratch (successor fit ∘ Fin.castAdd N) bitWord (bitAt f) (List.finRange N) ++
+ copyReports T.dest T.source (successor fit ∘ Fin.natAdd N) (List.finRange N)
+ (store T.scratch (bitWord ∘ bitAt f) (owners T.own) m) := by
+ rw [finRange_halves, first_reports_append, second_reports]
+ simp only [Function.comp_def, bitAt_first, owners]
+
+/-- Full report list, including the explicit halt after the copies. -/
+def completeReports (bitWord : Bool → Word w) (fit : N+N < 2^w)
+ (f : Assignment T.own) (m : Memory w) : List (Report w) :=
+ scheduledReports T.ops bitWord fit (bitAt (T.assignmentEquiv f)) (List.finRange _) m ++ [haltReport w]
+
+/-- Replaying the genuine RAM events produces the original two-pass memory. -/
+theorem after_completeReports (bitWord : Bool → Word w) (fit : N+N < 2^w)
+ (f : Assignment T.own) (m : Memory w) :
+ after m (eventLog (T.completeReports bitWord fit f m)) =
+ secondPass T.dest T.source (store T.scratch (bitWord ∘ bitAt f) (owners T.own) m) := by
+ rw [completeReports, reports_split]
+ simp only [eventLog, List.flatMap_append, List.flatMap_cons, haltReport, List.flatMap_nil,
+ List.append_nil]
+ rw [show ∀ xs ys : List (Event w), after m (xs ++ ys) = after (after m xs) ys by simp [after]]
+ simp only [List.flatMap_def, after_reports, after_copyReports, secondPass, owners]
+
+/-- One call and at most one write at each first-pass position, one call and at most
+two probes per copy, and one final halt. -/
+theorem completeReports_cost_le (bitWord : Bool → Word w) (fit : N+N < 2^w)
+ (f : Assignment T.own) (m : Memory w) :
+ RAMBuckets.cost Report.probes (T.completeReports bitWord fit f m) ≤ 5*N + 1 := by
+ rw [completeReports, reports_split, RAMBuckets.cost_append, RAMBuckets.cost_append, reports_cost]
+ have h := copyReports_cost_le T.dest T.source (successor fit ∘ Fin.natAdd N) (List.finRange N)
+ (store T.scratch (bitWord ∘ bitAt f) (owners T.own) m)
+ have hs := owners_length_le T.own
+ rw [owners] at hs
+ simp only [List.length_finRange, RAMBuckets.cost, haltReport, Report.probes, countProbes] at h ⊢
+ omega
+
+/-- Memory at the terminal cursor, before the explicit halt. This is the memory
+available for a subsequent computation on the assembled tapes. -/
+theorem scheduledMemory_eq (bitWord : Bool → Word w) (fit : N+N < 2^w)
+ (f : Assignment T.own) (m : Memory w) :
+ scheduledMemory T.ops bitWord (bitAt (T.assignmentEquiv f)) (List.finRange _) m =
+ secondPass T.dest T.source (store T.scratch (bitWord ∘ bitAt f) (owners T.own) m) := by
+ rw [← after_scheduledReports T.ops bitWord fit]
+ simpa only [completeReports, eventLog, List.flatMap_append, List.flatMap_cons,
+ List.flatMap_nil, haltReport, List.append_nil] using T.after_completeReports bitWord fit f m
+
+/-- Flattening the per-call histories recovers the original first-pass choice
+stream in the order of the designated cells. -/
+theorem flatten_assignmentCalls (f : Assignment T.own) :
+ (assignmentCalls T.ops (T.assignmentEquiv f)).flatten = branches f := by
+ have first (cells : List (Fin N)) :
+ (cells.flatMap fun i ↦ (T.ops (Fin.castAdd N i)).bits
+ (bitAt (T.assignmentEquiv f) (Fin.castAdd N i))) = (cells.filter T.own).map (bitAt f) := by
+ induction cells with
+ | nil => rfl
+ | cons i cells ih =>
+ rw [List.flatMap_cons, ih]
+ cases h : T.own i <;> simp [Item.bits, h]
+ have second (cells : List (Fin N)) :
+ (cells.flatMap fun i ↦ (T.ops (Fin.natAdd N i)).bits
+ (bitAt (T.assignmentEquiv f) (Fin.natAdd N i))) = [] := by
+ induction cells with
+ | nil => rfl
+ | cons i cells ih =>
+ rw [List.flatMap_cons, ih]
+ simp only [Item.bits, owns_second, Bool.false_eq_true, ↓reduceIte, List.nil_append]
+ rw [assignmentCalls, finRange_halves]
+ simp only [List.map_append, List.flatten_append, List.flatten_cons, List.flatten_nil,
+ List.append_nil, List.map_map, ← List.flatMap_def, Function.comp_def, first, second, branches,
+ owners]
+
+/-- A completed two-pass run on a branch assignment computes exactly its reports. -/
+theorem run_completeReports (bitWord : Bool → Word w) (fit : N+N < 2^w)
+ (f : Assignment T.own) (m : Memory w) :
+ runSegment (scheduledProgram T.ops bitWord fit) 3 (some 0) m
+ (assignmentCalls T.ops (T.assignmentEquiv f)) = some (T.completeReports bitWord fit f m) :=
+ run_generated T.ops bitWord fit (bitAt (T.assignmentEquiv f)) m
+
+/-- The cap depends only on the number of cells, uniformly over bit assignments,
+memory contents, and the number of fetches among the second-pass cells. -/
+theorem scheduledCost_le (bitWord : Bool → Word w) (fit : N+N < 2^w) (m : Memory w) :
+ scheduledCost T.ops ≤ 5*N + 1 := by
+ let f : Assignment T.own := fun _ ↦ false
+ rw [← generated_cost T.ops bitWord fit (bitAt (T.assignmentEquiv f)) m]
+ exact T.completeReports_cost_le bitWord fit f m
+
+theorem withinCaps_completeReports (bitWord : Bool → Word w) (fit : N+N < 2^w)
+ (f : Assignment T.own) (m : Memory w) {S H : ℕ} (hH : 3 ≤ H) (hTotal : 5*N+1 ≤ S*H) :
+ withinCaps S H (T.completeReports bitWord fit f m) :=
+ scheduledReports_withinCaps T.ops bitWord fit (bitAt (T.assignmentEquiv f)) m hH
+ ((T.scheduledCost_le bitWord fit m).trans hTotal)
+
+/-- Bounded accepting paths of the single program enumerate precisely the original
+designated-cell assignments, also when two branches encode the same memory word. -/
+def actualPathEquiv (bitWord : Bool → Word w) (fit : N+N < 2^w) (m : Memory w)
+ {S H : ℕ} (hH : 3 ≤ H) (hTotal : 5*N+1 ≤ S*H) :
+ ActualPaths (scheduledProgram T.ops bitWord fit) 3 0 m (withinCaps S H) ≃ Assignment T.own :=
+ (scheduledPathEquivWithinCaps T.ops bitWord fit m hH
+ ((T.scheduledCost_le bitWord fit m).trans hTotal)).trans T.assignmentEquiv.symm
+
+/-- For the assignment recovered from any accepted native path, the computed report
+list is the canonical one with its observed choices and memory reads. -/
+theorem run_actualPath (bitWord : Bool → Word w) (fit : N+N < 2^w) (m : Memory w)
+ {S H : ℕ} (hH : 3 ≤ H) (hTotal : 5*N+1 ≤ S*H)
+ (p : ActualPaths (scheduledProgram T.ops bitWord fit) 3 0 m (withinCaps S H)) :
+ runSegment (scheduledProgram T.ops bitWord fit) 3 (some 0) m p.val =
+ some (T.completeReports bitWord fit (T.actualPathEquiv bitWord fit m hH hTotal p) m) := by
+ obtain ⟨f, rfl⟩ := (T.actualPathEquiv bitWord fit m hH hTotal).symm.surjective p
+ rw [Equiv.apply_symm_apply]
+ exact T.run_completeReports bitWord fit f m
+
+end TwoPass
+end PrimedInputRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedScheduleRAM.lean b/lean/OAI/Computability/VPVNP/PrimedScheduleRAM.lean
new file mode 100644
index 0000000000..fc13fa0f57
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedScheduleRAM.lean
@@ -0,0 +1,175 @@
+import OAI.Computability.VPVNP.RAMSuccessor
+
+/-!
+# Composing successive calls of the primed coefficient counter
+
+Each item of the two input scans, the site parses, and the final comparisons
+has a fixed absolute call number. The machine passes that number in its
+persistent word. The only possible successful execution on prescribed header
+memory therefore has exactly one list of choices per item, and carries the
+actual external memory through all phases.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedSchedule
+
+open BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- Encode the absolute call index as the persistent width-`w` word. -/
+def cursor (w i : ℕ) : Word w := Fin.ofNat _ i
+
+@[simp] theorem cursor_value {i : ℕ} (h : i < 2^w) : (cursor w i).val = i := Nat.mod_eq_of_lt h
+
+/-- A running call at item `i`, and the unique accepted state at the end. -/
+def control (w U i : ℕ) : Option (Word w) := if i < U then some (cursor w i) else none
+
+/-- Semantics of a scheduled counter call. Given its absolute index, incoming memory and choice
+stream, it returns a report on success. -/
+abbrev Item (w : ℕ) := ℕ → Memory w → List Bool → Option (Report w)
+
+/-- Independent per-item semantics, with reports recording the actual reads
+and writes. A supplied choice list after the last item is rejected. -/
+def runItems (item : Item w) (U : ℕ) : ℕ → Memory w → List (List Bool) → Option (List (Report w))
+ | _, _, [] => some []
+ | i, m, b :: bs =>
+ if i < U then
+ match item i m b with
+ | none => none
+ | some r => (runItems item U (i+1) (after m r.events) bs).map (r :: ·)
+ else none
+
+/-- What the opcode proof for each phase must establish. Invariants may depend
+on the cursor and the memory, so this applies to the parse stack, leaf marks,
+and cumulative histogram throughout the counter. -/
+structure ScheduleSpec (P : Program w C) (fuel U : ℕ) (item : Item w) (inv : ℕ → Memory w → Prop) : Prop where
+ call_eq : ∀ i < U, ∀ m, inv i m → ∀ b,
+ execute P fuel (P.start (cursor w i)) m b = item i m b
+ progress : ∀ i < U, ∀ m, inv i m → ∀ b r, item i m b = some r →
+ r.result = control w U (i+1) ∧ inv (i+1) (after m r.events)
+
+/-- The actual reset-private-memory run computes the same reports as the
+composition of the item semantics. -/
+theorem native_eq_runItems {P : Program w C} {fuel U : ℕ} {item : Item w} {inv}
+ (hs : ScheduleSpec P fuel U item inv) (i : ℕ) (m : Memory w) (hi : inv i m)
+ (bs : List (List Bool)) :
+ runSegment P fuel (control w U i) m bs = runItems item U i m bs := by
+ induction bs generalizing i m with
+ | nil => rfl
+ | cons b bs ih =>
+ by_cases h : i < U
+ · simp only [control, h, ↓reduceIte, runSegment, runItems, hs.call_eq i h m hi]
+ cases he : item i m b with
+ | none => rfl
+ | some r =>
+ obtain ⟨hr, hm⟩ := hs.progress i h m hi _ _ he
+ dsimp only
+ rw [hr, ih (i+1) _ hm]
+ · simp [control, runSegment, runItems, h]
+
+/-- At a successful partial run the next cursor and the number of consumed
+choice lists agree, so splitting a sequence into individual items is unique. -/
+theorem runItems_progress {P : Program w C} {fuel U : ℕ} {item : Item w} {inv}
+ (hs : ScheduleSpec P fuel U item inv) (i : ℕ) (m : Memory w) (hi : inv i m) (hbound : i ≤ U)
+ {bs : List (List Bool)} {rs : List (Report w)} (hr : runItems item U i m bs = some rs) :
+ rs.length = bs.length ∧ i + bs.length ≤ U ∧
+ endState (control w U i) rs = control w U (i+bs.length) := by
+ induction bs generalizing i m rs with
+ | nil => simp [runItems] at hr; subst rs; simp [endState, hbound]
+ | cons b bs ih =>
+ by_cases h : i < U
+ · simp only [runItems, h, ↓reduceIte] at hr
+ cases he : item i m b with
+ | none => simp [he] at hr
+ | some r =>
+ simp only [he, Option.map_eq_some_iff] at hr
+ obtain ⟨rs, ht, rfl⟩ := hr
+ obtain ⟨hresult, hmem⟩ := hs.progress i h m hi _ _ he
+ obtain ⟨hlen, hcap, hstate⟩ := ih (i+1) _ hmem h ht
+ simp only [List.length_cons, endState, hresult, hlen]
+ rw [hstate]
+ exact ⟨trivial, by omega, by congr 1; omega⟩
+ · simp [runItems, h] at hr
+
+/-- Reports of adjacent phases compose with exact transfer of persistent
+state, external memory, and branch lists. -/
+theorem runSegment_append (P : Program w C) (fuel : ℕ) (s : Option (Word w)) (m : Memory w)
+ (bs cs : List (List Bool)) :
+ runSegment P fuel s m (bs++cs) =
+ (runSegment P fuel s m bs).bind fun rs =>
+ (runSegment P fuel (endState s rs) (after m (eventLog rs)) cs).map (rs++·) := by
+ induction bs generalizing s m with
+ | nil => simp [runSegment, endState, after, eventLog]
+ | cons b bs ih =>
+ cases s with
+ | none => rfl
+ | some s =>
+ simp only [List.cons_append, runSegment]
+ cases hx : execute P fuel (P.start s) m b with
+ | none => rfl
+ | some r =>
+ dsimp only
+ rw [ih]
+ cases hy : runSegment P fuel r.result (after m r.events) bs with
+ | none => rfl
+ | some rs =>
+ simp only [Option.bind_some, Option.map_some, eventLog, List.flatMap_cons, endState,
+ after, List.foldl_append, List.cons_append]
+ cases runSegment P fuel (endState r.result rs)
+ ((List.flatMap Report.events rs).foldl update (r.events.foldl update m)) cs <;> rfl
+
+/-- One exact branch list per scheduled item, including a possibly empty
+list for deterministic input scans or final comparisons. -/
+abbrev Choices (item : Item w) (U : ℕ) (m : Memory w) (cap : List (Report w) → Prop) :=
+ {b : Fin U → List Bool // ∃ rs, runItems item U 0 m (List.ofFn b) = some rs ∧ cap rs}
+
+private theorem initial_control {U : ℕ} (hU : 0 < U) : control w U 0 = some (cursor w 0) := by
+ simp [control, hU]
+
+private theorem actual_length {P : Program w C} {fuel U : ℕ} {item : Item w} {inv}
+ (hs : ScheduleSpec P fuel U item inv) (hU : 0 < U) (m : Memory w) (hi : inv 0 m)
+ (cap : List (Report w) → Prop) (b : ActualPaths P fuel (cursor w 0) m cap) : b.val.length = U := by
+ obtain ⟨rs, hr, hhalt, _⟩ := b.property
+ have he := native_eq_runItems hs 0 m hi b.val
+ rw [initial_control hU] at he
+ have hr := he.symm.trans hr
+ obtain ⟨_, hle, hstate⟩ := runItems_progress hs _ _ hi (Nat.zero_le _) hr
+ rw [initial_control hU, hhalt, Nat.zero_add] at hstate
+ have hge : U ≤ b.val.length := by
+ by_contra! h
+ simp [control, h] at hstate
+ omega
+
+/-- Native accepting paths of the assembled machine and the fixed-index
+per-item choices count the same executions. -/
+def nativeScheduleEquiv {P : Program w C} {fuel U : ℕ} {item : Item w} {inv}
+ (hs : ScheduleSpec P fuel U item inv) (hU : 0 < U) (m : Memory w) (hi : inv 0 m)
+ (cap : List (Report w) → Prop) : ActualPaths P fuel (cursor w 0) m cap ≃ Choices item U m cap where
+ toFun b := ⟨fun i => b.val[i.val]'(by rw [actual_length hs hU m hi cap b]; exact i.isLt), by
+ have hbs : List.ofFn (fun i : Fin U => b.val[i.val]'(by rw [actual_length hs hU m hi cap b]; exact i.isLt))
+ = b.val := List.ext_getElem (by rw [List.length_ofFn, actual_length hs hU m hi cap b])
+ (by intros; simp)
+ obtain ⟨rs, hr, _, hc⟩ := b.property
+ rw [hbs, ← native_eq_runItems hs _ _ hi, initial_control hU]
+ exact ⟨rs, hr, hc⟩⟩
+ invFun b := ⟨List.ofFn b.val, by
+ obtain ⟨rs, hr, hc⟩ := b.property
+ obtain ⟨_, _, hs'⟩ := runItems_progress hs _ _ hi (Nat.zero_le _) hr
+ simp only [Nat.zero_add, List.length_ofFn, control, hU, ↓reduceIte, Nat.lt_irrefl] at hs'
+ have he := native_eq_runItems hs 0 m hi (List.ofFn b.val)
+ rw [initial_control hU] at he
+ exact ⟨rs, he.trans hr, hs', hc⟩⟩
+ left_inv b := by
+ apply Subtype.ext
+ exact List.ext_getElem (by rw [List.length_ofFn, actual_length hs hU m hi cap b]) (by intros; simp)
+ right_inv b := by apply Subtype.ext; funext i; simp
+
+end PrimedSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAM.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAM.lean
new file mode 100644
index 0000000000..1b2ef0dca0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAM.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.PrimedStackRAMCode
+import OAI.Computability.VPVNP.PrimedStackRAMLayout
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Constant-probe instructions for the primed parser
+
+Registers 0 and 1 hold the current degree minus one and nonterminal state.
+Register 2 holds a chosen location or split. Registers 3 and 4 hold child
+states, 5 is the offset of the input row, 6 is the selected bit, and 7 is the
+dense production index. The remaining registers are private temporaries.
+
+Public words 0 through 4 are the degree-plane, state-plane, mark, histogram and
+depth addresses. Words 5, 6, 7 are the stack capacity, number of positions and
+number of states. Words 8, 9, 10 are the input base, terminal-label count and
+total label count. These are public parameters of a fixed instruction table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM BurstRAM.PrivateRAM
+
+/-- One straight-line instruction for the primed parser, with sixteen registers and eleven
+public words. -/
+abbrev Line := Op 16 11
+
+/-- Push the frame in registers 0 and 1. The pointer records the next free slot. -/
+def push : List Line :=
+ [.publicWord 9 4, .read 8 9, .publicWord 11 5, .guardLt 8 11,
+ .publicWord 11 0, .binary .add 11 11 8, .write 11 0,
+ .publicWord 11 1, .binary .add 11 11 8, .write 11 1,
+ .constant 10 1, .binary .add 8 8 10, .write 9 8]
+
+/-- Pop the most recently pushed frame into registers 0 and 1. -/
+def pop : List Line :=
+ [.publicWord 9 4, .read 8 9, .constant 12 0, .guardLt 12 8,
+ .constant 10 1, .binary .sub 8 8 10, .write 9 8,
+ .publicWord 11 0, .binary .add 11 11 8, .read 0 11,
+ .publicWord 11 1, .binary .add 11 11 8, .read 1 11]
+
+/-- Reject a repeated leaf and mark its position otherwise. -/
+def mark : List Line :=
+ [.publicWord 11 6, .guardLt 2 11, .publicWord 9 2, .binary .add 9 9 2,
+ .read 14 9, .constant 12 0, .guardEq 14 12, .constant 10 1, .write 9 10]
+
+/-- Clear the indicated mark while preparing a fresh site. -/
+def clearMark : List Line :=
+ [.publicWord 11 6, .guardLt 2 11, .publicWord 9 2, .binary .add 9 9 2,
+ .constant 12 0, .write 9 12]
+
+/-- Fetch one bit of the assembled input row. -/
+def leafBit : List Line :=
+ [.publicWord 11 6, .guardLt 2 11, .publicWord 9 8, .binary .add 9 9 5,
+ .binary .add 9 9 2, .read 6 9, .constant 13 2, .guardLt 6 13]
+
+/-- Increment the word for a production. Reject an out-of-range label or a wrapped count. -/
+def increment : List Line :=
+ [.publicWord 11 10, .guardLt 7 11, .publicWord 9 3, .binary .add 9 9 7,
+ .read 14 9, .constant 10 1, .binary .add 15 14 10, .guardLt 14 15, .write 9 15]
+
+/-- Private arithmetic for the terminal production (state, position, bit). -/
+def terminalIndex : List Line :=
+ [.publicWord 11 6, .binary .mul 7 1 11, .binary .add 7 7 2,
+ .constant 13 2, .binary .mul 7 7 13, .binary .add 7 7 6]
+
+/-- Private arithmetic for the ordered binary production. Degree is positive
+on entry, so its triangular prefix is degree times (degree minus one) divided by two. -/
+def binaryIndex : List Line :=
+ [.constant 10 1, .binary .sub 7 0 10, .binary .mul 7 7 0, .constant 13 2,
+ .binary .div 7 7 13, .binary .add 7 7 2, .publicWord 11 7,
+ .binary .mul 7 7 11, .binary .add 7 7 1, .binary .mul 7 7 11,
+ .binary .add 7 7 3, .binary .mul 7 7 11, .binary .add 7 7 4,
+ .publicWord 11 9, .binary .add 7 7 11]
+
+variable {w : ℕ} (pub : Fin 11 → Word w) (state : Word w) (regs : Regs w 16) (mem : Memory w)
+
+/-- The written degree, state and depth are exactly the three payloads of a push. -/
+theorem push_spec (h : mem (pub 4).val < pub 5) :
+ let depth := mem (pub 4).val
+ let m' := writeMemory (writeMemory (writeMemory mem (pub 0 + depth) (regs 0))
+ (pub 1 + depth) (regs 1)) (pub 4) (depth + 1)
+ ∃ es rs, trace pub state push regs mem = some (es, rs, m') ∧
+ countProbes es = 4 ∧ es.length = 13 ∧ rs 0 = regs 0 ∧ rs 1 = regs 1 := by
+ simp (config := { decide := true }) [push, trace, Op.effect, BinaryOp.eval, h, Function.update,
+ countProbes]
+ rfl
+
+theorem push_full (h : ¬mem (pub 4).val < pub 5) : trace pub state push regs mem = none := by
+ simp (config := { decide := true }) [push, trace, Op.effect, h, Function.update]
+
+/-- Popping reads the words at the previous top and decreases the depth. -/
+theorem pop_spec (h : 0 < mem (pub 4).val) :
+ let top := mem (pub 4).val - 1
+ let m' := writeMemory mem (pub 4) top
+ ∃ es rs, trace pub state pop regs mem = some (es, rs, m') ∧
+ countProbes es = 4 ∧ es.length = 13 ∧ rs 0 = m' (pub 0 + top).val ∧
+ rs 1 = m' (pub 1 + top).val := by
+ simp (config := { decide := true }) [pop, trace, Op.effect, BinaryOp.eval, h, Function.update,
+ countProbes]
+ exact ⟨rfl, rfl, rfl⟩
+
+theorem pop_empty (h : mem (pub 4).val = 0) : trace pub state pop regs mem = none := by
+ simp (config := { decide := true }) [pop, trace, Op.effect, h, Function.update]
+
+/-- The distinct-position test succeeds exactly on an unused position in range. -/
+theorem mark_spec (h : regs 2 < pub 6) (hnew : mem (pub 2 + regs 2).val = 0) :
+ ∃ es rs, trace pub state mark regs mem = some (es, rs, writeMemory mem (pub 2 + regs 2) 1) ∧
+ countProbes es = 2 ∧ es.length = 9 ∧ rs 2 = regs 2 := by
+ simp (config := { decide := true }) [mark, trace, Op.effect, BinaryOp.eval, h, hnew,
+ Function.update, countProbes]
+ rfl
+
+theorem mark_reject (h : ¬regs 2 < pub 6 ∨ mem (pub 2 + regs 2).val ≠ 0) :
+ trace pub state mark regs mem = none := by
+ rcases h with h | h
+ · simp (config := { decide := true }) [mark, trace, Op.effect, Function.update, h]
+ · by_cases hi : regs 2 < pub 6 <;>
+ simp (config := { decide := true }) [mark, trace, Op.effect, BinaryOp.eval, Function.update, hi, h]
+
+theorem clearMark_spec (h : regs 2 < pub 6) :
+ ∃ es rs, trace pub state clearMark regs mem = some (es, rs, writeMemory mem (pub 2 + regs 2) 0) ∧
+ countProbes es = 1 ∧ es.length = 6 := by
+ simp (config := { decide := true }) [clearMark, trace, Op.effect, BinaryOp.eval, h,
+ Function.update, countProbes]
+
+theorem leafBit_spec (h : regs 2 < pub 6) (hbit : mem (pub 8 + regs 5 + regs 2).val < 2) :
+ ∃ es rs, trace pub state leafBit regs mem = some (es, rs, mem) ∧
+ countProbes es = 1 ∧ es.length = 8 ∧ rs 6 = mem (pub 8 + regs 5 + regs 2).val := by
+ simp (config := { decide := true }) [leafBit, trace, Op.effect, BinaryOp.eval, h, hbit,
+ Function.update, countProbes]
+
+theorem increment_spec (h : regs 7 < pub 10) (hcount : (mem (pub 3 + regs 7).val).val + 1 < 2^w) :
+ let a := pub 3 + regs 7
+ ∃ es rs, trace pub state increment regs mem = some (es, rs, writeMemory mem a (mem a.val + 1)) ∧
+ countProbes es = 2 ∧ es.length = 9 ∧ (mem a.val + 1 : Word w).val = (mem a.val).val + 1 := by
+ let v := mem (pub 3 + regs 7).val
+ have he : (v + 1).val = v.val + 1 := Fin.val_add_one_of_lt' hcount
+ have hlt : v < v + 1 := by change v.val < (v+1).val; omega
+ change mem (pub 3 + regs 7).val < mem (pub 3 + regs 7).val + Fin.ofNat (2^w) 1 at hlt
+ simp at hlt
+ change (mem (pub 3 + regs 7).val + 1 : Word w).val = _ at he
+ simp (config := { decide := true }) [increment, trace, Op.effect, BinaryOp.eval, h, hlt, he,
+ Function.update, countProbes]
+ exact ⟨rfl, rfl⟩
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMBinaryVisit.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMBinaryVisit.lean
new file mode 100644
index 0000000000..ad55d7482b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMBinaryVisit.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.PrimedStackRAMLeafVisit
+
+/-!
+# Internal visits of the primed counter
+
+The range guards precede the counter update. An accepted internal choice
+adds the dense binary production once and pushes the ordered children on
+the external stack. All marks and all assembled input bits remain available.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM PrimedCounter ParseGrammar
+open scoped Fin.CommRing Classical
+
+variable {base R n m H w : ℕ} {x : Fin 2 → Fin R → Fin m → Bool}
+variable {st : VisitState n m H} {mem : Memory w}
+
+private theorem push_holds (hr : Holds base x st mem) (state : Word w) (regs : Regs w 16)
+ (d : Fin n) (h : Fin H) (hd : regs 0 = (d.val : Word w)) (hh : regs 1 = (h.val : Word w))
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hc : st.pending.length < n) :
+ ∃ es rs m', trace (publicData w base R n m H) state push regs mem = some (es,rs,m') ∧
+ Holds base x {st with pending := (d,h)::st.pending} m' ∧ countProbes es = 4 := by
+ have hlen : (frames w st.pending).length < n := by simpa [frames] using hc
+ obtain ⟨es,rs,m',ht,hp,hs⟩ := push_rep state regs hr.pending hf hlen
+ rw [hd,hh] at hs
+ exact ⟨es,rs,m',ht,hr.withStack _ (push_data hr.pending hf hlen ht) hs,hp⟩
+
+private theorem pushChildren_holds (hr : Holds base x st mem) (state : Word w) (regs : Regs w 16)
+ (d : Fin n) (b : Fin d.val) (i j : Fin H) (hd : (regs 0).val = d.val)
+ (hb : (regs 2).val = b.val) (hi : (regs 3).val = i.val) (hj : (regs 4).val = j.val)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hH : H < 2^w)
+ (hcap : st.pending.length + 2 ≤ n) :
+ ∃ es rs m', trace (publicData w base R n m H) state pushChildren regs mem = some (es,rs,m') ∧
+ Holds base x {st with pending := (leftDegree d b,i)::(rightDegree d b,j)::st.pending} m' ∧
+ countProbes es = 8 := by
+ let pub := publicData w base R n m H
+ have hB : regs 2 < regs 0 := by change (regs 2).val < (regs 0).val; simp [hb,hd]
+ have hI : regs 3 < pub 7 := by
+ change (regs 3).val < (H : Word w).val
+ simp [hi,Fin.val_natCast,Nat.mod_eq_of_lt hH]
+ have hJ : regs 4 < pub 7 := by
+ change (regs 4).val < (H : Word w).val
+ simp [hj,Fin.val_natCast,Nat.mod_eq_of_lt hH]
+ obtain ⟨es₀,rs₀,h₀,p₀,_,hd₀,hs₀⟩ := rightFrame_spec pub state regs mem hB hI hJ
+ have hdRight : rs₀ 0 = ((rightDegree d b).val : Word w) := by
+ rw [hd₀, ← (child_degrees d b _ _ hd hb).2, Fin.cast_val_eq_self]
+ have hhRight : rs₀ 1 = (j.val : Word w) := by rw [hs₀, ← hj, Fin.cast_val_eq_self]
+ obtain ⟨es₁,rs₁,m₁,h₁,hr₁,p₁⟩ := push_holds hr state rs₀ (rightDegree d b) j hdRight hhRight hf (by omega)
+ obtain ⟨es₂,rs₂,h₂,p₂,_,hd₂,hs₂⟩ := leftFrame_spec pub state rs₁ m₁
+ have same (u : Fin 16) (hu : u = 2 ∨ u = 3) : rs₁ u = regs u := by
+ have hu₁ : ∀ op ∈ push, op.destination ≠ some u := by rcases hu with rfl | rfl <;> decide
+ have hu₀ : ∀ op ∈ rightFrame, op.destination ≠ some u := by rcases hu with rfl | rfl <;> decide
+ exact (trace_preserves hu₁ h₁).trans (trace_preserves hu₀ h₀)
+ have hdLeft : rs₂ 0 = ((leftDegree d b).val : Word w) := by
+ rw [hd₂, same 2 (Or.inl rfl), ← (child_degrees d b _ _ hd hb).1, Fin.cast_val_eq_self]
+ have hhLeft : rs₂ 1 = (i.val : Word w) := by rw [hs₂, same 3 (Or.inr rfl), ← hi, Fin.cast_val_eq_self]
+ obtain ⟨es₃,rs₃,m₃,h₃,hr₃,p₃⟩ := push_holds hr₁ state rs₂ (leftDegree d b) i hdLeft hhLeft hf (by simp; omega)
+ refine ⟨es₀ ++ (es₁ ++ (es₂ ++ es₃)),rs₃,m₃,?_,hr₃,?_⟩
+ · change trace pub state pushChildren regs mem = _
+ rw [pushChildren, trace_append, h₀]
+ simp only [Option.bind_some]
+ rw [trace_append, h₁]
+ simp only [Option.bind_some]
+ rw [trace_append, h₂]
+ simp only [Option.bind_some]
+ rw [h₃]
+ rfl
+ · simp [probes_append,p₀,p₁,p₂,p₃]
+
+theorem binaryLines_valid (hr : Holds base x st mem) (state : Word w) (regs : Regs w 16)
+ (d : Fin n) (b : Fin d.val) (h i j : Fin H) (hd : (regs 0).val = d.val)
+ (hh : regs 1 = (h.val : Word w)) (hb : (regs 2).val = b.val)
+ (hi : (regs 3).val = i.val) (hj : (regs 4).val = j.val)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hH : H < 2^w) (hw : 2 < 2^w)
+ (hprod : (d.val-1)*d.val < 2^w) (hcap : st.pending.length + 2 ≤ n)
+ (hcount : st.counts (.inr ⟨d,h,b,i,j⟩) + 1 < 2^w) :
+ let a : Label n m (Fin H) := .inr ⟨d,h,b,i,j⟩
+ ∃ es rs m', trace (publicData w base R n m H) state binaryLines regs mem = some (es,rs,m') ∧
+ Holds base x ⟨(leftDegree d b,i)::(rightDegree d b,j)::st.pending, st.marked,
+ st.counts + Finsupp.single a 1⟩ m' ∧ countProbes es = 10 := by
+ let pub := publicData w base R n m H
+ let a : Label n m (Fin H) := .inr ⟨d,h,b,i,j⟩
+ let ix := labelIndex n m H a
+ have hB : regs 2 < regs 0 := by change (regs 2).val < (regs 0).val; simp [hb,hd]
+ have hI : regs 3 < pub 7 := by
+ change (regs 3).val < (H : Word w).val
+ simp [hi,Fin.val_natCast,Nat.mod_eq_of_lt hH]
+ have hJ : regs 4 < pub 7 := by
+ change (regs 4).val < (H : Word w).val
+ simp [hj,Fin.val_natCast,Nat.mod_eq_of_lt hH]
+ have ht₀ : trace pub state binaryChecks regs mem = some (List.replicate 4 .tick, Function.update regs 11 (pub 7), mem) := by
+ simp (config := {decide := true}) [binaryChecks,trace,Op.effect,Function.update,hB,hI,hJ]
+ let rs₀ := Function.update regs 11 (pub 7)
+ have same₀ (u : Fin 16) (hu : u < 5) : rs₀ u = regs u := Function.update_of_ne (by omega) _ _
+ have hT : labelCount n m H ≤ 2^w := by unfold size at hf; omega
+ obtain ⟨es₁,rs₁,ht₁,hc₁,_,he₁⟩ := binaryIndex_spec pub state rs₀ mem d b h i j rfl rfl
+ ((congrArg Fin.val (same₀ 0 (by decide))).trans hd) ((same₀ 1 (by decide)).trans hh)
+ (by rw [same₀ 2 (by decide), ← hb, Fin.cast_val_eq_self])
+ (by rw [same₀ 3 (by decide), ← hi, Fin.cast_val_eq_self])
+ (by rw [same₀ 4 (by decide), ← hj, Fin.cast_val_eq_self]) hw hprod hT
+ have hv : rs₁ 7 = (ix.val : Word w) := by change rs₁ 7 = (↑((labelIndex n m H _).val) : Word w); rw [← he₁, Fin.cast_val_eq_self]
+ obtain ⟨es₂,rs₂,ht₂,hc₂⟩ := increment_cell mem state rs₁ ix hv hf ((hr.counts a) ▸ hcount)
+ have hr₂ := hr.increment a hf hcount
+ have same₂ (u : Fin 16) (hu : u < 5) : rs₂ u = regs u := by
+ have ha : ∀ op ∈ increment, op.destination ≠ some u := by
+ fin_cases u <;> first | decide | contradiction
+ have hb' : ∀ op ∈ binaryIndex, op.destination ≠ some u := by
+ fin_cases u <;> first | decide | contradiction
+ exact (trace_preserves ha ht₂).trans ((trace_preserves hb' ht₁).trans (same₀ u hu))
+ obtain ⟨es₃,rs₃,m₃,ht₃,hr₃,hc₃⟩ := pushChildren_holds hr₂ state rs₂ d b i j
+ ((congrArg Fin.val (same₂ 0 (by decide))).trans hd)
+ ((congrArg Fin.val (same₂ 2 (by decide))).trans hb)
+ ((congrArg Fin.val (same₂ 3 (by decide))).trans hi)
+ ((congrArg Fin.val (same₂ 4 (by decide))).trans hj) hf hH hcap
+ refine ⟨((List.replicate 4 .tick ++ es₁) ++ es₂) ++ es₃,rs₃,m₃,?_,hr₃,?_⟩
+ · change trace pub state binaryLines regs mem = _
+ simp [binaryLines, trace_append, ht₀, ht₁, ht₂, rs₀, pub]
+ exact ht₃
+ · simp [probes_append,hc₁,hc₂,hc₃,countProbes]
+
+theorem binaryLines_reject (pub : Fin 11 → Word w) (state : Word w) (regs : Regs w 16) (m' : Memory w)
+ (bad : ¬regs 2 < regs 0 ∨ ¬regs 3 < pub 7 ∨ ¬regs 4 < pub 7) :
+ trace pub state binaryLines regs m' = none := by
+ have hguard : trace pub state binaryChecks regs m' = none := by
+ by_cases hb : regs 2 < regs 0
+ · by_cases hi : regs 3 < pub 7
+ · have hj := (bad.resolve_left (not_not_intro hb)).resolve_left (not_not_intro hi)
+ simp (config := { decide := true }) [binaryChecks, trace, Op.effect, Function.update, hb, hi, hj]
+ · simp (config := { decide := true }) [binaryChecks, trace, Op.effect, Function.update, hb, hi]
+ · simp [binaryChecks, trace, Op.effect, hb]
+ rw [binaryLines, trace_append, trace_append, trace_append, hguard]
+ rfl
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMChildren.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMChildren.lean
new file mode 100644
index 0000000000..ca44050539
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMChildren.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.PrimedStackRAMMemory
+
+/-!
+# Pushing two pending subtrees
+
+The word code validates a chosen split and both child states, then pushes the
+right child followed by the left child. The next pop therefore visits the left
+subtree. Both pushes use the same external depth word and two frame planes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM
+open scoped Fin.CommRing
+
+/-- Check the chosen split and state words, then form the right child in registers 0 and 1. -/
+def rightFrame : List Line :=
+ [.guardLt 2 0, .publicWord 11 7, .guardLt 3 11, .guardLt 4 11,
+ .constant 10 1, .binary .sub 0 0 10, .binary .sub 0 0 2, .copy 1 4]
+
+/-- Form the left child from the retained split and left-state words. -/
+def leftFrame : List Line := [.copy 0 2, .copy 1 3]
+
+/-- Check the split and child states, then push the right frame followed by the left frame so
+that preorder traversal pops the left child first. -/
+def pushChildren : List Line := rightFrame ++ (push ++ (leftFrame ++ push))
+
+variable {w : ℕ}
+
+private theorem count_append (es fs : List (Event w)) :
+ countProbes (es ++ fs) = countProbes es + countProbes fs := by
+ induction es with
+ | nil => simp [countProbes]
+ | cons e es ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+theorem rightFrame_spec (pub : Fin 11 → Word w) (state : Word w) (regs : Regs w 16) (mem : Memory w)
+ (hb : regs 2 < regs 0) (hi : regs 3 < pub 7) (hj : regs 4 < pub 7) :
+ ∃ es rs, trace pub state rightFrame regs mem = some (es, rs, mem) ∧
+ countProbes es = 0 ∧ es.length = 8 ∧ rs 0 = regs 0 - 1 - regs 2 ∧ rs 1 = regs 4 := by
+ simp (config := { decide := true }) [rightFrame, trace, Op.effect, BurstRAM.PrivateRAM.BinaryOp.eval,
+ Function.update, hb, hi, hj, countProbes]
+
+theorem rightFrame_reject (pub : Fin 11 → Word w) (state : Word w) (regs : Regs w 16) (mem : Memory w)
+ (bad : ¬regs 2 < regs 0 ∨ ¬regs 3 < pub 7 ∨ ¬regs 4 < pub 7) :
+ trace pub state rightFrame regs mem = none := by
+ by_cases hb : regs 2 < regs 0
+ · by_cases hi : regs 3 < pub 7
+ · have hj := (bad.resolve_left (not_not_intro hb)).resolve_left (not_not_intro hi)
+ simp (config := { decide := true }) [rightFrame, trace, Op.effect, Function.update, hb, hi, hj]
+ · simp (config := { decide := true }) [rightFrame, trace, Op.effect, Function.update, hb, hi]
+ · simp [rightFrame, trace, Op.effect, hb]
+
+theorem leftFrame_spec (pub : Fin 11 → Word w) (state : Word w) (regs : Regs w 16) (mem : Memory w) :
+ ∃ es rs, trace pub state leftFrame regs mem = some (es, rs, mem) ∧
+ countProbes es = 0 ∧ es.length = 2 ∧ rs 0 = regs 2 ∧ rs 1 = regs 3 := by
+ simp (config := { decide := true }) [leftFrame, trace, Op.effect, Function.update, countProbes]
+
+/-- The abstract stack after the genuine two pushes, including the eight external probes. -/
+theorem pushChildren_rep {base R n m H : ℕ} {mem : Memory w} {stack : List (Word w × Word w)}
+ (state : Word w) (regs : Regs w 16)
+ (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem stack)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hc : stack.length+2 ≤ n)
+ (hb : regs 2 < regs 0) (hi : regs 3 < publicData w base R n m H 7)
+ (hj : regs 4 < publicData w base R n m H 7) :
+ ∃ es rs mem', trace (publicData w base R n m H) state pushChildren regs mem = some (es, rs, mem') ∧
+ countProbes es = 8 ∧ Represents (R := R) (n := n) (m := m) (H := H) base mem'
+ ((regs 2, regs 3) :: (regs 0-1-regs 2, regs 4) :: stack) := by
+ let pub := publicData w base R n m H
+ obtain ⟨es₀, rs₀, h₀, p₀, _, hd₀, hs₀⟩ := rightFrame_spec pub state regs mem hb hi hj
+ obtain ⟨es₁, rs₁, m₁, h₁, p₁, hr₁⟩ := push_rep state rs₀ hr hf (by omega)
+ obtain ⟨es₂, rs₂, h₂, p₂, _, hd₂, hs₂⟩ := leftFrame_spec pub state rs₁ m₁
+ obtain ⟨es₃, rs₃, m₃, h₃, p₃, hr₃⟩ := push_rep state rs₂ hr₁ hf (by simp; omega)
+ have unchanged (j : Fin 16) (h : j = 2 ∨ j = 3) : rs₁ j = regs j := by
+ have hpres (ops : List Line) (hops : ops = push ∨ ops = rightFrame) :
+ ∀ op ∈ ops, op.destination ≠ some j := by
+ rcases hops with rfl | rfl
+ · rcases h with rfl | rfl <;> simp (config := { decide := true })
+ · rcases h with rfl | rfl <;> simp (config := { decide := true })
+ exact (trace_preserves (hpres push (Or.inl rfl)) h₁).trans
+ (trace_preserves (hpres rightFrame (Or.inr rfl)) h₀)
+ rw [hd₀, hs₀, hd₂, hs₂, unchanged 2 (Or.inl rfl), unchanged 3 (Or.inr rfl)] at hr₃
+ refine ⟨es₀ ++ (es₁ ++ (es₂ ++ es₃)), rs₃, m₃, ?_, ?_, hr₃⟩
+ · change trace pub state pushChildren regs mem = _
+ rw [pushChildren, trace_append, h₀]
+ simp only [Option.bind_some]
+ rw [trace_append, h₁]
+ simp only [Option.bind_some]
+ rw [trace_append, h₂]
+ simp only [Option.bind_some]
+ rw [h₃]
+ rfl
+ · simp [count_append, p₀, p₁, p₂, p₃]
+
+/-- For a legal split the two computed degree words are precisely the
+integer left and right degrees. In particular subtraction does not wrap. -/
+theorem child_degrees {n : ℕ} (d : Fin n) (b : Fin d.val) (deg split : Word w)
+ (hd : deg.val = d.val) (hb : split.val = b.val) :
+ split.val = (ParseGrammar.leftDegree d b).val ∧
+ (deg-1-split).val = (ParseGrammar.rightDegree d b).val := by
+ have hz : deg ≠ 0 := by
+ intro he
+ rw [he] at hd
+ have := b.isLt
+ simp at hd
+ omega
+ have hs : split ≤ deg-1 := by
+ change split.val ≤ (deg-1).val
+ rw [Fin.val_sub_one_of_ne_zero hz, hd, hb]
+ have := b.isLt
+ omega
+ exact ⟨hb, by rw [Fin.sub_val_of_le hs, Fin.val_sub_one_of_ne_zero hz, hd, hb]; rfl⟩
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMChoices.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMChoices.lean
new file mode 100644
index 0000000000..fb9cc49a5f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMChoices.lean
@@ -0,0 +1,185 @@
+import OAI.Computability.VPVNP.PrimedStackRAMBinaryVisit
+
+/-!
+# Complete word choices at a parser node
+
+The private RAM consumes one word at a terminal and three at an internal node.
+A call cannot accept with unused choices. Separating this exact-length check
+from the range checks identifies the same choice streams as the mathematical
+token decoder, including truncated and overlong streams.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM PrimedCounter
+open scoped Fin.CommRing
+
+variable {w n m H : ℕ}
+
+/-- Words guessed at one parser node before checking their bounds. A leaf carries a position,
+and a binary node carries a split and two child states. -/
+inductive RawChoice (w : ℕ)
+ | leaf (v : Word w)
+ | binary (b i j : Word w)
+
+/-- Decode the entire branch tape as one width-`w` position word for a leaf or three width-`w`
+words for a binary node. Return `none` for a truncated tape or leftover bits. -/
+def exactChoice (w : ℕ) (leaf : Bool) (bits : List Bool) : Option (RawChoice w) := do
+ let (b,tail) ← takeWord w bits
+ if leaf then
+ if tail.isEmpty then return .leaf b else none
+ else
+ let (i,tail) ← takeWord w tail
+ let (j,tail) ← takeWord w tail
+ if tail.isEmpty then return .binary b i j else none
+
+/-- Convert a raw choice to a grammar token by checking the leaf position against `m` or the
+binary split against `d` and both child states against `H`. -/
+def RawChoice.token (d m H : ℕ) : RawChoice w → Option (Token m (Fin H))
+ | .leaf j => if h : j.val < m then some (.terminal ⟨j.val,h⟩) else none
+ | .binary b i j => if b.val < d then
+ if hi : i.val < H then if hj : j.val < H then some (.binary b.val ⟨i.val,hi⟩ ⟨j.val,hj⟩) else none
+ else none
+ else none
+
+theorem readToken_eq_choice (d : ℕ) (bits : List Bool) :
+ readToken w m H d bits =
+ (exactChoice w (decide (d = 0)) bits).bind (RawChoice.token d m H) := by
+ cases h₀ : takeWord w bits with
+ | none => by_cases h : d = 0 <;> simp [readToken, exactChoice, takeBounded, h, h₀]
+ | some a =>
+ obtain ⟨b,t₀⟩ := a
+ by_cases hd : d = 0
+ · by_cases hb : b.val < m <;> cases t₀ <;>
+ simp [readToken, exactChoice, RawChoice.token, takeBounded, h₀, hd, hb]
+ · cases h₁ : takeWord w t₀ with
+ | none => by_cases hb : b.val < d <;> simp [readToken, exactChoice, takeBounded, hd, hb, h₀, h₁]
+ | some a =>
+ obtain ⟨i,t₁⟩ := a
+ cases h₂ : takeWord w t₁ with
+ | none =>
+ by_cases hb : b.val < d <;> by_cases hi : i.val < H <;>
+ simp [readToken, exactChoice, takeBounded, hd, hb, hi, h₀, h₁, h₂]
+ | some a =>
+ obtain ⟨j,t₂⟩ := a
+ by_cases hb : b.val < d <;> by_cases hi : i.val < H <;> by_cases hj : j.val < H <;>
+ cases t₂ <;> simp [readToken, exactChoice, RawChoice.token, takeBounded, hd, hb, hi, hj, h₀, h₁, h₂]
+
+/-- Test whether the raw node choice consists of a single leaf-position word. -/
+def RawChoice.isLeaf : RawChoice w → Bool
+ | .leaf _ => true
+ | .binary .. => false
+
+theorem exactChoice_kind (w : ℕ) (leaf : Bool) (bits : List Bool) (c : RawChoice w)
+ (h : exactChoice w leaf bits = some c) : c.isLeaf = leaf := by
+ cases leaf with
+ | true =>
+ simp only [exactChoice, bind, Option.bind_eq_some_iff, ite_true] at h
+ obtain ⟨⟨v,t⟩,_,h⟩ := h
+ cases t <;> simp_all [RawChoice.isLeaf]
+ subst c
+ rfl
+ | false =>
+ simp only [exactChoice, bind, Option.bind_eq_some_iff, Bool.false_eq_true, ite_false] at h
+ obtain ⟨⟨b,t⟩,_,⟨i,u⟩,_,⟨j,z⟩,_,h⟩ := h
+ cases z <;> simp_all [RawChoice.isLeaf]
+ subst c
+ rfl
+
+/-- The outgoing call state, requiring the branch tape to be consumed exactly. -/
+def completeNode (pub : Fin 11 → Word w) (state : Word w) (regs : Regs w 16)
+ (mem : Memory w) (bits : List Bool) : Option (Output w 16) :=
+ (nodeKernel pub state regs mem bits).filter fun o => o.bits.isEmpty
+
+/-- Store the guessed word in the first register of the supplied embedding and clear the other
+two registers used by the word reader. -/
+def setGuess (reg : Fin 3 ↪ Fin 16) (rs : Regs w 16) (v : Word w) := GuessWord.resultRegs reg rs v
+
+/-- Register file after the node guesses. Register 2 holds the leaf position or split, and
+binary nodes also place the left and right states in registers 3 and 4. -/
+def choiceRegs (rs : Regs w 16) : RawChoice w → Regs w 16
+ | .leaf j => setGuess (guessRegs 2 (by decide) (by decide)) rs j
+ | .binary b i j =>
+ let rs := setGuess (guessRegs 2 (by decide) (by decide)) rs b
+ let rs := setGuess (guessRegs 3 (by decide) (by decide)) rs i
+ setGuess (guessRegs 4 (by decide) (by decide)) rs j
+
+/-- Select the leaf or binary instruction block that processes the guessed words after the
+stack pop. -/
+def RawChoice.lines : RawChoice w → List Line
+ | .leaf _ => leafLines
+ | .binary .. => binaryLines
+
+/-- Private word-reader trace for the leaf position or, at a binary node, the concatenated
+traces for the split, left state, and right state. -/
+def RawChoice.events : RawChoice w → List (Event w)
+ | .leaf v => GuessWord.trace v
+ | .binary b i j => GuessWord.trace b ++ (GuessWord.trace i ++ GuessWord.trace j)
+
+private theorem guess_no_probes (v : Word w) : countProbes (GuessWord.trace v) = 0 := by
+ have aux (bits : List Bool) : countProbes (GuessWord.events (w := w) bits) = 0 := by
+ induction bits with
+ | nil => rfl
+ | cons b bits ih => simpa [GuessWord.events, countProbes] using ih
+ simpa [GuessWord.trace, countProbes] using aux (wordBits v)
+
+theorem RawChoice.no_probes (c : RawChoice w) : countProbes c.events = 0 := by
+ cases c <;> simp [RawChoice.events, probes_append, guess_no_probes]
+
+/-- After the initial pop, the complete native node accepts exactly the decoded
+raw choice and then executes the corresponding leaf or internal block. -/
+theorem completeNode_pop (pub : Fin 11 → Word w) (st : Word w) (rs r₀ : Regs w 16)
+ (mem m₀ : Memory w) (es₀ : List (Event w)) (bits : List Bool)
+ (hp : trace pub st pop rs mem = some (es₀,r₀,m₀)) :
+ completeNode pub st rs mem bits =
+ (exactChoice w (decide (r₀ 0 = r₀ 12)) bits).bind fun c =>
+ (trace pub st c.lines (choiceRegs r₀ c) m₀).map fun (es,rs',m') =>
+ ⟨es₀ ++ (.tick :: (c.events ++ es)),rs',m',[]⟩ := by
+ cases h₀ : takeWord w bits with
+ | none =>
+ by_cases h : r₀ 0 = r₀ 12 <;>
+ simp [completeNode,nodeKernel,seqKernel,lineKernel,eqKernel,leafKernel,binaryKernel,
+ guessKernel,exactChoice,hp,h,h₀]
+ | some a =>
+ obtain ⟨b,t₀⟩ := a
+ by_cases h : r₀ 0 = r₀ 12
+ · let t := trace pub st leafLines (choiceRegs r₀ (.leaf b)) m₀
+ cases ht : t with
+ | none =>
+ cases t₀ <;> simp [completeNode,nodeKernel,seqKernel,lineKernel,eqKernel,leafKernel,guessKernel,
+ exactChoice,hp,h,h₀,RawChoice.lines,choiceRegs,setGuess,t] at ht ⊢ <;> simp [ht]
+ | some a =>
+ obtain ⟨es,r₁,m₁⟩ := a
+ cases t₀ <;> simp [completeNode,nodeKernel,seqKernel,lineKernel,eqKernel,leafKernel,guessKernel,
+ exactChoice,hp,h,h₀,RawChoice.lines,RawChoice.events,Output.prepend,choiceRegs,setGuess,t] at ht ⊢ <;>
+ simp [ht, Output.prepend]
+ · cases h₁ : takeWord w t₀ with
+ | none => simp [completeNode,nodeKernel,seqKernel,lineKernel,eqKernel,binaryKernel,guessKernel,exactChoice,
+ hp,h,h₀,h₁]
+ | some a =>
+ obtain ⟨i,t₁⟩ := a
+ cases h₂ : takeWord w t₁ with
+ | none => simp [completeNode,nodeKernel,seqKernel,lineKernel,eqKernel,binaryKernel,guessKernel,exactChoice,
+ hp,h,h₀,h₁,h₂]
+ | some a =>
+ obtain ⟨j,t₂⟩ := a
+ let t := trace pub st binaryLines (choiceRegs r₀ (.binary b i j)) m₀
+ cases ht : t with
+ | none =>
+ cases t₂ <;> simp [completeNode,nodeKernel,seqKernel,lineKernel,eqKernel,binaryKernel,guessKernel,
+ exactChoice,hp,h,h₀,h₁,h₂,RawChoice.lines,choiceRegs,setGuess,t] at ht ⊢ <;> simp [ht]
+ | some a =>
+ obtain ⟨es,r₁,m₁⟩ := a
+ cases t₂ <;> simp [completeNode,nodeKernel,seqKernel,lineKernel,eqKernel,binaryKernel,guessKernel,
+ exactChoice,hp,h,h₀,h₁,h₂,RawChoice.lines,RawChoice.events,Output.prepend,choiceRegs,setGuess,t] at ht ⊢ <;>
+ simp [ht,Output.prepend]
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMCode.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMCode.lean
new file mode 100644
index 0000000000..5222c55c7e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMCode.lean
@@ -0,0 +1,245 @@
+import OAI.Computability.VPVNP.RAMUniform
+
+/-!
+# Straight-line word code for the preorder counter
+
+Each operation emits one instruction of the finite burst machine. Guards jump to
+the program's reject instruction. The same block may occupy any prescribed
+sequence of program counters, so stack and counter operations can be inserted
+between the loops which read nondeterministic grammar choices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {p r k w : ℕ}
+
+/-- Operands of a straight-line instruction, with a two-bit literal format. -/
+inductive Op (r k : ℕ) where
+ | constant (dst : Fin r) (value : Word 2)
+ | publicWord (dst : Fin r) (i : Fin k)
+ | stateWord (dst : Fin r)
+ | copy (dst src : Fin r)
+ | binary (op : BinaryOp) (dst lhs rhs : Fin r)
+ | read (dst addr : Fin r)
+ | write (addr src : Fin r)
+ | guardEq (lhs rhs : Fin r)
+ | guardLt (lhs rhs : Fin r)
+
+/-- Translate one line using the successor and rejecting program counters. -/
+def Op.emit (next bad : Fin p) : Op r k → Instr 2 p r k
+ | .constant dst v => .constant dst v next
+ | .publicWord dst i => .publicWord dst i next
+ | .stateWord dst => .stateWord dst next
+ | .copy dst src => .copy dst src next
+ | .binary op dst x y => .binary op dst x y next
+ | .read dst a => .readExternal dst a next
+ | .write a s => .writeExternal a s next
+ | .guardEq x y => .jumpEq x y next bad
+ | .guardLt x y => .jumpLt x y next bad
+
+/-- Contents of the `r` private registers, each holding a width-`w` word. -/
+abbrev Regs (w r : ℕ) := Fin r → Word w
+/-- Continuation that takes the current register file and external memory and returns an
+optional burst report. -/
+abbrev Cont (w r : ℕ) := Regs w r → Memory w → Option (Report w)
+
+/-- Register, external-memory and event semantics of one line. -/
+def Op.effect (pub : Fin k → Word w) (state : Word w) (op : Op r k)
+ (regs : Regs w r) (mem : Memory w) : Option (Event w × Regs w r × Memory w) :=
+ match op with
+ | .constant dst v => some (.tick, Function.update regs dst (Fin.ofNat _ v.val), mem)
+ | .publicWord dst i => some (.tick, Function.update regs dst (pub i), mem)
+ | .stateWord dst => some (.tick, Function.update regs dst state, mem)
+ | .copy dst src => some (.tick, Function.update regs dst (regs src), mem)
+ | .binary op dst x y => some (.tick, Function.update regs dst (op.eval (regs x) (regs y)), mem)
+ | .read dst a =>
+ let v := mem (regs a).val
+ some (.read (regs a) v, Function.update regs dst v, mem)
+ | .write a s => some (.write (regs a) (regs s), regs, writeMemory mem (regs a) (regs s))
+ | .guardEq x y => if regs x = regs y then some (.tick, regs, mem) else none
+ | .guardLt x y => if regs x < regs y then some (.tick, regs, mem) else none
+
+/-- Execute one straight-line operation, pass the resulting registers and memory to the
+continuation, and prepend its event to a successful report. -/
+def Op.run (pub : Fin k → Word w) (state : Word w) (op : Op r k) (next : Cont w r) :
+ Cont w r := fun regs mem ↦ (op.effect pub state regs mem).bind fun (e, rs, m) =>
+ (next rs m).map (Report.prepend e)
+
+/-- Execute the straight-line block in list order before invoking the continuation with its
+final registers and memory. -/
+def run (ops : List (Op r k)) (pub : Fin k → Word w) (state : Word w) (next : Cont w r) :
+ Cont w r := ops.foldr (Op.run pub state) next
+
+theorem run_append (a b : List (Op r k)) (pub : Fin k → Word w) (state : Word w) (next : Cont w r) :
+ run (a ++ b) pub state next = run a pub state (run b pub state next) := by simp [run]
+
+/-- Evaluate a whole block, retaining the post-state for a subsequent block. -/
+def trace (pub : Fin k → Word w) (state : Word w) :
+ List (Op r k) → Regs w r → Memory w → Option (List (Event w) × Regs w r × Memory w)
+ | [], rs, m => some ([], rs, m)
+ | op :: rest, rs, m => do
+ let (e, rs, m) ← op.effect pub state rs m
+ let (es, rs, m) ← trace pub state rest rs m
+ return (e :: es, rs, m)
+
+theorem run_eq_trace (ops : List (Op r k)) (pub : Fin k → Word w) (state : Word w)
+ (next : Cont w r) (regs : Regs w r) (mem : Memory w) :
+ run ops pub state next regs mem =
+ (trace pub state ops regs mem).bind fun (es, rs, m) =>
+ (next rs m).map fun t => ⟨es ++ t.events, t.result⟩ := by
+ induction ops generalizing regs mem with
+ | nil => simp [run, trace]
+ | cons op ops ih =>
+ change op.run pub state (run ops pub state next) regs mem = _
+ cases he : op.effect pub state regs mem with
+ | none => simp [Op.run, trace, he]
+ | some a =>
+ obtain ⟨e, rs, m⟩ := a
+ cases ht : trace pub state ops rs m with
+ | none => simp [Op.run, trace, he, ih rs m, ht]
+ | some a =>
+ obtain ⟨es, rs', m'⟩ := a
+ cases hn : next rs' m' <;> simp [Op.run, trace, he, ih rs m, ht, hn, Report.prepend]
+
+/-- Concatenation runs the two blocks with the actual intermediate registers and memory. -/
+theorem trace_append (pub : Fin k → Word w) (state : Word w) (a b : List (Op r k))
+ (regs : Regs w r) (mem : Memory w) :
+ trace pub state (a ++ b) regs mem =
+ (trace pub state a regs mem).bind fun (es, rs, m) =>
+ (trace pub state b rs m).map fun (fs, rs', m') => (es ++ fs, rs', m') := by
+ induction a generalizing regs mem with
+ | nil => simp [trace]
+ | cons op a ih =>
+ cases he : op.effect pub state regs mem with
+ | none => simp [trace, he]
+ | some t =>
+ obtain ⟨e, rs, m⟩ := t
+ cases ht : trace pub state a rs m with
+ | none => simp [trace, he, ih, ht]
+ | some t =>
+ obtain ⟨es, rs', m'⟩ := t
+ cases hf : trace pub state b rs' m' <;> simp [trace, he, ih, ht, hf]
+
+/-- Registers available to surrounding blocks when no line names them as its destination. -/
+def Op.destination : Op r k → Option (Fin r)
+ | .constant i _ | .publicWord i _ | .stateWord i | .copy i _
+ | .binary _ i _ _ | .read i _ => some i
+ | .write .. | .guardEq .. | .guardLt .. => none
+
+theorem trace_preserves {pub : Fin k → Word w} {state : Word w} {ops : List (Op r k)}
+ {regs rs : Regs w r} {mem m : Memory w} {es : List (Event w)} {i : Fin r}
+ (hw : ∀ op ∈ ops, op.destination ≠ some i)
+ (ht : trace pub state ops regs mem = some (es, rs, m)) : rs i = regs i := by
+ induction ops generalizing regs mem es with
+ | nil => simp [trace] at ht; rw [ht.2.1]
+ | cons op ops ih =>
+ cases he : op.effect pub state regs mem with
+ | none => simp [trace, he] at ht
+ | some t =>
+ obtain ⟨e, r₁, m₁⟩ := t
+ cases hs : trace pub state ops r₁ m₁ with
+ | none => simp [trace, he, hs] at ht
+ | some t =>
+ obtain ⟨es', r₂, m₂⟩ := t
+ simp [trace, he, hs] at ht
+ obtain ⟨_, rfl, rfl⟩ := ht
+ rw [ih (fun a ha => hw a (List.mem_cons_of_mem _ ha)) hs]
+ have hd := hw op (List.mem_cons_self ..)
+ cases op <;> simp [Op.effect, Op.destination] at he hd
+ all_goals first
+ | exact congrFun he.2.1.symm i
+ | rw [← he.2.1]; exact Function.update_of_ne (Ne.symm hd) _ _
+ | exact congrFun he.2.2.1.symm i
+
+/-- Occurrence of a block inside a possibly larger, looping instruction table. -/
+inductive Contains (M : Machine w p r k) (bad : Fin p) : Fin p → List (Op r k) → Fin p → Prop
+ | nil (pc : Fin p) : Contains M bad pc [] pc
+ | cons {pc next stop op ops}
+ (head : M.code pc = (Op.emit next bad op).resize w)
+ (tail : Contains M bad next ops stop) : Contains M bad pc (op :: ops) stop
+
+private theorem execute_reject (M : Machine w p r k) (c : Config w p r) (mem : Memory w)
+ (bits : List Bool) (f : ℕ) (hb : M.code c.pc = .reject) :
+ execute M.program f c mem bits = none := by
+ cases f <;> simp [execute, Machine.program, hb, Instr.run]
+
+private theorem program_step (M : Machine w p r k) (c : Config w p r) :
+ M.program.step c = (M.code c.pc).run M.publicData c := rfl
+
+/-- Native execution consumes one instruction of fuel per line and agrees
+with the block semantics on registers, external memory and every event. -/
+theorem Contains.execute {M : Machine w p r k} {bad start stop : Fin p} {ops : List (Op r k)}
+ (h : Contains M bad start ops stop) (hb : M.code bad = .reject)
+ (state : Word w) (regs : Regs w r) (priv : Word w → Word w)
+ (mem : Memory w) (bits : List Bool) (f : ℕ) :
+ BurstRAM.execute M.program (f + ops.length) ⟨start, state, regs, priv⟩ mem bits =
+ run ops M.publicData state
+ (fun regs mem ↦ BurstRAM.execute M.program f ⟨stop, state, regs, priv⟩ mem bits) regs mem := by
+ induction h generalizing regs mem with
+ | nil => rfl
+ | @cons pc next stop op ops hhead htail ih =>
+ have hre : BurstRAM.execute M.program (f + ops.length) ⟨bad, state, regs, priv⟩ mem bits = none :=
+ execute_reject _ _ _ _ _ hb
+ cases op <;>
+ simp only [List.length_cons, BurstRAM.execute, program_step, hhead,
+ Op.emit, Instr.resize, Instr.run, Config.put, run, List.foldr_cons, Op.run, Op.effect, Option.bind_some]
+ all_goals first | exact congrArg (fun z => Option.map _ z) (ih _ _) | split <;> simp_all [run]
+
+/-- Compile a whole block into a fixed table with a return and a reject instruction. -/
+def template (ops : List (Op r k)) (result : Fin r) : Template (ops.length + 2) r k where
+ literalWidth := 2
+ entry := ⟨0, by omega⟩
+ code i := if hi : i.val < ops.length then
+ (ops[i.val]).emit ⟨i.val + 1, by omega⟩ ⟨ops.length + 1, by omega⟩
+ else if i.val = ops.length then .returnState result else .reject
+
+private theorem contains_indexed (M : Machine w p r k) (bad : Fin p) (ops : List (Op r k))
+ (pc : Fin (ops.length+1) → Fin p)
+ (hc : ∀ i : Fin ops.length, M.code (pc i.castSucc) =
+ (Op.emit (pc i.succ) bad ops[i.val]).resize w) :
+ Contains M bad (pc 0) ops (pc (Fin.last ops.length)) := by
+ induction ops with
+ | nil => exact .nil _
+ | cons o ops ih =>
+ apply Contains.cons (next := pc (⟨0, by simp⟩ : Fin (o :: ops).length).succ) (hc ⟨0, by simp⟩)
+ exact ih (fun i => pc i.succ) (fun i => hc i.succ)
+
+/-- The compiler places the complete block before its two terminal instructions. -/
+theorem template_contains (ops : List (Op r k)) (result : Fin r) (pub : Fin k → Word w) :
+ Contains ((template ops result).instantiate w pub) ⟨ops.length + 1, by omega⟩
+ ⟨0, by omega⟩ ops ⟨ops.length, by omega⟩ := by
+ apply contains_indexed _ _ ops (fun i => ⟨i.val, by have := i.isLt; omega⟩)
+ intro i
+ simp [template, Template.instantiate, i.isLt]
+
+/-- Start at the entry of the actual opcode table. Registers may be supplied
+by a preceding part of the same call. A standalone call supplies all zeros. -/
+theorem execute_template (ops : List (Op r k)) (result : Fin r) (pub : Fin k → Word w)
+ (state : Word w) (regs : Regs w r) (priv : Word w → Word w) (mem : Memory w) :
+ let M := (template ops result).instantiate w pub
+ BurstRAM.execute M.program (1 + ops.length) ⟨M.entry, state, regs, priv⟩ mem [] =
+ run ops pub state (fun rs _ => some ⟨[], some (rs result)⟩) regs mem := by
+ let M := (template ops result).instantiate w pub
+ have hb : M.code ⟨ops.length + 1, by omega⟩ = .reject := by
+ simp [M, template, Template.instantiate, Instr.resize, show ¬ops.length+1 < ops.length by omega]
+ have he := (template_contains ops result pub).execute hb state regs priv mem [] 1
+ have hret : M.code ⟨ops.length, by omega⟩ = .returnState result := by
+ simp [M, template, Template.instantiate, Instr.resize]
+ change _ = run ops M.publicData state _ regs mem
+ apply he.trans
+ congr 1
+ funext rs m
+ change BurstRAM.execute M.program 1 ⟨_, state, rs, priv⟩ m [] = _
+ simp [BurstRAM.execute, program_step, hret, Instr.run]
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMFootprint.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMFootprint.lean
new file mode 100644
index 0000000000..c0cb7911d0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMFootprint.lean
@@ -0,0 +1,205 @@
+import OAI.Computability.VPVNP.PrimedStackRAMNative
+
+/-!
+# Header preservation by the complete parser visit
+
+Successful scratch writes target the depth word, a guarded stack index, a
+guarded mark or a guarded production index. The header words below the
+rectangle, including the nominated histogram, are therefore available at
+their original addresses for the final comparison.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM
+open scoped Fin.CommRing
+
+variable {base R n m H w : ℕ}
+
+/-- Agreement of two external memories at every address strictly below the scratch base,
+including header words stored there. -/
+def Below (base : ℕ) (m₀ m₁ : Memory w) : Prop := ∀ a < base, m₁ a = m₀ a
+
+private theorem Below.trans {m₀ m₁ m₂ : Memory w} (h₀ : Below base m₀ m₁) (h₁ : Below base m₁ m₂) :
+ Below base m₀ m₂ := fun a ha => (h₁ a ha).trans (h₀ a ha)
+
+private theorem below_write (mem : Memory w) (v a : Word w) (h : base ≤ a.val) :
+ Below base mem (writeMemory mem a v) := by
+ intro b hb
+ simp [writeMemory, show b ≠ a.val by omega]
+
+private theorem cell_lower (c : Locations R n m H) (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ base ≤ (address base c : Word w).val := by
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt (address_lt hf c)]
+ exact Nat.le_add_right ..
+
+private structure Protects (base : ℕ) (pub : Fin 11 → Word w) (ops : List Line) : Prop where
+ run : ∀ {st rs mem es rs' m'}, trace pub st ops rs mem = some (es,rs',m') → Below base mem m'
+
+private theorem Protects.append {pub : Fin 11 → Word w} {xs ys : List Line}
+ (hx : Protects base pub xs) (hy : Protects base pub ys) : Protects base pub (xs ++ ys) := by
+ constructor
+ intro st rs mem es rs' m' ht
+ rw [trace_append] at ht
+ obtain ⟨⟨ea,ra,ma⟩,ha,h⟩ := Option.bind_eq_some_iff.mp ht
+ obtain ⟨⟨eb,rb,mb⟩,hb,he⟩ := Option.map_eq_some_iff.mp h
+ cases he
+ exact (hx.run ha).trans (hy.run hb)
+
+/-- The non-writing opcode blocks retain all external memory words. -/
+private theorem protects_readOnly {pub : Fin 11 → Word w} {ops : List Line}
+ (ho : ∀ op ∈ ops, ∀ a b, op ≠ .write a b) : Protects base pub ops := by
+ constructor
+ intro st rs mem es rs' m' ht
+ induction ops generalizing rs mem es with
+ | nil => simp [trace] at ht; rw [← ht.2.2]; exact fun _ _ => rfl
+ | cons op ops ih =>
+ cases he : op.effect pub st rs mem with
+ | none => simp [trace, he] at ht
+ | some t =>
+ obtain ⟨e,ra,ma⟩ := t
+ cases htail : trace pub st ops ra ma with
+ | none => simp [trace, he, htail] at ht
+ | some z =>
+ obtain ⟨eb,rb,mb⟩ := z
+ simp [trace, he, htail] at ht
+ obtain ⟨rfl,rfl,rfl⟩ := ht
+ have hm : ma = mem := by
+ cases op <;> simp [Op.effect] at he
+ all_goals first
+ | exact he.2.2.symm
+ | exact he.2.2.2.symm
+ | exact (ho _ (List.mem_cons_self ..) _ _ rfl).elim
+ subst ma
+ exact ih (fun a h => ho a (List.mem_cons_of_mem _ h)) htail
+
+private theorem pop_protects (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ Protects base (publicData w base R n m H) pop := by
+ let pub := publicData w base R n m H
+ constructor
+ intro st rs mem es rs' m' ht
+ by_cases hz : 0 < mem (pub 4).val
+ · obtain ⟨_,_,h,_⟩ := pop_spec pub st rs mem hz
+ have hm := congrArg (fun x : List (Event w) × Regs w 16 × Memory w => x.2.2) (Option.some.inj (ht.symm.trans h))
+ dsimp only at hm
+ rw [hm]
+ exact below_write _ _ _ (by rw [show (pub 4).val = _ from public_depth_val base hf]; exact Nat.le_add_right ..)
+ · have h := pop_empty pub st rs mem (le_antisymm (not_lt.mp hz) (Fin.zero_le _))
+ rw [ht] at h
+ contradiction
+
+private theorem push_protects (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ Protects base (publicData w base R n m H) push := by
+ let pub := publicData w base R n m H
+ constructor
+ intro st rs mem es rs' m' ht
+ by_cases hz : mem (pub 4).val < pub 5
+ · obtain ⟨_,_,h,_⟩ := push_spec pub st rs mem hz
+ have hm := congrArg (fun x : List (Event w) × Regs w 16 × Memory w => x.2.2) (Option.some.inj (ht.symm.trans h))
+ dsimp only at hm
+ rw [hm]
+ have hd : (mem (pub 4).val).val < n := by
+ change (mem _).val < (n : Word w).val at hz
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt (capacity_fit base hf)] using hz
+ let i : Fin n := ⟨(mem (pub 4).val).val,hd⟩
+ have hi : mem (pub 4).val = (i.val : Word w) := (Fin.cast_val_eq_self _).symm
+ have hd₀ : base ≤ (pub 0 + mem (pub 4).val).val := by
+ rw [hi, show pub 0 + (i.val : Word w) = _ from public_degree base i]
+ exact cell_lower _ hf
+ have hd₁ : base ≤ (pub 1 + mem (pub 4).val).val := by
+ rw [hi, show pub 1 + (i.val : Word w) = _ from public_state base i]
+ exact cell_lower _ hf
+ exact (below_write mem _ _ hd₀).trans ((below_write _ _ _ hd₁).trans
+ (below_write _ _ _ (by rw [show (pub 4).val = _ from public_depth_val base hf]; exact Nat.le_add_right ..)))
+ · rw [push_full pub st rs mem hz] at ht
+ contradiction
+
+private theorem mark_protects (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ Protects base (publicData w base R n m H) mark := by
+ let pub := publicData w base R n m H
+ constructor
+ intro st rs mem es rs' m' ht
+ by_cases hi : rs 2 < pub 6
+ · by_cases hnew : mem (pub 2 + rs 2).val = 0
+ · obtain ⟨_,_,h,_⟩ := mark_spec pub st rs mem hi hnew
+ have hm := congrArg (fun x : List (Event w) × Regs w 16 × Memory w => x.2.2) (Option.some.inj (ht.symm.trans h))
+ dsimp only at hm
+ rw [hm]
+ have hw : m < 2^w := by unfold size at hf; omega
+ have hj : (rs 2).val < m := by
+ change (rs 2).val < (m : Word w).val at hi
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt hw] using hi
+ let i : Fin m := ⟨(rs 2).val,hj⟩
+ apply below_write
+ rw [show rs 2 = (i.val : Word w) from (Fin.cast_val_eq_self _).symm,
+ show pub 2 + (i.val : Word w) = _ from public_mark base i]
+ exact cell_lower _ hf
+ · rw [mark_reject pub st rs mem (Or.inr hnew)] at ht
+ contradiction
+ · rw [mark_reject pub st rs mem (Or.inl hi)] at ht
+ contradiction
+
+private theorem increment_protects (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ Protects base (publicData w base R n m H) increment := by
+ let pub := publicData w base R n m H
+ constructor
+ intro st rs mem es rs' m' ht
+ change trace pub st increment rs mem = _ at ht
+ by_cases hi : rs 7 < pub 10
+ · by_cases hval : mem (pub 3 + rs 7).val < mem (pub 3 + rs 7).val + Fin.ofNat (2^w) 1
+ · simp at hval
+ simp (config := {decide := true}) [increment,trace,Op.effect,PrivateRAM.BinaryOp.eval,Function.update,hi,hval] at ht
+ rw [← ht.2.2]
+ apply below_write
+ have hw : labelCount n m H < 2^w := by unfold size at hf; omega
+ have hj : (rs 7).val < labelCount n m H := by
+ change (rs 7).val < (labelCount n m H : Word w).val at hi
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt hw] using hi
+ let i : Fin (labelCount n m H) := ⟨(rs 7).val,hj⟩
+ rw [show rs 7 = (i.val : Word w) from (Fin.cast_val_eq_self _).symm,
+ show pub 3 + (i.val : Word w) = _ from public_count base i]
+ exact cell_lower _ hf
+ · simp at hval
+ simp (config := {decide := true}) [increment,trace,Op.effect,PrivateRAM.BinaryOp.eval,Function.update,hi,not_lt.mpr hval] at ht
+ · simp (config := {decide := true}) [increment,trace,Op.effect,Function.update,hi] at ht
+
+private theorem choice_protects (c : RawChoice w) (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ Protects base (publicData w base R n m H) c.lines := by
+ cases c with
+ | leaf v =>
+ change Protects _ _ ((mark ++ leafBit ++ terminalIndex) ++ increment)
+ apply Protects.append _ (increment_protects hf)
+ apply Protects.append _ (protects_readOnly (ops := terminalIndex) (by simp [terminalIndex]))
+ exact Protects.append (mark_protects hf) (protects_readOnly (by simp [leafBit]))
+ | binary b i j =>
+ apply Protects.append
+ · apply Protects.append _ (increment_protects hf)
+ exact Protects.append (protects_readOnly (by simp [binaryChecks])) (protects_readOnly (by simp [binaryIndex]))
+ · apply Protects.append (protects_readOnly (ops := rightFrame) (by simp [rightFrame]))
+ exact Protects.append (push_protects hf) (Protects.append (protects_readOnly (by simp [leftFrame])) (push_protects hf))
+
+/-- The final nomination comparison can read every original header word. This
+also holds for an arbitrary initial memory whenever the physical call succeeds. -/
+theorem completeNode_below {st : Word w} {rs : Regs w 16} {mem : Memory w} {bits : List Bool} {o : Output w 16}
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w)
+ (hc : completeNode (publicData w base R n m H) st rs mem bits = some o) :
+ ∀ a < base, o.mem a = mem a := by
+ let pub := publicData w base R n m H
+ cases hp : trace pub st pop rs mem with
+ | none => simp [completeNode,nodeKernel,seqKernel,lineKernel,pub,hp] at hc
+ | some z =>
+ obtain ⟨es₀,r₀,m₀⟩ := z
+ rw [completeNode_pop pub st rs r₀ mem m₀ es₀ bits hp] at hc
+ obtain ⟨c,_,hc⟩ := Option.bind_eq_some_iff.mp hc
+ obtain ⟨⟨_,_,m'⟩,ht,rfl⟩ := Option.map_eq_some_iff.mp hc
+ exact ((pop_protects hf).run hp).trans ((choice_protects c hf).run ht)
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMFrame.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMFrame.lean
new file mode 100644
index 0000000000..24010d3ea1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMFrame.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.PrimedStackRAMChildren
+import OAI.Computability.VPVNP.PrimedCounterVisit
+
+/-!
+# Memory represented at each node visit
+
+Input, mark and count cells occupy disjoint regions from the frame planes.
+The external stack instructions leave the full input rectangle, every mark
+and every production count intact.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM PrimedCounter
+open scoped Fin.CommRing
+
+variable {base R n m H w : ℕ}
+
+/-- Recognize an input cell, leaf-position mark, or production counter among the parser’s
+scratch locations. -/
+def dataCell : Locations R n m H → Bool
+ | .inl _ | .inr (.inr (.inr (.inl _))) | .inr (.inr (.inr (.inr (.inl _)))) => true
+ | _ => false
+
+/-- Agreement of two memories on the assembled inputs, leaf marks, and production counts of the
+scratch rectangle based at `base`. -/
+def DataEq (base R n m H : ℕ) (m₀ m₁ : Memory w) : Prop :=
+ ∀ c : Locations R n m H, dataCell c → view base m₁ c = view base m₀ c
+
+theorem DataEq.trans {m₀ m₁ m₂ : Memory w} (h₀ : DataEq base R n m H m₀ m₁)
+ (h₁ : DataEq base R n m H m₁ m₂) : DataEq base R n m H m₀ m₂ :=
+ fun c hc => (h₁ c hc).trans (h₀ c hc)
+
+private theorem dataEq_store {mem : Memory w} (c : Locations R n m H) (v : Word w)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hc : dataCell c = false) :
+ DataEq base R n m H mem (store base mem c v) := by
+ intro a ha
+ rw [view_store_apply base mem c a v hf, ite_eq_right (by rintro rfl; simp [hc] at ha)]
+
+private theorem depth_mem {mem : Memory w} {stack : List (Word w × Word w)}
+ (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem stack)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ mem (publicData w base R n m H 4).val = (stack.length : Word w) := by
+ rw [public_depth_val base hf]
+ exact len_word hr
+
+theorem push_data {state : Word w} {regs rs : Regs w 16} {mem m' : Memory w} {es : List (Event w)}
+ {stack : List (Word w × Word w)} (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem stack)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hc : stack.length < n)
+ (ht : trace (publicData w base R n m H) state push regs mem = some (es, rs, m')) :
+ DataEq base R n m H mem m' := by
+ let pub := publicData w base R n m H
+ let i : Fin n := ⟨stack.length,hc⟩
+ have hd := depth_mem hr hf
+ have hn : n < 2^w := by unfold size at hf; omega
+ have hlt : mem (pub 4).val < pub 5 := by
+ rw [hd]
+ change (stack.length : Word w).val < (n : Word w).val
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt hn, Nat.mod_eq_of_lt (hc.trans hn)] using hc
+ obtain ⟨_, _, h, _⟩ := push_spec pub state regs mem hlt
+ have he := congrArg (fun z : List (Event w) × Regs w 16 × Memory w => z.2.2) (Option.some.inj (ht.symm.trans h))
+ dsimp only at he
+ rw [he]
+ have ad : pub 0 + mem (pub 4).val = (address base (degCell i : Locations R n m H) : Word w) := by
+ rw [hd]; exact public_degree base i
+ have ast : pub 1 + mem (pub 4).val = (address base (stateCell i : Locations R n m H) : Word w) := by
+ rw [hd]; exact public_state base i
+ have ap : pub 4 = (address base (depthCell : Locations R n m H) : Word w) := public_depth base
+ rw [ad, ast, ap]
+ exact (dataEq_store (degCell i) _ hf rfl).trans
+ ((dataEq_store (stateCell i) _ hf rfl).trans (dataEq_store depthCell _ hf rfl))
+
+theorem pop_data {state : Word w} {regs rs : Regs w 16} {mem m' : Memory w} {es : List (Event w)}
+ {stack : List (Word w × Word w)} {f : Word w × Word w}
+ (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem (f :: stack))
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w)
+ (ht : trace (publicData w base R n m H) state pop regs mem = some (es, rs, m')) :
+ DataEq base R n m H mem m' := by
+ let pub := publicData w base R n m H
+ have hw : (f::stack).length < 2^w := hr.fits.trans_lt (by unfold size at hf; omega)
+ have hd := depth_mem hr hf
+ have hlt : 0 < mem (pub 4).val := by
+ rw [hd]
+ change 0 < ((f::stack).length : Word w).val
+ rw [Fin.val_natCast, Nat.mod_eq_of_lt hw]
+ simp
+ obtain ⟨_, _, h, _⟩ := pop_spec pub state regs mem hlt
+ have he := congrArg (fun z : List (Event w) × Regs w 16 × Memory w => z.2.2) (Option.some.inj (ht.symm.trans h))
+ dsimp only at he
+ rw [he]
+ have ap : pub 4 = (address base (depthCell : Locations R n m H) : Word w) := public_depth base
+ rw [ap]
+ exact dataEq_store depthCell _ hf rfl
+
+/-- The frame list encoded as exact machine words (top first). -/
+def frames (w : ℕ) (stack : List (Frame n (Fin H))) : List (Word w × Word w) :=
+ stack.map fun (d,h) => (↑d.val, ↑h.val)
+
+/-- One complete logical visit state together with its assembled input rectangle. -/
+structure Holds (base : ℕ) (x : Fin 2 → Fin R → Fin m → Bool)
+ (st : VisitState n m H) (mem : Memory w) : Prop where
+ pending : Represents (R := R) (n := n) (m := m) (H := H) base mem (frames w st.pending)
+ input (g : Fin 2) (s : Fin R) (j : Fin m) :
+ view base mem (.inl ((g,s),j) : Locations R n m H) = (↑(x g s j).toNat : Word w)
+ marked (j : Fin m) :
+ view base mem (markCell j : Locations R n m H) = (if j ∈ st.marked then 1 else 0)
+ counts (a : Label n m (Fin H)) :
+ (view base mem (countCell (labelIndex n m H a) : Locations R n m H)).val = st.counts a
+
+theorem Holds.withStack {mem m' : Memory w} {x : Fin 2 → Fin R → Fin m → Bool} {st : VisitState n m H}
+ (hr : Holds base x st mem) (stack : List (Frame n (Fin H))) (he : DataEq base R n m H mem m')
+ (hs : Represents (R := R) (n := n) (m := m) (H := H) base m' (frames w stack)) :
+ Holds base x {st with pending := stack} m' where
+ pending := hs
+ input g s j := (he _ rfl).trans (hr.input g s j)
+ marked j := (he _ rfl).trans (hr.marked j)
+ counts a := (congrArg Fin.val (he _ rfl)).trans (hr.counts a)
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMIndex.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMIndex.lean
new file mode 100644
index 0000000000..c8caf2d647
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMIndex.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.PrimedStackRAM
+
+/-!
+# Dense counter addresses computed by the word opcodes
+
+The terminal and binary instruction blocks produce the index of the chosen
+production. Only the product used before division by two requires a separate
+intermediate word bound. All arithmetic after the triangular prefix is
+compatible with reduction modulo the word modulus.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM BurstRAM.PrivateRAM
+open scoped Fin.CommRing
+
+variable {w : ℕ} (pub : Fin 11 → Word w) (state : Word w) (regs : Regs w 16) (mem : Memory w)
+
+theorem terminalIndex_word :
+ ∃ es rs, trace pub state terminalIndex regs mem = some (es, rs, mem) ∧
+ countProbes es = 0 ∧ es.length = 6 ∧ rs 7 = (regs 1 * pub 6 + regs 2)*2 + regs 6 := by
+ simp (config := { decide := true }) [terminalIndex, trace, Op.effect, BinaryOp.eval,
+ Function.update, countProbes]
+
+theorem binaryIndex_word :
+ let tri := Fin.ofNat (2^w) (((regs 0 - 1)*regs 0).val / (2 : Word w).val)
+ ∃ es rs, trace pub state binaryIndex regs mem = some (es, rs, mem) ∧
+ countProbes es = 0 ∧ es.length = 15 ∧
+ rs 7 = (((tri + regs 2)*pub 7 + regs 1)*pub 7 + regs 3)*pub 7 + regs 4 + pub 9 := by
+ simp (config := { decide := true }) [binaryIndex, trace, Op.effect, BinaryOp.eval,
+ Function.update, countProbes]
+
+variable {n m H : ℕ}
+
+/-- Word indices are exact for all legal terminal choices whenever the dense array fits. -/
+theorem terminalIndex_spec (h : Fin H) (j : Fin m) (b : Bool)
+ (hp : pub 6 = (m : Word w)) (hr₁ : regs 1 = (h.val : Word w))
+ (hr₂ : regs 2 = (j.val : Word w)) (hr₆ : regs 6 = (b.toNat : Word w))
+ (hfit : labelCount n m H ≤ 2^w) :
+ ∃ es rs, trace pub state terminalIndex regs mem = some (es, rs, mem) ∧
+ countProbes es = 0 ∧ es.length = 6 ∧
+ (rs 7).val = (labelIndex n m H (.inl (h,j,b))).val := by
+ obtain ⟨es, rs, ht, hc, hl, he⟩ := terminalIndex_word pub state regs mem
+ refine ⟨es, rs, ht, hc, hl, ?_⟩
+ have hw := ((labelIndex n m H (.inl (h,j,b))).isLt).trans_le hfit
+ rw [labelIndex_terminal] at hw ⊢
+ rw [he, hr₁, hr₂, hr₆, hp]
+ exact (show ((↑((h.val*m + j.val)*2+b.toNat) : Word w)).val = _ from
+ (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt hw)) ▸ by push_cast; rfl
+
+/-- The exact triangular prefix of the split after the divide instruction. -/
+private theorem tri_exact (d : Fin n) (b : Fin d.val) (hr : (regs 0).val = d.val)
+ (hw : 2 < 2^w) (hprod : (d.val-1)*d.val < 2^w) :
+ Fin.ofNat (2^w) (((regs 0 - 1)*regs 0).val / (2 : Word w).val) = (d.val.choose 2 : Word w) := by
+ have hz : regs 0 ≠ 0 := by
+ intro hh
+ have hb := b.isLt
+ rw [hh] at hr
+ simp at hr
+ omega
+ change Fin.ofNat (2^w) ((((regs 0 - 1).val * (regs 0).val) % (2^w)) / (2 : Word w).val) = _
+ rw [Fin.val_sub_one_of_ne_zero hz, hr, Nat.mod_eq_of_lt hprod]
+ have htwo : (2 : Word w).val = 2 := Nat.mod_eq_of_lt hw
+ rw [htwo, Nat.choose_two_right, Nat.mul_comm (d.val-1), Fin.ofNat_eq_cast]
+
+theorem binaryIndex_spec (d : Fin n) (b : Fin d.val) (h i j : Fin H)
+ (hp : pub 7 = (H : Word w)) (hp₉ : pub 9 = (H*m*2 : ℕ))
+ (hr₀ : (regs 0).val = d.val) (hr₁ : regs 1 = (h.val : Word w))
+ (hr₂ : regs 2 = (b.val : Word w)) (hr₃ : regs 3 = (i.val : Word w))
+ (hr₄ : regs 4 = (j.val : Word w)) (hw : 2 < 2^w)
+ (hprod : (d.val-1)*d.val < 2^w) (hfit : labelCount n m H ≤ 2^w) :
+ ∃ es rs, trace pub state binaryIndex regs mem = some (es, rs, mem) ∧
+ countProbes es = 0 ∧ es.length = 15 ∧
+ (rs 7).val = (labelIndex n m H (.inr ⟨d,h,b,i,j⟩)).val := by
+ obtain ⟨es, rs, ht, hc, hl, he⟩ := binaryIndex_word pub state regs mem
+ refine ⟨es, rs, ht, hc, hl, ?_⟩
+ have hw' := ((labelIndex n m H (.inr ⟨d,h,b,i,j⟩)).isLt).trans_le hfit
+ rw [labelIndex_binary] at hw' ⊢
+ rw [he, tri_exact regs d b hr₀ hw hprod, hr₁, hr₂, hr₃, hr₄, hp, hp₉]
+ let ix := H*m*2 + (((d.val.choose 2 + b.val)*H + h.val)*H + i.val)*H + j.val
+ have hx : (↑ix : Word w).val = ix := (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt hw')
+ convert hx using 2
+ simp only [ix, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]
+ ring
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMLayout.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMLayout.lean
new file mode 100644
index 0000000000..9b2d169973
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMLayout.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.GrammarLabels
+import Mathlib.Algebra.BigOperators.Intervals
+import Mathlib.Logic.Equiv.Fin.Basic
+
+/-!
+# Scratch addresses for preorder parsing
+
+One row of the input rectangle belongs to each site in each of the two
+groups. After these rows are two planes for pending stack frames, one mark
+per position, one word per production, and one word for the stack depth.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+/-- Separate logical locations in the physical scratch interval. -/
+abbrev Cell (R n m T : ℕ) :=
+ ((Fin 2 × Fin R) × Fin m) ⊕ Fin n ⊕ Fin n ⊕ Fin m ⊕ Fin T ⊕ Fin 1
+
+/-- Number of words in the parser scratch interval, comprising two groups of input rows, two
+stack planes, position marks, production counters, and the stack depth. -/
+def size (R n m T : ℕ) := 2 * R * m + (n + (n + (m + (T + 1))))
+
+/-- Row-major address of every typed cell, contiguous across the six regions. -/
+def cellOffset (R n m T : ℕ) : Cell R n m T ≃ Fin (size R n m T) :=
+ let hist := ((Equiv.refl (Fin T)).sumCongr (Equiv.refl (Fin 1))).trans finSumFinEquiv
+ let marks := ((Equiv.refl (Fin m)).sumCongr hist).trans finSumFinEquiv
+ let states := ((Equiv.refl (Fin n)).sumCongr marks).trans finSumFinEquiv
+ let degrees := ((Equiv.refl (Fin n)).sumCongr states).trans finSumFinEquiv
+ let rows := (finProdFinEquiv.prodCongr (Equiv.refl (Fin m))).trans finProdFinEquiv
+ (rows.sumCongr degrees).trans finSumFinEquiv
+
+variable {R n m T : ℕ}
+
+/-- External word address of a typed parser cell, obtained by adding its offset in the scratch
+layout to `base`. -/
+def address (base : ℕ) (c : Cell R n m T) := base + (cellOffset R n m T c).val
+
+theorem address_injective (base : ℕ) : Function.Injective (address (R := R) (n := n) (m := m) (T := T) base) :=
+ fun _ _ h => (cellOffset R n m T).injective (Fin.ext (Nat.add_left_cancel h))
+
+theorem address_lt {base w : ℕ} (hfit : base + size R n m T ≤ 2 ^ w) (c : Cell R n m T) :
+ address base c < 2 ^ w :=
+ (Nat.add_lt_add_left (cellOffset R n m T c).isLt base).trans_le hfit
+
+theorem address_input (base : ℕ) (g : Fin 2) (s : Fin R) (j : Fin m) :
+ address (n := n) (T := T) base (.inl ((g, s), j)) = base + (g.val * R + s.val) * m + j.val := by
+ change base + (j.val + m * (s.val + R * g.val)) = _
+ ring
+
+theorem address_degree (base : ℕ) (j : Fin n) :
+ address (R := R) (m := m) (T := T) base (.inr (.inl j)) = base + 2*R*m + j.val := by
+ change base + (2*R*m + j.val) = _
+ omega
+
+theorem address_state (base : ℕ) (j : Fin n) :
+ address (R := R) (m := m) (T := T) base (.inr (.inr (.inl j))) = base + 2*R*m + n + j.val := by
+ change base + (2*R*m + (n + j.val)) = _
+ omega
+
+theorem address_mark (base : ℕ) (j : Fin m) :
+ address (R := R) (n := n) (T := T) base (.inr (.inr (.inr (.inl j)))) =
+ base + 2*R*m + 2*n + j.val := by
+ change base + (2*R*m + (n + (n + j.val))) = _
+ omega
+
+theorem address_hist (base : ℕ) (j : Fin T) :
+ address (R := R) (n := n) (m := m) base (.inr (.inr (.inr (.inr (.inl j))))) =
+ base + 2*R*m + 2*n + m + j.val := by
+ change base + (2*R*m + (n + (n + (m + j.val)))) = _
+ omega
+
+theorem address_depth (base : ℕ) :
+ address (R := R) (n := n) (m := m) (T := T) base (.inr (.inr (.inr (.inr (.inr 0))))) =
+ base + 2*R*m + 2*n + m + T := by
+ change base + (2*R*m + (n + (n + (m + (T + 0))))) = _
+ omega
+
+/-- All legal pairs (degree minus one, split minus one) in triangular order. -/
+def splitIndex {n : ℕ} (d : Fin n) (b : Fin d.val) : Fin (n.choose 2) :=
+ ⟨d.val.choose 2 + b.val, by
+ have hc := Nat.choose_le_choose 2 d.isLt
+ rw [Nat.choose_succ_succ d.val 1, Nat.choose_one_right] at hc
+ change d.val + d.val.choose 2 ≤ n.choose 2 at hc
+ have := b.isLt
+ omega⟩
+
+private theorem split_degree_eq {d e : Fin n} {b : Fin d.val} {a : Fin e.val}
+ (h : splitIndex d b = splitIndex e a) : d = e := by
+ have hv := congrArg Fin.val h
+ change d.val.choose 2 + b.val = e.val.choose 2 + a.val at hv
+ have upper (i : Fin n) (j : Fin i.val) : i.val.choose 2 + j.val < (i.val + 1).choose 2 := by
+ rw [Nat.choose_succ_succ i.val 1, Nat.choose_one_right]
+ change i.val.choose 2 + j.val < i.val + i.val.choose 2
+ have := j.isLt
+ omega
+ apply Fin.ext
+ rcases lt_trichotomy d.val e.val with hd | hd | hd
+ · have := (upper d b).trans_le (Nat.choose_le_choose 2 hd)
+ omega
+ · exact hd
+ · have := (upper e a).trans_le (Nat.choose_le_choose 2 hd)
+ omega
+
+private noncomputable def splitEquiv (n : ℕ) : (Σ d : Fin n, Fin d.val) ≃ Fin (n.choose 2) := by
+ let f := fun t : Σ d : Fin n, Fin d.val => splitIndex t.1 t.2
+ have hinj : Function.Injective f := by
+ rintro ⟨d,b⟩ ⟨e,a⟩ he
+ obtain rfl := split_degree_eq he
+ have hv := congrArg Fin.val he
+ change d.val.choose 2 + b.val = d.val.choose 2 + a.val at hv
+ obtain rfl := Fin.ext (Nat.add_left_cancel hv)
+ rfl
+ have hcard : Fintype.card (Σ d : Fin n, Fin d.val) = Fintype.card (Fin (n.choose 2)) := by
+ simp only [Fintype.card_sigma, Fintype.card_fin, Nat.choose_two_right]
+ exact (Fin.sum_univ_eq_sum_range id n).trans (Finset.sum_range_id n)
+ exact Equiv.ofBijective f ⟨hinj, ((Fintype.bijective_iff_injective_and_card f).mpr ⟨hinj, hcard⟩).2⟩
+
+/-- Number of occupied production counter cells. -/
+def labelCount (n m H : ℕ) := H * m * 2 + (((n.choose 2 * H) * H) * H)
+
+private def groupBinary (n H : ℕ) :
+ (Σ d : Fin n, Fin H × Fin d.val × Fin H × Fin H) ≃
+ (((Σ d : Fin n, Fin d.val) × Fin H) × Fin H) × Fin H where
+ toFun | ⟨d,h,b,i,j⟩ => (((⟨d,b⟩,h),i),j)
+ invFun | (((⟨d,b⟩,h),i),j) => ⟨d,h,b,i,j⟩
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+/-- Dense production indexing, using the triangular prefix for the split and
+then row-major coordinates for the parent, left child and right child. -/
+noncomputable def labelIndex (n m H : ℕ) :
+ GrammarLabel (Fin m × Bool) (Fin H) n ≃ Fin (labelCount n m H) :=
+ let term := (Equiv.prodAssoc _ _ _).symm.trans
+ ((finProdFinEquiv.prodCongr finTwoEquiv.symm).trans finProdFinEquiv)
+ let splitParent := (((splitEquiv n).prodCongr (Equiv.refl (Fin H))).trans finProdFinEquiv)
+ let left := (splitParent.prodCongr (Equiv.refl (Fin H))).trans finProdFinEquiv
+ let binary := (groupBinary n H).trans ((left.prodCongr (Equiv.refl (Fin H))).trans finProdFinEquiv)
+ (term.sumCongr binary).trans finSumFinEquiv
+
+theorem labelIndex_terminal {H : ℕ} (h : Fin H) (j : Fin m) (b : Bool) :
+ (labelIndex n m H (.inl (h,j,b))).val = (h.val*m + j.val)*2 + b.toNat := by
+ cases b
+ · change 0 + 2 * (j.val + m * h.val) = (h.val*m + j.val)*2 + 0
+ ring
+ · change 1 + 2 * (j.val + m * h.val) = (h.val*m + j.val)*2 + 1
+ ring
+
+theorem labelIndex_binary {H : ℕ} (d : Fin n) (b : Fin d.val) (h i j : Fin H) :
+ (labelIndex n m H (.inr ⟨d,h,b,i,j⟩)).val =
+ H*m*2 + (((d.val.choose 2 + b.val)*H + h.val)*H + i.val)*H + j.val := by
+ change H*m*2 + (j.val + H * (i.val + H * (h.val + H * (d.val.choose 2 + b.val)))) = _
+ ring
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMLeafVisit.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMLeafVisit.lean
new file mode 100644
index 0000000000..7231641d9d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMLeafVisit.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.PrimedStackRAMState
+
+/-!
+# Terminal visits of the primed counter
+
+For a fresh chosen position, the native instructions set the location mark,
+fetch the actual row bit and increment exactly that production. Repeated
+and out-of-range choices fail before reaching the increment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM PrimedCounter
+open scoped Fin.CommRing Classical
+
+variable {base R n m H w : ℕ} {x : Fin 2 → Fin R → Fin m → Bool}
+variable {st : VisitState n m H} {mem : Memory w}
+
+theorem probes_append (es fs : List (Event w)) :
+ countProbes (es ++ fs) = countProbes es + countProbes fs := by
+ induction es with
+ | nil => simp [countProbes]
+ | cons e es ih => cases e <;> simp [countProbes, ih, Nat.add_assoc]
+
+theorem leafLines_valid (hr : Holds base x st mem) (g : Fin 2) (s : Fin R)
+ (state : Word w) (regs : Regs w 16) (h : Fin H) (j : Fin m)
+ (hh : regs 1 = (h.val : Word w)) (hj : regs 2 = (j.val : Word w))
+ (hrow : regs 5 = (↑((g.val*R+s.val)*m) : Word w)) (hnew : j ∉ st.marked)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hw : 2 < 2^w)
+ (hcount : st.counts (.inl (h,j,x g s j)) + 1 < 2^w) :
+ let a : Label n m (Fin H) := .inl (h,j,x g s j)
+ ∃ es rs m', trace (publicData w base R n m H) state leafLines regs mem = some (es,rs,m') ∧
+ Holds base x {st with marked := insert j st.marked, counts := st.counts + Finsupp.single a 1} m' ∧
+ countProbes es = 5 := by
+ let pub := publicData w base R n m H
+ let st₁ := {st with marked := insert j st.marked}
+ let m₁ := store base mem (markCell j : Locations R n m H) 1
+ let a : Label n m (Fin H) := .inl (h,j,x g s j)
+ let ix := labelIndex n m H a
+ have hzero : view base mem (markCell j : Locations R n m H) = 0 := by simp [hr.marked j, hnew]
+ obtain ⟨es₀, rs₀, ht₀, hc₀⟩ := mark_cell mem state regs j hj hf hzero
+ have h₁ : Holds base x st₁ m₁ := hr.mark j hf
+ have hpos₁ : rs₀ 2 = regs 2 := trace_preserves (by decide) ht₀
+ have hrow₁ : rs₀ 5 = regs 5 := trace_preserves (by decide) ht₀
+ have hh₁ : rs₀ 1 = regs 1 := trace_preserves (by decide) ht₀
+ obtain ⟨es₁, rs₁, ht₁, hv₁, hc₁⟩ := leafBit_cell h₁ g s j state rs₀ (hpos₁.trans hj) (hrow₁.trans hrow) hf hw
+ have hpos₂ : rs₁ 2 = rs₀ 2 := trace_preserves (by decide) ht₁
+ have hh₂ : rs₁ 1 = rs₀ 1 := trace_preserves (by decide) ht₁
+ have hT : labelCount n m H ≤ 2^w := by unfold size at hf; omega
+ obtain ⟨es₂, rs₂, ht₂, hc₂, _, he₂⟩ := terminalIndex_spec pub state rs₁ m₁ h j (x g s j)
+ rfl (hh₂.trans (hh₁.trans hh)) (hpos₂.trans (hpos₁.trans hj)) hv₁ hT
+ have hv : rs₂ 7 = (ix.val : Word w) := by
+ change rs₂ 7 = (↑((labelIndex n m H (.inl (h,j,x g s j))).val) : Word w)
+ rw [← he₂, Fin.cast_val_eq_self]
+ have hinc : (view base m₁ (countCell ix : Locations R n m H)).val + 1 < 2^w :=
+ (h₁.counts a) ▸ hcount
+ obtain ⟨es₃, rs₃, ht₃, hc₃⟩ := increment_cell m₁ state rs₂ ix hv hf hinc
+ refine ⟨((es₀ ++ es₁) ++ es₂) ++ es₃, rs₃, _, ?_, h₁.increment a hf hcount, ?_⟩
+ · change trace pub state leafLines regs mem = _
+ simp [leafLines, trace_append, ht₀, ht₁, ht₂, ht₃, pub, m₁]
+ rfl
+ · simp [probes_append, hc₀, hc₁, hc₂, hc₃]
+
+theorem leafLines_outside (state : Word w) (regs : Regs w 16)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (ho : m ≤ (regs 2).val) :
+ trace (publicData w base R n m H) state leafLines regs mem = none := by
+ let pub := publicData w base R n m H
+ have hm : m < 2^w := by unfold size at hf; omega
+ have hg : ¬regs 2 < pub 6 := by
+ change ¬(regs 2).val < (m : Word w).val
+ simpa [Fin.val_natCast, Nat.mod_eq_of_lt hm] using Nat.not_lt.mpr ho
+ have h := mark_reject pub state regs mem (Or.inl hg)
+ change trace pub state leafLines regs mem = _
+ rw [leafLines, trace_append, trace_append, trace_append, h]
+ rfl
+
+theorem leafLines_repeated (hr : Holds base x st mem) (state : Word w) (regs : Regs w 16) (j : Fin m)
+ (hj : regs 2 = (j.val : Word w)) (hused : j ∈ st.marked)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hw : 2 < 2^w) :
+ trace (publicData w base R n m H) state leafLines regs mem = none := by
+ let pub := publicData w base R n m H
+ have he : pub 2 + regs 2 = (address base (markCell j : Locations R n m H) : Word w) :=
+ hj ▸ public_mark base j
+ have hv : mem (pub 2 + regs 2).val ≠ 0 := by
+ rw [he, Fin.val_natCast, Nat.mod_eq_of_lt (address_lt hf (markCell j))]
+ change view base mem (markCell j : Locations R n m H) ≠ 0
+ rw [hr.marked j, ite_eq_left hused]
+ intro h
+ have := congrArg Fin.val h
+ simp [Nat.mod_eq_of_lt (by omega : 1 < 2^w)] at this
+ have h := mark_reject pub state regs mem (Or.inr hv)
+ change trace pub state leafLines regs mem = _
+ rw [leafLines, trace_append, trace_append, trace_append, h]
+ rfl
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMMemory.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMMemory.lean
new file mode 100644
index 0000000000..37d1cd43d5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMMemory.lean
@@ -0,0 +1,295 @@
+import OAI.Computability.VPVNP.PrimedStackRAMIndex
+
+/-!
+# External memory and the preorder stack
+
+The two frame planes store the stack from bottom to top. The pointer cell
+contains its length, so the degree and state of the top frame have index
+one less than the pointer. The typed scratch addresses give the frame rules
+for the other words in the rectangle.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM
+open scoped Fin.CommRing
+
+variable {R n m H w : ℕ}
+
+/-- Typed parser scratch cells for two groups of `R` input rows, `n` frame slots, `m`
+positions, and a histogram indexed by the grammar’s production labels. -/
+abbrev Locations (R n m H : ℕ) := Cell R n m (labelCount n m H)
+
+/-- Classical decidable equality on typed parser locations for updating one cell in the
+scratch-memory view. -/
+noncomputable local instance : DecidableEq (Locations R n m H) := Classical.decEq _
+
+/-- Cell in the degree plane that stores degree minus one for the frame at stack slot `i`. -/
+def degCell (i : Fin n) : Locations R n m H := .inr (.inl i)
+/-- Cell in the state plane that stores the nonterminal state for the frame at stack slot `i`. -/
+def stateCell (i : Fin n) : Locations R n m H := .inr (.inr (.inl i))
+/-- Mark for input position `i`, used to detect a repeated position during a parse. -/
+def markCell (i : Fin m) : Locations R n m H := .inr (.inr (.inr (.inl i)))
+/-- Histogram cell counting uses of the production with dense label index `i`. -/
+def countCell (i : Fin (labelCount n m H)) : Locations R n m H := .inr (.inr (.inr (.inr (.inl i))))
+/-- Single scratch word holding the current stack length, which also indexes the next free
+frame slot. -/
+def depthCell : Locations R n m H := .inr (.inr (.inr (.inr (.inr 0))))
+
+/-- Runtime public word table. The input base is the start of the assembled rows. -/
+def publicData (w base R n m H : ℕ) : Fin 11 → Word w :=
+ let deg := base + 2*R*m
+ let sta := deg + n
+ let mark := sta + n
+ let hist := mark + m
+ let T := labelCount n m H
+ ![↑deg, ↑sta, ↑mark, ↑hist, ↑(hist+T), ↑n, ↑m, ↑H, ↑base, ↑(H*m*2), ↑T]
+
+/-- Read a typed parser location from external memory using the scratch layout based at `base`. -/
+def view (base : ℕ) (mem : Memory w) (c : Locations R n m H) : Word w := mem (address base c)
+
+/-- Write to a typed cell. All other scratch coordinates retain their previous values. -/
+def store (base : ℕ) (mem : Memory w) (c : Locations R n m H) (v : Word w) :=
+ writeMemory mem (address base c : Word w) v
+
+theorem view_store (base : ℕ) (mem : Memory w) (c : Locations R n m H) (v : Word w)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ view base (store base mem c v) = Function.update (view base mem) c v := by
+ funext a
+ have hv : (↑(address base c) : Word w).val = address base c :=
+ (Fin.val_natCast ..).trans (Nat.mod_eq_of_lt (address_lt hf c))
+ by_cases h : a = c
+ · subst a
+ simp [view, store, writeMemory, hv]
+ · simp [view, store, writeMemory, hv, Function.update_of_ne h,
+ show address base a ≠ address base c from fun he => h (address_injective base he)]
+
+theorem view_store_apply (base : ℕ) (mem : Memory w) (c a : Locations R n m H) (v : Word w)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ view base (store base mem c v) a = if a = c then v else view base mem a := by
+ rw [view_store _ _ _ _ hf]
+ by_cases ha : a = c
+ · subst a
+ simp
+ · simp [ha]
+
+theorem public_degree (base : ℕ) (i : Fin n) :
+ publicData w base R n m H 0 + (i.val : Word w) = ↑(address base (degCell i : Locations R n m H)) := by
+ rw [degCell, address_degree, Nat.cast_add]
+ rfl
+
+theorem public_state (base : ℕ) (i : Fin n) :
+ publicData w base R n m H 1 + (i.val : Word w) = ↑(address base (stateCell i : Locations R n m H)) := by
+ rw [stateCell, address_state, Nat.cast_add]
+ rfl
+
+theorem public_depth (base : ℕ) :
+ publicData w base R n m H 4 = ↑(address base (depthCell : Locations R n m H)) := by
+ rw [depthCell, address_depth]
+ change (↑(base+2*R*m+n+n+m+labelCount n m H) : Word w) = _
+ congr 1
+ omega
+
+theorem public_mark (base : ℕ) (i : Fin m) :
+ publicData w base R n m H 2 + (i.val : Word w) = ↑(address base (markCell i : Locations R n m H)) := by
+ rw [markCell, address_mark, Nat.cast_add]
+ change ↑(base+2*R*m+n+n) + (i.val : Word w) = _
+ rw [show base+2*R*m+n+n = base+2*R*m+2*n by omega]
+
+theorem public_count (base : ℕ) (i : Fin (labelCount n m H)) :
+ publicData w base R n m H 3 + (i.val : Word w) = ↑(address base (countCell i : Locations R n m H)) := by
+ rw [countCell, address_hist, Nat.cast_add]
+ change ↑(base+2*R*m+n+n+m) + (i.val : Word w) = _
+ rw [show base+2*R*m+n+n+m = base+2*R*m+2*n+m by omega]
+
+theorem public_depth_val (base : ℕ) (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ (publicData w base R n m H 4).val = address base (depthCell : Locations R n m H) := by
+ rw [public_depth, Fin.val_natCast, Nat.mod_eq_of_lt (address_lt hf depthCell)]
+
+theorem capacity_fit (base : ℕ) (hf : base + size R n m (labelCount n m H) ≤ 2^w) : n < 2^w := by
+ unfold size at hf
+ omega
+
+/-- Stack representation for a list of frames in preorder (top first). -/
+structure Represents (base : ℕ) (mem : Memory w) (stack : List (Word w × Word w)) : Prop where
+ fits : stack.length ≤ n
+ depth : (view base mem (depthCell : Locations R n m H)).val = stack.length
+ degrees (i : Fin stack.length) :
+ view base mem (degCell (i.castLE fits) : Locations R n m H) = stack.reverse[i.val].1
+ states (i : Fin stack.length) :
+ view base mem (stateCell (i.castLE fits) : Locations R n m H) = stack.reverse[i.val].2
+
+theorem len_word {base : ℕ} {mem : Memory w} {stack : List (Word w × Word w)}
+ (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem stack) :
+ view base mem (depthCell : Locations R n m H) = (stack.length : Word w) :=
+ hr.depth ▸ (Fin.cast_val_eq_self _).symm
+
+/-- Storing a frame in the first free slot and incrementing the depth represents a push. -/
+private theorem represents_push {base : ℕ} {mem : Memory w} {stack : List (Word w × Word w)}
+ (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem stack)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hc : stack.length < n)
+ (d h : Word w) :
+ let i : Fin n := ⟨stack.length, hc⟩
+ Represents (R := R) (n := n) (m := m) (H := H) base
+ (store base (store base (store base mem (degCell i : Locations R n m H) d)
+ (stateCell i : Locations R n m H) h) (depthCell : Locations R n m H) (stack.length+1 : ℕ))
+ ((d,h) :: stack) := by
+ dsimp only
+ have hw : stack.length + 1 < 2^w := (Nat.succ_le_of_lt hc).trans_lt (capacity_fit base hf)
+ refine ⟨by simpa using hc, ?_, ?_, ?_⟩
+ · rw [view_store _ _ _ _ hf, Function.update_self, Fin.val_natCast, Nat.mod_eq_of_lt hw]
+ rfl
+ all_goals
+ intro i
+ rcases i with ⟨j, hj⟩
+ simp only [view_store_apply _ _ _ _ _ hf, List.reverse_cons]
+ by_cases hi : j = stack.length
+ · simp [degCell, stateCell, depthCell, Fin.castLE, hi]
+ · have hlt : j < stack.length := by simp at hj; omega
+ rw [List.getElem_append_left (by simpa using hlt)]
+ simp [degCell, stateCell, depthCell, Fin.castLE, hi]
+ first | simpa [degCell, Fin.castLE] using hr.degrees ⟨j,hlt⟩ | simpa [stateCell, Fin.castLE] using hr.states ⟨j,hlt⟩
+
+/-- The compiled push inserts the two actual words and preserves every
+older pending frame. -/
+theorem push_rep {base : ℕ} {mem : Memory w} {stack : List (Word w × Word w)}
+ (state : Word w) (regs : Regs w 16)
+ (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem stack)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hc : stack.length < n) :
+ ∃ es rs mem', trace (publicData w base R n m H) state push regs mem = some (es, rs, mem') ∧
+ countProbes es = 4 ∧ Represents (R := R) (n := n) (m := m) (H := H) base mem'
+ ((regs 0, regs 1) :: stack) := by
+ let pub := publicData w base R n m H
+ have hp : (pub 4).val = _ := public_depth_val base hf
+ have hw : mem (pub 4).val = (stack.length : Word w) := hp ▸ len_word hr
+ have hdepth : (mem (pub 4).val).val = stack.length := hp ▸ hr.depth
+ have hcap : mem (pub 4).val < pub 5 := by
+ change (mem (pub 4).val).val < (n : Word w).val
+ simpa only [hdepth, Fin.val_natCast, Nat.mod_eq_of_lt (capacity_fit base hf)] using hc
+ obtain ⟨es, rs, ht, hp', _⟩ := push_spec pub state regs mem hcap
+ refine ⟨es, rs, _, ht, hp', ?_⟩
+ let i : Fin n := ⟨stack.length, hc⟩
+ change Represents base (writeMemory (writeMemory (writeMemory mem (pub 0 + mem (pub 4).val) _)
+ (pub 1 + mem (pub 4).val) _) (pub 4) _) _
+ rw [hw, show pub 0 + ↑stack.length = _ from public_degree base i,
+ show pub 1 + ↑stack.length = _ from public_state base i, show pub 4 = _ from public_depth base]
+ simpa only [store, Nat.cast_add, Nat.cast_one] using represents_push hr hf hc (regs 0) (regs 1)
+
+private theorem represents_pop {base : ℕ} {mem : Memory w} {stack : List (Word w × Word w)}
+ {d h : Word w} (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem ((d,h)::stack))
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ let mem' := store base mem (depthCell : Locations R n m H) (stack.length : Word w)
+ let i : Fin n := ⟨stack.length, hr.fits⟩
+ Represents (R := R) (n := n) (m := m) (H := H) base mem' stack ∧
+ view base mem' (degCell i : Locations R n m H) = d ∧
+ view base mem' (stateCell i : Locations R n m H) = h := by
+ dsimp only
+ have hc : stack.length < n := hr.fits
+ have hw := hc.trans (capacity_fit base hf)
+ refine ⟨⟨hc.le, ?_, ?_, ?_⟩, ?_, ?_⟩
+ · rw [view_store_apply _ _ _ _ _ hf, ite_eq_left rfl, Fin.val_natCast, Nat.mod_eq_of_lt hw]
+ · rintro ⟨i, hi⟩
+ have hd := hr.degrees ⟨i, by simp; omega⟩
+ rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (by simp [degCell, depthCell])]
+ simp only [List.reverse_cons] at hd
+ rw [List.getElem_append_left (by simpa using hi)] at hd
+ exact hd
+ · rintro ⟨i, hi⟩
+ have hs := hr.states ⟨i, by simp; omega⟩
+ rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (by simp [stateCell, depthCell])]
+ simp only [List.reverse_cons] at hs
+ rw [List.getElem_append_left (by simpa using hi)] at hs
+ exact hs
+ · rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (by simp [degCell, depthCell])]
+ simpa [List.reverse_cons, Fin.castLE] using hr.degrees ⟨stack.length, by simp⟩
+ · rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (by simp [stateCell, depthCell])]
+ simpa [List.reverse_cons, Fin.castLE] using hr.states ⟨stack.length, by simp⟩
+
+/-- The compiled pop returns the abstract top frame in the two destination
+registers and represents the exact remaining preorder stack. -/
+theorem pop_rep {base : ℕ} {mem : Memory w} {stack : List (Word w × Word w)} {d h : Word w}
+ (state : Word w) (regs : Regs w 16)
+ (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem ((d,h) :: stack))
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ ∃ es rs mem', trace (publicData w base R n m H) state pop regs mem = some (es, rs, mem') ∧
+ countProbes es = 4 ∧ Represents (R := R) (n := n) (m := m) (H := H) base mem' stack ∧
+ rs 0 = d ∧ rs 1 = h := by
+ let pub := publicData w base R n m H
+ let i : Fin n := ⟨stack.length, hr.fits⟩
+ let top := mem (pub 4).val - 1
+ have hp : (pub 4).val = _ := public_depth_val base hf
+ have hdepth : (mem (pub 4).val).val = stack.length+1 := hp ▸ hr.depth
+ have hpos : 0 < mem (pub 4).val := by change 0 < (mem _).val; omega
+ have htop : top.val = stack.length := by
+ rw [show top = mem (pub 4).val - 1 from rfl, Fin.val_sub_one_of_ne_zero hpos.ne', hdepth]
+ omega
+ have hw : top = (i.val : Word w) := by
+ change top = (stack.length : Word w)
+ rw [← htop, Fin.cast_val_eq_self]
+ obtain ⟨es, rs, ht, hc, _, hd, hs⟩ := pop_spec pub state regs mem hpos
+ refine ⟨es, rs, _, ht, hc, ?_⟩
+ let mem' := writeMemory mem (pub 4) top
+ have hm : mem' = store base mem (depthCell : Locations R n m H) (stack.length : Word w) := by
+ rw [show mem' = writeMemory mem (pub 4) top from rfl, hw, show pub 4 = _ from public_depth base]
+ rfl
+ change Represents base mem' stack ∧ _ ∧ _
+ rw [hd, hs]
+ change _ ∧ mem' (pub 0 + top).val = d ∧ mem' (pub 1 + top).val = h
+ rw [hm, hw, show pub 0 + ↑i.val = _ from public_degree base i,
+ show pub 1 + ↑i.val = _ from public_state base i, Fin.val_natCast, Fin.val_natCast,
+ Nat.mod_eq_of_lt (address_lt hf (degCell i)), Nat.mod_eq_of_lt (address_lt hf (stateCell i))]
+ exact represents_pop hr hf
+
+/-- The location test reads its own mark and succeeds with exactly that mark set. -/
+theorem mark_cell {base : ℕ} (mem : Memory w) (state : Word w) (regs : Regs w 16) (j : Fin m)
+ (hj : regs 2 = (j.val : Word w)) (hf : base + size R n m (labelCount n m H) ≤ 2^w)
+ (hnew : view base mem (markCell j : Locations R n m H) = 0) :
+ ∃ es rs, trace (publicData w base R n m H) state mark regs mem =
+ some (es, rs, store base mem (markCell j : Locations R n m H) 1) ∧ countProbes es = 2 := by
+ let pub := publicData w base R n m H
+ have hm : m < 2^w := by unfold size at hf; omega
+ have hjm : regs 2 < pub 6 := by
+ rw [hj]
+ change (j.val : Word w).val < (m : Word w).val
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt (j.isLt.trans hm), Nat.mod_eq_of_lt hm] using j.isLt
+ have he : pub 2 + regs 2 = (address base (markCell j : Locations R n m H) : Word w) :=
+ hj ▸ public_mark base j
+ have hmem : mem (pub 2 + regs 2).val = 0 := by
+ rw [he, Fin.val_natCast, Nat.mod_eq_of_lt (address_lt hf (markCell j))]
+ exact hnew
+ obtain ⟨es, rs, ht, hc, _⟩ := mark_spec pub state regs mem hjm hmem
+ rw [he] at ht
+ exact ⟨es, rs, ht, hc⟩
+
+/-- A valid counter increment writes only the indexed production's cell. -/
+theorem increment_cell {base : ℕ} (mem : Memory w) (state : Word w) (regs : Regs w 16)
+ (j : Fin (labelCount n m H)) (hj : regs 7 = (j.val : Word w))
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w)
+ (hcount : (view base mem (countCell j : Locations R n m H)).val + 1 < 2^w) :
+ ∃ es rs, trace (publicData w base R n m H) state increment regs mem =
+ some (es, rs, store base mem (countCell j : Locations R n m H)
+ (view base mem (countCell j : Locations R n m H) + 1)) ∧ countProbes es = 2 := by
+ let pub := publicData w base R n m H
+ have ht : labelCount n m H < 2^w := by unfold size at hf; omega
+ have hjt : regs 7 < pub 10 := by
+ rw [hj]
+ change (j.val : Word w).val < (labelCount n m H : Word w).val
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt (j.isLt.trans ht), Nat.mod_eq_of_lt ht] using j.isLt
+ have he : pub 3 + regs 7 = (address base (countCell j : Locations R n m H) : Word w) :=
+ hj ▸ public_count base j
+ have hval : mem (pub 3 + regs 7).val = view base mem (countCell j : Locations R n m H) := by
+ rw [he, Fin.val_natCast, Nat.mod_eq_of_lt (address_lt hf (countCell j))]
+ rfl
+ obtain ⟨es, rs, hx, hc, _⟩ := increment_spec pub state regs mem hjt (hval ▸ hcount)
+ rw [hval, he] at hx
+ exact ⟨es, rs, hx, hc⟩
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMNative.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMNative.lean
new file mode 100644
index 0000000000..f1b316542b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMNative.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.PrimedStackRAMVisit
+
+/-!
+# Acceptance of the native preorder-node program
+
+At ordinary burst-call entry the private workspace is zero. The program
+loads the row offset from the persistent word and executes the finite node
+table. Its accepting choice streams agree exactly with the grammar visit,
+including the end-of-call test for unused bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedCounter
+open scoped Fin.CommRing
+
+variable {w n m R H base : ℕ}
+
+/-- Private register file after loading the persistent input-row offset into register 5 of the
+initially zero workspace. -/
+def entryRegs (row : Word w) : Regs w 16 := Function.update (fun _ => 0) 5 row
+
+theorem execute_nodeTemplate (pub : Fin 11 → Word w) (row : Word w) (mem : Memory w) (bits : List Bool) :
+ let M := nodeTemplate.instantiate w pub
+ BurstRAM.execute M.program (12*w+92) (M.program.start row) mem bits =
+ (completeNode pub row (entryRegs row) mem bits).map fun o =>
+ ⟨.tick :: o.events, some (o.regs 5)⟩ := by
+ let a : Flow 16 11 := .seq (.line (.stateWord 5)) nodeFlow
+ let M := (a.template (some 5)).instantiate w pub
+ let lab : nodeFlow.Label → Fin (a.length+2) := fun i => a.pc (.inr i)
+ have hl := Flow.template_linked (w := w) a (some 5) pub
+ have hb : M.code a.rejectPC = .reject := by
+ change ((a.template (some 5)).code a.rejectPC).resize w = _
+ rw [Flow.template_reject]
+ rfl
+ have hret : M.code a.exitPC = .returnState 5 := by
+ change ((a.template (some 5)).code a.exitPC).resize w = _
+ rw [Flow.template_exit]
+ rfl
+ have hs : M.program.step (M.program.start row) =
+ .localStep ⟨lab nodeFlow.entry,row,entryRegs row,fun _ => 0⟩ := by
+ change (M.code (a.pc (.inl ()))).run pub _ = _
+ rw [hl.atLabel (.inl ())]
+ rfl
+ have he := node_refines.execute hl.seqRight hb row (entryRegs row) (fun _ => 0) mem bits
+ (12*w+91) (by omega)
+ change BurstRAM.execute M.program (12*w+92) (M.program.start row) mem bits = _
+ rw [show 12*w+92 = (12*w+91)+1 by omega, BurstRAM.execute, hs]
+ change (BurstRAM.execute M.program (12*w+91) ⟨lab nodeFlow.entry,row,entryRegs row,fun _ => 0⟩ mem bits).map _ = _
+ apply (congrArg (Option.map (Report.prepend .tick)) he).trans
+ change ((nodeKernel pub row (entryRegs row) mem bits).bind _).map _ = _
+ cases hh : nodeKernel pub row (entryRegs row) mem bits with
+ | none => simp [completeNode, hh]
+ | some o =>
+ have hlen := node_refines.bounded hh
+ obtain ⟨f,hf⟩ : ∃ f, 12*w+91-o.events.length = f+1 := ⟨12*w+90-o.events.length, by omega⟩
+ have hd : M.program.step ⟨a.exitPC,row,o.regs,fun _ => 0⟩ = .finish (some (o.regs 5)) := by
+ change (M.code a.exitPC).run pub _ = _
+ rw [hret]
+ rfl
+ simp only [Option.bind_some]
+ change ((BurstRAM.execute M.program (12*w+91-o.events.length)
+ ⟨a.exitPC,row,o.regs,fun _ => 0⟩ o.mem o.bits).map _).map _ = _
+ rw [hf, BurstRAM.execute, hd]
+ cases hbits : o.bits <;> simp [completeNode, hh, hbits]
+ change Report.mk (.tick :: o.events) _ = Report.mk (.tick :: (o.events ++ [])) _
+ simp
+ rfl
+
+theorem Agreement.isSome_eq {x : Fin 2 → Fin R → Fin m → Bool} {a : Option (VisitState n m H)}
+ {o : Option (Output w 16)} (h : Agreement base x a o) : o.isSome = a.isSome := by cases h <;> rfl
+
+/-- Native accepting paths for this call, with no per-input changes to the instruction table. -/
+theorem nodeTemplate_accepts_iff {x : Fin 2 → Fin R → Fin m → Bool} {st : VisitState n m H}
+ {mem : Memory w} (hr : Holds base x st mem) (g : Fin 2) (s : Fin R) (bits : List Bool)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hH : H < 2^w) (hw : 2 < 2^w)
+ (hprod : n*n ≤ 2^w) (hmass : leafMass st.pending ≤ n) (hcounts : ∀ a, st.counts a + 1 < 2^w) :
+ let M := nodeTemplate.instantiate w (publicData w base R n m H)
+ let row : Word w := ↑((g.val*R+s.val)*m)
+ (BurstRAM.execute M.program (12*w+92) (M.program.start row) mem bits).isSome ↔
+ (visit w (x g s) st bits).isSome := by
+ dsimp only
+ rw [execute_nodeTemplate, Option.isSome_map]
+ let row : Word w := ↑((g.val*R+s.val)*m)
+ have h := completeNode_visit hr g s row (entryRegs row) bits (by simp [entryRegs,row])
+ hf hH hw hprod hmass hcounts
+ rw [h.isSome_eq]
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMNodeRun.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMNodeRun.lean
new file mode 100644
index 0000000000..2111998f3f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMNodeRun.lean
@@ -0,0 +1,236 @@
+import OAI.Computability.VPVNP.PrimedStackRAMNodeTable
+
+/-!
+# Native execution of the complete preorder-node table
+
+The evaluator below reads the same finite word encodings as the linked loops
+and retains the unused choice suffix for the surrounding program. A missing
+choice or failed guard aborts the native execution at every sufficient fuel.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedCounter
+
+variable {r k p w : ℕ}
+
+/-- Result of a successful RAM segment, including its event trace, final registers and memory,
+and the choice bits available to the continuation. -/
+structure Output (w r : ℕ) where
+ /-- RAM events in execution order, including ticks, choices, and memory probes. -/
+ events : List (Event w)
+ /-- Register contents passed to the next segment. -/
+ regs : Regs w r
+ /-- External memory after the segment has executed its writes. -/
+ mem : Memory w
+ /-- Suffix of the choice stream left for the next segment. -/
+ bits : List Bool
+
+/-- Prefix a successful segment’s trace with the events of an earlier segment. -/
+def Output.prepend (es : List (Event w)) (o : Output w r) := {o with events := es ++ o.events}
+
+/-- Partial execution of a RAM segment from public words, a state word, registers, memory, and
+a choice stream. Success returns the trace and the state needed by the continuation. -/
+abbrev Kernel (w r k : ℕ) :=
+ (Fin k → Word w) → Word w → Regs w r → Memory w → List Bool → Option (Output w r)
+
+/-- Execute a straight-line list of opcodes and carry the choice stream through to the
+continuation. -/
+def lineKernel (ops : List (Op r k)) : Kernel w r k := fun pub st rs mem bits =>
+ (trace pub st ops rs mem).map fun (es,rs',m') => ⟨es, rs', m', bits⟩
+
+/-- Consume one word’s worth of choice bits, record the guessing loop’s trace, and update its
+three registers. A short stream causes rejection. -/
+def guessKernel (reg : Fin 3 ↪ Fin r) : Kernel w r k := fun _ _ rs mem bits =>
+ (takeWord w bits).map fun (v, tail) =>
+ ⟨GuessWord.trace v, GuessWord.resultRegs reg rs v, mem, tail⟩
+
+/-- Run two kernels in order, passing the first result’s registers, memory, and unused bits to
+the second and appending their traces on success. -/
+def seqKernel (a b : Kernel w r k) : Kernel w r k := fun pub st rs mem bits => do
+ let x ← a pub st rs mem bits
+ let y ← b pub st x.regs x.mem x.bits
+ return y.prepend x.events
+
+/-- Compare two registers to select a kernel and prefix its successful trace with the tick
+spent on the comparison. -/
+def eqKernel (l q : Fin r) (a b : Kernel w r k) : Kernel w r k := fun pub st rs mem bits =>
+ ((if rs l = rs q then a else b) pub st rs mem bits).map (Output.prepend [.tick])
+
+private def extend (es : List (Event w)) (rep : Report w) : Report w := ⟨es ++ rep.events, rep.result⟩
+
+private theorem extend_comp (a b : List (Event w)) : extend a ∘ extend b = extend (a ++ b) := by
+ funext z
+ simp [extend, List.append_assoc]
+
+/-- Bounded refinement for every containing table and every continuation. -/
+structure Refines (a : Flow r k) (budget : ℕ) (f : Kernel w r k) : Prop where
+ bounded {pub st rs mem bits out} (h : f pub st rs mem bits = some out) : out.events.length ≤ budget
+ execute {p : ℕ} {M : Machine w p r k} {label : a.Label → Fin p} {stop bad : Fin p}
+ (hl : Flow.Linked M a label stop bad) (hb : M.code bad = .reject)
+ (st : Word w) (rs : Regs w r) (priv : Word w → Word w) (m : Memory w)
+ (bs : List Bool) (fuel : ℕ) (hf : budget ≤ fuel) :
+ BurstRAM.execute M.program fuel ⟨label a.entry,st,rs,priv⟩ m bs =
+ (f M.publicData st rs m bs).bind fun o =>
+ (BurstRAM.execute M.program (fuel-o.events.length) ⟨stop,st,o.regs,priv⟩ o.mem o.bits).map
+ (extend o.events)
+
+private theorem length_trace {ops : List (Op r k)} {pub : Fin k → Word w} {st : Word w}
+ {rs rs' : Regs w r} {m m' : Memory w} {es} (ht : trace pub st ops rs m = some (es,rs',m')) :
+ es.length = ops.length := by
+ induction ops generalizing rs m es with
+ | nil => simp [trace] at ht; rw [ht.1]; rfl
+ | cons op ops ih =>
+ cases he : op.effect pub st rs m with
+ | none => simp [trace, he] at ht
+ | some t =>
+ obtain ⟨e,r₁,m₁⟩ := t
+ cases hs : trace pub st ops r₁ m₁ with
+ | none => simp [trace, he, hs] at ht
+ | some t =>
+ obtain ⟨es₁,r₂,m₂⟩ := t
+ simp [trace, he, hs] at ht
+ obtain ⟨rfl, rfl, rfl⟩ := ht
+ simp [ih hs]
+
+theorem lines_refine (ops : List (Op r k)) (hn : ops ≠ []) :
+ Refines (lines ops hn) ops.length (lineKernel (w := w) ops) := by
+ constructor
+ · intro pub st rs mem bits out h
+ obtain ⟨⟨es,rs',m'⟩,hs,rfl⟩ := Option.map_eq_some_iff.mp h
+ exact (length_trace hs).le
+ · intro p M label stop bad hl hb st rs priv m bs fuel hf
+ have he := (contains_lines ops hn label stop bad hl).execute hb st rs priv m bs (fuel-ops.length)
+ rw [Nat.sub_add_cancel hf, run_eq_trace] at he
+ rw [he]
+ cases ht : trace M.publicData st ops rs m with
+ | none => simp [lineKernel, ht]
+ | some t =>
+ obtain ⟨es,rs',m'⟩ := t
+ simp [lineKernel, ht, length_trace ht]
+ rfl
+
+private theorem takeWord_short {bits : List Bool} (hn : takeWord w bits = none) : bits.length < w := by
+ by_contra! hlen
+ obtain ⟨v,hv⟩ := GuessWord.exists_wordBits (w := w) (bits.take w) (by simp [hlen])
+ have h := (takeWord_eq_some_iff (w := w) bits v (bits.drop w)).mpr (by rw [hv, List.take_append_drop])
+ rw [hn] at h
+ contradiction
+
+theorem guess_refine (reg : Fin 3 ↪ Fin r) :
+ Refines (GuessWord.flow (k := k) reg) (4*w+4) (guessKernel (w := w) reg) := by
+ constructor
+ · intro pub st rs mem bits o h
+ obtain ⟨⟨v,t⟩,_,rfl⟩ := Option.map_eq_some_iff.mp h
+ exact (show (GuessWord.trace v).length = 4*w+4 by simp [GuessWord.trace]).le
+ · intro p M label stop bad hl _ st rs priv m bs fuel hf
+ cases h : takeWord w bs with
+ | none =>
+ simp only [guessKernel, h, Option.map_none, Option.bind_none]
+ exact GuessWord.native_short (GuessWord.contains_flow hl) _ rfl bs (takeWord_short h) fuel m
+ | some t =>
+ obtain ⟨v,tail⟩ := t
+ have hbits := (takeWord_eq_some_iff ..).mp h
+ have hp := GuessWord.flow_native_exact hl (⟨label _,st,rs,priv⟩ : Config w p r) rfl v
+ have he := hp.execute (fuel-(4*w+4)) m tail
+ have hlen : (GuessWord.trace v).length = 4*w+4 := by simp [GuessWord.trace]
+ have hchoice : choiceBits (GuessWord.trace v) = wordBits v := by simp [GuessWord.trace, choiceBits]
+ rw [hlen, Nat.sub_add_cancel hf, hchoice, ← hbits] at he
+ simp only [guessKernel, h, Option.map_some, Option.bind_some, hlen]
+ exact he
+
+theorem Refines.seq {a b : Flow r k} {na nb : ℕ} {fa fb : Kernel w r k}
+ (ha : Refines a na fa) (hb : Refines b nb fb) :
+ Refines (.seq a b) (na + nb) (seqKernel fa fb) := by
+ constructor
+ · intro pub st rs mem bits o h
+ simp only [seqKernel, bind, Option.bind_eq_some_iff] at h
+ obtain ⟨x, hx, y, hy, he⟩ := h
+ cases he
+ exact (List.length_append ..).trans_le (Nat.add_le_add (ha.bounded hx) (hb.bounded hy))
+ · intro p M label stop bad hl hbad st rs priv m bs fuel hf
+ have he := ha.execute hl.seqLeft hbad st rs priv m bs fuel (by omega)
+ change BurstRAM.execute M.program fuel ⟨label (.inl a.entry),st,rs,priv⟩ m bs = _
+ erw [he]
+ cases hx : fa M.publicData st rs m bs with
+ | none => simp [seqKernel, hx]
+ | some x =>
+ have hlen := ha.bounded hx
+ have he' := hb.execute hl.seqRight hbad st x.regs priv x.mem x.bits (fuel-x.events.length) (by omega)
+ simp only [seqKernel, hx, Option.bind_some]
+ erw [he']
+ cases hy : fb M.publicData st x.regs x.mem x.bits with
+ | none => simp [hy]
+ | some y =>
+ simp [hy, Output.prepend, Option.map_map,
+ extend_comp, Nat.sub_add_eq]
+
+theorem Refines.ifEq {a b : Flow r k} {na nb : ℕ} {fa fb : Kernel w r k}
+ (l q : Fin r) (ha : Refines a na fa) (hb : Refines b nb fb) :
+ Refines (.ifEq l q a b) (1+max na nb) (eqKernel l q fa fb) := by
+ constructor
+ · intro pub st rs mem bits o h
+ unfold eqKernel at h
+ split at h <;> obtain ⟨x,hx,rfl⟩ := Option.map_eq_some_iff.mp h
+ · have := ha.bounded hx; simp [Output.prepend]; omega
+ · have := hb.bounded hx; simp [Output.prepend]; omega
+ · intro p M label stop bad hl hbad st rs priv m bs fuel hf
+ obtain ⟨f,rfl⟩ : ∃ f, fuel = f+1 := ⟨fuel-1, by omega⟩
+ change BurstRAM.execute M.program (f+1) ⟨label (.inl ()),st,rs,priv⟩ m bs = _
+ rw [hl.execute_ifEq]
+ by_cases h : rs l = rs q
+ · have he := ha.execute hl.ifEqYes hbad st rs priv m bs f (by omega)
+ simp only [Function.comp_def] at he
+ simp only [h, ite_true, eqKernel]
+ erw [he]
+ cases fa M.publicData st rs m bs <;> simp [Output.prepend, extend,
+ Option.map_map, Function.comp_def, Report.prepend]
+ rfl
+ · have he := hb.execute hl.ifEqNo hbad st rs priv m bs f (by omega)
+ simp only [Function.comp_def] at he
+ simp only [h, ite_false, eqKernel]
+ erw [he]
+ cases fb M.publicData st rs m bs <;> simp [Output.prepend, extend,
+ Option.map_map, Function.comp_def, Report.prepend]
+ rfl
+
+/-- Guess the terminal position into register 2, then run the leaf checks and record its
+production. -/
+def leafKernel : Kernel w 16 11 :=
+ seqKernel (guessKernel (guessRegs 2 (by decide) (by decide))) (lineKernel leafLines)
+
+/-- Guess the split and the two child states into registers 2, 3, and 4, then execute the
+binary production and stack updates. -/
+def binaryKernel : Kernel w 16 11 :=
+ seqKernel (guessKernel (guessRegs 2 (by decide) (by decide))) <|
+ seqKernel (guessKernel (guessRegs 3 (by decide) (by decide))) <|
+ seqKernel (guessKernel (guessRegs 4 (by decide) (by decide))) (lineKernel binaryLines)
+
+/-- Pop the pending frame, compare its degree with zero, and run the leaf or binary kernel
+selected by that comparison. -/
+def nodeKernel : Kernel w 16 11 :=
+ seqKernel (lineKernel pop) (eqKernel 0 12 leafKernel binaryKernel)
+
+/-- Refinement of the complete native node. The continuation receives the
+true post-memory and remaining bits. -/
+theorem node_refines : Refines nodeFlow (12*w+90) (nodeKernel (w := w)) := by
+ have l := (guess_refine (w := w) (guessRegs 2 (by decide) (by decide))).seq
+ (lines_refine leafLines (by decide))
+ have b := (guess_refine (w := w) (guessRegs 2 (by decide) (by decide))).seq
+ ((guess_refine (w := w) (guessRegs 3 (by decide) (by decide))).seq
+ ((guess_refine (w := w) (guessRegs 4 (by decide) (by decide))).seq
+ (lines_refine binaryLines (by decide))))
+ have res := (lines_refine pop (by decide)).seq (Refines.ifEq 0 12 l b)
+ have he : 12*w+90 = 13 + (1 + max (4*w+4+32) (4*w+4+(4*w+4+(4*w+4+64)))) := by omega
+ rw [he]
+ exact res
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMNodeTable.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMNodeTable.lean
new file mode 100644
index 0000000000..f37da52bbe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMNodeTable.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.PrimedStackRAMChildren
+import OAI.Computability.VPVNP.PrimedCounterGuessFlow
+import OAI.Computability.VPVNP.PrimedInputRAMFlowLinks
+
+/-!
+# Fixed word-RAM table for a node of the primed counter
+
+After popping the top frame, the degree determines whether the next choice is
+one word or three. The zero register for this test is initialized by the pop.
+Each chooser uses registers 8 and 12 temporarily. On entry register 5 gives
+the offset of the assembled input row. A standalone call can initialize it
+from the persistent word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM
+open PrimedCounter
+
+variable {p r k w : ℕ}
+
+/-- Turn a nonempty straight-line segment into structured code with exactly the
+same number of instructions. -/
+def straight (head : Op r k) : List (Op r k) → Flow r k
+ | [] => .line head
+ | op :: rest => .seq (.line head) (straight op rest)
+
+theorem straight_length (head : Op r k) (rest : List (Op r k)) :
+ (straight head rest).length = rest.length + 1 := by
+ induction rest generalizing head with
+ | nil => rfl
+ | cons op rest ih => simp [straight, Flow.length, ih, Nat.add_comm]
+
+/-- Every compiled occurrence of a nonempty straight-line sequence contains the
+genuine opcode block used in its trace specification. -/
+theorem contains_straight {M : Machine w p r k} (head : Op r k) (rest : List (Op r k))
+ (lab : (straight head rest).Label → Fin p) (stop bad : Fin p)
+ (h : Flow.Linked M (straight head rest) lab stop bad) :
+ Contains M bad (lab (straight head rest).entry) (head :: rest) stop := by
+ induction rest generalizing head with
+ | nil =>
+ exact .cons (h.atLabel ()) (.nil stop)
+ | cons op rest ih =>
+ have h₁ := h.seqLeft
+ have h₂ := h.seqRight
+ exact .cons (h₁.atLabel ()) (ih op _ h₂)
+
+/-- A nonempty literal instruction list. -/
+def lines (ops : List (Op r k)) (hn : ops ≠ []) : Flow r k :=
+ straight (ops.head hn) ops.tail
+
+theorem contains_lines {M : Machine w p r k} (ops : List (Op r k)) (hn : ops ≠ [])
+ (lab : (lines ops hn).Label → Fin p) (stop bad : Fin p)
+ (h : Flow.Linked M (lines ops hn) lab stop bad) :
+ Contains M bad (lab (lines ops hn).entry) ops stop := by
+ cases ops with
+ | nil => contradiction
+ | cons op ops => exact contains_straight op ops lab stop bad h
+
+/-- Choices have distinct result, weight and zero registers. The scratch
+registers are shared by the three successive invocations. -/
+def guessRegs (dst : Fin 16) (h₈ : dst ≠ 8) (h₁₂ : dst ≠ 12) : Fin 3 ↪ Fin 16 where
+ toFun := ![dst, 8, 12]
+ inj' := by
+ intro i j he
+ fin_cases i <;> fin_cases j <;> simp_all
+
+/-- Check and mark the chosen terminal position, read its input bit, compute the terminal
+production index, and increment its count. -/
+def leafLines : List Line := mark ++ leafBit ++ terminalIndex ++ increment
+
+/-- Check that the chosen split is below the popped degree and both child states are below the
+public state count. -/
+def binaryChecks : List Line :=
+ [.guardLt 2 0, .publicWord 11 7, .guardLt 3 11, .guardLt 4 11]
+
+/-- Validate the binary choice, increment its production count, and push the right child
+followed by the left for preorder traversal. -/
+def binaryLines : List Line := binaryChecks ++ binaryIndex ++ increment ++ pushChildren
+
+/-- Structured RAM code that guesses one terminal position and executes the leaf instruction
+list. -/
+def leafFlow : Flow 16 11 :=
+ .seq (GuessWord.flow (guessRegs 2 (by decide) (by decide))) (lines leafLines (by decide))
+
+/-- Structured RAM code that guesses a degree split and two child states before executing the
+binary instruction list. -/
+def binaryFlow : Flow 16 11 :=
+ .seq (GuessWord.flow (guessRegs 2 (by decide) (by decide))) <|
+ .seq (GuessWord.flow (guessRegs 3 (by decide) (by decide))) <|
+ .seq (GuessWord.flow (guessRegs 4 (by decide) (by decide))) (lines binaryLines (by decide))
+
+/-- Structured code for one preorder visit. Pop a frame and branch on whether its degree is
+zero. -/
+def nodeFlow : Flow 16 11 :=
+ .seq (lines pop (by decide)) (.ifEq 0 12 leafFlow binaryFlow)
+
+/-- Standalone instruction table for one node, initialized by copying the persistent state word
+into register 5 as the input-row offset. -/
+def nodeTemplate :=
+ (Flow.seq (.line (.stateWord 5)) nodeFlow).template (some 5)
+
+theorem node_template_fixed : nodeTemplate.literalWidth = 2 := rfl
+
+/-- Exact number of elementary word instructions when a leaf succeeds, including
+the one-word guess and the branch on the popped degree. -/
+def leafWork (w : ℕ) := pop.length + 1 + (4*w+4) + leafLines.length
+
+/-- The three fixed-width choices of an internal node. -/
+def binaryWork (w : ℕ) := pop.length + 1 + 3*(4*w+4) + binaryLines.length
+
+theorem leafWork_eq (w : ℕ) : leafWork w = 4*w + 50 := by unfold leafWork; change 13+1+(4*w+4)+32 = _; omega
+theorem binaryWork_eq (w : ℕ) : binaryWork w = 12*w + 90 := by
+ unfold binaryWork
+ change 13+1+3*(4*w+4)+64 = _
+ omega
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMState.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMState.lean
new file mode 100644
index 0000000000..7dc6dff2e5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMState.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.PrimedStackRAMFrame
+import OAI.Computability.VPVNP.PrimedStackRAMNodeRun
+
+/-!
+# Word-memory updates on a represented grammar visit
+
+A location mark changes one bit. A production increment changes one dense
+counter by one. Neither operation changes pending frames or input rows.
+Popping a frame has the complementary effect on these regions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM PrimedCounter
+open scoped Fin.CommRing Classical
+
+variable {base R n m H w : ℕ} {x : Fin 2 → Fin R → Fin m → Bool}
+variable {st : VisitState n m H} {mem : Memory w}
+
+private theorem stack_store {stack : List (Word w × Word w)}
+ (hr : Represents (R := R) (n := n) (m := m) (H := H) base mem stack)
+ (c : Locations R n m H) (v : Word w) (hc : dataCell c)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ Represents (R := R) (n := n) (m := m) (H := H) base (store base mem c v) stack := by
+ have he (a : Locations R n m H) (ha : dataCell a = false) :
+ view base (store base mem c v) a = view base mem a := by
+ rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (by rintro rfl; simp [ha] at hc)]
+ exact ⟨hr.fits, (congrArg Fin.val (he _ rfl)).trans hr.depth,
+ fun i => (he _ rfl).trans (hr.degrees i), fun i => (he _ rfl).trans (hr.states i)⟩
+
+/-- Set a location mark while preserving every other represented component. -/
+theorem Holds.mark (hr : Holds base x st mem) (j : Fin m)
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) :
+ Holds base x {st with marked := insert j st.marked}
+ (store base mem (markCell j : Locations R n m H) 1) := by
+ refine ⟨stack_store hr.pending _ _ rfl hf, ?_, ?_, ?_⟩
+ · intro g s i
+ rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (by simp [markCell])]
+ exact hr.input g s i
+ · intro i
+ rw [view_store_apply _ _ _ _ _ hf, hr.marked]
+ by_cases hi : i = j <;> simp [markCell, hi]
+ · intro a
+ rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (by simp [countCell,markCell])]
+ exact hr.counts a
+
+/-- Increment exactly the logical Finsupp component selected by the dense label. -/
+theorem Holds.increment (hr : Holds base x st mem) (a : Label n m (Fin H))
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hc : st.counts a + 1 < 2^w) :
+ let c := (countCell (labelIndex n m H a) : Locations R n m H)
+ Holds base x {st with counts := st.counts + Finsupp.single a 1}
+ (store base mem c (view base mem c + 1)) := by
+ dsimp only
+ refine ⟨stack_store hr.pending _ _ rfl hf, ?_, ?_, ?_⟩
+ · intro g s i
+ rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (by simp [countCell])]
+ exact hr.input g s i
+ · intro i
+ rw [view_store_apply _ _ _ _ _ hf, ite_eq_right (by simp [countCell,markCell])]
+ exact hr.marked i
+ · intro b
+ rw [view_store_apply _ _ _ _ _ hf]
+ by_cases h : a = b
+ · subst b
+ have hh := Fin.val_add_one_of_lt' (i := view base mem
+ (countCell (labelIndex n m H a) : Locations R n m H)) ((hr.counts a) ▸ hc)
+ simp [hh, hr.counts a]
+ · simp [countCell, Ne.symm h]
+ exact hr.counts b
+
+private theorem pop_zero {pub : Fin 11 → Word w} {state : Word w} {regs rs : Regs w 16}
+ {m' : Memory w} {es} (ht : trace pub state pop regs mem = some (es, rs, m')) : rs 12 = 0 := by
+ by_cases h : 0 < mem (pub 4).val
+ · simp (config := { decide := true }) [pop, trace, Op.effect, Function.update, h] at ht
+ rw [← ht.2.1]
+ simp (config := { decide := true }) [Function.update]
+ · simp (config := { decide := true }) [pop, trace, Op.effect, Function.update, h] at ht
+
+/-- Pop the next logical frame. The row register survives, and the branch test
+register is zero even when arbitrary temporaries were supplied on entry. -/
+theorem pop_holds (hr : Holds base x st mem) {d : Fin n} {h : Fin H} {tail : List (Frame n (Fin H))}
+ (hp : st.pending = (d,h)::tail) (hf : base + size R n m (labelCount n m H) ≤ 2^w)
+ (state : Word w) (regs : Regs w 16) :
+ ∃ es rs m', trace (publicData w base R n m H) state pop regs mem = some (es,rs,m') ∧
+ Holds base x {st with pending := tail} m' ∧ rs 0 = (d.val : Word w) ∧
+ rs 1 = (h.val : Word w) ∧ rs 5 = regs 5 ∧ rs 12 = 0 ∧ countProbes es = 4 := by
+ have hs := hr.pending
+ rw [hp] at hs
+ change Represents base ((mem : Memory w)) ((↑d.val, ↑h.val)::frames w tail) at hs
+ obtain ⟨es, rs, m', ht, hc, hm, hd, hh⟩ := pop_rep state regs hs hf
+ refine ⟨es, rs, m', ht, hr.withStack tail (pop_data hs hf ht) hm, hd, hh, ?_, pop_zero ht, hc⟩
+ exact trace_preserves (by decide) ht
+
+/-- Zero pending frames reject immediately at the underflow guard. -/
+theorem pop_holds_empty (hr : Holds base x st mem) (hp : st.pending = [])
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (state : Word w) (regs : Regs w 16) :
+ trace (publicData w base R n m H) state pop regs mem = none := by
+ apply pop_empty
+ rw [public_depth_val base hf]
+ have hh := len_word hr.pending
+ rw [hp] at hh
+ exact hh
+
+/-- Read the assembled terminal bit from the physical row selected by the outer schedule. -/
+theorem leafBit_cell (hr : Holds base x st mem) (g : Fin 2) (s : Fin R) (j : Fin m)
+ (state : Word w) (regs : Regs w 16) (hpos : regs 2 = (j.val : Word w))
+ (hrow : regs 5 = (↑((g.val * R + s.val)*m) : Word w))
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hw : 2 < 2^w) :
+ ∃ es rs, trace (publicData w base R n m H) state leafBit regs mem = some (es,rs,mem) ∧
+ rs 6 = (↑(x g s j).toNat : Word w) ∧ countProbes es = 1 := by
+ let pub := publicData w base R n m H
+ let c : Locations R n m H := .inl ((g,s),j)
+ have haddr : pub 8 + regs 5 + regs 2 = (address base c : Word w) := by
+ rw [hrow, hpos, show address base c = _ from address_input base g s j, Nat.cast_add, Nat.cast_add]
+ rfl
+ have hread : mem (pub 8 + regs 5 + regs 2).val = (↑(x g s j).toNat : Word w) := by
+ rw [haddr, Fin.val_natCast, Nat.mod_eq_of_lt (address_lt hf c)]
+ exact hr.input g s j
+ have hm : m < 2^w := by unfold size at hf; omega
+ have hj : regs 2 < pub 6 := by
+ rw [hpos]
+ change (j.val : Word w).val < (m : Word w).val
+ simpa only [Fin.val_natCast, Nat.mod_eq_of_lt (j.isLt.trans hm), Nat.mod_eq_of_lt hm] using j.isLt
+ have hb : mem (pub 8 + regs 5 + regs 2).val < 2 := by
+ rw [hread]
+ change (↑(x g s j).toNat : Word w).val < (2 : Word w).val
+ rw [Fin.val_natCast, show (2 : Word w).val = 2 from Nat.mod_eq_of_lt hw]
+ cases x g s j <;> simp [Nat.mod_eq_of_lt (by omega : 1 < 2^w)]
+ obtain ⟨es,rs,ht,hc,_,hv⟩ := leafBit_spec pub state regs mem hj hb
+ exact ⟨es,rs,ht,hv.trans hread,hc⟩
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrimedStackRAMVisit.lean b/lean/OAI/Computability/VPVNP/PrimedStackRAMVisit.lean
new file mode 100644
index 0000000000..1d3e733a93
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrimedStackRAMVisit.lean
@@ -0,0 +1,188 @@
+import OAI.Computability.VPVNP.PrimedStackRAMChoices
+
+/-!
+# The native preorder visit agrees with the grammar traversal
+
+The complete opcode execution rejects exactly the branch strings rejected by
+the mathematical visit. When it succeeds, its external memory represents
+the prescribed next pending stack, mark set and common production histogram.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace PrimedStackRAM
+
+open BurstRAM PrimedCounter ParseGrammar
+open scoped Fin.CommRing Classical
+
+variable {base R n m H w : ℕ} {x : Fin 2 → Fin R → Fin m → Bool}
+variable {st : VisitState n m H} {mem : Memory w}
+
+/-- Agreement between a grammar visit and a native node execution. They reject together, or the
+final memory represents the resulting visit state, the choice stream is exhausted, and the
+trace uses at most fourteen probes. -/
+inductive Agreement (base : ℕ) (x : Fin 2 → Fin R → Fin m → Bool) :
+ Option (VisitState n m H) → Option (Output w 16) → Prop
+ | reject : Agreement base x none none
+ | accept {st' o} (holds : Holds base x st' o.mem) (bits : o.bits = [])
+ (probes : countProbes o.events ≤ 14) : Agreement base x (some st') (some o)
+
+private noncomputable def abstractChoice (x₀ : Fin m → Bool) (st₀ : VisitState n m H) (d : Fin n) (h : Fin H)
+ (c : RawChoice w) : Option (VisitState n m H) := do
+ let t ← c.token d.val m H
+ let (a, children) ← step x₀ (d,h) t
+ let marked ← markToken st₀.marked t
+ return ⟨children ++ st₀.pending,marked,st₀.counts + Finsupp.single a 1⟩
+
+private def physicalChoice (pub : Fin 11 → Word w) (state : Word w) (rs : Regs w 16)
+ (m₀ : Memory w) (popEvents : List (Event w)) (c : RawChoice w) : Option (Output w 16) :=
+ (trace pub state c.lines (choiceRegs rs c) m₀).map fun (es,rs',m') =>
+ ⟨popEvents ++ (.tick :: (c.events ++ es)),rs',m',[]⟩
+
+private theorem terminal_step (xx : Fin m → Bool) (d : Fin n) (h : Fin H) (j : Fin m)
+ (hd : d.val = 0) : step xx (d,h) (.terminal j) = some (.inl (h,j,xx j),[]) := by
+ rcases d with ⟨k,hk⟩
+ change k = 0 at hd
+ subst k
+ rfl
+
+private theorem binary_step (xx : Fin m → Bool) (d : Fin n) (b : Fin d.val) (h i j : Fin H) :
+ step xx (d,h) (.binary b.val i j) = some (.inr ⟨d,h,b,i,j⟩,[(leftDegree d b,i),(rightDegree d b,j)]) := by
+ rcases d with ⟨k,hk⟩
+ cases k with
+ | zero => exact Fin.elim0 b
+ | succ k => simp [step,b.isLt]
+
+private theorem choice_agreement (hr : Holds base x st mem) (g : Fin 2) (s : Fin R)
+ (d : Fin n) (h : Fin H) (state : Word w) (rs : Regs w 16) (es₀ : List (Event w))
+ (hp : countProbes es₀ = 4) (hr₀ : (rs 0).val = d.val) (hr₁ : rs 1 = (h.val : Word w))
+ (hr₅ : rs 5 = (↑((g.val*R+s.val)*m) : Word w)) (c : RawChoice w) (hc : c.isLeaf = decide (d.val = 0))
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hH : H < 2^w) (hw : 2 < 2^w)
+ (hprod : (d.val-1)*d.val < 2^w) (hcap : 0 < d.val → st.pending.length+2 ≤ n)
+ (hcounts : ∀ a, st.counts a + 1 < 2^w) :
+ Agreement base x (abstractChoice (x g s) st d h c)
+ (physicalChoice (publicData w base R n m H) state rs mem es₀ c) := by
+ let pub := publicData w base R n m H
+ cases c with
+ | leaf v =>
+ have hd : d.val = 0 := by simpa [RawChoice.isLeaf] using hc.symm
+ let rg := choiceRegs rs (.leaf v)
+ have hg : rg 2 = v ∧ rg 1 = rs 1 ∧ rg 5 = rs 5 := by
+ simp (config := {decide := true}) [rg,choiceRegs,setGuess,guessRegs,GuessWord.resultRegs,Function.update]
+ by_cases hv : v.val < m
+ · let j : Fin m := ⟨v.val,hv⟩
+ have hrj : rg 2 = (j.val : Word w) := hg.1.trans (Fin.cast_val_eq_self v).symm
+ by_cases hused : j ∈ st.marked
+ · have ht := leafLines_repeated hr state rg j hrj hused hf hw
+ have hs := terminal_step (x g s) d h j hd
+ change Agreement base x _ ((trace pub state leafLines rg mem).map _)
+ rw [ht]
+ simp [abstractChoice,RawChoice.token,hv,hs,markToken,j] at hused ⊢
+ simp [hused,Agreement.reject]
+ · obtain ⟨es,rg',m',ht,hst,hpr⟩ := leafLines_valid hr g s state rg h j (hg.2.1.trans hr₁) hrj
+ (hg.2.2.trans hr₅) hused hf hw (hcounts _)
+ have hs := terminal_step (x g s) d h j hd
+ change Agreement base x _ ((trace pub state leafLines rg mem).map _)
+ rw [ht]
+ change Agreement base x (abstractChoice (x g s) st d h (.leaf v)) (some _)
+ have ha : abstractChoice (x g s) st d h (.leaf v) = some
+ ⟨st.pending,insert j st.marked,st.counts + Finsupp.single (.inl (h,j,x g s j)) 1⟩ := by
+ simp only [abstractChoice,RawChoice.token,hv,dite_true,bind,Option.bind_some]
+ rw [hs]
+ have hused' : (⟨v.val,hv⟩ : Fin m) ∉ st.marked := hused
+ simp [markToken,hused',j]
+ rw [ha]
+ exact .accept hst rfl (by simp [probes_append,countProbes,hp,RawChoice.no_probes,hpr])
+ · have ht := leafLines_outside (R := R) (n := n) (H := H) state rg (mem := mem) hf
+ (by rw [hg.1]; omega)
+ change Agreement base x _ ((trace pub state leafLines rg mem).map _)
+ rw [ht]
+ simpa [abstractChoice, RawChoice.token, hv] using (Agreement.reject (base := base) (x := x) (w := w) (H := H) (n := n))
+ | binary b i j =>
+ let rg := choiceRegs rs (.binary b i j)
+ have hg : rg 0 = rs 0 ∧ rg 1 = rs 1 ∧ rg 2 = b ∧ rg 3 = i ∧ rg 4 = j := by
+ simp (config := {decide := true}) [rg,choiceRegs,setGuess,guessRegs,GuessWord.resultRegs,Function.update]
+ have hpub : (pub 7).val = H := (Fin.val_natCast H (2^w)).trans (Nat.mod_eq_of_lt hH)
+ by_cases hv : b.val < d.val ∧ i.val < H ∧ j.val < H
+ · let b' : Fin d.val := ⟨b.val,hv.1⟩
+ let i' : Fin H := ⟨i.val,hv.2.1⟩
+ let j' : Fin H := ⟨j.val,hv.2.2⟩
+ have hsz : 0 < d.val := by have := b'.isLt; omega
+ obtain ⟨es,rg',m',ht,hst,hpr⟩ := binaryLines_valid hr state rg d b' h i' j'
+ ((congrArg Fin.val hg.1).trans hr₀) (hg.2.1.trans hr₁) (congrArg Fin.val hg.2.2.1)
+ (congrArg Fin.val hg.2.2.2.1) (congrArg Fin.val hg.2.2.2.2) hf hH hw hprod (hcap hsz) (hcounts _)
+ have hs := binary_step (x g s) d b' h i' j'
+ change Agreement base x _ ((trace pub state binaryLines rg mem).map _)
+ rw [ht]
+ have ha : abstractChoice (x g s) st d h (.binary b i j) = some
+ ⟨(leftDegree d b',i') :: (rightDegree d b',j') :: st.pending, st.marked,
+ st.counts + Finsupp.single (.inr ⟨d,h,b',i',j'⟩) 1⟩ := by
+ simp only [abstractChoice,RawChoice.token,hv.1,hv.2.1,hv.2.2,dite_true,ite_true,bind,Option.bind_some]
+ rw [hs]
+ rfl
+ rw [ha]
+ exact .accept hst rfl (by simp [probes_append,countProbes,hp,RawChoice.no_probes,hpr])
+ · have hbad : ¬rg 2 < rg 0 ∨ ¬rg 3 < pub 7 ∨ ¬rg 4 < pub 7 := by
+ change ¬(rg 2).val < (rg 0).val ∨ ¬(rg 3).val < (pub 7).val ∨ ¬(rg 4).val < (pub 7).val
+ rw [hg.1,hg.2.2.1,hg.2.2.2.1,hg.2.2.2.2,hpub,hr₀]
+ tauto
+ have ht := binaryLines_reject pub state rg mem hbad
+ change Agreement base x _ ((trace pub state binaryLines rg mem).map _)
+ rw [ht]
+ have ha : abstractChoice (x g s) st d h (.binary b i j) = none := by
+ by_cases hb : b.val < d.val <;> by_cases hi : i.val < H <;> by_cases hj : j.val < H <;>
+ simp_all [abstractChoice, RawChoice.token]
+ rw [ha]
+ exact .reject
+
+private theorem length_le_leafMass (stack : List (Frame n (Fin H))) : stack.length ≤ leafMass stack := by
+ induction stack with
+ | nil => rfl
+ | cons f stack ih => change stack.length+1 ≤ f.1.val+1+leafMass stack; omega
+
+/-- Complete correctness at a single scheduled node, including malformed
+and truncated bitstrings, repeated locations and exact post-memory. -/
+theorem completeNode_visit (hr : Holds base x st mem) (g : Fin 2) (s : Fin R) (state : Word w)
+ (regs : Regs w 16) (bits : List Bool) (hrow : regs 5 = (↑((g.val*R+s.val)*m) : Word w))
+ (hf : base + size R n m (labelCount n m H) ≤ 2^w) (hH : H < 2^w) (hw : 2 < 2^w)
+ (hprod : n*n ≤ 2^w) (hmass : leafMass st.pending ≤ n) (hcounts : ∀ a, st.counts a + 1 < 2^w) :
+ Agreement base x (visit w (x g s) st bits)
+ (completeNode (publicData w base R n m H) state regs mem bits) := by
+ let pub := publicData w base R n m H
+ cases hp : st.pending with
+ | nil =>
+ have ht := pop_holds_empty hr hp hf state regs
+ simpa [visit,hp,completeNode,nodeKernel,seqKernel,lineKernel,ht] using
+ (Agreement.reject (base := base) (x := x) (w := w) (H := H) (n := n))
+ | cons f tail =>
+ obtain ⟨d,h⟩ := f
+ obtain ⟨es₀,r₀,m₀,ht,hr',hd,hh,hrow',hz,hprobes⟩ := pop_holds hr hp hf state regs
+ have hdw : (r₀ 0).val = d.val := by
+ rw [hd, Fin.val_natCast, Nat.mod_eq_of_lt (d.isLt.trans (capacity_fit base hf))]
+ have he : (r₀ 0 = r₀ 12) ↔ d.val = 0 := by simp [Fin.ext_iff,hz,hdw]
+ rw [completeNode_pop pub state regs r₀ mem m₀ es₀ bits ht, decide_eq_decide.mpr he]
+ cases hc : exactChoice w (decide (d.val=0)) bits with
+ | none =>
+ simpa [visit,hp,readToken_eq_choice,hc] using
+ (Agreement.reject (base := base) (x := x) (w := w) (H := H) (n := n))
+ | some c =>
+ have hcap (hs : 0 < d.val) : tail.length+2 ≤ n := by
+ rw [hp] at hmass
+ change d.val + 1 + leafMass tail ≤ n at hmass
+ have := length_le_leafMass tail
+ omega
+ have htri : (d.val - 1)*d.val < 2^w := by
+ exact ((Nat.mul_le_mul_right _ (Nat.sub_le d.val 1)).trans_lt
+ (Nat.mul_self_lt_mul_self d.isLt)).trans_le hprod
+ have ha := choice_agreement hr' g s d h state r₀ es₀ hprobes hdw hh (hrow'.trans hrow) c
+ (exactChoice_kind w (decide (d.val = 0)) bits c hc) hf hH hw htri hcap hcounts
+ simpa only [visit,hp,readToken_eq_choice,hc,bind,Option.bind_some,abstractChoice,physicalChoice,
+ Option.bind_assoc] using ha
+
+end PrimedStackRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/PrivateRAMRegisterOperands.lean b/lean/OAI/Computability/VPVNP/PrivateRAMRegisterOperands.lean
new file mode 100644
index 0000000000..e31d5f32d7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/PrivateRAMRegisterOperands.lean
@@ -0,0 +1,330 @@
+import OAI.Computability.VPVNP.RAMPrivateLogRun
+import OAI.Computability.VPVNP.RAMUniform
+
+/-!
+# Lowering public-word operands inside a native subroutine
+
+A virtual public word is supplied either by the enclosing machine's public data
+or by a register initialized before entry. The subroutine keeps these registers
+intact. A second copy of the host program counters executes the caller after
+return, so its continuation may overwrite any operand or invoke the subroutine
+again. Both executions produce the same report for every fuel and bit stream.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM.RegisterOperands
+
+variable {w v p q r k k' : ℕ}
+
+/-- Source of a virtual public word, given by either a register index or an index into the
+caller's public data. -/
+inductive Operand (r k : ℕ) where
+ | register (index : Fin r)
+ | «public» (index : Fin k)
+ deriving DecidableEq
+
+/-- Read the word stored in the register or public-data slot named by an operand. -/
+def Operand.value (reg : Fin r → Word w) (pub : Fin k → Word w) : Operand r k → Word w
+ | .register a => reg a
+ | .public j => pub j
+
+/-- Relabel jump targets and compile public loads in a single pass. -/
+def translate (pc : Fin p → Fin q) (ops : Fin k → Operand r k') : Instr w p r k → Instr w q r k'
+ | .constant a v j => .constant a v (pc j)
+ | .publicWord a i j => match ops i with
+ | .register b => .copy a b (pc j)
+ | .public n => .publicWord a n (pc j)
+ | .stateWord a j => .stateWord a (pc j)
+ | .copy a b j => .copy a b (pc j)
+ | .binary op a b c j => .binary op a b c (pc j)
+ | .loadPrivate a b j => .loadPrivate a b (pc j)
+ | .storePrivate a b j => .storePrivate a b (pc j)
+ | .jumpEq a b y n => .jumpEq a b (pc y) (pc n)
+ | .jumpLt a b y n => .jumpLt a b (pc y) (pc n)
+ | .choose y n => .choose (pc y) (pc n)
+ | .readExternal a b j => .readExternal a b (pc j)
+ | .writeExternal a b j => .writeExternal a b (pc j)
+ | .returnState a => .returnState a
+ | .accept => .accept
+ | .reject => .reject
+
+/-- Compile each virtual public load into a register copy or a physical public load according
+to the operand assignment. -/
+abbrev lower (ops : Fin k → Operand r k') (i : Instr w p r k) := translate id ops i
+/-- Apply a program-counter map to every continuation and jump target in an instruction. -/
+abbrev mapPC (pc : Fin p → Fin q) (i : Instr w p r k) := translate pc Operand.public i
+
+@[simp] theorem translate_resize (pc : Fin p → Fin q) (ops : Fin k → Operand r k') (i : Instr v p r k) :
+ (translate pc ops i).resize w = translate pc ops (i.resize w) := by
+ cases i <;> try rfl
+ case publicWord dst j next => cases h : ops j <;> simp [translate, h, Instr.resize]
+
+theorem mapPC_lower (pc : Fin p → Fin q) (ops : Fin k → Operand r k') (i : Instr w p r k) :
+ mapPC pc (lower ops i) = translate pc ops i := by
+ cases i <;> try rfl
+ case publicWord dst j next => cases h : ops j <;> simp [mapPC, lower, translate, h]
+
+/-- Construct a configuration with the supplied program counter and the given persistent word,
+registers, and private memory. -/
+def withPC (pc : Fin q) (c : Config w p r) : Config w q r :=
+ ⟨pc, c.persistent, c.reg, c.privateMem⟩
+
+/-- Apply a label map to the program counter of a RAM configuration. -/
+def mapConfig (pc : Fin p → Fin q) (c : Config w p r) := withPC (pc c.pc) c
+
+theorem translate_run (pc : Fin p → Fin q) (ops : Fin k → Operand r k') (i : Instr w p r k)
+ (pub : Fin k' → Word w) (c : Config w p r) (j : Fin q) :
+ (translate pc ops i).run pub (withPC j c) =
+ (i.run (fun n => (ops n).value c.reg pub) c).mapState (mapConfig pc) := by
+ cases i <;> try rfl
+ case publicWord dst n next => cases h : ops n <;> simp [translate, h, Operand.value, Instr.run,
+ Config.put, CallAction.mapState, mapConfig, withPC]
+ all_goals simp only [translate, Instr.run, CallAction.mapState, mapConfig, withPC, apply_ite]
+ all_goals split <;> rename_i h <;> simp only [h, ↓reduceIte]
+
+/-- The operand bank agrees with the semantic data on entry. -/
+def Agrees (ops : Fin k → Operand r k') (virtual : Fin k → Word w)
+ (pub : Fin k' → Word w) (reg : Fin r → Word w) : Prop :=
+ ∀ j, (ops j).value reg pub = virtual j
+
+/-- Embed a program label in the first copy of the instruction table, used for subroutine
+entry. -/
+abbrev enter (j : Fin p) : Fin (p + p) := j.castAdd p
+/-- Embed a program label in the second copy of the instruction table, used for the caller's
+continuation. -/
+abbrev caller (j : Fin p) : Fin (p + p) := j.natAdd p
+/-- Recover the original program label from its address in either copy of the instruction
+table. -/
+def fold : Fin (p + p) → Fin p := Fin.addCases id id
+
+@[simp] theorem fold_enter (j : Fin p) : fold (enter j) = j := Fin.addCases_left ..
+theorem fold_caller (j : Fin p) : fold (caller j) = j := Fin.addCases_right ..
+
+@[simp] theorem fold_addNat (j : Fin p) : fold (j.addNat p) = j := by
+ simpa only [caller, Fin.natAdd_eq_addNat] using fold_caller j
+
+/-- Place a configuration at the corresponding label in the subroutine-entry copy of the
+program. -/
+abbrev enterConfig (c : Config w p r) := mapConfig enter c
+/-- Place a configuration at the corresponding label in the caller's copy of the program. -/
+abbrev callerConfig (c : Config w p r) := mapConfig caller c
+/-- Recover a configuration of the original machine by folding its doubled program counter. -/
+abbrev project (c : Config w (p + p) r) := mapConfig fold c
+
+@[simp] theorem project_enterConfig (c : Config w p r) : project (enterConfig c) = c := by
+ simp only [project, enterConfig, mapConfig, withPC, fold_enter]
+
+@[simp] theorem project_callerConfig (c : Config w p r) : project (callerConfig c) = c := by
+ simp only [project, callerConfig, mapConfig, withPC, fold_caller]
+
+/-- The first copy uses the role's semantic rows and virtual data inside its
+region. All remaining rows use physical public data and jump to caller PCs. -/
+def shadow (A : Machine w p r k') (inside : Fin p → Prop) [DecidablePred inside]
+ (roleText : Fin p → Instr w (p+p) r k) (virtual : Fin k → Word w)
+ (ι : Fin k' → Fin k) : Machine w (p+p) r k where
+ entry := enter A.entry
+ publicData := virtual
+ code := let host := fun j => translate caller (fun n => .public (ι n)) (A.code j)
+ Fin.addCases (fun j => if inside j then roleText j else host j) host
+
+variable (A : Machine w p r k') (inside : Fin p → Prop) [DecidablePred inside]
+ (roleText : Fin p → Instr w (p+p) r k) (virtual : Fin k → Word w) (ι : Fin k' → Fin k)
+
+theorem shadow_code_enter (j : Fin p) (hj : inside j) :
+ (shadow A inside roleText virtual ι).code (enter j) = roleText j := by
+ simp [shadow, enter, hj]
+
+variable (publicOk : ∀ n, virtual (ι n) = A.publicData n)
+
+include publicOk in
+private theorem shadow_host_step (c : Config w (p+p) r) (j : Fin p) (hpc : fold c.pc = j)
+ (hostRow : (shadow A inside roleText virtual ι).code c.pc =
+ translate caller (fun n => .public (ι n)) (A.code j)) :
+ (shadow A inside roleText virtual ι).program.step c =
+ (A.program.step (project c)).mapState callerConfig := by
+ change ((shadow A inside roleText virtual ι).code c.pc).run virtual _ = ((A.code (fold c.pc)).run _ _).mapState _
+ rw [hostRow, hpc]
+ have h := translate_run caller (fun n : Fin k' => Operand.public (r := r) (ι n))
+ (A.code j) virtual (project c) c.pc
+ simpa only [Operand.value, publicOk, show withPC c.pc (project c) = c from rfl, callerConfig] using h
+
+private theorem shadow_inside_step (c : Config w (p+p) r) (j : Fin p)
+ (hpc : c.pc = enter j) (hj : inside j) :
+ (shadow A inside roleText virtual ι).program.step c = (roleText j).run virtual c := by
+ change ((shadow A inside roleText virtual ι).code c.pc).run virtual _ = _
+ rw [hpc, shadow_code_enter A inside roleText virtual ι j hj]
+
+include publicOk in
+private theorem shadow_outside_step (c : Config w (p+p) r)
+ (outside : ∀ j, c.pc = enter j → ¬ inside j) :
+ (shadow A inside roleText virtual ι).program.step c = (A.program.step (project c)).mapState callerConfig := by
+ cases eqn : c.pc using Fin.addCases with
+ | left j =>
+ apply shadow_host_step A inside roleText virtual ι publicOk c j (eqn ▸ fold_enter _)
+ simp only [shadow, eqn, Fin.addCases_left, ite_eq_right (outside j eqn)]
+ | right j =>
+ apply shadow_host_step A inside roleText virtual ι publicOk c j (eqn ▸ fold_caller _)
+ simp only [shadow, eqn, Fin.addCases_right]
+
+private theorem caller_ne_enter (j i : Fin p) : caller j ≠ enter i := by
+ intro eqn
+ have hv := congrArg Fin.val eqn
+ simp only [caller, enter, Fin.val_natAdd, Fin.val_castAdd] at hv
+ omega
+
+private theorem continuesTo_mapState {C D : Type*} (a : CallAction w C) (f : C → D) {d : D}
+ (hc : (a.mapState f).continuesTo d) : ∃ c, d = f c := by
+ cases a with
+ | localStep c | write _ _ c => exact ⟨c,hc⟩
+ | branch g | read _ g => obtain ⟨x,h⟩ := hc; exact ⟨g x,h⟩
+ | finish | reject => exact hc.elim
+
+/-- The register written by this instruction, including the destination
+filled by a successful external read. -/
+def destination : Instr w p r k → Option (Fin r)
+ | .constant dst _ _ | .publicWord dst _ _ | .stateWord dst _
+ | .copy dst _ _ | .binary _ dst _ _ _ | .loadPrivate dst _ _
+ | .readExternal dst _ _ => some dst
+ | _ => none
+
+@[simp] theorem destination_resize (i : Instr w p r k) (v : ℕ) :
+ destination (i.resize v) = destination i := by
+ cases i <;> rfl
+
+/-- Every continuation preserves registers outside the instruction's
+destination, for either choice and every possible read answer. -/
+theorem reg_of_continuesTo {i : Instr w p r k} {pub : Fin k → Word w}
+ {c next : Config w p r} {a : Fin r} (h : (i.run pub c).continuesTo next)
+ (haway : destination i ≠ some a) : next.reg a = c.reg a := by
+ cases i <;> simp only [Instr.run, CallAction.continuesTo] at h
+ case constant | publicWord | stateWord | copy | binary | loadPrivate =>
+ subst next
+ simp only [destination, ne_eq, Option.some.injEq] at haway
+ exact Function.update_of_ne (Ne.symm haway) _ _
+ case readExternal =>
+ obtain ⟨_, rfl⟩ := h
+ simp only [destination, ne_eq, Option.some.injEq] at haway
+ exact Function.update_of_ne (Ne.symm haway) _ _
+ case storePrivate | jumpEq | jumpLt | writeExternal => subst next; rfl
+ case choose => obtain ⟨_, rfl⟩ := h; rfl
+
+
+variable {C D : Type*}
+
+/-- Projecting every continuation on an invariant set preserves the entire
+external execution report at any fuel and on every choice stream. -/
+theorem execute_project (P : Program w C) (Q : Program w D) (f : C → D) (good : C → Prop)
+ (step : ∀ c, good c → (P.step c).mapState f = Q.step (f c))
+ (frame : ∀ c c', good c → (P.step c).continuesTo c' → good c') (fuel : ℕ)
+ (c : C) (hc : good c) (m : Memory w) (bits : List Bool) :
+ execute P fuel c m bits = execute Q fuel (f c) m bits := by
+ induction fuel generalizing c m bits with
+ | zero => rfl
+ | succ fuel ih =>
+ rw [execute, execute, ← step c hc]
+ cases hs : P.step c with
+ | localStep next | write _ _ next =>
+ have hg := frame c next hc (by rw [hs]; rfl)
+ simp [CallAction.mapState, ih next hg]
+ | branch next =>
+ cases bits with
+ | nil => rfl
+ | cons b bs =>
+ have hg := frame c (next b) hc (by rw [hs]; exact ⟨b, rfl⟩)
+ simp [CallAction.mapState, ih (next b) hg]
+ | read a next =>
+ have hg := frame c (next (m a.val)) hc (by rw [hs]; exact ⟨m a.val, rfl⟩)
+ simp [CallAction.mapState, ih (next (m a.val)) hg]
+ | finish | reject => rfl
+
+include publicOk in
+/-- Once the role returns to a caller PC, the shadow runs the actual caller,
+including later calls and writes to any of the formerly saved operands. -/
+theorem execute_caller (c : Config w p r) (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute (shadow A inside roleText virtual ι).program fuel (callerConfig c) m bits =
+ execute A.program fuel c m bits := by
+ symm
+ apply execute_project A.program (shadow A inside roleText virtual ι).program callerConfig
+ (fun _ => True) _ (fun _ _ _ _ => trivial) fuel c trivial m bits
+ intro c _
+ have h := shadow_outside_step A inside roleText virtual ι publicOk (callerConfig c)
+ (fun j hj => (caller_ne_enter _ j hj).elim)
+ simpa only [project_callerConfig] using h.symm
+
+/-- Project a returned configuration directly to the caller's program counter
+space. All register and memory fields are kept verbatim. -/
+theorem callerConfig_project_of_pc (c : Config w (p+p) r) {j : Fin p} (h : c.pc = caller j) :
+ callerConfig (project c) = c := by
+ change withPC (caller (fold c.pc)) c = c
+ rw [h, fold_caller, ← h]
+ rfl
+
+include publicOk in
+theorem execute_caller_of_pc (c : Config w (p+p) r) {j : Fin p} (h : c.pc = caller j)
+ (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute (shadow A inside roleText virtual ι).program fuel c m bits =
+ execute A.program fuel (project c) m bits := by
+ simpa only [callerConfig_project_of_pc c h] using
+ execute_caller A inside roleText virtual ι publicOk (project c) fuel m bits
+
+variable (ops : Fin k → Operand r k')
+ (rows : ∀ j, inside j → A.code j = translate fold ops (roleText j))
+ (frame : ∀ j, inside j → ∀ n a, ops n = .register a → destination (roleText j) ≠ some a)
+
+private def Good (c : Config w (p+p) r) :=
+ ∀ j, c.pc = enter j → inside j → Agrees ops virtual A.publicData c.reg
+
+omit [DecidablePred inside] in
+include frame in
+private theorem agree_next {j : Fin p} (hj : inside j) {c next : Config w (p+p) r}
+ (h : ((roleText j).run virtual c).continuesTo next) (agree : Agrees ops virtual A.publicData c.reg) :
+ Agrees ops virtual A.publicData next.reg := by
+ intro n
+ have hn := agree n
+ cases eqn : ops n with
+ | register a =>
+ simpa only [eqn, Operand.value, reg_of_continuesTo h (frame j hj n a eqn)] using hn
+ | «public» i => simpa only [eqn, Operand.value] using hn
+
+include publicOk rows frame in
+/-- Every lowered step agrees with the virtual one until the role returns.
+Only rows in the role are required to preserve the operand registers. -/
+theorem execute_enter (c : Config w p r) (agree : Agrees ops virtual A.publicData c.reg)
+ (fuel : ℕ) (m : Memory w) (bits : List Bool) :
+ execute (shadow A inside roleText virtual ι).program fuel (enterConfig c) m bits =
+ execute A.program fuel c m bits := by
+ have step (s : Config w (p+p) r) (hs : Good A inside virtual ops s) :
+ ((shadow A inside roleText virtual ι).program.step s).mapState project = A.program.step (project s) := by
+ by_cases role : ∃ j, s.pc = enter j ∧ inside j
+ · obtain ⟨j, hpc, hj⟩ := role
+ rw [shadow_inside_step A inside roleText virtual ι s j hpc hj]
+ change _ = (A.code (fold s.pc)).run A.publicData (project s)
+ rw [hpc, fold_enter, rows j hj]
+ have h := translate_run fold ops (roleText j) A.publicData s (fold s.pc)
+ have eqn : (fun n => (ops n).value s.reg A.publicData) = virtual := funext (hs j hpc hj)
+ rw [eqn] at h
+ exact h.symm
+ · have outside : ∀ j, s.pc = enter j → ¬ inside j := fun j hpc hj => role ⟨j,hpc,hj⟩
+ rw [shadow_outside_step A inside roleText virtual ι publicOk s outside]
+ cases h : A.program.step (project s) <;> simp only [CallAction.mapState, project_callerConfig]
+ have stable (s t : Config w (p+p) r) (hs : Good A inside virtual ops s)
+ (ht : ((shadow A inside roleText virtual ι).program.step s).continuesTo t) : Good A inside virtual ops t := by
+ by_cases role : ∃ j, s.pc = enter j ∧ inside j
+ · obtain ⟨j,hpc,hj⟩ := role
+ rw [shadow_inside_step A inside roleText virtual ι s j hpc hj] at ht
+ exact fun _ _ _ => agree_next A inside roleText virtual ops frame hj ht (hs j hpc hj)
+ · have outside : ∀ j, s.pc = enter j → ¬ inside j := fun j hpc hj => role ⟨j,hpc,hj⟩
+ rw [shadow_outside_step A inside roleText virtual ι publicOk s outside] at ht
+ obtain ⟨d,rfl⟩ := continuesTo_mapState _ _ ht
+ exact fun j hpc _ => (caller_ne_enter d.pc j hpc).elim
+ simpa only [project_enterConfig] using execute_project (shadow A inside roleText virtual ι).program
+ A.program project (Good A inside virtual ops) step stable fuel (enterConfig c) (fun _ _ _ => agree) m bits
+
+end BurstRAM.PrivateRAM.RegisterOperands
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ProgramLength.lean b/lean/OAI/Computability/VPVNP/ProgramLength.lean
new file mode 100644
index 0000000000..59522438b3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ProgramLength.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.UniversalMachine
+import Mathlib.Tactic.Linarith
+
+/-!
+# Length of a literal coefficient-machine program
+
+There are nine table rows per running state, each with at most two transition
+records. A unary target takes at most one bit per state including the halting
+states. This gives a quadratic bound for the self-delimiting program prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+private theorem unary_length (k : ℕ) : (unary k).length = k + 1 := by simp [unary]
+
+private theorem instructionBits_length_le {extra : ℕ} (a : Instruction extra) :
+ ((instructionFields a).flatMap unary).length ≤ extra + 14 := by
+ simp only [instructionFields, List.flatMap_cons, List.flatMap_nil, List.length_append,
+ unary_length, List.length_nil]
+ have := a.target.isLt
+ have := a.firstSymbol.isLt
+ have := a.secondSymbol.isLt
+ have := a.firstMove.isLt
+ have := a.secondMove.isLt
+ omega
+
+private theorem branchBits_length_le {extra : ℕ} (b : Branches extra) :
+ ((branchFields b).flatMap unary).length ≤ 2 * extra + 31 := by
+ cases b with
+ | stop => simp [branchFields, unary_length]
+ | one a =>
+ simp only [branchFields, List.flatMap_cons, List.length_append, unary_length]
+ have := instructionBits_length_le a
+ omega
+ | two a b =>
+ simp only [branchFields, List.flatMap_cons, List.flatMap_append, List.length_append,
+ unary_length]
+ have := instructionBits_length_le a
+ have := instructionBits_length_le b
+ omega
+
+private theorem rowsBits_length_le {extra : ℕ} (rows : List (Branches extra)) :
+ ((rows.flatMap branchFields).flatMap unary).length ≤ rows.length * (2 * extra + 31) := by
+ induction rows with
+ | nil => simp
+ | cons b rows ih =>
+ simp only [List.flatMap_cons, List.flatMap_append, List.length_append, List.length_cons,
+ Nat.add_mul, Nat.one_mul]
+ exact (Nat.add_le_add (branchBits_length_le b) ih).trans_eq (Nat.add_comm ..)
+
+/-- Including its unary length header, a literal table has polynomial size in its state count. -/
+theorem programPrefix_length_le (p : Program) :
+ (programPrefix p).length ≤ 1000 * (p.extra + 1) ^ 2 := by
+ have hrows := rowsBits_length_le p.rows
+ rw [p.rows_length] at hrows
+ simp only [programPrefix, List.length_append, unary_length, tableBits]
+ split
+ · simp_all
+ · simp only [List.flatMap_cons, List.length_append, unary_length]
+ have hsub : p.extra - 1 + 1 = p.extra := by omega
+ rw [hsub]
+ nlinarith [Nat.zero_le (p.extra ^ 2)]
+
+end UniversalMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ProjectedPowerObstruction.lean b/lean/OAI/Computability/VPVNP/ProjectedPowerObstruction.lean
new file mode 100644
index 0000000000..6c4ea6065f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ProjectedPowerObstruction.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.BalancedPowerObstruction
+import OAI.Computability.VPVNP.TensorPowerLengths
+
+/-!
+# Applying the balanced-cut obstruction to projected powers
+
+A literal projection of each tensor power from the universal polynomial transfers
+a circuit at an isolated small-circuit length to the largest power fitting there.
+The exponent in the projection length bound multiplies the assumed circuit exponent.
+A strict spectral cost gap then rules out arbitrarily large small-circuit lengths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial WireTensor
+
+variable {I J : Type} [Fintype I] [DecidableEq I] [Fintype J]
+
+omit [Fintype J] in
+@[simp] theorem partyExponent_univ_apply [DecidableEq J] (x : I → J) (i : I) (j : J) :
+ partyExponent Finset.univ x (i, j) = if x i = j then 1 else 0 := by
+ rw [partyExponent, Finsupp.finsetSum_apply, Finset.sum_eq_single i]
+ · simp [Finsupp.single_apply]
+ · intro i' _ hi
+ simp [hi]
+ · simp
+
+omit [Fintype J] in
+theorem partyExponent_univ_injective :
+ Function.Injective (partyExponent (Finset.univ : Finset I) (J := J)) := by
+ classical
+ intro x y h
+ funext i
+ have hxy := DFunLike.congr_fun h (i, y i)
+ simpa using hxy
+
+/-- The selected coefficient of the set-multilinear tensor form is its array entry. -/
+theorem coeff_partyForm {R : Type*} [CommSemiring R] (A : (I → J) → R) (a : I → J) :
+ (∑ x : I → J, (∏ i, X (i, x i)) * C (A x) : MvPolynomial (I × J) R).coeff
+ (partyExponent Finset.univ a) = A a := by
+ classical
+ have e : (∑ x : I → J, (∏ i, X (i, x i)) * C (A x) : MvPolynomial (I × J) R) =
+ ∑ x, monomial (partyExponent Finset.univ x) (A x) := by
+ simp only [partyExponent, monomial_sum_index, X]
+ exact Finset.sum_congr rfl fun _ _ ↦ mul_comm _ _
+ simp [e, coeff_monomial, partyExponent_univ_injective.eq_iff]
+
+variable {k P : Type*} [Field k] [Fintype P]
+
+/-- Under a strict spectral layout gap, a family of projected powers as in Section
+4.2 precludes arbitrarily large small-circuit lengths for the original family. -/
+theorem not_small_universal_of_power_projections
+ (F : SpectralPoint k P) (place : I → P) (centers : Finset I → Bool → P) (A : (I → J) → k)
+ (forms : (h : ℕ) → MvPolynomial (I × (Fin h → J)) k) (M D C : ℕ)
+ (hM : 0 < M) (hD : 0 < D) (hC : 0 < C) (hI : 3 ≤ Fintype.card I) (hJ : 1 < Fintype.card J)
+ (coeffs : ∀ h a, (forms h).coeff (partyExponent Finset.univ a) =
+ ∏ t : Fin h, A (fun i ↦ a i t))
+ (project : ∀ h n, M * (Fintype.card J ^ D)^h ≤ n →
+ ∃ φ : Projection k (Fin n × Bool) (I × (Fin h → J)),
+ φ.hom (map (Int.castRingHom k) (VPVNP.P n)) = forms h)
+ (hA : 0 < (F.value (placedTensor place (fun _ ↦ J) A) : ℝ))
+ (hgap : ∀ S : Finset I, Fintype.card I ≤ 3 * S.card → 3 * S.card ≤ 2 * Fintype.card I →
+ (Fintype.card J : ℝ) ^
+ ((D * C : ℕ) * F.wireDistance (centers S false) (centers S true) +
+ ∑ i, F.wireDistance (place i) (centers S (cutSide S i))) <
+ (F.value (placedTensor place (fun _ ↦ J) A) : ℝ)) :
+ ¬ ∀ N, ∃ n ≥ N, circuitSize (map (Int.castRingHom k) (VPVNP.P n)) ≤ n^C := by
+ intro small
+ let K := (M * Fintype.card J ^ D)^C
+ obtain ⟨N, hN⟩ := eventually_no_balanced_power_circuit F place centers A (D*C) K
+ (Nat.mul_pos hD hC) hI (by omega) hA hgap
+ obtain ⟨h, hn, hs⟩ := arbitrarily_large_powers_of_small_circuits forms hM
+ (one_lt_pow₀ hJ hD.ne') project small N
+ obtain ⟨c, hc⟩ := circuitSize_spec (forms h)
+ refine hN h hn _ ?_ c (fun a ↦ by rw [hc]; exact coeffs h a)
+ simpa only [K, ← pow_mul, mul_assoc, mul_comm D h] using hs
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ProjectionClosure.lean b/lean/OAI/Computability/VPVNP/ProjectionClosure.lean
new file mode 100644
index 0000000000..00532d9a2d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ProjectionClosure.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.PolynomialBounds
+import OAI.Computability.VPVNP.ProjectionDegree
+
+/-!
+# Closure of VP and VNP under p-projections
+
+The family receiving a projection has polynomially many variables. Lift a projection
+through the VNP sum by projecting the visible variables and keeping each Boolean
+witness variable as a formal input to the new summand.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped Classical
+
+variable {F : Type*} [Field F] {X Y : ℕ → Type} [∀ n, Fintype (X n)] [∀ n, Fintype (Y n)]
+
+/-- Formal variable-or-scalar substitution preserves a polynomial bound on the degree. -/
+theorem PFamily.of_pProjects {p : Family F X} {q : Family F Y}
+ (hq : PFamily q) (hpq : PProjects p q)
+ (hvar : PolynomiallyBounded (fun n => Fintype.card (X n))) : PFamily p := by
+ obtain ⟨r, hr, hφ⟩ := hpq
+ refine ⟨hvar, (hq.2.comp hr).of_le fun n => ?_⟩
+ obtain ⟨φ, he⟩ := hφ n
+ rw [← he]
+ exact φ.totalDegree_hom_le _
+
+theorem IsVP.of_pProjects {p : Family F X} {q : Family F Y}
+ (hq : IsVP q) (hpq : PProjects p q)
+ (hvar : PolynomiallyBounded (fun n => Fintype.card (X n))) : IsVP p := by
+ refine ⟨hq.1.of_pProjects hpq hvar, ?_⟩
+ obtain ⟨r, hr, hφ⟩ := hpq
+ apply (hq.2.comp hr).of_le
+ intro n
+ obtain ⟨φ, he⟩ := hφ n
+ rw [← he]
+ exact circuitSize_projection_le _ _
+
+/-- Extend a projection of visible variables by the identity on witness variables. -/
+def Projection.withWitness {σ τ W : Type} (φ : Projection F σ τ) :
+ Projection F (σ ⊕ W) (τ ⊕ W) :=
+ Sum.elim (fun i => (φ i).map Sum.inl id) (fun i => .inl (.inr i))
+
+/-- Specializing the Boolean witness before or after the visible projection agrees. -/
+theorem Projection.witnessValue_comp {σ τ W : Type} (φ : Projection F σ τ) (y : W → Bool) :
+ (witnessValue (X := τ) y).comp (φ.withWitness.hom) =
+ φ.hom.comp (witnessValue (X := σ) y) := by
+ apply MvPolynomial.ringHom_ext
+ · intro a
+ simp [Projection.hom, witnessValue]
+ · rintro (i | j)
+ · cases h : φ i <;> simp [Projection.withWitness, Projection.hom, witnessValue, h]
+ · cases h : y j <;> simp [Projection.withWitness, Projection.hom, witnessValue, h]
+
+theorem IsVNP.of_pProjects {p : Family F X} {q : Family F Y}
+ (hq : IsVNP q) (hpq : PProjects p q)
+ (hvar : PolynomiallyBounded (fun n => Fintype.card (X n))) : IsVNP p := by
+ obtain ⟨hqf, W, instW, g, hw, hg, hsum⟩ := hq
+ let : ∀ n, Fintype (W n) := instW
+ refine ⟨hqf.of_pProjects hpq hvar, ?_⟩
+ obtain ⟨r, hr, hproj⟩ := hpq
+ choose φ hφ using hproj
+ let s : Family F (fun n => X n ⊕ W (r n)) := fun n => (φ n).withWitness.hom (g (r n))
+ refine ⟨fun n => W (r n), fun n => instW (r n), s, hw.comp hr, ?_, ?_⟩
+ · apply hg.of_pProjects ⟨r, hr, fun n => ⟨(φ n).withWitness, rfl⟩⟩
+ simpa only [Fintype.card_sum] using hvar.add (hw.comp hr)
+ · intro n
+ rw [← hφ n, hsum, map_sum]
+ apply Finset.sum_congr rfl
+ intro y _
+ exact DFunLike.congr_fun ((φ n).witnessValue_comp y).symm _
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ProjectionComposition.lean b/lean/OAI/Computability/VPVNP/ProjectionComposition.lean
new file mode 100644
index 0000000000..5703af7b5e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ProjectionComposition.lean
@@ -0,0 +1,42 @@
+import OAI.Computability.VPVNP.PolynomialBounds
+
+/-!
+# Composition of polynomial projections
+
+Following two variable-or-constant substitutions gives another substitution of
+the same kind. For families, the source length is obtained by composing the two
+polynomially bounded index functions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+variable {R σ τ υ : Type*}
+
+/-- Follow a variable of the intermediate polynomial through the second projection. -/
+def Projection.comp (ψ : Projection R τ υ) (φ : Projection R σ τ) : Projection R σ υ :=
+ fun i => (φ i).elim ψ Sum.inr
+
+theorem Projection.hom_comp [CommSemiring R] (ψ : Projection R τ υ) (φ : Projection R σ τ) :
+ (ψ.comp φ).hom = ψ.hom.comp φ.hom := by
+ apply MvPolynomial.ringHom_ext
+ · intro r
+ simp [Projection.hom]
+ · intro i
+ cases hi : φ i <;> simp [Projection.comp, Projection.hom, hi]
+
+/-- A p-projection of a p-projection is a p-projection. -/
+theorem PProjects.trans {F : Type*} [Field F] {X Y Z : ℕ → Type}
+ {p : Family F X} {q : Family F Y} {s : Family F Z}
+ (hpq : PProjects p q) (hqs : PProjects q s) : PProjects p s := by
+ obtain ⟨r, hr, hφ⟩ := hpq
+ obtain ⟨t, ht, hψ⟩ := hqs
+ refine ⟨fun n => t (r n), ht.comp hr, fun n => ?_⟩
+ obtain ⟨φ, heqφ⟩ := hφ n
+ obtain ⟨ψ, heqψ⟩ := hψ (r n)
+ exact ⟨φ.comp ψ, by rw [Projection.hom_comp, RingHom.comp_apply, heqψ, heqφ]⟩
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ProjectionDegree.lean b/lean/OAI/Computability/VPVNP/ProjectionDegree.lean
new file mode 100644
index 0000000000..a90fa7eb48
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ProjectionDegree.lean
@@ -0,0 +1,39 @@
+import OAI.Computability.VPVNP.Circuits
+import Mathlib.Algebra.MvPolynomial.Degrees
+
+/-! # Total degree under variable-or-scalar projections -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+/-- A p-projection preserves the total-degree upper bound, even when it identifies
+variables or specializes them to arbitrary constants. -/
+theorem Projection.totalDegree_hom_le {R σ τ : Type*} [CommSemiring R]
+ (φ : Projection R σ τ) (p : MvPolynomial σ R) : (φ.hom p).totalDegree ≤ p.totalDegree := by
+ classical
+ rcases subsingleton_or_nontrivial R with h | h
+ · rw [Subsingleton.elim (φ.hom p) 0, totalDegree_zero]
+ exact Nat.zero_le _
+ conv_lhs => rw [p.as_sum, map_sum]
+ apply totalDegree_finsetSum_le
+ intro m hm
+ rw [Projection.hom, eval₂Hom_monomial]
+ refine (totalDegree_mul _ _).trans ?_
+ rw [totalDegree_C, zero_add]
+ refine (totalDegree_finsetProd m.support _).trans (le_trans ?_ (le_totalDegree hm))
+ apply Finset.sum_le_sum
+ intro i hi
+ cases hφ : φ i with
+ | inl j => simp [hφ]
+ | inr r =>
+ simp only [hφ, Sum.elim_inr]
+ change (C r ^ m i : MvPolynomial τ R).totalDegree ≤ m i
+ rw [← map_pow, totalDegree_C]
+ exact Nat.zero_le _
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/QueryClock.lean b/lean/OAI/Computability/VPVNP/QueryClock.lean
new file mode 100644
index 0000000000..008bd86e83
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/QueryClock.lean
@@ -0,0 +1,63 @@
+import OAI.Computability.VPVNP.UniversalMachine
+
+/-!
+# Clock and length bounds for compiled payload queries
+
+Each query can scan the full input and then move at most the length of the
+payload to reach the addressed bit. The literal table contributes enough
+prefix bits for a cubic bound on the total number of steps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open UniversalMachine
+
+/-- The unary state-count header alone has one bit for each running state. -/
+theorem queryPrefix_lower {p : Program} {t : ℕ} (ht : t + 1 ≤ p.extra) :
+ t + 2 ≤ (programPrefix p).length := by
+ have hpos : p.extra ≠ 0 := by omega
+ have htable : p.extra ≤ (tableBits p).length := by
+ simp [tableBits, hpos, unary]
+ omega
+ simp [programPrefix, unary]
+ omega
+
+/-- The fixed clock of §1.1 allows a full scan and a payload traversal for
+each query, plus the halting instruction. -/
+theorem querySteps_le_clock {t k ℓ n : ℕ} (hn : n = ℓ + k) (ht : t + 2 ≤ ℓ) :
+ t * (n + k + 1) + 1 ≤ n ^ clockExponent := by
+ have hn2 : 2 ≤ n := by omega
+ calc
+ t * (n + k + 1) + 1 ≤ (t + 1) * (n + k + 1) := by rw [Nat.succ_mul]; omega
+ _ ≤ n * (2 * n) := Nat.mul_le_mul (by omega) (by omega)
+ _ ≤ n * (n * n) := Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ hn2)
+ _ = n ^ 3 := by simp [pow_succ, Nat.mul_assoc]
+ _ ≤ n ^ clockExponent := Nat.pow_le_pow_right (by omega) (by decide : 3 ≤ clockExponent)
+
+/-- A quadratic table encoding preserves polynomial bounds on the number of
+queries, the number of query-program states, and the payload length. -/
+theorem queryInputLength_le {t q k ℓ A B : ℕ}
+ (hprefix : ℓ ≤ A * ((t + 1) * q * (k + 1) + 1) ^ 2)
+ (ht : t + 1 ≤ B) (hq : q ≤ B) (hk : k + 1 ≤ B) :
+ ℓ + k ≤ (4 * A + 1) * B ^ 6 := by
+ have hpos : 0 < B := by omega
+ have hcontrols : (t + 1) * q * (k + 1) ≤ B ^ 3 := by
+ simpa [pow_succ] using Nat.mul_le_mul (Nat.mul_le_mul ht hq) hk
+ have hplus : (t + 1) * q * (k + 1) + 1 ≤ 2 * B ^ 3 := by
+ have := Nat.pow_pos hpos (n := 3)
+ omega
+ have hsq := Nat.pow_le_pow_left hplus 2
+ have hk6 : k ≤ B ^ 6 := calc
+ k ≤ B ^ 1 := by simpa using (show k ≤ B by omega)
+ _ ≤ B ^ 6 := Nat.pow_le_pow_right hpos (by decide)
+ calc
+ ℓ + k ≤ A * (2 * B ^ 3) ^ 2 + B ^ 6 :=
+ Nat.add_le_add (hprefix.trans (Nat.mul_le_mul_left _ hsq)) hk6
+ _ = (4 * A + 1) * B ^ 6 := by
+ rw [Nat.mul_pow, ← Nat.pow_mul, Nat.add_mul, Nat.one_mul, ← Nat.mul_assoc, Nat.mul_comm A]
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/QueryControl.lean b/lean/OAI/Computability/VPVNP/QueryControl.lean
new file mode 100644
index 0000000000..1b67bdeed0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/QueryControl.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.QueryProgram
+import OAI.Computability.VPVNP.QueryTape
+import OAI.Computability.VPVNP.TableCompiler
+import Mathlib.Data.Fintype.Prod
+
+/-!
+# Read a query bit on the literal machine's tape
+
+A control records the remaining number of queries, the query-program state, and a phase.
+Phase zero scans right until the blank immediately after the input. A query for suffix bit
+`i` then moves left by `k - i` cells. Phase one reads the selected symbol and starts the next
+query. The input and work tapes are preserved throughout the simulation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace QueryMachine
+
+open UniversalMachine TableCompiler QueryTape
+
+/-- Control state recording the remaining query budget, the query-program state, and the
+tape-scan phase. -/
+abbrev Control (t k : ℕ) (Q : Type*) := Fin (t + 1) × Q × Fin (k + 1)
+
+/-- Decrease a bounded counter by one, saturating at zero. -/
+def predFin {n : ℕ} (a : Fin (n + 1)) : Fin (n + 1) := ⟨a.val - 1, by omega⟩
+
+/-- Distance from the blank after the payload to bit `i` of its `k`-bit suffix. -/
+def offset {k : ℕ} (i : Fin k) : Fin (k + 1) := ⟨k - i.val, by omega⟩
+
+variable {k : ℕ} {Q : Type*} (p : QueryProgram k Q) (t : ℕ)
+
+/-- Start at the query program's initial state with all `t` queries available and scan phase
+zero. -/
+def start : Control t k Q := (Fin.last t, p.start, 0)
+
+/-- Take one tape-control step toward the requested bit, branch on its value when reached, or
+halt with the query result. -/
+def command (c : Control t k Q) (a : Symbol) : Step (Control t k Q) :=
+ let (r, q, phase) := c
+ match p.step q with
+ | .halt b => .halt b
+ | .read i low high =>
+ if r.val = 0 then .halt false else
+ if phase.val = 0 then
+ if a = 0 then .move (r, q, offset i) 1 else .move (r, q, 0) 2
+ else if phase.val = 1 then .move (predFin r, if a = 2 then high else low, 0) 0
+ else .move (r, q, predFin phase) 1
+
+variable [Fintype Q]
+
+/-- Compile the bounded binary query controller into the universal machine's instruction table. -/
+noncomputable def machine : Program := compile (start p t) (command p t)
+
+/-- Count accepting paths with the specified tick budget, control state, input-head position,
+and initially blank work tape. -/
+noncomputable def countAt (input : Word) (pos : ℕ) (c : Control t k Q) (ticks : ℕ) : ℕ :=
+ paths (machine p t) ticks
+ (running (start p t) c (atPosition input pos) (Turing.Tape.mk₁ []))
+
+theorem countAt_step (input : Word) (pos : ℕ) (c : Control t k Q) (ticks : ℕ) :
+ countAt p t input pos c (ticks + 1) =
+ match command p t c (atPosition input pos).head with
+ | .halt b => if b then 1 else 0
+ | .move next dir => paths (machine p t) ticks
+ (running (start p t) next (moveTape (atPosition input pos) dir) (Turing.Tape.mk₁ [])) :=
+ by
+ have h := paths_running_succ (start p t) (command p t) c (atPosition input pos) (Turing.Tape.mk₁ []) ticks
+ cases hc : command p t c (atPosition input pos).head <;> simp only [hc] at h <;> exact h
+
+end QueryMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/QueryMachine.lean b/lean/OAI/Computability/VPVNP/QueryMachine.lean
new file mode 100644
index 0000000000..70ecd30672
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/QueryMachine.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.QueryScan
+
+/-!
+# Clocked simulation of a finite query program
+
+For every query the head scans to the end of the input, then back to the selected payload
+bit. The bound allows one final transition into a halting state, including on query timeout.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace QueryMachine
+
+open UniversalMachine TableCompiler QueryTape
+
+variable {k : ℕ} {Q : Type*} [Fintype Q] (p : QueryProgram k Q) (t : ℕ)
+
+private theorem readAtEnd (pre : Word) (x : Fin k → Bool) (r : Fin (t + 1)) (q : Q)
+ {i : Fin k} {low high : Q} (hr : r.val ≠ 0) (hq : p.step q = .read i low high)
+ (budget : ℕ) :
+ countAt p t (pre ++ List.ofFn x) (pre.length + k) (r, q, 0) (k - i.val + 1 + budget) =
+ countAt p t (pre ++ List.ofFn x) (pre.length + i.val)
+ (predFin r, if x i then high else low, 0) budget := by
+ let input := pre ++ List.ofFn x
+ let base := pre.length + i.val
+ let rem := k - i.val - 1
+ have hphase : rem + 1 < k + 1 := by dsimp [rem]; omega
+ let one : Fin (k + 1) := ⟨1, by omega⟩
+ have hlast : input.length = pre.length + k := by simp [input]
+ have hblank : (atPosition input (pre.length + k)).head = 0 := hlast ▸ head_atPosition_length input
+ have hpos : pre.length + k = (base + rem) + 1 := by dsimp [base, rem]; omega
+ have hoff : offset i = ⟨rem + 1, hphase⟩ := by apply Fin.ext; dsimp [offset, rem]; omega
+ have depart (j : ℕ) :
+ countAt p t input (pre.length + k) (r, q, 0) (j + 1) =
+ countAt p t input (base + rem) (r, q, ⟨rem + 1, hphase⟩) j := by
+ rw [countAt_step, hblank]
+ simp [command, hq, hr, hoff, moveTape, hpos, move_left_atPosition_succ, countAt]
+ have read : countAt p t input base (r, q, one) (budget + 1) =
+ countAt p t input base (predFin r, if x i then high else low, 0) budget := by
+ rw [countAt_step, show (atPosition input base).head = _ from head_atPosition_suffix pre x i]
+ cases x i <;> simp [command, hq, hr, one, countAt, moveTape]
+ have htime : k - i.val + 1 + budget = (rem + (budget + 1)) + 1 := by dsimp [rem]; omega
+ rw [htime]
+ exact (depart _).trans ((scanLeft p t input hr hq base rem (budget + 1) hphase).trans read)
+
+private theorem runAt (pre : Word) (x : Fin k → Bool) (d : ℕ) (r : Fin (t + 1))
+ (hrd : r.val = d) (q : Q) (pos ticks : ℕ) (hpos : pos ≤ pre.length + k)
+ (ht : d * (pre.length + k + k + 1) + 1 ≤ ticks) :
+ countAt p t (pre ++ List.ofFn x) pos (r, q, 0) ticks = (p.eval x d q).toNat := by
+ induction d generalizing r q pos ticks with
+ | zero =>
+ obtain ⟨ticks, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : ticks ≠ 0)
+ rw [countAt_step]
+ cases hq : p.step q with
+ | halt b => cases b <;> simp [command, hq, QueryProgram.eval]
+ | read i low high => simp [command, hq, hrd, QueryProgram.eval]
+ | succ d ih =>
+ cases hq : p.step q with
+ | halt b =>
+ obtain ⟨ticks, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : ticks ≠ 0)
+ rw [countAt_step]
+ cases b <;> simp [command, hq, QueryProgram.eval]
+ | read i low high =>
+ let input := pre ++ List.ofFn x
+ let dist := pre.length + k - pos
+ let budget := ticks - (dist + (k - i.val + 1))
+ have hr : r.val ≠ 0 := by omega
+ have hlen : input.length = pre.length + k := by simp [input]
+ have hend : pos + dist = input.length := by dsimp [dist]; omega
+ rw [Nat.succ_mul] at ht
+ have hbudget : d * (pre.length + k + k + 1) + 1 ≤ budget := by dsimp [budget, dist]; omega
+ have htime : ticks = dist + (k - i.val + 1 + budget) := by dsimp [budget, dist]; omega
+ have hpred : (predFin r).val = d := by dsimp [predFin]; omega
+ simp only [QueryProgram.eval, hq]
+ rw [htime, scanRight p t input hr hq pos dist _ hend, hlen, readAtEnd p t pre x r q hr hq]
+ exact ih (predFin r) hpred _ (pre.length + i.val) budget (by omega) hbudget
+
+/-- At every clock above the bound the literal table counts exactly the query result. -/
+theorem correct (pre : Word) (x : Fin k → Bool) (ticks : ℕ)
+ (ht : t * (pre.length + k + k + 1) + 1 ≤ ticks) :
+ paths (machine p t) ticks (initial (machine p t) (pre ++ List.ofFn x)) =
+ (p.eval x t p.start).toNat := by
+ rw [machine, initial_eq_running]
+ exact runAt p t pre x t (Fin.last t) rfl p.start 0 ticks (Nat.zero_le _) ht
+
+end QueryMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/QueryPrefix.lean b/lean/OAI/Computability/VPVNP/QueryPrefix.lean
new file mode 100644
index 0000000000..5efd03b8da
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/QueryPrefix.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.QueryMachine
+import OAI.Computability.VPVNP.QueryClock
+import OAI.Computability.VPVNP.ProgramLength
+
+/-!
+# Query predicates as coefficients of the explicit family
+
+The literal encoding of a bounded query program supplies a fixed prefix.
+Appending any payload computes its Boolean query result with the universal
+coefficient machine's prescribed clock.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace QueryMachine
+
+open UniversalMachine
+
+/-- A single program prefix compiles the entire finite query program at a
+given query budget. Every payload is interpreted with the fixed clock of §1.1. -/
+theorem exists_prefix {k : ℕ} {Q : Type*} [Fintype Q] (p : QueryProgram k Q) (t : ℕ) :
+ ∃ (l : ℕ) (bits : Fin l → Bool),
+ l ≤ 1000 * ((t + 1) * Fintype.card Q * (k + 1) + 1) ^ 2 ∧
+ ∀ x : Fin k → Bool, acceptingCount (Fin.append bits x) = (p.eval x t p.start).toNat := by
+ let pre := programPrefix (machine p t)
+ have hc : (machine p t).extra = (t + 1) * Fintype.card Q * (k + 1) := by
+ simp [machine, TableCompiler.compile, Control, Nat.mul_assoc]
+ refine ⟨pre.length, pre.get, (programPrefix_length_le _).trans_eq (by rw [hc]), ?_⟩
+ intro x
+ have hq : 0 < Fintype.card Q := Fintype.card_pos_iff.mpr ⟨p.start⟩
+ have hstates : t + 1 ≤ (machine p t).extra := by
+ rw [hc]
+ exact (Nat.le_mul_of_pos_right _ hq).trans (Nat.le_mul_of_pos_right _ (by omega))
+ simp only [acceptingCount, List.ofFn_fin_append, List.ofFn_get, pre, decode_programPrefix]
+ exact correct p t pre x _ (querySteps_le_clock rfl (queryPrefix_lower hstates))
+
+end QueryMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/QueryProgram.lean b/lean/OAI/Computability/VPVNP/QueryProgram.lean
new file mode 100644
index 0000000000..c969da6f23
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/QueryProgram.lean
@@ -0,0 +1,44 @@
+import Mathlib.Init
+
+/-!
+# Finite control for a binary query program
+
+A read addresses one of the fixed payload bits and branches to another
+control state. The clock counts payload queries. Halting consumes no query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+/-- One binary query action, either a Boolean halt or a payload-bit read with low and high
+successor states. -/
+inductive QueryStep (k : Nat) (Q : Type*) where
+ | halt (accept : Bool)
+ | read (i : Fin k) (low high : Q)
+
+/-- A binary query program on `k` payload bits, specified by its initial state and the action
+at each state. -/
+structure QueryProgram (k : Nat) (Q : Type*) where
+ /-- State from which execution of the query program begins. -/
+ start : Q
+ /-- Action prescribed at each query state, including the addressed bit and the two successors
+ for a read. -/
+ step : Q → QueryStep k Q
+
+/-- Evaluate from a given state, spending one unit of fuel per bit read and rejecting a read
+attempted at zero fuel. -/
+def QueryProgram.eval {k : Nat} {Q : Type*} (p : QueryProgram k Q) (x : Fin k → Bool) :
+ Nat → Q → Bool
+ | 0, q =>
+ match p.step q with
+ | .halt b => b
+ | .read _ _ _ => false
+ | fuel + 1, q =>
+ match p.step q with
+ | .halt b => b
+ | .read i low high => p.eval x fuel (if x i then high else low)
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/QueryScan.lean b/lean/OAI/Computability/VPVNP/QueryScan.lean
new file mode 100644
index 0000000000..1c89131c90
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/QueryScan.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.QueryControl
+
+/-!
+# Traversal time for a payload query
+
+The rightward scan stops on the blank after the entire input. The leftward scan
+then counts down to phase one, when the selected payload bit is under the head.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace QueryMachine
+
+open UniversalMachine TableCompiler QueryTape
+
+variable {k : ℕ} {Q : Type*} [Fintype Q] (p : QueryProgram k Q) (t : ℕ) (input : Word)
+ {r : Fin (t + 1)} {q : Q} {i : Fin k} {low high : Q}
+
+/-- Phase zero scans each remaining input bit in one transition. -/
+theorem scanRight (hr : r.val ≠ 0) (h : p.step q = .read i low high)
+ (pos dist budget : ℕ) (hend : pos + dist = input.length) :
+ countAt p t input pos (r, q, 0) (dist + budget) =
+ countAt p t input input.length (r, q, 0) budget := by
+ induction dist generalizing pos with
+ | zero => simpa using congrArg (fun j => countAt p t input j (r, q, 0) budget) hend
+ | succ dist ih =>
+ have hpos : pos < input.length := by omega
+ have hbit : (atPosition input pos).head ≠ 0 := by
+ rw [head_atPosition_of_lt _ _ hpos]
+ split <;> decide
+ have hcommand : command p t (r, q, 0) (atPosition input pos).head =
+ .move (r, q, 0) 2 := by simp [command, h, hr, hbit]
+ rw [Nat.succ_add, countAt_step, hcommand]
+ change paths (machine p t) (dist + budget)
+ (running (start p t) (r, q, 0) ((atPosition input pos).move .right) _) = _
+ rw [move_right_atPosition]
+ exact ih (pos + 1) (by omega)
+
+/-- Each left move lowers the phase counter by one until the read phase. -/
+theorem scanLeft (hr : r.val ≠ 0) (h : p.step q = .read i low high)
+ (base rem budget : ℕ) (hrem : rem + 1 < k + 1) :
+ countAt p t input (base + rem) (r, q, ⟨rem + 1, hrem⟩) (rem + budget) =
+ countAt p t input base (r, q, ⟨1, by omega⟩) budget := by
+ induction rem with
+ | zero => simp
+ | succ rem ih =>
+ have hprev : rem + 1 < k + 1 := by omega
+ have hcommand (a : Symbol) : command p t (r, q, ⟨rem.succ + 1, hrem⟩) a =
+ .move (r, q, ⟨rem + 1, hprev⟩) 1 := by
+ simp [command, h, hr, predFin]
+ rw [Nat.succ_add rem budget, countAt_step, hcommand]
+ change paths (machine p t) (rem + budget)
+ (running (start p t) (r, q, ⟨rem + 1, hprev⟩)
+ ((atPosition input ((base + rem) + 1)).move .left) _) = _
+ rw [move_left_atPosition_succ]
+ exact ih hprev
+
+end QueryMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/QueryTape.lean b/lean/OAI/Computability/VPVNP/QueryTape.lean
new file mode 100644
index 0000000000..59c23c005d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/QueryTape.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.UniversalMachine
+
+/-!
+# Scanning the input tape of the universal coefficient machine
+
+Moving the head preserves the input. After scanning the program prefix, the cell
+at offset `i` contains the symbol encoding the `i`th payload bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace QueryTape
+
+open Turing
+
+/-- Input tape with its head at cell `pos`, counting from the first input bit. -/
+def atPosition (input : List Bool) (pos : ℕ) : Tape (Fin 3) :=
+ (Tape.move Dir.right)^[pos] (Tape.mk₁ (input.map fun b => if b then 2 else 1))
+
+theorem atPosition_zero (input : List Bool) :
+ atPosition input 0 = Tape.mk₁ (input.map fun b => if b then 2 else 1) := rfl
+
+theorem move_right_atPosition (input : List Bool) (pos : ℕ) :
+ (atPosition input pos).move .right = atPosition input (pos + 1) :=
+ (Function.iterate_succ_apply' _ _ _).symm
+
+theorem move_left_atPosition_succ (input : List Bool) (pos : ℕ) :
+ (atPosition input (pos + 1)).move .left = atPosition input pos := by
+ rw [← move_right_atPosition, Tape.move_right_left]
+
+private theorem head_atPosition (input : List Bool) (pos : ℕ) :
+ (atPosition input pos).head = (input.map fun b => if b then 2 else 1).getI pos := by
+ simp only [atPosition, Tape.move_right_n_head, Tape.mk₁, Tape.mk₂, Tape.mk'_nth_nat,
+ ListBlank.nth_mk]
+
+theorem head_atPosition_of_lt (input : List Bool) (pos : ℕ) (hp : pos < input.length) :
+ (atPosition input pos).head = if input[pos] then 2 else 1 := by
+ rw [head_atPosition, List.getI_eq_getElem _ (by simpa using hp), List.getElem_map]
+
+theorem head_atPosition_length (input : List Bool) :
+ (atPosition input input.length).head = 0 := by
+ rw [head_atPosition, List.getI_eq_default _ (by simp)]
+ rfl
+
+theorem head_atPosition_suffix {k : ℕ} (pre : List Bool) (x : Fin k → Bool) (i : Fin k) :
+ (atPosition (pre ++ List.ofFn x) (pre.length + i.val)).head = if x i then 2 else 1 := by
+ rw [head_atPosition_of_lt _ _ (by simp),
+ List.getElem_append_right (by omega)]
+ simp
+
+end QueryTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMApplications.lean b/lean/OAI/Computability/VPVNP/RAMApplications.lean
new file mode 100644
index 0000000000..26d8f5b9e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMApplications.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.CursorBounds
+import OAI.Computability.VPVNP.RAMSortAddressBounds
+import OAI.Computability.VPVNP.RAMValidatorPaths
+
+/-!
+# The live and virtual applications of the RAM transcript lemma
+
+The live processors use a private call clock `n^10000`. The processors
+of the virtual RAM use `n^10`. Both inherit the same quartic word width.
+The bounds below hold on every local incident vector and branch stream,
+including those obtained from a tensor expansion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open Filter Compression CursorBounds RAMLayout
+
+/-- Enough word space for every record and for the physical bit addresses,
+together with the numerical bounds used by the local validator clock. -/
+structure ProcessorBudget (n d e w : ℕ) : Prop where
+ tags : 2 ≤ w
+ capFits : 2^d * 2^e < 2^w
+ addresses : RAMSort.addressEnvelope (2+e) d w < 2^w
+ word_le : w ≤ n
+ bucket_le : 2^e ≤ 2*n
+ phase_le : 2+e+d+1 ≤ n
+
+private theorem eventually_processorBudget {B : ℕ} (hB : 1 ≤ B) :
+ ∀ᶠ n : ℕ in atTop, ∀ d e, d ≤ (B+2)*Nat.clog 2 n → 2^e ≤ 2*n →
+ ProcessorBudget n d e (CursorBounds.wordBits B n) := by
+ filter_upwards [eventually_ge_atTop (2^(B+6)),
+ eventually_word_stage_le B (B+6)] with n hn hw
+ intro d e hd hH
+ have hnpos : 0 < n := (Nat.two_pow_pos _).trans_le hn
+ have hr := log2_le_addressWidth hB n
+ have hl := clog_le_log2_succ n
+ have hd' := hd.trans (Nat.mul_le_mul_left (B+2) hl)
+ have he := (Nat.le_log2 (by omega : 2*n ≠ 0)).mpr hH
+ rw [Nat.log2_two_mul hnpos.ne'] at he
+ have hsum : 2+e+d+1 ≤ (B+6)*(n.log2+1) := by rw [Nat.add_mul] at hd' ⊢; omega
+ obtain ⟨hword, hstage⟩ := hw (addressWidth B n) _ (Nat.mul_le_mul_left _ hl) hsum
+ have hk := ((Nat.le_log2 hnpos.ne').mpr hn).trans hr
+ have hscale := hsum.trans (Nat.mul_le_mul_left (B+6) (Nat.succ_le_succ hr))
+ change 2+e+d+1 ≤ (B+6)*(addressWidth B n + 1) at hscale
+ have hde : d+e ≤ (B+6)*(addressWidth B n + 1) := by omega
+ obtain ⟨htags, hcap⟩ := RAMSerialization.word_capacity _ _ _ _ hde (by omega)
+ have hsq : 2+e+d ≤ (addressWidth B n+10)^2 := by
+ rw [pow_two]
+ exact (by omega : 2+e+d ≤ (B+6)*(addressWidth B n + 1)).trans
+ (Nat.mul_le_mul (by omega) (by omega))
+ exact ⟨htags, hcap, RAMSort.addressEnvelope_lt_paperWord hsq, hword, hH, hstage⟩
+
+private theorem bucket_le_twice {x : ℝ} (hx : 0 ≤ x) (hx' : x ≤ 1) {n : ℕ} (hn : 1 ≤ n) :
+ 2^bucketExponent x n ≤ 2*n := by
+ have hh := (bucketExponent_bounds hx hn).2
+ have hpow : (n:ℝ)^x ≤ n := by
+ simpa using Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast hn) hx'
+ exact_mod_cast hh.trans (mul_le_mul_of_nonneg_left hpow (by norm_num : (0:ℝ) ≤ 2))
+
+/-- One eventual threshold works for both processors' message formats and
+their cutoffs in §§10–12. -/
+theorem eventually_bothProcessorBudgets {B : ℕ} (hB : 1 ≤ B) {δ : ℝ} (hδ : 0 ≤ δ) (hδ' : δ ≤ 1) :
+ ∀ᶠ n : ℕ in atTop,
+ ProcessorBudget n (addressWidth B n) (bucketExponent (1-δ) n) (CursorBounds.wordBits B n) ∧
+ ProcessorBudget n (virtualBits B n) (roundedUp 1 4 n) (CursorBounds.wordBits B n) := by
+ filter_upwards [eventually_processorBudget hB, eventually_ge_atTop 1] with n h hn
+ refine ⟨h _ _ (Nat.mul_le_mul_right _ (by omega)) (bucket_le_twice (by linarith) (by linarith) hn),
+ h _ _ (virtualBits_le ..) ?_⟩
+ rw [roundedUp_eq]
+ exact bucket_le_twice (by norm_num) (by norm_num) hn
+
+/-- Section 10's live `n^100030` bound and Section 12's virtual `n^130`
+bound apply uniformly to the concrete instruction table and all local input
+values at the respective lengths. -/
+theorem ProcessorBudget.validate_clock {n d e w p r k u : ℕ} (b : ProcessorBudget n d e w)
+ (M : PrivateRAM.Machine w p r k) (hn : 2048 ≤ n) (hk : k+2 ≤ n) (hu : 1 ≤ u)
+ (initial header : Word w) (v : Fin (2^d)) (inc : Fin (width d (2^e) w) → Bool)
+ (bits : List Bool) :
+ (M.validateIncident (n^u) initial header b.tags b.capFits v inc bits).2 ≤ n^(10*u+30) :=
+ M.validateIncident_clock n u _ _ _ _ _ _ _ hn hu hk b.word_le b.bucket_le b.phase_le
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMBitLocality.lean b/lean/OAI/Computability/VPVNP/RAMBitLocality.lean
new file mode 100644
index 0000000000..643444d9ef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMBitLocality.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.RAMBitTranscript
+import OAI.Computability.VPVNP.RAMValidatorLocality
+
+/-!
+# The incident-bit input of a single RAM validator
+
+A site's predicate depends only on its own header and its incident vector of
+the width in equation (10.1). Equality of two such vectors gives equality of
+the adjacent successor messages and both messages of every incident sorting
+exchange. This applies to malformed assignments as well as accepted ones.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMLayout RAMSerialization
+
+variable {d e w : ℕ} {C : Type*}
+
+/-- One site's physical bit vector in the contiguous layout of equation (10.1). -/
+def incidentBits (bits : RawAssignment d e w) (v : Fin (2 ^ d)) : Fin (width d (2 ^ e) w) → Bool :=
+ RAMLayout.incidentBits (sendArraysEquiv d (2 ^ e) w bits) v
+
+@[simp] theorem incidentBits_at (bits : RawAssignment d e w) (v : Fin (2 ^ d)) (p : Slot d (2 ^ e) w) :
+ incidentBits bits v (offset d (2 ^ e) w p) =
+ (incidentEquiv d (2 ^ e) w (sendArraysEquiv d (2 ^ e) w bits)).val (v, p) := by
+ simp [incidentBits]
+
+theorem incidentBits_sort_send (bits : RawAssignment d e w) (v : Fin (2 ^ d)) (l : Layer d)
+ (j : Fin (blockBits (2 ^ e) w)) :
+ incidentBits bits v (offset d (2 ^ e) w (.inr (l, 0, j))) =
+ (sendArraysEquiv d (2 ^ e) w bits).2 l v j := by
+ rw [incidentBits_at]
+ exact incident_send _ (.inr (l, v, j))
+
+theorem incidentBits_sort_receive (bits : RawAssignment d e w) (v : Fin (2 ^ d)) (l : Layer d)
+ (j : Fin (blockBits (2 ^ e) w)) :
+ incidentBits bits v (offset d (2 ^ e) w (.inr (l, 1, j))) =
+ (sendArraysEquiv d (2 ^ e) w bits).2 l (l.partner v) j := by
+ rw [incidentBits_at, incident_receive_sort]
+
+theorem incidentBits_successor_send (bits : RawAssignment d e w) (v : Fin (2 ^ d))
+ (hv : v.val + 1 < 2 ^ d) (j : Fin (8 * w)) :
+ incidentBits bits v (offset d (2 ^ e) w (.inl (0, j))) =
+ (sendArraysEquiv d (2 ^ e) w bits).1 ⟨v.val, by omega⟩ j := by
+ rw [incidentBits_at]
+ exact incident_send _ (.inl (⟨v.val, by omega⟩, j))
+
+theorem incidentBits_successor_receive (bits : RawAssignment d e w) (v : Fin (2 ^ d))
+ (hv : 0 < v.val) (j : Fin (8 * w)) :
+ incidentBits bits v (offset d (2 ^ e) w (.inl (1, j))) =
+ (sendArraysEquiv d (2 ^ e) w bits).1 ⟨v.val - 1, by have := v.isLt; omega⟩ j := by
+ rw [incidentBits_at, incident_receive_successor _ v hv j]
+
+theorem incidentBits_clamped (bits : RawAssignment d e w) (v : Fin (2 ^ d))
+ (p : Slot d (2 ^ e) w) (h : peer v p = none) :
+ incidentBits bits v (offset d (2 ^ e) w p) = false := by
+ rw [incidentBits_at]
+ exact incident_clamp _ _ h
+
+/-- Equality of all of the physical sender arrays consulted at a single site. -/
+private structure AgreeAt (a b : SendArrays d (2 ^ e) w) (v : Fin (2 ^ d)) : Prop where
+ successor : ∀ j : Fin (2 ^ d - 1), j.val = v.val ∨ j.val + 1 = v.val → a.1 j = b.1 j
+ sorting : ∀ l, a.2 l v = b.2 l v ∧ a.2 l (l.partner v) = b.2 l (l.partner v)
+
+private theorem agree_of_incident {a b : RawAssignment d e w} {v : Fin (2 ^ d)}
+ (h : incidentBits a v = incidentBits b v) :
+ AgreeAt (sendArraysEquiv d (2 ^ e) w a) (sendArraysEquiv d (2 ^ e) w b) v := by
+ constructor
+ · intro j hj
+ funext i
+ obtain he | he := hj
+ · have hs : v.val + 1 < 2 ^ d := by have := j.isLt; omega
+ have heq := congrFun h (offset d (2 ^ e) w (.inl (0, i)))
+ simpa only [incidentBits_successor_send _ v hs, ← he] using heq
+ · have hv : 0 < v.val := by omega
+ have heq := congrFun h (offset d (2 ^ e) w (.inl (1, i)))
+ have hij : v.val - 1 = j.val := by omega
+ simpa only [incidentBits_successor_receive _ v hv, hij] using heq
+ · intro l
+ constructor
+ · funext i
+ simpa only [incidentBits_sort_send] using congrFun h (offset d (2 ^ e) w (.inr (l, 0, i)))
+ · funext i
+ simpa only [incidentBits_sort_receive] using congrFun h (offset d (2 ^ e) w (.inr (l, 1, i)))
+
+private theorem AgreeAt.parsed {a b : SendArrays d (2 ^ e) w} {v : Fin (2 ^ d)} (hab : AgreeAt a b v)
+ (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) :
+ (unpackMessages (parseMessages hw hc a)).AgreeAt (unpackMessages (parseMessages hw hc b)) v := by
+ constructor
+ · intro j hj
+ simp [unpackMessages, parseMessages, hab.successor j hj]
+ · intro l
+ simp [unpackMessages, parseMessages, (hab.sorting l).1, (hab.sorting l).2]
+
+private theorem AgreeAt.formats {a b : SendArrays d (2 ^ e) w} {v : Fin (2 ^ d)} (hab : AgreeAt a b v)
+ (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) :
+ (OutgoingOK hw hc a v ↔ OutgoingOK hw hc b v) ∧ (IncomingOK hw hc a v ↔ IncomingOK hw hc b v) := by
+ constructor
+ · unfold OutgoingOK
+ apply and_congr
+ · split
+ · simp [messageBits, parseMessages, hab.successor ⟨v.val, by omega⟩ (.inl rfl)]
+ · rfl
+ · apply forall_congr'
+ intro l
+ simp [messageBits, parseMessages, (hab.sorting l).1]
+ · unfold IncomingOK
+ apply and_congr
+ · split
+ · have he : v.val - 1 + 1 = v.val := by omega
+ simp [messageBits, parseMessages, hab.successor ⟨v.val - 1, by have := v.isLt; omega⟩ (.inr he)]
+ · rfl
+ · apply forall_congr'
+ intro l
+ simp [messageBits, parseMessages, (hab.sorting l).2]
+
+/-- A site's validator is a function of its own header and incident bit vector.
+Both the canonicality test and the call/sort checks satisfy this locality. -/
+theorem bitValidator_congr (P : Program w C) (fuel : ℕ) (initial : Word w)
+ {header header' : ℕ → Word w} (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w)
+ {a b : RawAssignment d e w} {v : Fin (2 ^ d)} (hh : header v = header' v)
+ (hi : incidentBits a v = incidentBits b v) (rs : List (Report w)) :
+ BitValidator P fuel initial header hw hc a v rs ↔ BitValidator P fuel initial header' hw hc b v rs := by
+ have ha := agree_of_incident hi
+ have hf := ha.formats hw hc
+ exact and_congr (and_congr hf.1 hf.2) (validator_congr _ _ _ hh (ha.parsed hw hc) rs)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMBitTranscript.lean b/lean/OAI/Computability/VPVNP/RAMBitTranscript.lean
new file mode 100644
index 0000000000..0fc03c3c03
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMBitTranscript.lean
@@ -0,0 +1,204 @@
+import OAI.Computability.VPVNP.RAMMessageBounds
+import OAI.Computability.VPVNP.RAMSerialization
+import OAI.Computability.VPVNP.RAMSharedFields
+import OAI.Computability.VPVNP.RAMTranscript
+
+/-!
+# Parsimonious transcripts over individual shared bits
+
+Lemma 10.1 sums over bits on existing links. Each site parses its received
+fields, checks its outgoing fields for canonical encoding, and validates its
+local call reports. All accepted typed messages are representable, so replacing
+whole messages by their individual shared bits preserves the path count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMMemory RAMLayout RAMSerialization
+
+variable {d e w : ℕ} {C : Type*}
+
+/-- An assignment of one Boolean to every sending endpoint of an existing transcript link. -/
+abbrev RawAssignment (d e w : ℕ) := SharedBit d (2 ^ e) w → Bool
+
+/-- The sorting proof numbers each site block by its logarithmic length. -/
+def recordPosition (e : ℕ) : Fin (2 ^ (2 + e)) ≃ Fin (4 * 2 ^ e) :=
+ finCongr (by rw [pow_add]; rfl)
+
+/-- Word-bounded messages with exactly the fields present in the bit layout. -/
+abbrev PackedMessages (d e w : ℕ) :=
+ (Fin (2 ^ d - 1) → Successor w (2 ^ d * 2 ^ e)) ×
+ (Layer d → Fin (2 ^ d) → Fin (4 * 2 ^ e) → Option (WordRecord w))
+
+/-- Convert packed successor words and sorting blocks to chain and memory messages, widening
+each present record and retaining its position. -/
+def unpackMessages (p : PackedMessages d e w) : Messages d e w where
+ chain i := ⟨(p.1 i).cost.val, (p.1 i).state⟩
+ memory := ⟨fun l v j ↦ ⟨(p.2 l v (recordPosition e j)).map WordRecord.record⟩,
+ fun i ↦ (p.1 i).lastRecord.map WordRecord.record⟩
+
+/-- Each successor cost fits the total site budget, and every record carried by the sorting and
+successor links fits the chosen word width. -/
+def Messages.FitsWord (m : Messages d e w) : Prop :=
+ (∀ j, (m.chain j).cost ≤ 2 ^ d * 2 ^ e) ∧ m.memory.FitsWord
+
+/-- Pack bounded chain costs, states, last records and sorting blocks into the fixed successor
+and sorting message formats. -/
+def packMessages (m : Messages d e w) (h : m.FitsWord) : PackedMessages d e w :=
+ (fun i ↦ ⟨(m.chain i).state, ⟨(m.chain i).cost, Nat.lt_succ_of_le (h.1 i)⟩,
+ narrowSlot (m.memory.lastRecords i) (h.2.2 i)⟩,
+ fun l v j ↦ narrowSlot (m.memory.sortSends l v ((recordPosition e).symm j)).record (h.2.1 l v _))
+
+theorem unpack_pack (m : Messages d e w) (h : m.FitsWord) :
+ unpackMessages (packMessages m h) = m := by
+ apply Messages.ext
+ · rfl
+ · apply MemoryMessages.ext
+ · funext l v j
+ apply congrArg OrderedSlot.mk
+ simp [packMessages]
+ · funext j
+ exact widen_narrowSlot _ _
+
+private theorem narrow_widen (r : Option (WordRecord w)) (h) :
+ narrowSlot (r.map WordRecord.record) h = r := by
+ cases r with
+ | none => rfl
+ | some r => cases r; rfl
+
+private theorem pack_unpack (p : PackedMessages d e w) (h) :
+ packMessages (unpackMessages p) h = p := by
+ apply Prod.ext
+ · funext i
+ change Successor.mk (p.1 i).state (p.1 i).cost _ = p.1 i
+ rw [show narrowSlot ((unpackMessages p).memory.lastRecords i) (h.2.2 i) =
+ (p.1 i).lastRecord from narrow_widen _ _]
+ · funext l v j
+ simp [packMessages, unpackMessages, narrow_widen]
+
+theorem validators_fitWord (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ {m : Messages d e w} {reports : Fin (2 ^ d) → List (Report w)} (hword : 2 ^ d * 2 ^ e < 2 ^ w)
+ (h : ∀ v, Validator P fuel initial header m v (reports v)) : m.FitsWord := by
+ obtain ⟨hs, hm, _⟩ := (validators_iff ..).mp h
+ exact ⟨sitesPass_wire_cost hs, hm ▸ actualMemoryMessages_fitsWord header
+ (successor_sound (Nat.two_pow_pos d) hs).2.2.1 hword⟩
+
+/-- Encode each outgoing message independently. -/
+def messageBits (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (p : PackedMessages d e w) :
+ SendArrays d (2 ^ e) w :=
+ (fun i ↦ (successorFormat hw hc).encode (p.1 i),
+ fun l v ↦ (blockFormat (2 ^ e) hw).encode (p.2 l v))
+
+/-- Parsing uses the fixed length of each field. Malformed patterns have a
+candidate parse but fail the sender's canonicality check below. -/
+def parseMessages (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (b : SendArrays d (2 ^ e) w) :
+ PackedMessages d e w :=
+ (fun i ↦ (successorFormat hw hc).parse ((arrayBits 8 w).symm (b.1 i)),
+ fun l v ↦ (blockFormat (2 ^ e) hw).parse ((arrayBits _ w).symm (b.2 l v)))
+
+@[simp] theorem parse_messageBits (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w)
+ (p : PackedMessages d e w) : parseMessages hw hc (messageBits hw hc p) = p := by
+ simp [parseMessages, messageBits, Format.encode, Format.parse_words]
+
+/-- One successor-send check when that edge exists, and one send check for
+each cross-site layer. Both sides inspect only the fields at the specified site. -/
+def OutgoingOK (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (b : SendArrays d (2 ^ e) w)
+ (v : Fin (2 ^ d)) : Prop :=
+ let a := messageBits hw hc (parseMessages hw hc b)
+ (if h : v.val + 1 < 2 ^ d then
+ b.1 ⟨v.val, by omega⟩ = a.1 ⟨v.val, by omega⟩ else True) ∧ ∀ l, b.2 l v = a.2 l v
+
+private theorem outgoingOK_iff (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (b : SendArrays d (2 ^ e) w) :
+ (∀ v, OutgoingOK hw hc b v) ↔ b = messageBits hw hc (parseMessages hw hc b) := by
+ constructor
+ · intro h
+ apply Prod.ext
+ · funext j
+ have hj := j.isLt
+ let v : Fin (2 ^ d) := ⟨j.val, by omega⟩
+ have he := (h v).1
+ simpa [v, show j.val + 1 < 2 ^ d by omega] using he
+ · funext l v
+ exact (h v).2 l
+ · intro h v
+ unfold OutgoingOK
+ constructor
+ · split
+ · exact congrFun (congrArg Prod.fst h) _
+ · trivial
+ · intro l
+ exact congrFun (congrFun (congrArg Prod.snd h) l) v
+
+/-- Check the incoming predecessor field when present and the incoming
+sorting blocks at their XOR partners. These checks reject malformed receives
+even when evaluating a single site on an arbitrary incident bit pattern. -/
+def IncomingOK (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (b : SendArrays d (2 ^ e) w)
+ (v : Fin (2 ^ d)) : Prop :=
+ let a := messageBits hw hc (parseMessages hw hc b)
+ (if h : 0 < v.val then
+ b.1 ⟨v.val - 1, by have := v.isLt; omega⟩ = a.1 ⟨v.val - 1, by have := v.isLt; omega⟩
+ else True) ∧ ∀ l, b.2 l (l.partner v) = a.2 l (l.partner v)
+
+theorem incomingOK_messageBits (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w)
+ (p : PackedMessages d e w) (v : Fin (2 ^ d)) : IncomingOK hw hc (messageBits hw hc p) v := by
+ simp [IncomingOK]
+
+/-- The site validator applied to raw link bits. Missing end fields carry
+zero by construction of the layout, and genuine fields use their unique source. -/
+def BitValidator (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) (bits : RawAssignment d e w)
+ (v : Fin (2 ^ d)) (rs : List (Report w)) : Prop :=
+ let arrays := sendArraysEquiv d (2 ^ e) w bits
+ (OutgoingOK hw hc arrays v ∧ IncomingOK hw hc arrays v) ∧
+ Validator P fuel initial header (unpackMessages (parseMessages hw hc arrays)) v rs
+
+/-- Shared-bit assignments together with a list of local call reports at each site, subject to
+every site's bit validator. -/
+abbrev BitJointPaths (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) :=
+ {t : RawAssignment d e w × (Fin (2 ^ d) → List (Report w)) //
+ ∀ v, BitValidator P fuel initial header hw hc t.1 v (t.2 v)}
+
+/-- The exact bijection between accepted joint transcripts in their typed and
+bit-level forms. In particular padding and clamped fields add no choices. -/
+def jointBitEquiv (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) :
+ TypedJointPaths P fuel initial header d e ≃ BitJointPaths P fuel initial header hw hc where
+ toFun t :=
+ let h := validators_fitWord P fuel initial header hc t.property
+ let a := messageBits hw hc (packMessages t.val.1 h)
+ ⟨⟨(sendArraysEquiv d (2 ^ e) w).symm a, t.val.2⟩, by
+ intro v
+ simp only [BitValidator, Equiv.apply_symm_apply, a, parse_messageBits, unpack_pack]
+ exact ⟨⟨(outgoingOK_iff ..).mpr (by simp) v, incomingOK_messageBits ..⟩, t.property v⟩⟩
+ invFun t := ⟨⟨unpackMessages (parseMessages hw hc (sendArraysEquiv d (2 ^ e) w t.val.1)),
+ t.val.2⟩, fun v ↦ (t.property v).2⟩
+ left_inv t := by
+ apply Subtype.ext
+ apply Prod.ext
+ · simp [unpack_pack]
+ · rfl
+ right_inv t := by
+ apply Subtype.ext
+ apply Prod.ext
+ · apply (sendArraysEquiv d (2 ^ e) w).injective
+ have hout := (outgoingOK_iff hw hc _).mp (fun v ↦ (t.property v).1.1)
+ simpa [pack_unpack] using hout.symm
+ · rfl
+
+/-- Lemma 10.1's parsimonious correspondence for the exact shared-bit layout. -/
+noncomputable def bitTranscriptEquiv (P : Program w C) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w) :
+ ActualPaths P fuel initial (initialMemory (2^d) header) (withinCaps (2^d) (2^e)) ≃
+ BitJointPaths P fuel initial header hw hc :=
+ (transcriptEquiv ..).trans (jointBitEquiv ..)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMBoundary.lean b/lean/OAI/Computability/VPVNP/RAMBoundary.lean
new file mode 100644
index 0000000000..f209475d7b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMBoundary.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.RAMMemory
+import Mathlib.Data.List.OfFn
+
+/-!
+# Last-record fields in the distributed RAM transcript
+
+In Lemma 10.1 each interior successor link carries the final physical slot of its
+source's sorted block. The receiving validator uses this slot as the predecessor
+of its first record. Flattening the blocks gives precisely the same read checks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMBoundary
+
+open RAMMemory
+
+variable {S B : ℕ} {Word : Type*}
+
+/-- Each interior successor edge has one shared last-record field. -/
+abbrev Sends (S : ℕ) (Word : Type*) := Fin (S - 1) → Option (Record Word)
+
+/-- Physical slots in site-major order. -/
+def flat (blocks : Fin S → Fin B → Option (Record Word)) : List (Option (Record Word)) :=
+ (List.ofFn fun v ↦ List.ofFn (blocks v)).flatten
+
+/-- Last slot of a nonempty block, including its padding if present. -/
+def lastSlot (hB : 0 < B) (block : Fin B → Option (Record Word)) : Option (Record Word) :=
+ block ⟨B - 1, by omega⟩
+
+/-- The fields prescribed by the final sorted blocks. -/
+def actual (hB : 0 < B) (blocks : Fin S → Fin B → Option (Record Word)) : Sends S Word :=
+ fun i ↦ lastSlot hB (blocks ⟨i.val, by have := i.isLt; omega⟩)
+
+/-- The physical send at the final site is clamped. -/
+def outgoing (sent : Sends S Word) (v : Fin S) : Option (Record Word) :=
+ if h : v.val + 1 < S then sent ⟨v.val, by omega⟩ else none
+
+private def receiveFrom (initial : Option (Record Word)) (sent : Sends S Word) :
+ Fin S → Option (Record Word)
+ | ⟨0, _⟩ => initial
+ | ⟨i + 1, _⟩ => sent ⟨i, by omega⟩
+
+/-- An incoming field is the preceding site's shared send. The first receive
+has the clamped value, so a read with no preceding write must return zero. -/
+def receive (sent : Sends S Word) (v : Fin S) : Option (Record Word) :=
+ receiveFrom none sent v
+
+@[simp] theorem receive_first (sent : Sends (S + 1) Word) : receive sent 0 = none := rfl
+
+@[simp] theorem outgoing_last (sent : Sends (S + 1) Word) :
+ outgoing sent (Fin.last S) = none := by simp [outgoing]
+
+theorem receive_succ (sent : Sends (S + 1) Word) (v : Fin S) :
+ receive sent v.succ = outgoing sent v.castSucc := by
+ simp only [outgoing, Fin.val_castSucc, Nat.add_lt_add_iff_right, v.isLt, dite_true]
+ rfl
+
+/-- At a singleton site both endpoint fields are clamped and there are no interior sends. -/
+theorem singleton_clamps (sent : Sends 1 Word) :
+ outgoing sent 0 = none ∧ receive sent 0 = none := ⟨rfl, rfl⟩
+
+variable [Zero Word]
+
+/-- The validator checks each read using its incoming field and, when a successor
+exists, checks its outgoing field against its own final physical slot. -/
+def checkAt (hB : 0 < B) (sent : Sends S Word) (v : Fin S)
+ (block : Fin B → Option (Record Word)) : Prop :=
+ PaddedCheck (receive sent v) (List.ofFn block) ∧
+ (v.val + 1 < S → outgoing sent v = lastSlot hB block)
+
+/-- Apply the one-site validator to the corresponding block of the sorted array. -/
+def checks (hB : 0 < B) (blocks : Fin S → Fin B → Option (Record Word))
+ (sent : Sends S Word) (v : Fin S) : Prop := checkAt hB sent v (blocks v)
+
+omit [Zero Word] in
+private theorem block_last (hB : 0 < B) (block : Fin B → Option (Record Word)) :
+ (List.ofFn block).getLast? = some (lastSlot hB block) := by
+ have hne : List.ofFn block ≠ [] := mt List.ofFn_eq_nil_iff.mp (Nat.ne_of_gt hB)
+ rw [List.getLast?_eq_some_getLast hne, List.getLast_ofFn]
+ rfl
+
+private theorem paddedCheck_flat_iff (hB : 0 < B) (blocks : Fin S → Fin B → Option (Record Word))
+ (previous : Option (Record Word)) :
+ PaddedCheck previous (flat blocks) ↔
+ ∀ v, PaddedCheck (receiveFrom previous (actual hB blocks) v) (List.ofFn (blocks v)) := by
+ induction S generalizing previous with
+ | zero => simp [flat, PaddedCheck]
+ | succ S ih =>
+ let rest := fun v : Fin S ↦ blocks v.succ
+ have hflat : flat blocks = List.ofFn (blocks 0) ++ flat rest := by
+ unfold flat
+ rw [List.ofFn_succ, List.flatten_cons]
+ rw [hflat, paddedCheck_append, block_last hB, Option.getD_some, ih rest, Fin.forall_fin_succ]
+ refine and_congr Iff.rfl (forall_congr' fun v ↦ ?_)
+ have hreceive : receiveFrom (lastSlot hB (blocks 0)) (actual hB rest) v =
+ receiveFrom previous (actual hB blocks) v.succ := by
+ rcases v with ⟨i, hi⟩
+ cases i <;> rfl
+ rw [hreceive]
+
+/-- The outgoing checks force the complete assignment of interior fields.
+The remaining site checks are equivalent to one scan of the physical array. -/
+theorem checks_iff (hB : 0 < B) (blocks : Fin S → Fin B → Option (Record Word))
+ (sent : Sends S Word) :
+ (∀ v, checks hB blocks sent v) ↔ PaddedCheck none (flat blocks) ∧ sent = actual hB blocks := by
+ constructor
+ · intro hv
+ have he : sent = actual hB blocks := by
+ funext i
+ have hi : i.val + 1 < S := by have := i.isLt; omega
+ let v : Fin S := ⟨i.val, by omega⟩
+ simpa only [v, outgoing, hi, dite_eq_left, actual] using (hv v).2 hi
+ subst sent
+ exact ⟨(paddedCheck_flat_iff hB blocks none).mpr (fun v ↦ (hv v).1), rfl⟩
+ · rintro ⟨hp, rfl⟩ v
+ refine ⟨(paddedCheck_flat_iff hB blocks none).mp hp v, fun hv ↦ ?_⟩
+ simp [outgoing, hv, actual]
+
+/-- Exactly one shared last-record assignment passes all the local checks
+when the flattened physical array passes its global predecessor check. -/
+theorem existsUnique_checks_iff (hB : 0 < B) (blocks : Fin S → Fin B → Option (Record Word)) :
+ (∃! sent : Sends S Word, ∀ v, checks hB blocks sent v) ↔ PaddedCheck none (flat blocks) := by
+ constructor
+ · rintro ⟨sent, h, _⟩
+ exact ((checks_iff hB blocks sent).mp h).1
+ · intro h
+ exact ⟨actual hB blocks, (checks_iff ..).mpr ⟨h, rfl⟩,
+ fun sent hs ↦ ((checks_iff ..).mp hs).2⟩
+
+end RAMBoundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMBuckets.lean b/lean/OAI/Computability/VPVNP/RAMBuckets.lean
new file mode 100644
index 0000000000..2ac9911503
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMBuckets.lean
@@ -0,0 +1,295 @@
+import Mathlib.Data.List.Basic
+import Mathlib.Data.Nat.Basic
+
+/-!
+# Partitioning RAM calls by cumulative cost
+
+In Lemma 10.1 of *VP and VNP differ over every field*, the site of a call is
+determined by its starting cost. A call costs one plus its number of external
+probes. The construction below preserves the full sequence of calls, so calls
+with identical costs but different nondeterministic choices remain distinct.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMBuckets
+
+variable {Call : Type*}
+
+/-- Cost of a contiguous sequence of calls. -/
+def cost (probes : Call → ℕ) : List Call → ℕ
+ | [] => 0
+ | a :: xs => (1 + probes a) + cost probes xs
+
+@[simp] theorem cost_append (probes : Call → ℕ) (xs ys : List Call) :
+ cost probes (xs ++ ys) = cost probes xs + cost probes ys := by
+ induction xs with
+ | nil => simp [cost]
+ | cons a xs ih => simp [cost, ih, Nat.add_assoc]
+
+@[simp] theorem cost_eq_zero_iff (probes : Call → ℕ) (xs : List Call) :
+ cost probes xs = 0 ↔ xs = [] := by
+ cases xs <;> simp [cost]
+
+/-- All calls start before the boundary, including a last call that may finish
+on or beyond the boundary. -/
+def StartsBefore (probes : Call → ℕ) (boundary : ℕ) : ℕ → List Call → Prop
+ | _, [] => True
+ | start, a :: xs =>
+ start < boundary ∧ StartsBefore probes boundary (start + (1 + probes a)) xs
+
+/-- Split immediately before the first call that starts on or beyond the boundary. -/
+def split (probes : Call → ℕ) (boundary : ℕ) : ℕ → List Call → List Call × List Call
+ | _, [] => ([], [])
+ | start, a :: xs =>
+ if start < boundary then
+ let rest := split probes boundary (start + (1 + probes a)) xs
+ (a :: rest.1, rest.2)
+ else ([], a :: xs)
+
+/-- The site takes an initial segment. It can stop with work left only after
+reaching its boundary. -/
+structure IsSplit (probes : Call → ℕ) (boundary start : ℕ) (xs front rest : List Call) : Prop where
+ append_eq : front ++ rest = xs
+ before : StartsBefore probes boundary start front
+ stopped : rest ≠ [] → boundary ≤ start + cost probes front
+
+theorem split_spec (probes : Call → ℕ) (boundary start : ℕ) (xs : List Call) :
+ IsSplit probes boundary start xs (split probes boundary start xs).1
+ (split probes boundary start xs).2 := by
+ induction xs generalizing start with
+ | nil => exact ⟨rfl, trivial, by simp [split]⟩
+ | cons a xs ih =>
+ by_cases h : start < boundary
+ · simp only [split, h, ↓reduceIte]
+ have hr := ih (start + (1 + probes a))
+ exact ⟨by simp [hr.append_eq], ⟨h, hr.before⟩,
+ fun hn => by simpa [cost, Nat.add_assoc] using hr.stopped hn⟩
+ · simp only [split, h, ↓reduceIte]
+ exact ⟨rfl, trivial, fun _ => by simpa [cost] using Nat.le_of_not_gt h⟩
+
+theorem IsSplit.eq_split {probes : Call → ℕ} {boundary start : ℕ} {xs front rest : List Call}
+ (h : IsSplit probes boundary start xs front rest) :
+ split probes boundary start xs = (front, rest) := by
+ rcases h with ⟨rfl, hbefore, hstop⟩
+ induction front generalizing start with
+ | nil =>
+ cases rest with
+ | nil => rfl
+ | cons a rest =>
+ have hc := hstop (by simp)
+ simp only [cost, Nat.add_zero] at hc
+ simp [split, Nat.not_lt.mpr hc]
+ | cons a front ih =>
+ obtain ⟨hlt, htail⟩ := hbefore
+ simp [split, hlt, ih htail (by simpa [cost, Nat.add_assoc] using hstop)]
+
+/-- Starting with site `v`, run the successive start-cost cutoffs. Sites after a
+halt receive empty lists. -/
+def partition (probes : Call → ℕ) (H : ℕ) : ℕ → ℕ → ℕ → List Call → List (List Call)
+ | _, 0, _, _ => []
+ | v, sites + 1, start, xs =>
+ let parts := split probes ((v + 1) * H) start xs
+ parts.1 :: partition probes H (v + 1) sites (start + cost probes parts.1) parts.2
+
+/-- The local cost checks on the successor chain. -/
+def Valid (probes : Call → ℕ) (H : ℕ) : ℕ → ℕ → List (List Call) → Prop
+ | _, _, [] => True
+ | v, start, front :: blocks =>
+ (front ≠ [] → v * H ≤ start) ∧
+ StartsBefore probes ((v + 1) * H) start front ∧
+ (blocks.flatten ≠ [] → (v + 1) * H ≤ start + cost probes front) ∧
+ Valid probes H (v + 1) (start + cost probes front) blocks
+
+@[simp] theorem length_partition (probes : Call → ℕ) (H v sites start : ℕ) (xs : List Call) :
+ (partition probes H v sites start xs).length = sites := by
+ induction sites generalizing v start xs with
+ | zero => rfl
+ | succ k ih => simp [partition, ih]
+
+theorem partition_spec {probes : Call → ℕ} {H v sites start : ℕ} {xs : List Call}
+ (hlower : xs ≠ [] → v * H ≤ start)
+ (hcap : start + cost probes xs ≤ (v + sites) * H) :
+ (partition probes H v sites start xs).flatten = xs ∧
+ Valid probes H v start (partition probes H v sites start xs) := by
+ induction sites generalizing v start xs with
+ | zero =>
+ have hempty : xs = [] := by
+ by_contra hn
+ have h := hlower hn
+ have hp := (cost_eq_zero_iff probes xs).not.mpr hn
+ simp only [Nat.add_zero] at hcap
+ omega
+ exact ⟨hempty.symm, trivial⟩
+ | succ k ih =>
+ let p := split probes ((v + 1) * H) start xs
+ have hs : IsSplit probes ((v + 1) * H) start xs p.1 p.2 := split_spec ..
+ have htotal : cost probes p.1 + cost probes p.2 = cost probes xs := by
+ rw [← cost_append, hs.append_eq]
+ obtain ⟨hflat, hvalid⟩ := ih (v := v + 1) (xs := p.2) hs.stopped (by
+ rw [Nat.add_assoc, htotal]
+ simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hcap)
+ refine ⟨?_, ?_⟩
+ · change p.1 ++ (partition probes H (v + 1) k _ p.2).flatten = xs
+ rw [hflat, hs.append_eq]
+ · refine ⟨fun h => hlower ?_, hs.before, ?_, hvalid⟩
+ · rw [← hs.append_eq]
+ exact fun he => h (List.append_eq_nil_iff.mp he).1
+ · change (partition probes H (v + 1) k _ p.2).flatten ≠ [] → _
+ rw [hflat]
+ exact hs.stopped
+
+theorem Valid.eq_partition {probes : Call → ℕ} {H v start : ℕ} {blocks : List (List Call)}
+ (h : Valid probes H v start blocks) :
+ partition probes H v blocks.length start blocks.flatten = blocks := by
+ induction blocks generalizing v start with
+ | nil => rfl
+ | cons front blocks ih =>
+ obtain ⟨_, hbefore, hstop, htail⟩ := h
+ have hs : IsSplit probes ((v + 1) * H) start (front ++ blocks.flatten) front blocks.flatten :=
+ ⟨rfl, hbefore, hstop⟩
+ simp [partition, hs.eq_split, ih htail]
+
+/-- There is exactly one contiguous grouping into the given number of sites
+that recovers the original path and passes the local start/stop cost checks. -/
+theorem existsUnique_partition (probes : Call → ℕ) (S H : ℕ) (xs : List Call)
+ (hcap : cost probes xs ≤ S * H) :
+ ∃! blocks : List (List Call), blocks.length = S ∧ blocks.flatten = xs ∧
+ Valid probes H 0 0 blocks := by
+ have hs := partition_spec (v := 0) (start := 0) (sites := S) (xs := xs)
+ (fun _ => by simp) (by simpa using hcap)
+ refine ⟨partition probes H 0 S 0 xs, ⟨length_partition .., hs⟩, ?_⟩
+ rintro blocks ⟨hlen, hxs, hv⟩
+ simpa [hlen, hxs] using hv.eq_partition.symm
+
+/-- Inspect the start cost of a specified call after a prefix of its block. -/
+theorem StartsBefore.start_lt {probes : Call → ℕ} {boundary start : ℕ}
+ {front rest : List Call} {a : Call}
+ (h : StartsBefore probes boundary start (front ++ a :: rest)) :
+ start + cost probes front < boundary := by
+ induction front generalizing start with
+ | nil => simpa [cost] using h.1
+ | cons b front ih =>
+ simpa [cost, Nat.add_assoc] using ih h.2
+
+/-- Every call in a valid site block has exactly the site number prescribed by
+the floor of its starting cost divided by the bucket size. -/
+theorem call_site {probes : Call → ℕ} {H v start : ℕ} {front rest : List Call} {a : Call}
+ (hH : 0 < H) (hlower : v * H ≤ start)
+ (hb : StartsBefore probes ((v + 1) * H) start (front ++ a :: rest)) :
+ (start + cost probes front) / H = v := by
+ have hlo : v ≤ (start + cost probes front) / H :=
+ (Nat.le_div_iff_mul_le hH).mpr (Nat.le_trans hlower (Nat.le_add_right ..))
+ have hhi : (start + cost probes front) / H < v + 1 :=
+ (Nat.div_lt_iff_lt_mul hH).mpr hb.start_lt
+ omega
+
+/-- A permitted call can only stay in its bucket or advance one bucket. -/
+theorem next_bucket {H start charge : ℕ} (hH : 0 < H) (hc : charge ≤ H) :
+ (start + charge) / H = start / H ∨ (start + charge) / H = start / H + 1 := by
+ have hl : start / H ≤ (start + charge) / H := Nat.div_le_div_right (Nat.le_add_right ..)
+ have hb : start < (start / H + 1) * H :=
+ (Nat.div_lt_iff_lt_mul hH).mp (Nat.lt_succ_self _)
+ have hu : (start + charge) / H < (start / H + 1 + 1) := by
+ apply (Nat.div_lt_iff_lt_mul hH).mpr
+ rw [Nat.succ_mul]
+ omega
+ omega
+
+theorem StartsBefore.finish_lt {probes : Call → ℕ} {boundary H start : ℕ} {xs : List Call}
+ (hb : StartsBefore probes boundary start xs) (hne : xs ≠ [])
+ (hc : ∀ a ∈ xs, 1 + probes a ≤ H) :
+ start + cost probes xs < boundary + H := by
+ induction xs generalizing start with
+ | nil => contradiction
+ | cons a xs ih =>
+ obtain ⟨hs, ht⟩ := hb
+ have ha := hc a (by simp)
+ by_cases he : xs = []
+ · subst xs
+ simp only [cost, Nat.add_zero]
+ omega
+ · simpa [cost, Nat.add_assoc] using ih ht he (fun b hm => hc b (by simp [hm]))
+
+/-- The last call starts before the upper boundary and costs at most `H`. -/
+theorem site_cost_lt {probes : Call → ℕ} {H v start : ℕ} {xs : List Call}
+ (hH : 0 < H) (hlower : xs ≠ [] → v * H ≤ start)
+ (hb : StartsBefore probes ((v + 1) * H) start xs)
+ (hc : ∀ a ∈ xs, 1 + probes a ≤ H) :
+ cost probes xs < 2 * H := by
+ by_cases he : xs = []
+ · simp [he, cost, hH]
+ have hf := hb.finish_lt he hc
+ have hl := hlower he
+ rw [Nat.succ_mul] at hf
+ omega
+
+/-- One record is emitted per probe, independently of its kind and value. -/
+def probeCount (probes : Call → ℕ) : List Call → ℕ
+ | [] => 0
+ | a :: xs => probes a + probeCount probes xs
+
+theorem cost_eq_length_add_probes (probes : Call → ℕ) (xs : List Call) :
+ cost probes xs = xs.length + probeCount probes xs := by
+ induction xs with
+ | nil => rfl
+ | cons a xs ih => simp only [cost, ih, List.length_cons, probeCount]; omega
+
+/-- The one initialization record and all probe records fit in the site's block. -/
+theorem records_fit {probes : Call → ℕ} {H : ℕ} {xs : List Call}
+ (hcost : cost probes xs < 2 * H) :
+ 1 + probeCount probes xs ≤ 4 * H := by
+ rw [cost_eq_length_add_probes] at hcost
+ omega
+
+theorem Valid.block_bounds {probes : Call → ℕ} {H v start : ℕ} {blocks : List (List Call)}
+ (hH : 0 < H) (hv : Valid probes H v start blocks)
+ (hc : ∀ a ∈ blocks.flatten, 1 + probes a ≤ H) :
+ ∀ xs ∈ blocks, cost probes xs < 2 * H ∧ 1 + probeCount probes xs ≤ 4 * H := by
+ induction blocks generalizing v start with
+ | nil => simp
+ | cons xs blocks ih =>
+ obtain ⟨hl, hb, _, ht⟩ := hv
+ intro ys hm
+ rcases List.mem_cons.mp hm with rfl | hm
+ · have h := site_cost_lt hH hl hb (fun a ha => hc a (by simp [ha]))
+ exact ⟨h, records_fit h⟩
+ · exact ih ht (fun a ha => hc a (by simp [ha])) ys hm
+
+/-- With both of the paper's caps, the canonical site grouping satisfies the
+local cost and record capacity bounds simultaneously. -/
+theorem partition_block_bounds {probes : Call → ℕ} {S H : ℕ} {xs : List Call}
+ (hH : 0 < H) (hcap : cost probes xs ≤ S * H) (hc : ∀ a ∈ xs, 1 + probes a ≤ H) :
+ ∀ ys ∈ partition probes H 0 S 0 xs,
+ cost probes ys < 2 * H ∧ 1 + probeCount probes ys ≤ 4 * H := by
+ obtain ⟨hflat, hv⟩ := partition_spec (v := 0) (start := 0) (sites := S)
+ (xs := xs) (fun _ => by simp) (by simpa using hcap)
+ exact hv.block_bounds hH (by rw [hflat]; exact hc)
+
+/-- If the final call consumes the entire cap, its start still belongs to
+the last site. This applies equally to an accepting final call. -/
+theorem last_site_at_cap {S H start probes : ℕ}
+ (hcall : 1 + probes ≤ H) (hcap : start + (1 + probes) = (S + 1) * H) :
+ start / H = S := by
+ have hH : 0 < H := by omega
+ have hl : S ≤ start / H := (Nat.le_div_iff_mul_le hH).mpr (by
+ rw [Nat.succ_mul] at hcap
+ omega)
+ have hu : start / H < S + 1 := (Nat.div_lt_iff_lt_mul hH).mpr (by omega)
+ omega
+
+/-- At the last available unit, starting a call is possible exactly when
+there are no subsequent probes in it. -/
+theorem final_unit_iff {cap start probes : ℕ} (h : start + 1 = cap) :
+ start + (1 + probes) ≤ cap ↔ probes = 0 := by omega
+
+/-- A running continuation at the cap cannot start even a probe-free call. -/
+theorem next_call_exceeds_cap (cap probes : ℕ) : cap < cap + (1 + probes) := by omega
+
+end RAMBuckets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMChain.lean b/lean/OAI/Computability/VPVNP/RAMChain.lean
new file mode 100644
index 0000000000..31c313e415
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMChain.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.RAMExecution
+
+/-!
+# Successive calls with reset private memory and persistent external memory
+
+A path is specified by its list of actual binary choices in each call. The
+native run computes reads and addresses itself. A local replay uses the
+reported values. Read consistency over the concatenated event log identifies
+the two descriptions of a path, including when branches yield identical states.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+theorem correct_append (m : Memory w) (es fs : List (Event w)) :
+ Correct m (es ++ fs) ↔ Correct m es ∧ Correct (after m es) fs := by
+ induction es generalizing m with
+ | nil => simp [Correct, after]
+ | cons e es ih => cases e <;> simp [Correct, after, update, ih, and_assoc]
+
+/-- Native execution of consecutive calls. Each entry supplies just the branch
+choices of that call. After a halt a further call rejects. -/
+def runSegment (P : Program w C) (fuel : ℕ) :
+ Option (Word w) → Memory w → List (List Bool) → Option (List (Report w))
+ | _, _, [] => some []
+ | none, _, _ :: _ => none
+ | some state, m, bs :: more =>
+ match execute P fuel (P.start state) m bs with
+ | none => none
+ | some r => (runSegment P fuel r.result (after m r.events) more).map (r :: ·)
+
+/-- The local processor validates the sequence of calls using their reported
+read answers, propagating the returned persistent word. -/
+def LocalSegment (P : Program w C) (fuel : ℕ) : Option (Word w) → List (Report w) → Prop
+ | _, [] => True
+ | none, _ :: _ => False
+ | some state, r :: rest =>
+ Guessed P fuel (P.start state) r.events r.result ∧ LocalSegment P fuel r.result rest
+
+/-- The persistent state after a sequence of reports, given by the last report's result or the
+incoming state for an empty sequence. -/
+def endState : Option (Word w) → List (Report w) → Option (Word w)
+ | s, [] => s
+ | _, r :: rest => endState r.result rest
+
+/-- Extract one list of actual binary branch choices from each call report, in call order. -/
+def branchPaths (rs : List (Report w)) : List (List Bool) := rs.map (fun r => choiceBits r.events)
+
+/-- Concatenate all calls' events in execution order for replay against external memory. -/
+def eventLog (rs : List (Report w)) : List (Event w) := rs.flatMap Report.events
+
+theorem endState_append (s : Option (Word w)) (rs ts : List (Report w)) :
+ endState s (rs ++ ts) = endState (endState s rs) ts := by
+ induction rs generalizing s with
+ | nil => rfl
+ | cons r rs ih => simpa [endState] using ih r.result
+
+theorem localSegment_append (P : Program w C) (fuel : ℕ) (s : Option (Word w))
+ (rs ts : List (Report w)) :
+ LocalSegment P fuel s (rs ++ ts) ↔
+ LocalSegment P fuel s rs ∧ LocalSegment P fuel (endState s rs) ts := by
+ induction rs generalizing s with
+ | nil => simp [LocalSegment, endState]
+ | cons r rs ih => cases s <;> simp [LocalSegment, endState, ih, and_assoc]
+
+theorem runSegment_iff (P : Program w C) (fuel : ℕ) (s : Option (Word w)) (m : Memory w)
+ (bits : List (List Bool)) (rs : List (Report w)) :
+ runSegment P fuel s m bits = some rs ↔
+ LocalSegment P fuel s rs ∧ Correct m (eventLog rs) ∧ branchPaths rs = bits := by
+ induction bits generalizing rs s m with
+ | nil => cases rs <;> simp [runSegment, LocalSegment, eventLog, Correct, branchPaths]
+ | cons bs bits ih =>
+ cases s with
+ | none =>
+ cases rs <;> simp [runSegment, LocalSegment, branchPaths]
+ | some s =>
+ cases h : execute P fuel (P.start s) m bs with
+ | none =>
+ cases rs with
+ | nil => simp [runSegment, h, branchPaths]
+ | cons r rs =>
+ simp only [runSegment, h, reduceCtorEq, LocalSegment,
+ eventLog, List.flatMap_cons, correct_append, branchPaths, List.map_cons,
+ List.cons.injEq, false_iff]
+ rintro ⟨⟨hg, _⟩, ⟨hm, _⟩, hb, _⟩
+ have hr := (execute_iff (r := r) (P := P) (c := P.start s)).mpr ⟨hg, hm, hb⟩
+ rw [h] at hr
+ contradiction
+ | some t =>
+ have ht := execute_spec h
+ cases rs with
+ | nil =>
+ simp [runSegment, h, branchPaths, Option.map_eq_some_iff]
+ | cons r rs =>
+ simp only [runSegment, h, Option.map_eq_some_iff,
+ List.cons.injEq, LocalSegment, eventLog,
+ List.flatMap_cons, correct_append, branchPaths, List.map_cons]
+ constructor
+ · rintro ⟨l, hl, rfl, rfl⟩
+ obtain ⟨hL, hM, hB⟩ := (ih _ _ _).mp hl
+ exact ⟨⟨ht.1, hL⟩, ⟨ht.2.1, hM⟩, ht.2.2, hB⟩
+ · rintro ⟨⟨hg, hL⟩, ⟨hm, hM⟩, hb, hB⟩
+ have hr := (execute_iff (r := r) (P := P) (c := P.start s)).mpr ⟨hg, hm, hb⟩
+ have he : t = r := Option.some.inj (h.symm.trans hr)
+ subst r
+ exact ⟨rs, (ih _ _ _).mpr ⟨hL, hM, hB⟩, rfl, rfl⟩
+
+/-- Accepted native paths subject to a predicate on their computed reports.
+This predicate will impose the exact global and per-call cost caps. -/
+abbrev ActualPaths (P : Program w C) (fuel : ℕ) (initial : Word w) (m : Memory w)
+ (withinCaps : List (Report w) → Prop) :=
+ {bits : List (List Bool) // ∃ rs, runSegment P fuel (some initial) m bits = some rs ∧
+ endState (some initial) rs = none ∧ withinCaps rs}
+
+/-- Accepted local call reports, with correct reads over the whole memory
+history. The sorted-record check is a local implementation of this last test. -/
+abbrev VerifiedReports (P : Program w C) (fuel : ℕ) (initial : Word w) (m : Memory w)
+ (withinCaps : List (Report w) → Prop) :=
+ {rs : List (Report w) // LocalSegment P fuel (some initial) rs ∧
+ Correct m (eventLog rs) ∧ endState (some initial) rs = none ∧ withinCaps rs}
+
+private noncomputable def getReports {P : Program w C} {fuel initial m cap}
+ (b : ActualPaths P fuel initial m cap) : VerifiedReports P fuel initial m cap :=
+ ⟨b.property.choose, by
+ obtain ⟨h, ha, hc⟩ := b.property.choose_spec
+ obtain ⟨hl, hm, _⟩ := (runSegment_iff ..).mp h
+ exact ⟨hl, hm, ha, hc⟩⟩
+
+private def getChoices {P : Program w C} {fuel initial m cap}
+ (r : VerifiedReports P fuel initial m cap) : ActualPaths P fuel initial m cap :=
+ ⟨branchPaths r.val, r.val, (runSegment_iff ..).mpr ⟨r.property.1, r.property.2.1, rfl⟩,
+ r.property.2.2⟩
+
+/-- Parsimony before partitioning calls into sites. -/
+noncomputable def reportEquiv (P : Program w C) (fuel : ℕ) (initial : Word w) (m : Memory w)
+ (withinCaps : List (Report w) → Prop) :
+ ActualPaths P fuel initial m withinCaps ≃ VerifiedReports P fuel initial m withinCaps where
+ toFun := getReports
+ invFun := getChoices
+ left_inv b := Subtype.ext ((runSegment_iff ..).mp b.property.choose_spec.1).2.2
+ right_inv r := by
+ apply Subtype.ext
+ have h := (runSegment_iff P fuel (some initial) m (branchPaths r.val) r.val).mpr
+ ⟨r.property.1, r.property.2.1, rfl⟩
+ exact Option.some.inj ((getChoices r).property.choose_spec.1.symm.trans h)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMChoicePrefix.lean b/lean/OAI/Computability/VPVNP/RAMChoicePrefix.lean
new file mode 100644
index 0000000000..fe703cffa0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMChoicePrefix.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.RAMExecution
+
+/-!
+# Exact choice streams of a burst RAM call
+
+From fixed control and external memory, two successful streams of choices
+cannot properly extend one another. The assertion is independent of their
+instruction fuel. In particular, success on every bit pattern of a given
+width determines the complete set of admissible streams.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*} {P : Program w C}
+
+/-- A successful stream has no successful proper extension, even with a
+different fuel allowance. Equality of streams forces equality of reports. -/
+theorem execute_prefix_unique {f g : ℕ} {c : C} {m : Memory w} {bits suffix : List Bool}
+ {r r' : Report w} (h : execute P f c m bits = some r)
+ (h' : execute P g c m (bits ++ suffix) = some r') : suffix = [] ∧ r = r' := by
+ induction f generalizing g c m bits r r' with
+ | zero => simp [execute] at h
+ | succ f ih =>
+ cases g with
+ | zero => simp [execute] at h'
+ | succ g =>
+ cases hs : P.step c with
+ | reject => simp [execute, hs] at h
+ | finish result =>
+ cases bits <;> cases suffix <;> simp_all [execute]
+ | branch next =>
+ cases bits with
+ | nil => simp [execute, hs] at h
+ | cons b bs =>
+ simp only [execute, hs, List.cons_append, Option.map_eq_some_iff] at h h'
+ obtain ⟨s, hs, rfl⟩ := h
+ obtain ⟨s', hs', rfl⟩ := h'
+ obtain ⟨hz, rfl⟩ := ih hs hs'
+ exact ⟨hz, rfl⟩
+ | localStep next | read a next | write a v next =>
+ simp only [execute, hs, Option.map_eq_some_iff] at h h'
+ obtain ⟨s, hs, rfl⟩ := h
+ obtain ⟨s', hs', rfl⟩ := h'
+ obtain ⟨hz, rfl⟩ := ih hs hs'
+ exact ⟨hz, rfl⟩
+
+/-- If all length-`k` bit patterns return, every returning execution consumes
+exactly `k` choices. Shorter patterns extend to length `k`, and longer patterns
+have a prefix of that length. -/
+theorem execute_length_of_complete {k f : ℕ} {c : C} {m : Memory w}
+ (hfull : ∀ bs : List Bool, bs.length = k → ∃ g r', execute P g c m bs = some r')
+ {bits : List Bool} {r : Report w} (h : execute P f c m bits = some r) : bits.length = k := by
+ rcases (show bits.length < k ∨ bits.length = k ∨ k < bits.length by omega) with hlt | heq | hgt
+ · let suffix := List.replicate (k - bits.length) false
+ obtain ⟨g, r', h'⟩ := hfull (bits ++ suffix) (by simp [suffix]; omega)
+ have hlen := congrArg List.length (execute_prefix_unique h h').1
+ simp only [suffix, List.length_replicate, List.length_nil] at hlen
+ omega
+ · exact heq
+ · obtain ⟨g, r', h'⟩ := hfull (bits.take k) (by simp [Nat.min_eq_left (Nat.le_of_lt hgt)])
+ have ht : execute P f c m (bits.take k ++ bits.drop k) = some r := by simpa using h
+ have hlen := congrArg List.length (execute_prefix_unique h' ht).1
+ simp only [List.length_drop, List.length_nil] at hlen
+ omega
+
+/-- At a fixed fuel budget, sufficiency of all fixed-width tapes also proves
+necessity of that width. -/
+theorem exists_execute_iff_length {k f : ℕ} {c : C} {m : Memory w}
+ (hfull : ∀ bs : List Bool, bs.length = k → ∃ r, execute P f c m bs = some r)
+ (bits : List Bool) : (∃ r, execute P f c m bits = some r) ↔ bits.length = k :=
+ ⟨fun ⟨_, h⟩ ↦ execute_length_of_complete (fun bs hb ↦ ⟨f, hfull bs hb⟩) h, hfull bits⟩
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMClock.lean b/lean/OAI/Computability/VPVNP/RAMClock.lean
new file mode 100644
index 0000000000..a0f973292f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMClock.lean
@@ -0,0 +1,141 @@
+import Mathlib.Analysis.SpecificLimits.Normed
+import Mathlib.Data.Nat.Log
+import Mathlib.Tactic.FieldSimp
+import Mathlib.Tactic.Ring
+
+/-!
+# The word-step exponent for parsimonious RAM transcripts
+
+The site loop can charge a linear scan of the private-write log at each
+instruction. The sorting term pays for every offset at every comparator
+layer. Since the word width and the stage counts are polylogarithmic, their
+constants and powers fit the slack in the exponent of Lemma 10.1.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open Filter
+
+/-- A fixed polynomial in the logarithm fits within the input length,
+with a threshold independent of every private computation or message. -/
+theorem eventually_polylog_le (A k : ℕ) : ∀ᶠ n : ℕ in atTop, A * (n.log2 + 1)^k ≤ n := by
+ have hk := (isLittleO_pow_const_const_pow_of_one_lt (R := ℝ) k
+ (r := 2) (by norm_num)).def (c := ((A+1 : ℕ) : ℝ)⁻¹ / 2^k) (by positivity)
+ obtain ⟨L, hL⟩ := eventually_atTop.mp hk
+ filter_upwards [eventually_ge_atTop (2^(max L 1))] with n hn
+ have hn0 : 0 < n := (Nat.two_pow_pos _).trans_le hn
+ have hlarge : max L 1 ≤ n.log2 := (Nat.le_log2 hn0.ne').mpr hn
+ have hpos : 1 ≤ n.log2 := (le_max_right _ _).trans hlarge
+ have hh := hL n.log2 ((le_max_left ..).trans hlarge)
+ simp only [Real.norm_eq_abs, abs_pow, abs_of_nonneg (show 0 ≤ (n.log2 : ℝ) by positivity), abs_of_nonneg (by norm_num : 0 ≤ (2:ℝ))] at hh
+ have hreal : ((A+1 : ℕ) : ℝ) * 2^k * (n.log2 : ℝ)^k ≤ (2:ℝ)^n.log2 := by
+ have hp : 0 < ((A+1 : ℕ) : ℝ) := by positivity
+ have htwo : 0 < (2:ℝ)^k := by positivity
+ calc
+ _ ≤ ((A+1 : ℕ) : ℝ) * 2^k * (((A+1 : ℕ) : ℝ)⁻¹ / 2^k * (2:ℝ)^n.log2) :=
+ mul_le_mul_of_nonneg_left hh (by positivity)
+ _ = (2:ℝ)^n.log2 := by field_simp
+ have hnat : (A+1) * 2^k * n.log2^k ≤ 2^n.log2 := by exact_mod_cast hreal
+ calc
+ A * (n.log2 + 1)^k ≤ (A+1) * (2*n.log2)^k := by gcongr <;> omega
+ _ = (A+1) * 2^k * n.log2^k := by rw [mul_pow, Nat.mul_assoc]
+ _ ≤ 2^n.log2 := hnat
+ _ ≤ n := (Nat.le_log2 hn0.ne').mp le_rfl
+
+/-- The logarithmic number of address bits and the prescribed quartic word
+width simultaneously fit the bounds used below. `r ≤ B(log₂ n+1)` includes
+the rounded address format of the live and virtual RAMs. -/
+theorem eventually_word_stage_le (B D : ℕ) : ∀ᶠ n : ℕ in atTop, ∀ r t : ℕ,
+ r ≤ B * (n.log2 + 1) → t ≤ D * (n.log2 + 1) →
+ (r + 10)^4 ≤ n ∧ t ≤ n := by
+ filter_upwards [eventually_polylog_le ((B+10)^4) 4, eventually_polylog_le D 1] with n hw ht
+ intro r t hr hts
+ constructor
+ · have h : r+10 ≤ (B+10)*(n.log2+1) := by
+ rw [Nat.add_mul]; omega
+ exact (Nat.pow_le_pow_left h 4).trans (by simpa [mul_pow] using hw)
+ · simpa using hts.trans (by simpa using ht)
+
+/-- An upper envelope in primitive word steps. Here `stages` is the number
+of bitonic phases, `H` the bucket capacity, and `k` a fixed program constant.
+Each of the `4H` slots is visited at each sorting layer. -/
+def transcriptWorkBound (k w H stages fuel : ℕ) : ℕ :=
+ 2048 * (w + 1) + 2048 * (H + 1) * (fuel + 1) * (fuel + 1) * (w + k + 2) +
+ (stages + 1).choose 2 * (4 * H * (1024 * (w + 1)) + 9)
+
+set_option maxRecDepth 8192 in
+/-- The envelope with private fuel `n^u` is within the paper's site clock.
+The threshold on the fixed program constant and the polylogarithmic
+parameters can be taken before choosing the messages. -/
+theorem transcriptWorkBound_le_clock {n u k w H stages : ℕ} (hn : 2048 ≤ n)
+ (hk : k+2 ≤ n) (hw : w ≤ n) (hH : H ≤ 2*n) (hstage : stages+1 ≤ n) :
+ transcriptWorkBound k w H stages (n^u) ≤ n^(10*u+30) := by
+ have hn2 : 2 ≤ n := by omega
+ have hn1 : 1 ≤ n := by omega
+ have hs : 2*n ≤ n^2 := by rw [pow_two]; exact Nat.mul_le_mul_right n hn2
+ have hw' : w+1 ≤ n^2 := (by omega : w+1 ≤ 2*n).trans hs
+ have hk' : w+k+2 ≤ n^2 := (by omega : w+k+2 ≤ 2*n).trans hs
+ have hH' : H+1 ≤ n^2 := by
+ rw [pow_two]
+ exact (by omega : H+1 ≤ 3*n).trans (Nat.mul_le_mul_right n (by omega))
+ have hf : n^u + 1 ≤ n^(u+1) := by
+ rw [pow_succ]
+ have h := Nat.pow_pos (by omega : 0 < n) (n := u)
+ exact (by omega : n^u+1 ≤ n^u*2).trans (Nat.mul_le_mul_left _ hn2)
+ have hb : 4*H ≤ n^2 := by
+ rw [pow_two]
+ exact (by omega : 4*H ≤ 8*n).trans (Nat.mul_le_mul_right n (by omega))
+ have hc : (stages+1).choose 2 ≤ n^2 := by
+ rw [Nat.choose_two_right, pow_two]
+ exact (Nat.div_le_self _ _).trans (Nat.mul_le_mul hstage (by omega))
+ have a : 2048*(w+1) ≤ n^3 := by
+ calc _ ≤ n*n^2 := Nat.mul_le_mul hn hw'
+ _ = _ := by ring
+ have b : 2048*(H+1)*(n^u+1)*(n^u+1)*(w+k+2) ≤ n^(2*u+7) := by
+ calc _ ≤ n*n^2*n^(u+1)*n^(u+1)*n^2 := by gcongr
+ _ = _ := by rw [show 2*u+7 = 1+2+(u+1)+(u+1)+2 by omega]; simp only [pow_add, pow_one]
+ have c : 4*H*(1024*(w+1)) ≤ n^5 := by
+ calc _ ≤ n^2*(n*n^2) := by gcongr; omega
+ _ = _ := by ring
+ have cc : (stages+1).choose 2 * (4*H*(1024*(w+1))+9) ≤ n^8 := by
+ calc _ ≤ n^2 * n^6 := by
+ apply Nat.mul_le_mul hc
+ rw [show n^6=n^5*n by ring]
+ have hp : 9 ≤ n^5 := (by omega : 9 ≤ n).trans (Nat.le_self_pow (by decide) n)
+ exact (by omega : 4*H*(1024*(w+1))+9 ≤ n^5*2).trans (Nat.mul_le_mul_left _ hn2)
+ _ = _ := by ring
+ have ha := a.trans (Nat.pow_le_pow_right hn1 (show 3 ≤ 2*u+8 by omega))
+ have hbb := b.trans (Nat.pow_le_pow_right hn1 (show 2*u+7 ≤ 2*u+8 by omega))
+ have hcc := cc.trans (Nat.pow_le_pow_right hn1 (show 8 ≤ 2*u+8 by omega))
+ calc
+ transcriptWorkBound k w H stages (n^u) ≤ n^(2*u+8)*3 := by unfold transcriptWorkBound; omega
+ _ ≤ n^(2*u+8)*n := Nat.mul_le_mul_left _ (by omega)
+ _ = n^(2*u+9) := (pow_succ n (2*u+8)).symm
+ _ ≤ n^(10*u+30) := Nat.pow_le_pow_right hn1 (by omega)
+
+/-- With `S=2^d`, `H=2^e`, a logarithmic site identifier and
+`H ≤ 2n`, the site-clock estimate holds eventually and uniformly over all
+permitted choices of the parameters. -/
+theorem eventually_transcriptWorkBound_le_clock (B D k u : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ r d e : ℕ, r ≤ B * (n.log2 + 1) → d ≤ D * (n.log2 + 1) →
+ 2^e ≤ 2*n →
+ transcriptWorkBound k ((r+10)^4) (2^e) (2+e+d) (n^u) ≤ n^(10*u+30) := by
+ filter_upwards [eventually_ge_atTop 2048, eventually_ge_atTop (k+2),
+ eventually_word_stage_le B (D+4)] with n hn hk hparams
+ intro r d e hr hd hH
+ have hn0 : n ≠ 0 := by omega
+ have he := (Nat.le_log2 (by omega : 2*n ≠ 0)).mpr hH
+ rw [Nat.log2_two_mul hn0] at he
+ have ht : 2+e+d+1 ≤ (D+4)*(n.log2+1) := by rw [Nat.add_mul]; omega
+ obtain ⟨hw, hstage⟩ := hparams r _ hr ht
+ exact transcriptWorkBound_le_clock hn hk hw hH hstage
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMExecution.lean b/lean/OAI/Computability/VPVNP/RAMExecution.lean
new file mode 100644
index 0000000000..9b8ca114c2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMExecution.lean
@@ -0,0 +1,198 @@
+import Mathlib.Data.Fin.Basic
+import Mathlib.Data.List.Basic
+
+/-!
+# Bounded executions of burst RAM calls
+
+The genuine interpreter follows a supplied sequence of binary choices and
+answers external reads from memory. A processor in Lemma 10.1 instead guesses
+each answer. The two executions agree exactly when all reads in its local
+transcript have their prescribed values. Binary choices are retained even when
+their two continuations coincide.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+/-- A width-`w` RAM word, represented by a natural number strictly below `2^w`. -/
+abbrev Word (w : ℕ) := Fin (2 ^ w)
+/-- External RAM storing a width-`w` word at each natural-number address. -/
+abbrev Memory (w : ℕ) := ℕ → Word w
+
+/-- A small step in a call. `finish none` accepts and `finish (some s)`
+returns the persistent state for the next call. -/
+inductive CallAction (w : ℕ) (C : Type*)
+ | localStep (next : C)
+ | branch (next : Bool → C)
+ | read (address : Word w) (next : Word w → C)
+ | write (address value : Word w) (next : C)
+ | finish (result : Option (Word w))
+ | reject
+
+/-- A burst-RAM call program with a private configuration type, an initializer from the
+persistent word and a one-step instruction function. -/
+structure Program (w : ℕ) (C : Type*) where
+ /-- Private state is recreated from the persistent word on every call. -/
+ start : Word w → C
+ /-- Select the next call action from the current private configuration. -/
+ step : C → CallAction w C
+
+/-- A recorded private tick, binary branch choice, external read or external write. Both kinds
+of probe carry the address and word value. -/
+inductive Event (w : ℕ)
+ | tick
+ | choice (bit : Bool)
+ | read (address value : Word w)
+ | write (address value : Word w)
+ deriving DecidableEq
+
+/-- A single call's ordered event trace and its optional persistent word for the next call. -/
+structure Report (w : ℕ) where
+ /-- Chronological sequence of private ticks, branch choices and external probes during the
+ call. -/
+ events : List (Event w)
+ /-- Persistent word returned to start another call, or `none` when the machine accepts and
+ stops. -/
+ result : Option (Word w)
+ deriving DecidableEq
+
+variable {w : ℕ} {C : Type*}
+
+/-- Add an earlier event to the front of a call report. -/
+def Report.prepend (e : Event w) (r : Report w) : Report w := ⟨e :: r.events, r.result⟩
+
+/-- Set the addressed external word to the supplied value and preserve all other addresses. -/
+def writeMemory (m : Memory w) (a v : Word w) : Memory w :=
+ fun i => if i = a.val then v else m i
+
+/-- Apply one event to external memory, storing the supplied value on a write and preserving
+memory for every other event. -/
+def update (m : Memory w) : Event w → Memory w
+ | .write a v => writeMemory m a v
+ | _ => m
+
+/-- External memory after applying the writes in a chronological list of events. -/
+def after (m : Memory w) (events : List (Event w)) : Memory w := events.foldl update m
+
+/-- Every reported read equals the external word at its address after all preceding writes in
+the trace. -/
+def Correct (m : Memory w) (events : List (Event w)) : Prop :=
+ match events with
+ | [] => True
+ | .read a v :: es => v = m a.val ∧ Correct m es
+ | e :: es => Correct (update m e) es
+
+/-- Extract the binary branch outcomes in order from a call's event trace. -/
+def choiceBits : List (Event w) → List Bool
+ | [] => []
+ | .choice b :: es => b :: choiceBits es
+ | _ :: es => choiceBits es
+
+/-- Native execution. Unused choice bits, a rejecting halt, and exhausted
+instruction fuel all reject. The exact-use convention gives a unique encoding
+of each branch path. -/
+def execute (P : Program w C) : ℕ → C → Memory w → List Bool → Option (Report w)
+ | 0, _, _, _ => none
+ | f + 1, c, m, bits =>
+ match P.step c with
+ | .localStep c' => (execute P f c' m bits).map (Report.prepend .tick)
+ | .branch next =>
+ match bits with
+ | [] => none
+ | b :: bs => (execute P f (next b) m bs).map (Report.prepend (.choice b))
+ | .read a next =>
+ (execute P f (next (m a.val)) m bits).map (Report.prepend (.read a (m a.val)))
+ | .write a v c' =>
+ (execute P f c' (writeMemory m a v) bits).map (Report.prepend (.write a v))
+ | .finish r => if bits = [] then some ⟨[], r⟩ else none
+ | .reject => none
+
+/-- Local call execution. Each external read guesses an arbitrary word. -/
+inductive Guessed (P : Program w C) : ℕ → C → List (Event w) → Option (Word w) → Prop
+ | done {f c r} (h : P.step c = .finish r) : Guessed P (f + 1) c [] r
+ | step {f c c' es r} (h : P.step c = .localStep c') (tail : Guessed P f c' es r) :
+ Guessed P (f + 1) c (.tick :: es) r
+ | branch {f c next b es r} (h : P.step c = .branch next) (tail : Guessed P f (next b) es r) :
+ Guessed P (f + 1) c (.choice b :: es) r
+ | read {f c a next v es r} (h : P.step c = .read a next) (tail : Guessed P f (next v) es r) :
+ Guessed P (f + 1) c (.read a v :: es) r
+ | write {f c a v c' es r} (h : P.step c = .write a v c') (tail : Guessed P f c' es r) :
+ Guessed P (f + 1) c (.write a v :: es) r
+
+theorem Guessed.to_execute {P : Program w C} {f c es r} (h : Guessed P f c es r)
+ {m : Memory w} (hm : Correct m es) :
+ execute P f c m (choiceBits es) = some ⟨es, r⟩ := by
+ induction h generalizing m with
+ | done h => simp [execute, h, choiceBits]
+ | step h _ ih =>
+ simp only [execute, h, choiceBits, Option.map_eq_some_iff]
+ exact ⟨_, ih hm, rfl⟩
+ | branch h _ ih =>
+ simp only [execute, h, choiceBits, Option.map_eq_some_iff]
+ exact ⟨_, ih hm, rfl⟩
+ | read h _ ih =>
+ obtain ⟨rfl, hc⟩ := hm
+ simp [execute, h, choiceBits, ih hc, Report.prepend]
+ | write h _ ih =>
+ simp only [execute, h, choiceBits, Option.map_eq_some_iff]
+ exact ⟨_, ih hm, rfl⟩
+
+theorem execute_spec {P : Program w C} {f c m bits} {r : Report w}
+ (h : execute P f c m bits = some r) :
+ Guessed P f c r.events r.result ∧ Correct m r.events ∧ choiceBits r.events = bits := by
+ induction f generalizing c m bits r with
+ | zero => simp [execute] at h
+ | succ f ih =>
+ cases hs : P.step c with
+ | reject => simp [execute, hs] at h
+ | finish result =>
+ by_cases hb : bits = []
+ · subst bits
+ simp [execute, hs] at h
+ subst r
+ exact ⟨.done hs, trivial, rfl⟩
+ · simp [execute, hs, hb] at h
+ | localStep next =>
+ simp only [execute, hs, Option.map_eq_some_iff] at h
+ obtain ⟨t, ht, rfl⟩ := h
+ obtain ⟨hg, hm, hb⟩ := ih ht
+ exact ⟨.step hs hg, hm, hb⟩
+ | branch next =>
+ cases bits with
+ | nil => simp [execute, hs] at h
+ | cons b bits =>
+ simp only [execute, hs, Option.map_eq_some_iff] at h
+ obtain ⟨t, ht, rfl⟩ := h
+ obtain ⟨hg, hm, hb⟩ := ih ht
+ exact ⟨.branch hs hg, hm, congrArg (b :: ·) hb⟩
+ | read a next =>
+ simp only [execute, hs, Option.map_eq_some_iff] at h
+ obtain ⟨t, ht, rfl⟩ := h
+ obtain ⟨hg, hm, hb⟩ := ih ht
+ exact ⟨.read hs hg, ⟨rfl, hm⟩, hb⟩
+ | write a v next =>
+ simp only [execute, hs, Option.map_eq_some_iff] at h
+ obtain ⟨t, ht, rfl⟩ := h
+ obtain ⟨hg, hm, hb⟩ := ih ht
+ exact ⟨.write hs hg, hm, hb⟩
+
+/-- Correct read guesses leave one transcript per path of binary choices. -/
+theorem execute_iff {P : Program w C} {f c m bits} {r : Report w} :
+ execute P f c m bits = some r ↔
+ Guessed P f c r.events r.result ∧ Correct m r.events ∧ choiceBits r.events = bits := by
+ refine ⟨execute_spec, ?_⟩
+ rintro ⟨hg, hm, rfl⟩
+ exact hg.to_execute hm
+
+theorem Guessed.length_lt {P : Program w C} {f c es r} (h : Guessed P f c es r) :
+ es.length < f := by
+ induction h <;> simp_all
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMFinite.lean b/lean/OAI/Computability/VPVNP/RAMFinite.lean
new file mode 100644
index 0000000000..bc92e0a568
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMFinite.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.RAMChain
+import OAI.Computability.VPVNP.RAMRecords
+import Mathlib.Data.Set.Finite.List
+import Mathlib.SetTheory.Cardinal.Finite
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Finite path counts for burst RAMs
+
+The fuel bound makes the event history of an individual call finite. The
+charge for starting a call also bounds the number of calls in an accepting
+execution. These two bounds suffice even when the set of private machine
+configurations is infinite. Fixing all shared bits leaves an independent
+choice of a valid report list at each site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+deriving instance Fintype for Event
+
+/-- A report list with boundedly many calls, each of which fits its instruction fuel. -/
+abbrev BoundedReports (w fuel maxCalls : ℕ) :=
+ {rs : List (Report w) // rs.length ≤ maxCalls ∧ ∀ r ∈ rs, r.events.length < fuel}
+
+private theorem finite_shortReports (w fuel : ℕ) :
+ Finite {r : Report w // r.events.length < fuel} := by
+ let : Finite {es : List (Event w) // es.length < fuel} := List.finite_length_lt _ _
+ let encode (r : {r : Report w // r.events.length < fuel}) :
+ {es : List (Event w) // es.length < fuel} × Option (Word w) :=
+ (⟨r.val.events, r.property⟩, r.val.result)
+ apply Finite.of_injective encode
+ rintro ⟨⟨es, s⟩, _⟩ ⟨⟨fs, t⟩, _⟩ h
+ simpa [encode] using h
+
+instance (w fuel maxCalls : ℕ) : Finite (BoundedReports w fuel maxCalls) := by
+ let Short := {r : Report w // r.events.length < fuel}
+ let : Finite Short := finite_shortReports w fuel
+ let : Finite {rs : List Short // rs.length ≤ maxCalls} := List.finite_length_le _ _
+ let encode (rs : BoundedReports w fuel maxCalls) : {rs : List Short // rs.length ≤ maxCalls} :=
+ ⟨rs.val.attachWith _ rs.property.2, List.length_attachWith.le.trans rs.property.1⟩
+ apply Finite.of_injective encode
+ intro rs ts he
+ apply Subtype.ext
+ simpa [encode, Short] using congrArg (fun xs => xs.val.map (Subtype.val : Short → Report w)) he
+
+/-- Every locally replayed call obeys its own instruction bound. -/
+theorem localSegment_event_bound {P : Program w C} {fuel s rs}
+ (h : LocalSegment P fuel s rs) : ∀ r ∈ rs, r.events.length < fuel := by
+ induction rs generalizing s with
+ | nil => simp
+ | cons a rs ih =>
+ cases s with
+ | none => contradiction
+ | some s =>
+ intro r hr
+ rcases List.mem_cons.mp hr with rfl | hmem
+ · exact h.1.length_lt
+ · exact ih h.2 _ hmem
+
+/-- The cost cap bounds the total number of calls, including calls without probes. -/
+theorem boundedReports_of_localSegment {P : Program w C} {fuel maxCalls s rs}
+ (h : LocalSegment P fuel s rs) (hc : RAMBuckets.cost Report.probes rs ≤ maxCalls) :
+ rs.length ≤ maxCalls ∧ ∀ r ∈ rs, r.events.length < fuel := by
+ rw [RAMBuckets.cost_eq_length_add_probes] at hc
+ exact ⟨by omega, localSegment_event_bound h⟩
+
+theorem finite_verifiedReports {P : Program w C} {fuel initial m withinCaps maxCalls}
+ (hcap : ∀ rs, withinCaps rs → RAMBuckets.cost Report.probes rs ≤ maxCalls) :
+ Finite (VerifiedReports P fuel initial m withinCaps) := by
+ let encode (r : VerifiedReports P fuel initial m withinCaps) : BoundedReports w fuel maxCalls :=
+ ⟨r.val, boundedReports_of_localSegment r.property.1 (hcap _ r.property.2.2.2)⟩
+ exact Finite.of_injective encode fun _ _ he => Subtype.ext (congrArg (fun t : BoundedReports w fuel maxCalls => t.val) he)
+
+theorem finite_actualPaths {P : Program w C} {fuel initial m withinCaps maxCalls}
+ (hcap : ∀ rs, withinCaps rs → RAMBuckets.cost Report.probes rs ≤ maxCalls) :
+ Finite (ActualPaths P fuel initial m withinCaps) := by
+ let := finite_verifiedReports (P := P) (fuel := fuel) (initial := initial) (m := m) hcap
+ exact Finite.of_equiv _ (reportEquiv P fuel initial m withinCaps).symm
+
+/-- Pairing a shared assignment with separate local witnesses enforces precisely
+all the local checks on the pair. -/
+def siteWitnessEquiv {Shared Site : Type*} {Local : Site → Type*}
+ (valid : Shared → (i : Site) → Local i → Prop) :
+ {t : Shared × ((i : Site) → Local i) // ∀ i, valid t.1 i (t.2 i)} ≃
+ ((b : Shared) × ((i : Site) → {r : Local i // valid b i r})) where
+ toFun t := ⟨t.val.1, fun i => ⟨t.val.2 i, t.property i⟩⟩
+ invFun t := ⟨⟨t.1, fun i => (t.2 i).val⟩, fun i => (t.2 i).property⟩
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+/-- Counting independent local witnesses after fixing the shared assignment
+turns the number of transcripts into a sum of products. -/
+theorem card_siteWitnesses {Shared Site : Type*} [Fintype Shared] [Fintype Site]
+ {Local : Site → Type*} [∀ i, Finite (Local i)] (valid : Shared → (i : Site) → Local i → Prop) :
+ Nat.card {t : Shared × ((i : Site) → Local i) // ∀ i, valid t.1 i (t.2 i)} =
+ ∑ b, ∏ i, Nat.card {r : Local i // valid b i r} := by
+ rw [Nat.card_congr (siteWitnessEquiv valid), Nat.card_sigma]
+ simp only [Nat.card_pi]
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMGuessBudget.lean b/lean/OAI/Computability/VPVNP/RAMGuessBudget.lean
new file mode 100644
index 0000000000..2047a6b88d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMGuessBudget.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.RAMValidatorPaths
+
+/-!
+# A uniform bound on the private bit string of a successful site
+
+Every local binary choice uses one bit, and each admitted read guesses one
+full word. These bounds give the finite range for a tape program that chooses
+the complete private string, with a single stop at its selected length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMLayout
+
+variable {w : ℕ}
+
+theorem length_guessBits_le (es : List (Event w)) :
+ (guessBits es).length ≤ es.length + w * countProbes es := by
+ induction es with
+ | nil => simp [guessBits, countProbes]
+ | cons e es ih =>
+ cases e <;> simp only [guessBits, countProbes, List.length_cons, List.length_append,
+ length_wordBits, Nat.mul_add, Nat.mul_one] <;> omega
+
+private theorem length_guesses_blocks {C : Type*} {P : Program w C} {s fuel rs}
+ (h : LocalSegment P fuel s rs) :
+ (rs.flatMap (fun r => guessBits r.events)).length ≤
+ rs.length * fuel + w * RAMBuckets.probeCount Report.probes rs := by
+ induction rs generalizing s with
+ | nil => simp [RAMBuckets.probeCount]
+ | cons r rs ih =>
+ cases s with
+ | none => contradiction
+ | some s =>
+ have he := length_guessBits_le r.events
+ have hf := h.1.length_lt
+ have ht := ih h.2
+ simp only [List.flatMap_cons, List.length_append, List.length_cons, Nat.succ_mul,
+ RAMBuckets.probeCount, Nat.mul_add, Report.probes] at *
+ omega
+
+/-- This single public length bound works for every incident string arising
+from the shared-bit layout, independently of its acceptance or rejection by
+other sites. -/
+theorem PrivateRAM.Machine.incident_guesses_le {p r k d e : ℕ} (M : PrivateRAM.Machine w p r k)
+ (fuel : ℕ) (initial : Word w) (header : ℕ → Word w) (hw : 2 ≤ w)
+ (hc : 2^d * 2^e < 2^w) (bits : RawAssignment d e w) (v : Fin (2^d))
+ (path : M.IncidentPaths fuel initial (header v) hw hc v (incidentBits bits v)) :
+ path.val.length ≤ 2 * 2^e * (fuel+w) := by
+ obtain ⟨rs, hs⟩ := Option.isSome_iff_exists.mp path.property
+ obtain ⟨hval, he⟩ := (M.validateIncident_iff fuel initial header hw hc bits v path.val rs).mp hs
+ have hl := length_guesses_blocks hval.2.1.1.calls
+ have hcost := hval.2.1.1.cost_lt (Nat.two_pow_pos e)
+ rw [RAMBuckets.cost_eq_length_add_probes] at hcost
+ rw [he]
+ calc
+ _ ≤ _ := hl
+ _ ≤ (2*2^e)*fuel + w*(2*2^e) := Nat.add_le_add
+ (Nat.mul_le_mul_right _ (by omega)) (Nat.mul_le_mul_left _ (by omega))
+ _ = _ := by rw [Nat.mul_add, Nat.mul_comm w]
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMLayout.lean b/lean/OAI/Computability/VPVNP/RAMLayout.lean
new file mode 100644
index 0000000000..f60e6410cb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMLayout.lean
@@ -0,0 +1,325 @@
+import OAI.Computability.VPVNP.RAMSortRouting
+import Mathlib.Logic.Equiv.Fin.Basic
+import Mathlib.Tactic.Ring
+
+/-!
+# The communication fields of the RAM transcript
+
+Lemma 10.1 of *VP and VNP differ over every field* uses two successor fields and
+two fields for each cross-site sorting layer. We number the layers in phase order,
+with decreasing stride within each phase. A field bit has a contiguous local
+offset and either a unique matching bit at another site or a prescribed zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMLayout
+
+/-- Number of cross-site layers for `2^d` sites. -/
+def layerCount (d : ℕ) : ℕ := (d + 1).choose 2
+
+private theorem layerCount_succ (d : ℕ) : layerCount (d + 1) = layerCount d + (d + 1) := by
+ rw [layerCount, Nat.choose_succ_succ (d + 1) 1, Nat.choose_one_right, Nat.add_comm]
+ rfl
+
+/-- In phase `h + phase + 1` of an array with `2^h` positions per site,
+the cross-site strides decrease from `2^(h+phase)` to `2^h`. -/
+@[ext] structure Layer (d : ℕ) where
+ /-- Zero-based phase of the cross-site sorting network, below the number of site-index bits. -/
+ phase : ℕ
+ /-- Zero-based step in a sorting phase, ranging from zero through the phase number in
+ decreasing stride order. -/
+ step : ℕ
+ phase_lt : phase < d
+ step_le : step ≤ phase
+ deriving DecidableEq
+
+variable {d : ℕ}
+
+/-- Site-index bit flipped to find the partner at this layer, equal to the phase number minus
+its step. -/
+def Layer.siteBit (s : Layer d) : ℕ := s.phase - s.step
+
+theorem Layer.siteBit_lt (s : Layer d) : s.siteBit < d :=
+ lt_of_le_of_lt (Nat.sub_le _ _) s.phase_lt
+
+/-- Translate a cross-site layer to its ordinal among all exchanges. -/
+def Layer.ordinal (s : Layer d) : Fin (layerCount d) :=
+ ⟨layerCount s.phase + s.step, by
+ have h := Nat.choose_le_choose 2 (Nat.succ_le_succ s.phase_lt)
+ change layerCount (s.phase + 1) ≤ layerCount d at h
+ rw [layerCount_succ] at h
+ have := s.step_le
+ omega⟩
+
+/-- Decode a layer ordinal by comparing against one triangular prefix per phase. -/
+def layerAt : (d : ℕ) → Fin (layerCount d) → Layer d
+ | 0, i => Fin.elim0 i
+ | d + 1, i =>
+ if h : i.val < layerCount d then
+ let s := layerAt d ⟨i.val, h⟩
+ ⟨s.phase, s.step, Nat.lt_succ_of_lt s.phase_lt, s.step_le⟩
+ else
+ ⟨d, i.val - layerCount d, Nat.lt_succ_self _, by
+ have hbound := i.isLt
+ have := layerCount_succ d
+ omega⟩
+
+private theorem ordinal_layerAt (i : Fin (layerCount d)) : (layerAt d i).ordinal = i := by
+ induction d with
+ | zero => exact Fin.elim0 i
+ | succ d ih =>
+ apply Fin.ext
+ simp only [Layer.ordinal, layerAt]
+ split
+ · exact congrArg Fin.val (ih _)
+ · change layerCount d + (i.val - layerCount d) = i.val
+ omega
+
+private theorem Layer.ordinal_injective : Function.Injective (Layer.ordinal (d := d)) := by
+ intro a b hab
+ have hn := congrArg Fin.val hab
+ change layerCount a.phase + a.step = layerCount b.phase + b.step at hn
+ have upper (s : Layer d) : layerCount s.phase + s.step < layerCount (s.phase + 1) := by
+ rw [layerCount_succ]
+ exact Nat.add_lt_add_left (Nat.lt_succ_of_le s.step_le) _
+ have mono : Monotone layerCount := fun _ _ h ↦ Nat.choose_le_choose 2 (Nat.succ_le_succ h)
+ have hp : a.phase = b.phase := by
+ rcases lt_trichotomy a.phase b.phase with h | h | h
+ · have : layerCount (a.phase + 1) ≤ layerCount b.phase := mono h
+ have := upper a
+ omega
+ · exact h
+ · have : layerCount (b.phase + 1) ≤ layerCount a.phase := mono h
+ have := upper b
+ omega
+ exact Layer.ext hp (by rw [hp] at hn; omega)
+
+/-- Bijection between physical sorting layers and their consecutive field numbers. -/
+def layerEquiv (d : ℕ) : Layer d ≃ Fin (layerCount d) where
+ toFun := Layer.ordinal
+ invFun := layerAt d
+ left_inv s := Layer.ordinal_injective (ordinal_layerAt s.ordinal)
+ right_inv := ordinal_layerAt
+
+/-- One block in a sorting direction contains five words per padded record. -/
+def blockBits (H w : ℕ) : ℕ := 4 * H * 5 * w
+
+/-- Successor fields carry status, cost, state, and one final five-word record.
+The direction is zero for send and one for receive. -/
+abbrev Slot (d H w : ℕ) :=
+ (Fin 2 × Fin (8 * w)) ⊕ (Layer d × (Fin 2 × Fin (blockBits H w)))
+
+/-- Number of incident bits at one site, counting both successor fields and a send and receive
+block at every cross-site sorting layer. -/
+def width (d H w : ℕ) : ℕ := 2 * (8 * w) + layerCount d * (2 * blockBits H w)
+
+/-- Equation (10.1), with `d = log₂ S`. Both endpoints reserve both successor fields. -/
+theorem width_eq (d H w : ℕ) :
+ width d H w = 16 * w + 40 * H * w * (d + 1).choose 2 := by
+ unfold width blockBits layerCount
+ ring
+
+/-- A uniform constant in the asymptotic estimate of (10.1), with `H = 2^e`
+and `S = 2^d`. The sort has `log₂ (4HS)` phases. -/
+theorem width_le (d e w : ℕ) :
+ width d (2 ^ e) w ≤ 56 * (2 ^ e) * w * ((4 * 2 ^ e * 2 ^ d).log2) ^ 2 := by
+ have hlog : (4 * 2 ^ e * 2 ^ d).log2 = 2 + e + d := by
+ rw [show 4 * 2 ^ e * 2 ^ d = 2 ^ (2 + e + d) by rw [pow_add, pow_add]; rfl]
+ exact Nat.log2_two_pow
+ have hcount : (d + 1).choose 2 ≤ (2 + e + d) ^ 2 := by
+ rw [Nat.choose_two_right, pow_two]
+ exact (Nat.div_le_self _ _).trans (Nat.mul_le_mul (by omega) (by omega))
+ have hpos := Nat.two_pow_pos e
+ have hsquare : 1 ≤ (2 + e + d) ^ 2 := Nat.one_le_pow _ _ (by omega)
+ rw [width_eq, hlog]
+ calc
+ 16 * w + 40 * 2 ^ e * w * (d + 1).choose 2 ≤
+ (16 * 2 ^ e * w + 40 * 2 ^ e * w) * (2 + e + d) ^ 2 := by
+ rw [Nat.add_mul]
+ apply Nat.add_le_add
+ · exact (Nat.mul_le_mul_right w (Nat.le_mul_of_pos_right _ hpos)).trans
+ (Nat.le_mul_of_pos_right _ hsquare)
+ · exact Nat.mul_le_mul_left _ hcount
+ _ = _ := by ring
+
+/-- A contiguous, invertible bit address: the two successor fields precede the
+send/receive field pair for each sorting layer in chronological order. -/
+def offset (d H w : ℕ) : Slot d H w ≃ Fin (width d H w) :=
+ (finProdFinEquiv.sumCongr
+ (((layerEquiv d).prodCongr finProdFinEquiv).trans finProdFinEquiv)).trans finSumFinEquiv
+
+variable {H w : ℕ}
+
+theorem offset_successor (dir : Fin 2) (j : Fin (8 * w)) :
+ (offset d H w (.inl (dir, j))).val = 8 * w * dir.val + j.val := by
+ change j.val + 8 * w * dir.val = _
+ omega
+
+theorem offset_sort (s : Layer d) (dir : Fin 2) (j : Fin (blockBits H w)) :
+ (offset d H w (.inr (s, dir, j))).val =
+ 16 * w + s.ordinal.val * (2 * blockBits H w) + dir.val * blockBits H w + j.val := by
+ change 2 * (8 * w) + (j.val + blockBits H w * dir.val + 2 * blockBits H w * s.ordinal.val) = _
+ ring
+
+/-- The common partner of all records sent by a site at this layer. -/
+def Layer.partner (s : Layer d) (v : Fin (2 ^ d)) : Fin (2 ^ d) :=
+ ⟨RAMSort.partner s.siteBit v.val, RAMSort.partner_lt v.isLt s.siteBit_lt⟩
+
+@[simp] theorem Layer.partner_partner (s : Layer d) (v : Fin (2 ^ d)) :
+ s.partner (s.partner v) = v :=
+ Fin.ext (RAMSort.partner_partner _ _)
+
+theorem Layer.partner_ne (s : Layer d) (v : Fin (2 ^ d)) : s.partner v ≠ v :=
+ fun h ↦ RAMSort.partner_ne _ _ (congrArg Fin.val h)
+
+theorem Layer.record_partner (s : Layer d) (v : Fin (2 ^ d)) {h : ℕ} (j : Fin (2 ^ h)) :
+ RAMSort.partner (h + s.siteBit) (v.val * 2 ^ h + j.val) =
+ (s.partner v).val * 2 ^ h + j.val := by
+ simpa [Layer.partner] using RAMSort.partner_cross v.val j.isLt (Nat.le_add_right h s.siteBit)
+
+/-- The missing successor send at the last site and receive at the first site
+are represented by `none`. All other bits have one peer with opposite direction. -/
+def peer (v : Fin (2 ^ d)) : Slot d H w → Option (Fin (2 ^ d) × Slot d H w)
+ | .inl (dir, j) =>
+ if dir = 0 then
+ if h : v.val + 1 < 2 ^ d then some (⟨v.val + 1, h⟩, .inl (1, j)) else none
+ else
+ if h : 0 < v.val then some (⟨v.val - 1, by omega⟩, .inl (0, j)) else none
+ | .inr (s, dir, j) => some (s.partner v, .inr (s, dir.rev, j))
+
+theorem peer_send_end (v : Fin (2 ^ d)) (h : v.val + 1 = 2 ^ d) (j : Fin (8 * w)) :
+ peer (H := H) v (.inl (0, j)) = none := by simp [peer, h]
+
+theorem peer_receive_start (v : Fin (2 ^ d)) (h : v.val = 0) (j : Fin (8 * w)) :
+ peer (H := H) v (.inl (1, j)) = none := by simp [peer, h]
+
+/-- Direction of an incident bit, in both parts of the layout. -/
+def direction : Slot d H w → Fin 2
+ | .inl (dir, _) | .inr (_, dir, _) => dir
+
+private theorem peer_pair {v u : Fin (2 ^ d)} {p q : Slot d H w} (hp : peer v p = some (u, q)) :
+ peer u q = some (v, p) ∧ direction q = (direction p).rev := by
+ rcases p with ⟨dir, j⟩ | ⟨s, dir, j⟩
+ · by_cases hd : dir = 0
+ · subst dir
+ by_cases h : v.val + 1 < 2 ^ d
+ · simp [peer, h] at hp
+ obtain ⟨rfl, rfl⟩ := hp
+ exact ⟨by simp [peer], rfl⟩
+ · simp [peer, h] at hp
+ · have hdir : dir = 1 := by
+ apply Fin.ext
+ have := dir.isLt
+ have : dir.val ≠ 0 := fun he ↦ hd (Fin.ext he)
+ omega
+ subst dir
+ by_cases h : 0 < v.val
+ · simp [peer, h] at hp
+ obtain ⟨rfl, rfl⟩ := hp
+ have he : v.val - 1 + 1 = v.val := by omega
+ exact ⟨by simp [peer, he, v.isLt], rfl⟩
+ · simp [peer, h] at hp
+ · cases hp
+ exact ⟨by simp [peer], rfl⟩
+
+/-- Each actual connection pairs two ports and can be traced from either end. -/
+theorem peer_reverse {v u : Fin (2 ^ d)} {p q : Slot d H w} (hp : peer v p = some (u, q)) :
+ peer u q = some (v, p) := (peer_pair hp).1
+
+theorem peer_direction {v u : Fin (2 ^ d)} {p q : Slot d H w}
+ (hp : peer v p = some (u, q)) : direction q = (direction p).rev := (peer_pair hp).2
+
+private theorem rev_eq_zero_iff (i : Fin 2) : i.rev = 0 ↔ i ≠ 0 := by
+ simp only [ne_eq, Fin.ext_iff, Fin.val_rev]
+ have := i.isLt
+ change 2 - (i.val + 1) = 0 ↔ i.val ≠ 0
+ omega
+
+/-- One incident bit position specified by its site and its local communication slot. -/
+abbrev Endpoint (d H w : ℕ) := Fin (2 ^ d) × Slot d H w
+
+/-- Shared assignments carry one bit per existing send. There is no independent
+assignment to a clamped field or to the receiving copy of a shared bit. -/
+def IsSend (x : Endpoint d H w) : Prop :=
+ direction x.2 = 0 ∧ (peer x.1 x.2).isSome
+
+instance (x : Endpoint d H w) : Decidable (IsSend x) := by
+ unfold IsSend
+ infer_instance
+
+/-- A sending endpoint of an existing link, indexing the one Boolean shared with its matching
+receiving endpoint. -/
+abbrev SharedBit (d H w : ℕ) := {x : Endpoint d H w // IsSend x}
+
+/-- Locate a port's bit in the array of sends. A missing endpoint is zero. -/
+def source (x : Endpoint d H w) : Option (Endpoint d H w) :=
+ (peer x.1 x.2).map fun y ↦ if direction x.2 = 0 then x else y
+
+theorem source_shared {x s : Endpoint d H w} (hs : source x = some s) : IsSend s := by
+ cases h : peer x.1 x.2 with
+ | none => simp [source, h] at hs
+ | some y =>
+ by_cases hx : direction x.2 = 0
+ · simp [source, h, hx] at hs
+ subst s
+ simp [IsSend, hx, h]
+ · simp [source, h, hx] at hs
+ subst s
+ exact ⟨(peer_direction h).trans ((rev_eq_zero_iff _).2 hx), by simp [peer_reverse h]⟩
+
+private theorem source_send (s : SharedBit d H w) : source s.val = some s.val := by
+ have hh := s.property.2
+ cases h : peer s.val.1 s.val.2 with
+ | none => simp [h] at hh
+ | some y => simp [source, h, s.property.1]
+
+theorem source_peer {x y : Endpoint d H w} (h : peer x.1 x.2 = some y) :
+ source x = source y := by
+ have hr := peer_reverse h
+ have hd := peer_direction h
+ by_cases hx : direction x.2 = 0
+ · have hy : direction y.2 ≠ 0 := by simpa [hd, rev_eq_zero_iff] using hx
+ simp [source, h, hr, hx, hy]
+ · have hy : direction y.2 = 0 := hd.trans ((rev_eq_zero_iff _).2 hx)
+ simp [source, h, hr, hx, hy]
+
+/-- Clamps and pairwise equality are exactly the constraints on incident bit values. -/
+def Compatible (b : Endpoint d H w → Bool) : Prop :=
+ (∀ x, peer x.1 x.2 = none → b x = false) ∧
+ (∀ x y, peer x.1 x.2 = some y → b x = b y)
+
+private def sentValue (b : SharedBit d H w → Bool) (s : Endpoint d H w) : Bool :=
+ if h : IsSend s then b ⟨s, h⟩ else false
+
+/-- Shared assignments and compatible incident assignments have equal multiplicities,
+including the one-site case where both successor fields are clamped. -/
+def assignmentEquiv (d H w : ℕ) :
+ (SharedBit d H w → Bool) ≃ {b : Endpoint d H w → Bool // Compatible b} where
+ toFun b := ⟨fun x ↦ ((source x).map (sentValue b)).getD false, by
+ constructor
+ · intro x hx
+ simp [source, hx]
+ · intro x y hxy
+ exact congrArg (fun z ↦ (z.map (sentValue b)).getD false) (source_peer hxy)⟩
+ invFun b := fun s ↦ b.val s.val
+ left_inv b := funext fun s ↦ by simp [source_send, sentValue, s.property]
+ right_inv b := by
+ apply Subtype.ext
+ funext x
+ cases h : peer x.1 x.2 with
+ | none => simp [source, h, b.property.1 x h]
+ | some y =>
+ by_cases hx : direction x.2 = 0
+ · have hs : source x = some x := by simp [source, h, hx]
+ simp [hs, sentValue, source_shared hs]
+ · have hs : source x = some y := by simp [source, h, hx]
+ simp [hs, sentValue, source_shared hs, b.property.2 x y h]
+
+end RAMLayout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMLocalRun.lean b/lean/OAI/Computability/VPVNP/RAMLocalRun.lean
new file mode 100644
index 0000000000..061d2f1964
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMLocalRun.lean
@@ -0,0 +1,218 @@
+import OAI.Computability.VPVNP.RAMWordBits
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Binary paths of the private call interpreter
+
+A site processor in Lemma 10.1 follows the program's binary branches and reads
+exactly one word of guesses at a permitted external read. A write has no guessed
+value. The processor checks its instruction clock before dispatch, and checks
+its remaining probe budget before consuming read bits or recording a write.
+A successful call returns its unused bit suffix for the next call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- Bits used by the site validator, including the guesses made at reads. -/
+def guessBits : List (Event w) → List Bool
+ | [] => []
+ | .choice b :: es => b :: guessBits es
+ | .read _ v :: es => wordBits v ++ guessBits es
+ | _ :: es => guessBits es
+
+/-- Charge one probe for each external read or write and zero for a private tick or branch. -/
+def Event.probeCharge : Event w → ℕ
+ | .read .. | .write .. => 1
+ | _ => 0
+
+/-- Number of guess bits reserved by the site validator for this event. A branch uses one bit
+and a read uses one full word. -/
+def Event.guessWidth : Event w → ℕ
+ | .choice _ => 1
+ | .read .. => w
+ | _ => 0
+
+/-- Metered execution on a binary stream. `guessWork` counts reserved bit slots,
+including the requested slots when the stream ends during a guess. -/
+structure LocalCallRun (w : ℕ) where
+ /-- The successful call report and unused guess suffix, or `none` when the local execution
+ fails. -/
+ output : Option (Report w × List Bool)
+ /-- Number of instructions charged by the local interpreter, including the terminating
+ instruction when one executes. -/
+ instructions : ℕ
+ /-- Number of probe slots charged, including an allowed read that fails for lack of enough
+ guess bits. -/
+ probes : ℕ
+ /-- Number of guess-bit slots requested by branches and reads, including requests whose input
+ stream is too short. -/
+ guessWork : ℕ
+
+/-- One terminating instruction. -/
+def LocalCallRun.stop (out : Option (Report w × List Bool)) (probes guessWork : ℕ) : LocalCallRun w :=
+ ⟨out, 1, probes, guessWork⟩
+
+/-- One executed instruction followed by the remainder of this call. -/
+def LocalCallRun.prepend (e : Event w) (t : LocalCallRun w) : LocalCallRun w :=
+ ⟨t.output.map (fun (r, bits) => (r.prepend e, bits)), 1 + t.instructions,
+ e.probeCharge + t.probes, e.guessWidth + t.guessWork⟩
+
+/-- Interpret a call privately. The caller supplies the remaining allowance for
+probes after charging the unit for starting the call. -/
+def runLocalCall (P : Program w C) : ℕ → C → ℕ → List Bool → LocalCallRun w
+ | 0, _, _, _ => ⟨none, 0, 0, 0⟩
+ | f + 1, c, allowance, bits =>
+ match P.step c with
+ | .finish s => .stop (some (⟨[], s⟩, bits)) 0 0
+ | .reject => .stop none 0 0
+ | .localStep c' => (runLocalCall P f c' allowance bits).prepend .tick
+ | .branch next =>
+ match bits with
+ | [] => .stop none 0 1
+ | b :: bs => (runLocalCall P f (next b) allowance bs).prepend (.choice b)
+ | .read a next =>
+ match allowance with
+ | 0 => .stop none 0 0
+ | p + 1 =>
+ match takeWord w bits with
+ | none => .stop none 1 w
+ | some (v, bs) => (runLocalCall P f (next v) p bs).prepend (.read a v)
+ | .write a v c' =>
+ match allowance with
+ | 0 => .stop none 0 0
+ | p + 1 => (runLocalCall P f c' p bits).prepend (.write a v)
+
+theorem runLocalCall_spec {P : Program w C} {f c p bits tail} {r : Report w}
+ (h : (runLocalCall P f c p bits).output = some (r, tail)) :
+ Guessed P f c r.events r.result ∧ countProbes r.events ≤ p ∧ bits = guessBits r.events ++ tail := by
+ induction f generalizing c p bits tail r with
+ | zero => simp [runLocalCall] at h
+ | succ f ih =>
+ cases hs : P.step c with
+ | reject => simp [runLocalCall, hs, LocalCallRun.stop] at h
+ | finish s =>
+ simp only [runLocalCall, hs, LocalCallRun.stop, Option.some.injEq, Prod.mk.injEq] at h
+ obtain ⟨rfl, rfl⟩ := h
+ exact ⟨.done hs, Nat.zero_le _, rfl⟩
+ | localStep c' =>
+ simp only [runLocalCall, hs, LocalCallRun.prepend, Option.map_eq_some_iff] at h
+ obtain ⟨⟨r', t⟩, hr, he⟩ := h
+ cases he
+ obtain ⟨hg, hp, hb⟩ := ih hr
+ exact ⟨.step hs hg, hp, hb⟩
+ | branch next =>
+ cases bits with
+ | nil => simp [runLocalCall, hs, LocalCallRun.stop] at h
+ | cons b bs =>
+ simp only [runLocalCall, hs, LocalCallRun.prepend, Option.map_eq_some_iff] at h
+ obtain ⟨⟨r', t⟩, hr, he⟩ := h
+ cases he
+ obtain ⟨hg, hp, hb⟩ := ih hr
+ exact ⟨.branch hs hg, hp, congrArg (b :: ·) hb⟩
+ | read a next =>
+ cases p with
+ | zero => simp [runLocalCall, hs, LocalCallRun.stop] at h
+ | succ p =>
+ cases hw : takeWord w bits with
+ | none => simp [runLocalCall, hs, hw, LocalCallRun.stop] at h
+ | some z =>
+ obtain ⟨v, bs⟩ := z
+ simp only [runLocalCall, hs, hw, LocalCallRun.prepend, Option.map_eq_some_iff] at h
+ obtain ⟨⟨r', t⟩, hr, he⟩ := h
+ cases he
+ obtain ⟨hg, hp, hb⟩ := ih hr
+ refine ⟨.read hs hg, by change 1 + countProbes r'.events ≤ p + 1; omega, ?_⟩
+ change bits = (wordBits v ++ guessBits r'.events) ++ t
+ rw [List.append_assoc, ← hb]
+ exact (takeWord_eq_some_iff _ _ _).mp hw
+ | write a v c' =>
+ cases p with
+ | zero => simp [runLocalCall, hs, LocalCallRun.stop] at h
+ | succ p =>
+ simp only [runLocalCall, hs, LocalCallRun.prepend, Option.map_eq_some_iff] at h
+ obtain ⟨⟨r', t⟩, hr, he⟩ := h
+ cases he
+ obtain ⟨hg, hp, hb⟩ := ih hr
+ exact ⟨.write hs hg, by change 1 + countProbes r'.events ≤ p + 1; omega, hb⟩
+
+theorem Guessed.to_runLocalCall {P : Program w C} {f c es s}
+ (hg : Guessed P f c es s) {p : ℕ} (hp : countProbes es ≤ p) (tail : List Bool) :
+ (runLocalCall P f c p (guessBits es ++ tail)).output = some (⟨es, s⟩, tail) := by
+ induction hg generalizing p with
+ | done hs => simp [runLocalCall, hs, guessBits, LocalCallRun.stop]
+ | step hs _ ih =>
+ simp [runLocalCall, hs, guessBits, LocalCallRun.prepend, ih hp, Report.prepend]
+ | branch hs _ ih =>
+ simp [runLocalCall, hs, guessBits, LocalCallRun.prepend, ih hp, Report.prepend]
+ | read hs _ ih =>
+ rename_i es _ _
+ cases p with
+ | zero => simp [countProbes] at hp
+ | succ p =>
+ have ht : countProbes es ≤ p := by simp only [countProbes] at hp; omega
+ simp only [guessBits, List.append_assoc, runLocalCall, hs]
+ rw [(takeWord_eq_some_iff _ _ _).mpr rfl]
+ simp [LocalCallRun.prepend, ih ht, Report.prepend]
+ | write hs _ ih =>
+ rename_i es _ _
+ cases p with
+ | zero => simp [countProbes] at hp
+ | succ p =>
+ have ht : countProbes es ≤ p := by simp only [countProbes] at hp; omega
+ simp [runLocalCall, hs, guessBits, LocalCallRun.prepend, ih ht, Report.prepend]
+
+/-- A successful report determines the consumed binary string exactly. This
+also distinguishes branches with the same continuation or result. -/
+theorem runLocalCall_iff {P : Program w C} {f c p bits tail} {r : Report w} :
+ (runLocalCall P f c p bits).output = some (r, tail) ↔
+ Guessed P f c r.events r.result ∧ r.probes ≤ p ∧ bits = guessBits r.events ++ tail := by
+ refine ⟨runLocalCall_spec, ?_⟩
+ rintro ⟨hg, hp, rfl⟩
+ exact hg.to_runLocalCall hp tail
+
+/-- With exact use of the bits, every permitted trace has one accepting
+binary path through the local call simulator. -/
+theorem existsUnique_callBits {P : Program w C} {f c p} {r : Report w}
+ (hg : Guessed P f c r.events r.result) (hp : r.probes ≤ p) :
+ ∃! bs, (runLocalCall P f c p bs).output = some (r, []) := by
+ refine ⟨guessBits r.events, runLocalCall_iff.mpr ⟨hg, hp, by simp⟩, fun bs hb => ?_⟩
+ simpa using (runLocalCall_iff.mp hb).2.2
+
+/-- The three remaining allowances count the startup charge as well as the
+probes. A zero allowance rejects before the program sees its first instruction. -/
+def runChargedCall (P : Program w C) (f : ℕ) (c : C) (callLeft globalLeft siteLeft : ℕ)
+ (bits : List Bool) : LocalCallRun w :=
+ match min callLeft (min globalLeft siteLeft) with
+ | 0 => ⟨none, 0, 0, 0⟩
+ | p + 1 => runLocalCall P f c p bits
+
+theorem runChargedCall_iff {P : Program w C} {f c callLeft globalLeft siteLeft bits tail}
+ {r : Report w} :
+ (runChargedCall P f c callLeft globalLeft siteLeft bits).output = some (r, tail) ↔
+ Guessed P f c r.events r.result ∧ 1 + r.probes ≤ callLeft ∧
+ 1 + r.probes ≤ globalLeft ∧ 1 + r.probes ≤ siteLeft ∧ bits = guessBits r.events ++ tail := by
+ have hcap : ∀ x : ℕ, x ≤ min callLeft (min globalLeft siteLeft) ↔
+ x ≤ callLeft ∧ x ≤ globalLeft ∧ x ≤ siteLeft := fun x => by simp only [le_min_iff]
+ cases hm : min callLeft (min globalLeft siteLeft) with
+ | zero =>
+ simp only [runChargedCall, hm, reduceCtorEq, false_iff]
+ rintro ⟨_, hc, hg, hs, _⟩
+ have := (hcap _).mpr ⟨hc, hg, hs⟩
+ omega
+ | succ p =>
+ simp only [runChargedCall, hm, runLocalCall_iff]
+ have hc : r.probes ≤ p ↔ 1 + r.probes ≤ callLeft ∧ 1 + r.probes ≤ globalLeft ∧
+ 1 + r.probes ≤ siteLeft := by rw [← hcap, hm]; omega
+ tauto
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMLocalWork.lean b/lean/OAI/Computability/VPVNP/RAMLocalWork.lean
new file mode 100644
index 0000000000..9b9c3ee60f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMLocalWork.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.RAMLocalRun
+
+/-!
+# Pathwise work of a local RAM call
+
+The bounds hold for every supplied bit stream, including a stream that ends
+during a read, and every private state. A branch reserves one bit and a
+permitted read reserves one word. The instruction and probe counters bound
+the sum of these charges independently of whether the call succeeds.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+private structure LocalCallRun.Within (t : LocalCallRun w) (fuel allowance : ℕ) : Prop where
+ instructions_le : t.instructions ≤ fuel
+ probes_le : t.probes ≤ allowance
+ probes_le_instructions : t.probes ≤ t.instructions
+ guessWork_le : t.guessWork ≤ t.instructions + w * t.probes
+
+private theorem LocalCallRun.Within.prepend {t : LocalCallRun w} {fuel allowance : ℕ}
+ (h : t.Within fuel allowance) (e : Event w) :
+ (t.prepend e).Within (fuel + 1) (e.probeCharge + allowance) := by
+ obtain ⟨hi, hp, hpi, hg⟩ := h
+ have hcharge : e.probeCharge ≤ 1 := by cases e <;> simp [Event.probeCharge]
+ have hwidth : e.guessWidth ≤ 1 + w * e.probeCharge := by
+ cases e <;> simp [Event.probeCharge, Event.guessWidth]
+ constructor <;> simp only [LocalCallRun.prepend, Nat.mul_add] <;> omega
+
+private theorem runLocalCall_within (P : Program w C) (fuel : ℕ) (c : C)
+ (allowance : ℕ) (bits : List Bool) :
+ (runLocalCall P fuel c allowance bits).Within fuel allowance := by
+ induction fuel generalizing c allowance bits with
+ | zero => constructor <;> simp [runLocalCall]
+ | succ f ih =>
+ cases hs : P.step c with
+ | localStep c' =>
+ simpa [runLocalCall, hs, Event.probeCharge] using (ih c' allowance bits).prepend .tick
+ | branch next =>
+ cases bits with
+ | nil => constructor <;> simp [runLocalCall, hs, LocalCallRun.stop]
+ | cons b bs =>
+ simpa [runLocalCall, hs, Event.probeCharge] using
+ (ih (next b) allowance bs).prepend (.choice b)
+ | read a next =>
+ cases allowance with
+ | zero => constructor <;> simp [runLocalCall, hs, LocalCallRun.stop]
+ | succ p =>
+ cases hb : takeWord w bits with
+ | none => constructor <;> simp [runLocalCall, hs, hb, LocalCallRun.stop]
+ | some val =>
+ obtain ⟨v, bs⟩ := val
+ simpa [runLocalCall, hs, hb, Event.probeCharge, Nat.one_add] using
+ (ih (next v) p bs).prepend (.read a v)
+ | write a v c' =>
+ cases allowance with
+ | zero => constructor <;> simp [runLocalCall, hs, LocalCallRun.stop]
+ | succ p =>
+ simpa [runLocalCall, hs, Event.probeCharge, Nat.one_add] using
+ (ih c' p bits).prepend (.write a v)
+ | finish s => constructor <;> simp [runLocalCall, hs, LocalCallRun.stop]
+ | reject => constructor <;> simp [runLocalCall, hs, LocalCallRun.stop]
+
+/-- Pathwise bounds on dispatches, charged probes and reserved bit slots. -/
+theorem runLocalCall_bounds (P : Program w C) (fuel : ℕ) (c : C)
+ (allowance : ℕ) (bits : List Bool) :
+ let t := runLocalCall P fuel c allowance bits
+ t.instructions ≤ fuel ∧ t.probes ≤ allowance ∧
+ t.guessWork ≤ t.instructions + w * t.probes := by
+ obtain ⟨hi, hp, _, hg⟩ := runLocalCall_within P fuel c allowance bits
+ exact ⟨hi, hp, hg⟩
+
+/-- Counting one unit per dispatch, per charged probe and per reserved bit. -/
+theorem runLocalCall_totalWork_le (P : Program w C) (fuel : ℕ) (c : C)
+ (allowance : ℕ) (bits : List Bool) :
+ let t := runLocalCall P fuel c allowance bits
+ t.instructions + t.probes + t.guessWork ≤ 3 * fuel + w * allowance := by
+ obtain ⟨hi, hp, hpi, hg⟩ := runLocalCall_within P fuel c allowance bits
+ have := Nat.mul_le_mul_left w hp
+ dsimp only
+ omega
+
+/-- The startup unit leaves one fewer probe slot in each of the three
+allowances. If any allowance is zero the call uses no slots at all. -/
+theorem runChargedCall_bounds (P : Program w C) (fuel : ℕ) (c : C)
+ (callLeft globalLeft siteLeft : ℕ) (bits : List Bool) :
+ let t := runChargedCall P fuel c callLeft globalLeft siteLeft bits
+ t.instructions ≤ fuel ∧ t.probes ≤ min callLeft (min globalLeft siteLeft) - 1 ∧
+ t.guessWork ≤ t.instructions + w * t.probes := by
+ cases h : min callLeft (min globalLeft siteLeft) with
+ | zero => simp [runChargedCall, h]
+ | succ p => simpa [runChargedCall, h] using runLocalCall_bounds P fuel c p bits
+
+/-- Work of the charged interpreter on an arbitrary private bit stream. -/
+theorem runChargedCall_totalWork_le (P : Program w C) (fuel : ℕ) (c : C)
+ (callLeft globalLeft siteLeft : ℕ) (bits : List Bool) :
+ let t := runChargedCall P fuel c callLeft globalLeft siteLeft bits
+ t.instructions + t.probes + t.guessWork ≤
+ 3 * fuel + w * (min callLeft (min globalLeft siteLeft) - 1) := by
+ cases h : min callLeft (min globalLeft siteLeft) with
+ | zero => simp [runChargedCall, h]
+ | succ p => simpa [runChargedCall, h] using runLocalCall_totalWork_le P fuel c p bits
+
+private theorem Guessed.runLocalCall_probes {P : Program w C} {f c es s}
+ (hg : Guessed P f c es s) {p : ℕ} (hp : countProbes es ≤ p) (tail : List Bool) :
+ (runLocalCall P f c p (guessBits es ++ tail)).probes = countProbes es := by
+ induction hg generalizing p with
+ | done hs => simp [runLocalCall, hs, LocalCallRun.stop, countProbes]
+ | step hs _ ih =>
+ simpa [runLocalCall, hs, guessBits, LocalCallRun.prepend, Event.probeCharge, countProbes]
+ using ih hp
+ | branch hs _ ih =>
+ simpa [runLocalCall, hs, guessBits, LocalCallRun.prepend, Event.probeCharge, countProbes]
+ using ih hp
+ | read hs _ ih =>
+ rename_i es _ _
+ cases p with
+ | zero => simp [countProbes] at hp
+ | succ p =>
+ have ht : countProbes es ≤ p := by simp only [countProbes] at hp; omega
+ simp only [runLocalCall, hs, guessBits, List.append_assoc]
+ rw [(takeWord_eq_some_iff _ _ _).mpr rfl]
+ simp [LocalCallRun.prepend, Event.probeCharge, countProbes, ih ht]
+ | write hs _ ih =>
+ rename_i es _ _
+ cases p with
+ | zero => simp [countProbes] at hp
+ | succ p =>
+ have ht : countProbes es ≤ p := by simp only [countProbes] at hp; omega
+ simp [runLocalCall, hs, guessBits, LocalCallRun.prepend, Event.probeCharge, countProbes,
+ ih ht]
+
+/-- On success, the accumulated counter gives the report's probe count. The
+site loop can advance its charge using this counter without scanning events. -/
+theorem runChargedCall_probes_eq {P : Program w C} {fuel c callLeft globalLeft siteLeft bits tail}
+ {r : Report w}
+ (h : (runChargedCall P fuel c callLeft globalLeft siteLeft bits).output = some (r, tail)) :
+ (runChargedCall P fuel c callLeft globalLeft siteLeft bits).probes = r.probes := by
+ cases hm : min callLeft (min globalLeft siteLeft) with
+ | zero => simp [runChargedCall, hm] at h
+ | succ p =>
+ simp only [runChargedCall, hm] at h ⊢
+ obtain ⟨hg, hp, rfl⟩ := runLocalCall_iff.mp h
+ exact hg.runLocalCall_probes hp tail
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMLoggedCall.lean b/lean/OAI/Computability/VPVNP/RAMLoggedCall.lean
new file mode 100644
index 0000000000..c375cf667e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMLoggedCall.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.RAMPrivateLogRun
+
+/-!
+# Single-pass metered private call execution
+
+The instruction interpreter uses the write log for private memory, reads a
+private cell and its work count in the same scan, and threads the report and
+operation count through the same call recursion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM
+
+open VPVNP.BurstRAM
+
+variable {w p r k : ℕ} {C : Type*}
+
+/-- Charge the actual lookup in a log implementation, stopping at the first
+matching write. Only a store extends the log. -/
+def Instr.actualLogWork (i : Instr w p r k) (l : LogConfig w p r) : ℕ :=
+ match i with
+ | .loadPrivate _ addr _ => (WriteLog.scan l.writes (l.reg addr)).2
+ | .storePrivate .. => 3
+ | _ => 0
+
+/-- The private load uses the value and cost of the same linear scan. -/
+def Instr.meteredAction (i : Instr w p r k) (pub : Fin k → Word w) (l : LogConfig w p r) :
+ CallAction w (LogConfig w p r) × ℕ :=
+ match i with
+ | .loadPrivate dst addr next =>
+ let t := WriteLog.scan l.writes (l.reg addr)
+ (.localStep {l with pc := next, reg := Function.update l.reg dst t.1}, i.wordWork + t.2)
+ | .storePrivate .. => (i.runLogged pub l, i.wordWork + 3)
+ | _ => (i.runLogged pub l, i.wordWork)
+
+theorem Instr.meteredAction_spec (i : Instr w p r k) (pub : Fin k → Word w) (l : LogConfig w p r) :
+ i.meteredAction pub l = (i.runLogged pub l, i.wordWork + i.actualLogWork l) := by
+ cases i <;> rfl
+
+/-- The frame gives the charged result of a stopping instruction or the one
+continuation invocation and the event to prepend on return. -/
+inductive CallFrame (w : ℕ) (C : Type*)
+ | stop (out : LocalCallRun w)
+ | next (event : Event w) (config : C) (allowance : ℕ) (bits : List Bool)
+
+/-- Resolve one instruction action using the remaining probe allowance and choice stream.
+Produce either a stopping result or an event with its residual call state. -/
+def CallFrame.ofAction : CallAction w C → ℕ → List Bool → CallFrame w C
+ | .finish s, _, bits => .stop (.stop (some (⟨[], s⟩, bits)) 0 0)
+ | .reject, _, _ => .stop (.stop none 0 0)
+ | .localStep c, a, bits => .next .tick c a bits
+ | .branch _, _, [] => .stop (.stop none 0 1)
+ | .branch c, a, b :: bits => .next (.choice b) (c b) a bits
+ | .read .., 0, _ | .write .., 0, _ => .stop (.stop none 0 0)
+ | .read addr c, a + 1, bits =>
+ match takeWord w bits with
+ | none => .stop (.stop none 1 w)
+ | some (v, tail) => .next (.read addr v) (c v) a tail
+ | .write addr v c, a + 1, bits => .next (.write addr v) c a bits
+
+/-- Evaluate a call frame, prepending its event to the recursive run when the frame continues. -/
+def CallFrame.result (recur : C → ℕ → List Bool → LocalCallRun w) : CallFrame w C → LocalCallRun w
+ | .stop t => t
+ | .next e c a bs => (recur c a bs).prepend e
+
+theorem CallFrame.result_eq (P : Program w C) (f : ℕ) (c : C) (a : ℕ) (bits : List Bool) :
+ (ofAction (P.step c) a bits).result (runLocalCall P f) = runLocalCall P (f+1) c a bits := by
+ cases hs : P.step c with
+ | finish | reject | localStep => simp [runLocalCall, hs, ofAction, result]
+ | branch => cases bits <;> simp [runLocalCall, hs, ofAction, result]
+ | write => cases a <;> simp [runLocalCall, hs, ofAction, result]
+ | read =>
+ cases a with
+ | zero => simp [runLocalCall, hs, ofAction, result]
+ | succ a =>
+ cases h : takeWord w bits with
+ | none => simp [runLocalCall, hs, ofAction, result, h]
+ | some pair =>
+ obtain ⟨v, rest⟩ := pair
+ simp [runLocalCall, hs, ofAction, result, h]
+
+/-- The interpreter controls reserve eight word operations per dispatch,
+five stores per occupied probe, and four operations per guess bit. -/
+def LocalCharge (t : LocalCallRun w) : ℕ := 8*t.instructions + 5*t.probes + 4*t.guessWork
+
+/-- Interpreter work charged to one continuing event, with eight operations for dispatch, five
+per probe and four per requested guess bit. -/
+def EventCharge (e : Event w) : ℕ := 8 + 5*e.probeCharge + 4*e.guessWidth
+
+theorem localCharge_prepend (e : Event w) (t : LocalCallRun w) :
+ LocalCharge (t.prepend e) = EventCharge e + LocalCharge t := by
+ simp only [LocalCharge, EventCharge, LocalCallRun.prepend, Nat.mul_add, Nat.mul_one]
+ omega
+
+/-- Run a bounded private call using its write log and return both the local execution and its
+work, charging each actual log scan in that execution. -/
+def Machine.meteredLoggedCall (M : Machine w p r k) :
+ ℕ → LogConfig w p r → ℕ → List Bool → LocalCallRun w × ℕ
+ | 0, _, _, _ => (⟨none, 0, 0, 0⟩, 0)
+ | f+1, l, a, bits =>
+ let step := (M.code l.pc).meteredAction M.publicData l
+ match CallFrame.ofAction step.1 a bits with
+ | .stop t => (t, step.2 + LocalCharge t)
+ | .next e c a' bs =>
+ let tail := M.meteredLoggedCall f c a' bs
+ (tail.1.prepend e, step.2 + EventCharge e + tail.2)
+
+theorem Machine.meteredLoggedCall_logResult (M : Machine w p r k) (fuel : ℕ) (l : LogConfig w p r)
+ (a : ℕ) (bits : List Bool) :
+ (M.meteredLoggedCall fuel l a bits).1 = runLocalCall M.logProgram fuel l a bits := by
+ induction fuel generalizing l a bits with
+ | zero => rfl
+ | succ f ih =>
+ rw [Machine.meteredLoggedCall, Instr.meteredAction_spec, ← CallFrame.result_eq]
+ change ((match CallFrame.ofAction (M.logProgram.step l) a bits with
+ | .stop t => (t, _)
+ | .next e c a' bs => ((M.meteredLoggedCall f c a' bs).1.prepend e, _))
+ : LocalCallRun w × ℕ).1 = _
+ cases h : CallFrame.ofAction (M.logProgram.step l) a bits with
+ | stop t => rfl
+ | next e c a' bs => simp [CallFrame.result, ih]
+
+theorem Machine.meteredLoggedCall_result (M : Machine w p r k) (fuel : ℕ) (l : LogConfig w p r)
+ (a : ℕ) (bits : List Bool) :
+ (M.meteredLoggedCall fuel l a bits).1 = runLocalCall M.program fuel l.denote a bits :=
+ (M.meteredLoggedCall_logResult ..).trans (M.runLocalCall_logProgram ..)
+
+end BurstRAM.PrivateRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMLoggedSite.lean b/lean/OAI/Computability/VPVNP/RAMLoggedSite.lean
new file mode 100644
index 0000000000..95d3326d77
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMLoggedSite.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.RAMLoggedCall
+import OAI.Computability.VPVNP.RAMSiteWork
+
+/-!
+# Single-pass site loop with concrete private word work
+
+A site starts every charged call with a fresh write log, records the call's
+work in the same recursion that obtains its report, and uses its probe count
+to advance the cut. The final loop check costs sixteen operations even when
+no call can start.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM
+
+open VPVNP.BurstRAM
+
+variable {w p r k : ℕ}
+
+/-- Charge startup against each remaining allowance before dispatching.
+Every attempted call returns both the metered run and its word work. -/
+def Machine.loggedChargedCall (M : Machine w p r k) (fuel : ℕ) (s : Word w)
+ (callLeft globalLeft siteLeft : ℕ) (bits : List Bool) : LocalCallRun w × ℕ :=
+ match min callLeft (min globalLeft siteLeft) with
+ | 0 => (⟨none, 0, 0, 0⟩, 0)
+ | a + 1 => M.meteredLoggedCall fuel (M.logProgram.start s) a bits
+
+theorem Machine.loggedChargedCall_result (M : Machine w p r k) (fuel : ℕ) (s : Word w)
+ (callLeft globalLeft siteLeft : ℕ) (bits : List Bool) :
+ (M.loggedChargedCall fuel s callLeft globalLeft siteLeft bits).1 =
+ runChargedCall M.program fuel (M.program.start s) callLeft globalLeft siteLeft bits := by
+ cases h : min callLeft (min globalLeft siteLeft) with
+ | zero => simp [Machine.loggedChargedCall, runChargedCall, h]
+ | succ a => simp [Machine.loggedChargedCall, runChargedCall, h,
+ Machine.meteredLoggedCall_result, Machine.logProgram_start]
+
+/-- A single run returns the reports, unused suffix and total primitive work.
+The sixteen control operations cover the cut tests, budget arithmetic and
+collection of the returned reports. -/
+def Machine.runLoggedSite (M : Machine w p r k) (fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) : MeteredSiteRun w :=
+ if c.cost ≤ globalCap then
+ match c.state with
+ | none => ⟨some ([], bits), 16⟩
+ | some s =>
+ if c.cost < boundary then
+ match steps with
+ | 0 => ⟨none, 16⟩
+ | n + 1 =>
+ let t := M.loggedChargedCall fuel s H (globalCap - c.cost) siteLeft bits
+ let work := 16 + t.2
+ match t.1.output with
+ | none => ⟨none, work⟩
+ | some (report, tail) =>
+ let charge := 1 + t.1.probes
+ let rest := M.runLoggedSite fuel H boundary globalCap n
+ ⟨c.cost + charge, report.result⟩ (siteLeft - charge) tail
+ ⟨rest.output.map (fun (rs, bs) => (report :: rs, bs)), work + rest.work⟩
+ else ⟨some ([], bits), 16⟩
+ else ⟨none, 16⟩
+termination_by structural steps
+
+/-- The logged interpreter follows exactly the reports and binary choices
+used in the validator's path-counting theorem. -/
+theorem Machine.runLoggedSite_output (M : Machine w p r k) (fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) :
+ (M.runLoggedSite fuel H boundary globalCap steps c siteLeft bits).output =
+ runSiteLoop M.program fuel H boundary globalCap steps c siteLeft bits := by
+ rw [← meteredSiteLoop_output_eq M.program 16]
+ induction steps generalizing c siteLeft bits with
+ | zero =>
+ rw [Machine.runLoggedSite, meteredSiteLoop]
+ by_cases hc : c.cost ≤ globalCap
+ · cases c.state <;> simp [hc]
+ · simp [hc]
+ | succ n ih =>
+ rw [Machine.runLoggedSite, meteredSiteLoop]
+ by_cases hc : c.cost ≤ globalCap
+ · cases hs : c.state with
+ | none => simp [hc]
+ | some s =>
+ by_cases hb : c.cost < boundary
+ · simp only [hc, hb, ↓reduceIte, Machine.loggedChargedCall_result]
+ cases (runChargedCall M.program fuel (M.program.start s) H
+ (globalCap - c.cost) siteLeft bits).output with
+ | none => rfl
+ | some z => obtain ⟨report, tail⟩ := z; simp only [ih]
+ · simp [hc, hb]
+ · simp [hc]
+
+end BurstRAM.PrivateRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMMemory.lean b/lean/OAI/Computability/VPVNP/RAMMemory.lean
new file mode 100644
index 0000000000..10c932d2d1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMMemory.lean
@@ -0,0 +1,343 @@
+import Mathlib.Data.List.Sort
+import Mathlib.Data.Prod.Lex
+import Mathlib.Order.WithBot
+
+/-!
+# Memory checks in the distributed RAM transcript
+
+In Lemma 10.1, the guessed values of external reads are checked using only the
+previous record in address-sorted order. Initialization records are writes.
+The chronological semantics below leaves memory unchanged on a read, and
+checks the guessed value against the actual current memory.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMMemory
+
+/-- Memory transcript operation, distinguished as a header initialization, an external read or
+an external write. -/
+inductive Kind where
+ | init | read | write
+ deriving DecidableEq
+
+/-- Nonempty five-word records. Padding is represented by `none`. -/
+structure Record (Word : Type*) where
+ /-- Operation that produced this record, used to give header initialization priority over
+ later probes. -/
+ kind : Kind
+ /-- External address to which this initialization or probe refers. -/
+ address : ℕ
+ /-- Word installed by an initialization or write, or the value claimed by a read. -/
+ value : Word
+ /-- Cumulative cost at the start of the issuing call. Initialization records use their own
+ address in this timestamp field. -/
+ startCost : ℕ
+ /-- Probe index within its issuing call, used with the start cost to order probes
+ chronologically. -/
+ ordinal : ℕ
+ deriving DecidableEq
+
+variable {Word : Type*}
+
+/-- Initialization precedes every probe. Probes are ordered by the starting
+cost of their call and their ordinal within that call. -/
+def Record.timestamp (r : Record Word) : Lex (ℕ × Lex (ℕ × ℕ)) :=
+ toLex (if r.kind = .init then 0 else 1, toLex (r.startCost, r.ordinal))
+
+/-- The order of events in the RAM computation. -/
+def Chronological (records : List (Record Word)) : Prop :=
+ records.Pairwise fun x y => x.timestamp < y.timestamp
+
+/-- Strict order of the nonempty keys in the sorted probe array. -/
+def AddressSorted (records : List (Record Word)) : Prop :=
+ records.Pairwise fun x y => x.address < y.address ∨
+ x.address = y.address ∧ x.timestamp < y.timestamp
+
+/-- Execute one probe. A read does not modify memory. -/
+def afterRecord (mem : ℕ → Word) (r : Record Word) : ℕ → Word :=
+ fun a => if r.kind = .read then mem a else Function.update mem r.address r.value a
+
+/-- Correctness of the claimed read values under ordinary sequential RAM
+execution from the given memory. Writes may overwrite any previous value. -/
+def ReadsCorrect (mem : ℕ → Word) : List (Record Word) → Prop
+ | [] => True
+ | r :: rs => (r.kind = .read → r.value = mem r.address) ∧
+ ReadsCorrect (afterRecord mem r) rs
+
+variable [Zero Word]
+
+/-- Previous value if the previous record addresses this cell, and zero
+otherwise. This needs only the predecessor site's last record at a block edge. -/
+def previousValue (previous : Option (Record Word)) (address : ℕ) : Word :=
+ match previous with
+ | none => 0
+ | some r => if r.address = address then r.value else 0
+
+/-- The local predecessor test on all reads of one block. -/
+def PredecessorCheck (previous : Option (Record Word)) : List (Record Word) → Prop
+ | [] => True
+ | r :: rs => (r.kind = .read → r.value = previousValue previous r.address) ∧
+ PredecessorCheck (some r) rs
+
+private def atAddress (a : ℕ) (records : List (Record Word)) :=
+ records.filter fun r => r.address == a
+
+private def cellCheck (v : Word) : List (Record Word) → Prop
+ | [] => True
+ | r :: rs => (r.kind = .read → r.value = v) ∧
+ cellCheck (if r.kind = .read then v else r.value) rs
+
+omit [Zero Word] in
+private theorem readsCorrect_iff_cells (mem : ℕ → Word) (records : List (Record Word)) :
+ ReadsCorrect mem records ↔ ∀ a, cellCheck (mem a) (atAddress a records) := by
+ induction records generalizing mem with
+ | nil => simp [ReadsCorrect, atAddress, cellCheck]
+ | cons r rs ih =>
+ rw [ReadsCorrect, ih]
+ have hsame : afterRecord mem r r.address =
+ if r.kind = .read then mem r.address else r.value := by
+ split <;> simp_all [afterRecord]
+ have hother (a : ℕ) (ha : r.address ≠ a) : afterRecord mem r a = mem a := by
+ simp [afterRecord, Function.update_of_ne ha.symm]
+ constructor
+ · rintro ⟨hread, htail⟩ a
+ by_cases ha : r.address = a
+ · subst a
+ simpa [atAddress, cellCheck, hsame] using And.intro hread (htail r.address)
+ · simpa [atAddress, ha, hother a ha] using htail a
+ · intro hall
+ have h := hall r.address
+ simp [atAddress, cellCheck] at h
+ refine ⟨h.1, fun a => ?_⟩
+ by_cases ha : r.address = a
+ · subst a
+ simpa [hsame, atAddress] using h.2
+ · simpa [atAddress, ha, hother a ha] using hall a
+
+omit [Zero Word] in
+/-- Sorting groups each address while preserving its complete probe history,
+including intermediate reads. Strict timestamps prevent tie ambiguities. -/
+private theorem address_histories_eq {chron sorted : List (Record Word)}
+ (hp : chron.Perm sorted) (hc : Chronological chron) (hs : AddressSorted sorted) (a : ℕ) :
+ atAddress a chron = atAddress a sorted := by
+ let p := fun (r : Record Word) => r.address == a
+ have hchron := hc.filter p
+ have hsorted := hs.filter p
+ have htime : (sorted.filter p).Pairwise fun x y => x.timestamp < y.timestamp := by
+ apply hsorted.imp_of_mem
+ intro x y hx hy hxy
+ have hxa : x.address = a := by simpa [p] using (List.mem_filter.mp hx).2
+ have hya : y.address = a := by simpa [p] using (List.mem_filter.mp hy).2
+ simpa [hxa, hya] using hxy
+ exact (hp.filter p).eq_of_pairwise (fun _ _ _ _ hxy hyx => (lt_asymm hxy hyx).elim)
+ hchron htime
+
+private theorem predecessorCheck_iff_sorted {previous : Option (Record Word)}
+ {mem : ℕ → Word} {sorted : List (Record Word)} (hs : AddressSorted sorted)
+ (hp : ∀ p ∈ previous, ∀ r ∈ sorted, p.address ≤ r.address)
+ (hm : ∀ r ∈ sorted, mem r.address = previousValue previous r.address) :
+ PredecessorCheck previous sorted ↔ ReadsCorrect mem sorted := by
+ induction sorted generalizing previous mem with
+ | nil => simp [PredecessorCheck, ReadsCorrect]
+ | cons r rs ih =>
+ obtain ⟨hr, htail⟩ := List.pairwise_cons.mp hs
+ have hle (s : Record Word) (hsr : s ∈ rs) : r.address ≤ s.address :=
+ (hr s hsr).elim le_of_lt (fun h => h.1.le)
+ rw [PredecessorCheck, ReadsCorrect, hm r (List.mem_cons_self ..)]
+ apply and_congr_right
+ intro hread
+ apply ih htail
+ · simpa using hle
+ · intro s hsr
+ by_cases heq : r.address = s.address
+ · rw [← heq]
+ simp only [previousValue, afterRecord]
+ by_cases hk : r.kind = .read
+ · simpa [hk, hm r (List.mem_cons_self ..)] using (hread hk).symm
+ · simp [hk]
+ · have hzero : previousValue previous s.address = 0 := by
+ cases previous with
+ | none => rfl
+ | some p =>
+ have hpr := hp p (by simp) r (List.mem_cons_self ..)
+ have hps : p.address ≠ s.address :=
+ (lt_of_le_of_lt hpr (lt_of_le_of_ne (hle s hsr) heq)).ne
+ simp [previousValue, hps]
+ simp [afterRecord, Function.update_of_ne (Ne.symm heq), previousValue, heq,
+ (hm s (List.mem_cons_of_mem _ hsr)).trans hzero]
+
+/-- The neighboring-record tests on the actual sorted permutation accept
+exactly the chronological histories whose read answers are correct. -/
+theorem predecessorCheck_iff_readsCorrect {chron sorted : List (Record Word)}
+ (hp : chron.Perm sorted) (hc : Chronological chron) (hs : AddressSorted sorted) :
+ PredecessorCheck none sorted ↔ ReadsCorrect (fun _ => 0) chron := by
+ rw [predecessorCheck_iff_sorted (mem := fun _ => 0) hs (by simp) (by simp [previousValue])]
+ rw [readsCorrect_iff_cells, readsCorrect_iff_cells]
+ exact forall_congr' fun a => by rw [address_histories_eq hp hc hs a]
+
+/-- Successor messages suffice for blockwise checking, including the case
+of an empty block. -/
+theorem predecessorCheck_append (previous : Option (Record Word)) (xs ys : List (Record Word)) :
+ PredecessorCheck previous (xs ++ ys) ↔
+ PredecessorCheck previous xs ∧ PredecessorCheck (xs.getLast?.or previous) ys := by
+ induction xs generalizing previous with
+ | nil => simp [PredecessorCheck]
+ | cons r rs ih =>
+ rw [List.cons_append, PredecessorCheck, PredecessorCheck, ih]
+ cases rs <;> simp [and_assoc, List.getLast?_cons]
+
+/-- The initialization writes specified by the headers at addresses below S. -/
+def initRecord (header : ℕ → Word) (a : ℕ) : Record Word := ⟨.init, a, header a, a, 0⟩
+
+/-- Header initialization writes for the consecutive addresses from zero through `S - 1`,
+listed in address order. -/
+def initialRecords (S : ℕ) (header : ℕ → Word) : List (Record Word) :=
+ (List.range S).map (initRecord header)
+
+/-- External memory with the supplied header words below `S` and zero at every higher address. -/
+def initialMemory (S : ℕ) (header : ℕ → Word) (a : ℕ) : Word :=
+ if a < S then header a else 0
+
+/-- Processing the synthetic initialization writes installs exactly the header
+memory, retaining zero on all other addresses. -/
+theorem readsCorrect_initialRecords_append (S : ℕ) (header : ℕ → Word)
+ (probes : List (Record Word)) :
+ ReadsCorrect (fun _ => 0) (initialRecords S header ++ probes) ↔
+ ReadsCorrect (initialMemory S header) probes := by
+ induction S generalizing probes with
+ | zero =>
+ have hz : initialMemory 0 header = fun _ => 0 := by funext a; simp [initialMemory]
+ simp [initialRecords, hz]
+ | succ S ih =>
+ have hlist : initialRecords (S + 1) header = initialRecords S header ++ [initRecord header S] := by
+ simp [initialRecords, List.range_succ]
+ rw [hlist, List.append_assoc, List.singleton_append, ih, ReadsCorrect]
+ have hmem : afterRecord (initialMemory S header) (initRecord header S) =
+ initialMemory (S + 1) header := by
+ funext a
+ by_cases h : a = S
+ · subst a
+ simp [afterRecord, initRecord, initialMemory]
+ · have hequiv : a < S + 1 ↔ a < S := by omega
+ simp [afterRecord, initRecord, Function.update_of_ne h, initialMemory, hequiv]
+ rw [hmem]
+ simp [initRecord]
+
+omit [Zero Word] in
+theorem chronological_initialRecords_append {S : ℕ} {header : ℕ → Word}
+ {probes : List (Record Word)} (ht : Chronological probes)
+ (hprobe : ∀ r ∈ probes, r.kind ≠ .init) :
+ Chronological (initialRecords S header ++ probes) := by
+ apply List.pairwise_append.mpr
+ refine ⟨?_, ht, ?_⟩
+ · apply List.pairwise_map.mpr
+ exact List.pairwise_lt_range.imp fun h => by
+ simp [initRecord, Record.timestamp, Prod.Lex.toLex_lt_toLex, h]
+ · intro r hr s hs
+ obtain ⟨a, _, rfl⟩ := List.mem_map.mp hr
+ simp [initRecord, Record.timestamp, Prod.Lex.toLex_lt_toLex, hprobe s hs]
+
+/-- The nonempty key has four components: address, initialization priority,
+starting cost, and ordinal. A padding record is larger than every such key. -/
+def paddedKey : Option (Record Word) → WithTop (Lex (ℕ × Lex (ℕ × Lex (ℕ × ℕ))))
+ | none => ⊤
+ | some r => ↑(toLex (r.address, r.timestamp))
+
+omit [Zero Word] in
+theorem addressSorted_of_padded_sort {chron : List (Record Word)}
+ {sorted : List (Option (Record Word))} (hp : chron.Perm (sorted.filterMap id))
+ (hc : Chronological chron) (hs : sorted.Pairwise fun x y => paddedKey x ≤ paddedKey y) :
+ AddressSorted (sorted.filterMap id) := by
+ have hle : (sorted.filterMap id).Pairwise fun x y =>
+ x.address < y.address ∨ x.address = y.address ∧ x.timestamp ≤ y.timestamp := by
+ apply hs.filterMap id
+ intro x y h s hx t hy
+ change x = some s at hx
+ change y = some t at hy
+ subst x
+ subst y
+ simpa [paddedKey, Prod.Lex.toLex_le_toLex] using h
+ have hn : (chron.map Record.timestamp).Nodup :=
+ List.nodup_iff_pairwise_ne.mpr (List.pairwise_map.mpr (hc.imp fun h => h.ne))
+ have hn' := (hp.map Record.timestamp).nodup_iff.mp hn
+ have hne := List.pairwise_map.mp (List.nodup_iff_pairwise_ne.mp hn')
+ exact (hle.and hne).imp fun ⟨hord, hd⟩ => hord.imp_right fun ⟨ha, ht⟩ =>
+ ⟨ha, lt_of_le_of_ne ht hd⟩
+
+/-- Validation after sorting and removing padding agrees with executing the
+probes against the specified headers. The premises on the sort are its usual
+permutation and non-strict ordering postconditions. -/
+theorem padded_predecessorCheck_iff {S : ℕ} {header : ℕ → Word}
+ {probes : List (Record Word)} {raw sorted : List (Option (Record Word))}
+ (hrecords : (initialRecords S header ++ probes).Perm (raw.filterMap id))
+ (hperm : raw.Perm sorted) (hsorted : sorted.Pairwise fun x y => paddedKey x ≤ paddedKey y)
+ (ht : Chronological probes) (hprobe : ∀ r ∈ probes, r.kind ≠ .init) :
+ PredecessorCheck none (sorted.filterMap id) ↔ ReadsCorrect (initialMemory S header) probes := by
+ have hp := hrecords.trans (hperm.filterMap id)
+ have hc := chronological_initialRecords_append (S := S) (header := header) ht hprobe
+ exact (predecessorCheck_iff_readsCorrect hp hc (addressSorted_of_padded_sort hp hc hsorted)).trans
+ (readsCorrect_initialRecords_append S header probes)
+
+/-- The site validator scans its physical slots, including empties. Its
+incoming predecessor field is the final physical slot of the preceding site. -/
+def PaddedCheck (previous : Option (Record Word)) : List (Option (Record Word)) → Prop
+ | [] => True
+ | none :: rs => PaddedCheck none rs
+ | some r :: rs => (r.kind = .read → r.value = previousValue previous r.address) ∧
+ PaddedCheck (some r) rs
+
+theorem paddedCheck_append (previous : Option (Record Word))
+ (xs ys : List (Option (Record Word))) :
+ PaddedCheck previous (xs ++ ys) ↔
+ PaddedCheck previous xs ∧ PaddedCheck (xs.getLast?.getD previous) ys := by
+ induction xs generalizing previous with
+ | nil => simp [PaddedCheck]
+ | cons r rs ih =>
+ cases r with
+ | none =>
+ rw [List.cons_append, PaddedCheck, PaddedCheck, ih]
+ simp [List.getLast?_cons]
+ | some r =>
+ rw [List.cons_append, PaddedCheck, PaddedCheck, ih]
+ simp [List.getLast?_cons, and_assoc]
+
+/-- In a sorted array a padding record cannot interrupt an address history. -/
+theorem paddedCheck_iff_filter {sorted : List (Option (Record Word))}
+ (hs : sorted.Pairwise fun x y => paddedKey x ≤ paddedKey y) (previous : Option (Record Word)) :
+ PaddedCheck previous sorted ↔ PredecessorCheck previous (sorted.filterMap id) := by
+ induction sorted generalizing previous with
+ | nil => simp [PaddedCheck, PredecessorCheck]
+ | cons r rs ih =>
+ obtain ⟨hh, ht⟩ := List.pairwise_cons.mp hs
+ cases r with
+ | none =>
+ have hempty : rs.filterMap id = [] := by
+ apply List.eq_nil_iff_forall_not_mem.mpr
+ intro x hx
+ obtain ⟨r, hr, he⟩ := List.mem_filterMap.mp hx
+ change r = some x at he
+ subst r
+ simpa [paddedKey] using hh _ hr
+ rw [PaddedCheck, ih ht none, List.filterMap_cons_none (by rfl), hempty]
+ rfl
+ | some r => simp [PaddedCheck, PredecessorCheck, ih ht]
+
+/-- Physical site checks, with actual empty slots, recover precisely the
+valid RAM reads starting from the headers. -/
+theorem paddedCheck_iff_readsCorrect {S : ℕ} {header : ℕ → Word}
+ {probes : List (Record Word)} {raw sorted : List (Option (Record Word))}
+ (hrecords : (initialRecords S header ++ probes).Perm (raw.filterMap id))
+ (hperm : raw.Perm sorted) (hsorted : sorted.Pairwise fun x y => paddedKey x ≤ paddedKey y)
+ (ht : Chronological probes) (hprobe : ∀ r ∈ probes, r.kind ≠ .init) :
+ PaddedCheck none sorted ↔ ReadsCorrect (initialMemory S header) probes :=
+ (paddedCheck_iff_filter hsorted none).trans
+ (padded_predecessorCheck_iff hrecords hperm hsorted ht hprobe)
+
+end RAMMemory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMMemoryMessages.lean b/lean/OAI/Computability/VPVNP/RAMMemoryMessages.lean
new file mode 100644
index 0000000000..92d8db82ad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMMemoryMessages.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.RAMBoundary
+import OAI.Computability.VPVNP.RAMRecordIndex
+import OAI.Computability.VPVNP.RAMSortedRecords
+import OAI.Computability.VPVNP.RAMSortFieldEquiv
+
+/-!
+# The memory checks in a single site's transcript
+
+Starting with its own padded records, a site verifies its outgoing messages,
+replays the sorting layers using the prescribed partners, and checks reads
+against preceding slots. Together these independent checks enforce the true
+memory semantics and uniquely determine all sorting and last-record fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMMemory RAMSort
+
+/-- Blocks of ordered record slots sent by each site at each cross-site sorting layer. -/
+abbrev SortSends (h d w : ℕ) :=
+ RAMLayout.Layer d → Fin (2 ^ d) → Wires h (OrderedSlot (Word w))
+
+/-- All outgoing sorting blocks and the last sorted records passed along successor links for
+the memory check. -/
+@[ext] structure MemoryMessages (h d w : ℕ) where
+ /-- Claimed outgoing record block for every site at every cross-site sorting layer. -/
+ sortSends : SortSends h d w
+ /-- Claimed last record sent to each succeeding site for checking the boundary of its sorted
+ block. -/
+ lastRecords : RAMBoundary.Sends (2 ^ d) (Word w)
+
+variable {h d w : ℕ}
+
+private abbrev schedule (h d : ℕ) := phases (h + d) (h + d) le_rfl
+
+/-- The final local block is computed from the local records and the incident
+sort sends, with the receive for each cross-layer taken from its XOR partner. -/
+def outputAt (m : MemoryMessages h d w) (v : Fin (2^d)) (input : Wires h (OrderedSlot (Word w))) :
+ Wires h (Option (Record (Word w))) :=
+ fun i => (replay v (schedule h d) (physicalFieldsEquiv.{0,0} h d _ m.sortSends) input i).record
+
+/-- The site passes its sorting-layer message checks and verifies its output reads using the
+predecessor record at its block boundary. -/
+def MemoryAt (m : MemoryMessages h d w) (v : Fin (2^d)) (input : Wires h (OrderedSlot (Word w))) :
+ Prop :=
+ checks v (schedule h d) (physicalFieldsEquiv.{0,0} h d _ m.sortSends) input ∧
+ RAMBoundary.checkAt (Nat.two_pow_pos h) m.lastRecords v (outputAt m v input)
+
+/-- The site's block after running the full sorting network, with each ordered slot projected
+to its optional memory record. -/
+def sortedBlock (h d : ℕ) (x : ℕ → OrderedSlot (Word w)) (v : Fin (2^d)) :
+ Wires h (Option (Record (Word w))) :=
+ fun i => (block h v.val (runPhases (h + d) x) i).record
+
+/-- The genuine sorting messages and predecessor records, computed in their
+order of use. -/
+def actualMemoryMessages (h d : ℕ) (x : ℕ → OrderedSlot (Word w)) : MemoryMessages h d w where
+ sortSends := (physicalFieldsEquiv.{0,0} h d _).symm (actual (schedule h d) x)
+ lastRecords := RAMBoundary.actual (Nat.two_pow_pos h) (sortedBlock h d x)
+
+/-- Local checks force both families of messages. The only remaining test is
+the immediate-predecessor rule in the sorted array. -/
+theorem memoryAt_iff (m : MemoryMessages h d w) (x : ℕ → OrderedSlot (Word w)) :
+ (∀ v, MemoryAt m v (block h v.val x)) ↔
+ m = actualMemoryMessages h d x ∧
+ PaddedCheck none (RAMBoundary.flat (sortedBlock h d x)) := by
+ constructor
+ · intro hm
+ have hc := fun v => (hm v).1
+ have hout (v) : outputAt m v (block h v.val x) = sortedBlock h d x v := by
+ funext i
+ exact congrArg (fun f : Wires h (OrderedSlot (Word w)) => (f i).record)
+ (replay_phases _ x hc v)
+ have hb := (RAMBoundary.checks_iff (Nat.two_pow_pos h) (sortedBlock h d x) m.lastRecords).mp
+ (fun v => by change RAMBoundary.checkAt _ _ _ _; rw [← hout v]; exact (hm v).2)
+ refine ⟨MemoryMessages.ext ?_ hb.2, hb.1⟩
+ apply (physicalFieldsEquiv.{0,0} h d _).injective
+ change _ = (physicalFieldsEquiv.{0,0} h d _) ((physicalFieldsEquiv.{0,0} h d _).symm _)
+ rw [Equiv.apply_symm_apply]
+ exact fields_eq_actual _ _ x hc
+ · rintro ⟨rfl, hb⟩
+ let msg := actualMemoryMessages h d x
+ have hc (v) : checks v (schedule h d) (physicalFieldsEquiv.{0,0} h d _ msg.sortSends)
+ (block h v.val x) := by
+ change checks v _ ((physicalFieldsEquiv.{0,0} h d _) ((physicalFieldsEquiv.{0,0} h d _).symm _)) _
+ rw [Equiv.apply_symm_apply]
+ exact checks_actual ..
+ intro v
+ refine ⟨hc v, ?_⟩
+ have hout : outputAt msg v (block h v.val x) = sortedBlock h d x v := by
+ funext i
+ exact congrArg (fun f : Wires h (OrderedSlot (Word w)) => (f i).record)
+ (replay_phases _ x hc v)
+ change RAMBoundary.checkAt _ _ _ (outputAt msg v _)
+ rw [hout]
+ exact (RAMBoundary.checks_iff _ _ _).mpr ⟨hb, rfl⟩ v
+
+/-- The memory transcript for the actual RAM record blocks. -/
+theorem report_memoryAt_iff (header : ℕ → Word w) {d e : ℕ} {rs : List (Report w)}
+ (hcap : RAMBuckets.cost Report.probes rs ≤ 2^d * 2^e)
+ (hc : ∀ r ∈ rs, 1 + r.probes ≤ 2^e) (m : MemoryMessages (2+e) d w) :
+ (∀ v, MemoryAt m v (block (2+e) v.val (recordWires header d e rs))) ↔
+ m = actualMemoryMessages (2+e) d (recordWires header d e rs) ∧
+ Correct (initialMemory (2^d) header) (rs.map Report.events).flatten := by
+ rw [memoryAt_iff, ← sortedRecords_read_check header hcap hc]
+ have hflat : RAMBoundary.flat (sortedBlock (2+e) d (recordWires header d e rs)) =
+ sortedRecords header d e rs := by
+ let x := runPhases ((2+e)+d) (recordWires header d e rs)
+ have he := flatten_ofFn_blocks (2+e) d (fun i => (x i).record)
+ unfold sortedRecords
+ rw [List.map_ofFn]
+ exact he
+ rw [hflat]
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMMessageBounds.lean b/lean/OAI/Computability/VPVNP/RAMMessageBounds.lean
new file mode 100644
index 0000000000..1b6e633ffd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMMessageBounds.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.RAMMemoryMessages
+import OAI.Computability.VPVNP.RAMWordBounds
+
+/-!
+# Word bounds throughout the distributed RAM sort
+
+Every comparator copies one of its two input records. Thus a pointwise
+predicate of the input is preserved both by the pre-comparison blocks sent
+between sites and by the last records sent on successor links. Applying this
+to the canonical record wires proves representability of all these messages.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+variable {α : Type*} [LinearOrder α] {h d : ℕ} {P : α → Prop}
+
+private theorem comparatorLayer_preserves (j : ℕ) (direction : ℕ → Bool)
+ {x : ℕ → α} (hx : ∀ i, P (x i)) (i : ℕ) : P (comparatorLayer j direction x i) := by
+ simp only [comparatorLayer, lower, upper, min_def, max_def]
+ split <;> split <;> split <;> exact hx _
+
+private theorem runStrides_preserves (k : ℕ) (direction : ℕ → Bool)
+ {x : ℕ → α} (hx : ∀ i, P (x i)) : ∀ i, P (runStrides k direction x i) := by
+ induction k generalizing x with
+ | zero => exact hx
+ | succ k ih => exact ih (comparatorLayer_preserves _ _ hx)
+
+theorem runPhases_preserves (a : ℕ) {x : ℕ → α} (hx : ∀ i, P (x i)) :
+ ∀ i, P (runPhases a x i) := by
+ induction a with
+ | zero => exact hx
+ | succ a ih => exact runStrides_preserves _ _ ih
+
+private theorem actual_stage_preserves (ss : List (Stage (h + d))) (hn : ss.Nodup)
+ {x : ℕ → α} (hx : ∀ i, P (x i)) (f : ∀ s ∈ ss, Sends h d s α)
+ (hf : fieldsOfStages ss hn f = actual ss x) :
+ ∀ s hs hc v i, P (f s hs hc v i) := by
+ induction ss generalizing x with
+ | nil => intro s hs; exact False.elim (List.not_mem_nil hs)
+ | cons s ss ih =>
+ have hhead : f s (List.mem_cons_self ..) = fun _ v ↦ block h v.val x :=
+ congrArg Prod.fst hf
+ let tail := fun (t : Stage (h + d)) (ht : t ∈ ss) ↦ f t (List.mem_cons_of_mem s ht)
+ have htail : fieldsOfStages ss (List.nodup_cons.mp hn).2 tail =
+ actual ss (comparatorLayer s.stride (phaseDirection s.phase) x) := congrArg Prod.snd hf
+ intro t ht hc v i
+ rcases List.mem_cons.mp ht with rfl | hm
+ · rw [hhead]
+ exact hx _
+ · exact ih _ (comparatorLayer_preserves _ _ hx) tail htail t hm hc v i
+
+/-- Every physical sort send is a pre-comparison block whose records retain
+any pointwise property shared by all input records. -/
+theorem actual_sortSends_preserves (h d : ℕ) {x : ℕ → α} (hx : ∀ i, P (x i))
+ (l : RAMLayout.Layer d) (v : Fin (2 ^ d)) (i : Fin (2 ^ h)) :
+ P ((physicalFieldsEquiv h d α).symm (actual (phases (h+d) (h+d) le_rfl) x) l v i) := by
+ let ss := phases (h+d) (h+d) le_rfl
+ let sent := (physicalFieldsEquiv h d α).symm (actual ss x)
+ let f := fun (s : Stage (h+d)) (_ : s ∈ ss) (hc : h ≤ s.stride) ↦
+ sent ((crossStageEquiv h d).symm ⟨s, hc⟩)
+ have hf : fieldsOfStages ss (phases_nodup le_rfl) f = actual ss x :=
+ (physicalFieldsEquiv h d α).apply_symm_apply _
+ let t := crossStageEquiv h d l
+ have ht := actual_stage_preserves ss _ hx f hf t.val (mem_fullPhases _) t.property v i
+ change P (sent ((crossStageEquiv h d).symm t) v i) at ht
+ simpa only [t, Equiv.symm_apply_apply] using ht
+
+end RAMSort
+
+namespace BurstRAM
+
+open RAMMemory RAMSort
+
+variable {w h d e : ℕ}
+
+/-- Every present record in a sorting message or last-record message has address and timestamp
+fields representable at the word width. -/
+def MemoryMessages.FitsWord (m : MemoryMessages h d w) : Prop :=
+ (∀ l v i t, t ∈ (m.sortSends l v i).record → RecordFitsWord t) ∧
+ (∀ j t, t ∈ m.lastRecords j → RecordFitsWord t)
+
+theorem recordWires_fitsWord (header : ℕ → Word w) {rs : List (Report w)}
+ (hcap : RAMBuckets.cost Report.probes rs ≤ 2^d * 2^e) (hword : 2^d * 2^e < 2^w) :
+ ∀ i t, t ∈ (recordWires header d e rs i).record → RecordFitsWord t := by
+ let slots := (canonicalRecordBlocks header (2^d) (2^e) rs).flatten
+ intro i t ht
+ change (slots[i]?).getD none = some t at ht
+ by_cases hi : i < slots.length
+ · rw [List.getElem?_eq_getElem hi, Option.getD_some] at ht
+ exact canonicalRecordBlocks_fitsWord header (Nat.two_pow_pos e) hcap hword
+ (ht ▸ List.getElem_mem hi)
+ · simp [List.getElem?_eq_none (Nat.le_of_not_gt hi)] at ht
+
+/-- For an execution within the cost cap, every occupied record sent by a
+sort stage or a predecessor fits in the three address and timestamp words. -/
+theorem actualMemoryMessages_fitsWord (header : ℕ → Word w) {rs : List (Report w)}
+ (hcap : RAMBuckets.cost Report.probes rs ≤ 2^d * 2^e) (hword : 2^d * 2^e < 2^w) :
+ (actualMemoryMessages (2+e) d (recordWires header d e rs)).FitsWord := by
+ let x := recordWires header d e rs
+ let P := fun a : OrderedSlot (Word w) ↦ ∀ t ∈ a.record, RecordFitsWord t
+ have hx : ∀ i, P (x i) := recordWires_fitsWord header hcap hword
+ constructor
+ · intro l v i
+ exact actual_sortSends_preserves _ _ hx l v i
+ · intro j
+ exact runPhases_preserves _ hx _
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMParameters.lean b/lean/OAI/Computability/VPVNP/RAMParameters.lean
new file mode 100644
index 0000000000..5d7e99242c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMParameters.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.CompressionParameters
+import OAI.Computability.VPVNP.RAMSiteBounds
+
+/-!
+# Integer computations of the transcript parameters
+
+The prescribed rational multiples of the binary logarithm can be rounded
+using only integer powers and integer logarithms. In particular a processor
+need not compute any real-valued function to determine its field widths.
+The virtual site count is the least power of two satisfying the budget
+inequality of Section 11.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+/-- Ceiling of a nonnegative rational multiple of `log₂ n` computed over
+integers. For fixed numerator and positive denominator the powers have
+`O(log n)` bits. -/
+def roundedUp (p q n : ℕ) : ℕ := Nat.clog (2^q) (n^p)
+
+/-- Floor used for the number of compression blocks. -/
+def roundedDown (p q n : ℕ) : ℕ := Nat.log (2^q) (n^p)
+
+private theorem scaled_log (p q n : ℕ) :
+ Real.logb ((2^q : ℕ) : ℝ) ((n^p : ℕ) : ℝ) = ((p:ℝ)/q) * Real.logb 2 n := by
+ push_cast
+ simp only [Real.logb, Real.log_pow, div_eq_mul_inv, mul_inv_rev]
+ ring
+
+theorem roundedUp_eq (p q n : ℕ) :
+ roundedUp p q n = Compression.bucketExponent ((p:ℝ)/q) n := by
+ rw [roundedUp, Compression.bucketExponent, ← Real.natCeil_logb_natCast, scaled_log]
+
+theorem roundedDown_eq (p q n : ℕ) :
+ roundedDown p q n = Compression.blockCount ((p:ℝ)/q) n := by
+ rw [roundedDown, Compression.blockCount, ← Real.natFloor_logb_natCast, scaled_log]
+
+/-- The rounding of the live address width from §9.1. -/
+def addressWidth (B n : ℕ) : ℕ := B * Nat.clog 2 n
+
+theorem clog_le_log2_succ (n : ℕ) : Nat.clog 2 n ≤ n.log2 + 1 := by
+ rw [Nat.clog_le_iff_le_pow (by decide : 1 < 2)]
+ cases n with
+ | zero => simp
+ | succ n => exact ((Nat.log2_lt (by omega)).mp (Nat.lt_succ_self _)).le
+
+theorem log2_le_addressWidth {B : ℕ} (hB : 1 ≤ B) (n : ℕ) : n.log2 ≤ addressWidth B n := by
+ rw [Nat.log2_eq_log_two]
+ exact (Nat.log_le_clog 2 n).trans (Nat.le_mul_of_pos_left _ hB)
+
+/-- Binary site count for the virtual group in §11. -/
+def virtualSiteExponent (r n : ℕ) : ℕ :=
+ Nat.clog 2 (2^r * n * Nat.clog 2 n) - roundedUp 1 4 n
+
+/-- The chosen number of virtual sites is exactly the least permitted power of
+two, including cases in which a single bucket covers the entire budget. -/
+theorem virtualSiteExponent_le_iff (r n d : ℕ) :
+ virtualSiteExponent r n ≤ d ↔ 2^r * n * Nat.clog 2 n ≤ 2^d * 2^(roundedUp 1 4 n) := by
+ rw [virtualSiteExponent, Nat.sub_le_iff_le_add, Nat.clog_le_iff_le_pow (by decide : 1 < 2), pow_add]
+
+/-- For the actual live choices of Section 9, the whole literal and shared
+input is available to the coefficient program at every sufficiently large
+length. -/
+theorem eventually_liveInputFits (program : UniversalMachine.Program) (B : ℕ)
+ {δ : ℝ} (hδ : 0 < δ) (hδ' : δ ≤ 1) :
+ ∀ᶠ n : ℕ in Filter.atTop,
+ ProcessorInput.Fits program n (addressWidth B n) (Compression.liveBucket δ n)
+ ((addressWidth B n + 10)^4) := by
+ filter_upwards [eventually_processorInputFits program B hδ, Filter.eventually_ge_atTop 1] with n h hn
+ apply h (addressWidth B n) (Compression.bucketExponent (1-δ) n)
+ · exact Nat.mul_le_mul_left _ (clog_le_log2_succ _)
+ · simpa [Compression.liveBucket] using (Compression.liveBucket_bounds hδ' hn).2
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMPathCount.lean b/lean/OAI/Computability/VPVNP/RAMPathCount.lean
new file mode 100644
index 0000000000..9a7686896e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMPathCount.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.RAMBitTranscript
+import OAI.Computability.VPVNP.RAMFinite
+
+/-!
+# Counting RAM paths as a contraction of local validators
+
+For every shared-bit assignment, the factor at a site is the number of its
+successful local branch histories. All these sets are finite, even for
+malformed messages. Summing their product gives the genuine capped RAM
+path count in Lemma 10.1.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMLayout RAMMemory
+
+variable {d e w : ℕ} {C : Type*}
+
+/-- Lists of call reports accepted by a single site's validator for the given shared-bit
+assignment. -/
+abbrev SitePaths (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (bits : RawAssignment d e w) (v : Fin (2^d)) :=
+ {rs : List (Report w) // BitValidator P fuel initial header hw hc bits v rs}
+
+instance (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (bits : RawAssignment d e w) (v : Fin (2^d)) :
+ Finite (SitePaths P fuel initial header hw hc bits v) := by
+ let pack (r : SitePaths P fuel initial header hw hc bits v) : BoundedReports w fuel (2 * 2^e) :=
+ ⟨r.val, boundedReports_of_localSegment r.property.2.1.1.calls
+ (r.property.2.1.1.cost_lt (Nat.two_pow_pos e)).le⟩
+ exact Finite.of_injective pack fun _ _ h => Subtype.ext (congrArg (fun t : BoundedReports w fuel (2 * 2^e) => t.val) h)
+
+instance (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w) (d e : ℕ) :
+ Finite (ActualPaths P fuel initial (initialMemory (2^d) header) (withinCaps (2^d) (2^e))) :=
+ finite_actualPaths (maxCalls := 2^d * 2^e) (fun _ h => h.1)
+
+/-- Lemma 10.1. The sites use the exact bit layout of (10.1), with the
+first and last successor fields clamped. -/
+theorem parsimoniousRAMTranscripts (P : Program w C) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) :
+ Nat.card (ActualPaths P fuel initial (initialMemory (2^d) header) (withinCaps (2^d) (2^e))) =
+ ∑ bits : RawAssignment d e w, ∏ v : Fin (2^d),
+ Nat.card (SitePaths P fuel initial header hw hc bits v) := by
+ rw [Nat.card_congr (bitTranscriptEquiv P fuel initial header hw hc),
+ Nat.card_congr (siteWitnessEquiv (BitValidator P fuel initial header hw hc)), Nat.card_sigma]
+ simp only [Nat.card_pi]
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMPrivateLog.lean b/lean/OAI/Computability/VPVNP/RAMPrivateLog.lean
new file mode 100644
index 0000000000..19b9aefd20
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMPrivateLog.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.RAMProgram
+
+/-!
+# Linear-scan private memory
+
+A fresh call has an empty list of writes. Storing a word conses an address and
+value, while loading scans from the head and defaults to zero. A write to a
+previously used address therefore supersedes its older entries. Each scan
+compares full words without ever iterating up to a supplied address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C D : Type*}
+
+/-- Change only the private continuations of an instruction, including both
+binary continuations and every possible read answer. -/
+def CallAction.mapState (f : C → D) : CallAction w C → CallAction w D
+ | .localStep c => .localStep (f c)
+ | .branch g => .branch (fun b => f (g b))
+ | .read a g => .read a (fun v => f (g v))
+ | .write a v c => .write a v (f c)
+ | .finish r => .finish r
+ | .reject => .reject
+
+namespace PrivateRAM
+
+variable {p r k : ℕ}
+
+/-- A newest-first list of private address-value writes. Looking up the first matching address
+recovers its latest word. -/
+abbrev WriteLog (w : ℕ) := List (Word w × Word w)
+
+/-- A scan returns the newest value and a charge for testing the list, reading
+the address, comparing it, and either advancing or copying the value. -/
+def WriteLog.scan : WriteLog w → Word w → Word w × ℕ
+ | [], _ => (0, 1)
+ | (key, v) :: rest, a =>
+ if a = key then (v, 4)
+ else let t := scan rest a; (t.1, 4 + t.2)
+
+theorem WriteLog.scan_work_le (log : WriteLog w) (a : Word w) :
+ (WriteLog.scan log a).2 ≤ 4 * (log.length + 1) := by
+ induction log with
+ | nil => simp [WriteLog.scan]
+ | cons e log ih =>
+ obtain ⟨key, v⟩ := e
+ by_cases h : a = key <;> simp [WriteLog.scan, h] <;> omega
+
+/-- The total memory function represented by the log. -/
+def WriteLog.memory (log : WriteLog w) (a : Word w) : Word w := (WriteLog.scan log a).1
+
+@[simp] theorem WriteLog.memory_nil : WriteLog.memory ([] : WriteLog w) = fun _ => 0 := rfl
+
+theorem WriteLog.memory_cons (log : WriteLog w) (key v : Word w) :
+ WriteLog.memory ((key, v) :: log) = Function.update (WriteLog.memory log) key v := by
+ funext a
+ by_cases h : a = key <;> simp [WriteLog.memory, WriteLog.scan, h, Function.update_of_ne]
+
+/-- Private RAM configuration with its program counter, persistent word, registers and a
+newest-first log of writes. -/
+structure LogConfig (w p r : ℕ) where
+ /-- Instruction address currently selected in the private machine's finite program table. -/
+ pc : Fin p
+ /-- Persistent word carried in the current private call configuration. -/
+ persistent : Word w
+ /-- Current contents of the private word registers. -/
+ reg : Fin r → Word w
+ /-- Newest-first list of private stores since the beginning of the call. -/
+ writes : WriteLog w
+
+/-- Interpret a logged configuration as an ordinary RAM configuration by evaluating its write
+log as a private memory. -/
+def LogConfig.denote (l : LogConfig w p r) : Config w p r :=
+ ⟨l.pc, l.persistent, l.reg, WriteLog.memory l.writes⟩
+
+/-- A store extends the log once. Every other opcode retains the current log. -/
+def Instr.nextLog (i : Instr w p r k) (l : LogConfig w p r) : WriteLog w :=
+ match i with
+ | .storePrivate addr src _ => (l.reg addr, l.reg src) :: l.writes
+ | _ => l.writes
+
+theorem Instr.nextLog_length_le (i : Instr w p r k) (l : LogConfig w p r) :
+ (i.nextLog l).length ≤ l.writes.length + 1 := by cases i <;> simp [Instr.nextLog]
+
+/-- Use the instruction's register and control updates unchanged. In the
+input configuration the private read operation is the linear scan, and in
+every continuing output the writes are kept as a list. -/
+def Instr.runLogged (i : Instr w p r k) (pub : Fin k → Word w) (l : LogConfig w p r) :
+ CallAction w (LogConfig w p r) :=
+ (i.run pub l.denote).mapState fun c => ⟨c.pc, c.persistent, c.reg, i.nextLog l⟩
+
+/-- The logged dispatcher implements all of the direct-memory opcodes. -/
+theorem Instr.runLogged_correct (i : Instr w p r k) (pub : Fin k → Word w) (l : LogConfig w p r) :
+ (i.runLogged pub l).mapState LogConfig.denote = i.run pub l.denote := by
+ cases i <;>
+ simp [Instr.runLogged, Instr.run, CallAction.mapState, Instr.nextLog, LogConfig.denote,
+ Config.put, Config.store, WriteLog.memory_cons]
+
+/-- Resetting the private log is independent of the width of the address
+space. Public data and the persistent state have the native interpretation. -/
+def Machine.logProgram (M : Machine w p r k) : Program w (LogConfig w p r) where
+ start s := ⟨M.entry, s, fun _ => 0, []⟩
+ step l := (M.code l.pc).runLogged M.publicData l
+
+theorem Machine.logProgram_start (M : Machine w p r k) (s : Word w) :
+ (M.logProgram.start s).denote = M.program.start s := rfl
+
+theorem Machine.logProgram_step (M : Machine w p r k) (l : LogConfig w p r) :
+ (M.logProgram.step l).mapState LogConfig.denote = M.program.step l.denote :=
+ (M.code l.pc).runLogged_correct M.publicData l
+
+end PrivateRAM
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMPrivateLogRun.lean b/lean/OAI/Computability/VPVNP/RAMPrivateLogRun.lean
new file mode 100644
index 0000000000..396bdc2f91
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMPrivateLogRun.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.RAMPrivateLog
+import OAI.Computability.VPVNP.RAMLocalRun
+
+/-!
+# Call simulation and log capacity
+
+The list-backed machine produces the direct machine's exact report, unused
+suffix, and all three counters even on rejecting inputs. Along every possible
+prefix, including arbitrary read guesses, the log grows by at most one entry
+per instruction. Hence the same fixed scan allowance applies on every path.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C D : Type*}
+
+/-- Mapping every instruction continuation preserves the whole metered call. -/
+theorem runLocalCall_mapState (P : Program w C) (Q : Program w D) (f : C → D)
+ (hs : ∀ c, (P.step c).mapState f = Q.step (f c)) (fuel : ℕ)
+ (c : C) (allowance : ℕ) (bits : List Bool) :
+ runLocalCall P fuel c allowance bits = runLocalCall Q fuel (f c) allowance bits := by
+ induction fuel generalizing c allowance bits with
+ | zero => rfl
+ | succ n ih =>
+ rw [runLocalCall, runLocalCall, ← hs]
+ cases P.step c with
+ | localStep | finish | reject => simp [CallAction.mapState, ih]
+ | branch next => cases bits <;> simp [CallAction.mapState, ih]
+ | read a next =>
+ cases allowance with
+ | zero => rfl
+ | succ p => cases takeWord w bits <;> simp [CallAction.mapState, ih]
+ | write a v next => cases allowance <;> simp [CallAction.mapState, ih]
+
+/-- All continuations of a dispatched instruction, before enforcing fuel,
+probe caps, or correctness of the supplied read value. -/
+def CallAction.continuesTo (action : CallAction w C) (c : C) : Prop :=
+ match action with
+ | .localStep next | .write _ _ next => c = next
+ | .branch next => ∃ b, c = next b
+ | .read _ next => ∃ v, c = next v
+ | .finish _ | .reject => False
+
+/-- A prefix of `n` continuing instructions, retaining every binary choice
+and possible read answer. Halting and rejection have no continuations. -/
+inductive InstructionPrefix (P : Program w C) (start : C) : ℕ → C → Prop
+ | initial : InstructionPrefix P start 0 start
+ | step {n c next} (tail : InstructionPrefix P start n c) (hc : (P.step c).continuesTo next) :
+ InstructionPrefix P start (n + 1) next
+
+namespace PrivateRAM
+
+variable {p r k : ℕ}
+
+theorem Machine.runLocalCall_logProgram (M : Machine w p r k) (fuel : ℕ)
+ (l : LogConfig w p r) (allowance : ℕ) (bits : List Bool) :
+ runLocalCall M.logProgram fuel l allowance bits =
+ runLocalCall M.program fuel l.denote allowance bits :=
+ runLocalCall_mapState M.logProgram M.program LogConfig.denote M.logProgram_step fuel l allowance bits
+
+theorem Instr.runLogged_writes {i : Instr w p r k} {pub : Fin k → Word w}
+ {l next : LogConfig w p r} (hc : (i.runLogged pub l).continuesTo next) :
+ next.writes = i.nextLog l := by
+ unfold Instr.runLogged at hc
+ cases h : i.run pub l.denote <;> rw [h] at hc
+ case localStep | write => cases hc; rfl
+ case branch | read => obtain ⟨_, rfl⟩ := hc; rfl
+ case finish | reject => exact hc.elim
+
+theorem Machine.prefix_log_length_le (M : Machine w p r k) {start l : LogConfig w p r}
+ {n : ℕ} (h : InstructionPrefix M.logProgram start n l) :
+ l.writes.length ≤ start.writes.length + n := by
+ induction h with
+ | initial => simp
+ | step h hc ih =>
+ rw [Instr.runLogged_writes hc]
+ exact ((M.code _).nextLog_length_le _).trans (by omega)
+
+/-- With `n` dispatches used out of the initial fuel, the reached log and
+the remaining fuel still fit in the reserved capacity. -/
+theorem Machine.prefix_log_capacity (M : Machine w p r k) {start l : LogConfig w p r}
+ {n fuel capacity : ℕ} (h : InstructionPrefix M.logProgram start n l)
+ (hn : n ≤ fuel) (hcap : start.writes.length + fuel ≤ capacity) :
+ l.writes.length + (fuel - n) ≤ capacity := by
+ have := M.prefix_log_length_le h
+ omega
+
+/-- This bound covers each private read, regardless of the supplied address
+and the persistent input. The capacity depends only on the call fuel. -/
+theorem Machine.prefix_scan_work_le (M : Machine w p r k) (s a : Word w)
+ {l : LogConfig w p r} {n fuel : ℕ}
+ (h : InstructionPrefix M.logProgram (M.logProgram.start s) n l) (hn : n ≤ fuel) :
+ (WriteLog.scan l.writes a).2 ≤ 4 * (fuel + 1) := by
+ have hlen := M.prefix_log_length_le h
+ change l.writes.length ≤ 0 + n at hlen
+ exact (WriteLog.scan_work_le _ _).trans (Nat.mul_le_mul_left 4 (by omega))
+
+end PrivateRAM
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorBank.lean b/lean/OAI/Computability/VPVNP/RAMProcessorBank.lean
new file mode 100644
index 0000000000..139dfdb529
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorBank.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.RAMProcessorLocalResult
+import OAI.Computability.VPVNP.RAMProcessorCallCredit
+import OAI.Computability.VPVNP.RAMProcessorSiteTests
+import OAI.Computability.VPVNP.RAMTapeRecordBuffer
+
+/-!
+# Shared stack bank of the physical burst-site controller
+
+The instruction interpreter and credit routines read the same fuel tally.
+The site tests read the same cost and persistent state as the call controller.
+Record fields three and four directly name the saved start cost and current
+probe ordinal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM
+
+/-- Stacks of the physical site controller for instruction execution, credit accounting, tests,
+record emission and temporary work. -/
+inductive Port (r k : ℕ) where
+ | isa (i : ISA.Port r k)
+ | credit (i : CallCredit.Port)
+ | test (i : SiteTests.Port)
+ | record (i : RecordBuffer.Port)
+ | scratch (i : Fin 8)
+ deriving DecidableEq, Fintype
+
+variable {r k p w : ℕ}
+
+/-- Embed the local instruction processor, sharing its fuel stack with the credit bank and its
+choice stream with the site tests. -/
+def localPorts : LocalProcessor.Port r k → Port r k
+ | .inl i => .isa i
+ | .inr false => .credit (.budget .fuel)
+ | .inr true => .test .choices
+
+theorem localPorts_injective : Function.Injective (@localPorts r k) := by
+ intro i j h
+ rcases i with i | b <;> rcases j with j | c
+ · exact congrArg Sum.inl (Port.isa.inj h)
+ · cases c <;> contradiction
+ · cases b <;> contradiction
+ · cases b <;> cases c <;> first | rfl | contradiction
+
+/-- Route the cost and cap tests to the credit bank and the state test to the persistent ISA
+word, with the other tests on their dedicated ports. -/
+def testPorts : SiteTests.Port → Port r k
+ | .word .cost => .credit (.budget .cost)
+ | .word .cap => .credit .globalCap
+ | .word .state => .isa .persistent
+ | i => .test i
+
+theorem testPorts_injective : Function.Injective (@testPorts r k) := by
+ let back : Port r k → SiteTests.Port
+ | .credit (.budget .cost) => .word .cost
+ | .credit .globalCap => .word .cap
+ | .isa .persistent => .word .state
+ | .test i => i
+ | _ => .choices
+ apply Function.LeftInverse.injective (g := back)
+ intro i
+ cases i with
+ | word f => cases f <;> rfl
+ | _ => rfl
+
+/-- Route the record's starting cost and probe ordinal to their live credit stacks and its
+other fields to the record buffer. -/
+def recordPorts : RecordBuffer.Port → Port r k
+ | .field i => if i = 3 then .credit .savedStart else if i = 4 then .credit .ordinal else .record (.field i)
+ | i => .record i
+
+theorem recordPorts_injective : Function.Injective (@recordPorts r k) := by
+ let back : Port r k → RecordBuffer.Port
+ | .credit .savedStart => .field 3
+ | .credit .ordinal => .field 4
+ | .record i => i
+ | _ => .temp
+ apply Function.LeftInverse.injective (g := back)
+ intro i
+ cases i with
+ | field j => by_cases hj : j = 3 <;> by_cases hk : j = 4 <;> simp_all [recordPorts, back]
+ | _ => rfl
+
+private def localExit (T : Template p r k) : LocalProcessor.State T → Option (ISA.Callback p r)
+ | .exit cb => some cb
+ | _ => none
+
+/-- One call segment performs the actual instruction fetches and stops on its
+external-action label, with private choice bits and fuel updated in the bank. -/
+def localBlock (T : Template p r k) (pc : Fin p) : Fragment (Port r k) (ISA.Callback p r) :=
+ (Fragment.fromCode (LocalProcessor.code T) (.begin pc) (localExit T)).onPorts localPorts
+
+theorem localBlock_run (T : Template p r k) (pub : Fin k → Word w) (f : ℕ)
+ (c : LogConfig w p r) (bs : List Bool) (limit : ℕ) (hl : c.writes.length+f ≤ limit)
+ (s : Stacks (Port r k)) (hs : ∀ j, s (localPorts j) = LocalProcessor.store pub c f bs j) :
+ let out := LocalProcessor.scan T pub f c bs
+ ∃ t ≤ f*(ISA.prepareBound w limit+4)+1,
+ (localBlock T c.pc).Runs t s out.exit
+ (installStacks localPorts s (LocalProcessor.store pub out.cfg out.fuel out.bits)) := by
+ obtain ⟨t, ht, run⟩ := LocalProcessor.scan_run T pub f c bs limit hl
+ have core := Fragment.fromCode_runs (localExit T) rfl rfl
+ (fun q h => by cases q <;> first | rfl | contradiction) run
+ have h := Fragment.runs_onPorts localPorts localPorts_injective s core
+ rw [installStacks_eq localPorts_injective s _ hs] at h
+ exact ⟨t, ht, h⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorCallCredit.lean b/lean/OAI/Computability/VPVNP/RAMProcessorCallCredit.lean
new file mode 100644
index 0000000000..91b15ff10e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorCallCredit.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.RAMProcessorCreditReset
+import OAI.Computability.VPVNP.RAMProcessorProbeCredit
+import OAI.Computability.VPVNP.RAMProcessorGlobalCredit
+
+/-!
+# Starting a metered call
+
+Before any instruction dispatch, restore the two unary credits from their
+public tallies, save the current cost as the call start, reset the probe
+ordinal to zero, and take the mandatory startup charge. A call can therefore
+start with one remaining unit and complete without a probe.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.CallCredit
+
+open BurstRAM
+
+variable {w : ℕ}
+
+/-- Startup first prepares the per-call state, then charges its unit. -/
+def startCall : FiniteRoutine Port := resetCredits.followedBy prepareProbe
+
+/-- Stack-step count for restoring call and instruction credits, saving the start cost and
+resetting the probe ordinal, accounting for the lengths of their previous contents. -/
+def resetTicks (w H fuelCap fuel call : ℕ) (saved ord : List Bool) : ℕ :=
+ call + fuel + saved.length + ord.length + 7*(H + fuelCap + 2*w) + 12
+
+theorem startCall_run (H fuelCap fuel call site : ℕ) (cap g c : Word w) (saved ord : List Bool)
+ (hH : 0 < H) (hs : 0 < site) (hg : 0 < g.val) (hc : c.val + 1 < 2 ^ w) :
+ startCall.Runs (resetTicks w H fuelCap fuel call saved ord + (8*w+6))
+ (bank H fuelCap fuel call site cap g c saved ord)
+ (bank H fuelCap fuelCap (H-1) (site-1) cap (Charges.prevWord g) ⟨c.val+1,hc⟩
+ (wordBits c) (wordBits (0 : Word w))) := by
+ cases H with
+ | zero => contradiction
+ | succ a =>
+ cases site with
+ | zero => contradiction
+ | succ s =>
+ exact (resetCredits_run (a+1) fuelCap fuel call (s+1) cap g c saved ord).followedBy
+ (prepareProbe_run (a+1) fuelCap fuelCap a s cap g c (wordBits c) (wordBits (0 : Word w)) hg hc)
+
+/-- In a sequenced routine a rejecting state of the second stage remains a
+rejecting state, with no transition past the failure. -/
+private theorem followRight {K : Type} [DecidableEq K] {a b : FiniteRoutine K}
+ {n : ℕ} {s t : Stacks K} {exit : b.State}
+ (h : StackRuns b.body.standalone n (some b.body.entry) s (some exit) t) :
+ StackRuns (a.followedBy b).body.standalone n (some (.inr b.body.entry)) s
+ (some (.inr exit)) t := by
+ let labels (q : Option b.State) : Option (a.State ⊕ b.State) := q.elim none (some ∘ Sum.inr)
+ have hc (q : Option b.State) (hn : (b.body.standalone q).returns = false) :
+ (a.followedBy b).body.standalone (labels q) = (b.body.standalone q).rename id labels := by
+ cases q with
+ | none => contradiction
+ | some x => rfl
+ have h' := h.lift id Function.injective_id labels s hc
+ have he (u : Stacks K) : installStacks id s u = u := by
+ funext i; exact installStacks_at Function.injective_id s u i
+ rw [he, he] at h'
+ exact h'
+
+theorem startCall_reject (H fuelCap fuel call site : ℕ) (cap g c : Word w) (saved ord : List Bool)
+ (bad : H = 0 ∨ site = 0 ∨ g.val = 0 ∨ 2 ^ w ≤ c.val + 1) :
+ ∃ out, StackRuns startCall.body.standalone
+ (resetTicks w H fuelCap fuel call saved ord + Charges.failureTicks H site g)
+ (some startCall.body.entry) (bank H fuelCap fuel call site cap g c saved ord)
+ (some (.inr .reject)) out := by
+ have hreset := resetCredits_run H fuelCap fuel call site cap g c saved ord
+ have hr := hreset.link startCall.body Sum.inl (some (.inr prepareProbe.body.entry)) (fun _ => rfl)
+ obtain ⟨_, hbad⟩ := prepareProbe_reject H fuelCap fuelCap H site cap g c
+ (wordBits c) (wordBits (0 : Word w)) bad
+ exact ⟨_, hr.trans (followRight (a := resetCredits) (b := prepareProbe) hbad)⟩
+
+@[simp] theorem startCall_halt : startCall.body.standalone (some (.inr .reject)) = .halt false := rfl
+
+/-- Initialize the binary allowance from the supplied cap and incoming cost
+before starting the site's first live call. -/
+def firstCall : FiniteRoutine Port := GlobalCredit.routine.followedBy startCall
+
+theorem firstCall_run (H fuelCap fuel call site : ℕ) (cap old c : Word w) (saved ord : List Bool)
+ (hH : 0 < H) (hs : 0 < site) (hlt : c.val < cap.val) :
+ let hc : c.val + 1 < 2 ^ w := (Nat.succ_le_of_lt hlt).trans_lt cap.isLt
+ firstCall.Runs ((16*w+7) + (resetTicks w H fuelCap fuel call saved ord + (8*w+6)))
+ (bank H fuelCap fuel call site cap old c saved ord)
+ (bank H fuelCap fuelCap (H-1) (site-1) cap (Charges.prevWord (cap-c)) ⟨c.val+1,hc⟩
+ (wordBits c) (wordBits (0 : Word w))) := by
+ have hinit := GlobalCredit.bank_run H fuelCap fuel call site cap old c saved ord hlt.le
+ have hg : 0 < (cap-c).val := by rw [GlobalCredit.remaining_val cap c hlt.le]; omega
+ exact hinit.followedBy
+ (startCall_run H fuelCap fuel call site cap (cap-c) c saved ord hH hs hg
+ ((Nat.succ_le_of_lt hlt).trans_lt cap.isLt))
+
+/-- After a permitted charge, the two binary counters continue to sum to
+the cap, and the incremented cost fits the same word. -/
+theorem remaining_after_charge {cap g c : Word w} (hg : 0 < g.val)
+ (hcap : g.val + c.val = cap.val) :
+ (Charges.prevWord g).val + (c.val + 1) = cap.val ∧ c.val + 1 < 2 ^ w := by
+ have := cap.isLt
+ change g.val - 1 + (c.val + 1) = cap.val ∧ _
+ omega
+
+/-- A probe ordinal counts only the probes since startup. Its next value
+therefore fits even if the probe takes the global cost exactly to the cap. -/
+theorem ordinal_fits {saved o c : Word w} (hstart : saved.val + (1 + o.val) = c.val) :
+ o.val + 1 < 2 ^ w := by have := c.isLt; omega
+
+end RAMTape.CallCredit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorCallInvariant.lean b/lean/OAI/Computability/VPVNP/RAMProcessorCallInvariant.lean
new file mode 100644
index 0000000000..facefb38e5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorCallInvariant.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.RAMProcessorSiteClose
+import OAI.Computability.VPVNP.RAMProcessorGraphStart
+
+/-!
+# Bounds at the physical call boundary
+
+A charge transfers one unit from the remaining global credit to the cumulative
+cost. The private log and unspent fuel together remain bounded by the public
+call clock. Every future probe therefore has room in the record buffer before
+it is staged.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k : ℕ}
+
+/-- Site-controller invariant at a call boundary, tracking the buffered records, public limits,
+remaining credits, private clock and scratch-word lengths. -/
+structure CallReady (hw : 2 ≤ w) (H F : ℕ) (first : Bool) (s : Snapshot w p r k)
+ (ys : List (WordRecord w)) : Prop where
+ publicH : s.publicH = H
+ publicFuel : s.publicFuel = F
+ positive : 0 < H
+ boundary : s.boundary.val ≤ s.cap.val
+ room : ys.length + s.siteLeft ≤ 4*H
+ buffer : RecordBuffer.Holds hw H ys s.records
+ privateClock : s.cfg.writes.length + s.fuel ≤ F
+ callCredit : s.callLeft ≤ H
+ saved : s.savedStart.length ≤ w
+ ordinal : s.ordinal.length ≤ w
+ tag : s.tag.length ≤ w
+ address : s.address.length ≤ w
+ value : s.value.length ≤ w
+ global : first = false → s.globalLeft.val + s.cost.val = s.cap.val
+ firstCredit : first = true → 0 < s.siteLeft
+
+/-- Call-boundary invariant strengthened with the saved start and probe ordinal. The current
+cost is the start plus one startup charge and the ordinal. -/
+structure InCall (hw : 2 ≤ w) (H F : ℕ) (s : Snapshot w p r k) (ys : List (WordRecord w))
+ (start ord : Word w) : Prop extends CallReady hw H F false s ys where
+ savedEq : s.savedStart = BurstRAM.wordBits start
+ ordinalEq : s.ordinal = BurstRAM.wordBits ord
+ timestamp : start.val+(1+ord.val) = s.cost.val
+
+theorem CallReady.toHolds {s : Snapshot w p r k} {hw : 2 ≤ w} {H F : ℕ} {first records}
+ (h : CallReady hw H F first s records) : RecordBuffer.Holds hw s.publicH records s.records :=
+ h.publicH ▸ h.buffer
+
+/-- Stack-step allowance for one segment of private instructions between external actions, as a
+function of the word width and call clock. -/
+def segmentWork (w F : ℕ) : ℕ := (F+1)*(ISA.prepareBound w F+4)+200*(w+1)
+/-- Stack-step allowance for an entire metered call, reserving `F + 1` segments at the
+per-segment bound. -/
+def callWork (w F : ℕ) : ℕ := (F+1)*segmentWork w F
+
+/-- One returned segment preserves the public bank and records, and reports
+the extra probes of the current call with their original startup time and
+the ordinals immediately following those already emitted. -/
+structure CallReturn (s u : Snapshot w p r k) (old new : List (WordRecord w))
+ (start ord : Word w) (rep : Report w) (tail : List Bool) : Prop where
+ pub : u.pub = s.pub
+ H : u.publicH = s.publicH
+ fuel : u.publicFuel = s.publicFuel
+ cap : u.cap = s.cap
+ boundary : u.boundary = s.boundary
+ target : u.tests.target = s.tests.target
+ cost : u.cost.val = s.cost.val + rep.probes
+ state : u.tests.cut.state = rep.result
+ siteLeft : u.siteLeft = s.siteLeft - rep.probes
+ bits : u.choices = tail
+ records : new.map WordRecord.record = old.map WordRecord.record ++ eventRecords start.val ord.val rep.events
+
+/-- The linked site controller rejects when local call execution fails, or returns to its
+iteration test with the corresponding report, residual choices and buffered records. -/
+def SegmentRun (T : Template p r k) (hw : 2 ≤ w) (H F : ℕ) (s : Snapshot w p r k)
+ (ys : List (WordRecord w)) (start ord : Word w) (t : ℕ) : Prop :=
+ match (runLocalCall (T.instantiate w s.pub).logProgram s.fuel s.cfg
+ (min s.callLeft (min s.globalLeft.val s.siteLeft)) s.choices).output with
+ | none => RejectRun (table T) t (atLabel T (.segment s.cfg.pc)) s.bank
+ | some (rep,tail) => ∃ u new, CallReady hw H F false u new ∧ CallReturn s u ys new start ord rep tail ∧
+ StackRuns (table T) t (atLabel T (.segment s.cfg.pc)) s.bank (atLabel T .iteration) u.bank
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorCallRun.lean b/lean/OAI/Computability/VPVNP/RAMProcessorCallRun.lean
new file mode 100644
index 0000000000..1bd6285165
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorCallRun.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.RAMProcessorProbeContinue
+
+/-!
+# Correctness of the physical call loop
+
+Strong induction on unspent private instruction fuel follows every sequence
+of adaptive reads and writes. At each callback the proof uses the actual
+site table, the three remaining allowances, and the single physical record
+emitted for the probe. It covers malformed guesses and every cap rejection.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k H F : ℕ} {hw : 2 ≤ w}
+
+theorem segment_correct (T : Template p r k) (s : Snapshot w p r k) (ys : List (WordRecord w))
+ (start ord : Word w) (hin : InCall hw H F s ys start ord) :
+ ∃ t ≤ (s.fuel+1)*segmentWork w F, SegmentRun T hw H F s ys start ord t := by
+ suffices allFuel : ∀ n (s : Snapshot w p r k) ys start ord, s.fuel = n →
+ InCall hw H F s ys start ord →
+ ∃ t ≤ (n+1)*segmentWork w F, SegmentRun T hw H F s ys start ord t by
+ exact allFuel s.fuel s ys start ord rfl hin
+ intro n
+ induction n using Nat.strong_induction_on with
+ | h n ih =>
+ intro s ys start ord hf hin
+ let y := LocalProcessor.scan T s.pub s.fuel s.cfg s.choices
+ let z := s.afterLocal y
+ have hz : InCall hw H F z ys start ord := hin.afterLocal T
+ obtain ⟨t, ht, run⟩ := segment_run T s F hin.privateClock
+ have hpos (hn : y.exit ≠ .reject) : z.fuel < n := by
+ rw [← hf]; exact LocalProcessor.scan_fuel_lt T s.pub s.fuel s.cfg s.choices hn
+ have probe (a : ProbeStep w p r) (ha : a.callback = y.exit)
+ (haPos : 0 < allowance z) (hbits : a.accepts z) :
+ ∃ d ≤ 200*(w+1)+n*segmentWork w F,
+ Meets T hw H F z ys start ord (.callback y.exit) (pending T z y.exit) d := by
+ have hy : z.fuel < n := hpos (by rw [← ha]; cases a <;> simp [ProbeStep.callback])
+ obtain ⟨d, hd, hp⟩ := a.continue_run T hz haPos hbits (by
+ dsimp only
+ intro hnext
+ let u := a.finish z hw start ord (hz.costRoom haPos) hz.ordRoom
+ exact ih u.fuel (by simpa only [u, a.finish_fuel] using hy) u _ _ _ rfl hnext)
+ rw [ha] at hp
+ exact ⟨d, hd.trans (Nat.add_le_add_left (Nat.mul_le_mul_right _ hy) _), hp⟩
+ have cb : ∃ d ≤ 200*(w+1)+n*segmentWork w F,
+ Meets T hw H F z ys start ord (.callback y.exit) (pending T z y.exit) d := by
+ cases he : y.exit with
+ | next j | choose j l =>
+ have hterminal := (LocalProcessor.scan_bounds T s.pub s.fuel s.cfg s.choices).2.2.1
+ change LocalProcessor.externalOrTerminal y.exit at hterminal
+ rw [he] at hterminal
+ exact False.elim hterminal
+ | reject => exact ⟨1, by omega, pending_reject T z ys start ord⟩
+ | accept => exact ⟨3, by omega, pending_accept T hz⟩
+ | returnState src => exact ⟨8*w+6, by omega, pending_return T hz src⟩
+ | read dst addr pc =>
+ by_cases hc : allowance z = 0
+ · obtain ⟨d, hd, hr⟩ := read_no_credit T z ys start ord dst addr pc hc (hw := hw) (H := H) (F := F)
+ exact ⟨d, by omega, hr⟩
+ · cases hg : takeWord w z.choices with
+ | none =>
+ obtain ⟨d, hd, hr⟩ := read_no_guess T hz dst addr pc (by omega) hg
+ exact ⟨d, by omega, hr⟩
+ | some pair =>
+ obtain ⟨v,tail⟩ := pair
+ have h := probe (.read dst addr pc v tail) he.symm (by omega)
+ ((takeWord_eq_some_iff ..).mp hg)
+ simpa only [he] using h
+ | write addr src pc =>
+ by_cases hc : allowance z = 0
+ · obtain ⟨d, hd, hr⟩ := write_no_credit T z ys start ord addr src pc hc (hw := hw) (H := H) (F := F)
+ exact ⟨d, by omega, hr⟩
+ · have h := probe (.write addr src pc) he.symm (by omega) trivial
+ simpa only [he] using h
+ obtain ⟨d, hd, hr⟩ := cb
+ refine ⟨t+d, ?_, scan_then_pending T s run hr⟩
+ have hbudget := hin.privateClock
+ have hm : s.fuel*(ISA.prepareBound w F+4) ≤ F*(ISA.prepareBound w F+4) :=
+ Nat.mul_le_mul_right _ (by omega)
+ have overhead : segmentWork w F = F*(ISA.prepareBound w F+4) + (ISA.prepareBound w F+4) + 200*(w+1) := by
+ simp only [segmentWork, Nat.add_mul, Nat.one_mul]
+ rw [Nat.succ_mul]
+ omega
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorCallStartup.lean b/lean/OAI/Computability/VPVNP/RAMProcessorCallStartup.lean
new file mode 100644
index 0000000000..8d3884eaa9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorCallStartup.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.RAMProcessorCallInvariant
+import OAI.Computability.VPVNP.RAMProcessorLogged
+
+/-! # State and native semantics of a freshly charged physical call -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k H F : ℕ} {hw : 2 ≤ w}
+
+/-- State just after charging call startup and initializing the fresh private instruction
+configuration, when cumulative cost is below the cap. -/
+def Snapshot.prepared (s : Snapshot w p r k) (T : Template p r k) (hlt : s.cost.val < s.cap.val) :=
+ (s.afterStart (s.cap-s.cost) ((Nat.succ_le_of_lt hlt).trans_lt s.cap.isLt)).afterFresh T
+
+theorem CallReady.cost_lt {s : Snapshot w p r k} {first ys} (h : CallReady hw H F first s ys)
+ (hd : SiteTests.iteration.eval s.tests = .dispatch) : s.cost.val < s.cap.val := by
+ rw [SiteTests.iteration_eval] at hd
+ split_ifs at hd with hcap hr
+ simp only [Bool.and_eq_true, decide_eq_true_eq] at hr
+ exact hr.2.trans_le h.boundary
+
+theorem CallReady.prepared {s : Snapshot w p r k} {first ys} (h : CallReady hw H F first s ys)
+ (T : Template p r k) (hlt : s.cost.val < s.cap.val) (hs : 0 < s.siteLeft) :
+ InCall hw H F (s.prepared T hlt) ys s.cost 0 := by
+ have hg := CallCredit.GlobalCredit.remaining_val s.cap s.cost hlt.le
+ refine ⟨⟨h.publicH,h.publicFuel,h.positive,h.boundary,?_,?_,?_,?_,?_,?_,h.tag,h.address,h.value,?_,nofun⟩,
+ rfl,rfl,?_⟩
+ · change ys.length+(s.siteLeft-1) ≤ 4*H
+ have hr := h.room
+ omega
+ · exact ⟨h.buffer.fit, rfl, rfl, h.buffer.remaining, h.buffer.buffer, h.buffer.output⟩
+ · change 0+s.publicFuel ≤ F
+ simp [h.publicFuel]
+ · change s.publicH-1 ≤ H
+ rw [h.publicH]
+ omega
+ · exact (length_wordBits s.cost).le
+ · exact (length_wordBits (0 : Word w)).le
+ · intro _
+ change (s.cap-s.cost).val-1+(s.cost.val+1) = s.cap.val
+ omega
+ · change s.cost.val+(1+0) = s.cost.val+1
+ omega
+
+/-- Run the template from the current snapshot using its fuel and choices and the least of its
+call, global and site probe allowances. -/
+def Snapshot.localResult (T : Template p r k) (s : Snapshot w p r k) :=
+ (runLocalCall (T.instantiate w s.pub).logProgram s.fuel s.cfg
+ (min s.callLeft (min s.globalLeft.val s.siteLeft)) s.choices).output
+
+theorem nativeCall_prepared (T : Template p r k) (s : Snapshot w p r k) (hH : 0 < s.publicH)
+ (hs : 0 < s.siteLeft) (hlt : s.cost.val < s.cap.val) :
+ nativeCall T s = (s.prepared T hlt).localResult T := by
+ let M := T.instantiate w s.pub
+ change (runChargedCall M.program s.publicFuel (M.program.start s.cfg.persistent) s.publicH (s.cap.val-s.cost.val) s.siteLeft s.choices).output = _
+ rw [← Machine.chargedCall_logged M s.publicFuel s.cfg.persistent s.publicH _ s.siteLeft s.choices]
+ let post := s.prepared T hlt
+ let a := min post.callLeft (min post.globalLeft.val post.siteLeft)
+ have hg := CallCredit.GlobalCredit.remaining_val s.cap s.cost hlt.le
+ have he : min s.publicH (min (s.cap.val-s.cost.val) s.siteLeft) = a+1 := by
+ change min s.publicH (min (s.cap.val-s.cost.val) s.siteLeft) =
+ min (s.publicH-1) (min ((s.cap-s.cost).val-1) (s.siteLeft-1))+1
+ omega
+ unfold runChargedCall
+ rw [he]
+ rfl
+
+theorem CallReturn.startProgress {s u : Snapshot w p r k} {old new : List (WordRecord w)}
+ {rep tail} (T : Template p r k) (hlt : s.cost.val < s.cap.val)
+ (hr : CallReturn (s.prepared T hlt) u old new s.cost 0 rep tail) :
+ Progress s u old new [rep] tail := by
+ refine ⟨hr.pub,hr.H,hr.fuel,hr.cap,hr.boundary,hr.target,?_,?_,hr.bits,?_⟩
+ · apply Cut.ext
+ · have hc : u.cost.val = (s.cost.val+1)+rep.probes := hr.cost
+ change u.cost.val = s.cost.val + RAMBuckets.cost Report.probes [rep]
+ simp [RAMBuckets.cost, hc, Nat.add_assoc]
+ · exact hr.state
+ ·
+ have he : u.siteLeft = s.siteLeft-1-rep.probes := hr.siteLeft
+ rw [he, Nat.sub_sub]
+ simp [RAMBuckets.cost]
+ · simpa only [probeRecords, List.append_nil, Fin.val_zero] using hr.records
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorChargedRun.lean b/lean/OAI/Computability/VPVNP/RAMProcessorChargedRun.lean
new file mode 100644
index 0000000000..dbca8163f6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorChargedRun.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.RAMProcessorCallStartup
+import OAI.Computability.VPVNP.RAMProcessorPhysicalClock
+
+/-!
+# Linking the per-instruction call simulation to the bucket loop
+
+The startup unit is charged before execution. A site with no remaining
+credit rejects at startup. Successful startup resets the registers and log,
+and the segment simulation then follows the real instruction table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k H F : ℕ} {hw : 2 ≤ w}
+
+private theorem startup_graph (T : Template p r k) (first : Bool) (s : Snapshot w p r k)
+ {ys} (h : CallReady hw H F first s ys) (hlt : s.cost.val < s.cap.val) (hs : 0 < s.siteLeft) :
+ ∃ t ≤ (16*w+7+s.startTicks) + (r*(8*w+3)+3*(s.cfg.writes.length*(w+1)+1)+2),
+ StackRuns (table T) t (atLabel T (startLabel first)) s.bank
+ (atLabel T (.segment T.entry)) (s.prepared T hlt).bank := by
+ have hH : 0 < s.publicH := h.publicH ▸ h.positive
+ have hc := (Nat.succ_le_of_lt hlt).trans_lt s.cap.isLt
+ obtain ⟨b, hb, fresh⟩ := fresh_run T (s.afterStart (s.cap-s.cost) hc)
+ change b ≤ r*(8*w+3)+3*(s.cfg.writes.length*(w+1)+1)+2 at hb
+ cases first with
+ | true =>
+ have run := first_run T s hH hs hlt
+ exact ⟨_, by omega, run.trans fresh⟩
+ | false =>
+ have hg := h.global rfl
+ have hgv := CallCredit.GlobalCredit.remaining_val s.cap s.cost hlt.le
+ have he : s.globalLeft = s.cap-s.cost := Fin.ext (by omega)
+ have run := newCall_run T s hH hs (by omega) hc
+ rw [he] at run
+ exact ⟨_, by omega, run.trans fresh⟩
+
+/-- Fold the concrete call induction through both startup labels. -/
+theorem startRuns_of_segments (T : Template p r k)
+ (segments : ∀ (s : Snapshot w p r k) (ys : List (WordRecord w)) (start ord : Word w),
+ InCall hw H F s ys start ord → ∃ t ≤ (s.fuel+1)*segmentWork w F,
+ SegmentRun T hw H F s ys start ord t) :
+ StartRuns T (CallReady hw H F) (perCallEstimate r w H F) := by
+ intro first s ys hadm hd
+ have hlt := hadm.cost_lt hd
+ have bound := hadm.start_and_call_le
+ by_cases hs : s.siteLeft = 0
+ · have hf : first = false := by
+ cases first with
+ | false => rfl
+ | true => have := hadm.firstCredit rfl; omega
+ subst first
+ have run := newCall_reject T s (Or.inr (Or.inl hs))
+ have ht := Charges.failureTicks_le s.publicH s.siteLeft s.globalLeft
+ have he : nativeCall T s = none := by simp [nativeCall, runChargedCall, hs]
+ rw [he]
+ refine ⟨_, ?_, run⟩
+ unfold Snapshot.startTicks at bound
+ omega
+ · have hpos := Nat.pos_of_ne_zero hs
+ let z := s.prepared T hlt
+ obtain ⟨a, ha, run⟩ := startup_graph T first s hadm hlt hpos
+ obtain ⟨b, hb, result⟩ := segments z ys s.cost 0 (hadm.prepared T hlt hpos)
+ have hbf : b ≤ callWork w F := by
+ change b ≤ (s.publicFuel+1)*segmentWork w F at hb
+ exact hadm.publicFuel ▸ hb
+ have he := nativeCall_prepared T s (hadm.publicH ▸ hadm.positive) hpos hlt
+ rw [he]
+ change (match z.localResult T with
+ | none => RejectRun (table T) b (atLabel T (.segment z.cfg.pc)) z.bank
+ | some (rep,tail) => ∃ u new, CallReady hw H F false u new ∧ CallReturn z u ys new s.cost 0 rep tail ∧
+ StackRuns (table T) b (atLabel T (.segment z.cfg.pc)) z.bank (atLabel T .iteration) u.bank) at result
+ cases hr : z.localResult T with
+ | none =>
+ rw [hr] at result
+ exact ⟨_, by omega, run.thenReject result⟩
+ | some pair =>
+ obtain ⟨rep,tail⟩ := pair
+ rw [hr] at result
+ obtain ⟨u,new,hready,hprog,hret⟩ := result
+ exact ⟨_, by omega, u,new,hready,hprog.startProgress T hlt,run.trans hret⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorChoiceCount.lean b/lean/OAI/Computability/VPVNP/RAMProcessorChoiceCount.lean
new file mode 100644
index 0000000000..97c4f64eda
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorChoiceCount.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.RAMProcessorChoices
+import OAI.Computability.VPVNP.RAMGuessBudget
+
+/-!
+# The finite choice generator counts private validator paths
+
+Only strings accepted by the site are counted. Its proven guess bound covers
+every such string, so restricting the physical generator to that length
+preserves the natural cardinal used in the transcript contraction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ProcessorChoices
+
+open BurstRAM RAMLayout
+
+private theorem sum_indicator (pred : List Bool → Bool) (xs : List (List Bool)) :
+ (xs.map fun x => (pred x).toNat).sum = (xs.filter pred).length := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih => cases h : pred x <;> simp [h, ih, Nat.add_comm]
+
+theorem bounded_count (bound : ℕ) (pred : List Bool → Bool)
+ (hb : ∀ bs, pred bs = true → bs.length ≤ bound) :
+ ((words bound).map fun x => (pred x).toNat).sum = Nat.card {bs : List Bool // pred bs = true} := by
+ classical
+ let candidates := (words bound).filter pred
+ let found := candidates.toFinset
+ have hn : candidates.Nodup := (words_nodup bound).filter _
+ have hm (bs : List Bool) : bs ∈ found ↔ pred bs = true := by
+ simp only [found, candidates, List.mem_toFinset, List.mem_filter, mem_words]
+ exact ⟨And.right, fun h => ⟨hb _ h, h⟩⟩
+ let equiv : found ≃ {bs : List Bool // pred bs = true} :=
+ ⟨fun x => ⟨x.val, (hm x.val).mp x.property⟩,
+ fun x => ⟨x.val, (hm x.val).mpr x.property⟩, fun _ => rfl, fun _ => rfl⟩
+ rw [← Nat.card_congr equiv, Nat.card_eq_fintype_card, Fintype.card_coe, sum_indicator]
+ exact (List.toFinset_card_of_nodup hn).symm
+
+theorem site_choices {w p r k d e : ℕ} (M : PrivateRAM.Machine w p r k) (fuel : ℕ)
+ (initial : Word w) (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (shared : RawAssignment d e w) (v : Fin (2^d)) :
+ let accepted := fun bs => (M.validateIncident fuel initial (header v) hw hc v (incidentBits shared v) bs).1.isSome
+ ((words (2*2^e*(fuel+w))).map fun bs => (accepted bs).toNat).sum =
+ Nat.card (M.IncidentPaths fuel initial (header v) hw hc v (incidentBits shared v)) := by
+ apply bounded_count
+ intro bs hb
+ exact M.incident_guesses_le fuel initial header hw hc shared v ⟨bs, hb⟩
+
+end RAMTape.ProcessorChoices
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorChoices.lean b/lean/OAI/Computability/VPVNP/RAMProcessorChoices.lean
new file mode 100644
index 0000000000..ee17197416
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorChoices.lean
@@ -0,0 +1,202 @@
+import OAI.Computability.VPVNP.StructuredStackTotal
+import Mathlib.Tactic.DeriveFintype
+import Mathlib.Data.Fintype.Sum
+
+/-!
+# Generating the bounded private-choice stream
+
+One accepting computation of the site validator consumes exactly one finite
+list of guessed bits. This table generates each list up to the public bound
+once. The budget is a unary stack. After the stop choice the routine drains
+the remaining budget deterministically, with the same instruction count on
+every path. The continuation receives the complete guessed list.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ProcessorChoices
+
+/-- Finite controls for choosing a bounded private stream and draining the remaining budget. -/
+inductive State where
+ | active | stopOrContinue | toss | emit (b : Bool)
+ | stopFirst | stopSecond | inactive | waitOne | waitTwo | waitThree
+ deriving Fintype
+
+variable {K : Type*}
+
+/-- Generate each allowed bit list once and pass it to the continuation. -/
+def routine (budget bits : K) : Routine K State where
+ entry := .active
+ code
+ | .active => .pop budget (fun x => if x.isSome then some .stopOrContinue else none)
+ | .stopOrContinue => .choose (some .stopFirst) (some .toss)
+ | .stopFirst => .goto (some .stopSecond)
+ | .stopSecond => .goto (some .inactive)
+ | .toss => .choose (some (.emit false)) (some (.emit true))
+ | .emit b => .push bits b (some .active)
+ | .inactive => .pop budget (fun x => if x.isSome then some .waitOne else none)
+ | .waitOne => .goto (some .waitTwo)
+ | .waitTwo => .goto (some .waitThree)
+ | .waitThree => .goto (some .inactive)
+
+/-- Lists are grouped by the last chosen bit, which is at the bottom of the
+generated stack. -/
+def words : ℕ → List (List Bool)
+ | 0 => [[]]
+ | n+1 => [] :: ((words n).map (· ++ [false]) ++ (words n).map (· ++ [true]))
+
+theorem mem_words (w : List Bool) (n : ℕ) : w ∈ words n ↔ w.length ≤ n := by
+ induction n generalizing w with
+ | zero => simp [words]
+ | succ n ih =>
+ rw [words, List.mem_cons, List.mem_append, List.mem_map, List.mem_map]
+ constructor
+ · rintro (rfl | ⟨a, ha, rfl⟩ | ⟨a, ha, rfl⟩) <;> simp_all
+ · intro h
+ induction w using List.reverseRecOn with
+ | nil => exact .inl rfl
+ | append_singleton s b _ =>
+ have hs := (ih s).mpr (by simp at h; omega)
+ cases b
+ · exact .inr (.inl ⟨s, hs, rfl⟩)
+ · exact .inr (.inr ⟨s, hs, rfl⟩)
+
+theorem words_nodup (n : ℕ) : (words n).Nodup := by
+ induction n with
+ | zero => simp [words]
+ | succ n ih =>
+ rw [words, List.nodup_cons, List.nodup_append]
+ refine ⟨by simp, ih.map (fun a b h => List.append_cancel_right h),
+ ih.map (fun a b h => List.append_cancel_right h), ?_⟩
+ intro a ha b hb heq
+ subst b
+ obtain ⟨v, _, rfl⟩ := List.mem_map.mp ha
+ obtain ⟨u, _, he⟩ := List.mem_map.mp hb
+ have hh := congrArg List.getLast? he
+ simp at hh
+
+variable [DecidableEq K] (budget bits : K) (hne : budget ≠ bits)
+
+private def store (base : Stacks K) (credits guess : List Bool) :=
+ Function.update (Function.update base budget credits) bits guess
+
+include hne in
+private theorem credits_at (base : Stacks K) (credits guess : List Bool) :
+ store budget bits base credits guess budget = credits := by
+ simp [store, Function.update_of_ne hne]
+
+private theorem guess_at (base : Stacks K) (credits guess : List Bool) :
+ store budget bits base credits guess bits = guess := by simp [store]
+
+include hne in
+private theorem put_credit (base : Stacks K) (old new guess : List Bool) :
+ Function.update (store budget bits base old guess) budget new = store budget bits base new guess := by
+ simp [store, Function.update_comm hne.symm]
+
+private theorem put_guess (base : Stacks K) (credits old new : List Bool) :
+ Function.update (store budget bits base credits old) bits new = store budget bits base credits new := by
+ simp [store]
+
+include hne in
+private theorem inactive_count (base : Stacks K) (credits guess : List Bool)
+ (c : ℕ → Stacks K → ℕ) (t : ℕ) :
+ (routine budget bits).countFrom c (t + 4*credits.length + 1) (some .inactive)
+ (store budget bits base credits guess) = c t (store budget bits base [] guess) := by
+ induction credits with
+ | nil => simp [routine, Routine.countFrom, credits_at budget bits hne, put_credit budget bits hne]
+ | cons b xs ih =>
+ simp only [List.length_cons, Nat.mul_succ]
+ rw [show t + (4*xs.length+4) + 1 = (t+4*xs.length+1)+1+1+1+1 by omega]
+ simpa only [Routine.countFrom, routine, credits_at budget bits hne, List.head?_cons,
+ Option.isSome_some, ↓reduceIte, List.tail_cons, put_credit budget bits hne] using ih
+
+include hne in
+private theorem active_step (base : Stacks K) (credit : Bool) (xs guess : List Bool)
+ (c : ℕ → Stacks K → ℕ) (t : ℕ) :
+ (routine budget bits).countFrom c (t+1+1+1+1) (some .active)
+ (store budget bits base (credit :: xs) guess) =
+ (routine budget bits).countFrom c t (some .inactive) (store budget bits base xs guess) +
+ ((routine budget bits).countFrom c t (some .active) (store budget bits base xs (false :: guess)) +
+ (routine budget bits).countFrom c t (some .active) (store budget bits base xs (true :: guess))) := by
+ simp only [Routine.countFrom, routine, credits_at budget bits hne, List.head?_cons,
+ Option.isSome_some, ↓reduceIte, List.tail_cons, put_credit budget bits hne, guess_at, put_guess]
+
+include hne in
+private theorem active_count (base : Stacks K) (credits guess : List Bool)
+ (c : ℕ → Stacks K → ℕ) (t : ℕ) :
+ (routine budget bits).countFrom c (t + 4*credits.length + 1) (some .active)
+ (store budget bits base credits guess) =
+ ((words credits.length).map (fun bs => c t (store budget bits base [] (bs ++ guess)))).sum := by
+ induction credits generalizing guess with
+ | nil => simp [routine, Routine.countFrom, words, credits_at budget bits hne, put_credit budget bits hne]
+ | cons b xs ih =>
+ simp only [List.length_cons, Nat.mul_succ]
+ rw [show t + (4*xs.length+4) + 1 = (t+4*xs.length+1)+1+1+1+1 by omega]
+ rw [active_step budget bits hne, inactive_count budget bits hne, ih, ih]
+ simp [words, Function.comp_def, List.append_assoc]
+
+include hne in
+/-- Exact CPS count, with the budget and output ports explicit in the caller. -/
+theorem count (base : Stacks K) (credits : List Bool) (c : ℕ → Stacks K → ℕ) (t : ℕ) :
+ (routine budget bits).count c (t+4*credits.length+1)
+ (Function.update (Function.update base budget credits) bits []) =
+ ((words credits.length).map (fun bs => c t (Function.update (Function.update base budget []) bits bs))).sum := by
+ simpa [Routine.count, store, routine] using active_count budget bits hne base credits [] c t
+
+include hne in
+private theorem inactive_stops (base : Stacks K) (credits guess : List Bool)
+ (c : ℕ → Stacks K → Prop) (t : ℕ) :
+ (routine budget bits).AllStopsFrom c (t + 4*credits.length + 1) (some .inactive)
+ (store budget bits base credits guess) ↔ c t (store budget bits base [] guess) := by
+ induction credits with
+ | nil => simp [routine, Routine.AllStopsFrom, credits_at budget bits hne, put_credit budget bits hne]
+ | cons b xs ih =>
+ simp only [List.length_cons, Nat.mul_succ]
+ rw [show t + (4*xs.length+4) + 1 = (t+4*xs.length+1)+1+1+1+1 by omega]
+ simpa only [Routine.AllStopsFrom, routine, credits_at budget bits hne, List.head?_cons,
+ Option.isSome_some, ↓reduceIte, List.tail_cons, put_credit budget bits hne] using ih
+
+include hne in
+private theorem active_stops_step (base : Stacks K) (credit : Bool) (xs guess : List Bool)
+ (c : ℕ → Stacks K → Prop) (t : ℕ) :
+ (routine budget bits).AllStopsFrom c (t+1+1+1+1) (some .active)
+ (store budget bits base (credit :: xs) guess) ↔
+ (routine budget bits).AllStopsFrom c t (some .inactive) (store budget bits base xs guess) ∧
+ (routine budget bits).AllStopsFrom c t (some .active) (store budget bits base xs (false :: guess)) ∧
+ (routine budget bits).AllStopsFrom c t (some .active) (store budget bits base xs (true :: guess)) := by
+ simp only [Routine.AllStopsFrom, routine, credits_at budget bits hne, List.head?_cons,
+ Option.isSome_some, ↓reduceIte, List.tail_cons, put_credit budget bits hne, guess_at, put_guess]
+
+include hne in
+private theorem active_stops (base : Stacks K) (credits guess : List Bool)
+ (c : ℕ → Stacks K → Prop) (t : ℕ) :
+ (routine budget bits).AllStopsFrom c (t + 4*credits.length + 1) (some .active)
+ (store budget bits base credits guess) ↔
+ ∀ bs ∈ words credits.length, c t (store budget bits base [] (bs ++ guess)) := by
+ induction credits generalizing guess with
+ | nil => simp [routine, Routine.AllStopsFrom, words, credits_at budget bits hne, put_credit budget bits hne]
+ | cons b xs ih =>
+ simp only [List.length_cons, Nat.mul_succ]
+ rw [show t + (4*xs.length+4) + 1 = (t+4*xs.length+1)+1+1+1+1 by omega]
+ rw [active_stops_step budget bits hne, inactive_stops budget bits hne, ih, ih]
+ simp only [words, List.forall_mem_cons, List.forall_mem_append, List.forall_mem_map,
+ List.nil_append, List.append_assoc, List.singleton_append]
+
+include hne in
+/-- Every generator branch spends exactly the same prefix cost. The remaining
+budget suffices exactly when the continuation stops on each permitted list. -/
+theorem allStops_iff (base : Stacks K) (credits : List Bool) (c : ℕ → Stacks K → Prop) (t : ℕ) :
+ (routine budget bits).AllStops c (t+4*credits.length+1)
+ (Function.update (Function.update base budget credits) bits []) ↔
+ ∀ bs : List Bool, bs.length ≤ credits.length →
+ c t (Function.update (Function.update base budget []) bits bs) := by
+ simpa only [Routine.AllStops, routine, store, mem_words, List.append_nil] using
+ active_stops budget bits hne base credits [] c t
+
+end RAMTape.ProcessorChoices
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorCreditPorts.lean b/lean/OAI/Computability/VPVNP/RAMProcessorCreditPorts.lean
new file mode 100644
index 0000000000..00091f06b2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorCreditPorts.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.RAMTapeCharges
+
+/-!
+# Ports for the private interpreter's call credits and probe timestamps
+
+The public unary tallies are copied anew for each call. The global cap and
+remaining allowance stay binary. The saved start cost and the ordinal are
+the two per-call words needed for a chronological probe record.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.CallCredit
+
+open BurstRAM
+
+/-- Stack names for public and remaining credits, the binary global cap, probe timestamps and
+scratch space for copying and arithmetic. -/
+inductive Port where
+ | budget (p : Charges.Port)
+ | publicH | publicFuel | globalCap | savedStart | ordinal
+ | copyA | copyB | arithA | arithB
+ deriving DecidableEq, Fintype
+
+/-- The six-port charge routine is installed at the budget ports. -/
+theorem budget_injective : Function.Injective Port.budget := fun _ _ => Port.budget.inj
+
+/-- Encode the current credit state in its stacks, with unary public allowances, binary cap and
+the saved start and ordinal bit strings. -/
+def bank {w : ℕ} (H fuelCap fuel call site : ℕ) (cap g c : Word w)
+ (saved ordinal : List Bool) : Stacks Port
+ | .budget p => Charges.bank fuel call site g c p
+ | .publicH => List.replicate H true
+ | .publicFuel => List.replicate fuelCap true
+ | .globalCap => wordBits cap
+ | .savedStart => saved
+ | .ordinal => ordinal
+ | _ => []
+
+/-- The charge routine affects only the six installed counters and scratch.
+The public tallies, saved start and ordinal are kept in the caller's frame. -/
+theorem install_budget_bank {w : ℕ} (H fuelCap fuel call site fuel' call' site' : ℕ)
+ (cap g c g' c' : Word w) (saved ord : List Bool) :
+ installStacks Port.budget (bank H fuelCap fuel call site cap g c saved ord)
+ (Charges.bank fuel' call' site' g' c') =
+ bank H fuelCap fuel' call' site' cap g' c' saved ord := by
+ funext p
+ cases p with
+ | budget p => exact installStacks_at budget_injective ..
+ | publicH | publicFuel | globalCap | savedStart | ordinal | copyA | copyB | arithA | arithB =>
+ exact installStacks_outside _ _ (by simp)
+
+end RAMTape.CallCredit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorCreditReset.lean b/lean/OAI/Computability/VPVNP/RAMProcessorCreditReset.lean
new file mode 100644
index 0000000000..0050e3d597
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorCreditReset.lean
@@ -0,0 +1,151 @@
+import OAI.Computability.VPVNP.RAMProcessorCreditPorts
+import OAI.Computability.VPVNP.RAMTapeWordOperands
+import OAI.Computability.VPVNP.RAMTapeUnaryWordValue
+
+/-!
+# Resetting the private interpreter's call credits
+
+The reset copies the two public unary allowances and snapshots the cumulative
+cost. A second scan of the cost word supplies the width for the zero probe
+ordinal. Each scan restores its source and clears the previous destination.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.CallCredit
+
+open BurstRAM TapeWord
+
+private inductive Field where
+ | call | fuel | start | ordinal
+ deriving DecidableEq
+
+private def source : Field → Port
+ | .call => .publicH
+ | .fuel => .publicFuel
+ | .start | .ordinal => .budget .cost
+
+private def destination : Field → Port
+ | .call => .budget .call
+ | .fuel => .budget .fuel
+ | .start => .savedStart
+ | .ordinal => .ordinal
+
+private def ports (f : Field) : ScanPort → Port
+ | .left => source f
+ | .right => .copyA
+ | .tmp => .copyB
+ | .out => destination f
+
+private theorem ports_injective (f : Field) : Function.Injective (ports f) := by
+ intro i j h
+ cases f <;> cases i <;> cases j <;> simp_all [ports, source, destination]
+
+private def bit (f : Field) (_ : Unit) (b : Bool) : Bool × Unit :=
+ (if f = .ordinal then false else b, ())
+
+private def payload (f : Field) (xs : List Bool) :=
+ if f = .ordinal then List.replicate xs.length false else xs
+
+private theorem emitted (f : Field) (xs : List Bool) :
+ Operand.emitted (bit f) () xs = (payload f xs, ()) := by
+ induction xs with
+ | nil => simp [Operand.emitted, payload]
+ | cons b xs ih =>
+ rw [Operand.emitted]
+ simp only [bit, ih]
+ by_cases h : f = .ordinal <;> simp [payload, h, List.replicate_succ]
+
+private def normal : Operand.State Unit → Bool
+ | .done _ => true
+ | _ => false
+
+private def writeField (f : Field) : FiniteRoutine Port :=
+ .ofStackCode (Operand.code (bit f)) (ports f) (.clear ()) normal
+
+private def written (f : Field) (s : Stacks Port) :=
+ Function.update s (destination f) (payload f (s (source f)))
+
+private theorem writeField_runs (f : Field) (s : Stacks Port) (ha : s .copyA = []) (hb : s .copyB = []) :
+ (writeField f).Runs ((s (destination f)).length + 7*(s (source f)).length + 3) s (written f s) := by
+ have run := Operand.run (bit f) () (s (source f)) (s (destination f))
+ rw [emitted] at run
+ refine FiniteRoutine.runs_ofStackCode_framed (ports_injective f) (normal := normal) rfl rfl
+ (fun q h => ?_) run ?_ ?_ ?_
+ · cases q <;> first | rfl | contradiction
+ · intro i
+ cases i <;> first | rfl | exact ha | exact hb
+ · intro i
+ cases f <;> cases i <;> simp [written, ports, destination, source, scanStacks, ha, hb]
+ · intro i hi
+ exact Function.update_of_ne (Ne.symm (hi .out)) ..
+
+/-- Install the public budgets and record the start of this call. -/
+def resetCredits : FiniteRoutine Port :=
+ (((writeField .call).followedBy (writeField .fuel)).followedBy (writeField .start)).followedBy
+ (writeField .ordinal)
+
+/-- Only the two per-call allowances, start cost and probe ordinal are replaced. -/
+def resetFrame (s : Stacks Port) : Stacks Port
+ | .budget .call => s .publicH
+ | .budget .fuel => s .publicFuel
+ | .savedStart => s (.budget .cost)
+ | .ordinal => List.replicate (s (.budget .cost)).length false
+ | i => s i
+
+/-- Exact running time on a caller's frame. Empty, partially used, and
+full destination stacks are all permitted. -/
+theorem resetCredits_framed (s : Stacks Port) (ha : s .copyA = []) (hb : s .copyB = []) :
+ resetCredits.Runs ((s (.budget .call)).length + (s (.budget .fuel)).length +
+ (s .savedStart).length + (s .ordinal).length +
+ 7*((s .publicH).length + (s .publicFuel).length + 2*(s (.budget .cost)).length) + 12)
+ s (resetFrame s) := by
+ let s₁ := written .call s
+ let s₂ := written .fuel s₁
+ let s₃ := written .start s₂
+ have h₁ := writeField_runs .call s ha hb
+ have h₂ := writeField_runs .fuel s₁ (by simpa [s₁, written, destination] using ha)
+ (by simpa [s₁, written, destination] using hb)
+ have h₃ := writeField_runs .start s₂ (by simpa [s₂, s₁, written, destination] using ha)
+ (by simpa [s₂, s₁, written, destination] using hb)
+ have h₄ := writeField_runs .ordinal s₃ (by simpa [s₃, s₂, s₁, written, destination] using ha)
+ (by simpa [s₃, s₂, s₁, written, destination] using hb)
+ have h := ((h₁.followedBy h₂).followedBy h₃).followedBy h₄
+ have he : written .ordinal s₃ = resetFrame s := by
+ funext i
+ cases i with
+ | budget p => cases p <;> rfl
+ | _ => rfl
+ rw [he] at h
+ convert h using 1
+ · rfl
+ · simp [s₃, s₂, s₁, written, destination, source]
+ omega
+
+/-- Starting a call reloads the full fuel and call budgets, records the old
+cumulative cost, and initializes the ordinal to the width-correct zero. -/
+theorem resetCredits_run {w : ℕ} (H fuelCap fuel call site : ℕ) (cap g c : Word w)
+ (saved ord : List Bool) :
+ resetCredits.Runs (call + fuel + saved.length + ord.length + 7*(H + fuelCap + 2*w) + 12)
+ (bank H fuelCap fuel call site cap g c saved ord)
+ (bank H fuelCap fuelCap H site cap g c (wordBits c) (wordBits (0 : Word w))) := by
+ let s := bank H fuelCap fuel call site cap g c saved ord
+ have h := resetCredits_framed s rfl rfl
+ have he : resetFrame s = bank H fuelCap fuelCap H site cap g c (wordBits c) (wordBits (0 : Word w)) := by
+ funext i
+ cases i with
+ | budget p => cases p <;> rfl
+ | ordinal =>
+ change List.replicate (wordBits c).length false = wordBits (0 : Word w)
+ rw [length_wordBits, UnaryWord.zeros_wordBits]
+ | _ => rfl
+ rw [he] at h
+ simpa only [s, bank, Charges.bank, Charges.Data.stacks, List.length_replicate, length_wordBits] using h
+
+end RAMTape.CallCredit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorFlow.lean b/lean/OAI/Computability/VPVNP/RAMProcessorFlow.lean
new file mode 100644
index 0000000000..a53691ba98
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorFlow.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.RAMTapeISAPorts
+
+/-!
+# Linking burst-processor stages with named exits
+
+The call interpreter must return to one of several program counters, request
+an external read or write, or finish its call. A fragment's local rows can
+name both local continuations and arbitrary exits. Linking selects the entry
+of the destination immediately, with no added step on these transfers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+/-- A finite stack-code block whose instructions can continue at a local state or transfer to a
+named exit. -/
+structure Fragment (K L : Type) where
+ /-- Finite set of instruction states internal to this fragment. -/
+ State : Type
+ [finiteState : Fintype State]
+ /-- Initial local instruction state on entry to the fragment. -/
+ entry : State
+ /-- Instruction at each local state, with successors selected from local states and named
+ exits. -/
+ code : State → StackOp K (State ⊕ L)
+
+attribute [instance] Fragment.finiteState
+
+namespace Fragment
+
+variable {K L Q : Type}
+
+/-- Standalone fragment table that executes the local code and treats every named exit as an
+accepting halt. -/
+def isolated (f : Fragment K L) : StackCode K (f.State ⊕ L)
+ | .inl q => f.code q
+ | .inr _ => .halt true
+
+/-- An execution from fragment entry to the specified named exit in exactly the stated number
+of steps and with the stated final stacks. -/
+abbrev Runs [DecidableEq K] (f : Fragment K L) (t : ℕ) (s : Stacks K) (exit : L) (out : Stacks K) :=
+ StackRuns f.isolated t (.inl f.entry) s (.inr exit) out
+
+/-- Form a one-instruction fragment whose continuations are all named exits. -/
+def direct (op : StackOp K L) : Fragment K L :=
+ ⟨Unit, (), fun _ => op.rename id Sum.inr⟩
+
+/-- Turn a finite routine into a fragment that transfers a normal return to the specified exit
+label. -/
+def returning (r : FiniteRoutine K) (next : L) : Fragment K L :=
+ ⟨r.State, r.body.entry, fun q => (r.body.code q).rename id (Option.elim · (.inr next) Sum.inl)⟩
+
+/-- The continuation after an ordinary subroutine can be any flow label. -/
+theorem returning_runs [DecidableEq K] {r : FiniteRoutine K} {t s u}
+ (h : r.Runs t s u) (next : L) : (returning r next).Runs t s next u := by
+ let labels : Option r.State → (returning r next).State ⊕ L := fun q => q.elim (.inr next) Sum.inl
+ have same (s t : Stacks K) : installStacks id s t = t := by
+ funext i
+ exact installStacks_at Function.injective_id s t i
+ have link := h.lift id Function.injective_id labels s
+ (target := (returning r next).isolated) (by
+ intro q hq
+ cases q with
+ | none => contradiction
+ | some q => rfl)
+ change StackRuns (returning r next).isolated t (.inl r.body.entry) s (.inr next) u
+ change StackRuns (returning r next).isolated t (.inl r.body.entry) (installStacks id s s) (.inr next) (installStacks id s u) at link
+ simpa only [same] using link
+
+/-- Install a multi-exit program. A designated boundary row is intercepted
+on entry, allowing the caller to decide what follows each returned action. -/
+def fromCode [Fintype Q] (src : StackCode K Q) (entry : Q) (exits : Q → Option L) :
+ Fragment K L :=
+ ⟨Q, entry, fun q => match exits q with
+ | some l => .goto (.inr l)
+ | none => (src q).rename id (fun r => (exits r).elim (.inl r) Sum.inr)⟩
+
+theorem fromCode_runs [DecidableEq K] [Fintype Q] {src : StackCode K Q} {entry finish : Q}
+ (exits : Q → Option L) (he : exits entry = none) {next : L} (hx : exits finish = some next)
+ (hb : ∀ q, (src q).returns = false → exits q = none) {t s u}
+ (run : StackRuns src t entry s finish u) :
+ (fromCode src entry exits).Runs t s next u := by
+ let labels : Q → (fromCode src entry exits).State ⊕ L :=
+ fun q => (exits q).elim (.inl q) Sum.inr
+ have same (s t : Stacks K) : installStacks id s t = t := by
+ funext i
+ exact installStacks_at Function.injective_id s t i
+ have link := run.lift id Function.injective_id labels s
+ (target := (fromCode src entry exits).isolated) (by
+ intro q hq
+ simp only [labels, hb q hq, Option.elim_none, isolated, fromCode])
+ change StackRuns (fromCode src entry exits).isolated t (.inl entry) s (.inr next) u
+ simpa only [labels, he, hx, Option.elim_none, Option.elim_some, same] using link
+
+/-- Place a fragment's ports inside a larger bank, leaving the remaining
+stacks available to the caller. -/
+def onPorts {J : Type} (f : Fragment K L) (ports : K → J) : Fragment J L :=
+ ⟨f.State, f.entry, fun q => (f.code q).rename ports id⟩
+
+theorem runs_onPorts {J : Type} [DecidableEq K] [DecidableEq J] {f : Fragment K L}
+ (ports : K → J) (hi : Function.Injective ports) (base : Stacks J)
+ {t s exit u} (run : f.Runs t s exit u) :
+ (f.onPorts ports).Runs t (installStacks ports base s) exit (installStacks ports base u) := by
+ have h := run.lift ports hi id base (target := (f.onPorts ports).isolated) (by
+ intro q hq
+ cases q with
+ | inl _ => rfl
+ | inr _ => contradiction)
+ exact h
+
+end Fragment
+
+namespace ProcessorFlow
+
+variable {K L : Type}
+
+/-- Instruction address in the linked processor, pairing a block label with a local state of
+that block. -/
+abbrev State (blocks : L → Fragment K L) := Σ l, (blocks l).State
+
+/-- Select a named block and its entry state as the linked instruction address. -/
+def enter (blocks : L → Fragment K L) (l : L) : State blocks := ⟨l, (blocks l).entry⟩
+
+/-- Resolve a successor by continuing inside the current block or entering the destination
+named by an exit. -/
+def next (blocks : L → Fragment K L) (l : L) : (blocks l).State ⊕ L → State blocks :=
+ Sum.elim (fun q => ⟨l, q⟩) (enter blocks)
+
+/-- Link the fragment tables into one stack program by resolving each local successor and each
+named transfer. -/
+def program (blocks : L → Fragment K L) : StackCode K (State blocks) :=
+ fun ⟨l, q⟩ => ((blocks l).code q).rename id (next blocks l)
+
+/-- A whole deterministic path in a fragment runs unchanged in the linked
+program, arriving directly at the entry of its exit label. -/
+theorem run [DecidableEq K] {blocks : L → Fragment K L} {l exit t s u}
+ (h : (blocks l).Runs t s exit u) : StackRuns (program blocks) t (enter blocks l) s (enter blocks exit) u := by
+ have same (s t : Stacks K) : installStacks id s t = t := by
+ funext i
+ exact installStacks_at Function.injective_id s t i
+ have link := h.lift id Function.injective_id (next blocks l) s (target := program blocks) (by
+ intro q hq
+ cases q with
+ | inl q => rfl
+ | inr r => contradiction)
+ simpa only [enter, next, Sum.elim_inl, Sum.elim_inr, same] using link
+
+end ProcessorFlow
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorGlobalCredit.lean b/lean/OAI/Computability/VPVNP/RAMProcessorGlobalCredit.lean
new file mode 100644
index 0000000000..5d86016ef5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorGlobalCredit.lean
@@ -0,0 +1,194 @@
+import OAI.Computability.VPVNP.RAMProcessorCreditPorts
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+import OAI.Computability.VPVNP.RAMTapeWordSimple
+
+/-!
+# Initializing the processor's remaining global allowance
+
+The input cap and incoming cumulative cost occupy binary words. The processor
+copies both words, subtracts the cost from the cap, and rejects on a final
+borrow. The cap, the cumulative cost, and the other call counters survive this
+operation. The running time is linear in the word width and the old output.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.CallCredit.GlobalCredit
+
+open BurstRAM TapeWord SuccessorFields
+
+private def stages : FiniteRoutine Port :=
+ (prependCopy Port.globalCap .arithA .copyA).followedBy
+ (prependCopy (.budget .cost) .arithB .copyA)
+
+/-- Control states for staging the cap and cost, clearing the destination and subtracting to
+compute the remaining global credit. -/
+inductive State where
+ | stage (q : stages.State)
+ | clear
+ | subtract (q : ScanState)
+ deriving Fintype
+
+private def ports : ScanPort → Port
+ | .left => .arithA
+ | .right => .arithB
+ | .tmp => .budget .tmp
+ | .out => .budget .globalLeft
+
+private def resume : ScanState → Option State
+ | .done false => none
+ | q => some (.subtract q)
+
+/-- The no-borrow exit returns to the caller. A borrow stops the entire path. -/
+def body : Routine Port State where
+ entry := State.stage stages.body.entry
+ code := fun
+ | .stage q => stages.body.install State.stage (some .clear) q
+ | .clear => .pop (.budget .globalLeft) fun b => b.elim (some (.subtract (.left false))) (fun _ => some .clear)
+ | .subtract (.done _) => .halt false
+ | .subtract q => (scanCode subBit q).rename ports resume
+
+/-- Compute the remaining global credit by subtracting cumulative cost from the cap, rejecting
+if subtraction borrows past the word. -/
+abbrev routine : FiniteRoutine Port := ⟨State, body⟩
+
+@[simp] theorem borrow_halts : routine.body.code (.subtract (.done true)) = .halt false := rfl
+
+private def staged (s : Stacks Port) (a b : List Bool) : Stacks Port :=
+ Function.update (Function.update s .arithA a) .arithB b
+
+private theorem stageRun {w : ℕ} (s : Stacks Port) (cap cost : Word w)
+ (hcap : s .globalCap = wordBits cap) (hcost : s (.budget .cost) = wordBits cost)
+ (hcopy : s .copyA = []) (ha : s .arithA = []) (hb : s .arithB = []) :
+ stages.Runs (10*w+4) s (staged s (wordBits cap) (wordBits cost)) := by
+ have h₁ := prependCopy_runs Port.globalCap .arithA .copyA (by decide) (by decide) (by decide) s hcopy
+ simp only [hcap, ha, List.append_nil, length_wordBits] at h₁
+ let s' := Function.update s .arithA (wordBits cap)
+ have h₂ := prependCopy_runs (Port.budget .cost) .arithB .copyA (by decide) (by decide) (by decide) s'
+ (by simpa [s'] using hcopy)
+ have hc' : s' (.budget .cost) = wordBits cost := by simpa [s'] using hcost
+ have hb' : s' .arithB = [] := by simpa [s'] using hb
+ simp only [hc', hb', List.append_nil, length_wordBits] at h₂
+ rw [show 10*w+4 = (5*w+2)+(5*w+2) by omega]
+ exact h₁.followedBy h₂
+
+private theorem clearRun (s : Stacks Port) (xs : List Bool) :
+ StackRuns routine.body.standalone (xs.length+1) (some .clear)
+ (Function.update s (.budget .globalLeft) xs) (some (.subtract (.left false)))
+ (Function.update s (.budget .globalLeft) []) := by
+ induction xs with
+ | nil =>
+ refine .cons (.pop rfl) ?_
+ simp only [Function.update_self, List.head?_nil, List.tail_nil, Option.elim_none, Function.update_idem]
+ exact .nil ..
+ | cons b xs ih =>
+ refine .cons (.pop rfl) ?_
+ simp only [Function.update_self, List.head?_cons, List.tail_cons, Option.elim_some, Function.update_idem]
+ exact ih
+
+private theorem subtractRun {w : ℕ} (s : Stacks Port) (cap cost : Word w)
+ (ha : s .arithA = []) (hb : s .arithB = []) (ht : s (.budget .tmp) = []) :
+ StackRuns routine.body.standalone (5*w+2) (some (.subtract (.left false)))
+ (Function.update (staged s (wordBits cap) (wordBits cost)) (.budget .globalLeft) [])
+ (resume (.done (decide (cap.val < cost.val))))
+ (Function.update s (.budget .globalLeft) (wordBits (cap-cost))) := by
+ have hp : Function.Injective ports := by decide
+ have rows (q : ScanState) (hn : (scanCode subBit q).returns = false) :
+ routine.body.standalone (resume q) = (scanCode subBit q).rename ports resume := by
+ cases q <;> first | rfl | contradiction
+ have hr := (ScanOp.word_run .sub cap cost).lift ports hp resume s rows
+ have hf : (scan subBit false (wordBits cap) (wordBits cost)).2 = decide (cap.val < cost.val) := by
+ apply Bool.eq_iff_iff.mpr
+ simpa only [value_wordBits, Bool.toNat_false, Nat.add_zero, decide_eq_true_eq] using
+ subScan_borrow (c := false) (x := wordBits cap) (y := wordBits cost) (by simp)
+ change StackRuns _ _ _ (installStacks ports s (scanStacks (wordBits cap) (wordBits cost) [] []))
+ (resume (.done (scan subBit false (wordBits cap) (wordBits cost)).2))
+ (installStacks ports s (scanStacks [] [] [] (wordBits (cap-cost)))) at hr
+ rw [hf] at hr
+ have hi : installStacks ports s (scanStacks (wordBits cap) (wordBits cost) [] []) =
+ Function.update (staged s (wordBits cap) (wordBits cost)) (.budget .globalLeft) [] := by
+ apply installStacks_frame hp
+ · intro p; cases p <;> simp [staged, ports, scanStacks, ht]
+ · intro i hout
+ have hl : i ≠ .arithA := (hout .left).symm
+ have hr : i ≠ .arithB := (hout .right).symm
+ have ho : i ≠ .budget .globalLeft := (hout .out).symm
+ simp [staged, Function.update_of_ne, hl, hr, ho]
+ have ho : installStacks ports s (scanStacks [] [] [] (wordBits (cap-cost))) =
+ Function.update s (.budget .globalLeft) (wordBits (cap-cost)) := by
+ apply installStacks_frame hp
+ · intro p; cases p <;> simp [ports, scanStacks, ha, hb, ht]
+ · intro i hout; exact Function.update_of_ne (Ne.symm (hout .out)) ..
+ rwa [hi, ho] at hr
+
+/-- Every valid pair of input words has a deterministic path of the same
+length. The final control is the rejecting halt exactly when the cost
+exceeds the cap. All ports except the global allowance are restored. -/
+theorem run {w : ℕ} (s : Stacks Port) (cap cost : Word w)
+ (hcap : s .globalCap = wordBits cap) (hcost : s (.budget .cost) = wordBits cost)
+ (hcopy : s .copyA = []) (ha : s .arithA = []) (hb : s .arithB = []) (ht : s (.budget .tmp) = []) :
+ StackRuns routine.body.standalone ((s (.budget .globalLeft)).length + 15*w+7)
+ (some routine.body.entry) s (if cap.val < cost.val then some (.subtract (.done true)) else none)
+ (Function.update s (.budget .globalLeft) (wordBits (cap-cost))) := by
+ let t := staged s (wordBits cap) (wordBits cost)
+ have hs := (stageRun s cap cost hcap hcost hcopy ha hb).link routine.body State.stage
+ (some .clear) (fun _ => rfl)
+ have hc := clearRun t (t (.budget .globalLeft))
+ rw [Function.update_eq_self] at hc
+ have he : t (.budget .globalLeft) = s (.budget .globalLeft) := by simp [t, staged]
+ rw [he] at hc
+ have hu := subtractRun s cap cost ha hb ht
+ rw [show (s (.budget .globalLeft)).length+15*w+7 =
+ (10*w+4)+((s (.budget .globalLeft)).length+1)+(5*w+2) by omega]
+ have hall := (hs.trans hc).trans hu
+ rw [show (if cap.val < cost.val then some (State.subtract (.done true)) else none) =
+ resume (.done (decide (cap.val < cost.val))) by by_cases h : cap.val < cost.val <;> simp [h, resume]]
+ exact hall
+
+/-- The arithmetic word represents ordinary natural subtraction whenever
+initialization returns, including at exact exhaustion of the global allowance. -/
+theorem remaining_val {w : ℕ} (cap cost : Word w) (hle : cost.val ≤ cap.val) :
+ (cap-cost).val = cap.val - cost.val := by
+ rw [Fin.val_sub]
+ have hcap := cap.isLt
+ have hcost := cost.isLt
+ rw [show 2^w - cost.val + cap.val = (cap.val-cost.val) + 2^w by omega, Nat.add_mod_right,
+ Nat.mod_eq_of_lt (by omega)]
+
+private theorem update_bank {w : ℕ} (H fuelCap fuel call site : ℕ) (cap old cost out : Word w)
+ (saved ord : List Bool) :
+ Function.update (bank H fuelCap fuel call site cap old cost saved ord) (.budget .globalLeft) (wordBits out) =
+ bank H fuelCap fuel call site cap out cost saved ord := by
+ funext p
+ cases p with
+ | budget p => cases p <;> rfl
+ | _ => rfl
+
+theorem bank_run {w : ℕ} (H fuelCap fuel call site : ℕ) (cap old cost : Word w) (saved ord : List Bool)
+ (hle : cost.val ≤ cap.val) :
+ routine.Runs (16*w+7) (bank H fuelCap fuel call site cap old cost saved ord)
+ (bank H fuelCap fuel call site cap (cap-cost) cost saved ord) := by
+ have hr := run (bank H fuelCap fuel call site cap old cost saved ord) cap cost rfl rfl rfl rfl rfl rfl
+ rw [ite_eq_right (Nat.not_lt.mpr hle), update_bank] at hr
+ change StackRuns _ ((wordBits old).length+15*w+7) _ _ none _ at hr
+ rw [length_wordBits, show w+15*w+7 = 16*w+7 by omega] at hr
+ exact hr
+
+theorem bank_reject {w : ℕ} (H fuelCap fuel call site : ℕ) (cap old cost : Word w) (saved ord : List Bool)
+ (hbad : cap.val < cost.val) :
+ StackRuns routine.body.standalone (16*w+7) (some routine.body.entry)
+ (bank H fuelCap fuel call site cap old cost saved ord) (some (.subtract (.done true)))
+ (bank H fuelCap fuel call site cap (cap-cost) cost saved ord) := by
+ have hr := run (bank H fuelCap fuel call site cap old cost saved ord) cap cost rfl rfl rfl rfl rfl rfl
+ rw [ite_eq_left hbad, update_bank] at hr
+ change StackRuns _ ((wordBits old).length+15*w+7) _ _ _ _ at hr
+ rw [length_wordBits, show w+15*w+7 = 16*w+7 by omega] at hr
+ exact hr
+
+end RAMTape.CallCredit.GlobalCredit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorGraph.lean b/lean/OAI/Computability/VPVNP/RAMProcessorGraph.lean
new file mode 100644
index 0000000000..418eefacd1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorGraph.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.RAMProcessorState
+import OAI.Computability.VPVNP.RAMProcessorReset
+import OAI.Computability.VPVNP.RAMProcessorProbeStages
+import OAI.Computability.VPVNP.RAMProcessorSiteTestsFlow
+
+/-!
+# The fixed stack table for a complete burst site
+
+On entry the initialization record is staged and the parser has supplied the
+local header, cuts and public budgets. Every call starts with fresh registers
+and private log. Each probe first pays its unit, then stages its record, emits
+it, and increments the ordinal. A returning call either starts another call
+in this bucket or finishes the site. The normal exit exposes the padded record
+block to the local bitonic and memory checks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+namespace Fragment
+
+variable {K L M : Type}
+
+/-- Apply a continuation-label map to every normal exit of a fragment. -/
+def mapExits (f : Fragment K L) (g : L → M) : Fragment K M :=
+ ⟨f.State, f.entry, fun q => (f.code q).rename id (Sum.map id g)⟩
+
+theorem runs_mapExits [DecidableEq K] {f : Fragment K L} (g : L → M)
+ {t s exit out} (h : f.Runs t s exit out) :
+ (f.mapExits g).Runs t s (g exit) out := by
+ have hi (x : Stacks K) : installStacks id s x = x := by
+ funext j; exact installStacks_at Function.injective_id s x j
+ have hr := h.lift id Function.injective_id (Sum.map id g) s (target := (f.mapExits g).isolated)
+ (by intro q hq; cases q with | inl _ => rfl | inr _ => contradiction)
+ change StackRuns (f.mapExits g).isolated t (.inl f.entry) s (.inr (g exit)) out
+ change StackRuns (f.mapExits g).isolated t (.inl f.entry) (installStacks id s s) (.inr (g exit)) (installStacks id s out) at hr
+ simpa only [hi] using hr
+
+end Fragment
+
+namespace SiteProcessor
+
+open BurstRAM PrivateRAM
+
+/-- Locations in the site's call, probe, record and acceptance graph. -/
+inductive Label (p r : ℕ) where
+ | initialRecord | checkEntry | first | newCall | fresh
+ | segment (pc : Fin p)
+ | callback (cb : ISA.Callback p r)
+ | read (dst addr : Fin r) (next : Fin p)
+ | write (addr src : Fin r) (next : Fin p)
+ | emit (next : Fin p) | increment (next : Fin p)
+ | iteration | finalCheck | close | done | reject
+ deriving Fintype
+
+variable {p r k : ℕ}
+
+/-- Select the first call, a subsequent call, the final check or rejection. -/
+def route (first : Bool) : SiteTests.Exit → Label p r
+ | .reject => .reject
+ | .dispatch => if first then .first else .newCall
+ | .finish => .finalCheck
+
+/-- Fixed jump graph, instantiated once from a literal-width call template. -/
+def blocks (T : Template p r k) : Label p r → Fragment (Port r k) (Label p r)
+ | .initialRecord => (Fragment.returning RecordBuffer.appendRecord .checkEntry).onPorts recordPorts
+ | .checkEntry => (SiteTests.entry.fragment (route true)).onPorts testPorts
+ | .first => (Fragment.returning CallCredit.firstCall .fresh).onPorts Port.credit
+ | .newCall => (Fragment.returning CallCredit.startCall .fresh).onPorts Port.credit
+ | .fresh => (Fragment.returning (ISA.freshCall (r := r) (k := k)) (.segment T.entry)).onPorts Port.isa
+ | .segment pc => (localBlock T pc).mapExits Label.callback
+ | .callback (.read dst addr next) => (Fragment.returning CallCredit.prepareProbe (.read dst addr next)).onPorts Port.credit
+ | .callback (.write addr src next) => (Fragment.returning CallCredit.prepareProbe (.write addr src next)).onPorts Port.credit
+ | .read dst addr next => (ProbeStages.read dst addr (.emit next) .reject).onPorts probePorts
+ | .write addr src next => (Fragment.returning (ProbeStages.writePayload addr src) (.emit next)).onPorts probePorts
+ | .emit next => (Fragment.returning RecordBuffer.appendRecord (.increment next)).onPorts recordPorts
+ | .increment next => (Fragment.returning CallCredit.finishProbe (.segment next)).onPorts Port.credit
+ | .callback (.returnState src) => (Fragment.returning (ProbeStages.returnState src) .iteration).onPorts probePorts
+ | .callback .accept => (Fragment.returning (ProbeStages.accept (r := r) (k := k)) .iteration).onPorts probePorts
+ | .callback _ => Fragment.direct (.goto .reject)
+ | .iteration => (SiteTests.iteration.fragment (route false)).onPorts testPorts
+ | .finalCheck => (SiteTests.finalCheck.fragment (fun e => if e = .finish then .close else .reject)).onPorts testPorts
+ | .close => (Fragment.returning RecordBuffer.close .done).onPorts recordPorts
+ | .done => Fragment.direct (.halt true)
+ | .reject => Fragment.direct (.halt false)
+
+/-- The finite control type obtained by linking the site's fragments. -/
+abbrev Control (T : Template p r k) := ProcessorFlow.State (blocks T)
+
+/-- The executable stack instruction table for a fixed RAM template. -/
+def table (T : Template p r k) : StackCode (Port r k) (Control T) :=
+ ProcessorFlow.program (blocks T)
+
+/-- Enter the fragment belonging to a site graph location. -/
+def atLabel (T : Template p r k) (l : Label p r) : Control T := ProcessorFlow.enter (blocks T) l
+
+@[simp] theorem done_row (T : Template p r k) : table T (atLabel T .done) = .halt true := rfl
+@[simp] theorem reject_row (T : Template p r k) : table T (atLabel T .reject) = .halt false := rfl
+
+/-- Physical execution of a segment of the actual graph, including its fuel
+and choice cutoffs. -/
+theorem segment_run {w : ℕ} (T : Template p r k) (s : Snapshot w p r k) (limit : ℕ)
+ (hl : s.cfg.writes.length+s.fuel ≤ limit) :
+ let y := LocalProcessor.scan T s.pub s.fuel s.cfg s.choices
+ ∃ t ≤ s.fuel*(ISA.prepareBound w limit+4)+1,
+ StackRuns (table T) t (atLabel T (.segment s.cfg.pc)) s.bank
+ (atLabel T (.callback y.exit)) (s.afterLocal y).bank := by
+ obtain ⟨t, ht, h⟩ := s.runLocal T limit hl
+ exact ⟨t, ht, ProcessorFlow.run (blocks := blocks T) (l := Label.segment s.cfg.pc) (Fragment.runs_mapExits Label.callback h)⟩
+
+end SiteProcessor
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorGraphCredit.lean b/lean/OAI/Computability/VPVNP/RAMProcessorGraphCredit.lean
new file mode 100644
index 0000000000..0de696389d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorGraphCredit.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.RAMProcessorGraphRuns
+
+/-!
+# Charging transitions of the linked site graph
+
+The transfer to a read or write payload is possible only after all three
+allowances are checked. On a failing allowance the graph halts inside the
+charging routine. The probe ordinal increases after the record emission.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM
+
+variable {w p r k : ℕ}
+
+/-- Update the runtime instruction, call, site and global credit registers. -/
+def Snapshot.setCredit (s : Snapshot w p r k) (fuel callLeft siteLeft : ℕ) (g cost : Word w)
+ (saved ordinal : List Bool) : Snapshot w p r k :=
+ {s with
+ fuel := fuel
+ callLeft := callLeft
+ siteLeft := siteLeft
+ globalLeft := g
+ cost := cost
+ savedStart := saved
+ ordinal := ordinal}
+
+theorem Snapshot.credit_frame (s : Snapshot w p r k) (fuel callLeft siteLeft : ℕ) (g cost : Word w)
+ (saved ordinal : List Bool) (j : Port r k) (hj : ∀ i, Port.credit i ≠ j) :
+ (s.setCredit fuel callLeft siteLeft g cost saved ordinal).bank j = s.bank j := by
+ cases j with
+ | credit i => exact (hj i rfl).elim
+ | test i => cases i with | word f => cases f <;> rfl | _ => rfl
+ | record i => cases i with | field i => fin_cases i <;> rfl | _ => rfl
+ | _ => rfl
+
+theorem credit_routine (T : Template p r k) (s : Snapshot w p r k) {rt : FiniteRoutine CallCredit.Port}
+ {l next : Label p r} (link : blocks T l = (Fragment.returning rt next).onPorts Port.credit)
+ {t fuel callLeft siteLeft g cost saved ordinal}
+ (h : rt.Runs t s.credit (s.setCredit fuel callLeft siteLeft g cost saved ordinal).credit) :
+ StackRuns (table T) t (atLabel T l) s.bank (atLabel T next)
+ (s.setCredit fuel callLeft siteLeft g cost saved ordinal).bank := by
+ apply ProcessorFlow.run (blocks := blocks T)
+ rw [link]
+ exact Fragment.runs_framed (fun _ _ h => Port.credit.inj h) (Fragment.returning_runs h next)
+ (fun _ => rfl) (fun _ => rfl) (fun j hj => s.credit_frame fuel callLeft siteLeft g cost saved ordinal j hj)
+
+/-- The snapshot after a successful unit charge for a probe. -/
+def Snapshot.afterCharge (s : Snapshot w p r k) (hc : s.cost.val+1 < 2^w) :=
+ s.setCredit s.fuel (s.callLeft-1) (s.siteLeft-1) (Charges.prevWord s.globalLeft) ⟨s.cost.val+1,hc⟩
+ s.savedStart s.ordinal
+
+theorem precharge_run (T : Template p r k) (s : Snapshot w p r k) {l next : Label p r}
+ (link : blocks T l = (Fragment.returning CallCredit.prepareProbe next).onPorts Port.credit)
+ (hc : s.cost.val+1 < 2^w) (hg : 0 < s.globalLeft.val) (hcall : 0 < s.callLeft) (hsite : 0 < s.siteLeft) :
+ StackRuns (table T) (8*w+6) (atLabel T l) s.bank (atLabel T next) (s.afterCharge hc).bank := by
+ apply credit_routine T s link
+ have h := CallCredit.prepareProbe_run s.publicH s.publicFuel s.fuel (s.callLeft-1) (s.siteLeft-1)
+ s.cap s.globalLeft s.cost s.savedStart s.ordinal hg hc
+ simpa only [Snapshot.setCredit, Snapshot.credit, Nat.sub_add_cancel hcall, Nat.sub_add_cancel hsite] using h
+
+theorem precharge_reject (T : Template p r k) (s : Snapshot w p r k) {l next : Label p r}
+ (link : blocks T l = (Fragment.returning CallCredit.prepareProbe next).onPorts Port.credit)
+ (bad : s.callLeft = 0 ∨ s.siteLeft = 0 ∨ s.globalLeft.val = 0 ∨ 2^w ≤ s.cost.val+1) :
+ RejectRun (table T) (Charges.failureTicks s.callLeft s.siteLeft s.globalLeft) (atLabel T l) s.bank := by
+ obtain ⟨_, hr⟩ := CallCredit.prepareProbe_reject s.publicH s.publicFuel s.fuel s.callLeft s.siteLeft
+ s.cap s.globalLeft s.cost s.savedStart s.ordinal bad
+ exact ProcessorFlow.routine_reject (blocks := blocks T) (fun _ _ h => Port.credit.inj h)
+ link hr CallCredit.prepareProbe_halt (fun _ => rfl)
+
+/-- The snapshot after incrementing the emitted probe's ordinal. -/
+def Snapshot.afterIncrement (s : Snapshot w p r k) (o : Word w) (ho : o.val+1 < 2^w) :=
+ s.setCredit s.fuel s.callLeft s.siteLeft s.globalLeft s.cost s.savedStart (wordBits (⟨o.val+1,ho⟩ : Word w))
+
+theorem increment_run (T : Template p r k) (s : Snapshot w p r k) (next : Fin p) (o : Word w)
+ (hord : s.ordinal = wordBits o) (ho : o.val+1 < 2^w) :
+ StackRuns (table T) (4*w+2) (atLabel T (.increment next)) s.bank (atLabel T (.segment next))
+ (s.afterIncrement o ho).bank := by
+ apply credit_routine T s (rt := CallCredit.finishProbe) rfl
+ have hr := CallCredit.finishProbe_bank s.publicH s.publicFuel s.fuel s.callLeft s.siteLeft
+ s.cap s.globalLeft s.cost o s.savedStart ho
+ simpa only [Snapshot.credit, Snapshot.setCredit, hord] using hr
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorGraphProbe.lean b/lean/OAI/Computability/VPVNP/RAMProcessorGraphProbe.lean
new file mode 100644
index 0000000000..f635655f52
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorGraphProbe.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.RAMProcessorGraphRuns
+
+/-!
+# Native graph transfers for reads, writes and call returns
+
+At an external read the graph copies the old address, consumes a full guessed
+word, and only then replaces the destination register. Writes copy both original
+register values. Return and acceptance update the persistent state/status used
+by the site's iteration test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM
+
+variable {w p r k : ℕ}
+
+private def Snapshot.withProbe (s : Snapshot w p r k) (cfg : LogConfig w p r)
+ (choices tag addr value : List Bool) (running : Bool) : Snapshot w p r k :=
+ {s with cfg := cfg, choices := choices, tag := tag, address := addr, value := value, running := running}
+
+/-- The record stages the address from before the destination register was
+assigned. Thus the address and destination may be the same register. -/
+def Snapshot.afterRead (s : Snapshot w p r k) (dst addr : Fin r) (next : Fin p)
+ (v : Word w) (tail : List Bool) : Snapshot w p r k :=
+ s.withProbe {s.cfg with pc := next, reg := Function.update s.cfg.reg dst v} tail
+ (wordBits (Fin.ofNat (2^w) 2)) (wordBits (s.cfg.reg addr)) (wordBits v) s.running
+
+/-- Snapshot after decoding an external write, with the next instruction selected and the write
+tag, source address and value staged for recording. -/
+def Snapshot.afterWrite (s : Snapshot w p r k) (addr src : Fin r) (next : Fin p) : Snapshot w p r k :=
+ s.withProbe {s.cfg with pc := next} s.choices (wordBits (Fin.ofNat (2^w) 3))
+ (wordBits (s.cfg.reg addr)) (wordBits (s.cfg.reg src)) s.running
+
+/-- Snapshot after a call returns the designated register as its persistent word and marks the
+machine as running. -/
+def Snapshot.afterReturn (s : Snapshot w p r k) (src : Fin r) : Snapshot w p r k :=
+ s.withProbe {s.cfg with persistent := s.cfg.reg src} s.choices s.tag s.address s.value true
+
+/-- Snapshot after acceptance, with the running flag cleared for the site's next iteration
+test. -/
+def Snapshot.afterAccept (s : Snapshot w p r k) : Snapshot w p r k :=
+ s.withProbe s.cfg s.choices s.tag s.address s.value false
+
+private theorem probe_frame (s : Snapshot w p r k) (cfg : LogConfig w p r)
+ (cs t a v : List Bool) (run : Bool) (j : Port r k) (hj : ∀ i, probePorts i ≠ j) :
+ (s.withProbe cfg cs t a v run).bank j = s.bank j := by
+ cases j with
+ | isa i => exact (hj (.inl i) rfl).elim
+ | credit i => rfl
+ | test i =>
+ cases i with
+ | choices => exact (hj (.inr .choices) rfl).elim
+ | bit b => cases b <;> first | rfl | exact (hj (.inr .running) rfl).elim
+ | word f => cases f <;> rfl
+ | _ => rfl
+ | record i =>
+ cases i with
+ | field f =>
+ fin_cases f <;>
+ first | rfl | exact (hj (.inr .tag) rfl).elim | exact (hj (.inr .address) rfl).elim |
+ exact (hj (.inr .value) rfl).elim
+ | _ => rfl
+ | scratch _ => rfl
+
+private theorem read_probe (s : Snapshot w p r k) (dst addr : Fin r) (next : Fin p)
+ (v : Word w) (tail : List Bool) :
+ (s.afterRead dst addr next v tail).probe =
+ {s.probe with
+ choices := tail
+ value := wordBits v
+ tag := wordBits (Fin.ofNat (2^w) 2)
+ address := wordBits (s.cfg.reg addr)
+ isa := Function.update s.probe.isa (.reg dst) (wordBits v)} := by
+ simp only [Snapshot.afterRead, Snapshot.withProbe, Snapshot.probe, ISA.configBank, ISA.bank_updateReg]
+
+private theorem return_probe (s : Snapshot w p r k) (src : Fin r) :
+ (s.afterReturn src).probe =
+ {s.probe with isa := Function.update s.probe.isa .persistent (wordBits (s.cfg.reg src)), running := [true]} := by
+ have he : ISA.configBank s.pub {s.cfg with persistent := s.cfg.reg src} =
+ Function.update (ISA.configBank s.pub s.cfg) .persistent (wordBits (s.cfg.reg src)) := by
+ funext j
+ cases j <;> simp [ISA.configBank, ISA.bank]
+ simp only [Snapshot.afterReturn, Snapshot.withProbe, Snapshot.probe, he]
+
+/-- Genuine path on the table from read dispatch to record emission. -/
+theorem read_run (T : Template p r k) (s : Snapshot w p r k) (dst addr : Fin r) (next : Fin p)
+ (v : Word w) (tail : List Bool) (hs : s.choices = wordBits v ++ tail) :
+ StackRuns (table T) (s.value.length+s.tag.length+s.address.length+30*w+13)
+ (atLabel T (.read dst addr next)) s.bank (atLabel T (.emit next)) (s.afterRead dst addr next v tail).bank := by
+ let out := s.afterRead dst addr next v tail
+ have hr := ProbeStages.read_run dst addr (Label.emit (r := r) next) .reject s.probe s.cfg.persistent
+ (s.cfg.reg addr) v tail rfl rfl hs
+ rw [← read_probe s dst addr next v tail] at hr
+ have ht : s.probe.value.length+s.probe.tag.length+s.probe.address.length+(s.probe.isa (.reg dst)).length+29*w+13 =
+ s.value.length+s.tag.length+s.address.length+30*w+13 := by
+ change _ + (wordBits (s.cfg.reg dst)).length + 29*w + 13 = _
+ rw [length_wordBits]
+ dsimp only [Snapshot.probe]
+ omega
+ rw [ht] at hr
+ exact ProcessorFlow.run (blocks := blocks T) (l := .read dst addr next)
+ (Fragment.runs_framed probePorts_injective hr s.probe_at out.probe_at (probe_frame s _ _ _ _ _ _))
+
+/-- Short read guesses reach the literal rejecting table row. -/
+theorem read_short (T : Template p r k) (s : Snapshot w p r k) (dst addr : Fin r) (next : Fin p)
+ (hs : s.choices.length < w) :
+ RejectRun (table T) (s.value.length+4*s.choices.length+3) (atLabel T (.read dst addr next)) s.bank := by
+ obtain ⟨out,hr⟩ := ProbeStages.read_short dst addr (Label.emit (r := r) next) .reject
+ s.probe (s.cfg.reg addr) rfl hs
+ have hp := Fragment.runs_onPorts probePorts probePorts_injective s.bank hr
+ rw [installStacks_eq probePorts_injective s.bank s.probe.stacks s.probe_at] at hp
+ exact ⟨atLabel T .reject, _, ProcessorFlow.run (blocks := blocks T) (l := .read dst addr next) hp, rfl⟩
+
+theorem write_run (T : Template p r k) (s : Snapshot w p r k) (addr src : Fin r) (next : Fin p) :
+ StackRuns (table T) (s.tag.length+s.address.length+s.value.length+21*w+9)
+ (atLabel T (.write addr src next)) s.bank (atLabel T (.emit next)) (s.afterWrite addr src next).bank := by
+ let out := s.afterWrite addr src next
+ have hr := Fragment.returning_runs (ProbeStages.writePayload_run addr src s.probe s.cfg.persistent
+ (s.cfg.reg addr) (s.cfg.reg src) rfl rfl rfl) (Label.emit (r := r) next)
+ exact ProcessorFlow.run (blocks := blocks T) (l := .write addr src next)
+ (Fragment.runs_framed probePorts_injective hr s.probe_at out.probe_at (probe_frame s _ _ _ _ _ _))
+
+theorem returnState_run (T : Template p r k) (s : Snapshot w p r k) (src : Fin r) :
+ StackRuns (table T) (8*w+6) (atLabel T (.callback (.returnState src))) s.bank
+ (atLabel T .iteration) (s.afterReturn src).bank := by
+ let out := s.afterReturn src
+ have hr := Fragment.returning_runs (ProbeStages.returnState_run src s.probe s.cfg.persistent
+ (s.cfg.reg src) rfl rfl) (Label.iteration (p := p) (r := r))
+ rw [← return_probe s src] at hr
+ exact ProcessorFlow.run (blocks := blocks T) (l := .callback (.returnState src))
+ (Fragment.runs_framed probePorts_injective hr s.probe_at out.probe_at (probe_frame s _ _ _ _ _ _))
+
+theorem accept_run (T : Template p r k) (s : Snapshot w p r k) :
+ StackRuns (table T) 3 (atLabel T (.callback .accept)) s.bank
+ (atLabel T .iteration) s.afterAccept.bank := by
+ have hr := Fragment.returning_runs (ProbeStages.accept_run s.probe) (Label.iteration (p := p) (r := r))
+ exact ProcessorFlow.run (blocks := blocks T) (l := .callback .accept)
+ (Fragment.runs_framed probePorts_injective hr s.probe_at s.afterAccept.probe_at (probe_frame s _ _ _ _ _ _))
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorGraphProbeEmit.lean b/lean/OAI/Computability/VPVNP/RAMProcessorGraphProbeEmit.lean
new file mode 100644
index 0000000000..0957821b38
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorGraphProbeEmit.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.RAMProcessorGraphRuns
+
+/-!
+# Emitting and closing the physical site record buffer
+
+The linked emission routine pops one vacant slot and copies the five staged words
+into the reversed buffer. Closing fills each vacant slot with zero words and reverses
+the bits onto the output stack for the site's sorting circuit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM BurstRAM.PrivateRAM RAMSerialization
+
+variable {w p r k H : ℕ}
+
+private def Snapshot.setBuffer (s : Snapshot w p r k) (left reverseBuffer output : List Bool) :=
+ {s with remaining := left, reverseBuffer := reverseBuffer, output := output}
+
+private theorem Snapshot.buffer_frame (s : Snapshot w p r k) (left buf out : List Bool)
+ (j : Port r k) (hj : ∀ i, recordPorts i ≠ j) :
+ (s.setBuffer left buf out).bank j = s.bank j := by
+ cases j with
+ | record i =>
+ cases i with
+ | remaining => exact (hj .remaining rfl).elim
+ | reverseBuffer => exact (hj .reverseBuffer rfl).elim
+ | output => exact (hj .output rfl).elim
+ | field i => rfl
+ | temp | zeros => rfl
+ | test i => cases i with | word f => cases f <;> rfl | _ => rfl
+ | _ => rfl
+
+private theorem record_routine (T : Template p r k) (s : Snapshot w p r k)
+ {rt : FiniteRoutine RecordBuffer.Port} {l next : Label p r}
+ (link : blocks T l = (Fragment.returning rt next).onPorts recordPorts)
+ {t left buf out} (h : rt.Runs t s.records (s.setBuffer left buf out).records) :
+ StackRuns (table T) t (atLabel T l) s.bank (atLabel T next) (s.setBuffer left buf out).bank := by
+ apply ProcessorFlow.run (blocks := blocks T)
+ rw [link]
+ exact Fragment.runs_framed recordPorts_injective (Fragment.returning_runs h next)
+ s.record_at (s.setBuffer left buf out).record_at (s.buffer_frame left buf out)
+
+/-- A single slot holds the reversed serialization of the actual staged record. -/
+def Snapshot.afterEmit (s : Snapshot w p r k) (hw : 2 ≤ w) (record : WordRecord w) :=
+ s.setBuffer s.remaining.tail
+ ((List.ofFn ((recordFormat hw).encode (some record))).reverse ++ s.reverseBuffer) s.output
+
+/-- Emit a staged initialization or probe record at its linked occurrence. -/
+theorem record_emit_run (T : Template p r k) (s : Snapshot w p r k) (hw : 2 ≤ w)
+ {l next : Label p r}
+ (link : blocks T l = (Fragment.returning RecordBuffer.appendRecord next).onPorts recordPorts)
+ {records : List (WordRecord w)} (hbuf : RecordBuffer.Holds hw H records s.records)
+ (hfree : records.length < 4*H) (record : WordRecord w)
+ (hf : ∀ j, s.records (.field j) = BurstRAM.wordBits ((recordFormat hw).words (some record) j)) :
+ StackRuns (table T) (25*w+12) (atLabel T l) s.bank (atLabel T next) (s.afterEmit hw record).bank ∧
+ RecordBuffer.Holds hw H (records ++ [record]) (s.afterEmit hw record).records := by
+ obtain ⟨hr,hh⟩ := hbuf.emit hfree record hf
+ have hremaining : s.remaining = true :: List.replicate (4*H-(records.length+1)) true := by
+ change s.records .remaining = _
+ rw [hbuf.remaining, show 4*H-records.length = (4*H-(records.length+1))+1 by omega, List.replicate_succ]
+ have he : (s.afterEmit hw record).records =
+ RecordBuffer.emitted s.records (List.replicate (4*H-(records.length+1)) true)
+ (List.ofFn ((recordFormat hw).encode (some record))) := by
+ funext j
+ cases j with
+ | remaining => exact congrArg List.tail hremaining
+ | _ => rfl
+ rw [← he] at hr hh
+ exact ⟨record_routine T s link hr, hh⟩
+
+/-- A probe reaches its ordinal increment after exactly the five word copies. -/
+theorem emit_run (T : Template p r k) (s : Snapshot w p r k) (hw : 2 ≤ w) (next : Fin p)
+ {records : List (WordRecord w)} (hbuf : RecordBuffer.Holds hw H records s.records)
+ (hfree : records.length < 4*H) (record : WordRecord w)
+ (hf : ∀ j, s.records (.field j) = BurstRAM.wordBits ((recordFormat hw).words (some record) j)) :
+ StackRuns (table T) (25*w+12) (atLabel T (.emit next)) s.bank (atLabel T (.increment next))
+ (s.afterEmit hw record).bank ∧
+ RecordBuffer.Holds hw H (records ++ [record]) (s.afterEmit hw record).records :=
+ record_emit_run T s hw rfl hbuf hfree record hf
+
+/-- The actual pop reaches a rejecting row in one step when the slot stack is empty
+or when its top is a false mark. -/
+theorem record_emit_reject (T : Template p r k) (s : Snapshot w p r k) {l next : Label p r}
+ (link : blocks T l = (Fragment.returning RecordBuffer.appendRecord next).onPorts recordPorts)
+ (hbad : s.remaining.head? ≠ some true) :
+ RejectRun (table T) 1 (atLabel T l) s.bank := by
+ let rt := RecordBuffer.appendRecord
+ have hs : StackStep rt.body.standalone (some rt.body.entry) s.records _ _ :=
+ StackStep.pop (k := RecordBuffer.Port.remaining) rfl
+ change (s.records .remaining).head? ≠ some true at hbad
+ cases he : (s.records .remaining).head? with
+ | none =>
+ rw [he] at hs
+ exact ProcessorFlow.routine_reject (blocks := blocks T) recordPorts_injective link
+ (StackRuns.cons hs (.nil _ _)) rfl s.record_at
+ | some b =>
+ cases b with
+ | false =>
+ rw [he] at hs
+ exact ProcessorFlow.routine_reject (blocks := blocks T) recordPorts_injective link
+ (StackRuns.cons hs (.nil _ _)) rfl s.record_at
+ | true => exact (hbad he).elim
+
+/-- After the close routine, the padded record array is serialized on the output stack. -/
+def Snapshot.afterClose (s : Snapshot w p r k) (hw : 2 ≤ w) (H : ℕ) (records : List (WordRecord w)) :=
+ s.setBuffer [] [] (List.ofFn ((blockFormat H hw).encode (RecordBuffer.slots H records)))
+
+/-- The site reaches its accepting row with the canonical serialized, padded record block. -/
+theorem close_run (T : Template p r k) (s : Snapshot w p r k) (hw : 2 ≤ w)
+ {records : List (WordRecord w)} (hbuf : RecordBuffer.Holds hw H records s.records) :
+ StackRuns (table T) ((4*H-records.length)*(25*w+12)+1+(2*(4*H*5*w)+1)) (atLabel T .close) s.bank
+ (atLabel T .done) (s.afterClose hw H records).bank := by
+ have hr := hbuf.close
+ apply record_routine T s (rt := RecordBuffer.close) rfl
+ convert hr using 2
+ funext j
+ cases j <;> rfl
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorGraphRuns.lean b/lean/OAI/Computability/VPVNP/RAMProcessorGraphRuns.lean
new file mode 100644
index 0000000000..20e14d9398
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorGraphRuns.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.RAMProcessorGraph
+
+/-!
+# Runs to graph exits and to literal rejecting rows
+
+Some budget and format checks reject inside a routine. A rejection witness
+retains the exact stopping control and proves its physical row halts false.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+variable {K L Q J : Type}
+
+/-- A deterministic run ending on a rejecting stack instruction. -/
+abbrev RejectRun [DecidableEq K] (code : StackCode K Q) (n : ℕ) (q : Q) (s : Stacks K) :=
+ ∃ z u, StackRuns code n q s z u ∧ code z = .halt false
+
+theorem StackRuns.thenReject [DecidableEq K] {code : StackCode K Q} {m n q s q' u}
+ (h : StackRuns code m q s q' u) (hr : RejectRun code n q' u) :
+ RejectRun code (m+n) q s := by
+ obtain ⟨z, v, run, halt⟩ := hr
+ exact ⟨z, v, h.trans run, halt⟩
+
+theorem Fragment.runs_framed [DecidableEq K] [DecidableEq J] {f : Fragment K L} {ports : K → J}
+ (hi : Function.Injective ports) {t st x l y u} (h : f.Runs t x l y)
+ (hin : ∀ k, st (ports k) = x k) (hout : ∀ k, u (ports k) = y k)
+ (frame : ∀ j, (∀ k, ports k ≠ j) → u j = st j) :
+ (f.onPorts ports).Runs t st l u := by
+ have hr := f.runs_onPorts ports hi st h
+ rwa [installStacks_eq hi st x hin, installStacks_frame hi hout frame] at hr
+
+namespace Fragment
+
+/-- A fragment run that reaches an internal rejecting halt. -/
+abbrev Rejects [DecidableEq K] (f : Fragment K L) (n : ℕ) (s : Stacks K) :=
+ ∃ q u, StackRuns f.isolated n (.inl f.entry) s (.inl q) u ∧ f.code q = .halt false
+
+theorem returning_reject [DecidableEq K] {r : FiniteRoutine K} {next : L}
+ {t q s u} (h : StackRuns r.body.standalone t (some r.body.entry) s (some q) u)
+ (bad : r.body.code q = .halt false) : (returning r next).Rejects t s := by
+ let labels : Option r.State → (returning r next).State ⊕ L :=
+ fun q => q.elim (.inr next) Sum.inl
+ have hrow (q : Option r.State) (hc : (r.body.standalone q).returns = false) :
+ (returning r next).isolated (labels q) = (r.body.standalone q).rename id labels := by
+ cases q with | none => contradiction | some _ => rfl
+ have run := h.lift id Function.injective_id labels s hrow
+ have same (a : Stacks K) : installStacks id s a = a := by
+ funext j; exact installStacks_at Function.injective_id s a j
+ rw [same, same] at run
+ exact ⟨q, u, run, by simp [returning, bad]⟩
+
+theorem reject_onPorts [DecidableEq K] [DecidableEq J] {f : Fragment K L} {ports : K → J}
+ (hi : Function.Injective ports) {t x st} (h : f.Rejects t x)
+ (hin : ∀ i, st (ports i) = x i) : (f.onPorts ports).Rejects t st := by
+ obtain ⟨q, u, run, bad⟩ := h
+ have hr := run.lift ports hi id st (target := (f.onPorts ports).isolated) (by
+ intro q hc; cases q with | inl _ => rfl | inr _ => contradiction)
+ rw [installStacks_eq hi st _ hin] at hr
+ exact ⟨q, _, hr, by simp [onPorts, bad]⟩
+
+end Fragment
+
+namespace ProcessorFlow
+
+theorem reject [DecidableEq K] {blocks : L → Fragment K L} {l t s}
+ (h : (blocks l).Rejects t s) : RejectRun (program blocks) t (enter blocks l) s := by
+ obtain ⟨q, u, run, bad⟩ := h
+ have hr := run.lift id Function.injective_id (next blocks l) s (target := program blocks) (by
+ intro q hc; cases q with | inl _ => rfl | inr _ => contradiction)
+ have same (a : Stacks K) : installStacks id s a = a := by
+ funext j; exact installStacks_at Function.injective_id s a j
+ rw [same, same] at hr
+ exact ⟨⟨l,q⟩, u, hr, by simp [program, bad]⟩
+
+theorem routine_reject [DecidableEq K] [DecidableEq J] {blocks : L → Fragment J L}
+ {r : FiniteRoutine K} {l next : L} {ports : K → J} (hi : Function.Injective ports)
+ (link : blocks l = (Fragment.returning r next).onPorts ports)
+ {t q s u st} (h : StackRuns r.body.standalone t (some r.body.entry) s (some q) u)
+ (bad : r.body.code q = .halt false) (hin : ∀ i, st (ports i) = s i) :
+ RejectRun (program blocks) t (enter blocks l) st := by
+ apply reject
+ rw [link]
+ exact Fragment.reject_onPorts hi (Fragment.returning_reject h bad) hin
+
+end ProcessorFlow
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorGraphStart.lean b/lean/OAI/Computability/VPVNP/RAMProcessorGraphStart.lean
new file mode 100644
index 0000000000..91f0c83df0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorGraphStart.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.RAMProcessorGraphCredit
+
+/-!
+# Beginning a charged call in the site graph
+
+The first call initializes the global allowance by subtraction. Every call
+restores its own allowances, snapshots the start cost, and pays its startup
+unit. Its private register bank and memory log are then reset before fetching
+the first opcode of the fixed program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM
+
+variable {w p r k : ℕ}
+
+/-- Reset the call allowance, save the starting cost and charge for the new call. -/
+def Snapshot.afterStart (s : Snapshot w p r k) (g : Word w) (hc : s.cost.val+1 < 2^w) :=
+ s.setCredit s.publicFuel (s.publicH-1) (s.siteLeft-1) (Charges.prevWord g) ⟨s.cost.val+1,hc⟩
+ (wordBits s.cost) (wordBits (0 : Word w))
+
+/-- Instruction count of the call-start credit and reset routine. -/
+def Snapshot.startTicks (s : Snapshot w p r k) :=
+ CallCredit.resetTicks w s.publicH s.publicFuel s.fuel s.callLeft s.savedStart s.ordinal + (8*w+6)
+
+theorem newCall_run (T : Template p r k) (s : Snapshot w p r k)
+ (hH : 0 < s.publicH) (hs : 0 < s.siteLeft) (hg : 0 < s.globalLeft.val) (hc : s.cost.val+1 < 2^w) :
+ StackRuns (table T) s.startTicks (atLabel T .newCall) s.bank (atLabel T .fresh)
+ (s.afterStart s.globalLeft hc).bank := by
+ apply credit_routine T s (rt := CallCredit.startCall) rfl
+ exact CallCredit.startCall_run s.publicH s.publicFuel s.fuel s.callLeft s.siteLeft s.cap s.globalLeft s.cost s.savedStart s.ordinal hH hs hg hc
+
+theorem newCall_reject (T : Template p r k) (s : Snapshot w p r k)
+ (bad : s.publicH = 0 ∨ s.siteLeft = 0 ∨ s.globalLeft.val = 0 ∨ 2^w ≤ s.cost.val+1) :
+ RejectRun (table T) (CallCredit.resetTicks w s.publicH s.publicFuel s.fuel s.callLeft s.savedStart s.ordinal +
+ Charges.failureTicks s.publicH s.siteLeft s.globalLeft) (atLabel T .newCall) s.bank := by
+ obtain ⟨_, run⟩ := CallCredit.startCall_reject s.publicH s.publicFuel s.fuel s.callLeft s.siteLeft
+ s.cap s.globalLeft s.cost s.savedStart s.ordinal bad
+ exact ProcessorFlow.routine_reject (blocks := blocks T) (l := .newCall) (next := .fresh)
+ (fun _ _ h => Port.credit.inj h) (r := CallCredit.startCall) rfl run CallCredit.startCall_halt (fun _ => rfl)
+
+theorem first_run (T : Template p r k) (s : Snapshot w p r k)
+ (hH : 0 < s.publicH) (hs : 0 < s.siteLeft) (hlt : s.cost.val < s.cap.val) :
+ StackRuns (table T) (16*w+7+s.startTicks) (atLabel T .first) s.bank (atLabel T .fresh)
+ (s.afterStart (s.cap-s.cost) ((Nat.succ_le_of_lt hlt).trans_lt s.cap.isLt)).bank := by
+ apply credit_routine T s (rt := CallCredit.firstCall) rfl
+ exact CallCredit.firstCall_run s.publicH s.publicFuel s.fuel s.callLeft s.siteLeft s.cap s.globalLeft s.cost s.savedStart s.ordinal hH hs hlt
+
+/-- Initialize private registers and the write log at the template's entry. -/
+def Snapshot.afterFresh (s : Snapshot w p r k) (T : Template p r k) : Snapshot w p r k :=
+ {s with cfg := ⟨T.entry, s.cfg.persistent, fun _ => 0, []⟩}
+
+theorem fresh_run (T : Template p r k) (s : Snapshot w p r k) :
+ ∃ t ≤ r*(8*w+3)+3*(s.cfg.writes.length*(w+1)+1)+2,
+ StackRuns (table T) t (atLabel T .fresh) s.bank (atLabel T (.segment T.entry)) (s.afterFresh T).bank := by
+ obtain ⟨t, ht, hr⟩ := ISA.freshCall_run s.pub s.cfg.persistent (fun i => wordBits (s.cfg.reg i))
+ s.cfg.writes (by simp)
+ refine ⟨t, ht, ProcessorFlow.run (blocks := blocks T) (l := .fresh) ?_⟩
+ change ((Fragment.returning (ISA.freshCall (r := r) (k := k)) (Label.segment T.entry : Label p r)).onPorts Port.isa).Runs t s.bank _ (s.afterFresh T).bank
+ apply Fragment.runs_framed (ports := Port.isa) (fun _ _ h => Port.isa.inj h)
+ (Fragment.returning_runs hr (Label.segment T.entry : Label p r))
+ · intro i
+ cases i <;> rfl
+ · intro i
+ cases i <;> rfl
+ · intro j hj
+ cases j with
+ | isa i => exact (hj i rfl).elim
+ | test i => cases i with | word f => cases f <;> rfl | _ => rfl
+ | record i => cases i <;> rfl
+ | _ => rfl
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorGraphTerminal.lean b/lean/OAI/Computability/VPVNP/RAMProcessorGraphTerminal.lean
new file mode 100644
index 0000000000..a7b23edb07
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorGraphTerminal.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.RAMProcessorPrelude
+import OAI.Computability.VPVNP.StructuredStackTotal
+import OAI.Computability.VPVNP.StructuredStackCount
+
+/-!
+# Rejecting halts in the compiled site processor
+
+A failed format, credit, or consistency check can halt inside an embedded routine.
+Its literal rejecting row survives compilation of the graph and attachment of the
+site prelude. Its path contributes zero and stops within one tick of reaching that row,
+for every continuation of the enclosing program.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+variable {K Q J : Type} [DecidableEq K]
+
+/-- A literal rejecting halt in the routine's own control space. The endpoint
+has a named instruction so that it still halts when the routine is linked. -/
+def Routine.Rejects (rt : Routine K Q) (t : ℕ) (s : Stacks K) : Prop :=
+ ∃ q u, StackRuns rt.standalone t (some rt.entry) s (some q) u ∧ rt.code q = .halt false
+
+/-- A deterministic path into a rejecting row stops, independently of every
+normal-return continuation. -/
+theorem Routine.Rejects.verdict {rt : Routine K Q} {n : ℕ} {s : Stacks K}
+ (h : rt.Rejects n s) (c : ℕ → Stacks K → ℕ) (d : ℕ → Stacks K → Prop) (fuel : ℕ) :
+ rt.count c (fuel+n+1) s = 0 ∧ rt.AllStops d (fuel+n+1) s := by
+ obtain ⟨z,u,hr,bad⟩ := h
+ have walk {n q s j u} (run : StackRuns rt.standalone n q s j u) :
+ ∀ z, j = some z → rt.code z = .halt false →
+ rt.countFrom c (fuel+n+1) q s = 0 ∧ rt.AllStopsFrom d (fuel+n+1) q s := by
+ induction run with
+ | nil =>
+ rintro z rfl hb
+ simp [countFrom, AllStopsFrom, hb]
+ | @cons q s _ _ _ _ n step _ ih =>
+ intro z hz hb
+ have tail := ih z hz hb
+ cases q with
+ | none => cases step <;> contradiction
+ | some q =>
+ rw [show fuel+(n+1)+1=(fuel+n+1)+1 by omega]
+ cases step with
+ | push he | pop he | goto he =>
+ change rt.code q = _ at he
+ simpa only [countFrom, AllStopsFrom, he] using tail
+ exact walk hr z rfl bad
+
+/-- A normal first return enters a second routine's literal rejecting row. -/
+theorem Routine.Runs.then_reject {a : Routine K Q} {b : Routine K J} {t n : ℕ}
+ {s mid : Stacks K} (ha : a.Runs t s mid) (hb : b.Rejects n mid) :
+ (a.followedBy b).Rejects (t+n) s := by
+ obtain ⟨z,u,hr,bad⟩ := hb
+ let outer := a.followedBy b
+ let labels (q : Option J) : Option (Q ⊕ J) := q.elim none (some ∘ Sum.inr)
+ have hc (q : Option J) (h : (b.standalone q).returns = false) :
+ outer.standalone (labels q) = (b.standalone q).rename id labels := by
+ cases q with | none => contradiction | some q => rfl
+ have htail := hr.lift id Function.injective_id labels s hc
+ have same (x : Stacks K) : installStacks id s x = x := by
+ funext i; exact installStacks_at Function.injective_id s x i
+ rw [same, same] at htail
+ refine ⟨.inr z, u, (ha.link outer Sum.inl (some (.inr b.entry)) (fun _ ↦ rfl)).trans htail, ?_⟩
+ simp [Routine.followedBy, Routine.install, bad, StackOp.rename]
+
+/-- The normal labels of the input code must be accepting halts. This makes
+every literal rejecting row of the source an interior row of the compiled routine. -/
+theorem FiniteRoutine.reject_ofStackCode [Fintype Q] {src : StackCode K Q} {normal : Q → Bool}
+ {entry : Q} (he : normal entry = false) (haccept : ∀ q, normal q = true → src q = .halt true)
+ {n : ℕ} {s : Stacks K} (h : RejectRun src n entry s) :
+ (ofStackCode src id entry normal).body.Rejects n s := by
+ obtain ⟨z,u,hr,bad⟩ := h
+ let rt := (ofStackCode src id entry normal).body
+ let labels (q : Q) := if normal q then none else some q
+ have hc (q : Q) (h : (src q).returns = false) :
+ rt.standalone (labels q) = (src q).rename id labels := by
+ have hn : normal q = false := by
+ cases hx : normal q with
+ | false => rfl
+ | true => rw [haccept q hx] at h; contradiction
+ simp [rt, ofStackCode, ofRoutine, Routine.standalone, Routine.close, labels, hn]
+ have hrun := hr.lift id Function.injective_id labels s hc
+ have same (x : Stacks K) : installStacks id s x = x := by
+ funext i; exact installStacks_at Function.injective_id s x i
+ have hz : normal z = false := by
+ cases hx : normal z with
+ | false => rfl
+ | true => have hh := haccept z hx; rw [bad] at hh; cases hh
+ rw [same, same] at hrun
+ refine ⟨z,u,?_,?_⟩
+ · change StackRuns rt.standalone n (some entry) s (some z) u
+ simp only [labels, he, hz, Bool.false_eq_true, ↓reduceIte] at hrun
+ exact hrun
+ · simp [ofStackCode, ofRoutine, hz, bad, StackOp.rename]
+
+namespace SiteProcessor
+
+open BurstRAM PrivateRAM
+
+variable {p r k : ℕ}
+
+/-- The named rejected row of the complete burst graph is also a rejecting
+row in the corresponding finite routine. -/
+theorem graphRoutine_reject (T : Template p r k) {n : ℕ} {s : Stacks (Port r k)}
+ (h : RejectRun (table T) n (atLabel T .initialRecord) s) :
+ (graphRoutine T).body.Rejects n s :=
+ FiniteRoutine.reject_ofStackCode (normal := graphDone) rfl (graphDone_row T) h
+
+/-- Include the boot steps that allocate and stage the physical record fields. -/
+theorem callSite_reject (T : Template p r k) {m n : ℕ} {bare start : Stacks (Port r k)}
+ (booted : boot.Runs m bare start) (h : RejectRun (table T) n (atLabel T .initialRecord) start) :
+ (callSite T).body.Rejects (m+n) bare :=
+ booted.then_reject (graphRoutine_reject T h)
+
+/-- A failed call-site run has count zero under every continuation and a uniform
+stopping bound, including the final instruction that observes the rejecting halt. -/
+theorem callSite_reject_verdict (T : Template p r k) {m n : ℕ} {bare start : Stacks (Port r k)}
+ (booted : boot.Runs m bare start) (h : RejectRun (table T) n (atLabel T .initialRecord) start)
+ (c : ℕ → Stacks (Port r k) → ℕ) (d : ℕ → Stacks (Port r k) → Prop) (extra : ℕ) :
+ (callSite T).body.count c (extra+(m+n)+1) bare = 0 ∧
+ (callSite T).body.AllStops d (extra+(m+n)+1) bare :=
+ (callSite_reject T booted h).verdict c d extra
+
+end SiteProcessor
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorGuardedPayload.lean b/lean/OAI/Computability/VPVNP/RAMProcessorGuardedPayload.lean
new file mode 100644
index 0000000000..adeb24dd5e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorGuardedPayload.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.RAMProcessorFlow
+
+/-!
+# A deterministic payload after a two-exit processor fragment
+
+A successful test enters the payload without an extra transition. Rejection
+jumps directly to its caller label, leaving the rejected branch's stack state
+available to the caller.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Fragment
+
+variable {K L : Type}
+
+private def guardedLabel (guard : Fragment K Bool) (payload : FiniteRoutine K) (bad : L) :
+ guard.State ⊕ Bool → (guard.State ⊕ payload.State) ⊕ L
+ | .inl q => .inl (.inl q)
+ | .inr true => .inl (.inr payload.body.entry)
+ | .inr false => .inr bad
+
+private def payloadLabel (guard : Fragment K Bool) (payload : FiniteRoutine K) (good : L) :
+ Option payload.State → (guard.State ⊕ payload.State) ⊕ L :=
+ fun r => r.elim (.inr good) (Sum.inl ∘ Sum.inr)
+
+/-- Link a Boolean guard to a returning payload. Success enters the payload and a failed guard
+transfers directly to the rejection label. -/
+def withPayload (guard : Fragment K Bool) (payload : FiniteRoutine K) (good bad : L) : Fragment K L where
+ State := guard.State ⊕ payload.State
+ entry := .inl guard.entry
+ code
+ | .inl q => (guard.code q).rename id (guardedLabel guard payload bad)
+ | .inr q => (payload.body.code q).rename id (payloadLabel guard payload good)
+
+variable [DecidableEq K]
+
+private theorem guard_run {guard : Fragment K Bool} (payload : FiniteRoutine K) (good bad : L)
+ {t s b u} (h : guard.Runs t s b u) :
+ StackRuns (guard.withPayload payload good bad).isolated t
+ (.inl (guard.withPayload payload good bad).entry) s (guardedLabel guard payload bad (.inr b)) u := by
+ have hh (q : guard.State ⊕ Bool) (hn : (guard.isolated q).returns = false) :
+ (guard.withPayload payload good bad).isolated (guardedLabel guard payload bad q) =
+ (guard.isolated q).rename id (guardedLabel guard payload bad) := by
+ cases q with
+ | inl => rfl
+ | inr => contradiction
+ have run := h.lift id Function.injective_id (guardedLabel guard payload bad) s hh
+ have same (v : Stacks K) : installStacks id s v = v := by
+ funext j; exact installStacks_at Function.injective_id s v j
+ rw [same, same] at run
+ exact run
+
+theorem withPayload_reject {guard : Fragment K Bool} (payload : FiniteRoutine K) (good bad : L)
+ {t s u} (h : guard.Runs t s false u) :
+ (guard.withPayload payload good bad).Runs t s bad u := guard_run payload good bad h
+
+theorem withPayload_ok {guard : Fragment K Bool} {payload : FiniteRoutine K} (good bad : L)
+ {t m s mid u} (test : guard.Runs t s true mid) (h : payload.Runs m mid u) :
+ (guard.withPayload payload good bad).Runs (t+m) s good u := by
+ have hh (q : Option payload.State) (hn : (payload.body.standalone q).returns = false) :
+ (guard.withPayload payload good bad).isolated (payloadLabel guard payload good q) =
+ (payload.body.standalone q).rename id (payloadLabel guard payload good) := by
+ cases q with
+ | none => contradiction
+ | some => rfl
+ have run := h.lift id Function.injective_id (payloadLabel guard payload good) mid hh
+ have same (v : Stacks K) : installStacks id mid v = v := by
+ funext j; exact installStacks_at Function.injective_id mid v j
+ rw [same, same] at run
+ exact (guard_run payload good bad test).trans run
+
+end RAMTape.Fragment
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorInitFields.lean b/lean/OAI/Computability/VPVNP/RAMProcessorInitFields.lean
new file mode 100644
index 0000000000..5ecc3efafd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorInitFields.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.RAMTapeRecordBuffer
+import OAI.Computability.VPVNP.RAMTapeWordOperands
+import OAI.Computability.VPVNP.RAMTapeUnaryWordValue
+
+/-!
+# Staging the site's prescribed initialization record
+
+The input preparer supplies the site address and packed header word in fields
+one and two. The fixed staging routine sets the initialization tag, copies the
+site address to the start-cost field, and copies the zero word to the ordinal.
+It restores all inputs and its two scratch stacks before record emission.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.RecordBuffer
+
+open BurstRAM TapeWord
+
+/-- The initialization record fields supplied by the staging routine, namely its tag, start
+cost and ordinal. -/
+inductive InitField | tag | start | ordinal
+
+private def source : InitField → Port
+ | .tag | .start => .field 1
+ | .ordinal => .zeros
+
+private def dest : InitField → Port
+ | .tag => .field 0
+ | .start => .field 3
+ | .ordinal => .field 4
+
+private def copyPorts (f : InitField) : ScanPort → Port
+ | .left => source f
+ | .right => .temp
+ | .tmp => .output
+ | .out => dest f
+
+private theorem copy_inj (f : InitField) : Function.Injective (copyPorts f) := by
+ intro i j h
+ cases f <;> cases i <;> cases j <;> simp_all [copyPorts, source, dest]
+
+private def normal {A : Type} : Operand.State A → Bool
+ | .done _ => true
+ | _ => false
+
+private def fill {A : Type} [Fintype A] (f : InitField) (bit : A → Bool → Bool × A)
+ (start : A) : FiniteRoutine Port :=
+ .ofStackCode (Operand.code bit) (copyPorts f) (.clear start) normal
+
+private theorem fill_run {A : Type} [Fintype A] (f : InitField) (bit : A → Bool → Bool × A)
+ (start finish : A) (s : Stacks Port) (v : List Bool) {t : ℕ}
+ (h : StackRuns (Operand.code bit) t (.clear start) (scanStacks (s (source f)) [] [] (s (dest f)))
+ (.done finish) (scanStacks (s (source f)) [] [] v)) (ht : s .temp = []) (ho : s .output = []) :
+ (fill f bit start).Runs t s (Function.update s (dest f) v) := by
+ apply FiniteRoutine.runs_ofStackCode_framed (copy_inj f) (normal := normal) rfl (exit := .done finish) rfl
+ (fun q hn => by cases q <;> first | rfl | contradiction) h
+ · intro i; cases i <;> first | rfl | exact ht | exact ho
+ · intro i
+ cases f <;> cases i <;> simp_all [copyPorts, source, dest, scanStacks]
+ · intro j hj
+ exact Function.update_of_ne (Ne.symm (hj .out)) ..
+
+/-- Stage the initialization tag, copy the site address into the start-cost field and fill the
+ordinal field with zero. -/
+def initFields : FiniteRoutine Port :=
+ ((fill .tag (Operand.literalBit 1) (Fin.last 1)).followedBy
+ (fill .start Operand.copyBit ())).followedBy (fill .ordinal Operand.copyBit ())
+
+/-- Record-buffer contents after setting the initialization tag, the start cost equal to the
+address, and the probe ordinal to zero. -/
+def initialized {w : ℕ} (s : Stacks Port) (address : Word w) : Stacks Port :=
+ Function.update (Function.update (Function.update s (.field 0) (wordBits (Fin.ofNat (2^w) 1)))
+ (.field 3) (wordBits address)) (.field 4) (wordBits (0 : Word w))
+
+theorem initFields_run {w : ℕ} (s : Stacks Port) (a : Word w)
+ (ha : s (.field 1) = wordBits a) (hz : s .zeros = wordBits (0 : Word w))
+ (ht : s .temp = []) (ho : s .output = []) :
+ initFields.Runs ((s (.field 0)).length+(s (.field 3)).length+(s (.field 4)).length+21*w+9)
+ s (initialized s a) := by
+ let tag := wordBits (Fin.ofNat (2^w) 1 : Word w)
+ let s₁ := Function.update s (.field 0) tag
+ let s₂ := Function.update s₁ (.field 3) (wordBits a)
+ obtain ⟨q, run⟩ := Operand.literal_run 1 a (s (.field 0))
+ have h₁ : (fill .tag (Operand.literalBit 1) (Fin.last 1)).Runs ((s (.field 0)).length+7*w+3) s s₁ := by
+ apply fill_run .tag _ _ q s tag _ ht ho
+ simpa only [source, dest, ha] using run
+ have h₂ : (fill .start Operand.copyBit ()).Runs ((s (.field 3)).length+7*w+3) s₁ s₂ := by
+ apply fill_run .start _ _ () s₁ (wordBits a) _ (by simpa [s₁] using ht) (by simpa [s₁] using ho)
+ simpa [source, dest, s₁, ha] using Operand.copy_run (wordBits a) (s (.field 3))
+ have h₃ : (fill .ordinal Operand.copyBit ()).Runs ((s (.field 4)).length+7*w+3) s₂ (initialized s a) := by
+ apply fill_run .ordinal _ _ () s₂ (wordBits (0 : Word w)) _ (by simpa [s₂, s₁] using ht) (by simpa [s₂, s₁] using ho)
+ simpa [source, dest, s₂, s₁, hz] using Operand.copy_run (wordBits (0 : Word w)) (s (.field 4))
+ convert (h₁.followedBy h₂).followedBy h₃ using 1
+ · rfl
+ omega
+
+end RAMTape.RecordBuffer
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorInitRun.lean b/lean/OAI/Computability/VPVNP/RAMProcessorInitRun.lean
new file mode 100644
index 0000000000..97ab1ddfd5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorInitRun.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.RAMProcessorPrelude
+
+/-!
+# The initialization record of the linked site
+
+The staged words encode the prescribed initialization, including its site
+address in the start-cost position. Every site contributes this record even
+when its incoming status has already halted.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM RAMSerialization
+
+variable {w p r k H : ℕ}
+
+/-- Initialization record installing the site's header word at its address, using that same
+address as its start cost and zero as its ordinal. -/
+def initRecord (addr header : Word w) : WordRecord w := ⟨.init, addr, header, addr, 0⟩
+
+theorem Snapshot.initWords (s : Snapshot w p r k) (hw : 2 ≤ w) (a h : Word w)
+ (ha : s.address = BurstRAM.wordBits a) (hh : s.value = BurstRAM.wordBits h) (i : Fin 5) :
+ (s.withInitFields a).records (.field i) =
+ BurstRAM.wordBits ((recordFormat hw).words (some (initRecord a h)) i) := by
+ fin_cases i
+ · apply congrArg BurstRAM.wordBits
+ apply Fin.ext
+ change 1 % (2^w) = 1
+ exact Nat.mod_eq_of_lt ((by decide : 1 < 2^2).trans_le (Nat.pow_le_pow_right (by decide) hw))
+ · exact ha
+ · exact hh
+ · rfl
+ · rfl
+
+theorem Snapshot.emptyHolds (s : Snapshot w p r k) (hw : 2 ≤ w)
+ (hs : s.remaining = List.replicate (4*H) true) (hb : s.reverseBuffer = []) (ho : s.output = []) :
+ RecordBuffer.Holds hw H [] s.records :=
+ ⟨Nat.zero_le _, rfl, rfl, hs, hb, ho⟩
+
+theorem initialRecord_run (T : PrivateRAM.Template p r k) (s : Snapshot w p r k) (hw : 2 ≤ w)
+ (a h : Word w) (ha : s.address = BurstRAM.wordBits a) (hh : s.value = BurstRAM.wordBits h)
+ (hs : s.remaining = List.replicate (4*H) true) (hb : s.reverseBuffer = []) (ho : s.output = [])
+ (hH : 0 < H) :
+ let staged := s.withInitFields a
+ let after := staged.afterEmit hw (initRecord a h)
+ StackRuns (table T) (25*w+12) (atLabel T .initialRecord) staged.bank (atLabel T .checkEntry) after.bank ∧
+ RecordBuffer.Holds hw H [initRecord a h] after.records := by
+ exact record_emit_run T (s.withInitFields a) hw rfl ((s.withInitFields a).emptyHolds hw hs hb ho)
+ (by simp; omega) (initRecord a h) (s.initWords hw a h ha hh)
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorLocal.lean b/lean/OAI/Computability/VPVNP/RAMProcessorLocal.lean
new file mode 100644
index 0000000000..410ffdc368
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorLocal.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.RAMProcessorFlow
+import OAI.Computability.VPVNP.RAMTapeISADispatch
+import OAI.Computability.VPVNP.RAMProcessorLogged
+
+/-!
+# Fuel-checked private instruction execution between external probes
+
+The controller consumes an instruction credit before fetching the opcode.
+Ordinary continuations jump to the next credit test. A private choice consumes
+one already nominated bit, with a short stream reaching rejection. Read and
+write callbacks return to the site controller for charging and recording.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.LocalProcessor
+
+open BurstRAM PrivateRAM
+
+variable {p r k w : ℕ}
+
+/-- Ports of the private instruction interpreter together with its unary fuel stack and binary
+guess stream. -/
+abbrev Port (r k : ℕ) := ISA.Port r k ⊕ Bool
+
+/-- Stack holding one token per remaining private instruction. -/
+def fuelPort : Port r k := .inr false
+/-- Stack containing the remaining nominated binary choices for private branches. -/
+def choicePort : Port r k := .inr true
+
+/-- Control states for checking fuel at a program counter, executing an ISA instruction and
+yielding its callback. -/
+inductive State (T : Template p r k) where
+ | begin (pc : Fin p)
+ | instr (q : ISA.State T)
+ | exit (cb : ISA.Callback p r)
+ deriving Fintype
+
+/-- Consume one fuel token before dispatch, follow private branches using the choice stack, and
+yield external actions or termination to the site controller. -/
+def code (T : Template p r k) : StackCode (Port r k) (State T)
+ | .begin pc => .pop fuelPort fun x => if x.isSome then .instr (ISA.entry T pc) else .exit .reject
+ | .instr q => match ISA.resume? T q with
+ | none => (ISA.code T q).rename Sum.inl State.instr
+ | some (.next pc) => .goto (.begin pc)
+ | some (.choose yes no) => .pop choicePort fun b => match b with
+ | none => .exit .reject
+ | some b => .begin (if b then yes else no)
+ | some cb => .goto (.exit cb)
+ | .exit _ => .halt true
+
+/-- Build the local interpreter's stack bank from the public words, logged private
+configuration, fuel tally and remaining guess bits. -/
+def store (pub : Fin k → Word w) (c : LogConfig w p r) (fuel : ℕ) (bits : List Bool) : Stacks (Port r k) :=
+ Sum.elim (ISA.configBank pub c) (fun b => if b then bits else List.replicate fuel true)
+
+theorem putFuel (pub : Fin k → Word w) (c : LogConfig w p r) (f f' : ℕ) (bs : List Bool) :
+ Function.update (store pub c f bs) fuelPort (List.replicate f' true) = store pub c f' bs := by
+ funext j
+ rcases j with j | b
+ · simp [fuelPort, store]
+ · cases b <;> simp [fuelPort, store]
+
+theorem putChoices (pub : Fin k → Word w) (c : LogConfig w p r) (f : ℕ) (bs tail : List Bool) :
+ Function.update (store pub c f bs) choicePort tail = store pub c f tail := by
+ funext j
+ rcases j with j | b
+ · simp [choicePort, store]
+ · cases b <;> simp [choicePort, store]
+
+private theorem installed (pub : Fin k → Word w) (old new : LogConfig w p r) (fuel : ℕ) (bs : List Bool) :
+ installStacks Sum.inl (store pub old fuel bs) (ISA.configBank pub new) = store pub new fuel bs := by
+ funext j
+ rcases j with j | b
+ · exact installStacks_at Sum.inl_injective ..
+ · exact installStacks_outside _ _ (by simp)
+
+/-- Callback selected by the current template instruction and its conditional jump test on the
+logged configuration. -/
+def instructionExit (T : Template p r k) (c : LogConfig w p r) :=
+ ISA.exitFor (T.code c.pc) ((ISA.jumpTest (T.code c.pc) c).getD false)
+
+/-- Logged private configuration after the current instruction's register and private-memory
+updates. -/
+def instructionPost (T : Template p r k) (pub : Fin k → Word w) (c : LogConfig w p r) :=
+ ISA.post (T.code c.pc) pub c
+
+theorem fetch (T : Template p r k) (pub : Fin k → Word w) (c : LogConfig w p r) (fuel : ℕ)
+ (bits : List Bool) :
+ ∃ ticks ≤ ISA.prepareBound w c.writes.length+3,
+ StackRuns (code T) ticks (.begin c.pc) (store pub c (fuel+1) bits)
+ (.instr (ISA.callback T (instructionExit T c))) (store pub (instructionPost T pub c) fuel bits) := by
+ obtain ⟨t, ht, run⟩ := ISA.dispatch_step T pub c
+ have lift := run.lift Sum.inl Sum.inl_injective State.instr (store pub c fuel bits)
+ (target := code T) (by intro q h; simp only [code, ISA.resume_none_of_continuing T q h])
+ rw [installed, installed] at lift
+ have first := StackStep.pop (s := store pub c (fuel+1) bits) (code := code T) (q := .begin c.pc)
+ (show code T (.begin c.pc) = .pop fuelPort _ from rfl)
+ change StackStep (code T) (.begin c.pc) (store pub c (fuel+1) bits) (.instr (ISA.entry T c.pc))
+ (Function.update (store pub c (fuel+1) bits) fuelPort (List.replicate fuel true)) at first
+ rw [putFuel] at first
+ exact ⟨_, by omega, .cons first lift⟩
+
+theorem cutoff (T : Template p r k) (pub : Fin k → Word w) (c : LogConfig w p r) (bits : List Bool) :
+ StackRuns (code T) 1 (.begin c.pc) (store pub c 0 bits) (.exit .reject) (store pub c 0 bits) := by
+ have hs := StackStep.pop (s := store pub c 0 bits) (code := code T) (q := .begin c.pc)
+ (show code T (.begin c.pc) = .pop fuelPort _ from rfl)
+ change StackStep (code T) _ _ (.exit .reject) (Function.update _ fuelPort (List.replicate 0 true)) at hs
+ rw [putFuel] at hs
+ exact .cons hs (.nil ..)
+
+theorem next_step (T : Template p r k) (pc : Fin p) (s : Stacks (Port r k)) :
+ StackStep (code T) (.instr (ISA.callback T (.next pc))) s (.begin pc) s :=
+ .goto (by simp [code, ISA.resume_callback])
+
+theorem branch_step (T : Template p r k) (yes no : Fin p) (pub : Fin k → Word w)
+ (c : LogConfig w p r) (f : ℕ) (b : Bool) (tail : List Bool) :
+ StackStep (code T) (.instr (ISA.callback T (.choose yes no))) (store pub c f (b :: tail))
+ (.begin (if b then yes else no)) (store pub c f tail) := by
+ have hs := StackStep.pop (s := store pub c f (b :: tail)) (code := code T)
+ (q := .instr (ISA.callback T (.choose yes no))) (show code T _ = .pop choicePort _ from rfl)
+ change StackStep (code T) _ _ (.begin (if b then yes else no)) (Function.update _ choicePort tail) at hs
+ rwa [putChoices] at hs
+
+theorem short_choice (T : Template p r k) (yes no : Fin p) (pub : Fin k → Word w)
+ (c : LogConfig w p r) (f : ℕ) :
+ StackStep (code T) (.instr (ISA.callback T (.choose yes no))) (store pub c f [])
+ (.exit .reject) (store pub c f []) := by
+ have hs := StackStep.pop (s := store pub c f []) (code := code T)
+ (q := .instr (ISA.callback T (.choose yes no))) (show code T _ = .pop choicePort _ from rfl)
+ change StackStep (code T) _ _ (.exit .reject) (Function.update _ choicePort []) at hs
+ rwa [putChoices] at hs
+
+end RAMTape.LocalProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorLocalResult.lean b/lean/OAI/Computability/VPVNP/RAMProcessorLocalResult.lean
new file mode 100644
index 0000000000..2c553258ab
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorLocalResult.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.RAMProcessorLocalScan
+
+/-!
+# Exact native result at the external-action boundary
+
+A successful private scan returns a callback and the residual state, fuel and
+guess suffix. The caller's permitted probe consumes its charge before looking
+at a read value. Resuming this way and prepending the scan's private events
+gives exactly the native local report, also on over-cap or truncated streams.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.LocalProcessor
+
+open BurstRAM PrivateRAM
+
+variable {w p r k : ℕ}
+
+/-- Optional call report together with the unconsumed suffix of the site's nominated bit
+stream. -/
+abbrev Output (w : ℕ) := Option (Report w × List Bool)
+
+/-- Prepend one event to a successful report while retaining its unused bit suffix and
+propagating failure. -/
+def addEvent (e : Event w) (out : Output w) : Output w :=
+ out.map fun ⟨r, bs⟩ => (r.prepend e, bs)
+
+/-- Prepend a chronological event prefix to a successful local output, preserving its residual
+bits. -/
+def addEvents : List (Event w) → Output w → Output w
+ | [], out => out
+ | e :: es, out => addEvent e (addEvents es out)
+
+/-- Resume exactly one pending external or terminal action. -/
+def resume (P : Program w (LogConfig w p r)) (allowance : ℕ) (y : Yield w p r) : Output w :=
+ match y.exit.action y.cfg with
+ | .finish s => some (⟨[], s⟩, y.bits)
+ | .read a next =>
+ match allowance with
+ | 0 => none
+ | left+1 =>
+ (takeWord w y.bits).bind fun ⟨v, tail⟩ =>
+ addEvent (.read a v) (runLocalCall P y.fuel (next v) left tail).output
+ | .write a v c =>
+ match allowance with
+ | 0 => none
+ | left+1 => addEvent (.write a v) (runLocalCall P y.fuel c left y.bits).output
+ | _ => none
+
+/-- Resume a yielded local call under the remaining probe allowance and attach the private
+events recorded before its callback. -/
+def result (P : Program w (LogConfig w p r)) (allowance : ℕ) (y : Yield w p r) : Output w :=
+ addEvents y.prefixEvents (resume P allowance y)
+
+private theorem result_prepend (P : Program w (LogConfig w p r)) (a : ℕ)
+ (e : Event w) (y : Yield w p r) :
+ result P a (y.prepend e) = addEvent e (result P a y) := rfl
+
+/-- The caller can consume the generated word and communicate a record at
+each callback without losing or multiplying any native successful report. -/
+theorem scan_result (T : Template p r k) (pub : Fin k → Word w) (f : ℕ)
+ (c : LogConfig w p r) (bs : List Bool) (a : ℕ) :
+ let P := (T.instantiate w pub).logProgram
+ result P a (scan T pub f c bs) = (runLocalCall P f c a bs).output := by
+ let P := (T.instantiate w pub).logProgram
+ change result P a _ = (runLocalCall P f c a bs).output
+ induction f generalizing c bs with
+ | zero => rfl
+ | succ f ih =>
+ have hstep : P.step c = (instructionExit T c).action (instructionPost T pub c) :=
+ (ISA.callback_action (T.code c.pc) pub c).symm
+ rw [runLocalCall, hstep, scan]
+ cases instructionExit T c with
+ | next j => rw [result_prepend, ih]; rfl
+ | choose yes no =>
+ cases bs with
+ | nil => rfl
+ | cons b bs => rw [result_prepend, ih]; rfl
+ | read dst addr j =>
+ cases a with
+ | zero => rfl
+ | succ a =>
+ cases hs : takeWord w bs with
+ | none => simp [result, resume, ISA.Callback.action, hs, LocalCallRun.stop, addEvents]
+ | some pair =>
+ obtain ⟨v, tail⟩ := pair
+ simp [result, resume, ISA.Callback.action, hs, LocalCallRun.prepend, addEvents, addEvent]
+ | write addr src j => cases a <;> rfl
+ | returnState _ | accept | reject => rfl
+
+end RAMTape.LocalProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorLocalScan.lean b/lean/OAI/Computability/VPVNP/RAMProcessorLocalScan.lean
new file mode 100644
index 0000000000..dfb4afb11a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorLocalScan.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.RAMProcessorLocal
+
+/-!
+# Complete private execution through the next external action
+
+The bounded scan executes the instruction table repeatedly. It retains the
+exact local event prefix needed to identify the corresponding native report.
+Only an actual read, write, finish or rejection returns control to the caller.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.LocalProcessor
+
+open BurstRAM PrivateRAM
+
+variable {w p r k : ℕ}
+
+/-- Result at the boundary of a private instruction scan, including its callback,
+configuration, remaining fuel and choices, and chronological event prefix. -/
+structure Yield (w p r : ℕ) where
+ /-- Callback reached by the scan. The scan also returns the rejecting callback when it
+ exhausts fuel or a required choice bit. -/
+ exit : ISA.Callback p r
+ /-- Private program counter, registers, persistent state and write log at the scan boundary,
+ before the caller handles the callback. -/
+ cfg : LogConfig w p r
+ /-- Instruction fuel left after the scan. Fetching the instruction that requests an external
+ action consumes one unit. -/
+ fuel : ℕ
+ /-- Unused suffix of the binary choice stream after the private branches in this segment. -/
+ bits : List Bool
+ /-- Ticks and chosen branch bits from the private instructions preceding the callback, in
+ execution order. -/
+ prefixEvents : List (Event w)
+
+/-- Add an earlier instruction event to the front of a scan's chronological prefix. -/
+def Yield.prepend (e : Event w) (y : Yield w p r) : Yield w p r :=
+ {y with prefixEvents := e :: y.prefixEvents}
+
+/-- Run private instructions up to the next read, write, return, accept or reject callback.
+Follow jumps and consume branch bits while recording their events, and reject on exhausted
+fuel or choices. -/
+def scan (T : Template p r k) (pub : Fin k → Word w) : ℕ → LogConfig w p r → List Bool → Yield w p r
+ | 0, c, bs => ⟨.reject, c, 0, bs, []⟩
+ | f+1, c, bs =>
+ let out := instructionPost T pub c
+ match instructionExit T c with
+ | .next j => (scan T pub f {out with pc := j} bs).prepend .tick
+ | .choose yes no => match bs with
+ | [] => ⟨.reject, out, f, [], []⟩
+ | b :: tail => (scan T pub f {out with pc := if b then yes else no} tail).prepend (.choice b)
+ | cb => ⟨cb, out, f, bs, []⟩
+
+private def continuation : ISA.Callback p r → Bool
+ | .next _ | .choose _ _ => true
+ | _ => false
+
+private theorem boundary (T : Template p r k) (cb : ISA.Callback p r) (h : continuation cb = false)
+ (s : Stacks (Port r k)) :
+ StackStep (code T) (.instr (ISA.callback T cb)) s (.exit cb) s := by
+ apply StackStep.goto
+ cases cb <;> simp_all [code, ISA.resume_callback, continuation]
+
+/-- The physical controller reaches the declared exit with the exact bank
+and suffix, including when fuel or choices run out. -/
+theorem scan_run (T : Template p r k) (pub : Fin k → Word w) (f : ℕ)
+ (c : LogConfig w p r) (bs : List Bool) (limit : ℕ) (hl : c.writes.length+f ≤ limit) :
+ let out := scan T pub f c bs
+ ∃ ticks ≤ f*(ISA.prepareBound w limit + 4)+1, StackRuns (code T) ticks (.begin c.pc)
+ (store pub c f bs) (.exit out.exit) (store pub out.cfg out.fuel out.bits) := by
+ induction f generalizing c bs with
+ | zero => exact ⟨1, by simp, cutoff ..⟩
+ | succ f ih =>
+ let out := instructionPost T pub c
+ have hg : out.writes.length ≤ c.writes.length+1 := ISA.post_writes_length_le ..
+ obtain ⟨d, hd, fetchRun⟩ := fetch T pub c f bs
+ have hm : ISA.prepareBound w c.writes.length ≤ ISA.prepareBound w limit :=
+ Nat.mul_le_mul_left _ (by omega)
+ have ht {t : ℕ} (h : t ≤ f*(ISA.prepareBound w limit+4)+1) :
+ d+(t+1) ≤ (f+1)*(ISA.prepareBound w limit+4)+1 := by rw [Nat.succ_mul]; omega
+ have hd' : d+1 ≤ (f+1)*(ISA.prepareBound w limit+4)+1 := by rw [Nat.succ_mul]; omega
+ dsimp only
+ cases he : instructionExit T c with
+ | next j =>
+ rw [he] at fetchRun
+ let after := {out with pc := j}
+ obtain ⟨t, ht', run⟩ := ih after bs (by change out.writes.length+f ≤ limit; omega)
+ refine ⟨_, ht ht', ?_⟩
+ simpa only [scan, he, Yield.prepend] using
+ fetchRun.trans (.cons (next_step T j _) run)
+ | choose yes no =>
+ rw [he] at fetchRun
+ cases bs with
+ | nil =>
+ refine ⟨_, hd', ?_⟩
+ simpa only [scan, he] using fetchRun.trans (.cons (short_choice T yes no pub out f) (.nil ..))
+ | cons b bs =>
+ let after := {out with pc := if b then yes else no}
+ obtain ⟨t, ht', run⟩ := ih after bs (by change out.writes.length+f ≤ limit; omega)
+ refine ⟨_, ht ht', ?_⟩
+ simpa only [scan, he, Yield.prepend] using
+ fetchRun.trans (.cons (branch_step T yes no pub out f b bs) run)
+ | read dst addr j | write addr src j | returnState src | accept | reject =>
+ rw [he] at fetchRun
+ refine ⟨_, hd', ?_⟩
+ simpa only [scan, he] using fetchRun.trans (.cons (boundary T _ rfl _) (.nil ..))
+
+end RAMTape.LocalProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorLogged.lean b/lean/OAI/Computability/VPVNP/RAMProcessorLogged.lean
new file mode 100644
index 0000000000..ccc4c2328f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorLogged.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.RAMPrivateLog
+import OAI.Computability.VPVNP.RAMLocalRun
+
+/-!
+# The logged interpreter computes the same metered local calls
+
+The physical processor represents private memory by a finite write log.
+These equations transfer the native instruction and probe cutoff, including
+rejection on a short guess stream, to that representation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C D : Type*}
+
+theorem runLocalCall_map {P : Program w C} {Q : Program w D} (denote : C → D)
+ (step : ∀ c, (P.step c).mapState denote = Q.step (denote c))
+ (fuel : ℕ) (c : C) (allowance : ℕ) (bits : List Bool) :
+ runLocalCall P fuel c allowance bits = runLocalCall Q fuel (denote c) allowance bits := by
+ induction fuel generalizing c allowance bits with
+ | zero => rfl
+ | succ f ih =>
+ rw [runLocalCall, runLocalCall, ← step]
+ cases P.step c with
+ | localStep _ => simp only [CallAction.mapState, ih]
+ | branch _ => cases bits <;> simp only [CallAction.mapState, ih]
+ | read _ _ =>
+ cases allowance with
+ | zero => rfl
+ | succ _ =>
+ cases h : takeWord w bits with
+ | none => rfl
+ | some pair => obtain ⟨v, tail⟩ := pair; simp only [CallAction.mapState, ih]
+ | write _ _ _ => cases allowance <;> simp only [CallAction.mapState, ih]
+ | finish _ | reject => rfl
+
+namespace PrivateRAM
+
+variable {p r k : ℕ}
+
+theorem Machine.localCall_logged (M : Machine w p r k) (fuel : ℕ) (l : LogConfig w p r)
+ (allowance : ℕ) (bits : List Bool) :
+ runLocalCall M.logProgram fuel l allowance bits = runLocalCall M.program fuel l.denote allowance bits :=
+ runLocalCall_map LogConfig.denote M.logProgram_step fuel l allowance bits
+
+theorem Machine.chargedCall_logged (M : Machine w p r k) (fuel : ℕ) (persist : Word w)
+ (callLeft globalLeft siteLeft : ℕ) (bits : List Bool) :
+ runChargedCall M.logProgram fuel (M.logProgram.start persist) callLeft globalLeft siteLeft bits =
+ runChargedCall M.program fuel (M.program.start persist) callLeft globalLeft siteLeft bits := by
+ unfold runChargedCall
+ cases min callLeft (min globalLeft siteLeft) with
+ | zero => rfl
+ | succ _ => exact M.localCall_logged ..
+
+end PrivateRAM
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorLoopTests.lean b/lean/OAI/Computability/VPVNP/RAMProcessorLoopTests.lean
new file mode 100644
index 0000000000..dc562ad1f7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorLoopTests.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.RAMProcessorGraphRuns
+
+/-! # Physical dispatch of the bucket entry, loop, and final checks -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM
+
+variable {w p r k : ℕ}
+
+private theorem test_run (T : Template p r k) (s : Snapshot w p r k) (l : Label p r)
+ (tree : SiteTests.Tree) (next : SiteTests.Exit → Label p r)
+ (hblock : blocks T l = (tree.fragment next).onPorts testPorts) :
+ StackRuns (table T) (tree.ticks s.tests + (tree.eval s.tests).bits.length)
+ (atLabel T l) s.bank (atLabel T (next (tree.eval s.tests))) s.bank := by
+ apply ProcessorFlow.run (blocks := blocks T) (l := l)
+ rw [hblock]
+ exact Fragment.runs_framed testPorts_injective (tree.fragment_runs next s.tests)
+ s.test_at s.test_at (fun _ _ => rfl)
+
+private theorem exit_length_le (e : SiteTests.Exit) : e.bits.length ≤ 2 := by cases e <;> decide
+
+theorem checkEntry_run (T : Template p r k) (s : Snapshot w p r k) :
+ ∃ n ≤ 60*w+41, StackRuns (table T) n (atLabel T .checkEntry) s.bank
+ (atLabel T (route true (SiteTests.entry.eval s.tests))) s.bank := by
+ have h := SiteTests.entry_work s.tests
+ have hl := exit_length_le (SiteTests.entry.eval s.tests)
+ exact ⟨_, by omega, test_run T s .checkEntry SiteTests.entry (route true) rfl⟩
+
+theorem iteration_run (T : Template p r k) (s : Snapshot w p r k) :
+ ∃ n ≤ 40*w+30, StackRuns (table T) n (atLabel T .iteration) s.bank
+ (atLabel T (route false (SiteTests.iteration.eval s.tests))) s.bank := by
+ have h := SiteTests.iteration_work s.tests
+ have hl := exit_length_le (SiteTests.iteration.eval s.tests)
+ exact ⟨_, by omega, test_run T s .iteration SiteTests.iteration (route false) rfl⟩
+
+theorem finalCheck_run (T : Template p r k) (s : Snapshot w p r k) :
+ ∃ n ≤ 40*w+42, StackRuns (table T) n (atLabel T .finalCheck) s.bank
+ (atLabel T (if SiteTests.finalCheck.eval s.tests = .finish then .close else .reject)) s.bank := by
+ have h := SiteTests.final_work s.tests
+ have hl := exit_length_le (SiteTests.finalCheck.eval s.tests)
+ exact ⟨_, by omega, test_run T s .finalCheck SiteTests.finalCheck _ rfl⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorOrdinal.lean b/lean/OAI/Computability/VPVNP/RAMProcessorOrdinal.lean
new file mode 100644
index 0000000000..a6917aaa42
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorOrdinal.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.RAMProcessorCreditPorts
+
+/-!
+# Incrementing a probe ordinal after recording it
+
+The timestamp field of a probe is the ordinal before this increment. The
+routine scans the ordinal word and scratch stack. It returns with the
+incremented ordinal, or reaches the rejecting halt on overflow.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.CallCredit
+
+open BurstRAM TapeWord
+
+/-- The incrementer's active word is the ordinal. Its other labels are
+injected into the usual budget ports. -/
+def ordinalPorts : Charges.Port → Port
+ | .cost => .ordinal
+ | p => .budget p
+
+theorem ordinalPorts_injective : Function.Injective ordinalPorts := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [ordinalPorts]
+
+/-- Increment the probe ordinal after emitting its old value as the timestamp. Overflow of the
+fixed-width word leads to rejection. -/
+def finishProbe : FiniteRoutine Port := Charges.routine ordinalPorts (.scan true true)
+
+private theorem ordinalFrame (s : Stacks Port) (bits : List Bool) (ht : s (.budget .tmp) = []) :
+ installStacks ordinalPorts s
+ (Charges.scanData true (s (.budget .fuel)) (s (.budget .call)) (s (.budget .site))
+ (s (.budget .globalLeft)) bits []).stacks = Function.update s .ordinal bits := by
+ apply installStacks_frame ordinalPorts_injective
+ · intro p
+ cases p <;> simp [ordinalPorts, Charges.scanData, Charges.Data.stacks, ht]
+ · intro p hp
+ exact Function.update_of_ne (fun h => hp .cost h.symm) ..
+
+/-- Increment only the ordinal after its old value has been emitted. -/
+theorem finishProbe_run {w : ℕ} (o : Word w) (ho : o.val + 1 < 2 ^ w) (s : Stacks Port)
+ (hs : s .ordinal = wordBits o) (ht : s (.budget .tmp) = []) :
+ finishProbe.Runs (4*w+2) s
+ (Function.update s .ordinal (wordBits (⟨o.val + 1, ho⟩ : Word w))) := by
+ have h := Charges.adjustRun true true (wordBits o)
+ (s (.budget .fuel)) (s (.budget .call)) (s (.budget .site)) (s (.budget .globalLeft))
+ simp only [length_wordBits, Charges.adjust_inc_word o ho] at h
+ have hh := Charges.liftRun ordinalPorts_injective s
+ (entry := .scan true true) (exit := .done) (by decide) h
+ simp only [ordinalFrame s _ ht, ↓reduceIte] at hh
+ rw [← hs, Function.update_eq_self] at hh
+ exact hh
+
+/-- Overflow reaches the rejecting row after exactly the same fixed-width
+scan. It makes no further probe or program choice. -/
+theorem finishProbe_reject {w : ℕ} (o : Word w) (ho : 2 ^ w ≤ o.val + 1) (s : Stacks Port)
+ (hs : s .ordinal = wordBits o) (ht : s (.budget .tmp) = []) :
+ ∃ out, StackRuns finishProbe.body.standalone (4*w+2) (some (.scan true true)) s
+ (some .reject) out := by
+ have hf := (Charges.adjust_overflow_iff (wordBits o)).mpr (by simpa only [length_wordBits, value_wordBits] using ho)
+ have h := Charges.adjustRun true true (wordBits o)
+ (s (.budget .fuel)) (s (.budget .call)) (s (.budget .site)) (s (.budget .globalLeft))
+ simp only [length_wordBits, hf] at h
+ have hh := Charges.liftRun ordinalPorts_injective s
+ (entry := .scan true true) (exit := .reject) (by decide) h
+ simp only [ordinalFrame s _ ht, show Charges.State.reject ≠ .done by decide, ↓reduceIte] at hh
+ rw [← hs, Function.update_eq_self] at hh
+ exact ⟨_, hh⟩
+
+end RAMTape.CallCredit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorPending.lean b/lean/OAI/Computability/VPVNP/RAMProcessorPending.lean
new file mode 100644
index 0000000000..c649427d84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorPending.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+import OAI.Computability.VPVNP.RAMProcessorGraphProbe
+
+/-!
+# External callbacks after a bounded private segment
+
+The pending result uses the unspent fuel and the three probe allowances in
+the physical bank. Connecting it to the internal scan preserves the full
+report, including private choices that did not create memory records.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k H F : ℕ} {hw : 2 ≤ w}
+
+/-- Resume the native log program at a physical callback using the snapshot's remaining
+instruction fuel, probe allowance and private choice stream. -/
+def pending (T : Template p r k) (s : Snapshot w p r k) (cb : ISA.Callback p r) :=
+ LocalProcessor.resume (T.instantiate w s.pub).logProgram (allowance s)
+ ⟨cb, s.cfg, s.fuel, s.choices, []⟩
+
+/-- Specification of a physical run from a given label for a pending native result. Failure
+reaches a rejecting row. Success reaches the iteration label with the matching report,
+record buffer and unused choice suffix. -/
+def Meets (T : Template p r k) (hw : 2 ≤ w) (H F : ℕ) (s : Snapshot w p r k)
+ (ys : List (WordRecord w)) (start ord : Word w) (l : Label p r) (out : LocalProcessor.Output w) (t : ℕ) : Prop :=
+ match out with
+ | none => RejectRun (table T) t (atLabel T l) s.bank
+ | some (rep, tail) => ∃ u new, CallReady hw H F false u new ∧ CallReturn s u ys new start ord rep tail ∧
+ StackRuns (table T) t (atLabel T l) s.bank (atLabel T .iteration) u.bank
+
+theorem scan_then_pending (T : Template p r k) (s : Snapshot w p r k) {ys start ord t d}
+ (run : let y := LocalProcessor.scan T s.pub s.fuel s.cfg s.choices
+ StackRuns (table T) t (atLabel T (.segment s.cfg.pc)) s.bank (atLabel T (.callback y.exit))
+ (s.afterLocal y).bank)
+ (hr : let y := LocalProcessor.scan T s.pub s.fuel s.cfg s.choices
+ Meets T hw H F (s.afterLocal y) ys start ord (.callback y.exit) (pending T (s.afterLocal y) y.exit) d) :
+ SegmentRun T hw H F s ys start ord (t+d) := by
+ let y := LocalProcessor.scan T s.pub s.fuel s.cfg s.choices
+ let out := pending T (s.afterLocal y) y.exit
+ have eqout : (runLocalCall (T.instantiate w s.pub).logProgram s.fuel s.cfg (allowance s) s.choices).output =
+ out.map (fun z => (z.1.withEvents y.prefixEvents, z.2)) := by
+ rw [← LocalProcessor.scan_result, LocalProcessor.result, LocalProcessor.addEvents_eq]
+ rfl
+ change Meets T hw H F (s.afterLocal y) ys start ord (.callback y.exit) out d at hr
+ unfold SegmentRun
+ unfold allowance at eqout
+ rw [eqout]
+ cases ho : out with
+ | none =>
+ change RejectRun (table T) (t+d) (atLabel T (.segment s.cfg.pc)) s.bank
+ rw [ho] at hr
+ exact run.thenReject hr
+ | some z =>
+ obtain ⟨rep,tail⟩ := z
+ rw [ho] at hr
+ obtain ⟨u, zs, ready, ret, finish⟩ := hr
+ exact ⟨u,zs,ready,ret.privatePrefix T,run.trans finish⟩
+
+private theorem callReady_return {s : Snapshot w p r k} {ys start ord} (hin : InCall hw H F s ys start ord)
+ (src : Fin r) : CallReady hw H F false (s.afterReturn src) ys := by
+ exact {hin.toCallReady with buffer := {
+ fit := hin.buffer.fit, scratch := rfl, zeros := rfl, remaining := hin.buffer.remaining,
+ buffer := hin.buffer.buffer, output := hin.buffer.output }}
+
+private theorem callReady_accept {s : Snapshot w p r k} {ys start ord} (hin : InCall hw H F s ys start ord) :
+ CallReady hw H F false s.afterAccept ys := by
+ exact {hin.toCallReady with buffer := {
+ fit := hin.buffer.fit, scratch := rfl, zeros := rfl, remaining := hin.buffer.remaining,
+ buffer := hin.buffer.buffer, output := hin.buffer.output }}
+
+theorem pending_return (T : Template p r k) {s : Snapshot w p r k} {ys start ord}
+ (hin : InCall hw H F s ys start ord) (src : Fin r) :
+ Meets T hw H F s ys start ord (.callback (.returnState src)) (pending T s (.returnState src)) (8*w+6) := by
+ refine ⟨s.afterReturn src, ys, callReady_return hin src, ?_, returnState_run T s src⟩
+ exact ⟨rfl,rfl,rfl,rfl,rfl,rfl,by simp [Report.probes,countProbes]; rfl,rfl,
+ by simp [Report.probes,countProbes]; rfl,rfl,by simp [eventRecords]⟩
+
+theorem pending_accept (T : Template p r k) {s : Snapshot w p r k} {ys start ord}
+ (hin : InCall hw H F s ys start ord) :
+ Meets T hw H F s ys start ord (.callback .accept) (pending T s .accept) 3 := by
+ refine ⟨s.afterAccept, ys, callReady_accept hin, ?_, accept_run T s⟩
+ exact ⟨rfl,rfl,rfl,rfl,rfl,rfl,by simp [Report.probes,countProbes]; rfl,rfl,
+ by simp [Report.probes,countProbes]; rfl,rfl,by simp [eventRecords]⟩
+
+theorem pending_reject (T : Template p r k) (s : Snapshot w p r k) (ys : List (WordRecord w)) (start ord : Word w) :
+ Meets T hw H F s ys start ord (.callback .reject) (pending T s .reject) 1 := by
+ exact ⟨atLabel T .reject, s.bank, .cons (.goto rfl) (.nil ..), rfl⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorPhysicalClock.lean b/lean/OAI/Computability/VPVNP/RAMProcessorPhysicalClock.lean
new file mode 100644
index 0000000000..7e6ad4b693
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorPhysicalClock.lean
@@ -0,0 +1,212 @@
+import OAI.Computability.VPVNP.RAMProcessorCallInvariant
+import OAI.Computability.VPVNP.RAMApplications
+import OAI.Computability.VPVNP.RAMTapeSitePostClock
+import OAI.Computability.VPVNP.RAMTapeNamed
+
+/-!
+# The literal processor clock for the two RAM transcript applications
+
+The estimate counts the site-entry and call loops, the closing checks, all
+startup and sorting work, and the two-tape simulation of the named bit stacks.
+The constants for a fixed template and its ports affect the threshold in the
+input length. The clock exponent is uniform over the site and its choices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open Filter BurstRAM
+
+/-- Upper bound for starting a bucket call, resetting its registers and private
+log, and executing its private and external instruction segments. -/
+def perCallEstimate (regs w H fuel : ℕ) :=
+ (16*w+7 + 80*(H+fuel+w+1)) + (regs*(8*w+3) + 3*(fuel*(w+1)+1)+2) + callWork w fuel
+
+theorem CallReady.start_and_call_le {w p regs k H fuel : ℕ} {hw : 2 ≤ w} {first : Bool}
+ {s : Snapshot w p regs k} {ys} (h : CallReady hw H fuel first s ys) :
+ (16*w+7+s.startTicks) + (regs*(8*w+3)+3*(s.cfg.writes.length*(w+1)+1)+2) + callWork w fuel ≤
+ perCallEstimate regs w H fuel := by
+ have hlog := h.privateClock
+ have hcredit := h.callCredit
+ have hsaved := h.saved
+ have hord := h.ordinal
+ have hs : s.startTicks ≤ 80*(H+fuel+w+1) := by
+ unfold Snapshot.startTicks CallCredit.resetTicks
+ rw [h.publicH, h.publicFuel]
+ omega
+ have hl := Nat.mul_le_mul_right (w+1) (show s.cfg.writes.length ≤ fuel by omega)
+ unfold perCallEstimate
+ omega
+
+theorem perCallEstimate_le (regs w H fuel : ℕ) :
+ perCallEstimate regs w H fuel ≤ 1000*(regs+1)*(H+1)^2*(fuel+1)^3*(w+1)^4 := by
+ let D := (H+1)^2*(fuel+1)^3*(w+1)^4
+ have hH : H+1 ≤ (H+1)^2 := Nat.le_self_pow (by decide) _
+ have hf : fuel+1 ≤ (fuel+1)^3 := Nat.le_self_pow (by decide) _
+ have hw : w+1 ≤ (w+1)^4 := Nat.le_self_pow (by decide) _
+ have hBig : (fuel+1)^3*(w+1)^4 ≤ D := by
+ dsimp only [D]
+ rw [Nat.mul_assoc]
+ exact Nat.le_mul_of_pos_left _ (by positivity)
+ have hD : H+1 ≤ D := hH.trans ((Nat.le_mul_of_pos_right _ (by positivity :
+ 0 < (fuel+1)^3)).trans (Nat.le_mul_of_pos_right _ (by positivity)))
+ have hfD : fuel+1 ≤ D := hf.trans ((Nat.le_mul_of_pos_right _ (by positivity)).trans hBig)
+ have hwD : w+1 ≤ D := hw.trans ((Nat.le_mul_of_pos_left _ (by positivity)).trans hBig)
+ have hfw : (fuel+1)*(w+1) ≤ D := (Nat.mul_le_mul hf hw).trans hBig
+ have hsq : (fuel+1)^2 ≤ D := (Nat.pow_le_pow_right (Nat.succ_pos _) (by decide : 2 ≤ 3)).trans
+ ((Nat.le_mul_of_pos_right _ (by positivity)).trans hBig)
+ have hcube : (fuel+1)^3*(w+1)^2 ≤ D := (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right
+ (Nat.succ_pos _) (by decide : 2 ≤ 4))).trans hBig
+ have hscan : callWork w fuel ≤ 304*D := by
+ rw [show callWork w fuel = 100*((fuel+1)^3*(w+1)^2) + 4*(fuel+1)^2 + 200*((fuel+1)*(w+1)) by
+ unfold callWork segmentWork ISA.prepareBound; ring]
+ omega
+ have hreg : regs*(8*w+3) ≤ 11*(regs*D) := by
+ rw [show 11*(regs*D)=regs*(11*D) by ring]
+ exact Nat.mul_le_mul_left _ (by omega)
+ have hlog : fuel*(w+1) ≤ D := (Nat.mul_le_mul_right _ (Nat.le_succ fuel)).trans hfw
+ rw [show 1000*(regs+1)*(H+1)^2*(fuel+1)^3*(w+1)^4 = 1000*(regs*D)+1000*D by dsimp [D]; ring]
+ unfold perCallEstimate
+ omega
+
+private theorem startup_le {u n c startup : ℕ} (hn : 1 ≤ n)
+ (hc : c * 2 ^ max 7 (u+1) ≤ n)
+ (hstart : startup ≤ c * (n+1) ^ max 7 (u+1)) :
+ startup ≤ n^(3*u+8) := by
+ let k := max 7 (u+1)
+ calc
+ startup ≤ c*(2*n)^k := hstart.trans (Nat.mul_le_mul_left c (Nat.pow_le_pow_left (by omega) _))
+ _ = (c*2^k)*n^k := by rw [mul_pow, Nat.mul_assoc]
+ _ ≤ n*n^k := Nat.mul_le_mul_right _ hc
+ _ = n^(k+1) := by rw [pow_succ, Nat.mul_comm]
+ _ ≤ n^(3*u+8) := Nat.pow_le_pow_right hn (by dsimp [k]; omega)
+
+private theorem call_le {u n c fuel H w work : ℕ} (hn : 1 ≤ n) (hc : 1152*c ≤ n)
+ (hw : w ≤ n) (hH : H ≤ 2*n) (hf : fuel ≤ n^u)
+ (hwork : work ≤ c*(H+1)^2*(fuel+1)^3*(w+1)^4) :
+ work ≤ n^(3*u+7) := by
+ have hp : 1 ≤ n^u := Nat.one_le_pow _ _ hn
+ calc
+ work ≤ c*(3*n)^2*(2*n^u)^3*(2*n)^4 := hwork.trans (Nat.mul_le_mul
+ (Nat.mul_le_mul (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by omega) _))
+ (Nat.pow_le_pow_left (by omega) _)) (Nat.pow_le_pow_left (by omega) _))
+ _ = (1152*c)*n^(3*u+6) := by
+ rw [show 3*u+6=u*3+6 by omega, pow_add, pow_mul]
+ ring
+ _ ≤ n*n^(3*u+6) := Nat.mul_le_mul_right _ hc
+ _ = n^(3*u+7) := by rw [pow_succ n (3*u+6), Nat.mul_comm]
+
+private theorem loop_le {n H w work E : ℕ} (hn : 1 ≤ n) (hw : w ≤ n) (hH : H ≤ 2*n)
+ (hE : n ≤ E) (hwork : work ≤ E) :
+ siteWork w H work + closeWork w H ≤ 1020*(n*E) := by
+ have h₁ : 60*w+41+work ≤ 102*E := by omega
+ have h₂ : (2*H-1)*(work+(40*w+30)) ≤ (4*n)*(71*E) :=
+ Nat.mul_le_mul (by omega) (by omega)
+ have h₃ : (4*H)*(25*w+12) ≤ (8*n)*(37*E) := Nat.mul_le_mul (by omega) (by omega)
+ have h₄ : (4*H*5*w) ≤ (40*n)*E := Nat.mul_le_mul (by omega) (by omega)
+ have h₅ : 40*w+42+1+1 ≤ 84*E := by omega
+ have hE' : E ≤ n*E := Nat.le_mul_of_pos_left _ hn
+ unfold siteWork closeWork
+ nlinarith only [h₁,h₂,h₃,h₄,h₅,hE',Nat.zero_le (n*E)]
+
+/-- Absorb all concrete stack stages into a single `n` power. The threshold is
+independent of the register contents, site, bucket, and clock realization. -/
+theorem eventually_stack_clock (u cstart ccall : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ w H fuel startup post work T : ℕ,
+ w ≤ n → H ≤ 2*n → fuel ≤ n^u →
+ startup ≤ cstart*(n+1)^max 7 (u+1) → post ≤ n^7 →
+ work ≤ ccall*(H+1)^2*(fuel+1)^3*(w+1)^4 →
+ T ≤ startup + siteWork w H work + closeWork w H + post → T ≤ n^(3*u+9) := by
+ filter_upwards [eventually_ge_atTop 1024, eventually_ge_atTop (1152*ccall),
+ eventually_ge_atTop (cstart*2^max 7 (u+1))] with n hn hcall hstart
+ intro w H fuel startup post work T hw hH hf hs hp hc hT
+ have h₀ : 1 ≤ n := by omega
+ have start := startup_le h₀ hstart hs
+ have call := call_le h₀ hcall hw hH hf hc
+ have loop := loop_le h₀ hw hH (Nat.le_self_pow (by omega : 3*u+7 ≠ 0) n) call
+ rw [← Nat.pow_succ'] at loop
+ change siteWork w H work + closeWork w H ≤ 1020 * n^(3*u+8) at loop
+ have fin := hp.trans (Nat.pow_le_pow_right h₀ (by omega : 7 ≤ 3*u+8))
+ have bound : T ≤ 1024*n^(3*u+8) := by omega
+ exact bound.trans ((Nat.mul_le_mul_right _ hn).trans_eq (Nat.pow_succ' ..).symm)
+
+/-- Exact physical two-tape simulation overhead used by `input_count_labeled`. -/
+theorem eventually_physical_clock (u cstart ccall ports : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ w H fuel startup post work T : ℕ,
+ w ≤ n → H ≤ 2*n → fuel ≤ n^u →
+ startup ≤ cstart*(n+1)^max 7 (u+1) → post ≤ n^7 →
+ work ≤ ccall*(H+1)^2*(fuel+1)^3*(w+1)^4 →
+ T ≤ startup + siteWork w H work + closeWork w H + post →
+ T*(6*(n+(ports+1)+T)+4) ≤ n^(10*u+30) := by
+ filter_upwards [eventually_stack_clock u cstart ccall, eventually_ge_atTop ports,
+ eventually_ge_atTop 28] with n stack hports hn
+ intro w H fuel startup post work T hw hH hf hs hp hc hT
+ have hs' := stack w H fuel startup post work T hw hH hf hs hp hc hT
+ let A := n^(3*u+9)
+ have hA : n ≤ A := Nat.le_self_pow (by omega : 3*u+9 ≠ 0) _
+ have ht : T ≤ A := hs'
+ calc
+ _ ≤ A*(28*A) := Nat.mul_le_mul ht (by omega)
+ _ = 28*n^((3*u+9)*2) := by dsimp [A]; rw [pow_mul]; ring
+ _ ≤ n*n^((3*u+9)*2) := Nat.mul_le_mul_right _ hn
+ _ = n^((3*u+9)*2+1) := (Nat.pow_succ' ..).symm
+ _ ≤ n^(10*u+30) := Nat.pow_le_pow_right (by omega) (by omega)
+
+/-- Physical stack budget through the last incident-record check. The
+postprocessor includes its sorting startup, all row exchanges, and its terminal
+flag and boundary scans. -/
+def totalStackCutoff (d e w regs fuel startup : ℕ) :=
+ startup + siteWork w (2^e) (perCallEstimate regs w (2^e) fuel) +
+ closeWork w (2^e) + SitePost.budget d e w 0
+
+/-- A graph realization whose individual call costs satisfy the physical
+estimate is covered by the same total cutoff. -/
+theorem le_totalStackCutoff {d e w regs fuel startup work T : ℕ}
+ (hcall : work ≤ perCallEstimate regs w (2^e) fuel)
+ (hT : T ≤ startup + siteWork w (2^e) work + closeWork w (2^e) + SitePost.budget d e w 0) :
+ T ≤ totalStackCutoff d e w regs fuel startup := by
+ apply hT.trans
+ unfold totalStackCutoff siteWork
+ gcongr
+
+/-- The actual named-stack tape clock, including the closed memory checker,
+at the paper's processor parameters. -/
+def ApplicationClock (n d e w u regs cstart ports : ℕ) : Prop :=
+ ∀ fuel startup T : ℕ, fuel ≤ n^u → startup ≤ cstart*(n+1)^max 7 (u+1) →
+ T ≤ totalStackCutoff d e w regs fuel startup →
+ T*(6*(n+(ports+1)+T)+4) ≤ n^(10*u+30) ∧ T*(6*(n+(ports+1)+T)+4) ≤ n^clockExponent
+
+theorem eventually_application_clock (u regs cstart ports : ℕ) (hexp : 10*u+30 ≤ clockExponent) :
+ ∀ᶠ n : ℕ in atTop, ∀ d e w, ProcessorBudget n d e w → ApplicationClock n d e w u regs cstart ports := by
+ filter_upwards [eventually_physical_clock u cstart (1000*(regs+1)) ports,
+ eventually_ge_atTop 4000010] with n hclock hn
+ intro d e w budget fuel startup T hf hstart hT
+ have hpost := SitePost.budget_le (d := d) hn budget.bucket_le (by have := budget.phase_le; omega) budget.word_le
+ have h := hclock w (2^e) fuel startup (SitePost.budget d e w 0)
+ (perCallEstimate regs w (2^e) fuel) T budget.word_le budget.bucket_le hf hstart hpost
+ (perCallEstimate_le ..) hT
+ exact ⟨h, h.trans (Nat.pow_le_pow_right (by omega) hexp)⟩
+
+/-- One length threshold covers the live and virtual processors, with their
+respective private fuels `n^10000` and `n^10`. The two templates and their
+numbers of ports and registers may differ. -/
+theorem eventually_both_application_clocks {B : ℕ} (hB : 1 ≤ B) {δ : ℝ}
+ (hδ : 0 ≤ δ) (hδ' : δ ≤ 1) (liveRegs liveStart livePorts virtualRegs virtualStart virtualPorts : ℕ) :
+ ∀ᶠ n : ℕ in atTop,
+ ApplicationClock n (addressWidth B n) (Compression.bucketExponent (1-δ) n)
+ (CursorBounds.wordBits B n) 10000 liveRegs liveStart livePorts ∧
+ ApplicationClock n (CursorBounds.virtualBits B n) (roundedUp 1 4 n)
+ (CursorBounds.wordBits B n) 10 virtualRegs virtualStart virtualPorts := by
+ filter_upwards [eventually_bothProcessorBudgets hB hδ hδ',
+ eventually_application_clock 10000 liveRegs liveStart livePorts (by decide),
+ eventually_application_clock 10 virtualRegs virtualStart virtualPorts (by decide)] with n h live virtual
+ exact ⟨live _ _ _ h.1, virtual _ _ _ h.2⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorPrelude.lean b/lean/OAI/Computability/VPVNP/RAMProcessorPrelude.lean
new file mode 100644
index 0000000000..fc69753c98
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorPrelude.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.RAMProcessorGraphStart
+import OAI.Computability.VPVNP.RAMProcessorInitFields
+import OAI.Computability.VPVNP.RAMProcessorGraphProbeEmit
+
+/-!
+# Initializing and entering the complete burst-site graph
+
+A freshly parsed site has empty architectural registers. The prelude creates
+width-correct zeros in those registers and stages the five-word initialization
+record. The caller supplies the zero-extended site address and the four-bit
+header packed in a word, exactly the values produced by the input preparer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM
+
+variable {p r k w : ℕ}
+
+/-- Stack bank of a freshly parsed site, with empty private register stacks ready for
+initialization. -/
+def Snapshot.bare (s : Snapshot w p r k) : Stacks (Port r k)
+ | .isa (.reg _) => []
+ | i => s.bank i
+
+/-- Stage the initialization record's tag one, saved site address and zero probe ordinal in the
+snapshot. -/
+def Snapshot.withInitFields (s : Snapshot w p r k) (a : Word w) : Snapshot w p r k :=
+ {s with tag := wordBits (Fin.ofNat (2^w) 1), savedStart := wordBits a, ordinal := wordBits (0 : Word w)}
+
+/-- Initialize the private registers and write log for a fresh call, then stage the
+initialization record fields. -/
+def boot : FiniteRoutine (Port r k) :=
+ ((ISA.freshCall (r := r) (k := k)).onPorts Port.isa).followedBy (RecordBuffer.initFields.onPorts recordPorts)
+
+theorem initFields_run (s : Snapshot w p r k) (a : Word w) (ha : s.address = wordBits a) (ho : s.output = []) :
+ (RecordBuffer.initFields.onPorts recordPorts).Runs (s.tag.length+s.savedStart.length+s.ordinal.length+21*w+9)
+ s.bank (s.withInitFields a).bank := by
+ have h := RecordBuffer.initFields_run s.records a ha (UnaryWord.zeros_wordBits w) rfl ho
+ apply RecordBuffer.initFields.runs_onPorts_framed recordPorts_injective h s.record_at
+ · intro j
+ rw [Snapshot.record_at]
+ cases j with
+ | field j => fin_cases j <;> rfl
+ | _ => rfl
+ · intro j hj
+ cases j with
+ | isa _ | scratch _ => rfl
+ | test i => cases i with | word f => cases f <;> rfl | _ => rfl
+ | credit i =>
+ cases i with
+ | savedStart => exact (hj (.field 3) rfl).elim
+ | ordinal => exact (hj (.field 4) rfl).elim
+ | _ => rfl
+ | record i =>
+ cases i with
+ | field i =>
+ fin_cases i <;> first | rfl | exact (hj (.field 0) rfl).elim
+ | _ => rfl
+
+theorem boot_run (T : Template p r k) (s : Snapshot w p r k) (a : Word w)
+ (ha : s.address = wordBits a) (ho : s.output = []) :
+ ∃ t ≤ r*(8*w+3)+3*(s.cfg.writes.length*(w+1)+1)+2 +
+ (s.tag.length+s.savedStart.length+s.ordinal.length+21*w+9),
+ boot.Runs t s.bare ((s.afterFresh T).withInitFields a).bank := by
+ obtain ⟨t, ht, fresh⟩ := ISA.freshCall_run s.pub s.cfg.persistent (fun _ : Fin r => [])
+ s.cfg.writes (by simp)
+ have h₁ : (ISA.freshCall.onPorts (Port.isa : ISA.Port r k → Port r k)).Runs t s.bare (s.afterFresh T).bank := by
+ apply ISA.freshCall.runs_onPorts_framed (fun _ _ h => Port.isa.inj h) fresh
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> rfl
+ · intro j hj
+ cases j with
+ | isa i => exact (hj i rfl).elim
+ | test i => cases i with | word f => cases f <;> rfl | _ => rfl
+ | record i => cases i <;> rfl
+ | _ => rfl
+ exact ⟨_, Nat.add_le_add_right ht _, h₁.followedBy (initFields_run (s.afterFresh T) a ha ho)⟩
+
+/-- Test whether the control is at the site graph's successful completion label. -/
+def graphDone {T : Template p r k} (q : Control T) : Bool :=
+ match q.1 with | .done => true | _ => false
+
+theorem graphDone_row (T : Template p r k) (q : Control T) (hq : graphDone q = true) :
+ table T q = .halt true := by
+ rcases q with ⟨q, state⟩
+ cases q <;> first | contradiction | rfl
+
+/-- Normal graph completion transfers the padded block to the next local
+validator. A rejecting row halts the entire path. -/
+def graphRoutine (T : Template p r k) : FiniteRoutine (Port r k) :=
+ .ofStackCode (table T) id (atLabel T .initialRecord) graphDone
+
+theorem graphRoutine_run (T : Template p r k) {t s u}
+ (h : StackRuns (table T) t (atLabel T .initialRecord) s (atLabel T .done) u) :
+ (graphRoutine T).Runs t s u := by
+ have hhalt (q : Control T) (hq : graphDone q = true) : (table T q).returns = true := by
+ rw [graphDone_row T q hq]; rfl
+ exact FiniteRoutine.runs_ofStackCode_framed Function.injective_id (normal := graphDone) rfl rfl hhalt h
+ (fun _ => rfl) (fun _ => rfl) (fun j hj => (hj j rfl).elim)
+
+/-- Boot a freshly parsed site and execute its graph from initialization-record emission
+through successful completion or rejection. -/
+def callSite (T : Template p r k) : FiniteRoutine (Port r k) := boot.followedBy (graphRoutine T)
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorProbeContinue.lean b/lean/OAI/Computability/VPVNP/RAMProcessorProbeContinue.lean
new file mode 100644
index 0000000000..43a2eb2372
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorProbeContinue.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.RAMProcessorProbeStep
+import OAI.Computability.VPVNP.RAMProcessorProbeFailure
+
+/-!
+# Resuming the physical call after an admitted probe
+
+The native read continuation sees the exact guessed value. The write
+continuation sees its original register bank. Both consume precisely the
+probe just staged and recorded by the graph.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor.ProbeStep
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k H F : ℕ} {hw : 2 ≤ w}
+
+/-- Native read or write event corresponding to the staged probe. Its address comes from the
+original register bank even if a read overwrites the address register. -/
+def event (a : ProbeStep w p r) (s : Snapshot w p r k) : Event w :=
+ match a with
+ | .read _ i _ v _ => .read (s.cfg.reg i) v
+ | .write i j _ => .write (s.cfg.reg i) (s.cfg.reg j)
+
+theorem link (a : ProbeStep w p r) (s : Snapshot w p r k) (start ord : Word w) (hc ho) :
+ ProbeLink s (a.finish s hw start ord hc ho) (a.record s start ord) (a.event s) start ord ⟨ord.val+1,ho⟩ := by
+ cases a <;> exact ⟨rfl,rfl,rfl,rfl,rfl,rfl,rfl,rfl,fun _ => rfl,fun _ => rfl⟩
+
+theorem finish_fuel (a : ProbeStep w p r) (s : Snapshot w p r k) (start ord : Word w) (hc ho) :
+ (a.finish s hw start ord hc ho).fuel = s.fuel := by cases a <;> rfl
+
+theorem finish_pc (a : ProbeStep w p r) (s : Snapshot w p r k) (start ord : Word w) (hc ho) :
+ (a.finish s hw start ord hc ho).cfg.pc = a.next := by cases a <;> rfl
+
+theorem pending_eq (a : ProbeStep w p r) (T : Template p r k) (s : Snapshot w p r k)
+ (start ord : Word w) (hc ho) (hp : 0 < allowance s) (hb : a.accepts s) :
+ let u := a.finish s hw start ord hc ho
+ pending T s a.callback = LocalProcessor.addEvent (a.event s)
+ (runLocalCall (T.instantiate w u.pub).logProgram u.fuel u.cfg (allowance u) u.choices).output := by
+ dsimp only
+ rw [a.finish_allowance s hw start ord hc ho hp]
+ have he : allowance s = (allowance s-1)+1 := by omega
+ cases a with
+ | read dst addr pc v tail =>
+ have hg := (takeWord_eq_some_iff s.choices v tail).mpr hb
+ unfold pending LocalProcessor.resume
+ conv_lhs => rw [he]
+ simp only [callback, ISA.Callback.action, hg, Option.bind_some]
+ rfl
+ | write addr src pc =>
+ unfold pending LocalProcessor.resume
+ conv_lhs => rw [he]
+ rfl
+
+/-- Inductively transfer the entire successful or failed continuation. -/
+theorem continue_run (a : ProbeStep w p r) (T : Template p r k) {s : Snapshot w p r k} {ys start ord}
+ (hin : InCall hw H F s ys start ord) (hp : 0 < allowance s) (hb : a.accepts s)
+ (ih : let u := a.finish s hw start ord (hin.costRoom hp) hin.ordRoom
+ InCall hw H F u (ys++[a.record s start ord]) start ⟨ord.val+1,hin.ordRoom⟩ →
+ ∃ n ≤ (u.fuel+1)*segmentWork w F, SegmentRun T hw H F u (ys++[a.record s start ord])
+ start ⟨ord.val+1,hin.ordRoom⟩ n) :
+ ∃ d ≤ 200*(w+1) + (s.fuel+1)*segmentWork w F,
+ Meets T hw H F s ys start ord (.callback a.callback) (pending T s a.callback) d := by
+ let u := a.finish s hw start ord (hin.costRoom hp) hin.ordRoom
+ obtain ⟨d, hd, hrun, hnext⟩ := a.run T hin hp hb
+ obtain ⟨t, ht, tail⟩ := ih hnext
+ rw [a.finish_fuel] at ht
+ rw [← a.finish_pc s start ord (hin.costRoom hp) hin.ordRoom (hw := hw)] at hrun
+ exact ⟨d+t, Nat.add_le_add hd ht, probe_then_segment T hrun (a.link ..)
+ (a.pending_eq T s start ord (hin.costRoom hp) hin.ordRoom hp hb) tail⟩
+
+end RAMTape.SiteProcessor.ProbeStep
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorProbeCredit.lean b/lean/OAI/Computability/VPVNP/RAMProcessorProbeCredit.lean
new file mode 100644
index 0000000000..6a70b7ec84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorProbeCredit.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.RAMProcessorOrdinal
+
+/-!
+# Charged probe entry and post-emission timestamps
+
+Startup and every external probe enter the same precharge. A successful
+precharge preserves the saved call start and current ordinal. Emission can
+therefore read them before the separate ordinal increment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.CallCredit
+
+open BurstRAM
+
+variable {w : ℕ}
+
+/-- Charge a probe against call, site and global credit, and increment the cumulative cost. An
+exhausted allowance or cost overflow rejects before the probe is staged. -/
+def prepareProbe : FiniteRoutine Port := Charges.routine Port.budget .charge
+
+theorem prepareProbe_run (H fuelCap fuel call site : ℕ) (cap g c : Word w) (saved ord : List Bool)
+ (hg : 0 < g.val) (hc : c.val + 1 < 2 ^ w) :
+ prepareProbe.Runs (8*w+6) (bank H fuelCap fuel (call+1) (site+1) cap g c saved ord)
+ (bank H fuelCap fuel call site cap (Charges.prevWord g) ⟨c.val+1,hc⟩ saved ord) := by
+ let before := bank H fuelCap fuel (call+1) (site+1) cap g c saved ord
+ have h := Charges.liftRun budget_injective before (entry := .charge) (exit := .done) (by decide)
+ (Charges.chargeRun fuel call site g c hg hc)
+ simp only [before, install_budget_bank, ↓reduceIte] at h
+ exact h
+
+/-- Failed precharging updates only budget ports and cannot reach a probe
+callback. The controls are physically at the rejecting halt. -/
+theorem prepareProbe_reject (H fuelCap fuel call site : ℕ) (cap g c : Word w) (saved ord : List Bool)
+ (bad : call = 0 ∨ site = 0 ∨ g.val = 0 ∨ 2 ^ w ≤ c.val + 1) :
+ let before := bank H fuelCap fuel call site cap g c saved ord
+ ∃ raw, StackRuns prepareProbe.body.standalone (Charges.failureTicks call site g)
+ (some .charge) before (some .reject) (installStacks Port.budget before raw) := by
+ obtain ⟨raw, hr⟩ := Charges.chargeReject fuel call site g c bad
+ let before := bank H fuelCap fuel call site cap g c saved ord
+ have h := Charges.liftRun budget_injective before (entry := .charge) (exit := .reject)
+ (by decide) hr
+ simp only [before, install_budget_bank, show Charges.State.reject ≠ .done by decide, ↓reduceIte] at h
+ exact ⟨_, h⟩
+
+@[simp] theorem prepareProbe_halt :
+ prepareProbe.body.standalone (some .reject) = .halt false := rfl
+
+theorem finishProbe_bank {w : ℕ} (H fuelCap fuel call site : ℕ) (cap g c o : Word w)
+ (saved : List Bool) (ho : o.val + 1 < 2 ^ w) :
+ finishProbe.Runs (4*w+2) (bank H fuelCap fuel call site cap g c saved (wordBits o))
+ (bank H fuelCap fuel call site cap g c saved (wordBits (⟨o.val+1,ho⟩ : Word w))) := by
+ have he := finishProbe_run o ho (bank H fuelCap fuel call site cap g c saved (wordBits o)) rfl rfl
+ convert he using 1
+ funext p
+ cases p <;> rfl
+
+/-- Run the record callback after paying for the probe and before increasing
+its ordinal. The callback may use the saved timestamp words and may update
+the surrounding record buffers. -/
+def withProbe {K : Type} (ports : Port → K) (emit : FiniteRoutine K) : FiniteRoutine K :=
+ ((prepareProbe.onPorts ports).followedBy emit).followedBy (finishProbe.onPorts ports)
+
+theorem withProbe_run {K : Type} [DecidableEq K] {ports : Port → K} (hp : Function.Injective ports)
+ (emit : FiniteRoutine K) (before afterRecord : Stacks K) (H fuelCap fuel call site : ℕ)
+ (cap g c o : Word w) (saved : List Bool) (hg : 0 < g.val) (hc : c.val+1 < 2^w)
+ (ho : o.val+1 < 2^w) (emitTicks : ℕ)
+ (hr : let charged := bank H fuelCap fuel call site cap (Charges.prevWord g) ⟨c.val+1,hc⟩ saved (wordBits o)
+ emit.Runs emitTicks (installStacks ports before charged)
+ (installStacks ports afterRecord charged)) :
+ (withProbe ports emit).Runs (8*w+6 + emitTicks + (4*w+2))
+ (installStacks ports before (bank H fuelCap fuel (call+1) (site+1) cap g c saved (wordBits o)))
+ (installStacks ports afterRecord (bank H fuelCap fuel call site cap (Charges.prevWord g)
+ ⟨c.val+1,hc⟩ saved (wordBits (⟨o.val+1,ho⟩ : Word w)))) := by
+ have h₁ := prepareProbe.runs_onPorts hp before
+ (prepareProbe_run H fuelCap fuel call site cap g c saved (wordBits o) hg hc)
+ have h₂ := finishProbe.runs_onPorts hp afterRecord
+ (finishProbe_bank H fuelCap fuel call site cap (Charges.prevWord g) ⟨c.val+1,hc⟩ o saved ho)
+ exact (h₁.followedBy hr).followedBy h₂
+
+end RAMTape.CallCredit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorProbeFailure.lean b/lean/OAI/Computability/VPVNP/RAMProcessorProbeFailure.lean
new file mode 100644
index 0000000000..72c47f40d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorProbeFailure.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.RAMProcessorProbeReturn
+
+/-!
+# Rejection before or during an external read
+
+An exhausted minimum allowance reaches the charging routine's rejecting row
+before any read guess or emitted record. A permitted read with too few guess
+bits reaches the physical read routine's rejection. Both cases have the
+same native output on arbitrary incident data.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k H F : ℕ} {hw : 2 ≤ w}
+
+theorem read_no_word {bs : List Bool} (h : takeWord w bs = none) : bs.length < w := by
+ induction w generalizing bs with
+ | zero => simp [takeWord] at h
+ | succ w ih =>
+ cases bs with
+ | nil => simp
+ | cons b bs =>
+ cases he : takeWord w bs with
+ | none => simpa using ih he
+ | some z => simp [takeWord, he] at h
+
+private theorem exhausted {s : Snapshot w p r k} (h : allowance s = 0) :
+ s.callLeft = 0 ∨ s.siteLeft = 0 ∨ s.globalLeft.val = 0 ∨ 2^w ≤ s.cost.val+1 := by
+ unfold allowance at h
+ omega
+
+theorem read_no_credit (T : Template p r k) (s : Snapshot w p r k) (ys : List (WordRecord w))
+ (start ord : Word w) (dst addr : Fin r) (next : Fin p) (h : allowance s = 0) :
+ ∃ t ≤ 200*(w+1), Meets T hw H F s ys start ord (.callback (.read dst addr next))
+ (pending T s (.read dst addr next)) t := by
+ have hr := precharge_reject T s (l := .callback (.read dst addr next)) (next := .read dst addr next) rfl (exhausted h)
+ refine ⟨Charges.failureTicks s.callLeft s.siteLeft s.globalLeft, (Charges.failureTicks_le s.callLeft s.siteLeft s.globalLeft).trans (by omega), ?_⟩
+ simpa only [Meets, pending, LocalProcessor.resume, ISA.Callback.action, h] using hr
+
+theorem write_no_credit (T : Template p r k) (s : Snapshot w p r k) (ys : List (WordRecord w))
+ (start ord : Word w) (addr src : Fin r) (next : Fin p) (h : allowance s = 0) :
+ ∃ t ≤ 200*(w+1), Meets T hw H F s ys start ord (.callback (.write addr src next))
+ (pending T s (.write addr src next)) t := by
+ have hr := precharge_reject T s (l := .callback (.write addr src next)) (next := .write addr src next) rfl (exhausted h)
+ refine ⟨Charges.failureTicks s.callLeft s.siteLeft s.globalLeft, (Charges.failureTicks_le s.callLeft s.siteLeft s.globalLeft).trans (by omega), ?_⟩
+ simpa only [Meets, pending, LocalProcessor.resume, ISA.Callback.action, h] using hr
+
+theorem read_no_guess (T : Template p r k) {s : Snapshot w p r k} {ys start ord}
+ (hin : InCall hw H F s ys start ord) (dst addr : Fin r) (next : Fin p)
+ (hc : 0 < allowance s) (hb : takeWord w s.choices = none) :
+ ∃ t ≤ 200*(w+1), Meets T hw H F s ys start ord (.callback (.read dst addr next))
+ (pending T s (.read dst addr next)) t := by
+ have hglobal := hin.global rfl
+ have hcredits : 0 < s.callLeft ∧ 0 < s.globalLeft.val ∧ 0 < s.siteLeft := by
+ unfold allowance at hc
+ omega
+ have hcost : s.cost.val+1 < 2^w := by have := s.cap.isLt; omega
+ have charged := precharge_run T s (l := .callback (.read dst addr next)) (next := .read dst addr next) rfl
+ hcost hcredits.2.1 hcredits.1 hcredits.2.2
+ have hlen := read_no_word hb
+ have fail := read_short T (s.afterCharge hcost) dst addr next hlen
+ have he : allowance s = (allowance s-1)+1 := by omega
+ have hp : pending T s (.read dst addr next) = none := by
+ unfold pending LocalProcessor.resume
+ rw [he]
+ simp only [ISA.Callback.action, hb, Option.bind_none]
+ rw [hp]
+ refine ⟨_, ?_, charged.thenReject fail⟩
+ have hv := hin.value
+ change 8*w+6 + (s.value.length+4*s.choices.length+3) ≤ _
+ omega
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorProbeFields.lean b/lean/OAI/Computability/VPVNP/RAMProcessorProbeFields.lean
new file mode 100644
index 0000000000..928f8a72bb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorProbeFields.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMTapeWordOperands
+
+/-!
+# Staging ports for external reads, writes, and call returns
+
+The architectural bank shares the read destination and the address and value
+registers with the instruction interpreter. Three separate field stacks feed
+the pre-sort record writer. Both copy stacks are empty at every boundary.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ProbeStages
+
+open BurstRAM TapeWord
+
+/-- Non-architectural ports for the choice stream, staged record fields, running flag and two
+copy stacks. -/
+inductive Extra where
+ | choices | tag | address | value | running | copyA | copyB
+ deriving DecidableEq
+
+instance : Fintype Extra := derive_fintype% _
+
+/-- Combined port space for the instruction interpreter and the extra stacks used to stage
+external probes. -/
+abbrev Port (r k : ℕ) := ISA.Port r k ⊕ Extra
+
+/-- Stack contents at a probe-stage boundary, comprising the architectural bank, unused
+choices, staged record fields and running flag. -/
+structure Bank (r k : ℕ) where
+ /-- Architectural register, public-word, persistent-state and interpreter workspace stacks
+ available to the probe stages. -/
+ isa : Stacks (ISA.Port r k)
+ /-- Remaining private bits from which an external read draws its guessed word. -/
+ choices : List Bool
+ /-- Encoded operation tag staged for the next memory record. -/
+ tag : List Bool
+ /-- Bits of the probed address, saved before a read may overwrite its address register. -/
+ address : List Bool
+ /-- Payload bits for the next record, drawn from the choice stream on a read and from a
+ register on a write. -/
+ value : List Bool
+ /-- Stack encoding the site's running flag, which the accept callback sets to false. -/
+ running : List Bool
+
+variable {r k w : ℕ}
+
+/-- Realize the probe-stage bank on the combined port space, supplying empty stacks at both
+copy ports. -/
+def Bank.stacks (s : Bank r k) : Stacks (Port r k)
+ | .inl p => s.isa p
+ | .inr .choices => s.choices
+ | .inr .tag => s.tag
+ | .inr .address => s.address
+ | .inr .value => s.value
+ | .inr .running => s.running
+ | .inr .copyA | .inr .copyB => []
+
+/-- Word transfers for staging register operands, assigning a read result, returning a
+persistent state or forming a record tag. -/
+inductive Transfer (r : ℕ) where
+ | address (i : Fin r) | value (i : Fin r) | assign (i : Fin r) | returnState (i : Fin r) | tag
+
+/-- Source port for a staged word transfer. Tag generation uses the persistent word as its
+width template. -/
+def Transfer.src : Transfer r → Port r k
+ | .address i | .value i | .returnState i => .inl (.reg i)
+ | .assign _ => .inr .value
+ | .tag => .inl .persistent
+
+/-- Port receiving the transfer's word, selected among the record fields, a read destination
+register and persistent state. -/
+def Transfer.dst : Transfer r → Port r k
+ | .address _ => .inr .address
+ | .value _ => .inr .value
+ | .assign i => .inl (.reg i)
+ | .returnState _ => .inl .persistent
+ | .tag => .inr .tag
+
+/-- Install a bit string at the transfer's destination in the structured probe bank. -/
+def Transfer.set (f : Transfer r) (s : Bank r k) (data : List Bool) : Bank r k :=
+ match f with
+ | .address _ => {s with address := data}
+ | .value _ => {s with value := data}
+ | .assign i => {s with isa := Function.update s.isa (.reg i) data}
+ | .returnState _ => {s with isa := Function.update s.isa .persistent data}
+ | .tag => {s with tag := data}
+
+theorem Transfer.set_stacks (f : Transfer r) (s : Bank r k) (data : List Bool) :
+ Function.update s.stacks f.dst data = (f.set s data).stacks := by
+ funext j
+ rcases j with j | j
+ · cases f <;> simp [Transfer.dst, Transfer.set, Bank.stacks, Function.update] <;> split_ifs <;> simp_all <;> subst_vars <;> rfl
+ · cases f <;> cases j <;> rfl
+
+private def ports (f : Transfer r) : ScanPort → Port r k
+ | .left => f.src
+ | .right => .inr .copyA
+ | .tmp => .inr .copyB
+ | .out => f.dst
+
+private theorem injective (f : Transfer r) : Function.Injective (ports (k := k) f) := by
+ intro i j h
+ cases f <;> cases i <;> cases j <;> simp_all [ports, Transfer.src, Transfer.dst]
+
+private def normal {A : Type} : Operand.State A → Bool
+ | .done _ => true
+ | _ => false
+
+private def wordRoutine {A : Type} [Fintype A] (f : Transfer r)
+ (step : A → Bool → Bool × A) (a : A) : FiniteRoutine (Port r k) :=
+ .ofStackCode (Operand.code step) (ports f) (.clear a) normal
+
+private theorem wordRun {A : Type} [Fintype A] (f : Transfer r) (step : A → Bool → Bool × A)
+ (a b : A) (s : Bank r k) (data : List Bool) (n : ℕ)
+ (h : StackRuns (Operand.code step) n (.clear a)
+ (scanStacks (s.stacks f.src) [] [] (s.stacks f.dst)) (.done b)
+ (scanStacks (s.stacks f.src) [] [] data)) :
+ (wordRoutine f step a).Runs n s.stacks (f.set s data).stacks := by
+ rw [← Transfer.set_stacks]
+ refine FiniteRoutine.runs_ofStackCode_framed (injective f) (normal := normal) rfl rfl
+ (fun q hq => ?_) h ?_ ?_ ?_
+ · cases q <;> first | rfl | contradiction
+ · intro i; cases i <;> rfl
+ · intro i
+ cases f <;> cases i <;> simp [ports, Transfer.src, Transfer.dst, scanStacks, Bank.stacks]
+ · intro j hj
+ exact Function.update_of_ne (Ne.symm (hj .out)) ..
+
+/-- Copy a transfer's source word to its destination using the two staging scratch stacks and
+restore the source. -/
+def copy (f : Transfer r) : FiniteRoutine (Port r k) := wordRoutine f Operand.copyBit ()
+
+theorem copy_run (f : Transfer r) (s : Bank r k) :
+ (copy f).Runs ((s.stacks f.dst).length + 7*(s.stacks f.src).length + 3) s.stacks
+ (f.set s (s.stacks f.src)).stacks := wordRun f _ () () s _ _ (Operand.copy_run ..)
+
+/-- Write the literal record tag at the width of the persistent word, reducing the literal
+modulo the word capacity. -/
+def setTag (n : ℕ) : FiniteRoutine (Port r k) :=
+ wordRoutine .tag (Operand.literalBit n) (Fin.last n)
+
+theorem tag_run (n : ℕ) (s : Bank r k) (p : Word w) (hp : s.isa .persistent = wordBits p) :
+ (setTag n).Runs (s.tag.length + 7*w + 3) s.stacks
+ ({s with tag := wordBits (Fin.ofNat (2^w) n)} : Bank r k).stacks := by
+ obtain ⟨b, h⟩ := Operand.literal_run n p s.tag
+ apply wordRun .tag _ (Fin.last n) b s _ _
+ simpa only [Transfer.src, Transfer.dst, Bank.stacks, hp] using h
+
+end RAMTape.ProbeStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorProbePayload.lean b/lean/OAI/Computability/VPVNP/RAMProcessorProbePayload.lean
new file mode 100644
index 0000000000..59c3b52596
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorProbePayload.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.RAMProcessorProbeFields
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+
+/-!
+# Probe record payloads and call returns
+
+External writes copy both source registers to the record fields. External
+reads stage the address before assigning the guessed word to its destination,
+so a read may use the same register for its address and destination. A call
+return copies the next persistent state and signals that the RAM is running.
+An accepting call signals that execution has finished.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ProbeStages
+
+open BurstRAM
+
+variable {r k w : ℕ}
+
+/-- Tag three marks an external write record. -/
+def writePayload (addr src : Fin r) : FiniteRoutine (Port r k) :=
+ ((setTag 3).followedBy (copy (.address addr))).followedBy (copy (.value src))
+
+/-- The write fields contain the register values at the start of the probe. -/
+theorem writePayload_run (addr src : Fin r) (s : Bank r k) (p a v : Word w)
+ (hp : s.isa .persistent = wordBits p) (ha : s.isa (.reg addr) = wordBits a)
+ (hv : s.isa (.reg src) = wordBits v) :
+ (writePayload addr src).Runs (s.tag.length + s.address.length + s.value.length + 21*w + 9)
+ s.stacks ({s with
+ tag := wordBits (Fin.ofNat (2^w) 3), address := wordBits a, value := wordBits v} : Bank r k).stacks := by
+ let tagged : Bank r k := {s with tag := wordBits (Fin.ofNat (2^w) 3)}
+ let addressed : Bank r k := {tagged with address := wordBits a}
+ have tag := tag_run 3 s p hp
+ have address := copy_run (.address addr) tagged
+ have value := copy_run (.value src) addressed
+ simp only [tagged, addressed, Transfer.src, Transfer.dst, Transfer.set, Bank.stacks, ha, hv,
+ length_wordBits] at address value
+ unfold writePayload
+ convert (tag.followedBy address).followedBy value using 1
+ omega
+
+/-- Tag two marks an external read. Copy the old address before assigning
+the guessed word from the value field. -/
+def readPayload (dst addr : Fin r) : FiniteRoutine (Port r k) :=
+ ((setTag 2).followedBy (copy (.address addr))).followedBy (copy (.assign dst))
+
+/-- The read record retains the address, even when the guessed value replaces
+that address in the architectural bank. -/
+theorem readPayload_run (dst addr : Fin r) (s : Bank r k) (p a v : Word w)
+ (hp : s.isa .persistent = wordBits p) (ha : s.isa (.reg addr) = wordBits a)
+ (hv : s.value = wordBits v) :
+ (readPayload dst addr).Runs
+ (s.tag.length + s.address.length + (s.isa (.reg dst)).length + 21*w + 9) s.stacks
+ ({s with tag := wordBits (Fin.ofNat (2^w) 2), address := wordBits a,
+ isa := Function.update s.isa (.reg dst) (wordBits v)} : Bank r k).stacks := by
+ let tagged : Bank r k := {s with tag := wordBits (Fin.ofNat (2^w) 2)}
+ let addressed : Bank r k := {tagged with address := wordBits a}
+ have tag := tag_run 2 s p hp
+ have address := copy_run (.address addr) tagged
+ have assign := copy_run (.assign dst) addressed
+ simp only [tagged, Transfer.src, Transfer.dst, Transfer.set, Bank.stacks, ha, length_wordBits] at address
+ simp only [tagged, addressed, Transfer.src, Transfer.dst, Transfer.set, Bank.stacks] at assign
+ have run := (tag.followedBy address).followedBy assign
+ unfold readPayload
+ simp only [hv, length_wordBits] at run ⊢
+ convert run using 1
+ omega
+
+private def status (b : Bool) : FiniteRoutine (Port r k) :=
+ (SliceArithmetic.CallClear.clear (.inr .running)).followedBy (.ofRoutine (Routine.push (.inr .running) b))
+
+private theorem status_run (b : Bool) (s : Bank r k) :
+ (status b).Runs (s.running.length + 2) s.stacks ({s with running := [b]} : Bank r k).stacks := by
+ let p : Port r k := .inr .running
+ let empty := Function.update s.stacks p []
+ have clear := SliceArithmetic.CallClear.clear_runs p s.stacks
+ have push : (FiniteRoutine.ofRoutine (Routine.push p b)).Runs 1 empty
+ (Function.update empty p (b :: empty p)) := Routine.runs_push p b empty
+ have he : Function.update empty p (b :: empty p) = ({s with running := [b]} : Bank r k).stacks := by
+ funext i
+ rcases i with i | i
+ · rfl
+ · cases i <;> rfl
+ rw [he] at push
+ exact clear.followedBy push
+
+/-- Return a register as the persistent input for the next call. -/
+def returnState (src : Fin r) : FiniteRoutine (Port r k) :=
+ (copy (.returnState src)).followedBy (status true)
+
+theorem returnState_run (src : Fin r) (s : Bank r k) (p v : Word w)
+ (hp : s.isa .persistent = wordBits p) (hv : s.isa (.reg src) = wordBits v) :
+ (returnState src).Runs (8*w + s.running.length + 5) s.stacks
+ ({s with isa := Function.update s.isa .persistent (wordBits v), running := [true]} : Bank r k).stacks := by
+ have state := copy_run (.returnState src) s
+ simp only [Transfer.src, Transfer.dst, Transfer.set, Bank.stacks, hp, hv, length_wordBits] at state
+ have finish := status_run true ({s with isa := Function.update s.isa .persistent (wordBits v)} : Bank r k)
+ unfold returnState
+ convert state.followedBy finish using 1
+ dsimp only
+ omega
+
+/-- A final accepting call writes the stopped status. -/
+def accept : FiniteRoutine (Port r k) := status false
+
+theorem accept_run (s : Bank r k) :
+ accept.Runs (s.running.length + 2) s.stacks ({s with running := [false]} : Bank r k).stacks :=
+ status_run false s
+
+end RAMTape.ProbeStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorProbeReader.lean b/lean/OAI/Computability/VPVNP/RAMProcessorProbeReader.lean
new file mode 100644
index 0000000000..91e5c30d81
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorProbeReader.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.RAMProcessorProbeFields
+import OAI.Computability.VPVNP.RAMProcessorReadWord
+import OAI.Computability.VPVNP.RAMProcessorFlow
+
+/-!
+# External read guesses on the architectural processor bank
+
+The source address word supplies the width. The guessed value is placed in
+the independent record-value field, so its bits cannot overwrite an aliased
+address register before the address is recorded. A short stream exits in
+rejection at the first missing bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ProbeStages
+
+open BurstRAM
+
+variable {r k w : ℕ}
+
+private def readPorts (addr : Fin r) : ProbeWord.Port → Port r k
+ | .template => .inl (.reg addr)
+ | .stream => .inr .choices
+ | .value => .inr .value
+ | .saved => .inr .copyA
+ | .bits => .inr .copyB
+
+private theorem read_inj (addr : Fin r) : Function.Injective (readPorts (k := k) addr) := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [readPorts]
+
+private def readerExits : ProbeWord.State → Option Bool
+ | .done => some true
+ | .reject => some false
+ | _ => none
+
+private theorem reader_active (q : ProbeWord.State) (h : (ProbeWord.code q).returns = false) :
+ readerExits q = none := by cases q <;> first | rfl | contradiction
+
+/-- Read as many private choice bits as there are bits in the address register and stage the
+resulting word. The Boolean exit reports whether the entire word was available. -/
+def reader (addr : Fin r) : Fragment (Port r k) Bool :=
+ (Fragment.fromCode ProbeWord.code .clear readerExits).onPorts (readPorts addr)
+
+private theorem frame (s : Bank r k) (addr : Fin r) (choices value : List Bool) :
+ installStacks (readPorts addr) s.stacks (ProbeWord.bank (s.isa (.reg addr)) choices value [] []) =
+ ({s with choices, value} : Bank r k).stacks := by
+ apply installStacks_frame (read_inj addr)
+ · intro i; cases i <;> rfl
+ · intro i hi
+ rcases i with j | j
+ · rfl
+ · cases j <;> first | rfl | exact (hi .stream rfl).elim | exact (hi .value rfl).elim
+
+/-- Complete-word input preserves the address and leaves the exact unused
+choice suffix. Width zero consumes no choice bits. -/
+theorem reader_run (addr : Fin r) (s : Bank r k) (a v : Word w) (tail : List Bool)
+ (ha : s.isa (.reg addr) = wordBits a) (hs : s.choices = wordBits v ++ tail) :
+ (reader addr).Runs (s.value.length+8*w+4) s.stacks true
+ ({s with choices := tail, value := wordBits v} : Bank r k).stacks := by
+ have h := ProbeWord.read_run (wordBits a) (wordBits v) tail s.value (by simp)
+ rw [length_wordBits, ← hs, ← ha] at h
+ have localRun := Fragment.fromCode_runs readerExits rfl rfl reader_active h
+ have installed := Fragment.runs_onPorts (readPorts addr) (read_inj addr) s.stacks localRun
+ rwa [frame, frame] at installed
+
+/-- Short-word input reaches the rejecting exit without dispatching any
+following instruction. The contents of that rejected branch need no rewind. -/
+theorem reader_short (addr : Fin r) (s : Bank r k) (a : Word w)
+ (ha : s.isa (.reg addr) = wordBits a) (hs : s.choices.length < w) :
+ ∃ out, (reader addr).Runs (s.value.length+4*s.choices.length+3) s.stacks false out := by
+ obtain ⟨out, run⟩ := ProbeWord.short_run (wordBits a) s.choices s.value (by simpa using hs)
+ rw [← ha] at run
+ have localRun := Fragment.fromCode_runs readerExits rfl rfl reader_active run
+ have installed := Fragment.runs_onPorts (readPorts addr) (read_inj addr) s.stacks localRun
+ rw [frame] at installed
+ exact ⟨_, installed⟩
+
+end RAMTape.ProbeStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorProbeReturn.lean b/lean/OAI/Computability/VPVNP/RAMProcessorProbeReturn.lean
new file mode 100644
index 0000000000..c205ec0c83
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorProbeReturn.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.RAMProcessorPending
+
+/-!
+# Splicing a permitted external probe into a completed call
+
+A successful probe contributes one unit of cost and one chronologically
+stamped record. A later rejection remains a rejection even when earlier
+probes wrote records into the site's private buffer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k H F : ℕ} {hw : 2 ≤ w}
+
+/-- Accounting needed to prepend an admitted probe to a call return. It relates the two
+snapshots' budgets and identifies the charged event's timestamped record ahead of the
+continuation. -/
+structure ProbeLink (s u : Snapshot w p r k) (record : WordRecord w) (e : Event w)
+ (start ord nextOrd : Word w) : Prop where
+ pub : u.pub = s.pub
+ H : u.publicH = s.publicH
+ fuelCap : u.publicFuel = s.publicFuel
+ cap : u.cap = s.cap
+ boundary : u.boundary = s.boundary
+ target : u.tests.target = s.tests.target
+ cost : u.cost.val = s.cost.val+1
+ siteLeft : u.siteLeft = s.siteLeft-1
+ eventCharge : ∀ xs, countProbes (e::xs) = 1+countProbes xs
+ recordHead : ∀ xs, eventRecords start.val ord.val (e::xs) =
+ record.record :: eventRecords start.val nextOrd.val xs
+
+theorem CallReturn.afterProbe {s u v : Snapshot w p r k} {rec e start ord nextOrd ys zs rep tail}
+ (link : ProbeLink s u rec e start ord nextOrd)
+ (ret : CallReturn u v (ys++[rec]) zs start nextOrd rep tail) :
+ CallReturn s v ys zs start ord (rep.prepend e) tail := by
+ refine ⟨ret.pub.trans link.pub, ret.H.trans link.H, ret.fuel.trans link.fuelCap,
+ ret.cap.trans link.cap, ret.boundary.trans link.boundary, ret.target.trans link.target, ?_,
+ ret.state, ?_, ret.bits, ?_⟩
+ · simpa only [Report.prepend, Report.probes, link.eventCharge, link.cost, Nat.add_assoc] using ret.cost
+ · simpa only [Report.prepend, Report.probes, link.eventCharge, link.siteLeft, Nat.sub_sub] using ret.siteLeft
+ · simpa only [Report.prepend, link.recordHead, List.map_append, List.map_cons, List.map_nil,
+ List.append_assoc, List.cons_append, List.nil_append] using ret.records
+
+theorem probe_then_segment (T : Template p r k) {s u : Snapshot w p r k} {ys rec start ord nextOrd e cb d t}
+ (step : StackRuns (table T) d (atLabel T (.callback cb)) s.bank (atLabel T (.segment u.cfg.pc)) u.bank)
+ (link : ProbeLink s u rec e start ord nextOrd)
+ (eqout : pending T s cb = LocalProcessor.addEvent e
+ (runLocalCall (T.instantiate w u.pub).logProgram u.fuel u.cfg (allowance u) u.choices).output)
+ (tail : SegmentRun T hw H F u (ys++[rec]) start nextOrd t) :
+ Meets T hw H F s ys start ord (.callback cb) (pending T s cb) (d+t) := by
+ rw [eqout]
+ let out := (runLocalCall (T.instantiate w u.pub).logProgram u.fuel u.cfg (allowance u) u.choices).output
+ change Meets T hw H F u (ys++[rec]) start nextOrd (.segment u.cfg.pc) out t at tail
+ change Meets T hw H F s ys start ord (.callback cb) (LocalProcessor.addEvent e out) (d+t)
+ cases he : out with
+ | none => rw [he] at tail; exact step.thenReject tail
+ | some z =>
+ obtain ⟨rep,bs⟩ := z
+ rw [he] at tail
+ obtain ⟨v,zs,ready,ret,run⟩ := tail
+ exact ⟨v, zs, ready, ret.afterProbe link, step.trans run⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorProbeStages.lean b/lean/OAI/Computability/VPVNP/RAMProcessorProbeStages.lean
new file mode 100644
index 0000000000..7c2cf58259
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorProbeStages.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.RAMProcessorProbeReader
+import OAI.Computability.VPVNP.RAMProcessorProbePayload
+import OAI.Computability.VPVNP.RAMProcessorGuardedPayload
+
+/-!
+# External-probe stages of the burst processor
+
+Only a complete guessed word enters the register-update and record staging
+routine. The successful path consumes exactly that word and preserves the
+rest of the private stream. A write consumes no private bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ProbeStages
+
+open BurstRAM
+
+variable {r k w : ℕ} {L : Type}
+
+/-- On a read, resume at the caller's successful label or short-input label. -/
+def read (dst addr : Fin r) (next reject : L) : Fragment (Port r k) L :=
+ (reader addr).withPayload (readPayload dst addr) next reject
+
+theorem read_run (dst addr : Fin r) (next reject : L) (s : Bank r k) (p a v : Word w) (tail : List Bool)
+ (hp : s.isa .persistent = wordBits p) (ha : s.isa (.reg addr) = wordBits a)
+ (hs : s.choices = wordBits v ++ tail) :
+ (read dst addr next reject).Runs
+ (s.value.length+s.tag.length+s.address.length+(s.isa (.reg dst)).length+29*w+13) s.stacks next
+ ({s with
+ choices := tail, value := wordBits v, tag := wordBits (Fin.ofNat (2^w) 2),
+ address := wordBits a, isa := Function.update s.isa (.reg dst) (wordBits v)} : Bank r k).stacks := by
+ let staged : Bank r k := {s with choices := tail, value := wordBits v}
+ have word := reader_run addr s a v tail ha hs
+ have payload := readPayload_run dst addr staged p a v hp ha rfl
+ have result := Fragment.withPayload_ok next reject word payload
+ dsimp only [staged] at result
+ unfold read
+ convert result using 1
+ omega
+
+theorem read_short (dst addr : Fin r) (next reject : L) (s : Bank r k) (a : Word w)
+ (ha : s.isa (.reg addr) = wordBits a) (hs : s.choices.length < w) :
+ ∃ out, (read dst addr next reject).Runs (s.value.length+4*s.choices.length+3) s.stacks reject out := by
+ obtain ⟨out, run⟩ := reader_short addr s a ha hs
+ exact ⟨out, Fragment.withPayload_reject (readPayload dst addr) next reject run⟩
+
+/-- In a normal architectural bank the destination is one word, and the
+record fields are empty or left over from a single preceding record. -/
+theorem read_work_le (dst : Fin r) (s : Bank r k)
+ (hv : s.value.length ≤ w) (ht : s.tag.length ≤ w) (ha : s.address.length ≤ w)
+ (hd : (s.isa (.reg dst)).length ≤ w) :
+ s.value.length+s.tag.length+s.address.length+(s.isa (.reg dst)).length+29*w+13 ≤ 33*w+13 := by omega
+
+theorem write_work_le (s : Bank r k)
+ (hv : s.value.length ≤ w) (ht : s.tag.length ≤ w) (ha : s.address.length ≤ w) :
+ s.tag.length+s.address.length+s.value.length+21*w+9 ≤ 24*w+9 := by omega
+
+end RAMTape.ProbeStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorProbeStep.lean b/lean/OAI/Computability/VPVNP/RAMProcessorProbeStep.lean
new file mode 100644
index 0000000000..22337d3a66
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorProbeStep.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.RAMProcessorReportPrefix
+import OAI.Computability.VPVNP.RAMProcessorGraphProbe
+import OAI.Computability.VPVNP.RAMProcessorGraphProbeEmit
+import OAI.Computability.VPVNP.RAMProcessorGraphCredit
+
+/-!
+# Executing one charged probe inside the physical call
+
+The four transfers from the instruction callback to the next instruction
+charge the budgets, stage the address and value, append the record, and
+advance its ordinal. The recorded address is always read from the original
+register bank, including when a read overwrites its own address register.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k H F : ℕ} {hw : 2 ≤ w}
+
+/-- One external read or write with its successor instruction. A read also specifies the
+guessed word and the choice suffix left after consuming it. -/
+inductive ProbeStep (w p r : ℕ) where
+ | read (dst addr : Fin r) (next : Fin p) (v : Word w) (tail : List Bool)
+ | write (addr src : Fin r) (next : Fin p)
+
+namespace ProbeStep
+
+/-- Private program counter at which execution resumes after the read or write. -/
+def next : ProbeStep w p r → Fin p
+ | .read _ _ pc _ _ | .write _ _ pc => pc
+
+/-- Interpreter callback for the probe, retaining its register operands and successor
+instruction. -/
+def callback : ProbeStep w p r → ISA.Callback p r
+ | .read d a pc _ _ => .read d a pc
+ | .write a v pc => .write a v pc
+
+/-- Choice-stream condition for staging a probe. A read requires the encoded guessed word
+followed by the declared suffix, and every write satisfies the condition. -/
+def accepts (a : ProbeStep w p r) (s : Snapshot w p r k) : Prop :=
+ match a with
+ | .read _ _ _ v tail => s.choices = BurstRAM.wordBits v ++ tail
+ | .write .. => True
+
+/-- Five-word record of the probe, with operation tag, original address, read or write value,
+call start and current ordinal. -/
+def record (a : ProbeStep w p r) (s : Snapshot w p r k) (start ord : Word w) : WordRecord w :=
+ match a with
+ | .read _ addr _ v _ => ⟨.read,s.cfg.reg addr,v,start,ord⟩
+ | .write addr src _ => ⟨.write,s.cfg.reg addr,s.cfg.reg src,start,ord⟩
+
+/-- Stage the probe payload and advance the private program counter. A read also installs the
+guessed word in its destination and consumes the corresponding choice bits. -/
+def stage (a : ProbeStep w p r) (s : Snapshot w p r k) : Snapshot w p r k :=
+ match a with
+ | .read d addr pc v tail => s.afterRead d addr pc v tail
+ | .write addr src pc => s.afterWrite addr src pc
+
+/-- Complete the probe by charging its cost, staging the payload, emitting the timestamped
+record and incrementing the ordinal. -/
+def finish (a : ProbeStep w p r) (s : Snapshot w p r k) (hw : 2 ≤ w) (start ord : Word w)
+ (hc : s.cost.val+1 < 2^w) (ho : ord.val+1 < 2^w) : Snapshot w p r k :=
+ ((a.stage (s.afterCharge hc)).afterEmit hw (a.record s start ord)).afterIncrement ord ho
+
+end ProbeStep
+
+variable {s : Snapshot w p r k} {ys : List (WordRecord w)} {start ord : Word w}
+
+theorem InCall.costRoom (h : InCall hw H F s ys start ord) (hp : 0 < allowance s) : s.cost.val+1 < 2^w := by
+ have hb := h.global rfl
+ have hg : 0 < s.globalLeft.val := by unfold allowance at hp; omega
+ have hc := s.cap.isLt
+ omega
+
+theorem InCall.ordRoom (h : InCall hw H F s ys start ord) : ord.val+1 < 2^w := by
+ have ht := h.timestamp
+ have hc := s.cost.isLt
+ omega
+
+namespace ProbeStep
+
+variable (a : ProbeStep w p r)
+
+theorem finish_allowance (s : Snapshot w p r k) (hw : 2 ≤ w) (start ord : Word w) (hc ho)
+ (hp : 0 < allowance s) : allowance (a.finish s hw start ord hc ho) = allowance s - 1 := by
+ cases a <;> change min (s.callLeft-1) (min (s.globalLeft.val-1) (s.siteLeft-1)) = allowance s - 1
+ all_goals unfold allowance at *; omega
+
+private theorem stage_buffer (hc) (h : RecordBuffer.Holds hw H ys s.records) :
+ RecordBuffer.Holds hw H ys (a.stage (s.afterCharge hc)).records := by
+ cases a <;> exact ⟨h.fit,rfl,rfl,h.remaining,h.buffer,h.output⟩
+
+private theorem staged_fields (hc) (hs : s.savedStart = BurstRAM.wordBits start)
+ (ho : s.ordinal = BurstRAM.wordBits ord) (j : Fin 5) :
+ (a.stage (s.afterCharge hc)).records (.field j) =
+ BurstRAM.wordBits ((recordFormat hw).words (some (a.record s start ord)) j) := by
+ have hfour : 4 ≤ 2^w := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ cases a <;> fin_cases j <;> try first | rfl | exact hs | exact ho
+ all_goals
+ apply congrArg BurstRAM.wordBits
+ apply Fin.ext
+ exact Nat.mod_eq_of_lt (by first | exact (by decide : 2 < 4).trans_le hfour | exact (by decide : 3 < 4).trans_le hfour)
+
+private theorem finish_inCall (hin : InCall hw H F s ys start ord) (hp : 0 < allowance s)
+ (hb : RecordBuffer.Holds hw H (ys++[a.record s start ord])
+ ((a.stage (s.afterCharge (hin.costRoom hp))).afterEmit hw (a.record s start ord)).records) :
+ InCall hw H F (a.finish s hw start ord (hin.costRoom hp) hin.ordRoom) (ys++[a.record s start ord])
+ start ⟨ord.val+1,hin.ordRoom⟩ := by
+ have hroom := hin.room
+ have ht := hin.timestamp
+ have hg := hin.global rfl
+ have hl : 0 < s.siteLeft := by unfold allowance at hp; omega
+ have hgpos : 0 < s.globalLeft.val := by unfold allowance at hp; omega
+ cases a <;>
+ refine ⟨?_,hin.savedEq,rfl,by change start.val + (1+(ord.val+1)) = s.cost.val+1; omega⟩ <;>
+ refine ⟨hin.publicH,hin.publicFuel,hin.positive,hin.boundary,?_,?_,hin.privateClock,?_,hin.saved,?_,?_,?_,?_,?_,?_,⟩
+ all_goals first
+ | (change (ys++[_]).length + (s.siteLeft-1) ≤ _; simp only [List.length_append, List.length_singleton]; omega)
+ | exact ⟨hb.fit,rfl,rfl,hb.remaining,hb.buffer,hb.output⟩
+ | exact (Nat.sub_le _ _).trans hin.callCredit
+ | exact (BurstRAM.length_wordBits _).le
+ | (intro _; change s.globalLeft.val-1+(s.cost.val+1) = s.cap.val; omega)
+ | (intro h; contradiction)
+
+/-- One external action on the literal graph from the callback to the next
+instruction, including the emitted record and both timestamp fields. -/
+theorem run (T : Template p r k) (hin : InCall hw H F s ys start ord)
+ (hpos : 0 < allowance s) (hbits : a.accepts s) :
+ let u := a.finish s hw start ord (hin.costRoom hpos) hin.ordRoom
+ ∃ t ≤ 200*(w+1), StackRuns (table T) t (atLabel T (.callback a.callback)) s.bank
+ (atLabel T (.segment a.next)) u.bank ∧
+ InCall hw H F u (ys++[a.record s start ord]) start ⟨ord.val+1,hin.ordRoom⟩ := by
+ let c := s.afterCharge (hin.costRoom hpos)
+ let b := a.stage c
+ let recd := a.record s start ord
+ let e := b.afterEmit hw recd
+ have hglobal : 0 < s.globalLeft.val := by unfold allowance at hpos; omega
+ have hcall : 0 < s.callLeft := by unfold allowance at hpos; omega
+ have hsite : 0 < s.siteLeft := by unfold allowance at hpos; omega
+ have hroom := hin.room
+ have hbuf := a.stage_buffer (hin.costRoom hpos) hin.buffer
+ have ⟨emit,hout⟩ := emit_run T b hw a.next hbuf (by omega) recd
+ (a.staged_fields (hin.costRoom hpos) hin.savedEq hin.ordinalEq)
+ have he : e.ordinal = BurstRAM.wordBits ord := by cases a <;> exact hin.ordinalEq
+ have inc := increment_run T e a.next ord he hin.ordRoom
+ have hin' := a.finish_inCall hin hpos hout
+ have ht := hin.tag
+ have hv := hin.value
+ have ha := hin.address
+ cases a with
+ | read dst addr pc v tail =>
+ have charge := precharge_run T s (l := .callback (.read dst addr pc)) (next := .read dst addr pc)
+ rfl (hin.costRoom hpos) hglobal hcall hsite
+ have payload := read_run T c dst addr pc v tail hbits
+ refine ⟨_, ?_, ((charge.trans payload).trans emit).trans inc, hin'⟩
+ change 8*w+6 + (s.value.length+s.tag.length+s.address.length+30*w+13) + (25*w+12) + (4*w+2) ≤ _
+ omega
+ | write addr src pc =>
+ have charge := precharge_run T s (l := .callback (.write addr src pc)) (next := .write addr src pc)
+ rfl (hin.costRoom hpos) hglobal hcall hsite
+ have payload := write_run T c addr src pc
+ refine ⟨_, ?_, ((charge.trans payload).trans emit).trans inc, hin'⟩
+ change 8*w+6 + (s.tag.length+s.address.length+s.value.length+21*w+9) + (25*w+12) + (4*w+2) ≤ _
+ omega
+
+end ProbeStep
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorReadWord.lean b/lean/OAI/Computability/VPVNP/RAMProcessorReadWord.lean
new file mode 100644
index 0000000000..12547f4893
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorReadWord.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.RAMTapeISAPorts
+
+/-!
+# Taking one external read guess on bit stacks
+
+The template word determines the number of bits to take from the private
+choice stream. The reader restores that template and writes the guessed word
+in its original order. Exhausting the stream early reaches a rejecting row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ProbeWord
+
+/-- Stacks holding the width template, choice stream, output value, saved template bits and
+collected guess bits of the read-guess routine. -/
+inductive Port | template | stream | value | saved | bits
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Control states for clearing an old value, pairing each template bit with a guessed bit,
+restoring the template and emitting the guessed word. -/
+inductive State
+ | clear | scan | read (widthBit : Bool) | save (widthBit guess : Bool) | collect (guess : Bool)
+ | restore | putWidth (b : Bool) | output | putBit (b : Bool) | done | reject
+ deriving DecidableEq, Fintype
+
+/-- Stack instruction table that consumes one choice per template bit, restores the template
+and writes the guess in its original order. A short choice stream reaches the rejecting
+row. -/
+def code : StackCode Port State
+ | .clear => .pop .value fun b => if b.isSome then .clear else .scan
+ | .scan => .pop .template fun b => b.elim .restore .read
+ | .read w => .pop .stream fun b => b.elim .reject (.save w)
+ | .save w b => .push .saved w (.collect b)
+ | .collect b => .push .bits b .scan
+ | .restore => .pop .saved fun b => b.elim .output .putWidth
+ | .putWidth b => .push .template b .restore
+ | .output => .pop .bits fun b => b.elim .done .putBit
+ | .putBit b => .push .value b .output
+ | .done => .halt true
+ | .reject => .halt false
+
+/-- Place the template word, choice stream, current value and the two partially collected bit
+lists on their respective reader ports. -/
+def bank (w bs val saved collected : List Bool) : Stacks Port
+ | .template => w
+ | .stream => bs
+ | .value => val
+ | .saved => saved
+ | .bits => collected
+
+private theorem at_port (w bs val saved collected new : List Bool) (i : Port) :
+ Function.update (bank w bs val saved collected) i new =
+ match i with
+ | .template => bank new bs val saved collected
+ | .stream => bank w new val saved collected
+ | .value => bank w bs new saved collected
+ | .saved => bank w bs val new collected
+ | .bits => bank w bs val saved new := by
+ funext j
+ cases i <;> cases j <;> rfl
+
+local macro "stepPop" : tactic => `(tactic|
+ refine StackRuns.cons (StackStep.pop (show code _ = .pop _ _ from rfl)) ?_ <;>
+ simp only [at_port, bank, List.head?_nil, List.head?_cons, List.tail_nil, List.tail_cons,
+ Option.elim_none, Option.elim_some, Option.isSome_none, Option.isSome_some, ↓reduceIte])
+local macro "stepPush" : tactic => `(tactic|
+ refine StackRuns.cons (StackStep.push (show code _ = .push _ _ _ from rfl)) ?_ <;>
+ simp only [at_port, bank])
+
+private theorem clear_run (w bs val : List Bool) :
+ StackRuns code (val.length+1) .clear (bank w bs val [] []) .scan (bank w bs [] [] []) := by
+ induction val with
+ | nil => stepPop; exact .nil ..
+ | cons b val ih => stepPop; exact ih
+
+private theorem restore_run (w bs val saved collected : List Bool) :
+ StackRuns code (2*saved.length+1) .restore (bank w bs val saved collected)
+ .output (bank (saved.reverse ++ w) bs val [] collected) := by
+ induction saved generalizing w with
+ | nil => stepPop; exact .nil ..
+ | cons b saved ih =>
+ rw [List.length_cons, Nat.mul_succ, show 2*saved.length+2+1 = (2*saved.length+1)+1+1 by omega]
+ stepPop
+ stepPush
+ simpa [List.append_assoc] using ih (b::w)
+
+private theorem output_run (w bs val collected : List Bool) :
+ StackRuns code (2*collected.length+1) .output (bank w bs val [] collected)
+ .done (bank w bs (collected.reverse ++ val) [] []) := by
+ induction collected generalizing val with
+ | nil => stepPop; exact .nil ..
+ | cons b collected ih =>
+ rw [List.length_cons, Nat.mul_succ, show 2*collected.length+2+1 = (2*collected.length+1)+1+1 by omega]
+ stepPop
+ stepPush
+ simpa [List.append_assoc] using ih (b::val)
+
+private theorem collect_run (w data tail saved collected : List Bool) (h : data.length = w.length) :
+ StackRuns code (4*w.length+1) .scan (bank w (data ++ tail) [] saved collected)
+ .restore (bank [] tail [] (w.reverse ++ saved) (data.reverse ++ collected)) := by
+ induction w generalizing data saved collected with
+ | nil =>
+ have hd : data = [] := by simpa using h
+ subst data
+ stepPop
+ exact .nil ..
+ | cons a w ih =>
+ cases data with
+ | nil => simp at h
+ | cons b data =>
+ rw [List.length_cons, Nat.mul_succ, show 4*w.length+4+1 = (4*w.length+1)+1+1+1+1 by omega]
+ simp only [List.cons_append]
+ stepPop
+ stepPop
+ stepPush
+ stepPush
+ simpa [List.append_assoc] using ih data (a::saved) (b::collected) (by simpa using h)
+
+theorem read_run (w data tail old : List Bool) (h : data.length = w.length) :
+ StackRuns code (old.length+8*w.length+4) .clear (bank w (data ++ tail) old [] [])
+ .done (bank w tail data [] []) := by
+ have h₁ := clear_run w (data ++ tail) old
+ have h₂ := collect_run w data tail [] [] h
+ have h₃ := restore_run [] tail [] w.reverse data.reverse
+ have h₄ := output_run w tail [] data.reverse
+ simp only [List.append_nil, List.length_reverse, List.reverse_reverse, h] at h₂ h₃ h₄
+ have run := ((h₁.trans h₂).trans h₃).trans h₄
+ convert run using 1
+ omega
+
+private theorem collect_short (w bs saved collected : List Bool) (h : bs.length < w.length) :
+ ∃ out, StackRuns code (4*bs.length+2) .scan (bank w bs [] saved collected) .reject out := by
+ induction bs generalizing w saved collected with
+ | nil =>
+ cases w with
+ | nil => simp at h
+ | cons a w => refine ⟨bank w [] [] saved collected, ?_⟩; stepPop; stepPop; exact .nil ..
+ | cons b bs ih =>
+ cases w with
+ | nil => simp at h
+ | cons a w =>
+ obtain ⟨out, run⟩ := ih w (a::saved) (b::collected) (by simpa using h)
+ refine ⟨out, ?_⟩
+ rw [List.length_cons, Nat.mul_succ, show 4*bs.length+4+2 = (4*bs.length+2)+1+1+1+1 by omega]
+ stepPop
+ stepPop
+ stepPush
+ stepPush
+ exact run
+
+theorem short_run (w bs old : List Bool) (h : bs.length < w.length) :
+ ∃ out, StackRuns code (old.length+4*bs.length+3) .clear (bank w bs old [] []) .reject out := by
+ obtain ⟨out, run⟩ := collect_short w bs [] [] h
+ refine ⟨out, ?_⟩
+ convert (clear_run w bs old).trans run using 1
+ omega
+
+end RAMTape.ProbeWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorReportPrefix.lean b/lean/OAI/Computability/VPVNP/RAMProcessorReportPrefix.lean
new file mode 100644
index 0000000000..fcfed83978
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorReportPrefix.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.RAMProcessorScanBounds
+import OAI.Computability.VPVNP.RAMProcessorCallInvariant
+
+/-!
+# Returning a private event prefix from a physical call segment
+
+The internal instruction scan contributes ticks and private branch choices to
+the report. Its prefix consumes no external probes, so it leaves the costs,
+record timestamps, and emitted slots of the external continuation intact.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ}
+
+theorem countProbes_append (xs ys : List (Event w)) :
+ countProbes (xs++ys) = countProbes xs + countProbes ys := by
+ induction xs with
+ | nil => simp [countProbes]
+ | cons x xs ih => cases x <;> simp [countProbes, ih, Nat.add_assoc]
+
+theorem eventRecords_append (start ord : ℕ) (xs ys : List (Event w)) :
+ eventRecords start ord (xs++ys) = eventRecords start ord xs ++
+ eventRecords start (ord+countProbes xs) ys := by
+ induction xs generalizing ord with
+ | nil => simp [eventRecords, countProbes]
+ | cons x xs ih => cases x <;> simp [eventRecords, countProbes, ih, Nat.add_assoc]
+
+/-- Prepend an ordered event prefix to a call report and retain its final result. -/
+def Report.withEvents (prefixEvents : List (Event w)) (r : Report w) : Report w :=
+ ⟨prefixEvents++r.events, r.result⟩
+
+end BurstRAM
+
+namespace RAMTape.LocalProcessor
+
+open BurstRAM PrivateRAM
+
+variable {w p r k : ℕ}
+
+theorem addEvents_eq (xs : List (Event w)) (out : Output w) :
+ addEvents xs out = out.map (fun z => (z.1.withEvents xs, z.2)) := by
+ induction xs with
+ | nil => cases out <;> simp [addEvents, Report.withEvents]
+ | cons e xs ih =>
+ cases out with
+ | none => simp [addEvents, ih, addEvent]
+ | some z => rcases z with ⟨r,bs⟩; simp [addEvents, ih, addEvent, Report.withEvents, Report.prepend]
+
+theorem scan_probeCount (T : Template p r k) (pub : Fin k → Word w) (f : ℕ)
+ (c : LogConfig w p r) (bs : List Bool) :
+ countProbes (scan T pub f c bs).prefixEvents = 0 := by
+ rw [← length_eventRecords 0 0, scan_no_probes]
+ rfl
+
+end RAMTape.LocalProcessor
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k H F : ℕ} {hw : 2 ≤ w}
+
+/-- Number of further probes admitted by all three budgets, the minimum of the remaining call,
+global and site credits. -/
+def allowance (s : Snapshot w p r k) := min s.callLeft (min s.globalLeft.val s.siteLeft)
+
+theorem InCall.afterLocal (T : Template p r k) {s : Snapshot w p r k} {ys start ord}
+ (hin : InCall hw H F s ys start ord) :
+ InCall hw H F (s.afterLocal (LocalProcessor.scan T s.pub s.fuel s.cfg s.choices)) ys start ord := by
+ let y := LocalProcessor.scan T s.pub s.fuel s.cfg s.choices
+ have hpc := (LocalProcessor.scan_writes_le T s.pub s.fuel s.cfg s.choices).trans hin.privateClock
+ refine ⟨?_, hin.savedEq, hin.ordinalEq, hin.timestamp⟩
+ exact {hin.toCallReady with privateClock := hpc, buffer := {
+ fit := hin.buffer.fit, scratch := rfl, zeros := rfl, remaining := hin.buffer.remaining,
+ buffer := hin.buffer.buffer, output := hin.buffer.output }}
+
+theorem CallReturn.privatePrefix (T : Template p r k) {s u : Snapshot w p r k} {ys zs start ord r tail}
+ (h : CallReturn (s.afterLocal (LocalProcessor.scan T s.pub s.fuel s.cfg s.choices)) u ys zs start ord r tail) :
+ CallReturn s u ys zs start ord (r.withEvents (LocalProcessor.scan T s.pub s.fuel s.cfg s.choices).prefixEvents) tail := by
+ have hz := LocalProcessor.scan_probeCount T s.pub s.fuel s.cfg s.choices
+ have hn := LocalProcessor.scan_no_probes T s.pub s.fuel s.cfg s.choices start.val ord.val
+ refine ⟨h.pub, h.H, h.fuel, h.cap, h.boundary, ?_, ?_, h.state, ?_, h.bits, ?_⟩
+ · exact h.target
+ · simpa [Snapshot.afterLocal, Report.probes, Report.withEvents, countProbes_append, hz] using h.cost
+ · simpa [Snapshot.afterLocal, Report.probes, Report.withEvents, countProbes_append, hz] using h.siteLeft
+ · simpa [Report.withEvents, eventRecords_append, hn, hz] using h.records
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorReset.lean b/lean/OAI/Computability/VPVNP/RAMProcessorReset.lean
new file mode 100644
index 0000000000..16251a9feb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorReset.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.RAMTapeWordISAClear
+
+/-!
+# Fresh private workspace at every burst call
+
+A call starts with one persistent word and its public constants. The processor
+overwrites every private register with a width-correct zero and clears the
+newest-first write log. Its cost depends on the stored entries, including for
+the first call where the physical register stacks may be empty.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {r k w : ℕ}
+
+private def zeroList : List (Fin r) → FiniteRoutine (Port r k)
+ | [] => .ret
+ | i :: is => (loadLiteral 0 i).followedBy (zeroList is)
+
+private def zeroed (is : List (Fin r)) (s : Stacks (Port r k)) : Stacks (Port r k)
+ | .reg i => if i ∈ is then wordBits (0 : Word w) else s (.reg i)
+ | j => s j
+
+private theorem zeroList_run (is : List (Fin r)) (s : Stacks (Port r k)) (persist : Word w)
+ (hp : s .persistent = wordBits persist) (h14 : s (.work 14) = []) (h15 : s (.work 15) = [])
+ (hr : ∀ i, (s (.reg i)).length ≤ w) :
+ ∃ t ≤ is.length * (8*w+3) + 1, (zeroList is).Runs t s (zeroed (w := w) is s) := by
+ induction is generalizing s with
+ | nil =>
+ have he : zeroed (w := w) [] s = s := by funext j; cases j <;> simp [zeroed]
+ exact ⟨1, by simp, he.symm ▸ Routine.runs_ret s⟩
+ | cons i is ih =>
+ let s' := Function.update s (.reg i) (wordBits (0 : Word w))
+ have hhead : (loadLiteral 0 i).Runs ((s (.reg i)).length + 7*w+3) s s' :=
+ loadLiteral_at 0 i s persist hp h14 h15
+ obtain ⟨t, ht, htail⟩ := ih s' (by simpa [s'] using hp) (by simpa [s'] using h14)
+ (by simpa [s'] using h15) (fun j => by
+ by_cases he : i = j
+ · subst j; simp [s']
+ · simpa [s', Function.update_of_ne (show Port.reg j ≠ (Port.reg i : Port r k) by
+ intro h; exact he (Port.reg.inj h).symm)] using hr j)
+ have he : zeroed (w := w) is s' = zeroed (w := w) (i :: is) s := by
+ funext j
+ cases j with
+ | reg j => by_cases hji : j = i <;> simp [zeroed, s', hji, Function.update_of_ne]
+ | pub | persistent | work | logPort => simp [zeroed, s']
+ rw [he] at htail
+ refine ⟨_, ?_, hhead.followedBy htail⟩
+ have := hr i
+ simp only [List.length_cons, Nat.add_mul, Nat.one_mul]
+ omega
+
+private def logPorts : List (Port r k) := [.logPort .keys, .logPort .values, .logPort .occupied]
+
+/-- Start a private call with width-correct zeroes in all registers and clear the write log's
+key, value and occupancy streams. -/
+def freshCall : FiniteRoutine (Port r k) :=
+ (zeroList (List.finRange r)).followedBy (clearList logPorts)
+
+/-- Before a call the private register bank may still contain bits from a
+previous call. The three log streams have a bounded total entry count. -/
+def preCall (pub : Fin k → Word w) (persistent : Word w) (raw : Fin r → List Bool)
+ (log : WriteLog w) : Stacks (Port r k)
+ | .reg i => raw i
+ | .pub i => wordBits (pub i)
+ | .persistent => wordBits persistent
+ | .work _ => []
+ | .logPort i => logStacks log i
+
+theorem freshCall_run (pub : Fin k → Word w) (persistent : Word w) (raw : Fin r → List Bool)
+ (log : WriteLog w) (hr : ∀ i, (raw i).length ≤ w) :
+ ∃ t ≤ r*(8*w+3)+3*(log.length*(w+1)+1)+2,
+ (freshCall (r := r) (k := k)).Runs t (preCall pub persistent raw log)
+ (bank pub persistent (fun _ => 0) []) := by
+ let s := preCall pub persistent raw log
+ let z := zeroed (w := w) (List.finRange r) s
+ have hz := zeroList_run (List.finRange r) s persistent rfl rfl rfl hr
+ obtain ⟨a, ha, h₁⟩ := hz
+ have hl (l : WriteLog w) : (AddressLog.keys l).length = l.length*w ∧
+ (AddressLog.values l).length = l.length*w := by
+ induction l with
+ | nil => simp [AddressLog.keys, AddressLog.values]
+ | cons pair xs ih =>
+ change (wordBits pair.1 ++ AddressLog.keys xs).length = (xs.length+1)*w ∧
+ (wordBits pair.2 ++ AddressLog.values xs).length = (xs.length+1)*w
+ simp [ih.1, ih.2, Nat.add_mul, Nat.add_comm]
+ have hc : ∀ j ∈ logPorts, (z j).length ≤ log.length*(w+1) := by
+ intro j hj
+ have ⟨hk, hv⟩ := hl log
+ rcases (show j = .logPort .keys ∨ j = .logPort .values ∨ j = .logPort .occupied by
+ simpa [logPorts] using hj) with rfl | rfl | rfl <;>
+ simp [z, zeroed, s, preCall, logStacks, hk, hv, Nat.mul_succ]
+ obtain ⟨b, hb, h₂⟩ := clearList_runs logPorts z (log.length*(w+1)) hc
+ have he : cleared logPorts z = bank pub persistent (fun _ => 0) [] := by
+ funext j
+ cases j with
+ | reg j | pub j | work j => simp [z, s, zeroed, cleared, logPorts, preCall, bank]
+ | persistent => simp [z, s, zeroed, cleared, logPorts, preCall, bank]
+ | logPort j => cases j <;> simp [z, s, zeroed, cleared, logPorts, preCall, bank, logStacks,
+ AddressLog.keys, AddressLog.values]
+ rw [he] at h₂
+ refine ⟨_, ?_, h₁.followedBy h₂⟩
+ simp only [List.length_finRange] at ha
+ change b ≤ 3*(log.length*(w+1)+1)+1 at hb
+ omega
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorScanBounds.lean b/lean/OAI/Computability/VPVNP/RAMProcessorScanBounds.lean
new file mode 100644
index 0000000000..2db01363ca
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorScanBounds.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.RAMProcessorLocalResult
+
+/-!
+# Bounds and emitted events of a private segment
+
+A returned segment has no internal probe records. Every terminal or external
+instruction consumes a fuel unit. The remaining fuel also bounds the total
+growth of the private log when several segments are executed in one call.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.LocalProcessor
+
+open BurstRAM PrivateRAM
+
+variable {w p r k : ℕ}
+
+/-- Callbacks that return control from the private scan to the site processor, namely external
+reads or writes, state returns, acceptance and rejection. -/
+def externalOrTerminal : ISA.Callback p r → Prop
+ | .next _ | .choose _ _ => False
+ | _ => True
+
+theorem scan_bounds (T : Template p r k) (pub : Fin k → Word w) (f : ℕ)
+ (c : LogConfig w p r) (bs : List Bool) :
+ let y := scan T pub f c bs
+ y.fuel ≤ f ∧ (y.exit ≠ .reject → y.fuel < f) ∧ externalOrTerminal y.exit ∧
+ y.cfg.writes.length + y.fuel ≤ c.writes.length + f ∧
+ (∀ start ord, eventRecords start ord y.prefixEvents = []) := by
+ induction f generalizing c bs with
+ | zero => simp [scan, eventRecords, externalOrTerminal]
+ | succ f ih =>
+ let out := instructionPost T pub c
+ have hg : out.writes.length ≤ c.writes.length + 1 := ISA.post_writes_length_le ..
+ dsimp only
+ rw [scan]
+ cases h : instructionExit T c with
+ | next j =>
+ obtain ⟨hf, _, he, hl, hrec⟩ := ih {out with pc := j} bs
+ simp only [Yield.prepend, eventRecords]
+ dsimp only [out] at hf hl hg ⊢
+ exact ⟨by omega, fun _ => by omega, he, by omega, hrec⟩
+ | choose yes no =>
+ cases bs with
+ | nil => dsimp only; exact ⟨by omega, fun _ => by omega, trivial, by change out.writes.length+f ≤ _; omega, fun _ _ => rfl⟩
+ | cons b bs =>
+ obtain ⟨hf, _, he, hl, hrec⟩ := ih {out with pc := if b then yes else no} bs
+ simp only [Yield.prepend, eventRecords]
+ dsimp only [out] at hf hl hg ⊢
+ exact ⟨by omega, fun _ => by omega, he, by omega, hrec⟩
+ | read _ _ _ | write _ _ _ | accept | returnState _ | reject =>
+ dsimp only
+ exact ⟨by omega, fun _ => by omega, trivial, by change out.writes.length+f ≤ _; omega, fun _ _ => rfl⟩
+
+theorem scan_fuel_lt (T : Template p r k) (pub : Fin k → Word w) (f : ℕ)
+ (c : LogConfig w p r) (bs : List Bool) (h : (scan T pub f c bs).exit ≠ .reject) :
+ (scan T pub f c bs).fuel < f := (scan_bounds ..).2.1 h
+
+theorem scan_writes_le (T : Template p r k) (pub : Fin k → Word w) (f : ℕ)
+ (c : LogConfig w p r) (bs : List Bool) :
+ let y := scan T pub f c bs
+ y.cfg.writes.length + y.fuel ≤ c.writes.length + f := (scan_bounds ..).2.2.2.1
+
+theorem scan_no_probes (T : Template p r k) (pub : Fin k → Word w) (f : ℕ)
+ (c : LogConfig w p r) (bs : List Bool) (start ord : ℕ) :
+ eventRecords start ord (scan T pub f c bs).prefixEvents = [] := (scan_bounds ..).2.2.2.2 start ord
+
+end RAMTape.LocalProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorSiteClose.lean b/lean/OAI/Computability/VPVNP/RAMProcessorSiteClose.lean
new file mode 100644
index 0000000000..b3cb67cb57
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorSiteClose.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.RAMProcessorSiteEntry
+import OAI.Computability.VPVNP.RAMProcessorGraphProbeEmit
+
+/-!
+# Exact-use validation and closing the physical bucket
+
+The last test consumes no further guesses. A nonempty suffix or an incorrect
+outgoing cut reaches the rejecting graph row. On success the graph pads the
+record array to its public size and exposes its serialized bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k : ℕ}
+
+/-- Accept the report list when all choices were consumed and advancing the incoming cut
+matches the target. At a site without a target, the advanced cut must be halted. -/
+def checkResult (s : Snapshot w p r k) (rs : List (Report w)) (tail : List Bool) :
+ Option (List (Report w)) :=
+ if tail = [] then
+ match s.tests.target with
+ | some c => if c = s.tests.cut.advance rs then some rs else none
+ | none => if (s.tests.cut.advance rs).state = none then some rs else none
+ else none
+
+private theorem checkResult_eq {s u : Snapshot w p r k} {old new : List (WordRecord w)}
+ {rs : List (Report w)} {tail : List Bool} (h : Progress s u old new rs tail) :
+ checkResult s rs tail = if SiteTests.finalCheck.eval u.tests = .finish then some rs else none := by
+ classical
+ rw [SiteTests.final_eval]
+ change checkResult s rs tail = if (if u.choices = [] ∧
+ (match u.tests.target with | some c => c = u.tests.cut | none => u.tests.cut.state = none)
+ then SiteTests.Exit.finish else SiteTests.Exit.reject) = SiteTests.Exit.finish then some rs else none
+ rw [h.bits, h.target, h.cut]
+ unfold checkResult
+ cases s.tests.target <;> split_ifs <;> simp_all
+
+/-- Physical execution specification for a completed site. Native failure reaches a rejecting
+row, and native success reaches the done label with the exact report history, exhausted
+choices and padded record block. -/
+def ClosedRun (T : Template p r k) (hw : 2 ≤ w) (s : Snapshot w p r k)
+ (old : List (WordRecord w)) (l : Label p r) (t : ℕ) (native : Option (List (Report w))) : Prop :=
+ match native with
+ | none => RejectRun (table T) t (atLabel T l) s.bank
+ | some rs => ∃ u ys, Progress s u old ys rs [] ∧
+ StackRuns (table T) t (atLabel T l) s.bank (atLabel T .done)
+ (u.afterClose hw s.publicH ys).bank
+
+/-- Upper bound on stack steps for the final cut and choice checks, padding to four times the
+public site allowance and exposing the five-word records as bits. -/
+def closeWork (w H : ℕ) := 40*w+42+(4*H)*(25*w+12)+1+(2*(4*H*5*w)+1)
+
+private theorem finalize {T : Template p r k} (hw : 2 ≤ w) {s : Snapshot w p r k}
+ {old : List (WordRecord w)} {l : Label p r} {t : ℕ} {native : Option (List (Report w) × List Bool)}
+ (hr : LoopRun T (fun u ys => RecordBuffer.Holds hw s.publicH ys u.records) l .finalCheck s old t native) :
+ ∃ n ≤ t+closeWork w s.publicH,
+ ClosedRun T hw s old l n (native.bind fun (rs, tail) => checkResult s rs tail) := by
+ cases native with
+ | none => exact ⟨t, Nat.le_add_right .., hr⟩
+ | some z =>
+ obtain ⟨rs, tail⟩ := z
+ obtain ⟨u, ys, hh, hp, run⟩ := hr
+ simp only [Option.bind_some]
+ rw [checkResult_eq hp]
+ obtain ⟨b, hb, hfinal⟩ := finalCheck_run T u
+ by_cases he : SiteTests.finalCheck.eval u.tests = .finish
+ · rw [ite_eq_left he] at hfinal ⊢
+ have hout := close_run T u hw hh
+ have htail : tail = [] := by
+ by_contra hbad
+ have hn : u.tests.choices ≠ [] := fun hz => hbad (hp.bits.symm.trans hz)
+ rw [SiteTests.final_eval] at he
+ simp [hn] at he
+ subst tail
+ have hlen := Nat.mul_le_mul_right (25*w+12) (Nat.sub_le (4*s.publicH) ys.length)
+ refine ⟨_, ?_, u, ys, hp, (run.trans hfinal).trans hout⟩
+ unfold closeWork
+ omega
+ · rw [ite_eq_right he] at hfinal ⊢
+ exact ⟨_, by unfold closeWork; omega, _, _, run.trans hfinal, reject_row T⟩
+
+/-- Physical execution from the already initialized record buffer through
+the unique terminal row of the graph, including exact incoming/outgoing
+cuts, the native site/call caps, and an arbitrary private choice stream. -/
+theorem checkEntry_close {T : Template p r k} {ready : Bool → BoundaryInvariant w p r k}
+ {work : ℕ} (call : StartRuns T ready work) (hw : 2 ≤ w)
+ (hbuf : ∀ first u ys, ready first u ys → RecordBuffer.Holds hw u.publicH ys u.records)
+ (s : Snapshot w p r k) (old : List (WordRecord w)) (hs : ready true s old) (S v : ℕ)
+ (hl : s.lower.val = v*s.publicH) (hb : s.boundary.val = (v+1)*s.publicH)
+ (hc : s.cap.val = S*s.publicH) (hleft : s.siteLeft = 2*s.publicH-1) :
+ ∃ n ≤ siteWork w s.publicH work+closeWork w s.publicH,
+ ClosedRun T hw s old .checkEntry n
+ (validateSite (T.instantiate w s.pub).program s.publicFuel S s.publicH v s.tests.cut s.tests.target s.choices) := by
+ obtain ⟨t, ht, run⟩ := checkEntry_loop call hbuf s old hs S v hl hb hc hleft
+ have hr : LoopRun T (fun u ys => RecordBuffer.Holds hw s.publicH ys u.records) .checkEntry .finalCheck s old t
+ (runSite (T.instantiate w s.pub).program s.publicFuel S s.publicH v s.tests.cut s.choices) := by
+ generalize ho : runSite (T.instantiate w s.pub).program s.publicFuel S s.publicH v s.tests.cut s.choices = z at run ⊢
+ cases z with
+ | none => exact run
+ | some z =>
+ obtain ⟨rs,tail⟩ := z
+ obtain ⟨u,ys,hh,hp,hr⟩ := run
+ exact ⟨u,ys,hp.H ▸ hh,hp,hr⟩
+ obtain ⟨n,hn,hfinish⟩ := finalize hw hr
+ exact ⟨n, by omega, hfinish⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorSiteEntry.lean b/lean/OAI/Computability/VPVNP/RAMProcessorSiteEntry.lean
new file mode 100644
index 0000000000..c15117665a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorSiteEntry.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.RAMProcessorSiteLoop
+
+/-! # Native bucket entry and physical execution up to the final checks -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k : ℕ}
+
+private theorem LoopRun.weaken {T : Template p r k} {ready valid : BoundaryInvariant w p r k}
+ {l next s records t native} (h : LoopRun T ready l next s records t native)
+ (hgood : ∀ u ys, ready u ys → valid u ys) : LoopRun T valid l next s records t native := by
+ cases native with
+ | none => exact h
+ | some z =>
+ obtain ⟨rs,tail⟩ := z
+ obtain ⟨u, ys, hready, progress, run⟩ := h
+ exact ⟨u, ys, hgood u ys hready, progress, run⟩
+
+private theorem iteration_of_entry (s : SiteTests.Snapshot w) (hd : SiteTests.entry.eval s = .dispatch) :
+ SiteTests.iteration.eval s = .dispatch := by
+ rw [SiteTests.entry_eval] at hd
+ rw [SiteTests.iteration_eval]
+ split at hd <;> rename_i h
+ · split at hd <;> rename_i hstate
+ · simp [h.1, hstate, (h.2 hstate).2]
+ · contradiction
+ · contradiction
+
+/-- Stack-step bound from the site entry check to the final check, accounting for startup,
+bounded charged calls and intervening iteration tests. -/
+def siteWork (w H work : ℕ) : ℕ := 60*w+41+work+(2*H-1)*(work+(40*w+30))
+
+theorem checkEntry_loop {T : Template p r k} {ready : Bool → BoundaryInvariant w p r k}
+ {valid : BoundaryInvariant w p r k} {work : ℕ} (call : StartRuns T ready work)
+ (hgood : ∀ first u ys, ready first u ys → valid u ys)
+ (s : Snapshot w p r k) (records : List (WordRecord w)) (hs : ready true s records) (S v : ℕ)
+ (hl : s.lower.val = v*s.publicH) (hb : s.boundary.val = (v+1)*s.publicH)
+ (hc : s.cap.val = S*s.publicH) (hleft : s.siteLeft = 2*s.publicH-1) :
+ ∃ t ≤ siteWork w s.publicH work, LoopRun T valid .checkEntry .finalCheck s records t
+ (runSite (T.instantiate w s.pub).program s.publicFuel S s.publicH v s.tests.cut s.choices) := by
+ obtain ⟨a, ha, run⟩ := checkEntry_run T s
+ have hmodel := SiteTests.runSite_at_exit (T.instantiate w s.pub).program s.publicFuel S s.publicH v s.tests hl hb hc
+ change runSite (T.instantiate w s.pub).program s.publicFuel S s.publicH v s.tests.cut s.choices = _ at hmodel
+ rw [hmodel]
+ cases hd : SiteTests.entry.eval s.tests with
+ | reject =>
+ rw [hd] at run
+ exact ⟨_, by unfold siteWork; omega, _, _, run, reject_row T⟩
+ | finish =>
+ rw [hd] at run
+ exact ⟨_, by unfold siteWork; omega, s, records, hgood true s records hs, Progress.nil s records, run⟩
+ | dispatch =>
+ rw [hd] at run
+ obtain ⟨b, hbnd, hloop⟩ := first_loop call (2*s.publicH-1) s records hs hleft.le (iteration_of_entry _ hd)
+ have hfull := (hloop.weaken (hgood false)).prepend run
+ unfold nativeLoop at hfull
+ rw [hb, hc, hleft] at hfull
+ exact ⟨_, by unfold siteWork; omega, hfull⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorSiteLoop.lean b/lean/OAI/Computability/VPVNP/RAMProcessorSiteLoop.lean
new file mode 100644
index 0000000000..40ec80807c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorSiteLoop.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.RAMProcessorSiteProgress
+
+/-!
+# Following the physical loop through all calls of a cost bucket
+
+Every successful start decreases the site allowance. In particular, when
+the native call-count bound is exhausted the next attempted start has zero
+credit and physically rejects. A failed call retains its actual halting
+row even when earlier calls have already returned.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k : ℕ}
+
+/-- Select the first-call label at bucket entry or the new-call label for a later iteration. -/
+def startLabel (first : Bool) : Label p r := if first then .first else .newCall
+
+/-- The two startup labels have the same charged call specification.
+The first one additionally initializes the global allowance. -/
+def StartRuns (T : Template p r k) (ready : Bool → BoundaryInvariant w p r k) (work : ℕ) :=
+ ∀ (first : Bool) (s : Snapshot w p r k) (records : List (WordRecord w)), ready first s records →
+ SiteTests.iteration.eval s.tests = .dispatch →
+ ∃ t ≤ work, LoopRun T (ready false) (startLabel first) .iteration s records t
+ ((nativeCall T s).map fun (rep, tail) => ([rep], tail))
+
+private theorem dispatch_eq (T : Template p r k) (s : Snapshot w p r k) (steps : ℕ)
+ (hd : SiteTests.iteration.eval s.tests = .dispatch) :
+ nativeLoop T steps s = match steps with
+ | 0 => none
+ | j+1 => collectCall (nativeCall T s) (fun rep tail =>
+ runSiteLoop (T.instantiate w s.pub).program s.publicFuel s.publicH s.boundary.val
+ s.cap.val j (s.tests.cut.advance [rep]) (s.siteLeft-(1+rep.probes)) tail) := by
+ have h := SiteTests.runSiteLoop_at_exit (T.instantiate w s.pub).program s.publicFuel s.publicH steps s.siteLeft s.tests
+ rw [hd] at h
+ exact h
+
+private theorem dispatch_run {T : Template p r k} {ready : Bool → BoundaryInvariant w p r k}
+ {work : ℕ} (call : StartRuns T ready work) (steps : ℕ) (first : Bool) (s : Snapshot w p r k)
+ (records : List (WordRecord w)) (hadm : ready first s records) (hleft : s.siteLeft ≤ steps)
+ (hd : SiteTests.iteration.eval s.tests = .dispatch)
+ (ih : ∀ j < steps, ∀ u ys, ready false u ys → u.siteLeft ≤ j →
+ ∃ b ≤ (j+1)*(work+(40*w+30)),
+ LoopRun T (ready false) .iteration .finalCheck u ys b (nativeLoop T j u)) :
+ ∃ n ≤ work+steps*(work+(40*w+30)),
+ LoopRun T (ready false) (startLabel first) .finalCheck s records n (nativeLoop T steps s) := by
+ obtain ⟨t, ht, run⟩ := call first s records hadm hd
+ rw [dispatch_eq T s steps hd]
+ cases hc : nativeCall T s with
+ | none =>
+ rw [hc] at run
+ cases steps <;> exact ⟨t, by omega, run⟩
+ | some z =>
+ obtain ⟨rep, tail⟩ := z
+ rw [hc] at run
+ obtain ⟨u, ys, hready, progress, hr⟩ := run
+ have hcharge : 1+rep.probes ≤ s.siteLeft := (runChargedCall_iff.mp hc).2.2.2.1
+ cases steps with
+ | zero => omega
+ | succ j =>
+ have hl : u.siteLeft ≤ j := by
+ have he := progress.siteLeft
+ simp [RAMBuckets.cost] at he
+ omega
+ obtain ⟨b, hb, hrest⟩ := ih j (by omega) u ys hready hl
+ have hnext := LoopRun.prependReport hr progress hrest
+ rw [nativeLoop_next T progress j] at hnext
+ exact ⟨t+b, by omega, hnext⟩
+
+/-- From the iteration test through the entire remaining bucket. The
+singleton progress returned by each native call composes into the complete
+ordered list of reports and emitted probe records. -/
+theorem iteration_loop {T : Template p r k} {ready : Bool → BoundaryInvariant w p r k} {work : ℕ}
+ (call : StartRuns T ready work) (steps : ℕ) (s : Snapshot w p r k)
+ (records : List (WordRecord w)) (hadm : ready false s records) (hleft : s.siteLeft ≤ steps) :
+ ∃ t ≤ (steps+1)*(work+(40*w+30)),
+ LoopRun T (ready false) .iteration .finalCheck s records t (nativeLoop T steps s) := by
+ induction steps using Nat.strong_induction_on generalizing s records with
+ | h n ih =>
+ obtain ⟨a, ha, run⟩ := iteration_run T s
+ cases hd : SiteTests.iteration.eval s.tests with
+ | reject =>
+ rw [hd] at run
+ have hnone : nativeLoop T n s = none := by
+ have h := SiteTests.runSiteLoop_at_exit (T.instantiate w s.pub).program s.publicFuel s.publicH n s.siteLeft s.tests
+ rw [hd] at h
+ exact h
+ rw [hnone]
+ exact ⟨a, by rw [Nat.add_mul]; omega, _, _, run, reject_row T⟩
+ | finish =>
+ rw [hd] at run
+ have hdone : nativeLoop T n s = some ([],s.choices) := by
+ have h := SiteTests.runSiteLoop_at_exit (T.instantiate w s.pub).program s.publicFuel s.publicH n s.siteLeft s.tests
+ rw [hd] at h
+ exact h
+ rw [hdone]
+ exact ⟨a, by rw [Nat.add_mul]; omega, s, records, hadm, Progress.nil s records, run⟩
+ | dispatch =>
+ rw [hd] at run
+ obtain ⟨b, hb, hloop⟩ := dispatch_run call n false s records hadm hleft hd ih
+ exact ⟨a+b, by rw [Nat.add_mul]; omega, hloop.prepend run⟩
+
+theorem first_loop {T : Template p r k} {ready : Bool → BoundaryInvariant w p r k} {work : ℕ}
+ (call : StartRuns T ready work) (steps : ℕ) (s : Snapshot w p r k)
+ (records : List (WordRecord w)) (hadm : ready true s records) (hleft : s.siteLeft ≤ steps)
+ (hd : SiteTests.iteration.eval s.tests = .dispatch) :
+ ∃ t ≤ work+steps*(work+(40*w+30)),
+ LoopRun T (ready false) .first .finalCheck s records t (nativeLoop T steps s) :=
+ dispatch_run call steps true s records hadm hleft hd (fun j _ => iteration_loop call j)
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorSiteProgress.lean b/lean/OAI/Computability/VPVNP/RAMProcessorSiteProgress.lean
new file mode 100644
index 0000000000..5d6573bcef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorSiteProgress.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.RAMProcessorLoopTests
+
+/-!
+# State and record accounting between bucket calls
+
+The loop invariant retains the public template parameters and target cut,
+the exact native continuation, the unconsumed guess suffix, and the full
+list of records already emitted by the physical graph.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM RAMSerialization
+
+variable {w p r k : ℕ}
+
+/-- Relate two call boundaries across a sequence of reports. The reports advance the cut, debit
+the site credit and append exactly their timestamped probe records, with the specified
+choice suffix. -/
+structure Progress (s u : Snapshot w p r k) (old new : List (WordRecord w))
+ (reports : List (Report w)) (tail : List Bool) : Prop where
+ pub : u.pub = s.pub
+ H : u.publicH = s.publicH
+ fuel : u.publicFuel = s.publicFuel
+ cap : u.cap = s.cap
+ boundary : u.boundary = s.boundary
+ target : u.tests.target = s.tests.target
+ cut : u.tests.cut = s.tests.cut.advance reports
+ siteLeft : u.siteLeft = s.siteLeft - RAMBuckets.cost Report.probes reports
+ bits : u.choices = tail
+ records : new.map WordRecord.record = old.map WordRecord.record ++ probeRecords s.cost.val reports
+
+theorem Progress.nil (s : Snapshot w p r k) (rs : List (WordRecord w)) :
+ Progress s s rs rs [] s.choices :=
+ ⟨rfl, rfl, rfl, rfl, rfl, rfl, (Cut.advance_nil _).symm, rfl, rfl, by simp [probeRecords]⟩
+
+theorem Progress.append {s u v : Snapshot w p r k} {a b c : List (WordRecord w)}
+ {xs ys : List (Report w)} {mid tail : List Bool}
+ (hx : Progress s u a b xs mid) (hy : Progress u v b c ys tail) :
+ Progress s v a c (xs++ys) tail := by
+ refine ⟨hy.pub.trans hx.pub, hy.H.trans hx.H, hy.fuel.trans hx.fuel, hy.cap.trans hx.cap,
+ hy.boundary.trans hx.boundary, hy.target.trans hx.target, ?_, ?_, hy.bits, ?_⟩
+ · rw [Cut.advance_append, ← hx.cut, hy.cut]
+ · rw [hy.siteLeft, hx.siteLeft, Nat.sub_sub, RAMBuckets.cost_append]
+ · have hc : u.cost.val = s.cost.val + RAMBuckets.cost Report.probes xs := congrArg Cut.cost hx.cut
+ rw [hy.records, hx.records, probeRecords_append, hc, List.append_assoc]
+
+/-- Run one charged call of the instantiated program from the snapshot's persistent state using
+its public fuel and remaining global and site credit. -/
+def nativeCall (T : Template p r k) (s : Snapshot w p r k) : Option (Report w × List Bool) :=
+ let P := (T.instantiate w s.pub).program
+ (runChargedCall P s.publicFuel (P.start s.cfg.persistent) s.publicH
+ (s.cap.val-s.cost.val) s.siteLeft s.choices).output
+
+/-- Run the native site loop with the supplied iteration bound, starting at the snapshot's cut
+with its site credit and remaining choices. -/
+def nativeLoop (T : Template p r k) (n : ℕ) (s : Snapshot w p r k) :=
+ runSiteLoop (T.instantiate w s.pub).program s.publicFuel s.publicH s.boundary.val
+ s.cap.val n s.tests.cut s.siteLeft s.choices
+
+theorem nativeLoop_next (T : Template p r k) {s u : Snapshot w p r k} {xs ys : List (WordRecord w)}
+ {rep : Report w} {tail : List Bool} (h : Progress s u xs ys [rep] tail) (n : ℕ) :
+ nativeLoop T n u = runSiteLoop (T.instantiate w s.pub).program s.publicFuel s.publicH s.boundary.val
+ s.cap.val n (s.tests.cut.advance [rep]) (s.siteLeft-(1+rep.probes)) tail := by
+ unfold nativeLoop
+ rw [h.pub, h.fuel, h.H, h.boundary, h.cap, h.cut, h.siteLeft, h.bits]
+ simp [RAMBuckets.cost]
+
+/-- Type of a predicate on a site snapshot and the chronological word records accumulated at a
+call boundary. -/
+abbrev BoundaryInvariant (w p r k : ℕ) := Snapshot w p r k → List (WordRecord w) → Prop
+
+/-- A complete graph run either reaches its next public label with the
+indicated records and exact report stream, or reaches an actual rejecting row. -/
+def LoopRun (T : Template p r k) (ready : BoundaryInvariant w p r k) (l next : Label p r)
+ (s : Snapshot w p r k) (records : List (WordRecord w)) (t : ℕ)
+ (native : Option (List (Report w) × List Bool)) : Prop :=
+ match native with
+ | none => RejectRun (table T) t (atLabel T l) s.bank
+ | some (rs, tail) => ∃ u suffix, ready u suffix ∧ Progress s u records suffix rs tail ∧
+ StackRuns (table T) t (atLabel T l) s.bank (atLabel T next) u.bank
+
+theorem LoopRun.prepend {T : Template p r k} {ready : BoundaryInvariant w p r k} {l mid next}
+ {s : Snapshot w p r k} {records : List (WordRecord w)} {a b : ℕ} {native}
+ (h : StackRuns (table T) a (atLabel T l) s.bank (atLabel T mid) s.bank)
+ (hr : LoopRun T ready mid next s records b native) :
+ LoopRun T ready l next s records (a+b) native := by
+ cases native with
+ | none => exact h.thenReject hr
+ | some z =>
+ obtain ⟨rs, tail⟩ := z
+ obtain ⟨u, ys, hu, hp, run⟩ := hr
+ exact ⟨u, ys, hu, hp, h.trans run⟩
+
+theorem LoopRun.prependReport {T : Template p r k} {ready : BoundaryInvariant w p r k}
+ {s u : Snapshot w p r k} {xs ys : List (WordRecord w)} {rep : Report w} {rest}
+ {l mid next} {a b : ℕ} {native : Option (List (Report w) × List Bool)}
+ (h : StackRuns (table T) a (atLabel T l) s.bank (atLabel T mid) u.bank)
+ (hp : Progress s u xs ys [rep] rest) (hr : LoopRun T ready mid next u ys b native) :
+ LoopRun T ready l next s xs (a+b) (native.map fun (rs, tail) => (rep :: rs, tail)) := by
+ cases native with
+ | none => exact h.thenReject hr
+ | some z =>
+ obtain ⟨rs, tail⟩ := z
+ obtain ⟨v, zs, hv, hs, run⟩ := hr
+ exact ⟨v, zs, hv, hp.append hs, h.trans run⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorSiteTests.lean b/lean/OAI/Computability/VPVNP/RAMProcessorSiteTests.lean
new file mode 100644
index 0000000000..acb3d1a8a9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorSiteTests.lean
@@ -0,0 +1,173 @@
+import OAI.Computability.VPVNP.RAMProcessorSiteTestsTree
+import OAI.Computability.VPVNP.RAMValidatorControl
+
+/-!
+# Entry, call dispatch, and final checks for a RAM processor
+
+A running entry must start inside its own half-open cost bucket. A halted
+entry is checked only against the global cap. Later calls may cross the bucket
+boundary, including when a final cost equals the global cap. The final
+comparison distinguishes an absent outgoing edge from a present halted cut.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteTests
+
+open TapeWord BurstRAM
+
+variable {w : ℕ}
+
+/-- Decode the current cut from the cumulative cost and, while running, the persistent state
+word. -/
+def Snapshot.cut (s : Snapshot w) : Cut w :=
+ ⟨(s.words .cost).val, if s.flags .running then some (s.words .state) else none⟩
+
+/-- Decode the optional outgoing cut using the presence and running flags, target cost and
+target state. -/
+def Snapshot.target (s : Snapshot w) : Option (Cut w) :=
+ if s.flags .hasTarget then
+ some ⟨(s.words .targetCost).val, if s.flags .targetRunning then some (s.words .targetState) else none⟩
+ else none
+
+/-- Check the incoming range and choose the first site action. -/
+def entry : Tree :=
+ .branch (.compare .lt .cap .cost) (.leaf .reject) <|
+ .branch (.flag .running)
+ (.branch (.compare .lt .cost .lower) (.leaf .reject)
+ (.branch (.compare .lt .cost .boundary) (.leaf .dispatch) (.leaf .reject)))
+ (.leaf .finish)
+
+/-- Test the cut produced by the preceding charged call. -/
+def iteration : Tree :=
+ .branch (.compare .lt .cap .cost) (.leaf .reject) <|
+ .branch (.flag .running)
+ (.branch (.compare .lt .cost .boundary) (.leaf .dispatch) (.leaf .finish))
+ (.leaf .finish)
+
+/-- Exact use of choices and equality with the successor cut, or acceptance
+at the terminal site. The state payload of a halt is ignored. -/
+def finalCheck : Tree :=
+ .branch .emptyChoices
+ (.branch (.flag .hasTarget)
+ (.branch (.compare .eq .cost .targetCost)
+ (.branch (.flag .running)
+ (.branch (.flag .targetRunning)
+ (.branch (.compare .eq .state .targetState) (.leaf .finish) (.leaf .reject))
+ (.leaf .reject))
+ (.branch (.flag .targetRunning) (.leaf .reject) (.leaf .finish)))
+ (.leaf .reject))
+ (.branch (.flag .running) (.leaf .reject) (.leaf .finish)))
+ (.leaf .reject)
+
+theorem entry_eval (s : Snapshot w) :
+ entry.eval s = if s.cut.cost ≤ (s.words .cap).val ∧
+ (s.cut.state.isSome → (s.words .lower).val ≤ s.cut.cost ∧ s.cut.cost < (s.words .boundary).val)
+ then if s.cut.state.isSome then .dispatch else .finish else .reject := by
+ cases h : s.flags .running <;>
+ simp [entry, Tree.eval, Atom.eval, Comparison.Op.eval, Snapshot.cut, h, Fin.lt_def, -Fin.val_fin_lt, -Fin.val_fin_le] <;>
+ split_ifs <;> first | rfl | omega
+
+theorem iteration_eval (s : Snapshot w) :
+ iteration.eval s = if s.cut.cost ≤ (s.words .cap).val then
+ if s.cut.state.isSome && decide (s.cut.cost < (s.words .boundary).val) then .dispatch else .finish
+ else .reject := by
+ cases h : s.flags .running <;>
+ simp [iteration, Tree.eval, Atom.eval, Comparison.Op.eval, Snapshot.cut, h, Fin.lt_def, -Fin.val_fin_lt, -Fin.val_fin_le] <;>
+ split_ifs <;> first | rfl | omega
+
+open Classical in
+theorem final_eval (s : Snapshot w) :
+ finalCheck.eval s = if s.choices = [] ∧
+ (match s.target with | some d => d = s.cut | none => s.cut.state = none)
+ then .finish else .reject := by
+ cases ht : s.flags .hasTarget <;> cases hs : s.flags .running <;> cases hr : s.flags .targetRunning <;>
+ simp [finalCheck, Tree.eval, Atom.eval, Comparison.Op.eval, Snapshot.cut, Snapshot.target, ht, hs, hr,
+ Fin.ext_iff] <;>
+ split_ifs <;> simp_all
+
+/-- A terminal equality test of the physical processor has exactly the
+Boolean outcome of the native report checker. -/
+theorem final_eq_finishReports (s : Snapshot w) (input : Cut w) (reports : List (Report w))
+ (hc : s.cut = input.advance reports) :
+ finalCheck.eval s = if (finishReports input s.target reports s.choices).1 then .finish else .reject := by
+ rw [final_eval]
+ have valid := finishReports_spec input s.target reports s.choices
+ rw [← hc] at valid
+ cases ho : s.target <;> simp only [ho] at valid ⊢ <;> split_ifs <;> tauto
+
+/-- The dispatch label selects precisely the native call of this site,
+including its remaining credit and unused binary choices. -/
+theorem runSiteLoop_at_exit {C : Type*} (P : Program w C) (fuel H steps siteLeft : ℕ) (s : Snapshot w) :
+ runSiteLoop P fuel H (s.words .boundary).val (s.words .cap).val steps s.cut siteLeft s.choices =
+ match iteration.eval s with
+ | .reject => none
+ | .finish => some ([], s.choices)
+ | .dispatch =>
+ match steps with
+ | 0 => none
+ | j+1 => collectCall (runChargedCall P fuel (P.start (s.words .state)) H
+ ((s.words .cap).val - s.cut.cost) siteLeft s.choices).output (fun rep rest =>
+ runSiteLoop P fuel H (s.words .boundary).val (s.words .cap).val j (s.cut.advance [rep])
+ (siteLeft - (1 + rep.probes)) rest) := by
+ rw [runSiteLoop, iteration_eval]
+ cases hr : s.flags .running <;>
+ by_cases hc : (s.words .cost).val ≤ (s.words .cap).val <;>
+ by_cases hb : (s.words .cost).val < (s.words .boundary).val <;>
+ simp [Snapshot.cut, hr, hc, hb]
+ cases steps <;> rfl
+
+/-- The entry fragment rejects an invalid incoming bucket and immediately
+finishes on a valid halted cut. Its dispatch label enters the native site loop. -/
+theorem runSite_at_exit {C : Type*} (P : Program w C) (fuel S H v : ℕ) (s : Snapshot w)
+ (hl : (s.words .lower).val = v*H) (hb : (s.words .boundary).val = (v+1)*H)
+ (hc : (s.words .cap).val = S*H) :
+ runSite P fuel S H v s.cut s.choices =
+ match entry.eval s with
+ | .reject => none
+ | .finish => some ([], s.choices)
+ | .dispatch => runSiteLoop P fuel H ((v+1)*H) (S*H) (2*H-1) s.cut (2*H-1) s.choices := by
+ rw [entry_eval, hl, hb, hc, runSite]
+ cases hr : s.flags .running <;>
+ by_cases hcap : (s.words .cost).val ≤ S*H <;>
+ by_cases hrange : v*H ≤ (s.words .cost).val ∧ (s.words .cost).val < (v+1)*H <;>
+ simp [Snapshot.cut, hr, hcap, hrange] <;> rw [runSiteLoop] <;> simp [hcap]
+
+private def Atom.bound (a : Atom) (w : ℕ) : ℕ :=
+ match a with | .compare .. => 20*w+10 | _ => 3
+
+private def Tree.bound : Tree → ℕ → ℕ
+ | .leaf e, _ => e.bits.length
+ | .branch a yes no, w => a.bound w + (max (yes.bound w) (no.bound w) + 1)
+
+private theorem ticks_le (t : Tree) (s : Snapshot w) : t.ticks s ≤ t.bound w := by
+ induction t with
+ | leaf => exact le_rfl
+ | branch a y n iy ineg =>
+ have ha : a.ticks s ≤ a.bound w := by
+ cases a <;> simp only [Atom.ticks, Atom.bound] <;> first | exact le_rfl | split <;> decide
+ dsimp only [Tree.ticks, Tree.bound]
+ split <;> omega
+
+theorem entry_work (s : Snapshot w) : entry.ticks s ≤ 60*w+39 := by
+ apply (ticks_le entry s).trans
+ simp [entry, Tree.bound, Atom.bound, Exit.bits]
+ omega
+
+theorem iteration_work (s : Snapshot w) : iteration.ticks s ≤ 40*w+28 := by
+ apply (ticks_le iteration s).trans
+ simp [iteration, Tree.bound, Atom.bound, Exit.bits]
+ omega
+
+theorem final_work (s : Snapshot w) : finalCheck.ticks s ≤ 40*w+40 := by
+ apply (ticks_le finalCheck s).trans
+ simp [finalCheck, Tree.bound, Atom.bound, Exit.bits]
+ omega
+
+end RAMTape.SiteTests
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorSiteTestsFlow.lean b/lean/OAI/Computability/VPVNP/RAMProcessorSiteTestsFlow.lean
new file mode 100644
index 0000000000..c41d08b912
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorSiteTestsFlow.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.RAMProcessorSiteTests
+import OAI.Computability.VPVNP.RAMProcessorFlow
+
+/-!
+# Typed exits of the site checks
+
+The graph consumes the verdict stack before transferring to the selected
+caller label. The caller receives all original site data and empty scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteTests
+
+variable {L : Type} {w : ℕ}
+
+/-- Compile the site's decision tree into a graph fragment that consumes its verdict bits and
+jumps to the caller's reject, finish or dispatch label. -/
+def Tree.fragment (tree : Tree) (next : Exit → L) : Fragment Port L where
+ State := tree.machine.State ⊕ Bool
+ entry := .inl tree.machine.body.entry
+ code
+ | .inl q => (tree.machine.body.code q).rename id fun r => .inl (r.elim (.inr false) Sum.inl)
+ | .inr false => .pop .verdict fun
+ | some true => .inl (.inr true)
+ | _ => .inr (next .reject)
+ | .inr true => .pop .verdict fun
+ | some true => .inr (next .dispatch)
+ | some false => .inr (next .finish)
+ | none => .inr (next .reject)
+
+private theorem decodeRun (tree : Tree) (next : Exit → L) (e : Exit) (s : Snapshot w) :
+ StackRuns (tree.fragment next).isolated e.bits.length (.inl (.inr false))
+ (Function.update s.bank .verdict e.bits) (.inr (next e)) s.bank := by
+ have endBank : Function.update s.bank .verdict [] = s.bank := Function.update_eq_self _ _
+ cases e <;> (
+ refine .cons (.pop rfl) ?_
+ simp only [Function.update_self, Function.update_idem, Exit.bits, List.head?_cons,
+ List.tail_cons, endBank]
+ first | exact .nil .. | (refine .cons (.pop rfl) ?_; simp only [Function.update_self, Function.update_idem, List.head?_cons, List.tail_cons, endBank]; exact .nil ..))
+
+theorem Tree.fragment_runs (tree : Tree) (next : Exit → L) (s : Snapshot w) :
+ (tree.fragment next).Runs (tree.ticks s + (tree.eval s).bits.length) s.bank
+ (next (tree.eval s)) s.bank := by
+ let f := tree.fragment next
+ let labels : Option tree.machine.State → f.State ⊕ L := fun r => .inl (r.elim (.inr false) Sum.inl)
+ have rows (q : Option tree.machine.State) (hq : (tree.machine.body.standalone q).returns = false) :
+ f.isolated (labels q) = (tree.machine.body.standalone q).rename id labels := by
+ cases q with
+ | none => contradiction
+ | some q => rfl
+ have same (u : Stacks Port) : installStacks id s.bank u = u := by
+ funext j
+ exact installStacks_at Function.injective_id _ _ j
+ have run := (tree.run s).lift id Function.injective_id labels s.bank rows
+ rw [same, same] at run
+ exact run.trans (decodeRun tree next (tree.eval s) s)
+
+end RAMTape.SiteTests
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorSiteTestsTree.lean b/lean/OAI/Computability/VPVNP/RAMProcessorSiteTestsTree.lean
new file mode 100644
index 0000000000..9741833aa0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorSiteTestsTree.lean
@@ -0,0 +1,164 @@
+import OAI.Computability.VPVNP.RAMProcessorSiteTestsWord
+
+/-!
+# Finite decision trees on decoded site fields
+
+Each test preserves the site data. The branch pop consumes its temporary
+answer. A leaf returns the caller's exit tag on the verdict stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteTests
+
+open TapeWord BurstRAM
+
+variable {w : ℕ}
+
+/-- A site test that compares two word fields, inspects a status flag or checks whether the
+choice stream is empty. -/
+inductive Atom where
+ | compare (op : Comparison.Op) (left right : WordField)
+ | flag (f : BitField)
+ | emptyChoices
+
+/-- Boolean outcome of a primitive site check on the decoded words, flags and choices of a
+snapshot. -/
+def Atom.eval (a : Atom) (s : Snapshot w) : Bool :=
+ match a with
+ | .compare op x y => op.eval (s.words x) (s.words y)
+ | .flag f => s.flags f
+ | .emptyChoices => s.choices.isEmpty
+
+private def peek (p : Port) (f : Option Bool → Bool) : FiniteRoutine Port :=
+ let emit := fun b => Routine.push Port.left (f b)
+ let restore := fun b => (Routine.push p b).followedBy (emit (some b))
+ .ofRoutine (Routine.popCase p (emit none) (restore false) (restore true))
+
+private theorem peek_run (p : Port) (f : Option Bool → Bool) (s : Stacks Port) (hl : s .left = []) :
+ (peek p f).Runs (if (s p).isEmpty then 2 else 3) s (Function.update s .left [f (s p).head?]) := by
+ cases he : s p with
+ | nil =>
+ have hp := Routine.runs_push Port.left (f none) s
+ rw [hl] at hp
+ apply Routine.runs_popCase_empty p _ _ _ he hp
+ | cons b bs =>
+ let popped := Function.update s p bs
+ have hr : (Routine.push p b).Runs 1 popped s := by
+ have h := Routine.runs_push p b popped
+ simpa only [popped, Function.update_self, Function.update_idem, ← he, Function.update_eq_self] using h
+ have hp := Routine.runs_push Port.left (f (some b)) s
+ rw [hl] at hp
+ have hb := hr.followedBy hp
+ cases b
+ · apply Routine.runs_popCase_false p _ _ _ he hb
+ · apply Routine.runs_popCase_true p _ _ _ he hb
+
+/-- Stack routine implementing an atomic site test and delivering its Boolean answer on the
+left scratch stack. -/
+def Atom.machine : Atom → FiniteRoutine Port
+ | .compare op x y => SiteTests.compare op x y
+ | .flag f => peek (.bit f) (fun b => b.getD false)
+ | .emptyChoices => peek .choices Option.isNone
+
+/-- Exact stack-step count for an atomic test. A word comparison costs 20 times the width plus
+10, a flag costs three, and testing choices costs two or three according to emptiness. -/
+def Atom.ticks (a : Atom) (s : Snapshot w) : ℕ :=
+ match a with
+ | .compare .. => 20*w+10
+ | .flag _ => 3
+ | .emptyChoices => if s.choices.isEmpty then 2 else 3
+
+theorem Atom.run (a : Atom) (s : Snapshot w) :
+ a.machine.Runs (a.ticks s) s.bank (Function.update s.bank .left [a.eval s]) := by
+ cases a with
+ | compare op x y => exact compare_runs op x y s
+ | flag f => exact peek_run (.bit f) (fun b => b.getD false) s.bank rfl
+ | emptyChoices =>
+ have h := peek_run .choices Option.isNone s.bank rfl
+ cases he : s.choices <;> simpa [Atom.machine, Atom.eval, Atom.ticks, Snapshot.bank, he] using h
+
+/-- Decision to reject execution, finish the current bucket or dispatch another charged call. -/
+inductive Exit where
+ | reject | finish | dispatch
+ deriving DecidableEq
+
+/-- Verdict-stack encoding of the three exits. A leading false bit rejects, and a leading true
+bit is followed by false for finish or true for dispatch. -/
+def Exit.bits : Exit → List Bool
+ | .reject => [false] | .finish => [true, false] | .dispatch => [true, true]
+
+private def leafCode : Exit → FiniteRoutine Port
+ | .reject => .ofRoutine (Routine.push Port.verdict false)
+ | .finish => .ofRoutine ((Routine.push Port.verdict false).followedBy (Routine.push Port.verdict true))
+ | .dispatch => .ofRoutine ((Routine.push Port.verdict true).followedBy (Routine.push Port.verdict true))
+
+private theorem leaf_run (e : Exit) (s : Snapshot w) :
+ (leafCode e).Runs e.bits.length s.bank (Function.update s.bank .verdict e.bits) := by
+ have two (b : Bool) : ((Routine.push Port.verdict b).followedBy (Routine.push Port.verdict true)).Runs 2
+ s.bank (Function.update s.bank .verdict [true, b]) := by
+ have h := (Routine.runs_push Port.verdict b s.bank).followedBy
+ (Routine.runs_push Port.verdict true (Function.update s.bank .verdict [b]))
+ simpa only [Function.update_self, Function.update_idem] using h
+ cases e with
+ | reject => exact Routine.runs_push _ _ _
+ | finish => exact two false
+ | dispatch => exact two true
+
+/-- Finite decision tree with primitive site tests at branches and processor exits at leaves. -/
+inductive Tree where
+ | leaf (e : Exit)
+ | branch (a : Atom) (yes no : Tree)
+
+/-- Follow the branch outcomes on a fixed decoded snapshot to obtain the processor exit at the
+selected leaf. -/
+def Tree.eval : Tree → Snapshot w → Exit
+ | .leaf e, _ => e
+ | .branch a yes no, s => if a.eval s then yes.eval s else no.eval s
+
+/-- Exact stack-step count along the selected tree path, including each test, its branch pop
+and the verdict bits pushed at the leaf. -/
+def Tree.ticks : Tree → Snapshot w → ℕ
+ | .leaf e, _ => e.bits.length
+ | .branch a yes no, s => a.ticks s + ((if a.eval s then yes.ticks s else no.ticks s) + 1)
+
+private def select (yes no : FiniteRoutine Port) : FiniteRoutine Port :=
+ .ofRoutine (Routine.popCase Port.left (Routine.halt false) no.body yes.body)
+
+/-- Compile each branch to an atomic test and a pop that selects its successor. At a leaf the
+routine pushes the encoded exit onto the verdict stack. -/
+def Tree.machine : Tree → FiniteRoutine Port
+ | .leaf e => leafCode e
+ | .branch a yes no => a.machine.followedBy (select yes.machine no.machine)
+
+/-- A normally returning site test delivers its precise exit code. The
+original choices, bounds, status bits and state words remain available. -/
+theorem Tree.run (t : Tree) (s : Snapshot w) :
+ t.machine.Runs (t.ticks s) s.bank (Function.update s.bank .verdict (t.eval s).bits) := by
+ induction t with
+ | leaf e => exact leaf_run e s
+ | branch a yes no ih₁ ih₂ =>
+ have ht := a.run s
+ cases h : a.eval s with
+ | false =>
+ rw [h] at ht
+ simp only [Tree.machine, Tree.ticks, Tree.eval, h, Bool.false_eq_true, ite_false]
+ apply FiniteRoutine.Runs.followedBy ht
+ apply Routine.runs_popCase_false Port.left _ _ _ (tail := []) (Function.update_self ..)
+ rw [Function.update_idem, show Function.update s.bank .left [] = s.bank from Function.update_eq_self _ _]
+ exact ih₂
+ | true =>
+ rw [h] at ht
+ simp only [Tree.machine, Tree.ticks, Tree.eval, h, ite_true]
+ apply FiniteRoutine.Runs.followedBy ht
+ apply Routine.runs_popCase_true Port.left _ _ _ (tail := []) (Function.update_self ..)
+ rw [Function.update_idem, show Function.update s.bank .left [] = s.bank from Function.update_eq_self _ _]
+ exact ih₁
+
+end RAMTape.SiteTests
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorSiteTestsWord.lean b/lean/OAI/Computability/VPVNP/RAMProcessorSiteTestsWord.lean
new file mode 100644
index 0000000000..5933b930df
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorSiteTestsWord.lean
@@ -0,0 +1,153 @@
+import OAI.Computability.VPVNP.RAMTapeWordComparison
+import OAI.Computability.VPVNP.RAMTapeWordOperands
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-!
+# Read-only word comparisons in the outer site processor
+
+The cumulative charge, its bounds, and the incoming or outgoing persistent
+state are full-width words. Two operand copies are compared by a fixed table;
+a comparison preserves both source words and returns its decision in one bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteTests
+
+open TapeWord BurstRAM
+
+/-- Full-width site fields for the bucket bounds, cumulative cost, global cap, persistent state
+and the target cut's cost and state. -/
+inductive WordField where
+ | lower | cost | boundary | cap | state | targetCost | targetState
+ deriving DecidableEq
+
+instance : Fintype WordField := derive_fintype% _
+
+/-- Flags indicating whether the incoming cut is running, whether a target cut is present and
+whether that target is running. -/
+inductive BitField where
+ | running | hasTarget | targetRunning
+ deriving DecidableEq
+
+instance : Fintype BitField := derive_fintype% _
+
+/-- Stack ports for decoded site fields, unused choices and verdict bits, together with the
+operand and scratch stacks for read-only comparisons. -/
+inductive Port where
+ | word (f : WordField) | bit (f : BitField) | choices | verdict
+ | left | right | tmp | out | sourceTmp | copyTmp
+ deriving DecidableEq, Fintype
+
+/-- Decoded site data on which entry, iteration and final checks operate, comprising
+fixed-width words, status flags and the remaining choices. -/
+structure Snapshot (w : ℕ) where
+ /-- Fixed-width cost, bound and state words indexed by their role in the site checks. -/
+ words : WordField → Word w
+ /-- Boolean values of the running and target-status fields used to interpret the cut words. -/
+ flags : BitField → Bool
+ /-- Unconsumed private choice stream tested for exact exhaustion when the site closes. -/
+ choices : List Bool
+
+variable {w : ℕ}
+
+/-- Encode each word as its bit string and each flag as a singleton stack, install the choices
+and initialize the verdict and comparison scratch stacks to empty. -/
+def Snapshot.bank (s : Snapshot w) : Stacks Port
+ | .word f => wordBits (s.words f)
+ | .bit f => [s.flags f]
+ | .choices => s.choices
+ | _ => []
+
+private def copyPorts (src : WordField) (dest : Bool) : ScanPort → Port
+ | .left => .word src
+ | .right => .sourceTmp
+ | .tmp => .copyTmp
+ | .out => if dest then .right else .left
+
+private theorem copy_inj (src : WordField) (dest : Bool) : Function.Injective (copyPorts src dest) := by
+ intro i j h
+ cases dest <;> cases i <;> cases j <;> simp_all [copyPorts]
+
+private def normal : Operand.State Unit → Bool
+ | .done _ => true
+ | _ => false
+
+private def copy (src : WordField) (dest : Bool) : FiniteRoutine Port :=
+ FiniteRoutine.ofStackCode (Operand.code Operand.copyBit) (copyPorts src dest) (.clear ()) normal
+
+private theorem copy_runs (src : WordField) (dest : Bool) (s : Stacks Port)
+ (h₁ : s .sourceTmp = []) (h₂ : s .copyTmp = []) :
+ let dst : Port := if dest then .right else .left
+ (copy src dest).Runs ((s dst).length + 7*(s (.word src)).length + 3) s
+ (Function.update s dst (s (.word src))) := by
+ dsimp only
+ refine FiniteRoutine.runs_ofStackCode_framed (copy_inj src dest) (normal := normal)
+ rfl rfl (fun q h => ?_) (Operand.copy_run (s (.word src)) (s (if dest then .right else .left))) ?_ ?_ ?_
+ · cases q <;> first | rfl | contradiction
+ · intro k
+ cases k <;> first | rfl | exact h₁ | exact h₂
+ · intro k
+ cases dest <;> cases k <;> simp [copyPorts, scanStacks, h₁, h₂]
+ · intro k hk
+ exact Function.update_of_ne (Ne.symm (hk .out)) ..
+
+private def cmpPorts : ScanPort → Port
+ | .left => .left | .right => .right | .tmp => .tmp | .out => .out
+
+private theorem cmp_inj : Function.Injective cmpPorts := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [cmpPorts]
+
+private def scanFlag (op : Comparison.Op) : FiniteRoutine Port := FiniteRoutine.ofRoutine {
+ entry := Comparison.State.scan (.left op.initial)
+ code := fun
+ | .done b => .push .left b none
+ | q@(.scan _) => (Comparison.code op q).rename cmpPorts some }
+
+/-- Return one test bit in the left scratch stack. Both source words remain
+available, including when they name the same field. -/
+def compare (op : Comparison.Op) (x y : WordField) : FiniteRoutine Port :=
+ ((copy x false).followedBy (copy y true)).followedBy (scanFlag op)
+
+theorem compare_runs (op : Comparison.Op) (x y : WordField) (s : Snapshot w) :
+ (compare op x y).Runs (20*w+10) s.bank
+ (Function.update s.bank .left [op.eval (s.words x) (s.words y)]) := by
+ let s₁ := Function.update s.bank .left (wordBits (s.words x))
+ let s₂ := Function.update s₁ .right (wordBits (s.words y))
+ have first : (copy x false).Runs (7*w+3) s.bank s₁ := by
+ simpa only [Bool.false_eq_true, ite_false, s₁, Snapshot.bank, length_wordBits, List.length_nil, Nat.zero_add] using
+ copy_runs x false s.bank rfl rfl
+ have second : (copy y true).Runs (7*w+3) s₁ s₂ := by
+ have h := copy_runs y true s₁ rfl rfl
+ change (copy y true).Runs (0 + 7*(wordBits (s.words y)).length+3) s₁ s₂ at h
+ simpa only [length_wordBits, Nat.zero_add] using h
+ have hc (q : Comparison.State) (hq : (Comparison.code op q).returns = false) :
+ (scanFlag op).body.standalone (some q) = (Comparison.code op q).rename cmpPorts some := by
+ cases q with
+ | scan => rfl
+ | done => contradiction
+ have scan := (Comparison.word_run op (s.words x) (s.words y)).lift cmpPorts cmp_inj some s.bank hc
+ have hi : installStacks cmpPorts s.bank (scanStacks (wordBits (s.words x)) (wordBits (s.words y)) [] []) = s₂ := by
+ apply installStacks_frame cmp_inj
+ · intro i; cases i <;> rfl
+ · intro j hj
+ exact (Function.update_of_ne (Ne.symm (hj .right)) ..).trans
+ (Function.update_of_ne (Ne.symm (hj .left)) ..)
+ have ho : installStacks cmpPorts s.bank (scanStacks [] [] [] []) = s.bank :=
+ installStacks_eq cmp_inj s.bank _ (fun i => by cases i <;> rfl)
+ rw [hi, ho] at scan
+ let b := op.eval (s.words x) (s.words y)
+ have push : StackRuns (scanFlag op).body.standalone 1 (some (.done b)) s.bank none
+ (Function.update s.bank .left [b]) := .cons (.push rfl) (.nil ..)
+ have hr : (scanFlag op).Runs ((6*w+3)+1) s₂ (Function.update s.bank .left [b]) := scan.trans push
+ rw [show 20*w+10 = (7*w+3+(7*w+3)) + ((6*w+3)+1) by omega]
+ exact FiniteRoutine.Runs.followedBy (FiniteRoutine.Runs.followedBy first second) hr
+
+end RAMTape.SiteTests
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProcessorState.lean b/lean/OAI/Computability/VPVNP/RAMProcessorState.lean
new file mode 100644
index 0000000000..436dbcee52
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProcessorState.lean
@@ -0,0 +1,218 @@
+import OAI.Computability.VPVNP.RAMProcessorBank
+import OAI.Computability.VPVNP.RAMProcessorProbeFields
+import Mathlib.Tactic.FinCases
+
+/-!
+# The physical bank at call-segment boundaries
+
+This representation names every stack used by the opcode, credit, probe, test,
+and record routines. Shared fields occupy a single stack. The same incoming
+choices, cost, persistent word, and probe ordinal are therefore visible at each
+stage without copying or consulting a global message assignment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessor
+
+open BurstRAM PrivateRAM
+
+variable {w p r k : ℕ}
+
+/-- Place each probe-stage port in the shared site-processor bank, reusing the ISA, choice,
+record-field, and running-status stacks and assigning two scratch stacks for copies. -/
+def probePorts : ProbeStages.Port r k → Port r k
+ | .inl i => .isa i
+ | .inr .choices => .test .choices
+ | .inr .tag => .record (.field 0)
+ | .inr .address => .record (.field 1)
+ | .inr .value => .record (.field 2)
+ | .inr .running => .test (.bit .running)
+ | .inr .copyA => .scratch 0
+ | .inr .copyB => .scratch 1
+
+theorem probePorts_injective : Function.Injective (@probePorts r k) := by
+ intro i j he
+ rcases i with i | a <;> rcases j with j | b
+ · exact congrArg Sum.inl (Port.isa.inj he)
+ · cases b <;> contradiction
+ · cases a <;> contradiction
+ · cases a <;> cases b <;> simp_all [probePorts]
+
+/-- The record buffer is already in reverse serialization order. Its
+remaining stack contains one mark for each unoccupied slot. -/
+structure Snapshot (w p r k : ℕ) where
+ /-- Public operand words read by the instruction table during a call. -/
+ pub : Fin k → Word w
+ /-- Current program counter, persistent word, registers, and private-memory write log of the
+ simulated RAM. -/
+ cfg : LogConfig w p r
+ /-- Public call-cost allowance copied into the call counter when a fresh call begins. -/
+ publicH : ℕ
+ /-- Public instruction allowance used to reset the fuel of each new call. -/
+ publicFuel : ℕ
+ /-- Instructions still available to the currently simulated call. -/
+ fuel : ℕ
+ /-- Remaining units of call cost available under the current call’s allowance. -/
+ callLeft : ℕ
+ /-- Remaining call-cost units in this site’s budget for its local loop. -/
+ siteLeft : ℕ
+ /-- Word encoding the upper bound on cumulative call cost for the entire computation. -/
+ cap : Word w
+ /-- Word holding the remaining global cost credit after charges already incurred. -/
+ globalLeft : Word w
+ /-- Cumulative cost charged so far, counting one unit per call and one per external probe. -/
+ cost : Word w
+ /-- Bits of the start-cost field staged for the next record. For a probe this is the
+ cumulative cost before its call. -/
+ savedStart : List Bool
+ /-- Bits encoding the next probe’s zero-based ordinal within the current call. -/
+ ordinal : List Bool
+ /-- Lower endpoint of the current site’s cost bucket, used to check the incoming running cut. -/
+ lower : Word w
+ /-- Upper endpoint of the site’s cost bucket. A running computation continues here while its
+ cost is below this word. -/
+ boundary : Word w
+ /-- Cumulative cost advertised by the outgoing successor message for the end-of-site check. -/
+ targetCost : Word w
+ /-- Persistent word advertised by the outgoing cut when the target is running. -/
+ targetState : Word w
+ /-- Whether the computation at the current cut has a running persistent state. -/
+ running : Bool
+ /-- Whether this site has an outgoing successor cut to check at its boundary. -/
+ hasTarget : Bool
+ /-- Running-status bit of the advertised outgoing cut. -/
+ targetRunning : Bool
+ /-- Unconsumed private choice bits for RAM branches and guessed external-read answers. -/
+ choices : List Bool
+ /-- Serialized kind word staged for the current initialization, read, or write record. -/
+ tag : List Bool
+ /-- Address bits staged for the record that the processor is about to emit. -/
+ address : List Bool
+ /-- Value bits staged for the initialization, read, or write at the recorded address. -/
+ value : List Bool
+ /-- One stack marker for each vacant slot in the site’s fixed-capacity record buffer. -/
+ remaining : List Bool
+ /-- Accumulated serialized record bits in reverse order, ready to be reversed into the output
+ block. -/
+ reverseBuffer : List Bool
+ /-- Stack receiving the padded record block in forward serialization order. -/
+ output : List Bool
+
+/-- Expose the public limits, remaining credits, cumulative cost, saved start cost, and probe
+ordinal on the credit routine’s ports. -/
+def Snapshot.credit (s : Snapshot w p r k) : Stacks CallCredit.Port :=
+ CallCredit.bank s.publicH s.publicFuel s.fuel s.callLeft s.siteLeft s.cap s.globalLeft s.cost s.savedStart s.ordinal
+
+/-- Project the bucket endpoints, current cut, outgoing target, status flags, and remaining
+choices onto the site-test bank. -/
+def Snapshot.tests (s : Snapshot w p r k) : SiteTests.Snapshot w where
+ words
+ | .lower => s.lower
+ | .cost => s.cost
+ | .cap => s.cap
+ | .state => s.cfg.persistent
+ | .boundary => s.boundary
+ | .targetCost => s.targetCost
+ | .targetState => s.targetState
+ flags
+ | .running => s.running
+ | .hasTarget => s.hasTarget
+ | .targetRunning => s.targetRunning
+ choices := s.choices
+
+/-- Assemble the ISA bank, choice bits, staged record fields, and running flag used by the
+probe handlers. -/
+def Snapshot.probe (s : Snapshot w p r k) : ProbeStages.Bank r k where
+ isa := ISA.configBank s.pub s.cfg
+ choices := s.choices
+ tag := s.tag
+ address := s.address
+ value := s.value
+ running := [s.running]
+
+/-- Arrange the five staged record fields, zero padding, vacant-slot markers, and serialization
+buffers on the record routine’s ports. -/
+def Snapshot.records (s : Snapshot w p r k) : Stacks RecordBuffer.Port
+ | .field i => ![s.tag, s.address, s.value, s.savedStart, s.ordinal] i
+ | .temp => []
+ | .zeros => List.replicate w false
+ | .remaining => s.remaining
+ | .reverseBuffer => s.reverseBuffer
+ | .output => s.output
+
+/-- Unused copies of aliased port labels stay blank. -/
+def Snapshot.bank (s : Snapshot w p r k) : Stacks (Port r k)
+ | .isa i => ISA.configBank s.pub s.cfg i
+ | .credit i => s.credit i
+ | .test (.word .cost) | .test (.word .cap) | .test (.word .state) => []
+ | .test i => s.tests.bank i
+ | .record (.field i) => if i = 3 ∨ i = 4 then [] else s.records (.field i)
+ | .record i => s.records i
+ | .scratch _ => []
+
+theorem Snapshot.local_at (s : Snapshot w p r k) (j : LocalProcessor.Port r k) :
+ s.bank (localPorts j) = LocalProcessor.store s.pub s.cfg s.fuel s.choices j := by
+ rcases j with j | b
+ · rfl
+ · cases b <;> rfl
+
+theorem Snapshot.test_at (s : Snapshot w p r k) (j : SiteTests.Port) :
+ s.bank (testPorts j) = s.tests.bank j := by
+ cases j with
+ | word f => cases f <;> rfl
+ | _ => rfl
+
+theorem Snapshot.probe_at (s : Snapshot w p r k) (j : ProbeStages.Port r k) :
+ s.bank (probePorts j) = s.probe.stacks j := by
+ rcases j with j | j
+ · rfl
+ · cases j <;> rfl
+
+theorem Snapshot.record_at (s : Snapshot w p r k) (j : RecordBuffer.Port) :
+ s.bank (recordPorts j) = s.records j := by
+ cases j with
+ | field i => fin_cases i <;> rfl
+ | _ => rfl
+
+/-- Install the configuration, remaining fuel, and unused choice bits yielded by a local
+instruction segment. -/
+def Snapshot.afterLocal (s : Snapshot w p r k) (y : LocalProcessor.Yield w p r) : Snapshot w p r k :=
+ {s with cfg := y.cfg, fuel := y.fuel, choices := y.bits}
+
+/-- A local segment changes only its ISA bank, remaining fuel, and choices. -/
+theorem Snapshot.installLocal (s : Snapshot w p r k) (y : LocalProcessor.Yield w p r) :
+ installStacks localPorts s.bank (LocalProcessor.store s.pub y.cfg y.fuel y.bits) =
+ (s.afterLocal y).bank := by
+ apply installStacks_frame localPorts_injective
+ · exact (s.afterLocal y).local_at
+ · intro j hj
+ cases j with
+ | isa i => exact (hj (.inl i) rfl).elim
+ | credit i =>
+ cases i with
+ | budget i => cases i <;> first | rfl | exact (hj (.inr false) rfl).elim
+ | _ => rfl
+ | test i =>
+ cases i with
+ | choices => exact (hj (.inr true) rfl).elim
+ | word f => cases f <;> rfl
+ | _ => rfl
+ | record i => cases i <;> rfl
+ | scratch _ => rfl
+
+theorem Snapshot.runLocal (s : Snapshot w p r k) (T : Template p r k) (limit : ℕ)
+ (hl : s.cfg.writes.length+s.fuel ≤ limit) :
+ let y := LocalProcessor.scan T s.pub s.fuel s.cfg s.choices
+ ∃ t ≤ s.fuel*(ISA.prepareBound w limit+4)+1,
+ (localBlock T s.cfg.pc).Runs t s.bank y.exit (s.afterLocal y).bank := by
+ obtain ⟨t, ht, run⟩ := localBlock_run T s.pub s.fuel s.cfg s.choices limit hl s.bank s.local_at
+ exact ⟨t, ht, s.installLocal _ ▸ run⟩
+
+end RAMTape.SiteProcessor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMProgram.lean b/lean/OAI/Computability/VPVNP/RAMProgram.lean
new file mode 100644
index 0000000000..0e5795e9cf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMProgram.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.RAMExecution
+
+/-!
+# Elementary programs for the burst RAM
+
+A fixed finite instruction table and finite public constants specify the private
+word computation of a call in Lemma 10.1. Register operands and instruction
+destinations are bounded indices into the fixed machine. Private and external
+addresses are full words. Private memory and registers start at zero on each
+call, while the persistent input is separately available to its instructions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM
+
+open VPVNP.BurstRAM
+
+/-- Arithmetic uses reduction modulo the word modulus. Division and remainder
+use Lean's natural-number conventions on a zero divisor. Shifts by at least
+the word width have value zero. -/
+inductive BinaryOp where
+ | add | sub | mul | div | mod | bitAnd | bitOr | bitXor | shiftLeft | shiftRight
+ deriving DecidableEq
+
+variable {w p r k : ℕ}
+
+/-- Evaluate a binary arithmetic or bitwise opcode on width-w words. Arithmetic results are
+word-sized, and a shift by at least the word width yields zero. -/
+def BinaryOp.eval : BinaryOp → Word w → Word w → Word w
+ | .add, x, y => x + y
+ | .sub, x, y => x - y
+ | .mul, x, y => x * y
+ | .div, x, y => Fin.ofNat _ (x.val / y.val)
+ | .mod, x, y => Fin.ofNat _ (x.val % y.val)
+ | .bitAnd, x, y => Fin.ofNat _ (x.val &&& y.val)
+ | .bitOr, x, y => Fin.ofNat _ (x.val ||| y.val)
+ | .bitXor, x, y => Fin.ofNat _ (x.val ^^^ y.val)
+ | .shiftLeft, x, y => if y.val < w then Fin.ofNat _ (x.val <<< y.val) else 0
+ | .shiftRight, x, y => if y.val < w then Fin.ofNat _ (x.val >>> y.val) else 0
+
+/-- Each instruction has constant arity. The conditional tests and branch
+choices designate two program counters; every other continuing instruction
+designates one. -/
+inductive Instr (w p r k : ℕ) where
+ | constant (dst : Fin r) (value : Word w) (next : Fin p)
+ | publicWord (dst : Fin r) (index : Fin k) (next : Fin p)
+ | stateWord (dst : Fin r) (next : Fin p)
+ | copy (dst src : Fin r) (next : Fin p)
+ | binary (op : BinaryOp) (dst lhs rhs : Fin r) (next : Fin p)
+ | loadPrivate (dst addr : Fin r) (next : Fin p)
+ | storePrivate (addr src : Fin r) (next : Fin p)
+ | jumpEq (lhs rhs : Fin r) (yes no : Fin p)
+ | jumpLt (lhs rhs : Fin r) (yes no : Fin p)
+ | choose (yes no : Fin p)
+ | readExternal (dst addr : Fin r) (next : Fin p)
+ | writeExternal (addr src : Fin r) (next : Fin p)
+ | returnState (src : Fin r)
+ | accept
+ | reject
+ deriving DecidableEq
+
+/-- Finite instruction table for a burst RAM call, with an entry counter and an indexed table
+of public operand words. -/
+structure Machine (w p r k : ℕ) where
+ /-- Program counter at which every fresh call starts. -/
+ entry : Fin p
+ /-- Instruction fetched at each of the machine’s finite program counters. -/
+ code : Fin p → Instr w p r k
+ /-- Public operand words addressed by the machine’s public-word load instructions. -/
+ publicData : Fin k → Word w
+
+/-- Private RAM state within one call, consisting of its program counter, persistent input
+word, registers, and addressable private memory. -/
+structure Config (w p r : ℕ) where
+ /-- Program counter used to fetch the next instruction. -/
+ pc : Fin p
+ /-- Incoming persistent state word available to state-word loads during the call. -/
+ persistent : Word w
+ /-- Private word stored in each of the call’s registers. -/
+ reg : Fin r → Word w
+ /-- Private word memory indexed by a word address and initialized to zero at call entry. -/
+ privateMem : Word w → Word w
+
+/-- Write a value to the destination register and advance to the given program counter. -/
+def Config.put (c : Config w p r) (next : Fin p) (dst : Fin r) (v : Word w) : Config w p r :=
+ { c with pc := next, reg := Function.update c.reg dst v }
+
+/-- Write a word at a private-memory address and advance to the given program counter. -/
+def Config.store (c : Config w p r) (next : Fin p) (addr v : Word w) : Config w p r :=
+ { c with pc := next, privateMem := Function.update c.privateMem addr v }
+
+/-- Interpret one instruction as a local step, binary choice, external memory probe, return of
+a persistent word, accepting halt, or rejection. -/
+def Instr.run (i : Instr w p r k) (pub : Fin k → Word w) (c : Config w p r) :
+ CallAction w (Config w p r) :=
+ match i with
+ | .constant dst v next => .localStep (c.put next dst v)
+ | .publicWord dst j next => .localStep (c.put next dst (pub j))
+ | .stateWord dst next => .localStep (c.put next dst c.persistent)
+ | .copy dst src next => .localStep (c.put next dst (c.reg src))
+ | .binary op dst x y next => .localStep (c.put next dst (op.eval (c.reg x) (c.reg y)))
+ | .loadPrivate dst addr next => .localStep (c.put next dst (c.privateMem (c.reg addr)))
+ | .storePrivate addr src next => .localStep (c.store next (c.reg addr) (c.reg src))
+ | .jumpEq x y yes no => .localStep {c with pc := if c.reg x = c.reg y then yes else no}
+ | .jumpLt x y yes no => .localStep {c with pc := if c.reg x < c.reg y then yes else no}
+ | .choose yes no => .branch fun b => {c with pc := if b then yes else no}
+ | .readExternal dst addr next => .read (c.reg addr) fun v => c.put next dst v
+ | .writeExternal addr src next => .write (c.reg addr) (c.reg src) {c with pc := next}
+ | .returnState src => .finish (some (c.reg src))
+ | .accept => .finish none
+ | .reject => .reject
+
+/-- Executable translation to the burst interpreter. Resetting the private
+workspace is part of call entry in this machine model. -/
+def Machine.program (M : Machine w p r k) : Program w (Config w p r) where
+ start s := ⟨M.entry, s, fun _ => 0, fun _ => 0⟩
+ step c := (M.code c.pc).run M.publicData c
+
+theorem Machine.start_spec (M : Machine w p r k) (s : Word w) :
+ (M.program.start s).pc = M.entry ∧ (M.program.start s).persistent = s ∧
+ (∀ i, (M.program.start s).reg i = 0) ∧ (∀ a, (M.program.start s).privateMem a = 0) :=
+ ⟨rfl, rfl, fun _ => rfl, fun _ => rfl⟩
+
+/-- The value returned by an external read is available to every later
+instruction, in particular to the address operand of another probe. -/
+theorem Machine.step_read (M : Machine w p r k) (c : Config w p r)
+ {dst addr : Fin r} {next : Fin p} (h : M.code c.pc = .readExternal dst addr next) :
+ M.program.step c = .read (c.reg addr) (fun v => c.put next dst v) := by
+ simp [Machine.program, h, Instr.run]
+
+@[simp] theorem Config.put_same (c : Config w p r) (next : Fin p) (dst : Fin r) (v : Word w) :
+ (c.put next dst v).reg dst = v := by simp [Config.put]
+
+@[simp] theorem Config.store_same (c : Config w p r) (next : Fin p) (a v : Word w) :
+ (c.store next a v).privateMem a = v := by simp [Config.store]
+
+theorem Config.store_other (c : Config w p r) (next : Fin p) (a b v : Word w) (h : b ≠ a) :
+ (c.store next a v).privateMem b = c.privateMem b := by
+ simp [Config.store, Function.update_of_ne h]
+
+/-- Two consecutive external reads can use the answer of the first as the
+address of the second. This is the native execution rule on actual memory. -/
+theorem Machine.execute_dependent_reads (M : Machine w p r k) (c : Config w p r)
+ (mem : Memory w) (bits : List Bool) (fuel : ℕ) {dst addr dst' : Fin r} {next next' : Fin p}
+ (h₁ : M.code c.pc = .readExternal dst addr next)
+ (h₂ : M.code next = .readExternal dst' dst next') :
+ let a := c.reg addr
+ let v := mem a.val
+ let u := mem v.val
+ execute M.program (fuel + 2) c mem bits =
+ ((execute M.program fuel ((c.put next dst v).put next' dst' u) mem bits).map
+ (Report.prepend (.read v u))).map (Report.prepend (.read a v)) := by
+ dsimp only
+ have hs := M.step_read (c.put next dst (mem (c.reg addr).val)) h₂
+ simp only [execute, M.step_read c h₁, hs, Config.put_same]
+
+/-- A conservative word-operation accounting for a dispatch: instruction
+fetch and program-counter update, operand reads, one arithmetic operation
+or comparison, and a destination write. Read/write probe logging and guess
+bits are counted separately. -/
+def Instr.wordWork : Instr w p r k → ℕ
+ | .constant .. | .stateWord .. => 3
+ | .publicWord .. | .copy .. => 4
+ | .binary .. => 6
+ | .loadPrivate .. | .storePrivate .. | .jumpEq .. | .jumpLt .. => 5
+ | .choose .. => 3
+ | .readExternal .. | .writeExternal .. => 4
+ | .returnState .. => 2
+ | .accept | .reject => 1
+
+theorem Instr.wordWork_le (i : Instr w p r k) : i.wordWork ≤ 6 := by
+ cases i <;> simp [Instr.wordWork]
+
+end BurstRAM.PrivateRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMRecordBlocks.lean b/lean/OAI/Computability/VPVNP/RAMRecordBlocks.lean
new file mode 100644
index 0000000000..38a5809fd0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMRecordBlocks.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.RAMRecords
+
+/-!
+# Padded record blocks for the RAM transcript
+
+Each site in Lemma 10.1 contributes one initialization record, the probes of the
+calls whose starting costs belong to that site, and enough empty slots to fill
+a block of size `4H`. Filtering the physical array to its occupied slots gives
+exactly the initialization and probe records, up to permutation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMMemory
+
+variable {w : ℕ}
+
+/-- Fill the slots in a single site. The cost of its first call is supplied
+by the predecessor, so probe timestamps are global across sites. -/
+def siteRecordBlock (header : ℕ → Word w) (H site start : ℕ) (rs : List (Report w)) :
+ List (Option (Record (Word w))) :=
+ let records := initRecord header site :: probeRecords start rs
+ records.map some ++ List.replicate (4 * H - records.length) none
+
+theorem siteRecordBlock_occupied (header : ℕ → Word w) (H site start : ℕ)
+ (rs : List (Report w)) :
+ (siteRecordBlock header H site start rs).filterMap id =
+ initRecord header site :: probeRecords start rs := by
+ simp [siteRecordBlock, List.filterMap_map]
+
+theorem length_siteRecordBlock (header : ℕ → Word w) (H site start : ℕ) (rs : List (Report w))
+ (hfit : 1 + RAMBuckets.probeCount Report.probes rs ≤ 4 * H) :
+ (siteRecordBlock header H site start rs).length = 4 * H := by
+ simp only [siteRecordBlock, List.length_append, List.length_map, List.length_cons,
+ List.length_replicate, length_probeRecords]
+ omega
+
+/-- Encode consecutive sites starting at `site`, maintaining the actual
+cumulative cost across the entire chain, including the sites after halt. -/
+def recordBlocks (header : ℕ → Word w) (H : ℕ) :
+ ℕ → ℕ → List (List (Report w)) → List (List (Option (Record (Word w))))
+ | _, _, [] => []
+ | site, start, front :: rest =>
+ siteRecordBlock header H site start front ::
+ recordBlocks header H (site + 1) (start + RAMBuckets.cost Report.probes front) rest
+
+theorem length_recordBlocks (header : ℕ → Word w) (H site start : ℕ)
+ (blocks : List (List (Report w))) :
+ (recordBlocks header H site start blocks).length = blocks.length := by
+ induction blocks generalizing site start with
+ | nil => rfl
+ | cons front rest ih => simp [recordBlocks, ih]
+
+theorem recordBlocks_width (header : ℕ → Word w) (H site start : ℕ)
+ (blocks : List (List (Report w)))
+ (hfit : ∀ rs ∈ blocks, 1 + RAMBuckets.probeCount Report.probes rs ≤ 4 * H) :
+ ∀ block ∈ recordBlocks header H site start blocks, block.length = 4 * H := by
+ induction blocks generalizing site start with
+ | nil => simp [recordBlocks]
+ | cons front rest ih =>
+ intro block hblock
+ rcases List.mem_cons.mp hblock with rfl | hmem
+ · exact length_siteRecordBlock header H site start front (hfit front (List.mem_cons_self ..))
+ · exact ih _ _ (fun rs hrs => hfit rs (List.mem_cons_of_mem _ hrs)) block hmem
+
+/-- The cost supplied to a site's encoder is the sum of the charges at
+all preceding sites. Empty buckets contribute no charge. -/
+theorem getElem_recordBlocks (header : ℕ → Word w) (H site start : ℕ)
+ (blocks : List (List (Report w))) (i : ℕ) (hi : i < blocks.length) :
+ (recordBlocks header H site start blocks)[i]'(by simpa [length_recordBlocks] using hi) =
+ siteRecordBlock header H (site + i)
+ (start + RAMBuckets.cost Report.probes (blocks.take i).flatten) blocks[i] := by
+ induction blocks generalizing site start i with
+ | nil => simp at hi
+ | cons front rest ih =>
+ cases i with
+ | zero => simp [recordBlocks, RAMBuckets.cost]
+ | succ i =>
+ have hrest : i < rest.length := by simpa using hi
+ simpa [recordBlocks, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm] using
+ ih (site + 1) (start + RAMBuckets.cost Report.probes front) i hrest
+
+/-- Gather the initialization records in address order and the probes in time
+order. Their interleaving within the physical array preserves their multiset. -/
+theorem recordBlocks_perm (header : ℕ → Word w) (H site start : ℕ)
+ (blocks : List (List (Report w))) :
+ ((List.range' site blocks.length).map (initRecord header) ++
+ probeRecords start blocks.flatten).Perm
+ ((recordBlocks header H site start blocks).flatten.filterMap id) := by
+ induction blocks generalizing site start with
+ | nil => simp [recordBlocks, probeRecords]
+ | cons front rest ih =>
+ simp only [List.length_cons, List.range'_succ, List.map_cons, List.flatten_cons,
+ probeRecords_append, List.cons_append, recordBlocks, List.filterMap_append,
+ siteRecordBlock_occupied]
+ apply List.Perm.cons
+ exact (List.perm_append_comm_assoc _ _ _).trans ((ih _ _).append_left _)
+
+/-- The input blocks for the global sort, obtained from the unique grouping
+by starting costs. Even sites with no calls contribute their header record. -/
+def canonicalRecordBlocks (header : ℕ → Word w) (S H : ℕ) (rs : List (Report w)) :
+ List (List (Option (Record (Word w)))) :=
+ recordBlocks header H 0 0 (RAMBuckets.partition Report.probes H 0 S 0 rs)
+
+theorem length_canonicalRecordBlocks (header : ℕ → Word w) (S H : ℕ) (rs : List (Report w)) :
+ (canonicalRecordBlocks header S H rs).length = S := by
+ simp [canonicalRecordBlocks, length_recordBlocks]
+
+/-- Read the physical row at site `v` directly from its canonical bucket,
+using the total cost of the preceding buckets as its start. -/
+theorem getElem_canonicalRecordBlocks (header : ℕ → Word w) (S H : ℕ)
+ (rs : List (Report w)) (v : Fin S) :
+ let buckets := RAMBuckets.partition Report.probes H 0 S 0 rs
+ (canonicalRecordBlocks header S H rs)[v.val]'(by simp [length_canonicalRecordBlocks]) = siteRecordBlock header H v.val
+ (RAMBuckets.cost Report.probes (buckets.take v.val).flatten)
+ (buckets[v.val]'(by simp [buckets])) := by
+ simpa [canonicalRecordBlocks] using
+ getElem_recordBlocks header H 0 0 (RAMBuckets.partition Report.probes H 0 S 0 rs)
+ v.val (by simp)
+
+theorem canonicalRecordBlocks_width (header : ℕ → Word w) {S H : ℕ} {rs : List (Report w)}
+ (hH : 0 < H) (hcap : RAMBuckets.cost Report.probes rs ≤ S * H)
+ (hc : ∀ r ∈ rs, 1 + r.probes ≤ H) :
+ ∀ block ∈ canonicalRecordBlocks header S H rs, block.length = 4 * H :=
+ recordBlocks_width header H 0 0 _ fun ys hys =>
+ (RAMBuckets.partition_block_bounds hH hcap hc ys hys).2
+
+theorem length_flatten_canonicalRecordBlocks (header : ℕ → Word w) {S H : ℕ} {rs : List (Report w)}
+ (hH : 0 < H) (hcap : RAMBuckets.cost Report.probes rs ≤ S * H)
+ (hc : ∀ r ∈ rs, 1 + r.probes ≤ H) :
+ (canonicalRecordBlocks header S H rs).flatten.length = S * (4 * H) := by
+ let blocks := canonicalRecordBlocks header S H rs
+ have hlen : blocks.map List.length = List.replicate blocks.length (4 * H) :=
+ List.map_eq_replicate_iff.mpr (canonicalRecordBlocks_width header hH hcap hc)
+ change blocks.flatten.length = S * (4 * H)
+ rw [List.length_flatten, hlen, List.sum_replicate_nat, length_canonicalRecordBlocks]
+
+theorem canonicalRecordBlocks_perm (header : ℕ → Word w) {S H : ℕ} {rs : List (Report w)}
+ (hcap : RAMBuckets.cost Report.probes rs ≤ S * H) :
+ (initialRecords S header ++ probeRecords 0 rs).Perm
+ ((canonicalRecordBlocks header S H rs).flatten.filterMap id) := by
+ have h := RAMBuckets.partition_spec (v := 0) (start := 0) (sites := S)
+ (xs := rs) (fun _ => by simp) (by simpa using hcap)
+ simpa only [canonicalRecordBlocks, RAMBuckets.length_partition, h.1, initialRecords,
+ List.range_eq_range'] using
+ recordBlocks_perm header H 0 0 (RAMBuckets.partition Report.probes H 0 S 0 rs)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMRecordIndex.lean b/lean/OAI/Computability/VPVNP/RAMRecordIndex.lean
new file mode 100644
index 0000000000..680be1a2d7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMRecordIndex.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.RAMSortLayers
+import Mathlib.Data.List.OfFn
+
+/-!
+# Row-major indices for grouped transcript records
+
+The initial record array of Lemma 10.1 has one fixed-width block per group.
+Flattening those blocks reads the global array in increasing address order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+variable {α : Type*}
+
+/-- Reading consecutive aligned blocks enumerates exactly the entries of the large block. -/
+theorem flatten_ofFn_blocks (h d : ℕ) (x : ℕ → α) :
+ (List.ofFn fun v : Fin (2 ^ d) ↦ List.ofFn (block h v.val x)).flatten =
+ List.ofFn (block (h + d) 0 x) := by
+ have hs : 2 ^ (h + d) = 2 ^ d * 2 ^ h := by rw [Nat.add_comm, Nat.pow_add]
+ rw [List.ofFn_congr hs, List.ofFn_mul]
+ simp only [block, Nat.zero_mul, Nat.zero_add]
+ rfl
+
+/-- Look up a slot in the flattened array by its group index and within-group offset. -/
+theorem getElem?_flatten_rect {rows : List (List α)} {W : ℕ}
+ (hw : ∀ r ∈ rows, r.length = W) {v j : ℕ} (hv : v < rows.length) (hj : j < W) :
+ rows.flatten[v * W + j]? = rows[v][j]? := by
+ induction rows generalizing v with
+ | nil => simp at hv
+ | cons r rows ih =>
+ have hr : r.length = W := hw r (by simp)
+ cases v with
+ | zero =>
+ simpa only [List.flatten_cons, Nat.zero_mul, Nat.zero_add, List.getElem_cons_zero] using
+ (List.getElem?_append_left (l₁ := r) (l₂ := rows.flatten) (i := j) (hr ▸ hj))
+ | succ v =>
+ have hv' : v < rows.length := by simpa using hv
+ simp only [List.flatten_cons, List.getElem_cons_succ, Nat.succ_mul]
+ rw [List.getElem?_append_right (by omega), hr]
+ rw [show v * W + W + j - W = v * W + j by omega]
+ exact ih (fun t ht ↦ hw t (List.mem_cons_of_mem _ ht)) hv'
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMRecordOrder.lean b/lean/OAI/Computability/VPVNP/RAMRecordOrder.lean
new file mode 100644
index 0000000000..c60424700c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMRecordOrder.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.RAMMemory
+
+/-!
+# Deterministic comparison of complete RAM record slots
+
+The sorting network moves a whole five-word record at each comparison.
+The address and timestamp decide the primary order. When keys tie, the
+kind and value distinguish the remaining payload using fields already in
+the record. The unique empty slot sorts after every nonempty one.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMMemory
+
+variable {Word : Type*}
+
+/-- Tie-breaking rank of an initialization, read, or write in the sort order, numbered zero,
+one, and two respectively. -/
+def Kind.code : Kind → ℕ
+ | .init => 0
+ | .read => 1
+ | .write => 2
+
+private theorem kind_code_injective : Function.Injective Kind.code := by
+ intro a b h
+ cases a <;> cases b <;> simp_all [Kind.code]
+
+/-- Physical record with the network's deterministic total order. -/
+structure OrderedSlot (Word : Type*) where
+ /-- Optional memory record at a sorting wire, with the empty option representing a padding
+ slot. -/
+ record : Option (Record Word)
+
+/-- Lexicographic sorting key for an occupied slot, using address and timestamp followed by
+kind rank and value. Padding sorts above every record. -/
+def OrderedSlot.code (s : OrderedSlot Word) :
+ WithTop (Lex (Lex (ℕ × Lex (ℕ × Lex (ℕ × ℕ))) × Lex (ℕ × Word))) :=
+ match s.record with
+ | none => ⊤
+ | some r => ↑(toLex (toLex (r.address, r.timestamp), toLex (Kind.code r.kind, r.value)))
+
+private theorem slot_code_injective : Function.Injective (@OrderedSlot.code Word) := by
+ rintro ⟨a⟩ ⟨b⟩ h
+ cases a with
+ | none =>
+ cases b <;> simp_all [OrderedSlot.code]
+ | some r =>
+ cases b with
+ | none => simp [OrderedSlot.code] at h
+ | some s =>
+ simp [OrderedSlot.code, Record.timestamp] at h
+ obtain ⟨⟨ha, _, hc, hj⟩, hk, hv⟩ := h
+ have he := kind_code_injective hk
+ cases r
+ cases s
+ simp_all
+
+instance [LinearOrder Word] : LinearOrder (OrderedSlot Word) :=
+ LinearOrder.lift' OrderedSlot.code slot_code_injective
+
+/-- Every ascending comparator output is ascending in the paper's primary
+key even when a tie required consulting the remaining fields. -/
+theorem paddedKey_mono [LinearOrder Word] : Monotone (fun s : OrderedSlot Word => paddedKey s.record) := by
+ rintro ⟨a⟩ ⟨b⟩ h
+ change OrderedSlot.code ⟨a⟩ ≤ OrderedSlot.code ⟨b⟩ at h
+ cases a with
+ | none =>
+ cases b <;> simp_all [OrderedSlot.code, paddedKey]
+ | some r =>
+ cases b with
+ | none => simp [paddedKey]
+ | some s =>
+ simp only [OrderedSlot.code, WithTop.coe_le_coe, Prod.Lex.toLex_le_toLex] at h
+ simpa [paddedKey] using h.elim le_of_lt (fun e => e.1.le)
+
+end RAMMemory
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMRecords.lean b/lean/OAI/Computability/VPVNP/RAMRecords.lean
new file mode 100644
index 0000000000..e48239ebf6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMRecords.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.RAMBuckets
+import OAI.Computability.VPVNP.RAMExecution
+import OAI.Computability.VPVNP.RAMMemory
+
+/-!
+# Chronological probe records of a burst RAM execution
+
+In Lemma 10.1 each external read or write emits a five-word record, carrying
+its call's starting cost and its ordinal among the probes of that call.
+Internal steps and binary choices produce no records. These timestamps are
+strictly increasing, and the record-level memory checks recover the read
+semantics of the original events.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMMemory
+
+variable {w : ℕ}
+
+/-- The number of external word probes made by the events. -/
+def countProbes : List (Event w) → ℕ
+ | [] => 0
+ | .read _ _ :: es | .write _ _ :: es => 1 + countProbes es
+ | _ :: es => countProbes es
+
+/-- Number of external read and write events in this call report. -/
+def Report.probes (r : Report w) : ℕ := countProbes r.events
+
+/-- Probe ordinals start at zero and advance only at external reads and writes. -/
+def eventRecords (start : ℕ) : ℕ → List (Event w) → List (Record (Word w))
+ | _, [] => []
+ | j, .read a v :: es => ⟨.read, a.val, v, start, j⟩ :: eventRecords start (j + 1) es
+ | j, .write a v :: es => ⟨.write, a.val, v, start, j⟩ :: eventRecords start (j + 1) es
+ | j, _ :: es => eventRecords start j es
+
+/-- All non-initialization records emitted by the sequence of calls. -/
+def probeRecords : ℕ → List (Report w) → List (Record (Word w))
+ | _, [] => []
+ | start, r :: rs => eventRecords start 0 r.events ++
+ probeRecords (start + (1 + r.probes)) rs
+
+theorem length_eventRecords (start j : ℕ) (es : List (Event w)) :
+ (eventRecords start j es).length = countProbes es := by
+ induction es generalizing j with
+ | nil => rfl
+ | cons e es ih => cases e <;> simp [eventRecords, countProbes, ih, Nat.add_comm]
+
+theorem length_probeRecords (start : ℕ) (rs : List (Report w)) :
+ (probeRecords start rs).length = RAMBuckets.probeCount Report.probes rs := by
+ induction rs generalizing start with
+ | nil => rfl
+ | cons r rs ih =>
+ simp [probeRecords, RAMBuckets.probeCount, length_eventRecords, ih, Report.probes]
+
+theorem probeRecords_append (start : ℕ) (rs ts : List (Report w)) :
+ probeRecords start (rs ++ ts) = probeRecords start rs ++
+ probeRecords (start + RAMBuckets.cost Report.probes rs) ts := by
+ induction rs generalizing start with
+ | nil => simp [probeRecords, RAMBuckets.cost]
+ | cons r rs ih => simp [probeRecords, RAMBuckets.cost, ih, List.append_assoc, Nat.add_assoc]
+
+theorem mem_eventRecords {start j : ℕ} {es : List (Event w)} {r : Record (Word w)}
+ (h : r ∈ eventRecords start j es) :
+ r.kind ≠ .init ∧ r.startCost = start ∧ j ≤ r.ordinal := by
+ induction es generalizing j with
+ | nil => simp [eventRecords] at h
+ | cons e es ih =>
+ cases e with
+ | tick | choice => exact ih h
+ | read a v | write a v =>
+ rcases List.mem_cons.mp h with rfl | ht
+ · simp
+ · obtain ⟨hk, hc, hj⟩ := ih ht
+ exact ⟨hk, hc, by omega⟩
+
+theorem mem_probeRecords {start : ℕ} {rs : List (Report w)} {r : Record (Word w)}
+ (h : r ∈ probeRecords start rs) :
+ r.kind ≠ .init ∧ start ≤ r.startCost := by
+ induction rs generalizing start with
+ | nil => simp [probeRecords] at h
+ | cons s rs ih =>
+ rcases List.mem_append.mp h with hs | ht
+ · obtain ⟨hk, he, _⟩ := mem_eventRecords hs
+ exact ⟨hk, he.ge⟩
+ · obtain ⟨hk, hle⟩ := ih ht
+ exact ⟨hk, by omega⟩
+
+theorem chronological_eventRecords (start j : ℕ) (es : List (Event w)) :
+ Chronological (eventRecords start j es) := by
+ induction es generalizing j with
+ | nil => exact List.Pairwise.nil
+ | cons e es ih =>
+ cases e with
+ | tick | choice => exact ih j
+ | read a v | write a v =>
+ apply List.pairwise_cons.mpr
+ refine ⟨?_, ih (j + 1)⟩
+ intro r hr
+ obtain ⟨hk, hc, hj⟩ := mem_eventRecords hr
+ simpa [Record.timestamp, Prod.Lex.toLex_lt_toLex, hk, hc] using (show j < r.ordinal from hj)
+
+theorem chronological_probeRecords (start : ℕ) (rs : List (Report w)) :
+ Chronological (probeRecords start rs) := by
+ induction rs generalizing start with
+ | nil => exact List.Pairwise.nil
+ | cons r rs ih =>
+ apply List.pairwise_append.mpr
+ refine ⟨chronological_eventRecords .., ih _, ?_⟩
+ intro a ha b hb
+ obtain ⟨hka, hca, _⟩ := mem_eventRecords ha
+ obtain ⟨hkb, hcb⟩ := mem_probeRecords hb
+ have hlt : a.startCost < b.startCost := by omega
+ simp [Record.timestamp, Prod.Lex.toLex_lt_toLex, hka, hkb, hlt]
+
+private theorem eventRecords_reads_append (start j : ℕ) (es tail : List (Event w))
+ (records : List (Record (Word w))) (m : Memory w)
+ (h : ∀ m, ReadsCorrect m records ↔ Correct m tail) :
+ ReadsCorrect m (eventRecords start j es ++ records) ↔ Correct m (es ++ tail) := by
+ induction es generalizing m j with
+ | nil => exact h m
+ | cons e es ih =>
+ cases e with
+ | tick | choice => exact ih j m
+ | read a v =>
+ have hu : afterRecord m ⟨.read, a.val, v, start, j⟩ = m := by
+ funext i
+ simp [afterRecord]
+ simp [eventRecords, ReadsCorrect, Correct, hu, ih]
+ | write a v =>
+ have hu : afterRecord m ⟨.write, a.val, v, start, j⟩ = writeMemory m a v := by
+ funext i
+ simp [afterRecord, writeMemory, Function.update_apply]
+ simp [eventRecords, ReadsCorrect, Correct, update, hu, ih]
+
+/-- Checking all read records chronologically is equivalent to checking the
+actual events, starting from any prescribed external memory. -/
+theorem readsCorrect_probeRecords (start : ℕ) (rs : List (Report w)) (m : Memory w) :
+ ReadsCorrect m (probeRecords start rs) ↔ Correct m (rs.map Report.events).flatten := by
+ induction rs generalizing m start with
+ | nil => rfl
+ | cons r rs ih => exact eventRecords_reads_append _ _ _ _ _ _ (ih _)
+
+/-- The sorted-record check in Lemma 10.1 tests precisely the read answers of
+the original call reports, including the first read at an initialized address. -/
+theorem padded_read_check {S : ℕ} {header : ℕ → Word w} {rs : List (Report w)}
+ {raw sorted : List (Option (Record (Word w)))}
+ (hrecords : (initialRecords S header ++ probeRecords 0 rs).Perm (raw.filterMap id))
+ (hperm : raw.Perm sorted) (hsorted : sorted.Pairwise fun x y => paddedKey x ≤ paddedKey y) :
+ PredecessorCheck none (sorted.filterMap id) ↔
+ Correct (initialMemory S header) (rs.map Report.events).flatten :=
+ (padded_predecessorCheck_iff hrecords hperm hsorted (chronological_probeRecords ..)
+ fun _ hr => (mem_probeRecords hr).1).trans (readsCorrect_probeRecords ..)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSerialization.lean b/lean/OAI/Computability/VPVNP/RAMSerialization.lean
new file mode 100644
index 0000000000..a5278ea937
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSerialization.lean
@@ -0,0 +1,312 @@
+import OAI.Computability.VPVNP.RAMLayout
+import OAI.Computability.VPVNP.RAMWordBounds
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Data.Fin.VecNotation
+
+/-!
+# Binary messages of the RAM transcript
+
+Lemma 10.1 sends an eight-word successor message and a block of `4H`
+five-word records at each cross-site sorting layer. Each word occupies exactly
+`w` bits in little-endian order. The parsers below decode fixed-size fields and
+check the input against the canonical encoding. This rejects unknown tags,
+nonzero padding, and nonzero state fields for halted calls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSerialization
+
+open BurstRAM RAMMemory
+
+/-- Least significant bit first. -/
+def wordBits (w : ℕ) : Word w ≃ (Fin w → Bool) :=
+ finFunctionFinEquiv.symm.trans ((Equiv.refl _).arrowCongr finTwoEquiv)
+
+/-- Concatenate `k` fixed-width words in their given order. -/
+def arrayBits (k w : ℕ) : (Fin k → Word w) ≃ (Fin (k * w) → Bool) :=
+ (((Equiv.refl _).arrowCongr (wordBits w)).trans (Equiv.curry _ _ _).symm).trans
+ (finProdFinEquiv.arrowCongr (Equiv.refl _))
+
+variable {w k : ℕ}
+
+theorem arrayBits_at (a : Fin k → Word w) (i : Fin k) (j : Fin w) :
+ arrayBits k w a (finProdFinEquiv (i, j)) = wordBits w (a i) j := by
+ simp [arrayBits, Equiv.curry]
+
+theorem wordBits_zero (j : Fin w) : wordBits w 0 j = false := by
+ change (finFunctionFinEquiv.symm (0 : Word w) j == 1) = false
+ have hz : finFunctionFinEquiv.symm (0 : Word w) j = 0 := by
+ apply Fin.ext
+ simp [finFunctionFinEquiv_symm_apply_val]
+ simp [hz]
+
+/-- Natural-valued records from the trace, with their word range enforced
+for all three counter/address fields. -/
+structure WordRecord (w : ℕ) where
+ /-- Whether this serialized record describes initialization, an external read, or an external
+ write. -/
+ kind : Kind
+ /-- External word address of the recorded initialization or probe. -/
+ address : Word w
+ /-- Word initialized, returned by a read, or supplied to a write. -/
+ value : Word w
+ /-- Word-sized start-cost field used with the ordinal to order probes from the same address. -/
+ startCost : Word w
+ /-- Word-sized ordinal giving a probe’s position among the external accesses in its call. -/
+ ordinal : Word w
+ deriving DecidableEq
+
+/-- Widen the address, start cost, and ordinal to natural numbers to obtain the memory record
+used by the ordering and read checks. -/
+def WordRecord.record (r : WordRecord w) : Record (Word w) :=
+ ⟨r.kind, r.address.val, r.value, r.startCost.val, r.ordinal.val⟩
+
+/-- Convert a memory record to word fields using bounds on its address, start cost, and
+ordinal. -/
+def WordRecord.ofRecord (r : Record (Word w))
+ (h : RecordFitsWord r) : WordRecord w :=
+ ⟨r.kind, ⟨r.address, h.1⟩, r.value, ⟨r.startCost, h.2.1⟩, ⟨r.ordinal, h.2.2⟩⟩
+
+@[simp] theorem WordRecord.ofRecord_record (r : Record (Word w)) (h) :
+ (WordRecord.ofRecord r h).record = r := rfl
+
+theorem WordRecord.record_injective : Function.Injective (WordRecord.record (w := w)) := by
+ rintro ⟨_, ⟨_, _⟩, _, ⟨_, _⟩, ⟨_, _⟩⟩ ⟨_, ⟨_, _⟩, _, ⟨_, _⟩, ⟨_, _⟩⟩ h
+ cases h
+ rfl
+
+/-- A fixed-length word format with a left inverse. On arbitrary bit strings the
+public decoder checks that re-encoding reproduces every bit. -/
+structure Format (w k : ℕ) (α : Type*) where
+ /-- The fixed array of width-w words that canonically represents a message. -/
+ words : α → Fin k → Word w
+ /-- Recover a candidate message from a fixed word array, with exact recovery on arrays
+ produced by the encoder. -/
+ parse : (Fin k → Word w) → α
+ parse_words : ∀ a, parse (words a) = a
+
+variable {α : Type*}
+
+/-- Concatenate the message’s word fields in order, with each field written least significant
+bit first. -/
+def Format.encode (f : Format w k α) (a : α) : Fin (k * w) → Bool := arrayBits k w (f.words a)
+
+/-- Parse the input bits as a word array and accept the resulting message exactly when
+re-encoding it reproduces the input. -/
+def Format.decode (f : Format w k α) (b : Fin (k * w) → Bool) : Option α :=
+ let x := f.parse ((arrayBits k w).symm b)
+ if f.encode x = b then some x else none
+
+theorem Format.decode_iff (f : Format w k α) (b : Fin (k * w) → Bool) (x : α) :
+ f.decode b = some x ↔ b = f.encode x := by
+ constructor
+ · simp only [Format.decode]
+ split
+ · rename_i h
+ intro he
+ cases he
+ exact h.symm
+ · simp
+ · rintro rfl
+ simp [Format.decode, Format.encode, f.parse_words]
+
+theorem Format.encode_injective (f : Format w k α) : Function.Injective f.encode := by
+ intro x y h
+ exact Option.some.inj (((f.decode_iff _ x).2 rfl).symm.trans ((f.decode_iff _ y).2 h))
+
+/-- The valid binary patterns are in bijection with the typed messages. -/
+def Format.canonicalEquiv (f : Format w k α) : α ≃ {b // (f.decode b).isSome} where
+ toFun a := ⟨f.encode a, by rw [(f.decode_iff _ a).2 rfl]; rfl⟩
+ invFun b := (f.decode b.val).get b.property
+ left_inv a := by
+ apply Option.some.inj
+ exact (Option.some_get _).trans ((f.decode_iff _ a).2 rfl)
+ right_inv b := Subtype.ext ((f.decode_iff _ _).mp (Option.some_get _).symm).symm
+
+private def kindTag : Kind → Fin 4
+ | .init => 1
+ | .read => 2
+ | .write => 3
+
+private def tagWord (hw : 2 ≤ w) (tag : Fin 4) : Word w :=
+ ⟨tag.val, tag.isLt.trans_le (Nat.pow_le_pow_right (by decide : 0 < 2) hw)⟩
+
+/-- `(kind, address, value, start cost, ordinal)`. The all-zero tuple alone
+encodes the empty record. The other tags are 1 for init, 2 for read, 3 for write. -/
+def recordFormat (hw : 2 ≤ w) : Format w 5 (Option (WordRecord w)) where
+ words
+ | none => fun _ ↦ 0
+ | some r => ![tagWord hw (kindTag r.kind), r.address, r.value, r.startCost, r.ordinal]
+ parse a :=
+ let mk := fun k ↦ some (WordRecord.mk k (a 1) (a 2) (a 3) (a 4))
+ match (a 0).val with
+ | 1 => mk .init
+ | 2 => mk .read
+ | 3 => mk .write
+ | _ => none
+ parse_words := by
+ rintro (_ | ⟨k, a, v, c, j⟩)
+ · rfl
+ · cases k <;> rfl
+
+theorem recordFormat_empty (hw : 2 ≤ w) : (recordFormat hw).encode none = fun _ ↦ false := by
+ funext i
+ obtain ⟨⟨j, t⟩, rfl⟩ := finProdFinEquiv.surjective i
+ exact (arrayBits_at _ j t).trans (wordBits_zero t)
+
+/-- Consecutive copies of the same format. Each record occupies its own
+complete five-word interval in a sorting block. -/
+def Format.replicate (f : Format w k α) (m : ℕ) : Format w (m * k) (Fin m → α) where
+ words a i :=
+ let p := finProdFinEquiv.symm i
+ f.words (a p.1) p.2
+ parse a i := f.parse (fun j ↦ a (finProdFinEquiv (i, j)))
+ parse_words a := by
+ funext i
+ simp [f.parse_words]
+
+/-- Format for a sorting block of 4H slots, each occupying five words and holding either a word
+record or canonical padding. -/
+def blockFormat (H : ℕ) (hw : 2 ≤ w) : Format w (4 * H * 5) (Fin (4 * H) → Option (WordRecord w)) :=
+ (recordFormat hw).replicate (4 * H)
+
+theorem block_decode_iff (H : ℕ) (hw : 2 ≤ w) (b : Fin (RAMLayout.blockBits H w) → Bool)
+ (r : Fin (4 * H) → Option (WordRecord w)) :
+ (blockFormat H hw).decode b = some r ↔ b = (blockFormat H hw).encode r :=
+ Format.decode_iff ..
+
+/-- Narrow a padded slot once its three natural-valued fields have been
+checked against the word width. -/
+def narrowSlot (r : Option (Record (Word w))) (h : ∀ t ∈ r, RecordFitsWord t) :
+ Option (WordRecord w) :=
+ match r with
+ | none => none
+ | some t => some (WordRecord.ofRecord t (h t rfl))
+
+@[simp] theorem widen_narrowSlot (r : Option (Record (Word w))) (h) :
+ (narrowSlot r h).map WordRecord.record = r := by cases r <;> rfl
+
+private theorem widenSlot_injective :
+ Function.Injective (Option.map (WordRecord.record (w := w))) := by
+ intro x y h
+ cases x <;> cases y <;> simp_all [WordRecord.record_injective.eq_iff]
+
+/-- Decoding a block produces the same padded-record type that the network sorts. -/
+def decodeBlock (H : ℕ) (hw : 2 ≤ w) (b : Fin (RAMLayout.blockBits H w) → Bool) :
+ Option (Fin (4 * H) → Option (Record (Word w))) :=
+ ((blockFormat H hw).decode b).map fun a i ↦ (a i).map WordRecord.record
+
+/-- Every representable sorting block has just one accepted bit pattern. -/
+theorem decodeBlock_iff (H : ℕ) (hw : 2 ≤ w) (r : Fin (4 * H) → Option (Record (Word w)))
+ (hr : ∀ i t, t ∈ r i → RecordFitsWord t) (b : Fin (RAMLayout.blockBits H w) → Bool) :
+ decodeBlock H hw b = some r ↔
+ b = (blockFormat H hw).encode (fun i ↦ narrowSlot (r i) (hr i)) := by
+ rw [decodeBlock, Option.map_eq_some_iff]
+ constructor
+ · rintro ⟨a, ha, h⟩
+ have he : a = fun i ↦ narrowSlot (r i) (hr i) := by
+ funext i
+ apply widenSlot_injective
+ exact (congrFun h i).trans (widen_narrowSlot _ _).symm
+ rw [← he]
+ exact (block_decode_iff H hw _ _).mp ha
+ · intro h
+ exact ⟨_, (block_decode_iff H hw _ _).mpr h, funext fun i ↦ widen_narrowSlot _ _⟩
+
+/-- In a capped run the representability condition follows from membership
+in the padded input array. It therefore holds in every permuted intermediate
+sorting array. -/
+theorem permuted_block_encoding {S H : ℕ} (hw : 2 ≤ w) (header : ℕ → Word w)
+ {rs : List (Report w)} {out : List (Option (Record (Word w)))}
+ (hH : 0 < H) (hc : RAMBuckets.cost Report.probes rs ≤ S * H) (hword : S * H < 2 ^ w)
+ (hp : (canonicalRecordBlocks header S H rs).flatten.Perm out)
+ (r : Fin (4 * H) → Option (Record (Word w))) (hm : ∀ i, r i ∈ out) :
+ ∃! b, decodeBlock H hw b = some r := by
+ have hr (i : Fin (4 * H)) (t : Record (Word w)) (ht : t ∈ r i) : RecordFitsWord t :=
+ perm_canonicalRecordBlocks_fitsWord header hH hc hword hp (ht ▸ hm i)
+ exact ⟨_, (decodeBlock_iff H hw r hr _).2 rfl, fun _ h ↦ (decodeBlock_iff H hw r hr _).1 h⟩
+
+/-- The paper sets `w = (r+10)^4`, where `r = B ⌈log₂ n⌉`. A polynomial
+site/call budget gives `d+e = log₂ (SH) ≤ K(r+1)` for some fixed `K`.
+Already at `r+1 ≥ K`, all four tags and the final cost `SH` fit. -/
+theorem word_capacity (r d e K : ℕ) (hsize : d + e ≤ K * (r + 1)) (hr : K ≤ r + 1) :
+ 2 ≤ (r + 10) ^ 4 ∧ 2 ^ d * 2 ^ e < 2 ^ ((r + 10) ^ 4) := by
+ have hpow : 2 ≤ (r + 10) ^ 4 := by
+ calc
+ 2 ≤ 10 ^ 4 := by decide
+ _ ≤ _ := Nat.pow_le_pow_left (by omega) _
+ refine ⟨hpow, ?_⟩
+ rw [← pow_add]
+ apply Nat.pow_lt_pow_right (by decide)
+ have hquad := hsize.trans (Nat.mul_le_mul_right (r + 1) hr)
+ calc
+ d + e ≤ (r + 1) ^ 2 := by simpa [pow_two] using hquad
+ _ < (r + 10) ^ 2 := Nat.pow_lt_pow_left (by omega) (by decide)
+ _ ≤ (r + 10) ^ 4 := Nat.pow_le_pow_right (by omega) (by decide)
+
+/-- The status distinguishes a running state word from an accepted halt.
+The actual cumulative cost may equal the global cap. -/
+structure Successor (w cap : ℕ) where
+ /-- Persistent word passed to a running successor, or the empty option for an accepted halt. -/
+ state : Option (Word w)
+ /-- Cumulative cost transmitted across the site boundary, bounded inclusively by the global
+ cap. -/
+ cost : Fin (cap + 1)
+ /-- Last padded slot of the sender’s sorted block, transmitted for the predecessor check
+ across the site boundary. -/
+ lastRecord : Option (WordRecord w)
+
+variable {cap : ℕ}
+
+private def controlWords (hw : 2 ≤ w) (hc : cap < 2 ^ w) (s : Successor w cap) : Fin 3 → Word w :=
+ ![tagWord hw (if s.state.isSome then 1 else 2),
+ ⟨s.cost.val, lt_of_le_of_lt (Nat.le_of_lt_succ s.cost.isLt) hc⟩, s.state.getD 0]
+
+/-- `(status, cost, state)` followed by the last sorted record. Status 1 means
+running and 2 means accepted. On a halt the state word is zero. The whole cost,
+including a final cost exactly `SH`, fits when `SH < 2^w`. -/
+def successorFormat (hw : 2 ≤ w) (hc : cap < 2 ^ w) : Format w 8 (Successor w cap) where
+ words s := Fin.append (controlWords hw hc s) ((recordFormat hw).words s.lastRecord)
+ parse a :=
+ let status := a (Fin.castAdd 5 (0 : Fin 3))
+ let cost := a (Fin.castAdd 5 (1 : Fin 3))
+ let state := a (Fin.castAdd 5 (2 : Fin 3))
+ ⟨if status.val = 1 then some state else none,
+ if h : cost.val ≤ cap then ⟨cost.val, Nat.lt_succ_of_le h⟩ else 0,
+ (recordFormat hw).parse (fun i ↦ a (Fin.natAdd 3 i))⟩
+ parse_words := by
+ rintro ⟨state, cost, last⟩
+ have h := Nat.le_of_lt_succ cost.isLt
+ simp only [Fin.append_left, Fin.append_right, Format.parse_words]
+ cases state <;> simp [controlWords, tagWord, h]
+
+theorem successor_decode_iff (hw : 2 ≤ w) (hc : cap < 2 ^ w) (b : Fin (8 * w) → Bool)
+ (s : Successor w cap) :
+ (successorFormat hw hc).decode b = some s ↔ b = (successorFormat hw hc).encode s :=
+ Format.decode_iff ..
+
+/-- The prescribed all-zero end field cannot be misread as a successor
+message. A validator handles the boundary locally using its site identifier. -/
+theorem clamped_successor (hw : 2 ≤ w) (hc : cap < 2 ^ w) :
+ (successorFormat hw hc).decode (fun _ ↦ false) = none := by
+ cases h : (successorFormat hw hc).decode (fun _ ↦ false) with
+ | none => rfl
+ | some s =>
+ have he := (successor_decode_iff hw hc _ s).mp h
+ have hz : arrayBits 8 w (fun _ ↦ 0) = fun _ ↦ false := by
+ funext i
+ obtain ⟨⟨j, t⟩, rfl⟩ := finProdFinEquiv.surjective i
+ exact (arrayBits_at _ j t).trans (wordBits_zero t)
+ have heq := (arrayBits 8 w).injective (hz.trans he)
+ have htag := congrArg (fun f : Fin 8 → Word w ↦ (f (Fin.castAdd 5 (0 : Fin 3))).val) heq
+ change 0 = (tagWord hw (if s.state.isSome then 1 else 2)).val at htag
+ cases hs : s.state <;> simp [hs, tagWord] at htag
+
+end RAMSerialization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSharedFields.lean b/lean/OAI/Computability/VPVNP/RAMSharedFields.lean
new file mode 100644
index 0000000000..c7d9f01085
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSharedFields.lean
@@ -0,0 +1,139 @@
+import OAI.Computability.VPVNP.RAMLayout
+import Mathlib.Data.Fintype.Pi
+
+/-!
+# Indexing shared assignments by physical sends
+
+A shared assignment in Lemma 10.1 consists of one successor message for each
+of the first `S-1` sites and one sorting send per layer and site. The final
+successor send and the initial successor receive are clamped. The following
+equivalences retain exactly the bits of those actual messages.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMLayout
+
+instance (d : ℕ) : Fintype (Layer d) :=
+ Fintype.ofEquiv (Fin (layerCount d)) (layerEquiv d).symm
+
+instance (d H w : ℕ) : DecidableEq (SharedBit d H w) :=
+ fun x y ↦ decidable_of_iff (x.val = y.val) Subtype.ext_iff.symm
+
+/-- Index of one transmitted bit, either on an internal successor wire or in a specified site’s
+outgoing block for a sorting layer. -/
+abbrev SendIndex (d H w : ℕ) :=
+ (Fin (2 ^ d - 1) × Fin (8 * w)) ⊕ (Layer d × (Fin (2 ^ d) × Fin (blockBits H w)))
+
+variable {d H w : ℕ}
+
+/-- The physical source endpoint of each indexed send. -/
+def sendBit : SendIndex d H w → SharedBit d H w
+ | .inl (u, j) =>
+ let v : Fin (2 ^ d) := ⟨u.val, by have := u.isLt; omega⟩
+ ⟨(v, .inl (0, j)), rfl, by
+ have hv : v.val + 1 < 2 ^ d := by have := u.isLt; dsimp [v]; omega
+ simp [peer, hv]⟩
+ | .inr (s, v, j) => ⟨(v, .inr (s, 0, j)), rfl, by simp [peer]⟩
+
+private theorem existing_successor {v : Fin (2 ^ d)} {j : Fin (8 * w)}
+ (h : (peer (H := H) v (.inl (0, j))).isSome) : v.val < 2 ^ d - 1 := by
+ by_contra hn
+ have hh : ¬ v.val + 1 < 2 ^ d := by omega
+ simp [peer, hh] at h
+
+/-- Recover the array indices of an actual sender from its endpoint. -/
+def indexOfSend (x : SharedBit d H w) : SendIndex d H w :=
+ match h : x.val.2 with
+ | .inl (dir, j) =>
+ .inl (⟨x.val.1.val, existing_successor (H := H) (j := j) (by
+ have hd := x.property.1
+ have hp := x.property.2
+ rw [h] at hd hp
+ change dir = 0 at hd
+ simpa [hd] using hp)⟩, j)
+ | .inr (s, _, j) => .inr (s, x.val.1, j)
+
+/-- Bijection between successor-or-sorting array indices and their physical shared sender
+endpoints. -/
+def sendIndexEquiv (d H w : ℕ) : SendIndex d H w ≃ SharedBit d H w where
+ toFun := sendBit
+ invFun := indexOfSend
+ left_inv i := by
+ rcases i with ⟨⟨v, hv⟩, j⟩ | ⟨s, v, j⟩ <;> rfl
+ right_inv x := by
+ rcases x with ⟨⟨v, ⟨dir, j⟩ | ⟨s, dir, j⟩⟩, hd, _⟩ <;>
+ change dir = 0 at hd <;> subst dir <;> rfl
+
+/-- One successor vector for each internal boundary and one block vector for
+each sorting exchange. Each array entry is the vector sent by the named site. -/
+abbrev SendArrays (d H w : ℕ) :=
+ (Fin (2 ^ d - 1) → Fin (8 * w) → Bool) ×
+ (Layer d → Fin (2 ^ d) → Fin (blockBits H w) → Bool)
+
+/-- Reindex an assignment on shared bits as the array of successor messages and the
+layer-by-site array of sorting blocks. -/
+def sendArraysEquiv (d H w : ℕ) : (SharedBit d H w → Bool) ≃ SendArrays d H w where
+ toFun b := (fun v j ↦ b (sendBit (.inl (v, j))),
+ fun s v j ↦ b (sendBit (.inr (s, v, j))))
+ invFun a x :=
+ match indexOfSend x with
+ | .inl (v, j) => a.1 v j
+ | .inr (s, v, j) => a.2 s v j
+ left_inv b := by
+ funext x
+ obtain ⟨i, rfl⟩ := (sendIndexEquiv d H w).surjective x
+ rcases i with ⟨⟨v, hv⟩, j⟩ | ⟨s, v, j⟩ <;> rfl
+ right_inv a := by
+ apply Prod.ext
+ · funext ⟨v, hv⟩ j
+ rfl
+ · rfl
+
+/-- Reconstruct compatible incident fields from sender-indexed message arrays. -/
+def incidentEquiv (d H w : ℕ) :
+ SendArrays d H w ≃ {b : Endpoint d H w → Bool // Compatible b} :=
+ (sendArraysEquiv d H w).symm.trans (assignmentEquiv d H w)
+
+/-- Linear local bit address for a site's physical sender arrays. -/
+def incidentBits (a : SendArrays d H w) (v : Fin (2 ^ d)) : Fin (width d H w) → Bool :=
+ fun i ↦ (incidentEquiv d H w a).val (v, (offset d H w).symm i)
+
+@[simp] theorem incidentBits_offset (a : SendArrays d H w) (v : Fin (2 ^ d)) (p : Slot d H w) :
+ incidentBits a v (offset d H w p) = (incidentEquiv d H w a).val (v, p) := by
+ simp [incidentBits]
+
+theorem incident_send (a : SendArrays d H w) (i : SendIndex d H w) :
+ (incidentEquiv d H w a).val (sendBit i).val =
+ match i with
+ | .inl (v, j) => a.1 v j
+ | .inr (s, v, j) => a.2 s v j := by
+ have hinv := (assignmentEquiv d H w).symm_apply_apply ((sendArraysEquiv d H w).symm a)
+ have he := congrFun hinv (sendBit i)
+ rcases i with ⟨⟨v, hv⟩, j⟩ | ⟨s, v, j⟩ <;> exact he
+
+theorem incident_receive_sort (a : SendArrays d H w) (s : Layer d) (v : Fin (2 ^ d))
+ (j : Fin (blockBits H w)) :
+ (incidentEquiv d H w a).val (v, .inr (s, 1, j)) = a.2 s (s.partner v) j := by
+ have h : peer v (.inr (s, 1, j)) = some (sendBit (.inr (s, s.partner v, j))).val := rfl
+ exact ((incidentEquiv d H w a).property.2 _ _ h).trans (incident_send a (.inr (s, s.partner v, j)))
+
+theorem incident_receive_successor (a : SendArrays d H w) (v : Fin (2 ^ d)) (hv : 0 < v.val)
+ (j : Fin (8 * w)) :
+ (incidentEquiv d H w a).val (v, .inl (1, j)) =
+ a.1 ⟨v.val - 1, by have := v.isLt; omega⟩ j := by
+ let u : Fin (2 ^ d - 1) := ⟨v.val - 1, by have := v.isLt; omega⟩
+ have h : peer (H := H) v (.inl (1, j)) = some (sendBit (.inl (u, j))).val := by
+ simp [peer, hv, sendBit, u]
+ exact ((incidentEquiv d H w a).property.2 _ _ h).trans (incident_send a (.inl (u, j)))
+
+theorem incident_clamp (a : SendArrays d H w) (x : Endpoint d H w) (h : peer x.1 x.2 = none) :
+ (incidentEquiv d H w a).val x = false := (incidentEquiv d H w a).property.1 x h
+
+end RAMLayout
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSiteBounds.lean b/lean/OAI/Computability/VPVNP/RAMSiteBounds.lean
new file mode 100644
index 0000000000..86fec32fad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSiteBounds.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.RAMClock
+import OAI.Computability.VPVNP.RAMSiteInput
+import Mathlib.Analysis.SpecialFunctions.Pow.Real
+
+/-!
+# Processor strings and counters at large lengths
+
+The logarithmic address and quartic word width can be fixed before selecting
+a successful circuit length. The shared messages fit in the processor input
+under the live bucket's strictly sublinear growth. The same word width holds
+every counter bounded by a fixed polynomial in the input length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open Filter RAMLayout
+
+theorem polynomial_lt_wordModulus {n r a : ℕ} (hn : 0 < n) (hr : n.log2 ≤ r) (ha : a ≤ r+1) :
+ n^a < 2^((r+10)^4) := by
+ have h := (Nat.log2_lt hn.ne').mp (Nat.lt_succ_self n.log2)
+ have he : (n.log2+1)*a < (r+10)^4 := by
+ have hle := Nat.mul_le_mul (Nat.succ_le_succ hr) ha
+ have hsq : (r+1)^2 < (r+10)^2 := Nat.pow_lt_pow_left (by omega) (by decide)
+ have hsq' : (r+1)*(r+1) < (r+10)^2 := by simpa only [pow_two] using hsq
+ exact lt_of_le_of_lt hle (hsq'.trans_le
+ (Nat.pow_le_pow_right (by omega) (by decide : 2 ≤ 4)))
+ exact (Nat.pow_le_pow_left h.le a).trans_lt (by
+ rw [← pow_mul]
+ exact Nat.pow_lt_pow_right (by decide) he)
+
+/-- Any fixed power eventually fits a word, uniformly in all address
+widths at least `log₂ n`. -/
+theorem eventually_polynomial_lt_wordModulus (a : ℕ) :
+ ∀ᶠ n : ℕ in atTop, ∀ r, n.log2 ≤ r → n^a < 2^((r+10)^4) := by
+ filter_upwards [eventually_ge_atTop (2^a)] with n hn
+ have hn0 : 0 < n := (Nat.two_pow_pos _).trans_le hn
+ intro r hr
+ apply polynomial_lt_wordModulus hn0 hr
+ have := (Nat.le_log2 hn0.ne').mpr hn
+ omega
+
+/-- Any fixed log-polynomial factor fits inside an arbitrarily small
+positive power. This handles the overhead from words, stages and field tags. -/
+theorem eventually_polylog_le_rpow (A k : ℕ) {δ : ℝ} (hδ : 0 < δ) :
+ ∀ᶠ n : ℕ in atTop, ((A * (n.log2+1)^k : ℕ) : ℝ) ≤ (n : ℝ)^δ := by
+ obtain ⟨m, hm⟩ := exists_nat_gt δ⁻¹
+ have hm' : 0 < (m : ℝ) := lt_trans (inv_pos.mpr hδ) hm
+ have hmd : 1 < δ * m := by
+ have := mul_lt_mul_of_pos_left hm hδ
+ rwa [mul_inv_cancel₀ hδ.ne'] at this
+ filter_upwards [eventually_polylog_le (A^m) (k*m), eventually_ge_atTop 1] with n hp hn
+ have h := Real.rpow_le_rpow (by positivity : (0 : ℝ) ≤ ((A * (n.log2 + 1)^k : ℕ) : ℝ)^m)
+ (show ((A * (n.log2+1)^k : ℕ) : ℝ)^m ≤ n from by
+ exact_mod_cast (show (A * (n.log2+1)^k)^m ≤ n from by simpa [mul_pow, ← pow_mul] using hp))
+ (inv_nonneg.mpr hm'.le)
+ have hn' : (1 : ℝ) ≤ n := by exact_mod_cast hn
+ calc
+ ((A * (n.log2+1)^k : ℕ) : ℝ) = (((A * (n.log2+1)^k : ℕ) : ℝ)^m)^((m:ℝ)⁻¹) := by
+ rw [← Real.rpow_natCast, ← Real.rpow_mul (by positivity), mul_inv_cancel₀ hm'.ne', Real.rpow_one]
+ _ ≤ _ := h
+ _ ≤ _ := Real.rpow_le_rpow_of_exponent_le hn' ((inv_le_iff_one_le_mul₀ hm').mpr
+ (by simpa [mul_comm] using hmd.le))
+
+/-- A whole site uses only a fixed log-polynomial overhead per bucket
+entry. Here `L` is the program-prefix length. -/
+private theorem site_length_bound (L B d H t : ℕ) (ht : 1 ≤ t) (hH : 1 ≤ H) (hd : d ≤ B*t) :
+ L + (d+4+width d H ((d+10)^4)) ≤
+ (L+B+4 + 16*(B+10)^4 + 40*(B+10)^4*(B+1)^2) * H * t^6 := by
+ have hl : 1 ≤ H * t^6 := Nat.mul_pos hH (Nat.pow_pos ht)
+ have ht6 : t ≤ H*t^6 :=
+ (Nat.le_self_pow (by decide) _).trans (Nat.le_mul_of_pos_left _ hH)
+ have hs : d+10 ≤ (B+10)*t := by rw [Nat.add_mul]; omega
+ have h1 : d+1 ≤ (B+1)*t := by rw [Nat.add_mul]; omega
+ have hw : (d+10)^4 ≤ (B+10)^4 * t^4 := by simpa [mul_pow] using Nat.pow_le_pow_left hs 4
+ have h4 : t^4 ≤ H*t^6 := (Nat.pow_le_pow_right ht (by decide : 4 ≤ 6)).trans
+ (Nat.le_mul_of_pos_left _ hH)
+ have hch : (d+1).choose 2 ≤ (B+1)^2 * t^2 := by
+ rw [Nat.choose_two_right, ← mul_pow, pow_two]
+ exact (Nat.div_le_self _ _).trans (Nat.mul_le_mul h1 (by omega))
+ have hd' := hd.trans (Nat.mul_le_mul_left B ht6)
+ have hw' := hw.trans (Nat.mul_le_mul_left _ h4)
+ rw [width_eq]
+ calc
+ _ ≤ L*(H*t^6) + (B*(H*t^6)+4*(H*t^6) +
+ (16*((B+10)^4*(H*t^6)) + 40*H*((B+10)^4*t^4)*((B+1)^2*t^2))) := by
+ gcongr
+ · exact Nat.le_mul_of_pos_right _ hl
+ · exact Nat.le_mul_of_pos_right _ hl
+ _ = _ := by ring
+
+/-- Section 10's live processor layout fits all its fields in `n` input
+bits, for any fixed `δ > 0`, prefix, and logarithmic address multiplier. -/
+theorem eventually_processorInputFits (p : UniversalMachine.Program) (B : ℕ) {δ : ℝ} (hδ : 0 < δ) :
+ ∀ᶠ n : ℕ in atTop, ∀ d e : ℕ, d ≤ B * (n.log2+1) →
+ (2:ℝ)^e ≤ 2*(n:ℝ)^(1-δ) → ProcessorInput.Fits p n d (2^e) ((d+10)^4) := by
+ let L := (UniversalMachine.programPrefix p).length
+ let K := L+B+4 + 16*(B+10)^4 + 40*(B+10)^4*(B+1)^2
+ filter_upwards [eventually_polylog_le_rpow (2*K) 6 hδ, eventually_ge_atTop 1] with n hpoly hn
+ intro d e hd hH
+ have hlen := site_length_bound L B d (2^e) (n.log2+1) (by omega) (Nat.two_pow_pos e) hd
+ have hn' : 0 < (n:ℝ) := by exact_mod_cast hn
+ have htotal : ((K * 2^e * (n.log2+1)^6 : ℕ) : ℝ) ≤ n := by
+ push_cast
+ calc
+ _ ≤ (K : ℝ)*(2*n^(1-δ))*(n.log2+1)^6 := by gcongr
+ _ = (((2*K)*(n.log2+1)^6 : ℕ) : ℝ) * (n:ℝ)^(1-δ) := by push_cast; ring
+ _ ≤ n^δ * (n:ℝ)^(1-δ) := mul_le_mul_of_nonneg_right hpoly (by positivity)
+ _ = n := by rw [← Real.rpow_add hn', add_sub_cancel, Real.rpow_one]
+ exact hlen.trans (by exact_mod_cast htotal)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSiteInput.lean b/lean/OAI/Computability/VPVNP/RAMSiteInput.lean
new file mode 100644
index 0000000000..2e5e86c375
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSiteInput.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.RAMBitLocality
+import OAI.Computability.VPVNP.UniversalMachine
+
+/-!
+# Input string of a live or primed site
+
+Section 9.2 uses a literal self-delimiting program prefix, the site's address,
+four header bits, its incident communication bits, and zeros. The full string
+is an input to the coefficient machine. The prescribed header word and address
+are recovered from exactly the fields that appear on its input tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.ProcessorInput
+
+open RAMLayout RAMSerialization
+
+variable {d H w n : ℕ}
+
+/-- Four header bits for a site, in the order group index, advice, incoming cut, and outgoing
+cut. -/
+abbrev Header := Fin 4 → Bool
+
+/-- The four header bits are group index, advice, incoming cut, outgoing cut. -/
+def header (index advice incoming outgoing : Bool) : Header := ![index, advice, incoming, outgoing]
+
+/-- The low four bits of the site's initialized word hold its header. -/
+def headerWord (_hw : 4 ≤ w) (hdr : Header) : Word w :=
+ (wordBits w).symm fun i => if h : i.val < 4 then hdr ⟨i.val, h⟩ else false
+
+theorem headerWord_bit (hw : 4 ≤ w) (hdr : Header) (j : Fin 4) :
+ wordBits w (headerWord hw hdr) (j.castLE hw) = hdr j := by
+ simp [headerWord]
+
+theorem headerWord_padding (hw : 4 ≤ w) (hdr : Header) (j : Fin w) (hj : 4 ≤ j.val) :
+ wordBits w (headerWord hw hdr) j = false := by simp [headerWord, Nat.not_lt.mpr hj]
+
+/-- Address, literal index/advice and cut bits, and incident communication fields. -/
+def payload (v : Fin (2^d)) (hdr : Header) (inc : Fin (width d H w) → Bool) : List Bool :=
+ List.ofFn (wordBits d v) ++ List.ofFn hdr ++ List.ofFn inc
+
+@[simp] theorem length_payload (v : Fin (2^d)) (hdr : Header) (inc : Fin (width d H w) → Bool) :
+ (payload v hdr inc).length = d + 4 + width d H w := by simp only [payload, List.length_append, List.length_ofFn]
+
+/-- The self-delimiting program prefix, site address, four header bits, and all incident
+communication bits fit within the input length. -/
+abbrev Fits (program : UniversalMachine.Program) (n d H w : ℕ) :=
+ (UniversalMachine.programPrefix program).length + (d + 4 + width d H w) ≤ n
+
+/-- Construct the site’s literal input by concatenating the program prefix, address, header,
+and incident bits, then filling the available suffix with zeros. -/
+def tape (program : UniversalMachine.Program) (n : ℕ) (v : Fin (2^d)) (hdr : Header)
+ (inc : Fin (width d H w) → Bool) : List Bool :=
+ let used := (UniversalMachine.programPrefix program).length + (d + 4 + width d H w)
+ UniversalMachine.programPrefix program ++ (payload v hdr inc ++ List.replicate (n-used) false)
+
+theorem length_tape (p : UniversalMachine.Program) (v : Fin (2^d)) (hdr : Header)
+ (inc : Fin (width d H w) → Bool) (hf : Fits p n d H w) :
+ (tape p n v hdr inc).length = n := by
+ simp only [tape, List.length_append, length_payload, List.length_replicate]
+ unfold Fits at hf
+ omega
+
+/-- Index the fitted site input tape by its n positions to obtain a Boolean coefficient input. -/
+def encode (program : UniversalMachine.Program) (n : ℕ) (v : Fin (2^d)) (hdr : Header)
+ (inc : Fin (width d H w) → Bool) (hf : Fits program n d H w) : Fin n → Bool :=
+ fun j => (tape program n v hdr inc)[j.val]'(by rw [length_tape _ _ _ _ hf]; exact j.isLt)
+
+@[simp] theorem ofFn_encode (p : UniversalMachine.Program) (n : ℕ) (v : Fin (2^d)) (hdr : Header)
+ (inc : Fin (width d H w) → Bool) (hf : Fits p n d H w) :
+ List.ofFn (encode p n v hdr inc hf) = tape p n v hdr inc := by
+ apply List.ext_getElem
+ · rw [List.length_ofFn, length_tape _ _ _ _ hf]
+ · intro i _ _
+ simp [encode]
+
+/-- The first field really is the self-delimiting prefix accepted by the
+universal coefficient machine, independently of all other sites' choices. -/
+theorem decode (p : UniversalMachine.Program) (n : ℕ) (v : Fin (2^d)) (hdr : Header)
+ (inc : Fin (width d H w) → Bool) (hf : Fits p n d H w) :
+ UniversalMachine.decode (List.ofFn (encode p n v hdr inc hf)) = some p := by
+ rw [ofFn_encode, tape, UniversalMachine.decode_programPrefix]
+
+theorem coefficient (p : UniversalMachine.Program) (n : ℕ) (v : Fin (2^d)) (hdr : Header)
+ (inc : Fin (width d H w) → Bool) (hf : Fits p n d H w) :
+ acceptingCount (encode p n v hdr inc hf) =
+ UniversalMachine.paths p (n^clockExponent) (UniversalMachine.initial p (tape p n v hdr inc)) := by
+ dsimp only [acceptingCount]
+ rw [decode, ofFn_encode]
+
+/-- The exact suffix after the literal prefix, including zero padding. -/
+theorem drop_prefix (p : UniversalMachine.Program) (n : ℕ) (v : Fin (2^d)) (hdr : Header)
+ (inc : Fin (width d H w) → Bool) :
+ (tape p n v hdr inc).drop (UniversalMachine.programPrefix p).length =
+ payload v hdr inc ++ List.replicate (n - ((UniversalMachine.programPrefix p).length +
+ (d + 4 + width d H w))) false := by simp [tape]
+
+/-- Every designated address, header, and communication bit can be read
+directly at its own offset. -/
+theorem payload_address (v : Fin (2^d)) (hdr : Header) (inc : Fin (width d H w) → Bool)
+ (i : Fin d) : (payload v hdr inc)[i.val]? = some (wordBits d v i) := by
+ simp only [payload, List.append_assoc]
+ rw [List.getElem?_append_left (by simpa only [List.length_ofFn] using i.isLt)]
+ rw [List.getElem?_eq_getElem (by simpa only [List.length_ofFn] using i.isLt)]
+ simp only [List.getElem_ofFn]
+
+theorem payload_header (v : Fin (2^d)) (hdr : Header) (inc : Fin (width d H w) → Bool)
+ (i : Fin 4) : (payload v hdr inc)[d+i.val]? = some (hdr i) := by
+ simp only [payload, List.append_assoc]
+ rw [List.getElem?_append_right (by simp), List.length_ofFn, Nat.add_sub_cancel_left]
+ rw [List.getElem?_append_left (by simpa only [List.length_ofFn] using i.isLt)]
+ rw [List.getElem?_eq_getElem (by simpa only [List.length_ofFn] using i.isLt)]
+ simp only [List.getElem_ofFn]
+
+theorem payload_incident (v : Fin (2^d)) (hdr : Header) (inc : Fin (width d H w) → Bool)
+ (i : Fin (width d H w)) : (payload v hdr inc)[d+4+i.val]? = some (inc i) := by
+ simp only [payload, List.append_assoc]
+ rw [List.getElem?_append_right (by simp only [List.length_ofFn]; omega), List.length_ofFn,
+ show d+4+i.val-d = 4+i.val by omega]
+ rw [List.getElem?_append_right (by simp only [List.length_ofFn]; omega), List.length_ofFn,
+ Nat.add_sub_cancel_left, List.getElem?_eq_getElem (by simpa only [List.length_ofFn] using i.isLt)]
+ simp only [List.getElem_ofFn]
+
+end BurstRAM.ProcessorInput
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSiteLoop.lean b/lean/OAI/Computability/VPVNP/RAMSiteLoop.lean
new file mode 100644
index 0000000000..6f66c436ec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSiteLoop.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.RAMLocalRun
+import OAI.Computability.VPVNP.RAMSuccessor
+
+/-!
+# Streaming the private choices of a site
+
+The site starts calls until its incoming state halts or the cumulative charge
+reaches the next bucket. A call may cross that boundary, subject to the three
+remaining charge limits. Each call leaves a suffix for its successor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- Continue from the unused suffix and keep the current call's report. -/
+def collectCall (call : Option (Report w × List Bool))
+ (next : Report w → List Bool → Option (List (Report w) × List Bool)) :
+ Option (List (Report w) × List Bool) :=
+ call.bind fun (r, bs) => (next r bs).map fun (rs, tail) => (r :: rs, tail)
+
+private theorem collectCall_ne_nil (call : Option (Report w × List Bool))
+ (next : Report w → List Bool → Option (List (Report w) × List Bool)) (tail : List Bool) :
+ collectCall call next ≠ some ([], tail) := by
+ simp [collectCall, Option.bind_eq_some_iff]
+
+private theorem collectCall_cons (call : Option (Report w × List Bool))
+ (next : Report w → List Bool → Option (List (Report w) × List Bool))
+ (r : Report w) (rs : List (Report w)) (tail : List Bool) :
+ collectCall call next = some (r :: rs, tail) ↔
+ ∃ bs, call = some (r, bs) ∧ next r bs = some (rs, tail) := by
+ simp only [collectCall, Option.bind_eq_some_iff, Option.map_eq_some_iff, Prod.exists,
+ Prod.mk.injEq, List.cons.injEq]
+ constructor
+ · rintro ⟨_, bs, hc, _, _, hn, ⟨rfl, rfl⟩, rfl⟩
+ exact ⟨bs, hc, hn⟩
+ · rintro ⟨bs, hc, hn⟩
+ exact ⟨r, bs, hc, rs, tail, hn, ⟨rfl, rfl⟩, rfl⟩
+
+/-- Execute consecutive charged calls in a bucket. `steps` bounds the number
+of calls and `siteLeft` bounds their total startup and probe charges. -/
+def runSiteLoop (P : Program w C) (fuel H boundary globalCap steps : ℕ) (c : Cut w)
+ (siteLeft : ℕ) (bits : List Bool) : Option (List (Report w) × List Bool) :=
+ if c.cost ≤ globalCap then
+ match c.state with
+ | none => some ([], bits)
+ | some s =>
+ if c.cost < boundary then
+ match steps with
+ | 0 => none
+ | n + 1 =>
+ collectCall (runChargedCall P fuel (P.start s) H (globalCap - c.cost) siteLeft bits).output
+ (fun r bs => runSiteLoop P fuel H boundary globalCap n (c.advance [r])
+ (siteLeft - (1 + r.probes)) bs)
+ else some ([], bits)
+ else none
+termination_by structural steps
+
+/-- The loop uses precisely the binary guesses of the successful reports. It
+may return a running state only at or past the next bucket boundary. -/
+theorem runSiteLoop_iff {P : Program w C} {fuel H boundary globalCap steps : ℕ} {c : Cut w}
+ {siteLeft : ℕ} {bits tail : List Bool} {rs : List (Report w)} :
+ runSiteLoop P fuel H boundary globalCap steps c siteLeft bits = some (rs, tail) ↔
+ LocalSegment P fuel c.state rs ∧ RAMBuckets.StartsBefore Report.probes boundary c.cost rs ∧
+ (∀ r ∈ rs, 1 + r.probes ≤ H) ∧ (c.advance rs).cost ≤ globalCap ∧
+ RAMBuckets.cost Report.probes rs ≤ siteLeft ∧ rs.length ≤ steps ∧
+ ((c.advance rs).state.isSome → boundary ≤ (c.advance rs).cost) ∧
+ bits = rs.flatMap (fun r => guessBits r.events) ++ tail := by
+ induction rs generalizing steps c siteLeft bits with
+ | nil =>
+ rw [runSiteLoop]
+ simp only [Cut.advance_nil, LocalSegment, RAMBuckets.StartsBefore, RAMBuckets.cost,
+ List.length_nil, List.flatMap_nil, List.nil_append, Nat.zero_le, List.not_mem_nil,
+ IsEmpty.forall_iff, implies_true, true_and]
+ by_cases hc : c.cost ≤ globalCap
+ · cases c.state with
+ | none => simp [hc]
+ | some s =>
+ by_cases hb : c.cost < boundary
+ · cases steps <;> simp [hc, hb, collectCall_ne_nil, Nat.not_le.mpr hb]
+ · simp [hc, hb, Nat.le_of_not_gt hb]
+ · simp [hc]
+ | cons r rs ih =>
+ rw [runSiteLoop]
+ by_cases hc : c.cost ≤ globalCap
+ · cases c.state with
+ | none => simp [hc, LocalSegment]
+ | some s =>
+ by_cases hb : c.cost < boundary
+ · cases steps with
+ | zero => simp [hc, hb]
+ | succ n =>
+ simp only [hc, hb, ↓reduceIte, collectCall_cons, runChargedCall_iff, ih,
+ LocalSegment, RAMBuckets.StartsBefore, List.forall_mem_cons, List.length_cons,
+ Nat.succ_le_succ_iff, List.flatMap_cons, List.append_assoc]
+ simp only [Cut.advance, RAMBuckets.cost, Nat.add_zero, endState, Nat.add_assoc]
+ constructor
+ · rintro ⟨bs, ⟨hcall, hH, _, hsite, he⟩, hseg, hbefore, hcalls, hcap,
+ hleft, hlen, hcross, hbs⟩
+ exact ⟨⟨hcall, hseg⟩, ⟨trivial, hbefore⟩, ⟨hH, hcalls⟩, hcap,
+ by omega, hlen, hcross, he.trans (congrArg (guessBits r.events ++ ·) hbs)⟩
+ · rintro ⟨⟨hcall, hseg⟩, ⟨_, hbefore⟩, ⟨hH, hcalls⟩, hcap, hsite, hlen, hcross, he⟩
+ exact ⟨_, ⟨hcall, hH, by omega, by omega, he⟩, hseg, hbefore, hcalls,
+ hcap, by omega, hlen, hcross, rfl⟩
+ · simp [hc, hb, RAMBuckets.StartsBefore]
+ · have hn : ¬ (c.advance (r :: rs)).cost ≤ globalCap := by
+ change ¬ c.cost + _ ≤ _
+ omega
+ simp [hc, hn]
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSiteRun.lean b/lean/OAI/Computability/VPVNP/RAMSiteRun.lean
new file mode 100644
index 0000000000..aae6430fb5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSiteRun.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.RAMSiteLoop
+import OAI.Computability.VPVNP.RAMFinite
+
+/-!
+# Binary paths of a site validator
+
+The public bucket size bounds the number of calls independently of incoming
+messages. The validator checks the input range before simulating the calls.
+Its outgoing check compares an internal send with the actual result, or
+requires acceptance on the terminal site. It consumes exactly the local binary
+choices and fixed-width read guesses used by those calls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- Simulate the private calls assigned to this site, leaving the unused bits. -/
+def runSite (P : Program w C) (fuel S H v : ℕ) (c : Cut w) (bits : List Bool) :
+ Option (List (Report w) × List Bool) :=
+ if c.state.isSome → v * H ≤ c.cost ∧ c.cost < (v + 1) * H then
+ runSiteLoop P fuel H ((v + 1) * H) (S * H) (2 * H - 1) c (2 * H - 1) bits
+ else none
+
+theorem runSite_iff {P : Program w C} {fuel S H v} {c : Cut w} {bits rs tail}
+ (hH : 0 < H) : runSite P fuel S H v c bits = some (rs, tail) ↔
+ SiteRun P fuel S H v c rs ∧ bits = rs.flatMap (fun r => guessBits r.events) ++ tail := by
+ unfold runSite
+ split
+ · rename_i hin
+ rw [runSiteLoop_iff]
+ constructor
+ · rintro ⟨hc, hb, hcall, hcap, _, _, hx, he⟩
+ exact ⟨⟨hin, hb, hc, hcall, hcap, hx⟩, he⟩
+ · rintro ⟨hr, he⟩
+ have hcost := hr.cost_lt hH
+ have hlen := RAMBuckets.cost_eq_length_add_probes Report.probes rs
+ exact ⟨hr.calls, hr.before, hr.call_cap, hr.total_cap, by omega, by omega, hr.crossing, he⟩
+ · rename_i hn
+ exact ⟨nofun, fun h => (hn h.1.incoming).elim⟩
+
+/-- Exact-use site validator with the successor or terminal check. Later local
+record and sorting checks can be applied to the returned reports. -/
+def validateSite (P : Program w C) (fuel S H v : ℕ) (input : Cut w)
+ (output : Option (Cut w)) (bits : List Bool) : Option (List (Report w)) :=
+ (runSite P fuel S H v input bits).bind fun (rs, tail) =>
+ if tail = [] then
+ match output with
+ | some d => if d = input.advance rs then some rs else none
+ | none => if (input.advance rs).state = none then some rs else none
+ else none
+
+theorem validateSite_iff {P : Program w C} {fuel S H v} {input : Cut w} {output bits rs}
+ (hH : 0 < H) : validateSite P fuel S H v input output bits = some rs ↔
+ SiteCheck P fuel S H v input output rs ∧ bits = rs.flatMap (fun r => guessBits r.events) := by
+ rw [validateSite, Option.bind_eq_some_iff]
+ constructor
+ · rintro ⟨⟨ts, tail⟩, hrun, htest⟩
+ dsimp only at htest
+ split at htest
+ · rename_i ht
+ subst tail
+ obtain ⟨hr, hb⟩ := (runSite_iff hH).mp hrun
+ cases output <;> dsimp only at htest <;> split at htest <;> simp_all [SiteCheck]
+ · contradiction
+ · rintro ⟨⟨hsite, hend⟩, rfl⟩
+ refine ⟨(rs, []), (runSite_iff hH).mpr ⟨hsite, by simp⟩, ?_⟩
+ cases output <;> simp_all
+
+/-- Any further deterministic check of the local reports preserves the exact
+correspondence between valid reports and accepting binary inputs. -/
+noncomputable def siteBitsEquiv {P : Program w C} {fuel S H v} {input : Cut w} {output}
+ (hH : 0 < H) (check : List (Report w) → Prop) :
+ {bs : List Bool // ∃ rs, validateSite P fuel S H v input output bs = some rs ∧ check rs} ≃
+ {rs : List (Report w) // SiteCheck P fuel S H v input output rs ∧ check rs} := by
+ let encode (r : {rs : List (Report w) // SiteCheck P fuel S H v input output rs ∧ check rs}) :
+ {bs : List Bool // ∃ rs, validateSite P fuel S H v input output bs = some rs ∧ check rs} :=
+ ⟨r.val.flatMap (fun t => guessBits t.events), r.val,
+ (validateSite_iff hH).mpr ⟨r.property.1, rfl⟩, r.property.2⟩
+ refine (Equiv.ofBijective encode ⟨?_, ?_⟩).symm
+ · intro r t he
+ have hr := (validateSite_iff hH).mpr (show SiteCheck P fuel S H v input output r.val ∧
+ (encode r).val = _ from ⟨r.property.1, rfl⟩)
+ have ht := (validateSite_iff hH).mpr (show SiteCheck P fuel S H v input output t.val ∧
+ (encode t).val = _ from ⟨t.property.1, rfl⟩)
+ rw [he] at hr
+ exact Subtype.ext (Option.some.inj (hr.symm.trans ht))
+ · intro bs
+ obtain ⟨rs, hrun, hc⟩ := bs.property
+ obtain ⟨hr, he⟩ := (validateSite_iff hH).mp hrun
+ exact ⟨⟨rs, hr, hc⟩, Subtype.ext he.symm⟩
+
+/-- The local path count is unchanged by restricting the ambient space of
+reports to the finite domain used for the product of validator counts. -/
+noncomputable def boundedSiteBitsEquiv {P : Program w C} {fuel S H v} {input : Cut w} {output}
+ (hH : 0 < H) (check : List (Report w) → Prop) :
+ {bs : List Bool // ∃ rs, validateSite P fuel S H v input output bs = some rs ∧ check rs} ≃
+ {r : BoundedReports w fuel (2 * H) // SiteCheck P fuel S H v input output r.val ∧ check r.val} := by
+ refine (siteBitsEquiv hH check).trans ?_
+ refine ⟨fun r => ⟨⟨r.val, ?_⟩, r.property⟩, fun r => ⟨r.val.val, r.property⟩,
+ fun _ => rfl, fun _ => rfl⟩
+ exact boundedReports_of_localSegment r.property.1.1.calls (r.property.1.1.cost_lt hH).le
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSiteWork.lean b/lean/OAI/Computability/VPVNP/RAMSiteWork.lean
new file mode 100644
index 0000000000..ef1caeb07c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSiteWork.lean
@@ -0,0 +1,271 @@
+import OAI.Computability.VPVNP.RAMLocalWork
+import OAI.Computability.VPVNP.RAMSiteRun
+
+/-!
+# Work of the bucket's private call loop
+
+The metered loop follows the same calls as `runSiteLoop`. It reserves a fixed
+control charge on each visit, including the final check, and counts dispatches,
+charged probes and reserved guess slots for each attempted call. On success it
+uses the accumulated probe count to advance the cut in constant time.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- Result and word-work charge for one site’s private call loop, including paths that stop
+with a failed check. -/
+structure MeteredSiteRun (w : ℕ) where
+ /-- On success, the site’s call reports in order and the suffix of the private bit stream
+ left for later processing. -/
+ output : Option (List (Report w) × List Bool)
+ /-- Total charge for loop control, instruction dispatch, external probes, and private guesses
+ on the simulated path. -/
+ work : ℕ
+
+/-- Meter the call loop on every input. The charge `controlCharge` covers a
+fixed set of loop checks and counter updates per visit. The call charge covers
+the instruction dispatch, one slot per charged probe, and the individual
+binary guesses. -/
+def meteredSiteLoop (P : Program w C) (controlCharge fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) : MeteredSiteRun w :=
+ if c.cost ≤ globalCap then
+ match c.state with
+ | none => ⟨some ([], bits), controlCharge⟩
+ | some s =>
+ if c.cost < boundary then
+ match steps with
+ | 0 => ⟨none, controlCharge⟩
+ | n + 1 =>
+ let t := runChargedCall P fuel (P.start s) H (globalCap - c.cost) siteLeft bits
+ let work := controlCharge + (t.instructions + t.probes + t.guessWork)
+ match t.output with
+ | none => ⟨none, work⟩
+ | some (r, bs) =>
+ let charge := 1 + t.probes
+ let rest := meteredSiteLoop P controlCharge fuel H boundary globalCap n
+ ⟨c.cost + charge, r.result⟩ (siteLeft - charge) bs
+ ⟨rest.output.map (fun (rs, tail) => (r :: rs, tail)), work + rest.work⟩
+ else ⟨some ([], bits), controlCharge⟩
+ else ⟨none, controlCharge⟩
+termination_by structural steps
+
+/-- The counters, including the constant-time cost update, preserve the exact
+result of the private choice stream. -/
+theorem meteredSiteLoop_output_eq (P : Program w C) (controlCharge fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) :
+ (meteredSiteLoop P controlCharge fuel H boundary globalCap steps c siteLeft bits).output =
+ runSiteLoop P fuel H boundary globalCap steps c siteLeft bits := by
+ induction steps generalizing c siteLeft bits with
+ | zero =>
+ rw [meteredSiteLoop, runSiteLoop]
+ by_cases hc : c.cost ≤ globalCap
+ · cases c.state <;> simp [hc]
+ split <;> rfl
+ · simp [hc]
+ | succ n ih =>
+ rw [meteredSiteLoop, runSiteLoop]
+ by_cases hc : c.cost ≤ globalCap
+ · cases hs : c.state with
+ | none => simp [hc]
+ | some s =>
+ by_cases hb : c.cost < boundary
+ · simp only [hc, hb, ↓reduceIte]
+ let t := runChargedCall P fuel (P.start s) H (globalCap - c.cost) siteLeft bits
+ change _ = t.output.bind (fun (r, bs) =>
+ (runSiteLoop P fuel H boundary globalCap n (c.advance [r])
+ (siteLeft - (1 + r.probes)) bs).map (fun (rs, tail) => (r :: rs, tail)))
+ cases ht : t.output with
+ | none => rfl
+ | some z =>
+ obtain ⟨r, bs⟩ := z
+ have hp : t.probes = r.probes := runChargedCall_probes_eq ht
+ dsimp only [t] at hp
+ simp only [hp, Option.bind_some, ih, Cut.advance, RAMBuckets.cost, endState, Nat.add_zero]
+ · simp [hc, hb]
+ · simp [hc]
+
+/-- Arbitrary incoming cuts and private bit streams satisfy the same bound,
+including paths that reject after partially simulating a call. -/
+theorem siteWork_le (P : Program w C) (controlCharge fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) :
+ (meteredSiteLoop P controlCharge fuel H boundary globalCap steps c siteLeft bits).work ≤
+ (steps + 1) * (controlCharge + 3 * fuel + w * H) := by
+ let perVisit := controlCharge + 3 * fuel + w * H
+ have hcontrol : controlCharge ≤ perVisit := by dsimp [perVisit]; omega
+ have hbase (n : ℕ) : controlCharge ≤ (n + 1) * perVisit := by
+ rw [Nat.add_mul, Nat.one_mul]
+ omega
+ induction steps generalizing c siteLeft bits with
+ | zero =>
+ rw [meteredSiteLoop]
+ by_cases hc : c.cost ≤ globalCap
+ · cases c.state <;> simp only [hc, ↓reduceIte]
+ · exact hbase 0
+ · split <;> exact hbase 0
+ · simp only [hc, ↓reduceIte]
+ exact hbase 0
+ | succ n ih =>
+ rw [meteredSiteLoop]
+ by_cases hc : c.cost ≤ globalCap
+ · cases hs : c.state with
+ | none => simpa only [hc, ↓reduceIte] using hbase (n + 1)
+ | some s =>
+ by_cases hb : c.cost < boundary
+ · simp only [hc, hb, ↓reduceIte]
+ let t := runChargedCall P fuel (P.start s) H (globalCap - c.cost) siteLeft bits
+ have hprobe : min H (min (globalCap - c.cost) siteLeft) - 1 ≤ H :=
+ (Nat.sub_le _ _).trans (min_le_left _ _)
+ have hcall := runChargedCall_totalWork_le P fuel (P.start s) H (globalCap - c.cost) siteLeft bits
+ have hwork : controlCharge + (t.instructions + t.probes + t.guessWork) ≤ perVisit := by
+ have := Nat.mul_le_mul_left w hprobe
+ dsimp only [t, perVisit]
+ dsimp only at hcall
+ omega
+ cases ht : (runChargedCall P fuel (P.start s) H (globalCap - c.cost) siteLeft bits).output with
+ | none =>
+ change controlCharge + _ ≤ (n + 1 + 1) * perVisit
+ rw [Nat.add_mul, Nat.one_mul]
+ exact hwork.trans (by omega)
+ | some z =>
+ obtain ⟨r, bs⟩ := z
+ have htail := ih ⟨c.cost + (1 + t.probes), r.result⟩ (siteLeft - (1 + t.probes)) bs
+ change controlCharge + _ + _ ≤ (n + 1 + 1) * perVisit
+ rw [Nat.add_mul, Nat.one_mul]
+ exact Nat.add_le_add hwork htail |>.trans_eq (Nat.add_comm _ _)
+ · simpa only [hc, hb, ↓reduceIte] using hbase (n + 1)
+ · simpa only [hc, ↓reduceIte] using hbase (n + 1)
+
+/-- Scan each event once, counting the probes and the operations to advance
+the cursor, inspect the tag and update the count. -/
+private def countProbesWork : List (Event w) → ℕ × ℕ
+ | [] => (0, 1)
+ | e :: es =>
+ let t := countProbesWork es
+ (e.probeCharge + t.1, 4 + t.2)
+
+private theorem countProbesWork_spec (es : List (Event w)) :
+ countProbesWork es = (countProbes es, 4 * es.length + 1) := by
+ induction es with
+ | nil => rfl
+ | cons e es ih =>
+ cases e <;> simp [countProbesWork, ih, countProbes, Event.probeCharge] <;> omega
+
+/-- Compute the outgoing cost and state in one pass over the reports and their
+events. Six further operations per report cover advancing the cursor, reading
+the persistent state, and updating the cost. -/
+def meteredAdvance (c : Cut w) : List (Report w) → Cut w × ℕ
+ | [] => (c, 1)
+ | r :: rs =>
+ let p := countProbesWork r.events
+ let rest := meteredAdvance ⟨c.cost + (1 + p.1), r.result⟩ rs
+ (rest.1, 6 + p.2 + rest.2)
+
+theorem meteredAdvance_result (c : Cut w) (rs : List (Report w)) :
+ (meteredAdvance c rs).1 = c.advance rs := by
+ induction rs generalizing c with
+ | nil => simp [meteredAdvance]
+ | cons r rs ih =>
+ simp [meteredAdvance, countProbesWork_spec, ih, Cut.advance, RAMBuckets.cost,
+ Report.probes, endState, Nat.add_assoc]
+
+theorem meteredAdvance_work_le (c : Cut w) (rs : List (Report w)) (fuel : ℕ)
+ (h : ∀ r ∈ rs, r.events.length < fuel) :
+ (meteredAdvance c rs).2 ≤ 1 + rs.length * (7 + 4 * fuel) := by
+ induction rs generalizing c with
+ | nil => simp [meteredAdvance]
+ | cons r rs ih =>
+ have hr := h r List.mem_cons_self
+ have ht := ih ⟨c.cost + (1 + countProbes r.events), r.result⟩ (fun s hs => h s (List.mem_cons_of_mem _ hs))
+ simp only [meteredAdvance, countProbesWork_spec, List.length_cons, Nat.add_mul, Nat.one_mul]
+ omega
+
+/-- The exact-use validator reserves a fixed control budget for the incoming
+range test and outgoing comparisons. The cut scan starts only after exact
+consumption of the private choices. -/
+def meteredValidateSite (P : Program w C) (fuel S H v : ℕ) (input : Cut w)
+ (output : Option (Cut w)) (bits : List Bool) : Option (List (Report w)) × ℕ :=
+ if input.state.isSome → v * H ≤ input.cost ∧ input.cost < (v + 1) * H then
+ let loop := meteredSiteLoop P 32 fuel H ((v + 1) * H) (S * H)
+ (2 * H - 1) input (2 * H - 1) bits
+ let base := 32 + loop.work
+ match loop.output with
+ | some (rs, []) =>
+ let d := meteredAdvance input rs
+ let accepted := match output with
+ | some o => decide (o = d.1)
+ | none => d.1.state.isNone
+ (if accepted then some rs else none, base + d.2)
+ | _ => (none, base)
+ else (none, 32)
+
+theorem meteredValidateSite_result (P : Program w C) (fuel S H v : ℕ) (input : Cut w)
+ (output : Option (Cut w)) (bits : List Bool) :
+ (meteredValidateSite P fuel S H v input output bits).1 =
+ validateSite P fuel S H v input output bits := by
+ unfold meteredValidateSite validateSite runSite
+ split
+ · dsimp only
+ rw [meteredSiteLoop_output_eq]
+ cases runSiteLoop P fuel H ((v + 1) * H) (S * H) (2 * H - 1) input (2 * H - 1) bits with
+ | none => rfl
+ | some z =>
+ obtain ⟨rs, tail⟩ := z
+ cases tail with
+ | cons b bs => rfl
+ | nil => cases output <;> simp [meteredAdvance_result]
+ · rfl
+
+/-- The work bound for the full private site validator, including incoming
+format tests and the final cut scan, on arbitrary bit streams and cuts. -/
+theorem meteredValidateSite_work_le (P : Program w C) (fuel S H v : ℕ) (input : Cut w)
+ (output : Option (Cut w)) (bits : List Bool) (hH : 0 < H) :
+ (meteredValidateSite P fuel S H v input output bits).2 ≤
+ 33 + 2 * H * (32 + 3 * fuel + w * H) + 2 * H * (7 + 4 * fuel) := by
+ unfold meteredValidateSite
+ split
+ · dsimp only
+ let loop := meteredSiteLoop P 32 fuel H ((v + 1) * H) (S * H)
+ (2 * H - 1) input (2 * H - 1) bits
+ have hloop : loop.work ≤ 2 * H * (32 + 3 * fuel + w * H) := by
+ simpa only [show 2 * H - 1 + 1 = 2 * H by omega, loop] using
+ siteWork_le P 32 fuel H ((v + 1) * H) (S * H) (2 * H - 1) input (2 * H - 1) bits
+ cases hres : loop.output with
+ | none => change 32 + loop.work ≤ _; omega
+ | some z =>
+ obtain ⟨rs, tail⟩ := z
+ cases tail with
+ | cons b bs => change 32 + loop.work ≤ _; omega
+ | nil =>
+ have hrun := (meteredSiteLoop_output_eq P 32 fuel H ((v + 1) * H) (S * H)
+ (2 * H - 1) input (2 * H - 1) bits).symm.trans hres
+ obtain ⟨hseg, _, _, _, _, hlen, _, _⟩ := runSiteLoop_iff.mp hrun
+ have hscan := meteredAdvance_work_le input rs fuel (localSegment_event_bound hseg)
+ have hsize := Nat.mul_le_mul_right (7 + 4 * fuel) (hlen.trans (Nat.sub_le _ _))
+ change 32 + loop.work + (meteredAdvance input rs).2 ≤ _
+ omega
+ · dsimp only; omega
+
+/-- A single product bounding the private validator. For the application's
+fuel `n^u`, the hypothesis on the bucket follows from `H ≤ 2n` and `u ≥ 1`. -/
+theorem meteredValidateSite_work_le_product (P : Program w C) (fuel S H v : ℕ) (input : Cut w)
+ (output : Option (Cut w)) (bits : List Bool) (hH : 0 < H) (hf : H ≤ 2 * fuel) :
+ (meteredValidateSite P fuel S H v input output bits).2 ≤
+ 64 * (H + 1) * (fuel + 1) * (w + 2) := by
+ calc
+ _ ≤ 33 + 2 * H * (32 + 3 * fuel + w * H) + 2 * H * (7 + 4 * fuel) :=
+ meteredValidateSite_work_le P fuel S H v input output bits hH
+ _ ≤ 33 + 2 * H * (32 + 3 * fuel + w * (2 * fuel)) + 2 * H * (7 + 4 * fuel) := by
+ gcongr
+ _ ≤ _ := by ring_nf; omega
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortAddressBounds.lean b/lean/OAI/Computability/VPVNP/RAMSortAddressBounds.lean
new file mode 100644
index 0000000000..73aaa94802
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortAddressBounds.lean
@@ -0,0 +1,173 @@
+import OAI.Computability.VPVNP.RAMSortCostLayout
+
+/-!
+# Intermediate register widths for sort addresses
+
+The addresses in Lemma 10.1 are computed by a bounded number of word operations.
+For that interpretation the intermediate products in the triangular layer number
+also have to fit. We bound the largest register value in each address expression,
+including its inputs, by a fixed polynomial in the array length and the word width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+/-- The largest value appearing at any node in the straight-line evaluation. -/
+def IndexExpr.peak (e : IndexExpr) : ℕ :=
+ match e with
+ | .arg x => x
+ | .add a b | .sub a b | .mul a b | .div a b | .mod a b | .xor a b | .shl a b | .shr a b =>
+ max e.eval (max a.peak b.peak)
+
+theorem IndexExpr.eval_le_peak (e : IndexExpr) : e.eval ≤ e.peak := by
+ cases e <;> simp [IndexExpr.peak, IndexExpr.eval]
+
+/-- Register semantics: the output of each elementary operation is reduced modulo
+`2^bits` as soon as it is written. -/
+def IndexExpr.evalWord (bits : ℕ) : IndexExpr → Fin (2 ^ bits)
+ | .arg x => Fin.ofNat _ x
+ | .add a b => Fin.ofNat _ ((a.evalWord bits).val + (b.evalWord bits).val)
+ | .sub a b => Fin.ofNat _ ((a.evalWord bits).val - (b.evalWord bits).val)
+ | .mul a b => Fin.ofNat _ ((a.evalWord bits).val * (b.evalWord bits).val)
+ | .div a b => Fin.ofNat _ ((a.evalWord bits).val / (b.evalWord bits).val)
+ | .mod a b => Fin.ofNat _ ((a.evalWord bits).val % (b.evalWord bits).val)
+ | .xor a b => Fin.ofNat _ ((a.evalWord bits).val ^^^ (b.evalWord bits).val)
+ | .shl a b => Fin.ofNat _ ((a.evalWord bits).val <<< (b.evalWord bits).val)
+ | .shr a b => Fin.ofNat _ ((a.evalWord bits).val >>> (b.evalWord bits).val)
+
+/-- A word evaluator recovers the exact address if all intermediate registers fit. -/
+theorem IndexExpr.evalWord_eq {bits : ℕ} (e : IndexExpr) (h : e.peak < 2 ^ bits) :
+ (e.evalWord bits).val = e.eval := by
+ induction e <;> simp_all [IndexExpr.peak, IndexExpr.evalWord, IndexExpr.eval, max_lt_iff,
+ Fin.ofNat, Nat.mod_eq_of_lt]
+
+/-- A uniform bound for all register values in the sort address calculations. -/
+def addressEnvelope (h d w : ℕ) : ℕ := 64 * (2 ^ (h+d) + w + 32) ^ 4
+
+/-- Global index, XOR partner and direction test. The shift arguments and the mask
+itself are included, even when the output direction bit is zero. -/
+theorem wireAddress_peak_le {h d w site off a j : ℕ} (hs : site < 2 ^ d) (ho : off < 2 ^ h)
+ (hj : j < a) (ha : a ≤ h + d) :
+ (wireIndex h site off).peak ≤ addressEnvelope h d w ∧
+ (wirePartner h site off j).peak ≤ addressEnvelope h d w ∧
+ (directionBit h site off a).peak ≤ addressEnvelope h d w := by
+ let n := 2 ^ (h+d) + w + 32
+ have hn : 2 ≤ n := (by decide : 2 ≤ 32).trans (Nat.le_add_left ..)
+ have hn4 : n ≤ n ^ 4 := by
+ simpa using (Nat.pow_le_pow_right (by omega : 0 < n) (by decide : 1 ≤ 4))
+ have hhd : h + d < 2 ^ (h+d) := Nat.lt_two_pow_self
+ have h2h : 2 ^ h ≤ 2 ^ (h+d) := Nat.pow_le_pow_right (by decide) (by omega)
+ have h2d : 2 ^ d ≤ 2 ^ (h+d) := Nat.pow_le_pow_right (by decide) (by omega)
+ have h2j : 2 ^ j < 2 ^ (h+d) := Nat.pow_lt_pow_right (by decide) (hj.trans_le ha)
+ have hi : site * 2 ^ h + off < 2 ^ (h+d) := by
+ calc
+ site * 2 ^ h + off < site * 2 ^ h + 2 ^ h := Nat.add_lt_add_left ho _
+ _ = (site + 1) * 2 ^ h := by rw [Nat.add_mul, Nat.one_mul]
+ _ ≤ 2 ^ d * 2 ^ h := Nat.mul_le_mul_right _ hs
+ _ = 2 ^ (h+d) := by rw [Nat.pow_add, Nat.mul_comm]
+ have hx := Nat.xor_lt_two_pow hi h2j
+ have hquot := Nat.div_le_self (site * 2 ^ h + off) (2 ^ a)
+ have hmod := Nat.mod_lt ((site * 2 ^ h + off) / 2 ^ a) (by decide : 0 < 2)
+ have harray : 2 ^ (h+d) ≤ n := by dsimp [n]; omega
+ change _ ≤ 64 * n ^ 4 ∧ _ ≤ 64 * n ^ 4 ∧ _ ≤ 64 * n ^ 4
+ simp only [wireIndex, wirePartner, directionBit, IndexExpr.peak, IndexExpr.eval,
+ Nat.shiftLeft_eq, Nat.one_mul, Nat.shiftRight_eq_div_pow, max_le_iff]
+ exact ⟨by repeat' constructor <;> omega, by repeat' constructor <;> omega,
+ by repeat' constructor <;> omega⟩
+
+/-- Computing the physical address of an individual bit adds its in-record offset
+only after computing the start address. -/
+def fieldAddress (h w a j dir off bit : ℕ) : IndexExpr :=
+ .add (fieldStart h w a j dir off) (.arg bit)
+
+/-- The maximum register value includes the product before division by two in the
+triangular ordinal and the product of the field number and the field width. -/
+theorem fieldAddress_peak_le {h d w a j dir off bit : ℕ} (ha : a ≤ h + d) (hj : j < a)
+ (hd : dir < 2) (ho : off < 2 ^ h) (hb : bit < 5 * w) :
+ (fieldAddress h w a j dir off bit).peak ≤ addressEnvelope h d w := by
+ let n := 2 ^ (h+d) + w + 32
+ let p := a - h - 1
+ let step := a - j - 1
+ let ord := p * (p+1) / 2 + step
+ let width := 2 ^ h * 5 * w
+ have hn : 32 ≤ n := Nat.le_add_left ..
+ have hn2 : n ≤ n ^ 2 := by
+ simpa using (Nat.pow_le_pow_right (by omega : 0 < n) (by decide : 1 ≤ 2))
+ have hn4 : n ^ 2 ≤ n ^ 4 := Nat.pow_le_pow_right (by omega) (by decide)
+ have hhd : h+d < 2 ^ (h+d) := Nat.lt_two_pow_self
+ have harray : 2 ^ (h+d) ≤ n := by dsimp [n]; omega
+ have hword : w ≤ n := by dsimp [n]; omega
+ have hwidth : 2 ^ h ≤ n := (Nat.pow_le_pow_right (by decide) (by omega : h ≤ h+d)).trans harray
+ have hp : p + 1 ≤ n := by dsimp [p]; omega
+ have hstep : step ≤ n := by dsimp [step]; omega
+ have hprod : p * (p + 1) ≤ n ^ 2 := by
+ rw [pow_two]; exact Nat.mul_le_mul (by omega) hp
+ have hdiv := Nat.div_le_self (p * (p + 1)) 2
+ have hord : ord ≤ 2 * n ^ 2 := by dsimp [ord]; omega
+ have hfield : ord * 2 + dir ≤ 5 * n ^ 2 := by omega
+ have hblock (k : ℕ) (hk : k ≤ n) : k * 5 * w ≤ 5 * n ^ 2 := by
+ rw [pow_two, Nat.mul_comm k 5, Nat.mul_assoc]
+ exact Nat.mul_le_mul_left 5 (Nat.mul_le_mul hk hword)
+ have hspan : width ≤ 5 * n ^ 2 := hblock _ hwidth
+ have hoff := hblock _ (ho.le.trans hwidth)
+ have haddr : (ord * 2 + dir) * width ≤ 25 * n ^ 4 := by
+ calc
+ _ ≤ (5 * n ^ 2) * (5 * n ^ 2) := Nat.mul_le_mul hfield hspan
+ _ = _ := by ring
+ change _ ≤ 64 * n ^ 4
+ simp only [fieldAddress, fieldStart, IndexExpr.peak, IndexExpr.eval, max_le_iff, Nat.shiftLeft_eq,
+ Nat.one_mul]
+ dsimp only [p, step, ord, width] at hp hstep hprod hdiv hord hfield hspan haddr
+ repeat' constructor <;> omega
+
+theorem fieldStart_peak_le {h d w a j dir off : ℕ} (ha : a ≤ h+d) (hj : j < a)
+ (hd : dir < 2) (ho : off < 2 ^ h) (hw : 0 < w) :
+ (fieldStart h w a j dir off).peak ≤ addressEnvelope h d w := by
+ have hb := fieldAddress_peak_le ha hj hd ho (by omega : 0 < 5 * w)
+ simp only [fieldAddress, IndexExpr.peak, max_le_iff] at hb
+ exact hb.2.1
+
+/-- For Section 9's choice `w = (r+10)^4`, all the sorting registers fit as soon
+as the logarithm of the array length is at most `(r+10)^2`. In particular, for
+`h+d ≤ C*r` this holds for every `r ≥ C`. -/
+theorem addressEnvelope_lt_paperWord {h d r : ℕ} (hd : h+d ≤ (r+10)^2) :
+ addressEnvelope h d ((r+10)^4) < 2 ^ ((r+10)^4) := by
+ let t := r + 10
+ have ht : 10 ≤ t := Nat.le_add_left ..
+ have ht2 : 10 * t ≤ t ^ 2 := by simpa [pow_two] using Nat.mul_le_mul_right t ht
+ have ht4 : 10 * t ^ 2 ≤ t ^ 4 := by
+ calc
+ _ ≤ t ^ 2 * t ^ 2 := Nat.mul_le_mul_right _ (by omega)
+ _ = t ^ 4 := by ring
+ have hw : t ^ 4 ≤ 2 ^ (t ^ 2) := by
+ calc
+ t ^ 4 ≤ (2 ^ t) ^ 4 := Nat.pow_le_pow_left Nat.lt_two_pow_self.le _
+ _ = 2 ^ (t * 4) := (pow_mul ..).symm
+ _ ≤ 2 ^ (t ^ 2) := Nat.pow_le_pow_right (by decide) (by omega)
+ have h32 : 32 ≤ 2 ^ (t ^ 2) :=
+ Nat.pow_le_pow_right (by decide : 0 < 2) (by omega : 5 ≤ t ^ 2)
+ have harr : 2 ^ (h+d) ≤ 2 ^ (t ^ 2) := Nat.pow_le_pow_right (by decide) hd
+ have hscale : 2 ^ (h+d) + t ^ 4 + 32 ≤ 2 ^ (t ^ 2 + 2) := by
+ rw [Nat.pow_add 2 (t ^ 2) 2, show 2 ^ 2 = 4 by decide]
+ omega
+ calc
+ addressEnvelope h d (t ^ 4) ≤ 64 * (2 ^ (t ^ 2 + 2)) ^ 4 :=
+ Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hscale _)
+ _ = 2 ^ (6 + (t ^ 2 + 2) * 4) := by rw [pow_add 2 6, pow_mul]; rfl
+ _ < 2 ^ (t ^ 4) := Nat.pow_lt_pow_right (by decide) (by omega)
+
+/-- The explicit eventual threshold for a linear phase bound `C*r`. -/
+theorem addressEnvelope_lt_paperWord_of_linear {h d C r : ℕ} (hC : C ≤ r) (hd : h+d ≤ C*r) :
+ addressEnvelope h d ((r+10)^4) < 2 ^ ((r+10)^4) :=
+ addressEnvelope_lt_paperWord (hd.trans (by
+ rw [pow_two]
+ exact Nat.mul_le_mul (by omega) (by omega)))
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortBlockSlices.lean b/lean/OAI/Computability/VPVNP/RAMSortBlockSlices.lean
new file mode 100644
index 0000000000..b58fafff6f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortBlockSlices.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.RAMSerialization
+
+/-!
+# Consecutive record intervals in a sorting exchange
+
+Each site sends a block of `4H` five-word records. A validator can parse and
+check its incident sorting field one record at a time, by reading the bit
+interval beginning at offset `i * 5 * w`. This gives the same records and
+canonicality check as the serialized block format.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSerialization
+
+/-- The physical interval occupied by the five words of the `i`th record. -/
+def recordSlice (H w : ℕ) (bits : Fin (RAMLayout.blockBits H w) → Bool) (i : Fin (4 * H))
+ (j : Fin (5 * w)) : Bool :=
+ bits ⟨i.val * 5 * w + j.val, by
+ calc
+ i.val * 5 * w + j.val < (i.val + 1) * (5 * w) := by
+ rw [Nat.add_mul, Nat.one_mul, Nat.mul_assoc]
+ exact Nat.add_lt_add_left j.isLt _
+ _ ≤ (4 * H) * (5 * w) := Nat.mul_le_mul_right _ i.isLt
+ _ = RAMLayout.blockBits H w := (Nat.mul_assoc ..).symm⟩
+
+theorem recordSlice_at (H w : ℕ) (bits : Fin (RAMLayout.blockBits H w) → Bool) (i : Fin (4 * H))
+ (j : Fin 5) (t : Fin w) :
+ recordSlice H w bits i (finProdFinEquiv (j, t)) =
+ bits (finProdFinEquiv (finProdFinEquiv (i, j), t)) := by
+ apply congrArg bits
+ apply Fin.ext
+ change i.val * 5 * w + (t.val + w * j.val) = t.val + w * (j.val + 5 * i.val)
+ ring
+
+/-- Parsing the physical slice reads the corresponding entry of the full
+block parser on every input, including malformed encodings. -/
+theorem blockParse_slice (H : ℕ) {w : ℕ} (hw : 2 ≤ w)
+ (bits : Fin (RAMLayout.blockBits H w) → Bool) (i : Fin (4 * H)) :
+ (recordFormat hw).parse ((arrayBits 5 w).symm (recordSlice H w bits i)) =
+ (blockFormat H hw).parse ((arrayBits (4 * H * 5) w).symm bits) i := by
+ unfold RAMLayout.blockBits at bits
+ simp only [blockFormat, Format.replicate]
+ apply congrArg (recordFormat hw).parse
+ funext j
+ apply (wordBits w).injective
+ funext t
+ rw [← arrayBits_at, Equiv.apply_symm_apply, recordSlice_at H w bits i j t, ← arrayBits_at,
+ Equiv.apply_symm_apply]
+
+/-- Slicing an encoded block gives the encoding of its corresponding slot. -/
+theorem blockEncode_slice (H : ℕ) {w : ℕ} (hw : 2 ≤ w)
+ (records : Fin (4 * H) → Option (WordRecord w)) (i : Fin (4 * H)) :
+ recordSlice H w ((blockFormat H hw).encode records) i = (recordFormat hw).encode (records i) := by
+ funext u
+ obtain ⟨⟨j, t⟩, rfl⟩ := finProdFinEquiv.surjective u
+ refine (recordSlice_at H w ((blockFormat H hw).encode records) i j t).trans ?_
+ simp only [Format.encode, arrayBits_at, blockFormat, Format.replicate, Equiv.symm_apply_apply]
+
+/-- A block passes its re-encoding test precisely when every physical slice
+is the canonical encoding of a record or an empty slot. -/
+theorem blockCanonical_iff (H : ℕ) {w : ℕ} (hw : 2 ≤ w)
+ (bits : Fin (RAMLayout.blockBits H w) → Bool) :
+ bits = (blockFormat H hw).encode ((blockFormat H hw).parse ((arrayBits _ w).symm bits)) ↔
+ ∀ i, ∃ r, recordSlice H w bits i = (recordFormat hw).encode r := by
+ let records := (blockFormat H hw).parse ((arrayBits (4 * H * 5) w).symm bits)
+ constructor
+ · intro he i
+ refine ⟨records i, ?_⟩
+ exact (congrArg (fun b ↦ recordSlice H w b i) he).trans (blockEncode_slice H hw records i)
+ · intro hs
+ have sameSlice (i : Fin (4 * H)) :
+ recordSlice H w bits i = recordSlice H w ((blockFormat H hw).encode records) i := by
+ rw [blockEncode_slice, show records i = _ from (blockParse_slice H hw bits i).symm]
+ obtain ⟨r, hr⟩ := hs i
+ rw [hr]
+ simp [Format.encode, Format.parse_words]
+ funext u
+ obtain ⟨⟨p, t⟩, rfl⟩ := finProdFinEquiv.surjective u
+ obtain ⟨⟨i, j⟩, rfl⟩ := finProdFinEquiv.surjective p
+ exact (recordSlice_at H w bits i j t).symm.trans <|
+ (congrFun (sameSlice i) (finProdFinEquiv (j, t))).trans (recordSlice_at H w _ i j t)
+
+end RAMSerialization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortCompareCost.lean b/lean/OAI/Computability/VPVNP/RAMSortCompareCost.lean
new file mode 100644
index 0000000000..8c0f32a079
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortCompareCost.lean
@@ -0,0 +1,321 @@
+import OAI.Computability.VPVNP.RAMRecordOrder
+import OAI.Computability.VPVNP.RAMSerialization
+import Mathlib.Tactic.FinCases
+
+/-!
+# Word program for one sorting comparison
+
+The fixed five-word format is ordered first by address, then by the
+initialization flag, start cost and probe ordinal. Ties are broken by kind
+and value. Empty records follow every occupied record. The comparator below
+uses only fixed-offset reads, word constants, comparisons and conditional
+selection. Each expression node costs one elementary operation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+open BurstRAM RAMMemory RAMSerialization
+
+namespace WordCompare
+
+/-- Word expressions. A conditional selection is evaluated after its three
+operands, so the operation count is independent of the input. -/
+inductive Expr where
+ | field (right : Bool) (index : Fin 5)
+ | const (n : Fin 4)
+ | eq (a b : Expr)
+ | lt (a b : Expr)
+ | le (a b : Expr)
+ | select (test yes no : Expr)
+
+/-- Two five-word comparison operands indexed by side and by field within each record. -/
+abbrev Input := Bool → Fin 5 → ℕ
+
+/-- Evaluate a comparison expression on the two input records, encoding truth by one and
+selecting the false arm on a zero test. -/
+def Expr.eval (x : Input) : Expr → ℕ
+ | .field right index => x right index
+ | .const n => n.val
+ | .eq a b => if a.eval x = b.eval x then 1 else 0
+ | .lt a b => if a.eval x < b.eval x then 1 else 0
+ | .le a b => if a.eval x ≤ b.eval x then 1 else 0
+ | .select test yes no => if test.eval x = 0 then no.eval x else yes.eval x
+
+/-- Word-operation count for a comparison expression, charging field accesses, constants,
+comparisons, and both arms of a select. -/
+def Expr.steps : Expr → ℕ
+ | .field .. | .const _ => 1
+ | .eq a b | .lt a b | .le a b => a.steps + b.steps + 1
+ | .select test yes no => test.steps + yes.steps + no.steps + 1
+
+/-- Each intermediate result fits one word when both operands fit.
+The immediate constants use at most two bits. -/
+theorem Expr.eval_lt {w : ℕ} (hw : 2 ≤ w) {x : Input} (hx : ∀ b i, x b i < 2 ^ w) (e : Expr) :
+ e.eval x < 2 ^ w := by
+ have hsize : 4 ≤ 2 ^ w := Nat.pow_le_pow_right (by decide : 0 < 2) hw
+ induction e with
+ | field b i => exact hx b i
+ | const n => exact n.isLt.trans_le hsize
+ | eq | lt | le => simp only [Expr.eval]; split <;> omega
+ | select => simp only [Expr.eval]; split <;> assumption
+
+private def occupied (right : Bool) : Expr :=
+ .select (.lt (.const 3) (.field right 0)) (.const 0) (.lt (.const 0) (.field right 0))
+
+private def lexStep (a b tail : Expr) : Expr := .select (.eq a b) tail (.lt a b)
+
+private def compareField (i : Fin 5) (tail : Expr) : Expr :=
+ lexStep (.field false i) (.field true i) tail
+
+private def probeFlag (right : Bool) : Expr := .lt (.const 1) (.field right 0)
+
+/-- The straight-line word comparison for two encoded slots. Tags outside
+the occupied range 1--3 compare as empty, as in the parser. -/
+def program : Expr :=
+ .select (occupied true)
+ (.select (occupied false)
+ (compareField 1 (lexStep (probeFlag false) (probeFlag true)
+ (compareField 3 (compareField 4 (compareField 0 (.le (.field false 2) (.field true 2)))))))
+ (.const 0))
+ (.const 1)
+
+private def tag : Kind → ℕ
+ | .init => 1
+ | .read => 2
+ | .write => 3
+
+/-- Word values of the paper's physical record, viewed as naturals. -/
+def slotWords {w : ℕ} (s : OrderedSlot (Word w)) : Fin 5 → ℕ :=
+ match s.record with
+ | none => fun _ ↦ 0
+ | some r => ![tag r.kind, r.address, r.value.val, r.startCost, r.ordinal]
+
+/-- Assemble the comparator input from two five-word arrays, choosing the right array on true
+and the left array on false. -/
+def inputs (l r : Fin 5 → ℕ) : Input := fun side ↦ if side then r else l
+
+private def kindIndex : Kind → ℕ
+ | .init => 0
+ | .read => 1
+ | .write => 2
+
+private abbrev Code (V : Type*) :=
+ WithTop (Lex (Lex (ℕ × Lex (ℕ × Lex (ℕ × ℕ))) × Lex (ℕ × V)))
+
+private def key {V : Type*} (s : OrderedSlot V) : Code V :=
+ match s.record with
+ | none => ⊤
+ | some r => ↑(toLex (toLex (r.address, r.timestamp), toLex (kindIndex r.kind, r.value)))
+
+private theorem le_iff_key {V : Type*} [LinearOrder V] (s t : OrderedSlot V) :
+ s ≤ t ↔ key s ≤ key t := Iff.rfl
+
+private theorem program_slots {w : ℕ} (s t : OrderedSlot (Word w)) :
+ program.eval (inputs (slotWords s) (slotWords t)) ≠ 0 ↔ s ≤ t := by
+ rcases s with ⟨_ | ⟨k, a, v, c, j⟩⟩ <;> rcases t with ⟨_ | ⟨k', a', v', c', j'⟩⟩
+ all_goals rw [le_iff_key]
+ all_goals first | cases k | skip
+ all_goals first | cases k' | skip
+ all_goals simp [program, occupied, compareField, lexStep, probeFlag, Expr.eval, inputs,
+ slotWords, tag, key, kindIndex, Record.timestamp, Prod.Lex.toLex_le_toLex,
+ Prod.Lex.toLex_lt_toLex]
+ all_goals try split_ifs
+ all_goals (try simp_all) <;> omega
+
+end WordCompare
+
+/-- Result and elementary word count of the fixed comparator. Natural field
+values represent one word for every slot supplied by the word-format parser. -/
+def compareSlots {w : ℕ} (s t : OrderedSlot (Word w)) : Bool × ℕ :=
+ (decide (WordCompare.program.eval (WordCompare.inputs (WordCompare.slotWords s)
+ (WordCompare.slotWords t)) ≠ 0), WordCompare.program.steps)
+
+theorem compareSlots_result {w : ℕ} (s t : OrderedSlot (Word w)) :
+ (compareSlots s t).1 = decide (s ≤ t) :=
+ decide_eq_decide.mpr (WordCompare.program_slots s t)
+
+@[simp] theorem compareSlots_steps {w : ℕ} (s t : OrderedSlot (Word w)) :
+ (compareSlots s t).2 = 66 := rfl
+
+/-- The word-level representation supplied by the five-word parser, including
+its convention for unknown tags and noncanonical padding. Canonicality is
+checked separately by `Format.decode`. -/
+def parsedSlot {w : ℕ} (hw : 2 ≤ w) (x : Fin 5 → Word w) : OrderedSlot (Word w) :=
+ ⟨((recordFormat hw).parse x).map WordRecord.record⟩
+
+namespace WordCompare
+
+private def Occupied (x : Fin 5 → ℕ) : Prop := 0 < x 0 ∧ x 0 ≤ 3
+
+private instance (x : Fin 5 → ℕ) : Decidable (Occupied x) :=
+ inferInstanceAs (Decidable (0 < x 0 ∧ x 0 ≤ 3))
+
+private def normalize (x : Fin 5 → ℕ) : Fin 5 → ℕ := if Occupied x then x else fun _ ↦ 0
+
+private theorem occupied_eval (x : Input) (side : Bool) :
+ (occupied side).eval x = if Occupied (x side) then 1 else 0 := by
+ by_cases hi : 3 < x side 0
+ · simp [occupied, Expr.eval, Occupied, hi, Nat.not_le_of_lt hi]
+ · have hle := Nat.le_of_not_gt hi
+ by_cases hpos : 0 < x side 0 <;> simp [occupied, Expr.eval, Occupied, hi, hle, hpos]
+
+private theorem program_normalize (x y : Fin 5 → ℕ) :
+ program.eval (inputs x y) = program.eval (inputs (normalize x) (normalize y)) := by
+ by_cases hy : Occupied y
+ · by_cases hx : Occupied x
+ · simp [normalize, hx, hy]
+ · have hz : ¬Occupied (fun _ ↦ 0) := by simp [Occupied]
+ simp [program, Expr.eval, occupied_eval, inputs, normalize, hx, hy, hz]
+ · have hz : ¬Occupied (fun _ ↦ 0) := by simp [Occupied]
+ simp [program, Expr.eval, occupied_eval, inputs, normalize, hy, hz]
+
+private theorem slotWords_parse {w : ℕ} (hw : 2 ≤ w) (a : Fin 5 → Word w) :
+ slotWords (parsedSlot hw a) = normalize (fun i ↦ (a i).val) := by
+ by_cases hv : Occupied (fun i ↦ (a i).val)
+ · rw [normalize, ite_eq_left hv]
+ change 0 < (a 0).val ∧ (a 0).val ≤ 3 at hv
+ have ht : (a 0).val = 1 ∨ (a 0).val = 2 ∨ (a 0).val = 3 := by omega
+ rcases ht with h | h | h <;> funext i <;> fin_cases i <;>
+ simp [slotWords, parsedSlot, recordFormat, WordRecord.record, tag, h]
+ · rw [normalize, ite_eq_right hv]
+ change ¬(0 < (a 0).val ∧ (a 0).val ≤ 3) at hv
+ have h₁ : (a 0).val ≠ 1 := by omega
+ have h₂ : (a 0).val ≠ 2 := by omega
+ have h₃ : (a 0).val ≠ 3 := by omega
+ simp [slotWords, parsedSlot, recordFormat]
+
+end WordCompare
+
+namespace WordCompare
+
+private def flag {w : ℕ} (hw : 2 ≤ w) (p : Prop) [Decidable p] : Word w :=
+ if p then ⟨1, by have := Nat.pow_le_pow_right (by decide : 0 < 2) hw; omega⟩ else 0
+
+private theorem flag_val {w : ℕ} (hw : 2 ≤ w) (p : Prop) [Decidable p] :
+ (flag hw p).val = if p then 1 else 0 := by
+ by_cases h : p <;> simp [flag, h]
+
+/-- Execute the syntax using genuine `w`-bit words. Each operand is evaluated
+before its instruction, including all three inputs of conditional selection. -/
+def Expr.runWord {w : ℕ} (hw : 2 ≤ w) (x : Bool → Fin 5 → Word w) : Expr → Word w × ℕ
+ | .field b i => (x b i, 1)
+ | .const n => (⟨n.val, n.isLt.trans_le (Nat.pow_le_pow_right (by decide : 0 < 2) hw)⟩, 1)
+ | .eq a b =>
+ let l := a.runWord hw x
+ let r := b.runWord hw x
+ (flag hw (l.1 = r.1), l.2 + r.2 + 1)
+ | .lt a b =>
+ let l := a.runWord hw x
+ let r := b.runWord hw x
+ (flag hw (l.1 < r.1), l.2 + r.2 + 1)
+ | .le a b =>
+ let l := a.runWord hw x
+ let r := b.runWord hw x
+ (flag hw (l.1 ≤ r.1), l.2 + r.2 + 1)
+ | .select t a b =>
+ let test := t.runWord hw x
+ let l := a.runWord hw x
+ let r := b.runWord hw x
+ (if test.1.val = 0 then r.1 else l.1, test.2 + l.2 + r.2 + 1)
+
+theorem Expr.runWord_spec {w : ℕ} (hw : 2 ≤ w) (x : Bool → Fin 5 → Word w) (e : Expr) :
+ (e.runWord hw x).1.val = e.eval (fun b i ↦ (x b i).val) ∧ (e.runWord hw x).2 = e.steps := by
+ induction e with
+ | field | const => exact ⟨rfl, rfl⟩
+ | eq a b ha hb =>
+ simp only [runWord, eval, steps, flag_val, Fin.ext_iff, ha.1, hb.1, ha.2, hb.2, and_self]
+ | lt a b ha hb =>
+ simp only [runWord, eval, steps, flag_val, Fin.lt_def, ha.1, hb.1, ha.2, hb.2, and_self]
+ | le a b ha hb =>
+ simp only [runWord, eval, steps, flag_val, Fin.le_def, ha.1, hb.1, ha.2, hb.2, and_self]
+ | select t a b ht ha hb =>
+ simp only [runWord, eval, steps, ht.1, ht.2, ha.2, hb.2, and_true]
+ split
+ · exact hb.1
+ · exact ha.1
+
+end WordCompare
+
+/-- Evaluation directly on the two received five-word tuples. -/
+def compareWords {w : ℕ} (hw : 2 ≤ w) (l r : Fin 5 → Word w) : Bool × ℕ :=
+ let output := WordCompare.program.runWord hw (fun side ↦ if side then r else l)
+ (decide (output.1.val ≠ 0), output.2)
+
+/-- The direct word computation gives exactly the abstract slot order and
+cost, even on arbitrary tag values that the raw parser interprets as empty. -/
+theorem compareWords_eq {w : ℕ} (hw : 2 ≤ w) (l r : Fin 5 → Word w) :
+ compareWords hw l r = compareSlots (parsedSlot hw l) (parsedSlot hw r) := by
+ have spec := WordCompare.program.runWord_spec hw (fun side ↦ if side then r else l)
+ simp only [compareWords, spec.1, spec.2, compareSlots, WordCompare.slotWords_parse]
+ change (decide (WordCompare.program.eval (WordCompare.inputs (fun i ↦ (l i).val)
+ (fun i ↦ (r i).val)) ≠ 0), _) = _
+ rw [WordCompare.program_normalize]
+
+/-- Every valid record, including an initialization or empty record, can be
+compared in the physical representation with the same result and step count. -/
+theorem compareWords_encoded {w : ℕ} (hw : 2 ≤ w) (l r : Option (WordRecord w)) :
+ compareWords hw ((recordFormat hw).words l) ((recordFormat hw).words r) =
+ compareSlots ⟨l.map WordRecord.record⟩ ⟨r.map WordRecord.record⟩ := by
+ simp [compareWords_eq, parsedSlot, Format.parse_words]
+
+namespace WordCompare
+
+/-- Lexicographic step on ordinary unsigned word values. -/
+def lexBit (a b : ℕ) (tail : Bool) : Bool := if a = b then tail else decide (a < b)
+
+private theorem lex_eval (x : Input) (a b tail : Expr) :
+ decide ((lexStep a b tail).eval x ≠ 0) =
+ lexBit (a.eval x) (b.eval x) (decide (tail.eval x ≠ 0)) := by
+ by_cases he : a.eval x = b.eval x <;> by_cases hl : a.eval x < b.eval x <;>
+ simp [lexStep, lexBit, Expr.eval, he, hl]
+
+/-- The bit-level sorting comparator can compute each lexicographic step
+as soon as it has classified the two unsigned word values. -/
+theorem compareWords_lex {w : ℕ} (hw : 2 ≤ w) (a b : Fin 5 → Word w) :
+ (compareWords hw a b).1 =
+ if 0 < (b 0).val ∧ (b 0).val ≤ 3 then
+ if 0 < (a 0).val ∧ (a 0).val ≤ 3 then
+ lexBit (a 1).val (b 1).val (lexBit (if 1 < (a 0).val then 1 else 0)
+ (if 1 < (b 0).val then 1 else 0) (lexBit (a 3).val (b 3).val
+ (lexBit (a 4).val (b 4).val (lexBit (a 0).val (b 0).val (decide (a 2 ≤ b 2)))))) else false
+ else true := by
+ have spec := program.runWord_spec hw (fun side ↦ if side then b else a)
+ simp only [compareWords, spec.1]
+ let x : Input := inputs (fun i ↦ (a i).val) (fun i ↦ (b i).val)
+ change decide (program.eval x ≠ 0) = _
+ have ha : (occupied false).eval x = if 0 < (a 0).val ∧ (a 0).val ≤ 3 then 1 else 0 :=
+ occupied_eval x false
+ have hb : (occupied true).eval x = if 0 < (b 0).val ∧ (b 0).val ≤ 3 then 1 else 0 :=
+ occupied_eval x true
+ let body := compareField 1 (lexStep (probeFlag false) (probeFlag true)
+ (compareField 3 (compareField 4 (compareField 0 (.le (.field false 2) (.field true 2))))))
+ change decide ((if (occupied true).eval x = 0 then 1 else if (occupied false).eval x = 0 then 0
+ else body.eval x) ≠ 0) = _
+ rw [ha,hb]
+ by_cases vb : 0 < (b 0).val ∧ (b 0).val ≤ 3
+ · rw [ite_eq_left vb, ite_eq_right (by decide : (1:ℕ) ≠ 0), ite_eq_left vb]
+ by_cases va : 0 < (a 0).val ∧ (a 0).val ≤ 3
+ · rw [ite_eq_left va, ite_eq_right (by decide : (1:ℕ) ≠ 0), ite_eq_left va]
+ dsimp only [body, compareField]
+ erw [lex_eval, lex_eval, lex_eval, lex_eval, lex_eval]
+ apply congrArg (fun bit ↦ lexBit (a 1).val (b 1).val (lexBit (if 1 < (a 0).val then 1 else 0)
+ (if 1 < (b 0).val then 1 else 0) (lexBit (a 3).val (b 3).val (lexBit (a 4).val (b 4).val
+ (lexBit (a 0).val (b 0).val bit)))))
+ apply decide_eq_decide.mpr
+ change (if (a 2).val ≤ (b 2).val then 1 else 0) ≠ 0 ↔ _
+ by_cases hv : (a 2).val ≤ (b 2).val <;> simp [hv, show (a 2 ≤ b 2) ↔ _ from Fin.le_def]
+ · rw [ite_eq_right va, ite_eq_left rfl, ite_eq_right va]
+ rfl
+ · rw [ite_eq_right vb, ite_eq_left rfl, ite_eq_right vb]
+ rfl
+
+end WordCompare
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortCorrect.lean b/lean/OAI/Computability/VPVNP/RAMSortCorrect.lean
new file mode 100644
index 0000000000..fd08cba613
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortCorrect.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.RAMSortNetwork
+import OAI.Computability.VPVNP.RAMSortPulse
+import Mathlib.Order.BooleanAlgebra.Basic
+
+/-!
+# Correctness of the bitonic record sort
+
+At any threshold a bitonic block has one cyclic interval of ones. Opposite
+comparisons produce a smaller and a larger pulse. Recursing sorts these into
+the two halves of the correct output, whose one counts are determined by
+truncating the old one count at half the block size. Thresholding then lifts
+the Boolean result to any linearly ordered record type.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+private theorem width_succ (b : ℕ) : 2 ^ (b + 1) = 2 * 2 ^ b := by
+ rw [Nat.pow_succ, Nat.mul_comm]
+
+private def pulseBlock (b s k : ℕ) : Wires b Bool := fun i ↦ pulse (2 ^ b) s k i
+
+/-- The Boolean block with `k` ones in the specified order. -/
+def orderedBits (b : ℕ) (up : Bool) (k : ℕ) : Wires b Bool :=
+ fun i ↦ if up then decide (2 ^ b - k ≤ i.val) else decide (i.val < k)
+
+private theorem min_bool (x y : Bool) : min x y = (x && y) := by cases x <;> cases y <;> rfl
+private theorem max_bool (x y : Bool) : max x y = (x || y) := by cases x <;> cases y <;> rfl
+
+private theorem splitMin (b s k : ℕ) :
+ (fun i ↦ min (lo (pulseBlock (b+1) s k) i) (hi (pulseBlock (b+1) s k) i)) =
+ pulseBlock b s (k - 2 ^ b) := by
+ funext i
+ change min (pulse (2 ^ (b+1)) s k i.val) (pulse (2 ^ (b+1)) s k (i.val + 2^b)) = _
+ rw [min_bool, width_succ, pulse_and (Nat.pow_pos (by decide))]
+ rfl
+
+private theorem splitMax (b s k : ℕ) :
+ (fun i ↦ max (lo (pulseBlock (b+1) s k) i) (hi (pulseBlock (b+1) s k) i)) =
+ pulseBlock b s (min k (2 ^ b)) := by
+ funext i
+ change max (pulse (2 ^ (b+1)) s k i.val) (pulse (2 ^ (b+1)) s k (i.val + 2^b)) = _
+ rw [max_bool, width_succ, pulse_or (Nat.pow_pos (by decide))]
+ rfl
+
+private theorem merge_pulse (b : ℕ) (up : Bool) (s k : ℕ) (hk : k ≤ 2 ^ b) :
+ merge b up (pulseBlock b s k) = orderedBits b up k := by
+ induction b generalizing k up with
+ | zero =>
+ funext i
+ have hi : i.val = 0 := by have := i.isLt; simp at this; omega
+ cases up <;> simp [merge, orderedBits, pulseBlock, pulse] <;> omega
+ | succ b ih =>
+ have hwidth := width_succ b
+ have hsmall : k - 2 ^ b ≤ 2 ^ b := by omega
+ have hlarge : min k (2 ^ b) ≤ 2 ^ b := min_le_right ..
+ cases up <;> simp only [merge, lower, upper, Bool.false_eq_true, ite_false, ite_true,
+ splitMin, splitMax, ih _ _ hsmall, ih _ _ hlarge]
+ all_goals
+ apply eq_of_halves <;> simp only [lo_join, hi_join]
+ all_goals
+ funext i
+ have := i.isLt
+ simp only [orderedBits, lo, hi, Bool.false_eq_true, ite_false, ite_true, decide_eq_decide]
+ omega
+
+private theorem bits_join_pulse (b k t : ℕ) (hk : k ≤ 2 ^ b) (ht : t ≤ 2 ^ b) :
+ join (orderedBits b true k) (orderedBits b false t) =
+ pulseBlock (b+1) (2 * 2 ^ b - (2 ^ b - k)) (k + t) := by
+ funext i
+ have hi := i.isLt
+ have hw := width_succ b
+ have hseg := pulse_of_segments (n := 2 ^ b) (a := 2 ^ b - k) (b := t)
+ (Nat.sub_le ..) ht (i := i.val) (by omega)
+ have hc : 2 ^ b - (2 ^ b - k) = k := by omega
+ rw [hc] at hseg
+ simp only [pulseBlock, hw, hseg, join, orderedBits, ite_true, Bool.false_eq_true, ite_false]
+ split <;> rfl
+
+/-- The network sorts every Boolean block into a single run of zeros and a
+single run of ones in the requested order. -/
+theorem sort_bits (b : ℕ) (up : Bool) (x : Wires b Bool) :
+ ∃ k ≤ 2 ^ b, sort b up x = orderedBits b up k := by
+ induction b generalizing up with
+ | zero =>
+ refine ⟨if x 0 then 1 else 0, ?_, ?_⟩
+ · split <;> decide
+ · funext i
+ have hi : i = 0 := Fin.ext (by have := i.isLt; simp at this; omega)
+ rw [hi]
+ cases h : x 0 <;> cases up <;> simp [sort, orderedBits, h]
+ | succ b ih =>
+ obtain ⟨k, hk, h₀⟩ := ih true (lo x)
+ obtain ⟨t, ht, h₁⟩ := ih false (hi x)
+ have hkt : k + t ≤ 2 ^ (b + 1) := by have := width_succ b; omega
+ refine ⟨k + t, hkt, ?_⟩
+ rw [sort, h₀, h₁, bits_join_pulse b k t hk ht, merge_pulse _ _ _ _ hkt]
+
+private theorem cut_mono {α : Type*} [LinearOrder α] (a : α) :
+ Monotone (fun x ↦ decide (a ≤ x)) := by
+ intro x y h
+ exact Bool.le_iff_imp.mpr (by simpa using fun hax : a ≤ x ↦ hax.trans h)
+
+/-- Batcher's ascending network sorts the entire block. -/
+theorem sort_monotone {α : Type*} [LinearOrder α] (b : ℕ) (x : Wires b α) :
+ Monotone (sort b true x) := by
+ intro i j hij
+ let cut := fun a : α ↦ decide (sort b true x i ≤ a)
+ have hmap := sort_map cut (cut_mono _) b true x
+ obtain ⟨k, _, hbits⟩ := sort_bits b true (cut ∘ x)
+ rw [hbits] at hmap
+ have hi := congrFun hmap i
+ have hj := congrFun hmap j
+ simp [cut, orderedBits] at hi hj
+ exact hj.mpr (hi.trans (Nat.add_le_add_right hij k))
+
+/-- Odd-numbered intermediate blocks are sorted in descending order. -/
+theorem sort_antitone {α : Type*} [LinearOrder α] (b : ℕ) (x : Wires b α) :
+ Antitone (sort b false x) := by
+ intro i j hij
+ let cut := fun a : α ↦ decide (sort b false x j ≤ a)
+ have hmap := sort_map cut (cut_mono _) b false x
+ obtain ⟨k, _, hbits⟩ := sort_bits b false (cut ∘ x)
+ rw [hbits] at hmap
+ have hi := congrFun hmap i
+ have hj := congrFun hmap j
+ simp [cut, orderedBits] at hi hj
+ exact hi.mpr (lt_of_le_of_lt hij hj)
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortCost.lean b/lean/OAI/Computability/VPVNP/RAMSortCost.lean
new file mode 100644
index 0000000000..bec6e1c236
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortCost.lean
@@ -0,0 +1,361 @@
+import OAI.Computability.VPVNP.RAMSortCostLayout
+import OAI.Computability.VPVNP.RAMSortCompareCost
+import OAI.Computability.VPVNP.RAMSortDecodeCost
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+
+/-!
+# Word work of the local bitonic validator
+
+A site materializes its next block in a second array, scanning every local
+offset once per layer. At a cross-site stride it reads both five-word fields
+from the site's incident bit array. It validates both encodings, checks the
+send against the current record, and uses the receive in the comparator.
+Malformed fields set a failure flag. All loop lengths are public, including
+on paths that have already set this flag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+open BurstRAM RAMSerialization RAMMemory
+
+variable {h d w : ℕ}
+
+private abbrev Slot (w : ℕ) := OrderedSlot (Word w)
+
+private def orderedRecord (r : Option (WordRecord w)) : Slot w := ⟨r.map WordRecord.record⟩
+
+/-- Parse one record at its exact linear address in the incident bit array.
+In addition to the word scan, each of its `5*w` reads adds the record's base
+to the within-record bit index. -/
+def readSlot (hw : 2 ≤ w) (incident : ℕ → Bool) (s : Stage (h+d)) (dir : Fin 2)
+ (i : Fin (2 ^ h)) : Option (OrderedSlot (Word w)) × ℕ :=
+ let start := fieldStart h w s.phase s.stride dir.val i.val
+ let decoded := decodeSlot hw (fun bit ↦ incident (start.eval + bit.val))
+ (decoded.1.map orderedRecord, start.work + 5*w + decoded.2)
+
+theorem readSlot_cost (hw : 2 ≤ w) (incident : ℕ → Bool) (s : Stage (h+d)) (dir : Fin 2)
+ (i : Fin (2 ^ h)) : (readSlot hw incident s dir i).2 ≤ 21 + 5*w + 64*(w+1) := by
+ unfold readSlot
+ simp only [fieldStart_work]
+ exact Nat.add_le_add_left (decodeSlot_cost ..) _
+
+private def emptySlot : Slot w := ⟨none⟩
+
+private def exchange (keepMin : Bool) (x y : Slot w) : Slot w × ℕ :=
+ let cmp := compareSlots x y
+ -- One Boolean equality, a branch and five word copies.
+ (if cmp.1 == keepMin then x else y, cmp.2 + 7)
+
+private theorem exchange_value (keepMin : Bool) (x y : Slot w) :
+ (exchange keepMin x y).1 = if keepMin then min x y else max x y := by
+ by_cases hle : x ≤ y
+ · cases keepMin <;> simp [exchange, compareSlots_result, hle]
+ · have hy := le_of_not_ge hle
+ cases keepMin <;> simp [exchange, compareSlots_result, hle, min_eq_right hy, max_eq_left hy]
+
+/-- Result of processing one wire offset in a local sorting layer, with its selected record,
+validation flag, and work charge. -/
+structure SiteRow (w : ℕ) where
+ /-- Padded record selected by the comparator for this wire in the next layer. -/
+ slot : OrderedSlot (Word w)
+ /-- Per-offset validation flag. At a cross-site layer it checks both encodings and agreement
+ of the outgoing record with the current wire. -/
+ ok : Bool
+ /-- Word operations charged to addressing, reading, checking, and comparing the records at
+ this offset. -/
+ steps : ℕ
+
+/-- One bounded per-offset operation. Local strides have no incident fields.
+The additional constant steps cover tag-presence checks, Boolean operations,
+five output writes and offset-loop control. -/
+def scanRow (hw : 2 ≤ w) (incident : ℕ → Bool) (s : Stage (h+d)) (v : Fin (2^d))
+ (current : Wires h (Slot w)) (i : Fin (2^h)) : SiteRow w :=
+ let g := wireIndex h v.val i.val
+ let p := wirePartner h v.val i.val s.stride
+ let dir := directionBit h v.val i.val s.phase
+ let keepMin := decide (g.eval < p.eval) == decide (dir.eval = 0)
+ let addressWork := g.work + p.work + dir.work + 2
+ if hc : h ≤ s.stride then
+ let out := readSlot hw incident s 0 i
+ let inc := readSlot hw incident s 1 i
+ let sent := out.1.getD emptySlot
+ let ab := compareSlots sent (current i)
+ let ba := compareSlots (current i) sent
+ let next := exchange keepMin (current i) (inc.1.getD emptySlot)
+ ⟨next.1, out.1.isSome && inc.1.isSome && ab.1 && ba.1,
+ addressWork + out.2 + inc.2 + ab.2 + ba.2 + next.2 + 20⟩
+ else
+ let other := current ⟨partner s.stride i, partner_lt i.isLt (Nat.lt_of_not_ge hc)⟩
+ let next := exchange keepMin (current i) other
+ -- Shift/xor for the local partner, plus writes and loop control.
+ ⟨next.1, true, addressWork + next.2 + 12⟩
+
+/-- What the local send and receive field parsers return for this layer.
+The receive field comes from the unique designated partner. -/
+def Loads (hw : 2 ≤ w) (incident : ℕ → Bool) (s : Stage (h+d)) (send : Sends h d s (Slot w))
+ (v : Fin (2^d)) : Prop :=
+ ∀ hc : h ≤ s.stride, ∀ i,
+ (readSlot hw incident s 0 i).1 = some (send hc v i) ∧
+ (readSlot hw incident s 1 i).1 = some (send hc (sourceSite s hc v) i)
+
+private theorem exchange_orientation (first up : Bool) (x y : Slot w) :
+ (exchange (first == up) x y).1 = if first then lower up x y else upper up y x := by
+ rw [exchange_value]
+ cases first <;> cases up <;> simp [lower, upper, min_comm, max_comm]
+
+private theorem scanRow_spec (hw : 2 ≤ w) (incident : ℕ → Bool) (s : Stage (h+d))
+ (send : Sends h d s (Slot w)) (v : Fin (2^d)) (current : Wires h (Slot w))
+ (i : Fin (2^h)) (hs : Loads hw incident s send v) :
+ (scanRow hw incident s v current i).slot = localLayer s send v current i ∧
+ ((scanRow hw incident s v current i).ok = true ↔ ∀ hc, send hc v i = current i) := by
+ by_cases hc : h ≤ s.stride
+ · obtain ⟨h₀, h₁⟩ := hs hc i
+ simp only [scanRow, localLayer, hc, dite_true, h₀, h₁, Option.getD_some, Option.isSome_some,
+ wireIndex_eval, wirePartner_eval, directionBit_eval, exchange_orientation, compareSlots_result,
+ Bool.true_and, Bool.and_eq_true, decide_eq_true_eq]
+ simp only [true_and]
+ exact ⟨fun h _ ↦ le_antisymm h.1 h.2, fun he ↦ ⟨(he trivial).le, (he trivial).ge⟩⟩
+ · simp [scanRow, localLayer, hc, exchange_orientation]
+
+/-- Output array, status flag and work accumulated during a materialized
+scan of one site block or of several consecutive layers. -/
+structure Scan (h w : ℕ) where
+ /-- The site’s array of padded records after the scanned sorting layers. -/
+ block : Wires h (Slot w)
+ /-- Conjunction of the per-offset validation flags over the layers processed by the scan. -/
+ ok : Bool
+ /-- Accumulated word work of the site’s scan, including the row charges and public loop
+ overhead. -/
+ steps : ℕ
+
+/-- Tabulate all offsets into the next buffer, retaining the conjunction of
+their flags. Each row is computed once. The two buffers can swap roles. -/
+def scanLayer (hw : 2 ≤ w) (incident : ℕ → Bool) (s : Stage (h+d))
+ (v : Fin (2^d)) (current : Wires h (Slot w)) : Scan h w :=
+ let rows := Vector.ofFn (scanRow hw incident s v current)
+ ⟨fun i ↦ rows[i.val].slot, (List.ofFn (fun i : Fin (2^h) ↦ rows[i.val].ok)).all id,
+ (∑ i : Fin (2^h), rows[i.val].steps) + 4⟩
+
+/-- Public phase and stride loops. Rejection is latched, so the upper bound
+also covers arbitrary messages after the first failing check. -/
+def scanStages (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d)) :
+ List (Stage (h+d)) → Wires h (Slot w) → Scan h w
+ | [], current => ⟨current, true, 1⟩
+ | s :: ss, current =>
+ let step := scanLayer hw incident s v current
+ let rest := scanStages hw incident v ss step.block
+ ⟨rest.block, step.ok && rest.ok, step.steps + rest.steps + 5⟩
+
+/-- Successful raw parsing of all chronological send/receive fields into
+the corresponding records of a replay assignment. -/
+def LoadsStages (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d)) :
+ (ss : List (Stage (h+d))) → Fields h d (Slot w) ss → Prop
+ | [], _ => True
+ | s :: ss, fields => Loads hw incident s fields.1 v ∧ LoadsStages hw incident v ss fields.2
+
+/-- Whenever the physical fields parse, this costed scan runs exactly the
+local validator: it gives the same resulting records and the same decision. -/
+theorem scanStages_spec (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d))
+ (ss : List (Stage (h+d))) (fields : Fields h d (Slot w) ss) (current : Wires h (Slot w))
+ (hs : LoadsStages hw incident v ss fields) :
+ (scanStages hw incident v ss current).block = replay v ss fields current ∧
+ ((scanStages hw incident v ss current).ok = true ↔ checks v ss fields current) := by
+ induction ss generalizing current with
+ | nil => simp [scanStages, replay, checks]
+ | cons s ss ih =>
+ have hr := fun i ↦ scanRow_spec hw incident s fields.1 v current i hs.1
+ have hblock : (scanLayer hw incident s v current).block = localLayer s fields.1 v current :=
+ funext fun i ↦ by simpa [scanLayer] using (hr i).1
+ have hok : (scanLayer hw incident s v current).ok = true ↔ ∀ hc, fields.1 hc v = current := by
+ simp only [scanLayer, Vector.getElem_ofFn, List.all_eq_true, List.mem_ofFn, id_eq]
+ constructor
+ · intro hh hc
+ funext i
+ exact ((hr i).2.mp (hh _ ⟨i, rfl⟩)) hc
+ · rintro hh _ ⟨i, rfl⟩
+ exact (hr i).2.mpr fun hc ↦ congrFun (hh hc) i
+ have ht := ih fields.2 (localLayer s fields.1 v current) hs.2
+ simp only [scanStages, replay, checks, hblock, Bool.and_eq_true, hok, ht.1, ht.2, true_and]
+
+private theorem canonical_of_readSlot (hw : 2 ≤ w) (incident : ℕ → Bool) (s : Stage (h+d))
+ (dir : Fin 2) (i : Fin (2 ^ h)) (hp : (readSlot hw incident s dir i).1.isSome = true) :
+ ∃ r : Option (WordRecord w),
+ (fun bit : Fin (5*w) ↦ incident ((fieldStart h w s.phase s.stride dir.val i.val).eval +
+ bit.val)) = (recordFormat hw).encode r := by
+ let bits := fun bit : Fin (5*w) ↦
+ incident ((fieldStart h w s.phase s.stride dir.val i.val).eval + bit.val)
+ change ((decodeSlot hw bits).1.map orderedRecord).isSome = true at hp
+ rw [decodeSlot_eq] at hp
+ cases hp' : (recordFormat hw).decode bits with
+ | none => simp [hp'] at hp
+ | some r => exact ⟨r, ((recordFormat hw).decode_iff bits r).mp hp'⟩
+
+/-- Passing the costed scan forces every raw send and receive field used by
+this site to be a canonical encoding. A malformed tag or noncanonical
+padding at any layer prevents acceptance. -/
+theorem scanStages_canonical (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d))
+ (ss : List (Stage (h+d))) (current : Wires h (Slot w))
+ (hp : (scanStages hw incident v ss current).ok = true) :
+ ∀ s ∈ ss, h ≤ s.stride → ∀ dir : Fin 2, ∀ i : Fin (2^h), ∃ r : Option (WordRecord w),
+ (fun bit : Fin (5*w) ↦ incident ((fieldStart h w s.phase s.stride dir.val i.val).eval +
+ bit.val)) = (recordFormat hw).encode r := by
+ induction ss generalizing current with
+ | nil => simp
+ | cons s ss ih =>
+ obtain ⟨hfirst, htail⟩ := Bool.and_eq_true_iff.mp hp
+ intro t ht hc dir i
+ rcases List.mem_cons.mp ht with rfl | hmem
+ · have hr : (scanRow hw incident t v current i).ok = true := by
+ simp only [scanLayer, Vector.getElem_ofFn] at hfirst
+ exact List.all_eq_true.mp hfirst _ (List.mem_ofFn.mpr ⟨i, rfl⟩)
+ simp only [scanRow, hc, dite_true, Bool.and_eq_true] at hr
+ apply canonical_of_readSlot
+ have hdir : dir = 0 ∨ dir = 1 := by
+ have hv : dir.val = 0 ∨ dir.val = 1 := by have := dir.isLt; omega
+ rcases hv with h | h
+ · exact Or.inl (Fin.ext h)
+ · exact Or.inr (Fin.ext h)
+ rcases hdir with rfl | rfl
+ · exact hr.1.1.1
+ · exact hr.1.1.2
+ · exact ih _ htail t hmem hc dir i
+
+/-- Work bound for one offset, including two arbitrary five-word fields on
+a cross-site layer. -/
+theorem scanRow_cost (hw : 2 ≤ w) (incident : ℕ → Bool) (s : Stage (h+d)) (v : Fin (2^d))
+ (current : Wires h (Slot w)) (i : Fin (2^h)) :
+ (scanRow hw incident s v current i).steps ≤ 1000 * (w+1) := by
+ by_cases hc : h ≤ s.stride
+ · have ho := readSlot_cost hw incident s 0 i
+ have hi := readSlot_cost hw incident s 1 i
+ simp only [scanRow, hc, dite_true, wireAddress_work, exchange, compareSlots_steps]
+ omega
+ · simp only [scanRow, hc, dite_false, wireAddress_work, exchange, compareSlots_steps]
+ omega
+
+theorem scanStages_cost (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d))
+ (ss : List (Stage (h+d))) (current : Wires h (Slot w)) :
+ (scanStages hw incident v ss current).steps ≤ 1 + ss.length * (2^h * (1000*(w+1)) + 9) := by
+ induction ss generalizing current with
+ | nil => simp [scanStages]
+ | cons s ss ih =>
+ have hsum := Finset.sum_le_sum (s := Finset.univ) (fun i _ ↦ scanRow_cost hw incident s v current i)
+ simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, Nat.nsmul_eq_mul] at hsum
+ have ht := ih (scanLayer hw incident s v current).block
+ simp only [scanStages, scanLayer, Vector.getElem_ofFn, List.length_cons, Nat.add_mul,
+ Nat.one_mul, Fin.eta] at ht ⊢
+ omega
+
+/-- Exact public loop bound. The slot bound applies even when a field
+encodes a bad tag or nonzero padding. -/
+theorem sortScan_cost (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d))
+ (current : Wires h (Slot w)) :
+ (scanStages hw incident v (phases (h+d) (h+d) le_rfl) current).steps ≤
+ 1 + (h+d+1).choose 2 * (2^h * (1000*(w+1)) + 9) := by
+ simpa using scanStages_cost hw incident v (phases (h+d) (h+d) le_rfl) current
+
+/-- Emit the `k` stride entries of a phase directly onto a supplied suffix.
+Each iteration tests and decrements the counter, writes the two stage words,
+and links the new entry. -/
+def emitStrides (b a : ℕ) (ha : a ≤ b) :
+ (k : ℕ) → k ≤ a → List (Stage b) → List (Stage b) × ℕ
+ | 0, _, tail => (tail, 1)
+ | k+1, hk, tail =>
+ let rest := emitStrides b a ha k (Nat.le_of_succ_le hk) tail
+ (⟨a,k,hk,ha⟩ :: rest.1, rest.2 + 5)
+
+private theorem emitStrides_spec (b a : ℕ) (ha : a ≤ b) (k : ℕ) (hk : k ≤ a)
+ (tail : List (Stage b)) :
+ emitStrides b a ha k hk tail = (strides b a ha k hk ++ tail, 1 + 5*k) := by
+ induction k with
+ | zero => simp [emitStrides, strides]
+ | succ k ih => simp [emitStrides, strides, ih, Nat.mul_add, Nat.add_assoc]
+
+/-- Generate the public chronological layer schedule in a single pass,
+using a suffix accumulator. The construction copies each stage only once. -/
+def emitPhases (b : ℕ) : (a : ℕ) → a ≤ b → List (Stage b) → List (Stage b) × ℕ
+ | 0, _, tail => (tail, 1)
+ | a+1, ha, tail =>
+ let suffix := emitStrides b (a+1) ha (a+1) le_rfl tail
+ let result := emitPhases b a (Nat.le_of_succ_le ha) suffix.1
+ (result.1, suffix.2 + result.2 + 4)
+
+/-- Exact word charge for emitting the public phase and stride schedule. -/
+theorem emitPhases_spec (b a : ℕ) (ha : a ≤ b) (tail : List (Stage b)) :
+ emitPhases b a ha tail = (phases b a ha ++ tail, 1 + 5*a + 5*(a+1).choose 2) := by
+ induction a generalizing tail with
+ | zero => simp [emitPhases, phases]
+ | succ a ih =>
+ simp only [emitPhases, emitStrides_spec, ih, phases, List.append_assoc,
+ Nat.choose_succ_succ (a+1) 1, Nat.choose_one_right, Nat.reduceSucc, Prod.mk.injEq, true_and]
+ omega
+
+/-- Complete costed sorting subroutine, including the linear-time generation
+of all comparator layers. -/
+def scanSort (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d))
+ (current : Wires h (Slot w)) : Scan h w :=
+ if h+d = 0 then ⟨current, true, 1⟩
+ else
+ let stages := emitPhases (h+d) (h+d) le_rfl []
+ let run := scanStages hw incident v stages.1 current
+ ⟨run.block, run.ok, stages.2 + run.steps + 1⟩
+
+@[simp] theorem scanSort_block (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d))
+ (current : Wires h (Slot w)) :
+ (scanSort hw incident v current).block =
+ (scanStages hw incident v (phases (h+d) (h+d) le_rfl) current).block := by
+ by_cases hb : h+d = 0
+ · obtain ⟨rfl, rfl⟩ : h = 0 ∧ d = 0 := by omega
+ rfl
+ · simp only [scanSort, hb, ite_false, emitPhases_spec, List.append_nil]
+
+@[simp] theorem scanSort_ok (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d))
+ (current : Wires h (Slot w)) :
+ (scanSort hw incident v current).ok =
+ (scanStages hw incident v (phases (h+d) (h+d) le_rfl) current).ok := by
+ by_cases hb : h+d = 0
+ · obtain ⟨rfl, rfl⟩ : h = 0 ∧ d = 0 := by omega
+ rfl
+ · simp only [scanSort, hb, ite_false, emitPhases_spec, List.append_nil]
+
+private theorem layers_ge_phase (b : ℕ) : b ≤ (b+1).choose 2 := by
+ induction b with
+ | zero => simp
+ | succ b ih =>
+ rw [Nat.choose_succ_succ (b+1) 1, Nat.choose_one_right]
+ exact Nat.le_add_right ..
+
+/-- All parsing, address computations, comparator applications and public
+schedule generation in the sorting subroutine have a uniform word bound. -/
+theorem scanSort_cost (hw : 2 ≤ w) (incident : ℕ → Bool) (v : Fin (2^d))
+ (current : Wires h (Slot w)) :
+ (scanSort hw incident v current).steps ≤
+ 1 + (h+d+1).choose 2 * (2^h * (1024*(w+1)) + 9) := by
+ by_cases hb : h+d = 0
+ · obtain ⟨rfl, rfl⟩ : h = 0 ∧ d = 0 := by omega
+ simp [scanSort]
+ · let L := (h+d+1).choose 2
+ have hL : h+d ≤ L := layers_ge_phase (h+d)
+ have hwork := sortScan_cost hw incident v current
+ have hscale : 1 ≤ 2^h * (w+1) := Nat.mul_pos (Nat.two_pow_pos h) (Nat.succ_pos _)
+ have hslack : 2^h * (1000*(w+1)) + 9 + 12 ≤ 2^h * (1024*(w+1)) + 9 := by
+ rw [Nat.mul_left_comm (2^h) 1000, Nat.mul_left_comm (2^h) 1024]
+ omega
+ have hmain := Nat.mul_le_mul_left L hslack
+ rw [Nat.mul_add L _ 12] at hmain
+ simp only [scanSort, hb, ite_false, emitPhases_spec, List.append_nil]
+ change _ ≤ 1 + L * (2^h * (1024*(w+1)) + 9)
+ change _ ≤ 1 + L * (2^h * (1000*(w+1)) + 9) at hwork
+ change 1 + 5*(h+d) + 5*L + _ + 1 ≤ _
+ omega
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortCostLayout.lean b/lean/OAI/Computability/VPVNP/RAMSortCostLayout.lean
new file mode 100644
index 0000000000..a03af95a4a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortCostLayout.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.RAMSortFieldIndex
+
+/-!
+# Loop bounds and word addresses for replaying a sorting stage
+
+The validator enumerates the public phase and stride counters. It computes
+each partner by a shift and xor, and computes the start of an incident
+record field using a triangular layer number and a linear bit offset.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+@[simp] theorem length_strides {b a : ℕ} (ha : a ≤ b) (k : ℕ) (hk : k ≤ a) :
+ (strides b a ha k hk).length = k := by
+ induction k with
+ | zero => rfl
+ | succ k ih => simp [strides, ih]
+
+/-- Exactly this many comparator layers are visited, regardless of the data. -/
+@[simp] theorem length_phases {b : ℕ} (a : ℕ) (ha : a ≤ b) :
+ (phases b a ha).length = (a + 1).choose 2 := by
+ induction a with
+ | zero => rfl
+ | succ a ih =>
+ rw [phases, List.length_append, ih, length_strides,
+ Nat.choose_succ_succ (a + 1) 1, Nat.choose_one_right, Nat.add_comm]
+
+/-- A straight-line calculation of addresses and routing flags. Input
+registers and public constants are available before this calculation. -/
+inductive IndexExpr
+ | arg (x : ℕ)
+ | add (a b : IndexExpr)
+ | sub (a b : IndexExpr)
+ | mul (a b : IndexExpr)
+ | div (a b : IndexExpr)
+ | mod (a b : IndexExpr)
+ | xor (a b : IndexExpr)
+ | shl (a b : IndexExpr)
+ | shr (a b : IndexExpr)
+
+/-- Evaluate a sorting address or routing expression using natural-number arithmetic, shifts,
+and exclusive-or. -/
+def IndexExpr.eval : IndexExpr → ℕ
+ | .arg x => x
+ | .add a b => a.eval + b.eval
+ | .sub a b => a.eval - b.eval
+ | .mul a b => a.eval * b.eval
+ | .div a b => a.eval / b.eval
+ | .mod a b => a.eval % b.eval
+ | .xor a b => a.eval ^^^ b.eval
+ | .shl a b => a.eval <<< b.eval
+ | .shr a b => a.eval >>> b.eval
+
+/-- Count one operation for every binary node of the routing expression, treating its given
+arguments as available registers. -/
+def IndexExpr.work : IndexExpr → ℕ
+ | .arg _ => 0
+ | .add a b | .sub a b | .mul a b | .div a b | .mod a b | .xor a b | .shl a b | .shr a b =>
+ a.work + b.work + 1
+
+/-- Arithmetic expressions for the current index, its comparator partner,
+and the direction bit of the phase. -/
+def wireIndex (h site off : ℕ) : IndexExpr := .add (.shl (.arg site) (.arg h)) (.arg off)
+/-- Comparator partner index obtained by toggling bit j of the global wire index formed from
+the site and offset. -/
+def wirePartner (h site off j : ℕ) : IndexExpr := .xor (wireIndex h site off) (.shl (.arg 1) (.arg j))
+/-- Extract bit a of the global wire index to determine ascending or descending order in phase
+a. -/
+def directionBit (h site off a : ℕ) : IndexExpr :=
+ .mod (.shr (wireIndex h site off) (.arg a)) (.arg 2)
+
+@[simp] theorem wireIndex_eval (h site off : ℕ) :
+ (wireIndex h site off).eval = site * 2 ^ h + off := by
+ simp [wireIndex, IndexExpr.eval, Nat.shiftLeft_eq]
+
+@[simp] theorem wirePartner_eval (h site off j : ℕ) :
+ (wirePartner h site off j).eval = partner j (site * 2 ^ h + off) := by
+ simp [wirePartner, IndexExpr.eval, Nat.shiftLeft_eq, partner]
+
+@[simp] theorem directionBit_eval (h site off a : ℕ) :
+ decide ((directionBit h site off a).eval = 0) = phaseDirection a (site * 2 ^ h + off) := by
+ simp [directionBit, IndexExpr.eval, Nat.shiftRight_eq_div_pow, phaseDirection]
+
+/-- Linear bit address of the first bit of a single five-word record. The
+two direction fields at each cross layer immediately follow the two
+eight-word successor fields. -/
+def fieldStart (h w a j dir off : ℕ) : IndexExpr :=
+ let p := IndexExpr.sub (.sub (.arg a) (.arg h)) (.arg 1)
+ let step := IndexExpr.sub (.sub (.arg a) (.arg j)) (.arg 1)
+ let ord := IndexExpr.add (.div (.mul p (.add p (.arg 1))) (.arg 2)) step
+ let width := IndexExpr.mul (.mul (.shl (.arg 1) (.arg h)) (.arg 5)) (.arg w)
+ .add (.add (.mul (.arg 16) (.arg w)) (.mul (.add (.mul ord (.arg 2)) (.arg dir)) width))
+ (.mul (.mul (.arg off) (.arg 5)) (.arg w))
+
+theorem fieldStart_eval (h w a j dir off : ℕ) :
+ (fieldStart h w a j dir off).eval =
+ 16 * w + ((((a-h-1) * ((a-h-1)+1) / 2 + (a-j-1)) * 2 + dir) *
+ (2 ^ h * 5 * w)) + off * 5 * w := by
+ simp [fieldStart, IndexExpr.eval, Nat.shiftLeft_eq]
+
+/-- The straight-line address is the address in the allocation of equation
+(10.1), including the offset of an individual bit inside its record. -/
+theorem fieldStart_physical {h d H w : ℕ} (hw : 2 ^ h = 4 * H)
+ (s : Stage (h+d)) (hc : h ≤ s.stride) (dir : Fin 2) (off : Fin (2 ^ h))
+ (bit : Fin (5 * w)) :
+ (fieldStart h w s.phase s.stride dir.val off.val).eval + bit.val =
+ (RAMLayout.offset d H w (.inr (((crossStageEquiv h d).symm ⟨s, hc⟩), dir,
+ ⟨off.val * 5 * w + bit.val, by
+ have hoff : (off.val + 1) ≤ 4 * H := hw ▸ off.isLt
+ have hb := Nat.mul_le_mul_right (5 * w) hoff
+ have hbit := bit.isLt
+ simp only [Nat.add_mul, Nat.one_mul, ← Nat.mul_assoc] at hb
+ unfold RAMLayout.blockBits
+ omega⟩))).val := by
+ rw [fieldStart_eval, RAMLayout.offset_sort]
+ simp only [crossStageEquiv, Equiv.coe_fn_symm_mk, RAMLayout.Layer.ordinal, RAMLayout.layerCount,
+ Nat.choose_two_right, Nat.add_sub_cancel, RAMLayout.blockBits, hw]
+ rw [Nat.mul_comm (s.phase - h - 1 + 1) (s.phase - h - 1)]
+ ring
+
+/-- Two address comparisons after computing all three expressions, even
+when the current index is recomputed for each use. -/
+theorem wireAddress_work (h site off j a : ℕ) :
+ (wireIndex h site off).work + (wirePartner h site off j).work +
+ (directionBit h site off a).work + 2 = 12 := rfl
+
+@[simp] theorem fieldStart_work (h w a j dir off : ℕ) :
+ (fieldStart h w a j dir off).work = 21 := rfl
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortDecodeCost.lean b/lean/OAI/Computability/VPVNP/RAMSortDecodeCost.lean
new file mode 100644
index 0000000000..ba6d82379c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortDecodeCost.lean
@@ -0,0 +1,198 @@
+import OAI.Computability.VPVNP.RAMSerialization
+import Mathlib.Tactic.FinCases
+
+/-!
+# Word work to decode a sorting record
+
+The validator of Lemma 10.1 receives five little-endian words per record. The scan below
+visits the most significant remaining bit, doubles the accumulator, and adds the bit.
+The decoder retains the five results, parses their tag and checks the resulting canonical
+words. Its bound applies to every bit field, including unknown tags and malformed padding.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+open BurstRAM RAMSerialization
+
+variable {w : ℕ}
+
+/-- The first component is the decoded value. The second counts word operations. At each
+bit charge the loop test, decrement, offset arithmetic, bit load, doubling, addition and
+loop branch. Offset arithmetic has two operations, giving eight in total. The final zero
+counter test costs one. -/
+private def scanFrom (b : Fin w → Bool) : (k : ℕ) → k ≤ w → ℕ → ℕ × ℕ
+ | 0, _, acc => (acc, 1)
+ | k + 1, hk, acc =>
+ let bit := b ⟨k, hk⟩
+ let r := scanFrom b k (by omega) (acc + acc + bit.toNat)
+ (r.1, 8 + r.2)
+
+private theorem scanFrom_steps (b : Fin w → Bool) (k : ℕ) (hk : k ≤ w) (acc : ℕ) :
+ (scanFrom b k hk acc).2 = 8 * k + 1 := by
+ induction k generalizing acc with
+ | zero => rfl
+ | succ k ih => simp only [scanFrom, ih]; omega
+
+/-- After `w-k-1` bits, doubling the accumulator and adding a bit fits in `w-k` bits.
+Thus all intermediate results of the scan from zero fit in a single `w`-bit word. -/
+theorem scan_digit_fits {k acc : ℕ} (hk : k + 1 ≤ w) (ha : acc < 2 ^ (w - (k + 1))) (bit : Bool) :
+ acc + acc + bit.toNat < 2 ^ (w - k) := by
+ rw [show w - k = (w - (k + 1)) + 1 by omega, Nat.pow_succ]
+ cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega
+
+private theorem scanFrom_value (b : Fin w → Bool) (k : ℕ) (hk : k ≤ w) (acc : ℕ) :
+ (scanFrom b k hk acc).1 = acc * 2 ^ k + ∑ i : Fin k, (b ⟨i, i.isLt.trans_le hk⟩).toNat * 2 ^ (i : ℕ) := by
+ induction k generalizing acc with
+ | zero => simp [scanFrom]
+ | succ k ih =>
+ rw [scanFrom, ih, Fin.sum_univ_castSucc]
+ simp only [Fin.val_castSucc, Fin.val_last, Nat.pow_succ, Nat.add_mul, ← Nat.mul_assoc]
+ omega
+
+private theorem inverse_word_value (b : Fin w → Bool) :
+ ((wordBits w).symm b).val = ∑ i, (b i).toNat * 2 ^ (i : ℕ) := by
+ change (finFunctionFinEquiv (fun i ↦ finTwoEquiv.symm (b i)) : ℕ) = _
+ rw [finFunctionFinEquiv_apply]
+ apply Finset.sum_congr rfl
+ intro i _
+ cases h : b i <;> rfl
+
+/-- Decode a word once. Charge the initialization of the cursor and accumulator. -/
+def scanWord (b : Fin w → Bool) : Word w × ℕ :=
+ let result := scanFrom b w le_rfl 0
+ (⟨result.1, by
+ rw [scanFrom_value, Nat.zero_mul, Nat.zero_add, ← inverse_word_value b]
+ exact ((wordBits w).symm b).isLt⟩, result.2 + 2)
+
+theorem scanWord_eq (b : Fin w → Bool) : (scanWord b).1 = (wordBits w).symm b := by
+ apply Fin.ext
+ simp [scanWord, scanFrom_value, inverse_word_value]
+
+@[simp] theorem scanWord_steps (b : Fin w → Bool) : (scanWord b).2 = 8 * w + 3 := by
+ simp [scanWord, scanFrom_steps, Nat.add_assoc]
+
+/-- Read the tag register, compare against up to three known tags, and copy four
+payload registers into the parsed record. Each failed comparison costs a compare and a
+branch. Unknown tags reach the empty-record candidate and are checked below. -/
+private def parseSaved (a : Fin 5 → Word w) : Option (WordRecord w) × ℕ :=
+ let tag := (a 0).val
+ let mk := fun k ↦ some (WordRecord.mk k (a 1) (a 2) (a 3) (a 4))
+ if tag = 1 then (mk .init, 8)
+ else if tag = 2 then (mk .read, 10)
+ else if tag = 3 then (mk .write, 12)
+ else (none, 8)
+
+private theorem parseSaved_eq (hw : 2 ≤ w) (a : Fin 5 → Word w) :
+ (parseSaved a).1 = (recordFormat hw).parse a := by
+ simp only [parseSaved, recordFormat]
+ generalize (a 0).val = tag
+ match tag with
+ | 0 | 1 | 2 | 3 | _ + 4 => rfl
+
+private theorem parseSaved_steps (a : Fin 5 → Word w) : (parseSaved a).2 ≤ 12 := by
+ dsimp only [parseSaved]
+ split_ifs <;> dsimp <;> decide
+
+/-- Check canonical fields from the highest remaining register downwards. A failed word
+comparison exits immediately. Charge the loop test, decrement, two loads, equality and
+branch on each iteration, and one test for an empty prefix. -/
+private def checkPrefix (a b : Fin 5 → Word w) : (k : ℕ) → k ≤ 5 → Bool × ℕ
+ | 0, _ => (true, 1)
+ | k + 1, hk =>
+ if a ⟨k, hk⟩ = b ⟨k, hk⟩ then
+ let r := checkPrefix a b k (by omega)
+ (r.1, 6 + r.2)
+ else (false, 6)
+
+private theorem checkPrefix_spec (a b : Fin 5 → Word w) (k : ℕ) (hk : k ≤ 5) :
+ (checkPrefix a b k hk).1 = true ↔ ∀ i : Fin 5, i.val < k → a i = b i := by
+ induction k with
+ | zero => simp [checkPrefix]
+ | succ k ih =>
+ rw [checkPrefix]
+ split
+ · rename_i he
+ rw [ih]
+ constructor
+ · intro hall i hi
+ rcases Nat.lt_or_eq_of_le (Nat.le_of_lt_succ hi) with h | h
+ · exact hall i h
+ · exact (Fin.ext h : i = ⟨k, hk⟩) ▸ he
+ · exact fun hall i hi ↦ hall i (Nat.lt_succ_of_lt hi)
+ · rename_i hne
+ simp only [Bool.false_eq_true, false_iff]
+ exact fun hall ↦ hne (hall ⟨k, hk⟩ (Nat.lt_succ_self k))
+
+private theorem checkPrefix_steps (a b : Fin 5 → Word w) (k : ℕ) (hk : k ≤ 5) :
+ (checkPrefix a b k hk).2 ≤ 6 * k + 1 := by
+ induction k with
+ | zero => rfl
+ | succ k ih =>
+ rw [checkPrefix]
+ split <;> dsimp
+ · have := ih (by omega)
+ omega
+ · omega
+
+/-- The `5*w` physical bits split into five successive word streams. -/
+private def readField (b : Fin (5 * w) → Bool) (i : Fin 5) : Word w × ℕ :=
+ scanWord (fun j ↦ b (finProdFinEquiv (i, j)))
+
+private theorem readField_eq (b : Fin (5 * w) → Bool) (i : Fin 5) :
+ (readField b i).1 = (arrayBits 5 w).symm b i := by
+ rw [readField, scanWord_eq]
+ apply (wordBits w).injective
+ funext j
+ rw [Equiv.apply_symm_apply]
+ rw [← arrayBits_at, Equiv.apply_symm_apply]
+
+/-- Scan the five words into registers and run the tag and canonical-field checks.
+In addition to their measured costs, charge five register writes, ten operations for
+dispatch and writing the five canonical words, and two for the final branch and return.
+`some none` is the canonical empty record, and `none` rejects. -/
+def decodeSlot (hw : 2 ≤ w) (b : Fin (5 * w) → Bool) : Option (Option (WordRecord w)) × ℕ :=
+ let f₀ := readField b 0
+ let f₁ := readField b 1
+ let f₂ := readField b 2
+ let f₃ := readField b 3
+ let f₄ := readField b 4
+ let a := ![f₀.1, f₁.1, f₂.1, f₃.1, f₄.1]
+ let parsed := parseSaved a
+ let check := checkPrefix ((recordFormat hw).words parsed.1) a 5 le_rfl
+ (if check.1 then some parsed.1 else none,
+ f₀.2 + f₁.2 + f₂.2 + f₃.2 + f₄.2 + 5 + parsed.2 + 10 + check.2 + 2)
+
+/-- The bounded decoder and the message format agree for every input bit string. -/
+theorem decodeSlot_eq (hw : 2 ≤ w) (b : Fin (5 * w) → Bool) :
+ (decodeSlot hw b).1 = (recordFormat hw).decode b := by
+ let a := (arrayBits 5 w).symm b
+ have hv : ![(readField b 0).1, (readField b 1).1, (readField b 2).1, (readField b 3).1,
+ (readField b 4).1] = a := by
+ funext i
+ fin_cases i <;> apply readField_eq
+ have hcheck (u v : Fin 5 → Word w) : (checkPrefix u v 5 le_rfl).1 = true ↔ u = v := by
+ rw [checkPrefix_spec]
+ exact ⟨fun h ↦ funext (fun i ↦ h i i.isLt), fun h _ _ ↦ congrFun h _⟩
+ simp only [decodeSlot, hv, Format.decode, hcheck, parseSaved_eq hw, Format.encode]
+ have hc (x : Fin 5 → Word w) : arrayBits 5 w x = b ↔ x = a :=
+ (arrayBits 5 w).eq_symm_apply.symm
+ simp only [hc]
+ rfl
+
+theorem decodeSlot_cost (hw : 2 ≤ w) (b : Fin (5 * w) → Bool) :
+ (decodeSlot hw b).2 ≤ 64 * (w + 1) := by
+ simp only [decodeSlot, readField, scanWord_steps]
+ have hp := parseSaved_steps (w := w)
+ have hc (a b : Fin 5 → Word w) := checkPrefix_steps a b 5 le_rfl
+ grw [hp, hc]
+ omega
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortFieldEquiv.lean b/lean/OAI/Computability/VPVNP/RAMSortFieldEquiv.lean
new file mode 100644
index 0000000000..1f597a3db9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortFieldEquiv.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.RAMSortFieldIndex
+
+/-!
+# Identifying distributed sort transcripts with physical send fields
+
+The chronological list of layer checks uses a dependent product of field
+assignments. This product indexes exactly the sorting send fields allocated
+by the physical layout, once at each cross-site layer and site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+variable {h d : ℕ} {α : Type*}
+
+private def bundle : (ss : List (Stage (h+d))) →
+ (∀ s ∈ ss, Sends h d s α) → Fields h d α ss
+ | [], _ => PUnit.unit
+ | s :: ss, f => (f s (List.mem_cons_self ..),
+ bundle ss (fun t ht ↦ f t (List.mem_cons_of_mem _ ht)))
+
+private def lookup : (ss : List (Stage (h+d))) → Fields h d α ss →
+ (∀ s ∈ ss, Sends h d s α)
+ | [], _, _, hmem => False.elim (List.not_mem_nil hmem)
+ | s :: ss, fields, t, ht =>
+ if he : s = t then he ▸ fields.1
+ else lookup ss fields.2 t ((List.mem_cons.mp ht).resolve_left (Ne.symm he))
+
+private theorem lookup_bundle (ss : List (Stage (h+d)))
+ (f : ∀ s ∈ ss, Sends h d s α) : lookup ss (bundle ss f) = f := by
+ induction ss with
+ | nil => funext s hs; exact False.elim (List.not_mem_nil hs)
+ | cons s ss ih =>
+ funext t ht
+ by_cases he : s = t
+ · subst t; simp [lookup, bundle]
+ · simp only [lookup, bundle, dite_eq_right he]
+ rw [ih]
+
+private theorem bundle_lookup (ss : List (Stage (h+d))) (hn : ss.Nodup)
+ (fields : Fields h d α ss) : bundle ss (lookup ss fields) = fields := by
+ induction ss with
+ | nil => cases fields; rfl
+ | cons s ss ih =>
+ have hs := List.nodup_cons.mp hn
+ rcases fields with ⟨f, fs⟩
+ apply Prod.ext
+ · simp [bundle, lookup]
+ · change bundle ss (fun t ht ↦ lookup (s :: ss) (f, fs) t _) = fs
+ have he : (fun t ht ↦ lookup (s :: ss) (f, fs) t (List.mem_cons_of_mem s ht)) =
+ lookup ss fs := by
+ funext t ht
+ have hne : s ≠ t := fun e ↦ hs.1 (e ▸ ht)
+ simp [lookup, hne]
+ rw [he, ih hs.2]
+
+/-- A duplicate-free schedule stores its indexed fields once each. -/
+def fieldsOfStages (ss : List (Stage (h+d))) (hn : ss.Nodup) :
+ (∀ s ∈ ss, Sends h d s α) ≃ Fields h d α ss where
+ toFun := bundle ss
+ invFun := lookup ss
+ left_inv := lookup_bundle ss
+ right_inv := bundle_lookup ss hn
+
+/-- Reindex the sorting fields by their physical layer and source site. -/
+private def physicalIndex (h d : ℕ) (α : Type*) :
+ (RAMLayout.Layer d → Fin (2 ^ d) → Wires h α) ≃ (∀ s : Stage (h+d), Sends h d s α) where
+ toFun fields s hc := fields ((crossStageEquiv h d).symm ⟨s, hc⟩)
+ invFun fields l := fields ((crossStageEquiv h d) l).val ((crossStageEquiv h d) l).property
+ left_inv fields := by funext l; simp
+ right_inv fields := by
+ funext s hc
+ exact congrArg (fun z : {s : Stage (h+d) // h ≤ s.stride} ↦ fields z.val z.property)
+ ((crossStageEquiv h d).apply_symm_apply ⟨s, hc⟩)
+
+private def restrictIndex (ss : List (Stage (h+d))) (hall : ∀ s, s ∈ ss) :
+ (∀ s : Stage (h+d), Sends h d s α) ≃ (∀ s ∈ ss, Sends h d s α) where
+ toFun f s _ := f s
+ invFun f s := f s (hall s)
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+/-- Bijection with the send blocks allocated in the paper's equation (10.1). -/
+def physicalFieldsEquiv (h d : ℕ) (α : Type*) :
+ (RAMLayout.Layer d → Fin (2 ^ d) → Wires h α) ≃
+ Fields h d α (phases (h+d) (h+d) le_rfl) :=
+ (physicalIndex h d α).trans ((restrictIndex _ mem_fullPhases).trans
+ (fieldsOfStages _ (phases_nodup le_rfl)))
+
+/-- Every physical sorting send slot is constrained by the local validator.
+For any initial record array exactly one physical send assignment passes. -/
+theorem existsUnique_physicalFields [LinearOrder α] (h d : ℕ) (x : ℕ → α) :
+ ∃! send : RAMLayout.Layer d → Fin (2 ^ d) → Wires h α, ∀ v,
+ checks v _ (physicalFieldsEquiv h d α send) (block h v.val x) := by
+ let e := physicalFieldsEquiv h d α
+ let ss := phases (h+d) (h+d) le_rfl
+ refine ⟨e.symm (actual ss x), ?_, ?_⟩
+ · change ∀ v, checks v ss (e (e.symm (actual ss x))) (block h v.val x)
+ rw [e.apply_symm_apply]
+ exact checks_actual ss x
+ · intro send hc
+ apply e.injective
+ rw [e.apply_symm_apply]
+ exact fields_eq_actual ss _ x hc
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortFieldIndex.lean b/lean/OAI/Computability/VPVNP/RAMSortFieldIndex.lean
new file mode 100644
index 0000000000..9823656b7b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortFieldIndex.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.RAMSortReplay
+import OAI.Computability.VPVNP.RAMLayout
+
+/-!
+# Sorting stages and the physical exchange fields
+
+In Lemma 10.1 of *VP and VNP differ over every field*, the stride exponent
+determines whether a comparison needs an exchange. Every such stage has its
+own field at each site, and its addressed record partner is precisely the
+site partner designated by that field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+/-- The physical fields index exactly the stages with stride at least the
+site block width. Physical steps increase as the stride decreases. -/
+def crossStageEquiv (h d : ℕ) : RAMLayout.Layer d ≃ {s : Stage (h + d) // h ≤ s.stride} where
+ toFun s :=
+ ⟨⟨h + s.phase + 1, h + s.siteBit, by
+ unfold RAMLayout.Layer.siteBit
+ omega, by have := s.phase_lt; omega⟩, Nat.le_add_right ..⟩
+ invFun s :=
+ ⟨s.val.phase - h - 1, s.val.phase - s.val.stride - 1,
+ by have := s.val.phase_le; have := s.val.stride_lt; have := s.property; omega,
+ by have := s.val.stride_lt; have := s.property; omega⟩
+ left_inv s := by
+ apply RAMLayout.Layer.ext
+ · dsimp
+ omega
+ · dsimp [RAMLayout.Layer.siteBit]
+ have := s.step_le
+ omega
+ right_inv s := by
+ rcases s with ⟨⟨a, j, hja, hab⟩, hj⟩
+ change h ≤ j at hj
+ apply Subtype.ext
+ apply Stage.ext <;> dsimp [RAMLayout.Layer.siteBit] <;> omega
+
+/-- The record address in a nonlocal comparator, decoded from its field,
+has the same offset at the designated peer site. -/
+theorem crossStage_partner {h d : ℕ} (s : {s : Stage (h + d) // h ≤ s.stride})
+ (v : Fin (2 ^ d)) (i : Fin (2 ^ h)) :
+ partner s.val.stride (v.val * 2 ^ h + i.val) =
+ (((crossStageEquiv h d).symm s).partner v).val * 2 ^ h + i.val := by
+ obtain ⟨l, rfl⟩ := (crossStageEquiv h d).surjective s
+ simp only [Equiv.symm_apply_apply]
+ exact l.record_partner v i
+
+/-- The sender read during local replay is the peer specified by the physical field. -/
+theorem sourceSite_eq_physical {h d : ℕ} (s : Stage (h + d)) (hc : h ≤ s.stride)
+ (v : Fin (2 ^ d)) :
+ sourceSite s hc v = ((crossStageEquiv h d).symm ⟨s, hc⟩).partner v := by
+ have hs := (crossStageEquiv h d).apply_symm_apply ⟨s, hc⟩
+ have hj := congrArg (fun t ↦ t.val.stride) hs
+ let l := (crossStageEquiv h d).symm ⟨s, hc⟩
+ change h + l.siteBit = s.stride at hj
+ apply Fin.ext
+ change partner (s.stride - h) v.val = partner l.siteBit v.val
+ rw [← hj, Nat.add_sub_cancel_left]
+
+@[simp] theorem mem_strides {b a k : ℕ} (ha : a ≤ b) (hk : k ≤ a) (s : Stage b) :
+ s ∈ strides b a ha k hk ↔ s.phase = a ∧ s.stride < k := by
+ induction k with
+ | zero => simp [strides]
+ | succ k ih =>
+ rw [strides, List.mem_cons, ih]
+ constructor
+ · rintro (rfl | ⟨hphase, hstride⟩)
+ · exact ⟨rfl, Nat.lt_succ_self k⟩
+ · exact ⟨hphase, Nat.lt_succ_of_lt hstride⟩
+ · rintro ⟨hphase, hstride⟩
+ by_cases h : s.stride = k
+ · exact Or.inl (Stage.ext hphase h)
+ · exact Or.inr ⟨hphase, by omega⟩
+
+@[simp] theorem mem_phases {b a : ℕ} (ha : a ≤ b) (s : Stage b) :
+ s ∈ phases b a ha ↔ s.phase ≤ a := by
+ induction a with
+ | zero => simp [phases]; have := s.stride_lt; omega
+ | succ a ih =>
+ rw [phases, List.mem_append, ih, mem_strides]
+ have := s.stride_lt
+ omega
+
+theorem strides_nodup {b a k : ℕ} (ha : a ≤ b) (hk : k ≤ a) :
+ (strides b a ha k hk).Nodup := by
+ induction k with
+ | zero => simp [strides]
+ | succ k ih =>
+ rw [strides, List.nodup_cons]
+ exact ⟨by simp, ih _⟩
+
+/-- Phases one through `a` visit each of their stages exactly once. -/
+theorem phases_nodup {b a : ℕ} (ha : a ≤ b) : (phases b a ha).Nodup := by
+ induction a with
+ | zero => simp [phases]
+ | succ a ih =>
+ rw [phases, List.nodup_append]
+ refine ⟨ih _, strides_nodup _ _, ?_⟩
+ intro s hs t ht he
+ subst t
+ have hprev := (mem_phases _ s).mp hs
+ have hnext := ((mem_strides _ _ s).mp ht).1
+ omega
+
+/-- The full physical schedule includes every allowed `(phase, stride)`. -/
+theorem mem_fullPhases {b : ℕ} (s : Stage b) : s ∈ phases b b le_rfl :=
+ (mem_phases _ _).mpr s.phase_le
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortIncident.lean b/lean/OAI/Computability/VPVNP/RAMSortIncident.lean
new file mode 100644
index 0000000000..d9607c199a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortIncident.lean
@@ -0,0 +1,49 @@
+import OAI.Computability.VPVNP.RAMSharedFields
+import OAI.Computability.VPVNP.RAMSortCostLayout
+import OAI.Computability.VPVNP.RAMBitTranscript
+
+/-!
+# Linear addressing of a site's incident fields
+
+The word validator sees a contiguous bit array. Restricting the sender
+arrays to a site uses the physical port offsets, including clamped ports.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+/-- Extend the finite local bit array by zero at unused addresses. -/
+def readIncident {n : ℕ} (inc : Fin n → Bool) (a : ℕ) : Bool :=
+ if h : a < n then inc ⟨a, h⟩ else false
+
+@[simp] theorem readIncident_at {n : ℕ} (inc : Fin n → Bool) (i : Fin n) :
+ readIncident inc i.val = inc i := by simp [readIncident, i.isLt]
+
+end RAMSort
+
+namespace BurstRAM
+
+open RAMLayout RAMSort
+
+variable {d e w : ℕ}
+
+/-- Read the bit at a site’s linear incident address from its shared sender arrays, returning
+false beyond the incident layout. -/
+def sortIncident (b : SendArrays d (2^e) w) (v : Fin (2^d)) (a : ℕ) : Bool :=
+ readIncident (fun j ↦ (incidentEquiv d (2^e) w b).val (v, (offset d (2^e) w).symm j)) a
+
+@[simp] theorem sortIncident_offset (b : SendArrays d (2^e) w) (v : Fin (2^d))
+ (slot : RAMLayout.Slot d (2^e) w) :
+ sortIncident b v (offset d (2^e) w slot).val = (incidentEquiv d (2^e) w b).val (v, slot) := by
+ simp [sortIncident]
+
+theorem record_width (e : ℕ) : 2^(2+e) = 4*2^e := by rw [Nat.pow_add]
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortLayers.lean b/lean/OAI/Computability/VPVNP/RAMSortLayers.lean
new file mode 100644
index 0000000000..e1d29b1466
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortLayers.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.RAMSortNetwork
+import OAI.Computability.VPVNP.RAMSortRouting
+
+/-!
+# Addressed layers of the bitonic sorting network
+
+Lemma 10.1 uses one XOR mask at every site of a layer. The layer definitions
+below act on records indexed by natural numbers. Their restrictions to aligned
+finite blocks agree with the recursive bitonic network. In particular the
+result at each index of a finite array is independent of all records outside it.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+variable {α : Type*}
+
+/-- Read an aligned block of `2^k` records from the global array. -/
+def block (k site : ℕ) (x : ℕ → α) : Wires k α := fun i ↦ x (site * 2 ^ k + i)
+
+private theorem leftBase (k site : ℕ) : (2 * site) * 2 ^ k = site * 2 ^ (k + 1) := by
+ rw [Nat.pow_succ]
+ ac_rfl
+
+private theorem rightBase (k site : ℕ) :
+ (2 * site + 1) * 2 ^ k = site * 2 ^ (k + 1) + 2 ^ k := by
+ rw [Nat.add_mul, Nat.one_mul, leftBase]
+
+@[simp] theorem lo_block (k site : ℕ) (x : ℕ → α) :
+ lo (block (k + 1) site x) = block k (2 * site) x := by
+ funext i
+ simp [lo, block, leftBase]
+
+@[simp] theorem hi_block (k site : ℕ) (x : ℕ → α) :
+ hi (block (k + 1) site x) = block k (2 * site + 1) x := by
+ funext i
+ simp only [hi, block, rightBase]
+ congr 1
+ omega
+
+variable [LinearOrder α]
+
+/-- A layer with stride `2^j`. The direction function is shared by the
+positions of each block being merged. -/
+def comparatorLayer (j : ℕ) (direction : ℕ → Bool) (x : ℕ → α) (i : ℕ) : α :=
+ let p := partner j i
+ if i < p then lower (direction i) (x i) (x p) else upper (direction i) (x p) (x i)
+
+/-- Strides in a phase are applied from `2^(k-1)` down to one. -/
+def runStrides : ℕ → (ℕ → Bool) → (ℕ → α) → (ℕ → α)
+ | 0, _, x => x
+ | k + 1, direction, x => runStrides k direction (comparatorLayer k direction x)
+
+private theorem stride_left (k site : ℕ) (direction : ℕ → Bool) (x : ℕ → α)
+ (up : Bool) (hd : ∀ i < 2 ^ (k + 1), direction (site * 2 ^ (k + 1) + i) = up) :
+ block k (2 * site) (comparatorLayer k direction x) =
+ fun i ↦ lower up (lo (block (k + 1) site x) i) (hi (block (k + 1) site x) i) := by
+ funext i
+ have hpow : 2 ^ (k + 1) = 2 ^ k + 2 ^ k := by rw [Nat.pow_succ, Nat.mul_two]
+ have hpos : i.val < 2 ^ (k + 1) := by rw [hpow]; omega
+ simp only [block, lo, hi, leftBase, comparatorLayer]
+ rw [partner_local site hpos (Nat.lt_succ_self k), partner_lo i.isLt, hd i hpos]
+ rw [ite_eq_left (by have := Nat.two_pow_pos k; omega)]
+
+private theorem stride_right (k site : ℕ) (direction : ℕ → Bool) (x : ℕ → α)
+ (up : Bool) (hd : ∀ i < 2 ^ (k + 1), direction (site * 2 ^ (k + 1) + i) = up) :
+ block k (2 * site + 1) (comparatorLayer k direction x) =
+ fun i ↦ upper up (lo (block (k + 1) site x) i) (hi (block (k + 1) site x) i) := by
+ funext i
+ have hpow : 2 ^ (k + 1) = 2 ^ k + 2 ^ k := by rw [Nat.pow_succ, Nat.mul_two]
+ have hpos : i.val + 2 ^ k < 2 ^ (k + 1) := by rw [hpow]; omega
+ simp only [block, lo, hi, rightBase, comparatorLayer]
+ rw [show site * 2 ^ (k + 1) + 2 ^ k + i.val = site * 2 ^ (k + 1) + (i.val + 2 ^ k) by omega,
+ partner_local site hpos (Nat.lt_succ_self k), partner_hi i.isLt, hd _ hpos,
+ ite_eq_right (by omega)]
+
+/-- A phase of addressed layers acts on every aligned block exactly as
+`merge`, when that block has the indicated common direction. -/
+theorem block_runStrides (k site : ℕ) (direction : ℕ → Bool) (x : ℕ → α) (up : Bool)
+ (hd : ∀ i < 2 ^ k, direction (site * 2 ^ k + i) = up) :
+ block k site (runStrides k direction x) = merge k up (block k site x) := by
+ induction k generalizing site x with
+ | zero => rfl
+ | succ k ih =>
+ have hpow : 2 ^ (k + 1) = 2 ^ k + 2 ^ k := by rw [Nat.pow_succ, Nat.mul_two]
+ apply eq_of_halves
+ · simp only [runStrides, lo_block, merge, lo_join]
+ rw [ih, stride_left k site direction x up hd]
+ · simp only [lo_block]
+ intro i hi
+ rw [leftBase]
+ apply hd
+ omega
+ · simp only [runStrides, hi_block, merge, hi_join]
+ rw [ih, stride_right k site direction x up hd]
+ · simp only [hi_block]
+ intro i hi
+ rw [rightBase, Nat.add_assoc]
+ apply hd
+ omega
+
+/-- Even-numbered blocks in phase `a` are ascending. -/
+def phaseDirection (a i : ℕ) : Bool := decide ((i / 2 ^ a) % 2 = 0)
+
+@[simp] theorem phaseDirection_block (a site : ℕ) {i : ℕ} (hi : i < 2 ^ a) :
+ phaseDirection a (site * 2 ^ a + i) = decide (site % 2 = 0) := by
+ simp [phaseDirection, Nat.mul_comm site, Nat.mul_add_div (Nat.two_pow_pos a), Nat.div_eq_of_lt hi]
+
+/-- Execute phases one through `a`, choosing the comparator directions
+from the global block numbers. -/
+def runPhases : ℕ → (ℕ → α) → (ℕ → α)
+ | 0, x => x
+ | a + 1, x => runStrides (a + 1) (phaseDirection (a + 1)) (runPhases a x)
+
+/-- Every phase produces a recursively sorted block, ascending for even
+block numbers and descending for odd ones. -/
+theorem block_runPhases (a site : ℕ) (x : ℕ → α) :
+ block a site (runPhases a x) = sort a (decide (site % 2 = 0)) (block a site x) := by
+ induction a generalizing site with
+ | zero => rfl
+ | succ a ih =>
+ rw [runPhases, block_runStrides _ _ _ _ _ (fun _ h ↦ phaseDirection_block _ _ h), sort]
+ congr 1
+ apply eq_of_halves <;> simp [ih]
+
+/-- Run the network on a specified array width, with the requested direction
+for its final merge. Earlier phases use their ordinary alternating directions. -/
+def runSort : ℕ → Bool → (ℕ → α) → (ℕ → α)
+ | 0, _, x => x
+ | a + 1, up, x => runStrides (a + 1) (fun _ ↦ up) (runPhases a x)
+
+/-- Restricting the globally addressed execution to the first finite block
+recovers Batcher's network in either requested direction. -/
+theorem block_runSort (a : ℕ) (up : Bool) (x : ℕ → α) :
+ block a 0 (runSort a up x) = sort a up (block a 0 x) := by
+ cases a with
+ | zero => rfl
+ | succ a =>
+ rw [runSort, block_runStrides _ _ _ _ _ (fun _ _ ↦ rfl), sort]
+ congr 1
+ apply eq_of_halves <;> simp [block_runPhases]
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortNetwork.lean b/lean/OAI/Computability/VPVNP/RAMSortNetwork.lean
new file mode 100644
index 0000000000..6f44f3dc06
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortNetwork.lean
@@ -0,0 +1,114 @@
+import Mathlib.Data.Fin.Tuple.Basic
+import Mathlib.Order.MinMax
+
+/-!
+# Batcher's bitonic sorting network
+
+Lemma 10.1 of *VP and VNP differ over every field* sorts records by phases.
+A phase on a block of size `2^(b+1)` compares its two halves at stride
+`2^b`, then continues the merge in parallel in the two halves. The phase
+begins with an ascending left half and a descending right half.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+/-- A contiguous block of records in the network. -/
+abbrev Wires (b : ℕ) (α : Type*) := Fin (2 ^ b) → α
+
+private theorem double_width (b : ℕ) : 2 ^ (b + 1) = 2 ^ b + 2 ^ b := by
+ rw [Nat.pow_succ, Nat.mul_two]
+
+/-- Read the first half of a block. -/
+def lo {b : ℕ} {α : Type*} (x : Wires (b + 1) α) (i : Fin (2 ^ b)) : α :=
+ x ⟨i, by rw [double_width]; omega⟩
+
+/-- Read the second half of a block. -/
+def hi {b : ℕ} {α : Type*} (x : Wires (b + 1) α) (i : Fin (2 ^ b)) : α :=
+ x ⟨i + 2 ^ b, by rw [double_width]; omega⟩
+
+/-- Write the two halves of a block. -/
+def join {b : ℕ} {α : Type*} (x y : Wires b α) (i : Fin (2 ^ (b + 1))) : α :=
+ if h : (i : ℕ) < 2 ^ b then x ⟨i, h⟩
+ else y ⟨i - 2 ^ b, by have := double_width b; have := i.isLt; omega⟩
+
+@[simp] theorem lo_join {b : ℕ} {α : Type*} (x y : Wires b α) :
+ lo (join x y) = x := by funext i; simp [lo, join, i.isLt]
+
+@[simp] theorem hi_join {b : ℕ} {α : Type*} (x y : Wires b α) :
+ hi (join x y) = y := by funext i; simp [hi, join]
+
+@[simp] theorem join_lo_hi {b : ℕ} {α : Type*} (x : Wires (b + 1) α) :
+ join (lo x) (hi x) = x := by
+ funext i
+ simp only [join, lo, hi]
+ split <;> congr 1
+ apply Fin.ext
+ change i.val - 2 ^ b + 2 ^ b = i.val
+ omega
+
+/-- Equality of blocks can be checked separately on each half. -/
+theorem eq_of_halves {b : ℕ} {α : Type*} {x y : Wires (b + 1) α}
+ (h₀ : lo x = lo y) (h₁ : hi x = hi y) : x = y := by
+ rw [← join_lo_hi x, ← join_lo_hi y, h₀, h₁]
+
+variable {α : Type*} [LinearOrder α]
+
+/-- Value written at the smaller index of a comparator. -/
+def lower (up : Bool) (x y : α) : α := if up then min x y else max x y
+
+/-- Value written at the larger index of a comparator. -/
+def upper (up : Bool) (x y : α) : α := if up then max x y else min x y
+
+/-- One merge phase. The two recursive calls are parallel disjoint blocks. -/
+def merge : (b : ℕ) → Bool → Wires b α → Wires b α
+ | 0, _, x => x
+ | b + 1, up, x =>
+ join (merge b up (fun i ↦ lower up (lo x i) (hi x i)))
+ (merge b up (fun i ↦ upper up (lo x i) (hi x i)))
+
+/-- Sort a block, with ascending order requested by `true`. -/
+def sort : (b : ℕ) → Bool → Wires b α → Wires b α
+ | 0, _, x => x
+ | b + 1, up, x => merge (b + 1) up (join (sort b true (lo x)) (sort b false (hi x)))
+
+section Map
+
+variable {β : Type*} [LinearOrder β]
+
+omit [LinearOrder α] [LinearOrder β] in
+private theorem map_join {b : ℕ} (f : α → β) (x y : Wires b α) :
+ f ∘ join x y = join (f ∘ x) (f ∘ y) := by
+ funext i
+ simp only [Function.comp_apply, join]
+ split <;> rfl
+
+/-- Thresholding commutes with every comparator, and hence with a full merge. -/
+theorem merge_map (f : α → β) (hf : Monotone f) (b : ℕ) (up : Bool) (x : Wires b α) :
+ f ∘ merge b up x = merge b up (f ∘ x) := by
+ induction b generalizing up with
+ | zero => rfl
+ | succ b ih =>
+ simp only [merge, map_join, ih]
+ congr 1 <;> congr 1 <;> funext i <;>
+ cases up <;> simp [lower, upper, lo, hi, hf.map_min, hf.map_max]
+
+/-- A monotone map can be pushed from the output to the input of the network. -/
+theorem sort_map (f : α → β) (hf : Monotone f) (b : ℕ) (up : Bool) (x : Wires b α) :
+ f ∘ sort b up x = sort b up (f ∘ x) := by
+ induction b generalizing up with
+ | zero => rfl
+ | succ b ih =>
+ simp only [sort, merge_map f hf, map_join, ih]
+ rfl
+
+end Map
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortPerm.lean b/lean/OAI/Computability/VPVNP/RAMSortPerm.lean
new file mode 100644
index 0000000000..2c9c8a0117
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortPerm.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.RAMSortNetwork
+import Mathlib.Data.List.OfFn
+
+/-!
+# Record multiplicities in the bitonic network
+
+Each comparator outputs its two inputs in one of the two orders. Consequently the
+list of records in a whole block is permuted by the network, including repeated records.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+variable {α : Type*}
+
+/-- In wire order, joining two contiguous blocks concatenates their record lists. -/
+theorem ofFn_join {b : ℕ} (x y : Wires b α) :
+ List.ofFn (join x y) = List.ofFn x ++ List.ofFn y := by
+ apply List.ext_getElem
+ · rw [List.length_append, List.length_ofFn, List.length_ofFn, List.length_ofFn,
+ Nat.pow_succ, Nat.mul_two]
+ intro i hi hj
+ rw [List.getElem_append]
+ simp [List.getElem_ofFn, join]
+
+private theorem ofFn_halves {b : ℕ} (x : Wires (b + 1) α) :
+ List.ofFn (lo x) ++ List.ofFn (hi x) = List.ofFn x := by
+ rw [← ofFn_join, join_lo_hi]
+
+variable [LinearOrder α]
+
+/-- A single parallel comparison layer preserves all input records. -/
+theorem compare_perm {n : ℕ} (up : Bool) (x y : Fin n → α) :
+ (List.ofFn (fun i ↦ lower up (x i) (y i)) ++ List.ofFn (fun i ↦ upper up (x i) (y i))).Perm
+ (List.ofFn x ++ List.ofFn y) := by
+ apply List.perm_iff_count.mpr
+ intro a
+ induction n with
+ | zero => simp
+ | succ n ih =>
+ specialize ih (fun i ↦ x i.succ) (fun i ↦ y i.succ)
+ simp only [List.count_append] at ih
+ simp only [List.count_append, List.ofFn_succ, List.count_cons]
+ let wt (z : α) : ℕ := if z == a then 1 else 0
+ have heads : wt (lower up (x 0) (y 0)) + wt (upper up (x 0) (y 0)) = wt (x 0) + wt (y 0) := by
+ rcases le_total (x 0) (y 0) with h | h
+ · cases up <;> simp [lower, upper, min_eq_left h, max_eq_right h, Nat.add_comm]
+ · cases up <;> simp [lower, upper, min_eq_right h, max_eq_left h, Nat.add_comm]
+ dsimp [wt] at heads
+ omega
+
+/-- A merge phase preserves the multiset of records of the input block. -/
+theorem merge_perm (b : ℕ) (up : Bool) (x : Wires b α) :
+ (List.ofFn (merge b up x)).Perm (List.ofFn x) := by
+ induction b with
+ | zero => exact List.Perm.refl _
+ | succ b ih =>
+ rw [merge, ofFn_join, ← ofFn_halves x]
+ exact ((ih _).append (ih _)).trans (compare_perm up (lo x) (hi x))
+
+/-- The full network preserves every record and its multiplicity. -/
+theorem sort_perm (b : ℕ) (up : Bool) (x : Wires b α) :
+ (List.ofFn (sort b up x)).Perm (List.ofFn x) := by
+ induction b generalizing up with
+ | zero => exact List.Perm.refl _
+ | succ b ih =>
+ rw [sort]
+ refine (merge_perm _ _ _).trans ?_
+ rw [ofFn_join, ← ofFn_halves x]
+ exact (ih true _).append (ih false _)
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortPulse.lean b/lean/OAI/Computability/VPVNP/RAMSortPulse.lean
new file mode 100644
index 0000000000..1e086f4df7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortPulse.lean
@@ -0,0 +1,82 @@
+import Mathlib.Data.Nat.Basic
+
+/-!
+# Boolean bitonic sequences
+
+A cyclic block of consecutive ones describes the thresholded input to a
+bitonic merge. Comparing opposite positions splits the block into two
+shorter blocks, independently of its starting position.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+/-- A periodic sequence whose first `ones` positions after shifting are true. -/
+def pulse (width shift ones i : ℕ) : Bool := decide ((i + shift) % width < ones)
+
+private theorem opposite_residues (x : ℕ) {n : ℕ} (hn : 0 < n) :
+ (x % (2 * n) = x % n ∧ (x + n) % (2 * n) = x % n + n) ∨
+ (x % (2 * n) = x % n + n ∧ (x + n) % (2 * n) = x % n) := by
+ let r := x % (2 * n)
+ have hr : r < 2 * n := Nat.mod_lt _ (by omega)
+ have hsmall : r % n = x % n := Nat.mod_mod_of_dvd _ ⟨2, Nat.mul_comm ..⟩
+ have hopp : (r + n) % (2 * n) = (x + n) % (2 * n) := Nat.mod_add_mod ..
+ change (r = _ ∧ _) ∨ (r = _ ∧ _)
+ rw [← hsmall, ← hopp]
+ by_cases h : r < n
+ · left
+ rw [Nat.mod_eq_of_lt h, Nat.mod_eq_of_lt (show r + n < 2 * n by omega)]
+ exact ⟨rfl, rfl⟩
+ · right
+ have h₁ : r % n = r - n := by
+ rw [Nat.mod_eq_sub_mod (by omega), Nat.mod_eq_of_lt (by omega)]
+ have h₂ : (r + n) % (2 * n) = r - n := by
+ rw [Nat.mod_eq_sub_mod (by omega), Nat.mod_eq_of_lt (by omega)]
+ omega
+ rw [h₁, h₂]
+ omega
+
+/-- The smaller Boolean output at each opposite pair is a pulse with the
+excess over half the original width. -/
+theorem pulse_and {n : ℕ} (hn : 0 < n) (shift ones i : ℕ) :
+ (pulse (2 * n) shift ones i && pulse (2 * n) shift ones (i + n)) =
+ pulse n shift (ones - n) i := by
+ simp only [pulse, ← Bool.decide_and, decide_eq_decide]
+ rw [show i + n + shift = i + shift + n by omega]
+ rcases opposite_residues (i + shift) hn with ⟨h₁, h₂⟩ | ⟨h₁, h₂⟩ <;>
+ rw [h₁, h₂] <;> omega
+
+/-- The larger Boolean output at each opposite pair is a pulse capped at
+half the original width. -/
+theorem pulse_or {n : ℕ} (hn : 0 < n) (shift ones i : ℕ) :
+ (pulse (2 * n) shift ones i || pulse (2 * n) shift ones (i + n)) =
+ pulse n shift (min ones n) i := by
+ simp only [pulse, ← Bool.decide_or, decide_eq_decide]
+ rw [show i + n + shift = i + shift + n by omega]
+ have hlt := Nat.mod_lt (i + shift) hn
+ rcases opposite_residues (i + shift) hn with ⟨h₁, h₂⟩ | ⟨h₁, h₂⟩ <;>
+ rw [h₁, h₂] <;> omega
+
+/-- A rising segment at cut `a` followed by a falling segment at cut `b`
+forms one cyclic pulse of length `n - a + b`. -/
+theorem pulse_of_segments {n a b i : ℕ} (ha : a ≤ n) (hb : b ≤ n) (hi : i < 2 * n) :
+ pulse (2 * n) (2 * n - a) (n - a + b) i =
+ if i < n then decide (a ≤ i) else decide (i - n < b) := by
+ unfold pulse
+ by_cases h : i < a
+ · rw [ite_eq_left (show i < n by omega), Nat.mod_eq_of_lt (by omega), decide_eq_decide]
+ omega
+ · have hm : (i + (2 * n - a)) % (2 * n) = i - a := by
+ rw [Nat.mod_eq_sub_mod (by omega), Nat.mod_eq_of_lt (by omega)]
+ omega
+ rw [hm]
+ split <;> rw [decide_eq_decide] <;> omega
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortReplay.lean b/lean/OAI/Computability/VPVNP/RAMSortReplay.lean
new file mode 100644
index 0000000000..6a478f0e97
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortReplay.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.RAMSortLayers
+
+/-!
+# Local replay of the distributed sorting layers
+
+A site keeps its current records and reads the matching site's send field
+only at a cross-site stride. The local check at every such layer compares
+its outgoing field with its own pre-comparison block. For a fixed input all
+send fields are uniquely determined by these checks, and the final records
+at each site agree with the globally addressed bitonic network.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+/-- One comparator layer in an array with `2^b` positions. -/
+@[ext] structure Stage (b : ℕ) where
+ /-- Bitonic merge phase exponent, whose bit in the global wire index selects the comparison
+ direction. -/
+ phase : ℕ
+ /-- Bit position toggled in the wire index to find its comparator partner in this layer. -/
+ stride : ℕ
+ stride_lt : stride < phase
+ phase_le : phase ≤ b
+ deriving DecidableEq
+
+/-- The last `k` layers of phase `a`, in the order of execution. -/
+def strides (b a : ℕ) (ha : a ≤ b) : (k : ℕ) → k ≤ a → List (Stage b)
+ | 0, _ => []
+ | k + 1, hk => ⟨a, k, hk, ha⟩ :: strides b a ha k (Nat.le_of_succ_le hk)
+
+/-- All layers in phases one through `a` of a fixed-width array. -/
+def phases (b : ℕ) : (a : ℕ) → a ≤ b → List (Stage b)
+ | 0, _ => []
+ | a + 1, ha => phases b a (Nat.le_of_succ_le ha) ++ strides b (a+1) ha (a+1) le_rfl
+
+variable {α : Type*}
+
+private def evaluate [LinearOrder α] {b : ℕ} (layers : List (Stage b)) (x : ℕ → α) : ℕ → α :=
+ layers.foldl (fun state s ↦ comparatorLayer s.stride (phaseDirection s.phase) state) x
+
+private theorem evaluate_strides [LinearOrder α] (b a : ℕ) (ha : a ≤ b) (k : ℕ) (hk : k ≤ a)
+ (x : ℕ → α) :
+ evaluate (strides b a ha k hk) x = runStrides k (phaseDirection a) x := by
+ induction k generalizing x with
+ | zero => rfl
+ | succ k ih =>
+ change evaluate (strides b a ha k _) (comparatorLayer k (phaseDirection a) x) = _
+ rw [ih, runStrides]
+
+private theorem evaluate_phases [LinearOrder α] (b a : ℕ) (ha : a ≤ b) (x : ℕ → α) :
+ evaluate (phases b a ha) x = runPhases a x := by
+ induction a with
+ | zero => rfl
+ | succ a ih =>
+ simp only [phases, evaluate, List.foldl_append]
+ change evaluate (strides b (a+1) ha _ _) (evaluate (phases b a _) x) = _
+ rw [ih, evaluate_strides, runPhases]
+
+variable {h d : ℕ}
+
+/-- Exactly one block is sent by each site on a cross-site layer. A local
+layer has a unique empty field since its domain `h ≤ s.stride` is empty. -/
+abbrev Sends (h d : ℕ) (s : Stage (h+d)) (α : Type*) :=
+ h ≤ s.stride → Fin (2 ^ d) → Wires h α
+
+/-- Chronologically arranged outgoing fields. Each receive is addressed to
+the corresponding field of its partner site. -/
+def Fields (h d : ℕ) (α : Type*) : List (Stage (h+d)) → Type _
+ | [] => PUnit
+ | s :: ss => Sends h d s α × Fields h d α ss
+
+/-- Arithmetic address of the unique sender supplying this entire block. -/
+def sourceSite (s : Stage (h+d)) (hc : h ≤ s.stride) (v : Fin (2 ^ d)) : Fin (2 ^ d) :=
+ ⟨partner (s.stride - h) v, partner_lt v.isLt (by have := s.stride_lt; have := s.phase_le; omega)⟩
+
+variable [LinearOrder α]
+
+/-- Update one site's block. Internal strides read both records locally.
+Cross-site strides read the partner's outgoing block at the same offset. -/
+def localLayer (s : Stage (h+d)) (send : Sends h d s α) (v : Fin (2 ^ d))
+ (current : Wires h α) (i : Fin (2 ^ h)) : α :=
+ let g := v.val * 2 ^ h + i.val
+ let other := if hc : h ≤ s.stride then send hc (sourceSite s hc v) i
+ else current ⟨partner s.stride i, partner_lt i.isLt (Nat.lt_of_not_ge hc)⟩
+ if g < partner s.stride g then lower (phaseDirection s.phase g) (current i) other
+ else upper (phaseDirection s.phase g) other (current i)
+
+/-- Sending the actual pre-comparison records produces the same local block
+as the XOR comparator layer. -/
+theorem localLayer_block (s : Stage (h+d)) (x : ℕ → α) (v : Fin (2 ^ d)) :
+ localLayer s (fun _ u ↦ block h u.val x) v (block h v.val x) =
+ block h v.val (comparatorLayer s.stride (phaseDirection s.phase) x) := by
+ funext i
+ by_cases hc : h ≤ s.stride
+ · simp only [localLayer, hc, dite_true, block, comparatorLayer, sourceSite,
+ partner_cross v.val i.isLt hc]
+ · simp only [localLayer, hc, dite_false, block, comparatorLayer,
+ partner_local v.val i.isLt (Nat.lt_of_not_ge hc)]
+
+/-- All outgoing fields agree with this site's computed records. -/
+def checks (v : Fin (2 ^ d)) :
+ (ss : List (Stage (h+d))) → Fields h d α ss → Wires h α → Prop
+ | [], _, _ => True
+ | s :: ss, fields, current =>
+ (∀ hc, fields.1 hc v = current) ∧ checks v ss fields.2 (localLayer s fields.1 v current)
+
+/-- The site's final records, computed only from its local input and the
+cross-site receive fields. -/
+def replay (v : Fin (2 ^ d)) :
+ (ss : List (Stage (h+d))) → Fields h d α ss → Wires h α → Wires h α
+ | [], _, current => current
+ | s :: ss, fields, current => replay v ss fields.2 (localLayer s fields.1 v current)
+
+/-- The actual pre-comparison blocks sent throughout a sequence of layers. -/
+def actual : (ss : List (Stage (h+d))) → (ℕ → α) → Fields h d α ss
+ | [], _ => PUnit.unit
+ | s :: ss, x => (fun _ v ↦ block h v.val x,
+ actual ss (comparatorLayer s.stride (phaseDirection s.phase) x))
+
+theorem checks_actual (ss : List (Stage (h+d))) (x : ℕ → α) (v : Fin (2 ^ d)) :
+ checks v ss (actual ss x) (block h v.val x) := by
+ induction ss generalizing x with
+ | nil => trivial
+ | cons s ss ih =>
+ simp only [checks, actual, localLayer_block]
+ exact ⟨fun _ ↦ trivial, ih _⟩
+
+/-- The local send checks determine the entire exchange transcript uniquely. -/
+theorem fields_eq_actual (ss : List (Stage (h+d))) (fields : Fields h d α ss) (x : ℕ → α)
+ (hc : ∀ v, checks v ss fields (block h v.val x)) : fields = actual ss x := by
+ induction ss generalizing x with
+ | nil => cases fields; rfl
+ | cons s ss ih =>
+ rcases fields with ⟨f, fs⟩
+ have hhead : f = fun _ v ↦ block h v.val x := funext fun h ↦ funext fun v ↦ (hc v).1 h
+ subst f
+ simp only [checks, localLayer_block] at hc
+ exact Prod.ext rfl (ih fs _ (fun v ↦ (hc v).2))
+
+private theorem replay_actual (ss : List (Stage (h+d))) (x : ℕ → α) (v : Fin (2 ^ d)) :
+ replay v ss (actual ss x) (block h v.val x) = block h v.val (evaluate ss x) := by
+ induction ss generalizing x with
+ | nil => rfl
+ | cons s ss ih =>
+ simp only [replay, actual, localLayer_block]
+ exact ih _
+
+/-- A locally accepted exchange reconstructs the correct globally sorted
+records at every site. -/
+theorem replay_phases (fields : Fields h d α (phases (h+d) (h+d) le_rfl)) (x : ℕ → α)
+ (hc : ∀ v, checks v _ fields (block h v.val x)) (v : Fin (2 ^ d)) :
+ replay v _ fields (block h v.val x) = block h v.val (runPhases (h+d) x) := by
+ rw [fields_eq_actual _ _ x hc, replay_actual, evaluate_phases]
+
+/-- For fixed records there is exactly one assignment of cross-site send fields. -/
+theorem existsUnique_fields (ss : List (Stage (h+d))) (x : ℕ → α) :
+ ∃! fields : Fields h d α ss, ∀ v, checks v ss fields (block h v.val x) :=
+ ⟨actual ss x, checks_actual ss x, fun fields hc ↦ fields_eq_actual ss fields x hc⟩
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortRouting.lean b/lean/OAI/Computability/VPVNP/RAMSortRouting.lean
new file mode 100644
index 0000000000..12677a87d6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortRouting.lean
@@ -0,0 +1,93 @@
+import Mathlib.Algebra.BigOperators.Intervals
+import Mathlib.Data.Nat.Bitwise
+import Mathlib.Data.Nat.Choose.Basic
+
+/-!
+# Routing comparator layers between sites
+
+In Lemma 10.1 of *VP and VNP differ over every field*, every site holds a block of
+`2^h = 4H` consecutive positions. A comparator at stride `2^j` pairs positions whose
+indices differ in bit `j`. When `j < h` this changes only the offset inside the block.
+Otherwise every record in the block goes to the same other site with its offset preserved.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+/-- The comparator partner of an array index in a layer with stride `2^j`. -/
+def partner (j x : ℕ) : ℕ := x ^^^ 2 ^ j
+
+@[simp] theorem partner_partner (j x : ℕ) : partner j (partner j x) = x :=
+ Nat.xor_xor_cancel_right x (2 ^ j)
+
+theorem partner_ne (j x : ℕ) : partner j x ≠ x := by
+ intro heq
+ have h := congrArg (fun y ↦ x ^^^ y) heq
+ simp [partner] at h
+
+/-- A comparator partner is a valid position in the same power-of-two array. -/
+theorem partner_lt {b j x : ℕ} (hx : x < 2 ^ b) (hj : j < b) : partner j x < 2 ^ b :=
+ Nat.xor_lt_two_pow hx (Nat.pow_lt_pow_right (by decide) hj)
+
+private theorem partner_split (j site h : ℕ) {off : ℕ} (ho : off < 2 ^ h) :
+ partner j (site * 2 ^ h + off) =
+ (site ^^^ 2 ^ j / 2 ^ h) * 2 ^ h + (off ^^^ 2 ^ j % 2 ^ h) := by
+ have hdiv : (site * 2 ^ h + off) / 2 ^ h = site := by
+ rw [Nat.mul_comm site, Nat.mul_add_div (Nat.two_pow_pos h), Nat.div_eq_of_lt ho,
+ Nat.add_zero]
+ rw [← Nat.div_add_mod' (partner j (site * 2 ^ h + off)) (2 ^ h)]
+ simp only [partner, Nat.xor_div_two_pow, Nat.xor_mod_two_pow, hdiv, Nat.mul_add_mod_of_lt ho]
+
+/-- The low bit belongs to the offset, so every comparator is internal to its site. -/
+theorem partner_local (site : ℕ) {h j off : ℕ} (ho : off < 2 ^ h) (hj : j < h) :
+ partner j (site * 2 ^ h + off) = site * 2 ^ h + partner j off := by
+ have hstride : 2 ^ j < 2 ^ h := Nat.pow_lt_pow_right (by decide) hj
+ rw [partner_split j site h ho]
+ simp [Nat.div_eq_of_lt hstride, Nat.mod_eq_of_lt hstride, partner]
+
+/-- A high bit changes the site and leaves every within-site offset unchanged. -/
+theorem partner_cross (site : ℕ) {h j off : ℕ} (ho : off < 2 ^ h) (hj : h ≤ j) :
+ partner j (site * 2 ^ h + off) = partner (j - h) site * 2 ^ h + off := by
+ have hm : (2 ^ j : ℕ) % 2 ^ h = 0 := Nat.mod_eq_zero_of_dvd (pow_dvd_pow 2 hj)
+ rw [partner_split j site h ho]
+ simp [Nat.pow_div hj (by decide : 0 < (2 : ℕ)), hm, partner]
+
+/-- The partner of a lower-half index lies at the same offset in the upper half. -/
+theorem partner_lo {j i : ℕ} (hi : i < 2 ^ j) : partner j i = i + 2 ^ j := by
+ simpa [partner, Nat.add_comm] using (partner_cross 0 hi (le_refl j))
+
+/-- The reverse comparison sends the upper-half index back to its lower-half mate. -/
+theorem partner_hi {j i : ℕ} (hi : i < 2 ^ j) : partner j (i + 2 ^ j) = i := by
+ rw [← partner_lo hi, partner_partner]
+
+/-- Stride exponents in phase `a` are `a-1, …, 0`. The ones requiring a whole-block
+exchange are exactly those at least `h`. -/
+def crossStrides (h a : ℕ) : Finset ℕ := (Finset.range a).filter (h ≤ ·)
+
+@[simp] theorem mem_crossStrides {h a j : ℕ} : j ∈ crossStrides h a ↔ h ≤ j ∧ j < a := by
+ simp [crossStrides, and_comm]
+
+@[simp] theorem card_crossStrides (h a : ℕ) : (crossStrides h a).card = a - h := by
+ have hIco : crossStrides h a = Finset.Ico h a := Finset.ext fun _ ↦ by simp
+ rw [hIco, Nat.card_Ico]
+
+/-- Summing over the phases of a `2^(h+d)` array gives the factor in equation (10.1).
+Phase zero is included in the index set and has no comparator layers. -/
+theorem total_crossStrides (h d : ℕ) :
+ ∑ a ∈ Finset.range (h + d + 1), (crossStrides h a).card = (d + 1).choose 2 := by
+ rw [Nat.add_assoc, Finset.sum_range_add]
+ have hlocal : ∑ a ∈ Finset.range h, (crossStrides h a).card = 0 := by
+ apply Finset.sum_eq_zero
+ intro a ha
+ simp [Nat.sub_eq_zero_of_le (Finset.mem_range.mp ha).le]
+ rw [hlocal]
+ simp [Finset.sum_range_id, Nat.choose_two_right]
+
+end RAMSort
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortScanMessages.lean b/lean/OAI/Computability/VPVNP/RAMSortScanMessages.lean
new file mode 100644
index 0000000000..9851ac3aad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortScanMessages.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.RAMSortCost
+import OAI.Computability.VPVNP.RAMSortIncident
+import OAI.Computability.VPVNP.RAMSortBlockSlices
+
+/-!
+# Costed sorting replay on the validator's physical messages
+
+The linear-address scan inspects the exact incident bit intervals allocated
+to the site's own sort sends and to its partner's sends. Its acceptance
+therefore checks canonicality of both physical fields and exactly the typed
+send constraints. Its output recovers the typed validator's sorted block.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMLayout RAMSerialization RAMMemory RAMSort
+
+variable {d e w : ℕ}
+
+private abbrev layers (e d : ℕ) := phases ((2+e)+d) ((2+e)+d) le_rfl
+
+private def physicalLayer (s : Stage ((2+e)+d)) (hs : 2+e ≤ s.stride) :=
+ (crossStageEquiv (2+e) d).symm ⟨s, hs⟩
+
+private theorem rawSlice (b : SendArrays d (2^e) w) (v : Fin (2^d)) (s : Stage ((2+e)+d))
+ (hs : 2+e ≤ s.stride) (dir : Fin 2) (i : Fin (2^(2+e))) :
+ (fun bit : Fin (5*w) ↦ sortIncident b v
+ ((fieldStart (2+e) w s.phase s.stride dir i.val).eval + bit.val)) =
+ recordSlice (2^e) w
+ (b.2 (physicalLayer s hs) (if dir = 0 then v else (physicalLayer s hs).partner v))
+ (recordPosition e i) := by
+ funext bit
+ rw [fieldStart_physical (record_width e) s hs dir i bit, sortIncident_offset]
+ have hv : dir.val = 0 ∨ dir.val = 1 := by have := dir.isLt; omega
+ rcases hv with he | he
+ · obtain rfl : dir = 0 := Fin.ext he
+ simp only [ite_true]
+ exact incident_send b (.inr (physicalLayer s hs, v, _))
+ · obtain rfl : dir = 1 := Fin.ext he
+ rw [ite_eq_right (by decide : (1 : Fin 2) ≠ 0)]
+ exact incident_receive_sort ..
+
+/-- Both blocks actually incident at this site in each cross-layer have
+canonical record encoding. -/
+def SortCanonical (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (b : SendArrays d (2^e) w)
+ (v : Fin (2^d)) : Prop :=
+ ∀ l, b.2 l v = (messageBits hw hc (parseMessages hw hc b)).2 l v ∧
+ b.2 l (l.partner v) = (messageBits hw hc (parseMessages hw hc b)).2 l (l.partner v)
+
+private theorem readSlot_of_canonical (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (b : SendArrays d (2^e) w) (v : Fin (2^d)) (s : Stage ((2+e)+d)) (hs : 2+e ≤ s.stride)
+ (dir : Fin 2) (i : Fin (2^(2+e))) (hcan : SortCanonical hw hc b v) :
+ (readSlot hw (sortIncident b v) s dir i).1 =
+ some ((unpackMessages (parseMessages hw hc b)).memory.sortSends (physicalLayer s hs)
+ (if dir = 0 then v else (physicalLayer s hs).partner v) i) := by
+ let l := physicalLayer s hs
+ let u := if dir = 0 then v else l.partner v
+ let records := (parseMessages hw hc b).2 l u
+ have hbits : b.2 l u = (blockFormat (2^e) hw).encode records := by
+ dsimp only [records, u]
+ split
+ · exact (hcan l).1
+ · exact (hcan l).2
+ have hslice : recordSlice (2^e) w (b.2 l u) (recordPosition e i) =
+ (recordFormat hw).encode (records (recordPosition e i)) :=
+ (congrArg (fun y ↦ recordSlice (2^e) w y (recordPosition e i)) hbits).trans (blockEncode_slice ..)
+ simp only [readSlot, rawSlice b v s hs dir i, decodeSlot_eq]
+ rw [show (recordFormat hw).decode (recordSlice (2^e) w (b.2 l u) (recordPosition e i)) =
+ some (records (recordPosition e i)) from ((recordFormat hw).decode_iff ..).mpr hslice]
+ rfl
+
+private theorem loadsOfStages {h : ℕ} (hw : 2 ≤ w) (raw : ℕ → Bool) (v : Fin (2^d))
+ (f : ∀ s : Stage (h+d), Sends h d s (OrderedSlot (Word w)))
+ (hf : ∀ s, Loads hw raw s (f s) v) (ss : List (Stage (h+d))) (hn : ss.Nodup) :
+ LoadsStages hw raw v ss ((fieldsOfStages ss hn) (fun s _ ↦ f s)) := by
+ induction ss with
+ | nil => trivial
+ | cons s ss ih => exact ⟨hf s, ih hn.of_cons⟩
+
+private theorem loadsMessages (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (b : SendArrays d (2^e) w)
+ (v : Fin (2^d)) (hcan : SortCanonical hw hc b v) :
+ LoadsStages hw (sortIncident b v) v (layers e d)
+ (physicalFieldsEquiv.{0,0} (2+e) d _ (unpackMessages (parseMessages hw hc b)).memory.sortSends) := by
+ apply loadsOfStages hw _ v
+ (fun s hs ↦ (unpackMessages (parseMessages hw hc b)).memory.sortSends (physicalLayer s hs))
+ intro s hs i
+ constructor
+ · simpa using readSlot_of_canonical hw hc b v s hs 0 i hcan
+ · rw [sourceSite_eq_physical]
+ simpa [physicalLayer] using readSlot_of_canonical hw hc b v s hs 1 i hcan
+ exact phases_nodup le_rfl
+
+private theorem canonicalOfScan (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (b : SendArrays d (2^e) w)
+ (v : Fin (2^d)) (input : Wires (2+e) (OrderedSlot (Word w)))
+ (hp : (scanStages hw (sortIncident b v) v (layers e d) input).ok = true) :
+ SortCanonical hw hc b v := by
+ intro l
+ let s := (crossStageEquiv (2+e) d) l
+ have hl : physicalLayer s.val s.property = l := (crossStageEquiv (2+e) d).symm_apply_apply l
+ have hall (dir : Fin 2) :
+ ∀ k, ∃ r, recordSlice (2^e) w (b.2 l (if dir = 0 then v else l.partner v)) k =
+ (recordFormat hw).encode r := by
+ intro k
+ obtain ⟨i, rfl⟩ := (recordPosition e).surjective k
+ obtain ⟨r, hr⟩ := scanStages_canonical hw (sortIncident b v) v _ input hp s.val (mem_fullPhases _)
+ s.property dir i
+ rw [rawSlice b v s.val s.property dir i, hl] at hr
+ exact ⟨r, hr⟩
+ constructor
+ · exact (blockCanonical_iff (2^e) hw _).mpr (by simpa using hall 0)
+ · exact (blockCanonical_iff (2^e) hw _).mpr (by simpa using hall 1)
+
+/-- Exact acceptance criterion for the costed local sorting scan on an
+arbitrary raw assignment. -/
+theorem sortScan_messages (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (b : SendArrays d (2^e) w)
+ (v : Fin (2^d)) (input : Wires (2+e) (OrderedSlot (Word w))) :
+ (scanStages hw (sortIncident b v) v (layers e d) input).ok = true ↔
+ SortCanonical hw hc b v ∧ checks v (layers e d)
+ (physicalFieldsEquiv.{0,0} (2+e) d _ (unpackMessages (parseMessages hw hc b)).memory.sortSends)
+ input := by
+ constructor
+ · intro hp
+ have hcan := canonicalOfScan hw hc b v input hp
+ exact ⟨hcan, ((scanStages_spec hw _ _ _ _ _ (loadsMessages hw hc b v hcan)).2).mp hp⟩
+ · rintro ⟨hcan, hp⟩
+ exact ((scanStages_spec hw _ _ _ _ _ (loadsMessages hw hc b v hcan)).2).mpr hp
+
+/-- With canonically parsed sorting fields, the record array handed to the
+predecessor check is the exact `outputAt` array of the typed validator. -/
+theorem sortScan_output (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (b : SendArrays d (2^e) w)
+ (v : Fin (2^d)) (input : Wires (2+e) (OrderedSlot (Word w))) (hcan : SortCanonical hw hc b v) :
+ (fun i ↦ ((scanStages hw (sortIncident b v) v (layers e d) input).block i).record) =
+ outputAt (unpackMessages (parseMessages hw hc b)).memory v input :=
+ congrArg (fun f : Wires (2+e) (OrderedSlot (Word w)) ↦ fun i ↦ (f i).record)
+ ((scanStages_spec hw _ _ _ _ _ (loadsMessages hw hc b v hcan)).1)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSortedRecords.lean b/lean/OAI/Computability/VPVNP/RAMSortedRecords.lean
new file mode 100644
index 0000000000..c73d8f18b7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSortedRecords.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.RAMRecordBlocks
+import OAI.Computability.VPVNP.RAMRecordIndex
+import OAI.Computability.VPVNP.RAMRecordOrder
+import OAI.Computability.VPVNP.RAMSortCorrect
+import OAI.Computability.VPVNP.RAMSortPerm
+
+/-!
+# Checking the reads after the addressed Batcher sort
+
+The canonical call buckets supply `2^d` contiguous blocks, each of width
+`4 * 2^e`. The globally addressed sorting layers permute these very records.
+Consequently the predecessor check on the final array recovers the original
+read semantics from the headers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMMemory RAMSort
+
+variable {w : ℕ}
+
+/-- The padded records on the input wires. Outside the physical array the
+wire function is extended by the empty slot. -/
+def recordWires (header : ℕ → Word w) (d e : ℕ) (rs : List (Report w)) :
+ ℕ → OrderedSlot (Word w) :=
+ fun i => ⟨((canonicalRecordBlocks header (2^d) (2^e) rs).flatten[i]?).getD none⟩
+
+private theorem record_block_width (e : ℕ) : 2 ^ (2 + e) = 4 * 2 ^ e := by
+ rw [Nat.pow_add]
+
+private theorem record_array_width (d e : ℕ) : 2 ^ ((2 + e) + d) = 2^d * (4 * 2^e) := by
+ rw [Nat.pow_add, record_block_width, Nat.mul_comm]
+
+/-- The finite input to the network is exactly the array produced by the
+call buckets. Every comparison moves the full record. -/
+theorem raw_recordWires (header : ℕ → Word w) {d e : ℕ} {rs : List (Report w)}
+ (hcap : RAMBuckets.cost Report.probes rs ≤ 2^d * 2^e)
+ (hc : ∀ r ∈ rs, 1 + r.probes ≤ 2^e) :
+ List.ofFn (block ((2 + e) + d) 0 (recordWires header d e rs)) =
+ (canonicalRecordBlocks header (2^d) (2^e) rs).flatten.map OrderedSlot.mk := by
+ have hlen := length_flatten_canonicalRecordBlocks header (Nat.two_pow_pos e) hcap hc
+ apply List.ext_getElem
+ · simp only [List.length_ofFn, List.length_map, hlen, record_array_width]
+ intro i _ hi
+ simp only [List.length_map] at hi
+ simp only [List.getElem_ofFn, block, recordWires, Nat.zero_mul, Nat.zero_add,
+ List.getElem?_eq_getElem hi, Option.getD_some, List.getElem_map]
+
+/-- Reading the aligned input block at site `v` uses precisely the records
+from that site's canonical call bucket. -/
+theorem block_recordWires (header : ℕ → Word w) {d e : ℕ} {rs : List (Report w)}
+ (hcap : RAMBuckets.cost Report.probes rs ≤ 2^d * 2^e)
+ (hc : ∀ r ∈ rs, 1 + r.probes ≤ 2^e) (v : Fin (2^d)) :
+ List.ofFn (block (2 + e) v.val (recordWires header d e rs)) =
+ ((canonicalRecordBlocks header (2^d) (2^e) rs)[v.val]'(by
+ simp [length_canonicalRecordBlocks])).map OrderedSlot.mk := by
+ let rows := canonicalRecordBlocks header (2^d) (2^e) rs
+ have hw : ∀ row ∈ rows, row.length = 2 ^ (2 + e) := by
+ rw [record_block_width]
+ exact canonicalRecordBlocks_width header (Nat.two_pow_pos e) hcap hc
+ have hv : v.val < rows.length := by simp [rows, length_canonicalRecordBlocks]
+ have hrow := hw rows[v.val] (List.getElem_mem hv)
+ apply List.ext_getElem
+ · exact List.length_ofFn.trans ((List.length_map ..).trans hrow).symm
+ intro j hj hj'
+ have hjW : j < 2 ^ (2 + e) := by simpa only [List.length_ofFn] using hj
+ have hjrow : j < rows[v.val].length := hrow.symm ▸ hjW
+ simp only [List.getElem_ofFn, List.getElem_map, block, recordWires]
+ change ⟨(rows.flatten[v.val * 2 ^ (2 + e) + j]?).getD none⟩ = OrderedSlot.mk rows[v.val][j]
+ rw [getElem?_flatten_rect hw hv hjW, List.getElem?_eq_getElem hjrow]
+ rfl
+
+/-- The five-word slots after the last addressed layer of the network. -/
+def sortedRecords (header : ℕ → Word w) (d e : ℕ) (rs : List (Report w)) :
+ List (Option (Record (Word w))) :=
+ let b := (2 + e) + d
+ (List.ofFn (block b 0 (runPhases b (recordWires header d e rs)))).map OrderedSlot.record
+
+/-- Concatenate the final blocks scanned by the physical site validators,
+retaining every padding slot. -/
+theorem flatten_sorted_record_blocks (header : ℕ → Word w) (d e : ℕ) (rs : List (Report w)) :
+ let h := 2 + e
+ let output := runPhases (h + d) (recordWires header d e rs)
+ (List.ofFn fun v : Fin (2^d) =>
+ (List.ofFn (block h v.val output)).map OrderedSlot.record).flatten =
+ sortedRecords header d e rs := by
+ let h := 2 + e
+ let output := runPhases (h + d) (recordWires header d e rs)
+ simpa only [sortedRecords, List.map_flatten, List.map_ofFn, Function.comp_def] using
+ congrArg (List.map OrderedSlot.record) (flatten_ofFn_blocks h d output)
+
+/-- The physical ascending output contains exactly the original padded records. -/
+theorem sortedRecords_perm (header : ℕ → Word w) {d e : ℕ} {rs : List (Report w)}
+ (hcap : RAMBuckets.cost Report.probes rs ≤ 2^d * 2^e)
+ (hc : ∀ r ∈ rs, 1 + r.probes ≤ 2^e) :
+ (canonicalRecordBlocks header (2^d) (2^e) rs).flatten.Perm (sortedRecords header d e rs) := by
+ let b := (2 + e) + d
+ let x := recordWires header d e rs
+ have hp := ((sort_perm b true (block b 0 x)).symm).map OrderedSlot.record
+ rw [show List.ofFn (block b 0 x) = _ from raw_recordWires header hcap hc] at hp
+ have hid : OrderedSlot.record ∘ (@OrderedSlot.mk (Word w)) = id := rfl
+ simpa only [sortedRecords, block_runPhases, Nat.zero_mod, decide_true, b, x, List.map_map,
+ hid, List.map_id_fun, id_eq] using hp
+
+/-- The physical output is in the paper's padded-key order. -/
+theorem sortedRecords_sorted (header : ℕ → Word w) (d e : ℕ) (rs : List (Report w)) :
+ (sortedRecords header d e rs).Pairwise fun x y => paddedKey x ≤ paddedKey y := by
+ simp only [sortedRecords, block_runPhases, Nat.zero_mod, decide_true, List.pairwise_map,
+ List.pairwise_ofFn]
+ intro i j hij
+ exact paddedKey_mono (sort_monotone _ _ hij.le)
+
+/-- The local predecessor rule applied to the actual sorting-network output
+accepts exactly the correct read guesses of the original RAM events. -/
+theorem sortedRecords_read_check (header : ℕ → Word w) {d e : ℕ} {rs : List (Report w)}
+ (hcap : RAMBuckets.cost Report.probes rs ≤ 2^d * 2^e)
+ (hc : ∀ r ∈ rs, 1 + r.probes ≤ 2^e) :
+ PaddedCheck none (sortedRecords header d e rs) ↔
+ Correct (initialMemory (2^d) header) (rs.map Report.events).flatten :=
+ (paddedCheck_iff_filter (sortedRecords_sorted ..) none).trans
+ (padded_read_check (canonicalRecordBlocks_perm header hcap)
+ (sortedRecords_perm header hcap hc) (sortedRecords_sorted ..))
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSuccessor.lean b/lean/OAI/Computability/VPVNP/RAMSuccessor.lean
new file mode 100644
index 0000000000..bcde56cb0b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSuccessor.lean
@@ -0,0 +1,306 @@
+import OAI.Computability.VPVNP.RAMChain
+import OAI.Computability.VPVNP.RAMRecords
+import Mathlib.Data.Fin.Tuple.Basic
+
+/-!
+# Successor messages and local RAM call validation
+
+In Lemma 10.1, a successor message carries the cumulative cost and either
+the running state or a halt. The last processor checks acceptance locally.
+The site predicate reads its own reports and its two incident cuts. Its
+unique consistent assignments recover precisely the bounded accepting call
+chains, with read values still to be checked by the sorting network.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ} {C : Type*}
+
+/-- The status and persistent state form a tagged option. A halted state has
+one representation, independently of the last persistent word. -/
+@[ext] structure Cut (w : ℕ) where
+ /-- Cumulative cost of the computation up to this boundary between site segments. -/
+ cost : ℕ
+ /-- Persistent state at the cut while the computation is running, or the empty option after
+ an accepting halt. -/
+ state : Option (Word w)
+ deriving DecidableEq
+
+/-- Advance the cut through the given call reports by adding their call-and-probe costs and
+taking the resulting persistent state. -/
+def Cut.advance (c : Cut w) (xs : List (Report w)) : Cut w :=
+ ⟨c.cost + RAMBuckets.cost Report.probes xs, endState c.state xs⟩
+
+@[simp] theorem Cut.advance_nil (c : Cut w) : c.advance [] = c := by
+ cases c
+ simp [Cut.advance, RAMBuckets.cost, endState]
+
+theorem Cut.advance_append (c : Cut w) (xs ys : List (Report w)) :
+ c.advance (xs ++ ys) = (c.advance xs).advance ys := by
+ simp [Cut.advance, endState_append, Nat.add_assoc]
+
+/-- Local processing at site `v`. A running continuation must have reached
+the next bucket. All reports are validated using the incident running state. -/
+structure SiteRun (P : Program w C) (fuel S H v : ℕ) (c : Cut w)
+ (xs : List (Report w)) : Prop where
+ incoming : c.state.isSome → v * H ≤ c.cost ∧ c.cost < (v + 1) * H
+ before : RAMBuckets.StartsBefore Report.probes ((v + 1) * H) c.cost xs
+ calls : LocalSegment P fuel c.state xs
+ call_cap : ∀ r ∈ xs, 1 + r.probes ≤ H
+ total_cap : (c.advance xs).cost ≤ S * H
+ crossing : (c.advance xs).state.isSome → (v + 1) * H ≤ (c.advance xs).cost
+
+/-- At an internal cut the outgoing message must be exactly the local result.
+At the last site the send is clamped and the actual local result must be halted. -/
+def SiteCheck (P : Program w C) (fuel S H v : ℕ) (input : Cut w)
+ (output : Option (Cut w)) (block : List (Report w)) : Prop :=
+ SiteRun P fuel S H v input block ∧
+ match output with
+ | some d => d = input.advance block
+ | none => (input.advance block).state = none
+
+/-- Internal wires are indexed by the site that sends them. -/
+def inputCut {S : ℕ} (first : Cut w) (wire : Fin (S - 1) → Cut w) (i : Fin S) : Cut w :=
+ if h : i.val = 0 then first else wire ⟨i.val - 1, by have := i.isLt; omega⟩
+
+/-- Look up the successor message sent by this site if it has a successor, returning the empty
+option at the final site. -/
+def outputCut {S : ℕ} (wire : Fin (S - 1) → Cut w) (i : Fin S) : Option (Cut w) :=
+ if h : i.val + 1 < S then some (wire ⟨i.val, by omega⟩) else none
+
+/-- Only the initial site substitutes a fixed incoming status. -/
+def SitesPass (P : Program w C) (fuel S H : ℕ) (initial : Word w)
+ (blocks : Fin S → List (Report w)) (wire : Fin (S - 1) → Cut w) : Prop :=
+ ∀ i, SiteCheck P fuel S H i.val (inputCut ⟨0, some initial⟩ wire i) (outputCut wire i) (blocks i)
+
+/-- Accumulated cost and state determine all internal cuts, independently of
+the accept/reject decision. -/
+def canonicalCuts : (n : ℕ) → Cut w → (Fin n → List (Report w)) → Fin (n - 1) → Cut w
+ | 0, _, _ => Fin.elim0
+ | 1, _, _ => Fin.elim0
+ | n + 2, c, blocks =>
+ let d := c.advance (blocks 0)
+ Fin.cons d (canonicalCuts (n + 1) d (Fin.tail blocks))
+
+/-- Recursive semantics for proving the equivalence with the independent
+site tests. The cost and state are recomputed at each boundary. -/
+private def ChainChecks (P : Program w C) (fuel S H : ℕ) :
+ ℕ → Cut w → List (List (Report w)) → Prop
+ | _, c, [] => c.state = none ∧ c.cost ≤ S * H
+ | v, c, block :: rest =>
+ SiteRun P fuel S H v c block ∧ ChainChecks P fuel S H (v + 1) (c.advance block) rest
+
+private theorem cut_succ {n : ℕ} (c : Cut w) (wire : Fin (n + 1) → Cut w) (i : Fin (n + 1)) :
+ inputCut c wire i.succ = inputCut (S := n + 1) (wire 0) (Fin.tail wire) i ∧
+ outputCut wire i.succ = outputCut (S := n + 1) (Fin.tail wire) i := by
+ rcases i with ⟨i, hi⟩
+ cases i <;> simp [inputCut, outputCut, Fin.tail, Nat.succ_lt_succ_iff]
+
+private theorem indexed_checks (P : Program w C) (fuel S H v n : ℕ) (c : Cut w)
+ (blocks : Fin (n + 1) → List (Report w)) (wire : Fin n → Cut w) :
+ (∀ i : Fin (n + 1), SiteCheck P fuel S H (v + i.val) (inputCut (S := n + 1) c wire i)
+ (outputCut (S := n + 1) wire i) (blocks i)) ↔
+ ChainChecks P fuel S H v c (List.ofFn blocks) ∧ wire = canonicalCuts (n + 1) c blocks := by
+ induction n generalizing v c with
+ | zero =>
+ rw [Fin.forall_fin_succ]
+ have he : wire = canonicalCuts 1 c blocks := Subsingleton.elim ..
+ simp [inputCut, outputCut, SiteCheck, ChainChecks, he]
+ exact fun hr _ => hr.total_cap
+ | succ n ih =>
+ rw [Fin.forall_fin_succ, List.ofFn_succ]
+ have hrest : (∀ i : Fin (n + 1), SiteCheck P fuel S H (v + i.succ.val)
+ (inputCut c wire i.succ) (outputCut wire i.succ) (blocks i.succ)) ↔
+ ChainChecks P fuel S H (v + 1) (wire 0) (List.ofFn (Fin.tail blocks)) ∧
+ Fin.tail wire = canonicalCuts (n + 1) (wire 0) (Fin.tail blocks) := by
+ refine Iff.trans ?_ (ih (v + 1) (wire 0) (Fin.tail blocks) (Fin.tail wire))
+ apply forall_congr'
+ intro i
+ obtain ⟨h1, h2⟩ := cut_succ c wire i
+ rw [h1, h2]
+ simp [Nat.add_comm, Nat.add_left_comm, Fin.tail]
+ rw [hrest]
+ simp only [Fin.val_zero, Nat.add_zero, inputCut, ↓reduceDIte, outputCut, Nat.zero_add,
+ Nat.succ_lt_succ_iff, Nat.zero_lt_succ, SiteCheck, ChainChecks]
+ constructor
+ · rintro ⟨⟨hsite, he⟩, hchecks, htail⟩
+ change wire 0 = c.advance (blocks 0) at he
+ rw [he] at hchecks htail
+ refine ⟨⟨hsite, hchecks⟩, ?_⟩
+ rw [← Fin.cons_self_tail wire, canonicalCuts, he, htail]
+ · rintro ⟨⟨hsite, ht⟩, rfl⟩
+ simp only [canonicalCuts, Fin.cons_zero, Fin.tail_cons]
+ exact ⟨⟨hsite, rfl⟩, ht, trivial⟩
+
+private theorem local_some_of_ne_nil {P : Program w C} {fuel : ℕ} {s : Option (Word w)}
+ {xs : List (Report w)} (hc : LocalSegment P fuel s xs) (hx : xs ≠ []) : s.isSome := by
+ cases xs with
+ | nil => contradiction
+ | cons r rs => cases s with
+ | none => contradiction
+ | some _ => rfl
+
+theorem SiteRun.input_cap {P : Program w C} {fuel S H v : ℕ} {c : Cut w}
+ {block : List (Report w)} (h : SiteRun P fuel S H v c block) : c.cost ≤ S * H :=
+ Nat.le_trans (Nat.le_add_right ..) h.total_cap
+
+theorem SiteRun.cost_lt {P : Program w C} {fuel S H v : ℕ} {c : Cut w}
+ {block : List (Report w)} (h : SiteRun P fuel S H v c block) (hH : 0 < H) :
+ RAMBuckets.cost Report.probes block < 2 * H :=
+ RAMBuckets.site_cost_lt hH (fun hn => (h.incoming (local_some_of_ne_nil h.calls hn)).1)
+ h.before h.call_cap
+
+/-- The cumulative cost sent on each internal edge is representable whenever
+the global cap fits in a word. -/
+theorem sitesPass_wire_cost {P : Program w C} {fuel S H : ℕ} {initial : Word w}
+ {blocks : Fin S → List (Report w)} {wire : Fin (S - 1) → Cut w}
+ (h : SitesPass P fuel S H initial blocks wire) (j : Fin (S - 1)) :
+ (wire j).cost ≤ S * H := by
+ have hj := j.isLt
+ let i : Fin S := ⟨j.val, by omega⟩
+ obtain ⟨hr, hs⟩ := h i
+ have he : outputCut wire i = some (wire j) := by
+ simp [outputCut, i, show j.val + 1 < S by omega]
+ rw [he] at hs
+ rw [hs]
+ exact hr.total_cap
+
+private theorem checks_sound {P : Program w C} {fuel S H v : ℕ} {c : Cut w}
+ {blocks : List (List (Report w))} (hv : ChainChecks P fuel S H v c blocks) :
+ RAMBuckets.Valid Report.probes H v c.cost blocks ∧ LocalSegment P fuel c.state blocks.flatten ∧
+ (c.advance blocks.flatten).state = none ∧ (c.advance blocks.flatten).cost ≤ S * H ∧
+ ∀ r ∈ blocks.flatten, 1 + r.probes ≤ H := by
+ induction blocks generalizing v c with
+ | nil => simpa [List.flatten_nil, Cut.advance_nil, LocalSegment, RAMBuckets.Valid, ChainChecks] using hv
+ | cons block blocks ih =>
+ obtain ⟨hr, ht⟩ := hv
+ obtain ⟨hvalid, hseg, hend, hcap, hcalls⟩ := ih ht
+ simp only [List.flatten_cons, Cut.advance_append, localSegment_append]
+ refine ⟨⟨fun hn => (hr.incoming (local_some_of_ne_nil hr.calls hn)).1,
+ hr.before, fun hn => hr.crossing (local_some_of_ne_nil hseg hn), hvalid⟩,
+ ⟨hr.calls, hseg⟩, hend, hcap, ?_⟩
+ exact fun r h => (List.mem_append.mp h).elim (hr.call_cap r) (hcalls r)
+
+private theorem checks_complete {P : Program w C} {fuel S H v : ℕ} {c : Cut w}
+ {blocks : List (List (Report w))} (hi : c.state.isSome → v * H ≤ c.cost ∧ c.cost < (v + 1) * H)
+ (hv : RAMBuckets.Valid Report.probes H v c.cost blocks)
+ (hseg : LocalSegment P fuel c.state blocks.flatten)
+ (hend : (c.advance blocks.flatten).state = none)
+ (hcap : (c.advance blocks.flatten).cost ≤ S * H)
+ (hcalls : ∀ r ∈ blocks.flatten, 1 + r.probes ≤ H) : ChainChecks P fuel S H v c blocks := by
+ induction blocks generalizing v c with
+ | nil => simpa [ChainChecks] using And.intro hend hcap
+ | cons block rest ih =>
+ obtain ⟨_, hbefore, hstop, hvalid⟩ := hv
+ simp only [List.flatten_cons, Cut.advance_append, localSegment_append] at hseg hend hcap
+ have hbcap : ∀ r ∈ block, 1 + r.probes ≤ H := fun r hr => hcalls r (by simp [hr])
+ have hc : (c.advance block).cost ≤ S * H := Nat.le_trans (Nat.le_add_right ..) hcap
+ have hcross (h : (c.advance block).state.isSome) : (v + 1) * H ≤ (c.advance block).cost := by
+ apply hstop
+ intro he
+ rw [he, Cut.advance_nil] at hend
+ simp [hend] at h
+ refine ⟨⟨hi, hbefore, hseg.1, hbcap, hc, hcross⟩,
+ ih ?_ hvalid hseg.2 hend hcap (fun r hr => hcalls r (by simp [hr]))⟩
+ intro h
+ refine ⟨hcross h, ?_⟩
+ by_cases hn : block = []
+ · subst block
+ rw [Cut.advance_nil] at h ⊢
+ have hu := (hi h).2
+ rw [Nat.succ_mul]
+ omega
+ · have hu := hbefore.finish_lt hn hbcap
+ rw [Nat.succ_mul (v + 1)]
+ exact hu
+
+/-- The bounds used for accepted paths in Lemma 10.1. -/
+def withinCaps (S H : ℕ) (rs : List (Report w)) : Prop :=
+ RAMBuckets.cost Report.probes rs ≤ S * H ∧ ∀ r ∈ rs, 1 + r.probes ≤ H
+
+private theorem sitesPass_iff {P : Program w C} {fuel S H : ℕ} {initial : Word w}
+ {blocks : Fin S → List (Report w)} {wire : Fin (S - 1) → Cut w} (hS : 0 < S) :
+ SitesPass P fuel S H initial blocks wire ↔
+ ChainChecks P fuel S H 0 ⟨0, some initial⟩ (List.ofFn blocks) ∧
+ wire = canonicalCuts S ⟨0, some initial⟩ blocks := by
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (Nat.ne_of_gt hS)
+ simpa [SitesPass] using indexed_checks P fuel (n + 1) H 0 n ⟨0, some initial⟩ blocks wire
+
+theorem successor_sound {P : Program w C} {fuel S H : ℕ} {initial : Word w}
+ {blocks : Fin S → List (Report w)} {wire : Fin (S - 1) → Cut w} (hS : 0 < S)
+ (h : SitesPass P fuel S H initial blocks wire) :
+ LocalSegment P fuel (some initial) (List.ofFn blocks).flatten ∧
+ endState (some initial) (List.ofFn blocks).flatten = none ∧
+ withinCaps S H (List.ofFn blocks).flatten := by
+ obtain ⟨_, hs, he, hc, ha⟩ := checks_sound ((sitesPass_iff hS).mp h).1
+ exact ⟨hs, he, by simpa [Cut.advance] using hc, ha⟩
+
+theorem sitesPass_eq_partition {P : Program w C} {fuel S H : ℕ} {initial : Word w}
+ {blocks : Fin S → List (Report w)} {wire : Fin (S - 1) → Cut w} (hS : 0 < S)
+ (h : SitesPass P fuel S H initial blocks wire) :
+ List.ofFn blocks = RAMBuckets.partition Report.probes H 0 S 0 (List.ofFn blocks).flatten := by
+ obtain ⟨hv, _⟩ := checks_sound ((sitesPass_iff hS).mp h).1
+ simpa using hv.eq_partition.symm
+
+private theorem canonical_input (S : ℕ) (c : Cut w) (blocks : Fin S → List (Report w)) (i : Fin S) :
+ inputCut c (canonicalCuts S c blocks) i =
+ c.advance ((List.ofFn blocks).take i.val).flatten := by
+ cases S with
+ | zero => exact Fin.elim0 i
+ | succ n =>
+ induction n generalizing c with
+ | zero =>
+ have hi : i = 0 := Fin.ext (by simp)
+ subst i
+ simp [inputCut]
+ | succ n ih =>
+ refine Fin.cases ?_ (fun j => ?_) i
+ · simp [inputCut]
+ · rw [(cut_succ c (canonicalCuts (n + 2) c blocks) j).1]
+ simp only [canonicalCuts, Fin.cons_zero, Fin.tail_cons]
+ rw [ih, List.ofFn_succ (f := blocks), Fin.val_succ, List.take_succ_cons, List.flatten_cons,
+ Cut.advance_append]
+ rfl
+
+theorem sitesPass_input_cost {P : Program w C} {fuel S H : ℕ} {initial : Word w}
+ {blocks : Fin S → List (Report w)} {wire : Fin (S - 1) → Cut w} (hS : 0 < S)
+ (h : SitesPass P fuel S H initial blocks wire) (i : Fin S) :
+ (inputCut ⟨0, some initial⟩ wire i).cost =
+ RAMBuckets.cost Report.probes ((List.ofFn blocks).take i.val).flatten := by
+ rw [((sitesPass_iff hS).mp h).2, canonical_input]
+ simp [Cut.advance]
+
+/-- Every bounded accepting call chain has a unique grouping and assignment
+of the internal successor wires. Read consistency can be imposed independently. -/
+theorem successor_unique (P : Program w C) (fuel S H : ℕ) (initial : Word w) (rs : List (Report w))
+ (hS : 0 < S) (hH : 0 < H) (hseg : LocalSegment P fuel (some initial) rs)
+ (hend : endState (some initial) rs = none) (hc : withinCaps S H rs) :
+ ∃! p : (Fin S → List (Report w)) × (Fin (S - 1) → Cut w),
+ (List.ofFn p.1).flatten = rs ∧ SitesPass P fuel S H initial p.1 p.2 := by
+ obtain ⟨bs, ⟨hlen, hflat, hv⟩, huniq⟩ := RAMBuckets.existsUnique_partition Report.probes S H rs hc.1
+ let blocks : Fin S → List (Report w) := fun i => bs.get (Fin.cast hlen.symm i)
+ have heq : List.ofFn blocks = bs := by
+ subst S
+ simp [blocks]
+ let c : Cut w := ⟨0, some initial⟩
+ refine ⟨(blocks, canonicalCuts S c blocks), ⟨by simpa [heq] using hflat, (sitesPass_iff hS).mpr ?_⟩, ?_⟩
+ · refine ⟨?_, rfl⟩
+ rw [heq]
+ exact checks_complete (by simp [hH]) hv (hflat ▸ hseg) (by simpa [Cut.advance, hflat] using hend)
+ (by simpa [Cut.advance, hflat] using hc.1) (hflat ▸ hc.2)
+ · rintro ⟨other, wire⟩ ⟨hf, hp⟩
+ obtain ⟨hchecks, hwire⟩ := (sitesPass_iff hS).mp hp
+ have hlo := huniq (List.ofFn other) ⟨List.length_ofFn, hf, (checks_sound hchecks).1⟩
+ have hb : other = blocks := List.ofFn_injective (hlo.trans heq.symm)
+ subst other
+ exact Prod.ext rfl hwire
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMSuccessorDecodeCost.lean b/lean/OAI/Computability/VPVNP/RAMSuccessorDecodeCost.lean
new file mode 100644
index 0000000000..96b8e9fc78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMSuccessorDecodeCost.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.RAMSortDecodeCost
+
+/-!
+# Word work to decode a successor message
+
+The successor field of Lemma 10.1 comprises three control words and a five-word
+record. The validator scans each word into a register once. It returns the parsed
+successor together with a flag for equality with the canonical eight registers.
+This separates parsing from rejection, including when the input is a clamped field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSerialization
+
+open BurstRAM RAMSort
+
+variable {w cap : ℕ}
+
+private def scanFieldWord (b : Fin (8 * w) → Bool) (i : Fin 8) : Word w × ℕ :=
+ scanWord fun j ↦ b (finProdFinEquiv (i, j))
+
+private theorem scanFieldWord_value (b : Fin (8 * w) → Bool) (i : Fin 8) :
+ (scanFieldWord b i).1 = (arrayBits 8 w).symm b i := by
+ rw [scanFieldWord, scanWord_eq]
+ apply (wordBits w).injective
+ funext j
+ rw [Equiv.apply_symm_apply, ← arrayBits_at, Equiv.apply_symm_apply]
+
+/-- Each scan returns its word and operation count. The eight register writes are
+charged once when saving the results. -/
+private def scanEight (b : Fin (8 * w) → Bool) : (Fin 8 → Word w) × ℕ :=
+ let f₀ := scanFieldWord b 0
+ let f₁ := scanFieldWord b 1
+ let f₂ := scanFieldWord b 2
+ let f₃ := scanFieldWord b 3
+ let f₄ := scanFieldWord b 4
+ let f₅ := scanFieldWord b 5
+ let f₆ := scanFieldWord b 6
+ let f₇ := scanFieldWord b 7
+ (![f₀.1, f₁.1, f₂.1, f₃.1, f₄.1, f₅.1, f₆.1, f₇.1],
+ f₀.2 + f₁.2 + f₂.2 + f₃.2 + f₄.2 + f₅.2 + f₆.2 + f₇.2 + 8)
+
+private theorem scanEight_value (b : Fin (8 * w) → Bool) :
+ (scanEight b).1 = (arrayBits 8 w).symm b := by
+ funext i
+ fin_cases i <;> apply scanFieldWord_value
+
+private def checkEight (a c : Fin 8 → Word w) : Bool :=
+ (List.finRange 8).all fun i ↦ decide (a i = c i)
+
+private theorem checkEight_valid (a c : Fin 8 → Word w) :
+ checkEight a c = true ↔ a = c := by
+ simp [checkEight, funext_iff]
+
+/-- Parse the saved control and record fields and compare with the canonical words.
+Allow 24 operations for dispatch (status, cost cap and up to three record tags)
+and copying the payload. Allow 24 for forming the canonical control and record
+words. Comparing eight registers costs at most six operations per register
+(loop test, advance, two loads, equality and branch) plus the final test.
+Returning the successor and flag costs two more writes. -/
+def scanSuccessor (hw : 2 ≤ w) (hc : cap < 2 ^ w) (b : Fin (8 * w) → Bool) :
+ (Successor w cap × Bool) × ℕ :=
+ let saved := scanEight b
+ let f := successorFormat hw hc
+ let parsed := f.parse saved.1
+ ((parsed, checkEight saved.1 (f.words parsed)), saved.2 + 24 + 24 + (6 * 8 + 1) + 2)
+
+theorem scanSuccessor_value (hw : 2 ≤ w) (hc : cap < 2 ^ w) (b : Fin (8 * w) → Bool) :
+ (scanSuccessor hw hc b).1.1 = (successorFormat hw hc).parse ((arrayBits 8 w).symm b) := by
+ simp only [scanSuccessor, scanEight_value]
+
+theorem scanSuccessor_valid (hw : 2 ≤ w) (hc : cap < 2 ^ w) (b : Fin (8 * w) → Bool) :
+ (scanSuccessor hw hc b).1.2 = true ↔
+ b = (successorFormat hw hc).encode ((successorFormat hw hc).parse ((arrayBits 8 w).symm b)) := by
+ simp only [scanSuccessor, scanEight_value, checkEight_valid, Format.encode]
+ exact (arrayBits 8 w).symm_apply_eq
+
+theorem scanSuccessor_cost (hw : 2 ≤ w) (hc : cap < 2 ^ w) (b : Fin (8 * w) → Bool) :
+ (scanSuccessor hw hc b).2 ≤ 224 * (w + 1) := by
+ simp only [scanSuccessor, scanEight, scanFieldWord, scanWord_steps]
+ omega
+
+end RAMSerialization
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTape.lean b/lean/OAI/Computability/VPVNP/RAMTape.lean
new file mode 100644
index 0000000000..f8d78f16d0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTape.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.UniversalMachine
+import Mathlib.Data.Fintype.EquivFin
+
+/-!
+# Writable nondeterministic controls for the coefficient machine
+
+A named finite control can inspect both head symbols, write and move both tapes,
+and make a binary choice. The compiler emits the nine literal rows for each state.
+Each occupied branch slot contributes its own path count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+open UniversalMachine
+
+/-- Halting or two-head transition with a named successor state. -/
+inductive Command (Q : Type*) where
+ | halt (accept : Bool)
+ | next (state : Q) (firstSymbol firstMove secondSymbol secondMove : Fin 3)
+
+/-- The occupied nondeterministic branch slots of one table row. -/
+inductive Choices (Q : Type*) where
+ | stop
+ | one (a : Command Q)
+ | two (a b : Command Q)
+
+/-- The commands available at each state and pair of scanned symbols. -/
+abbrev Control (Q : Type*) := Q → Symbol → Symbol → Choices Q
+
+variable {Q : Type*} [Fintype Q]
+
+private theorem card_pos (start : Q) : 0 < Fintype.card Q :=
+ Fintype.card_pos_iff.mpr ⟨start⟩
+
+private noncomputable def number (start : Q) : Q ≃ Fin (Fintype.card Q) :=
+ (Fintype.equivFin Q).trans (Equiv.swap (Fintype.equivFin Q start) ⟨0, card_pos start⟩)
+
+private noncomputable def target (start q : Q) : Fin (Fintype.card Q + 2) :=
+ ⟨(number start q).val + 2, by have := (number start q).isLt; omega⟩
+
+/-- Encode one named command as a universal-machine instruction. -/
+noncomputable def instruction (start : Q) : Command Q → Instruction (Fintype.card Q)
+ | .halt b => ⟨⟨if b then 1 else 0, by split <;> omega⟩, 0, 0, 0, 0⟩
+ | .next q a d b e => ⟨target start q, a, d, b, e⟩
+
+/-- Encode the occupied branch slots, preserving their multiplicities. -/
+noncomputable def records (start : Q) : Choices Q → Branches (Fintype.card Q)
+ | .stop => .stop
+ | .one a => .one (instruction start a)
+ | .two a b => .two (instruction start a) (instruction start b)
+
+private noncomputable def row (start : Q) (code : Control Q)
+ (i : Fin (Fintype.card Q * 9)) : Branches (Fintype.card Q) :=
+ records start (code ((number start).symm ⟨i.val / 9, by omega⟩)
+ ⟨i.val % 9 / 3, by omega⟩ ⟨i.val % 3, by omega⟩)
+
+/-- The physical table for a fixed finite control. -/
+noncomputable abbrev compile (start : Q) (code : Control Q) : Program :=
+ ⟨Fintype.card Q, List.ofFn (row start code), List.length_ofFn⟩
+
+/-- Physical configuration of a named nonhalting state and its two tapes. -/
+noncomputable def running (start q : Q) (t u : Turing.Tape Symbol) : Config (Fintype.card Q) :=
+ ⟨target start q, t, u⟩
+
+/-- The two halting states precede every encoded control state. -/
+theorem running_state_ge_two (start q : Q) (t u : Turing.Tape Symbol) :
+ 2 ≤ (running start q t u).state.val := by
+ change 2 ≤ (number start q).val + 2
+ omega
+
+theorem initial_eq_running (start : Q) (code : Control Q) (input : Word) :
+ initial (compile start code) input =
+ running start start (Turing.Tape.mk₁ (input.map fun b => if b then 2 else 1))
+ (Turing.Tape.mk₁ []) := by
+ unfold initial running
+ congr 1
+ apply Fin.ext
+ simp [compile, (card_pos start).ne', target, number]
+
+theorem lookup (start : Q) (code : Control Q) (q : Q) (t u : Turing.Tape Symbol) :
+ branches (compile start code) (running start q t u) = records start (code q t.head u.head) := by
+ let j := (number start q).val * 9 + t.head.val * 3 + u.head.val
+ have hq := (number start q).isLt
+ have ha := t.head.isLt
+ have hb := u.head.isLt
+ have hj : j < Fintype.card Q * 9 := by dsimp [j]; omega
+ unfold branches compile running target
+ simp only [Nat.add_sub_cancel]
+ change (List.ofFn (row start code))[j]?.getD .stop = _
+ rw [List.getElem?_eq_getElem (by simpa using hj)]
+ simp only [Option.getD_some, List.getElem_ofFn, row]
+ have h₁ : (⟨j / 9, by omega⟩ : Fin (Fintype.card Q)) = number start q :=
+ Fin.ext (by dsimp [j]; omega)
+ have h₂ : (⟨j % 9 / 3, by omega⟩ : Symbol) = t.head := Fin.ext (by dsimp [j]; omega)
+ have h₃ : (⟨j % 3, by omega⟩ : Symbol) = u.head := Fin.ext (by dsimp [j]; omega)
+ simp [h₁, h₂, h₃]
+
+/-- Accepting paths from the given named configuration within the tape clock. -/
+noncomputable abbrev count (start : Q) (code : Control Q) (ticks : ℕ) (q : Q)
+ (t u : Turing.Tape Symbol) := paths (compile start code) ticks (running start q t u)
+
+/-- The contribution of one executed command to the remaining accepting path count. -/
+noncomputable def after (start : Q) (code : Control Q) (ticks : ℕ) (t u : Turing.Tape Symbol) :
+ Command Q → ℕ
+ | .halt b => b.toNat
+ | .next q a d b e => count start code ticks q (updateTape t a d) (updateTape u b e)
+
+private theorem paths_advance (start : Q) (code : Control Q) (ticks : ℕ) (q : Q)
+ (t u : Turing.Tape Symbol) (a : Command Q) :
+ paths (compile start code) ticks (advance (running start q t u) (instruction start a)) =
+ after start code ticks t u a := by
+ cases a with
+ | halt b => cases b <;> first | exact paths_reject _ _ rfl _ | exact paths_accept _ _ rfl _
+ | next => rfl
+
+/-- A literal binary row adds two counts, including when its targets agree. -/
+theorem paths_step (start : Q) (code : Control Q) (ticks : ℕ) (q : Q)
+ (t u : Turing.Tape Symbol) :
+ count start code (ticks + 1) q t u =
+ match code q t.head u.head with
+ | .stop => 0
+ | .one a => after start code ticks t u a
+ | .two a b => after start code ticks t u a + after start code ticks t u b := by
+ have h₁ : (running start q t u).state.val ≠ 1 := by change (number start q).val + 2 ≠ 1; omega
+ have h₀ : (running start q t u).state.val ≠ 0 := by change (number start q).val + 2 ≠ 0; omega
+ rw [count, paths]
+ simp only [ite_eq_right h₁, ite_eq_right h₀, lookup]
+ cases code q t.head u.head <;> simp only [records, paths_advance]
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeAddressLogControl.lean b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogControl.lean
new file mode 100644
index 0000000000..0b8399653c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogControl.lean
@@ -0,0 +1,174 @@
+import OAI.Computability.VPVNP.RAMPrivateLog
+import OAI.Computability.VPVNP.RAMWordBits
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Finite bit-stack control for a private RAM write log
+
+Parallel streams store the newest-first addresses, values, and one occupancy
+bit per entry. The query stack itself sets the word width. Even width zero
+therefore permits distinct entries. Bits visited during lookup are saved and
+restored before return.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.AddressLog
+
+open BurstRAM BurstRAM.PrivateRAM
+
+/-- Stack labels for a private write-log lookup, including the address, result, three log
+streams, and five restoration stacks. -/
+inductive Port where
+ | query | out | keys | values | occupied | keySave | valueSave | querySave | countSave | resultSave
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Contents of the lookup stacks, with parallel streams for addresses, written values, and
+entry marks. -/
+structure Bank where
+ /-- Bits of the query address. Its length determines how many bits to read per log word. -/
+ q : List Bool
+ /-- Output stack onto which the lookup restores the selected value. -/
+ o : List Bool
+ /-- Address words of the private write log in newest-first order. -/
+ ks : List Bool
+ /-- Written values in the same entry order as the address stream. -/
+ vs : List Bool
+ /-- One occupancy mark per log entry, including entries with zero-width words. -/
+ marks : List Bool
+ /-- Address bits saved in reverse order during the lookup. -/
+ sk : List Bool
+ /-- Written-value bits saved for restoration after the scan. -/
+ sv : List Bool
+ /-- Query bits temporarily removed while comparing an address. -/
+ sq : List Bool
+ /-- Occupancy marks removed from entries already visited. -/
+ sm : List Bool
+ /-- Bits of the selected value staged for transfer to the output. -/
+ so : List Bool
+
+/-- Select the bit stack of a lookup bank by its port. -/
+def Bank.stacks (s : Bank) : Stacks Port
+ | .query => s.q
+ | .out => s.o
+ | .keys => s.ks
+ | .values => s.vs
+ | .occupied => s.marks
+ | .keySave => s.sk
+ | .valueSave => s.sv
+ | .querySave => s.sq
+ | .countSave => s.sm
+ | .resultSave => s.so
+
+/-- Replace the bit stack at one lookup port. -/
+def Bank.set (s : Bank) (p : Port) (x : List Bool) : Bank :=
+ match p with
+ | .query => {s with q := x}
+ | .out => {s with o := x}
+ | .keys => {s with ks := x}
+ | .values => {s with vs := x}
+ | .occupied => {s with marks := x}
+ | .keySave => {s with sk := x}
+ | .valueSave => {s with sv := x}
+ | .querySave => {s with sq := x}
+ | .countSave => {s with sm := x}
+ | .resultSave => {s with so := x}
+
+@[simp] theorem Bank.update_stacks (s : Bank) (p : Port) (x : List Bool) :
+ Function.update s.stacks p x = (s.set p x).stacks := by
+ funext k
+ cases p <;> cases k <;> rfl
+
+variable {w : ℕ}
+
+/-- Store every key in increasing order of bit significance. -/
+def keys (log : WriteLog w) : List Bool := log.flatMap fun e => wordBits e.1
+
+/-- Concatenate the bit encodings of the written values in log order. -/
+def values (log : WriteLog w) : List Bool := log.flatMap fun e => wordBits e.2
+
+/-- Initialize lookup with the query, output tail, encoded write log, one mark per entry, and
+empty restoration stacks. -/
+def bank (a : Word w) (out : List Bool) (log : WriteLog w) : Bank :=
+ ⟨wordBits a, out, keys log, values log, List.replicate log.length true, [], [], [], [], []⟩
+
+/-- The common rewind loop specializes to each saved stream. -/
+inductive Rewind where
+ | query | keys | values | marks | result
+ deriving DecidableEq
+
+instance : Fintype Rewind := derive_fintype% _
+
+/-- Finite lookup control for comparing keys, selecting a value or zero, and restoring the
+scanned stacks. -/
+inductive State where
+ | record | saveMark
+ | key (eq : Bool) | saveQ (eq b : Bool) | getK (eq b : Bool) | saveK (eq bit : Bool)
+ | value (hit : Bool) | putQ (hit b : Bool) | getV (hit : Bool) | saveV (hit bit : Bool)
+ | copyV (bit : Bool)
+ | zero | saveZeroQ (bit : Bool) | emitZero
+ | rewind (phase : Rewind) | put (phase : Rewind) (bit : Bool)
+ | done | reject
+ deriving DecidableEq, Fintype
+
+/-- Scratch port holding the reversed bits for the current restoration pass. -/
+def Rewind.src : Rewind → Port
+ | .query => .querySave | .keys => .keySave | .values => .valueSave
+ | .marks => .countSave | .result => .resultSave
+
+/-- Port that receives the bits restored in the current pass. -/
+def Rewind.dst : Rewind → Port
+ | .query => .query | .keys => .keys | .values => .values
+ | .marks => .occupied | .result => .out
+
+/-- Advance through restoration of the query, keys, values, occupancy marks, and result, then
+finish. -/
+def Rewind.next : Rewind → State
+ | .query => .rewind .keys | .keys => .rewind .values | .values => .rewind .marks
+ | .marks => .rewind .result | .result => .done
+
+/-- A load stops at the first matching full word. The key and value scans
+both have width determined by the query, independently of its numeric value. -/
+def loadCode : StackCode Port State
+ | .record => .pop .occupied fun | none => .zero | some true => .saveMark | some false => .reject
+ | .saveMark => .push .countSave true (.key true)
+ | .key eq => .pop .query fun | none => .value eq | some b => .saveQ eq b
+ | .saveQ eq b => .push .querySave b (.getK eq b)
+ | .getK eq b => .pop .keys fun | none => .reject | some d => .saveK (eq && (b == d)) d
+ | .saveK eq d => .push .keySave d (.key eq)
+ | .value hit => .pop .querySave fun
+ | none => if hit then .rewind .keys else .record
+ | some b => .putQ hit b
+ | .putQ hit b => .push .query b (.getV hit)
+ | .getV hit => .pop .values fun | none => .reject | some v => .saveV hit v
+ | .saveV hit v => .push .valueSave v (if hit then .copyV v else .value false)
+ | .copyV v => .push .resultSave v (.value true)
+ | .zero => .pop .query fun | none => .rewind .query | some b => .saveZeroQ b
+ | .saveZeroQ b => .push .querySave b .emitZero
+ | .emitZero => .push .resultSave false .zero
+ | .rewind phase => .pop phase.src fun | none => phase.next | some b => .put phase b
+ | .put phase b => .push phase.dst b (.rewind phase)
+ | .done => .halt true
+ | .reject => .halt false
+
+/-- Elementary instruction proofs can be stated directly in terms of a bank. -/
+theorem stepPush {Q : Type*} {code : StackCode Port Q} (s : Bank) {u v p b}
+ (h : code u = .push p b v) :
+ StackStep code u s.stacks v (s.set p (b :: s.stacks p)).stacks := by
+ simpa only [Bank.update_stacks] using StackStep.push (s := s.stacks) h
+
+theorem stepPop {Q : Type*} {code : StackCode Port Q} (s : Bank) {u p f}
+ (h : code u = .pop p f) :
+ StackStep code u s.stacks (f (s.stacks p).head?) (s.set p (s.stacks p).tail).stacks := by
+ simpa only [Bank.update_stacks] using StackStep.pop (s := s.stacks) h
+
+end RAMTape.AddressLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeAddressLogLoad.lean b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogLoad.lean
new file mode 100644
index 0000000000..45bb81553e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogLoad.lean
@@ -0,0 +1,187 @@
+import OAI.Computability.VPVNP.RAMTapeAddressLogRestore
+import OAI.Computability.VPVNP.RAMTapeAddressLogValues
+
+/-!
+# Private log lookup on a fixed finite bit-stack machine
+
+The scan compares each full address against the query, starting at the newest
+write. The first hit supplies the output. Exhaustion supplies a width-matched
+zero. Rewinding the consumed prefixes restores every occupied entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.AddressLog
+
+open BurstRAM BurstRAM.PrivateRAM
+
+variable {w : ℕ}
+
+/-- Split after the first matching entry, or after the entire log on a miss. -/
+def scanSplit (a : Word w) : WriteLog w → WriteLog w × WriteLog w
+ | [] => ([], [])
+ | (k, v) :: tail =>
+ if a = k then ([(k, v)], tail)
+ else let cut := scanSplit a tail; ((k, v) :: cut.1, cut.2)
+
+theorem scanSplit_append (a : Word w) (log : WriteLog w) :
+ (scanSplit a log).1 ++ (scanSplit a log).2 = log := by
+ induction log with
+ | nil => rfl
+ | cons e tail ih =>
+ obtain ⟨k, v⟩ := e
+ by_cases h : a = k <;> simp [scanSplit, h, ih]
+
+/-- Cost up to the rewind of the key stream. An unsuccessful final empty
+test includes making the zero result and restoring the query. -/
+def seekCost (a : Word w) : WriteLog w → ℕ
+ | [] => 5 * w + 3
+ | (k, _) :: tail => if a = k then 9 * w + 4 else 8 * w + 4 + seekCost a tail
+
+private def start (a : Word w) (log : WriteLog w) (s : Bank) : Bank :=
+ {s with
+ q := wordBits a, ks := keys log, vs := values log, marks := List.replicate log.length true,
+ sq := [], so := []}
+
+private def finish (a : Word w) (log : WriteLog w) (s : Bank) : Bank :=
+ let cut := scanSplit a log
+ {s with
+ q := wordBits a, ks := keys cut.2, vs := values cut.2, marks := List.replicate cut.2.length true,
+ sq := [], so := (wordBits (WriteLog.memory log a)).reverse,
+ sk := (keys cut.1).reverse ++ s.sk, sv := (values cut.1).reverse ++ s.sv,
+ sm := List.replicate cut.1.length true ++ s.sm}
+
+private theorem bit_comparison (a k : Word w) :
+ (wordBits a == wordBits k) = decide (a = k) := by
+ by_cases h : a = k
+ · simp [h]
+ · have hn : wordBits a ≠ wordBits k := fun eq => h ((RAMSerialization.wordBits w).injective
+ (List.ofFn_injective eq))
+ simp [h, hn]
+
+private theorem zero_bits : wordBits (0 : Word w) = List.replicate w false := by
+ rw [wordBits, ← List.ofFn_const]
+ exact congrArg List.ofFn (funext RAMSerialization.wordBits_zero)
+
+private def advanced (s : Bank) (k v : Word w) : Bank :=
+ {s with sk := (wordBits k).reverse ++ s.sk, sv := (wordBits v).reverse ++ s.sv, sm := true :: s.sm}
+
+private def afterEntry (a k v : Word w) (tail : WriteLog w) (s : Bank) : Bank :=
+ {start a tail (advanced s k v) with so := if a = k then (wordBits v).reverse else []}
+
+/-- One occupancy pop and push, one width-driven comparison, and one value scan. -/
+private theorem entryRun (a k v : Word w) (tail : WriteLog w) (s : Bank) :
+ StackRuns loadCode (if a = k then 9 * w + 4 else 8 * w + 4)
+ .record (start a ((k,v) :: tail) s).stacks
+ (if a = k then .rewind .keys else .record) (afterEntry a k v tail s).stacks := by
+ let st : Bank := {start a tail s with sm := true :: s.sm, vs := wordBits v ++ values tail}
+ have key := keyRuns true (wordBits a) (wordBits k) (keys tail) st (by simp)
+ simp only [length_wordBits, Bool.true_and, bit_comparison, st, start, List.append_nil] at key
+ let mid : Bank := {st with q := [], ks := keys tail, sk := (wordBits k).reverse ++ s.sk}
+ have val := valueRuns (decide (a = k)) (wordBits a).reverse (wordBits v) (values tail) mid (by simp)
+ simp only [List.length_reverse, length_wordBits, List.reverse_reverse, mid, st, start, List.append_nil,
+ decide_eq_true_eq] at val
+ have pair := key.trans val
+ have full : StackRuns loadCode ((4 * w + 1 + ((if a = k then 5 else 4) * w + 1)) + 1 + 1)
+ .record (start a ((k,v) :: tail) s).stacks
+ (if a = k then .rewind .keys else .record) (afterEntry a k v tail s).stacks :=
+ .cons (stepPop _ (show loadCode .record = _ from rfl))
+ (.cons (stepPush _ (show loadCode .saveMark = _ from rfl)) pair)
+ convert full using 1
+ split <;> omega
+
+private theorem seekRun (a : Word w) (log : WriteLog w) (s : Bank) :
+ StackRuns loadCode (seekCost a log) .record (start a log s).stacks
+ (.rewind .keys) (finish a log s).stacks := by
+ induction log generalizing s with
+ | nil =>
+ let st := start a [] s
+ have z := zeroRuns (wordBits a) st
+ simp only [st, start, length_wordBits, List.append_nil] at z
+ let mid : Bank := {st with q := [], sq := (wordBits a).reverse, so := List.replicate w false}
+ have restore := rewindRuns .query mid
+ change StackRuns loadCode (2 * (wordBits a).reverse.length + 1) (.rewind .query) mid.stacks
+ (.rewind .keys) ({mid with sq := [], q := (wordBits a).reverse.reverse ++ []} : Bank).stacks at restore
+ simp only [List.reverse_reverse, List.append_nil, List.length_reverse, length_wordBits] at restore
+ have run : StackRuns loadCode ((3 * w + 1 + (2 * w + 1)) + 1) .record st.stacks
+ (.rewind .keys) ({mid with sq := [], q := wordBits a} : Bank).stacks :=
+ .cons (stepPop _ (show loadCode .record = _ from rfl)) (z.trans restore)
+ rw [show 3 * w + 1 + (2 * w + 1) + 1 = 5 * w + 3 by omega] at run
+ simpa [st, mid, start, finish, scanSplit, keys, values, zero_bits, seekCost] using run
+ | cons e tail ih =>
+ obtain ⟨k,v⟩ := e
+ have one := entryRun a k v tail s
+ by_cases hit : a = k
+ · simp only [hit, ↓reduceIte] at one
+ simpa [hit, finish, scanSplit, seekCost, afterEntry, start, advanced, keys, values,
+ WriteLog.memory_cons] using one
+ · simp only [hit, ↓reduceIte, afterEntry] at one
+ have run := one.trans (ih (advanced s k v))
+ simp only [finish, scanSplit, hit, ↓reduceIte, WriteLog.memory_cons,
+ Function.update_of_ne hit, keys, values, List.flatMap_cons, List.reverse_append,
+ List.append_assoc, advanced, List.length_cons, List.replicate_succ', List.singleton_append,
+ seekCost] at run ⊢
+ exact run
+
+/-- The load includes rewinding the visited keys, values, occupancy marks and output. -/
+def loadCost (a : Word w) (log : WriteLog w) : ℕ :=
+ let n := (scanSplit a log).1.length
+ seekCost a log + (2 * (n * w + n * w + n + w) + 4)
+
+private theorem length_keys (log : WriteLog w) : (keys log).length = log.length * w := by
+ induction log with
+ | nil => simp [keys]
+ | cons e log ih => simp [keys, List.length_flatMap, Nat.succ_mul] at ih ⊢; omega
+
+private theorem length_values (log : WriteLog w) : (values log).length = log.length * w := by
+ induction log with
+ | nil => simp [values]
+ | cons e log ih => simp [values, List.length_flatMap, Nat.succ_mul] at ih ⊢; omega
+
+/-- A lookup preserves the query and the full log, clears its work stacks,
+and prepends the encoded result to the output port. -/
+theorem load_run (a : Word w) (out : List Bool) (log : WriteLog w) :
+ StackRuns loadCode (loadCost a log) .record (bank a out log).stacks
+ .done (bank a (wordBits (WriteLog.memory log a) ++ out) log).stacks := by
+ let s := bank a out log
+ have seek := seekRun a log s
+ have restore := restoreRuns (finish a log s)
+ have hkeys := congrArg keys (scanSplit_append a log)
+ have hvalues := congrArg values (scanSplit_append a log)
+ have hlen := congrArg List.length (scanSplit_append a log)
+ simp only [keys, List.flatMap_append] at hkeys
+ simp only [values, List.flatMap_append] at hvalues
+ simp only [List.length_append] at hlen
+ have run := seek.trans restore
+ simp only [s, bank, start, finish, loadCost, List.append_nil, List.length_reverse,
+ List.length_replicate, length_wordBits, length_keys, length_values, List.reverse_reverse,
+ List.reverse_replicate, ← List.replicate_add, hlen] at run ⊢
+ simpa only [keys, values, hkeys, hvalues] using run
+
+private theorem seekCost_le (a : Word w) (log : WriteLog w) :
+ seekCost a log ≤ (9 * w + 4) * log.length + (5 * w + 3) := by
+ induction log with
+ | nil => simp [seekCost]
+ | cons e log ih =>
+ obtain ⟨k,v⟩ := e
+ by_cases hit : a = k <;> simp [hit, seekCost, Nat.mul_succ] <;> omega
+
+/-- The time bound is linear in the length of the encoded log. -/
+theorem loadCost_le (a : Word w) (log : WriteLog w) :
+ loadCost a log ≤ (13 * w + 6) * log.length + (7 * w + 7) := by
+ have hs := seekCost_le a log
+ have he := congrArg List.length (scanSplit_append a log)
+ simp only [List.length_append] at he
+ have hn : (scanSplit a log).1.length ≤ log.length := by omega
+ have hw := Nat.mul_le_mul_right w hn
+ dsimp [loadCost]
+ rw [Nat.add_mul, Nat.mul_assoc, Nat.mul_comm w log.length] at hs ⊢
+ omega
+
+end RAMTape.AddressLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeAddressLogPhases.lean b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogPhases.lean
new file mode 100644
index 0000000000..00cd213219
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogPhases.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.RAMTapeAddressLogControl
+
+/-!
+# Exact runs for private-log comparison and restoration
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.AddressLog
+
+/-- Compare exactly one complete key, saving both bit streams. -/
+theorem keyRuns (eq : Bool) (qbits kbits tail : List Bool) (s : Bank)
+ (hlen : qbits.length = kbits.length) :
+ StackRuns loadCode (4 * qbits.length + 1) (.key eq)
+ ({s with q := qbits, ks := kbits ++ tail} : Bank).stacks (.value (eq && (qbits == kbits)))
+ ({s with q := [], ks := tail, sq := qbits.reverse ++ s.sq, sk := kbits.reverse ++ s.sk} : Bank).stacks := by
+ induction qbits generalizing eq kbits s with
+ | nil =>
+ have hk : kbits = [] := List.length_eq_zero_iff.mp hlen.symm
+ subst kbits
+ simp only [List.nil_append, List.reverse_nil, List.length_nil, Nat.mul_zero, Nat.zero_add,
+ beq_self_eq_true, Bool.and_true]
+ exact .cons (stepPop _ (show loadCode (.key eq) = _ from rfl)) (.nil ..)
+ | cons b bs ih =>
+ cases kbits with
+ | nil => simp at hlen
+ | cons d ds =>
+ let st : Bank := {s with sq := b :: s.sq, sk := d :: s.sk}
+ have rest := ih (eq && (b == d)) ds st (Nat.succ.inj hlen)
+ have first :
+ StackRuns loadCode (4 * bs.length + 1 + 1 + 1 + 1 + 1) (.key eq)
+ ({s with q := b :: bs, ks := d :: (ds ++ tail)} : Bank).stacks
+ (.value ((eq && (b == d)) && (bs == ds)))
+ ({st with q := [], ks := tail, sq := bs.reverse ++ st.sq, sk := ds.reverse ++ st.sk} : Bank).stacks :=
+ .cons (stepPop _ (show loadCode (.key eq) = _ from rfl))
+ (.cons (stepPush _ (show loadCode (.saveQ eq b) = _ from rfl))
+ (.cons (stepPop _ (show loadCode (.getK eq b) = _ from rfl))
+ (.cons (stepPush _ (show loadCode (.saveK (eq && (b == d)) d) = _ from rfl)) rest)))
+ simpa [st, List.reverse_cons, List.append_assoc, Nat.mul_succ, Nat.add_assoc,
+ Bool.and_assoc, List.beq_cons_cons] using first
+
+private def Rewind.pair (ph : Rewind) (s : Bank) (x y : List Bool) : Bank :=
+ (s.set ph.src x).set ph.dst y
+
+private theorem pair_src (ph : Rewind) (s : Bank) (x y : List Bool) :
+ (ph.pair s x y).stacks ph.src = x := by cases ph <;> rfl
+
+private theorem pair_dst (ph : Rewind) (s : Bank) (x y : List Bool) :
+ (ph.pair s x y).stacks ph.dst = y := by cases ph <;> rfl
+
+private theorem set_src (ph : Rewind) (s : Bank) (x y z : List Bool) :
+ (ph.pair s x y).set ph.src z = ph.pair s z y := by cases ph <;> rfl
+
+private theorem set_dst (ph : Rewind) (s : Bank) (x y z : List Bool) :
+ (ph.pair s x y).set ph.dst z = ph.pair s x z := by cases ph <;> rfl
+
+private theorem rewindPair (ph : Rewind) (s : Bank) (x y : List Bool) :
+ StackRuns loadCode (2 * x.length + 1) (.rewind ph) (ph.pair s x y).stacks
+ ph.next (ph.pair s [] (x.reverse ++ y)).stacks := by
+ induction x generalizing y with
+ | nil =>
+ have h := stepPop (ph.pair s [] y) (show loadCode (.rewind ph) = _ from rfl)
+ rw [pair_src, set_src] at h
+ exact .cons h (.nil ..)
+ | cons b bs ih =>
+ have h := stepPop (ph.pair s (b :: bs) y) (show loadCode (.rewind ph) = _ from rfl)
+ rw [pair_src, set_src] at h
+ have hp := stepPush (ph.pair s bs y) (show loadCode (.put ph b) = _ from rfl)
+ rw [pair_dst, set_dst] at hp
+ simpa only [List.length_cons, List.reverse_cons, List.append_assoc, List.cons_append,
+ List.nil_append, Nat.mul_succ, Nat.add_assoc] using StackRuns.cons h (.cons hp (ih (b :: y)))
+
+/-- Consume a saved stream and prepend its reverse to the corresponding live stream. -/
+theorem rewindRuns (ph : Rewind) (s : Bank) :
+ StackRuns loadCode (2 * (s.stacks ph.src).length + 1) (.rewind ph) s.stacks
+ ph.next ((s.set ph.src []).set ph.dst ((s.stacks ph.src).reverse ++ s.stacks ph.dst)).stacks := by
+ have h := rewindPair ph s (s.stacks ph.src) (s.stacks ph.dst)
+ have he : ph.pair s (s.stacks ph.src) (s.stacks ph.dst) = s := by cases ph <;> rfl
+ rwa [he] at h
+
+/-- Produce one zero bit per address bit on an unsuccessful search. -/
+theorem zeroRuns (bits : List Bool) (s : Bank) :
+ StackRuns loadCode (3 * bits.length + 1) .zero ({s with q := bits} : Bank).stacks
+ (.rewind .query)
+ ({s with q := [], sq := bits.reverse ++ s.sq, so := List.replicate bits.length false ++ s.so} : Bank).stacks := by
+ induction bits generalizing s with
+ | nil =>
+ exact .cons (stepPop _ (show loadCode .zero = _ from rfl)) (.nil ..)
+ | cons b bs ih =>
+ let st : Bank := {s with sq := b :: s.sq, so := false :: s.so}
+ have h : StackRuns loadCode (3 * bs.length + 1 + 1 + 1 + 1) .zero
+ ({s with q := b :: bs} : Bank).stacks (.rewind .query)
+ ({st with q := [], sq := bs.reverse ++ st.sq, so := List.replicate bs.length false ++ st.so} : Bank).stacks :=
+ .cons (stepPop _ (show loadCode .zero = _ from rfl))
+ (.cons (stepPush _ (show loadCode (.saveZeroQ b) = _ from rfl))
+ (.cons (stepPush _ (show loadCode .emitZero = _ from rfl)) (ih st)))
+ have rep : List.replicate bs.length false ++ false :: s.so =
+ List.replicate (bs.length + 1) false ++ s.so := by
+ rw [List.replicate_succ', List.append_assoc]
+ rfl
+ simpa only [st, rep, List.length_cons, List.reverse_cons, List.append_assoc, List.cons_append,
+ List.nil_append, Nat.mul_succ, Nat.add_assoc] using h
+
+end RAMTape.AddressLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeAddressLogRestore.lean b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogRestore.lean
new file mode 100644
index 0000000000..773861a773
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogRestore.lean
@@ -0,0 +1,35 @@
+import OAI.Computability.VPVNP.RAMTapeAddressLogPhases
+
+/-!
+# Rewinding the private write log
+
+A load returns the visited key bits, value bits, and occupancy markers to
+three independent streams. The final pass transfers the saved result onto
+the output stack. Each stream requires one empty test and two steps per bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.AddressLog
+
+/-- The four final rewind passes restore the log and deliver the read result. -/
+theorem restoreRuns (s : Bank) :
+ StackRuns loadCode (2 * (s.sk.length + s.sv.length + s.sm.length + s.so.length) + 4)
+ (.rewind .keys) s.stacks .done ({s with
+ ks := s.sk.reverse ++ s.ks, vs := s.sv.reverse ++ s.vs,
+ marks := s.sm.reverse ++ s.marks, o := s.so.reverse ++ s.o,
+ sk := [], sv := [], sm := [], so := []} : Bank).stacks := by
+ let k : Bank := {s with ks := s.sk.reverse ++ s.ks, sk := []}
+ let v : Bank := {k with vs := s.sv.reverse ++ s.vs, sv := []}
+ let m : Bank := {v with marks := s.sm.reverse ++ s.marks, sm := []}
+ have run := (((rewindRuns .keys s).trans (rewindRuns .values k)).trans
+ (rewindRuns .marks v)).trans (rewindRuns .result m)
+ convert run using 1 <;> first | rfl | (dsimp [Rewind.src, Bank.stacks, k, v, m]; omega)
+
+end RAMTape.AddressLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeAddressLogStore.lean b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogStore.lean
new file mode 100644
index 0000000000..cc13170e31
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogStore.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.RAMTapeAddressLogControl
+
+/-!
+# Prepending a private RAM write
+
+The forward pass transfers the address and value to two scratch stacks. The
+return pass restores the input words and pushes a copy of each bit onto the
+corresponding log stream, low bit first in the completed log. A final marker
+records the entry, including when both words have width zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.AddressLog
+
+open BurstRAM BurstRAM.PrivateRAM
+
+/-- States for saving the new address and value, restoring their input stacks, and prepending
+the write to the log. -/
+inductive StoreState where
+ | readKey | readValue (k : Bool) | saveKey (k v : Bool) | saveValue (v : Bool)
+ | restore | popValue (k : Bool) | restoreKey (k v : Bool) | restoreValue (k v : Bool)
+ | pushKey (k v : Bool) | pushValue (v : Bool) | mark | done | reject
+ deriving DecidableEq, Fintype
+
+/-- Stack instructions that prepend the address and value to the log and push an occupancy
+mark, including for zero-width words. -/
+def storeCode : StackCode Port StoreState
+ | .readKey => .pop .query fun | none => .restore | some k => .readValue k
+ | .readValue k => .pop .out fun | none => .reject | some v => .saveKey k v
+ | .saveKey k v => .push .keySave k (.saveValue v)
+ | .saveValue v => .push .valueSave v .readKey
+ | .restore => .pop .keySave fun | none => .mark | some k => .popValue k
+ | .popValue k => .pop .valueSave fun | none => .reject | some v => .restoreKey k v
+ | .restoreKey k v => .push .query k (.restoreValue k v)
+ | .restoreValue k v => .push .out v (.pushKey k v)
+ | .pushKey k v => .push .keys k (.pushValue v)
+ | .pushValue v => .push .values v .restore
+ | .mark => .push .occupied true .done
+ | .done => .halt true
+ | .reject => .halt false
+
+private abbrev StoreRun (n : ℕ) (q : StoreState) (s : Bank) (q' : StoreState) (t : Bank) :=
+ StackRuns storeCode n q s.stacks q' t.stacks
+
+local macro "store_step" : tactic => `(tactic|
+ first | refine StackRuns.cons (stepPop _ rfl) ?_ | refine StackRuns.cons (stepPush _ rfl) ?_)
+
+private theorem save_run (s : Bank) (q o sk sv : List Bool) (hlen : o.length = q.length) :
+ StoreRun (4 * q.length + 1) .readKey {s with q, o, sk, sv}
+ .restore {s with q := [], o := [], sk := q.reverse ++ sk, sv := o.reverse ++ sv} := by
+ induction q generalizing o sk sv with
+ | nil =>
+ obtain rfl : o = [] := List.length_eq_zero_iff.mp hlen
+ store_step
+ exact .nil ..
+ | cons k q ih =>
+ cases o with
+ | nil => simp at hlen
+ | cons v o =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ store_step
+ store_step
+ store_step
+ store_step
+ exact ih o (k :: sk) (v :: sv) (Nat.succ.inj hlen)
+
+private theorem restore_run (s : Bank) (sk sv q o ks vs : List Bool) (hlen : sv.length = sk.length) :
+ StoreRun (6 * sk.length + 2) .restore {s with q, o, sk, sv, ks, vs}
+ .done {s with
+ q := sk.reverse ++ q, o := sv.reverse ++ o, ks := sk.reverse ++ ks,
+ vs := sv.reverse ++ vs, marks := true :: s.marks, sk := [], sv := []} := by
+ induction sk generalizing sv q o ks vs with
+ | nil =>
+ obtain rfl : sv = [] := List.length_eq_zero_iff.mp hlen
+ store_step
+ store_step
+ exact .nil ..
+ | cons k sk ih =>
+ cases sv with
+ | nil => simp at hlen
+ | cons v sv =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ store_step
+ store_step
+ store_step
+ store_step
+ store_step
+ store_step
+ exact ih sv (k :: q) (v :: o) (k :: ks) (v :: vs) (Nat.succ.inj hlen)
+
+/-- A private store preserves the source words and realizes exactly one cons
+of the native newest-first `WriteLog`, in a number of steps independent of
+its previous length and of the numerical address. -/
+theorem store_run {w : ℕ} (a v : Word w) (log : WriteLog w) :
+ StackRuns storeCode (10 * w + 3) .readKey (bank a (wordBits v) log).stacks
+ .done (bank a (wordBits v) ((a, v) :: log)).stacks := by
+ let s := bank a (wordBits v) log
+ have hf := save_run s (wordBits a) (wordBits v) [] [] (by simp)
+ have hr := restore_run s (wordBits a).reverse (wordBits v).reverse [] [] (keys log) (values log) (by simp)
+ simp only [List.append_nil, List.reverse_reverse, List.length_reverse, length_wordBits] at hf hr
+ have run := hf.trans hr
+ rw [show (4 * w + 1) + (6 * w + 2) = 10 * w + 3 by omega] at run
+ simpa only [s, bank, keys, values, List.flatMap_cons, List.length_cons, List.replicate_succ] using run
+
+end RAMTape.AddressLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeAddressLogValues.lean b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogValues.lean
new file mode 100644
index 0000000000..f7d2c3f947
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeAddressLogValues.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.RAMTapeAddressLogControl
+
+/-!
+# Scanning a value during an addressed load
+
+Each saved query bit controls one iteration of the value scan. The loop
+restores the query while saving the value for the later log rewind. On a
+match, it also saves the result for delivery in its original bit order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.AddressLog
+
+local macro "value_step" : tactic => `(tactic|
+ first | refine StackRuns.cons (stepPop _ rfl) ?_
+ | refine StackRuns.cons (stepPush _ rfl) ?_)
+
+/-- The matched branch uses five instructions per bit. A miss omits the
+push to the result stack and uses four. The final empty test selects the
+next record on a miss and starts the log rewind on a match. -/
+theorem valueRuns (hit : Bool) (qbits vbits tail : List Bool) (s : Bank)
+ (len : qbits.length = vbits.length) :
+ StackRuns loadCode ((if hit then 5 else 4) * qbits.length + 1) (.value hit)
+ ({s with sq := qbits, vs := vbits ++ tail} : Bank).stacks
+ (if hit then .rewind .keys else .record)
+ ({s with
+ sq := [], vs := tail, q := qbits.reverse ++ s.q, sv := vbits.reverse ++ s.sv,
+ so := if hit then vbits.reverse ++ s.so else s.so} : Bank).stacks := by
+ induction qbits generalizing s vbits with
+ | nil =>
+ have hv : vbits = [] := List.length_eq_zero_iff.mp len.symm
+ subst vbits
+ cases hit <;> simp only [↓reduceIte, Bool.false_eq_true, List.length_nil, Nat.mul_zero,
+ Nat.zero_add, List.reverse_nil, List.nil_append] <;> value_step <;> exact .nil ..
+ | cons b qs ih =>
+ cases vbits with
+ | nil => simp at len
+ | cons v vs =>
+ have hlen : qs.length = vs.length := by simpa using len
+ cases hit
+ · simp only [Bool.false_eq_true, ↓reduceIte, List.length_cons, Nat.mul_succ]
+ value_step
+ value_step
+ value_step
+ value_step
+ simpa [Bank.set, Bank.stacks, List.append_assoc] using
+ ih vs {s with q := b :: s.q, sv := v :: s.sv} hlen
+ · simp only [↓reduceIte, List.length_cons, Nat.mul_succ]
+ value_step
+ value_step
+ value_step
+ value_step
+ value_step
+ simpa [Bank.set, Bank.stacks, List.append_assoc] using
+ ih vs {s with q := b :: s.q, sv := v :: s.sv, so := v :: s.so} hlen
+
+end RAMTape.AddressLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeBoundary.lean b/lean/OAI/Computability/VPVNP/RAMTapeBoundary.lean
new file mode 100644
index 0000000000..a41ddea02a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeBoundary.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.RAMTapeBoundaryRecord
+import OAI.Computability.VPVNP.RAMTapeBoundaryEnds
+import OAI.Computability.VPVNP.RAMTapeBoundaryDecision
+import Mathlib.Tactic.Linarith
+
+/-!
+# Finite stack execution of the local predecessor and last-record checks
+
+The sorted input is a contiguous sequence of five-word slots. Each interior
+endpoint contributes its raw five-word last-record field. The machine tests
+a clamped field for zero on missing edges. Width and slot count come from
+unary stacks. Every field loop takes the same number of instructions on
+arbitrary data, including after a failure has been latched.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Boundary
+
+open RAMBoundary
+
+variable {w : ℕ}
+
+private abbrev tally (n : ℕ) := List.replicate n true
+
+private theorem scanRows (hp hs : Bool) (previous sent : RawSlot w) (xs : List (RawSlot w)) (ok : Bool) :
+ let result := rows previous xs ok
+ StackRuns (code hp hs) (xs.length * (45*w+17)) (.next ok)
+ (store (blockBytes xs) (recordBytes previous) (recordBytes sent) (tally w) [] [] (tally xs.length))
+ (.next result.2) (store [] (recordBytes result.1) (recordBytes sent) (tally w) [] [] []) := by
+ induction xs generalizing previous ok with
+ | nil =>
+ simp only [rows, List.length_nil, Nat.zero_mul]
+ exact .nil ..
+ | cons current xs ih =>
+ let n := tally xs.length
+ let ok' := ok && checked (foldRecord previous current)
+ have hr := record_run hp hs .row ok previous current [] (blockBytes xs) (recordBytes sent) [] n
+ simp only [recordView, List.append_nil, ite_true] at hr
+ have ht := restoreSlot_runs hp hs .row ok' (blockBytes xs) [] (recordBytes sent) (tally w) []
+ (recordBytes current).reverse n
+ simp only [ite_true, List.reverse_reverse, List.append_nil, List.length_reverse, length_recordBytes] at ht
+ have hnext : StackRuns (code hp hs) 1 (.next ok)
+ (store (blockBytes (current :: xs)) (recordBytes previous) (recordBytes sent)
+ (tally w) [] [] (true :: n))
+ (.field .row 0 ok (.tick initial))
+ (store (recordBytes current ++ blockBytes xs) (recordBytes previous)
+ (recordBytes sent) (tally w) [] [] n) := by
+ refine .cons (.pop rfl) ?_
+ simp only [store, update_store, List.head?_cons, List.tail_cons, Option.elim_some]
+ exact .nil ..
+ have h := ((hnext.trans hr).trans ht).trans (ih current ok')
+ change StackRuns _ ((xs.length+1)*(45*w+17)) _ _ _ _
+ rw [show (xs.length+1)*(45*w+17) =
+ 1 + 5*(7*w+3) + (2*(5*w)+1) + xs.length*(45*w+17) by rw [Nat.add_mul, Nat.one_mul]; omega]
+ exact h
+
+private theorem finish (hp hs : Bool) (last sent : RawSlot w) (ok : Bool) :
+ StackRuns (code hp hs) (if hs then 45*w+17 else 5*w+2) (.next ok)
+ (store [] (recordBytes last) (recordBytes sent) (tally w) [] [] [])
+ (.done (ok && if hs then equalChecked (foldRecord last sent) else (recordBytes sent).all (!·)))
+ (store [] (recordBytes (if hs then sent else last)) [] (tally w) [] [] []) := by
+ cases hs with
+ | false =>
+ have h := checkSent_runs hp false ok [] (recordBytes last) (recordBytes sent) (tally w) [] [] []
+ simp only [length_recordBytes] at h
+ refine .cons (.pop rfl) ?_
+ simpa only [store, update_store, List.head?_nil, List.tail_nil, Option.elim_none,
+ Bool.false_eq_true, ite_false] using h
+ | true =>
+ let ok' := ok && equalChecked (foldRecord last sent)
+ have hr := record_run hp true .edge ok last sent [] [] [] [] []
+ simp only [recordView, List.append_nil, reduceCtorEq, ite_false] at hr
+ have ht := restoreSlot_runs hp true .edge ok' [] [] [] (tally w) [] (recordBytes sent).reverse []
+ simp only [reduceCtorEq, ite_false, List.reverse_reverse, List.append_nil, List.length_reverse,
+ length_recordBytes] at ht
+ have h := hr.trans ht
+ simp only [ite_true]
+ rw [show 45*w+17 = (5*(7*w+3)+(2*(5*w)+1))+1 by omega]
+ refine .cons (.pop rfl) ?_
+ simpa only [store, update_store, List.head?_nil, List.tail_nil, Option.elim_none, ite_true] using h
+
+private theorem start (hp hs : Bool) (previous sent : RawSlot w) (block slots : List Bool) :
+ let s := store block (recordBytes previous) (recordBytes sent) (tally w) [] [] slots
+ StackRuns (code hp hs) (1 + if hp then 0 else 20*w+2) .start s
+ (.next (hp || (recordBytes previous).all (!·))) s := by
+ cases hp with
+ | true => exact .cons (.goto rfl) (.nil ..)
+ | false =>
+ have h₁ := checkPrev_runs false hs true block (recordBytes previous) (recordBytes sent) (tally w) [] [] slots
+ simp only [length_recordBytes, Bool.true_and, List.append_nil] at h₁
+ have h₂ := restoreSlot_runs false hs .row ((recordBytes previous).all (!·)) block []
+ (recordBytes sent) (tally w) [] (recordBytes previous).reverse slots
+ simp only [ite_true, List.length_reverse, length_recordBytes, List.reverse_reverse, List.append_nil] at h₂
+ have h := h₁.trans h₂
+ simp only [Bool.false_eq_true, ite_false, Bool.false_or]
+ rw [show 1+(20*w+2) = (2*(5*w)+1+(2*(5*w)+1))+1 by omega]
+ exact .cons (.goto rfl) h
+
+/-- Exact number of elementary stack steps, independent of the record bits. -/
+def work (hasPredecessor hasSuccessor : Bool) (B w : ℕ) : ℕ :=
+ (1 + if hasPredecessor then 0 else 20*w+2) + B*(45*w+17) + if hasSuccessor then 45*w+17 else 5*w+2
+
+theorem work_le (hp hs : Bool) (B w : ℕ) : work hp hs B w ≤ 96*(B+1)*(w+1) := by
+ cases hp <;> cases hs <;> simp only [work, ite_true, Bool.false_eq_true, ite_false] <;>
+ nlinarith only [Nat.zero_le (B*w), Nat.zero_le B, Nat.zero_le w]
+
+/-- The concrete finite control starts with just the two endpoint fields,
+the sorted block, and two unary sizes. It implements all read, outgoing,
+and clamping checks. It consumes the sorted block and both scratch stacks
+finish empty. -/
+theorem runs (hp hs : Bool) (previous sent : RawSlot w) (xs : List (RawSlot w)) :
+ let result := rows previous xs (hp || (recordBytes previous).all (!·))
+ StackRuns (code hp hs) (work hp hs xs.length w) .start
+ (store (blockBytes xs) (recordBytes previous) (recordBytes sent) (List.replicate w true) [] []
+ (List.replicate xs.length true))
+ (.done (decision hp hs previous sent xs))
+ (store [] (recordBytes (if hs then sent else result.1)) [] (List.replicate w true) [] [] []) := by
+ let ok := hp || (recordBytes previous).all (!·)
+ let result := rows previous xs ok
+ exact ((start hp hs previous sent (blockBytes xs) (tally xs.length)).trans
+ (scanRows hp hs previous sent xs ok)).trans (finish hp hs result.1 sent result.2)
+
+/-- The deterministic pass contributes one accepting path exactly when
+the scanned fields pass. The final instruction reads the latched status. -/
+theorem path_count (hp hs : Bool) (previous sent : RawSlot w) (xs : List (RawSlot w)) :
+ stackPaths (code hp hs) (1 + work hp hs xs.length w) .start
+ (store (blockBytes xs) (recordBytes previous) (recordBytes sent) (List.replicate w true) [] []
+ (List.replicate xs.length true)) =
+ (decision hp hs previous sent xs).toNat := by
+ rw [(runs hp hs previous sent xs).paths 1]
+ rfl
+
+/-- On a site's actual parsed edge fields the terminal stack program has
+one accepting path precisely when the local `checkAt` predicate holds and
+the two missing endpoint fields, when present in the physical layout, are zero. -/
+theorem path_count_checkAt_iff {B S : ℕ} (hw : 2 ≤ w) (hB : 0 < B)
+ (messages : RAMBoundary.Sends S (BurstRAM.Word w)) (v : Fin S)
+ (previous sent : RawSlot w) (block : Fin B → RawSlot w)
+ (hprev : (RAMSort.parsedSlot hw previous).record = RAMBoundary.receive messages v)
+ (hsent : v.val+1 < S → (RAMSort.parsedSlot hw sent).record = RAMBoundary.outgoing messages v) :
+ let hp := decide (0 < v.val)
+ let hs := decide (v.val+1 < S)
+ stackPaths (code hp hs) (1 + work hp hs B w) .start
+ (store (blockBytes (List.ofFn block)) (recordBytes previous) (recordBytes sent)
+ (List.replicate w true) [] [] (List.replicate B true)) = 1 ↔
+ (v.val = 0 → (recordBytes previous).all (!·) = true) ∧
+ RAMBoundary.checkAt hB messages v (fun i ↦ (RAMSort.parsedSlot hw (block i)).record) ∧
+ (S ≤ v.val+1 → (recordBytes sent).all (!·) = true) := by
+ let hp := decide (0 < v.val)
+ let hs := decide (v.val+1 < S)
+ have hc := path_count hp hs previous sent (List.ofFn block)
+ simp only [List.length_ofFn] at hc
+ have hedges : (if hs then some (RAMSort.parsedSlot hw sent).record else none) =
+ (if v.val+1 < S then some (RAMBoundary.outgoing messages v) else none) := by
+ by_cases he : v.val+1 < S <;> simp [hs, he, hsent]
+ dsimp only
+ rw [hc, Bool.toNat_eq_one, decision_scan hw, hprev, hedges]
+ simp only [Bool.and_eq_true, Bool.or_eq_true, hp, hs, decide_eq_true_eq, RAMBoundary.scan_spec hB]
+ grind
+
+end RAMTape.Boundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeBoundaryBits.lean b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryBits.lean
new file mode 100644
index 0000000000..72304a56a3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryBits.lean
@@ -0,0 +1,322 @@
+import OAI.Computability.VPVNP.RAMTapeWord
+import OAI.Computability.VPVNP.RAMValidatorBoundaryWord
+import Mathlib.Tactic.DeriveFintype
+import Mathlib.Data.Fintype.Sigma
+
+/-!
+# Bit-by-bit checks of adjacent RAM records
+
+Two equal-width physical records are scanned together, from low to high bit
+within each of the five fields. The finite control recognizes the tag, tracks
+address and value equality, and tests the current value for zero. The same
+scan also tests complete-slot equality for an outgoing message.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Boundary
+
+open BurstRAM RAMMemory RAMSort RAMSerialization RAMBoundary TapeWord
+
+/-- Position in the tag scan, distinguishing the low bit, second bit, and remaining high bits. -/
+inductive TagPhase where
+ | low | second | high
+ deriving DecidableEq
+
+instance : Fintype TagPhase :=
+ ⟨{.low, .second, .high}, fun p ↦ by cases p <;> simp⟩
+
+/-- Finite summary of the two tags, field comparisons, and zero test accumulated while scanning
+adjacent records. -/
+structure Flags where
+ /-- Position of the next tag bit in the low, second, or high part of the word. -/
+ phase : TagPhase
+ /-- Running test that the predecessor tag denotes an occupied slot. -/
+ prevUsed : Bool
+ /-- Running test that the current tag denotes an occupied slot. -/
+ currUsed : Bool
+ /-- Running test that the current tag denotes a read. -/
+ currRead : Bool
+ /-- Whether all address-bit pairs compared so far agree. -/
+ addressEq : Bool
+ /-- Whether all value-bit pairs compared so far agree. -/
+ valueEq : Bool
+ /-- Whether every current value bit examined so far is zero. -/
+ currZero : Bool
+ /-- Whether every pair of record bits examined so far agrees. -/
+ allEqual : Bool
+ deriving DecidableEq
+
+set_option synthInstance.maxSize 4096 in
+deriving instance Fintype for Flags
+
+/-- Start at the low tag bit with empty comparisons and zero tests satisfied. -/
+def initial : Flags := ⟨.low, false, false, false, true, true, true, true⟩
+
+private def payload (j : Fin 5) (s : Flags) (eq zero : Bool) : Flags :=
+ {s with addressEq := if j = 1 then s.addressEq && eq else s.addressEq
+ valueEq := if j = 2 then s.valueEq && eq else s.valueEq
+ currZero := if j = 2 then s.currZero && zero else s.currZero
+ allEqual := s.allEqual && eq}
+
+private def highTag (s : Flags) (az bz eq : Bool) : Flags :=
+ {s with prevUsed := s.prevUsed && az, currUsed := s.currUsed && bz,
+ currRead := s.currRead && bz, allEqual := s.allEqual && eq}
+
+/-- One physical bit pair. After the first two tag bits, any set bit makes the
+corresponding tag invalid. This requires only three phases for every width. -/
+def stepField (j : Fin 5) (s : Flags) (a b : Bool) : Flags :=
+ if j = 0 then
+ match s.phase with
+ | .low => {s with phase := .second, prevUsed := a, currUsed := b, currRead := !b,
+ allEqual := s.allEqual && (a == b)}
+ | .second => {s with phase := .high, prevUsed := s.prevUsed || a, currUsed := s.currUsed || b,
+ currRead := s.currRead && b, allEqual := s.allEqual && (a == b)}
+ | .high => highTag s (!a) (!b) (a == b)
+ else payload j s (a == b) (!b)
+
+/-- Update the boundary flags from one pair of bits at the given field index. -/
+abbrev step := stepField
+
+/-- Fold a paired-bit update over two words until either stream ends. -/
+def foldWord (next : Flags → Bool → Bool → Flags) : Flags → List Bool → List Bool → Flags
+ | s, a :: as, b :: bs => foldWord next (next s a b) as bs
+ | s, _, _ => s
+
+/-- Compare the bits of a single field using its field-specific flag update. -/
+abbrev foldField (j : Fin 5) := foldWord (stepField j)
+
+@[simp] theorem foldField_nil (j : Fin 5) (s : Flags) (ys : List Bool) :
+ foldField j s [] ys = s := rfl
+
+theorem foldField_cons (j : Fin 5) (s : Flags) (a b : Bool) (xs ys : List Bool) :
+ foldField j s (a :: xs) (b :: ys) = foldField j (stepField j s a b) xs ys := rfl
+
+/-- Scan the specified field indices in order, passing each comparison’s flags to the next. -/
+def foldFields : List (Fin 5) → Flags → (Fin 5 → List Bool) → (Fin 5 → List Bool) → Flags
+ | [], s, _, _ => s
+ | j :: js, s, a, b => foldFields js (foldField j s (a j) (b j)) a b
+
+variable {w : ℕ}
+
+/-- The five fields of a physical slot, each encoded as a low-bit-first word. -/
+def recordWords (a : RawSlot w) : List (List Bool) := List.ofFn fun i ↦ BurstRAM.wordBits (a i)
+
+/-- Compare two complete physical slots from the initial flags in field order. -/
+def foldRecord (a b : RawSlot w) : Flags :=
+ foldFields (List.finRange 5) initial (fun i ↦ BurstRAM.wordBits (a i)) (fun i ↦ BurstRAM.wordBits (b i))
+
+/-- Accept a read if its value matches an occupied predecessor at the same address, or is zero
+when there is no such predecessor. -/
+def checked (s : Flags) : Bool :=
+ !s.currRead || (if s.prevUsed && s.addressEq then s.valueEq else s.currZero)
+
+/-- For an occupied predecessor require complete record equality. For an unused predecessor
+require an unused current slot. -/
+def equalChecked (s : Flags) : Bool := if s.prevUsed then s.allEqual else !s.currUsed
+
+private theorem same_cons (a b : Bool) (xs ys : List Bool) :
+ decide (a :: xs = b :: ys) = ((a == b) && decide (xs = ys)) := by
+ apply Bool.eq_iff_iff.mpr
+ simp
+
+private theorem zero_cons (a : Bool) (xs : List Bool) :
+ decide (value (a :: xs) = 0) = (!a && decide (value xs = 0)) := by
+ cases a <;> simp [value]
+
+private theorem payload_append (j : Fin 5) (s : Flags) (ae az be bz : Bool) :
+ payload j (payload j s ae az) be bz = payload j s (ae && be) (az && bz) := by
+ by_cases h₁ : j = 1 <;> by_cases h₂ : j = 2 <;> simp [payload, h₁, h₂, Bool.and_assoc]
+
+private theorem highTag_append (s : Flags) (az bz ae cz dz be : Bool) :
+ highTag (highTag s az bz ae) cz dz be = highTag s (az && cz) (bz && dz) (ae && be) := by
+ simp [highTag, Bool.and_assoc]
+
+private theorem fold_payload (j : Fin 5) (hj : j ≠ 0) (s : Flags) (xs ys : List Bool)
+ (hlen : xs.length = ys.length) :
+ foldField j s xs ys = payload j s (decide (xs = ys)) (decide (value ys = 0)) := by
+ induction xs generalizing ys s with
+ | nil =>
+ have : ys = [] := by simpa using hlen.symm
+ subst ys
+ simp [payload, value]
+ | cons a xs ih =>
+ cases ys with
+ | nil => simp at hlen
+ | cons b ys =>
+ rw [foldField_cons, ih _ _ (Nat.succ.inj hlen), same_cons, zero_cons]
+ simp only [stepField, hj, ite_false, payload_append]
+
+private theorem fold_high (s : Flags) (h : s.phase = .high) (xs ys : List Bool)
+ (hlen : xs.length = ys.length) : foldField 0 s xs ys =
+ highTag s (decide (value xs = 0)) (decide (value ys = 0)) (decide (xs = ys)) := by
+ induction xs generalizing ys s with
+ | nil =>
+ have : ys = [] := by simpa using hlen.symm
+ subst ys
+ simp [highTag, value]
+ | cons a xs ih =>
+ cases ys with
+ | nil => simp at hlen
+ | cons b ys =>
+ rw [foldField_cons, ih _ (by simp [stepField, h, highTag]) _ (Nat.succ.inj hlen),
+ same_cons, zero_cons, zero_cons]
+ simp only [stepField, h, ite_true, highTag_append]
+
+private theorem used_digits (lo hi : Bool) (n : ℕ) :
+ ((lo || hi) && decide (n = 0)) =
+ decide (0 < lo.toNat + 2 * (hi.toNat + 2 * n) ∧ lo.toNat + 2 * (hi.toNat + 2 * n) ≤ 3) := by
+ apply Bool.eq_iff_iff.mpr
+ cases lo <;> cases hi <;> simp <;> omega
+
+private theorem read_digits (lo hi : Bool) (n : ℕ) :
+ ((!lo && hi) && decide (n = 0)) = decide (lo.toNat + 2 * (hi.toNat + 2 * n) = 2) := by
+ apply Bool.eq_iff_iff.mpr
+ cases lo <;> cases hi <;> simp <;> omega
+
+private def tagSummary (a b : ℕ) (eq : Bool) : Flags :=
+ {initial with phase := .high, prevUsed := decide (0 < a ∧ a ≤ 3), currUsed := decide (0 < b ∧ b ≤ 3),
+ currRead := decide (b = 2), allEqual := eq}
+
+private theorem fold_tag (xs ys : List Bool) (hl : xs.length = ys.length) (hw : 2 ≤ xs.length) :
+ foldField 0 initial xs ys = tagSummary (value xs) (value ys) (decide (xs = ys)) := by
+ obtain ⟨a₀, a₁, xs, rfl⟩ : ∃ a₀ a₁ as, xs = a₀ :: a₁ :: as := by
+ cases xs with
+ | nil => simp at hw
+ | cons a as => cases as <;> simp_all; omega
+ obtain ⟨b₀, b₁, ys, rfl⟩ : ∃ b₀ b₁ bs, ys = b₀ :: b₁ :: bs := by
+ cases ys with
+ | nil => simp at hl
+ | cons b bs => cases bs <;> simp_all
+ rw [foldField_cons, foldField_cons, fold_high _ rfl _ _ (by simpa using hl)]
+ simp only [tagSummary, highTag, stepField, initial, ite_true, Bool.true_and, used_digits, read_digits,
+ value, same_cons]
+ simp only [Bool.and_assoc]
+ rfl
+
+private theorem wordBits_eq {a b : Word w} : BurstRAM.wordBits a = BurstRAM.wordBits b ↔ a = b := by
+ constructor
+ · intro h
+ apply Fin.ext
+ simpa only [value_wordBits] using congrArg value h
+ · rintro rfl
+ rfl
+
+private theorem fold_payload_word (j : Fin 5) (hj : j ≠ 0) (s : Flags) (a b : Word w) :
+ foldField j s (BurstRAM.wordBits a) (BurstRAM.wordBits b) =
+ payload j s (decide (a = b)) (decide (b.val = 0)) := by
+ rw [fold_payload _ hj _ _ _ (by simp), value_wordBits, decide_eq_decide.mpr wordBits_eq]
+
+private theorem fold_tag_word (hw : 2 ≤ w) (a b : Word w) :
+ foldField 0 initial (BurstRAM.wordBits a) (BurstRAM.wordBits b) =
+ tagSummary a.val b.val (decide (a = b)) := by
+ rw [fold_tag _ _ (by simp) (by simpa using hw), value_wordBits, value_wordBits,
+ decide_eq_decide.mpr wordBits_eq]
+
+private abbrev Used {w : ℕ} (a : RawSlot w) : Prop := 0 < (a 0).val ∧ (a 0).val ≤ 3
+
+private theorem used_tags {w : ℕ} {a : RawSlot w} (h : Used a) :
+ (a 0).val = 1 ∨ (a 0).val = 2 ∨ (a 0).val = 3 := by
+ unfold Used at h
+ omega
+
+private theorem unused_parse {w : ℕ} (hw : 2 ≤ w) (a : RawSlot w) (h : ¬Used a) :
+ (parsedSlot hw a).record = none := by
+ unfold Used at h
+ have h₁ : (a 0).val ≠ 1 := by omega
+ have h₂ : (a 0).val ≠ 2 := by omega
+ have h₃ : (a 0).val ≠ 3 := by omega
+ simp [parsedSlot, recordFormat]
+
+private theorem parsed_read_iff {w : ℕ} (hw : 2 ≤ w) (a b : RawSlot w) :
+ (readOK (parsedSlot hw a).record (parsedSlot hw b).record).1 = true ↔
+ ((b 0).val = 2 → (if Used a ∧ a 1 = b 1 then b 2 = a 2 else (b 2).val = 0)) := by
+ rw [readOK_spec]
+ by_cases hb : Used b
+ · rcases used_tags hb with ht | ht | ht
+ · simp [parsedSlot, recordFormat, WordRecord.record, ht]
+ · by_cases ha : Used a
+ · rcases used_tags ha with h | h | h <;> by_cases he : a 1 = b 1 <;>
+ simp [parsedSlot, recordFormat, WordRecord.record, ht, h, previousValue, he,
+ Fin.val_inj]
+ · rw [unused_parse hw a ha]
+ simp [parsedSlot, recordFormat, WordRecord.record, ht, previousValue, ha]
+ · simp [parsedSlot, recordFormat, WordRecord.record, ht]
+ · have ht : (b 0).val ≠ 2 := fun he ↦ hb (by simp [Used, he])
+ simp [unused_parse hw b hb, ht]
+
+private theorem fields_iff {w : ℕ} (a b : RawSlot w) (h : (a 0).val = (b 0).val) :
+ (a 1 = b 1 ∧ a 2 = b 2 ∧ a 3 = b 3 ∧ a 4 = b 4) ↔ a = b := by
+ constructor
+ · rintro ⟨h₁, h₂, h₃, h₄⟩
+ funext i
+ fin_cases i <;> first | exact Fin.ext h | assumption
+ · rintro rfl
+ simp
+
+private theorem parsed_equal_iff {w : ℕ} (hw : 2 ≤ w) (a b : RawSlot w) :
+ (equalSlot (parsedSlot hw a).record (parsedSlot hw b).record).1 = true ↔
+ if Used a then a = b else ¬Used b := by
+ rw [equalSlot_spec]
+ by_cases ha : Used a
+ · rw [ite_eq_left ha]
+ constructor
+ · intro he
+ by_cases hb : Used b
+ · rcases used_tags ha with ht | ht | ht <;> rcases used_tags hb with ht' | ht' | ht' <;>
+ simp [parsedSlot, recordFormat, WordRecord.record, ht, ht', Fin.val_inj] at he
+ all_goals exact (fields_iff a b (ht.trans ht'.symm)).1 he
+ · rw [unused_parse hw b hb] at he
+ rcases used_tags ha with ht | ht | ht <;> simp [parsedSlot, recordFormat, ht] at he
+ · rintro rfl
+ rfl
+ · rw [ite_eq_right ha, unused_parse hw a ha]
+ by_cases hb : Used b
+ · rcases used_tags hb with ht | ht | ht <;> simp [parsedSlot, recordFormat, ht]
+ · simp [unused_parse hw b hb, hb]
+
+private theorem complete_equal (a b : RawSlot w) :
+ ((((decide (a 0 = b 0) && decide (a 1 = b 1)) && decide (a 2 = b 2)) &&
+ decide (a 3 = b 3)) && decide (a 4 = b 4)) = decide (a = b) := by
+ apply Bool.eq_iff_iff.mpr
+ simp only [Bool.and_eq_true, decide_eq_true_eq, and_assoc]
+ constructor
+ · rintro ⟨h₀, hs⟩
+ exact (fields_iff a b (congrArg Fin.val h₀)).1 hs
+ · rintro rfl
+ simp
+
+private theorem foldRecord_summary (hw : 2 ≤ w) (a b : RawSlot w) :
+ foldRecord a b = ⟨.high, decide (Used a), decide (Used b), decide ((b 0).val = 2),
+ decide (a 1 = b 1), decide (a 2 = b 2), decide ((b 2).val = 0), decide (a = b)⟩ := by
+ rw [foldRecord, show List.finRange 5 = [0, 1, 2, 3, 4] from rfl]
+ simp only [foldFields, fold_tag_word hw, fold_payload_word 1 (by decide), fold_payload_word 2 (by decide),
+ fold_payload_word 3 (by decide), fold_payload_word 4 (by decide)]
+ simp [payload, tagSummary, initial, Used, complete_equal]
+
+/-- For arbitrary tuples, the read flag is precisely the word validator's decision. -/
+theorem checked_foldRecord (hw : 2 ≤ w) (a b : RawSlot w) :
+ checked (foldRecord a b) = (readOK (parsedSlot hw a).record (parsedSlot hw b).record).1 := by
+ apply Bool.eq_iff_iff.mpr
+ rw [parsed_read_iff, foldRecord_summary hw]
+ by_cases hr : (b 0).val = 2 <;> by_cases ha : Used a <;> by_cases he : a 1 = b 1 <;>
+ simp [checked, hr, ha, he, eq_comm (a := a 2)]
+
+/-- Complete-slot equality ignores the payload when both tags parse as empty. -/
+theorem equalChecked_foldRecord (hw : 2 ≤ w) (a b : RawSlot w) :
+ equalChecked (foldRecord a b) = (equalSlot (parsedSlot hw a).record (parsedSlot hw b).record).1 := by
+ apply Bool.eq_iff_iff.mpr
+ rw [parsed_equal_iff, foldRecord_summary hw]
+ change (if decide (Used a) then decide (a = b) else !decide (Used b)) = true ↔ _
+ by_cases ha : Used a
+ · rw [ite_eq_left (decide_eq_true ha), ite_eq_left ha, decide_eq_true_eq]
+ · rw [ite_eq_right (fun h ↦ ha (of_decide_eq_true h)), ite_eq_right ha]
+ simp only [Bool.not_eq_true', decide_eq_false_iff_not]
+
+end RAMTape.Boundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeBoundaryControl.lean b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryControl.lean
new file mode 100644
index 0000000000..60fc6b3403
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryControl.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.RAMTapeBoundaryField
+import OAI.Computability.VPVNP.RAMTapeBoundaryBits
+import OAI.Computability.VPVNP.RAMTapeStackLift
+
+/-!
+# The finite control for scanning sorted records and both endpoint fields
+
+At each record the previous and current bit streams pass through the same
+five field loops. The saved current bits are restored to the predecessor
+stack before the next record. At an outgoing interior edge the right-hand
+stream comes from the sent field. A missing edge requires all of its bits
+to be zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Boundary
+
+/-- Stack ports for the sorted block, predecessor, sent record, field width, saved bits, and
+slot count. -/
+inductive Port where
+ | block | previous | sent | width | widthBack | saved | slots
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Select an adjacent-row read check or an outgoing-edge equality check. -/
+inductive Mode where
+ | row | edge
+ deriving DecidableEq
+
+instance : Fintype Mode := derive_fintype% _
+
+/-- Control of the boundary pass, carrying accumulated validity through record scans,
+restoration, and endpoint checks. -/
+inductive Phase where
+ | start
+ | checkPrev (ok : Bool)
+ | keepPrev (ok bit : Bool)
+ | next (ok : Bool)
+ | field (mode : Mode) (index : Fin 5) (ok : Bool) (phase : Field.State Flags)
+ | restoreSlot (mode : Mode) (ok : Bool)
+ | putSlot (mode : Mode) (ok bit : Bool)
+ | checkSent (ok : Bool)
+ | done (ok : Bool)
+ deriving Fintype
+
+/-- Assemble the seven boundary stacks from their bit lists. -/
+def store (block previous sent width widthBack saved slots : List Bool) : Stacks Port
+ | .block => block
+ | .previous => previous
+ | .sent => sent
+ | .width => width
+ | .widthBack => widthBack
+ | .saved => saved
+ | .slots => slots
+
+/-- Route a field scanner to the predecessor on the left and to the block or sent field on the
+right according to the mode. -/
+def fieldPorts (m : Mode) : Field.Port → Port
+ | .width => .width
+ | .widthBack => .widthBack
+ | .left => .previous
+ | .right => if m = .row then .block else .sent
+ | .saved => .saved
+
+theorem fieldPorts_injective (m : Mode) : Function.Injective (fieldPorts m) := by
+ intro x y he
+ cases m <;> cases x <;> cases y <;> simp_all [fieldPorts]
+
+/-- Advance to the next of five fields, or latch the row or edge check and start restoring the
+slot. -/
+def afterField (m : Mode) (j : Fin 5) (ok : Bool) (f : Flags) : Phase :=
+ if h : j.val+1 < 5 then .field m ⟨j.val+1, h⟩ ok (.tick f)
+ else .restoreSlot m (ok && if m = .row then checked f else equalChecked f)
+
+/-- Choose one of four fixed controls using the site's endpoint flags.
+Neither the width nor the slot count occurs in the control type. -/
+def code (hasPredecessor hasSuccessor : Bool) : StackCode Port Phase
+ | .start => .goto (if hasPredecessor then .next true else .checkPrev true)
+ | .checkPrev ok => .pop .previous fun b ↦ b.elim (.restoreSlot .row ok) (fun x ↦ .keepPrev (ok && !x) x)
+ | .keepPrev ok x => .push .saved x (.checkPrev ok)
+ | .next ok => .pop .slots fun b ↦ b.elim
+ (if hasSuccessor then .field .edge 0 ok (.tick initial) else .checkSent ok)
+ (fun _ ↦ .field .row 0 ok (.tick initial))
+ | .field m j ok (.done f) => .goto (afterField m j ok f)
+ | .field m j ok q => (Field.code (stepField j) q).rename (fieldPorts m) (.field m j ok)
+ | .restoreSlot m ok => .pop .saved fun b ↦ b.elim (if m = .row then .next ok else .done ok)
+ (fun x ↦ .putSlot m ok x)
+ | .putSlot m ok x => .push .previous x (.restoreSlot m ok)
+ | .checkSent ok => .pop .sent fun b ↦ b.elim (.done ok) (fun x ↦ .checkSent (ok && !x))
+ | .done ok => .halt ok
+
+theorem update_store (b p s w r t n v : List Bool) (k : Port) :
+ Function.update (store b p s w r t n) k v = match k with
+ | .block => store v p s w r t n
+ | .previous => store b v s w r t n
+ | .sent => store b p v w r t n
+ | .width => store b p s v r t n
+ | .widthBack => store b p s w v t n
+ | .saved => store b p s w r v n
+ | .slots => store b p s w r t v := by
+ funext i
+ cases k <;> cases i <;> rfl
+
+end RAMTape.Boundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeBoundaryDecision.lean b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryDecision.lean
new file mode 100644
index 0000000000..8aa1a8c0be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryDecision.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.RAMTapeBoundaryBits
+import OAI.Computability.VPVNP.RAMValidatorBoundary
+
+/-!
+# Decision of the RAM boundary tape pass
+
+The pass retains the last physical record, including padding, and latches
+every read check. Missing predecessor and successor fields are checked bit
+by bit against zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Boundary
+
+open RAMBoundary RAMMemory RAMSort
+
+variable {w B : ℕ}
+
+/-- Flatten the five word encodings of one physical slot into its bit stream. -/
+def recordBytes (x : RawSlot w) : List Bool := (recordWords x).flatten
+
+/-- Concatenate the physical slot encodings in block order. -/
+def blockBytes (xs : List (RawSlot w)) : List Bool := xs.flatMap recordBytes
+
+@[simp] theorem length_recordBytes (x : RawSlot w) : (recordBytes x).length = 5 * w := by
+ simp [recordBytes, recordWords]
+ omega
+
+@[simp] theorem length_blockBytes (xs : List (RawSlot w)) :
+ (blockBytes xs).length = xs.length * (5 * w) := by
+ simp [blockBytes, List.length_flatMap]
+
+/-- Each visited record replaces the predecessor, even after a failed check. -/
+def rows (previous : RawSlot w) (records : List (RawSlot w)) (ok : Bool) : RawSlot w × Bool :=
+ match records with
+ | [] => (previous, ok)
+ | current :: rest => rows current rest (ok && checked (foldRecord previous current))
+
+/-- An interior send is compared with the last physical record. At either
+missing edge the transmitted bits must all be zero. -/
+def decision (hasPrev hasNext : Bool) (previous sent : RawSlot w)
+ (records : List (RawSlot w)) : Bool :=
+ let result := rows previous records (hasPrev || (recordBytes previous).all (!·))
+ result.2 && if hasNext then equalChecked (foldRecord result.1 sent) else (recordBytes sent).all (!·)
+
+private theorem rows_last (previous : RawSlot w) (records : List (RawSlot w)) (ok : Bool) :
+ (rows previous records ok).1 = records.getLast?.getD previous := by
+ induction records generalizing previous ok with
+ | nil => rfl
+ | cons current rest ih => simp [rows, ih, List.getLast?_cons]
+
+private theorem rows_check (hw : 2 ≤ w) (previous : RawSlot w) (records : List (RawSlot w))
+ (ok : Bool) :
+ (rows previous records ok).2 = true ↔ ok = true ∧
+ PaddedCheck (parsedSlot hw previous).record (records.map fun r ↦ (parsedSlot hw r).record) := by
+ induction records generalizing previous ok with
+ | nil => simp [rows, PaddedCheck]
+ | cons current rest ih =>
+ rw [rows, ih, Bool.and_eq_true, checked_foldRecord hw, readOK_spec, List.map_cons]
+ cases h : (parsedSlot hw current).record <;> simp [PaddedCheck, and_assoc]
+
+/-- The tape decision is the parsed-slot scan conjoined with a zero-bit
+test on each missing endpoint. The raw records may use any tag or payload. -/
+theorem decision_scan (hw : 2 ≤ w) (hasPrev hasNext : Bool) (previous sent : RawSlot w)
+ (block : Fin B → RawSlot w) :
+ decision hasPrev hasNext previous sent (List.ofFn block) =
+ ((hasPrev || (recordBytes previous).all (!·)) &&
+ (scan (parsedSlot hw previous).record (if hasNext then some (parsedSlot hw sent).record else none)
+ (fun i ↦ (parsedSlot hw (block i)).record)).1 &&
+ (hasNext || (recordBytes sent).all (!·))) := by
+ cases B with
+ | zero =>
+ cases hasNext with
+ | false =>
+ change (_ && _) = (_ && true && _)
+ simp [rows]
+ | true =>
+ change (_ && equalChecked (foldRecord previous sent)) =
+ (_ && (true && (equalSlot (parsedSlot hw sent).record (parsedSlot hw previous).record).1) && true)
+ apply Bool.eq_iff_iff.mpr
+ simp [rows, equalChecked_foldRecord hw, equalSlot_spec]
+ grind only
+ | succ b =>
+ have hB : 0 < b + 1 := Nat.succ_pos b
+ have hlast : (List.ofFn block).getLast? = some (block ⟨(b + 1) - 1, by omega⟩) := by
+ rw [List.getLast?_eq_some_getLast (mt List.ofFn_eq_nil_iff.mp (Nat.ne_of_gt hB)),
+ List.getLast_ofFn]
+ apply Bool.eq_iff_iff.mpr
+ simp only [decision, Bool.and_eq_true, rows_check hw, rows_last, hlast, Option.getD_some,
+ List.map_ofFn, Function.comp_def, scan_ok_iff hB]
+ cases hasNext <;> simp [equalChecked_foldRecord hw, equalSlot_spec, lastSlot, and_assoc]
+ grind only
+
+end RAMTape.Boundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeBoundaryEnds.lean b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryEnds.lean
new file mode 100644
index 0000000000..5ae368170c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryEnds.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.RAMTapeBoundaryControl
+
+/-!
+# Restoring a record and checking zero boundary messages
+
+The incoming edge check saves each inspected bit so that the usual restore
+loop reconstructs the predecessor. The outgoing edge check consumes its
+message. Each check accumulates the zero test in a single control bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Boundary
+
+local macro "boundary_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, update_store, List.head?_cons, List.tail_cons, List.head?_nil,
+ List.tail_nil, Option.elim_some, Option.elim_none])
+
+/-- Return the saved slot to the predecessor stack, reversing the order in
+which its bits were pushed during the scan. -/
+theorem restoreSlot_runs (hasPrev hasNext : Bool) (m : Mode) (ok : Bool)
+ (block previous sent width widthBack saved slots : List Bool) :
+ StackRuns (code hasPrev hasNext) (2 * saved.length + 1) (.restoreSlot m ok)
+ (store block previous sent width widthBack saved slots)
+ (if m = .row then .next ok else .done ok)
+ (store block (saved.reverse ++ previous) sent width widthBack [] slots) := by
+ induction saved generalizing previous with
+ | nil => boundary_step; exact .nil ..
+ | cons b bs ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ boundary_step
+ boundary_step
+ exact ih (b :: previous)
+
+/-- Check an incoming boundary message and save the inspected bits. -/
+theorem checkPrev_runs (hasPrev hasNext ok : Bool)
+ (block previous sent width widthBack saved slots : List Bool) :
+ StackRuns (code hasPrev hasNext) (2 * previous.length + 1) (.checkPrev ok)
+ (store block previous sent width widthBack saved slots)
+ (.restoreSlot .row (ok && previous.all (!·)))
+ (store block [] sent width widthBack (previous.reverse ++ saved) slots) := by
+ induction previous generalizing saved ok with
+ | nil =>
+ simp only [List.all_nil, Bool.and_true]
+ boundary_step
+ exact .nil ..
+ | cons b bs ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append, List.all_cons, ← Bool.and_assoc]
+ boundary_step
+ boundary_step
+ exact ih (ok && !b) (b :: saved)
+
+/-- Check an outgoing boundary message and consume its bit stream. -/
+theorem checkSent_runs (hasPrev hasNext ok : Bool)
+ (block previous sent width widthBack saved slots : List Bool) :
+ StackRuns (code hasPrev hasNext) (sent.length + 1) (.checkSent ok)
+ (store block previous sent width widthBack saved slots)
+ (.done (ok && sent.all (!·))) (store block previous [] width widthBack saved slots) := by
+ induction sent generalizing ok with
+ | nil =>
+ simp only [List.all_nil, Bool.and_true]
+ boundary_step
+ exact .nil ..
+ | cons b bs ih =>
+ simp only [List.length_cons, List.all_cons, ← Bool.and_assoc]
+ boundary_step
+ exact ih (ok && !b)
+
+end RAMTape.Boundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeBoundaryField.lean b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryField.lean
new file mode 100644
index 0000000000..5fdeccea6f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryField.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.RAMTapeStackLift
+import Mathlib.Tactic.DeriveFintype
+import Mathlib.Data.Fintype.Sigma
+import Mathlib.Data.Fintype.Sum
+
+/-!
+# Scanning one field of adjacent boundary records
+
+A unary stack determines the field width. The control reads one pair of bits
+per mark, saves the right bit, and moves the mark to a second stack. On reaching
+the end of the width stack, it restores all marks for the next field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Boundary.Field
+
+/-- Ports for two field streams, the unary width and its temporary copy, and saved right-hand
+bits. -/
+inductive Port where
+ | width | widthBack | left | right | saved
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Construct the field-scanner bank from the width, restoration, input, and saved-bit stacks. -/
+def store (width widthBack left right saved : List Bool) : Stacks Port
+ | .width => width
+ | .widthBack => widthBack
+ | .left => left
+ | .right => right
+ | .saved => saved
+
+/-- Field-scanning control carrying a comparison accumulator through paired reads, bit saving,
+and width restoration. -/
+inductive State (F : Type*) where
+ | tick (f : F)
+ | readLeft (f : F)
+ | readRight (f : F) (a : Bool)
+ | save (f : F) (b : Bool)
+ | mark (f : F)
+ | rewindWidth (f : F)
+ | restoreMark (f : F)
+ | done (f : F)
+ | reject
+ deriving DecidableEq, Fintype
+
+variable {F : Type*} (step : F → Bool → Bool → F)
+
+/-- Consume one bit pair per width mark, apply the comparison update, save the right bit, and
+restore the width for the next field. -/
+def code : StackCode Port (State F)
+ | .tick f => .pop .width fun x => x.elim (.rewindWidth f) fun _ => .readLeft f
+ | .readLeft f => .pop .left fun x => x.elim .reject (.readRight f)
+ | .readRight f a => .pop .right fun x => x.elim .reject fun b => .save (step f a b) b
+ | .save f b => .push .saved b (.mark f)
+ | .mark f => .push .widthBack true (.tick f)
+ | .rewindWidth f => .pop .widthBack fun x => x.elim (.done f) fun _ => .restoreMark f
+ | .restoreMark f => .push .width true (.rewindWidth f)
+ | .done _ => .halt true
+ | .reject => .halt false
+
+/-- Apply the field comparison update to consecutive bit pairs until either list ends. -/
+def fold : F → List Bool → List Bool → F
+ | f, a :: xs, b :: ys => fold (step f a b) xs ys
+ | f, _, _ => f
+
+private theorem update_width (w v l r s u : List Bool) :
+ Function.update (store w v l r s) .width u = store u v l r s := by
+ funext p; cases p <;> rfl
+
+private theorem update_back (w v l r s u : List Bool) :
+ Function.update (store w v l r s) .widthBack u = store w u l r s := by
+ funext p; cases p <;> rfl
+
+private theorem update_left (w v l r s u : List Bool) :
+ Function.update (store w v l r s) .left u = store w v u r s := by
+ funext p; cases p <;> rfl
+
+private theorem update_right (w v l r s u : List Bool) :
+ Function.update (store w v l r s) .right u = store w v l u s := by
+ funext p; cases p <;> rfl
+
+private theorem update_saved (w v l r s u : List Bool) :
+ Function.update (store w v l r s) .saved u = store w v l r u := by
+ funext p; cases p <;> rfl
+
+private theorem readPair (f : F) (a b : Bool) (w v l r s : List Bool) :
+ StackRuns (code step) 5 (.tick f) (store (true :: w) v (a :: l) (b :: r) s)
+ (.tick (step f a b)) (store w (true :: v) l r (b :: s)) := by
+ refine .cons (.pop rfl) ?_
+ simp only [store, List.head?_cons, List.tail_cons, Option.elim_some, update_width]
+ refine .cons (.pop rfl) ?_
+ simp only [store, List.head?_cons, List.tail_cons, Option.elim_some, update_left]
+ refine .cons (.pop rfl) ?_
+ simp only [store, List.head?_cons, List.tail_cons, Option.elim_some, update_right]
+ refine .cons (.push rfl) ?_
+ simp only [store, update_saved]
+ refine .cons (.push rfl) ?_
+ simp only [store, update_back]
+ exact .nil ..
+
+private theorem collect (f : F) (xs ys l r s : List Bool) (n : ℕ)
+ (h : xs.length = ys.length) :
+ StackRuns (code step) (5 * xs.length + 1) (.tick f)
+ (store (List.replicate xs.length true) (List.replicate n true) (xs ++ l) (ys ++ r) s)
+ (.rewindWidth (fold step f xs ys))
+ (store [] (List.replicate (xs.length + n) true) l r (ys.reverse ++ s)) := by
+ induction xs generalizing f ys n s with
+ | nil =>
+ have hy : ys = [] := List.length_eq_zero_iff.mp h.symm
+ subst ys
+ simp only [List.length_nil, List.replicate_zero, List.nil_append, Nat.zero_add, Nat.mul_zero,
+ List.reverse_nil, fold]
+ refine .cons (.pop rfl) ?_
+ simp only [store, List.head?_nil, List.tail_nil, Option.elim_none, update_width]
+ exact .nil ..
+ | cons a xs ih =>
+ cases ys with
+ | nil => simp at h
+ | cons b ys =>
+ have h₁ := readPair step f a b (List.replicate xs.length true) (List.replicate n true)
+ (xs ++ l) (ys ++ r) s
+ have h₂ := ih (step f a b) ys (b :: s) (n+1) (Nat.succ.inj h)
+ rw [List.replicate_succ (n := n)] at h₂
+ simpa [List.replicate_succ, fold, Nat.mul_add, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm,
+ List.reverse_cons, List.append_assoc] using h₁.trans h₂
+
+private theorem rewind (f : F) (n : ℕ) (w l r s : List Bool) :
+ StackRuns (code step) (2 * n + 1) (.rewindWidth f) (store w (List.replicate n true) l r s)
+ (.done f) (store (List.replicate n true ++ w) [] l r s) := by
+ induction n generalizing w with
+ | zero =>
+ refine .cons (.pop rfl) ?_
+ simp only [store, List.replicate_zero, List.head?_nil, List.tail_nil, Option.elim_none, update_back,
+ List.nil_append]
+ exact .nil ..
+ | succ n ih =>
+ have hh : 2 * (n + 1) + 1 = (2 * n + 1 + 1) + 1 := by omega
+ rw [hh, List.replicate_succ]
+ refine .cons (.pop rfl) ?_
+ simp only [store, List.head?_cons, List.tail_cons, Option.elim_some, update_back]
+ refine .cons (.push rfl) ?_
+ simp only [store, update_width]
+ have hr := ih (true :: w)
+ rw [← List.singleton_append (x := true), ← List.append_assoc, ← List.replicate_succ'] at hr
+ exact hr
+
+/-- A field of width `xs.length` takes five instructions per pair and two per
+restored mark. The two additional pops detect the ends of the width stacks. -/
+theorem runs (f : F) (xs ys leftTail rightTail saved : List Bool) (h : xs.length = ys.length) :
+ StackRuns (code step) (7 * xs.length + 2) (.tick f)
+ (store (List.replicate xs.length true) [] (xs ++ leftTail) (ys ++ rightTail) saved)
+ (.done (fold step f xs ys))
+ (store (List.replicate xs.length true) [] leftTail rightTail (ys.reverse ++ saved)) := by
+ have h₁ := collect step f xs ys leftTail rightTail saved 0 h
+ have h₂ := rewind step (fold step f xs ys) xs.length [] leftTail rightTail (ys.reverse ++ saved)
+ simp only [List.replicate_zero, Nat.add_zero] at h₁
+ simp only [List.append_nil] at h₂
+ exact (show 5 * xs.length + 1 + (2 * xs.length + 1) = 7 * xs.length + 2 by omega) ▸ h₁.trans h₂
+
+end RAMTape.Boundary.Field
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeBoundaryRecord.lean b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryRecord.lean
new file mode 100644
index 0000000000..81382b4b01
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeBoundaryRecord.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.RAMTapeBoundaryControl
+import OAI.Computability.VPVNP.RAMTapeBoundaryDecision
+
+/-!
+# Scanning the five fields of a boundary record
+
+The same field subroutine serves both the adjacent-row check and the outgoing
+edge check. After the fifth return the saved stack contains the whole current
+record in reverse order, ready for restoration as the next predecessor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Boundary
+
+open RAMBoundary
+
+/-- In row mode the right stream is the remaining block. In edge mode it is
+the outgoing message. The other stream is left untouched by the field pass. -/
+def recordView (m : Mode) (left right other width widthBack saved slots : List Bool) : Stacks Port :=
+ match m with
+ | .row => store right left other width widthBack saved slots
+ | .edge => store other left right width widthBack saved slots
+
+private theorem install_recordView (m : Mode) (left right other width widthBack saved slots : List Bool) :
+ installStacks (fieldPorts m) (recordView m [] [] other [] [] [] slots)
+ (Field.store width widthBack left right saved) =
+ recordView m left right other width widthBack saved slots := by
+ funext k
+ by_cases hk : ∃ j, fieldPorts m j = k
+ · obtain ⟨j, rfl⟩ := hk
+ rw [installStacks_at (fieldPorts_injective m)]
+ cases m <;> cases j <;> rfl
+ · rw [installStacks_outside _ _ (not_exists.mp hk)]
+ cases m <;> cases k <;> first
+ | rfl
+ | exact (hk ⟨.left, rfl⟩).elim
+ | exact (hk ⟨.right, rfl⟩).elim
+ | exact (hk ⟨.width, rfl⟩).elim
+ | exact (hk ⟨.widthBack, rfl⟩).elim
+ | exact (hk ⟨.saved, rfl⟩).elim
+
+private theorem field_fold (j : Fin 5) (f : Flags) (xs ys : List Bool) :
+ Field.fold (stepField j) f xs ys = foldField j f xs ys := by
+ induction xs generalizing f ys with
+ | nil => rfl
+ | cons x xs ih =>
+ cases ys with
+ | nil => rfl
+ | cons y ys => exact ih _ _
+
+private theorem field_run (hasPrev hasNext : Bool) (m : Mode) (j : Fin 5) (ok : Bool)
+ (f : Flags) {w : ℕ} (a b : RawSlot w) (leftTail rightTail other saved slots : List Bool) :
+ StackRuns (code hasPrev hasNext) (7*w+3) (.field m j ok (.tick f))
+ (recordView m (BurstRAM.wordBits (a j) ++ leftTail) (BurstRAM.wordBits (b j) ++ rightTail)
+ other (List.replicate w true) [] saved slots)
+ (afterField m j ok (foldField j f (BurstRAM.wordBits (a j)) (BurstRAM.wordBits (b j))))
+ (recordView m leftTail rightTail other (List.replicate w true) []
+ ((BurstRAM.wordBits (b j)).reverse ++ saved) slots) := by
+ have h := Field.runs (stepField j) f (BurstRAM.wordBits (a j)) (BurstRAM.wordBits (b j))
+ leftTail rightTail saved (by simp)
+ have linked := h.lift (target := code hasPrev hasNext) (fieldPorts m) (fieldPorts_injective m)
+ (.field m j ok) (recordView m [] [] other [] [] [] slots) (by
+ intro q hq
+ cases q <;> first | rfl | contradiction)
+ simp only [BurstRAM.length_wordBits, install_recordView, field_fold] at linked
+ exact linked.trans (.cons (.goto rfl) (.nil ..))
+
+private theorem recordBytes_fields {w : ℕ} (a : RawSlot w) :
+ recordBytes a = BurstRAM.wordBits (a 0) ++ (BurstRAM.wordBits (a 1) ++
+ (BurstRAM.wordBits (a 2) ++ (BurstRAM.wordBits (a 3) ++ BurstRAM.wordBits (a 4)))) := by
+ rw [recordBytes, recordWords, List.ofFn_succ, List.ofFn_succ, List.ofFn_succ,
+ List.ofFn_succ, List.ofFn_succ, List.ofFn_zero]
+ simp only [List.flatten_cons, List.flatten_nil, List.append_nil]
+ rfl
+
+/-- A whole record takes five field scans, including one continuation jump
+per field. The last continuation chooses the check for the active mode. -/
+theorem record_run (hasPrev hasNext : Bool) (m : Mode) (ok : Bool) {w : ℕ}
+ (a b : RawSlot w) (leftTail rightTail other saved slots : List Bool) :
+ StackRuns (code hasPrev hasNext) (5 * (7*w+3)) (.field m 0 ok (.tick initial))
+ (recordView m (recordBytes a ++ leftTail) (recordBytes b ++ rightTail)
+ other (List.replicate w true) [] saved slots)
+ (.restoreSlot m (ok && if m = .row then checked (foldRecord a b) else equalChecked (foldRecord a b)))
+ (recordView m leftTail rightTail other (List.replicate w true) []
+ ((recordBytes b).reverse ++ saved) slots) := by
+ let n := 7*w+3
+ rw [show 5 * (7*w+3) = n + (n + (n + (n + n))) by omega]
+ simp only [recordBytes_fields, List.append_assoc, List.reverse_append, foldRecord,
+ show List.finRange 5 = [0, 1, 2, 3, 4] from rfl, foldFields]
+ refine (field_run hasPrev hasNext m 0 ok initial a b _ _ other saved slots).trans ?_
+ refine (field_run hasPrev hasNext m 1 ok _ a b _ _ other _ slots).trans ?_
+ refine (field_run hasPrev hasNext m 2 ok _ a b _ _ other _ slots).trans ?_
+ refine (field_run hasPrev hasNext m 3 ok _ a b _ _ other _ slots).trans ?_
+ exact field_run hasPrev hasNext m 4 ok _ a b leftTail rightTail other _ slots
+
+end RAMTape.Boundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeCeilLog.lean b/lean/OAI/Computability/VPVNP/RAMTapeCeilLog.lean
new file mode 100644
index 0000000000..c26c1655b6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeCeilLog.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.RAMTapeCeilLogCost
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Data.Fintype.Sum
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# A finite stack control for the physical site address width
+
+The source stack holds the input length in unary. A round consumes pairs
+of marks, returning one mark per pair, including a final singleton. Every
+round with at least two source marks prepends a fixed number of output
+marks. The last round consumes zero or one source mark and returns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.CeilLog
+
+/-- Stack labels for the unary length, its rounded half, and accumulated address-width marks. -/
+inductive Port where
+ | src | tmp | out
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Control of the repeated ceiling-halving rounds, with a finite counter for the fixed output
+marks per nontrivial round. -/
+inductive Phase (B : ℕ) where
+ | scan | second | firstHalf
+ | pair | save | skip
+ | emit (marks : Fin (B+1))
+ | transfer | put | done
+ deriving DecidableEq, Fintype
+
+/-- Each nontrivial round emits the fixed `B` bits. The changing count is
+stored in unary on the stacks. -/
+def code (B : ℕ) : StackCode Port (Phase B)
+ | .scan => .pop .src fun b ↦ b.elim .done (fun _ ↦ .second)
+ | .second => .pop .src fun b ↦ b.elim .done (fun _ ↦ .firstHalf)
+ | .firstHalf => .push .tmp true .pair
+ | .pair => .pop .src fun b ↦ b.elim (.emit (Fin.last B)) (fun _ ↦ .save)
+ | .save => .push .tmp true .skip
+ | .skip => .pop .src fun b ↦ b.elim (.emit (Fin.last B)) (fun _ ↦ .pair)
+ | .emit i => if h : i.val = 0 then .goto .transfer
+ else .push .out true (.emit ⟨i.val - 1, by have := i.isLt; omega⟩)
+ | .transfer => .pop .tmp fun b ↦ b.elim .scan (fun _ ↦ .put)
+ | .put => .push .src true .transfer
+ | .done => .halt true
+
+/-- Place the supplied bit lists on the length, intermediate, and width-output stacks. -/
+def store (src tmp out : List Bool) : Stacks Port
+ | .src => src
+ | .tmp => tmp
+ | .out => out
+
+private abbrev ones (n : ℕ) := List.replicate n true
+
+private theorem update_store (x t o v : List Bool) (k : Port) :
+ Function.update (store x t o) k v = match k with
+ | .src => store v t o
+ | .tmp => store x v o
+ | .out => store x t v := by
+ funext i
+ cases k <;> cases i <;> simp [store]
+
+local macro "stack_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_store])
+
+private theorem pairs_run (B n : ℕ) (t o : List Bool) :
+ StackRuns (code B) (n + (n+1)/2 + 1) .pair (store (ones n) t o)
+ (.emit (Fin.last B)) (store [] (ones ((n+1)/2) ++ t) o) := by
+ induction n using Nat.twoStepInduction generalizing t with
+ | zero => stack_step; exact .nil ..
+ | one => stack_step; stack_step; stack_step; exact .nil ..
+ | more n ih _ =>
+ have hhalf : (n+2+1)/2 = (n+1)/2 + 1 := by omega
+ rw [hhalf, show n+2+((n+1)/2+1)+1 = (n+(n+1)/2+1)+1+1+1 by omega]
+ change StackRuns _ _ _ (store (true :: true :: ones n) t o) _ _
+ stack_step
+ stack_step
+ stack_step
+ simpa only [ones, List.replicate_succ', List.append_assoc, List.singleton_append] using
+ ih (true :: t)
+
+private theorem emit_run (B : ℕ) (k : ℕ) (hk : k ≤ B) (t o : List Bool) :
+ StackRuns (code B) (k+1) (.emit ⟨k, by omega⟩) (store [] t o)
+ .transfer (store [] t (ones k ++ o)) := by
+ induction k generalizing o with
+ | zero => exact .cons (.goto (by simp [code])) (.nil ..)
+ | succ k ih =>
+ have h : code B (.emit ⟨k+1, by omega⟩) = .push .out true (.emit ⟨k, by omega⟩) := by
+ simp [code]
+ refine .cons (.push h) ?_
+ simpa only [ones, store, update_store, List.replicate_succ', List.append_assoc, List.singleton_append]
+ using ih (by omega) (true :: o)
+
+private theorem transfer_run (B k : ℕ) (x o : List Bool) :
+ StackRuns (code B) (2*k+1) .transfer (store x (ones k) o) .scan (store (ones k ++ x) [] o) := by
+ induction k generalizing x with
+ | zero => stack_step; exact .nil ..
+ | succ k ih =>
+ simp only [Nat.mul_succ]
+ change StackRuns _ _ _ (store x (true :: ones k) o) _ _
+ stack_step
+ stack_step
+ simpa only [ones, List.replicate_succ', List.append_assoc, List.singleton_append] using ih (true :: x)
+
+private theorem round_run (B n : ℕ) (o : List Bool) :
+ let m := (n+2+1)/2
+ StackRuns (code B) (n+2 + 3*m + B + 3) .scan (store (ones (n+2)) [] o)
+ .scan (store (ones m) [] (ones B ++ o)) := by
+ let m := (n+2+1)/2
+ have hp := pairs_run B n [true] o
+ have hstack : ones ((n+1)/2) ++ [true] = ones m := by
+ rw [show m = (n+1)/2+1 by dsimp [m]; omega]
+ exact List.replicate_succ'.symm
+ rw [hstack] at hp
+ have he := emit_run B B le_rfl (ones m) o
+ have ht := transfer_run B m [] (ones B ++ o)
+ rw [List.append_nil] at ht
+ have h := (hp.trans he).trans ht
+ change StackRuns _ (n+2+3*m+B+3) _ (store (true :: true :: ones n) [] o) _ _
+ rw [show n+2+3*m+B+3 = ((n+(n+1)/2+1 + (B+1)) + (2*m+1))+1+1+1 by dsimp [m]; omega]
+ stack_step
+ stack_step
+ stack_step
+ exact h
+
+/-- The output stack receives exactly the site's address width
+`B * Nat.clog 2 n` in unary. The source and temporary stacks finish empty.
+The exact instruction count is `cost B n`, bounded by `cost_le`. -/
+theorem runs (B n : ℕ) (out : List Bool) :
+ StackRuns (code B) (cost B n) .scan (store (List.replicate n true) [] out)
+ .done (store [] [] (List.replicate (B * Nat.clog 2 n) true ++ out)) := by
+ induction n using Nat.strong_induction_on generalizing out with
+ | h n ih =>
+ match n with
+ | 0 =>
+ simp only [cost_zero, Nat.clog_zero_right, Nat.mul_zero, List.replicate_zero, List.nil_append]
+ stack_step
+ exact .nil ..
+ | 1 =>
+ simp only [cost_one, Nat.clog_one_right, Nat.mul_zero, List.replicate_zero, List.nil_append]
+ stack_step
+ stack_step
+ exact .nil ..
+ | n + 2 =>
+ let m := (n+2+1)/2
+ have h := (round_run B n out).trans (ih m (by dsimp [m]; omega) (ones B ++ out))
+ rw [cost_step B (by omega : 2 ≤ n+2), clog_step (by omega : 2 ≤ n+2), Nat.mul_succ,
+ List.replicate_add (B * Nat.clog 2 m) B, List.append_assoc]
+ exact h
+
+end RAMTape.CeilLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeCeilLogCost.lean b/lean/OAI/Computability/VPVNP/RAMTapeCeilLogCost.lean
new file mode 100644
index 0000000000..b9b52fedf3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeCeilLogCost.lean
@@ -0,0 +1,58 @@
+import Mathlib.Data.Nat.Log
+
+/-!
+# Cost of computing the ceiling binary logarithm on a unary tape
+
+Each round pairs the remaining marks, keeps a mark for an unpaired last one,
+outputs `B` marks, and transfers the shortened tally for the next round.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.CeilLog
+
+theorem clog_step {n : ℕ} (hn : 2 ≤ n) :
+ Nat.clog 2 n = Nat.clog 2 ((n + 1) / 2) + 1 := by
+ simpa using Nat.clog_of_two_le (by decide : 1 < 2) hn
+
+/-- Count the unary scan, pair emission, fixed output and return transfer. -/
+def roundCost (B n : ℕ) : ℕ := n + 3 * ((n + 1) / 2) + B + 3
+
+/-- The stopping tests take one instruction on an empty tally and two on a singleton. -/
+def cost (B n : ℕ) : ℕ :=
+ if _h : 2 ≤ n then roundCost B n + cost B ((n + 1) / 2) else n + 1
+termination_by n
+decreasing_by omega
+
+@[simp] theorem cost_zero (B : ℕ) : cost B 0 = 1 := by rw [cost, dite_eq_right (by decide)]
+
+@[simp] theorem cost_one (B : ℕ) : cost B 1 = 2 := by rw [cost, dite_eq_right (by decide)]
+
+theorem cost_step (B : ℕ) {n : ℕ} (hn : 2 ≤ n) :
+ cost B n = roundCost B n + cost B ((n + 1) / 2) := by
+ rw [cost, dite_eq_left hn]
+
+/-- For fixed output width the total instruction count is linear in the initial tally. -/
+theorem cost_le (B n : ℕ) : cost B n ≤ (B + 32) * (n + 1) := by
+ induction n using Nat.strong_induction_on with
+ | h n ih =>
+ by_cases hn : 2 ≤ n
+ · have hhalf : (n + 1) / 2 < n := by omega
+ have hB : B * ((n + 1) / 2 + 1) + B ≤ B * (n + 1) := by
+ rw [← Nat.mul_succ]
+ exact Nat.mul_le_mul_left B (by omega)
+ rw [cost_step B hn]
+ calc
+ _ ≤ roundCost B n + (B + 32) * ((n + 1) / 2 + 1) :=
+ Nat.add_le_add_left (ih _ hhalf) _
+ _ ≤ (B + 32) * (n + 1) := by simp only [roundCost, Nat.add_mul]; omega
+ · rw [cost, dite_eq_right hn]
+ exact Nat.le_mul_of_pos_left _ (by omega)
+
+end RAMTape.CeilLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeCharges.lean b/lean/OAI/Computability/VPVNP/RAMTapeCharges.lean
new file mode 100644
index 0000000000..e2f599a133
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeCharges.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.RAMTapeChargesControl
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-!
+# Precharging startup, probes and instruction dispatch
+
+The local verifier pays for a dispatch before reading a program row, and
+pays for each call startup or probe before using any read guesses or writing
+a probe record. Failed checks enter the rejecting halt. The normal charge
+decrements both unary allowances and the binary global allowance and
+increments the binary cumulative cost.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Charges
+
+open BurstRAM TapeWord
+
+variable {w : ℕ}
+
+private abbrev marks (n : ℕ) := List.replicate n true
+
+/-- The instruction, call and site caps have one mark per remaining unit.
+The global allowance and cumulative cost each occupy exactly one word. -/
+def bank (fuel call site : ℕ) (g c : Word w) : Stacks Port :=
+ (Data.mk (marks fuel) (marks call) (marks site) (wordBits g) (wordBits c) []).stacks
+
+theorem dispatchRun (fuel call site : ℕ) (g c : Word w) :
+ StackRuns code 1 .dispatch (bank (fuel+1) call site g c) .done (bank fuel call site g c) := by
+ exact prepend rfl (.nil ..)
+
+theorem dispatchReject (call site : ℕ) (g c : Word w) :
+ StackRuns code 1 .dispatch (bank 0 call site g c) .reject (bank 0 call site g c) := by
+ exact prepend rfl (.nil ..)
+
+private theorem enterScan (fuel call site : ℕ) (g c : Word w) :
+ StackRuns code 2 .charge (bank fuel (call + 1) (site + 1) g c)
+ (.scan false true) (bank fuel call site g c) := by
+ exact prepend rfl (prepend rfl (.nil ..))
+
+private theorem chargeGlobal (fuel call site : ℕ) (g c : Word w) (hg : 0 < g.val) :
+ StackRuns code (4*w+2) (.scan false true) (bank fuel call site g c)
+ (.scan true true) (bank fuel call site (prevWord g) c) := by
+ have h := adjustRun false true (wordBits g) (marks fuel) (marks call) (marks site) (wordBits c)
+ simp only [length_wordBits, adjust_dec_word g hg] at h
+ exact h
+
+/-- The successful path takes exactly two unary pops and two linear binary
+updates. Startup and probes have the same one-unit effect on these caps. -/
+theorem chargeRun (fuel call site : ℕ) (g c : Word w)
+ (hg : 0 < g.val) (hc : c.val + 1 < 2 ^ w) :
+ StackRuns code (8*w+6) .charge (bank fuel (call+1) (site+1) g c) .done
+ (bank fuel call site (prevWord g) ⟨c.val + 1, hc⟩) := by
+ have hup := adjustRun true true (wordBits c) (marks fuel) (marks call) (marks site)
+ (wordBits (prevWord g))
+ simp only [length_wordBits, adjust_inc_word c hc] at hup
+ rw [show 8*w+6 = 2 + (4*w+2) + (4*w+2) by omega]
+ exact ((enterScan fuel call site g c).trans (chargeGlobal fuel call site g c hg)).trans hup
+
+/-- The first failed allowance determines where execution stops. A final
+overflow after both unary pops and the global decrement takes the full cost. -/
+def failureTicks (call site : ℕ) (g : Word w) : ℕ :=
+ if call = 0 then 1 else if site = 0 then 2 else if g.val = 0 then 4*w+4 else 8*w+6
+
+theorem failureTicks_le (call site : ℕ) (g : Word w) : failureTicks call site g ≤ 8*w+6 := by
+ unfold failureTicks
+ split <;> (try split) <;> (try split) <;> omega
+
+/-- Every exhausted budget and every cost overflow reaches the actual
+rejecting row, with the exact stopping cost of the precharge. -/
+theorem chargeReject (fuel call site : ℕ) (g c : Word w)
+ (hbad : call = 0 ∨ site = 0 ∨ g.val = 0 ∨ 2 ^ w ≤ c.val + 1) :
+ ∃ out, StackRuns code (failureTicks call site g) .charge (bank fuel call site g c) .reject out := by
+ cases call with
+ | zero => exact ⟨_, prepend rfl (.nil ..)⟩
+ | succ a =>
+ cases site with
+ | zero => exact ⟨_, prepend rfl (prepend rfl (.nil ..))⟩
+ | succ s =>
+ have h0 := enterScan fuel a s g c
+ by_cases hg : g.val = 0
+ · have hf := (adjust_borrow_iff (wordBits g)).mpr (by simpa only [value_wordBits] using hg)
+ have h := adjustRun false true (wordBits g) (marks fuel) (marks a) (marks s) (wordBits c)
+ simp only [hf, length_wordBits] at h
+ refine ⟨(scanData false (marks fuel) (marks a) (marks s) (wordBits c)
+ (adjust false true (wordBits g)).1 []).stacks, ?_⟩
+ simp only [failureTicks, Nat.succ_ne_zero, hg, ↓reduceIte]
+ rw [
+ show 4*w+4 = 2 + (4*w+2) by omega]
+ exact h0.trans h
+ · have hc : 2 ^ w ≤ c.val + 1 := by omega
+ have hf := (adjust_overflow_iff (wordBits c)).mpr (by simpa only [value_wordBits, length_wordBits] using hc)
+ have h := adjustRun true true (wordBits c) (marks fuel) (marks a) (marks s)
+ (wordBits (prevWord g))
+ simp only [hf, length_wordBits] at h
+ refine ⟨(scanData true (marks fuel) (marks a) (marks s) (wordBits (prevWord g))
+ (adjust true true (wordBits c)).1 []).stacks, ?_⟩
+ simp only [failureTicks, Nat.succ_ne_zero, hg, ↓reduceIte]
+ rw [
+ show 8*w+6 = 2 + (4*w+2) + (4*w+2) by omega]
+ exact (h0.trans (chargeGlobal fuel a s g c (by omega))).trans h
+
+/-- Redirect the successful halt to a normal return while keeping the
+rejecting halt and all stack updates on the named ports. -/
+def routine {K : Type} (ports : Port → K) (entry : State) : FiniteRoutine K :=
+ FiniteRoutine.ofStackCode code ports entry (fun q => decide (q = .done))
+
+/-- Lifting also covers an execution ending at the rejecting control state.
+Every port outside the image of `ports` keeps its initial stack. -/
+theorem liftRun {K : Type} [DecidableEq K] {ports : Port → K} (hp : Function.Injective ports)
+ (base : Stacks K) {n : ℕ} {entry exit : State} (he : entry ≠ .done)
+ {s t : Stacks Port} (hr : StackRuns code n entry s exit t) :
+ StackRuns (routine ports entry).body.standalone n (some entry) (installStacks ports base s)
+ (if exit = .done then none else some exit) (installStacks ports base t) := by
+ let labels (q : State) := if q = .done then none else some q
+ have hc (q : State) (hn : (code q).returns = false) :
+ (routine ports entry).body.standalone (labels q) = (code q).rename ports labels := by
+ have hq : q ≠ .done := by rintro rfl; contradiction
+ simp [routine, FiniteRoutine.ofStackCode, FiniteRoutine.ofRoutine, Routine.standalone,
+ Routine.close, labels, hq]
+ have h := hr.lift ports hp labels base hc
+ rw [show labels entry = some entry by simp [labels, he]] at h
+ exact h
+
+@[simp] theorem routine_rejects {K : Type} (ports : Port → K) (entry : State) :
+ (routine ports entry).body.standalone (some .reject) = .halt false := rfl
+
+end RAMTape.Charges
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeChargesControl.lean b/lean/OAI/Computability/VPVNP/RAMTapeChargesControl.lean
new file mode 100644
index 0000000000..6c57d67f39
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeChargesControl.lean
@@ -0,0 +1,171 @@
+import OAI.Computability.VPVNP.RAMTapeChargesValue
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Finite control for metering RAM calls and probes
+
+One dispatch removes one unary fuel mark. Starting a call and taking a probe
+use the same charge entry: remove a call mark and a site mark, subtract one
+from the binary global allowance, and increment the binary cumulative cost.
+No branch of the control iterates to the numerical value of a binary word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Charges
+
+/-- Stack labels for dispatch fuel, call and site credits, binary global and cumulative
+counters, and arithmetic scratch. -/
+inductive Port where
+ | fuel | call | site | globalLeft | cost | tmp
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Metering control for dispatch, unary credit removal, binary carry or borrow, and counter
+restoration. -/
+inductive State where
+ | dispatch | charge | site
+ | scan (up carry : Bool) | emit (up bit carry : Bool)
+ | restore (up overflow : Bool) | put (up bit overflow : Bool)
+ | done | reject
+ deriving DecidableEq, Fintype
+
+/-- Reject overflow after restoration, finish after incrementing cost, or begin incrementing
+cost after decrementing the global budget. -/
+def resume (up overflow : Bool) : State :=
+ if overflow then .reject else if up then .done else .scan true true
+
+/-- Meter a dispatch by one fuel mark, or charge a call or probe against the call, site,
+global, and cumulative counters. -/
+def code : StackCode Port State
+ | .dispatch => .pop .fuel (fun | none => .reject | some _ => .done)
+ | .charge => .pop .call (fun | none => .reject | some _ => .site)
+ | .site => .pop .site (fun | none => .reject | some _ => .scan false true)
+ | .scan up carry => .pop (if up then .cost else .globalLeft)
+ (fun | none => .restore up carry | some b => .emit up (b ^^ carry) (nextCarry up carry b))
+ | .emit up bit carry => .push .tmp bit (.scan up carry)
+ | .restore up overflow => .pop .tmp
+ (fun | none => resume up overflow | some b => .put up b overflow)
+ | .put up bit overflow => .push (if up then .cost else .globalLeft) bit (.restore up overflow)
+ | .done => .halt true
+ | .reject => .halt false
+
+/-- Contents of the unary allowances, binary charge counters, and scratch stack used by the
+metering control. -/
+structure Data where
+ /-- Unary instruction fuel, with one mark removed for each dispatch. -/
+ fuel : List Bool
+ /-- Remaining unary charge marks for the current call. -/
+ call : List Bool
+ /-- Remaining unary charge marks for the site. -/
+ site : List Bool
+ /-- Binary global allowance decremented by one per charge. -/
+ globalLeft : List Bool
+ /-- Binary cumulative cost incremented by one per charge. -/
+ cost : List Bool
+ /-- Reversed output bits saved while updating a binary counter. -/
+ tmp : List Bool
+
+/-- Read a metering stack from its named counter or scratch field. -/
+def Data.stacks (s : Data) : Stacks Port
+ | .fuel => s.fuel
+ | .call => s.call
+ | .site => s.site
+ | .globalLeft => s.globalLeft
+ | .cost => s.cost
+ | .tmp => s.tmp
+
+/-- Update a single metering stack in the charge bank. -/
+def Data.set (s : Data) : Port → List Bool → Data
+ | .fuel, x => {s with fuel := x}
+ | .call, x => {s with call := x}
+ | .site, x => {s with site := x}
+ | .globalLeft, x => {s with globalLeft := x}
+ | .cost, x => {s with cost := x}
+ | .tmp, x => {s with tmp := x}
+
+theorem Data.set_stacks (s : Data) (i : Port) (xs : List Bool) :
+ (s.set i xs).stacks = Function.update s.stacks i xs := by
+ funext j
+ cases i <;> cases j <;> rfl
+
+/-- A continuing deterministic transition. Halting states have no successor. -/
+def tick (q : State) (s : Data) : Option (State × Data) :=
+ match code q with
+ | .pop k f => some (f (s.stacks k).head?, s.set k (s.stacks k).tail)
+ | .push k b next => some (next, s.set k (b :: s.stacks k))
+ | .goto next => some (next, s)
+ | .choose _ _ | .halt _ => none
+
+/-- An execution of the charge controller between two states and banks in exactly the given
+number of stack steps. -/
+abbrev Run (n : ℕ) (q : State) (s : Data) (q' : State) (t : Data) :=
+ StackRuns code n q s.stacks q' t.stacks
+
+theorem prepend {q q' q'' : State} {s t u : Data} {n : ℕ}
+ (h : tick q s = some (q', t)) (hr : Run n q' t q'' u) : Run (n + 1) q s q'' u := by
+ apply StackRuns.cons _ hr
+ unfold tick at h
+ cases hc : code q with
+ | push k b next =>
+ rw [hc] at h
+ cases h
+ rw [Data.set_stacks]
+ exact .push hc
+ | pop k f =>
+ rw [hc] at h
+ cases h
+ rw [Data.set_stacks]
+ exact .pop hc
+ | goto next => rw [hc] at h; cases h; exact .goto hc
+ | choose | halt => simp [hc] at h
+
+/-- Choose the active binary counter without disturbing the other counter. -/
+def scanData (up : Bool) (f a s other bits tmp : List Bool) : Data :=
+ if up then ⟨f,a,s,other,bits,tmp⟩ else ⟨f,a,s,bits,other,tmp⟩
+
+private theorem firstPass (up carry : Bool) (bits tmp f a s other : List Bool) :
+ let t := adjust up carry bits
+ Run (2 * bits.length + 1) (.scan up carry) (scanData up f a s other bits tmp)
+ (.restore up t.2) (scanData up f a s other [] (t.1.reverse ++ tmp)) := by
+ induction bits generalizing tmp carry with
+ | nil => cases up <;> exact prepend rfl (.nil ..)
+ | cons b bits ih =>
+ dsimp only
+ rw [adjust_cons]
+ simp only [List.reverse_cons, List.append_assoc, List.singleton_append, List.length_cons, Nat.mul_succ]
+ have h := ih (nextCarry up carry b) ((b ^^ carry) :: tmp)
+ cases up <;> exact prepend rfl (prepend rfl h)
+
+private theorem restorePass (up overflow : Bool) (tmp bits f a s other : List Bool) :
+ Run (2 * tmp.length + 1) (.restore up overflow) (scanData up f a s other bits tmp)
+ (resume up overflow) (scanData up f a s other (tmp.reverse ++ bits) []) := by
+ induction tmp generalizing bits with
+ | nil => cases up <;> exact prepend rfl (.nil ..)
+ | cons b tmp ih =>
+ simp only [List.reverse_cons, List.append_assoc, List.singleton_append, List.length_cons, Nat.mul_succ]
+ have h := ih (b :: bits)
+ cases up <;> exact prepend rfl (prepend rfl h)
+
+/-- Exact runtime of the binary update, with overflow and underflow flags
+preserved all the way to the terminating control decision. -/
+theorem adjustRun (up carry : Bool) (bits f a s other : List Bool) :
+ let t := adjust up carry bits
+ Run (4 * bits.length + 2) (.scan up carry) (scanData up f a s other bits [])
+ (resume up t.2) (scanData up f a s other t.1 []) := by
+ have h := firstPass up carry bits [] f a s other
+ have hr := restorePass up (adjust up carry bits).2 (adjust up carry bits).1.reverse [] f a s other
+ simp only [List.append_nil] at h
+ simp only [List.length_reverse, adjust_length, List.reverse_reverse, List.append_nil] at hr
+ convert h.trans hr using 1
+ omega
+
+end RAMTape.Charges
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeChargesValue.lean b/lean/OAI/Computability/VPVNP/RAMTapeChargesValue.lean
new file mode 100644
index 0000000000..5ed83d467a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeChargesValue.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+
+/-!
+# Single-unit arithmetic for binary charge counters
+
+A charge subtracts one from the remaining global budget and adds one to
+the cumulative cost. The carry or borrow beyond the high bit detects every
+overflow or underflow, including in a zero-width counter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Charges
+
+open TapeWord BurstRAM
+
+/-- Propagate a carry through a set bit when incrementing, or a borrow through a zero bit when
+decrementing. -/
+def nextCarry (up carry bit : Bool) : Bool := carry && (if up then bit else !bit)
+
+/-- Ripple one incoming unit up or down across the little-endian bits. -/
+def adjust (up carry : Bool) (bits : List Bool) : List Bool × Bool :=
+ scan (if up then addBit else subBit) carry bits (List.replicate bits.length false)
+
+@[simp] theorem adjust_nil (up carry : Bool) : adjust up carry [] = ([], carry) := rfl
+
+theorem adjust_cons (up carry bit : Bool) (bits : List Bool) :
+ adjust up carry (bit :: bits) =
+ let t := adjust up (nextCarry up carry bit) bits
+ ((bit ^^ carry) :: t.1, t.2) := by
+ cases up <;> cases carry <;> cases bit <;> rfl
+
+@[simp] theorem adjust_length (up carry : Bool) (bits : List Bool) :
+ (adjust up carry bits).1.length = bits.length :=
+ length_scan _ _ _ _ (by simp)
+
+theorem adjust_up_spec (carry : Bool) (bits : List Bool) :
+ value (adjust true carry bits).1 + 2 ^ bits.length * (adjust true carry bits).2.toNat =
+ value bits + carry.toNat := by
+ simpa only [adjust, ↓reduceIte, value_zeros, Nat.add_zero] using
+ addScan_spec (c := carry) (x := bits) (y := List.replicate bits.length false) (by simp)
+
+theorem adjust_down_spec (carry : Bool) (bits : List Bool) :
+ value (adjust false carry bits).1 + carry.toNat =
+ value bits + 2 ^ bits.length * (adjust false carry bits).2.toNat := by
+ simpa only [adjust, Bool.false_eq_true, ↓reduceIte, value_zeros, Nat.add_zero] using
+ subScan_spec (c := carry) (x := bits) (y := List.replicate bits.length false) (by simp)
+
+theorem adjust_borrow_iff (bits : List Bool) :
+ (adjust false true bits).2 = true ↔ value bits = 0 := by
+ have h := adjust_down_spec true bits
+ have hb := value_lt (adjust false true bits).1
+ rw [adjust_length] at hb
+ cases hflag : (adjust false true bits).2 <;>
+ simp only [hflag, Bool.toNat_false, Bool.toNat_true, Nat.mul_zero, Nat.add_zero, Nat.mul_one] at h <;>
+ simp <;> omega
+
+theorem adjust_overflow_iff (bits : List Bool) :
+ (adjust true true bits).2 = true ↔ 2 ^ bits.length ≤ value bits + 1 := by
+ have h := adjust_up_spec true bits
+ have hb := value_lt (adjust true true bits).1
+ rw [adjust_length] at hb
+ cases hflag : (adjust true true bits).2 <;>
+ simp only [hflag, Bool.toNat_false, Bool.toNat_true, Nat.mul_zero, Nat.add_zero, Nat.mul_one] at h <;>
+ simp <;> omega
+
+variable {w : ℕ}
+
+/-- The predecessor cost word. At zero the borrow flag rejects the charge. -/
+def prevWord (x : Word w) : Word w := ⟨x.val - 1, (Nat.sub_le ..).trans_lt x.isLt⟩
+
+theorem adjust_dec_word (x : Word w) (hx : 0 < x.val) :
+ adjust false true (wordBits x) = (wordBits (prevWord x), false) := by
+ have he := adjust_down_spec true (wordBits x)
+ have hf : (adjust false true (wordBits x)).2 = false := by
+ apply Bool.eq_false_iff.mpr
+ intro hb
+ have := (adjust_borrow_iff _).mp hb
+ rw [value_wordBits] at this
+ omega
+ apply Prod.ext _ hf
+ apply eq_of_length_value (by simp)
+ simp only [hf, Bool.toNat_false, Bool.toNat_true, Nat.mul_zero, Nat.add_zero, value_wordBits] at he
+ rw [value_wordBits]
+ change _ = x.val - 1
+ omega
+
+theorem adjust_inc_word (x : Word w) (hx : x.val + 1 < 2 ^ w) :
+ adjust true true (wordBits x) = (wordBits (⟨x.val + 1, hx⟩ : Word w), false) := by
+ have he := adjust_up_spec true (wordBits x)
+ have hf : (adjust true true (wordBits x)).2 = false := by
+ apply Bool.eq_false_iff.mpr
+ intro hb
+ have := (adjust_overflow_iff _).mp hb
+ rw [value_wordBits, length_wordBits] at this
+ omega
+ apply Prod.ext _ hf
+ apply eq_of_length_value (by simp)
+ simpa [hf, value_wordBits] using he
+
+end RAMTape.Charges
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeCoefficient.lean b/lean/OAI/Computability/VPVNP/RAMTapeCoefficient.lean
new file mode 100644
index 0000000000..ed5efc10d5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeCoefficient.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.RAMTapeStackClock
+import OAI.Computability.VPVNP.RAMSiteInput
+import Mathlib.Data.Fin.Tuple.Basic
+
+/-!
+# Fixed bit-stack processors as literal coefficients of the integer family
+
+The original raw input is already the contents of stack zero. The blank tail
+of that tape supplies the separators of every unused stack. Consequently the
+table reads its own prefix in exactly the same way as any subsequent bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.StackCompiler
+
+open UniversalMachine Turing BurstRAM
+
+variable {k : ℕ} {Q : Type*} [Fintype Q]
+
+/-- The concrete universal-machine program that simulates the indexed stack code. -/
+noncomputable abbrev program (code : StackCode (Fin (k+1)) Q) (start : Q) : Program :=
+ compile (.ready start) (rows code)
+
+/-- Put the input word on the first stack and initialize the others to empty. -/
+def inputStacks (input : Word) : Stacks (Fin (k+1)) := Fin.cons input (fun _ => [])
+
+private theorem empty_fields (n : ℕ) : fields (List.replicate n []) = List.replicate n 0 := by
+ induction n with
+ | zero => rfl
+ | succ n ih => simp [List.replicate_succ, ih]
+
+theorem packed_input (input : Word) :
+ packed (inputStacks (k := k) input) = input.map bit ++ List.replicate (k+1) 0 := by
+ simp [packed, inputStacks, List.ofFn_succ, empty_fields, List.replicate_succ]
+
+theorem physical_initial (code : StackCode (Fin (k+1)) Q) (start : Q) (input : Word) :
+ initial (program code start) input = running (.ready start) (.ready start)
+ (tapeList (packed (inputStacks (k := k) input))) (tapeList []) := by
+ rw [initial_eq_running, packed_input]
+ have he : ListBlank.mk (input.map bit ++ List.replicate (k+1) 0) = ListBlank.mk (input.map bit) :=
+ Quotient.sound (Or.inr ⟨k+1, rfl⟩)
+ exact congrArg (fun r => running (Phase.ready (k := k+1) start) (.ready start) (Tape.mk' (ListBlank.mk []) r) (tapeList [])) he.symm
+
+theorem input_count (code : StackCode (Fin (k+1)) Q) (start : Q) (input : Word) (T ticks : ℕ)
+ (stops : StopsWithin code T start (inputStacks input))
+ (clock : T * (6 * (input.length + (k+1) + T) + 4) ≤ ticks) :
+ paths (program code start) ticks (initial (program code start) input) =
+ stackPaths code T start (inputStacks input) := by
+ rw [physical_initial]
+ apply physical_eq code start T start _ _ ticks stops _ clock
+ simp [packed_input]
+
+/-- The same prefix serves every length and every payload that fits the
+clock. All branch counts include the literal table's prefix in the input. -/
+theorem prefix_count (code : StackCode (Fin (k+1)) Q) (start : Q) (payload : Word) (T : ℕ)
+ (stops : StopsWithin code T start (inputStacks (programPrefix (program code start) ++ payload)))
+ (clock : let n := (programPrefix (program code start)).length + payload.length
+ T * (6 * (n + (k+1) + T) + 4) ≤ n^clockExponent) :
+ acceptingCount ((programPrefix (program code start) ++ payload).get) =
+ stackPaths code T start (inputStacks (programPrefix (program code start) ++ payload)) := by
+ simp only [acceptingCount, List.ofFn_get, decode_programPrefix]
+ apply input_count _ _ _ _ _ stops
+ simpa only [List.length_append] using clock
+
+/-- The processor receives exactly its local fields and the shared prefix
+under the length-`n` site encoding used by the contraction. -/
+theorem site_count (code : StackCode (Fin (k+1)) Q) (start : Q) (n T : ℕ) {d H w : ℕ}
+ (v : Fin (2^d)) (hdr : ProcessorInput.Header) (inc : Fin (RAMLayout.width d H w) → Bool)
+ (fits : ProcessorInput.Fits (program code start) n d H w)
+ (stops : StopsWithin code T start (inputStacks (ProcessorInput.tape (program code start) n v hdr inc)))
+ (clock : T * (6 * (n + (k+1) + T) + 4) ≤ n^clockExponent) :
+ acceptingCount (ProcessorInput.encode (program code start) n v hdr inc fits) =
+ stackPaths code T start (inputStacks (ProcessorInput.tape (program code start) n v hdr inc)) := by
+ rw [ProcessorInput.coefficient]
+ apply input_count _ _ _ _ _ stops
+ simpa only [ProcessorInput.length_tape _ _ _ _ fits] using clock
+
+end RAMTape.StackCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeDivision.lean b/lean/OAI/Computability/VPVNP/RAMTapeDivision.lean
new file mode 100644
index 0000000000..087fe70386
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeDivision.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.RAMTapeDivisionForward
+import OAI.Computability.VPVNP.RAMTapeDivisionInit
+import OAI.Computability.VPVNP.RAMTapeDivisionRestore
+
+/-!
+# Restoring division in quadratic bit-stack time
+
+This fixed finite control computes both outputs of the word RAM's unsigned
+division and remainder instructions. It preserves the divisor and leaves all
+temporary stacks empty. The separate zero-divisor path also works at zero
+width. Every input has exactly one accepting path with the stated clock.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.DivisionStack
+
+open RAMTape
+
+private theorem divideStep_length (d r : List Bool) (b : Bool) (hlen : r.length = d.length) :
+ (divideStep d b r).2.length = d.length := by
+ have hx : (b :: r).length = (d ++ [false]).length := by simp [hlen]
+ unfold divideStep
+ dsimp only
+ split <;> simp [length_subScan hx, hlen]
+
+/-- One complete quotient-digit loop, including the shift, subtraction and
+the restoration of the divisor and selected remainder. -/
+theorem digitRun (feed q d r : List Bool) (b : Bool) (hlen : r.length = d.length) :
+ let t := divideStep d b r
+ Run (10 * d.length + 4) .outer ⟨[], b :: feed, d, r, q, [], [], []⟩
+ .outer ⟨[], feed, d, t.2, t.1 :: q, [], [], []⟩ := by
+ let candidate := b :: r
+ let trial := subScan false candidate (d ++ [false])
+ let orig := candidate.take d.length
+ let diff := trial.1.take d.length
+ let selected := if trial.2 then orig else diff
+ have hx : candidate.length = (d ++ [false]).length := by simp [candidate, hlen]
+ have ho : orig.length = d.length := by simp [orig, candidate, hlen]
+ have ht : diff.length = d.length := by simp [diff, trial, length_subScan hx, candidate, hlen]
+ have hstep : divideStep d b r = (!trial.2, selected) := by
+ unfold divideStep
+ change (if trial.2 then (false, orig) else (true, diff)) = _
+ dsimp only [selected]
+ cases trial.2 <;> rfl
+ have hfinish : Run 1 (.digit trial.2) ⟨[],feed,d,selected,q,[],[],[]⟩
+ .outer ⟨[],feed,d,selected,(!trial.2)::q,[],[],[]⟩ :=
+ prepend rfl (.nil ..)
+ have hbody := ((forwardRun feed q d r b hlen).trans
+ (restoreRun feed q d orig diff trial.2 ho ht)).trans hfinish
+ dsimp only
+ rw [hstep, show 10 * d.length + 4 = ((5*d.length + 1) + (5*d.length + 1) + 1) + 1 by omega]
+ exact prepend rfl hbody
+
+private def divideFeed (d : List Bool) : List Bool → List Bool → List Bool → List Bool × List Bool
+ | [], q, r => (q, r)
+ | b :: feed, q, r =>
+ let t := divideStep d b r
+ divideFeed d feed (t.1 :: q) t.2
+
+private theorem divideFeed_reverse (d x feed : List Bool) :
+ divideFeed d (x.reverse ++ feed) [] (List.replicate d.length false) =
+ divideFeed d feed (dividePass d x).1 (dividePass d x).2 := by
+ induction x generalizing feed with
+ | nil => rfl
+ | cons b xs ih =>
+ simpa only [List.reverse_cons, List.append_assoc, List.cons_append, List.nil_append, dividePass, divideFeed]
+ using ih (b :: feed)
+
+private theorem outerRun (feed q d r : List Bool) (hlen : r.length = d.length) :
+ let out := divideFeed d feed q r
+ Run (feed.length * (10*d.length+4) + 1) .outer ⟨[],feed,d,r,q,[],[],[]⟩
+ .done ⟨[],[],d,out.2,out.1,[],[],[]⟩ := by
+ induction feed generalizing q r with
+ | nil =>
+ simp only [divideFeed, List.length_nil, Nat.zero_mul, Nat.zero_add]
+ exact prepend rfl (.nil ..)
+ | cons b feed ih =>
+ let t := divideStep d b r
+ have hr := ih (t.1 :: q) t.2 (divideStep_length d r b hlen)
+ have h := (digitRun feed q d r b hlen).trans hr
+ simpa only [t, divideFeed, List.length_cons, Nat.add_mul, Nat.one_mul, Nat.add_left_comm,
+ Nat.add_assoc, Nat.add_comm] using h
+
+/-- Exact running time of the restoring word macro. -/
+def ticks (x d : List Bool) : ℕ :=
+ 2 * x.length + 5 * d.length + 3 +
+ if d.any id then x.length * (10 * d.length + 4) + 1 else d.length + 3 * x.length + 2
+
+theorem divideRun (x d : List Bool) :
+ let out := divideWords x d
+ Run (ticks x d) .reverseInput ⟨x,[],d,[],[],[],[],[]⟩
+ .done ⟨[],[],d,out.2,out.1,[],[],[]⟩ := by
+ have hi := initRun x d
+ cases hz : d.any id with
+ | false =>
+ simp only [hz, Bool.false_eq_true, ↓reduceIte] at hi
+ simpa only [divideWords, ticks, hz, Bool.false_eq_true, ↓reduceIte] using
+ hi.trans (zeroRun x d)
+ | true =>
+ simp only [hz, ↓reduceIte] at hi
+ have ho := outerRun x.reverse [] d
+ (List.replicate d.length false) (by simp)
+ have he := divideFeed_reverse d x []
+ simp only [List.append_nil, divideFeed] at he
+ simp only [he, List.length_reverse] at ho
+ simpa only [divideWords, ticks, hz, ↓reduceIte] using hi.trans ho
+
+theorem ticks_le {x d : List Bool} (hlen : x.length = d.length) :
+ ticks x d ≤ 12 * (x.length + 1)^2 := by
+ unfold ticks
+ rw [← hlen]
+ split <;> ring_nf <;> omega
+
+open BurstRAM PrivateRAM in
+/-- Both RAM opcode results in little-endian bit-stack format. The same fixed
+program table applies to every word width. -/
+theorem divideWordRun {w : ℕ} (x d : Word w) :
+ Run (ticks (wordBits x) (wordBits d)) .reverseInput
+ ⟨wordBits x,[],wordBits d,[],[],[],[],[]⟩ .done
+ ⟨[],[],wordBits d,wordBits (BinaryOp.mod.eval x d),wordBits (BinaryOp.div.eval x d),[],[],[]⟩ := by
+ simpa only [divideWords_wordBits] using divideRun (wordBits x) (wordBits d)
+
+/-- An extra instruction beyond the transition bound visits the accepting
+halt. The deterministic division routine has exactly one accepting path. -/
+theorem dividePaths {x d : List Bool} (hlen : x.length = d.length) :
+ stackPaths code (12 * (x.length + 1)^2 + 1) .reverseInput
+ (Data.mk x [] d [] [] [] [] []).stacks = 1 := by
+ have hle := ticks_le hlen
+ let spare := 12 * (x.length + 1)^2 - ticks x d
+ have hfuel : 12 * (x.length + 1)^2 + 1 = (spare + 1) + ticks x d := by
+ dsimp [spare]; omega
+ rw [hfuel, (divideRun x d).paths (spare + 1)]
+ rfl
+
+end TapeWord.DivisionStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeDivisionCore.lean b/lean/OAI/Computability/VPVNP/RAMTapeDivisionCore.lean
new file mode 100644
index 0000000000..407a6022f7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeDivisionCore.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.RAMTapeWordDivision
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Fixed stack control for restoring division
+
+The control reverses the dividend to expose its most significant bit, tests
+the divisor for zero, and initializes a zero remainder of the same width. A
+forward scan saves the divisor, candidate bits and trial difference on three
+scratch stacks. The restore scan puts the divisor back and uses the final
+borrow to choose the new remainder.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.DivisionStack
+
+open RAMTape
+
+/-- Ports for the dividend, its reversed feed, divisor, quotient, remainder, and three
+trial-subtraction stacks. -/
+inductive Port where
+ | input | feed | divisor | remainder | quotient | saved | original | difference
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Control of restoring division, including dividend reversal, zero-divisor handling, trial
+subtraction, and quotient-bit emission. -/
+inductive State where
+ | reverseInput | saveInput (b : Bool)
+ | init (nonzero : Bool) | saveInit (d nonzero : Bool) | initZero (nonzero : Bool)
+ | restoreInit (nonzero : Bool) | putInit (d nonzero : Bool)
+ | clearRemainder | zeroLoop | zeroQuot (b : Bool) | zeroRem (b : Bool)
+ | outer
+ | forward (borrow prev : Bool) | readR (borrow prev d : Bool)
+ | saveD (d orig result borrow prev : Bool) | saveOrig (orig result borrow prev : Bool)
+ | saveDiff (result borrow prev : Bool)
+ | restore (borrow : Bool) | putD (d borrow : Bool)
+ | readOrig (borrow : Bool) | readDiff (orig borrow : Bool)
+ | putR (b borrow : Bool) | digit (borrow : Bool)
+ | done | reject
+ deriving DecidableEq, Fintype
+
+/-- Perform binary restoring division from the most significant dividend bit. For a zero
+divisor emit a zero quotient and return the dividend as the remainder. -/
+def code : StackCode Port State
+ | .reverseInput => .pop .input (fun | none => .init false | some b => .saveInput b)
+ | .saveInput b => .push .feed b .reverseInput
+ | .init nonzero => .pop .divisor
+ (fun | none => .restoreInit nonzero | some d => .saveInit d (nonzero || d))
+ | .saveInit d nonzero => .push .saved d (.initZero nonzero)
+ | .initZero nonzero => .push .remainder false (.init nonzero)
+ | .restoreInit nonzero => .pop .saved
+ (fun | none => if nonzero then .outer else .clearRemainder | some d => .putInit d nonzero)
+ | .putInit d nonzero => .push .divisor d (.restoreInit nonzero)
+ | .clearRemainder => .pop .remainder (fun | none => .zeroLoop | some _ => .clearRemainder)
+ | .zeroLoop => .pop .feed (fun | none => .done | some b => .zeroQuot b)
+ | .zeroQuot b => .push .quotient false (.zeroRem b)
+ | .zeroRem b => .push .remainder b .zeroLoop
+ | .outer => .pop .feed (fun | none => .done | some b => .forward false b)
+ | .forward borrow prev => .pop .divisor
+ (fun | none => .restore (subBit borrow prev false).2 | some d => .readR borrow prev d)
+ | .readR borrow prev d => .pop .remainder (fun
+ | none => .reject
+ | some r =>
+ let t := subBit borrow prev d
+ .saveD d prev t.1 t.2 r)
+ | .saveD d orig result borrow prev => .push .saved d (.saveOrig orig result borrow prev)
+ | .saveOrig orig result borrow prev => .push .original orig (.saveDiff result borrow prev)
+ | .saveDiff result borrow prev => .push .difference result (.forward borrow prev)
+ | .restore borrow => .pop .saved (fun | none => .digit borrow | some d => .putD d borrow)
+ | .putD d borrow => .push .divisor d (.readOrig borrow)
+ | .readOrig borrow => .pop .original (fun | none => .reject | some b => .readDiff b borrow)
+ | .readDiff orig borrow => .pop .difference (fun
+ | none => .reject
+ | some diff => .putR (if borrow then orig else diff) borrow)
+ | .putR b borrow => .push .remainder b (.restore borrow)
+ | .digit borrow => .push .quotient (!borrow) .outer
+ | .done => .halt true
+ | .reject => .halt false
+
+/-- Bit stacks for restoring division, including the trial remainder and difference used to
+resolve each quotient digit. -/
+structure Data where
+ /-- Dividend bits before reversal into most-significant-first order. -/
+ input : List Bool
+ /-- Remaining dividend bits in the order in which division consumes them. -/
+ feed : List Bool
+ /-- Divisor word restored after every trial subtraction. -/
+ divisor : List Bool
+ /-- Current partial remainder of the division. -/
+ remainder : List Bool
+ /-- Quotient digits accumulated as the dividend bits are consumed. -/
+ quotient : List Bool
+ /-- Divisor bits held temporarily during initialization or trial subtraction. -/
+ saved : List Bool
+ /-- Candidate remainder bits saved before subtraction for the borrow case. -/
+ original : List Bool
+ /-- Trial-difference bits saved for the case in which subtraction succeeds. -/
+ difference : List Bool
+
+/-- Read the division bank by its stack port. -/
+def Data.stacks (s : Data) : Stacks Port
+ | .input => s.input
+ | .feed => s.feed
+ | .divisor => s.divisor
+ | .remainder => s.remainder
+ | .quotient => s.quotient
+ | .saved => s.saved
+ | .original => s.original
+ | .difference => s.difference
+
+/-- Replace one of the eight division stacks. -/
+def Data.set (s : Data) : Port → List Bool → Data
+ | .input, x => {s with input := x}
+ | .feed, x => {s with feed := x}
+ | .divisor, x => {s with divisor := x}
+ | .remainder, x => {s with remainder := x}
+ | .quotient, x => {s with quotient := x}
+ | .saved, x => {s with saved := x}
+ | .original, x => {s with original := x}
+ | .difference, x => {s with difference := x}
+
+theorem Data.set_stacks (s : Data) (i : Port) (xs : List Bool) :
+ (s.set i xs).stacks = Function.update s.stacks i xs := by
+ funext j
+ cases i <;> cases j <;> rfl
+
+/-- One deterministic transition, written using concrete record projections
+to simplify the verified word-level macros. -/
+def tick (q : State) (s : Data) : Option (State × Data) :=
+ match code q with
+ | .pop k f => some (f (s.stacks k).head?, s.set k (s.stacks k).tail)
+ | .push k b next => some (next, s.set k (b :: s.stacks k))
+ | .goto next => some (next, s)
+ | .choose _ _ | .halt _ => none
+
+/-- An execution of the division control between two states and banks in exactly the given
+number of stack steps. -/
+abbrev Run (n : ℕ) (q : State) (s : Data) (q' : State) (t : Data) :=
+ StackRuns code n q s.stacks q' t.stacks
+
+theorem stepOfTick {q q' : State} {s t : Data} (h : tick q s = some (q', t)) :
+ StackStep code q s.stacks q' t.stacks := by
+ unfold tick at h
+ cases hc : code q with
+ | push k b next =>
+ rw [hc] at h
+ cases h
+ rw [Data.set_stacks]
+ exact .push hc
+ | pop k f =>
+ rw [hc] at h
+ cases h
+ rw [Data.set_stacks]
+ exact .pop hc
+ | goto next => rw [hc] at h; cases h; exact .goto hc
+ | choose | halt => simp [hc] at h
+
+theorem prepend {q q' t : State} {s s' u : Data} {n : ℕ}
+ (h : tick q s = some (q', s')) (tail : Run n q' s' t u) : Run (n + 1) q s t u :=
+ .cons (stepOfTick h) tail
+
+end TapeWord.DivisionStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeDivisionForward.lean b/lean/OAI/Computability/VPVNP/RAMTapeDivisionForward.lean
new file mode 100644
index 0000000000..00dcfd8ab7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeDivisionForward.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.RAMTapeDivisionCore
+
+/-!
+# Forward scan of a restoring division step
+
+The control holds the next shifted candidate bit in `prev`. For each low
+position it saves the divisor, candidate and difference bits. At the high
+position it subtracts the zero extension of the divisor to obtain the final
+borrow. Only the low positions occupy the three scratch stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.DivisionStack
+
+private theorem forwardBit (feed q d r saved orig diff : List Bool) (c prev a b : Bool) :
+ Run 5 (.forward c prev) ⟨[], feed, a :: d, b :: r, q, saved, orig, diff⟩
+ (.forward (subBit c prev a).2 b)
+ ⟨[], feed, d, r, q, a :: saved, prev :: orig, (subBit c prev a).1 :: diff⟩ := by
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ exact .nil ..
+
+private theorem forwardAux (feed q d r saved orig diff : List Bool)
+ (c prev : Bool) (hlen : r.length = d.length) :
+ let candidate := prev :: r
+ let trial := subScan c candidate (d ++ [false])
+ Run (5 * d.length + 1) (.forward c prev) ⟨[], feed, d, r, q, saved, orig, diff⟩
+ (.restore trial.2)
+ ⟨[], feed, [], [], q, d.reverse ++ saved, (candidate.take d.length).reverse ++ orig,
+ (trial.1.take d.length).reverse ++ diff⟩ := by
+ induction d generalizing r c prev saved orig diff with
+ | nil =>
+ have hr : r = [] := List.length_eq_zero_iff.mp hlen
+ subst r
+ apply prepend (by rfl)
+ exact .nil ..
+ | cons a d ih =>
+ cases r with
+ | nil => simp at hlen
+ | cons b r =>
+ have tail := ih r (a :: saved) (prev :: orig) ((subBit c prev a).1 :: diff)
+ (subBit c prev a).2 b (Nat.succ.inj hlen)
+ have run := (forwardBit feed q d r saved orig diff c prev a b).trans tail
+ dsimp only at run ⊢
+ simpa only [List.length_cons, Nat.mul_succ, Nat.add_assoc, Nat.add_left_comm,
+ Nat.add_comm, List.cons_append, subScan, scan, List.take_succ_cons, List.reverse_cons,
+ List.append_assoc, List.nil_append] using run
+
+/-- A full forward pass saves the three reversed low words and branches on
+the same final borrow as subtraction of the zero-extended divisor. -/
+theorem forwardRun (feed q d r : List Bool) (b : Bool) (hlen : r.length = d.length) :
+ let cand := b :: r
+ let tr := subScan false cand (d ++ [false])
+ Run (5 * d.length + 1) (.forward false b) ⟨[], feed, d, r, q, [], [], []⟩
+ (.restore tr.2)
+ ⟨[], feed, [], [], q, d.reverse, (cand.take d.length).reverse, (tr.1.take d.length).reverse⟩ := by
+ simpa only [List.append_nil] using forwardAux feed q d r [] [] [] false b hlen
+
+end TapeWord.DivisionStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeDivisionInit.lean b/lean/OAI/Computability/VPVNP/RAMTapeDivisionInit.lean
new file mode 100644
index 0000000000..fed27c896f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeDivisionInit.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.RAMTapeDivisionCore
+
+/-!
+# Initialization and division by zero on bit stacks
+
+Reversing the input exposes the dividend in most-significant-bit order.
+While saving the divisor the machine records whether any bit is set and
+allocates a zero remainder cell for each divisor bit. Restoring the saved
+divisor then branches on the computed nonzero flag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.DivisionStack
+
+open RAMTape
+
+private theorem reverseInputRun (x feed d : List Bool) :
+ Run (2 * x.length + 1) .reverseInput ⟨x, feed, d, [], [], [], [], []⟩
+ (.init false) ⟨[], x.reverse ++ feed, d, [], [], [], [], []⟩ := by
+ induction x generalizing feed with
+ | nil =>
+ apply prepend (by rfl)
+ exact .nil ..
+ | cons b xs ih =>
+ rw [List.length_cons, Nat.mul_succ,
+ show 2 * xs.length + 2 + 1 = (2 * xs.length + 1 + 1) + 1 by omega]
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ simpa [Data.set, Data.stacks, List.append_assoc] using ih (b :: feed)
+
+private theorem saveInitRun (flag : Bool) (feed d rem saved : List Bool) :
+ Run (3 * d.length + 1) (.init flag) ⟨[], feed, d, rem, [], saved, [], []⟩
+ (.restoreInit (flag || d.any id))
+ ⟨[], feed, [], List.replicate d.length false ++ rem, [], d.reverse ++ saved, [], []⟩ := by
+ induction d generalizing flag rem saved with
+ | nil =>
+ simp only [List.length_nil, Nat.mul_zero, Nat.zero_add, List.any_nil,
+ Bool.or_false, List.replicate_zero, List.nil_append, List.reverse_nil]
+ apply prepend (by rfl)
+ exact .nil ..
+ | cons b ds ih =>
+ rw [List.length_cons, Nat.mul_succ,
+ show 3 * ds.length + 3 + 1 = ((3 * ds.length + 1 + 1) + 1) + 1 by omega]
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ simpa [Data.set, Data.stacks, List.any_cons, Bool.or_assoc, List.append_assoc, List.replicate_succ']
+ using ih (flag || b) (false :: rem) (b :: saved)
+
+private theorem restoreInitRun (flag : Bool) (feed d rem saved : List Bool) :
+ Run (2 * saved.length + 1) (.restoreInit flag) ⟨[], feed, d, rem, [], saved, [], []⟩
+ (if flag then .outer else .clearRemainder) ⟨[], feed, saved.reverse ++ d, rem, [], [], [], []⟩ := by
+ induction saved generalizing d with
+ | nil =>
+ apply prepend (by rfl)
+ exact .nil ..
+ | cons b ds ih =>
+ rw [List.length_cons, Nat.mul_succ,
+ show 2 * ds.length + 2 + 1 = (2 * ds.length + 1 + 1) + 1 by omega]
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ simpa [Data.set, Data.stacks, List.append_assoc] using ih (b :: d)
+
+/-- The initial scans detect a zero divisor at every width, including zero.
+They consume the dividend stack, restore the divisor, and prepare a zero
+remainder of exactly the divisor's width. -/
+theorem initRun (x d : List Bool) :
+ Run (2 * x.length + 5 * d.length + 3) .reverseInput ⟨x, [], d, [], [], [], [], []⟩
+ (if d.any id then .outer else .clearRemainder)
+ ⟨[], x.reverse, d, List.replicate d.length false, [], [], [], []⟩ := by
+ have h₁ := reverseInputRun x [] d
+ have h₂ := saveInitRun false x.reverse d [] []
+ have h₃ := restoreInitRun (d.any id) x.reverse [] (List.replicate d.length false) d.reverse
+ simp only [List.append_nil, List.length_reverse, List.reverse_reverse, Bool.false_or] at h₁ h₂ h₃
+ convert (h₁.trans h₂).trans h₃ using 1
+ omega
+
+private theorem clearRemainderRun (feed d rem : List Bool) :
+ Run (rem.length + 1) .clearRemainder ⟨[], feed, d, rem, [], [], [], []⟩
+ .zeroLoop ⟨[], feed, d, [], [], [], [], []⟩ := by
+ induction rem with
+ | nil =>
+ apply prepend (by rfl)
+ exact .nil ..
+ | cons b rs ih =>
+ apply prepend (by rfl)
+ exact ih
+
+private theorem zeroLoopRun (feed d rem quot : List Bool) :
+ Run (3 * feed.length + 1) .zeroLoop ⟨[], feed, d, rem, quot, [], [], []⟩
+ .done ⟨[], [], d, feed.reverse ++ rem, List.replicate feed.length false ++ quot, [], [], []⟩ := by
+ induction feed generalizing rem quot with
+ | nil =>
+ apply prepend (by rfl)
+ exact .nil ..
+ | cons b bs ih =>
+ rw [List.length_cons, Nat.mul_succ,
+ show 3 * bs.length + 3 + 1 = ((3 * bs.length + 1 + 1) + 1) + 1 by omega]
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ apply prepend (by rfl)
+ simpa [Data.set, Data.stacks, List.append_assoc, List.replicate_succ'] using ih (b :: rem) (false :: quot)
+
+/-- After zero-divisor detection the machine returns an all-zero quotient
+and the original dividend as remainder, both at the dividend's width. -/
+theorem zeroRun (x d : List Bool) :
+ Run (d.length + 3 * x.length + 2) .clearRemainder
+ ⟨[], x.reverse, d, List.replicate d.length false, [], [], [], []⟩
+ .done ⟨[], [], d, x, List.replicate x.length false, [], [], []⟩ := by
+ have h₁ := clearRemainderRun x.reverse d (List.replicate d.length false)
+ have h₂ := zeroLoopRun x.reverse d [] []
+ simp only [List.length_replicate, List.length_reverse, List.reverse_reverse,
+ List.append_nil] at h₁ h₂
+ convert h₁.trans h₂ using 1
+ omega
+
+end TapeWord.DivisionStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeDivisionRestore.lean b/lean/OAI/Computability/VPVNP/RAMTapeDivisionRestore.lean
new file mode 100644
index 0000000000..230c895d58
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeDivisionRestore.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.RAMTapeDivisionCore
+
+/-!
+# Restore scan for binary division
+
+Each iteration restores one divisor bit and consumes the corresponding bits
+of both possible remainders. The borrow from the forward scan determines
+which bit is written. Reversing the three scratch stacks in this way puts
+the resulting words back in least-significant-bit-first order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.DivisionStack
+
+private theorem restoreAux (feed q ds os ts d r : List Bool) (borrow : Bool)
+ (ho : os.length = ds.length) (ht : ts.length = ds.length) :
+ Run (5 * ds.length + 1) (.restore borrow) ⟨[], feed, d, r, q, ds, os, ts⟩
+ (.digit borrow) ⟨[], feed, ds.reverse ++ d,
+ (if borrow then os else ts).reverse ++ r, q, [], [], []⟩ := by
+ induction ds generalizing os ts d r with
+ | nil =>
+ have hos : os = [] := List.length_eq_zero_iff.mp ho
+ have hts : ts = [] := List.length_eq_zero_iff.mp ht
+ subst os ts
+ simp only [ite_self, List.reverse_nil, List.nil_append]
+ exact prepend rfl (.nil ..)
+ | cons b bs ih =>
+ cases os with
+ | nil => simp at ho
+ | cons a as =>
+ cases ts with
+ | nil => simp at ht
+ | cons c cs =>
+ have tail := ih as cs (b :: d) ((if borrow then a else c) :: r)
+ (Nat.succ.inj ho) (Nat.succ.inj ht)
+ have selected : (if borrow then a :: as else c :: cs) =
+ (if borrow then a else c) :: (if borrow then as else cs) := by cases borrow <;> rfl
+ simp only [selected, List.reverse_cons, List.append_assoc, List.singleton_append,
+ List.length_cons, Nat.mul_succ]
+ exact prepend rfl (prepend rfl (prepend rfl (prepend rfl (prepend rfl tail))))
+
+/-- Restore the divisor and select the low word of the old or trial
+remainder. The final empty pop transfers control to the quotient digit. -/
+theorem restoreRun (feed q d original diff : List Bool) (borrow : Bool)
+ (h₁ : original.length = d.length) (h₂ : diff.length = d.length) :
+ Run (5 * d.length + 1) (.restore borrow)
+ ⟨[], feed, [], [], q, d.reverse, original.reverse, diff.reverse⟩
+ (.digit borrow) ⟨[], feed, d, if borrow then original else diff, q, [], [], []⟩ := by
+ have h := restoreAux feed q d.reverse original.reverse diff.reverse [] [] borrow
+ (by simpa using h₁) (by simpa using h₂)
+ cases borrow <;> simpa using h
+
+end TapeWord.DivisionStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeISAComparison.lean b/lean/OAI/Computability/VPVNP/RAMTapeISAComparison.lean
new file mode 100644
index 0000000000..aad399d5d3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeISAComparison.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.RAMTapeISAOperand
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMTapeWordComparison
+
+/-!
+# Register comparisons for the conditional-jump dispatcher
+
+The two operands are copied into independent work stacks before the scan,
+even if both names refer to the same register. The scan returns one Boolean
+at work port zero and empties the rest of its scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open TapeWord BurstRAM PrivateRAM
+
+variable {r k w : ℕ}
+
+private def comparisonPorts : ScanPort → Port r k
+ | .left => .work 0
+ | .right => .work 1
+ | .tmp => .work 2
+ | .out => .work 3
+
+private theorem comparisonPorts_injective : Function.Injective (comparisonPorts (r := r) (k := k)) := by
+ intro i j h
+ cases i <;> cases j <;> first | rfl | exact False.elim (of_decide_eq_false rfl (Port.work.inj h))
+
+private def testRoutine (op : Comparison.Op) : FiniteRoutine (Port r k) := FiniteRoutine.ofRoutine {
+ entry := Comparison.State.scan (.left op.initial)
+ code := fun
+ | .done bit => .push (.work 0) bit none
+ | q@(.scan _) => (Comparison.code op q).rename comparisonPorts some }
+
+/-- Stage both operands, run the comparison, and return with one decision bit. -/
+def compareRegs (op : Comparison.Op) (x y : Fin r) : FiniteRoutine (Port r k) :=
+ ((loadOperand (.reg x) (.work 0)).followedBy (loadOperand (.reg y) (.work 1))).followedBy
+ (testRoutine op)
+
+theorem compareRegs_run (op : Comparison.Op) (x y : Fin r) (pub : Fin k → Word w)
+ (persistent : Word w) (reg : Fin r → Word w) (log : WriteLog w) :
+ (compareRegs op x y).Runs (20 * w + 10) (bank pub persistent reg log)
+ (Function.update (bank pub persistent reg log) (.work 0) [op.eval (reg x) (reg y)]) := by
+ let s := bank pub persistent reg log
+ let s₁ := Function.update s (.work 0) (wordBits (reg x))
+ let s₂ := Function.update s₁ (.work 1) (wordBits (reg y))
+ have hx : (loadOperand (.reg x) (.work 0)).Runs (7*w+3) s s₁ := by
+ simpa only [s, s₁, bank, List.length_nil, Nat.zero_add, length_wordBits] using
+ loadOperand_runs (src := .reg x) (dst := .work 0) (by simp)
+ (by simp [copySafe]) (by simp [copySafe]) s rfl rfl
+ have hy : (loadOperand (.reg y) (.work 1)).Runs (7*w+3) s₁ s₂ := by
+ have h := loadOperand_runs (src := .reg y) (dst := .work 1) (by simp)
+ (by simp [copySafe]) (by simp [copySafe]) s₁ (by rfl) (by rfl)
+ change (loadOperand _ _).Runs (0 + 7 * (wordBits (reg y)).length + 3) s₁ s₂ at h
+ simpa only [length_wordBits, Nat.zero_add] using h
+ let kernel := testRoutine (r := r) (k := k) op
+ let flag := op.eval (reg x) (reg y)
+ have rows (q : Comparison.State) (hq : (Comparison.code op q).returns = false) :
+ kernel.body.standalone (some q) = (Comparison.code op q).rename comparisonPorts some := by
+ cases q with
+ | scan => rfl
+ | done => contradiction
+ have scan := (Comparison.word_run op (reg x) (reg y)).lift comparisonPorts
+ comparisonPorts_injective some s rows
+ have hin : installStacks comparisonPorts s (scanStacks (wordBits (reg x)) (wordBits (reg y)) [] []) =
+ s₂ := by
+ apply installStacks_frame comparisonPorts_injective
+ · intro i
+ cases i <;> rfl
+ · intro j hj
+ exact (Function.update_of_ne (Ne.symm (hj .right)) ..).trans
+ (Function.update_of_ne (Ne.symm (hj .left)) ..)
+ have hout : installStacks comparisonPorts s (scanStacks [] [] [] []) = s :=
+ installStacks_eq comparisonPorts_injective s _ (fun i => by cases i <;> rfl)
+ rw [hin, hout] at scan
+ have push : StackRuns kernel.body.standalone 1 (some (.done flag)) s none
+ (Function.update s (.work 0) [flag]) := .cons (.push rfl) (.nil ..)
+ have test : kernel.Runs ((6*w+3)+1) s₂ (Function.update s (.work 0) [flag]) := scan.trans push
+ rw [show 20 * w + 10 = (7*w+3 + (7*w+3)) + ((6*w+3)+1) by omega]
+ exact FiniteRoutine.Runs.followedBy (FiniteRoutine.Runs.followedBy hx hy) test
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeISADispatch.lean b/lean/OAI/Computability/VPVNP/RAMTapeISADispatch.lean
new file mode 100644
index 0000000000..174cda6641
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeISADispatch.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.RAMTapeISAPrepare
+import Mathlib.Data.Fintype.Sigma
+
+/-!
+# One finite stack control for a fixed RAM instruction table
+
+The control for a template contains entry and exit states for every program
+counter and the finite states of its operand routines. Its states and code
+are fixed before choosing a word width, public data, or a private execution.
+The typed boundary states allow the caller to implement external accesses,
+binary choices, the per-instruction clock and return propagation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open BurstRAM PrivateRAM
+
+variable {v w p r k : ℕ}
+
+/-- Dispatcher states for program-counter entry, execution of its preparation routine,
+instruction exit, and typed callback. -/
+abbrev State (T : Template p r k) :=
+ Fin p ⊕ ((i : Fin p) × (prepare (T.code i)).State) ⊕ Fin p ⊕ Callback p r
+
+/-- Enter the fixed table at the given program counter. -/
+def entry (T : Template p r k) (pc : Fin p) : State T := .inl pc
+
+/-- Embed a typed instruction exit in the dispatcher state space. -/
+def callback (T : Template p r k) (cb : Callback p r) : State T := .inr (.inr (.inr cb))
+
+private def localState (T : Template p r k) (i : Fin p) (q : (prepare (T.code i)).State) : State T :=
+ .inr (.inl ⟨i, q⟩)
+
+private def finishState (T : Template p r k) (i : Fin p) : State T := .inr (.inr (.inl i))
+
+/-- Identify precisely the outer-controller callback boundaries. -/
+def resume? (T : Template p r k) : State T → Option (Callback p r)
+ | .inr (.inr (.inr cb)) => some cb
+ | _ => none
+
+@[simp] theorem resume_callback (T : Template p r k) (cb : Callback p r) :
+ resume? T (callback T cb) = some cb := rfl
+
+@[simp] theorem resume_entry (T : Template p r k) (i : Fin p) : resume? T (entry T i) = none := rfl
+
+private def finishOp (T : Template p r k) (i : Instr v p r k) : StackOp (Port r k) (State T) :=
+ match i with
+ | .jumpEq .. | .jumpLt .. => .pop (.work 0) fun flag => callback T (exitFor i (flag.getD false))
+ | _ => .goto (callback T (exitFor i false))
+
+/-- The complete deterministic dispatch table, with callbacks initially
+represented by halts. Linking replaces their behavior in the caller. -/
+def code (T : Template p r k) : StackCode (Port r k) (State T)
+ | .inl i => .goto (localState T i (prepare (T.code i)).body.entry)
+ | .inr (.inl ⟨i, q⟩) => ((prepare (T.code i)).body.code q).rename id
+ (fun next => next.elim (finishState T i) (localState T i))
+ | .inr (.inr (.inl i)) => finishOp T (T.code i)
+ | .inr (.inr (.inr _)) => .halt true
+
+theorem resume_none_of_continuing (T : Template p r k) (q : State T) (h : (code T q).returns = false) :
+ resume? T q = none := by
+ rcases q with i | q | i | cb <;> first | rfl | contradiction
+
+private theorem prepare_link (T : Template p r k) (i : Fin p) {t : ℕ} {s out : Stacks (Port r k)}
+ (h : (prepare (T.code i)).Runs t s out) :
+ StackRuns (code T) t (localState T i (prepare (T.code i)).body.entry) s (finishState T i) out := by
+ let routine := prepare (T.code i)
+ let labels (q : Option routine.State) : State T := q.elim (finishState T i) (localState T i)
+ have hc (q : Option routine.State) (hn : (routine.body.standalone q).returns = false) :
+ code T (labels q) = (routine.body.standalone q).rename id labels := by
+ cases q with
+ | none => contradiction
+ | some q => rfl
+ have hi (t : Stacks (Port r k)) : installStacks id s t = t := by
+ funext j
+ exact installStacks_at Function.injective_id s t j
+ simpa only [labels, Option.elim_none, Option.elim_some, hi] using
+ h.lift id Function.injective_id labels s hc
+
+private theorem finish_step (T : Template p r k) (pc : Fin p) (pub : Fin k → Word w) (c : LogConfig w p r) :
+ let i := T.code pc
+ StackStep (code T) (finishState T pc) (preparedBank i pub c)
+ (callback T (exitFor i ((jumpTest i c).getD false))) (configBank pub (post i pub c)) := by
+ dsimp only
+ cases h : T.code pc <;> try exact .goto (by simp [code, finishState, h, finishOp, jumpTest])
+ all_goals
+ let s := configBank pub c
+ let b := (jumpTest (T.code pc) c).getD false
+ have hs : s (.work 0) = [] := rfl
+ have he : code T (finishState T pc) = .pop (.work 0)
+ (fun flag => callback T (exitFor (T.code pc) (flag.getD false))) := by
+ simp only [code, finishState, h, finishOp]
+ have hh := StackStep.pop (s := Function.update s (.work 0) [b]) he
+ have hu : Function.update s (.work 0) [] = s := by rw [← hs, Function.update_eq_self]
+ simp only [Function.update_self, List.head?_cons, Option.getD_some, List.tail_cons,
+ Function.update_idem, hu] at hh
+ simpa only [s, b, h, preparedBank, post, jumpTest, Option.getD_some] using hh
+
+/-- The outgoing bank and the typed callback are explicitly determined by the
+instruction, independently of how the caller uses either one. -/
+theorem dispatch_step (T : Template p r k) (pub : Fin k → Word w) (c : LogConfig w p r) :
+ let i := T.code c.pc
+ ∃ steps ≤ prepareBound w c.writes.length + 2,
+ StackRuns (code T) steps (entry T c.pc) (configBank pub c)
+ (callback T (exitFor i ((jumpTest i c).getD false))) (configBank pub (post i pub c)) := by
+ dsimp only
+ let i := T.code c.pc
+ obtain ⟨t, ht, hprep⟩ := prepare_runs i pub c
+ have hb : StackStep (code T) (entry T c.pc) (configBank pub c)
+ (localState T c.pc (prepare i).body.entry) (configBank pub c) := .goto rfl
+ have he := finish_step T c.pc pub c
+ exact ⟨(t+1)+1, by omega, .cons hb ((prepare_link T c.pc hprep).trans (.cons he (.nil ..)))⟩
+
+/-- Every reached instruction follows its fixed template table to a typed exit
+and implements exactly one native small step. The pathwise cost includes the
+initial transfer and the final callback selection. -/
+theorem dispatch_run (T : Template p r k) (pub : Fin k → Word w) (c : LogConfig w p r) :
+ ∃ steps cb postCfg, steps ≤ prepareBound w c.writes.length + 2 ∧
+ StackRuns (code T) steps (entry T c.pc) (configBank pub c) (callback T cb) (configBank pub postCfg) ∧
+ cb.action postCfg = (T.instantiate w pub).logProgram.step c := by
+ obtain ⟨t, ht, hrun⟩ := dispatch_step T pub c
+ exact ⟨t, _, _, ht, hrun, callback_action (T.code c.pc) pub c⟩
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeISAOperand.lean b/lean/OAI/Computability/VPVNP/RAMTapeISAOperand.lean
new file mode 100644
index 0000000000..9136646b35
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeISAOperand.lean
@@ -0,0 +1,151 @@
+import OAI.Computability.VPVNP.RAMTapeISAPorts
+import OAI.Computability.VPVNP.RAMTapeWordOperands
+
+/-!
+# Architectural operand staging and scratch cleanup
+
+Copies may read architectural, public, or temporary stacks. Two reserved
+work stacks hold the reversed source and output during a copy. A same-register
+copy is a separate no-op in the instruction dispatcher. Other instructions
+stage their inputs before writing a destination that aliases an input.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open TapeWord BurstRAM
+
+variable {r k w : ℕ}
+
+/-- The port avoids work stacks 14 and 15, both reserved by operand copying. -/
+def copySafe (i : Port r k) := i ≠ .work 14 ∧ i ≠ .work 15
+
+/-- Route a copying scan to the source, destination, and the two reserved work stacks. -/
+def copyPorts (src dst : Port r k) : ScanPort → Port r k
+ | .left => src
+ | .right => .work 14
+ | .tmp => .work 15
+ | .out => dst
+
+theorem copyPorts_injective {src dst : Port r k} (hd : src ≠ dst) (hs : copySafe src)
+ (ht : copySafe dst) : Function.Injective (copyPorts src dst) := by
+ obtain ⟨hs₁, hs₂⟩ := hs
+ obtain ⟨ht₁, ht₂⟩ := ht
+ have hw : (Port.work 14 : Port r k) ≠ .work 15 := fun he => (by decide : (14 : Fin 16) ≠ 15) (Port.work.inj he)
+ intro i j he
+ cases i <;> cases j <;> simp_all [copyPorts]
+
+private theorem install_copy {src dst : Port r k} (hd : src ≠ dst) (hs : copySafe src) (ht : copySafe dst)
+ (s : Stacks (Port r k)) (h14 : s (.work 14) = []) (h15 : s (.work 15) = []) (out : List Bool) :
+ installStacks (copyPorts src dst) s (scanStacks (s src) [] [] out) = Function.update s dst out := by
+ have hp := copyPorts_injective hd hs ht
+ funext j
+ by_cases h : ∃ i, copyPorts src dst i = j
+ · obtain ⟨i, rfl⟩ := h
+ rw [installStacks_at hp]
+ cases i <;> simp [copyPorts, scanStacks, Function.update, hd, Ne.symm ht.1, Ne.symm ht.2, h14, h15]
+ · have hj : j ≠ dst := fun he => h ⟨.out, he.symm⟩
+ rw [installStacks_outside _ _ (not_exists.mp h), Function.update_of_ne hj]
+
+private def operandReturn {A : Type} : Operand.State A → Bool
+ | .done _ => true
+ | _ => false
+
+private theorem operandReturn_halts {A : Type} (step : A → Bool → Bool × A) :
+ ∀ q, operandReturn q = true → ((Operand.code step) q).returns = true := by
+ intro q h
+ cases q <;> simp_all [operandReturn, Operand.code]
+
+/-- Copy a word from the source port to the destination with the finite operand scan. -/
+def loadOperand (src dst : Port r k) : FiniteRoutine (Port r k) :=
+ FiniteRoutine.ofStackCode (Operand.code Operand.copyBit) (copyPorts src dst) (.clear ()) operandReturn
+
+theorem loadOperand_runs {src dst : Port r k} (hd : src ≠ dst) (hs : copySafe src) (ht : copySafe dst)
+ (s : Stacks (Port r k)) (h14 : s (.work 14) = []) (h15 : s (.work 15) = []) :
+ (loadOperand src dst).Runs ((s dst).length + 7 * (s src).length + 3) s (Function.update s dst (s src)) := by
+ have h := FiniteRoutine.runs_ofStackCode (copyPorts_injective hd hs ht) (normal := operandReturn)
+ rfl rfl (operandReturn_halts _) s (Operand.copy_run (s src) (s dst))
+ rwa [install_copy hd hs ht s h14 h15, Function.update_eq_self, install_copy hd hs ht s h14 h15] at h
+
+/-- Clear a stack by popping until the first empty test. -/
+def clearPort (i : Port r k) : FiniteRoutine (Port r k) := FiniteRoutine.ofRoutine {
+ entry := ()
+ code := fun _ => .pop i fun b => b.map fun _ => () }
+
+theorem clearPort_runs (i : Port r k) (s : Stacks (Port r k)) :
+ (clearPort i).Runs ((s i).length + 1) s (Function.update s i []) := by
+ suffices h : ∀ xs (t : Stacks (Port r k)), t i = xs →
+ (clearPort i).Runs (xs.length + 1) t (Function.update t i []) by exact h _ s rfl
+ intro xs
+ induction xs with
+ | nil =>
+ intro t he
+ have hs := StackStep.pop (s := t) (code := (clearPort i).body.standalone)
+ (q := some (clearPort i).body.entry)
+ (show (clearPort i).body.standalone (some (clearPort i).body.entry) =
+ .pop i (fun b => b.map fun _ => ()) from rfl)
+ rw [he] at hs
+ exact .cons hs (.nil ..)
+ | cons b xs ih =>
+ intro t he
+ have hs := StackStep.pop (s := t) (code := (clearPort i).body.standalone)
+ (q := some (clearPort i).body.entry)
+ (show (clearPort i).body.standalone (some (clearPort i).body.entry) =
+ .pop i (fun b => b.map fun _ => ()) from rfl)
+ rw [he] at hs
+ have hr := ih (Function.update t i xs) (Function.update_self ..)
+ rw [Function.update_idem] at hr
+ exact .cons hs hr
+
+/-- Load a fixed natural literal into the destination register using the persistent word to
+determine the bit width. -/
+def loadLiteral (n : ℕ) (dst : Fin r) : FiniteRoutine (Port r k) :=
+ FiniteRoutine.ofStackCode (Operand.code (Operand.literalBit n)) (copyPorts .persistent (.reg dst))
+ (.clear (Fin.last n)) operandReturn
+
+theorem loadLiteral_run (n : ℕ) (dst : Fin r) (pub : Fin k → Word w) (persist : Word w)
+ (reg : Fin r → Word w) (log : PrivateRAM.WriteLog w) :
+ (loadLiteral n dst).Runs (8*w+3) (bank pub persist reg log)
+ (bank pub persist (Function.update reg dst (Fin.ofNat (2^w) n)) log) := by
+ let s := bank pub persist reg log
+ obtain ⟨exit, h⟩ := Operand.literal_run n persist (s (.reg dst))
+ have hd : (Port.persistent : Port r k) ≠ .reg dst := by simp
+ have hs : copySafe (Port.persistent : Port r k) := by simp [copySafe]
+ have ht : copySafe (Port.reg dst : Port r k) := by simp [copySafe]
+ have hr := FiniteRoutine.runs_ofStackCode (copyPorts_injective hd hs ht) (normal := operandReturn)
+ rfl (exit := .done exit) rfl (operandReturn_halts _) s h
+ change (loadLiteral n dst).Runs ((s (.reg dst)).length + 7*w+3)
+ (installStacks (copyPorts .persistent (.reg dst)) s (scanStacks (s .persistent) [] [] (s (.reg dst))))
+ (installStacks (copyPorts .persistent (.reg dst)) s (scanStacks (s .persistent) [] [] (wordBits (Fin.ofNat _ n)))) at hr
+ rw [install_copy hd hs ht s rfl rfl, Function.update_eq_self, install_copy hd hs ht s rfl rfl] at hr
+ dsimp only [s] at hr
+ rw [bank_updateReg] at hr
+ convert hr using 1
+ change 8*w+3 = (wordBits (reg dst)).length + 7*w+3
+ rw [length_wordBits]
+ omega
+
+/-- A fresh call may initially have empty registers. The width template in
+the persistent port determines the literal independently of the old register. -/
+theorem loadLiteral_at (n : ℕ) (dst : Fin r) (s : Stacks (Port r k)) (persist : Word w)
+ (hp : s .persistent = wordBits persist) (h14 : s (.work 14) = []) (h15 : s (.work 15) = []) :
+ (loadLiteral n dst).Runs ((s (.reg dst)).length + 7*w+3) s
+ (Function.update s (.reg dst) (wordBits (Fin.ofNat (2^w) n))) := by
+ obtain ⟨exit, h⟩ := Operand.literal_run n persist (s (.reg dst))
+ have hd : (Port.persistent : Port r k) ≠ .reg dst := by simp
+ have hs : copySafe (Port.persistent : Port r k) := by simp [copySafe]
+ have ht : copySafe (Port.reg dst : Port r k) := by simp [copySafe]
+ have hr := FiniteRoutine.runs_ofStackCode (copyPorts_injective hd hs ht) (normal := operandReturn)
+ rfl (exit := .done exit) rfl (operandReturn_halts _) s h
+ rw [← hp] at hr
+ rw [install_copy hd hs ht s h14 h15, Function.update_eq_self, install_copy hd hs ht s h14 h15] at hr
+ exact hr
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeISAPorts.lean b/lean/OAI/Computability/VPVNP/RAMTapeISAPorts.lean
new file mode 100644
index 0000000000..4288a972c3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeISAPorts.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.RAMTapeAddressLogControl
+import OAI.Computability.VPVNP.StructuredStackRuns
+
+/-!
+# Stack bank and returning routines for fixed RAM instruction tables
+
+The program counter is in finite control. Registers, the persistent word and
+public words have distinct stack labels. The three stored private-log streams
+share the address-log convention. Work ports 14 and 15 serve as scratch for
+operand copies, independently of the arithmetic and address-log routines.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+/-- A finite control packaged with its entry, so separately typed opcode
+routines can form a single fixed program by sequencing. -/
+structure FiniteRoutine (K : Type) where
+ /-- Finite control-state type of the returning stack routine. -/
+ State : Type
+ [finiteState : Fintype State]
+ /-- Stack routine on the specified ports and finite control states. -/
+ body : Routine K State
+
+attribute [instance] FiniteRoutine.finiteState
+
+namespace FiniteRoutine
+
+variable {K L Q : Type}
+
+/-- Package a returning stack routine with its finite control-state type. -/
+def ofRoutine [Fintype Q] (r : Routine K Q) : FiniteRoutine K := ⟨Q, r⟩
+
+/-- Sequence two finite routines so the return from the first enters the second. -/
+def followedBy (a b : FiniteRoutine K) : FiniteRoutine K := ofRoutine (a.body.followedBy b.body)
+
+/-- The finite routine that immediately returns. -/
+def ret : FiniteRoutine K := ofRoutine Routine.ret
+
+/-- Execution of the routine from the input bank to the output bank in the given number of
+steps. -/
+abbrev Runs [DecidableEq K] (a : FiniteRoutine K) (n : ℕ) (s t : Stacks K) := a.body.Runs n s t
+
+theorem Runs.followedBy [DecidableEq K] {a b : FiniteRoutine K} {m n : ℕ} {s t u : Stacks K}
+ (ha : a.Runs m s t) (hb : b.Runs n t u) : (a.followedBy b).Runs (m + n) s u :=
+ Routine.Runs.followedBy ha hb
+
+/-- Redirect the normal halts of a finite subprogram into the caller. Rejection
+remains a rejecting halt. No extra step is charged for a normal return. -/
+def ofStackCode [Fintype Q] (src : StackCode K Q) (ports : K → L) (entry : Q)
+ (normal : Q → Bool) : FiniteRoutine L := ofRoutine {
+ entry := entry
+ code := fun q => if normal q then .goto none else
+ (src q).rename ports (fun j => if normal j then none else some j) }
+
+theorem runs_ofStackCode [Fintype Q] [DecidableEq K] [DecidableEq L]
+ {src : StackCode K Q} {ports : K → L} (hp : Function.Injective ports) {entry exit : Q}
+ {normal : Q → Bool} (he : normal entry = false) (hx : normal exit = true)
+ (hs : ∀ q, normal q = true → (src q).returns = true) (base : Stacks L)
+ {t : ℕ} {s u : Stacks K} (h : StackRuns src t entry s exit u) :
+ (ofStackCode src ports entry normal).Runs t (installStacks ports base s) (installStacks ports base u) := by
+ let labels (q : Q) : Option Q := if normal q then none else some q
+ let target := (ofStackCode src ports entry normal).body.standalone
+ have hc (q : Q) (hn : (src q).returns = false) : target (labels q) = (src q).rename ports labels := by
+ have hq : normal q = false := by
+ cases h : normal q with
+ | false => rfl
+ | true => exact Bool.noConfusion ((hs q h).symm.trans hn)
+ simp [target, labels, ofStackCode, ofRoutine, Routine.standalone, Routine.close, hq]
+ have lifted := h.lift ports hp labels base hc
+ simp only [labels, he, hx, Bool.false_eq_true, ite_false, ite_true] at lifted
+ exact lifted
+
+end FiniteRoutine
+
+namespace ISA
+
+open BurstRAM PrivateRAM
+
+/-- Architectural, public, persistent, scratch, and private write-log stack labels for a fixed
+instruction table. -/
+inductive Port (r k : ℕ) where
+ | reg (i : Fin r) | pub (i : Fin k) | persistent | work (i : Fin 16) | logPort (i : AddressLog.Port)
+ deriving DecidableEq, Fintype
+
+variable {r k w p : ℕ}
+
+/-- Encode a private write log by its keys, values, and occupancy marks, with the other log
+ports empty. -/
+def logStacks (log : WriteLog w) : Stacks AddressLog.Port
+ | .keys => AddressLog.keys log
+ | .values => AddressLog.values log
+ | .occupied => List.replicate log.length true
+ | _ => []
+
+/-- Between instructions, every work stack and address-log scratch stack is
+empty. The architectural bank is independent of the program-counter label. -/
+def bank (pub : Fin k → Word w) (persistent : Word w) (reg : Fin r → Word w) (log : WriteLog w) :
+ Stacks (Port r k)
+ | .reg i => wordBits (reg i)
+ | .pub i => wordBits (pub i)
+ | .persistent => wordBits persistent
+ | .work _ => []
+ | .logPort i => logStacks log i
+
+/-- Encode the public words, persistent state, registers, and writes of a RAM configuration as
+a stack bank. -/
+def configBank (pub : Fin k → Word w) (c : LogConfig w p r) := bank pub c.persistent c.reg c.writes
+
+theorem bank_updateReg (pub : Fin k → Word w) (persistent : Word w) (reg : Fin r → Word w)
+ (log : WriteLog w) (i : Fin r) (v : Word w) :
+ Function.update (bank pub persistent reg log) (.reg i) (wordBits v) =
+ bank pub persistent (Function.update reg i v) log := by
+ funext j
+ cases j with
+ | reg j => by_cases he : j = i <;> simp [bank, he]
+ | pub | persistent | work | logPort => simp [bank]
+
+end ISA
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeISAPrepare.lean b/lean/OAI/Computability/VPVNP/RAMTapeISAPrepare.lean
new file mode 100644
index 0000000000..d6413be087
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeISAPrepare.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.RAMTapeISASemantics
+import OAI.Computability.VPVNP.RAMTapeISAComparison
+import OAI.Computability.VPVNP.RAMTapePrivateISALoad
+import OAI.Computability.VPVNP.RAMTapePrivateISAStore
+import OAI.Computability.VPVNP.RAMTapeWordISAStage
+
+/-!
+# Compiling the deterministic work of every RAM instruction
+
+Each fixed instruction selects one finite stack routine. Register operands are
+copied before overwriting a destination. Conditional branches leave one test
+bit. Operations handled by the outer call controller return immediately.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open BurstRAM PrivateRAM TapeWord
+
+variable {v w p r k : ℕ}
+
+/-- Compile the deterministic portion of an instruction, staging operands and leaving a
+comparison bit for a conditional jump. -/
+def prepare : Instr v p r k → FiniteRoutine (Port r k)
+ | .constant dst val _ => loadLiteral val.val dst
+ | .publicWord dst j _ => loadOperand (.pub j) (.reg dst)
+ | .stateWord dst _ => loadOperand .persistent (.reg dst)
+ | .copy dst src _ => if src = dst then FiniteRoutine.ret else loadOperand (.reg src) (.reg dst)
+ | .binary op dst x y _ => binary op dst x y
+ | .loadPrivate dst addr _ => loadPrivate dst addr
+ | .storePrivate addr src _ => storePrivate addr src
+ | .jumpEq x y _ _ => compareRegs .eq x y
+ | .jumpLt x y _ _ => compareRegs .lt x y
+ | _ => FiniteRoutine.ret
+
+/-- Bank after the instruction’s local effects, with its jump-test bit placed on work stack
+zero when applicable. -/
+def preparedBank (i : Instr v p r k) (pub : Fin k → Word w) (c : LogConfig w p r) : Stacks (Port r k) :=
+ let s := configBank pub (post i pub c)
+ match jumpTest i c with
+ | none => s
+ | some b => Function.update s (.work 0) [b]
+
+private theorem loadReg_at (pub : Fin k → Word w) (c : LogConfig w p r) (src : Port r k) (dst : Fin r)
+ (v : Word w) (hd : src ≠ .reg dst) (hs : copySafe src) (he : configBank pub c src = wordBits v) :
+ (loadOperand src (.reg dst)).Runs (8*w + 3) (configBank pub c)
+ (bank pub c.persistent (Function.update c.reg dst v) c.writes) := by
+ have h := loadOperand_runs hd hs (by simp [copySafe]) (configBank pub c) rfl rfl
+ rw [he] at h
+ change (loadOperand src (.reg dst)).Runs ((wordBits (c.reg dst)).length + 7*(wordBits v).length+3)
+ (configBank pub c) (Function.update (bank pub c.persistent c.reg c.writes) (.reg dst) (wordBits v)) at h
+ rw [bank_updateReg, length_wordBits, length_wordBits] at h
+ convert h using 1
+ omega
+
+/-- The dispatch bound is independent of register values, addresses, and
+private branch choices. Each private load may inspect every prior write. -/
+def prepareBound (width writes : ℕ) := 100 * (width + 1)^2 * (writes + 1)
+
+private theorem basic_bound (w n : ℕ) : 100 * (w + 1)^2 ≤ prepareBound w n :=
+ Nat.le_mul_of_pos_right _ (Nat.succ_pos _)
+
+private theorem linear_bound (w n : ℕ) : 26*w+11 ≤ prepareBound w n :=
+ (by nlinarith [Nat.zero_le (w^2)] : 26*w+11 ≤ 100*(w+1)^2).trans (basic_bound ..)
+
+private theorem private_bound (a : Word w) (log : WriteLog w) :
+ 17*w+8+AddressLog.loadCost a log ≤ prepareBound w log.length := by
+ apply (loadPrivate_cost_le a log).trans
+ unfold prepareBound
+ ring_nf
+ omega
+
+theorem prepare_runs (i : Instr v p r k) (pub : Fin k → Word w) (c : LogConfig w p r) :
+ ∃ t ≤ prepareBound w c.writes.length, (prepare i).Runs t (configBank pub c) (preparedBank i pub c) := by
+ have hlin := linear_bound w c.writes.length
+ cases i with
+ | constant dst val pc => exact ⟨_, by omega, loadLiteral_run ..⟩
+ | publicWord dst j pc => exact ⟨_, by omega, loadReg_at pub c (.pub j) dst (pub j)
+ (by simp) (by simp [copySafe]) rfl⟩
+ | stateWord dst pc => exact ⟨_, by omega, loadReg_at pub c .persistent dst c.persistent
+ (by simp) (by simp [copySafe]) rfl⟩
+ | copy dst src pc =>
+ by_cases h : src = dst
+ · subst src
+ refine ⟨1, by omega, ?_⟩
+ simpa [prepare, preparedBank, jumpTest, post, configBank, FiniteRoutine.ret, FiniteRoutine.ofRoutine] using
+ Routine.runs_ret (configBank pub c)
+ · refine ⟨8*w+3, by omega, ?_⟩
+ simpa only [prepare, h, ↓reduceIte, preparedBank, jumpTest, post, configBank] using
+ loadReg_at pub c (.reg src) dst (c.reg src) (by simpa using h) (by simp [copySafe]) rfl
+ | binary op dst x y pc =>
+ obtain ⟨t, ht, hr⟩ := binary_runs op dst x y pub c.persistent c.reg c.writes
+ exact ⟨t, ht.trans (basic_bound ..), hr⟩
+ | loadPrivate dst addr pc => exact ⟨_, private_bound .., loadPrivate_run ..⟩
+ | storePrivate addr src pc => exact ⟨_, hlin, storePrivate_run ..⟩
+ | jumpEq x y yes no => exact ⟨_, by omega, compareRegs_run .eq x y pub c.persistent c.reg c.writes⟩
+ | jumpLt x y yes no => exact ⟨_, by omega, compareRegs_run .lt x y pub c.persistent c.reg c.writes⟩
+ | choose | readExternal | writeExternal | returnState | accept | reject =>
+ exact ⟨1, by omega, Routine.runs_ret _⟩
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeISASemantics.lean b/lean/OAI/Computability/VPVNP/RAMTapeISASemantics.lean
new file mode 100644
index 0000000000..dfc9bda4aa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeISASemantics.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.RAMUniform
+import OAI.Computability.VPVNP.RAMTapeISAPorts
+import OAI.Computability.VPVNP.RAMTapeWordComparison
+
+/-!
+# Instruction dispatch and its typed exits
+
+A local instruction updates the register or private-log bank before reporting
+the next program counter. Binary choices and external reads and writes are
+returned to the call controller. This separates their charging and bit choices
+from the deterministic work of fetching and interpreting the instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open BurstRAM PrivateRAM TapeWord
+
+/-- Typed instruction exit carrying the next counter, a choice, an external access, a returned
+state, or a halt decision. -/
+inductive Callback (p r : ℕ) where
+ | next (pc : Fin p)
+ | choose (yes no : Fin p)
+ | read (dst addr : Fin r) (next : Fin p)
+ | write (addr src : Fin r) (next : Fin p)
+ | returnState (src : Fin r)
+ | accept
+ | reject
+ deriving DecidableEq, Fintype
+
+variable {v w p r k : ℕ}
+
+/-- Native continuation represented by the exit label and the resulting
+architectural bank. The outer call controller handles the read answer and the
+binary choice. -/
+def Callback.action (cb : Callback p r) (c : LogConfig w p r) : CallAction w (LogConfig w p r) :=
+ match cb with
+ | .next j => .localStep {c with pc := j}
+ | .choose yes no => .branch fun b => {c with pc := if b then yes else no}
+ | .read dst addr j => .read (c.reg addr) fun x => {c with pc := j, reg := Function.update c.reg dst x}
+ | .write addr src j => .write (c.reg addr) (c.reg src) {c with pc := j}
+ | .returnState src => .finish (some (c.reg src))
+ | .accept => .finish none
+ | .reject => .reject
+
+/-- The fields written by deterministic instruction preparation. The program
+counter belongs to the finite control and is set by `Callback.action`. -/
+def post (i : Instr v p r k) (pub : Fin k → Word w) (c : LogConfig w p r) : LogConfig w p r :=
+ match i with
+ | .constant dst val _ => {c with reg := Function.update c.reg dst (Fin.ofNat _ val.val)}
+ | .publicWord dst j _ => {c with reg := Function.update c.reg dst (pub j)}
+ | .stateWord dst _ => {c with reg := Function.update c.reg dst c.persistent}
+ | .copy dst src _ => {c with reg := Function.update c.reg dst (c.reg src)}
+ | .binary op dst x y _ => {c with reg := Function.update c.reg dst (op.eval (c.reg x) (c.reg y))}
+ | .loadPrivate dst addr _ => {c with reg := Function.update c.reg dst (WriteLog.memory c.writes (c.reg addr))}
+ | .storePrivate addr src _ => {c with writes := (c.reg addr, c.reg src) :: c.writes}
+ | _ => c
+
+theorem post_writes (i : Instr v p r k) (pub : Fin k → Word w) (c : LogConfig w p r) :
+ (post i pub c).writes = (i.resize w).nextLog c := by cases i <;> rfl
+
+theorem post_writes_length_le (i : Instr v p r k) (pub : Fin k → Word w) (c : LogConfig w p r) :
+ (post i pub c).writes.length ≤ c.writes.length + 1 := by
+ rw [post_writes]
+ exact Instr.nextLog_length_le ..
+
+/-- Determine an instruction’s typed exit, using the supplied test bit to select the target of
+a conditional jump. -/
+def exitFor (i : Instr v p r k) (test : Bool) : Callback p r :=
+ match i with
+ | .constant _ _ j | .publicWord _ _ j | .stateWord _ j | .copy _ _ j | .binary _ _ _ _ j
+ | .loadPrivate _ _ j | .storePrivate _ _ j => .next j
+ | .jumpEq _ _ yes no | .jumpLt _ _ yes no => .next (if test then yes else no)
+ | .choose yes no => .choose yes no
+ | .readExternal dst addr j => .read dst addr j
+ | .writeExternal addr src j => .write addr src j
+ | .returnState src => .returnState src
+ | .accept => .accept
+ | .reject => .reject
+
+/-- Only conditional jumps leave a single-bit test result for the dispatcher. -/
+def jumpTest (i : Instr v p r k) (c : LogConfig w p r) : Option Bool :=
+ match i with
+ | .jumpEq x y _ _ => some (Comparison.Op.eq.eval (c.reg x) (c.reg y))
+ | .jumpLt x y _ _ => some (Comparison.Op.lt.eval (c.reg x) (c.reg y))
+ | _ => none
+
+theorem callback_action (i : Instr v p r k) (pub : Fin k → Word w) (c : LogConfig w p r) :
+ (exitFor i ((jumpTest i c).getD false)).action (post i pub c) = (i.resize w).runLogged pub c := by
+ cases i <;> simp [jumpTest, exitFor, Callback.action, post, Instr.resize, Instr.runLogged,
+ Instr.run, LogConfig.denote, Instr.nextLog, CallAction.mapState, Config.put, Config.store,
+ Comparison.Op.eval] <;> rfl
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInput.lean b/lean/OAI/Computability/VPVNP/RAMTapeInput.lean
new file mode 100644
index 0000000000..e3fcfcd62d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInput.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.RAMTapeInputFields
+import OAI.Computability.VPVNP.RAMTapeInputRoutines
+import OAI.Computability.VPVNP.RAMSiteInput
+
+/-!
+# Uniform finite-stack parsing of the physical site tape
+
+After the public field lengths are available as unary scratch counters, the
+control copies the self-delimiting prefix, the site address, its four header
+bits and the whole incident vector, then consumes the zero padding. The control
+and its register set are fixed across all lengths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputReader
+
+open BurstRAM ProcessorInput RAMLayout RAMSerialization UniversalMachine
+
+private def headerMarks :=
+ let mark := Routine.push InputPort.count true
+ ((mark.followedBy mark).followedBy mark).followedBy mark
+
+private theorem headerMarks_runs (s : Stacks InputPort) :
+ headerMarks.Runs 4 s (Function.update s .count (List.replicate 4 true ++ s .count)) := by
+ let push := fun t : Stacks InputPort => Function.update t .count (true :: t .count)
+ have one (t : Stacks InputPort) : (Routine.push .count true).Runs 1 t (push t) :=
+ Routine.runs_push ..
+ have h := (((one s).followedBy (one (push s))).followedBy (one (push (push s)))).followedBy
+ (one (push (push (push s))))
+ have he : push (push (push (push s))) = Function.update s .count (List.replicate 4 true ++ s .count) := by
+ simp [push, Function.update_idem, List.replicate_succ]
+ exact he ▸ h
+
+/-- Sequential reader. The address and incident lengths are popped from their
+own counters and the fixed four header marks are written by the control. -/
+def parse := (((((prefixRoutine.followedBy (readField .address)).followedBy headerMarks).followedBy
+ (readField .header)).followedBy (readField .incident)).followedBy padding)
+
+/-- Bank after parsing, with the prefix, address, header, and incident bits on separate stacks
+and the measured size preserved. -/
+def result (s : Stacks InputPort) (pref addr hdr inc : List Bool) : Stacks InputPort
+ | .input | .tmp | .count | .addressCount | .incidentCount => []
+ | .prefix => pref
+ | .address => addr
+ | .header => hdr
+ | .incident => inc
+ | .size => s .size
+
+/-- Correct on all data-field values and all lengths of zero padding. Unused
+scratch data are cleared, while the full literal prefix is saved in order. -/
+theorem parse_runs (s : Stacks InputPort) (table addr hdr inc : List Bool) (z : ℕ)
+ (hlen : hdr.length = 4)
+ (hin : s .input = (unary table.length ++ table) ++ (addr ++ hdr ++ inc ++ List.replicate z false))
+ (ht : s .tmp = []) (hc : s .count = []) (hp : s .prefix = [])
+ (ha : s .address = []) (hh : s .header = []) (hi : s .incident = [])
+ (hac : s .addressCount = List.replicate addr.length true)
+ (hic : s .incidentCount = List.replicate inc.length true) :
+ parse.Runs (10*table.length + 5*addr.length + 5*hdr.length + 5*inc.length + 2*z + 17) s
+ (result s (unary table.length ++ table) addr hdr inc) := by
+ let pref := unary table.length ++ table
+ let pad := List.replicate z false
+ let u := Function.update (Function.update s .input (addr ++ hdr ++ inc ++ pad)) .prefix pref
+ let a := fieldResult u .address addr (hdr ++ inc ++ pad)
+ let m := Function.update a .count (List.replicate 4 true ++ a .count)
+ let b := fieldResult m .header hdr (inc ++ pad)
+ let c := fieldResult b .incident inc pad
+ have h₁ := prefixRoutine_runs s table (addr ++ hdr ++ inc ++ pad) hin ht hc hp
+ change prefixRoutine.Runs _ s u at h₁
+ have h₂ : (readField .address).Runs _ u a := readField_runs u .address addr (hdr ++ inc ++ pad)
+ (by simp [u, List.append_assoc]) (by simpa [u, Field.counter] using hac) (by simpa [u] using ht)
+ have h₃ := headerMarks_runs a
+ change headerMarks.Runs 4 a m at h₃
+ have h₄ : (readField .header).Runs _ m b := readField_runs m .header hdr (inc ++ pad)
+ (by simp [m, a, fieldResult, Field.counter, Field.output, List.append_assoc])
+ (by simp [m, a, u, fieldResult, Field.counter, Field.output, hc, hlen])
+ (by simp [m, a, u, fieldResult, Field.counter, Field.output, ht])
+ have h₅ : (readField .incident).Runs _ b c := readField_runs b .incident inc pad
+ (by simp [b, fieldResult, Field.counter, Field.output])
+ (by simp [b, m, a, u, fieldResult, Field.counter, Field.output, hic])
+ (by simp [b, m, a, u, fieldResult, Field.counter, Field.output, ht])
+ have h₆ := padding_runs c z (by simp [c, fieldResult, Field.counter, Field.output, pad])
+ have he : Function.update c .input [] = result s pref addr hdr inc := by
+ funext j
+ cases j <;> simp [c, b, m, a, u, fieldResult, Field.counter, Field.output, result, ha, hh, hi, ht]
+ rw [he] at h₆
+ have run := ((((h₁.followedBy h₂).followedBy h₃).followedBy h₄).followedBy h₅).followedBy h₆
+ exact (show 10*table.length+6 + (5*addr.length+2) + 4 + (5*hdr.length+2) + (5*inc.length+2) +
+ (2*z+1) = 10*table.length + 5*addr.length + 5*hdr.length + 5*inc.length + 2*z + 17 by omega) ▸ run
+
+/-- The local parser begins with its entire tape at the input head. The size
+and field counts can have been produced by previous routines on these stacks. -/
+def prepared (raw : List Bool) (d width : ℕ) (size : List Bool) : Stacks InputPort
+ | .input => raw
+ | .addressCount => List.replicate d true
+ | .incidentCount => List.replicate width true
+ | .size => size
+ | _ => []
+
+/-- A linear stack-instruction bound for parsing the literal physical tape.
+The successful run exposes the exact incident vector used by the word machine. -/
+theorem parse_processorTape {d H w : ℕ} (program : UniversalMachine.Program) (n : ℕ)
+ (v : Fin (2^d)) (hdr : Header) (inc : Fin (width d H w) → Bool) (size : List Bool)
+ (hfit : Fits program n d H w) :
+ let s := prepared (ProcessorInput.tape program n v hdr inc) d (width d H w) size
+ ∃ t ≤ 5*n+17, parse.Runs t s (result s (programPrefix program)
+ (List.ofFn (RAMSerialization.wordBits d v)) (List.ofFn hdr) (List.ofFn inc)) := by
+ let s := prepared (ProcessorInput.tape program n v hdr inc) d (width d H w) size
+ let t := tableBits program
+ let a := List.ofFn (RAMSerialization.wordBits d v)
+ let h := List.ofFn hdr
+ let c := List.ofFn inc
+ let z := n - ((programPrefix program).length + (d+4+width d H w))
+ have run := parse_runs s t a h c z (List.length_ofFn)
+ (by simp only [s, prepared, ProcessorInput.tape, ProcessorInput.payload, programPrefix, t, a, h, c, z,
+ List.append_assoc]) rfl rfl rfl rfl rfl rfl (by simp [s, prepared, a]) (by simp [s, prepared, c])
+ refine ⟨_, ?_, run⟩
+ have hpre : (programPrefix program).length = 2*t.length+1 := by
+ simp [programPrefix, unary, t]; omega
+ have hf : (programPrefix program).length + (d+4+width d H w) ≤ n := hfit
+ dsimp only [a, h, c, z]
+ simp only [List.length_ofFn]
+ omega
+
+end RAMTape.InputReader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputFields.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputFields.lean
new file mode 100644
index 0000000000..8e067b4e9e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputFields.lean
@@ -0,0 +1,185 @@
+import OAI.Computability.VPVNP.RAMTapeInputPorts
+import OAI.Computability.VPVNP.StructuredStackLoop
+import OAI.Computability.VPVNP.StructuredStackRuns
+
+/-!
+# Reading fixed-width fields with a finite stack control
+
+The reader consumes one unary count mark and one input bit at a time. It
+collects the bits in reverse order and restores them to their destination in
+a second pass. Both passes use the same finite control at every input length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputReader
+
+open Routine
+
+/-- Fixed-width fields following the prefix on a site tape, namely the address, four-bit
+header, and incident vector. -/
+inductive Field where
+ | address | header | incident
+ deriving DecidableEq
+
+/-- Select the unary width counter for the address, header, or incident vector. -/
+def Field.counter : Field → InputPort
+ | .address => .addressCount
+ | .header => .count
+ | .incident => .incidentCount
+
+/-- Select the stack on which the reader deposits the requested field. -/
+def Field.output : Field → InputPort
+ | .address => .address
+ | .header => .header
+ | .incident => .incident
+
+private def copyBit :=
+ popCase InputPort.input (Routine.halt false) (Routine.push .tmp false) (Routine.push .tmp true)
+
+/-- Consume one input bit per true width mark, pushing the bits onto a temporary stack in
+reverse order. -/
+def collect (f : Field) :=
+ popLoop f.counter (fun _ => true) (Routine.halt false) copyBit
+
+/-- Move the collected field bits from the temporary stack to their output stack in original
+order. -/
+def restore (f : Field) :=
+ popLoop .tmp (fun _ => true) (Routine.push f.output false) (Routine.push f.output true)
+
+/-- Read one fixed-width field by collecting its bits and then restoring their order. -/
+def readField (f : Field) := (collect f).followedBy (restore f)
+
+/-- The unrelated registers are carried through all field instructions. -/
+private def frame (s : Stacks InputPort) (f : Field) (input count tmp output : List Bool) :
+ Stacks InputPort := fun j =>
+ if j = .input then input else if j = f.counter then count else
+ if j = .tmp then tmp else if j = f.output then output else s j
+
+private theorem frame_eq (s : Stacks InputPort) (f : Field) :
+ frame s f (s .input) (s f.counter) (s .tmp) (s f.output) = s := by
+ funext j
+ cases j <;> cases f <;> rfl
+
+private theorem write_in (s : Stacks InputPort) (f : Field) (x c t o x' : List Bool) :
+ Function.update (frame s f x c t o) .input x' = frame s f x' c t o := by
+ funext j
+ cases j <;> cases f <;> rfl
+
+private theorem write_count (s : Stacks InputPort) (f : Field) (x c t o c' : List Bool) :
+ Function.update (frame s f x c t o) f.counter c' = frame s f x c' t o := by
+ funext j
+ cases j <;> cases f <;> rfl
+
+private theorem write_tmp (s : Stacks InputPort) (f : Field) (x c t o t' : List Bool) :
+ Function.update (frame s f x c t o) .tmp t' = frame s f x c t' o := by
+ funext j
+ cases j <;> cases f <;> rfl
+
+private theorem write_out (s : Stacks InputPort) (f : Field) (x c t o o' : List Bool) :
+ Function.update (frame s f x c t o) f.output o' = frame s f x c t o' := by
+ funext j
+ cases j <;> cases f <;> rfl
+
+private theorem at_count (s : Stacks InputPort) (f : Field) (x c t o : List Bool) :
+ frame s f x c t o f.counter = c := by cases f <;> rfl
+
+private theorem at_tmp (s : Stacks InputPort) (f : Field) (x c t o : List Bool) :
+ frame s f x c t o .tmp = t := by cases f <;> rfl
+
+private theorem at_out (s : Stacks InputPort) (f : Field) (x c t o : List Bool) :
+ frame s f x c t o f.output = o := by cases f <;> rfl
+
+private theorem copyBit_runs (s : Stacks InputPort) (f : Field) (b : Bool) (x c t o : List Bool) :
+ copyBit.Runs 2 (frame s f (b::x) c t o) (frame s f x c (b::t) o) := by
+ have put := runs_push InputPort.tmp b (frame s f x c t o)
+ rw [at_tmp, write_tmp] at put
+ have hi : frame s f (b::x) c t o .input = b :: x := rfl
+ cases b with
+ | false => exact runs_popCase_false InputPort.input _ _ _ hi (by rw [write_in]; exact put)
+ | true => exact runs_popCase_true InputPort.input _ _ _ hi (by rw [write_in]; exact put)
+
+private theorem collect_runs (s : Stacks InputPort) (f : Field) (xs suffix t o : List Bool) :
+ (collect f).Runs (3*xs.length+1) (frame s f (xs++suffix) (List.replicate xs.length true) t o)
+ (frame s f suffix [] (xs.reverse ++ t) o) := by
+ induction xs generalizing t with
+ | nil =>
+ exact Runs.popLoop_empty f.counter (fun _ => true) (Routine.halt false) copyBit (at_count s f suffix [] t o)
+ | cons b bs ih =>
+ let c := List.replicate bs.length true
+ let x := bs ++ suffix
+ have h := Runs.popLoop_true_continue (mid := frame s f x c (b::t) o) (n := 2) f.counter (fun _ => true) (Routine.halt false) copyBit
+ (at_count s f (b::x) (true::c) t o) rfl
+ (by rw [write_count]; exact copyBit_runs s f b x c t o) (ih (b::t))
+ simpa [collect, c, x, List.replicate_succ, List.reverse_cons, List.append_assoc,
+ Nat.mul_succ, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using h
+
+private theorem restore_runs (s : Stacks InputPort) (f : Field) (x c t o : List Bool) :
+ (restore f).Runs (2*t.length+1) (frame s f x c t o) (frame s f x c [] (t.reverse++o)) := by
+ induction t generalizing o with
+ | nil => exact Runs.popLoop_empty .tmp (fun _ => true) (Routine.push f.output false) (Routine.push f.output true) (at_tmp s f x c [] o)
+ | cons b bs ih =>
+ have put : (Routine.push f.output b).Runs 1 (frame s f x c bs o) (frame s f x c bs (b::o)) := by
+ rw [← write_out s f x c bs o (b::o)]
+ have hs : StackStep (Routine.push f.output b).standalone (some ()) (frame s f x c bs o)
+ none (Function.update (frame s f x c bs o) f.output (b :: frame s f x c bs o f.output)) :=
+ .push rfl
+ rw [at_out] at hs
+ exact .cons hs (.nil ..)
+ have h := Runs.popLoop_continue (mid := frame s f x c bs (b::o)) (n := 1) InputPort.tmp (fun _ => true) (Routine.push f.output false) (Routine.push f.output true)
+ (at_tmp s f x c (b::bs) o) rfl (by rw [write_tmp]; cases b <;> exact put) (ih (b::o))
+ simpa [restore, List.reverse_cons, List.append_assoc, Nat.mul_succ, Nat.add_assoc,
+ Nat.add_comm, Nat.add_left_comm] using h
+
+/-- Deterministic stack update after a field has been read. -/
+def fieldResult (s : Stacks InputPort) (f : Field) (data suffix : List Bool) : Stacks InputPort :=
+ Function.update (Function.update (Function.update s .input suffix) f.counter []) f.output (data ++ s f.output)
+
+/-- One counter mark and one input bit are consumed in three stack steps,
+then two steps restore each bit to its original order. -/
+theorem readField_runs (s : Stacks InputPort) (f : Field) (data suffix : List Bool)
+ (hin : s .input = data ++ suffix) (hc : s f.counter = List.replicate data.length true)
+ (ht : s .tmp = []) :
+ (readField f).Runs (5*data.length+2) s (fieldResult s f data suffix) := by
+ have h₁ := collect_runs s f data suffix [] (s f.output)
+ simp only [List.append_nil] at h₁
+ have h₂ := restore_runs s f suffix [] data.reverse (s f.output)
+ simp only [List.length_reverse, List.reverse_reverse] at h₂
+ have hs := frame_eq s f
+ rw [hin, hc, ht] at hs
+ have he : frame s f suffix [] [] (data ++ s f.output) = fieldResult s f data suffix := by
+ funext i
+ cases f <;> cases i <;> first | rfl | exact ht.symm
+ rw [hs] at h₁
+ rw [he] at h₂
+ exact (show 3*data.length+1+(2*data.length+1) = 5*data.length+2 by omega) ▸ h₁.followedBy h₂
+
+/-- A zero padding bit consumes a pop and a return. A one in this region
+executes a rejecting halt. -/
+def padding := popLoop InputPort.input (fun _ => true) Routine.ret (Routine.halt false)
+
+theorem padding_runs (s : Stacks InputPort) (n : ℕ) (hi : s .input = List.replicate n false) :
+ padding.Runs (2*n+1) s (Function.update s .input []) := by
+ induction n generalizing s with
+ | zero =>
+ change s .input = [] at hi
+ have he : Function.update s .input [] = s := by rw [← hi]; exact Function.update_eq_self _ _
+ rw [he]
+ exact Runs.popLoop_empty InputPort.input _ _ _ hi
+ | succ n ih =>
+ rw [List.replicate_succ] at hi
+ let t := Function.update s InputPort.input (List.replicate n false)
+ have hh := Runs.popLoop_false_continue InputPort.input (fun _ => true) Routine.ret (Routine.halt false)
+ hi rfl (runs_ret t) (ih t (Function.update_self ..))
+ have he : Function.update t .input [] = Function.update s .input [] := by
+ simp [t, Function.update_idem]
+ rw [he] at hh
+ exact (show 1+1+(2*n+1) = 2*(n+1)+1 by omega) ▸ hh
+
+end RAMTape.InputReader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputLength.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputLength.lean
new file mode 100644
index 0000000000..82ce9c41c9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputLength.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.RAMTapeInputPorts
+
+/-!
+# Reading the complete input length before parsing the site fields
+
+The size stack acquires one unary mark per input bit, including program-prefix
+bits and padding. The control saves each popped bit on a temporary stack and
+then transfers the bits back, restoring the original input in head-first order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+/-- States of the length pass that saves every input bit, counts it with a unary mark, and
+restores the input. -/
+inductive LengthPhase where
+ | scan
+ | save (bit : Bool)
+ | mark
+ | restore
+ | put (bit : Bool)
+ | done
+ deriving DecidableEq, Fintype
+
+/-- A fixed control, independent of the length and contents of the physical input. -/
+def lengthCode : StackCode InputPort LengthPhase
+ | .scan => .pop .input (fun b ↦ b.elim .restore .save)
+ | .save b => .push .tmp b .mark
+ | .mark => .push .size true .scan
+ | .restore => .pop .tmp (fun b ↦ b.elim .done .put)
+ | .put b => .push .input b .restore
+ | .done => .halt true
+
+private def lengthStore (base : Stacks InputPort) (input tmp size : List Bool) : Stacks InputPort
+ | .input => input
+ | .tmp => tmp
+ | .size => size
+ | k => base k
+
+private theorem write_input (s : Stacks InputPort) (x t n v : List Bool) :
+ Function.update (lengthStore s x t n) .input v = lengthStore s v t n := by
+ funext k
+ cases k <;> simp [lengthStore, Function.update]
+
+private theorem write_tmp (s : Stacks InputPort) (x t n v : List Bool) :
+ Function.update (lengthStore s x t n) .tmp v = lengthStore s x v n := by
+ funext k
+ cases k <;> simp [lengthStore, Function.update]
+
+private theorem write_size (s : Stacks InputPort) (x t n v : List Bool) :
+ Function.update (lengthStore s x t n) .size v = lengthStore s x t v := by
+ funext k
+ cases k <;> simp [lengthStore, Function.update]
+
+local macro "length_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [write_input, write_tmp, write_size, lengthStore, List.head?_cons, List.tail_cons,
+ List.head?_nil, List.tail_nil, Option.elim_some, Option.elim_none])
+
+private theorem scan_length (s : Stacks InputPort) (x t n : List Bool) :
+ StackRuns lengthCode (3 * x.length + 1) .scan (lengthStore s x t n) .restore
+ (lengthStore s [] (x.reverse ++ t) (List.replicate x.length true ++ n)) := by
+ induction x generalizing t n with
+ | nil => length_step; exact .nil ..
+ | cons b x ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append, List.replicate_succ']
+ length_step
+ length_step
+ length_step
+ exact ih (b :: t) (true :: n)
+
+private theorem restore_input (s : Stacks InputPort) (x t n : List Bool) :
+ StackRuns lengthCode (2 * t.length + 1) .restore (lengthStore s x t n) .done
+ (lengthStore s (t.reverse ++ x) [] n) := by
+ induction t generalizing x with
+ | nil => length_step; exact .nil ..
+ | cons b t ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ length_step
+ length_step
+ exact ih (b :: x)
+
+/-- Exactly five stack instructions per input bit and two end tests. With an
+empty size stack the output is the unary input length. Every other stack,
+including the complete input, agrees with its value on entry. -/
+theorem length_runs (s : Stacks InputPort) (ht : s .tmp = []) :
+ StackRuns lengthCode (5 * (s .input).length + 2) .scan s .done
+ (Function.update s .size (List.replicate (s .input).length true ++ s .size)) := by
+ let x := s .input
+ let n := List.replicate x.length true ++ s .size
+ have hscan := scan_length s x [] (s .size)
+ have hrestore := restore_input s [] x.reverse n
+ simp only [List.append_nil, List.length_reverse, List.reverse_reverse] at hscan hrestore
+ have hstart : lengthStore s x [] (s .size) = s := by
+ funext k
+ cases k <;> simp [lengthStore, x, ht]
+ have hdone : lengthStore s x [] n = Function.update s .size n := by
+ funext k
+ cases k <;> simp [lengthStore, Function.update, x, ht]
+ have h := hscan.trans hrestore
+ rw [hstart, hdone, show 3 * x.length + 1 + (2 * x.length + 1) = 5 * x.length + 2 by omega] at h
+ exact h
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputOperandStartup.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputOperandStartup.lean
new file mode 100644
index 0000000000..a7de4977ad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputOperandStartup.lean
@@ -0,0 +1,200 @@
+import OAI.Computability.VPVNP.RAMTapeOwnPrefixOperands
+import OAI.Computability.VPVNP.RAMTapeSiteEntryFrame
+
+/-!
+# Installing parsed prefix and geometry operands in the site processor
+
+The first arithmetic registers are the actual public ports of the burst
+interpreter. Two site scratch stacks hold the packed prefix and its length
+during initialization, then a fixed routine clears both stacks before the
+successor guard. The sorting workspace remains available at entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputOperandStartup
+
+open BurstRAM LiveProgram RAMLayout ProcessorInput StackCompiler PublicExprMachine
+open SiteProcessorPorts (Frame)
+open OwnPrefix.Physical (operandStartup operand_runs operandCoefficient)
+
+variable {k : ℕ}
+
+/-- Geometry expressions for operand slots, with zero placeholders for slots supplied from the
+actual program prefix. -/
+abbrev Expr (args : Fin k → InputOperand) := InputOperandMachine.geometryOnly args
+/-- Combined site-processor bank for the private table and its parsed operand vector. -/
+abbrev Target (r : ℕ) (args : Fin k → InputOperand) := SiteProcessorPorts.Port r (Expr args)
+/-- Bank on which the physical prefix and operand initialization routines execute before their
+ports are renamed. -/
+abbrev Source (args : Fin k → InputOperand) := OwnPrefix.Physical.Port (InputOperandMachine.registers args)
+
+/-- Map computed operands to the interpreter’s public registers and map the two temporary
+prefix words to site scratch stacks. -/
+def ports (r : ℕ) (args : Fin k → InputOperand) : Source args → Target r args
+ | .inl p => SiteProcessorPorts.pub r _ p
+ | .inr (.reg i) => if h : i.val < k then SiteProcessorPorts.native r _ (.isa (.pub ⟨i.val,h⟩))
+ else .inl (.inr (.inr (.reg i)))
+ | .inr (.pub i) =>
+ if h : i.val < 4 then .inl (.inr (.inr (.pub ⟨i.val, h⟩)))
+ else if i.val = 4 then SiteProcessorPorts.native r _ (.scratch 0)
+ else SiteProcessorPorts.native r _ (.scratch 1)
+ | .inr .persistent => .inl (.inr (.inr .persistent))
+ | .inr (.work i) => .inl (.inr (.inr (.work i)))
+ | .inr (.logPort i) => .inl (.inr (.inr (.logPort i)))
+
+theorem ports_injective (r : ℕ) (args : Fin k → InputOperand) : Function.Injective (ports r args) := by
+ let back : Target r args → Source args := fun
+ | .inl (.inr (.inl p)) => .inl p
+ | .inl (.inl (.isa (.pub i))) => .inr (.reg (InputOperandMachine.slot args i))
+ | .inl (.inr (.inr (.reg i))) => .inr (.reg i)
+ | .inl (.inr (.inr (.pub i))) => .inr (.pub (i.castAdd 2))
+ | .inl (.inr (.inr .persistent)) => .inr .persistent
+ | .inl (.inr (.inr (.work i))) => .inr (.work i)
+ | .inl (.inr (.inr (.logPort i))) => .inr (.logPort i)
+ | .inl (.inl (.scratch i)) => .inr (.pub (if i = 0 then 4 else 5))
+ | _ => .inl ProcessorPublic.rawPort
+ apply Function.LeftInverse.injective (g := back)
+ rintro (j | j)
+ · rfl
+ · cases j with
+ | reg i =>
+ by_cases hi : i.val < k <;> simp [ports, hi, SiteProcessorPorts.native, back, InputOperandMachine.slot]
+ | pub i => fin_cases i <;> rfl
+ | _ => rfl
+
+private def clear (args : Fin k → InputOperand) : FiniteRoutine (Source args) :=
+ (ISA.clearList [.pub 4, .pub 5]).onPorts Sum.inr
+
+/-- Initialize the operand vector from the parsed site, clear the two prefix-word scratch
+stacks, and return on the processor’s own ports. -/
+def program (r : ℕ) (args : Fin k → InputOperand) (B a b u lit : ℕ) (hb : 0 < b) :
+ FiniteRoutine (Target r args) :=
+ ((operandStartup args B a b u lit hb).followedBy (clear args)).onPorts (ports r args)
+
+/-- Fixed coefficient in the operand-startup clock bound, including the final scratch cleanup. -/
+def clockCoefficient (args : Fin k → InputOperand) (B a b u : ℕ) :=
+ operandCoefficient args B a b u + 3
+
+/-- The geometry arithmetic bank is kept apart from the site and sort work
+stacks. Only the first arithmetic registers become site operands. -/
+def result (r : ℕ) (args : Fin k → InputOperand) (g : Geometry)
+ (proc : Stacks ProcessorPublic.Port) (out : Fin (InputOperandMachine.registers args) → Word g.w) :
+ Stacks (Target r args)
+ | .inl (.inl (.isa (.pub j))) => wordBits (out (InputOperandMachine.slot args j))
+ | .inl (.inr (.inl j)) => proc j
+ | .inl (.inr (.inr (.reg i))) => if i.val < k then [] else wordBits (out i)
+ | .inl (.inr (.inr j)) => ISA.bank (geometryWords g) 0 out [] j
+ | _ => []
+
+private theorem install (r : ℕ) (args : Fin k → InputOperand) (g : Geometry) (pref : LiteralPrefix)
+ (proc : Stacks ProcessorPublic.Port) (raw : List Bool) (out : Fin (InputOperandMachine.registers args) → Word g.w)
+ (src : FiniteRoutine (Source args)) {t : ℕ}
+ (h : src.Runs t (labeledInput (.inl ProcessorPublic.rawPort) raw)
+ (Sum.elim proc (ISA.bank (InputOperandMachine.input g pref) 0 out []))) :
+ ∃ t' ≤ t + 2*(g.w+1)+1, ((src.followedBy (clear args)).onPorts (ports r args)).Runs t'
+ (labeledInput (SiteProcessorPorts.pub r _ ProcessorPublic.rawPort) raw) (result r args g proc out) := by
+ let bank := ISA.bank (InputOperandMachine.input g pref) 0 out []
+ let clean := ISA.cleared [.pub 4, .pub 5] bank
+ obtain ⟨n, hn, hc⟩ := ISA.clearList_runs [.pub 4, .pub 5] bank g.w (by
+ intro i hi; simp only [List.mem_cons, List.mem_nil_iff, or_false] at hi
+ rcases hi with rfl | rfl <;> simp [bank, ISA.bank])
+ have hc' : (clear args).Runs n (Sum.elim proc bank) (Sum.elim proc clean) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inr_injective hc
+ · intro; rfl
+ · intro; rfl
+ · rintro (j|j) hj
+ · rfl
+ · exact (hj j rfl).elim
+ refine ⟨t+n, by simp only [List.length_cons, List.length_nil] at hn; omega, ?_⟩
+ apply FiniteRoutine.runs_onPorts_framed _ (ports_injective r args) (h.followedBy hc')
+ · rintro (j|j)
+ · simp [ports, SiteProcessorPorts.pub, labeledInput]
+ · cases j with
+ | reg i => by_cases hi : i.val < k <;> simp [ports, hi, SiteProcessorPorts.native, SiteProcessorPorts.pub, labeledInput]
+ | pub i => fin_cases i <;> rfl
+ | _ => rfl
+ · rintro (j|j)
+ · rfl
+ · cases j with
+ | reg i =>
+ by_cases hi : i.val < k <;> simp [ports, hi, result, clean, bank, ISA.cleared, ISA.bank,
+ SiteProcessorPorts.native, InputOperandMachine.slot]
+ | pub i => fin_cases i <;> rfl
+ | logPort i => cases i <;> rfl
+ | _ => rfl
+ · rintro (((j | (j|j)) | j)) hj
+ · cases j with
+ | isa x =>
+ cases x with
+ | pub i => exact (hj (.inr (.reg (InputOperandMachine.slot args i))) (by
+ simp [ports, InputOperandMachine.slot, i.isLt, SiteProcessorPorts.native])).elim
+ | _ => rfl
+ | _ => rfl
+ · exact (hj (.inl j) rfl).elim
+ · cases j with
+ | reg i =>
+ by_cases hi : i.val < k
+ · simp [result, hi, labeledInput, SiteProcessorPorts.pub]
+ · exact (hj (.inr (.reg i)) (by simp [ports, hi])).elim
+ | pub i =>
+ exact (hj (.inr (.pub (i.castAdd 2))) (by simp [ports, i.isLt])).elim
+ | persistent => exact (hj (.inr .persistent) rfl).elim
+ | work i => exact (hj (.inr (.work i)) rfl).elim
+ | logPort i => exact (hj (.inr (.logPort i)) rfl).elim
+ · rfl
+
+/-- The installed public bank is ready for the successor guard, the native
+call interpreter, and the physical sorter. -/
+theorem frame_runs (r : ℕ) (args : Fin k → InputOperand) (B a b u lit : ℕ)
+ (hB : 1 ≤ B) (hb : 0 < b) (hab : a ≤ b) (hu : 1 ≤ u) (n : ℕ) (hn : 1 ≤ n) :
+ let d := B * Nat.clog 2 n
+ let e := roundedUp a b n
+ let w := (d+10)^4
+ let g : Geometry := ⟨n,d,2^e,w⟩
+ ∀ (x : SiteCutBank.Input d e w), x.n = n → x.u = u → x.lit = lit →
+ Fits x.prog n d (2^e) w → (UniversalMachine.programPrefix x.prog).length ≤ w →
+ (∀ i, (Expr args i).Fits g (2^w)) →
+ ∃ t ≤ clockCoefficient args B a b u * (n+1)^max 7 (u+1), ∃ s : Stacks (Target r args),
+ (program r args B a b u lit hb).Runs t (labeledInput (SiteProcessorPorts.pub r (Expr args) ProcessorPublic.rawPort)
+ (ProcessorInput.tape x.prog n x.v x.hdr (incidentBits x.sends x.v))) s ∧
+ Frame r (Expr args) x (fun j => Pieces.word g (CounterPublic.actualPrefix x.prog) (args j)) s ∧
+ ∀ j : SitePost.Port, s (.inr (.inr j)) = [] := by
+ intro d e w g x hxn hxu hxl fit hp hf
+ obtain ⟨t, ht, out, hrun, hout⟩ := operand_runs args B a b u lit hB hb hab hu x.prog n hn
+ x.v x.hdr (incidentBits x.sends x.v) fit hp hf
+ let proc := ProcessorPublic.recordResult (ProcessorPublic.rawResult x.prog n d (2^e) w x.v x.hdr
+ (incidentBits x.sends x.v)) n d e w u lit x.v x.hdr x.hcap x.hw
+ obtain ⟨t', ht', hlift⟩ := install r args g _ proc _ out _ hrun
+ refine ⟨t', ?_, _, hlift, ?_, fun _ => rfl⟩
+ · have hw : w ≤ n := by
+ change (UniversalMachine.programPrefix x.prog).length + (d + 4 + width d (2^e) w) ≤ n at fit
+ rw [width_eq] at fit
+ omega
+ let K := (n+1)^max 7 (u+1)
+ have hK : n+1 ≤ K := Nat.le_self_pow (by omega) _
+ change t' ≤ t+2*(w+1)+1 at ht'
+ change t ≤ operandCoefficient args B a b u * K at ht
+ change t' ≤ (operandCoefficient args B a b u+3)*K
+ rw [Nat.add_mul]
+ omega
+ · constructor
+ · rintro (j|j)
+ · change proc j = _
+ simp [proc, SiteCutBank.Input.prepared, hxn, hxu, hxl]
+ · rfl
+ · intro j
+ cases j with
+ | isa y =>
+ cases y with
+ | pub i => exact congrArg wordBits (hout i)
+ | _ => rfl
+ | _ => rfl
+
+end RAMTape.InputOperandStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputParameters.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputParameters.lean
new file mode 100644
index 0000000000..093da63131
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputParameters.lean
@@ -0,0 +1,279 @@
+import OAI.Computability.VPVNP.RAMTapeInputParametersWidthCost
+import OAI.Computability.VPVNP.RAMTapeInput
+import OAI.Computability.VPVNP.RAMTapeInputParametersFromSize
+import OAI.Computability.VPVNP.RAMTapeInputPorts
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMTapeCeilLog
+import OAI.Computability.VPVNP.TallyStacks
+
+/-!
+# Preparing the physical reader's field lengths
+
+Copy the unary input length before computing the address width and the live
+bucket on separate passes. The incident width calculation reads both results,
+after which the bucket tally can be erased. The raw input and the reader's data
+fields are carried through every pass.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputParameters
+
+/-- Work ports for the saved length, unary bucket, and the separate bucket and incident-width
+computations. -/
+inductive Work (K L : Type) where
+ | lengthCopy | bucket | bucketWork (k : K) | widthWork (l : L)
+ deriving DecidableEq, Fintype
+
+private abbrev Registers (K L : Type) := InputPort ⊕ Work K L
+private abbrev ones (k : ℕ) := List.replicate k true
+
+variable {K L : Type} [DecidableEq K] [DecidableEq L]
+
+private def frame (base : Stacks InputPort) (size copy address bucket incident : ℕ) :
+ Stacks (Registers K L)
+ | .inl .size => ones size
+ | .inl .addressCount => ones address
+ | .inl .incidentCount => ones incident
+ | .inl .tmp => []
+ | .inl i => base i
+ | .inr .lengthCopy => ones copy
+ | .inr .bucket => ones bucket
+ | .inr (.bucketWork _) | .inr (.widthWork _) => []
+
+private def copyPort : CeilLog.Port → Registers K L
+ | .src => .inl .size
+ | .tmp => .inl .tmp
+ | .out => .inr .lengthCopy
+
+private def addressPort : CeilLog.Port → Registers K L
+ | .src => .inr .lengthCopy
+ | .tmp => .inl .tmp
+ | .out => .inl .addressCount
+
+private def copyLength : FiniteRoutine (Registers K L) :=
+ (FiniteRoutine.ofRoutine (Tally.copyAdd CeilLog.Port.src .out .tmp)).onPorts copyPort
+
+private def addressWidth (B : ℕ) : FiniteRoutine (Registers K L) :=
+ FiniteRoutine.ofStackCode (CeilLog.code B) addressPort .scan (· == .done)
+
+private theorem copy_run (base : Stacks InputPort) (n : ℕ) :
+ (copyLength (K := K) (L := L)).Runs (5*n+2) (frame base n 0 0 0 0) (frame base n n 0 0 0) := by
+ let s : Tally.State CeilLog.Port := fun i => if i = .src then n else 0
+ have run := Tally.copyAdd_runs CeilLog.Port.src .out .tmp (by decide) (by decide) (by decide) s rfl
+ apply FiniteRoutine.runs_onPorts_framed _ (by intro a b h; cases a <;> cases b <;> simp_all [copyPort]) run
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> simp [frame, copyPort, Tally.encode, s, Function.update]
+ · rintro (i | u) h
+ · cases i <;> rfl
+ · cases u <;> first | rfl | exact (h .out rfl).elim
+
+private theorem address_run (B n : ℕ) (base : Stacks InputPort) :
+ (addressWidth (K := K) (L := L) B).Runs (CeilLog.cost B n)
+ (frame base n n 0 0 0) (frame base n 0 (B * Nat.clog 2 n) 0 0) := by
+ apply FiniteRoutine.runs_ofStackCode_framed
+ (by intro a b h; cases a <;> cases b <;> simp_all [addressPort])
+ rfl rfl (fun z hz => by simp only [beq_iff_eq] at hz; subst z; rfl) (CeilLog.runs B n [])
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> simp [frame, CeilLog.store, addressPort]
+ · rintro (i | u) h
+ · cases i <;> first | rfl | exact (h .out rfl).elim
+ · cases u <;> first | rfl | exact (h .src rfl).elim
+
+private def clearCode : StackCode Unit Bool
+ | false => .pop () (fun b => b.isNone)
+ | true => .halt true
+
+private def clearBucket : FiniteRoutine (Registers K L) :=
+ FiniteRoutine.ofStackCode clearCode (fun _ => .inr .bucket) false id
+
+private theorem clear_run (base : Stacks InputPort) (d H width : ℕ) :
+ (clearBucket (K := K) (L := L)).Runs (H+1) (frame base 0 0 d H width) (frame base 0 0 d 0 width) := by
+ have hh (h : ℕ) : StackRuns clearCode (h+1) false (fun _ => ones h) true (fun _ => []) := by
+ induction h with
+ | zero => exact .cons (.pop rfl) (.nil ..)
+ | succ h ih =>
+ refine .cons (.pop rfl) ?_
+ convert ih using 1
+ · simp [ones, List.replicate_succ]
+ · funext j; cases j; simp [ones, List.replicate_succ]
+ apply FiniteRoutine.runs_ofStackCode_framed (fun _ _ _ => Subsingleton.elim ..) rfl rfl
+ (by intro z hz; cases z <;> simp_all [clearCode]) (hh H)
+ · intro i; cases i; rfl
+ · intro i; cases i; rfl
+ · rintro (i | u) h
+ · cases i <;> rfl
+ · cases u <;> first | rfl | exact (h () rfl).elim
+
+private def bucketPort : InputBucketFromSize.Port → Registers InputBucketFromSize.Port L
+ | .size => .inl .size
+ | .bucket => .inr .bucket
+ | r => .inr (.bucketWork r)
+
+private def computeBucket (p q : ℕ) (hq : 0 < q) :
+ FiniteRoutine (Registers InputBucketFromSize.Port L) :=
+ (InputBucketFromSize.routine p q hq).onPorts bucketPort
+
+private theorem computeBucket_run (base : Stacks InputPort) (d p q n : ℕ)
+ (hq : 0 < q) (hpq : p ≤ q) (hn : 1 ≤ n) :
+ ∃ t ≤ InputBucketFromSize.clockCoefficient p q * (n+1)^2,
+ (computeBucket (L := L) p q hq).Runs t (frame base n 0 d 0 0)
+ (frame base 0 0 d (2^BurstRAM.roundedUp p q n) 0) := by
+ obtain ⟨t, ht, run⟩ := InputBucketFromSize.runs p q n hq hpq hn
+ refine ⟨t, ht, ?_⟩
+ apply FiniteRoutine.runs_onPorts_framed _ (by intro a b h; cases a <;> cases b <;> simp_all [bucketPort]) run
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> rfl
+ · rintro (i | u) h
+ · cases i <;> first | rfl | exact (h .size rfl).elim
+ · cases u <;> first | rfl | exact (h .bucket rfl).elim
+
+/-- Scratch bank for preparing the physical input fields with the bucket and width subroutines. -/
+abbrev Scratch := Work InputBucketFromSize.Port InputWidth.Port
+
+private def widthPort : InputWidth.Port → InputPort ⊕ Scratch
+ | .address => .inl .addressCount
+ | .bucket => .inr .bucket
+ | .incident => .inl .incidentCount
+ | r => .inr (.widthWork r)
+
+private def incidentWidth : FiniteRoutine (InputPort ⊕ Scratch) :=
+ (FiniteRoutine.ofRoutine InputWidth.program.code).onPorts widthPort
+
+private theorem incident_run (base : Stacks InputPort) (d H : ℕ) :
+ incidentWidth.Runs (InputWidth.program.work (InputWidth.initial d H))
+ (frame base 0 0 d H 0) (frame base 0 0 d H (RAMLayout.width d H ((d+10)^4))) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (by intro a b h; cases a <;> cases b <;> simp_all [widthPort])
+ (InputWidth.runs d H)
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> rfl
+ · rintro (i | u) h
+ · cases i <;> first | rfl | exact (h .incident rfl).elim
+ · cases u <;> rfl
+
+/-- The only length-dependent data are on stacks. The finite control depends
+on the fixed address multiplier and rational exponent. -/
+def routineKeep (B p q : ℕ) (hq : 0 < q) : FiniteRoutine (InputPort ⊕ Scratch) :=
+ ((copyLength.followedBy (addressWidth B)).followedBy (computeBucket p q hq)).followedBy incidentWidth
+
+/-- A parser-only run erases the bucket tally after preparing the two lengths. -/
+def routine (B p q : ℕ) (hq : 0 < q) : FiniteRoutine (InputPort ⊕ Scratch) :=
+ (routineKeep B p q hq).followedBy clearBucket
+
+/-- The parameter stage preserves all reader stacks outside its working registers. -/
+def readerFrame (base : Stacks InputPort) (size copy d H width : ℕ) : Stacks (InputPort ⊕ Scratch) :=
+ frame base size copy d H width
+
+/-- Parser stacks with their literal input and the unary counters. -/
+def bank (raw : List Bool) (size copy d H width : ℕ) : Stacks (InputPort ⊕ Scratch) :=
+ readerFrame (InputReader.prepared raw 0 0 []) size copy d H width
+
+theorem bank_inl (raw : List Bool) (size copy d H width : ℕ) (i : InputPort) :
+ bank raw size copy d H width (.inl i) =
+ InputReader.prepared raw d width (List.replicate size true) i := by cases i <;> rfl
+
+@[simp] theorem bank_bucket (raw : List Bool) (size copy d H width : ℕ) :
+ bank raw size copy d H width (.inr .bucket) = List.replicate H true := rfl
+
+theorem bank_inr_other (raw : List Bool) (size d H width : ℕ) (i : Scratch) (hi : i ≠ .bucket) :
+ bank raw size 0 d H width (.inr i) = [] := by cases i <;> first | rfl | contradiction
+
+theorem bank_inr_empty (raw : List Bool) (size d width : ℕ) (i : Scratch) :
+ bank raw size 0 d 0 width (.inr i) = [] := by cases i <;> rfl
+
+/-- Sum of instruction bounds for the five passes. -/
+private def prepBudget (B p q n : ℕ) : ℕ :=
+ let d := B * Nat.clog 2 n
+ let H := 2^BurstRAM.roundedUp p q n
+ 5*n+2 + CeilLog.cost B n + InputBucketFromSize.clockCoefficient p q * (n+1)^2 +
+ InputWidth.program.work (InputWidth.initial d H)
+
+/-- Step budget for preparing field widths, including erasure of the unary bucket copy. -/
+def budget (B p q n : ℕ) := prepBudget B p q n + (2^BurstRAM.roundedUp p q n + 1)
+
+set_option maxHeartbeats 1000000 in
+private theorem keep_framed (B p q n : ℕ) (hq : 0 < q) (hpq : p ≤ q) (hn : 1 ≤ n)
+ (base : Stacks InputPort) :
+ let d := B * Nat.clog 2 n
+ let H := 2^BurstRAM.roundedUp p q n
+ ∃ t ≤ prepBudget B p q n, (routineKeep B p q hq).Runs t (readerFrame base n 0 0 0 0)
+ (readerFrame base 0 0 d H (RAMLayout.width d H ((d+10)^4))) := by
+ let d := B * Nat.clog 2 n
+ let H := 2^BurstRAM.roundedUp p q n
+ obtain ⟨t, ht, hb⟩ := computeBucket_run (L := InputWidth.Port) base d p q n hq hpq hn
+ have copy := copy_run (K := InputBucketFromSize.Port) (L := InputWidth.Port) base n
+ have addr := address_run (K := InputBucketFromSize.Port) (L := InputWidth.Port) B n base
+ have first := FiniteRoutine.Runs.followedBy copy addr
+ have second := FiniteRoutine.Runs.followedBy first hb
+ have third := FiniteRoutine.Runs.followedBy second (incident_run base d H)
+ refine ⟨_, ?_, third⟩
+ unfold prepBudget
+ exact Nat.add_le_add_right (Nat.add_le_add_left ht _) _
+
+/-- Keep the bucket tally for subsequent validation after parsing the address and incident fields. -/
+theorem runs_keep (B p q n : ℕ) (hq : 0 < q) (hpq : p ≤ q) (hn : 1 ≤ n) (raw : List Bool) :
+ let d := B * Nat.clog 2 n
+ let H := 2^BurstRAM.roundedUp p q n
+ ∃ t ≤ budget B p q n, (routineKeep B p q hq).Runs t (bank raw n 0 0 0 0)
+ (bank raw 0 0 d H (RAMLayout.width d H ((d+10)^4))) := by
+ obtain ⟨t, ht, h⟩ := keep_framed B p q n hq hpq hn (InputReader.prepared raw 0 0 [])
+ exact ⟨t, ht.trans (Nat.le_add_right ..), h⟩
+
+theorem runs_framed (B p q n : ℕ) (hq : 0 < q) (hpq : p ≤ q) (hn : 1 ≤ n)
+ (base : Stacks InputPort) :
+ let d := B * Nat.clog 2 n
+ let H := 2^BurstRAM.roundedUp p q n
+ ∃ t ≤ budget B p q n, (routine B p q hq).Runs t (readerFrame base n 0 0 0 0)
+ (readerFrame base 0 0 d 0 (RAMLayout.width d H ((d+10)^4))) := by
+ let d := B * Nat.clog 2 n
+ let H := 2^BurstRAM.roundedUp p q n
+ obtain ⟨t, ht, h⟩ := keep_framed B p q n hq hpq hn base
+ exact ⟨_, Nat.add_le_add_right ht _, FiniteRoutine.Runs.followedBy h
+ (clear_run base d H (RAMLayout.width d H ((d+10)^4)))⟩
+
+/-- On the physical input tape the address and incident counts become available
+to the parser and all private scratch stacks finish empty. -/
+theorem runs (B p q n : ℕ) (hq : 0 < q) (hpq : p ≤ q) (hn : 1 ≤ n) (raw : List Bool) :
+ let d := B * Nat.clog 2 n
+ let H := 2^BurstRAM.roundedUp p q n
+ ∃ t ≤ budget B p q n, (routine B p q hq).Runs t (bank raw n 0 0 0 0)
+ (bank raw 0 0 d 0 (RAMLayout.width d H ((d+10)^4))) :=
+ runs_framed B p q n hq hpq hn _
+
+/-- A constant depending only on the address multiplier and fixed exponent. -/
+def clockCoefficient (B p q : ℕ) : ℕ :=
+ 7 + (B+32) + InputBucketFromSize.clockCoefficient p q + 917*(B+13)^7 + 3
+
+/-- A polynomial clock for preparing both input fields, uniform in the tape length. -/
+theorem budget_le (B p q n : ℕ) (hq : 0 < q) (hpq : p ≤ q) (hn : 1 ≤ n) :
+ budget B p q n ≤ clockCoefficient B p q * (n+1)^7 := by
+ let d := B * Nat.clog 2 n
+ let H := 2^BurstRAM.roundedUp p q n
+ have hc : Nat.clog 2 n ≤ n := Nat.clog_le_of_le_pow (Nat.lt_pow_self (by decide : 1 < 2)).le
+ have hd : d ≤ B*n := Nat.mul_le_mul_left _ hc
+ have hH : H ≤ 2*n := InputBucketFromSize.bucket_le hq hpq hn
+ have hw : d+H+11 ≤ (B+13)*(n+1) := by
+ simp only [Nat.add_mul, Nat.mul_add, Nat.mul_one]
+ omega
+ have h₁ : n+1 ≤ (n+1)^7 := by
+ simpa using Nat.pow_le_pow_right (Nat.succ_pos n) (by decide : 1 ≤ 7)
+ have h₂ : (n+1)^2 ≤ (n+1)^7 := Nat.pow_le_pow_right (Nat.succ_pos n) (by decide)
+ have hcopy : 5*n+2 ≤ 7*(n+1)^7 := by
+ apply (show 5*n+2 ≤ 7*(n+1) by omega).trans
+ exact Nat.mul_le_mul_left _ h₁
+ have hlog := (CeilLog.cost_le B n).trans (Nat.mul_le_mul_left _ h₁)
+ have hwidth := (InputWidth.work_le_seventh d H).trans
+ (Nat.mul_le_mul_left 917 (Nat.pow_le_pow_left hw 7))
+ rw [Nat.mul_pow, ← Nat.mul_assoc] at hwidth
+ have hclear : H+1 ≤ 3*(n+1)^7 := (show H+1 ≤ 3*(n+1) by omega).trans (Nat.mul_le_mul_left _ h₁)
+ have hsum := Nat.add_le_add (Nat.add_le_add (Nat.add_le_add (Nat.add_le_add hcopy hlog)
+ (Nat.mul_le_mul_left (InputBucketFromSize.clockCoefficient p q) h₂)) hwidth) hclear
+ simpa only [budget, prepBudget, clockCoefficient, d, H, Nat.add_mul] using hsum
+
+end RAMTape.InputParameters
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputParametersBucket.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersBucket.lean
new file mode 100644
index 0000000000..db65a8945e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersBucket.lean
@@ -0,0 +1,224 @@
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Data.Fintype.Sum
+import Mathlib.Data.Fintype.EquivFin
+import Mathlib.Tactic.DeriveFintype
+import Mathlib.Tactic.Positivity
+import Mathlib.Tactic.Ring
+
+/-!
+# Computing a unary bucket size from the rounded binary exponent
+
+The denominator is fixed in the finite control. For each nonempty block of at
+most `q` input bits the machine doubles its unary output, using a third stack
+temporarily. Every instruction reads or writes a single stack bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputBucket
+
+/-- Stack labels for the logarithm marks, unary bucket, and temporary doubling stack. -/
+inductive Port
+ | src | out | tmp
+ deriving DecidableEq
+
+instance : Fintype Port :=
+ ⟨{.src, .out, .tmp}, fun p => by cases p <;> simp⟩
+
+/-- States that double the unary bucket once per block and count the remaining skips within a
+block of size at most the fixed denominator. -/
+inductive State (q : ℕ)
+ | init | block | copy | pushFirst | pushSecond | restore | putBack | skip (r : Fin q) | done
+ deriving DecidableEq, Fintype
+
+/-- Start with one bucket mark and double its unary value once for every nonempty block of at
+most the denominator’s number of input marks. -/
+def code (q : ℕ) (hq : 0 < q) : StackCode Port (State q)
+ | .init => .push .out true .block
+ | .block => .pop .src (fun b => b.elim .done (fun _ => .copy))
+ | .copy => .pop .out (fun b => b.elim .restore (fun _ => .pushFirst))
+ | .pushFirst => .push .tmp true .pushSecond
+ | .pushSecond => .push .tmp true .copy
+ | .restore => .pop .tmp (fun b => b.elim (.skip ⟨q - 1, by omega⟩) (fun _ => .putBack))
+ | .putBack => .push .out true .restore
+ | .skip r => if r.val = 0 then .goto .block else
+ .pop .src (fun b => b.elim .block (fun _ => .skip ⟨r.val - 1, by have := r.isLt; omega⟩))
+ | .done => .halt true
+
+/-- Represent the input, output, and scratch tallies of the bucket routine as stacks of true
+bits. -/
+def store (src out tmp : ℕ) : Stacks Port
+ | .src => List.replicate src true
+ | .out => List.replicate out true
+ | .tmp => List.replicate tmp true
+
+private theorem set_store (src out tmp v : ℕ) (k : Port) :
+ Function.update (store src out tmp) k (List.replicate v true) = match k with
+ | .src => store v out tmp
+ | .out => store src v tmp
+ | .tmp => store src out v := by
+ cases k <;> funext j <;> cases j <;> simp [store]
+
+variable {q : ℕ} (hq : 0 < q)
+
+private theorem pop_src_succ {n a t : ℕ} {s : State q} {f}
+ (h : code q hq s = .pop .src f) :
+ StackStep (code q hq) s (store (n + 1) a t) (f (some true)) (store n a t) := by
+ simpa only [store, List.replicate_succ, List.head?_cons, List.tail_cons, set_store]
+ using StackStep.pop (s := store (n + 1) a t) h
+
+private theorem pop_src_zero {a t : ℕ} {s : State q} {f}
+ (h : code q hq s = .pop .src f) :
+ StackStep (code q hq) s (store 0 a t) (f none) (store 0 a t) := by
+ have he := StackStep.pop (s := store 0 a t) h
+ change StackStep _ _ _ (f none) (Function.update (store 0 a t) .src (List.replicate 0 true)) at he
+ simpa only [set_store] using he
+
+private theorem pop_out_succ {n a t : ℕ} {s : State q} {f}
+ (h : code q hq s = .pop .out f) :
+ StackStep (code q hq) s (store n (a + 1) t) (f (some true)) (store n a t) := by
+ simpa only [store, List.replicate_succ, List.head?_cons, List.tail_cons, set_store]
+ using StackStep.pop (s := store n (a + 1) t) h
+
+private theorem pop_tmp_succ {n a t : ℕ} {s : State q} {f}
+ (h : code q hq s = .pop .tmp f) :
+ StackStep (code q hq) s (store n a (t + 1)) (f (some true)) (store n a t) := by
+ simpa only [store, List.replicate_succ, List.head?_cons, List.tail_cons, set_store]
+ using StackStep.pop (s := store n a (t + 1)) h
+
+private theorem push_tmp {n a t : ℕ} {s s' : State q} (h : code q hq s = .push .tmp true s') :
+ StackStep (code q hq) s (store n a t) s' (store n a (t + 1)) := by
+ have he := StackStep.push (s := store n a t) h
+ change StackStep _ _ _ _ (Function.update (store n a t) .tmp (List.replicate (t+1) true)) at he
+ simpa only [set_store] using he
+
+private theorem push_out {n a t : ℕ} {s s' : State q} (h : code q hq s = .push .out true s') :
+ StackStep (code q hq) s (store n a t) s' (store n (a + 1) t) := by
+ have he := StackStep.push (s := store n a t) h
+ change StackStep _ _ _ _ (Function.update (store n a t) .out (List.replicate (a+1) true)) at he
+ simpa only [set_store] using he
+
+private theorem copy_run (n a t : ℕ) :
+ StackRuns (code q hq) (3*a+1) .copy (store n a t) .restore (store n 0 (t+2*a)) := by
+ induction a generalizing t with
+ | zero =>
+ have he := StackStep.pop (s := store n 0 t) (show code q hq .copy = .pop .out _ from rfl)
+ change StackStep (code q hq) _ _ .restore (Function.update (store n 0 t) .out (List.replicate 0 true)) at he
+ simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, set_store] using
+ StackRuns.cons he (StackRuns.nil _ _)
+ | succ a ih =>
+ have h := StackRuns.cons (pop_out_succ hq (show code q hq .copy = .pop .out _ from rfl))
+ (StackRuns.cons (push_tmp hq (show code q hq .pushFirst = .push .tmp true _ from rfl))
+ (StackRuns.cons (push_tmp hq (show code q hq .pushSecond = .push .tmp true _ from rfl))
+ (ih (t + 1 + 1))))
+ convert h using 1
+ congr 1
+ omega
+
+private theorem restore_run (n a t : ℕ) :
+ StackRuns (code q hq) (2*t+1) .restore (store n a t) (.skip ⟨q-1, by omega⟩) (store n (a+t) 0) := by
+ induction t generalizing a with
+ | zero =>
+ have he := StackStep.pop (s := store n a 0) (show code q hq .restore = .pop .tmp _ from rfl)
+ change StackStep (code q hq) _ _ (.skip ⟨q-1, by omega⟩)
+ (Function.update (store n a 0) .tmp (List.replicate 0 true)) at he
+ simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, set_store] using
+ StackRuns.cons he (StackRuns.nil _ _)
+ | succ t ih =>
+ have h := StackRuns.cons (pop_tmp_succ hq (show code q hq .restore = .pop .tmp _ from rfl))
+ (StackRuns.cons (push_out hq (show code q hq .putBack = .push .out true _ from rfl)) (ih (a+1)))
+ convert h using 1
+ congr 1
+ omega
+
+private theorem skip_run (r : Fin q) (n a : ℕ) : ∃ u ≤ r.val + 1,
+ StackRuns (code q hq) u (.skip r) (store n a 0) .block (store (n-r.val) a 0) := by
+ obtain ⟨r,hr⟩ := r
+ induction r generalizing n with
+ | zero =>
+ refine ⟨1, le_rfl, ?_⟩
+ exact .cons (.goto (by simp [code])) (.nil ..)
+ | succ r ih =>
+ have hc : code q hq (.skip ⟨r+1,hr⟩) = .pop .src
+ (fun b => b.elim .block (fun _ => .skip ⟨r, by omega⟩)) := by simp [code]
+ cases n with
+ | zero =>
+ refine ⟨1, by simp, ?_⟩
+ simp only [Nat.zero_sub]
+ exact .cons (pop_src_zero hq hc) (.nil ..)
+ | succ n =>
+ obtain ⟨u, hu, run⟩ := ih n (by omega)
+ refine ⟨u+1, by simp at hu ⊢; omega, ?_⟩
+ simpa using StackRuns.cons (pop_src_succ hq hc) run
+
+private def rounds (k q : ℕ) := (k + (q - 1)) / q
+
+private theorem rounds_zero (hq : 0 < q) : rounds 0 q = 0 := by
+ simp only [rounds, Nat.zero_add]
+ exact Nat.div_eq_of_lt (by omega)
+
+private theorem rounds_succ (hq : 0 < q) (k : ℕ) : rounds (k+1) q = rounds (k - (q-1)) q + 1 := by
+ unfold rounds
+ by_cases h : q - 1 ≤ k
+ · have h₁ : k + 1 + (q - 1) = k + q := by omega
+ have h₂ : k - (q - 1) + (q - 1) = k := by omega
+ rw [h₁, h₂, Nat.add_div_right _ hq]
+ · have h₁ : k + 1 + (q - 1) = k + q := by omega
+ have h₂ : k - (q - 1) = 0 := by omega
+ rw [h₁, h₂, Nat.zero_add, Nat.add_div_right _ hq, Nat.div_eq_of_lt (by omega : k < q),
+ Nat.div_eq_of_lt (by omega : q-1 < q)]
+
+private theorem loop_run (k a : ℕ) : ∃ t ≤ (k+1)*(q+10)*(a * 2^rounds k q+1),
+ StackRuns (code q hq) t .block (store k a 0) .done (store 0 (a * 2^rounds k q) 0) := by
+ induction k using Nat.strong_induction_on generalizing a with
+ | h k ih =>
+ cases k with
+ | zero =>
+ rw [rounds_zero hq, pow_zero, Nat.mul_one]
+ refine ⟨1, Nat.succ_le_iff.mpr (by positivity), ?_⟩
+ exact .cons (pop_src_zero hq (show code q hq .block = .pop .src _ from rfl)) (.nil ..)
+ | succ k =>
+ let r := k - (q-1)
+ have hr : r < k+1 := by dsimp [r]; omega
+ obtain ⟨s, hs, scan⟩ := skip_run hq ⟨q-1, by omega⟩ k (2*a)
+ have hfirst := StackRuns.cons (pop_src_succ hq (show code q hq .block = .pop .src _ from rfl))
+ (((copy_run hq k a 0).trans (by simpa using restore_run hq k 0 (2*a))).trans scan)
+ obtain ⟨t,ht,run⟩ := ih r hr (2*a)
+ have he : a*2^rounds (k+1) q = (2*a)*2^rounds r q := by
+ rw [rounds_succ hq, pow_succ]; dsimp [r]; ring
+ rw [he]
+ refine ⟨_, ?_, hfirst.trans run⟩
+ have hs' : s ≤ q := by change s ≤ q-1+1 at hs; omega
+ let A := (2*a)*2^rounds r q+1
+ have ha : a ≤ A := by
+ have he' := Nat.mul_le_mul_left (2*a) (Nat.one_le_two_pow (n := rounds r q))
+ dsimp [A]
+ omega
+ have hround : (3*a+1 + (2*(2*a)+1) + s + 1) ≤ (q+10)*A := by
+ have h₁ := Nat.mul_le_mul_left 10 ha
+ have h₂ := Nat.mul_le_mul_left q (by dsimp [A]; omega : 1 ≤ A)
+ rw [Nat.add_mul]
+ dsimp [A] at *
+ omega
+ have hremain : t ≤ (k+1)*(q+10)*A :=
+ ht.trans (Nat.mul_le_mul_right A (Nat.mul_le_mul_right (q+10) (by omega)))
+ calc
+ _ ≤ (q+10)*A + (k+1)*(q+10)*A := Nat.add_le_add hround hremain
+ _ = _ := by ring
+
+/-- From initially empty work stacks, compute the unary bucket size and clear the input. -/
+theorem bucket_run (q k : ℕ) (hq : 0 < q) :
+ ∃ t ≤ (k+1)*(q+10)*(2^((k+(q-1))/q)+1)+1,
+ StackRuns (code q hq) t .init (store k 0 0) .done (store 0 (2^((k+(q-1))/q)) 0) := by
+ obtain ⟨t, ht, h⟩ := loop_run hq k 1
+ simp only [Nat.one_mul, rounds] at ht h
+ exact ⟨t+1, Nat.add_le_add_right ht 1,
+ .cons (push_out hq (show code q hq .init = .push .out true _ from rfl)) h⟩
+
+end RAMTape.InputBucket
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputParametersFromSize.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersFromSize.lean
new file mode 100644
index 0000000000..73dbb9ac94
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersFromSize.lean
@@ -0,0 +1,241 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMTapeInputParametersLog
+import OAI.Computability.VPVNP.RAMTapeInputParametersPower
+import OAI.Computability.VPVNP.RAMTapeInputParametersBucket
+import OAI.Computability.VPVNP.RAMTapeUnaryWord
+import OAI.Computability.VPVNP.RAMParameters
+
+/-!
+# Computing the live bucket from the unary input length
+
+The fixed rational exponent has numerator `p` and positive denominator `q`.
+The potentially large integer `n^p` stays in a padded binary word. Only its
+binary logarithm and the final bucket size are expanded as unary tallies.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputBucketFromSize
+
+open BurstRAM
+
+/-- Stack labels for converting unary size to a padded word, exponentiating, taking its
+logarithm, and producing the unary bucket. -/
+inductive Port
+ | size | bucket | base | acc | log | tmp | pending | factor | product | shifted | sum
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Initialize the named size, base, power accumulator, logarithm, and bucket stacks with empty
+arithmetic scratch. -/
+def store (size base acc log bucket : List Bool) : Stacks Port
+ | .size => size
+ | .base => base
+ | .acc => acc
+ | .log => log
+ | .bucket => bucket
+ | _ => []
+
+/-- Connect unary-to-word conversion to the size, pending marks, base, initial unit, and
+temporary stack of bucket preparation. -/
+def unaryPort : UnaryWord.Port → Port
+ | .src => .size
+ | .pending => .pending
+ | .number => .base
+ | .unit => .acc
+ | .tmp => .tmp
+
+/-- Connect repeated multiplication to the base, accumulator, factor, product, shifted factor,
+sum, and temporary stack. -/
+def powerPort : InputPower.Port → Port
+ | .base => .base
+ | .tmp => .tmp
+ | .mul .multiplier => .acc
+ | .mul .multiplicand => .factor
+ | .mul .accumulator => .product
+ | .mul .shifted => .shifted
+ | .mul .sum => .sum
+
+/-- Feed the power accumulator to the word ceiling-log scan and collect its marks on the
+logarithm stack. -/
+def logPort : WordCeilLog.Port → Port
+ | .word => .acc
+ | .tmp => .tmp
+ | .out => .log
+
+/-- Feed logarithm marks into the block-doubling routine and collect the resulting unary
+bucket. -/
+def bucketPort : InputBucket.Port → Port
+ | .src => .log
+ | .out => .bucket
+ | .tmp => .tmp
+
+private def unary (p : ℕ) := FiniteRoutine.ofStackCode (UnaryWord.code p) unaryPort
+ (.alloc (Fin.last (p+1))) (· == .done)
+private def power (p : ℕ) := FiniteRoutine.ofStackCode (InputPower.code p) powerPort
+ (.round (Fin.last p) .test) (· == .done)
+private def logarithm := FiniteRoutine.ofStackCode WordCeilLog.code logPort .reverse (· == .done)
+private def bucket (q : ℕ) (hq : 0 < q) := FiniteRoutine.ofStackCode (InputBucket.code q hq)
+ bucketPort .init (· == .done)
+
+private def clearCode : StackCode Unit Bool
+ | false => .pop () Option.isNone
+ | true => .halt true
+
+private def clearBase := FiniteRoutine.ofStackCode clearCode (fun _ => Port.base) false id
+
+/-- One finite control per fixed rational parameter, independent of input length. -/
+def routine (p q : ℕ) (hq : 0 < q) : FiniteRoutine Port :=
+ ((((unary p).followedBy (power p)).followedBy clearBase).followedBy logarithm).followedBy (bucket q hq)
+
+private theorem unary_run (p n : ℕ) :
+ (unary p).Runs (UnaryWord.work p n) (store (List.replicate n true) [] [] [] [])
+ (store [] (wordBits (UnaryWord.inputWord p n)) (wordBits (UnaryWord.unitWord p n)) [] []) := by
+ apply FiniteRoutine.runs_ofStackCode_framed (by decide) rfl rfl (fun z h => by simp only [beq_iff_eq] at h; subst z; rfl)
+ (UnaryWord.runs p n)
+ · intro k; cases k <;> rfl
+ · intro k; cases k <;> rfl
+ · intro i hi
+ cases i <;> first | rfl | exact (hi .src rfl).elim | exact (hi .number rfl).elim | exact (hi .unit rfl).elim
+
+/-- The allocated width suffices even when the rational numerator is large. -/
+theorem power_fits (p n : ℕ) : n^p < 2^(UnaryWord.width p n) := by
+ have h : n ≤ 2^(n+1) := (Nat.lt_pow_self (by decide : 1 < 2)).le.trans
+ (Nat.pow_le_pow_right (by decide) (Nat.le_succ n))
+ calc
+ n^p ≤ (2^(n+1))^p := Nat.pow_le_pow_left h p
+ _ = 2^(p*(n+1)) := by rw [← pow_mul, Nat.mul_comm]
+ _ < _ := Nat.pow_lt_pow_right (by decide) (by simp [UnaryWord.width, Nat.succ_mul])
+
+private def powerWord (p n : ℕ) : Word (UnaryWord.width p n) := ⟨n^p, power_fits p n⟩
+
+private theorem power_run (p n : ℕ) :
+ let w := UnaryWord.width p n
+ let x := wordBits (UnaryWord.inputWord p n)
+ (power p).Runs (p*(8*w^2+18*w+10)+1) (store [] x (wordBits (UnaryWord.unitWord p n)) [] [])
+ (store [] x (wordBits (powerWord p n)) [] []) := by
+ have h := InputPower.power_run (Fin.last p) (UnaryWord.inputWord p n) (UnaryWord.unitWord p n)
+ simp only [Fin.val_last, UnaryWord.inputWord_val, UnaryWord.unitWord_val, Nat.mul_one] at h
+ have he : Fin.ofNat (2 ^ UnaryWord.width p n) (n^p) = powerWord p n :=
+ Fin.ext (Nat.mod_eq_of_lt (power_fits p n))
+ rw [he] at h
+ apply FiniteRoutine.runs_ofStackCode_framed (by decide) rfl rfl (fun z hh => by simp only [beq_iff_eq] at hh; subst z; rfl) h
+ · intro k; cases k with
+ | base | tmp => rfl
+ | mul r => cases r <;> rfl
+ · intro k; cases k with
+ | base | tmp => rfl
+ | mul r => cases r <;> rfl
+ · intro i hi; cases i <;> first | rfl | exact (hi (.mul .multiplier) rfl).elim
+
+private theorem clear_run (x a : List Bool) :
+ clearBase.Runs (x.length+1) (store [] x a [] []) (store [] [] a [] []) := by
+ have loop (l : List Bool) : StackRuns clearCode (l.length+1) false (fun _ => l) true (fun _ => []) := by
+ induction l with
+ | nil => exact .cons (.pop rfl) (.nil ..)
+ | cons b l ih =>
+ refine .cons (.pop rfl) ?_
+ convert ih using 1
+ · rfl
+ · funext u; cases u; simp
+ apply FiniteRoutine.runs_ofStackCode_framed (by decide) rfl rfl (by intro b h; cases b <;> simp_all [clearCode]) (loop x)
+ · intro u; cases u; rfl
+ · intro u; cases u; rfl
+ · intro i hi; cases i <;> first | rfl | exact (hi () rfl).elim
+
+private theorem log_run (p n : ℕ) :
+ ∃ t ≤ 4*(UnaryWord.width p n)+3, logarithm.Runs t (store [] [] (wordBits (powerWord p n)) [] [])
+ (store [] [] [] (List.replicate (Nat.clog 2 (n^p)) true) []) := by
+ obtain ⟨t, ht, h⟩ := WordCeilLog.runs (wordBits (powerWord p n)) []
+ simp only [length_wordBits, TapeWord.value_wordBits, powerWord, List.append_nil] at ht h
+ refine ⟨t, ht, ?_⟩
+ apply FiniteRoutine.runs_ofStackCode_framed (by decide) rfl rfl (fun z hh => by simp only [beq_iff_eq] at hh; subst z; rfl) h
+ · intro k; cases k <;> rfl
+ · intro k; cases k <;> rfl
+ · intro i hi; cases i <;> first | rfl | exact (hi .word rfl).elim | exact (hi .out rfl).elim
+
+private theorem bucket_run (p q n : ℕ) (hq : 0 < q) :
+ let k := Nat.clog 2 (n^p)
+ let H := 2^(roundedUp p q n)
+ ∃ t ≤ (k+1)*(q+10)*(H+1)+1, (bucket q hq).Runs t (store [] [] [] (List.replicate k true) [])
+ (store [] [] [] [] (List.replicate H true)) := by
+ obtain ⟨t, ht, h⟩ := InputBucket.bucket_run q (Nat.clog 2 (n^p)) hq
+ dsimp only
+ rw [roundedUp, Nat.clog_pow_left]
+ refine ⟨t, ht, ?_⟩
+ apply FiniteRoutine.runs_ofStackCode_framed (by decide) rfl rfl (fun z hh => by simp only [beq_iff_eq] at hh; subst z; rfl) h
+ · intro k; cases k <;> rfl
+ · intro k; cases k <;> rfl
+ · intro i hi; cases i <;> first | rfl | exact (hi .src rfl).elim | exact (hi .out rfl).elim
+
+/-- With exponent at most one, rounding to a binary power costs at most a
+factor of two in the live bucket size. -/
+theorem bucket_le {p q n : ℕ} (hq : 0 < q) (hpq : p ≤ q) (hn : 1 ≤ n) :
+ 2^(roundedUp p q n) ≤ 2*n := by
+ have e : roundedUp p q n ≤ Nat.clog 2 n := by
+ rw [roundedUp, Nat.clog_le_iff_le_pow (Nat.one_lt_pow hq.ne' (by decide))]
+ calc
+ n^p ≤ n^q := Nat.pow_le_pow_right (by omega) hpq
+ _ ≤ (2^(Nat.clog 2 n))^q := Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) n) _
+ _ = _ := by rw [← pow_mul, ← pow_mul, Nat.mul_comm]
+ apply (Nat.pow_le_pow_right (by decide : 0 < 2) e).trans
+ by_cases h : 1 < n
+ · have he := Nat.clog_pos (by decide : 1 < 2) h
+ have ht := Nat.pow_pred_clog_lt_self (by decide : 1 < 2) h
+ calc
+ 2^(Nat.clog 2 n) = 2^(Nat.clog 2 n).pred*2 := by
+ rw [← pow_succ]
+ exact congrArg (2^·) (Nat.succ_pred_eq_of_pos he).symm
+ _ ≤ 2*n := by omega
+ · have : n = 1 := by omega
+ subst n
+ decide
+
+/-- The clock's coefficient depends on the fixed rational. Its degree in
+the input length is two for all numerators and denominators. -/
+def clockCoefficient (p q : ℕ) : ℕ :=
+ 12*(p+1) + (36*p+1)*(p+1)^2 + 9*(p+1) + (6*(p+1)*(q+10)+1)
+
+theorem runs (p q n : ℕ) (hq : 0 < q) (hpq : p ≤ q) (hn : 1 ≤ n) :
+ ∃ t ≤ clockCoefficient p q * (n+1)^2,
+ (routine p q hq).Runs t (store (List.replicate n true) [] [] [] [])
+ (store [] [] [] [] (List.replicate (2^(roundedUp p q n)) true)) := by
+ let w := UnaryWord.width p n
+ let H := 2^(roundedUp p q n)
+ let k := Nat.clog 2 (n^p)
+ obtain ⟨t₁, ht₁, hlog⟩ := log_run p n
+ obtain ⟨t₂, ht₂, hbucket⟩ := bucket_run p q n hq
+ have hclear := clear_run (wordBits (UnaryWord.inputWord p n)) (wordBits (powerWord p n))
+ rw [length_wordBits] at hclear
+ have hrun := ((((unary_run p n).followedBy (power_run p n)).followedBy hclear).followedBy hlog).followedBy hbucket
+ refine ⟨_, ?_, hrun⟩
+ have hw : 1 ≤ w := UnaryWord.width_pos p n
+ have hsq : w ≤ w^2 := by nlinarith
+ have hnsq : n+1 ≤ (n+1)^2 := by nlinarith
+ have ha := UnaryWord.work_le p n
+ have hb : p*(8*w^2+18*w+10)+1 ≤ (36*p+1)*(p+1)^2*(n+1)^2 := calc
+ _ ≤ p*(36*w^2)+w^2 := Nat.add_le_add (Nat.mul_le_mul_left _ (by omega)) (by omega)
+ _ = _ := by simp only [w, UnaryWord.width]; ring
+ have hc : (w+1)+t₁ ≤ 9*(p+1)*(n+1)^2 := calc
+ _ ≤ 9*w := by change t₁ ≤ 4*w+3 at ht₁; omega
+ _ ≤ 9*((p+1)*(n+1)^2) := Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ hnsq)
+ _ = _ := by ring
+ have hk : k ≤ w := Nat.clog_le_of_le_pow (power_fits p n).le
+ have hH : H+1 ≤ 3*(n+1) := by have := bucket_le hq hpq hn; dsimp [H]; omega
+ have hd : t₂ ≤ (6*(p+1)*(q+10)+1)*(n+1)^2 := calc
+ _ ≤ (k+1)*(q+10)*(H+1)+1 := ht₂
+ _ ≤ (2*w)*(q+10)*(3*(n+1))+(n+1)^2 :=
+ Nat.add_le_add (Nat.mul_le_mul (Nat.mul_le_mul_right _ (by omega)) hH) (by omega)
+ _ = _ := by simp only [w, UnaryWord.width]; ring
+ change UnaryWord.work p n + (p*(8*w^2+18*w+10)+1) + (w+1) + t₁ + t₂ ≤ _
+ rw [clockCoefficient, Nat.add_mul, Nat.add_mul, Nat.add_mul]
+ omega
+
+end RAMTape.InputBucketFromSize
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputParametersLog.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersLog.lean
new file mode 100644
index 0000000000..50c68e7edd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersLog.lean
@@ -0,0 +1,164 @@
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Tactic.DeriveFintype
+import Mathlib.Data.Nat.Log
+
+/-!
+# Reading the ceiling binary logarithm from a padded word
+
+After reversing the bit stack, skip the leading zeros. For each bit below
+the leading one emit one mark. A final extra mark is needed exactly when
+one of those lower bits was set.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.WordCeilLog
+
+open TapeWord
+
+/-- Labels for the padded word, its reversed copy, and the unary ceiling-log output. -/
+inductive Port | word | tmp | out
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- States for reversing the word, skipping leading zeros, counting lower positions, and
+rounding up if any lower bit is set. -/
+inductive State
+ | reverse | save (bit : Bool) | leading | lower (nonzero : Bool) | mark (nonzero : Bool)
+ | extra | done
+ deriving DecidableEq, Fintype
+
+/-- Emit one unary mark per position below the highest set bit and one more if a lower bit is
+set, giving the ceiling binary logarithm. -/
+def code : StackCode Port State
+ | .reverse => .pop .word fun b => b.elim .leading .save
+ | .save b => .push .tmp b .reverse
+ | .leading => .pop .tmp fun
+ | none => .done
+ | some false => .leading
+ | some true => .lower false
+ | .lower nz => .pop .tmp fun b => b.elim (if nz then .extra else .done) (fun v => .mark (nz || v))
+ | .mark nz => .push .out true (.lower nz)
+ | .extra => .push .out true .done
+ | .done => .halt true
+
+/-- Place the word, its temporary reversal, and accumulated output on the logarithm scanner’s
+ports. -/
+def store (word tmp out : List Bool) : Stacks Port
+ | .word => word
+ | .tmp => tmp
+ | .out => out
+
+private theorem write_store (w t o l : List Bool) (k : Port) :
+ Function.update (store w t o) k l = match k with
+ | .word => store l t o
+ | .tmp => store w l o
+ | .out => store w t l := by funext j; cases k <;> cases j <;> simp [store]
+
+local macro "log_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, write_store])
+
+private theorem reverse_run (x t out : List Bool) :
+ StackRuns code (2*x.length+1) .reverse (store x t out) .leading (store [] (x.reverse ++ t) out) := by
+ induction x generalizing t with
+ | nil => log_step; exact .nil ..
+ | cons b xs ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ log_step
+ log_step
+ exact ih (b :: t)
+
+private theorem lower_run (x out : List Bool) (nz : Bool) :
+ let extra := (nz || x.any id).toNat
+ StackRuns code (2*x.length+1+extra) (.lower nz) (store [] x out) .done
+ (store [] [] (List.replicate (x.length+extra) true ++ out)) := by
+ induction x generalizing nz out with
+ | nil =>
+ cases nz <;> simp only [List.length_nil, List.any_nil, Bool.or_false, Bool.toNat_false,
+ Bool.toNat_true, Nat.mul_zero, Nat.zero_add, Nat.add_zero, List.replicate_zero, List.nil_append,
+ List.replicate_one, List.singleton_append]
+ · log_step; exact .nil ..
+ · log_step; log_step; exact .nil ..
+ | cons b xs ih =>
+ have h := ih (true :: out) (nz || b)
+ have he : (nz || (b::xs).any id) = ((nz || b) || xs.any id) := by simp [Bool.or_assoc]
+ dsimp only
+ rw [he]
+ simp only [List.length_cons, Nat.mul_succ, Nat.succ_add, List.replicate_succ']
+ rw [List.append_assoc, List.singleton_append]
+ rw [show (2*xs.length+(nz || b || xs.any id).toNat).succ.succ.succ =
+ (2*xs.length+1+(nz || b || xs.any id).toNat)+1+1 by omega]
+ log_step
+ log_step
+ exact h
+
+/-- If the most significant bit is set, the ceiling logarithm counts the
+bits below it and tests whether any of them is set. -/
+theorem clog_leading_one (x : List Bool) :
+ Nat.clog 2 (value ((true :: x).reverse)) = x.length + (x.any id).toNat := by
+ have hx : value x.reverse = 0 ↔ x.any id = false := by
+ induction x with
+ | nil => simp [value]
+ | cons b xs ih =>
+ cases b <;> simp [List.reverse_cons, value_append, value, ih]
+ have hlt : value x.reverse < 2^x.length := by simpa using value_lt x.reverse
+ simp only [List.reverse_cons, value_append, List.length_reverse, value, Nat.mul_zero,
+ Bool.toNat_true, Nat.add_zero, Nat.mul_one]
+ cases h : x.any id with
+ | false => simp [hx.mpr h, Nat.clog_pow 2 _ (by decide)]
+ | true =>
+ have hp : 0 < value x.reverse := Nat.pos_of_ne_zero (fun he => by rw [hx.mp he] at h; contradiction)
+ simp only [Bool.toNat_true]
+ apply le_antisymm
+ · apply Nat.clog_le_of_le_pow
+ rw [pow_succ]
+ omega
+ · apply (Nat.lt_clog_iff_pow_lt (by decide : 1 < 2)).mpr
+ omega
+
+private theorem leading_run (x out : List Bool) :
+ ∃ t ≤ 2*x.length+2, StackRuns code t .leading (store [] x out) .done
+ (store [] [] (List.replicate (Nat.clog 2 (value x.reverse)) true ++ out)) := by
+ induction x with
+ | nil =>
+ refine ⟨1, by decide, ?_⟩
+ simp only [List.reverse_nil, value, Nat.clog_zero_right, List.replicate_zero, List.nil_append]
+ log_step
+ exact .nil ..
+ | cons b xs ih =>
+ cases b with
+ | false =>
+ obtain ⟨t, ht, run⟩ := ih
+ refine ⟨t+1, by simp only [List.length_cons, Nat.mul_succ]; omega, ?_⟩
+ simp only [List.reverse_cons, value_append, value, Bool.toNat_false, Nat.mul_zero,
+ Nat.add_zero]
+ log_step
+ exact run
+ | true =>
+ let k := (xs.any id).toNat
+ have hk : k ≤ 1 := by unfold k; cases xs.any id <;> decide
+ refine ⟨(2*xs.length+1+k)+1, by simp only [List.length_cons, Nat.mul_succ]; omega, ?_⟩
+ rw [clog_leading_one]
+ log_step
+ simpa only [Bool.false_or] using lower_run xs out false
+
+/-- Read every word, including zero and words with high padding, in linear time. -/
+theorem runs (x out : List Bool) :
+ ∃ t ≤ 4*x.length+3, StackRuns code t .reverse (store x [] out) .done
+ (store [] [] (List.replicate (Nat.clog 2 (value x)) true ++ out)) := by
+ obtain ⟨t, ht, run⟩ := leading_run x.reverse out
+ have h := reverse_run x [] out
+ simp only [List.length_reverse, List.reverse_reverse, List.append_nil] at ht run h
+ exact ⟨_, by omega, h.trans run⟩
+
+end RAMTape.WordCeilLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputParametersMultiply.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersMultiply.lean
new file mode 100644
index 0000000000..a274931991
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersMultiply.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.TallyStacks
+import Mathlib.Tactic.Ring
+
+/-!
+# Fixed unary multiplication for the live input parameters
+
+Transfer the left factor to the outer scratch stack. For each of its tally marks,
+restore one mark to the left input and add a copy of the right input to the accumulator.
+The two inputs and both scratch stacks are restored at the normal return.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Tally
+
+open Routine
+
+variable {K : Type*}
+
+/-- Add the product of the two input tallies to `dst`. -/
+def mulAdd (lhs rhs dst outer tmp : K) :=
+ let body := (Routine.push lhs true).followedBy (copyAdd rhs dst tmp)
+ (move lhs outer).followedBy (Routine.popLoop outer (fun _ => true) body body)
+
+variable [DecidableEq K]
+
+/-- Frame for the three stacks that change during the outer loop. -/
+private def mulFrame (s : State K) (lhs dst outer : K) (a d n : ℕ) : State K :=
+ fun i => if i = lhs then a else if i = dst then d else if i = outer then n else s i
+
+theorem mulAdd_runs (lhs rhs dst outer tmp : K) (hd : [lhs, rhs, dst, outer, tmp].Nodup)
+ (s : State K) (ho : s outer = 0) (ht : s tmp = 0) :
+ (mulAdd lhs rhs dst outer tmp).Runs (s lhs * (5 * s rhs + 6) + 2)
+ (encode s) (encode (Function.update s dst (s dst + s lhs * s rhs))) := by
+ simp [List.nodup_cons] at hd
+ obtain ⟨⟨hlr, hld, hlo, hlt⟩, ⟨hrd, hro, hrt⟩, ⟨hdo, hdt⟩, hot⟩ := hd
+ let frame := mulFrame s lhs dst outer
+ have setL (a d n v : ℕ) : Function.update (frame a d n) lhs v = frame v d n := by
+ funext i
+ by_cases h : i = lhs <;> simp [frame, mulFrame, h]
+ have setD (a d n v : ℕ) : Function.update (frame a d n) dst v = frame a v n := by
+ funext i
+ by_cases h : i = dst <;> simp [frame, mulFrame, h, Ne.symm hld]
+ have setO (a d n v : ℕ) : Function.update (frame a d n) outer v = frame a d v := by
+ funext i
+ by_cases h : i = outer <;> simp [frame, mulFrame, h, Ne.symm hlo, Ne.symm hdo]
+ let states (i : ℕ) := frame (s lhs - i) (s dst + (s lhs - i) * s rhs) i
+ let body := (Routine.push lhs true).followedBy (copyAdd rhs dst tmp)
+ have hstates (i : ℕ) (_ : i ≤ s lhs) : states i outer = i := by
+ simp [states, frame, mulFrame, Ne.symm hlo, Ne.symm hdo]
+ have hbody (i : ℕ) (hi : i < s lhs) :
+ body.Runs (1 + (5 * s rhs + 2)) (encode (Function.update (states (i+1)) outer i))
+ (encode (states i)) := by
+ let a := s lhs - (i + 1)
+ let d := s dst + a * s rhs
+ have hpop : Function.update (states (i+1)) outer i = frame a d i := setO _ _ _ _
+ have hsucc : a + 1 = s lhs - i := by dsimp [a]; omega
+ have hpush := increment (frame a d i) lhs
+ have hval : (frame a d i) lhs = a := by simp [frame, mulFrame]
+ rw [hval, setL] at hpush
+ have htmp : (frame (a+1) d i) tmp = 0 := by
+ simp [frame, mulFrame, Ne.symm hlt, Ne.symm hdt, Ne.symm hot, ht]
+ have hcopy := copyAdd_runs rhs dst tmp hrd hrt hdt (frame (a+1) d i) htmp
+ have hright : (frame (a+1) d i) rhs = s rhs := by
+ simp [frame, mulFrame, Ne.symm hlr, hrd, hro]
+ have hdst : (frame (a+1) d i) dst = d := by simp [frame, mulFrame, Ne.symm hld]
+ rw [hright, hdst, setD] at hcopy
+ have hout : frame (a+1) (d + s rhs) i = states i := by
+ unfold states
+ rw [← hsucc, Nat.succ_mul]
+ simp [d, Nat.add_assoc]
+ rw [hpop, ← hout]
+ exact hpush.followedBy hcopy
+ have hloop := drainRuns outer body states (fun _ => 1 + (5 * s rhs + 2)) (s lhs) hstates hbody
+ have hmove := move_runs lhs outer hlo s
+ have hstart : Function.update (Function.update s lhs 0) outer (s outer + s lhs) = states (s lhs) := by
+ funext i
+ by_cases he : i = lhs <;> by_cases he' : i = outer <;>
+ simp_all [states, frame, mulFrame, Ne.symm hdo, Ne.symm hlo]
+ have hend : states 0 = Function.update s dst (s dst + s lhs * s rhs) := by
+ funext i
+ by_cases he : i = dst <;> by_cases he' : i = lhs <;> by_cases he'' : i = outer <;>
+ simp_all [states, frame, mulFrame, Ne.symm hdo, Ne.symm hlo, Ne.symm hld]
+ rw [hstart] at hmove
+ rw [hend] at hloop
+ have h := hmove.followedBy hloop
+ convert! h using 1
+ simp
+ ring
+
+end RAMTape.Tally
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputParametersPower.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersPower.lean
new file mode 100644
index 0000000000..c4a338f9ec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersPower.lean
@@ -0,0 +1,192 @@
+import OAI.Computability.VPVNP.RAMTapeWordMul
+import OAI.Computability.VPVNP.RAMTapeStackLift
+
+/-!
+# Binary powers for the live bucket exponent
+
+The fixed numerator of the rational exponent is a finite loop bound.
+Each iteration copies the base, calls the word multiplier, and restores
+the product to its input port for the next call. The word width is supplied
+by the stacks and is independent of the number of control states.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputPower
+
+open TapeWord BurstRAM
+
+/-- Ports for the power routine’s base, temporary reversal, and multiplication registers. -/
+inductive Port
+ | base | tmp | mul (r : Mul.Reg)
+ deriving DecidableEq, Fintype
+
+/-- Phases of one power round, from copying the base through multiplication to moving the
+product into the next accumulator. -/
+inductive Round
+ | test | copy | save (b : Bool) | restore | baseBit (b : Bool) | factorBit (b : Bool)
+ | mul (s : Mul.State) | reverseProduct | saveProduct (b : Bool)
+ | restoreProduct | putProduct (b : Bool)
+ deriving DecidableEq, Fintype
+
+/-- Power control carrying a bounded number of remaining rounds and the current multiplication
+phase. -/
+inductive State (p : ℕ)
+ | round (i : Fin (p+1)) (s : Round)
+ | done
+ deriving DecidableEq, Fintype
+
+/-- Repeat multiplication by a restored copy of the base and transfer each product to the
+accumulator for the next round. -/
+def code (p : ℕ) : StackCode Port (State p)
+ | .done => .halt true
+ | .round i s => match s with
+ | .test => if i.val = 0 then .goto .done else .goto (.round i .copy)
+ | .copy => .pop .base fun b => .round i (b.elim .restore .save)
+ | .save b => .push .tmp b (.round i .copy)
+ | .restore => .pop .tmp fun b => .round i (b.elim (.mul .init) .baseBit)
+ | .baseBit b => .push .base b (.round i (.factorBit b))
+ | .factorBit b => .push (.mul .multiplicand) b (.round i .restore)
+ | .mul .done => .goto (.round i .reverseProduct)
+ | .mul s => (Mul.code s).rename Port.mul (fun q => .round i (.mul q))
+ | .reverseProduct => .pop (.mul .accumulator) fun b => .round i (b.elim .restoreProduct .saveProduct)
+ | .saveProduct b => .push .tmp b (.round i .reverseProduct)
+ | .restoreProduct => .pop .tmp fun b => b.elim
+ (.round ⟨i.val - 1, by omega⟩ .test) (fun v => .round i (.putProduct v))
+ | .putProduct b => .push (.mul .multiplier) b (.round i .restoreProduct)
+
+/-- Initialize the base and temporary stack together with the accumulator, factor, and product
+of the embedded multiplier. -/
+def store (base tmp acc factor product : List Bool) : Stacks Port
+ | .base => base
+ | .tmp => tmp
+ | .mul r => Mul.store acc factor product [] [] r
+
+private theorem set_store (base tmp a f v l : List Bool) (k : Port) :
+ Function.update (store base tmp a f v) k l = match k with
+ | .base => store l tmp a f v
+ | .tmp => store base l a f v
+ | .mul .multiplier => store base tmp l f v
+ | .mul .multiplicand => store base tmp a l v
+ | .mul .accumulator => store base tmp a f l
+ | .mul _ => Function.update (store base tmp a f v) k l := by
+ cases k with
+ | base | tmp => funext j; cases j <;> simp [store]
+ | mul r =>
+ cases r <;> first | rfl | (funext j; cases j with
+ | base | tmp => simp [store]
+ | mul u => cases u <;> simp [store, Mul.store])
+
+local macro "power_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, Mul.store, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, set_store])
+
+variable {p : ℕ} (i : Fin (p+1))
+
+private theorem copy_run (x t a : List Bool) :
+ StackRuns (code p) (2 * x.length + 1) (.round i .copy) (store x t a [] [])
+ (.round i .restore) (store [] (x.reverse ++ t) a [] []) := by
+ induction x generalizing t with
+ | nil => power_step; exact .nil ..
+ | cons b x ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ power_step
+ power_step
+ exact ih (b :: t)
+
+private theorem restore_run (x t a f : List Bool) :
+ StackRuns (code p) (3 * t.length + 1) (.round i .restore) (store x t a f [])
+ (.round i (.mul .init)) (store (t.reverse ++ x) [] a (t.reverse ++ f) []) := by
+ induction t generalizing x f with
+ | nil => power_step; exact .nil ..
+ | cons b t ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ power_step
+ power_step
+ power_step
+ exact ih (b :: x) (b :: f)
+
+private theorem reverse_run (x t a : List Bool) :
+ StackRuns (code p) (2 * a.length + 1) (.round i .reverseProduct) (store x t [] [] a)
+ (.round i .restoreProduct) (store x (a.reverse ++ t) [] [] []) := by
+ induction a generalizing t with
+ | nil => power_step; exact .nil ..
+ | cons b a ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ power_step
+ power_step
+ exact ih (b :: t)
+
+private theorem put_run (x t a : List Bool) :
+ StackRuns (code p) (2 * t.length + 1) (.round i .restoreProduct) (store x t a [] [])
+ (.round ⟨i.val - 1, by omega⟩ .test) (store x [] (t.reverse ++ a) [] []) := by
+ induction t generalizing a with
+ | nil => power_step; exact .nil ..
+ | cons b t ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ power_step
+ power_step
+ exact ih (b :: a)
+
+private theorem mul_run {w : ℕ} (x a : Word w) :
+ StackRuns (code p) (8*w^2+9*w+4) (.round i (.mul .init))
+ (store (wordBits x) [] (wordBits a) (wordBits x) []) (.round i (.mul .done))
+ (store (wordBits x) [] [] [] (wordBits (x*a))) := by
+ have hinj : Function.Injective Port.mul := fun _ _ h => Port.mul.inj h
+ let base := store (wordBits x) [] [] [] []
+ have h := (Mul.multiply_word_run x a).lift Port.mul hinj (fun s => State.round i (.mul s)) base
+ (target := code p) (by intro q h; cases q <;> first | rfl | simp [Mul.code] at h)
+ have hstore (u v t : List Bool) :
+ installStacks Port.mul base (Mul.store u v t [] []) = store (wordBits x) [] u v t := by
+ funext k
+ cases k with
+ | mul r => rw [installStacks_at hinj]; rfl
+ | base | tmp => rw [installStacks_outside _ _ (by intro r; simp)]; rfl
+ have he : PrivateRAM.BinaryOp.mul.eval x a = x * a := by apply Fin.ext; rfl
+ simpa only [hstore, he] using h
+
+/-- One round costs a quadratic number of bit operations and leaves the base available. -/
+theorem round_run {w : ℕ} (x a : Word w) (hi : i.val ≠ 0) :
+ StackRuns (code p) (8*w^2+18*w+10) (.round i .test) (store (wordBits x) [] (wordBits a) [] [])
+ (.round ⟨i.val-1, by omega⟩ .test) (store (wordBits x) [] (wordBits (x*a)) [] []) := by
+ have h₁ := copy_run i (wordBits x) [] (wordBits a)
+ have h₂ := restore_run i [] (wordBits x).reverse (wordBits a) []
+ have h₃ := mul_run i x a
+ have h₄ := reverse_run i (wordBits x) [] (wordBits (x*a))
+ have h₅ := put_run i (wordBits x) (wordBits (x*a)).reverse []
+ simp only [List.append_nil, List.reverse_reverse, List.length_reverse, length_wordBits] at h₁ h₂ h₄ h₅
+ have ht := (h₁.trans h₂).trans (h₃.trans
+ (StackRuns.cons (StackStep.goto (show code p (.round i (.mul .done)) = _ from rfl)) (h₄.trans h₅)))
+ convert StackRuns.cons (StackStep.goto (show code p (.round i .test) =
+ .goto (.round i .copy) by simp [code, hi])) ht using 1
+ ring
+
+/-- The full fixed power loop works at every bit width, including zero width. -/
+theorem power_run {w : ℕ} (x a : Word w) :
+ StackRuns (code p) (i.val * (8*w^2+18*w+10) + 1) (.round i .test)
+ (store (wordBits x) [] (wordBits a) [] []) .done
+ (store (wordBits x) [] (wordBits (Fin.ofNat (2^w) (x.val^i.val*a.val))) [] []) := by
+ obtain ⟨k, hk⟩ := i
+ induction k generalizing a with
+ | zero =>
+ have he : Fin.ofNat (2^w) (x.val^0*a.val) = a := by apply Fin.ext; simp [Fin.ofNat, Nat.mod_eq_of_lt a.isLt]
+ simpa only [he, Nat.zero_mul, Nat.zero_add] using StackRuns.cons (StackStep.goto (show code p (.round ⟨0,hk⟩ .test) =
+ .goto .done by simp [code])) (StackRuns.nil (code := code p) .done (store (wordBits x) [] (wordBits a) [] []))
+ | succ k ih =>
+ have h := (round_run (⟨k+1,hk⟩ : Fin (p+1)) x a (by simp)).trans (ih (x*a) (by omega))
+ convert h using 1
+ · change (k+1)*_+1 = _ + (k*_+1)
+ ring
+ · congr 2
+ apply Fin.ext
+ change (x.val ^ (k+1) * a.val) % _ = (x.val ^ k * ((x.val * a.val) % (2^w))) % _
+ rw [Nat.mul_mod_mod, pow_succ, Nat.mul_assoc]
+
+end RAMTape.InputPower
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputParametersTriangle.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersTriangle.lean
new file mode 100644
index 0000000000..ab71d17818
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersTriangle.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.TallyStacks
+import Mathlib.Data.Nat.Choose.Basic
+import Mathlib.Tactic.Linarith
+
+/-!
+# Computing the triangular sorting-layer count on unary stacks
+
+The outer counter starts at the source value. After each pop, its remaining
+value is copied to the destination and one additional mark is pushed. This
+adds the successive integers from the source value down to one.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Tally
+
+open Function Routine
+
+variable {K : Type*} [DecidableEq K]
+
+private def triangleBody (counter dst tmp : K) :=
+ (copyAdd counter dst tmp).followedBy (push dst true)
+
+private def triangleLoop (counter dst tmp : K) :=
+ popLoop counter (fun _ => true) (halt false) (triangleBody counter dst tmp)
+
+/-- Add the number of unordered pairs from `d+1` elements to the destination,
+where `d` is the number of unary marks on the source stack. -/
+def triangleAdd (src dst counter tmp : K) :=
+ (copyAdd src counter tmp).followedBy (triangleLoop counter dst tmp)
+
+private theorem triangleBody_runs (counter dst tmp : K) (hcd : counter ≠ dst)
+ (hct : counter ≠ tmp) (hdt : dst ≠ tmp) (s : State K) (ht : s tmp = 0) :
+ (triangleBody counter dst tmp).Runs (5 * s counter + 3) (encode s)
+ (encode (update s dst (s dst + s counter + 1))) := by
+ have hc := copyAdd_runs counter dst tmp hcd hct hdt s ht
+ have hp := increment (update s dst (s dst + s counter)) dst
+ simpa [triangleBody] using hc.followedBy hp
+
+private theorem choose_succ_two (d : ℕ) : (d + 1).choose 2 = d + d.choose 2 := by
+ rw [Nat.choose_succ_succ d 1, Nat.choose_one_right]
+
+private theorem triangleLoop_runs (counter dst tmp : K) (hcd : counter ≠ dst)
+ (hct : counter ≠ tmp) (hdt : dst ≠ tmp) (d : ℕ) (s : State K)
+ (hd : s counter = d) (ht : s tmp = 0) :
+ (triangleLoop counter dst tmp).Runs (1 + 4 * d + 5 * d.choose 2) (encode s)
+ (encode (update (update s counter 0) dst (s dst + (d+1).choose 2))) := by
+ induction d generalizing s with
+ | zero =>
+ have he := Runs.popLoop_empty counter (fun _ => true) (halt false) (triangleBody counter dst tmp)
+ (s := encode s) (by simp [encode, hd])
+ have hreset : update s counter 0 = s := hd ▸ update_eq_self counter s
+ simpa [triangleLoop, hreset, update_eq_self] using he
+ | succ d ih =>
+ let popped := update s counter d
+ let mid := update popped dst (s dst + d + 1)
+ have hp : popped counter = d := update_self ..
+ have hp' : popped dst = s dst := update_of_ne hcd.symm _ _
+ have htmp : popped tmp = 0 := (update_of_ne hct.symm _ _).trans ht
+ have hmid : mid counter = d := (update_of_ne hcd _ _).trans hp
+ have hmidt : mid tmp = 0 := (update_of_ne hdt.symm _ _).trans htmp
+ have hpop : update (encode s) counter (List.replicate d true) = encode popped :=
+ encode_update s counter d
+ have hb : (triangleBody counter dst tmp).Runs (5 * d + 3)
+ (update (encode s) counter (List.replicate d true)) (encode mid) := by
+ rw [hpop]
+ simpa only [hp, hp', mid] using triangleBody_runs counter dst tmp hcd hct hdt popped htmp
+ have hr := Runs.popLoop_true_continue counter (fun _ => true) (halt false)
+ (triangleBody counter dst tmp) (by simp [encode, hd, List.replicate_succ]) rfl hb
+ (ih mid hmid hmidt)
+ have hstate : update (update mid counter 0) dst (mid dst + (d + 1).choose 2) =
+ update (update s counter 0) dst (s dst + (d + 1 + 1).choose 2) := by
+ funext i
+ by_cases he : i = dst
+ · subst i
+ simp only [update_self, mid, choose_succ_two]
+ omega
+ · by_cases hc : i = counter
+ · subst i; simp [update_of_ne hcd]
+ · simp [mid, popped, update_of_ne hc, update_of_ne he]
+ rw [hstate] at hr
+ have hcost : 1 + (5 * d + 3) + (1 + 4 * d + 5 * d.choose 2) =
+ 1 + 4 * (d + 1) + 5 * (d + 1).choose 2 := by rw [choose_succ_two d]; omega
+ simpa only [triangleLoop, hcost] using hr
+
+/-- Exact deterministic tick count. The output updates only the destination. -/
+theorem triangleAdd_runs (src dst counter tmp : K)
+ (hsc : src ≠ counter) (hst : src ≠ tmp) (hdc : dst ≠ counter) (hdt : dst ≠ tmp)
+ (hct : counter ≠ tmp) (s : State K) (hc : s counter = 0) (ht : s tmp = 0) :
+ (triangleAdd src dst counter tmp).Runs (3 + 9 * s src + 5 * (s src).choose 2) (encode s)
+ (encode (update s dst (s dst + (s src + 1).choose 2))) := by
+ let copied := update s counter (s counter + s src)
+ have ha := copyAdd_runs src counter tmp hsc hst hct s ht
+ have hc' : copied counter = s src := by simp [copied, hc]
+ have ht' : copied tmp = 0 := (update_of_ne hct.symm _ _).trans ht
+ have hreset : update copied counter 0 = s := by
+ rw [show copied = _ from rfl, update_idem, ← hc, update_eq_self]
+ have hd' : copied dst = s dst := update_of_ne hdc _ _
+ have hb := triangleLoop_runs counter dst tmp hdc.symm hct hdt (s src) copied hc' ht'
+ rw [hreset, hd'] at hb
+ have hcost : 5 * s src + 2 + (1 + 4 * s src + 5 * (s src).choose 2) =
+ 3 + 9 * s src + 5 * (s src).choose 2 := by omega
+ simpa only [triangleAdd, hcost] using ha.followedBy hb
+
+/-- A quadratic bound for the fixed routine, valid also on a zero source. -/
+theorem triangleAdd_cost_le (d : ℕ) : 3 + 9 * d + 5 * d.choose 2 ≤ 20 * (d + 1) ^ 2 := by
+ have h : d.choose 2 ≤ d * d := by
+ rw [Nat.choose_two_right]
+ exact (Nat.div_le_self ..).trans (Nat.mul_le_mul_left _ (Nat.sub_le ..))
+ nlinarith
+
+end RAMTape.Tally
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputParametersWidth.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersWidth.lean
new file mode 100644
index 0000000000..7676a0412a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersWidth.lean
@@ -0,0 +1,139 @@
+import OAI.Computability.VPVNP.TallyConstants
+import OAI.Computability.VPVNP.RAMLayout
+import Mathlib.Tactic.DeriveFintype
+
+/-! # Computing the incident-vector width on the validator's actual stacks
+
+The address and bucket registers contain `d` and `H` in unary. The fixed program
+forms `w = (d+10)^4`, counts the sorting layers, and writes the entire incident
+width of equation (10.1). It returns both input registers and clears its scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputWidth
+
+open Tally
+
+/-- Unary counters for the address, bucket, incident width, and intermediate arithmetic in the
+layout-width calculation. -/
+inductive Port where
+ | address | bucket | incident | base | duplicate | square | word | layers
+ | blocks | payload | factor | outer | tmp
+ deriving DecidableEq
+
+noncomputable instance : Fintype Port := derive_fintype% Port
+
+/-- Start width computation with address width and bucket size on their counters and zero
+elsewhere. -/
+def initial (d H : ℕ) : State Port
+ | .address => d
+ | .bucket => H
+ | _ => 0
+
+/-- Final width state containing the original address and bucket tallies and the complete
+incident-vector width. -/
+def result (d H : ℕ) : State Port :=
+ Function.update (initial d H) .incident (RAMLayout.width d H ((d+10)^4))
+
+/-- Two squarings of `d+10`. Each multiply reads disjoint input stacks. -/
+def wordProgram : Program Port :=
+ (Program.copy .address .base .tmp (by decide) (by decide) (by decide)).seq <|
+ (Program.addConst .base 10).seq <|
+ (Program.copy .base .duplicate .tmp (by decide) (by decide) (by decide)).seq <|
+ (Program.mul .base .duplicate .square .outer .tmp (by decide)).seq <|
+ (Program.clear .duplicate).seq <|
+ (Program.copy .square .duplicate .tmp (by decide) (by decide) (by decide)).seq <|
+ (Program.mul .square .duplicate .word .outer .tmp (by decide)).seq <|
+ Program.clear .duplicate
+
+/-- Intermediate tallies for the address width plus ten, its square, and its fourth power,
+which gives the word width. -/
+def words (d H : ℕ) : State Port
+ | .base => d+10
+ | .square => (d+10)^2
+ | .word => (d+10)^4
+ | p => initial d H p
+
+/-- Count `(d+1).choose 2` sorting layers and multiply by bucket and word widths. -/
+def payloadProgram : Program Port :=
+ (Program.triangle .address .layers .outer .tmp (by decide) (by decide) (by decide)
+ (by decide) (by decide)).seq <|
+ (Program.mul .bucket .layers .blocks .outer .tmp (by decide)).seq <|
+ Program.mul .word .blocks .payload .outer .tmp (by decide)
+
+/-- Intermediate counts for sorting layers, bucket slots across those layers, and their
+word-width product. -/
+def payloads (d H : ℕ) : State Port
+ | .layers => (d+1).choose 2
+ | .blocks => H*(d+1).choose 2
+ | .payload => (d+10)^4*(H*(d+1).choose 2)
+ | p => words d H p
+
+/-- Add the successor-field width and the sorting-field width into the output register. -/
+def countProgram : Program Port :=
+ (Program.addConst .factor 16).seq <|
+ (Program.mul .factor .word .incident .outer .tmp (by decide)).seq <|
+ (Program.clear .factor).seq <|
+ (Program.addConst .factor 40).seq <|
+ (Program.mul .factor .payload .incident .outer .tmp (by decide)).seq <|
+ Program.clear .factor
+
+/-- State after writing the full incident width while the intermediate geometry tallies are
+still present. -/
+def counted (d H : ℕ) : State Port :=
+ Function.update (payloads d H) .incident (RAMLayout.width d H ((d+10)^4))
+
+/-- Erase the base, square, word, layers, blocks, and payload counters after storing the
+incident width. -/
+def cleanup : Program Port :=
+ (Program.clear .base).seq <| (Program.clear .square).seq <| (Program.clear .word).seq <|
+ (Program.clear .layers).seq <| (Program.clear .blocks).seq <| Program.clear .payload
+
+/-- A single fixed finite control, independent of `d` and `H`. -/
+def program : Program Port := wordProgram.seq (payloadProgram.seq (countProgram.seq cleanup))
+
+private theorem eval_wordProgram (d H : ℕ) : wordProgram.eval (initial d H) = words d H := by
+ funext p
+ cases p <;> simp (config := { decide := true }) [wordProgram, initial, words] <;> ring
+
+private theorem eval_payloadProgram (d H : ℕ) : payloadProgram.eval (words d H) = payloads d H := by
+ funext p
+ cases p <;> simp (config := { decide := true }) [payloadProgram, words, initial, payloads]
+
+private theorem eval_countProgram (d H : ℕ) : countProgram.eval (payloads d H) = counted d H := by
+ funext p
+ cases p <;> simp (config := { decide := true }) [countProgram, counted, payloads, words, initial,
+ RAMLayout.width_eq]
+ ring
+
+private theorem eval_cleanup (d H : ℕ) : cleanup.eval (counted d H) = result d H := by
+ funext p
+ cases p <;> simp (config := { decide := true }) [cleanup, result, counted, payloads, words, initial]
+
+theorem eval_program (d H : ℕ) : program.eval (initial d H) = result d H := by
+ change cleanup.eval (countProgram.eval (payloadProgram.eval (wordProgram.eval (initial d H)))) = _
+ rw [eval_wordProgram, eval_payloadProgram, eval_countProgram, eval_cleanup]
+
+theorem ready_program (d H : ℕ) : program.ready (initial d H) := by
+ simp only [program, Program.seq_ready, eval_wordProgram, eval_payloadProgram, eval_countProgram]
+ simp (config := { decide := true }) [wordProgram, payloadProgram, countProgram, cleanup,
+ initial, words, payloads]
+
+/-- The subroutines' exact instruction counts add across the four stages. -/
+theorem work_program (d H : ℕ) : program.work (initial d H) =
+ wordProgram.work (initial d H) + (payloadProgram.work (words d H) +
+ (countProgram.work (payloads d H) + cleanup.work (counted d H))) := by
+ simp only [program, Program.seq_work, eval_wordProgram, eval_payloadProgram, eval_countProgram]
+
+theorem runs (d H : ℕ) : program.code.Runs (program.work (initial d H))
+ (encode (initial d H)) (encode (result d H)) :=
+ eval_program d H ▸ program.spec (initial d H) (ready_program d H)
+
+end RAMTape.InputWidth
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputParametersWidthCost.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersWidthCost.lean
new file mode 100644
index 0000000000..119c49fc90
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputParametersWidthCost.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.RAMTapeInputParametersWidth
+
+/-!
+# Cost of computing the incident width
+
+The exact instruction count includes every copy, multiplication and scratch clear. The
+largest term is proportional to the payload `(d+10)^4 * H * (d+1).choose 2`, which gives
+a degree-seven bound in the combined address and bucket sizes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputWidth
+
+open Tally
+
+/-- Total instruction count of the four stages, grouped by the intermediate register values. -/
+theorem work_eq (d H : ℕ) :
+ program.work (initial d H) =
+ 548 + 14*d + 15*(d+10) + 20*(d+10)^2 + 93*(d+10)^4 + 5*d.choose 2 +
+ 7*(H*(d+1).choose 2) + 6*H + 207*((d+10)^4*(H*(d+1).choose 2)) + 2*(d+1).choose 2 := by
+ rw [work_program]
+ simp (config := { decide := true }) [wordProgram, payloadProgram, countProgram, cleanup,
+ words, initial, payloads, counted]
+ ring
+
+private theorem choose_two_le_square (n : ℕ) : n.choose 2 ≤ n^2 := by
+ rw [Nat.choose_two_right, pow_two]
+ exact (Nat.div_le_self _ _).trans (Nat.mul_le_mul_left _ (Nat.sub_le ..))
+
+theorem work_le_seventh (d H : ℕ) : program.work (initial d H) ≤ 917*(d+H+11)^7 := by
+ let B := d + H + 11
+ have hB : 0 < B := by dsimp [B]; omega
+ have mono {i j : ℕ} (h : i ≤ j) : B^i ≤ B^j := Nat.pow_le_pow_right hB h
+ have ht : d + 10 ≤ B := by dsimp [B]; omega
+ have hh : H ≤ B := by dsimp [B]; omega
+ have hs : (d+10)^2 ≤ B^2 := Nat.pow_le_pow_left ht _
+ have hw : (d+10)^4 ≤ B^4 := Nat.pow_le_pow_left ht _
+ have hL : (d+1).choose 2 ≤ B^2 :=
+ (choose_two_le_square _).trans (Nat.pow_le_pow_left (by omega) _)
+ have hJ : d.choose 2 ≤ B^2 :=
+ (choose_two_le_square _).trans (Nat.pow_le_pow_left (by omega) _)
+ have hblocks : H * (d+1).choose 2 ≤ B^3 := by
+ calc
+ _ ≤ B * B^2 := Nat.mul_le_mul hh hL
+ _ = B^3 := by ring
+ have hpayload : (d+10)^4 * (H*(d+1).choose 2) ≤ B^7 := by
+ calc
+ _ ≤ B^4 * B^3 := Nat.mul_le_mul hw hblocks
+ _ = B^7 := by ring
+ have h1 : 1 ≤ B^7 := (by simpa using mono (by decide : 0 ≤ 7))
+ have h2 : B ≤ B^7 := by simpa using mono (by decide : 1 ≤ 7)
+ have h3 := mono (by decide : 2 ≤ 7)
+ have h4 := mono (by decide : 3 ≤ 7)
+ have h5 := mono (by decide : 4 ≤ 7)
+ rw [work_eq]
+ change _ ≤ 917 * B^7
+ omega
+
+/-- Bound used by the fixed live-validator clock. -/
+theorem work_le (d H : ℕ) : program.work (initial d H) ≤ 10^12 * (d+H+11)^12 :=
+ (work_le_seventh d H).trans (Nat.mul_le_mul (by decide)
+ (Nat.pow_le_pow_right (by omega) (by decide)))
+
+end RAMTape.InputWidth
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputPorts.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputPorts.lean
new file mode 100644
index 0000000000..c92bbfa5b1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputPorts.lean
@@ -0,0 +1,25 @@
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Data.Fintype.Sum
+import Mathlib.Tactic.DeriveFintype
+
+/-! # Stack registers of the length-independent physical input reader -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+/-- Input, working counters, and the four extracted data fields. Each stack
+contains individual bits in head-first order. -/
+inductive InputPort where
+ | input | tmp | count | prefix | address | header | incident | addressCount | incidentCount | size
+ deriving DecidableEq
+
+instance : Fintype InputPort := derive_fintype% _
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputPrefix.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputPrefix.lean
new file mode 100644
index 0000000000..476d1155bb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputPrefix.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.RAMTapeInputPorts
+import OAI.Computability.VPVNP.UniversalMachine
+
+/-!
+# Extracting the literal self-delimiting table prefix
+
+A fixed stack control reads one unary length digit at a time. Each digit
+supplies one counter marker, authorizing one payload bit after the zero
+delimiter. It copies the entire field, including those length digits and
+the delimiter, into the prefix stack in its original order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+/-- Control for reading the unary prefix length, zero delimiter, and the indicated payload
+bits, then restoring the whole prefix in order. -/
+inductive PrefixPhase
+ | entry | saveDigit | countDigit | delimiter | nextBit | readBit | saveBit (bit : Bool)
+ | restore | put (bit : Bool) | done | reject
+ deriving DecidableEq, Fintype
+
+/-- Length-independent stack instructions for the first field. A missing
+delimiter or a truncated table sends control to rejection. -/
+def prefixCode : StackCode InputPort PrefixPhase
+ | .entry => .pop .input fun b => b.elim .reject fun digit => if digit then .saveDigit else .delimiter
+ | .saveDigit => .push .tmp true .countDigit
+ | .countDigit => .push .count true .entry
+ | .delimiter => .push .tmp false .nextBit
+ | .nextBit => .pop .count fun marker => marker.elim .restore fun _ => .readBit
+ | .readBit => .pop .input fun b => b.elim .reject .saveBit
+ | .saveBit bit => .push .tmp bit .nextBit
+ | .restore => .pop .tmp fun b => b.elim .done .put
+ | .put bit => .push .prefix bit .restore
+ | .done => .halt true
+ | .reject => .halt false
+
+private def workStacks (base : Stacks InputPort) (bits tmp count result : List Bool) : Stacks InputPort
+ | .input => bits
+ | .tmp => tmp
+ | .count => count
+ | .prefix => result
+ | k => base k
+
+private theorem update_input (base : Stacks InputPort) (bits tmp count result new : List Bool) :
+ Function.update (workStacks base bits tmp count result) .input new =
+ workStacks base new tmp count result := by
+ funext i
+ cases i <;> simp [workStacks]
+
+private theorem update_tmp (base : Stacks InputPort) (bits tmp count result new : List Bool) :
+ Function.update (workStacks base bits tmp count result) .tmp new =
+ workStacks base bits new count result := by
+ funext i
+ cases i <;> simp [workStacks]
+
+private theorem update_count (base : Stacks InputPort) (bits tmp count result new : List Bool) :
+ Function.update (workStacks base bits tmp count result) .count new =
+ workStacks base bits tmp new result := by
+ funext i
+ cases i <;> simp [workStacks]
+
+private theorem update_result (base : Stacks InputPort) (bits tmp count result new : List Bool) :
+ Function.update (workStacks base bits tmp count result) .prefix new =
+ workStacks base bits tmp count new := by
+ funext i
+ cases i <;> simp [workStacks]
+
+local macro "prefix_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [workStacks, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, ↓reduceIte, Bool.false_eq_true,
+ update_input, update_tmp, update_count, update_result])
+
+private theorem digits_runs (base : Stacks InputPort) (n : ℕ) (rest tmp count result : List Bool) :
+ StackRuns prefixCode (3*n+2) .entry
+ (workStacks base (List.replicate n true ++ false :: rest) tmp count result)
+ .nextBit (workStacks base rest (false :: (List.replicate n true ++ tmp))
+ (List.replicate n true ++ count) result) := by
+ induction n generalizing tmp count with
+ | zero =>
+ simp only [List.replicate_zero, List.nil_append, Nat.mul_zero, Nat.zero_add]
+ prefix_step
+ prefix_step
+ exact .nil ..
+ | succ n ih =>
+ rw [show 3*(n+1)+2 = (3*n+2)+1+1+1 by omega]
+ rw [List.replicate_succ, List.cons_append]
+ prefix_step
+ prefix_step
+ prefix_step
+ have hrep : true :: List.replicate n true = List.replicate n true ++ [true] := by
+ rw [← List.replicate_succ, List.replicate_succ']
+ simpa only [hrep, List.append_assoc, List.singleton_append] using ih (true :: tmp) (true :: count)
+
+private theorem payload_runs (base : Stacks InputPort) (t rest tmp result : List Bool) :
+ StackRuns prefixCode (3*t.length+1) .nextBit
+ (workStacks base (t ++ rest) tmp (List.replicate t.length true) result)
+ .restore (workStacks base rest (t.reverse ++ tmp) [] result) := by
+ induction t generalizing tmp with
+ | nil =>
+ simp only [List.length_nil, List.reverse_nil, List.nil_append, List.replicate_zero, Nat.mul_zero,
+ Nat.zero_add]
+ prefix_step
+ exact .nil ..
+ | cons b t ih =>
+ simp only [List.length_cons, List.cons_append, List.replicate_succ, List.reverse_cons,
+ List.append_assoc]
+ rw [show 3*(t.length+1)+1 = (3*t.length+1)+1+1+1 by omega]
+ prefix_step
+ prefix_step
+ prefix_step
+ exact ih (b :: tmp)
+
+private theorem restore_runs (base : Stacks InputPort) (rest tmp result : List Bool) :
+ StackRuns prefixCode (2*tmp.length+1) .restore (workStacks base rest tmp [] result)
+ .done (workStacks base rest [] [] (tmp.reverse ++ result)) := by
+ induction tmp generalizing result with
+ | nil =>
+ simp only [List.length_nil, List.reverse_nil, List.nil_append, Nat.mul_zero, Nat.zero_add]
+ prefix_step
+ exact .nil ..
+ | cons b tmp ih =>
+ simp only [List.length_cons, List.reverse_cons, List.append_assoc, List.singleton_append]
+ rw [show 2*(tmp.length+1)+1 = (2*tmp.length+1)+1+1 by omega]
+ prefix_step
+ prefix_step
+ exact ih (b :: result)
+
+/-- The machine consumes precisely the self-delimiting table prefix. It leaves
+the suffix at the input head, restores both scratch stacks and preserves the
+values of every other port. The run length depends only on the table length. -/
+theorem prefix_runs (s : Stacks InputPort) (t suffix : List Bool)
+ (hin : s .input = (UniversalMachine.unary t.length ++ t) ++ suffix)
+ (ht : s .tmp = []) (hc : s .count = []) (hp : s .prefix = []) :
+ StackRuns prefixCode (10*t.length+6) .entry s .done
+ (Function.update (Function.update s .input suffix) .prefix (UniversalMachine.unary t.length ++ t)) := by
+ let digits := List.replicate t.length true
+ have h₁ := digits_runs s t.length (t ++ suffix) [] [] []
+ have h₂ := payload_runs s t suffix (false :: digits) []
+ have h₃ := restore_runs s suffix (t.reverse ++ false :: digits) []
+ simp only [List.append_nil] at h₁ h₃
+ have h := (h₁.trans h₂).trans h₃
+ have hs : workStacks s (digits ++ false :: (t ++ suffix)) [] [] [] = s := by
+ funext i
+ cases i <;> simp [workStacks, hin, ht, hc, hp, UniversalMachine.unary, digits, List.append_assoc]
+ have he : workStacks s suffix [] [] (t.reverse ++ false :: digits).reverse =
+ Function.update (Function.update s .input suffix) .prefix (UniversalMachine.unary t.length ++ t) := by
+ funext i
+ cases i <;> simp [workStacks, ht, hc, UniversalMachine.unary, digits]
+ rw [hs, he] at h
+ convert h using 1
+ simp [digits]
+ omega
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputRoutines.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputRoutines.lean
new file mode 100644
index 0000000000..df6c27dc52
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputRoutines.lean
@@ -0,0 +1,34 @@
+import OAI.Computability.VPVNP.RAMTapeInputLength
+import OAI.Computability.VPVNP.RAMTapeInputPrefix
+import OAI.Computability.VPVNP.StructuredStackCall
+
+/-! # Callable length and prefix passes of the physical input reader -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputReader
+
+/-- Callable length-measuring pass from scan entry to its successful return. -/
+def lengthRoutine := Routine.ofCode lengthCode .scan .done
+/-- Callable self-delimiting prefix reader from entry to its successful return. -/
+def prefixRoutine := Routine.ofCode prefixCode .entry .done
+
+theorem lengthRoutine_runs (s : Stacks InputPort) (ht : s .tmp = []) :
+ lengthRoutine.Runs (5*(s .input).length+2) s
+ (Function.update s .size (List.replicate (s .input).length true ++ s .size)) :=
+ Routine.runs_ofCode (by decide) rfl (length_runs s ht)
+
+theorem prefixRoutine_runs (s : Stacks InputPort) (t suffix : List Bool)
+ (hin : s .input = (UniversalMachine.unary t.length ++ t) ++ suffix)
+ (ht : s .tmp = []) (hc : s .count = []) (hp : s .prefix = []) :
+ prefixRoutine.Runs (10*t.length+6) s
+ (Function.update (Function.update s .input suffix) .prefix (UniversalMachine.unary t.length ++ t)) :=
+ Routine.runs_ofCode (by decide) rfl (prefix_runs s t suffix hin ht hc hp)
+
+end RAMTape.InputReader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeInputStartup.lean b/lean/OAI/Computability/VPVNP/RAMTapeInputStartup.lean
new file mode 100644
index 0000000000..616236b9b0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeInputStartup.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.RAMTapeInput
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMTapeNamed
+
+/-!
+# Sequencing input measurement, public parameters and field parsing
+
+The raw input starts on one stack and all remaining stacks start empty. The
+fixed length pass restores the input, the parameter pass computes the two
+field widths, and the fixed parsing pass extracts the four data stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputReader
+
+open BurstRAM ProcessorInput RAMLayout UniversalMachine StackCompiler
+
+variable {K : Type} [DecidableEq K]
+
+/-- The input registers together with the parameter routine's scratch bank. -/
+def withScratch (s : Stacks InputPort) : Stacks (InputPort ⊕ K) := Sum.elim s (fun _ => [])
+
+/-- The complete physical tape has been measured and restored. -/
+def measured (raw : List Bool) (n : ℕ) : Stacks (InputPort ⊕ K) :=
+ withScratch (prepared raw 0 0 (List.replicate n true))
+
+/-- Measure and restore the raw input, prepare its field widths with the supplied routine, and
+parse the site fields. -/
+def startup (parameters : FiniteRoutine (InputPort ⊕ K)) :=
+ (((FiniteRoutine.ofRoutine lengthRoutine).onPorts Sum.inl).followedBy parameters).followedBy
+ ((FiniteRoutine.ofRoutine parse).onPorts Sum.inl)
+
+omit [DecidableEq K] in
+private theorem length_start (raw : List Bool) :
+ lengthRoutine.Runs (5*raw.length+2) (prepared raw 0 0 [])
+ (prepared raw 0 0 (List.replicate raw.length true)) := by
+ have h := lengthRoutine_runs (prepared raw 0 0 []) rfl
+ change lengthRoutine.Runs (5*raw.length+2) _ (Function.update _ .size (List.replicate raw.length true ++ [])) at h
+ rw [List.append_nil] at h
+ have he : Function.update (prepared raw 0 0 []) .size (List.replicate raw.length true) =
+ prepared raw 0 0 (List.replicate raw.length true) := by funext j; cases j <;> rfl
+ exact he ▸ h
+
+/-- The raw site tape is the only populated stack at entry. Once the public
+parameter pass has run on its measured size, parsing incurs at most another
+`5n+17` stack instructions. -/
+theorem startup_runs (params : FiniteRoutine (InputPort ⊕ K)) {d H w : ℕ}
+ (p : UniversalMachine.Program) (n : ℕ) (v : Fin (2^d)) (hdr : Header) (inc : Fin (width d H w) → Bool)
+ (hf : Fits p n d H w) (t : ℕ)
+ (hp : params.Runs t (measured (ProcessorInput.tape p n v hdr inc) n)
+ (withScratch (prepared (ProcessorInput.tape p n v hdr inc) d (width d H w) []))) :
+ let raw := ProcessorInput.tape p n v hdr inc
+ let small := prepared raw d (width d H w) []
+ ∃ steps ≤ t + 10*n+19, (startup params).Runs steps (labeledInput (.inl InputPort.input) raw)
+ (withScratch (result small (programPrefix p)
+ (List.ofFn (RAMSerialization.wordBits d v)) (List.ofFn hdr) (List.ofFn inc))) := by
+ let raw := ProcessorInput.tape p n v hdr inc
+ let small := prepared raw d (width d H w) []
+ have hlen : raw.length = n := ProcessorInput.length_tape p v hdr inc hf
+ have hm := length_start raw
+ rw [hlen] at hm
+ have hmeasure : ((FiniteRoutine.ofRoutine lengthRoutine).onPorts Sum.inl).Runs (5*n+2)
+ (labeledInput (.inl InputPort.input) raw) (measured (K := K) raw n) :=
+ (FiniteRoutine.ofRoutine lengthRoutine).runs_onPorts_framed Sum.inl_injective hm
+ (fun i => by cases i <;> rfl) (fun _ => rfl) (fun j hj => by
+ cases j with
+ | inl i => exact (hj i rfl).elim
+ | inr _ => rfl)
+ obtain ⟨z, hz, hparse⟩ := parse_processorTape p n v hdr inc [] hf
+ let done := result small (programPrefix p) (List.ofFn (RAMSerialization.wordBits d v)) (List.ofFn hdr) (List.ofFn inc)
+ have hread : ((FiniteRoutine.ofRoutine parse).onPorts Sum.inl).Runs z
+ (withScratch (K := K) small) (withScratch done) :=
+ (FiniteRoutine.ofRoutine parse).runs_onPorts_framed Sum.inl_injective hparse
+ (fun _ => rfl) (fun _ => rfl) (fun j hj => by
+ cases j with
+ | inl i => exact (hj i rfl).elim
+ | inr _ => rfl)
+ exact ⟨_, by omega, (hmeasure.followedBy hp).followedBy hread⟩
+
+end RAMTape.InputReader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeLinkedClock.lean b/lean/OAI/Computability/VPVNP/RAMTapeLinkedClock.lean
new file mode 100644
index 0000000000..151dd2ed2c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeLinkedClock.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.RAMTapeSiteCore
+import OAI.Computability.VPVNP.RAMTapeOwnPrefixOperands
+import OAI.Computability.VPVNP.RAMProcessorPhysicalClock
+
+/-!
+# Clock and input capacity of the linked live coefficient program
+
+Startup computes the public operands, reads the cuts and nominates the
+private choice string. The fixed per-choice program then runs the site graph
+and checks the sorting fields. Its exact budget includes initialization of
+the architectural registers, the site's first record, and the terminal test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+
+open BurstRAM SiteProcessor Filter
+
+/-- The complete clock for a raw site, including its public input stage. -/
+def linkedTicks {d e w : ℕ} (regs cstart : ℕ) (x : SiteCutBank.Input d e w) : ℕ :=
+ cstart*(x.n+1)^max 7 (x.u+1) + coreSteps regs x
+
+/-- Absorb the actual entry, register reset and first-record costs in the
+startup term of the physical two-tape estimate. -/
+theorem linkedTicks_le {d e w : ℕ} (regs cstart : ℕ) (x : SiteCutBank.Input d e w)
+ (hu : 1 ≤ x.u) (hH : 2^e ≤ 2*x.n) (hw : w ≤ x.n) :
+ linkedTicks regs cstart x ≤ totalStackCutoff d e w regs (x.n^x.u)
+ ((cstart+500+11*regs)*(x.n+1)^max 7 (x.u+1)) := by
+ let N := (x.n+1)^max 7 (x.u+1)
+ have hn : x.n+1 ≤ N := Nat.le_self_pow (by dsimp [N]; omega) _
+ have hp : (x.n+1)^(x.u+1) ≤ N := Nat.pow_le_pow_right (Nat.succ_pos _) (le_max_right ..)
+ have hentry := (entrySteps_le x hu hH hw).trans (Nat.mul_le_mul_left 400 hp)
+ have hr : regs*(8*w+3) ≤ (11*regs)*N := by
+ rw [show 11*regs*N = regs*(11*N) by ring]
+ exact Nat.mul_le_mul_left _ (by omega)
+ change cstart*N + (perChoiceBudget d e w regs (x.n^x.u) + entrySteps x) ≤
+ totalStackCutoff d e w regs (x.n^x.u) ((cstart+500+11*regs)*N)
+ simp only [perChoiceBudget, SiteCutBank.graphBudget, totalStackCutoff, Nat.add_mul]
+ omega
+
+set_option exponentiation.threshold 100031 in
+/-- Live integer exponents give the same bucket capacity as the paper's real
+formula. A single threshold handles all site addresses, all incident choices,
+the literal table prefix, and both the tighter site clock and `K_*`. -/
+theorem eventually_live_clock (prog : UniversalMachine.Program) (regs cstart ports B a b : ℕ)
+ (hB : 1 ≤ B) (hab : a < b) :
+ ∀ᶠ n : ℕ in atTop,
+ let d := addressWidth B n
+ let e := roundedUp a b n
+ let w := CursorBounds.wordBits B n
+ ProcessorInput.Fits prog n d (2^e) w ∧ (UniversalMachine.programPrefix prog).length ≤ w ∧
+ ∀ x : SiteCutBank.Input d e w, x.n = n → x.u = 10000 →
+ let T := linkedTicks regs cstart x
+ T*(6*(n+(ports+1)+T)+4) ≤ n^100030 ∧ T*(6*(n+(ports+1)+T)+4) ≤ n^clockExponent := by
+ let δ := 1-(a:ℝ)/b
+ have hb : 0 < (b:ℝ) := by exact_mod_cast (show 0 < b by omega)
+ have hδ : 0 < δ := sub_pos.mpr ((div_lt_one hb).mpr (by exact_mod_cast hab))
+ have hδ' : δ ≤ 1 := sub_le_self _ (by positivity)
+ have eqe (n : ℕ) : Compression.bucketExponent (1-δ) n = roundedUp a b n := by
+ rw [roundedUp_eq, show 1-δ = (a:ℝ)/b by dsimp [δ]; ring]
+ filter_upwards [eventually_both_application_clocks hB hδ.le hδ' regs (cstart+500+11*regs)
+ ports 0 0 0, eventually_bothProcessorBudgets hB hδ.le hδ', eventually_liveInputFits prog B hδ hδ',
+ OwnPrefix.Physical.eventually_prefix_fits prog hB] with n clock budget fit pre
+ have hc := clock.1
+ have hbound := budget.1
+ rw [eqe] at hc hbound
+ change ProcessorInput.Fits prog n _ (2^(Compression.bucketExponent (1-δ) n)) _ at fit
+ rw [eqe] at fit
+ refine ⟨fit, pre, ?_⟩
+ intro x hxn hxu
+ have hH := hbound.bucket_le.trans_eq (congrArg (2*·) hxn.symm)
+ have hw := hbound.word_le.trans_eq hxn.symm
+ have ht := linkedTicks_le regs cstart x (by omega) hH hw
+ rw [hxn, hxu] at ht
+ exact hc (n^10000) ((cstart+500+11*regs)*(n+1)^max 7 (10000+1)) (linkedTicks regs cstart x)
+ le_rfl le_rfl ht
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeLiveProcessor.lean b/lean/OAI/Computability/VPVNP/RAMTapeLiveProcessor.lean
new file mode 100644
index 0000000000..dada9228da
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeLiveProcessor.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.RAMTapeSiteMachine
+import OAI.Computability.VPVNP.RAMTapeLinkedClock
+import OAI.Computability.VPVNP.RAMTapeInputOperandStartup
+
+/-!
+# A literal universal coefficient for the live RAM transcript
+
+Given a fixed private instruction table and its finite list of public operand
+formulas, compile the actual raw-input processor into a two-tape program.
+At every sufficiently large fitted length, each site's coefficient is the
+exact cardinal of its private incident paths. The program reads its own
+literal prefix to obtain operands that refer to that prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+set_option synthInstance.maxSize 10000
+
+open BurstRAM PrivateRAM LiveProgram ProcessorInput RAMLayout Filter
+variable {p r k : ℕ}
+
+/-- Literal two-tape program combining the fixed private template with the startup that
+evaluates its operands from the physical site and the program’s own prefix. -/
+noncomputable def machine (T : Template p r k) (args : Fin k → InputOperand)
+ (B a b u lit : ℕ) (hb : 0 < b) : UniversalMachine.Program :=
+ table (InputOperandStartup.Expr args) T (InputOperandStartup.program r args B a b u lit hb)
+
+theorem machine_count (T : Template p r k) (args : Fin k → InputOperand)
+ (B a b u lit : ℕ) (hB : 1 ≤ B) (hb : 0 < b) (hab : a ≤ b) (hu : 1 ≤ u)
+ (n : ℕ) (hn : 1 ≤ n) :
+ let d := addressWidth B n
+ let e := roundedUp a b n
+ let w := CursorBounds.wordBits B n
+ let g : Geometry := ⟨n,d,2^e,w⟩
+ let D := machine T args B a b u lit hb
+ ∀ (x : SiteCutBank.Input d e w), x.prog = D → x.n = n → x.u = u → x.lit = lit →
+ ∀ (fit : Fits D n d (2^e) w), (UniversalMachine.programPrefix D).length ≤ w →
+ (∀ i, (InputOperandStartup.Expr args i).Fits g (2^w)) →
+ let ticks := linkedTicks r (InputOperandStartup.clockCoefficient args B a b u) x
+ ticks*(6*(n+(Fintype.card (InputOperandStartup.Target r args)+1)+ticks)+4) ≤ n^clockExponent →
+ acceptingCount (encode D n x.v x.hdr (RAMLayout.incidentBits x.sends x.v) fit) =
+ x.pathCard T (fun i => Pieces.word g (CounterPublic.actualPrefix D) (args i)) := by
+ intro d e w g D x hx hxn hxu hxl fit hprefix hg ticks hclock
+ obtain ⟨t, ht, s, run, frame, blank⟩ := InputOperandStartup.frame_runs r args B a b u lit
+ hB hb hab hu n hn x hxn hxu hxl (hx ▸ fit) (hx ▸ hprefix) hg
+ rw [hx] at run frame
+ have hbound : coreSteps r x + t ≤ ticks := by
+ dsimp only [ticks, linkedTicks]
+ rw [hxn, hxu, Nat.add_comm]
+ exact Nat.add_le_add_right ht _
+ have eqn := table_coefficient (InputOperandStartup.Expr args) T (InputOperandStartup.program r args B a b u lit hb)
+ x (fun i => Pieces.word g (CounterPublic.actualPrefix D) (args i)) s t ticks
+ rw [hxn] at eqn
+ exact eqn fit run frame blank hbound hclock
+
+/-- All group headers and compatible incident words at one live geometry. -/
+def CountsAt (T : Template p r k) (args : Fin k → InputOperand)
+ (D : UniversalMachine.Program) (n d e w lit : ℕ) (hw : 4 ≤ w) : Prop :=
+ let g : Geometry := ⟨n,d,2^e,w⟩
+ ∃ fit : Fits D n d (2^e) w,
+ (∀ i, (InputOperandStartup.Expr args i).Fits g (2^w)) →
+ ∀ (v : Word d) (hdr : Header) (sends : SendArrays d (2^e) w),
+ ∃ hc : 2^d*2^e < 2^w,
+ acceptingCount (encode D n v hdr (RAMLayout.incidentBits sends v) fit) =
+ Nat.card ((T.instantiate w (fun i => Pieces.word g (CounterPublic.actualPrefix D) (args i))).IncidentPaths
+ (n^10000) (Fin.ofNat (2^w) lit) (headerWord hw hdr) ((by decide : 2 ≤ 4).trans hw)
+ hc v (RAMLayout.incidentBits sends v))
+
+set_option exponentiation.threshold 10000 in
+/-- At the live exponent the explicit physical clock and the literal-prefix
+fit are simultaneous for every site, header and shared-bit assignment. -/
+theorem eventually_machine_count (T : Template p r k) (args : Fin k → InputOperand)
+ (B a b lit : ℕ) (hB : 1 ≤ B) (hb : 0 < b) (hab : a < b) :
+ ∀ᶠ n : ℕ in atTop, CountsAt T args (machine T args B a b 10000 lit hb) n (addressWidth B n)
+ (roundedUp a b n) (CursorBounds.wordBits B n) lit (ProcessorPublic.recordWidth_ge_four _) := by
+ let D := machine T args B a b 10000 lit hb
+ let coef := InputOperandStartup.clockCoefficient args B a b 10000
+ let ports := Fintype.card (InputOperandStartup.Target r args)
+ filter_upwards [eventually_live_clock D r coef ports B a b hB hab, eventually_ge_atTop 1] with n h hn
+ obtain ⟨fit, hprefix, clock⟩ := h
+ refine ⟨fit, fun hg v hdr sends => ?_⟩
+ let x : SiteCutBank.Input (addressWidth B n) (roundedUp a b n) (CursorBounds.wordBits B n) :=
+ ⟨D,n,10000,lit,v,hdr,sends,ProcessorPublic.capFits B a b n hB hb hab.le hn,
+ ProcessorPublic.recordWidth_ge_four _,rfl⟩
+ exact ⟨x.cap_lt, machine_count T args B a b 10000 lit hB hb hab.le (by decide)
+ n hn x rfl rfl rfl rfl fit hprefix hg (clock x rfl rfl).2⟩
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeMapWord.lean b/lean/OAI/Computability/VPVNP/RAMTapeMapWord.lean
new file mode 100644
index 0000000000..36b10e652d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeMapWord.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.StructuredStackLoop
+
+/-!
+# Emitting the bits of a record word without consuming its register
+
+The buffer for the pre-sort probe records is accumulated in reverse bit
+order. A fixed pop/push control copies each word's bits onto this buffer and
+restores the source using one scratch stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.WordCopy
+
+variable {K : Type} (tmpPort outPort : K)
+open Routine
+
+/-- Copy a single popped bit to the accumulating record buffer and save it
+temporarily for restoration. -/
+private def saveBit (f : Bool → Bool) (b : Bool) :=
+ (Routine.push outPort (f b)).followedBy (Routine.push tmpPort b)
+
+private def save (f : Bool → Bool) (src : K) :=
+ Routine.popLoop src (fun _ => true) (saveBit tmpPort outPort f false) (saveBit tmpPort outPort f true)
+
+private def restore (src : K) :=
+ Routine.popLoop tmpPort (fun _ => true) (Routine.push src false) (Routine.push src true)
+
+/-- Copy the source word to the reverse buffer bit by bit through the given Boolean map, then
+restore the source from scratch. -/
+def mapWord (f : Bool → Bool) (src : K) : FiniteRoutine K :=
+ .ofRoutine ((save tmpPort outPort f src).followedBy (restore tmpPort src))
+
+variable [DecidableEq K] {src : K}
+
+private def frame (src : K) (s : Stacks K) (x tmp buf : List Bool) : Stacks K :=
+ fun j => if j = src then x else if j = tmpPort then tmp else if j = outPort then buf else s j
+
+private theorem frame_eq (src : K) (s : Stacks K) :
+ frame tmpPort outPort src s (s src) (s tmpPort) (s outPort) = s := by
+ funext j
+ simp only [frame]
+ split_ifs <;> subst_vars <;> rfl
+
+private theorem set_src (s : Stacks K) (x tmp buf x' : List Bool) :
+ Function.update (frame tmpPort outPort src s x tmp buf) src x' = frame tmpPort outPort src s x' tmp buf := by
+ funext j
+ by_cases h : j=src <;> simp [frame, h]
+
+private theorem set_tmp (h : src ≠ tmpPort) (s : Stacks K) (x tmp buf tmp' : List Bool) :
+ Function.update (frame tmpPort outPort src s x tmp buf) tmpPort tmp' = frame tmpPort outPort src s x tmp' buf := by
+ funext j
+ by_cases h₁ : j=tmpPort <;> simp [frame, h₁, Ne.symm h]
+
+private theorem set_buf (h : src ≠ outPort) (hd : tmpPort ≠ outPort) (s : Stacks K) (x tmp buf buf' : List Bool) :
+ Function.update (frame tmpPort outPort src s x tmp buf) outPort buf' = frame tmpPort outPort src s x tmp buf' := by
+ funext j
+ by_cases h₁ : j=outPort <;> simp [frame, h₁, Ne.symm h, Ne.symm hd]
+
+private theorem saveBit_runs (f : Bool → Bool) (h₁ : src ≠ tmpPort) (h₂ : src ≠ outPort) (h₃ : tmpPort ≠ outPort)
+ (s : Stacks K) (x tmp buf : List Bool) (b : Bool) :
+ (saveBit tmpPort outPort f b).Runs 2 (frame tmpPort outPort src s x tmp buf) (frame tmpPort outPort src s x (b::tmp) (f b::buf)) := by
+ have hb := runs_push outPort (f b) (frame tmpPort outPort src s x tmp buf)
+ have ht := runs_push tmpPort b (frame tmpPort outPort src s x tmp (f b::buf))
+ simp only [set_buf _ _ h₂ h₃, set_tmp _ _ h₁, frame, Ne.symm h₁, Ne.symm h₂, Ne.symm h₃,
+ ↓reduceIte] at hb ht
+ exact hb.followedBy ht
+
+private theorem save_runs (f : Bool → Bool) (h₁ : src ≠ tmpPort) (h₂ : src ≠ outPort) (h₃ : tmpPort ≠ outPort)
+ (s : Stacks K) (x tmp buf : List Bool) :
+ (save tmpPort outPort f src).Runs (3*x.length+1) (frame tmpPort outPort src s x tmp buf)
+ (frame tmpPort outPort src s [] (x.reverse++tmp) ((x.map f).reverse++buf)) := by
+ induction x generalizing tmp buf with
+ | nil =>
+ apply Runs.popLoop_empty
+ simp [frame]
+ | cons b xs ih =>
+ have head : frame tmpPort outPort src s (b::xs) tmp buf src = b::xs := by simp [frame]
+ have hbody := saveBit_runs tmpPort outPort f h₁ h₂ h₃ s xs tmp buf b
+ have tail := ih (b::tmp) (f b::buf)
+ have H := Runs.popLoop_continue src (fun _ => true) (saveBit tmpPort outPort f false) (saveBit tmpPort outPort f true) head rfl
+ (by rw [set_src]; cases b <;> exact hbody) tail
+ simpa [save, List.reverse_cons, List.append_assoc, Nat.mul_succ, Nat.add_comm, Nat.add_left_comm] using H
+
+private theorem restore_runs (h₁ : src ≠ tmpPort) (s : Stacks K) (x tmp buf : List Bool) :
+ (restore tmpPort src).Runs (2*tmp.length+1) (frame tmpPort outPort src s x tmp buf)
+ (frame tmpPort outPort src s (tmp.reverse++x) [] buf) := by
+ induction tmp generalizing x with
+ | nil =>
+ apply Runs.popLoop_empty
+ simp [frame, Ne.symm h₁]
+ | cons b tmp ih =>
+ have head : frame tmpPort outPort src s x (b::tmp) buf tmpPort = b::tmp := by simp [frame, Ne.symm h₁]
+ have hbody := runs_push src b (frame tmpPort outPort src s x tmp buf)
+ rw [set_src] at hbody
+ have H := Runs.popLoop_continue tmpPort (fun _ => true) (Routine.push src false)
+ (Routine.push src true) head rfl (by
+ rw [set_tmp _ _ h₁]
+ cases b <;> simpa [frame] using hbody) (ih (b::x))
+ simpa [restore, List.reverse_cons, List.append_assoc, Nat.mul_succ, Nat.add_comm, Nat.add_left_comm] using H
+
+/-- Five primitive instructions per source bit and the two empty-stack tests. -/
+theorem mapWord_run (f : Bool → Bool) (h₁ : src ≠ tmpPort) (h₂ : src ≠ outPort) (h₃ : tmpPort ≠ outPort) (s : Stacks K)
+ (ht : s tmpPort = []) :
+ (mapWord tmpPort outPort f src).Runs (5*(s src).length+2) s
+ (Function.update s outPort (((s src).map f).reverse ++ s outPort)) := by
+ let x := s src
+ let b := s outPort
+ have ha := save_runs tmpPort outPort f h₁ h₂ h₃ s x [] b
+ have hr := restore_runs tmpPort outPort h₁ s [] x.reverse ((x.map f).reverse ++ b)
+ simp only [List.append_nil, List.length_reverse, List.reverse_reverse] at ha hr
+ have H := ha.followedBy hr
+ have hi := frame_eq tmpPort outPort src s
+ rw [ht] at hi
+ have ho := set_buf tmpPort outPort (src := src) h₂ h₃ s x [] b ((x.map f).reverse ++ b)
+ rw [hi] at ho
+ rw [hi, ← ho] at H
+ rw [show 3*x.length+1+(2*x.length+1) = 5*x.length+2 by omega] at H
+ exact H
+
+/-- Prepare a zero word from the preserved width template, using one empty
+scratch stack. Every input bit contributes one output zero. -/
+theorem zero_template (h₁ : src ≠ tmpPort) (h₂ : src ≠ outPort) (h₃ : tmpPort ≠ outPort)
+ (s : Stacks K) (hs : s tmpPort = []) (ho : s outPort = []) :
+ (mapWord tmpPort outPort (fun _ => false) src).Runs (5*(s src).length+2) s
+ (Function.update s outPort (List.replicate (s src).length false)) := by
+ simpa [ho, List.map_const'] using mapWord_run tmpPort outPort (fun _ => false) h₁ h₂ h₃ s hs
+
+end RAMTape.WordCopy
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeNamed.lean b/lean/OAI/Computability/VPVNP/RAMTapeNamed.lean
new file mode 100644
index 0000000000..308e44888f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeNamed.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.RAMTapeCoefficient
+import OAI.Computability.VPVNP.RAMTapeStackLift
+
+/-!
+# Named stack ports for the literal coefficient machine
+
+Port zero receives the raw input tape. All other labels in the finite bank
+are sent to distinct positive ports, so a program can be compiled directly
+from its named stack control. Renaming preserves each branch's halting bound
+and the integer count of accepting paths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+/-- Relabel a finite-control machine with all instructions preserved,
+including both targets of each binary choice. -/
+theorem stopsWithin_lift {K L Q R : Type*} [DecidableEq K] [DecidableEq L]
+ {src : StackCode K Q} {target : StackCode L R} (ports : K → L)
+ (hp : Function.Injective ports) (labels : Q → R) (base : Stacks L)
+ (hc : ∀ q, target (labels q) = (src q).rename ports labels)
+ (n : ℕ) (q : Q) (s : Stacks K) :
+ StopsWithin target n (labels q) (installStacks ports base s) ↔ StopsWithin src n q s := by
+ induction n generalizing q s with
+ | zero => rfl
+ | succ n ih =>
+ rw [StopsWithin, hc, StopsWithin]
+ cases src q <;> simp only [StackOp.rename, Function.comp_apply, installStacks_at hp,
+ installStacks_update hp, ih]
+
+namespace StackCompiler
+
+open UniversalMachine BurstRAM
+
+variable {K Q : Type*} [Fintype K] [DecidableEq K]
+
+/-- The physical compiler uses a spare positive port to avoid subtracting
+one from the bank size when moving the designated input to port zero. -/
+noncomputable def labeledPort (inputPort p : K) : Fin (Fintype.card K + 1) :=
+ if p = inputPort then 0 else (Fintype.equivFin K p).succ
+
+theorem labeledPort_injective (inputPort : K) : Function.Injective (labeledPort inputPort) := by
+ intro i j h
+ by_cases hi : i = inputPort <;> by_cases hj : j = inputPort <;>
+ simp_all [labeledPort, Fin.succ_inj]
+ exact (Fin.succ_ne_zero _ h.symm).elim
+
+/-- Relocate the named stack instructions to numerical stack indices. -/
+noncomputable def labeledCode (inputPort : K) (code : StackCode K Q) : StackCode (Fin (Fintype.card K + 1)) Q :=
+ fun q => (code q).rename (labeledPort inputPort) id
+
+/-- Initialize the designated input stack with the raw input word. -/
+def labeledInput (inputPort : K) (raw : Word) : Stacks K :=
+ fun p => if p = inputPort then raw else []
+
+theorem installedInput (inputPort : K) (raw : Word) :
+ installStacks (labeledPort inputPort) (inputStacks raw) (labeledInput inputPort raw) = inputStacks raw := by
+ apply installStacks_eq (labeledPort_injective inputPort)
+ intro p
+ by_cases h : p = inputPort <;> simp [h, labeledPort, labeledInput, inputStacks]
+
+variable [Fintype Q]
+
+/-- The literal universal-machine program for the named stack machine. -/
+noncomputable abbrev labeledProgram (inputPort : K) (code : StackCode K Q) (start : Q) : Program :=
+ program (labeledCode inputPort code) start
+
+/-- The fixed two-tape table for a labeled stack program computes its exact
+bounded accepting-path count from a raw input. -/
+theorem input_count_labeled (inputPort : K) (code : StackCode K Q) (start : Q) (raw : Word)
+ (T ticks : ℕ) (stops : StopsWithin code T start (labeledInput inputPort raw))
+ (clock : T * (6 * (raw.length + (Fintype.card K + 1) + T) + 4) ≤ ticks) :
+ paths (labeledProgram inputPort code start) ticks (initial (labeledProgram inputPort code start) raw) =
+ stackPaths code T start (labeledInput inputPort raw) := by
+ have halt := (stopsWithin_lift (target := labeledCode inputPort code) (labeledPort inputPort)
+ (labeledPort_injective inputPort) id (inputStacks raw) (fun _ => rfl) T start _).2 stops
+ have count := stackPaths_lift (src := code) (target := labeledCode inputPort code) (labeledPort inputPort)
+ (labeledPort_injective inputPort) id (inputStacks raw) (fun _ => rfl) T start (labeledInput inputPort raw)
+ rw [installedInput] at halt count
+ exact (input_count _ _ _ _ _ halt clock).trans count
+
+/-- At a site, the input on the designated named port contains the fixed
+program's own prefix, header, incidence messages, and padding to length n. -/
+theorem site_count_labeled (inputPort : K) (code : StackCode K Q) (start : Q) (n T : ℕ) {d H w : ℕ}
+ (v : Fin (2^d)) (hdr : ProcessorInput.Header) (inc : Fin (RAMLayout.width d H w) → Bool)
+ (fits : ProcessorInput.Fits (labeledProgram inputPort code start) n d H w)
+ (stops : StopsWithin code T start (labeledInput inputPort
+ (ProcessorInput.tape (labeledProgram inputPort code start) n v hdr inc)))
+ (clock : T * (6 * (n + (Fintype.card K + 1) + T) + 4) ≤ n^clockExponent) :
+ acceptingCount (ProcessorInput.encode (labeledProgram inputPort code start) n v hdr inc fits) =
+ stackPaths code T start (labeledInput inputPort
+ (ProcessorInput.tape (labeledProgram inputPort code start) n v hdr inc)) := by
+ rw [ProcessorInput.coefficient]
+ apply input_count_labeled _ _ _ _ _ _ stops
+ simpa only [ProcessorInput.length_tape _ _ _ _ fits] using clock
+
+end StackCompiler
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeOwnPrefix.lean b/lean/OAI/Computability/VPVNP/RAMTapeOwnPrefix.lean
new file mode 100644
index 0000000000..fac022cbff
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeOwnPrefix.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.RAMTapePublicGeometry
+import OAI.Computability.VPVNP.RAMTapeSiteRecordWords
+import OAI.Computability.VPVNP.PrimedInputRAMOpcodeParameters
+
+/-!
+# Packing the processor's own parsed prefix
+
+The prefix remains on the processor's input-reader stack. A fixed stack
+routine extends these bits to the physical word width and counts their
+actual length into a second word. It takes the prefix solely as data.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.OwnPrefix
+
+open BurstRAM TapeWord Function
+open SiteRecordWords (Port)
+
+private def counterPorts : UnaryWord.Port → Port
+ | .src => .header
+ | .pending => .count
+ | .number => .addressWord
+ | .unit => .width
+ | .tmp => .tmp
+
+private theorem counterPorts_inj : Injective counterPorts := by decide
+
+private def count := FiniteRoutine.ofStackCode (UnaryWord.code 0) counterPorts .count (· == .done)
+
+/-- Extend the copied prefix and count its bits. The same stack table is
+used for every processor and every program on the input tape. -/
+def program : FiniteRoutine Port :=
+ ((SiteRecordWords.extendHeader.followedBy
+ (WordCopy.mapWord .tmp .addressWord (fun _ => false) .width)).followedBy
+ (WordCopy.mapWord .tmp .count (fun _ => true) .header)).followedBy count
+
+/-- Step count for padding and packing the parsed prefix and computing its length as a word. -/
+def steps (w P : ℕ) := (5*w + 13*P + 7) + (5*w+2) + (5*P+2) + (P*(4*w+3)+1)
+
+theorem steps_le {w P : ℕ} (h : P ≤ w) : steps w P ≤ 43*(w+1)^2 := by
+ have hp := Nat.mul_le_mul_right (4*w+3) h
+ unfold steps
+ nlinarith only [h, hp, Nat.zero_le w, Nat.zero_le (w*w)]
+
+/-- `.header` is the saved prefix and `.width` the saved unary word width.
+The two output fields receive its packed bits and its packed length. -/
+theorem runs (s : Stacks Port) (w : ℕ) (hfit : (s .header).length ≤ w)
+ (hw : s .width = List.replicate w true) (hb : s .headerWord = [])
+ (hl : s .addressWord = []) (hc : s .count = []) (ht : s .tmp = []) :
+ program.Runs (steps w (s .header).length) s
+ (update (update s .headerWord (s .header ++ List.replicate (w-(s .header).length) false))
+ .addressWord (wordBits (Fin.ofNat (2^w) (s .header).length))) := by
+ let P := (s .header).length
+ let v := update s Port.headerWord (s .header ++ List.replicate (w-P) false)
+ let z := update v Port.addressWord (List.replicate w false)
+ let ready := update z Port.count (List.replicate P true)
+ let out := update v Port.addressWord (wordBits (Fin.ofNat (2^w) P))
+ have hv := SiteRecordWords.extendHeader_runs s w hfit hw hb hc ht
+ have hz : (WordCopy.mapWord .tmp .addressWord (fun _ => false) .width).Runs (5*w+2) v z := by
+ have hr := WordCopy.mapWord_run Port.tmp Port.addressWord (fun _ => false)
+ (by decide : Port.width ≠ .tmp) (by decide) (by decide) v (by simpa [v] using ht)
+ simpa [v, z, hw, hl, List.map_const'] using hr
+ have hm : (WordCopy.mapWord .tmp .count (fun _ => true) .header).Runs (5*P+2) z ready := by
+ have hr := WordCopy.mapWord_run Port.tmp Port.count (fun _ => true)
+ (by decide : Port.header ≠ .tmp) (by decide) (by decide) z (by simpa [z, v] using ht)
+ simpa [P, ready, z, v, hc, List.map_const'] using hr
+ have hcount : count.Runs (P*(4*w+3)+1) ready out := by
+ apply FiniteRoutine.runs_ofStackCode_framed counterPorts_inj (normal := (· == .done))
+ rfl rfl (fun q h => by cases q <;> first | rfl | contradiction)
+ (UnaryWord.count_fixed 0 w P (s .header) (s .width) (hfit.trans_lt Nat.lt_two_pow_self))
+ · intro j
+ cases j <;> simp [counterPorts, ready, z, v, UnaryWord.store, ht]
+ · intro j
+ cases j <;> simp [counterPorts, out, v, UnaryWord.store, hc, ht]
+ · intro j hj
+ cases j <;> first | rfl | exact (hj .number rfl).elim | exact (hj .pending rfl).elim
+ exact ((hv.followedBy hz).followedBy hm).followedBy hcount
+
+theorem prefixWordBits (p : UniversalMachine.Program) {w : ℕ} (hf : (UniversalMachine.programPrefix p).length ≤ w) :
+ UniversalMachine.programPrefix p ++ List.replicate (w-(UniversalMachine.programPrefix p).length) false =
+ wordBits (SiteRecordWords.addressWord hf (PrimedInputRAM.Opcodes.packedPrefix p)) := by
+ have h : wordBits (PrimedInputRAM.Opcodes.packedPrefix p) = UniversalMachine.programPrefix p := by
+ simp [wordBits, PrimedInputRAM.Opcodes.packedPrefix]
+ simpa only [h] using SiteRecordWords.address_bits hf (PrimedInputRAM.Opcodes.packedPrefix p)
+
+end RAMTape.OwnPrefix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeOwnPrefixOperands.lean b/lean/OAI/Computability/VPVNP/RAMTapeOwnPrefixOperands.lean
new file mode 100644
index 0000000000..6560799711
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeOwnPrefixOperands.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.RAMTapeOwnPrefixStartup
+
+/-!
+# Computing the live operand vector with the processor's own code as data
+
+Compose the six-word physical startup with the finite arithmetic expression
+loader. The primed assembler's length and packed-prefix slots agree with its
+specification for the actual program, although the loader is fixed before
+this program is chosen.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.OwnPrefix.Physical
+
+open BurstRAM LiveProgram RAMLayout ProcessorInput StackCompiler PublicExprMachine
+
+variable {k : ℕ}
+
+/-- Parse the physical site and its prefix into six public words, then run the operand program
+on that bank. -/
+def operandStartup (args : Fin k → InputOperand) (B a b u lit : ℕ) (hb : 0 < b) :
+ FiniteRoutine (Port (InputOperandMachine.registers args)) :=
+ (startup _ B a b u lit hb).followedBy ((InputOperandMachine.program args).onPorts Sum.inr)
+
+/-- Clock coefficient for parsing the physical inputs, packing the actual prefix, evaluating
+geometry, and filling the operand slots. -/
+def operandCoefficient (args : Fin k → InputOperand) (B a b u : ℕ) :=
+ ProcessorPublic.recordClockCoefficient B a b u + 183 + 11*InputOperandMachine.registers args +
+ coefficient (InputOperandMachine.geometryOnly args) + 11*k + 2
+
+theorem operand_runs (args : Fin k → InputOperand) (B a b u lit : ℕ)
+ (hB : 1 ≤ B) (hb : 0 < b) (hab : a ≤ b) (hu : 1 ≤ u)
+ (prog : UniversalMachine.Program) (n : ℕ) (hn : 1 ≤ n) :
+ let d := B * Nat.clog 2 n
+ let e := roundedUp a b n
+ let w := (d+10)^4
+ let g : Geometry := ⟨n, d, 2^e, w⟩
+ ∀ (v : Word d) (hdr : Header) (inc : Fin (width d (2^e) w) → Bool), Fits prog n d (2^e) w →
+ (UniversalMachine.programPrefix prog).length ≤ w →
+ (∀ i, (InputOperandMachine.geometryOnly args i).Fits g (2^w)) →
+ let processor := ProcessorPublic.recordResult (ProcessorPublic.rawResult prog n d (2^e) w v hdr inc)
+ n d e w u lit v hdr (ProcessorPublic.capFits B a b n hB hb hab hn) (ProcessorPublic.recordWidth_ge_four d)
+ ∃ t ≤ operandCoefficient args B a b u * (n+1)^max 7 (u+1),
+ ∃ out : Fin (InputOperandMachine.registers args) → Word w,
+ (operandStartup args B a b u lit hb).Runs t
+ (labeledInput (.inl ProcessorPublic.rawPort) (ProcessorInput.tape prog n v hdr inc))
+ (Sum.elim processor (ISA.bank (InputOperandMachine.input g (CounterPublic.actualPrefix prog)) 0 out [])) ∧
+ ∀ j, out (InputOperandMachine.slot args j) = Pieces.word g (CounterPublic.actualPrefix prog) (args j) := by
+ intro d e w g v hdr inc fit hp hf processor
+ obtain ⟨s, hs, hstart⟩ := startup_runs (InputOperandMachine.registers args) B a b u lit hB hb hab hu
+ prog n hn v hdr inc fit hp
+ obtain ⟨t, ht, out, hop, hout⟩ := InputOperandMachine.runs args g (CounterPublic.actualPrefix prog)
+ hf 0 (fun _ => 0) []
+ have lifted : ((InputOperandMachine.program args).onPorts Sum.inr).Runs t
+ (Sum.elim processor (ISA.bank (InputOperandMachine.input g (CounterPublic.actualPrefix prog)) 0 (fun _ => 0) []))
+ (Sum.elim processor (ISA.bank (InputOperandMachine.input g (CounterPublic.actualPrefix prog)) 0 out [])) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inr_injective hop
+ · intro; rfl
+ · intro; rfl
+ · rintro (i|i) h
+ · rfl
+ · exact (h i rfl).elim
+ refine ⟨_, ?_, out, hstart.followedBy lifted, hout⟩
+ let K := (n+1)^max 7 (u+1)
+ have hK : 1 ≤ K := one_le_pow₀ (by omega)
+ have hw : w ≤ n := by
+ change (UniversalMachine.programPrefix prog).length + (d + 4 + width d (2^e) w) ≤ n at fit
+ rw [width_eq] at fit
+ omega
+ have hw₂ : (w+1)^2 ≤ K := (Nat.pow_le_pow_left (Nat.succ_le_succ hw) 2).trans
+ (Nat.pow_le_pow_right (Nat.succ_pos n) (by omega))
+ have hw₁ : w + 1 ≤ K := (Nat.succ_le_succ hw).trans (Nat.le_self_pow (by omega) _)
+ have hm : k*(8*w+3) ≤ (11*k)*K := calc
+ _ ≤ k*(11*K) := Nat.mul_le_mul_left _ (by omega)
+ _ = _ := by ring
+ have ht' : t ≤ (coefficient (InputOperandMachine.geometryOnly args) + 11*k + 2)*K := by
+ change t ≤ coefficient (InputOperandMachine.geometryOnly args)*(w+1)^2+k*(8*w+3)+2 at ht
+ rw [Nat.add_mul, Nat.add_mul]
+ exact ht.trans (Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left _ hw₂) hm) (by omega))
+ exact (Nat.add_le_add hs ht').trans (by unfold operandCoefficient; dsimp [K]; ring_nf; rfl)
+
+/-- Every fixed program's literal prefix eventually fits in one live word. -/
+theorem eventually_prefix_fits (prog : UniversalMachine.Program) {B : ℕ} (hB : 1 ≤ B) :
+ ∀ᶠ n : ℕ in Filter.atTop, (UniversalMachine.programPrefix prog).length ≤ CursorBounds.wordBits B n := by
+ let P := (UniversalMachine.programPrefix prog).length
+ filter_upwards [Filter.eventually_ge_atTop (2^(P+1))] with n hn
+ have hn₀ : 0 < n := (Nat.two_pow_pos _).trans_le hn
+ have hlarge := ((Nat.le_log2 hn₀.ne').mpr hn).trans (log2_le_addressWidth hB n)
+ change P ≤ (addressWidth B n + 10)^4
+ exact (show P ≤ addressWidth B n + 10 by omega).trans (Nat.le_self_pow (by decide) _)
+
+end RAMTape.OwnPrefix.Physical
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeOwnPrefixStartup.lean b/lean/OAI/Computability/VPVNP/RAMTapeOwnPrefixStartup.lean
new file mode 100644
index 0000000000..9ffd9954ca
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeOwnPrefixStartup.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.RAMTapeOwnPrefix
+import OAI.Computability.VPVNP.RAMTapePublicGeometryStartup
+import OAI.Computability.VPVNP.RAMTapePublicInputOperands
+import OAI.Computability.VPVNP.LivePublicCounterOperands
+
+/-!
+# The six live public inputs from the original site tape
+
+The physical processor first parses its own tape and computes the four
+geometry words. It retains the literal self-delimiting prefix on a stack.
+A fixed routine copies that stack into the fifth and sixth public fields
+as its length and packed value. The startup code has no program-text operand.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.OwnPrefix.Physical
+
+open BurstRAM LiveProgram RAMLayout ProcessorInput StackCompiler PublicExprMachine
+
+/-- Combined physical processor ports and arithmetic bank with six public inputs, including the
+two parsed prefix words. -/
+abbrev Port (r : ℕ) := ProcessorPublic.Port ⊕ ISA.Port r 6
+
+instance (r : ℕ) : DecidableEq (Port r) := by
+ letI : DecidableEq ProcessorPublic.Port := inferInstance
+ infer_instance
+
+noncomputable instance (r : ℕ) : Fintype (Port r) := by
+ letI : Fintype ProcessorPublic.Port := inferInstance
+ infer_instance
+
+/-- Processor stack retaining the complete parsed self-delimiting prefix. -/
+def savedPrefix : ProcessorPublic.Port := .inl (.inl (.inl .prefix))
+
+private def widen {r : ℕ} : PublicGeometry.Physical.Port r → Port r :=
+ Sum.map id InputOperandMachine.embed
+
+private theorem widen_injective (r : ℕ) : Function.Injective (widen (r := r)) :=
+ Sum.map_injective.mpr ⟨Function.injective_id, InputOperandMachine.embed_inj⟩
+
+/-- Intermediate arithmetic bank containing the four geometry words, empty prefix-word slots,
+and zero-valued registers and persistent word. -/
+def geometryBank (r : ℕ) (g : Geometry) : Stacks (ISA.Port r 6)
+ | .pub i => if h : i.val < 4 then wordBits (geometryWords g ⟨i.val, h⟩) else []
+ | .reg _ | .persistent => wordBits (0 : Word g.w)
+ | .work _ | .logPort _ => []
+
+private theorem widen_geometry {r : ℕ} (g : Geometry) (processor : Stacks ProcessorPublic.Port)
+ (raw : List Bool) (code : FiniteRoutine (PublicGeometry.Physical.Port r)) {t : ℕ}
+ (h : code.Runs t (labeledInput (.inl ProcessorPublic.rawPort) raw)
+ (Sum.elim processor (ISA.bank (geometryWords g) 0 (fun _ => 0) []))) :
+ (code.onPorts widen).Runs t (labeledInput (.inl ProcessorPublic.rawPort) raw)
+ (Sum.elim processor (geometryBank r g)) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (widen_injective r) h
+ · rintro (j | j)
+ · simp [widen, labeledInput]
+ · cases j <;> simp [widen, InputOperandMachine.embed, labeledInput]
+ · rintro (j | j)
+ · rfl
+ · cases j with
+ | pub i => simp [widen, InputOperandMachine.embed, geometryBank, i.isLt, ISA.bank]
+ | logPort i => cases i <;> rfl
+ | _ => rfl
+ · rintro (j | j) hj
+ · exact (hj (.inl j) rfl).elim
+ · cases j with
+ | pub i =>
+ by_cases hi : i.val < 4
+ · have he : widen (.inr (.pub ⟨i.val, hi⟩) : PublicGeometry.Physical.Port r) = .inr (.pub i) := by
+ simp [widen, InputOperandMachine.embed]
+ exact (hj _ he).elim
+ · simp [geometryBank, hi, labeledInput]
+ | reg i => exact (hj (.inr (.reg i)) rfl).elim
+ | persistent => exact (hj (.inr .persistent) rfl).elim
+ | work i => exact (hj (.inr (.work i)) rfl).elim
+ | logPort i => exact (hj (.inr (.logPort i)) rfl).elim
+
+private def source (r : ℕ) : SiteRecordWords.Port → Port r
+ | .header => .inl savedPrefix
+ | .width => .inl ProcessorPublic.widthPort
+ | .headerWord => .inr (.pub 5)
+ | .addressWord => .inr (.pub 4)
+ | .count => .inr (.work 0)
+ | .tmp => .inr (.work 1)
+ | .siteLog => .inr (.work 2)
+ | .address => .inr (.work 3)
+
+private theorem source_injective (r : ℕ) : Function.Injective (source r) := by
+ intro a b hab
+ cases a <;> cases b <;> simp_all [source, savedPrefix, ProcessorPublic.widthPort, SiteSetup.wordPort]
+
+private theorem pack_geometry (r : ℕ) (g : Geometry) (prog : UniversalMachine.Program)
+ (processor : Stacks ProcessorPublic.Port) (hp : processor savedPrefix = UniversalMachine.programPrefix prog)
+ (hwidth : processor ProcessorPublic.widthPort = List.replicate g.w true)
+ (hf : (UniversalMachine.programPrefix prog).length ≤ g.w) :
+ (OwnPrefix.program.onPorts (source r)).Runs (steps g.w (UniversalMachine.programPrefix prog).length)
+ (Sum.elim processor (geometryBank r g))
+ (Sum.elim processor (ISA.bank (InputOperandMachine.input g (CounterPublic.actualPrefix prog)) 0 (fun _ => 0) [])) := by
+ let s := (Sum.elim processor (geometryBank r g)) ∘ source r
+ have hpre : s .header = UniversalMachine.programPrefix prog := hp
+ have hr := OwnPrefix.runs s g.w (hpre ▸ hf) hwidth rfl rfl rfl rfl
+ rw [hpre, prefixWordBits prog hf] at hr
+ have hv : SiteRecordWords.addressWord hf (PrimedInputRAM.Opcodes.packedPrefix prog) =
+ packed g.w (PrimedInputRAM.Opcodes.packedPrefix prog).val := by
+ apply Fin.ext
+ exact (Nat.mod_eq_of_lt ((PrimedInputRAM.Opcodes.packedPrefix prog).isLt.trans_le
+ (Nat.pow_le_pow_right (by decide : 0 < 2) hf))).symm
+ apply FiniteRoutine.runs_onPorts_framed _ (source_injective r) hr
+ · intro j; rfl
+ · intro j
+ cases j <;> first | rfl | (change wordBits _ = wordBits _; exact congrArg wordBits hv.symm)
+ · rintro (j | j) hj
+ · rfl
+ · cases j with
+ | pub i =>
+ fin_cases i <;> first | rfl | exact (hj .headerWord rfl).elim | exact (hj .addressWord rfl).elim
+ | logPort i => cases i <;> rfl
+ | _ => rfl
+
+/-- Parse and load the physical operand bank. Its fixed code depends only
+on the register count and the cost parameters of the processor. -/
+def startup (r B a b u lit : ℕ) (hb : 0 < b) : FiniteRoutine (Port r) :=
+ ((PublicGeometry.Physical.startup r B a b u lit hb).onPorts widen).followedBy
+ (OwnPrefix.program.onPorts (source r))
+
+theorem startup_runs (r B a b u lit : ℕ) (hB : 1 ≤ B) (hb : 0 < b) (hab : a ≤ b) (hu : 1 ≤ u)
+ (prog : UniversalMachine.Program) (n : ℕ) (hn : 1 ≤ n) :
+ let d := B * Nat.clog 2 n
+ let e := roundedUp a b n
+ let w := (d+10)^4
+ let g : Geometry := ⟨n, d, 2^e, w⟩
+ ∀ (v : Word d) (hdr : Header) (inc : Fin (width d (2^e) w) → Bool), Fits prog n d (2^e) w →
+ (UniversalMachine.programPrefix prog).length ≤ w →
+ let processor := ProcessorPublic.recordResult (ProcessorPublic.rawResult prog n d (2^e) w v hdr inc)
+ n d e w u lit v hdr (ProcessorPublic.capFits B a b n hB hb hab hn) (ProcessorPublic.recordWidth_ge_four d)
+ ∃ t ≤ (ProcessorPublic.recordClockCoefficient B a b u + 183 + 11*r)*(n+1)^max 7 (u+1),
+ (startup r B a b u lit hb).Runs t
+ (labeledInput (.inl ProcessorPublic.rawPort) (ProcessorInput.tape prog n v hdr inc))
+ (Sum.elim processor (ISA.bank (InputOperandMachine.input g (CounterPublic.actualPrefix prog)) 0
+ (fun _ => 0) [])) := by
+ intro d e w g v hdr inc fit hf processor
+ obtain ⟨s, hs, hrun⟩ := PublicGeometry.Physical.startup_runs r B a b u lit hB hb hab hu prog n hn v hdr inc fit
+ have hgeo := widen_geometry g processor _ _ hrun
+ have hprefix := pack_geometry r g prog processor rfl rfl hf
+ refine ⟨_, ?_, hgeo.followedBy hprefix⟩
+ have hw : w ≤ n := by
+ change (UniversalMachine.programPrefix prog).length + (d + 4 + width d (2^e) w) ≤ n at fit
+ rw [width_eq] at fit
+ omega
+ have h₂ : (w+1)^2 ≤ (n+1)^max 7 (u+1) := (Nat.pow_le_pow_left (Nat.succ_le_succ hw) 2).trans
+ (Nat.pow_le_pow_right (Nat.succ_pos n) (by omega))
+ have hl := (steps_le hf).trans (Nat.mul_le_mul_left 43 h₂)
+ exact (Nat.add_le_add hs hl).trans (by ring_nf; rfl)
+
+end RAMTape.OwnPrefix.Physical
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePhysicalHalting.lean b/lean/OAI/Computability/VPVNP/RAMTapePhysicalHalting.lean
new file mode 100644
index 0000000000..ccb976d95f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePhysicalHalting.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.RAMTapeSpaceNamed
+
+/-!
+# All-branch stopping of the literal stack interpreter
+
+The deterministic seek and restore sequences implementing each stack operation
+are followed along their actual table records. Each binary virtual choice
+branches at a single literal row. Thus the same quadratic clock that bounds
+the accepting-leaf count also bounds the duration of rejecting paths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+/-- Every path of the literal table has stopped within the given clock.
+A row with no successor rejects; the two distinguished terminal states halt
+immediately, independently of the remaining clock. -/
+def AllHalt (p : Program) : ℕ → Config p.extra → Prop
+ | 0, c => c.state.val < 2
+ | n+1, c => c.state.val < 2 ∨
+ match branches p c with
+ | .stop => True
+ | .one a => AllHalt p n (advance c a)
+ | .two a b => AllHalt p n (advance c a) ∧ AllHalt p n (advance c b)
+
+theorem allHalt_terminal (p : Program) (n : ℕ) (c : Config p.extra) (h : c.state.val < 2) :
+ AllHalt p n c := by cases n with
+ | zero => exact h
+ | succ => exact Or.inl h
+
+end UniversalMachine
+
+namespace RAMTape
+
+open UniversalMachine Turing
+
+variable {Q : Type*} [Fintype Q]
+
+private def haltAfter (start : Q) (code : Control Q) (ticks : ℕ) (t u : Tape Symbol) : Command Q → Prop
+ | .halt _ => True
+ | .next q a d b e => AllHalt (compile start code) ticks (running start q (updateTape t a d) (updateTape u b e))
+
+private theorem allHalt_advance (start : Q) (code : Control Q) (n : ℕ) (q : Q)
+ (t u : Tape Symbol) (cmd : Command Q) :
+ AllHalt (compile start code) n (advance (running start q t u) (instruction start cmd)) ↔
+ haltAfter start code n t u cmd := by
+ cases cmd with
+ | next => rfl
+ | halt b =>
+ change _ ↔ True
+ refine iff_true_intro (allHalt_terminal _ _ _ ?_)
+ cases b <;> simp [advance, instruction]
+
+private theorem allHalt_step (start : Q) (code : Control Q) (n : ℕ) (q : Q) (t u : Tape Symbol) :
+ AllHalt (compile start code) (n+1) (running start q t u) ↔
+ match code q t.head u.head with
+ | .stop => True
+ | .one a => haltAfter start code n t u a
+ | .two a b => haltAfter start code n t u a ∧ haltAfter start code n t u b := by
+ rw [AllHalt, or_iff_right (not_lt_of_ge (running_state_ge_two ..)), lookup]
+ cases code q t.head u.head <;> simp only [records, allHalt_advance]
+
+/-- A deterministic tape macro consumes exactly its run length. -/
+theorem Runs.allHalt {code : Control Q} {n q t u q' x y} (h : Runs code n q t u q' x y)
+ (start : Q) (fuel : ℕ) : AllHalt (compile start code) (fuel+n) (running start q t u) ↔
+ AllHalt (compile start code) fuel (running start q' x y) := by
+ induction h with
+ | nil => rfl
+ | cons hs _ ih => rw [Nat.add_succ, allHalt_step, hs]; exact ih
+
+namespace StackCompiler
+
+theorem HeadBox.mono {r R : ℕ} {dx dy : ℤ} (h : HeadBox r dx dy) (hr : r ≤ R) : HeadBox R dx dy := by
+ unfold HeadBox at h ⊢
+ omega
+
+variable {k : ℕ} (code : StackCode (Fin k) Q) (start : Q)
+
+private abbrev halted (ticks : ℕ) (q : Q) (s : Stacks (Fin k)) :=
+ AllHalt (compile (.ready start) (rows code)) ticks
+ (running (.ready start) (.ready q) (tapeList (packed s)) (tapeList []))
+
+private theorem allHalt_of_step {t B ticks : ℕ} {q s q' s'}
+ (h : StackStep code q s q' s') (hsize : (packed s).length+t+1 ≤ B)
+ (hclock : (t+1)*(6*B+4) ≤ ticks)
+ (ih : ∀ left, (packed s').length+t ≤ B → t*(6*B+4) ≤ left → halted code start left q' s') :
+ halted code start ticks q s := by
+ obtain ⟨d, hd, run⟩ := step_run code h
+ have hg := step_size code h
+ rw [Nat.succ_mul] at hclock
+ have h' := (run.allHalt (.ready start) (ticks-d)).mpr (ih _ (by omega) (by omega))
+ rwa [Nat.sub_add_cancel (by omega)] at h'
+
+/-- Lift the virtual all-path bound to the binary transition table. -/
+theorem physical_allHalt (t : ℕ) (q : Q) (s : Stacks (Fin k)) (B ticks : ℕ)
+ (stops : StopsWithin code t q s) (hsize : (packed s).length+t ≤ B)
+ (hclock : t*(6*B+4) ≤ ticks) : halted code start ticks q s := by
+ induction t generalizing q s ticks with
+ | zero => exact stops.elim
+ | succ t ih =>
+ cases h : code q with
+ | push i b r | pop i f | goto r =>
+ simp only [StopsWithin, h] at stops
+ apply allHalt_of_step code start _ (by omega) hclock (fun _ ↦ ih _ _ _ stops)
+ first | exact .push h | exact .pop h | exact .goto h
+ | choose low high =>
+ simp only [StopsWithin, h] at stops
+ rw [Nat.succ_mul] at hclock
+ obtain ⟨ticks, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : ticks ≠ 0)
+ apply (allHalt_step ..).mpr
+ simp only [rows, h, haltAfter, update_stay]
+ exact ⟨ih _ _ _ stops.1 (by omega) (by omega), ih _ _ _ stops.2 (by omega) (by omega)⟩
+ | halt b =>
+ rw [Nat.succ_mul] at hclock
+ obtain ⟨ticks, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : ticks ≠ 0)
+ apply (allHalt_step ..).mpr
+ simp [rows, h, haltAfter]
+
+/-- On the actual raw input, every branch of a named stack program has halted
+by the same quadratic clock used for its exact integer path count. -/
+theorem input_allHalt_labeled {K : Type*} [Fintype K] [DecidableEq K] (input : K)
+ (code : StackCode K Q) (start : Q) (raw : Word) (T ticks : ℕ)
+ (stops : StopsWithin code T start (labeledInput input raw))
+ (clock : T*(6*(raw.length+(Fintype.card K+1)+T)+4) ≤ ticks) :
+ let p := labeledProgram input code start
+ AllHalt p ticks (initial p raw) := by
+ have h := (stopsWithin_lift (target := labeledCode input code) (labeledPort input)
+ (labeledPort_injective input) id (inputStacks raw) (fun _ ↦ rfl) T start _).2 stops
+ rw [installedInput] at h
+ dsimp only
+ rw [physical_initial]
+ apply physical_allHalt _ start T start _ _ ticks h _ clock
+ simp [packed_input]
+
+end StackCompiler
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePhysicalInput.lean b/lean/OAI/Computability/VPVNP/RAMTapePhysicalInput.lean
new file mode 100644
index 0000000000..ffbe94a451
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePhysicalInput.lean
@@ -0,0 +1,178 @@
+import OAI.Computability.VPVNP.RAMTapeInputStartup
+import OAI.Computability.VPVNP.RAMTapeInputParameters
+
+/-!
+# Complete uniform finite-stack reader for a live site
+
+The only initially occupied stack contains the physical input. This fixed
+control measures its length, prepares the exact widths, and extracts the
+literal data fields. It retains the public length, address width, and bucket
+capacity in unary for the site's remaining computations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputReader
+
+open BurstRAM ProcessorInput RAMLayout UniversalMachine StackCompiler
+
+/-- Retained unary length and address-width tallies of the physical site reader. -/
+inductive Public where
+ | length | address
+ deriving DecidableEq
+
+instance : Fintype Public := derive_fintype% _
+
+/-- Complete reader bank combining parsing ports, parameter scratch, and the retained public
+tallies. -/
+abbrev Registers := InputPort ⊕ (InputParameters.Scratch ⊕ Public)
+
+/-- Port holding the measured length of the full physical input in unary. -/
+def lengthPort : Registers := .inr (.inr .length)
+/-- Port holding the computed site address width in unary. -/
+def addressWidthPort : Registers := .inr (.inr .address)
+/-- Port holding the computed bucket capacity in unary. -/
+def bucketPort : Registers := .inr (.inl .bucket)
+
+private abbrev ones (n : ℕ) := List.replicate n true
+
+private def corePort : InputPort ⊕ InputParameters.Scratch → Registers := Sum.elim Sum.inl (Sum.inr ∘ Sum.inl)
+
+private theorem core_injective : Function.Injective corePort := by
+ intro x y h
+ cases x <;> cases y <;> simp_all [corePort]
+
+private def decorate (core : Stacks (InputPort ⊕ InputParameters.Scratch)) (n d : ℕ) : Stacks Registers
+ | .inl i => core (.inl i)
+ | .inr (.inl i) => core (.inr i)
+ | .inr (.inr .length) => ones n
+ | .inr (.inr .address) => ones d
+
+private theorem decorate_core (s : Stacks (InputPort ⊕ InputParameters.Scratch)) (n d : ℕ)
+ (i : InputPort ⊕ InputParameters.Scratch) : decorate s n d (corePort i) = s i := by cases i <;> rfl
+
+private def savePort (p : Public) : Registers := .inr (.inr p)
+private def sourcePort : Public → InputPort
+ | .length => .size
+ | .address => .addressCount
+
+private def copyPorts (p : Public) : CeilLog.Port → Registers
+ | .src => .inl (sourcePort p)
+ | .out => savePort p
+ | .tmp => .inl .tmp
+
+private def retain (p : Public) : FiniteRoutine Registers :=
+ (FiniteRoutine.ofRoutine (Tally.copyAdd CeilLog.Port.src .out .tmp)).onPorts (copyPorts p)
+
+private theorem retain_run (p : Public) (s : Stacks Registers) (k : ℕ)
+ (hs : s (.inl (sourcePort p)) = ones k) (ht : s (.inl .tmp) = []) (ho : s (savePort p) = []) :
+ (retain p).Runs (5*k+2) s (Function.update s (savePort p) (ones k)) := by
+ let vals : Tally.State CeilLog.Port := fun i => if i = .src then k else 0
+ have run := Tally.copyAdd_runs CeilLog.Port.src .out .tmp (by decide) (by decide) (by decide) vals rfl
+ apply FiniteRoutine.runs_onPorts_framed _ (by intro i j hij; cases p <;> cases i <;> cases j <;> simp_all [copyPorts, sourcePort, savePort]) run
+ · intro i; cases i with
+ | src => exact hs
+ | tmp => exact ht
+ | out => exact ho
+ · intro i
+ cases i with
+ | src => simpa [copyPorts, savePort, vals, Tally.encode] using hs
+ | tmp => simpa [copyPorts, savePort, vals, Tally.encode] using ht
+ | out => simp [copyPorts, vals, Tally.encode, ones]
+ · intro i hi
+ exact Function.update_of_ne (Ne.symm (hi .out)) ..
+
+private def measure : FiniteRoutine Registers := (FiniteRoutine.ofRoutine lengthRoutine).onPorts Sum.inl
+private def fields : FiniteRoutine Registers := (FiniteRoutine.ofRoutine parse).onPorts Sum.inl
+
+/-- Code independent of the length. The rational exponent of the live bucket
+is `p/q` (in the paper, `1-δ`). -/
+def physicalReader (B p q : ℕ) (hq : 0 < q) : FiniteRoutine Registers :=
+ (((measure.followedBy (retain .length)).followedBy
+ ((InputParameters.routineKeep B p q hq).onPorts corePort)).followedBy (retain .address)).followedBy fields
+
+/-- All private scratch is empty at return. The length, address width and
+bucket capacity are available alongside the actual prefix and data fields. -/
+def physicalResult (n d H : ℕ) (pref addr hdr inc : List Bool) : Stacks Registers
+ | .inl .prefix => pref
+ | .inl .address => addr
+ | .inl .header => hdr
+ | .inl .incident => inc
+ | .inr (.inl .bucket) => ones H
+ | .inr (.inr .length) => ones n
+ | .inr (.inr .address) => ones d
+ | _ => []
+
+/-- From just the original site tape, the fixed processor obtains its local
+input with polynomially bounded bit-stack instructions. The public parameters
+are computed on its branch path from the length. -/
+theorem physicalReader_runs (B p q : ℕ) (hq : 0 < q) (hpq : p ≤ q) (prog : UniversalMachine.Program)
+ (n : ℕ) (hn : 1 ≤ n) :
+ let d := B * Nat.clog 2 n
+ let H := 2^(roundedUp p q n)
+ let w := (d+10)^4
+ ∀ (v : Fin (2^d)) (hdr : Header) (inc : Fin (width d H w) → Bool),
+ Fits prog n d H w →
+ let raw := ProcessorInput.tape prog n v hdr inc
+ ∃ steps ≤ (InputParameters.clockCoefficient B p q + 43)*(n+1)^7,
+ (physicalReader B p q hq).Runs steps (labeledInput (.inl InputPort.input) raw)
+ (physicalResult n d H (programPrefix prog) (List.ofFn (RAMSerialization.wordBits d v))
+ (List.ofFn hdr) (List.ofFn inc)) := by
+ intro d H w v hdr inc hf raw
+ let D := width d H w
+ let src := InputParameters.bank raw n 0 0 0 0
+ let dest := InputParameters.bank raw 0 0 d H D
+ have hlen : raw.length = n := ProcessorInput.length_tape prog v hdr inc hf
+ have hsmall := lengthRoutine_runs (prepared raw 0 0 []) rfl
+ change lengthRoutine.Runs (5*raw.length+2) _ (Function.update _ .size (ones raw.length ++ [])) at hsmall
+ rw [hlen, List.append_nil] at hsmall
+ have h₀ : measure.Runs (5*n+2) (labeledInput (.inl InputPort.input) raw) (decorate src 0 0) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective hsmall
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> rfl
+ · rintro (i | j) hh
+ · exact (hh i rfl).elim
+ · cases j with
+ | inl k => cases k <;> rfl
+ | inr k => cases k <;> rfl
+ have h₁ := retain_run .length (decorate src 0 0) n rfl rfl rfl
+ have e₁ : Function.update (decorate src 0 0) (savePort .length) (ones n) = decorate src n 0 := by
+ funext i; rcases i with i | (i | i) <;> first | rfl | cases i <;> rfl
+ rw [e₁] at h₁
+ obtain ⟨t, ht, hp⟩ := InputParameters.runs_keep B p q n hq hpq hn raw
+ have h₂ : ((InputParameters.routineKeep B p q hq).onPorts corePort).Runs t (decorate src n 0)
+ (decorate dest n 0) := by
+ apply FiniteRoutine.runs_onPorts_framed _ core_injective hp (decorate_core src n 0) (decorate_core dest n 0)
+ rintro (i | (i | i)) hh
+ · exact (hh (.inl i) rfl).elim
+ · exact (hh (.inr i) rfl).elim
+ · cases i <;> rfl
+ have h₃ := retain_run .address (decorate dest n 0) d rfl rfl rfl
+ have e₃ : Function.update (decorate dest n 0) (savePort .address) (ones d) = decorate dest n d := by
+ funext i; rcases i with i | (i | i) <;> first | rfl | cases i <;> rfl
+ rw [e₃] at h₃
+ obtain ⟨z, hz, hflds⟩ := parse_processorTape prog n v hdr inc [] hf
+ let target := physicalResult n d H (programPrefix prog) (List.ofFn (RAMSerialization.wordBits d v))
+ (List.ofFn hdr) (List.ofFn inc)
+ have h₄ : fields.Runs z (decorate dest n d) target := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective hflds
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> rfl
+ · rintro (i | (i | i)) hh
+ · exact (hh i rfl).elim
+ · cases i <;> rfl
+ · cases i <;> rfl
+ refine ⟨_, ?_, (((h₀.followedBy h₁).followedBy h₂).followedBy h₃).followedBy h₄⟩
+ have hd : d ≤ n := by change (programPrefix prog).length + (d + 4 + D) ≤ n at hf; omega
+ have hb := InputParameters.budget_le B p q n hq hpq hn
+ have hrest := Nat.mul_le_mul_left 43 (Nat.le_self_pow (by decide : 7 ≠ 0) (n+1))
+ rw [Nat.add_mul]
+ omega
+
+end RAMTape.InputReader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePrivateISABank.lean b/lean/OAI/Computability/VPVNP/RAMTapePrivateISABank.lean
new file mode 100644
index 0000000000..6983848016
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePrivateISABank.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.RAMTapeISAPorts
+
+/-!
+# Staging registers on the private-log ports
+
+The private load and store routines share two staging words. All remaining
+architectural ports retain their values while the log kernel is running.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open BurstRAM PrivateRAM
+
+variable {w r k : ℕ}
+
+/-- A bank in which the query and output log ports are occupied. -/
+def stagedBank (pub : Fin k → Word w) (persistent : Word w) (reg : Fin r → Word w)
+ (log : WriteLog w) (query out : List Bool) : Stacks (Port r k)
+ | .logPort .query => query
+ | .logPort .out => out
+ | port => bank pub persistent reg log port
+
+@[simp] theorem stagedBank_empty (pub : Fin k → Word w) (s : Word w) (reg : Fin r → Word w)
+ (log : WriteLog w) : stagedBank pub s reg log [] [] = bank pub s reg log := by
+ funext j
+ cases j with
+ | logPort j => cases j <;> rfl
+ | _ => rfl
+
+theorem stagedBank_update_query (pub : Fin k → Word w) (s : Word w) (reg : Fin r → Word w)
+ (log : WriteLog w) (query out x : List Bool) :
+ Function.update (stagedBank pub s reg log query out) (.logPort .query) x =
+ stagedBank pub s reg log x out := by
+ funext j
+ cases j with
+ | logPort j => cases j <;> rfl
+ | _ => rfl
+
+theorem stagedBank_update_out (pub : Fin k → Word w) (s : Word w) (reg : Fin r → Word w)
+ (log : WriteLog w) (query out x : List Bool) :
+ Function.update (stagedBank pub s reg log query out) (.logPort .out) x =
+ stagedBank pub s reg log query x := by
+ funext j
+ cases j with
+ | logPort j => cases j <;> rfl
+ | _ => rfl
+
+theorem stagedBank_update_reg (pub : Fin k → Word w) (s : Word w) (reg : Fin r → Word w)
+ (log : WriteLog w) (query out : List Bool) (i : Fin r) (v : Word w) :
+ Function.update (stagedBank pub s reg log query out) (.reg i) (wordBits v) =
+ stagedBank pub s (Function.update reg i v) log query out := by
+ funext j
+ cases j with
+ | reg j => by_cases h : j = i <;> simp [stagedBank, bank, h]
+ | logPort j => cases j <;> rfl
+ | _ => rfl
+
+theorem logPort_injective : Function.Injective (@Port.logPort r k) := fun _ _ => Port.logPort.inj
+
+/-- Installing the ten streams of a native log routine replaces precisely
+the staged query, output, and log. The ambient registers are preserved. -/
+theorem install_logBank (pub : Fin k → Word w) (s : Word w) (reg : Fin r → Word w)
+ (baseLog : WriteLog w) (a : Word w) (out : List Bool) (log : WriteLog w) :
+ installStacks Port.logPort (bank pub s reg baseLog) (AddressLog.bank a out log).stacks =
+ stagedBank pub s reg log (wordBits a) out := by
+ funext j
+ cases j with
+ | logPort j =>
+ rw [installStacks_at logPort_injective]
+ cases j <;> rfl
+ | reg | pub | persistent | work =>
+ rw [installStacks_outside _ _ (by simp)]
+ rfl
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePrivateISAKernels.lean b/lean/OAI/Computability/VPVNP/RAMTapePrivateISAKernels.lean
new file mode 100644
index 0000000000..68734f2e9f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePrivateISAKernels.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.RAMTapePrivateISABank
+import OAI.Computability.VPVNP.RAMTapeAddressLogLoad
+import OAI.Computability.VPVNP.RAMTapeAddressLogStore
+
+/-!
+# Private load and store kernels in the RAM instruction bank
+
+The log's ten native ports are installed in the architectural bank. A normal
+completion returns directly to the caller with the two operand ports staged.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open BurstRAM PrivateRAM
+
+variable {w r k : ℕ}
+
+/-- Scan the private log for a staged address. -/
+def logLoad : FiniteRoutine (Port r k) :=
+ FiniteRoutine.ofStackCode AddressLog.loadCode Port.logPort .record (fun q => decide (q = .done))
+
+/-- Add the staged address and value to the head of the private log. -/
+def logStore : FiniteRoutine (Port r k) :=
+ FiniteRoutine.ofStackCode AddressLog.storeCode Port.logPort .readKey (fun q => decide (q = .done))
+
+theorem logLoad_run (pub : Fin k → Word w) (s : Word w) (reg : Fin r → Word w) (log : WriteLog w)
+ (a : Word w) :
+ logLoad.Runs (AddressLog.loadCost a log) (stagedBank pub s reg log (wordBits a) [])
+ (stagedBank pub s reg log (wordBits a) (wordBits (WriteLog.memory log a))) := by
+ have run := FiniteRoutine.runs_ofStackCode logPort_injective
+ (normal := fun q : AddressLog.State => decide (q = .done)) rfl rfl
+ (fun q h => by obtain rfl := of_decide_eq_true h; rfl) (bank pub s reg log)
+ (AddressLog.load_run a [] log)
+ simpa only [logLoad, install_logBank, List.append_nil] using run
+
+theorem logStore_run (pub : Fin k → Word w) (s : Word w) (reg : Fin r → Word w) (log : WriteLog w)
+ (a v : Word w) :
+ logStore.Runs (10 * w + 3) (stagedBank pub s reg log (wordBits a) (wordBits v))
+ (stagedBank pub s reg ((a, v) :: log) (wordBits a) (wordBits v)) := by
+ have run := FiniteRoutine.runs_ofStackCode logPort_injective
+ (normal := fun q : AddressLog.StoreState => decide (q = .done)) rfl rfl
+ (fun q h => by obtain rfl := of_decide_eq_true h; rfl) (bank pub s reg log)
+ (AddressLog.store_run a v log)
+ simpa only [logStore, install_logBank] using run
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePrivateISALoad.lean b/lean/OAI/Computability/VPVNP/RAMTapePrivateISALoad.lean
new file mode 100644
index 0000000000..98d6821025
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePrivateISALoad.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.RAMTapePrivateISAKernels
+import OAI.Computability.VPVNP.RAMTapeISAOperand
+
+/-!
+# Lowering the private-load opcode to finite stack control
+
+The first copy stages the complete address before the destination register is
+overwritten. This also implements loads whose address and destination are the
+same register. The write log is restored by its kernel and the two staging
+ports are emptied before returning to the instruction dispatcher.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open BurstRAM PrivateRAM
+
+variable {r k w p : ℕ}
+
+/-- Stage the address before overwriting the destination, look it up in the private write log,
+copy the result to the destination, and clear both staging stacks. -/
+def loadPrivate (dst addr : Fin r) : FiniteRoutine (Port r k) :=
+ (((loadOperand (.reg addr) (.logPort .query)).followedBy logLoad).followedBy
+ (loadOperand (.logPort .out) (.reg dst))).followedBy
+ ((clearPort (.logPort .query)).followedBy (clearPort (.logPort .out)))
+
+theorem loadPrivate_run (dst addr : Fin r) (pub : Fin k → Word w) (s : Word w)
+ (reg : Fin r → Word w) (log : WriteLog w) :
+ (loadPrivate dst addr).Runs (17*w + 8 + AddressLog.loadCost (reg addr) log)
+ (bank pub s reg log) (bank pub s (Function.update reg dst (WriteLog.memory log (reg addr))) log) := by
+ let a := reg addr
+ let v := WriteLog.memory log a
+ let reg' := Function.update reg dst v
+ let stage := stagedBank pub s reg log
+ let post := stagedBank pub s reg' log
+ have address : (loadOperand (.reg addr) (.logPort .query)).Runs (7*w+3)
+ (stage [] []) (stage (wordBits a) []) := by
+ have h := loadOperand_runs (src := .reg addr) (dst := .logPort .query)
+ (by simp) (by simp [copySafe]) (by simp [copySafe]) (stage [] []) rfl rfl
+ change (loadOperand _ _).Runs (0 + 7*(wordBits a).length + 3) _
+ (Function.update (stagedBank pub s reg log [] []) (.logPort .query) (wordBits a)) at h
+ simpa only [Nat.zero_add, length_wordBits, stagedBank_update_query] using h
+ have readValue : logLoad.Runs (AddressLog.loadCost a log) (stage (wordBits a) [])
+ (stage (wordBits a) (wordBits v)) := logLoad_run pub s reg log a
+ have writeReg : (loadOperand (.logPort .out) (.reg dst)).Runs (8*w+3)
+ (stage (wordBits a) (wordBits v)) (post (wordBits a) (wordBits v)) := by
+ have h := loadOperand_runs (src := .logPort .out) (dst := .reg dst)
+ (by simp) (by simp [copySafe]) (by simp [copySafe]) (stage (wordBits a) (wordBits v)) rfl rfl
+ change (loadOperand _ _).Runs ((wordBits (reg dst)).length + 7*(wordBits v).length + 3) _
+ (Function.update (stagedBank pub s reg log (wordBits a) (wordBits v)) (.reg dst) (wordBits v)) at h
+ rw [stagedBank_update_reg, length_wordBits, length_wordBits] at h
+ exact (show w + 7*w + 3 = 8*w + 3 by omega) ▸ h
+ have clearAddress : (clearPort (.logPort .query)).Runs (w+1)
+ (post (wordBits a) (wordBits v)) (post [] (wordBits v)) := by
+ have h := clearPort_runs (.logPort .query) (post (wordBits a) (wordBits v))
+ change (clearPort _).Runs ((wordBits a).length + 1) _
+ (Function.update (stagedBank pub s reg' log (wordBits a) (wordBits v)) (.logPort .query) []) at h
+ simpa only [length_wordBits, stagedBank_update_query] using h
+ have clearValue : (clearPort (.logPort .out)).Runs (w+1) (post [] (wordBits v)) (post [] []) := by
+ have h := clearPort_runs (.logPort .out) (post [] (wordBits v))
+ change (clearPort _).Runs ((wordBits v).length + 1) _
+ (Function.update (stagedBank pub s reg' log [] (wordBits v)) (.logPort .out) []) at h
+ simpa only [length_wordBits, stagedBank_update_out] using h
+ have h := ((address.followedBy readValue).followedBy writeReg).followedBy (clearAddress.followedBy clearValue)
+ rw [show (7*w+3+AddressLog.loadCost a log+(8*w+3))+(w+1+(w+1)) =
+ 17*w+8+AddressLog.loadCost a log by omega] at h
+ simpa only [loadPrivate, stage, post, reg', a, v, stagedBank_empty] using h
+
+/-- For an arbitrary private configuration the physical load realizes the
+exact private continuation of the opcode. -/
+theorem loadPrivate_config_run (dst addr : Fin r) (next : Fin p) (pub : Fin k → Word w)
+ (c : LogConfig w p r) :
+ ∃ c' : LogConfig w p r,
+ (Instr.loadPrivate dst addr next).runLogged pub c = .localStep c' ∧
+ (loadPrivate dst addr).Runs (17*w + 8 + AddressLog.loadCost (c.reg addr) c.writes)
+ (configBank pub c) (configBank pub c') := by
+ refine ⟨{c with pc := next, reg := Function.update c.reg dst (WriteLog.memory c.writes (c.reg addr))}, rfl, ?_⟩
+ exact loadPrivate_run dst addr pub c.persistent c.reg c.writes
+
+/-- Uniform bound in the width and number of writes. No step loops over the
+numeric value of the address. -/
+theorem loadPrivate_cost_le (a : Word w) (log : WriteLog w) :
+ 17*w + 8 + AddressLog.loadCost a log ≤ (13*w+6)*log.length + 24*w + 15 := by
+ have h := AddressLog.loadCost_le a log
+ omega
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePrivateISAStore.lean b/lean/OAI/Computability/VPVNP/RAMTapePrivateISAStore.lean
new file mode 100644
index 0000000000..4b9faf8fa4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePrivateISAStore.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.RAMTapePrivateISAKernels
+import OAI.Computability.VPVNP.RAMTapeISAOperand
+
+/-!
+# A private store on the architectural stack bank
+
+The instruction copies the address and the value from the architectural
+registers, prepends their bits to the private log, and clears the two staging
+ports. Since each operand copy restores its source, one register may supply
+both operands.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open BurstRAM PrivateRAM
+
+variable {w r k : ℕ}
+
+/-- Execute the private store with its two source registers fixed by the
+instruction table. -/
+def storePrivate (addr src : Fin r) : FiniteRoutine (Port r k) :=
+ (loadOperand (.reg addr) (.logPort .query)).followedBy <|
+ (loadOperand (.reg src) (.logPort .out)).followedBy <|
+ logStore.followedBy <|
+ (clearPort (.logPort .query)).followedBy (clearPort (.logPort .out))
+
+/-- The newest write extends the private log and the instruction returns
+with an empty workspace. The instruction count is independent of the old
+log length and of the address stored in the register. -/
+theorem storePrivate_run (addr src : Fin r) (pub : Fin k → Word w) (persistent : Word w)
+ (reg : Fin r → Word w) (log : WriteLog w) :
+ (storePrivate (k := k) addr src).Runs (26 * w + 11)
+ (bank pub persistent reg log)
+ (bank pub persistent reg ((reg addr, reg src) :: log)) := by
+ let a := reg addr
+ let v := reg src
+ let after := (a, v) :: log
+ let staged := stagedBank pub persistent reg
+ have h₁ := loadOperand_runs (src := Port.reg addr) (dst := .logPort .query)
+ (by simp) (by simp [copySafe]) (by simp [copySafe]) (staged log [] []) rfl rfl
+ change (loadOperand _ _).Runs (0 + 7 * (wordBits a).length + 3) (staged log [] [])
+ (Function.update (staged log [] []) (.logPort .query) (wordBits a)) at h₁
+ simp only [staged, stagedBank_update_query, Nat.zero_add, length_wordBits] at h₁
+ have h₂ := loadOperand_runs (src := Port.reg src) (dst := .logPort .out)
+ (by simp) (by simp [copySafe]) (by simp [copySafe]) (staged log (wordBits a) []) rfl rfl
+ change (loadOperand _ _).Runs (0 + 7 * (wordBits v).length + 3) (staged log (wordBits a) [])
+ (Function.update (staged log (wordBits a) []) (.logPort .out) (wordBits v)) at h₂
+ simp only [staged, stagedBank_update_out, Nat.zero_add, length_wordBits] at h₂
+ have h₃ := logStore_run pub persistent reg log a v
+ have h₄ := clearPort_runs (Port.logPort .query) (staged after (wordBits a) (wordBits v))
+ change (clearPort _).Runs ((wordBits a).length + 1) _
+ (Function.update (staged after (wordBits a) (wordBits v)) (.logPort .query) []) at h₄
+ simp only [staged, stagedBank_update_query, length_wordBits] at h₄
+ have h₅ := clearPort_runs (Port.logPort .out) (staged after [] (wordBits v))
+ change (clearPort _).Runs ((wordBits v).length + 1) _
+ (Function.update (staged after [] (wordBits v)) (.logPort .out) []) at h₅
+ simp only [staged, stagedBank_update_out, length_wordBits] at h₅
+ have run := h₁.followedBy (h₂.followedBy (h₃.followedBy (h₄.followedBy h₅)))
+ rw [show 7 * w + 3 + (7 * w + 3 + (10 * w + 3 + (w + 1 + (w + 1)))) = 26 * w + 11 by omega] at run
+ simpa only [stagedBank_empty, storePrivate] using run
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeProcessorPublic.lean b/lean/OAI/Computability/VPVNP/RAMTapeProcessorPublic.lean
new file mode 100644
index 0000000000..31e8d1cc78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeProcessorPublic.lean
@@ -0,0 +1,261 @@
+import OAI.Computability.VPVNP.RAMTapeSiteFuel
+import OAI.Computability.VPVNP.RAMTapeSiteLiteral
+import OAI.Computability.VPVNP.RAMTapeValidatorSetup
+import OAI.Computability.VPVNP.RAMTapeSuccessorParameters
+import OAI.Computability.VPVNP.RAMTapeSiteEndpoints
+
+/-!
+# Public registers of the fixed site processor
+
+The fields produced by the physical reader share a bank with the cost endpoints
+and three instruction tallies. All routines use four temporary stacks in common.
+Their finite tables depend only on the processor's fixed parameters.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ProcessorPublic
+
+open BurstRAM ProcessorInput RAMLayout StackCompiler TapeWord
+
+/-- Additional processor registers for fuel, credits, choice bounds, costs, initial-record
+words, and four scratch stacks. -/
+inductive Extra where
+ | fuel | callCredit | choiceBudget | bucketLog | globalCap | startCost | endCost | initial
+ | addressWord | headerWord | scratch (i : Fin 4)
+ deriving DecidableEq
+
+instance : Fintype Extra := derive_fintype% _
+/-- Combined site-setup ports and the additional public processor registers. -/
+abbrev Port := SiteSetup.Port ⊕ Extra
+
+/-- Input stack carrying the physical site tape before parsing. -/
+def rawPort : Port := .inl SiteSetup.rawPort
+/-- Unary per-call private instruction allowance. -/
+def fuelPort : Port := .inr .fuel
+/-- Unary call credits prepared from the site’s bucket capacity. -/
+def creditPort : Port := .inr .callCredit
+/-- Unary upper bound on the length of the site’s private choice string. -/
+def budgetPort : Port := .inr .choiceBudget
+/-- Word encoding the global cumulative-cost cap. -/
+def capPort : Port := .inr .globalCap
+/-- Word encoding the beginning of the site’s cost interval. -/
+def startPort : Port := .inr .startCost
+/-- Word encoding the end of the site’s cost interval. -/
+def endPort : Port := .inr .endCost
+/-- Word holding the validator’s fixed initial-state literal. -/
+def initPort : Port := .inr .initial
+/-- Padded word containing the site address for the initial record. -/
+def addressWordPort : Port := .inr .addressWord
+/-- Padded word containing the four header bits for the initial record. -/
+def headerWordPort : Port := .inr .headerWord
+/-- Unary width of each word in the physical RAM records. -/
+def widthPort : Port := .inl SiteSetup.wordPort
+/-- Retained unary length of the original input tape. -/
+def lengthPort : Port := .inl (.inl InputReader.lengthPort)
+/-- Retained unary address width of the site. -/
+def addressWidthPort : Port := .inl (.inl InputReader.addressWidthPort)
+/-- Retained unary capacity of a site’s cost bucket. -/
+def bucketPort : Port := .inl (.inl InputReader.bucketPort)
+/-- Stack carrying the parsed site-address bits. -/
+def addressPort : Port := .inl (.inl (.inl .address))
+/-- Stack carrying the four parsed header bits. -/
+def headerPort : Port := .inl (.inl (.inl .header))
+/-- Stack carrying the parsed incident vector. -/
+def incidentPort : Port := .inl (.inl (.inl .incident))
+/-- Stack holding the binary logarithm of the power-of-two bucket capacity in unary. -/
+def bucketLogPort : Port := .inr .bucketLog
+
+private def fuelPorts : SiteFuel.Port → Port
+ | .length => lengthPort
+ | .bucket => bucketPort
+ | .word => widthPort
+ | .fuel => fuelPort
+ | .credit => creditPort
+ | .choice => budgetPort
+ | .acc => .inr (.scratch 0)
+ | .sum => .inr (.scratch 1)
+ | .outer => .inr (.scratch 2)
+ | .tmp => .inr (.scratch 3)
+
+private def capPorts : SuccessorParameters.Port → Port
+ | .siteLog => addressWidthPort
+ | .bucket => bucketPort
+ | .width => widthPort
+ | .bucketLog => bucketLogPort
+ | .cap => capPort
+ | .work => .inr (.scratch 0)
+ | .tmp => .inr (.scratch 1)
+
+private def endpointPorts : SiteEndpoints.Port → Port
+ | .address => addressPort
+ | .siteLog => addressWidthPort
+ | .bucketLog => bucketLogPort
+ | .width => widthPort
+ | .startCost => startPort
+ | .endCost => endPort
+ | .count => .inr (.scratch 0)
+ | .tmp => .inr (.scratch 1)
+
+private def literalPorts : ScanPort → Port
+ | .left => .inl SiteSetup.zerosPort
+ | .right => .inr (.scratch 0)
+ | .tmp => .inr (.scratch 1)
+ | .out => initPort
+
+private theorem fuelPorts_inj : Function.Injective fuelPorts := by decide
+private theorem capPorts_inj : Function.Injective capPorts := by decide
+private theorem endpointPorts_inj : Function.Injective endpointPorts := by decide
+private theorem literalPorts_inj : Function.Injective literalPorts := by decide
+
+private def fueled (base : Stacks SiteSetup.Port) (n H w u : ℕ) : Stacks Port
+ | .inl j => base j
+ | .inr .fuel => List.replicate (n^u) true
+ | .inr .callCredit => List.replicate (2*H-1) true
+ | .inr .choiceBudget => List.replicate (2*H*(n^u+w)) true
+ | _ => []
+
+private def capped (base : Stacks SiteSetup.Port) (n d e w u : ℕ) (h : d+e []))
+ (result base n d e w u lit v h) := by
+ have h₁ : (fuel u).Runs ((SiteFuel.program u).work (SiteFuel.initial n (2^e) w))
+ (Sum.elim base (fun _ => [])) (fueled base n (2^e) w u) := by
+ apply FiniteRoutine.runs_onPorts_framed _ fuelPorts_inj (SiteFuel.runs n (2^e) w u)
+ · intro j; cases j <;> first | rfl | exact hn | exact hH | exact hw
+ · intro j; cases j <;> first | rfl | exact hn | exact hH | exact hw
+ · rintro (i | j) hi
+ · rfl
+ · cases j <;> first | rfl | exact (hi .fuel rfl).elim | exact (hi .credit rfl).elim |
+ exact (hi .choice rfl).elim
+ have h₂ := SuccessorParameters.prepare_onPorts_runs capPorts capPorts_inj
+ (fueled base n (2^e) w u) d e w h (by intro j; cases j <;> first | rfl | exact hd | exact hH | exact hw)
+ have h₃ := SiteEndpoints.prepare_runs endpointPorts endpointPorts_inj (capped base n d e w u h)
+ v e w h hv hd rfl hw rfl rfl rfl rfl
+ have h₄ := SiteLiteral.runs lit literalPorts literalPorts_inj (costed base n d e w u v h) (0 : Word w)
+ (hz.trans (UnaryWord.zeros_wordBits w)) rfl rfl
+ rw [show (costed base n d e w u v h (literalPorts .out)).length = 0 from rfl, Nat.zero_add] at h₄
+ exact ((h₁.followedBy h₂).followedBy h₃).followedBy h₄
+
+theorem steps_le (n d e w u : ℕ) (h : d+e [])) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective run
+ · intro j; simp [labeledInput, raw, rawPort]
+ · intro j; rfl
+ · rintro (i | j) hi
+ · exact (hi i rfl).elim
+ · rfl
+ have h₂ := parameters_runs base n d e w u lit v hcap rfl rfl rfl rfl rfl rfl
+ refine ⟨_, ?_, h₁.followedBy h₂⟩
+ have hw : w ≤ n := by
+ change (UniversalMachine.programPrefix prog).length + (d + 4 + width d (2^e) w) ≤ n at fit
+ rw [width_eq] at fit
+ omega
+ have hh := steps_le n d e w u hcap hu (InputBucketFromSize.bucket_le hq hpq hn) hw
+ unfold clockCoefficient
+ rw [Nat.add_mul]
+ exact Nat.add_le_add (ht.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (Nat.succ_pos n) (le_max_left ..))))
+ (hh.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (Nat.succ_pos n) (le_max_right ..))))
+
+end RAMTape.ProcessorPublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeProcessorStartup.lean b/lean/OAI/Computability/VPVNP/RAMTapeProcessorStartup.lean
new file mode 100644
index 0000000000..54491aaeef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeProcessorStartup.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.RAMTapeProcessorPublic
+import OAI.Computability.VPVNP.RAMTapeSiteRecordWords
+
+/-!
+# Preparing the live processor's public bank and initial-record words
+
+Starting with only the raw site input, the program parses its literal prefix and fields,
+computes the public bounds and the two cost endpoints, and zero-extends the parsed address
+and four header bits into the two words used by the initial memory record.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ProcessorPublic
+
+open BurstRAM ProcessorInput RAMLayout StackCompiler
+
+private def recordPorts : SiteRecordWords.Port → Port
+ | .address => addressPort
+ | .header => headerPort
+ | .siteLog => addressWidthPort
+ | .width => widthPort
+ | .addressWord => addressWordPort
+ | .headerWord => headerWordPort
+ | .count => .inr (.scratch 0)
+ | .tmp => .inr (.scratch 1)
+
+private theorem recordPorts_inj : Function.Injective recordPorts := by decide
+
+/-- The two record words occupy their dedicated stacks in the prepared bank. -/
+def recordResult (base : Stacks SiteSetup.Port) (n d e w u lit : ℕ) (v : Word d) (hdr : Header)
+ (hcap : d+e List.replicate (n^u) true
+ | .callCredit => List.replicate (2 * 2^e - 1) true
+ | .choiceBudget => List.replicate (2 * 2^e * (n^u+w)) true
+ | .bucketLog => List.replicate e true
+ | .globalCap => BurstRAM.wordBits (SuccessorParameters.capWord d e w hcap)
+ | .startCost => BurstRAM.wordBits (SiteEndpoints.startWord e w v hcap)
+ | .endCost => BurstRAM.wordBits (SiteEndpoints.endWord e w v hcap)
+ | .initial => BurstRAM.wordBits (Fin.ofNat (2^w) lit)
+ | .addressWord => BurstRAM.wordBits (SiteRecordWords.addressWord (by omega : d≤w) v)
+ | .headerWord => BurstRAM.wordBits (headerWord hw hdr)
+ | .scratch _ => [] := by cases i <;> rfl
+
+end Projections
+
+/-- Fixed processor preparation, including both words of the initial record. -/
+def recordStartup (B p q u lit : ℕ) (hq : 0 < q) : FiniteRoutine Port :=
+ (startup B p q u lit hq).followedBy (SiteRecordWords.prepare recordPorts)
+
+/-- Clock coefficient for public startup including preparation of the initial record’s address
+and header words. -/
+def recordClockCoefficient (B p q u : ℕ) := clockCoefficient B p q u + 89
+
+theorem recordWidth_ge_four (d : ℕ) : 4 ≤ (d+10)^4 :=
+ (show 4 ≤ d+10 by omega).trans (Nat.le_self_pow (by decide) _)
+
+set_option maxHeartbeats 1000000 in
+/-- The only initially occupied stack carries the complete input, including the program prefix.
+On return all parsed fields, cost and fuel registers, and initial-record words are present. -/
+theorem recordStartup_runs (B p q u lit : ℕ) (hB : 1 ≤ B) (hq : 0 < q) (hpq : p ≤ q) (hu : 1 ≤ u)
+ (prog : UniversalMachine.Program) (n : ℕ) (hn : 1 ≤ n) :
+ let d := B * Nat.clog 2 n
+ let e := roundedUp p q n
+ let w := (d+10)^4
+ ∀ (v : Word d) (hdr : Header) (inc : Fin (width d (2^e) w) → Bool),
+ Fits prog n d (2^e) w →
+ ∃ t ≤ recordClockCoefficient B p q u * (n+1)^(max 7 (u+1)),
+ (recordStartup B p q u lit hq).Runs t (labeledInput rawPort (ProcessorInput.tape prog n v hdr inc))
+ (recordResult (rawResult prog n d (2^e) w v hdr inc) n d e w u lit v hdr
+ (capFits B p q n hB hq hpq hn) (recordWidth_ge_four d)) := by
+ intro d e w v hdr inc fit
+ let hcap := capFits B p q n hB hq hpq hn
+ have hdw : d ≤ w := by change d+e < w at hcap; omega
+ have hw := recordWidth_ge_four d
+ let base := rawResult prog n d (2^e) w v hdr inc
+ obtain ⟨t, ht, run⟩ := startup_runs B p q u lit hB hq hpq hu prog n hn v hdr inc fit
+ have words := SiteRecordWords.prepare_runs recordPorts recordPorts_inj
+ (result base n d e w u lit v hcap) v hdr hdw hw rfl rfl rfl rfl rfl rfl rfl rfl
+ refine ⟨_, ?_, run.followedBy words⟩
+ have hsize : w ≤ n := by
+ change (UniversalMachine.programPrefix prog).length + (d + 4 + width d (2^e) w) ≤ n at fit
+ rw [width_eq] at fit
+ omega
+ have hpow : n+1 ≤ (n+1)^(max 7 (u+1)) := Nat.le_self_pow (by omega) _
+ have hcost := SiteRecordWords.steps_le hdw
+ unfold recordClockCoefficient
+ rw [Nat.add_mul]
+ exact Nat.add_le_add ht ((hcost.trans (by omega : 23*w+66 ≤ 89*(n+1))).trans
+ (Nat.mul_le_mul_left _ hpow))
+
+end RAMTape.ProcessorPublic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicExprArithmetic.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicExprArithmetic.lean
new file mode 100644
index 0000000000..9f1b3b79ce
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicExprArithmetic.lean
@@ -0,0 +1,179 @@
+import OAI.Computability.VPVNP.LivePublicExpr
+import OAI.Computability.VPVNP.RAMTapeISAComparison
+import OAI.Computability.VPVNP.RAMTapeWordISAStage
+
+/-! # Physical word operations for the length-only public expressions
+
+All arithmetic uses the fixed RAM word kernels. Natural subtraction tests
+the unsigned order first, since the expression language truncates at zero.
+Powers of two shift a literal unit and constant division uses the physical
+word divider.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicExprMachine
+
+open BurstRAM PrivateRAM LiveProgram
+
+/-- Represent a natural number as a word by reduction modulo two to the word width. -/
+abbrev packed (w n : ℕ) : Word w := Fin.ofNat (2^w) n
+
+/-- The four geometry inputs in register order, namely input length, site address width, bucket
+capacity, and RAM word width. -/
+def geometryNat (g : Geometry) : Fin 4 → ℕ := ![g.n, g.d, g.H, g.w]
+
+/-- Encode the selected geometry parameter at the RAM word width. -/
+def geometryWords (g : Geometry) (i : Fin 4) : Word g.w := packed g.w (geometryNat g i)
+
+theorem packed_val {w n : ℕ} (h : n < 2^w) : (packed w n).val = n := Nat.mod_eq_of_lt h
+
+variable {r k w : ℕ}
+
+/-- Copy one geometry word into an arithmetic register. -/
+def load (dst : Fin r) (i : Fin k) : FiniteRoutine (ISA.Port r k) :=
+ ISA.loadOperand (.pub i) (.reg dst)
+
+theorem load_runs (dst : Fin r) (i : Fin k) (pub : Fin k → Word w) (persist : Word w)
+ (rs : Fin r → Word w) (log : WriteLog w) :
+ (load dst i).Runs (8*w+3) (ISA.bank pub persist rs log)
+ (ISA.bank pub persist (Function.update rs dst (pub i)) log) := by
+ let s := ISA.bank pub persist rs log
+ have hr := ISA.loadOperand_runs (src := ISA.Port.pub i) (dst := .reg dst) (by simp)
+ (by simp [ISA.copySafe]) (by simp [ISA.copySafe]) s rfl rfl
+ change (load dst i).Runs ((wordBits (rs dst)).length + 7*(wordBits (pub i)).length+3)
+ s (Function.update s (.reg dst) (wordBits (pub i))) at hr
+ simpa only [length_wordBits, s, ISA.bank_updateReg, show w+7*w+3=8*w+3 by omega] using hr
+
+/-- Compare unsigned operands and return zero on underflow, otherwise compute their word
+difference. -/
+def subtract (dst a b : Fin r) : FiniteRoutine (ISA.Port r k) :=
+ (ISA.compareRegs .lt a b).followedBy (.ofRoutine (Routine.popCase (.work 0) (Routine.halt false)
+ (ISA.binary .sub dst a b).body (ISA.loadLiteral 0 dst).body))
+
+theorem subtract_runs (dst a b : Fin r) (pub : Fin k → Word w) (persist : Word w)
+ (rs : Fin r → Word w) (log : WriteLog w) :
+ ∃ t ≤ 150*(w+1)^2, (subtract dst a b).Runs t (ISA.bank pub persist rs log)
+ (ISA.bank pub persist (Function.update rs dst (packed w ((rs a).val-(rs b).val))) log) := by
+ let s := ISA.bank pub persist rs log
+ have cmp := ISA.compareRegs_run .lt a b pub persist rs log
+ let branch := Routine.popCase (ISA.Port.work 0) (Routine.halt false)
+ (ISA.binary (k := k) .sub dst a b).body (ISA.loadLiteral 0 dst).body
+ have back (bit : Bool) : Function.update (Function.update s (.work 0) [bit]) (.work 0) [] = s := by
+ rw [Function.update_idem]
+ exact Function.update_eq_self ..
+ by_cases h : (rs a).val < (rs b).val
+ · have hb : TapeWord.Comparison.Op.lt.eval (rs a) (rs b) = true := decide_eq_true h
+ rw [hb] at cmp
+ have val : (rs a).val - (rs b).val = 0 := Nat.sub_eq_zero_of_le h.le
+ rw [val]
+ have put := ISA.loadLiteral_run 0 dst pub persist rs log
+ have select : branch.Runs ((8*w+3)+1) (Function.update s (.work 0) [true]) _ :=
+ Routine.runs_popCase_true _ _ _ _ (Function.update_self ..) (by rw [back]; exact put)
+ refine ⟨_, ?_, FiniteRoutine.Runs.followedBy cmp (b := .ofRoutine branch) select⟩
+ nlinarith [Nat.zero_le (w*w)]
+ · have hb : TapeWord.Comparison.Op.lt.eval (rs a) (rs b) = false := decide_eq_false h
+ rw [hb] at cmp
+ obtain ⟨u, hu, hr⟩ := ISA.binary_runs .sub dst a b pub persist rs log
+ have he : BinaryOp.sub.eval (rs a) (rs b) = packed w ((rs a).val-(rs b).val) := by
+ apply Fin.ext
+ change ((2^w - (rs b).val + (rs a).val) % 2^w) = _
+ have hlt := (rs b).isLt
+ have hadd : 2^w - (rs b).val + (rs a).val = ((rs a).val-(rs b).val)+2^w := by omega
+ rw [hadd, Nat.add_mod_right]
+ rfl
+ rw [he] at hr
+ have select : branch.Runs (u+1) (Function.update s (.work 0) [false]) _ :=
+ Routine.runs_popCase_false _ _ _ _ (Function.update_self ..) (by rw [back]; exact hr)
+ refine ⟨_, ?_, FiniteRoutine.Runs.followedBy cmp (b := .ofRoutine branch) select⟩
+ nlinarith [Nat.zero_le (w*w)]
+
+/-- Binary operations of the public expression language, namely addition, truncated
+subtraction, and multiplication. -/
+inductive Arithmetic where | add | sub | mul
+ deriving DecidableEq
+
+/-- Interpret the binary operation on natural numbers, with subtraction truncated at zero. -/
+def Arithmetic.eval : Arithmetic → ℕ → ℕ → ℕ
+ | .add => (· + ·)
+ | .sub => (· - ·)
+ | .mul => (· * ·)
+
+/-- Compile the binary operation to a word routine, using an unsigned comparison for truncated
+subtraction. -/
+def Arithmetic.code (op : Arithmetic) (dst a b : Fin r) : FiniteRoutine (ISA.Port r k) :=
+ match op with
+ | .add => ISA.binary .add dst a b
+ | .sub => subtract dst a b
+ | .mul => ISA.binary .mul dst a b
+
+theorem Arithmetic.runs (op : Arithmetic) (dst a b : Fin r) (pub : Fin k → Word w)
+ (persist : Word w) (rs : Fin r → Word w) (log : WriteLog w) :
+ ∃ t ≤ 150*(w+1)^2, (op.code dst a b).Runs t (ISA.bank pub persist rs log)
+ (ISA.bank pub persist (Function.update rs dst (packed w (op.eval (rs a).val (rs b).val))) log) := by
+ cases op with
+ | add =>
+ obtain ⟨t, ht, hr⟩ := ISA.binary_runs .add dst a b pub persist rs log
+ exact ⟨t, ht.trans (Nat.mul_le_mul_right _ (by decide)), hr⟩
+ | sub => exact subtract_runs ..
+ | mul =>
+ obtain ⟨t, ht, hr⟩ := ISA.binary_runs .mul dst a b pub persist rs log
+ exact ⟨t, ht.trans (Nat.mul_le_mul_right _ (by decide)), hr⟩
+
+/-- Unary public-expression operations that need an auxiliary literal, namely division by a
+fixed natural and raising two to a power. -/
+inductive ConstantOp where
+ | divConst (denominator : ℕ)
+ | pow2
+
+/-- The auxiliary literal loaded for a constant operation, either its divisor or the unit to
+shift left. -/
+def ConstantOp.literal : ConstantOp → ℕ
+ | .divConst b => b
+ | .pow2 => 1
+
+/-- Interpret the fixed-divisor or power-of-two operation on a natural input. -/
+def ConstantOp.eval : ConstantOp → ℕ → ℕ
+ | .divConst b => (· / b)
+ | .pow2 => (2^·)
+
+/-- Load the auxiliary literal, then divide the destination word or shift a unit left by its
+value. -/
+def ConstantOp.code (op : ConstantOp) (dst tmp : Fin r) : FiniteRoutine (ISA.Port r k) :=
+ (ISA.loadLiteral op.literal tmp).followedBy (match op with
+ | .divConst _ => ISA.binary .div dst dst tmp
+ | .pow2 => ISA.binary .shiftLeft dst tmp dst)
+
+theorem ConstantOp.runs (op : ConstantOp) (dst tmp : Fin r) (hne : dst ≠ tmp)
+ (pub : Fin k → Word w) (persist : Word w) (rs : Fin r → Word w) (log : WriteLog w)
+ (hlit : op.literal < 2^w) (hout : op.eval (rs dst).val < 2^w) :
+ ∃ t ≤ 150*(w+1)^2, (op.code dst tmp).Runs t (ISA.bank pub persist rs log)
+ (ISA.bank pub persist (Function.update (Function.update rs tmp (packed w op.literal))
+ dst (packed w (op.eval (rs dst).val))) log) := by
+ let mid := Function.update rs tmp (packed w op.literal)
+ have load := ISA.loadLiteral_run op.literal tmp pub persist rs log
+ have htmp : (mid tmp).val = op.literal := by simp only [mid, Function.update_self, packed_val hlit]
+ have hdst : mid dst = rs dst := Function.update_of_ne hne ..
+ cases op with
+ | divConst b =>
+ obtain ⟨u, hu, hr⟩ := ISA.binary_runs .div dst dst tmp pub persist mid log
+ have he : BinaryOp.div.eval (mid dst) (mid tmp) = packed w ((rs dst).val / b) := by
+ simp only [BinaryOp.eval, hdst, htmp, ConstantOp.literal, packed]
+ rw [he] at hr
+ exact ⟨_, by nlinarith [Nat.zero_le (w*w)], FiniteRoutine.Runs.followedBy load hr⟩
+ | pow2 =>
+ have hexp : (rs dst).val < w := (Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp hout
+ obtain ⟨u, hu, hr⟩ := ISA.binary_runs .shiftLeft dst tmp dst pub persist mid log
+ have he : BinaryOp.shiftLeft.eval (mid tmp) (mid dst) = packed w (2^(rs dst).val) := by
+ simp only [BinaryOp.eval, hdst, hexp, ↓reduceIte, htmp, ConstantOp.literal, Nat.shiftLeft_eq,
+ Nat.one_mul, packed]
+ rw [he] at hr
+ exact ⟨_, by nlinarith [Nat.zero_le (w*w)], FiniteRoutine.Runs.followedBy load hr⟩
+
+end RAMTape.PublicExprMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicExprCompiler.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicExprCompiler.lean
new file mode 100644
index 0000000000..816b257cb6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicExprCompiler.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.RAMTapePublicExprComposition
+import OAI.Computability.VPVNP.RAMTapePublicExprLog
+
+/-! # A fixed finite stack program for every live public operand expression
+
+The syntax fixes the instruction table and the number of temporary registers.
+Word width and operand values come from the parsed geometry at execution time.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicExprMachine
+
+open BurstRAM PrivateRAM LiveProgram
+
+/-- Number of extra registers required above the result slot to evaluate an expression
+recursively. -/
+def extra : PublicExpr → ℕ
+ | .add a b | .sub a b | .mul a b => max (extra a) (extra b + 1)
+ | .divConst a _ | .pow2 a => max (extra a) 1
+ | .log2 a | .clog2 a => extra a
+ | _ => 0
+
+/-- Number of syntax-tree nodes, counting geometry parameters and literals as leaves. -/
+def nodes : PublicExpr → ℕ
+ | .add a b | .sub a b | .mul a b => nodes a + nodes b + 1
+ | .divConst a _ | .pow2 a | .log2 a | .clog2 a => nodes a + 1
+ | _ => 1
+
+/-- Compile the expression into a fixed register program that writes at its base and stages a
+binary right operand one register higher. -/
+def compile (r base : ℕ) : PublicExpr → FiniteRoutine (BankPort r)
+ | .lit n => ISA.loadLiteral n (addr r base)
+ | .n => load (addr r base) 0
+ | .d => load (addr r base) 1
+ | .H => load (addr r base) 2
+ | .w => load (addr r base) 3
+ | .add a b => combine .add base (compile r base a) (compile r (base+1) b)
+ | .sub a b => combine .sub base (compile r base a) (compile r (base+1) b)
+ | .mul a b => combine .mul base (compile r base a) (compile r (base+1) b)
+ | .divConst a n => constant (.divConst n) base (compile r base a)
+ | .pow2 a => constant .pow2 base (compile r base a)
+ | .log2 a => (compile r base a).followedBy (PublicExprLog.code false (addr r base))
+ | .clog2 a => (compile r base a).followedBy (PublicExprLog.code true (addr r base))
+
+/-- Quadratic step allowance for a single compiled expression node at the given word width. -/
+def nodeCost (w : ℕ) := 150*(w+1)^2
+
+private theorem logarithm_computes {g : Geometry} {r base x t : ℕ} (ceil : Bool)
+ {a : FiniteRoutine (BankPort r)} (hb : base ≤ r) (hx : x < 2^g.w)
+ (ha : Computes g r base x t a) :
+ Computes g r base (if ceil then Nat.clog 2 x else Nat.log 2 x) (t+nodeCost g.w)
+ (a.followedBy (PublicExprLog.code ceil (addr r base))) := by
+ intro p rs log
+ obtain ⟨u,hu,z,first,hz,keep⟩ := ha p rs log
+ obtain ⟨v,hv,hr⟩ := PublicExprLog.runs ceil (addr r base) (geometryWords g) p z log
+ have val : (z (addr r base)).val = x := hz ▸ packed_val hx
+ rw [val] at hr
+ refine ⟨_, Nat.add_le_add hu (hv.trans ?_), _, first.followedBy hr, Function.update_self .., ?_⟩
+ · exact Nat.mul_le_mul_right _ (by decide : 12 ≤ 150)
+ · intro i hi
+ rw [Function.update_of_ne (by intro he; rw [he, addr_val hb] at hi; omega), keep i hi]
+
+private theorem fits_value {g : Geometry} {e : PublicExpr} {n : ℕ} (h : e.Fits g n) : e.eval g < n := by
+ cases e <;> exact h.1
+
+theorem compile_computes (g : Geometry) (r base : ℕ) (e : PublicExpr)
+ (hr : base + extra e ≤ r) (hf : e.Fits g (2^g.w)) :
+ Computes g r base (e.eval g) (nodes e * nodeCost g.w) (compile r base e) := by
+ have hlinear : 8*g.w+3 ≤ nodeCost g.w := by unfold nodeCost; nlinarith [Nat.zero_le (g.w*g.w)]
+ induction e generalizing base with
+ | lit n =>
+ exact (literal_computes g base n (by simpa [extra] using hr)).mono (by simpa [nodes] using hlinear)
+ | n =>
+ exact (load_computes g base 0 (by simpa [extra] using hr)).mono (by simpa [nodes] using hlinear)
+ | d =>
+ exact (load_computes g base 1 (by simpa [extra] using hr)).mono (by simpa [nodes] using hlinear)
+ | H =>
+ exact (load_computes g base 2 (by simpa [extra] using hr)).mono (by simpa [nodes] using hlinear)
+ | w =>
+ exact (load_computes g base 3 (by simpa [extra] using hr)).mono (by simpa [nodes] using hlinear)
+ | add a b ha hb | sub a b ha hb | mul a b ha hb =>
+ simp only [extra] at hr
+ obtain ⟨_, hfa, hfb⟩ := hf
+ simp only [compile, nodes, Nat.add_mul, Nat.one_mul]
+ apply combine_computes g _ (by omega) (fits_value hfa) (fits_value hfb) (ha base (by omega) hfa) (hb (base+1) (by omega) hfb)
+ | divConst a n ha =>
+ simp only [extra] at hr
+ obtain ⟨hout, hfa, hlit⟩ := hf
+ simp only [compile, nodes, Nat.add_mul, Nat.one_mul]
+ exact constant_computes g (.divConst n) (by omega) (fits_value hfa) hlit hout (ha base (by omega) hfa)
+ | pow2 a ha =>
+ simp only [extra] at hr
+ obtain ⟨hout, hfa⟩ := hf
+ simp only [compile, nodes, Nat.add_mul, Nat.one_mul]
+ have hunit : 1 < 2^g.w := (Nat.one_le_two_pow (n := a.eval g)).trans_lt hout
+ exact constant_computes g .pow2 (by omega) (fits_value hfa) hunit hout (ha base (by omega) hfa)
+ | log2 a ha =>
+ obtain ⟨_, hfa⟩ := hf
+ simp only [compile, nodes, Nat.add_mul, Nat.one_mul]
+ exact logarithm_computes false (by simp only [extra] at hr; omega) (fits_value hfa) (ha base hr hfa)
+ | clog2 a ha =>
+ obtain ⟨_, hfa⟩ := hf
+ simp only [compile, nodes, Nat.add_mul, Nat.one_mul]
+ exact logarithm_computes true (by simp only [extra] at hr; omega) (fits_value hfa) (ha base hr hfa)
+
+end RAMTape.PublicExprMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicExprComposition.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicExprComposition.lean
new file mode 100644
index 0000000000..d7df88cfaa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicExprComposition.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.RAMTapePublicExprArithmetic
+
+/-! # Register allocation for nested public expressions
+
+An expression writes its result at its base register and uses only registers
+above that base for intermediate words. Computing a right operand one position
+higher therefore retains the already computed left operand.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicExprMachine
+
+open BurstRAM PrivateRAM LiveProgram
+
+variable {r : ℕ}
+
+/-- Interpret a natural base address in the finite bank of one more than the supplied register
+bound. -/
+def addr (r base : ℕ) : Fin (r+1) := Fin.ofNat (r+1) base
+
+theorem addr_val {base : ℕ} (hb : base ≤ r) : (addr r base).val = base :=
+ Nat.mod_eq_of_lt (by omega)
+
+/-- Arithmetic bank with the bounded register file and four public geometry words. -/
+abbrev BankPort (r : ℕ) := ISA.Port (r+1) 4
+
+/-- The routine writes the packed natural result at its base within the step budget, preserving
+all lower registers, public words, persistent state, and log. -/
+def Computes (g : Geometry) (r base value steps : ℕ) (routine : FiniteRoutine (BankPort r)) : Prop :=
+ ∀ (persist : Word g.w) (rs : Fin (r+1) → Word g.w) (log : WriteLog g.w),
+ ∃ t ≤ steps, ∃ out : Fin (r+1) → Word g.w,
+ routine.Runs t (ISA.bank (geometryWords g) persist rs log) (ISA.bank (geometryWords g) persist out log) ∧
+ out (addr r base) = packed g.w value ∧ ∀ i : Fin (r+1), i.val < base → out i = rs i
+
+theorem Computes.mono {g : Geometry} {base v m n : ℕ} {code : FiniteRoutine (BankPort r)}
+ (h : Computes g r base v m code) (hm : m ≤ n) : Computes g r base v n code := by
+ intro p rs log
+ obtain ⟨t, ht, rest⟩ := h p rs log
+ exact ⟨t, ht.trans hm, rest⟩
+
+private theorem below_ne {base : ℕ} (hb : base ≤ r) {i : Fin (r+1)} (hi : i.val < base) :
+ i ≠ addr r base := fun he => by rw [he, addr_val hb] at hi; omega
+
+theorem literal_computes (g : Geometry) (base n : ℕ) (hb : base ≤ r) :
+ Computes g r base n (8*g.w+3) (ISA.loadLiteral n (addr r base)) := by
+ intro p rs log
+ exact ⟨_, le_rfl, _, ISA.loadLiteral_run .., Function.update_self ..,
+ fun i hi => Function.update_of_ne (below_ne hb hi) ..⟩
+
+theorem load_computes (g : Geometry) (base : ℕ) (i : Fin 4) (hb : base ≤ r) :
+ Computes g r base (geometryNat g i) (8*g.w+3) (load (addr r base) i) := by
+ intro p rs log
+ exact ⟨_, le_rfl, _, load_runs .., Function.update_self ..,
+ fun j hj => Function.update_of_ne (below_ne hb hj) ..⟩
+
+/-- Sequence the two operand routines, then apply the binary word operation to the base
+register and its successor. -/
+def combine (op : Arithmetic) (base : ℕ) (a b : FiniteRoutine (BankPort r)) : FiniteRoutine (BankPort r) :=
+ (a.followedBy b).followedBy (op.code (addr r base) (addr r base) (addr r (base+1)))
+
+theorem combine_computes (g : Geometry) (op : Arithmetic) {base x y u v : ℕ}
+ {a b : FiniteRoutine (BankPort r)} (hb : base+1 ≤ r)
+ (hx : x < 2^g.w) (hy : y < 2^g.w)
+ (ha : Computes g r base x u a) (hc : Computes g r (base+1) y v b) :
+ Computes g r base (op.eval x y) (u+v+150*(g.w+1)^2) (combine op base a b) := by
+ intro p rs log
+ obtain ⟨t, ht, l, first, hl, kl⟩ := ha p rs log
+ obtain ⟨s, hs, z, second, hz, kz⟩ := hc p l log
+ obtain ⟨k, hk, applyOp⟩ := op.runs (addr r base) (addr r base) (addr r (base+1)) (geometryWords g) p z log
+ have old : z (addr r base) = packed g.w x := (kz _ (by rw [addr_val (by omega)]; omega)).trans hl
+ rw [old, hz, packed_val hx, packed_val hy] at applyOp
+ refine ⟨_, Nat.add_le_add (Nat.add_le_add ht hs) hk, _, (first.followedBy second).followedBy applyOp,
+ Function.update_self .., ?_⟩
+ intro i hi
+ rw [Function.update_of_ne (below_ne (by omega) hi), kz i (by omega), kl i hi]
+
+/-- Evaluate the operand, then run the constant operation with the next register as scratch. -/
+def constant (op : ConstantOp) (base : ℕ) (a : FiniteRoutine (BankPort r)) : FiniteRoutine (BankPort r) :=
+ a.followedBy (op.code (addr r base) (addr r (base+1)))
+
+theorem constant_computes (g : Geometry) (op : ConstantOp) {base x u : ℕ}
+ {a : FiniteRoutine (BankPort r)} (hb : base+1 ≤ r)
+ (hx : x < 2^g.w) (hlit : op.literal < 2^g.w) (hout : op.eval x < 2^g.w)
+ (ha : Computes g r base x u a) :
+ Computes g r base (op.eval x) (u+150*(g.w+1)^2) (constant op base a) := by
+ intro p rs log
+ obtain ⟨t, ht, l, first, hl, keep⟩ := ha p rs log
+ have val : (l (addr r base)).val = x := by rw [hl, packed_val hx]
+ have hdst : addr r base ≠ addr r (base+1) :=
+ below_ne hb (by rw [addr_val (by omega)]; omega)
+ obtain ⟨k,hk,hr⟩ := op.runs (addr r base) (addr r (base+1)) hdst (geometryWords g) p l log
+ hlit (val ▸ hout)
+ rw [val] at hr
+ refine ⟨_, Nat.add_le_add ht hk, _, first.followedBy hr, Function.update_self .., ?_⟩
+ intro i hi
+ rw [Function.update_of_ne (below_ne (by omega) hi), Function.update_of_ne (below_ne hb (by omega)), keep i hi]
+
+end RAMTape.PublicExprMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicExprLog.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicExprLog.lean
new file mode 100644
index 0000000000..6ecba32f5a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicExprLog.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.RAMTapePublicExprLogScan
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-! # Padded word code for the public grammar logarithms
+
+A single fixed control computes either binary logarithm in the destination
+register. After scanning the bits it converts at most `w` unary marks to a
+padded binary word by verified word increments. The other registers, public
+words, persistent word and private write log are preserved.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicExprLog
+
+open BurstRAM BurstRAM.PrivateRAM
+open UnaryWord (Port store)
+
+variable {r k w : ℕ}
+
+private def ports (dst : Fin r) : Port → ISA.Port r k
+ | .number => .reg dst
+ | .pending => .work 0
+ | .tmp => .work 1
+ | .src => .work 2
+ | .unit => .work 3
+
+private theorem ports_injective (dst : Fin r) : Function.Injective (ports (k := k) dst) := by
+ intro p q h
+ cases p <;> cases q <;> simp [ports] at h ⊢
+
+/-- In-place floor or ceiling binary logarithm; no auxiliary architectural
+register is required. -/
+def code (ceiling : Bool) (dst : Fin r) : FiniteRoutine (ISA.Port r k) :=
+ (FiniteRoutine.ofStackCode (scan ceiling) (ports dst) .reverse (· == .done)).followedBy
+ (FiniteRoutine.ofStackCode (UnaryWord.code 0) (ports dst) .count (· == .done))
+
+/-- Quadratic step bound for computing a floor or ceiling binary logarithm in a padded word. -/
+def bound (w : ℕ) := 12 * (w+1)^2
+
+theorem runs (ceiling : Bool) (dst : Fin r) (pub : Fin k → Word w) (persist : Word w)
+ (rs : Fin r → Word w) (log : WriteLog w) :
+ ∃ t ≤ bound w, (code ceiling dst).Runs t (ISA.bank pub persist rs log)
+ (ISA.bank pub persist (Function.update rs dst
+ (Fin.ofNat (2^w) (if ceiling then Nat.clog 2 (rs dst).val else Nat.log 2 (rs dst).val))) log) := by
+ let x := rs dst
+ let j := if ceiling then Nat.clog 2 x.val else Nat.log 2 x.val
+ let y := Fin.ofNat (2^w) j
+ let base := ISA.bank pub persist rs log
+ have hj : j ≤ w := by
+ cases ceiling with
+ | true => exact Nat.clog_le_of_le_pow x.isLt.le
+ | false =>
+ by_cases hz : x.val = 0
+ · simp [j, hz]
+ · exact (Nat.log_lt_of_lt_pow hz x.isLt).le
+ have hfit : j < 2^w := hj.trans_lt (Nat.lt_two_pow_self (n := w))
+ obtain ⟨t, ht, hscan⟩ := scan_runs ceiling (wordBits x)
+ simp only [length_wordBits, TapeWord.value_wordBits] at ht hscan
+ obtain ⟨res,hl,hv,hcount⟩ := UnaryWord.count_run 0 j [] (List.replicate w false) []
+ (by simpa only [UnaryWord.zeros_value, Nat.zero_add, List.length_replicate] using hfit)
+ simp only [List.length_replicate, UnaryWord.zeros_value, Nat.zero_add] at hl hv hcount
+ have he : res = wordBits y := TapeWord.eq_of_length_value (hl.trans (length_wordBits y).symm)
+ (by rw [hv, TapeWord.value_wordBits]; exact (Nat.mod_eq_of_lt hfit).symm)
+ rw [he] at hcount
+ have hp := ports_injective (k := k) dst
+ have first := FiniteRoutine.runs_ofStackCode hp (normal := (· == Phase.done)) rfl rfl
+ (fun q h => by simp only [beq_iff_eq] at h; subst q; rfl) base hscan
+ have second := FiniteRoutine.runs_ofStackCode hp (normal := (· == UnaryWord.Phase.done)) rfl rfl
+ (fun q h => by simp only [beq_iff_eq] at h; subst q; rfl) base hcount
+ have hi : installStacks (ports dst) base (store [] [] (wordBits x) [] []) = base := by
+ apply installStacks_eq hp
+ intro p
+ cases p <;> rfl
+ have ho : installStacks (ports dst) base (store [] [] (wordBits y) [] []) =
+ Function.update base (.reg dst) (wordBits y) := by
+ apply installStacks_frame hp
+ · intro p
+ cases p <;> simp [ports, store, base, ISA.bank]
+ · intro l h
+ exact Function.update_of_ne (h .number).symm ..
+ rw [hi] at first
+ rw [ho, ISA.bank_updateReg] at second
+ refine ⟨t+(j*(4*w+3)+1), ?_, first.followedBy second⟩
+ have hjw := Nat.mul_le_mul_right (4*w+3) hj
+ unfold bound
+ nlinarith only [hjw, ht, Nat.zero_le (w*w), Nat.zero_le w]
+
+end RAMTape.PublicExprLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicExprLogScan.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicExprLogScan.lean
new file mode 100644
index 0000000000..a98862f9cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicExprLogScan.lean
@@ -0,0 +1,144 @@
+import OAI.Computability.VPVNP.RAMTapePublicExprLogValue
+import OAI.Computability.VPVNP.RAMTapeUnaryWord
+
+/-! # Finite scan for the highest set bit of a word
+
+The scan reverses the input to inspect its most significant bit first. It emits a
+unary mark for each position below the first one. For a ceiling logarithm it adds
+a final mark exactly when some lower bit was set. Every consumed bit also allocates
+a zero in the eventual result register.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicExprLog
+
+open UnaryWord (Port store)
+open TapeWord
+
+/-- States for reversing the input word, locating its highest set bit, counting lower
+positions, and optionally rounding up. -/
+inductive Phase
+ | reverse | save (bit : Bool)
+ | leading | leadingZero | highZero
+ | lower (seen : Bool) | lowerZero (seen : Bool) | mark (seen : Bool)
+ | extra | done
+ deriving DecidableEq, Fintype
+
+/-- Scan from the highest bit, emit logarithm marks, and allocate zero bits for the result. In
+ceiling mode add a mark when a lower bit is set. -/
+def scan (ceiling : Bool) : StackCode Port Phase
+ | .reverse => .pop .number fun b ↦ b.elim .leading .save
+ | .save b => .push .tmp b .reverse
+ | .leading => .pop .tmp fun b ↦ b.elim .done fun d ↦ if d then .highZero else .leadingZero
+ | .leadingZero => .push .number false .leading
+ | .highZero => .push .number false (.lower false)
+ | .lower seen => .pop .tmp fun b ↦ b.elim (if ceiling && seen then .extra else .done)
+ (fun d ↦ .lowerZero (seen || d))
+ | .lowerZero seen => .push .number false (.mark seen)
+ | .mark seen => .push .pending true (.lower seen)
+ | .extra => .push .pending true .done
+ | .done => .halt true
+
+private abbrev zeros (n : ℕ) := List.replicate n false
+private abbrev marks (n : ℕ) := List.replicate n true
+
+private theorem upd (a x t v : List Bool) (k : Port) :
+ Function.update (store [] a x [] t) k v = match k with
+ | .src => store v a x [] t | .unit => store [] a x v t
+ | .pending => store [] v x [] t | .number => store [] a v [] t
+ | .tmp => store [] a x [] v := by
+ funext j
+ cases k <;> cases j <;> simp [store]
+
+local macro "log_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_) <;>
+ simp only [store, upd, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, Bool.false_eq_true, ↓reduceIte])
+
+private theorem reverse_run (c : Bool) (xs acc : List Bool) :
+ StackRuns (scan c) (2*xs.length+1) .reverse (store [] [] xs [] acc)
+ .leading (store [] [] [] [] (xs.reverse ++ acc)) := by
+ induction xs generalizing acc with
+ | nil => log_step; exact .nil ..
+ | cons b xs ih =>
+ rw [List.length_cons, Nat.mul_succ, show 2*xs.length+2+1 = (2*xs.length+1)+1+1 by omega]
+ log_step
+ log_step
+ simpa only [List.reverse_cons, List.append_assoc, List.singleton_append] using ih (b::acc)
+
+private theorem leading_run (c : Bool) (z n : ℕ) (xs : List Bool) :
+ StackRuns (scan c) (2*z) .leading (store [] [] (zeros n) [] (zeros z ++ xs))
+ .leading (store [] [] (zeros (n+z)) [] xs) := by
+ induction z generalizing n with
+ | zero => exact .nil ..
+ | succ z ih =>
+ rw [Nat.mul_succ]
+ change StackRuns _ _ _ (store [] [] _ [] (false :: (zeros z ++ xs))) _ _
+ log_step
+ log_step
+ simpa only [zeros, List.replicate_succ, show n+1+z = n+(z+1) by omega] using ih (n+1)
+
+private theorem lower_run (c seen : Bool) (xs : List Bool) (k n : ℕ) :
+ ∃ t ≤ 3*xs.length+2, StackRuns (scan c) t (.lower seen) (store [] (marks k) (zeros n) [] xs)
+ .done (store [] (marks (k + xs.length + (c && (seen || xs.contains true)).toNat))
+ (zeros (n+xs.length)) [] []) := by
+ induction xs generalizing seen k n with
+ | nil =>
+ cases c <;> cases seen
+ all_goals first
+ | exact ⟨1, by decide, by log_step; exact .nil ..⟩
+ | exact ⟨2, by decide, by log_step; log_step; exact .nil ..⟩
+ | cons b xs ih =>
+ obtain ⟨t, ht, hr⟩ := ih (seen || b) (k+1) (n+1)
+ refine ⟨t+1+1+1, by simp only [List.length_cons]; omega, ?_⟩
+ log_step
+ log_step
+ log_step
+ have hb : ((seen || b) || xs.contains true) = (seen || (b::xs).contains true) := by
+ cases seen <;> cases b <;> simp
+ simpa only [marks, zeros, List.length_cons, List.replicate_succ, hb,
+ show k+1+xs.length = k+(xs.length+1) by omega,
+ show n+1+xs.length = n+(xs.length+1) by omega] using hr
+
+/-- The first scan produces the mathematical logarithm in unary and allocates
+exactly the original number of zero result cells. -/
+theorem scan_runs (c : Bool) (xs : List Bool) :
+ let j := if c then Nat.clog 2 (value xs) else Nat.log 2 (value xs)
+ ∃ t ≤ 5*xs.length+4, StackRuns (scan c) t .reverse (store [] [] xs [] [])
+ .done (store [] (marks j) (zeros xs.length) [] []) := by
+ dsimp only
+ have start := reverse_run c xs []
+ rw [List.append_nil] at start
+ rcases split_word xs with hz | ⟨low,z,rfl⟩
+ · have hv : value xs = 0 := by rw [hz]; exact UnaryWord.zeros_value _
+ have rev : xs.reverse = zeros xs.length := by conv_lhs => rw [hz, List.reverse_replicate]
+ rw [rev] at start
+ have lead := leading_run c xs.length 0 []
+ simp only [Nat.zero_add, List.append_nil] at lead
+ have stop : StackRuns (scan c) 1 .leading (store [] [] (zeros xs.length) [] []) .done
+ (store [] [] (zeros xs.length) [] []) := by log_step; exact .nil ..
+ refine ⟨(2*xs.length+1)+2*xs.length+1, by omega, ?_⟩
+ simpa only [hv, Nat.clog_zero_right, Nat.log_zero_right, ite_self, marks, List.replicate_zero] using (start.trans lead).trans stop
+ · rw [List.reverse_append, List.reverse_cons, List.reverse_replicate, List.append_assoc,
+ List.singleton_append] at start
+ have lead := leading_run c z 0 (true::low.reverse)
+ simp only [Nat.zero_add] at lead
+ have high : StackRuns (scan c) 2 .leading (store [] [] (zeros z) [] (true::low.reverse))
+ (.lower false) (store [] [] (zeros (z+1)) [] low.reverse) := by
+ log_step; log_step; exact .nil ..
+ obtain ⟨t, ht, hr⟩ := lower_run c false low.reverse 0 (z+1)
+ simp only [List.length_reverse, Nat.zero_add, Bool.false_or, List.contains_reverse] at ht hr
+ have he := ((start.trans lead).trans high).trans hr
+ simp only [List.length_append, List.length_cons, List.length_replicate] at he ⊢
+ rw [log_split]
+ refine ⟨(2*(low.length+(z+1))+1)+2*z+2+t, by omega, ?_⟩
+ simpa only [show z+1+low.length = low.length+(z+1) by omega] using he
+
+end RAMTape.PublicExprLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicExprLogValue.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicExprLogValue.lean
new file mode 100644
index 0000000000..8b2e651819
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicExprLogValue.lean
@@ -0,0 +1,71 @@
+import OAI.Computability.VPVNP.RAMTapeUnaryWordValue
+import Mathlib.Data.Nat.Log
+
+/-! # Logarithms of a padded binary word
+
+A nonzero little-endian word has a unique highest set bit. Its lower bits
+determine whether the ceiling exceeds the floor by one.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicExprLog
+
+open TapeWord
+
+theorem split_word (xs : List Bool) :
+ xs = List.replicate xs.length false ∨ ∃ low z, xs = low ++ true :: List.replicate z false := by
+ induction xs with
+ | nil => exact Or.inl rfl
+ | cons b xs ih =>
+ rcases ih with h | ⟨low,z,rfl⟩
+ · cases b
+ · exact Or.inl (congrArg (false :: ·) h)
+ · exact Or.inr ⟨[], xs.length, congrArg (true :: ·) h⟩
+ · exact Or.inr ⟨b::low, z, rfl⟩
+
+private theorem value_append (xs ys : List Bool) :
+ value (xs ++ ys) = value xs + 2 ^ xs.length * value ys := by
+ induction xs with
+ | nil => simp [value]
+ | cons b xs ih => simp [value, ih, pow_succ]; ring
+
+private theorem contains_one (xs : List Bool) : xs.contains true = true ↔ 0 < value xs := by
+ induction xs with
+ | nil => simp [value]
+ | cons b xs ih =>
+ cases b <;> simp [value] at ih ⊢
+ exact ih
+
+theorem log_split (ceiling : Bool) (low : List Bool) (z : ℕ) :
+ let x := value (low ++ true :: List.replicate z false)
+ (if ceiling then Nat.clog 2 x else Nat.log 2 x) =
+ low.length + (ceiling && low.contains true).toNat := by
+ dsimp only
+ rw [value_append]
+ simp only [value, Bool.toNat_true, UnaryWord.zeros_value, Nat.mul_zero, Nat.add_zero, Nat.mul_one]
+ have hlt := value_lt low
+ have htop : value low + 2 ^ low.length < 2 ^ (low.length + 1) := by rw [pow_succ]; omega
+ cases ceiling with
+ | false => simpa using Nat.log_eq_of_pow_le_of_lt_pow (Nat.le_add_left ..) htop
+ | true =>
+ cases hb : low.contains true
+ · have hv : value low = 0 := by
+ have hn : ¬0 < value low := fun h ↦ Bool.false_ne_true (hb.symm.trans ((contains_one low).mpr h))
+ omega
+ simp [hv, Nat.clog_pow _ _ (by decide : 1 < 2)]
+ · have hv := (contains_one low).mp hb
+ have hu := Nat.clog_le_of_le_pow htop.le
+ have hl : ¬ Nat.clog 2 (value low + 2 ^ low.length) ≤ low.length := by
+ rw [Nat.clog_le_iff_le_pow (by decide : 1 < 2)]
+ omega
+ simp only [Bool.true_and, Bool.toNat_true, ite_true]
+ omega
+
+end RAMTape.PublicExprLog
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicExprVector.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicExprVector.lean
new file mode 100644
index 0000000000..8ed9163d1a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicExprVector.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.RAMTapePublicExprCompiler
+
+/-! # Preparing the finite vector of public operands for the live instruction table
+
+Registers are filled in increasing order. Each expression's private registers
+lie above its result, so later evaluations preserve the preceding outputs.
+After the last expression, the same finite loop writes zero to every remaining
+register.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicExprMachine
+
+open BurstRAM PrivateRAM LiveProgram
+
+variable {k r : ℕ}
+
+/-- Largest register index used by the vector program. -/
+def capacity (expr : Fin k → PublicExpr) := k + Finset.univ.sup (fun i => extra (expr i))
+
+/-- Size of the register file allocated for evaluating the entire public expression vector. -/
+abbrev registerCount (expr : Fin k → PublicExpr) := capacity expr + 1
+
+private def term (expr : Fin k → PublicExpr) (i : Fin (registerCount expr)) :=
+ if h : i.val < k then expr ⟨i.val,h⟩ else .lit 0
+
+private theorem term_room (expr : Fin k → PublicExpr) (i : Fin (registerCount expr)) :
+ i.val + extra (term expr i) ≤ capacity expr := by
+ unfold term
+ split
+ · rename_i hi
+ exact Nat.add_le_add hi.le (Finset.le_sup (f := fun j => extra (expr j)) (Finset.mem_univ _))
+ · simpa [extra] using Nat.le_of_lt_succ i.isLt
+
+private theorem term_fits (g : Geometry) (expr : Fin k → PublicExpr)
+ (hf : ∀ j, (expr j).Fits g (2^g.w)) (i : Fin (registerCount expr)) :
+ (term expr i).Fits g (2^g.w) := by
+ unfold term
+ split
+ · exact hf _
+ · exact ⟨Nat.two_pow_pos _, trivial⟩
+
+private def compilePrefix (expr : Fin (r+1) → PublicExpr) : (n : ℕ) → n ≤ r+1 → FiniteRoutine (BankPort r)
+ | 0, _ => .ret
+ | n+1, hn => (compilePrefix expr n (by omega)).followedBy (compile r n (expr ⟨n,hn⟩))
+
+private def maxNodes (expr : Fin (r+1) → PublicExpr) := Finset.univ.sup (fun i => nodes (expr i))
+
+private theorem prefix_runs (g : Geometry) (expr : Fin (r+1) → PublicExpr)
+ (hroom : ∀ i, i.val + extra (expr i) ≤ r) (hfits : ∀ i, (expr i).Fits g (2^g.w))
+ (p : Word g.w) (rs : Fin (r+1) → Word g.w) (log : WriteLog g.w) (n : ℕ) (hn : n ≤ r+1) :
+ ∃ t ≤ n * (maxNodes expr * nodeCost g.w) + 1, ∃ out : Fin (r+1) → Word g.w,
+ (compilePrefix expr n hn).Runs t (ISA.bank (geometryWords g) p rs log) (ISA.bank (geometryWords g) p out log) ∧
+ ∀ i : Fin (r+1), i.val < n → out i = packed g.w ((expr i).eval g) := by
+ induction n with
+ | zero =>
+ exact ⟨1, by simp, rs, Routine.runs_ret _, fun _ h => (Nat.not_lt_zero _ h).elim⟩
+ | succ n ih =>
+ obtain ⟨t,ht,mid,pre,ok⟩ := ih (by omega)
+ let i : Fin (r+1) := ⟨n, hn⟩
+ obtain ⟨u,hu,out,one,hout,keep⟩ :=
+ compile_computes g r n (expr i) (hroom i) (hfits i) p mid log
+ have hs : nodes (expr i) ≤ maxNodes expr := Finset.le_sup (f := fun j => nodes (expr j)) (Finset.mem_univ i)
+ have hcost := hu.trans (Nat.mul_le_mul_right (nodeCost g.w) hs)
+ refine ⟨_, by rw [Nat.succ_mul]; omega, out, pre.followedBy one, ?_⟩
+ intro j hj
+ by_cases he : j.val = n
+ · have ji : j = i := Fin.ext he
+ have ai : addr r n = i := Fin.ext (addr_val (by omega))
+ simpa only [ji, ai] using hout
+ · exact (keep _ (by omega)).trans (ok _ (by omega))
+
+/-- Evaluate public expressions in increasing slot order and zero the remaining registers. -/
+def vector (expr : Fin k → PublicExpr) : FiniteRoutine (ISA.Port (registerCount expr) 4) :=
+ compilePrefix (term expr) (registerCount expr) le_rfl
+
+/-- Expected register contents after vector evaluation, with packed expression values in the
+operand slots and zero elsewhere. -/
+def output (g : Geometry) (expr : Fin k → PublicExpr) (i : Fin (registerCount expr)) : Word g.w :=
+ if h : i.val < k then packed g.w ((expr ⟨i.val,h⟩).eval g) else 0
+
+/-- The coefficient of the quadratic word-width bound depends only on the fixed expression vector. -/
+def coefficient (expr : Fin k → PublicExpr) := registerCount expr * maxNodes (term expr) * 150
+
+theorem vector_runs (g : Geometry) (expr : Fin k → PublicExpr) (hfits : ∀ i, (expr i).Fits g (2^g.w))
+ (p : Word g.w) (rs : Fin (registerCount expr) → Word g.w) (log : WriteLog g.w) :
+ ∃ t ≤ coefficient expr * (g.w+1)^2 + 1, (vector expr).Runs t
+ (ISA.bank (geometryWords g) p rs log) (ISA.bank (geometryWords g) p (output g expr) log) := by
+ obtain ⟨t,ht,out,run,ho⟩ := prefix_runs g (term expr) (term_room expr) (term_fits g expr hfits)
+ p rs log (registerCount expr) le_rfl
+ have he : out = output g expr := by
+ funext i
+ rw [ho i i.isLt, output, term]
+ split <;> rfl
+ rw [he] at run
+ exact ⟨t, by simpa only [nodeCost, coefficient, Nat.mul_assoc] using ht, run⟩
+
+/-- The instruction table can address its public operands in their original order. -/
+theorem output_at (g : Geometry) (expr : Fin k → PublicExpr) (i : Fin k) :
+ output g expr ⟨i.val, by dsimp [registerCount, capacity]; omega⟩ =
+ packed g.w ((expr i).eval g) := by simp [output, i.isLt]
+
+end RAMTape.PublicExprMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicGeometry.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicGeometry.lean
new file mode 100644
index 0000000000..004ea62701
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicGeometry.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.RAMTapePublicExprArithmetic
+import OAI.Computability.VPVNP.RAMTapeUnaryWord
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-!
+# Converting the physical geometry tallies into public RAM words
+
+The processor supplies four unary stacks and a persistent width-sized zero
+template. For each field, copy the zero template into the destination, save
+the field's unary marks, and increment the destination word once per mark.
+All four source tallies and the template remain available to the processor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicGeometry
+
+open BurstRAM LiveProgram PublicExprMachine
+
+/-- Stack labels for four unary geometry tallies, their corresponding word outputs, a zero
+template, and conversion scratch. -/
+inductive Port where
+ | unary (i : Fin 4) | word (i : Fin 4) | zeros | pending | tmp
+ deriving DecidableEq, Fintype
+
+private def counterPorts (i : Fin 4) : UnaryWord.Port → Port
+ | .src => .unary i
+ | .pending => .pending
+ | .number => .word i
+ | .unit => .zeros
+ | .tmp => .tmp
+
+private theorem counterPorts_inj (i : Fin 4) : Function.Injective (counterPorts i) := by
+ intro a b h
+ cases a <;> cases b <;> simp_all [counterPorts]
+
+private def count (i : Fin 4) : FiniteRoutine Port :=
+ FiniteRoutine.ofStackCode (UnaryWord.code 0) (counterPorts i) .count (· == .done)
+
+private def field (i : Fin 4) : FiniteRoutine Port :=
+ ((SuccessorFields.prependCopy .zeros (.word i) .tmp).followedBy
+ (SuccessorFields.prependCopy (.unary i) .pending .tmp)).followedBy (count i)
+
+private def bank (g : Geometry) (done : ℕ) : Stacks Port
+ | .unary j => List.replicate (geometryNat g j) true
+ | .word j => if j.val < done then wordBits (geometryWords g j) else []
+ | .zeros => List.replicate g.w false
+ | .pending | .tmp => []
+
+/-- Geometry-conversion bank before any of the four unary fields has been converted to a word. -/
+def initial (g : Geometry) : Stacks Port := bank g 0
+
+/-- Bank containing all four packed geometry words and the original tallies and zero template. -/
+def result (g : Geometry) : Stacks Port
+ | .word j => wordBits (geometryWords g j)
+ | j => initial g j
+
+private def work (w v : ℕ) := (5*w+2) + (5*v+2) + (v*(4*w+3)+1)
+
+private theorem field_runs (g : Geometry) (i : Fin 4) (hfit : geometryNat g i < 2^g.w) :
+ (field i).Runs (work g.w (geometryNat g i)) (bank g i.val) (bank g (i.val+1)) := by
+ let v := geometryNat g i
+ let z := List.replicate g.w false
+ let marks := List.replicate v true
+ let s := bank g i.val
+ let allocated := Function.update s (.word i) z
+ let ready := Function.update allocated Port.pending marks
+ have hz := SuccessorFields.prependCopy_runs Port.zeros (.word i) .tmp (by simp) (by decide) (by simp) s rfl
+ have halloc : (SuccessorFields.prependCopy .zeros (.word i) .tmp).Runs (5*g.w+2) s allocated := by
+ simpa [s, allocated, bank, z] using hz
+ have hs := SuccessorFields.prependCopy_runs (Port.unary i) .pending .tmp (by simp) (by simp) (by decide)
+ allocated (by simp [allocated,s,bank])
+ have hsave : (SuccessorFields.prependCopy (.unary i) .pending .tmp).Runs (5*v+2) allocated ready := by
+ simpa [ready, allocated, s, bank, v, marks] using hs
+ have hc : (count i).Runs (v*(4*g.w+3)+1) ready (bank g (i.val+1)) := by
+ apply FiniteRoutine.runs_ofStackCode_framed (counterPorts_inj i) (normal := (· == .done))
+ rfl rfl (fun q h => by cases q <;> first | rfl | contradiction)
+ (UnaryWord.count_fixed 0 g.w v marks z hfit)
+ · intro j; cases j <;> simp [counterPorts, ready, allocated, s, bank, marks, v, z, UnaryWord.store]
+ · intro j; cases j <;> simp [counterPorts, bank, marks, v, z, UnaryWord.store, geometryWords, packed]
+ · intro p hp
+ cases p with
+ | word j =>
+ have hn : j ≠ i := by rintro rfl; exact hp .number rfl
+ have hv : j.val ≠ i.val := fun h => hn (Fin.ext h)
+ have hlt : j.val < i.val + 1 ↔ j.val < i.val := by omega
+ simp [ready, allocated, s, bank, hn, hlt]
+ | unary j | zeros => simp [ready, allocated, s, bank]
+ | pending => exact (hp .pending rfl).elim
+ | tmp => exact (hp .tmp rfl).elim
+ exact (halloc.followedBy hsave).followedBy hc
+
+/-- The four source fields are prepared in the public operand order. -/
+def prepare : FiniteRoutine Port :=
+ (((field 0).followedBy (field 1)).followedBy (field 2)).followedBy (field 3)
+
+/-- Total conversion steps for input length, address width, bucket capacity, and word width. -/
+def steps (g : Geometry) := work g.w g.n + work g.w g.d + work g.w g.H + work g.w g.w
+
+theorem steps_le (g : Geometry) :
+ steps g ≤ 25 * (g.n+g.d+g.H+g.w+1)*(g.w+1) := by
+ unfold steps work
+ nlinarith only [Nat.zero_le g.n, Nat.zero_le g.d, Nat.zero_le g.H, Nat.zero_le g.w,
+ Nat.zero_le (g.n*g.w), Nat.zero_le (g.d*g.w), Nat.zero_le (g.H*g.w), Nat.zero_le (g.w*g.w)]
+
+theorem runs (g : Geometry) (hfit : ∀ i, geometryNat g i < 2^g.w) :
+ prepare.Runs (steps g) (initial g) (result g) := by
+ have finish : bank g 4 = result g := by
+ funext p
+ cases p with
+ | word j => simp [result, bank, j.isLt]
+ | unary | zeros | pending | tmp => rfl
+ rw [← finish]
+ exact (((field_runs g 0 (hfit 0)).followedBy (field_runs g 1 (hfit 1))).followedBy
+ (field_runs g 2 (hfit 2))).followedBy (field_runs g 3 (hfit 3))
+
+end RAMTape.PublicGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicGeometryPorts.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicGeometryPorts.lean
new file mode 100644
index 0000000000..d0a7e9237f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicGeometryPorts.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.RAMTapePublicGeometry
+import OAI.Computability.VPVNP.RAMTapeProcessorStartup
+import OAI.Computability.VPVNP.RAMProcessorReset
+
+/-!
+# Loading parsed public geometry into the arithmetic interpreter
+
+The physical parser supplies the four unary parameters and its zero-bit
+template. The converter writes the four public operands of the ISA bank,
+copies the template into its persistent word, and initializes its padded
+register words and empty private log. The existing processor stacks are
+available throughout the expression evaluation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicGeometry.Physical
+
+open BurstRAM LiveProgram PublicExprMachine
+
+/-- Joint bank of parsed processor data and the four-public-input arithmetic interpreter. -/
+abbrev Port (r : ℕ) := ProcessorPublic.Port ⊕ ISA.Port r 4
+
+instance (r : ℕ) : DecidableEq (Port r) := by
+ letI : DecidableEq ProcessorPublic.Port := inferInstance
+ infer_instance
+
+noncomputable instance (r : ℕ) : Fintype (Port r) := by
+ letI : Fintype ProcessorPublic.Port := inferInstance
+ infer_instance
+
+private def unaryPort : Fin 4 → ProcessorPublic.Port :=
+ ![ProcessorPublic.lengthPort, ProcessorPublic.addressWidthPort, ProcessorPublic.bucketPort, ProcessorPublic.widthPort]
+
+private def zeros : ProcessorPublic.Port := .inl SiteSetup.zerosPort
+
+private def embed (r : ℕ) : PublicGeometry.Port → Port r
+ | .unary i => .inl (unaryPort i)
+ | .word i => .inr (.pub i)
+ | .zeros => .inl zeros
+ | .pending => .inr (.work 1)
+ | .tmp => .inr (.work 0)
+
+private theorem embed_injective (r : ℕ) : Function.Injective (embed r) := by
+ have hu : Function.Injective unaryPort := by decide
+ have hz : ∀ i, unaryPort i ≠ zeros := by decide
+ intro a b he
+ cases a <;> cases b <;> simp [embed, hz, Ne.symm (hz _)] at he ⊢ <;> first | assumption | exact hu he
+
+/-- Enter the fixed arithmetic routine with an initialized ISA bank.
+The number of arithmetic registers belongs to the fixed expression code. -/
+def prepare (r : ℕ) : FiniteRoutine (Port r) :=
+ (((PublicGeometry.prepare.onPorts (embed r)).followedBy
+ (SuccessorFields.prependCopy (.inl zeros) (.inr .persistent) (.inr (.work 0)))).followedBy
+ (ISA.freshCall.onPorts Sum.inr))
+
+/-- Time for loading the four public inputs, padding the persistent word,
+and initializing the requested private arithmetic register bank. -/
+def budget (g : Geometry) (r : ℕ) := PublicGeometry.steps g + (5*g.w+2) + (r*(8*g.w+3)+5)
+
+variable {r : ℕ}
+
+theorem prepare_runs (g : Geometry) (processor : Stacks ProcessorPublic.Port)
+ (hn : processor ProcessorPublic.lengthPort = List.replicate g.n true)
+ (hd : processor ProcessorPublic.addressWidthPort = List.replicate g.d true)
+ (hH : processor ProcessorPublic.bucketPort = List.replicate g.H true)
+ (hw : processor ProcessorPublic.widthPort = List.replicate g.w true)
+ (hz : processor (.inl SiteSetup.zerosPort) = List.replicate g.w false)
+ (hfit : ∀ i, geometryNat g i < 2^g.w) :
+ ∃ t ≤ budget g r, (prepare r).Runs t (Sum.elim processor (fun _ => []))
+ (Sum.elim processor (ISA.bank (geometryWords g) 0 (fun _ => 0) [])) := by
+ change processor zeros = List.replicate g.w false at hz
+ let empty : Stacks (ISA.Port r 4) := fun _ => []
+ let loaded : Stacks (ISA.Port r 4) := fun p =>
+ match p with
+ | .pub i => wordBits (geometryWords g i)
+ | _ => []
+ let dest := ISA.preCall (geometryWords g) (0 : Word g.w) (fun _ : Fin r => []) []
+ have hsource (i : Fin 4) : processor (unaryPort i) = List.replicate (geometryNat g i) true := by
+ fin_cases i <;> first | exact hn | exact hd | exact hH | exact hw
+ have cv : (PublicGeometry.prepare.onPorts (embed r)).Runs (PublicGeometry.steps g)
+ (Sum.elim processor empty) (Sum.elim processor loaded) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (embed_injective r) (PublicGeometry.runs g hfit)
+ · intro j
+ cases j <;> first | rfl | exact hsource _ | exact hz
+ · intro j
+ cases j <;> first | rfl | exact hsource _ | exact hz
+ · rintro (j | j) h
+ · rfl
+ · cases j with
+ | pub i => exact (h (.word i) rfl).elim
+ | reg | work | persistent | logPort => rfl
+ have copy := SuccessorFields.prependCopy_runs (Sum.inl zeros : Port r) (.inr .persistent) (.inr (.work 0))
+ (by simp) (by simp) (by simp) (Sum.elim processor loaded) rfl
+ have copyResult : Function.update (Sum.elim processor loaded) (.inr .persistent)
+ (processor zeros ++ loaded .persistent) = Sum.elim processor dest := by
+ funext p
+ rcases p with i | i
+ · rfl
+ · cases i with
+ | persistent =>
+ change processor zeros ++ [] = wordBits (0 : Word g.w)
+ rw [List.append_nil, hz, UnaryWord.zeros_wordBits]
+ | reg | pub | work => rfl
+ | logPort j => cases j <;> rfl
+ change (SuccessorFields.prependCopy (.inl zeros) (.inr .persistent) (.inr (.work 0))).Runs
+ (5*(processor zeros).length+2) (Sum.elim processor loaded)
+ (Function.update (Sum.elim processor loaded) (.inr .persistent) (processor zeros ++ loaded .persistent)) at copy
+ rw [copyResult, hz, List.length_replicate] at copy
+ obtain ⟨u,hu,reset⟩ := ISA.freshCall_run (geometryWords g) (0 : Word g.w) (fun _ : Fin r => []) [] (by simp)
+ have reset' : (ISA.freshCall.onPorts Sum.inr).Runs u (Sum.elim processor dest)
+ (Sum.elim processor (ISA.bank (geometryWords g) 0 (fun _ => 0) [])) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inr_injective reset
+ · intro _; rfl
+ · intro _; rfl
+ · rintro (j | j) hj
+ · rfl
+ · exact (hj j rfl).elim
+ exact ⟨_, Nat.add_le_add_left (by simpa using hu) _, (cv.followedBy copy).followedBy reset'⟩
+
+end RAMTape.PublicGeometry.Physical
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicGeometryStartup.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicGeometryStartup.lean
new file mode 100644
index 0000000000..451cd96554
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicGeometryStartup.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.RAMTapePublicGeometryPorts
+
+/-!
+# Public-expression registers initialized from the original site tape
+
+The record startup first parses the physical input and prepares its public
+processor fields. The next finite routine forms the four fixed-width
+arithmetic inputs. Its quadratic preparation cost fits the existing startup
+clock for all lengths and sites satisfying the processor input bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicGeometry.Physical
+
+open BurstRAM LiveProgram PublicExprMachine RAMLayout ProcessorInput StackCompiler
+
+private theorem geometry_fit {B n d e w : ℕ} (hB : 1 ≤ B) (hd : d = B * Nat.clog 2 n) (hcap : d+e < w) :
+ ∀ i, geometryNat ⟨n,d,2^e,w⟩ i < 2^w := by
+ have hclog : Nat.clog 2 n ≤ d := hd ▸ Nat.le_mul_of_pos_left _ hB
+ have hdw : d < w := by omega
+ have hn := (Nat.le_pow_clog (by decide : 1 < 2) n).trans_lt
+ (Nat.pow_lt_pow_right (by decide) (hclog.trans_lt hdw))
+ have hh : 2^e < 2^w := Nat.pow_lt_pow_right (by decide) (by omega)
+ intro i
+ fin_cases i
+ · exact hn
+ · exact hdw.trans Nat.lt_two_pow_self
+ · exact hh
+ · exact Nat.lt_two_pow_self
+
+private theorem budget_le {g : Geometry} (r : ℕ) (hd : g.d ≤ g.w) (hw : g.w ≤ g.n) (hH : g.H ≤ 2*g.n) :
+ budget g r ≤ (140+11*r)*(g.n+1)^2 := by
+ have hsum : g.n+g.d+g.H+g.w+1 ≤ 5*(g.n+1) := by omega
+ have hprep := (PublicGeometry.steps_le g).trans
+ (Nat.mul_le_mul (Nat.mul_le_mul_left 25 hsum) (Nat.succ_le_succ hw))
+ have hadd : r*(8*g.w+3) ≤ r*(11*(g.n+1)) := Nat.mul_le_mul_left _ (by omega)
+ unfold budget
+ nlinarith only [hprep, hadd, hw, Nat.zero_le g.n, Nat.zero_le (g.n*g.n), Nat.zero_le (r*g.n*g.n),
+ Nat.zero_le (r*g.n), Nat.zero_le r]
+
+/-- Parse the raw site and prepare its initial-record words, then convert the geometry tallies
+and initialize the arithmetic registers. -/
+def startup (r B p q u lit : ℕ) (hq : 0 < q) : FiniteRoutine (Port r) :=
+ ((ProcessorPublic.recordStartup B p q u lit hq).onPorts Sum.inl).followedBy (prepare r)
+
+/-- The fixed public arithmetic register bank is ready after parsing an
+actual complete processor input, with every original public stack retained. -/
+theorem startup_runs (r B p q u lit : ℕ) (hB : 1 ≤ B) (hq : 0 < q) (hpq : p ≤ q) (hu : 1 ≤ u)
+ (prog : UniversalMachine.Program) (n : ℕ) (hn : 1 ≤ n) :
+ let d := B*Nat.clog 2 n
+ let e := roundedUp p q n
+ let w := (d+10)^4
+ ∀ (v : Word d) (hdr : Header) (inc : Fin (width d (2^e) w) → Bool), Fits prog n d (2^e) w →
+ let processor := ProcessorPublic.recordResult (ProcessorPublic.rawResult prog n d (2^e) w v hdr inc)
+ n d e w u lit v hdr (ProcessorPublic.capFits B p q n hB hq hpq hn) (ProcessorPublic.recordWidth_ge_four d)
+ ∃ t ≤ (ProcessorPublic.recordClockCoefficient B p q u + 140+11*r)*(n+1)^(max 7 (u+1)),
+ (startup r B p q u lit hq).Runs t
+ (labeledInput (.inl ProcessorPublic.rawPort) (ProcessorInput.tape prog n v hdr inc))
+ (Sum.elim processor (ISA.bank (geometryWords ⟨n,d,2^e,w⟩) 0 (fun _ => 0) [])) := by
+ intro d e w v hdr inc fit processor
+ let g : Geometry := ⟨n,d,2^e,w⟩
+ let tape := ProcessorInput.tape prog n v hdr inc
+ obtain ⟨u₁,hw₁,h₁⟩ := ProcessorPublic.recordStartup_runs B p q u lit hB hq hpq hu prog n hn v hdr inc fit
+ have lifted : ((ProcessorPublic.recordStartup B p q u lit hq).onPorts (Sum.inl : _ → Port r)).Runs u₁
+ (labeledInput (.inl ProcessorPublic.rawPort) tape) (Sum.elim processor (fun _ => [])) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective h₁
+ · intro j; simp [labeledInput, tape]
+ · intro j; rfl
+ · rintro (j | j) h
+ · exact (h j rfl).elim
+ · rfl
+ have cap := ProcessorPublic.capFits B p q n hB hq hpq hn
+ change d+e < w at cap
+ obtain ⟨u₂,hw₂,h₂⟩ := prepare_runs (r := r) g processor rfl rfl rfl rfl rfl (geometry_fit hB rfl cap)
+ refine ⟨u₁+u₂,?_,lifted.followedBy h₂⟩
+ have hwn : w ≤ n := by
+ change (UniversalMachine.programPrefix prog).length + (d + 4 + width d (2^e) w) ≤ n at fit
+ rw [width_eq] at fit
+ omega
+ have hbudget := budget_le (g := g) r (by change d ≤ w; omega) hwn (InputBucketFromSize.bucket_le hq hpq hn)
+ have hpow := Nat.pow_le_pow_right (Nat.succ_pos n) (show 2 ≤ max 7 (u+1) by omega)
+ rw [Nat.add_assoc, Nat.add_mul]
+ exact Nat.add_le_add hw₁ (hw₂.trans (hbudget.trans (Nat.mul_le_mul_left _ hpow)))
+
+end RAMTape.PublicGeometry.Physical
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicInputOperands.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicInputOperands.lean
new file mode 100644
index 0000000000..6f57186c2d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicInputOperands.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.LiveProgramPieces
+import OAI.Computability.VPVNP.RAMTapePublicExprVector
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-!
+# Loading a fixed operand vector from geometry and a parsed program prefix
+
+The physical operand bank has six inputs. The first four are the parsed
+geometry. The remaining two are the length and packed value of the actual
+program prefix read from the input tape. The program fills the expression
+slots, then copies the two parsed words to each of their designated slots.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputOperandMachine
+
+open BurstRAM BurstRAM.PrivateRAM LiveProgram PublicExprMachine
+
+variable {k : ℕ}
+
+/-- Replace the two prefix-derived operand forms by literal zero while retaining the geometry
+expressions in their own slots. -/
+def geometryOnly (args : Fin k → InputOperand) (i : Fin k) : PublicExpr :=
+ match args i with
+ | .geometry e => e
+ | _ => .lit 0
+
+/-- Register count needed for evaluating the geometry part of the input operand vector. -/
+abbrev registers (args : Fin k → InputOperand) := registerCount (geometryOnly args)
+
+/-- The six public inputs, in order, are the four geometry words followed by the packed length
+and value of the parsed prefix. -/
+def input (g : Geometry) (lit : LiteralPrefix) : Fin 6 → Word g.w :=
+ Fin.append (geometryWords g) ![packed g.w lit.length, packed g.w lit.value]
+
+/-- Embed the geometry interpreter’s four public ports into the first four of six while
+retaining its other port names. -/
+def embed {r : ℕ} : ISA.Port r 4 → ISA.Port r 6
+ | .pub i => .pub (i.castAdd 2)
+ | .reg i => .reg i
+ | .persistent => .persistent
+ | .work i => .work i
+ | .logPort i => .logPort i
+
+theorem embed_inj {r : ℕ} : Function.Injective (@embed r) := by
+ intro a b h
+ cases a <;> cases b <;> simp_all [embed]
+ exact Fin.ext (congrArg (fun j : Fin 6 => j.val) h)
+
+/-- Register index at which the selected input operand is stored. -/
+def slot (args : Fin k → InputOperand) (i : Fin k) : Fin (registers args) :=
+ ⟨i.val,by dsimp [registers,registerCount,capacity]; omega⟩
+
+private def put (args : Fin k → InputOperand) (i : Fin k) : FiniteRoutine (ISA.Port (registers args) 6) :=
+ match args i with
+ | .geometry _ => .ret
+ | .prefixLength => load (slot args i) 4
+ | .prefixWord => load (slot args i) 5
+
+private def patch (args : Fin k → InputOperand) : (n : ℕ) → n ≤ k → FiniteRoutine (ISA.Port (registers args) 6)
+ | 0, _ => .ret
+ | n+1, h => (patch args n (by omega)).followedBy (put args ⟨n,h⟩)
+
+/-- Evaluate the geometry slots, then copy the parsed prefix length or value to each slot that
+requests it. -/
+def program (args : Fin k → InputOperand) : FiniteRoutine (ISA.Port (registers args) 6) :=
+ ((vector (geometryOnly args)).onPorts embed).followedBy (patch args k le_rfl)
+
+private theorem vector_input {r : ℕ} (g : Geometry) (lit : LiteralPrefix)
+ (st : Word g.w) (rs out : Fin r → Word g.w) (log : WriteLog g.w)
+ (routine : FiniteRoutine (ISA.Port r 4)) {t : ℕ}
+ (h : routine.Runs t (ISA.bank (geometryWords g) st rs log) (ISA.bank (geometryWords g) st out log)) :
+ (routine.onPorts embed).Runs t (ISA.bank (input g lit) st rs log) (ISA.bank (input g lit) st out log) := by
+ apply FiniteRoutine.runs_onPorts_framed _ embed_inj h
+ · intro j; cases j <;> simp [embed, ISA.bank, input]
+ · intro j; cases j <;> simp [embed, ISA.bank, input]
+ · intro j hj
+ cases j with
+ | reg i => exact (hj (.reg i) rfl).elim
+ | _ => rfl
+
+private def mixed (args : Fin k → InputOperand) (g : Geometry) (lit : LiteralPrefix) (n : ℕ)
+ (i : Fin (registers args)) : Word g.w :=
+ if hi : i.val < k then
+ if i.val < n then Pieces.word g lit (args ⟨i.val,hi⟩) else output g (geometryOnly args) i
+ else output g (geometryOnly args) i
+
+private theorem put_run (args : Fin k → InputOperand) (g : Geometry) (lit : LiteralPrefix)
+ (st : Word g.w) (log : WriteLog g.w) (i : Fin k) :
+ ∃ t ≤ 8*g.w+3, (put args i).Runs t
+ (ISA.bank (input g lit) st (mixed args g lit i.val) log)
+ (ISA.bank (input g lit) st (mixed args g lit (i.val+1)) log) := by
+ have hnew : mixed args g lit (i.val+1) (slot args i) = Pieces.word g lit (args i) := by
+ simp [mixed,slot,i.isLt]
+ have hsame (j : Fin (registers args)) (hne : j ≠ slot args i) :
+ mixed args g lit (i.val+1) j = mixed args g lit i.val j := by
+ have hj : j.val ≠ i.val := fun h => hne (Fin.ext h)
+ simp only [mixed,show j.val < i.val+1 ↔ j.val < i.val by omega]
+ have hbase : mixed args g lit i.val (slot args i) = packed g.w ((geometryOnly args i).eval g) := by
+ simp only [mixed,slot,i.isLt,↓reduceDIte,lt_self_iff_false,↓reduceIte]
+ exact output_at ..
+ have eq (a : Word g.w) (ha : Pieces.word g lit (args i) = a) :
+ Function.update (mixed args g lit i.val) (slot args i) a = mixed args g lit (i.val+1) := by
+ funext j
+ by_cases hj : j = slot args i
+ · subst j; rw [Function.update_self,hnew,ha]
+ · rw [Function.update_of_ne hj,hsame j hj]
+ cases h : args i with
+ | geometry e =>
+ have he : mixed args g lit i.val = mixed args g lit (i.val+1) := by
+ funext j
+ by_cases hj : j = slot args i
+ · subst j; rw [hnew,hbase]; simp [geometryOnly,h,Pieces.word,InputOperand.eval]
+ · exact (hsame j hj).symm
+ rw [put,h,he]
+ exact ⟨1,by omega,Routine.runs_ret _⟩
+ | prefixLength =>
+ rw [put,h,← eq ((input g lit) 4) (by rw [h]; rfl)]
+ exact ⟨_,le_rfl,load_runs ..⟩
+ | prefixWord =>
+ rw [put,h,← eq ((input g lit) 5) (by rw [h]; rfl)]
+ exact ⟨_,le_rfl,load_runs ..⟩
+
+private theorem patch_run (args : Fin k → InputOperand) (g : Geometry) (lit : LiteralPrefix)
+ (st : Word g.w) (log : WriteLog g.w) (n : ℕ) (hn : n ≤ k) :
+ ∃ t ≤ n*(8*g.w+3)+1, (patch args n hn).Runs t
+ (ISA.bank (input g lit) st (mixed args g lit 0) log)
+ (ISA.bank (input g lit) st (mixed args g lit n) log) := by
+ induction n with
+ | zero => exact ⟨1,by simp,Routine.runs_ret _⟩
+ | succ n ih =>
+ obtain ⟨t,ht,first⟩ := ih (by omega)
+ obtain ⟨u,hu,last⟩ := put_run args g lit st log ⟨n,hn⟩
+ exact ⟨_,by rw [Nat.succ_mul]; omega,first.followedBy last⟩
+
+/-- Each component of the flattened table is loaded from its prescribed
+operand. The time constant depends only on the fixed operand vector. -/
+theorem runs (args : Fin k → InputOperand) (g : Geometry) (lit : LiteralPrefix)
+ (hf : ∀ i, (geometryOnly args i).Fits g (2^g.w))
+ (st : Word g.w) (rs : Fin (registers args) → Word g.w) (log : WriteLog g.w) :
+ ∃ t ≤ coefficient (geometryOnly args)*(g.w+1)^2+k*(8*g.w+3)+2,
+ ∃ out : Fin (registers args) → Word g.w, (program args).Runs t
+ (ISA.bank (input g lit) st rs log) (ISA.bank (input g lit) st out log) ∧
+ ∀ i, out (slot args i) = Pieces.word g lit (args i) := by
+ obtain ⟨t,ht,arith⟩ := vector_runs g (geometryOnly args) hf st rs log
+ have pre := vector_input g lit st rs _ log _ arith
+ have hzero : mixed args g lit 0 = output g (geometryOnly args) := by funext i; simp [mixed]
+ obtain ⟨u,hu,fix⟩ := patch_run args g lit st log k le_rfl
+ rw [hzero] at fix
+ exact ⟨_,by omega,_,pre.followedBy fix,fun i => by simp [mixed,slot,i.isLt]⟩
+
+end RAMTape.InputOperandMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicOperandPorts.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicOperandPorts.lean
new file mode 100644
index 0000000000..6d8fe9ac6e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicOperandPorts.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.RAMTapePublicOperandStartup
+import OAI.Computability.VPVNP.RAMProcessorBank
+
+/-! # Installing the evaluated public operands in the actual processor bank
+
+The first arithmetic registers are the instruction interpreter's public-word
+ports. The arithmetic program reads and writes those ports directly. Its
+temporary registers and the retained input fields have separate labels.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicOperandStartup
+
+open BurstRAM LiveProgram RAMLayout ProcessorInput StackCompiler PublicExprMachine
+
+variable {k : ℕ}
+
+/-- Port space combining the site interpreter and the arithmetic source of its public operands. -/
+abbrev Port (r : ℕ) (expr : Fin k → PublicExpr) := SiteProcessor.Port r k ⊕ Source expr
+
+private def index (expr : Fin k → PublicExpr) (i : Fin k) : Fin (registerCount expr) :=
+ ⟨i.val, by dsimp [registerCount, capacity]; omega⟩
+
+/-- Identify the first arithmetic result registers with the interpreter’s public operand ports
+and keep the other source ports separate. -/
+def ports (r : ℕ) (expr : Fin k → PublicExpr) : Source expr → Port r expr
+ | .inr (.reg i) => if h : i.val < k then .inl (.isa (.pub ⟨i.val,h⟩)) else .inr (.inr (.reg i))
+ | p => .inr p
+
+theorem ports_injective (r : ℕ) (expr : Fin k → PublicExpr) : Function.Injective (ports r expr) := by
+ let back : Port r expr → Source expr := fun
+ | .inl (.isa (.pub i)) => .inr (.reg (index expr i))
+ | .inr p => p
+ | _ => .inl ProcessorPublic.rawPort
+ apply Function.LeftInverse.injective (g := back)
+ rintro (p|p)
+ · rfl
+ · cases p with
+ | reg i => by_cases hi : i.val < k <;> simp [ports, hi, back, index]
+ | _ => rfl
+
+/-- Exactly the public registers of the site interpreter are populated. -/
+def siteWords (r : ℕ) (expr : Fin k → PublicExpr) (g : Geometry) : Stacks (SiteProcessor.Port r k)
+ | .isa (.pub i) => wordBits (packed g.w ((expr i).eval g))
+ | _ => []
+
+/-- Original processor fields and all arithmetic workspace after initialization. -/
+def result (r : ℕ) (expr : Fin k → PublicExpr) (g : Geometry) (processor : Stacks ProcessorPublic.Port) :
+ Stacks (Port r expr)
+ | .inl p => siteWords r expr g p
+ | .inr (.inl p) => processor p
+ | .inr (.inr (.reg i)) => if i.val < k then [] else arithmetic g expr (.reg i)
+ | .inr (.inr p) => arithmetic g expr p
+
+theorem result_public (r : ℕ) (expr : Fin k → PublicExpr) (g : Geometry)
+ (processor : Stacks ProcessorPublic.Port) (i : Fin k) :
+ result r expr g processor (.inl (.isa (.pub i))) = wordBits (packed g.w ((expr i).eval g)) := rfl
+
+theorem result_processor (r : ℕ) (expr : Fin k → PublicExpr) (g : Geometry)
+ (processor : Stacks ProcessorPublic.Port) (p : ProcessorPublic.Port) :
+ result r expr g processor (.inr (.inl p)) = processor p := rfl
+
+/-- Run the physical operand initializer on the port bank that installs its results directly in
+the site interpreter. -/
+def program (r : ℕ) (expr : Fin k → PublicExpr) (B p q u lit : ℕ) (hq : 0 < q) :
+ FiniteRoutine (Port r expr) := (sourceProgram expr B p q u lit hq).onPorts (ports r expr)
+
+private theorem install_run (r : ℕ) (expr : Fin k → PublicExpr) {t : ℕ} {src : FiniteRoutine (Source expr)}
+ (g : Geometry) (processor : Stacks ProcessorPublic.Port) (tape : List Bool)
+ (hr : src.Runs t (labeledInput (.inl ProcessorPublic.rawPort) tape) (Sum.elim processor (arithmetic g expr))) :
+ (src.onPorts (ports r expr)).Runs t (labeledInput (.inr (.inl ProcessorPublic.rawPort)) tape)
+ (result r expr g processor) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (ports_injective r expr) hr
+ · rintro (p|p)
+ · simp [ports, labeledInput]
+ · cases p with
+ | reg i => by_cases hi : i.val < k <;> simp [ports, hi, labeledInput]
+ | _ => simp [ports, labeledInput]
+ · rintro (p|p)
+ · rfl
+ · cases p with
+ | reg i =>
+ by_cases hi : i.val < k
+ · simp [ports, hi, result, siteWords, arithmetic, output, ISA.bank]
+ · simp [ports, hi, result]
+ | _ => rfl
+ · rintro (p | (p|p)) hp
+ · cases p with
+ | isa i =>
+ cases i with
+ | pub j =>
+ exact (hp (.inr (.reg (index expr j))) (by simp [ports, index, j.isLt])).elim
+ | _ => rfl
+ | _ => rfl
+ · exact (hp (.inl p) rfl).elim
+ · cases p with
+ | reg i =>
+ by_cases hi : i.val < k
+ · simp [result, hi, labeledInput]
+ · exact (hp (.inr (.reg i)) (by simp [ports, hi])).elim
+ | pub i => exact (hp (.inr (.pub i)) rfl).elim
+ | persistent => exact (hp (.inr .persistent) rfl).elim
+ | work i => exact (hp (.inr (.work i)) rfl).elim
+ | logPort i => exact (hp (.inr (.logPort i)) rfl).elim
+
+theorem runs (r : ℕ) (expr : Fin k → PublicExpr) (B p q u lit : ℕ) (hB : 1 ≤ B) (hq : 0 < q)
+ (hpq : p ≤ q) (hu : 1 ≤ u) (prog : UniversalMachine.Program) (n : ℕ) (hn : 1 ≤ n) :
+ let d := B*Nat.clog 2 n
+ let e := roundedUp p q n
+ let w := (d+10)^4
+ let g : Geometry := ⟨n,d,2^e,w⟩
+ ∀ (v : Word d) (hdr : Header) (inc : Fin (width d (2^e) w) → Bool), Fits prog n d (2^e) w →
+ (∀ i, (expr i).Fits g (2^w)) →
+ let processor := ProcessorPublic.recordResult (ProcessorPublic.rawResult prog n d (2^e) w v hdr inc)
+ n d e w u lit v hdr (ProcessorPublic.capFits B p q n hB hq hpq hn) (ProcessorPublic.recordWidth_ge_four d)
+ ∃ t ≤ clockCoefficient expr B p q u * (n+1)^(max 7 (u+1)), (program r expr B p q u lit hq).Runs t
+ (labeledInput (.inr (.inl ProcessorPublic.rawPort)) (ProcessorInput.tape prog n v hdr inc))
+ (result r expr g processor) := by
+ intro d e w g v hdr inc fit hf processor
+ obtain ⟨t,ht,hr⟩ := source_runs expr B p q u lit hB hq hpq hu prog n hn v hdr inc fit hf
+ exact ⟨t, ht, install_run r expr g processor _ hr⟩
+
+end RAMTape.PublicOperandStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapePublicOperandStartup.lean b/lean/OAI/Computability/VPVNP/RAMTapePublicOperandStartup.lean
new file mode 100644
index 0000000000..c44ba646a3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapePublicOperandStartup.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.RAMTapePublicExprVector
+import OAI.Computability.VPVNP.RAMTapePublicGeometryStartup
+
+/-! # Computing the live table's public operands from the original site input
+
+The geometry parser, word initialization and expression interpreter form one
+fixed finite control. It retains the processor's record fields and leaves the
+operand vector at the front of its arithmetic register bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.PublicOperandStartup
+
+open BurstRAM LiveProgram RAMLayout ProcessorInput StackCompiler PublicExprMachine
+
+variable {k : ℕ}
+
+/-- Port bank of the physical geometry parser and the register file sized for the expression
+vector. -/
+abbrev Source (expr : Fin k → PublicExpr) := PublicGeometry.Physical.Port (registerCount expr)
+
+/-- Initialize the geometry words from the raw tape, then evaluate the expression vector on the
+arithmetic bank. -/
+def sourceProgram (expr : Fin k → PublicExpr) (B p q u lit : ℕ) (hq : 0 < q) :
+ FiniteRoutine (Source expr) :=
+ (PublicGeometry.Physical.startup (registerCount expr) B p q u lit hq).followedBy
+ ((vector expr).onPorts Sum.inr)
+
+/-- Arithmetic output bank with the geometry inputs, evaluated operand vector, zero persistent
+word, and empty private log. -/
+def arithmetic (g : Geometry) (expr : Fin k → PublicExpr) :=
+ ISA.bank (geometryWords g) 0 (output g expr) []
+
+/-- Fixed clock coefficient for physical geometry startup, register allocation, and vector
+evaluation. -/
+def clockCoefficient (expr : Fin k → PublicExpr) (B p q u : ℕ) :=
+ ProcessorPublic.recordClockCoefficient B p q u + 140 + 11*registerCount expr + coefficient expr + 1
+
+theorem source_runs (expr : Fin k → PublicExpr) (B p q u lit : ℕ) (hB : 1 ≤ B) (hq : 0 < q)
+ (hpq : p ≤ q) (hu : 1 ≤ u) (prog : UniversalMachine.Program) (n : ℕ) (hn : 1 ≤ n) :
+ let d := B*Nat.clog 2 n
+ let e := roundedUp p q n
+ let w := (d+10)^4
+ let g : Geometry := ⟨n,d,2^e,w⟩
+ ∀ (v : Word d) (hdr : Header) (inc : Fin (width d (2^e) w) → Bool), Fits prog n d (2^e) w →
+ (∀ i, (expr i).Fits g (2^w)) →
+ let processor := ProcessorPublic.recordResult (ProcessorPublic.rawResult prog n d (2^e) w v hdr inc)
+ n d e w u lit v hdr (ProcessorPublic.capFits B p q n hB hq hpq hn) (ProcessorPublic.recordWidth_ge_four d)
+ ∃ t ≤ clockCoefficient expr B p q u * (n+1)^(max 7 (u+1)),
+ (sourceProgram expr B p q u lit hq).Runs t
+ (labeledInput (.inl ProcessorPublic.rawPort) (ProcessorInput.tape prog n v hdr inc))
+ (Sum.elim processor (arithmetic g expr)) := by
+ intro d e w g v hdr inc fit hf processor
+ obtain ⟨t,ht,init⟩ := PublicGeometry.Physical.startup_runs (registerCount expr) B p q u lit hB hq hpq hu
+ prog n hn v hdr inc fit
+ obtain ⟨s,hs,arith⟩ := vector_runs g expr hf 0 (fun _ => 0) []
+ have installed : ((vector expr).onPorts (Sum.inr : _ → Source expr)).Runs s
+ (Sum.elim processor (ISA.bank (geometryWords g) 0 (fun _ => 0) [])) (Sum.elim processor (arithmetic g expr)) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inr_injective arith
+ · intro; rfl
+ · intro; rfl
+ · rintro (x|x) hx
+ · rfl
+ · exact (hx x rfl).elim
+ refine ⟨_, ?_, init.followedBy installed⟩
+ have hw : w ≤ n := by
+ change (UniversalMachine.programPrefix prog).length + (d + 4 + width d (2^e) w) ≤ n at fit
+ rw [width_eq] at fit
+ omega
+ let K := (n+1)^(max 7 (u+1))
+ have hK : 1 ≤ K := Nat.one_le_pow _ _ (by omega)
+ have hpow : (w+1)^2 ≤ K := (Nat.pow_le_pow_left (Nat.succ_le_succ hw) 2).trans
+ (Nat.pow_le_pow_right (Nat.succ_pos n) (by omega))
+ have h₂ := (Nat.add_le_add (Nat.mul_le_mul_left (coefficient expr) hpow) hK)
+ change s ≤ coefficient expr * (w+1)^2 + 1 at hs
+ exact (Nat.add_le_add ht (hs.trans h₂)).trans (by unfold clockCoefficient; dsimp [K]; ring_nf; rfl)
+
+end RAMTape.PublicOperandStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeRecordBuffer.lean b/lean/OAI/Computability/VPVNP/RAMTapeRecordBuffer.lean
new file mode 100644
index 0000000000..ee35d026dc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeRecordBuffer.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.RAMTapeRecords
+import OAI.Computability.VPVNP.RAMTapeRecordClose
+import OAI.Computability.VPVNP.RAMBitTranscript
+
+/-!
+# Relating the emitted tape records to the site's initial sorting array
+
+One invocation of the record callback extends the accumulated prefix by the
+canonical bits of the staged record. Closing an admitted prefix adds just the
+vacant physical slots. Its decoded wire array is the `localRecords` input to
+the distributed validator, including the initialization record at sites with
+no calls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.RecordBuffer
+
+open BurstRAM RAMMemory RAMSerialization
+
+variable {w H : ℕ}
+
+/-- Between emissions all output bits are on the reverse buffer, and every
+free slot is represented by one true mark. -/
+structure Holds (hw : 2 ≤ w) (H : ℕ) (records : List (WordRecord w)) (s : Stacks Port) : Prop where
+ fit : records.length ≤ 4*H
+ scratch : s .temp = []
+ zeros : s .zeros = List.replicate w false
+ remaining : s .remaining = List.replicate (4*H-records.length) true
+ buffer : s .reverseBuffer = (serialized hw (records.map some)).reverse
+ output : s .output = []
+
+/-- Constructing a single probe or initialization record does not change
+the caller's five word registers. It extends the physical array once. -/
+theorem Holds.emit {hw : 2 ≤ w} {records : List (WordRecord w)} {s : Stacks Port}
+ (h : Holds hw H records s) (hfree : records.length < 4*H) (r : WordRecord w)
+ (hf : ∀ j, s (.field j) = BurstRAM.wordBits ((recordFormat hw).words (some r) j)) :
+ let left := List.replicate (4*H-(records.length+1)) true
+ let t := emitted s left (List.ofFn ((recordFormat hw).encode (some r)))
+ appendRecord.Runs (25*w+12) s t ∧ Holds hw H (records++[r]) t := by
+ dsimp only
+ have hlen : 4*H-records.length = 4*H-(records.length+1)+1 := by omega
+ refine ⟨appendRecord_run hw (some r) s _ (by rw [h.remaining, hlen, List.replicate_succ]) h.scratch hf,
+ ⟨by simp; omega, by simpa [emitted] using h.scratch, by simpa [emitted] using h.zeros, ?_, ?_,
+ by simpa [emitted] using h.output⟩⟩
+ · simp [emitted]
+ · simp [emitted, h.buffer, serialized, List.reverse_append]
+
+/-- The remaining indices return the unique empty slot. -/
+def slots (H : ℕ) (records : List (WordRecord w)) : Fin (4*H) → Option (WordRecord w) :=
+ fun i => records[i.val]?
+
+theorem slots_list (H : ℕ) (records : List (WordRecord w)) (hfit : records.length ≤ 4*H) :
+ List.ofFn (slots H records) = records.map some ++ List.replicate (4*H-records.length) none := by
+ apply List.ext_getElem?
+ intro j
+ by_cases hj : j < 4*H
+ · rw [List.getElem?_eq_getElem (by simpa only [List.length_ofFn] using hj), List.getElem_ofFn]
+ change some (records[j]?) = _
+ by_cases h : j < records.length
+ · rw [List.getElem?_append_left (by simpa using h), List.getElem?_map, List.getElem?_eq_getElem h]
+ rfl
+ · rw [List.getElem?_append_right (by simpa using Nat.le_of_not_gt h), List.length_map,
+ List.getElem?_eq_none (Nat.le_of_not_gt h)]
+ simp [show j-records.length < 4*H-records.length by omega]
+ · have hl : (records.map some ++ List.replicate (4*H-records.length) (none : Option (WordRecord w))).length
+ = 4*H := by simp only [List.length_append, List.length_map, List.length_replicate]; omega
+ rw [List.getElem?_eq_none (by simp only [List.length_ofFn]; omega),
+ List.getElem?_eq_none (by rw [hl]; omega)]
+
+theorem Holds.close {hw : 2 ≤ w} {records : List (WordRecord w)} {s : Stacks Port}
+ (h : Holds hw H records s) :
+ RecordBuffer.close.Runs ((4*H-records.length)*(25*w+12)+1+(2*(4*H*5*w)+1)) s
+ (Function.update (Function.update (Function.update s .remaining []) .reverseBuffer []) .output
+ (List.ofFn ((blockFormat H hw).encode (slots H records)))) :=
+ close_block hw _ s _ _ (slots_list H records h.fit) h.scratch h.zeros h.remaining h.buffer h.output
+
+/-- Widening the emitted slots, in order, recovers the complete typed input
+to the actual Batcher sorting replay. -/
+theorem slots_eq_localRecords {e v start : ℕ} (header : ℕ → Word w) (rs : List (Report w))
+ (records : List (WordRecord w))
+ (hrecs : records.map WordRecord.record = initRecord header v :: probeRecords start rs)
+ (i : Fin (2^(2+e))) :
+ ((slots (2^e) records (recordPosition e i)).map WordRecord.record) =
+ (localRecords header e v start rs i).record := by
+ let a := records.map WordRecord.record
+ have hj : (recordPosition e i).val = i.val := rfl
+ simp only [slots, hj, ← List.getElem?_map, hrecs, localRecords, siteRecordBlock]
+ let occupied := initRecord header v :: probeRecords start rs
+ change occupied[i.val]? = ((occupied.map some ++ List.replicate _ none)[i.val]?).getD none
+ by_cases h : i.val < occupied.length
+ · rw [List.getElem?_append_left (by simpa using h), List.getElem?_map, List.getElem?_eq_getElem h]
+ rfl
+ · rw [List.getElem?_append_right (by simpa using Nat.le_of_not_gt h), List.length_map,
+ List.getElem?_eq_none (Nat.le_of_not_gt h)]
+ simp
+
+end RAMTape.RecordBuffer
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeRecordClose.lean b/lean/OAI/Computability/VPVNP/RAMTapeRecordClose.lean
new file mode 100644
index 0000000000..fe9b37bf91
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeRecordClose.lean
@@ -0,0 +1,179 @@
+import OAI.Computability.VPVNP.RAMTapeRecordWord
+import OAI.Computability.VPVNP.RAMSortBlockSlices
+
+/-!
+# Completing the serialized pre-sort block
+
+Each unused record slot contributes five all-zero words. The remaining-slot
+counter controls padding independently of the values in the accumulated
+records. The last pass reverses the whole buffer once to expose records and
+their word bits in the order consumed by the first sorting layer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.RecordBuffer
+
+open Routine
+
+private def zeros : ℕ → FiniteRoutine Port
+ | 0 => .ret
+ | k+1 => (appendWord .zeros).followedBy (zeros k)
+
+/-- Append one zero record for each unary mark left after probe emission. -/
+def pad : FiniteRoutine Port := .ofRoutine
+ (popLoop Port.remaining (fun _ => true) (halt false) (zeros 5).body)
+
+/-- Pop the completed reverse buffer onto the output stack. -/
+def reverse : FiniteRoutine Port := .ofRoutine
+ (popLoop Port.reverseBuffer (fun _ => true) (push Port.output false) (push Port.output true))
+
+/-- Pad every unused slot with a zero record, then reverse the buffer to obtain the sorting
+input in record order. -/
+def close : FiniteRoutine Port := pad.followedBy reverse
+
+private def cells (s : Stacks Port) (remaining : ℕ) (buf out : List Bool) : Stacks Port
+ | .remaining => List.replicate remaining true
+ | .reverseBuffer => buf
+ | .output => out
+ | j => s j
+
+private theorem set_remaining (s : Stacks Port) (k k' : ℕ) (buf out : List Bool) :
+ Function.update (cells s k buf out) .remaining (List.replicate k' true) = cells s k' buf out := by
+ funext i; cases i <;> simp [cells]
+
+private theorem set_buffer (s : Stacks Port) (k : ℕ) (buf out b : List Bool) :
+ Function.update (cells s k buf out) .reverseBuffer b = cells s k b out := by
+ funext i; cases i <;> simp [cells]
+
+private theorem set_output (s : Stacks Port) (k : ℕ) (buf out o : List Bool) :
+ Function.update (cells s k buf out) .output o = cells s k buf o := by
+ funext i; cases i <;> simp [cells]
+
+private theorem zeros_run (s : Stacks Port) {w : ℕ} (ht : s .temp = []) (hz : s .zeros = List.replicate w false)
+ (t k : ℕ) (buf out : List Bool) :
+ (zeros t).Runs (t*(5*w+2)+1) (cells s k buf out)
+ (cells s k (List.replicate (t*w) false ++ buf) out) := by
+ induction t generalizing buf with
+ | zero => simpa [zeros, FiniteRoutine.ret, FiniteRoutine.Runs, FiniteRoutine.ofRoutine] using runs_ret (cells s k buf out)
+ | succ t ih =>
+ have h := appendWord_run (src := .zeros) (by decide) (by decide) (cells s k buf out) ht
+ change (appendWord .zeros).Runs (5*(s .zeros).length+2) _ (Function.update _ _ ((s .zeros).reverse ++ buf)) at h
+ rw [hz, List.reverse_replicate, List.length_replicate, set_buffer] at h
+ have H := h.followedBy (ih (List.replicate w false ++ buf))
+ rw [show 5*w+2+(t*(5*w+2)+1) = (t+1)*(5*w+2)+1 by ring] at H
+ simpa only [zeros, Nat.succ_mul, List.replicate_add, List.append_assoc] using H
+
+private theorem pad_run (s : Stacks Port) {w : ℕ} (ht : s .temp = []) (hz : s .zeros = List.replicate w false)
+ (k : ℕ) (buf out : List Bool) :
+ pad.Runs (k*(25*w+12)+1) (cells s k buf out)
+ (cells s 0 (List.replicate (k*(5*w)) false ++ buf) out) := by
+ induction k generalizing buf with
+ | zero =>
+ simp only [Nat.zero_mul, Nat.zero_add, List.replicate_zero, List.nil_append]
+ exact Runs.popLoop_empty Port.remaining (fun _ => true) (halt false) (zeros 5).body (s := cells s 0 buf out) rfl
+ | succ k ih =>
+ have head : cells s (k+1) buf out .remaining = true :: List.replicate k true := List.replicate_succ
+ have hb := zeros_run s ht hz 5 k buf out
+ have H := Runs.popLoop_true_continue Port.remaining (fun _ => true) (halt false) (zeros 5).body head rfl
+ (by rw [set_remaining]; exact hb) (ih (List.replicate (5*w) false ++ buf))
+ rw [show 1+(5*(5*w+2)+1)+(k*(25*w+12)+1) = (k+1)*(25*w+12)+1 by ring] at H
+ simpa only [pad, FiniteRoutine.ofRoutine, Nat.succ_mul, List.replicate_add, List.append_assoc] using H
+
+private theorem reverse_run (s : Stacks Port) (k : ℕ) (buf out : List Bool) :
+ reverse.Runs (2*buf.length+1) (cells s k buf out) (cells s k [] (buf.reverse++out)) := by
+ induction buf generalizing out with
+ | nil => exact Runs.popLoop_empty Port.reverseBuffer (fun _ => true) (push Port.output false) (push Port.output true) (s := cells s k [] out) rfl
+ | cons b xs ih =>
+ have head : cells s k (b::xs) out .reverseBuffer = b::xs := rfl
+ have hb := runs_push Port.output b (cells s k xs out)
+ change (push Port.output b).Runs 1 _ (Function.update _ .output (b::out)) at hb
+ rw [set_output] at hb
+ have H := Runs.popLoop_continue Port.reverseBuffer (fun _ => true) (push Port.output false) (push Port.output true)
+ head rfl (by rw [set_buffer]; cases b <;> exact hb) (ih (b::out))
+ rw [show 1+1+(2*xs.length+1) = 2*(xs.length+1)+1 by omega] at H
+ simpa only [reverse, FiniteRoutine.ofRoutine, FiniteRoutine.Runs, List.length_cons, List.reverse_cons,
+ List.append_assoc, List.singleton_append] using H
+
+/-- Closing adds the exact prescribed suffix of zero bits. It clears the
+slot counter and reverse buffer, and preserves the five field registers,
+the zero template, and the empty scratch stack. -/
+theorem close_run (s : Stacks Port) (w k : ℕ) (buf : List Bool) (ht : s .temp = [])
+ (hz : s .zeros = List.replicate w false) (hk : s .remaining = List.replicate k true)
+ (hb : s .reverseBuffer = buf.reverse) (ho : s .output = []) :
+ close.Runs (k*(25*w+12)+1 + (2*(buf.length+k*(5*w))+1)) s
+ (Function.update (Function.update (Function.update s .remaining []) .reverseBuffer [])
+ .output (buf ++ List.replicate (k*(5*w)) false)) := by
+ have h₁ := pad_run s ht hz k buf.reverse []
+ have h₂ := reverse_run s 0 (List.replicate (k*(5*w)) false ++ buf.reverse) []
+ have h := h₁.followedBy h₂
+ have hi : cells s k buf.reverse [] = s := by funext j; cases j <;> simp [cells, hk, hb, ho]
+ have hout (x : List Bool) : cells s 0 [] x =
+ Function.update (Function.update (Function.update s .remaining []) .reverseBuffer []) .output x := by
+ funext j; cases j <;> simp [cells]
+ rw [hi, hout] at h
+ simpa only [close, List.length_append, List.length_replicate, List.length_reverse, List.reverse_append,
+ List.reverse_replicate, List.reverse_reverse, List.append_nil, Nat.add_comm (k*(5*w))] using h
+
+
+open RAMSerialization
+
+/-- The same byte sequence emitted by consecutive `appendRecord` calls. -/
+def serialized {w : ℕ} (hw : 2 ≤ w) (records : List (Option (WordRecord w))) : List Bool :=
+ records.flatMap (fun r => List.ofFn ((recordFormat hw).encode r))
+
+theorem block_serialized {w H : ℕ} (hw : 2 ≤ w) (block : Fin (4*H) → Option (WordRecord w)) :
+ List.ofFn ((blockFormat H hw).encode block) = serialized hw (List.ofFn block) := by
+ let bits := (blockFormat H hw).encode block
+ have cast : 4*H*5*w = (4*H)*(5*w) := Nat.mul_assoc _ _ _
+ rw [List.ofFn_congr cast ((blockFormat H hw).encode block), List.ofFn_mul]
+ rw [serialized, List.flatMap_def, List.map_ofFn]
+ apply congrArg List.flatten
+ apply congrArg List.ofFn
+ funext i
+ apply congrArg List.ofFn
+ funext j
+ have h := congrFun (blockEncode_slice H hw block i) j
+ change bits ⟨i.val*(5*w)+j.val, _⟩ = _
+ apply Eq.trans _ h
+ apply congrArg bits
+ apply Fin.ext
+ change i.val*(5*w)+j.val = i.val*5*w+j.val
+ ring
+
+private theorem padding_serialized {w : ℕ} (hw : 2 ≤ w) (k : ℕ) :
+ serialized hw (List.replicate k none) = List.replicate (k*(5*w)) false := by
+ induction k with
+ | zero => simp [serialized]
+ | succ k ih =>
+ rw [List.replicate_succ, serialized, List.flatMap_cons, recordFormat_empty, List.ofFn_const,
+ ← serialized, ih, ← List.replicate_add]
+ apply congrArg (fun a => List.replicate a false)
+ ring
+
+/-- When the existing records followed by the vacant slots describe a
+complete block, the output is its canonical sorting-exchange encoding. -/
+theorem close_block {w H : ℕ} (hw : 2 ≤ w) (k : ℕ) (s : Stacks Port)
+ (records : List (Option (WordRecord w))) (block : Fin (4*H) → Option (WordRecord w))
+ (hblock : List.ofFn block = records ++ List.replicate k none)
+ (ht : s .temp = []) (hz : s .zeros = List.replicate w false) (hk : s .remaining = List.replicate k true)
+ (hb : s .reverseBuffer = (serialized hw records).reverse) (ho : s .output = []) :
+ close.Runs (k*(25*w+12)+1 + (2*(4*H*5*w)+1)) s
+ (Function.update (Function.update (Function.update s .remaining []) .reverseBuffer [])
+ .output (List.ofFn ((blockFormat H hw).encode block))) := by
+ have he : List.ofFn ((blockFormat H hw).encode block) =
+ serialized hw records ++ List.replicate (k*(5*w)) false := by
+ rw [block_serialized, hblock, serialized, List.flatMap_append, ← serialized, ← serialized,
+ padding_serialized]
+ have hlen := congrArg List.length he
+ simp only [List.length_ofFn, List.length_append, List.length_replicate] at hlen
+ rw [he, hlen]
+ exact close_run s w k (serialized hw records) ht hz hk hb ho
+
+end RAMTape.RecordBuffer
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeRecordWord.lean b/lean/OAI/Computability/VPVNP/RAMTapeRecordWord.lean
new file mode 100644
index 0000000000..d665d6765c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeRecordWord.lean
@@ -0,0 +1,38 @@
+import OAI.Computability.VPVNP.RAMTapeMapWord
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Record buffer word registers
+
+The pre-sort probe records are accumulated in reverse bit order. Copying a
+staged word into the buffer restores the source using one scratch stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.RecordBuffer
+
+/-- The five staged word fields, temporary copy stack, reverse buffer, free-slot counter,
+zeros, and output of the record emitter. -/
+inductive Port
+ | field (i : Fin 5)
+ | temp | reverseBuffer | remaining | zeros | output
+ deriving DecidableEq, Fintype
+
+/-- Copy one staged word into the reverse record buffer, restoring the source word afterward. -/
+def appendWord (src : Port) : FiniteRoutine Port :=
+ WordCopy.mapWord .temp .reverseBuffer id src
+
+theorem appendWord_run {src : Port} (h₁ : src ≠ .temp) (h₂ : src ≠ .reverseBuffer)
+ (s : Stacks Port) (ht : s .temp = []) :
+ (appendWord src).Runs (5*(s src).length+2) s
+ (Function.update s .reverseBuffer ((s src).reverse ++ s .reverseBuffer)) := by
+ simpa [appendWord] using WordCopy.mapWord_run .temp .reverseBuffer id h₁ h₂ (by decide) s ht
+
+end RAMTape.RecordBuffer
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeRecords.lean b/lean/OAI/Computability/VPVNP/RAMTapeRecords.lean
new file mode 100644
index 0000000000..10efb81571
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeRecords.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.RAMTapeRecordWord
+import OAI.Computability.VPVNP.RAMTapeSuccessorFields
+import Mathlib.Data.List.FinRange
+
+/-!
+# Fixed control for emitting a whole five-word RAM probe record
+
+The call interpreter stages the tag, address, value, call start and probe
+ordinal in five word stacks. Each emission takes one free slot, copies all
+five words in order, and restores the caller's registers. The empty and
+malformed remaining-slot counters reject without continuing.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.RecordBuffer
+
+open BurstRAM RAMSerialization
+
+private def putFields : List (Fin 5) → FiniteRoutine Port
+ | [] => .ret
+ | j :: js => (appendWord (.field j)).followedBy (putFields js)
+
+private def words (s : Stacks Port) (js : List (Fin 5)) : List Bool := js.flatMap (fun j => s (.field j))
+
+private theorem putFields_run (js : List (Fin 5)) (s : Stacks Port) (w : ℕ)
+ (ht : s .temp = []) (hf : ∀ j ∈ js, (s (.field j)).length = w) :
+ (putFields js).Runs (js.length*(5*w+2)+1) s
+ (Function.update s .reverseBuffer ((words s js).reverse ++ s .reverseBuffer)) := by
+ induction js generalizing s with
+ | nil => simpa [putFields, FiniteRoutine.ret, words, FiniteRoutine.Runs, FiniteRoutine.ofRoutine] using Routine.runs_ret s
+ | cons j js ih =>
+ let mid := Function.update s .reverseBuffer ((s (.field j)).reverse ++ s .reverseBuffer)
+ have h₁ : (appendWord (.field j)).Runs (5*w+2) s mid := by
+ simpa only [mid, hf j (List.mem_cons_self ..)] using
+ appendWord_run (src := .field j) (by simp) (by simp) s ht
+ have h₂ := ih mid (by simpa [mid] using ht) (fun i hi => by
+ simpa [mid] using hf i (List.mem_cons_of_mem _ hi))
+ have he : words mid js = words s js := by simp [words, mid]
+ have hh := h₁.followedBy h₂
+ rw [he] at hh
+ rw [show 5*w+2+(js.length*(5*w+2)+1) = (js.length+1)*(5*w+2)+1 by ring] at hh
+ simpa only [putFields, mid, Function.update_self, Function.update_idem, words, List.flatMap_cons,
+ List.reverse_append, List.append_assoc, List.length_cons] using hh
+
+/-- The one-record callback. The tag selects initialization, read or write
+and all fields already occupy the paper's fixed word width. -/
+def appendRecord : FiniteRoutine Port := .ofRoutine
+ (Routine.popCase Port.remaining (Routine.halt false) (Routine.halt false)
+ (putFields (List.finRange 5)).body)
+
+/-- Bank after record emission, with the new free-slot tally and the reversed record encoding
+prepended to the buffer. -/
+def emitted (s : Stacks Port) (left encoded : List Bool) : Stacks Port :=
+ Function.update (Function.update s .remaining left) .reverseBuffer (encoded.reverse ++ s .reverseBuffer)
+
+/-- Staging canonical record words in the five registers produces precisely
+the bits of the paper's physical slot, with no fresh choices. -/
+theorem appendRecord_run {w : ℕ} (hw : 2 ≤ w) (record : Option (WordRecord w))
+ (s : Stacks Port) (left : List Bool) (hleft : s .remaining = true::left)
+ (ht : s .temp = []) (hf : ∀ j, s (.field j) = BurstRAM.wordBits ((recordFormat hw).words record j)) :
+ appendRecord.Runs (25*w+12) s
+ (emitted s left (List.ofFn ((recordFormat hw).encode record))) := by
+ let next := Function.update s Port.remaining left
+ have hwords (j : Fin 5) : next (.field j) = BurstRAM.wordBits ((recordFormat hw).words record j) := by
+ simpa [next] using hf j
+ have h := putFields_run (List.finRange 5) next w (by simpa [next] using ht)
+ (fun j _ => by rw [hwords, length_wordBits])
+ have he : words next (List.finRange 5) = List.ofFn ((recordFormat hw).encode record) := by
+ rw [SuccessorFields.raw_eq_flatten_words, Format.encode, Equiv.symm_apply_apply]
+ unfold words
+ rw [List.flatMap_def, List.ofFn_eq_map]
+ simp only [hwords]
+ rw [he] at h
+ have hr := Routine.runs_popCase_true Port.remaining (Routine.halt false) (Routine.halt false)
+ (putFields (List.finRange 5)).body hleft h
+ rw [List.length_finRange, show 5*(5*w+2)+1+1=25*w+12 by ring] at hr
+ simpa only [appendRecord, FiniteRoutine.ofRoutine, FiniteRoutine.Runs, emitted, next,
+ Function.update_of_ne (by decide : Port.reverseBuffer ≠ Port.remaining)] using hr
+
+end RAMTape.RecordBuffer
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeRoutinePorts.lean b/lean/OAI/Computability/VPVNP/RAMTapeRoutinePorts.lean
new file mode 100644
index 0000000000..61b1f96f4f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeRoutinePorts.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.RAMTapeISAPorts
+
+/-! # Preserving the caller's other stacks when running a finite routine -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+variable {K L Q : Type}
+
+/-- Run an existing routine at the caller's physical port names. The control
+states, including the normal return, are copied verbatim. -/
+def FiniteRoutine.onPorts (r : FiniteRoutine K) (ports : K → L) : FiniteRoutine L :=
+ .ofRoutine ⟨r.body.entry, fun q => (r.body.code q).rename ports id⟩
+
+theorem FiniteRoutine.runs_onPorts [DecidableEq K] [DecidableEq L] (r : FiniteRoutine K)
+ {ports : K → L} (hp : Function.Injective ports) (base : Stacks L) {t : ℕ} {s out : Stacks K}
+ (h : r.Runs t s out) :
+ (r.onPorts ports).Runs t (installStacks ports base s) (installStacks ports base out) := by
+ have hh (q : Option r.State) (_ : (r.body.standalone q).returns = false) :
+ (r.onPorts ports).body.standalone (id q) = (r.body.standalone q).rename ports id := by
+ cases q <;> rfl
+ exact h.lift ports hp id base hh
+
+theorem installStacks_frame {ports : K → L} (hp : Function.Injective ports)
+ {base target : Stacks L} {small : Stacks K} (hin : ∀ k, target (ports k) = small k)
+ (hout : ∀ l, (∀ k, ports k ≠ l) → target l = base l) : installStacks ports base small = target := by
+ funext l
+ by_cases h : ∃ k, ports k = l
+ · obtain ⟨k, rfl⟩ := h
+ exact (installStacks_at hp base small k).trans (hin k).symm
+ · exact (installStacks_outside base small (not_exists.mp h)).trans (hout l (not_exists.mp h)).symm
+
+theorem FiniteRoutine.runs_onPorts_framed [DecidableEq K] [DecidableEq L] (r : FiniteRoutine K)
+ {ports : K → L} (hp : Function.Injective ports) {s u : Stacks L} {small out : Stacks K}
+ {t : ℕ} (h : r.Runs t small out) (hin : ∀ k, s (ports k) = small k)
+ (hu : ∀ k, u (ports k) = out k) (hout : ∀ l, (∀ k, ports k ≠ l) → u l = s l) :
+ (r.onPorts ports).Runs t s u := by
+ have hrun := r.runs_onPorts hp s h
+ rwa [installStacks_frame hp hin (fun _ _ => rfl), installStacks_frame hp hu hout] at hrun
+
+theorem FiniteRoutine.runs_ofStackCode_framed [Fintype Q] [DecidableEq K] [DecidableEq L]
+ {src : StackCode K Q} {ports : K → L} (hp : Function.Injective ports) {entry exit : Q}
+ {normal : Q → Bool} (he : normal entry = false) (hx : normal exit = true)
+ (hs : ∀ q, normal q = true → (src q).returns = true) {s u : Stacks L} {small out : Stacks K}
+ {t : ℕ} (h : StackRuns src t entry small exit out) (hin : ∀ k, s (ports k) = small k)
+ (hu : ∀ k, u (ports k) = out k) (hout : ∀ l, (∀ k, ports k ≠ l) → u l = s l) :
+ (ofStackCode src ports entry normal).Runs t s u := by
+ have hrun := runs_ofStackCode hp he hx hs s h
+ rwa [installStacks_frame hp hin (fun _ _ => rfl), installStacks_frame hp hu hout] at hrun
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeRoutineTotalPorts.lean b/lean/OAI/Computability/VPVNP/RAMTapeRoutineTotalPorts.lean
new file mode 100644
index 0000000000..b1d1b18aca
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeRoutineTotalPorts.lean
@@ -0,0 +1,48 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.StructuredStackTotal
+
+/-!
+# All-branch stopping bounds for framed stack routines
+
+Installing an injective port map preserves each stack transition and both branches of every
+choice. The same residual fuel is passed to the continuation, with the local outputs written
+back into the caller's untouched frame.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.FiniteRoutine
+
+variable {K L : Type} [DecidableEq K] [DecidableEq L]
+
+/-- Transport the continuation predicate through the installed ports, at any control label. -/
+theorem allStopsFrom_onPorts (r : FiniteRoutine K) (ports : K → L) (hp : Function.Injective ports)
+ (base : Stacks L) (c : ℕ → Stacks L → Prop) (n : ℕ) (q : Option r.State) (s : Stacks K) :
+ (r.onPorts ports).body.AllStopsFrom c n q (installStacks ports base s) ↔
+ r.body.AllStopsFrom (fun fuel out => c fuel (installStacks ports base out)) n q s := by
+ induction n generalizing q s with
+ | zero => cases q <;> rfl
+ | succ n ih =>
+ cases q with
+ | none => rfl
+ | some q =>
+ simp only [Routine.AllStopsFrom]
+ have hcode : (r.onPorts ports).body.code q = (r.body.code q).rename ports id := rfl
+ rw [hcode]
+ cases r.body.code q <;> simp [installStacks_at hp, installStacks_update hp, ih]
+
+/-- The local machine starts with exactly the caller's stacks at its named ports. -/
+theorem allStops_onPorts (r : FiniteRoutine K) (ports : K → L) (hp : Function.Injective ports)
+ (base : Stacks L) (c : ℕ → Stacks L → Prop) (n : ℕ) :
+ (r.onPorts ports).body.AllStops c n base ↔
+ r.body.AllStops (fun fuel out => c fuel (installStacks ports base out)) n (base ∘ ports) := by
+ have h := allStopsFrom_onPorts r ports hp base c n (some r.body.entry) (base ∘ ports)
+ rwa [installStacks_eq hp base (base ∘ ports) (fun _ => rfl)] at h
+
+end RAMTape.FiniteRoutine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeRun.lean b/lean/OAI/Computability/VPVNP/RAMTapeRun.lean
new file mode 100644
index 0000000000..b4236df877
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeRun.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.RAMTape
+
+/-!
+# Deterministic routines inside a branching tape program
+
+A run contains only one-record rows. Executing it consumes its recorded number
+of transitions and preserves the multiplicity of all continuations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+open UniversalMachine Turing
+
+variable {Q : Type*}
+
+/-- An exact finite run of deterministic two-tape commands between named configurations. -/
+inductive Runs (code : Control Q) :
+ ℕ → Q → Tape Symbol → Tape Symbol → Q → Tape Symbol → Tape Symbol → Prop
+ | nil (q t u) : Runs code 0 q t u q t u
+ | cons {q t u q' a d b e n r x y}
+ (h : code q t.head u.head = .one (.next q' a d b e))
+ (tail : Runs code n q' (updateTape t a d) (updateTape u b e) r x y) :
+ Runs code (n+1) q t u r x y
+
+theorem Runs.single {code : Control Q} {q t u q' a d b e}
+ (h : code q t.head u.head = .one (.next q' a d b e)) :
+ Runs code 1 q t u q' (updateTape t a d) (updateTape u b e) :=
+ .cons h (.nil ..)
+
+theorem Runs.trans {code : Control Q} {a b q t u q' x y r x' y'}
+ (h : Runs code a q t u q' x y) (g : Runs code b q' x y r x' y') :
+ Runs code (a+b) q t u r x' y' := by
+ induction h with
+ | nil => simpa using g
+ | cons hs _ ih => simpa [Nat.succ_add] using Runs.cons hs (ih g)
+
+theorem Runs.count [Fintype Q] {code : Control Q} {n q t u q' x y}
+ (h : Runs code n q t u q' x y) (start : Q) (fuel : ℕ) :
+ RAMTape.count start code (fuel+n) q t u = RAMTape.count start code fuel q' x y := by
+ induction h with
+ | nil => rfl
+ | cons hs _ ih => rw [Nat.add_succ, paths_step, hs]; exact ih
+
+/-- A two-way tape specified by the cells to the left and at or to the right of the head. -/
+abbrev cells := Tape.mk₂ (Γ := Symbol)
+
+@[simp] theorem cells_head (l : List Symbol) (x : Symbol) (r : List Symbol) :
+ (cells l (x :: r)).head = x := rfl
+
+@[simp] theorem cells_head_nil (l : List Symbol) : (cells l []).head = 0 := rfl
+
+@[simp] theorem update_stay (t : Tape Symbol) : updateTape t t.head 0 = t := Tape.write_self t
+
+theorem update_right (l r : List Symbol) (x y : Symbol) :
+ updateTape (cells l (x :: r)) y 2 = cells (y :: l) r := rfl
+
+theorem update_left (l r : List Symbol) (x z y : Symbol) :
+ updateTape (cells (z :: l) (x :: r)) y 1 = cells l (z :: y :: r) := rfl
+
+theorem cells_nil_cons_blank (l r : List Symbol) :
+ cells l (r ++ [0]) = cells l r := by
+ have he : ListBlank.mk (r ++ [(0 : Symbol)]) = ListBlank.mk r :=
+ Quotient.sound (Or.inr ⟨1, rfl⟩)
+ exact congrArg (Tape.mk' (ListBlank.mk l)) he
+
+/-- The head points to the stack top and every cell on its left is blank. -/
+abbrev tapeList (s : List Symbol) := cells [] s
+
+theorem cells_blank_left (s : List Symbol) : cells [0] s = tapeList s :=
+ congrArg (fun l => Tape.mk' l (ListBlank.mk s))
+ (show ListBlank.mk [(0 : Symbol)] = ListBlank.mk [] from Quotient.sound (Or.inr ⟨1, rfl⟩))
+
+@[simp] theorem pop_cell (a : Symbol) (s : List Symbol) :
+ updateTape (tapeList (a :: s)) 0 2 = tapeList s := cells_blank_left s
+
+theorem left_for_push (s : List Symbol) :
+ updateTape (tapeList s) (tapeList s).head 1 = tapeList (0 :: s) := by
+ change ((tapeList s).write (tapeList s).head).move .left = _
+ rw [Tape.write_self]
+ change (Tape.mk' (ListBlank.mk []) (ListBlank.mk s)).move .left = _
+ rw [Tape.move_left_mk']
+ rfl
+
+@[simp] theorem replace_top (a x : Symbol) (s : List Symbol) :
+ updateTape (tapeList (x :: s)) a 0 = tapeList (a :: s) := rfl
+
+@[simp] theorem write_left (a x : Symbol) (s : List Symbol) :
+ updateTape (tapeList (x :: s)) a 1 = tapeList (0 :: a :: s) := rfl
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteChoiceCard.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteChoiceCard.lean
new file mode 100644
index 0000000000..7addfcbe2c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteChoiceCard.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.RAMTapeSiteGraphInput
+import OAI.Computability.VPVNP.RAMProcessorChoiceCount
+
+/-! # Cardinal of the bounded choice strings on the parsed incident tape -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteCutBank
+
+open BurstRAM RAMLayout PrivateRAM
+
+variable {d e w p r k : ℕ} (x : Input d e w) (T : Template p r k) (operands : Fin k → Word w)
+
+/-- Test whether the instantiated private program’s incident validator succeeds on the given
+site and choice string. -/
+def Input.accepts (bs : List Bool) : Bool :=
+ ((T.instantiate w operands).validateIncident (x.n^x.u) x.initialWord x.headerWord x.word_ge_two
+ x.cap_lt x.v (RAMLayout.incidentBits x.sends x.v) bs).1.isSome
+
+/-- Cardinality of the private incident paths for the instantiated table, parsed site, and
+instruction fuel. -/
+noncomputable def Input.pathCard :=
+ Nat.card ((T.instantiate w operands).IncidentPaths (x.n^x.u) x.initialWord x.headerWord x.word_ge_two
+ x.cap_lt x.v (RAMLayout.incidentBits x.sends x.v))
+
+theorem Input.choiceCard :
+ ((ProcessorChoices.words (2*2^e*(x.n^x.u+w))).map (fun bs => (x.accepts T operands bs).toNat)).sum =
+ x.pathCard T operands := by
+ let shared := (sendArraysEquiv d (2^e) w).symm x.sends
+ have h := ProcessorChoices.site_choices (T.instantiate w operands) (x.n^x.u) x.initialWord
+ (fun _ => x.headerWord) x.word_ge_two x.cap_lt shared x.v
+ simpa only [BurstRAM.incidentBits, shared, Equiv.apply_symm_apply, Input.pathCard, Input.accepts] using h
+
+theorem Input.invalid_choice (hinv : ¬x.valid) (bs : List Bool) : x.accepts T operands bs = false := by
+ have he := scanSuccessors_spec x.word_ge_two x.cap_lt x.initialWord x.v (sortIncident x.sends x.v)
+ x.sends (sortIncident_offset x.sends x.v)
+ have h : x.summary.valid = false := Bool.eq_false_iff.mpr (fun hp => hinv (he.valid_iff.mp hp))
+ change (if x.summary.valid then _ else (none, _)).1.isSome = false
+ rw [h]; rfl
+
+theorem Input.invalid_pathCard (hinv : ¬x.valid) : x.pathCard T operands = 0 := by
+ rw [← x.choiceCard]
+ simp [x.invalid_choice T operands hinv]
+
+end RAMTape.SiteCutBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteCore.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteCore.lean
new file mode 100644
index 0000000000..ae4ef8cb33
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteCore.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.RAMTapeSiteValidated
+import OAI.Computability.VPVNP.RAMTapeSitePostEntry
+import OAI.Computability.VPVNP.RAMTapeSiteEntryView
+import OAI.Computability.VPVNP.RAMTapeSiteChoiceCard
+
+/-! # Exact private-path count of the site's fixed physical verifier -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+set_option synthInstance.maxSize 10000
+
+open BurstRAM PrivateRAM LiveProgram
+variable {p r k d e w : ℕ}
+
+/-- Prepare the guarded site entry and then run the per-choice verifier for the fixed
+instruction template. -/
+def core (r : ℕ) (expr : Fin k → PublicExpr) (T : Template p r k) : FiniteRoutine (Port r expr) :=
+ (prepareEntry r expr).followedBy (perChoice r expr T)
+
+/-- Site-core step budget combining entry costs with the per-choice bound at the site’s fuel. -/
+def coreSteps (r : ℕ) (x : SiteCutBank.Input d e w) :=
+ perChoiceBudget d e w r (x.n^x.u) + entrySteps x
+
+theorem core_spec (r : ℕ) (expr : Fin k → PublicExpr) (T : Template p r k) (x : SiteCutBank.Input d e w)
+ (operands : Fin k → Word w) (s : Stacks (Port r expr)) (hf : Frame r expr x operands s)
+ (hblank : ∀ j : SitePost.Port, s (.inr (.inr j)) = []) (t : ℕ) (ht : coreSteps r x ≤ t) :
+ (∀ c, (core r expr T).body.count c t s = x.pathCard T operands) ∧
+ (∀ c, (core r expr T).body.AllStops c t s) := by
+ classical
+ let rem := t - entrySteps x
+ have hrem : perChoiceBudget d e w r (x.n^x.u) ≤ rem := by dsimp [coreSteps, rem] at *; omega
+ have heq : t = rem + entrySteps x := by dsimp [coreSteps, rem] at *; omega
+ have per (hv : x.valid) (bs : List Bool) :
+ (∀ c, (perChoice r expr T).body.count c rem (entryBank r expr x s bs) = (x.accepts T operands bs).toNat) ∧
+ (∀ c, (perChoice r expr T).body.AllStops c rem (entryBank r expr x s bs)) :=
+ perChoice_complete r expr x T operands bs (entryBank r expr x s bs) hv (entry_view expr x T hf hv bs)
+ (PostReady.entry r expr x hf hv hblank bs) rem hrem
+ constructor
+ · intro c
+ change ((prepareEntry r expr).body.followedBy (perChoice r expr T).body).count c t s = _
+ rw [Routine.count_followedBy, heq, prepare_count r expr x hf]
+ by_cases hv : x.valid
+ · rw [ite_eq_left hv]
+ have hp := fun bs => (per hv bs).1 c
+ simp only [hp, x.choiceCard]
+ · rw [ite_eq_right hv, x.invalid_pathCard T operands hv]
+ · intro c
+ change ((prepareEntry r expr).body.followedBy (perChoice r expr T).body).AllStops c t s
+ rw [Routine.allStops_followedBy, heq, prepare_allStops r expr x hf]
+ exact fun hv bs _ => (per hv bs).2 c
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteCutBank.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteCutBank.lean
new file mode 100644
index 0000000000..f2f54624e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteCutBank.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.RAMTapeProcessorStartup
+import OAI.Computability.VPVNP.RAMTapeSuccessorTotal
+import OAI.Computability.VPVNP.RAMTapeSuccessorCuts
+import OAI.Computability.VPVNP.RAMTapeRoutineTotalPorts
+import OAI.Computability.VPVNP.EvaluatorRoutineFrame
+
+/-!
+# The successor guard on the actual public processor bank
+
+The reader addresses the parsed site and incident bits, the computed word width and cap,
+and the literal initial word directly in the public bank. Its running flags, decoded words
+and record payloads occupy separate auxiliary stacks. The guarded output below is the exact
+stack state supplied to the call loop or sorting pass on a valid pair of successor fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteCutBank
+set_option synthInstance.maxSize 256
+
+open BurstRAM ProcessorInput RAMLayout
+
+/-- Auxiliary guard ports for outgoing presence, per-side status, endpoint records, and eight
+decoded words on each side. -/
+inductive Aux where
+ | outPresent | running (side : Successors.Side) | verdict (side : Successors.Side)
+ | record (side : Successors.Side) | word (side : Successors.Side) (i : Fin 8)
+ deriving DecidableEq, Fintype
+
+/-- Combined public processor and successor-guard auxiliary bank. -/
+abbrev Port := ProcessorPublic.Port ⊕ Aux
+
+/-- Connect the successor reader to the parsed public fields and its dedicated scratch,
+decoded-word, and endpoint-record ports. -/
+def ports : Successors.Port → Port
+ | .address => .inl ProcessorPublic.addressPort
+ | .incident => .inl ProcessorPublic.incidentPort
+ | .width => .inl ProcessorPublic.widthPort
+ | .cap => .inl ProcessorPublic.capPort
+ | .initial => .inl ProcessorPublic.initPort
+ | .tmp => .inl (.inr (.scratch 0))
+ | .capTmp => .inl (.inr (.scratch 1))
+ | .outPresent => .inr .outPresent
+ | .running side => .inr (.running side)
+ | .verdict side => .inr (.verdict side)
+ | .record side => .inr (.record side)
+ | .word side i => .inr (.word side i)
+
+theorem ports_injective : Function.Injective ports := by decide
+
+/-- Run the two successor-field checks directly on the processor and guard banks. -/
+def checked : FiniteRoutine Port := Successors.checked.onPorts ports
+
+/-- Site data and width bounds used by the shared-bit guard. -/
+structure Input (d e w : ℕ) where
+ /-- Universal program whose literal prefix appears in the site input. -/
+ prog : UniversalMachine.Program
+ /-- Length of the complete physical site input, including its padding. -/
+ n : ℕ
+ /-- Exponent giving the private instruction allowance as a power of the input length. -/
+ u : ℕ
+ /-- Natural literal loaded as the private computation’s initial state word. -/
+ lit : ℕ
+ /-- Site address encoded in the public address width. -/
+ v : Word d
+ /-- Four-bit header accompanying the site address on the input. -/
+ hdr : Header
+ /-- Shared send arrays that determine the site’s incident bits and successor checks. -/
+ sends : SendArrays d (2^e) w
+ hcap : d + e < w
+ hw : 4 ≤ w
+ width_eq : w = (d+10)^4
+
+variable {d e w : ℕ} (x : Input d e w)
+
+include x in
+theorem Input.cap_lt : 2^d * 2^e < 2^w := (SuccessorParameters.capWord d e w x.hcap).isLt
+
+include x in
+theorem Input.word_ge_two : 2 ≤ w := (by decide : 2 ≤ 4).trans x.hw
+
+/-- Initial-state literal packed into a word of the site’s RAM width. -/
+def Input.initialWord : Word w := Fin.ofNat (2^w) x.lit
+
+/-- The public half is exactly the output of `recordStartup_runs`. -/
+def Input.prepared : Stacks Port := Sum.elim (ProcessorPublic.recordResult
+ (ProcessorPublic.rawResult x.prog x.n d (2^e) w x.v x.hdr (incidentBits x.sends x.v))
+ x.n d e w x.u x.lit x.v x.hdr x.hcap x.hw) (fun _ => [])
+
+theorem Input.width_ready : (x.prepared ∘ ports) .width = List.replicate w true := by
+ conv_rhs => rw [x.width_eq]
+ rfl
+
+/-- Both the sent and received successor fields satisfy their respective checks at the selected
+site. -/
+def Input.valid : Prop := SuccessorSendOK x.word_ge_two x.cap_lt x.sends x.v ∧
+ SuccessorReceiveOK x.word_ge_two x.cap_lt x.sends x.v
+
+/-- Actual continuation bank. Every update is local to the named guard ports. -/
+noncomputable def Input.guarded : Stacks Port := installStacks ports x.prepared
+ (Successors.guardResult (Successors.sharedFinish x.cap_lt x.sends x.v (x.prepared ∘ ports)))
+
+@[simp] theorem guarded_at (p : Successors.Port) :
+ x.guarded (ports p) = Successors.guardResult
+ (Successors.sharedFinish x.cap_lt x.sends x.v (x.prepared ∘ ports)) p :=
+ installStacks_at ports_injective _ _ p
+
+theorem guarded_outside (i : Port) (h : ∀ p, ports p ≠ i) : x.guarded i = x.prepared i :=
+ installStacks_outside _ _ h
+
+/-- Step count of the successor-field scan, with predecessor presence determined by whether the
+site address is positive. -/
+def Input.readSteps : ℕ := Successors.steps d w (decide (0 < x.v.val))
+
+open scoped Classical in
+/-- Rejection contributes zero. A valid pair reaches the continuation once, after two guard pops. -/
+theorem checked_count (c : ℕ → Stacks Port → ℕ) (fuel : ℕ) :
+ checked.body.count c (fuel + 2 + x.readSteps) x.prepared =
+ if x.valid then c fuel x.guarded else 0 := by
+ rw [checked, FiniteRoutine.count_onPorts _ _ ports_injective]
+ have h := Successors.checked_shared_count x.word_ge_two x.cap_lt x.sends (x.prepared ∘ ports) x.v x.initialWord
+ rfl rfl x.width_ready rfl rfl rfl rfl (fun _ _ => rfl)
+ (fun f out => c f (installStacks ports x.prepared out)) fuel
+ dsimp only at h
+ by_cases hgood : x.valid
+ · rw [ite_eq_left hgood, ite_eq_left (show SuccessorSendOK _ _ _ _ ∧ SuccessorReceiveOK _ _ _ _ from hgood)] at *
+ exact h
+ · rw [ite_eq_right hgood, ite_eq_right (show ¬ (SuccessorSendOK _ _ _ _ ∧ SuccessorReceiveOK _ _ _ _) from hgood)] at *
+ exact h
+
+/-- Three guard ticks suffice for either rejection path. On a valid pair the extra tick
+is passed to the continuation. -/
+theorem checked_allStops (c : ℕ → Stacks Port → Prop) (fuel : ℕ) :
+ checked.body.AllStops c (fuel + 3 + x.readSteps) x.prepared ↔
+ (x.valid → c (fuel + 1) x.guarded) := by
+ rw [checked, FiniteRoutine.allStops_onPorts _ _ ports_injective]
+ exact Successors.checked_shared_allStops x.word_ge_two x.cap_lt x.sends (x.prepared ∘ ports) x.v x.initialWord
+ rfl rfl x.width_ready rfl rfl rfl rfl (fun _ _ => rfl) _ fuel
+
+theorem checked_runs (h : x.valid) : checked.Runs (x.readSteps + 2) x.prepared x.guarded := by
+ have localRun := Successors.checked_shared_runs x.word_ge_two x.cap_lt x.sends
+ (x.prepared ∘ ports) x.v x.initialWord rfl rfl x.width_ready rfl rfl rfl rfl (fun _ _ => rfl) h
+ have run := Successors.checked.runs_onPorts ports_injective x.prepared localRun
+ rwa [installStacks_eq ports_injective x.prepared (x.prepared ∘ ports) (fun _ => rfl)] at run
+
+/-- Cost, state, record, presence and remaining incident bits at the guard's normal return. -/
+theorem guarded_registers (h : x.valid) :
+ Successors.CutRegisters (x.prepared ∘ ports) (x.guarded ∘ ports) x.word_ge_two
+ (scanSuccessors x.word_ge_two x.cap_lt x.initialWord x.v (sortIncident x.sends x.v)).1
+ ((List.ofFn (incidentBits x.sends x.v)).drop (16*w)) := by
+ have hout : x.guarded ∘ ports = Successors.guardResult
+ (Successors.sharedFinish x.cap_lt x.sends x.v (x.prepared ∘ ports)) := funext (guarded_at x)
+ rw [hout]
+ exact Successors.guarded_cutRegisters x.word_ge_two x.cap_lt x.initialWord x.sends x.v
+ (x.prepared ∘ ports) rfl h.1 h.2
+
+end RAMTape.SiteCutBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteCutSnapshot.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteCutSnapshot.lean
new file mode 100644
index 0000000000..58f4112ce4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteCutSnapshot.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.RAMTapeSiteCutBank
+import OAI.Computability.VPVNP.RAMTapeVirtualSite
+
+/-!
+# The site controller snapshot furnished by the physical parser
+
+The incoming and outgoing cost words are read from the two successor fields.
+Missing fields take their canonical endpoint values, and halted cuts carry a
+zero state word. The other public words come from the computed site address,
+bucket size, public call clock and packed header.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteCutBank
+
+open BurstRAM PrivateRAM ProcessorInput SiteProcessor RAMLayout
+
+variable {d e w p r k : ℕ} (x : Input d e w)
+
+/-- Successor cuts reconstructed from the incident sort messages. -/
+def Input.summary : SiteSuccessors w :=
+ (scanSuccessors x.word_ge_two x.cap_lt x.initialWord x.v (sortIncident x.sends x.v)).1
+
+/-- The cumulative cost word on the selected side of this site. -/
+def Input.sideWord (side : Successors.Side) : Word w :=
+ Fin.ofNat (2^w) (Successors.sideCut x.summary side).cost
+
+theorem Input.sideWord_val (h : x.valid) (side : Successors.Side) :
+ (x.sideWord side).val = (Successors.sideCut x.summary side).cost := by
+ obtain ⟨z, _, hz⟩ := (guarded_registers x h).cost side
+ exact Nat.mod_eq_of_lt (hz ▸ z.isLt)
+
+theorem Input.guarded_cost (h : x.valid) (side : Successors.Side) :
+ x.guarded (ports (.word side 1)) = BurstRAM.wordBits (x.sideWord side) := by
+ obtain ⟨z, hz, he⟩ := (guarded_registers x h).cost side
+ exact hz.trans (congrArg BurstRAM.wordBits (Fin.ext (he.trans (x.sideWord_val h side).symm)))
+
+/-- The live site address in the RAM's full word format. -/
+def Input.addrWord : Word w := SiteRecordWords.addressWord ((Nat.le_add_right d e).trans x.hcap.le) x.v
+
+/-- The four physical header bits packed into one RAM word. -/
+def Input.headerWord : Word w := ProcessorInput.headerWord x.hw x.hdr
+
+/-- A four-bit live header supplies the same verifier as the auxiliary full-word
+header once it has been packed in its prescribed RAM word. -/
+def Input.asWordSite : VirtualSite.Input d e w where
+ fuel := x.n^x.u
+ v := x.v
+ initialWord := x.initialWord
+ headerWord := x.headerWord
+ sends := x.sends
+ hw := x.word_ge_two
+ hc := x.cap_lt
+
+/-- Initial interpreter snapshot for the selected program, operands and private choices. -/
+def Input.bare (T : Template p r k) (pub : Fin k → Word w) (bits : List Bool) : Snapshot w p r k :=
+ x.asWordSite.bare T pub bits
+
+theorem Input.bare_cut (T : Template p r k) (pub : Fin k → Word w) (bits : List Bool) (h : x.valid) :
+ (x.bare T pub bits).tests.cut = x.summary.input := by
+ apply Cut.ext
+ · exact x.sideWord_val h .receive
+ · change (if x.summary.input.state.isSome then some (x.summary.input.state.getD 0) else none) = _
+ cases x.summary.input.state <;> rfl
+
+theorem Input.bare_target (T : Template p r k) (pub : Fin k → Word w) (bits : List Bool) (h : x.valid) :
+ (x.bare T pub bits).tests.target = x.summary.output := by
+ have hc := x.sideWord_val h .send
+ change (x.sideWord .send).val = (x.summary.output.getD ⟨0,none⟩).cost at hc
+ change (if x.summary.output.isSome then some ⟨(x.sideWord .send).val,
+ if (x.summary.output.getD ⟨0,none⟩).state.isSome then some ((x.summary.output.getD ⟨0,none⟩).state.getD 0)
+ else none⟩ else none) = x.summary.output
+ rw [hc]
+ cases x.summary.output with
+ | none => rfl
+ | some c => obtain ⟨c,status⟩ := c; cases status <;> rfl
+
+theorem Input.bare_buffer (T : Template p r k) (pub : Fin k → Word w) (bits : List Bool) :
+ RecordBuffer.Holds x.word_ge_two (2^e) [] (x.bare T pub bits).records :=
+ ⟨Nat.zero_le _, rfl, rfl, rfl, rfl, rfl⟩
+
+end RAMTape.SiteCutBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteEndpointTrim.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteEndpointTrim.lean
new file mode 100644
index 0000000000..28af5fc2e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteEndpointTrim.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.RAMTapeISAPorts
+import OAI.Computability.VPVNP.StructuredStackLoop
+
+/-! # Trimming an endpoint's allocated word
+
+Each unary count mark removes one zero from the front of the allocated word.
+The empty count ends the scan, leaving the remaining word in its original order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteEndpointTrim
+
+open Function Routine
+
+variable {K : Type}
+
+private def popZero (dst : K) :=
+ popCase dst (halt false) ret (halt false)
+
+/-- Trim one leading zero from the destination per unary count mark, rejecting malformed marks
+or destination bits. -/
+def routine (count dst : K) : FiniteRoutine K :=
+ .ofRoutine (popLoop count (fun _ => true) (halt false) (popZero dst))
+
+/-- Removing each zero costs a count pop, a word pop, and a return. One
+final empty count pop terminates the loop. Only the two named stacks change. -/
+theorem run [DecidableEq K] {count dst : K} (hne : count ≠ dst) (s : Stacks K)
+ (n : ℕ) (tail : List Bool) (hc : s count = List.replicate n true)
+ (hd : s dst = List.replicate n false ++ tail) :
+ (routine count dst).Runs (3*n+1) s (update (update s count []) dst tail) := by
+ induction n generalizing s with
+ | zero =>
+ change s count = [] at hc
+ change s dst = tail at hd
+ rw [← hc, update_eq_self, ← hd, update_eq_self]
+ exact Runs.popLoop_empty count (fun _ => true) (halt false) (popZero dst) hc
+ | succ n ih =>
+ rw [List.replicate_succ] at hc
+ rw [List.replicate_succ, List.cons_append] at hd
+ let popped := update s count (List.replicate n true)
+ let mid := update popped dst (List.replicate n false ++ tail)
+ have hword : popped dst = false :: (List.replicate n false ++ tail) :=
+ (update_of_ne hne.symm ..).trans hd
+ have body := runs_popCase_false dst (halt false) ret (halt false) hword (runs_ret mid)
+ have rest := ih mid (by simp [mid, popped, update_of_ne hne]) (update_self ..)
+ have steps := Runs.popLoop_true_continue count (fun _ => true) (halt false) (popZero dst)
+ hc rfl body rest
+ have endState : update (update mid count []) dst tail = update (update s count []) dst tail := by
+ simp only [mid, popped, update_comm hne.symm, update_idem]
+ rw [endState] at steps
+ exact (show 1+(1+1)+(3*n+1) = 3*(n+1)+1 by omega) ▸ steps
+
+end RAMTape.SiteEndpointTrim
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteEndpointWords.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteEndpointWords.lean
new file mode 100644
index 0000000000..a237bcc3b8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteEndpointWords.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+import OAI.Computability.VPVNP.RAMTapeUnaryWordValue
+
+/-!
+# Exact endpoint words for a processor's cost interval
+
+A site numbered `v` with bucket capacity `2^e` checks the two endpoints
+`v * 2^e` and `(v+1) * 2^e`. Padding the site address before incrementing it
+retains the carry of the final site, whose end word equals the global cap.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteEndpoints
+
+open BurstRAM TapeWord
+
+variable {d : ℕ}
+
+/-- Word encoding the start of the site’s cost interval, its address multiplied by the
+power-of-two bucket capacity. -/
+def startWord (e w : ℕ) (v : Word d) (h : d+e < w) : Word w :=
+ ⟨v.val * 2^e, (Nat.mul_le_mul_right _ v.isLt.le).trans_lt
+ ((pow_add 2 d e) ▸ Nat.pow_lt_pow_right (by decide : 1 < 2) h)⟩
+
+/-- Word encoding the end of the site’s cost interval, `(v.val + 1) * 2^e` for site address
+`v`. -/
+def endWord (e w : ℕ) (v : Word d) (h : d+e < w) : Word w :=
+ ⟨(v.val+1) * 2^e, (Nat.mul_le_mul_right _ v.isLt).trans_lt
+ ((pow_add 2 d e) ▸ Nat.pow_lt_pow_right (by decide : 1 < 2) h)⟩
+
+/-- Leave room for a carry out of the original address before shifting. -/
+def padded (e w : ℕ) (v : Word d) := BurstRAM.wordBits v ++ List.replicate (w-(d+e)) false
+
+@[simp] theorem padded_length (e w : ℕ) (v : Word d) (h : d+e < w) :
+ (padded e w v).length = w-e := by simp [padded]; omega
+
+theorem start_bits (e w : ℕ) (v : Word d) (h : d+e < w) :
+ List.replicate e false ++ padded e w v = BurstRAM.wordBits (startWord e w v h) := by
+ apply eq_of_length_value
+ · simp only [List.length_append, List.length_replicate, padded_length _ _ _ h, length_wordBits]
+ omega
+ · simp [padded, startWord, value_append, value_wordBits, Nat.mul_comm]
+
+theorem end_bits (e w : ℕ) (v : Word d) (h : d+e < w) :
+ List.replicate e false ++ (UnaryWord.incScan true (padded e w v)).1 =
+ BurstRAM.wordBits (endWord e w v h) := by
+ have hv : value (padded e w v) = v.val := by simp [padded, value_append, value_wordBits]
+ have room : v.val + 1 < 2^(w-e) := Nat.lt_of_le_of_lt v.isLt
+ (Nat.pow_lt_pow_right (by decide) (by omega : d < w-e))
+ apply eq_of_length_value
+ · simp only [List.length_append, List.length_replicate, UnaryWord.incScan_length,
+ padded_length _ _ _ h, length_wordBits]
+ omega
+ · rw [value_append, value_zeros, List.length_replicate, Nat.zero_add,
+ UnaryWord.incScan_value_of_lt _ _ (by simpa [hv, padded_length _ _ _ h] using room), hv]
+ simp [endWord, value_wordBits, Nat.mul_comm]
+
+end RAMTape.SiteEndpoints
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteEndpoints.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteEndpoints.lean
new file mode 100644
index 0000000000..3be89735ad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteEndpoints.lean
@@ -0,0 +1,192 @@
+import OAI.Computability.VPVNP.RAMTapeMapWord
+import OAI.Computability.VPVNP.RAMTapeSiteEndpointTrim
+import OAI.Computability.VPVNP.RAMTapeSiteEndpointWords
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+import OAI.Computability.VPVNP.RAMTapeWordOperands
+
+/-!
+# Computing the two physical cost endpoints from the site address
+
+Allocate a zero word and remove the public number of cells reserved for the
+address and low shift bits. Prepend the address, copy and increment the
+padded word, then prepend the low zero bits to both results.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteEndpoints
+
+open BurstRAM TapeWord
+
+/-- Ports for the site address, address and bucket exponents, word width, two cost endpoints,
+and trimming scratch. -/
+inductive Port where | address | siteLog | bucketLog | width | startCost | endCost | count | tmp
+ deriving DecidableEq
+instance : Fintype Port := derive_fintype% _
+
+private def incPorts : ScanPort → Port
+ | .left => .startCost
+ | .right => .count
+ | .tmp => .tmp
+ | .out => .endCost
+
+private theorem incPorts_inj : Function.Injective incPorts := by decide
+
+private def incBit (carry b : Bool) := (b ^^ carry, b && carry)
+
+private theorem emitted_inc (carry : Bool) (xs : List Bool) :
+ Operand.emitted incBit carry xs = UnaryWord.incScan carry xs := by
+ induction xs generalizing carry with
+ | nil => rfl
+ | cons b xs ih => simp [Operand.emitted, incBit, UnaryWord.incScan, ih]
+
+private def done : Operand.State Bool → Bool
+ | .done _ => true
+ | _ => false
+
+private def incrementCopy : FiniteRoutine Port :=
+ FiniteRoutine.ofStackCode (Operand.code incBit) incPorts (.clear true) done
+
+private theorem incrementCopy_runs (s : Stacks Port) (hc : s .count = []) (ht : s .tmp = []) :
+ incrementCopy.Runs ((s .endCost).length + 7*(s .startCost).length+3) s
+ (Function.update s .endCost (UnaryWord.incScan true (s .startCost)).1) := by
+ have h := Operand.run incBit true (s .startCost) (s .endCost)
+ rw [emitted_inc] at h
+ apply FiniteRoutine.runs_ofStackCode_framed incPorts_inj (normal := done) rfl rfl
+ (fun q hn => by cases q <;> first | rfl | contradiction) h
+ · intro k
+ cases k <;> first | rfl | exact hc | exact ht
+ · intro k
+ cases k <;> first | rfl | exact hc | exact ht
+ · intro k hk
+ exact Function.update_of_ne (Ne.symm (hk .out)) ..
+
+private def zeros (src dst : Port) := WordCopy.mapWord .tmp dst (fun _ => false) src
+
+private theorem zeros_runs (src dst : Port) (ht : src ≠ .tmp) (hd : src ≠ dst) (hu : .tmp ≠ dst)
+ (s : Stacks Port) (hs : s .tmp = []) :
+ (zeros src dst).Runs (5*(s src).length+2) s
+ (Function.update s dst (List.replicate (s src).length false ++ s dst)) := by
+ simpa only [zeros, List.map_const', List.reverse_replicate] using
+ WordCopy.mapWord_run Port.tmp dst (fun _ => false) ht hd hu s hs
+
+private def copy (src dst : Port) := SuccessorFields.prependCopy src dst .tmp
+
+private theorem copy_runs (src dst : Port) (hd : src ≠ dst) (hs : src ≠ .tmp) (ht : dst ≠ .tmp)
+ (s : Stacks Port) (h : s .tmp = []) :
+ (copy src dst).Runs (5*(s src).length+2) s (Function.update s dst (s src ++ s dst)) :=
+ SuccessorFields.prependCopy_runs src dst .tmp hd hs ht s h
+
+private def localPrepare : FiniteRoutine Port :=
+ (((((((zeros .width .startCost).followedBy (copy .siteLog .count)).followedBy
+ (copy .bucketLog .count)).followedBy (SiteEndpointTrim.routine .count .startCost)).followedBy
+ (copy .address .startCost)).followedBy incrementCopy).followedBy
+ (zeros .bucketLog .startCost)).followedBy (zeros .bucketLog .endCost)
+
+/-- One finite instruction table for every width, site count and bucket size. -/
+def prepare {K : Type} (ports : Port → K) := localPrepare.onPorts ports
+
+/-- Step count for allocating, trimming, incrementing, and shifting the two padded
+cost-endpoint words. -/
+def steps (d e w : ℕ) :=
+ (5*w+2)+(5*d+2)+(5*e+2)+(3*(d+e)+1)+(5*d+2)+(7*(w-e)+3)+(5*e+2)+(5*e+2)
+
+theorem steps_le (d e w : ℕ) (h : d+e < w) : steps d e w ≤ 25*w+16 := by
+ unfold steps
+ omega
+
+private abbrev marks (n : ℕ) := List.replicate n true
+private abbrev zeroBits (n : ℕ) := List.replicate n false
+
+private def bank (address : List Bool) (d e w n : ℕ) (low high : List Bool) : Stacks Port
+ | .address => address
+ | .siteLog => marks d
+ | .bucketLog => marks e
+ | .width => marks w
+ | .count => marks n
+ | .tmp => []
+ | .startCost => low
+ | .endCost => high
+
+private theorem write_count (address : List Bool) (d e w n : ℕ) (low high : List Bool) (m : ℕ) :
+ Function.update (bank address d e w n low high) .count (marks m) = bank address d e w m low high := by
+ funext j; cases j <;> rfl
+
+private theorem write_low (address : List Bool) (d e w n : ℕ) (low high xs : List Bool) :
+ Function.update (bank address d e w n low high) .startCost xs = bank address d e w n xs high := by
+ funext j; cases j <;> rfl
+
+private theorem write_high (address : List Bool) (d e w n : ℕ) (low high xs : List Bool) :
+ Function.update (bank address d e w n low high) .endCost xs = bank address d e w n low xs := by
+ funext j; cases j <;> rfl
+
+private theorem local_prepare_runs {d : ℕ} (v : Word d) (e w : ℕ) (hf : d+e < w) :
+ localPrepare.Runs (steps d e w) (bank (wordBits v) d e w 0 [] [])
+ (bank (wordBits v) d e w 0 (wordBits (startWord e w v hf)) (wordBits (endWord e w v hf))) := by
+ let st := bank (wordBits v) d e w
+ let pad := zeroBits (w-(d+e))
+ let x := padded e w v
+ let y := (UnaryWord.incScan true x).1
+ have z := zeros_runs .width .startCost (by decide) (by decide) (by decide) (st 0 [] []) rfl
+ change (zeros ..).Runs (5*(marks w).length+2) _ (Function.update (st 0 [] []) .startCost
+ (zeroBits (marks w).length ++ [])) at z
+ rw [List.length_replicate, List.append_nil, write_low] at z
+ have c₁ := copy_runs .siteLog .count (by decide) (by decide) (by decide) (st 0 (zeroBits w) []) rfl
+ change (copy ..).Runs (5*(marks d).length+2) _ (Function.update (st 0 (zeroBits w) []) .count
+ (marks d ++ [])) at c₁
+ rw [List.length_replicate, List.append_nil, write_count] at c₁
+ have c₂ := copy_runs .bucketLog .count (by decide) (by decide) (by decide) (st d (zeroBits w) []) rfl
+ change (copy ..).Runs (5*(marks e).length+2) _ (Function.update (st d (zeroBits w) []) .count
+ (marks e ++ marks d)) at c₂
+ rw [List.length_replicate, show marks e ++ marks d = marks (d+e) by rw [← List.replicate_add, Nat.add_comm],
+ write_count] at c₂
+ have hwidth : zeroBits w = zeroBits (d+e) ++ pad := by
+ rw [← List.replicate_add, show d+e+(w-(d+e)) = w by omega]
+ have tr := SiteEndpointTrim.run (count := Port.count) (dst := .startCost) (by decide)
+ (st (d+e) (zeroBits w) []) (d+e) pad rfl hwidth
+ change (SiteEndpointTrim.routine ..).Runs _ _
+ (Function.update (Function.update (st (d+e) (zeroBits w) []) .count (marks 0)) .startCost pad) at tr
+ rw [write_count, write_low] at tr
+ have addr := copy_runs .address .startCost (by decide) (by decide) (by decide) (st 0 pad []) rfl
+ change (copy ..).Runs (5*(wordBits v).length+2) _ (Function.update (st 0 pad []) .startCost x) at addr
+ rw [length_wordBits, write_low] at addr
+ have inc := incrementCopy_runs (st 0 x []) rfl rfl
+ change incrementCopy.Runs (0+7*x.length+3) _ (Function.update (st 0 x []) .endCost y) at inc
+ rw [Nat.zero_add, padded_length _ _ _ hf, write_high] at inc
+ have low := zeros_runs .bucketLog .startCost (by decide) (by decide) (by decide) (st 0 x y) rfl
+ change (zeros ..).Runs (5*(marks e).length+2) _ (Function.update (st 0 x y) .startCost
+ (zeroBits (marks e).length ++ x)) at low
+ rw [List.length_replicate, start_bits _ _ _ hf, write_low] at low
+ have high := zeros_runs .bucketLog .endCost (by decide) (by decide) (by decide)
+ (st 0 (wordBits (startWord e w v hf)) y) rfl
+ change (zeros ..).Runs (5*(marks e).length+2) _ (Function.update _ .endCost
+ (zeroBits (marks e).length ++ y)) at high
+ rw [List.length_replicate, end_bits _ _ _ hf, write_high] at high
+ exact ((((((z.followedBy c₁).followedBy c₂).followedBy tr).followedBy addr).followedBy inc).followedBy
+ low).followedBy high
+
+/-- Compute both cost words, preserve the address and public counters, and
+return both scratch stacks empty. The last site's end word is the global cap. -/
+theorem prepare_runs {K : Type} [DecidableEq K] {d : ℕ} (ports : Port → K) (hp : Function.Injective ports)
+ (s : Stacks K) (v : Word d) (e w : ℕ) (hf : d+e < w)
+ (hv : s (ports .address) = wordBits v) (hd : s (ports .siteLog) = List.replicate d true)
+ (he : s (ports .bucketLog) = List.replicate e true) (hw : s (ports .width) = List.replicate w true)
+ (hstart : s (ports .startCost) = []) (hend : s (ports .endCost) = [])
+ (hc : s (ports .count) = []) (ht : s (ports .tmp) = []) :
+ (prepare ports).Runs (steps d e w) s (Function.update (Function.update s (ports .startCost)
+ (wordBits (startWord e w v hf))) (ports .endCost) (wordBits (endWord e w v hf))) := by
+ apply FiniteRoutine.runs_onPorts_framed localPrepare hp (local_prepare_runs v e w hf)
+ · intro p
+ cases p <;> assumption
+ · intro p
+ cases p <;> simp [bank, hp.eq_iff, hv, hd, he, hw, hc, ht]
+ · intro p h
+ rw [Function.update_of_ne (Ne.symm (h .endCost)), Function.update_of_ne (Ne.symm (h .startCost))]
+
+end RAMTape.SiteEndpoints
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryCPS.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryCPS.lean
new file mode 100644
index 0000000000..48d8bdb3fd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryCPS.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.RAMTapeSiteEntryFrame
+import OAI.Computability.VPVNP.RAMTapeSiteEntryZero
+import OAI.Computability.VPVNP.RAMProcessorChoices
+
+/-!
+# The guarded site entry and its continuation
+
+The two successor fields are checked before the global credit is initialized. On a
+valid site the choice routine exhausts its unary budget and enters the continuation
+once for each permitted bit stream. All such streams leave the same residual clock.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+
+set_option synthInstance.maxSize 256
+
+open BurstRAM LiveProgram
+
+variable {k d e w : ℕ} (r : ℕ) (expr : Fin k → PublicExpr)
+
+private def choices := ProcessorChoices.routine (pub r expr ProcessorPublic.budgetPort)
+ (native r expr (.test .choices))
+
+/-- Check the successor fields, initialize the global credit word, and generate the bounded
+private choice string. -/
+def prepareEntry : FiniteRoutine (Port r expr) :=
+ (SiteCutBank.checked.onPorts (cut r expr)).followedBy
+ ((zeroGlobal r expr).followedBy (.ofRoutine (choices r expr)))
+
+variable (x : SiteCutBank.Input d e w)
+
+/-- Steps for the successor scan and guards, zero-word initialization, and the complete bounded
+choice pass. -/
+def entrySteps : ℕ :=
+ x.readSteps + 2 + (5*w+2) + (4*(2*2^e*(x.n^x.u+w))+1)
+
+/-- Polynomial running time once the public width and bucket fit the physical input. -/
+theorem entrySteps_le (hu : 1 ≤ x.u) (hH : 2^e ≤ 2*x.n) (hw : w ≤ x.n) :
+ entrySteps x ≤ 400*(x.n+1)^(x.u+1) := by
+ have hd : d ≤ x.n := (Nat.le_add_right d e).trans (x.hcap.le.trans hw)
+ have read : x.readSteps ≤ 4*d+234*w+107 := Successors.steps_le _ _ _
+ let M := (x.n+1)^x.u
+ have hn : x.n+1 ≤ M := Nat.le_self_pow (by omega) _
+ have hf : x.n^x.u ≤ M := Nat.pow_le_pow_left (by omega) _
+ have hguess := Nat.mul_le_mul (Nat.mul_le_mul_left 2 hH)
+ (show x.n^x.u+w ≤ 2*M by omega)
+ have hnom : 2*2^e*(x.n^x.u+w) ≤ 8*(x.n+1)^(x.u+1) := by
+ calc
+ _ ≤ (2*(2*x.n))*(2*M) := hguess
+ _ = 8*(M*x.n) := by ring
+ _ ≤ 8*(M*(x.n+1)) := Nat.mul_le_mul_left _ (Nat.mul_le_mul_left _ (by omega))
+ _ = _ := by rw [pow_succ]
+ have hl : x.n+1 ≤ (x.n+1)^(x.u+1) := Nat.le_self_pow (by omega) _
+ unfold entrySteps
+ omega
+
+variable {operands : Fin k → Word w} {s : Stacks (Port r expr)}
+ (hf : Frame r expr x operands s)
+
+include hf
+
+private theorem guardZeroRuns :
+ (zeroGlobal r expr).Runs (5*w+2) (guardBank r expr x s) (zeroBank r expr x s) := by
+ apply zeroGlobal_runs
+ · change guardBank r expr x s (cut r expr (.inl (.inl SiteSetup.zerosPort))) = _
+ rw [guardBank_at, guarded_public_ne x _ (by decide)]
+ conv_rhs => rw [x.width_eq]
+ rfl
+ · rw [guardBank_native]
+ exact hf.natives _
+ · change guardBank r expr x s (cut r expr (.inl (.inr (.scratch 2)))) = []
+ rw [guardBank_at, guarded_public_ne x _ (by decide)]
+ rfl
+
+private theorem zeroBankChoices :
+ Function.update (Function.update (zeroBank r expr x s) (pub r expr ProcessorPublic.budgetPort)
+ (List.replicate (2*2^e*(x.n^x.u+w)) true)) (native r expr (.test .choices)) [] =
+ zeroBank r expr x s := by
+ have hb : zeroBank r expr x s (pub r expr ProcessorPublic.budgetPort) =
+ List.replicate (2*2^e*(x.n^x.u+w)) true := by
+ change Function.update (guardBank r expr x s) _ _ (cut r expr (.inl ProcessorPublic.budgetPort)) = _
+ rw [Function.update_of_ne ((native_ne_cut r expr _ _).symm),
+ guardBank_at, guarded_public_ne x _ (by decide)]
+ rfl
+ have hbits : zeroBank r expr x s (native r expr (.test .choices)) = [] := by
+ change Function.update (guardBank r expr x s) (native r expr (.credit (.budget .globalLeft))) _
+ (native r expr (.test .choices)) = []
+ rw [Function.update_of_ne (by simp [native]), guardBank_native]
+ exact hf.natives _
+ rw [← hb, Function.update_eq_self, ← hbits, Function.update_eq_self]
+
+private theorem choices_count (c : ℕ → Stacks (Port r expr) → ℕ) (t : ℕ) :
+ (choices r expr).count c (t + 4*(2*2^e*(x.n^x.u+w)) + 1) (zeroBank r expr x s) =
+ ((ProcessorChoices.words (2*2^e*(x.n^x.u+w))).map (fun bs => c t (entryBank r expr x s bs))).sum := by
+ have h := ProcessorChoices.count (pub r expr ProcessorPublic.budgetPort)
+ (native r expr (.test .choices)) (by simp [pub, native]) (zeroBank r expr x s)
+ (List.replicate (2*2^e*(x.n^x.u+w)) true) c t
+ simpa only [choices, entryBank, List.length_replicate, zeroBankChoices r expr x hf] using h
+
+private theorem choices_allStops (c : ℕ → Stacks (Port r expr) → Prop) (t : ℕ) :
+ (choices r expr).AllStops c (t + 4*(2*2^e*(x.n^x.u+w)) + 1) (zeroBank r expr x s) ↔
+ ∀ bs : List Bool, bs.length ≤ 2*2^e*(x.n^x.u+w) → c t (entryBank r expr x s bs) := by
+ have h := ProcessorChoices.allStops_iff (pub r expr ProcessorPublic.budgetPort)
+ (native r expr (.test .choices)) (by simp [pub, native]) (zeroBank r expr x s)
+ (List.replicate (2*2^e*(x.n^x.u+w)) true) c t
+ simpa only [choices, entryBank, List.length_replicate, zeroBankChoices r expr x hf] using h
+
+open scoped Classical in
+/-- Invalid successor fields reject. Each valid bounded word enters the continuation
+on the bank containing that word and with exactly the requested residual fuel. -/
+theorem prepare_count (c : ℕ → Stacks (Port r expr) → ℕ) (t : ℕ) :
+ (prepareEntry r expr).body.count c (t + entrySteps x) s =
+ if x.valid then
+ ((ProcessorChoices.words (2*2^e*(x.n^x.u+w))).map (fun bs => c t (entryBank r expr x s bs))).sum
+ else 0 := by
+ let a := SiteCutBank.checked.onPorts (cut r expr)
+ let b := (zeroGlobal r expr).body.followedBy (choices r expr)
+ let u := t + 4*(2*2^e*(x.n^x.u+w)) + 1
+ have he : t + entrySteps x = (u + (5*w+2)) + 2 + x.readSteps := by dsimp [entrySteps, u]; omega
+ change (a.body.followedBy b).count c _ _ = _
+ rw [Routine.count_followedBy, he, FiniteRoutine.count_onPorts _ _ (cut_injective r expr),
+ show s ∘ cut r expr = x.prepared from funext hf.cuts, SiteCutBank.checked_count]
+ by_cases hv : x.valid
+ · simp only [hv, ↓reduceIte]
+ change ((zeroGlobal r expr).body.followedBy (choices r expr)).count c (u + (5*w+2))
+ (guardBank r expr x s) = _
+ rw [Routine.count_followedBy, (guardZeroRuns r expr x hf).count_eq]
+ exact choices_count r expr x hf c t
+ · simp [hv]
+
+/-- The same clock covers all rejecting branches and leaves the same continuation fuel
+on every valid branch. -/
+theorem prepare_allStops (c : ℕ → Stacks (Port r expr) → Prop) (t : ℕ) :
+ (prepareEntry r expr).body.AllStops c (t + entrySteps x) s ↔
+ (x.valid → ∀ bs : List Bool, bs.length ≤ 2*2^e*(x.n^x.u+w) → c t (entryBank r expr x s bs)) := by
+ let a := SiteCutBank.checked.onPorts (cut r expr)
+ let b := (zeroGlobal r expr).body.followedBy (choices r expr)
+ let u := t + 4*(2*2^e*(x.n^x.u+w)) + 1
+ have he : t + entrySteps x = (u + (5*w+1)) + 3 + x.readSteps := by dsimp [entrySteps, u]; omega
+ change (a.body.followedBy b).AllStops c _ _ ↔ _
+ rw [Routine.allStops_followedBy, he, FiniteRoutine.allStops_onPorts _ _ (cut_injective r expr),
+ show s ∘ cut r expr = x.prepared from funext hf.cuts, SiteCutBank.checked_allStops]
+ apply imp_congr_right
+ intro _
+ change ((zeroGlobal r expr).body.followedBy (choices r expr)).AllStops c (u + (5*w+1)+1)
+ (guardBank r expr x s) ↔ _
+ rw [show u+(5*w+1)+1 = u+(5*w+2) by omega, Routine.allStops_followedBy,
+ (guardZeroRuns r expr x hf).allStops_iff]
+ exact choices_allStops r expr x hf c t
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryFrame.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryFrame.lean
new file mode 100644
index 0000000000..75bbf968d1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryFrame.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.RAMTapeSiteProcessorPorts
+
+/-!
+# Frame for installing the cut guard and preparing call inputs
+
+The public operand table populates the native ISA public-word stacks. Its arithmetic scratch
+may contain other data outside the call and cut banks. Only the parsed public fields and the
+initially blank call workspace are relevant to the site-entry proof.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+
+open BurstRAM LiveProgram PublicExprMachine Function
+
+variable {k d e w : ℕ} (r : ℕ) (expr : Fin k → PublicExpr) (x : SiteCutBank.Input d e w)
+
+/-- Physical input precondition. The public vector may already contain literal prefix operands. -/
+structure Frame (args : Fin k → Word w) (s : Stacks (Port r expr)) : Prop where
+ cuts : ∀ i, s (cut r expr i) = x.prepared i
+ natives : ∀ p, s (native r expr p) = match p with
+ | .isa (.pub i) => wordBits (args i)
+ | _ => []
+
+/-- The concrete public expression startup gives this frame directly. -/
+theorem result_frame (g : Geometry) (hw : g.w = w) :
+ let s : Stacks (Port r expr) := Sum.elim
+ (PublicOperandStartup.result r expr g (x.prepared ∘ Sum.inl)) (fun _ => [])
+ Frame r expr x (fun i => packed w ((expr i).eval g)) s := by
+ subst w
+ constructor
+ · rintro (i|i) <;> rfl
+ · intro p
+ cases p with
+ | isa i => cases i <;> rfl
+ | _ => rfl
+
+/-- Install the successor-guard output on its connected ports within the full processor bank. -/
+noncomputable def guardBank (s : Stacks (Port r expr)) : Stacks (Port r expr) :=
+ installStacks (cut r expr) s x.guarded
+
+theorem guardBank_at (s : Stacks (Port r expr)) (i : SiteCutBank.Port) :
+ guardBank r expr x s (cut r expr i) = x.guarded i :=
+ installStacks_at (cut_injective r expr) _ _ i
+
+theorem guardBank_native (s : Stacks (Port r expr)) (p : SiteProcessor.Port r k) :
+ guardBank r expr x s (native r expr p) = s (native r expr p) :=
+ installStacks_outside _ _ (fun i => Ne.symm (native_ne_cut r expr p i))
+
+/-- Guarded bank with a zero word installed in the native global-credit register. -/
+noncomputable def zeroBank (s : Stacks (Port r expr)) : Stacks (Port r expr) :=
+ update (guardBank r expr x s) (native r expr (.credit (.budget .globalLeft))) (wordBits (0 : Word w))
+
+/-- Choice-entry bank with the unary choice budget exhausted and the selected bits on the
+native choice stack. -/
+noncomputable def entryBank (s : Stacks (Port r expr)) (bits : List Bool) : Stacks (Port r expr) :=
+ update (update (zeroBank r expr x s) (pub r expr ProcessorPublic.budgetPort) [])
+ (native r expr (.test .choices)) bits
+
+/-- The read-only public fields keep their original values. The incident field supplies the
+suffix after the two successor messages. -/
+theorem guarded_public_ne (p : ProcessorPublic.Port) (hp : p ≠ ProcessorPublic.incidentPort) :
+ x.guarded (.inl p) = x.prepared (.inl p) := by
+ by_cases h : ∃ j, SiteCutBank.ports j = Sum.inl p
+ · obtain ⟨j, hj⟩ := h
+ rw [← hj, SiteCutBank.guarded_at]
+ cases j with
+ | address | width | cap | initial | tmp | capTmp =>
+ simp only [Successors.guardResult, Successors.sharedFinish, Successors.finish, Successors.afterNormalize]
+ split <;> rfl
+ | incident => exact (hp (Sum.inl.inj hj).symm).elim
+ | outPresent | running | verdict | record | word => contradiction
+ · exact SiteCutBank.guarded_outside _ _ (not_exists.mp h)
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryView.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryView.lean
new file mode 100644
index 0000000000..35aae1f8aa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryView.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.RAMTapeSiteEntryFrame
+import OAI.Computability.VPVNP.RAMTapeSiteCutSnapshot
+
+/-!
+# The call controller's physical input view
+
+Every port of the bare snapshot has its declared value after a successful guard, the zero
+word copy, and the nomination of a choice string. Shared flags and words come from the
+actual guard output. The initialization record's address and value come from the padded
+site words. Both private scratch and the shadow labels of shared registers start empty.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+
+open BurstRAM PrivateRAM LiveProgram Function SiteProcessor
+
+variable {k r p d e w : ℕ} (expr : Fin k → PublicExpr) (x : SiteCutBank.Input d e w)
+ {args : Fin k → Word w} {s : Stacks (Port r expr)}
+
+private theorem entry_aux (bits : List Bool) (j : SiteCutBank.Aux) :
+ entryBank r expr x s bits (cut r expr (.inr j)) = x.guarded (.inr j) := by
+ rw [entryBank, update_of_ne (by simp [cut, native]), update_of_ne (by simp [cut, pub]),
+ zeroBank, update_of_ne (by simp [cut, native]), guardBank_at]
+
+private theorem entry_public (bits : List Bool) (j : ProcessorPublic.Port)
+ (hb : j ≠ ProcessorPublic.budgetPort) (hi : j ≠ ProcessorPublic.incidentPort) :
+ entryBank r expr x s bits (pub r expr j) = x.prepared (.inl j) := by
+ rw [entryBank, update_of_ne (by simp [pub, native]), update_of_ne (by simpa [pub] using hb),
+ zeroBank, update_of_ne (by simp [pub, native])]
+ exact (guardBank_at r expr x s (.inl j)).trans (guarded_public_ne x j hi)
+
+private theorem entry_native (hf : Frame r expr x args s) (bits : List Bool) (i : SiteProcessor.Port r k) :
+ entryBank r expr x s bits (native r expr i) =
+ if i = .test .choices then bits else if i = .credit (.budget .globalLeft) then wordBits (0 : Word w) else
+ match i with | .isa (.pub j) => wordBits (args j) | _ => [] := by
+ by_cases hc : i = .test .choices
+ · subst i; simp [entryBank]
+ · by_cases hg : i = .credit (.budget .globalLeft)
+ · subst i; simp [entryBank, zeroBank, native, pub]
+ · rw [entryBank, update_of_ne (by simpa [native] using hc), update_of_ne (by simp [native, pub]),
+ zeroBank, update_of_ne (by simpa [native] using hg), guardBank_native, hf.natives]
+ simp [hc, hg]
+ cases i with
+ | isa j => cases j <;> rfl
+ | _ => rfl
+
+/-- The physical call ports are the complete bare snapshot, for every nominated bit list. -/
+theorem entry_view (T : Template p r k) (hf : Frame r expr x args s) (h : x.valid) (bits : List Bool) :
+ entryBank r expr x s bits ∘ callPorts r expr = (x.bare T args bits).bare := by
+ have hn := entry_native expr x hf bits
+ have hp := entry_public (s := s) expr x bits
+ have ha := entry_aux (s := s) expr x bits
+ have regs := SiteCutBank.guarded_registers x h
+ funext i
+ change entryBank r expr x s bits (callPorts r expr i) = _
+ cases i with
+ | isa i =>
+ cases i with
+ | persistent => exact (ha _).trans (regs.state .receive)
+ | logPort q => cases q <;> exact hn _
+ | reg | pub | work => exact hn _
+ | credit i =>
+ cases i with
+ | publicH | publicFuel | globalCap => exact hp _ (by decide) (by decide)
+ | budget j =>
+ cases j with
+ | site => exact hp _ (by decide) (by decide)
+ | cost => exact (ha _).trans (x.guarded_cost h .receive)
+ | fuel | call | globalLeft | tmp => exact hn _
+ | savedStart | ordinal | copyA | copyB | arithA | arithB => exact hn _
+ | test i =>
+ cases i with
+ | word j =>
+ cases j with
+ | lower | boundary => exact hp _ (by decide) (by decide)
+ | targetCost => exact (ha _).trans (x.guarded_cost h .send)
+ | targetState => exact (ha _).trans (regs.state .send)
+ | cost | cap | state => exact hn _
+ | bit j =>
+ cases j with
+ | running => exact (ha _).trans (regs.running .receive)
+ | hasTarget => exact (ha _).trans regs.outPresent
+ | targetRunning => exact (ha _).trans (regs.running .send)
+ | choices | verdict | left | right | tmp | out | sourceTmp | copyTmp => exact hn _
+ | record i =>
+ cases i with
+ | field j =>
+ fin_cases j
+ · exact hn _
+ · exact hp _ (by decide) (by decide)
+ · exact hp _ (by decide) (by decide)
+ · exact hn _
+ · exact hn _
+ | zeros =>
+ refine (hp _ (by decide) (by decide)).trans ?_
+ exact congrArg (fun m => List.replicate m false) x.width_eq.symm
+ | remaining => exact hp _ (by decide) (by decide)
+ | temp | reverseBuffer | output => exact hn _
+ | scratch j => exact hn _
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryZero.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryZero.lean
new file mode 100644
index 0000000000..9f658ce48a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteEntryZero.lean
@@ -0,0 +1,41 @@
+import OAI.Computability.VPVNP.RAMTapeSiteProcessorPorts
+
+/-!
+# Initializing the processor's global credit word
+
+The parser leaves a width-sized stack of zero bits. Copying this stack to the
+empty global credit register prepares the word consumed by the credit routine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+
+open BurstRAM LiveProgram
+
+variable {k : ℕ} (r : ℕ) (expr : Fin k → PublicExpr)
+
+/-- Copy the public width-sized zero template into the native global-credit register. -/
+def zeroGlobal : FiniteRoutine (Port r expr) :=
+ SuccessorFields.prependCopy (pub r expr (.inl SiteSetup.zerosPort))
+ (native r expr (.credit (.budget .globalLeft))) (pub r expr (.inr (.scratch 2)))
+
+theorem zeroGlobal_runs (s : Stacks (Port r expr)) (w : ℕ)
+ (hsource : s (pub r expr (.inl SiteSetup.zerosPort)) = List.replicate w false)
+ (hdest : s (native r expr (.credit (.budget .globalLeft))) = [])
+ (htmp : s (pub r expr (.inr (.scratch 2))) = []) :
+ (zeroGlobal r expr).Runs (5*w+2) s
+ (Function.update s (native r expr (.credit (.budget .globalLeft))) (wordBits (0 : Word w))) := by
+ have run := SuccessorFields.prependCopy_runs (pub r expr (.inl SiteSetup.zerosPort))
+ (native r expr (.credit (.budget .globalLeft))) (pub r expr (.inr (.scratch 2)))
+ (by simp [pub, native]) (by simp [pub]) (by simp [native, pub]) s htmp
+ simpa only [zeroGlobal, hsource, hdest, List.append_nil, UnaryWord.zeros_wordBits,
+ length_wordBits] using run
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteFuel.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteFuel.lean
new file mode 100644
index 0000000000..83e6db3fd8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteFuel.lean
@@ -0,0 +1,173 @@
+import OAI.Computability.VPVNP.TallyConstants
+import Mathlib.Tactic.DeriveFintype
+
+/-! # Preparing the private fuel and choice bound on a finite stack machine
+
+At input length `n` each call uses at most `n^u` private instructions. The
+site uses a unary stack for this bound, one for its `2H-1` call credits and one
+for the maximum `2H*(n^u+w)` bits in the canonical choice string. The fixed
+parameter `u` affects only the finite control.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteFuel
+
+open Tally
+
+/-- Unary tallies for input length, bucket size, word width, instruction fuel, call credits,
+choice bits, and arithmetic scratch. -/
+inductive Port where
+ | length | bucket | word | fuel | credit | choice | acc | sum | outer | tmp
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% Port
+
+/-- Initial allowance-computation state containing only the input length, bucket capacity, and
+word width. -/
+def initial (n H w : ℕ) : State Port
+ | .length => n
+ | .bucket => H
+ | .word => w
+ | _ => 0
+
+/-- Intermediate state with the input length raised to the fixed exponent on the fuel counter. -/
+def powered (n H w u : ℕ) : State Port :=
+ Function.update (initial n H w) .fuel (n^u)
+
+/-- State with fuel `n^u`, call credits `2*H - 1`, and choice-string bound `2*H*(n^u + w)` in
+unary. -/
+def result (n H w u : ℕ) : State Port :=
+ Function.update (Function.update (powered n H w u) .credit (2*H-1)) .choice (2*H*(n^u+w))
+
+private def round : Program Port :=
+ (Program.mul .fuel .length .acc .outer .tmp (by decide)).seq <|
+ (Program.clear .fuel).seq <|
+ (Program.copy .acc .fuel .tmp (by decide) (by decide) (by decide)).seq <|
+ Program.clear .acc
+
+/-- Unary program computing the fixed power of the input length by starting with one and
+multiplying in each round. -/
+def power : ℕ → Program Port
+ | 0 => Program.addConst .fuel 1
+ | u+1 => (power u).seq round
+
+private theorem round_eval (n H w u : ℕ) : round.eval (powered n H w u) = powered n H w (u+1) := by
+ funext i
+ cases i <;> simp (config := { decide := true }) [round, powered, initial, pow_succ]
+
+theorem power_eval (n H w u : ℕ) : (power u).eval (initial n H w) = powered n H w u := by
+ induction u with
+ | zero => funext i; cases i <;> simp (config := { decide := true }) [power, powered, initial]
+ | succ u ih => change round.eval ((power u).eval _) = _; rw [ih, round_eval]
+
+private theorem power_ready (n H w u : ℕ) : (power u).ready (initial n H w) := by
+ induction u with
+ | zero => trivial
+ | succ u ih =>
+ simp only [power, Program.seq_ready, ih, true_and, power_eval]
+ simp (config := { decide := true }) [round, powered, initial]
+
+private theorem round_work (n H w u : ℕ) :
+ round.work (powered n H w u) = 12*n^u*n + 8*n^u + 6 := by
+ simp (config := { decide := true }) [round, powered, initial]
+ ring
+
+theorem power_work_le (n H w u : ℕ) :
+ (power u).work (initial n H w) ≤ (26*u+2)*(n+1)^u := by
+ induction u with
+ | zero => simp [power]
+ | succ u ih =>
+ rw [power, Program.seq_work, power_eval, round_work]
+ have hpow : n^u ≤ (n+1)^u := Nat.pow_le_pow_left (Nat.le_succ n) u
+ have hstep : (n+1)^u ≤ (n+1)^(u+1) := Nat.pow_le_pow_right (Nat.succ_pos n) (Nat.le_succ u)
+ have hmul : n^u*n ≤ (n+1)^(u+1) := by
+ rw [pow_succ]
+ exact Nat.mul_le_mul hpow (Nat.le_succ n)
+ have h₁ : 1 ≤ (n+1)^(u+1) := Nat.one_le_pow _ _ (Nat.succ_pos n)
+ have hprev := ih.trans (Nat.mul_le_mul_left _ hstep)
+ have hfu := hpow.trans hstep
+ rw [Nat.mul_succ, show 26*u+26+2 = (26*u+2)+26 by omega, Nat.add_mul]
+ rw [Nat.mul_assoc 12]
+ omega
+
+private def decrement (src : Port) : Program Port where
+ Q := _
+ code := Routine.popCase src Routine.ret Routine.ret Routine.ret
+ eval s := Function.update s src (s src - 1)
+ work _ := 2
+ ready _ := True
+ spec s _ := by
+ cases h : s src with
+ | zero =>
+ have hs := Routine.runs_popCase_empty src Routine.ret Routine.ret Routine.ret
+ (s := encode s) (by simp [encode, h]) (Routine.runs_ret _)
+ have he : Function.update s src (s src-1) = s := by
+ rw [show s src-1 = s src by omega, Function.update_eq_self]
+ rw [h] at he
+ rw [he]
+ exact hs
+ | succ k =>
+ have hs := Routine.runs_popCase_true src Routine.ret Routine.ret Routine.ret
+ (s := encode s) (tail := List.replicate k true) (by simp [encode, h, List.replicate_succ])
+ (Routine.runs_ret _)
+ simpa only [h, Nat.add_sub_cancel, encode_update] using hs
+
+private def bounds : Program Port :=
+ let addBucket := Program.copy Port.bucket Port.credit Port.tmp (by decide) (by decide) (by decide)
+ addBucket.seq <| addBucket.seq <|
+ (Program.copy .fuel .sum .tmp (by decide) (by decide) (by decide)).seq <|
+ (Program.copy .word .sum .tmp (by decide) (by decide) (by decide)).seq <|
+ (Program.mul .credit .sum .choice .outer .tmp (by decide)).seq <|
+ (decrement .credit).seq <| Program.clear .sum
+
+/-- Compute private instruction fuel and use it to prepare the call-credit and choice-string
+tallies. -/
+def program (u : ℕ) : Program Port := (power u).seq bounds
+
+theorem eval_program (n H w u : ℕ) : (program u).eval (initial n H w) = result n H w u := by
+ change bounds.eval ((power u).eval (initial n H w)) = _
+ rw [power_eval]
+ funext i
+ cases i <;> simp (config := { decide := true }) [result, bounds, powered, initial, decrement, two_mul]
+
+theorem runs (n H w u : ℕ) : (program u).code.Runs ((program u).work (initial n H w))
+ (encode (initial n H w)) (encode (result n H w u)) := by
+ apply eval_program n H w u ▸ (program u).spec _
+ simp only [program, Program.seq_ready, power_ready, true_and, power_eval]
+ simp (config := { decide := true }) [bounds, powered, initial, decrement]
+
+theorem bounds_work (n H w u : ℕ) :
+ (program u).work (initial n H w) = (power u).work (initial n H w) +
+ (22*H + 7*n^u + 7*w + 10*H*(n^u+w) + 13) := by
+ simp only [program, Program.seq_work, power_eval, Nat.add_left_cancel_iff]
+ simp (config := { decide := true }) [bounds, powered, initial, decrement]
+ ring
+
+/-- Under the live transcript bounds, constructing all three tallies takes
+a fixed polynomial number of stack instructions. -/
+theorem work_le (n H w u : ℕ) (hu : 1 ≤ u) (hH : H ≤ 2*n) (hw : w ≤ n) :
+ (program u).work (initial n H w) ≤ (26*u+113)*(n+1)^(u+1) := by
+ let B := (n+1)^(u+1)
+ have one : 1 ≤ B := Nat.one_le_pow _ _ (Nat.succ_pos n)
+ have hbase : n+1 ≤ (n+1)^u := Nat.le_self_pow (by omega) _
+ have hp : (n+1)^u ≤ B := Nat.pow_le_pow_right (Nat.succ_pos n) (Nat.le_succ u)
+ have hn : n ≤ (n+1)^u := (Nat.le_succ n).trans hbase
+ have hf : n^u ≤ (n+1)^u := Nat.pow_le_pow_left (Nat.le_succ n) u
+ have hmul : H*(n^u+w) ≤ 4*B := by
+ calc
+ _ ≤ (2*(n+1)) * (2*(n+1)^u) := Nat.mul_le_mul (hH.trans (by omega)) (by omega)
+ _ = _ := by dsimp [B]; rw [pow_succ]; ring
+ have hpower := (power_work_le n H w u).trans (Nat.mul_le_mul_left _ hp)
+ rw [bounds_work, show 26*u+113 = (26*u+2)+111 by omega, Nat.add_mul]
+ change _ ≤ (26*u+2)*B + 111*B
+ rw [Nat.mul_assoc 10 H]
+ omega
+
+end RAMTape.SiteFuel
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteGraphInput.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteGraphInput.lean
new file mode 100644
index 0000000000..3cf8ffc494
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteGraphInput.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.RAMTapeSiteCutSnapshot
+import OAI.Computability.VPVNP.RAMTapeVirtualSiteGraph
+
+/-!
+# The call graph on the parsed site's own incoming and outgoing fields
+
+The controller first emits the compulsory local initialization record. From
+that bank the call loop tests its incoming cost bucket, simulates the private
+instructions, checks the outgoing cut and closes the ordered record buffer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteCutBank
+
+open BurstRAM PrivateRAM RAMSerialization SiteProcessor
+
+variable {d e w p r k : ℕ} (x : Input d e w) (T : Template p r k) (pub : Fin k → Word w) (bits : List Bool)
+
+/-- Compulsory first record built from the parsed address and header words. -/
+def Input.initSlot := SiteProcessor.initRecord x.addrWord x.headerWord
+
+/-- Controller snapshot after fresh-call initialization and staging the address for the
+compulsory record. -/
+def Input.staged : Snapshot w p r k := ((x.bare T pub bits).afterFresh T).withInitFields x.addrWord
+
+/-- Controller snapshot immediately after emitting the site’s compulsory initialization record. -/
+def Input.entered : Snapshot w p r k := (x.staged T pub bits).afterEmit x.word_ge_two x.initSlot
+
+theorem Input.init_run :
+ StackRuns (table T) (25*w+12) (atLabel T .initialRecord) (x.staged T pub bits).bank
+ (atLabel T .checkEntry) (x.entered T pub bits).bank ∧
+ RecordBuffer.Holds x.word_ge_two (2^e) [x.initSlot] (x.entered T pub bits).records :=
+ initialRecord_run T ((x.bare T pub bits).afterFresh T) x.word_ge_two x.addrWord x.headerWord
+ rfl rfl rfl rfl rfl (Nat.two_pow_pos _)
+
+theorem Input.entered_ready :
+ CallReady x.word_ge_two (2^e) (x.n^x.u) true (x.entered T pub bits) [x.initSlot] :=
+ x.asWordSite.entered_ready T pub bits
+
+/-- Abstract site validation for the instantiated program, actual incoming and outgoing
+summaries, and the given private choice bits. -/
+def Input.validated :=
+ validateSite (T.instantiate w pub).program (x.n^x.u) (2^d) (2^e) x.v.val
+ x.summary.input x.summary.output bits
+
+/-- Budget for initial-record emission, all bounded site calls, and closing the padded record
+buffer. -/
+def graphBudget (r w e fuel : ℕ) : ℕ :=
+ 25*w+12+siteWork w (2^e) (perCallEstimate r w (2^e) fuel)+closeWork w (2^e)
+
+/-- Execution outcome matching abstract site validation. Failure reaches rejection, and success
+closes the initialization record followed by the probes in order. -/
+def Input.GraphOutcome (t : ℕ) : Prop :=
+ match x.validated T pub bits with
+ | none => RejectRun (table T) t (atLabel T .initialRecord) (x.staged T pub bits).bank
+ | some rs => ∃ (u : Snapshot w p r k) (ys : List (WordRecord w)), ys.map WordRecord.record =
+ x.initSlot.record :: probeRecords x.summary.input.cost rs ∧
+ StackRuns (table T) t (atLabel T .initialRecord) (x.staged T pub bits).bank
+ (atLabel T .done) (u.afterClose x.word_ge_two (2^e) ys).bank
+
+end RAMTape.SiteCutBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteGraphRun.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteGraphRun.lean
new file mode 100644
index 0000000000..02b1e19119
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteGraphRun.lean
@@ -0,0 +1,31 @@
+import OAI.Computability.VPVNP.RAMTapeSiteGraphInput
+
+/-!
+# Complete physical simulation of a site's capped native burst calls
+
+The fixed graph begins with the initialization slot, starts every call from
+fresh registers and private memory, and observes the real external actions
+of the template. Its unique terminal behavior follows the native validator
+on every possible private choice string.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteCutBank
+
+open BurstRAM PrivateRAM SiteProcessor
+
+variable {d e w p r k : ℕ}
+
+theorem Input.graphOutcome (x : Input d e w) (T : Template p r k) (pub : Fin k → Word w)
+ (bits : List Bool) (_hvalid : x.valid) :
+ ∃ t ≤ graphBudget r w e (x.n^x.u), x.GraphOutcome T pub bits t :=
+ x.asWordSite.graphOutcome T pub bits
+
+end RAMTape.SiteCutBank
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteLiteral.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteLiteral.lean
new file mode 100644
index 0000000000..0304770d98
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteLiteral.lean
@@ -0,0 +1,49 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMTapeWordOperands
+
+/-! # Loading the validator's fixed initial word
+
+The word scan used by the private instruction set also loads a fixed natural
+literal into an arbitrary bank. Its template gives the word width, and the
+two reverse stacks are empty again when the subroutine returns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteLiteral
+
+open BurstRAM TapeWord
+
+variable {K : Type}
+
+private def normal {A : Type} : Operand.State A → Bool
+ | .done _ => true
+ | _ => false
+
+/-- Load a fixed natural literal into a word using the operand scanner on the specified ports. -/
+def routine (lit : ℕ) (ports : ScanPort → K) : FiniteRoutine K :=
+ FiniteRoutine.ofStackCode (Operand.code (Operand.literalBit lit)) ports
+ (.clear (Fin.last lit)) normal
+
+theorem runs [DecidableEq K] {w : ℕ} (lit : ℕ) (ports : ScanPort → K)
+ (hp : Function.Injective ports) (s : Stacks K) (template : Word w)
+ (hs : s (ports .left) = wordBits template) (ht : s (ports .right) = [])
+ (hu : s (ports .tmp) = []) :
+ (routine lit ports).Runs ((s (ports .out)).length+7*w+3) s
+ (Function.update s (ports .out) (wordBits (Fin.ofNat (2^w) lit))) := by
+ obtain ⟨q, h⟩ := Operand.literal_run lit template (s (ports .out))
+ apply FiniteRoutine.runs_ofStackCode_framed hp (normal := normal) rfl (exit := .done q) rfl
+ (fun q hq => by cases q <;> first | rfl | contradiction) h
+ · intro p; cases p <;> first | rfl | exact hs | exact ht | exact hu
+ · intro p
+ cases p <;> simp [Function.update, hp.eq_iff, scanStacks, hs, ht, hu]
+ · intro j hj
+ exact Function.update_of_ne (Ne.symm (hj .out)) ..
+
+end RAMTape.SiteLiteral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteMachine.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteMachine.lean
new file mode 100644
index 0000000000..da5f156069
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteMachine.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.RAMTapeSiteCore
+import OAI.Computability.VPVNP.RAMTapeNamed
+
+/-!
+# Compiling the site's counted stack program into a literal two-tape table
+
+The public reader is run once before the shared guard and private choice
+tree. Only the bank produced by that deterministic startup enters the
+counted computation. The literal table may be supplied as its own input
+prefix, since the instruction table is fixed before that input is formed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+set_option synthInstance.maxSize 10000
+
+open BurstRAM LiveProgram PrivateRAM StackCompiler ProcessorInput
+
+variable {p r k d e w : ℕ}
+
+/-- Sequence deterministic public startup with the site’s guarded, choice-counted verifier. -/
+def linked (expr : Fin k → PublicExpr) (T : Template p r k) (start : FiniteRoutine (Port r expr)) :=
+ start.followedBy (core r expr T)
+
+/-- Processor port initially containing the raw site input for two-tape compilation. -/
+def inputPort (r : ℕ) (expr : Fin k → PublicExpr) := pub r expr ProcessorPublic.rawPort
+
+/-- Compile the linked startup and site verifier to a literal two-tape program with the raw
+input at its designated port. -/
+noncomputable def table (expr : Fin k → PublicExpr) (T : Template p r k)
+ (start : FiniteRoutine (Port r expr)) : UniversalMachine.Program :=
+ let rt := (linked expr T start).body
+ labeledProgram (inputPort r expr) (rt.close false) (some rt.entry)
+
+theorem linked_stack_count (expr : Fin k → PublicExpr) (T : Template p r k) (start : FiniteRoutine (Port r expr))
+ (x : SiteCutBank.Input d e w) (operands : Fin k → Word w) (raw s : Stacks (Port r expr))
+ (steps ticks : ℕ) (hstart : start.Runs steps raw s) (hf : Frame r expr x operands s)
+ (hblank : ∀ j : SitePost.Port, s (.inr (.inr j)) = []) (ht : coreSteps r x + steps ≤ ticks) :
+ let rt := (linked expr T start).body
+ stackPaths (rt.close false) ticks (some rt.entry) raw = x.pathCard T operands ∧
+ StopsWithin (rt.close false) ticks (some rt.entry) raw := by
+ intro rt
+ let rem := ticks-steps
+ have heq : ticks = rem+steps := by dsimp [rem]; omega
+ have hcore := core_spec r expr T x operands s hf hblank rem (by dsimp [rem]; omega)
+ constructor
+ · rw [Routine.stackPaths_close]
+ change (start.body.followedBy (core r expr T).body).count _ ticks raw = _
+ rw [Routine.count_followedBy, heq, hstart.count_eq]
+ exact hcore.1 _
+ · rw [Routine.stopsWithin_close_iff]
+ change (start.body.followedBy (core r expr T).body).AllStops _ ticks raw
+ rw [Routine.allStops_followedBy, heq, hstart.allStops_iff]
+ exact hcore.2 _
+
+theorem table_coefficient (expr : Fin k → PublicExpr) (T : Template p r k)
+ (start : FiniteRoutine (Port r expr)) (x : SiteCutBank.Input d e w) (operands : Fin k → Word w)
+ (s : Stacks (Port r expr)) (steps ticks : ℕ)
+ (fit : Fits (table expr T start) x.n d (2^e) w)
+ (hstart : start.Runs steps (labeledInput (inputPort r expr)
+ (tape (table expr T start) x.n x.v x.hdr (RAMLayout.incidentBits x.sends x.v))) s)
+ (hf : Frame r expr x operands s) (hblank : ∀ j : SitePost.Port, s (.inr (.inr j)) = [])
+ (ht : coreSteps r x + steps ≤ ticks)
+ (hclock : ticks * (6 * (x.n + (Fintype.card (Port r expr)+1) + ticks) + 4) ≤ x.n^clockExponent) :
+ acceptingCount (encode (table expr T start) x.n x.v x.hdr (RAMLayout.incidentBits x.sends x.v) fit) =
+ x.pathCard T operands := by
+ let rt := (linked expr T start).body
+ obtain ⟨count,halt⟩ := linked_stack_count expr T start x operands _ s steps ticks hstart hf hblank ht
+ exact (site_count_labeled (inputPort r expr) (rt.close false) (some rt.entry) x.n ticks x.v x.hdr
+ (RAMLayout.incidentBits x.sends x.v) fit halt hclock).trans count
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSitePost.lean b/lean/OAI/Computability/VPVNP/RAMTapeSitePost.lean
new file mode 100644
index 0000000000..b46ee797d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSitePost.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.RAMTapeSitePostStartup
+import OAI.Computability.VPVNP.RAMTapeSitePostSpec
+
+/-!
+# Exact path count for the finite site memory pass
+
+The post-pass starts with the raw padded records, the two successor payloads
+and the unread sorting suffix. The one fixed table computes the layout and
+executes every sort and predecessor check. Both accepting and rejecting
+executions halt within the same budget.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SitePost
+
+open BurstRAM RAMLayout RAMSort RAMBoundary Boundary
+
+/-- Prepare and run the sorting stages, then check boundary records and all accumulated flags. -/
+def complete : FiniteRoutine Port := prepareSort.followedBy terminal
+
+/-- Step budget covering sorting initialization, all sorting stages, flag tests, and the final
+boundary scan. -/
+def budget (d e w nflags : ℕ) :=
+ SortStartup.cost d (4*2^e) + SortStages.ticks (2+e) d w +
+ (nflags + 2*2^(2+e)*(((2+e)+d+1).choose 2) + 4*d + 96*(2^(2+e)+1)*(w+1) + 7)
+
+variable {d e w : ℕ}
+
+/-- At every time above the explicit cutoff, every continuation sees the same
+closed decision, and every computation path has halted. -/
+theorem complete_spec (hw : 2 ≤ w) (hc : 2^d*2^e<2^w) (b : SendArrays d (2^e) w) (v : Word d)
+ (x : SortReplay.State (2+e) w) (hcanon : SortReplay.CanonicalBlock hw x.1) (prev sent : RawSlot w) :
+ let m := (unpackMessages (parseMessages hw hc b)).memory
+ let start := prestate v prev sent x ((List.ofFn (RAMLayout.incidentBits b v)).drop (16*w))
+ let accepts := x.2.all id = true ∧ SortCanonical hw hc b v ∧ MemoryAt m v (SortReplay.decoded hw x.1)
+ ∀ (_hp : (parsedSlot hw prev).record = RAMBoundary.receive m.lastRecords v)
+ (_hs : v.val+1 < 2^d → (parsedSlot hw sent).record = RAMBoundary.outgoing m.lastRecords v)
+ (_hz : v.val = 0 → (recordBytes prev).all (!·) = true)
+ (_hl : 2^d ≤ v.val+1 → (recordBytes sent).all (!·) = true)
+ (t : ℕ), budget d e w x.2.length ≤ t →
+ (∀ c, complete.body.count c t start = @ite ℕ accepts (Classical.propDecidable _) 1 0) ∧
+ (∀ c, complete.body.AllStops c t start) := by
+ classical
+ intro m start accepts hp hs hz hl t ht
+ obtain ⟨ticks, hTicks, y, run, hflags, hsort, hout⟩ := prepareSort_messages hw hc b v prev sent x hcanon
+ change prepareSort.Runs ticks start (finalBank v prev sent y) at run
+ let k := SiteTerminal.steps d w (2^(2+e)) v y.2
+ have hterm := SiteTerminal.steps_le d w (2^(2+e)) v y.2
+ change k ≤ _ at hterm
+ have hcost : ticks + k ≤ t := by
+ unfold budget at ht
+ omega
+ let extra := t - (ticks + k)
+ have heq : t = (extra+k)+ticks := by dsimp [extra]; omega
+ let ok := decision (decide (0 h (iff.mp hg))
+ rw [ite_eq_right h, hfalse]; rfl)
+ · intro c
+ change (prepareSort.body.followedBy terminal.body).AllStops c t start
+ rw [Routine.allStops_followedBy, heq, run.allStops_iff]
+ exact terminal_total v prev sent y c extra
+
+end RAMTape.SitePost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSitePostBank.lean b/lean/OAI/Computability/VPVNP/RAMTapeSitePostBank.lean
new file mode 100644
index 0000000000..90044be198
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSitePostBank.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.RAMTapeSiteTerminal
+import OAI.Computability.VPVNP.RAMTapeSortStages
+
+/-! # The shared bank for sorting and checking the predecessor records -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SitePost
+
+open BurstRAM RAMBoundary Boundary
+
+/-- Additional post-pass ports for the previous boundary record, sent boundary record, and
+unary address width. -/
+inductive Extra where | previous | sent | addressWidth deriving DecidableEq
+instance : Fintype Extra := derive_fintype% _
+/-- Combined bank for the sorting stages and the boundary-record checks. -/
+abbrev Port := SortStages.Port ⊕ Extra
+
+/-- Extend a sorting bank with serialized predecessor and sent records and the unary address
+width. -/
+def bank {w : ℕ} (d : ℕ) (prev sent : RawSlot w) (s : Stacks SortStages.Port) : Stacks Port :=
+ Sum.elim s fun
+ | .previous => recordBytes prev
+ | .sent => recordBytes sent
+ | .addressWidth => List.replicate d true
+
+private def row (p : SortRow.Port) : Port := .inl (.inr (.inl (.inl (.inl p))))
+
+/-- Port carrying the serialized block currently being sorted or checked. -/
+def blockPort := row .current
+/-- Unary word-width port shared by the sorting row and boundary scanner. -/
+def widthPort := row .width
+/-- Port holding the unary number of slots in the local sorting block. -/
+def slotsPort : Port := .inl (.inr (.inr ()))
+/-- Port collecting the validity flags produced during sorting. -/
+def flagPort := row .flags
+/-- Port holding the site address bits for the sorting pass. -/
+def addressPort : Port := .inl (.inr (.inl (.inl (.inr .site))))
+/-- Port carrying the remaining incident bits to the sorting row’s receive stream. -/
+def incidentPort := row .crossReceive
+/-- Unary site address width retained for initializing the sorting schedule. -/
+def addressWidthPort : Port := .inr .addressWidth
+/-- Port containing the serialized incoming predecessor record. -/
+def previousPort : Port := .inr .previous
+/-- Port containing the serialized record sent at the outgoing boundary. -/
+def sentPort : Port := .inr .sent
+
+/-- Connect the final boundary scanner to the sorted block, endpoint records, word width, saved
+bits, and slot count. -/
+def boundaryPorts : Boundary.Port → Port
+ | .block => blockPort
+ | .previous => previousPort
+ | .sent => sentPort
+ | .width => widthPort
+ | .widthBack => row .widthBack
+ | .saved => row .saved
+ | .slots => slotsPort
+
+private def scanTmp := row .lookup
+
+/-- Run the final site-boundary decision and check the flags collected during sorting. -/
+def terminal : FiniteRoutine Port := SiteTerminal.routine boundaryPorts addressPort scanTmp flagPort
+
+variable {w h d : ℕ}
+
+/-- Sorting and boundary bank at the initial schedule position, with the full incident tail
+available. -/
+def initialBank (v : Word d) (prev sent : RawSlot w) (x : SortReplay.State h w) (tail : List Bool) :=
+ bank d prev sent (SortSchedule.bank (SortStages.data v x tail) (h+d) 0 0)
+
+/-- Sorting and boundary bank at the final schedule position, with the incident tail exhausted. -/
+def finalBank (v : Word d) (prev sent : RawSlot w) (x : SortReplay.State h w) :=
+ bank d prev sent (SortSchedule.bank (SortStages.data v x []) 0 (h+d) 0)
+
+private theorem boundaryPorts_inj : Function.Injective boundaryPorts := by decide
+private theorem flags_disjoint : ∀ j, boundaryPorts j ≠ flagPort := by decide
+
+theorem terminal_count (v : Word d) (prev sent : RawSlot w) (y : SortReplay.State h w)
+ (c : ℕ → Stacks Port → ℕ) (extra : ℕ) :
+ terminal.body.count c (extra+SiteTerminal.steps d w (2^h) v y.2) (finalBank v prev sent y) =
+ (decision (decide (0 first | rfl | simp [boundaryPorts, slotsPort, finalBank, bank,
+ SortSchedule.bank, SortStages.data, SortOneStage.data, SortOneStage.bank, Boundary.store,
+ SiteTerminal.inputs]) c extra
+ simpa only [List.length_ofFn, show finalBank v prev sent y flagPort = y.2 from rfl, terminal] using ht
+
+theorem terminal_total (v : Word d) (prev sent : RawSlot w) (y : SortReplay.State h w)
+ (c : ℕ → Stacks Port → Prop) (extra : ℕ) :
+ terminal.body.AllStops c (extra+SiteTerminal.steps d w (2^h) v y.2) (finalBank v prev sent y) := by
+ have ht := SiteTerminal.total boundaryPorts boundaryPorts_inj addressPort scanTmp flagPort
+ (by decide) flags_disjoint prev sent (List.ofFn y.1) v (finalBank v prev sent y) rfl rfl
+ (by intro j; cases j <;> first | rfl | simp [boundaryPorts, slotsPort, finalBank, bank,
+ SortSchedule.bank, SortStages.data, SortOneStage.data, SortOneStage.bank, Boundary.store,
+ SiteTerminal.inputs]) c extra
+ simpa only [List.length_ofFn, show finalBank v prev sent y flagPort = y.2 from rfl, terminal] using ht
+
+end RAMTape.SitePost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSitePostClock.lean b/lean/OAI/Computability/VPVNP/RAMTapeSitePostClock.lean
new file mode 100644
index 0000000000..ee09273303
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSitePostClock.lean
@@ -0,0 +1,44 @@
+import OAI.Computability.VPVNP.RAMTapeSitePost
+import Mathlib.Data.Nat.Choose.Bounds
+
+/-! # Physical clock for the complete local memory verification -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SitePost
+
+theorem budget_le {n d e w : ℕ} (hn : 4000010 ≤ n) (hH : 2^e ≤ 2*n)
+ (hd : (2+e)+d ≤ n) (hw : w ≤ n) : budget d e w 0 ≤ n^7 := by
+ let B := 2^(2+e)
+ have hB : B = 4*2^e := by dsimp [B]; rw [pow_add]; rfl
+ have hb : B ≤ 8*n := by rw [hB]; omega
+ have hd' : d ≤ n := by omega
+ have sort := SortStages.ticks_le hn hb hd hw
+ have prep := SortStartup.cost_le d (4*2^e)
+ have hprep : SortStartup.cost d (4*2^e) ≤ 388*n := by omega
+ have hc : (((2+e)+d+1).choose 2) ≤ (2*n)^2 :=
+ (Nat.choose_le_pow _ _).trans (Nat.pow_le_pow_left (by omega) _)
+ have hc' := Nat.mul_le_mul (Nat.mul_le_mul_left 2 hb) hc
+ have hflag : 2*B*(((2+e)+d+1).choose 2) ≤ 64*n^3 := by
+ convert hc' using 1; ring
+ have hbound := Nat.mul_le_mul (Nat.mul_le_mul_left 96 (show B+1 ≤ 9*n by omega))
+ (show w+1 ≤ 2*n by omega)
+ have hterm : 96*(B+1)*(w+1) ≤ 1728*n^2 := by convert hbound using 1; ring
+ have hsmall (i : ℕ) (hi : i ≤ 6) : n^i ≤ n^6 := Nat.pow_le_pow_right (by omega) hi
+ have h₁ : n ≤ n^6 := by simpa using hsmall 1 (by decide)
+ have h₂ := hsmall 2 (by decide)
+ have h₃ := hsmall 3 (by decide)
+ have h₄ : 2189*n^6 ≤ n^7 := by
+ rw [show n^7 = n*n^6 by ring]
+ exact Nat.mul_le_mul_right _ (by omega)
+ change SortStartup.cost d (4*2^e) + SortStages.ticks (2+e) d w +
+ (0+2*B*(((2+e)+d+1).choose 2)+4*d+96*(B+1)*(w+1)+7) ≤ n^7
+ omega
+
+end RAMTape.SitePost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSitePostEntry.lean b/lean/OAI/Computability/VPVNP/RAMTapeSitePostEntry.lean
new file mode 100644
index 0000000000..72c28a6a6e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSitePostEntry.lean
@@ -0,0 +1,45 @@
+import OAI.Computability.VPVNP.RAMTapeSitePostLink
+import OAI.Computability.VPVNP.RAMTapeSiteEntryCPS
+
+/-! # The sorter frame at entry for every generated choice stream -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+set_option synthInstance.maxSize 10000
+
+open BurstRAM LiveProgram
+
+variable {d e w k : ℕ} (r : ℕ) (expr : Fin k → PublicExpr) (x : SiteCutBank.Input d e w)
+ {args : Fin k → Word w} {s : Stacks (Port r expr)}
+
+/-- Prepare the post-pass input certificate at private-choice entry from a valid guard, the
+initial frame, and blank sorter scratch. -/
+noncomputable def PostReady.entry (hf : Frame r expr x args s) (hvalid : x.valid)
+ (hblank : ∀ j : SitePost.Port, s (.inr (.inr j)) = []) (bs : List Bool) :
+ PostReady r expr x (entryBank r expr x s bs) := by
+ let hg := PostReady.ofGuarded r expr x (guardBank r expr x s) hvalid (guardBank_at r expr x s)
+ (fun j => (installStacks_outside _ _ (by rintro (u|u) h <;> simp [cut, pub] at h)).trans (hblank j))
+ ((guardBank_native r expr x s _).trans (hf.natives _))
+ refine ⟨hg.previous,hg.sent,hg.previous_eq,hg.sent_eq,?_⟩
+ refine Eq.trans ?_ hg.bank_eq
+ funext j
+ change entryBank r expr x s bs (postPorts r expr j) = guardBank r expr x s (postPorts r expr j)
+ have h₁ : postPorts r expr j ≠ native r expr (.test .choices) := by
+ intro h
+ exact (show (SiteProcessor.Port.test .choices : SiteProcessor.Port r k) ≠ .record .output from nofun)
+ ((postPorts_eq_call_iff r expr j (.test .choices)).mp h).2
+ have h₂ : postPorts r expr j ≠ native r expr (.credit (.budget .globalLeft)) := by
+ intro h
+ exact (show (SiteProcessor.Port.credit (.budget .globalLeft) : SiteProcessor.Port r k) ≠ .record .output from nofun)
+ ((postPorts_eq_call_iff r expr j (.credit (.budget .globalLeft))).mp h).2
+ simp only [entryBank, zeroBank, Function.update_of_ne h₁, Function.update_of_ne h₂,
+ Function.update_of_ne (postPorts_ne_budget r expr j)]
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSitePostLink.lean b/lean/OAI/Computability/VPVNP/RAMTapeSitePostLink.lean
new file mode 100644
index 0000000000..eefed57bbb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSitePostLink.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.RAMTapeSitePostPorts
+import OAI.Computability.VPVNP.RAMTapeSiteProcessorPortsInjective
+
+/-!
+# Preserving the physical post-pass inputs through the call controller
+
+The guarded frame retains the literal sorting suffix and two endpoint
+records while private calls run. Writing a completed call bank into that
+frame replaces the sorting input block by the controller's serialized
+output. No machine parameter depends on the record sequence or edge bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+set_option synthInstance.maxSize 10000
+
+open BurstRAM LiveProgram RAMLayout RAMSerialization RAMMemory
+
+variable {d e w k : ℕ} (r : ℕ) (expr : Fin k → PublicExpr) (x : SiteCutBank.Input d e w)
+
+/-- Received and sent boundary records decoded from the site’s actual successor scan. -/
+def edges := (scanSuccessors x.word_ge_two x.cap_lt x.initialWord x.v (sortIncident x.sends x.v)).1
+
+/-- Physical post-pass bank with the completed block, remaining incident bits, and encoded
+predecessor and sent records. -/
+def postBank (pr sr : Option (WordRecord w)) (block : List Bool) : Stacks SitePost.Port :=
+ SitePost.rawBank d w (4*2^e) (BurstRAM.wordBits x.v) block
+ ((List.ofFn (RAMLayout.incidentBits x.sends x.v)).drop (16*w)) []
+ (List.ofFn ((recordFormat x.word_ge_two).encode pr)) (List.ofFn ((recordFormat x.word_ge_two).encode sr))
+
+/-- Certificate that the post-pass ports contain the two decoded boundary records and the
+required bank before call output is installed. -/
+structure PostReady (s : Stacks (Port r expr)) where
+ /-- Optional predecessor record retained from the guard for the final boundary scan. -/
+ previous : Option (WordRecord w)
+ /-- Optional outgoing record retained from the guard for the final boundary scan. -/
+ sent : Option (WordRecord w)
+ previous_eq : previous.map WordRecord.record = (edges x).received
+ sent_eq : sent.map WordRecord.record = (edges x).sent
+ bank_eq : s ∘ postPorts r expr = postBank x previous sent []
+
+private theorem guard_address :
+ x.guarded (.inl ProcessorPublic.addressPort) = BurstRAM.wordBits x.v := by
+ rw [show (.inl ProcessorPublic.addressPort : SiteCutBank.Port) = SiteCutBank.ports .address from rfl,
+ SiteCutBank.guarded_at]
+ by_cases hp : 0 < x.v.val <;> simp [Successors.guardResult, Successors.sharedFinish,
+ Successors.finish, Successors.afterNormalize, Successors.afterEdge, hp] <;> rfl
+
+private theorem guard_width :
+ x.guarded (.inl ProcessorPublic.widthPort) = List.replicate w true := by
+ rw [show (.inl ProcessorPublic.widthPort : SiteCutBank.Port) = SiteCutBank.ports .width from rfl,
+ SiteCutBank.guarded_at]
+ by_cases hp : 0 < x.v.val <;> simp [Successors.guardResult, Successors.sharedFinish,
+ Successors.finish, Successors.afterNormalize, Successors.afterEdge, hp] <;> exact x.width_ready
+
+private theorem guard_slots :
+ x.guarded (.inl (.inl SiteSetup.slotsPort)) = List.replicate (4*2^e) true := by
+ rw [SiteCutBank.guarded_outside x _ (by decide)]
+ rfl
+
+private theorem guard_addressWidth :
+ x.guarded (.inl ProcessorPublic.addressWidthPort) = List.replicate d true := by
+ rw [SiteCutBank.guarded_outside x _ (by decide)]
+ rfl
+
+/-- The actual guard supplies canonical predecessor words and the untouched
+sorting suffix. Sorting scratch is blank at this point. -/
+noncomputable def PostReady.ofGuarded (s : Stacks (Port r expr)) (hvalid : x.valid)
+ (hc : ∀ i, s (cut r expr i) = x.guarded i)
+ (hblank : ∀ p : SitePost.Port, s (.inr (.inr p)) = [])
+ (hblock : s (native r expr (.record .output)) = []) : PostReady r expr x s := by
+ have hreg := SiteCutBank.guarded_registers x hvalid
+ choose records hm hbits using hreg.record
+ let pr := records .receive
+ let sr := records .send
+ refine ⟨pr, sr, hm .receive, hm .send, ?_⟩
+ have hp : s (cut r expr (.inr (.record .receive))) = List.ofFn ((recordFormat x.word_ge_two).encode pr) := by
+ rw [hc]
+ have h := hbits .receive
+ change x.guarded (.inr (.record .receive)) = List.ofFn ((recordFormat x.word_ge_two).encode pr) ++ [] at h
+ exact h.trans (List.append_nil _)
+ have hs : s (cut r expr (.inr (.record .send))) = List.ofFn ((recordFormat x.word_ge_two).encode sr) := by
+ rw [hc]
+ have h := hbits .send
+ change x.guarded (.inr (.record .send)) = List.ofFn ((recordFormat x.word_ge_two).encode sr) ++ [] at h
+ exact h.trans (List.append_nil _)
+ have inc : s (pub r expr ProcessorPublic.incidentPort) =
+ (List.ofFn (RAMLayout.incidentBits x.sends x.v)).drop (16*w) :=
+ (hc (.inl ProcessorPublic.incidentPort)).trans hreg.incident
+ have addr := (hc (.inl ProcessorPublic.addressPort)).trans (guard_address x)
+ have wid := (hc (.inl ProcessorPublic.widthPort)).trans (guard_width x)
+ have slots := (hc (.inl (.inl SiteSetup.slotsPort))).trans (guard_slots x)
+ have dw := (hc (.inl ProcessorPublic.addressWidthPort)).trans (guard_addressWidth x)
+ funext j
+ rcases j with (c | (((i|z)|o)|u)) | a
+ · cases c <;> exact hblank _
+ · cases i <;> first | exact hblock | exact inc | exact wid | exact hblank _
+ · cases z <;> first | exact addr | exact hblank _
+ · cases o <;> exact hblank _
+ · cases u; exact slots
+ · cases a <;> first | exact hp | exact hs | exact dw
+
+theorem PostReady.after_call {s : Stacks (Port r expr)} (h : PostReady r expr x s)
+ (out : Stacks (SiteProcessor.Port r k)) :
+ installStacks (callPorts r expr) s out ∘ postPorts r expr =
+ postBank x h.previous h.sent (out (.record .output)) := by
+ rw [installCall_post r expr (portsInj := callPorts_injective r expr), h.bank_eq]
+ funext j
+ rcases j with (c | (((i|z)|o)|u)) | a
+ · cases c <;> rfl
+ · cases i <;> rfl
+ · cases z <;> rfl
+ · cases o <;> rfl
+ · cases u; rfl
+ · cases a <;> rfl
+
+/-- At the returned call bank the physical continuation computes the exact
+memory predicate on the emitted reports, regardless of sorting success. -/
+theorem PostReady.complete {s : Stacks (Port r expr)} (h : PostReady r expr x s)
+ (header : ℕ → Word w) (he : (edges x).Spec x.word_ge_two x.cap_lt x.initialWord x.v x.sends)
+ (rs : List (Report w)) (records : List (WordRecord w))
+ (hrecs : records.map WordRecord.record = initRecord header x.v.val :: probeRecords (edges x).input.cost rs)
+ (out : Stacks (SiteProcessor.Port r k))
+ (hout : out (.record .output) = List.ofFn ((blockFormat (2^e) x.word_ge_two).encode (RecordBuffer.slots (2^e) records)))
+ (t : ℕ) (ht : SitePost.budget d e w 0 ≤ t) :
+ let st := installStacks (callPorts r expr) s out
+ (∀ c, (post r expr).body.count c t st =
+ (checkSiteMemory (e := e) x.word_ge_two x.v (header x.v.val) (sortIncident x.sends x.v) (edges x) rs).1.toNat) ∧
+ (∀ c, (post r expr).body.AllStops c t st) := by
+ intro st
+ have hb := h.after_call r expr x out
+ rw [hout] at hb
+ have H := SitePost.complete_records x.word_ge_two x.cap_lt x.sends x.v header x.initialWord
+ (edges x) he rs records hrecs h.previous h.sent h.previous_eq h.sent_eq t ht
+ constructor
+ · intro c
+ rw [post, FiniteRoutine.count_onPorts _ _ (postPorts_injective r expr), show st ∘ postPorts r expr = _ from hb]
+ exact H.1 _
+ · intro c
+ rw [post, FiniteRoutine.allStops_onPorts _ _ (postPorts_injective r expr), show st ∘ postPorts r expr = _ from hb]
+ exact H.2 _
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSitePostPorts.lean b/lean/OAI/Computability/VPVNP/RAMTapeSitePostPorts.lean
new file mode 100644
index 0000000000..207d7ba1e2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSitePostPorts.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.RAMTapeSitePostRecords
+import OAI.Computability.VPVNP.RAMTapeSiteProcessorPorts
+
+/-!
+# Physical connection from the call loop to the local memory pass
+
+The sorter reads the call loop's completed record buffer and the shared
+guard's two predecessor records. Its address, width, slot count and remaining
+incident tape use the original parser registers. All sorting scratch has its
+own labels.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+set_option synthInstance.maxSize 10000
+
+open BurstRAM LiveProgram RAMSerialization RAMBoundary
+variable {k : ℕ} (r : ℕ) (expr : Fin k → PublicExpr)
+
+/-- Connect sorting input to the call loop’s output, reuse the parsed fields and guard records,
+and assign separate ports to sorting scratch. -/
+def postPorts (p : SitePost.Port) : Port r expr :=
+ if p = SitePost.blockPort then native r expr (.record .output) else
+ if p = SitePost.addressPort then pub r expr ProcessorPublic.addressPort else
+ if p = SitePost.incidentPort then pub r expr ProcessorPublic.incidentPort else
+ if p = SitePost.widthPort then pub r expr ProcessorPublic.widthPort else
+ if p = SitePost.slotsPort then pub r expr (.inl SiteSetup.slotsPort) else
+ if p = SitePost.addressWidthPort then pub r expr ProcessorPublic.addressWidthPort else
+ if p = SitePost.previousPort then cut r expr (.inr (.record .receive)) else
+ if p = SitePost.sentPort then cut r expr (.inr (.record .send)) else .inr (.inr p)
+
+private def cutPost (p : SiteCutBank.Port) : Option SitePost.Port :=
+ if p = .inl ProcessorPublic.addressPort then some SitePost.addressPort else
+ if p = .inl ProcessorPublic.incidentPort then some SitePost.incidentPort else
+ if p = .inl ProcessorPublic.widthPort then some SitePost.widthPort else
+ if p = .inl (.inl SiteSetup.slotsPort) then some SitePost.slotsPort else
+ if p = .inl ProcessorPublic.addressWidthPort then some SitePost.addressWidthPort else
+ if p = .inr (.record .receive) then some SitePost.previousPort else
+ if p = .inr (.record .send) then some SitePost.sentPort else none
+
+private def postView : Port r expr → Option SitePost.Port
+ | .inl (.inl (.record .output)) => some SitePost.blockPort
+ | .inl (.inr (.inl p)) => cutPost (.inl p)
+ | .inr (.inl i) => cutPost (.inr i)
+ | .inr (.inr p) => some p
+ | _ => none
+
+private theorem postView_post (p : SitePost.Port) : postView r expr (postPorts r expr p) = some p := by
+ unfold postPorts
+ repeat' first | split <;> rename_i he | subst p <;> rfl
+ all_goals rfl
+
+theorem postPorts_injective : Function.Injective (postPorts r expr) := by
+ intro p q he
+ have := congrArg (postView r expr) he
+ simpa only [postView_post, Option.some.injEq] using this
+
+private theorem postView_call (p : SiteProcessor.Port r k) :
+ postView r expr (callPorts r expr p) =
+ if p = .record .output then some SitePost.blockPort else none := by
+ cases p with
+ | isa i => cases i <;> rfl
+ | credit i => cases i with
+ | budget j => cases j <;> rfl
+ | _ => rfl
+ | test i => cases i with
+ | word j => cases j <;> rfl
+ | bit j => cases j <;> rfl
+ | _ => rfl
+ | record i => cases i with
+ | field j => fin_cases j <;> rfl
+ | _ => rfl
+ | scratch i => rfl
+
+theorem postPorts_eq_call_iff (j : SitePost.Port) (i : SiteProcessor.Port r k) :
+ postPorts r expr j = callPorts r expr i ↔ j = SitePost.blockPort ∧ i = .record .output := by
+ constructor
+ · intro h
+ have eq := congrArg (postView r expr) h
+ rw [postView_post, postView_call] at eq
+ split at eq <;> simp_all
+ · rintro ⟨rfl,rfl⟩; rfl
+
+theorem postPorts_ne_budget (j : SitePost.Port) : postPorts r expr j ≠ pub r expr ProcessorPublic.budgetPort := by
+ intro h
+ have he := congrArg (postView r expr) h
+ rw [postView_post] at he
+ have impossible : some j = none := he
+ cases impossible
+
+/-- A physical call replaces only the occupied input block of the sorter. -/
+theorem installCall_post {portsInj : Function.Injective (callPorts r expr)}
+ (base : Stacks (Port r expr)) (out : Stacks (SiteProcessor.Port r k)) :
+ installStacks (callPorts r expr) base out ∘ postPorts r expr =
+ Function.update (base ∘ postPorts r expr) SitePost.blockPort (out (.record .output)) := by
+ funext j
+ by_cases he : j = SitePost.blockPort
+ · subst j; simp only [Function.update_self, Function.comp_apply]
+ exact installStacks_at portsInj base out (.record .output)
+ · rw [Function.update_of_ne he]
+ exact installStacks_outside _ _ (fun i h => he ((postPorts_eq_call_iff r expr j i).mp h.symm).1)
+
+/-- Run the complete local sorting and memory-checking pass on the processor’s connected ports. -/
+def post (r : ℕ) (expr : Fin k → PublicExpr) : FiniteRoutine (Port r expr) :=
+ SitePost.complete.onPorts (postPorts r expr)
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSitePostRecords.lean b/lean/OAI/Computability/VPVNP/RAMTapeSitePostRecords.lean
new file mode 100644
index 0000000000..a62c835291
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSitePostRecords.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.RAMTapeSitePost
+
+/-! # Applying the physical memory pass to the emitted reports and decoded edge records -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SitePost
+
+open BurstRAM RAMLayout RAMSerialization RAMMemory RAMSort RAMBoundary Boundary
+
+variable {d e w : ℕ}
+
+private theorem record_zero (hw : 2 ≤ w) :
+ (recordBytes ((recordFormat hw).words none)).all (!·) = true := by
+ rw [SortReplay.recordBytes_words, recordFormat_empty]
+ simp
+
+/-- The initial block and both predecessor payloads occupy their physical
+encoding. Under the checked successor relation, the complete finite
+post-pass computes exactly the word-level validator's memory decision. -/
+theorem complete_records (hw : 2 ≤ w) (hc : 2^d*2^e<2^w) (b : SendArrays d (2^e) w)
+ (v : Word d) (header : ℕ → Word w) (initial : Word w) (edges : SiteSuccessors w)
+ (he : edges.Spec hw hc initial v b) (rs : List (Report w)) (records : List (WordRecord w))
+ (hrecs : records.map WordRecord.record = initRecord header v.val :: probeRecords edges.input.cost rs)
+ (pr sr : Option (WordRecord w)) (hp : pr.map WordRecord.record = edges.received)
+ (hs : sr.map WordRecord.record = edges.sent) (t : ℕ) (ht : budget d e w 0 ≤ t) :
+ let raw := rawBank d w (4*2^e) (BurstRAM.wordBits v)
+ (List.ofFn ((blockFormat (2^e) hw).encode (RecordBuffer.slots (2^e) records)))
+ ((List.ofFn (RAMLayout.incidentBits b v)).drop (16*w)) []
+ (List.ofFn ((recordFormat hw).encode pr)) (List.ofFn ((recordFormat hw).encode sr))
+ (∀ c, complete.body.count c t raw =
+ (checkSiteMemory (e := e) hw v (header v) (sortIncident b v) edges rs).1.toNat) ∧
+ (∀ c, complete.body.AllStops c t raw) := by
+ classical
+ intro raw
+ let prev := (recordFormat hw).words pr
+ let sent := (recordFormat hw).words sr
+ let x : SortReplay.State (2+e) w := (SortReplay.emittedBlock hw e records, [])
+ let m := (unpackMessages (parseMessages hw hc b)).memory
+ have hprev : (parsedSlot hw prev).record = RAMBoundary.receive m.lastRecords v := by
+ simpa only [prev, parsedSlot, Format.parse_words] using hp.trans he.received_eq
+ have hsent : (parsedSlot hw sent).record = RAMBoundary.outgoing m.lastRecords v := by
+ simpa only [sent, parsedSlot, Format.parse_words] using hs.trans he.sent_eq
+ have hpz (hv : v.val = 0) : (recordBytes prev).all (!·) = true := by
+ have hn : RAMBoundary.receive m.lastRecords v = none := by
+ rcases v with ⟨i,hi⟩
+ change i = 0 at hv
+ subst i; rfl
+ have hp' : pr = none := Option.map_eq_none_iff.mp (hp.trans (he.received_eq.trans hn))
+ simpa only [prev, hp'] using record_zero (w := w) hw
+ have hsz (hv : 2^d ≤ v.val+1) : (recordBytes sent).all (!·) = true := by
+ have hn : RAMBoundary.outgoing m.lastRecords v = none := by simp [RAMBoundary.outgoing, Nat.not_lt.mpr hv]
+ have hs' : sr = none := Option.map_eq_none_iff.mp (hs.trans (he.sent_eq.trans hn))
+ simpa only [sent, hs'] using record_zero (w := w) hw
+ have spec := complete_spec hw hc b v x (SortReplay.emittedBlock_canonical hw e records) prev sent
+ hprev (fun _ => hsent) hpz hsz t ht
+ let tail := (List.ofFn (RAMLayout.incidentBits b v)).drop (16*w)
+ have hraw : prestate v prev sent x tail = raw := by
+ rw [prestate_eq_raw]
+ simp only [raw, x, tail, prev, sent, SortReplay.emittedBlock_bytes, SortReplay.recordBytes_words]
+ rw [record_width]
+ change (∀ c, complete.body.count c t (prestate v prev sent x tail) = _) ∧
+ (∀ c, complete.body.AllStops c t (prestate v prev sent x tail)) at spec
+ rw [hraw] at spec
+ refine ⟨fun c => (spec.1 c).trans ?_, spec.2⟩
+ let accept := (checkSiteMemory (e := e) hw v (header v) (sortIncident b v) edges rs).1
+ have hiff : accept = true ↔ (x.2.all id = true ∧ SortCanonical hw hc b v ∧ MemoryAt m v (SortReplay.decoded hw x.1)) := by
+ simp only [x, List.all_nil, true_and, SortReplay.decoded_emittedBlock hw header rs records hrecs]
+ exact checkSiteMemory_iff hw hc b v header initial edges he rs
+ let passing := x.2.all id = true ∧ SortCanonical hw hc b v ∧ MemoryAt m v (SortReplay.decoded hw x.1)
+ change (@ite ℕ passing (Classical.propDecidable _) 1 0) = accept.toNat
+ split
+ · rename_i h
+ rw [hiff.mpr h]; rfl
+ · rename_i h
+ have ha : accept = false := Bool.eq_false_iff.mpr (fun hp => h (hiff.mp hp))
+ rw [ha]; rfl
+
+end RAMTape.SitePost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSitePostSpec.lean b/lean/OAI/Computability/VPVNP/RAMTapeSitePostSpec.lean
new file mode 100644
index 0000000000..4fe33b893c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSitePostSpec.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.RAMTapeSitePostBank
+import OAI.Computability.VPVNP.RAMValidatorPost
+
+/-!
+# Correctness of the physical sort and boundary decisions
+
+For the actual shared sorting fields the checked block determines the
+terminal predecessor test. On a passing sorting transcript the physical
+last-slot test therefore compares exactly the replayed block with the
+edge records. A failed comparator contributes zero regardless of that block.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SitePost
+
+open BurstRAM RAMLayout RAMSort RAMBoundary Boundary
+
+variable {d e w : ℕ}
+
+theorem boundary_decision (hw : 2 ≤ w) {B S : ℕ} (hB : 0 < B)
+ (messages : RAMBoundary.Sends S (Word w)) (v : Fin S) (previous sent : RawSlot w)
+ (block : Fin B → RawSlot w)
+ (hp : (parsedSlot hw previous).record = RAMBoundary.receive messages v)
+ (hs : v.val+1 < S → (parsedSlot hw sent).record = RAMBoundary.outgoing messages v)
+ (hzero : v.val = 0 → (recordBytes previous).all (!·) = true)
+ (hlast : S ≤ v.val+1 → (recordBytes sent).all (!·) = true) :
+ decision (decide (0 (parsedSlot hw (block i)).record) := by
+ have iff := Boundary.path_count_checkAt_iff hw hB messages v previous sent block hp hs
+ dsimp only at iff
+ have cnt := Boundary.path_count (decide (0 (iff.mp h).2.1, fun h => iff.mpr ⟨hzero,h,hlast⟩⟩
+
+theorem decision_iff (hw : 2 ≤ w) (hc : 2^d*2^e<2^w) (b : SendArrays d (2^e) w) (v : Word d)
+ (x y : SortReplay.State (2+e) w) (prev sent : RawSlot w) :
+ let ss := phases ((2+e)+d) ((2+e)+d) le_rfl
+ let m := (unpackMessages (parseMessages hw hc b)).memory
+ (y.2.all id = true ↔ x.2.all id = true ∧ SortCanonical hw hc b v ∧ RAMSort.checks v ss
+ (physicalFieldsEquiv.{0,0} (2+e) d _ m.sortSends) (SortReplay.decoded hw x.1)) →
+ (y.2.all id = true → (fun i => (parsedSlot hw (y.1 i)).record) = outputAt m v (SortReplay.decoded hw x.1)) →
+ (parsedSlot hw prev).record = RAMBoundary.receive m.lastRecords v →
+ (v.val+1 < 2^d → (parsedSlot hw sent).record = RAMBoundary.outgoing m.lastRecords v) →
+ (v.val = 0 → (recordBytes prev).all (!·) = true) →
+ (2^d ≤ v.val+1 → (recordBytes sent).all (!·) = true) →
+ ((decision (decide (0 addressWidthPort
+ | .slots => slotsPort
+ | .copy => .inl (.inl .phase)
+ | .tmp => .inl (.inl .tmp)
+ | .rowWidth => rowWidthPort
+ | .remaining => remainingPort
+
+/-- Initialize the local sorting scheduler and row-width counter on the physical post-pass
+bank. -/
+def prepare : FiniteRoutine Port := SortStartup.routine.onPorts preparePorts
+
+variable {d h w : ℕ}
+
+/-- Stack bank before initialization, immediately after the record block
+has been closed and the two successor fields have been extracted. -/
+def prestate (v : Word d) (prev sent : RawSlot w) (x : SortReplay.State h w) (tail : List Bool) : Stacks Port :=
+ Function.update (Function.update (initialBank v prev sent x tail) rowWidthPort []) remainingPort []
+
+theorem prepare_runs (v : Word d) (prev sent : RawSlot w) (x : SortReplay.State h w) (tail : List Bool) :
+ prepare.Runs (SortStartup.cost d (2^h)) (prestate v prev sent x tail) (initialBank v prev sent x tail) := by
+ have hlog : Nat.clog 2 (2^h) = h := Nat.clog_pow _ _ (by decide)
+ apply FiniteRoutine.runs_onPorts_framed _ (by decide : Function.Injective preparePorts) (SortStartup.runs d (2^h))
+ · intro p; cases p <;> rfl
+ · intro p; cases p <;> first | rfl | (simp only [SortStartup.bank, Tally.encode, hlog]; rfl)
+ · intro p hp
+ have hr := Ne.symm (hp .remaining)
+ have hw' := Ne.symm (hp .rowWidth)
+ change p ≠ remainingPort at hr
+ change p ≠ rowWidthPort at hw'
+ simp only [prestate, Function.update_of_ne hr, Function.update_of_ne hw']
+
+/-- The actual nonempty ports at the handoff. The initial block and two
+boundary records may contain arbitrary raw words. -/
+theorem prestate_ports (v : Word d) (prev sent : RawSlot w) (x : SortReplay.State h w) (tail : List Bool) :
+ let s := prestate v prev sent x tail
+ s blockPort = blockBytes (List.ofFn x.1) ∧ s flagPort = x.2 ∧
+ s addressPort = BurstRAM.wordBits v ∧ s widthPort = List.replicate w true ∧
+ s slotsPort = List.replicate (2^h) true ∧ s incidentPort = tail ∧
+ s previousPort = recordBytes prev ∧ s sentPort = recordBytes sent ∧
+ s addressWidthPort = List.replicate d true := by
+ exact ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩
+
+/-- An untyped view of the call-to-sort handoff, for installing these ports
+into the surrounding processor. The other stacks start empty. -/
+def rawBank (d w slots : ℕ) (address block tail flags prev sent : List Bool) : Stacks Port
+ | .inl (.inr (.inl (.inl (.inl .current)))) => block
+ | .inl (.inr (.inl (.inl (.inl .crossReceive)))) => tail
+ | .inl (.inr (.inl (.inl (.inl .flags)))) => flags
+ | .inl (.inr (.inl (.inl (.inl .width)))) => List.replicate w true
+ | .inl (.inr (.inl (.inl (.inr .site)))) => address
+ | .inl (.inr (.inr ())) => List.replicate slots true
+ | .inr .previous => prev
+ | .inr .sent => sent
+ | .inr .addressWidth => List.replicate d true
+ | _ => []
+
+theorem prestate_eq_raw (v : Word d) (prev sent : RawSlot w) (x : SortReplay.State h w) (tail : List Bool) :
+ prestate v prev sent x tail = rawBank d w (2^h) (BurstRAM.wordBits v)
+ (blockBytes (List.ofFn x.1)) tail x.2 (recordBytes prev) (recordBytes sent) := by
+ funext p
+ rcases p with (c | (((r|e)|o)|u)) | extra
+ · cases c <;> rfl
+ · cases r <;> rfl
+ · cases e <;> rfl
+ · cases o <;> rfl
+ · cases u; rfl
+ · cases extra <;> rfl
+
+/-- The sorter shares the predecessor and successor record ports with
+the terminal scan through the surrounding bank. -/
+def prepareSort : FiniteRoutine Port := prepare.followedBy (SortStages.program.onPorts Sum.inl)
+
+theorem prepareSort_run {H : ℕ} (hw : 2 ≤ w) (hslots : 2^h = 4*H)
+ (incident : Fin (width d H w) → Bool) (raw : ℕ → Bool) (hraw : ∀ j : Fin (width d H w), raw j.val = incident j)
+ (v : Word d) (prev sent : RawSlot w) (x : SortReplay.State h w) :
+ ∃ t ≤ SortStartup.cost d (2^h)+SortStages.ticks h d w,
+ prepareSort.Runs t (prestate v prev sent x ((List.ofFn incident).drop (16*w)))
+ (finalBank v prev sent (SortStages.result raw v x)) := by
+ obtain ⟨t, ht, hr⟩ := SortStages.run_incident hw hslots incident raw hraw v x
+ have sort : (SortStages.program.onPorts Sum.inl).Runs t
+ (initialBank v prev sent x ((List.ofFn incident).drop (16*w)))
+ (finalBank v prev sent (SortStages.result raw v x)) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective hr
+ · intro k; rfl
+ · intro k; rfl
+ · rintro (i|e) he
+ · exact (he i rfl).elim
+ · rfl
+ exact ⟨_, Nat.add_le_add_left ht _, (prepare_runs v prev sent x _).followedBy sort⟩
+
+/-- Use exactly the five-word encodings left by the record emitter. -/
+theorem prepareSort_emitted {e : ℕ} (hw : 2 ≤ w) (incident : Fin (width d (2^e) w) → Bool)
+ (raw : ℕ → Bool) (hraw : ∀ j : Fin (width d (2^e) w), raw j.val = incident j)
+ (v : Word d) (prev sent : RawSlot w) (records : List (WordRecord w)) (flags : List Bool) :
+ let x : SortReplay.State (2+e) w := (SortReplay.emittedBlock hw e records, flags)
+ ∃ t ≤ SortStartup.cost d (4*2^e)+SortStages.ticks (2+e) d w,
+ prepareSort.Runs t (prestate v prev sent x ((List.ofFn incident).drop (16*w)))
+ (finalBank v prev sent (SortStages.result raw v x)) := by
+ intro x
+ simpa only [record_width] using prepareSort_run hw (record_width e) incident raw hraw v prev sent x
+
+
+open RAMSort
+
+/-- Starting at the call-to-sort handoff, execute the scheduler and retain
+the two physical boundary records for the final predecessor check. -/
+theorem prepareSort_messages {e : ℕ} (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (b : SendArrays d (2^e) w) (v : Word d) (prev sent : RawSlot w) (x : SortReplay.State (2+e) w)
+ (hcanon : SortReplay.CanonicalBlock hw x.1) :
+ let incident := fun j => (incidentEquiv d (2^e) w b).val (v, (offset d (2^e) w).symm j)
+ let ss := phases ((2+e)+d) ((2+e)+d) le_rfl
+ let mem := (unpackMessages (parseMessages hw hc b)).memory
+ ∃ t ≤ SortStartup.cost d (4*2^e) + SortStages.ticks (2+e) d w, ∃ y : SortReplay.State (2+e) w,
+ prepareSort.Runs t (prestate v prev sent x ((List.ofFn incident).drop (16*w))) (finalBank v prev sent y) ∧
+ y.2.length ≤ x.2.length + 2*2^(2+e)*(((2+e)+d+1).choose 2) ∧
+ (y.2.all id = true ↔ x.2.all id = true ∧ SortCanonical hw hc b v ∧
+ RAMSort.checks v ss (physicalFieldsEquiv.{0,0} (2+e) d _ mem.sortSends) (SortReplay.decoded hw x.1)) ∧
+ (y.2.all id = true → (fun i => (parsedSlot hw (y.1 i)).record) =
+ outputAt mem v (SortReplay.decoded hw x.1)) := by
+ intro incident ss mem
+ have hraw (k : Fin (width d (2^e) w)) : sortIncident b v k.val = incident k := readIncident_at _ k
+ obtain ⟨t, ht, hr⟩ := prepareSort_run hw (record_width e) incident (sortIncident b v) hraw v prev sent x
+ rw [record_width] at ht
+ exact ⟨t, ht, SortStages.result (sortIncident b v) v x, hr, SortStages.result_flags_length _ _ _,
+ SortReplay.fold_messages hw hc b v x hcanon, SortReplay.fold_messages_output hw hc b v x hcanon⟩
+
+end RAMTape.SitePost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteProcessorPorts.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteProcessorPorts.lean
new file mode 100644
index 0000000000..c37290868c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteProcessorPorts.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.RAMTapeSiteCutBank
+import OAI.Computability.VPVNP.RAMTapePublicOperandPorts
+import OAI.Computability.VPVNP.RAMTapeSitePostBank
+
+/-!
+# Physical port names shared by the live processor passes
+
+The call loop reads the same fuel and cost stacks prepared by the parser and the same two
+cut words just checked by the guard. Separate stacks hold the predecessor records, the
+unconsumed incident vector, and the read-only slot count needed by the sorting pass.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+set_option synthInstance.maxSize 10000
+
+open BurstRAM LiveProgram
+
+variable {k : ℕ}
+
+/-- Full site bank combining operand initialization and native execution with guard and sorting
+workspaces. -/
+abbrev Port (r : ℕ) (expr : Fin k → PublicExpr) :=
+ PublicOperandStartup.Port r expr ⊕ (SiteCutBank.Aux ⊕ SitePost.Port)
+
+-- Give the finite sums explicit instances at this nesting depth.
+instance (r : ℕ) (expr : Fin k → PublicExpr) : DecidableEq (Port r expr) :=
+ inferInstanceAs (DecidableEq (PublicOperandStartup.Port r expr ⊕ (SiteCutBank.Aux ⊕ SitePost.Port)))
+
+variable (r : ℕ) (expr : Fin k → PublicExpr)
+
+/-- Embed a parsed public processor port into the full site bank. -/
+def pub (i : ProcessorPublic.Port) : Port r expr := .inl (.inr (.inl i))
+/-- Embed a native private-interpreter port into the full site bank. -/
+def native (p : SiteProcessor.Port r k) : Port r expr := .inl (.inl p)
+
+/-- Connect public guard ports to the parsed fields and private guard ports to their dedicated
+auxiliary stacks. -/
+def cut : SiteCutBank.Port → Port r expr
+ | .inl i => pub r expr i
+ | .inr p => .inr (.inl p)
+
+theorem cut_injective : Function.Injective (cut r expr) := by
+ rintro (i|i) (j|j) h <;> simp [cut, pub] at h ⊢ <;> assumption
+
+theorem native_ne_cut (p : SiteProcessor.Port r k) (i : SiteCutBank.Port) :
+ native r expr p ≠ cut r expr i := by cases i <;> simp [cut, pub, native]
+
+/-- The operand, credit, comparison and record ports that share existing stacks. -/
+def external : SiteProcessor.Port r k → Option SiteCutBank.Port
+ | .isa .persistent => some (.inr (.word .receive 2))
+ | .credit .publicH => some (.inl ProcessorPublic.bucketPort)
+ | .credit .publicFuel => some (.inl ProcessorPublic.fuelPort)
+ | .credit .globalCap => some (.inl ProcessorPublic.capPort)
+ | .credit (.budget .site) => some (.inl ProcessorPublic.creditPort)
+ | .credit (.budget .cost) => some (.inr (.word .receive 1))
+ | .test (.word .lower) => some (.inl ProcessorPublic.startPort)
+ | .test (.word .boundary) => some (.inl ProcessorPublic.endPort)
+ | .test (.word .targetCost) => some (.inr (.word .send 1))
+ | .test (.word .targetState) => some (.inr (.word .send 2))
+ | .test (.bit .running) => some (.inr (.running .receive))
+ | .test (.bit .hasTarget) => some (.inr .outPresent)
+ | .test (.bit .targetRunning) => some (.inr (.running .send))
+ | .record (.field i) => if i = 1 then some (.inl ProcessorPublic.addressWordPort) else
+ if i = 2 then some (.inl ProcessorPublic.headerWordPort) else none
+ | .record .zeros => some (.inl (.inl SiteSetup.zerosPort))
+ | .record .remaining => some (.inl (.inl SiteSetup.remainingPort))
+ | _ => none
+
+/-- Route call-controller ports to their shared public or guard stacks when connected, and
+otherwise to their native stacks. -/
+def callPorts (p : SiteProcessor.Port r k) : Port r expr :=
+ (external r p).elim (native r expr p) (cut r expr)
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteProcessorPortsInjective.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteProcessorPortsInjective.lean
new file mode 100644
index 0000000000..4832ad24f6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteProcessorPortsInjective.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.RAMTapeSiteProcessorPorts
+
+/-! # Recovering call-loop port names from the shared processor bank -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteProcessorPorts
+
+open BurstRAM LiveProgram
+
+/-- Partial inverse of the shared aliases. A `none` identifies a guard or public
+stack lying outside the call loop's image. -/
+def origin (r k : ℕ) : SiteCutBank.Port → Option (SiteProcessor.Port r k)
+ | .inr (.word .receive i) => if i = 1 then some (.credit (.budget .cost)) else
+ if i = 2 then some (.isa .persistent) else none
+ | .inr (.word .send i) => if i = 1 then some (.test (.word .targetCost)) else
+ if i = 2 then some (.test (.word .targetState)) else none
+ | .inr (.running .receive) => some (.test (.bit .running))
+ | .inr (.running .send) => some (.test (.bit .targetRunning))
+ | .inr .outPresent => some (.test (.bit .hasTarget))
+ | .inl (.inr .fuel) => some (.credit .publicFuel)
+ | .inl (.inr .globalCap) => some (.credit .globalCap)
+ | .inl (.inr .callCredit) => some (.credit (.budget .site))
+ | .inl (.inr .startCost) => some (.test (.word .lower))
+ | .inl (.inr .endCost) => some (.test (.word .boundary))
+ | .inl (.inr .addressWord) => some (.record (.field 1))
+ | .inl (.inr .headerWord) => some (.record (.field 2))
+ | .inl (.inl (.inr .zeros)) => some (.record .zeros)
+ | .inl (.inl (.inr .remaining)) => some (.record .remaining)
+ | .inl p => if p = ProcessorPublic.bucketPort then some (.credit .publicH) else none
+ | _ => none
+
+variable {k : ℕ} (r : ℕ) (expr : Fin k → PublicExpr)
+
+private theorem external_origin (p : SiteProcessor.Port r k) :
+ ∀ i, external r p = some i → origin r k i = some p := by
+ have present {p : SiteProcessor.Port r k} {i : SiteCutBank.Port} (hi : external r p = some i)
+ (h : origin r k i = some p) : ∀ j, external r p = some j → origin r k j = some p := by
+ intro j hj
+ rwa [← Option.some.inj (hi.symm.trans hj)]
+ have absent {p : SiteProcessor.Port r k} (hp : external r p = none) :
+ ∀ i, external r p = some i → origin r k i = some p := by simp [hp]
+ cases p with
+ | isa i => cases i <;> first | exact present rfl rfl | exact absent rfl
+ | credit i =>
+ cases i with
+ | budget j => cases j <;> first | exact present rfl rfl | exact absent rfl
+ | _ => first | exact present rfl rfl | exact absent rfl
+ | test i =>
+ cases i with
+ | word j => cases j <;> first | exact present rfl rfl | exact absent rfl
+ | bit j => cases j <;> exact present rfl rfl
+ | _ => exact absent rfl
+ | record i =>
+ cases i with
+ | field j =>
+ by_cases h₁ : j = 1
+ · subst j; exact present rfl rfl
+ by_cases h₂ : j = 2
+ · subst j; exact present rfl rfl
+ exact absent (by simp [external, h₁, h₂])
+ | _ => first | exact present rfl rfl | exact absent rfl
+ | scratch _ => exact absent rfl
+
+/-- Every two distinct logical ports of a call occupy different physical stacks. -/
+theorem callPorts_injective : Function.Injective (callPorts r expr) := by
+ intro p q h
+ cases hp : external r p with
+ | none =>
+ cases hq : external r q with
+ | none => simpa [callPorts, hp, hq, native] using h
+ | some j => exact (native_ne_cut r expr p j (by simpa [callPorts, hp, hq] using h)).elim
+ | some i =>
+ cases hq : external r q with
+ | none => exact (native_ne_cut r expr q i (by simpa [callPorts, hp, hq] using h.symm)).elim
+ | some j =>
+ have hij := cut_injective r expr (by simpa [callPorts, hp, hq] using h)
+ subst j
+ exact Option.some.inj ((external_origin r p i hp).symm.trans (external_origin r q i hq))
+
+/-- Any public or guard register whose inverse entry is vacant survives an entire call. -/
+theorem callPorts_ne_cut_of_origin_none (p : SiteProcessor.Port r k) (i : SiteCutBank.Port)
+ (hi : origin r k i = none) : callPorts r expr p ≠ cut r expr i := by
+ cases hp : external r p with
+ | none => simpa [callPorts, hp] using native_ne_cut r expr p i
+ | some j =>
+ intro h
+ have hji := cut_injective r expr (by simpa [callPorts, hp] using h)
+ subst j
+ simpa [hi] using external_origin r p i hp
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteRecordWords.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteRecordWords.lean
new file mode 100644
index 0000000000..1657f30821
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteRecordWords.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.RAMTapeSiteEndpoints
+import OAI.Computability.VPVNP.RAMSiteInput
+
+/-!
+# Preparing the address and header words for the initial memory record
+
+Allocate `w` zero bits, trim as many cells as the source width, and prepend the low-order
+source bits. For the site address the trim count comes from its public tally. For the
+header a scan counts its four actual cells. Every source and scratch stack is restored.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteRecordWords
+
+open BurstRAM TapeWord Function
+
+/-- Ports for parsed address and header bits, their padded word outputs, public widths, and
+conversion scratch. -/
+inductive Port where | address | header | siteLog | width | addressWord | headerWord | count | tmp
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- The same unsigned site address, represented with `w` bits. -/
+def addressWord {d w : ℕ} (hd : d ≤ w) (v : Word d) : Word w :=
+ ⟨v.val, v.isLt.trans_le (Nat.pow_le_pow_right (by decide) hd)⟩
+
+theorem address_bits {d w : ℕ} (hd : d ≤ w) (v : Word d) :
+ wordBits v ++ List.replicate (w-d) false = wordBits (addressWord hd v) := by
+ apply eq_of_length_value
+ · simp; omega
+ · simp [addressWord, value_append, value_wordBits]
+
+theorem header_bits {w : ℕ} (hw : 4 ≤ w) (hdr : ProcessorInput.Header) :
+ List.ofFn hdr ++ List.replicate (w-4) false = wordBits (ProcessorInput.headerWord hw hdr) := by
+ apply List.ext_getElem
+ · simp; omega
+ · intro i _ hi
+ have hiw : i < w := by simpa using hi
+ by_cases h : i < 4
+ · rw [List.getElem_append_left (by simpa using h)]
+ simp only [BurstRAM.wordBits, List.getElem_ofFn, ProcessorInput.headerWord, Equiv.apply_symm_apply, h, dite_true]
+ · rw [List.getElem_append_right (by simpa using Nat.le_of_not_gt h), List.getElem_replicate]
+ simpa only [BurstRAM.wordBits, List.getElem_ofFn] using
+ (ProcessorInput.headerWord_padding hw hdr ⟨i,hiw⟩ (Nat.le_of_not_gt h)).symm
+
+private inductive Field where | address | header
+private def src : Field → Port | .address => .address | .header => .header
+private def sizeSource : Field → Port | .address => .siteLog | .header => .header
+private def dst : Field → Port | .address => .addressWord | .header => .headerWord
+
+private def extend (f : Field) : FiniteRoutine Port :=
+ (((WordCopy.mapWord .tmp (dst f) (fun _ => false) .width).followedBy
+ (WordCopy.mapWord .tmp .count (fun _ => true) (sizeSource f))).followedBy
+ (SiteEndpointTrim.routine .count (dst f))).followedBy
+ (SuccessorFields.prependCopy (src f) (dst f) .tmp)
+
+private theorem extend_runs (f : Field) (s : Stacks Port) (n w : ℕ) (hn : n ≤ w)
+ (hwidth : s .width = List.replicate w true) (hsize : (s (sizeSource f)).length = n)
+ (hbits : (s (src f)).length = n) (hdst : s (dst f) = []) (hc : s .count = []) (ht : s .tmp = []) :
+ (extend f).Runs (5*w + 13*n + 7) s
+ (update s (dst f) (s (src f) ++ List.replicate (w-n) false)) := by
+ have h₁ : Port.width ≠ dst f := by cases f <;> decide
+ have h₂ : Port.tmp ≠ dst f := by cases f <;> decide
+ have h₃ : sizeSource f ≠ Port.tmp := by cases f <;> decide
+ have h₄ : sizeSource f ≠ Port.count := by cases f <;> decide
+ have h₅ : sizeSource f ≠ dst f := by cases f <;> decide
+ have h₆ : Port.count ≠ dst f := by cases f <;> decide
+ have h₇ : src f ≠ dst f := by cases f <;> decide
+ have h₈ : src f ≠ Port.tmp := by cases f <;> decide
+ let padded := update s (dst f) (List.replicate w false)
+ let counted := update padded .count (List.replicate n true)
+ let tail := List.replicate (w - n) false
+ let trimmed := update s (dst f) tail
+ have hz := WordCopy.mapWord_run Port.tmp (dst f) (fun _ => false) (by decide : Port.width ≠ .tmp)
+ h₁ h₂ s ht
+ simp only [hwidth, hdst, List.map_const', List.length_replicate, List.reverse_replicate,
+ List.append_nil] at hz
+ have hm := WordCopy.mapWord_run Port.tmp Port.count (fun _ => true) h₃ h₄ (by decide) padded
+ (by simpa [padded, h₂] using ht)
+ simp only [padded, update_of_ne h₅, update_of_ne h₆, hc, List.map_const',
+ List.reverse_replicate, List.append_nil, hsize] at hm
+ have hlen : List.replicate w false = List.replicate n false ++ tail := by
+ rw [show tail = List.replicate (w - n) false from rfl, ← List.replicate_add, Nat.add_sub_of_le hn]
+ have htrim := SiteEndpointTrim.run h₆ counted n tail (update_self ..)
+ (by simpa [counted, padded, Ne.symm h₆] using hlen)
+ have hframe : update (update counted .count []) (dst f) tail = trimmed := by
+ funext i
+ by_cases hd : i = dst f <;> by_cases hcount : i = Port.count <;>
+ simp [counted, padded, trimmed, hd, hcount, hc, h₆]
+ rw [hframe] at htrim
+ have hcopy := SuccessorFields.prependCopy_runs (src f) (dst f) Port.tmp h₇ h₈ (Ne.symm h₂)
+ trimmed (by simpa [trimmed, h₂] using ht)
+ simp only [trimmed, update_of_ne h₇, update_self, update_idem, hbits] at hcopy
+ have h := ((hz.followedBy hm).followedBy htrim).followedBy hcopy
+ convert! h using 1
+ omega
+
+/-- The same finite table prepares both words for all public widths. -/
+def prepare {K : Type} (ports : Port → K) : FiniteRoutine K :=
+ ((extend .address).followedBy (extend .header)).onPorts ports
+
+/-- Exact step count for forming the padded address and header words used in the initial
+record. -/
+def steps (d w : ℕ) : ℕ := 10*w + 13*d + 66
+
+theorem steps_le {d w : ℕ} (hd : d ≤ w) : steps d w ≤ 23*w + 66 := by unfold steps; omega
+
+theorem prepare_runs {K : Type} [DecidableEq K] {d w : ℕ} (ports : Port → K) (hp : Injective ports)
+ (s : Stacks K) (v : Word d) (hdr : ProcessorInput.Header) (hd : d ≤ w) (hw : 4 ≤ w)
+ (hv : s (ports .address) = wordBits v) (hh : s (ports .header) = List.ofFn hdr)
+ (hdmarks : s (ports .siteLog) = List.replicate d true)
+ (hwmarks : s (ports .width) = List.replicate w true)
+ (ha : s (ports .addressWord) = []) (hb : s (ports .headerWord) = [])
+ (hc : s (ports .count) = []) (ht : s (ports .tmp) = []) :
+ (prepare ports).Runs (steps d w) s (update (update s (ports .addressWord)
+ (wordBits (addressWord hd v))) (ports .headerWord) (wordBits (ProcessorInput.headerWord hw hdr))) := by
+ let base := s ∘ ports
+ let mid := update base .addressWord (wordBits (addressWord hd v))
+ have h₁ := extend_runs .address base d w hd hwmarks
+ (by simp [base, sizeSource, hdmarks]) (by simp [base, src, hv]) ha hc ht
+ have he₁ : base (src .address) ++ List.replicate (w-d) false = wordBits (addressWord hd v) := by
+ simpa [base, src, hv] using address_bits hd v
+ rw [he₁] at h₁
+ have h₂ := extend_runs .header mid 4 w hw hwmarks (by simp [mid, base, sizeSource, hh])
+ (by simp [mid, base, src, hh]) hb hc ht
+ have he₂ : mid (src .header) ++ List.replicate (w-4) false = wordBits (ProcessorInput.headerWord hw hdr) := by
+ simpa [mid, base, src, hh] using header_bits hw hdr
+ rw [he₂] at h₂
+ have hcost : (5*w+13*d+7) + (5*w+13*4+7) = steps d w := by unfold steps; omega
+ have hrun := h₁.followedBy h₂
+ rw [hcost] at hrun
+ apply FiniteRoutine.runs_onPorts_framed _ hp hrun
+ · intro i; rfl
+ · intro i; cases i <;> simp [mid, base, dst, hp.eq_iff]
+ · intro i hi
+ rw [update_of_ne (Ne.symm (hi .headerWord)), update_of_ne (Ne.symm (hi .addressWord))]
+
+/-- Extend the actual contents of the header source to the indicated word
+width. The source may have any length that fits. -/
+def extendHeader := extend .header
+
+theorem extendHeader_runs (s : Stacks Port) (w : ℕ) (hs : (s .header).length ≤ w)
+ (hwidth : s .width = List.replicate w true) (hd : s .headerWord = [])
+ (hc : s .count = []) (ht : s .tmp = []) :
+ extendHeader.Runs (5*w + 13*(s .header).length + 7) s
+ (update s .headerWord (s .header ++ List.replicate (w - (s .header).length) false)) :=
+ extend_runs .header s _ w hs hwidth rfl rfl hd hc ht
+
+end RAMTape.SiteRecordWords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteSizes.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteSizes.lean
new file mode 100644
index 0000000000..ccafbf9a64
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteSizes.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.RAMTapeInputParametersWidthCost
+
+/-!
+# Preparing the word width and sorting block length after parsing
+
+The validator retains the public address count `d` and bucket size `H`. The
+following fixed pass gives the successor reader its word width and the sorter
+its block length. The input and the two output counts occupy distinct stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.InputWidth
+
+open Tally
+
+private def blockProgram : Program Port :=
+ let add := Program.copy Port.bucket Port.blocks Port.tmp (by decide) (by decide) (by decide)
+ add.seq <| add.seq <| add.seq <| add.seq <| (Program.clear .base).seq (Program.clear .square)
+
+/-- Write the word width and the number of five-word sorting slots. -/
+def siteSizeProgram : Program Port := wordProgram.seq blockProgram
+
+/-- Prepared site-size tallies with word width `(d + 10)^4` and sorting block length `4*H`. -/
+def siteSizes (d H : ℕ) : State Port
+ | .word => (d+10)^4
+ | .blocks => 4*H
+ | p => initial d H p
+
+theorem siteSizes_runs (d H : ℕ) : siteSizeProgram.code.Runs (siteSizeProgram.work (initial d H))
+ (encode (initial d H)) (encode (siteSizes d H)) := by
+ have he : siteSizeProgram.eval (initial d H) = siteSizes d H := by
+ funext p
+ cases p <;> simp (config := { decide := true }) [siteSizeProgram, blockProgram, wordProgram,
+ initial, siteSizes] <;> ring
+ apply he ▸ siteSizeProgram.spec (initial d H)
+ simp (config := { decide := true }) [siteSizeProgram, blockProgram, wordProgram, initial]
+
+theorem siteSizes_work_le (d H : ℕ) :
+ siteSizeProgram.work (initial d H) ≤ 1000*(d+H+11)^7 := by
+ have h₁ : wordProgram.work (initial d H) ≤ 917*(d+H+11)^7 := by
+ exact (show _ ≤ program.work (initial d H) by rw [work_program]; omega).trans (work_le_seventh d H)
+ have he : siteSizeProgram.work (initial d H) =
+ wordProgram.work (initial d H) + (20*H + 10 + 2*(d+10) + 2*(d+10)^2) := by
+ simp only [siteSizeProgram, Program.seq_work, Nat.add_left_cancel_iff]
+ simp (config := { decide := true }) [blockProgram, wordProgram, initial]
+ ring
+ rw [he]
+ let B := d+H+11
+ have hpos : 0 < B := by dsimp [B]; omega
+ have hsmall : d+10 ≤ B := by dsimp [B]; omega
+ have hH : H ≤ B := by dsimp [B]; omega
+ have hB : B ≤ B^7 := by simpa using Nat.pow_le_pow_right hpos (by decide : 1 ≤ 7)
+ have hs : (d+10)^2 ≤ B^7 :=
+ (Nat.pow_le_pow_left hsmall _).trans (Nat.pow_le_pow_right hpos (by decide))
+ change wordProgram.work (initial d H) ≤ 917*B^7 at h₁
+ change _ ≤ 1000*B^7
+ omega
+
+end RAMTape.InputWidth
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSiteTerminal.lean b/lean/OAI/Computability/VPVNP/RAMTapeSiteTerminal.lean
new file mode 100644
index 0000000000..144a28c15d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSiteTerminal.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.RAMTapeBoundary
+import OAI.Computability.VPVNP.RAMTapeSuccessorDispatch
+import OAI.Computability.VPVNP.StructuredStackCount
+import OAI.Computability.VPVNP.StructuredStackTotal
+
+/-!
+# Terminal predecessor check on the actual sorted site tapes
+
+The address selects the missing-edge cases. The record scan adds its verdict
+to the list of flags produced by the sort. A final linear pass halts with the
+conjunction of all of these flags, including after a failed comparison.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteTerminal
+
+open BurstRAM Boundary RAMBoundary
+
+variable {K : Type} [DecidableEq K]
+
+private def branch (ports : Boundary.Port → K) (flags : K) (outgoing incoming : Bool) : FiniteRoutine K :=
+ FiniteRoutine.ofRoutine ({
+ entry := .start
+ code
+ | .done b => .push flags b none
+ | q => (Boundary.code incoming outgoing q).rename ports some
+ } : Routine K Boundary.Phase)
+
+private noncomputable def after (ports : Boundary.Port → K) (s : Stacks K) (hp hs : Bool)
+ {w : ℕ} (previous sent : RawSlot w) (xs : List (RawSlot w)) : Stacks K :=
+ let last := (rows previous xs (hp || (recordBytes previous).all (!·))).1
+ installStacks ports s (store [] (recordBytes (if hs then sent else last)) [] (List.replicate w true) [] [] [])
+
+/-- Prepare the final sorted block, the predecessor and sent boundary records, a unary
+word-width counter and one marker per slot for the boundary scan. -/
+def inputs {w : ℕ} (previous sent : RawSlot w) (xs : List (RawSlot w)) : Stacks Boundary.Port :=
+ store (blockBytes xs) (recordBytes previous) (recordBytes sent) (List.replicate w true) [] []
+ (List.replicate xs.length true)
+
+private theorem branch_runs (ports : Boundary.Port → K) (hi : Function.Injective ports) (flags : K)
+ (hf : ∀ j, ports j ≠ flags) (hp hs : Bool) (s : Stacks K) {w : ℕ} (prev sent : RawSlot w)
+ (xs : List (RawSlot w)) (hb : ∀ j, s (ports j) = inputs prev sent xs j) :
+ (branch ports flags hs hp).Runs (Boundary.work hp hs xs.length w+1) s
+ (Function.update (after ports s hp hs prev sent xs) flags
+ (decision hp hs prev sent xs :: s flags)) := by
+ let r := (branch ports flags hs hp).body
+ have h := (Boundary.runs hp hs prev sent xs).lift ports hi some s (target := r.standalone)
+ (by intro q hq; cases q <;> first | rfl | contradiction)
+ have hin := installStacks_eq hi s (inputs prev sent xs) hb
+ change StackRuns r.standalone _ (some .start) (installStacks ports s (inputs prev sent xs))
+ (some (.done (decision hp hs prev sent xs))) (after ports s hp hs prev sent xs) at h
+ rw [hin] at h
+ have endFlag : after ports s hp hs prev sent xs flags = s flags := installStacks_outside _ _ hf
+ have push := StackStep.push (s := after ports s hp hs prev sent xs) (code := r.standalone)
+ (q := some (.done (decision hp hs prev sent xs)))
+ (show r.standalone (some (.done _)) = .push flags (decision hp hs prev sent xs) none from rfl)
+ rw [endFlag] at push
+ exact h.trans (.cons push (.nil ..))
+
+private def verdicts (flags : K) : FiniteRoutine K :=
+ FiniteRoutine.ofRoutine ({
+ entry := none
+ code
+ | none => .pop flags fun bit => some (if bit.isNone then some true else
+ if bit = some true then none else some false)
+ | some b => .halt b
+ } : Routine K (Option Bool))
+
+private theorem verdicts_count (flags : K) (c : ℕ → Stacks K → ℕ) (extra : ℕ)
+ (xs : List Bool) (s : Stacks K) (hf : s flags = xs) :
+ (verdicts flags).body.count c (extra+xs.length+2) s = (xs.all id).toNat := by
+ induction xs generalizing s extra with
+ | nil =>
+ change (verdicts flags).body.countFrom c ((extra+1)+1) (some none) s = 1
+ change (verdicts flags).body.countFrom c (extra+1) (some (if (s flags).head?.isNone then some true else
+ if (s flags).head? = some true then none else some false)) _ = _
+ rw [hf]; rfl
+ | cons b xs ih =>
+ rw [List.length_cons, show extra+(xs.length+1)+2 = (extra+xs.length+2)+1 by omega]
+ change (verdicts flags).body.countFrom c ((extra+xs.length+2)+1) (some none) s = _
+ change (verdicts flags).body.countFrom c (extra+xs.length+2) (some (if (s flags).head?.isNone then
+ some true else if (s flags).head? = some true then none else some false))
+ (Function.update s flags (s flags).tail) = _
+ rw [hf]
+ cases b with
+ | false => rfl
+ | true => exact ih extra (Function.update s flags xs) (Function.update_self ..)
+
+private theorem verdicts_total (flags : K) (c : ℕ → Stacks K → Prop) (extra : ℕ)
+ (xs : List Bool) (s : Stacks K) (hf : s flags = xs) :
+ (verdicts flags).body.AllStops c (extra+xs.length+2) s := by
+ induction xs generalizing s extra with
+ | nil =>
+ change (verdicts flags).body.AllStopsFrom c ((extra+1)+1) (some none) s
+ change (verdicts flags).body.AllStopsFrom c (extra+1) (some (if (s flags).head?.isNone then some true else
+ if (s flags).head? = some true then none else some false)) _
+ rw [hf]; trivial
+ | cons b xs ih =>
+ rw [List.length_cons, show extra+(xs.length+1)+2 = (extra+xs.length+2)+1 by omega]
+ change (verdicts flags).body.AllStopsFrom c ((extra+xs.length+2)+1) (some none) s
+ change (verdicts flags).body.AllStopsFrom c (extra+xs.length+2) (some (if (s flags).head?.isNone then
+ some true else if (s flags).head? = some true then none else some false))
+ (Function.update s flags (s flags).tail)
+ rw [hf]
+ cases b with
+ | false => trivial
+ | true => exact ih extra (Function.update s flags xs) (Function.update_self ..)
+
+/-- Use the site address to choose the endpoint checks, scan the sorted records, then halt with
+the conjunction of the scan verdict and the accumulated sort flags. -/
+def routine (ports : Boundary.Port → K) (addr tmp flags : K) : FiniteRoutine K :=
+ (SuccessorEnds.dispatch addr tmp (branch ports flags)).followedBy (verdicts flags)
+
+/-- Tick allowance for selecting the endpoint case, checking the sorted records and consuming
+every accumulated verdict flag. -/
+def steps (d w B : ℕ) (v : Word d) (flags : List Bool) : ℕ :=
+ flags.length+3+(4*d+3+(Boundary.work (decide (0 0
+ | some rs => (checkSiteMemory (e := e) x.word_ge_two x.v x.headerWord
+ (sortIncident x.sends x.v) (edges x) rs).1.toNat := by
+ have hgood := (edge_spec x).valid_iff.mpr hv
+ unfold Machine.validateIncident
+ change ((if (edges x).valid then _ else _) : Option (List (Report w)) × ℕ).1.isSome.toNat = _
+ rw [ite_eq_left hgood]
+ dsimp only
+ rw [Machine.runBucket_result]
+ conv_lhs =>
+ pattern validateSite ..
+ change x.validated T pub bits
+ cases x.validated T pub bits with
+ | none => rfl
+ | some rs =>
+ dsimp only
+ change (if (checkSiteMemory (e := e) x.word_ge_two x.v x.headerWord
+ (sortIncident x.sends x.v) (edges x) rs).1 then some rs else none).isSome.toNat = _
+ cases (checkSiteMemory (e := e) x.word_ge_two x.v x.headerWord
+ (sortIncident x.sends x.v) (edges x) rs).1 <;> rfl
+
+/-- Malformed successor fields reject for every private string. -/
+theorem invalid_incident (hv : ¬x.valid) :
+ ((T.instantiate w pub).validateIncident (x.n^x.u) x.initialWord x.headerWord
+ x.word_ge_two x.cap_lt x.v (RAMLayout.incidentBits x.sends x.v) bits).1 = none := by
+ have hbad : ¬ (edges x).valid = true := fun h => hv ((edge_spec x).valid_iff.mp h)
+ unfold Machine.validateIncident
+ change ((if (edges x).valid then _ else _) : Option (List (Report w)) × ℕ).1 = none
+ rw [ite_eq_right hbad]
+
+theorem perChoice_complete (s : Stacks (Port r expr)) (hvalid : x.valid)
+ (hbare : s ∘ callPorts r expr = (x.bare T pub bits).bare)
+ (hready : PostReady r expr x s) (t : ℕ) (ht : perChoiceBudget d e w r (x.n^x.u) ≤ t) :
+ (∀ c, (perChoice r expr T).body.count c t s =
+ ((T.instantiate w pub).validateIncident (x.n^x.u) x.initialWord x.headerWord
+ x.word_ge_two x.cap_lt x.v (RAMLayout.incidentBits x.sends x.v) bits).1.isSome.toNat) ∧
+ (∀ c, (perChoice r expr T).body.AllStops c t s) := by
+ rw [incident_acceptance r x T pub bits hvalid]
+ obtain ⟨m,hm,booted⟩ := SiteProcessor.boot_run T (x.bare T pub bits) x.addrWord rfl rfl
+ change m ≤ r*(8*w+3)+3*(0*(w+1)+1)+2 + (0+0+0+21*w+9) at hm
+ change SiteProcessor.boot.Runs m (x.bare T pub bits).bare (x.staged T pub bits).bank at booted
+ obtain ⟨n,hn,graph⟩ := x.graphOutcome T pub bits hvalid
+ unfold SiteCutBank.Input.GraphOutcome at graph
+ unfold perChoiceBudget at ht
+ have hp := callPorts_injective r expr
+ cases he : x.validated T pub bits with
+ | none =>
+ rw [he] at graph
+ have htime : t = (t-(m+n+1))+(m+n)+1 := by omega
+ have bad := SiteProcessor.callSite_reject T booted graph
+ constructor
+ · intro c
+ change (((SiteProcessor.callSite T).onPorts (callPorts r expr)).body.followedBy
+ (post r expr).body).count c t s = 0
+ rw [Routine.count_followedBy, FiniteRoutine.count_onPorts _ _ hp, hbare, htime]
+ exact (bad.verdict _ (fun _ _ => True) _).1
+ · intro c
+ change (((SiteProcessor.callSite T).onPorts (callPorts r expr)).body.followedBy
+ (post r expr).body).AllStops c t s
+ rw [Routine.allStops_followedBy, FiniteRoutine.allStops_onPorts _ _ hp, hbare, htime]
+ exact (bad.verdict (fun _ _ => 0) _ _).2
+ | some rs =>
+ rw [he] at graph
+ obtain ⟨u, records, hrecords, run⟩ := graph
+ let out := (u.afterClose x.word_ge_two (2^e) records).bank
+ have hr : (SiteProcessor.callSite T).Runs (m+n) (x.bare T pub bits).bare out :=
+ booted.followedBy (SiteProcessor.graphRoutine_run T run)
+ have framed := (SiteProcessor.callSite T).runs_onPorts hp s hr
+ rw [installStacks_eq hp s _ (fun i => congrFun hbare i)] at framed
+ have htime : t = (t-(m+n))+(m+n) := by omega
+ have postVerdict := hready.complete r expr x (fun _ => x.headerWord) (edge_spec x) rs records
+ hrecords out rfl (t-(m+n)) (by omega)
+ constructor
+ · intro c
+ change (((SiteProcessor.callSite T).onPorts (callPorts r expr)).body.followedBy
+ (post r expr).body).count c t s = _
+ rw [Routine.count_followedBy, htime, framed.count_eq]
+ exact postVerdict.1 c
+ · intro c
+ change (((SiteProcessor.callSite T).onPorts (callPorts r expr)).body.followedBy
+ (post r expr).body).AllStops c t s
+ rw [Routine.allStops_followedBy, htime, framed.allStops_iff]
+ exact postVerdict.2 c
+
+end RAMTape.SiteProcessorPorts
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortBoundary.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortBoundary.lean
new file mode 100644
index 0000000000..3daddb352e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortBoundary.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.RAMTapeSortGatherPreserve
+import OAI.Computability.VPVNP.EvaluatorRadixDivision
+
+/-! # The physical block moves between sorting layers
+
+Before a cross-site layer, split the outgoing block off the incident stream.
+The received block and all later fields stay in order on the incident stack.
+After the row loop, release the previous local block and expose the accumulated
+next block in increasing row order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortBoundary
+
+open EvaluatorRadixDivision (reverseOnto reverseOnto_runs)
+
+/-- Stacks holding the current and next blocks, sent and received incident data, word width,
+slot count and two temporary buffers. -/
+inductive Port where
+ | current | next | crossSend | crossReceive | width | slots | scratch1 | scratch2
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+private def gatherPorts : SortGather.Port → Port
+ | .block => .crossReceive
+ | .offset => .scratch1
+ | .width => .width
+ | .widthBack => .crossSend
+ | .saved => .scratch2
+ | .recordBack => .current
+ | .output => .next
+
+private theorem injective_gatherPorts : Function.Injective gatherPorts := by
+ intro i j h
+ cases i <;> cases j <;> first | rfl | cases h
+
+private def copySlots := SuccessorFields.prependCopy Port.slots .scratch1 .scratch2
+
+/-- Separate the leading block of the incident stream in forward bit order. -/
+def splitCross : FiniteRoutine Port :=
+ (copySlots.followedBy (SortGather.skip.onPorts gatherPorts)).followedBy
+ (reverseOnto .scratch2 .crossSend)
+
+/-- Tick cost for separating a complete outgoing block of five-word records from the incident
+stream and restoring it in forward bit order. -/
+def splitCost (slots w : ℕ) := slots*(40*w+17)+4
+
+theorem splitCross_runs (n w : ℕ) (s : Stacks Port) (data tail : List Bool)
+ (hlen : data.length = n*(5*w)) (hb : s .crossReceive = data ++ tail)
+ (hc : s .crossSend = []) (hw : s .width = List.replicate w true)
+ (hn : s .slots = List.replicate n true) (ht : s .scratch1 = []) (hu : s .scratch2 = []) :
+ splitCross.Runs (splitCost n w) s
+ (Function.update (Function.update s .crossReceive tail) .crossSend data) := by
+ let m := Function.update s Port.scratch1 (List.replicate n true)
+ have copy := SuccessorFields.prependCopy_runs Port.slots .scratch1 .scratch2
+ (by decide) (by decide) (by decide) s hu
+ rw [hn, ht, List.append_nil, List.length_replicate] at copy
+ let u := Function.update (Function.update s Port.crossReceive tail) .scratch2 data.reverse
+ have move := SortGather.skip_runs w n data tail [] (s .current) (s .next) hlen
+ simp only [List.append_nil] at move
+ have lifted : (SortGather.skip.onPorts gatherPorts).Runs (n*(30*w+12)+1) m u := by
+ apply SortGather.skip.runs_onPorts_framed injective_gatherPorts move
+ · intro j
+ cases j <;> simp [gatherPorts, SortGather.store, m, hb, hw, hu, hc]
+ · intro j
+ cases j <;> simp [gatherPorts, SortGather.store, u, ht, hw, hc]
+ · intro j hj
+ have h₁ := Ne.symm (hj .block)
+ have h₂ := Ne.symm (hj .saved)
+ have h₃ := Ne.symm (hj .offset)
+ simp only [gatherPorts] at h₁ h₂ h₃
+ simp [u, m, h₁, h₂, h₃]
+ let out := Function.update (Function.update s Port.crossReceive tail) .crossSend data
+ have rewind := reverseOnto_runs (src := Port.scratch2) (dst := .crossSend) (by decide) u out
+ (by simp [out, hu]) (by simp [u, out, hc]) (by
+ intro j h₁ h₂
+ simp [u, out, h₁, h₂])
+ simp only [u, Function.update_self, List.length_reverse, hlen] at rewind
+ have h := (FiniteRoutine.Runs.followedBy copy lifted).followedBy rewind
+ unfold splitCross copySlots
+ convert h using 1
+ unfold splitCost
+ ring
+
+private def clearCurrent : FiniteRoutine Port := .ofRoutine {
+ entry := ()
+ code := fun _ => .pop .current fun b => b.map fun _ => () }
+
+private theorem clearCurrent_runs (s : Stacks Port) :
+ clearCurrent.Runs ((s .current).length+1) s (Function.update s .current []) := by
+ generalize hx : s Port.current = xs
+ induction xs generalizing s with
+ | nil =>
+ have hp := StackStep.pop (s := s) (code := clearCurrent.body.standalone)
+ (q := some clearCurrent.body.entry)
+ (show clearCurrent.body.standalone (some clearCurrent.body.entry) =
+ .pop .current (fun b => b.map fun _ => ()) from rfl)
+ rw [hx] at hp
+ exact .cons hp (.nil ..)
+ | cons b xs ih =>
+ have hp := StackStep.pop (s := s) (code := clearCurrent.body.standalone)
+ (q := some clearCurrent.body.entry)
+ (show clearCurrent.body.standalone (some clearCurrent.body.entry) =
+ .pop .current (fun b => b.map fun _ => ()) from rfl)
+ rw [hx] at hp
+ have hr := ih (Function.update s .current xs) (Function.update_self ..)
+ rw [Function.update_idem] at hr
+ exact .cons hp hr
+
+/-- Install the completed row outputs as the input of the following layer. -/
+def advance : FiniteRoutine Port := clearCurrent.followedBy (reverseOnto .next .current)
+
+theorem advance_runs (s : Stacks Port) :
+ advance.Runs ((s .current).length + 2*(s .next).length + 2) s
+ (Function.update (Function.update s .next []) .current (s .next).reverse) := by
+ let m := Function.update s Port.current []
+ let out := Function.update (Function.update s Port.next []) .current (s .next).reverse
+ have move := reverseOnto_runs (src := Port.next) (dst := .current) (by decide) m out
+ (by simp [out]) (by simp [out, m]) (by intro j h₁ h₂; simp [m, out, h₁, h₂])
+ have h := FiniteRoutine.Runs.followedBy (clearCurrent_runs s) move
+ change advance.Runs ((s .current).length+1+(2*(s .next).length+1)) s out at h
+ exact (show (s .current).length+1+(2*(s .next).length+1) = (s .current).length+2*(s .next).length+2
+ by omega) ▸ h
+
+end RAMTape.SortBoundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortClock.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortClock.lean
new file mode 100644
index 0000000000..3c9723cc6e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortClock.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.RAMTapeSortOneStageModel
+import OAI.Computability.VPVNP.RAMParameters
+
+/-! # Pathwise clock for the physical sorting passes -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortStages
+
+open BurstRAM Filter
+
+/-- Includes every phase update, row scan, split and array reversal. -/
+def ticks (h d w : ℕ) :=
+ (h+d)*((SortOneStage.budget h d w+6)*(h+d)+5)+1
+
+/-- The sorting part of the physical stack computation fits a fixed power
+when the address and word lengths fit in `n` and the block has at most
+eight records per input bit. -/
+theorem ticks_le {n h d w : ℕ} (hn : 4000010 ≤ n) (hb : 2^h ≤ 8*n)
+ (ha : h+d ≤ n) (hw : w ≤ n) : ticks h d w ≤ n^6 := by
+ have h₁ : (2^h+1)^2 ≤ (9*n)^2 := Nat.pow_le_pow_left (by omega) _
+ have h₂ : h+d+w+1 ≤ 3*n := by omega
+ have hl := (SortOneStage.budget_le h d w).trans
+ (Nat.mul_le_mul (Nat.mul_le_mul_left 16384 h₁) h₂)
+ have hp : SortOneStage.budget h d w + 6 ≤ 4000000*n^3 := by
+ rw [show 16384*(9*n)^2*(3*n)=3981312*n^3 by ring] at hl
+ have hpos : 0 < n^3 := pow_pos (by omega) _
+ omega
+ calc
+ ticks h d w ≤ n*((4000000*n^3)*n+5)+1 :=
+ Nat.add_le_add_right (Nat.mul_le_mul ha (Nat.add_le_add_right (Nat.mul_le_mul hp ha) _)) _
+ _ = 4000000*n^5 + 5*n + 1 := by ring
+ _ ≤ 4000010*n^5 := by
+ have hsmall : n ≤ n^5 := by simpa only [pow_one] using Nat.pow_le_pow_right (by omega : 0
+ refine StackRuns.cons (.pop rfl) ?_
+ simp only [Function.update_self, List.head?_nil, List.tail_nil, Option.elim_none, Function.update_idem]
+ exact .nil ..
+ | cons x xs ih =>
+ refine StackRuns.cons (.pop rfl) ?_
+ simp only [Function.update_self, List.head?_cons, List.tail_cons, Option.elim_some,
+ Function.update_idem, hd, Option.isSome_none, Bool.false_eq_true, ite_false]
+ exact ih
+
+private def pair (s : Stacks Port) (src dst : Port) (x y : List Bool) : Stacks Port :=
+ Function.update (Function.update s src x) dst y
+
+private theorem move_run (mode : Mode) (r : Route) (ok : Bool) (dst : Port)
+ (hd : r.dst = some dst) (hne : r.src ≠ dst) (s : Stacks Port) (xs ys : List Bool) :
+ StackRuns (recordCode mode) (2*xs.length+1) (.clean r ok) (pair s r.src dst xs ys)
+ (r.after ok) (pair s r.src dst [] (xs.reverse ++ ys)) := by
+ have getSrc (a b : List Bool) : pair s r.src dst a b r.src = a := by simp [pair, hne]
+ have getDst (a b : List Bool) : pair s r.src dst a b dst = b := by simp [pair]
+ have setSrc (a b c : List Bool) : Function.update (pair s r.src dst a b) r.src c =
+ pair s r.src dst c b := by simp only [pair]; rw [Function.update_comm hne.symm, Function.update_idem]
+ have setDst (a b c : List Bool) : Function.update (pair s r.src dst a b) dst c =
+ pair s r.src dst a c := by simp [pair]
+ induction xs generalizing ys with
+ | nil =>
+ simp only [List.length_nil, Nat.mul_zero, List.reverse_nil, List.nil_append]
+ refine StackRuns.cons (.pop rfl) ?_
+ simp only [getSrc, List.head?_nil, List.tail_nil, Option.elim_none, setSrc]
+ exact .nil ..
+ | cons x xs ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ refine StackRuns.cons (.pop rfl) ?_
+ simp only [getSrc, List.head?_cons, List.tail_cons, Option.elim_some, setSrc,
+ hd, Option.isSome_some, ite_true]
+ refine StackRuns.cons (.push rfl) ?_
+ simp only [hd, Option.getD_some, getDst, setDst]
+ exact ih (x :: ys)
+
+private theorem discard_bank (mode : Mode) (r : Route) (ok : Bool) (hd : r.dst = none) (s : Bank) :
+ StackRuns (recordCode mode) ((s.stacks r.src).length+1) (.clean r ok) s.stacks
+ (r.after ok) (s.update r.src []).stacks := by
+ simpa only [Function.update_eq_self, Bank.update_stacks] using discard_run mode r ok hd s.stacks (s.stacks r.src)
+
+private theorem move_bank (mode : Mode) (r : Route) (ok : Bool) (dst : Port)
+ (hd : r.dst = some dst) (hne : r.src ≠ dst) (s : Bank) :
+ StackRuns (recordCode mode) (2*(s.stacks r.src).length+1) (.clean r ok) s.stacks
+ (r.after ok) ((s.update r.src []).update dst ((s.stacks r.src).reverse ++ s.stacks dst)).stacks := by
+ simpa only [pair, Function.update_eq_self, Bank.update_stacks] using
+ move_run mode r ok dst hd hne s.stacks (s.stacks r.src) (s.stacks dst)
+
+private theorem emit_run (mode : Mode) (ok : Bool) (b : Bank) :
+ StackRuns (recordCode mode) 1 (.emit ok) b.stacks .done {b with valid := ok :: b.valid}.stacks := by
+ refine StackRuns.cons (.push rfl) ?_
+ rw [Bank.update_stacks]; exact .nil ..
+
+/-- Isolate two records, leaving the supplied tails and destination history
+untouched until they are needed. -/
+def ready {w : ℕ} (a b : RawSlot w) (s : Bank) : Bank :=
+ {s with left := Boundary.recordBytes a ++ s.left, right := Boundary.recordBytes b ++ s.right,
+ width := List.replicate w true, widthBack := [], savedLeft := [], savedRight := [], tmp := []}
+
+/-- A clean return bank with the new validity bit. The caller may latch
+this bit or reject as soon as it is false. -/
+def returned (w : ℕ) (s : Bank) (ok : Bool) (bytes : List Bool) : Bank :=
+ {s with width := List.replicate w true, widthBack := [], savedLeft := [], savedRight := [], tmp := [],
+ next := bytes ++ s.next, valid := ok :: s.valid}
+
+private def saved {w : ℕ} (a b : RawSlot w) (s : Bank) : Bank :=
+ {s with width := List.replicate w true, widthBack := [], savedLeft := (Boundary.recordBytes a).reverse,
+ savedRight := (Boundary.recordBytes b).reverse, tmp := []}
+
+private theorem scan_saved (mode : Mode) {w : ℕ} (a b : RawSlot w) (s : Bank) :
+ StackRuns (recordCode mode) (5*(8*w+3)) entry (ready a b s).stacks
+ (cleanup mode (expected a b)) (saved a b s).stacks := by
+ simpa only [ready,saved,List.append_nil] using
+ record_run mode a b {s with savedLeft := [], savedRight := [], tmp := []}
+
+private theorem returning (mode : Mode) (k : ℕ) (s t : Bank)
+ (h : StackRuns (recordCode mode) k entry s.stacks .done t.stacks) :
+ (routine mode).Runs k s.stacks t.stacks := by
+ apply FiniteRoutine.runs_ofStackCode_framed (ports := id) Function.injective_id
+ (normal := fun q ↦ decide (q = State.done)) (entry := entry) (exit := .done)
+ (by rfl) (by rfl) (fun q hq ↦ by obtain rfl := of_decide_eq_true hq; rfl) h
+ (fun _ ↦ rfl) (fun _ ↦ rfl)
+ exact fun j hj ↦ (hj j rfl).elim
+
+/-- Verifying an outgoing slot compares all five raw words and rejects
+noncanonical records through the returned bit. No input values affect its clock. -/
+theorem verify_runs {w : ℕ} (a b : RawSlot w) (s : Bank) :
+ verify.Runs (50*w+18) (ready a b s).stacks (returned w s (verifyOK a b) []).stacks := by
+ let ok := verifyOK a b
+ let start := saved a b s
+ let x := start.update .savedLeft []
+ let y := x.update .savedRight []
+ have h₀ := scan_saved .verify a b s
+ have h₁ := discard_bank .verify .verifyLeft ok rfl start
+ have h₂ := discard_bank .verify .verifyRight ok rfl x
+ have h₃ := emit_run .verify ok y
+ have hh := h₀.trans (h₁.trans (h₂.trans h₃))
+ simp only [Route.src, start, x, saved, Bank.update, Bank.stacks, List.length_reverse,
+ Boundary.length_recordBytes] at hh
+ apply returning
+ convert hh using 1 <;> first | rfl | omega
+
+private theorem select_left {w : ℕ} (keepMin ok : Bool) (a b : RawSlot w) (s : Bank) :
+ StackRuns (recordCode (.select keepMin)) (25*w+4) (.clean (.discardOther true) ok) (saved a b s).stacks
+ .done (returned w s ok (Boundary.recordBytes a).reverse).stacks := by
+ let mode := Mode.select keepMin
+ let start := saved a b s
+ let x := start.update .savedRight []
+ let y := (x.update .savedLeft []).update .tmp ((x.stacks .savedLeft).reverse ++ x.stacks .tmp)
+ let z := (y.update .tmp []).update .next ((y.stacks .tmp).reverse ++ y.stacks .next)
+ have hd := discard_bank mode (.discardOther true) ok rfl start
+ have hm := move_bank mode (.saved true) ok .tmp rfl (by decide) x
+ have hn := move_bank mode .staged ok .next rfl (by decide) y
+ have he := emit_run mode ok z
+ have hh := hd.trans (hm.trans (hn.trans he))
+ simp only [start,x,y,z,saved,Bank.update,Bank.stacks,Route.src,ite_true,List.length_reverse,
+ List.reverse_reverse,List.append_nil,Boundary.length_recordBytes] at hh
+ convert hh using 1 <;> first | rfl | omega
+
+private theorem select_right {w : ℕ} (keepMin ok : Bool) (a b : RawSlot w) (s : Bank) :
+ StackRuns (recordCode (.select keepMin)) (25*w+4) (.clean (.discardOther false) ok) (saved a b s).stacks
+ .done (returned w s ok (Boundary.recordBytes b).reverse).stacks := by
+ let mode := Mode.select keepMin
+ let start := saved a b s
+ let x := start.update .savedLeft []
+ let y := (x.update .savedRight []).update .tmp ((x.stacks .savedRight).reverse ++ x.stacks .tmp)
+ let z := (y.update .tmp []).update .next ((y.stacks .tmp).reverse ++ y.stacks .next)
+ have hd := discard_bank mode (.discardOther false) ok rfl start
+ have hm := move_bank mode (.saved false) ok .tmp rfl (by decide) x
+ have hn := move_bank mode .staged ok .next rfl (by decide) y
+ have he := emit_run mode ok z
+ have hh := hd.trans (hm.trans (hn.trans he))
+ simp only [start,x,y,z,saved,Bank.update,Bank.stacks,Route.src,Bool.false_eq_true,ite_false,
+ List.length_reverse,List.reverse_reverse,List.append_nil,Boundary.length_recordBytes] at hh
+ convert hh using 1 <;> first | rfl | omega
+
+/-- Select the comparator output and append its reversed five-word encoding
+to the backward destination block. All scratch stacks are empty on return. -/
+theorem select_runs {w : ℕ} (keepMin : Bool) (a b : RawSlot w) (s : Bank) :
+ (select keepMin).Runs (65*w+19) (ready a b s).stacks
+ (returned w s (selectOK a b) (Boundary.recordBytes (chosen keepMin a b)).reverse).stacks := by
+ apply returning
+ rw [show 65*w+19 = 5*(8*w+3)+(25*w+4) by omega]
+ apply (scan_saved (.select keepMin) a b s).trans
+ by_cases h : (leDecision (expected a b) == keepMin) = true
+ · simpa [cleanup,h,chosen,selectOK] using select_left keepMin (selectOK a b) a b s
+ · have hf := Bool.eq_false_iff.mpr h
+ simpa [cleanup,hf,chosen,selectOK] using select_right keepMin (selectOK a b) a b s
+
+end RAMTape.Sorter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortCompareBits.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortCompareBits.lean
new file mode 100644
index 0000000000..9b6b4a447d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortCompareBits.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.RAMTapeBoundaryRecord
+import OAI.Computability.VPVNP.RAMSortCompareCost
+import OAI.Computability.VPVNP.RAMTapeSuccessorTags
+
+/-!
+# Finite bit summaries for physical record comparison
+
+The sorter scans each five-word record from its tag through its probe
+ordinal. Within a word, the most recent unequal pair of bits decides the
+unsigned order. Only the low two bits and the presence of a higher set bit
+matter for tag validation. The summaries therefore use a fixed finite state
+space independent of the word width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Sorter
+
+open BurstRAM RAMSort RAMBoundary TapeWord
+
+/-- A low-order result is retained only while all remaining high bits agree. -/
+def orderStep (o : Ordering) (a b : Bool) : Ordering :=
+ if a = b then o else if a then .gt else .lt
+
+private def orderWith (a b : ℕ) (tie : Ordering) : Ordering :=
+ if a < b then .lt else if b < a then .gt else tie
+
+private theorem order_fold (o : Ordering) (xs ys : List Bool) (h : xs.length = ys.length) :
+ Boundary.Field.fold orderStep o xs ys = orderWith (value xs) (value ys) o := by
+ induction xs generalizing ys o with
+ | nil => cases ys <;> simp_all [Boundary.Field.fold, orderWith, value]
+ | cons x xs ih =>
+ cases ys with
+ | nil => simp at h
+ | cons y ys =>
+ rw [Boundary.Field.fold, ih _ ys (Nat.succ.inj h)]
+ rcases lt_trichotomy (value xs) (value ys) with hlt | he | hgt <;> cases x <;> cases y <;>
+ simp [value, orderStep, orderWith] <;> grind
+
+/-- Finite state of one word scan. The bounded tag observations also detect
+an all-zero payload word without storing its numerical value. -/
+structure WordState where
+ /-- Finite tag-decoder state summarizing the bits scanned so far in the left word. -/
+ lhs : SuccessorTags.State
+ /-- Finite tag-decoder state summarizing the bits scanned so far in the right word. -/
+ rhs : SuccessorTags.State
+ /-- Unsigned order of the two little-endian prefixes. A later unequal pair of bits supersedes
+ the earlier order. -/
+ ord : Ordering
+ deriving DecidableEq
+
+instance sorterOrderingFintype : Fintype Ordering := ⟨{.lt,.eq,.gt}, fun q ↦ by cases q <;> simp⟩
+
+instance : Fintype WordState := derive_fintype% _
+
+/-- Start a field comparison with both tag decoders empty and the operand words provisionally
+equal. -/
+def WordState.start : WordState := ⟨.first,.first,.eq⟩
+
+/-- Feed one bit from each operand to its tag decoder and update the unsigned order at this bit
+position. -/
+def WordState.step (s : WordState) (x y : Bool) : WordState :=
+ ⟨SuccessorTags.advance s.lhs x, SuccessorTags.advance s.rhs y, orderStep s.ord x y⟩
+
+private theorem word_fold (s : WordState) (xs ys : List Bool) (h : xs.length = ys.length) :
+ Boundary.Field.fold WordState.step s xs ys =
+ ⟨xs.foldl SuccessorTags.advance s.lhs, ys.foldl SuccessorTags.advance s.rhs,
+ Boundary.Field.fold orderStep s.ord xs ys⟩ := by
+ induction xs generalizing ys s with
+ | nil => cases ys <;> simp_all [Boundary.Field.fold]
+ | cons x xs ih =>
+ cases ys with
+ | nil => simp at h
+ | cons y ys =>
+ rw [Boundary.Field.fold, ih _ ys (Nat.succ.inj h)]
+ rfl
+
+theorem wordState_spec {w : ℕ} (a b : Word w) :
+ let s := Boundary.Field.fold WordState.step WordState.start (wordBits a) (wordBits b)
+ SuccessorTags.finish s.lhs = SuccessorTags.Tag.ofNat a.val ∧
+ SuccessorTags.finish s.rhs = SuccessorTags.Tag.ofNat b.val ∧
+ s.ord = compare a.val b.val := by
+ have h : (wordBits a).length = (wordBits b).length := by simp
+ simp only [word_fold _ _ _ h, WordState.start, SuccessorTags.finish_fold, order_fold _ _ _ h, value_wordBits, true_and]
+ simp only [orderWith, compareOfLessAndEq, compare]
+ split_ifs <;> grind
+
+end RAMTape.Sorter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortDecision.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortDecision.lean
new file mode 100644
index 0000000000..b29c7c5d97
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortDecision.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.RAMTapeSortCompareBits
+
+/-! # Order and canonicality decisions from the five scanned word fields -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Sorter
+
+open BurstRAM RAMBoundary RAMSort RAMSerialization SuccessorTags
+
+/-- Information retained about one field after scanning both words, including each decoded tag
+category and their unsigned comparison. -/
+structure Observation where
+ /-- Tag category assigned to the left word, distinguishing zero, one, two, three and larger
+ values. -/
+ left : Tag
+ /-- Tag category assigned to the right word using the same finite decoder. -/
+ right : Tag
+ /-- Unsigned ordering of the two field words after the scan completes. -/
+ ord : Ordering
+ deriving DecidableEq
+
+instance : Fintype Observation := derive_fintype% _
+
+/-- One comparison observation for each of the five fields of the paired records. -/
+abbrev RecordInfo := Fin 5 → Observation
+
+/-- Finish both tag decoders and retain the word ordering from the completed field scan. -/
+def observe (s : WordState) : Observation := ⟨finish s.lhs, finish s.rhs, s.ord⟩
+
+/-- The five field observations computed directly from two raw records' natural word values. -/
+def expected {w : ℕ} (a b : RawSlot w) : RecordInfo := fun i ↦
+ ⟨Tag.ofNat (a i).val, Tag.ofNat (b i).val, compare (a i).val (b i).val⟩
+
+theorem observe_fold {w : ℕ} (a b : RawSlot w) (i : Fin 5) :
+ observe (Boundary.Field.fold WordState.step WordState.start (BurstRAM.wordBits (a i))
+ (BurstRAM.wordBits (b i))) = expected a b i := by
+ obtain ⟨hl,hr,ho⟩ := wordState_spec (a i) (b i)
+ simp only [observe, expected, hl, hr, ho]
+
+/-- Recognize the three occupied record tags, one through three. -/
+def used : Tag → Bool
+ | .one | .two | .three => true
+ | _ => false
+
+private def probe : Tag → Bool
+ | .zero | .one => false
+ | _ => true
+
+private theorem tags (n : ℕ) :
+ used (Tag.ofNat n) = decide (0 < n ∧ n ≤ 3) ∧
+ (probe (Tag.ofNat n)).toNat = (if 1 < n then 1 else 0) ∧
+ (Tag.ofNat n = .zero ↔ n = 0) := by
+ match n with
+ | 0 | 1 | 2 | 3 => decide
+ | n + 4 =>
+ rw [Tag.ofNat_large (by omega)]
+ simp [used, probe]
+
+/-- Return the left-first verdict for an unequal comparison and use the supplied secondary
+verdict to break equality. -/
+def chooseOrder : Ordering → Bool → Bool
+ | .lt, _ => true
+ | .gt, _ => false
+ | .eq, tie => tie
+
+private theorem chooseOrder_compare (a b : ℕ) (tie : Bool) :
+ chooseOrder (compare a b) tie = WordCompare.lexBit a b tie := by
+ rcases lt_trichotomy a b with hl | he | hg
+ · simp [compare, compareOfLessAndEq, WordCompare.lexBit, chooseOrder, hl, hl.ne]
+ · subst b; simp [compare, compareOfLessAndEq, WordCompare.lexBit, chooseOrder]
+ · simp [compare, compareOfLessAndEq, WordCompare.lexBit, chooseOrder, not_lt_of_gt hg, hg.ne']
+
+/-- The initialized-address flag is between the address and the timestamp.
+The value is consulted only after equal timestamp and kind. -/
+def leDecision (f : RecordInfo) : Bool :=
+ if used (f 0).right then
+ if used (f 0).left then
+ chooseOrder (f 1).ord (chooseOrder (compare (probe (f 0).left).toNat (probe (f 0).right).toNat)
+ (chooseOrder (f 3).ord (chooseOrder (f 4).ord (chooseOrder (f 0).ord (chooseOrder (f 2).ord true)))))
+ else false
+ else true
+
+/-- On an arbitrary five-word tuple the scan compares the parsed slots,
+including the parser's empty value for unknown tags. -/
+theorem leDecision_eq {w : ℕ} (hw : 2 ≤ w) (a b : RawSlot w) :
+ leDecision (expected a b) = decide (parsedSlot hw a ≤ parsedSlot hw b) := by
+ rw [← compareSlots_result, ← compareWords_eq hw a b, WordCompare.compareWords_lex]
+ simp only [leDecision, expected, chooseOrder_compare, (tags _).1, (tags _).2.1, decide_eq_true_eq]
+ have tail : WordCompare.lexBit (a 2).val (b 2).val true = decide (a 2 ≤ b 2) := by
+ by_cases he : (a 2).val = (b 2).val
+ · simp [WordCompare.lexBit, he, show a 2 ≤ b 2 from Nat.le_of_eq he]
+ · by_cases hl : (a 2).val < (b 2).val
+ · simp [WordCompare.lexBit, he, hl, show a 2 ≤ b 2 from hl.le]
+ · simp [WordCompare.lexBit, he, hl, show ¬a 2 ≤ b 2 from fun h ↦ by
+ change (a 2).val ≤ (b 2).val at h; omega]
+ rw [tail]
+
+/-- An occupied tag may carry data fields, while an empty record must have all five fields
+zero. -/
+def canonical (f : Fin 5 → Tag) : Bool := used (f 0) || decide (∀ j, f j = .zero)
+
+theorem canonical_iff {w : ℕ} (hw : 2 ≤ w) (a : RawSlot w) :
+ canonical (fun i ↦ Tag.ofNat (a i).val) = true ↔ ∃ r, (recordFormat hw).words r = a := by
+ simp only [canonical, (tags _).1, (tags _).2.2, Bool.or_eq_true, decide_eq_true_eq]
+ constructor
+ · rintro (h | h)
+ · have ht : (a 0).val = 1 ∨ (a 0).val = 2 ∨ (a 0).val = 3 := by omega
+ rcases ht with hi | hr | hw'
+ · exact ⟨some ⟨.init,a 1,a 2,a 3,a 4⟩, funext fun i ↦ by fin_cases i <;> first | rfl | exact Fin.ext hi.symm⟩
+ · exact ⟨some ⟨.read,a 1,a 2,a 3,a 4⟩, funext fun i ↦ by fin_cases i <;> first | rfl | exact Fin.ext hr.symm⟩
+ · exact ⟨some ⟨.write,a 1,a 2,a 3,a 4⟩, funext fun i ↦ by fin_cases i <;> first | rfl | exact Fin.ext hw'.symm⟩
+ · exact ⟨none, funext fun j ↦ Fin.ext (h j).symm⟩
+ · rintro ⟨_ | ⟨kind,a',v,c,j⟩, rfl⟩
+ · exact Or.inr (fun _ ↦ rfl)
+ · left
+ cases kind with
+ | init => change 0 < 1 ∧ 1 ≤ 3; decide
+ | read => change 0 < 2 ∧ 2 ≤ 3; decide
+ | write => change 0 < 3 ∧ 3 ≤ 3; decide
+
+/-- Check equality of all five fields of the compared records. -/
+def equalDecision (f : RecordInfo) : Bool := decide (∀ i, (f i).ord = .eq)
+
+theorem equalDecision_eq {w : ℕ} (a b : RawSlot w) :
+ equalDecision (expected a b) = decide (a = b) := by
+ apply decide_eq_decide.mpr
+ change (∀ i, compare (a i).val (b i).val = .eq) ↔ a = b
+ simp only [compare_eq_iff_eq]
+ exact ⟨fun h ↦ funext fun i ↦ Fin.ext (h i), fun h i ↦ h ▸ rfl⟩
+
+end RAMTape.Sorter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortField.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortField.lean
new file mode 100644
index 0000000000..84b1b759e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortField.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.RAMTapeSortDecision
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-! # Scanning and saving both words of one comparator field -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Sorter
+
+/-- Comparator ports for the two operands, the reversible width counter, saved operand bits,
+staging, output block and validity flags. -/
+inductive Port where
+ | left | right | width | widthBack | savedLeft | savedRight | tmp | next | valid
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Bit-stack contents while a pair of records is scanned, preserved and optionally copied into
+the next sorting layer. -/
+structure Bank where
+ /-- Unread bits of the left record stream. -/
+ left : List Bool
+ /-- Unread bits of the right record stream. -/
+ right : List Bool
+ /-- Unary markers limiting the scan of one field to one machine word. -/
+ width : List Bool
+ /-- Consumed width markers kept for restoring the counter after a field scan. -/
+ widthBack : List Bool
+ /-- Left operand bits accumulated in reverse order during comparison. -/
+ savedLeft : List Bool
+ /-- Right operand bits accumulated in reverse order during comparison. -/
+ savedRight : List Bool
+ /-- Temporary stack used to stage a selected record during the move to the next block. -/
+ tmp : List Bool
+ /-- Stack accumulating the selected output records for the next sorting layer. -/
+ next : List Bool
+ /-- Stack of Boolean comparison and format verdicts retained for the final acceptance check. -/
+ valid : List Bool
+
+/-- Interpret the named comparator bank as a stack indexed by each physical comparator port. -/
+def Bank.stacks (s : Bank) : Stacks Port
+ | .left => s.left
+ | .right => s.right
+ | .width => s.width
+ | .widthBack => s.widthBack
+ | .savedLeft => s.savedLeft
+ | .savedRight => s.savedRight
+ | .tmp => s.tmp
+ | .next => s.next
+ | .valid => s.valid
+
+/-- Replace the bit stack on a single comparator port while retaining the others. -/
+def Bank.update (s : Bank) (i : Port) (l : List Bool) : Bank :=
+ match i with
+ | .left => {s with left := l}
+ | .right => {s with right := l}
+ | .width => {s with width := l}
+ | .widthBack => {s with widthBack := l}
+ | .savedLeft => {s with savedLeft := l}
+ | .savedRight => {s with savedRight := l}
+ | .tmp => {s with tmp := l}
+ | .next => {s with next := l}
+ | .valid => {s with valid := l}
+
+theorem Bank.update_stacks (s : Bank) (i : Port) (l : List Bool) :
+ Function.update s.stacks i l = (s.update i l).stacks := by
+ funext j
+ cases i <;> cases j <;> rfl
+
+/-- Control for scanning one fixed-width field, comparing and saving its bits, and restoring
+the unary width counter. -/
+inductive FieldState where
+ | tick (s : WordState) | readLeft (s : WordState) | readRight (s : WordState) (x : Bool)
+ | saveLeft (s : WordState) (x y : Bool) | saveRight (s : WordState) (y : Bool)
+ | mark (s : WordState) | rewind (s : WordState) | restore (s : WordState)
+ | done (s : WordState) | reject
+ deriving DecidableEq, Fintype
+
+/-- Pop paired operand bits under the unary width counter, update their comparison summary,
+save both words and restore the counter. -/
+def fieldCode : StackCode Port FieldState
+ | .tick s => .pop .width fun mark ↦ mark.elim (.rewind s) fun _ ↦ .readLeft s
+ | .readLeft s => .pop .left fun x ↦ x.elim .reject (.readRight s)
+ | .readRight s x => .pop .right fun y ↦ y.elim .reject fun b ↦ .saveLeft (s.step x b) x b
+ | .saveLeft s x y => .push .savedLeft x (.saveRight s y)
+ | .saveRight s y => .push .savedRight y (.mark s)
+ | .mark s => .push .widthBack true (.tick s)
+ | .rewind s => .pop .widthBack fun mark ↦ mark.elim (.done s) fun _ ↦ .restore s
+ | .restore s => .push .width true (.rewind s)
+ | .done _ => .halt true
+ | .reject => .halt false
+
+local macro "field_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [Bank.stacks, Bank.update_stacks, Bank.update, List.head?_cons, List.tail_cons,
+ List.head?_nil, List.tail_nil, Option.elim_some, Option.elim_none])
+
+private theorem readPair (s : WordState) (b : Bank) (x y : Bool) :
+ StackRuns fieldCode 6 (.tick s)
+ {b with width := true :: b.width, left := x :: b.left, right := y :: b.right}.stacks
+ (.tick (s.step x y))
+ {b with widthBack := true :: b.widthBack, savedLeft := x :: b.savedLeft, savedRight := y :: b.savedRight}.stacks := by
+ field_step
+ field_step
+ field_step
+ field_step
+ field_step
+ field_step
+ exact .nil ..
+
+private theorem collect (s : WordState) (b : Bank) (xs ys : List Bool) (n : ℕ)
+ (h : xs.length = ys.length) :
+ StackRuns fieldCode (6*xs.length+1) (.tick s)
+ {b with left := xs ++ b.left, right := ys ++ b.right, width := List.replicate xs.length true, widthBack := List.replicate n true}.stacks (.rewind (Boundary.Field.fold WordState.step s xs ys))
+ {b with width := [], widthBack := List.replicate (xs.length+n) true, savedLeft := xs.reverse ++ b.savedLeft, savedRight := ys.reverse ++ b.savedRight}.stacks := by
+ induction xs generalizing s b ys n with
+ | nil =>
+ have he := List.length_eq_zero_iff.mp h.symm
+ subst ys
+ simp only [List.length_nil, List.replicate_zero, List.nil_append, List.reverse_nil, Nat.zero_add,
+ Nat.mul_zero, Boundary.Field.fold]
+ field_step; exact .nil ..
+ | cons x xs ih =>
+ cases ys with
+ | nil => simp at h
+ | cons y ys =>
+ let c := {b with left := xs ++ b.left, right := ys ++ b.right, width := List.replicate xs.length true, widthBack := List.replicate n true}
+ have hnext := ih (s.step x y) {b with savedLeft := x :: b.savedLeft, savedRight := y :: b.savedRight}
+ ys (n+1) (Nat.succ.inj h)
+ rw [List.replicate_succ (n := n)] at hnext
+ simpa [c, List.replicate_succ, Boundary.Field.fold, Nat.mul_add, Nat.add_assoc, Nat.add_comm,
+ Nat.add_left_comm, List.reverse_cons, List.append_assoc] using (readPair s c x y).trans hnext
+
+private theorem rewind (s : WordState) (b : Bank) (n : ℕ) :
+ StackRuns fieldCode (2*n+1) (.rewind s) {b with widthBack := List.replicate n true}.stacks
+ (.done s) {b with width := List.replicate n true ++ b.width, widthBack := []}.stacks := by
+ induction n generalizing b with
+ | zero =>
+ simp only [List.replicate_zero, Nat.mul_zero, List.nil_append]
+ field_step; exact .nil ..
+ | succ n ih =>
+ rw [show 2*(n+1)+1 = (2*n+1+1)+1 by omega, List.replicate_succ]
+ field_step; field_step
+ have hr := ih {b with width := true :: b.width}
+ rw [← List.singleton_append (x := true), ← List.append_assoc, ← List.replicate_succ'] at hr
+ exact hr
+
+/-- Both consumed operands remain available on the two saved stacks in
+reverse order. The width counter is returned intact. -/
+theorem field_runs (s : WordState) (b : Bank) (xs ys : List Bool) (h : xs.length = ys.length) :
+ StackRuns fieldCode (8*xs.length+2) (.tick s)
+ {b with left := xs ++ b.left, right := ys ++ b.right, width := List.replicate xs.length true, widthBack := []}.stacks (.done (Boundary.Field.fold WordState.step s xs ys))
+ {b with width := List.replicate xs.length true, widthBack := [], savedLeft := xs.reverse ++ b.savedLeft, savedRight := ys.reverse ++ b.savedRight}.stacks := by
+ have hc := collect s b xs ys 0 h
+ let endState := Boundary.Field.fold WordState.step s xs ys
+ have hr := rewind endState {b with width := [], savedLeft := xs.reverse ++ b.savedLeft, savedRight := ys.reverse ++ b.savedRight} xs.length
+ simp only [Nat.add_zero, List.replicate_zero] at hc
+ simp only [List.append_nil] at hr
+ rw [show 8*xs.length+2 = (6*xs.length+1)+(2*xs.length+1) by omega]
+ exact hc.trans hr
+
+end RAMTape.Sorter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortGather.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortGather.lean
new file mode 100644
index 0000000000..e9ed8e93c7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortGather.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.RAMTapeSortGatherScan
+import OAI.Computability.VPVNP.RAMSortBlockSlices
+
+/-! # Fetching one record from an arbitrary physical sort block
+
+The two reverse buffers restore the selected record and then the skipped
+prefix. The selected record also goes to the operand stack in forward order.
+The finite control depends only on the five-field record format. Neither the
+word width nor the requested offset occurs in its states.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortGather
+
+open Routine
+
+private def emit (x : Bool) := (push Port.block x).followedBy (push Port.output x)
+
+private def emitRecord : FiniteRoutine Port :=
+ .ofRoutine (popLoop Port.recordBack (fun _ => true) (emit false) (emit true))
+
+private def rewindPrefix : FiniteRoutine Port :=
+ .ofRoutine (popLoop Port.saved (fun _ => true) (push Port.block false) (push Port.block true))
+
+private theorem set_block (w i : ℕ) (block saved selected out val : List Bool) :
+ Function.update (store w i block saved selected out) .block val =
+ store w i val saved selected out := by funext k; cases k <;> rfl
+
+private theorem set_output (w i : ℕ) (block saved selected out val : List Bool) :
+ Function.update (store w i block saved selected out) .output val =
+ store w i block saved selected val := by funext k; cases k <;> rfl
+
+private theorem set_saved (w i : ℕ) (block saved selected out val : List Bool) :
+ Function.update (store w i block saved selected out) .saved val =
+ store w i block val selected out := by funext k; cases k <;> rfl
+
+private theorem set_recordBack (w i : ℕ) (block saved selected out val : List Bool) :
+ Function.update (store w i block saved selected out) .recordBack val =
+ store w i block saved val out := by funext k; cases k <;> rfl
+
+private theorem emitRecord_runs (w i : ℕ) (block saved data out : List Bool) :
+ emitRecord.Runs (3*data.length+1) (store w i block saved data out)
+ (store w i (data.reverse++block) saved [] (data.reverse++out)) := by
+ induction data generalizing block out with
+ | nil =>
+ exact Runs.popLoop_empty Port.recordBack (fun _ => true) (emit false) (emit true) rfl
+ | cons b bs ih =>
+ have pushB := runs_push Port.block b (store w i block saved bs out)
+ have pushO := runs_push Port.output b (store w i (b::block) saved bs out)
+ simp only [set_block, set_output, store] at pushB pushO
+ have he := pushB.followedBy pushO
+ have hh := Runs.popLoop_continue Port.recordBack (fun _ => true) (emit false) (emit true)
+ (s := store w i block saved (b::bs) out) rfl rfl
+ (by rw [set_recordBack]; cases b <;> exact he) (ih (b::block) (b::out))
+ rw [show 1+(1+1)+(3*bs.length+1) = 3*(bs.length+1)+1 by omega] at hh
+ simpa only [emitRecord, FiniteRoutine.ofRoutine, FiniteRoutine.Runs, List.reverse_cons,
+ List.append_assoc, List.singleton_append, List.length_cons] using hh
+
+private theorem rewindPrefix_runs (w i : ℕ) (block saved selected out : List Bool) :
+ rewindPrefix.Runs (2*saved.length+1) (store w i block saved selected out)
+ (store w i (saved.reverse++block) [] selected out) := by
+ induction saved generalizing block with
+ | nil =>
+ exact Runs.popLoop_empty Port.saved (fun _ => true) (push Port.block false) (push Port.block true) rfl
+ | cons b bs ih =>
+ have hp := runs_push Port.block b (store w i block bs selected out)
+ simp only [set_block, store] at hp
+ have hh := Runs.popLoop_continue Port.saved (fun _ => true) (push Port.block false)
+ (push Port.block true) (s := store w i block (b::bs) selected out) rfl rfl
+ (by rw [set_saved]; cases b <;> exact hp) (ih (b::block))
+ rw [show 1+1+(2*bs.length+1) = 2*(bs.length+1)+1 by omega] at hh
+ simpa only [rewindPrefix, FiniteRoutine.ofRoutine, FiniteRoutine.Runs, List.reverse_cons,
+ List.append_assoc, List.singleton_append, List.length_cons] using hh
+
+/-- Consume a unary record offset, preserve its source block, and prepend the selected
+record to the destination. All temporary stacks are cleared on return. -/
+def fetch : FiniteRoutine Port :=
+ ((skip.followedBy select).followedBy emitRecord).followedBy rewindPrefix
+
+/-- Tick allowance to skip i five-word records, fetch the next one and restore both it and the
+skipped prefix to the block. -/
+def cost (i w : ℕ) := i*(40*w+12)+45*w+14
+
+theorem fetch_runs (w i : ℕ) (s : Stacks Port) (pre data tail : List Bool)
+ (hp : pre.length = i*(5*w)) (hd : data.length = 5*w)
+ (hb : s .block = pre ++ data ++ tail) (hi : s .offset = List.replicate i true)
+ (hw : s .width = List.replicate w true) (ht : s .widthBack = [])
+ (hs : s .saved = []) (hr : s .recordBack = []) :
+ fetch.Runs (cost i w) s
+ (Function.update (Function.update s .offset []) .output (data ++ s .output)) := by
+ have h₁ := skip_runs w i pre (data++tail) [] [] (s .output) hp
+ have h₂ := select_runs w 0 data tail pre.reverse [] (s .output) hd
+ have h₃ := emitRecord_runs w 0 tail pre.reverse data.reverse (s .output)
+ have h₄ := rewindPrefix_runs w 0 (data++tail) pre.reverse [] (data++s .output)
+ simp only [List.append_nil, List.reverse_reverse, List.length_reverse] at h₁ h₂ h₃ h₄
+ have h := ((FiniteRoutine.Runs.followedBy h₁ h₂).followedBy h₃).followedBy h₄
+ have hstart : store w i (pre ++ (data ++ tail)) [] [] (s .output) = s := by
+ funext k
+ cases k <;> simp [store, hb, hi, hw, ht, hs, hr, List.append_assoc]
+ have hend : store w 0 (pre ++ (data ++ tail)) [] [] (data++s .output) =
+ Function.update (Function.update s .offset []) .output (data++s .output) := by
+ funext k
+ cases k <;> simp [store, hb, hw, ht, hs, hr, List.append_assoc]
+ rw [hstart, hend, hp, hd] at h
+ unfold fetch
+ convert h using 1
+ unfold cost
+ ring
+
+open RAMSerialization
+
+/-- In the physical block encoding the fetched bits are exactly the record slice,
+including when the supplied bits encode a malformed record. -/
+theorem fetch_slice_runs (H w : ℕ) (i : Fin (4*H)) (bits : Fin (RAMLayout.blockBits H w) → Bool)
+ (s : Stacks Port) (hb : s .block = List.ofFn bits) (hi : s .offset = List.replicate i.val true)
+ (hw : s .width = List.replicate w true) (ht : s .widthBack = [])
+ (hs : s .saved = []) (hr : s .recordBack = []) :
+ fetch.Runs (cost i.val w) s (Function.update (Function.update s .offset []) .output
+ (List.ofFn (recordSlice H w bits i) ++ s .output)) := by
+ let off := i.val*(5*w)
+ let all := List.ofFn bits
+ have hend : off+5*w ≤ all.length := by
+ change i.val*(5*w)+5*w ≤ (List.ofFn bits).length
+ rw [List.length_ofFn, RAMLayout.blockBits, Nat.mul_assoc, ← Nat.succ_mul]
+ exact Nat.mul_le_mul_right _ i.isLt
+ have hpre : (all.take off).length = off := by simp [List.length_take, show off ≤ all.length by omega]
+ have hdata : ((all.drop off).take (5*w)).length = 5*w := by
+ simp [List.length_take, List.length_drop, show 5*w ≤ all.length-off by omega]
+ have heq : (all.drop off).take (5*w) = List.ofFn (recordSlice H w bits i) := by
+ apply List.ext_getElem (by simp [hdata])
+ intro k hk _
+ rw [List.getElem_take, List.getElem_drop, List.getElem_ofFn, List.getElem_ofFn]
+ unfold recordSlice
+ apply congrArg bits
+ apply Fin.ext
+ simp only [off, Nat.mul_assoc]
+ have split : s .block = all.take off ++ (all.drop off).take (5*w) ++ (all.drop off).drop (5*w) := by
+ rw [List.append_assoc, List.take_append_drop, List.take_append_drop, hb]
+ have h := fetch_runs w i.val s (all.take off) ((all.drop off).take (5*w))
+ ((all.drop off).drop (5*w)) hpre hdata split hi hw ht hs hr
+ rwa [heq] at h
+
+end RAMTape.SortGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortGatherPreserve.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortGatherPreserve.lean
new file mode 100644
index 0000000000..6fdf0b4eba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortGatherPreserve.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.RAMTapeSortGather
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-! # Indexed sort lookup preserving the row counter
+
+Copy the live row tally into the gather routine's private offset register
+before fetching the record. The gather's width scratch is free during this
+copy, and the original row tally is available to the next row instruction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortGather
+
+variable {K : Type}
+
+/-- Copy the live unary row index into private scratch before fetching the record, preserving
+the caller's index for the next operation. -/
+def fetchPreserving (ports : Port → K) (index : K) : FiniteRoutine K :=
+ (SuccessorFields.prependCopy index (ports .offset) (ports .widthBack)).followedBy
+ (fetch.onPorts ports)
+
+variable [DecidableEq K]
+
+theorem fetchPreserving_runs (ports : Port → K) (hp : Function.Injective ports) (index : K)
+ (hdist : ∀ j, index ≠ ports j) (w i : ℕ) (s : Stacks K) (pre data tail : List Bool)
+ (hpre : pre.length = i*(5*w)) (hdata : data.length = 5*w)
+ (hb : s (ports .block) = pre ++ data ++ tail) (hi : s index = List.replicate i true)
+ (ho : s (ports .offset) = []) (hw : s (ports .width) = List.replicate w true)
+ (ht : s (ports .widthBack) = []) (hs : s (ports .saved) = []) (hr : s (ports .recordBack) = []) :
+ (fetchPreserving ports index).Runs (5*i+2 + cost i w) s
+ (Function.update s (ports .output) (data++s (ports .output))) := by
+ let m := Function.update s (ports .offset) (List.replicate i true)
+ have copy := SuccessorFields.prependCopy_runs index (ports .offset) (ports .widthBack)
+ (hdist _) (hdist _) (hp.ne (by decide)) s ht
+ rw [hi, ho, List.append_nil, List.length_replicate] at copy
+ have neq (p : Port) (h : p ≠ .offset) : m (ports p) = s (ports p) :=
+ Function.update_of_ne (hp.ne h) ..
+ have run := fetch_runs w i (m ∘ ports) pre data tail hpre hdata
+ ((neq _ (by decide)).trans hb) (Function.update_self ..) ((neq _ (by decide)).trans hw)
+ ((neq _ (by decide)).trans ht) ((neq _ (by decide)).trans hs) ((neq _ (by decide)).trans hr)
+ have lifted : (fetch.onPorts ports).Runs (cost i w) m
+ (Function.update s (ports .output) (data++s (ports .output))) := by
+ apply fetch.runs_onPorts_framed hp run (fun _ => rfl)
+ · intro j
+ cases j <;> simp [m, Function.comp_def, hp.eq_iff, ho]
+ · intro j hj
+ simp [m, Ne.symm (hj .output), Ne.symm (hj .offset)]
+ exact FiniteRoutine.Runs.followedBy copy lifted
+
+end RAMTape.SortGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortGatherScan.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortGatherScan.lean
new file mode 100644
index 0000000000..b4a173eb54
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortGatherScan.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.RAMTapeSortGatherWord
+
+/-! # Scanning to a unary record offset
+
+Five invocations of the word mover remove a physical record. An offset loop
+repeats this fixed subprogram for the records preceding the selected one.
+All skipped bits accumulate in reverse order for restoration.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortGather
+
+open Routine
+
+private def words (b : Buffer) : ℕ → FiniteRoutine Port
+ | 0 => .ret
+ | n+1 => (word b).followedBy (words b n)
+
+private theorem words_runs (b : Buffer) (w n : ℕ) (s : Stacks Port) (data tail : List Bool)
+ (hlen : data.length = n*w) (hb : s .block = data ++ tail)
+ (hw : s .width = List.replicate w true) (ht : s .widthBack = []) :
+ (words b n).Runs (n*(6*w+2)+1) s
+ (Function.update (Function.update s .block tail) b.dest (data.reverse ++ s b.dest)) := by
+ induction n generalizing s data with
+ | zero =>
+ have hd : data = [] := List.length_eq_zero_iff.mp (by simpa using hlen)
+ subst data
+ simp only [List.nil_append] at hb
+ simp only [words, Nat.zero_mul, Nat.zero_add, List.reverse_nil, List.nil_append, ← hb,
+ Function.update_eq_self]
+ exact runs_ret s
+ | succ n ih =>
+ let x := data.take w
+ let xs := data.drop w
+ have hs : x ++ xs = data := List.take_append_drop ..
+ have hle : w ≤ data.length := by rw [hlen, Nat.succ_mul]; omega
+ have hx : x.length = w := by simp [x, hle]
+ have hxs : xs.length = n*w := by simp [xs, hlen, Nat.succ_mul]
+ let mid := Function.update (Function.update s Port.block (xs ++ tail)) b.dest
+ (x.reverse ++ s b.dest)
+ have hm : s .block = x ++ (xs ++ tail) := by rw [← List.append_assoc, hs, hb]
+ have first := word_runs b s x (xs++tail) hm (by rwa [hx]) ht
+ have rest := ih mid xs hxs (by cases b <;> simp [mid, Buffer.dest])
+ (by cases b <;> simp [mid, Buffer.dest, hw]) (by cases b <;> simp [mid, Buffer.dest, ht])
+ have finish : Function.update (Function.update mid .block tail) b.dest (xs.reverse ++ mid b.dest) =
+ Function.update (Function.update s .block tail) b.dest (data.reverse ++ s b.dest) := by
+ rw [← hs, List.reverse_append, List.append_assoc]
+ funext k
+ cases b <;> cases k <;> simp [mid, Buffer.dest]
+ rw [finish] at rest
+ rw [hx] at first
+ simpa only [words, Nat.succ_mul, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm] using
+ FiniteRoutine.Runs.followedBy first rest
+
+/-- Place the block, skipped prefix, selected record and output on their gather ports with
+unary offset and width counters and empty width scratch. -/
+def store (w i : ℕ) (block saved selected out : List Bool) : Stacks Port
+ | .block => block
+ | .offset => List.replicate i true
+ | .width => List.replicate w true
+ | .widthBack => []
+ | .saved => saved
+ | .recordBack => selected
+ | .output => out
+
+/-- The skipped prefix is saved bit-for-bit on a single reverse buffer. -/
+def skip : FiniteRoutine Port := .ofRoutine
+ (popLoop Port.offset (fun _ => true) (halt false) (words .skipped 5).body)
+
+theorem skip_runs (w i : ℕ) (pre tail saved selected out : List Bool)
+ (hlen : pre.length = i*(5*w)) :
+ skip.Runs (i*(30*w+12)+1) (store w i (pre++tail) saved selected out)
+ (store w 0 tail (pre.reverse++saved) selected out) := by
+ induction i generalizing pre saved with
+ | zero =>
+ have h : pre = [] := List.length_eq_zero_iff.mp (by simpa using hlen)
+ subst pre
+ simp only [Nat.zero_mul, Nat.zero_add, List.nil_append, List.reverse_nil]
+ exact Runs.popLoop_empty Port.offset (fun _ => true) (halt false) (words .skipped 5).body rfl
+ | succ i ih =>
+ let x := pre.take (5*w)
+ let xs := pre.drop (5*w)
+ have hs : x ++ xs = pre := List.take_append_drop ..
+ have hle : 5*w ≤ pre.length := by rw [hlen, Nat.succ_mul i (5*w)]; omega
+ have hx : x.length = 5*w := by simp [x, hle]
+ have hxs : xs.length = i*(5*w) := by simp [xs, hlen, Nat.succ_mul]
+ let start := store w (i+1) (pre++tail) saved selected out
+ let one := store w i (pre++tail) saved selected out
+ have head : start .offset = true :: List.replicate i true := List.replicate_succ
+ have pop : Function.update start .offset (List.replicate i true) = one := by
+ funext k
+ cases k <;> rfl
+ have hb := words_runs .skipped w 5 one x (xs++tail) hx
+ (by change pre ++ tail = _; rw [← hs, List.append_assoc]) rfl rfl
+ have hu : Function.update (Function.update one .block (xs++tail)) Buffer.skipped.dest
+ (x.reverse ++ one Buffer.skipped.dest) = store w i (xs++tail) (x.reverse++saved) selected out := by
+ funext k
+ cases k <;> rfl
+ rw [hu] at hb
+ have rest := ih xs (x.reverse++saved) hxs
+ have loop := Runs.popLoop_true_continue Port.offset (fun _ => true) (halt false)
+ (words .skipped 5).body head rfl (by rw [pop]; exact hb) rest
+ rw [show 1+(5*(6*w+2)+1)+(i*(30*w+12)+1) = (i+1)*(30*w+12)+1 by ring] at loop
+ have hend : pre.reverse ++ saved = xs.reverse ++ (x.reverse ++ saved) := by
+ rw [← hs, List.reverse_append, List.append_assoc]
+ rw [hend]
+ exact loop
+
+/-- The selected record moves to its own reverse buffer, separate from the prefix. -/
+def select : FiniteRoutine Port := words .selected 5
+
+theorem select_runs (w i : ℕ) (data tail saved selected out : List Bool)
+ (hlen : data.length = 5*w) :
+ select.Runs (30*w+11) (store w i (data++tail) saved selected out)
+ (store w i tail saved (data.reverse++selected) out) := by
+ have h := words_runs .selected w 5 (store w i (data++tail) saved selected out) data tail hlen
+ rfl rfl rfl
+ have he : Function.update (Function.update (store w i (data++tail) saved selected out)
+ .block tail) Buffer.selected.dest (data.reverse ++ selected) = store w i tail saved
+ (data.reverse++selected) out := by
+ funext k
+ cases k <;> rfl
+ change select.Runs _ _ (Function.update _ Buffer.selected.dest (data.reverse ++ selected)) at h
+ rw [he, show 5*(6*w+2)+1 = 30*w+11 by ring] at h
+ exact h
+
+end RAMTape.SortGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortGatherWord.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortGatherWord.lean
new file mode 100644
index 0000000000..bb737c9cea
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortGatherWord.lean
@@ -0,0 +1,177 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.StructuredStackLoop
+
+/-! # Moving one word of a sort block onto a reverse buffer
+
+The input and buffer hold arbitrary bits. A separate unary word-width stack
+is restored after the move so the same finite control can read all five
+fields of a record and all records before the selected slot.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortGather
+
+/-- Gather ports for the record block, unary offset and width, reversible width counter,
+skipped and selected buffers and output. -/
+inductive Port where
+ | block | offset | width | widthBack | saved | recordBack | output
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+namespace WordMove
+
+/-- The word mover's source block, reversible width tally and reverse destination buffer. -/
+inductive Port where
+ | block | width | widthBack | dest
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Control for moving a fixed-width word bit by bit, saving width markers, then restoring the
+width tally. -/
+inductive Phase where
+ | tick | read | save (b : Bool) | mark | rewind | put | done | reject
+ deriving DecidableEq, Fintype
+
+/-- Use one width marker per bit moved from the block to the destination and restore all
+markers at the end of the word. -/
+def code : StackCode Port Phase
+ | .tick => .pop .width fun m => m.elim .rewind fun _ => .read
+ | .read => .pop .block fun b => b.elim .reject .save
+ | .save b => .push .dest b .mark
+ | .mark => .push .widthBack true .tick
+ | .rewind => .pop .widthBack fun m => m.elim .done fun _ => .put
+ | .put => .push .width true .rewind
+ | .done => .halt true
+ | .reject => .halt false
+
+private def bank (block width back dest : List Bool) : Stacks Port
+ | .block => block
+ | .width => width
+ | .widthBack => back
+ | .dest => dest
+
+private theorem update_bank (block width back dest val : List Bool) (p : Port) :
+ Function.update (bank block width back dest) p val = match p with
+ | .block => bank val width back dest
+ | .width => bank block val back dest
+ | .widthBack => bank block width val dest
+ | .dest => bank block width back val := by
+ funext j
+ cases p <;> cases j <;> rfl
+
+local macro "move_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [bank, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_bank])
+
+private theorem collect (data tail back dst : List Bool) :
+ StackRuns code (4 * data.length + 1) .tick
+ (bank (data ++ tail) (List.replicate data.length true) back dst)
+ .rewind (bank tail [] (List.replicate data.length true ++ back) (data.reverse ++ dst)) := by
+ induction data generalizing back dst with
+ | nil =>
+ simp only [List.length_nil, Nat.mul_zero, Nat.zero_add, List.nil_append, List.reverse_nil,
+ List.replicate_zero]
+ move_step
+ exact .nil ..
+ | cons b bs ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.cons_append, List.reverse_cons,
+ List.append_assoc]
+ rw [List.replicate_succ (n := bs.length)]
+ move_step
+ move_step
+ move_step
+ move_step
+ have hr := ih (true :: back) (b :: dst)
+ rw [← List.singleton_append (x := true), ← List.append_assoc, ← List.replicate_succ', List.replicate_succ] at hr
+ exact hr
+
+private theorem restore (block width dest : List Bool) (n : ℕ) :
+ StackRuns code (2*n+1) .rewind (bank block width (List.replicate n true) dest) .done
+ (bank block (List.replicate n true ++ width) [] dest) := by
+ induction n generalizing width with
+ | zero =>
+ simp only [List.replicate_zero, List.nil_append, Nat.mul_zero, Nat.zero_add]
+ move_step
+ exact .nil ..
+ | succ n ih =>
+ rw [Nat.mul_succ, List.replicate_succ (n := n)]
+ move_step
+ move_step
+ have hr := ih (true :: width)
+ rw [← List.singleton_append (x := true), ← List.append_assoc, ← List.replicate_succ', List.replicate_succ] at hr
+ exact hr
+
+theorem runs (s : Stacks Port) (data tail : List Bool)
+ (hb : s .block = data ++ tail) (hw : s .width = List.replicate data.length true)
+ (ht : s .widthBack = []) :
+ StackRuns code (6*data.length+2) .tick s .done
+ (Function.update (Function.update s .block tail) .dest (data.reverse ++ s .dest)) := by
+ have h₁ := collect data tail [] (s .dest)
+ have h₂ := restore tail [] (data.reverse ++ s .dest) data.length
+ simp only [List.append_nil] at h₁ h₂
+ have hs : bank (data ++ tail) (List.replicate data.length true) [] (s .dest) = s := by
+ funext p
+ cases p <;> simp [bank, hb, hw, ht]
+ have hu : bank tail (List.replicate data.length true) [] (data.reverse ++ s .dest) =
+ Function.update (Function.update s .block tail) .dest (data.reverse ++ s .dest) := by
+ funext p
+ cases p <;> simp [bank, hw, ht]
+ rw [hs] at h₁
+ rw [hu] at h₂
+ convert h₁.trans h₂ using 1
+ omega
+
+end WordMove
+
+/-- Distinguish a word from a skipped record from one belonging to the selected record. -/
+inductive Buffer where
+ | skipped | selected
+ deriving DecidableEq
+
+/-- Use the saved-prefix port for skipped words and the selected-record reverse buffer for
+selected words. -/
+def Buffer.dest : Buffer → Port
+ | .skipped => .saved
+ | .selected => .recordBack
+
+private def wordPorts (b : Buffer) : WordMove.Port → Port
+ | .block => .block
+ | .width => .width
+ | .widthBack => .widthBack
+ | .dest => b.dest
+
+private theorem injective_wordPorts (b : Buffer) : Function.Injective (wordPorts b) := by
+ intro i j h
+ cases b <;> cases i <;> cases j <;> first | rfl | cases h
+
+/-- Move one width-delimited word from the current block to the named reverse buffer. -/
+def word (b : Buffer) : FiniteRoutine Port :=
+ .ofStackCode WordMove.code (wordPorts b) .tick fun q => decide (q = .done)
+
+theorem word_runs (b : Buffer) (s : Stacks Port) (data tail : List Bool)
+ (hb : s .block = data ++ tail) (hw : s .width = List.replicate data.length true)
+ (ht : s .widthBack = []) :
+ (word b).Runs (6*data.length+2) s
+ (Function.update (Function.update s .block tail) b.dest (data.reverse ++ s b.dest)) := by
+ let small := s ∘ wordPorts b
+ unfold word
+ apply FiniteRoutine.runs_ofStackCode_framed (src := WordMove.code) (injective_wordPorts b)
+ (normal := fun q => decide (q = .done)) (entry := .tick) (exit := .done) rfl rfl
+ (fun q h => by have hq : q = .done := of_decide_eq_true h; subst q; rfl)
+ (WordMove.runs small data tail hb hw ht) (fun _ => rfl)
+ · intro i
+ cases b <;> cases i <;> simp [wordPorts, Buffer.dest, small]
+ · intro j hj
+ simp [show j ≠ b.dest from Ne.symm (hj .dest), show j ≠ .block from Ne.symm (hj .block)]
+
+end RAMTape.SortGather
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortLayerDispatch.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerDispatch.lean
new file mode 100644
index 0000000000..1cdde99add
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerDispatch.lean
@@ -0,0 +1,200 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-! # Choosing the local or cross-site sorting layer
+
+A layer with stride exponent `j` uses the incident stream precisely when
+the site holds `2^h` rows and `h ≤ j`. The finite control compares the unary
+exponents before any stream is split. It removes one mark from each exponent
+per round and saves the number of rounds above a delimiter. It restores the
+two exponents and consumes the delimiter before entering the selected branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortLayerDispatch
+
+/-- Unary block-width and stride exponents together with the scratch stack used to compare and
+restore them before layer dispatch. -/
+inductive Port where
+ | width | stride | tmp
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+private inductive Phase where
+ | start | scanWidth | scanStride | save | undoWidth
+ | restore (cross : Bool) | putWidth (cross : Bool) | putStride (cross : Bool)
+ | report (cross : Bool) | done
+ deriving DecidableEq, Fintype
+
+private def code : StackCode Port Phase
+ | .start => .push .tmp false .scanWidth
+ | .scanWidth => .pop .width fun b => b.elim (.restore true) (fun _ => .scanStride)
+ | .scanStride => .pop .stride fun b => b.elim .undoWidth (fun _ => .save)
+ | .save => .push .tmp true .scanWidth
+ | .undoWidth => .push .width true (.restore false)
+ | .restore b => .pop .tmp fun mark => if mark = some true then .putWidth b else .report b
+ | .putWidth b => .push .width true (.putStride b)
+ | .putStride b => .push .stride true (.restore b)
+ | .report b => .push .tmp b .done
+ | .done => .halt true
+
+private abbrev marks (n : ℕ) := List.replicate n true
+
+private def bank (width stride tmp : List Bool) : Stacks Port
+ | .width => width
+ | .stride => stride
+ | .tmp => tmp
+
+private theorem set_bank (w j t v : List Bool) (p : Port) :
+ Function.update (bank w j t) p v = match p with
+ | .width => bank v j t
+ | .stride => bank w v t
+ | .tmp => bank w j v := by
+ funext k
+ cases p <;> cases k <;> rfl
+
+local macro "dispatch_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [bank, set_bank, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, Bool.false_ne_true,
+ Option.some.injEq, ↓reduceIte])
+
+private theorem scan_pairs (n h j : ℕ) (tmp : List Bool) :
+ StackRuns code (3*n) .scanWidth (bank (marks (h+n)) (marks (j+n)) tmp)
+ .scanWidth (bank (marks h) (marks j) (marks n ++ tmp)) := by
+ induction n generalizing tmp with
+ | zero => exact .nil ..
+ | succ n ih =>
+ rw [Nat.mul_succ, Nat.add_succ, Nat.add_succ]
+ change StackRuns _ _ _ (bank (true :: marks (h+n)) (true :: marks (j+n)) tmp) _ _
+ dispatch_step
+ dispatch_step
+ dispatch_step
+ simpa only [marks, List.replicate_succ', List.append_assoc, List.singleton_append]
+ using ih (true :: tmp)
+
+private theorem restore_pairs (b : Bool) (n h j : ℕ) (tmp : List Bool) :
+ StackRuns code (3*n+2) (.restore b)
+ (bank (marks h) (marks j) (marks n ++ false :: tmp))
+ .done (bank (marks (h+n)) (marks (j+n)) (b :: tmp)) := by
+ induction n generalizing h j with
+ | zero =>
+ change StackRuns _ 2 _ (bank _ _ (false :: tmp)) _ _
+ dispatch_step
+ dispatch_step
+ exact .nil ..
+ | succ n ih =>
+ rw [Nat.mul_succ, show 3*n+3+2 = (3*n+2)+1+1+1 by omega]
+ change StackRuns _ _ _ (bank _ _ (true :: (marks n ++ false :: tmp))) _ _
+ dispatch_step
+ dispatch_step
+ dispatch_step
+ simpa only [marks, List.replicate_succ, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm]
+ using ih (h+1) (j+1)
+
+private theorem scan_cross (h d : ℕ) (tmp : List Bool) :
+ StackRuns code (6*h+4) .start (bank (marks h) (marks (d+h)) tmp)
+ .done (bank (marks h) (marks (d+h)) (true :: tmp)) := by
+ have pairs := scan_pairs h 0 d (false :: tmp)
+ have restore := restore_pairs true h 0 d tmp
+ simp only [Nat.zero_add] at pairs restore
+ have finish : StackRuns code ((3*h+2)+1) .scanWidth
+ (bank [] (marks d) (marks h ++ false :: tmp)) .done
+ (bank (marks h) (marks (d+h)) (true :: tmp)) := by
+ dispatch_step
+ exact restore
+ rw [show 6*h+4 = (3*h + ((3*h+2)+1))+1 by omega]
+ dispatch_step
+ exact pairs.trans finish
+
+private theorem scan_local (j d : ℕ) (tmp : List Bool) :
+ StackRuns code (6*j+6) .start (bank (marks (d+1+j)) (marks j) tmp)
+ .done (bank (marks (d+1+j)) (marks j) (false :: tmp)) := by
+ have pairs := scan_pairs j (d+1) 0 (false :: tmp)
+ have restore := restore_pairs false j (d+1) 0 tmp
+ simp only [Nat.zero_add] at pairs restore
+ have finish : StackRuns code ((3*j+2)+1+1+1) .scanWidth
+ (bank (true :: marks d) [] (marks j ++ false :: tmp)) .done
+ (bank (marks (d+1+j)) (marks j) (false :: tmp)) := by
+ dispatch_step
+ dispatch_step
+ dispatch_step
+ exact restore
+ rw [show 6*j+6 = (3*j + ((3*j+2)+1+1+1))+1 by omega]
+ dispatch_step
+ exact pairs.trans finish
+
+variable {K : Type}
+
+private def test (ports : Port → K) : FiniteRoutine K :=
+ FiniteRoutine.ofStackCode code ports .start (· == .done)
+
+private def branch (tmp : K) (cross sameSite : FiniteRoutine K) : FiniteRoutine K :=
+ .ofRoutine (Routine.popCase tmp (Routine.halt false) sameSite.body cross.body)
+
+/-- The branch callback receives the full caller store, with both exponents
+and the previous contents of the temporary stack restored. -/
+def routine (ports : Port → K) (cross sameSite : FiniteRoutine K) : FiniteRoutine K :=
+ (test ports).followedBy (branch (ports .tmp) cross sameSite)
+
+variable [DecidableEq K]
+
+private theorem test_runs (ports : Port → K) (hp : Function.Injective ports)
+ {h j n : ℕ} {b : Bool} (s : Stacks K) (hh : s (ports .width) = marks h)
+ (hj : s (ports .stride) = marks j)
+ (run : StackRuns code n .start (bank (marks h) (marks j) (s (ports .tmp)))
+ .done (bank (marks h) (marks j) (b :: s (ports .tmp)))) :
+ (test ports).Runs n s (Function.update s (ports .tmp) (b :: s (ports .tmp))) := by
+ apply FiniteRoutine.runs_ofStackCode_framed hp (normal := (· == .done)) rfl rfl
+ (fun q e => by simp only [beq_iff_eq] at e; subst q; rfl) run
+ · intro p
+ cases p <;> first | assumption | rfl
+ · intro p
+ cases p <;> simp [hp.eq_iff, bank, hh, hj]
+ · intro k hk
+ exact Function.update_of_ne (hk .tmp).symm ..
+
+/-- Cross-site stride, including the equality boundary. -/
+theorem cross_runs (ports : Port → K) (hp : Function.Injective ports)
+ (cross sameSite : FiniteRoutine K) {s out : Stacks K} {h j t : ℕ}
+ (hh : s (ports .width) = List.replicate h true)
+ (hj : s (ports .stride) = List.replicate j true) (hc : h ≤ j)
+ (hr : cross.Runs t s out) :
+ (routine ports cross sameSite).Runs (6*h+5+t) s out := by
+ have scan := scan_cross h (j-h) (s (ports .tmp))
+ rw [Nat.sub_add_cancel hc] at scan
+ have first := test_runs ports hp s hh hj scan
+ let mid := Function.update s (ports .tmp) (true :: s (ports .tmp))
+ have pick : (branch (ports .tmp) cross sameSite).Runs (t+1) mid out := by
+ apply Routine.runs_popCase_true (ports .tmp) (Routine.halt false) sameSite.body cross.body (s := mid)
+ (Function.update_self ..)
+ simpa only [mid, Function.update_idem, Function.update_eq_self] using hr
+ rw [show 6*h+5+t = (6*h+4)+(t+1) by omega]
+ exact first.followedBy pick
+
+/-- Strides strictly below the site's row width use its materialized block. -/
+theorem local_runs (ports : Port → K) (hp : Function.Injective ports)
+ (cross sameSite : FiniteRoutine K) {s out : Stacks K} {h j t : ℕ}
+ (hh : s (ports .width) = List.replicate h true)
+ (hj : s (ports .stride) = List.replicate j true) (hl : j < h)
+ (hr : sameSite.Runs t s out) :
+ (routine ports cross sameSite).Runs (6*j+7+t) s out := by
+ have scan := scan_local j (h-j-1) (s (ports .tmp))
+ rw [show h-j-1+1+j = h by omega] at scan
+ have first := test_runs ports hp s hh hj scan
+ let mid := Function.update s (ports .tmp) (false :: s (ports .tmp))
+ have pick : (branch (ports .tmp) cross sameSite).Runs (t+1) mid out := by
+ apply Routine.runs_popCase_false (ports .tmp) (Routine.halt false) sameSite.body cross.body (s := mid)
+ (Function.update_self ..)
+ simpa only [mid, Function.update_idem, Function.update_eq_self] using hr
+ rw [show 6*j+7+t = (6*j+6)+(t+1) by omega]
+ exact first.followedBy pick
+
+end RAMTape.SortLayerDispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRows.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRows.lean
new file mode 100644
index 0000000000..7399478fdf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRows.lean
@@ -0,0 +1,67 @@
+import OAI.Computability.VPVNP.RAMTapeSortLayerRowsProgram
+import OAI.Computability.VPVNP.RAMTapeSortRowCross
+import OAI.Computability.VPVNP.RAMTapeSortRowLocal
+
+/-!
+# Physical execution of a complete sorting layer
+
+The fixed row traversal implements the local and cross-site comparators on
+arbitrary five-word inputs. It preserves the input block, consumes exactly
+the two exchange fields when the stride crosses sites, and accumulates the
+selected records and every canonicality and outgoing-copy check.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortLayerRows
+
+open BurstRAM RAMSort RAMBoundary Boundary
+
+variable {h d w : ℕ}
+
+theorem recordVisit_all (s : Stage (h+d)) (v : Word d) (current send recv : Wires h (RawSlot w))
+ (next sendTail recvTail flags : List Bool) (i : Word h) :
+ recordVisit s v current send recv next sendTail recvTail flags i := by
+ let cur := blockBytes (List.ofFn current)
+ let output := pushed (selected s v current recv) next i.val
+ let ss := pending s send sendTail i.val
+ let rr := pending s recv recvTail i.val
+ let fs := latched (checks s current send recv) flags i.val
+ let data := bank v s.phase s.stride w cur output ss rr fs
+ let rs := prepared s v i data ∘ rowPorts
+ have hready := prepared_ready s v i current output ss rr fs
+ change SortRow.Ready rs current i (peerIndex s i) (decide (s.stride < h)) (keepMin s v i) at hready
+ change ∃ t ≤ _, SortRow.program.Runs t rs (SortRow.result rs _ _ _ _ _ _)
+ have hs : rs .crossSend = pending s send sendTail i.val := rfl
+ have hr : rs .crossReceive = pending s recv recvTail i.val := rfl
+ by_cases hj : s.stride < h
+ · rw [decide_eq_true hj] at hready
+ have run := SortRow.program_local_runs rs current i (peerIndex s i) (keepMin s v i) hready
+ simpa only [other, hj, ↓reduceIte, hs, hr, pending] using run
+ · rw [decide_eq_false hj] at hready
+ have hsend := hs.trans (pending_cross hj send sendTail i)
+ have hrecv := hr.trans (pending_cross hj recv recvTail i)
+ have run := SortRow.program_cross_runs rs current i (peerIndex s i) (keepMin s v i) (send i) (recv i)
+ (pending s send sendTail (i.val+1)) (pending s recv recvTail (i.val+1)) hready hsend hrecv
+ simpa only [other, hj, ↓reduceIte] using run
+
+
+/-- Complete row traversal at the word width of the five-word record format. -/
+theorem runs (_hw : 2 ≤ w) (s : Stage (h+d)) (v : Word d) (current send recv : Wires h (RawSlot w))
+ (next sendTail recvTail flags : List Bool) :
+ ∃ t ≤ budget h d w s.phase s.stride, program.Runs t
+ (SortOffsets.idle (bank v s.phase s.stride w (blockBytes (List.ofFn current)) next
+ (fieldsBefore s send sendTail) (fieldsBefore s recv recvTail) flags) h)
+ (SortOffsets.idle (bank v s.phase s.stride w (blockBytes (List.ofFn current))
+ ((blockBytes (List.ofFn (selected s v current recv))).reverse ++ next) sendTail recvTail
+ ((List.ofFn (checks s current send recv)).reverse.flatten ++ flags)) h) :=
+ runs_of_visits s v current send recv next sendTail recvTail flags
+ (recordVisit_all s v current send recv next sendTail recvTail flags)
+
+end RAMTape.SortLayerRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsModel.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsModel.lean
new file mode 100644
index 0000000000..7dbdf61654
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsModel.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.RAMTapeSortLayerRowsPorts
+import OAI.Computability.VPVNP.RAMTapeSortRowModel
+
+/-!
+# Streams after a prefix of sorting rows
+
+The local record array is immutable during one layer. The selected records
+accumulate in reverse bit order and the row checks accumulate in reverse
+row order. At a cross-site stride the unread messages are suffixes of the
+supplied outgoing and incoming fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortLayerRows
+
+open BurstRAM RAMSort RAMBoundary Boundary
+
+variable {h d w : ℕ}
+
+/-- Right comparator operand at a row, obtained from the partner in the local block for a local
+stride and from the received row for a cross-site stride. -/
+def other (s : Stage (h+d)) (current recv : Wires h (RawSlot w)) (i : Word h) : RawSlot w :=
+ if s.stride < h then current (peerIndex s i) else recv i
+
+/-- Output record at this row after comparing it with its partner and applying the stage's
+minimum-or-maximum orientation. -/
+def selected (s : Stage (h+d)) (v : Word d) (current recv : Wires h (RawSlot w))
+ (i : Word h) : RawSlot w :=
+ SortRow.chosen (keepMin s v i) (current i) (other s current recv i)
+
+/-- Per-row validity bits checking both operands' formats and, on a cross-site stride, equality
+of the sent record with the current row. -/
+def checks (s : Stage (h+d)) (current send recv : Wires h (RawSlot w)) (i : Word h) : List Bool :=
+ SortRow.selectOK (current i) (other s current recv i) ::
+ (if s.stride < h then [] else [SortRow.verifyOK (current i) (send i)])
+
+/-- The pending suffix for a given direction. On a local stride the following
+fields have not been consumed. -/
+def pending (s : Stage (h+d)) (field : Wires h (RawSlot w)) (tail : List Bool) (k : ℕ) : List Bool :=
+ if s.stride < h then tail else blockBytes ((List.ofFn field).drop k) ++ tail
+
+/-- Bits of the first k chosen records in reverse order prepended to the existing next-block
+stack. -/
+def pushed (f : Wires h (RawSlot w)) (next : List Bool) (k : ℕ) : List Bool :=
+ (blockBytes ((List.ofFn f).take k)).reverse ++ next
+
+/-- Flags for the first k completed rows, stacked in reverse row order ahead of earlier flags. -/
+def latched (f : Word h → List Bool) (flags : List Bool) (k : ℕ) : List Bool :=
+ ((List.ofFn f).take k).reverse.flatten ++ flags
+
+theorem pending_cross {s : Stage (h+d)} (hj : ¬s.stride < h) (field : Wires h (RawSlot w))
+ (tail : List Bool) (i : Word h) :
+ pending s field tail i.val = recordBytes (field i) ++ pending s field tail (i.val+1) := by
+ have hi : i.val < (List.ofFn field).length := by simp
+ simp [pending, hj, List.drop_eq_getElem_cons hi, blockBytes, List.append_assoc]
+
+theorem pushed_succ (f : Wires h (RawSlot w)) (next : List Bool) (i : Word h) :
+ pushed f next (i.val+1) = (recordBytes (f i)).reverse ++ pushed f next i.val := by
+ have hi : i.val < (List.ofFn f).length := by simp
+ simp [pushed, List.take_succ_eq_append_getElem hi, blockBytes, List.append_assoc]
+
+theorem latched_succ (f : Word h → List Bool) (flags : List Bool) (i : Word h) :
+ latched f flags (i.val+1) = f i ++ latched f flags i.val := by
+ have hi : i.val < (List.ofFn f).length := by simp
+ simp [latched, List.take_succ_eq_append_getElem hi, List.append_assoc]
+
+/-- Ambient state between callbacks, with all address and record scratch free. -/
+def prefixBank (s : Stage (h+d)) (v : Word d) (current send recv : Wires h (RawSlot w))
+ (next sendTail recvTail flags : List Bool) (k : ℕ) : Stacks Data :=
+ bank v s.phase s.stride w (blockBytes (List.ofFn current)) (pushed (selected s v current recv) next k)
+ (pending s send sendTail k) (pending s recv recvTail k) (latched (checks s current send recv) flags k)
+
+/-- The incident stream at layer entry, beginning with the stage's record block exactly when
+the stride crosses sites. -/
+def fieldsBefore (s : Stage (h+d)) (field : Wires h (RawSlot w)) (tail : List Bool) :=
+ if s.stride < h then tail else blockBytes (List.ofFn field) ++ tail
+
+theorem prefixBank_zero (s : Stage (h+d)) (v : Word d) (current send recv : Wires h (RawSlot w))
+ (next sendTail recvTail flags : List Bool) :
+ prefixBank s v current send recv next sendTail recvTail flags 0 =
+ bank v s.phase s.stride w (blockBytes (List.ofFn current)) next
+ (fieldsBefore s send sendTail) (fieldsBefore s recv recvTail) flags := by
+ simp [prefixBank, pushed, pending, latched, fieldsBefore, blockBytes]
+
+theorem prefixBank_all (s : Stage (h+d)) (v : Word d) (current send recv : Wires h (RawSlot w))
+ (next sendTail recvTail flags : List Bool) :
+ prefixBank s v current send recv next sendTail recvTail flags (2^h) =
+ bank v s.phase s.stride w (blockBytes (List.ofFn current))
+ ((blockBytes (List.ofFn (selected s v current recv))).reverse ++ next) sendTail recvTail
+ ((List.ofFn (checks s current send recv)).reverse.flatten ++ flags) := by
+ have ht {α : Type} (f : Word h → α) : (List.ofFn f).take (2^h) = List.ofFn f :=
+ List.take_of_length_le (by simp)
+ have hd {α : Type} (f : Word h → α) : (List.ofFn f).drop (2^h) = [] :=
+ List.drop_eq_nil_of_le (by simp)
+ simp [prefixBank, pushed, pending, latched, ht, hd, blockBytes]
+
+/-- The counter pass and the two physical record lookups per row have a quadratic
+bound in the local row count, with linear dependence on the two widths. -/
+def budget (h d w a j : ℕ) : ℕ :=
+ 6*h+7 + 2^h*(SortRowAddress.budget h d a j + 4096*(2^h+1)*(w+1) + 4*h+6)
+
+theorem budget_le (s : Stage (h+d)) :
+ budget h d w s.phase s.stride ≤ 8192*(2^h+1)^2*(h+d+w+1) := by
+ let N := 2^h
+ let m := h+d+w+1
+ have ha := s.phase_le
+ have hj := s.stride_lt
+ have hm : 1 ≤ m := by dsimp [m]; omega
+ let C := (N+1)*m
+ have hn : 1 ≤ N+1 := Nat.succ_pos _
+ have hnm : h+d+w+1 ≤ C := Nat.le_mul_of_pos_left m hn
+ have hnn : N ≤ C := (Nat.le_succ _).trans (Nat.le_mul_of_pos_right _ hm)
+ have hmul : (N+1)*(w+1) ≤ C := Nat.mul_le_mul_left _ (by dsimp [m]; omega)
+ have hstep : SortRowAddress.budget h d s.phase s.stride + 4096*(N+1)*(w+1) + 4*h+6 ≤
+ 8192*((N+1)*m) := by
+ unfold SortRowAddress.budget
+ rw [Nat.mul_assoc 4096]
+ change 28*h+16*d+6*s.phase+12*s.stride+7*N+29 + 4096*((N+1)*(w+1)) + 4*h+6 ≤ 8192*C
+ omega
+ have hsmall : 6*h+7 ≤ 8192*C := by omega
+ calc
+ budget h d w s.phase s.stride ≤ 8192*((N+1)*m) + N*(8192*((N+1)*m)) :=
+ Nat.add_le_add hsmall (Nat.mul_le_mul_left N hstep)
+ _ = 8192*(N+1)^2*m := by ring
+
+end RAMTape.SortLayerRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsPorts.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsPorts.lean
new file mode 100644
index 0000000000..710316d523
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsPorts.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.RAMTapeSortOffsets
+import OAI.Computability.VPVNP.RAMTapeSortRowAddress
+import OAI.Computability.VPVNP.RAMTapeSortRowPorts
+
+/-!
+# Stack assignments inside a sorting layer
+
+The address routine reads the binary index, and the record lookup reads
+its unary copy. The partner count and two decision bits go directly from
+the address routine to the record routine. Both routines preserve the
+site identifier and the stage counters throughout the traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortLayerRows
+
+open BurstRAM RAMSort RAMBoundary
+
+/-- Site address, stage counters, observed wire bits and scratch stacks used when computing the
+comparator's partner and orientation. -/
+inductive Extra
+ | site | phase | stride | observed (axis : SortRowAddress.Axis) | bits | count | rev | tmp
+ deriving DecidableEq, Fintype
+
+/-- Combine the record-operation ports with the additional ports for computing a row's address
+and partner. -/
+abbrev Data := SortRow.Port ⊕ Extra
+/-- The layer's data stacks together with the row iterator's binary and unary counters. -/
+abbrev Port := Data ⊕ SortOffsets.Port
+
+/-- Connect the record routine's row offset to the iterator's unary counter and its other
+operands to the layer data. -/
+def rowPorts : SortRow.Port → Port
+ | .row => .inr .unary
+ | p => .inl (.inl p)
+
+/-- Route the address computation to the iterator's binary row index, preserved site and stage
+parameters, and its decision and scratch stacks. -/
+def addressPorts : SortRowAddress.Port → Port
+ | .row => .inr .index
+ | .site => .inl (.inr .site)
+ | .index .phase => .inl (.inr .phase)
+ | .index .stride => .inl (.inr .stride)
+ | .orientation => .inl (.inl .orientation)
+ | .offset => .inl (.inl .partner)
+ | .localFlag => .inl (.inl .localFlag)
+ | .observed a => .inl (.inr (.observed a))
+ | .bits => .inl (.inr .bits)
+ | .count => .inl (.inr .count)
+ | .rev => .inl (.inr .rev)
+ | .tmp => .inl (.inr .tmp)
+
+theorem rowPorts_injective : Function.Injective rowPorts := by decide
+theorem addressPorts_injective : Function.Injective addressPorts := by decide
+
+/-- The site and stage data shared by consecutive visits. Only the accumulated
+output, the two exchange streams, and the list of flags change during a layer. -/
+def bank {d : ℕ} (v : Word d) (a j w : ℕ)
+ (current next send recv flags : List Bool) : Stacks Data
+ | .inl .current => current
+ | .inl .next => next
+ | .inl .crossSend => send
+ | .inl .crossReceive => recv
+ | .inl .width => List.replicate w true
+ | .inl .flags => flags
+ | .inr .site => wordBits v
+ | .inr .phase => List.replicate a true
+ | .inr .stride => List.replicate j true
+ | _ => []
+
+/-- This wire keeps the smaller record precisely when the stride bit and phase bit of its
+global wire index agree. -/
+def keepMin {h d : ℕ} (s : Stage (h+d)) (v : Word d) (i : Word h) : Bool :=
+ let g := v.val * 2^h + i.val
+ g.testBit s.stride == g.testBit s.phase
+
+/-- For an in-site stride, toggle its bit in the row index to find the partner. A cross-site
+comparator uses the same row at the peer site. -/
+def peerIndex {h d : ℕ} (s : Stage (h+d)) (i : Word h) : Word h :=
+ if hj : s.stride < h then ⟨partner s.stride i, partner_lt i.isLt hj⟩ else i
+
+/-- The prepared row has its three address outputs installed in the record
+routine's input ports, with every other port equal to the callback's entry. -/
+def prepared {h d : ℕ} (s : Stage (h+d)) (v : Word d) (i : Word h) (data : Stacks Data) : Stacks Port :=
+ let orig := SortOffsets.visit data i
+ fun p => match p with
+ | .inl (.inl .orientation) => [keepMin s v i]
+ | .inl (.inl .localFlag) => [decide (s.stride < h)]
+ | .inl (.inl .partner) => List.replicate (peerIndex s i).val true
+ | _ => orig p
+
+/-- Running the installed address machine leaves all pending tape streams
+available to the record operation on that row. -/
+theorem address_run {h d w : ℕ} (s : Stage (h+d)) (v : Word d) (i : Word h)
+ (cur next send recv flags : List Bool) :
+ let b := bank v s.phase s.stride w cur next send recv flags
+ ∃ t ≤ SortRowAddress.budget h d s.phase s.stride,
+ (SortRowAddress.routine.onPorts addressPorts).Runs t (SortOffsets.visit b i) (prepared s v i b) := by
+ obtain ⟨t,ht,hr⟩ := SortRowAddress.runs i v s.phase s.stride
+ refine ⟨t, ht, ?_⟩
+ apply FiniteRoutine.runs_onPorts_framed _ addressPorts_injective hr
+ · intro p
+ rw [SortRowAddress.initial_port]
+ cases p <;> first | rfl | rename_i ax; cases ax <;> rfl
+ · intro p
+ rw [SortRowAddress.final_port, SortRowAddress.initial_port]
+ cases p with
+ | index ax => cases ax <;> rfl
+ | offset =>
+ by_cases hj : s.stride < h <;> simp [prepared, addressPorts, peerIndex, hj]
+ | _ => rfl
+ · intro p hp
+ rcases p with (r | e) | f
+ · cases r <;> first | rfl | exact (hp .orientation rfl).elim
+ | exact (hp .offset rfl).elim | exact (hp .localFlag rfl).elim
+ · rfl
+ · rfl
+
+end RAMTape.SortLayerRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsPost.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsPost.lean
new file mode 100644
index 0000000000..a8df555c3b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsPost.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.RAMTapeSortLayerRowsPorts
+import OAI.Computability.VPVNP.RAMTapeSortRowModel
+
+/-!
+# Installing a record comparison in the row traversal
+
+The partner offset and decision bits produced by the address routine satisfy
+the record routine's input conditions. A comparison changes the pending
+output, exchange streams and flags. The traversal retains its binary and
+unary row indices for the subsequent increment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortLayerRows
+
+open BurstRAM RAMSort RAMBoundary Boundary
+
+/-- The address computation has prepared all record operands and scratch stacks. -/
+theorem prepared_ready {h d w : ℕ} (s : Stage (h+d)) (v : Word d) (i : Word h)
+ (block : Word h → RawSlot w) (next send recv flags : List Bool) :
+ SortRow.Ready
+ (prepared s v i (bank v s.phase s.stride w (blockBytes (List.ofFn block)) next send recv flags) ∘ rowPorts)
+ block i (peerIndex s i) (decide (s.stride < h)) (keepMin s v i) := by
+ constructor <;> first | rfl | constructor <;> rfl
+
+/-- Install a record routine's execution on the layer ports. The next row
+will see the selected record and flags at the heads of their reverse streams. -/
+theorem row_run {h d w t : ℕ} (s : Stage (h+d)) (v : Word d) (i : Word h)
+ (cur next send recv flags : List Bool) (a b : RawSlot w) (sent : Option (RawSlot w))
+ (sendTail recvTail : List Bool) (prog : FiniteRoutine SortRow.Port)
+ (hr : let rs := prepared s v i (bank v s.phase s.stride w cur next send recv flags) ∘ rowPorts
+ prog.Runs t rs (SortRow.result rs (keepMin s v i) a b sent sendTail recvTail)) :
+ (prog.onPorts rowPorts).Runs t
+ (prepared s v i (bank v s.phase s.stride w cur next send recv flags))
+ (SortOffsets.visit (bank v s.phase s.stride w cur
+ ((recordBytes (SortRow.chosen (keepMin s v i) a b)).reverse ++ next) sendTail recvTail
+ (SortRow.selectOK a b :: sent.elim flags (fun x => SortRow.verifyOK a x :: flags))) i) := by
+ apply FiniteRoutine.runs_onPorts_framed _ rowPorts_injective hr
+ · intro p; rfl
+ · intro p; cases p <;> rfl
+ · intro p hp
+ rcases p with (r | e) | f
+ · cases r <;> first | rfl | exact (hp .next rfl).elim
+ | exact (hp .crossSend rfl).elim | exact (hp .crossReceive rfl).elim
+ | exact (hp .partner rfl).elim | exact (hp .orientation rfl).elim
+ | exact (hp .localFlag rfl).elim | exact (hp .flags rfl).elim
+ · cases e <;> rfl
+ · rfl
+
+end RAMTape.SortLayerRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsProgram.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsProgram.lean
new file mode 100644
index 0000000000..43ebbce82c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortLayerRowsProgram.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.RAMTapeSortLayerRowsModel
+import OAI.Computability.VPVNP.RAMTapeSortLayerRowsPost
+import OAI.Computability.VPVNP.RAMTapeSortRowProgram
+
+/-!
+# Composing the address, record and counter controls for one sorting layer
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortLayerRows
+
+open BurstRAM RAMSort RAMBoundary Boundary
+
+/-- Compute the partner and comparison direction from the row address, then execute the record
+routine on that row. -/
+def row : FiniteRoutine Port :=
+ (SortRowAddress.routine.onPorts addressPorts).followedBy (SortRow.program.onPorts rowPorts)
+
+/-- Use the finite row iterator to execute the address and record routines at every row in the
+layer. -/
+def program : FiniteRoutine Port := SortOffsets.routine row
+
+variable {h d w : ℕ} (s : Stage (h+d)) (v : Word d) (current send recv : Wires h (RawSlot w))
+ (next sendTail recvTail flags : List Bool)
+
+/-- The physical record subroutine consumes the two field heads precisely on
+a nonlocal stride. The next unread message offsets are the suffixes at `i+1`. -/
+def recordVisit (i : Word h) : Prop :=
+ let data := prefixBank s v current send recv next sendTail recvTail flags i.val
+ let rs := prepared s v i data ∘ rowPorts
+ ∃ t ≤ 4096*(2^h+1)*(w+1), SortRow.program.Runs t rs
+ (SortRow.result rs (keepMin s v i) (current i) (other s current recv i)
+ (if s.stride < h then none else some (send i))
+ (pending s send sendTail (i.val+1)) (pending s recv recvTail (i.val+1)))
+
+/-- Each address preparation reaches the exact inputs of the record routine.
+The outputs update all four streams for the subsequent row. -/
+theorem visit_run (i : Word h) (hr : recordVisit s v current send recv next sendTail recvTail flags i) :
+ let data := prefixBank s v current send recv next sendTail recvTail flags
+ ∃ t ≤ SortRowAddress.budget h d s.phase s.stride + 4096*(2^h+1)*(w+1),
+ row.Runs t (SortOffsets.visit (data i.val) i) (SortOffsets.visit (data (i.val+1)) i) := by
+ let cur := blockBytes (List.ofFn current)
+ let output := pushed (selected s v current recv) next i.val
+ let ss := pending s send sendTail i.val
+ let rr := pending s recv recvTail i.val
+ let fs := latched (checks s current send recv) flags i.val
+ obtain ⟨t,ht,ha⟩ := address_run s v i cur output ss rr fs
+ obtain ⟨u,hu,hrec⟩ := hr
+ have hrun := row_run s v i cur output ss rr fs (current i) (other s current recv i)
+ (if s.stride < h then none else some (send i)) (pending s send sendTail (i.val+1))
+ (pending s recv recvTail (i.val+1)) SortRow.program hrec
+ have he :
+ SortRow.selectOK (current i) (other s current recv i) ::
+ (if s.stride < h then none else some (send i)).elim fs (fun x => SortRow.verifyOK (current i) x :: fs) =
+ checks s current send recv i ++ fs := by
+ by_cases hj : s.stride < h <;> simp [checks,hj]
+ rw [he] at hrun
+ refine ⟨_, Nat.add_le_add ht hu, ?_⟩
+ simpa only [row, cur, output, ss, rr, fs, prefixBank, pushed_succ, latched_succ, selected] using
+ (FiniteRoutine.Runs.followedBy ha hrun)
+
+/-- The concrete counter traversal consumes the message blocks and accumulates
+the selected rows and their flags. -/
+theorem runs_of_visits
+ (hr : ∀ i, recordVisit s v current send recv next sendTail recvTail flags i) :
+ ∃ t ≤ budget h d w s.phase s.stride, program.Runs t
+ (SortOffsets.idle (bank v s.phase s.stride w (blockBytes (List.ofFn current)) next
+ (fieldsBefore s send sendTail) (fieldsBefore s recv recvTail) flags) h)
+ (SortOffsets.idle (bank v s.phase s.stride w (blockBytes (List.ofFn current))
+ ((blockBytes (List.ofFn (selected s v current recv))).reverse ++ next) sendTail recvTail
+ ((List.ofFn (checks s current send recv)).reverse.flatten ++ flags)) h) := by
+ have hrun := SortOffsets.runs row (prefixBank s v current send recv next sendTail recvTail flags) h
+ (SortRowAddress.budget h d s.phase s.stride + 4096*(2^h+1)*(w+1))
+ (fun i => visit_run s v current send recv next sendTail recvTail flags i (hr i))
+ simpa only [budget, program, prefixBank_zero, prefixBank_all] using hrun
+
+end RAMTape.SortLayerRows
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortOffsets.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortOffsets.lean
new file mode 100644
index 0000000000..746c76c55a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortOffsets.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.RAMTapeSortOffsetsCode
+import OAI.Computability.VPVNP.StructuredStackLoop
+
+/-!
+# Visiting the physical rows of a sorting layer
+
+A single finite routine visits the offsets in increasing order. The caller
+can use the fixed-width binary row for the direction and partner tests and
+the unary row to gather its record. The callback's other tape streams pass
+from one visit to the next.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortOffsets
+
+open BurstRAM UnaryWord TapeWord
+
+variable {K : Type}
+
+/-- Only the row width is occupied between successive traversals. -/
+def idle (data : Stacks K) (h : ℕ) : Stacks (K ⊕ Port) :=
+ Sum.elim data (store (ones h) [] [] [] [])
+
+private def row (data : Stacks K) (h i : ℕ) (flag : List Bool) : Stacks (K ⊕ Port) :=
+ Sum.elim data (store (ones h) (wordBits (Fin.ofNat (2^h) i)) (ones i) [] flag)
+
+/-- The callback's ports at a physical row. The temporary and loop-flag stacks are empty. -/
+def visit (data : Stacks K) {h : ℕ} (i : Fin (2^h)) : Stacks (K ⊕ Port) :=
+ Sum.elim data (store (ones h) (wordBits i) (ones i.val) [] [])
+
+private def part (q : Phase) : FiniteRoutine (K ⊕ Port) :=
+ FiniteRoutine.ofStackCode code Sum.inr q (· == .done)
+
+private def loop (body : FiniteRoutine (K ⊕ Port)) : FiniteRoutine (K ⊕ Port) :=
+ FiniteRoutine.ofRoutine (Routine.popLoop (.inr Port.again) id Routine.ret
+ (body.followedBy (part (.add true))).body)
+
+/-- Fixed control independent of the input width, row count, and record size. -/
+def routine (body : FiniteRoutine (K ⊕ Port)) : FiniteRoutine (K ⊕ Port) :=
+ ((part .init).followedBy (loop body)).followedBy (part .clearIndex)
+
+variable [DecidableEq K]
+
+private theorem part_run {q : Phase} (hq : q ≠ .done) {s t : Stacks Port} {m : ℕ}
+ (run : StackRuns code m q s .done t) (data : Stacks K) :
+ (part q).Runs m (Sum.elim data s) (Sum.elim data t) := by
+ apply FiniteRoutine.runs_ofStackCode_framed Sum.inr_injective (normal := (· == .done))
+ (by simpa using hq) rfl (fun u h => by simp only [beq_iff_eq] at h; subst u; rfl) run
+ · intro; rfl
+ · intro; rfl
+ · intro p hp; cases p with
+ | inl k => rfl
+ | inr k => exact (hp k rfl).elim
+
+private theorem pop_flag (data : Stacks K) (h i : ℕ) (b : Bool) :
+ Function.update (row data h i [b]) (.inr Port.again) [] = row data h i [] := by
+ funext p; cases p with
+ | inl k => simp [row]
+ | inr p => cases p <;> simp [row, store]
+
+private theorem ofNat_val {h i : ℕ} (hi : i < 2^h) :
+ (Fin.ofNat (2^h) i).val = i := Nat.mod_eq_of_lt hi
+
+omit [DecidableEq K] in
+private theorem visit_eq_row (data : Stacks K) {h i : ℕ} (hi : i < 2^h) :
+ visit data ⟨i,hi⟩ = row data h i [] := by
+ simp only [visit, row, show Fin.ofNat (2^h) i = ⟨i,hi⟩ from Fin.ext (ofNat_val hi)]
+
+private theorem advance {h i : ℕ} (hi : i < 2^h) (data : Stacks K) :
+ (part (.add true)).Runs (4*h+4) (row data h i [])
+ (row data h (i+1) [decide (i+1 < 2^h)]) := by
+ let x := wordBits (Fin.ofNat (2^h) i)
+ have hx : x.length = h := length_wordBits _
+ have hv : value x = i := (value_wordBits _).trans (ofNat_val hi)
+ have hl : (incScan true x).1.length = h := (incScan_length ..).trans hx
+ have ha := incScan_value true x
+ rw [hx, hv, Bool.toNat_true] at ha
+ have hsmall := value_lt (incScan true x).1
+ rw [hl] at hsmall
+ have ho : (!(incScan true x).2) = decide (i+1 < 2^h) := by
+ cases hh : (incScan true x).2 <;> simp [hh] at ha ⊢ <;> omega
+ have hout : (incScan true x).1 = wordBits (Fin.ofNat (2^h) (i+1)) := by
+ apply eq_of_length_value (hl.trans (length_wordBits _).symm)
+ rw [value_wordBits]
+ change value (incScan true x).1 = (i+1) % (2^h)
+ cases hh : (incScan true x).2
+ · simp only [hh, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at ha
+ rw [← ha, Nat.mod_eq_of_lt hsmall]
+ · simp only [hh, Bool.toNat_true, Nat.mul_one] at ha
+ have he : i+1 = 2^h := by omega
+ rw [he, Nat.mod_self]
+ omega
+ have hr := part_run (by decide : Phase.add true ≠ .done) (advance_run (ones h) x (ones i)) data
+ simpa only [hx, hout, ho, row, ones, List.replicate_succ] using hr
+
+private theorem loop_run (body : FiniteRoutine (K ⊕ Port)) (data : ℕ → Stacks K) (h T : ℕ)
+ (bodyRun : ∀ i : Fin (2^h), ∃ t ≤ T,
+ body.Runs t (visit (data i.val) i) (visit (data (i.val+1)) i))
+ (m i : ℕ) (hs : m+i = 2^h) :
+ ∃ t ≤ m*(T+4*h+5)+2, (loop body).Runs t
+ (row (data i) h i [decide (i < 2^h)]) (row (data (2^h)) h (2^h) []) := by
+ induction m generalizing i with
+ | zero =>
+ have he : i = 2^h := by omega
+ subst i
+ simp only [Nat.lt_irrefl, decide_false, Nat.zero_mul, Nat.zero_add]
+ refine ⟨2, le_rfl, ?_⟩
+ apply Routine.Runs.popLoop_false_stop (.inr Port.again) id Routine.ret
+ (body.followedBy (part (.add true))).body (s := row (data (2^h)) h (2^h) [false])
+ (n := 1) rfl rfl
+ rw [pop_flag]
+ exact Routine.runs_ret _
+ | succ m ih =>
+ have hi : i < 2^h := by omega
+ have hre : decide (i < 2^h) = true := decide_eq_true hi
+ obtain ⟨t, ht, hb⟩ := bodyRun ⟨i,hi⟩
+ simp only [visit_eq_row] at hb
+ have ha := advance hi (data (i+1))
+ have hr := hb.followedBy ha
+ obtain ⟨s, hs', hr'⟩ := ih (i+1) (by omega)
+ rw [hre]
+ refine ⟨1+(t+(4*h+4))+s, ?_, ?_⟩
+ · rw [Nat.succ_mul m]; omega
+ · let hiBody := (body.followedBy (part (.add true))).body
+ change (Routine.popLoop (.inr Port.again) id Routine.ret hiBody).Runs _ _ _ at hr' ⊢
+ exact Routine.Runs.popLoop_true_continue (.inr Port.again) id Routine.ret hiBody
+ (s := row (data i) h i [true]) (tail := []) (n := t+(4*h+4)) (m := s)
+ (mid := row (data (i+1)) h (i+1) [decide (i+1 < 2^h)]) rfl rfl
+ (by rw [pop_flag]; exact hr) hr'
+
+/-- A traversal makes one callback for each physical row, in increasing order.
+The additive charge per row is linear in its binary width and includes the
+cleanup of the unary offsets after the last callback. -/
+theorem runs (body : FiniteRoutine (K ⊕ Port)) (data : ℕ → Stacks K) (h T : ℕ)
+ (bodyRun : ∀ i : Fin (2^h), ∃ t ≤ T,
+ body.Runs t (visit (data i.val) i) (visit (data (i.val+1)) i)) :
+ ∃ t ≤ 6*h+7 + 2^h*(T+4*h+6), (routine body).Runs t (idle (data 0) h) (idle (data (2^h)) h) := by
+ have hinit : (part .init).Runs (5*h+3) (idle (data 0) h) (row (data 0) h 0 [true]) :=
+ part_run (by decide : Phase.init ≠ .done) (initialize_run h) (data 0)
+ obtain ⟨t, ht, hloop⟩ := loop_run body data h T bodyRun (2^h) 0 (by omega)
+ rw [decide_eq_true (Nat.two_pow_pos _)] at hloop
+ let x := wordBits (Fin.ofNat (2^h) (2^h))
+ have hclear := part_run (by decide : Phase.clearIndex ≠ .done)
+ (clear_run (ones h) x (ones (2^h))) (data (2^h))
+ simp only [x, ones, length_wordBits, List.length_replicate] at hclear
+ refine ⟨_, ?_, (hinit.followedBy hloop).followedBy hclear⟩
+ rw [show T+4*h+6 = (T+4*h+5)+1 by omega, Nat.mul_succ]
+ omega
+
+end RAMTape.SortOffsets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortOffsetsCode.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortOffsetsCode.lean
new file mode 100644
index 0000000000..241ead63af
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortOffsetsCode.lean
@@ -0,0 +1,171 @@
+import OAI.Computability.VPVNP.RAMTapeUnaryWordValue
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Fixed stack controls for a physical sorting row counter
+
+The width arrives on a unary stack. Initialization builds a zero word of
+that width and restores the width tally. Each advance adds one to the binary
+and unary counters. The outgoing carry records when the traversal has reached
+the last row, including the one-row case at width zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortOffsets
+
+open BurstRAM UnaryWord TapeWord
+
+/-- Stacks for the unary row width, binary row index, unary row index, temporary bits and
+continuation flag. -/
+inductive Port | width | index | unary | tmp | again
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Control for initializing the binary index from the width, advancing binary and unary row
+counts, and recording overflow at the final row. -/
+inductive Phase
+ | init | zeroBit | saveWidth | restoreWidth | widthMark | start
+ | add (carry : Bool) | emit (b carry : Bool)
+ | restore (overflow : Bool) | put (b overflow : Bool)
+ | next (overflow : Bool) | flag (overflow : Bool)
+ | clearIndex | clearUnary | done
+ deriving DecidableEq, Fintype
+
+/-- Build a width-sized zero index and execute a carry-propagating row increment while
+maintaining its unary copy. -/
+def code : StackCode Port Phase
+ | .init => .pop .width fun b => b.elim .restoreWidth (fun _ => .zeroBit)
+ | .zeroBit => .push .index false .saveWidth
+ | .saveWidth => .push .tmp true .init
+ | .restoreWidth => .pop .tmp fun b => b.elim .start (fun _ => .widthMark)
+ | .widthMark => .push .width true .restoreWidth
+ | .start => .push .again true .done
+ | .add carry => .pop .index fun b =>
+ b.elim (.restore carry) (fun bit => .emit (bit ^^ carry) (bit && carry))
+ | .emit b c => .push .tmp b (.add c)
+ | .restore ov => .pop .tmp fun b => b.elim (.next ov) (fun bit => .put bit ov)
+ | .put b ov => .push .index b (.restore ov)
+ | .next ov => .push .unary true (.flag ov)
+ | .flag ov => .push .again (!ov) .done
+ | .clearIndex => .pop .index fun b => b.elim .clearUnary (fun _ => .clearIndex)
+ | .clearUnary => .pop .unary fun b => b.elim .done (fun _ => .clearUnary)
+ | .done => .halt true
+
+/-- Install the width, binary index, unary index, scratch and continuation bit lists on the
+row-counter ports. -/
+def store (w x u tmp again : List Bool) : Stacks Port
+ | .width => w
+ | .index => x
+ | .unary => u
+ | .tmp => tmp
+ | .again => again
+
+private theorem set_store (w x u t f v : List Bool) (k : Port) :
+ Function.update (store w x u t f) k v = match k with
+ | .width => store v x u t f
+ | .index => store w v u t f
+ | .unary => store w x v t f
+ | .tmp => store w x u v f
+ | .again => store w x u t v := by
+ funext j; cases k <;> cases j <;> simp [store]
+
+local macro "offset_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, set_store, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none])
+
+/-- Unary encoding of a natural number as that many true bits. -/
+abbrev ones (n : ℕ) := List.replicate n true
+private abbrev zeros (n : ℕ) := List.replicate n false
+
+private theorem alloc_run (n : ℕ) (x t : List Bool) :
+ StackRuns code (3*n+1) .init (store (ones n) x [] t [])
+ .restoreWidth (store [] (zeros n ++ x) [] (ones n ++ t) []) := by
+ induction n generalizing x t with
+ | zero => offset_step; exact .nil ..
+ | succ n ih =>
+ simp only [Nat.mul_succ]
+ change StackRuns code _ _ (store (true :: ones n) x [] t []) _ _
+ offset_step; offset_step; offset_step
+ simpa only [zeros, ones, List.replicate_succ', List.append_assoc, List.singleton_append] using
+ ih (false :: x) (true :: t)
+
+private theorem width_run (n : ℕ) (w x : List Bool) :
+ StackRuns code (2*n+2) .restoreWidth (store w x [] (ones n) []) .done
+ (store (ones n ++ w) x [] [] [true]) := by
+ induction n generalizing w with
+ | zero => offset_step; offset_step; exact .nil ..
+ | succ n ih =>
+ rw [show 2*(n+1)+2 = (2*n+2)+1+1 by omega]
+ change StackRuns code _ _ (store w x [] (true :: ones n) []) _ _
+ rw [show ones (n+1) ++ w = ones n ++ true :: w by
+ simp [ones, List.replicate_succ', List.append_assoc]]
+ offset_step; offset_step
+ exact ih (true :: w)
+
+/-- Initialize from the supplied width. -/
+theorem initialize_run (h : ℕ) :
+ StackRuns code (5*h+3) .init (store (ones h) [] [] [] []) .done
+ (store (ones h) (wordBits (0 : Word h)) [] [] [true]) := by
+ have h₁ := alloc_run h [] []
+ have h₂ := width_run h [] (zeros h)
+ simp only [List.append_nil] at h₁ h₂
+ simpa only [zeros_wordBits, show 3*h+1+(2*h+2) = 5*h+3 by omega] using h₁.trans h₂
+
+private theorem scan_run (carry : Bool) (w x u t : List Bool) :
+ StackRuns code (2*x.length+1) (.add carry) (store w x u t [])
+ (.restore (incScan carry x).2) (store w [] u ((incScan carry x).1.reverse ++ t) []) := by
+ induction x generalizing carry t with
+ | nil => offset_step; exact .nil ..
+ | cons b x ih =>
+ simp only [List.length_cons, Nat.mul_succ, incScan, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ offset_step; offset_step
+ exact ih (b && carry) ((b ^^ carry) :: t)
+
+private theorem restore_run (ov : Bool) (w x u t : List Bool) :
+ StackRuns code (2*t.length+3) (.restore ov) (store w x u t []) .done
+ (store w (t.reverse ++ x) (true :: u) [] [!ov]) := by
+ induction t generalizing x with
+ | nil => offset_step; offset_step; offset_step; exact .nil ..
+ | cons b t ih =>
+ rw [show 2*(b::t).length+3 = (2*t.length+3)+1+1 by simp [Nat.mul_succ]]
+ simp only [List.reverse_cons, List.append_assoc, List.singleton_append]
+ offset_step; offset_step
+ exact ih (b :: x)
+
+/-- Advance both counters and set the continuation flag from the binary carry out. -/
+theorem advance_run (w x u : List Bool) :
+ StackRuns code (4*x.length+4) (.add true) (store w x u [] []) .done
+ (store w (incScan true x).1 (true :: u) [] [!(incScan true x).2]) := by
+ have h₁ := scan_run true w x u []
+ have h₂ := restore_run (incScan true x).2 w [] u (incScan true x).1.reverse
+ simp only [List.append_nil, List.length_reverse, List.reverse_reverse, incScan_length] at h₁ h₂
+ simpa only [show 2*x.length+1+(2*x.length+3) = 4*x.length+4 by omega] using h₁.trans h₂
+
+private theorem clear_unary (w u : List Bool) :
+ StackRuns code (u.length+1) .clearUnary (store w [] u [] []) .done (store w [] [] [] []) := by
+ induction u with
+ | nil => offset_step; exact .nil ..
+ | cons b u ih => offset_step; exact ih
+
+/-- Clear both counters after the final row. -/
+theorem clear_run (w x u : List Bool) :
+ StackRuns code (x.length+u.length+2) .clearIndex (store w x u [] []) .done (store w [] [] [] []) := by
+ induction x with
+ | nil => offset_step; simpa using clear_unary w u
+ | cons b x ih =>
+ rw [show (b::x).length+u.length+2 = (x.length+u.length+2)+1 by simp; omega]
+ offset_step
+ exact ih
+
+end RAMTape.SortOffsets
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortOneStage.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortOneStage.lean
new file mode 100644
index 0000000000..c5a9d6e8ce
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortOneStage.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.RAMTapeSortOneStageModel
+import OAI.Computability.VPVNP.RAMTapeSortLayerRows
+
+/-! # Executing one sorting stage of the transcript validator
+
+The finite routine splits the incident field when the stride crosses sites,
+visits every row, then reverses the accumulated output into the current block.
+The entire operation uses the live unary phase and stride of the schedule.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortOneStage
+
+open BurstRAM RAMSort RAMBoundary Boundary
+
+/-- Prepare the stage's incident streams, visit every row under its phase and stride, then
+expose the selected next block in forward order. -/
+def program : FiniteRoutine Port :=
+ (prepare.followedBy (SortLayerRows.program.onPorts Sum.inl)).followedBy advance
+
+/-- A single callback for the schedule's nested phase and stride loops. -/
+def layer : FiniteRoutine (SortSchedule.Port Port) := program.onPorts schedulePorts
+
+variable {h d w : ℕ}
+
+/-- The validator returns the selected local block, the unconsumed tail of
+the incident stream, and the comparator flags in reverse row order. -/
+theorem runs (hw : 2 ≤ w) (s : Stage (h+d)) (v : Word d) (left : ℕ)
+ (current send recv : Wires h (RawSlot w)) (tail flags : List Bool) :
+ ∃ t ≤ budget h d w, layer.Runs t
+ (SortSchedule.bank (data v w h current (stream s send recv tail) flags) left s.phase s.stride)
+ (SortSchedule.bank (data v w h (SortLayerRows.selected s v current recv) tail
+ ((List.ofFn (SortLayerRows.checks s current send recv)).reverse.flatten ++ flags)) left s.phase s.stride) := by
+ obtain ⟨t, ht, first⟩ := prepare_runs s v current send recv tail flags
+ obtain ⟨u, hu, scan⟩ := SortLayerRows.runs hw s v current send recv [] [] tail flags
+ simp only [List.append_nil] at scan
+ have rows := rows_runs v s.phase s.stride w h scan
+ let out := SortLayerRows.selected s v current recv
+ let checks := (List.ofFn (SortLayerRows.checks s current send recv)).reverse.flatten ++ flags
+ have move := advance_runs v s.phase s.stride w h (blockBytes (List.ofFn current))
+ (blockBytes (List.ofFn out)) tail checks
+ have native := (first.followedBy rows).followedBy move
+ simp only [length_blockBytes, List.length_ofFn] at native
+ refine ⟨_, ?_, schedule_run v s.phase s.stride w h left current out _ flags tail checks
+ (native := program) native⟩
+ have hu' := hu.trans (SortLayerRows.budget_le s)
+ unfold budget
+ omega
+
+theorem runs_local (hw : 2 ≤ w) (s : Stage (h+d)) (hl : s.stride < h) (v : Word d) (left : ℕ)
+ (current send recv : Wires h (RawSlot w)) (tail flags : List Bool) :
+ ∃ t ≤ budget h d w, layer.Runs t (SortSchedule.bank (data v w h current tail flags) left s.phase s.stride)
+ (SortSchedule.bank (data v w h (SortLayerRows.selected s v current recv) tail
+ ((List.ofFn (SortLayerRows.checks s current send recv)).reverse.flatten ++ flags)) left s.phase s.stride) := by
+ simpa only [stream, hl, ↓reduceIte] using runs hw s v left current send recv tail flags
+
+theorem runs_cross (hw : 2 ≤ w) (s : Stage (h+d)) (hc : h ≤ s.stride) (v : Word d) (left : ℕ)
+ (current send recv : Wires h (RawSlot w)) (tail flags : List Bool) :
+ ∃ t ≤ budget h d w, layer.Runs t
+ (SortSchedule.bank (data v w h current (blockBytes (List.ofFn send) ++ (blockBytes (List.ofFn recv) ++ tail))
+ flags) left s.phase s.stride)
+ (SortSchedule.bank (data v w h (SortLayerRows.selected s v current recv) tail
+ ((List.ofFn (SortLayerRows.checks s current send recv)).reverse.flatten ++ flags)) left s.phase s.stride) := by
+ simpa only [stream, Nat.not_lt.mpr hc, ↓reduceIte] using runs hw s v left current send recv tail flags
+
+end RAMTape.SortOneStage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortOneStageModel.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortOneStageModel.lean
new file mode 100644
index 0000000000..e77462c214
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortOneStageModel.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.RAMTapeSortOneStagePorts
+import OAI.Computability.VPVNP.RAMTapeSortLayerRowsModel
+
+/-! # The incident stream and cost of one physical sorting layer -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortOneStage
+
+open BurstRAM RAMSort RAMBoundary Boundary
+
+variable {h d w : ℕ}
+
+/-- The next two physical blocks precede the remaining stream at a cross-site layer. -/
+def stream (s : Stage (h+d)) (send recv : Wires h (RawSlot w)) (tail : List Bool) : List Bool :=
+ if s.stride < h then tail else blockBytes (List.ofFn send) ++ (blockBytes (List.ofFn recv) ++ tail)
+
+theorem prepare_runs (s : Stage (h+d)) (v : Word d) (current send recv : Wires h (RawSlot w))
+ (tail flags : List Bool) :
+ ∃ t ≤ 6*h+8+SortBoundary.splitCost (2^h) w,
+ prepare.Runs t (bank v s.phase s.stride w h (blockBytes (List.ofFn current)) [] []
+ (stream s send recv tail) flags)
+ (bank v s.phase s.stride w h (blockBytes (List.ofFn current)) []
+ (SortLayerRows.fieldsBefore s send []) (SortLayerRows.fieldsBefore s recv tail) flags) := by
+ by_cases hl : s.stride < h
+ · simp only [stream, SortLayerRows.fieldsBefore, hl, ↓reduceIte]
+ exact ⟨_, by omega, prepare_local v s.phase s.stride w h _ _ _ hl⟩
+ · simp only [stream, SortLayerRows.fieldsBefore, hl, ↓reduceIte, List.append_nil]
+ exact ⟨_, by omega, prepare_cross v s.phase s.stride w h _ _ _ _ (by omega) (by simp)⟩
+
+/-- A common bound for all stages, covering split, row visits, and block reversal. -/
+def budget (h d w : ℕ) :=
+ 6*h+8 + SortBoundary.splitCost (2^h) w + 8192*(2^h+1)^2*(h+d+w+1) + 3*(2^h*(5*w)) + 2
+
+theorem budget_le (h d w : ℕ) : budget h d w ≤ 16384*(2^h+1)^2*(h+d+w+1) := by
+ let n := 2^h
+ let m := h+d+w+1
+ have hnm : n*(w+1) ≤ (n+1)^2*m := by
+ gcongr
+ · calc
+ n ≤ (n+1)*1 := by simp
+ _ ≤ (n+1)*(n+1) := Nat.mul_le_mul_left _ (Nat.succ_le_succ (Nat.zero_le _))
+ _ = _ := (pow_two _).symm
+ · dsimp [m]; omega
+ have hbase : m ≤ (n+1)^2*m := Nat.le_mul_of_pos_left _ (by positivity)
+ have hn : n ≤ n*(w+1) := Nat.le_mul_of_pos_right _ (by omega)
+ have hw : n*w ≤ n*(w+1) := Nat.mul_le_mul_left _ (by omega)
+ change 6*h+8 + (n*(40*w+17)+4) + 8192*(n+1)^2*m + 3*(n*(5*w)) + 2 ≤ 16384*(n+1)^2*m
+ rw [Nat.mul_add, show n*(40*w) = 40*(n*w) by ring, show n*(5*w) = 5*(n*w) by ring,
+ Nat.mul_assoc 8192, Nat.mul_assoc 16384, Nat.mul_comm n 17]
+ dsimp only [m] at hbase ⊢
+ dsimp only [m] at hnm
+ omega
+
+end RAMTape.SortOneStage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortOneStagePorts.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortOneStagePorts.lean
new file mode 100644
index 0000000000..c4c89e209e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortOneStagePorts.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.RAMTapeSortBoundary
+import OAI.Computability.VPVNP.RAMTapeSortLayerDispatch
+import OAI.Computability.VPVNP.RAMTapeSortLayerRowsPorts
+import OAI.Computability.VPVNP.RAMTapeSortSchedule
+
+/-! # Registers shared by the boundary moves and row traversal of a sorting stage
+
+The row traversal and the exchange-stream split share their temporary ports.
+The stage also has a preserved unary record count for splitting a whole block.
+When installed in the schedule, its phase and stride refer directly to the
+schedule's counters.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortOneStage
+
+open BurstRAM RAMBoundary Boundary
+
+/-- The extra port holds the unary number of records in a site block. -/
+abbrev Port := SortLayerRows.Port ⊕ Unit
+
+private def row (p : SortRow.Port) : Port := .inl (.inl (.inl p))
+
+/-- Initialize one stage's row and boundary stacks, including the site identifier, stage
+exponents, live record streams, flags and unary block size. -/
+def bank {d : ℕ} (v : Word d) (a j w h : ℕ) (current next send recv flags : List Bool) :
+ Stacks Port :=
+ Sum.elim (SortOffsets.idle (SortLayerRows.bank v a j w current next send recv flags) h)
+ (fun _ => List.replicate (2^h) true)
+
+/-- Connect the local-versus-cross-site stride test to the row-width and stride counters and
+temporary storage. -/
+def dispatchPorts : SortLayerDispatch.Port → Port
+ | .width => .inl (.inr .width)
+ | .stride => .inl (.inl (.inr .stride))
+ | .tmp => .inl (.inl (.inr .tmp))
+
+/-- Route block splitting and advancement to the same current, next, incident and scratch
+stacks used by the row traversal. -/
+def boundaryPorts : SortBoundary.Port → Port
+ | .current => row .current
+ | .next => row .next
+ | .crossSend => row .crossSend
+ | .crossReceive => row .crossReceive
+ | .width => row .width
+ | .slots => .inr ()
+ | .scratch1 => row .lookup
+ | .scratch2 => row .saved
+
+theorem dispatchPorts_injective : Function.Injective dispatchPorts := by decide
+theorem boundaryPorts_injective : Function.Injective boundaryPorts := by decide
+
+/-- The local branch leaves the incident stream in place. The cross-site
+branch separates its first block onto the send stack. -/
+def prepare : FiniteRoutine Port :=
+ SortLayerDispatch.routine dispatchPorts (SortBoundary.splitCross.onPorts boundaryPorts) .ret
+
+private theorem split_run {d : ℕ} (v : Word d) (a j w h : ℕ)
+ (cur send recv flags : List Bool) (hlen : send.length = 2^h*(5*w)) :
+ (SortBoundary.splitCross.onPorts boundaryPorts).Runs (SortBoundary.splitCost (2^h) w)
+ (bank v a j w h cur [] [] (send++recv) flags)
+ (bank v a j w h cur [] send recv flags) := by
+ let initial := bank v a j w h cur [] [] (send++recv) flags
+ let small := initial ∘ boundaryPorts
+ have hr := SortBoundary.splitCross_runs (2^h) w small send recv hlen rfl rfl rfl rfl rfl rfl
+ apply FiniteRoutine.runs_onPorts_framed _ boundaryPorts_injective hr
+ · intro p; rfl
+ · intro p; cases p <;> rfl
+ · intro p hp
+ rcases p with ((r|e)|o)|u
+ · cases r <;> first | rfl | exact (hp .crossSend rfl).elim | exact (hp .crossReceive rfl).elim
+ · cases e <;> rfl
+ · rfl
+ · rfl
+
+theorem prepare_cross {d : ℕ} (v : Word d) (a j w h : ℕ)
+ (cur send recv flags : List Bool) (hc : h ≤ j) (hlen : send.length = 2^h*(5*w)) :
+ prepare.Runs (6*h+5+SortBoundary.splitCost (2^h) w)
+ (bank v a j w h cur [] [] (send++recv) flags)
+ (bank v a j w h cur [] send recv flags) :=
+ SortLayerDispatch.cross_runs _ dispatchPorts_injective _ .ret rfl rfl hc (split_run v a j w h cur send recv flags hlen)
+
+theorem prepare_local {d : ℕ} (v : Word d) (a j w h : ℕ)
+ (cur recv flags : List Bool) (hl : j < h) :
+ prepare.Runs (6*j+8) (bank v a j w h cur [] [] recv flags) (bank v a j w h cur [] [] recv flags) :=
+ SortLayerDispatch.local_runs _ dispatchPorts_injective (SortBoundary.splitCross.onPorts boundaryPorts)
+ .ret (s := bank v a j w h cur [] [] recv flags) rfl rfl hl (Routine.runs_ret _)
+
+/-- Discard the old current block and reverse the completed next block into its place on the
+stage's physical ports. -/
+def advance : FiniteRoutine Port := SortBoundary.advance.onPorts boundaryPorts
+
+theorem advance_runs {d : ℕ} (v : Word d) (a j w h : ℕ)
+ (cur next recv flags : List Bool) :
+ advance.Runs (cur.length + 2*next.length + 2)
+ (bank v a j w h cur next.reverse [] recv flags)
+ (bank v a j w h next [] [] recv flags) := by
+ let initial := bank v a j w h cur next.reverse [] recv flags
+ let small := initial ∘ boundaryPorts
+ have hr := SortBoundary.advance_runs small
+ change SortBoundary.advance.Runs (cur.length + 2*next.reverse.length + 2) small
+ (Function.update (Function.update small .next []) .current next.reverse.reverse) at hr
+ rw [List.reverse_reverse, List.length_reverse] at hr
+ apply FiniteRoutine.runs_onPorts_framed _ boundaryPorts_injective hr
+ · intro p; rfl
+ · intro p; cases p <;> rfl
+ · intro p hp
+ rcases p with ((r|e)|o)|u
+ · cases r <;> first | rfl | exact (hp .current rfl).elim | exact (hp .next rfl).elim
+ · cases e <;> rfl
+ · rfl
+ · rfl
+
+theorem rows_runs {d : ℕ} (v : Word d) (a j w h : ℕ)
+ {cur next send recv flags cur' next' send' recv' flags' : List Bool}
+ {rows : FiniteRoutine SortLayerRows.Port} {t : ℕ}
+ (hr : rows.Runs t (SortOffsets.idle (SortLayerRows.bank v a j w cur next send recv flags) h)
+ (SortOffsets.idle (SortLayerRows.bank v a j w cur' next' send' recv' flags') h)) :
+ (rows.onPorts (Sum.inl : SortLayerRows.Port → Port)).Runs t
+ (bank v a j w h cur next send recv flags) (bank v a j w h cur' next' send' recv' flags') := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective hr
+ · intro p; rfl
+ · intro p; rfl
+ · rintro (p|u) hp
+ · exact (hp p rfl).elim
+ · rfl
+
+/-- Share the stage's phase and stride directly with the schedule counters and route its
+remaining stacks to the schedule's data bank. -/
+def schedulePorts : Port → SortSchedule.Port Port
+ | .inl (.inl (.inr .phase)) => .inl .phase
+ | .inl (.inl (.inr .stride)) => .inl .stride
+ | p => .inr p
+
+theorem schedulePorts_injective : Function.Injective schedulePorts := by decide
+
+/-- Between layers, the schedule itself supplies phase and stride. -/
+def data {d : ℕ} (v : Word d) (w h : ℕ) (cur : Word h → RawSlot w)
+ (recv flags : List Bool) : Stacks Port :=
+ bank v 0 0 w h (blockBytes (List.ofFn cur)) [] [] recv flags
+
+private theorem schedule_bank {d : ℕ} (v : Word d) (a j w h left : ℕ) (cur : Word h → RawSlot w)
+ (recv flags : List Bool) (p : Port) :
+ SortSchedule.bank (data v w h cur recv flags) left a j (schedulePorts p) =
+ bank v a j w h (blockBytes (List.ofFn cur)) [] [] recv flags p := by
+ rcases p with ((r|e)|o)|u
+ · cases r <;> rfl
+ · cases e <;> rfl
+ · rfl
+ · rfl
+
+theorem schedule_run {d : ℕ} (v : Word d) (a j w h left : ℕ) (cur cur' : Word h → RawSlot w)
+ (recv flags recv' flags' : List Bool) {native : FiniteRoutine Port} {t : ℕ}
+ (hr : native.Runs t (bank v a j w h (blockBytes (List.ofFn cur)) [] [] recv flags)
+ (bank v a j w h (blockBytes (List.ofFn cur')) [] [] recv' flags')) :
+ (native.onPorts schedulePorts).Runs t
+ (SortSchedule.bank (data v w h cur recv flags) left a j)
+ (SortSchedule.bank (data v w h cur' recv' flags') left a j) := by
+ apply FiniteRoutine.runs_onPorts_framed _ schedulePorts_injective hr
+ (schedule_bank v a j w h left cur recv flags) (schedule_bank v a j w h left cur' recv' flags')
+ intro p hp
+ rcases p with c | (((r|e)|o)|u)
+ · cases c <;> rfl
+ · exact (hp (.inl (.inl (.inl r))) rfl).elim
+ · cases e <;> rfl
+ · exact (hp (.inl (.inr o)) rfl).elim
+ · exact (hp (.inr u) rfl).elim
+
+end RAMTape.SortOneStage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRecordCode.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRecordCode.lean
new file mode 100644
index 0000000000..5613fb997b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRecordCode.lean
@@ -0,0 +1,219 @@
+import OAI.Computability.VPVNP.RAMTapeSortField
+
+/-! # Returning stack routines for sorting, selecting and validating two complete records -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Sorter
+
+open BurstRAM RAMBoundary
+
+/-- Select either a record-equality check or a sorting comparison that retains the designated
+minimum or maximum. -/
+inductive Mode where
+ | verify | select (keepMin : Bool)
+ deriving DecidableEq, Fintype
+
+/-- Post-comparison transfer through the saved operands, temporary staging and next-block
+output, including the discard and verification cases. -/
+inductive Route where
+ | verifyLeft | verifyRight | discardOther (takeLeft : Bool) | saved (takeLeft : Bool) | staged
+ deriving DecidableEq, Fintype
+
+/-- The stack to drain at this cleanup or transfer step. -/
+def Route.src : Route → Port
+ | .verifyLeft => .savedLeft
+ | .verifyRight => .savedRight
+ | .discardOther left => if left then .savedRight else .savedLeft
+ | .saved left => if left then .savedLeft else .savedRight
+ | .staged => .tmp
+
+/-- Destination for a moved bit, using staging and then the next block for the selected
+operand. Verification and discard routes drop the bit. -/
+def Route.dst : Route → Option Port
+ | .saved _ => some .tmp
+ | .staged => some .next
+ | _ => none
+
+/-- Control of a five-field comparator, retaining the observed fields, cleanup route and
+Boolean verdict through the final return. -/
+inductive State where
+ | field (i : Fin 5) (info : RecordInfo) (s : FieldState)
+ | clean (route : Route) (ok : Bool)
+ | put (route : Route) (ok bit : Bool)
+ | emit (ok : Bool)
+ | done
+ deriving DecidableEq, Fintype
+
+/-- Choose the next cleanup, staging or verdict state after exhausting the current route's
+source stack. -/
+def Route.after (ok : Bool) : Route → State
+ | .verifyLeft => .clean .verifyRight ok
+ | .verifyRight | .staged => .emit ok
+ | .discardOther left => .clean (.saved left) ok
+ | .saved _ => .clean .staged ok
+
+/-- Check that each scanned five-word operand is a canonical encoded record. -/
+def bothCanonical (info : RecordInfo) : Bool :=
+ canonical (fun i ↦ (info i).left) && canonical (fun i ↦ (info i).right)
+
+/-- After all fields are scanned, choose the operand-transfer route and verdict for equality
+checking or minimum/maximum selection. -/
+def cleanup (mode : Mode) (info : RecordInfo) : State :=
+ match mode with
+ | .verify => .clean .verifyLeft (bothCanonical info && equalDecision info)
+ | .select keepMin => .clean (.discardOther (leDecision info == keepMin)) (bothCanonical info)
+
+private def emptyInfo : RecordInfo := fun _ ↦ ⟨.zero,.zero,.eq⟩
+
+/-- Save the observation for the completed field, then start the next field or proceed to
+cleanup after field five. -/
+def fieldExit (mode : Mode) (j : Fin 5) (f : RecordInfo) (s : WordState) : State :=
+ let newInfo := Function.update f j (observe s)
+ if h : j.val + 1 < 5 then .field ⟨j.val+1,h⟩ newInfo (.tick WordState.start)
+ else cleanup mode newInfo
+
+/-- Execute the field comparisons, drain or transfer the saved records, and emit the validity
+bit for the selected mode. -/
+def recordCode (mode : Mode) : StackCode Port State
+ | .field j info (.done s) => .goto (fieldExit mode j info s)
+ | .field j info s => (fieldCode s).rename id (.field j info)
+ | .clean route ok => .pop route.src fun x ↦ x.elim (route.after ok) fun bit ↦
+ if route.dst.isSome then .put route ok bit else .clean route ok
+ | .put route ok bit => .push (route.dst.getD .tmp) bit (.clean route ok)
+ | .emit ok => .push .valid ok .done
+ | .done => .halt true
+
+/-- Start at field zero with empty field observations and an initial word comparison state. -/
+def entry : State := .field 0 emptyInfo (.tick WordState.start)
+
+/-- Package the five-field record comparator as a returning finite routine for the chosen mode. -/
+def routine (mode : Mode) : FiniteRoutine Port :=
+ FiniteRoutine.ofStackCode (recordCode mode) id entry (fun s ↦ decide (s = .done))
+
+/-- Sort two raw records and stage the requested minimum or maximum with a canonical-format
+verdict. -/
+def select (keepMin : Bool) : FiniteRoutine Port := routine (.select keepMin)
+/-- Consume both records and emit the verdict that they are canonical and equal in all fields. -/
+def verify : FiniteRoutine Port := routine .verify
+
+/-- Validity flag for a sorting selection, requiring both operands to be canonically encoded. -/
+def selectOK {w : ℕ} (a b : RawSlot w) : Bool := bothCanonical (expected a b)
+/-- Validity flag for checking a transmitted copy, requiring canonical encodings and equal
+words in all five fields. -/
+def verifyOK {w : ℕ} (a b : RawSlot w) : Bool := selectOK a b && equalDecision (expected a b)
+
+/-- The raw operand selected by the record order and the wire's minimum-or-maximum direction. -/
+def chosen {w : ℕ} (keepMin : Bool) (a b : RawSlot w) : RawSlot w :=
+ if leDecision (expected a b) == keepMin then a else b
+
+/-- The returned validity bit for a comparison checks both five-word encodings. -/
+theorem selectOK_iff {w : ℕ} (hw : 2 ≤ w) (a b : RawSlot w) :
+ selectOK a b = true ↔ (∃ r, (RAMSerialization.recordFormat hw).words r = a) ∧
+ ∃ r, (RAMSerialization.recordFormat hw).words r = b := by
+ simp only [selectOK, bothCanonical, expected, Bool.and_eq_true, canonical_iff hw]
+
+/-- The outgoing field must be exactly the same canonical five words as
+the staged local record. -/
+theorem verifyOK_iff {w : ℕ} (hw : 2 ≤ w) (a b : RawSlot w) :
+ verifyOK a b = true ↔ (∃ r, (RAMSerialization.recordFormat hw).words r = a) ∧ a = b := by
+ rw [verifyOK, Bool.and_eq_true, selectOK_iff hw, equalDecision_eq, decide_eq_true_iff]
+ constructor
+ · exact fun h ↦ ⟨h.1.1, h.2⟩
+ · rintro ⟨h,rfl⟩; exact ⟨⟨h,h⟩,rfl⟩
+
+/-- The selected bit string represents the requested comparator output
+even when a malformed slot was presented and its validity bit is false. -/
+theorem chosen_parsed {w : ℕ} (hw : 2 ≤ w) (keepMin : Bool) (a b : RawSlot w) :
+ RAMSort.parsedSlot hw (chosen keepMin a b) =
+ if keepMin then min (RAMSort.parsedSlot hw a) (RAMSort.parsedSlot hw b)
+ else max (RAMSort.parsedSlot hw a) (RAMSort.parsedSlot hw b) := by
+ unfold chosen
+ rw [leDecision_eq hw]
+ by_cases he : RAMSort.parsedSlot hw a ≤ RAMSort.parsedSlot hw b
+ · cases keepMin <;> simp [he]
+ · have hr := le_of_not_ge he
+ cases keepMin <;> simp [he,min_eq_right hr,max_eq_left hr]
+
+private theorem install_id (base small : Stacks Port) : installStacks id base small = small := by
+ funext p
+ exact installStacks_at Function.injective_id base small p
+
+private def prefixInfo (n : ℕ) (f : RecordInfo) : RecordInfo :=
+ fun i ↦ if i.val < n then f i else emptyInfo i
+
+private def position (mode : Mode) (f : RecordInfo) (n : ℕ) : State :=
+ if h : n < 5 then .field ⟨n,h⟩ (prefixInfo n f) (.tick WordState.start) else cleanup mode f
+
+private theorem fieldExit_eq {w : ℕ} (mode : Mode) (j : Fin 5) (a b : RawSlot w) (s : WordState)
+ (hobs : observe s = expected a b j) :
+ fieldExit mode j (prefixInfo j.val (expected a b)) s = position mode (expected a b) (j.val+1) := by
+ let f := expected a b
+ have hf : Function.update (prefixInfo j.val f) j (observe s) = prefixInfo (j.val+1) f := by
+ funext k
+ by_cases he : k = j
+ · subst k; simp [prefixInfo, hobs, f]
+ · have hn : k.val ≠ j.val := fun hv ↦ he (Fin.ext hv)
+ have hlt : k.val < j.val + 1 ↔ k.val < j.val := by omega
+ simp [Function.update_of_ne he, prefixInfo, hlt]
+ change fieldExit mode j (prefixInfo j.val f) s = position mode f (j.val+1)
+ unfold fieldExit
+ rw [hf]
+ unfold position
+ split
+ · rfl
+ · have hall : prefixInfo (j.val+1) f = f := by
+ funext k
+ have hk := k.isLt
+ simp [prefixInfo, show k.val < j.val+1 by omega]
+ simp [hall]
+
+private theorem field_run (mode : Mode) {w : ℕ} (a b : RawSlot w) (j : Fin 5) (base : Bank) :
+ StackRuns (recordCode mode) (8*w+3) (position mode (expected a b) j.val)
+ {base with left := wordBits (a j) ++ base.left, right := wordBits (b j) ++ base.right, width := List.replicate w true, widthBack := []}.stacks
+ (position mode (expected a b) (j.val+1))
+ {base with width := List.replicate w true, widthBack := [], savedLeft := (wordBits (a j)).reverse ++ base.savedLeft, savedRight := (wordBits (b j)).reverse ++ base.savedRight}.stacks := by
+ let f := expected a b
+ have hr := field_runs WordState.start base (wordBits (a j)) (wordBits (b j)) (by simp)
+ have hl := hr.lift (target := recordCode mode) id Function.injective_id (.field j (prefixInfo j.val f))
+ (fun _ ↦ []) (fun q hq ↦ by cases q <;> first | rfl | contradiction)
+ simp only [install_id, length_wordBits] at hl
+ rw [position, dite_eq_left j.isLt]
+ have hx := fieldExit_eq mode j a b _ (observe_fold a b j)
+ exact hl.trans (.cons (.goto (show recordCode mode _ = .goto _ from congrArg StackOp.goto hx)) (.nil ..))
+
+private theorem bytes_fields {w : ℕ} (a : RawSlot w) :
+ Boundary.recordBytes a = wordBits (a 0) ++ (wordBits (a 1) ++ (wordBits (a 2) ++
+ (wordBits (a 3) ++ wordBits (a 4)))) := by
+ rw [Boundary.recordBytes, Boundary.recordWords, List.ofFn_succ, List.ofFn_succ, List.ofFn_succ,
+ List.ofFn_succ, List.ofFn_succ, List.ofFn_zero]
+ simp only [List.flatten_cons, List.flatten_nil, List.append_nil]
+ rfl
+
+/-- The five-word pass consumes exactly two records and preserves their
+complete bit strings on the two save stacks. -/
+theorem record_run (mode : Mode) {w : ℕ} (a b : RawSlot w) (base : Bank) :
+ StackRuns (recordCode mode) (5*(8*w+3)) entry
+ {base with left := Boundary.recordBytes a ++ base.left, right := Boundary.recordBytes b ++ base.right, width := List.replicate w true, widthBack := []}.stacks
+ (cleanup mode (expected a b))
+ {base with width := List.replicate w true, widthBack := [], savedLeft := (Boundary.recordBytes a).reverse ++ base.savedLeft, savedRight := (Boundary.recordBytes b).reverse ++ base.savedRight}.stacks := by
+ let go (j : Fin 5) (lt rt ls rs : List Bool) :=
+ field_run mode a b j {base with left := lt, right := rt, savedLeft := ls, savedRight := rs}
+ let n := 8*w+3
+ rw [show 5*(8*w+3) = n+(n+(n+(n+n))) by omega]
+ simp only [bytes_fields, List.append_assoc, List.reverse_append]
+ refine (go 0 _ _ base.savedLeft base.savedRight).trans ?_
+ refine (go 1 _ _ _ _).trans ?_
+ refine (go 2 _ _ _ _).trans ?_
+ refine (go 3 _ _ _ _).trans ?_
+ let saved (z : RawSlot w) (s : List Bool) := (wordBits (z 3)).reverse ++
+ ((wordBits (z 2)).reverse ++ ((wordBits (z 1)).reverse ++ ((wordBits (z 0)).reverse ++ s)))
+ exact go 4 base.left base.right (saved a base.savedLeft) (saved b base.savedRight)
+
+end RAMTape.Sorter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortReplay.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortReplay.lean
new file mode 100644
index 0000000000..890798764d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortReplay.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.RAMTapeSortReplayLayer
+import OAI.Computability.VPVNP.RAMTapeSortReplayFields
+import OAI.Computability.VPVNP.RAMSortScanMessages
+
+/-! # Acceptance and output of the chronological physical sorting replay
+
+A failed check is retained through every remaining stage, irrespective of
+the later messages. On a successful prefix the physical block is canonical,
+so the next stage starts from the exact block of the checked word-work scan.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortReplay
+
+open BurstRAM RAMSort RAMMemory RAMBoundary
+
+variable {h d w : ℕ}
+
+theorem fold_retains (raw : ℕ → Bool) (v : Word d) (ss : List (Stage (h+d))) (x : State h w)
+ (hp : (ss.foldl (update raw v) x).2.all id = true) : x.2.all id = true := by
+ induction ss generalizing x with
+ | nil => exact hp
+ | cons s ss ih => exact update_retains raw v x s (ih _ hp)
+
+/-- Starting from any canonical local block and any saved check flags, both
+sort scans have the same acceptance. When they pass, parsing the physical
+output gives the replayed record array. -/
+theorem fold_spec (hw : 2 ≤ w) (raw : ℕ → Bool) (v : Word d) (ss : List (Stage (h+d)))
+ (x : State h w) (hcur : CanonicalBlock hw x.1) :
+ let final := ss.foldl (update raw v) x
+ let checked := scanStages hw raw v ss (decoded hw x.1)
+ (final.2.all id = (x.2.all id && checked.ok)) ∧
+ (final.2.all id = true → CanonicalBlock hw final.1 ∧ decoded hw final.1 = checked.block) := by
+ induction ss generalizing x with
+ | nil =>
+ exact ⟨(Bool.and_true _).symm, fun _ => ⟨hcur,rfl⟩⟩
+ | cons s ss ih =>
+ let y := update raw v x s
+ let layer := scanLayer hw raw s v (decoded hw x.1)
+ have hy : y.2.all id = (x.2.all id && layer.ok) := update_flags hw raw v x s hcur
+ change ((ss.foldl (update raw v) y).2.all id =
+ (x.2.all id && (layer.ok && (scanStages hw raw v ss layer.block).ok))) ∧
+ ((ss.foldl (update raw v) y).2.all id = true →
+ CanonicalBlock hw (ss.foldl (update raw v) y).1 ∧
+ decoded hw (ss.foldl (update raw v) y).1 = (scanStages hw raw v ss layer.block).block)
+ rw [← Bool.and_assoc, ← hy]
+ by_cases hgood : y.2.all id = true
+ · obtain ⟨hcanon, hblock⟩ := update_output hw raw v x s hgood
+ have ht := ih y hcanon
+ change decoded hw y.1 = layer.block at hblock
+ rw [← hblock]
+ exact ht
+ · have hfinal : (ss.foldl (update raw v) y).2.all id = false := by
+ cases he : (ss.foldl (update raw v) y).2.all id
+ · rfl
+ · exact (hgood (fold_retains raw v ss y he)).elim
+ have hold : y.2.all id = false := by cases he : y.2.all id <;> simp_all
+ simp only [hold, hfinal, Bool.false_and, Bool.false_eq_true, false_implies, and_self]
+
+variable {e : ℕ}
+
+/-- For the actual incident messages, passing the physical rows checks both
+canonicality and the typed send constraints at this site. -/
+theorem fold_messages (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w) (b : RAMLayout.SendArrays d (2^e) w)
+ (v : Word d) (x : State (2+e) w) (hcur : CanonicalBlock hw x.1) :
+ let ss := phases ((2+e)+d) ((2+e)+d) le_rfl
+ (ss.foldl (update (sortIncident b v) v) x).2.all id = true ↔
+ x.2.all id = true ∧ SortCanonical hw hc b v ∧ RAMSort.checks v ss
+ (physicalFieldsEquiv.{0,0} (2+e) d _ (unpackMessages (parseMessages hw hc b)).memory.sortSends)
+ (decoded hw x.1) := by
+ dsimp only
+ rw [(fold_spec hw (sortIncident b v) v _ x hcur).1, Bool.and_eq_true, sortScan_messages hw hc b v]
+
+/-- On passing physical messages the output supplied to the predecessor
+test is the sorted record block of the typed distributed validator. -/
+theorem fold_messages_output (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w) (b : RAMLayout.SendArrays d (2^e) w)
+ (v : Word d) (x : State (2+e) w) (hcur : CanonicalBlock hw x.1) :
+ let ss := phases ((2+e)+d) ((2+e)+d) le_rfl
+ let final := ss.foldl (update (sortIncident b v) v) x
+ final.2.all id = true →
+ (fun i => (parsedSlot hw (final.1 i)).record) =
+ outputAt (unpackMessages (parseMessages hw hc b)).memory v (decoded hw x.1) := by
+ intro ss final hp
+ have hblock := ((fold_spec hw (sortIncident b v) v ss x hcur).2 hp).2
+ have hcan := ((fold_messages hw hc b v x hcur).mp hp).2.1
+ exact (congrArg (fun f : Wires (2+e) (OrderedSlot (Word w)) => fun i => (f i).record) hblock).trans
+ (sortScan_output hw hc b v (decoded hw x.1) hcan)
+
+end RAMTape.SortReplay
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortReplayFields.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortReplayFields.lean
new file mode 100644
index 0000000000..81c4369810
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortReplayFields.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.RAMTapeSortReplaySlot
+import OAI.Computability.VPVNP.RAMTapeSortScheduleFields
+import OAI.Computability.VPVNP.RAMTapeBoundaryDecision
+
+/-! # Physical exchange fields as streams of five-word sorting records -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortReplay
+
+open RAMSort RAMLayout RAMBoundary Boundary
+
+variable {h d H w : ℕ}
+
+/-- Decoding one addressed record and writing its five words recovers its original bits,
+including for malformed tags and noncanonical payloads. -/
+theorem recordBytes_fieldWords (w : ℕ) (raw : ℕ → Bool) (s : Stage (h+d)) (dir : Fin 2)
+ (i : Fin (2^h)) :
+ recordBytes (fieldWords w raw s dir i) = List.ofFn fun bit : Fin (5*w) =>
+ raw ((fieldStart h w s.phase s.stride dir.val i.val).eval+bit.val) :=
+ (SuccessorFields.raw_eq_flatten_words _).symm
+
+/-- Row-major concatenation of the addressed five-word records exactly recovers the
+incident send or receive field selected by this cross-site stride. -/
+theorem fieldWords_bits (hslots : 2^h = 4*H) (incident : Fin (width d H w) → Bool)
+ (raw : ℕ → Bool) (hraw : ∀ k : Fin (width d H w), raw k.val = incident k)
+ (s : Stage (h+d)) (hc : h ≤ s.stride) (dir : Fin 2) :
+ (List.ofFn fun j : Fin (blockBits H w) =>
+ incident (offset d H w (.inr ((crossStageEquiv h d).symm ⟨s,hc⟩,dir,j)))) =
+ blockBytes (List.ofFn (fieldWords w raw s dir)) := by
+ let l := (crossStageEquiv h d).symm ⟨s,hc⟩
+ let f (k : Fin (blockBits H w)) := incident (offset d H w (.inr (l,dir,k)))
+ have hwidth : 2^h*(5*w) = blockBits H w := by rw [hslots, blockBits]; ring
+ let f' (k : Fin (2^h*(5*w))) := f (k.cast hwidth)
+ have he : List.ofFn f = List.ofFn f' := by
+ apply List.ext_getElem (by simp [hwidth])
+ intro k h₁ h₂
+ simp [f']
+ change List.ofFn f = _
+ rw [he, SuccessorFields.raw_eq_flatten, blockBytes, List.flatMap_def, List.map_ofFn]
+ apply congrArg List.flatten
+ apply congrArg List.ofFn
+ funext i
+ change (List.ofFn fun bit => f' (finProdFinEquiv (i,bit))) = recordBytes (fieldWords w raw s dir i)
+ rw [recordBytes_fieldWords]
+ apply congrArg List.ofFn
+ funext bit
+ rw [fieldStart_physical hslots s hc dir i bit, hraw]
+ apply congrArg (fun k : Fin (blockBits H w) => incident (offset d H w (.inr (l,dir,k))))
+ apply Fin.ext
+ change bit.val + 5*w*i.val = i.val*5*w+bit.val
+ ring
+
+/-- The two consecutive streams in the physical schedule carry exactly the rows
+of the outgoing and incoming blocks for this stage. -/
+theorem fieldPair_eq_blocks (hslots : 2^h = 4*H) (incident : Fin (width d H w) → Bool)
+ (raw : ℕ → Bool) (hraw : ∀ k : Fin (width d H w), raw k.val = incident k)
+ (s : Stage (h+d)) (hc : h ≤ s.stride) :
+ SortSchedule.fieldPair incident ((crossStageEquiv h d).symm ⟨s,hc⟩).ordinal.val =
+ blockBytes (List.ofFn (fieldWords w raw s 0)) ++ blockBytes (List.ofFn (fieldWords w raw s 1)) := by
+ let l := (crossStageEquiv h d).symm ⟨s,hc⟩
+ rw [SortSchedule.fieldPair, dite_eq_left l.ordinal.isLt]
+ change (List.ofFn fun k : Fin (blockBits H w) =>
+ incident (offset d H w (.inr ((layerEquiv d).symm ((layerEquiv d) l),0,k)))) ++
+ (List.ofFn fun k : Fin (blockBits H w) =>
+ incident (offset d H w (.inr ((layerEquiv d).symm ((layerEquiv d) l),1,k)))) = _
+ rw [Equiv.symm_apply_apply]
+ exact congrArg₂ List.append (fieldWords_bits hslots incident raw hraw s hc 0)
+ (fieldWords_bits hslots incident raw hraw s hc 1)
+
+end RAMTape.SortReplay
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortReplayInput.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortReplayInput.lean
new file mode 100644
index 0000000000..9c8c8d864b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortReplayInput.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.RAMTapeSortReplay
+import OAI.Computability.VPVNP.RAMTapeRecordBuffer
+
+/-! # Initial physical records of the sorting replay
+
+A completed local transcript contributes its initialization and probe records
+in their original order. The emitter then fills every remaining slot with
+the canonical empty record. Its output bytes are exactly the input block for
+the finite layer traversal.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortReplay
+
+open BurstRAM RAMMemory RAMSort RAMSerialization RAMBoundary Boundary
+
+variable {w : ℕ}
+
+/-- Initial five-word records at all row indices of a site, including empty slots. -/
+def emittedBlock (hw : 2 ≤ w) (e : ℕ) (records : List (WordRecord w)) : Wires (2+e) (RawSlot w) :=
+ fun i => (recordFormat hw).words (RecordBuffer.slots (2^e) records (recordPosition e i))
+
+theorem emittedBlock_canonical (hw : 2 ≤ w) (e : ℕ) (records : List (WordRecord w)) :
+ CanonicalBlock hw (emittedBlock hw e records) := by
+ intro i
+ simp [Canonical, emittedBlock, Format.parse_words]
+
+theorem recordBytes_words (hw : 2 ≤ w) (r : Option (WordRecord w)) :
+ recordBytes ((recordFormat hw).words r) = List.ofFn ((recordFormat hw).encode r) := by
+ have h := (SuccessorFields.raw_eq_flatten_words ((recordFormat hw).encode r)).symm
+ simpa only [recordBytes, recordWords, Format.encode, Equiv.symm_apply_apply] using h
+
+theorem emittedBlock_bytes (hw : 2 ≤ w) (e : ℕ) (records : List (WordRecord w)) :
+ blockBytes (List.ofFn (emittedBlock hw e records)) =
+ List.ofFn ((blockFormat (2^e) hw).encode (RecordBuffer.slots (2^e) records)) := by
+ rw [RecordBuffer.block_serialized]
+ simp only [blockBytes, RecordBuffer.serialized, List.flatMap_def, List.map_ofFn]
+ apply congrArg List.flatten
+ apply List.ext_getElem (by simp [record_width])
+ intro j hj hk
+ simp only [List.getElem_ofFn, Function.comp_apply, emittedBlock, recordBytes_words]
+ rfl
+
+/-- The exact physical output of the record-emission routine supplies the
+initial block of the finite sort without any data conversion. -/
+theorem close_emittedBlock {hw : 2 ≤ w} {e : ℕ} {records : List (WordRecord w)}
+ {s : Stacks RecordBuffer.Port} (h : RecordBuffer.Holds hw (2^e) records s) :
+ RecordBuffer.close.Runs ((4*2^e-records.length)*(25*w+12)+1+(2*(4*2^e*5*w)+1)) s
+ (Function.update (Function.update (Function.update s .remaining []) .reverseBuffer [])
+ .output (blockBytes (List.ofFn (emittedBlock hw e records)))) := by
+ rw [emittedBlock_bytes]
+ exact h.close
+
+/-- When the records came from this site's report stream, their checked
+parse is the typed validator's local input array. -/
+theorem decoded_emittedBlock (hw : 2 ≤ w) {e v start : ℕ} (header : ℕ → Word w)
+ (rs : List (Report w)) (records : List (WordRecord w))
+ (he : records.map WordRecord.record = initRecord header v :: probeRecords start rs) :
+ decoded hw (emittedBlock hw e records) = localRecords header e v start rs := by
+ funext i
+ have hh := RecordBuffer.slots_eq_localRecords header rs records he i
+ cases eqn : localRecords header e v start rs i with
+ | mk r =>
+ rw [eqn] at hh
+ simp only [decoded, emittedBlock, parsedSlot, Format.parse_words]
+ exact congrArg OrderedSlot.mk hh
+
+end RAMTape.SortReplay
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortReplayLayer.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortReplayLayer.lean
new file mode 100644
index 0000000000..15b781e21b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortReplayLayer.lean
@@ -0,0 +1,111 @@
+import OAI.Computability.VPVNP.RAMTapeSortReplayRow
+import OAI.Computability.VPVNP.RAMTapeSortLayerRowsModel
+
+/-! # One materialized sorting layer agrees with the checked RAM replay
+
+The machine compares arbitrary fixed-width record fields. Its initially
+canonical local block supplies the left operand at every row. If every
+new row flag passes, the next block is canonical and parses to the checked
+replay's next block. The acceptance test also covers malformed incident fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortReplay
+
+open BurstRAM RAMMemory RAMSort RAMBoundary SortLayerRows
+
+variable {h d w : ℕ}
+
+/-- The current block of raw five-word rows and the accumulated Boolean validity flags of the
+physical replay. -/
+abbrev State (h w : ℕ) := Wires h (RawSlot w) × List Bool
+
+/-- Replay one bitonic stage using its incident send and receive fields, replacing the local
+block by the selected rows and accumulating their checks. -/
+def update (raw : ℕ → Bool) (v : Word d) (x : State h w) (s : Stage (h+d)) : State h w :=
+ let send := fieldWords w raw s 0
+ let recv := fieldWords w raw s 1
+ (selected s v x.1 recv, (List.ofFn (SortLayerRows.checks s x.1 send recv)).reverse.flatten ++ x.2)
+
+/-- Parse every raw five-word row in a physical block to the ordered slot used in the checked
+sorting replay. -/
+abbrev decoded (hw : 2 ≤ w) (x : Wires h (RawSlot w)) : Wires h (OrderedSlot (Word w)) :=
+ fun i => parsedSlot hw (x i)
+
+/-- Each raw row of this block is exactly the canonical encoding of its parsed slot. -/
+abbrev CanonicalBlock (hw : 2 ≤ w) (x : Wires h (RawSlot w)) := ∀ i, Canonical hw (x i)
+
+private theorem checks_row (hw : 2 ≤ w) (raw : ℕ → Bool) (s : Stage (h+d)) (v : Word d)
+ (cur : Wires h (RawSlot w)) (hcur : CanonicalBlock hw cur) (i : Word h) :
+ (SortLayerRows.checks s cur (fieldWords w raw s 0) (fieldWords w raw s 1) i).all id = true ↔
+ (scanRow hw raw s v (decoded hw cur) i).ok = true := by
+ by_cases hc : s.stride < h
+ · rw [local_ok hw raw s v _ i hc]
+ simp only [SortLayerRows.checks, other, hc, ite_true, List.all_cons, List.all_nil,
+ id_eq, Bool.and_true, selectOK_iff hw]
+ exact ⟨fun _ => trivial, fun _ => ⟨hcur _, hcur _⟩⟩
+ · rw [cross_ok hw raw s v _ i (Nat.le_of_not_gt hc)]
+ simp only [SortLayerRows.checks, other, hc, ite_false, List.all_cons, List.all_nil,
+ id_eq, Bool.and_true, Bool.and_eq_true, selectOK_iff hw, verifyOK_iff hw]
+ constructor
+ · rintro ⟨⟨_, hi⟩, ⟨_, ho⟩, he⟩
+ exact ⟨ho, hi, congrArg (parsedSlot hw) he.symm⟩
+ · rintro ⟨ho, hi, he⟩
+ exact ⟨⟨hcur i, hi⟩, ⟨hcur i, ho⟩, ((parsed_eq_iff hw ho (hcur i)).mp he).symm⟩
+
+private theorem accepted_row (hw : 2 ≤ w) (raw : ℕ → Bool) (s : Stage (h+d)) (v : Word d)
+ (cur : Wires h (RawSlot w)) (i : Word h)
+ (hp : (SortLayerRows.checks s cur (fieldWords w raw s 0) (fieldWords w raw s 1) i).all id = true) :
+ let result := selected s v cur (fieldWords w raw s 1) i
+ Canonical hw result ∧ parsedSlot hw result = (scanRow hw raw s v (decoded hw cur) i).slot := by
+ have hsel := (selectOK_iff hw ..).mp (Bool.and_eq_true_iff.mp hp).1
+ refine ⟨chosen_canonical hw _ hsel.1 hsel.2, ?_⟩
+ by_cases hc : s.stride < h
+ · rw [local_value hw raw s v _ i hc]
+ simp only [selected, parsed_chosen, other, hc, ite_true, peerIndex, dite_true, keepMin]
+ · have hi : Canonical hw (fieldWords w raw s 1 i) := by simpa only [other, hc, ite_false] using hsel.2
+ rw [cross_value hw raw s v _ i (Nat.le_of_not_gt hc) hi]
+ simp only [selected, parsed_chosen, other, hc, ite_false, keepMin]
+
+private theorem all_rows {α : Type} {n : ℕ} (f : Fin n → α) (p : α → Bool) :
+ (List.ofFn f).all p = true ↔ ∀ i, p (f i) = true := by
+ simp [List.all_eq_true, List.mem_ofFn]
+
+private theorem new_flags (hw : 2 ≤ w) (raw : ℕ → Bool) (s : Stage (h+d)) (v : Word d)
+ (cur : Wires h (RawSlot w)) (hcur : CanonicalBlock hw cur) :
+ (List.ofFn (SortLayerRows.checks s cur (fieldWords w raw s 0) (fieldWords w raw s 1))).reverse.flatten.all id =
+ (scanLayer hw raw s v (decoded hw cur)).ok := by
+ apply Bool.eq_iff_iff.mpr
+ rw [List.all_flatten, List.all_reverse, all_rows]
+ simp only [scanLayer, Vector.getElem_ofFn, all_rows, id_eq]
+ exact forall_congr' (checks_row hw raw s v cur hcur)
+
+/-- Existing failure flags are retained even when this layer sees arbitrary bits. -/
+theorem update_retains (raw : ℕ → Bool) (v : Word d) (x : State h w) (s : Stage (h+d))
+ (hp : (update raw v x s).2.all id = true) : x.2.all id = true := by
+ simp only [update, List.all_append, Bool.and_eq_true] at hp
+ exact hp.2
+
+theorem update_flags (hw : 2 ≤ w) (raw : ℕ → Bool) (v : Word d) (x : State h w)
+ (s : Stage (h+d)) (hcur : CanonicalBlock hw x.1) :
+ (update raw v x s).2.all id =
+ (x.2.all id && (scanLayer hw raw s v (decoded hw x.1)).ok) := by
+ simp only [update, List.all_append, new_flags hw raw s v x.1 hcur]
+ exact Bool.and_comm ..
+
+theorem update_output (hw : 2 ≤ w) (raw : ℕ → Bool) (v : Word d) (x : State h w)
+ (s : Stage (h+d)) (hp : (update raw v x s).2.all id = true) :
+ CanonicalBlock hw (update raw v x s).1 ∧
+ decoded hw (update raw v x s).1 = (scanLayer hw raw s v (decoded hw x.1)).block := by
+ simp only [update, List.all_append, Bool.and_eq_true, List.all_flatten, List.all_reverse, all_rows] at hp
+ have rows := fun i => accepted_row hw raw s v x.1 i (hp.1 i)
+ exact ⟨fun i => (rows i).1, funext fun i => by simp only [scanLayer, Vector.getElem_ofFn, update, decoded]; exact (rows i).2⟩
+
+end RAMTape.SortReplay
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortReplayRow.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortReplayRow.lean
new file mode 100644
index 0000000000..3f4b65da73
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortReplayRow.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.RAMTapeSortReplaySlot
+import OAI.Computability.VPVNP.RAMTapeSortRowModel
+
+/-! # Comparison outcomes and flags on one physical sorting row -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortReplay
+
+open BurstRAM RAMSort RAMMemory RAMBoundary
+
+variable {h d w : ℕ}
+
+/-- Return the operand chosen by a minimum or maximum comparison, with the
+same equality convention as the finite comparator. -/
+def pick (keepMin : Bool) (a b : OrderedSlot (Word w)) : OrderedSlot (Word w) :=
+ if decide (a ≤ b) == keepMin then a else b
+
+theorem parsed_chosen (hw : 2 ≤ w) (keepMin : Bool) (a b : RawSlot w) :
+ parsedSlot hw (SortRow.chosen keepMin a b) = pick keepMin (parsedSlot hw a) (parsedSlot hw b) := by
+ simp only [SortRow.chosen, Sorter.leDecision_eq hw, pick]
+ split <;> rfl
+
+theorem chosen_canonical (hw : 2 ≤ w) (keepMin : Bool) {a b : RawSlot w}
+ (ha : Canonical hw a) (hb : Canonical hw b) : Canonical hw (SortRow.chosen keepMin a b) := by
+ unfold SortRow.chosen
+ split <;> assumption
+
+theorem selectOK_iff (hw : 2 ≤ w) (a b : RawSlot w) :
+ SortRow.selectOK a b = true ↔ Canonical hw a ∧ Canonical hw b := by
+ simp only [SortRow.selectOK, Bool.and_eq_true, canonical_observed hw]
+
+theorem verifyOK_iff (hw : 2 ≤ w) (a b : RawSlot w) :
+ SortRow.verifyOK a b = true ↔ (Canonical hw a ∧ Canonical hw b) ∧ a = b := by
+ simp only [SortRow.verifyOK, Bool.and_eq_true, selectOK_iff hw, Sorter.equalDecision_eq, decide_eq_true_eq]
+
+private def rowBit (s : Stage (h+d)) (v : Fin (2^d)) (i : Fin (2^h)) : Bool :=
+ let g := v.val*2^h+i.val
+ g.testBit s.stride == g.testBit s.phase
+
+private theorem bit_eq (s : Stage (h+d)) (v : Fin (2^d)) (i : Fin (2^h)) :
+ (decide ((wireIndex h v.val i.val).eval < (wirePartner h v.val i.val s.stride).eval) ==
+ decide ((directionBit h v.val i.val s.phase).eval = 0)) = rowBit s v i := by
+ rw [wireIndex_eval, wirePartner_eval, directionBit_eval, orientation]
+ rfl
+
+variable (hw : 2 ≤ w) (raw : ℕ → Bool) (s : Stage (h+d)) (v : Fin (2^d))
+ (cur : Wires h (OrderedSlot (Word w))) (i : Fin (2^h))
+
+theorem cross_ok (hc : h ≤ s.stride) :
+ (scanRow hw raw s v cur i).ok = true ↔
+ Canonical hw (fieldWords w raw s 0 i) ∧ Canonical hw (fieldWords w raw s 1 i) ∧
+ parsedSlot hw (fieldWords w raw s 0 i) = cur i := by
+ simp only [scanRow, hc, dite_true, readSlot_eq, compareSlots_result]
+ by_cases ho : Canonical hw (fieldWords w raw s 0 i) <;>
+ by_cases hi : Canonical hw (fieldWords w raw s 1 i) <;>
+ simp [ho, hi, Bool.and_eq_true]
+ rw [ite_eq_left ho, Option.getD_some]
+ exact ⟨fun h => ⟨ho,hi,le_antisymm h.1.2 h.2⟩,
+ fun h => ⟨⟨⟨ho,hi⟩,h.2.2.le⟩,h.2.2.ge⟩⟩
+
+theorem cross_value (hc : h ≤ s.stride) (hi : Canonical hw (fieldWords w raw s 1 i)) :
+ (scanRow hw raw s v cur i).slot =
+ pick ((v.val*2^h+i.val).testBit s.stride == (v.val*2^h+i.val).testBit s.phase)
+ (cur i) (parsedSlot hw (fieldWords w raw s 1 i)) := by
+ simp only [scanRow, hc, dite_true, readSlot_eq]
+ change (if (compareSlots _ _).1 == _ then cur i else _) = _
+ rw [compareSlots_result, bit_eq, ite_eq_left hi, Option.getD_some]
+ rfl
+
+theorem local_ok (hc : s.stride < h) : (scanRow hw raw s v cur i).ok = true := by
+ simp [scanRow, Nat.not_le.mpr hc]
+
+theorem local_value (hc : s.stride < h) :
+ (scanRow hw raw s v cur i).slot =
+ pick ((v.val*2^h+i.val).testBit s.stride == (v.val*2^h+i.val).testBit s.phase)
+ (cur i) (cur ⟨partner s.stride i, partner_lt i.isLt hc⟩) := by
+ simp only [scanRow, Nat.not_le.mpr hc, dite_false]
+ change (if (compareSlots _ _).1 == _ then cur i else _) = _
+ rw [compareSlots_result, bit_eq]
+ rfl
+
+end RAMTape.SortReplay
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortReplaySlot.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortReplaySlot.lean
new file mode 100644
index 0000000000..ca09fa59d1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortReplaySlot.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.RAMTapeSortDecision
+import OAI.Computability.VPVNP.RAMTapeSortRowAddress
+import OAI.Computability.VPVNP.RAMSortCost
+
+/-! # The decoded value and validity of an addressed sorting record
+
+The physical comparator works on five arbitrary words, while the word-work
+replay uses the checked bit decoder. Re-encoding the parsed slot characterizes
+precisely when that decoder returns a record, including the all-zero empty slot.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortReplay
+
+open BurstRAM RAMMemory RAMSort RAMSerialization RAMBoundary
+
+variable {h d w : ℕ}
+
+/-- Parsing a raw five-word slot and re-encoding it reproduces every word, including the
+all-zero encoding of an empty slot. -/
+abbrev Canonical (hw : 2 ≤ w) (a : RawSlot w) := (recordFormat hw).words ((recordFormat hw).parse a) = a
+
+theorem canonical_iff (hw : 2 ≤ w) (a : RawSlot w) :
+ Canonical hw a ↔ ∃ r, (recordFormat hw).words r = a := by
+ constructor
+ · exact fun h => ⟨_,h⟩
+ · rintro ⟨r, rfl⟩
+ simp [Canonical, Format.parse_words]
+
+theorem canonical_observed (hw : 2 ≤ w) (a : RawSlot w) :
+ Sorter.canonical (fun i ↦ SuccessorTags.Tag.ofNat (a i).val) = true ↔ Canonical hw a :=
+ (Sorter.canonical_iff hw a).trans (canonical_iff hw a).symm
+
+theorem parsed_eq_iff (hw : 2 ≤ w) {a b : RawSlot w} (ha : Canonical hw a) (hb : Canonical hw b) :
+ parsedSlot hw a = parsedSlot hw b ↔ a = b := by
+ refine ⟨?_, fun h => h ▸ rfl⟩
+ intro he
+ have hh := congrArg OrderedSlot.record he
+ change ((recordFormat hw).parse a).map WordRecord.record =
+ ((recordFormat hw).parse b).map WordRecord.record at hh
+ have inj : Function.Injective (Option.map (WordRecord.record (w := w))) := by
+ intro r t ht
+ cases r <;> cases t <;> simp_all [WordRecord.record_injective.eq_iff]
+ exact ha.symm.trans ((congrArg (recordFormat hw).words (inj hh)).trans hb)
+
+/-- The raw five words at the exact bit address used by the checked RAM scan. -/
+def fieldWords (w : ℕ) (incident : ℕ → Bool) (s : Stage (h+d)) (dir : Fin 2) (i : Fin (2^h)) :
+ RawSlot w :=
+ (arrayBits 5 w).symm (fun bit => incident ((fieldStart h w s.phase s.stride dir.val i.val).eval + bit.val))
+
+theorem readSlot_eq (hw : 2 ≤ w) (incident : ℕ → Bool) (s : Stage (h+d)) (dir : Fin 2)
+ (i : Fin (2^h)) :
+ (readSlot hw incident s dir i).1 =
+ if Canonical hw (fieldWords w incident s dir i) then some (parsedSlot hw (fieldWords w incident s dir i))
+ else none := by
+ let bits := fun bit : Fin (5*w) => incident ((fieldStart h w s.phase s.stride dir.val i.val).eval + bit.val)
+ let a := (arrayBits 5 w).symm bits
+ have he : (recordFormat hw).encode ((recordFormat hw).parse a) = bits ↔ Canonical hw a :=
+ ((arrayBits 5 w).eq_symm_apply).symm
+ simp only [readSlot, decodeSlot_eq, Format.decode]
+ change (if (recordFormat hw).encode ((recordFormat hw).parse a) = bits then some ((recordFormat hw).parse a)
+ else none).map _ = if Canonical hw a then some (parsedSlot hw a) else none
+ simp only [he]
+ split <;> rfl
+
+/-- The integer address comparison and phase-direction test in the checked
+replay give the same bit as the finite row-address routine. -/
+theorem orientation (g a j : ℕ) :
+ (decide (g < partner j g) == phaseDirection a g) = (g.testBit j == g.testBit a) := by
+ have he : phaseDirection a g = !(g.testBit a) := by
+ simp only [phaseDirection, Nat.testBit_eq_decide_div_mod_eq, ← decide_not, decide_eq_decide]
+ have := Nat.mod_lt (g / 2^a) (by decide : 0 < 2)
+ omega
+ have hd : decide (g < partner j g) = decide (g.testBit j = false) := decide_eq_decide.mpr (SortRowAddress.lt_partner_iff g j)
+ rw [he, hd]
+ cases g.testBit j <;> cases g.testBit a <;> decide
+
+end RAMTape.SortReplay
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowAddress.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowAddress.lean
new file mode 100644
index 0000000000..6e4bc252d1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowAddress.lean
@@ -0,0 +1,352 @@
+import OAI.Computability.VPVNP.RAMTapeSortRowAddressScan
+import OAI.Computability.VPVNP.RAMTapeSortRowAddressUnary
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+import OAI.Computability.VPVNP.RAMSortFieldIndex
+
+/-! # The bitonic sorter’s finite row-address machine
+
+The global wire has the row bits followed by the site bits in little-endian
+order. The phase and stride are unary counters on the tape. Two indexed reads
+supply the direction. A third pass toggles the stride bit within the row, if
+present, and converts the resulting offset to a unary record count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRowAddress
+
+open BurstRAM TapeWord
+
+/-- The phase and stride bit positions queried in the global wire address to determine the
+comparator orientation. -/
+inductive Axis where | phase | stride
+ deriving DecidableEq
+
+instance : Fintype Axis := derive_fintype% _
+
+/-- Ports for the row and site indices, stage parameters, orientation and partner decisions,
+and scratch for bit scans and unary conversion. -/
+inductive Port where
+ | row | site | index (axis : Axis) | orientation | offset | localFlag
+ | observed (axis : Axis) | bits | count | rev | tmp
+ deriving DecidableEq, Fintype
+
+/-- The unary index of the phase bit to read from the concatenated row and site address. -/
+abbrev Port.phase : Port := .index .phase
+/-- The unary index of the stride bit used for both orientation and partner selection. -/
+abbrev Port.stride : Port := .index .stride
+
+private abbrev marks (n : ℕ) := List.replicate n true
+
+private structure Work where
+ observed : Axis → List Bool := fun _ => []
+ orientation : List Bool := []
+ localFlag : List Bool := []
+ offset : ℕ := 0
+ bits : List Bool := []
+ count : List Bool := []
+ rev : List Bool := []
+
+private def number (a j : ℕ) : Axis → ℕ
+ | .phase => a
+ | .stride => j
+
+private def frame (row site : List Bool) (a j : ℕ) (s : Work) : Stacks Port
+ | .row => row
+ | .site => site
+ | .index ax => marks (number a j ax)
+ | .observed ax => s.observed ax
+ | .orientation => s.orientation
+ | .offset => marks s.offset
+ | .localFlag => s.localFlag
+ | .bits => s.bits
+ | .count => s.count
+ | .rev => s.rev
+ | .tmp => []
+
+private def copy (src dst : Port) := SuccessorFields.prependCopy src dst .tmp
+
+private theorem copy_run (src dst : Port) (hd : src ≠ dst) (hs : src ≠ .tmp) (ht : dst ≠ .tmp)
+ (s : Stacks Port) (h : s .tmp = []) :
+ (copy src dst).Runs (5*(s src).length+2) s (Function.update s dst (s src ++ s dst)) :=
+ SuccessorFields.prependCopy_runs _ _ _ hd hs ht s h
+
+private def scanPorts (flag : Port) : IndexScan.Port → Port
+ | .bits => .bits
+ | .count => .count
+ | .rev => .rev
+ | .flag => flag
+
+private def readWire (axis : Axis) : FiniteRoutine Port :=
+ (((copy .site .bits).followedBy (copy .row .bits)).followedBy
+ (copy (.index axis) .count)).followedBy ((IndexScan.routine false).onPorts (scanPorts (.observed axis)))
+
+private theorem readWire_run (axis : Axis) (row site : List Bool) (a j : ℕ) (obs : Axis → List Bool)
+ (ho : obs axis = []) :
+ let k := number a j axis
+ let g := value (row ++ site)
+ ∃ t ≤ 8*(row.length+site.length)+6*k+9, (readWire axis).Runs t
+ (frame row site a j {observed := obs})
+ (frame row site a j {observed := Function.update obs axis [g.testBit k]}) := by
+ let k := number a j axis
+ let F := frame row site a j
+ let s₀ : Work := {observed := obs}
+ let s₁ := {s₀ with bits := site}
+ let s₂ := {s₁ with bits := row ++ site}
+ let s₃ := {s₂ with count := marks k}
+ let s₄ : Work := {observed := Function.update obs axis [(value (row ++ site)).testBit k]}
+ have c₁ := copy_run .site .bits (by decide) (by decide) (by decide) (F s₀) rfl
+ have c₂ := copy_run .row .bits (by decide) (by decide) (by decide) (F s₁) rfl
+ have c₃ := copy_run (.index axis) .count (by intro h; cases h) (by intro h; cases h) (by decide) (F s₂) rfl
+ have e₁ : Function.update (F s₀) Port.bits (site ++ []) = F s₁ := by
+ funext p; cases p <;> simp [F, s₀, s₁, frame, Function.update]
+ have e₂ : Function.update (F s₁) Port.bits (row ++ site) = F s₂ := by
+ funext p; cases p <;> rfl
+ have e₃ : Function.update (F s₂) Port.count (marks k ++ []) = F s₃ := by
+ funext p; cases p <;> simp [F, s₂, s₃, frame, Function.update]
+ change (copy ..).Runs (5*site.length+2) (F s₀) (Function.update (F s₀) .bits (site ++ [])) at c₁
+ change (copy ..).Runs (5*row.length+2) (F s₁) (Function.update (F s₁) .bits (row ++ site)) at c₂
+ change (copy ..).Runs (5*(marks k).length+2) (F s₂) (Function.update (F s₂) .count (marks k ++ [])) at c₃
+ rw [e₁] at c₁
+ rw [e₂] at c₂
+ rw [e₃, List.length_replicate] at c₃
+ obtain ⟨n, hn, hscan⟩ := IndexScan.runs false k (row ++ site)
+ have scan : ((IndexScan.routine false).onPorts (scanPorts (.observed axis))).Runs n (F s₃) (F s₄) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (by intro x y h; cases x <;> cases y <;> simp_all [scanPorts]) hscan
+ · intro p; cases p <;> first | rfl | exact ho
+ · intro p; cases p <;> first | rfl | exact Function.update_self ..
+ · intro p h
+ cases p with
+ | observed z =>
+ exact Function.update_of_ne (by intro e; subst z; exact h .flag rfl) ..
+ | bits => exact (h .bits rfl).elim
+ | count => exact (h .count rfl).elim
+ | row | site | index | orientation | offset | localFlag | rev | tmp => rfl
+ refine ⟨_, ?_, ((c₁.followedBy c₂).followedBy c₃).followedBy scan⟩
+ simp only [List.length_append] at hn
+ dsimp only [k] at *
+ omega
+
+private inductive EqState where | phase | stride (x : Bool) | emit (b : Bool) | done
+ deriving DecidableEq, Fintype
+
+private def eqCode : StackCode Port EqState
+ | .phase => .pop (.observed .phase) fun x => .stride (x.getD false)
+ | .stride x => .pop (.observed .stride) fun y => .emit (x == y.getD false)
+ | .emit b => .push .orientation b .done
+ | .done => .halt true
+
+private def equalBits : FiniteRoutine Port := FiniteRoutine.ofStackCode eqCode id .phase (· == .done)
+
+private theorem equalBits_run (row site : List Bool) (a j : ℕ) (x y : Bool) :
+ equalBits.Runs 3 (frame row site a j {observed := fun | .phase => [x] | .stride => [y]})
+ (frame row site a j {orientation := [x == y]}) := by
+ let F := frame row site a j
+ let s₀ : Work := {observed := fun | .phase => [x] | .stride => [y]}
+ let s₁ : Work := {observed := fun | .phase => [] | .stride => [y]}
+ let s₂ : Work := {}
+ let s₃ : Work := {orientation := [x == y]}
+ have e₁ : Function.update (F s₀) (.observed .phase) [] = F s₁ := by
+ funext p; cases p <;> first | rfl | rename_i k; cases k <;> rfl
+ have e₂ : Function.update (F s₁) (.observed .stride) [] = F s₂ := by
+ funext p; cases p <;> first | rfl | rename_i k; cases k <;> rfl
+ have e₃ : Function.update (F s₂) Port.orientation [x == y] = F s₃ := by
+ funext p; cases p <;> rfl
+ have run : StackRuns eqCode 3 .phase (F s₀) .done (F s₃) := by
+ refine .cons (.pop rfl) ?_
+ change StackRuns eqCode 2 (.stride x) (Function.update (F s₀) (.observed .phase) []) _ _
+ rw [e₁]
+ refine .cons (.pop rfl) ?_
+ change StackRuns eqCode 1 (.emit (x == y)) (Function.update (F s₁) (.observed .stride) []) _ _
+ rw [e₂]
+ refine .cons (.push rfl) ?_
+ change StackRuns eqCode 0 .done (Function.update (F s₂) .orientation [x == y]) _ _
+ rw [e₃]
+ exact .nil ..
+ exact FiniteRoutine.runs_ofStackCode_framed Function.injective_id rfl rfl
+ (fun q h => by simp only [beq_iff_eq] at h; subst q; rfl) run (fun _ => rfl) (fun _ => rfl)
+ (fun p h => (h p rfl).elim)
+
+private def unaryPorts : Unary.Port → Port
+ | .bits => .rev
+ | .out => .offset
+ | .tmp => .tmp
+
+private def offsetRoutine : FiniteRoutine Port :=
+ (((copy .row .bits).followedBy (copy .stride .count)).followedBy
+ ((IndexScan.routine true).onPorts (scanPorts .localFlag))).followedBy (Unary.routine.onPorts unaryPorts)
+
+private theorem offset_run (row site : List Bool) (a j : ℕ) (direction : Bool) :
+ let peer := IndexScan.flip j row
+ ∃ t ≤ 12*row.length+6*j+7*value peer+8, offsetRoutine.Runs t
+ (frame row site a j {orientation := [direction]})
+ (frame row site a j {orientation := [direction], offset := value peer, localFlag := [decide (j simp [F, s₀, s₁, frame, Function.update]
+ have e₂ : Function.update (F s₁) Port.count (marks j ++ []) = F s₂ := by
+ funext p; cases p <;> simp [F, s₁, s₂, frame, Function.update]
+ change (copy ..).Runs (5*row.length+2) (F s₀) (Function.update (F s₀) .bits (row ++ [])) at c₁
+ change (copy ..).Runs (5*(marks j).length+2) (F s₁) (Function.update (F s₁) .count (marks j ++ [])) at c₂
+ rw [e₁] at c₁
+ rw [e₂, List.length_replicate] at c₂
+ obtain ⟨n, hn, hscan⟩ := IndexScan.runs true j row
+ have scan : ((IndexScan.routine true).onPorts (scanPorts .localFlag)).Runs n (F s₂) (F s₃) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (by intro x y h; cases x <;> cases y <;> simp_all [scanPorts]) hscan
+ · intro p; cases p <;> rfl
+ · intro p; cases p <;> rfl
+ · intro p h; cases p <;> first | rfl | exact (h .bits rfl).elim | exact (h .count rfl).elim
+ | exact (h .rev rfl).elim | exact (h .flag rfl).elim
+ obtain ⟨u, hu, hunary⟩ := Unary.runs peer
+ have un : (Unary.routine.onPorts unaryPorts).Runs u (F s₃) (F s₄) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (by intro x y h; cases x <;> cases y <;> simp_all [unaryPorts]) hunary
+ · intro p; cases p <;> rfl
+ · intro p; cases p <;> rfl
+ · intro p h; cases p <;> first | rfl | exact (h .bits rfl).elim | exact (h .out rfl).elim
+ refine ⟨_, ?_, ((c₁.followedBy c₂).followedBy scan).followedBy un⟩
+ simp only [peer, IndexScan.length_flip] at hu
+ omega
+
+/-- All input-dependent parameters are bit stacks. The instruction table is fixed. -/
+def routine : FiniteRoutine Port :=
+ (((readWire .phase).followedBy (readWire .stride)).followedBy equalBits).followedBy offsetRoutine
+
+/-- Initialize the row-address machine with the given row and site bits, unary phase and
+stride, and empty work stacks. -/
+def initial (row site : List Bool) (a j : ℕ) : Stacks Port := frame row site a j {}
+
+/-- The three outputs are a one-bit orientation, a one-bit local stride indicator,
+and the unary record offset. The original row, site and both counters are retained. -/
+def final (row site : List Bool) (a j : ℕ) (keepMin localStride : Bool) (offset : ℕ) : Stacks Port :=
+ frame row site a j {orientation := [keepMin], localFlag := [localStride], offset := offset}
+
+theorem initial_port (row site : List Bool) (a j : ℕ) (p : Port) :
+ initial row site a j p = match p with
+ | .row => row
+ | .site => site
+ | .index .phase => List.replicate a true
+ | .index .stride => List.replicate j true
+ | _ => [] := by
+ cases p <;> first | rfl | rename_i ax; cases ax <;> rfl
+
+theorem final_port (row site : List Bool) (a j : ℕ) (keepMin localStride : Bool)
+ (offset : ℕ) (p : Port) :
+ final row site a j keepMin localStride offset p = match p with
+ | .orientation => [keepMin]
+ | .localFlag => [localStride]
+ | .offset => List.replicate offset true
+ | _ => initial row site a j p := by
+ cases p <;> rfl
+
+/-- Tick allowance for the indexed phase and stride reads and conversion of the possibly
+toggled h-bit row index to a unary offset. -/
+def budget (h d a j : ℕ) : ℕ := 28*h+16*d+6*a+12*j+7*2^h+29
+
+/-- The maximum phase, equal to the total width, reads a zero direction bit.
+This also covers empty row and site words. -/
+theorem runs_bits (row site : List Bool) (a j : ℕ) :
+ let g := value site * 2^row.length + value row
+ let off := if j < row.length then RAMSort.partner j (value row) else value row
+ ∃ t ≤ budget row.length site.length a j, routine.Runs t (initial row site a j)
+ (final row site a j (g.testBit j == g.testBit a) (decide (j < row.length)) off) := by
+ let g := value (row ++ site)
+ let obs : Axis → List Bool := Function.update (fun _ => []) .phase [g.testBit a]
+ obtain ⟨t, ht, h₁⟩ := readWire_run .phase row site a j (fun _ => []) rfl
+ obtain ⟨u, hu, h₂⟩ := readWire_run .stride row site a j obs rfl
+ have he : Function.update obs Axis.stride [g.testBit j] =
+ fun | .phase => [g.testBit a] | .stride => [g.testBit j] := by funext ax; cases ax <;> rfl
+ change (readWire .stride).Runs u _ (frame row site a j {observed := Function.update obs .stride [g.testBit j]}) at h₂
+ rw [he] at h₂
+ have eq := equalBits_run row site a j (g.testBit a) (g.testBit j)
+ obtain ⟨v, hv, h₃⟩ := offset_run row site a j (g.testBit a == g.testBit j)
+ have chain := ((h₁.followedBy h₂).followedBy eq).followedBy h₃
+ have hval := value_lt (IndexScan.flip j row)
+ rw [IndexScan.length_flip] at hval
+ have hg : g = value site * 2^row.length + value row := by simp [g, value_append, Nat.mul_comm, Nat.add_comm]
+ change routine.Runs _ (initial row site a j)
+ (final row site a j (g.testBit a == g.testBit j) (decide (j < row.length)) (value (IndexScan.flip j row))) at chain
+ rw [hg, IndexScan.flip_value, BEq.comm] at chain
+ refine ⟨_, ?_, chain⟩
+ change t ≤ 8*(row.length+site.length)+6*a+9 at ht
+ change u ≤ 8*(row.length+site.length)+6*j+9 at hu
+ unfold budget
+ omega
+
+theorem runs {h d : ℕ} (i : Word h) (v : Word d) (a j : ℕ) :
+ let g := v.val * 2^h + i.val
+ let off := if j < h then RAMSort.partner j i.val else i.val
+ ∃ t ≤ budget h d a j, routine.Runs t (initial (wordBits i) (wordBits v) a j)
+ (final (wordBits i) (wordBits v) a j (g.testBit j == g.testBit a) (decide (j simp [Function.update, hp.eq_iff, hi]
+ · intro k hk
+ simp [Function.update, Ne.symm (hk .orientation), Ne.symm (hk .localFlag), Ne.symm (hk .offset)]
+
+/-- The lower-numbered wire in an XOR pair is the one with a zero stride bit. -/
+theorem lt_partner_iff (g j : ℕ) : g < RAMSort.partner j g ↔ g.testBit j = false := by
+ have same (k : ℕ) (hk : j < k) : (RAMSort.partner j g).testBit k = g.testBit k := by
+ simp [RAMSort.partner, Nat.testBit_two_pow_of_ne hk.ne]
+ have toggled : (RAMSort.partner j g).testBit j = !(g.testBit j) := by
+ simp [RAMSort.partner, Nat.testBit_two_pow_self]
+ cases h : g.testBit j with
+ | false =>
+ have lt := Nat.lt_of_testBit j h (by simpa [h] using toggled)
+ (fun k hk => (same k hk).symm)
+ simp [lt]
+ | true =>
+ have lt := Nat.lt_of_testBit j (by simpa [h] using toggled) h same
+ simp [Nat.not_lt_of_ge lt.le]
+
+private theorem direction_eq (g a : ℕ) : RAMSort.phaseDirection a g = !(g.testBit a) := by
+ simp only [RAMSort.phaseDirection, Nat.testBit_eq_decide_div_mod_eq, ← decide_not, decide_eq_decide]
+ have := Nat.mod_lt (g / 2^a) (by decide : 0 < 2)
+ omega
+
+/-- The machine's orientation chooses precisely the output assigned by the
+bitonic comparator, with the row's own record as the first input. -/
+theorem select_eq_comparator {α : Type*} [LinearOrder α] (g a j : ℕ) (own other : α) :
+ (if g.testBit j == g.testBit a then min own other else max own other) =
+ if g < RAMSort.partner j g then RAMSort.lower (RAMSort.phaseDirection a g) own other
+ else RAMSort.upper (RAMSort.phaseDirection a g) other own := by
+ simp only [lt_partner_iff, direction_eq]
+ cases g.testBit j <;> cases g.testBit a <;> simp [RAMSort.lower, RAMSort.upper, min_comm, max_comm]
+
+/-- A nonlocal stride changes precisely bit `j-h` of the site. The allocated
+physical field specifies the same peer as the global wire calculation. -/
+theorem cross_siteBit {h d : ℕ} (s : RAMSort.Stage (h+d)) (hc : h ≤ s.stride) :
+ ((RAMSort.crossStageEquiv h d).symm ⟨s,hc⟩).siteBit = s.stride - h := by
+ change s.phase - h - 1 - (s.phase - s.stride - 1) = s.stride - h
+ have := s.stride_lt
+ omega
+
+end RAMTape.SortRowAddress
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowAddressScan.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowAddressScan.lean
new file mode 100644
index 0000000000..094750b865
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowAddressScan.lean
@@ -0,0 +1,178 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+import OAI.Computability.VPVNP.RAMSortRouting
+
+/-! # Indexed bit reads and stride-bit flips in the row address machine -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRowAddress.IndexScan
+
+open TapeWord
+
+/-- Read a little-endian bit with zero extension. -/
+def read : ℕ → List Bool → Bool
+ | _, [] => false
+ | 0, b :: _ => b
+ | j+1, _ :: bs => read j bs
+
+/-- Toggle a bit within a fixed width. An out-of-range index preserves the word. -/
+def flip : ℕ → List Bool → List Bool
+ | _, [] => []
+ | 0, b :: bs => (!b) :: bs
+ | j+1, b :: bs => b :: flip j bs
+
+@[simp] theorem length_flip (j : ℕ) (xs : List Bool) : (flip j xs).length = xs.length := by
+ induction xs generalizing j with
+ | nil => simp [flip]
+ | cons b xs ih => cases j <;> simp [flip, ih]
+
+theorem read_value (j : ℕ) (xs : List Bool) : read j xs = (value xs).testBit j := by
+ induction xs generalizing j with
+ | nil => simp [value, read]
+ | cons b xs ih =>
+ have h : b.toNat < 2^1 := by cases b <;> decide
+ rw [value, Nat.add_comm, ← pow_one (2 : ℕ), Nat.testBit_two_pow_mul_add _ h]
+ cases j with
+ | zero => cases b <;> rfl
+ | succ j => simpa [read] using ih j
+
+private theorem read_flip (j k : ℕ) (xs : List Bool) :
+ read k (flip j xs) = (read k xs ^^ decide (j = k ∧ j < xs.length)) := by
+ induction xs generalizing j k with
+ | nil => simp [read, flip]
+ | cons b xs ih =>
+ cases j <;> cases k <;> simp [read, flip, ih]
+
+theorem flip_value (j : ℕ) (xs : List Bool) :
+ value (flip j xs) = if j < xs.length then RAMSort.partner j (value xs) else value xs := by
+ apply Nat.eq_of_testBit_eq
+ intro k
+ rw [← read_value, read_flip, read_value]
+ by_cases h : j < xs.length <;> simp [h, RAMSort.partner, Nat.testBit_two_pow]
+
+/-- The bit stream, unary position counter, reverse buffer and one-bit result of an indexed
+address scan. -/
+inductive Port where | bits | count | rev | flag
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Control for consuming the unary index, recording or flipping the addressed bit, draining
+the remaining stream and reporting the result. -/
+inductive State where
+ | scan | count (b : Bool) | write (b : Bool) (found : Option Bool)
+ | rest (b : Bool) | clear (b : Bool) | report (b : Bool) | done
+ deriving DecidableEq, Fintype
+
+/-- The same scan is used in two modes. A read returns the observed bit.
+A partner scan emits the modified word in high-to-low order and returns
+whether the stride bit belongs to the row. -/
+def code (peer : Bool) : StackCode Port State
+ | .scan => .pop .bits fun x => x.elim (.clear false) .count
+ | .count b => .pop .count fun x => x.elim (.write (!b) (some b)) (fun _ => .write b none)
+ | .write b found =>
+ let next := found.elim .scan .rest
+ if peer then .push .rev b next else .goto next
+ | .rest b => .pop .bits fun x => x.elim (.clear (peer || b)) (fun z => .write z (some b))
+ | .clear b => .pop .count fun x => x.elim (.report b) (fun _ => .clear b)
+ | .report b => .push .flag b .done
+ | .done => .halt true
+
+/-- Install the source bits, remaining count, reversed bits and result flag on their
+indexed-scan ports. -/
+def bank (xs count rev flag : List Bool) : Stacks Port
+ | .bits => xs
+ | .count => count
+ | .rev => rev
+ | .flag => flag
+
+private theorem set_bank (xs n rev flag v : List Bool) (p : Port) :
+ Function.update (bank xs n rev flag) p v = match p with
+ | .bits => bank v n rev flag
+ | .count => bank xs v rev flag
+ | .rev => bank xs n v flag
+ | .flag => bank xs n rev v := by
+ cases p <;> funext k <;> cases k <;> rfl
+
+local macro "scan_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_
+ | refine StackRuns.cons (.goto rfl) ?_)
+ <;> simp only [bank, List.replicate_succ, List.replicate_zero, List.head?_cons, List.head?_nil,
+ List.tail_cons, List.tail_nil, Option.elim_none, Option.elim_some, set_bank])
+
+private theorem clear_run (peer b : Bool) (j : ℕ) (rev flag : List Bool) :
+ StackRuns (code peer) (j+2) (.clear b) (bank [] (List.replicate j true) rev flag)
+ .done (bank [] [] rev (b :: flag)) := by
+ induction j with
+ | zero => scan_step; scan_step; exact .nil ..
+ | succ j ih => scan_step; exact ih
+
+private theorem rest_run (peer b : Bool) (xs rev flag : List Bool) :
+ StackRuns (code peer) (2*xs.length+3) (.rest b) (bank xs [] rev flag)
+ .done (bank [] [] (if peer then xs.reverse ++ rev else rev) ((peer || b) :: flag)) := by
+ induction xs generalizing rev with
+ | nil =>
+ simp only [List.length_nil, Nat.mul_zero, Nat.zero_add, List.reverse_nil, List.nil_append, ite_self]
+ scan_step
+ exact clear_run peer _ 0 _ _
+ | cons c xs ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ scan_step
+ cases peer <;> simp only [Bool.false_eq_true, ↓reduceIte] at ih ⊢ <;> scan_step <;> exact ih _
+
+theorem scan_run (peer : Bool) (j : ℕ) (xs rev flag : List Bool) :
+ ∃ t ≤ 3*xs.length+j+3, StackRuns (code peer) t .scan (bank xs (List.replicate j true) rev flag)
+ .done (bank [] [] (if peer then (flip j xs).reverse ++ rev else rev)
+ ((if peer then decide (j < xs.length) else read j xs) :: flag)) := by
+ induction xs generalizing j rev with
+ | nil =>
+ refine ⟨(j+2)+1, by simp, ?_⟩
+ simp only [flip, read, List.length_nil, List.reverse_nil, List.nil_append, ite_self, Nat.not_lt_zero,
+ decide_false]
+ scan_step
+ exact clear_run peer false j rev flag
+ | cons c xs ih =>
+ cases j with
+ | zero =>
+ refine ⟨2*xs.length+3+3, by simp; omega, ?_⟩
+ simp only [read, flip, List.length_cons, Nat.zero_lt_succ, decide_true, List.reverse_cons,
+ List.append_assoc, List.singleton_append]
+ scan_step
+ scan_step
+ cases peer <;> simp only [Bool.false_eq_true, ↓reduceIte] <;> scan_step
+ · simpa using rest_run false c xs rev flag
+ · simpa using rest_run true c xs ((!c)::rev) flag
+ | succ j =>
+ let out := if peer then c :: rev else rev
+ obtain ⟨t, ht, h⟩ := ih j out
+ refine ⟨t+3, by simp; omega, ?_⟩
+ simp only [read, flip, List.length_cons, Nat.succ_lt_succ_iff, List.reverse_cons,
+ List.append_assoc, List.singleton_append]
+ scan_step
+ scan_step
+ cases peer <;> simp only [out, Bool.false_eq_true, ↓reduceIte] at h ⊢ <;> scan_step <;> exact h
+
+/-- Read the requested bit with zero extension, or in peer mode toggle it when present and
+produce the reversed partner bits and local-stride flag. -/
+def routine (peer : Bool) : FiniteRoutine Port :=
+ FiniteRoutine.ofStackCode (code peer) id .scan (· == .done)
+
+theorem runs (peer : Bool) (j : ℕ) (xs : List Bool) :
+ ∃ t ≤ 3*xs.length+j+3, (routine peer).Runs t (bank xs (List.replicate j true) [] [])
+ (bank [] [] (if peer then (flip j xs).reverse else [])
+ [if peer then decide (j < xs.length) else (value xs).testBit j]) := by
+ obtain ⟨t, ht, run⟩ := scan_run peer j xs [] []
+ simp only [List.append_nil, read_value] at run
+ refine ⟨t, ht, ?_⟩
+ exact FiniteRoutine.runs_ofStackCode_framed Function.injective_id rfl rfl
+ (fun q h => by simp only [beq_iff_eq] at h; subst q; rfl) run (fun _ => rfl) (fun _ => rfl)
+ (fun k h => (h k rfl).elim)
+
+end RAMTape.SortRowAddress.IndexScan
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowAddressUnary.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowAddressUnary.lean
new file mode 100644
index 0000000000..56bdd43097
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowAddressUnary.lean
@@ -0,0 +1,148 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+
+/-! # Converting the sorter’s high-bit-first row offset to a unary count -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRowAddress.Unary
+
+open TapeWord
+
+/-- Stacks for high-bit-first binary input, the unary output and the scratch tally used while
+doubling it. -/
+inductive Port where | bits | out | tmp
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Control for reading the next bit, doubling the unary accumulator, restoring its marks and
+adding the bit. -/
+inductive State where
+ | read | double (b : Bool) | put₁ (b : Bool) | put₂ (b : Bool)
+ | restore (b : Bool) | putBack (b : Bool) | extra | done
+ deriving DecidableEq, Fintype
+
+/-- Consume high-order bits first and update the unary offset by doubling and adding the
+incoming bit. -/
+def code : StackCode Port State
+ | .read => .pop .bits fun x => x.elim .done .double
+ | .double b => .pop .out fun x => x.elim (.restore b) (fun _ => .put₁ b)
+ | .put₁ b => .push .tmp true (.put₂ b)
+ | .put₂ b => .push .tmp true (.double b)
+ | .restore b => .pop .tmp fun x => x.elim (if b then .extra else .read) (fun _ => .putBack b)
+ | .putBack b => .push .out true (.restore b)
+ | .extra => .push .out true .read
+ | .done => .halt true
+
+/-- Install the remaining binary input and unary encodings of the output and scratch counts. -/
+def bank (xs : List Bool) (n k : ℕ) : Stacks Port
+ | .bits => xs
+ | .out => List.replicate n true
+ | .tmp => List.replicate k true
+
+private def raw (xs out tmp : List Bool) : Stacks Port
+ | .bits => xs
+ | .out => out
+ | .tmp => tmp
+
+private theorem set_raw (xs out tmp v : List Bool) (p : Port) :
+ Function.update (raw xs out tmp) p v = match p with
+ | .bits => raw v out tmp
+ | .out => raw xs v tmp
+ | .tmp => raw xs out v := by
+ cases p <;> funext k <;> cases k <;> rfl
+
+local macro "unary_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [raw, List.replicate_succ, List.replicate_zero, List.head?_cons,
+ List.head?_nil, List.tail_cons, List.tail_nil, Option.elim_none, Option.elim_some, set_raw])
+
+private theorem double_runs (b : Bool) (xs : List Bool) (n k : ℕ) :
+ StackRuns code (3*n+1) (.double b) (bank xs n k) (.restore b) (bank xs 0 (k+2*n)) := by
+ change StackRuns code _ _ (raw xs _ _) _ (raw xs _ _)
+ induction n generalizing k with
+ | zero => simp only [Nat.mul_zero, Nat.add_zero]; unary_step; exact .nil ..
+ | succ n ih =>
+ simp only [Nat.mul_succ]
+ unary_step
+ unary_step
+ unary_step
+ simpa only [List.replicate_zero, List.replicate_succ, show k + (2*n+2) = (k+1+1)+2*n by omega]
+ using ih (k+1+1)
+
+private theorem restore_runs (b : Bool) (xs : List Bool) (n k : ℕ) :
+ StackRuns code (2*k+1) (.restore b) (bank xs n k) (if b then .extra else .read)
+ (bank xs (n+k) 0) := by
+ change StackRuns code _ _ (raw xs _ _) _ (raw xs _ _)
+ induction k generalizing n with
+ | zero => simp only [Nat.mul_zero, Nat.add_zero]; unary_step; exact .nil ..
+ | succ k ih =>
+ simp only [Nat.mul_succ]
+ unary_step
+ unary_step
+ simpa only [List.replicate_zero, List.replicate_succ, show n+(k+1) = (n+1)+k by omega] using ih (n+1)
+
+private def eval (xs : List Bool) (n : ℕ) : ℕ := xs.foldl (fun a b => 2*a+b.toNat) n
+
+private theorem scan (xs : List Bool) (n : ℕ) : ∃ t, t + 7*n ≤ 7*eval xs n + 4*xs.length+1 ∧
+ StackRuns code t .read (bank xs n 0) .done (bank [] (eval xs n) 0) := by
+ induction xs generalizing n with
+ | nil =>
+ refine ⟨1, by simp [eval]; omega, ?_⟩
+ change StackRuns code 1 _ (raw [] _ _) _ (raw [] _ _)
+ unary_step
+ exact .nil ..
+ | cons b xs ih =>
+ obtain ⟨t, ht, tail⟩ := ih (2*n+b.toNat)
+ have hd := double_runs b xs n 0
+ have hr := restore_runs b xs 0 (2*n)
+ simp only [Nat.zero_add] at hd hr
+ have start : StackRuns code 1 .read (bank (b :: xs) n 0) (.double b) (bank xs n 0) := by
+ change StackRuns code 1 _ (raw _ _ _) _ (raw _ _ _)
+ unary_step
+ exact .nil ..
+ have endStep : StackRuns code b.toNat (if b then .extra else .read)
+ (bank xs (2*n) 0) .read (bank xs (2*n+b.toNat) 0) := by
+ cases b with
+ | false => exact .nil ..
+ | true =>
+ change StackRuns code 1 _ (raw _ _ _) _ (raw _ _ _)
+ unary_step
+ exact .nil ..
+ refine ⟨_, ?_, (((start.trans hd).trans hr).trans endStep).trans tail⟩
+ simp only [eval, List.foldl_cons, List.length_cons] at ht ⊢
+ cases b <;> simp_all only [Bool.toNat_false, Bool.toNat_true] <;> omega
+
+private theorem eval_value (xs : List Bool) (n : ℕ) :
+ eval xs n = value xs.reverse + 2^xs.length*n := by
+ induction xs generalizing n with
+ | nil => simp [eval, value]
+ | cons b xs ih =>
+ change eval xs (2*n+b.toNat) = _
+ rw [ih, List.reverse_cons, value_append, List.length_reverse, List.length_cons, pow_succ]
+ simp only [value, Nat.mul_zero, Nat.add_zero]
+ ring
+
+/-- Convert the possibly toggled row address to the unary count used to fetch its partner
+record. -/
+def routine : FiniteRoutine Port := FiniteRoutine.ofStackCode code id .read (· == .done)
+
+/-- The accumulator doubles once per bit. Charging each old unary mark to a newly
+created mark bounds the total number of stack steps linearly in the final offset. -/
+theorem runs (xs : List Bool) : ∃ t ≤ 7*value xs + 4*xs.length+1,
+ routine.Runs t (bank xs.reverse 0 0) (bank [] (value xs) 0) := by
+ obtain ⟨t, ht, run⟩ := scan xs.reverse 0
+ simp only [eval_value, List.reverse_reverse, Nat.mul_zero, Nat.add_zero, List.length_reverse] at ht run
+ refine ⟨t, ht, ?_⟩
+ exact FiniteRoutine.runs_ofStackCode_framed Function.injective_id rfl rfl
+ (fun q h => by simp only [beq_iff_eq] at h; subst q; rfl) run (fun _ => rfl) (fun _ => rfl)
+ (fun k h => (h k rfl).elim)
+
+end RAMTape.SortRowAddress.Unary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowBranch.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowBranch.lean
new file mode 100644
index 0000000000..21c987ac32
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowBranch.lean
@@ -0,0 +1,45 @@
+import OAI.Computability.VPVNP.RAMTapeSortRowCompare
+
+/-!
+# Dispatching and closing a comparison row
+
+The public local-stride bit selects the corresponding row pass. The
+private partner cursor is emptied when that pass returns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRow
+
+theorem program_of_local {s m : Stacks Port} {t : ℕ} (hflag : s .localFlag = [true])
+ (h : localPass.Runs t (Function.update s .localFlag []) m) :
+ program.Runs (t+1+(2*(m .partner).length+1)) s (Function.update m .partner []) := by
+ apply FiniteRoutine.Runs.followedBy (a := _) (b := clearPartner) (s := s) (t := m)
+ · exact Routine.runs_popCase_true Port.localFlag (Routine.halt false) crossPass.body localPass.body hflag h
+ · exact clearPartner_runs m
+
+theorem program_of_cross {s m : Stacks Port} {t : ℕ} (hflag : s .localFlag = [false])
+ (h : crossPass.Runs t (Function.update s .localFlag []) m) :
+ program.Runs (t+1+(2*(m .partner).length+1)) s (Function.update m .partner []) := by
+ apply FiniteRoutine.Runs.followedBy (a := _) (b := clearPartner) (s := s) (t := m)
+ · exact Routine.runs_popCase_false Port.localFlag (Routine.halt false) crossPass.body localPass.body hflag h
+ · exact clearPartner_runs m
+
+/-- One row visits at most two records of its block, verifies at most one
+outgoing field, and selects one of its two operands. -/
+theorem rowCost_le {i j B w : ℕ} (hi : i ≤ B) (hj : j ≤ B) :
+ (5*i+2+SortGather.cost i w) + (50*w+18) + (5*j+2+SortGather.cost j w) +
+ (65*w+20) + 1 + (2*B+1) ≤ 4096*(B+1)*(w+1) := by
+ have hiw := Nat.mul_le_mul_right (40*w+12) hi
+ have hjw := Nat.mul_le_mul_right (40*w+12) hj
+ unfold SortGather.cost
+ ring_nf at hiw hjw ⊢
+ omega
+
+end RAMTape.SortRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowCompare.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowCompare.lean
new file mode 100644
index 0000000000..8ad66795a2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowCompare.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.RAMTapeSortCompare
+import OAI.Computability.VPVNP.RAMTapeSortRowProgram
+import OAI.Computability.VPVNP.StructuredStackRuns
+
+/-!
+# Executing a comparator at a local or cross-site sorting row
+
+The selected source determines which physical stream supplies the right
+record. Verification consumes the outgoing copy. Selection prepends the
+chosen record in reverse bit order to the next block, and both operations
+push their validity bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRow
+
+open RAMBoundary Boundary
+
+/-- The comparator starts with w unary width markers and empty width scratch, saved operand
+buffers and selection staging. -/
+structure CompareReady (w : ℕ) (s : Stacks Port) : Prop where
+ width : s .width = List.replicate w true
+ widthBack : s .widthBack = []
+ savedLeft : s .savedLeft = []
+ savedRight : s .savedRight = []
+ selectTmp : s .selectTmp = []
+
+/-- The caller retains the unread part of both operands. -/
+def compareResult (s : Stacks Port) (src : RightSource) (lt rt chunk : List Bool) (flag : Bool) :
+ Stacks Port := fun p =>
+ if p = .left then lt else if p = src.port then rt else if p = .next then chunk ++ s .next else
+ if p = .flags then flag :: s .flags else s p
+
+private def bank (s : Stacks Port) (lt rt : List Bool) : Sorter.Bank :=
+ ⟨lt, rt, [], [], [], [], [], s .next, s .flags⟩
+
+private theorem lift_compare {w n : ℕ} (r : FiniteRoutine Sorter.Port) (src : RightSource)
+ (s : Stacks Port) (a b : RawSlot w) (lt rt chunk : List Bool) (flag : Bool) (ready : CompareReady w s)
+ (hl : s .left = recordBytes a ++ lt) (hr : s src.port = recordBytes b ++ rt)
+ (run : r.Runs n (Sorter.ready a b (bank s lt rt)).stacks
+ (Sorter.returned w (bank s lt rt) flag chunk).stacks) :
+ (r.onPorts (comparePorts src)).Runs n s (compareResult s src lt rt chunk flag) := by
+ obtain ⟨hw, hwb, hsl, hsr, ht⟩ := ready
+ apply FiniteRoutine.runs_onPorts_framed r (comparePorts_injective src) run
+ · intro p
+ cases p <;> first | rfl | assumption
+ · intro p
+ cases src <;> cases p <;> first | rfl | assumption
+ · intro p h
+ have h₁ : p ≠ .left := Ne.symm (h .left)
+ have h₂ : p ≠ src.port := Ne.symm (h .right)
+ have h₃ : p ≠ .next := Ne.symm (h .next)
+ have h₄ : p ≠ .flags := Ne.symm (h .valid)
+ simp only [compareResult, h₁, h₂, h₃, h₄, ite_false]
+
+/-- Verify a cross-site send against the local slot, retaining its unread tail. -/
+theorem verify_runs {w : ℕ} (s : Stacks Port) (a b : RawSlot w) (lt rt : List Bool)
+ (ready : CompareReady w s) (hl : s .left = recordBytes a ++ lt)
+ (hr : s .crossSend = recordBytes b ++ rt) :
+ verify.Runs (50*w+18) s (compareResult s .outgoing lt rt [] (verifyOK a b)) :=
+ lift_compare Sorter.verify .outgoing s a b lt rt [] (verifyOK a b) ready hl hr
+ (Sorter.verify_runs a b (bank s lt rt))
+
+/-- Execute a known comparator orientation on two prepared operand streams. -/
+theorem select_runs {w : ℕ} (src : RightSource) (s : Stacks Port) (keepMin : Bool) (a b : RawSlot w)
+ (lt rt : List Bool) (ready : CompareReady w s) (hl : s .left = recordBytes a ++ lt)
+ (hr : s src.port = recordBytes b ++ rt) :
+ (select src keepMin).Runs (65*w+19) s
+ (compareResult s src lt rt (recordBytes (chosen keepMin a b)).reverse (selectOK a b)) :=
+ lift_compare (Sorter.select keepMin) src s a b lt rt (recordBytes (chosen keepMin a b)).reverse
+ (selectOK a b) ready hl hr (Sorter.select_runs keepMin a b (bank s lt rt))
+
+/-- Reading the public orientation takes one instruction before selection. -/
+theorem oriented_runs {w : ℕ} (src : RightSource) (s : Stacks Port) (keepMin : Bool) (a b : RawSlot w)
+ (lt rt : List Bool) (ready : CompareReady w s) (hkeep : s .orientation = [keepMin])
+ (hl : s .left = recordBytes a ++ lt) (hr : s src.port = recordBytes b ++ rt) :
+ (oriented src).Runs (65*w+20) s (compareResult (Function.update s .orientation []) src lt rt
+ (recordBytes (chosen keepMin a b)).reverse (selectOK a b)) := by
+ let t := Function.update s .orientation []
+ have ht : CompareReady w t :=
+ ⟨ready.width, ready.widthBack, ready.savedLeft, ready.savedRight, ready.selectTmp⟩
+ have hr' : t src.port = recordBytes b ++ rt := by cases src <;> exact hr
+ have hs := select_runs src t keepMin a b lt rt ht hl hr'
+ cases keepMin with
+ | false => exact Routine.runs_popCase_false Port.orientation _ _ _ hkeep hs
+ | true => exact Routine.runs_popCase_true Port.orientation _ _ _ hkeep hs
+
+end RAMTape.SortRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowCross.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowCross.lean
new file mode 100644
index 0000000000..e42ee8f94e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowCross.lean
@@ -0,0 +1,37 @@
+import OAI.Computability.VPVNP.RAMTapeSortRowCrossPass
+import OAI.Computability.VPVNP.RAMTapeSortRowBranch
+
+/-! # The cross-site branch of the physical sorting row -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRow
+
+open RAMBoundary Boundary
+
+theorem program_cross_runs {w B : ℕ} (s : Stacks Port) (block : Fin B → RawSlot w)
+ (i j : Fin B) (keepMin : Bool) (sent peer : RawSlot w) (st rt : List Bool)
+ (h : Ready s block i j false keepMin) (hs : s .crossSend = recordBytes sent ++ st)
+ (hr : s .crossReceive = recordBytes peer ++ rt) :
+ ∃ t ≤ 4096*(B+1)*(w+1), program.Runs t s
+ (result s keepMin (block i) peer (some sent) st rt) := by
+ let out := result s keepMin (block i) peer (some sent) st rt
+ have hp := crossPass_runs s block i j keepMin sent peer st rt h hs hr
+ have run := program_of_cross h.localFlag hp
+ simp only [Function.update_self, Function.update_idem, h.partner_eq, List.length_replicate] at run
+ have hclear : Function.update out Port.partner [] = out := by
+ change Function.update out Port.partner (out .partner) = out
+ exact Function.update_eq_self ..
+ rw [hclear] at run
+ have hc := rowCost_le (w := w) i.isLt.le i.isLt.le
+ have hj := j.isLt
+ refine ⟨_, ?_, run⟩
+ omega
+
+end RAMTape.SortRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowCrossPass.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowCrossPass.lean
new file mode 100644
index 0000000000..5f9adfc969
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowCrossPass.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.RAMTapeSortRowCompare
+
+/-!
+# Two physical record comparisons for a cross-site row
+
+The first local fetch is compared with the next outgoing field. After that
+check consumes the two operands, the routine fetches the local slot again
+and compares it with the incoming field to form the layer output.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRow
+
+open RAMBoundary Boundary
+
+theorem crossPass_runs {w B : ℕ} (s : Stacks Port) (block : Fin B → RawSlot w)
+ (i j : Fin B) (keepMin : Bool) (sent peer : RawSlot w) (st rt : List Bool)
+ (h : Ready s block i j false keepMin) (hs : s .crossSend = recordBytes sent ++ st)
+ (hr : s .crossReceive = recordBytes peer ++ rt) :
+ let f := 5*i.val+2+SortGather.cost i.val w
+ crossPass.Runs (f + (50*w+18 + (f + (65*w+20)))) (Function.update s .localFlag [])
+ (Function.update (result s keepMin (block i) peer (some sent) st rt) .partner (s .partner)) := by
+ let t := Function.update s Port.localFlag []
+ let a := block i
+ let f := 5*i.val+2+SortGather.cost i.val w
+ let r₁ := Function.update t Port.left (recordBytes a)
+ have ht : FetchReady w t := ⟨h.width, h.lookup, h.widthBack, h.saved, h.recordBack⟩
+ have h₁ : (fetch .first).Runs f t r₁ := by
+ have he := fetch_runs .first t block i ht h.block_eq h.row_eq
+ change (fetch .first).Runs f t (Function.update t Port.left (recordBytes a ++ t .left)) at he
+ simpa only [show t .left = [] from h.left, List.append_nil] using he
+ let r₂ := compareResult r₁ .outgoing [] st [] (verifyOK a sent)
+ have hcmp₁ : CompareReady w r₁ := ⟨h.width,h.widthBack,h.savedLeft,h.savedRight,h.selectTmp⟩
+ have h₂ : verify.Runs (50*w+18) r₁ r₂ := verify_runs r₁ a sent [] st hcmp₁ (by
+ change recordBytes a = recordBytes a ++ []
+ rw [List.append_nil]) hs
+ let r₃ := Function.update r₂ Port.left (recordBytes a)
+ have ht₂ : FetchReady w r₂ := ⟨h.width, h.lookup, h.widthBack, h.saved, h.recordBack⟩
+ have h₃ : (fetch .first).Runs f r₂ r₃ := by
+ have he := fetch_runs .first r₂ block i ht₂ h.block_eq h.row_eq
+ change (fetch .first).Runs f r₂ (Function.update r₂ Port.left (recordBytes a ++ [])) at he
+ simpa only [List.append_nil] using he
+ have hcmp₃ : CompareReady w r₃ := ⟨h.width,h.widthBack,h.savedLeft,h.savedRight,h.selectTmp⟩
+ have h₄ := oriented_runs .incoming r₃ keepMin a peer [] rt hcmp₃ h.orientation (by
+ change recordBytes a = recordBytes a ++ []
+ rw [List.append_nil]) hr
+ have hrun := h₁.followedBy (h₂.followedBy (h₃.followedBy h₄))
+ have he :
+ compareResult (Function.update r₃ .orientation []) .incoming [] rt
+ (recordBytes (chosen keepMin a peer)).reverse (selectOK a peer) =
+ Function.update (result s keepMin a peer (some sent) st rt) .partner (s .partner) := by
+ funext p
+ cases p <;> first | rfl | exact h.left.symm
+ rw [he] at hrun
+ exact hrun
+
+end RAMTape.SortRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowLocal.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowLocal.lean
new file mode 100644
index 0000000000..74f0494b07
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowLocal.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.RAMTapeSortRowBranch
+
+/-!
+# The local branch of a physical sorting row
+
+Both comparator operands are read from the current materialized array.
+The next block receives the selected record and the validity register
+receives its canonical-format check.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRow
+
+open RAMBoundary Boundary
+
+theorem program_local_runs {w B : ℕ} (s : Stacks Port) (block : Fin B → RawSlot w)
+ (i j : Fin B) (keepMin : Bool) (h : Ready s block i j true keepMin) :
+ ∃ t ≤ 4096*(B+1)*(w+1), program.Runs t s
+ (result s keepMin (block i) (block j) none (s .crossSend) (s .crossReceive)) := by
+ let t := Function.update s Port.localFlag []
+ let a := block i
+ let b := block j
+ let u := Function.update t Port.left (recordBytes a)
+ let v := Function.update u Port.right (recordBytes b)
+ have ht : FetchReady w t := ⟨h.width, h.lookup, h.widthBack, h.saved, h.recordBack⟩
+ have hu : FetchReady w u := ⟨h.width, h.lookup, h.widthBack, h.saved, h.recordBack⟩
+ have h₁ : (fetch .first).Runs (5*i.val+2+SortGather.cost i.val w) t u := by
+ have he := fetch_runs .first t block i ht h.block_eq h.row_eq
+ change (fetch .first).Runs _ t (Function.update t .left (recordBytes a ++ t .left)) at he
+ simpa only [show t .left = [] from h.left, List.append_nil] using he
+ have h₂ : (fetch .other).Runs (5*j.val+2+SortGather.cost j.val w) u v := by
+ have he := fetch_runs .other u block j hu h.block_eq h.partner_eq
+ change (fetch .other).Runs _ u (Function.update u .right (recordBytes b ++ u .right)) at he
+ simpa only [show u .right = [] from h.right, List.append_nil] using he
+ have hcmp : CompareReady w v := ⟨h.width, h.widthBack, h.savedLeft, h.savedRight, h.selectTmp⟩
+ have h₃ := oriented_runs .localRegister v keepMin a b [] [] hcmp h.orientation
+ (by change recordBytes a = recordBytes a ++ []; rw [List.append_nil])
+ (by change recordBytes b = recordBytes b ++ []; rw [List.append_nil])
+ let out := result s keepMin a b none (s .crossSend) (s .crossReceive)
+ have hpass := h₁.followedBy (h₂.followedBy h₃)
+ have he : compareResult (Function.update v .orientation []) .localRegister [] []
+ (recordBytes (chosen keepMin a b)).reverse (selectOK a b) =
+ Function.update out .partner (s .partner) := by
+ funext p
+ cases p <;> first | rfl | exact h.left.symm | exact h.right.symm
+ rw [he] at hpass
+ have run := program_of_local h.localFlag hpass
+ simp only [Function.update_self, Function.update_idem, h.partner_eq, List.length_replicate] at run
+ have hclear : Function.update out Port.partner [] = out := by
+ change Function.update out Port.partner (out .partner) = out
+ exact Function.update_eq_self ..
+ rw [hclear] at run
+ have hc := rowCost_le (w := w) i.isLt.le j.isLt.le
+ have hj := j.isLt
+ exact ⟨_, by omega, run⟩
+
+end RAMTape.SortRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowModel.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowModel.lean
new file mode 100644
index 0000000000..3a6ba1c4a9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowModel.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.RAMTapeSortRowPorts
+import OAI.Computability.VPVNP.RAMTapeSortField
+
+/-!
+# Register layout and outcomes for a physical compare-exchange row
+
+A local partner is fetched from the current block. At a cross-site layer
+the outgoing block is compared with the site’s current records and the
+incoming partner record supplies the other comparator operand. The flags
+are retained in reverse chronological order, just as the output records are.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRow
+
+open RAMBoundary Boundary
+
+/-- Source of the right comparison operand, either the fetched local partner, the outgoing
+record, or the incoming record. -/
+inductive RightSource | localRegister | outgoing | incoming
+ deriving DecidableEq
+
+/-- Select the row stack holding the right operand for this source. -/
+def RightSource.port : RightSource → Port
+ | .localRegister => .right
+ | .outgoing => .crossSend
+ | .incoming => .crossReceive
+
+/-- Wire a record comparator into the row stacks, sending its output to the next block and its
+validity bit to the flags stack. -/
+def comparePorts (src : RightSource) : Sorter.Port → Port
+ | .left => .left
+ | .right => src.port
+ | .width => .width
+ | .widthBack => .widthBack
+ | .savedLeft => .savedLeft
+ | .savedRight => .savedRight
+ | .tmp => .selectTmp
+ | .next => .next
+ | .valid => .flags
+
+theorem comparePorts_injective (src : RightSource) : Function.Injective (comparePorts src) := by
+ cases src <;> decide
+
+variable {w B : ℕ}
+
+/-- Choose the smaller or larger raw record according to the comparator orientation, choosing
+the first on a minimum tie and the second on a maximum tie. -/
+def chosen (keepMin : Bool) (a b : RawSlot w) : RawSlot w :=
+ if Sorter.leDecision (Sorter.expected a b) == keepMin then a else b
+
+/-- Test that both raw slots have canonical record tags. -/
+def selectOK (a b : RawSlot w) : Bool :=
+ Sorter.canonical (fun i => SuccessorTags.Tag.ofNat (a i).val) &&
+ Sorter.canonical (fun i => SuccessorTags.Tag.ofNat (b i).val)
+
+/-- Test canonicality of both slots and equality according to the record comparator. -/
+def verifyOK (a b : RawSlot w) : Bool := selectOK a b && Sorter.equalDecision (Sorter.expected a b)
+
+/-- All sources of a prepared row except the two cross-site streams. -/
+structure Ready (s : Stacks Port) (block : Fin B → RawSlot w) (i j : Fin B)
+ (localStride keepMin : Bool) : Prop extends FetchReady w s where
+ block_eq : s .current = blockBytes (List.ofFn block)
+ row_eq : s .row = List.replicate i.val true
+ partner_eq : s .partner = List.replicate j.val true
+ orientation : s .orientation = [keepMin]
+ localFlag : s .localFlag = [localStride]
+ left : s .left = []
+ right : s .right = []
+ savedLeft : s .savedLeft = []
+ savedRight : s .savedRight = []
+ selectTmp : s .selectTmp = []
+
+/-- Terminal register values of one row. A cross-site row pushes its verify
+flag first and its select flag second. -/
+def result (s : Stacks Port) (keepMin : Bool) (a b : RawSlot w)
+ (sent : Option (RawSlot w)) (sendTail receiveTail : List Bool) : Stacks Port
+ | .partner | .orientation | .localFlag => []
+ | .next => (recordBytes (chosen keepMin a b)).reverse ++ s .next
+ | .flags => selectOK a b :: (sent.elim (s .flags) (fun x => verifyOK a x :: s .flags))
+ | .crossSend => sendTail
+ | .crossReceive => receiveTail
+ | p => s p
+
+end RAMTape.SortRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowPorts.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowPorts.lean
new file mode 100644
index 0000000000..d77a552774
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowPorts.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.RAMTapeSortGatherPreserve
+import OAI.Computability.VPVNP.RAMTapeBoundaryDecision
+import OAI.Computability.VPVNP.StructuredStackLoop
+
+/-!
+# Fetching comparison operands at one physical sorting row
+
+The row traversal retains its unary row offset. A local stride additionally
+fetches its XOR partner from the same materialized block. At a cross-site
+stride the two remote fields are instead consumed as record streams.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRow
+
+open Boundary RAMSort RAMBoundary
+
+/-- Stacks for a sorting row, including the current and next blocks, remote streams, row
+offsets, comparator orientation, and validity flags. -/
+inductive Port
+ | current | next | crossSend | crossReceive | width | row | partner | orientation | localFlag
+ | lookup | saved | widthBack | recordBack | left | right | savedLeft | savedRight | selectTmp | flags
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Which locally fetched record to stage, the current row's record or its partner's. -/
+inductive Operand | first | other
+ deriving DecidableEq
+
+/-- Select the unary row offset or partner offset used to fetch this operand. -/
+def Operand.index : Operand → Port | .first => .row | .other => .partner
+/-- Select the left or right staging stack for the fetched operand. -/
+def Operand.destination : Operand → Port | .first => .left | .other => .right
+
+/-- Connect the block reader to the current block, scratch stacks, and this operand's
+destination. -/
+def fetchPorts (operand : Operand) : SortGather.Port → Port
+ | .block => .current
+ | .offset => .lookup
+ | .width => .width
+ | .widthBack => .widthBack
+ | .saved => .saved
+ | .recordBack => .recordBack
+ | .output => operand.destination
+
+/-- Fetch the indexed record from the current block while preserving the operand's offset. -/
+def fetch (operand : Operand) : FiniteRoutine Port :=
+ SortGather.fetchPreserving (fetchPorts operand) operand.index
+
+/-- Scratch and the word-width register required by a materialized array lookup. -/
+structure FetchReady (w : ℕ) (s : Stacks Port) : Prop where
+ width : s .width = List.replicate w true
+ lookup : s .lookup = []
+ widthBack : s .widthBack = []
+ saved : s .saved = []
+ recordBack : s .recordBack = []
+
+theorem fetch_runs {w B : ℕ} (o : Operand) (s : Stacks Port) (block : Fin B → RawSlot w)
+ (i : Fin B) (hready : FetchReady w s) (hblock : s .current = blockBytes (List.ofFn block))
+ (hidx : s o.index = List.replicate i.val true) :
+ (fetch o).Runs (5*i.val+2+SortGather.cost i.val w) s
+ (Function.update s o.destination (recordBytes (block i) ++ s o.destination)) := by
+ let rows := List.ofFn block
+ have hi : i.val < rows.length := by simp [rows]
+ have hs := List.take_append_drop i.val rows
+ rw [List.drop_eq_getElem_cons hi] at hs
+ have he : s .current = blockBytes (rows.take i.val) ++ recordBytes (block i) ++
+ blockBytes (rows.drop (i.val+1)) := by
+ rw [hblock]
+ have h := congrArg blockBytes hs
+ simpa only [blockBytes, List.flatMap_append, List.flatMap_cons, rows, List.getElem_ofFn,
+ List.append_assoc] using h.symm
+ have hinj : Function.Injective (fetchPorts o) := by cases o <;> decide
+ have hdis : ∀ j, o.index ≠ fetchPorts o j := by cases o <;> decide
+ apply SortGather.fetchPreserving_runs _ hinj _ hdis w i.val s
+ (blockBytes (rows.take i.val)) (recordBytes (block i)) (blockBytes (rows.drop (i.val+1)))
+ · simp [rows]
+ · exact length_recordBytes _
+ · exact he
+ · exact hidx
+ · exact hready.lookup
+ · exact hready.width
+ · exact hready.widthBack
+ · exact hready.saved
+ · exact hready.recordBack
+
+/-- The computed partner offset is private to one row. Discard it when
+returning control to the outer traversal. -/
+def clearPartner : FiniteRoutine Port :=
+ .ofRoutine (Routine.popLoop Port.partner (fun _ => true) Routine.ret Routine.ret)
+
+theorem clearPartner_runs (s : Stacks Port) :
+ clearPartner.Runs (2*(s .partner).length+1) s (Function.update s .partner []) := by
+ generalize hx : s .partner = xs
+ induction xs generalizing s with
+ | nil =>
+ have he : Function.update s .partner [] = s := by rw [← hx, Function.update_eq_self]
+ rw [he]
+ simpa [clearPartner, FiniteRoutine.ofRoutine, FiniteRoutine.Runs] using Routine.Runs.popLoop_empty Port.partner (fun _ => true) Routine.ret Routine.ret hx
+ | cons b xs ih =>
+ let mid := Function.update s Port.partner xs
+ have h := Routine.Runs.popLoop_continue Port.partner (fun _ => true) Routine.ret Routine.ret hx rfl
+ (mid := mid) (n := 1) (by cases b <;> exact Routine.runs_ret mid)
+ (ih mid (Function.update_self ..))
+ rw [show 1+1+(2*xs.length+1) = 2*(xs.length+1)+1 by omega] at h
+ simpa only [clearPartner, FiniteRoutine.ofRoutine, FiniteRoutine.Runs, List.length_cons,
+ mid, Function.update_idem] using h
+
+end RAMTape.SortRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortRowProgram.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortRowProgram.lean
new file mode 100644
index 0000000000..a42c2e4167
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortRowProgram.lean
@@ -0,0 +1,55 @@
+import OAI.Computability.VPVNP.RAMTapeSortRowModel
+import OAI.Computability.VPVNP.RAMTapeSortRecordCode
+
+/-!
+# The fixed finite stack control for one sorting row
+
+The public address routine delivers the local-stride and orientation bits.
+A local row fetches both operands from the current array. A cross-site row
+verifies the sent copy and then combines a freshly fetched local record
+with the receive. The two physical incident streams are consumed only by
+the corresponding cross-site operations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortRow
+
+/-- Run the row comparator on the chosen right operand and retain the minimum or maximum as
+directed. -/
+def select (src : RightSource) (keepMin : Bool) : FiniteRoutine Port :=
+ (Sorter.select keepMin).onPorts (comparePorts src)
+
+/-- Compare the staged local record with the outgoing record and emit the verification flag. -/
+def verify : FiniteRoutine Port := Sorter.verify.onPorts (comparePorts .outgoing)
+
+/-- Pop the public comparator orientation and consume the two staged
+records. A missing address decision rejects. -/
+def oriented (src : RightSource) : FiniteRoutine Port :=
+ .ofRoutine (Routine.popCase Port.orientation (Routine.halt false) (select src false).body
+ (select src true).body)
+
+/-- Fetch the current row and its local partner, then apply the comparison in the requested
+orientation. -/
+def localPass : FiniteRoutine Port :=
+ (fetch .first).followedBy ((fetch .other).followedBy (oriented .localRegister))
+
+/-- Verify the outgoing copy against the current row, fetch that row again, and compare it with
+the incoming partner. -/
+def crossPass : FiniteRoutine Port :=
+ (fetch .first).followedBy (verify.followedBy ((fetch .first).followedBy (oriented .incoming)))
+
+private def branch : FiniteRoutine Port :=
+ .ofRoutine (Routine.popCase Port.localFlag (Routine.halt false) crossPass.body localPass.body)
+
+/-- Dispatch on the local-stride flag, execute the corresponding row pass, and clear the
+partner offset. -/
+def program : FiniteRoutine Port := branch.followedBy clearPartner
+
+end RAMTape.SortRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortSchedule.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortSchedule.lean
new file mode 100644
index 0000000000..207ac8658f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortSchedule.lean
@@ -0,0 +1,276 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.TallyStacks
+import OAI.Computability.VPVNP.RAMSortCostLayout
+
+/-!
+# Finite control for the bitonic phase and stride loops
+
+Start with one unary mark for each bit of the global wire address. Each
+outer pop advances the phase. A preserved copy of the new phase drives
+the inner loop, which presents the exponents in descending order. The
+layer routine sees the actual unary phase and stride while it works on
+the site's bit stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortSchedule
+
+open RAMSort Routine
+
+/-- Unary loop counters and scratch stack for the phase and descending-stride loops of bitonic
+sorting. -/
+inductive Control | remaining | phase | stride | tmp
+ deriving DecidableEq
+
+instance : Fintype Control := derive_fintype% _
+
+/-- Sorting schedule registers formed from the loop-control stacks and the caller's layer
+registers. -/
+abbrev Port (K : Type) := Control ⊕ K
+
+/-- Initialize the remaining, phase, and stride stacks with unary marks, clear the temporary
+stack, and retain the caller's data. -/
+def bank {K : Type} (s : Stacks K) (left a j : ℕ) : Stacks (Port K)
+ | .inl .remaining => List.replicate left true
+ | .inl .phase => List.replicate a true
+ | .inl .stride => List.replicate j true
+ | .inl .tmp => []
+ | .inr k => s k
+
+variable {K : Type} [DecidableEq K]
+
+private def copyPhase : FiniteRoutine (Port K) :=
+ (FiniteRoutine.ofRoutine (Tally.copyAdd Control.phase .stride .tmp)).onPorts Sum.inl
+
+private theorem copyPhase_run (s : Stacks K) (left a : ℕ) :
+ copyPhase.Runs (5*a+2) (bank s left a 0) (bank s left a a) := by
+ let registers : Tally.State Control
+ | .remaining => left
+ | .phase => a
+ | _ => 0
+ have h := Tally.copyAdd_runs Control.phase .stride .tmp (by decide) (by decide) (by decide) registers rfl
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective h
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> simp [bank, Tally.encode, registers, Function.update]
+ · rintro (i|k) h
+ · exact (h i rfl).elim
+ · rfl
+
+private theorem change_left (s : Stacks K) (left next a j : ℕ) :
+ Function.update (bank s left a j) (.inl .remaining) (List.replicate next true) = bank s next a j := by
+ funext k; rcases k with c | k; cases c <;> simp [bank]; simp [bank]
+
+private theorem change_stride (s : Stacks K) (left a j next : ℕ) :
+ Function.update (bank s left a j) (.inl .stride) (List.replicate next true) = bank s left a next := by
+ funext k; rcases k with c | k; cases c <;> simp [bank]; simp [bank]
+
+private theorem incPhase_run (s : Stacks K) (left a : ℕ) :
+ (push (Sum.inl Control.phase) true).Runs 1 (bank s left a 0) (bank s left (a+1) 0) := by
+ convert runs_push (Sum.inl Control.phase) true (bank s left a 0) using 1
+ funext i; rcases i with c | k; cases c <;> simp [bank, List.replicate_succ]; simp [bank]
+
+variable (layer : FiniteRoutine (Port K))
+
+private def eachStride : FiniteRoutine (Port K) :=
+ .ofRoutine (popLoop (.inl .stride) (fun _ => true) (halt false) layer.body)
+
+private def phaseBody : FiniteRoutine (Port K) :=
+ ((FiniteRoutine.ofRoutine (push (Sum.inl Control.phase) true)).followedBy copyPhase).followedBy (eachStride layer)
+
+/-- The stage counter lives on four bit stacks. Only the finite layer
+control is incorporated into the surrounding transition table. -/
+def program : FiniteRoutine (Port K) :=
+ .ofRoutine (popLoop (.inl .remaining) (fun _ => true) (halt false) (phaseBody layer).body)
+
+variable {X : Type*} {b : ℕ} (view : X → Stacks K) (next : X → Stage b → X) (limit : ℕ)
+
+/-- The callback updates its data and preserves the phase and stride ports. -/
+def LayerRuns : Prop :=
+ ∀ (s : Stage b) (left : ℕ) (x : X), ∃ t ≤ limit,
+ layer.Runs t (bank (view x) left s.phase s.stride) (bank (view (next x s)) left s.phase s.stride)
+
+private theorem strides_run (h : LayerRuns layer view next limit) (a left : ℕ) (ha : a ≤ b)
+ (k : ℕ) (hk : k ≤ a) (x : X) :
+ ∃ t ≤ k*(limit+1)+1, (eachStride layer).Runs t (bank (view x) left a k)
+ (bank (view ((strides b a ha k hk).foldl next x)) left a 0) := by
+ induction k generalizing x with
+ | zero =>
+ simp only [strides, List.foldl_nil, eachStride, FiniteRoutine.Runs, FiniteRoutine.ofRoutine]
+ exact ⟨1, by simp, Runs.popLoop_empty (Sum.inl Control.stride) (fun _ => true) (halt false) layer.body
+ (s := bank (view x) left a 0) rfl⟩
+ | succ k ih =>
+ let s : Stage b := ⟨a, k, hk, ha⟩
+ obtain ⟨u, hu, hc⟩ := h s left x
+ obtain ⟨t, ht, htail⟩ := ih (by omega) (next x s)
+ simp only [eachStride, FiniteRoutine.Runs, FiniteRoutine.ofRoutine] at htail
+ have hh : (bank (view x) left a (k+1)) (.inl .stride) = true :: List.replicate k true := List.replicate_succ
+ have run := Runs.popLoop_true_continue (Sum.inl Control.stride) (fun _ => true) (halt false) layer.body hh rfl
+ (by rw [change_stride]; exact hc) htail
+ refine ⟨_, ?_, run⟩
+ rw [Nat.succ_mul]
+ omega
+
+private theorem phase_run (h : LayerRuns layer view next limit) (a left : ℕ) (ha : a+1 ≤ b) (x : X) :
+ ∃ t ≤ 1 + (5*(a+1)+2) + ((a+1)*(limit+1)+1),
+ (phaseBody layer).Runs t (bank (view x) left a 0)
+ (bank (view ((strides b (a+1) ha (a+1) le_rfl).foldl next x)) left (a+1) 0) := by
+ obtain ⟨t, ht, hh⟩ := strides_run layer view next limit h (a+1) left ha (a+1) le_rfl x
+ have inc : (FiniteRoutine.ofRoutine (push (.inl Control.phase) true)).Runs 1
+ (bank (view x) left a 0) (bank (view x) left (a+1) 0) := incPhase_run ..
+ exact ⟨_, by omega, (inc.followedBy (copyPhase_run (view x) left (a+1))).followedBy hh⟩
+
+private theorem remaining_run (h : LayerRuns layer view next limit) (x : X) (left a : ℕ) (htotal : a+left=b) :
+ ∃ t ≤ left*((limit+6)*b+5)+1,
+ (program layer).Runs t (bank (view ((phases b a (by omega)).foldl next x)) left a 0)
+ (bank (view ((phases b b le_rfl).foldl next x)) 0 b 0) := by
+ induction left generalizing a with
+ | zero =>
+ simp only [Nat.add_zero] at htotal
+ subst b
+ exact ⟨1, by simp, Runs.popLoop_empty (Sum.inl Control.remaining) (fun _ => true) (halt false)
+ (phaseBody layer).body (s := bank (view ((phases a a le_rfl).foldl next x)) 0 a 0) rfl⟩
+ | succ left ih =>
+ let y := (phases b a (by omega)).foldl next x
+ obtain ⟨u, hu, hc⟩ := phase_run layer view next limit h a left (by omega) y
+ obtain ⟨t, ht, tail⟩ := ih (a+1) (by omega)
+ simp only [program, FiniteRoutine.Runs, FiniteRoutine.ofRoutine] at tail
+ have hs : (phases b (a+1) (by omega)).foldl next x = (strides b (a+1) (by omega) (a+1) le_rfl).foldl next y := by rw [phases, List.foldl_append]
+ rw [hs] at tail
+ have hh : bank (view y) (left+1) a 0 (.inl .remaining) = true :: List.replicate left true := List.replicate_succ
+ have run := Runs.popLoop_true_continue (Sum.inl Control.remaining) (fun _ => true) (halt false)
+ (phaseBody layer).body hh rfl (by rw [change_left]; exact hc) tail
+ refine ⟨_, ?_, run⟩
+ have hbound : 1+(1+(5*(a+1)+2)+((a+1)*(limit+1)+1)) ≤ (limit+6)*b+5 := calc
+ _ = (limit+6)*(a+1)+5 := by ring
+ _ ≤ _ := by gcongr; omega
+ rw [Nat.succ_mul]
+ omega
+
+/-- From the initial unary global width, run every prescribed layer once
+in chronological order. No address-width-dependent transition table is used. -/
+theorem runs (h : LayerRuns layer view next limit) (x : X) :
+ ∃ t ≤ b*((limit+6)*b+5)+1,
+ (program layer).Runs t (bank (view x) b 0 0)
+ (bank (view ((phases b b le_rfl).foldl next x)) 0 b 0) :=
+ remaining_run layer view next limit h x b 0 (by omega)
+
+
+/-- A bounded execution of each callback on the successive actual buffers.
+This version permits callbacks whose run depends on having the appropriate
+send and receive blocks at the front of the stream. -/
+inductive Visits {b : ℕ} (layer : FiniteRoutine (Port K)) (limit : ℕ) :
+ List (Stage b) → Stacks K → Stacks K → Prop
+ | nil (x) : Visits layer limit [] x x
+ | cons {s ss x y z t} (ht : t ≤ limit)
+ (run : layer.Runs t (bank x (b-s.phase) s.phase s.stride) (bank y (b-s.phase) s.phase s.stride))
+ (rest : Visits layer limit ss y z) : Visits layer limit (s::ss) x z
+
+private theorem Visits.split {b : ℕ} {layer : FiniteRoutine (Port K)} {limit : ℕ}
+ (ls rs : List (Stage b)) {x z : Stacks K} (h : Visits layer limit (ls++rs) x z) :
+ ∃ y, Visits layer limit ls x y ∧ Visits layer limit rs y z := by
+ induction ls generalizing x with
+ | nil => exact ⟨x, .nil _, h⟩
+ | cons s ss ih =>
+ cases h with
+ | cons ht run rest =>
+ obtain ⟨y, first, tail⟩ := ih rest
+ exact ⟨y, .cons ht run first, tail⟩
+
+private theorem traceStrides {b limit : ℕ} (a : ℕ) (ha : a ≤ b) (k : ℕ) (hk : k ≤ a)
+ {x z : Stacks K} (h : Visits layer limit (strides b a ha k hk) x z) :
+ ∃ t ≤ k*(limit+1)+1, (eachStride layer).Runs t (bank x (b-a) a k) (bank z (b-a) a 0) := by
+ induction k generalizing x with
+ | zero =>
+ cases h
+ exact ⟨1, by simp, Runs.popLoop_empty (Sum.inl Control.stride) (fun _ => true) (halt false) layer.body
+ (s := bank z (b-a) a 0) rfl⟩
+ | succ k ih =>
+ cases h with
+ | @cons _ _ _ y _ u hu hc rest =>
+ obtain ⟨t, ht, tail⟩ := ih (by omega) rest
+ simp only [eachStride, FiniteRoutine.Runs, FiniteRoutine.ofRoutine] at tail
+ have hh : bank x (b-a) a (k+1) (.inl .stride) = true :: List.replicate k true := List.replicate_succ
+ have run := Runs.popLoop_true_continue (Sum.inl Control.stride) (fun _ => true) (halt false) layer.body hh rfl
+ (by rw [change_stride]; exact hc) tail
+ refine ⟨_, ?_, run⟩
+ rw [Nat.succ_mul]
+ omega
+
+/-- The unvisited phase suffix after finishing phase `a`. -/
+private def future (b a : ℕ) : (k : ℕ) → a+k ≤ b → List (Stage b)
+ | 0, _ => []
+ | k+1, h =>
+ strides b (a+1) (by omega) (a+1) le_rfl ++ future b (a+1) k (by omega)
+
+private theorem phases_future (b a k : ℕ) (h : a+k ≤ b) :
+ phases b a (by omega) ++ future b a k h = phases b (a+k) h := by
+ induction k generalizing a with
+ | zero => simp [future]
+ | succ k ih =>
+ rw [future, ← List.append_assoc, ← phases]
+ simpa only [Nat.add_assoc, Nat.add_comm 1 k] using ih (a+1) (by omega)
+
+private theorem traceFuture {b limit : ℕ} (a k : ℕ) (hk : a+k=b) {x z : Stacks K}
+ (h : Visits layer limit (future b a k hk.le) x z) :
+ ∃ t ≤ k*((limit+6)*b+5)+1, (program layer).Runs t (bank x k a 0) (bank z 0 b 0) := by
+ induction k generalizing a x with
+ | zero =>
+ cases h
+ simp only [Nat.add_zero] at hk
+ subst b
+ exact ⟨1, by simp, Runs.popLoop_empty (Sum.inl Control.remaining) (fun _ => true) (halt false)
+ (phaseBody layer).body (s := bank z 0 a 0) rfl⟩
+ | succ k ih =>
+ rw [future] at h
+ obtain ⟨y, first, rest⟩ := h.split _ _
+ obtain ⟨t, ht, hstr⟩ := traceStrides layer (a+1) (by omega) (a+1) le_rfl first
+ rw [show b-(a+1)=k by omega] at hstr
+ have inc : (FiniteRoutine.ofRoutine (push (.inl Control.phase) true)).Runs 1
+ (bank x k a 0) (bank x k (a+1) 0) := incPhase_run ..
+ have body := (inc.followedBy (copyPhase_run x k (a+1))).followedBy hstr
+ obtain ⟨v, hv, tail⟩ := ih (a+1) (by omega) rest
+ simp only [program, FiniteRoutine.Runs, FiniteRoutine.ofRoutine] at tail
+ have hh : bank x (k+1) a 0 (.inl .remaining) = true :: List.replicate k true := List.replicate_succ
+ have run := Runs.popLoop_true_continue (Sum.inl Control.remaining) (fun _ => true) (halt false)
+ (phaseBody layer).body hh rfl (by rw [change_left]; exact body) tail
+ refine ⟨_, ?_, run⟩
+ have hbound : 1+(1+(5*(a+1)+2)+((a+1)*(limit+1)+1)) ≤ (limit+6)*b+5 := calc
+ _ = (limit+6)*(a+1)+5 := by ring
+ _ ≤ _ := by gcongr; omega
+ rw [Nat.succ_mul k]
+ omega
+
+/-- Each callback need only run on the state it actually receives. -/
+theorem runs_of_visits {b limit : ℕ} {x z : Stacks K} (h : Visits layer limit (phases b b le_rfl) x z) :
+ ∃ t ≤ b*((limit+6)*b+5)+1, (program layer).Runs t (bank x b 0 0) (bank z 0 b 0) := by
+ have eq : future b 0 b (by omega) = phases b b le_rfl := by
+ simpa only [phases, List.nil_append, Nat.zero_add] using phases_future b 0 b (by omega)
+ apply traceFuture layer 0 b (by omega)
+ rwa [eq]
+
+
+/-- Compose stage computations that consume a chronological suffix of the
+incident stream. Local stages take an empty prefix. The final stage returns
+whatever tail the caller placed after the sorting fields. -/
+theorem Visits.of_stream {b limit : ℕ} (layer : FiniteRoutine (Port K)) {A : Type*}
+ (data : A → List Bool → Stacks K) (update : A → Stage b → A) (field : Stage b → List Bool)
+ (one : ∀ (x : A) (s : Stage b) (tail : List Bool), ∃ t ≤ limit,
+ layer.Runs t (bank (data x (field s ++ tail)) (b-s.phase) s.phase s.stride)
+ (bank (data (update x s) tail) (b-s.phase) s.phase s.stride))
+ (ss : List (Stage b)) (x : A) (tail : List Bool) :
+ Visits layer limit ss (data x (ss.flatMap field ++ tail)) (data (ss.foldl update x) tail) := by
+ induction ss generalizing x with
+ | nil => exact .nil _
+ | cons s ss ih =>
+ obtain ⟨t, ht, h⟩ := one x s (ss.flatMap field ++ tail)
+ rw [List.flatMap_cons, List.append_assoc]
+ exact .cons ht h (ih (update x s))
+
+end RAMTape.SortSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortScheduleFields.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortScheduleFields.lean
new file mode 100644
index 0000000000..c1c632c8ad
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortScheduleFields.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.RAMSortCostLayout
+import OAI.Computability.VPVNP.RAMTapeSuccessorFields
+
+/-!
+# Streaming the physical exchange blocks in stage order
+
+Local strides leave the incident stream untouched. At every cross-site
+stride its next two whole blocks are the outgoing and incoming fields for
+that layer. Thus one forward pass over the stream implements the address
+formula of Lemma 10.1 without storing a numerical global wire address.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortSchedule
+
+open RAMSort RAMLayout
+
+/-- Physical layer number, present only for cross-site comparisons. -/
+def exchangeNumber {b : ℕ} (h : ℕ) (s : Stage b) : Option ℕ :=
+ if h ≤ s.stride then some (layerCount (s.phase-h-1) + (s.phase-s.stride-1)) else none
+
+theorem exchangeNumber_eq {h d : ℕ} (s : Stage (h+d)) (hc : h ≤ s.stride) :
+ exchangeNumber h s = some (((crossStageEquiv h d).symm ⟨s,hc⟩).ordinal.val) := by
+ simp [exchangeNumber, hc, crossStageEquiv, Layer.ordinal]
+
+private theorem strides_numbers {b : ℕ} (h a : ℕ) (ha : a ≤ b) (k : ℕ) (hk : k ≤ a) :
+ (strides b a ha k hk).filterMap (exchangeNumber h) =
+ List.range' (layerCount (a-h-1)+(a-k)) (k-h) := by
+ induction k with
+ | zero => simp [strides]
+ | succ k ih =>
+ rw [strides, List.filterMap_cons]
+ by_cases hc : h ≤ k
+ · have hcount : k+1-h = (k-h)+1 := by omega
+ have hpos : layerCount (a-h-1)+(a-(k+1))+1 = layerCount (a-h-1)+(a-k) := by omega
+ simp only [exchangeNumber, hc, ite_true, ih (by omega), hcount, List.range', hpos]
+ congr 2
+ · simp only [exchangeNumber, hc, ite_false, ih (by omega)]
+ rw [show k-h=0 by omega, show k+1-h=0 by omega]
+ rfl
+
+private theorem phases_numbers {b : ℕ} (h a : ℕ) (ha : a ≤ b) :
+ (phases b a ha).filterMap (exchangeNumber h) = List.range' 0 (layerCount (a-h)) := by
+ induction a with
+ | zero => simp [phases, layerCount]
+ | succ a ih =>
+ rw [phases, List.filterMap_append, ih, strides_numbers]
+ simp only [Nat.sub_self, Nat.add_zero]
+ by_cases hle : h ≤ a
+ · have he : a+1-h=(a-h)+1 := by omega
+ rw [he, Nat.add_sub_cancel]
+ have ht (v : ℕ) : layerCount (v+1) = layerCount v + (v+1) := by
+ rw [layerCount, layerCount, Nat.choose_succ_succ (v+1) 1, Nat.choose_one_right, Nat.add_comm]
+ rw [ht]
+ simpa only [Nat.zero_add] using
+ (List.range'_append_1 (s := 0) (m := layerCount (a-h)) (n := a-h+1))
+ · rw [show a+1-h=0 by omega, show a-h=0 by omega]
+ rfl
+
+/-- Reading two consecutive blocks per cross stride visits physical layer
+ordinals from zero up to the full incident width, in exactly that order. -/
+theorem exchangeNumbers (h d : ℕ) :
+ (phases (h+d) (h+d) le_rfl).filterMap (exchangeNumber h) = List.range (layerCount d) := by
+ simpa only [Nat.add_sub_cancel_left, List.range_eq_range'] using phases_numbers h (h+d) le_rfl
+
+/-- Concatenating the blocks in execution order gives the same input stream
+as iterating over their physical field indices. -/
+theorem exchangeStream (h d : ℕ) (field : ℕ → List Bool) :
+ ((phases (h+d) (h+d) le_rfl).filterMap (exchangeNumber h)).flatMap field =
+ (List.range (layerCount d)).flatMap field := by rw [exchangeNumbers]
+
+
+variable {d H w : ℕ}
+
+/-- The two contiguous directions reserved for a physical layer ordinal. -/
+def fieldPair (incident : Fin (width d H w) → Bool) (i : ℕ) : List Bool :=
+ if hi : i < layerCount d then
+ let layer := (layerEquiv d).symm ⟨i, hi⟩
+ (List.ofFn fun j : Fin (blockBits H w) => incident (offset d H w (.inr (layer, 0, j)))) ++
+ (List.ofFn fun j : Fin (blockBits H w) => incident (offset d H w (.inr (layer, 1, j))))
+ else []
+
+private theorem two_fields {n : ℕ} (f : Fin (2*n) → Bool) :
+ List.ofFn f = (List.ofFn fun j : Fin n => f (finProdFinEquiv (0, j))) ++
+ (List.ofFn fun j : Fin n => f (finProdFinEquiv (1, j))) := by
+ rw [SuccessorFields.raw_eq_flatten]
+ simp [List.ofFn_succ]
+
+private theorem ordinal_map {α : Type*} (f : ℕ → α) (n : ℕ) :
+ (List.ofFn fun i : Fin n => f i.val) = (List.range n).map f := by
+ apply List.ext_getElem (by simp)
+ intros
+ simp
+
+/-- The tape bytes consumed by the successor pass and by the chronological
+stage loop are exactly the supplied incident bit vector, including for
+arbitrary malformed record encodings. -/
+theorem incident_stream (h : ℕ) (incident : Fin (width d H w) → Bool) :
+ List.ofFn incident =
+ (List.ofFn fun j : Fin (8*w) => incident (offset d H w (.inl (0,j)))) ++
+ (List.ofFn fun j : Fin (8*w) => incident (offset d H w (.inl (1,j)))) ++
+ ((phases (h+d) (h+d) le_rfl).filterMap (exchangeNumber h)).flatMap (fieldPair incident) := by
+ rw [exchangeNumbers, List.flatMap_def, ← ordinal_map]
+ apply (List.ofFn_add (n := 2*(8*w)) (m := layerCount d * (2*blockBits H w)) (f := incident)).trans
+ congr 1
+ · exact two_fields _
+ · rw [SuccessorFields.raw_eq_flatten]
+ apply congrArg List.flatten
+ apply congrArg List.ofFn
+ funext i
+ rw [fieldPair, dite_eq_left i.isLt]
+ have he : layerEquiv d ((layerEquiv d).symm i) = i := Equiv.apply_symm_apply _ _
+ have pair (dir : Fin 2) (j : Fin (blockBits H w)) :
+ offset d H w (.inr ((layerEquiv d).symm i, dir, j)) =
+ Fin.natAdd (2*(8*w)) (finProdFinEquiv (i,finProdFinEquiv (dir,j))) := by
+ change Fin.natAdd _ (finProdFinEquiv (layerEquiv d ((layerEquiv d).symm i), _)) = _
+ rw [he]
+ simpa only [pair] using
+ (two_fields (fun j : Fin (2*blockBits H w) =>
+ incident (Fin.natAdd (2*(8*w)) (finProdFinEquiv (i,j)))))
+
+end RAMTape.SortSchedule
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortStages.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortStages.lean
new file mode 100644
index 0000000000..0f5a9fa6ef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortStages.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.RAMTapeSortClock
+import OAI.Computability.VPVNP.RAMTapeSortOneStage
+import OAI.Computability.VPVNP.RAMTapeSortReplay
+import OAI.Computability.VPVNP.RAMTapeSortStream
+
+/-!
+# Executable local sorting of the transcript records
+
+The nested stage and offset loops run on the literal site stacks. For every
+input bit vector, they consume exactly the suffix after the two successor
+fields, materialize the selected block and retain every validity flag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortStages
+
+open BurstRAM RAMSort RAMLayout RAMBoundary
+
+/-- Registers for the phase and stride scheduler together with the registers used by each
+sorting layer. -/
+abbrev Port := SortSchedule.Port SortOneStage.Port
+
+/-- Run the finite bitonic sorting schedule with the physical single-layer routine at every
+stage. -/
+def program : FiniteRoutine Port := SortSchedule.program SortOneStage.layer
+
+variable {h d H w : ℕ}
+
+/-- State between stages, with the actual remaining incident stream. -/
+def data (v : Word d) (x : SortReplay.State h w) (stream : List Bool) : Stacks SortOneStage.Port :=
+ SortOneStage.data v w h x.1 stream x.2
+
+/-- Fold the site replay update over all bitonic stages on the combined row and site address
+bits. -/
+def result (raw : ℕ → Bool) (v : Word d) (x : SortReplay.State h w) : SortReplay.State h w :=
+ (phases (h+d) (h+d) le_rfl).foldl (SortReplay.update raw v) x
+
+private theorem flags_step (raw : ℕ → Bool) (v : Word d) (x : SortReplay.State h w) (s : Stage (h+d)) :
+ (SortReplay.update raw v x s).2.length ≤ x.2.length + 2*2^h := by
+ have bound (ls : List (List Bool)) (each : ∀ l ∈ ls, l.length ≤ 2) :
+ ls.flatten.length ≤ 2*ls.length := by
+ induction ls with
+ | nil => rfl
+ | cons y ys ih =>
+ have hy := each y (by simp)
+ have ht := ih (fun z hz => each z (List.mem_cons_of_mem _ hz))
+ simp only [List.flatten_cons, List.length_append, List.length_cons, Nat.mul_succ]
+ omega
+ let flags := SortLayerRows.checks s x.1 (SortReplay.fieldWords w raw s 0) (SortReplay.fieldWords w raw s 1)
+ have each (i) : (flags i).length ≤ 2 := by
+ simp only [flags, SortLayerRows.checks]; split <;> simp
+ have hh := bound (List.ofFn flags).reverse (by
+ intro l hl
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp (List.mem_reverse.mp hl)
+ exact each i)
+ simp only [List.length_reverse, List.length_ofFn] at hh
+ change ((List.ofFn flags).reverse.flatten ++ x.2).length ≤ _
+ rw [List.length_append]
+ omega
+
+theorem result_flags_length (raw : ℕ → Bool) (v : Word d) (x : SortReplay.State h w) :
+ (result raw v x).2.length ≤ x.2.length + 2*2^h*((h+d+1).choose 2) := by
+ have aux (ss : List (Stage (h+d))) (y : SortReplay.State h w) :
+ (ss.foldl (SortReplay.update raw v) y).2.length ≤ y.2.length + 2*2^h*ss.length := by
+ induction ss generalizing y with
+ | nil => simp
+ | cons s ss ih =>
+ have hs := flags_step raw v y s
+ have ht := ih (SortReplay.update raw v y s)
+ simp only [List.foldl_cons, List.length_cons, Nat.mul_succ]
+ omega
+ simpa only [result, length_phases] using aux (phases (h+d) (h+d) le_rfl) x
+
+/-- Every finite stage callback returns on every raw slot and field value.
+Only the public stream lengths enter the clock. -/
+theorem run_incident (hw : 2 ≤ w) (hslots : 2^h = 4*H) (incident : Fin (width d H w) → Bool)
+ (raw : ℕ → Bool) (hraw : ∀ k : Fin (width d H w), raw k.val = incident k)
+ (v : Word d) (x : SortReplay.State h w) :
+ ∃ t ≤ ticks h d w, program.Runs t
+ (SortSchedule.bank (data v x ((List.ofFn incident).drop (16*w))) (h+d) 0 0)
+ (SortSchedule.bank (data v (result raw v x) []) 0 (h+d) 0) := by
+ have one (y : SortReplay.State h w) (s : Stage (h+d)) (tail : List Bool) :
+ ∃ t ≤ SortOneStage.budget h d w, SortOneStage.layer.Runs t
+ (SortSchedule.bank (data v y (SortStream.bytes w raw s ++ tail)) (h+d-s.phase) s.phase s.stride)
+ (SortSchedule.bank (data v (SortReplay.update raw v y s) tail) (h+d-s.phase) s.phase s.stride) := by
+ have eq : SortOneStage.stream s (SortReplay.fieldWords w raw s 0) (SortReplay.fieldWords w raw s 1) tail =
+ SortStream.bytes w raw s ++ tail := by
+ by_cases hl : s.stride < h <;> simp [SortOneStage.stream, SortStream.bytes, hl, List.append_assoc]
+ obtain ⟨t, ht, hr⟩ := SortOneStage.runs hw s v (h+d-s.phase) y.1
+ (SortReplay.fieldWords w raw s 0) (SortReplay.fieldWords w raw s 1) tail y.2
+ rw [eq] at hr
+ exact ⟨t, ht, hr⟩
+ have trace := SortSchedule.Visits.of_stream SortOneStage.layer (data v) (SortReplay.update raw v)
+ (SortStream.bytes w raw) one (phases (h+d) (h+d) le_rfl) x []
+ simp only [List.append_nil] at trace
+ rw [SortStream.suffix hslots incident raw hraw]
+ exact SortSchedule.runs_of_visits SortOneStage.layer trace
+
+/-- The program returns the same decision as the word-level validator.
+On every accepted input it returns the same parsed block, including the
+final padded record used by the boundary pass. -/
+theorem run_checked (hw : 2 ≤ w) (hslots : 2^h = 4*H) (incident : Fin (width d H w) → Bool)
+ (raw : ℕ → Bool) (hraw : ∀ k : Fin (width d H w), raw k.val = incident k)
+ (v : Word d) (x : SortReplay.State h w) (hcanon : SortReplay.CanonicalBlock hw x.1) :
+ let ss := phases (h+d) (h+d) le_rfl
+ let scan := scanStages hw raw v ss (SortReplay.decoded hw x.1)
+ ∃ t ≤ ticks h d w, ∃ y : SortReplay.State h w, program.Runs t
+ (SortSchedule.bank (data v x ((List.ofFn incident).drop (16*w))) (h+d) 0 0)
+ (SortSchedule.bank (data v y []) 0 (h+d) 0) ∧
+ y.2.all id = (x.2.all id && scan.ok) ∧
+ (y.2.all id = true → SortReplay.CanonicalBlock hw y.1 ∧ SortReplay.decoded hw y.1 = scan.block) := by
+ obtain ⟨t, ht, hr⟩ := run_incident hw hslots incident raw hraw v x
+ exact ⟨t, ht, result raw v x, hr, SortReplay.fold_spec hw raw v _ x hcanon⟩
+
+
+/-- On the actual live processor input, the final flags check every sorting
+send and receive and the successful output is the typed validator's block. -/
+theorem run_messages {e : ℕ} (hw : 2 ≤ w) (hc : 2^d*2^e < 2^w)
+ (b : SendArrays d (2^e) w) (v : Word d) (x : SortReplay.State (2+e) w)
+ (hcanon : SortReplay.CanonicalBlock hw x.1) :
+ let incident := fun j => (incidentEquiv d (2^e) w b).val (v, (offset d (2^e) w).symm j)
+ let ss := phases ((2+e)+d) ((2+e)+d) le_rfl
+ let mem := (unpackMessages (parseMessages hw hc b)).memory
+ ∃ t ≤ ticks (2+e) d w, ∃ y : SortReplay.State (2+e) w, program.Runs t
+ (SortSchedule.bank (data v x ((List.ofFn incident).drop (16*w))) ((2+e)+d) 0 0)
+ (SortSchedule.bank (data v y []) 0 ((2+e)+d) 0) ∧
+ y.2.length ≤ x.2.length + 2*2^(2+e)*(((2+e)+d+1).choose 2) ∧
+ (y.2.all id = true ↔ x.2.all id = true ∧ SortCanonical hw hc b v ∧
+ RAMSort.checks v ss (physicalFieldsEquiv.{0,0} (2+e) d _ mem.sortSends) (SortReplay.decoded hw x.1)) ∧
+ (y.2.all id = true → (fun i => (parsedSlot hw (y.1 i)).record) =
+ outputAt mem v (SortReplay.decoded hw x.1)) := by
+ intro incident ss mem
+ have hraw (k : Fin (width d (2^e) w)) : sortIncident b v k.val = incident k := readIncident_at _ k
+ obtain ⟨t, ht, hr⟩ := run_incident hw (record_width e) incident (sortIncident b v) hraw v x
+ exact ⟨t, ht, result (sortIncident b v) v x, hr, result_flags_length _ _ _, SortReplay.fold_messages hw hc b v x hcanon,
+ SortReplay.fold_messages_output hw hc b v x hcanon⟩
+
+end RAMTape.SortStages
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortStartup.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortStartup.lean
new file mode 100644
index 0000000000..96b472784d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortStartup.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.RAMTapeCeilLog
+import OAI.Computability.VPVNP.RAMTapeSortOffsets
+import OAI.Computability.VPVNP.RAMTapeSortSchedule
+import OAI.Computability.VPVNP.RAMTapeValidatorSetup
+
+/-! # Preparing the bitonic sorter from the site's public registers
+
+The initialized site already holds its word width and its number of slots,
+`4H`, in unary. Copy the latter and halve the copy until only one mark remains.
+This writes the row width `h = log₂(4H)`. The phase loop receives `h+d` marks
+from the row and site widths. Both original dimensions remain available to the
+record reader, and the temporary stacks finish empty.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortStartup
+
+/-- Registers for the site address width, slot count, logarithm calculation, row width, and
+remaining phase count. -/
+inductive Port where | address | slots | copy | tmp | rowWidth | remaining
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+private abbrev marks (n : ℕ) := List.replicate n true
+
+private def counts (d N copy h rem : ℕ) : Tally.State Port
+ | .address => d
+ | .slots => N
+ | .copy => copy
+ | .rowWidth => h
+ | .remaining => rem
+ | .tmp => 0
+
+/-- Encode the supplied dimensions, working copy, row width, and remaining phase count as unary
+stacks. -/
+def bank (d N copy h rem : ℕ) : Stacks Port := Tally.encode (counts d N copy h rem)
+
+private def copyAdd (src dst : Port) : FiniteRoutine Port :=
+ FiniteRoutine.ofRoutine (Tally.copyAdd src dst Port.tmp)
+
+private def logPorts : CeilLog.Port → Port
+ | .src => .copy
+ | .tmp => .tmp
+ | .out => .rowWidth
+
+private def rowWidth : FiniteRoutine Port :=
+ FiniteRoutine.ofStackCode (CeilLog.code 1) logPorts .scan (· == .done)
+
+/-- A fixed control, with the slot count and both widths held on actual stacks. -/
+def routine : FiniteRoutine Port :=
+ (((copyAdd .slots .copy).followedBy rowWidth).followedBy
+ (copyAdd .rowWidth .remaining)).followedBy (copyAdd .address .remaining)
+
+/-- Number of startup steps for copying the slot count, computing its ceiling binary logarithm,
+and assembling the phase count. -/
+def cost (d N : ℕ) : ℕ := (5*N+2)+CeilLog.cost 1 N+(5*Nat.clog 2 N+2)+(5*d+2)
+
+private theorem logarithm_run (d N : ℕ) :
+ rowWidth.Runs (CeilLog.cost 1 N) (bank d N N 0 0) (bank d N 0 (Nat.clog 2 N) 0) := by
+ apply FiniteRoutine.runs_ofStackCode_framed
+ (by intro x y h; cases x <;> cases y <;> simp_all [logPorts]) rfl rfl
+ (fun q h => by simp only [beq_iff_eq] at h; subst q; rfl) (CeilLog.runs 1 N [])
+ · intro p; cases p <;> rfl
+ · intro p; cases p <;> simp [logPorts, bank, Tally.encode, counts, CeilLog.store]
+ · intro p hp; cases p <;> first | rfl | exact (hp .out rfl).elim | exact (hp .src rfl).elim
+
+/-- Only the two new output registers change, even for a non-power-of-two slot count. -/
+theorem runs (d N : ℕ) :
+ routine.Runs (cost d N) (bank d N 0 0 0) (bank d N 0 (Nat.clog 2 N) (Nat.clog 2 N+d)) := by
+ let h := Nat.clog 2 N
+ have c₁ := Tally.copyAdd_runs Port.slots .copy .tmp (by decide) (by decide) (by decide)
+ (counts d N 0 0 0) rfl
+ have c₂ := Tally.copyAdd_runs Port.rowWidth .remaining .tmp (by decide) (by decide) (by decide)
+ (counts d N 0 h 0) rfl
+ have c₃ := Tally.copyAdd_runs Port.address .remaining .tmp (by decide) (by decide) (by decide)
+ (counts d N 0 h h) rfl
+ have e₁ : Function.update (counts d N 0 0 0) .copy (0+N) = counts d N N 0 0 := by
+ funext p; cases p <;> simp [counts, Function.update]
+ have e₂ : Function.update (counts d N 0 h 0) .remaining (0+h) = counts d N 0 h h := by
+ funext p; cases p <;> simp [counts, Function.update]
+ have e₃ : Function.update (counts d N 0 h h) .remaining (h+d) = counts d N 0 h (h+d) := by
+ funext p; cases p <;> rfl
+ change (copyAdd .slots .copy).Runs (5*N+2) _ (Tally.encode (Function.update (counts d N 0 0 0) .copy (0+N))) at c₁
+ change (copyAdd .rowWidth .remaining).Runs (5*h+2) _ (Tally.encode (Function.update (counts d N 0 h 0) .remaining (0+h))) at c₂
+ change (copyAdd .address .remaining).Runs (5*d+2) _ (Tally.encode (Function.update (counts d N 0 h h) .remaining (h+d))) at c₃
+ rw [e₁] at c₁
+ rw [e₂] at c₂
+ rw [e₃] at c₃
+ exact ((c₁.followedBy (logarithm_run d N)).followedBy c₂).followedBy c₃
+
+theorem cost_le (d N : ℕ) : cost d N ≤ 43*N+5*d+39 := by
+ have hc := CeilLog.cost_le 1 N
+ have hw : Nat.clog 2 N ≤ N := Nat.clog_le_of_le_pow (Nat.lt_two_pow_self (n := N)).le
+ unfold cost
+ omega
+
+/-- A caller can map the output registers directly to the stage counter and the row
+enumerator. Every stack outside these two outputs is restored. -/
+theorem runs_framed {K : Type} [DecidableEq K] (ports : Port → K) (hp : Function.Injective ports)
+ (d N : ℕ) (s : Stacks K) (hin : ∀ p, s (ports p) = bank d N 0 0 0 p) :
+ (routine.onPorts ports).Runs (cost d N) s
+ (Function.update (Function.update s (ports .rowWidth) (marks (Nat.clog 2 N)))
+ (ports .remaining) (marks (Nat.clog 2 N+d))) := by
+ apply FiniteRoutine.runs_onPorts_framed _ hp (runs d N) hin
+ · intro p; cases p <;> simp [Function.update, hp.eq_iff, hin, bank, Tally.encode, counts, marks]
+ · intro k hk; simp [Function.update, Ne.symm (hk .rowWidth), Ne.symm (hk .remaining)]
+
+/-- Two temporary sorter startup stacks for the slot-count copy and the logarithm calculation. -/
+inductive Scratch where | copy | tmp
+ deriving DecidableEq
+
+instance : Fintype Scratch := derive_fintype% _
+
+/-- Combined register bank for schedule control, site setup, startup scratch, and sorting
+offsets. -/
+abbrev Registers := SortSchedule.Port ((SiteSetup.Port ⊕ Scratch) ⊕ SortOffsets.Port)
+set_option synthInstance.maxSize 1024
+
+/-- Embed a site setup register into the combined sorter register bank. -/
+def caller (p : SiteSetup.Port) : Registers := .inr (.inl (.inl p))
+
+/-- Wire each startup port to its address-width, slot-count, scratch, row-width, or schedule
+register. -/
+def ports : Port → Registers
+ | .address => caller (.inl InputReader.addressWidthPort)
+ | .slots => caller SiteSetup.slotsPort
+ | .rowWidth => .inr (.inr .width)
+ | .remaining => .inl .remaining
+ | .copy => .inr (.inl (.inr .copy))
+ | .tmp => .inr (.inl (.inr .tmp))
+
+private theorem ports_injective : Function.Injective ports := by
+ intro x y he
+ cases x <;> cases y <;> simp_all [ports, caller, SiteSetup.slotsPort]
+
+/-- Install the prepared site stacks in the idle sorter with the given row width and remaining
+phase count and zero phase and stride. -/
+def ready (s : Stacks SiteSetup.Port) (h rem : ℕ) : Stacks Registers :=
+ SortSchedule.bank (SortOffsets.idle (Sum.elim s (fun _ => [])) h) rem 0 0
+
+/-- Preserve all bit fields, including the staged records, word width, and slot count.
+Only the outer schedule and the inner row traversal receive new marks. -/
+theorem startup_runs (d e : ℕ) (s : Stacks SiteSetup.Port)
+ (hd : s (.inl InputReader.addressWidthPort) = marks d)
+ (hs : s SiteSetup.slotsPort = marks (4*2^e)) :
+ (routine.onPorts ports).Runs (cost d (4*2^e)) (ready s 0 0) (ready s (2+e) (2+e+d)) := by
+ have hpow : 4*2^e = 2^(2+e) := by rw [pow_add]; rfl
+ have hlog : Nat.clog 2 (4*2^e) = 2+e := hpow ▸ Nat.clog_pow 2 _ (by decide)
+ apply FiniteRoutine.runs_onPorts_framed _ ports_injective (runs d (4*2^e))
+ · intro p; cases p <;> first | rfl | exact hd | exact hs
+ · intro p; cases p <;> first | rfl | exact hd | exact hs | simp [ready, ports, SortSchedule.bank,
+ SortOffsets.idle, SortOffsets.store, SortOffsets.ones, bank, Tally.encode, counts, hlog]
+ · rintro (c | (p | r)) hout
+ · cases c <;> first | rfl | exact (hout .remaining rfl).elim
+ · rfl
+ · cases r <;> first | rfl | exact (hout .rowWidth rfl).elim
+
+/-- On the initialized physical site, the sorter sees the same word and slot dimensions
+as the record emitter, together with its own binary width and schedule length. -/
+theorem from_prepared (d e : ℕ) (s : Stacks InputReader.Registers)
+ (hd : s InputReader.addressWidthPort = marks d) :
+ let state := SiteSetup.prepared s d (2^e)
+ (routine.onPorts ports).Runs (cost d (4*2^e)) (ready state 0 0) (ready state (2+e) (2+e+d)) ∧
+ ready state (2+e) (2+e+d) (caller SiteSetup.wordPort) = marks ((d+10)^4) ∧
+ ready state (2+e) (2+e+d) (caller SiteSetup.slotsPort) = marks (4*2^e) :=
+ ⟨startup_runs d e _ hd rfl, rfl, rfl⟩
+
+end RAMTape.SortStartup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSortStream.lean b/lean/OAI/Computability/VPVNP/RAMTapeSortStream.lean
new file mode 100644
index 0000000000..eae809276d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSortStream.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.RAMTapeSortReplayFields
+
+/-! # The sorting suffix as a sequence of raw record blocks -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SortStream
+
+open RAMSort RAMLayout Boundary SortReplay
+
+variable {h d H w : ℕ}
+
+/-- Every nonlocal layer consumes its two blocks, in send/receive order.
+The addressed words are reconstructed directly from arbitrary incident bits. -/
+def bytes (w : ℕ) (raw : ℕ → Bool) (s : Stage (h+d)) : List Bool :=
+ if s.stride < h then [] else
+ blockBytes (List.ofFn (fieldWords w raw s 0)) ++ blockBytes (List.ofFn (fieldWords w raw s 1))
+
+private theorem chronological (hslots : 2^h = 4*H) (incident : Fin (width d H w) → Bool)
+ (raw : ℕ → Bool) (hraw : ∀ k : Fin (width d H w), raw k.val = incident k)
+ (ss : List (Stage (h+d))) :
+ (ss.filterMap (SortSchedule.exchangeNumber h)).flatMap (SortSchedule.fieldPair incident) =
+ ss.flatMap (bytes w raw) := by
+ induction ss with
+ | nil => rfl
+ | cons s ss ih =>
+ rw [List.filterMap_cons, List.flatMap_cons]
+ by_cases hj : s.stride < h
+ · rw [show SortSchedule.exchangeNumber h s = none by simp [SortSchedule.exchangeNumber, Nat.not_le_of_lt hj]]
+ simp only [bytes, hj, ite_true, List.nil_append, ih]
+ · have hc := Nat.le_of_not_gt hj
+ rw [SortSchedule.exchangeNumber_eq s hc]
+ simp only [List.flatMap_cons, ih, bytes, hj, ite_false]
+ rw [fieldPair_eq_blocks hslots incident raw hraw s hc]
+
+/-- Removing the two successor fields leaves precisely the stream on which
+the stage routine operates. This covers malformed tags and padding. -/
+theorem suffix (hslots : 2^h = 4*H) (incident : Fin (width d H w) → Bool)
+ (raw : ℕ → Bool) (hraw : ∀ k : Fin (width d H w), raw k.val = incident k) :
+ (List.ofFn incident).drop (16*w) = (phases (h+d) (h+d) le_rfl).flatMap (bytes w raw) := by
+ have h₁ := SuccessorFields.incident_prefix incident
+ have h₂ := SortSchedule.incident_stream h incident
+ rw [chronological hslots incident raw hraw] at h₂
+ exact List.append_cancel_left (h₁.symm.trans h₂)
+
+end RAMTape.SortStream
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSpace.lean b/lean/OAI/Computability/VPVNP/RAMTapeSpace.lean
new file mode 100644
index 0000000000..77ec57a060
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSpace.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.RAMTapeSpaceAccess
+import OAI.Computability.VPVNP.RAMTapeSpacePaths
+
+/-!
+# Space preservation by the two-tape stack compiler
+
+At every instruction boundary, the first head has moved left by the growth
+in the packed bank since initialization, and the scratch head has returned
+to its initial cell. An unfinished instruction can move either head by at
+most its own linear scan time. These bounds do not accumulate with the
+number of completed instructions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.StackCompiler
+
+open UniversalMachine Turing
+
+variable {k : ℕ} {Q : Type*}
+
+/-- Stack states on any branch starting from the specified initial bank. -/
+inductive Reach {K : Type*} [DecidableEq K] (code : StackCode K Q) (start : Q) (initial : Stacks K) :
+ Q → Stacks K → Prop
+ | initial : Reach code start initial start initial
+ | step {q s q' s'} : Reach code start initial q s → StackStep code q s q' s' →
+ Reach code start initial q' s'
+ | low {q s l h} : Reach code start initial q s → code q = .choose l h → Reach code start initial l s
+ | high {q s l h} : Reach code start initial q s → code q = .choose l h → Reach code start initial h s
+
+/-- Each tape head lies in the interval from minus the radius to plus the radius. -/
+def HeadBox (radius : ℕ) (dx dy : ℤ) : Prop :=
+ -(radius : ℤ) ≤ dx ∧ dx ≤ radius ∧ -(radius : ℤ) ≤ dy ∧ dy ≤ radius
+
+private theorem space_from {code : StackCode (Fin k) Q} {q₀ q : Q} {s₀ s : Stacks (Fin k)}
+ {M : ℕ} (bounded : ∀ ⦃q' s'⦄, Reach code q₀ s₀ q' s' → (packed s').length ≤ M)
+ (reach : Reach code q₀ s₀ q s) {n : ℕ} {dx dy : ℤ} {r x y}
+ (p : HeadPath (rows code) n dx dy (.ready q) (tapeList (packed s)) (tapeList []) r x y) :
+ HeadBox (7*M+4) ((packed s₀).length - (packed s).length + dx) dy := by
+ induction n using Nat.strong_induction_on generalizing q s dx dy r x y with
+ | h n ih =>
+ have hbase := bounded (.initial : Reach code q₀ s₀ q₀ s₀)
+ have hsize := bounded reach
+ have deterministic {q' s'} (step : StackStep code q s q' s') :
+ HeadBox (7*M+4) ((packed s₀).length - (packed s).length + dx) dy := by
+ obtain ⟨t, ht, hcost, travel⟩ := step_travel code step
+ by_cases hlen : t ≤ n
+ · obtain ⟨m, ex, ey, hm, hx, hy, tail⟩ := travel.suffix p hlen
+ have bound := ih m (by omega) (.step reach step) tail
+ have he : (packed s₀).length - (packed s).length + dx =
+ ((packed s₀).length : ℤ) - (packed s').length + ex := by omega
+ rwa [he, hy, Int.zero_add]
+ · have := p.range
+ unfold HeadBox
+ push_cast
+ omega
+ cases hc : code q with
+ | push i b q' => exact deterministic (.push hc)
+ | pop i f => exact deterministic (.pop hc)
+ | goto q' => exact deterministic (.goto hc)
+ | choose l h =>
+ cases p with
+ | nil =>
+ unfold HeadBox
+ push_cast
+ omega
+ | cons hp tail =>
+ simp only [rows, hc, Choices.contains] at hp
+ rcases hp with hp | hp
+ · cases hp
+ simpa only [delta_stay, update_stay, Int.zero_add] using
+ ih _ (Nat.lt_succ_self _) (.low reach hc) (by simpa only [update_stay] using tail)
+ · cases hp
+ simpa only [delta_stay, update_stay, Int.zero_add] using
+ ih _ (Nat.lt_succ_self _) (.high reach hc) (by simpa only [update_stay] using tail)
+ | halt b =>
+ cases p with
+ | nil =>
+ unfold HeadBox
+ push_cast
+ omega
+ | cons hp _ => simp [rows, hc, Choices.contains] at hp
+
+/-- On either tape every cell visited by every finite prefix lies within
+radius 7M+4 of the initial head, uniformly over the execution time. -/
+theorem headPath_space {code : StackCode (Fin k) Q} (start : Q) (s : Stacks (Fin k)) {M : ℕ}
+ (bounded : ∀ ⦃q' s'⦄, Reach code start s q' s' → (packed s').length ≤ M)
+ {n dx dy r x y}
+ (p : HeadPath (rows code) n dx dy (.ready start) (tapeList (packed s)) (tapeList []) r x y) :
+ HeadBox (7*M+4) dx dy := by
+ simpa using space_from bounded Reach.initial p
+
+end RAMTape.StackCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSpaceAccess.lean b/lean/OAI/Computability/VPVNP/RAMTapeSpaceAccess.lean
new file mode 100644
index 0000000000..3b80b16dd6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSpaceAccess.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.RAMTapeSpaceSeek
+import OAI.Computability.VPVNP.RAMTapeStackAccess
+
+/-!
+# Displacement for a packed stack instruction
+
+The seek and rewind cancel on each tape. The scratch head therefore returns
+to its original position. At the next instruction boundary the first head
+has moved left by one cell on a push, right by one on a successful pop, and
+zero cells on an empty pop or a jump.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.StackCompiler
+
+open UniversalMachine
+
+variable {k : ℕ} {Q : Type*} (code : StackCode (Fin k) Q)
+
+private theorem reachTravel (q : Q) (s : Stacks (Fin k)) (i : Fin k)
+ (h : ∀ a b, rows code (.ready q) a b = .one (.next (.seek q i.castSucc) a 0 b 0)) :
+ Travel (rows code) (3 * (fields (before s i)).length + 1)
+ (fields (before s i)).length (-2 * (fields (before s i)).length)
+ (.ready q) (tapeList (packed s)) (tapeList []) (.seek q 0)
+ (tapeList ((s i).map bit ++ 0 :: fields (later s i)))
+ (tapeList (scratch (fields (before s i)).reverse)) := by
+ have first := Travel.single (t := tapeList (packed s)) (u := tapeList []) (h _ _)
+ simp only [delta_stay, update_stay] at first
+ have seek := seek_travel code q (before s i) (by simp [length_before])
+ ((s i).map bit ++ 0 :: fields (later s i)) []
+ have hi : (⟨(before s i).length, by rw [length_before]; omega⟩ : Fin (k+1)) = i.castSucc :=
+ Fin.ext (length_before s i)
+ rw [hi, ← List.append_assoc, ← packed_split] at seek
+ simpa [scratch, Nat.add_comm] using first.trans seek
+
+private theorem pushTravel {q q' : Q} {i : Fin k} {b : Bool} (h : code q = .push i b q')
+ (s : Stacks (Fin k)) :
+ Travel (rows code) (6 * (fields (before s i)).length + 4) (-1) 0
+ (.ready q) (tapeList (packed s)) (tapeList [])
+ (.ready q') (tapeList (packed (Function.update s i (b :: s i)))) (tapeList []) := by
+ let pre := fields (before s i)
+ let data := (s i).map bit ++ 0 :: fields (later s i)
+ have reach := reachTravel code q s i (by simp [rows, h])
+ have push : Travel (rows code) 2 (-1) 0 (.seek q 0) (tapeList data) (tapeList (scratch pre.reverse))
+ (.restore q') (tapeList (bit b :: data)) (tapeList (scratch pre.reverse)) := by
+ apply Travel.cons (dx := 0) (dy := 0) (show rows code (.seek q 0) _ _ =
+ .one (.next (.pushing q' b) (tapeList data).head 1 (tapeList (scratch pre.reverse)).head 0)
+ by simp [rows, h])
+ simp only [left_for_push, update_stay]
+ apply Travel.cons (d := 0) (e := 0) (dx := 0) (dy := 0) rfl
+ simp only [replace_top, update_stay]
+ exact .nil ..
+ have run := (reach.trans push).trans (restore_travel code q' pre.reverse (bit b :: data))
+ simp only [List.length_reverse, List.reverse_reverse] at run
+ rw [packed_set, List.append_assoc, List.map_cons, List.cons_append]
+ convert run using 1 <;> dsimp [pre] <;> omega
+
+private theorem popTravel {q : Q} {i : Fin k} {f : Option Bool → Q} (h : code q = .pop i f)
+ (s : Stacks (Fin k)) :
+ Travel (rows code) (6 * (fields (before s i)).length + 3)
+ ((s i).length - ((s i).tail.length : ℤ)) 0
+ (.ready q) (tapeList (packed s)) (tapeList [])
+ (.ready (f (s i).head?)) (tapeList (packed (Function.update s i (s i).tail))) (tapeList []) := by
+ let pre := fields (before s i)
+ let suffix := 0 :: fields (later s i)
+ have reach := reachTravel code q s i (by simp [rows, h])
+ have pop : Travel (rows code) 1 ((s i).length - ((s i).tail.length : ℤ)) 0
+ (.seek q 0) (tapeList ((s i).map bit ++ suffix)) (tapeList (scratch pre.reverse))
+ (.restore (f (s i).head?)) (tapeList ((s i).tail.map bit ++ suffix)) (tapeList (scratch pre.reverse)) := by
+ cases hh : s i with
+ | nil =>
+ have step := Travel.single (code := rows code) (q := .seek q 0) (t := tapeList suffix)
+ (u := tapeList (scratch pre.reverse))
+ (show rows code (.seek q 0) _ _ = .one (.next (.restore (f none)) (tapeList suffix).head 0
+ (tapeList (scratch pre.reverse)).head 0) by simp [rows, h, suffix])
+ simpa using step
+ | cons b bs =>
+ have step := Travel.single (code := rows code) (q := .seek q 0)
+ (t := tapeList (bit b :: (bs.map bit ++ suffix))) (u := tapeList (scratch pre.reverse))
+ (show rows code (.seek q 0) _ _ = .one (.next (.restore (f (some b))) 0 2
+ (tapeList (scratch pre.reverse)).head 0) by cases b <;> simp [rows, h, bit])
+ simpa using step
+ have run := (reach.trans pop).trans (restore_travel code (f (s i).head?) pre.reverse ((s i).tail.map bit ++ suffix))
+ simp only [List.length_reverse, List.reverse_reverse] at run
+ rw [packed_set, List.append_assoc]
+ convert run using 1 <;> dsimp [pre] <;> omega
+
+/-- A deterministic stack instruction costs a positive number of transitions.
+At the next instruction boundary, growth of the packed bank gives the exact
+negative displacement of its head. -/
+theorem step_travel {s s' : Stacks (Fin k)} {q q' : Q} (h : StackStep code q s q' s') :
+ ∃ ticks, 0 < ticks ∧ ticks ≤ 6 * (packed s).length + 4 ∧
+ Travel (rows code) ticks ((packed s).length - ((packed s').length : ℤ)) 0
+ (.ready q) (tapeList (packed s)) (tapeList []) (.ready q') (tapeList (packed s')) (tapeList []) := by
+ have bound (i : Fin k) : (fields (before s i)).length ≤ (packed s).length := by
+ rw [packed_split s i]
+ simp
+ cases h with
+ | push h =>
+ rename_i i b
+ have hb := bound i
+ refine ⟨6 * (fields (before s i)).length + 4, by omega, ?_, ?_⟩
+ · exact Nat.add_le_add_right (Nat.mul_le_mul_left 6 hb) 4
+ · convert pushTravel code h s using 1
+ rw [packed_set, packed_split s i]
+ simp
+ | pop h =>
+ rename_i i f
+ have hb := bound i
+ refine ⟨6 * (fields (before s i)).length + 3, by omega, by omega, ?_⟩
+ convert popTravel code h s using 1
+ rw [packed_set, packed_split s i]
+ simp
+ | goto h =>
+ refine ⟨1, by decide, by omega, ?_⟩
+ have step := Travel.single (code := rows code) (q := .ready q) (t := tapeList (packed s)) (u := tapeList [])
+ (show rows code (.ready q) _ _ = .one (.next (.ready q') (tapeList (packed s)).head 0 (tapeList []).head 0)
+ by simp [rows, h])
+ simpa only [delta_stay, update_stay, sub_self] using step
+
+end RAMTape.StackCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSpaceLiteral.lean b/lean/OAI/Computability/VPVNP/RAMTapeSpaceLiteral.lean
new file mode 100644
index 0000000000..9fff4a88bf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSpaceLiteral.lean
@@ -0,0 +1,111 @@
+import OAI.Computability.VPVNP.RAMTapeSpacePaths
+import OAI.Computability.VPVNP.VerifierMachineSimulation
+
+/-!
+# Head displacement of a literal compiled table on a choice string
+
+A bit selecting an instruction contributes the two moves in that record.
+Rejection of an invalid choice and all padding after a halt leave both head
+positions fixed. The continuing records form a prefix of a path through the
+source control with exactly the displacement of the whole literal run.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+open UniversalMachine Turing
+
+/-- Read the moves of the instruction actually selected by a witness bit. -/
+def choiceMotion (p : Program) (c : Config p.extra) (bit : Bool) : ℤ × ℤ :=
+ if 2 ≤ c.state.val then
+ match chosenInstruction (branches p c) bit with
+ | none => (0, 0)
+ | some a => (moveDelta a.firstMove, moveDelta a.secondMove)
+ else (0, 0)
+
+/-- Sum the moves from the literal rows, evolving the same configuration as
+`acceptsChoices` on each bit. -/
+def choiceDisplacement (p : Program) : Config p.extra → List Bool → ℤ × ℤ
+ | _, [] => (0, 0)
+ | c, b :: bs => choiceMotion p c b + choiceDisplacement p (choiceStep p c b) bs
+
+private theorem halted_step (p : Program) (c : Config p.extra) (b : Bool) (h : c.state.val < 2) :
+ (choiceStep p c b).state.val < 2 := by
+ by_cases ha : c.state.val = 1
+ · cases b <;> simp [choiceStep, ha, reject]
+ · have hr : c.state.val = 0 := by omega
+ simp [choiceStep, hr]
+
+private theorem halted_displacement (p : Program) (c : Config p.extra) (bits : List Bool)
+ (h : c.state.val < 2) : choiceDisplacement p c bits = (0, 0) := by
+ induction bits generalizing c with
+ | nil => rfl
+ | cons b bs ih =>
+ rw [choiceDisplacement, ih _ (halted_step p c b h)]
+ simp [choiceMotion, Nat.not_le_of_lt h]
+
+variable {Q : Type*}
+
+private def selected (row : Choices Q) (bit : Bool) : Option (Command Q) :=
+ match row with
+ | .stop => none
+ | .one a => if bit then none else some a
+ | .two a b => some (if bit then b else a)
+
+private theorem contains_selected {row : Choices Q} {b : Bool} {a : Command Q} (h : selected row b = some a) :
+ row.contains a := by
+ cases row <;> cases b <;> simp_all [Choices.contains, selected]
+
+variable [Fintype Q]
+
+private theorem literal_selection (start : Q) (code : Control Q) (q : Q) (t u : Tape Symbol) (b : Bool) :
+ let c := running start q t u
+ let p := compile start code
+ let sel := selected (code q t.head u.head) b
+ choiceStep p c b = sel.elim (reject c) (fun a => advance c (instruction start a)) ∧
+ choiceMotion p c b = sel.elim (0, 0) (fun a =>
+ (moveDelta (instruction start a).firstMove, moveDelta (instruction start a).secondMove)) := by
+ dsimp only
+ have hr := running_state_ge_two start q t u
+ have ha : (running start q t u).state.val ≠ 1 := by omega
+ have hz : (running start q t u).state.val ≠ 0 := by omega
+ simp only [choiceStep, choiceMotion, hr, ha, hz, ite_true, ite_false, lookup]
+ cases code q t.head u.head <;> cases b <;> exact ⟨rfl, rfl⟩
+
+/-- Every prefix of padded witness bits has the net motion of a prefix of
+continuing source commands, even when a later witness bit invalidates it. -/
+theorem choiceDisplacement_path (start : Q) (code : Control Q) (q : Q) (t u : Tape Symbol)
+ (bits : List Bool) :
+ let d := choiceDisplacement (compile start code) (running start q t u) bits
+ ∃ n ≤ bits.length, ∃ r x y, HeadPath code n d.1 d.2 q t u r x y := by
+ induction bits generalizing q t u with
+ | nil => exact ⟨0, by simp, q, t, u, .nil ..⟩
+ | cons b bs ih =>
+ dsimp only
+ obtain ⟨hc, hm⟩ := literal_selection start code q t u b
+ rw [choiceDisplacement, hc, hm]
+ cases hs : selected (code q t.head u.head) b with
+ | none =>
+ simp only [Option.elim_none]
+ rw [halted_displacement _ _ _ (by simp [reject])]
+ exact ⟨0, by omega, q, t, u, .nil ..⟩
+ | some cmd =>
+ simp only [Option.elim_some]
+ cases cmd with
+ | halt accept =>
+ have hh : (advance (running start q t u) (instruction start (.halt accept))).state.val < 2 := by
+ cases accept <;> simp [advance, instruction]
+ rw [halted_displacement _ _ _ hh]
+ exact ⟨0, by omega, q, t, u, .nil ..⟩
+ | next v a d a' e =>
+ obtain ⟨n, hn, r, x, y, hp⟩ := ih v (updateTape t a d) (updateTape u a' e)
+ exact ⟨n+1, by simp; omega, r, x, y, .cons (contains_selected hs) hp⟩
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSpaceNamed.lean b/lean/OAI/Computability/VPVNP/RAMTapeSpaceNamed.lean
new file mode 100644
index 0000000000..eb9c2b1cac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSpaceNamed.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.RAMTapeNamed
+import OAI.Computability.VPVNP.RAMTapeSpace
+import OAI.Computability.VPVNP.RAMTapeSpaceLiteral
+import Mathlib.Algebra.BigOperators.Fin
+
+/-!
+# Reachable space of a named stack bank
+
+Installing a fixed bank of labeled stacks in the physical machine adds one
+spare empty port. The size of its packed tape is the number of separators
+plus the total bit count in the named stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.StackCompiler
+
+open UniversalMachine
+
+variable {K Q : Type*} [DecidableEq K] [Fintype K]
+
+private theorem unique_step {L : Type*} [DecidableEq L] {code : StackCode L Q} {q s a b u v}
+ (first : StackStep code q s a u) (second : StackStep code q s b v) : a = b ∧ u = v := by
+ cases first <;> cases second <;> simp_all
+
+private theorem reflect_step (input : K) (code : StackCode K Q) (base : Stacks (Fin (Fintype.card K+1)))
+ (q : Q) (s : Stacks K) {u t}
+ (h : StackStep (labeledCode input code) q (installStacks (labeledPort input) base s) u t) :
+ ∃ s', StackStep code q s u s' ∧ t = installStacks (labeledPort input) base s' := by
+ have lift {r s'} (small : StackStep code q s r s') :
+ ∃ s', StackStep code q s u s' ∧ t = installStacks (labeledPort input) base s' := by
+ have big := small.lift (target := labeledCode input code) (labeledPort input)
+ (labeledPort_injective input) id base (fun _ _ => rfl)
+ obtain ⟨he, ht⟩ := unique_step h big
+ exact ⟨s', he.symm ▸ small, ht⟩
+ cases hc : code q with
+ | push => exact lift (.push hc)
+ | pop => exact lift (.pop hc)
+ | goto => exact lift (.goto hc)
+ | choose | halt => cases h <;> simp_all [labeledCode]
+
+private theorem choice_of_labeled {input : K} {code : StackCode K Q} {q l h}
+ (hc : labeledCode input code q = .choose l h) : code q = .choose l h := by
+ cases hs : code q <;> simp_all [labeledCode]
+
+/-- All reachable numbered banks have a corresponding reachable named bank. -/
+theorem reflect_reach (input : K) (code : StackCode K Q) (start : Q) (s : Stacks K)
+ (base : Stacks (Fin (Fintype.card K+1))) {u t}
+ (h : Reach (labeledCode input code) start (installStacks (labeledPort input) base s) u t) :
+ ∃ s', Reach code start s u s' ∧ t = installStacks (labeledPort input) base s' := by
+ induction h with
+ | initial => exact ⟨s, .initial, rfl⟩
+ | step _ big ih =>
+ obtain ⟨s', small, rfl⟩ := ih
+ obtain ⟨t', hs, ht⟩ := reflect_step input code base _ s' big
+ exact ⟨t', .step small hs, ht⟩
+ | low _ ch ih =>
+ obtain ⟨s', small, ht⟩ := ih
+ exact ⟨s', .low small (choice_of_labeled ch), ht⟩
+ | high _ ch ih =>
+ obtain ⟨s', small, ht⟩ := ih
+ exact ⟨s', .high small (choice_of_labeled ch), ht⟩
+
+theorem packed_length {k : ℕ} (s : Stacks (Fin k)) :
+ (packed s).length = k + ∑ p, (s p).length := by
+ simp [packed, fields, List.length_flatMap, List.map_ofFn, List.sum_ofFn, Finset.sum_add_distrib, Nat.add_comm]
+
+/-- The one spare physical label is empty at initialization and stays empty. -/
+theorem installed_length (input : K) (raw : Word) (s : Stacks K) :
+ (packed (installStacks (labeledPort input) (inputStacks raw) s)).length =
+ (Fintype.card K+1) + ∑ p, (s p).length := by
+ classical
+ rw [packed_length]
+ congr 1
+ let ks := Finset.univ.image (labeledPort input)
+ have zero (i : Fin (Fintype.card K+1)) (hi : i ∉ ks) :
+ (installStacks (labeledPort input) (inputStacks raw) s i).length = 0 := by
+ have hn : ∀ p, labeledPort input p ≠ i := by simpa [ks] using hi
+ rw [installStacks_outside _ _ hn]
+ have h0 := hn input
+ simp [labeledPort] at h0
+ cases i using Fin.cases with
+ | zero => exact (h0 rfl).elim
+ | succ j => simp [inputStacks]
+ rw [← Finset.sum_subset (Finset.subset_univ ks) (fun i _ hi => zero i hi)]
+ rw [Finset.sum_image (labeledPort_injective input).injOn]
+ simp [installStacks_at (labeledPort_injective input)]
+
+/-- A size invariant on reachable named banks bounds every packed physical
+instruction boundary, starting on the raw input tape. -/
+theorem named_reach_packed_le (input : K) (code : StackCode K Q) (start : Q) (raw : Word) {M : ℕ}
+ (bounded : ∀ ⦃q s⦄, Reach code start (labeledInput input raw) q s →
+ Fintype.card K+1 + ∑ p, (s p).length ≤ M) {q t}
+ (h : Reach (labeledCode input code) start (inputStacks raw) q t) : (packed t).length ≤ M := by
+ have he : installStacks (labeledPort input) (inputStacks raw) (labeledInput input raw) = inputStacks raw := by
+ apply installStacks_eq (labeledPort_injective input)
+ intro p
+ by_cases hp : p = input <;> simp [hp, labeledPort, inputStacks, labeledInput]
+ rw [← he] at h
+ obtain ⟨s, hs, rfl⟩ := reflect_reach _ _ _ _ _ h
+ rw [installed_length]
+ exact bounded hs
+
+variable [Fintype Q]
+
+/-- The two literal table heads stay in a fixed interval for every prefix
+of witness bits, including padded execution after a halt. -/
+theorem input_space {k : ℕ} (code : StackCode (Fin (k+1)) Q) (start : Q) (raw : Word) {M : ℕ}
+ (bounded : ∀ ⦃q s⦄, Reach code start (inputStacks raw) q s → (packed s).length ≤ M)
+ (bits : List Bool) :
+ let d := choiceDisplacement (program code start) (initial (program code start) raw) bits
+ HeadBox (7*M+4) d.1 d.2 := by
+ rw [physical_initial]
+ obtain ⟨_, _, _, _, _, hp⟩ := choiceDisplacement_path (.ready start) (rows code) (.ready start)
+ (tapeList (packed (inputStacks raw))) (tapeList []) bits
+ exact headPath_space start (inputStacks raw) bounded hp
+
+/-- A bound on the total reachable bit count of the evaluator's named stack
+bank gives a time-independent space bound for the compiled universal program. -/
+theorem input_space_labeled (input : K) (code : StackCode K Q) (start : Q) (raw : Word) {M : ℕ}
+ (bounded : ∀ ⦃q s⦄, Reach code start (labeledInput input raw) q s →
+ Fintype.card K+1 + ∑ p, (s p).length ≤ M) (bits : List Bool) :
+ let program := labeledProgram input code start
+ let d := choiceDisplacement program (initial program raw) bits
+ HeadBox (7*M+4) d.1 d.2 :=
+ input_space (labeledCode input code) start raw (fun ⦃_ _⦄ h => named_reach_packed_le input code start raw bounded h) bits
+
+end RAMTape.StackCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSpacePaths.lean b/lean/OAI/Computability/VPVNP/RAMTapeSpacePaths.lean
new file mode 100644
index 0000000000..f937dd9d59
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSpacePaths.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.RAMTapeSpaceTravel
+
+/-!
+# Head positions along a branching physical execution
+
+A path can follow either occupied continuation slot. Its integer indices
+measure the total displacement on each tape; applying the displacement bound
+to every prefix bounds every cell visited.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+open UniversalMachine Turing
+
+variable {Q : Type*}
+
+/-- A command occupies one of the available continuation slots in a physical machine step. -/
+def Choices.contains (branches : Choices Q) (cmd : Command Q) : Prop :=
+ match branches with
+ | .stop => False
+ | .one a => a = cmd
+ | .two a b => a = cmd ∨ b = cmd
+
+/-- A prefix following actual continuing commands, with its physical
+head displacement on both tapes. -/
+inductive HeadPath (code : Control Q) :
+ ℕ → ℤ → ℤ → Q → Tape Symbol → Tape Symbol → Q → Tape Symbol → Tape Symbol → Prop
+ | nil (q t u) : HeadPath code 0 0 0 q t u q t u
+ | cons {q t u q' a d b e n dx dy r x y}
+ (h : (code q t.head u.head).contains (.next q' a d b e))
+ (tail : HeadPath code n dx dy q' (updateTape t a d) (updateTape u b e) r x y) :
+ HeadPath code (n+1) (moveDelta d + dx) (moveDelta e + dy) q t u r x y
+
+/-- Each instruction moves each head by at most one cell. -/
+theorem HeadPath.range {code : Control Q} {n dx dy q t u r x y}
+ (p : HeadPath code n dx dy q t u r x y) :
+ -(n : ℤ) ≤ dx ∧ dx ≤ n ∧ -(n : ℤ) ≤ dy ∧ dy ≤ n := by
+ induction p with
+ | nil => simp
+ | @cons _ _ _ _ _ d _ e _ _ _ _ _ _ _ _ ih =>
+ have := delta_range d
+ have := delta_range e
+ push_cast
+ omega
+
+/-- An execution that runs at least as long as a deterministic routine
+must follow that routine, leaving only its suffix and residual displacement. -/
+theorem Travel.suffix {code : Control Q} {m dx dy q t u r x y}
+ (run : Travel code m dx dy q t u r x y) {n ex ey v a b}
+ (walk : HeadPath code n ex ey q t u v a b) (hlen : m ≤ n) :
+ ∃ k wx wy, n = m + k ∧ ex = dx + wx ∧ ey = dy + wy ∧ HeadPath code k wx wy r x y v a b := by
+ induction run generalizing n ex ey with
+ | nil => exact ⟨n, ex, ey, by omega, by omega, by omega, walk⟩
+ | cons hr _ ih =>
+ cases walk with
+ | nil => omega
+ | cons hw tail =>
+ rw [hr] at hw
+ simp only [Choices.contains] at hw
+ cases hw
+ obtain ⟨k, wx, wy, hk, hx, hy, hs⟩ := ih tail (by omega)
+ exact ⟨k, wx, wy, by omega, by omega, by omega, hs⟩
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSpaceSeek.lean b/lean/OAI/Computability/VPVNP/RAMTapeSpaceSeek.lean
new file mode 100644
index 0000000000..b104b1b41e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSpaceSeek.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.VPVNP.RAMTapeSpaceTravel
+import OAI.Computability.VPVNP.RAMTapeStackControl
+
+/-!
+# Physical head displacement during a stack seek and rewind
+
+Passing a packed cell advances the first head by one and moves the second
+head left by two to store the cell and its tag. Restoring the cell reverses
+both movements. These counts include blank stack delimiters.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.StackCompiler
+
+open UniversalMachine
+
+variable {k : ℕ} {Q : Type*} (code : StackCode (Fin k) Q)
+
+private theorem scanCellTravel (q : Q) (i : Fin (k+1)) (hi : i.val ≠ 0) (x : Symbol)
+ (data saved : List Symbol) :
+ Travel (rows code) 3 1 (-2) (.seek q i) (tapeList (x :: data)) (tapeList (scratch saved))
+ (.seek q (remaining i x)) (tapeList data) (tapeList (scratch (x :: saved))) := by
+ apply Travel.cons (dx := 0) (dy := -1) (show rows code (.seek q i) (tapeList (x :: data)).head
+ (tapeList (scratch saved)).head = .one (.next (.stash q (remaining i x) x) 0 2
+ (tapeList (scratch saved)).head 1) by simp [rows, hi])
+ simp only [pop_cell, left_for_push]
+ apply Travel.cons (d := 0) (e := 1) (dx := 0) (dy := 0) rfl
+ simp only [update_stay, write_left]
+ apply Travel.cons (d := 0) (e := 0) (dx := 0) (dy := 0) rfl
+ simp only [update_stay, replace_top]
+ exact .nil ..
+
+private theorem scanFieldTravel (q : Q) (i : Fin (k+1)) (hi : i.val ≠ 0) (s : List Bool)
+ (data saved : List Symbol) :
+ Travel (rows code) (3 * (s.length + 1)) (s.length + 1) (-2 * (s.length + 1))
+ (.seek q i) (tapeList (s.map bit ++ 0 :: data)) (tapeList (scratch saved))
+ (.seek q (remaining i 0)) (tapeList data) (tapeList (scratch (0 :: (s.map bit).reverse ++ saved))) := by
+ induction s generalizing saved with
+ | nil => exact scanCellTravel code q i hi 0 data saved
+ | cons b s ih =>
+ have hcell := scanCellTravel code q i hi (bit b) (s.map bit ++ 0 :: data) saved
+ have hbit : remaining i (bit b) = i := by cases b <;> simp [bit, remaining]
+ rw [hbit] at hcell
+ have h := hcell.trans (ih (bit b :: saved))
+ convert h using 1 <;> simp [List.append_assoc] <;> omega
+
+/-- The seek moves one packed cell right and two scratch cells left for
+every cell of the prefix. -/
+theorem seek_travel (q : Q) (ss : List (List Bool)) (hs : ss.length ≤ k) (data saved : List Symbol) :
+ Travel (rows code) (3 * (fields ss).length) (fields ss).length (-2 * (fields ss).length)
+ (.seek q ⟨ss.length, by omega⟩) (tapeList (fields ss ++ data)) (tapeList (scratch saved))
+ (.seek q 0) (tapeList data) (tapeList (scratch ((fields ss).reverse ++ saved))) := by
+ induction ss generalizing saved with
+ | nil => exact .nil ..
+ | cons s ss ih =>
+ let i : Fin (k+1) := ⟨ss.length+1, by simp only [List.length_cons] at hs; omega⟩
+ have hr : remaining i 0 = ⟨ss.length, by simp at hs; omega⟩ := by
+ apply Fin.ext
+ simp [remaining, i]
+ have hfield := scanFieldTravel code q i (by simp [i]) s (fields ss ++ data) saved
+ rw [hr] at hfield
+ have htail := ih (by simp at hs; omega) (0 :: (s.map bit).reverse ++ saved)
+ convert hfield.trans htail using 1 <;> simp [List.append_assoc] <;> omega
+
+private theorem restoreCellTravel (q : Q) (x : Symbol) (xs data : List Symbol) :
+ Travel (rows code) 3 (-1) 2 (.restore q) (tapeList data) (tapeList (scratch (x :: xs)))
+ (.restore q) (tapeList (x :: data)) (tapeList (scratch xs)) := by
+ simp only [scratch, List.flatMap_cons, List.cons_append, List.nil_append]
+ apply Travel.cons (d := 0) (e := 2) (dx := -1) (dy := 1) rfl
+ simp only [update_stay, pop_cell]
+ apply Travel.cons (d := 1) (e := 2) (dx := 0) (dy := 0) rfl
+ simp only [left_for_push, pop_cell]
+ apply Travel.cons (d := 0) (e := 0) (dx := 0) (dy := 0) rfl
+ simp only [replace_top, update_stay, cells_head]
+ exact .nil ..
+
+/-- Rewind all saved cells to their original order, returning the scratch
+head to its original position. The final empty test moves neither head. -/
+theorem restore_travel (q : Q) (saved data : List Symbol) :
+ Travel (rows code) (3 * saved.length + 1) (- (saved.length : ℤ)) (2 * saved.length)
+ (.restore q) (tapeList data) (tapeList (scratch saved)) (.ready q)
+ (tapeList (saved.reverse ++ data)) (tapeList []) := by
+ induction saved generalizing data with
+ | nil =>
+ change Travel (rows code) 1 0 0 (.restore q) (tapeList data) (tapeList []) (.ready q) (tapeList data) (tapeList [])
+ apply Travel.cons (d := 0) (e := 0) (dx := 0) (dy := 0) rfl
+ rw [update_stay]
+ exact .nil ..
+ | cons x xs ih =>
+ have h := (restoreCellTravel code q x xs data).trans (ih (x :: data))
+ convert h using 1 <;> simp [List.append_assoc] <;> omega
+
+end RAMTape.StackCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSpaceTravel.lean b/lean/OAI/Computability/VPVNP/RAMTapeSpaceTravel.lean
new file mode 100644
index 0000000000..7f3c4aea8e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSpaceTravel.lean
@@ -0,0 +1,63 @@
+import OAI.Computability.VPVNP.RAMTapeRun
+
+/-!
+# Signed head displacement in a two-tape routine
+
+Positions on each bidirectional tape are measured from its initial head.
+The same transition that writes the symbol and moves the tape contributes
+one signed unit, or zero for a stationary head.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+open UniversalMachine Turing
+
+/-- Directions 0, 1 and 2 in a table row mean stay, left and right. -/
+def moveDelta (d : Fin 3) : ℤ := if d = 0 then 0 else if d = 1 then -1 else 1
+
+@[simp] theorem delta_stay : moveDelta 0 = 0 := rfl
+@[simp] theorem delta_left : moveDelta 1 = -1 := rfl
+@[simp] theorem delta_right : moveDelta 2 = 1 := rfl
+
+theorem delta_range (d : Fin 3) : -1 ≤ moveDelta d ∧ moveDelta d ≤ 1 := by
+ simp only [moveDelta]
+ split <;> first | decide | split <;> decide
+
+variable {Q : Type*}
+
+/-- A deterministic physical run with the two net head displacements. -/
+inductive Travel (code : Control Q) :
+ ℕ → ℤ → ℤ → Q → Tape Symbol → Tape Symbol → Q → Tape Symbol → Tape Symbol → Prop
+ | nil (q t u) : Travel code 0 0 0 q t u q t u
+ | cons {q t u q' a d b e n dx dy r x y}
+ (h : code q t.head u.head = .one (.next q' a d b e))
+ (tail : Travel code n dx dy q' (updateTape t a d) (updateTape u b e) r x y) :
+ Travel code (n+1) (moveDelta d + dx) (moveDelta e + dy) q t u r x y
+
+theorem Travel.single {code : Control Q} {q t u q' a d b e}
+ (h : code q t.head u.head = .one (.next q' a d b e)) :
+ Travel code 1 (moveDelta d) (moveDelta e) q t u q' (updateTape t a d) (updateTape u b e) := by
+ simpa using Travel.cons h (.nil ..)
+
+theorem Travel.trans {code : Control Q} {a b dx dy ex ey q t u q' x y r x' y'}
+ (h : Travel code a dx dy q t u q' x y) (g : Travel code b ex ey q' x y r x' y') :
+ Travel code (a+b) (dx+ex) (dy+ey) q t u r x' y' := by
+ induction h with
+ | nil => simpa using g
+ | cons hs _ ih => simpa [Nat.succ_add, Int.add_assoc] using Travel.cons hs (ih g)
+
+theorem Travel.runs {code : Control Q} {n dx dy q t u r x y}
+ (h : Travel code n dx dy q t u r x y) : Runs code n q t u r x y := by
+ induction h with
+ | nil => exact .nil ..
+ | cons hs _ ih => exact .cons hs ih
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeStackAccess.lean b/lean/OAI/Computability/VPVNP/RAMTapeStackAccess.lean
new file mode 100644
index 0000000000..674682360c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeStackAccess.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.RAMTapeStackScan
+
+/-!
+# A literal stack operation at any address
+
+The machine returns to the beginning of the packed stack bank with empty
+scratch. The exact cost depends on the number of preceding cells, not on
+the value stored in the addressed stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.StackCompiler
+
+open UniversalMachine
+
+variable {k : ℕ} {Q : Type*} (code : StackCode (Fin k) Q)
+
+/-- The primary tape's complete representation of a finite stack bank. -/
+def packed (s : Stacks (Fin k)) := fields (List.ofFn s)
+
+/-- Stack fields before the selected ordinal in the packed bank. -/
+def before (s : Stacks (Fin k)) (i : Fin k) := (List.ofFn s).take i.val
+/-- Stack fields after the selected ordinal in the packed bank. -/
+def later (s : Stacks (Fin k)) (i : Fin k) := (List.ofFn s).drop (i.val+1)
+
+theorem length_before (s : Stacks (Fin k)) (i : Fin k) : (before s i).length = i.val := by
+ simp [before]
+
+private theorem fields_append (ss tt : List (List Bool)) :
+ fields (ss ++ tt) = fields ss ++ fields tt := List.flatMap_append ..
+
+private theorem ofFn_set (s : Stacks (Fin k)) (i : Fin k) (a : List Bool) :
+ List.ofFn (Function.update s i a) = (List.ofFn s).set i.val a := by
+ apply List.ext_getElem (by simp)
+ intro j hj _
+ rw [List.getElem_ofFn, List.getElem_set]
+ by_cases he : i.val = j
+ · subst j
+ simp
+ · simp [he, Function.update_of_ne (show (⟨j, by simpa using hj⟩ : Fin k) ≠ i by
+ intro h; exact he (congrArg Fin.val h).symm)]
+
+theorem packed_set (s : Stacks (Fin k)) (i : Fin k) (a : List Bool) :
+ packed (Function.update s i a) = fields (before s i) ++ a.map bit ++ 0 :: fields (later s i) := by
+ simp only [packed, ofFn_set, List.set_eq_take_append_cons_drop, List.length_ofFn,
+ i.isLt, ↓reduceIte, fields_append, fields_cons, List.append_assoc, before, later]
+
+theorem packed_split (s : Stacks (Fin k)) (i : Fin k) :
+ packed s = fields (before s i) ++ (s i).map bit ++ 0 :: fields (later s i) := by
+ simpa using packed_set s i (s i)
+
+private theorem reach (q : Q) (s : Stacks (Fin k)) (i : Fin k)
+ (h : ∀ a b, rows code (.ready q) a b = .one (.next (.seek q i.castSucc) a 0 b 0)) :
+ Runs (rows code) (3 * (fields (before s i)).length + 1) (.ready q) (tapeList (packed s))
+ (tapeList []) (.seek q 0) (tapeList ((s i).map bit ++ 0 :: fields (later s i)))
+ (tapeList (scratch (fields (before s i)).reverse)) := by
+ apply Runs.cons (h _ _)
+ simp only [update_stay]
+ rw [packed_split s i, List.append_assoc]
+ have hp := seek_run code q (before s i) (by simp [length_before]) ((s i).map bit ++ 0 :: fields (later s i)) []
+ have hi : (⟨(before s i).length, by rw [length_before]; omega⟩ : Fin (k+1)) = i.castSucc :=
+ Fin.ext (length_before s i)
+ rw [hi] at hp
+ simpa [scratch] using hp
+
+theorem push_run {q q' : Q} {i : Fin k} {b : Bool} (h : code q = .push i b q')
+ (s : Stacks (Fin k)) :
+ Runs (rows code) (6 * (fields (before s i)).length + 4) (.ready q) (tapeList (packed s)) (tapeList [])
+ (.ready q') (tapeList (packed (Function.update s i (b :: s i)))) (tapeList []) := by
+ let pre := fields (before s i)
+ let data := (s i).map bit ++ 0 :: fields (later s i)
+ have hr := reach code q s i (by simp [rows, h])
+ have hp : Runs (rows code) 2 (.seek q 0) (tapeList data) (tapeList (scratch pre.reverse))
+ (.restore q') (tapeList (bit b :: data)) (tapeList (scratch pre.reverse)) := by
+ apply Runs.cons (show rows code (.seek q 0) _ _ = .one (.next (.pushing q' b) (tapeList data).head 1 (tapeList (scratch pre.reverse)).head 0)
+ by simp [rows, h])
+ simp only [left_for_push, update_stay]
+ apply Runs.cons rfl
+ simp only [replace_top, update_stay]
+ exact .nil ..
+ have hs := (hr.trans hp).trans (restore_run code q' pre.reverse (bit b :: data))
+ simp only [List.length_reverse, List.reverse_reverse] at hs
+ rw [packed_set, List.append_assoc, List.map_cons, List.cons_append]
+ convert hs using 1
+ dsimp [pre]
+ omega
+
+theorem pop_run {q : Q} {i : Fin k} {f : Option Bool → Q} (h : code q = .pop i f)
+ (s : Stacks (Fin k)) :
+ Runs (rows code) (6 * (fields (before s i)).length + 3) (.ready q) (tapeList (packed s)) (tapeList [])
+ (.ready (f (s i).head?)) (tapeList (packed (Function.update s i (s i).tail))) (tapeList []) := by
+ let pre := fields (before s i)
+ let suffix := 0 :: fields (later s i)
+ have hr := reach code q s i (by simp [rows, h])
+ have hp : Runs (rows code) 1 (.seek q 0) (tapeList ((s i).map bit ++ suffix))
+ (tapeList (scratch pre.reverse)) (.restore (f (s i).head?))
+ (tapeList ((s i).tail.map bit ++ suffix)) (tapeList (scratch pre.reverse)) := by
+ cases hh : s i with
+ | nil =>
+ have hs := Runs.single (code := rows code) (q := .seek q 0) (t := tapeList suffix)
+ (u := tapeList (scratch pre.reverse))
+ (show rows code (.seek q 0) _ _ = .one (.next (.restore (f none)) (tapeList suffix).head 0 (tapeList (scratch pre.reverse)).head 0) by simp [rows, h, suffix])
+ simpa [update_stay] using hs
+ | cons b bs =>
+ have hs := Runs.single (code := rows code) (q := .seek q 0)
+ (t := tapeList (bit b :: (bs.map bit ++ suffix))) (u := tapeList (scratch pre.reverse))
+ (show rows code (.seek q 0) _ _ = .one (.next (.restore (f (some b))) 0 2 (tapeList (scratch pre.reverse)).head 0)
+ by cases b <;> simp [rows, h, bit])
+ simpa [pop_cell, update_stay] using hs
+ have hs := (hr.trans hp).trans (restore_run code (f (s i).head?) pre.reverse ((s i).tail.map bit ++ suffix))
+ simp only [List.length_reverse, List.reverse_reverse] at hs
+ rw [packed_set, List.append_assoc]
+ convert hs using 1
+ dsimp [pre]
+ omega
+
+end RAMTape.StackCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeStackClock.lean b/lean/OAI/Computability/VPVNP/RAMTapeStackClock.lean
new file mode 100644
index 0000000000..8e2840052f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeStackClock.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.RAMTapeStackAccess
+
+/-!
+# Path counts and clock of the physical stack interpreter
+
+At most one packed cell is added by each stack instruction. Seeking and
+restoring any stack costs at most six transitions per preceding cell, plus
+four for dispatch and the operation itself. Every virtual choice is a
+single literal two-record row.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.StackCompiler
+
+open UniversalMachine
+
+variable {k : ℕ} {Q : Type*} (code : StackCode (Fin k) Q)
+
+private theorem before_le (s : Stacks (Fin k)) (i : Fin k) :
+ (fields (before s i)).length ≤ (packed s).length := by
+ rw [packed_split s i]
+ simp
+
+theorem step_size {s s' : Stacks (Fin k)} {q q' : Q} (h : StackStep code q s q' s') :
+ (packed s').length ≤ (packed s).length + 1 := by
+ cases h with
+ | goto => omega
+ | push =>
+ rename_i i b _
+ rw [packed_set, packed_split s i]
+ simp
+ omega
+ | pop =>
+ rename_i i _ _
+ rw [packed_set, packed_split s i]
+ simp
+ omega
+
+theorem step_run {s s' : Stacks (Fin k)} {q q' : Q} (h : StackStep code q s q' s') :
+ ∃ ticks ≤ 6*(packed s).length+4, Runs (rows code) ticks
+ (.ready q) (tapeList (packed s)) (tapeList []) (.ready q') (tapeList (packed s')) (tapeList []) := by
+ cases h with
+ | push h =>
+ exact ⟨_, Nat.add_le_add_right (Nat.mul_le_mul_left 6 (before_le ..)) _, push_run code h s⟩
+ | pop h =>
+ rename_i i f
+ have hb := before_le s i
+ exact ⟨_, by omega, pop_run code h s⟩
+ | goto h =>
+ refine ⟨1, by omega, ?_⟩
+ apply Runs.cons (show rows code (.ready q) _ _ =
+ .one (.next (.ready q') (tapeList (packed s)).head 0 (tapeList []).head 0) by simp [rows, h])
+ simp only [update_stay]
+ exact .nil ..
+
+variable [Fintype Q]
+
+/-- Accepting path count on the packed primary tape and initially empty scratch tape. -/
+noncomputable abbrev physical (start : Q) (ticks : ℕ) (q : Q) (s : Stacks (Fin k)) :=
+ count (.ready start) (rows code) ticks (.ready q) (tapeList (packed s)) (tapeList [])
+
+private theorem count_step (start : Q) {t B ticks : ℕ} {q s q' s'}
+ (h : StackStep code q s q' s') (hsize : (packed s).length+t+1 ≤ B)
+ (hclock : (t+1)*(6*B+4) ≤ ticks)
+ (ih : ∀ left, (packed s').length+t ≤ B → t*(6*B+4) ≤ left →
+ physical code start left q' s' = stackPaths code t q' s') :
+ physical code start ticks q s = stackPaths code t q' s' := by
+ obtain ⟨d, hd, run⟩ := step_run code h
+ have hg := step_size code h
+ have hb : d ≤ 6*B+4 := by omega
+ rw [Nat.succ_mul] at hclock
+ have he : ticks - d + d = ticks := by omega
+ have hr := run.count (.ready start) (ticks-d)
+ rw [he] at hr
+ exact hr.trans (ih _ (by omega) (by omega))
+
+/-- All virtual leaves have been reached by the indicated physical clock.
+This compares the actual integer path counts, with repeated targets counted
+once per incoming branch slot. -/
+theorem physical_eq (start : Q) (t : ℕ) (q : Q) (s : Stacks (Fin k)) (B ticks : ℕ)
+ (stops : StopsWithin code t q s) (hsize : (packed s).length+t ≤ B)
+ (hclock : t*(6*B+4) ≤ ticks) :
+ physical code start ticks q s = stackPaths code t q s := by
+ induction t generalizing q s ticks with
+ | zero => exact stops.elim
+ | succ t ih =>
+ cases h : code q with
+ | push i b r =>
+ simp only [StopsWithin, h] at stops
+ simp only [stackPaths, h]
+ exact count_step code start (.push h) (by omega) hclock (fun _ => ih _ _ _ stops)
+ | pop i f =>
+ simp only [StopsWithin, h] at stops
+ simp only [stackPaths, h]
+ exact count_step code start (.pop h) (by omega) hclock (fun _ => ih _ _ _ stops)
+ | goto r =>
+ simp only [StopsWithin, h] at stops
+ simp only [stackPaths, h]
+ exact count_step code start (.goto h) (by omega) hclock (fun _ => ih _ _ _ stops)
+ | choose low high =>
+ simp only [StopsWithin, h] at stops
+ rw [Nat.succ_mul] at hclock
+ obtain ⟨ticks, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : ticks ≠ 0)
+ change count _ _ (ticks+1) _ _ _ = _
+ rw [paths_step]
+ simp only [rows, h, after, update_stay, stackPaths]
+ exact congrArg₂ Nat.add (ih low s ticks stops.1 (by omega) (by omega))
+ (ih high s ticks stops.2 (by omega) (by omega))
+ | halt b =>
+ rw [Nat.succ_mul] at hclock
+ obtain ⟨ticks, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : ticks ≠ 0)
+ change count _ _ (ticks+1) _ _ _ = _
+ rw [paths_step]
+ simp only [rows, h, after, stackPaths]
+
+end RAMTape.StackCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeStackControl.lean b/lean/OAI/Computability/VPVNP/RAMTapeStackControl.lean
new file mode 100644
index 0000000000..c685b277c5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeStackControl.lean
@@ -0,0 +1,107 @@
+import OAI.Computability.VPVNP.RAMTapeRun
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Tactic.DeriveFintype
+import Mathlib.Data.Fintype.Sigma
+import Mathlib.Data.Fintype.Sum
+
+/-!
+# Two physical tapes for a fixed finite bank of bit stacks
+
+The first tape lists the stacks in order, each terminated by a blank.
+To reach stack `i`, move the preceding symbols onto the second tape. Each
+saved symbol gets a nonblank tag, so a stored delimiter is distinguishable
+from the empty scratch tape. A push or pop takes place at the exposed top.
+Then restore the saved prefix, clearing every scratch cell as it is consumed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.StackCompiler
+
+open UniversalMachine
+
+/-- Control states used to scan to one stack and restore the packed tape. -/
+inductive Phase (k : ℕ) (Q : Type*) where
+ | ready (q : Q)
+ | seek (q : Q) (remaining : Fin (k+1))
+ | stash (q : Q) (remaining : Fin (k+1)) (value : Symbol)
+ | tag (q : Q) (remaining : Fin (k+1))
+ | pushing (q : Q) (bit : Bool)
+ | restore (q : Q)
+ | value (q : Q)
+ | write (q : Q) (value : Symbol)
+ deriving Fintype
+
+/-- Encode a Boolean by one of the two nonblank tape symbols. -/
+def bit (b : Bool) : Symbol := if b then 2 else 1
+
+variable {k : ℕ} {Q : Type*}
+
+/-- Number of further stack separators to cross after reading this symbol. -/
+def remaining (i : Fin (k+1)) (x : Symbol) : Fin (k+1) :=
+ if x = 0 then ⟨i.val-1, by omega⟩ else i
+
+/-- The physical two-tape instructions implementing the given stack table. -/
+def rows (code : StackCode (Fin k) Q) : Control (Phase k Q)
+ | .ready q, x, y =>
+ match code q with
+ | .push i .. | .pop i .. => .one (.next (.seek q i.castSucc) x 0 y 0)
+ | .goto q' => .one (.next (.ready q') x 0 y 0)
+ | .choose low high => .two (.next (.ready low) x 0 y 0) (.next (.ready high) x 0 y 0)
+ | .halt b => .one (.halt b)
+ | .seek q i, x, y =>
+ if i.val = 0 then match code q with
+ | .push _ b q' => .one (.next (.pushing q' b) x 1 y 0)
+ | .pop _ f => if x = 0 then .one (.next (.restore (f none)) x 0 y 0)
+ else .one (.next (.restore (f (some (x = 2)))) 0 2 y 0)
+ | _ => .stop
+ else .one (.next (.stash q (remaining i x) x) 0 2 y 1)
+ | .stash q i x, a, _ => .one (.next (.tag q i) a 0 x 1)
+ | .tag q i, x, _ => .one (.next (.seek q i) x 0 2 0)
+ | .pushing q b, _, y => .one (.next (.restore q) (bit b) 0 y 0)
+ | .restore q, x, y => if y = 0 then .one (.next (.ready q) x 0 y 0)
+ else .one (.next (.value q) x 0 0 2)
+ | .value q, x, y => .one (.next (.write q y) x 1 0 2)
+ | .write q x, _, y => .one (.next (.restore q) x 0 y 0)
+
+/-- Store the nearest saved symbol first. -/
+def scratch (saved : List Symbol) : List Symbol :=
+ saved.flatMap fun x => [2, x]
+
+variable (code : StackCode (Fin k) Q)
+
+theorem restore_run (q : Q) (saved data : List Symbol) :
+ Runs (rows code) (3 * saved.length + 1) (.restore q) (tapeList data)
+ (tapeList (scratch saved)) (.ready q) (tapeList (saved.reverse ++ data)) (tapeList []) := by
+ induction saved generalizing data with
+ | nil =>
+ change Runs (rows code) 1 (.restore q) (tapeList data) (tapeList []) (.ready q) (tapeList data) (tapeList [])
+ apply Runs.cons rfl
+ rw [update_stay]
+ exact .nil ..
+ | cons x xs ih =>
+ have h := ih (x :: data)
+ simp only [scratch, List.flatMap_cons, List.cons_append, List.nil_append,
+ List.reverse_cons, List.append_assoc, List.length_cons, Nat.mul_succ] at *
+ rw [show 3 * xs.length + 3 + 1 = ((3 * xs.length + 1 + 1) + 1) + 1 by omega]
+ apply Runs.cons rfl
+ simp only [update_stay, pop_cell]
+ apply Runs.cons rfl
+ simp only [left_for_push, pop_cell]
+ apply Runs.cons rfl
+ simpa only [replace_top, update_stay, cells_head] using h
+
+/-- The byte stream of a block of consecutive stacks. -/
+def fields (ss : List (List Bool)) : List Symbol :=
+ ss.flatMap fun s => s.map bit ++ [0]
+
+@[simp] theorem fields_cons (s : List Bool) (ss : List (List Bool)) :
+ fields (s :: ss) = s.map bit ++ 0 :: fields ss := by simp [fields, List.append_assoc]
+
+end RAMTape.StackCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeStackLift.lean b/lean/OAI/Computability/VPVNP/RAMTapeStackLift.lean
new file mode 100644
index 0000000000..0cc5ff978c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeStackLift.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.RAMTapeStacks
+
+/-!
+# Installing a stack routine in a larger machine
+
+Stack labels may be renamed into any disjoint set of ports. Control labels
+may name states of the caller. Deterministic executions can be installed even
+when a terminal state of the subroutine is used as a continuation by the caller.
+Only the installed stacks can change during such an execution.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+variable {K L Q R : Type*}
+
+/-- Relabel the stack and control references of an instruction, preserving its operation and
+its halt verdict. -/
+@[simp] def StackOp.rename (ports : K → L) (labels : Q → R) : StackOp K Q → StackOp L R
+ | .push k b q => .push (ports k) b (labels q)
+ | .pop k f => .pop (ports k) (labels ∘ f)
+ | .goto q => .goto (labels q)
+ | .choose a b => .choose (labels a) (labels b)
+ | .halt b => .halt b
+
+/-- A source `halt` can be a return boundary for the linked machine. -/
+@[simp] def StackOp.returns : StackOp K Q → Bool
+ | .halt _ => true
+ | _ => false
+
+/-- Replace the stacks at installed ports and retain the ambient values at all
+other labels. The injection hypothesis is used in the restriction theorems. -/
+noncomputable def installStacks (ports : K → L) (base : Stacks L) (small : Stacks K) : Stacks L :=
+ fun l => open Classical in if h : ∃ k, ports k = l then small h.choose else base l
+
+@[simp] theorem installStacks_at {ports : K → L} (hp : Function.Injective ports)
+ (base : Stacks L) (small : Stacks K) (k : K) :
+ installStacks ports base small (ports k) = small k := by
+ unfold installStacks
+ split
+ · rename_i h
+ rw [hp h.choose_spec]
+ · rename_i h
+ exact (h ⟨k, rfl⟩).elim
+
+theorem installStacks_outside {ports : K → L} (base : Stacks L) (small : Stacks K) {l : L}
+ (hl : ∀ k, ports k ≠ l) : installStacks ports base small l = base l := by
+ simp [installStacks, not_exists.mpr hl]
+
+theorem installStacks_eq {ports : K → L} (hp : Function.Injective ports) (base : Stacks L)
+ (small : Stacks K) (he : ∀ k, base (ports k) = small k) :
+ installStacks ports base small = base := by
+ funext l
+ by_cases hm : ∃ k, ports k = l
+ · obtain ⟨k, rfl⟩ := hm
+ rw [installStacks_at hp, he]
+ · exact installStacks_outside _ _ (not_exists.mp hm)
+
+theorem installStacks_update [DecidableEq K] [DecidableEq L] {ports : K → L}
+ (hp : Function.Injective ports) (base : Stacks L) (small : Stacks K) (k : K) (v : List Bool) :
+ Function.update (installStacks ports base small) (ports k) v =
+ installStacks ports base (Function.update small k v) := by
+ funext l
+ by_cases hm : ∃ j, ports j = l
+ · obtain ⟨j, rfl⟩ := hm
+ by_cases hj : j = k
+ · subst j
+ simp [installStacks_at hp]
+ · simp [Function.update_of_ne (fun h => hj (hp h)), Function.update_of_ne hj, installStacks_at hp]
+ · have hl := not_exists.mp hm
+ rw [Function.update_of_ne (Ne.symm (hl k)), installStacks_outside _ _ hl,
+ installStacks_outside _ _ hl]
+
+variable [DecidableEq K] [DecidableEq L]
+
+/-- Lift one deterministic source instruction with exactly the same cost. -/
+theorem StackStep.lift {src : StackCode K Q} {target : StackCode L R} {q s q' s'}
+ (run : StackStep src q s q' s') (ports : K → L) (hp : Function.Injective ports) (labels : Q → R)
+ (base : Stacks L) (hc : ∀ u, (src u).returns = false → target (labels u) = (src u).rename ports labels) :
+ StackStep target (labels q) (installStacks ports base s) (labels q') (installStacks ports base s') := by
+ cases run with
+ | push h =>
+ have he := hc q (by simp [h])
+ rw [h, StackOp.rename] at he
+ simpa only [installStacks_at hp, installStacks_update hp] using
+ (StackStep.push (s := installStacks ports base s) he)
+ | pop h =>
+ have he := hc q (by simp [h])
+ rw [h, StackOp.rename] at he
+ simpa only [Function.comp_apply, installStacks_at hp, installStacks_update hp] using
+ (StackStep.pop (s := installStacks ports base s) he)
+ | goto h => exact .goto ((hc _ (by simp [h])).trans (by simp [h]))
+
+/-- Linking preserves each step and each ambient stack outside the routine.
+No control equality is required at the final state if it returns. -/
+theorem StackRuns.lift {src : StackCode K Q} {target : StackCode L R} {n q s q' s'}
+ (run : StackRuns src n q s q' s') (ports : K → L) (hp : Function.Injective ports) (labels : Q → R)
+ (base : Stacks L) (hc : ∀ u, (src u).returns = false → target (labels u) = (src u).rename ports labels) :
+ StackRuns target n (labels q) (installStacks ports base s) (labels q') (installStacks ports base s') := by
+ induction run with
+ | nil => exact .nil ..
+ | cons hs _ ih => exact .cons (hs.lift ports hp labels base hc) ih
+
+/-- If all rows, including halts and choices, are renamed, the bounded path
+counts agree on every installed stack. Control names need only agree on the
+states used by the source. -/
+theorem stackPaths_lift {src : StackCode K Q} {target : StackCode L R} (ports : K → L)
+ (hp : Function.Injective ports) (labels : Q → R) (base : Stacks L)
+ (hc : ∀ q, target (labels q) = (src q).rename ports labels) (n : ℕ) (q : Q) (s : Stacks K) :
+ stackPaths target n (labels q) (installStacks ports base s) = stackPaths src n q s := by
+ induction n generalizing q s with
+ | zero => rfl
+ | succ n ih =>
+ rw [stackPaths, hc, stackPaths]
+ cases src q <;> simp only [StackOp.rename, Function.comp_apply, installStacks_at hp,
+ installStacks_update hp, ih]
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeStackScan.lean b/lean/OAI/Computability/VPVNP/RAMTapeStackScan.lean
new file mode 100644
index 0000000000..f283a461fa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeStackScan.lean
@@ -0,0 +1,70 @@
+import OAI.Computability.VPVNP.RAMTapeStackControl
+
+/-!
+# Seeking an addressed bit stack
+
+The finite counter counts delimiters. Every saved cell, including an internal
+blank, takes exactly three physical transitions and two scratch cells.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.StackCompiler
+
+open UniversalMachine
+
+variable {k : ℕ} {Q : Type*} (code : StackCode (Fin k) Q)
+
+private theorem scan_cell (q : Q) (i : Fin (k+1)) (hi : i.val ≠ 0) (x : Symbol)
+ (data saved : List Symbol) :
+ Runs (rows code) 3 (.seek q i) (tapeList (x :: data)) (tapeList (scratch saved))
+ (.seek q (remaining i x)) (tapeList data) (tapeList (scratch (x :: saved))) := by
+ apply Runs.cons (show rows code (.seek q i) (tapeList (x :: data)).head
+ (tapeList (scratch saved)).head = .one (.next (.stash q (remaining i x) x) 0 2
+ (tapeList (scratch saved)).head 1) by simp [rows, hi])
+ simp only [pop_cell, left_for_push]
+ apply Runs.cons rfl
+ simp only [update_stay, write_left]
+ apply Runs.cons rfl
+ simp only [update_stay, replace_top]
+ exact .nil ..
+
+private theorem scan_field (q : Q) (i : Fin (k+1)) (hi : i.val ≠ 0) (s : List Bool)
+ (data saved : List Symbol) :
+ Runs (rows code) (3 * (s.length + 1)) (.seek q i) (tapeList (s.map bit ++ 0 :: data))
+ (tapeList (scratch saved)) (.seek q (remaining i 0)) (tapeList data)
+ (tapeList (scratch (0 :: (s.map bit).reverse ++ saved))) := by
+ induction s generalizing saved with
+ | nil => exact scan_cell code q i hi 0 data saved
+ | cons b s ih =>
+ have hcell := scan_cell code q i hi (bit b) (s.map bit ++ 0 :: data) saved
+ have hbit : remaining i (bit b) = i := by cases b <;> simp [bit, remaining]
+ rw [hbit] at hcell
+ have h := hcell.trans (ih (bit b :: saved))
+ simpa [Nat.mul_succ, Nat.add_comm, Nat.add_left_comm, List.append_assoc] using h
+
+/-- The target stack follows the explicitly listed prefix of stacks. -/
+theorem seek_run (q : Q) (ss : List (List Bool)) (hs : ss.length ≤ k) (data saved : List Symbol) :
+ Runs (rows code) (3 * (fields ss).length) (.seek q ⟨ss.length, by omega⟩)
+ (tapeList (fields ss ++ data)) (tapeList (scratch saved))
+ (.seek q 0) (tapeList data) (tapeList (scratch ((fields ss).reverse ++ saved))) := by
+ induction ss generalizing saved with
+ | nil => exact .nil ..
+ | cons s ss ih =>
+ let i : Fin (k+1) := ⟨ss.length+1, by simp only [List.length_cons] at hs; omega⟩
+ have hr : remaining i 0 = ⟨ss.length, by simp at hs; omega⟩ := by
+ apply Fin.ext
+ simp [remaining, i]
+ have hfield := scan_field code q i (by simp [i]) s (fields ss ++ data) saved
+ rw [hr] at hfield
+ have htail := ih (by simp at hs; omega) (0 :: (s.map bit).reverse ++ saved)
+ simpa [i, Nat.mul_add, Nat.mul_succ, List.append_assoc, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using
+ hfield.trans htail
+
+end RAMTape.StackCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeStacks.lean b/lean/OAI/Computability/VPVNP/RAMTapeStacks.lean
new file mode 100644
index 0000000000..e72e3554f5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeStacks.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.RAMTape
+
+/-!
+# Elementary bit-stack instructions
+
+A stack step changes at most one bit. All unbounded data belong to the stacks.
+The named control can inspect a popped bit, including the empty-stack case.
+Binary choices preserve their two branch slots.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+/-- One finite-control instruction acting on a named stack bank. -/
+inductive StackOp (K Q : Type*) where
+ | push (k : K) (b : Bool) (next : Q)
+ | pop (k : K) (next : Option Bool → Q)
+ | goto (next : Q)
+ | choose (low high : Q)
+ | halt (accept : Bool)
+
+/-- Instruction table for the bit-stack machine. -/
+abbrev StackCode (K Q : Type*) := Q → StackOp K Q
+/-- A bit list for each named stack, with its top at the head. -/
+abbrev Stacks (K : Type*) := K → List Bool
+
+variable {K Q : Type*} [DecidableEq K]
+
+/-- A single deterministic, continuing instruction. The stored pop
+continuation branches on its actual symbol. -/
+inductive StackStep (code : StackCode K Q) : Q → Stacks K → Q → Stacks K → Prop
+ | push {q s k b q'} (h : code q = .push k b q') :
+ StackStep code q s q' (Function.update s k (b :: s k))
+ | pop {q s k f} (h : code q = .pop k f) :
+ StackStep code q s (f (s k).head?) (Function.update s k (s k).tail)
+ | goto {q s q'} (h : code q = .goto q') : StackStep code q s q' s
+
+/-- A deterministic sequence of exactly the given number of stack instructions. -/
+inductive StackRuns (code : StackCode K Q) : ℕ → Q → Stacks K → Q → Stacks K → Prop
+ | nil (q s) : StackRuns code 0 q s q s
+ | cons {q s q' s' t u n} :
+ StackStep code q s q' s' → StackRuns code n q' s' t u →
+ StackRuns code (n + 1) q s t u
+
+theorem StackRuns.trans {code : StackCode K Q} {a b q s q' s' t u}
+ (h₁ : StackRuns code a q s q' s') (h₂ : StackRuns code b q' s' t u) :
+ StackRuns code (a + b) q s t u := by
+ induction h₁ with
+ | nil => simpa using h₂
+ | cons hs _ ih => simpa [Nat.succ_add] using StackRuns.cons hs (ih h₂)
+
+/-- Accepting leaf multiplicity up to a stack instruction bound. -/
+def stackPaths (code : StackCode K Q) : ℕ → Q → Stacks K → ℕ
+ | 0, _, _ => 0
+ | n + 1, q, s =>
+ match code q with
+ | .push k b q' => stackPaths code n q' (Function.update s k (b :: s k))
+ | .pop k f => stackPaths code n (f (s k).head?) (Function.update s k (s k).tail)
+ | .goto q' => stackPaths code n q' s
+ | .choose low high => stackPaths code n low s + stackPaths code n high s
+ | .halt b => b.toNat
+
+theorem StackRuns.paths {code : StackCode K Q} {n q s t u}
+ (h : StackRuns code n q s t u) (fuel : ℕ) :
+ stackPaths code (fuel + n) q s = stackPaths code fuel t u := by
+ induction h with
+ | nil => rfl
+ | cons hs _ ih => cases hs <;> simp_all [stackPaths]
+
+/-- Every branch halts within the stated number of elementary instructions. -/
+def StopsWithin (code : StackCode K Q) : ℕ → Q → Stacks K → Prop
+ | 0, _, _ => False
+ | n + 1, q, s =>
+ match code q with
+ | .push k b q' => StopsWithin code n q' (Function.update s k (b :: s k))
+ | .pop k f => StopsWithin code n (f (s k).head?) (Function.update s k (s k).tail)
+ | .goto q' => StopsWithin code n q' s
+ | .choose low high => StopsWithin code n low s ∧ StopsWithin code n high s
+ | .halt _ => True
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorCap.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorCap.lean
new file mode 100644
index 0000000000..abc73cffdc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorCap.lean
@@ -0,0 +1,140 @@
+import OAI.Computability.VPVNP.RAMTapeWordSimple
+import OAI.Computability.VPVNP.RAMTapeStackLift
+
+/-!
+# Comparing the successor cost with its cap
+
+The cost and the cap arrive least-significant bit first. Subtracting the cap
+with an initial borrow of one tests whether the cost is at most the cap.
+Each pair of popped bits is saved and later returned to its original stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorCap
+
+open TapeWord BurstRAM
+
+/-- Control states for subtracting the cap with an initial borrow, restoring both operands, and
+reporting whether the cost fits. -/
+inductive State where
+ | left (borrow : Bool)
+ | right (borrow x : Bool)
+ | saveLeft (borrow x y : Bool)
+ | saveRight (borrow y : Bool)
+ | restore (borrow : Bool)
+ | takeRight (borrow x : Bool)
+ | putLeft (borrow x y : Bool)
+ | putRight (borrow y : Bool)
+ | done (withinCap : Bool)
+ | reject
+ deriving DecidableEq, Fintype
+
+/-- The scratch ports `.tmp` and `.out` save the left and right inputs. -/
+def code : StackCode ScanPort State
+ | .left c => .pop .left fun b => b.elim (.restore c) (.right c)
+ | .right c x => .pop .right fun b => b.elim .reject fun y => .saveLeft (subBit c x y).2 x y
+ | .saveLeft c x y => .push .tmp x (.saveRight c y)
+ | .saveRight c y => .push .out y (.left c)
+ | .restore c => .pop .tmp fun b => b.elim (.done c) (.takeRight c)
+ | .takeRight c x => .pop .out fun b => b.elim .reject (.putLeft c x)
+ | .putLeft c x y => .push .left x (.putRight c y)
+ | .putRight c y => .push .right y (.restore c)
+ | .done _ => .halt true
+ | .reject => .halt false
+
+private theorem update_stacks (x y t u word : List Bool) (k : ScanPort) :
+ Function.update (scanStacks x y t u) k word = match k with
+ | .left => scanStacks word y t u
+ | .right => scanStacks x word t u
+ | .tmp => scanStacks x y word u
+ | .out => scanStacks x y t word := by
+ funext j; cases k <;> cases j <;> simp [scanStacks]
+
+local macro "cap_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [scanStacks, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_stacks])
+
+private theorem save_run (c : Bool) (x y t u : List Bool) (hlen : x.length = y.length) :
+ StackRuns code (4 * x.length + 1) (.left c) (scanStacks x y t u)
+ (.restore (subScan c x y).2) (scanStacks [] [] (x.reverse ++ t) (y.reverse ++ u)) := by
+ induction x generalizing c y t u with
+ | nil =>
+ have hy := List.length_eq_zero_iff.mp hlen.symm
+ subst y
+ cap_step
+ exact .nil ..
+ | cons x xs ih =>
+ cases y with
+ | nil => simp at hlen
+ | cons y ys =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append, subScan, scan]
+ cap_step
+ cap_step
+ cap_step
+ cap_step
+ exact ih _ _ _ _ (Nat.succ.inj hlen)
+
+private theorem restore_run (c : Bool) (x y t u : List Bool) (hlen : t.length = u.length) :
+ StackRuns code (4 * t.length + 1) (.restore c) (scanStacks x y t u)
+ (.done c) (scanStacks (t.reverse ++ x) (u.reverse ++ y) [] []) := by
+ induction t generalizing x y u with
+ | nil =>
+ have hu := List.length_eq_zero_iff.mp hlen.symm
+ subst u
+ cap_step
+ exact .nil ..
+ | cons a t ih =>
+ cases u with
+ | nil => simp at hlen
+ | cons b u =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ cap_step
+ cap_step
+ cap_step
+ cap_step
+ exact ih _ _ _ (Nat.succ.inj hlen)
+
+/-- Exactly eight stack instructions per bit and two empty pops. The final
+state holds the unsigned comparison and all four stacks have their entry values. -/
+theorem run (x y : List Bool) (hlen : x.length = y.length) :
+ StackRuns code (8 * x.length + 2) (.left true) (scanStacks x y [] [])
+ (.done (decide (value x ≤ value y))) (scanStacks x y [] []) := by
+ have hb : (subScan true x y).2 = decide (value x ≤ value y) := by
+ apply Bool.eq_iff_iff.mpr
+ simpa only [Bool.toNat_true, Nat.lt_succ_iff, decide_eq_true_eq] using
+ subScan_borrow (c := true) hlen
+ have hf := save_run true x y [] [] hlen
+ have hr := restore_run (subScan true x y).2 [] [] x.reverse y.reverse (by simpa)
+ simp only [List.append_nil, List.reverse_reverse, List.length_reverse, hb] at hf hr
+ convert hf.trans hr using 1
+ omega
+
+theorem word_run {w : ℕ} (cost cap : Word w) :
+ StackRuns code (8 * w + 2) (.left true) (scanStacks (wordBits cost) (wordBits cap) [] [])
+ (.done (decide (cost.val ≤ cap.val))) (scanStacks (wordBits cost) (wordBits cap) [] []) := by
+ simpa only [length_wordBits, value_wordBits] using run (wordBits cost) (wordBits cap) (by simp)
+
+/-- A caller can use any four distinct ports. The entire caller stack bank
+is restored, and the caller can use the terminal flag to select its continuation. -/
+theorem run_lift {K Q : Type*} [DecidableEq K] {target : StackCode K Q}
+ (ports : ScanPort → K) (hp : Function.Injective ports) (labels : State → Q)
+ (rows : ∀ q, (code q).returns = false → target (labels q) = (code q).rename ports labels)
+ (s : Stacks K) (hlen : (s (ports .left)).length = (s (ports .right)).length)
+ (ht : s (ports .tmp) = []) (hu : s (ports .out) = []) :
+ StackRuns target (8 * (s (ports .left)).length + 2) (labels (.left true)) s
+ (labels (.done (decide (value (s (ports .left)) ≤ value (s (ports .right)))))) s := by
+ have he := installStacks_eq hp s (scanStacks (s (ports .left)) (s (ports .right)) [] [])
+ (by intro k; cases k <;> first | rfl | exact ht | exact hu)
+ simpa only [he] using (run _ _ hlen).lift ports hp labels s rows
+
+end RAMTape.SuccessorCap
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorChecks.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorChecks.lean
new file mode 100644
index 0000000000..a63c366e57
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorChecks.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorGuard
+import OAI.Computability.VPVNP.RAMTapeSuccessorEdgeValues
+import OAI.Computability.VPVNP.RAMValidatorSuccessor
+
+/-!
+# The stack successor guard recognizes the shared-bit validator's fields
+
+On an arbitrary local vector the finite stack program accepts exactly the
+canonical present fields and the zero clamps. When the vector comes from a
+shared-bit assignment, these tests are the successor parts of the local RAM
+validator. A malformed field has zero accepting continuation count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successors
+
+open BurstRAM RAMLayout RAMSerialization
+
+variable {d e w cap : ℕ}
+
+/-- A present successor field decodes to a canonical message, and an absent field consists
+entirely of zero bits. -/
+def GoodField (hw : 2 ≤ w) (hc : cap < 2 ^ w) (present : Bool) (bits : Fin (8*w) → Bool) : Prop :=
+ if present then ∃ x, (successorFormat hw hc).decode bits = some x else bits = fun _ ↦ false
+
+private theorem good_iff (hw : 2 ≤ w) (hc : cap < 2 ^ w) (present : Bool)
+ (bits : Fin (8*w) → Bool) :
+ Successor.valid present (Successor.wordTags ((arrayBits 8 w).symm bits))
+ (decide ((((arrayBits 8 w).symm bits) 1).val ≤ cap)) = true ↔ GoodField hw hc present bits := by
+ let s : Stacks SuccessorEdge.Port := fun _ ↦ []
+ cases present with
+ | true =>
+ simpa only [GoodField, ↓reduceIte, SuccessorEdge.edgeResult, List.cons.injEq, and_true]
+ using SuccessorEdge.present_verdict_iff hw hc s bits []
+ | false =>
+ simpa only [GoodField, Bool.false_eq_true, ↓reduceIte, SuccessorEdge.edgeResult,
+ List.cons.injEq, and_true] using SuccessorEdge.clamp_verdict_iff s bits ⟨cap, hc⟩ []
+
+/-- The machine's two validity bits, evaluated on an arbitrary fixed-size
+incident vector, test the full format including every padding bit. -/
+theorem finish_good_iff (hw : 2 ≤ w) (hc : cap < 2 ^ w) (s : Stacks Port) (outgoing incoming : Bool)
+ (sent received : Fin (8*w) → Bool) (suffix : List Bool) :
+ let out := finish s outgoing incoming sent received ⟨cap, hc⟩ suffix
+ (out (.verdict .send)).head? = some true ∧ (out (.verdict .receive)).head? = some true ↔
+ GoodField hw hc outgoing sent ∧ GoodField hw hc incoming received := by
+ cases incoming <;> simp [finish, afterNormalize, afterEdge, SuccessorEdge.edgeResult, good_iff hw hc]
+
+private theorem present_iff_canonical (hw : 2 ≤ w) (hc : cap < 2 ^ w) (bits : Fin (8*w) → Bool) :
+ GoodField hw hc true bits ↔ bits =
+ (successorFormat hw hc).encode ((successorFormat hw hc).parse ((arrayBits 8 w).symm bits)) := by
+ change (∃ x, (successorFormat hw hc).decode bits = some x) ↔ _
+ constructor
+ · rintro ⟨x, h⟩
+ have he := (successor_decode_iff hw hc _ _).mp h
+ rw [he]
+ simp [Format.encode, Format.parse_words]
+ · intro h
+ exact ⟨_, (successor_decode_iff hw hc _ _).mpr h⟩
+
+/-- At shared-bit inputs the missing end vectors are clamped by construction,
+and the two remaining tests are exactly the sender and receiver predicates. -/
+theorem shared_fields_iff (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w)
+ (a : SendArrays d (2 ^ e) w) (v : Fin (2 ^ d)) :
+ let bits := RAMLayout.incidentBits a v
+ (GoodField hw hc (decide (v.val+1 < 2^d)) (fun j ↦ bits (offset d (2^e) w (.inl (0, j)))) ∧
+ GoodField hw hc (decide (0 < v.val)) (fun j ↦ bits (offset d (2^e) w (.inl (1, j))))) ↔
+ SuccessorSendOK hw hc a v ∧ SuccessorReceiveOK hw hc a v := by
+ dsimp only
+ apply and_congr
+ · by_cases hv : v.val + 1 < 2 ^ d
+ · let j : Fin (2^d-1) := ⟨v.val, by omega⟩
+ have he : (fun i ↦ RAMLayout.incidentBits a v (offset d (2^e) w (.inl (0, i)))) = a.1 j := by
+ funext i
+ rw [RAMLayout.incidentBits_offset]
+ exact incident_send _ (.inl (j, i))
+ simp only [hv, decide_true, he, present_iff_canonical, SuccessorSendOK, ↓reduceDIte]
+ rfl
+ · have he : v.val + 1 = 2 ^ d := by have := v.isLt; omega
+ simp only [hv, decide_false, GoodField, Bool.false_eq_true, ↓reduceIte, SuccessorSendOK,
+ ↓reduceDIte, iff_true]
+ exact funext fun i ↦ (RAMLayout.incidentBits_offset ..).trans
+ (incident_clamp a _ (peer_send_end v he i))
+ · by_cases hv : 0 < v.val
+ · let j : Fin (2^d-1) := ⟨v.val-1, by have := v.isLt; omega⟩
+ have he : (fun i ↦ RAMLayout.incidentBits a v (offset d (2^e) w (.inl (1, i)))) = a.1 j := by
+ funext i
+ rw [RAMLayout.incidentBits_offset]
+ exact incident_receive_successor a v hv i
+ simp only [hv, decide_true, he, present_iff_canonical, SuccessorReceiveOK, ↓reduceDIte]
+ rfl
+ · have he : v.val = 0 := by omega
+ simp only [hv, decide_false, GoodField, Bool.false_eq_true, ↓reduceIte, SuccessorReceiveOK,
+ ↓reduceDIte, iff_true]
+ exact funext fun i ↦ (RAMLayout.incidentBits_offset ..).trans
+ (incident_clamp a _ (peer_receive_start v he i))
+
+/-- The actual table spends the declared budget on valid fields and calls its
+continuation once. On malformed fields its accepting multiplicity is zero. -/
+theorem checked_shared_count (hw : 2 ≤ w) (hc : 2 ^ d * 2 ^ e < 2 ^ w)
+ (a : SendArrays d (2 ^ e) w) (s : Stacks Port) (v : Word d) (initial : Word w)
+ (hv : s .address = BurstRAM.wordBits v) (hin : s .incident = List.ofFn (RAMLayout.incidentBits a v))
+ (hwidth : s .width = List.replicate w true) (hcap : s .cap = BurstRAM.wordBits ⟨2^d * 2^e, hc⟩)
+ (hi : s .initial = BurstRAM.wordBits initial) (ht : s .tmp = []) (hu : s .capTmp = [])
+ (hblank : ∀ side i, s (.word side i) = []) (c : ℕ → Stacks Port → ℕ) (fuel : ℕ)
+ [Decidable (SuccessorSendOK hw hc a v ∧ SuccessorReceiveOK hw hc a v)] :
+ let bits := RAMLayout.incidentBits a v
+ let out := finish s (decide (v.val+1 < 2^d)) (decide (0 < v.val))
+ (fun j ↦ bits (offset d (2^e) w (.inl (0, j)))) (fun j ↦ bits (offset d (2^e) w (.inl (1, j))))
+ ⟨2^d * 2^e, hc⟩ ((List.ofFn bits).drop (16*w))
+ checked.body.count c (fuel + 2 + steps d w (decide (0 < v.val))) s =
+ if SuccessorSendOK hw hc a v ∧ SuccessorReceiveOK hw hc a v then c fuel (guardResult out) else 0 := by
+ dsimp only
+ have h := read_incident_runs s v ⟨_, hc⟩ initial _ hv hin hwidth hcap hi ht hu hblank
+ rw [checked_count_of_read h]
+ have he := finish_good_iff hw hc s (decide (v.val+1 < 2^d)) (decide (0 < v.val))
+ (fun j ↦ RAMLayout.incidentBits a v (offset d (2^e) w (.inl (0, j))))
+ (fun j ↦ RAMLayout.incidentBits a v (offset d (2^e) w (.inl (1, j)))) ((List.ofFn (RAMLayout.incidentBits a v)).drop (16*w))
+ have hiff := he.trans (shared_fields_iff hw hc a v)
+ by_cases hp : SuccessorSendOK hw hc a v ∧ SuccessorReceiveOK hw hc a v
+ · exact (ite_eq_left (hiff.mpr hp)).trans (ite_eq_left hp).symm
+ · exact (ite_eq_right (mt hiff.mp hp)).trans (ite_eq_right hp).symm
+
+end RAMTape.Successors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorControl.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorControl.lean
new file mode 100644
index 0000000000..eca66bb025
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorControl.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorCap
+import OAI.Computability.VPVNP.RAMTapeSuccessorScan
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-!
+# The fixed stack control for checking a parsed successor field
+
+The control reads each of the eight little-endian words, retaining its
+small tag. It compares the cost and the cap bit by bit. All input words
+are restored. The two output stacks receive the running-state flag and
+the format validity flag, respectively.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successor
+
+open BurstRAM RAMSerialization SuccessorTags TapeWord
+
+/-- Stacks for the eight parsed words, cap comparison, running-state bit, and field verdict. -/
+inductive CheckPort where
+ | word (i : Fin 8) | cap | tmp | capTmp | running | verdict
+ deriving DecidableEq, Fintype
+
+/-- Phases for scanning successor tags, comparing the cost with the cap, and emitting the
+running and validity bits. -/
+inductive CheckState where
+ | tags (q : TagState)
+ | cap (tagOK running : Bool) (q : SuccessorCap.State)
+ | emit (good running : Bool)
+ | verdict (good : Bool)
+ | done
+ deriving DecidableEq, Fintype
+
+/-- Wire the cap comparator to successor word one, the public cap, and their two scratch
+stacks. -/
+def capPorts : ScanPort → CheckPort
+ | .left => .word 1
+ | .right => .cap
+ | .tmp => .tmp
+ | .out => .capTmp
+
+private theorem capPorts_inj : Function.Injective capPorts := by
+ intro x y h
+ cases x <;> cases y <;> first | rfl | cases h
+
+/-- Scan the eight word tags, compare cost against the cap, and push the running bit and field
+validity bit. -/
+def checkCode (present : Bool) : StackCode CheckPort CheckState
+ | .tags (.done t) => .goto (.cap (valid present t true) (decide (t 0 = .one)) (.left true))
+ | .tags q => (tagCode CheckPort.word .tmp q).rename id CheckState.tags
+ | .cap ok run (.done withinCap) => .goto (.emit (ok && (!present || withinCap)) run)
+ | .cap ok run q => (SuccessorCap.code q).rename capPorts (CheckState.cap ok run)
+ | .emit good run => .push .running run (.verdict good)
+ | .verdict good => .push .verdict good .done
+ | .done => .halt true
+
+/-- Push the supplied running bit and verdict onto their respective stacks, preserving the rest
+of the bank. -/
+def checkResult (s : Stacks CheckPort) (good run : Bool) : Stacks CheckPort :=
+ Function.update (Function.update s .running (run :: s .running)) .verdict (good :: s .verdict)
+
+theorem check_run {w : ℕ} (present : Bool) (s : Stacks CheckPort) (a : Fin 8 → Word w) (cap : Word w)
+ (hw : ∀ i, s (.word i) = BurstRAM.wordBits (a i)) (hc : s .cap = BurstRAM.wordBits cap)
+ (ht : s .tmp = []) (hu : s .capTmp = []) :
+ StackRuns (checkCode present) (40 * w + 22) (.tags tagEntry) s .done
+ (checkResult s (valid present (wordTags a) (decide ((a 1).val ≤ cap.val)))
+ (decide ((wordTags a) 0 = .one))) := by
+ let t := wordTags a
+ let run := decide (t 0 = .one)
+ let ok := valid present t true
+ let withinCap := decide ((a 1).val ≤ cap.val)
+ have hh := tag_run CheckPort.word .tmp (fun _ h ↦ by cases h) s ht a hw
+ have hframe : installStacks id s s = s := funext fun i ↦ installStacks_at Function.injective_id s s i
+ have htags := hh.lift id Function.injective_id CheckState.tags s (target := checkCode present)
+ (by intro q hq; cases q <;> first | rfl | contradiction)
+ rw [hframe] at htags
+ have hstart : StackStep (checkCode present) (.tags (.done t)) s (.cap ok run (.left true)) s := .goto rfl
+ have hcap := SuccessorCap.run_lift (target := checkCode present) capPorts capPorts_inj
+ (CheckState.cap ok run) (by intro q hq; cases q <;> first | rfl | contradiction) s
+ (by simp [capPorts, hw, hc]) ht hu
+ simp only [capPorts, hw, hc, length_wordBits, value_wordBits] at hcap
+ have hv : (ok && (!present || withinCap)) = valid present t withinCap := by
+ cases present <;> cases withinCap <;> simp [ok, valid]
+ have hfinal : StackRuns (checkCode present) 3 (.cap ok run (.done withinCap)) s .done
+ (checkResult s (valid present t withinCap) run) := by
+ rw [← hv]
+ refine .cons (.goto rfl) (.cons (.push rfl) ?_)
+ exact .cons (.push rfl) (.nil ..)
+ have total := htags.trans (.cons hstart (hcap.trans hfinal))
+ convert total using 1
+ omega
+
+/-- Install the successor checker on the caller's ports for a present field or an absent-edge
+clamp. -/
+def checkRoutine {K : Type} (ports : CheckPort → K) (present : Bool) : FiniteRoutine K :=
+ FiniteRoutine.ofStackCode (checkCode present) ports (.tags tagEntry) (fun q ↦ decide (q = .done))
+
+theorem checkRoutine_runs {K : Type} [DecidableEq K] {w : ℕ} (ports : CheckPort → K)
+ (hp : Function.Injective ports) (present : Bool) (s : Stacks K) (a : Fin 8 → Word w) (cap : Word w)
+ (hw : ∀ i, s (ports (.word i)) = BurstRAM.wordBits (a i))
+ (hc : s (ports .cap) = BurstRAM.wordBits cap)
+ (ht : s (ports .tmp) = []) (hu : s (ports .capTmp) = []) :
+ (checkRoutine ports present).Runs (40 * w + 22) s
+ (installStacks ports s (checkResult (s ∘ ports)
+ (valid present (wordTags a) (decide ((a 1).val ≤ cap.val))) (decide ((wordTags a) 0 = .one)))) := by
+ have h := FiniteRoutine.runs_ofStackCode (normal := fun q ↦ decide (q = .done)) hp
+ (by decide) (by decide) (fun q h ↦ by simpa only [decide_eq_true_eq] using
+ ((of_decide_eq_true h) ▸ (show ((checkCode present) .done).returns = true from rfl))) s
+ (check_run present (s ∘ ports) a cap hw hc ht hu)
+ rwa [installStacks_eq hp s (s ∘ ports) (fun _ ↦ rfl)] at h
+
+end RAMTape.Successor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorCuts.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorCuts.lean
new file mode 100644
index 0000000000..c75827c37a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorCuts.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorSharedValues
+import OAI.Computability.VPVNP.RAMSortIncident
+
+/-!
+# From physical successor registers to the site's RAM cuts
+
+The validator's word-level successor scan specifies the input and output cuts
+and the two last records for the boundary check. On canonical incident fields
+the physical stacks contain those same values, including the initial cut and
+the missing output at the ends of the site chain.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successors
+
+open BurstRAM RAMLayout RAMSerialization RAMMemory
+
+variable {d e w : ℕ}
+
+/-- The word stacks at a missing send contain the zero, nonrunning cut. The
+separate presence stack distinguishes it from a present halted target. -/
+def sideCut (summary : SiteSuccessors w) : Side → Cut w
+ | .send => summary.output.getD ⟨0, none⟩
+ | .receive => summary.input
+
+/-- Select the optional sent or received boundary record from a site's successor summary. -/
+def sideRecord (summary : SiteSuccessors w) : Side → Option (Record (Word w))
+ | .send => summary.sent
+ | .receive => summary.received
+
+/-- Register contents in terms of the word validator. Each cost occupies a
+full word and has the stated natural value. Each record's encoded words
+widen to the actual address, timestamp and ordinal in the transcript. -/
+structure CutRegisters (base out : Stacks Port) (hw : 2 ≤ w) (summary : SiteSuccessors w)
+ (suffix : List Bool) : Prop where
+ incident : out .incident = suffix
+ outPresent : out .outPresent = summary.output.isSome :: base .outPresent
+ running : ∀ side, out (.running side) = (sideCut summary side).state.isSome :: base (.running side)
+ cost : ∀ side, ∃ x : Word w, out (.word side 1) = BurstRAM.wordBits x ∧ x.val = (sideCut summary side).cost
+ state : ∀ side, out (.word side 2) = BurstRAM.wordBits ((sideCut summary side).state.getD 0)
+ record : ∀ side, ∃ r : Option (WordRecord w), r.map WordRecord.record = sideRecord summary side ∧
+ out (.record side) = List.ofFn ((recordFormat hw).encode r) ++ base (.record side)
+
+private theorem summary_out (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (initial : Word w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) (summary : SiteSuccessors w)
+ (h : summary.Spec hw hc initial v a) :
+ summary.output.isSome = (sentMessage hw hc a v).isSome := by
+ rw [h.output_eq, outputCut, sentMessage]
+ split <;> rfl
+
+private theorem summary_cut (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (initial : Word w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) (summary : SiteSuccessors w)
+ (h : summary.Spec hw hc initial v a) (side : Side) :
+ let msg := atSide (sentMessage hw hc a v) (receivedMessage hw hc a v) side
+ sideCut summary side = ⟨(costWord hc msg).val, savedState initial side msg⟩ := by
+ cases side with
+ | send =>
+ change summary.output.getD _ = ⟨_, _⟩
+ rw [h.output_eq, outputCut]
+ by_cases hv : v.val + 1 < 2^d <;>
+ simp [atSide, sentMessage, hv, costWord, savedState, unpackMessages]
+ | receive =>
+ change summary.input = ⟨_, _⟩
+ rw [h.input_eq, inputCut]
+ by_cases hv : v.val = 0
+ · simp [atSide, receivedMessage, hv, costWord, savedState]
+ · have hpos : 0 < v.val := by omega
+ simp [atSide, receivedMessage, hv, hpos, costWord, savedState, unpackMessages]
+
+private theorem summary_record (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (initial : Word w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) (summary : SiteSuccessors w)
+ (h : summary.Spec hw hc initial v a) (side : Side) :
+ let msg := atSide (sentMessage hw hc a v) (receivedMessage hw hc a v) side
+ (msg.bind (·.lastRecord)).map WordRecord.record = sideRecord summary side := by
+ cases side with
+ | send =>
+ change ((sentMessage hw hc a v).bind (·.lastRecord)).map WordRecord.record = summary.sent
+ rw [h.sent_eq, RAMBoundary.outgoing, sentMessage]
+ split <;> rfl
+ | receive =>
+ change ((receivedMessage hw hc a v).bind (·.lastRecord)).map WordRecord.record = summary.received
+ rw [h.received_eq]
+ rcases v with ⟨i, hi⟩
+ cases i <;> rfl
+
+/-- Identify physical register outputs with any typed summary satisfying the
+site successor specification. The lemma applies before and after the guard. -/
+theorem Outputs.cutRegisters {hw : 2 ≤ w} {hc : 2^d * 2^e < 2^w} {initial : Word w}
+ {s out : Stacks Port} {a : SendArrays d (2^e) w} {v : Fin (2^d)} {suffix : List Bool}
+ (registers : Outputs s out hw hc initial (sentMessage hw hc a v) (receivedMessage hw hc a v) suffix)
+ (summary : SiteSuccessors w) (hs : summary.Spec hw hc initial v a) :
+ CutRegisters s out hw summary suffix := by
+ have hcut := summary_cut hw hc initial a v summary hs
+ have hrecord := summary_record hw hc initial a v summary hs
+ refine ⟨registers.incident, ?_, ?_, ?_, ?_, ?_⟩
+ · rw [summary_out hw hc initial a v summary hs]
+ exact registers.outPresent
+ · intro side
+ rw [hcut side]
+ exact registers.running side
+ · intro side
+ rw [hcut side]
+ exact ⟨_, registers.cost side, rfl⟩
+ · intro side
+ rw [hcut side]
+ exact registers.state side
+ · intro side
+ exact ⟨_, hrecord side, registers.record side⟩
+
+/-- At the continuation of the guard, the exact stack representation agrees
+with the word validator's successor scan on the same site and shared bits. -/
+theorem guarded_cutRegisters (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (initial : Word w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) (s : Stacks Port)
+ (hi : s .initial = BurstRAM.wordBits initial) (hs : SuccessorSendOK hw hc a v)
+ (hr : SuccessorReceiveOK hw hc a v) :
+ CutRegisters s (guardResult (sharedFinish hc a v s)) hw
+ (scanSuccessors hw hc initial v (sortIncident a v)).1
+ ((List.ofFn (RAMLayout.incidentBits a v)).drop (16*w)) :=
+ (guard_shared_values hw hc a v s initial hi hs hr).cutRegisters _
+ (scanSuccessors_spec hw hc initial v (sortIncident a v) a (sortIncident_offset a v))
+
+end RAMTape.Successors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorDispatch.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorDispatch.lean
new file mode 100644
index 0000000000..e7c1cab14d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorDispatch.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorEnds
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import Mathlib.Data.Fintype.Sigma
+
+/-!
+# Dispatch on the two end conditions of a site
+
+A fixed finite routine first scans the site's address, preserving its bits.
+The two resulting flags select one of four finite continuations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorEnds
+
+open BurstRAM
+
+variable {K : Type}
+
+private abbrev Labels (body : Bool → Bool → FiniteRoutine K) :=
+ State ⊕ (Σ flags : Bool × Bool, (body flags.1 flags.2).State)
+
+/-- Scan the address for outgoing and incoming edges, restore it, then enter the continuation
+selected by the two flags. -/
+def dispatch (src tmp : K) (body : Bool → Bool → FiniteRoutine K) : FiniteRoutine K :=
+ FiniteRoutine.ofRoutine ({
+ entry := .inl (.read false false)
+ code
+ | .inl (.done outgoing incoming) =>
+ .goto (some (.inr ⟨(outgoing, incoming), (body outgoing incoming).body.entry⟩))
+ | .inl q => (code src tmp q).rename id (some ∘ Sum.inl)
+ | .inr ⟨f, q⟩ => (body f.1 f.2).body.install (fun q ↦ .inr ⟨f, q⟩) none q
+ } : Routine K (Labels body))
+
+theorem dispatch_runs [DecidableEq K] {d : ℕ} (src tmp : K) (hne : src ≠ tmp)
+ (body : Bool → Bool → FiniteRoutine K) (s : Stacks K) (v : Word d)
+ (hv : s src = BurstRAM.wordBits v) (ht : s tmp = []) {n : ℕ} {out : Stacks K}
+ (hb : (body (decide (v.val + 1 < 2 ^ d)) (decide (0 < v.val))).Runs n s out) :
+ (dispatch src tmp body).Runs (4 * d + 3 + n) s out := by
+ let r := (dispatch src tmp body).body
+ let f := (decide (v.val + 1 < 2 ^ d), decide (0 < v.val))
+ have he := (word_run src tmp hne s v hv ht).lift id Function.injective_id
+ (fun q ↦ some (Sum.inl q)) s (target := r.standalone)
+ (by intro q h; cases q <;> first | rfl | contradiction)
+ have hframe : installStacks id s s = s := funext fun i ↦ installStacks_at Function.injective_id s s i
+ rw [hframe] at he
+ have hj : StackStep r.standalone (some (.inl (.done f.1 f.2))) s
+ (some (.inr ⟨f, (body f.1 f.2).body.entry⟩)) s := .goto rfl
+ have hrun := hb.link r (fun q ↦ .inr ⟨f, q⟩) none (fun _ ↦ rfl)
+ rw [show 4 * d + 3 + n = (4 * d + 2) + (n + 1) by omega]
+ exact he.trans (.cons hj hrun)
+
+end RAMTape.SuccessorEnds
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorEdge.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorEdge.lean
new file mode 100644
index 0000000000..b4762ddb82
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorEdge.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorControl
+import OAI.Computability.VPVNP.RAMTapeSuccessorFields
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-!
+# Executing one successor field check on the incident stack
+
+Read the next eight words, check the successor or its boundary clamp, and
+retain the five-word raw record for the final predecessor check. Every
+fixed-length bit pattern returns both flags in the same number of steps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorEdge
+
+open BurstRAM RAMSerialization Successor
+
+/-- Registers for reading an incident successor field, checking its cost and tags, and
+retaining its record and flags. -/
+inductive Port where
+ | input | width | tmp | cap | capTmp | running | verdict | record | word (i : Fin 8)
+ deriving DecidableEq, Fintype
+
+private def readPorts : SuccessorFields.Port → Port
+ | .input => .input
+ | .width => .width
+ | .tmp => .tmp
+ | .word i => .word i
+
+private def checkPorts : CheckPort → Port
+ | .cap => .cap
+ | .capTmp => .capTmp
+ | .running => .running
+ | .verdict => .verdict
+ | .tmp => .tmp
+ | .word i => .word i
+
+private def recordPorts : SuccessorFields.RecordPort → Port
+ | .tmp => .tmp
+ | .record => .record
+ | .word i => .word i
+
+private theorem readPorts_inj : Function.Injective readPorts := by
+ intro a b h
+ cases a <;> cases b <;> simp_all [readPorts]
+
+private theorem checkPorts_inj : Function.Injective checkPorts := by
+ intro a b h
+ cases a <;> cases b <;> simp_all [checkPorts]
+
+private theorem recordPorts_inj : Function.Injective recordPorts := by
+ intro a b h
+ cases a <;> cases b <;> simp_all [recordPorts]
+
+variable {w : ℕ}
+
+/-- Raw little-endian bits of words 3 through 7. They are copied even for a
+malformed record, so the boundary check sees the actual incident payload. -/
+def recordBits (a : Fin 8 → Word w) : List Bool :=
+ (List.ofFn fun i : Fin 5 => BurstRAM.wordBits (a (Fin.natAdd 3 i))).flatten
+
+private theorem recordBits_words (a : Fin 8 → Word w) :
+ recordBits a = BurstRAM.wordBits (a 3) ++ BurstRAM.wordBits (a 4) ++
+ BurstRAM.wordBits (a 5) ++ BurstRAM.wordBits (a 6) ++ BurstRAM.wordBits (a 7) := by
+ simp only [recordBits, List.ofFn_succ, List.ofFn_zero, List.flatten_cons, List.flatten_nil,
+ List.append_nil, List.append_assoc]
+ rfl
+
+private def localEdge (present : Bool) : FiniteRoutine Port :=
+ ((SuccessorFields.read readPorts).followedBy (checkRoutine checkPorts present)).followedBy
+ (SuccessorFields.appendRecord recordPorts)
+
+/-- A caller chooses the physical stacks for all inputs, scratch, and outputs. -/
+def edge {K : Type} (ports : Port → K) (present : Bool) : FiniteRoutine K :=
+ (localEdge present).onPorts ports
+
+/-- Exact state at the return from one edge check. The input head now points
+to the next field. The cap word and unary width are available for that field. -/
+def edgeResult (s : Stacks Port) (present : Bool) (bits : Fin (8*w) → Bool) (cap : Word w)
+ (suffix : List Bool) : Stacks Port :=
+ let a := (arrayBits 8 w).symm bits
+ fun p => match p with
+ | .input => suffix
+ | .word i => BurstRAM.wordBits (a i)
+ | .record => recordBits a ++ s .record
+ | .running => decide (wordTags a 0 = .one) :: s .running
+ | .verdict => valid present (wordTags a) (decide ((a 1).val ≤ cap.val)) :: s .verdict
+ | p => s p
+
+private def extracted (s : Stacks Port) (a : Fin 8 → Word w) (suffix : List Bool) : Stacks Port
+ | .input => suffix
+ | .word i => BurstRAM.wordBits (a i)
+ | p => s p
+
+private def flagged (s : Stacks Port) (good run : Bool) : Stacks Port
+ | .running => run :: s .running
+ | .verdict => good :: s .verdict
+ | p => s p
+
+private theorem localEdge_runs (present : Bool) (s : Stacks Port) (bits : Fin (8*w) → Bool)
+ (cap : Word w) (suffix : List Bool) (hin : s .input = List.ofFn bits ++ suffix)
+ (hw : s .width = List.replicate w true) (hc : s .cap = BurstRAM.wordBits cap)
+ (ht : s .tmp = []) (hu : s .capTmp = []) (hwords : ∀ i, s (.word i) = []) :
+ (localEdge present).Runs (113*w+49) s (edgeResult s present bits cap suffix) := by
+ let a := (arrayBits 8 w).symm bits
+ let t := extracted s a suffix
+ let good := valid present (wordTags a) (decide ((a 1).val ≤ cap.val))
+ let run := decide (wordTags a 0 = .one)
+ let u := flagged t good run
+ have h₁ := SuccessorFields.read_raw_runs readPorts readPorts_inj s bits suffix hin hw ht
+ have he : installStacks readPorts s
+ (SuccessorFields.result (s ∘ readPorts) (fun i => BurstRAM.wordBits (a i)) suffix) = t := by
+ apply installStacks_frame readPorts_inj
+ · intro k
+ cases k <;> simp [t, extracted, readPorts, SuccessorFields.result, hwords]
+ · intro l hl
+ cases l with
+ | input => exact (hl .input rfl).elim
+ | word i => exact (hl (.word i) rfl).elim
+ | _ => rfl
+ rw [he] at h₁
+ have h₂ := checkRoutine_runs checkPorts checkPorts_inj present t a cap
+ (fun _ => rfl) hc ht hu
+ have he' : installStacks checkPorts t (checkResult (t ∘ checkPorts) good run) = u := by
+ apply installStacks_frame checkPorts_inj
+ · intro k
+ cases k <;> simp [u, flagged, checkResult, checkPorts]
+ · intro l hl
+ cases l with
+ | running => exact (hl .running rfl).elim
+ | verdict => exact (hl .verdict rfl).elim
+ | _ => rfl
+ rw [he'] at h₂
+ have h₃ := SuccessorFields.appendRecord_runs recordPorts_inj u (w := w) ht
+ (fun i _ => BurstRAM.length_wordBits (a i))
+ have hf : Function.update u (recordPorts .record)
+ (u (recordPorts (.word 3)) ++ u (recordPorts (.word 4)) ++ u (recordPorts (.word 5)) ++
+ u (recordPorts (.word 6)) ++ u (recordPorts (.word 7)) ++ u (recordPorts .record)) =
+ edgeResult s present bits cap suffix := by
+ funext p
+ cases p <;> simp [edgeResult, u, t, extracted, flagged, recordPorts, recordBits_words, a, good, run]
+ rw [hf] at h₃
+ rw [show 113*w+49 = (8*(6*w+2)+1)+(40*w+22)+(25*w+10) by omega]
+ exact (h₁.followedBy h₂).followedBy h₃
+
+/-- On all wire values, the same exact stack cost covers extraction, testing,
+and the copy needed for the predecessor condition. -/
+theorem edge_runs {K : Type} [DecidableEq K] (ports : Port → K) (hp : Function.Injective ports)
+ (present : Bool) (s : Stacks K) (bits : Fin (8*w) → Bool) (cap : Word w) (suffix : List Bool)
+ (hin : s (ports .input) = List.ofFn bits ++ suffix)
+ (hw : s (ports .width) = List.replicate w true) (hc : s (ports .cap) = BurstRAM.wordBits cap)
+ (ht : s (ports .tmp) = []) (hu : s (ports .capTmp) = [])
+ (hwords : ∀ i, s (ports (.word i)) = []) :
+ (edge ports present).Runs (113*w+49) s
+ (installStacks ports s (edgeResult (s ∘ ports) present bits cap suffix)) := by
+ have h := (localEdge present).runs_onPorts hp s
+ (localEdge_runs present (s ∘ ports) bits cap suffix hin hw hc ht hu hwords)
+ rwa [installStacks_eq hp s (s ∘ ports) (fun _ => rfl)] at h
+
+end RAMTape.SuccessorEdge
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorEdgeValues.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorEdgeValues.lean
new file mode 100644
index 0000000000..7a206b6858
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorEdgeValues.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorEdge
+
+/-!
+# Successor values returned by the physical edge check
+
+For a present edge the validity flag recognizes the entire canonical encoding.
+The running bit, cumulative cost, state and record on a valid return agree with
+the typed message. At a missing edge the only valid input is the zero clamp.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorEdge
+
+open BurstRAM RAMSerialization Successor
+
+variable {w cap : ℕ}
+
+private theorem zeroArray {k : ℕ} :
+ (arrayBits k w).symm (fun _ => false) = fun _ => (0 : Word w) := by
+ apply (arrayBits k w).injective
+ rw [Equiv.apply_symm_apply]
+ funext j
+ obtain ⟨⟨i, t⟩, rfl⟩ := finProdFinEquiv.surjective j
+ exact ((arrayBits_at _ i t).trans (RAMSerialization.wordBits_zero t)).symm
+
+/-- The returning validity bit on a present edge agrees with successful decoding. -/
+theorem present_verdict_iff (hw : 2 ≤ w) (hc : cap < 2^w) (s : Stacks Port)
+ (bits : Fin (8*w) → Bool) (suffix : List Bool) :
+ edgeResult s true bits ⟨cap, hc⟩ suffix .verdict = true :: s .verdict ↔
+ ∃ x, (successorFormat hw hc).decode bits = some x := by
+ let a := (arrayBits 8 w).symm bits
+ change (valid true (wordTags a) (decide ((a 1).val ≤ cap)) :: _) = _ ↔ _
+ simp only [List.cons.injEq, and_true, valid_present_iff hw hc, successor_decode_iff, Format.encode]
+ apply exists_congr
+ intro x
+ exact ((arrayBits 8 w).eq_symm_apply).trans eq_comm
+
+private theorem encodedRecord (hw : 2 ≤ w) (hc : cap < 2^w) (x : RAMSerialization.Successor w cap) :
+ recordBits ((successorFormat hw hc).words x) = List.ofFn ((recordFormat hw).encode x.lastRecord) := by
+ rw [SuccessorFields.raw_eq_flatten_words, Format.encode, Equiv.symm_apply_apply]
+ change (List.ofFn fun i : Fin 5 => BurstRAM.wordBits
+ (Fin.append _ ((recordFormat hw).words x.lastRecord) (Fin.natAdd 3 i))).flatten = _
+ simp only [Fin.append_right]
+
+/-- On a successful present-edge check, the saved cost includes the possible
+endpoint value `cap`. A halt supplies the zero state word. -/
+theorem present_values (hw : 2 ≤ w) (hc : cap < 2^w) (s : Stacks Port)
+ (bits : Fin (8*w) → Bool) (suffix : List Bool) (x : RAMSerialization.Successor w cap)
+ (hx : (successorFormat hw hc).decode bits = some x) :
+ let out := edgeResult s true bits ⟨cap, hc⟩ suffix
+ out .verdict = true :: s .verdict ∧ out .running = x.state.isSome :: s .running ∧
+ out (.word 1) = BurstRAM.wordBits
+ (⟨x.cost.val, (Nat.le_of_lt_succ x.cost.isLt).trans_lt hc⟩ : Word w) ∧
+ out (.word 2) = BurstRAM.wordBits (x.state.getD 0) ∧
+ out .record = List.ofFn ((recordFormat hw).encode x.lastRecord) ++ s .record := by
+ refine ⟨(present_verdict_iff hw hc s bits suffix).mpr ⟨x, hx⟩, ?_⟩
+ have ha : (arrayBits 8 w).symm bits = (successorFormat hw hc).words x := by
+ rw [(successor_decode_iff hw hc bits x).mp hx, Format.encode, Equiv.symm_apply_apply]
+ simp only [edgeResult, ha, encodedRecord]
+ refine ⟨?_, rfl, rfl, trivial⟩
+ cases x with
+ | mk state cost last => cases state <;> rfl
+
+/-- On a missing edge the verdict bit tests every incident bit against zero. -/
+theorem clamp_verdict_iff (s : Stacks Port) (bits : Fin (8*w) → Bool) (bound : Word w)
+ (suffix : List Bool) :
+ edgeResult s false bits bound suffix .verdict = true :: s .verdict ↔ bits = fun _ => false := by
+ simp only [edgeResult, List.cons.injEq, and_true, valid_clamp_iff]
+ rw [← zeroArray]
+ exact (arrayBits 8 w).symm.injective.eq_iff
+
+/-- The only valid missing field supplies eight zero words, a zero record
+of exactly five word widths, and the nonrunning flag before site normalization. -/
+theorem clamped_values (s : Stacks Port) (bound : Word w) (suffix : List Bool) :
+ let out := edgeResult s false (fun _ => false) bound suffix
+ out .verdict = true :: s .verdict ∧ out .running = false :: s .running ∧
+ (∀ i, out (.word i) = BurstRAM.wordBits (0 : Word w)) ∧
+ out .record = List.replicate (5*w) false ++ s .record := by
+ refine ⟨(clamp_verdict_iff s _ bound suffix).mpr rfl, ?_⟩
+ simp only [edgeResult, zeroArray]
+ refine ⟨rfl, fun _ => True.intro, ?_⟩
+ have h := SuccessorFields.raw_eq_flatten_words (fun _ : Fin (5*w) => false)
+ rw [zeroArray, List.ofFn_const] at h
+ exact congrArg (· ++ s .record) h.symm
+
+end RAMTape.SuccessorEdge
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorEnds.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorEnds.lean
new file mode 100644
index 0000000000..1b207b0148
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorEnds.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.RAMTapeWord
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Detecting the two ends of the site chain
+
+A site has an outgoing edge when a bit in its address is zero. It has an
+incoming edge when a bit is one. The scan saves and restores the address and
+returns both edge-presence flags in finite control.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorEnds
+
+open TapeWord BurstRAM
+
+/-- States for scanning and restoring the site address while recording whether outgoing and
+incoming edges exist. -/
+inductive State where
+ | read (outgoing incoming : Bool)
+ | save (outgoing incoming bit : Bool)
+ | restore (outgoing incoming : Bool)
+ | put (outgoing incoming bit : Bool)
+ | done (outgoing incoming : Bool)
+ deriving DecidableEq, Fintype
+
+variable {K : Type*}
+
+/-- The control scans a site address once, then transfers its bits back. -/
+def code (src tmp : K) : StackCode K State
+ | .read o i => .pop src fun b => b.elim (.restore o i) fun x => .save (o || !x) (i || x) x
+ | .save o i x => .push tmp x (.read o i)
+ | .restore o i => .pop tmp fun b => b.elim (.done o i) (.put o i)
+ | .put o i x => .push src x (.restore o i)
+ | .done _ _ => .halt true
+
+theorem any_zero (xs : List Bool) : xs.any (!·) = decide (value xs + 1 < 2 ^ xs.length) := by
+ induction xs with
+ | nil => rfl
+ | cons b xs ih =>
+ have hb := value_lt xs
+ rw [List.any_cons, ih]
+ apply Bool.eq_iff_iff.mpr
+ cases b <;> simp [value, pow_succ] <;> omega
+
+theorem any_one (xs : List Bool) : xs.any id = decide (0 < value xs) := by
+ induction xs with
+ | nil => rfl
+ | cons b xs ih =>
+ rw [List.any_cons, ih]
+ apply Bool.eq_iff_iff.mpr
+ cases b <;> simp [value]
+
+variable [DecidableEq K] (src tmp : K)
+
+private def bank (s : Stacks K) (x t : List Bool) : Stacks K :=
+ Function.update (Function.update s tmp t) src x
+
+private theorem bank_src (s : Stacks K) (x t : List Bool) : bank src tmp s x t src = x := by
+ simp [bank]
+
+private theorem bank_tmp (h : src ≠ tmp) (s : Stacks K) (x t : List Bool) :
+ bank src tmp s x t tmp = t := by
+ simp [bank, Function.update_of_ne (Ne.symm h)]
+
+private theorem write_src (s : Stacks K) (x t v : List Bool) :
+ Function.update (bank src tmp s x t) src v = bank src tmp s v t := by
+ simp only [bank, Function.update_idem]
+
+private theorem write_tmp (h : src ≠ tmp) (s : Stacks K) (x t v : List Bool) :
+ Function.update (bank src tmp s x t) tmp v = bank src tmp s x v := by
+ rw [bank, Function.update_comm h, Function.update_idem, bank]
+
+local macro "end_step" h:term : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [bank_src, bank_tmp _ _ $h, List.head?_cons, List.tail_cons, List.head?_nil,
+ List.tail_nil, Option.elim_some, Option.elim_none, write_src, write_tmp _ _ $h])
+
+private theorem read_run (h : src ≠ tmp) (s : Stacks K) (x t : List Bool) (o i : Bool) :
+ StackRuns (code src tmp) (2 * x.length + 1) (.read o i) (bank src tmp s x t)
+ (.restore (o || x.any (!·)) (i || x.any id)) (bank src tmp s [] (x.reverse ++ t)) := by
+ induction x generalizing t o i with
+ | nil =>
+ simp only [List.any_nil, Bool.or_false, List.reverse_nil, List.nil_append]
+ end_step h
+ exact .nil ..
+ | cons b xs ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append, List.any_cons, id_eq, ← Bool.or_assoc]
+ end_step h
+ end_step h
+ exact ih _ _ _
+
+private theorem restore_run (h : src ≠ tmp) (s : Stacks K) (x t : List Bool) (o i : Bool) :
+ StackRuns (code src tmp) (2 * t.length + 1) (.restore o i) (bank src tmp s x t)
+ (.done o i) (bank src tmp s (t.reverse ++ x) []) := by
+ induction t generalizing x with
+ | nil =>
+ end_step h
+ exact .nil ..
+ | cons b t ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ end_step h
+ end_step h
+ exact ih _
+
+/-- The entire bank is restored, including the address. The empty address
+returns two false flags, as required for the single-site chain. -/
+theorem run (h : src ≠ tmp) (s : Stacks K) (ht : s tmp = []) :
+ StackRuns (code src tmp) (4 * (s src).length + 2) (.read false false) s
+ (.done (decide (value (s src) + 1 < 2 ^ (s src).length)) (decide (0 < value (s src)))) s := by
+ let xs := s src
+ have hf := read_run src tmp h s xs [] false false
+ have hr := restore_run src tmp h s [] xs.reverse (xs.any (!·)) (xs.any id)
+ have hs : bank src tmp s xs [] = s := by
+ simp [bank, xs, ← ht]
+ simp only [Bool.false_or, List.append_nil, List.length_reverse, List.reverse_reverse, hs] at hf hr
+ have hc := hf.trans hr
+ rw [any_zero, any_one] at hc
+ convert hc using 1
+ dsimp [xs]
+ omega
+
+theorem word_run {d : ℕ} (h : src ≠ tmp) (s : Stacks K) (v : Word d)
+ (hv : s src = wordBits v) (ht : s tmp = []) :
+ StackRuns (code src tmp) (4 * d + 2) (.read false false) s
+ (.done (decide (v.val + 1 < 2 ^ d)) (decide (0 < v.val))) s := by
+ simpa only [hv, length_wordBits, value_wordBits] using run src tmp h s ht
+
+end RAMTape.SuccessorEnds
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorFields.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorFields.lean
new file mode 100644
index 0000000000..fad8c48e46
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorFields.lean
@@ -0,0 +1,303 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMWordBits
+
+/-!
+# Splitting the successor wire on the physical incident tape
+
+One unary width stack supplies a count for each of the eight words. After each
+word, the reader restores this count and reverses the saved bits into their
+destination stack, preserving the least-significant-bit-first representation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorFields
+
+/-- Stacks for extracting one fixed-width word from the incident bit stream. -/
+inductive WordPort where
+ | input | width | tmp | out
+ deriving DecidableEq
+
+instance : Fintype WordPort := derive_fintype% _
+
+/-- Control states for collecting a word, restoring its unary width, and rejecting an exhausted
+incident stream. -/
+inductive Phase where
+ | collect | readBit | save (bit : Bool) | restore | put (bit : Bool) | mark | done | reject
+ deriving DecidableEq, Fintype
+
+/-- Read one field of the width given in unary, then restore its markers for the next field. -/
+def wordCode : StackCode WordPort Phase
+ | .collect => .pop .width fun mark => mark.elim .restore fun _ => .readBit
+ | .readBit => .pop .input fun b => b.elim .reject .save
+ | .save b => .push .tmp b .collect
+ | .restore => .pop .tmp fun b => b.elim .done .put
+ | .put b => .push .out b .mark
+ | .mark => .push .width true .restore
+ | .done => .halt true
+ | .reject => .halt false
+
+private def wordStacks (input width tmp out : List Bool) : Stacks WordPort
+ | .input => input
+ | .width => width
+ | .tmp => tmp
+ | .out => out
+
+private theorem update_wordStacks (input width tmp out new : List Bool) (k : WordPort) :
+ Function.update (wordStacks input width tmp out) k new = match k with
+ | .input => wordStacks new width tmp out
+ | .width => wordStacks input new tmp out
+ | .tmp => wordStacks input width new out
+ | .out => wordStacks input width tmp new := by
+ funext j
+ cases k <;> cases j <;> rfl
+
+local macro "field_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [wordStacks, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_wordStacks])
+
+private theorem collect_runs (data suffix tmp out : List Bool) :
+ StackRuns wordCode (3 * data.length + 1) .collect
+ (wordStacks (data ++ suffix) (List.replicate data.length true) tmp out)
+ .restore (wordStacks suffix [] (data.reverse ++ tmp) out) := by
+ induction data generalizing tmp with
+ | nil =>
+ simp only [List.length_nil, List.nil_append, List.reverse_nil, List.replicate_zero,
+ Nat.mul_zero, Nat.zero_add]
+ field_step
+ exact .nil ..
+ | cons b data ih =>
+ simp only [List.length_cons, List.cons_append, List.replicate_succ, List.reverse_cons,
+ List.append_assoc, Nat.mul_succ]
+ field_step
+ field_step
+ field_step
+ exact ih (b :: tmp)
+
+private theorem restore_runs (input width tmp out : List Bool) :
+ StackRuns wordCode (3 * tmp.length + 1) .restore (wordStacks input width tmp out)
+ .done (wordStacks input (List.replicate tmp.length true ++ width) [] (tmp.reverse ++ out)) := by
+ induction tmp generalizing width out with
+ | nil =>
+ simp only [List.length_nil, List.nil_append, List.reverse_nil, List.replicate_zero,
+ Nat.mul_zero, Nat.zero_add]
+ field_step
+ exact .nil ..
+ | cons b tmp ih =>
+ simp only [List.length_cons, List.replicate_succ', List.reverse_cons, List.append_assoc,
+ List.singleton_append, Nat.mul_succ]
+ field_step
+ field_step
+ field_step
+ exact ih (true :: width) (b :: out)
+
+/-- Extract the given word in its original order, restoring its unary width. -/
+theorem word_runs (s : Stacks WordPort) (data suffix : List Bool)
+ (hin : s .input = data ++ suffix) (hw : s .width = List.replicate data.length true)
+ (ht : s .tmp = []) :
+ StackRuns wordCode (6 * data.length + 2) .collect s .done
+ (Function.update (Function.update s .input suffix) .out (data ++ s .out)) := by
+ have hc := collect_runs data suffix [] (s .out)
+ simp only [List.append_nil] at hc
+ have hr := restore_runs suffix [] data.reverse (s .out)
+ simp only [List.append_nil, List.length_reverse, List.reverse_reverse] at hr
+ have hs : wordStacks (data ++ suffix) (List.replicate data.length true) [] (s .out) = s := by
+ funext k
+ cases k <;> simp [wordStacks, hin, hw, ht]
+ have hf : wordStacks suffix (List.replicate data.length true) [] (data ++ s .out) =
+ Function.update (Function.update s .input suffix) .out (data ++ s .out) := by
+ funext k
+ cases k <;> simp [wordStacks, hw, ht]
+ rw [hs] at hc
+ rw [hf] at hr
+ convert hc.trans hr using 1
+ omega
+
+/-- Shared input, width, and scratch stacks and the eight individual successor word stacks. -/
+inductive Port where
+ | input | width | tmp | word (index : Fin 8)
+ deriving DecidableEq, Fintype
+
+private def wordPorts (i : Fin 8) : WordPort → Port
+ | .input => .input
+ | .width => .width
+ | .tmp => .tmp
+ | .out => .word i
+
+private theorem wordPorts_injective (i : Fin 8) : Function.Injective (wordPorts i) := by
+ intro a b h
+ cases a <;> cases b <;> first | rfl | cases h
+
+private def wordReturn (q : Phase) := decide (q = .done)
+
+private def one (i : Fin 8) : FiniteRoutine Port :=
+ FiniteRoutine.ofStackCode wordCode (wordPorts i) .collect wordReturn
+
+private theorem one_runs (i : Fin 8) (s : Stacks Port) (data suffix : List Bool)
+ (hin : s .input = data ++ suffix) (hw : s .width = List.replicate data.length true)
+ (ht : s .tmp = []) : (one i).Runs (6 * data.length + 2) s
+ (Function.update (Function.update s .input suffix) (.word i) (data ++ s (.word i))) := by
+ let small := s ∘ wordPorts i
+ apply FiniteRoutine.runs_ofStackCode_framed (wordPorts_injective i) (normal := wordReturn)
+ (entry := .collect) (exit := .done) rfl rfl
+ (fun q h => by have hq : q = .done := of_decide_eq_true h; subst q; rfl)
+ (word_runs small data suffix hin hw ht) (fun _ => rfl)
+ · intro k
+ cases k <;> simp [wordPorts, small]
+ · intro l hl
+ have ho : l ≠ .word i := Ne.symm (hl .out)
+ have hi : l ≠ .input := Ne.symm (hl .input)
+ simp [ho, hi]
+
+/-- The indices of the eight words are fixed in the finite control. -/
+private def indices := List.ofFn (id : Fin 8 → Fin 8)
+
+private def readList : List (Fin 8) → FiniteRoutine Port
+ | [] => FiniteRoutine.ret
+ | i :: is => (one i).followedBy (readList is)
+
+private def afterList (s : Stacks Port) (data : Fin 8 → List Bool)
+ (is : List (Fin 8)) (suffix : List Bool) : Stacks Port
+ | .input => suffix
+ | .word i => if i ∈ is then data i ++ s (.word i) else s (.word i)
+ | .tmp => s .tmp
+ | .width => s .width
+
+private theorem readList_runs
+ (w : ℕ) (data : Fin 8 → List Bool) (hdata : ∀ i, (data i).length = w)
+ (is : List (Fin 8)) (hd : is.Nodup) (s : Stacks Port) (suffix : List Bool)
+ (hin : s .input = is.flatMap data ++ suffix) (hw : s .width = List.replicate w true)
+ (ht : s .tmp = []) :
+ (readList is).Runs (is.length * (6*w+2) + 1) s (afterList s data is suffix) := by
+ induction is generalizing s with
+ | nil =>
+ have he : afterList s data [] suffix = s := by
+ funext k
+ cases k <;> simp_all [afterList]
+ rw [he]
+ rw [List.length_nil, Nat.zero_mul, Nat.zero_add]
+ exact Routine.runs_ret s
+ | cons i is ih =>
+ let rest := is.flatMap data ++ suffix
+ let mid := Function.update (Function.update s .input rest) (.word i) (data i ++ s (.word i))
+ have h₁ : (one i).Runs (6*w+2) s mid := by
+ rw [← hdata i]
+ exact one_runs i s (data i) rest (by simpa [rest, List.append_assoc] using hin)
+ (by simpa [hdata] using hw) ht
+ have h₂ := ih (List.nodup_cons.mp hd).2 mid (by simp [mid, rest])
+ (by simpa [mid] using hw) (by simpa [mid] using ht)
+ have he : afterList mid data is suffix = afterList s data (i :: is) suffix := by
+ have hi := (List.nodup_cons.mp hd).1
+ funext k
+ cases k with
+ | word j =>
+ by_cases hj : j = i
+ · subst j
+ simp [afterList, mid, hi]
+ · simp [afterList, mid, hj]
+ | input | width | tmp => simp [afterList, mid]
+ rw [he] at h₂
+ change ((one i).followedBy (readList is)).Runs ((is.length+1)*(6*w+2)+1) s _
+ rw [Nat.succ_mul, show is.length * (6*w+2) + (6*w+2) + 1 =
+ (6*w+2) + (is.length * (6*w+2) + 1) by omega]
+ exact h₁.followedBy h₂
+
+/-- After reading, the next field starts at the top of the input stack. The
+public width and the scratch stack have their original contents. -/
+def result (s : Stacks Port) (data : Fin 8 → List Bool) (suffix : List Bool) : Stacks Port
+ | .input => suffix
+ | .word i => data i ++ s (.word i)
+ | .width => s .width
+ | .tmp => s .tmp
+
+private theorem readEight_runs
+ (w : ℕ) (data : Fin 8 → List Bool) (hdata : ∀ i, (data i).length = w)
+ (s : Stacks Port) (suffix : List Bool) (hin : s .input = (List.ofFn data).flatten ++ suffix)
+ (hw : s .width = List.replicate w true) (ht : s .tmp = []) :
+ (readList indices).Runs (8*(6*w+2)+1) s (result s data suffix) := by
+ have hi : indices.flatMap data = (List.ofFn data).flatten := by
+ rw [List.flatMap_def, indices, List.map_ofFn]
+ rfl
+ have he : afterList s data indices suffix = result s data suffix := by
+ funext k
+ cases k with
+ | word i =>
+ have hm : i ∈ indices := List.mem_ofFn.mpr ⟨i, rfl⟩
+ simp [afterList, result, hm]
+ | input | tmp | width => rfl
+ have h := readList_runs w data hdata indices (by decide) s suffix (hi ▸ hin) hw ht
+ rwa [he, show indices.length = 8 from List.length_ofFn] at h
+
+/-- The eight-word program is independent of the bit width and of all wire values. -/
+def read {K : Type} (ports : Port → K) : FiniteRoutine K := (readList indices).onPorts ports
+
+/-- Read an arbitrary successor field, including noncanonical encodings. The
+same instruction count applies to every input with the public field lengths. -/
+theorem read_runs {K : Type} [DecidableEq K] (ports : Port → K) (hp : Function.Injective ports)
+ (s : Stacks K) (w : ℕ) (data : Fin 8 → List Bool) (suffix : List Bool)
+ (hdata : ∀ i, (data i).length = w)
+ (hin : s (ports .input) = (List.ofFn data).flatten ++ suffix)
+ (hw : s (ports .width) = List.replicate w true) (ht : s (ports .tmp) = []) :
+ (read ports).Runs (8*(6*w+2)+1) s (installStacks ports s (result (s ∘ ports) data suffix)) := by
+ have run := (readList indices).runs_onPorts hp s
+ (readEight_runs w data hdata (s ∘ ports) suffix hin hw ht)
+ rwa [installStacks_eq hp s (s ∘ ports) (fun _ => rfl)] at run
+
+/-- The physical input tape is the row-major concatenation of fixed-width fields. -/
+theorem raw_eq_flatten {α : Type*} {k w : ℕ} (b : Fin (k * w) → α) :
+ List.ofFn b = (List.ofFn fun i : Fin k =>
+ List.ofFn fun j : Fin w => b (finProdFinEquiv (i, j))).flatten := by
+ simpa only [finProdFinEquiv, Equiv.coe_fn_mk, Nat.mul_comm w, Nat.add_comm] using List.ofFn_mul b
+
+/-- Decoding the word array preserves every bit, including for malformed successor messages. -/
+theorem raw_eq_flatten_words {k w : ℕ} (b : Fin (k * w) → Bool) :
+ List.ofFn b = (List.ofFn fun i : Fin k =>
+ BurstRAM.wordBits ((RAMSerialization.arrayBits k w).symm b i)).flatten := by
+ rw [raw_eq_flatten]
+ congr 1
+ apply congrArg List.ofFn
+ funext i
+ unfold BurstRAM.wordBits
+ apply congrArg List.ofFn
+ funext j
+ simpa only [Equiv.apply_symm_apply] using
+ RAMSerialization.arrayBits_at ((RAMSerialization.arrayBits k w).symm b) i j
+
+/-- Specialization to a successor wire in the serial transcript. -/
+theorem read_raw_runs {K : Type} [DecidableEq K] (ports : Port → K) (hp : Function.Injective ports)
+ (s : Stacks K) {w : ℕ} (bits : Fin (8*w) → Bool) (suffix : List Bool)
+ (hin : s (ports .input) = List.ofFn bits ++ suffix)
+ (hw : s (ports .width) = List.replicate w true) (ht : s (ports .tmp) = []) :
+ (read ports).Runs (8*(6*w+2)+1) s (installStacks ports s (result (s ∘ ports)
+ (fun i => BurstRAM.wordBits ((RAMSerialization.arrayBits 8 w).symm bits i)) suffix)) := by
+ apply read_runs ports hp s w _ suffix (fun _ => BurstRAM.length_wordBits _)
+ · rwa [← raw_eq_flatten_words]
+ · exact hw
+ · exact ht
+
+open RAMLayout
+
+/-- The incident stack exposes its send field, then its receive field, then
+the unchanged sorting wires. This includes both zero-clamped boundary fields. -/
+theorem incident_prefix {α : Type*} {d H w : ℕ} (inc : Fin (width d H w) → α) :
+ List.ofFn inc =
+ List.ofFn (fun j => inc (offset d H w (.inl (0, j)))) ++
+ List.ofFn (fun j => inc (offset d H w (.inl (1, j)))) ++
+ (List.ofFn inc).drop (16*w) := by
+ let head := fun i : Fin (2*(8*w)) => inc (Fin.castAdd (layerCount d * (2*blockBits H w)) i)
+ let tail := fun i : Fin (layerCount d * (2*blockBits H w)) => inc (Fin.natAdd (2*(8*w)) i)
+ have hs : List.ofFn inc = List.ofFn head ++ List.ofFn tail := List.ofFn_add
+ have hd : (List.ofFn inc).drop (16*w) = List.ofFn tail := by
+ rw [hs, show 16*w = (List.ofFn head).length by simp [head]; omega, List.drop_left]
+ rw [hd, hs, raw_eq_flatten head]
+ simp only [List.ofFn_succ, List.ofFn_zero, List.flatten_cons, List.flatten_nil, List.append_nil]
+ rfl
+
+end RAMTape.SuccessorFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorFormat.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorFormat.lean
new file mode 100644
index 0000000000..e614e6a599
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorFormat.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorTags
+import OAI.Computability.VPVNP.RAMSuccessorDecodeCost
+
+/-!
+# The finite control test for an eight-word successor field
+
+The bit-stack machine retains the small tags of the eight words and a separate
+unsigned cost comparison. These finite data decide exactly the canonical
+encoding test, or the all-zero clamp at a missing edge.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successor
+
+open BurstRAM RAMMemory RAMSerialization SuccessorTags
+
+/-- One small integer tag for each of the eight words in a successor message. -/
+abbrev Tags := Fin 8 → Tag
+
+/-- Empty record padding is fixed in all five words. -/
+def recordOK (t : Tags) : Bool := decide (
+ t 3 = .one ∨ t 3 = .two ∨ t 3 = .three ∨
+ t 3 = .zero ∧ t 4 = .zero ∧ t 5 = .zero ∧ t 6 = .zero ∧ t 7 = .zero)
+
+/-- The zero clamp is separate from a regular, present message. -/
+def valid (present : Bool) (t : Tags) (costOK : Bool) : Bool :=
+ if present then (decide (t 0 = .one ∨ t 0 = .two ∧ t 2 = .zero)) && costOK && recordOK t
+ else decide (∀ j, t j = .zero)
+
+private theorem tagSmall (n : ℕ) :
+ (Tag.ofNat n = .zero ↔ n = 0) ∧ (Tag.ofNat n = .one ↔ n = 1) ∧
+ (Tag.ofNat n = .two ↔ n = 2) ∧ (Tag.ofNat n = .three ↔ n = 3) := by
+ by_cases h : 4 ≤ n
+ · rw [Tag.ofNat_large h]
+ simp; omega
+ · have : n = 0 ∨ n = 1 ∨ n = 2 ∨ n = 3 := by omega
+ rcases this with rfl | rfl | rfl | rfl <;> decide
+
+variable {w cap : ℕ}
+
+/-- Classify the unsigned value of each successor word by its small integer tag. -/
+def wordTags (a : Fin 8 → Word w) : Tags := fun i ↦ Tag.ofNat (a i).val
+
+private def GoodRecord (a : Fin 8 → Word w) : Prop :=
+ (a 3).val = 1 ∨ (a 3).val = 2 ∨ (a 3).val = 3 ∨
+ (a 3).val = 0 ∧ (a 4).val = 0 ∧ (a 5).val = 0 ∧ (a 6).val = 0 ∧ (a 7).val = 0
+
+private theorem goodRecord_iff (hw : 2 ≤ w) (a : Fin 8 → Word w) :
+ GoodRecord a ↔ ∃ r : Option (WordRecord w),
+ ∀ i : Fin 5, (recordFormat hw).words r i = a (Fin.natAdd 3 i) := by
+ constructor
+ · rintro (hi | hr | hw' | he)
+ · refine ⟨some ⟨.init, a 4, a 5, a 6, a 7⟩, fun i ↦ ?_⟩
+ fin_cases i <;> first | rfl | exact Fin.ext hi.symm
+ · refine ⟨some ⟨.read, a 4, a 5, a 6, a 7⟩, fun i ↦ ?_⟩
+ fin_cases i <;> first | rfl | exact Fin.ext hr.symm
+ · refine ⟨some ⟨.write, a 4, a 5, a 6, a 7⟩, fun i ↦ ?_⟩
+ fin_cases i <;> first | rfl | exact Fin.ext hw'.symm
+ · obtain ⟨h3, h4, h5, h6, h7⟩ := he
+ refine ⟨none, fun i ↦ ?_⟩
+ fin_cases i <;> apply Fin.ext <;> first | exact h3.symm | exact h4.symm | exact h5.symm | exact h6.symm | exact h7.symm
+ · rintro ⟨_ | ⟨kind, addr, val, start, ord⟩, he⟩
+ · exact .inr (.inr (.inr ⟨(congrArg Fin.val (he 0)).symm, (congrArg Fin.val (he 1)).symm,
+ (congrArg Fin.val (he 2)).symm, (congrArg Fin.val (he 3)).symm, (congrArg Fin.val (he 4)).symm⟩))
+ · have h := (congrArg Fin.val (he 0)).symm
+ cases kind with
+ | init => exact .inl h
+ | read => exact .inr (.inl h)
+ | write => exact .inr (.inr (.inl h))
+
+/-- A present field passes exactly when all eight saved words have the unique
+canonical encoding. Acceptance at the cap is allowed and has state word zero. -/
+theorem valid_present_iff (hw : 2 ≤ w) (hc : cap < 2 ^ w) (a : Fin 8 → Word w) :
+ valid true (wordTags a) (decide ((a 1).val ≤ cap)) = true ↔
+ ∃ x : Successor w cap, (successorFormat hw hc).words x = a := by
+ simp only [valid, ↓reduceIte, Bool.and_eq_true, decide_eq_true_eq, wordTags, recordOK,
+ (tagSmall _).1, (tagSmall _).2.1, (tagSmall _).2.2.1, (tagSmall _).2.2.2]
+ change ((_ ∨ _ ∧ _) ∧ _) ∧ GoodRecord a ↔ _
+ rw [goodRecord_iff hw]
+ constructor
+ · rintro ⟨⟨hstatus, hcost⟩, r, hr⟩
+ let c : Fin (cap + 1) := ⟨(a 1).val, Nat.lt_succ_of_le hcost⟩
+ rcases hstatus with hrun | ⟨hhalt, hz⟩
+ · refine ⟨⟨some (a 2), c, r⟩, funext (Fin.addCases (m := 3) (n := 5) (fun i ↦ ?_) (fun i ↦ (Fin.append_right _ _ i).trans (hr i)))⟩
+ fin_cases i <;> first | rfl | exact Fin.ext hrun.symm
+ · refine ⟨⟨none, c, r⟩, funext (Fin.addCases (m := 3) (n := 5) (fun i ↦ ?_) (fun i ↦ (Fin.append_right _ _ i).trans (hr i)))⟩
+ fin_cases i <;> first | rfl | exact Fin.ext hhalt.symm | exact Fin.ext hz.symm
+ · rintro ⟨⟨state, cost, last⟩, rfl⟩
+ refine ⟨⟨?_, Nat.le_of_lt_succ cost.isLt⟩, last, fun i ↦ (Fin.append_right _ _ i).symm⟩
+ cases state with
+ | none => exact .inr ⟨rfl, rfl⟩
+ | some _ => exact .inl rfl
+
+theorem valid_clamp_iff (a : Fin 8 → Word w) (costOK : Bool) :
+ valid false (wordTags a) costOK = true ↔ a = fun _ ↦ 0 := by
+ simp only [valid, Bool.false_eq_true, ↓reduceIte, decide_eq_true_eq, wordTags, (tagSmall _).1]
+ exact ⟨fun h ↦ funext fun i ↦ Fin.ext (h i), fun h i ↦ congrArg Fin.val (congrFun h i)⟩
+
+/-- Equality with the word-level validator on every bit pattern. -/
+theorem valid_present_bits (hw : 2 ≤ w) (hc : cap < 2 ^ w) (b : Fin (8 * w) → Bool) :
+ let a := (arrayBits 8 w).symm b
+ valid true (wordTags a) (decide ((a 1).val ≤ cap)) = (scanSuccessor hw hc b).1.2 := by
+ apply Bool.eq_iff_iff.mpr
+ rw [valid_present_iff hw hc, scanSuccessor_valid, Format.encode]
+ constructor
+ · rintro ⟨x, hx⟩
+ rw [← hx, Format.parse_words, hx, Equiv.apply_symm_apply]
+ · intro he
+ exact ⟨_, (arrayBits 8 w).eq_symm_apply.mpr he.symm⟩
+
+end RAMTape.Successor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorGuard.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorGuard.lean
new file mode 100644
index 0000000000..36090558bb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorGuard.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessors
+import OAI.Computability.VPVNP.StructuredStackCount
+import OAI.Computability.VPVNP.StructuredStackTotal
+
+/-!
+# Rejecting malformed successor fields
+
+The field reader produces separate validity bits for the send and receive.
+The guard consumes those bits, continues only when both are true, and
+otherwise halts with rejection. This instruction table can be linked directly
+to the processor's call loop.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successors
+
+open BurstRAM RAMSerialization RAMLayout
+
+/-- States for testing the send and receive verdicts and halting on a failed test. -/
+inductive GuardState where | send | receive | reject
+ deriving DecidableEq
+
+instance : Fintype GuardState := derive_fintype% _
+
+/-- Consume the send verdict followed by the receive verdict, continuing only if both are
+present and true. -/
+def guard : FiniteRoutine Port := FiniteRoutine.ofRoutine ({
+ entry := .send
+ code
+ | .send => .pop (.verdict .send) fun b ↦ if b = some true then some .receive else some .reject
+ | .receive => .pop (.verdict .receive) fun b ↦ if b = some true then none else some .reject
+ | .reject => .halt false
+ } : Routine Port GuardState)
+
+/-- Read the two successor fields and then guard the continuation with both validity bits. -/
+def checked : FiniteRoutine Port := read.followedBy guard
+
+/-- Pop the send and receive verdict stacks after a successful guard. -/
+def guardResult (s : Stacks Port) : Stacks Port :=
+ Function.update (Function.update s (.verdict .send) (s (.verdict .send)).tail)
+ (.verdict .receive) (s (.verdict .receive)).tail
+
+theorem guard_runs (s : Stacks Port) (hs : (s (.verdict .send)).head? = some true)
+ (hr : (s (.verdict .receive)).head? = some true) : guard.Runs 2 s (guardResult s) := by
+ let t := Function.update s (.verdict .send) (s (.verdict .send)).tail
+ have hs' : StackStep guard.body.standalone (some GuardState.send) s (some GuardState.receive) t := by
+ simpa only [hs, ite_true] using (StackStep.pop (s := s) (code := guard.body.standalone)
+ (show guard.body.standalone (some GuardState.send) = .pop (.verdict .send)
+ (fun b ↦ if b = some true then some GuardState.receive else some GuardState.reject) from rfl))
+ have ht : t (.verdict .receive) = s (.verdict .receive) := rfl
+ have hr' : StackStep guard.body.standalone (some GuardState.receive) t none (guardResult s) := by
+ simpa only [ht, hr, ite_true, guardResult, t] using (StackStep.pop (s := t) (code := guard.body.standalone)
+ (show guard.body.standalone (some GuardState.receive) = .pop (.verdict .receive)
+ (fun b ↦ if b = some true then none else some GuardState.reject) from rfl))
+ exact .cons hs' (.cons hr' (.nil ..))
+
+theorem guard_count (s : Stacks Port) (c : ℕ → Stacks Port → ℕ) (fuel : ℕ) :
+ guard.body.count c (fuel+2) s =
+ if (s (.verdict .send)).head? = some true ∧ (s (.verdict .receive)).head? = some true
+ then c fuel (guardResult s) else 0 := by
+ by_cases hs : (s (.verdict .send)).head? = some true
+ · by_cases hr : (s (.verdict .receive)).head? = some true
+ · simpa [hs, hr] using (guard_runs s hs hr).count_eq c fuel
+ · cases fuel <;> simp [Routine.count, Routine.countFrom, guard, FiniteRoutine.ofRoutine,
+ hs, hr]
+ · simp [Routine.count, Routine.countFrom, guard, FiniteRoutine.ofRoutine, hs]
+
+theorem checked_count_of_read {s out : Stacks Port} {n : ℕ} (h : read.Runs n s out)
+ (c : ℕ → Stacks Port → ℕ) (fuel : ℕ) :
+ checked.body.count c (fuel + 2 + n) s =
+ if (out (.verdict .send)).head? = some true ∧ (out (.verdict .receive)).head? = some true
+ then c fuel (guardResult out) else 0 := by
+ change (read.body.followedBy guard.body).count _ _ _ = _
+ rw [Routine.count_followedBy, h.count_eq, guard_count]
+
+/-- The third guard instruction suffices even when the second validity bit
+is false and the explicit rejecting halt must still execute. -/
+theorem checked_allStops_of_read {s out : Stacks Port} {n : ℕ} (h : read.Runs n s out)
+ (c : ℕ → Stacks Port → Prop) (fuel : ℕ) :
+ checked.body.AllStops c (fuel + 3 + n) s ↔
+ ((out (.verdict .send)).head? = some true ∧ (out (.verdict .receive)).head? = some true →
+ c (fuel + 1) (guardResult out)) := by
+ change (read.body.followedBy guard.body).AllStops _ _ _ ↔ _
+ rw [Routine.allStops_followedBy, h.allStops_iff]
+ by_cases hs : (out (.verdict .send)).head? = some true
+ · by_cases hr : (out (.verdict .receive)).head? = some true
+ · simpa [hs, hr] using (guard_runs out hs hr).allStops_iff c (fuel+1)
+ · simp [Routine.AllStops, Routine.AllStopsFrom, guard, FiniteRoutine.ofRoutine, hs, hr]
+ · simp [Routine.AllStops, Routine.AllStopsFrom, guard, FiniteRoutine.ofRoutine, hs]
+
+end RAMTape.Successors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorInitial.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorInitial.lean
new file mode 100644
index 0000000000..0cc86e57b5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorInitial.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.RAMTapeWordOperands
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-!
+# The public initial state at the first processor
+
+After checking the incoming zero clamp, the first processor needs the public
+initial word in its state register and a running flag. The word-copy scan
+overwrites the destination while restoring the public word. The next two
+instructions replace the top status bit and preserve the tail of that stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorInitial
+
+open TapeWord
+
+/-- Ports for copying the public initial word into the incoming state register and setting its
+running bit. -/
+inductive Port where
+ | initial | state | running | sourceTmp | outTmp
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+private def copyPorts : ScanPort → Port
+ | .left => .initial
+ | .right => .sourceTmp
+ | .tmp => .outTmp
+ | .out => .state
+
+private theorem copyPorts_injective : Function.Injective copyPorts := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [copyPorts]
+
+private def normal : Operand.State Unit → Bool
+ | .done _ => true
+ | _ => false
+
+variable {K : Type}
+
+private def copy (ports : Port → K) : FiniteRoutine K :=
+ FiniteRoutine.ofStackCode (Operand.code Operand.copyBit) (ports ∘ copyPorts) (.clear ()) normal
+
+private theorem copy_runs [DecidableEq K] {ports : Port → K} (hp : Function.Injective ports)
+ (s : Stacks K) (hs : s (ports .sourceTmp) = []) (ho : s (ports .outTmp) = []) :
+ (copy ports).Runs ((s (ports .state)).length + 7*(s (ports .initial)).length + 3) s
+ (Function.update s (ports .state) (s (ports .initial))) := by
+ refine FiniteRoutine.runs_ofStackCode_framed (hp.comp copyPorts_injective) (normal := normal)
+ rfl rfl (fun q h => ?_) (Operand.copy_run _ _) ?_ ?_ ?_
+ · cases q <;> first | rfl | contradiction
+ · intro k
+ cases k <;> first | rfl | exact hs | exact ho
+ · intro k
+ cases k <;> simp [copyPorts, scanStacks, Function.update, hp.eq_iff, hs, ho]
+ · intro j hj
+ exact Function.update_of_ne (Ne.symm (hj .out)) ..
+
+private def setRunning (port : K) : FiniteRoutine K := FiniteRoutine.ofRoutine {
+ entry := false
+ code
+ | false => .pop port fun _ => some true
+ | true => .push port true none }
+
+private theorem setRunning_runs [DecidableEq K] (port : K) (s : Stacks K) :
+ (setRunning port).Runs 2 s (Function.update s port (true :: (s port).tail)) := by
+ refine .cons (.pop rfl) (.cons (.push rfl) ?_)
+ simp only [Function.update_self, Function.update_idem]
+ exact .nil ..
+
+/-- At an absent incoming edge, install the initial running configuration. -/
+def normalize (ports : Port → K) : FiniteRoutine K :=
+ (copy ports).followedBy (setRunning (ports .running))
+
+/-- With two empty scratch stacks, normalization takes eight instructions per
+word bit plus five fixed instructions, regardless of the old state and flag. -/
+theorem normalize_runs [DecidableEq K] {ports : Port → K} (hp : Function.Injective ports)
+ (s : Stacks K) {w : ℕ} (hs : s (ports .sourceTmp) = []) (ho : s (ports .outTmp) = [])
+ (hi : (s (ports .initial)).length = w) (hd : (s (ports .state)).length = w) :
+ (normalize ports).Runs (8*w+5) s (Function.update (Function.update s (ports .state)
+ (s (ports .initial))) (ports .running) (true :: (s (ports .running)).tail)) := by
+ have copied := copy_runs hp s hs ho
+ have set := setRunning_runs (ports .running) (Function.update s (ports .state) (s (ports .initial)))
+ have hne : ports .running ≠ ports .state := fun h => Port.noConfusion (hp h)
+ rw [hi, hd] at copied
+ rw [Function.update_of_ne hne] at set
+ rw [show 8*w+5 = (w+7*w+3)+2 by omega]
+ exact FiniteRoutine.Runs.followedBy copied set
+
+end RAMTape.SuccessorInitial
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorParameters.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorParameters.lean
new file mode 100644
index 0000000000..a892d12bba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorParameters.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorPowerBit
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+import OAI.Computability.VPVNP.RAMTapeCeilLog
+import OAI.Computability.VPVNP.RAMTapeMapWord
+
+/-!
+# Building the global cost cap on the processor's stack tape
+
+The input parser retains the unary site logarithm `d`, bucket capacity `H`
+and word width `w`. Compute `e = ⌈log₂ H⌉` on a copy of the tally, then set
+bit `d+e` in a zero word. For `H = 2^e` this produces exactly the w-bit
+global cost cap `SH`, and retains all the tallies needed by the site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorParameters
+
+open BurstRAM
+
+/-- Unary dimensions, intermediate tally and scratch stacks, and the binary cap register used
+to construct the global cost cap. -/
+inductive Port where | siteLog | bucket | width | bucketLog | cap | work | tmp
+ deriving DecidableEq
+instance : Fintype Port := derive_fintype% _
+
+/-- Store the site logarithm, bucket capacity, word width, bucket logarithm, and working count
+in unary alongside the supplied cap bits. -/
+def bank (d H w e work : ℕ) (cap : List Bool) : Stacks Port
+ | .siteLog => List.replicate d true
+ | .bucket => List.replicate H true
+ | .width => List.replicate w true
+ | .bucketLog => List.replicate e true
+ | .work => List.replicate work true
+ | .cap => cap
+ | .tmp => []
+
+private def logPorts : CeilLog.Port → Port
+ | .src => .work
+ | .tmp => .tmp
+ | .out => .bucketLog
+
+private def bitPorts : SuccessorPowerBit.Port → Port
+ | .exponent => .work
+ | .word => .cap
+ | .tmp => .tmp
+
+private theorem logPorts_inj : Function.Injective logPorts := by decide
+private theorem bitPorts_inj : Function.Injective bitPorts := by decide
+
+private def takeLog : FiniteRoutine Port :=
+ FiniteRoutine.ofStackCode (CeilLog.code 1) logPorts .scan (· == .done)
+
+private def addWork (src : Port) : FiniteRoutine Port :=
+ SuccessorFields.prependCopy src .work .tmp
+
+private def zeros : FiniteRoutine Port := WordCopy.mapWord .tmp .cap (fun _ ↦ false) .width
+
+/-- One fixed table, including both the logarithm and power-bit scans. -/
+def prepare : FiniteRoutine Port :=
+ (((((addWork .bucket).followedBy takeLog).followedBy (addWork .siteLog)).followedBy
+ (addWork .bucketLog)).followedBy zeros).followedBy (SuccessorPowerBit.routine bitPorts)
+
+private theorem addWork_runs (d H w e m : ℕ) (cap : List Bool) (src : Port) (k : ℕ)
+ (hs : src ≠ .work) (ht : src ≠ .tmp) (hk : bank d H w e m cap src = List.replicate k true) :
+ (addWork src).Runs (5*k+2) (bank d H w e m cap) (bank d H w e (k+m) cap) := by
+ have h := SuccessorFields.prependCopy_runs src .work .tmp hs ht (by decide) (bank d H w e m cap) rfl
+ have he : Function.update (bank d H w e m cap) .work (List.replicate k true ++ List.replicate m true) =
+ bank d H w e (k+m) cap := by
+ funext j
+ cases j <;> first | rfl | exact (List.replicate_add ..).symm
+ simp only [hk, List.length_replicate] at h
+ exact he ▸ h
+
+private theorem takeLog_runs (d e w : ℕ) :
+ takeLog.Runs (CeilLog.cost 1 (2^e)) (bank d (2^e) w 0 (2^e) []) (bank d (2^e) w e 0 []) := by
+ have h := CeilLog.runs 1 (2^e) []
+ rw [Nat.clog_pow 2 e (by decide), Nat.one_mul, List.append_nil] at h
+ apply FiniteRoutine.runs_ofStackCode_framed logPorts_inj (normal := (· == .done)) rfl rfl
+ (fun q he ↦ by simp only [beq_iff_eq] at he; subst q; rfl) h
+ · intro j; cases j <;> rfl
+ · intro j; cases j <;> rfl
+ · intro j hj
+ cases j <;> first | rfl | exact (hj .out rfl).elim | exact (hj .src rfl).elim
+
+private theorem zeros_runs (d H w e m : ℕ) :
+ zeros.Runs (5*w+2) (bank d H w e m []) (bank d H w e m (List.replicate w false)) := by
+ have h := WordCopy.mapWord_run Port.tmp .cap (fun _ ↦ false) (src := .width) (by decide)
+ (by decide) (by decide) (bank d H w e m []) rfl
+ have he : Function.update (bank d H w e m []) .cap (List.replicate w false) =
+ bank d H w e m (List.replicate w false) := by funext j; cases j <;> rfl
+ simpa only [zeros, bank, List.length_replicate, List.map_replicate, List.reverse_replicate,
+ List.append_nil, ← he] using h
+
+/-- The global cap word with value two to the sum of the site and bucket logarithms, when its
+set bit fits the width. -/
+def capWord (d e w : ℕ) (h : d + e < w) : Word w :=
+ ⟨2^d * 2^e, by rw [← pow_add]; exact Nat.pow_lt_pow_right (by decide) h⟩
+
+private theorem bit_runs (d e w : ℕ) (h : d+e < w) :
+ (SuccessorPowerBit.routine bitPorts).Runs (5*(d+e)+4)
+ (bank d (2^e) w e (d+e) (List.replicate w false))
+ (bank d (2^e) w e 0 (BurstRAM.wordBits (capWord d e w h))) := by
+ apply FiniteRoutine.runs_ofStackCode_framed bitPorts_inj (normal := (· == .done)) rfl rfl
+ (fun q he ↦ by simp only [beq_iff_eq] at he; subst q; rfl) (SuccessorPowerBit.run (d+e) w h)
+ · intro j; cases j <;> rfl
+ · intro j
+ cases j <;> first | rfl | exact congrArg BurstRAM.wordBits (Fin.ext (pow_add 2 d e).symm)
+ · intro j hj
+ cases j <;> first | rfl | exact (hj .word rfl).elim | exact (hj .exponent rfl).elim
+
+/-- Number of steps to construct the cap word from the site logarithm, power-of-two bucket
+capacity, and word width. -/
+def steps (d e w : ℕ) : ℕ :=
+ 5*(2^e)+2 + CeilLog.cost 1 (2^e) + (5*d+2) + (5*e+2) + (5*w+2) + (5*(d+e)+4)
+
+theorem prepare_runs (d e w : ℕ) (h : d+e < w) :
+ prepare.Runs (steps d e w) (bank d (2^e) w 0 0 [])
+ (bank d (2^e) w e 0 (BurstRAM.wordBits (capWord d e w h))) := by
+ have ha := addWork_runs d (2^e) w 0 0 [] .bucket (2^e) (by decide) (by decide) rfl
+ have hb := takeLog_runs d e w
+ have hd := addWork_runs d (2^e) w e 0 [] .siteLog d (by decide) (by decide) rfl
+ have he := addWork_runs d (2^e) w e d [] .bucketLog e (by decide) (by decide) rfl
+ rw [Nat.add_comm e d] at he
+ exact (((((ha.followedBy hb).followedBy hd).followedBy he).followedBy
+ (zeros_runs ..)).followedBy (bit_runs d e w h))
+
+/-- Install the parameter adapter in a caller's bank. Only the two output
+registers are changed, and the work and temporary stacks return empty. -/
+theorem prepare_onPorts_runs {K : Type} [DecidableEq K] (ports : Port → K) (hp : Function.Injective ports)
+ (s : Stacks K) (d e w : ℕ) (h : d+e < w)
+ (hs : ∀ j, s (ports j) = bank d (2^e) w 0 0 [] j) :
+ (prepare.onPorts ports).Runs (steps d e w) s
+ (Function.update (Function.update s (ports .bucketLog) (List.replicate e true))
+ (ports .cap) (BurstRAM.wordBits (capWord d e w h))) := by
+ apply FiniteRoutine.runs_onPorts_framed _ hp (prepare_runs d e w h) hs
+ · intro j
+ cases j <;> simp [hp.eq_iff, hs, bank]
+ · intro j hj
+ simp [Function.update_of_ne (Ne.symm (hj .cap)), Function.update_of_ne (Ne.symm (hj .bucketLog))]
+
+/-- Linear in the unary inputs and the word length. -/
+theorem steps_le (d e w : ℕ) : steps d e w ≤ 38*(2^e)+10*(d+e)+5*w+45 := by
+ have h := CeilLog.cost_le 1 (2^e)
+ unfold steps
+ omega
+
+end RAMTape.SuccessorParameters
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorPowerBit.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorPowerBit.lean
new file mode 100644
index 0000000000..4f0b0a3b6c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorPowerBit.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+
+/-! # Writing a power of two into a fixed-width little-endian word -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorPowerBit
+
+open BurstRAM TapeWord
+
+/-- Stacks for the unary exponent, destination word, and saved zero bits. -/
+inductive Port where | exponent | word | tmp
+ deriving DecidableEq
+instance : Fintype Port := derive_fintype% _
+
+/-- Control states for skipping low bits, setting the power-of-two bit, and restoring the lower
+zeros. -/
+inductive State where | scan | skip | save | set | putOne | restore | putZero | done | reject
+ deriving DecidableEq
+instance : Fintype State := derive_fintype% _
+
+/-- Consume the unary exponent, write a one at that bit position, and fill the lower positions
+with zeros, rejecting if the word is too short. -/
+def code : StackCode Port State
+ | .scan => .pop .exponent fun b ↦ b.elim .set (fun _ ↦ .skip)
+ | .skip => .pop .word fun b ↦ b.elim .reject (fun _ ↦ .save)
+ | .save => .push .tmp false .scan
+ | .set => .pop .word fun b ↦ b.elim .reject (fun _ ↦ .putOne)
+ | .putOne => .push .word true .restore
+ | .restore => .pop .tmp fun b ↦ b.elim .done (fun _ ↦ .putZero)
+ | .putZero => .push .word false .restore
+ | .done => .halt true
+ | .reject => .halt false
+
+/-- Initialize the exponent as unary marks and the scratch stack as zeros alongside the
+supplied word bits. -/
+def bank (exp : ℕ) (word : List Bool) (tmp : ℕ) : Stacks Port
+ | .exponent => List.replicate exp true
+ | .word => word
+ | .tmp => List.replicate tmp false
+
+private def frame (exp word tmp : List Bool) : Stacks Port
+ | .exponent => exp
+ | .word => word
+ | .tmp => tmp
+
+private theorem write_frame (e w t xs : List Bool) (j : Port) :
+ Function.update (frame e w t) j xs =
+ match j with
+ | .exponent => frame xs w t
+ | .word => frame e xs t
+ | .tmp => frame e w xs := by funext i; cases i <;> cases j <;> rfl
+
+local macro "power_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [frame, write_frame, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_none, Option.elim_some])
+
+private theorem forward (k t : ℕ) (suffix : List Bool) :
+ StackRuns code (3*k+1) .scan
+ (frame (List.replicate k true) (List.replicate k false ++ suffix) (List.replicate t false))
+ .set (frame [] suffix (List.replicate (k+t) false)) := by
+ induction k generalizing t with
+ | zero =>
+ simp only [List.replicate_zero, List.nil_append, Nat.zero_add, Nat.mul_zero]
+ power_step
+ exact .nil ..
+ | succ k ih =>
+ simp only [List.replicate_succ, List.cons_append, Nat.mul_succ, Nat.add_assoc]
+ power_step
+ power_step
+ power_step
+ simpa [List.replicate_succ, Nat.add_comm, Nat.add_left_comm, Nat.add_assoc] using ih (t+1)
+
+private theorem backward (k : ℕ) (bits : List Bool) :
+ StackRuns code (2*k+1) .restore (frame [] bits (List.replicate k false))
+ .done (frame [] (List.replicate k false ++ bits) []) := by
+ induction k generalizing bits with
+ | zero =>
+ simp only [List.replicate_zero, List.nil_append, Nat.mul_zero, Nat.zero_add]
+ power_step
+ exact .nil ..
+ | succ k ih =>
+ rw [List.replicate_succ, Nat.mul_succ]
+ power_step
+ power_step
+ rw [← List.replicate_succ, List.replicate_succ', List.append_assoc, List.singleton_append]
+ exact ih (false::bits)
+
+theorem run (k w : ℕ) (hk : k < w) :
+ StackRuns code (5*k+4) .scan (bank k (List.replicate w false) 0) .done
+ (bank 0 (BurstRAM.wordBits (⟨2^k, Nat.pow_lt_pow_right (by decide) hk⟩ : Word w)) 0) := by
+ let suffix := List.replicate (w-(k+1)) false
+ have hf := forward k 0 (false :: suffix)
+ have he : List.replicate k false ++ false :: suffix = List.replicate w false := by
+ rw [show false :: suffix = List.replicate (w-(k+1)+1) false from (List.replicate_succ ..).symm,
+ ← List.replicate_add, show k + (w-(k+1)+1) = w by omega]
+ rw [he, Nat.add_zero] at hf
+ have hm : StackRuns code 2 .set (frame [] (false::suffix) (List.replicate k false))
+ .restore (frame [] (true::suffix) (List.replicate k false)) := by
+ power_step
+ power_step
+ exact .nil ..
+ have hbits : List.replicate k false ++ true :: suffix =
+ BurstRAM.wordBits (⟨2^k, Nat.pow_lt_pow_right (by decide) hk⟩ : Word w) := by
+ apply eq_of_length_value
+ · simp [suffix]; omega
+ · simp [value_append, value, suffix, value_wordBits]
+ rw [← hbits, show 5*k+4 = (3*k+1)+2+(2*k+1) by omega]
+ exact (hf.trans hm).trans (backward k _)
+
+/-- Install the bit-setting instruction table on the caller's stacks, entering at the exponent
+scan. -/
+def routine {K : Type} (ports : Port → K) : FiniteRoutine K :=
+ FiniteRoutine.ofStackCode code ports .scan (· == .done)
+
+end RAMTape.SuccessorPowerBit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorRecord.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorRecord.lean
new file mode 100644
index 0000000000..b9f0b2a1b5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorRecord.lean
@@ -0,0 +1,166 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-!
+# Prepending a five-word successor record
+
+The record fields are words 3 through 7 of the successor message. To
+prepend them in increasing order, the machine visits them in decreasing
+order. For each word it reverses the bits onto a scratch stack, then pops
+them back to both the source and the record.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorFields
+
+/-- Ports used to prepend successor words three through seven to the saved record while
+restoring the word stacks. -/
+inductive RecordPort where
+ | tmp | record | word (i : Fin 8)
+ deriving DecidableEq, Fintype
+
+private inductive CopyPort where
+ | src | tmp | dst
+ deriving DecidableEq
+
+private inductive CopyState where
+ | read | save (b : Bool) | restore | putSource (b : Bool) | putRecord (b : Bool) | done
+ deriving DecidableEq, Fintype
+
+private def copyCode : StackCode CopyPort CopyState
+ | .read => .pop .src fun b => b.elim .restore .save
+ | .save b => .push .tmp b .read
+ | .restore => .pop .tmp fun b => b.elim .done .putSource
+ | .putSource b => .push .src b (.putRecord b)
+ | .putRecord b => .push .dst b .restore
+ | .done => .halt true
+
+private def frame (x tmp dst : List Bool) : Stacks CopyPort
+ | .src => x
+ | .tmp => tmp
+ | .dst => dst
+
+private theorem update_frame (x tmp dst bits : List Bool) (k : CopyPort) :
+ Function.update (frame x tmp dst) k bits = match k with
+ | .src => frame bits tmp dst
+ | .tmp => frame x bits dst
+ | .dst => frame x tmp bits := by
+ cases k <;> funext j <;> cases j <;> rfl
+
+local macro "copy_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [frame, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_frame])
+
+private theorem read_runs (x tmp dst : List Bool) :
+ StackRuns copyCode (2*x.length+1) .read (frame x tmp dst)
+ .restore (frame [] (x.reverse ++ tmp) dst) := by
+ induction x generalizing tmp with
+ | nil => copy_step; exact .nil ..
+ | cons b x ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ copy_step
+ copy_step
+ exact ih (b :: tmp)
+
+private theorem restore_runs (x tmp dst : List Bool) :
+ StackRuns copyCode (3*tmp.length+1) .restore (frame x tmp dst)
+ .done (frame (tmp.reverse ++ x) [] (tmp.reverse ++ dst)) := by
+ induction tmp generalizing x dst with
+ | nil => copy_step; exact .nil ..
+ | cons b tmp ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ copy_step
+ copy_step
+ copy_step
+ exact ih (b :: x) (b :: dst)
+
+private theorem copy_runs (x dst : List Bool) :
+ StackRuns copyCode (5*x.length+2) .read (frame x [] dst) .done (frame x [] (x ++ dst)) := by
+ have h := read_runs x [] dst
+ rw [List.append_nil] at h
+ have h' := restore_runs [] x.reverse dst
+ simp only [List.reverse_reverse, List.append_nil, List.length_reverse] at h'
+ rw [show 5*x.length+2 = (2*x.length+1) + (3*x.length+1) by omega]
+ exact h.trans h'
+
+private def normal : CopyState → Bool
+ | .done => true
+ | _ => false
+
+private def copyPorts {K : Type} (src dst tmp : K) : CopyPort → K
+ | .src => src
+ | .tmp => tmp
+ | .dst => dst
+
+/-- Prepend the contents of one bit stack to another, preserving their order
+and restoring the source. The temporary stack must start empty. -/
+def prependCopy {K : Type} (src dst tmp : K) : FiniteRoutine K :=
+ FiniteRoutine.ofStackCode copyCode (copyPorts src dst tmp) .read normal
+
+/-- Each bit costs two instructions to save it and three to restore and copy it.
+The two empty pops finish the scans. Only the destination changes. -/
+theorem prependCopy_runs {K : Type} [DecidableEq K] (src dst tmp : K)
+ (hsd : src ≠ dst) (hst : src ≠ tmp) (hdt : dst ≠ tmp) (s : Stacks K) (ht : s tmp = []) :
+ (prependCopy src dst tmp).Runs (5 * (s src).length + 2) s
+ (Function.update s dst (s src ++ s dst)) := by
+ have inj : Function.Injective (copyPorts src dst tmp) := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [copyPorts]
+ apply FiniteRoutine.runs_ofStackCode_framed inj (normal := normal) rfl rfl
+ (fun q h => by cases q <;> first | rfl | contradiction) (copy_runs (s src) (s dst))
+ · intro i
+ cases i <;> first | rfl | exact ht
+ · intro i
+ cases i <;> simp [copyPorts, frame, hsd, hdt.symm, ht]
+ · intro i h
+ exact Function.update_of_ne (Ne.symm (h .dst)) ..
+
+private def copyField {K : Type} (ports : RecordPort → K) (i : Fin 8) : FiniteRoutine K :=
+ prependCopy (ports (.word i)) (ports .record) (ports .tmp)
+
+private theorem copyField_runs {K : Type} [DecidableEq K] {ports : RecordPort → K}
+ (hp : Function.Injective ports) (i : Fin 8) (s : Stacks K) (ht : s (ports .tmp) = []) :
+ (copyField ports i).Runs (5*(s (ports (.word i))).length+2) s
+ (Function.update s (ports .record) (s (ports (.word i)) ++ s (ports .record))) :=
+ prependCopy_runs _ _ _ (hp.ne (by simp)) (hp.ne (by simp)) (hp.ne (by simp)) s ht
+
+/-- A fixed routine for the record payload, independent of the word width. -/
+def appendRecord {K : Type} (ports : RecordPort → K) : FiniteRoutine K :=
+ ((((copyField ports 7).followedBy (copyField ports 6)).followedBy (copyField ports 5)).followedBy
+ (copyField ports 4)).followedBy (copyField ports 3)
+
+/-- Each word costs two empty pops and five instructions per bit. All
+source and scratch stacks return to their initial contents. -/
+theorem appendRecord_runs {K : Type} [DecidableEq K] {ports : RecordPort → K}
+ (hp : Function.Injective ports) (s : Stacks K) {w : ℕ} (ht : s (ports .tmp) = [])
+ (hlen : ∀ i : Fin 8, 3 ≤ i.val → (s (ports (.word i))).length = w) :
+ (appendRecord ports).Runs (25*w+10) s (Function.update s (ports .record)
+ (s (ports (.word 3)) ++ s (ports (.word 4)) ++ s (ports (.word 5)) ++ s (ports (.word 6))
+ ++ s (ports (.word 7)) ++ s (ports .record))) := by
+ let state (bits : List Bool) := Function.update s (ports .record) bits
+ let word (i : Fin 8) := s (ports (.word i))
+ have step (i : Fin 8) (hi : 3 ≤ i.val) (bits : List Bool) :
+ (copyField ports i).Runs (5*w+2) (state bits) (state (word i ++ bits)) := by
+ have ht' : state bits (ports .tmp) = [] := by simp [state, hp.eq_iff, ht]
+ have hi' : state bits (ports (.word i)) = word i := by
+ simp [state, word, hp.eq_iff]
+ simpa only [hi', word, hlen i hi, state, Function.update_self, Function.update_idem] using
+ copyField_runs hp i (state bits) ht'
+ have h7 := step 7 (by decide) (s (ports .record))
+ have h6 := FiniteRoutine.Runs.followedBy h7 (step 6 (by decide) _)
+ have h5 := FiniteRoutine.Runs.followedBy h6 (step 5 (by decide) _)
+ have h4 := FiniteRoutine.Runs.followedBy h5 (step 4 (by decide) _)
+ have h3 := FiniteRoutine.Runs.followedBy h4 (step 3 (by decide) _)
+ rw [show 25*w+10 = (5*w+2)+(5*w+2)+(5*w+2)+(5*w+2)+(5*w+2) by omega]
+ simpa only [appendRecord, state, word, Function.update_eq_self, List.append_assoc] using h3
+
+end RAMTape.SuccessorFields
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorScan.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorScan.lean
new file mode 100644
index 0000000000..a706773a19
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorScan.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorFormat
+import OAI.Computability.VPVNP.RAMTapeSuccessorTagPreserve
+import OAI.Computability.VPVNP.RAMTapeStackLift
+
+/-!
+# The eight-word tag pass of a successor validator
+
+The finite control scans word seven down to word zero. It stores each tag
+on return from the preserving scan and immediately starts the next word.
+The eight input stacks and the common scratch stack are restored on exit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successor
+
+open SuccessorTags BurstRAM
+
+/-- Control for the eight-word tag scan, retaining the word index, accumulated tags, and
+current word scan state. -/
+inductive TagState where
+ | scan (i : Fin 8) (tags : Tags) (q : KeepState)
+ | done (tags : Tags)
+ deriving DecidableEq, Fintype
+
+/-- Start at word seven with all tag slots zero and the single-word scanner at its first bit. -/
+def tagEntry : TagState := .scan 7 (fun _ => .zero) (.read .first)
+
+private def tagLabel (i : Fin 8) (tags : Tags) : KeepState → TagState
+ | .done t =>
+ let saved := Function.update tags i t
+ if i.val = 0 then .done saved else .scan ⟨i.val - 1, by omega⟩ saved (.read .first)
+ | q => .scan i tags q
+
+/-- Install the eight scans at their respective word ports. The last empty
+scratch pop of each scan goes directly to its continuation. -/
+def tagCode {K : Type*} (word : Fin 8 → K) (tmp : K) : StackCode K TagState
+ | .scan i tags q => (codeKeep (word i) tmp q).rename id (tagLabel i tags)
+ | .done _ => .halt true
+
+variable {K : Type*} [DecidableEq K] (word : Fin 8 → K) (tmp : K) (hne : ∀ i, word i ≠ tmp)
+ (s : Stacks K) (ht : s tmp = []) {w : ℕ} (a : Fin 8 → Word w)
+ (ha : ∀ i, s (word i) = wordBits (a i))
+
+include hne ht ha
+
+private theorem one_tag (i : Fin 8) (tags : Tags) :
+ StackRuns (tagCode word tmp) (4*w+2) (.scan i tags (.read .first)) s
+ (tagLabel i tags (.done (wordTags a i))) s := by
+ have rows (q : KeepState) (h : (codeKeep (word i) tmp q).returns = false) :
+ tagCode word tmp (tagLabel i tags q) = (codeKeep (word i) tmp q).rename id (tagLabel i tags) := by
+ cases q <;> first | rfl | contradiction
+ have scan := (keep_run (word i) tmp (hne i) s ht).lift id Function.injective_id (tagLabel i tags) s rows
+ have hst := installStacks_eq Function.injective_id s s (fun _ => rfl)
+ simpa only [hst, ha, length_wordBits, TapeWord.value_wordBits, wordTags, tagLabel] using scan
+
+private theorem remaining_tags (i : Fin 8) (tags : Tags)
+ (saved : ∀ j : Fin 8, i.val < j.val → tags j = wordTags a j) :
+ StackRuns (tagCode word tmp) ((i.val+1)*(4*w+2)) (.scan i tags (.read .first)) s
+ (.done (wordTags a)) s := by
+ obtain ⟨k, hk⟩ := i
+ induction k generalizing tags with
+ | zero =>
+ let i : Fin 8 := ⟨0, hk⟩
+ have complete : Function.update tags i (wordTags a i) = wordTags a := by
+ funext j
+ by_cases hj : j = i
+ · subst j; exact Function.update_self ..
+ · rw [Function.update_of_ne hj]
+ apply saved j
+ change 0 < j.val
+ exact Nat.pos_of_ne_zero fun h => hj (Fin.ext h)
+ have hstep := one_tag word tmp hne s ht a ha i tags
+ change StackRuns (tagCode word tmp) (4*w+2) (.scan i tags (.read .first)) s (.done (Function.update tags i (wordTags a i))) s at hstep
+ rw [complete] at hstep
+ simpa [i] using hstep
+ | succ k ih =>
+ let i : Fin 8 := ⟨k+1, hk⟩
+ let next := Function.update tags i (wordTags a i)
+ have checked (j : Fin 8) (hj : k < j.val) : next j = wordTags a j := by
+ by_cases he : j = i
+ · subst j; exact Function.update_self ..
+ · rw [show next j = tags j from Function.update_of_ne he ..]
+ apply saved j
+ change k+1 < j.val
+ have hval : j.val ≠ k+1 := fun h => he (Fin.ext h)
+ omega
+ have hstep := one_tag word tmp hne s ht a ha i tags
+ have hrest := ih next (by omega) checked
+ have hlink : tagLabel i tags (.done (wordTags a i)) = .scan ⟨k, by omega⟩ next (.read .first) := by
+ simp [tagLabel, next, i]
+ rw [hlink] at hstep
+ convert hstep.trans hrest using 1
+ change (k+1+1)*_ = _ + (k+1)*_
+ ring
+
+/-- The complete field pass classifies all eight words and preserves the caller's
+stacks. Only the temporary stack must be distinct from each data port. -/
+theorem tag_run :
+ StackRuns (tagCode word tmp) (8*(4*w+2)) tagEntry s (.done (wordTags a)) s := by
+ apply remaining_tags word tmp hne s ht a ha 7 (fun _ => .zero)
+ intro j hj
+ have := j.isLt
+ change 7 < j.val at hj
+ omega
+
+end RAMTape.Successor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorSharedValues.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorSharedValues.lean
new file mode 100644
index 0000000000..7d0377f29d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorSharedValues.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorValues
+import OAI.Computability.VPVNP.RAMValidatorSuccessor
+
+/-!
+# Successor registers on the shared bits of a RAM transcript
+
+Each interior edge has one send array. The receiving site reads those same
+bits at its incoming port. The two endpoints instead read an all-zero field.
+Under the local canonicality checks, the physical registers therefore hold
+the typed messages parsed from the adjacent send arrays.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successors
+
+open BurstRAM RAMSerialization RAMLayout
+
+variable {d e w : ℕ}
+
+/-- Read the outgoing or incoming successor field at a site's incident offset from the shared
+send arrays. -/
+def sharedField (a : SendArrays d (2^e) w) (v : Fin (2^d)) (dir : Fin 2) : Fin (8*w) → Bool :=
+ fun j ↦ RAMLayout.incidentBits a v (offset d (2^e) w (.inl (dir, j)))
+
+/-- Return the parsed outgoing message on an interior send edge, or no message at the last
+site. -/
+def sentMessage (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (a : SendArrays d (2^e) w)
+ (v : Fin (2^d)) : Option (RAMSerialization.Successor w (2^d * 2^e)) :=
+ if h : v.val + 1 < 2^d then some ((parseMessages hw hc a).1 ⟨v.val, by omega⟩) else none
+
+/-- Return the preceding site's parsed send message on an interior receive edge, or no message
+at the first site. -/
+def receivedMessage (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (a : SendArrays d (2^e) w)
+ (v : Fin (2^d)) : Option (RAMSerialization.Successor w (2^d * 2^e)) :=
+ if h : 0 < v.val then some ((parseMessages hw hc a).1 ⟨v.val-1, by have := v.isLt; omega⟩) else none
+
+@[simp] theorem sentMessage_isSome (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) :
+ (sentMessage hw hc a v).isSome = decide (v.val+1 < 2^d) := by
+ by_cases h : v.val+1 < 2^d <;> simp [sentMessage, h]
+
+@[simp] theorem receivedMessage_isSome (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) :
+ (receivedMessage hw hc a v).isSome = decide (0 < v.val) := by
+ by_cases h : 0 < v.val <;> simp [receivedMessage, h]
+
+theorem sentMessage_expectation (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) (hs : SuccessorSendOK hw hc a v) :
+ EdgeExpectation hw hc (sharedField a v 0) (sentMessage hw hc a v) := by
+ by_cases h : v.val+1 < 2^d
+ · let edge : Fin (2^d-1) := ⟨v.val, by omega⟩
+ have he : a.1 edge = (successorFormat hw hc).encode ((parseMessages hw hc a).1 edge) := by
+ simpa only [SuccessorSendOK, h, ↓reduceDIte, messageBits] using hs
+ rw [sentMessage, dite_eq_left h]
+ apply (successor_decode_iff hw hc _ _).mpr
+ funext j
+ exact ((incidentBits_offset ..).trans (incident_send a (.inl (edge, j)))).trans (congrFun he j)
+ · rw [sentMessage, dite_eq_right h]
+ funext j
+ exact (incidentBits_offset ..).trans (incident_clamp a _
+ (peer_send_end v (by have := v.isLt; omega) j))
+
+theorem receivedMessage_expectation (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) (hr : SuccessorReceiveOK hw hc a v) :
+ EdgeExpectation hw hc (sharedField a v 1) (receivedMessage hw hc a v) := by
+ by_cases h : 0 < v.val
+ · let edge : Fin (2^d-1) := ⟨v.val-1, by have := v.isLt; omega⟩
+ have he : a.1 edge = (successorFormat hw hc).encode ((parseMessages hw hc a).1 edge) := by
+ simpa only [SuccessorReceiveOK, h, ↓reduceDIte, messageBits] using hr
+ rw [receivedMessage, dite_eq_left h]
+ apply (successor_decode_iff hw hc _ _).mpr
+ funext j
+ exact ((incidentBits_offset ..).trans (incident_receive_successor a v h j)).trans (congrFun he j)
+ · rw [receivedMessage, dite_eq_right h]
+ funext j
+ exact (incidentBits_offset ..).trans (incident_clamp a _ (peer_receive_start v (by omega) j))
+
+/-- The physical reader's final stacks on the full incident vector. Its
+remaining input starts at the first sorting field. -/
+def sharedFinish (hc : 2^d * 2^e < 2^w) (a : SendArrays d (2^e) w) (v : Fin (2^d))
+ (s : Stacks Port) : Stacks Port :=
+ finish s (decide (v.val+1 < 2^d)) (decide (0 < v.val)) (sharedField a v 0) (sharedField a v 1)
+ ⟨2^d * 2^e, hc⟩ ((List.ofFn (RAMLayout.incidentBits a v)).drop (16*w))
+
+theorem finish_shared_values (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (a : SendArrays d (2^e) w)
+ (v : Fin (2^d)) (s : Stacks Port) (initial : Word w) (hi : s .initial = BurstRAM.wordBits initial)
+ (hs : SuccessorSendOK hw hc a v) (hr : SuccessorReceiveOK hw hc a v) :
+ Outputs s (sharedFinish hc a v s) hw hc initial (sentMessage hw hc a v) (receivedMessage hw hc a v)
+ ((List.ofFn (RAMLayout.incidentBits a v)).drop (16*w)) := by
+ simpa only [sharedFinish, sentMessage_isSome, receivedMessage_isSome] using
+ finish_values hw hc s initial _ _ _ _ _ hi (sentMessage_expectation hw hc a v hs)
+ (receivedMessage_expectation hw hc a v hr)
+
+theorem guard_shared_values (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (a : SendArrays d (2^e) w)
+ (v : Fin (2^d)) (s : Stacks Port) (initial : Word w) (hi : s .initial = BurstRAM.wordBits initial)
+ (hs : SuccessorSendOK hw hc a v) (hr : SuccessorReceiveOK hw hc a v) :
+ Outputs s (guardResult (sharedFinish hc a v s)) hw hc initial
+ (sentMessage hw hc a v) (receivedMessage hw hc a v) ((List.ofFn (RAMLayout.incidentBits a v)).drop (16*w)) :=
+ guardResult_values (finish_shared_values hw hc a v s initial hi hs hr)
+
+end RAMTape.Successors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorTagPreserve.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorTagPreserve.lean
new file mode 100644
index 0000000000..3c7e9b2fb1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorTagPreserve.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorTags
+
+/-!
+# Reading a successor tag and restoring the input word
+
+After classifying each bit, push it onto the temporary stack. Once the tag
+has been decided, transfer those bits back. The caller receives the tag in
+finite control and can still read the whole word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorTags
+
+open TapeWord
+
+/-- States for classifying a word while saving its bits, then restoring them with the tag held
+in control. -/
+inductive KeepState where
+ | read (q : State)
+ | save (q : State) (bit : Bool)
+ | restore (tag : Tag)
+ | put (tag : Tag) (bit : Bool)
+ | done (tag : Tag)
+ deriving DecidableEq, Fintype
+
+variable {K : Type*}
+
+/-- Classify the source word, move its bits back from scratch, and finish with its tag in
+finite control. -/
+def codeKeep (src tmp : K) : StackCode K KeepState
+ | .read q => .pop src fun bit => bit.elim (.restore (finish q)) fun b => .save (advance q b) b
+ | .save q b => .push tmp b (.read q)
+ | .restore t => .pop tmp fun bit => bit.elim (.done t) (.put t)
+ | .put t b => .push src b (.restore t)
+ | .done _ => .halt true
+
+variable [DecidableEq K] {src tmp : K}
+
+private def pair (base : Stacks K) (src tmp : K) (input scratch : List Bool) : Stacks K :=
+ Function.update (Function.update base src input) tmp scratch
+
+private theorem source_get (hne : src ≠ tmp) (base : Stacks K) (x y : List Bool) :
+ pair base src tmp x y src = x := by simp [pair, Function.update_of_ne hne]
+
+private theorem scratch_get (base : Stacks K) (x y : List Bool) :
+ pair base src tmp x y tmp = y := by simp [pair]
+
+private theorem source_write (hne : src ≠ tmp) (base : Stacks K) (x y z : List Bool) :
+ Function.update (pair base src tmp x y) src z = pair base src tmp z y := by
+ simp only [pair]
+ rw [Function.update_comm hne.symm, Function.update_idem]
+
+private theorem scratch_write (base : Stacks K) (x y z : List Bool) :
+ Function.update (pair base src tmp x y) tmp z = pair base src tmp x z := by simp [pair]
+
+local macro "keep_step " h:ident : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [source_get $h, scratch_get, source_write $h, scratch_write, List.head?_cons,
+ List.tail_cons, List.head?_nil, List.tail_nil, Option.elim_some, Option.elim_none])
+
+private theorem save_run (hne : src ≠ tmp) (base : Stacks K) (q : State) (x y : List Bool) :
+ StackRuns (codeKeep src tmp) (2*x.length+1) (.read q) (pair base src tmp x y)
+ (.restore (finish (x.foldl advance q))) (pair base src tmp [] (x.reverse ++ y)) := by
+ induction x generalizing q y with
+ | nil => keep_step hne; exact .nil ..
+ | cons b x ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append, List.foldl_cons]
+ keep_step hne
+ keep_step hne
+ exact ih (advance q b) (b :: y)
+
+private theorem restore_run (hne : src ≠ tmp) (base : Stacks K) (t : Tag) (x y : List Bool) :
+ StackRuns (codeKeep src tmp) (2*y.length+1) (.restore t) (pair base src tmp x y)
+ (.done t) (pair base src tmp (y.reverse ++ x) []) := by
+ induction y generalizing x with
+ | nil => keep_step hne; exact .nil ..
+ | cons b y ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ keep_step hne
+ keep_step hne
+ exact ih (b :: x)
+
+/-- Classify the source using an empty scratch stack. The two passes restore
+all stacks after exactly four instructions per bit and two empty pops. -/
+theorem keep_run (src tmp : K) (hne : src ≠ tmp) (s : Stacks K) (ht : s tmp = []) :
+ StackRuns (codeKeep src tmp) (4*(s src).length+2) (.read .first) s
+ (.done (Tag.ofNat (value (s src)))) s := by
+ have hs := save_run hne s .first (s src) []
+ have hr := restore_run hne s (Tag.ofNat (value (s src))) [] (s src).reverse
+ have hpair : pair s src tmp (s src) [] = s := by
+ simp [pair, ← ht]
+ simp only [finish_fold, List.append_nil, List.length_reverse, List.reverse_reverse, hpair] at hs hr
+ convert hs.trans hr using 1
+ omega
+
+end RAMTape.SuccessorTags
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorTags.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorTags.lean
new file mode 100644
index 0000000000..e3f887993b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorTags.lean
@@ -0,0 +1,126 @@
+import OAI.Computability.VPVNP.RAMTapeStacks
+import OAI.Computability.VPVNP.RAMTapeWord
+import Mathlib.Data.Fintype.Sum
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Scanning the small integer tags of a successor message
+
+Status and record-kind words use the values zero through three. Scanning a
+little-endian word, the control remembers its low two bits and tests whether
+any higher bit is set. The same scan tests whether a padding or clamp word
+is zero. It works on arbitrary lists, including empty and malformed words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SuccessorTags
+
+open TapeWord
+
+/-- Successor word classes for unsigned values zero through three and values at least four. -/
+inductive Tag where
+ | zero | one | two | three | large
+ deriving DecidableEq
+
+instance : Fintype Tag := derive_fintype% _
+
+/-- The enumeration maps all values of at least four to its final constructor. -/
+
+theorem Tag.ofNat_large {n : ℕ} (h : 4 ≤ n) : Tag.ofNat n = .large := by
+ obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le h
+ rw [Nat.add_comm]
+ rfl
+
+/-- States for remembering the low two bits and detecting set higher bits during a
+little-endian tag scan. -/
+inductive State where
+ | first
+ | second (low : Bool)
+ | high (tag : Tag)
+ | done (tag : Tag)
+ deriving DecidableEq, Fintype
+
+/-- The transition on one actual bit. -/
+def advance : State → Bool → State
+ | .first, b => .second b
+ | .second low, b => .high (Tag.ofNat (low.toNat + 2 * b.toNat))
+ | .high t, b => .high (if b then .large else t)
+ | .done t, _ => .done t
+
+/-- The tag when the source word has been exhausted. -/
+def finish : State → Tag
+ | .first => .zero
+ | .second b => Tag.ofNat b.toNat
+ | .high t | .done t => t
+
+private theorem high_fold (xs : List Bool) (t : Tag) :
+ finish (xs.foldl advance (.high t)) = if value xs = 0 then t else .large := by
+ induction xs generalizing t with
+ | nil => rfl
+ | cons b xs ih =>
+ cases b <;> simp [advance, ih, value]
+
+/-- The width-independent scan classifies the full unsigned word. -/
+theorem finish_fold (word : List Bool) :
+ finish (word.foldl advance .first) = Tag.ofNat (value word) := by
+ cases word with
+ | nil => rfl
+ | cons low rest =>
+ cases rest with
+ | nil => simp [advance, finish, value]
+ | cons b xs =>
+ simp only [List.foldl_cons, advance, high_fold, value]
+ by_cases h : value xs = 0
+ · simp [h]
+ · rw [ite_eq_right h]
+ exact (Tag.ofNat_large (by omega)).symm
+
+/-- On the empty pop, return the classification in finite control. -/
+def code {K : Type*} (src : K) : StackCode K State
+ | .done _ => .halt true
+ | q => .pop src fun bit => bit.elim (.done (finish q)) (advance q)
+
+private def scanning : State → Prop
+ | .done _ => False
+ | _ => True
+
+private theorem pop_eq {K : Type*} (src : K) (q : State) (hq : scanning q) :
+ code src q = .pop src (fun bit => bit.elim (.done (finish q)) (advance q)) := by
+ cases q <;> first | rfl | exact hq.elim
+
+private theorem scan_runs {K : Type*} [DecidableEq K] (src : K) (base : Stacks K)
+ (xs : List Bool) (q : State) (hq : scanning q) :
+ StackRuns (code src) (xs.length + 1) q (Function.update base src xs)
+ (.done (finish (xs.foldl advance q))) (Function.update base src []) := by
+ induction xs generalizing q with
+ | nil =>
+ refine .cons (.pop (pop_eq src q hq)) ?_
+ simp only [Function.update_self, List.head?_nil, List.tail_nil, Option.elim_none,
+ Function.update_idem]
+ exact .nil ..
+ | cons b xs ih =>
+ refine .cons (.pop (pop_eq src q hq)) ?_
+ simp only [Function.update_self, List.head?_cons, List.tail_cons, Option.elim_some,
+ Function.update_idem, List.foldl_cons]
+ exact ih (advance q b) (by cases q <;> trivial)
+
+/-- The designated stack is emptied in one pop per bit plus one empty pop. -/
+theorem run {K : Type*} [DecidableEq K] (src : K) (s : Stacks K) :
+ StackRuns (code src) ((s src).length + 1) .first s
+ (.done (Tag.ofNat (value (s src)))) (Function.update s src []) := by
+ simpa only [Function.update_eq_self, finish_fold] using
+ scan_runs src s (s src) .first trivial
+
+theorem word_run {K : Type*} [DecidableEq K] {w : ℕ} (src : K) (s : Stacks K)
+ (a : BurstRAM.Word w) (h : s src = BurstRAM.wordBits a) :
+ StackRuns (code src) (w + 1) .first s (.done (Tag.ofNat a.val)) (Function.update s src []) := by
+ simpa only [h, BurstRAM.length_wordBits, value_wordBits] using run src s
+
+end RAMTape.SuccessorTags
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorTotal.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorTotal.lean
new file mode 100644
index 0000000000..d0b86959dd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorTotal.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorChecks
+import OAI.Computability.VPVNP.RAMTapeSuccessorSharedValues
+
+/-!
+# Return and rejection of the successor guard on shared words
+
+The two checked fields decide whether the continuation is reached. On a valid site the
+reader takes its exact scan cost and the guard takes two further instructions. One extra
+instruction in the all-branch budget lets the explicit rejecting halt execute when the
+incoming verdict is false.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successors
+
+open BurstRAM RAMLayout
+
+variable {d e w : ℕ} (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (a : SendArrays d (2^e) w) (s : Stacks Port) (v : Word d)
+
+/-- The verdict stacks at the end of this physical scan test precisely the two local predicates. -/
+theorem shared_verdicts_iff :
+ ((sharedFinish hc a v s (.verdict .send)).head? = some true ∧
+ (sharedFinish hc a v s (.verdict .receive)).head? = some true) ↔
+ SuccessorSendOK hw hc a v ∧ SuccessorReceiveOK hw hc a v :=
+ (finish_good_iff hw hc s (decide (v.val+1 < 2^d)) (decide (0 < v.val))
+ (sharedField a v 0) (sharedField a v 1) ((List.ofFn (incidentBits a v)).drop (16*w))).trans
+ (shared_fields_iff hw hc a v)
+
+variable (initial : Word w) (hv : s .address = BurstRAM.wordBits v)
+ (hin : s .incident = List.ofFn (RAMLayout.incidentBits a v))
+ (hwidth : s .width = List.replicate w true) (hcap : s .cap = BurstRAM.wordBits ⟨2^d * 2^e, hc⟩)
+ (hi : s .initial = BurstRAM.wordBits initial) (ht : s .tmp = []) (hu : s .capTmp = [])
+ (hblank : ∀ side i, s (.word side i) = [])
+include hv hin hwidth hcap hi ht hu hblank
+
+/-- On a canonical pair the exact run preserves the typed output stacks for the next pass. -/
+theorem checked_shared_runs (hgood : SuccessorSendOK hw hc a v ∧ SuccessorReceiveOK hw hc a v) :
+ checked.Runs (steps d w (decide (0 < v.val)) + 2) s (guardResult (sharedFinish hc a v s)) := by
+ have hread := read_incident_runs s v ⟨_, hc⟩ initial _ hv hin hwidth hcap hi ht hu hblank
+ have hguard := (shared_verdicts_iff hw hc a s v).mpr hgood
+ exact hread.followedBy (guard_runs (sharedFinish hc a v s) hguard.1 hguard.2)
+
+/-- With three guard ticks every malformed pair has stopped. A canonical pair must satisfy
+its continuation with the one unused guard tick and the physical output of the scan. -/
+theorem checked_shared_allStops (c : ℕ → Stacks Port → Prop) (fuel : ℕ) :
+ checked.body.AllStops c (fuel + 3 + steps d w (decide (0 < v.val))) s ↔
+ ((SuccessorSendOK hw hc a v ∧ SuccessorReceiveOK hw hc a v) →
+ c (fuel + 1) (guardResult (sharedFinish hc a v s))) := by
+ have hread := read_incident_runs s v ⟨_, hc⟩ initial _ hv hin hwidth hcap hi ht hu hblank
+ exact (checked_allStops_of_read hread c fuel).trans
+ (imp_congr_left (shared_verdicts_iff hw hc a s v))
+
+end RAMTape.Successors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessorValues.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorValues.lean
new file mode 100644
index 0000000000..b99f67f8b9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessorValues.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorEdgeValues
+import OAI.Computability.VPVNP.RAMTapeSuccessorGuard
+
+/-!
+# Typed values of the two physical successor checks
+
+An interior field carries a canonical typed message. A missing field carries
+the zero clamp. Once both fields pass, the physical cost, state and record
+stacks give the cuts and last records used by the call loop and boundary pass.
+The first processor starts from the public initial word at cost zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successors
+
+open BurstRAM RAMSerialization
+
+variable {w cap : ℕ}
+
+/-- Match a physical field to a typed edge, with a zero clamp for a missing edge. -/
+def EdgeExpectation (hw : 2 ≤ w) (hc : cap < 2^w) (bits : Fin (8*w) → Bool) :
+ Option (RAMSerialization.Successor w cap) → Prop
+ | some msg => (successorFormat hw hc).decode bits = some msg
+ | none => bits = fun _ => false
+
+/-- Select the optional outgoing or incoming typed successor message for the requested side. -/
+def atSide (sent received : Option (RAMSerialization.Successor w cap)) :
+ Side → Option (RAMSerialization.Successor w cap)
+ | .send => sent
+ | .receive => received
+
+/-- The endpoint cost fits in one physical word even when it equals the cap. -/
+def costWord (hc : cap < 2^w) : Option (RAMSerialization.Successor w cap) → Word w
+ | some x => ⟨x.cost.val, (Nat.le_of_lt_succ x.cost.isLt).trans_lt hc⟩
+ | none => 0
+
+/-- A missing incoming edge installs the initial word. A missing outgoing
+edge has no running target. A present edge takes its state from the message. -/
+def savedState (initial : Word w) (side : Side) :
+ Option (RAMSerialization.Successor w cap) → Option (Word w)
+ | some x => x.state
+ | none => match side with
+ | .send => none
+ | .receive => some initial
+
+/-- The stacks consumed by the call and sorting passes, stated relative to
+their caller so a saved flag or record may have a nonempty stack tail. -/
+structure Outputs (base out : Stacks Port) (hw : 2 ≤ w) (hc : cap < 2^w) (initial : Word w)
+ (sent received : Option (RAMSerialization.Successor w cap)) (suffix : List Bool) : Prop where
+ outPresent : out .outPresent = sent.isSome :: base .outPresent
+ incident : out .incident = suffix
+ running : ∀ side, out (.running side) =
+ (savedState initial side (atSide sent received side)).isSome :: base (.running side)
+ cost : ∀ side, out (.word side 1) = BurstRAM.wordBits (costWord hc (atSide sent received side))
+ state : ∀ side, out (.word side 2) =
+ BurstRAM.wordBits ((savedState initial side (atSide sent received side)).getD 0)
+ record : ∀ side, out (.record side) =
+ List.ofFn ((recordFormat hw).encode ((atSide sent received side).bind (·.lastRecord))) ++
+ base (.record side)
+
+private theorem edge_values (hw : 2 ≤ w) (hc : cap < 2^w) (base : Stacks SuccessorEdge.Port)
+ (bits : Fin (8*w) → Bool) (msg : Option (RAMSerialization.Successor w cap)) (tail : List Bool)
+ (hm : EdgeExpectation hw hc bits msg) :
+ let out := SuccessorEdge.edgeResult base msg.isSome bits ⟨cap, hc⟩ tail
+ out .verdict = true :: base .verdict ∧
+ out .running = (msg.bind (·.state)).isSome :: base .running ∧
+ out (.word 1) = BurstRAM.wordBits (costWord hc msg) ∧
+ out (.word 2) = BurstRAM.wordBits ((msg.bind (·.state)).getD 0) ∧
+ out .record = List.ofFn ((recordFormat hw).encode (msg.bind (·.lastRecord))) ++ base .record := by
+ cases msg with
+ | some x => exact SuccessorEdge.present_values hw hc base bits tail x hm
+ | none =>
+ subst bits
+ obtain ⟨hv, hr, hs, hp⟩ := SuccessorEdge.clamped_values base (⟨cap, hc⟩ : Word w) tail
+ refine ⟨hv, hr, hs 1, hs 2, ?_⟩
+ simpa only [Option.isSome_none, Option.bind_none, recordFormat_empty, List.ofFn_const] using hp
+
+private theorem finish_spec (hw : 2 ≤ w) (hc : cap < 2^w) (s : Stacks Port) (initial : Word w)
+ (sent received : Fin (8*w) → Bool) (sendMsg recvMsg : Option (RAMSerialization.Successor w cap))
+ (suffix : List Bool) (hi : s .initial = BurstRAM.wordBits initial)
+ (hs : EdgeExpectation hw hc sent sendMsg) (hr : EdgeExpectation hw hc received recvMsg) :
+ let out := finish s sendMsg.isSome recvMsg.isSome sent received ⟨cap, hc⟩ suffix
+ Outputs s out hw hc initial sendMsg recvMsg suffix ∧
+ ∀ side, out (.verdict side) = true :: s (.verdict side) := by
+ let a := afterEdge s .send sendMsg.isSome sent ⟨cap, hc⟩ (List.ofFn received ++ suffix)
+ obtain ⟨sv, sr, sc, ss, sp⟩ := edge_values hw hc (s ∘ edgePorts .send) sent sendMsg
+ (List.ofFn received ++ suffix) hs
+ obtain ⟨rv, rr, rc, rs, rp⟩ := edge_values hw hc (a ∘ edgePorts .receive) received recvMsg suffix hr
+ constructor
+ · constructor
+ · cases recvMsg <;> rfl
+ · cases recvMsg <;> rfl
+ · intro side
+ cases side with
+ | send => cases sendMsg <;> cases recvMsg <;> exact sr
+ | receive => cases recvMsg with
+ | none => rfl
+ | some x => exact rr
+ · intro side
+ cases side with
+ | send => cases recvMsg <;> exact sc
+ | receive => cases recvMsg <;> exact rc
+ · intro side
+ cases side with
+ | send => cases sendMsg <;> cases recvMsg <;> exact ss
+ | receive => cases recvMsg with
+ | none => exact hi
+ | some x => exact rs
+ · intro side
+ cases side with
+ | send => cases recvMsg <;> exact sp
+ | receive => cases recvMsg <;> exact rp
+ · intro side
+ cases side with
+ | send => cases recvMsg <;> exact sv
+ | receive => cases recvMsg <;> exact rv
+
+/-- All physical output values after both decoded fields, including the
+initial cut and the missing target at the ends of the chain. -/
+theorem finish_values (hw : 2 ≤ w) (hc : cap < 2^w) (s : Stacks Port) (initial : Word w)
+ (sent received : Fin (8*w) → Bool) (sendMsg recvMsg : Option (RAMSerialization.Successor w cap))
+ (suffix : List Bool) (hi : s .initial = BurstRAM.wordBits initial)
+ (hs : EdgeExpectation hw hc sent sendMsg) (hr : EdgeExpectation hw hc received recvMsg) :
+ Outputs s (finish s sendMsg.isSome recvMsg.isSome sent received ⟨cap, hc⟩ suffix)
+ hw hc initial sendMsg recvMsg suffix :=
+ (finish_spec hw hc s initial sent received sendMsg recvMsg suffix hi hs hr).1
+
+/-- Both physical verdict bits are set when the fields match their typed edges. -/
+theorem finish_verdicts (hw : 2 ≤ w) (hc : cap < 2^w) (s : Stacks Port) (initial : Word w)
+ (sent received : Fin (8*w) → Bool) (sendMsg recvMsg : Option (RAMSerialization.Successor w cap))
+ (suffix : List Bool) (hi : s .initial = BurstRAM.wordBits initial)
+ (hs : EdgeExpectation hw hc sent sendMsg) (hr : EdgeExpectation hw hc received recvMsg) :
+ ∀ side, finish s sendMsg.isSome recvMsg.isSome sent received ⟨cap, hc⟩ suffix (.verdict side) =
+ true :: s (.verdict side) :=
+ (finish_spec hw hc s initial sent received sendMsg recvMsg suffix hi hs hr).2
+
+/-- The guard consumes the verdicts, preserving every register needed by the
+processor's continuation. -/
+theorem guardResult_values {s out : Stacks Port} {hw : 2 ≤ w} {hc : cap < 2^w} {initial : Word w}
+ {sent received : Option (RAMSerialization.Successor w cap)} {suffix : List Bool}
+ (h : Outputs s out hw hc initial sent received suffix) :
+ Outputs s (guardResult out) hw hc initial sent received suffix :=
+ ⟨h.outPresent, h.incident, h.running, h.cost, h.state, h.record⟩
+
+end RAMTape.Successors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeSuccessors.lean b/lean/OAI/Computability/VPVNP/RAMTapeSuccessors.lean
new file mode 100644
index 0000000000..501acfd6fc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeSuccessors.lean
@@ -0,0 +1,205 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorDispatch
+import OAI.Computability.VPVNP.RAMTapeSuccessorEdge
+import OAI.Computability.VPVNP.RAMTapeSuccessorInitial
+
+/-!
+# Executing the two successor checks of a RAM processor
+
+One uniform finite stack program examines the site address, reads the outgoing
+eight words and then the incoming eight words, and checks both fields. The
+first site installs the public initial state. The terminal site emits a false
+outgoing-presence flag. The unconsumed incident bits are the sorting fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Successors
+
+open BurstRAM RAMLayout RAMSerialization
+
+/-- Outgoing and incoming sides of a site's successor check. -/
+inductive Side where
+ | send | receive
+ deriving DecidableEq
+
+instance : Fintype Side := derive_fintype% _
+
+/-- Shared address, incident, width, cap, and scratch registers together with side-specific
+words, flags, and records. -/
+inductive Port where
+ | address | incident | width | cap | initial | tmp | capTmp | outPresent
+ | running (side : Side) | verdict (side : Side) | record (side : Side) | word (side : Side) (i : Fin 8)
+ deriving DecidableEq, Fintype
+
+/-- Connect a single-edge reader to the shared incident stacks and the selected side's word,
+flag, and record registers. -/
+def edgePorts (side : Side) : SuccessorEdge.Port → Port
+ | .input => .incident
+ | .width => .width
+ | .tmp => .tmp
+ | .cap => .cap
+ | .capTmp => .capTmp
+ | .running => .running side
+ | .verdict => .verdict side
+ | .record => .record side
+ | .word i => .word side i
+
+private theorem edgePorts_inj (side : Side) : Function.Injective (edgePorts side) := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [edgePorts]
+
+/-- Connect initial-state normalization to the public initial word, received state word,
+received running bit, and scratch stacks. -/
+def initialPorts : SuccessorInitial.Port → Port
+ | .initial => .initial
+ | .state => .word .receive 2
+ | .running => .running .receive
+ | .sourceTmp => .tmp
+ | .outTmp => .capTmp
+
+private theorem initialPorts_inj : Function.Injective initialPorts := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [initialPorts]
+
+/-- Install the public initial state at a site with no incoming edge and immediately return at
+an interior receive site. -/
+def normalizeIfFirst (incoming : Bool) : FiniteRoutine Port :=
+ if incoming then .ret else SuccessorInitial.normalize initialPorts
+
+private def emitPresent (outgoing : Bool) : FiniteRoutine Port :=
+ FiniteRoutine.ofRoutine (Routine.push Port.outPresent outgoing)
+
+/-- Check outgoing and incoming fields in stream order, normalize the first site's state, and
+emit the outgoing-presence bit. -/
+def body (outgoing incoming : Bool) : FiniteRoutine Port :=
+ (((SuccessorEdge.edge (edgePorts .send) outgoing).followedBy
+ (SuccessorEdge.edge (edgePorts .receive) incoming)).followedBy
+ (normalizeIfFirst incoming)).followedBy (emitPresent outgoing)
+
+/-- This table is independent of the word length, site count and site identifier. -/
+def read : FiniteRoutine Port := SuccessorEnds.dispatch .address .tmp body
+
+variable {w : ℕ}
+
+/-- Register bank after one side's field check, with the unconsumed incident tail and that
+side's updated words, record, and flags. -/
+def afterEdge (s : Stacks Port) (side : Side) (present : Bool) (bits : Fin (8 * w) → Bool)
+ (cap : Word w) (tail : List Bool) : Stacks Port :=
+ let row := SuccessorEdge.edgeResult (s ∘ edgePorts side) present bits cap tail
+ fun p ↦ match p with
+ | .incident => tail
+ | .running t => if t = side then row .running else s p
+ | .verdict t => if t = side then row .verdict else s p
+ | .record t => if t = side then row .record else s p
+ | .word t i => if t = side then row (.word i) else s p
+ | _ => s p
+
+private theorem edge_runs (s : Stacks Port) (side : Side) (present : Bool) (bits : Fin (8*w) → Bool)
+ (cap : Word w) (tail : List Bool) (hin : s .incident = List.ofFn bits ++ tail)
+ (hw : s .width = List.replicate w true) (hc : s .cap = BurstRAM.wordBits cap)
+ (ht : s .tmp = []) (hu : s .capTmp = []) (hblank : ∀ i, s (.word side i) = []) :
+ (SuccessorEdge.edge (edgePorts side) present).Runs (113*w+49) s
+ (afterEdge s side present bits cap tail) := by
+ have he := SuccessorEdge.edge_runs (edgePorts side) (edgePorts_inj side) present s bits cap tail
+ hin hw hc ht hu hblank
+ have hf : installStacks (edgePorts side) s
+ (SuccessorEdge.edgeResult (s ∘ edgePorts side) present bits cap tail) =
+ afterEdge s side present bits cap tail := by
+ apply installStacks_frame (edgePorts_inj side)
+ · intro k
+ cases k <;> simp [afterEdge, edgePorts, SuccessorEdge.edgeResult]
+ · intro k hk
+ cases k with
+ | incident => exact (hk .input rfl).elim
+ | running t | verdict t | record t =>
+ by_cases h : t = side
+ · subst t
+ first | exact (hk .running rfl).elim | exact (hk .verdict rfl).elim | exact (hk .record rfl).elim
+ · simp [afterEdge, h]
+ | word t i =>
+ by_cases h : t = side
+ · subst t
+ exact (hk (.word i) rfl).elim
+ · simp [afterEdge, h]
+ | _ => rfl
+ rwa [hf] at he
+
+/-- Install the public initial word and a true running bit in the incoming registers when the
+site has no incoming edge. -/
+def afterNormalize (s : Stacks Port) (incoming : Bool) : Stacks Port :=
+ if incoming then s else Function.update (Function.update s (.word .receive 2) (s .initial))
+ (.running .receive) (true :: (s (.running .receive)).tail)
+
+/-- Step count of first-site normalization, including the single return step when an incoming
+edge is present. -/
+def normalizeCost (w : ℕ) (incoming : Bool) := if incoming then 1 else 8*w+5
+
+private theorem normalize_runs (s : Stacks Port) (incoming : Bool) (ht : s .tmp = []) (hu : s .capTmp = [])
+ (hi : (s .initial).length = w) (hs : (s (.word .receive 2)).length = w) :
+ (normalizeIfFirst incoming).Runs (normalizeCost w incoming) s (afterNormalize s incoming) := by
+ cases incoming with
+ | false => exact SuccessorInitial.normalize_runs initialPorts_inj s ht hu hi hs
+ | true => exact Routine.runs_ret s
+
+/-- Final register bank after both edge checks, first-site normalization, and emission of the
+outgoing-presence bit. -/
+def finish (s : Stacks Port) (outgoing incoming : Bool) (sent received : Fin (8*w) → Bool)
+ (cap : Word w) (suffix : List Bool) : Stacks Port :=
+ let a := afterEdge s .send outgoing sent cap (List.ofFn received ++ suffix)
+ let b := afterEdge a .receive incoming received cap suffix
+ let c := afterNormalize b incoming
+ Function.update c .outPresent (outgoing :: c .outPresent)
+
+/-- Step count for the site-address scan, both eight-word successor checks, first-site
+normalization, and outgoing flag emission. -/
+def steps (d w : ℕ) (incoming : Bool) : ℕ :=
+ 4*d+3 + (((113*w+49)+(113*w+49)) + normalizeCost w incoming + 1)
+
+theorem steps_le (d w : ℕ) (incoming : Bool) : steps d w incoming ≤ 4*d+234*w+107 := by
+ cases incoming <;> simp [steps, normalizeCost] <;> omega
+
+/-- Both outgoing and incoming words are preserved for the call loop. The two
+record payloads are independently available to the sorted predecessor check.
+The result includes a canonicality flag for each raw field, even if malformed. -/
+theorem read_runs {d : ℕ} (s : Stacks Port) (v : Word d) (cap initial : Word w)
+ (sent received : Fin (8*w) → Bool) (suffix : List Bool)
+ (hv : s .address = BurstRAM.wordBits v)
+ (hin : s .incident = List.ofFn sent ++ (List.ofFn received ++ suffix))
+ (hw : s .width = List.replicate w true) (hc : s .cap = BurstRAM.wordBits cap)
+ (hi : s .initial = BurstRAM.wordBits initial) (ht : s .tmp = []) (hu : s .capTmp = [])
+ (hblank : ∀ side i, s (.word side i) = []) :
+ let outgoing := decide (v.val + 1 < 2 ^ d)
+ let incoming := decide (0 < v.val)
+ read.Runs (steps d w incoming) s (finish s outgoing incoming sent received cap suffix) := by
+ intro outgoing incoming
+ apply SuccessorEnds.dispatch_runs .address .tmp (by decide) body s v hv ht
+ let a := afterEdge s .send outgoing sent cap (List.ofFn received ++ suffix)
+ let b := afterEdge a .receive incoming received cap suffix
+ have ha := edge_runs s .send outgoing sent cap _ hin hw hc ht hu (hblank .send)
+ have hb := edge_runs a .receive incoming received cap suffix rfl hw hc ht hu (hblank .receive)
+ have hn := normalize_runs b incoming ht hu (show (s .initial).length = w from hi ▸ length_wordBits initial)
+ (show (b (.word .receive 2)).length = w from BurstRAM.length_wordBits _)
+ exact (((ha.followedBy hb).followedBy hn).followedBy (Routine.runs_push Port.outPresent outgoing (afterNormalize b incoming)))
+
+/-- The incident vector in the precise layout of (10.1) supplies both fields
+without a bit lookup oracle. -/
+theorem read_incident_runs {d H : ℕ} (s : Stacks Port) (v : Word d) (cap initial : Word w)
+ (inc : Fin (width d H w) → Bool)
+ (hv : s .address = BurstRAM.wordBits v) (hin : s .incident = List.ofFn inc)
+ (hw : s .width = List.replicate w true) (hc : s .cap = BurstRAM.wordBits cap)
+ (hi : s .initial = BurstRAM.wordBits initial) (ht : s .tmp = []) (hu : s .capTmp = [])
+ (hblank : ∀ side i, s (.word side i) = []) :
+ read.Runs (steps d w (decide (0 < v.val))) s
+ (finish s (decide (v.val+1 < 2^d)) (decide (0 < v.val))
+ (fun j ↦ inc (offset d H w (.inl (0, j)))) (fun j ↦ inc (offset d H w (.inl (1, j))))
+ cap ((List.ofFn inc).drop (16*w))) :=
+ read_runs s v cap initial _ _ _ hv
+ (hin.trans (by simpa only [List.append_assoc] using SuccessorFields.incident_prefix inc)) hw hc hi ht hu hblank
+
+end RAMTape.Successors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeUnaryWord.lean b/lean/OAI/Computability/VPVNP/RAMTapeUnaryWord.lean
new file mode 100644
index 0000000000..550154ee3a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeUnaryWord.lean
@@ -0,0 +1,245 @@
+import OAI.Computability.VPVNP.RAMTapeUnaryWordValue
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Data.Fintype.Sigma
+import Mathlib.Data.Fintype.Sum
+import Mathlib.Tactic.DeriveFintype
+import Mathlib.Tactic.Ring
+import Mathlib.Tactic.Linarith
+
+/-!
+# Preparing the length and the unit as padded binary words
+
+The input is a unary tally of the physical input length. A fixed control
+allocates two words, adding a group of `p+1` zero bits to each word for every
+mark and one further group. It sets the unit word's low bit and increments
+the length word once for each saved mark. All data-dependent loops operate
+on individual stack cells.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.UnaryWord
+
+/-- Stacks for a unary source tally, pending increments, padded binary length and unit words,
+and arithmetic scratch. -/
+inductive Port where
+ | src | pending | number | unit | tmp
+ deriving DecidableEq
+
+instance : Fintype Port := derive_fintype% _
+
+/-- Control states for allocating both padded words, setting the unit bit, and counting the
+saved unary marks into the length word. -/
+inductive Phase (p : ℕ) where
+ | alloc (remaining : Fin (p+2))
+ | allocUnit (remaining : Fin (p+2))
+ | next | save
+ | unitHead | unitOne | count
+ | add (carry : Bool) | emit (sum carry : Bool)
+ | restore | put (b : Bool) | done
+ deriving DecidableEq, Fintype
+
+/-- Allocate padded zero words in groups of the parameter plus one bits, set the unit to one,
+and increment the length word for each unary mark. -/
+def code (p : ℕ) : StackCode Port (Phase p)
+ | .alloc i => if h : i.val = 0 then .goto .next
+ else .push .number false (.allocUnit ⟨i.val-1, by have := i.isLt; omega⟩)
+ | .allocUnit i => .push .unit false (.alloc i)
+ | .next => .pop .src fun b ↦ b.elim .unitHead (fun _ ↦ .save)
+ | .save => .push .pending true (.alloc (Fin.last (p+1)))
+ | .unitHead => .pop .unit (fun _ ↦ .unitOne)
+ | .unitOne => .push .unit true .count
+ | .count => .pop .pending fun b ↦ b.elim .done (fun _ ↦ .add true)
+ | .add c => .pop .number fun b ↦ b.elim .restore (fun d ↦ .emit (d ^^ c) (d && c))
+ | .emit b c => .push .tmp b (.add c)
+ | .restore => .pop .tmp fun b ↦ b.elim .count .put
+ | .put b => .push .number b .restore
+ | .done => .halt true
+
+/-- Assign the supplied bit lists to the source, pending, length, unit, and temporary stacks. -/
+def store (src pending number unit tmp : List Bool) : Stacks Port
+ | .src => src
+ | .pending => pending
+ | .number => number
+ | .unit => unit
+ | .tmp => tmp
+
+private theorem update_store (s a x u t v : List Bool) (k : Port) :
+ Function.update (store s a x u t) k v = match k with
+ | .src => store v a x u t
+ | .pending => store s v x u t
+ | .number => store s a v u t
+ | .unit => store s a x v t
+ | .tmp => store s a x u v := by
+ funext i
+ cases k <;> cases i <;> simp [store]
+
+local macro "unary_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, update_store, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none])
+
+private abbrev ones (n : ℕ) := List.replicate n true
+private abbrev zeros (n : ℕ) := List.replicate n false
+
+private theorem alloc_run (p k : ℕ) (hk : k ≤ p+1) (s a x u : List Bool) :
+ StackRuns (code p) (2*k+1) (.alloc ⟨k, by omega⟩) (store s a x u []) .next
+ (store s a (zeros k ++ x) (zeros k ++ u) []) := by
+ induction k generalizing x u with
+ | zero => exact .cons (.goto (by simp [code])) (.nil ..)
+ | succ k ih =>
+ have hc : code p (.alloc ⟨k+1, by omega⟩) = .push .number false (.allocUnit ⟨k, by omega⟩) := by
+ simp [code]
+ simp only [Nat.mul_succ]
+ refine .cons (.push hc) ?_
+ simp only [store, update_store]
+ unary_step
+ simpa only [zeros, List.replicate_succ', List.append_assoc, List.singleton_append] using
+ ih (by omega) (false :: x) (false :: u)
+
+/-- Stack steps from the initial allocation to the instruction that sets the unit bit. -/
+private def allocWork (p n : ℕ) := (n+1)*(2*(p+1)+1) + 2*n + 1
+
+private theorem prepare_run (p n : ℕ) (a x u : List Bool) :
+ StackRuns (code p) (allocWork p n) (.alloc (Fin.last (p+1))) (store (ones n) a x u [])
+ .unitHead (store [] (ones n ++ a) (zeros ((p+1)*(n+1)) ++ x) (zeros ((p+1)*(n+1)) ++ u) []) := by
+ induction n generalizing a x u with
+ | zero =>
+ have h := alloc_run p (p+1) le_rfl [] a x u
+ have hnext : StackRuns (code p) 1 .next (store [] a (zeros (p+1) ++ x) (zeros (p+1) ++ u) [])
+ .unitHead (store [] a (zeros (p+1) ++ x) (zeros (p+1) ++ u) []) := by
+ unary_step
+ exact .nil ..
+ simpa [allocWork, ones, Fin.last] using h.trans hnext
+ | succ n ih =>
+ let x' := zeros (p+1) ++ x
+ let u' := zeros (p+1) ++ u
+ have h := alloc_run p (p+1) le_rfl (ones (n+1)) a x u
+ have hsave : StackRuns (code p) 2 .next (store (true :: ones n) a x' u' [])
+ (.alloc (Fin.last (p+1))) (store (ones n) (true :: a) x' u' []) := by
+ unary_step
+ unary_step
+ exact .nil ..
+ have htotal := (h.trans hsave).trans (ih (true :: a) x' u')
+ have hc : (2*(p+1)+1 + 2) + allocWork p n = allocWork p (n+1) := by
+ unfold allocWork
+ ring
+ rw [hc] at htotal
+ simpa only [zeros, Nat.mul_succ (p+1) (n+1), List.replicate_add, List.append_assoc,
+ ones, List.replicate_succ', List.singleton_append, x', u', Fin.last] using htotal
+
+private theorem add_run (p : ℕ) (carry : Bool) (src pending x unit tmp : List Bool) :
+ StackRuns (code p) (2*x.length+1) (.add carry) (store src pending x unit tmp) .restore
+ (store src pending [] unit ((incScan carry x).1.reverse ++ tmp)) := by
+ induction x generalizing carry tmp with
+ | nil => unary_step; exact .nil ..
+ | cons b x ih =>
+ simp only [List.length_cons, Nat.mul_succ, incScan, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ unary_step
+ unary_step
+ exact ih (b && carry) ((b ^^ carry) :: tmp)
+
+private theorem restore_run (p : ℕ) (src pending x unit tmp : List Bool) :
+ StackRuns (code p) (2*tmp.length+1) .restore (store src pending x unit tmp)
+ .count (store src pending (tmp.reverse ++ x) unit []) := by
+ induction tmp generalizing x with
+ | nil => unary_step; exact .nil ..
+ | cons b tmp ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ unary_step
+ unary_step
+ exact ih (b :: x)
+
+theorem count_run (p k : ℕ) (src x u : List Bool) (hfit : TapeWord.value x + k < 2^x.length) :
+ ∃ result, result.length = x.length ∧ TapeWord.value result = TapeWord.value x + k ∧
+ StackRuns (code p) (k*(4*x.length+3)+1) .count (store src (ones k) x u [])
+ .done (store src [] result u []) := by
+ induction k generalizing x with
+ | zero =>
+ refine ⟨x, rfl, (Nat.add_zero _).symm, ?_⟩
+ simp only [Nat.zero_mul]
+ unary_step
+ exact .nil ..
+ | succ k ih =>
+ let y := (incScan true x).1
+ have hlen : y.length = x.length := incScan_length ..
+ have hval : TapeWord.value y = TapeWord.value x + 1 := incScan_value_of_lt _ _ (by
+ simp only [Bool.toNat_true]
+ omega)
+ have hfit' : TapeWord.value y + k < 2^y.length := by rw [hlen, hval]; omega
+ obtain ⟨r, hr, hv, htail⟩ := ih y hfit'
+ refine ⟨r, hr.trans hlen, by omega, ?_⟩
+ have ha := add_run p true src (ones k) x u []
+ have hb := restore_run p src (ones k) [] u y.reverse
+ simp only [List.append_nil] at ha
+ simp only [List.length_reverse, List.reverse_reverse, List.append_nil, hlen] at hb
+ rw [hlen] at htail
+ rw [show (k+1)*(4*x.length+3)+1 = ((2*x.length+1)+(2*x.length+1)+(k*(4*x.length+3)+1))+1 by
+ ring]
+ change StackRuns _ _ _ (store src (true :: ones k) x u []) _ _
+ unary_step
+ exact (ha.trans hb).trans htail
+
+/-- Enter the counting loop with an already allocated zero word. Each saved
+mark increments that word. The source and unit stacks pass through intact. -/
+theorem count_fixed (p w k : ℕ) (src unit : List Bool) (hk : k < 2^w) :
+ StackRuns (code p) (k*(4*w+3)+1) .count
+ (store src (List.replicate k true) (List.replicate w false) unit []) .done
+ (store src [] (BurstRAM.wordBits (Fin.ofNat (2^w) k)) unit []) := by
+ obtain ⟨z,hl,hv,h⟩ := count_run p k src (zeros w) unit (by simpa [zeros] using hk)
+ simp only [zeros, List.length_replicate, zeros_value, Nat.zero_add] at hl hv h
+ have hz : z = BurstRAM.wordBits (Fin.ofNat (2^w) k) :=
+ TapeWord.eq_of_length_value (by simpa using hl)
+ (by simpa [TapeWord.value_wordBits, Fin.val_ofNat, Nat.mod_eq_of_lt hk] using hv)
+ simpa only [hz] using h
+
+/-- Allocate the two words, set the unit's low bit, and scan both directions
+through the length word once per input mark. -/
+def work (p n : ℕ) : ℕ := allocWork p n + 2 + (n*(4*width p n+3)+1)
+
+/-- The degree of the instruction bound is independent of the fixed
+program parameter `p`. -/
+theorem work_le (p n : ℕ) : work p n ≤ 12*(p+1)*(n+1)^2 := by
+ simp only [work, allocWork, width]
+ nlinarith only [Nat.zero_le (p*n), Nat.zero_le (p*n*n), Nat.zero_le (n*n), Nat.zero_le p, Nat.zero_le n]
+
+/-- Starting with only the unary tally, prepare the two fixed-width words.
+Their width, including all padding cells, is `(p+1)*(n+1)`. -/
+theorem runs (p n : ℕ) :
+ StackRuns (code p) (work p n) (.alloc (Fin.last (p+1))) (store (List.replicate n true) [] [] [] [])
+ .done (store [] [] (BurstRAM.wordBits (inputWord p n)) (BurstRAM.wordBits (unitWord p n)) []) := by
+ let W := width p n
+ let u := BurstRAM.wordBits (unitWord p n)
+ have hw : 0 < W := width_pos p n
+ have hz : zeros W = false :: zeros (W-1) := by
+ calc
+ zeros W = zeros ((W-1)+1) := congrArg zeros (by omega)
+ _ = _ := List.replicate_succ
+ have hset : StackRuns (code p) 2 .unitHead (store [] (ones n) (zeros W) (zeros W) [])
+ .count (store [] (ones n) (zeros W) u []) := by
+ rw [show u = true :: zeros (W-1) from (unit_wordBits p n).symm]
+ have h : StackRuns (code p) 2 .unitHead (store [] (ones n) (zeros W) (false :: zeros (W-1)) [])
+ .count (store [] (ones n) (zeros W) (true :: zeros (W-1)) []) := by
+ unary_step
+ unary_step
+ exact .nil ..
+ simpa only [← hz] using h
+ have hprep := prepare_run p n [] [] []
+ simp only [List.append_nil] at hprep
+ have hfit : TapeWord.value (zeros W) + n < 2 ^ (zeros W).length := by
+ simpa [zeros, W] using (inputWord p n).isLt
+ obtain ⟨r, hr, hv, hcount⟩ := count_run p n [] (zeros W) u hfit
+ simp only [zeros, List.length_replicate, zeros_value, Nat.zero_add] at hr hv hcount
+ have he : r = BurstRAM.wordBits (inputWord p n) :=
+ TapeWord.eq_of_length_value (by simpa using hr) (by simpa [TapeWord.value_wordBits] using hv)
+ rw [he] at hcount
+ exact (hprep.trans hset).trans hcount
+
+end RAMTape.UnaryWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeUnaryWordValue.lean b/lean/OAI/Computability/VPVNP/RAMTapeUnaryWordValue.lean
new file mode 100644
index 0000000000..517aa594cd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeUnaryWordValue.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+
+/-!
+# Binary word increment for the unary input routine
+
+Reading one unary mark adds one to a fixed-width little-endian word. The scan
+keeps a single carry bit in finite control, including the carry out of the
+highest bit. The input-length and unit words both fit the allocated width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.UnaryWord
+
+open BurstRAM TapeWord
+
+/-- Add the incoming carry to a little-endian bit list and retain the overflow bit. -/
+def incScan : Bool → List Bool → List Bool × Bool
+ | carry, [] => ([], carry)
+ | carry, b :: bits =>
+ let (rest, final) := incScan (b && carry) bits
+ ((b ^^ carry) :: rest, final)
+
+theorem incScan_length (carry : Bool) (bits : List Bool) :
+ (incScan carry bits).1.length = bits.length := by
+ induction bits generalizing carry with
+ | nil => rfl
+ | cons b bits ih => simp [incScan, ih]
+
+theorem incScan_value (carry : Bool) (bits : List Bool) :
+ value (incScan carry bits).1 + 2 ^ bits.length * (incScan carry bits).2.toNat =
+ value bits + carry.toNat := by
+ induction bits generalizing carry with
+ | nil => simp [incScan, value]
+ | cons b bits ih =>
+ have h := ih (b && carry)
+ have hdigit : (b ^^ carry).toNat + 2 * (b && carry).toNat = b.toNat + carry.toNat := by
+ cases b <;> cases carry <;> decide
+ simp only [incScan, value, List.length_cons, pow_succ, Nat.mul_right_comm _ 2 _]
+ omega
+
+/-- If the increment fits in the allocated word, the result retains its full value. -/
+theorem incScan_value_of_lt (carry : Bool) (bits : List Bool)
+ (hfit : value bits + carry.toNat < 2 ^ bits.length) :
+ value (incScan carry bits).1 = value bits + carry.toNat := by
+ have h := incScan_value carry bits
+ cases hc : (incScan carry bits).2 <;> simp [hc] at h <;> omega
+
+theorem zeros_value (k : ℕ) : value (List.replicate k false) = 0 :=
+ TapeWord.value_zeros k
+
+/-- Allocated word width for a program parameter `p` and unary input length `n`. -/
+def width (p n : ℕ) : ℕ := (p + 1) * (n + 1)
+
+theorem width_pos (p n : ℕ) : 0 < width p n := Nat.mul_pos (by omega) (by omega)
+
+/-- The encoded length fits even for a zero program parameter. -/
+def inputWord (p n : ℕ) : Word (width p n) :=
+ ⟨n, by
+ have hn : n + 1 ≤ width p n := Nat.le_mul_of_pos_left _ (by omega)
+ exact (Nat.lt_of_succ_le hn).trans (Nat.lt_pow_self (by decide))⟩
+
+@[simp] theorem inputWord_val (p n : ℕ) : (inputWord p n).val = n := rfl
+
+/-- The word one is available for every input, including the empty input. -/
+def unitWord (p n : ℕ) : Word (width p n) :=
+ ⟨1, lt_of_le_of_lt (width_pos p n) (Nat.lt_pow_self (by decide))⟩
+
+@[simp] theorem unitWord_val (p n : ℕ) : (unitWord p n).val = 1 := rfl
+
+theorem zeros_wordBits (w : ℕ) : List.replicate w false = wordBits (0 : Word w) :=
+ eq_of_length_value (by simp) (by simp [value_wordBits])
+
+theorem unit_wordBits (p n : ℕ) :
+ true :: List.replicate (width p n - 1) false = wordBits (unitWord p n) := by
+ apply eq_of_length_value
+ · simp only [List.length_cons, List.length_replicate, length_wordBits]
+ have := width_pos p n
+ omega
+ · simp [value, value_wordBits]
+
+end RAMTape.UnaryWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeValidatorSetup.lean b/lean/OAI/Computability/VPVNP/RAMTapeValidatorSetup.lean
new file mode 100644
index 0000000000..e765ddef65
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeValidatorSetup.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.RAMTapePhysicalInput
+import OAI.Computability.VPVNP.RAMTapeSiteSizes
+import OAI.Computability.VPVNP.RAMTapeMapWord
+
+/-! # Starting the local validator on its physical tape
+
+The fixed input reader and width routines share the public address and bucket
+registers. At their return the fields are in their original bit order. The record
+emitter receives a writable slot counter and a zero-word template, while a
+second slot count remains available for sorting and boundary checks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.SiteSetup
+
+open BurstRAM ProcessorInput RAMLayout StackCompiler
+
+/-- Working registers for computing the validator dimensions, remaining slot tally, zero
+template, and temporary storage. -/
+inductive Work
+ | shape (p : InputWidth.Port)
+ | remaining | zeros | tmp
+ deriving DecidableEq
+
+noncomputable instance : Fintype Work := derive_fintype% Work
+
+/-- Combined register bank for the physical input reader and validator setup. -/
+abbrev Port := InputReader.Registers ⊕ Work
+
+/-- Port for the input reader's raw bit stream. -/
+def rawPort : Port := .inl (.inl .input)
+/-- Port for the unary RAM word width computed from the input dimensions. -/
+def wordPort : Port := .inr (.shape .word)
+/-- Port for the retained unary count of record slots. -/
+def slotsPort : Port := .inr (.shape .blocks)
+/-- Writable slot counter used by the record emitter. -/
+def remainingPort : Port := .inr .remaining
+/-- Port for the fixed-width all-zero word template. -/
+def zerosPort : Port := .inr .zeros
+private def tmpPort : Port := .inr .tmp
+
+private def shapePort : InputWidth.Port → Port
+ | .address => .inl InputReader.addressWidthPort
+ | .bucket => .inl InputReader.bucketPort
+ | p => .inr (.shape p)
+
+private theorem shape_injective : Function.Injective shapePort := by
+ intro a b h
+ cases a <;> cases b <;> simp_all [shapePort, InputReader.addressWidthPort, InputReader.bucketPort]
+
+private def sizes : FiniteRoutine Port :=
+ (FiniteRoutine.ofRoutine InputWidth.siteSizeProgram.code).onPorts shapePort
+
+private def shaped (s : Stacks InputReader.Registers) (d H : ℕ) : Stacks Port
+ | .inl i => s i
+ | .inr (.shape .word) => List.replicate ((d+10)^4) true
+ | .inr (.shape .blocks) => List.replicate (4*H) true
+ | .inr _ => []
+
+/-- Extend the shaped bank with four times the bucket capacity in remaining slots and a zero
+word of the computed width. -/
+def prepared (s : Stacks InputReader.Registers) (d H : ℕ) : Stacks Port :=
+ Function.update (Function.update (shaped s d H) remainingPort (List.replicate (4*H) true))
+ zerosPort (List.replicate ((d+10)^4) false)
+
+private theorem sizes_run (s : Stacks InputReader.Registers) (d H : ℕ)
+ (hd : s InputReader.addressWidthPort = List.replicate d true)
+ (hH : s InputReader.bucketPort = List.replicate H true) :
+ sizes.Runs (InputWidth.siteSizeProgram.work (InputWidth.initial d H))
+ (Sum.elim s (fun _ => [])) (shaped s d H) := by
+ apply FiniteRoutine.runs_onPorts_framed _ shape_injective (InputWidth.siteSizes_runs d H)
+ · intro p; cases p <;> first | rfl | exact hd | exact hH
+ · intro p; cases p <;> first | rfl | exact hd | exact hH
+ · rintro (i | w) hm
+ · rfl
+ · cases w with
+ | shape p =>
+ cases p <;> first | rfl | exact (hm .word rfl).elim | exact (hm .blocks rfl).elim
+ | remaining | zeros | tmp => rfl
+
+private def templates : FiniteRoutine Port :=
+ (WordCopy.mapWord tmpPort remainingPort id slotsPort).followedBy
+ (WordCopy.mapWord tmpPort zerosPort (fun _ => false) wordPort)
+
+private theorem templates_run (s : Stacks InputReader.Registers) (d H : ℕ) :
+ templates.Runs (5*(4*H)+2 + (5*(d+10)^4+2)) (shaped s d H) (prepared s d H) := by
+ let u := shaped s d H
+ let v := Function.update u remainingPort (List.replicate (4*H) true)
+ have h₁ := WordCopy.mapWord_run tmpPort remainingPort id (src := slotsPort)
+ (by decide) (by decide) (by decide) u rfl
+ change (WordCopy.mapWord tmpPort remainingPort id slotsPort).Runs
+ (5*(List.replicate (4*H) true).length+2) u
+ (Function.update u remainingPort (((List.replicate (4*H) true).map id).reverse ++ [])) at h₁
+ simp only [List.length_replicate, List.map_id_fun, id_eq, List.reverse_replicate, List.append_nil] at h₁
+ have h₂ := WordCopy.zero_template tmpPort zerosPort (src := wordPort)
+ (by decide) (by decide) (by decide) v rfl rfl
+ change (WordCopy.mapWord tmpPort zerosPort (fun _ => false) wordPort).Runs
+ (5*(List.replicate ((d+10)^4) true).length+2) v
+ (Function.update v zerosPort (List.replicate (List.replicate ((d+10)^4) true).length false)) at h₂
+ simp only [List.length_replicate] at h₂
+ exact h₁.followedBy h₂
+
+/-- Run the physical input reader, compute the dimensions, and prepare the slot counter and
+zero-word template. -/
+def routine (B p q : ℕ) (hq : 0 < q) : FiniteRoutine Port :=
+ (((InputReader.physicalReader B p q hq).onPorts Sum.inl).followedBy sizes).followedBy templates
+
+/-- The initialized local bank and polynomial clock depend only on the data read from
+the original physical input, for every incident bit pattern. -/
+theorem runs (B p q : ℕ) (hq : 0 < q) (hpq : p ≤ q) (prog : UniversalMachine.Program)
+ (n : ℕ) (hn : 1 ≤ n) :
+ let d := B * Nat.clog 2 n
+ let H := 2 ^ roundedUp p q n
+ let w := (d+10)^4
+ ∀ (v : Fin (2^d)) (hdr : Header) (inc : Fin (width d H w) → Bool),
+ Fits prog n d H w →
+ ∃ steps ≤ (InputParameters.clockCoefficient B p q+43+1026*(B+13)^7)*(n+1)^7,
+ (routine B p q hq).Runs steps (labeledInput rawPort (ProcessorInput.tape prog n v hdr inc))
+ (prepared (InputReader.physicalResult n d H (UniversalMachine.programPrefix prog)
+ (List.ofFn (RAMSerialization.wordBits d v)) (List.ofFn hdr) (List.ofFn inc)) d H) := by
+ intro d H w v hdr inc hf
+ let raw := ProcessorInput.tape prog n v hdr inc
+ let out := InputReader.physicalResult n d H (UniversalMachine.programPrefix prog)
+ (List.ofFn (RAMSerialization.wordBits d v)) (List.ofFn hdr) (List.ofFn inc)
+ obtain ⟨t, ht, hr⟩ := InputReader.physicalReader_runs B p q hq hpq prog n hn v hdr inc hf
+ have h₁ : ((InputReader.physicalReader B p q hq).onPorts Sum.inl).Runs t
+ (labeledInput rawPort raw) (Sum.elim out (fun _ => [])) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective hr
+ · intro i; simp [labeledInput, rawPort, raw]
+ · intro i; rfl
+ · rintro (i | j) hi
+ · exact (hi i rfl).elim
+ · rfl
+ have h₂ := sizes_run out d H rfl rfl
+ have h₃ := templates_run out d H
+ refine ⟨_, ?_, (h₁.followedBy h₂).followedBy h₃⟩
+ let M := d+H+11
+ have hm : 0 < M := Nat.add_pos_right _ (by decide)
+ have hM : M ≤ M^7 := by simpa using Nat.pow_le_pow_right hm (by decide : 1 ≤ 7)
+ have hH : H ≤ M := by dsimp [M]; omega
+ have hsmall : d+10 ≤ M := Nat.add_le_add (Nat.le_add_right d H) (by decide : 10 ≤ 11)
+ have hw : (d+10)^4 ≤ M^7 :=
+ (Nat.pow_le_pow_left hsmall 4).trans
+ (Nat.pow_le_pow_right hm (by decide))
+ have hprep := InputWidth.siteSizes_work_le d H
+ change _ ≤ 1000*M^7 at hprep
+ have htotal : InputWidth.siteSizeProgram.work (InputWidth.initial d H) +
+ (5*(4*H)+2+(5*(d+10)^4+2)) ≤ 1026*M^7 := by omega
+ have hd : d ≤ B*n := Nat.mul_le_mul_left _ (Nat.clog_le_of_le_pow (Nat.lt_pow_self (by decide : 1 < 2)).le)
+ have hbucket : H ≤ 2*n := InputBucketFromSize.bucket_le hq hpq hn
+ have hparam : M ≤ (B+13)*(n+1) := by
+ dsimp [M]
+ rw [Nat.add_mul, Nat.mul_add, Nat.mul_one]
+ omega
+ have hscaled := (Nat.mul_le_mul_left 1026 (Nat.pow_le_pow_left hparam 7))
+ rw [Nat.mul_pow, ← Nat.mul_assoc] at hscaled
+ rw [Nat.add_mul]
+ omega
+
+end RAMTape.SiteSetup
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeVirtualSite.lean b/lean/OAI/Computability/VPVNP/RAMTapeVirtualSite.lean
new file mode 100644
index 0000000000..4e72cd9cb0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeVirtualSite.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.RAMProcessorCallInvariant
+import OAI.Computability.VPVNP.RAMProcessorPrelude
+import OAI.Computability.VPVNP.RAMTapeSuccessorCuts
+import OAI.Computability.VPVNP.RAMTapeSiteRecordWords
+import OAI.Computability.VPVNP.RAMTapeSuccessorParameters
+
+/-!
+# Full-word inputs to the auxiliary site verifier
+
+Section 12 places the auxiliary verifier at a cursor-zero vertex. Its header
+may contain a full histogram word. Its site-address width, machine-word
+width and private clock are independent public parameters of the virtual
+network.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.VirtualSite
+
+open BurstRAM PrivateRAM RAMLayout SiteProcessor
+
+/-- Full-word virtual site input, including its independent clock and incident sends. -/
+structure Input (d e w : ℕ) where
+ /-- Private instruction limit for each call of the auxiliary RAM. -/
+ fuel : ℕ
+ /-- Address of the virtual site. -/
+ v : Word d
+ /-- Initial persistent state of the auxiliary machine. -/
+ initialWord : Word w
+ /-- Auxiliary memory word initially stored at this address. -/
+ headerWord : Word w
+ /-- All shared successor and sorting messages on the virtual RAM network. -/
+ sends : SendArrays d (2^e) w
+ hw : 2 ≤ w
+ hc : 2^d*2^e < 2^w
+
+variable {d e w p r k : ℕ} (x : Input d e w)
+
+include x in
+theorem Input.hcap : d+e < w := by
+ have h := x.hc
+ rw [← pow_add] at h
+ exact (Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp h
+
+/-- Reconstructed incoming and outgoing cuts for the virtual site. -/
+def Input.summary : SiteSuccessors w :=
+ (scanSuccessors x.hw x.hc x.initialWord x.v (sortIncident x.sends x.v)).1
+
+/-- Validity of the site's transmitted and received successor messages. -/
+def Input.valid : Prop := SuccessorSendOK x.hw x.hc x.sends x.v ∧ SuccessorReceiveOK x.hw x.hc x.sends x.v
+
+/-- Word encoding the cumulative cost of the chosen boundary cut. -/
+def Input.sideWord (side : Successors.Side) : Word w := Fin.ofNat (2^w) (Successors.sideCut x.summary side).cost
+
+/-- Zero-extended virtual site address in the auxiliary word format. -/
+def Input.addrWord : Word w := SiteRecordWords.addressWord ((Nat.le_add_right d e).trans x.hcap.le) x.v
+
+/-- Full interpreter snapshot before it emits the initialization record. -/
+def Input.bare (T : Template p r k) (pub : Fin k → Word w) (bits : List Bool) :
+ Snapshot w p r k where
+ pub := pub
+ cfg := ⟨T.entry, x.summary.input.state.getD 0, fun _ => 0, []⟩
+ publicH := 2^e
+ publicFuel := x.fuel
+ fuel := 0
+ callLeft := 0
+ siteLeft := 2*2^e-1
+ cap := SuccessorParameters.capWord d e w x.hcap
+ globalLeft := 0
+ cost := x.sideWord .receive
+ savedStart := []
+ ordinal := []
+ lower := SiteEndpoints.startWord e w x.v x.hcap
+ boundary := SiteEndpoints.endWord e w x.v x.hcap
+ targetCost := x.sideWord .send
+ targetState := (Successors.sideCut x.summary .send).state.getD 0
+ running := x.summary.input.state.isSome
+ hasTarget := x.summary.output.isSome
+ targetRunning := (Successors.sideCut x.summary .send).state.isSome
+ choices := bits
+ tag := []
+ address := BurstRAM.wordBits x.addrWord
+ value := BurstRAM.wordBits x.headerWord
+ remaining := List.replicate (4*2^e) true
+ reverseBuffer := []
+ output := []
+
+theorem Input.sideWord_val (side : Successors.Side) : (x.sideWord side).val = (Successors.sideCut x.summary side).cost := by
+ have hs := scanSuccessors_spec x.hw x.hc x.initialWord x.v (sortIncident x.sends x.v) x.sends (sortIncident_offset x.sends x.v)
+ have hb : (Successors.sideCut x.summary side).cost ≤ 2^d*2^e := by
+ cases side with
+ | receive =>
+ change (scanSuccessors x.hw x.hc x.initialWord x.v (sortIncident x.sends x.v)).1.input.cost ≤ _
+ rw [hs.input_eq]
+ unfold inputCut
+ split <;> first | exact Nat.zero_le _ | exact Nat.le_of_lt_succ (Fin.isLt _)
+ | send =>
+ change ((scanSuccessors x.hw x.hc x.initialWord x.v (sortIncident x.sends x.v)).1.output.getD ⟨0,none⟩).cost ≤ _
+ rw [hs.output_eq]
+ unfold outputCut
+ split <;> first | exact Nat.zero_le _ | exact Nat.le_of_lt_succ (Fin.isLt _)
+ exact Nat.mod_eq_of_lt (hb.trans_lt x.hc)
+
+theorem Input.bare_cut (T : Template p r k) (pub : Fin k → Word w) (bits : List Bool) :
+ (x.bare T pub bits).tests.cut = x.summary.input := by
+ apply Cut.ext
+ · exact x.sideWord_val .receive
+ · change (if x.summary.input.state.isSome then some (x.summary.input.state.getD 0) else none) = _
+ cases x.summary.input.state <;> rfl
+
+theorem Input.bare_target (T : Template p r k) (pub : Fin k → Word w) (bits : List Bool) :
+ (x.bare T pub bits).tests.target = x.summary.output := by
+ have hc := x.sideWord_val .send
+ change (x.sideWord .send).val = (x.summary.output.getD ⟨0,none⟩).cost at hc
+ change (if x.summary.output.isSome then some ⟨(x.sideWord .send).val,
+ if (x.summary.output.getD ⟨0,none⟩).state.isSome then some ((x.summary.output.getD ⟨0,none⟩).state.getD 0)
+ else none⟩ else none) = x.summary.output
+ rw [hc]
+ cases x.summary.output with
+ | none => rfl
+ | some c => obtain ⟨c,status⟩ := c; cases status <;> rfl
+
+end RAMTape.VirtualSite
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeVirtualSiteGraph.lean b/lean/OAI/Computability/VPVNP/RAMTapeVirtualSiteGraph.lean
new file mode 100644
index 0000000000..c57c3d9b2e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeVirtualSiteGraph.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.RAMTapeVirtualSite
+import OAI.Computability.VPVNP.RAMProcessorCallRun
+import OAI.Computability.VPVNP.RAMProcessorInitRun
+import OAI.Computability.VPVNP.RAMProcessorChargedRun
+
+/-!
+# The call graph on the parsed site's own incoming and outgoing fields
+
+The controller emits a full-word initialization record for its auxiliary site. From
+that bank the call loop tests its incoming cost bucket, simulates the private
+instructions, checks the outgoing cut and closes the ordered record buffer.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.VirtualSite
+
+open BurstRAM PrivateRAM RAMSerialization SiteProcessor
+
+variable {d e w p r k : ℕ} (x : Input d e w) (T : Template p r k) (pub : Fin k → Word w) (bits : List Bool)
+
+/-- Initialization record for the actual auxiliary site's address and header word. -/
+def Input.initSlot := SiteProcessor.initRecord x.addrWord x.headerWord
+
+/-- Fresh processor snapshot with its initialization fields in place. -/
+def Input.staged : Snapshot w p r k := ((x.bare T pub bits).afterFresh T).withInitFields x.addrWord
+
+/-- Snapshot after the native graph emits its first memory record. -/
+def Input.entered : Snapshot w p r k := (x.staged T pub bits).afterEmit x.hw x.initSlot
+
+theorem Input.init_run :
+ StackRuns (table T) (25*w+12) (atLabel T .initialRecord) (x.staged T pub bits).bank
+ (atLabel T .checkEntry) (x.entered T pub bits).bank ∧
+ RecordBuffer.Holds x.hw (2^e) [x.initSlot] (x.entered T pub bits).records :=
+ initialRecord_run T ((x.bare T pub bits).afterFresh T) x.hw x.addrWord x.headerWord
+ rfl rfl rfl rfl rfl (Nat.two_pow_pos _)
+
+theorem Input.entered_ready :
+ CallReady x.hw (2^e) x.fuel true (x.entered T pub bits) [x.initSlot] := by
+ have hp := Nat.two_pow_pos e
+ refine ⟨rfl,rfl,hp,?_,?_,(x.init_run T pub bits).2,Nat.zero_le _,Nat.zero_le _,?_,?_,?_,?_,?_,nofun,?_⟩
+ · exact Nat.mul_le_mul_right _ x.v.isLt
+ · change 1+(2*2^e-1) ≤ 4*2^e
+ omega
+ · exact (length_wordBits _).le
+ · exact (length_wordBits _).le
+ · exact (length_wordBits _).le
+ · exact (length_wordBits _).le
+ · exact (length_wordBits _).le
+ · intro _
+ change 0 < 2*2^e-1
+ omega
+
+/-- Auxiliary site reports accepted on the nominated private choice string. -/
+def Input.validated :=
+ validateSite (T.instantiate w pub).program x.fuel (2^d) (2^e) x.v.val
+ x.summary.input x.summary.output bits
+
+/-- Work bound for initialization, interpreting all calls and closing the site. -/
+def graphBudget (r w e fuel : ℕ) : ℕ :=
+ 25*w+12+siteWork w (2^e) (perCallEstimate r w (2^e) fuel)+closeWork w (2^e)
+
+/-- Acceptance or rejection of the actual stack graph on the supplied private choices. -/
+def Input.GraphOutcome (t : ℕ) : Prop :=
+ match x.validated T pub bits with
+ | none => RejectRun (table T) t (atLabel T .initialRecord) (x.staged T pub bits).bank
+ | some rs => ∃ (u : Snapshot w p r k) (ys : List (WordRecord w)), ys.map WordRecord.record =
+ x.initSlot.record :: probeRecords x.summary.input.cost rs ∧
+ StackRuns (table T) t (atLabel T .initialRecord) (x.staged T pub bits).bank
+ (atLabel T .done) (u.afterClose x.hw (2^e) ys).bank
+
+theorem Input.graphOutcome_of_start
+ (start : StartRuns T (CallReady x.hw (2^e) x.fuel) (perCallEstimate r w (2^e) x.fuel)) :
+ ∃ t ≤ graphBudget r w e x.fuel, x.GraphOutcome T pub bits t := by
+ let s := x.entered T pub bits
+ obtain ⟨b,hb,hr⟩ := checkEntry_close start x.hw (fun _ _ _ h => h.toHolds) s [x.initSlot]
+ (x.entered_ready T pub bits) (2^d) x.v.val rfl rfl rfl rfl
+ have hc : s.tests.cut = x.summary.input := x.bare_cut T pub bits
+ have ht : s.tests.target = x.summary.output := x.bare_target T pub bits
+ rw [hc, ht] at hr
+ change ClosedRun T x.hw s [x.initSlot] .checkEntry b (x.validated T pub bits) at hr
+ have init := (x.init_run T pub bits).1
+ change b ≤ siteWork w (2^e) (perCallEstimate r w (2^e) x.fuel)+closeWork w (2^e) at hb
+ refine ⟨25*w+12+b, by unfold graphBudget; omega, ?_⟩
+ unfold Input.GraphOutcome
+ cases he : x.validated T pub bits with
+ | none => rw [he] at hr; exact init.thenReject hr
+ | some rs =>
+ rw [he] at hr
+ obtain ⟨u, ys, hp, run⟩ := hr
+ have hcost : s.cost.val = x.summary.input.cost := congrArg Cut.cost hc
+ have records := hp.records
+ rw [hcost] at records
+ exact ⟨u,ys,records,init.trans run⟩
+
+theorem Input.graphOutcome :
+ ∃ t ≤ graphBudget r w e x.fuel, x.GraphOutcome T pub bits t :=
+ x.graphOutcome_of_start T pub bits (startRuns_of_segments T (segment_correct T))
+
+end RAMTape.VirtualSite
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWord.lean b/lean/OAI/Computability/VPVNP/RAMTapeWord.lean
new file mode 100644
index 0000000000..0f99d1e03f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWord.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.RAMWordBits
+import Mathlib.Data.Nat.Bitwise
+
+/-!
+# Little-endian bit scans for the word RAM
+
+A word occupies one stack cell per bit. The elementary binary transducers
+scan two equal-length stacks from low to high, remembering one carry or
+borrow bit in their finite control. The final carry or borrow certifies the
+arithmetic even when the result wraps around.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord
+
+/-- Unsigned value of a little-endian list of bits, with the empty list representing zero. -/
+def value : List Bool → ℕ
+ | [] => 0
+ | b :: xs => b.toNat + 2 * value xs
+
+theorem value_lt (xs : List Bool) : value xs < 2 ^ xs.length := by
+ induction xs with
+ | nil => decide
+ | cons b xs ih =>
+ cases b <;> simp only [value, Bool.toNat_true, Bool.toNat_false, List.length_cons, pow_succ] <;> omega
+
+theorem value_ofFn (w : ℕ) (d : Fin w → Bool) :
+ value (List.ofFn d) = ∑ i, (d i).toNat * 2 ^ i.val := by
+ induction w with
+ | zero => simp [value]
+ | succ w ih =>
+ rw [List.ofFn_succ, value, ih, Fin.sum_univ_succ]
+ simp only [Fin.val_zero, pow_zero, mul_one, Fin.val_succ, pow_succ, ← Nat.mul_assoc,
+ ← Finset.sum_mul]
+ rw [Nat.mul_comm]
+
+theorem value_wordBits {w : ℕ} (a : BurstRAM.Word w) : value (BurstRAM.wordBits a) = a.val := by
+ let d := RAMSerialization.wordBits w a
+ have he : ((RAMSerialization.wordBits w).symm d).val =
+ ∑ i, (finTwoEquiv.symm (d i)).val * 2 ^ i.val := finFunctionFinEquiv_apply _
+ have hd (i : Fin w) : (finTwoEquiv.symm (d i)).val = (d i).toNat := by cases d i <;> rfl
+ rw [show (RAMSerialization.wordBits w).symm d = a from Equiv.symm_apply_apply _ _] at he
+ simpa only [BurstRAM.wordBits, value_ofFn, hd] using he.symm
+
+theorem eq_of_length_value {xs ys : List Bool} (hlen : xs.length = ys.length)
+ (hval : value xs = value ys) : xs = ys := by
+ induction xs generalizing ys with
+ | nil => simpa using hlen.symm
+ | cons b xs ih =>
+ cases ys with
+ | nil => simp at hlen
+ | cons d ys =>
+ simp only [List.length_cons, Nat.succ.injEq] at hlen
+ cases b <;> cases d <;> simp only [value, Bool.toNat_true, Bool.toNat_false] at hval <;>
+ first | exact congrArg (_ :: ·) (ih hlen (by omega)) | omega
+
+/-- A synchronous transducer. When the inputs are equally long it reads one
+bit from each stack per emitted bit and leaves its final control state. -/
+def scan (step : Bool → Bool → Bool → Bool × Bool) : Bool → List Bool → List Bool → List Bool × Bool
+ | c, b :: bs, d :: ds =>
+ let (out, next) := step c b d
+ let (rest, final) := scan step next bs ds
+ (out :: rest, final)
+ | c, _, _ => ([], c)
+
+theorem length_scan (step : Bool → Bool → Bool → Bool × Bool) (c : Bool) (x y : List Bool)
+ (hlen : x.length = y.length) : (scan step c x y).1.length = x.length := by
+ induction x generalizing c y with
+ | nil => rfl
+ | cons b bs ih =>
+ cases y with
+ | nil => simp at hlen
+ | cons d ds => simp [scan, ih _ _ (Nat.succ.inj hlen)]
+
+/-- Compute the sum bit and outgoing carry for two operand bits and an incoming carry. -/
+def addBit (c b d : Bool) : Bool × Bool :=
+ ((b ^^ d) ^^ c, (b && d) || (c && (b ^^ d)))
+
+/-- Compute the difference bit and outgoing borrow for two operand bits and an incoming borrow. -/
+def subBit (c b d : Bool) : Bool × Bool :=
+ ((b ^^ d) ^^ c, (!b && d) || (c && !(b ^^ d)))
+
+/-- Scan paired little-endian bits with a carry and return the sum bits and final carry when
+either input ends. -/
+abbrev addScan := scan addBit
+/-- Scan paired little-endian bits with a borrow and return the difference bits and final
+borrow when either input ends. -/
+abbrev subScan := scan subBit
+
+theorem length_addScan {c : Bool} {x y : List Bool} (hlen : x.length = y.length) :
+ (addScan c x y).1.length = x.length := length_scan _ _ _ _ hlen
+
+theorem length_subScan {c : Bool} {x y : List Bool} (hlen : x.length = y.length) :
+ (subScan c x y).1.length = x.length := length_scan _ _ _ _ hlen
+
+theorem addScan_spec {c : Bool} {x y : List Bool} (hlen : x.length = y.length) :
+ value (addScan c x y).1 + 2 ^ x.length * (addScan c x y).2.toNat =
+ value x + value y + c.toNat := by
+ induction x generalizing c y with
+ | nil => cases y <;> simp_all [addScan, scan, value]
+ | cons b bs ih =>
+ cases y with
+ | nil => simp at hlen
+ | cons d ds =>
+ have h := ih (c := (addBit c b d).2) (Nat.succ.inj hlen)
+ have hlow : (addBit c b d).1.toNat + 2 * (addBit c b d).2.toNat =
+ b.toNat + d.toNat + c.toNat := by cases c <;> cases b <;> cases d <;> decide
+ simp only [addScan] at h
+ simp only [addScan, scan, value, List.length_cons, pow_succ, Nat.mul_right_comm _ 2 _]
+ omega
+
+theorem subScan_spec {c : Bool} {x y : List Bool} (hlen : x.length = y.length) :
+ value (subScan c x y).1 + value y + c.toNat =
+ value x + 2 ^ x.length * (subScan c x y).2.toNat := by
+ induction x generalizing c y with
+ | nil => cases y <;> simp_all [subScan, scan, value]
+ | cons b bs ih =>
+ cases y with
+ | nil => simp at hlen
+ | cons d ds =>
+ have h := ih (c := (subBit c b d).2) (Nat.succ.inj hlen)
+ have hlow : (subBit c b d).1.toNat + d.toNat + c.toNat =
+ b.toNat + 2 * (subBit c b d).2.toNat := by cases c <;> cases b <;> cases d <;> decide
+ simp only [subScan] at h
+ simp only [subScan, scan, value, List.length_cons, pow_succ, Nat.mul_right_comm _ 2 _]
+ omega
+
+/-- Parallel Boolean operations use the same scan with a single dummy state. -/
+abbrev logicScan (op : Bool → Bool → Bool) := scan (fun _ b d => (op b d, false)) false
+
+theorem logicScan_spec {op : Bool → Bool → Bool} (hzero : op false false = false)
+ {x y : List Bool} (hlen : x.length = y.length) :
+ value (logicScan op x y).1 = Nat.bitwise op (value x) (value y) := by
+ induction x generalizing y with
+ | nil => cases y <;> simp_all [value, logicScan, scan]
+ | cons b bs ih =>
+ cases y with
+ | nil => simp at hlen
+ | cons d ds =>
+ have hbit (e : Bool) (n : ℕ) : Nat.bit e n = e.toNat + 2 * n := by
+ cases e <;> simp [Nat.bit, Nat.add_comm]
+ simp only [logicScan, scan, value]
+ rw [← hbit b, ← hbit d, Nat.bitwise_bit hzero, hbit, ← ih (Nat.succ.inj hlen)]
+
+end TapeWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordComparison.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordComparison.lean
new file mode 100644
index 0000000000..f2a059fbf3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordComparison.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.RAMTapeWordSimple
+import OAI.Computability.VPVNP.RAMTapeStackLift
+
+/-!
+# Conditional jumps on staged RAM words
+
+The equality scan remembers whether all pairs of bits have agreed so far.
+For an unsigned less-than test, the subtraction scan's final borrow gives
+the answer. The machine clears the emitted word before returning, keeping
+the branch bit in finite control. The two staged inputs may contain copies
+of the same register.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.Comparison
+
+open RAMTape BurstRAM
+
+/-- Equality and unsigned less-than operations used by word-RAM conditional branches. -/
+inductive Op where
+ | eq | lt
+ deriving DecidableEq
+
+/-- Initialize the equality flag to true or the subtraction borrow to false. -/
+def Op.initial : Op → Bool
+ | .eq => true
+ | .lt => false
+
+/-- Update the equality flag and emit zero, or perform a subtraction bit step to update the
+less-than borrow. -/
+def Op.step : Op → Bool → Bool → Bool → Bool × Bool
+ | .eq => fun c x y => (false, c && (x == y))
+ | .lt => subBit
+
+/-- Evaluate the selected equality or unsigned less-than test directly on two fixed-width
+words. -/
+def Op.eval {w : ℕ} : Op → Word w → Word w → Bool
+ | .eq, a, b => decide (a = b)
+ | .lt, a, b => decide (a < b)
+
+/-- Control states for executing the comparison bit scan and returning its branch decision. -/
+inductive State where
+ | scan (q : ScanState) | done (branch : Bool)
+ deriving DecidableEq, Fintype
+
+/-- Install the word scan, using its terminal flag while draining the output. -/
+def code (op : Op) : StackCode ScanPort State
+ | .scan (.done f) => .pop .out fun b => b.elim (.done f) fun _ => .scan (.done f)
+ | .scan q => (scanCode op.step q).rename id State.scan
+ | .done _ => .halt true
+
+private theorem eq_flag (c : Bool) (xs ys : List Bool) (hlen : xs.length = ys.length) :
+ (TapeWord.scan Op.eq.step c xs ys).2 = (c && decide (xs = ys)) := by
+ induction xs generalizing c ys with
+ | nil =>
+ have hnil : ys = [] := List.length_eq_zero_iff.mp hlen.symm
+ subst ys
+ simp [TapeWord.scan]
+ | cons x xs ih =>
+ cases ys with
+ | nil => simp at hlen
+ | cons y ys =>
+ rw [TapeWord.scan, ih _ ys (Nat.succ.inj hlen)]
+ cases x <;> cases y <;> simp [Op.step]
+
+private theorem flag {w : ℕ} (op : Op) (a b : Word w) :
+ (TapeWord.scan op.step op.initial (wordBits a) (wordBits b)).2 = op.eval a b := by
+ have hlen : (wordBits a).length = (wordBits b).length := by simp
+ cases op with
+ | eq =>
+ have he : wordBits a = wordBits b ↔ a = b := by
+ refine ⟨fun h => Fin.ext ?_, congrArg wordBits⟩
+ simpa only [value_wordBits] using congrArg value h
+ simp [eq_flag _ _ _ hlen, Op.initial, Op.eval, he]
+ | lt =>
+ apply Bool.eq_iff_iff.mpr
+ change (subScan false (wordBits a) (wordBits b)).2 = true ↔ decide (a.val < b.val) = true
+ simpa only [value_wordBits, Bool.toNat_false, Nat.add_zero, decide_eq_true_eq] using
+ subScan_borrow (c := false) hlen
+
+private theorem install_id (base small : Stacks ScanPort) : installStacks id base small = small := by
+ funext i
+ exact installStacks_at Function.injective_id base small i
+
+private theorem drain (op : Op) (f : Bool) (out : List Bool) :
+ StackRuns (code op) (out.length + 1) (.scan (.done f)) (scanStacks [] [] [] out)
+ (.done f) (scanStacks [] [] [] []) := by
+ have updateOut (x y : List Bool) : Function.update (scanStacks [] [] [] x) .out y =
+ scanStacks [] [] [] y := by funext p; cases p <;> simp [scanStacks]
+ induction out with
+ | nil =>
+ refine .cons (.pop rfl) ?_
+ simp only [scanStacks, List.head?_nil, List.tail_nil, Option.elim_none, updateOut]
+ exact .nil ..
+ | cons b out ih =>
+ refine .cons (.pop rfl) ?_
+ simp only [scanStacks, List.head?_cons, List.tail_cons, Option.elim_some, updateOut]
+ exact ih
+
+/-- From two operand copies, return the exact conditional-jump decision and
+empty all four ports in a width-independent control. -/
+theorem word_run {w : ℕ} (op : Op) (a b : Word w) :
+ StackRuns (code op) (6 * w + 3) (.scan (.left op.initial))
+ (scanStacks (wordBits a) (wordBits b) [] [])
+ (.done (op.eval a b)) (scanStacks [] [] [] []) := by
+ have hlen : (wordBits a).length = (wordBits b).length := by simp
+ let u := TapeWord.scan op.step op.initial (wordBits a) (wordBits b)
+ have hs := scanRuns op.step op.initial (wordBits a) (wordBits b) [] hlen
+ have rows (q : ScanState) (h : (scanCode op.step q).returns = false) :
+ code op (.scan q) = (scanCode op.step q).rename id State.scan := by
+ cases q <;> first | rfl | contradiction
+ have run := hs.lift id Function.injective_id State.scan (fun _ => []) rows
+ simp only [install_id, length_wordBits, List.append_nil, flag] at run
+ have hw : u.1.length = w := (length_scan op.step op.initial _ _ hlen).trans (length_wordBits a)
+ have clear := drain op (op.eval a b) u.1
+ rw [hw] at clear
+ convert run.trans clear using 1
+ omega
+
+end TapeWord.Comparison
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordDivision.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordDivision.lean
new file mode 100644
index 0000000000..5ab7ecdbe0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordDivision.lean
@@ -0,0 +1,139 @@
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+import OAI.Computability.VPVNP.RAMProgram
+
+/-!
+# Restoring binary division on a word tape
+
+Process the dividend from its most significant bit to its least significant
+bit. At each iteration one subtract-with-borrow scan of width `w+1`
+determines the quotient bit. The next remainder is the low `w` bits of the
+difference or of the restored candidate. Zero divisor follows the natural
+word convention of the RAM instruction table.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord
+
+/-- Return the quotient bit and new remainder. The high zero on the divisor
+allows the left-shifted candidate to use its carry bit. -/
+def divideStep (d : List Bool) (b : Bool) (r : List Bool) : Bool × List Bool :=
+ let candidate := b :: r
+ let trial := subScan false candidate (d ++ [false])
+ if trial.2 then (false, candidate.take d.length) else (true, trial.1.take d.length)
+
+theorem divideStep_spec {d r : List Bool} (b : Bool)
+ (hlen : r.length = d.length) (hr : value r < value d) :
+ let t := divideStep d b r
+ t.2.length = d.length ∧ value t.2 < value d ∧
+ value d * t.1.toNat + value t.2 = b.toNat + 2 * value r := by
+ let x := b :: r
+ let y := d ++ [false]
+ let trial := subScan false x y
+ have hxy : x.length = y.length := by simp [x, y, hlen]
+ have ht : trial.1.length = d.length + 1 := by simpa [trial, x, hlen] using length_subScan hxy
+ have he := subScan_spec (c := false) hxy
+ change value trial.1 + value y + false.toNat = value x + 2 ^ x.length * trial.2.toNat at he
+ have hy : value y = value d := by simp [y, value_append, value]
+ have hx : value x = b.toNat + 2 * value r := rfl
+ have hbl : b.toNat ≤ 1 := by cases b <;> decide
+ have htrial := value_lt trial.1
+ have hd := value_lt d
+ rw [ht] at htrial
+ rw [hy, show x.length = d.length + 1 by simp [x, hlen]] at he
+ dsimp only
+ cases hb : trial.2 with
+ | false =>
+ simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at he
+ have hv : value trial.1 < value d := by omega
+ have hout : divideStep d b r = (true, trial.1.take d.length) := by
+ unfold divideStep
+ change (if trial.2 then _ else _ : Bool × List Bool) = _
+ simp [hb]; rfl
+ rw [hout]
+ rw [value_take_of_lt (hv.trans hd)]
+ exact ⟨by simp [ht], hv, by simp only [Bool.toNat_true, Nat.mul_one]; omega⟩
+ | true =>
+ simp only [hb, Bool.toNat_false, Nat.add_zero, Bool.toNat_true, Nat.mul_one] at he
+ have hv : value x < value d := by omega
+ have hout : divideStep d b r = (false, x.take d.length) := by
+ unfold divideStep
+ change (if trial.2 then _ else _ : Bool × List Bool) = _
+ simp [hb]; rfl
+ rw [hout]
+ have hlen' : d.length ≤ x.length := by simp [x, hlen]
+ rw [value_take_of_lt (hv.trans hd)]
+ exact ⟨by simp [hlen'], hv, by simp [hx]⟩
+
+/-- The recursive result on the tail is the result on the already consumed
+higher-order prefix. Quotient bits are consed in little-endian order. -/
+def dividePass (d : List Bool) : List Bool → List Bool × List Bool
+ | [] => ([], List.replicate d.length false)
+ | b :: xs =>
+ let old := dividePass d xs
+ let next := divideStep d b old.2
+ (next.1 :: old.1, next.2)
+
+theorem dividePass_spec (d xs : List Bool) (hd : 0 < value d) :
+ let t := dividePass d xs
+ t.1.length = xs.length ∧ t.2.length = d.length ∧ value t.2 < value d ∧
+ value d * value t.1 + value t.2 = value xs := by
+ induction xs with
+ | nil => simp [dividePass, value, hd]
+ | cons b xs ih =>
+ obtain ⟨hq, hr, hlt, he⟩ := ih
+ obtain ⟨hlen, hlt', hstep⟩ := divideStep_spec b hr hlt
+ simp only [dividePass, List.length_cons, hq, hlen, hlt', value, true_and, Nat.mul_add]
+ rw [← he]
+ simp only [Nat.mul_add, Nat.mul_left_comm (value d) 2]
+ omega
+
+theorem anyBit_iff (xs : List Bool) : xs.any id = true ↔ 0 < value xs := by
+ induction xs with
+ | nil => simp [value]
+ | cons b xs ih => cases b <;> simp [value, ih]
+
+/-- Both outputs have the width of the input words. For division by zero the
+quotient is all zeros and the remainder is the original dividend. -/
+def divideWords (x d : List Bool) : List Bool × List Bool :=
+ if d.any id then dividePass d x else (List.replicate x.length false, x)
+
+theorem divideWords_spec (x d : List Bool) (hlen : x.length = d.length) :
+ let t := divideWords x d
+ t.1.length = x.length ∧ t.2.length = x.length ∧
+ value t.1 = value x / value d ∧ value t.2 = value x % value d := by
+ unfold divideWords
+ split
+ · rename_i h
+ have hd := (anyBit_iff d).mp h
+ obtain ⟨hq, hr, hlt, he⟩ := dividePass_spec d x hd
+ refine ⟨hq, hr.trans hlen.symm, ?_, ?_⟩
+ · rw [← he, Nat.mul_add_div hd, Nat.div_eq_of_lt hlt, Nat.add_zero]
+ · rw [← he, Nat.mul_add_mod, Nat.mod_eq_of_lt hlt]
+ · rename_i h
+ have hd : value d = 0 := by have := (anyBit_iff d).not.mp h; omega
+ simp [hd]
+
+open BurstRAM PrivateRAM in
+/-- The output bit stacks are the words returned by the RAM's division and
+remainder opcodes, including at zero width. -/
+theorem divideWords_wordBits {w : ℕ} (x d : Word w) :
+ divideWords (wordBits x) (wordBits d) =
+ (wordBits (BinaryOp.div.eval x d), wordBits (BinaryOp.mod.eval x d)) := by
+ obtain ⟨hq, hr, hdiv, hmod⟩ := divideWords_spec (wordBits x) (wordBits d) (by simp)
+ simp only [value_wordBits] at hdiv hmod
+ have hd : x.val / d.val < 2 ^ w := (Nat.div_le_self ..).trans_lt x.isLt
+ have hm : x.val % d.val < 2 ^ w := (Nat.mod_le ..).trans_lt x.isLt
+ apply Prod.ext
+ · apply eq_of_length_value (by simpa using hq)
+ simpa [value_wordBits, BinaryOp.eval, Fin.ofNat, Nat.mod_eq_of_lt hd] using hdiv
+ · apply eq_of_length_value (by simpa using hr)
+ simpa [value_wordBits, BinaryOp.eval, Fin.ofNat, Nat.mod_eq_of_lt hm] using hmod
+
+end TapeWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordISA.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordISA.lean
new file mode 100644
index 0000000000..2928b1dfdf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordISA.lean
@@ -0,0 +1,215 @@
+import OAI.Computability.VPVNP.RAMTapeWordSimple
+import OAI.Computability.VPVNP.RAMTapeWordMul
+import OAI.Computability.VPVNP.RAMTapeDivision
+import OAI.Computability.VPVNP.RAMTapeWordShift
+import OAI.Computability.VPVNP.RAMTapeStackLift
+
+/-!
+# Finite stack routines for every binary word instruction
+
+Every routine uses two distinct operand ports and an explicit result port.
+Other local stacks start empty. At a successful return every local stack
+contains at most one word's worth of bits, so the caller can reclaim all
+scratch space in linear time. The port embeddings leave four of sixteen
+workspace slots available for operand staging.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord
+
+open RAMTape BurstRAM BurstRAM.PrivateRAM
+
+/-- Place the two operand bit strings on their ports and initialize scratch
+ports to empty stacks. -/
+def operandStacks {K : Type*} [DecidableEq K] (lhs rhs : K) (x y : List Bool) : Stacks K :=
+ fun i => if i = lhs then x else if i = rhs then y else []
+
+/-- The finite control table of a binary word routine and its call contract. -/
+structure Kernel (op : BinaryOp) where
+ /-- Finite type of local bit stacks used by the selected binary word kernel. -/
+ K : Type
+ /-- Finite control states of the binary word kernel, fixed independently of the operand
+ width. -/
+ Q : Type
+ [decK : DecidableEq K]
+ [finK : Fintype K]
+ [decQ : DecidableEq Q]
+ [finQ : Fintype Q]
+ /-- Inject each kernel stack into one of the twelve reserved arithmetic stack positions. -/
+ index : K → Fin 12
+ index_injective : Function.Injective index
+ /-- Local stack initially holding the first operand's little-endian bits. -/
+ lhs : K
+ /-- Distinct local stack initially holding the second operand's little-endian bits. -/
+ rhs : K
+ /-- Stack containing the fixed-width opcode result at an accepting return. -/
+ out : K
+ lhs_ne_rhs : lhs ≠ rhs
+ /-- Initial control state for invoking the kernel on its two operand stacks. -/
+ entry : Q
+ /-- Bit-stack instructions implementing the selected binary operation at every word width. -/
+ code : StackCode K Q
+ run : ∀ {w : ℕ} (x y : Word w), ∃ (steps : ℕ) (exit : Q) (final : Stacks K),
+ steps ≤ 40 * (w + 1)^2 ∧
+ StackRuns code steps entry (operandStacks lhs rhs (wordBits x) (wordBits y)) exit final ∧
+ code exit = .halt true ∧ final out = wordBits (op.eval x y) ∧ ∀ i, (final i).length ≤ w
+
+attribute [instance] Kernel.decK Kernel.finK Kernel.decQ Kernel.finQ
+
+/-- A successful subroutine halt serves as the caller's return boundary. -/
+def Kernel.accepts {op : BinaryOp} (k : Kernel op) (q : k.Q) : Bool :=
+ match k.code q with
+ | .halt true => true
+ | _ => false
+
+theorem Kernel.accepts_iff {op : BinaryOp} (k : Kernel op) (q : k.Q) :
+ k.accepts q = true ↔ k.code q = .halt true := by
+ cases h : k.code q with
+ | halt b => cases b <;> simp [Kernel.accepts, h]
+ | push | pop | goto | choose => simp [Kernel.accepts, h]
+
+private def scanIndex : ScanPort → Fin 12
+ | .left => 0
+ | .right => 1
+ | .tmp => 2
+ | .out => 3
+
+private def scanKernel (op : ScanOp) : Kernel op.opcode where
+ K := ScanPort
+ Q := ScanState
+ index := scanIndex
+ index_injective := by intro i j h; cases i <;> cases j <;> simp_all [scanIndex]
+ lhs := .left
+ rhs := .right
+ out := .out
+ lhs_ne_rhs := by decide
+ entry := .left false
+ code := scanCode op.step
+ run := by
+ intro w x y
+ refine ⟨5 * w + 2, .done (scan op.step false (wordBits x) (wordBits y)).2,
+ scanStacks [] [] [] (wordBits (op.opcode.eval x y)), ?_, ?_, rfl, rfl, ?_⟩
+ · ring_nf; omega
+ · convert op.word_run x y using 1
+ funext i; cases i <;> rfl
+ · intro i; cases i <;> simp [scanStacks]
+
+private def mulIndex : Mul.Reg → Fin 12
+ | .multiplicand => 0
+ | .multiplier => 1
+ | .accumulator => 2
+ | .shifted => 3
+ | .sum => 4
+
+private def mulKernel : Kernel .mul where
+ K := Mul.Reg
+ Q := Mul.State
+ index := mulIndex
+ index_injective := by intro i j h; cases i <;> cases j <;> simp_all [mulIndex]
+ lhs := .multiplicand
+ rhs := .multiplier
+ out := .accumulator
+ lhs_ne_rhs := by decide
+ entry := .init
+ code := Mul.code
+ run := by
+ intro w x y
+ refine ⟨8 * w ^ 2 + 9 * w + 4, .done,
+ Mul.store [] [] (wordBits (BinaryOp.mul.eval x y)) [] [], ?_, ?_, rfl, rfl, ?_⟩
+ · ring_nf; omega
+ · convert Mul.multiply_word_run x y using 1
+ funext i; cases i <;> rfl
+ · intro i; cases i <;> simp [Mul.store]
+
+private def divisionIndex : DivisionStack.Port → Fin 12
+ | .input => 0
+ | .feed => 1
+ | .divisor => 2
+ | .remainder => 3
+ | .quotient => 4
+ | .saved => 5
+ | .original => 6
+ | .difference => 7
+
+private def divisionKernel (quot : Bool) : Kernel (if quot then .div else .mod) where
+ K := DivisionStack.Port
+ Q := DivisionStack.State
+ index := divisionIndex
+ index_injective := by intro i j h; cases i <;> cases j <;> simp_all [divisionIndex]
+ lhs := .input
+ rhs := .divisor
+ out := if quot then .quotient else .remainder
+ lhs_ne_rhs := by decide
+ entry := .reverseInput
+ code := DivisionStack.code
+ run := by
+ intro w x y
+ let final : DivisionStack.Data := ⟨[], [], wordBits y, wordBits (BinaryOp.mod.eval x y),
+ wordBits (BinaryOp.div.eval x y), [], [], []⟩
+ refine ⟨DivisionStack.ticks (wordBits x) (wordBits y), .done, final.stacks,
+ ?_, ?_, rfl, ?_, ?_⟩
+ · have h := DivisionStack.ticks_le (x := wordBits x) (d := wordBits y) (by simp)
+ rw [length_wordBits] at h
+ omega
+ · convert DivisionStack.divideWordRun x y using 1
+ funext i; cases i <;> rfl
+ · cases quot <;> rfl
+ · intro i; cases i <;> simp [final, DivisionStack.Data.stacks]
+
+private def shiftIndex : Shift.Reg → Fin 12
+ | .amount => 0
+ | .data => 1
+ | .temp => 2
+ | .output => 3
+ | .scratch => 4
+
+private def shiftKernel (left : Bool) : Kernel (if left then .shiftLeft else .shiftRight) where
+ K := Shift.Reg
+ Q := Shift.State
+ index := shiftIndex
+ index_injective := by intro i j h; cases i <;> cases j <;> simp_all [shiftIndex]
+ lhs := if left then .temp else .data
+ rhs := .amount
+ out := if left then .temp else .output
+ lhs_ne_rhs := by cases left <;> decide
+ entry := .start
+ code := Shift.code left
+ run := by
+ intro w x y
+ obtain ⟨steps, bound, run⟩ := Shift.shift_run left x y
+ refine ⟨steps, .done, Shift.output left (wordBits ((if left then BinaryOp.shiftLeft else
+ BinaryOp.shiftRight).eval x y)), bound, ?_, rfl, ?_, ?_⟩
+ · convert run using 1
+ funext i
+ cases left <;> cases i <;> rfl
+ · cases left <;> rfl
+ · intro i
+ cases left <;> cases i <;> simp [Shift.output, Shift.store]
+
+/-- Select the fixed finite bit-stack implementation of a word RAM opcode. -/
+def wordKernel : (op : BinaryOp) → Kernel op
+ | .add => scanKernel .add
+ | .sub => scanKernel .sub
+ | .bitAnd => scanKernel .bitAnd
+ | .bitOr => scanKernel .bitOr
+ | .bitXor => scanKernel .bitXor
+ | .mul => mulKernel
+ | .div => divisionKernel true
+ | .mod => divisionKernel false
+ | .shiftLeft => shiftKernel true
+ | .shiftRight => shiftKernel false
+
+theorem wordKernel_entry (op : BinaryOp) :
+ (wordKernel op).accepts (wordKernel op).entry = false := by cases op <;> rfl
+
+theorem wordKernel_entry_continues (op : BinaryOp) :
+ ((wordKernel op).code (wordKernel op).entry).returns = false := by cases op <;> rfl
+
+end TapeWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordISAClear.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordISAClear.lean
new file mode 100644
index 0000000000..42432e453b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordISAClear.lean
@@ -0,0 +1,53 @@
+import OAI.Computability.VPVNP.RAMTapeISAOperand
+
+/-!
+# Clearing a finite set of work stacks
+
+An opcode may retain intermediate words at its return boundary. The caller
+clears those stacks before the next instruction, using one pop per bit and
+one empty-stack test per selected stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+variable {r k : ℕ}
+
+/-- Clear each listed port by popping its bits until the stack is empty, then return. -/
+def clearList : List (Port r k) → FiniteRoutine (Port r k)
+ | [] => .ret
+ | k :: ks => (clearPort k).followedBy (clearList ks)
+
+/-- Clearing a stack twice has the same result as clearing it once. -/
+def cleared (ks : List (Port r k)) (s : Stacks (Port r k)) : Stacks (Port r k) := fun i => if i ∈ ks then [] else s i
+
+theorem clearList_runs (ks : List (Port r k)) (s : Stacks (Port r k)) (bound : ℕ)
+ (h : ∀ i ∈ ks, (s i).length ≤ bound) :
+ ∃ n ≤ ks.length * (bound + 1) + 1, (clearList ks).Runs n s (cleared ks s) := by
+ induction ks generalizing s with
+ | nil =>
+ have he : cleared [] s = s := by funext i; simp [cleared]
+ exact ⟨1, by simp, he.symm ▸ Routine.runs_ret s⟩
+ | cons k ks ih =>
+ obtain ⟨t, ht, run⟩ := ih (Function.update s k []) (by
+ intro i hi
+ by_cases he : i = k
+ · simp [he]
+ · simpa [Function.update_of_ne he] using h i (List.mem_cons_of_mem _ hi))
+ have he : cleared ks (Function.update s k []) = cleared (k :: ks) s := by
+ funext i
+ by_cases hk : i = k <;> by_cases hi : i ∈ ks <;> simp [cleared, hk, hi]
+ rw [he] at run
+ refine ⟨(s k).length + 1 + t, ?_, (clearPort_runs k s).followedBy run⟩
+ have hh := h k (by simp)
+ simp only [List.length_cons, Nat.succ_mul]
+ omega
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordISAStage.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordISAStage.lean
new file mode 100644
index 0000000000..c98f4e4f46
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordISAStage.lean
@@ -0,0 +1,172 @@
+import OAI.Computability.VPVNP.RAMTapeWordISA
+import OAI.Computability.VPVNP.RAMTapeWordISAClear
+
+/-!
+# Register-level execution of the binary word instructions
+
+The dispatcher stages both operands in separate stacks before executing the
+arithmetic kernel. This supports every alias among the two input registers and
+the destination. The result is written back, and the finite bank of temporary
+stacks is cleared before the instruction returns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.ISA
+
+open TapeWord BurstRAM PrivateRAM
+
+variable {r k w : ℕ} {op : BinaryOp}
+
+/-- Map a local arithmetic stack to its reserved work port in the simulated instruction
+machine. -/
+def kernelPort (routine : Kernel op) (i : routine.K) : Port r k :=
+ .work ((routine.index i).castLE (by decide))
+
+private theorem kernelPort_inj (routine : Kernel op) :
+ Function.Injective (kernelPort (r := r) (k := k) routine) := by
+ intro i j h
+ apply routine.index_injective
+ exact Fin.ext (congrArg (Fin.val : Fin 16 → ℕ) (Port.work.inj h))
+
+private theorem kernel_safe (routine : Kernel op) (i : routine.K) :
+ copySafe (kernelPort (r := r) (k := k) routine i) := by
+ have h := (routine.index i).isLt
+ constructor <;> intro he <;> apply Port.work.inj at he <;>
+ apply congrArg Fin.val at he <;> change (routine.index i).val = _ at he <;> omega
+
+private theorem reg_safe (i : Fin r) : copySafe (Port.reg i : Port r k) := by simp [copySafe]
+
+/-- Execute the binary opcode's fixed stack program on the designated arithmetic work ports. -/
+def arithmeticKernel (op : BinaryOp) : FiniteRoutine (Port r k) :=
+ let routine := wordKernel op
+ .ofStackCode routine.code (kernelPort routine) routine.entry routine.accepts
+
+/-- All sixteen scratch ports cleared before control returns from the simulated instruction. -/
+def workPorts (r k : ℕ) : List (Port r k) := List.ofFn (Port.work : Fin 16 → Port r k)
+
+/-- A finite routine whose entry and control depend only on the opcode and
+three register indices. Word width affects only the stack contents. -/
+def binary (op : BinaryOp) (dst lhs rhs : Fin r) : FiniteRoutine (Port r k) :=
+ let routine := wordKernel op
+ let stageL := loadOperand (.reg lhs) (kernelPort routine routine.lhs)
+ let stageR := loadOperand (.reg rhs) (kernelPort routine routine.rhs)
+ let result := loadOperand (kernelPort routine routine.out) (.reg dst)
+ ((((stageL.followedBy stageR).followedBy (arithmeticKernel op)).followedBy result).followedBy
+ (clearList (workPorts r k)))
+
+private theorem install_operands (routine : Kernel op) (s : Stacks (Port r k)) (x y : List Bool)
+ (h : ∀ i, s (.work i) = []) :
+ installStacks (kernelPort routine) s (operandStacks routine.lhs routine.rhs x y) =
+ Function.update (Function.update s (kernelPort routine routine.lhs) x)
+ (kernelPort routine routine.rhs) y := by
+ let p : routine.K → Port r k := kernelPort routine
+ have hi : Function.Injective p := kernelPort_inj routine
+ change installStacks p s _ = Function.update (Function.update s (p routine.lhs) x) (p routine.rhs) y
+ funext j
+ by_cases hm : ∃ i, p i = j
+ · obtain ⟨i, rfl⟩ := hm
+ rw [installStacks_at hi]
+ have hpi : s (p i) = [] := h _
+ by_cases he : i = routine.lhs
+ · subst i
+ simp [operandStacks, Function.update_of_ne (hi.ne routine.lhs_ne_rhs)]
+ · by_cases hf : i = routine.rhs
+ · subst i
+ simp [operandStacks, he]
+ · simp [operandStacks, he, hf, Function.update_of_ne (hi.ne he), Function.update_of_ne (hi.ne hf), hpi]
+ · have hl : j ≠ p routine.lhs := fun he => hm ⟨_, he.symm⟩
+ have hr : j ≠ p routine.rhs := fun he => hm ⟨_, he.symm⟩
+ rw [installStacks_outside _ _ (not_exists.mp hm), Function.update_of_ne hr, Function.update_of_ne hl]
+
+private theorem clear_result (routine : Kernel op) (final : Stacks routine.K)
+ (s : Stacks (Port r k)) (hwork : ∀ i, s (.work i) = []) (dst : Fin r) (value : List Bool) :
+ cleared (workPorts r k) (Function.update (installStacks (kernelPort routine) s final) (.reg dst) value) =
+ Function.update s (.reg dst) value := by
+ funext j
+ by_cases hm : j ∈ workPorts r k
+ · obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hm
+ simp [cleared, hm, hwork]
+ · simp only [cleared, hm, ↓reduceIte]
+ by_cases he : j = .reg dst
+ · subst j
+ simp
+ · rw [Function.update_of_ne he, Function.update_of_ne he]
+ exact installStacks_outside _ _ fun i eq => hm (List.mem_ofFn.mpr ⟨_, eq⟩)
+
+/-- Every binary opcode restores the architectural bank with exactly its
+destination register updated. The bound covers staging, arithmetic, writeback
+and cleanup of all sixteen work stacks, even for division by zero. -/
+theorem binary_runs (op : BinaryOp) (dst lhs rhs : Fin r) (pub : Fin k → Word w)
+ (persistent : Word w) (reg : Fin r → Word w) (log : WriteLog w) :
+ ∃ t ≤ 100 * (w + 1)^2, (binary op dst lhs rhs).Runs t (bank pub persistent reg log)
+ (bank pub persistent (Function.update reg dst (op.eval (reg lhs) (reg rhs))) log) := by
+ let routine := wordKernel op
+ let p : routine.K → Port r k := kernelPort routine
+ have hi : Function.Injective p := kernelPort_inj routine
+ have safe : ∀ i, copySafe (p i) := kernel_safe routine
+ let s := bank pub persistent reg log
+ let a := reg lhs
+ let b := reg rhs
+ let s₁ := Function.update s (p routine.lhs) (wordBits a)
+ let s₂ := Function.update s₁ (p routine.rhs) (wordBits b)
+ have h1 : (loadOperand (.reg lhs) (p routine.lhs)).Runs (7*w+3) s s₁ := by
+ simpa [s, s₁, p, kernelPort, bank, a] using loadOperand_runs (src := .reg lhs) (dst := p routine.lhs)
+ (by simp [p, kernelPort]) (reg_safe _) (safe _) s rfl rfl
+ have h₁ : p routine.rhs ≠ p routine.lhs := hi.ne routine.lhs_ne_rhs.symm
+ have s14 : s₁ (.work 14) = [] := Function.update_of_ne (safe _).1.symm ..
+ have s15 : s₁ (.work 15) = [] := Function.update_of_ne (safe _).2.symm ..
+ have h2 : (loadOperand (.reg rhs) (p routine.rhs)).Runs (7*w+3) s₁ s₂ := by
+ have hs : s₁ (.reg rhs) = wordBits b := Function.update_of_ne (by simp [p, kernelPort]) ..
+ have hd : s₁ (p routine.rhs) = [] := Function.update_of_ne h₁ ..
+ simpa only [hs, hd, List.length_nil, Nat.zero_add, length_wordBits] using
+ loadOperand_runs (src := .reg rhs) (dst := p routine.rhs) (by simp [p, kernelPort])
+ (reg_safe _) (safe _) s₁ s14 s15
+ obtain ⟨n, q, final, hn, run, hexit, hout, hbound⟩ := routine.run a b
+ let s₃ := installStacks p s final
+ have h3 : (arithmeticKernel op).Runs n s₂ s₃ := by
+ have hr := FiniteRoutine.runs_ofStackCode hi (normal := routine.accepts) (wordKernel_entry op)
+ ((routine.accepts_iff _).mpr hexit) (fun u hu => by rw [(routine.accepts_iff _).mp hu]; rfl) s run
+ rw [install_operands routine s _ _ (fun _ => rfl)] at hr
+ exact hr
+ have hread : s₃ (p routine.out) = wordBits (op.eval a b) :=
+ (installStacks_at hi s final _).trans hout
+ have hdst : s₃ (.reg dst) = wordBits (reg dst) :=
+ installStacks_outside _ _ (by simp [p, kernelPort])
+ have h14 : s₃ (.work 14) = [] := installStacks_outside _ _ (fun i => (safe i).1)
+ have h15 : s₃ (.work 15) = [] := installStacks_outside _ _ (fun i => (safe i).2)
+ let s₄ := Function.update s₃ (.reg dst) (wordBits (op.eval a b))
+ have h4 : (loadOperand (p routine.out) (.reg dst)).Runs (8*w+3) s₃ s₄ := by
+ have hr := loadOperand_runs (src := p routine.out) (dst := .reg dst) (by simp [p, kernelPort])
+ (safe _) (reg_safe _) s₃ h14 h15
+ rw [hread, hdst, length_wordBits, length_wordBits] at hr
+ convert hr using 1
+ omega
+ have hspace (j : Port r k) (hj : j ∈ workPorts r k) : (s₄ j).length ≤ w := by
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hj
+ change ((Function.update s₃ (.reg dst) _) (.work i)).length ≤ w
+ rw [Function.update_of_ne (by simp)]
+ by_cases hm : ∃ u, p u = .work i
+ · obtain ⟨u, he⟩ := hm
+ rw [← he, show s₃ (p u) = final u from installStacks_at hi ..]
+ exact hbound u
+ · rw [show s₃ (.work i) = s (.work i) from installStacks_outside _ _ (not_exists.mp hm)]
+ exact Nat.zero_le _
+ obtain ⟨m, hm, h5⟩ := clearList_runs (workPorts r k) s₄ w hspace
+ have htarget : cleared (workPorts r k) s₄ =
+ bank pub persistent (Function.update reg dst (op.eval a b)) log :=
+ (clear_result routine final s (fun _ => rfl) dst _).trans (bank_updateReg ..)
+ rw [htarget] at h5
+ have result := (((h1.followedBy h2).followedBy h3).followedBy h4).followedBy h5
+ refine ⟨_, ?_, result⟩
+ simp only [workPorts, List.length_ofFn] at hm
+ ring_nf at hn ⊢
+ omega
+
+end RAMTape.ISA
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordMul.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordMul.lean
new file mode 100644
index 0000000000..bf1d10b575
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordMul.lean
@@ -0,0 +1,233 @@
+import OAI.Computability.VPVNP.RAMProgram
+import OAI.Computability.VPVNP.RAMTapeStacks
+import OAI.Computability.VPVNP.RAMTapeWordMulValue
+import Mathlib.Tactic.DeriveFintype
+import Mathlib.Tactic.Ring
+
+/-!
+# Fixed bit-stack control for word multiplication
+
+The multiplier is read from least to most significant bit. Each round
+simultaneously shifts the multiplicand and conditionally adds it into the
+accumulator, discarding overflow at the width of the input stacks. Two
+scratch stacks restore both words to least-significant-bit-first order.
+The number of control states and stacks is independent of the word width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.Mul
+
+open RAMTape
+
+/-- Bit stacks for the multiplier, multiplicand, running accumulator and temporary shifted and
+summed words. -/
+inductive Reg
+ | multiplier | multiplicand | accumulator | shifted | sum
+ deriving DecidableEq
+
+instance : Fintype Reg :=
+ ⟨{.multiplier, .multiplicand, .accumulator, .shifted, .sum},
+ fun k => by cases k <;> simp⟩
+
+/-- Control states for initialization and for the shift-and-add rounds that consume successive
+multiplier bits. -/
+inductive State
+ | init | saveInit (bit : Bool) | zeroInit | restoreInit | pushInit (bit : Bool)
+ | loop | scanX (use carry previous : Bool) | scanAcc (use carry previous x : Bool)
+ | saveX (use next previous x out : Bool) | saveSum (use next x out : Bool)
+ | reverseX | reverseSum (x : Bool) | putX (x a : Bool) | putSum (a : Bool)
+ | discard | done | fail
+ deriving DecidableEq, Fintype
+
+/-- The only data in finite control are the handful of bits between pop and
+push instructions. Inputs are copied into these stacks by the caller. -/
+def code : StackCode Reg State
+ | .init => .pop .multiplicand fun b => b.elim .restoreInit .saveInit
+ | .saveInit b => .push .shifted b .zeroInit
+ | .zeroInit => .push .accumulator false .init
+ | .restoreInit => .pop .shifted fun b => b.elim .loop .pushInit
+ | .pushInit b => .push .multiplicand b .restoreInit
+ | .loop => .pop .multiplier fun b => b.elim .discard (fun use => .scanX use false false)
+ | .scanX use carry previous =>
+ .pop .multiplicand fun b => b.elim .reverseX (.scanAcc use carry previous)
+ | .scanAcc use carry previous b => .pop .accumulator fun d =>
+ d.elim .fail fun bit =>
+ let step := addBit carry (use && b) bit
+ .saveX use step.2 previous b step.1
+ | .saveX use next previous b out => .push .shifted previous (.saveSum use next b out)
+ | .saveSum use next b out => .push .sum out (.scanX use next b)
+ | .reverseX => .pop .shifted fun b => b.elim .loop .reverseSum
+ | .reverseSum b => .pop .sum fun a => a.elim .fail (.putX b)
+ | .putX b a => .push .multiplicand b (.putSum a)
+ | .putSum a => .push .accumulator a .reverseX
+ | .discard => .pop .multiplicand fun b => b.elim .done (fun _ => .discard)
+ | .done => .halt true
+ | .fail => .halt false
+
+/-- Install the five bit lists as the current multiplication operands, accumulator and
+temporary words. -/
+def store (bits x acc xr ar : List Bool) : Stacks Reg
+ | .multiplier => bits
+ | .multiplicand => x
+ | .accumulator => acc
+ | .shifted => xr
+ | .sum => ar
+
+private theorem update_store (bits x acc xr ar word : List Bool) (k : Reg) :
+ Function.update (store bits x acc xr ar) k word = match k with
+ | .multiplier => store word x acc xr ar
+ | .multiplicand => store bits word acc xr ar
+ | .accumulator => store bits x word xr ar
+ | .shifted => store bits x acc word ar
+ | .sum => store bits x acc xr word := by
+ funext i
+ cases k <;> cases i <;> simp [store]
+
+-- The instruction choice must reduce to a literal push or pop.
+local macro "mul_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_store])
+
+private theorem scan_run (use carry prev : Bool) (bits x acc xr ar : List Bool)
+ (hlen : acc.length = x.length) :
+ StackRuns code (4 * x.length + 1) (.scanX use carry prev) (store bits x acc xr ar)
+ .reverseX (store bits [] [] ((mulScan use carry prev x acc).1.reverse ++ xr)
+ ((mulScan use carry prev x acc).2.reverse ++ ar)) := by
+ induction x generalizing carry prev acc xr ar with
+ | nil =>
+ have he : acc = [] := List.length_eq_zero_iff.mp hlen
+ subst acc
+ mul_step
+ exact .nil ..
+ | cons b x ih =>
+ cases acc with
+ | nil => simp at hlen
+ | cons d acc =>
+ have ht := ih (addBit carry (use && b) d).2 b acc (prev :: xr)
+ ((addBit carry (use && b) d).1 :: ar) (Nat.succ.inj hlen)
+ simp only [List.length_cons, Nat.mul_succ, mulScan, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ mul_step
+ mul_step
+ mul_step
+ mul_step
+ exact ht
+
+private theorem reverse_run (bits x acc xr ar : List Bool) (hlen : ar.length = xr.length) :
+ StackRuns code (4 * xr.length + 1) .reverseX (store bits x acc xr ar)
+ .loop (store bits (xr.reverse ++ x) (ar.reverse ++ acc) [] []) := by
+ induction xr generalizing x acc ar with
+ | nil =>
+ have he : ar = [] := List.length_eq_zero_iff.mp hlen
+ subst ar
+ mul_step
+ exact .nil ..
+ | cons b xr ih =>
+ cases ar with
+ | nil => simp at hlen
+ | cons d ar =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ mul_step
+ mul_step
+ mul_step
+ mul_step
+ exact ih (b :: x) (d :: acc) ar (Nat.succ.inj hlen)
+
+private theorem discard_run (x acc : List Bool) :
+ StackRuns code (x.length + 1) .discard (store [] x acc [] []) .done (store [] [] acc [] []) := by
+ induction x with
+ | nil => mul_step; exact .nil ..
+ | cons b x ih => simp only [List.length_cons]; mul_step; exact ih
+
+/-- Consume the multiplier and compute a multiply-add, with wraparound. -/
+theorem loop_run (bits x acc : List Bool) (hlen : acc.length = x.length) :
+ StackRuns code (bits.length * (8 * x.length + 3) + (x.length + 2))
+ .loop (store bits x acc [] []) .done (store [] [] (mulFold bits x acc) [] []) := by
+ induction bits generalizing x acc with
+ | nil =>
+ simp only [List.length_nil, Nat.zero_mul, Nat.zero_add, mulFold]
+ mul_step
+ exact discard_run x acc
+ | cons use bits ih =>
+ let p := mulRound use x acc
+ obtain ⟨hx, ha⟩ := length_mulRound use hlen
+ have scan := scan_run use false false bits x acc [] [] hlen
+ have rev := reverse_run bits [] [] p.1.reverse p.2.reverse (by simp [p, hx, ha])
+ have h1 : StackRuns code (4 * x.length + 1) (.scanX use false false)
+ (store bits x acc [] []) .reverseX (store bits [] [] p.1.reverse p.2.reverse) := by
+ simpa [p, mulRound] using scan
+ have h2 : StackRuns code (4 * x.length + 1) .reverseX
+ (store bits [] [] p.1.reverse p.2.reverse) .loop (store bits p.1 p.2 [] []) := by
+ simpa [p, hx] using rev
+ have h3 := ih p.1 p.2 (ha.trans hx.symm)
+ rw [show p.1.length = x.length from hx] at h3
+ have htotal : (use :: bits).length * (8 * x.length + 3) + (x.length + 2) =
+ ((4 * x.length + 1) + (4 * x.length + 1) +
+ (bits.length * (8 * x.length + 3) + (x.length + 2))) + 1 := by
+ simp only [List.length_cons]
+ ring
+ rw [htotal]
+ mul_step
+ exact (h1.trans h2).trans h3
+
+private theorem init_run (bits x acc xr : List Bool) :
+ StackRuns code (3 * x.length + 1) .init (store bits x acc xr [])
+ .restoreInit (store bits [] (List.replicate x.length false ++ acc) (x.reverse ++ xr) []) := by
+ induction x generalizing acc xr with
+ | nil => mul_step; exact .nil ..
+ | cons b x ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append, List.replicate_succ']
+ mul_step
+ mul_step
+ mul_step
+ exact ih (false :: acc) (b :: xr)
+
+private theorem init_restore (bits x acc xr : List Bool) :
+ StackRuns code (2 * xr.length + 1) .restoreInit (store bits x acc xr [])
+ .loop (store bits (xr.reverse ++ x) acc [] []) := by
+ induction xr generalizing x with
+ | nil => mul_step; exact .nil ..
+ | cons b xr ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ mul_step
+ mul_step
+ exact ih (b :: x)
+
+/-- Start with two words and empty work stacks. The accumulator is initialized
+to a zero word of the multiplicand's width. All four other stacks are empty at
+exit. For equal widths `w` the time is `8*w² + 9*w + 4`. -/
+theorem multiply_run (bits x : List Bool) :
+ StackRuns code (bits.length * (8 * x.length + 3) + (6 * x.length + 4))
+ .init (store bits x [] [] []) .done
+ (store [] [] (mulFold bits x (List.replicate x.length false)) [] []) := by
+ let acc := List.replicate x.length false
+ have h1 := init_run bits x [] []
+ have h2 := init_restore bits [] acc x.reverse
+ simp only [List.append_nil, List.reverse_reverse, List.length_reverse] at h1 h2
+ have h3 := loop_run bits x acc (by simp [acc])
+ convert (h1.trans h2).trans h3 using 1
+ ring
+
+/-- The multiplication opcode, at every word width, is implemented by this
+single finite control. Each input and output uses the RAM word bit encoding. -/
+theorem multiply_word_run {w : ℕ} (a b : BurstRAM.Word w) :
+ StackRuns code (8 * w ^ 2 + 9 * w + 4) .init
+ (store (BurstRAM.wordBits b) (BurstRAM.wordBits a) [] [] []) .done
+ (store [] [] (BurstRAM.wordBits (BurstRAM.PrivateRAM.BinaryOp.mul.eval a b)) [] []) := by
+ have h := multiply_run (BurstRAM.wordBits b) (BurstRAM.wordBits a)
+ simp only [BurstRAM.length_wordBits, mulFold_wordBits] at h
+ rw [show 8 * w ^ 2 + 9 * w + 4 = w * (8 * w + 3) + (6 * w + 4) by ring]
+ exact h
+
+end TapeWord.Mul
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordMulValue.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordMulValue.lean
new file mode 100644
index 0000000000..89cb1aab4d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordMulValue.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.RAMTapeWord
+import Mathlib.Data.Nat.ModEq
+
+/-!
+# Multiplication on fixed-width bit tapes
+
+In each round the multiplier supplies its next low bit. A single synchronous
+scan of the other two words shifts the multiplicand and adds its selected
+bits to the accumulator. Discarding the last shifted bit and the last carry
+implements the word RAM's multiplication modulo its word size.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord
+
+/-- Emit the previous multiplicand bit and the current accumulator sum bit.
+The finite control retains the shifted-out bit and the adder carry. -/
+def mulScan (use : Bool) : Bool → Bool → List Bool → List Bool → List Bool × List Bool
+ | carry, prev, b :: xs, d :: ds =>
+ let sum := addBit carry (use && b) d
+ let out := mulScan use sum.2 b xs ds
+ (prev :: out.1, sum.1 :: out.2)
+ | _, _, _, _ => ([], [])
+
+/-- Start one shift-and-add scan with zero incoming shift bit and carry. -/
+def mulRound (use : Bool) (x acc : List Bool) : List Bool × List Bool :=
+ mulScan use false false x acc
+
+/-- Consume the multiplier from low to high, retaining the two output words
+between rounds. -/
+def mulFold : List Bool → List Bool → List Bool → List Bool
+ | [], _, acc => acc
+ | use :: bits, x, acc =>
+ let out := mulRound use x acc
+ mulFold bits out.1 out.2
+
+theorem length_mulScan (use carry prev : Bool) {x acc : List Bool}
+ (hlen : acc.length = x.length) :
+ (mulScan use carry prev x acc).1.length = x.length ∧
+ (mulScan use carry prev x acc).2.length = x.length := by
+ induction x generalizing carry prev acc with
+ | nil => cases acc <;> simp [mulScan]
+ | cons b xs ih =>
+ cases acc with
+ | nil => simp at hlen
+ | cons d ds =>
+ obtain ⟨hx, ha⟩ := ih (addBit carry (use && b) d).2 b (Nat.succ.inj hlen)
+ simp [mulScan, hx, ha]
+
+theorem length_mulRound (use : Bool) {x acc : List Bool} (hlen : acc.length = x.length) :
+ (mulRound use x acc).1.length = x.length ∧ (mulRound use x acc).2.length = x.length :=
+ length_mulScan use false false hlen
+
+theorem length_mulFold (bits : List Bool) {x acc : List Bool} (hlen : acc.length = x.length) :
+ (mulFold bits x acc).length = x.length := by
+ induction bits generalizing x acc with
+ | nil => exact hlen
+ | cons b bits ih =>
+ obtain ⟨hx, ha⟩ := length_mulRound b hlen
+ exact (ih (ha.trans hx.symm)).trans hx
+
+/-- Each finite scan discards whole multiples of the word modulus. -/
+private theorem mulScan_overflow (use carry prev : Bool) {x acc : List Bool}
+ (hlen : acc.length = x.length) :
+ ∃ shiftOverflow addOverflow : ℕ,
+ 2 * value x + prev.toNat =
+ value (mulScan use carry prev x acc).1 + 2 ^ x.length * shiftOverflow ∧
+ value acc + use.toNat * value x + carry.toNat =
+ value (mulScan use carry prev x acc).2 + 2 ^ x.length * addOverflow := by
+ induction x generalizing acc carry prev with
+ | nil =>
+ cases acc with
+ | nil => exact ⟨prev.toNat, carry.toNat, by simp [mulScan, value]⟩
+ | cons => simp at hlen
+ | cons b xs ih =>
+ cases acc with
+ | nil => simp at hlen
+ | cons d ds =>
+ let sum := addBit carry (use && b) d
+ obtain ⟨shiftOverflow, addOverflow, hx, ha⟩ := ih sum.2 b (Nat.succ.inj hlen)
+ have hbit : d.toNat + use.toNat * b.toNat + carry.toNat =
+ sum.1.toNat + 2 * sum.2.toNat := by
+ cases use <;> cases b <;> cases d <;> cases carry <;> decide
+ refine ⟨shiftOverflow, addOverflow, ?_, ?_⟩
+ · change 2 * (b.toNat + 2 * value xs) + prev.toNat =
+ prev.toNat + 2 * value (mulScan use sum.2 b xs ds).1 +
+ 2 ^ (xs.length + 1) * shiftOverflow
+ rw [pow_succ, Nat.mul_right_comm _ 2 shiftOverflow]
+ omega
+ · change (d.toNat + 2 * value ds) + use.toNat * (b.toNat + 2 * value xs) +
+ carry.toNat = sum.1.toNat + 2 * value (mulScan use sum.2 b xs ds).2 +
+ 2 ^ (xs.length + 1) * addOverflow
+ rw [pow_succ, Nat.mul_right_comm _ 2 addOverflow, Nat.mul_add,
+ ← Nat.mul_assoc use.toNat 2, Nat.mul_right_comm use.toNat 2]
+ omega
+
+theorem value_mulRound (use : Bool) {x acc : List Bool} (hlen : acc.length = x.length) :
+ value (mulRound use x acc).1 = (2 * value x) % 2 ^ x.length ∧
+ value (mulRound use x acc).2 = (value acc + use.toNat * value x) % 2 ^ x.length := by
+ obtain ⟨sx, sa, hx, ha⟩ := mulScan_overflow use false false hlen
+ simp only [Bool.toNat_false, Nat.add_zero] at hx ha
+ obtain ⟨hxl, hal⟩ := length_mulRound use hlen
+ have bx := value_lt (mulRound use x acc).1
+ have ba := value_lt (mulRound use x acc).2
+ rw [hxl] at bx
+ rw [hal] at ba
+ unfold mulRound at bx ba
+ rw [hx, ha, Nat.add_mul_mod_self_left, Nat.add_mul_mod_self_left,
+ Nat.mod_eq_of_lt bx, Nat.mod_eq_of_lt ba]
+ exact ⟨rfl, rfl⟩
+
+/-- The full shift-and-add computation, including an arbitrary initial
+accumulator, is the low word of the mathematical product plus that accumulator. -/
+theorem value_mulFold (bits : List Bool) {x acc : List Bool} (hlen : acc.length = x.length) :
+ value (mulFold bits x acc) = (value acc + value x * value bits) % 2 ^ x.length := by
+ induction bits generalizing x acc with
+ | nil =>
+ have hb := value_lt acc
+ rw [hlen] at hb
+ simp [mulFold, value, Nat.mod_eq_of_lt hb]
+ | cons b bits ih =>
+ obtain ⟨hx, ha⟩ := length_mulRound b hlen
+ obtain ⟨hvx, hva⟩ := value_mulRound b hlen
+ rw [mulFold, ih (ha.trans hx.symm), hx, hvx, hva, value]
+ have h := (Nat.mod_modEq (value acc + b.toNat * value x) (2 ^ x.length)).add
+ ((Nat.mod_modEq (2 * value x) (2 ^ x.length)).mul_right (value bits))
+ calc
+ _ = (value acc + b.toNat * value x + (2 * value x) * value bits) % 2 ^ x.length := h
+ _ = _ := by congr 1; ring
+
+private theorem value_replicate_false (w : ℕ) : value (List.replicate w false) = 0 := by
+ induction w with
+ | zero => rfl
+ | succ w ih => simp [List.replicate_succ, value, ih]
+
+/-- Starting with a zero tape produces the canonical bit string of the
+word product, including when the word multiplication wraps around. -/
+theorem mulFold_wordBits {w : ℕ} (a b : BurstRAM.Word w) :
+ mulFold (BurstRAM.wordBits b) (BurstRAM.wordBits a) (List.replicate w false) =
+ BurstRAM.wordBits (a * b) := by
+ have hlen : (List.replicate w false).length = (BurstRAM.wordBits a).length := by simp
+ apply eq_of_length_value
+ · simp [length_mulFold _ hlen]
+ · rw [value_mulFold _ hlen, value_replicate_false, Nat.zero_add, value_wordBits,
+ value_wordBits, value_wordBits, BurstRAM.length_wordBits]
+ rfl
+
+end TapeWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordOperands.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordOperands.lean
new file mode 100644
index 0000000000..3ebf14b483
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordOperands.lean
@@ -0,0 +1,182 @@
+import OAI.Computability.VPVNP.RAMTapeWordScan
+
+/-!
+# Loading register, public-word and fixed-literal operands
+
+A finite-state scan copies one bit per source cell, restoring the original
+word and overwriting the destination. Its finite output transition may copy
+the input bits unchanged, or ignore them and emit the low bits of a fixed
+literal. In the latter case the source supplies only the word width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.Operand
+
+open RAMTape BurstRAM
+
+/-- Control for clearing the destination, scanning a source word with a finite bit
+transformation, and restoring the source. -/
+inductive State (A : Type*)
+ | clear (a : A) | read (a : A) | save (b out : Bool) (a : A) | emit (out : Bool) (a : A)
+ | restore (a : A) | takeOut (b : Bool) (a : A) | putSrc (b out : Bool) (a : A)
+ | putOut (out : Bool) (a : A) | done (a : A) | reject
+ deriving DecidableEq, Fintype
+
+variable {A : Type*}
+
+/-- Load an operand word using the given bit transition, overwrite the destination and restore
+the source in its original order. -/
+def code (step : A → Bool → Bool × A) : StackCode ScanPort (State A)
+ | .clear a => .pop .out fun b => b.elim (.read a) fun _ => .clear a
+ | .read a => .pop .left fun b => b.elim (.restore a) fun x => .save x (step a x).1 (step a x).2
+ | .save b out a => .push .right b (.emit out a)
+ | .emit out a => .push .tmp out (.read a)
+ | .restore a => .pop .right fun b => b.elim (.done a) fun x => .takeOut x a
+ | .takeOut b a => .pop .tmp fun d => d.elim .reject fun x => .putSrc b x a
+ | .putSrc b out a => .push .left b (.putOut out a)
+ | .putOut out a => .push .out out (.restore a)
+ | .done _ => .halt true
+ | .reject => .halt false
+
+/-- Output bit list and final finite state obtained by applying the operand transformation once
+per input bit. -/
+def emitted (step : A → Bool → Bool × A) : A → List Bool → List Bool × A
+ | a, [] => ([], a)
+ | a, b :: xs =>
+ let (out, next) := step a b
+ let (rest, final) := emitted step next xs
+ (out :: rest, final)
+
+private theorem emitted_length (step : A → Bool → Bool × A) (a : A) (xs : List Bool) :
+ (emitted step a xs).1.length = xs.length := by
+ induction xs generalizing a with
+ | nil => rfl
+ | cons _ _ ih => simp [emitted, ih]
+
+private theorem update_stacks (x s t o word : List Bool) (k : ScanPort) :
+ Function.update (scanStacks x s t o) k word = match k with
+ | .left => scanStacks word s t o
+ | .right => scanStacks x word t o
+ | .tmp => scanStacks x s word o
+ | .out => scanStacks x s t word := by
+ funext j; cases k <;> cases j <;> simp [scanStacks]
+
+local macro "operand_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [scanStacks, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_stacks])
+
+private theorem clear_run (step : A → Bool → Bool × A) (a : A) (x s t o : List Bool) :
+ StackRuns (code step) (o.length + 1) (.clear a) (scanStacks x s t o) (.read a) (scanStacks x s t []) := by
+ induction o with
+ | nil => operand_step; exact .nil ..
+ | cons b o ih => operand_step; exact ih
+
+private theorem read_run (step : A → Bool → Bool × A) (a : A) (x s t o : List Bool) :
+ StackRuns (code step) (3 * x.length + 1) (.read a) (scanStacks x s t o)
+ (.restore (emitted step a x).2) (scanStacks [] (x.reverse ++ s) ((emitted step a x).1.reverse ++ t) o) := by
+ induction x generalizing a s t with
+ | nil => operand_step; exact .nil ..
+ | cons b x ih =>
+ simp only [List.length_cons, Nat.mul_succ, emitted, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ operand_step
+ operand_step
+ operand_step
+ exact ih _ _ _
+
+private theorem restore_run (step : A → Bool → Bool × A) (a : A) (x s t o : List Bool)
+ (hlen : s.length = t.length) :
+ StackRuns (code step) (4 * s.length + 1) (.restore a) (scanStacks x s t o)
+ (.done a) (scanStacks (s.reverse ++ x) [] [] (t.reverse ++ o)) := by
+ induction s generalizing x t o with
+ | nil =>
+ have ht : t = [] := List.length_eq_zero_iff.mp hlen.symm
+ subst t
+ operand_step
+ exact .nil ..
+ | cons b s ih =>
+ cases t with
+ | nil => simp at hlen
+ | cons d t =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ operand_step
+ operand_step
+ operand_step
+ operand_step
+ exact ih _ _ _ (Nat.succ.inj hlen)
+
+/-- The source is preserved, the destination is overwritten, and both
+scratch stacks are empty on return. -/
+theorem run (step : A → Bool → Bool × A) (a : A) (x old : List Bool) :
+ StackRuns (code step) (old.length + 7 * x.length + 3) (.clear a) (scanStacks x [] [] old)
+ (.done (emitted step a x).2) (scanStacks x [] [] (emitted step a x).1) := by
+ have hc := clear_run step a x [] [] old
+ have hr := read_run step a x [] [] []
+ simp only [List.append_nil] at hr
+ have hs := restore_run step (emitted step a x).2 [] x.reverse (emitted step a x).1.reverse []
+ (by simp [emitted_length])
+ simp only [List.append_nil, List.reverse_reverse, List.length_reverse] at hs
+ convert (hc.trans hr).trans hs using 1
+ omega
+
+/-- Load any saved word from a register, the persistent input, or public data. -/
+def copyBit (_ : Unit) (b : Bool) : Bool × Unit := (b, ())
+
+private theorem emitted_copy (x : List Bool) : emitted copyBit () x = (x, ()) := by
+ induction x <;> simp [emitted, copyBit, *]
+
+theorem copy_run (x old : List Bool) :
+ StackRuns (code copyBit) (old.length + 7 * x.length + 3) (.clear ()) (scanStacks x [] [] old)
+ (.done ()) (scanStacks x [] [] x) := by simpa [emitted_copy] using run copyBit () x old
+
+/-- A fixed literal is compiled into a finite family of control states for
+its successively halved values. Word width affects only the input stack. -/
+def literalBit (k : ℕ) (a : Fin (k + 1)) (_ : Bool) : Bool × Fin (k + 1) :=
+ (decide (a.val % 2 = 1), ⟨a.val / 2, (Nat.div_le_self _ _).trans_lt a.isLt⟩)
+
+private theorem emitted_literal (k : ℕ) (a : Fin (k + 1)) (x : List Bool) :
+ value (emitted (literalBit k) a x).1 + 2^x.length * (emitted (literalBit k) a x).2.val = a.val := by
+ induction x generalizing a with
+ | nil => simp [emitted, value]
+ | cons b x ih =>
+ have h := ih (literalBit k a b).2
+ have hl : (literalBit k a b).1.toNat = a.val % 2 := by
+ by_cases hz : a.val % 2 = 1 <;> simp [literalBit, hz]
+ omega
+ simp only [emitted, value, hl, List.length_cons, pow_succ, Nat.mul_right_comm _ 2 _]
+ change _ + _ = a.val / 2 at h
+ omega
+
+/-- Load a width-dependent residue of a fixed constant. -/
+theorem literal_run {w : ℕ} (k : ℕ) (widthTemplate : Word w) (old : List Bool) :
+ ∃ final : Fin (k + 1), StackRuns (code (literalBit k)) (old.length + 7*w + 3)
+ (.clear (Fin.last k)) (scanStacks (wordBits widthTemplate) [] [] old) (.done final)
+ (scanStacks (wordBits widthTemplate) [] [] (wordBits (Fin.ofNat (2^w) k))) := by
+ let x := wordBits widthTemplate
+ let a := Fin.last k
+ let z := emitted (literalBit k) a x
+ have hx : x.length = w := length_wordBits _
+ have hz : z.1.length = w := (emitted_length _ _ _).trans hx
+ have hv := emitted_literal k a x
+ change value z.1 + 2^x.length * z.2.val = k at hv
+ have hlo := value_lt z.1
+ rw [hz] at hlo
+ have he : z.1 = wordBits (Fin.ofNat (2^w) k) := by
+ apply eq_of_length_value (by simpa using hz)
+ have hm := congrArg (fun n => n % 2^w) hv
+ simpa only [value_wordBits, Fin.val_ofNat, hx, Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hlo] using hm
+ refine ⟨z.2, ?_⟩
+ have hr := run (literalBit k) a x old
+ change StackRuns _ _ (State.clear a) (scanStacks x [] [] old) (State.done z.2) (scanStacks x [] [] z.1) at hr
+ simpa only [hx, he] using hr
+
+end TapeWord.Operand
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordScan.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordScan.lean
new file mode 100644
index 0000000000..7ff9adcea7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordScan.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.RAMTapeWord
+import OAI.Computability.VPVNP.RAMTapeStacks
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Finite stack controls for binary word scans
+
+The first pass pops matching bits of the operands, applies the one-bit
+transition, and pushes each result onto a temporary stack. The second pass
+reverses that stack onto the output. The same fixed table works at every word
+width. Its final control remembers the carry, borrow, or other Boolean flag.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord
+
+open RAMTape
+
+/-- The two operand stacks, reversed temporary result and final output stack for a binary word
+scan. -/
+inductive ScanPort where
+ | left | right | tmp | out
+ deriving DecidableEq
+
+instance : Fintype ScanPort := derive_fintype% _
+
+/-- Control for reading paired operand bits, carrying the Boolean flag, emitting a temporary
+result and reversing it onto the output. -/
+inductive ScanState where
+ | left (flag : Bool)
+ | right (flag bit : Bool)
+ | emit (out flag : Bool)
+ | restore (flag : Bool)
+ | put (flag bit : Bool)
+ | done (flag : Bool)
+ | reject
+ deriving DecidableEq, Fintype
+
+/-- Run the one-bit operation on corresponding bits and return the result in word order with
+the final flag in control. -/
+def scanCode (step : Bool → Bool → Bool → Bool × Bool) : StackCode ScanPort ScanState
+ | .left c => .pop .left (fun | none => .restore c | some b => .right c b)
+ | .right c b => .pop .right (fun | none => .reject | some d => .emit (step c b d).1 (step c b d).2)
+ | .emit bit c => .push .tmp bit (.left c)
+ | .restore c => .pop .tmp (fun | none => .done c | some b => .put c b)
+ | .put c bit => .push .out bit (.restore c)
+ | .done _ => .halt true
+ | .reject => .halt false
+
+/-- Install the supplied bit lists on the left, right, temporary and output ports of the scan. -/
+def scanStacks (x y tmp out : List Bool) : Stacks ScanPort
+ | .left => x
+ | .right => y
+ | .tmp => tmp
+ | .out => out
+
+private theorem write_left (x y t o l : List Bool) :
+ Function.update (scanStacks x y t o) .left l = scanStacks l y t o := by
+ funext k; cases k <;> simp [Function.update, scanStacks]
+
+private theorem write_right (x y t o l : List Bool) :
+ Function.update (scanStacks x y t o) .right l = scanStacks x l t o := by
+ funext k; cases k <;> simp [Function.update, scanStacks]
+
+private theorem write_tmp (x y t o l : List Bool) :
+ Function.update (scanStacks x y t o) .tmp l = scanStacks x y l o := by
+ funext k; cases k <;> simp [Function.update, scanStacks]
+
+private theorem write_out (x y t o l : List Bool) :
+ Function.update (scanStacks x y t o) .out l = scanStacks x y t l := by
+ funext k; cases k <;> simp [Function.update, scanStacks]
+
+private theorem scan_first (step : Bool → Bool → Bool → Bool × Bool) (c : Bool)
+ (x y t o : List Bool) (hlen : x.length = y.length) :
+ StackRuns (scanCode step) (3 * x.length + 1) (.left c) (scanStacks x y t o)
+ (.restore (scan step c x y).2) (scanStacks [] [] ((scan step c x y).1.reverse ++ t) o) := by
+ induction x generalizing c y t with
+ | nil =>
+ have hy : y = [] := List.length_eq_zero_iff.mp hlen.symm
+ subst y
+ have hp : StackStep (scanCode step) (.left c) (scanStacks [] [] t o)
+ (.restore c) (scanStacks [] [] t o) := by
+ simpa [write_left, scanStacks] using (StackStep.pop (s := scanStacks [] [] t o)
+ (show scanCode step (.left c) = _ from rfl))
+ exact .cons hp (.nil ..)
+ | cons b xs ih =>
+ cases y with
+ | nil => simp at hlen
+ | cons d ys =>
+ have hleft : StackStep (scanCode step) (.left c) (scanStacks (b :: xs) (d :: ys) t o)
+ (.right c b) (scanStacks xs (d :: ys) t o) := by
+ simpa [write_left, scanStacks] using (StackStep.pop (s := scanStacks (b :: xs) (d :: ys) t o)
+ (show scanCode step (.left c) = _ from rfl))
+ have hright : StackStep (scanCode step) (.right c b) (scanStacks xs (d :: ys) t o)
+ (.emit (step c b d).1 (step c b d).2) (scanStacks xs ys t o) := by
+ simpa [write_right, scanStacks] using (StackStep.pop (s := scanStacks xs (d :: ys) t o)
+ (show scanCode step (.right c b) = _ from rfl))
+ have hemit : StackStep (scanCode step) (.emit (step c b d).1 (step c b d).2) (scanStacks xs ys t o)
+ (.left (step c b d).2) (scanStacks xs ys ((step c b d).1 :: t) o) := by
+ simpa [write_tmp, scanStacks] using (StackStep.push (s := scanStacks xs ys t o)
+ (show scanCode step (.emit (step c b d).1 (step c b d).2) = _ from rfl))
+ simpa only [scan, List.reverse_cons, List.append_assoc, List.cons_append, List.nil_append,
+ List.length_cons, Nat.mul_succ, Nat.add_assoc] using
+ StackRuns.cons hleft (.cons hright (.cons hemit (ih _ _ _ (Nat.succ.inj hlen))))
+
+private theorem scan_restore (step : Bool → Bool → Bool → Bool × Bool) (c : Bool)
+ (t o : List Bool) :
+ StackRuns (scanCode step) (2 * t.length + 1) (.restore c) (scanStacks [] [] t o)
+ (.done c) (scanStacks [] [] [] (t.reverse ++ o)) := by
+ induction t generalizing o with
+ | nil =>
+ have hpop : StackStep (scanCode step) (.restore c) (scanStacks [] [] [] o)
+ (.done c) (scanStacks [] [] [] o) := by
+ simpa [write_tmp, scanStacks] using (StackStep.pop (s := scanStacks [] [] [] o)
+ (show scanCode step (.restore c) = _ from rfl))
+ exact .cons hpop (.nil ..)
+ | cons b t ih =>
+ have hpop : StackStep (scanCode step) (.restore c) (scanStacks [] [] (b :: t) o)
+ (.put c b) (scanStacks [] [] t o) := by
+ simpa [write_tmp, scanStacks] using (StackStep.pop (s := scanStacks [] [] (b :: t) o)
+ (show scanCode step (.restore c) = _ from rfl))
+ have hpush : StackStep (scanCode step) (.put c b) (scanStacks [] [] t o)
+ (.restore c) (scanStacks [] [] t (b :: o)) := by
+ simpa [write_out, scanStacks] using (StackStep.push (s := scanStacks [] [] t o)
+ (show scanCode step (.put c b) = _ from rfl))
+ simpa only [List.reverse_cons, List.append_assoc, List.cons_append, List.nil_append,
+ List.length_cons, Nat.mul_succ, Nat.add_assoc] using StackRuns.cons hpop (.cons hpush (ih _))
+
+/-- Both inputs are consumed. The output stack receives the little-endian
+result. The scratch stack is empty and the final flag is retained. -/
+theorem scanRuns (step : Bool → Bool → Bool → Bool × Bool) (c : Bool)
+ (x y o : List Bool) (hlen : x.length = y.length) :
+ StackRuns (scanCode step) (5 * x.length + 2) (.left c) (scanStacks x y [] o)
+ (.done (scan step c x y).2) (scanStacks [] [] [] ((scan step c x y).1 ++ o)) := by
+ have hf := scan_first step c x y [] o hlen
+ simp only [List.append_nil] at hf
+ have hr := scan_restore step (scan step c x y).2 (scan step c x y).1.reverse o
+ simp only [List.reverse_reverse, List.length_reverse, length_scan step c x y hlen] at hr
+ convert hf.trans hr using 1
+ omega
+
+end TapeWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordShift.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordShift.lean
new file mode 100644
index 0000000000..053b3b2a74
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordShift.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.RAMTapeWordShiftBorrow
+import OAI.Computability.VPVNP.RAMTapeWordShiftMove
+import OAI.Computability.VPVNP.RAMTapeWordShiftValue
+import Mathlib.Tactic.Linarith
+
+/-!
+# Fixed-stack programs for variable word shifts
+
+The decrement loop processes at most the width of the data word, including
+when the shift amount represents an exponentially larger natural number.
+Reversing the data before and after the loop implements a left shift. Both
+variants leave a little-endian word and empty all their scratch stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.Shift
+
+open RAMTape BurstRAM
+
+/-- The entry port depends on the operation, so a left shift can first reverse
+its input onto the data stack. -/
+def input (left : Bool) (amount data : List Bool) : Stacks Reg :=
+ if left then store amount [] data [] [] else store amount data [] [] []
+
+/-- Returned stack layout for a variable shift. Left shifts place the final word on the
+temporary port, and right shifts place it on the output port. -/
+def output (left : Bool) (bits : List Bool) : Stacks Reg :=
+ if left then store [] [] bits [] [] else store [] [] [] bits []
+
+local macro "shift_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_store])
+
+/-- The data prefix is dropped one bit at a time. The padding is limited by
+the number of bits actually removed. -/
+private theorem loop_run (left : Bool) (a d o : List Bool) :
+ ∃ k ≤ (d.length + 1) * (5 * (a.length + 1) + 12) + 4 * d.length + 3,
+ StackRuns (code left) k .loop (store a d [] o []) .finish
+ (store [] [] [] (d.drop (value a) ++ (List.replicate (min (value a) d.length) false ++ o)) []) := by
+ induction d generalizing a o with
+ | nil =>
+ refine ⟨(a.length + 1) + 1, by simp; omega, ?_⟩
+ shift_step
+ simpa using discard_run left a [] [] o []
+ | cons b d ih =>
+ obtain ⟨kb, hkb, run⟩ := borrow_run left b a d [] o
+ by_cases hz : value a = 0
+ · simp only [hz, ↓reduceIte] at run
+ have hr := reverseData_run left [] (b :: d) [] o []
+ have ht := restoreData_run left [] [] (b :: d).reverse o []
+ simp only [List.append_nil, List.reverse_reverse, List.length_reverse] at hr ht
+ let m := 2 * (b :: d).length + 1
+ have hcopy : StackRuns (code left) ((m + m) + 1) (.zero b) (store [] d [] o [])
+ .finish (store [] [] [] ((b :: d) ++ o) []) := by
+ shift_step
+ exact hr.trans ht
+ refine ⟨(kb + ((m + m) + 1)) + 1, ?_, ?_⟩
+ · simp only [m, List.length_cons]
+ rw [Nat.succ_mul (d.length + 1)]
+ omega
+ · simp only [hz, Nat.zero_min, List.replicate_zero, List.nil_append, List.drop_zero]
+ shift_step
+ exact run.trans hcopy
+ · simp only [hz, ↓reduceIte] at run
+ obtain ⟨a', hlen, hval, hrun⟩ := run
+ obtain ⟨kt, hkt, htail⟩ := ih a' (false :: o)
+ rw [hlen] at hkt
+ have hc : StackRuns (code left) (kt + 1) .consume (store a' d [] o []) .finish
+ (store [] [] [] (d.drop (value a') ++
+ (List.replicate (min (value a') d.length) false ++ false :: o)) []) := by
+ shift_step
+ exact htail
+ refine ⟨(kb + (kt + 1)) + 1, ?_, ?_⟩
+ · simp only [List.length_cons]
+ rw [Nat.succ_mul (d.length + 1)]
+ omega
+ · have he : value a = value a' + 1 := by omega
+ simp only [he, List.drop_succ_cons, List.length_cons, Nat.succ_min_succ,
+ List.replicate_succ', List.append_assoc, List.singleton_append]
+ shift_step
+ exact hrun.trans hc
+
+private theorem start_run (left : Bool) (a x : List Bool) :
+ ∃ k ≤ 2 * x.length + 2, StackRuns (code left) k .start (input left a x) .loop
+ (store a (if left then x.reverse else x) [] [] []) := by
+ cases left with
+ | false =>
+ exact ⟨1, by omega, .cons (.goto rfl) (.nil ..)⟩
+ | true =>
+ refine ⟨(2 * x.length + 1) + 1, by omega, .cons (.goto rfl) ?_⟩
+ simpa [input] using prepare_run true a [] x [] []
+
+private theorem finish_run (left : Bool) (y : List Bool) :
+ ∃ k ≤ 2 * y.length + 2, StackRuns (code left) k .finish (store [] [] [] y []) .done
+ (output left (if left then y.reverse else y)) := by
+ cases left with
+ | false =>
+ exact ⟨1, by omega, .cons (.goto rfl) (.nil ..)⟩
+ | true =>
+ refine ⟨(2 * y.length + 1) + 1, by omega, .cons (.goto rfl) ?_⟩
+ simpa [output] using reverseOut_run true [] [] [] y []
+
+/-- Both variable-shift opcodes have a width-independent control and five
+stacks. The instruction bound is quadratic in the width, for every amount. -/
+theorem shift_run {w : ℕ} (left : Bool) (x y : Word w) :
+ ∃ k ≤ 40 * (w + 1) ^ 2, StackRuns (code left) k .start (input left (wordBits y) (wordBits x))
+ .done (output left (wordBits ((if left then PrivateRAM.BinaryOp.shiftLeft else
+ PrivateRAM.BinaryOp.shiftRight).eval x y))) := by
+ let z := if left then (wordBits x).reverse else wordBits x
+ let u := z.drop y.val ++ List.replicate (min y.val z.length) false
+ have hz : z.length = w := by cases left <;> simp [z]
+ have hu : u.length = w := by
+ simp only [u, List.length_append, List.length_drop, List.length_replicate, hz]
+ omega
+ obtain ⟨ka, ha, hstart⟩ := start_run left (wordBits y) (wordBits x)
+ obtain ⟨kb, hb, hcore⟩ := loop_run left (wordBits y) z []
+ obtain ⟨kc, hc, hend⟩ := finish_run left u
+ rw [length_wordBits] at ha
+ rw [hz, length_wordBits] at hb
+ rw [hu] at hc
+ refine ⟨ka + kb + kc, by nlinarith, ?_⟩
+ have core : StackRuns (code left) kb .loop (store (wordBits y) z [] [] []) .finish
+ (store [] [] [] u []) := by simpa only [value_wordBits, List.append_nil, u] using hcore
+ rw [← result_wordBits]
+ simpa only [result, value_wordBits] using (hstart.trans core).trans hend
+
+end TapeWord.Shift
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordShiftBorrow.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordShiftBorrow.lean
new file mode 100644
index 0000000000..3cd4496289
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordShiftBorrow.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.RAMTapeWordShiftControl
+
+/-!
+# Subtracting one from the binary shift amount
+
+A leading zero in the little-endian amount creates a pending one on the
+scratch stack. At the first set bit, the machine clears it and restores
+the pending ones. Reaching the end signals zero and clears the scratch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.Shift
+
+open RAMTape
+
+local macro "borrow_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_store, Bool.false_eq_true, ite_false, ite_true])
+
+private theorem clear_run (left b : Bool) (d t o s : List Bool) :
+ StackRuns (code left) (s.length + 1) (.clear b) (store [] d t o s)
+ (.zero b) (store [] d t o []) := by
+ induction s with
+ | nil => borrow_step; exact .nil ..
+ | cons x s ih =>
+ simp only [List.length_cons]
+ borrow_step
+ exact ih
+
+private theorem restore_run (left : Bool) (a d t o s : List Bool) :
+ StackRuns (code left) (2 * s.length + 1) .restore (store a d t o s)
+ .consume (store (List.replicate s.length true ++ a) d t o []) := by
+ induction s generalizing a with
+ | nil => borrow_step; exact .nil ..
+ | cons x s ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.replicate_succ', List.append_assoc,
+ List.singleton_append]
+ borrow_step
+ borrow_step
+ exact ih (true :: a)
+
+private theorem borrow_pending (left b : Bool) (a d t o s : List Bool) :
+ ∃ k ≤ 4 * a.length + 2 * s.length + 3,
+ if value a = 0 then
+ StackRuns (code left) k (.borrow b) (store a d t o s) (.zero b) (store [] d t o [])
+ else ∃ a', a'.length = a.length ∧ value a' = value a - 1 ∧
+ StackRuns (code left) k (.borrow b) (store a d t o s) .consume
+ (store (List.replicate s.length true ++ a') d t o []) := by
+ induction a generalizing s with
+ | nil =>
+ refine ⟨s.length + 1 + 1, by simp only [List.length_nil]; omega, ?_⟩
+ simp only [value, ite_true]
+ borrow_step
+ exact clear_run left b d t o s
+ | cons x a ih =>
+ cases x with
+ | true =>
+ refine ⟨2 * s.length + 1 + 1 + 1, by simp only [List.length_cons]; omega, ?_⟩
+ have hn : value (true :: a) ≠ 0 := by simp [value]
+ simp only [hn, ↓reduceIte]
+ refine ⟨false :: a, rfl, by simp [value], ?_⟩
+ borrow_step
+ borrow_step
+ exact restore_run left (false :: a) d t o s
+ | false =>
+ obtain ⟨k, hk, run⟩ := ih (true :: s)
+ refine ⟨k + 1 + 1, by simp only [List.length_cons] at *; omega, ?_⟩
+ by_cases hz : value a = 0
+ · have hz' : value (false :: a) = 0 := by simp [value, hz]
+ simp only [hz', ↓reduceIte]
+ simp only [hz, ↓reduceIte] at run
+ borrow_step
+ borrow_step
+ exact run
+ · have hn : value (false :: a) ≠ 0 := by simp [value, hz]
+ simp only [hn, ↓reduceIte]
+ simp only [hz, ↓reduceIte] at run
+ obtain ⟨a', hlen, hval, hr⟩ := run
+ refine ⟨true :: a', by simp [hlen], ?_, ?_⟩
+ · simp only [value, Bool.toNat_true, Bool.toNat_false]
+ omega
+ · borrow_step
+ borrow_step
+ simpa only [List.length_cons, List.replicate_succ', List.append_assoc,
+ List.singleton_append] using hr
+
+/-- A positive binary shift amount decreases by one with its width preserved.
+For a zero amount, the zero branch is reached with both amount and scratch empty. -/
+theorem borrow_run (left b : Bool) (a d t o : List Bool) :
+ ∃ k ≤ 5 * (a.length + 1) + 5,
+ if value a = 0 then
+ StackRuns (code left) k (.borrow b) (store a d t o []) (.zero b) (store [] d t o [])
+ else ∃ a', a'.length = a.length ∧ value a' = value a - 1 ∧
+ StackRuns (code left) k (.borrow b) (store a d t o []) .consume (store a' d t o []) := by
+ obtain ⟨k, hk, run⟩ := borrow_pending left b a d t o []
+ exact ⟨k, by simp only [List.length_nil] at hk; omega, by simpa using run⟩
+
+end TapeWord.Shift
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordShiftControl.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordShiftControl.lean
new file mode 100644
index 0000000000..091f6cdc01
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordShiftControl.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.RAMTapeStacks
+import OAI.Computability.VPVNP.RAMTapeWord
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Finite control for a bounded variable shift
+
+The loop removes a bit from the data and tries to subtract one from the shift
+amount. Each successful subtraction fills a vacated slot with zero. If the
+amount is zero, the machine puts the current bit back and copies the remaining
+data to the output. If the data runs out, it discards the unused amount.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.Shift
+
+open RAMTape
+
+/-- Stacks for the remaining shift amount, data word, reversed temporary data, output and
+scratch bits. -/
+inductive Reg
+ | amount | data | temp | output | scratch
+ deriving DecidableEq
+
+instance : Fintype Reg :=
+ ⟨{.amount, .data, .temp, .output, .scratch}, fun k => by cases k <;> simp⟩
+
+/-- Control for the bounded shift loop, decrementing the amount, inserting zeros, and reversing
+data when implementing a left shift. -/
+inductive State
+ | start | prepare | putPrepare (b : Bool)
+ | loop | borrow (b : Bool) | borrowFalse (b : Bool) | borrowOne
+ | restore | putTrue | clear (b : Bool) | zero (b : Bool) | consume | discard
+ | reverseData | putTemp (b : Bool) | restoreData | putOut (b : Bool)
+ | finish | reverseOut | putFinal (b : Bool) | done
+ deriving DecidableEq, Fintype
+
+/-- Fixed control that discards at most one data bit per successful decrement and preserves the
+word width by filling vacated positions with zeros. -/
+def code (left : Bool) : StackCode Reg State
+ | .start => .goto (if left then .prepare else .loop)
+ | .prepare => .pop .temp fun b => b.elim .loop .putPrepare
+ | .putPrepare b => .push .data b .prepare
+ | .loop => .pop .data fun b => b.elim .discard .borrow
+ | .borrow b => .pop .amount fun a => a.elim (.clear b) fun v =>
+ if v then .borrowOne else .borrowFalse b
+ | .borrowFalse b => .push .scratch true (.borrow b)
+ | .borrowOne => .push .amount false .restore
+ | .restore => .pop .scratch fun t => t.elim .consume (fun _ => .putTrue)
+ | .putTrue => .push .amount true .restore
+ | .clear b => .pop .scratch fun t => t.elim (.zero b) (fun _ => .clear b)
+ | .zero b => .push .data b .reverseData
+ | .consume => .push .output false .loop
+ | .discard => .pop .amount fun a => a.elim .finish (fun _ => .discard)
+ | .reverseData => .pop .data fun b => b.elim .restoreData .putTemp
+ | .putTemp b => .push .temp b .reverseData
+ | .restoreData => .pop .temp fun b => b.elim .finish .putOut
+ | .putOut b => .push .output b .restoreData
+ | .finish => .goto (if left then .reverseOut else .done)
+ | .reverseOut => .pop .output fun b => b.elim .done .putFinal
+ | .putFinal b => .push .temp b .reverseOut
+ | .done => .halt true
+
+/-- Place the five supplied lists on the shift amount, data, temporary, output and scratch
+ports. -/
+def store (amount data temp output scratch : List Bool) : Stacks Reg
+ | .amount => amount
+ | .data => data
+ | .temp => temp
+ | .output => output
+ | .scratch => scratch
+
+theorem update_store (a d t o s bits : List Bool) (k : Reg) :
+ Function.update (store a d t o s) k bits = match k with
+ | .amount => store bits d t o s
+ | .data => store a bits t o s
+ | .temp => store a d bits o s
+ | .output => store a d t bits s
+ | .scratch => store a d t o bits := by
+ funext i
+ cases k <;> cases i <;> simp [store]
+
+end TapeWord.Shift
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordShiftMove.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordShiftMove.lean
new file mode 100644
index 0000000000..c166e617e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordShiftMove.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.RAMTapeWordShiftControl
+
+/-!
+# Stack transfers in the variable-shift machine
+
+Each transfer pops the source and pushes its bits onto the destination.
+The final empty-stack test accounts for one step beyond the two steps per
+bit. Discarding the remaining shift amount needs only the pops.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.Shift
+
+open RAMTape
+
+local macro "move_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [store, List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil,
+ Option.elim_some, Option.elim_none, update_store])
+
+local macro "transfer_stack " src:Lean.Parser.Tactic.elimTarget " into " dst:ident : tactic => `(tactic|
+ induction $src generalizing $dst with
+ | nil => move_step; exact .nil ..
+ | cons b xs ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ move_step
+ move_step
+ exact ih (b :: $dst))
+
+theorem prepare_run (left : Bool) (a d t o s : List Bool) :
+ StackRuns (code left) (2 * t.length + 1) .prepare (store a d t o s)
+ .loop (store a (t.reverse ++ d) [] o s) := by
+ transfer_stack t into d
+
+theorem reverseData_run (left : Bool) (a d t o s : List Bool) :
+ StackRuns (code left) (2 * d.length + 1) .reverseData (store a d t o s)
+ .restoreData (store a [] (d.reverse ++ t) o s) := by
+ transfer_stack d into t
+
+theorem restoreData_run (left : Bool) (a d t o s : List Bool) :
+ StackRuns (code left) (2 * t.length + 1) .restoreData (store a d t o s)
+ .finish (store a d [] (t.reverse ++ o) s) := by
+ transfer_stack t into o
+
+theorem reverseOut_run (left : Bool) (a d t o s : List Bool) :
+ StackRuns (code left) (2 * o.length + 1) .reverseOut (store a d t o s)
+ .done (store a d (o.reverse ++ t) [] s) := by
+ transfer_stack o into t
+
+theorem discard_run (left : Bool) (a d t o s : List Bool) :
+ StackRuns (code left) (a.length + 1) .discard (store a d t o s)
+ .finish (store [] d t o s) := by
+ induction a with
+ | nil => move_step; exact .nil ..
+ | cons b a ih =>
+ simp only [List.length_cons]
+ move_step
+ exact ih
+
+end TapeWord.Shift
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordShiftValue.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordShiftValue.lean
new file mode 100644
index 0000000000..56a063336b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordShiftValue.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+import OAI.Computability.VPVNP.RAMProgram
+
+/-!
+# Logical shifts on fixed-width bit tapes
+
+A right shift drops the low bits and fills the high end with zeros. For a
+left shift the tape is reversed before and after the same operation. The
+number of zeros is capped at the width, so an overshift clears the tape.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord.Shift
+
+open BurstRAM
+
+/-- Drop and fill in the orientation determined by the shift direction. -/
+def result (left : Bool) (x : List Bool) (n : ℕ) : List Bool :=
+ let z := if left then x.reverse else x
+ let y := z.drop n ++ List.replicate (min n z.length) false
+ if left then y.reverse else y
+
+@[simp] theorem length_result (left : Bool) (x : List Bool) (n : ℕ) :
+ (result left x n).length = x.length := by
+ cases left <;> simp [result] <;> omega
+
+private theorem value_drop {xs : List Bool} {n : ℕ} (hn : n ≤ xs.length) :
+ value (xs.drop n) = value xs / 2 ^ n := by
+ have hlen : (xs.take n).length = n := by simp [hn]
+ have hlow : value (xs.take n) < 2 ^ n := by simpa only [hlen] using value_lt (xs.take n)
+ have h := congrArg value (List.take_append_drop n xs)
+ rw [value_append, hlen] at h
+ rw [← h, Nat.add_mul_div_left _ _ (Nat.pow_pos (by decide)), Nat.div_eq_of_lt hlow, Nat.zero_add]
+
+/-- The bit-string shift computes the RAM shift for every width and amount. -/
+theorem result_wordBits {w : ℕ} (left : Bool) (x y : Word w) :
+ result left (wordBits x) y.val =
+ wordBits ((if left then PrivateRAM.BinaryOp.shiftLeft else .shiftRight).eval x y) := by
+ apply eq_of_length_value
+ · simp
+ rw [value_wordBits]
+ by_cases hn : y.val < w
+ · have hlen : y.val ≤ (wordBits x).length := by simpa using hn.le
+ cases left with
+ | false =>
+ have hsmall : x.val / 2 ^ y.val < 2 ^ w :=
+ (Nat.div_le_self _ _).trans_lt x.isLt
+ simp [result, value_append, value_drop hlen, value_wordBits, PrivateRAM.BinaryOp.eval,
+ hn, Nat.shiftRight_eq_div_pow, Nat.mod_eq_of_lt hsmall]
+ | true =>
+ have hpow : 2 ^ w = 2 ^ y.val * 2 ^ (w - y.val) := by
+ rw [← pow_add, Nat.add_sub_of_le hn.le]
+ simp [result, List.drop_reverse, value_append, value_take_mod, value_wordBits, hn.le,
+ PrivateRAM.BinaryOp.eval, hn, Nat.shiftLeft_eq, Nat.mul_comm x.val, hpow,
+ Nat.mul_mod_mul_left]
+ · have hdrop : (wordBits x).length ≤ y.val := by simpa using Nat.le_of_not_gt hn
+ have hrev : (wordBits x).reverse.length ≤ y.val := by simpa using hdrop
+ cases left <;> simp [result, List.drop_of_length_le hdrop, List.drop_of_length_le hrev,
+ PrivateRAM.BinaryOp.eval, hn]
+
+end TapeWord.Shift
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordSimple.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordSimple.lean
new file mode 100644
index 0000000000..db120e61fa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordSimple.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.RAMTapeWordScan
+import OAI.Computability.VPVNP.RAMProgram
+
+/-!
+# Arithmetic and logical RAM opcodes in the finite scan control
+
+Addition and subtraction discard the final overflow bit. Parallel Boolean
+operations use a dummy flag. The same subtraction run retains the unsigned
+comparison result in its final state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord
+
+open RAMTape BurstRAM BurstRAM.PrivateRAM
+
+/-- RAM operations computable by scanning pairs of corresponding bits with a single Boolean
+carry or borrow. -/
+inductive ScanOp where
+ | add | sub | bitAnd | bitOr | bitXor
+ deriving DecidableEq
+
+/-- Identify the bit-scan operation with the corresponding binary RAM opcode. -/
+def ScanOp.opcode : ScanOp → BinaryOp
+ | .add => .add
+ | .sub => .sub
+ | .bitAnd => .bitAnd
+ | .bitOr => .bitOr
+ | .bitXor => .bitXor
+
+/-- Compute one output bit and the next carry or borrow. Bitwise logical operations compute the
+output without a carry. -/
+def ScanOp.step : ScanOp → Bool → Bool → Bool → Bool × Bool
+ | .add => addBit
+ | .sub => subBit
+ | .bitAnd => fun _ a b => (a && b, false)
+ | .bitOr => fun _ a b => (a || b, false)
+ | .bitXor => fun _ a b => (a ^^ b, false)
+
+private theorem addScan_wordBits {w : ℕ} (a b : Word w) :
+ (addScan false (wordBits a) (wordBits b)).1 = wordBits (a + b) := by
+ have hlen : (wordBits a).length = (wordBits b).length := by simp
+ have hr := length_addScan (c := false) hlen
+ simp only [length_wordBits] at hr
+ have hv := addScan_spec (c := false) hlen
+ simp only [length_wordBits, value_wordBits, Bool.toNat_false, Nat.add_zero] at hv
+ have hlo := value_lt (addScan false (wordBits a) (wordBits b)).1
+ rw [hr] at hlo
+ apply eq_of_length_value (by simpa using hr)
+ rw [value_wordBits, Fin.val_add, ← hv, Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hlo]
+
+private theorem subScan_wordBits {w : ℕ} (a b : Word w) :
+ (subScan false (wordBits a) (wordBits b)).1 = wordBits (a - b) := by
+ have hlen : (wordBits a).length = (wordBits b).length := by simp
+ have hr := length_subScan (c := false) hlen
+ simp only [length_wordBits] at hr
+ have hv := subScan_spec (c := false) hlen
+ simp only [length_wordBits, value_wordBits, Bool.toNat_false, Nat.add_zero] at hv
+ have hlo := value_lt (subScan false (wordBits a) (wordBits b)).1
+ rw [hr] at hlo
+ apply eq_of_length_value (by simpa using hr)
+ rw [value_wordBits, Fin.val_sub]
+ have hb := b.isLt
+ cases h : (subScan false (wordBits a) (wordBits b)).2
+ · simp only [h, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hv
+ have he : 2^w - b.val + a.val = value (subScan false (wordBits a) (wordBits b)).1 + 2^w := by omega
+ rw [he, Nat.add_mod_right, Nat.mod_eq_of_lt hlo]
+ · simp only [h, Bool.toNat_true, Nat.mul_one] at hv
+ have he : 2^w - b.val + a.val = value (subScan false (wordBits a) (wordBits b)).1 := by omega
+ rw [he, Nat.mod_eq_of_lt hlo]
+
+private theorem logic_wordBits {w : ℕ} (op : Bool → Bool → Bool) (hzero : op false false = false)
+ (a b : Word w) : (logicScan op (wordBits a) (wordBits b)).1 =
+ wordBits (Fin.ofNat (2^w) (Nat.bitwise op a.val b.val)) := by
+ have hlen : (wordBits a).length = (wordBits b).length := by simp
+ have hr := length_scan (fun _ x y => (op x y, false)) false _ _ hlen
+ have hs := logicScan_spec hzero hlen
+ have hlo := value_lt (logicScan op (wordBits a) (wordBits b)).1
+ change (logicScan op (wordBits a) (wordBits b)).1.length = _ at hr
+ rw [hr, length_wordBits] at hlo
+ simp only [value_wordBits] at hs
+ apply eq_of_length_value (by simpa using hr)
+ rw [value_wordBits, Fin.val_ofNat, ← hs, Nat.mod_eq_of_lt hlo]
+
+theorem ScanOp.result_wordBits {w : ℕ} (op : ScanOp) (a b : Word w) :
+ (scan op.step false (wordBits a) (wordBits b)).1 = wordBits (op.opcode.eval a b) := by
+ cases op with
+ | add => exact addScan_wordBits ..
+ | sub => exact subScan_wordBits ..
+ | bitAnd => exact logic_wordBits (· && ·) rfl a b
+ | bitOr => exact logic_wordBits (· || ·) rfl a b
+ | bitXor => exact logic_wordBits (· ^^ ·) rfl a b
+
+/-- Literal bit-stack executions of all five linear-time binary opcodes. -/
+theorem ScanOp.word_run {w : ℕ} (op : ScanOp) (a b : Word w) :
+ StackRuns (scanCode op.step) (5 * w + 2) (.left false) (scanStacks (wordBits a) (wordBits b) [] [])
+ (.done (scan op.step false (wordBits a) (wordBits b)).2)
+ (scanStacks [] [] [] (wordBits (op.opcode.eval a b))) := by
+ simpa only [length_wordBits, op.result_wordBits, List.append_nil] using
+ scanRuns op.step false (wordBits a) (wordBits b) [] (by simp)
+
+/-- Unsigned comparison of the operands can branch directly on the final
+borrow of the subtraction scan. -/
+theorem subScan_borrow {c : Bool} {x y : List Bool} (hlen : x.length = y.length) :
+ (subScan c x y).2 = true ↔ value x < value y + c.toNat := by
+ have hv := subScan_spec (c := c) hlen
+ have hz := value_lt (subScan c x y).1
+ rw [length_subScan hlen] at hz
+ cases h : (subScan c x y).2 <;> simp only [h, Bool.toNat_false, Bool.toNat_true, Nat.mul_zero,
+ Nat.mul_one, Nat.add_zero] at hv <;> simp <;> omega
+
+end TapeWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTapeWordSlice.lean b/lean/OAI/Computability/VPVNP/RAMTapeWordSlice.lean
new file mode 100644
index 0000000000..a2421c6968
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTapeWordSlice.lean
@@ -0,0 +1,40 @@
+import OAI.Computability.VPVNP.RAMTapeWord
+
+/-!
+# Low and high parts of a little-endian word
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TapeWord
+
+theorem value_append (xs ys : List Bool) :
+ value (xs ++ ys) = value xs + 2 ^ xs.length * value ys := by
+ induction xs with
+ | nil => simp [value]
+ | cons b xs ih =>
+ simp only [List.cons_append, value, List.length_cons, pow_succ, ih]
+ ring
+
+@[simp] theorem value_zeros (n : ℕ) : value (List.replicate n false) = 0 := by
+ induction n <;> simp [List.replicate_succ, value, *]
+
+theorem value_take_mod (xs : List Bool) (n : ℕ) :
+ value (xs.take n) = value xs % (2 ^ n) := by
+ by_cases hn : n ≤ xs.length
+ · have hlen : (xs.take n).length = n := by simp [List.length_take, hn]
+ rw [← List.take_append_drop n xs, value_append, List.take_left' hlen, hlen,
+ Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt (by simpa [hlen] using value_lt (xs.take n))]
+ · have htake : xs.take n = xs := List.take_of_length_le (by omega)
+ rw [htake, Nat.mod_eq_of_lt ((value_lt xs).trans_le (Nat.pow_le_pow_right (by decide) (by omega)))]
+
+theorem value_take_of_lt {xs : List Bool} {n : ℕ} (h : value xs < 2 ^ n) :
+ value (xs.take n) = value xs := by rw [value_take_mod, Nat.mod_eq_of_lt h]
+
+end TapeWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMTranscript.lean b/lean/OAI/Computability/VPVNP/RAMTranscript.lean
new file mode 100644
index 0000000000..a1a07cdde3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMTranscript.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.RAMMemoryMessages
+import OAI.Computability.VPVNP.RAMSuccessor
+
+/-!
+# Parsimonious distributed RAM transcripts
+
+For a power-of-two number of sites and bucket capacity, the accepting binary
+paths of the native RAM are in bijection with joint choices of successor and
+sorting messages and one successful local path at each site. The local tests
+read the site's header, its adjacent chain fields, and its sorting fields.
+They enforce the private instruction clock, per-call cost cap, global cost cap,
+and memory read consistency, without a global oracle at any processor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMMemory RAMSort
+
+/-- Shared successor cuts and sorting-network messages of one transcript. -/
+@[ext] structure Messages (d e w : ℕ) where
+ /-- Successor cut at each boundary between consecutive sites. -/
+ chain : Fin (2^d - 1) → Cut w
+ /-- Shared sorting-network data for verifying memory consistency. -/
+ memory : MemoryMessages (2+e) d w
+
+variable {d e w : ℕ} {C : Type*}
+
+/-- Padded initialization and probe records contributed by one processor. -/
+def localRecords (header : ℕ → Word w) (e v start : ℕ) (rs : List (Report w)) :
+ Wires (2+e) (OrderedSlot (Word w)) :=
+ fun j => ⟨(siteRecordBlock header (2^e) v start rs)[j.val]?.getD none⟩
+
+/-- One site's accepting reports. The header array is consulted only at
+`v`, in the initialization record of `localRecords`. -/
+def Validator (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (msg : Messages d e w) (v : Fin (2^d)) (rs : List (Report w)) : Prop :=
+ let c := inputCut ⟨0, some initial⟩ msg.chain v
+ SiteCheck P fuel (2^d) (2^e) v.val c (outputCut msg.chain v) rs ∧
+ MemoryAt msg.memory v (localRecords header e v.val c.cost rs)
+
+private theorem localRecords_eq_block {P : Program w C} {fuel : ℕ} {initial : Word w}
+ {reports : Fin (2^d) → List (Report w)} {chain : Fin (2^d-1) → Cut w}
+ (hp : SitesPass P fuel (2^d) (2^e) initial reports chain) (header : ℕ → Word w)
+ (v : Fin (2^d)) :
+ localRecords header e v.val (inputCut ⟨0, some initial⟩ chain v).cost (reports v) =
+ block (2+e) v.val (recordWires header d e (List.ofFn reports).flatten) := by
+ have caps := (successor_sound (Nat.two_pow_pos d) hp).2.2
+ have hr := block_recordWires header caps.1 caps.2 v
+ rw [getElem_canonicalRecordBlocks] at hr
+ have he := sitesPass_eq_partition (Nat.two_pow_pos d) hp
+ simp only [← he, List.getElem_ofFn] at hr
+ rw [sitesPass_input_cost (Nat.two_pow_pos d) hp]
+ funext j
+ have hj := congrArg (fun l : List (OrderedSlot (Word w)) => l[j.val]?) hr
+ have hlen := congrArg List.length hr
+ simp only [List.length_ofFn, List.length_map] at hlen
+ have hlt := lt_of_lt_of_eq j.isLt hlen
+ have hof : j.val < (List.ofFn (block (2+e) v.val (recordWires header d e
+ (List.ofFn reports).flatten))).length := by simpa only [List.length_ofFn] using j.isLt
+ rw [List.getElem?_eq_getElem hof, List.getElem?_map, List.getElem?_eq_getElem hlt] at hj
+ simpa [localRecords, List.getElem?_eq_getElem hlt] using hj.symm
+
+/-- The independent tests at all sites, expressed using their unique global
+execution and its correctly sorted memory history. -/
+theorem validators_iff (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (msg : Messages d e w) (reports : Fin (2^d) → List (Report w)) :
+ (∀ v, Validator P fuel initial header msg v (reports v)) ↔
+ SitesPass P fuel (2^d) (2^e) initial reports msg.chain ∧
+ msg.memory = actualMemoryMessages (2+e) d (recordWires header d e (List.ofFn reports).flatten) ∧
+ Correct (initialMemory (2^d) header) (eventLog (List.ofFn reports).flatten) := by
+ constructor
+ · intro h
+ have hs : SitesPass P fuel (2^d) (2^e) initial reports msg.chain := fun v => (h v).1
+ have caps := (successor_sound (Nat.two_pow_pos d) hs).2.2
+ refine ⟨hs, (report_memoryAt_iff header caps.1 caps.2 msg.memory).mp ?_⟩
+ intro v
+ rw [← localRecords_eq_block hs header v]
+ exact (h v).2
+ · rintro ⟨hs, hm, hread⟩
+ have caps := (successor_sound (Nat.two_pow_pos d) hs).2.2
+ have hm' := (report_memoryAt_iff header caps.1 caps.2 msg.memory).mpr ⟨hm, hread⟩
+ intro v
+ refine ⟨hs v, ?_⟩
+ rw [localRecords_eq_block hs header v]
+ exact hm' v
+
+/-- Accepted shared messages together with one verified report list at every site. -/
+abbrev TypedJointPaths (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (d e : ℕ) := {t : Messages d e w × (Fin (2^d) → List (Report w)) //
+ ∀ v, Validator P fuel initial header t.1 v (t.2 v)}
+
+private def jointReports (P : Program w C) (fuel : ℕ) (initial : Word w) (header : ℕ → Word w)
+ (t : TypedJointPaths P fuel initial header d e) :
+ VerifiedReports P fuel initial (initialMemory (2^d) header) (withinCaps (2^d) (2^e)) := by
+ refine ⟨(List.ofFn t.val.2).flatten, ?_⟩
+ obtain ⟨hs, _, hm⟩ := (validators_iff ..).mp t.property
+ obtain ⟨hg, ha, hc⟩ := successor_sound (Nat.two_pow_pos d) hs
+ exact ⟨hg, hm, ha, hc⟩
+
+/-- Flattening the local reports is a bijection. The successor messages,
+the bucket partition, all pre-comparison blocks, and every last-record field
+are determined by the native path, even after an early halt. -/
+private theorem jointReports_bijective (P : Program w C) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) :
+ Function.Bijective (jointReports (d := d) (e := e) P fuel initial header) := by
+ constructor
+ · intro a b hab
+ have hf : (List.ofFn a.val.2).flatten = (List.ofFn b.val.2).flatten := congrArg Subtype.val hab
+ obtain ⟨ha, hma, _⟩ := (validators_iff ..).mp a.property
+ obtain ⟨hb, hmb, _⟩ := (validators_iff ..).mp b.property
+ obtain ⟨hseg, hend, hcap⟩ := successor_sound (Nat.two_pow_pos d) hb
+ have hu := successor_unique _ _ _ _ _ _ (Nat.two_pow_pos d) (Nat.two_pow_pos e) hseg hend hcap
+ have hpair : (a.val.2, a.val.1.chain) = (b.val.2, b.val.1.chain) :=
+ hu.unique (show _ ∧ _ from ⟨hf, ha⟩) (show _ ∧ _ from ⟨rfl, hb⟩)
+ apply Subtype.ext
+ apply Prod.ext
+ · exact Messages.ext (congrArg Prod.snd hpair) (hma.trans (hf ▸ hmb.symm))
+ · exact congrArg Prod.fst hpair
+ · intro r
+ obtain ⟨p, ⟨hflat, hs⟩, _⟩ := successor_unique _ _ _ _ _ r.val (Nat.two_pow_pos d)
+ (Nat.two_pow_pos e) r.property.1 r.property.2.2.1 r.property.2.2.2
+ let msg : Messages d e w := ⟨p.2, actualMemoryMessages (2+e) d (recordWires header d e r.val)⟩
+ refine ⟨⟨⟨msg, p.1⟩, (validators_iff ..).mpr ⟨hs, ?_, ?_⟩⟩, Subtype.ext hflat⟩
+ · rw [hflat]
+ · rw [hflat]
+ exact r.property.2.1
+
+/-- Lemma 10.1 at the level of typed transcript fields. Genuine paths are
+indexed by their binary program choices. A validated read has exactly one
+allowed word, and therefore adds no multiplicity. -/
+noncomputable def transcriptEquiv (P : Program w C) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (d e : ℕ) :
+ ActualPaths P fuel initial (initialMemory (2^d) header) (withinCaps (2^d) (2^e)) ≃
+ TypedJointPaths P fuel initial header d e :=
+ (reportEquiv ..).trans (Equiv.ofBijective _ (jointReports_bijective ..)).symm
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMUniform.lean b/lean/OAI/Computability/VPVNP/RAMUniform.lean
new file mode 100644
index 0000000000..de615356e8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMUniform.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.RAMProgram
+
+/-!
+# A single burst instruction table at different word widths
+
+The public parameters and the machine word width depend on the input length.
+The instruction destinations, operand registers, and literal constants of a
+fixed program do not. A table in the finite literal format can be instantiated
+at every width. Increasing the width past the literal width preserves each
+constant's natural value.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM
+
+variable {p r k v w : ℕ}
+
+/-- Resize just the immediate constants of an instruction. No opcode, register,
+public-data location, jump target, or branch order is changed. -/
+def Instr.resize (w : ℕ) : Instr v p r k → Instr w p r k
+ | .constant dst value next => .constant dst (Fin.ofNat _ value.val) next
+ | .publicWord dst i next => .publicWord dst i next
+ | .stateWord dst next => .stateWord dst next
+ | .copy dst src next => .copy dst src next
+ | .binary op dst x y next => .binary op dst x y next
+ | .loadPrivate dst a next => .loadPrivate dst a next
+ | .storePrivate a src next => .storePrivate a src next
+ | .jumpEq x y yes no => .jumpEq x y yes no
+ | .jumpLt x y yes no => .jumpLt x y yes no
+ | .choose yes no => .choose yes no
+ | .readExternal dst a next => .readExternal dst a next
+ | .writeExternal a src next => .writeExternal a src next
+ | .returnState src => .returnState src
+ | .accept => .accept
+ | .reject => .reject
+
+theorem resize_literal (hv : v ≤ w) (a : Word v) :
+ (Fin.ofNat (2^w) a.val).val = a.val :=
+ Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le a.isLt (Nat.pow_le_pow_right (by decide) hv))
+
+/-- The finite, length-independent part of a call program. -/
+structure Template (p r k : ℕ) where
+ /-- Bit width in which the fixed instruction table stores its literal constants. -/
+ literalWidth : ℕ
+ /-- First instruction address of this table, shared by all word-width instantiations. -/
+ entry : Fin p
+ /-- Instruction stored at each bounded program counter, with constants encoded at the
+ template's literal width. -/
+ code : Fin p → Instr literalWidth p r k
+
+/-- Resize the table's literal constants to the runtime word width and install the supplied
+public operands. -/
+def Template.instantiate (t : Template p r k) (w : ℕ) (pub : Fin k → Word w) : Machine w p r k where
+ entry := t.entry
+ code i := (t.code i).resize w
+ publicData := pub
+
+theorem Template.constant_value (t : Template p r k) (w : ℕ) (pub : Fin k → Word w)
+ (i : Fin p) (dst : Fin r) (a : Word t.literalWidth) (next : Fin p)
+ (h : t.code i = .constant dst a next) (hw : t.literalWidth ≤ w) :
+ (t.instantiate w pub).code i = .constant dst
+ ⟨a.val, Nat.lt_of_lt_of_le a.isLt (Nat.pow_le_pow_right (by decide) hw)⟩ next := by
+ simp [instantiate, h, Instr.resize, Fin.ext_iff, Nat.mod_eq_of_lt (Nat.lt_of_lt_of_le a.isLt (Nat.pow_le_pow_right (by decide) hw))]
+
+end BurstRAM.PrivateRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorBoundary.lean b/lean/OAI/Computability/VPVNP/RAMValidatorBoundary.lean
new file mode 100644
index 0000000000..b3d61ad0c3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorBoundary.lean
@@ -0,0 +1,223 @@
+import OAI.Computability.VPVNP.RAMBoundary
+import OAI.Computability.VPVNP.RAMValidatorBoundaryWord
+
+/-!
+# A single pass over the local sorted RAM block
+
+The predecessor register starts at the received last record. At each physical
+slot the validator checks a possible read, latches the status, and replaces
+the predecessor even if the current slot is padding. At the end it compares
+this register with the outgoing field on sites that have a successor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMBoundary
+
+open RAMMemory BurstRAM
+
+variable {B S w : ℕ} {α β V : Type*}
+
+private def finish (equal : α → α → Bool × ℕ) (expected : Option α) (previous : α)
+ (ok : Bool) (work : ℕ) : Bool × ℕ :=
+ match expected with
+ | none => (ok, work + 3)
+ | some sent =>
+ let checked := equal sent previous
+ (ok && checked.1, work + checked.2 + 4)
+
+/-- The address argument counts the slots *after* the next slot, decreasing
+from `B - 1` to zero. The physical offset is its reversal in `Fin B`. This
+passes a constant-size index into a fixed buffer on each iteration. -/
+private def loop (read equal : α → α → Bool × ℕ) (expected : Option α) (get : Fin B → α) :
+ (k : ℕ) → k ≤ B → α → Bool → ℕ → Bool × ℕ
+ | 0, _, previous, ok, work => finish equal expected previous ok work
+ | k + 1, hk, previous, ok, work =>
+ let current := get ⟨k, hk⟩
+ let checked := read previous current
+ -- Offset subtraction, record loads and register copies, status and loop control.
+ loop read equal expected get k (by omega) current (ok && checked.1) (work + checked.2 + 16)
+
+private def remaining (get : Fin B → α) (k : ℕ) (hk : k ≤ B) : List α :=
+ List.ofFn fun i : Fin k ↦ get (i.rev.castLE hk)
+
+private theorem remaining_succ (get : Fin B → α) (k : ℕ) (hk : k+1 ≤ B) :
+ remaining get (k+1) hk = get ⟨k, hk⟩ :: remaining get k (by omega) := by
+ rw [remaining, List.ofFn_succ, Fin.rev_zero]
+ simp only [remaining, Fin.rev_succ]
+ rfl
+
+private theorem remaining_full (block : Fin B → α) :
+ remaining (fun i ↦ block i.rev) B le_rfl = List.ofFn block := by
+ simp [remaining]
+
+private theorem loop_spec [Zero V]
+ (read equal : Option (Record V) → Option (Record V) → Bool × ℕ)
+ (hr : ∀ p c, (read p c).1 = true ↔ ∀ r ∈ c, r.kind = .read → r.value = previousValue p r.address)
+ (he : ∀ a b, (equal a b).1 = true ↔ a = b)
+ (expected : Option (Option (Record V))) (get : Fin B → Option (Record V))
+ (k : ℕ) (hk : k ≤ B) (previous : Option (Record V)) (ok : Bool) (work : ℕ) :
+ (loop read equal expected get k hk previous ok work).1 = true ↔
+ ok = true ∧ PaddedCheck previous (remaining get k hk) ∧
+ ∀ x ∈ expected, x = (remaining get k hk).getLast?.getD previous := by
+ induction k generalizing previous ok work with
+ | zero =>
+ cases expected <;> simp [loop, finish, remaining, PaddedCheck, he]
+ | succ k ih =>
+ rw [loop, ih, remaining_succ, List.getLast?_cons, Option.getD_some, Bool.and_eq_true, hr]
+ cases hc : get ⟨k, hk⟩ <;> simp [PaddedCheck, and_assoc]
+
+private theorem loop_cost (read equal : α → α → Bool × ℕ)
+ (hr : ∀ p c, (read p c).2 ≤ 48) (he : ∀ a b, (equal a b).2 ≤ 60)
+ (expected : Option α) (get : Fin B → α) (k : ℕ) (hk : k ≤ B)
+ (previous : α) (ok : Bool) (work : ℕ) :
+ (loop read equal expected get k hk previous ok work).2 ≤ work + 64 * k + 64 := by
+ induction k generalizing previous ok work with
+ | zero =>
+ cases expected with
+ | none => simp [loop, finish]
+ | some s =>
+ simp only [loop, finish, Nat.mul_zero, Nat.add_zero]
+ have := he s previous
+ omega
+ | succ k ih =>
+ rw [loop]
+ have := hr previous (get ⟨k, hk⟩)
+ exact (ih (by omega) _ _ _).trans (by omega)
+
+private theorem loop_map (f : α → β) (read equal : α → α → Bool × ℕ)
+ (read' equal' : β → β → Bool × ℕ) (hr : ∀ p c, read p c = read' (f p) (f c))
+ (he : ∀ a b, equal a b = equal' (f a) (f b))
+ (expected : Option α) (get : Fin B → α) (k : ℕ) (hk : k ≤ B)
+ (previous : α) (ok : Bool) (work : ℕ) :
+ loop read equal expected get k hk previous ok work =
+ loop read' equal' (expected.map f) (fun i ↦ f (get i)) k hk (f previous) ok work := by
+ induction k generalizing previous ok work with
+ | zero => cases expected <;> simp [loop, finish, he]
+ | succ k ih => simp only [loop, hr, ih]
+
+/-- The loop counter is decremented by one in the machine word type. -/
+private def decrement (hw : 2 ≤ w) (counter : Word w) : Word w :=
+ let one : Word w := ⟨1, by have := Nat.pow_le_pow_right (by decide : 0 < 2) hw; omega⟩
+ counter - one
+
+private theorem decrement_val (hw : 2 ≤ w) (counter : Word w) (hn : counter.val ≠ 0) :
+ (decrement hw counter).val = counter.val - 1 :=
+ Fin.sub_val_of_le (by change 1 ≤ counter.val; omega)
+
+/-- Machine-word offset of the next record in the allocated local array. -/
+private def wordOffset (width counter : Word w) (hc : counter ≤ width) (hn : counter.val ≠ 0) :
+ Fin width.val :=
+ ⟨(width - counter).val, by rw [Fin.sub_val_of_le hc]; change counter.val ≤ width.val at hc; omega⟩
+
+private theorem wordOffset_val (width counter : Word w) (hc : counter ≤ width) (hn : counter.val ≠ 0) :
+ (wordOffset width counter hc hn).val = width.val - counter.val := Fin.sub_val_of_le hc
+
+/-- An executable loop over a materialized array. The counter, the decrement,
+and the subtraction that produces the next array offset use the machine word
+type. Loop termination follows from the counter value. -/
+private def wordLoop (hw : 2 ≤ w) (read equal : α → α → Bool × ℕ) (expected : Option α)
+ (buffer : Array α) (width : Word w) (hwidth : width.val = buffer.size)
+ (counter : Word w) (hc : counter ≤ width) (previous : α) (ok : Bool) (work : ℕ) : Bool × ℕ :=
+ if hz : counter.val = 0 then finish equal expected previous ok work else
+ let offset := wordOffset width counter hc hz
+ let current := buffer[offset.val]'(hwidth ▸ offset.isLt)
+ let checked := read previous current
+ wordLoop hw read equal expected buffer width hwidth (decrement hw counter)
+ (by change (decrement hw counter).val ≤ width.val; rw [decrement_val _ _ hz]
+ exact (Nat.sub_le ..).trans hc) current (ok && checked.1) (work + checked.2 + 16)
+termination_by counter.val
+decreasing_by rw [decrement_val _ _ hz]; omega
+
+private theorem wordLoop_eq (hw : 2 ≤ w) (read equal : α → α → Bool × ℕ) (expected : Option α)
+ (buffer : Array α) (width : Word w) (hwidth : width.val = buffer.size)
+ (k : ℕ) (hk : k ≤ buffer.size) (counter : Word w) (hc : counter ≤ width) (hcount : counter.val = k)
+ (previous : α) (ok : Bool) (work : ℕ) :
+ wordLoop hw read equal expected buffer width hwidth counter hc previous ok work =
+ loop read equal expected (fun i : Fin buffer.size ↦ buffer[i.rev.val]) k hk previous ok work := by
+ induction k generalizing counter previous ok work with
+ | zero => rw [wordLoop, dite_eq_left hcount, loop]
+ | succ k ih =>
+ have hn : counter.val ≠ 0 := by omega
+ rw [wordLoop, dite_eq_right hn, loop]
+ have hn' : (decrement hw counter).val = k := by rw [decrement_val _ _ hn]; omega
+ have hoff : (wordOffset width counter hc hn).val = (⟨k, hk⟩ : Fin buffer.size).rev.val := by
+ rw [wordOffset_val, Fin.val_rev, hwidth, hcount]
+ simp only [hoff]
+ exact ih _ _ _ hn' _ _ _
+
+/-- Scan the site's sorted slots in increasing order. The second argument is
+absent at the final site. A present field can itself contain padding. -/
+def scan (previous : Slot w) (expected : Option (Slot w)) (block : Fin B → Slot w) : Bool × ℕ :=
+ loop readOK equalSlot expected (fun i ↦ block i.rev) B le_rfl previous true 0
+
+/-- The status for independently supplied incoming and outgoing fields. -/
+theorem scan_ok_iff (hB : 0 < B) (previous : Slot w) (expected : Option (Slot w))
+ (block : Fin B → Slot w) :
+ (scan previous expected block).1 = true ↔
+ PaddedCheck previous (List.ofFn block) ∧ ∀ x ∈ expected, x = lastSlot hB block := by
+ have hlast : (List.ofFn block).getLast? = some (lastSlot hB block) := by
+ rw [List.getLast?_eq_some_getLast (mt List.ofFn_eq_nil_iff.mp (Nat.ne_of_gt hB)), List.getLast_ofFn]
+ rfl
+ simpa only [scan, remaining_full, hlast, Option.getD_some, true_and] using
+ loop_spec readOK equalSlot readOK_spec equalSlot_spec expected (fun i ↦ block i.rev) B
+ le_rfl previous true 0
+
+/-- The counted local scan implements the boundary predicate of Lemma 10.1
+on all message and record assignments. -/
+theorem scan_spec (hB : 0 < B) (sent : Sends S (Word w)) (v : Fin S) (block : Fin B → Slot w) :
+ (scan (receive sent v) (if v.val + 1 < S then some (outgoing sent v) else none) block).1 = true ↔
+ checkAt hB sent v block := by
+ rw [scan_ok_iff hB]
+ by_cases hv : v.val + 1 < S <;> simp [checkAt, hv]
+
+/-- Every slot is visited once, including slots after a failing read check. -/
+theorem scan_cost (previous : Slot w) (expected : Option (Slot w)) (block : Fin B → Slot w) :
+ (scan previous expected block).2 ≤ 64 * B + 64 := by
+ simpa only [scan, Nat.zero_add] using
+ loop_cost readOK equalSlot (fun p c ↦ (readOK_cost p c).trans (by decide))
+ (fun a b ↦ (equalSlot_cost a b).trans (by decide)) expected (fun i ↦ block i.rev) B
+ le_rfl previous true 0
+
+/-- The five fields of a physical slot occupy a fixed-size array. -/
+abbrev WordTuple (w : ℕ) := Vector (Word w) 5
+
+/-- Execute the same pass directly on a finite array of five-word tuples.
+The bound on the buffer length is the representability of the initial word
+counter. Every subsequent counter and offset fits by construction. -/
+def scanWords (hw : 2 ≤ w) (previous : WordTuple w) (expected : Option (WordTuple w))
+ (buffer : Array (WordTuple w)) (hfit : buffer.size < 2 ^ w) : Bool × ℕ :=
+ let width : Word w := ⟨buffer.size, hfit⟩
+ wordLoop hw (fun p c ↦ readRaw hw p.get c.get) (fun a b ↦ equalRaw hw a.get b.get)
+ expected buffer width rfl width le_rfl previous true 0
+
+/-- Both decision and work agree with the parsed-slot scan. Unknown tags and
+noncanonical payloads are included, with the parser's interpretation of each
+tuple. Canonicality is enforced when loading shared messages. -/
+theorem scanWords_eq (hw : 2 ≤ w) (previous : WordTuple w) (expected : Option (WordTuple w))
+ (buffer : Array (WordTuple w)) (hfit : buffer.size < 2 ^ w) :
+ let parse := fun r : WordTuple w ↦ (RAMSort.parsedSlot hw r.get).record
+ scanWords hw previous expected buffer hfit =
+ scan (parse previous) (expected.map parse) (fun i : Fin buffer.size ↦ parse buffer[i.val]) := by
+ let width : Word w := ⟨buffer.size, hfit⟩
+ let read := fun p c : WordTuple w ↦ readRaw hw p.get c.get
+ let equal := fun a b : WordTuple w ↦ equalRaw hw a.get b.get
+ exact (wordLoop_eq hw read equal expected buffer width rfl buffer.size
+ le_rfl width le_rfl rfl previous true 0).trans
+ (loop_map (fun r : WordTuple w ↦ (RAMSort.parsedSlot hw r.get).record) read equal readOK
+ equalSlot (fun p c ↦ readRaw_eq hw p.get c.get) (fun a b ↦ equalRaw_eq hw a.get b.get)
+ expected (fun i : Fin buffer.size ↦ buffer[i.rev.val]) buffer.size le_rfl previous true 0)
+
+theorem scanWords_cost (hw : 2 ≤ w) (previous : WordTuple w) (expected : Option (WordTuple w))
+ (buffer : Array (WordTuple w)) (hfit : buffer.size < 2 ^ w) :
+ (scanWords hw previous expected buffer hfit).2 ≤ 64 * buffer.size + 64 := by
+ rw [scanWords_eq]
+ exact scan_cost ..
+
+end RAMBoundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorBoundaryWord.lean b/lean/OAI/Computability/VPVNP/RAMValidatorBoundaryWord.lean
new file mode 100644
index 0000000000..05534e0d80
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorBoundaryWord.lean
@@ -0,0 +1,196 @@
+import OAI.Computability.VPVNP.RAMSortCompareCost
+
+/-!
+# Word tests for the boundary records of a RAM transcript
+
+A read uses the preceding slot's value exactly when that slot is occupied and has
+its address. At a successor edge the sender also compares the entire transmitted
+slot with its final slot. Both word programs respect the parser on all input tuples.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMBoundary
+
+open BurstRAM RAMMemory RAMSort RAMSort.WordCompare RAMSerialization
+
+/-- A transcript slot after decoding, either empty or holding a word-valued RAM record. -/
+abbrev Slot (w : ℕ) := Option (Record (Word w))
+/-- Five machine words making up a physical slot before occupancy and record fields are
+decoded. -/
+abbrev RawSlot (w : ℕ) := Fin 5 → Word w
+
+private abbrev Fields := Fin 5 → ℕ
+
+private def occupied (side : Bool) : Expr :=
+ .select (.eq (.field side 0) (.const 0)) (.const 0) (.le (.field side 0) (.const 3))
+
+private def sameField (i : Fin 5) : Expr := .eq (.field false i) (.field true i)
+
+private def readProgram : Expr :=
+ .select (.eq (.field true 0) (.const 2))
+ (.eq (.field true 2) (.select (occupied false)
+ (.select (sameField 1) (.field false 2) (.const 0)) (.const 0)))
+ (.const 1)
+
+private def requireSame (i : Fin 5) (rest : Expr) : Expr :=
+ .select (sameField i) rest (.const 0)
+
+private def equalProgram : Expr :=
+ .select (occupied false)
+ (requireSame 0 (requireSame 1 (requireSame 2 (requireSame 3 (sameField 4)))))
+ (.select (occupied true) (.const 0) (.const 1))
+
+variable {w : ℕ}
+
+private def typedRun (e : Expr) (a b : Slot w) : Bool × ℕ :=
+ (decide (e.eval (inputs (slotWords ⟨a⟩) (slotWords ⟨b⟩)) ≠ 0), e.steps)
+
+/-- Check the value of an occupied read against the preceding physical slot. -/
+def readOK (prev curr : Slot w) : Bool × ℕ := typedRun readProgram prev curr
+
+/-- Compare two physical slots, including the timestamp and ordinal of a probe. -/
+def equalSlot (a b : Slot w) : Bool × ℕ := typedRun equalProgram a b
+
+theorem readOK_cost (prev curr : Slot w) : (readOK prev curr).2 ≤ 35 := by
+ change readProgram.steps ≤ 35
+ decide
+
+theorem equalSlot_cost (a b : Slot w) : (equalSlot a b).2 ≤ 55 := by
+ change equalProgram.steps ≤ 55
+ decide
+
+private def Used (x : Fields) := 0 < x 0 ∧ x 0 ≤ 3
+
+private instance (x : Fields) : Decidable (Used x) :=
+ inferInstanceAs (Decidable (0 < x 0 ∧ x 0 ≤ 3))
+
+private theorem occupied_eval (x : Input) (side : Bool) :
+ (occupied side).eval x = if Used (x side) then 1 else 0 := by
+ by_cases hz : x side 0 = 0
+ · simp [occupied, Expr.eval, Used, hz]
+ · simp [occupied, Expr.eval, Used, hz, Nat.pos_of_ne_zero hz]
+
+private theorem read_eval (a b : Fields) :
+ readProgram.eval (inputs a b) ≠ 0 ↔
+ (b 0 = 2 → b 2 = if Used a ∧ a 1 = b 1 then a 2 else 0) := by
+ by_cases hr : b 0 = 2 <;> by_cases ha : Used a <;> by_cases he : a 1 = b 1 <;>
+ simp [readProgram, sameField, Expr.eval, occupied_eval, inputs, hr, ha, he]
+
+private theorem requireSame_eval (i : Fin 5) (tail : Expr) (a b : Fields) :
+ (requireSame i tail).eval (inputs a b) ≠ 0 ↔ a i = b i ∧ tail.eval (inputs a b) ≠ 0 := by
+ by_cases h : a i = b i <;> simp [requireSame, sameField, Expr.eval, inputs, h]
+
+private theorem equal_eval (a b : Fields) :
+ equalProgram.eval (inputs a b) ≠ 0 ↔
+ if Used a then a 0 = b 0 ∧ a 1 = b 1 ∧ a 2 = b 2 ∧ a 3 = b 3 ∧ a 4 = b 4 else ¬Used b := by
+ have hleft : (occupied false).eval (inputs a b) = if Used a then 1 else 0 :=
+ occupied_eval ..
+ have hright : (occupied true).eval (inputs a b) = if Used b then 1 else 0 :=
+ occupied_eval ..
+ by_cases ha : Used a
+ · simp only [equalProgram, Expr.eval, hleft, ite_eq_left ha, one_ne_zero, ite_false,
+ requireSame_eval]
+ by_cases h : a 4 = b 4 <;> simp [sameField, Expr.eval, inputs, h]
+ · by_cases hb : Used b <;> simp [equalProgram, Expr.eval, hleft, hright, ha, hb]
+
+private theorem words_none : slotWords (⟨none⟩ : OrderedSlot (Word w)) = fun _ ↦ 0 := rfl
+
+private theorem words_some (r : Record (Word w)) :
+ slotWords ⟨some r⟩ = ![r.kind.code + 1, r.address, r.value.val, r.startCost, r.ordinal] := by
+ rcases r with ⟨k, _, _, _, _⟩
+ cases k <;> rfl
+
+theorem readOK_spec (prev curr : Slot w) : (readOK prev curr).1 = true ↔
+ ∀ r ∈ curr, r.kind = .read → r.value = previousValue prev r.address := by
+ simp only [readOK, typedRun, decide_eq_true_eq, read_eval]
+ rcases curr with _ | ⟨k, a, v, c, j⟩
+ · simp [words_none]
+ · cases k <;> rcases prev with _ | ⟨k', a', v', c', j'⟩
+ all_goals first | cases k' | skip
+ all_goals simp [words_none, words_some, Used, Kind.code, previousValue]
+ all_goals split_ifs <;> first | exact Fin.ext_iff.symm | simp
+
+theorem equalSlot_spec (a b : Slot w) : (equalSlot a b).1 = true ↔ a = b := by
+ simp only [equalSlot, typedRun, decide_eq_true_eq, equal_eval]
+ rcases a with _ | ⟨k, _, _, _, _⟩ <;> rcases b with _ | ⟨k', _, _, _, _⟩
+ all_goals first | cases k | skip
+ all_goals first | cases k' | skip
+ all_goals simp [words_none, words_some, Used, Kind.code]
+ all_goals intros; exact Fin.ext_iff.symm
+
+private def rawRun (hw : 2 ≤ w) (e : Expr) (a b : RawSlot w) : Bool × ℕ :=
+ let output := e.runWord hw (fun side ↦ if side then b else a)
+ (decide (output.1.val ≠ 0), output.2)
+
+/-- Execute the predecessor test on two arbitrary five-word tuples. -/
+def readRaw (hw : 2 ≤ w) (prev curr : RawSlot w) : Bool × ℕ := rawRun hw readProgram prev curr
+
+/-- Execute whole-slot equality on two arbitrary five-word tuples. -/
+def equalRaw (hw : 2 ≤ w) (a b : RawSlot w) : Bool × ℕ := rawRun hw equalProgram a b
+
+private def values (a : RawSlot w) : Fields := fun i ↦ (a i).val
+
+private theorem rawRun_eq (hw : 2 ≤ w) (e : Expr) (a b : RawSlot w) :
+ rawRun hw e a b = (decide (e.eval (inputs (values a) (values b)) ≠ 0), e.steps) := by
+ have spec := e.runWord_spec hw (fun side ↦ if side then b else a)
+ have h : (fun side i ↦ ((if side then b else a) i).val) = inputs (values a) (values b) := by
+ funext side i
+ cases side <;> rfl
+ simp only [rawRun, spec.1, spec.2, h]
+
+private def normalize (x : Fields) : Fields := if Used x then x else fun _ ↦ 0
+
+private theorem words_parsed (hw : 2 ≤ w) (a : RawSlot w) :
+ slotWords ⟨(parsedSlot hw a).record⟩ = normalize (values a) := by
+ by_cases h : Used (values a)
+ · rw [normalize, ite_eq_left h]
+ change 0 < (a 0).val ∧ (a 0).val ≤ 3 at h
+ have ht : (a 0).val = 1 ∨ (a 0).val = 2 ∨ (a 0).val = 3 := by omega
+ rcases ht with ht | ht | ht <;> funext i <;> fin_cases i <;>
+ simp [parsedSlot, recordFormat, WordRecord.record, words_some, Kind.code, ht, values]
+ · rw [normalize, ite_eq_right h]
+ change ¬(0 < (a 0).val ∧ (a 0).val ≤ 3) at h
+ have h₁ : (a 0).val ≠ 1 := by omega
+ have h₂ : (a 0).val ≠ 2 := by omega
+ have h₃ : (a 0).val ≠ 3 := by omega
+ simp [parsedSlot, recordFormat, words_none]
+
+private theorem zero_unused : ¬Used (fun _ ↦ 0) := by simp [Used]
+
+private theorem read_normalize (a b : Fields) :
+ readProgram.eval (inputs a b) ≠ 0 ↔ readProgram.eval (inputs (normalize a) (normalize b)) ≠ 0 := by
+ rw [read_eval, read_eval]
+ by_cases hb : Used b
+ · by_cases ha : Used a <;> simp [normalize, ha, hb, zero_unused]
+ · have hread : b 0 ≠ 2 := fun ht ↦ hb (by simp [Used, ht])
+ simp [normalize, hb, hread]
+
+private theorem equal_normalize (a b : Fields) :
+ equalProgram.eval (inputs a b) ≠ 0 ↔ equalProgram.eval (inputs (normalize a) (normalize b)) ≠ 0 := by
+ rw [equal_eval, equal_eval]
+ by_cases ha : Used a <;> by_cases hb : Used b
+ · simp [normalize, ha, hb]
+ · have hne : a 0 ≠ b 0 := fun h ↦ hb (by simpa [Used, ← h] using ha)
+ have hnz : a 0 ≠ 0 := Nat.ne_of_gt ha.1
+ simp [normalize, ha, hb, hnz, hne]
+ · simp [normalize, ha, hb, zero_unused]
+ · simp [normalize, ha, hb, zero_unused]
+
+theorem readRaw_eq (hw : 2 ≤ w) (prev curr : RawSlot w) :
+ readRaw hw prev curr = readOK (parsedSlot hw prev).record (parsedSlot hw curr).record := by
+ simp only [readRaw, rawRun_eq, readOK, typedRun, words_parsed]
+ exact Prod.ext (decide_eq_decide.mpr (read_normalize _ _)) rfl
+
+theorem equalRaw_eq (hw : 2 ≤ w) (a b : RawSlot w) :
+ equalRaw hw a b = equalSlot (parsedSlot hw a).record (parsedSlot hw b).record := by
+ simp only [equalRaw, rawRun_eq, equalSlot, typedRun, words_parsed]
+ exact Prod.ext (decide_eq_decide.mpr (equal_normalize _ _)) rfl
+
+end RAMBoundary
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorBucket.lean b/lean/OAI/Computability/VPVNP/RAMValidatorBucket.lean
new file mode 100644
index 0000000000..689306a0d2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorBucket.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.RAMValidatorControl
+import OAI.Computability.VPVNP.RAMSiteRun
+import OAI.Computability.VPVNP.RAMWork
+
+/-!
+# Bounded machine simulation in a transcript bucket
+
+The range test precedes the private calls. Each call checks all three probe
+allowances before consuming a read guess. Once simulation stops, the processor
+validates its unused choice suffix and its outgoing cut or terminal halt.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM
+
+open VPVNP.BurstRAM
+
+variable {w p r k : ℕ}
+
+/-- Execute the calls and check their successor information. This includes
+work spent before an eventual failure on arbitrary input. -/
+def Machine.runBucket (M : Machine w p r k) (fuel S H v : ℕ) (input : Cut w)
+ (output : Option (Cut w)) (bits : List Bool) : Option (List (Report w)) × ℕ :=
+ if input.state.isSome → v * H ≤ input.cost ∧ input.cost < (v+1)*H then
+ let loop := M.privateSite fuel H ((v+1)*H) (S*H) (2*H-1) input (2*H-1) bits
+ match loop.output with
+ | none => (none, 16 + loop.work)
+ | some (rs, tail) =>
+ let finish := finishReports input output rs tail
+ (if finish.1 then some rs else none, 16 + loop.work + finish.2)
+ else (none, 16)
+
+theorem Machine.runBucket_result (M : Machine w p r k) (fuel S H v : ℕ) (input : Cut w)
+ (output : Option (Cut w)) (bits : List Bool) :
+ (M.runBucket fuel S H v input output bits).1 = validateSite M.program fuel S H v input output bits := by
+ unfold Machine.runBucket validateSite runSite
+ split
+ · dsimp only
+ rw [Machine.privateSite_output]
+ cases runSiteLoop M.program fuel H ((v+1)*H) (S*H) (2*H-1) input (2*H-1) bits with
+ | none => rfl
+ | some z =>
+ obtain ⟨rs, tail⟩ := z
+ cases tail with
+ | nil => cases output <;> simp [finishReports, meteredAdvance_result]
+ | cons b bs => rfl
+ · rfl
+
+theorem Machine.runBucket_iff (M : Machine w p r k) {fuel S H v : ℕ} {input : Cut w}
+ {output : Option (Cut w)} {bits : List Bool} {rs : List (Report w)} (hH : 0 < H) :
+ (M.runBucket fuel S H v input output bits).1 = some rs ↔
+ SiteCheck M.program fuel S H v input output rs ∧ bits = rs.flatMap (fun r => guessBits r.events) := by
+ rw [Machine.runBucket_result, validateSite_iff hH]
+
+theorem Machine.runBucket_work (M : Machine w p r k) (fuel S H v : ℕ) (input : Cut w)
+ (output : Option (Cut w)) (bits : List Bool) (hH : 0 < H) (hf : H ≤ 2*fuel) :
+ (M.runBucket fuel S H v input output bits).2 ≤
+ 48 + 256*(H+1)*(fuel+1)*(fuel+1)*(w+2) + (2*H)*(16*fuel+16) := by
+ let loop := M.privateSite fuel H ((v+1)*H) (S*H) (2*H-1) input (2*H-1) bits
+ have hl := M.privateSite_work_le hf ((v+1)*H) (S*H) input (2*H-1) bits
+ change loop.work ≤ _ at hl
+ by_cases hi : input.state.isSome → v * H ≤ input.cost ∧ input.cost < (v+1)*H
+ · unfold Machine.runBucket
+ rw [ite_eq_left hi]
+ rw [show M.privateSite fuel H ((v+1)*H) (S*H) (2*H-1) input (2*H-1) bits = loop from rfl]
+ dsimp only
+ cases he : loop.output with
+ | none =>
+ dsimp only
+ omega
+ | some z =>
+ obtain ⟨rs, tail⟩ := z
+ have hr : runSite M.program fuel S H v input bits = some (rs, tail) := by
+ unfold runSite
+ rw [ite_eq_left hi]
+ simpa only [loop, Machine.privateSite_output] using he
+ obtain ⟨hs, _⟩ := (runSite_iff hH).mp hr
+ have hb := finishReports_work input output rs tail H fuel
+ (boundedReports_of_localSegment hs.calls (hs.cost_lt hH).le)
+ dsimp only
+ omega
+ · unfold Machine.runBucket
+ rw [ite_eq_right hi]
+ omega
+
+end BurstRAM.PrivateRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorControl.lean b/lean/OAI/Computability/VPVNP/RAMValidatorControl.lean
new file mode 100644
index 0000000000..c424f44c39
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorControl.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.RAMSiteWork
+
+/-!
+# The local post-call control check of Lemma 10.1
+
+The validator checks that it used every private choice bit. On an internal
+successor edge it compares the final cumulative cost and status to the send.
+At the last site it requires the computed status to be an accepting halt.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ}
+
+/-- A nonempty suffix rejects immediately. Otherwise the validator scans each
+report and event once. The fixed cost covers the end-of-input test, the
+status, cost and state comparisons, branching and return. -/
+def finishReports (input : Cut w) (output : Option (Cut w)) (reports : List (Report w))
+ (tail : List Bool) : Bool × ℕ :=
+ match tail with
+ | _ :: _ => (false, 2)
+ | [] =>
+ let final := meteredAdvance input reports
+ let valid := match output with
+ | some c => decide (c = final.1)
+ | none => final.1.state.isNone
+ (valid, 16 + final.2)
+
+theorem finishReports_spec (input : Cut w) (output : Option (Cut w)) (reports : List (Report w))
+ (tail : List Bool) :
+ (finishReports input output reports tail).1 = true ↔ tail = [] ∧
+ match output with
+ | some c => c = input.advance reports
+ | none => (input.advance reports).state = none := by
+ cases tail <;> cases output <;> simp [finishReports, meteredAdvance_result]
+
+theorem finishReports_work (input : Cut w) (output : Option (Cut w)) (reports : List (Report w))
+ (tail : List Bool) (H fuel : ℕ)
+ (h : reports.length ≤ 2 * H ∧ ∀ r ∈ reports, r.events.length < fuel) :
+ (finishReports input output reports tail).2 ≤ 32 + (2*H)*(16*fuel+16) := by
+ cases tail with
+ | cons bit bits => simp [finishReports]; omega
+ | nil =>
+ have hscan := meteredAdvance_work_le input reports fuel h.2
+ have hsize : reports.length * (7 + 4*fuel) ≤ (2*H)*(16*fuel+16) :=
+ Nat.mul_le_mul h.1 (by omega)
+ simp only [finishReports]
+ omega
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorLocality.lean b/lean/OAI/Computability/VPVNP/RAMValidatorLocality.lean
new file mode 100644
index 0000000000..8af68b7a84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorLocality.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.RAMTranscript
+
+/-!
+# Locality of the distributed RAM validator
+
+A processor can check its candidate path using its own header, the two
+adjacent successor fields when present, and the sort fields incident to it.
+The comparison layers may carry arbitrary records. Agreement of the received
+blocks suffices to reproduce the local replay and agreement of the sent
+blocks suffices to reproduce the local send checks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMSort
+
+variable {α : Type*} [LinearOrder α] {h d : ℕ}
+
+private theorem localLayer_congr (s : Stage (h+d)) (v : Fin (2^d))
+ {f g : Sends h d s α}
+ (hpeer : ∀ hc, f hc (sourceSite s hc v) = g hc (sourceSite s hc v))
+ (input : Wires h α) : localLayer s f v input = localLayer s g v input := by
+ funext i
+ by_cases hc : h ≤ s.stride
+ · simp only [localLayer, hc, ↓reduceDIte, hpeer]
+ · simp only [localLayer, hc, ↓reduceDIte]
+
+private theorem stage_locality (v : Fin (2^d)) (f g : ∀ s : Stage (h+d), Sends h d s α)
+ (hsend : ∀ s hc, f s hc v = g s hc v)
+ (hpeer : ∀ s hc, f s hc (sourceSite s hc v) = g s hc (sourceSite s hc v))
+ (ss : List (Stage (h+d))) (hn : ss.Nodup) (input : Wires h α) :
+ let fs := fieldsOfStages ss hn (fun s _ ↦ f s)
+ let gs := fieldsOfStages ss hn (fun s _ ↦ g s)
+ (checks v ss fs input ↔ checks v ss gs input) ∧ replay v ss fs input = replay v ss gs input := by
+ induction ss generalizing input with
+ | nil => exact ⟨Iff.rfl, rfl⟩
+ | cons s ss ih =>
+ let hn' := (List.nodup_cons.mp hn).2
+ let fs := fieldsOfStages ss hn' (fun t _ ↦ f t)
+ let gs := fieldsOfStages ss hn' (fun t _ ↦ g t)
+ have heq := localLayer_congr s v (hpeer s) input
+ have htail := ih hn' (localLayer s (g s) v input)
+ change ((∀ hc, f s hc v = input) ∧ checks v ss fs (localLayer s (f s) v input) ↔
+ (∀ hc, g s hc v = input) ∧ checks v ss gs (localLayer s (g s) v input)) ∧
+ replay v ss fs (localLayer s (f s) v input) = replay v ss gs (localLayer s (g s) v input)
+ rw [heq]
+ exact ⟨and_congr (forall_congr' fun hc ↦ by rw [hsend s hc]) htail.1, htail.2⟩
+
+/-- Fixing the two incident blocks of each physical layer fixes both the
+processor's comparison checks and its final block. -/
+theorem physical_sort_locality (v : Fin (2^d)) {f g : RAMLayout.Layer d → Fin (2^d) → Wires h α}
+ (hs : ∀ l, f l v = g l v ∧ f l (l.partner v) = g l (l.partner v)) (input : Wires h α) :
+ let ss := phases (h+d) (h+d) le_rfl
+ let fs := physicalFieldsEquiv h d α f
+ let gs := physicalFieldsEquiv h d α g
+ (checks v ss fs input ↔ checks v ss gs input) ∧ replay v ss fs input = replay v ss gs input := by
+ let l := fun (s : Stage (h+d)) (hc : h ≤ s.stride) ↦ (crossStageEquiv h d).symm ⟨s, hc⟩
+ exact stage_locality v (fun s hc ↦ f (l s hc)) (fun s hc ↦ g (l s hc))
+ (fun s hc ↦ (hs (l s hc)).1)
+ (fun s hc ↦ by rw [sourceSite_eq_physical]; exact (hs (l s hc)).2)
+ _ (phases_nodup le_rfl) input
+
+end RAMSort
+
+namespace BurstRAM
+
+open RAMMemory RAMSort
+
+variable {w d e : ℕ} {C : Type*}
+
+/-- Two message assignments give the same fields at a site. Each existing
+successor edge is named by its sender. The first and last missing edges
+therefore require no equality. -/
+structure Messages.AgreeAt (m n : Messages d e w) (v : Fin (2^d)) : Prop where
+ successor : ∀ j : Fin (2^d-1), j.val = v.val ∨ j.val + 1 = v.val →
+ m.chain j = n.chain j ∧ m.memory.lastRecords j = n.memory.lastRecords j
+ sorting : ∀ l, m.memory.sortSends l v = n.memory.sortSends l v ∧
+ m.memory.sortSends l (l.partner v) = n.memory.sortSends l (l.partner v)
+
+private theorem Messages.AgreeAt.cuts {m n : Messages d e w} {v : Fin (2^d)}
+ (hm : m.AgreeAt n v) (initial : Word w) :
+ inputCut ⟨0, some initial⟩ m.chain v = inputCut ⟨0, some initial⟩ n.chain v ∧
+ outputCut m.chain v = outputCut n.chain v := by
+ constructor
+ · unfold inputCut
+ split
+ · rfl
+ · exact (hm.successor _ (.inr (by change v.val - 1 + 1 = v.val; omega))).1
+ · unfold outputCut
+ split
+ · exact congrArg some (hm.successor _ (.inl rfl)).1
+ · rfl
+
+private theorem Messages.AgreeAt.boundaries {m n : Messages d e w} {v : Fin (2^d)}
+ (hm : m.AgreeAt n v) :
+ RAMBoundary.receive m.memory.lastRecords v = RAMBoundary.receive n.memory.lastRecords v ∧
+ RAMBoundary.outgoing m.memory.lastRecords v = RAMBoundary.outgoing n.memory.lastRecords v := by
+ constructor
+ · rcases v with ⟨i, hi⟩
+ cases i with
+ | zero => rfl
+ | succ i => exact (hm.successor ⟨i, by omega⟩ (.inr rfl)).2
+ · unfold RAMBoundary.outgoing
+ split
+ · exact (hm.successor _ (.inl rfl)).2
+ · rfl
+
+private theorem memoryAt_congr {m n : Messages d e w} {v : Fin (2^d)} (hm : m.AgreeAt n v)
+ (input : Wires (2+e) (OrderedSlot (Word w))) : MemoryAt m.memory v input ↔ MemoryAt n.memory v input := by
+ have h := physical_sort_locality v hm.sorting input
+ have hout : outputAt m.memory v input = outputAt n.memory v input :=
+ funext fun i ↦ congrArg (fun f : Wires (2+e) (OrderedSlot (Word w)) ↦ (f i).record) h.2
+ unfold MemoryAt
+ apply and_congr h.1
+ rw [hout]
+ simp only [RAMBoundary.checkAt, hm.boundaries.1, hm.boundaries.2]
+
+/-- The local path predicate for any candidate reports, including rejecting
+candidates, depends only on the site's header word and incident fields. -/
+theorem validator_congr (P : Program w C) (fuel : ℕ) (initial : Word w)
+ {header header' : ℕ → Word w} {m n : Messages d e w} {v : Fin (2^d)}
+ (hheader : header v = header' v) (hm : m.AgreeAt n v) (rs : List (Report w)) :
+ Validator P fuel initial header m v rs ↔ Validator P fuel initial header' n v rs := by
+ have hrecords (start : ℕ) : localRecords header e v.val start rs = localRecords header' e v.val start rs := by
+ funext j
+ simp only [localRecords, siteRecordBlock, initRecord, hheader]
+ obtain ⟨hin, hout⟩ := hm.cuts initial
+ simp only [Validator]
+ rw [hin, hout, hrecords]
+ exact and_congr_right' (memoryAt_congr hm _)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorPaths.lean b/lean/OAI/Computability/VPVNP/RAMValidatorPaths.lean
new file mode 100644
index 0000000000..f3d943b92b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorPaths.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.RAMValidatorWork
+import OAI.Computability.VPVNP.RAMPathCount
+
+/-!
+# Private binary multiplicity of the executable site validator
+
+A successful site's raw choice string is exactly the concatenation of its
+branch bits and its guessed words. Hence one genuine computation path
+contributes once to the sum over shared bits of the product of local counts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM
+
+open BurstRAM RAMLayout RAMMemory
+
+variable {w p r k d e : ℕ}
+
+/-- An accepting binary branch path for a fixed local input. -/
+abbrev Machine.IncidentPaths (M : Machine w p r k) (fuel : ℕ) (initial header : Word w)
+ (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (v : Fin (2^d)) (inc : Fin (width d (2^e) w) → Bool) :=
+ {bs : List Bool // (M.validateIncident fuel initial header hw hc v inc bs).1.isSome = true}
+
+/-- Reading and emitting the successful report is inverse to choosing its
+specified bits. Distinct original binary branches remain distinct even when
+their continuations coincide. -/
+def Machine.incidentPathEquiv (M : Machine w p r k) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (bits : RawAssignment d e w)
+ (v : Fin (2^d)) :
+ M.IncidentPaths fuel initial (header v) hw hc v (BurstRAM.incidentBits bits v) ≃
+ SitePaths M.program fuel initial header hw hc bits v := by
+ let run := fun bs => (M.validateIncident fuel initial (header v) hw hc v (BurstRAM.incidentBits bits v) bs).1
+ let enc := fun (rs : List (Report w)) => rs.flatMap (fun r => guessBits r.events)
+ have spec (bs rs) : run bs = some rs ↔ BitValidator M.program fuel initial header hw hc bits v rs ∧ bs = enc rs :=
+ M.validateIncident_iff ..
+ refine ⟨fun b => ⟨(run b.val).get b.property, ((spec ..).mp (Option.some_get b.property).symm).1⟩,
+ fun s => ⟨enc s.val, Option.isSome_iff_exists.mpr ⟨s.val, (spec ..).mpr ⟨s.property, rfl⟩⟩⟩,
+ ?_, ?_⟩
+ · intro b
+ exact Subtype.ext ((spec ..).mp (Option.some_get b.property).symm).2.symm
+ · intro s
+ apply Subtype.ext
+ apply Option.some.inj
+ exact (Option.some_get _).trans ((spec ..).mpr ⟨s.property, rfl⟩)
+
+/-- Native capped path count expressed using the actual site machines and
+their own private choice strings. -/
+theorem Machine.parsimoniousIncidentPaths (M : Machine w p r k) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) :
+ Nat.card (ActualPaths M.program fuel initial (initialMemory (2^d) header) (withinCaps (2^d) (2^e))) =
+ ∑ bits : RawAssignment d e w, ∏ v : Fin (2^d),
+ Nat.card (M.IncidentPaths fuel initial (header v) hw hc v (BurstRAM.incidentBits bits v)) := by
+ rw [parsimoniousRAMTranscripts M.program fuel initial header hw hc]
+ exact Finset.sum_congr rfl fun b _ => Finset.prod_congr rfl fun v _ =>
+ (Nat.card_congr (M.incidentPathEquiv fuel initial header hw hc b v)).symm
+
+end BurstRAM.PrivateRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorPost.lean b/lean/OAI/Computability/VPVNP/RAMValidatorPost.lean
new file mode 100644
index 0000000000..bbc309eefe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorPost.lean
@@ -0,0 +1,80 @@
+import OAI.Computability.VPVNP.RAMValidatorRecords
+import OAI.Computability.VPVNP.RAMValidatorSuccessor
+import OAI.Computability.VPVNP.RAMValidatorBoundary
+import OAI.Computability.VPVNP.RAMSortScanMessages
+
+/-!
+# Deterministic memory pass of the site validator
+
+After a successful bucket simulation, the site fills its sorting buffer from
+its header and the returned reports. It runs the bitonic layers on the incident
+bit vector and checks every read and the outgoing last physical slot.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMLayout RAMSort RAMMemory
+
+variable {d e w : ℕ}
+
+/-- This computation accesses just the local header, reports, and incident
+array. Its result includes the work on malformed sorting fields. -/
+def checkSiteMemory (hw : 2 ≤ w) (v : Fin (2^d)) (header : Word w) (raw : ℕ → Bool)
+ (edges : SiteSuccessors w) (rs : List (Report w)) : Bool × ℕ :=
+ let records := recordBuffer e v.val header edges.input.cost rs
+ let sorted := scanSort hw raw v records.1
+ let boundary := RAMBoundary.scan edges.received
+ (if v.val+1 < 2^d then some edges.sent else none) (fun i => (sorted.block i).record)
+ (sorted.ok && boundary.1, records.2 + sorted.steps + boundary.2 + 8)
+
+theorem checkSiteMemory_iff (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (a : SendArrays d (2^e) w)
+ (v : Fin (2^d)) (header : ℕ → Word w) (initial : Word w) (edges : SiteSuccessors w)
+ (he : edges.Spec hw hc initial v a) (rs : List (Report w)) :
+ (checkSiteMemory (e := e) hw v (header v) (sortIncident a v) edges rs).1 = true ↔
+ SortCanonical hw hc a v ∧ MemoryAt (unpackMessages (parseMessages hw hc a)).memory v
+ (localRecords header e v.val edges.input.cost rs) := by
+ let records := localRecords header e v.val edges.input.cost rs
+ let m := (unpackMessages (parseMessages hw hc a)).memory
+ let sorted := scanStages hw (sortIncident a v) v (phases ((2+e)+d) ((2+e)+d) le_rfl) records
+ simp only [checkSiteMemory, recordBuffer_data, Bool.and_eq_true, scanSort_ok, scanSort_block, he.received_eq, he.sent_eq]
+ change (sorted.ok = true ∧ _) ↔ SortCanonical hw hc a v ∧ MemoryAt m v records
+ rw [sortScan_messages hw hc a v records, RAMBoundary.scan_spec (Nat.two_pow_pos _)]
+ constructor
+ · rintro ⟨⟨hcan, hsort⟩, hbound⟩
+ rw [sortScan_output hw hc a v records hcan] at hbound
+ exact ⟨hcan, hsort, hbound⟩
+ · rintro ⟨hcan, hsort, hbound⟩
+ rw [sortScan_output hw hc a v records hcan]
+ exact ⟨⟨hcan, hsort⟩, hbound⟩
+
+/-- The memory pass runs only after the bucket simulation succeeded. Its
+bound needs no validity hypothesis on the sorting or successor bits. -/
+theorem checkSiteMemory_work {C : Type*} {P : Program w C} {fuel : ℕ} (hw : 2 ≤ w)
+ (v : Fin (2^d)) (header : Word w) (raw : ℕ → Bool) (edges : SiteSuccessors w)
+ (rs : List (Report w)) (hs : SiteRun P fuel (2^d) (2^e) v.val edges.input rs) :
+ (checkSiteMemory (e := e) hw v header raw edges rs).2 ≤
+ 90 + (2 * 2^e) * (12 * fuel + 9) + 64 * (4 * 2^e) +
+ (((2+e)+d)+1).choose 2 * (4*2^e * (1024*(w+1)) + 9) := by
+ let records := recordBuffer e v.val header edges.input.cost rs
+ let sorted := scanSort hw raw v records.1
+ have hr := recordBuffer_work header hs
+ have hsort := scanSort_cost hw raw v records.1
+ have hb := RAMBoundary.scan_cost edges.received
+ (if v.val+1 < 2^d then some edges.sent else none) (fun i => (sorted.block i).record)
+ change records.2 ≤ _ at hr
+ change sorted.steps ≤ _ at hsort
+ rw [record_width] at hsort
+ conv_rhs at hb => rw [record_width]
+ change records.2 + sorted.steps + (RAMBoundary.scan edges.received
+ (if v.val+1 < 2^d then some edges.sent else none) (fun i => (sorted.block i).record)).2 + 8 ≤ _
+ omega
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorRecords.lean b/lean/OAI/Computability/VPVNP/RAMValidatorRecords.lean
new file mode 100644
index 0000000000..4dcc0c41ae
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorRecords.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.RAMTranscript
+import OAI.Computability.VPVNP.RAMFinite
+
+/-!
+# Materializing the site's initial sorting block
+
+The site reserves space for four slots per unit of bucket capacity and writes
+its header and probe records there in chronological order. Every event is
+visited once. The write pointer supplies the probe count of a completed call.
+Unwritten slots read as padding.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMMemory RAMSort
+
+variable {w : ℕ}
+
+private abbrev Buffer (w : ℕ) := Array (Record (Word w))
+
+/-- Append five words on a probe, leaving private instructions and choices out
+of the sorting block. The work includes the event test and loop control. -/
+private def appendEvents (start : ℕ) : ℕ → List (Event w) → Buffer w → Buffer w × ℕ
+ | _, [], buf => (buf, 1)
+ | j, .read a x :: es, buf =>
+ let next := appendEvents start (j + 1) es (buf.push ⟨.read, a.val, x, start, j⟩)
+ (next.1, 12 + next.2)
+ | j, .write a x :: es, buf =>
+ let next := appendEvents start (j + 1) es (buf.push ⟨.write, a.val, x, start, j⟩)
+ (next.1, 12 + next.2)
+ | j, _ :: es, buf =>
+ let next := appendEvents start j es buf
+ (next.1, 4 + next.2)
+
+private theorem appendEvents_data (start j : ℕ) (es : List (Event w)) (buf : Buffer w) :
+ (appendEvents start j es buf).1.toList = buf.toList ++ eventRecords start j es := by
+ induction es generalizing j buf with
+ | nil => simp [appendEvents, eventRecords]
+ | cons e es ih => cases e <;> simp [appendEvents, eventRecords, ih, List.append_assoc]
+
+private theorem appendEvents_work (start j : ℕ) (es : List (Event w)) (buf : Buffer w) :
+ (appendEvents start j es buf).2 ≤ 12 * es.length + 1 := by
+ induction es generalizing j buf with
+ | nil => simp [appendEvents]
+ | cons e es ih =>
+ cases e <;> simp only [appendEvents, List.length_cons, Nat.mul_add] <;>
+ apply le_trans (Nat.add_le_add_left (ih _ _) _) <;> omega
+
+private def appendCalls : ℕ → List (Report w) → Buffer w → Buffer w × ℕ
+ | _, [], buf => (buf, 1)
+ | start, r :: rs, buf =>
+ let step := appendEvents start 0 r.events buf
+ let next := appendCalls (start + (1 + (step.1.size - buf.size))) rs step.1
+ (next.1, 8 + step.2 + next.2)
+
+private theorem appendCalls_data (start : ℕ) (rs : List (Report w)) (buf : Buffer w) :
+ (appendCalls start rs buf).1.toList = buf.toList ++ probeRecords start rs := by
+ induction rs generalizing start buf with
+ | nil => simp [appendCalls, probeRecords]
+ | cons r rs ih =>
+ have h := congrArg List.length (appendEvents_data start 0 r.events buf)
+ simp only [Array.length_toList, List.length_append, length_eventRecords] at h
+ simp [appendCalls, ih, appendEvents_data, h, Report.probes, probeRecords, List.append_assoc]
+
+private theorem appendCalls_work (start fuel : ℕ) (rs : List (Report w)) (buf : Buffer w)
+ (hs : ∀ r ∈ rs, r.events.length < fuel) :
+ (appendCalls start rs buf).2 ≤ rs.length * (12 * fuel + 9) + 1 := by
+ induction rs generalizing start buf with
+ | nil => simp [appendCalls]
+ | cons r rs ih =>
+ simp only [List.forall_mem_cons] at hs
+ have he := appendEvents_work start 0 r.events buf
+ simp only [appendCalls, List.length_cons, Nat.add_mul, Nat.one_mul]
+ have hr := ih (start + (1 + ((appendEvents start 0 r.events buf).1.size - buf.size)))
+ (appendEvents start 0 r.events buf).1 hs.2
+ omega
+
+/-- The array view uses a single constant-time indexed lookup. Missing slots
+have the same zero-padding meaning as the full length-`4H` representation. -/
+def recordBuffer (e v : ℕ) (header : Word w) (start : ℕ) (rs : List (Report w)) :
+ Wires (2 + e) (OrderedSlot (Word w)) × ℕ :=
+ let init := (Array.emptyWithCapacity (4 * 2 ^ e)).push (initRecord (fun _ => header) v)
+ let result := appendCalls start rs init
+ (fun j => ⟨result.1[j.val]?⟩, 16 + result.2)
+
+private theorem get_padded {α : Type*} (l : List α) (k j : ℕ) :
+ (l.map some ++ List.replicate k none)[j]?.getD none = l[j]? := by
+ by_cases hj : j < l.length
+ · rw [List.getElem?_append_left (by simpa using hj), List.getElem?_map,
+ List.getElem?_eq_getElem hj]
+ rfl
+ · rw [List.getElem?_append_right (by simpa using Nat.le_of_not_gt hj),
+ List.getElem?_eq_none (Nat.le_of_not_gt hj)]
+ by_cases hk : j - l.length < k <;> simp [hk]
+
+theorem recordBuffer_data (e v : ℕ) (header : ℕ → Word w) (start : ℕ) (rs : List (Report w)) :
+ (recordBuffer e v (header v) start rs).1 = localRecords header e v start rs := by
+ funext j
+ apply congrArg OrderedSlot.mk
+ unfold siteRecordBlock
+ rw [← Array.getElem?_toList, appendCalls_data, get_padded]
+ rfl
+
+/-- On all report lists returned by the site, the single-pass collection takes
+at most a constant number of word operations per simulated instruction. -/
+theorem recordBuffer_work {C : Type*} {P : Program w C} {fuel S e v : ℕ}
+ {input : Cut w} {rs : List (Report w)} (header : Word w)
+ (hs : SiteRun P fuel S (2 ^ e) v input rs) :
+ (recordBuffer e v header input.cost rs).2 ≤ 17 + (2 * 2 ^ e) * (12 * fuel + 9) := by
+ obtain ⟨hl, he⟩ := boundedReports_of_localSegment hs.calls (hs.cost_lt (Nat.two_pow_pos e)).le
+ have h := appendCalls_work input.cost fuel rs
+ ((Array.emptyWithCapacity (4 * 2 ^ e)).push (initRecord (fun _ => header) v)) he
+ have hr := Nat.mul_le_mul_right (12 * fuel + 9) hl
+ dsimp only [recordBuffer]
+ omega
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorSuccessor.lean b/lean/OAI/Computability/VPVNP/RAMValidatorSuccessor.lean
new file mode 100644
index 0000000000..f409f058b7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorSuccessor.lean
@@ -0,0 +1,234 @@
+import OAI.Computability.VPVNP.RAMBitTranscript
+import OAI.Computability.VPVNP.RAMSuccessorDecodeCost
+
+/-!
+# Reading both successor fields at a site
+
+The two eight-word fields occupy the first `16*w` incident bits in Lemma 10.1.
+On an internal edge the site parses and checks the candidate successor. On a
+missing edge it checks the zero clamp. The initial site supplies its own start
+state, and the terminal site has no target cut. The same fields supply the
+two records used in the predecessor check after sorting.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMMemory RAMLayout RAMSerialization
+
+variable {d e w : ℕ}
+
+/-- Read the contiguous field at base address `8*w*dir`. -/
+def successorField (w : ℕ) (raw : ℕ → Bool) (dir : Fin 2) : Fin (8 * w) → Bool :=
+ fun j ↦ raw (8 * w * dir.val + j.val)
+
+private def zeroPrefix {n : ℕ} (b : Fin n → Bool) : (k : ℕ) → k ≤ n → Bool × ℕ
+ | 0, _ => (true, 1)
+ | k+1, hk =>
+ if b ⟨k, hk⟩ then (false, 6)
+ else
+ let next := zeroPrefix b k (by omega)
+ (next.1, 6 + next.2)
+
+private theorem zeroPrefix_spec {n : ℕ} (b : Fin n → Bool) (k : ℕ) (hk : k ≤ n) :
+ (zeroPrefix b k hk).1 = true ↔ ∀ i : Fin n, i.val < k → b i = false := by
+ induction k with
+ | zero => simp [zeroPrefix]
+ | succ k ih =>
+ cases h : b ⟨k, hk⟩ with
+ | true =>
+ simp only [zeroPrefix, h, ↓reduceIte, Bool.false_eq_true, false_iff]
+ exact fun hall ↦ Bool.noConfusion (h.symm.trans (hall ⟨k, hk⟩ (by simp)))
+ | false =>
+ simp only [zeroPrefix, h, Bool.false_eq_true, ↓reduceIte, ih]
+ constructor
+ · intro hall i hi
+ rcases Nat.lt_or_eq_of_le (Nat.le_of_lt_succ hi) with hi | hi
+ · exact hall i hi
+ · exact (Fin.ext hi : i = ⟨k, hk⟩) ▸ h
+ · exact fun hall i hi ↦ hall i (Nat.lt_succ_of_lt hi)
+
+private theorem zeroPrefix_all {n : ℕ} (b : Fin n → Bool) :
+ (zeroPrefix b n le_rfl).1 = true ↔ b = fun _ ↦ false := by
+ rw [zeroPrefix_spec]
+ exact ⟨fun h ↦ funext fun i ↦ h i i.isLt, fun h i _ ↦ congrFun h i⟩
+
+private theorem zeroPrefix_steps {n : ℕ} (b : Fin n → Bool) (k : ℕ) (hk : k ≤ n) :
+ (zeroPrefix b k hk).2 ≤ 6 * k + 1 := by
+ induction k with
+ | zero => rfl
+ | succ k ih =>
+ have := ih (by omega)
+ rw [zeroPrefix]
+ split <;> dsimp <;> omega
+
+private structure EdgeRead (w cap : ℕ) where
+ value : Option (Successor w cap)
+ valid : Bool
+ steps : ℕ
+
+/-- Computing the base costs two multiplications. Each decoder bit read adds
+the base to its within-field offset. In the zero test this addition is already
+included in the six operations per iteration (test, decrement, address, load,
+branch on bit, loop branch). The four fixed operations cover base setup,
+dispatch and return. -/
+private def readEdge {cap : ℕ} (hw : 2 ≤ w) (hc : cap < 2 ^ w) (raw : ℕ → Bool)
+ (dir : Fin 2) (present : Bool) : EdgeRead w cap :=
+ let bits := successorField w raw dir
+ if present then
+ let decoded := scanSuccessor hw hc bits
+ ⟨some decoded.1.1, decoded.1.2, decoded.2 + 8 * w + 4⟩
+ else
+ let check := zeroPrefix bits (8 * w) le_rfl
+ ⟨none, check.1, check.2 + 4⟩
+
+private theorem readEdge_cost {cap : ℕ} (hw : 2 ≤ w) (hc : cap < 2 ^ w)
+ (raw : ℕ → Bool) (dir : Fin 2) (present : Bool) :
+ (readEdge hw hc raw dir present).steps ≤ 236 * (w+1) := by
+ cases present
+ · have := zeroPrefix_steps (successorField w raw dir) _ le_rfl
+ simp only [readEdge, Bool.false_eq_true, ↓reduceIte]
+ omega
+ · have := scanSuccessor_cost hw hc (successorField w raw dir)
+ simp only [readEdge, ↓reduceIte]
+ omega
+
+private def successorCut {cap : ℕ} (s : Successor w cap) : Cut w :=
+ ⟨s.cost.val, s.state⟩
+
+private def successorRecord {cap : ℕ} (s : Successor w cap) : Option (Record (Word w)) :=
+ s.lastRecord.map WordRecord.record
+
+/-- The parts of the successor fields needed before and after the local sort. -/
+structure SiteSuccessors (w : ℕ) where
+ /-- Incoming cumulative cost and persistent state for the site, using the prescribed initial
+ cut at the first site. -/
+ input : Cut w
+ /-- Outgoing successor cut when the site has a following processor in the chain. -/
+ output : Option (Cut w)
+ /-- Predecessor's final record recovered from the incoming successor field for the boundary
+ check. -/
+ received : Option (Record (Word w))
+ /-- Final record carried by the site's outgoing successor field and checked against its local
+ record sequence. -/
+ sent : Option (Record (Word w))
+ /-- Whether both successor fields pass their decoding checks, including the zero clamp where
+ an edge is absent. -/
+ valid : Bool
+
+/-- Check both fields even on malformed input. The fixed allowance covers
+site endpoint tests, copies of the selected cut and record registers, and
+combining the two success flags. -/
+def scanSuccessors (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (initial : Word w) (v : Fin (2^d))
+ (raw : ℕ → Bool) : SiteSuccessors w × ℕ :=
+ let inc := readEdge hw hc raw 1 (decide (0 < v.val))
+ let out := readEdge hw hc raw 0 (decide (v.val + 1 < 2^d))
+ (⟨(inc.value.map successorCut).getD ⟨0, some initial⟩, out.value.map successorCut,
+ inc.value.bind successorRecord, out.value.bind successorRecord, out.valid && inc.valid⟩,
+ inc.steps + out.steps + 32)
+
+/-- A uniform bound on raw incident arrays, including nonzero end fields
+and unrecognized tags. -/
+theorem scanSuccessors_cost (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (initial : Word w)
+ (v : Fin (2^d)) (raw : ℕ → Bool) :
+ (scanSuccessors hw hc initial v raw).2 ≤ 512 * (w+1) := by
+ simp only [scanSuccessors]
+ have := readEdge_cost hw hc raw 1 (decide (0 < v.val))
+ have := readEdge_cost hw hc raw 0 (decide (v.val + 1 < 2^d))
+ omega
+
+/-- The first conjunct of the outgoing encoding check. -/
+def SuccessorSendOK (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (a : SendArrays d (2^e) w)
+ (v : Fin (2^d)) : Prop :=
+ if h : v.val + 1 < 2^d then
+ a.1 ⟨v.val, by omega⟩ = (messageBits hw hc (parseMessages hw hc a)).1 ⟨v.val, by omega⟩
+ else True
+
+/-- The first conjunct of the incoming encoding check. -/
+def SuccessorReceiveOK (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (a : SendArrays d (2^e) w)
+ (v : Fin (2^d)) : Prop :=
+ if h : 0 < v.val then
+ a.1 ⟨v.val - 1, by have := v.isLt; omega⟩ =
+ (messageBits hw hc (parseMessages hw hc a)).1 ⟨v.val - 1, by have := v.isLt; omega⟩
+ else True
+
+private theorem successorField_at (raw : ℕ → Bool) (a : SendArrays d (2^e) w)
+ (v : Fin (2^d)) (hraw : ∀ slot, raw (offset d (2^e) w slot).val =
+ (incidentEquiv d (2^e) w a).val (v, slot)) (dir : Fin 2) (j : Fin (8*w)) :
+ successorField w raw dir j = (incidentEquiv d (2^e) w a).val (v, .inl (dir, j)) := by
+ simpa [successorField, offset_successor] using hraw (.inl (dir, j))
+
+private theorem send_read_spec (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) (raw : ℕ → Bool)
+ (hraw : ∀ slot, raw (offset d (2^e) w slot).val = (incidentEquiv d (2^e) w a).val (v,slot)) :
+ let out := readEdge hw hc raw 0 (decide (v.val + 1 < 2^d))
+ (out.value = if h : v.val + 1 < 2^d then some ((parseMessages hw hc a).1 ⟨v.val, by omega⟩)
+ else none) ∧ (out.valid = true ↔ SuccessorSendOK hw hc a v) := by
+ by_cases hv : v.val + 1 < 2^d
+ · let edge : Fin (2^d-1) := ⟨v.val, by omega⟩
+ have he : successorField w raw 0 = a.1 edge := funext fun j ↦
+ (successorField_at raw a v hraw 0 j).trans (incident_send a (.inl (edge, j)))
+ simp only [hv, decide_true, readEdge, ↓reduceIte, ↓reduceDIte, he, scanSuccessor_value,
+ scanSuccessor_valid, SuccessorSendOK]
+ exact ⟨rfl, Iff.rfl⟩
+ · have he : successorField w raw 0 = fun _ ↦ false := funext fun j ↦
+ (successorField_at raw a v hraw 0 j).trans (incident_clamp a _ (peer_send_end v (by
+ have := v.isLt; omega) j))
+ simp [hv, readEdge, he, zeroPrefix_all, SuccessorSendOK]
+
+private theorem receive_read_spec (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (a : SendArrays d (2^e) w) (v : Fin (2^d)) (raw : ℕ → Bool)
+ (hraw : ∀ slot, raw (offset d (2^e) w slot).val = (incidentEquiv d (2^e) w a).val (v,slot)) :
+ let inc := readEdge hw hc raw 1 (decide (0 < v.val))
+ (inc.value = if h : 0 < v.val then
+ some ((parseMessages hw hc a).1 ⟨v.val-1, by have := v.isLt; omega⟩) else none) ∧
+ (inc.valid = true ↔ SuccessorReceiveOK hw hc a v) := by
+ by_cases hv : 0 < v.val
+ · let edge : Fin (2^d-1) := ⟨v.val-1, by have := v.isLt; omega⟩
+ have he : successorField w raw 1 = a.1 edge := funext fun j ↦
+ (successorField_at raw a v hraw 1 j).trans (incident_receive_successor a v hv j)
+ simp only [hv, decide_true, readEdge, ↓reduceIte, ↓reduceDIte, he, scanSuccessor_value,
+ scanSuccessor_valid, SuccessorReceiveOK]
+ exact ⟨rfl, Iff.rfl⟩
+ · have he : successorField w raw 1 = fun _ ↦ false := funext fun j ↦
+ (successorField_at raw a v hraw 1 j).trans (incident_clamp a _ (peer_receive_start v (by omega) j))
+ simp [hv, readEdge, he, zeroPrefix_all, SuccessorReceiveOK]
+
+/-- Match both cut registers, both record registers and the validity flag
+to the typed site validator on its incident shared-bit assignment. -/
+structure SiteSuccessors.Spec (s : SiteSuccessors w) (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w)
+ (initial : Word w) (v : Fin (2^d)) (a : SendArrays d (2^e) w) : Prop where
+ input_eq : s.input = inputCut ⟨0, some initial⟩ (unpackMessages (parseMessages hw hc a)).chain v
+ output_eq : s.output = outputCut (unpackMessages (parseMessages hw hc a)).chain v
+ received_eq : s.received = RAMBoundary.receive (unpackMessages (parseMessages hw hc a)).memory.lastRecords v
+ sent_eq : s.sent = RAMBoundary.outgoing (unpackMessages (parseMessages hw hc a)).memory.lastRecords v
+ valid_iff : s.valid = true ↔ SuccessorSendOK hw hc a v ∧ SuccessorReceiveOK hw hc a v
+
+theorem scanSuccessors_spec (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (initial : Word w)
+ (v : Fin (2^d)) (raw : ℕ → Bool) (a : SendArrays d (2^e) w)
+ (hraw : ∀ slot, raw (offset d (2^e) w slot).val = (incidentEquiv d (2^e) w a).val (v,slot)) :
+ (scanSuccessors hw hc initial v raw).1.Spec hw hc initial v a := by
+ obtain ⟨hout, hvalidOut⟩ := send_read_spec hw hc a v raw hraw
+ obtain ⟨hin, hvalidIn⟩ := receive_read_spec hw hc a v raw hraw
+ constructor
+ · simp only [scanSuccessors, hin, inputCut]
+ by_cases hv : 0 < v.val
+ · simp [hv, Nat.ne_of_gt hv, successorCut, unpackMessages]
+ · simp [show v.val = 0 by omega]
+ · simp only [scanSuccessors, hout, outputCut]
+ split <;> rfl
+ · simp only [scanSuccessors, hin]
+ rcases v with ⟨i, hi⟩
+ cases i <;> rfl
+ · simp only [scanSuccessors, hout, RAMBoundary.outgoing]
+ split <;> rfl
+ · simp only [scanSuccessors, Bool.and_eq_true, hvalidOut, hvalidIn]
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMValidatorWork.lean b/lean/OAI/Computability/VPVNP/RAMValidatorWork.lean
new file mode 100644
index 0000000000..5e9443f429
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMValidatorWork.lean
@@ -0,0 +1,164 @@
+import OAI.Computability.VPVNP.RAMValidatorBucket
+import OAI.Computability.VPVNP.RAMValidatorPost
+import OAI.Computability.VPVNP.RAMBitLocality
+import OAI.Computability.VPVNP.RAMClock
+
+/-!
+# The executable single-site RAM transcript validator
+
+Each processor receives its own header word, a contiguous vector of incident
+link bits, and a private binary branch path. It checks the two successor
+fields, simulates the site's burst calls, and runs the local bitonic sorting
+and memory boundary checks. The returned report sequence identifies the
+successful path exactly, including coincident branches.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM
+
+open BurstRAM RAMLayout RAMSort
+
+variable {w p r k d e : ℕ}
+
+/-- Apply the memory checks only to a successful bucket, preserving the work
+already incurred when a malformed bit or unsuccessful call caused rejection. -/
+private def afterBucket (hw : 2 ≤ w) (v : Fin (2^d)) (header : Word w) (raw : ℕ → Bool)
+ (edges : SiteSuccessors w) (bucket : Option (List (Report w))) :
+ Option (List (Report w)) × ℕ :=
+ match bucket with
+ | none => (none, 2)
+ | some rs =>
+ let check := checkSiteMemory (e := e) hw v header raw edges rs
+ (if check.1 then some rs else none, check.2 + 4)
+
+private theorem afterBucket_iff (hw : 2 ≤ w) (v : Fin (2^d)) (header : Word w) (raw : ℕ → Bool)
+ (edges : SiteSuccessors w) (bucket : Option (List (Report w))) (rs : List (Report w)) :
+ (afterBucket (e := e) hw v header raw edges bucket).1 = some rs ↔
+ bucket = some rs ∧ (checkSiteMemory (e := e) hw v header raw edges rs).1 = true := by
+ cases bucket with
+ | none => simp [afterBucket]
+ | some t =>
+ by_cases he : t = rs
+ · subst t
+ simp [afterBucket]
+ · simp [afterBucket, he]
+
+/-- The interpreter's only inputs depending on the instance at other sites are
+the bits delivered at this site's physical ports. -/
+def Machine.validateIncident (M : Machine w p r k) (fuel : ℕ) (initial header : Word w)
+ (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (v : Fin (2^d))
+ (inc : Fin (width d (2^e) w) → Bool) (choices : List Bool) : Option (List (Report w)) × ℕ :=
+ let raw := readIncident inc
+ let edges := scanSuccessors hw hc initial v raw
+ if edges.1.valid then
+ let bucket := M.runBucket fuel (2^d) (2^e) v.val edges.1.input edges.1.output choices
+ let post := afterBucket (e := e) hw v header raw edges.1 bucket.1
+ (post.1, edges.2 + bucket.2 + post.2 + 8)
+ else (none, edges.2 + 4)
+
+private theorem physical_iff (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (a : SendArrays d (2^e) w)
+ (v : Fin (2^d)) :
+ (SuccessorSendOK hw hc a v ∧ SuccessorReceiveOK hw hc a v) ∧ SortCanonical hw hc a v ↔
+ OutgoingOK hw hc a v ∧ IncomingOK hw hc a v := by
+ constructor
+ · rintro ⟨⟨hs, hr⟩, hsort⟩
+ exact ⟨⟨hs, fun l => (hsort l).1⟩, hr, fun l => (hsort l).2⟩
+ · rintro ⟨⟨hs, hso⟩, hr, hro⟩
+ exact ⟨⟨hs, hr⟩, fun l => ⟨hso l, hro l⟩⟩
+
+/-- On an arbitrary shared assignment, one local binary string accepts with
+the given reports precisely when the physical bit validator accepts them and
+the string contains exactly the choices and read guesses of those reports. -/
+theorem Machine.validateIncident_iff (M : Machine w p r k) (fuel : ℕ) (initial : Word w)
+ (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (bits : RawAssignment d e w)
+ (v : Fin (2^d)) (choices : List Bool) (rs : List (Report w)) :
+ (M.validateIncident fuel initial (header v) hw hc v (BurstRAM.incidentBits bits v) choices).1 = some rs ↔
+ BitValidator M.program fuel initial header hw hc bits v rs ∧
+ choices = rs.flatMap (fun r => guessBits r.events) := by
+ let a := sendArraysEquiv d (2^e) w bits
+ let raw := sortIncident a v
+ let edges := scanSuccessors hw hc initial v raw
+ have he := scanSuccessors_spec hw hc initial v raw a (sortIncident_offset a v)
+ let m := unpackMessages (parseMessages hw hc a)
+ change edges.1.Spec hw hc initial v a at he
+ change (if edges.1.valid then _ else (none, edges.2 + 4)).1 = some rs ↔ _
+ by_cases hv : edges.1.valid = true
+ · rw [ite_eq_left hv]
+ dsimp only
+ rw [afterBucket_iff, Machine.runBucket_iff M (Nat.two_pow_pos e)]
+ change ((SiteCheck M.program fuel (2^d) (2^e) v.val edges.1.input edges.1.output rs ∧
+ choices = rs.flatMap (fun r => guessBits r.events)) ∧
+ (checkSiteMemory (e := e) hw v (header v) (sortIncident a v) edges.1 rs).1 = true) ↔ _
+ rw [checkSiteMemory_iff hw hc a v header initial edges.1 he rs]
+ rw [he.input_eq, he.output_eq]
+ obtain ⟨hs, hr⟩ := he.valid_iff.mp hv
+ constructor
+ · rintro ⟨⟨hb, hbits⟩, hsort, hmem⟩
+ exact ⟨⟨(physical_iff hw hc a v).mp ⟨⟨hs, hr⟩, hsort⟩, hb, hmem⟩, hbits⟩
+ · rintro ⟨⟨hcan, hb, hmem⟩, hbits⟩
+ exact ⟨⟨hb, hbits⟩, ((physical_iff hw hc a v).mpr hcan).2, hmem⟩
+ · rw [ite_eq_right hv]
+ constructor
+ · intro h; cases h
+ · rintro ⟨⟨hcan, _⟩, _⟩
+ exact (hv (he.valid_iff.mpr ((physical_iff hw hc a v).mpr hcan).1)).elim
+
+private theorem overhead_le (k w H fuel : ℕ) :
+ 102 + (2*H)*(12*fuel+9) + 64*(4*H) + 48 + 256*(H+1)*(fuel+1)*(fuel+1)*(w+2) +
+ (2*H)*(16*fuel+16) ≤ 2048*(H+1)*(fuel+1)*(fuel+1)*(w+k+2) := by
+ ring_nf
+ omega
+
+/-- All received vectors and private bit streams meet the same bound,
+including invalid control fields and rejected partial reads. -/
+theorem Machine.validateIncident_work (M : Machine w p r k) (fuel : ℕ) (initial header : Word w)
+ (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (v : Fin (2^d)) (inc : Fin (width d (2^e) w) → Bool)
+ (choices : List Bool) (hf : 2^e ≤ 2*fuel) :
+ (M.validateIncident fuel initial header hw hc v inc choices).2 ≤
+ transcriptWorkBound k w (2^e) ((2+e)+d) fuel := by
+ let raw := readIncident inc
+ let edges := scanSuccessors hw hc initial v raw
+ let bucket := M.runBucket fuel (2^d) (2^e) v.val edges.1.input edges.1.output choices
+ have he := scanSuccessors_cost hw hc initial v raw
+ change edges.2 ≤ _ at he
+ have hb := M.runBucket_work fuel (2^d) (2^e) v.val edges.1.input edges.1.output choices
+ (Nat.two_pow_pos e) hf
+ change bucket.2 ≤ _ at hb
+ have ho := overhead_le k w (2^e) fuel
+ unfold transcriptWorkBound
+ by_cases hv : edges.1.valid = true
+ · unfold Machine.validateIncident
+ rw [ite_eq_left hv]
+ change edges.2 + bucket.2 + (afterBucket (e := e) hw v header raw edges.1 bucket.1).2 + 8 ≤ _
+ cases hx : bucket.1 with
+ | none =>
+ change edges.2 + bucket.2 + 2 + 8 ≤ _
+ omega
+ | some rs =>
+ have hs := ((M.runBucket_iff (Nat.two_pow_pos e)).mp hx).1.1
+ have hm := checkSiteMemory_work hw v header raw edges.1 rs hs
+ change edges.2 + bucket.2 + ((checkSiteMemory (e := e) hw v header raw edges.1 rs).2 + 4) + 8 ≤ _
+ omega
+ · unfold Machine.validateIncident
+ rw [ite_eq_right hv]
+ change edges.2 + 4 ≤ _
+ omega
+
+/-- The paper's word-step cap for every path of the executable validator. -/
+theorem Machine.validateIncident_clock (M : Machine w p r k) (n u : ℕ) (initial header : Word w)
+ (hw : 2 ≤ w) (hc : 2^d * 2^e < 2^w) (v : Fin (2^d)) (inc : Fin (width d (2^e) w) → Bool)
+ (choices : List Bool) (hn : 2048 ≤ n) (hu : 1 ≤ u) (hk : k+2 ≤ n) (hw' : w ≤ n)
+ (hH : 2^e ≤ 2*n) (hstages : ((2+e)+d)+1 ≤ n) :
+ (M.validateIncident (n^u) initial header hw hc v inc choices).2 ≤ n^(10*u+30) := by
+ have hf : 2^e ≤ 2*n^u := hH.trans (Nat.mul_le_mul_left 2 (Nat.le_self_pow (by omega) n))
+ exact (M.validateIncident_work (n^u) initial header hw hc v inc choices hf).trans
+ (transcriptWorkBound_le_clock hn hk hw' hH hstages)
+
+end BurstRAM.PrivateRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMVirtualCeilLog.lean b/lean/OAI/Computability/VPVNP/RAMVirtualCeilLog.lean
new file mode 100644
index 0000000000..64557c7280
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMVirtualCeilLog.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.PrimedInputRAMFlowEval
+import Mathlib.Data.Nat.Log
+
+/-!
+# Ceiling logarithm in the private word RAM
+
+Each iteration replaces the operand by its rounded-up half. Registers zero and
+one hold the constants one and two. Registers two and three hold the operand
+and the iteration count. The terminal comparison is included in the cost.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.VirtualParameters
+
+open PrivateRAM PrimedInputRAM PrimedStackRAM
+
+variable {w k : ℕ}
+
+/-- The three arithmetic instructions between successive loop tests. -/
+private def clogStep : Flow 12 k :=
+ .seq (.line (.binary .add 2 2 0))
+ (.seq (.line (.binary .div 2 2 1)) (.line (.binary .add 3 3 0)))
+
+/-- Repeated rounded-up halving of register two, counting in register three. -/
+def clogLoop : Flow 12 k := .whileLt 0 2 clogStep
+
+private theorem clogRunAux (pub : Fin k → Word w) (state : Word w) (m : Memory w)
+ (x count : ℕ) (rs : Regs w 12) (hOne : (rs 0).val = 1) (hTwo : (rs 1).val = 2)
+ (hOperand : (rs 2).val = x) (hCounter : (rs 3).val = count)
+ (hx : x + 1 < 2 ^ w) (hc : count + Nat.clog 2 x < 2 ^ w) :
+ ∃ out, Flow.Exec pub state clogLoop rs m (List.replicate (4 * Nat.clog 2 x + 1) .tick) out m ∧
+ (out 2).val ≤ 1 ∧ (out 3).val = count + Nat.clog 2 x ∧
+ ∀ i : Fin 12, i ≠ 2 → i ≠ 3 → out i = rs i := by
+ induction x using Nat.strong_induction_on generalizing count rs with
+ | h x ih =>
+ by_cases h : x ≤ 1
+ · rw [Nat.clog_of_right_le_one h, Nat.add_zero]
+ exact ⟨rs, .whileDone (by change ¬ (rs 0).val < (rs 2).val; omega),
+ hOperand.trans_le h, hCounter, fun _ _ _ => rfl⟩
+ · let half := (x + 1) / 2
+ have hhalf : half < x := by dsimp [half]; omega
+ have hlog : Nat.clog 2 x = Nat.clog 2 half + 1 := by
+ rw [Nat.clog_of_two_le Nat.one_lt_two (by omega : 2 ≤ x)]
+ congr 2
+ let a := Function.update rs (2 : Fin 12) (BinaryOp.add.eval (rs 2) (rs 0))
+ let b := Function.update a (2 : Fin 12) (BinaryOp.div.eval (a 2) (a 1))
+ let next := Function.update b (3 : Fin 12) (BinaryOp.add.eval (b 3) (b 0))
+ have preserve (i : Fin 12) (h₂ : i ≠ 2) (h₃ : i ≠ 3) : next i = rs i := by
+ simp [next, b, a, Function.update_of_ne h₂, Function.update_of_ne h₃]
+ have ha : (a 2).val = x + 1 := by
+ rw [show a 2 = rs 2 + rs 0 by simp [a, BinaryOp.eval],
+ Fin.val_add_eq_of_add_lt (by omega), hOperand, hOne]
+ have haOne : (a 1).val = 2 := by simpa [a, Function.update_apply] using hTwo
+ have hquot : (BinaryOp.div.eval (a 2) (a 1)).val = (a 2).val / (a 1).val :=
+ Nat.mod_eq_of_lt ((Nat.div_le_self _ _).trans_lt (a 2).isLt)
+ have hnextOperand : (next 2).val = half := by
+ rw [show next 2 = BinaryOp.div.eval (a 2) (a 1) by simp [next, b],
+ hquot, ha, haOne]
+ have hbCount : (b 3).val = count := by simpa [b, a, Function.update_apply] using hCounter
+ have hbOne : (b 0).val = 1 := by simpa [b, a, Function.update_apply] using hOne
+ have hnextCount : (next 3).val = count + 1 := by
+ rw [show next 3 = b 3 + b 0 by simp [next, BinaryOp.eval],
+ Fin.val_add_eq_of_add_lt (by omega), hbCount, hbOne]
+ have step : Flow.Exec pub state clogStep rs m [.tick, .tick, .tick] next m :=
+ Flow.Exec.seq (.line (rs' := a) rfl)
+ (Flow.Exec.seq (.line (rs' := b) rfl) (.line (rs' := next) rfl))
+ obtain ⟨out, run, small, value, keep⟩ := ih half hhalf (count + 1) next
+ (by rw [preserve 0 (by decide) (by decide), hOne])
+ (by rw [preserve 1 (by decide) (by decide), hTwo])
+ hnextOperand hnextCount (by omega) (by omega)
+ refine ⟨out, ?_, small, by omega, fun i h₂ h₃ => (keep i h₂ h₃).trans (preserve i h₂ h₃)⟩
+ rw [show 4 * Nat.clog 2 x + 1 = (3 + (4 * Nat.clog 2 half + 1)) + 1 by omega,
+ List.replicate_succ, List.replicate_add]
+ exact Flow.Exec.whileStep (by change (rs 0).val < (rs 2).val; omega) step run
+
+/-- Starting at zero the counter returns the ceiling logarithm. The only events
+are ticks, and the loop retains every register except its operand and counter. -/
+theorem clogRun (pub : Fin k → Word w) (state : Word w) (m : Memory w)
+ (x : ℕ) (rs : Regs w 12) (hOne : (rs 0).val = 1) (hTwo : (rs 1).val = 2)
+ (hOperand : (rs 2).val = x) (hCounter : (rs 3).val = 0)
+ (hx : x + 1 < 2 ^ w) (hc : Nat.clog 2 x < 2 ^ w) :
+ ∃ out, Flow.Exec pub state clogLoop rs m (List.replicate (4 * Nat.clog 2 x + 1) .tick) out m ∧
+ (out 2).val ≤ 1 ∧ (out 3).val = Nat.clog 2 x ∧
+ ∀ i : Fin 12, i ≠ 2 → i ≠ 3 → out i = rs i := by
+ simpa using clogRunAux pub state m x 0 rs hOne hTwo hOperand hCounter hx (by simpa using hc)
+
+end BurstRAM.VirtualParameters
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMVirtualParameterBounds.lean b/lean/OAI/Computability/VPVNP/RAMVirtualParameterBounds.lean
new file mode 100644
index 0000000000..d9121b5e01
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMVirtualParameterBounds.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.RAMParameters
+
+/-!
+# Integer operands for the virtual site count
+
+Section 11 chooses the least power of two whose buckets cover the probe budget.
+Its address width can be computed from the live address width and the product of
+the input length with its ceiling logarithm. This computation keeps the live
+processor count in exponent form and fits in the prescribed machine words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+private theorem clog_two_pow_mul (r m : ℕ) (hm : 0 < m) :
+ Nat.clog 2 (2 ^ r * m) = r + Nat.clog 2 m := by
+ induction r with
+ | zero => simp
+ | succ r ih =>
+ have hp : 0 < 2 ^ r * m := Nat.mul_pos (Nat.two_pow_pos _) hm
+ rw [pow_succ, Nat.mul_right_comm, Nat.clog_of_two_le (by decide : 1 < 2) (by omega)]
+ rw [show (2 ^ r * m * 2 + 2 - 1) / 2 = 2 ^ r * m by omega, ih]
+ omega
+
+/-- The virtual address width, computed without forming the live processor count. -/
+theorem virtualSiteExponent_eq_add_sub (r n : ℕ) (hn : 2 ≤ n) :
+ virtualSiteExponent r n =
+ r + Nat.clog 2 (n * Nat.clog 2 n) - (Nat.clog 2 n + 3) / 4 := by
+ have hc := Nat.clog_pos (by decide : 1 < 2) hn
+ rw [virtualSiteExponent, Nat.mul_assoc, clog_two_pow_mul _ _ (Nat.mul_pos (by omega) hc),
+ roundedUp, pow_one, Nat.clog_pow_left]
+
+/-- The product whose logarithm supplies the extra address bits has at most
+twice the ceiling logarithm of the input length as its ceiling logarithm. -/
+theorem clog_length_mul_clog_le (n : ℕ) :
+ Nat.clog 2 (n * Nat.clog 2 n) ≤ 2 * Nat.clog 2 n := by
+ let c := Nat.clog 2 n
+ apply Nat.clog_le_of_le_pow
+ calc
+ n * c ≤ 2 ^ c * 2 ^ c := Nat.mul_le_mul (Nat.le_pow_clog Nat.one_lt_two _) Nat.lt_two_pow_self.le
+ _ = 2 ^ (2 * c) := by rw [← pow_add, two_mul]
+
+/-- At every input length the product and its increment, the sum of the two
+logarithmic counters, and the numerator for ceiling division by four fit in a
+live processor word. -/
+theorem virtualParameterOperands_lt {B : ℕ} (hB : 1 ≤ B) (n : ℕ) :
+ let r := addressWidth B n
+ let w := (r + 10) ^ 4
+ let c := Nat.clog 2 n
+ n * c + 1 < 2 ^ w ∧ r + Nat.clog 2 (n * c) < 2 ^ w ∧ c + 3 < 2 ^ w := by
+ let r := addressWidth B n
+ let w := (r + 10) ^ 4
+ let c := Nat.clog 2 n
+ have hcr : c ≤ r := Nat.le_mul_of_pos_left _ hB
+ have hw : 3 * r + 4 ≤ w := by
+ change 3 * r + 4 ≤ (r + 10) ^ 4
+ calc
+ _ ≤ (r + 10) ^ 2 := by nlinarith [Nat.zero_le (r * r)]
+ _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide : 2 ≤ 4)
+ have hpow := Nat.pow_le_pow_right (by decide : 0 < 2) (show 2 * c + 2 ≤ w by omega)
+ have hprod : n * c ≤ 2 ^ (2 * c) :=
+ (Nat.le_pow_clog Nat.one_lt_two _).trans
+ (Nat.pow_le_pow_right (by decide) (clog_length_mul_clog_le n))
+ have hmargin : 0 < 2 ^ (2 * c) := Nat.two_pow_pos _
+ rw [pow_add] at hpow
+ have hcount := clog_length_mul_clog_le n
+ change Nat.clog 2 (n * c) ≤ 2 * c at hcount
+ have hlarge : w < 2 ^ w := Nat.lt_two_pow_self
+ change n * c + 1 < 2 ^ w ∧ r + Nat.clog 2 (n * c) < 2 ^ w ∧ c + 3 < 2 ^ w
+ constructor
+ · norm_num1 at hpow
+ omega
+ · omega
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMVirtualParametersCode.lean b/lean/OAI/Computability/VPVNP/RAMVirtualParametersCode.lean
new file mode 100644
index 0000000000..a610b5f5ec
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMVirtualParametersCode.lean
@@ -0,0 +1,221 @@
+import OAI.Computability.VPVNP.RAMVirtualCeilLog
+import OAI.Computability.VPVNP.RAMVirtualParameterBounds
+import OAI.Computability.VPVNP.PrimedInputRAMOnce
+import OAI.Computability.VPVNP.PrimedStackRAMNodeTable
+
+/-!
+# Computing the virtual site count on the private word RAM
+
+The public words give the input length and live address width. Two ceiling
+logarithms suffice to compute the least virtual site count and its bucket
+size in Section 11. All iterations and arithmetic fit in a live word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.VirtualParameters
+
+open PrivateRAM PrimedInputRAM PrimedStackRAM
+
+variable {w k : ℕ}
+
+private def setup (pn pr : Fin k) : Flow 12 k :=
+ straight (.constant 0 1) [.constant 1 2, .publicWord 4 pn, .publicWord 5 pr, .copy 2 4, .constant 3 0]
+
+private def product : Flow 12 k :=
+ straight (.copy 6 3) [.binary .mul 2 4 6, .constant 3 0]
+
+private def finish : Flow 12 k :=
+ straight (.constant 7 3) [.binary .add 8 1 1, .binary .add 9 6 7, .binary .div 9 9 8,
+ .binary .add 10 5 3, .binary .sub 10 10 9, .binary .shiftLeft 7 0 9, .binary .shiftLeft 11 0 10]
+
+/-- Fixed finite instruction text, with the length and address-width public slots supplied by the caller. -/
+def program (pn pr : Fin k) : Flow 12 k :=
+ .seq (setup pn pr) (.seq clogLoop (.seq product (.seq clogLoop finish)))
+
+/-- Number of executed instructions, including the final test of each loop. -/
+def ticks (n : ℕ) : ℕ := 4 * Nat.clog 2 n + 4 * Nat.clog 2 (n * Nat.clog 2 n) + 19
+
+theorem ticks_le (n : ℕ) : ticks n ≤ 12 * Nat.clog 2 n + 19 := by
+ unfold ticks
+ have := clog_length_mul_clog_le n
+ omega
+
+/-- Integer parameters in the final register file, including both powers of two. -/
+structure Result (n r : ℕ) (out : Regs w 12) : Prop where
+ inputLength : (out 4).val = n
+ addressBits : (out 5).val = r
+ lengthLog : (out 6).val = Nat.clog 2 n
+ bucket : (out 7).val = 2 ^ roundedUp 1 4 n
+ four : (out 8).val = 4
+ bucketBits : (out 9).val = roundedUp 1 4 n
+ siteBits : (out 10).val = virtualSiteExponent r n
+ sites : (out 11).val = 2 ^ virtualSiteExponent r n
+
+private abbrev literal (w a : ℕ) : Word w := Fin.ofNat _ a
+
+private def load (pub : Fin k → Word w) (pn pr : Fin k) (rs : Regs w 12) : Regs w 12 :=
+ let fields : List (Fin 12 × Word w) := [(0, literal w 1), (1, literal w 2),
+ (4, pub pn), (5, pub pr), (2, pub pn), (3, literal w 0)]
+ fields.foldl (fun a j => Function.update a j.1 j.2) rs
+
+private def prepare (rs : Regs w 12) : Regs w 12 :=
+ Function.update (Function.update (Function.update rs (6 : Fin 12) (rs 3))
+ 2 (BinaryOp.mul.eval (rs 4) (rs 3))) 3 (literal w 0)
+
+private theorem power_value (one exp : Word w) (h : one.val = 1) (he : exp.val < w) :
+ (BinaryOp.shiftLeft.eval one exp).val = 2 ^ exp.val := by
+ have hfit : 2 ^ exp.val < 2 ^ w := Nat.pow_lt_pow_right Nat.one_lt_two he
+ simp [BinaryOp.eval, he, Nat.shiftLeft_eq, h, Nat.mod_eq_of_lt hfit]
+
+private def finishRegs (rs : Regs w 12) : Regs w 12 :=
+ let three := literal w 3
+ let four := BinaryOp.add.eval (rs 1) (rs 1)
+ let num := BinaryOp.add.eval (rs 6) three
+ let q := BinaryOp.div.eval num four
+ let sum := BinaryOp.add.eval (rs 5) (rs 3)
+ let width := BinaryOp.sub.eval sum q
+ let fields : List (Fin 12 × Word w) := [(7,three),(8,four),(9,num),(9,q),(10,sum),(10,width),
+ (7,BinaryOp.shiftLeft.eval (rs 0) q),(11,BinaryOp.shiftLeft.eval (rs 0) width)]
+ fields.foldl (fun a j => Function.update a j.1 j.2) rs
+
+private theorem finishValues (n r : ℕ) (hn : 2 ≤ n) (rs : Regs w 12)
+ (hOne : (rs 0).val = 1) (hTwo : (rs 1).val = 2)
+ (hnat : (rs 4).val = n) (hr : (rs 5).val = r) (hc : (rs 6).val = Nat.clog 2 n)
+ (hd : (rs 3).val = Nat.clog 2 (n * Nat.clog 2 n))
+ (hcr : Nat.clog 2 n ≤ r) (hwidth : 3 * r + 4 ≤ w)
+ (hnum : Nat.clog 2 n + 3 < 2 ^ w) (hsum : r + Nat.clog 2 (n * Nat.clog 2 n) < 2 ^ w) :
+ Result n r (finishRegs rs) := by
+ let three := literal w 3
+ let four := BinaryOp.add.eval (rs 1) (rs 1)
+ let num := BinaryOp.add.eval (rs 6) three
+ let q := BinaryOp.div.eval num four
+ let sum := BinaryOp.add.eval (rs 5) (rs 3)
+ let width := BinaryOp.sub.eval sum q
+ have hclog := Nat.clog_pos Nat.one_lt_two (by omega : 1 < n)
+ have hw := Nat.lt_two_pow_self (n := w)
+ have hthree : three.val = 3 := Nat.mod_eq_of_lt (by omega)
+ have hfour : four.val = 4 := by
+ change ((rs 1) + (rs 1)).val = 4
+ rw [Fin.val_add_eq_of_add_lt (by omega), hTwo]
+ have htop : num.val = Nat.clog 2 n + 3 := by
+ change (rs 6 + three).val = _
+ rw [Fin.val_add_eq_of_add_lt (by omega), hc, hthree]
+ have hq : q.val = (Nat.clog 2 n + 3) / 4 := by
+ have hdiv : q.val = num.val / four.val := Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt num.isLt)
+ rw [hdiv, htop, hfour]
+ have hval : sum.val = r + Nat.clog 2 (n * Nat.clog 2 n) := by
+ change (rs 5 + rs 3).val = _
+ rw [Fin.val_add_eq_of_add_lt (by omega), hr, hd]
+ have hb : q.val = roundedUp 1 4 n := by
+ rw [hq, roundedUp, pow_one, Nat.clog_pow_left]
+ have hd' : width.val = virtualSiteExponent r n := by
+ change (sum - q).val = _
+ rw [Fin.sub_val_of_le (show q ≤ sum by change q.val ≤ sum.val; omega), hval,
+ virtualSiteExponent_eq_add_sub _ _ hn, hq]
+ have hlim := clog_length_mul_clog_le n
+ have hqfit : q.val < w := by omega
+ have hdfit : width.val < w := by rw [hd', virtualSiteExponent_eq_add_sub _ _ hn]; omega
+ constructor
+ · exact hnat
+ · exact hr
+ · exact hc
+ · change (BinaryOp.shiftLeft.eval (rs 0) q).val = _
+ rw [power_value _ _ hOne hqfit, hb]
+ · exact hfour
+ · exact hb
+ · exact hd'
+ · change (BinaryOp.shiftLeft.eval (rs 0) width).val = _
+ rw [power_value _ _ hOne hdfit, hd']
+
+private theorem seqTicks {pub : Fin k → Word w} {state : Word w} {m : Memory w}
+ {a b : Flow 12 k} {rs mid out : Regs w 12} {j t : ℕ}
+ (ha : Flow.Exec pub state a rs m (List.replicate j .tick) mid m)
+ (hb : Flow.Exec pub state b mid m (List.replicate t .tick) out m) :
+ Flow.Exec pub state (.seq a b) rs m (List.replicate (j+t) .tick) out m := by
+ simpa only [List.replicate_add] using ha.seq hb
+
+/-- Executing the fixed word program computes the prescribed virtual parameters
+for each length at least two and each live address multiplier at least one. -/
+theorem programRun (pub : Fin k → Word w) (pn pr : Fin k) (state : Word w) (m : Memory w)
+ (rs : Regs w 12) (B n : ℕ) (hB : 1 ≤ B) (hn : 2 ≤ n)
+ (hw : w = (addressWidth B n + 10) ^ 4) (hnat : (pub pn).val = n)
+ (hr : (pub pr).val = addressWidth B n) :
+ ∃ out, Flow.Exec pub state (program pn pr) rs m (List.replicate (ticks n) .tick) out m ∧
+ Result n (addressWidth B n) out := by
+ let r := addressWidth B n
+ let c := Nat.clog 2 n
+ let d := Nat.clog 2 (n * c)
+ have hcr : c ≤ r := Nat.le_mul_of_pos_left _ hB
+ have hc : 0 < c := Nat.clog_pos Nat.one_lt_two (by omega)
+ have hwidth : 3 * r + 4 ≤ w := by
+ rw [hw]
+ calc
+ _ ≤ (r + 10)^2 := by nlinarith [Nat.zero_le (r * r)]
+ _ ≤ (r + 10)^4 := Nat.pow_le_pow_right (by omega) (by decide)
+ obtain ⟨hprod, hsum, hnum⟩ := virtualParameterOperands_lt hB n
+ change n * c + 1 < 2 ^ (r + 10) ^ 4 at hprod
+ change r + d < 2 ^ (r + 10) ^ 4 at hsum
+ change c + 3 < 2 ^ (r + 10) ^ 4 at hnum
+ change w = (r + 10) ^ 4 at hw
+ rw [← hw] at hprod hsum hnum
+ have hsmall : n + 1 < 2 ^ w := by have := Nat.le_mul_of_pos_right n hc; omega
+ let start := load pub pn pr rs
+ have hstart : Flow.Exec pub state (setup pn pr) rs m (List.replicate 6 .tick) start m :=
+ (Flow.once_sound pub state false _ rs m rfl).1
+ have h₀ : (start 0).val = 1 := Nat.mod_eq_of_lt (by omega)
+ have h₁ : (start 1).val = 2 := Nat.mod_eq_of_lt (by omega)
+ obtain ⟨a, run₁, _, count₁, keep₁⟩ := clogRun pub state m n start h₀ h₁ hnat
+ (show (start 3).val = 0 from Nat.zero_mod _) hsmall (by change c < 2 ^ w; omega)
+ have haOne := (congrArg Fin.val (keep₁ 0 (by decide) (by decide))).trans h₀
+ have haTwo := (congrArg Fin.val (keep₁ 1 (by decide) (by decide))).trans h₁
+ have haN : (a 4).val = n := (congrArg Fin.val (keep₁ 4 (by decide) (by decide))).trans hnat
+ have haR : (a 5).val = r := (congrArg Fin.val (keep₁ 5 (by decide) (by decide))).trans hr
+ let b := prepare a
+ have hmiddle : Flow.Exec pub state product a m (List.replicate 3 .tick) b m :=
+ (Flow.once_sound pub state false _ a m rfl).1
+ have hbProd : (b 2).val = n * c := by
+ change ((a 4).val * (a 3).val) % (2 ^ w) = n * c
+ rw [haN, count₁, Nat.mod_eq_of_lt (by change n * c < 2 ^ w; omega)]
+ obtain ⟨z, run₂, _, count₂, keep₂⟩ := clogRun pub state m (n*c) b haOne haTwo hbProd
+ (show (b 3).val = 0 from Nat.zero_mod _) hprod (by change d < 2 ^ w; omega)
+ have hend : Flow.Exec pub state finish z m (List.replicate 8 .tick) (finishRegs z) m :=
+ (Flow.once_sound pub state false _ z m rfl).1
+ refine ⟨finishRegs z, ?_, finishValues n r hn z ?_ ?_ ?_ ?_ ?_ count₂ hcr hwidth hnum hsum⟩
+ · change Flow.Exec pub state _ rs m (List.replicate (4*c+4*d+19) .tick) _ m
+ rw [show 4*c+4*d+19 = 6 + ((4*c+1) + (3 + ((4*d+1)+8))) by omega]
+ exact seqTicks hstart (seqTicks run₁ (seqTicks hmiddle (seqTicks run₂ hend)))
+ · exact (congrArg Fin.val (keep₂ 0 (by decide) (by decide))).trans haOne
+ · exact (congrArg Fin.val (keep₂ 1 (by decide) (by decide))).trans haTwo
+ · exact (congrArg Fin.val (keep₂ 4 (by decide) (by decide))).trans haN
+ · exact (congrArg Fin.val (keep₂ 5 (by decide) (by decide))).trans haR
+ · exact (congrArg Fin.val (keep₂ 6 (by decide) (by decide))).trans count₁
+
+private theorem choiceBits_ticks (t : ℕ) : choiceBits (List.replicate t (.tick : Event w)) = [] := by
+ induction t with
+ | zero => rfl
+ | succ t ih => simp [List.replicate_succ, choiceBits, ih]
+
+/-- A linked occurrence transfers control to its continuation with the computed
+registers, the same branch bits, and the private and external memories it received. -/
+theorem programExecute {p : ℕ} (M : Machine w p 12 k) (pn pr : Fin k) (state : Word w)
+ (priv : Word w → Word w) (m : Memory w) (rs : Regs w 12) (B n : ℕ) (hB : 1 ≤ B)
+ (hn : 2 ≤ n) (hw : w = (addressWidth B n + 10) ^ 4) (hnat : (M.publicData pn).val = n)
+ (hr : (M.publicData pr).val = addressWidth B n) (label : (program pn pr).Label → Fin p)
+ (stop bad : Fin p) (hl : Flow.Linked M (program pn pr) label stop bad)
+ (hb : M.code bad = .reject) :
+ ∃ out, Result n (addressWidth B n) out ∧ ∀ fuel bits,
+ execute M.program (ticks n + fuel) ⟨label (program pn pr).entry, state, rs, priv⟩ m bits =
+ (execute M.program fuel ⟨stop, state, out, priv⟩ m bits).map
+ (Flow.prependEvents (List.replicate (ticks n) .tick)) := by
+ obtain ⟨out, run, result⟩ := programRun M.publicData pn pr state m rs B n hB hn hw hnat hr
+ refine ⟨out, result, fun fuel bits => ?_⟩
+ simpa only [List.length_replicate, choiceBits_ticks, List.nil_append] using run.execute hl hb priv fuel bits
+
+end BurstRAM.VirtualParameters
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMWordBits.lean b/lean/OAI/Computability/VPVNP/RAMWordBits.lean
new file mode 100644
index 0000000000..66f370f793
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMWordBits.lean
@@ -0,0 +1,122 @@
+import OAI.Computability.VPVNP.RAMSerialization
+import Mathlib.Data.List.OfFn
+
+/-!
+# Reading one RAM word from a bit stream
+
+The private choices for a reported RAM call contain fixed-width read answers.
+They use the same least-significant-bit-first encoding as the shared messages.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+variable {w : ℕ}
+
+/-- The `w` consecutive bits of a word, in increasing order of significance. -/
+def wordBits (a : Word w) : List Bool := List.ofFn (RAMSerialization.wordBits w a)
+
+@[simp] theorem length_wordBits (a : Word w) : (wordBits a).length = w :=
+ List.length_ofFn
+
+private def pushLow (b : Bool) (hi : Word w) : Word (w + 1) :=
+ ⟨(finTwoEquiv.symm b).val + 2 * hi.val, by
+ have hb := (finTwoEquiv.symm b).isLt
+ have hh := hi.isLt
+ rw [pow_succ]
+ omega⟩
+
+private theorem decode_digits (d : Fin w → Bool) :
+ ((RAMSerialization.wordBits w).symm d).val = ∑ i, (finTwoEquiv.symm (d i)).val * 2 ^ i.val :=
+ finFunctionFinEquiv_apply _
+
+private theorem decode_cons (b : Bool) (d : Fin w → Bool) :
+ (RAMSerialization.wordBits (w + 1)).symm (Fin.cons b d) =
+ pushLow b ((RAMSerialization.wordBits w).symm d) := by
+ apply Fin.ext
+ rw [decode_digits, Fin.sum_univ_succ]
+ simp only [Fin.cons_zero, Fin.val_zero, pow_zero, mul_one, Fin.cons_succ, Fin.val_succ, pow_succ,
+ ← Nat.mul_assoc, ← Finset.sum_mul]
+ simp [pushLow, decode_digits, Nat.mul_comm]
+
+private theorem wordBits_pushLow (b : Bool) (hi : Word w) :
+ wordBits (pushLow b hi) = b :: wordBits hi := by
+ have he := decode_cons b (RAMSerialization.wordBits w hi)
+ rw [Equiv.symm_apply_apply] at he
+ simp [wordBits, ← he, List.ofFn_succ]
+
+/-- Consume one bit per iteration. Each return computes the word by a single
+left shift and the addition of its low bit, without inspecting the suffix. -/
+def takeWord : (w : ℕ) → List Bool → Option (Word w × List Bool)
+ | 0, xs => some (0, xs)
+ | _ + 1, [] => none
+ | k + 1, b :: xs => (takeWord k xs).map (fun (a, tail) => (pushLow b a, tail))
+
+private theorem takeWord_sound (xs : List Bool) (a : Word w) (tail : List Bool)
+ (h : takeWord w xs = some (a, tail)) : xs = wordBits a ++ tail := by
+ induction w generalizing xs with
+ | zero =>
+ have he : ((0 : Word 0), xs) = (a, tail) := Option.some.inj h
+ obtain ⟨_, rfl⟩ := Prod.mk.inj he
+ simp [wordBits]
+ | succ w ih =>
+ cases xs with
+ | nil => simp [takeWord] at h
+ | cons b xs =>
+ simp only [takeWord, Option.map_eq_some_iff] at h
+ obtain ⟨⟨hi, ts⟩, hh, he⟩ := h
+ cases he
+ rw [wordBits_pushLow, List.cons_append, ih _ _ hh]
+
+private theorem takeWord_wordBits (a : Word w) (tail : List Bool) :
+ takeWord w (wordBits a ++ tail) = some (a, tail) := by
+ induction w with
+ | zero =>
+ have ha : a = 0 := by
+ apply Fin.ext
+ have h := a.isLt
+ simp at h
+ omega
+ simp [wordBits, takeWord, ha]
+ | succ w ih =>
+ let d := RAMSerialization.wordBits (w + 1) a
+ have he := decode_cons (d 0) (Fin.tail d)
+ rw [Fin.cons_self_tail, Equiv.symm_apply_apply] at he
+ rw [he, wordBits_pushLow, List.cons_append, takeWord, ih]
+ rfl
+
+theorem takeWord_eq_some_iff (xs : List Bool) (a : Word w) (tail : List Bool) :
+ takeWord w xs = some (a, tail) ↔ xs = wordBits a ++ tail :=
+ ⟨takeWord_sound xs a tail, fun he => he ▸ takeWord_wordBits a tail⟩
+
+/-- Meter the width test, list dispatch, low-bit conversion, shift and addition.
+On a short stream, including when the first missing bit is the last requested
+bit, the parser returns within the same bound as on a complete word. -/
+def meteredTakeWord : (w : ℕ) → List Bool → Option (Word w × List Bool) × ℕ
+ | 0, xs => (some (0, xs), 1)
+ | _ + 1, [] => (none, 2)
+ | k + 1, b :: xs =>
+ let (out, work) := meteredTakeWord k xs
+ (out.map (fun (a, tail) => (pushLow b a, tail)), 5 + work)
+
+/-- The metered stream parser realizes the decoder used by local calls. -/
+theorem meteredTakeWord_spec (w : ℕ) (xs : List Bool) :
+ (meteredTakeWord w xs).1 = takeWord w xs ∧ (meteredTakeWord w xs).2 ≤ 5 * w + 1 := by
+ induction w generalizing xs with
+ | zero => simp [meteredTakeWord, takeWord]
+ | succ k ih =>
+ cases xs with
+ | nil => simp [meteredTakeWord, takeWord]; omega
+ | cons b xs =>
+ obtain ⟨ho, hw⟩ := ih xs
+ simp only [meteredTakeWord, takeWord, ho, true_and]
+ omega
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMWordBounds.lean b/lean/OAI/Computability/VPVNP/RAMWordBounds.lean
new file mode 100644
index 0000000000..512cc72006
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMWordBounds.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.RAMRecordBlocks
+
+/-!
+# Word bounds for burst RAM records
+
+The address of a probe is already a word. Its starting cost and ordinal are
+bounded by the total cost of the calls, including the one unit charged per
+call. Initialization at site `a` uses `a` for both address and timestamp.
+These bounds hold throughout every permutation of the padded input blocks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM
+
+open RAMMemory
+
+variable {w : ℕ}
+
+/-- All three natural-valued fields of an occupied record fit in words. -/
+def RecordFitsWord (r : Record (Word w)) : Prop :=
+ r.address < 2 ^ w ∧ r.startCost < 2 ^ w ∧ r.ordinal < 2 ^ w
+
+theorem eventRecords_bounds {start j : ℕ} {es : List (Event w)} {r : Record (Word w)}
+ (hr : r ∈ eventRecords start j es) :
+ r.address < 2 ^ w ∧ r.ordinal < j + countProbes es := by
+ induction es generalizing j with
+ | nil => simp [eventRecords] at hr
+ | cons e es ih =>
+ cases e with
+ | tick | choice => exact ih hr
+ | read a v | write a v =>
+ rcases List.mem_cons.mp hr with rfl | ht
+ · exact ⟨a.isLt, by change j < j + (1 + countProbes es); omega⟩
+ · simpa only [countProbes, Nat.add_assoc] using ih ht
+
+/-- The start and ordinal of a chronological probe are jointly bounded by the
+ending cost. This estimate holds even for the final call at the budget cap. -/
+theorem probeRecords_bounds {start : ℕ} {rs : List (Report w)} {r : Record (Word w)}
+ (hr : r ∈ probeRecords start rs) :
+ r.address < 2 ^ w ∧ r.startCost + r.ordinal < start + RAMBuckets.cost Report.probes rs := by
+ induction rs generalizing start with
+ | nil => simp [probeRecords] at hr
+ | cons s rs ih =>
+ rcases List.mem_append.mp hr with hs | ht
+ · obtain ⟨ha, hj⟩ := eventRecords_bounds hs
+ have he := (mem_eventRecords hs).2.1
+ refine ⟨ha, ?_⟩
+ simp only [RAMBuckets.cost, Report.probes, he]
+ omega
+ · simpa only [RAMBuckets.cost, Nat.add_assoc] using ih ht
+
+theorem probeRecords_fitsWord {start : ℕ} {rs : List (Report w)} {r : Record (Word w)}
+ (hcost : start + RAMBuckets.cost Report.probes rs ≤ 2 ^ w)
+ (hr : r ∈ probeRecords start rs) : RecordFitsWord r := by
+ obtain ⟨ha, ht⟩ := probeRecords_bounds hr
+ exact ⟨ha, by omega, by omega⟩
+
+theorem initialRecords_fitsWord (header : ℕ → Word w) {S : ℕ} {r : Record (Word w)}
+ (hS : S ≤ 2 ^ w) (hr : r ∈ initialRecords S header) : RecordFitsWord r := by
+ obtain ⟨a, ha, rfl⟩ := List.mem_map.mp hr
+ have h := (List.mem_range.mp ha).trans_le hS
+ exact ⟨h, h, Nat.two_pow_pos w⟩
+
+theorem canonicalRecordBlocks_fitsWord (header : ℕ → Word w) {S H : ℕ} {rs : List (Report w)}
+ {r : Record (Word w)} (hH : 0 < H) (hcap : RAMBuckets.cost Report.probes rs ≤ S * H)
+ (hword : S * H < 2 ^ w) (hr : some r ∈ (canonicalRecordBlocks header S H rs).flatten) :
+ RecordFitsWord r := by
+ have hp := canonicalRecordBlocks_perm header hcap
+ have hm := hp.mem_iff.mpr (List.mem_filterMap.mpr ⟨_, hr, rfl⟩)
+ rcases List.mem_append.mp hm with hi | ht
+ · exact initialRecords_fitsWord header ((Nat.le_mul_of_pos_right S hH).trans hword.le) hi
+ · exact probeRecords_fitsWord (by simpa only [Nat.zero_add] using hcap.trans hword.le) ht
+
+/-- Every occupied slot still fits in words after any sorting-network permutation. -/
+theorem perm_canonicalRecordBlocks_fitsWord (header : ℕ → Word w) {S H : ℕ}
+ {rs : List (Report w)} {out : List (Option (Record (Word w)))} {r : Record (Word w)}
+ (hH : 0 < H) (hcap : RAMBuckets.cost Report.probes rs ≤ S * H) (hword : S * H < 2 ^ w)
+ (hp : (canonicalRecordBlocks header S H rs).flatten.Perm out) (hr : some r ∈ out) :
+ RecordFitsWord r :=
+ canonicalRecordBlocks_fitsWord header hH hcap hword (hp.mem_iff.mpr hr)
+
+end BurstRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RAMWork.lean b/lean/OAI/Computability/VPVNP/RAMWork.lean
new file mode 100644
index 0000000000..808468677d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RAMWork.lean
@@ -0,0 +1,349 @@
+import OAI.Computability.VPVNP.RAMLoggedSite
+import Mathlib.Tactic.Ring
+
+/-!
+# Word work of the finite instruction interpreter
+
+The instruction charges follow the actual local run, including a failed call.
+The bound is uniform in the incoming persistent state, probe allowances, and
+bits. All arithmetic in the private machine is on words and all operands have
+constant arity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BurstRAM.PrivateRAM
+
+open VPVNP.BurstRAM
+
+variable {w p r k : ℕ} {C : Type*}
+
+/-- Which invocation follows the current dispatch. A rejected probe, a short
+choice stream, or a terminating instruction has no successor invocation. -/
+private def continueCall : CallAction w C → ℕ → List Bool → Option (C × ℕ × List Bool)
+ | .localStep next, a, bs => some (next, a, bs)
+ | .branch _, _, [] => none
+ | .branch next, a, b :: bs => some (next b, a, bs)
+ | .read _ _, 0, _ => none
+ | .read _ next, a + 1, bs => (takeWord w bs).map fun (v, rest) => (next v, a, rest)
+ | .write .., 0, _ => none
+ | .write _ _ next, a + 1, bs => some (next, a, bs)
+ | .finish _, _, _ | .reject, _, _ => none
+
+private theorem instructionCount_succ (P : Program w C) (fuel : ℕ) (c : C)
+ (a : ℕ) (bits : List Bool) :
+ (runLocalCall P (fuel + 1) c a bits).instructions =
+ 1 + match continueCall (P.step c) a bits with
+ | none => 0
+ | some (c', a', bs) => (runLocalCall P fuel c' a' bs).instructions := by
+ cases hs : P.step c with
+ | finish result | reject | localStep next =>
+ simp [hs, continueCall, runLocalCall, LocalCallRun.prepend, LocalCallRun.stop]
+ | branch next =>
+ cases bits <;> simp [hs, continueCall, runLocalCall, LocalCallRun.prepend, LocalCallRun.stop]
+ | read addr next =>
+ cases a with
+ | zero => simp [hs, continueCall, runLocalCall, LocalCallRun.stop]
+ | succ a =>
+ cases h : takeWord w bits with
+ | none => simp [hs, h, continueCall, runLocalCall, LocalCallRun.stop]
+ | some pair =>
+ obtain ⟨v, rest⟩ := pair
+ simp [hs, h, continueCall, runLocalCall, LocalCallRun.prepend]
+ | write addr v next =>
+ cases a <;> simp [hs, continueCall, runLocalCall, LocalCallRun.stop, LocalCallRun.prepend]
+
+/-- A private load scans at most the number of write-log slots reserved
+for this call. A store prepends its address and value. -/
+def Instr.logCharge (i : Instr w p r k) (capacity : ℕ) : ℕ :=
+ match i with
+ | .loadPrivate .. => 4 * (capacity + 1)
+ | .storePrivate .. => 3
+ | _ => 0
+
+theorem Instr.logCharge_le (i : Instr w p r k) (capacity : ℕ) :
+ i.logCharge capacity ≤ 4 * (capacity + 1) := by
+ cases i <;> simp [Instr.logCharge]
+ omega
+
+/-- Sum the elementary opcode charges actually incurred by the local call.
+The final dispatched instruction counts even when it causes rejection. -/
+def Machine.dispatchWork (M : Machine w p r k) (capacity : ℕ) : ℕ → Config w p r → ℕ → List Bool → ℕ
+ | 0, _, _, _ => 0
+ | f + 1, c, a, bs =>
+ ((M.code c.pc).wordWork + (M.code c.pc).logCharge capacity) + match continueCall (M.program.step c) a bs with
+ | none => 0
+ | some (c', a', tail) => M.dispatchWork capacity f c' a' tail
+
+theorem Machine.dispatchWork_le (M : Machine w p r k) (capacity fuel : ℕ) (c : Config w p r)
+ (a : ℕ) (bits : List Bool) :
+ M.dispatchWork capacity fuel c a bits ≤ (6 + 4 * (capacity + 1)) * (runLocalCall M.program fuel c a bits).instructions := by
+ induction fuel generalizing c a bits with
+ | zero => simp [Machine.dispatchWork, runLocalCall]
+ | succ f ih =>
+ rw [Machine.dispatchWork, instructionCount_succ, Nat.mul_add, Nat.mul_one]
+ have hi := Nat.add_le_add (M.code c.pc).wordWork_le ((M.code c.pc).logCharge_le capacity)
+ cases h : continueCall (M.program.step c) a bits with
+ | none => simpa using hi
+ | some t =>
+ obtain ⟨c', a', tail⟩ := t
+ exact Nat.add_le_add hi (ih c' a' tail)
+
+private theorem continueCall_mapState {D : Type*} (f : C → D) (action : CallAction w C)
+ (allowance : ℕ) (bits : List Bool) :
+ continueCall (action.mapState f) allowance bits =
+ (continueCall action allowance bits).map (fun (c, a, bs) => (f c, a, bs)) := by
+ cases action with
+ | finish | reject | localStep => rfl
+ | branch => cases bits <;> rfl
+ | write => cases allowance <;> rfl
+ | read =>
+ cases allowance with
+ | zero => rfl
+ | succ a =>
+ simp only [continueCall, CallAction.mapState, Option.map_map]
+ rfl
+
+theorem Instr.actualLogWork_le (i : Instr w p r k) (l : LogConfig w p r) {capacity : ℕ}
+ (h : l.writes.length ≤ capacity) : i.actualLogWork l ≤ i.logCharge capacity := by
+ cases i <;> simp only [Instr.actualLogWork, Instr.logCharge, le_refl]
+ exact (WriteLog.scan_work_le ..).trans (Nat.mul_le_mul_left _ (Nat.add_le_add_right h 1))
+
+/-- Opcode work in the implementation with a concrete write log. -/
+def Machine.loggedDispatchWork (M : Machine w p r k) : ℕ → LogConfig w p r → ℕ → List Bool → ℕ
+ | 0, _, _, _ => 0
+ | f + 1, l, a, bs =>
+ ((M.code l.pc).wordWork + (M.code l.pc).actualLogWork l) +
+ match continueCall (M.logProgram.step l) a bs with
+ | none => 0
+ | some (l', a', tail) => M.loggedDispatchWork f l' a' tail
+
+private theorem Machine.continue_writes (M : Machine w p r k) (l : LogConfig w p r) {a bits l' a' tail}
+ (h : continueCall (M.logProgram.step l) a bits = some (l', a', tail)) :
+ l'.writes = (M.code l.pc).nextLog l := by
+ simp only [Machine.logProgram, Instr.runLogged, continueCall_mapState, Option.map_eq_some_iff] at h
+ obtain ⟨⟨_, _, _⟩, _, he⟩ := h
+ cases he
+ rfl
+
+/-- The reserved linear scans bound the actual linear scans on *every* choice
+stream. The invariant pays for at most one new private write per dispatch. -/
+theorem Machine.loggedDispatchWork_le (M : Machine w p r k) (fuel : ℕ) (l : LogConfig w p r)
+ (a : ℕ) (bits : List Bool) {capacity : ℕ} (hcap : l.writes.length + fuel ≤ capacity) :
+ M.loggedDispatchWork fuel l a bits ≤ M.dispatchWork capacity fuel l.denote a bits := by
+ induction fuel generalizing l a bits with
+ | zero => simp [Machine.loggedDispatchWork, Machine.dispatchWork]
+ | succ f ih =>
+ rw [Machine.loggedDispatchWork, Machine.dispatchWork, ← M.logProgram_step,
+ continueCall_mapState]
+ apply Nat.add_le_add
+ · exact Nat.add_le_add_left ((M.code l.pc).actualLogWork_le l (by omega)) _
+ · cases h : continueCall (M.logProgram.step l) a bits with
+ | none => rfl
+ | some t =>
+ obtain ⟨l', a', tail⟩ := t
+ apply ih
+ rw [M.continue_writes l h]
+ have := (M.code l.pc).nextLog_length_le l
+ omega
+
+/-- Each call starts with an empty log; its instruction fuel is enough log
+capacity even on rejecting paths. -/
+theorem Machine.loggedDispatchWork_start (M : Machine w p r k) (fuel a : ℕ) (s : Word w) (bs : List Bool) :
+ M.loggedDispatchWork fuel (M.logProgram.start s) a bs ≤
+ M.dispatchWork fuel fuel (M.program.start s) a bs :=
+ M.loggedDispatchWork_le fuel (M.logProgram.start s) a bs (by simp [Machine.logProgram])
+
+private def CallFrame.continuation : CallFrame w C → Option (C × ℕ × List Bool)
+ | .stop _ => none
+ | .next _ c a bs => some (c, a, bs)
+
+private theorem CallFrame.continuation_eq (action : CallAction w C) (a : ℕ) (bs : List Bool) :
+ (CallFrame.ofAction action a bs).continuation = continueCall action a bs := by
+ cases action with
+ | finish | reject | localStep => rfl
+ | branch => cases bs <;> rfl
+ | write => cases a <;> rfl
+ | read =>
+ cases a with
+ | zero => rfl
+ | succ a =>
+ cases h : takeWord w bs with
+ | none => simp [CallFrame.ofAction, CallFrame.continuation, continueCall, h]
+ | some pair =>
+ obtain ⟨v, tail⟩ := pair
+ simp [CallFrame.ofAction, CallFrame.continuation, continueCall, h]
+
+theorem Machine.meteredLoggedCall_work_eq (M : Machine w p r k) (f : ℕ) (l : LogConfig w p r)
+ (a : ℕ) (bs : List Bool) :
+ (M.meteredLoggedCall f l a bs).2 = M.loggedDispatchWork f l a bs +
+ LocalCharge (M.meteredLoggedCall f l a bs).1 := by
+ induction f generalizing l a bs with
+ | zero => rfl
+ | succ f ih =>
+ rw [Machine.meteredLoggedCall, Instr.meteredAction_spec, Machine.loggedDispatchWork,
+ ← CallFrame.continuation_eq]
+ dsimp only
+ change ((match CallFrame.ofAction (M.logProgram.step l) a bs with
+ | .stop t => (t, _)
+ | .next e c a' tail => ((M.meteredLoggedCall f c a' tail).1.prepend e, _))
+ : LocalCallRun w × ℕ).2 = _
+ cases h : CallFrame.ofAction (M.logProgram.step l) a bs with
+ | stop t =>
+ change _ = _ + LocalCharge ((match CallFrame.ofAction (M.logProgram.step l) a bs with
+ | .stop out => (out, _)
+ | .next e c a' tail => ((M.meteredLoggedCall f c a' tail).1.prepend e, _))
+ : LocalCallRun w × ℕ).1
+ rw [h]
+ rfl
+ | next e c a' tail =>
+ change _ = _ + LocalCharge ((match CallFrame.ofAction (M.logProgram.step l) a bs with
+ | .stop out => (out, _)
+ | .next e c a'' tail' => ((M.meteredLoggedCall f c a'' tail').1.prepend e, _))
+ : LocalCallRun w × ℕ).1
+ rw [h]
+ dsimp only [CallFrame.continuation]
+ rw [ih c a' tail, localCharge_prepend]
+ omega
+
+/-- Besides opcode work, reserve eight control operations per dispatch,
+five word stores per occupied probe record, and four operations per bit
+guessed, fetched and packed into a word. -/
+def Machine.callWordWork (M : Machine w p r k) (fuel : ℕ) (c : Config w p r)
+ (allowance : ℕ) (bits : List Bool) : ℕ :=
+ let t := runLocalCall M.program fuel c allowance bits
+ M.dispatchWork fuel fuel c allowance bits + 8 * t.instructions + 5 * t.probes + 4 * t.guessWork
+
+/-- On a fresh call the actual one-pass work is bounded by the reserved
+work, including truncated streams and attempted over-cap probes. -/
+theorem Machine.meteredLoggedCall_work_le (M : Machine w p r k) (fuel : ℕ) (s : Word w)
+ (allowance : ℕ) (bits : List Bool) :
+ (M.meteredLoggedCall fuel (M.logProgram.start s) allowance bits).2 ≤
+ M.callWordWork fuel (M.program.start s) allowance bits := by
+ rw [M.meteredLoggedCall_work_eq, M.meteredLoggedCall_result, M.logProgram_start]
+ have h := M.loggedDispatchWork_start fuel allowance s bits
+ dsimp only [Machine.callWordWork, LocalCharge]
+ omega
+
+theorem Machine.callWordWork_le_units (M : Machine w p r k) (fuel : ℕ) (c : Config w p r)
+ (allowance : ℕ) (bits : List Bool) :
+ let t := runLocalCall M.program fuel c allowance bits
+ M.callWordWork fuel c allowance bits ≤ (16 * (fuel + 2)) * (t.instructions + t.probes + t.guessWork) := by
+ let t := runLocalCall M.program fuel c allowance bits
+ have h := M.dispatchWork_le fuel fuel c allowance bits
+ change M.dispatchWork fuel fuel c allowance bits ≤ (6 + 4 * (fuel + 1)) * t.instructions at h
+ change M.dispatchWork fuel fuel c allowance bits + 8*t.instructions + 5*t.probes + 4*t.guessWork ≤ _
+ calc
+ _ ≤ (6 + 4 * (fuel + 1) + 8) * t.instructions + 5*t.probes + 4*t.guessWork := by
+ rw [Nat.add_mul]; omega
+ _ ≤ (16*(fuel+2))*t.instructions + (16*(fuel+2))*t.probes + (16*(fuel+2))*t.guessWork :=
+ Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_right _ (by omega))
+ (Nat.mul_le_mul_right _ (by omega))) (Nat.mul_le_mul_right _ (by omega))
+ _ = _ := by simp only [Nat.mul_add, t]
+
+theorem Machine.callWordWork_le (M : Machine w p r k) (fuel : ℕ) (c : Config w p r)
+ (allowance : ℕ) (bits : List Bool) :
+ M.callWordWork fuel c allowance bits ≤ (16 * (fuel + 2)) * (3 * fuel + w * allowance) :=
+ (M.callWordWork_le_units ..).trans
+ (Nat.mul_le_mul_left _ (runLocalCall_totalWork_le M.program fuel c allowance bits))
+
+private theorem Machine.loggedChargedCall_work_le_units (M : Machine w p r k) (fuel : ℕ) (s : Word w)
+ (callLeft globalLeft siteLeft : ℕ) (bits : List Bool) :
+ let t := runChargedCall M.program fuel (M.program.start s) callLeft globalLeft siteLeft bits
+ (M.loggedChargedCall fuel s callLeft globalLeft siteLeft bits).2 ≤
+ (16 * (fuel + 2)) * (t.instructions + t.probes + t.guessWork) := by
+ cases h : min callLeft (min globalLeft siteLeft) with
+ | zero => simp [Machine.loggedChargedCall, runChargedCall, h]
+ | succ a =>
+ simpa [Machine.loggedChargedCall, runChargedCall, h] using
+ (M.meteredLoggedCall_work_le fuel s a bits).trans (M.callWordWork_le_units fuel (M.program.start s) a bits)
+
+/-- Count the elementary work of the same invocation that returns the site's
+reports and unused bits. -/
+def Machine.siteWordWork (M : Machine w p r k) (fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) : ℕ :=
+ (M.runLoggedSite fuel H boundary globalCap steps c siteLeft bits).work
+
+theorem Machine.siteWordWork_le_units (M : Machine w p r k) (fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) :
+ M.siteWordWork fuel H boundary globalCap steps c siteLeft bits ≤
+ (16 * (fuel + 2)) * (meteredSiteLoop M.program 1 fuel H boundary globalCap steps c siteLeft bits).work := by
+ unfold Machine.siteWordWork
+ induction steps generalizing c siteLeft bits with
+ | zero =>
+ rw [Machine.runLoggedSite, meteredSiteLoop]
+ by_cases hc : c.cost ≤ globalCap
+ · cases c.state <;> simp only [hc, ↓reduceIte]
+ · simp
+ · split <;> simp
+ · simp [hc]
+ | succ n ih =>
+ rw [Machine.runLoggedSite, meteredSiteLoop]
+ by_cases hc : c.cost ≤ globalCap
+ · cases hs : c.state with
+ | none => simp [hc]
+ | some s =>
+ by_cases hb : c.cost < boundary
+ · simp only [hc, hb, ↓reduceIte, Machine.loggedChargedCall_result]
+ have hw := M.loggedChargedCall_work_le_units fuel s H (globalCap - c.cost) siteLeft bits
+ dsimp only at hw
+ cases ht : (runChargedCall M.program fuel (M.program.start s) H
+ (globalCap - c.cost) siteLeft bits).output with
+ | none =>
+ change 16 + _ ≤ (16 * (fuel+2)) * (1 + _)
+ rw [Nat.mul_add, Nat.mul_one]
+ exact Nat.add_le_add (by omega) hw
+ | some z =>
+ obtain ⟨report, tail⟩ := z
+ let t := runChargedCall M.program fuel (M.program.start s) H (globalCap-c.cost) siteLeft bits
+ let charge := 1 + t.probes
+ have htail := ih ⟨c.cost+charge, report.result⟩ (siteLeft-charge) tail
+ change 16 + _ + _ ≤ (16 * (fuel+2)) * ((1 + _) + _)
+ rw [Nat.mul_add, Nat.mul_add, Nat.mul_one]
+ exact Nat.add_le_add (Nat.add_le_add (by omega) hw) htail
+ · simp [hc, hb]
+ · simp [hc]
+
+theorem Machine.siteWordWork_le (M : Machine w p r k) (fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) :
+ M.siteWordWork fuel H boundary globalCap steps c siteLeft bits ≤
+ (16 * (fuel + 2)) * ((steps + 1) * (1 + 3 * fuel + w * H)) :=
+ (M.siteWordWork_le_units ..).trans (Nat.mul_le_mul_left _ (siteWork_le ..))
+
+/-- The metered result of the concrete word interpreter and its private
+memory log. The successful reports and unused bits are the ordinary site's
+output, including on malformed incoming data. -/
+def Machine.privateSite (M : Machine w p r k) (fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) : MeteredSiteRun w :=
+ M.runLoggedSite fuel H boundary globalCap steps c siteLeft bits
+
+theorem Machine.privateSite_output (M : Machine w p r k) (fuel H boundary globalCap steps : ℕ)
+ (c : Cut w) (siteLeft : ℕ) (bits : List Bool) :
+ (M.privateSite fuel H boundary globalCap steps c siteLeft bits).output =
+ runSiteLoop M.program fuel H boundary globalCap steps c siteLeft bits :=
+ M.runLoggedSite_output ..
+
+/-- The site portion of the paper's clock bound when the bucket size is at
+most twice the instruction fuel. For fuel `n^u`, `u ≥ 1`, this follows from
+`H ≤ 2n`. The constant leaves room for the remaining validation checks. -/
+theorem Machine.privateSite_work_le (M : Machine w p r k) {fuel H : ℕ} (hH : H ≤ 2 * fuel)
+ (boundary globalCap : ℕ) (c : Cut w) (siteLeft : ℕ) (bits : List Bool) :
+ (M.privateSite fuel H boundary globalCap (2*H-1) c siteLeft bits).work ≤
+ 256 * (H+1) * (fuel+1) * (fuel+1) * (w+2) := by
+ have hinner : 1 + 3*fuel + w*H ≤ 4*(fuel+1)*(w+2) := by
+ have := Nat.mul_le_mul_left w hH
+ ring_nf at *
+ omega
+ calc
+ _ ≤ (16*(fuel+2))*((2*H-1+1)*(1+3*fuel+w*H)) := M.siteWordWork_le ..
+ _ ≤ (16*(2*(fuel+1)))*((2*(H+1))*(4*(fuel+1)*(w+2))) :=
+ Nat.mul_le_mul (Nat.mul_le_mul_left _ (by omega)) (Nat.mul_le_mul (by omega) hinner)
+ _ = _ := by ring
+
+end BurstRAM.PrivateRAM
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RadicalCertificate.lean b/lean/OAI/Computability/VPVNP/RadicalCertificate.lean
new file mode 100644
index 0000000000..97d5c60a4d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RadicalCertificate.lean
@@ -0,0 +1,112 @@
+import Mathlib.Algebra.MvPolynomial.Equiv
+import Mathlib.Algebra.MvPolynomial.NoZeroDivisors
+import Mathlib.RingTheory.Ideal.Operations
+import Mathlib.RingTheory.Localization.FractionRing
+
+/-!
+# Clearing the Rabinowitsch certificate
+
+In Appendix D.1 of *VP and VNP differ over every field*, the auxiliary equation
+`1 - y f` converts a vanishing question into a certificate of inconsistency.
+Index the original variables by `Fin t` and the extra variable by zero in
+`Fin (t + 1)`. Substitution of `1/f` in the fraction field clears all denominators
+with a single power `f ^ P` and controls the total degree of each new multiplier.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate
+
+open MvPolynomial
+open scoped Polynomial
+
+variable {K : Type*} [Field K] {t : ℕ}
+
+private theorem univariate_rename_succ (p : MvPolynomial (Fin t) K) :
+ finSuccEquiv K t (rename Fin.succ p) = Polynomial.C p := by
+ induction p using MvPolynomial.induction_on with
+ | C c => simp [finSuccEquiv_apply]
+ | add p q hp hq => simp [hp, hq]
+ | mul_X p i hp => simp [hp, finSuccEquiv_X_succ]
+
+/-- The coefficient of `y ^ b` is multiplied by `f ^ (P - b)` to clear its denominator. -/
+noncomputable def clearedMultiplier (P : ℕ) (f : MvPolynomial (Fin t) K)
+ (A : MvPolynomial (Fin (t + 1)) K) : MvPolynomial (Fin t) K :=
+ let a := finSuccEquiv K t A
+ ∑ b ∈ a.support, a.coeff b * f ^ (P - b)
+
+/-- Total-degree control for the multipliers indexing the rows of the Macaulay matrix. -/
+theorem clearedMultiplier_totalDegree (P : ℕ) (f : MvPolynomial (Fin t) K)
+ (A : MvPolynomial (Fin (t + 1)) K) :
+ (clearedMultiplier P f A).totalDegree ≤ A.totalDegree + P * f.totalDegree := by
+ apply totalDegree_finsetSum_le
+ intro b hb
+ have h := totalDegree_coeff_finSuccEquiv_add_le A b (Polynomial.mem_support_iff.mp hb)
+ apply (totalDegree_mul _ _).trans
+ exact Nat.add_le_add (by omega) ((totalDegree_pow _ _).trans
+ (Nat.mul_le_mul_right _ (Nat.sub_le P b)))
+
+private theorem map_clearedMultiplier (P : ℕ) {f : MvPolynomial (Fin t) K} (hf : f ≠ 0)
+ (A : MvPolynomial (Fin (t + 1)) K) (hA : A.totalDegree ≤ P) :
+ let φ := algebraMap (MvPolynomial (Fin t) K) (FractionRing (MvPolynomial (Fin t) K))
+ φ (clearedMultiplier P f A) =
+ (φ f) ^ P * (finSuccEquiv K t A).eval₂ φ (φ f)⁻¹ := by
+ intro φ
+ have hφ : φ f ≠ 0 := by
+ exact fun h ↦ hf (IsFractionRing.injective _ _ (h.trans φ.map_zero.symm))
+ rw [clearedMultiplier, map_sum, Polynomial.eval₂_eq_sum, Polynomial.sum_def, Finset.mul_sum]
+ refine Finset.sum_congr rfl fun b hb ↦ ?_
+ have h := totalDegree_coeff_finSuccEquiv_add_le A b (Polynomial.mem_support_iff.mp hb)
+ rw [map_mul, map_pow, pow_sub₀ _ hφ (by omega), inv_pow, mul_left_comm]
+
+/-- Bounded Rabinowitsch denominator clearing. From the identity for `1` in the extended
+ring, obtain an identity for `f ^ P` in the original polynomial ring. -/
+theorem clear_certificate {ι : Type*} [Fintype ι] (F : ι → MvPolynomial (Fin t) K)
+ {f : MvPolynomial (Fin t) K} (hf : f ≠ 0) (A : ι → MvPolynomial (Fin (t + 1)) K)
+ (B : MvPolynomial (Fin (t + 1)) K) {H P : ℕ} (hHP : H ≤ P)
+ (hA : ∀ i, (A i).totalDegree ≤ H)
+ (hcert : (∑ i, A i * rename Fin.succ (F i)) + B * (1 - X 0 * rename Fin.succ f) = 1) :
+ (∑ i, clearedMultiplier P f (A i) * F i = f ^ P) ∧
+ ∀ i, (clearedMultiplier P f (A i)).totalDegree ≤ H + P * f.totalDegree := by
+ constructor
+ · let φ := algebraMap (MvPolynomial (Fin t) K) (FractionRing (MvPolynomial (Fin t) K))
+ have hφ : φ f ≠ 0 := fun h ↦ hf (IsFractionRing.injective _ _ (h.trans φ.map_zero.symm))
+ let ψ := Polynomial.eval₂RingHom φ (φ f)⁻¹
+ have h := congrArg (fun p ↦ ψ (finSuccEquiv K t p)) hcert
+ simp only [map_add, map_sum, map_mul, map_sub, map_one, univariate_rename_succ,
+ finSuccEquiv_X_zero] at h
+ simp only [ψ, Polynomial.coe_eval₂RingHom, Polynomial.eval₂_C, Polynomial.eval₂_X,
+ inv_mul_cancel₀ hφ, sub_self, mul_zero, add_zero] at h
+ apply IsFractionRing.injective (MvPolynomial (Fin t) K) (FractionRing (MvPolynomial (Fin t) K))
+ change φ _ = φ _
+ rw [map_sum, map_pow]
+ calc
+ _ = ∑ i, φ f ^ P * ((finSuccEquiv K t (A i)).eval₂ φ (φ f)⁻¹ * φ (F i)) := by
+ refine Finset.sum_congr rfl fun i _ ↦ ?_
+ rw [map_mul]
+ have hi := map_clearedMultiplier P hf (A i) ((hA i).trans hHP)
+ change φ (clearedMultiplier P f (A i)) = _ at hi
+ rw [hi, mul_assoc]
+ _ = φ f ^ P := by rw [← Finset.mul_sum, h, mul_one]
+ · intro i
+ exact (clearedMultiplier_totalDegree _ _ _).trans (Nat.add_le_add_right (hA i) _)
+
+/-- The certificate witnesses membership in the radical of the ideal of the original equations. -/
+theorem mem_radical_of_certificate {ι : Type*} [Fintype ι] (F : ι → MvPolynomial (Fin t) K)
+ {f : MvPolynomial (Fin t) K} (A : ι → MvPolynomial (Fin (t + 1)) K)
+ (B : MvPolynomial (Fin (t + 1)) K) {H P : ℕ} (hHP : H ≤ P)
+ (hA : ∀ i, (A i).totalDegree ≤ H)
+ (hcert : (∑ i, A i * rename Fin.succ (F i)) + B * (1 - X 0 * rename Fin.succ f) = 1) :
+ f ∈ (Ideal.span (Set.range F)).radical := by
+ by_cases hf : f = 0
+ · exact hf ▸ Ideal.zero_mem _
+ · exact Ideal.mem_radical_iff.mpr ⟨P, Ideal.mem_span_range_iff_exists_fun.mpr
+ ⟨fun i ↦ clearedMultiplier P f (A i), (clear_certificate F hf A B hHP hA hcert).1⟩⟩
+
+end RadicalCertificate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateAdvice.lean b/lean/OAI/Computability/VPVNP/RankCoordinateAdvice.lean
new file mode 100644
index 0000000000..7bbc1f6eab
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateAdvice.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.RankCoordinatePreparePorts
+
+/-!
+# Static advice for the Cramer coordinate reader
+
+Each slice supplies the two determinant roots, the greedy selector, the equation
+rank and row count, and one scale for each operation. Live basis indices and
+the label are supplied by the caller. All private work stacks start empty.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.FullAdvice
+
+open RAMTape UniversalCountStack SliceArithmetic
+
+variable {D K T : Type} {p e : ℕ}
+
+/-- The persistent image shared by the label and Frobenius readers. -/
+def advice (c : Vector p e) (r addr width rankW eqRows : ℕ) (den : Stacks D)
+ (num : Stacks (ArgumentStage.Num K)) (side : Stacks T) (powers : Bool → ℕ) :
+ Stacks (Prepare.Advice D K T) :=
+ Prepare.advice (RootInit.template c r addr width den num)
+ (Dynamic.bank side (Dynamic.regs (w := addr) 0 0 rankW eqRows 0 0 0 0))
+ (UnaryWord.store [] [] (digits addr 0) [] []) (fun b ↦ digits addr (powers b))
+
+/-- Advice and initially empty work stacks, mounted on the evaluator's extra ports. -/
+def extra (c : Vector p e) (r addr width rankW eqRows : ℕ) (den : Stacks D)
+ (num : Stacks (ArgumentStage.Num K)) (side : Stacks T) (powers : Bool → ℕ) :
+ Stacks (Prepare.Advice D K T ⊕ Prepare.Work D K T) :=
+ Sum.elim (advice c r addr width rankW eqRows den num side powers) (fun _ ↦ [])
+
+/-- Width of the largest advised stack, including the two nested readers and
+the selector's side bank. -/
+def portBound (addr width e readerBound sideBound : ℕ) :=
+ max (RootInit.templateCap addr width e readerBound) (max addr sideBound)
+
+variable [Fact p.Prime]
+variable (c : Vector p e) (r addr width rankW eqRows : ℕ) (den : Stacks D)
+ (num : Stacks (ArgumentStage.Num K)) (side : Stacks T) (powers : Bool → ℕ)
+ (readerBound sideBound : ℕ) (hr : r < 2^addr) (hw : Word.workingWidth p ≤ width)
+ (hd : ∀ i, (den i).length ≤ readerBound) (hn : ∀ i, (num i).length ≤ readerBound)
+ (hs : ∀ i, (side i).length ≤ sideBound)
+
+include hr hw hd hn hs
+
+theorem advice_length (i : Prepare.Advice D K T) :
+ (advice c r addr width rankW eqRows den num side powers i).length ≤
+ portBound addr width e readerBound sideBound := by
+ have addr_le : addr ≤ portBound addr width e readerBound sideBound :=
+ (le_max_left addr sideBound).trans (le_max_right ..)
+ rcases i with (j | (j | j) | j) | b
+ · exact (RootInit.template_length c r addr width readerBound hr hw den num hd hn j).trans
+ (le_max_left ..)
+ · exact (RegisterTable.bank_length_le Fin.elim0 0 _ j).trans addr_le
+ · exact (hs j).trans ((le_max_right addr sideBound).trans (le_max_right ..))
+ · cases j <;> simp [advice, Prepare.advice, UnaryWord.store, addr_le]
+ · simpa [advice, Prepare.advice] using addr_le
+
+theorem extra_length (i : Prepare.Advice D K T ⊕ Prepare.Work D K T) :
+ (extra c r addr width rankW eqRows den num side powers i).length ≤
+ portBound addr width e readerBound sideBound := by
+ cases i with
+ | inl i =>
+ exact advice_length c r addr width rankW eqRows den num side powers readerBound sideBound
+ hr hw hd hn hs i
+ | inr i => exact Nat.zero_le _
+
+/-- The bounds consumed by the preparation routine. Only the live unary label
+can exceed the maximum advised word length. -/
+theorem fit (label cur next : ℕ) :
+ let M := portBound addr width e readerBound sideBound
+ let rootData := RootInit.template c r addr width den num
+ let dynamicData := Dynamic.bank side (Dynamic.regs (w := addr) 0 0 rankW eqRows 0 0 0 0)
+ let unaryData := UnaryWord.store [] [] (digits addr 0) [] []
+ (∀ i, (rootData i).length ≤ M) ∧ (∀ i, (dynamicData i).length ≤ M) ∧
+ (∀ i, (unaryData i).length ≤ M) ∧
+ (∀ k, (NativeReader.state (List.replicate label true) (digits addr cur) (digits addr next) []
+ (advice c r addr width rankW eqRows den num side powers) (fun _ : Prepare.Work D K T ↦ []) k).length
+ ≤ max label M) := by
+ intro M rootData dynamicData unaryData
+ have bound := advice_length c r addr width rankW eqRows den num side powers readerBound sideBound hr hw hd hn hs
+ refine ⟨fun i ↦ bound (.inl (.inl i)), fun i ↦ bound (.inl (.inr (.inl i))),
+ fun i ↦ bound (.inl (.inr (.inr i))), ?_⟩
+ have addr_le : addr ≤ M := (le_max_left addr sideBound).trans (le_max_right ..)
+ intro k
+ cases k with
+ | label => exact List.length_replicate.trans_le (le_max_left ..)
+ | current | next => exact (length_digits ..).le.trans (addr_le.trans (le_max_right ..))
+ | result => exact Nat.zero_le _
+ | aux k => rcases k with i | i
+ · exact (bound i).trans (le_max_right ..)
+ · exact Nat.zero_le _
+
+theorem advice_total_length [Fintype (Prepare.Advice D K T)] :
+ ∑ i, (advice c r addr width rankW eqRows den num side powers i).length ≤
+ Fintype.card (Prepare.Advice D K T) * portBound addr width e readerBound sideBound := by
+ calc
+ _ ≤ ∑ _ : Prepare.Advice D K T, portBound addr width e readerBound sideBound :=
+ Finset.sum_le_sum fun i _ ↦ advice_length c r addr width rankW eqRows den num side powers
+ readerBound sideBound hr hw hd hn hs i
+ _ = _ := by simp
+
+/-- Empty work ports add no bits to the total advice length. -/
+theorem extra_total_length [Fintype (Prepare.Advice D K T)] [Fintype (Prepare.Work D K T)] :
+ ∑ i, (extra c r addr width rankW eqRows den num side powers i).length ≤
+ Fintype.card (Prepare.Advice D K T) * portBound addr width e readerBound sideBound := by
+ simpa [Fintype.sum_sum_type, extra] using
+ advice_total_length c r addr width rankW eqRows den num side powers readerBound sideBound
+ hr hw hd hn hs
+
+end RankQuery.Stack.Coordinate.FullAdvice
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateArgumentSelected.lean b/lean/OAI/Computability/VPVNP/RankCoordinateArgumentSelected.lean
new file mode 100644
index 0000000000..8a61a16de4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateArgumentSelected.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.RankCoordinateArgumentStage
+import OAI.Computability.VPVNP.RankCoordinateSelectedMinor
+import OAI.Computability.VPVNP.RankCoordinateTargetRead
+
+/-! # Dynamic input ports of the selected Cramer minors
+
+The numerator first selects original rows and columns. Its ordinary entry
+reader shares a sum bank with the powered target reader. Installing the
+four argument words reaches exactly the replacement index and the target
+reader's three live fields through these nested selectors.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.ArgumentStage
+
+open RAMTape UniversalCountStack SliceArithmetic NativeReader
+open RadicalCertificate.MonomialIndex
+
+variable {K Base D H A T : Type} {p e : ℕ}
+
+/-- Stack labels for a selected minor that can read both original matrix entries and entries of
+the replacement row. -/
+abbrev SelectedHost (K Base : Type) := SelectedMinor.Host K (Base ⊕ TargetRead.Work)
+
+/-- Mount the powered reader as the right-hand direct scalar reader. -/
+def targetMount : TargetRead.Work ↪ SelectedHost K Base :=
+ ⟨ThreeBanks.right ∘ Sum.inr, ThreeBanks.right_injective.comp Sum.inr_injective⟩
+
+/-- Place the three live target arguments inside the numerator reader's stack bank. -/
+def selectedSlot : Fin 3 ↪ SelectedHost K Base := TargetRead.slot.trans targetMount
+
+variable [DecidableEq K]
+
+/-- Initialize the selected-minor reader with pivot stacks, the original-entry reader, and the
+powered-target reader. -/
+noncomputable def selectedRaw (w v n m : ℕ) (c : Vector p e) (pivot : Stacks K)
+ (base : Stacks Base) (d : PairCall.Inputs) (constants : Bool → List Bool) : Stacks (SelectedHost K Base) :=
+ SelectedMinor.initial w v n m c pivot (Sum.elim base (TargetRead.bank w d constants))
+
+/-- Updating the target inside the selected-minor workspace preserves the
+two pivot banks and the ordinary scalar reader at every stack. -/
+theorem selected_after (w v n m : ℕ) (c : Vector p e) (pivot : Stacks K)
+ (base : Stacks Base) (d : PairCall.Inputs) (constants : Bool → List Bool) (source scale mark : ℕ) :
+ installStacks selectedSlot (selectedRaw w v n m c pivot base d constants) (TargetRead.words w source scale mark) =
+ selectedRaw w v n m c pivot base (TargetRead.setDynamic d source scale mark) constants := by
+ change installStacks (targetMount ∘ TargetRead.slot) _ _ = _
+ rw [target_bank_after targetMount w d constants source scale mark _ rfl]
+ apply installStacks_frame targetMount.injective
+ · intro _
+ rfl
+ · rintro (i | j | k | l) h
+ · rfl
+ · rfl
+ · rfl
+ · exact (h l rfl).elim
+
+/-- Each template destination is already a binary address word, so the
+clearing stage has the same height bound as the four incoming values. -/
+theorem selected_destination_length (w v n m r : ℕ) (c : Vector p e)
+ (host : RootInit.RootHost D (Num (SelectedHost K Base)) ↪ H)
+ (den : Stacks D) (pivot : Stacks K) (base : Stacks Base) (d : PairCall.Inputs)
+ (constants : Bool → List Bool) (old : ℕ) (work : Stacks H)
+ (hhost : ∀ i, work (host i) = RootInit.template c r w v den
+ (Replacement.workBank w (digits w old) (Submatrix.workBank [] [] (selectedRaw w v n m c pivot base d constants))) i)
+ (f : Field) : (work (destination host selectedSlot f)).length = w := by
+ change (work (host (RootInit.readerPort (.inr (numSlot selectedSlot f))))).length = w
+ rw [hhost]
+ rcases f with ⟨⟩ | j
+ · exact length_digits w old
+ · fin_cases j <;> exact length_digits w _
+
+/-- The final root host, after all four physical writes, is the canonical
+template for the selected minor at the live replacement row and monomial. -/
+theorem selected_host_after (w v n m r : ℕ) (c : Vector p e)
+ (host : RootInit.RootHost D (Num (SelectedHost K Base)) ↪ H)
+ (den : Stacks D) (pivot : Stacks K) (base : Stacks Base) (d : PairCall.Inputs)
+ (constants : Bool → List Bool) (old replace source scale mark : ℕ) (work : Stacks H)
+ (hhost : ∀ i, work (host i) = RootInit.template c r w v den
+ (Replacement.workBank w (digits w old) (Submatrix.workBank [] [] (selectedRaw w v n m c pivot base d constants))) i)
+ (i : RootInit.RootHost D (Num (SelectedHost K Base))) :
+ installStacks (destination host selectedSlot) work
+ (Sum.elim (fun _ : Unit ↦ digits w replace) (TargetRead.words w source scale mark)) (host i) =
+ RootInit.template c r w v den (Replacement.workBank w (digits w replace) (Submatrix.workBank [] []
+ (selectedRaw w v n m c pivot base (TargetRead.setDynamic d source scale mark) constants))) i := by
+ rw [host_after c r w v host selectedSlot den _ _ _ _ work hhost i, selected_after]
+
+/-- A runtime argument transport in the full selected minor. Its output
+describes both the enclosing work bank and the canonical paired root. -/
+theorem selected_machine_bounded [DecidableEq A] [DecidableEq H]
+ (w v n m r cap : ℕ) (c : Vector p e) (host : RootInit.RootHost D (Num (SelectedHost K Base)) ↪ H)
+ (src : Field → Bus A H) (scratch : H)
+ (den : Stacks D) (pivot : Stacks K) (base : Stacks Base) (d : PairCall.Inputs)
+ (constants : Bool → List Bool) (old replace source scale mark : ℕ)
+ (label current next result : List Bool) (advice : Stacks A) (work : Stacks H)
+ (apart : ∀ f g, src f ≠ workPort (destination host selectedSlot g))
+ (hs : ∀ f, src f ≠ workPort scratch) (hd : ∀ f, destination host selectedSlot f ≠ scratch)
+ (empty : work scratch = [])
+ (live : ∀ f, state label current next result advice work (src f) =
+ Sum.elim (fun _ : Unit ↦ digits w replace) (TargetRead.words w source scale mark) f)
+ (hhost : ∀ i, work (host i) = RootInit.template c r w v den
+ (Replacement.workBank w (digits w old) (Submatrix.workBank [] [] (selectedRaw w v n m c pivot base d constants))) i)
+ (room : ∀ k, (state label current next result advice work k).length ≤ cap) :
+ ∃ ticks ≤ clock w, ∃ out : Stacks H, out scratch = [] ∧
+ (∀ i, out (host i) = RootInit.template c r w v den (Replacement.workBank w (digits w replace)
+ (Submatrix.workBank [] [] (selectedRaw w v n m c pivot base (TargetRead.setDynamic d source scale mark) constants))) i) ∧
+ (machine host selectedSlot src scratch).BoundedRun (cap+clock w) ticks
+ (state label current next result advice work) (state label current next result advice out) := by
+ let words := Sum.elim (fun _ : Unit ↦ digits w replace) (TargetRead.words w source scale mark)
+ have small (f : Field) : (words f).length ≤ w := by
+ rcases f with ⟨⟩ | j
+ · exact (length_digits w replace).le
+ · fin_cases j <;> exact (length_digits w _).le
+ obtain ⟨ticks, bound, run⟩ := machine_bounded host selectedSlot src scratch w cap label current next result
+ advice work words apart hs hd empty live small
+ (fun f => (selected_destination_length w v n m r c host den pivot base d constants old work hhost f).le) room
+ exact ⟨ticks, bound, _, (installStacks_outside work words hd).trans empty,
+ selected_host_after w v n m r c host den pivot base d constants old replace source scale mark work hhost, run⟩
+
+variable [Fact p.Prime]
+
+/-- The two updated root inputs meet their exact readiness predicates. On the
+direct-reader sum, the base reader is ready and the powered reader has its
+specified monomial, scale, and mark. -/
+theorem selected_root_ready (w v n m r : ℕ) (c : Vector p e) (hr : r < 2^w)
+ {denReady : Stacks D → Prop} {baseReady : Stacks Base → Prop} (den : Stacks D) (hden : denReady den)
+ (pivot : Stacks K) (base : Stacks Base) (hbase : baseReady base)
+ (d : PairCall.Inputs) (replace source scale mark : ℕ) :
+ let dyn := TargetRead.setDynamic d source scale mark
+ let raw := selectedRaw w v n m c pivot base dyn (TargetRead.literal c v)
+ let directReady (s : Stacks (Base ⊕ TargetRead.Work)) :=
+ baseReady (s ∘ Sum.inl) ∧ TargetRead.Ready c w v dyn (s ∘ Sum.inr)
+ let num := Replacement.workBank w (digits w replace) (Submatrix.workBank [] [] raw)
+ GramEngine.Ready w v r r c denReady (GramEngine.initial w v r r c den) ∧
+ GramEngine.Ready w v r r c (Replacement.Ready w replace (Submatrix.Ready (SelectedMinor.Ready w v n m c pivot directReady)))
+ (GramEngine.initial w v r r c num) := by
+ apply root_ready c r w v hr den hden
+ apply SelectedMinor.initial_ready
+ exact ⟨hbase, rfl⟩
+
+end RankQuery.Stack.Coordinate.ArgumentStage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateArgumentStage.lean b/lean/OAI/Computability/VPVNP/RankCoordinateArgumentStage.lean
new file mode 100644
index 0000000000..4a46228fa4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateArgumentStage.lean
@@ -0,0 +1,270 @@
+import OAI.Computability.VPVNP.RankCoordinateDynamic
+import OAI.Computability.VPVNP.RankCoordinateRootInit
+import OAI.Computability.VPVNP.RankCoordinateReplacement
+import OAI.Computability.VPVNP.RankCoordinateTargetPorts
+import OAI.Computability.VPVNP.RankCoordinateNativeReader
+
+/-!
+# Installing the live Cramer query into its paired root banks
+
+The four copied words are the replacement ordinal, the original monomial
+index, the one-based label mark, and the target power scale. The first two
+come from the greedy selector's binary register bank. Every write is to a
+scalar-reader port of the numerator. Both roots, the arithmetic field advice,
+and the entire denominator reader retain their initialized contents.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.ArgumentStage
+
+open RAMTape UniversalCountStack SliceArithmetic NativeReader
+open RadicalCertificate.MonomialIndex
+
+/-- The four live Cramer arguments consist of a replacement-row index and three target-row
+words. -/
+abbrev Field := Unit ⊕ Fin 3
+/-- The numerator workspace compares the row index and then reads either the original submatrix
+or the replacement row. -/
+abbrev Num (K : Type) := Replacement.Work (Submatrix.Work K)
+
+variable {A H K D T : Type}
+
+/-- The comparison register and the three independent inputs of the target reader. -/
+def numSlot (target : Fin 3 ↪ K) : Field ↪ Num K where
+ toFun := Sum.elim (fun _ ↦ .inl (.reg 1)) (fun i ↦ .inr (.aux (target i)))
+ inj' := by
+ rintro (⟨⟩ | i) (⟨⟩ | j) h <;> simp_all [target.injective.eq_iff]
+
+/-- Actual physical destination of each word in the paired roots. -/
+def destination (host : RootInit.RootHost D (Num K) ↪ H) (target : Fin 3 ↪ K) : Field ↪ H where
+ toFun := host ∘ RootInit.readerPort ∘ Sum.inr ∘ numSlot target
+ inj' := host.injective.comp (RootInit.readerPort_injective.comp
+ (Sum.inr_injective.comp (numSlot target).injective))
+
+/-- Place a working stack on the auxiliary side of the coordinate callback's bus. -/
+def workPort (h : H) : Bus A H := .aux (.inr h)
+
+private theorem workPort_injective : Function.Injective (workPort (A := A) (H := H)) :=
+ fun _ _ h ↦ Sum.inr.inj (Reader.Port.aux.inj h)
+
+/-- Offsets five and seven are the two outputs of `Dynamic.machine`. The mark
+and scale may have independent advice or runtime source ports. -/
+def sources (dyn : Dynamic.Host T ↪ H) (mark scale : Bus A H) : Field → Bus A H :=
+ Sum.elim (fun _ ↦ workPort (dyn (.inl (.reg 5)))) ![workPort (dyn (.inl (.reg 7))), mark, scale]
+
+/-- Only two dynamic registers are read during transport, so other registers
+can be aliased to the enclosing evaluator's public ports. -/
+theorem source_words_at {addr : ℕ} (dyn : Dynamic.Host T ↪ H) (mark scale : Bus A H)
+ (label current next result : List Bool) (advice : Stacks A) (work : Stacks H)
+ (offNext mono marked power : ℕ)
+ (hnext : work (dyn (.inl (.reg 5))) = digits addr offNext)
+ (hmono : work (dyn (.inl (.reg 7))) = digits addr mono)
+ (hm : state label current next result advice work mark = digits addr marked)
+ (hs : state label current next result advice work scale = digits addr power) :
+ ∀ f, state label current next result advice work (sources dyn mark scale f) =
+ Sum.elim (fun _ : Unit ↦ digits addr offNext) (TargetRead.words addr mono power marked) f := by
+ rintro (⟨⟩ | i)
+ · exact hnext
+ · fin_cases i
+ · exact hmono
+ · exact hm
+ · exact hs
+
+theorem source_words {addr : ℕ} (dyn : Dynamic.Host T ↪ H) (mark scale : Bus A H)
+ (label current next result : List Bool) (advice : Stacks A) (work : Stacks H)
+ (aux : Stacks T) (u v rank rows offCur offNext original mono marked power : ℕ)
+ (hr : ∀ i, work (dyn i) = Dynamic.bank aux (Dynamic.regs (w := addr) u v rank rows offCur offNext original mono) i)
+ (hm : state label current next result advice work mark = digits addr marked)
+ (hs : state label current next result advice work scale = digits addr power) :
+ ∀ f, state label current next result advice work (sources dyn mark scale f) =
+ Sum.elim (fun _ : Unit ↦ digits addr offNext) (TargetRead.words addr mono power marked) f := by
+ exact source_words_at dyn mark scale label current next result advice work offNext mono marked power
+ (hr (.inl (.reg 5))) (hr (.inl (.reg 7))) hm hs
+
+private noncomputable def plan (dst : Field ↪ H) (src : Field → Bus A H) : List (Bus A H × Bus A H) :=
+ Finset.univ.toList.map fun f ↦ (src f, workPort (dst f))
+
+/-- Clear the four template words and copy their replacements with one shared
+scratch stack. The control is independent of the values and address width. -/
+noncomputable def machine
+ (host : RootInit.RootHost D (Num K) ↪ H) (target : Fin 3 ↪ K) (src : Field → Bus A H) (scratch : H) :
+ FiniteRoutine (Bus A H) :=
+ let ps := plan (destination host target) src
+ (CallClear.cleanup (ps.map Prod.snd)).followedBy (CallCopies.copyPlan (workPort scratch) ps)
+
+/-- Bound the steps to clear and copy all four argument words of the given width. -/
+def clock (width : ℕ) : ℕ := (4*(width+1)+1) + (4*(5*width+2)+1)
+
+private theorem valid (dst : Field ↪ H) (src : Field → Bus A H) (scratch : H)
+ (apart : ∀ f g, src f ≠ workPort (dst g)) (hs : ∀ f, src f ≠ workPort scratch)
+ (hd : ∀ f, dst f ≠ scratch) : CallCopies.Valid (workPort scratch) (plan dst src) := by
+ simp only [CallCopies.Valid, plan, List.map_map, Function.comp_def]
+ refine ⟨(Finset.nodup_toList _).map (workPort_injective.comp dst.injective), ?_, ?_, ?_⟩
+ · rintro _ hk hdest
+ obtain ⟨f, _, rfl⟩ := List.mem_map.mp hk
+ obtain ⟨g, _, hg⟩ := List.mem_map.mp hdest
+ exact apart f g hg.symm
+ · rintro hk
+ obtain ⟨f, _, hf⟩ := List.mem_map.mp hk
+ exact hs f hf
+ · rintro hk
+ obtain ⟨f, _, hf⟩ := List.mem_map.mp hk
+ exact hd f (workPort_injective hf)
+
+variable [DecidableEq A] [DecidableEq H]
+
+theorem machine_bounded (host : RootInit.RootHost D (Num K) ↪ H) (target : Fin 3 ↪ K)
+ (src : Field → Bus A H) (scratch : H) (width cap : ℕ)
+ (label current next result : List Bool) (advice : Stacks A) (work : Stacks H) (values : Stacks Field)
+ (apart : ∀ f g, src f ≠ workPort (destination host target g))
+ (hs : ∀ f, src f ≠ workPort scratch) (hd : ∀ f, destination host target f ≠ scratch)
+ (empty : work scratch = [])
+ (hvalues : ∀ f, state label current next result advice work (src f) = values f)
+ (small : ∀ f, (values f).length ≤ width)
+ (old : ∀ f, (work (destination host target f)).length ≤ width)
+ (room : ∀ k, (state label current next result advice work k).length ≤ cap) :
+ ∃ t ≤ clock width, (machine host target src scratch).BoundedRun (cap+clock width) t
+ (state label current next result advice work)
+ (state label current next result advice (installStacks (destination host target) work values)) := by
+ let dst := destination host target
+ let ps := plan dst src
+ let start := state label current next result advice work
+ let middle := CallClear.erased (ps.map Prod.snd) start
+ let finish := state label current next result advice (installStacks dst work values)
+ have ok := valid dst src scratch apart hs hd
+ have plen : ps.length = 4 := by simp [ps, plan, Field]
+ obtain ⟨a, ha, clear⟩ := CallClear.cleanup_runs (ps.map Prod.snd) start width (by
+ simp only [ps, plan, List.map_map, Function.comp_def, List.mem_map]
+ rintro _ ⟨f, _, rfl⟩; exact old f)
+ have raw (f : Field) : middle (src f) = values f := by
+ have mem : src f ∈ ps.map Prod.fst := by simp [ps, plan, List.map_map, Function.comp_def, List.mem_map]
+ rw [show middle (src f) = start (src f) from ite_eq_right (ok.2.1 _ mem)]
+ exact hvalues f
+ have tmp : middle (workPort scratch) = [] := by
+ rw [show middle (workPort scratch) = start (workPort scratch) from ite_eq_right ok.2.2.2]
+ exact empty
+ obtain ⟨b, hb, cp⟩ := CallCopies.copyPlan_runs (workPort scratch) ps middle width ok tmp (by
+ intro pair hpair; exact ite_eq_left (List.mem_map.mpr ⟨pair, hpair, rfl⟩)) (by
+ intro pair hpair; obtain ⟨f, _, rfl⟩ := List.mem_map.mp hpair; exact (raw f) ▸ small f)
+ have hfinish : CallCopies.copied ps middle = finish := by
+ funext k
+ by_cases h : ∃ f, workPort (A := A) (dst f) = k
+ · obtain ⟨f, rfl⟩ := h
+ rw [CallCopies.copied_at _ _ ok.1 (show (src f, workPort (dst f)) ∈ ps from
+ List.mem_map.mpr ⟨f, by simp, rfl⟩), raw]
+ exact (installStacks_at dst.injective work values f).symm
+ · have absent : k ∉ ps.map Prod.snd := by
+ simp only [ps, plan, List.map_map, Function.comp_def, List.mem_map]
+ rintro ⟨f, _, he⟩; exact h ⟨f, he⟩
+ rw [CallCopies.copied_outside _ _ _ absent, show middle k = start k from ite_eq_right absent]
+ cases k with
+ | label | current | next | result => rfl
+ | aux i =>
+ cases i with
+ | inl => rfl
+ | inr j =>
+ exact (installStacks_outside work values fun f hf ↦ h ⟨f, congrArg workPort hf⟩).symm
+ rw [hfinish] at cp
+ have htime : a+b ≤ clock width := by
+ rw [List.length_map, plen] at ha
+ rw [plen] at hb
+ exact Nat.add_le_add ha hb
+ exact ⟨a+b, htime, spaceRun_of_steps (clear.followedBy cp) fun k ↦ Nat.add_le_add (room k) htime⟩
+
+/-- Install a smaller bank through a larger port embedding. This characterizes
+the returned bank both on and off the four written stacks. -/
+private theorem install_comp {X Y Z : Type} (x : X → Y) (y : Y → Z)
+ (hx : Function.Injective x) (hy : Function.Injective y) (s : Stacks Z) (v : Stacks X) :
+ installStacks (y ∘ x) s v = installStacks y s (installStacks x (s ∘ y) v) := by
+ apply (installStacks_frame hy ?_ ?_).symm
+ · intro k
+ by_cases h : ∃ j, x j = k
+ · obtain ⟨j, rfl⟩ := h
+ exact (installStacks_at (hy.comp hx) s v j).trans (installStacks_at hx (s ∘ y) v j).symm
+ · rw [installStacks_outside (ports := y ∘ x) s v (fun j he ↦ h ⟨j, hy he⟩),
+ installStacks_outside (s ∘ y) v (not_exists.mp h)]
+ rfl
+ · intro k hout
+ exact installStacks_outside s v fun j ↦ hout (x j)
+
+/-- The four updates change precisely the replacement ordinal and the target
+reader's own raw-bank slots, leaving the two submatrix index stacks empty. -/
+theorem num_bank_after (target : Fin 3 ↪ K) (w : ℕ) (old new : List Bool)
+ (raw : Stacks K) (words : Stacks (Fin 3)) :
+ installStacks (numSlot target) (Replacement.workBank w old (Submatrix.workBank [] [] raw))
+ (Sum.elim (fun _ : Unit ↦ new) words) =
+ Replacement.workBank w new (Submatrix.workBank [] [] (installStacks target raw words)) := by
+ apply installStacks_frame (numSlot target).injective
+ · rintro (⟨⟩|i)
+ · rfl
+ · exact installStacks_at target.injective raw words i
+ · rintro (p|p) hout
+ · cases p with
+ | reg j => fin_cases j <;> first | rfl | exact (hout (.inl ()) rfl).elim
+ | _ => rfl
+ · cases p with
+ | row | col => rfl
+ | aux k =>
+ exact installStacks_outside raw words (fun i hi ↦
+ hout (.inr i) (congrArg (fun j : K ↦ (Sum.inr (.aux j) : Num K)) hi))
+
+omit [DecidableEq H] in
+/-- If the template has already been loaded, the entire paired host now sees
+the correct updated root banks. Static denominator inputs survive unchanged. -/
+theorem host_after {p e : ℕ} (c : Vector p e) (r addr v : ℕ)
+ (host : RootInit.RootHost D (Num K) ↪ H) (target : Fin 3 ↪ K)
+ (den : Stacks D) (raw : Stacks K) (old new : List Bool) (words : Stacks (Fin 3))
+ (work : Stacks H) (hhost : ∀ i, work (host i) = RootInit.template c r addr v den
+ (Replacement.workBank addr old (Submatrix.workBank [] [] raw)) i) (i : RootInit.RootHost D (Num K)) :
+ installStacks (destination host target) work (Sum.elim (fun _ : Unit ↦ new) words) (host i) =
+ RootInit.template c r addr v den
+ (Replacement.workBank addr new (Submatrix.workBank [] [] (installStacks target raw words))) i := by
+ let num := Replacement.workBank addr old (Submatrix.workBank [] [] raw)
+ let incoming : Stacks Field := Sum.elim (fun _ : Unit ↦ new) words
+ let routes : D ⊕ Num K → H := host ∘ RootInit.readerPort
+ have stored : work ∘ routes = Sum.elim den num := by
+ funext j
+ cases j <;> exact hhost (RootInit.readerPort _)
+ have update : installStacks (Sum.inr ∘ numSlot target) (Sum.elim den num) incoming =
+ Sum.elim den (Replacement.workBank addr new (Submatrix.workBank [] [] (installStacks target raw words))) := by
+ rw [install_comp (numSlot target) Sum.inr (numSlot target).injective Sum.inr_injective]
+ change installStacks Sum.inr (Sum.elim den num) (installStacks (numSlot target) num incoming) = _
+ rw [num_bank_after]
+ funext j
+ rcases j with j|j
+ · exact installStacks_outside _ _ fun _ he ↦ by cases he
+ · exact installStacks_at Sum.inr_injective ..
+ change installStacks (routes ∘ (Sum.inr ∘ numSlot target)) work incoming (host i) = _
+ rw [install_comp (Sum.inr ∘ numSlot target) routes (Sum.inr_injective.comp (numSlot target).injective)
+ (host.injective.comp RootInit.readerPort_injective), stored, update]
+ exact RootInit.setReaders_mounted host work c r addr v den den num _ hhost i
+
+/-- Readiness of the updated numerator and denominator after the exact word
+copies. Only the raw reader's own ready predicate is needed here. -/
+theorem root_ready {p e : ℕ} (c : Vector p e) (r addr v : ℕ) (hr : r < 2^addr)
+ {denReady : Stacks D → Prop} {rawReady : Stacks K → Prop} (den : Stacks D) (hd : denReady den)
+ (raw : Stacks K) (hw : rawReady raw) (replace : ℕ) :
+ let num := Replacement.workBank addr (digits addr replace) (Submatrix.workBank [] [] raw)
+ GramEngine.Ready addr v r r c denReady (GramEngine.initial addr v r r c den) ∧
+ GramEngine.Ready addr v r r c (Replacement.Ready addr replace (Submatrix.Ready rawReady))
+ (GramEngine.initial addr v r r c num) :=
+ RootInit.template_ready c r addr v hr den _ hd ⟨_, ⟨raw, hw, rfl⟩, rfl⟩
+
+/-- Mount the concrete three target words inside any containing raw workspace.
+Every unmounted raw-reader port retains the old value. -/
+theorem target_bank_after (mount : TargetRead.Work ↪ K) (w : ℕ)
+ (d : PairCall.Inputs) (constants : Bool → List Bool) (source scale mark : ℕ) (raw : Stacks K)
+ (hraw : raw ∘ mount = TargetRead.bank w d constants) :
+ installStacks (mount ∘ TargetRead.slot) raw (TargetRead.words w source scale mark) =
+ installStacks mount raw (TargetRead.bank w (TargetRead.setDynamic d source scale mark) constants) := by
+ rw [install_comp TargetRead.slot mount TargetRead.slot.injective mount.injective, hraw,
+ TargetRead.stage_dynamic]
+
+end RankQuery.Stack.Coordinate.ArgumentStage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateBanks.lean b/lean/OAI/Computability/VPVNP/RankCoordinateBanks.lean
new file mode 100644
index 0000000000..13ddf34474
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateBanks.lean
@@ -0,0 +1,215 @@
+import OAI.Computability.VPVNP.RankCoordinateOrdinal
+
+/-!
+# Installing ordinal and scalar readers in disjoint auxiliary banks
+
+The public address and result ports are shared with the caller. An injective
+map places only the reader's auxiliary stacks in a selected part of the host
+bank. A call updates that part in place and preserves every exterior stack,
+including the data used by the other coordinate readers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.FiniteRoutine
+
+variable {K L : Type} [DecidableEq K] [DecidableEq L]
+
+/-- A framed call needs a separate input-size bound only on the exterior
+ports. The callee's bounded run already covers every port in its image. -/
+theorem BoundedRun.framed_exterior {r : FiniteRoutine K} {ports : K → L} (hp : Function.Injective ports)
+ {S A t : ℕ} {s u : Stacks L} {small out : Stacks K} (run : r.BoundedRun S t small out)
+ (ext : ∀ j, (∀ i, ports i ≠ j) → (s j).length ≤ A)
+ (hin : ∀ i, s (ports i) = small i) (hu : ∀ i, u (ports i) = out i)
+ (hout : ∀ j, (∀ i, ports i ≠ j) → u j = s j) : (r.onPorts ports).BoundedRun (max S A) t s u := by
+ have h := FiniteRoutine.BoundedRun.onPorts (a := r) hp s (run.enlarge (Nat.le_max_left S A))
+ (fun j hj => (ext j hj).trans (Nat.le_max_right S A))
+ rwa [installStacks_frame hp hin (fun _ _ => rfl), installStacks_frame hp hu hout] at h
+
+end RAMTape.FiniteRoutine
+
+namespace RankQuery.Stack
+
+open RAMTape
+
+namespace OrdinalRead
+
+variable {K L : Type}
+
+/-- Rename the auxiliary ports while retaining the ordinal and result words. -/
+def auxPorts (E : K → L) : Port K → Port L
+ | .input => .input
+ | .result => .result
+ | .aux k => .aux (E k)
+
+/-- Mount an ordinal reader on a new auxiliary bank while retaining its public input and result
+ports. -/
+def onAux (E : K → L) (read : FiniteRoutine (Port K)) := read.onPorts (auxPorts E)
+
+private theorem auxPorts_injective {E : K → L} (hE : Function.Injective E) :
+ Function.Injective (auxPorts E) := by
+ intro x y h
+ cases x <;> cases y <;> simp_all [auxPorts, hE.eq_iff]
+
+theorem CorrectSpace.onAux [DecidableEq K] [DecidableEq L] {r n w B S A : ℕ}
+ {read : FiniteRoutine (Port K)} {g : Fin r → Fin n} {smallReady : Stacks K → Prop} {ready : Stacks L → Prop}
+ (hc : CorrectSpace read g w B S smallReady) (E : K → L) (hE : Function.Injective E)
+ (project : ∀ s, ready s → smallReady (s ∘ E))
+ (preserve : ∀ s out, ready s → smallReady out → ready (installStacks E s out))
+ (exterior : ∀ s, ready s → ∀ j, (∀ i, E i ≠ j) → (s j).length ≤ A) :
+ CorrectSpace (OrdinalRead.onAux E read) g w B (max S A) ready := by
+ intro i s hs
+ obtain ⟨t, ht, out, ho, run⟩ := hc i (s ∘ E) (project s hs)
+ refine ⟨t, ht, installStacks E s out, preserve s out hs ho, ?_⟩
+ apply FiniteRoutine.BoundedRun.framed_exterior (auxPorts_injective hE) run
+ · intro k hk
+ cases k with
+ | input => exact (hk .input rfl).elim
+ | result => exact (hk .result rfl).elim
+ | aux j => exact exterior s hs j (fun a h => hk (.aux a) (congrArg Port.aux h))
+ · intro k; cases k <;> rfl
+ · intro k
+ cases k with
+ | aux a => exact installStacks_at hE s out a
+ | _ => rfl
+ · intro k hk
+ cases k with
+ | aux j => exact installStacks_outside s out (fun a h => hk (.aux a) (congrArg Port.aux h))
+ | input => rfl
+ | result => exact (hk .result rfl).elim
+
+end OrdinalRead
+
+namespace MacaulayRead
+
+variable {K L : Type}
+
+/-- The row and column words and the result stay at their original public ports. -/
+def auxPorts (E : K → L) : Port K → Port L
+ | .row => .row
+ | .col => .col
+ | .result => .result
+ | .aux k => .aux (E k)
+
+/-- Mount a Macaulay entry reader on a new auxiliary bank while retaining its row, column, and
+result ports. -/
+def onAux (E : K → L) (read : FiniteRoutine (Port K)) := read.onPorts (auxPorts E)
+
+private theorem auxPorts_injective {E : K → L} (hE : Function.Injective E) :
+ Function.Injective (auxPorts E) := by
+ intro x y h
+ cases x <;> cases y <;> simp_all [auxPorts, hE.eq_iff]
+
+theorem CorrectSpace.onAux [DecidableEq K] [DecidableEq L] {p e n m w v B S A : ℕ}
+ {c : SliceArithmetic.Vector p e} {read : FiniteRoutine (Port K)} {M : Matrix (Fin n) (Fin m) (Scalar c)}
+ {smallReady : Stacks K → Prop} {ready : Stacks L → Prop}
+ (hc : CorrectSpace read M w v B S smallReady) (E : K → L) (hE : Function.Injective E)
+ (project : ∀ s, ready s → smallReady (s ∘ E))
+ (preserve : ∀ s out, ready s → smallReady out → ready (installStacks E s out))
+ (exterior : ∀ s, ready s → ∀ j, (∀ i, E i ≠ j) → (s j).length ≤ A) :
+ CorrectSpace (MacaulayRead.onAux E read) M w v B (max S A) ready := by
+ intro i j s hs
+ obtain ⟨t, ht, out, ho, run⟩ := hc i j (s ∘ E) (project s hs)
+ refine ⟨t, ht, installStacks E s out, preserve s out hs ho, ?_⟩
+ apply FiniteRoutine.BoundedRun.framed_exterior (auxPorts_injective hE) run
+ · intro k hk
+ cases k with
+ | row => exact (hk .row rfl).elim
+ | col => exact (hk .col rfl).elim
+ | result => exact (hk .result rfl).elim
+ | aux j => exact exterior s hs j (fun a h => hk (.aux a) (congrArg Port.aux h))
+ · intro k; cases k <;> rfl
+ · intro k
+ cases k with
+ | aux a => exact installStacks_at hE s out a
+ | _ => rfl
+ · intro k hk
+ cases k with
+ | aux j => exact installStacks_outside s out (fun a h => hk (.aux a) (congrArg Port.aux h))
+ | row | col => rfl
+ | result => exact (hk .result rfl).elim
+
+end MacaulayRead
+
+namespace Coordinate.ThreeBanks
+
+variable {X Y Z : Type}
+
+/-- A disjoint union of three auxiliary stack banks allows the readers to keep their own
+working data. -/
+abbrev Host (X Y Z : Type) := X ⊕ Y ⊕ Z
+
+/-- Place a port in the first of the three disjoint banks. -/
+def left (x : X) : Host X Y Z := .inl x
+/-- Place a port in the second bank, separated from the first and third reader workspaces. -/
+def middle (y : Y) : Host X Y Z := .inr (.inl y)
+/-- Place a port in the third of the three disjoint banks. -/
+def right (z : Z) : Host X Y Z := .inr (.inr z)
+
+theorem left_injective : Function.Injective (left (X := X) (Y := Y) (Z := Z)) := Sum.inl_injective
+theorem middle_injective : Function.Injective (middle (X := X) (Y := Y) (Z := Z)) :=
+ Sum.inr_injective.comp Sum.inl_injective
+theorem right_injective : Function.Injective (right (X := X) (Y := Y) (Z := Z)) :=
+ Sum.inr_injective.comp Sum.inr_injective
+
+/-- Independent readiness of the two selectors and the scalar reader. -/
+def Ready (rx : Stacks X → Prop) (ry : Stacks Y → Prop) (rz : Stacks Z → Prop) (s : Stacks (Host X Y Z)) : Prop :=
+ rx (s ∘ left) ∧ ry (s ∘ middle) ∧ rz (s ∘ right)
+
+variable {rx : Stacks X → Prop} {ry : Stacks Y → Prop} {rz : Stacks Z → Prop} {s : Stacks (Host X Y Z)}
+
+theorem project_left (hs : Ready rx ry rz s) : rx (s ∘ left) := hs.1
+theorem project_middle (hs : Ready rx ry rz s) : ry (s ∘ middle) := hs.2.1
+theorem project_right (hs : Ready rx ry rz s) : rz (s ∘ right) := hs.2.2
+
+private theorem project_install {K L : Type} {E : K → L} (hp : Function.Injective E)
+ (base : Stacks L) (out : Stacks K) : installStacks E base out ∘ E = out :=
+ funext (installStacks_at hp base out)
+
+private theorem project_other {K L J : Type} {E : K → L} {F : J → L}
+ (sep : ∀ i j, E i ≠ F j) (base : Stacks L) (out : Stacks K) :
+ installStacks E base out ∘ F = base ∘ F :=
+ funext fun j => installStacks_outside base out fun i => sep i j
+
+theorem preserve_left (hs : Ready rx ry rz s) {out : Stacks X} (ho : rx out) :
+ Ready rx ry rz (installStacks left s out) := by
+ unfold Ready
+ rw [project_install left_injective,
+ project_other (E := left) (F := middle) (fun _ _ h => by cases h),
+ project_other (E := left) (F := right) (fun _ _ h => by cases h)]
+ exact ⟨ho, hs.2⟩
+
+theorem preserve_middle (hs : Ready rx ry rz s) {out : Stacks Y} (ho : ry out) :
+ Ready rx ry rz (installStacks middle s out) := by
+ unfold Ready
+ rw [project_install middle_injective,
+ project_other (E := middle) (F := left) (fun _ _ h => by cases h),
+ project_other (E := middle) (F := right) (fun _ _ h => by cases h)]
+ exact ⟨hs.1, ho, hs.2.2⟩
+
+theorem preserve_right (hs : Ready rx ry rz s) {out : Stacks Z} (ho : rz out) :
+ Ready rx ry rz (installStacks right s out) := by
+ unfold Ready
+ rw [project_install right_injective,
+ project_other (E := right) (F := left) (fun _ _ h => by cases h),
+ project_other (E := right) (F := middle) (fun _ _ h => by cases h)]
+ exact ⟨hs.1, hs.2.1, ho⟩
+
+/-- A common component cap bounds every exterior stack of each mounted call. -/
+theorem length_le {A : ℕ} (hx : ∀ b, rx b → ∀ k, (b k).length ≤ A)
+ (hy : ∀ b, ry b → ∀ k, (b k).length ≤ A) (hz : ∀ b, rz b → ∀ k, (b k).length ≤ A)
+ (hs : Ready rx ry rz s) (k : Host X Y Z) : (s k).length ≤ A := by
+ rcases k with k | k | k
+ · exact hx _ hs.1 k
+ · exact hy _ hs.2.1 k
+ · exact hz _ hs.2.2 k
+
+end Coordinate.ThreeBanks
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateCanonicalReader.lean b/lean/OAI/Computability/VPVNP/RankCoordinateCanonicalReader.lean
new file mode 100644
index 0000000000..035b9629f8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateCanonicalReader.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.RankCoordinatePlannedReads
+import OAI.Computability.VPVNP.RankCoordinateSelectedPrepare
+import OAI.Computability.VPVNP.RankQueryPrepareResources
+
+/-! # A fixed coordinate callback for both operations of the evaluator
+
+Starting from the raw indexed relation-entry reader, the installed program
+performs pivot selection, computes the live target row, executes the two
+determinants, divides their outputs and reclaims its workspace. Both operation
+tables use the same advice and the same uniform clock and storage bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace RankQuery.Stack.Coordinate.CanonicalReader
+
+open RAMTape BurstRAM UniversalCountStack SliceArithmetic
+open Cursor
+open RadicalCertificate.MonomialIndex RadicalCertificate.MonomialIndex.QueryData
+open Evaluator Evaluator.MatrixCallbacks ConcreteResources SliceMinors NativeReader
+
+variable {K F : Type} [DecidableEq K] [Fintype K]
+
+/-- Decide equality of prefix-scan ports using the Gram engine's scan-port representation. -/
+local instance : DecidableEq (PrefixPort K) := inferInstanceAs (DecidableEq (ScanPort (GramEngine.Aux K)))
+/-- Decide equality of auxiliary ports used while computing the rank of a prefix. -/
+local instance : DecidableEq (PrefixWorkspace.Aux (PrefixPort K)) := fun a b => PrefixWorkspace.instDecidableEqAux a b
+/-- Compare addresses on one side of the selected-minor advice using their prefix-register
+representation. -/
+local instance : DecidableEq (SelectedAdvice.Side K) := inferInstanceAs (DecidableEq (PrefixWords.Port (PrefixWorkspace.Aux (PrefixPort K))))
+/-- Compare selected-minor ports by distinguishing the row bank, column bank, and scalar
+reader. -/
+local instance {J : Type} [DecidableEq J] : DecidableEq (SelectedMinor.Host K J) :=
+ inferInstanceAs (DecidableEq (SelectedAdvice.Side K ⊕ (SelectedAdvice.Side K ⊕ J)))
+/-- Compare working ports of the selected-minor reader using the underlying submatrix
+workspace. -/
+local instance {J : Type} [DecidableEq J] : DecidableEq (SelectedMinor.Work K J) := fun a b => Submatrix.instDecidableEqWork a b
+/-- Decide equality across the disjoint banks used to prepare a selected Cramer query. -/
+local instance : DecidableEq (SelectedAdvice.Parts K) := Prepare.partsDecidable
+
+variable [Fintype (SelectedAdvice.Parts K)]
+
+/-- Install the coordinate callback that prepares the two selected minors and divides their top
+Schur coefficients. The common determinant sign cancels, yielding the matrix entry with the
+next basis index as row and the current one as column. -/
+def program (read : FiniteRoutine (MacaulayRead.Port K)) (mode : Bool) :=
+ Reader.install (pairCore Prepare.root Prepare.scratch (SelectedAdvice.machine read mode)
+ (SelectedMinor.restrictEntry read read) (SelectedMinor.numerator read (ordinary read) powered))
+
+variable [Field F] [DecidableEq F] {p e t eqs d w v B A S : ℕ} [Fact p.Prime] [NeZero e]
+ [Algebra (ZMod p) F] {c : Vector p e} [Fact (Irreducible (modulus c))]
+ [DecidableEq (AdjoinRoot (modulus c))]
+
+set_option maxHeartbeats 1500000 in
+theorem readsEntryWithin (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (Q : QueryData t eqs F)
+ (dim : BurstRAM.Word w) (hdim : dim.val = Q.dimension) (op : Operation t)
+ (read : FiniteRoutine (MacaulayRead.Port K)) {ready : Stacks K → Prop}
+ (hc : MacaulayRead.CorrectSpace read (baseMatrix φ Q) w v B S ready)
+ (ha : ∀ a, ready a → ∀ k, (a k).length ≤ A) (base : Stacks K) (hr : ready base)
+ (hv : SliceArithmetic.Word.workingWidth p ≤ v) (fit : CanonicalFits Q d w v e A S B) :
+ let cost := preparedBudget (SelectedAdvice.Parts K) (SelectedAdvice.Work K) K
+ (height Q) (width Q) (order Q) d w v e B A S B t
+ ReadsEntryWithin φ dim (SelectedAdvice.selectedExtra c Q w v base) (program read (SelectedAdvice.mode op))
+ v (SelectedAdvice.label op) cost.time cost.space (fun i j => Q.matrixEntry op (Fin.cast hdim j) (Fin.cast hdim i)) := by
+ let minor := minorBudget K (height Q) (width Q) d w v e B A S B
+ let prep := prepareBudget (SelectedAdvice.Parts K) K (height Q) d w v e B A S t
+ let V := SelectedMinor.space K d w v e A S
+ let peak := pairPeak (order Q) w v e V minor.space prep.space
+ obtain ⟨hp,hq,hd⟩ := pairPeak_covers (order Q) w v e V minor.space prep.space
+ apply NativeReader.entry_reader (B := minor.time) (S := minor.space) (V := V) (prep := prep.time)
+ (peak := peak) Q φ dim hdim op (SelectedAdvice.label op) Prepare.root Prepare.scratch (fun _ => Sum.inl_ne_inr)
+ (SelectedAdvice.selectedAdvice c Q w v base) (SelectedAdvice.machine read (SelectedAdvice.mode op))
+ (SelectedMinor.restrictEntry read read) (SelectedMinor.numerator read (ordinary read) powered)
+ hv fit.widthThree fit.descriptorFit fit.depthFit fit.orderShape fit.orderBound fit.rootFit fit.childFit hq hd
+ intro i j
+ let cur := Fin.cast hdim i
+ let next := Fin.cast hdim j
+ let replace := combinedOrdinal Q.equations Q.monomials next
+ obtain ⟨dn,nu⟩ := native_reads_of_plan φ Q fit op cur next read hc ha base hr hv
+ obtain ⟨dc,nc⟩ := planned_ready_bounds (c := c) Q fit op cur ha base hr replace
+ obtain ⟨rd,rn⟩ := SelectedAdvice.prepared_root_ready c Q base hr fit.rowFit op cur next
+ have labelBound : SelectedAdvice.label op ≤ t := by cases op with | label i => exact i.isLt.le | frobenius => exact Nat.zero_le _
+ have labelFit : SelectedAdvice.label op+1 < 2^w := (Nat.add_le_add_right labelBound 1).trans_lt fit.labelFit
+ obtain ⟨u,hu,out,empty,roots,run⟩ := SelectedAdvice.prepare_bounded φ Q op cur next read hc ha base hr fit.rowShape fit.gramFit
+ hv fit.wordLive fit.arityLive fit.scalarLive labelFit
+ have cover := prepare_mode_covers (SelectedAdvice.Parts K) (SelectedAdvice.mode op) (SelectedAdvice.portBound K d w v e A S)
+ (max (SelectedAdvice.portBound K d w v e A S) t) (Select.scanTime K (height Q) d w v e B A S+OrdinalABI.overhead w)
+ (SelectedAdvice.selectorCap K d w v e A S) w labelBound
+ have input (j : Fin dim.val) : Reader.ordinal dim j = digits w (Fin.cast hdim j).val := by
+ unfold Reader.ordinal digits
+ apply congrArg wordBits
+ exact Fin.ext (Nat.mod_eq_of_lt (j.isLt.trans dim.isLt)).symm
+ rw [← input i,← input j] at run
+ exact ⟨{
+ denominator := denominator φ Q
+ numerator := numerator φ Q op cur next
+ denMatrix := denominator_map φ Q
+ numMatrix := numerator_map φ Q op cur next
+ denReady := _
+ numReady := _
+ denReads := dn
+ numReads := nu
+ denBound := dc
+ numBound := nc
+ work := out
+ scratchEmpty := empty
+ denAux := _
+ numAux := _
+ denInput := rd
+ numInput := rn
+ hostInput := roots
+ ticks := u
+ clock := hu.trans cover.1
+ run := run.enlarge (cover.2.trans hp)
+ }⟩
+
+end RankQuery.Stack.Coordinate.CanonicalReader
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateColumn.lean b/lean/OAI/Computability/VPVNP/RankCoordinateColumn.lean
new file mode 100644
index 0000000000..7fcbdf1fdb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateColumn.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.RankCoordinateDimension
+
+/-!
+# Selecting Cramer columns by scanning the original matrix
+
+Restricting row vectors to the first `s` coordinates is a linear map. Its
+image takes the full row span and the span of the greedy basis to the same
+space. Thus column-prefix ranks, including their first increases, can be
+queried in the original matrix independently of the selected row indices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+variable {K : Type*} [Field K] [DecidableEq K] {n m : ℕ}
+
+/-- Every column-prefix rank of the greedy row basis equals the corresponding
+rank queried directly on the transpose of the original matrix. -/
+theorem greedyRowBasis_columnPrefix_rank (A : Matrix (Fin n) (Fin m) K) (s : ℕ) (hs : s ≤ m) :
+ rankQuery (prefixRows (greedyRowBasis A).transpose s hs) =
+ rankQuery (prefixRows A.transpose s hs) := by
+ let restrict : (Fin m → K) →ₗ[K] (Fin s → K) := LinearMap.funLeft K K (Fin.castLE hs)
+ have h := congrArg (Submodule.map restrict) (greedyRowIndex_span A)
+ rw [Submodule.map_span, Submodule.map_span, ← Set.range_comp, ← Set.range_comp] at h
+ rw [rankQuery_eq (prefixRows (greedyRowBasis A).transpose s hs), rankQuery_eq (prefixRows A.transpose s hs),
+ Matrix.rank_eq_finrank_span_cols, Matrix.rank_eq_finrank_span_cols]
+ exact congrArg (fun S : Submodule K (Fin s → K) ↦ Module.finrank K S) h
+
+/-- Appendix D's columns of the selected-row matrix have the very same
+original indices as the independently selected greedy rows of the transpose. -/
+theorem coordinateColumns_greedyRowBasis (A : Matrix (Fin n) (Fin m) K) (i : Fin (rankQuery A)) :
+ coordinateColumns (greedyRowBasis A) (greedyRowBasis_fullRank A) i =
+ greedyRowIndex A.transpose (Fin.cast (by rw [rankQuery_eq, rankQuery_eq, Matrix.rank_transpose]) i) := by
+ let left := coordinateColumns (greedyRowBasis A) (greedyRowBasis_fullRank A) i
+ let right := greedyRowIndex A.transpose (Fin.cast (by rw [rankQuery_eq, rankQuery_eq, Matrix.rank_transpose]) i)
+ have before (s : ℕ) (hs : s ≤ m) : left.val < s ↔ right.val < s := by
+ dsimp only [left, right, coordinateColumns]
+ rw [greedyRowIndex_lt_iff _ _ s hs, greedyRowIndex_lt_iff _ _ s hs,
+ greedyRowBasis_columnPrefix_rank A s hs]
+ rfl
+ have hl := (before (right.val+1) right.isLt).mpr (Nat.lt_succ_self _)
+ have hr := (before (left.val+1) left.isLt).mp (Nat.lt_succ_self _)
+ apply Fin.ext
+ change left.val = right.val
+ omega
+
+/-- The Cramer query can use two independent base-matrix scans for its row
+and column index sets. -/
+theorem greedyCoordinateQuery_eq_baseColumns (A : Matrix (Fin n) (Fin m) K)
+ (target : Fin m → K) (i : Fin (rankQuery A)) :
+ greedyCoordinateQuery A target i = rowCoordinateQuery squareDetQuery (greedyRowBasis A)
+ (fun j ↦ greedyRowIndex A.transpose (Fin.cast
+ (by rw [rankQuery_eq, rankQuery_eq, Matrix.rank_transpose]) j)) target i := by
+ rw [greedyCoordinateQuery, coordinateQuery, funext (coordinateColumns_greedyRowBasis A)]
+
+/-- The sum defining the coordinate at a selected original row has one
+contributing ordinal. -/
+theorem originalRowCoordinate_at_greedy (A : Matrix (Fin n) (Fin m) K) (target : Fin m → K)
+ (k : Fin (rankQuery A)) :
+ originalRowCoordinate A target (greedyRowIndex A k) = greedyCoordinateQuery A target k := by
+ simp [originalRowCoordinate, streamSum_eq, greedyRowIndex_eq]
+
+open Stack.Coordinate (combinedOrdinal suffixBasisIndex_val)
+
+/-- The selected suffix row, expressed in the combined row indexing. -/
+theorem natAdd_suffixBasisIndex {w : ℕ} (W : Matrix (Fin w) (Fin m) K)
+ (M : Matrix (Fin n) (Fin m) K) (i : Fin (suffixDimension W M)) :
+ (suffixBasisIndex W M i).natAdd w = greedyRowIndex (appendRows W M) (combinedOrdinal W M i) := by
+ let ordinal := combinedOrdinal W M i
+ let g := greedyRowIndex (appendRows W M) ordinal
+ have before := greedyRowIndex_lt_iff (appendRows W M) ordinal w (Nat.le_add_right _ _)
+ have he : prefixRows (appendRows W M) w (Nat.le_add_right _ _) = W := by
+ ext j c
+ change appendRows W M (j.castAdd n) c = W j c
+ rw [appendRows_left]
+ rw [he] at before
+ have ge : w ≤ g.val := by
+ by_contra! h
+ have hl := before.mp h
+ change rankQuery W + i.val < rankQuery W at hl
+ omega
+ apply Fin.ext
+ change w + (suffixBasisIndex W M i).val = g.val
+ rw [suffixBasisIndex_val]
+ change w + (g.val - w) = g.val
+ omega
+
+/-- For a queried basis monomial, Cramer's row ordinal is the rank of the
+equation prefix plus its ordinal among the surviving monomials. -/
+theorem quotientCoordinate_at_suffix {w : ℕ} (W : Matrix (Fin w) (Fin m) K)
+ (M : Matrix (Fin n) (Fin m) K) (target : Fin m → K) (i : Fin (suffixDimension W M)) :
+ quotientCoordinate W M target (suffixBasisIndex W M i) =
+ greedyCoordinateQuery (appendRows W M) target (combinedOrdinal W M i) := by
+ rw [quotientCoordinate, natAdd_suffixBasisIndex, originalRowCoordinate_at_greedy]
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateCost.lean b/lean/OAI/Computability/VPVNP/RankCoordinateCost.lean
new file mode 100644
index 0000000000..4c6716ce41
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateCost.lean
@@ -0,0 +1,424 @@
+import OAI.Computability.VPVNP.RankQueryResourceBounds
+import OAI.Computability.VPVNP.RankQueryBoundedExecution
+import OAI.Computability.VPVNP.RankCoordinateCramer
+import OAI.Computability.VPVNP.MacaulayQueryBounds
+import OAI.Computability.VPVNP.RankQueryDescribeBounds
+import OAI.Computability.VPVNP.RankQueryStackGramSpace
+
+/-!
+# Fixed-depth resource bounds for Appendix D coordinate queries
+
+The augmented row count, its column count and its rank fit under a common
+binary size bound. The base scalar reader can have a singly exponential
+clock and polynomial stack height. The two prefix scans in a minor entry
+access the original matrix and its transpose. The determinant caller visits
+these entries one at a time. Repeated calls multiply clocks and share the
+maximum of their stack bounds.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.Cost
+
+/-- Time and peak height of a physical stack subroutine. -/
+structure Budget where
+ /-- Upper bound on the number of stack-machine instructions in the subroutine. -/
+ time : ℕ
+ /-- Upper bound on the peak height of its stacks during execution. -/
+ space : ℕ
+
+/-- The two subroutines use the same named bank and return at their boundaries. -/
+def Budget.thenRun (a b : Budget) : Budget := ⟨a.time+b.time, max a.space b.space⟩
+
+/-- A loop bound multiplies only the time. -/
+def Budget.repeated (a : Budget) (count : ℕ) : Budget := ⟨count*a.time, a.space⟩
+
+/-- Parameters common to the original rectangular matrix and its Cramer minors.
+`bits` bounds the logarithms of both original dimensions. `local` covers the
+short Schur actions and the fixed input/output adapters of each scalar read.
+`aux` is the maximum initial stack height at those boundaries. -/
+structure Parameters where
+ /-- Common bound on the binary logarithms of the original matrix dimensions. -/
+ bits : ℕ
+ /-- Bit width of addresses used for matrix entries and suspended frames. -/
+ addr : ℕ
+ /-- Bit width of one base-field coefficient in the packed scalar representation. -/
+ limb : ℕ
+ /-- Extension degree, hence the number of base-field coefficients in a scalar. -/
+ degree : ℕ
+ /-- Allowance for short Schur actions and the entry reader's setup and return steps. -/
+ localWork : ℕ
+ /-- Maximum initial height of auxiliary stacks at the reader's call boundaries. -/
+ aux : ℕ
+
+/-- Running a bounded number of sequential scalar reads within a descriptor,
+with short setup and teardown. The caller's suspended frames are included in
+its initial height. -/
+def descriptor (p : Parameters) (number : ℕ) (base : Budget) : Budget :=
+ let live := max 1 (max p.addr (p.degree*p.limb))
+ let frames := (p.bits+4+p.bits)*(2*live+1)
+ let initial := max (p.addr+p.limb+p.degree+p.degree*p.limb+p.aux) (max live frames)
+ ⟨number*base.time+p.localWork, max base.space initial + p.localWork⟩
+
+/-- A Gram entry requires at most two underlying rectangular entry reads. -/
+def gramDescriptor (p : Parameters) (base : Budget) := descriptor p 2 base
+
+/-- The actual weighted-Gram descriptor and all saved stack frames fit this
+budget whenever the short-action allowance covers its register overhead. -/
+theorem gramDescriptor_covers (p : Parameters) (base : Budget)
+ (hlocal : DescribeAdapter.clock p.addr p.limb p.degree 0 ≤ p.localWork) :
+ let start := GramEngine.entryCap p.addr p.limb p.degree p.aux (p.bits+4+p.bits)
+ DescribeAdapter.clock p.addr p.limb p.degree base.time ≤ (gramDescriptor p base).time ∧
+ max start (DescribeAdapter.space p.addr p.limb p.degree start base.space) ≤
+ (gramDescriptor p base).space := by
+ intro start
+ change _ ≤ 2*base.time+p.localWork ∧ _ ≤ max base.space start + p.localWork
+ rw [DescribeAdapter.clock_eq]
+ refine ⟨Nat.add_le_add_left hlocal _, max_le (by omega) ?_⟩
+ have h := DescribeAdapter.space_le_clock p.addr p.limb p.degree start base.space
+ omega
+
+/-- A constant-matrix descriptor reads one selected entry. Its signed-entry
+adapter may spend a short additional allowance. This checks the time and
+peak-height formulas of the actual Schur description routine. -/
+theorem singleDescriptor_covers (p : Parameters) (base : Budget) (extra : ℕ)
+ (hlocal : DescribeAdapter.timeWith p.addr p.limb p.degree extra ≤ p.localWork) :
+ let start := GramEngine.entryCap p.addr p.limb p.degree p.aux (p.bits+4+p.bits)
+ DescribeAdapter.timeWith p.addr p.limb p.degree (base.time+extra) ≤ (descriptor p 1 base).time ∧
+ max start (DescribeAdapter.peakWith p.addr p.limb p.degree start (fun a ↦ max a base.space+extra)) ≤
+ (descriptor p 1 base).space := by
+ intro start
+ change _ ≤ 1*base.time+p.localWork ∧ _ ≤ max base.space start + p.localWork
+ unfold DescribeAdapter.timeWith at hlocal ⊢
+ unfold DescribeAdapter.peakWith
+ dsimp only
+ rw [one_mul]
+ constructor
+ · omega
+ · apply max_le (by omega)
+ have h : max (start+Dispatch.Operation.describe.clock p.addr) base.space ≤
+ max base.space start + Dispatch.Operation.describe.clock p.addr := by omega
+ omega
+
+/-- Sum the dimension bit bound, the ceiling binary logarithm of descriptor time, the local
+work allowance, the address and limb widths, and the field extension degree to bound
+rank-query time. -/
+def rankScale (p : Parameters) (desc : Budget) :=
+ p.bits + Nat.clog 2 desc.time + p.localWork + p.addr + p.limb + p.degree
+
+/-- Common envelope for every rectangular prefix in either orientation. -/
+def rank (p : Parameters) (desc : Budget) : Budget :=
+ let s := rankScale p desc
+ ⟨2^((4*s+10)*(4*s+7)+5*s+20),
+ max (desc.space+1) (32768*(p.bits+p.aux+p.localWork+p.addr+p.limb+p.degree+1)^3)⟩
+
+/-- The actual clock and cap from the rectangular rank control fit the envelope. -/
+theorem rank_covers (p : Parameters) (desc : Budget) (rows cols : ℕ)
+ (hr : rows ≤ 2^p.bits) (hc : cols ≤ 2^p.bits) :
+ Cursor.boundedRankTime rows cols desc.time p.localWork p.addr p.limb p.degree ≤ (rank p desc).time ∧
+ Cursor.boundedRankSpace rows desc.space p.aux p.localWork p.addr p.limb p.degree ≤ (rank p desc).space := by
+ let s := rankScale p desc
+ have hpow {x : ℕ} (hx : x ≤ s) : x ≤ 2^s :=
+ Nat.lt_two_pow_self.le.trans (Nat.pow_le_pow_right (by decide) hx)
+ have hbits : 2^p.bits ≤ 2^s := Nat.pow_le_pow_right (by decide) (by dsimp [s, rankScale]; omega)
+ have hd : desc.time ≤ 2^s := (Nat.le_pow_clog (by decide) _).trans
+ (Nat.pow_le_pow_right (by decide) (by dsimp [s, rankScale]; omega))
+ refine ⟨Cursor.rankReadTime_le_exp _ _ _ _ _ _ _ s (hr.trans hbits) (hc.trans hbits) hd ?_ ?_ ?_ ?_,
+ Cursor.rankReadSpace_le rows _ _ _ _ _ _ _ hr⟩
+ all_goals apply hpow; dsimp [s, rankScale]; omega
+
+/-- Bound for one arithmetic register operation, with its initial word already in place. -/
+def arithmetic (p : Parameters) : Budget :=
+ ⟨arithmeticClock p.addr, p.addr+arithmeticClock p.addr⟩
+
+/-- The prefix tester computes the next length, requests its rank, compares with
+the ordinal, then advances its cursor. This is the clock of `PrefixWords.machine_runs`
+at the largest permitted prefix. -/
+def prefixScan (p : Parameters) (rankCall : Budget) : Budget :=
+ ⟨2^p.bits * ((arithmeticClock p.addr + rankCall.time + (20*p.addr+10)) + 1 + arithmeticClock p.addr),
+ max rankCall.space (arithmetic p).space⟩
+
+theorem prefixScan_covers (p : Parameters) (rankCall : Budget) (rows time : ℕ)
+ (hr : rows ≤ 2^p.bits) (ht : time ≤ rankCall.time) :
+ rows*((arithmeticClock p.addr+time+(20*p.addr+10))+1+arithmeticClock p.addr) ≤
+ (prefixScan p rankCall).time ∧ p.addr+arithmeticClock p.addr ≤ (prefixScan p rankCall).space := by
+ refine ⟨?_, le_max_right ..⟩
+ change rows*_ ≤ 2^p.bits*((arithmeticClock p.addr+rankCall.time+(20*p.addr+10))+1+arithmeticClock p.addr)
+ gcongr
+
+/-- Two independent rank calls followed by subtraction. -/
+def dimension (p : Parameters) (rankCall : Budget) : Budget :=
+ (rankCall.repeated 2).thenRun (arithmetic p)
+
+/-- Compute the combined ordinal, perform the row scan and remove the equation prefix. -/
+def suffix (p : Parameters) (rankCall : Budget) : Budget :=
+ ((rankCall.thenRun (arithmetic p)).thenRun (prefixScan p rankCall)).thenRun (arithmetic p)
+
+/-- Recompute the row and column indices independently, then read either
+the original entry or the replacement entry of the target row. -/
+def minorEntry (p : Parameters) (rankCall base : Budget) : Budget :=
+ ((prefixScan p rankCall).repeated 2).thenRun
+ ⟨(20*p.addr+10)+(base.time+1), max base.space (p.addr+(20*p.addr+10))⟩
+
+/-- A Schur determinant call on a minor, charging entry time and space separately. -/
+def determinant (p : Parameters) (desc : Budget) : Budget :=
+ let step := Engine.boundedStepTime desc.time p.localWork p.addr p.limb p.degree
+ ⟨2^((2*p.bits+8)*(2*p.bits+5))*step + 1,
+ Engine.boundedSpace desc.space p.aux (p.bits+4+p.bits) p.localWork p.addr p.limb p.degree⟩
+
+theorem determinant_covers (p : Parameters) (desc : Budget) (r : ℕ) (hr : r ≤ 2^p.bits) :
+ Cramer.SchurPair.clock r p.addr p.limb p.degree p.localWork desc.time ≤ (determinant p desc).time ∧
+ Cramer.SchurPair.space r p.addr p.limb p.degree p.localWork p.aux desc.space ≤ (determinant p desc).space := by
+ have hrec := SchurKey.clock_le_exp r r 0 p.bits hr hr (Nat.zero_le _)
+ have hd := Nat.clog_le_of_le_pow hr
+ refine ⟨Nat.add_le_add_right (Nat.mul_le_mul_right _ hrec) _, ?_⟩
+ dsimp [Cramer.SchurPair.space, Cramer.SchurPair.depth, determinant, Engine.boundedSpace, Engine.runSpace]
+ gcongr
+
+/-- The inverse and multiplication stage has polynomial clock and can pay this
+entire clock in space on top of its small input bank. -/
+def divide (p : Parameters) : Budget :=
+ let cost := Cramer.divideClock p.degree p.limb
+ ⟨cost, (p.degree+1)*(p.limb+1)+cost⟩
+
+/-- Reserve the quotient workspace already in the determinant contract. This
+makes the post-determinant room hypothesis of `Cramer.SchurPair.native_runs`
+hold even for a one-dimensional minor. -/
+def cramerDescriptor (p : Parameters) (desc : Budget) : Budget :=
+ ⟨desc.time, max desc.space (divide p).space⟩
+
+theorem cramer_room (p : Parameters) (desc : Budget) (r : ℕ) :
+ (p.degree+1)*(p.limb+1)+Cramer.divideClock p.degree p.limb ≤
+ Cramer.SchurPair.space r p.addr p.limb p.degree p.localWork p.aux (cramerDescriptor p desc).space := by
+ change (divide p).space ≤ max (max desc.space (divide p).space+1) _
+ exact ((le_max_right ..).trans (Nat.le_succ _)).trans (le_max_left ..)
+
+/-- Complete fixed-depth scalar query. The suffix lookup locates the input
+monomial. Its offset and the two prefix ranks also supply the output ordinal
+and dimension. Both determinant subcalls use the same per-entry envelope. -/
+def coordinate (p : Parameters) (base : Budget) : Budget :=
+ let rankCall := rank p (gramDescriptor p base)
+ let entries := minorEntry p rankCall base
+ let det := determinant p (cramerDescriptor p (descriptor p 1 entries))
+ let indices := ((dimension p rankCall).thenRun (suffix p rankCall)).thenRun (arithmetic p)
+ (indices.thenRun (det.repeated 2)).thenRun (divide p)
+
+/-- The joint determinant and division cost in the native Cramer theorem.
+The common cap also supplies room for division after both engines return. -/
+theorem cramer_covers (p : Parameters) (desc : Budget) (r : ℕ) (hr : r ≤ 2^p.bits) :
+ let bound := ((determinant p desc).repeated 2).thenRun (divide p)
+ 2*Cramer.SchurPair.clock r p.addr p.limb p.degree p.localWork desc.time +
+ Cramer.divideClock p.degree p.limb ≤ bound.time ∧
+ Cramer.SchurPair.space r p.addr p.limb p.degree p.localWork p.aux desc.space ≤ bound.space ∧
+ (p.degree+1)*(p.limb+1)+Cramer.divideClock p.degree p.limb ≤ bound.space := by
+ have ⟨ht, hs⟩ := determinant_covers p desc r hr
+ exact ⟨Nat.add_le_add_right (Nat.mul_le_mul_left _ ht) _,
+ hs.trans (le_max_left ..), le_max_right ..⟩
+
+/-- The ceiling of the base-two logarithm of the budget is eventually bounded by a polynomial
+in the input size. -/
+abbrev LogBound (f : ℕ → ℕ) := PolynomiallyBounded (fun n ↦ Nat.clog 2 (f n))
+
+/-- Any concrete matrix with these dimensions fits the common shape.
+The allowance includes the cost of formatting a weighted Gram entry. -/
+def forShape (rows cols addr limb degree other aux : ℕ) : Parameters :=
+ ⟨max (Nat.clog 2 rows) (Nat.clog 2 cols), addr, limb, degree,
+ max other (DescribeAdapter.allowance (max addr (max limb degree))), aux⟩
+
+theorem forShape_sizes (rows cols addr limb degree other aux : ℕ) :
+ let p := forShape rows cols addr limb degree other aux
+ rows ≤ 2^p.bits ∧ cols ≤ 2^p.bits ∧ DescribeAdapter.clock addr limb degree 0 ≤ p.localWork := by
+ refine ⟨(Nat.le_pow_clog (by decide) _).trans (Nat.pow_le_pow_right (by decide) (le_max_left ..)),
+ (Nat.le_pow_clog (by decide) _).trans (Nat.pow_le_pow_right (by decide) (le_max_right ..)), ?_⟩
+ exact (DescribeAdapter.overhead_le addr limb degree _ (le_max_left ..)
+ ((le_max_left ..).trans (le_max_right ..)) ((le_max_right ..).trans (le_max_right ..))).trans (le_max_right ..)
+
+/-- Feasible clocks and caps are measured on different scales. -/
+structure Feasible (f : ℕ → Budget) : Prop where
+ time : LogBound (fun n ↦ (f n).time)
+ space : PolynomiallyBounded (fun n ↦ (f n).space)
+
+/-- The word widths, logarithmic matrix shape, and short-action allowance
+are polynomially bounded in the input length. -/
+structure Small (p : ℕ → Parameters) : Prop where
+ bits : PolynomiallyBounded (fun n ↦ (p n).bits)
+ addr : PolynomiallyBounded (fun n ↦ (p n).addr)
+ limb : PolynomiallyBounded (fun n ↦ (p n).limb)
+ degree : PolynomiallyBounded (fun n ↦ (p n).degree)
+ localWork : PolynomiallyBounded (fun n ↦ (p n).localWork)
+ aux : PolynomiallyBounded (fun n ↦ (p n).aux)
+
+private theorem polyMax {f g : ℕ → ℕ} (hf : PolynomiallyBounded f) (hg : PolynomiallyBounded g) :
+ PolynomiallyBounded (fun n ↦ max (f n) (g n)) :=
+ (hf.add hg).of_le fun n ↦ by omega
+
+private theorem logMax {f g : ℕ → ℕ} (hf : LogBound f) (hg : LogBound g) :
+ LogBound (fun n ↦ max (f n) (g n)) :=
+ (PolynomiallyBounded.clog_add hf hg).of_le fun n ↦ Nat.clog_mono_right _ (by change max (f n) (g n) ≤ f n + g n; omega)
+
+private theorem logConst (k : ℕ) : LogBound (fun _ ↦ k) := (PolynomiallyBounded.const k).clog
+
+variable {p : ℕ → Parameters} {a b : ℕ → Budget}
+
+theorem Feasible.thenRun (ha : Feasible a) (hb : Feasible b) :
+ Feasible (fun n ↦ (a n).thenRun (b n)) :=
+ ⟨PolynomiallyBounded.clog_add ha.time hb.time, polyMax ha.space hb.space⟩
+
+theorem Feasible.repeated (ha : Feasible a) {f : ℕ → ℕ} (hf : LogBound f) :
+ Feasible (fun n ↦ (a n).repeated (f n)) :=
+ ⟨PolynomiallyBounded.clog_mul hf ha.time, ha.space⟩
+
+-- Close bounds formed by arithmetic on the supplied polynomial-size quantities.
+local macro "poly_bound" : tactic => `(tactic| repeat' first
+ | assumption
+ | exact PolynomiallyBounded.const _
+ | apply polyMax
+ | apply PolynomiallyBounded.add
+ | apply PolynomiallyBounded.mul
+ | apply PolynomiallyBounded.pow)
+
+theorem Feasible.of_exponent {f : ℕ → Budget} {e : ℕ → ℕ}
+ (he : PolynomiallyBounded e) (ht : ∀ n, (f n).time ≤ 2^(e n))
+ (hs : PolynomiallyBounded (fun n ↦ (f n).space)) : Feasible f :=
+ ⟨he.of_le (fun n ↦ Nat.clog_le_of_le_pow (ht n)), hs⟩
+
+theorem small_forShape {rows cols addr limb degree other aux : ℕ → ℕ} (hr : LogBound rows)
+ (hc : LogBound cols) (hw : PolynomiallyBounded addr) (hv : PolynomiallyBounded limb)
+ (he : PolynomiallyBounded degree) (hb : PolynomiallyBounded other) (ha : PolynomiallyBounded aux) :
+ Small (fun n ↦ forShape (rows n) (cols n) (addr n) (limb n) (degree n) (other n) (aux n)) := by
+ let x := polyMax hw (polyMax hv he)
+ have allowance := (PolynomiallyBounded.const
+ (DescribeAdapter.codeCost .describe + DescribeAdapter.codeCost .gram + 4000)).mul
+ ((x.add (.const 1)).pow 4)
+ exact ⟨polyMax hr hc, hw, hv, he, polyMax hb allowance, ha⟩
+
+theorem feasible_descriptor (hp : Small p) (ha : Feasible a) (number : ℕ) :
+ Feasible (fun n ↦ descriptor (p n) number (a n)) := by
+ obtain ⟨hi, hw, hv, he, hB, hA⟩ := hp
+ obtain ⟨ht, hs⟩ := ha
+ let live := polyMax (PolynomiallyBounded.const 1) (polyMax hw (he.mul hv))
+ let depth := (hi.add (.const 4)).add hi
+ let history := depth.mul (((PolynomiallyBounded.const 2).mul live).add (.const 1))
+ let initial := polyMax ((((hw.add hv).add he).add (he.mul hv)).add hA) (polyMax live history)
+ exact ⟨PolynomiallyBounded.clog_add (PolynomiallyBounded.clog_mul (logConst number) ht) hB.clog,
+ (polyMax hs initial).add hB⟩
+
+private theorem poly_rankScale (hp : Small p) (ha : Feasible a) :
+ PolynomiallyBounded (fun n ↦ rankScale (p n) (a n)) := by
+ obtain ⟨hi, hw, hv, he, hB, hA⟩ := hp
+ obtain ⟨ht, hs⟩ := ha
+ dsimp only [rankScale]
+ poly_bound
+
+theorem feasible_rank (hp : Small p) (ha : Feasible a) : Feasible (fun n ↦ rank (p n) (a n)) := by
+ have scale := poly_rankScale hp ha
+ obtain ⟨hi, hw, hv, he, hB, hA⟩ := hp
+ obtain ⟨ht, hs⟩ := ha
+ constructor
+ · apply PolynomiallyBounded.clog_pow (logConst 2)
+ poly_bound
+ · dsimp only [rank]
+ poly_bound
+
+private theorem feasible_arithmetic (hp : Small p) : Feasible (fun n ↦ arithmetic (p n)) := by
+ have hw := hp.addr
+ have ht : PolynomiallyBounded (fun n ↦ arithmeticClock (p n).addr) := by
+ dsimp only [arithmeticClock]
+ poly_bound
+ exact ⟨ht.clog, hw.add ht⟩
+
+theorem feasible_prefixScan (hp : Small p) (ha : Feasible a) :
+ Feasible (fun n ↦ prefixScan (p n) (a n)) := by
+ have shape := PolynomiallyBounded.clog_pow (logConst 2) hp.bits
+ have localTime := (feasible_arithmetic hp).time
+ have cmp := (((PolynomiallyBounded.const 20).mul hp.addr).add (.const 10)).clog
+ have ht := ha.time
+ refine ⟨?_, polyMax ha.space (feasible_arithmetic hp).space⟩
+ open PolynomiallyBounded in
+ exact clog_mul shape (clog_add (clog_add (clog_add (clog_add localTime ht) cmp) (logConst 1)) localTime)
+
+theorem feasible_minorEntry (hp : Small p) (ha : Feasible a) (hb : Feasible b) :
+ Feasible (fun n ↦ minorEntry (p n) (a n) (b n)) := by
+ apply ((feasible_prefixScan hp ha).repeated (logConst 2)).thenRun
+ let cmp := ((PolynomiallyBounded.const 20).mul hp.addr).add (.const 10)
+ exact ⟨PolynomiallyBounded.clog_add cmp.clog (PolynomiallyBounded.clog_add hb.time (logConst 1)),
+ polyMax hb.space (hp.addr.add cmp)⟩
+
+theorem feasible_determinant (hp : Small p) (ha : Feasible a) :
+ Feasible (fun n ↦ determinant (p n) (a n)) := by
+ obtain ⟨hi, hw, hv, he, hB, hA⟩ := hp
+ obtain ⟨ht, hs⟩ := ha
+ have count : LogBound (fun n ↦ 2^((2*(p n).bits+8)*(2*(p n).bits+5))) := by
+ apply PolynomiallyBounded.clog_pow (logConst 2)
+ poly_bound
+ let live := polyMax (PolynomiallyBounded.const 1) (polyMax hw (he.mul hv))
+ have short : PolynomiallyBounded (fun n ↦ Engine.stepBudget (p n).localWork (p n).addr (p n).limb (p n).degree) :=
+ (PolynomiallyBounded.const 4).mul ((hB.add ((PolynomiallyBounded.const 10).mul
+ (((PolynomiallyBounded.const 3).mul live).add (.const 2)))).add (.const 5))
+ constructor
+ · exact PolynomiallyBounded.clog_add (PolynomiallyBounded.clog_mul count
+ (logMax (PolynomiallyBounded.clog_add ht (logConst 1)) short.clog)) (logConst 1)
+ · let depth := (hi.add (.const 4)).add hi
+ let history := depth.mul (((PolynomiallyBounded.const 2).mul live).add (.const 1))
+ exact polyMax (hs.add (.const 1)) ((polyMax hA (polyMax live history)).add short)
+
+theorem feasible_divide (hp : Small p) : Feasible (fun n ↦ divide (p n)) := by
+ have he := hp.degree
+ have hv := hp.limb
+ have h : PolynomiallyBounded (fun n ↦ Cramer.divideClock (p n).degree (p n).limb) := by
+ refine (PolynomiallyBounded.of_le (g := fun n ↦ 7100*((p n).degree+1)^3*((p n).limb+1)^3) ?_
+ fun n ↦ Cramer.divideClock_le ..)
+ poly_bound
+ exact ⟨h.clog, (((he.add (.const 1)).mul (hv.add (.const 1))).add h)⟩
+
+/-- Composition covers both expensive scans in each minor without placing any
+exponential clock in a space bound. -/
+theorem feasible_coordinate (hp : Small p) (hb : Feasible b) :
+ Feasible (fun n ↦ coordinate (p n) (b n)) := by
+ have hr := feasible_rank hp (feasible_descriptor hp hb 2)
+ have hs := feasible_prefixScan hp hr
+ have har := feasible_arithmetic hp
+ have hdim := (hr.repeated (logConst 2)).thenRun har
+ have hsuf := ((hr.thenRun har).thenRun hs).thenRun har
+ have hentry := feasible_minorEntry hp hr hb
+ have hd := feasible_descriptor hp hentry 1
+ have hd' : Feasible (fun n ↦ cramerDescriptor (p n) (descriptor (p n) 1
+ (minorEntry (p n) (rank (p n) (gramDescriptor (p n) (b n))) (b n)))) :=
+ ⟨hd.time, polyMax hd.space (feasible_divide hp).space⟩
+ have hdet := feasible_determinant hp hd'
+ exact (((hdim.thenRun hsuf).thenRun har).thenRun (hdet.repeated (logConst 2))).thenRun (feasible_divide hp)
+
+/-- A single polynomial exponent bounds the complete clock, and a separate
+polynomial bounds the peak space. Both hold uniformly at every length. -/
+theorem coordinate_time_space (hp : Small p) (hb : Feasible b) :
+ ∃ exponent : ℕ → ℕ, PolynomiallyBounded exponent ∧
+ (∀ n, (coordinate (p n) (b n)).time ≤ 2^(exponent n)) ∧
+ PolynomiallyBounded (fun n ↦ (coordinate (p n) (b n)).space) := by
+ have h := feasible_coordinate hp hb
+ exact ⟨_, h.time, fun n ↦ Nat.le_pow_clog (by decide) _, h.space⟩
+
+open RadicalCertificate.MonomialIndex
+
+/-- Instantiate the two matrix dimensions from the actual graded Macaulay
+enumeration. The row count includes the equation prefix and the monomial suffix. -/
+def forSlice {t e : ℕ} {K : Type*} (S : QueryData t e K) (addr limb degree other aux : ℕ) :=
+ forShape (e * size t S.multiplierDegree + size t S.pointBound) (size t S.columnDegree)
+ addr limb degree other aux
+
+theorem small_forSlice {t e : ℕ → ℕ} {K : ℕ → Type*} (S : (n : ℕ) → QueryData (t n) (e n) (K n))
+ {addr limb degree other aux : ℕ → ℕ} (ht : PolynomiallyBounded t) (he : LogBound e)
+ (hQ : LogBound (fun n ↦ (S n).fieldOrder)) (hd : LogBound (fun n ↦ (S n).degreeBound))
+ (hN : LogBound (fun n ↦ (S n).pointBound)) (hQpos : ∀ n, 2 ≤ (S n).fieldOrder)
+ (hw : PolynomiallyBounded addr) (hv : PolynomiallyBounded limb) (hf : PolynomiallyBounded degree)
+ (hb : PolynomiallyBounded other) (ha : PolynomiallyBounded aux) :
+ Small (fun n ↦ forSlice (S n) (addr n) (limb n) (degree n) (other n) (aux n)) := by
+ obtain ⟨hrows, hcols, _⟩ := bounded_query_dimensions S ht he hQ hd hN hQpos
+ exact small_forShape hrows hcols hw hv hf hb ha
+
+end RankQuery.Stack.Coordinate.Cost
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateCramer.lean b/lean/OAI/Computability/VPVNP/RankCoordinateCramer.lean
new file mode 100644
index 0000000000..6af901540d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateCramer.lean
@@ -0,0 +1,476 @@
+import OAI.Computability.VPVNP.RankCoordinateDimension
+import OAI.Computability.VPVNP.RankQueryStackInterpretation
+import OAI.Computability.VPVNP.RankQueryStackEngineSpace
+import OAI.Computability.VPVNP.SliceArithmeticEncoding
+import OAI.Computability.VPVNP.SliceArithmeticInverseCall
+
+/-! # Two top-degree determinant queries for a greedy coordinate
+
+Appendix D.2 obtains a coordinate from a nonsingular minor and the minor with
+one row replaced. Their top pencil coefficients have the same sign. Division
+can therefore use the scalar returned by each Schur computation directly,
+including in characteristic two.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate
+
+open Polynomial SliceArithmetic RAMTape UniversalCountStack
+
+variable {r n m : ℕ}
+
+/-- The Schur evaluator for the outer top coefficient of a constant matrix. -/
+def topPencil {R : Type*} [CommRing R] (A : Matrix (Fin r) (Fin r) R) : R :=
+ SchurKey.compute (fun i j z => if z = 0 then A i j else 0) r 0
+
+/-- The Schur output differs from the determinant by the same sign at every
+matrix of the given order. -/
+theorem sign_mul_topPencil {R : Type*} [CommRing R] (A : Matrix (Fin r) (Fin r) R) :
+ (-1 : R)^r * topPencil A = A.det := by
+ nontriviality R
+ let M := A.map C
+ have entries (i j : Fin r) (z : ℕ) : (if z = 0 then A i j else 0) = (M i j).coeff z := by
+ simp [M, coeff_C]
+ rw [topPencil, SchurKey.compute_correct M _ entries]
+ have htop : M.charpolyRev.coeff r = M.charpoly.coeff 0 := by
+ rw [← M.reverse_charpoly, coeff_reverse, M.charpoly_natDegree_eq_dim, Fintype.card_fin]
+ simp
+ rw [htop]
+ have hs := M.det_eq_sign_charpoly_coeff
+ rw [Fintype.card_fin, ← show C ((-1 : R)^r) = (-1 : R[X])^r by simp] at hs
+ have h := congrArg (fun z : R[X] => z.coeff 0) hs
+ rw [coeff_C_mul] at h
+ change (C.mapMatrix A).det.coeff 0 = _ at h
+ rw [← C.map_det, coeff_C_zero] at h
+ exact h.symm
+
+/-- Two machine outputs can be divided without correcting either sign. This
+also holds after mapping the executable scalar ring into the advised field. -/
+theorem topPencil_div_map {R K : Type*} [CommRing R] [Field K] (f : R →+* K)
+ (N D : Matrix (Fin r) (Fin r) R) :
+ f (topPencil N) / f (topPencil D) = (N.map f).det / (D.map f).det := by
+ have hn := congrArg f (sign_mul_topPencil N)
+ have hd := congrArg f (sign_mul_topPencil D)
+ simp only [map_mul, map_pow, map_neg, map_one, RingHom.map_det] at hn hd
+ change _ = (f.mapMatrix N).det / (f.mapMatrix D).det
+ rw [← hn, ← hd, mul_div_mul_left _ _ (pow_ne_zero _ (neg_ne_zero.mpr one_ne_zero))]
+
+/-- The canonical numerator for a selected-row representation. -/
+def replacedMinor {K : Type*} (B : Matrix (Fin r) (Fin m) K) (cols : Fin r → Fin m)
+ (target : Fin m → K) (i : Fin r) := (B.submatrix id cols).updateRow i (target ∘ cols)
+
+/-- Packed-ring queries for the two minors produce the scalar appearing in the
+greedy coordinate formula. -/
+theorem topPencil_div_rowCoordinate {R K : Type*} [CommRing R] [Field K] (f : R →+* K)
+ (N D : Matrix (Fin r) (Fin r) R) (B : Matrix (Fin r) (Fin m) K) (cols : Fin r → Fin m)
+ (target : Fin m → K) (i : Fin r) (hn : N.map f = replacedMinor B cols target i)
+ (hd : D.map f = B.submatrix id cols) :
+ f (topPencil N) / f (topPencil D) = rowCoordinateQuery squareDetQuery B cols target i := by
+ rw [topPencil_div_map, hn, hd, rowCoordinateQuery, squareDetQuery_eq, squareDetQuery_eq]
+ rfl
+
+namespace Cramer
+
+/-- Keep the numerator outside the inverse's entire workspace. A second external
+stack is used temporarily to copy it into the multiplier's query operand. -/
+inductive Extra where
+ | numerator | scratch
+ deriving DecidableEq
+
+instance : Fintype Extra := ⟨{.numerator, .scratch}, by intro i; cases i <;> simp⟩
+
+/-- Stack ports for inversion and multiplication together with the numerator, denominator, and
+copying workspace. -/
+abbrev Port := InverseCall.Port ⊕ Extra
+
+private def mulPort (i : MultiplyCall.Port) : Port := .inl (.inl i)
+
+private theorem mulPort_injective : Function.Injective mulPort :=
+ Sum.inl_injective.comp Sum.inl_injective
+
+/-- Boundary of the quotient operation. The input denominator and numerator
+are kept on distinct read-only ports. The output is the multiplier accumulator. -/
+def frame (p e w : ℕ) (cb denominator numerator acc : List Bool) : Stacks Port :=
+ Sum.elim (InverseCall.frame p e w cb denominator (p^e - 2).bits.reverse [] acc [])
+ fun extra => match extra with | .numerator => numerator | .scratch => []
+
+/-- Pack the extension-field coefficient vector as fixed-width binary limbs for the quotient
+routine. -/
+abbrev digits {p e : ℕ} (w : ℕ) (a : Vector p e) := SliceArithmeticRound.packed w (List.ofFn a)
+
+private def copyNumerator : FiniteRoutine Port :=
+ SuccessorFields.prependCopy (.inr .numerator) (mulPort (.inr .query)) (.inr .scratch)
+
+/-- Invert the denominator in the polynomial basis and multiply by the saved numerator. -/
+def quotientCall (inv : FiniteRoutine InverseCall.Port) : FiniteRoutine Port :=
+ ((inv.onPorts Sum.inl).followedBy copyNumerator).followedBy (MultiplyCall.machine.onPorts mulPort)
+
+/-- Only the inverse, one operand copy, and one multiplication are charged here. -/
+def quotientClock (e w inverseClock : ℕ) := inverseClock + (5*(e*w)+2) + MultiplyCall.callCap e w
+
+variable {p e w : ℕ} [NeZero p]
+
+/-- Install an inverse run in the quotient bank and perform the remaining
+arithmetic by the literal finite multiplication machine. -/
+theorem quotientCall_runs (inv : FiniteRoutine InverseCall.Port) (he : 0 < e)
+ (hw : Word.workingWidth p ≤ w) (c num den : Vector p e) {it : ℕ}
+ (hinv : inv.Runs it
+ (InverseCall.frame p e w (digits w c) (digits w den) (p^e-2).bits.reverse [] [] [])
+ (InverseCall.frame p e w (digits w c) (digits w den) (p^e-2).bits.reverse []
+ (digits w (inverse c den)) [])) :
+ ∃ t ≤ quotientClock e w it, (quotientCall inv).Runs t
+ (frame p e w (digits w c) (digits w den) (digits w num) [])
+ (frame p e w (digits w c) (digits w den) (digits w num) (digits w (mul c num (inverse c den)))) := by
+ let f (acc : List Bool) := frame p e w (digits w c) (digits w den) (digits w num) acc
+ let ib := digits w (inverse c den)
+ let nb := digits w num
+ let staged := Function.update (f ib) (mulPort (.inr .query)) nb
+ have start : (inv.onPorts Sum.inl).Runs it (f []) (f ib) := by
+ apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective hinv (fun _ => rfl) (fun _ => rfl)
+ rintro (k | k) hout
+ · exact (hout k rfl).elim
+ · rfl
+ have copied : copyNumerator.Runs (5*(e*w)+2) (f ib) staged := by
+ have h := SuccessorFields.prependCopy_runs (K := Port) (.inr .numerator) (mulPort (.inr .query))
+ (.inr .scratch) (by decide) (by decide) (by decide) (f ib) rfl
+ change copyNumerator.Runs (5*nb.length+2) (f ib) (Function.update (f ib) (mulPort (.inr .query))
+ (nb ++ [])) at h
+ simpa only [staged, List.append_nil, nb, digits, SliceArithmeticRound.packed_length, List.length_ofFn]
+ using h
+ obtain ⟨m, hm, hmul⟩ := MultiplyCall.machine_runs he hw c num (inverse c den)
+ have finish : (MultiplyCall.machine.onPorts mulPort).Runs m staged (f (digits w (mul c num (inverse c den)))) := by
+ apply FiniteRoutine.runs_onPorts_framed _ mulPort_injective hmul
+ · rintro (k | k)
+ · rfl
+ · cases k <;> rfl
+ · rintro (k | k) <;> rfl
+ · rintro ((k | k) | k) hout
+ · exact (hout k rfl).elim
+ · rfl
+ · rfl
+ exact ⟨_, by unfold quotientClock; omega, (start.followedBy copied).followedBy finish⟩
+
+
+section Field
+
+variable {q deg width : ℕ} [Fact q.Prime] [NeZero deg] (c : Vector q deg)
+variable [Fact (Irreducible (modulus c))]
+
+/-- Native result of the two top pencil computations and the quotient call. -/
+def minorQuotient (N D : Matrix (Fin r) (Fin r) (Scalar c)) : Vector q deg :=
+ mul c (topPencil N).digits (inverse c (topPencil D).digits)
+
+theorem minorQuotient_value (N D : Matrix (Fin r) (Fin r) (Scalar c)) :
+ value (modulus c) (minorQuotient c N D) =
+ (N.map (Scalar.interpretation c)).det / (D.map (Scalar.interpretation c)).det := by
+ rw [minorQuotient, value_mul, value_inverse, ← div_eq_mul_inv]
+ exact topPencil_div_map (Scalar.interpretation c) N D
+
+theorem minorQuotient_rowCoordinate (N D : Matrix (Fin r) (Fin r) (Scalar c))
+ (B : Matrix (Fin r) (Fin m) (AdjoinRoot (modulus c))) (cols : Fin r → Fin m)
+ (target : Fin m → AdjoinRoot (modulus c)) (i : Fin r)
+ (hN : N.map (Scalar.interpretation c) = replacedMinor B cols target i)
+ (hD : D.map (Scalar.interpretation c) = B.submatrix id cols) :
+ value (modulus c) (minorQuotient c N D) = rowCoordinateQuery squareDetQuery B cols target i := by
+ rw [minorQuotient, value_mul, value_inverse, ← div_eq_mul_inv]
+ exact topPencil_div_rowCoordinate (Scalar.interpretation c) N D B cols target i hN hD
+
+variable [DecidableEq (AdjoinRoot (modulus c))]
+
+/-- Specialization to the two matrices selected by the greedy scans. -/
+theorem minorQuotient_greedy (A : Matrix (Fin n) (Fin m) (AdjoinRoot (modulus c)))
+ (target : Fin m → AdjoinRoot (modulus c)) (i : Fin (rankQuery A))
+ (N D : Matrix (Fin (rankQuery A)) (Fin (rankQuery A)) (Scalar c))
+ (hN : N.map (Scalar.interpretation c) = replacedMinor (greedyRowBasis A)
+ (coordinateColumns _ (greedyRowBasis_fullRank A)) target i)
+ (hD : D.map (Scalar.interpretation c) = (greedyRowBasis A).submatrix id
+ (coordinateColumns _ (greedyRowBasis_fullRank A))) :
+ value (modulus c) (minorQuotient c N D) = greedyCoordinateQuery A target i :=
+ minorQuotient_rowCoordinate c N D _ _ target i hN hD
+
+/-- The monomial-basis ordinal is offset past the independent equation rows. -/
+theorem minorQuotient_suffix {w : ℕ} (W : Matrix (Fin w) (Fin m) (AdjoinRoot (modulus c)))
+ (M : Matrix (Fin n) (Fin m) (AdjoinRoot (modulus c))) (target : Fin m → AdjoinRoot (modulus c))
+ (i : Fin (suffixDimension W M)) (N D : Matrix (Fin (rankQuery (appendRows W M)))
+ (Fin (rankQuery (appendRows W M))) (Scalar c))
+ (hN : N.map (Scalar.interpretation c) = replacedMinor (greedyRowBasis (appendRows W M))
+ (coordinateColumns _ (greedyRowBasis_fullRank _)) target (combinedOrdinal W M i))
+ (hD : D.map (Scalar.interpretation c) = (greedyRowBasis (appendRows W M)).submatrix id
+ (coordinateColumns _ (greedyRowBasis_fullRank _))) :
+ value (modulus c) (minorQuotient c N D) = greedyCoordinateQuery (appendRows W M) target
+ (combinedOrdinal W M i) :=
+ minorQuotient_greedy c _ target _ N D hN hD
+
+end Field
+
+variable {q deg width : ℕ} [Fact q.Prime] [NeZero deg]
+
+/-- Concrete finite quotient program, with the inverse obtained by binary powering. -/
+def divide : FiniteRoutine Port := quotientCall InverseCall.machine
+
+/-- Clock bound for the finite-field division, including inversion and multiplication at the
+stated degree and width. -/
+def divideClock (e w : ℕ) := quotientClock e w (InverseCall.callCap e w)
+
+theorem divideClock_le (e w : ℕ) : divideClock e w ≤ 7100*(e+1)^3*(w+1)^3 := by
+ have inv := InverseCall.callCap_le e w
+ have mul := MultiplyCall.callCap_le e w
+ unfold divideClock quotientClock
+ calc
+ _ ≤ 5000*(e+1)^3*(w+1)^3 + (5*(e*w)+2) + 2000*(e+1)^2*(w+1)^2 := by omega
+ _ ≤ _ := by ring_nf; omega
+
+/-- Division by the determinant takes polynomial time and preserves both input
+scalars and all advised field data. -/
+theorem divide_runs (hw : Word.workingWidth q ≤ width) (c num den : Vector q deg) :
+ ∃ t ≤ divideClock deg width, divide.Runs t (frame q deg width (digits width c) (digits width den)
+ (digits width num) []) (frame q deg width (digits width c) (digits width den) (digits width num)
+ (digits width (mul c num (inverse c den)))) := by
+ obtain ⟨it, hi, hinv⟩ := InverseCall.machine_runs (NeZero.pos deg) hw c den
+ obtain ⟨t, ht, h⟩ := quotientCall_runs InverseCall.machine (NeZero.pos deg) hw c num den hinv
+ exact ⟨t, ht.trans (by unfold divideClock quotientClock; omega), h⟩
+
+omit [NeZero deg] in
+/-- At a clean field boundary every live limb buffer and the exponent advice
+have polynomial length. -/
+theorem frame_length (hw : Word.workingWidth q ≤ width) (c num den : Vector q deg) (k : Port) :
+ (frame q deg width (digits width c) (digits width den) (digits width num) [] k).length ≤
+ (deg+1)*(width+1) := by
+ have hexp : (q^deg-2).bits.length ≤ deg*width := by
+ rw [Nat.size_eq_bits_len]
+ apply Nat.size_le.mpr
+ calc
+ q ^ deg - 2 < q ^ deg := by have := Nat.pow_pos (Fact.out : q.Prime).pos (n := deg); omega
+ _ ≤ (2 ^ width) ^ deg := Nat.pow_le_pow_left (Word.modulus_lt hw).le _
+ _ = 2 ^ (deg*width) := by rw [← pow_mul, Nat.mul_comm]
+ rcases k with ((inner | ext) | extra) | extra
+ · exact Nat.zero_le _
+ · cases ext <;> simp [frame, InverseCall.frame, MultiplyCall.clean, MultiplyCall.external, digits] <;> nlinarith
+ · cases extra <;> simp [frame, InverseCall.frame, digits] <;> nlinarith
+ · cases extra <;> simp [frame, digits]; nlinarith
+
+/-- Concrete Cramer program consuming the two determinant subqueries. -/
+def machine (den num : FiniteRoutine Port) := (den.followedBy num).followedBy divide
+
+theorem machine_runs (den num : FiniteRoutine Port) (c : Vector q deg) (hw : Word.workingWidth q ≤ width)
+ (N D : Matrix (Fin r) (Fin r) (Scalar c)) {initial middle : Stacks Port} {cap nd nn : ℕ}
+ (first : den.BoundedRun cap nd initial middle)
+ (second : num.BoundedRun cap nn middle (frame q deg width (digits width c)
+ (digits width (topPencil D).digits) (digits width (topPencil N).digits) []))
+ (room : (deg+1)*(width+1) + divideClock deg width ≤ cap) :
+ ∃ t ≤ nd + nn + divideClock deg width, (machine den num).BoundedRun cap t initial
+ (frame q deg width (digits width c) (digits width (topPencil D).digits)
+ (digits width (topPencil N).digits) (digits width (minorQuotient c N D))) := by
+ obtain ⟨t, ht, h⟩ := divide_runs hw c (topPencil N).digits (topPencil D).digits
+ have bounded := spaceRun_of_steps h fun k => (Nat.add_le_add (frame_length hw c _ _ k) ht).trans room
+ exact ⟨_, Nat.add_le_add_left ht _, (first.followedBy second).followedBy bounded⟩
+
+
+namespace SchurPair
+
+/-- Separate frame stacks for the two root calls, and a bank for their field
+arithmetic. The quotient reads the two engine result ports directly. -/
+abbrev Host (K L : Type) := Engine.Port K ⊕ (Engine.Port L ⊕ Port)
+
+instance {K L : Type} [DecidableEq K] [DecidableEq L] : DecidableEq (Host K L) := by
+ letI : DecidableEq Port := inferInstance
+ letI : DecidableEq (Engine.Port L ⊕ Port) := inferInstance
+ exact inferInstanceAs (DecidableEq (Engine.Port K ⊕ (Engine.Port L ⊕ Port)))
+
+/-- Combine the denominator engine, numerator engine, and quotient arithmetic into one disjoint
+physical bank. -/
+def host {K L : Type} (d : Stacks (Engine.Port K)) (n : Stacks (Engine.Port L)) (q : Stacks Port) :
+ Stacks (Host K L) := Sum.elim d (Sum.elim n q)
+
+/-- Wire the denominator and numerator to the actual output stacks of their
+Schur engines. All other quotient ports have their own storage. -/
+def quotientPort {K L : Type} : Port → Host K L
+ | .inl (.inr .base) => .inl .result
+ | .inr .numerator => .inr (.inl .result)
+ | j => .inr (.inr j)
+
+private theorem quotientPort_injective {K L : Type} :
+ Function.Injective (quotientPort (K := K) (L := L)) := by
+ rintro ((a | a) | a) ((b | b) | b) h
+ all_goals try cases a <;> cases b <;> simp_all [quotientPort]
+
+private def leftPort {K L : Type} (k : Engine.Port K) : Host K L := .inl k
+private def rightPort {K L : Type} (k : Engine.Port L) : Host K L := .inr (.inl k)
+
+/-- Run the two Schur determinant engines and divide their returned coefficients to obtain the
+Cramer coordinate. -/
+def query {K L : Type} (a : Engine.Actions K) (b : Engine.Actions L) : FiniteRoutine (Host K L) :=
+ ((((FiniteRoutine.ofRoutine (Engine.routine a)).onPorts leftPort).followedBy
+ ((FiniteRoutine.ofRoutine (Engine.routine b)).onPorts rightPort))).followedBy
+ (divide.onPorts quotientPort)
+
+private theorem quotient_frame {K L : Type} (d : Stacks (Engine.Port K)) (n : Stacks (Engine.Port L))
+ (cb acc : List Bool) (q e w : ℕ) (i : Port) :
+ host d n (frame q e w cb [] [] acc) (quotientPort i) = frame q e w cb (d .result) (n .result) acc i := by
+ rcases i with ((k | k) | k) | k
+ · rfl
+ · cases k <;> rfl
+ · cases k <;> rfl
+ · cases k <;> rfl
+
+private theorem quotient_outside {K L : Type} (d : Stacks (Engine.Port K)) (n : Stacks (Engine.Port L))
+ (q e w : ℕ) (cb a b : List Bool) (i : Host K L) (outside : ∀ k, quotientPort k ≠ i) :
+ host d n (frame q e w cb [] [] a) i = host d n (frame q e w cb [] [] b) i := by
+ rcases i with k | k | ((k | k) | k) | k
+ · rfl
+ · rfl
+ · rfl
+ · cases k <;> first | rfl | exact (outside (.inl (.inl (.inr .acc))) rfl).elim
+ · cases k <;> rfl
+ · cases k <;> rfl
+
+/-- Run both literal determinant engines. At the boundary their returned
+scalars are already located at the inverse's base and the multiplier's
+numerator, so no field-element copy from the engine output is required. -/
+theorem query_runs {K L : Type} [DecidableEq K] [DecidableEq L]
+ (a : Engine.Actions K) (b : Engine.Actions L) (c : Vector q deg) (hw : Word.workingWidth q ≤ width)
+ (N D : Matrix (Fin r) (Fin r) (Scalar c)) {d₀ d₁ : Stacks (Engine.Port K)}
+ {n₀ n₁ : Stacks (Engine.Port L)} {cap td tn : ℕ}
+ (hd : (FiniteRoutine.ofRoutine (Engine.routine a)).BoundedRun cap td d₀ d₁)
+ (hn : (FiniteRoutine.ofRoutine (Engine.routine b)).BoundedRun cap tn n₀ n₁)
+ (hD : d₁ .result = digits width (topPencil D).digits)
+ (hN : n₁ .result = digits width (topPencil N).digits)
+ (room : (deg+1)*(width+1) + divideClock deg width ≤ cap) :
+ ∃ t ≤ td+tn+divideClock deg width, (query a b).BoundedRun cap t
+ (host d₀ n₀ (frame q deg width (digits width c) [] [] []))
+ (host d₁ n₁ (frame q deg width (digits width c) [] [] (digits width (minorQuotient c N D)))) := by
+ let blank := frame q deg width (digits width c) [] [] []
+ have blank_cap (k : Port) : (blank k).length ≤ cap := by
+ have h := frame_length hw c (topPencil N).digits (topPencil D).digits k
+ apply (le_trans ?_ h).trans ((Nat.le_add_right _ _).trans room)
+ rcases k with ((j | j) | j) | j
+ · exact le_rfl
+ · cases j <;> exact le_rfl
+ · cases j <;> first | exact le_rfl | exact Nat.zero_le _
+ · cases j <;> first | exact le_rfl | exact Nat.zero_le _
+ have dcap (i : Host K L) : (host d₀ n₀ blank i).length ≤ cap := by
+ rcases i with k | k | k
+ · exact hd.initial_cap k
+ · exact hn.initial_cap k
+ · exact blank_cap k
+ have left := hd.onPorts (ports := leftPort) Sum.inl_injective (host d₀ n₀ blank) (fun i _ => dcap i)
+ have left_eq (d : Stacks (Engine.Port K)) : installStacks leftPort (host d₀ n₀ blank) d = host d n₀ blank := by
+ refine installStacks_frame (ports := leftPort) (base := host d₀ n₀ blank) (target := host d n₀ blank)
+ Sum.inl_injective (fun _ => rfl) ?_
+ rintro (k | k) h
+ · exact (h k rfl).elim
+ · rfl
+ rw [left_eq, left_eq] at left
+ have rinj : Function.Injective (rightPort (K := K) (L := L)) := Sum.inr_injective.comp Sum.inl_injective
+ have right := hn.onPorts (ports := rightPort) rinj (host d₁ n₀ blank) (fun i _ => left.final_cap i)
+ have right_eq (n : Stacks (Engine.Port L)) : installStacks rightPort (host d₁ n₀ blank) n = host d₁ n blank := by
+ refine installStacks_frame (base := host d₁ n₀ blank) (target := host d₁ n blank) rinj (fun _ => rfl) ?_
+ rintro (k | k | k) h
+ · rfl
+ · exact (h k rfl).elim
+ · rfl
+ rw [right_eq, right_eq] at right
+ obtain ⟨t, ht, divRun⟩ := divide_runs hw c (topPencil N).digits (topPencil D).digits
+ have bound := spaceRun_of_steps divRun fun k => (Nat.add_le_add (frame_length hw c _ _ k) ht).trans room
+ have last := FiniteRoutine.BoundedRun.onPorts quotientPort_injective (host d₁ n₁ blank) bound
+ (fun i _ => right.final_cap i)
+ have heq (acc : List Bool) : installStacks quotientPort (host d₁ n₁ blank)
+ (frame q deg width (digits width c) (digits width (topPencil D).digits) (digits width (topPencil N).digits) acc) =
+ host d₁ n₁ (frame q deg width (digits width c) [] [] acc) := by
+ apply installStacks_frame quotientPort_injective
+ · intro i
+ rw [← hD, ← hN]
+ exact quotient_frame d₁ n₁ _ acc _ _ _ i
+ · exact fun i outside => quotient_outside d₁ n₁ q deg width _ acc [] i outside
+ rw [heq, heq] at last
+ exact ⟨_, Nat.add_le_add_left ht _, (left.followedBy right).followedBy last⟩
+
+/-- Scalar entry oracle for the constant coefficient matrix of a pencil. -/
+def constantEntries {R : Type*} [Zero R] (M : Matrix (Fin r) (Fin r) R) : Entry r R :=
+ fun i j z => if z = 0 then M i j else 0
+
+/-- Depth allowance for a top-degree Schur query on an `r` by `r` minor. -/
+abbrev depth (r : ℕ) := Nat.clog 2 r + 4 + Nat.clog 2 r
+/-- Bound the determinant's instruction count using its descriptor-tree arity, depth, and
+per-step cost. -/
+abbrev clock (r addr width deg budget descTime : ℕ) :=
+ (5 + 6*SchurKey.arityBound r r 0)^(depth r + 1)*Engine.boundedStepTime descTime budget addr width deg + 1
+/-- Bound the peak stack height of the determinant engine, including suspended frames and the
+entry reader. -/
+abbrev space (r addr width deg budget auxBound descSpace : ℕ) :=
+ Engine.boundedSpace descSpace auxBound (depth r) budget addr width deg
+
+/-- Initialize a determinant query at its top-degree root with an empty stack of suspended
+frames. -/
+abbrev entryBank {K : Type} (c : Vector q deg) (r addr width : ℕ) (aux : Stacks K) :=
+ Engine.atControl (c := c) addr width (.enter (SchurKey.root (n := r) (Fin.last r) (Fin.last 0))) [] aux
+
+/-- The determinant engine's return configuration holds its scalar answer and an empty stack of
+frames. -/
+abbrev resultBank {K : Type} (c : Vector q deg) (r addr width : ℕ) (v : Scalar c) (aux : Stacks K) :=
+ Engine.atControl addr width (.returned v) ([] : List (Engine.F r r 0 c)) aux
+
+/-- Install the bounded Schur engine at the top pencil coefficient. Its result is
+already encoded at the limb width used by the field arithmetic routines. -/
+theorem topPencil_runs {K : Type} [DecidableEq K] (c : Vector q deg)
+ (M : Matrix (Fin r) (Fin r) (Scalar c)) (actions : Engine.Actions K)
+ {addr width budget auxBound descTime descSpace : ℕ} {ready : Stacks K → Prop} {pending : SchurKey r r 0 → Stacks K → Prop}
+ (spec : Engine.Contracts actions (SchurKey.program (U := r) (Z := 0) (constantEntries M))
+ addr width budget (SchurKey.arityBound r r 0) ready pending descTime)
+ (desc : Engine.DescribeBounded actions (SchurKey.program (U := r) (Z := 0) (constantEntries M))
+ addr width descTime descSpace (depth r) ready)
+ (bound : ∀ s, ready s → ∀ k, (s k).length ≤ auxBound) (aux : Stacks K) (ha : ready aux) :
+ ∃ t ≤ clock r addr width deg budget descTime, ∃ out, ready out ∧
+ (FiniteRoutine.ofRoutine (Engine.routine actions)).BoundedRun (space r addr width deg budget auxBound descSpace) t
+ (entryBank c r addr width aux) (resultBank c r addr width (topPencil M) out) := by
+ have he (i j : Fin r) (z : ℕ) : constantEntries M i j z = (M.map C i j).coeff z := by
+ simp [constantEntries, coeff_C, Matrix.map_apply]
+ obtain ⟨t, ht, out, ho, run⟩ := Engine.eval_root_bounded spec desc bound (M.map C) he (Fin.last r) (Fin.last 0) aux ha
+ refine ⟨t, ht, out, ho, ?_⟩
+ have eq : topPencil M = ((M.map C).charpolyRev.coeff r).coeff 0 :=
+ SchurKey.compute_correct (M.map C) _ he r 0
+ rw [eq]
+ exact run
+
+/-- Instantiating the two Schur calls, the concrete inverse and the final
+multiplication gives the packed Cramer quotient with a common polynomial
+space cap. The two ready auxiliary banks are returned separately. -/
+theorem native_runs {K L : Type} [DecidableEq K] [DecidableEq L] (c : Vector q deg)
+ (N D : Matrix (Fin r) (Fin r) (Scalar c)) (a : Engine.Actions K) (b : Engine.Actions L)
+ {addr width budget auxBound descTime descSpace : ℕ} (hw : Word.workingWidth q ≤ width)
+ {readyD : Stacks K → Prop} {readyN : Stacks L → Prop}
+ {pendingD : SchurKey r r 0 → Stacks K → Prop} {pendingN : SchurKey r r 0 → Stacks L → Prop}
+ (den : Engine.Contracts a (SchurKey.program (U := r) (Z := 0) (constantEntries D))
+ addr width budget (SchurKey.arityBound r r 0) readyD pendingD descTime)
+ (descD : Engine.DescribeBounded a (SchurKey.program (U := r) (Z := 0) (constantEntries D))
+ addr width descTime descSpace (depth r) readyD)
+ (num : Engine.Contracts b (SchurKey.program (U := r) (Z := 0) (constantEntries N))
+ addr width budget (SchurKey.arityBound r r 0) readyN pendingN descTime)
+ (descN : Engine.DescribeBounded b (SchurKey.program (U := r) (Z := 0) (constantEntries N))
+ addr width descTime descSpace (depth r) readyN)
+ (boundD : ∀ s, readyD s → ∀ k, (s k).length ≤ auxBound)
+ (boundN : ∀ s, readyN s → ∀ k, (s k).length ≤ auxBound)
+ (auxD : Stacks K) (hD : readyD auxD) (auxN : Stacks L) (hN : readyN auxN)
+ (room : (deg+1)*(width+1) + divideClock deg width ≤ space r addr width deg budget auxBound descSpace) :
+ ∃ t ≤ 2 * clock r addr width deg budget descTime + divideClock deg width,
+ ∃ outD outN, readyD outD ∧ readyN outN ∧
+ (query a b).BoundedRun (space r addr width deg budget auxBound descSpace) t
+ (host (entryBank c r addr width auxD) (entryBank c r addr width auxN)
+ (frame q deg width (digits width c) [] [] []))
+ (host (resultBank c r addr width (topPencil D) outD) (resultBank c r addr width (topPencil N) outN)
+ (frame q deg width (digits width c) [] [] (digits width (minorQuotient c N D)))) := by
+ obtain ⟨d, hd, outD, hoD, first⟩ := topPencil_runs c D a den descD boundD auxD hD
+ obtain ⟨n, hn, outN, hoN, second⟩ := topPencil_runs c N b num descN boundN auxN hN
+ obtain ⟨t, ht, both⟩ := query_runs a b c hw N D first second rfl rfl room
+ exact ⟨t, by omega, outD, outN, hoD, hoN, both⟩
+
+end SchurPair
+end Cramer
+end RankQuery.Stack.Coordinate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateDimension.lean b/lean/OAI/Computability/VPVNP/RankCoordinateDimension.lean
new file mode 100644
index 0000000000..15c1e3c7a9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateDimension.lean
@@ -0,0 +1,192 @@
+import OAI.Computability.VPVNP.RankCoordinatePrefix
+import OAI.Computability.VPVNP.RankQueryStackRegister
+import OAI.Computability.VPVNP.RegisterTable
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-!
+# Finite register routines for slice dimension and basis-index queries
+
+The dimension in Appendix D is the difference between the rank of the full
+matrix and the rank of its equation prefix. To locate a basis monomial, add the
+prefix rank to its ordinal, scan the original matrix for that greedy row, then
+remove the equation-row offset. The arithmetic runs on binary registers.
+The rank and prefix scans are returning calls in the same physical stack bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate
+
+open Dispatch RAMTape UniversalCountStack BurstRAM
+
+variable {K : Type} [DecidableEq K] {r width : ℕ}
+
+/-- The binary ISA ports inside a larger bank. The other ports can hold the
+caller's query or advice and have the same contents after register writeback. -/
+structure RegisterBank (ports : ISA.Port r 0 → K) (bank : Regs r width → Stacks K)
+ (persistent : Word width) : Prop where
+ injective : Function.Injective ports
+ inside (rs : Regs r width) (i : ISA.Port r 0) :
+ bank rs (ports i) = ISA.bank Fin.elim0 persistent rs [] i
+ outside (a b : Regs r width) (j : K) (hj : ∀ i, ports i ≠ j) :
+ bank a j = bank b j
+
+/-- Install a fixed instruction sequence at the caller's actual register ports. -/
+def registerCall (ports : ISA.Port r 0 → K) (c : RegCode r) : FiniteRoutine K :=
+ c.compile.onPorts ports
+
+/-- Bound the cost of a binary-register program by its instruction count and the word-width
+arithmetic cost. -/
+def registerClock (width : ℕ) (c : RegCode r) : ℕ := c.length * (100*(width+1)^2)
+
+theorem registerCall_runs {ports : ISA.Port r 0 → K} {bank : Regs r width → Stacks K}
+ {persistent : Word width} (hb : RegisterBank ports bank persistent)
+ (c : RegCode r) (rs : Regs r width) (cap : ℕ)
+ (room : width + registerClock width c ≤ cap)
+ (hout : ∀ j, (∀ i, ports i ≠ j) → (bank rs j).length ≤ cap) :
+ ∃ t ≤ registerClock width c,
+ (registerCall ports c).BoundedRun cap t (bank rs) (bank (c.exec rs)) := by
+ obtain ⟨t, ht, hr⟩ := c.compile_runs Fin.elim0 persistent rs
+ have hbr : c.compile.BoundedRun cap t (ISA.bank Fin.elim0 persistent rs [])
+ (ISA.bank Fin.elim0 persistent (c.exec rs) []) := by
+ apply spaceRun_of_steps hr
+ exact fun i ↦ (Nat.add_le_add (RegisterTable.bank_length_le Fin.elim0 persistent rs i) ht).trans room
+ have h := FiniteRoutine.BoundedRun.onPorts hb.injective (bank rs) hbr hout
+ rw [installStacks_frame hb.injective (hb.inside rs) (fun _ _ ↦ rfl),
+ installStacks_frame hb.injective (hb.inside (c.exec rs)) (hb.outside (c.exec rs) rs)] at h
+ exact ⟨t, ht, h⟩
+
+/-- A binary operation stages its two operands before changing the destination.
+Both instructions of the subtraction implementation are covered by this bound. -/
+def arithmeticClock (width : ℕ) : ℕ := 2 * (100*(width+1)^2)
+
+/-- The caller provides the two matrix rank routines. Their selected result
+registers remain available until the final subtraction. -/
+def dimensionMachine (ports : ISA.Port r 0 → K) (equations full : FiniteRoutine K)
+ (prefixRank fullRank dst : Fin r) : FiniteRoutine K :=
+ (equations.followedBy full).followedBy (registerCall ports (.op dst .sub fullRank prefixRank))
+
+variable {F : Type*} [Field F] [DecidableEq F] {w n m : ℕ}
+variable {ports : ISA.Port r 0 → K} {bank : Regs r width → Stacks K} {persistent : Word width}
+variable (W : Matrix (Fin w) (Fin m) F) (M : Matrix (Fin n) (Fin m) F)
+
+/-- The two completed rank calls and the compiled word operation compute the
+dimension. All other registers after the final operation equal their values
+at the return of the full-rank call. -/
+theorem dimensionMachine_runs (hb : RegisterBank ports bank persistent) (equations full : FiniteRoutine K) (prefixRank fullRank dst : Fin r)
+ {cap a b : ℕ} {rs middle last : Regs r width}
+ (he : equations.BoundedRun cap a (bank rs) (bank middle))
+ (hf : full.BoundedRun cap b (bank middle) (bank last))
+ (hp : (last prefixRank).val = rankQuery W)
+ (ht : (last fullRank).val = rankQuery (appendRows W M))
+ (room : width + arithmeticClock width ≤ cap) :
+ ∃ t ≤ a+b+arithmeticClock width, ∃ out : Regs r width,
+ (dimensionMachine ports equations full prefixRank fullRank dst).BoundedRun cap t (bank rs) (bank out) ∧
+ (out dst).val = suffixDimension W M ∧ ∀ j ≠ dst, out j = last j := by
+ let c : RegCode r := .op dst .sub fullRank prefixRank
+ obtain ⟨t, hclock, h⟩ := registerCall_runs hb c last cap room (fun j _ ↦ hf.final_cap j)
+ refine ⟨a+b+t, Nat.add_le_add_left hclock _, c.exec last, (he.followedBy hf).followedBy h, ?_, ?_⟩
+ · have hs : Arith.sub.eval (last fullRank).val (last prefixRank).val < 2^width :=
+ (Nat.sub_le ..).trans_lt (last fullRank).isLt
+ simp only [c, RegCode.exec, Function.update_self, Arith.word_val _ _ _ hs, Arith.eval,
+ hp, ht, suffixDimension]
+ rfl
+ · exact fun j hj ↦ Function.update_of_ne hj ..
+
+/-- Ordinal of the same selected monomial among all independent rows. -/
+def combinedOrdinal (i : Fin (suffixDimension W M)) : Fin (rankQuery (appendRows W M)) :=
+ ⟨rankQuery W+i.val, by have := i.isLt; unfold suffixDimension at this; omega⟩
+
+theorem suffixBasisIndex_val (i : Fin (suffixDimension W M)) :
+ (suffixBasisIndex W M i).val = (greedyRowIndex (appendRows W M) (combinedOrdinal W M i)).val - w :=
+ rfl
+
+/-- The scan reads `offset` and returns the original zero-based row in `found`.
+The prefix length lives in a register, so the same finite control serves every length. -/
+def suffixMachine (ports : ISA.Port r 0 → K) (equations scan : FiniteRoutine K)
+ (prefixRank ordinal offset found prefixRows dst : Fin r) : FiniteRoutine K :=
+ let withOffset := equations.followedBy (registerCall ports (.op offset .add prefixRank ordinal))
+ (withOffset.followedBy scan).followedBy (registerCall ports (.op dst .sub found prefixRows))
+
+/-- Correctness for an actual returning prefix scan. Its row result is the
+greedy index of the offset ordinal in the combined matrix. Rank and scan
+scratch registers may change inside their calls. -/
+theorem suffixMachine_runs (hb : RegisterBank ports bank persistent) (equations scan : FiniteRoutine K)
+ (prefixRank ordinal offset found prefixRows dst : Fin r) (i : Fin (suffixDimension W M))
+ {cap a B : ℕ} {rs middle : Regs r width}
+ (he : equations.BoundedRun cap a (bank rs) (bank middle))
+ (hp : (middle prefixRank).val = rankQuery W) (hi : (middle ordinal).val = i.val)
+ (fits : (combinedOrdinal W M i).val < 2^width)
+ (room : width + arithmeticClock width ≤ cap)
+ (hscan : let before := (RegCode.op offset .add prefixRank ordinal).exec middle
+ (before offset).val = (combinedOrdinal W M i).val → ∃ b ≤ B, ∃ after : Regs r width,
+ scan.BoundedRun cap b (bank before) (bank after) ∧
+ (after found).val = (greedyRowIndex (appendRows W M) (combinedOrdinal W M i)).val ∧
+ (after prefixRows).val = w) :
+ ∃ t ≤ a+arithmeticClock width+B+arithmeticClock width, ∃ out : Regs r width,
+ (suffixMachine ports equations scan prefixRank ordinal offset found prefixRows dst).BoundedRun
+ cap t (bank rs) (bank out) ∧ (out dst).val = (suffixBasisIndex W M i).val := by
+ let add : RegCode r := .op offset .add prefixRank ordinal
+ obtain ⟨s, hs, ha⟩ := registerCall_runs hb add middle cap room (fun j _ ↦ he.final_cap j)
+ have haFit : Arith.add.eval (middle prefixRank).val (middle ordinal).val < 2^width := by
+ change (middle prefixRank).val + (middle ordinal).val < 2^width
+ rw [hp, hi]
+ exact fits
+ have hval : (add.exec middle offset).val = (combinedOrdinal W M i).val := by
+ simp only [add, RegCode.exec, Function.update_self, Arith.word_val _ _ _ haFit, Arith.eval,
+ hp, hi, combinedOrdinal]
+ rfl
+ obtain ⟨b, hB, after, hcall, hfound, hrows⟩ := hscan hval
+ let sub : RegCode r := .op dst .sub found prefixRows
+ obtain ⟨u, hu, hsub⟩ := registerCall_runs hb sub after cap room (fun j _ ↦ hcall.final_cap j)
+ have hs' : s ≤ arithmeticClock width := hs
+ have hu' : u ≤ arithmeticClock width := hu
+ refine ⟨a+s+b+u, by omega, sub.exec after, ((he.followedBy ha).followedBy hcall).followedBy hsub, ?_⟩
+ have hsubFit : Arith.sub.eval (after found).val (after prefixRows).val < 2^width :=
+ (Nat.sub_le ..).trans_lt (after found).isLt
+ simp only [sub, RegCode.exec, Function.update_self, Arith.word_val _ _ _ hsubFit, Arith.eval,
+ hfound, hrows, suffixBasisIndex_val]
+ rfl
+
+/-- Instantiate the suffix query with the finite prefix-scan controller. The
+test and increment subroutines run on the current candidate. No call to select
+an earlier basis index occurs in the scan. -/
+theorem suffixGreedy_runs (hb : RegisterBank ports bank persistent)
+ (equations test bump : FiniteRoutine K) (flag : K)
+ (prefixRank ordinal offset found prefixSize dst : Fin r) (i : Fin (suffixDimension W M))
+ {cap a T B : ℕ} {rs middle : Regs r width}
+ (he : equations.BoundedRun cap a (bank rs) (bank middle))
+ (hp : (middle prefixRank).val = rankQuery W) (hi : (middle ordinal).val = i.val)
+ (fits : (combinedOrdinal W M i).val < 2^width)
+ (room : width + arithmeticClock width ≤ cap)
+ (input checked : ℕ → Regs r width)
+ (start : input 0 = (RegCode.op offset .add prefixRank ordinal).exec middle)
+ (hflag : ∀ j < w+n, bank (checked j) flag = [])
+ (htest : ∀ j (hj : j < w+n), ∃ t ≤ T, test.BoundedRun cap t (bank (input j))
+ (Function.update (bank (checked j)) flag [decide ((input 0 offset).val <
+ rankQuery (prefixRows (appendRows W M) (j+1) hj))]))
+ (hbump : ∀ j, j+1 < w+n → ∃ t ≤ B, bump.BoundedRun cap t (bank (checked j)) (bank (input (j+1))))
+ (hcursor : ∀ j < w+n, (checked j found).val = j ∧ (checked j prefixSize).val = w) :
+ ∃ t ≤ a+arithmeticClock width+(w+n)*(T+1+B)+arithmeticClock width, ∃ out : Regs r width,
+ (suffixMachine ports equations (greedyPrefix flag test bump)
+ prefixRank ordinal offset found prefixSize dst).BoundedRun cap t (bank rs) (bank out) ∧
+ (out dst).val = (suffixBasisIndex W M i).val := by
+ apply suffixMachine_runs W M hb equations (greedyPrefix flag test bump) _ _ _ _ _ _ i
+ he hp hi fits room
+ dsimp only
+ intro hOrdinal
+ have hO : (input 0 offset).val = (combinedOrdinal W M i).val := start ▸ hOrdinal
+ obtain ⟨b, hbnd, hscan⟩ := greedyPrefix_runs (appendRows W M) (combinedOrdinal W M i)
+ flag test bump (bank ∘ input) (bank ∘ checked) hflag (by
+ intro j hj
+ simpa only [Function.comp_apply, ← hO] using htest j hj) hbump
+ let j := greedyRowIndex (appendRows W M) (combinedOrdinal W M i)
+ exact ⟨b, hbnd, checked j.val, start ▸ hscan, hcursor j.val j.isLt⟩
+
+end RankQuery.Stack.Coordinate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateDynamic.lean b/lean/OAI/Computability/VPVNP/RankCoordinateDynamic.lean
new file mode 100644
index 0000000000..1961c773a7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateDynamic.lean
@@ -0,0 +1,166 @@
+import OAI.Computability.VPVNP.RankCoordinateOrdinalABI
+import OAI.Computability.VPVNP.RankCoordinateColumn
+
+/-! # Preparing the query-dependent Cramer row and target
+
+The rank and length of the equation block are fixed advice. Adding its rank to
+the current basis ordinal gives a greedy row query whose returned original
+index locates the source basis monomial. Adding the same rank to the next
+ordinal gives the row to replace in the square numerator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.Dynamic
+
+open RAMTape UniversalCountStack Dispatch BurstRAM SliceArithmetic
+
+variable {L : Type}
+
+/-- The eight-register ISA stack bank, including its persistent, scratch and private-log ports,
+together with the ordinal selector’s auxiliary ports. -/
+abbrev Host (L : Type) := ISA.Port 8 0 ⊕ L
+
+/-- Registers contain current, next, equation rank, equation-row count, the
+two combined ordinals, original selected row, and selected monomial ordinal. -/
+def regs {w : ℕ} (cur next rank rows offset replace original mono : ℕ) : Regs 8 w :=
+ ![Fin.ofNat _ cur, Fin.ofNat _ next, Fin.ofNat _ rank, Fin.ofNat _ rows,
+ Fin.ofNat _ offset, Fin.ofNat _ replace, Fin.ofNat _ original, Fin.ofNat _ mono]
+
+/-- Combine the live coordinate registers with the auxiliary stacks of the ordinal selector. -/
+def bank {w : ℕ} (aux : Stacks L) (rs : Regs 8 w) : Stacks (Host L) := Sum.elim (ISA.bank Fin.elim0 0 rs []) aux
+
+/-- Wire the selector's input and output to registers four and six while leaving its auxiliary
+ports in their own bank. -/
+def indexPorts : OrdinalRead.Port L → Host L
+ | .input => .inl (.reg 4) | .result => .inl (.reg 6) | .aux k => .inr k
+
+theorem indexPorts_injective : Function.Injective (indexPorts (L := L)) := by
+ intro a b he; cases a <;> cases b <;> simp_all [indexPorts]
+
+private def offsets : RegCode 8 := .seq (.op 4 .add 2 0) (.op 5 .add 2 1)
+private def removePrefix : RegCode 8 := .op 7 .sub 6 3
+
+/-- The greedy selector reads the current combined ordinal from register four.
+The two outputs for the Cramer caller are registers five and seven. -/
+def machine (selector : FiniteRoutine (OrdinalRead.Port L)) : FiniteRoutine (Host L) :=
+ (((offsets.compile.onPorts Sum.inl).followedBy (CallClear.clear (.inl (.reg 6)))).followedBy
+ (selector.onPorts indexPorts)).followedBy (removePrefix.compile.onPorts Sum.inl)
+
+/-- Tick allowance for computing the two rank offsets, clearing the selector’s result register
+and subtracting the equation-row count after selection. -/
+def overhead (w : ℕ) := registerClock w offsets+(w+1)+registerClock w removePrefix
+
+private theorem framed {w : ℕ} (aux : Stacks L) : RegisterBank Sum.inl (bank (w := w) aux) 0 := by
+ refine ⟨Sum.inl_injective, fun _ _ ↦ rfl, ?_⟩
+ intro _ _ k outside; cases k with
+ | inl i => exact (outside i rfl).elim
+ | inr => rfl
+
+private theorem outside_le {w cap : ℕ} (aux : Stacks L) (ha : ∀ k, (aux k).length ≤ cap) (rs : Regs 8 w)
+ (j : Host L) (hj : ∀ i, Sum.inl i ≠ j) : (bank aux rs j).length ≤ cap := by
+ cases j with
+ | inl i => exact (hj i rfl).elim
+ | inr k => exact ha k
+
+private theorem bank_cap {w cap : ℕ} {aux : Stacks L} (hw : w ≤ cap) (ha : ∀ k, (aux k).length ≤ cap)
+ (rs : Regs 8 w) (j : Host L) : (bank aux rs j).length ≤ cap := by
+ cases j with
+ | inl i => exact (RegisterTable.bank_length_le Fin.elim0 0 rs i).trans hw
+ | inr k => exact ha k
+
+private theorem add_offsets {w : ℕ} (u v rank size : ℕ) :
+ offsets.exec (regs (w := w) u v rank size 0 0 0 0) = regs u v rank size (rank+u) (rank+v) 0 0 := by
+ funext i
+ fin_cases i <;> simp [offsets, RegCode.exec, Arith.word, Arith.opcode, PrivateRAM.BinaryOp.eval, regs]
+ all_goals apply Fin.ext; simp [Fin.val_add, Nat.add_mod]
+
+private theorem sub_rows {w : ℕ} (u v rank size off k row : ℕ) (hsize : size < 2^w) (hrow : row < 2^w) :
+ removePrefix.exec (regs (w := w) u v rank size off k row 0) = regs u v rank size off k row (row-size) := by
+ funext i
+ fin_cases i <;> simp [removePrefix, RegCode.exec, regs]
+ apply Fin.ext
+ have hfit : Arith.sub.eval (Fin.ofNat (2^w) row).val (Fin.ofNat (2^w) size).val < 2^w := by
+ simp only [Arith.eval, Fin.val_ofNat, Nat.mod_eq_of_lt hrow, Nat.mod_eq_of_lt hsize]
+ exact (Nat.sub_le ..).trans_lt hrow
+ change (Arith.sub.word (Fin.ofNat (2^w) row) (Fin.ofNat (2^w) size)).val = (Fin.ofNat (2^w) (row-size)).val
+ rw [Arith.word_val _ _ _ hfit]
+ simp [Arith.eval, Nat.mod_eq_of_lt hrow, Nat.mod_eq_of_lt hsize,
+ Nat.mod_eq_of_lt ((Nat.sub_le row size).trans_lt hrow)]
+
+private theorem frame_outside [DecidableEq L] {w : ℕ} (u v rank size off k row : ℕ) (s out : Stacks L)
+ (j : Host L) (outside : ∀ z, indexPorts z ≠ j) :
+ bank out (regs (w := w) u v rank size off k row 0) j =
+ Function.update (bank s (regs (w := w) u v rank size off k 0 0)) (.inl (.reg 6)) [] j := by
+ have no : j ≠ .inl (.reg 6) := Ne.symm (outside .result)
+ rw [Function.update_of_ne no]
+ cases j with
+ | inr j => exact (outside (.aux j) rfl).elim
+ | inl j => cases j with
+ | reg z =>
+ have hne : z ≠ 6 := fun eq ↦ by subst z; exact outside .result rfl
+ fin_cases z <;> simp_all [bank, ISA.bank, regs]
+ | pub i => exact Fin.elim0 i
+ | persistent => change wordBits (0 : Word w) = _; rfl
+ | work i => change ([] : List Bool) = _; rfl
+ | logPort i => change ISA.logStacks ([] : PrivateRAM.WriteLog w) i = _; rfl
+
+variable [DecidableEq L] {F : Type*} [Field F] [DecidableEq F] {e n m w B S : ℕ}
+
+/-- Actual register and greedy-index execution. The result includes all offsets,
+the requested basis monomial, and the selector's reusable workspace. -/
+theorem machine_bounded (W : Matrix (Fin e) (Fin m) F) (M : Matrix (Fin n) (Fin m) F)
+ (cur next : Fin (suffixDimension W M)) (selector : FiniteRoutine (OrdinalRead.Port L))
+ {ready : Stacks L → Prop} (hc : OrdinalRead.CorrectSpace selector (greedyRowIndex (appendRows W M)) w B S ready)
+ (hw : w ≤ S) (fits : e+n < 2^w) (haux : ∀ s, ready s → ∀ k, (s k).length ≤ S)
+ (aux : Stacks L) (hr : ready aux) :
+ let rank := rankQuery W
+ let i := combinedOrdinal W M cur
+ let j := combinedOrdinal W M next
+ let row := greedyRowIndex (appendRows W M) i
+ ∃ t ≤ B+overhead w, ∃ out, ready out ∧ (machine selector).BoundedRun (S+overhead w) t
+ (bank aux (regs (w := w) cur next rank e 0 0 0 0))
+ (bank out (regs (w := w) cur next rank e i j row (suffixBasisIndex W M cur))) := by
+ let rank := rankQuery W
+ let i := combinedOrdinal W M cur
+ let j := combinedOrdinal W M next
+ let row := greedyRowIndex (appendRows W M) i
+ let rs := regs (w := w) cur next rank e i j 0 0
+ let rs' := regs (w := w) cur next rank e i j row 0
+ let cap := S+overhead w
+ have room : w+registerClock w offsets ≤ cap := Nat.add_le_add hw (by dsimp [cap,overhead]; omega)
+ have auxFit := haux aux hr
+ obtain ⟨a, ha, added⟩ := registerCall_runs (framed aux) offsets (regs (w := w) cur next rank e 0 0 0 0)
+ cap room (outside_le _ (fun k ↦ (auxFit k).trans (Nat.le_add_right ..)) _)
+ rw [add_offsets] at added
+ change (offsets.compile.onPorts Sum.inl).BoundedRun cap a _ (bank aux rs) at added
+ let slot : Host L := .inl (.reg 6)
+ let pre := Function.update (bank aux rs) slot []
+ have cleared := CallClear.clear_runs slot (bank aux rs)
+ rw [show ((bank aux rs) slot).length = w from length_wordBits _] at cleared
+ have clear : (CallClear.clear slot).BoundedRun cap (w+1) (bank aux rs) pre :=
+ spaceRun_of_steps cleared fun k ↦ Nat.add_le_add (bank_cap hw auxFit _ k) (by dsimp [overhead]; omega)
+ obtain ⟨b, hb, out, ho, find⟩ := hc i aux hr
+ have big : (selector.onPorts indexPorts).BoundedRun cap b pre (bank out rs') := by
+ refine FiniteRoutine.BoundedRun.framed (r := selector) indexPorts_injective
+ (find.mono_cap (show S ≤ cap from Nat.le_add_right ..)) clear.final_cap ?_ ?_ ?_
+ · intro k; cases k <;> rfl
+ · intro k; cases k <;> rfl
+ · exact frame_outside cur next rank e i j row aux out
+ obtain ⟨c, hs, subtracted⟩ := registerCall_runs (framed out) removePrefix rs' cap
+ (Nat.add_le_add hw (by dsimp [overhead]; omega)) (fun k _ ↦ big.final_cap k)
+ have hrow : row.val < 2^w := row.isLt.trans fits
+ have he : e < 2^w := (Nat.le_add_right ..).trans_lt fits
+ rw [show removePrefix.exec rs' = regs (w := w) cur next rank e i j row (row.val-e) from sub_rows cur next rank e i j row he hrow] at subtracted
+ have done := ((added.followedBy clear).followedBy big).followedBy subtracted
+ refine ⟨((a+(w+1))+b)+c, ?_, out, ho, ?_⟩
+ · dsimp [overhead]; omega
+ · exact done
+
+end RankQuery.Stack.Coordinate.Dynamic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateEvaluator.lean b/lean/OAI/Computability/VPVNP/RankCoordinateEvaluator.lean
new file mode 100644
index 0000000000..f7df9d52ef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateEvaluator.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.MacaulaySliceBasis
+import OAI.Computability.VPVNP.RankCoordinateColumn
+import OAI.Computability.VPVNP.RankCoordinateCramer
+import OAI.Computability.VPVNP.RankCoordinateReader
+
+/-!
+# From suffix coordinates to the evaluator's linear-step matrices
+
+A step of the counting evaluator starts at the current basis ordinal and chooses
+the next ordinal. Its scalar is the coefficient at the *next* ordinal in the
+image of the *current* basis vector. This is the entry of the transpose of the
+usual column-vector matrix. The indexed Cramer target therefore uses the current
+basis monomial, and its queried row ordinal uses the next one.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RadicalCertificate.MonomialIndex.QueryData
+
+open RankQuery FiniteSlice
+open RankQuery.Stack.Coordinate (combinedOrdinal)
+
+variable {K : Type*} [Field K] [DecidableEq K] {t e : ℕ} (S : QueryData t e K)
+
+/-- The row for the powered monomial obtained after acting on the current basis vector. -/
+abbrev stepTarget (op : Operation t) (j : Fin S.dimension) : Fin (size t S.columnDegree) → K :=
+ powerEntry S.power (S.target op (indexedDigits (S.basisIndex j)))
+
+/-- Cramer scalar for the next basis coordinate after acting on the current vector. -/
+def stepCoordinate (op : Operation t) (current next : Fin S.dimension) : K :=
+ greedyCoordinateQuery (appendRows S.equations S.monomials) (S.stepTarget op current)
+ (combinedOrdinal S.equations S.monomials next)
+
+theorem matrixEntry_eq_greedyCoordinate (op : Operation t) (i j : Fin S.dimension) :
+ S.matrixEntry op i j = greedyCoordinateQuery (appendRows S.equations S.monomials)
+ (S.stepTarget op j) (combinedOrdinal S.equations S.monomials i) :=
+ quotientCoordinate_at_suffix S.equations S.monomials (S.stepTarget op j) i
+
+open RankQuery.Stack RankQuery.Stack.Coordinate SliceArithmetic
+
+/-- The packed Cramer quotient has the correct value over the advised ground
+field, even when that field is presented through an algebra equivalence. -/
+theorem minorQuotient_eq_stepCoordinate {p deg : ℕ} [Fact p.Prime] [NeZero deg]
+ [Algebra (ZMod p) K] (c : Vector p deg) [Fact (Irreducible (modulus c))]
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (op : Operation t)
+ (current next : Fin S.dimension)
+ (N D : Matrix (Fin (rankQuery (appendRows S.equations S.monomials)))
+ (Fin (rankQuery (appendRows S.equations S.monomials))) (Scalar c))
+ (hN : N.map (φ.toRingEquiv.toRingHom.comp (Scalar.interpretation c)) =
+ replacedMinor (greedyRowBasis (appendRows S.equations S.monomials))
+ (coordinateColumns _ (greedyRowBasis_fullRank _)) (S.stepTarget op current)
+ (combinedOrdinal S.equations S.monomials next))
+ (hD : D.map (φ.toRingEquiv.toRingHom.comp (Scalar.interpretation c)) =
+ (greedyRowBasis (appendRows S.equations S.monomials)).submatrix id
+ (coordinateColumns _ (greedyRowBasis_fullRank _))) :
+ φ (value (modulus c) (Cramer.minorQuotient c N D)) = S.stepCoordinate op current next := by
+ rw [Cramer.minorQuotient, value_mul, value_inverse, ← div_eq_mul_inv, map_div₀]
+ exact topPencil_div_rowCoordinate (φ.toRingEquiv.toRingHom.comp (Scalar.interpretation c))
+ N D _ _ _ _ hN hD
+
+variable {E : Type*} [Field E] [Algebra K E] [Fintype K]
+
+/-- The linear map whose transpose is used in the basis-index transition. -/
+noncomputable def Operation.linearAction {A : Type*} [CommRing A] [Algebra K A]
+ (op : Operation t) (X : Fin t → A) : A →ₗ[K] A :=
+ match op with
+ | .label i => LinearMap.mulLeft K (X i)
+ | .frobenius => (FiniteField.frobeniusAlgHom K A).toLinearMap
+
+variable [IsAlgClosed E] (F : Fin e → MvPolynomial (Fin t) K)
+
+/-- The encoded ordinal width can present any natural number equal to the computed
+slice dimension. The row-column ordering here is the order of evaluator transitions. -/
+theorem stepCoordinate_eq_transition {D : ℕ} (hd : D = S.dimension)
+ (h : S.Presents F) (b : Module.Basis (Fin D) K (CoordinateAlgebra K (points F E)))
+ (hb : ∀ i, b i = S.listing F E (S.basisIndex (Fin.cast hd i))) (op : Operation t)
+ (current next : Fin D) :
+ S.stepCoordinate op (Fin.cast hd current) (Fin.cast hd next) =
+ ((LinearMap.toMatrixAlgEquiv b) (op.linearAction (coordinateLabel (points F E)))).transpose
+ current next := by
+ subst D
+ rw [stepCoordinate, ← S.matrixEntry_eq_greedyCoordinate op,
+ S.matrixEntry_eq_repr F h b hb op, Matrix.transpose_apply, LinearMap.toMatrixAlgEquiv_apply]
+ cases op with
+ | label => rfl
+ | frobenius =>
+ simp [Operation.apply, Operation.linearAction, h.fieldOrder_eq, FiniteField.frobeniusAlgHom_apply]
+
+end RadicalCertificate.MonomialIndex.QueryData
+
+namespace RankQuery.Stack.Coordinate.Reader
+
+open RAMTape SliceArithmetic Evaluator Evaluator.MatrixCallbacks FiniteSlice
+open RadicalCertificate.MonomialIndex RadicalCertificate.MonomialIndex.QueryData
+
+variable {K : Type} [Field K] [Fintype K] [DecidableEq K] {E : Type*} [Field E]
+ [Algebra K E] [IsAlgClosed E] {t e : ℕ} {P : Type} [DecidableEq P]
+ {p deg w v : ℕ} [Fact p.Prime] [Algebra (ZMod p) K] {c : Vector p deg}
+
+/-- An actual returning suffix-coordinate program meets the evaluator's entry-reader
+contract. Its packed result is identified by its value in the ground field, and its
+registers and private bank are restored at the return. -/
+theorem readsEntry_of_suffix (S : QueryData t e K) (F : Fin e → MvPolynomial (Fin t) K)
+ (h : S.Presents F) (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K)
+ (dim : BurstRAM.Word v) (hd : dim.val = S.dimension)
+ (b : Module.Basis (Fin dim.val) K (CoordinateAlgebra K (points F E)))
+ (hb : ∀ i, b i = S.listing F E (S.basisIndex (Fin.cast hd i)))
+ (op : Operation t) (label time : ℕ) (extra : Stacks P) (core : FiniteRoutine (Port P))
+ (query : ∀ current next : Fin dim.val, ∃ d ≤ time, ∃ a : Vector p deg,
+ φ (value (modulus c) a) = S.stepCoordinate op (Fin.cast hd current) (Fin.cast hd next) ∧
+ core.Runs d (bank (List.replicate label true) (ordinal dim current) (ordinal dim next) [] extra)
+ (bank (List.replicate label true) (ordinal dim current) (ordinal dim next)
+ (SliceArithmeticRound.packed w (List.ofFn a)) extra)) :
+ ReadsEntry φ dim extra (install core) w label time
+ ((LinearMap.toMatrixAlgEquiv b) (op.linearAction (coordinateLabel (points F E)))).transpose := by
+ apply readsEntry
+ intro current next
+ obtain ⟨d, ht, a, hval, hr⟩ := query current next
+ let T := ((LinearMap.toMatrixAlgEquiv b) (op.linearAction (coordinateLabel (points F E)))).transpose
+ have hentry : φ (value (modulus c) a) = T current next :=
+ hval.trans (S.stepCoordinate_eq_transition F hd h b hb op current next)
+ have he : a = scalarEncoding φ (T current next) :=
+ (valueEquiv c).injective (φ.injective (hentry.trans (map_scalarEncoding φ _).symm))
+ refine ⟨d, ht, ?_⟩
+ change core.Runs d _ (bank _ _ _ (SliceArithmeticRound.packed w
+ (List.ofFn (scalarEncoding φ (T current next)))) extra)
+ rw [← he]
+ exact hr
+
+end RankQuery.Stack.Coordinate.Reader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateFieldEquiv.lean b/lean/OAI/Computability/VPVNP/RankCoordinateFieldEquiv.lean
new file mode 100644
index 0000000000..59adcc08b6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateFieldEquiv.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.CoordinateQueries
+import OAI.Computability.VPVNP.RankQueryStackInterpretation
+
+/-!
+# Transport of greedy coordinate queries across the advised field isomorphism
+
+Every prefix rank is preserved when entries are mapped into an isomorphic
+field. The two greedy scans therefore select the same physical indices. The
+quotient of the two determinants then transports entrywise, for arbitrary
+target rows.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+variable {L F : Type*} [Field L] [Field F] [DecidableEq L] [DecidableEq F] {n m r : ℕ}
+
+/-- The physical rank scan commutes with interpretation into an isomorphic field. -/
+theorem rankQuery_map_eq (φ : L ≃+* F) (M : Matrix (Fin n) (Fin m) L) :
+ rankQuery (M.map φ) = rankQuery M := by
+ rw [rankQuery_eq, rankQuery_eq]
+ exact (Stack.SchurKey.computeRank_interpreted φ.toRingHom φ.injective M).symm.trans
+ (Stack.SchurKey.computeRank_eq M)
+
+private theorem firstPrefixAbove_congr (f g : (s : ℕ) → s ≤ n → ℕ) (h : f = g) (k : ℕ)
+ (hf : ∃ i : Fin n, k < f (i.val+1) i.isLt) (hg : ∃ i : Fin n, k < g (i.val+1) i.isLt) :
+ firstPrefixAbove f k hf = firstPrefixAbove g k hg := by
+ subst g
+ rfl
+
+/-- A prefix-rank increase occurs at the same original row after mapping
+the field. Casts identify only the two bounds on the dense ordinal. -/
+theorem greedyRowIndex_map (φ : L ≃+* F) (M : Matrix (Fin n) (Fin m) L)
+ (i : Fin (rankQuery (M.map φ))) :
+ greedyRowIndex (M.map φ) i = greedyRowIndex M (Fin.cast (rankQuery_map_eq φ M) i) := by
+ unfold greedyRowIndex
+ apply firstPrefixAbove_congr
+ funext s hs
+ exact rankQuery_map_eq φ (prefixRows M s hs)
+
+/-- The two assembled row bases agree entrywise under the field map. -/
+theorem greedyRowBasis_map_apply (φ : L ≃+* F) (M : Matrix (Fin n) (Fin m) L)
+ (i : Fin (rankQuery (M.map φ))) (j : Fin m) :
+ greedyRowBasis (M.map φ) i j = φ (greedyRowBasis M (Fin.cast (rankQuery_map_eq φ M) i) j) := by
+ change φ (M (greedyRowIndex (M.map φ) i) j) = φ (M _ j)
+ rw [greedyRowIndex_map]
+
+/-- On a full-row-rank matrix the transpose prefix scan selects the same columns. -/
+theorem coordinateColumns_map (φ : L ≃+* F) (B : Matrix (Fin r) (Fin m) L)
+ (h : B.rank = r) (h' : (B.map φ).rank = r) (i : Fin r) :
+ coordinateColumns (B.map φ) h' i = coordinateColumns B h i := by
+ unfold coordinateColumns
+ exact greedyRowIndex_map φ B.transpose _
+
+private theorem columns_cast {r' : ℕ} (φ : L ≃+* F) (eq : r' = r)
+ (B : Matrix (Fin r) (Fin m) L) (D : Matrix (Fin r') (Fin m) F)
+ (mapped : ∀ i j, D i j = φ (B (Fin.cast eq i) j)) (h : B.rank = r) (h' : D.rank = r')
+ (i : Fin r') : coordinateColumns D h' i = coordinateColumns B h (Fin.cast eq i) := by
+ subst r'
+ have he : D = B.map φ := Matrix.ext mapped
+ subst D
+ exact coordinateColumns_map φ B h h' i
+
+/-- Columns selected from the already selected rows commute with the
+isomorphism, including when the original matrix is rectangular or singular. -/
+theorem greedyColumns_map (φ : L ≃+* F) (M : Matrix (Fin n) (Fin m) L)
+ (i : Fin (rankQuery (M.map φ))) :
+ coordinateColumns (greedyRowBasis (M.map φ)) (greedyRowBasis_fullRank _) i =
+ coordinateColumns (greedyRowBasis M) (greedyRowBasis_fullRank _) (Fin.cast (rankQuery_map_eq φ M) i) :=
+ columns_cast φ (rankQuery_map_eq φ M) _ _ (greedyRowBasis_map_apply φ M) _ _ i
+
+omit [DecidableEq L] [DecidableEq F] in
+/-- Replacing the target row and dividing the two determinants commute
+with the field map, even for targets outside the selected rows' span. -/
+theorem rowCoordinateQuery_map (φ : L ≃+* F) (B : Matrix (Fin r) (Fin m) L) (cols : Fin r → Fin m)
+ (target : Fin m → L) (i : Fin r) :
+ rowCoordinateQuery squareDetQuery (B.map φ) cols (φ ∘ target) i =
+ φ (rowCoordinateQuery squareDetQuery B cols target i) := by
+ simp only [rowCoordinateQuery, squareDetQuery_eq, map_div₀]
+ let D := B.submatrix id cols
+ change ((D.map φ).updateRow i ((φ ∘ target) ∘ cols)).det / (D.map φ).det =
+ φ ((D.updateRow i (target ∘ cols)).det) / φ D.det
+ have hn := φ.toRingHom.map_det (D.updateRow i (target ∘ cols))
+ have hd := φ.toRingHom.map_det D
+ change φ ((D.updateRow i (target ∘ cols)).det) = ((D.updateRow i (target ∘ cols)).map φ).det at hn
+ rw [Matrix.map_updateRow] at hn
+ rw [hn, show φ D.det = (D.map φ).det from hd]
+ rfl
+
+private theorem coordinate_cast {r' : ℕ} (φ : L ≃+* F) (eq : r' = r)
+ (B : Matrix (Fin r) (Fin m) L) (D : Matrix (Fin r') (Fin m) F)
+ (mapped : ∀ i j, D i j = φ (B (Fin.cast eq i) j)) (h : B.rank = r) (h' : D.rank = r')
+ (target : Fin m → L) (i : Fin r') :
+ coordinateQuery D h' (φ ∘ target) i = φ (coordinateQuery B h target (Fin.cast eq i)) := by
+ subst r'
+ have he : D = B.map φ := Matrix.ext mapped
+ subst D
+ unfold coordinateQuery
+ rw [show coordinateColumns (B.map φ) h' = coordinateColumns B h from funext (coordinateColumns_map φ B h h')]
+ exact rowCoordinateQuery_map φ B _ target i
+
+/-- The physical greedy coordinate over the advised representation maps to
+the corresponding coordinate over the represented field. -/
+theorem greedyCoordinateQuery_map (φ : L ≃+* F) (M : Matrix (Fin n) (Fin m) L)
+ (target : Fin m → L) (i : Fin (rankQuery (M.map φ))) :
+ greedyCoordinateQuery (M.map φ) (φ ∘ target) i =
+ φ (greedyCoordinateQuery M target (Fin.cast (rankQuery_map_eq φ M) i)) :=
+ coordinate_cast φ (rankQuery_map_eq φ M) _ _ (greedyRowBasis_map_apply φ M) _ _ target i
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateLabelWord.lean b/lean/OAI/Computability/VPVNP/RankCoordinateLabelWord.lean
new file mode 100644
index 0000000000..a1f2472310
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateLabelWord.lean
@@ -0,0 +1,67 @@
+import OAI.Computability.VPVNP.RAMTapeUnaryWord
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+import OAI.Computability.VPVNP.StructuredStackCall
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-! # Encoding the one-based label in a Cramer target row
+
+The evaluator's label port stores its zero-based ordinal in unary. The powered
+monomial reader takes a fixed-width binary mark with value one greater. The
+original unary stream survives the conversion and can be reused on return.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.LabelWord
+
+open RAMTape UniversalCountStack
+
+private def count : FiniteRoutine UnaryWord.Port :=
+ .ofRoutine (Routine.ofCode (UnaryWord.code 0) .count .done)
+
+/-- Convert a zero-based unary label ordinal to its one-based binary mark, preserving the
+source stream. -/
+def machine : FiniteRoutine UnaryWord.Port :=
+ ((SuccessorFields.prependCopy .src .pending .tmp).followedBy
+ (FiniteRoutine.ofRoutine (Routine.push .pending true))).followedBy count
+
+/-- Step count for copying the unary label, appending one marker, and counting into a
+fixed-width word. -/
+def clock (label w : ℕ) := ((5*label+2)+1)+((label+1)*(4*w+3)+1)
+
+theorem machine_bounded (label w : ℕ) (fits : label+1 < 2^w) :
+ let bits := List.replicate label true
+ machine.BoundedRun (max label w + clock label w) (clock label w)
+ (UnaryWord.store bits [] (digits w 0) [] []) (UnaryWord.store bits [] (digits w (label+1)) [] []) := by
+ let bits := List.replicate label true
+ let src := UnaryWord.store bits [] (digits w 0) [] []
+ let saved := UnaryWord.store bits bits (digits w 0) [] []
+ let pre := UnaryWord.store bits (List.replicate (label+1) true) (digits w 0) [] []
+ have cp := SuccessorFields.prependCopy_runs UnaryWord.Port.src .pending .tmp (by decide) (by decide) (by decide) src rfl
+ have hs : Function.update src .pending (bits++[]) = saved := by funext k; cases k <;> simp [src, saved, UnaryWord.store]
+ change (SuccessorFields.prependCopy .src .pending .tmp).Runs (5*bits.length+2) src
+ (Function.update src .pending (bits++[])) at cp
+ rw [hs, show bits.length = label from List.length_replicate] at cp
+ have pushed := Routine.runs_push UnaryWord.Port.pending true saved
+ have hp : Function.update saved .pending (true :: saved .pending) = pre := by funext k; cases k <;> rfl
+ rw [hp] at pushed
+ have ctl := Routine.runs_ofCode (by decide : UnaryWord.Phase.count (p := 0) ≠ .done) rfl
+ (UnaryWord.count_fixed 0 w (label+1) bits [] fits)
+ have call : count.Runs ((label+1)*(4*w+3)+1) pre (UnaryWord.store bits [] (digits w (label+1)) [] []) := by
+ dsimp only [count, FiniteRoutine.ofRoutine, FiniteRoutine.Runs, pre]
+ rw [digits_zero]
+ exact ctl
+ have pushRun : (FiniteRoutine.ofRoutine (Routine.push UnaryWord.Port.pending true)).Runs 1 saved pre := pushed
+ have run := (cp.followedBy pushRun).followedBy call
+ apply spaceRun_of_steps (show machine.Runs (clock label w) src _ from run)
+ intro k
+ apply Nat.add_le_add_right
+ cases k <;> simp [src, bits, UnaryWord.store]
+
+end RankQuery.Stack.Coordinate.LabelWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateMinor.lean b/lean/OAI/Computability/VPVNP/RankCoordinateMinor.lean
new file mode 100644
index 0000000000..e01816c460
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateMinor.lean
@@ -0,0 +1,148 @@
+import OAI.Computability.VPVNP.RankCoordinateDimension
+import OAI.Computability.VPVNP.RankCoordinateColumn
+
+/-! # Physical scalar reads from the two Cramer minors
+
+A query recomputes the two selected indices in the original matrix and its
+transpose. For the replaced-row minor, a register equality selects either an
+ordinary matrix entry or the target entry at the selected column. All large
+matrices are accessed through scalar calls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.Minor
+
+open RAMTape UniversalCountStack Dispatch BurstRAM TapeWord
+
+variable {K : Type} [DecidableEq K] {r width : ℕ}
+
+/-- Compare two caller registers and use the returned bit to enter a subroutine. -/
+def equalBranch (ports : ISA.Port r 0 → K) (x y : Fin r) (ordinary replacement : FiniteRoutine K) :
+ FiniteRoutine K :=
+ ((ISA.compareRegs .eq x y).onPorts ports).followedBy (.ofRoutine
+ (Routine.popCase (ports (.work 0)) (Routine.halt false) ordinary.body replacement.body))
+
+private theorem choose_runs {flag : K} (low high : FiniteRoutine K) {cap t : ℕ} {s u : Stacks K}
+ {b : Bool} (hf : s flag = []) (hcap : ∀ k, (Function.update s flag [b] k).length ≤ cap)
+ (arm : (if b then high else low).BoundedRun cap t s u) :
+ (FiniteRoutine.ofRoutine (Routine.popCase flag (Routine.halt false) low.body high.body)).BoundedRun cap (t+1)
+ (Function.update s flag [b]) u := by
+ let code := Routine.popCase flag (Routine.halt false) low.body high.body
+ change SpaceRun code.standalone cap (t+1) (some code.entry) (Function.update s flag [b]) none u
+ have back : Function.update s flag [] = s := by rw [← hf, Function.update_eq_self]
+ cases b with
+ | false =>
+ change low.BoundedRun cap t s u at arm
+ have tail := arm.linkRoutine code (Sum.inr ∘ Sum.inr ∘ Sum.inl) none (fun _ ↦ rfl)
+ refine .cons hcap ?_ tail
+ simpa only [Function.update_self, List.head?_cons, List.tail_cons, Function.update_idem, back, Function.comp_apply] using
+ (StackStep.pop (s := Function.update s flag [false]) (show code.standalone (some code.entry) = _ from rfl))
+ | true =>
+ change high.BoundedRun cap t s u at arm
+ have tail := arm.linkRoutine code (Sum.inr ∘ Sum.inr ∘ Sum.inr) none (fun _ ↦ rfl)
+ refine .cons hcap ?_ tail
+ simpa only [Function.update_self, List.head?_cons, List.tail_cons, Function.update_idem, back, Function.comp_apply] using
+ (StackStep.pop (s := Function.update s flag [true]) (show code.standalone (some code.entry) = _ from rfl))
+
+/-- Branching preserves the call's space cap even if one of its subcalls takes
+exponentially many steps. The comparison itself scans only two binary words. -/
+theorem equalBranch_runs {ports : ISA.Port r 0 → K} {bank : Regs r width → Stacks K} {persistent : Word width}
+ (hb : RegisterBank ports bank persistent) (rs : Regs r width) (x y : Fin r) (low high : FiniteRoutine K)
+ {cap t : ℕ} {out : Stacks K} (hc : width+(20*width+10) ≤ cap)
+ (arm : (if rs x = rs y then high else low).BoundedRun cap t (bank rs) out) :
+ (equalBranch ports x y low high).BoundedRun cap ((20*width+10)+(t+1)) (bank rs) out := by
+ let localBank := ISA.bank Fin.elim0 persistent rs []
+ let bit := decide (rs x = rs y)
+ have step := ISA.compareRegs_run .eq x y Fin.elim0 persistent rs []
+ have small := spaceRun_of_steps (cap := cap) step fun k ↦
+ (Nat.add_le_add_right (RegisterTable.bank_length_le Fin.elim0 persistent rs k) _).trans hc
+ have cmp := FiniteRoutine.BoundedRun.onPorts (a := ISA.compareRegs .eq x y) hb.injective (bank rs) small
+ (fun k _ ↦ arm.initial_cap k)
+ have install : installStacks ports (bank rs) localBank = bank rs :=
+ installStacks_eq hb.injective _ _ (hb.inside rs)
+ rw [← installStacks_update hb.injective] at cmp
+ change SpaceRun _ _ _ _ (installStacks ports (bank rs) localBank) none
+ (Function.update (installStacks ports (bank rs) localBank) (ports (.work 0)) [bit]) at cmp
+ rw [install] at cmp
+ have flag := hb.inside rs (.work 0)
+ change bank rs (ports (.work 0)) = [] at flag
+ have hchoice := choose_runs low high flag cmp.final_cap (b := bit)
+ (by simpa only [bit, decide_eq_true_eq] using arm)
+ exact FiniteRoutine.BoundedRun.followedBy cmp hchoice
+
+variable {F : Type*} [Field F] [DecidableEq F] {n m : ℕ}
+
+/-- The original column selected at this ordinal by the greedy row algorithm on the transpose. -/
+def column (A : Matrix (Fin n) (Fin m) F) (j : Fin (rankQuery A)) : Fin m :=
+ greedyRowIndex A.transpose (Fin.cast (by rw [rankQuery_eq, rankQuery_eq, Matrix.rank_transpose]) j)
+
+/-- The original row and column bases, presented by two independent index queries. -/
+def square (A : Matrix (Fin n) (Fin m) F) := A.submatrix (greedyRowIndex A) (column A)
+
+/-- Replace the selected row of the greedy square minor by the target restricted to the same
+selected columns. -/
+def replaced (A : Matrix (Fin n) (Fin m) F) (target : Fin m → F) (k : Fin (rankQuery A)) :=
+ (square A).updateRow k (target ∘ column A)
+
+theorem greedyCoordinate_eq (A : Matrix (Fin n) (Fin m) F) (target : Fin m → F) (k : Fin (rankQuery A)) :
+ greedyCoordinateQuery A target k = squareDetQuery (replaced A target k) / squareDetQuery (square A) :=
+ greedyCoordinateQuery_eq_baseColumns A target k
+
+/-- The two index calls precede a single scalar read. -/
+def read (rows cols scalar : FiniteRoutine K) : FiniteRoutine K := (rows.followedBy cols).followedBy scalar
+
+/-- Entry query for the unchanged square minor. The raw scalar reader sees an original
+row and an original column in the caller's registers. -/
+theorem read_square_runs (A : Matrix (Fin n) (Fin m) F) (i j : Fin (rankQuery A)) (rows cols scalar : FiniteRoutine K)
+ {cap tr tc ts : ℕ} {start middle : Stacks K} (located : Fin n → Fin m → Stacks K) (output : F → Stacks K)
+ (rowRun : rows.BoundedRun cap tr start middle)
+ (colRun : cols.BoundedRun cap tc middle (located (greedyRowIndex A i) (column A j)))
+ (scalarRun : scalar.BoundedRun cap ts (located (greedyRowIndex A i) (column A j))
+ (output (A (greedyRowIndex A i) (column A j)))) :
+ (read rows cols scalar).BoundedRun cap (tr+tc+ts) start (output (square A i j)) :=
+ (rowRun.followedBy colRun).followedBy scalarRun
+
+/-- Entry query for the row-replaced square minor. The last comparison uses the
+original query ordinal, and the target is evaluated at the same selected column. -/
+theorem read_replaced_runs (A : Matrix (Fin n) (Fin m) F) (target : Fin m → F)
+ (k i j : Fin (rankQuery A)) {ports : ISA.Port r 0 → K} {bank : Regs r width → Stacks K}
+ {persistent : Word width} (hb : RegisterBank ports bank persistent) (rowOrdinal replaceOrdinal : Fin r)
+ (rows cols scalar targetRead : FiniteRoutine K) {cap tr tc ts tt : ℕ} {start middle : Stacks K}
+ (located : Fin n → Fin m → Regs r width) (output : F → Stacks K)
+ (rowRun : rows.BoundedRun cap tr start middle)
+ (colRun : cols.BoundedRun cap tc middle (bank (located (greedyRowIndex A i) (column A j))))
+ (scalarRun : scalar.BoundedRun cap ts (bank (located (greedyRowIndex A i) (column A j)))
+ (output (A (greedyRowIndex A i) (column A j))))
+ (targetRun : targetRead.BoundedRun cap tt (bank (located (greedyRowIndex A i) (column A j)))
+ (output (target (column A j))))
+ (hi : ∀ a b, (located a b rowOrdinal).val = i.val) (hk : ∀ a b, (located a b replaceOrdinal).val = k.val)
+ (hc : width+(20*width+10) ≤ cap) :
+ ∃ t ≤ tr+tc+(20*width+10)+(max ts tt+1),
+ (read rows cols (equalBranch ports rowOrdinal replaceOrdinal scalar targetRead)).BoundedRun cap t start
+ (output (replaced A target k i j)) := by
+ let a := greedyRowIndex A i
+ let b := column A j
+ have eqTest : located a b rowOrdinal = located a b replaceOrdinal ↔ i = k := by
+ rw [Fin.ext_iff, hi, hk, Fin.ext_iff]
+ by_cases he : i = k
+ · have arm := targetRun
+ have h := equalBranch_runs hb (located a b) rowOrdinal replaceOrdinal scalar targetRead hc
+ (t := tt) (out := output (target b)) (by rw [ite_eq_left (eqTest.mpr he)]; exact arm)
+ refine ⟨(tr+tc)+((20*width+10)+(tt+1)), by have := Nat.le_max_right ts tt; omega, ?_⟩
+ simpa only [read, replaced, he, Matrix.updateRow_self, Function.comp_apply, b] using
+ (rowRun.followedBy colRun).followedBy h
+ · have arm := scalarRun
+ have h := equalBranch_runs hb (located a b) rowOrdinal replaceOrdinal scalar targetRead hc
+ (t := ts) (out := output (A a b)) (by rw [ite_eq_right (eqTest.not.mpr he)]; exact arm)
+ refine ⟨(tr+tc)+((20*width+10)+(ts+1)), by have := Nat.le_max_left ts tt; omega, ?_⟩
+ simpa only [read, replaced, Matrix.updateRow_ne he, square, Matrix.submatrix_apply, a, b] using
+ (rowRun.followedBy colRun).followedBy h
+
+end RankQuery.Stack.Coordinate.Minor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateNativeReader.lean b/lean/OAI/Computability/VPVNP/RankCoordinateNativeReader.lean
new file mode 100644
index 0000000000..21d1fca61f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateNativeReader.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.RankCoordinateReaderSpace
+import OAI.Computability.VPVNP.RankQueryRoutineSpace
+
+/-! # Returning a Cramer quotient to the native evaluator
+
+Both determinant programs and the quotient arithmetic run inside a finite
+workspace. After the quotient has been copied into the evaluator's scalar
+operand, one pass clears every workspace stack, including the two determinant
+results and any registers left by the coefficient readers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.NativeReader
+
+open RAMTape UniversalCountStack SliceArithmetic
+open Cramer SchurPair
+
+variable {A H K L : Type}
+
+/-- The scalar reader's public ports with separate auxiliary banks for advice and writable
+workspace. -/
+abbrev Bus (A H : Type) := Reader.Port (A ⊕ H)
+/-- The denominator, numerator, and quotient working banks of the paired Schur query. -/
+abbrev Workspace (K L : Type) := SchurPair.Host K L
+
+/-- Embed one stack of the Schur-pair workspace in the writable portion of the scalar-reader
+bus. -/
+def port (host : Workspace K L ↪ H) (i : Workspace K L) : Bus A H :=
+ .aux (.inr (host i))
+
+theorem port_injective (host : Workspace K L ↪ H) : Function.Injective (port (A := A) host) := by
+ intro x y h; exact host.injective (Sum.inr.inj (Reader.Port.aux.inj h))
+
+/-- The multiplication accumulator containing the final numerator divided by the denominator. -/
+def quotient : Workspace K L := .inr (.inr (.inl (.inl (.inr .acc))))
+
+/-- Combine the label, live basis ordinals, scalar result, immutable advice, and writable
+workspace into one reader state. -/
+def state (label current next result : List Bool) (advice : Stacks A) (work : Stacks H) :=
+ Reader.bank label current next result (Sum.elim advice work)
+
+variable [DecidableEq A] [DecidableEq H] [Fintype H]
+
+/-- Copy the completed quotient to the public scalar result and reclaim the reader's working
+stacks. -/
+noncomputable def finish (host : Workspace K L ↪ H) (scratch : H) : FiniteRoutine (Bus A H) :=
+ (SuccessorFields.prependCopy (port host quotient) .result (.aux (.inr scratch))).followedBy Reader.reclaim
+
+/-- Bound the final result copy and cleanup scan using the workspace's port count and peak
+stack height. -/
+def returnClock (H : Type) [Fintype H] (peak : ℕ) := 5*peak+2 + (Fintype.card H*(peak+1)+1)
+
+theorem finish_bounded (host : Workspace K L ↪ H) (scratch : H) (disjoint : ∀ i, host i ≠ scratch)
+ (label current next : List Bool) (advice : Stacks A) (work : Stacks H) (answer : List Bool)
+ (peak : ℕ) (start : ∀ i, (state label current next [] advice work i).length ≤ peak)
+ (hs : work scratch = []) (hq : work (host quotient) = answer) :
+ ∃ t ≤ returnClock H peak, (finish host scratch).BoundedRun (peak+returnClock H peak) t
+ (state label current next [] advice work)
+ (state label current next answer advice (fun _ => [])) := by
+ let initial := state label current next [] advice work
+ let copied := state label current next answer advice work
+ have hcopy := SuccessorFields.prependCopy_runs (port (A := A) host quotient) .result (.aux (.inr scratch))
+ (fun h => by contradiction) (fun h => disjoint quotient (Sum.inr.inj (Reader.Port.aux.inj h)))
+ (fun h => by contradiction) initial hs
+ have hcopied : Function.update initial .result (initial (port host quotient) ++ initial .result) = copied := by
+ funext i; cases i <;> first | rfl | (change work (host quotient) ++ [] = answer; rw [hq,List.append_nil])
+ rw [hcopied] at hcopy
+ obtain ⟨t,ht,hclean⟩ := Reader.reclaim_runs label current next answer advice work peak (fun h => start (.aux (.inr h)))
+ have combined := hcopy.followedBy hclean
+ have hb : 5*(initial (port host quotient)).length+2+t ≤ returnClock H peak :=
+ Nat.add_le_add (Nat.add_le_add_right (Nat.mul_le_mul_left 5 (start _)) _) ht
+ exact ⟨_,hb,spaceRun_of_steps combined (fun k => Nat.add_le_add (start k) hb)⟩
+
+/-- Prepare the live arguments, evaluate the Schur pair on its mounted workspace, then return
+the quotient and clean up. -/
+noncomputable def core (host : Workspace K L ↪ H) (scratch : H) (prepare : FiniteRoutine (Bus A H))
+ (a : Engine.Actions K) (b : Engine.Actions L) : FiniteRoutine (Bus A H) :=
+ (prepare.followedBy ((SchurPair.query a b).onPorts (port host))).followedBy (finish host scratch)
+
+variable [DecidableEq K] [DecidableEq L]
+
+/-- Execute a prepared physical determinant pair and return with precisely
+the same label, basis indices and persistent advice. -/
+theorem core_bounded (host : Workspace K L ↪ H) (scratch : H) (disjoint : ∀ i, host i ≠ scratch)
+ (prepare : FiniteRoutine (Bus A H)) (a : Engine.Actions K) (b : Engine.Actions L)
+ (label current next : List Bool) (advice : Stacks A) (work : Stacks H) (hs : work scratch = [])
+ (before after : Stacks (Workspace K L)) (hin : ∀ i, work (host i) = before i)
+ (answer : List Bool) (hq : after quotient = answer) {peak setup query : ℕ}
+ (hsetup : prepare.BoundedRun peak setup (state label current next [] advice (fun _ => []))
+ (state label current next [] advice work))
+ (hquery : (SchurPair.query a b).BoundedRun peak query before after) :
+ ∃ t ≤ setup+query+returnClock H peak,
+ (core host scratch prepare a b).BoundedRun (peak+returnClock H peak) t
+ (state label current next [] advice (fun _ => []))
+ (state label current next answer advice (fun _ => [])) := by
+ let out := installStacks host work after
+ have hrun : ((SchurPair.query a b).onPorts (port host)).BoundedRun peak query
+ (state label current next [] advice work) (state label current next [] advice out) := by
+ apply FiniteRoutine.BoundedRun.framed (port_injective host) hquery hsetup.final_cap hin
+ · exact fun i => installStacks_at host.injective work after i
+ · intro i hi
+ cases i with
+ | aux i =>
+ rcases i with i|i
+ · rfl
+ · exact installStacks_outside work after (fun k hk => hi k (congrArg (fun z => Reader.Port.aux (Sum.inr z : A ⊕ H)) hk))
+ | _ => rfl
+ have hq' : out (host quotient) = answer := (installStacks_at host.injective work after _).trans hq
+ have hs' : out scratch = [] := (installStacks_outside work after disjoint).trans hs
+ obtain ⟨n,hn,hr⟩ := finish_bounded host scratch disjoint label current next advice out answer peak hrun.final_cap hs' hq'
+ exact ⟨_,Nat.add_le_add_left hn _,((hsetup.followedBy hrun).enlarge (Nat.le_add_right ..)).followedBy hr⟩
+
+end RankQuery.Stack.Coordinate.NativeReader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateOrdinal.lean b/lean/OAI/Computability/VPVNP/RankCoordinateOrdinal.lean
new file mode 100644
index 0000000000..9bd53c0573
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateOrdinal.lean
@@ -0,0 +1,41 @@
+import OAI.Computability.VPVNP.RankQueryGramReadSpace
+
+/-! # Calling convention for a streamed greedy index
+
+The input is a dense basis ordinal. A physical selector returns its original
+index in a fresh binary result word. Its auxiliary ports can be reused by a
+subsequent scalar query as soon as they satisfy the ready predicate again.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.OrdinalRead
+
+open RAMTape UniversalCountStack
+
+/-- An ordinal reader receives a binary input index and writes the selected original index on
+its result stack. -/
+inductive Port (K : Type) where
+ | input | result | aux (k : K)
+ deriving DecidableEq, Fintype
+
+/-- Initialize the ordinal reader with a fixed-width input index, a result stack, and its
+auxiliary stacks. -/
+def bank {K : Type} (w i : ℕ) (result : List Bool) (aux : Stacks K) : Stacks (Port K)
+ | .input => digits w i | .result => result | .aux k => aux k
+
+/-- For every valid ordinal and ready auxiliary bank, preserve the input word and return the
+selected index in a width-w word within the step and per-stack height bounds. The final
+auxiliary bank is ready for another call. -/
+def CorrectSpace {K : Type} [DecidableEq K] {r n : ℕ} (read : FiniteRoutine (Port K))
+ (g : Fin r → Fin n) (w B S : ℕ) (ready : Stacks K → Prop) : Prop :=
+ ∀ (i : Fin r) (aux : Stacks K), ready aux → ∃ t ≤ B, ∃ out, ready out ∧
+ read.BoundedRun S t (bank w i [] aux) (bank w i (digits w (g i)) out)
+
+end RankQuery.Stack.OrdinalRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateOrdinalABI.lean b/lean/OAI/Computability/VPVNP/RankCoordinateOrdinalABI.lean
new file mode 100644
index 0000000000..e287c1b93e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateOrdinalABI.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.RankCoordinateOrdinal
+import OAI.Computability.VPVNP.RankCoordinateRegisters
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-! # Returning an original greedy index as a binary word
+
+The caller supplies the dense ordinal on a dedicated port. The fixed adapter
+stages it in the five-register prefix scanner, copies out the successful cursor,
+and restores the zero-word templates in its scratch registers before returning.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.OrdinalABI
+
+open RAMTape UniversalCountStack BurstRAM Dispatch SliceArithmetic
+
+variable {K : Type} [DecidableEq K]
+
+/-- The prefix-rank registers and underlying scan workspace mounted inside the ordinal reader. -/
+abbrev Aux (K : Type) := PrefixWords.Port K
+/-- The ordinal reader's public input and output together with its private prefix-scan bank. -/
+abbrev Host (K : Type) := OrdinalRead.Port (Aux K)
+
+private def reg (i : Fin 5) : Host K := .aux (.inl (.reg i))
+private def tmp : Host K := .aux (.inl (.work 15))
+
+private def reset : RegCode 5 := .seq (.lit 0 0) (.seq (.lit 2 0) (.seq (.lit 3 0) (.lit 4 0)))
+
+private def prepare : FiniteRoutine (Host K) :=
+ (CallClear.clear (reg 2)).followedBy (SuccessorFields.prependCopy .input (reg 2) tmp)
+
+/-- Copy the requested ordinal into register two, run the supplied prefix scanner, copy its
+selected index from register zero to the result, and reset the four mutable prefix
+registers. -/
+def machine (scan : FiniteRoutine (Aux K)) : FiniteRoutine (Host K) :=
+ ((prepare.followedBy (scan.onPorts OrdinalRead.Port.aux)).followedBy
+ (SuccessorFields.prependCopy (reg 0) .result tmp)).followedBy
+ (reset.compile.onPorts (OrdinalRead.Port.aux ∘ Sum.inl))
+
+variable {w : ℕ}
+
+/-- Initial prefix-register values for an idle ordinal reader, retaining its underlying
+auxiliary stacks. -/
+def idle (side : Stacks K) := PrefixWords.bank side (PrefixWords.words (w := w) 0 0 0 0)
+
+private def framed (k : ℕ) (res : List Bool) (side : Stacks K) (rs : Regs 5 w) :=
+ OrdinalRead.bank w k res (PrefixWords.bank side rs)
+
+private theorem reg_eq (k : ℕ) (res : List Bool) (side : Stacks K) (rs : Regs 5 w) (i : Fin 5)
+ (a : Word w) : Function.update (framed k res side rs) (reg i) (wordBits a) =
+ framed k res side (Function.update rs i a) := by
+ funext z
+ cases z with
+ | input | result => rfl
+ | aux z =>
+ rcases z with z | z
+ · cases z with
+ | reg j => by_cases eq : j=i <;> simp [framed, reg, OrdinalRead.bank, PrefixWords.bank, ISA.bank, eq]
+ | _ => rfl
+ · rfl
+
+private theorem result_eq (k : ℕ) (old new : List Bool) (side : Stacks K) (rs : Regs 5 w) :
+ Function.update (framed k old side rs) .result new = framed k new side rs := by
+ funext z; cases z <;> rfl
+
+private theorem prepare_runs (k : ℕ) (side : Stacks K) : prepare.Runs ((w+1)+(5*w+2))
+ (OrdinalRead.bank w k [] (idle (w := w) side)) (framed k [] side (PrefixWords.words (w := w) 0 k 0 0)) := by
+ let s := framed k [] side (PrefixWords.words (w := w) 0 0 0 0)
+ let mid := Function.update s (reg 2) []
+ have clear := CallClear.clear_runs (reg 2) s
+ have hlen : (s (reg 2)).length = w := length_wordBits _
+ rw [hlen] at clear
+ have copy := SuccessorFields.prependCopy_runs (K := Host K) .input (reg 2) tmp
+ (by simp [reg]) (by simp [tmp]) (by simp [reg,tmp]) mid (by rfl)
+ have hi : mid .input = digits w k := rfl
+ have hd : mid (reg 2) = [] := Function.update_self ..
+ rw [hi, hd, List.append_nil, length_digits] at copy
+ have write : Function.update mid (reg 2) (digits w k) = framed k [] side (PrefixWords.words (w := w) 0 k 0 0) := by
+ dsimp only [mid]
+ rw [Function.update_idem]
+ change Function.update s (reg 2) (wordBits (Fin.ofNat (2^w) k)) = _
+ rw [show s = framed k [] side (PrefixWords.words (w := w) 0 0 0 0) from rfl, reg_eq]
+ congr 1
+ funext i; fin_cases i <;> rfl
+ rw [write] at copy
+ exact clear.followedBy copy
+
+omit [DecidableEq K] in
+private theorem framed_len {A : ℕ} (hw : w ≤ A) (k : ℕ) (result : List Bool) (hres : result.length ≤ A)
+ (side : Stacks K) (hside : ∀ j, (side j).length ≤ A) (rs : Regs 5 w) (z : Host K) :
+ ((framed k result side rs) z).length ≤ A := by
+ cases z with
+ | input => exact (length_digits ..).le.trans hw
+ | result => exact hres
+ | aux z => rcases z with z | z
+ · exact (RegisterTable.bank_length_le Fin.elim0 0 rs z).trans hw
+ · exact hside z
+
+private theorem reset_exec (cursor ordinal rank len : ℕ) :
+ reset.exec (PrefixWords.words (w := w) cursor ordinal rank len) = PrefixWords.words 0 0 0 0 := by
+ funext i; fin_cases i <;> rfl
+
+private theorem reset_runs {A : ℕ} (hw : w ≤ A) (k : ℕ) (side : Stacks K) (hs : ∀ j, (side j).length ≤ A)
+ (cursor rank len : ℕ) : ∃ t ≤ registerClock w reset,
+ (reset.compile.onPorts (OrdinalRead.Port.aux ∘ Sum.inl)).BoundedRun (A+registerClock w reset) t
+ (framed k (digits w cursor) side (PrefixWords.words (w := w) cursor k rank len))
+ (OrdinalRead.bank w k (digits w cursor) (idle (w := w) side)) := by
+ let f : ISA.Port 5 0 → Host K := OrdinalRead.Port.aux ∘ Sum.inl
+ let bank' := framed (w := w) k (digits w cursor) side
+ have regs : RegisterBank f bank' 0 := by
+ refine ⟨fun i j eq ↦ Sum.inl.inj (OrdinalRead.Port.aux.inj eq), fun _ _ ↦ rfl, ?_⟩
+ intro a b z out
+ cases z with
+ | input | result => rfl
+ | aux z => rcases z with z | z
+ · exact (out z rfl).elim
+ · rfl
+ let before := PrefixWords.words (w := w) cursor k rank len
+ obtain ⟨t, ht, run⟩ := registerCall_runs regs reset before (A+registerClock w reset) (Nat.add_le_add_right hw _)
+ (fun z _ ↦ (framed_len hw k _ ((length_digits ..).le.trans hw) side hs before z).trans (Nat.le_add_right ..))
+ change (reset.compile.onPorts f).BoundedRun _ _ _ (bank' (reset.exec before)) at run
+ rw [show reset.exec before = PrefixWords.words (w := w) 0 0 0 0 from reset_exec ..] at run
+ exact ⟨t, ht, run⟩
+
+/-- Time outside the prefix scanner, including all initialization and reclamation. -/
+def overhead (w : ℕ) := ((w+1)+(5*w+2))+(5*w+2)+registerClock w reset
+
+/-- The fixed five-register scanner supplies a true scalar-index callback,
+including its unchanged input and a reusable ready workspace. -/
+theorem correctSpace {r n w T S : ℕ} (g : Fin r → Fin n) (scan : FiniteRoutine (Aux K))
+ (side : Stacks K) (hside : ∀ j, (side j).length ≤ S) (hw : w ≤ S)
+ (scans : ∀ i : Fin r, ∃ t ≤ T, ∃ rank len : ℕ, scan.BoundedRun S t
+ (PrefixWords.bank side (PrefixWords.words (w := w) 0 i.val 0 0))
+ (PrefixWords.bank side (PrefixWords.words (w := w) (g i).val i.val rank len))) :
+ OrdinalRead.CorrectSpace (machine scan) g w (T+overhead w) (S+overhead w) (· = idle (w := w) side) := by
+ intro i s ready
+ subst s
+ let gval := (g i).val
+ obtain ⟨t, ht, rank, len, scanning⟩ := scans i
+ let pre := (w+1)+(5*w+2)
+ let copying := 5*w+2
+ let cap := S+overhead w
+ have setup := prepare_runs (w := w) i.val side
+ have smallPre : prepare.BoundedRun cap pre (OrdinalRead.bank w i.val [] (idle (w := w) side))
+ (framed i.val [] side (PrefixWords.words (w := w) 0 i.val 0 0)) := by
+ apply spaceRun_of_steps setup
+ intro z
+ have hz := framed_len hw i.val [] (Nat.zero_le _) side hside (PrefixWords.words (w := w) 0 0 0 0) z
+ exact Nat.add_le_add hz (by dsimp [pre,overhead]; omega)
+ let rs := PrefixWords.words (w := w) gval i.val rank len
+ have largeScan : (scan.onPorts OrdinalRead.Port.aux).BoundedRun cap t
+ (framed i.val [] side (PrefixWords.words (w := w) 0 i.val 0 0)) (framed i.val [] side rs) := by
+ refine FiniteRoutine.BoundedRun.framed (r := scan) (fun _ _ h ↦ OrdinalRead.Port.aux.inj h)
+ (scanning.mono_cap (show S ≤ cap from Nat.le_add_right ..))
+ smallPre.final_cap (fun _ ↦ rfl) (fun _ ↦ rfl) ?_
+ intro z outside
+ cases z <;> first | rfl | exact (outside _ rfl).elim
+ let mid := framed i.val [] side rs
+ have move := SuccessorFields.prependCopy_runs (K := Host K) (reg 0) .result tmp (by simp [reg]) (by simp [reg,tmp])
+ (by simp [tmp]) mid (by rfl)
+ have hsrc : mid (reg 0) = digits w gval := rfl
+ have hd : mid .result = [] := rfl
+ rw [hsrc, hd, List.append_nil, length_digits, result_eq] at move
+ have moved := spaceRun_of_steps (cap := cap) move fun z ↦
+ Nat.add_le_add (framed_len hw i.val [] (Nat.zero_le _) side hside rs z) (by dsimp [overhead]; omega)
+ obtain ⟨u, hu, clean⟩ := reset_runs hw i.val side hside gval rank len
+ have bigClean := clean.mono_cap (show S+registerClock w reset ≤ cap by dsimp [cap, overhead]; omega)
+ refine ⟨((pre+t)+copying)+u, ?_, idle (w := w) side, rfl,
+ ((smallPre.followedBy largeScan).followedBy moved).followedBy bigClean⟩
+ dsimp only [pre, copying, overhead]
+ omega
+
+end RankQuery.Stack.Coordinate.OrdinalABI
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinatePairReader.lean b/lean/OAI/Computability/VPVNP/RankCoordinatePairReader.lean
new file mode 100644
index 0000000000..cdc9f52395
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinatePairReader.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.RankCoordinateNativeReader
+import OAI.Computability.VPVNP.RankQueryPlainRoot
+
+/-! # Running two ordinary determinant queries inside the evaluator reader -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.NativeReader
+
+open RAMTape UniversalCountStack SliceArithmetic Dispatch
+open Cramer
+
+variable {A H K L : Type} [DecidableEq A] [DecidableEq H] [Fintype H] [DecidableEq K] [DecidableEq L]
+
+/-- Workspace of the two Schur determinant engines and their quotient routine. Each engine has
+a Gram-engine auxiliary bank and reads ordinary entries of its own square minor. -/
+abbrev PairedHost (K L : Type) := Workspace (GramEngine.Aux K) (GramEngine.Aux L)
+
+/-- Construct the coordinate callback from the two literal matrix-entry routines and a common
+preparation stage. -/
+noncomputable def pairCore (host : PairedHost K L ↪ H) (scratch : H) (prepare : FiniteRoutine (Bus A H))
+ (den : FiniteRoutine (MacaulayRead.Port K)) (num : FiniteRoutine (MacaulayRead.Port L)) :=
+ core host scratch prepare (GramEngine.actionsWith (PlainScalar.machine den)) (GramEngine.actionsWith (PlainScalar.machine num))
+
+/-- Clock allowance for preparation, both determinant queries, field division, result copying,
+and workspace reclamation. -/
+def pairTime (H : Type) [Fintype H] (setup r w v e B peak : ℕ) :=
+ setup+2*PlainEngine.queryTime r w v e B + divideClock e v + returnClock H peak
+
+variable {p e r w v d B S V s setup peak : ℕ} [Fact p.Prime] [NeZero e] {c : Vector p e}
+
+/-- With the roots staged from advice and the matrix-address parameters
+installed, the fixed reader makes the two determinant calls itself. -/
+theorem pairCore_bounded (host : PairedHost K L ↪ H) (scratch : H) (disjoint : ∀ i, host i ≠ scratch)
+ (prepare : FiniteRoutine (Bus A H)) (den : FiniteRoutine (MacaulayRead.Port K))
+ (num : FiniteRoutine (MacaulayRead.Port L)) (D N : Matrix (Fin r) (Fin r) (Scalar c))
+ {readyD : Stacks K → Prop} {readyN : Stacks L → Prop}
+ (hD : MacaulayRead.CorrectSpace den D w v B S readyD) (hN : MacaulayRead.CorrectSpace num N w v B S readyN)
+ (haD : ∀ a, readyD a → ∀ i, (a i).length ≤ V) (haN : ∀ a, readyN a → ∀ i, (a i).length ≤ V)
+ (hv : Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hw : (d+1)*widthFactor ≤ w) (hd : d ≤ w)
+ (hsize : r+r+0+r+8 < 2^d) (hn : r ≤ 2^s) (hs : 2*s+6 ≤ w) (hws : (2*s+6+1)*widthFactor ≤ w)
+ (hquery : PlainEngine.querySpace r w v e V S ≤ peak) (hroom : (e+1)*(v+1) + divideClock e v ≤ peak)
+ (label current next : List Bool) (advice : Stacks A) (work : Stacks H) (hscratch : work scratch = [])
+ (denAux : Stacks (GramEngine.Aux K)) (numAux : Stacks (GramEngine.Aux L))
+ (readyDen : GramEngine.Ready w v r r c readyD denAux) (readyNum : GramEngine.Ready w v r r c readyN numAux)
+ (hhost : ∀ i, work (host i) = SchurPair.host (SchurPair.entryBank c r w v denAux)
+ (SchurPair.entryBank c r w v numAux) (frame p e v (digits v c) [] [] []) i)
+ (hsetup : prepare.BoundedRun peak setup (state label current next [] advice (fun _ => []))
+ (state label current next [] advice work)) :
+ ∃ t ≤ pairTime H setup r w v e B peak, (pairCore host scratch prepare den num).BoundedRun
+ (peak+returnClock H peak) t (state label current next [] advice (fun _ => []))
+ (state label current next (digits v (minorQuotient c N D)) advice (fun _ => [])) := by
+ obtain ⟨td,htd,dout,_,rd⟩ := PlainEngine.top_query den D hD haD hv hw₃ hw hd hsize s hn hs hws denAux readyDen
+ obtain ⟨tn,htn,nout,_,rn⟩ := PlainEngine.top_query num N hN haN hv hw₃ hw hd hsize s hn hs hws numAux readyNum
+ let a := GramEngine.actionsWith (PlainScalar.machine den)
+ let b := GramEngine.actionsWith (PlainScalar.machine num)
+ obtain ⟨t,ht,both⟩ := SchurPair.query_runs a b c hv N D (rd.enlarge hquery) (rn.enlarge hquery) rfl rfl hroom
+ obtain ⟨u,hu,run⟩ := core_bounded host scratch disjoint prepare a b label current next advice work hscratch
+ _ _ hhost (digits v (minorQuotient c N D)) rfl hsetup both
+ exact ⟨u,by unfold pairTime; omega,run⟩
+
+end RankQuery.Stack.Coordinate.NativeReader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinatePlannedReads.lean b/lean/OAI/Computability/VPVNP/RankCoordinatePlannedReads.lean
new file mode 100644
index 0000000000..26c2727467
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinatePlannedReads.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.RankQueryReaderFits
+
+/-! # The native Cramer entries at the common reader-plan budgets
+
+A single advised width accommodates both orientations of the rectangular
+matrix, the two monomial decoders and the target shift. The polynomial
+space and logarithmic time estimates for the planned minor apply to each
+operation and both runtime basis ordinals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace RankQuery.Stack.Coordinate.SliceMinors
+
+open RAMTape BurstRAM Cursor ConcreteResources
+open SliceArithmetic FiniteSlice RadicalCertificate.MonomialIndex RadicalCertificate.MonomialIndex.QueryData
+
+variable {F : Type} [Field F] [DecidableEq F] {p e : ℕ} [Fact p.Prime] [NeZero e]
+ [Algebra (ZMod p) F] {c : Vector p e} [Fact (Irreducible (modulus c))]
+ [DecidableEq (AdjoinRoot (modulus c))] {K : Type} [Fintype K] [DecidableEq K]
+
+/-- Compare prefix-rank scan ports when mounting the planned minor readers. -/
+local instance : DecidableEq (PrefixPort K) := inferInstanceAs (DecidableEq (ScanPort (GramEngine.Aux K)))
+/-- Decide equality of workspace ports for the planned greedy row and column selections. -/
+local instance : DecidableEq (PrefixWorkspace.Aux (PrefixPort K)) := fun a b => PrefixWorkspace.instDecidableEqAux a b
+/-- Compare addresses within one pivot-selection bank using the prefix-word register layout. -/
+local instance : DecidableEq (Select.Side K) := inferInstanceAs (DecidableEq (PrefixWords.Port (PrefixWorkspace.Aux (PrefixPort K))))
+/-- Compare addresses of the two pivot banks and the scalar-reader portion of a planned minor. -/
+local instance {J : Type} [DecidableEq J] : DecidableEq (SelectedMinor.Host K J) :=
+ inferInstanceAs (DecidableEq (Select.Side K ⊕ (Select.Side K ⊕ J)))
+/-- Decide equality of the planned selected-minor workspace ports through the submatrix
+reader's representation. -/
+local instance {J : Type} [DecidableEq J] : DecidableEq (SelectedMinor.Work K J) := fun a b => Submatrix.instDecidableEqWork a b
+
+variable {t eqs d w v B A S : ℕ}
+
+/-- Passing `canonicalFits` for the reader plan supplies every shape, width
+and target bound. The two matrices use the common planned minor budget. -/
+theorem native_reads_of_plan (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F)
+ (data : QueryData t eqs F) (fit : CanonicalFits data d w v e A S B)
+ (op : Operation t) (current next : Fin data.dimension)
+ (scan : FiniteRoutine (MacaulayRead.Port K)) {ready : Stacks K → Prop}
+ (hc : MacaulayRead.CorrectSpace scan (baseMatrix φ data) w v B S ready)
+ (ha : ∀ a, ready a → ∀ k, (a k).length ≤ A)
+ (base : Stacks K) (hr : ready base) (hfield : Word.workingWidth p ≤ v) :
+ let n := height data
+ let m := width data
+ let budget := minorBudget K n m d w v e B A S B
+ let numReady := directReady c w v (targetArgs data op current) ready
+ MacaulayRead.CorrectSpace (SelectedMinor.restrictEntry scan scan) (denominator φ data) w v budget.time budget.space
+ (Submatrix.Ready (SelectedMinor.Ready w v n m c base ready)) ∧
+ MacaulayRead.CorrectSpace (SelectedMinor.numerator scan (ordinary scan) powered) (numerator φ data op current next)
+ w v budget.time budget.space (Replacement.Ready w (combinedOrdinal data.equations data.monomials next)
+ (Submatrix.Ready (SelectedMinor.Ready w v n m c base numReady))) := by
+ obtain ⟨hp,hclock,hspace⟩ := fit.target op current
+ obtain ⟨den,num⟩ := native_reads φ data op current next scan hc ha base hr fit.rowShape fit.columnShape
+ fit.gramFit hfield hp fit.wordLive fit.arityLive fit.scalarLive fit.liveSpace hspace
+ have time_bound : selectedTime K (height data) (width data) d w v e B B
+ (TargetRead.clock w A e v (targetTemplate data)) A S ≤
+ (minorBudget K (height data) (width data) d w v e B A S B).time := by
+ dsimp only [selectedTime,minorBudget]
+ apply Nat.add_le_add_left
+ apply Nat.add_le_add_right
+ apply max_le_max le_rfl
+ exact Nat.add_le_add_right (Nat.add_le_add_left hclock _) _
+ exact ⟨den.enlarge time_bound le_rfl, num.enlarge time_bound le_rfl⟩
+
+omit [NeZero e] [Algebra (ZMod p) F] [Fact (Irreducible (modulus c))] [DecidableEq (AdjoinRoot (modulus c))] in
+/-- Both auxiliary states at instruction boundaries share the planned
+height bound, including the three live target arguments. -/
+theorem planned_ready_bounds (data : QueryData t eqs F) (fit : CanonicalFits data d w v e A S B)
+ (op : Operation t) (current : Fin data.dimension)
+ {ready : Stacks K → Prop} (ha : ∀ a, ready a → ∀ k, (a k).length ≤ A)
+ (base : Stacks K) (hr : ready base) (replace : ℕ) :
+ let n := height data
+ let m := width data
+ let limit := SelectedMinor.space K d w v e A S
+ let dn := Submatrix.Ready (SelectedMinor.Ready w v n m c base ready)
+ let nu := Replacement.Ready w replace (Submatrix.Ready
+ (SelectedMinor.Ready w v n m c base (directReady c w v (targetArgs data op current) ready)))
+ (∀ bank, dn bank → ∀ k, (bank k).length ≤ limit) ∧ (∀ bank, nu bank → ∀ k, (bank k).length ≤ limit) := by
+ have hd := fun s h k => directReady_length (c := c) (ready := ready) (targetArgs data op current) ha
+ fit.wordLive fit.arityLive fit.scalarLive (s := s) h k
+ exact ⟨SelectedMinor.den_ready_length base hr ha ha fit.rowFit fit.columnFit,
+ SelectedMinor.num_ready_length base hr ha hd fit.rowFit fit.columnFit replace⟩
+
+end RankQuery.Stack.Coordinate.SliceMinors
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinatePrefix.lean b/lean/OAI/Computability/VPVNP/RankCoordinatePrefix.lean
new file mode 100644
index 0000000000..b776a36215
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinatePrefix.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.RoutineSpace
+import OAI.Computability.VPVNP.GreedySuffixIndex
+
+/-! # Physical prefix scan for the greedy row and column indices of Appendix D.2
+
+Each test queries the rank of the original matrix up to the current inclusive
+row. The same controller works on the transposed selected-row matrix for the
+column scan. Only a failed test increments the cursor. The returned cursor is
+the zero-based original index.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate
+
+open RAMTape UniversalCountStack
+
+variable {K : Type}
+
+/-- Finite controller for a rank test and a cursor increment. Both subroutine
+returns redirect directly to the caller. -/
+def greedyPrefix (flag : K) (test bump : FiniteRoutine K) : FiniteRoutine K :=
+ .ofRoutine (Q := test.State ⊕ (Unit ⊕ bump.State)) {
+ entry := .inl test.body.entry
+ code := fun
+ | .inl q => test.body.install Sum.inl (some (.inr (.inl ()))) q
+ | .inr (.inl ()) => .pop flag (fun b => if b = some false then some (.inr (.inr bump.body.entry)) else none)
+ | .inr (.inr q) => bump.body.install (Sum.inr ∘ Sum.inr) (some (.inl test.body.entry)) q }
+
+variable [DecidableEq K]
+
+/-- One iteration consumes the returned decision bit. When it is true, the
+successful candidate stays in the cursor register. -/
+private theorem testIteration {flag : K} {test bump : FiniteRoutine K} {cap n : ℕ}
+ {s out : Stacks K} {b : Bool} (hflag : out flag = [])
+ (run : test.BoundedRun cap n s (Function.update out flag [b])) :
+ let scan := greedyPrefix flag test bump
+ SpaceRun scan.body.standalone cap (n+1) (some scan.body.entry) s
+ (if b = false then some (.inr (.inr bump.body.entry)) else none) out := by
+ let scan := greedyPrefix flag test bump
+ have installed := run.linkRoutine scan.body Sum.inl (some (.inr (.inl ()))) (fun _ ↦ rfl)
+ have small (k : K) : (out k).length ≤ cap := by
+ by_cases e : k = flag
+ · simp [e, hflag]
+ · simpa only [Function.update_of_ne e] using run.final_cap k
+ have step := StackStep.pop (s := Function.update out flag [b])
+ (show scan.body.standalone (some (.inr (.inl ()))) = .pop flag
+ (fun bit => if bit = some false then some (.inr (.inr bump.body.entry)) else none) from rfl)
+ have hup : Function.update out flag [] = out := by rw [← hflag, Function.update_eq_self]
+ simp only [Function.update_self, List.head?_cons, List.tail_cons, Option.some.injEq,
+ Function.update_idem, hup] at step
+ exact installed.trans (.cons run.final_cap step (.nil _ _ small))
+
+/-- With a first successful index `last`, bounded subcalls give a bounded
+physical scan. The cap is independent of the number of preceding failed tests. -/
+theorem first_test_runs {flag : K} (test bump : FiniteRoutine K) {cap T B last : ℕ}
+ (input checked : ℕ → Stacks K) (hflag : ∀ j ≤ last, checked j flag = [])
+ (htest : ∀ j ≤ last, ∃ t ≤ T, test.BoundedRun cap t (input j)
+ (Function.update (checked j) flag [decide (j = last)]))
+ (hbump : ∀ j < last, ∃ t ≤ B, bump.BoundedRun cap t (checked j) (input (j+1))) :
+ ∃ t ≤ (last+1)*(T+1+B), (greedyPrefix flag test bump).BoundedRun cap t (input 0) (checked last) := by
+ let scan := greedyPrefix flag test bump
+ have loop (remaining j : ℕ) (hj : j+remaining=last) :
+ ∃ t ≤ (remaining+1)*(T+1+B), scan.BoundedRun cap t (input j) (checked last) := by
+ induction remaining generalizing j with
+ | zero =>
+ obtain ⟨a, ha, checkedRun⟩ := htest j (by omega)
+ have run := testIteration (bump := bump) (hflag j (by omega)) checkedRun
+ simp only [Nat.add_zero] at hj
+ subst j
+ refine ⟨a+1, by omega, ?_⟩
+ simpa only [decide_true, Bool.true_eq_false, ite_false, scan] using run
+ | succ r ih =>
+ obtain ⟨a, ha, checkedRun⟩ := htest j (by omega)
+ have run := testIteration (bump := bump) (hflag j (by omega)) checkedRun
+ have hlt : j < last := by omega
+ obtain ⟨b, hb, bumped⟩ := hbump j hlt
+ have one : SpaceRun scan.body.standalone cap (a+1) (some scan.body.entry) (input j)
+ (some (.inr (.inr bump.body.entry))) (checked j) := by
+ simpa only [decide_eq_false hlt.ne, ite_true, scan] using run
+ have next := bumped.linkRoutine scan.body (Sum.inr ∘ Sum.inr) (some scan.body.entry) (fun _ ↦ rfl)
+ obtain ⟨c, hc, tail⟩ := ih (j+1) (by omega)
+ refine ⟨_, ?_, (one.trans next).trans tail⟩
+ rw [Nat.succ_mul]
+ omega
+ exact loop last 0 (Nat.zero_add _)
+
+/-- The test contract refers to prefix ranks of the supplied matrix, not a basis
+computed recursively. It also applies verbatim to column selection on a transpose. -/
+theorem greedyPrefix_runs {F : Type*} [Field F] [DecidableEq F] {n m : ℕ}
+ (A : Matrix (Fin n) (Fin m) F) (k : Fin (rankQuery A)) (flag : K) (test bump : FiniteRoutine K)
+ {cap T B : ℕ} (input checked : ℕ → Stacks K) (hflag : ∀ j < n, checked j flag = [])
+ (htest : ∀ j (hj : j < n), ∃ t ≤ T, test.BoundedRun cap t (input j)
+ (Function.update (checked j) flag [decide (k.val < rankQuery (prefixRows A (j+1) hj))]))
+ (hbump : ∀ j, j+1 < n → ∃ t ≤ B, bump.BoundedRun cap t (checked j) (input (j+1))) :
+ ∃ t ≤ n*(T+1+B), (greedyPrefix flag test bump).BoundedRun cap t (input 0)
+ (checked (greedyRowIndex A k).val) := by
+ let last := (greedyRowIndex A k).val
+ have fits : last < n := (greedyRowIndex A k).isLt
+ have same (j : ℕ) (h : j ≤ last) (hj : j < n) : (k.val < rankQuery (prefixRows A (j+1) hj)) ↔ j = last := by
+ rw [← greedyRowIndex_lt_iff]
+ change last < j+1 ↔ j = last
+ omega
+ obtain ⟨t, ht, run⟩ := first_test_runs (last := last) (T := T) (B := B) test bump input checked
+ (fun j hj ↦ hflag j (hj.trans_lt fits))
+ (fun j hj ↦ by simpa only [same j hj (hj.trans_lt fits)] using htest j (hj.trans_lt fits))
+ (fun j hj ↦ hbump j (by omega))
+ exact ⟨t, ht.trans (Nat.mul_le_mul_right _ fits), run⟩
+
+end RankQuery.Stack.Coordinate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinatePrepare.lean b/lean/OAI/Computability/VPVNP/RankCoordinatePrepare.lean
new file mode 100644
index 0000000000..9e9fcd8ec7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinatePrepare.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.RankCoordinatePrepareCost
+
+/-! # Preparing the actual two Cramer roots from live evaluator inputs
+
+A fixed table clones the shared templates, computes the current original row
+and replacement ordinal, converts the label when required, and writes the
+four varying words to the numerator. The operation mode is fixed in control.
+Both modes can start from the same advised stacks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.Prepare
+
+open RAMTape UniversalCountStack BurstRAM NativeReader SliceArithmetic
+open RadicalCertificate.MonomialIndex
+
+variable {D K T : Type} [DecidableEq D] [DecidableEq K] [DecidableEq T]
+
+/-- Source ports for the numerator’s replacement-row ordinal and three target inputs. Dynamic
+registers five and seven supply the ordinal and monomial. The other ports supply the label
+mark and operation-specific scale. -/
+def sources (b : Bool) := ArgumentStage.sources (dyn (D := D) (K := K) (T := T))
+ (workPort (unary .number)) (scale b)
+
+private def isRoot : Ports D K T → Bool
+ | .aux (.inr (.inl (.inl _))) => true
+ | _ => false
+
+private def isScratch : Ports D K T → Bool
+ | .aux (.inr (.inr _)) => true
+ | _ => false
+
+omit [DecidableEq D] [DecidableEq K] [DecidableEq T] in
+private theorem source_flags (b : Bool) (f : ArgumentStage.Field) :
+ isRoot (sources (D := D) (K := K) (T := T) b f) = false ∧ isScratch (sources b f : Ports D K T) = false := by
+ rcases f with ⟨⟩|i
+ · exact ⟨rfl,rfl⟩
+ · fin_cases i <;> exact ⟨rfl,rfl⟩
+
+omit [DecidableEq D] [DecidableEq K] [DecidableEq T] in
+private theorem apart (target : Fin 3 ↪ K) (b : Bool) (f g : ArgumentStage.Field) :
+ sources (D := D) (K := K) (T := T) b f ≠ ArgumentStage.workPort (ArgumentStage.destination root target g) := by
+ intro eq
+ have h := congrArg isRoot eq
+ rw [(source_flags b f).1] at h
+ exact Bool.noConfusion (show false = true from h)
+
+omit [DecidableEq D] [DecidableEq K] [DecidableEq T] in
+private theorem separate (b : Bool) (f : ArgumentStage.Field) :
+ sources (D := D) (K := K) (T := T) b f ≠ ArgumentStage.workPort scratch := by
+ intro eq
+ have h := congrArg isScratch eq
+ rw [(source_flags b f).2] at h
+ exact Bool.noConfusion (show false = true from h)
+
+omit [DecidableEq D] [DecidableEq K] [DecidableEq T] in
+private theorem unused (target : Fin 3 ↪ K) (f : ArgumentStage.Field) :
+ ArgumentStage.destination (root (D := D) (T := T)) target f ≠ scratch := Sum.inl_ne_inr
+
+/-- Load the root templates, compute the replacement row from the next basis ordinal and the
+target monomial from the current one, and install those words with the operation’s label
+mark and scale. -/
+noncomputable def machine [Fintype (Parts D K T)] (selector : FiniteRoutine (OrdinalRead.Port T))
+ (target : Fin 3 ↪ K) (b : Bool) : FiniteRoutine (Ports D K T) :=
+ (((load.followedBy ((Dynamic.machine selector).onPorts dynPort)).followedBy (labelCall b))).followedBy
+ (ArgumentStage.machine root target (sources b) scratch)
+
+omit [DecidableEq D] [DecidableEq K] [DecidableEq T] in
+private theorem dormant_regs (w a b c d e f g h : ℕ) :
+ dormant (Dynamic.regs (w := w) a b c d e f g h) = Dynamic.regs 0 0 c d e f g h := by
+ funext i; fin_cases i <;> rfl
+
+variable [Fintype (Parts D K T)] {F : Type} [Field F] [DecidableEq F] {p e x y z w v M A S B : ℕ}
+
+set_option maxHeartbeats 1500000 in
+/-- Complete dynamic preparation. The live ordinal words and unary label are
+the only request-dependent input. The prepared roots contain the selected
+replacement row and the original powered-target monomial. -/
+theorem machine_bounded (W : Matrix (Fin x) (Fin z) F) (Y : Matrix (Fin y) (Fin z) F)
+ (cur next : Fin (suffixDimension W Y)) (label : ℕ) (b : Bool) (scaleValue : Bool → ℕ)
+ (c : Vector p e) (r : ℕ) (den : Stacks D) (raw : Stacks K) (target : Fin 3 ↪ K)
+ (selector : FiniteRoutine (OrdinalRead.Port T)) {ready : Stacks T → Prop}
+ (hsel : OrdinalRead.CorrectSpace selector (greedyRowIndex (appendRows W Y)) w B S ready)
+ (hw : w ≤ S) (fits : x+y < 2^w) (hready : ∀ s, ready s → ∀ k, (s k).length ≤ S)
+ (side : Stacks T) (hs : ready side) (labelFit : label+1 < 2^w)
+ (old : List Bool) (oldSize : old.length ≤ w) (rawSize : ∀ i, (raw (target i)).length ≤ w) :
+ let rootData := RootInit.template c r w v den (Replacement.workBank w old (Submatrix.workBank [] [] raw))
+ let dynamicData := Dynamic.bank side (Dynamic.regs (w := w) 0 0 (rankQuery W) x 0 0 0 0)
+ let unaryData := UnaryWord.store [] [] (digits w 0) [] []
+ let advised := advice rootData dynamicData unaryData (fun mode => digits w (scaleValue mode))
+ (∀ i, (rootData i).length ≤ M) → (∀ i, (dynamicData i).length ≤ M) → (∀ i, (unaryData i).length ≤ M) →
+ (∀ k, (state (List.replicate label true) (digits w cur) (digits w next) [] advised (fun _ : Work D K T => []) k).length ≤ A) →
+ ∃ t ≤ time (Parts D K T) b M B label w, ∃ out : Stacks (Work D K T), out scratch = [] ∧
+ (∀ i, out (root i) = RootInit.template c r w v den (Replacement.workBank w (digits w (combinedOrdinal W Y next))
+ (Submatrix.workBank [] [] (installStacks target raw (TargetRead.words w (suffixBasisIndex W Y cur)
+ (scaleValue b) (if b then 0 else label+1))))) i) ∧
+ (machine selector target b).BoundedRun (peak (Parts D K T) M A S label w) t
+ (state (List.replicate label true) (digits w cur) (digits w next) [] advised (fun _ : Work D K T => []))
+ (state (List.replicate label true) (digits w cur) (digits w next) [] advised out) := by
+ intro roots dynamicData unaryData adv rootFit dynFit unFit start
+ let labelBits := List.replicate label true
+ let cap := baseCap (Parts D K T) M A S label w
+ let full := peak (Parts D K T) M A S label w
+ have loadRoom : A+RootInit.loadClock (Parts D K T) M ≤ cap := le_max_left ..
+ have dynRoom : S+Dynamic.overhead w ≤ cap := (le_max_left ..).trans (le_max_right ..)
+ have labelRoom : max label w+LabelWord.clock label w ≤ cap := (le_max_right ..).trans (le_max_right ..)
+ have finishRoom : cap ≤ full := Nat.le_add_right ..
+ obtain ⟨u,hu,loaded⟩ := load_bounded labelBits (digits w cur) (digits w next) roots dynamicData unaryData
+ (fun mode => digits w (scaleValue mode)) A M rootFit dynFit unFit start
+ let ri := combinedOrdinal W Y cur
+ let rj := combinedOrdinal W Y next
+ let row := greedyRowIndex (appendRows W Y) ri
+ let mono := suffixBasisIndex W Y cur
+ let before := Dynamic.regs (w := w) cur next (rankQuery W) x 0 0 0 0
+ let after := Dynamic.regs (w := w) cur next (rankQuery W) x ri rj row mono
+ obtain ⟨u₁,hu₁,side',_,rawRun⟩ := Dynamic.machine_bounded W Y cur next selector hsel hw fits hready side hs
+ have stage₀ := loaded.enlarge loadRoom
+ have dh : dormant before = Dynamic.regs (w := w) 0 0 (rankQuery W) x 0 0 0 0 := dormant_regs ..
+ have dh' : dormant after = Dynamic.regs (w := w) 0 0 (rankQuery W) x ri rj row mono := dormant_regs ..
+ have stage₁ := dynamic_bounded selector side side' before after rfl rfl roots unaryData labelBits adv
+ (rawRun.enlarge dynRoom) (by rw [dh]; exact stage₀.final_cap)
+ rw [dh,dh'] at stage₁
+ let computed := Dynamic.bank side' (Dynamic.regs (w := w) 0 0 (rankQuery W) x ri rj row mono)
+ let mark := if b then 0 else label+1
+ let unaryOut := UnaryWord.store [] [] (digits w mark) [] []
+ have stage₂ := label_bounded b labelFit roots computed (digits w cur) (digits w next) adv stage₁.final_cap labelRoom
+ let installed := work roots computed unaryOut
+ let result := TargetRead.words w mono (scaleValue b) mark
+ let values := Sum.elim (fun _ : Unit => digits w rj) result
+ have hvalues : ∀ f, state labelBits (digits w cur) (digits w next) [] adv installed (sources b f) = values f := by
+ apply ArgumentStage.source_words dyn (workPort (unary .number)) (scale b) labelBits _ _ [] adv installed side'
+ 0 0 (rankQuery W) x ri rj row mono mark (scaleValue b) (fun _ => rfl) rfl rfl
+ have tiny (f : ArgumentStage.Field) : (values f).length ≤ w := by
+ rcases f with ⟨⟩|i
+ · simp [values]
+ · fin_cases i <;> simp [values,result,TargetRead.words]
+ have oldBound (f : ArgumentStage.Field) : (installed (ArgumentStage.destination root target f)).length ≤ w := by
+ rcases f with ⟨⟩|i
+ · exact oldSize
+ · exact rawSize i
+ obtain ⟨u₃,hu₃,st⟩ := ArgumentStage.machine_bounded root target (sources b) scratch w cap labelBits (digits w cur)
+ (digits w next) [] adv installed values (apart target b) (separate b) (unused target) rfl hvalues tiny oldBound stage₂.final_cap
+ let out := installStacks (ArgumentStage.destination root target) installed values
+ have hs' : out scratch = [] := installStacks_outside installed values (unused target)
+ have hhost (i : Root D K) := ArgumentStage.host_after c r w v root target den raw old (digits w rj) result installed
+ (fun _ => rfl) i
+ have first := ((stage₀.followedBy stage₁).followedBy stage₂).enlarge finishRoom
+ exact ⟨u+u₁+labelTime b label w+u₃,Nat.add_le_add (Nat.add_le_add_right (Nat.add_le_add hu hu₁) _) hu₃,out,hs',hhost,first.followedBy st⟩
+
+end RankQuery.Stack.Coordinate.Prepare
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinatePrepareCost.lean b/lean/OAI/Computability/VPVNP/RankCoordinatePrepareCost.lean
new file mode 100644
index 0000000000..4778671a89
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinatePrepareCost.lean
@@ -0,0 +1,28 @@
+import OAI.Computability.VPVNP.RankCoordinatePreparePorts
+
+/-! # Clock and peak height of the live two-root preparation -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.Prepare
+
+/-- Total instruction allowance for root loading, dynamic index selection, label preparation,
+and argument installation. -/
+def time (P : Type) [Fintype P] (b : Bool) (M B label w : ℕ) := RootInit.loadClock P M + (B+Dynamic.overhead w) +
+ labelTime b label w + ArgumentStage.clock w
+
+/-- Peak stack-height allowance through root loading, index selection, and unary label
+conversion. -/
+def baseCap (P : Type) [Fintype P] (M A S label w : ℕ) := max (A+RootInit.loadClock P M)
+ (max (S+Dynamic.overhead w) (max label w + LabelWord.clock label w))
+
+/-- Peak allowance for the complete preparation, including the final argument-copy phase. -/
+def peak (P : Type) [Fintype P] (M A S label w : ℕ) := baseCap P M A S label w + ArgumentStage.clock w
+
+end RankQuery.Stack.Coordinate.Prepare
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinatePreparePorts.lean b/lean/OAI/Computability/VPVNP/RankCoordinatePreparePorts.lean
new file mode 100644
index 0000000000..96d8a03176
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinatePreparePorts.lean
@@ -0,0 +1,197 @@
+import OAI.Computability.VPVNP.RankCoordinateArgumentStage
+import OAI.Computability.VPVNP.RankCoordinateLabelWord
+
+/-! # Shared advice and live ports of the two slice readers
+
+The two machines read the same root templates, selector bank, and zero label
+register. One advised scale is reserved for each operation. Dynamic register
+zero and register one directly read the evaluator's two basis indices, and
+the label converter directly reads its unary label. All three return intact.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.Prepare
+
+open RAMTape UniversalCountStack BurstRAM NativeReader
+
+/-- Paired-root workspace for the denominator and numerator determinant queries and their
+finite-field quotient. The numerator’s entry workspace also carries the replacement-row and
+target arguments. -/
+abbrev Root (D K : Type) := RootInit.RootHost D (ArgumentStage.Num K)
+/-- The combined root banks, dynamic ordinal registers, and unary-label workspace needed for
+preparation. -/
+abbrev Parts (D K T : Type) := Root D K ⊕ (Dynamic.Host T ⊕ UnaryWord.Port)
+/-- Immutable preparation advice, including the root images and the operation-dependent scale
+words. -/
+abbrev Advice (D K T : Type) := Parts D K T ⊕ Bool
+/-- Writable preparation stacks, with an additional temporary port for copying. -/
+abbrev Work (D K T : Type) := Parts D K T ⊕ Unit
+/-- The reader bus carrying the immutable advice and the writable preparation banks separately. -/
+abbrev Ports (D K T : Type) := Bus (Advice D K T) (Work D K T)
+
+variable {D K T : Type}
+
+/-- Assemble the saved determinant roots, dynamic-register image, unary-label image, and the
+two scale words as advice. -/
+def advice (root : Stacks (Root D K)) (dyn : Stacks (Dynamic.Host T)) (label : Stacks UnaryWord.Port)
+ (scale : Bool → List Bool) : Stacks (Advice D K T) := Sum.elim (Sum.elim root (Sum.elim dyn label)) scale
+
+/-- Assemble the live preparation workspace with an initially empty copying stack. -/
+def work (root : Stacks (Root D K)) (dyn : Stacks (Dynamic.Host T)) (label : Stacks UnaryWord.Port) : Stacks (Work D K T) :=
+ Sum.elim (Sum.elim root (Sum.elim dyn label)) (fun _ => [])
+
+/-- Embed the collection of prepared stacks into the writable bank. -/
+def parts : Parts D K T ↪ Work D K T := ⟨Sum.inl,Sum.inl_injective⟩
+/-- Embed both determinant-root banks into the preparation workspace. -/
+def root : Root D K ↪ Work D K T := ⟨Sum.inl ∘ Sum.inl,Sum.inl_injective.comp Sum.inl_injective⟩
+/-- Place the dynamic coordinate registers and ordinal-reader stacks in the preparation
+workspace. -/
+def dyn : Dynamic.Host T ↪ Work D K T := ⟨Sum.inl ∘ Sum.inr ∘ Sum.inl,Sum.inl_injective.comp (Sum.inr_injective.comp Sum.inl_injective)⟩
+/-- Place the unary-to-binary label converter in the preparation workspace. -/
+def unary : UnaryWord.Port ↪ Work D K T := ⟨Sum.inl ∘ Sum.inr ∘ Sum.inr,Sum.inl_injective.comp (Sum.inr_injective.comp Sum.inr_injective)⟩
+/-- The temporary stack used when copying static roots and arguments. -/
+def scratch : Work D K T := .inr ()
+/-- Access one writable preparation stack through the scalar reader's auxiliary port. -/
+def workPort (a : Work D K T) : Ports D K T := .aux (.inr a)
+/-- Read the operation-dependent scale word from the immutable advice bank. -/
+def scale (b : Bool) : Ports D K T := .aux (.inl (.inr b))
+
+/-- Copy the saved preparation data from advice into its writable counterpart using the
+temporary stack. -/
+noncomputable def load [Fintype (Parts D K T)] : FiniteRoutine (Ports D K T) :=
+ RootInit.load Sum.inl parts scratch
+
+variable [DecidableEq D] [DecidableEq K] [DecidableEq T]
+
+instance partsDecidable : DecidableEq (Parts D K T) := by
+ letI : DecidableEq (Submatrix.Work K) := fun a b => Submatrix.instDecidableEqWork a b
+ letI : DecidableEq (ArgumentStage.Num K) := inferInstanceAs (DecidableEq (ISA.Port 2 0 ⊕ Submatrix.Work K))
+ letI : DecidableEq (GramEngine.Aux D) := inferInstance
+ letI : DecidableEq (GramEngine.Aux (ArgumentStage.Num K)) := inferInstance
+ letI : DecidableEq (Root D K) := Cramer.SchurPair.instDecidableEqHost
+ letI : DecidableEq (Dynamic.Host T) := inferInstance
+ exact inferInstanceAs (DecidableEq (Root D K ⊕ (Dynamic.Host T ⊕ UnaryWord.Port)))
+
+theorem load_bounded [Fintype (Parts D K T)] (label current next : List Bool) (r : Stacks (Root D K))
+ (d : Stacks (Dynamic.Host T)) (u : Stacks UnaryWord.Port) (scales : Bool → List Bool)
+ (A M : ℕ) (rfit : ∀ i, (r i).length ≤ M) (dfit : ∀ i, (d i).length ≤ M) (ufit : ∀ i, (u i).length ≤ M)
+ (start : ∀ i, (state label current next [] (advice r d u scales) (fun _ : Work D K T => []) i).length ≤ A) :
+ ∃ t ≤ RootInit.loadClock (Parts D K T) M, load.BoundedRun (A+RootInit.loadClock (Parts D K T) M) t
+ (state label current next [] (advice r d u scales) (fun _ : Work D K T => []))
+ (state label current next [] (advice r d u scales) (work r d u)) := by
+ let tpl := Sum.elim r (Sum.elim d u)
+ have fit (i : Parts D K T) : (tpl i).length ≤ M := by
+ rcases i with i|i|i <;> first | exact rfit i | exact dfit i | exact ufit i
+ obtain ⟨t,ht,run⟩ := RootInit.load_runs Sum.inl parts scratch (fun _ h => by contradiction)
+ label current next [] (advice r d u scales) (fun _ : Work D K T => []) tpl (fun _ => rfl)
+ (fun _ => rfl) rfl M A fit start
+ have eq : installStacks parts (fun _ : Work D K T => []) tpl = work r d u := by
+ funext i; rcases i with i | i
+ · exact installStacks_at parts.injective _ _ i
+ · exact installStacks_outside _ _ (fun _ h => by contradiction)
+ rw [eq] at run
+ exact ⟨t,ht,run⟩
+
+/-- Wire the dynamic selector's current and next registers to the reader's live ordinals and
+mount its other ports in workspace. -/
+def dynPort (z : Dynamic.Host T) : Ports D K T :=
+ if z = .inl (.reg 0) then .current else if z = .inl (.reg 1) then .next else workPort (dyn z)
+
+omit [DecidableEq D] [DecidableEq K] in
+theorem dynPort_injective : Function.Injective (dynPort (D := D) (K := K) (T := T)) := by
+ intro a b eq; unfold dynPort at eq
+ split_ifs at eq <;> simp_all [workPort,dyn]
+
+/-- Wire the unary converter's source to the public label and its other ports to private
+preparation stacks. -/
+def unaryPort : UnaryWord.Port → Ports D K T
+ | .src => .label
+ | z => workPort (unary z)
+
+omit [DecidableEq D] [DecidableEq K] [DecidableEq T] in
+theorem unaryPort_injective : Function.Injective (unaryPort (D := D) (K := K) (T := T)) := by
+ intro a b eq; cases a <;> cases b <;> simp_all [unaryPort,workPort,unary]
+
+/-- Clear the current and next ordinal registers in the saved register image before they are
+supplied by the caller. -/
+def dormant {w : ℕ} (rs : Dispatch.Regs 8 w) : Dispatch.Regs 8 w :=
+ Function.update (Function.update rs 0 0) 1 0
+
+/-- Mount a selector run while leaving the two dormant template registers at
+zero. The two active indices are the evaluator's persistent input words. -/
+theorem dynamic_bounded {w B u : ℕ} (selector : FiniteRoutine (OrdinalRead.Port T))
+ (before after : Stacks T) (rs rs' : Dispatch.Regs 8 w) (h₀ : rs' 0 = rs 0) (h₁ : rs' 1 = rs 1)
+ (r : Stacks (Root D K)) (l : Stacks UnaryWord.Port) (label : List Bool) (a : Stacks (Advice D K T))
+ (run : (Dynamic.machine selector).BoundedRun B u (Dynamic.bank before rs) (Dynamic.bank after rs'))
+ (room : ∀ i, (state label (wordBits (rs 0)) (wordBits (rs 1)) [] a
+ (work r (Dynamic.bank before (dormant rs)) l) i).length ≤ B) :
+ ((Dynamic.machine selector).onPorts (dynPort (D := D) (K := K))).BoundedRun B u
+ (state label (wordBits (rs 0)) (wordBits (rs 1)) [] a (work r (Dynamic.bank before (dormant rs)) l))
+ (state label (wordBits (rs 0)) (wordBits (rs 1)) [] a (work r (Dynamic.bank after (dormant rs')) l)) := by
+ apply FiniteRoutine.BoundedRun.framed dynPort_injective run room
+ · rintro (i|i)
+ · cases i with
+ | reg j => by_cases j₀ : j = 0 <;> by_cases j₁ : j = 1 <;>
+ simp_all [dynPort,workPort,work,dyn,state,Reader.bank,Dynamic.bank,ISA.bank,dormant]
+ | _ => rfl
+ · rfl
+ · rintro (i|i)
+ · cases i with
+ | reg j => by_cases j₀ : j = 0 <;> by_cases j₁ : j = 1 <;>
+ simp_all [dynPort,workPort,work,dyn,state,Reader.bank,Dynamic.bank,ISA.bank,dormant]
+ | _ => rfl
+ · rfl
+ · intro k hk; cases k with
+ | aux k =>
+ rcases k with k | (k | (k|k)) | k
+ · rfl
+ · rfl
+ · by_cases h₀ : k = .inl (.reg 0)
+ · subst k; simp [state,Reader.bank,work,Dynamic.bank,ISA.bank,dormant]
+ · by_cases h₁ : k = .inl (.reg 1)
+ · subst k; simp [state,Reader.bank,work,Dynamic.bank,ISA.bank,dormant]
+ · exact (hk k (by simp [dynPort,h₀,h₁,workPort,dyn])).elim
+ · rfl
+ · rfl
+ | _ => rfl
+
+/-- Frob keeps the zero mark. Label calls convert the live unary label to
+its one-based binary mark and return the same label on its public port. -/
+def labelCall (frobenius : Bool) : FiniteRoutine (Ports D K T) :=
+ if frobenius then .ret else LabelWord.machine.onPorts unaryPort
+
+/-- One step for the immediate return in Frobenius mode, or the unary-to-word conversion clock
+for the one-based mark of a label operation. -/
+def labelTime (frobenius : Bool) (n w : ℕ) := if frobenius then 1 else LabelWord.clock n w
+
+theorem label_bounded {B n w : ℕ} (b : Bool) (hn : n+1 < 2^w) (r : Stacks (Root D K))
+ (d : Stacks (Dynamic.Host T)) (current next : List Bool) (a : Stacks (Advice D K T))
+ (room : ∀ k, (state (List.replicate n true) current next [] a
+ (work r d (UnaryWord.store [] [] (digits w 0) [] [])) k).length ≤ B)
+ (hb : max n w+LabelWord.clock n w ≤ B) :
+ (labelCall b).BoundedRun B (labelTime b n w)
+ (state (List.replicate n true) current next [] a (work r d (UnaryWord.store [] [] (digits w 0) [] [])))
+ (state (List.replicate n true) current next [] a (work r d (UnaryWord.store [] [] (digits w (if b then 0 else n+1)) [] []))) := by
+ cases b with
+ | true => exact .cons room (.goto rfl) (.nil _ _ room)
+ | false =>
+ apply FiniteRoutine.BoundedRun.framed unaryPort_injective ((LabelWord.machine_bounded n w hn).enlarge hb) room
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> rfl
+ · intro k hk; cases k with
+ | aux k => rcases k with k|(k|(k|k))|k
+ · rfl
+ · rfl
+ · rfl
+ · cases k <;> first | rfl | exact (hk UnaryWord.Port.number rfl).elim
+ · rfl
+ | _ => rfl
+
+end RankQuery.Stack.Coordinate.Prepare
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateReader.lean b/lean/OAI/Computability/VPVNP/RankCoordinateReader.lean
new file mode 100644
index 0000000000..8455b844ed
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateReader.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.EvaluatorReadInterface
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-! # Installing a scalar coordinate query in the weighted evaluator
+
+The reader uses the live little-endian basis ordinals and the unary label without
+copying. Its returned scalar is already on the next field multiplier's operand
+port. The caller's product, field coefficients and remaining index registers are
+outside the installed bank and survive every step of the query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.Reader
+
+open RAMTape UniversalCountStack Evaluator Evaluator.MatrixCallbacks SliceArithmetic
+
+/-- Public input and scalar output ports of the coordinate reader together with its auxiliary
+stack labels. -/
+inductive Port (P : Type) where
+ | label | current | next | result | aux (k : P)
+ deriving DecidableEq, Fintype
+
+variable {P : Type}
+
+/-- Wire the coordinate callback into the weighted evaluator's label, ordinal,
+arithmetic-result, and auxiliary ports. -/
+def mount : Port P → ReadPort P
+ | .label => .inl ()
+ | .current => .inr (.indices .current)
+ | .next => .inr (.indices .next)
+ | .result => .inr (.arithmetic (.inr .query))
+ | .aux k => .inr (.aux k)
+
+theorem mount_injective : Function.Injective (mount (P := P)) := by
+ intro x y eq
+ cases x <;> cases y <;> simp_all [mount]
+
+/-- Assemble the label, current and next basis indices, result bits, and auxiliary stacks as a
+reader configuration. -/
+def bank (label current next result : List Bool) (extra : Stacks P) : Stacks (Port P)
+ | .label => label | .current => current | .next => next | .result => result | .aux k => extra k
+
+/-- Install the coordinate reader on the weighted evaluator's physical ports. -/
+def install (core : FiniteRoutine (Port P)) : FiniteRoutine (ReadPort P) := core.onPorts mount
+
+variable [DecidableEq P] {p e w v : ℕ} [Fact p.Prime]
+ {F : Type} [Field F] [Algebra (ZMod p) F] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (dim : BurstRAM.Word v) (extra : Stacks P)
+
+/-- Encode the zero-based basis index, without changing its value, as a
+least-significant-bit-first word of the evaluator’s index width. -/
+abbrev ordinal (j : Fin dim.val) := BurstRAM.wordBits (Fin.castLE dim.isLt.le j : BurstRAM.Word v)
+
+/-- A returning native scalar query suffices for the evaluator's exact reader
+contract. Current and next are in transition order, so a column-vector matrix is
+queried at the transpose position. -/
+theorem readsEntry (core : FiniteRoutine (Port P)) (matrix : Matrix (Fin dim.val) (Fin dim.val) F)
+ (label time : ℕ) (query : ∀ i j : Fin dim.val, ∃ d ≤ time, core.Runs d
+ (bank (List.replicate label true) (ordinal dim i) (ordinal dim j) [] extra)
+ (bank (List.replicate label true) (ordinal dim i) (ordinal dim j) (WeightedStep.bits φ w (matrix i j)) extra)) :
+ ReadsEntry φ dim extra (install core) w label time matrix := by
+ intro s j
+ obtain ⟨d, hd, run⟩ := query s.1 j
+ refine ⟨d, hd, FiniteRoutine.runs_onPorts_framed core mount_injective run ?_ ?_ ?_⟩
+ · intro a; cases a <;> rfl
+ · intro a; cases a <;> rfl
+ · intro a outside
+ cases a with
+ | inl => rfl
+ | inr a =>
+ cases a with
+ | indices | width | aux => rfl
+ | arithmetic a =>
+ cases a with
+ | inl => rfl
+ | inr a =>
+ cases a with
+ | query => exact (outside .result rfl).elim
+ | prime | zeroWord | degree | coeff | acc => rfl
+
+/-- The physical core may leave its finite scratch bank occupied. A fixed
+cleanup pass discharges those ports while retaining advice and output. -/
+noncomputable def reclaim {A H : Type} [Fintype H] : FiniteRoutine (Port (A ⊕ H)) :=
+ CallClear.cleanup (Finset.univ.toList.map (fun h : H ↦ Port.aux (Sum.inr h)))
+
+theorem reclaim_runs {A H : Type} [Fintype H] [DecidableEq A] [DecidableEq H]
+ (label current next result : List Bool) (advice : Stacks A) (work : Stacks H) (cap : ℕ)
+ (fits : ∀ h, (work h).length ≤ cap) :
+ ∃ t ≤ Fintype.card H * (cap+1)+1, reclaim.Runs t
+ (bank label current next result (Sum.elim advice work))
+ (bank label current next result (Sum.elim advice (fun _ : H ↦ []))) := by
+ let ks := Finset.univ.toList.map (fun h : H ↦ Port.aux (Sum.inr h : A ⊕ H))
+ let s := bank label current next result (Sum.elim advice work)
+ have hlen : ks.length = Fintype.card H := by simp [ks]
+ obtain ⟨t, ht, h⟩ := CallClear.cleanup_runs ks s cap (fun k hk ↦ by
+ obtain ⟨h, _, rfl⟩ := List.mem_map.mp hk
+ exact fits h)
+ have endBank : CallClear.erased ks s = bank label current next result (Sum.elim advice (fun _ : H ↦ [])) := by
+ funext k
+ cases k with
+ | label | current | next | result => simp [CallClear.erased, ks, s, bank]
+ | aux a => cases a <;> simp [CallClear.erased, ks, s, bank]
+ exact ⟨t, hlen ▸ ht, endBank ▸ h⟩
+
+end RankQuery.Stack.Coordinate.Reader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateReaderSpace.lean b/lean/OAI/Computability/VPVNP/RankCoordinateReaderSpace.lean
new file mode 100644
index 0000000000..b8cc9a11be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateReaderSpace.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.RankCoordinateEvaluator
+import OAI.Computability.VPVNP.EvaluatorCallbackSafety
+
+/-! # Preserving the space bound of the evaluator's scalar reader
+
+The native coordinate routine owns the live label, current and next ordinal,
+result and private advice ports. Every other evaluator stack is unchanged and
+has length bounded by the index word width, scalar degree or scalar word length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.Reader
+
+open RAMTape SliceArithmetic Evaluator Evaluator.MatrixCallbacks UniversalCountStack
+
+variable {P : Type} [DecidableEq P] {p e w v : ℕ} [Fact p.Prime]
+ {F : Type} [Field F] [Algebra (ZMod p) F] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (dim : BurstRAM.Word v) (extra : Stacks P)
+
+/-- Maximum height among the caller's stacks outside the installed routine. -/
+def callerPeak (v e w : ℕ) := max v (max w (max e (e*w)))
+
+omit [DecidableEq P] in
+private theorem outsideBound (label : ℕ) (i j : Fin dim.val) (acc : F) (q : ReadPort P)
+ (outside : ∀ k, mount k ≠ q) :
+ ((queryBank (List.replicate label true) (WeightedStep.bank φ w dim i (ordinal dim j) [] acc extra)) q).length
+ ≤ callerPeak v e w := by
+ rcases q with ⟨⟩ | q
+ · exact (outside .label rfl).elim
+ · cases q with
+ | aux k => exact (outside (.aux k) rfl).elim
+ | width => simp [queryBank, WeightedStep.bank, callerPeak]
+ | indices k =>
+ cases k <;> simp [queryBank, WeightedStep.bank, IndexRegisters.bank, ordinal, callerPeak]
+ | arithmetic k =>
+ rcases k with k | k
+ · simp [queryBank, WeightedStep.bank, MultiplyCall.clean]
+ · cases k <;> simp [queryBank, WeightedStep.bank, MultiplyCall.clean, MultiplyCall.external,
+ WeightedStep.bits, callerPeak]
+
+/-- The native core's cap and the caller's untouched stacks determine the
+physical peak, independently of the time spent computing the coordinate. -/
+theorem readsEntryWithin (core : FiniteRoutine (Port P)) (matrix : Matrix (Fin dim.val) (Fin dim.val) F)
+ (label time peak : ℕ) (query : ∀ i j : Fin dim.val, ∃ d ≤ time, core.BoundedRun peak d
+ (bank (List.replicate label true) (ordinal dim i) (ordinal dim j) [] extra)
+ (bank (List.replicate label true) (ordinal dim i) (ordinal dim j) (WeightedStep.bits φ w (matrix i j)) extra)) :
+ ReadsEntryWithin φ dim extra (install core) w label time (max peak (callerPeak v e w)) matrix := by
+ intro s j
+ obtain ⟨d, hd, run⟩ := query s.1 j
+ let raw q := queryBank (List.replicate label true) (WeightedStep.bank φ w dim s.1 (ordinal dim j) q s.2 extra)
+ let localBank q := bank (List.replicate label true) (ordinal dim s.1) (ordinal dim j) q extra
+ have installed (q : List Bool) : installStacks mount (raw []) (localBank q) = raw q := by
+ apply installStacks_frame (ports := mount) (base := raw []) (small := localBank q) (target := raw q) mount_injective
+ · intro k; cases k <;> rfl
+ · intro k outside
+ rcases k with ⟨⟩ | k
+ · rfl
+ · cases k with
+ | indices | width | aux => rfl
+ | arithmetic k =>
+ rcases k with k | k
+ · rfl
+ · cases k <;> first | rfl | exact (outside .result rfl).elim
+ have big : core.BoundedRun (max peak (callerPeak v e w)) d (localBank [])
+ (localBank (WeightedStep.bits φ w (matrix s.1 j))) := run.mono_cap (le_max_left ..)
+ have mounted := FiniteRoutine.BoundedRun.onPorts (a := core) mount_injective (raw []) big
+ (fun k outside ↦ (outsideBound φ dim extra label s.1 j s.2 k outside).trans (le_max_right ..))
+ rw [installed, installed] at mounted
+ exact ⟨d, hd, mounted⟩
+
+open FiniteSlice RadicalCertificate.MonomialIndex RadicalCertificate.MonomialIndex.QueryData
+
+variable [Fintype F] [DecidableEq F] {E : Type*} [Field E] [Algebra F E] [IsAlgClosed E] {t eqs : ℕ}
+
+/-- Packed Cramer execution supplies the full time-and-space matrix callback
+on the concrete basis of the reduced algebra. -/
+theorem readsEntryWithin_of_suffix (S : QueryData t eqs F) (sys : Fin eqs → MvPolynomial (Fin t) F)
+ (h : S.Presents sys) (hd : dim.val = S.dimension)
+ (b : Module.Basis (Fin dim.val) F (CoordinateAlgebra F (points sys E)))
+ (hb : ∀ i, b i = S.listing sys E (S.basisIndex (Fin.cast hd i)))
+ (op : Operation t) (label time peak : ℕ) (core : FiniteRoutine (Port P))
+ (query : ∀ current next : Fin dim.val, ∃ d ≤ time, ∃ a : Vector p e,
+ φ (value (modulus c) a) = S.stepCoordinate op (Fin.cast hd current) (Fin.cast hd next) ∧
+ core.BoundedRun peak d (bank (List.replicate label true) (ordinal dim current) (ordinal dim next) [] extra)
+ (bank (List.replicate label true) (ordinal dim current) (ordinal dim next)
+ (SliceArithmeticRound.packed w (List.ofFn a)) extra)) :
+ ReadsEntryWithin φ dim extra (install core) w label time (max peak (callerPeak v e w))
+ ((LinearMap.toMatrixAlgEquiv b) (op.linearAction (coordinateLabel (points sys E)))).transpose := by
+ apply readsEntryWithin
+ intro current next
+ obtain ⟨d, ht, a, hv, run⟩ := query current next
+ let M := ((LinearMap.toMatrixAlgEquiv b) (op.linearAction (coordinateLabel (points sys E)))).transpose
+ have he : a = scalarEncoding φ (M current next) := (valueEquiv c).injective (φ.injective
+ ((hv.trans (S.stepCoordinate_eq_transition sys hd h b hb op current next)).trans (map_scalarEncoding φ _).symm))
+ refine ⟨d, ht, ?_⟩
+ change core.BoundedRun peak d _ (bank _ _ _ (SliceArithmeticRound.packed w (List.ofFn (scalarEncoding φ (M current next)))) extra)
+ rwa [← he]
+
+end RankQuery.Stack.Coordinate.Reader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateRegisters.lean b/lean/OAI/Computability/VPVNP/RankCoordinateRegisters.lean
new file mode 100644
index 0000000000..51fe7f9b9e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateRegisters.lean
@@ -0,0 +1,166 @@
+import OAI.Computability.VPVNP.RankCoordinateDimension
+import OAI.Computability.VPVNP.RankQueryStackRegister
+import OAI.Computability.VPVNP.RegisterTable
+
+/-! # Register arithmetic for a physical prefix-rank query
+
+The control holds the cursor, one, target ordinal, returned rank and inclusive
+prefix length in five binary words. It forms the inclusive length before every
+rank call and compares the returned word with the ordinal. Other ports remain
+available to the matrix and rank subroutines.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.PrefixWords
+
+open RAMTape UniversalCountStack BurstRAM Dispatch TapeWord
+
+variable {L : Type}
+
+/-- The five prefix-rank registers alongside the scalar reader's auxiliary bank. -/
+abbrev Port (L : Type) := ISA.Port 5 0 ⊕ L
+
+/-- Initialize the cursor, constant one, requested ordinal, returned rank, and inclusive prefix
+length. -/
+def words {w : ℕ} (cursor ordinal rank length : ℕ) : Regs 5 w :=
+ ![Fin.ofNat _ cursor, 1, Fin.ofNat _ ordinal, Fin.ofNat _ rank, Fin.ofNat _ length]
+
+/-- Mount the five binary words and the prefix reader's auxiliary state in their disjoint
+banks. -/
+def bank {w : ℕ} (s : Stacks L) (rs : Regs 5 w) : Stacks (Port L) :=
+ Sum.elim (ISA.bank Fin.elim0 0 rs []) s
+
+private def addCursor (dst : Fin 5) : RegCode 5 := .op dst .add 0 1
+
+/-- The prefix-length input is register four, and the rank output is register three.
+Only this subcall depends on the matrix representation. -/
+def rankTest (rank : FiniteRoutine (Port L)) : FiniteRoutine (Port L) :=
+ (((addCursor 4).compile.onPorts Sum.inl).followedBy rank).followedBy
+ ((ISA.compareRegs .lt (2 : Fin 5) 3).onPorts (Sum.inl : ISA.Port 5 0 → Port L))
+
+/-- Starting at cursor zero, ask for the rank through the current row and advance until that
+rank exceeds the requested zero-based ordinal. The cursor then identifies the corresponding
+greedy pivot row. -/
+def machine (rank : FiniteRoutine (Port L)) : FiniteRoutine (Port L) :=
+ greedyPrefix (.inl (.work 0)) (rankTest rank) ((addCursor 0).compile.onPorts Sum.inl)
+
+/-- Step allowance for one register addition, used both to form the inclusive prefix length and
+to advance the cursor. Each use contributes separately to the prefix-scan bound. -/
+def arithmeticBound (w : ℕ) := arithmeticClock w
+
+private theorem installed {w : ℕ} (s : Stacks L) (rs : Regs 5 w) :
+ installStacks Sum.inl (bank s rs) (ISA.bank Fin.elim0 0 rs []) = bank s rs :=
+ installStacks_eq Sum.inl_injective _ _ fun _ ↦ rfl
+
+private theorem outside_le {cap w : ℕ} {s : Stacks L} (hs : ∀ l, (s l).length ≤ cap) (rs : Regs 5 w)
+ (l : Port L) (outside : ∀ k, Sum.inl k ≠ l) : ((bank s rs) l).length ≤ cap := by
+ cases l with
+ | inl i => exact (outside i rfl).elim
+ | inr i => exact hs i
+
+
+private theorem registerBank {w : ℕ} (s : Stacks L) : RegisterBank Sum.inl (bank (w := w) s) 0 := by
+ refine ⟨Sum.inl_injective, fun _ _ ↦ rfl, ?_⟩
+ intro a b j outside
+ cases j with
+ | inl i => exact (outside i rfl).elim
+ | inr i => rfl
+
+variable [DecidableEq L]
+
+private theorem addCursor_runs {cap w : ℕ} {s : Stacks L} (hs : ∀ l, (s l).length ≤ cap)
+ (hc : w+arithmeticBound w ≤ cap) (rs : Regs 5 w) (dst : Fin 5) :
+ ∃ t ≤ arithmeticBound w, ((addCursor dst).compile.onPorts Sum.inl).BoundedRun cap t
+ (bank s rs) (bank s ((addCursor dst).exec rs)) :=
+ registerCall_runs (registerBank s) (addCursor dst) rs cap hc (outside_le hs rs)
+
+private theorem comparison_runs {cap w : ℕ} {s : Stacks L} (hs : ∀ l, (s l).length ≤ cap)
+ (hc : w+arithmeticBound w ≤ cap) (rs : Regs 5 w) :
+ ((ISA.compareRegs .lt (2 : Fin 5) 3).onPorts Sum.inl).BoundedRun cap (20*w+10) (bank s rs)
+ (Function.update (bank s rs) (.inl (.work 0)) [decide (rs 2 < rs 3)]) := by
+ have run := ISA.compareRegs_run .lt (2 : Fin 5) 3 Fin.elim0 (0 : Word w) rs []
+ have bound : 20*w+10 ≤ arithmeticBound w := by unfold arithmeticBound arithmeticClock; nlinarith [Nat.zero_le (w^2)]
+ have small := spaceRun_of_steps (cap := cap) run (fun k ↦
+ (Nat.add_le_add (RegisterTable.bank_length_le Fin.elim0 0 rs k) bound).trans hc)
+ have large := FiniteRoutine.BoundedRun.onPorts (a := ISA.compareRegs .lt (2 : Fin 5) 3) Sum.inl_injective
+ (bank s rs) small (outside_le hs rs)
+ rw [installed, ← installStacks_update Sum.inl_injective, installed] at large
+ exact large
+
+private theorem addCursor_length {w : ℕ} (j k a b : ℕ) :
+ (addCursor 4).exec (words (w := w) j k a b) = words j k a (j+1) := by
+ funext i
+ fin_cases i <;> simp [addCursor, RegCode.exec, Arith.word, Arith.opcode, PrivateRAM.BinaryOp.eval, words]
+ apply Fin.ext
+ simp [Fin.val_add, Nat.add_mod]
+
+private theorem addCursor_index {w : ℕ} (j k a b : ℕ) :
+ (addCursor 0).exec (words (w := w) j k a b) = words (j+1) k a b := by
+ funext i
+ fin_cases i <;> simp [addCursor, RegCode.exec, Arith.word, Arith.opcode, PrivateRAM.BinaryOp.eval, words]
+ apply Fin.ext
+ simp [Fin.val_add, Nat.add_mod]
+
+variable {F : Type*} [Field F] [DecidableEq F] {n m w cap T : ℕ}
+
+/-- Numeric rank of a prefix, with saturation only for out-of-range indices,
+which the machine never reaches. -/
+def rankAt (A : Matrix (Fin n) (Fin m) F) (j : ℕ) :=
+ if h : j ≤ n then rankQuery (prefixRows A j h) else rankQuery A
+
+theorem rankAt_eq (A : Matrix (Fin n) (Fin m) F) {j : ℕ} (hj : j ≤ n) :
+ rankAt A j = rankQuery (prefixRows A j hj) := by simp [rankAt, hj]
+
+private theorem rankAt_le (A : Matrix (Fin n) (Fin m) F) (j : ℕ) : rankAt A j ≤ n := by
+ unfold rankAt
+ split_ifs with hj
+ · rw [rankQuery_eq]
+ exact (by simpa only [Fintype.card_fin] using (prefixRows A j hj).rank_le_card_height : _ ≤ j).trans hj
+ · rw [rankQuery_eq]
+ simpa only [Fintype.card_fin] using A.rank_le_card_height
+
+/-- The only remaining call contract is the rank of a supplied prefix. All index
+arithmetic and comparisons are physical routines, independent of the matrix shape. -/
+theorem machine_runs (A : Matrix (Fin n) (Fin m) F) (k : Fin (rankQuery A)) (s : Stacks L)
+ (rank : FiniteRoutine (Port L)) (fits : n < 2^w) (hs : ∀ l, (s l).length ≤ cap)
+ (hc : w+arithmeticBound w ≤ cap)
+ (call : ∀ j < n, ∃ t ≤ T, rank.BoundedRun cap t
+ (bank s (words (w := w) j k.val (rankAt A j) (j+1)))
+ (bank s (words (w := w) j k.val (rankAt A (j+1)) (j+1)))) :
+ let out := (greedyRowIndex A k).val
+ ∃ t ≤ n*((arithmeticBound w+T+(20*w+10))+1+arithmeticBound w), (machine rank).BoundedRun cap t
+ (bank s (words (w := w) 0 k.val (rankAt A 0) 0))
+ (bank s (words (w := w) out k.val (rankAt A (out+1)) (out+1))) := by
+ let input j := bank s (words (w := w) j k.val (rankAt A j) j)
+ let checked j := bank s (words (w := w) j k.val (rankAt A (j+1)) (j+1))
+ apply greedyPrefix_runs A k _ _ _ input checked (fun _ _ ↦ rfl)
+ · intro j hj
+ obtain ⟨a, ha, add⟩ := addCursor_runs hs hc (words (w := w) j k.val (rankAt A j) j) 4
+ rw [addCursor_length] at add
+ obtain ⟨b, hb, result⟩ := call j hj
+ have comp := comparison_runs hs hc (words (w := w) j k.val (rankAt A (j+1)) (j+1))
+ have fitK : k.val < 2^w := by
+ have h := A.rank_le_card_height
+ rw [Fintype.card_fin] at h
+ exact (k.isLt.trans_le ((rankQuery_eq A).le.trans h)).trans fits
+ have fitR := (rankAt_le A (j+1)).trans_lt fits
+ rw [rankAt_eq A hj] at fitR
+ have cmp : decide ((words (w := w) j k.val (rankAt A (j+1)) (j+1)) 2 <
+ (words (w := w) j k.val (rankAt A (j+1)) (j+1)) 3) =
+ decide (k.val < rankQuery (prefixRows A (j+1) hj)) := by
+ simp [words, Fin.lt_def, Nat.mod_eq_of_lt fitK, Nat.mod_eq_of_lt fitR, rankAt_eq A hj]
+ rw [cmp] at comp
+ exact ⟨_, by omega, (add.followedBy result).followedBy comp⟩
+ · intro j _
+ obtain ⟨t, ht, add⟩ := addCursor_runs hs hc (words (w := w) j k.val (rankAt A (j+1)) (j+1)) 0
+ rw [addCursor_index] at add
+ exact ⟨t, ht, add⟩
+
+end RankQuery.Stack.Coordinate.PrefixWords
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateReplacement.lean b/lean/OAI/Computability/VPVNP/RankCoordinateReplacement.lean
new file mode 100644
index 0000000000..00acdcf4bb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateReplacement.lean
@@ -0,0 +1,189 @@
+import OAI.Computability.VPVNP.RankCoordinateMinor
+import OAI.Computability.VPVNP.RankCoordinateSubmatrix
+
+/-!
+# The numerator reader for a Cramer minor
+
+The comparison aliases the caller's dense row address and reads the
+replacement ordinal from a separate register. The selected scalar reader
+therefore receives the usual two addresses. Its result is the target scalar
+precisely on the replaced row. The ordinal and comparison workspace are
+ready again at every return.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.Replacement
+
+open RAMTape BurstRAM UniversalCountStack Dispatch
+
+/-- Two comparison registers and the scalar-reader workspace used to recognize the replaced
+row. -/
+abbrev Work (K : Type) := ISA.Port 2 0 ⊕ K
+/-- The public matrix-entry reader ports together with the row-replacement workspace. -/
+abbrev Port (K : Type) := MacaulayRead.Port (Work K)
+
+variable {K : Type}
+
+/-- At entry, the row supplied by the caller is register zero. The second
+comparison register holds the ordinal computed by the enclosing query. -/
+def workBank (w : ℕ) (replacement : List Bool) (s : Stacks K) : Stacks (Work K) :=
+ Sum.elim (fun a => match a with
+ | .reg j => if j = 1 then replacement else []
+ | z => ISA.bank Fin.elim0 (0 : Word w) (fun _ => 0) [] z) s
+
+/-- Installing a new ordinal into its designated stack preserves all other
+workspace and advice. -/
+theorem set_replacement [DecidableEq K] (w : ℕ) (old new : List Bool) (s : Stacks K) :
+ Function.update (workBank w old s) (.inl (.reg 1)) new = workBank w new s := by
+ funext k
+ rcases k with k | k
+ · cases k with
+ | reg i => fin_cases i <;> rfl
+ | _ => rfl
+ · rfl
+
+/-- The scalar reader’s auxiliary bank is ready, register one holds the width-w replacement-row
+ordinal, and the local register-zero stack is empty because comparison reads the caller’s
+row port. -/
+def Ready (w k : ℕ) (ready : Stacks K → Prop) (a : Stacks (Work K)) : Prop :=
+ ∃ s, ready s ∧ a = workBank w (digits w k) s
+
+private def comparePorts : ISA.Port 2 0 → Port K
+ | .reg i => if i = 0 then .row else .aux (.inl (.reg i))
+ | z => .aux (.inl z)
+
+private def entryPorts : MacaulayRead.Port K → Port K
+ | .row => .row | .col => .col | .result => .result | .aux k => .aux (.inr k)
+
+private theorem entryInj : Function.Injective (entryPorts (K := K)) := by
+ intro a b h; cases a <;> cases b <;> simp_all [entryPorts]
+
+/-- The replacement ordinal is a runtime input to this fixed routine. -/
+def numerator (ordinary target : FiniteRoutine (MacaulayRead.Port K)) : FiniteRoutine (Port K) :=
+ Minor.equalBranch comparePorts 0 1 (ordinary.onPorts entryPorts) (target.onPorts entryPorts)
+
+private def regBank {w : ℕ} (col result : List Bool) (s : Stacks K) (rs : Regs 2 w) : Stacks (Port K)
+ | .row => wordBits (rs 0)
+ | .col => col
+ | .result => result
+ | .aux p => workBank w (wordBits (rs 1)) s p
+
+private theorem comparisonBank {w : ℕ} (col result : List Bool) (s : Stacks K) :
+ RegisterBank comparePorts (regBank (w := w) col result s) 0 := by
+ constructor
+ · intro a b h
+ cases a <;> cases b <;> simp only [comparePorts] at h ⊢ <;> (try split_ifs at h) <;> simp_all
+ · intro rs a
+ cases a with
+ | reg i => fin_cases i <;> rfl
+ | _ => rfl
+ · intro a b p hp
+ cases p with
+ | row => exact (hp (.reg 0) rfl).elim
+ | col | result => rfl
+ | aux p =>
+ rcases p with p | p
+ · cases p with
+ | reg i => fin_cases i <;> first | rfl | exact (hp (.reg 1) rfl).elim
+ | _ => rfl
+ · rfl
+
+variable [DecidableEq K] {p e r s w v Bo Bt S : ℕ} {c : SliceArithmetic.Vector p e}
+ {ready : Stacks K → Prop} {ordinary target : FiniteRoutine (MacaulayRead.Port K)}
+ {D : Matrix (Fin r) (Fin s) (Scalar c)} {T : Fin s → Scalar c}
+
+private theorem liftEntry {i : Fin r} {j : Fin s} {k : Fin r} {run : FiniteRoutine (MacaulayRead.Port K)}
+ {z : List Bool} {a b : Stacks K} {t : ℕ}
+ (h : run.BoundedRun S t (MacaulayRead.bank w i j [] a) (MacaulayRead.bank w i j z b)) :
+ (run.onPorts entryPorts).BoundedRun (max S (w+(20*w+10))) t
+ (MacaulayRead.bank w i j [] (workBank w (digits w k) a))
+ (MacaulayRead.bank w i j z (workBank w (digits w k) b)) := by
+ refine FiniteRoutine.BoundedRun.framed entryInj (h.enlarge (le_max_left ..)) ?_
+ (fun x => by cases x <;> rfl) (fun x => by cases x <;> rfl) ?_
+ · intro x
+ cases x with
+ | row => exact (h.initial_cap .row).trans (le_max_left ..)
+ | col => exact (h.initial_cap .col).trans (le_max_left ..)
+ | result => exact Nat.zero_le _
+ | aux x =>
+ rcases x with x | x
+ · have hle : w ≤ max S (w+(20*w+10)) := (Nat.le_add_right ..).trans (le_max_right ..)
+ cases x with
+ | reg i => fin_cases i <;> simp [MacaulayRead.bank, workBank, hle]
+ | pub i => exact i.elim0
+ | persistent => simp [MacaulayRead.bank, workBank, ISA.bank]
+ | work _ => exact Nat.zero_le _
+ | logPort a => cases a <;> exact Nat.zero_le _
+ · exact (h.initial_cap (.aux x)).trans (le_max_left ..)
+ · intro x hx
+ cases x with
+ | row | col => rfl
+ | result => exact (hx .result rfl).elim
+ | aux x =>
+ rcases x with x | x
+ · rfl
+ · exact (hx (.aux x) rfl).elim
+
+/-- Supply the target row as a scalar reader of the constant-row matrix.
+Both arms may update the auxiliary state on return. Every address comparison
+and each selected arm respect the stated cap, independent of their running time. -/
+theorem correctSpace (ho : MacaulayRead.CorrectSpace ordinary D w v Bo S ready)
+ (ht : MacaulayRead.CorrectSpace target (fun _ j => T j : Matrix (Fin r) (Fin s) _) w v Bt S ready)
+ (k : Fin r) (hfit : r ≤ 2^w) :
+ MacaulayRead.CorrectSpace (numerator ordinary target) (D.updateRow k T) w v
+ (20*w+10+(max Bo Bt+1)) (max S (w+(20*w+10))) (Ready w k ready) := by
+ rintro i j _ ⟨a, ha, rfl⟩
+ let rs : Regs 2 w := ![Fin.ofNat _ i.val, Fin.ofNat _ k.val]
+ have heq : rs 0 = rs 1 ↔ i = k := by
+ simp only [rs, Matrix.cons_val_zero, Matrix.cons_val_one, Fin.ext_iff, Fin.val_ofNat,
+ Nat.mod_eq_of_lt (i.isLt.trans_le hfit), Nat.mod_eq_of_lt (k.isLt.trans_le hfit)]
+ let hb := comparisonBank (w := w) (digits w j) [] a
+ have aligned : regBank (digits w j) [] a rs = MacaulayRead.bank w i j [] (workBank w (digits w k) a) := by
+ funext p; cases p <;> rfl
+ by_cases hi : i = k
+ · obtain ⟨d, hd, b, hready, run⟩ := ht i j a ha
+ have branch := liftEntry (k := k) run
+ have test := Minor.equalBranch_runs hb rs 0 1 (ordinary.onPorts entryPorts) (target.onPorts entryPorts)
+ (t := d) (out := MacaulayRead.bank w i j (Engine.scalar v (T j)) (workBank w (digits w k) b))
+ (le_max_right S _) (by rw [ite_eq_left (heq.mpr hi), aligned]; exact branch)
+ rw [aligned] at test
+ refine ⟨20*w+10+(d+1), by have := le_max_right Bo Bt; omega, workBank w (digits w k) b, ⟨b, hready, rfl⟩, ?_⟩
+ simpa only [numerator, hi, Matrix.updateRow_self] using test
+ · obtain ⟨d, hd, b, hready, run⟩ := ho i j a ha
+ have branch := liftEntry (k := k) run
+ have test := Minor.equalBranch_runs hb rs 0 1 (ordinary.onPorts entryPorts) (target.onPorts entryPorts)
+ (t := d) (out := MacaulayRead.bank w i j (Engine.scalar v (D i j)) (workBank w (digits w k) b))
+ (le_max_right S _) (by rw [ite_eq_right (heq.not.mpr hi), aligned]; exact branch)
+ rw [aligned] at test
+ refine ⟨20*w+10+(d+1), by have := le_max_left Bo Bt; omega, workBank w (digits w k) b, ⟨b, hready, rfl⟩, ?_⟩
+ simpa only [numerator, Matrix.updateRow_ne hi] using test
+
+/-- Assemble the Cramer numerator from the ordinal selectors and two raw
+scalar reads. The target reader receives the selected original column on its
+column port. Its row input is immaterial for the constant-row target matrix. -/
+theorem submatrix_correctSpace {n m Br Bc : ℕ} {A : Matrix (Fin n) (Fin m) (Scalar c)}
+ {f : Fin r → Fin n} {g : Fin s → Fin m} {rawTarget : Fin m → Scalar c}
+ {rows cols : FiniteRoutine (OrdinalRead.Port K)}
+ (row : OrdinalRead.CorrectSpace rows f w Br S ready)
+ (col : OrdinalRead.CorrectSpace cols g w Bc S ready)
+ (entry : MacaulayRead.CorrectSpace ordinary A w v Bo S ready)
+ (targetEntry : MacaulayRead.CorrectSpace target (fun _ j => rawTarget j : Matrix (Fin n) (Fin m) _)
+ w v Bt S ready)
+ (k : Fin r) (hfit : r ≤ 2^w) :
+ MacaulayRead.CorrectSpace (numerator (Submatrix.minorRead rows cols ordinary)
+ (Submatrix.minorRead rows cols target)) ((A.submatrix f g).updateRow k (rawTarget ∘ g)) w v
+ (20*w+10+(max (Br+Bc+Bo+2*(w+1)) (Br+Bc+Bt+2*(w+1))+1)) (max S (w+(20*w+10)))
+ (Ready w k (Submatrix.Ready ready)) :=
+ correctSpace (D := A.submatrix f g) (T := rawTarget ∘ g)
+ (ordinary := Submatrix.minorRead rows cols ordinary) (target := Submatrix.minorRead rows cols target)
+ (Submatrix.correctSpace (M := A) (f := f) (g := g) row col entry)
+ (Submatrix.correctSpace (M := fun _ j => rawTarget j) (f := f) (g := g) row col targetEntry) k hfit
+
+end RankQuery.Stack.Coordinate.Replacement
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateRootInit.lean b/lean/OAI/Computability/VPVNP/RankCoordinateRootInit.lean
new file mode 100644
index 0000000000..00135a9189
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateRootInit.lean
@@ -0,0 +1,256 @@
+import OAI.Computability.VPVNP.RankCoordinateCramer
+import OAI.Computability.VPVNP.RankCoordinateReader
+import OAI.Computability.VPVNP.RankQueryPlainRoot
+import OAI.Computability.VPVNP.RankQueryStackGramInitialization
+import OAI.Computability.VPVNP.SliceArithmeticCallCopies
+
+/-! # Loading the two determinant roots from reusable advice
+
+The static root registers and field parameters can be stored once in advice.
+A fixed scan copies these stacks into fresh work ports before a pair of Schur
+queries. The private matrix-reader ports are the only parts of the root banks
+which depend on the live entry query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.RootInit
+
+open RAMTape UniversalCountStack SliceArithmetic
+
+variable {T A H : Type} [Fintype T]
+
+private def src (source : T → A) (i : T) : Reader.Port (A ⊕ H) := .aux (.inl (source i))
+private def dst (destination : T ↪ H) (i : T) : Reader.Port (A ⊕ H) := .aux (.inr (destination i))
+
+private noncomputable def plan (source : T → A) (destination : T ↪ H) :
+ List (Reader.Port (A ⊕ H) × Reader.Port (A ⊕ H)) :=
+ Finset.univ.toList.map (fun i => (src source i, dst destination i))
+
+/-- Copy each advised template stack to its corresponding root port. -/
+noncomputable def load (source : T → A) (destination : T ↪ H) (tmp : H) :=
+ CallCopies.copyPlan (.aux (.inr tmp)) (plan source destination)
+
+private theorem plan_valid (source : T → A) (destination : T ↪ H) (tmp : H)
+ (fresh : ∀ i, destination i ≠ tmp) :
+ CallCopies.Valid (.aux (.inr tmp)) (plan source destination) := by
+ simp only [CallCopies.Valid, plan, List.map_map, Function.comp_def]
+ refine ⟨(Finset.nodup_toList _).map (fun i j eq => destination.injective (Sum.inr.inj (Reader.Port.aux.inj eq))),
+ ?_, ?_, ?_⟩
+ · intro k hk hl
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp hk
+ obtain ⟨j, _, h⟩ := List.mem_map.mp hl
+ cases h
+ · intro hk
+ obtain ⟨i, _, h⟩ := List.mem_map.mp hk
+ cases h
+ · intro hk
+ obtain ⟨i, _, h⟩ := List.mem_map.mp hk
+ exact fresh i (Sum.inr.inj (Reader.Port.aux.inj h))
+
+/-- Bound the finite scan that copies all root stacks from advice, using the number of ports
+and maximum saved stack height. -/
+def loadClock (T : Type) [Fintype T] (M : ℕ) := Fintype.card T * (5*M+2)+1
+
+/-- Runtime copying retains both the reusable sources and every stack outside
+the chosen destinations. The space cap uses the initial height of all ports. -/
+theorem load_runs [DecidableEq A] [DecidableEq H]
+ (source : T → A) (destination : T ↪ H) (tmp : H) (fresh : ∀ i, destination i ≠ tmp)
+ (label current next result : List Bool) (advice : Stacks A) (work : Stacks H) (template : Stacks T)
+ (hsource : ∀ i, advice (source i) = template i) (blank : ∀ i, work (destination i) = [])
+ (scratch : work tmp = []) (M ambient : ℕ) (fits : ∀ i, (template i).length ≤ M)
+ (bankFits : ∀ i, ((Reader.bank label current next result (Sum.elim advice work)) i).length ≤ ambient) :
+ ∃ t ≤ loadClock T M, (load source destination tmp).BoundedRun (ambient + loadClock T M) t
+ (Reader.bank label current next result (Sum.elim advice work))
+ (Reader.bank label current next result (Sum.elim advice (installStacks destination work template))) := by
+ let before := Reader.bank label current next result (Sum.elim advice work)
+ let after := Reader.bank label current next result (Sum.elim advice (installStacks destination work template))
+ let pairs := plan source destination
+ have valid := plan_valid source destination tmp fresh
+ obtain ⟨t, ht, run⟩ := CallCopies.copyPlan_runs (Reader.Port.aux (Sum.inr tmp : A ⊕ H)) pairs before M valid scratch (by
+ intro p hp
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp hp
+ exact blank i) (by
+ intro p hp
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp hp
+ change (advice (source i)).length ≤ M
+ simpa only [hsource] using fits i)
+ have bound : t ≤ loadClock T M := by simpa only [pairs, plan, List.length_map,
+ Finset.length_toList, Finset.card_univ, loadClock] using ht
+ have out : CallCopies.copied pairs before = after := by
+ funext k
+ by_cases hk : ∃ i : T, dst destination i = k
+ · obtain ⟨i, rfl⟩ := hk
+ have mem : (src source i, dst destination i) ∈ pairs := List.mem_map.mpr ⟨i, by simp, rfl⟩
+ rw [CallCopies.copied_at _ _ valid.1 mem]
+ change advice (source i) = installStacks destination work template (destination i)
+ rw [hsource, installStacks_at destination.injective]
+ · have absent : k ∉ pairs.map Prod.snd := by
+ simp only [pairs, plan, List.map_map, Function.comp_def, List.mem_map]
+ rintro ⟨i, _, hi⟩
+ exact hk ⟨i, hi⟩
+ rw [CallCopies.copied_outside _ _ _ absent]
+ cases k with
+ | label | current | next | result => rfl
+ | aux a =>
+ rcases a with a | j
+ · rfl
+ · change work j = installStacks destination work template j
+ apply (installStacks_outside work template _).symm
+ intro i he
+ exact hk ⟨i, congrArg (fun k : H => (Reader.Port.aux (.inr k) : Reader.Port (A ⊕ H))) he⟩
+ rw [out] at run
+ exact ⟨t, bound, spaceRun_of_steps run (fun k => Nat.add_le_add (bankFits k) bound)⟩
+
+/-- Full work-port type of the two streamed determinants, with the matrix reader's
+private ports parameterized independently for numerator and denominator. -/
+abbrev RootHost (K L : Type) := Cramer.SchurPair.Host (GramEngine.Aux K) (GramEngine.Aux L)
+
+variable {K L : Type} {p e : ℕ}
+
+/-- Both engines start at the top coefficient of the degree-`r` pencil. Their
+continuation stacks and result ports are empty. -/
+def template (c : Vector p e) (r addr width : ℕ) (denReader : Stacks K) (numReader : Stacks L) :
+ Stacks (RootHost K L) :=
+ Cramer.SchurPair.host
+ (Cramer.SchurPair.entryBank c r addr width (GramEngine.initial addr width r r c denReader))
+ (Cramer.SchurPair.entryBank c r addr width (GramEngine.initial addr width r r c numReader))
+ (Cramer.frame p e width (Cramer.digits width c) [] [] [])
+
+/-- The two root auxiliary banks meet the concrete determinant readers' readiness
+conditions, including the binary matrix dimensions and packed field advice. -/
+theorem template_ready (c : Vector p e) (r addr width : ℕ) (hr : r < 2^addr)
+ (denReader : Stacks K) (numReader : Stacks L) {denReady : Stacks K → Prop} {numReady : Stacks L → Prop}
+ (hd : denReady denReader) (hn : numReady numReader) :
+ GramEngine.Ready addr width r r c denReady (GramEngine.initial addr width r r c denReader) ∧
+ GramEngine.Ready addr width r r c numReady (GramEngine.initial addr width r r c numReader) :=
+ ⟨GramEngine.initial_ready denReader hd hr hr, GramEngine.initial_ready numReader hn hr hr⟩
+
+/-- Location of a dynamic scalar-reader input within the paired root banks. -/
+def readerPort : K ⊕ L → RootHost K L
+ | .inl k => .inl (.aux (.inl (.inr (.aux k))))
+ | .inr l => .inr (.inl (.aux (.inl (.inr (.aux l)))))
+
+theorem readerPort_injective : Function.Injective (readerPort (K := K) (L := L)) := by
+ rintro (k|k) (l|l) h <;> simp_all [readerPort]
+
+/-- Filling the private reader inputs after loading the constant advice has
+exactly the same effect as placing those inputs in the corresponding root banks. -/
+theorem setReaders (c : Vector p e) (r addr width : ℕ) (oldD newD : Stacks K) (oldN newN : Stacks L) :
+ installStacks readerPort (template c r addr width oldD oldN) (Sum.elim newD newN) =
+ template c r addr width newD newN := by
+ apply installStacks_frame readerPort_injective
+ · rintro (i|i) <;> rfl
+ · rintro (i | i | i) outside
+ · cases i with
+ | aux j =>
+ rcases j with (j|j)|j
+ · rfl
+ · cases j <;> first | rfl | exact (outside (.inl _) rfl).elim
+ · cases j <;> rfl
+ | frame f => cases f <;> rfl
+ | condition | result => rfl
+ · cases i with
+ | aux j =>
+ rcases j with (j|j)|j
+ · rfl
+ · cases j <;> first | rfl | exact (outside (.inr _) rfl).elim
+ · cases j <;> rfl
+ | frame f => cases f <;> rfl
+ | condition | result => rfl
+ · rfl
+
+/-- The reader update can be made after the roots are mounted in a larger
+workspace. Every engine port then sees its precise initialized value. -/
+theorem setReaders_mounted (host : RootHost K L ↪ H) (work : Stacks H) (c : Vector p e)
+ (r addr width : ℕ) (oldD newD : Stacks K) (oldN newN : Stacks L)
+ (hhost : ∀ i, work (host i) = template c r addr width oldD oldN i) (i : RootHost K L) :
+ installStacks (host ∘ readerPort) work (Sum.elim newD newN) (host i) =
+ template c r addr width newD newN i := by
+ rw [← setReaders c r addr width oldD newD oldN newN]
+ by_cases hin : ∃ j, readerPort j = i
+ · obtain ⟨j, rfl⟩ := hin
+ rw [installStacks_at readerPort_injective]
+ exact installStacks_at (host.injective.comp readerPort_injective) work (Sum.elim newD newN) j
+ · rw [installStacks_outside (ports := host ∘ readerPort) _ _ (fun j h => hin ⟨j, host.injective h⟩),
+ installStacks_outside _ _ (not_exists.mp hin)]
+ exact hhost i
+
+/-- A uniform height bound for the fixed root template plus a scalar reader
+whose own input stacks each have length at most `a`. -/
+def templateCap (addr width e a : ℕ) :=
+ max (max (addr+width+e+e*width+a) (max 1 (max addr (e*width)))) ((e+1)*(width+1))
+
+variable [Fact p.Prime]
+
+theorem template_length (c : Vector p e) (r addr width a : ℕ) (hr : r < 2^addr)
+ (hw : Word.workingWidth p ≤ width) (denReader : Stacks K) (numReader : Stacks L)
+ (hd : ∀ i, (denReader i).length ≤ a) (hn : ∀ j, (numReader j).length ≤ a) (i : RootHost K L) :
+ ((template c r addr width denReader numReader) i).length ≤ templateCap addr width e a := by
+ have rootBound {J : Type} (localBank : Stacks J) (hj : ∀ j, (localBank j).length ≤ a)
+ (k : Engine.Port (GramEngine.Aux J)) :
+ (Cramer.SchurPair.entryBank c r addr width (GramEngine.initial addr width r r c localBank) k).length
+ ≤ templateCap addr width e a := by
+ let ready (s : Stacks J) := ∀ j, (s j).length ≤ a
+ have hready := GramEngine.initial_ready (readerReady := ready) (c := c) (v := width) localBank hj hr hr
+ have small := GramEngine.ready_length hready (fun _ hs => hs)
+ have h := Engine.state_length (d := 0) (c := c) (w := addr) (v := width)
+ (.enter (SchurKey.root (n := r) (Fin.last r) (Fin.last 0)), []) (by simp) _ small k
+ apply (le_trans h ?_)
+ simp only [Nat.zero_mul, Nat.max_zero]
+ exact le_max_left ..
+ rcases i with i | i | i
+ · exact rootBound denReader hd i
+ · exact rootBound numReader hn i
+ · have h := Cramer.frame_length hw c c c i
+ apply (le_trans ?_ h).trans (le_max_right ..)
+ rcases i with ((i|i)|i)|i
+ · exact le_rfl
+ · cases i <;> exact le_rfl
+ · cases i <;> first | exact le_rfl | exact Nat.zero_le _
+ · cases i <;> first | exact le_rfl | exact Nat.zero_le _
+
+/-- Each advised word is counted once, even when different ports receive equal data. -/
+theorem template_total_length [Fintype (RootHost K L)] (c : Vector p e) (r addr width a : ℕ)
+ (hr : r < 2^addr) (hw : Word.workingWidth p ≤ width) (denReader : Stacks K) (numReader : Stacks L)
+ (hd : ∀ i, (denReader i).length ≤ a) (hn : ∀ j, (numReader j).length ≤ a) :
+ ∑ i, ((template c r addr width denReader numReader) i).length ≤
+ Fintype.card (RootHost K L) * templateCap addr width e a := by
+ calc
+ _ ≤ ∑ _ : RootHost K L, templateCap addr width e a :=
+ Finset.sum_le_sum fun i _ => template_length c r addr width a hr hw denReader numReader hd hn i
+ _ = _ := by simp
+
+/-- Initialize the actual paired Schur workspaces in an empty scratch bank. Both
+roots are installed at the top pencil query, and the copy's temporary port is
+empty on return. The loaded template can be patched at `readerPort` with the
+current entry request before the two determinant calls. -/
+theorem loadRoot_runs [Fintype (RootHost K L)] [DecidableEq A] [DecidableEq H]
+ (source : RootHost K L → A) (host : RootHost K L ↪ H) (scratch : H) (fresh : ∀ i, host i ≠ scratch)
+ (c : Vector p e) (r addr width readerBound ambient : ℕ) (hr : r < 2^addr)
+ (hw : Word.workingWidth p ≤ width) (denReader : Stacks K) (numReader : Stacks L)
+ (hd : ∀ i, (denReader i).length ≤ readerBound) (hn : ∀ j, (numReader j).length ≤ readerBound)
+ (label current next : List Bool) (advice : Stacks A)
+ (hsource : ∀ i, advice (source i) = template c r addr width denReader numReader i)
+ (bankFits : ∀ i, (Reader.bank label current next [] (Sum.elim advice (fun _ : H => [])) i).length ≤ ambient) :
+ let cap := templateCap addr width e readerBound
+ ∃ t ≤ loadClock (RootHost K L) cap, ∃ work : Stacks H, work scratch = [] ∧
+ (∀ i, work (host i) = template c r addr width denReader numReader i) ∧
+ (load source host scratch).BoundedRun (ambient + loadClock (RootHost K L) cap) t
+ (Reader.bank label current next [] (Sum.elim advice (fun _ => [])))
+ (Reader.bank label current next [] (Sum.elim advice work)) := by
+ let tplt := template c r addr width denReader numReader
+ let cap := templateCap addr width e readerBound
+ let work := installStacks host (fun _ : H => []) tplt
+ obtain ⟨t, ht, run⟩ := load_runs source host scratch fresh label current next [] advice (fun _ => [])
+ tplt hsource (fun _ => rfl) rfl cap ambient (template_length c r addr width readerBound hr hw
+ denReader numReader hd hn) bankFits
+ exact ⟨t, ht, work, installStacks_outside _ _ fresh, installStacks_at host.injective _ _, run⟩
+
+end RankQuery.Stack.Coordinate.RootInit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSelect.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSelect.lean
new file mode 100644
index 0000000000..24c9b46962
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSelect.lean
@@ -0,0 +1,225 @@
+import OAI.Computability.VPVNP.RankCoordinateColumn
+import OAI.Computability.VPVNP.RankCoordinateOrdinalABI
+import OAI.Computability.VPVNP.RankPrefixRead
+import OAI.Computability.VPVNP.RankPrefixTemplate
+import OAI.Computability.VPVNP.RankPrefixWorkspace
+import OAI.Computability.VPVNP.RankQueryGramExecution
+
+/-! # Computing greedy row and column indices from a streamed matrix
+
+At each prefix the five-word controller starts the complete physical rank
+scan in private workspace. All matrix-entry requests address the original
+matrix. For a column query the two address ports of its reader are
+interchanged. Both routines return the original selected index.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace RankQuery.Stack.Coordinate.Select
+
+open RAMTape BurstRAM Dispatch UniversalCountStack Cursor PrefixWorkspace
+
+variable {K : Type} [Fintype K] [DecidableEq K]
+
+/-- Compare prefix-rank stack addresses using the port labels of the Gram scan. -/
+local instance : DecidableEq (PrefixPort K) :=
+ inferInstanceAs (DecidableEq (ScanPort (GramEngine.Aux K)))
+
+/-- Decide equality of addresses in the template, working copy, and scratch stack of a
+prefix-rank call. -/
+local instance : DecidableEq (PrefixWorkspace.Aux (PrefixPort K)) :=
+ fun a b => PrefixWorkspace.instDecidableEqAux a b
+
+/-- Cursor argument register containing the rank returned by the Gram scan. -/
+def rankResult : PrefixPort K := .cursor (.isa (.reg (Registers.arg 1)))
+
+/-- Compute the rank of the current row prefix by passing its length to the Gram routine and
+reading its result register. -/
+def prefixRank (read : FiniteRoutine (MacaulayRead.Port K)) :=
+ rankCall prefixDynamic (gramRank read) rankResult
+
+/-- Scan row prefixes for the rank increase that identifies the requested greedy basis row. -/
+def rows (read : FiniteRoutine (MacaulayRead.Port K)) := PrefixWords.machine (prefixRank read)
+
+/-- Apply the greedy row scan to the transpose reader to find the requested original column
+index. -/
+def columns (read : FiniteRoutine (MacaulayRead.Port K)) := rows (MacaulayRead.transpose read)
+
+/-- Maximum stack length needed for either the initial prefix template or the running Gram
+scan. -/
+def workCap (d w v e A S : ℕ) := max (w+v+e+e*v+A+1) (gramSpace d w v e A S)
+
+/-- Step bound for copying the prefix template, computing one rank, and returning the result. -/
+def timePerRank (K : Type) [Fintype K] (d w v e B A S : ℕ) :=
+ let M := workCap d w v e A S
+ copyClock (PrefixPort K) M + gramTime d w v e B + returnClock (PrefixPort K) w M
+
+/-- Step bound for testing up to `n` prefixes, including rank calls and updates to the
+controller words. -/
+def scanTime (K : Type) [Fintype K] (n d w v e B A S : ℕ) :=
+ n*((PrefixWords.arithmeticBound w+timePerRank K d w v e B A S+(20*w+10))+1+PrefixWords.arithmeticBound w)
+
+/-- Maximum stack length over the prefix controller's arithmetic and its private rank calls. -/
+def scanSpace (K : Type) [Fintype K] (d w v e A S : ℕ) :=
+ max (w+PrefixWords.arithmeticBound w) (callSpace (PrefixPort K) w (workCap d w v e A S))
+
+variable {p e n m d w v B A S : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- Initialize the reusable rank template with zero rows and `m` columns, leaving the working
+copy and scratch stack empty. -/
+def side (w v m : ℕ) (c : SliceArithmetic.Vector p e) (base : Stacks K) :=
+ auxBank (prefixRawBank w v 0 m c base) (fun _ => [])
+
+private theorem workCap_width : w ≤ workCap d w v e A S :=
+ (show w ≤ w+v+e+e*v+A+1 by omega).trans (le_max_left ..)
+
+private theorem width_le {d w : ℕ} (hw : gramWidth d ≤ w) : d ≤ w := by
+ have h := Nat.le_mul_of_pos_right (2*d+7) (Nat.succ_pos (max widthFactor control.wordFactor))
+ change 2*d+7 ≤ (2*d+7)*(max widthFactor control.wordFactor+1) at h
+ unfold gramWidth at hw
+ omega
+
+private theorem set_result (j k a b r : ℕ) : Function.update (PrefixWords.words (w := w) j k a b) 3 (Fin.ofNat _ r) =
+ PrefixWords.words j k r b := by funext i; fin_cases i <;> rfl
+
+theorem side_length {ready : Stacks K → Prop} (c : SliceArithmetic.Vector p e) (base : Stacks K)
+ (hr : ready base) (ha : ∀ s, ready s → ∀ i, (s i).length ≤ A) (hm : m < 2^w)
+ (i : PrefixWorkspace.Aux (PrefixPort K)) : (side w v m c base i).length ≤ scanSpace K d w v e A S := by
+ cases i with
+ | template h =>
+ apply (prefixRawBank_length c base hr ha (Nat.two_pow_pos w) hm h).trans
+ exact (le_max_left ..).trans ((Nat.le_add_right (workCap d w v e A S) _).trans (le_max_right ..))
+ | work h | scratch => exact Nat.zero_le _
+
+private theorem rankAt_zero {F : Type*} [Field F] [DecidableEq F] (L : Matrix (Fin n) (Fin m) F) :
+ PrefixWords.rankAt L 0 = 0 := by
+ rw [PrefixWords.rankAt_eq _ (Nat.zero_le n), rankQuery_eq]
+ have h := (prefixRows L 0 (Nat.zero_le n)).rank_le_card_height
+ simpa only [Fintype.card_fin, Nat.le_zero] using h
+
+variable [Fact p.Prime] [NeZero e] [Fact (Irreducible (SliceArithmetic.modulus c))]
+ [DecidableEq (AdjoinRoot (SliceArithmetic.modulus c))]
+
+/-- The rank subroutine called by the greedy controller. The incoming
+prefix register determines every dynamic dimension in the two nested scans. -/
+theorem prefixRank_runs (M : Matrix (Fin n) (Fin m) (Scalar c))
+ (read : FiniteRoutine (MacaulayRead.Port K)) {ready : Stacks K → Prop}
+ (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (ha : ∀ s, ready s → ∀ i, (s i).length ≤ A)
+ (hsize : n+n+(n+m)*n+m+8 < 2^d) (hw : gramWidth d ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (base : Stacks K) (hr : ready base) (j k old : ℕ) (hj : j < n) :
+ ∃ t ≤ timePerRank K d w v e B A S, (prefixRank read).BoundedRun (scanSpace K d w v e A S) t
+ (PrefixWords.bank (side w v m c base) (PrefixWords.words (w := w) j k old (j+1)))
+ (PrefixWords.bank (side w v m c base) (PrefixWords.words (w := w) j k
+ (PrefixWords.rankAt (M.map (Scalar.interpretation c)) (j+1)) (j+1))) := by
+ let R := (prefixRows (M.map (Scalar.interpretation c)) (j+1) hj).rank
+ let rs := PrefixWords.words (w := w) j k old (j+1)
+ let template := prefixRawBank w v 0 m c base
+ let cap := workCap d w v e A S
+ have hm : m < 2^w := (show m < 2^d by omega).trans_le (Nat.pow_le_pow_right (by decide) (width_le hw))
+ have ht (h : PrefixPort K) : (template h).length ≤ cap :=
+ (prefixRawBank_length c base hr ha (Nat.two_pow_pos w) hm h).trans (le_max_left ..)
+ obtain ⟨t,bt,out,aux,_,hout,run⟩ := gramRank_bounded (prefixRows M (j+1) hj) read (hc.prefixMatrix _ hj)
+ ha hj hsize hw hv base hr
+ have hraw : prepared prefixDynamic template rs = rawGram w v (j+1) m c base := by
+ funext h
+ change (if prefixDynamic h then digits w (j+1) else template h) = prefixRawBank w v (j+1) m c base h
+ exact (prefixRawBank_eq w v (j+1) m c base h).symm
+ let final := scanBank (j+1) (0 : Word w) out [] (idle aux)
+ have hresult : (out (Registers.arg 1)).val = R := hout 1 (by decide)
+ have hword : out (Registers.arg 1) = Fin.ofNat (2^w) R := by
+ apply Fin.ext
+ exact hresult.trans (Nat.mod_eq_of_lt (hresult ▸ (out (Registers.arg 1)).isLt)).symm
+ have hread : final rankResult = wordBits (Fin.ofNat (2^w) R) := congrArg wordBits hword
+ have framed := rankCall_bounded prefixDynamic (gramRank read) rankResult template final rs
+ (Fin.ofNat (2^w) R) cap t workCap_width ht (hraw.symm ▸ run.enlarge (le_max_right ..)) hread
+ obtain ⟨s,hs,hret⟩ := framed
+ have update : Function.update rs 3 (Fin.ofNat _ R) = PrefixWords.words j k R (j+1) := set_result ..
+ rw [update] at hret
+ refine ⟨s,hs.trans (Nat.add_le_add_right (Nat.add_le_add_left bt _) _),?_⟩
+ rw [PrefixWords.rankAt_eq _ hj, rankQuery_eq]
+ exact hret.enlarge (le_max_right ..)
+
+/-- Complete physical row selection, including all prefix rank and scalar
+entry requests, with a reusable private workspace. -/
+theorem row_runs (M : Matrix (Fin n) (Fin m) (Scalar c)) (read : FiniteRoutine (MacaulayRead.Port K))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (ha : ∀ s, ready s → ∀ i, (s i).length ≤ A)
+ (hsize : n+n+(n+m)*n+m+8 < 2^d) (hw : gramWidth d ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (base : Stacks K) (hr : ready base) (k : Fin (rankQuery (M.map (Scalar.interpretation c)))) :
+ let L := M.map (Scalar.interpretation c)
+ let found := (greedyRowIndex L k).val
+ ∃ t ≤ scanTime K n d w v e B A S, (rows read).BoundedRun (scanSpace K d w v e A S) t
+ (PrefixWords.bank (side w v m c base) (PrefixWords.words (w := w) 0 k.val (PrefixWords.rankAt L 0) 0))
+ (PrefixWords.bank (side w v m c base) (PrefixWords.words (w := w) found k.val (PrefixWords.rankAt L (found+1)) (found+1))) := by
+ have hdw : 2^d ≤ 2^w := Nat.pow_le_pow_right (by decide) (width_le hw)
+ have hn : n < 2^w := by omega
+ have hm : m < 2^w := by omega
+ apply PrefixWords.machine_runs _ k _ (prefixRank read) hn _ (le_max_left ..)
+ · intro j hj
+ exact prefixRank_runs M read hc ha hsize hw hv base hr j k _ hj
+ · exact side_length c base hr ha hm
+
+/-- The transpose scan returns the columns chosen for the square Cramer
+minor of the original matrix. -/
+theorem column_runs (M : Matrix (Fin n) (Fin m) (Scalar c)) (read : FiniteRoutine (MacaulayRead.Port K))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (ha : ∀ s, ready s → ∀ i, (s i).length ≤ A)
+ (hsize : m+m+(m+n)*m+n+8 < 2^d) (hw : gramWidth d ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (base : Stacks K) (hr : ready base) (k : Fin (rankQuery (M.map (Scalar.interpretation c)))) :
+ let L := M.map (Scalar.interpretation c)
+ let found := (coordinateColumns (greedyRowBasis L) (greedyRowBasis_fullRank L) k).val
+ ∃ t ≤ scanTime K m d w v e B A S, (columns read).BoundedRun (scanSpace K d w v e A S) t
+ (PrefixWords.bank (side w v n c base) (PrefixWords.words (w := w) 0 k.val (PrefixWords.rankAt L.transpose 0) 0))
+ (PrefixWords.bank (side w v n c base) (PrefixWords.words (w := w) found k.val (PrefixWords.rankAt L.transpose (found+1)) (found+1))) := by
+ dsimp only
+ rw [coordinateColumns_greedyRowBasis]
+ exact row_runs M.transpose (MacaulayRead.transpose read) hc.transpose ha hsize hw hv base hr
+ (Fin.cast (by rw [rankQuery_eq, rankQuery_eq]; exact (Matrix.rank_transpose _).symm) k)
+
+/-- Native ordinal reader for greedy rows of the streamed matrix. Its
+private work template is restored on every return. -/
+theorem row_correctSpace (M : Matrix (Fin n) (Fin m) (Scalar c)) (read : FiniteRoutine (MacaulayRead.Port K))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (ha : ∀ s, ready s → ∀ i, (s i).length ≤ A)
+ (hsize : n+n+(n+m)*n+m+8 < 2^d) (hw : gramWidth d ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (base : Stacks K) (hr : ready base) :
+ OrdinalRead.CorrectSpace (OrdinalABI.machine (rows read)) (greedyRowIndex (M.map (Scalar.interpretation c)))
+ w (scanTime K n d w v e B A S+OrdinalABI.overhead w) (scanSpace K d w v e A S+OrdinalABI.overhead w)
+ (· = OrdinalABI.idle (w := w) (side w v m c base)) := by
+ have hm : m < 2^w := (show m < 2^d by omega).trans_le (Nat.pow_le_pow_right (by decide) (width_le hw))
+ apply OrdinalABI.correctSpace _ _ _ (side_length c base hr ha hm) ((Nat.le_add_right _ _).trans (le_max_left ..))
+ intro i
+ obtain ⟨t,bt,run⟩ := row_runs M read hc ha hsize hw hv base hr i
+ rw [rankAt_zero] at run
+ exact ⟨t,bt,_,_,run⟩
+
+/-- Native ordinal reader for the selected columns of the square Cramer minor. -/
+theorem column_correctSpace (M : Matrix (Fin n) (Fin m) (Scalar c)) (read : FiniteRoutine (MacaulayRead.Port K))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (ha : ∀ s, ready s → ∀ i, (s i).length ≤ A)
+ (hsize : m+m+(m+n)*m+n+8 < 2^d) (hw : gramWidth d ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (base : Stacks K) (hr : ready base) :
+ let L := M.map (Scalar.interpretation c)
+ OrdinalRead.CorrectSpace (OrdinalABI.machine (columns read))
+ (coordinateColumns (greedyRowBasis L) (greedyRowBasis_fullRank L))
+ w (scanTime K m d w v e B A S+OrdinalABI.overhead w) (scanSpace K d w v e A S+OrdinalABI.overhead w)
+ (· = OrdinalABI.idle (w := w) (side w v n c base)) := by
+ have hn : n < 2^w := (show n < 2^d by omega).trans_le (Nat.pow_le_pow_right (by decide) (width_le hw))
+ apply OrdinalABI.correctSpace _ _ _ (side_length c base hr ha hn) ((Nat.le_add_right _ _).trans (le_max_left ..))
+ intro i
+ obtain ⟨t,bt,run⟩ := column_runs M read hc ha hsize hw hv base hr i
+ rw [rankAt_zero] at run
+ exact ⟨t,bt,_,_,run⟩
+
+end RankQuery.Stack.Coordinate.Select
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSelectedAdvice.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSelectedAdvice.lean
new file mode 100644
index 0000000000..100a41adc5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSelectedAdvice.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.RankCoordinateAdvice
+import OAI.Computability.VPVNP.RankCoordinateArgumentSelected
+import OAI.Computability.VPVNP.RankCoordinateSliceTargets
+
+/-! # Static advice of the two selected slice determinants
+
+Both greedy scans and the ordinary entry reads start from the supplied
+base matrix reader. The target uses a zero monomial, mark, and scale in the
+cloned template. The two advised scales are the certificate power and its
+product with the field order. The dynamic preparation then fills in the
+replacement row and the powered monomial for each requested matrix entry.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace RankQuery.Stack.Coordinate.SelectedAdvice
+
+open RAMTape SliceArithmetic UniversalCountStack NativeReader
+open RadicalCertificate.MonomialIndex
+open SliceMinors
+
+/-- Workspace ports for reading a denominator entry, with the base matrix reader serving both
+pivot scans and the final entry query. -/
+abbrev Den (K : Type) := SelectedMinor.Work K K
+/-- Ports for the numerator's pivot scans, original matrix entries and powered target entries. -/
+abbrev Raw (K : Type) := ArgumentStage.SelectedHost K K
+/-- Private ports of the rank-prefix scan that recovers the source row ordinal. -/
+abbrev Side (K : Type) := Select.Side K
+/-- Port families for the determinant pair, the dynamic index calculation and unary label
+conversion. -/
+abbrev Parts (K : Type) := Prepare.Parts (Den K) (Raw K) (Side K)
+/-- Read-only preparation ports carrying the component templates and the two possible target
+scales. -/
+abbrev Advice (K : Type) := Prepare.Advice (Den K) (Raw K) (Side K)
+/-- Writable preparation ports for the template copies and their temporary stack. -/
+abbrev Work (K : Type) := Prepare.Work (Den K) (Raw K) (Side K)
+
+variable {K F : Type} {p e t eqs : ℕ}
+
+/-- The certificate power for a label step, or its product with the field order for a Frobenius
+step. -/
+def powers (Q : QueryData t eqs F) (b : Bool) := if b then Q.power*Q.fieldOrder else Q.power
+
+variable [DecidableEq K] [Fact p.Prime]
+
+/-- Denominator template with both pivot scans initialized and the selected row and column
+words empty. -/
+def den (c : Vector p e) (Q : QueryData t eqs F) (w v : ℕ) (base : Stacks K) : Stacks (Den K) :=
+ Submatrix.workBank [] [] (SelectedMinor.initial w v (height Q) (width Q) c base base)
+
+/-- Initial numerator reader banks for the base matrix, its pivot scans and the powered target
+template. -/
+def raw (c : Vector p e) (Q : QueryData t eqs F) (w v : ℕ) (base : Stacks K) : Stacks (Raw K) :=
+ ArgumentStage.selectedRaw w v (height Q) (width Q) c base base (targetTemplate Q) (TargetRead.literal c v)
+
+/-- Numerator workspace before staging, with replacement ordinal zero and empty
+selected-address words. -/
+def num (c : Vector p e) (Q : QueryData t eqs F) (w v : ℕ) (base : Stacks K) : Stacks (ArgumentStage.Num (Raw K)) :=
+ Replacement.workBank w (digits w 0) (Submatrix.workBank [] [] (raw c Q w v base))
+
+/-- Idle bank for scanning row ranks of the base matrix with the slice's column count. -/
+def side (c : Vector p e) (Q : QueryData t eqs F) (w v : ℕ) (base : Stacks K) : Stacks (Side K) :=
+ SelectedMinor.selectorBank w v (width Q) c base
+
+/-- Stack-height bound for the greedy row scan together with its ordinal input and output
+registers. -/
+def selectorCap (K : Type) [Fintype K] (d w v e A S : ℕ) := Select.scanSpace K d w v e A S+OrdinalABI.overhead w
+
+/-- Maximum advised stack height accounting for selected-minor reads, ordinal selection and
+determinant initialization. -/
+def portBound (K : Type) [Fintype K] (d w v e A S : ℕ) :=
+ FullAdvice.portBound w v e (SelectedMinor.space K d w v e A S) (selectorCap K d w v e A S)
+
+variable [Field F] [DecidableEq F]
+
+/-- Static advice for one slice, including the two determinant templates, equation rank, row
+counts and target scales. -/
+def selectedAdvice (c : Vector p e) (Q : QueryData t eqs F) (w v : ℕ) (base : Stacks K) : Stacks (Advice K) :=
+ FullAdvice.advice c (order Q) w v (rankQuery Q.equations) (eqs*size t Q.multiplierDegree)
+ (den c Q w v base) (num c Q w v base) (side c Q w v base) (powers Q)
+
+/-- The static slice advice paired with an initially empty private preparation workspace. -/
+def selectedExtra (c : Vector p e) (Q : QueryData t eqs F) (w v : ℕ) (base : Stacks K) : Stacks (Advice K ⊕ Work K) :=
+ Sum.elim (selectedAdvice c Q w v base) (fun _ => [])
+
+variable [Fintype K] {d w v A S P : ℕ}
+
+omit [Fact p.Prime] [Field F] [DecidableEq F] in
+theorem side_length (c : Vector p e) (Q : QueryData t eqs F) (base : Stacks K)
+ (hbase : ∀ k, (base k).length ≤ A) (hm : width Q < 2^w) (k : Side K) :
+ (side c Q w v base k).length ≤ selectorCap K d w v e A S := by
+ have hw : w ≤ Select.scanSpace K d w v e A S := (Nat.le_add_right ..).trans (le_max_left ..)
+ cases k with
+ | inl k => exact (RegisterTable.bank_length_le Fin.elim0 0 _ k).trans (hw.trans (Nat.le_add_right ..))
+ | inr k => exact (Select.side_length (ready := (· = base)) c base rfl (fun s hs => hs ▸ hbase) hm k).trans (Nat.le_add_right ..)
+
+omit [Field F] [DecidableEq F] in
+theorem reader_length (c : Vector p e) (Q : QueryData t eqs F) (base : Stacks K)
+ (hbase : ∀ k, (base k).length ≤ A) (hn : height Q < 2^w) (hm : width Q < 2^w)
+ (hword : w ≤ P) (harity : t ≤ P) (hscalar : max P (e*v) ≤ A) :
+ (∀ k, (den c Q w v base k).length ≤ SelectedMinor.space K d w v e A S) ∧
+ (∀ k, (num c Q w v base k).length ≤ SelectedMinor.space K d w v e A S) := by
+ let isBase (s : Stacks K) := s = base
+ have cap : ∀ s, isBase s → ∀ k, (s k).length ≤ A := fun s hs => hs ▸ hbase
+ let target := targetTemplate Q
+ let direct := directReady c w v target isBase
+ have live : direct (Sum.elim base (TargetRead.bank w target (TargetRead.literal c v))) := ⟨rfl, rfl⟩
+ have directCap (s : Stacks (Direct K)) (h : direct s) (k : Direct K) : (s k).length ≤ A := by
+ rcases k with k | k
+ · exact cap _ h.1 k
+ · exact (TargetRead.ready_bound c target h.2 hword harity k).trans hscalar
+ constructor
+ · apply SelectedMinor.den_ready_length (pivot := isBase) (ready := isBase) base rfl cap cap hn hm
+ exact ⟨_, SelectedMinor.initial_ready base base rfl, rfl⟩
+ · apply SelectedMinor.num_ready_length (pivot := isBase) (ready := direct) base rfl cap directCap hn hm 0
+ exact ⟨_, ⟨_, SelectedMinor.initial_ready base _ live, rfl⟩, rfl⟩
+
+omit [DecidableEq K] [Fact p.Prime] [Fintype K] in
+theorem order_lt (Q : QueryData t eqs F) (hn : height Q < 2^w) : order Q < 2^w := by
+ exact lt_of_le_of_lt (by simpa only [order, rankQuery_eq, Fintype.card_fin] using
+ (fieldMatrix Q).rank_le_card_height) hn
+
+variable (c : Vector p e) (Q : QueryData t eqs F) (base : Stacks K)
+ (hbase : ∀ k, (base k).length ≤ A) (hn : height Q < 2^w) (hm : width Q < 2^w)
+ (hword : w ≤ P) (harity : t ≤ P) (hscalar : max P (e*v) ≤ A) (hv : Word.workingWidth p ≤ v)
+
+include hbase hn hm hword harity hscalar hv
+
+/-- Every advised stack and every initially empty private stack fits the
+same concrete cap for all current/next ordinals and for both operations. -/
+theorem extra_length (k : Advice K ⊕ Work K) : (selectedExtra c Q w v base k).length ≤ portBound K d w v e A S := by
+ obtain ⟨hd,hu⟩ := reader_length (d := d) (S := S) c Q base hbase hn hm hword harity hscalar
+ exact FullAdvice.extra_length c (order Q) w v (rankQuery Q.equations) (eqs*size t Q.multiplierDegree)
+ (den c Q w v base) (num c Q w v base) (side c Q w v base) (powers Q) _ _ (order_lt Q hn) hv hd hu
+ (side_length c Q base hbase hm) k
+
+/-- The clone and the public entry words fit their actual initialization and
+ambient capacities before the physical preparation machine starts. -/
+theorem fit (label cur next : ℕ) :
+ let M := portBound K d w v e A S
+ let root := RootInit.template c (order Q) w v (den c Q w v base) (num c Q w v base)
+ let dyn := Dynamic.bank (side c Q w v base) (Dynamic.regs (w := w) 0 0 (rankQuery Q.equations) (eqs*size t Q.multiplierDegree) 0 0 0 0)
+ let unary := UnaryWord.store [] [] (digits w 0) [] []
+ (∀ i, (root i).length ≤ M) ∧ (∀ i, (dyn i).length ≤ M) ∧ (∀ i, (unary i).length ≤ M) ∧
+ (∀ k, (state (List.replicate label true) (digits w cur) (digits w next) [] (selectedAdvice c Q w v base)
+ (fun _ : Work K => []) k).length ≤ max label M) := by
+ obtain ⟨hd,hu⟩ := reader_length (d := d) (S := S) c Q base hbase hn hm hword harity hscalar
+ exact FullAdvice.fit c (order Q) w v (rankQuery Q.equations) (eqs*size t Q.multiplierDegree)
+ (den c Q w v base) (num c Q w v base) (side c Q w v base) (powers Q) _ _ (order_lt Q hn) hv hd hu
+ (side_length c Q base hbase hm) label cur next
+
+end RankQuery.Stack.Coordinate.SelectedAdvice
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSelectedMinor.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSelectedMinor.lean
new file mode 100644
index 0000000000..1a89638e7e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSelectedMinor.lean
@@ -0,0 +1,230 @@
+import OAI.Computability.VPVNP.RankCoordinateSelect
+import OAI.Computability.VPVNP.RankCoordinateCramer
+import OAI.Computability.VPVNP.RankCoordinateBanks
+import OAI.Computability.VPVNP.RankCoordinateSubmatrix
+import OAI.Computability.VPVNP.RankCoordinateReplacement
+
+/-! # Physical coefficient readers for the two Cramer minors
+
+One bank supplies each greedy selector and a third supplies the underlying
+scalar reader. A target-row read uses the same selected column as an
+ordinary entry. The numerator stores its replacement ordinal separately
+from these three banks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace RankQuery.Stack.Coordinate
+
+open RAMTape BurstRAM Dispatch UniversalCountStack Cursor
+
+/-- Stack addresses for the greedy selector's controller words and its prefix-rank workspace. -/
+abbrev Select.Side (K : Type) := PrefixWorkspace.Port (PrefixPort K)
+
+namespace SelectedMinor
+
+/-- Disjoint stack addresses for the row selector, column selector, and underlying scalar
+reader. -/
+abbrev Host (K R : Type) := ThreeBanks.Host (Select.Side K) (Select.Side K) R
+/-- Stack addresses for the selected submatrix's two saved indices and its three reader banks. -/
+abbrev Work (K R : Type) := Submatrix.Work (Host K R)
+
+variable {K R : Type} [Fintype K] [DecidableEq K] [DecidableEq R] {p e n m w v d B S A E Ba : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- Compare the prefix scan addresses used when locating a pivot for a Cramer minor. -/
+local instance : DecidableEq (PrefixPort K) := inferInstanceAs (DecidableEq (ScanPort (GramEngine.Aux K)))
+/-- Decide equality of template, work, and scratch addresses within a pivot selector. -/
+local instance : DecidableEq (PrefixWorkspace.Aux (PrefixPort K)) := fun a b => PrefixWorkspace.instDecidableEqAux a b
+/-- Decide equality of controller and workspace stack addresses in a greedy selector bank. -/
+local instance : DecidableEq (Select.Side K) := inferInstanceAs (DecidableEq (PrefixWords.Port (PrefixWorkspace.Aux (PrefixPort K))))
+/-- Compare stack addresses by bank and then by their row-selector, column-selector, or
+scalar-reader label. -/
+local instance : DecidableEq (Host K R) := inferInstanceAs (DecidableEq (Select.Side K ⊕ (Select.Side K ⊕ R)))
+/-- Decide equality of the two saved-index addresses and the auxiliary bank addresses for a
+minor read. -/
+local instance : DecidableEq (Work K R) := fun a b => Submatrix.instDecidableEqWork a b
+
+/-- Idle state of an ordinal selector, with its rank template configured for a matrix with
+`cols` columns. -/
+def selectorBank (w v cols : ℕ) (c : SliceArithmetic.Vector p e) (base : Stacks K) :=
+ OrdinalABI.idle (w := w) (Select.side w v cols c base)
+
+/-- The row and column selectors are in their designated idle states and the scalar reader
+satisfies its readiness predicate. -/
+def Ready (w v n m : ℕ) (c : SliceArithmetic.Vector p e) (base : Stacks K) (ready : Stacks R → Prop) :=
+ ThreeBanks.Ready (· = selectorBank w v m c base) (· = selectorBank w v n c base) ready
+
+/-- Combine idle selectors for the matrix and its transpose with the supplied scalar-reader
+stacks. -/
+def initial (w v n m : ℕ) (c : SliceArithmetic.Vector p e) (base : Stacks K) (raw : Stacks R) : Stacks (Host K R) :=
+ Sum.elim (selectorBank w v m c base) (Sum.elim (selectorBank w v n c base) raw)
+
+omit [Fintype K] [DecidableEq R] in
+theorem initial_ready {ready : Stacks R → Prop} (base : Stacks K) (raw : Stacks R) (hr : ready raw) :
+ Ready w v n m c base ready (initial w v n m c base raw) := ⟨rfl,rfl,hr⟩
+
+/-- Pivot selection is always performed on the original relation matrix.
+The final scalar can be read from that matrix or from a powered target row. -/
+def restrictEntry (read : FiniteRoutine (MacaulayRead.Port K)) (entry : FiniteRoutine (MacaulayRead.Port R)) : FiniteRoutine (MacaulayRead.Port (Work K R)) :=
+ Submatrix.minorRead (OrdinalRead.onAux ThreeBanks.left (OrdinalABI.machine (Select.rows read)))
+ (OrdinalRead.onAux ThreeBanks.middle (OrdinalABI.machine (Select.columns read)))
+ (MacaulayRead.onAux ThreeBanks.right entry)
+
+/-- Uniform stack-length bound for selector calls, scalar reads, and the stored input banks. -/
+def space (K : Type) [Fintype K] (d w v e A S : ℕ) :=
+ max (Select.scanSpace K d w v e A S + OrdinalABI.overhead w) (max S A)
+
+/-- Step bound for selecting an original row and column, reading their scalar entry, and
+handling the two address words. -/
+def time (K : Type) [Fintype K] (n m d w v e B A S E : ℕ) :=
+ (Select.scanTime K n d w v e B A S+OrdinalABI.overhead w) +
+ (Select.scanTime K m d w v e B A S+OrdinalABI.overhead w) + E + 2*(w+1)
+
+
+omit [DecidableEq R] in
+theorem ready_length {pivot : Stacks K → Prop} {ready : Stacks R → Prop} (base : Stacks K) (hr : pivot base)
+ (ha : ∀ a, pivot a → ∀ k, (a k).length ≤ A) (he : ∀ a, ready a → ∀ k, (a k).length ≤ A) (hn : n < 2^w) (hm : m < 2^w)
+ (s : Stacks (Host K R)) (h : Ready w v n m c base ready s) (k : Host K R) :
+ (s k).length ≤ space K d w v e A S := by
+ let cap := space K d w v e A S
+ have hsc : Select.scanSpace K d w v e A S ≤ cap := (Nat.le_add_right _ _).trans (le_max_left ..)
+ have hw : w ≤ cap := ((Nat.le_add_right _ _).trans (le_max_left ..)).trans hsc
+ have hi (cols : ℕ) (hcols : cols < 2^w) (a : Stacks (Select.Side K))
+ (heq : a = selectorBank w v cols c base) (j : Select.Side K) : (a j).length ≤ cap := by
+ subst a
+ cases j with
+ | inl j => exact (RegisterTable.bank_length_le Fin.elim0 0 _ j).trans hw
+ | inr j => exact (Select.side_length c base hr ha hcols j).trans hsc
+ exact ThreeBanks.length_le (hi m hm) (hi n hn)
+ (fun b hb j => (he b hb j).trans ((le_max_right ..).trans (le_max_right ..))) h k
+
+omit [DecidableEq R] in
+theorem den_ready_length {pivot : Stacks K → Prop} {ready : Stacks R → Prop} (base : Stacks K) (hr : pivot base)
+ (ha : ∀ a, pivot a → ∀ k, (a k).length ≤ A) (he : ∀ a, ready a → ∀ k, (a k).length ≤ A) (hn : n < 2^w) (hm : m < 2^w)
+ (s : Stacks (Work K R)) (h : Submatrix.Ready (Ready w v n m c base ready) s) (k : Work K R) :
+ (s k).length ≤ space K d w v e A S := by
+ obtain ⟨b, hb, rfl⟩ := h
+ cases k with
+ | row | col => exact Nat.zero_le _
+ | aux k => exact ready_length base hr ha he hn hm _ hb k
+
+omit [DecidableEq R] in
+theorem num_ready_length {pivot : Stacks K → Prop} {ready : Stacks R → Prop} (base : Stacks K) (hr : pivot base)
+ (ha : ∀ a, pivot a → ∀ k, (a k).length ≤ A) (he : ∀ a, ready a → ∀ k, (a k).length ≤ A) (hn : n < 2^w) (hm : m < 2^w) (i : ℕ)
+ (s : Stacks (Replacement.Work (Work K R)))
+ (h : Replacement.Ready w i (Submatrix.Ready (Ready w v n m c base ready)) s) (k : Replacement.Work (Work K R)) :
+ (s k).length ≤ space K d w v e A S := by
+ obtain ⟨b, hb, rfl⟩ := h
+ have hw : w ≤ space K d w v e A S :=
+ (((Nat.le_add_right w _).trans (le_max_left ..)).trans (Nat.le_add_right (Select.scanSpace K d w v e A S) _)).trans (le_max_left ..)
+ rcases k with j | k
+ · cases j with
+ | pub j => exact j.elim0
+ | reg j => fin_cases j <;> simp [Replacement.workBank, length_digits]; exact hw
+ | persistent => exact (length_wordBits (0 : Word w)).le.trans hw
+ | work j => exact Nat.zero_le _
+ | logPort j => cases j <;> exact Nat.zero_le _
+ · exact den_ready_length base hr ha he hn hm _ hb k
+
+private theorem width_le (hw : gramWidth d ≤ w) : d ≤ w := by
+ have h : 2*d+7 ≤ (2*d+7)*(max widthFactor control.wordFactor+1) :=
+ Nat.le_mul_of_pos_right _ (Nat.succ_pos _)
+ unfold gramWidth at hw
+ omega
+
+variable [Fact p.Prime] [NeZero e] [Fact (Irreducible (SliceArithmetic.modulus c))]
+ [DecidableEq (AdjoinRoot (SliceArithmetic.modulus c))]
+
+/-- Column indices that form the nonsingular coordinate minor of the interpreted matrix's
+greedy row basis. -/
+abbrev cols (M : Matrix (Fin n) (Fin m) (Scalar c)) :=
+ let L := M.map (Scalar.interpretation c)
+ coordinateColumns (greedyRowBasis L) (greedyRowBasis_fullRank L)
+
+/-- Square submatrix of `D` at the greedy row and column indices chosen from the interpreted
+pivot matrix `M`. -/
+abbrev selected (M D : Matrix (Fin n) (Fin m) (Scalar c)) :=
+ D.submatrix (greedyRowIndex (M.map (Scalar.interpretation c))) (cols M)
+
+/-- Complete denominator or selected-target entry reader from the physical
+base scalar queries. Both true pivot selectors use the same live matrix. -/
+theorem restrictEntry_correctSpace (M D : Matrix (Fin n) (Fin m) (Scalar c))
+ (read : FiniteRoutine (MacaulayRead.Port K)) (entry : FiniteRoutine (MacaulayRead.Port R)) {pivot : Stacks K → Prop} {ready : Stacks R → Prop}
+ (hc : MacaulayRead.CorrectSpace read M w v B S pivot)
+ (he : MacaulayRead.CorrectSpace entry D w v E S ready)
+ (ha : ∀ s, pivot s → ∀ k, (s k).length ≤ A) (hb : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (hrSize : n+n+(n+m)*n+m+8 < 2^d) (hcSize : m+m+(m+n)*m+n+8 < 2^d)
+ (hw : gramWidth d ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (base : Stacks K) (hr : pivot base) :
+ MacaulayRead.CorrectSpace (restrictEntry read entry) (selected M D) w v (time K n m d w v e B A S E)
+ (space K d w v e A S) (Submatrix.Ready (Ready w v n m c base ready)) := by
+ let cap := space K d w v e A S
+ have hp : 2^d ≤ 2^w := Nat.pow_le_pow_right (by decide) (width_le hw)
+ have safe := ready_length (d := d) (S := S) (c := c) (v := v) base hr ha hb
+ (by omega : n < 2^w) (by omega : m < 2^w)
+ have rows := Select.row_correctSpace M read hc ha hrSize hw hv base hr
+ have columns := Select.column_correctSpace M read hc ha hcSize hw hv base hr
+ have rs := rows.onAux (ready := Ready w v n m c base ready) (A := cap) ThreeBanks.left ThreeBanks.left_injective
+ (fun _ h => ThreeBanks.project_left h) (fun _ _ h ho => ThreeBanks.preserve_left h ho) (fun s h k _ => safe s h k)
+ have cs := columns.onAux (ready := Ready w v n m c base ready) (A := cap) ThreeBanks.middle ThreeBanks.middle_injective
+ (fun _ h => ThreeBanks.project_middle h) (fun _ _ h ho => ThreeBanks.preserve_middle h ho) (fun s h k _ => safe s h k)
+ have es := he.onAux (ready := Ready w v n m c base ready) (A := cap) ThreeBanks.right ThreeBanks.right_injective
+ (fun _ h => ThreeBanks.project_right h) (fun _ _ h ho => ThreeBanks.preserve_right h ho) (fun s h k _ => safe s h k)
+ rw [max_eq_right (show Select.scanSpace K d w v e A S+OrdinalABI.overhead w ≤ cap from le_max_left ..)] at rs cs
+ rw [max_eq_right (show S ≤ cap from (le_max_left ..).trans (le_max_right ..))] at es
+ exact Submatrix.correctSpace rs cs es
+
+/-- Read a Cramer numerator entry, using the target at the selected column on the replacement
+row and the ordinary minor entry elsewhere. -/
+def numerator (read : FiniteRoutine (MacaulayRead.Port K)) (ordinary target : FiniteRoutine (MacaulayRead.Port R)) :=
+ Replacement.numerator (restrictEntry read ordinary) (restrictEntry read target)
+
+/-- The native numerator has the chosen dense row replaced by the target,
+evaluated at exactly the selected original columns. -/
+theorem numerator_correctSpace (M : Matrix (Fin n) (Fin m) (Scalar c)) (T : Fin m → Scalar c)
+ (read : FiniteRoutine (MacaulayRead.Port K)) (ordinary target : FiniteRoutine (MacaulayRead.Port R)) {pivot : Stacks K → Prop} {ready : Stacks R → Prop}
+ (hc : MacaulayRead.CorrectSpace read M w v B S pivot)
+ (ho : MacaulayRead.CorrectSpace ordinary M w v Ba S ready)
+ (ht : MacaulayRead.CorrectSpace target (fun _ j => T j : Matrix (Fin n) (Fin m) _) w v E S ready)
+ (ha : ∀ s, pivot s → ∀ k, (s k).length ≤ A) (hb : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (hrSize : n+n+(n+m)*n+m+8 < 2^d) (hcSize : m+m+(m+n)*m+n+8 < 2^d)
+ (hw : gramWidth d ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (base : Stacks K) (hr : pivot base) (i : Fin (rankQuery (M.map (Scalar.interpretation c)))) :
+ MacaulayRead.CorrectSpace (numerator read ordinary target) ((selected M M).updateRow i (T ∘ cols M)) w v
+ (20*w+10+(max (time K n m d w v e B A S Ba) (time K n m d w v e B A S E)+1))
+ (max (space K d w v e A S) (w+(20*w+10)))
+ (Replacement.Ready w i (Submatrix.Ready (Ready w v n m c base ready))) := by
+ have dn := restrictEntry_correctSpace M M read ordinary hc ho ha hb hrSize hcSize hw hv base hr
+ have tg := restrictEntry_correctSpace M _ read target hc ht ha hb hrSize hcSize hw hv base hr
+ have hn : n ≤ 2^w := (show n ≤ 2^d by omega).trans (Nat.pow_le_pow_right (by decide) (width_le hw))
+ apply Replacement.correctSpace dn tg i
+ rw [rankQuery_eq]
+ exact (by simpa using (M.map (Scalar.interpretation c)).rank_le_card_height : _ ≤ n).trans hn
+
+/-- The interpreted denominator matrix is Appendix D.2's canonical square minor. -/
+theorem selected_map (M : Matrix (Fin n) (Fin m) (Scalar c)) :
+ (selected M M).map (Scalar.interpretation c) =
+ (greedyRowBasis (M.map (Scalar.interpretation c))).submatrix id (cols M) := rfl
+
+theorem numerator_map (M : Matrix (Fin n) (Fin m) (Scalar c)) (T : Fin m → Scalar c)
+ (i : Fin (rankQuery (M.map (Scalar.interpretation c)))) :
+ ((selected M M).updateRow i (T ∘ cols M)).map (Scalar.interpretation c) =
+ replacedMinor (greedyRowBasis (M.map (Scalar.interpretation c))) (cols M) ((Scalar.interpretation c) ∘ T) i := by
+ ext j k
+ by_cases h : j = i
+ · subst j; simp [replacedMinor, Matrix.map_apply]
+ · simp only [Matrix.map_apply, replacedMinor, Matrix.updateRow_ne h]
+ rfl
+
+end SelectedMinor
+end RankQuery.Stack.Coordinate
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSelectedPrepare.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSelectedPrepare.lean
new file mode 100644
index 0000000000..34108e3a01
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSelectedPrepare.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.RankCoordinateSelectedAdvice
+import OAI.Computability.VPVNP.RankCoordinatePrepare
+
+/-! # Complete preparation of the two determinant queries
+
+The evaluator's two public ordinals determine the source monomial and the
+replacement row. The fixed label and Frobenius routines start with the same
+advice. Their bounded executions supply the canonical input to each Schur
+root for the live operation and pair of ordinals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace RankQuery.Stack.Coordinate.SelectedAdvice
+
+open RAMTape UniversalCountStack BurstRAM SliceArithmetic Cursor Dispatch NativeReader
+open RadicalCertificate.MonomialIndex QueryData SliceMinors
+
+variable {K F : Type} {p e t eqs d w v A S P B : ℕ}
+
+/-- Selects the Frobenius preparation routine on a Frobenius step and the label routine on a
+label step. -/
+def mode : Operation t → Bool | .label _ => false | .frobenius => true
+/-- The zero-based variable index for a label step, with zero as the unary input for a
+Frobenius step. -/
+def label : Operation t → ℕ | .label j => j | .frobenius => 0
+
+private theorem scale_eq (Q : QueryData t eqs F) (op : Operation t) :
+ powers Q (mode op) = PairCall.targetScale Q op := by cases op <;> rfl
+
+private theorem mark_eq (op : Operation t) :
+ (if mode op then 0 else label op+1) = PairCall.targetMark op := by cases op <;> rfl
+
+private theorem label_le (op : Operation t) : label op ≤ t := by
+ cases op with
+ | label j => exact j.isLt.le
+ | frobenius => exact Nat.zero_le _
+
+variable [DecidableEq K] [Fintype K]
+
+/-- Compares prefix-rank ports through the underlying Gram scan's register and auxiliary port
+tags. -/
+local instance : DecidableEq (PrefixPort K) := inferInstanceAs (DecidableEq (ScanPort (GramEngine.Aux K)))
+/-- Decides equality of the auxiliary ports used to call the prefix-rank machine. -/
+local instance : DecidableEq (PrefixWorkspace.Aux (PrefixPort K)) := fun a b => PrefixWorkspace.instDecidableEqAux a b
+/-- Distinguishes the word registers and auxiliary ports of the greedy selector workspace. -/
+local instance : DecidableEq (Side K) := inferInstanceAs (DecidableEq (PrefixWords.Port (PrefixWorkspace.Aux (PrefixPort K))))
+/-- Compares addresses in the row scan, column scan and direct entry reader of a selected
+minor. -/
+local instance {J : Type} [DecidableEq J] : DecidableEq (SelectedMinor.Host K J) :=
+ inferInstanceAs (DecidableEq (Side K ⊕ (Side K ⊕ J)))
+/-- Decides equality of the selected row word, selected column word and auxiliary addresses in
+the denominator bank. -/
+local instance : DecidableEq (Den K) := fun a b => Submatrix.instDecidableEqWork a b
+
+/-- Compares ports of the determinant, ordinal and unary-label preparation components. -/
+local instance : DecidableEq (Parts K) := Prepare.partsDecidable
+/-- Compares an advice address by its component port or its Boolean scale selector. -/
+local instance : DecidableEq (Advice K) := inferInstanceAs (DecidableEq (Parts K ⊕ Bool))
+/-- Distinguishes the writable component addresses from the shared temporary stack. -/
+local instance : DecidableEq (Work K) := inferInstanceAs (DecidableEq (Parts K ⊕ Unit))
+/-- Decides equality of public reader ports and their private advice or working addresses. -/
+local instance : DecidableEq (Prepare.Ports (Den K) (Raw K) (Side K)) :=
+ inferInstanceAs (DecidableEq (Reader.Port (Advice K ⊕ Work K)))
+
+variable [Fintype (Parts K)]
+
+/-- Prepares the determinant pair by reading the greedy row ordinal and staging the selected
+target arguments for the given operation mode. -/
+def machine (read : FiniteRoutine (MacaulayRead.Port K)) (b : Bool) : FiniteRoutine (Prepare.Ports (Den K) (Raw K) (Side K)) :=
+ Prepare.machine (OrdinalABI.machine (Select.rows read)) (ArgumentStage.selectedSlot (K := K) (Base := K)) b (D := Den K)
+
+variable [Field F] [DecidableEq F] [Fact p.Prime]
+
+/-- Numerator bank for one live query, with the next coordinate as replacement row and the
+current coordinate as source of the powered target. -/
+def numAt (c : Vector p e) (Q : QueryData t eqs F) (w v : ℕ) (base : Stacks K)
+ (op : Operation t) (cur next : Fin Q.dimension) : Stacks (ArgumentStage.Num (Raw K)) :=
+ Replacement.workBank w (digits w (combinedOrdinal Q.equations Q.monomials next)) (Submatrix.workBank [] []
+ (ArgumentStage.selectedRaw w v (height Q) (width Q) c base base (targetArgs Q op cur) (TargetRead.literal c v)))
+
+omit [Fintype K] [Fintype (Parts K)] in
+theorem prepared_root_ready (c : Vector p e) (Q : QueryData t eqs F) (base : Stacks K)
+ {ready : Stacks K → Prop} (hr : ready base) (hn : height Q < 2^w)
+ (op : Operation t) (cur next : Fin Q.dimension) :
+ let denReady := Submatrix.Ready (SelectedMinor.Ready w v (height Q) (width Q) c base ready)
+ let numReady := Replacement.Ready w (combinedOrdinal Q.equations Q.monomials next)
+ (Submatrix.Ready (SelectedMinor.Ready w v (height Q) (width Q) c base (directReady c w v (targetArgs Q op cur) ready)))
+ GramEngine.Ready w v (order Q) (order Q) c denReady (GramEngine.initial w v (order Q) (order Q) c (den c Q w v base)) ∧
+ GramEngine.Ready w v (order Q) (order Q) c numReady (GramEngine.initial w v (order Q) (order Q) c (numAt c Q w v base op cur next)) :=
+ ArgumentStage.selected_root_ready w v (height Q) (width Q) (order Q) c (order_lt Q hn) (den c Q w v base)
+ ⟨_, SelectedMinor.initial_ready base base hr, rfl⟩ base base hr (targetTemplate Q)
+ (combinedOrdinal Q.equations Q.monomials next) (Q.basisIndex cur) (PairCall.targetScale Q op) (PairCall.targetMark op)
+
+variable [NeZero e] [Algebra (ZMod p) F] {c : Vector p e} [Fact (Irreducible (modulus c))]
+ [DecidableEq (AdjoinRoot (modulus c))]
+
+/-- Runtime preparation from a reader for the original Macaulay relation
+matrix. The returned host and the two original public ordinal words meet
+the determinant caller's ABI. -/
+theorem prepare_bounded (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (Q : QueryData t eqs F)
+ (op : Operation t) (cur next : Fin Q.dimension) (read : FiniteRoutine (MacaulayRead.Port K))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read (baseMatrix φ Q) w v B S ready)
+ (ha : ∀ a, ready a → ∀ k, (a k).length ≤ A) (base : Stacks K) (hr : ready base)
+ (hrSize : height Q+height Q+(height Q+width Q)*height Q+width Q+8 < 2^d)
+ (hw : gramWidth d ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (hword : w ≤ P) (harity : t ≤ P) (hscalar : max P (e*v) ≤ A) (hlabel : label op+1 < 2^w) :
+ let M := portBound K d w v e A S
+ let R := Select.scanTime K (height Q) d w v e B A S + OrdinalABI.overhead w
+ let S₀ := selectorCap K d w v e A S
+ let lim := Prepare.peak (Parts K) M (max M t) S₀ (label op) w
+ ∃ ticks ≤ Prepare.time (Parts K) (mode op) M R (label op) w, ∃ out : Stacks (Work K),
+ out Prepare.scratch = [] ∧
+ (∀ i, out (Prepare.root i) = RootInit.template c (order Q) w v (den c Q w v base) (numAt c Q w v base op cur next) i) ∧
+ (machine read (mode op)).BoundedRun lim ticks
+ (state (List.replicate (label op) true) (digits w cur) (digits w next) [] (selectedAdvice c Q w v base) (fun _ => []))
+ (state (List.replicate (label op) true) (digits w cur) (digits w next) [] (selectedAdvice c Q w v base) out) := by
+ intro M R S₀ lim
+ have hdw : d ≤ w := by
+ have hh : 2*d+7 ≤ (2*d+7)*(max widthFactor control.wordFactor+1) :=
+ Nat.le_mul_of_pos_right _ (Nat.succ_pos _)
+ unfold gramWidth at hw
+ omega
+ have pfit := Nat.pow_le_pow_right (by decide : 0 < 2) hdw
+ have hn : height Q < 2^w := by omega
+ have hm : width Q < 2^w := by omega
+ have selector := (Select.row_correctSpace (baseMatrix φ Q) read hc ha hrSize hw hv base hr).castOrdinal
+ (interpretedRank φ Q) (interpretedRow φ Q)
+ have widthSide : w ≤ S₀ := (Nat.le_add_right w _).trans ((le_max_left ..).trans (Nat.le_add_right ..))
+ obtain ⟨hf₁,hf₂,hf₃,hf₄⟩ := fit (d := d) (S := S) c Q base (ha base hr) hn hm hword harity hscalar hv (label op) cur next
+ have ambient : max (label op) M ≤ max M t := max_le ((label_le op).trans (le_max_right ..)) (le_max_left ..)
+ obtain ⟨u,hu,out,scratch,hroot,run⟩ := Prepare.machine_bounded (M := M) (A := max M t) Q.equations Q.monomials cur next
+ (label op) (mode op) (powers Q) c (order Q) (den c Q w v base) (raw c Q w v base) ArgumentStage.selectedSlot
+ (OrdinalABI.machine (Select.rows read)) selector widthSide hn
+ (fun s hs => hs ▸ side_length (d := d) (S := S) c Q base (ha base hr) hm) (side c Q w v base) rfl hlabel
+ (digits w 0) (length_digits w 0).le (fun i => by fin_cases i <;> exact (length_digits w _).le)
+ hf₁ hf₂ hf₃ (fun k => (hf₄ k).trans ambient)
+ refine ⟨u,hu,out,scratch,?_,run⟩
+ intro i
+ rw [hroot]
+ unfold raw numAt
+ rw [ArgumentStage.selected_after, scale_eq, mark_eq]
+ rfl
+
+end RankQuery.Stack.Coordinate.SelectedAdvice
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSliceFieldEquiv.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSliceFieldEquiv.lean
new file mode 100644
index 0000000000..a3046d16b6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSliceFieldEquiv.lean
@@ -0,0 +1,117 @@
+import OAI.Computability.VPVNP.RankCoordinateFieldEquiv
+import OAI.Computability.VPVNP.RankCoordinateSliceMinors
+import OAI.Computability.VPVNP.RankCoordinateSelectedMinor
+
+/-!
+# Identifying the native and advised index sets of the slice minors
+
+The native rank code selects rows and columns after interpreting packed
+scalars in the polynomial-basis extension. The query data selects them in
+the advised field. The field isomorphism identifies both sets, including
+the dense ordinal of the row replaced in the numerator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+open RAMTape
+
+theorem OrdinalRead.CorrectSpace.castOrdinal {K : Type} [DecidableEq K] {r' r n w B S : ℕ}
+ {read : FiniteRoutine (OrdinalRead.Port K)} {f : Fin r' → Fin n} {g : Fin r → Fin n} {ready : Stacks K → Prop}
+ (hread : OrdinalRead.CorrectSpace read f w B S ready) (eq : r' = r) (hf : ∀ i, f i = g (Fin.cast eq i)) :
+ OrdinalRead.CorrectSpace read g w B S ready := by
+ subst r'
+ exact (show f = g from funext hf) ▸ hread
+
+theorem MacaulayRead.CorrectSpace.castSquare {K : Type} [DecidableEq K] {r' r w v B S p e : ℕ}
+ {c : SliceArithmetic.Vector p e} {read : FiniteRoutine (MacaulayRead.Port K)} {ready : Stacks K → Prop}
+ {N : Matrix (Fin r') (Fin r') (Scalar c)} {M : Matrix (Fin r) (Fin r) (Scalar c)}
+ (hread : MacaulayRead.CorrectSpace read N w v B S ready) (eq : r' = r)
+ (hN : ∀ i j, N i j = M (Fin.cast eq i) (Fin.cast eq j)) :
+ MacaulayRead.CorrectSpace read M w v B S ready := by
+ subst r'
+ exact (show N = M from Matrix.ext hN) ▸ hread
+
+private theorem row_eq_of_map_eq {L F : Type*} [Field L] [Field F] [DecidableEq L] [DecidableEq F] {n m : ℕ}
+ (φ : L ≃+* F) (M : Matrix (Fin n) (Fin m) L) (N : Matrix (Fin n) (Fin m) F)
+ (h : N = M.map φ) (hr : rankQuery N = rankQuery M) (i : Fin (rankQuery N)) :
+ greedyRowIndex N i = greedyRowIndex M (Fin.cast hr i) := by
+ subst N
+ exact greedyRowIndex_map φ M i
+
+private theorem col_eq_of_map_eq {L F : Type*} [Field L] [Field F] [DecidableEq L] [DecidableEq F] {n m : ℕ}
+ (φ : L ≃+* F) (M : Matrix (Fin n) (Fin m) L) (N : Matrix (Fin n) (Fin m) F)
+ (h : N = M.map φ) (hr : rankQuery N = rankQuery M) (i : Fin (rankQuery N)) :
+ coordinateColumns (greedyRowBasis N) (greedyRowBasis_fullRank N) i =
+ coordinateColumns (greedyRowBasis M) (greedyRowBasis_fullRank M) (Fin.cast hr i) := by
+ subst N
+ exact greedyColumns_map φ M i
+
+namespace Coordinate.SliceMinors
+
+open SliceArithmetic RadicalCertificate.MonomialIndex RadicalCertificate.MonomialIndex.QueryData
+
+variable {F : Type} [Field F] [DecidableEq F] {p e t eqs : ℕ} [Fact p.Prime] [NeZero e]
+ [Algebra (ZMod p) F] {c : Vector p e} [Fact (Irreducible (modulus c))]
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (data : QueryData t eqs F)
+
+/-- The encoded base matrix after interpreting each scalar in the polynomial extension field. -/
+noncomputable abbrev interpretedMatrix := (baseMatrix φ data).map (Scalar.interpretation c)
+
+omit [DecidableEq F] in
+/-- Reading the physical scalar followed by its ring interpretation produces
+the inverse image of the queried matrix entry in the advised field. -/
+theorem interpretedMatrix_eq : interpretedMatrix φ data = (fieldMatrix data).map φ.symm := by
+ ext i j
+ apply φ.injective
+ exact (decode_encode φ ((fieldMatrix data) i j)).trans (φ.apply_symm_apply _).symm
+
+variable [DecidableEq (AdjoinRoot (modulus c))]
+
+theorem interpretedRank : rankQuery (interpretedMatrix φ data) = rankQuery (fieldMatrix data) := by
+ rw [interpretedMatrix_eq]
+ exact rankQuery_map_eq φ.symm.toRingEquiv _
+
+theorem interpretedRow (i : Fin (rankQuery (interpretedMatrix φ data))) :
+ greedyRowIndex (interpretedMatrix φ data) i = row data (Fin.cast (interpretedRank φ data) i) :=
+ row_eq_of_map_eq φ.symm.toRingEquiv _ _ (interpretedMatrix_eq φ data) (interpretedRank φ data) i
+
+theorem interpretedCol (i : Fin (rankQuery (interpretedMatrix φ data))) :
+ SelectedMinor.cols (baseMatrix φ data) i = col data (Fin.cast (interpretedRank φ data) i) :=
+ col_eq_of_map_eq φ.symm.toRingEquiv _ _ (interpretedMatrix_eq φ data) (interpretedRank φ data) i
+
+/-- The next quotient coordinate's ordinal among all greedy basis rows, cast to the rank
+computed over the extension field. -/
+noncomputable abbrev nativeOrdinal (next : Fin data.dimension) :=
+ Fin.cast (interpretedRank φ data).symm (combinedOrdinal data.equations data.monomials next)
+
+theorem denominator_cast_apply (i j : Fin (rankQuery (interpretedMatrix φ data))) :
+ SelectedMinor.selected (baseMatrix φ data) (baseMatrix φ data) i j =
+ denominator φ data (Fin.cast (interpretedRank φ data) i) (Fin.cast (interpretedRank φ data) j) := by
+ change baseMatrix φ data (greedyRowIndex (interpretedMatrix φ data) i) (SelectedMinor.cols (baseMatrix φ data) j) =
+ baseMatrix φ data _ _
+ rw [interpretedRow, interpretedCol]
+
+theorem numerator_cast_apply (op : Operation t) (current next : Fin data.dimension)
+ (i j : Fin (rankQuery (interpretedMatrix φ data))) :
+ ((SelectedMinor.selected (baseMatrix φ data) (baseMatrix φ data)).updateRow (nativeOrdinal φ data next)
+ (target φ data op current ∘ SelectedMinor.cols (baseMatrix φ data))) i j =
+ numerator φ data op current next (Fin.cast (interpretedRank φ data) i) (Fin.cast (interpretedRank φ data) j) := by
+ by_cases hi : i = nativeOrdinal φ data next
+ · subst i
+ simp only [numerator, nativeOrdinal, Fin.cast_cast, Fin.cast_refl, id_eq, Matrix.updateRow_self, Function.comp_apply]
+ rw [interpretedCol]
+ · have hfield : Fin.cast (interpretedRank φ data) i ≠ combinedOrdinal data.equations data.monomials next :=
+ fun h => hi (Fin.ext (congrArg (fun i : Fin (rankQuery (fieldMatrix data)) => i.val) h))
+ simp only [numerator, Matrix.updateRow_ne hi, Matrix.updateRow_ne hfield]
+ exact denominator_cast_apply φ data i j
+
+end Coordinate.SliceMinors
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSliceMinors.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSliceMinors.lean
new file mode 100644
index 0000000000..15bde8f940
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSliceMinors.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.RankCoordinateSliceReader
+import OAI.Computability.VPVNP.RankCoordinateReplacement
+
+/-! # Encoded entries and selected minors of a slice coordinate query -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.SliceMinors
+
+open SliceArithmetic RadicalCertificate.MonomialIndex RadicalCertificate.MonomialIndex.QueryData
+open FiniteSlice RAMTape
+
+variable {F : Type} [Field F] [DecidableEq F] {p e t eqs : ℕ} [Fact p.Prime] [NeZero e]
+ [Algebra (ZMod p) F] {c : Vector p e} [Fact (Irreducible (modulus c))]
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (data : QueryData t eqs F)
+
+/-- Packs the extension-field coordinates of a field element into the scalar representation
+used by the entry reader. -/
+noncomputable def encode (x : F) : Scalar c := Scalar.pack c (scalarEncoding φ x)
+
+omit [DecidableEq F] in
+theorem decode_encode (x : F) : (φ.toRingEquiv.toRingHom.comp (Scalar.interpretation c)) (encode φ x) = x := by
+ change φ (value (modulus c) (Scalar.pack c (scalarEncoding φ x)).digits) = _
+ rw [Scalar.digits_pack,map_scalarEncoding]
+
+/-- The Macaulay relation matrix with the monomial rows appended below the equation rows. -/
+abbrev fieldMatrix := appendRows data.equations data.monomials
+/-- Original row indices selected by the greedy independent-row scan of the appended matrix. -/
+abbrev row := greedyRowIndex (fieldMatrix data)
+/-- Original column indices forming the invertible coordinate minor of the greedy row basis. -/
+abbrev col := coordinateColumns (greedyRowBasis (fieldMatrix data)) (greedyRowBasis_fullRank _)
+
+/-- The appended matrix with every field entry packed as a scalar for the native reader. -/
+noncomputable def baseMatrix := (fieldMatrix data).map (encode φ)
+/-- The square Cramer denominator formed by restricting the encoded matrix to the chosen
+independent rows and columns. -/
+noncomputable def denominator := (baseMatrix φ data).submatrix (row data) (col data)
+/-- The encoded target row for applying the given operation at one quotient-basis coordinate. -/
+noncomputable def target (op : Operation t) (i : Fin data.dimension) := encode φ ∘ data.stepTarget op i
+/-- The denominator minor with the row for the next coordinate replaced by the current target
+on the selected columns. -/
+noncomputable def numerator (op : Operation t) (i j : Fin data.dimension) :=
+ (denominator φ data).updateRow (combinedOrdinal data.equations data.monomials j) (target φ data op i ∘ col data)
+
+theorem denominator_map : (denominator φ data).map (φ.toRingEquiv.toRingHom.comp (Scalar.interpretation c)) =
+ (greedyRowBasis (fieldMatrix data)).submatrix id (col data) := by
+ ext i j; exact decode_encode φ _
+
+theorem numerator_map (op : Operation t) (i j : Fin data.dimension) :
+ (numerator φ data op i j).map (φ.toRingEquiv.toRingHom.comp (Scalar.interpretation c)) =
+ replacedMinor (greedyRowBasis (fieldMatrix data)) (col data) (data.stepTarget op i)
+ (combinedOrdinal data.equations data.monomials j) := by
+ ext x y
+ by_cases h : x = combinedOrdinal data.equations data.monomials j
+ · subst x; simp [numerator,replacedMinor,target]; exact decode_encode φ _
+ · simp [numerator,replacedMinor,h,Matrix.map_apply]
+ exact decode_encode φ _
+
+variable {K : Type} [DecidableEq K] {w v Br Bc Ba Bt S : ℕ}
+ {rows cols : FiniteRoutine (OrdinalRead.Port K)} {scalar power : FiniteRoutine (MacaulayRead.Port K)}
+ {ready : Stacks K → Prop}
+
+omit [NeZero e] in
+/-- The two scalar matrices consumed by the determinant roots are built from
+the selected row and column addresses of the full indexed equation matrix. -/
+theorem reads (op : Operation t) (i j : Fin data.dimension)
+ (hr : OrdinalRead.CorrectSpace rows (row data) w Br S ready)
+ (hc : OrdinalRead.CorrectSpace cols (col data) w Bc S ready)
+ (ha : MacaulayRead.CorrectSpace scalar (baseMatrix φ data) w v Ba S ready)
+ (ht : MacaulayRead.CorrectSpace power (fun _ j => target φ data op i j :
+ Matrix (Fin (eqs * size t data.multiplierDegree + size t data.pointBound)) (Fin (size t data.columnDegree)) _) w v Bt S ready)
+ (hfit : NativeReader.order data ≤ 2^w) :
+ MacaulayRead.CorrectSpace (Submatrix.minorRead rows cols scalar) (denominator φ data) w v
+ (Br+Bc+Ba+2*(w+1)) S (Submatrix.Ready ready) ∧
+ MacaulayRead.CorrectSpace (Replacement.numerator (Submatrix.minorRead rows cols scalar) (Submatrix.minorRead rows cols power))
+ (numerator φ data op i j) w v (20*w+10+(max (Br+Bc+Ba+2*(w+1)) (Br+Bc+Bt+2*(w+1))+1))
+ (max S (w+(20*w+10))) (Replacement.Ready w (combinedOrdinal data.equations data.monomials j) (Submatrix.Ready ready)) := by
+ exact ⟨Submatrix.correctSpace hr hc ha, Replacement.submatrix_correctSpace hr hc ha ht _ hfit⟩
+
+end RankQuery.Stack.Coordinate.SliceMinors
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSliceReader.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSliceReader.lean
new file mode 100644
index 0000000000..e8efbec68f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSliceReader.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.VPVNP.RankCoordinatePairReader
+
+/-! # Native Cramer reader for a finite reduced slice algebra
+
+The varying data are the replacement row and target monomial for a particular
+pair of basis ordinals. The two determinant tables and the enclosing reader
+are fixed throughout the quantification over both ordinals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.NativeReader
+
+open FiniteSlice RadicalCertificate.MonomialIndex RadicalCertificate.MonomialIndex.QueryData
+open RAMTape Evaluator Evaluator.MatrixCallbacks SliceArithmetic Dispatch Cramer
+
+variable {F : Type} [Field F] [DecidableEq F] {p e : ℕ} [Fact p.Prime] [NeZero e]
+ [Algebra (ZMod p) F] {c : Vector p e} [Fact (Irreducible (modulus c))]
+ {A H K L : Type} [DecidableEq A] [DecidableEq H] [Fintype H] [DecidableEq K] [DecidableEq L]
+ {t eqs addr v iw B S V peak prep : ℕ}
+
+/-- The rank of the appended equation and monomial rows, hence the common order of both Cramer
+minors. -/
+abbrev order (S : QueryData t eqs F) := rankQuery (appendRows S.equations S.monomials)
+
+/-- Data presented by the rank selectors and root initializer for one live
+query. Both matrix readers have the same physical ABI as the determinant. -/
+structure Staged (data : QueryData t eqs F) (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (op : Operation t)
+ (dim : BurstRAM.Word iw) (hdim : dim.val = data.dimension) (label : ℕ)
+ (host : PairedHost K L ↪ H) (scratch : H) (advice : Stacks A)
+ (prepare : FiniteRoutine (Bus A H)) (den : FiniteRoutine (MacaulayRead.Port K))
+ (num : FiniteRoutine (MacaulayRead.Port L)) (addr v B S V peak prep : ℕ) (i j : Fin dim.val) where
+ /-- The encoded square matrix whose determinant is the denominator for this coordinate query. -/
+ denominator : Matrix (Fin (order data)) (Fin (order data)) (Scalar c)
+ /-- The encoded square matrix with the selected row replaced by the operation's target row. -/
+ numerator : Matrix (Fin (order data)) (Fin (order data)) (Scalar c)
+ denMatrix : denominator.map (φ.toRingEquiv.toRingHom.comp (Scalar.interpretation c)) =
+ (greedyRowBasis (appendRows data.equations data.monomials)).submatrix id (coordinateColumns _ (greedyRowBasis_fullRank _))
+ numMatrix : numerator.map (φ.toRingEquiv.toRingHom.comp (Scalar.interpretation c)) =
+ replacedMinor (greedyRowBasis (appendRows data.equations data.monomials)) (coordinateColumns _ (greedyRowBasis_fullRank _))
+ (data.stepTarget op (Fin.cast hdim i)) (combinedOrdinal data.equations data.monomials (Fin.cast hdim j))
+ /-- Condition on the auxiliary stacks from which the denominator entry routine can run. -/
+ denReady : Stacks K → Prop
+ /-- Condition on the auxiliary stacks from which the numerator entry routine can run. -/
+ numReady : Stacks L → Prop
+ denReads : MacaulayRead.CorrectSpace den denominator addr v B S denReady
+ numReads : MacaulayRead.CorrectSpace num numerator addr v B S numReady
+ denBound : ∀ a, denReady a → ∀ k, (a k).length ≤ V
+ numBound : ∀ a, numReady a → ∀ k, (a k).length ≤ V
+ /-- Private host stacks after preparation, containing both determinant inputs and the
+ arithmetic frame. -/
+ work : Stacks H
+ scratchEmpty : work scratch = []
+ /-- Auxiliary Gram-engine stacks prepared for the denominator matrix. -/
+ denAux : Stacks (GramEngine.Aux K)
+ /-- Auxiliary Gram-engine stacks prepared for the numerator matrix with its replacement row. -/
+ numAux : Stacks (GramEngine.Aux L)
+ denInput : GramEngine.Ready addr v (order data) (order data) c denReady denAux
+ numInput : GramEngine.Ready addr v (order data) (order data) c numReady numAux
+ hostInput : ∀ k, work (host k) = SchurPair.host (SchurPair.entryBank c (order data) addr v denAux)
+ (SchurPair.entryBank c (order data) addr v numAux) (frame p e v (digits v c) [] [] []) k
+ /-- Number of machine ticks taken to prepare the two determinant inputs for this live query. -/
+ ticks : ℕ
+ clock : ticks ≤ prep
+ run : prepare.BoundedRun peak ticks
+ (state (List.replicate label true) (Reader.ordinal dim i) (Reader.ordinal dim j) [] advice (fun _ => []))
+ (state (List.replicate label true) (Reader.ordinal dim i) (Reader.ordinal dim j) [] advice work)
+
+/-- The native core returns the next-coordinate scalar for either operation. -/
+theorem core_step (data : QueryData t eqs F)
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (dim : BurstRAM.Word iw) (hdim : dim.val = data.dimension)
+ (op : Operation t) (label : ℕ) (host : PairedHost K L ↪ H) (scratch : H) (disjoint : ∀ i, host i ≠ scratch)
+ (advice : Stacks A) (prepare : FiniteRoutine (Bus A H)) (den : FiniteRoutine (MacaulayRead.Port K))
+ (num : FiniteRoutine (MacaulayRead.Port L)) {d s : ℕ}
+ (hv : Word.workingWidth p ≤ v) (hw₃ : 3 ≤ addr) (hw : (d+1)*widthFactor ≤ addr) (hd : d ≤ addr)
+ (hsize : order data+order data+0+order data+8 < 2^d)
+ (hn : order data ≤ 2^s) (hs : 2*s+6 ≤ addr) (hws : (2*s+6+1)*widthFactor ≤ addr)
+ (hquery : PlainEngine.querySpace (order data) addr v e V S ≤ peak) (hroom : (e+1)*(v+1)+divideClock e v ≤ peak)
+ (staged : ∀ i j, Nonempty (Staged data φ op dim hdim label host scratch advice prepare den num addr v B S V peak prep i j)) :
+ ∀ i j : Fin dim.val, ∃ u ≤ pairTime H prep (order data) addr v e B peak, ∃ a : Vector p e,
+ φ (value (modulus c) a) = data.stepCoordinate op (Fin.cast hdim i) (Fin.cast hdim j) ∧
+ (pairCore host scratch prepare den num).BoundedRun (peak+returnClock H peak) u
+ (state (List.replicate label true) (Reader.ordinal dim i) (Reader.ordinal dim j) [] advice (fun _ : H => []))
+ (state (List.replicate label true) (Reader.ordinal dim i) (Reader.ordinal dim j) (digits v a) advice (fun _ : H => [])) := by
+ intro i j
+ obtain ⟨st⟩ := staged i j
+ obtain ⟨u,hu,run⟩ := pairCore_bounded host scratch disjoint prepare den num st.denominator st.numerator
+ st.denReads st.numReads st.denBound st.numBound hv hw₃ hw hd hsize hn hs hws hquery hroom
+ (List.replicate label true) (Reader.ordinal dim i) (Reader.ordinal dim j) advice st.work st.scratchEmpty
+ st.denAux st.numAux st.denInput st.numInput st.hostInput st.run
+ refine ⟨u,hu.trans ?_,minorQuotient c st.numerator st.denominator,?_,run⟩
+ · unfold pairTime; have := st.clock; omega
+ · exact data.minorQuotient_eq_stepCoordinate c φ op _ _ st.numerator st.denominator st.numMatrix st.denMatrix
+
+variable [Fintype F] {E : Type*} [Field E] [Algebra F E] [IsAlgClosed E]
+
+theorem slice_reader (data : QueryData t eqs F) (sys : Fin eqs → MvPolynomial (Fin t) F) (h : data.Presents sys)
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (dim : BurstRAM.Word iw) (hdim : dim.val = data.dimension)
+ (basis : Module.Basis (Fin dim.val) F (CoordinateAlgebra F (points sys E)))
+ (hb : ∀ i, basis i = data.listing sys E (data.basisIndex (Fin.cast hdim i)))
+ (op : Operation t) (label : ℕ) (host : PairedHost K L ↪ H) (scratch : H) (disjoint : ∀ i, host i ≠ scratch)
+ (advice : Stacks A) (prepare : FiniteRoutine (Bus A H)) (den : FiniteRoutine (MacaulayRead.Port K))
+ (num : FiniteRoutine (MacaulayRead.Port L)) {d s : ℕ}
+ (hv : Word.workingWidth p ≤ v) (hw₃ : 3 ≤ addr) (hw : (d+1)*widthFactor ≤ addr) (hd : d ≤ addr)
+ (hsize : order data+order data+0+order data+8 < 2^d)
+ (hn : order data ≤ 2^s) (hs : 2*s+6 ≤ addr) (hws : (2*s+6+1)*widthFactor ≤ addr)
+ (hquery : PlainEngine.querySpace (order data) addr v e V S ≤ peak) (hroom : (e+1)*(v+1)+divideClock e v ≤ peak)
+ (staged : ∀ i j, Nonempty (Staged data φ op dim hdim label host scratch advice prepare den num addr v B S V peak prep i j)) :
+ ReadsEntryWithin φ dim (Sum.elim advice (fun _ : H => [])) (Reader.install (pairCore host scratch prepare den num))
+ v label (pairTime H prep (order data) addr v e B peak)
+ (max (peak+returnClock H peak) (Reader.callerPeak iw e v))
+ ((LinearMap.toMatrixAlgEquiv basis) (op.linearAction (coordinateLabel (points sys E)))).transpose := by
+ apply Reader.readsEntryWithin_of_suffix φ dim _ data sys h hdim basis hb op
+ exact core_step data φ dim hdim op label host scratch disjoint advice prepare den num hv hw₃ hw hd hsize hn hs hws hquery hroom staged
+
+omit [Fintype F] in
+/-- Entrywise form used directly by the evaluator's two callback contracts. -/
+theorem entry_reader (data : QueryData t eqs F)
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (dim : BurstRAM.Word iw) (hdim : dim.val = data.dimension)
+ (op : Operation t) (label : ℕ) (host : PairedHost K L ↪ H) (scratch : H) (disjoint : ∀ i, host i ≠ scratch)
+ (advice : Stacks A) (prepare : FiniteRoutine (Bus A H)) (den : FiniteRoutine (MacaulayRead.Port K))
+ (num : FiniteRoutine (MacaulayRead.Port L)) {d s : ℕ}
+ (hv : Word.workingWidth p ≤ v) (hw₃ : 3 ≤ addr) (hw : (d+1)*widthFactor ≤ addr) (hd : d ≤ addr)
+ (hsize : order data+order data+0+order data+8 < 2^d)
+ (hn : order data ≤ 2^s) (hs : 2*s+6 ≤ addr) (hws : (2*s+6+1)*widthFactor ≤ addr)
+ (hquery : PlainEngine.querySpace (order data) addr v e V S ≤ peak) (hroom : (e+1)*(v+1)+divideClock e v ≤ peak)
+ (staged : ∀ i j, Nonempty (Staged data φ op dim hdim label host scratch advice prepare den num addr v B S V peak prep i j)) :
+ ReadsEntryWithin φ dim (Sum.elim advice (fun _ : H => [])) (Reader.install (pairCore host scratch prepare den num))
+ v label (pairTime H prep (order data) addr v e B peak) (max (peak+returnClock H peak) (Reader.callerPeak iw e v))
+ (fun i j => data.matrixEntry op (Fin.cast hdim j) (Fin.cast hdim i)) := by
+ apply Reader.readsEntryWithin
+ intro i j
+ obtain ⟨u,hu,a,ha,run⟩ := core_step data φ dim hdim op label host scratch disjoint advice prepare den num hv hw₃ hw hd hsize hn hs hws hquery hroom staged i j
+ have hz : φ (value (modulus c) a) = data.matrixEntry op (Fin.cast hdim j) (Fin.cast hdim i) :=
+ ha.trans (data.matrixEntry_eq_greedyCoordinate op _ _).symm
+ have eq := (valueEquiv c).injective (φ.injective (hz.trans (map_scalarEncoding φ _).symm))
+ rw [eq] at run; exact ⟨u,hu,run⟩
+
+end RankQuery.Stack.Coordinate.NativeReader
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSliceSelection.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSliceSelection.lean
new file mode 100644
index 0000000000..20994c3e71
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSliceSelection.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.RankCoordinateSliceFieldEquiv
+
+/-! # Greedy minor readers for a live finite-slice query
+
+The two pivot templates depend only on the base relation matrix. The
+numerator has a separate direct reader bank for the currently staged
+powered monomial and the replacement row. Both physical readers use the
+same clock and stack cap expected by the paired determinant machine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace RankQuery.Stack
+
+open RAMTape
+
+theorem MacaulayRead.CorrectSpace.enlarge {K : Type} [DecidableEq K] {p e n m w v B B' S S' : ℕ}
+ {c : SliceArithmetic.Vector p e} {read : FiniteRoutine (MacaulayRead.Port K)}
+ {M : Matrix (Fin n) (Fin m) (Scalar c)} {ready : Stacks K → Prop}
+ (h : MacaulayRead.CorrectSpace read M w v B S ready) (hb : B ≤ B') (hs : S ≤ S') :
+ MacaulayRead.CorrectSpace read M w v B' S' ready := by
+ intro i j s hr
+ obtain ⟨u,hu,o,ho,run⟩ := h i j s hr
+ exact ⟨u,hu.trans hb,o,ho,run.enlarge hs⟩
+
+namespace Coordinate.SliceMinors
+
+open SliceArithmetic RadicalCertificate.MonomialIndex RadicalCertificate.MonomialIndex.QueryData
+open FiniteSlice BurstRAM Dispatch Cursor
+
+variable {F : Type} [Field F] [DecidableEq F] {p e t eqs : ℕ} [Fact p.Prime] [NeZero e]
+ [Algebra (ZMod p) F] {c : Vector p e} [Fact (Irreducible (modulus c))]
+ [DecidableEq (AdjoinRoot (modulus c))]
+ {K D R : Type} [Fintype K] [DecidableEq K] [DecidableEq D] [DecidableEq R]
+ {d w v B Ba Bt S A : ℕ}
+
+/-- Compares the ports of a prefix-rank call using the underlying Gram-scan address type. -/
+local instance : DecidableEq (PrefixPort K) := inferInstanceAs (DecidableEq (ScanPort (GramEngine.Aux K)))
+/-- Decides equality of auxiliary addresses in the greedy prefix scanner. -/
+local instance : DecidableEq (PrefixWorkspace.Aux (PrefixPort K)) := fun a b => PrefixWorkspace.instDecidableEqAux a b
+/-- Compares the register and auxiliary addresses of a row or column selector. -/
+local instance : DecidableEq (Select.Side K) := inferInstanceAs (DecidableEq (PrefixWords.Port (PrefixWorkspace.Aux (PrefixPort K))))
+
+/-- Distinguishes the two selector banks and the direct entry reader inside a selected minor. -/
+local instance {J : Type} [DecidableEq J] : DecidableEq (SelectedMinor.Host K J) :=
+ inferInstanceAs (DecidableEq (Select.Side K ⊕ (Select.Side K ⊕ J)))
+/-- Compares the selected row word, column word and remaining selected-minor workspace
+addresses. -/
+local instance {J : Type} [DecidableEq J] : DecidableEq (SelectedMinor.Work K J) := fun a b => Submatrix.instDecidableEqWork a b
+
+/-- Row count of the appended matrix, comprising equation multiples and monomials up to the
+point bound. -/
+abbrev height (data : QueryData t eqs F) := eqs*size t data.multiplierDegree+size t data.pointBound
+/-- Column count of the slice matrix, given by the number of monomials up to its column degree. -/
+abbrev width (data : QueryData t eqs F) := size t data.columnDegree
+
+/-- Time bound for a selected entry, covering the slower of the ordinary and powered readers
+and the row-replacement overhead. -/
+def selectedTime (K : Type) [Fintype K] (n m d w v e B Ba Bt A S : ℕ) :=
+ 20*w+10 + (max (SelectedMinor.time K n m d w v e B A S Ba) (SelectedMinor.time K n m d w v e B A S Bt)+1)
+
+/-- Peak stack height for a selected entry, including the workspace needed to test the
+replacement row. -/
+def selectedSpace (K : Type) [Fintype K] (d w v e A S : ℕ) :=
+ max (SelectedMinor.space K d w v e A S) (w+(20*w+10))
+
+/-- Physical readers for the exact two matrices in the finite-slice Cramer
+quotient. The three direct scalar programs may use different predicates and
+banks from the immutable pivot matrix reader. -/
+theorem selected_reads (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (data : QueryData t eqs F)
+ (op : Operation t) (current next : Fin data.dimension)
+ (scan : FiniteRoutine (MacaulayRead.Port K)) (denEntry : FiniteRoutine (MacaulayRead.Port D))
+ (numEntry power : FiniteRoutine (MacaulayRead.Port R))
+ {pivot : Stacks K → Prop} {denReady : Stacks D → Prop} {numReady : Stacks R → Prop}
+ (hs : MacaulayRead.CorrectSpace scan (baseMatrix φ data) w v B S pivot)
+ (hd : MacaulayRead.CorrectSpace denEntry (baseMatrix φ data) w v Ba S denReady)
+ (hn : MacaulayRead.CorrectSpace numEntry (baseMatrix φ data) w v Ba S numReady)
+ (ht : MacaulayRead.CorrectSpace power (fun _ j => target φ data op current j :
+ Matrix (Fin (height data)) (Fin (width data)) _) w v Bt S numReady)
+ (hsCap : ∀ a, pivot a → ∀ k, (a k).length ≤ A)
+ (hdCap : ∀ a, denReady a → ∀ k, (a k).length ≤ A)
+ (hnCap : ∀ a, numReady a → ∀ k, (a k).length ≤ A)
+ (hrSize : height data+height data+(height data+width data)*height data+width data+8 < 2^d)
+ (hcSize : width data+width data+(width data+height data)*width data+height data+8 < 2^d)
+ (hw : gramWidth d ≤ w) (hv : Word.workingWidth p ≤ v) (base : Stacks K) (hr : pivot base) :
+ let n := height data
+ let m := width data
+ let ticks := selectedTime K n m d w v e B Ba Bt A S
+ let cap := selectedSpace K d w v e A S
+ MacaulayRead.CorrectSpace (SelectedMinor.restrictEntry scan denEntry) (denominator φ data) w v ticks cap
+ (Submatrix.Ready (SelectedMinor.Ready w v n m c base denReady)) ∧
+ MacaulayRead.CorrectSpace (SelectedMinor.numerator scan numEntry power) (numerator φ data op current next) w v ticks cap
+ (Replacement.Ready w (combinedOrdinal data.equations data.monomials next)
+ (Submatrix.Ready (SelectedMinor.Ready w v n m c base numReady))) := by
+ let M := baseMatrix φ data
+ have dn := SelectedMinor.restrictEntry_correctSpace M M scan denEntry hs hd hsCap hdCap hrSize hcSize hw hv base hr
+ have nu := SelectedMinor.numerator_correctSpace M (target φ data op current) scan numEntry power hs hn ht
+ hsCap hnCap hrSize hcSize hw hv base hr (nativeOrdinal φ data next)
+ have hdcast := dn.castSquare (interpretedRank φ data) (denominator_cast_apply φ data)
+ have hncast := nu.castSquare (interpretedRank φ data) (numerator_cast_apply φ data op current next)
+ refine ⟨hdcast.enlarge ?_ (le_max_left ..), hncast⟩
+ exact (le_max_left ..).trans ((Nat.le_add_right _ _).trans (Nat.le_add_left ..))
+
+end Coordinate.SliceMinors
+end RankQuery.Stack
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSliceTargets.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSliceTargets.lean
new file mode 100644
index 0000000000..359659523e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSliceTargets.lean
@@ -0,0 +1,169 @@
+import OAI.Computability.VPVNP.RankCoordinateSliceSelection
+import OAI.Computability.VPVNP.RankCoordinateTargetRead
+
+/-! # The powered target in the live numerator bank
+
+The ordinary matrix reader and the target reader have disjoint auxiliary
+ports. The latter compares the indexed current monomial with the requested
+column, returning the native polynomial-basis encoding of zero or one.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+noncomputable section
+
+namespace RankQuery.Stack.Coordinate.SliceMinors
+
+open RAMTape BurstRAM UniversalCountStack Cursor
+open SliceArithmetic FiniteSlice RadicalCertificate.MonomialIndex RadicalCertificate.MonomialIndex.QueryData
+
+variable {F : Type} [Field F] [DecidableEq F] {p e t eqs : ℕ} [Fact p.Prime] [NeZero e]
+ [Algebra (ZMod p) F] {c : Vector p e} [Fact (Irreducible (modulus c))]
+ [DecidableEq (AdjoinRoot (modulus c))]
+ {K : Type} [Fintype K] [DecidableEq K] {d w v B S A P : ℕ}
+
+/-- Powered-monomial scan template with the slice arity and its two degree bounds fixed, and
+the dynamic arguments initialized to zero. -/
+def targetTemplate (data : QueryData t eqs F) : PairCall.Inputs where
+ arity := t
+ degree b := if b then data.columnDegree else data.pointBound
+ ordinal _ := 0
+ scale := 0
+ mark := 0
+
+/-- Installs the current basis monomial, operation scale and variable mark in the target
+template. -/
+def targetArgs (data : QueryData t eqs F) (op : Operation t) (i : Fin data.dimension) :=
+ TargetRead.setDynamic (targetTemplate data) (data.basisIndex i).val (PairCall.targetScale data op) (PairCall.targetMark op)
+
+/-- Disjoint auxiliary ports for the ordinary matrix reader and the powered-target reader. -/
+abbrev Direct (K : Type) := K ⊕ TargetRead.Work
+
+/-- Requires the base reader to be ready on its own ports and the powered reader to hold its
+target arguments on the other ports. -/
+def directReady (c : Vector p e) (w v : ℕ) (q : PairCall.Inputs) (ready : Stacks K → Prop)
+ (s : Stacks (Direct K)) : Prop := ready (s ∘ Sum.inl) ∧ TargetRead.Ready c w v q (s ∘ Sum.inr)
+
+/-- Runs the ordinary scalar entry reader using the left auxiliary bank of the direct reader. -/
+def ordinary (read : FiniteRoutine (MacaulayRead.Port K)) : FiniteRoutine (MacaulayRead.Port (Direct K)) :=
+ MacaulayRead.onAux Sum.inl read
+
+/-- Runs the powered-monomial entry reader using the right auxiliary bank of the direct reader. -/
+def powered : FiniteRoutine (MacaulayRead.Port (Direct K)) := MacaulayRead.onAux Sum.inr TargetRead.reader
+
+omit [Fintype K] [DecidableEq K] [NeZero e] [Fact (Irreducible (modulus c))] [DecidableEq (AdjoinRoot (modulus c))] in
+theorem directReady_length {ready : Stacks K → Prop} (q : PairCall.Inputs)
+ (ha : ∀ a, ready a → ∀ k, (a k).length ≤ A)
+ (hw : w ≤ P) (har : q.arity ≤ P) (ht : max P (e*v) ≤ A)
+ {s : Stacks (Direct K)} (hs : directReady c w v q ready s) (k : Direct K) : (s k).length ≤ A := by
+ rcases k with k | k
+ · exact ha _ hs.1 k
+ · exact (TargetRead.ready_bound c q hs.2 hw har k).trans ht
+
+omit [Fintype K] [NeZero e] [Fact (Irreducible (modulus c))] [DecidableEq (AdjoinRoot (modulus c))] in
+theorem ordinary_correctSpace {n m : ℕ} (q : PairCall.Inputs) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ (read : FiniteRoutine (MacaulayRead.Port K)) {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (hw : w ≤ P) (har : q.arity ≤ P) (ht : max P (e*v) ≤ S) :
+ MacaulayRead.CorrectSpace (ordinary read) M w v B S (directReady c w v q ready) := by
+ have h := hc.onAux (ready := directReady c w v q ready) (A := S) Sum.inl Sum.inl_injective
+ (fun _ hs => hs.1) (fun a out hs ho => by
+ constructor
+ · simpa only [show installStacks Sum.inl a out ∘ Sum.inl = out from funext (installStacks_at Sum.inl_injective a out)] using ho
+ · have eq : installStacks Sum.inl a out ∘ Sum.inr = a ∘ Sum.inr :=
+ funext fun j => installStacks_outside a out fun i he => by cases he
+ rw [eq]; exact hs.2) (fun s hs j outside => by
+ rcases j with j | j
+ · exact (outside j rfl).elim
+ · exact (TargetRead.ready_bound c q hs.2 hw har j).trans ht)
+ simpa only [ordinary, max_self] using h
+
+omit [DecidableEq (AdjoinRoot (modulus c))] in
+/-- The exact field encoding of the current powered target at one column. -/
+theorem target_flag (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (data : QueryData t eqs F)
+ (op : Operation t) (i : Fin data.dimension) (j : Fin (width data)) :
+ (if TargetRead.entryFlag (targetArgs data op i) (data.basisIndex i) j then (1 : Scalar c) else 0) =
+ target φ data op i j := by
+ let f := φ.toRingEquiv.toRingHom.comp (Scalar.interpretation c)
+ apply φ.injective.comp (Scalar.interpret_injective c)
+ change f _ = f (encode φ _)
+ rw [decode_encode]
+ exact TargetRead.map_match c f (targetArgs data op i) data op (data.basisIndex i) j rfl rfl
+
+omit [Fintype K] [DecidableEq (AdjoinRoot (modulus c))] in
+theorem powered_correctSpace (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (data : QueryData t eqs F)
+ (op : Operation t) (i : Fin data.dimension) {ready : Stacks K → Prop} (ha : ∀ a, ready a → ∀ k, (a k).length ≤ A)
+ (hw : PairCall.requiredWidth (targetArgs data op i) ≤ w) (hword : w ≤ P) (har : t ≤ P)
+ (hlocal : TargetRead.space w P e v ≤ S) (hA : A ≤ S) :
+ MacaulayRead.CorrectSpace (powered (K := K))
+ (fun _ j => target φ data op i j : Matrix (Fin (height data)) (Fin (width data)) _)
+ w v (TargetRead.clock w P e v (targetArgs data op i)) S (directReady c w v (targetArgs data op i) ready) := by
+ let q := targetArgs data op i
+ have raw := TargetRead.correctSpace (r := height data) (v := v) c q (data.basisIndex i) rfl hw hword har
+ have h := raw.onAux (ready := directReady c w v q ready) (A := A) Sum.inr Sum.inr_injective
+ (fun _ hs => hs.2) (fun a out hs ho => by
+ constructor
+ · have eq : installStacks Sum.inr a out ∘ Sum.inl = a ∘ Sum.inl :=
+ funext fun j => installStacks_outside a out fun i he => by cases he
+ rw [eq]; exact hs.1
+ · exact (show installStacks Sum.inr a out ∘ Sum.inr = out from funext (installStacks_at Sum.inr_injective a out)).symm ▸ ho)
+ (fun s hs j outside => by
+ rcases j with j | j
+ · exact ha _ hs.1 j
+ · exact (outside j rfl).elim)
+ have matrix_eq : (fun _ j => if TargetRead.entryFlag q (data.basisIndex i) j then (1 : Scalar c) else 0 :
+ Matrix (Fin (height data)) (Fin (width data)) _) = fun _ j => target φ data op i j :=
+ Matrix.ext fun _ j => target_flag φ data op i j
+ rw [← matrix_eq]
+ exact h.enlarge le_rfl (max_le hlocal hA)
+
+/-- Compares the ports of a prefix-rank call using the underlying Gram-scan address type. -/
+local instance : DecidableEq (PrefixPort K) := inferInstanceAs (DecidableEq (ScanPort (GramEngine.Aux K)))
+/-- Decides equality of auxiliary addresses in the greedy prefix scanner. -/
+local instance : DecidableEq (PrefixWorkspace.Aux (PrefixPort K)) := fun a b => PrefixWorkspace.instDecidableEqAux a b
+/-- Compares the register and auxiliary addresses of a row or column selector. -/
+local instance : DecidableEq (Select.Side K) := inferInstanceAs (DecidableEq (PrefixWords.Port (PrefixWorkspace.Aux (PrefixPort K))))
+/-- Distinguishes the two selector banks and the direct entry reader inside a selected minor. -/
+local instance {J : Type} [DecidableEq J] : DecidableEq (SelectedMinor.Host K J) :=
+ inferInstanceAs (DecidableEq (Select.Side K ⊕ (Select.Side K ⊕ J)))
+/-- Compares the selected row word, column word and remaining selected-minor workspace
+addresses. -/
+local instance {J : Type} [DecidableEq J] : DecidableEq (SelectedMinor.Work K J) := fun a b => Submatrix.instDecidableEqWork a b
+
+/-- Only the scalar entries of the original relation matrix are an input
+contract. The target and both pivot scans execute physical finite code.
+The common time and space bounds apply to every choice of basis ordinals. -/
+theorem native_reads (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] F) (data : QueryData t eqs F)
+ (op : Operation t) (current next : Fin data.dimension)
+ (scan : FiniteRoutine (MacaulayRead.Port K)) {ready : Stacks K → Prop}
+ (hc : MacaulayRead.CorrectSpace scan (baseMatrix φ data) w v B S ready)
+ (ha : ∀ a, ready a → ∀ k, (a k).length ≤ A) (base : Stacks K) (hr : ready base)
+ (hrSize : height data+height data+(height data+width data)*height data+width data+8 < 2^d)
+ (hcSize : width data+width data+(width data+height data)*width data+height data+8 < 2^d)
+ (hw : gramWidth d ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (hp : PairCall.requiredWidth (targetArgs data op current) ≤ w) (hword : w ≤ P) (har : t ≤ P)
+ (hbits : max P (e*v) ≤ A) (hA : A ≤ S) (hlocal : TargetRead.space w P e v ≤ S) :
+ let n := height data
+ let m := width data
+ let ticks := selectedTime K n m d w v e B B (TargetRead.clock w P e v (targetTemplate data)) A S
+ let cap := selectedSpace K d w v e A S
+ let q := targetArgs data op current
+ MacaulayRead.CorrectSpace (SelectedMinor.restrictEntry scan scan) (denominator φ data) w v ticks cap
+ (Submatrix.Ready (SelectedMinor.Ready w v n m c base ready)) ∧
+ MacaulayRead.CorrectSpace (SelectedMinor.numerator scan (ordinary scan) powered) (numerator φ data op current next)
+ w v ticks cap (Replacement.Ready w (combinedOrdinal data.equations data.monomials next)
+ (Submatrix.Ready (SelectedMinor.Ready w v n m c base (directReady c w v q ready)))) := by
+ let q := targetArgs data op current
+ have ho := ordinary_correctSpace (P := P) q (baseMatrix φ data) scan hc hword har (hbits.trans hA)
+ have ht := powered_correctSpace φ data op current ha hp hword har hlocal hA
+ exact selected_reads φ data op current next scan scan (ordinary scan) powered hc hc ho ht ha ha
+ (fun _ h k => directReady_length q ha hword har hbits h k) hrSize hcSize hw hv base hr
+
+end RankQuery.Stack.Coordinate.SliceMinors
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateSubmatrix.lean b/lean/OAI/Computability/VPVNP/RankCoordinateSubmatrix.lean
new file mode 100644
index 0000000000..f4822d72d9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateSubmatrix.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.RankCoordinateOrdinal
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+
+/-!
+# Entry reads for the selected Cramer submatrix
+
+Two ordinal selectors return original row and column addresses into distinct
+scratch words. The scalar reader uses both words directly. Their bits are
+discarded before returning to the determinant engine, so later queries can
+reuse the same two words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.CallClear
+
+open RAMTape UniversalCountStack
+
+/-- Popping a stack to empty never increases the peak height of any stack. -/
+theorem clear_bounded {K : Type} [DecidableEq K] (k : K) (s : Stacks K) (S : ℕ)
+ (fits : ∀ i, (s i).length ≤ S) :
+ (clear k).BoundedRun S ((s k).length+1) s (Function.update s k []) := by
+ generalize h : s k = bits
+ induction bits generalizing s with
+ | nil =>
+ have pop := StackStep.pop (s := s) (code := (clear k).body.standalone) (q := some ())
+ (show (clear k).body.standalone (some ()) = .pop k (fun b => b.map fun _ => ()) from rfl)
+ rw [h] at pop
+ refine .cons fits pop (.nil _ _ ?_)
+ intro i
+ by_cases hi : i = k
+ · subst i; simp
+ · simpa [hi] using fits i
+ | cons b bits ih =>
+ have pop := StackStep.pop (s := s) (code := (clear k).body.standalone) (q := some ())
+ (show (clear k).body.standalone (some ()) = .pop k (fun b => b.map fun _ => ()) from rfl)
+ rw [h] at pop
+ have later := ih (Function.update s k bits) (fun i => by
+ by_cases hi : i = k
+ · subst i
+ have hlen := fits k
+ rw [h, List.length_cons] at hlen
+ simpa using Nat.le_of_succ_le hlen
+ · simpa [hi] using fits i) (Function.update_self ..)
+ rw [Function.update_idem] at later
+ exact .cons fits pop later
+
+end SliceArithmetic.CallClear
+
+namespace RankQuery.Stack.Coordinate.Submatrix
+
+open RAMTape UniversalCountStack
+open SliceArithmetic.CallClear (clear clear_bounded)
+
+/-- Private ports holding the selected original row and column ordinals together with the
+scalar reader's workspace. -/
+inductive Work (K : Type) where
+ | row | col | aux (k : K)
+ deriving DecidableEq, Fintype
+
+/-- Public row, column and scalar-result ports extended by the selected-submatrix workspace. -/
+abbrev Port (K : Type) := MacaulayRead.Port (Work K)
+
+variable {K : Type}
+
+/-- Installs the two selected address words alongside the underlying scalar reader's stacks. -/
+def workBank (row col : List Bool) (s : Stacks K) : Stacks (Work K)
+ | .row => row | .col => col | .aux k => s k
+
+/-- Both original addresses are recomputed for each scalar query. -/
+def Ready (ready : Stacks K → Prop) (s : Stacks (Work K)) : Prop :=
+ ∃ a, ready a ∧ s = workBank [] [] a
+
+private def rowPorts : OrdinalRead.Port K → Port K
+ | .input => .row | .result => .aux .row | .aux k => .aux (.aux k)
+
+private def colPorts : OrdinalRead.Port K → Port K
+ | .input => .col | .result => .aux .col | .aux k => .aux (.aux k)
+
+private def scalarPorts : MacaulayRead.Port K → Port K
+ | .row => .aux .row | .col => .aux .col | .result => .result | .aux k => .aux (.aux k)
+
+private theorem rowInj : Function.Injective (rowPorts (K := K)) := by
+ intro a b hab; cases a <;> cases b <;> simp_all [rowPorts]
+
+private theorem colInj : Function.Injective (colPorts (K := K)) := by
+ intro a b hab; cases a <;> cases b <;> simp_all [colPorts]
+
+private theorem scalarInj : Function.Injective (scalarPorts (K := K)) := by
+ intro a b hab; cases a <;> cases b <;> simp_all [scalarPorts]
+
+/-- The caller supplies dense row and column indices, and receives the
+selected entry on its own scalar result stack. -/
+def minorRead (rows cols : FiniteRoutine (OrdinalRead.Port K))
+ (entry : FiniteRoutine (MacaulayRead.Port K)) : FiniteRoutine (Port K) :=
+ ((((rows.onPorts rowPorts).followedBy (cols.onPorts colPorts)).followedBy
+ (entry.onPorts scalarPorts)).followedBy (clear (.aux .row))).followedBy (clear (.aux .col))
+
+variable [DecidableEq K] {p e n m r s w v Br Bc Be S : ℕ} {c : SliceArithmetic.Vector p e}
+ {ready : Stacks K → Prop} {rows cols : FiniteRoutine (OrdinalRead.Port K)}
+ {entry : FiniteRoutine (MacaulayRead.Port K)} {M : Matrix (Fin n) (Fin m) (Scalar c)}
+ {f : Fin r → Fin n} {g : Fin s → Fin m}
+
+local macro "outside" : tactic => `(tactic|
+ (intro k hk; cases k with
+ | aux u => cases u <;> first | rfl | exact (hk (.aux _) rfl).elim | exact (hk .result rfl).elim
+ | row | col | result => first | rfl | exact (hk .result rfl).elim))
+
+/-- The square and rectangular versions use the same finite code. Only the
+two short erase scans are added to the selectors' and entry reader's costs. -/
+theorem correctSpace (hr : OrdinalRead.CorrectSpace rows f w Br S ready)
+ (hc : OrdinalRead.CorrectSpace cols g w Bc S ready)
+ (he : MacaulayRead.CorrectSpace entry M w v Be S ready) :
+ MacaulayRead.CorrectSpace (minorRead rows cols entry) (M.submatrix f g) w v
+ (Br+Bc+Be+2*(w+1)) S (Ready ready) := by
+ rintro i j _ ⟨a, ha, rfl⟩
+ let state (row col result : List Bool) (u : Stacks K) :=
+ MacaulayRead.bank w i j result (workBank row col u)
+ let ri := digits w (f i)
+ let cj := digits w (g j)
+ let val := Engine.scalar v (M (f i) (g j))
+ obtain ⟨tr, htr, b, hb, row⟩ := hr i a ha
+ obtain ⟨tc, htc, d, hd, col⟩ := hc j b hb
+ obtain ⟨te, hte, u, hu, read⟩ := he (f i) (g j) d hd
+ have rowRun : (rows.onPorts rowPorts).BoundedRun S tr (state [] [] [] a) (state ri [] [] b) := by
+ apply FiniteRoutine.BoundedRun.framed rowInj row _ (fun k => by cases k <;> rfl)
+ (fun k => by cases k <;> rfl) (by outside)
+ intro k
+ cases k with
+ | row => exact row.initial_cap .input
+ | col => simpa [state, MacaulayRead.bank, OrdinalRead.bank] using row.initial_cap .input
+ | result => exact Nat.zero_le _
+ | aux k => cases k with
+ | row | col => exact Nat.zero_le _
+ | aux k => exact row.initial_cap (.aux k)
+ have colRun : (cols.onPorts colPorts).BoundedRun S tc (state ri [] [] b) (state ri cj [] d) := by
+ apply FiniteRoutine.BoundedRun.framed colInj col rowRun.final_cap (fun k => by cases k <;> rfl)
+ (fun k => by cases k <;> rfl) (by outside)
+ have entryRun : (entry.onPorts scalarPorts).BoundedRun S te (state ri cj [] d) (state ri cj val u) := by
+ apply FiniteRoutine.BoundedRun.framed scalarInj read colRun.final_cap (fun k => by cases k <;> rfl)
+ (fun k => by cases k <;> rfl) (by outside)
+ have eraseRow := clear_bounded (MacaulayRead.Port.aux Work.row) (state ri cj val u) S entryRun.final_cap
+ have er : Function.update (state ri cj val u) (.aux .row) [] = state [] cj val u := by
+ funext k; cases k with | aux k => cases k <;> rfl | _ => rfl
+ rw [er] at eraseRow
+ have eraseCol := clear_bounded (MacaulayRead.Port.aux Work.col) (state [] cj val u) S eraseRow.final_cap
+ have ec : Function.update (state [] cj val u) (.aux .col) [] = state [] [] val u := by
+ funext k; cases k with | aux k => cases k <;> rfl | _ => rfl
+ rw [ec] at eraseCol
+ change (clear _).BoundedRun S (ri.length+1) _ _ at eraseRow
+ change (clear _).BoundedRun S (cj.length+1) _ _ at eraseCol
+ simp only [ri, cj, length_digits] at eraseRow eraseCol
+ exact ⟨_, by omega, workBank [] [] u, ⟨u, hu, rfl⟩,
+ (((rowRun.followedBy colRun).followedBy entryRun).followedBy eraseRow).followedBy eraseCol⟩
+
+end RankQuery.Stack.Coordinate.Submatrix
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateTargetPorts.lean b/lean/OAI/Computability/VPVNP/RankCoordinateTargetPorts.lean
new file mode 100644
index 0000000000..c0fb2d8bf7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateTargetPorts.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.MacaulayPairEntries
+import OAI.Computability.VPVNP.RankQueryGramReadSpace
+
+/-! # Dynamic inputs to the powered target row
+
+The enclosing coordinate query stages the source monomial ordinal, the
+marked variable, and the power scale. The other monomial address is the
+column requested by the scalar reader. The auxiliary bank also retains
+encoded constants zero and one.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.TargetRead
+
+open RAMTape UniversalCountStack RadicalCertificate.MonomialIndex
+
+/-- Additional powered-reader ports for the encoded zero and one scalars and a temporary stack. -/
+inductive Extra where
+ | constant (b : Bool) | tmp
+ deriving DecidableEq, Fintype
+
+/-- Private workspace combining the monomial pair scan, two scalar literals and a temporary
+stack. -/
+abbrev Work := PairCall.Port ⊕ Extra
+set_option synthInstance.maxSize 2500 in
+instance : DecidableEq Work := inferInstanceAs (DecidableEq (PairCall.Port ⊕ Extra))
+
+/-- Matrix entry interface whose auxiliary stacks run the powered target scan. -/
+abbrev Port := MacaulayRead.Port Work
+
+/-- Workspace address holding the source monomial's ordinal in the pair scan. -/
+def sourcePort : Work := .inl (.external (.ordinal false))
+/-- Workspace address holding the one-based variable mark, with zero denoting an unmarked
+target. -/
+def markPort : Work := .inl (.external .mark)
+/-- Workspace address holding the exponent scale used by the powered monomial test. -/
+def scalePort : Work := .inl (.external .scale)
+/-- Reader address of the equality flag produced by the powered monomial scan. -/
+abbrev flagPort : Port := .aux (.inl (.external .flag))
+
+/-- The full flag word belongs to the powered scan until the scalar copy
+has completed. The caller's column is the only aliased pair-scan port. -/
+def storage (w : ℕ) (d : PairCall.Inputs) (constants : Bool → List Bool) (flag : List Bool) : Stacks Work
+ | .inl (.external (.ordinal true)) => []
+ | .inl p => PairCall.publicBank w d (fun _ => []) [] flag p
+ | .inr (.constant b) => constants b
+ | .inr .tmp => []
+
+/-- Initial powered-reader bank with the supplied scalar literals and an empty result flag. -/
+def bank (w : ℕ) (d : PairCall.Inputs) (constants : Bool → List Bool) : Stacks Work :=
+ storage w d constants []
+
+/-- Updates the source ordinal, power scale and variable mark while preserving the column
+ordinal and degree bounds. -/
+def setDynamic (d : PairCall.Inputs) (source scale mark : ℕ) : PairCall.Inputs :=
+ {d with ordinal := fun b => if b then d.ordinal true else source, scale := scale, mark := mark}
+
+/-- The staging slots, in source ordinal, marked variable, and scale order. -/
+def slot : Fin 3 ↪ Work :=
+ ⟨![sourcePort, markPort, scalePort], by intro i j h; fin_cases i <;> fin_cases j <;> first | rfl | contradiction⟩
+
+/-- The three fixed-width staging words, ordered as source ordinal, variable mark and exponent
+scale. -/
+def words (w source scale mark : ℕ) : Stacks (Fin 3) :=
+ ![digits w source, digits w mark, digits w scale]
+
+/-- Powered-reader template with the three dynamic argument stacks emptied for staging. -/
+noncomputable def blankDynamic (w : ℕ) (d : PairCall.Inputs) (constants : Bool → List Bool) : Stacks Work :=
+ installStacks slot (bank w d constants) (fun _ => [])
+
+private theorem updated_outside (w : ℕ) (d : PairCall.Inputs) (constants : Bool → List Bool)
+ (source scale mark : ℕ) (p : Work) (outside : ∀ i, slot i ≠ p) :
+ bank w (setDynamic d source scale mark) constants p = bank w d constants p := by
+ rcases p with (f | k | _) | e
+ · cases f with
+ | ordinal b => cases b <;> first | rfl | exact (outside 0 rfl).elim
+ | mark => exact (outside 1 rfl).elim
+ | scale => exact (outside 2 rfl).elim
+ | _ => rfl
+ · rfl
+ · rfl
+ · cases e <;> rfl
+
+theorem stage_dynamic (w : ℕ) (d : PairCall.Inputs) (constants : Bool → List Bool) (source scale mark : ℕ) :
+ installStacks slot (bank w d constants) (words w source scale mark) =
+ bank w (setDynamic d source scale mark) constants := by
+ apply installStacks_frame slot.injective (fun i => by fin_cases i <;> rfl)
+ (updated_outside w d constants source scale mark)
+
+theorem stage_blankDynamic (w : ℕ) (d : PairCall.Inputs) (constants : Bool → List Bool) (source scale mark : ℕ) :
+ installStacks slot (blankDynamic w d constants) (words w source scale mark) =
+ bank w (setDynamic d source scale mark) constants := by
+ apply installStacks_frame slot.injective (fun i => by fin_cases i <;> rfl)
+ intro p hp
+ rw [updated_outside w d constants source scale mark p hp, blankDynamic, installStacks_outside _ _ hp]
+
+end RankQuery.Stack.Coordinate.TargetRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCoordinateTargetRead.lean b/lean/OAI/Computability/VPVNP/RankCoordinateTargetRead.lean
new file mode 100644
index 0000000000..4aab944bf7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCoordinateTargetRead.lean
@@ -0,0 +1,233 @@
+import OAI.Computability.VPVNP.RankCoordinateTargetPorts
+import OAI.Computability.VPVNP.RankCoordinateSubmatrix
+import OAI.Computability.VPVNP.RankQueryTagSpace
+import OAI.Computability.VPVNP.MacaulayPairBounds
+
+/-! # Physical scalar reader for the powered target row
+
+The monomial pair scan compares the requested original column with the
+powered target exponent. The returned bit selects a canonical field zero
+or one. Both the exponent scan and the scalar copy restore the prepared
+target parameters, so subsequent column queries use the same advice.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.TargetRead
+
+open RAMTape UniversalCountStack RadicalCertificate.MonomialIndex
+open SliceArithmetic.CallClear (clear clear_bounded)
+
+private def mount : PairCall.Port → Port
+ | .external (.ordinal true) => .col
+ | q => .aux (.inl q)
+
+private theorem mount_inj : Function.Injective mount := by
+ let q : PairCall.Port := .external (.ordinal true)
+ have rest (a : PairCall.Port) (h : a ≠ q) : mount a = .aux (.inl a) := by
+ cases a with
+ | external f => cases f with
+ | ordinal b => cases b <;> first | rfl | exact (h rfl).elim
+ | _ => rfl
+ | _ => rfl
+ intro a b hab
+ by_cases ha : a = q <;> by_cases hb : b = q <;> simp_all [q, mount]
+
+private def copy (b : Bool) : FiniteRoutine Port :=
+ SuccessorFields.prependCopy (.aux (.inr (.constant b))) .result (.aux (.inr .tmp))
+
+/-- The equality word has numeric value zero or one. The tag scan reads its
+low bit before the whole word is reclaimed. -/
+def reader : FiniteRoutine Port :=
+ ((PairCall.powered.onPorts mount).followedBy
+ (TagRouter.select flagPort 1 (fun tag => copy (tag == 1)))).followedBy (clear flagPort)
+
+/-- Inputs for a query of one target-row entry. The source ordinal is fixed and the column
+ordinal is set to the requested column. -/
+def live (d : PairCall.Inputs) (column : ℕ) : PairCall.Inputs :=
+ {d with ordinal := fun b => if b then column else d.ordinal false}
+
+/-- The two bounded monomial indices used by a target query, with the source at false and the
+column at true. -/
+def ordinals (d : PairCall.Inputs) (source : Fin (size d.arity (d.degree false)))
+ (col : Fin (size d.arity (d.degree true))) : PairCall.Ordinals d
+ | false => source
+ | true => col
+
+/-- Whether the enumerated column monomial equals the source monomial after applying the
+specified power and coordinate shift. -/
+def entryFlag (d : PairCall.Inputs) (source : Fin (size d.arity (d.degree false)))
+ (col : Fin (size d.arity (d.degree true))) : Bool :=
+ PairCall.powerMatch d (PairCall.monomial d (ordinals d source col) false)
+ (PairCall.monomial d (ordinals d source col) true)
+
+/-- Step bound for scanning both monomial indices, testing the powered exponents, copying the
+selected field literal, and clearing the flag. -/
+def clock (w B e v : ℕ) (d : PairCall.Inputs) :=
+ PairCall.scanClock w B d + PairCall.powerClock d.arity w B + PairCall.clearCost w +
+ (2+(5*(e*v)+2))+(w+1)
+
+/-- Stack-height bound for the target-row reader, including the powered-monomial scan and the
+copy of an `e`-limb scalar with `v` bits per limb. -/
+def space (w B e v : ℕ) :=
+ max (PairCall.poweredSpace w B) (max w (e*v)) + (5*(e*v)+2)
+
+variable {p e r w v B : ℕ} [Fact p.Prime] [NeZero e] (c : SliceArithmetic.Vector p e)
+
+/-- The packed field element returned for a Boolean entry flag, encoding one on a monomial
+match and zero otherwise. -/
+def literal (v : ℕ) (b : Bool) : List Bool :=
+ Engine.scalar v (if b then (1 : Scalar c) else 0)
+
+/-- The target reader’s work stacks contain the prepared monomial parameters and the two packed
+field literals for this extension. -/
+def Ready (w v : ℕ) (d : PairCall.Inputs) (s : Stacks Work) : Prop :=
+ s = bank w d (literal c v)
+
+omit [NeZero e] in
+/-- Bound on each auxiliary stack before and after a target query. -/
+theorem ready_bound (d : PairCall.Inputs) {s : Stacks Work} (hs : Ready c w v d s)
+ (hword : w ≤ B) (harity : d.arity ≤ B) (k : Work) : (s k).length ≤ max B (e*v) := by
+ subst s
+ rcases k with (f | a | _) | a
+ · have h := PairCall.values_le d (fun _ => []) [] [] hword harity (by simp) (by simp) (by simp) f
+ cases f with
+ | ordinal b => cases b <;> first | exact h.trans (le_max_left ..) | exact Nat.zero_le _
+ | _ => exact h.trans (le_max_left ..)
+ · exact Nat.zero_le _
+ · exact Nat.zero_le _
+ · cases a with
+ | constant b => simp [bank, storage, literal]
+ | tmp => exact Nat.zero_le _
+
+private theorem mounted (d : PairCall.Inputs) (i j w : ℕ) (res flag : List Bool)
+ (constants : Bool → List Bool) (q : PairCall.Port) :
+ MacaulayRead.bank w i j res (storage w d constants flag) (mount q) =
+ PairCall.publicBank w (live d j) (fun _ => []) [] flag q := by
+ cases q with
+ | external f => cases f with
+ | ordinal b => cases b <;> rfl
+ | _ => rfl
+ | _ => rfl
+
+private theorem outside (d : PairCall.Inputs) (i j w : ℕ) (flag : List Bool)
+ (constants : Bool → List Bool) (p : Port) (hp : ∀ q, mount q ≠ p) :
+ MacaulayRead.bank w i j [] (storage w d constants flag) p =
+ MacaulayRead.bank w i j [] (storage w d constants []) p := by
+ cases p with
+ | row | col | result => rfl
+ | aux p =>
+ rcases p with (f | k | _) | e
+ · cases f with
+ | ordinal b => cases b <;> rfl
+ | flag => exact (hp (.external .flag) rfl).elim
+ | _ => rfl
+ · rfl
+ · rfl
+ · cases e <;> rfl
+
+omit [NeZero e] in
+/-- The actual finite routine reads the target independently of the dense
+row and uses the original column index as its second monomial address. -/
+theorem correctSpace (d : PairCall.Inputs) (source : Fin (size d.arity (d.degree false)))
+ (hsource : d.ordinal false = source.val) (hw : PairCall.requiredWidth d ≤ w)
+ (hword : w ≤ B) (harity : d.arity ≤ B) :
+ MacaulayRead.CorrectSpace reader
+ (fun (_ : Fin r) j => if entryFlag d source j then (1 : Scalar c) else 0) w v
+ (clock w B e v d) (space w B e v) (Ready c w v d) := by
+ rintro i j _ rfl
+ let data := live d j.val
+ let ij : PairCall.Ordinals data := ordinals d source j
+ let b := entryFlag d source j
+ let fl := digits w b.toNat
+ let frame (bits res : List Bool) := MacaulayRead.bank w i j res (storage w d (literal c v) bits)
+ let cap := max (PairCall.poweredSpace w B) (max w (e*v))
+ have hk (a : Bool) : data.ordinal a = (ij a).val := by cases a; exact hsource; rfl
+ obtain ⟨hf, hx⟩ := PairCall.fits_of_width data ij hw
+ have hpos : 0 < w := by
+ have h := (hf false).one_lt
+ by_contra! hh
+ simp [show w = 0 by omega] at h
+ obtain ⟨n, hn, raw⟩ := PairCall.powered_runs data ij hk hf hx [] [] hword harity (by simp) (by simp)
+ have flagEq : PairCall.powerMatch data (PairCall.monomial data ij false) (PairCall.monomial data ij true) = b := rfl
+ rw [flagEq, List.append_nil] at raw
+ have scan : (PairCall.powered.onPorts mount).BoundedRun cap n (frame [] []) (frame fl []) := by
+ refine FiniteRoutine.BoundedRun.framed mount_inj (raw.enlarge (le_max_left ..)) ?_
+ (mounted d i j w [] [] _)
+ (mounted d i j w [] fl _)
+ (outside d i j w fl _)
+ intro z
+ cases z with
+ | row | col =>
+ simp only [frame, MacaulayRead.bank, length_digits]
+ exact (le_max_left ..).trans (le_max_right ..)
+ | result => exact Nat.zero_le _
+ | aux z =>
+ rcases z with z | z
+ · by_cases he : z = .external (.ordinal true)
+ · subst z; exact Nat.zero_le _
+ · have hm : mount z = .aux (.inl z) := by
+ cases z with
+ | external f => cases f with
+ | ordinal u => cases u <;> first | rfl | exact (he rfl).elim
+ | _ => rfl
+ | _ => rfl
+ change ((frame [] []) (.aux (.inl z))).length ≤ cap
+ rw [← hm, show (frame [] []) (mount z) = _ from mounted d i j w [] [] _ z]
+ exact (raw.initial_cap z).trans (le_max_left ..)
+ · cases z with
+ | constant b =>
+ simp only [frame, MacaulayRead.bank, storage, literal, Engine.scalar_length]
+ exact (le_max_right ..).trans (le_max_right ..)
+ | tmp => exact Nat.zero_le _
+ let ans := literal c v b
+ have copyRun : (copy b).Runs (5*(e*v)+2) (frame fl []) (frame fl ans) := by
+ have cp := SuccessorFields.prependCopy_runs (K := Port) (.aux (.inr (.constant b))) .result (.aux (.inr .tmp))
+ (by intro h; cases h) (by intro h; cases h) (by intro h; cases h) (frame fl []) rfl
+ have endBank : Function.update (frame fl []) MacaulayRead.Port.result ans = frame fl ans := by
+ funext p; cases p <;> rfl
+ change (copy b).Runs (5*ans.length+2) (frame fl []) (Function.update (frame fl []) .result (ans++[])) at cp
+ rw [List.append_nil, endBank] at cp
+ simpa only [ans, literal, Engine.scalar_length] using cp
+ have copied := spaceRun_of_steps copyRun (fun z => Nat.add_le_add_right (scan.final_cap z) _)
+ have selected := TagRouter.digits_bounded flagPort (fun tag => copy (tag == 1)) hpos
+ (show b.toNat < 2^1 by cases b <;> decide) (frame fl []) (frame fl ans) rfl
+ (by simpa only [show (b.toNat == 1) = b by cases b <;> rfl] using copied)
+ have cleared := clear_bounded flagPort (frame fl ans) (space w B e v) selected.final_cap
+ have ef : Function.update (frame fl ans) flagPort [] = frame [] ans := by
+ funext z; cases z with
+ | aux z =>
+ rcases z with (f | k | _) | e
+ · cases f with | ordinal b => cases b <;> rfl | _ => rfl
+ · rfl
+ · rfl
+ · cases e <;> rfl
+ | _ => rfl
+ rw [ef] at cleared
+ change (clear flagPort).BoundedRun _ (fl.length+1) _ _ at cleared
+ simp only [fl, length_digits] at cleared
+ have all := ((scan.enlarge (Nat.le_add_right cap _)).followedBy selected).followedBy cleared
+ refine ⟨_, ?_, bank w d (literal c v), rfl, all⟩
+ unfold clock
+ exact Nat.add_le_add_right (Nat.add_le_add_right hn _) _
+
+/-- The native equality flag reads exactly the field-valued powered target
+of a Frobenius or label operation. -/
+theorem map_match {F : Type*} [Semiring F] (φ : Scalar c →+* F) {a : ℕ}
+ (d : PairCall.Inputs) (S : QueryData d.arity a F) (op : QueryData.Operation d.arity)
+ (source : Fin (size d.arity (d.degree false))) (j : Fin (size d.arity (d.degree true)))
+ (hscale : d.scale = PairCall.targetScale S op) (hmark : d.mark = PairCall.targetMark op) :
+ φ (if entryFlag d source j then (1 : Scalar c) else 0) =
+ powerEntry S.power (S.target op (indexedDigits source)) j := by
+ have h := PairCall.powerMatch_target d (ordinals d source j) S op hscale hmark
+ change φ (if entryFlag d source j then 1 else 0) = _
+ rw [apply_ite φ, map_one, map_zero]
+ exact h
+
+end RankQuery.Stack.Coordinate.TargetRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorCheck.lean b/lean/OAI/Computability/VPVNP/RankCursorCheck.lean
new file mode 100644
index 0000000000..89eba58b94
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorCheck.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.RankCursorPorts
+import OAI.Computability.VPVNP.RankCursorLoop
+import OAI.Computability.VPVNP.SliceArithmeticZero
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+
+/-! # Checking one Schur coefficient and rolling the rank registers
+
+After the root query returns, the zero test scans the field element in its
+polynomial-basis representation. Its bit feeds the cursor update directly.
+The check erases the coefficient and reuses the same registers on the next
+root query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch
+
+variable {K : Type} [DecidableEq K]
+
+private def zeroPort : SliceArithmeticZero.Port → ScanPort K
+ | .input => .engine .result
+ | .flag => .cursor .flag
+ | .scratch => .scratch
+
+omit [DecidableEq K] in
+private theorem zeroPort_injective : Function.Injective (zeroPort (K := K)) := by
+ intro x y h
+ cases x <;> cases y <;> simp_all [zeroPort]
+
+/-- Consume the scalar result, roll the two binary cursor words, and emit
+the control bit for the next iteration. -/
+def check : FiniteRoutine (ScanPort K) :=
+ (((SliceArithmeticZero.machine.onPorts zeroPort).followedBy
+ (SliceArithmetic.CallClear.clear (.engine .result))).followedBy (Registers.next.onPorts .cursor))
+
+/-- Step bound for testing the packed Schur coefficient for zero, clearing the scalar, and
+advancing the rank cursor registers. -/
+def checkClock (w v e : ℕ) := 5*(e*v) + 4 + Registers.clock w
+
+private theorem zero_test {p e w v : ℕ} [Fact p.Prime]
+ {c : SliceArithmetic.Vector p e} (hw : SliceArithmetic.Word.workingWidth p ≤ v)
+ (n : ℕ) (persistent : Word w) (rs : Regs Registers.R w) (aux : Stacks K) (a : Scalar c) :
+ (SliceArithmeticZero.machine.onPorts zeroPort).Runs (4*(e*v)+3)
+ (scanBank n persistent rs [] (yielded aux (Engine.scalar v a)))
+ (scanBank n persistent rs [decide (a = 0)] (yielded aux (Engine.scalar v a))) := by
+ have hd : a.digits = SliceArithmetic.zero p e ↔ a = 0 := by
+ constructor
+ · intro h
+ change a = Scalar.pack c (SliceArithmetic.zero p e)
+ simpa only [Scalar.pack_digits] using congrArg (Scalar.pack c) h
+ · rintro rfl
+ exact Scalar.digits_pack _
+ have h := SliceArithmeticZero.vector_runs hw a.digits []
+ simp only [hd] at h
+ apply SliceArithmeticZero.machine.runs_onPorts_framed (ports := zeroPort) zeroPort_injective h
+ · intro k; cases k <;> rfl
+ · intro k; cases k <;> rfl
+ · intro k hk
+ cases k with
+ | cursor k => cases k with
+ | isa j => rfl
+ | flag => exact (hk .flag rfl).elim
+ | _ => rfl
+
+/-- The rank registers and the entire engine bank are reusable after the
+scalar check, including the full polynomial-basis zero test in characteristic two. -/
+theorem check_runs {p e w v b : ℕ} [Fact p.Prime]
+ {c : SliceArithmetic.Vector p e} (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (n Z u z : ℕ) (persistent : Word w) (rs : Regs Registers.R w)
+ (aux : Stacks K) (a : Scalar c)
+ (hw : (b+1)*control.wordFactor ≤ w)
+ (he : ∀ i, input Z u z (decide (a=0)) i < 2^b) (hr : Registers.Stores rs Z u z) :
+ let s := advance Z u z (decide (a=0))
+ ∃ d ≤ checkClock w v e, ∃ rs',
+ check.Runs d (scanBank n persistent rs [] (yielded aux (Engine.scalar v a)))
+ (scanBank n persistent rs' [s.continues] (idle aux)) ∧
+ Registers.Stores rs' Z (s.words 1) (s.words 2) := by
+ let flag := decide (a=0)
+ let s := advance Z u z flag
+ have h₁ := zero_test hv n persistent rs aux a
+ have h₂ : (SliceArithmetic.CallClear.clear (ScanPort.engine Engine.Port.result)).Runs (e*v+1)
+ (scanBank n persistent rs [flag] (yielded aux (Engine.scalar v a)))
+ (scanBank n persistent rs [flag] (idle aux)) := by
+ have h := SliceArithmetic.CallClear.clear_runs (ScanPort.engine Engine.Port.result)
+ (scanBank n persistent rs [flag] (yielded aux (Engine.scalar v a)))
+ have heq : Function.update (scanBank n persistent rs [flag] (yielded aux (Engine.scalar v a)))
+ (.engine .result) [] = scanBank n persistent rs [flag] (idle aux) := by
+ funext k
+ cases k with
+ | engine j => cases j with | frame f => cases f <;> rfl | _ => rfl
+ | _ => rfl
+ rw [heq] at h
+ exact (Engine.scalar_length v a) ▸ h
+ obtain ⟨d, hd, out, hn, hs⟩ := Registers.next_runs Z u z flag persistent rs [] hw he hr
+ have h₃ : (Registers.next.onPorts ScanPort.cursor).Runs d (scanBank n persistent rs [flag] (idle aux))
+ (scanBank n persistent out [s.continues] (idle aux)) := by
+ have ha : Registers.continuing s = s.continues := by cases s <;> rfl
+ apply Registers.next.runs_onPorts_framed (ports := ScanPort.cursor) (fun _ _ h => ScanPort.cursor.inj h) hn
+ · intro k; rfl
+ · intro k; rw [← ha]; rfl
+ · intro k hk; cases k with | cursor j => exact (hk j rfl).elim | _ => rfl
+ exact ⟨(4*(e*v)+3) + (e*v+1) + d, by unfold checkClock; omega, out, (h₁.followedBy h₂).followedBy h₃, hs⟩
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorDepth.lean b/lean/OAI/Computability/VPVNP/RankCursorDepth.lean
new file mode 100644
index 0000000000..9136a20922
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorDepth.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.RankCursorPorts
+import OAI.Computability.VPVNP.RAMTapePublicExprLog
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-! # Preparing the depth of the Schur product from a binary matrix dimension
+
+At startup the dimension is present on the row-count stack. The rank scan
+copies it into the depth word, then computes its ceiling binary logarithm.
+The one-register logarithm uses the cursor's otherwise empty ISA work
+stacks and leaves every cursor register available to the first request.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch UniversalCountStack
+
+variable {K : Type}
+
+private def logPort : ISA.Port 1 0 → ScanPort K
+ | .reg _ => .depth
+ | .pub i => Fin.elim0 i
+ | .persistent => .cursor (.isa .persistent)
+ | .work i => .cursor (.isa (.work i))
+ | .logPort i => .cursor (.isa (.logPort i))
+
+private theorem logPort_inj : Function.Injective (@logPort K) := by
+ intro i j h
+ cases i with
+ | pub i => exact i.elim0
+ | reg i => cases j with
+ | pub j => exact j.elim0
+ | reg j => exact congrArg ISA.Port.reg (Subsingleton.elim i j)
+ | persistent | work | logPort => cases h
+ | persistent | work | logPort =>
+ cases j <;> first | exact Fin.elim0 ‹Fin 0› | simp_all [logPort]
+
+/-- Copy the binary row count to the depth stack and replace the copy by its ceiling base-two
+logarithm. -/
+def prepareDepth : FiniteRoutine (ScanPort K) :=
+ (SuccessorFields.prependCopy .rows .depth .scratch).followedBy
+ ((PublicExprLog.code (r := 1) (k := 0) true 0).onPorts logPort)
+
+/-- Step bound for copying a w-bit row count and computing the depth of the balanced Schur
+product. -/
+def depthClock (w : ℕ) := 5*w + 2 + PublicExprLog.bound w
+
+variable [DecidableEq K]
+
+/-- At normal return the bank contains the computed depth word for the full
+rank scan. This also works for dimension zero and for the empty word. -/
+theorem prepareDepth_runs {w : ℕ} (n : ℕ) (hn : n < 2^w) (persistent : Word w)
+ (rs : Regs Registers.R w) (flags : List Bool) (work : Stacks (Engine.Port K)) :
+ ∃ t ≤ depthClock w, prepareDepth.Runs t
+ (Function.update (scanBank n persistent rs flags work) ScanPort.depth [])
+ (scanBank n persistent rs flags work) := by
+ let s := scanBank n persistent rs flags work
+ let x : Word w := ⟨n, hn⟩
+ let first := Function.update s ScanPort.depth []
+ let mid := Function.update s ScanPort.depth (digits w n)
+ have hc := SuccessorFields.prependCopy_runs ScanPort.rows ScanPort.depth ScanPort.scratch
+ (by intro h; cases h) (by intro h; cases h) (by intro h; cases h) first rfl
+ have runCopy : (SuccessorFields.prependCopy ScanPort.rows ScanPort.depth ScanPort.scratch).Runs
+ (5*w+2) first mid := by
+ simpa only [first, mid, Function.update_of_ne (show ScanPort.rows ≠ (ScanPort.depth : ScanPort K) by intro he; cases he),
+ Function.update_self, List.append_nil, Function.update_idem, s, scanBank, length_digits] using hc
+ have hx : digits w n = wordBits x := congrArg wordBits (Fin.ext (Nat.mod_eq_of_lt hn))
+ obtain ⟨t,ht,run⟩ := PublicExprLog.runs (r := 1) (k := 0) true 0 Fin.elim0 persistent (fun _ => x) []
+ have log : ((PublicExprLog.code (r := 1) (k := 0) true 0).onPorts logPort).Runs t mid s := by
+ apply FiniteRoutine.runs_onPorts_framed _ logPort_inj run
+ · intro i
+ cases i with
+ | reg j => exact hx
+ | pub j => exact j.elim0
+ | persistent | work | logPort => rfl
+ · intro i
+ cases i with
+ | reg j =>
+ have he : j = 0 := Subsingleton.elim ..
+ subst j
+ simp only [s, scanBank, logPort, ISA.bank, Function.update_self, ite_true, x, digits]
+ | pub j => exact j.elim0
+ | persistent | work | logPort => rfl
+ · intro k hk
+ have hne : k ≠ ScanPort.depth := fun he => hk (.reg 0) he.symm
+ exact (Function.update_of_ne hne ..).symm
+ exact ⟨_, Nat.add_le_add_left ht _, runCopy.followedBy log⟩
+
+/-- The startup space is polynomial in word width, with the incoming
+engine storage and any previously supplied flag bits counted separately. -/
+theorem prepareDepth_bounded {w A : ℕ} (n : ℕ) (hn : n < 2^w) (persistent : Word w)
+ (rs : Regs Registers.R w) (flags : List Bool) (work : Stacks (Engine.Port K))
+ (hw : ∀ k, (work k).length ≤ A) :
+ ∃ t ≤ depthClock w, prepareDepth.BoundedRun (max (max w flags.length) A + depthClock w) t
+ (Function.update (scanBank n persistent rs flags work) ScanPort.depth [])
+ (scanBank n persistent rs flags work) := by
+ obtain ⟨t,ht,run⟩ := prepareDepth_runs n hn persistent rs flags work
+ refine ⟨t,ht,spaceRun_of_steps run fun k => Nat.add_le_add ?_ ht⟩
+ cases k with
+ | cursor j => exact (Registers.bank_length persistent rs flags j).trans (le_max_left ..)
+ | engine j => exact (hw j).trans (le_max_right ..)
+ | rows => exact (length_digits w n).le.trans ((le_max_left ..).trans (le_max_left ..))
+ | depth | scratch => exact Nat.zero_le _
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorDimensions.lean b/lean/OAI/Computability/VPVNP/RankCursorDimensions.lean
new file mode 100644
index 0000000000..b4e333d347
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorDimensions.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.RankCursorDepth
+import OAI.Computability.VPVNP.RankQueryGramReadSpace
+
+/-! # Initializing a rank scan from the two binary matrix dimensions
+
+Register one supplies the row count and register three supplies the column
+count. The machine adds and multiplies them to compute the inner scan bound
+`(n + m) * n`. The preceding logarithm pass initializes the balanced Schur
+depth from the row-count word.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch UniversalCountStack
+
+variable {K : Type} [DecidableEq K]
+
+/-- The two physical dimension words supplied by the caller. -/
+def dimensionRegs (w n m : ℕ) : Regs Registers.R w :=
+ Registers.initial (Fin.ofNat _ m) (Fin.ofNat _ n) 0
+
+private def dimensionsCode : RegCode Registers.R :=
+ .seq (.op (Registers.arg 2) .add (Registers.arg 1) (Registers.arg 3))
+ (.seq (.op (Registers.arg 2) .mul (Registers.arg 2) (Registers.arg 1))
+ (.copy (Registers.arg 3) (Registers.arg 2)))
+
+/-- Cursor registers after computing the inner index and its bound as the word product `(n + m)
+* n` in `w`-bit arithmetic. The outer register holds the word for `n`. -/
+def startRegs (w n m : ℕ) := dimensionsCode.exec (dimensionRegs w n m)
+
+private theorem arg_inj : Function.Injective Registers.arg := fun _ _ h => Fin.ext (congrArg (Fin.val : Fin Registers.R → ℕ) h)
+
+theorem startRegs_stores {w : ℕ} (n m : ℕ) (hadd : n+m < 2^w) (hmul : (n+m)*n < 2^w) :
+ Registers.Stores (startRegs w n m) ((n+m)*n) n ((n+m)*n) := by
+ let rs := dimensionRegs w n m
+ let sum := Arith.add.word (rs (Registers.arg 1)) (rs (Registers.arg 3))
+ let prod := Arith.mul.word sum (rs (Registers.arg 1))
+ have hn : n < 2^w := by omega
+ have hm : m < 2^w := by omega
+ have hstored := Registers.initial_stores (Fin.ofNat (2^w) m) (Fin.ofNat (2^w) n) (0 : Word w)
+ have hx : (rs (Registers.arg 1)).val = n := by
+ have h : (rs (Registers.arg 1)).val = (Fin.ofNat (2^w) n).val := hstored 1 (by decide)
+ exact h.trans (Nat.mod_eq_of_lt hn)
+ have hy : (rs (Registers.arg 3)).val = m := by
+ have h : (rs (Registers.arg 3)).val = (Fin.ofNat (2^w) m).val := hstored 3 (by decide)
+ exact h.trans (Nat.mod_eq_of_lt hm)
+ have hs : sum.val = n+m := by
+ change (Arith.add.word _ _).val = _
+ have h : Arith.add.eval (rs (Registers.arg 1)).val (rs (Registers.arg 3)).val < 2^w := by
+ change (rs (Registers.arg 1)).val + (rs (Registers.arg 3)).val < _
+ rwa [hx, hy]
+ have v := Arith.word_val .add _ _ h
+ change _ = (rs (Registers.arg 1)).val + (rs (Registers.arg 3)).val at v
+ rwa [hx, hy] at v
+ have hp : prod.val = (n+m)*n := by
+ change (Arith.mul.word _ _).val = _
+ have h : Arith.mul.eval sum.val (rs (Registers.arg 1)).val < 2^w := by
+ change sum.val * (rs (Registers.arg 1)).val < _
+ rwa [hs, hx]
+ have v := Arith.word_val .mul _ _ h
+ change _ = sum.val * (rs (Registers.arg 1)).val at v
+ rwa [hs, hx] at v
+ have hfinal : startRegs w n m =
+ Function.update (Function.update rs (Registers.arg 2) prod) (Registers.arg 3) prod := by
+ simp [startRegs, dimensionsCode, RegCode.exec, arg_inj.eq_iff, prod, sum, rs]
+ intro i hi
+ rw [hfinal]
+ by_cases h₂ : i = 2
+ · subst i; simpa [arg_inj.eq_iff, input] using hp
+ by_cases h₃ : i = 3
+ · subst i; simpa [input] using hp
+ rw [Function.update_of_ne (arg_inj.ne h₃), Function.update_of_ne (arg_inj.ne h₂)]
+ have h := hstored i hi
+ fin_cases i <;> first | exact hx | exact h | contradiction
+
+private def arithmeticPort (i : ISA.Port Registers.R 0) : ScanPort K := .cursor (.isa i)
+
+/-- Prepare the balanced-product depth from the row count and compute the inner scan bound from
+the two dimension registers. -/
+def initializeDimensions : FiniteRoutine (ScanPort K) :=
+ prepareDepth.followedBy (dimensionsCode.compile.onPorts arithmeticPort)
+
+/-- Step bound for computing the logarithmic depth and initializing the dimension registers
+before the first rank query. -/
+def startupClock (w : ℕ) := depthClock w + 5 * (100*(w+1)^2)
+
+/-- Stack-height bound during rank initialization, accounting for the work bank, the w-bit
+registers, and the existing flag stack. -/
+def startupSpace (A w flags : ℕ) := max (max w flags) A + startupClock w
+
+omit [DecidableEq K] in
+private theorem bank_length {w : ℕ} (n : ℕ) (persist : Word w) (rs : Regs Registers.R w)
+ (flags : List Bool) (work : Stacks (Engine.Port K)) (A : ℕ) (ha : ∀ i, (work i).length ≤ A)
+ (k : ScanPort K) : (scanBank n persist rs flags work [] k).length ≤ max (max w flags.length) A := by
+ cases k with
+ | cursor j => exact (Registers.bank_length persist rs flags j).trans (le_max_left ..)
+ | engine j => exact (ha j).trans (le_max_right ..)
+ | rows | depth => exact (length_digits ..).le.trans ((le_max_left ..).trans (le_max_left ..))
+ | scratch => exact Nat.zero_le _
+
+/-- From encoded row and column counts, prepare the cursor and Schur root
+constants and return the correct initial cursor registers. -/
+theorem initialize_bounded {w A : ℕ} (n m : ℕ) (hn : n < 2^w)
+ (persistent : Word w) (flags : List Bool) (work : Stacks (Engine.Port K))
+ (ha : ∀ i, (work i).length ≤ A) :
+ ∃ t ≤ startupClock w, initializeDimensions.BoundedRun (startupSpace A w flags.length) t
+ (Function.update (scanBank n persistent (dimensionRegs w n m) flags work) ScanPort.depth [])
+ (scanBank n persistent (startRegs w n m) flags work) := by
+ obtain ⟨t₁,h₁,depth⟩ := prepareDepth_bounded n hn persistent (dimensionRegs w n m) flags work ha
+ obtain ⟨t₂,h₂,arith⟩ := dimensionsCode.compile_runs Fin.elim0 persistent (dimensionRegs w n m)
+ change t₂ ≤ 5 * (100*(w+1)^2) at h₂
+ have run : (dimensionsCode.compile.onPorts (arithmeticPort (K := K))).Runs t₂
+ (scanBank n persistent (dimensionRegs w n m) flags work)
+ (scanBank n persistent (startRegs w n m) flags work) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (fun _ _ h => Registers.Port.isa.inj (ScanPort.cursor.inj h))
+ arith (fun _ => rfl) (fun _ => rfl)
+ intro k hk; cases k with
+ | cursor j => cases j with | isa i => exact (hk i rfl).elim | flag => rfl
+ | _ => rfl
+ have hd : max (max w flags.length) A + depthClock w ≤ startupSpace A w flags.length :=
+ Nat.add_le_add_left (Nat.le_add_right ..) _
+ have hr : (dimensionsCode.compile.onPorts (arithmeticPort (K := K))).BoundedRun (startupSpace A w flags.length) t₂
+ (scanBank n persistent (dimensionRegs w n m) flags work)
+ (scanBank n persistent (startRegs w n m) flags work) :=
+ spaceRun_of_steps run (fun k => Nat.add_le_add (bank_length n persistent _ flags work A ha k)
+ (h₂.trans (Nat.le_add_left ..)))
+ exact ⟨_, Nat.add_le_add h₁ h₂, (depth.enlarge hd).followedBy hr⟩
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorLoop.lean b/lean/OAI/Computability/VPVNP/RankCursorLoop.lean
new file mode 100644
index 0000000000..78155cc612
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorLoop.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.RankQueryStackCursor
+import OAI.Computability.VPVNP.StructuredStackLoop
+import OAI.Computability.VPVNP.StructuredStackRuns
+
+/-! # The physical descending scan for the rank query
+
+A successful coefficient query and cursor update leave one continuation bit.
+The loop requests the next pair when this bit is true and returns the rank
+already stored by the update when it is false. No loop bound or matrix
+dimension is part of the finite control.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape
+
+/-- The initial and continuing states of the rank scan carry a true flag. -/
+def State.continues : State → Bool
+ | .running .. => true
+ | .done _ => false
+
+/-- Invoke the coefficient-and-update routine at each true mark. Its normal
+return supplies the flag read by the next iteration. -/
+def scan {K : Type} (flag : K) (body : FiniteRoutine K) : FiniteRoutine K :=
+ .ofRoutine (Routine.popLoop flag id Routine.ret body.body)
+
+variable {K : Type} [DecidableEq K]
+
+/-- A physical step preserves the encoded cursor and advances it according
+to the coefficient zero test. This yields a complete finite run, with a
+bound uniform over every rectangular coefficient query. -/
+theorem scan_runs (flag : K) (body : FiniteRoutine K) (q : ℕ → ℕ → Bool) (Z B : ℕ)
+ (ready : State → Stacks K → Prop)
+ (hflag : ∀ state s, ready state s → s flag = [state.continues])
+ (hstep : ∀ u z s, ready (.running u z) s → ∃ k ≤ B, ∃ s',
+ body.Runs k (Function.update s flag []) s' ∧ ready (step q Z (.running u z)) s')
+ (state : State) (s : Stacks K) (hs : ready state s) :
+ ∃ k ≤ remaining Z state * (B+1) + 2, ∃ out,
+ ready (.done (answer q Z state)) out ∧ (scan flag body).Runs k s (Function.update out flag []) := by
+ induction state using (measure (remaining Z)).wf.induction generalizing s with
+ | h state ih =>
+ cases state with
+ | done r =>
+ have hr := Routine.Runs.popLoop_false_stop flag id Routine.ret body.body (hflag _ s hs) rfl
+ (Routine.runs_ret (Function.update s flag []))
+ exact ⟨2, by simp [remaining], s, hs, hr⟩
+ | running u z =>
+ have dec := remaining_decreases q Z u z
+ obtain ⟨k, hk, s', hh, hready⟩ := hstep u z s hs
+ obtain ⟨m, hm, out, hout, hrun⟩ := ih _ dec s' hready
+ have cost : 1+k+m ≤ remaining Z (.running u z) * (B+1) + 2 := by
+ have h := Nat.mul_le_mul_right (B+1) dec
+ rw [Nat.succ_mul] at h
+ omega
+ refine ⟨1+k+m, cost, out, ?_, ?_⟩
+ · rwa [answer_step] at hout
+ · exact Routine.Runs.popLoop_true_continue flag id Routine.ret body.body (hflag _ s hs) rfl hh hrun
+
+/-- With the Schur coefficients this control returns the ordinary rank over
+any field, including characteristic two. -/
+theorem matrix_scan_runs {F : Type*} [Field F] [DecidableEq F] {n m : ℕ}
+ (M : Matrix (Fin n) (Fin m) F) (get : ℕ → ℕ → F)
+ (hg : ∀ u z, get u z = ((rankPolynomial M).coeff u).coeff z)
+ (flag : K) (body : FiniteRoutine K) (B : ℕ)
+ (ready : State → Stacks K → Prop)
+ (hflag : ∀ state s, ready state s → s flag = [state.continues])
+ (hstep : ∀ u z s, ready (.running u z) s → ∃ k ≤ B, ∃ s',
+ body.Runs k (Function.update s flag []) s' ∧
+ ready (advance ((n+m)*n) u z (decide (get u z = 0))) s')
+ (s : Stacks K) (hs : ready (.running n ((n+m)*n)) s) :
+ ∃ k ≤ ((n+1)*((n+m)*n+1)) * (B+1) + 2, ∃ out, ready (.done M.rank) out ∧
+ (scan flag body).Runs k s (Function.update out flag []) := by
+ obtain ⟨k, hk, out, hout, hr⟩ := scan_runs flag body (fun u z => decide (get u z = 0))
+ ((n+m)*n) B ready hflag hstep _ s hs
+ rw [initial_answer M get hg] at hout
+ refine ⟨k, ?_, out, hout, hr⟩
+ simpa only [remaining, Nat.succ_mul, Nat.add_assoc] using hk
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorMachine.lean b/lean/OAI/Computability/VPVNP/RankCursorMachine.lean
new file mode 100644
index 0000000000..14b866ac4f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorMachine.lean
@@ -0,0 +1,113 @@
+import OAI.Computability.VPVNP.RankCursorCheck
+import OAI.Computability.VPVNP.RankQueryStackInterpretation
+
+/-! # Executing the outer rank scan
+
+Each request returns one scalar Schur coefficient, the zero test selects
+the cursor update, and the updated registers give the next request or the
+rank. Only the current field element and binary degree pair survive a step.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch
+
+variable {K : Type} [DecidableEq K] {w v b p e n m : ℕ}
+variable [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+/-- The control, including its loop, is independent of every size parameter. -/
+def rankMachine (query : FiniteRoutine (ScanPort K)) : FiniteRoutine (ScanPort K) :=
+ scan (.cursor .flag) (query.followedBy check)
+
+theorem initial_schur_answer [Fact (Irreducible (SliceArithmetic.modulus c))]
+ (M : Matrix (Fin n) (Fin m) (Scalar c)) :
+ let Z := (n+m)*n
+ answer (fun u z => decide (SchurKey.compute (weightedGramEntryCoeff M) u z = 0))
+ Z (.running n Z) = (M.map (Scalar.interpretation c)).rank := by
+ let Z := (n+m)*n
+ let q (u z : ℕ) := decide (SchurKey.compute (weightedGramEntryCoeff M) u z = 0)
+ change max (below q Z n) (row q n (Z+1)) = _
+ rw [below, ← peak_succ (fun u => row q u (Z+1)) n, ← Scalar.rank_correct c M]
+ simp [SchurKey.computeRank, scanRank, peak, row, q, Z]
+
+/-- The root-query contract uses the actual binary indices, field scalar
+encoding and live auxiliary matrix bank. -/
+def RootRead (query : FiniteRoutine (ScanPort K)) (Z w v n B : ℕ)
+ (value : ℕ → ℕ → Scalar c) (ready : Stacks K → Prop) : Prop :=
+ ∀ (u z : ℕ), u ≤ n → z ≤ Z → ∀ (persist : Word w) (rs : Regs Registers.R w) aux,
+ Registers.Stores rs Z u z → ready aux →
+ ∃ k ≤ B, ∃ aux', ready aux' ∧ query.Runs k (scanBank n persist rs [] (idle aux))
+ (scanBank n persist rs [] (yielded aux' (Engine.scalar v (value u z))))
+
+theorem advance_bounds (Z n u z : ℕ) (hu : u ≤ n) (hz : z ≤ Z) (zero : Bool) :
+ (advance Z u z zero).words 1 ≤ n ∧ (advance Z u z zero).words 2 ≤ Z := by
+ cases zero <;> by_cases h₁ : u=0 <;> by_cases h₂ : z=0 <;>
+ simp [advance, State.words, h₁, h₂] <;> omega
+
+theorem clear_flag (n : ℕ) (persist : Word w) (rs : Regs Registers.R w) (aux : Stacks K) (bit : Bool) :
+ Function.update (scanBank n persist rs [bit] (idle aux)) (.cursor .flag) [] =
+ scanBank n persist rs [] (idle aux) := by
+ funext k
+ cases k with | cursor k => cases k <;> rfl | _ => rfl
+
+/-- The physical run returns the rank in cursor register one. The input field
+is the irreducible polynomial-basis extension in which the matrix was encoded. -/
+theorem rankMachine_runs [Fact (Irreducible (SliceArithmetic.modulus c))]
+ (query : FiniteRoutine (ScanPort K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ (ready : Stacks K → Prop) (B : ℕ)
+ (hq : RootRead query ((n+m)*n) w v n B (SchurKey.compute (weightedGramEntryCoeff M)) ready)
+ (hwidth : (b+1)*control.wordFactor ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (hsize : max 1 (max n ((n+m)*n)) < 2^b)
+ (persist : Word w) (initialRegs : Regs Registers.R w) (aux : Stacks K) (haux : ready aux)
+ (hregs : Registers.Stores initialRegs ((n+m)*n) n ((n+m)*n)) :
+ let Z := (n+m)*n
+ ∃ k ≤ ((n+1)*(Z+1))*(B+checkClock w v e+1)+2, ∃ rs' aux',
+ ready aux' ∧ Registers.Stores rs' Z (M.map (Scalar.interpretation c)).rank 0 ∧
+ (rankMachine query).Runs k (scanBank n persist initialRegs [true] (idle aux))
+ (scanBank n persist rs' [] (idle aux')) := by
+ let Z := (n+m)*n
+ let val := SchurKey.compute (weightedGramEntryCoeff M)
+ let q (u z : ℕ) := decide (val u z = 0)
+ let good (st : State) (s : Stacks (ScanPort K)) : Prop :=
+ st.words 1 ≤ n ∧ st.words 2 ≤ Z ∧ ∃ rs a, ready a ∧ Registers.Stores rs Z (st.words 1) (st.words 2) ∧
+ s = scanBank n persist rs [st.continues] (idle a)
+ have flag (st : State) (s : Stacks (ScanPort K)) (hs : good st s) : s (.cursor .flag) = [st.continues] := by
+ obtain ⟨_,_,_,_,_,_,rfl⟩ := hs
+ rfl
+ have one (u z : ℕ) (s : Stacks (ScanPort K)) (hs : good (.running u z) s) :
+ ∃ k ≤ B+checkClock w v e, ∃ out,
+ (query.followedBy check).Runs k (Function.update s (.cursor .flag) []) out ∧ good (step q Z (.running u z)) out := by
+ obtain ⟨hu,hz,rs,a,ha,hreg,rfl⟩ := hs
+ change u ≤ n at hu
+ change z ≤ Z at hz
+ obtain ⟨k, hk, a', ha', hread⟩ := hq u z hu hz persist rs a hreg ha
+ have fit (i : Fin 8) : input Z u z (q u z) i < 2^b := by
+ have hqv : (q u z).toNat ≤ 1 := by cases q u z <;> decide
+ change max 1 (max n Z) < 2^b at hsize
+ fin_cases i <;> simp [input] <;> omega
+ obtain ⟨d, hd, rs', hcheck, hstore⟩ := check_runs hv n Z u z persist rs a' (val u z)
+ hwidth fit hreg
+ rw [clear_flag]
+ exact ⟨k+d, Nat.add_le_add hk hd, _, hread.followedBy hcheck,
+ (advance_bounds Z n u z hu hz (q u z)).1, (advance_bounds Z n u z hu hz (q u z)).2,
+ rs', a', ha', hstore, rfl⟩
+ have init : good (.running n Z) (scanBank n persist initialRegs [true] (idle aux)) :=
+ ⟨le_rfl,le_rfl,initialRegs,aux,haux,hregs,rfl⟩
+ obtain ⟨k, hk, out, hout, hrun⟩ := scan_runs (.cursor .flag) (query.followedBy check) q Z
+ (B+checkClock w v e) good flag one _ _ init
+ have hrank : answer q Z (.running n Z) = (M.map (Scalar.interpretation c)).rank := initial_schur_answer M
+ rw [hrank] at hout
+ obtain ⟨_,_,outRegs,a,ha,hst,rfl⟩ := hout
+ refine ⟨k, ?_, outRegs,a,ha,hst, ?_⟩
+ · simpa only [remaining, Nat.succ_mul, Nat.add_assoc] using hk
+ · simpa only [rankMachine, clear_flag] using hrun
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorPorts.lean b/lean/OAI/Computability/VPVNP/RankCursorPorts.lean
new file mode 100644
index 0000000000..94da72fec5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorPorts.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.RankCursorRegisters
+import OAI.Computability.VPVNP.RankQueryStackEngineSpec
+
+/-! # Stack layout of a complete rank scan
+
+The arithmetic cursor and the Schur engine use separate banks. The row
+count and balanced product depth supply two constant fields of every root
+request. The scalar output is read from the engine's result port.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch
+
+/-- Ports of the rectangular rank scan. The cursor and Schur engine have separate stack banks
+alongside the row count, product depth, and copy scratch. -/
+inductive ScanPort (K : Type) where
+ | cursor (p : Registers.Port)
+ | engine (p : Engine.Port K)
+ | rows | depth | scratch
+ deriving DecidableEq, Fintype
+
+variable {K : Type} {w : ℕ}
+
+/-- A bank with independently specified engine and arithmetic registers. -/
+def scanBank (n : ℕ) (persistent : Word w) (rs : Regs Registers.R w)
+ (flags : List Bool) (work : Stacks (Engine.Port K)) (scratch : List Bool := []) : Stacks (ScanPort K)
+ | .cursor k => Registers.bank persistent rs flags k
+ | .engine k => work k
+ | .rows => UniversalCountStack.digits w n
+ | .depth => UniversalCountStack.digits w (Nat.clog 2 n)
+ | .scratch => scratch
+
+/-- All frame and query stacks are empty between requests; the auxiliary
+engine bank retains the matrix and field description. -/
+def idle (aux : Stacks K) : Stacks (Engine.Port K) :=
+ Engine.store (fun _ => []) (fun _ => []) [] [] aux
+
+/-- At the scalar check boundary the Schur result occupies its result port. -/
+def yielded (aux : Stacks K) (bits : List Bool) : Stacks (Engine.Port K) :=
+ Engine.store (fun _ => []) (fun _ => []) [] bits aux
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorRegisters.lean b/lean/OAI/Computability/VPVNP/RankCursorRegisters.lean
new file mode 100644
index 0000000000..4976a851c4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorRegisters.lean
@@ -0,0 +1,240 @@
+import OAI.Computability.VPVNP.RankQueryStackCursor
+import OAI.Computability.VPVNP.EvaluatorRadixSpace
+
+/-!
+# A reusable physical cursor for the rank scan
+
+A scalar coefficient supplies one zero-test bit. The cursor reads that bit,
+computes its next two indices, copies them into its input registers, and
+emits a new loop marker. A zero marker stops the enclosing loop with the
+rank in input register one. A one marker calls the scalar query again using
+the updated indices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor.Registers
+
+open Dispatch BurstRAM RAMTape TapeWord
+
+/-- Number of cursor word registers, comprising eight inputs, six outputs, and the scratch
+registers of the control program. -/
+abbrev R := 14 + control.scratch
+/-- Address of one of the eight input words in the rank cursor’s physical register file. -/
+abbrev arg := Code.inReg control.scratch
+/-- Address of one of the six output words produced by the rank cursor control program. -/
+abbrev resultReg := Code.outReg control.scratch
+
+/-- The cursor’s word-machine ports together with the flag stack for the zero test and loop
+decision. -/
+inductive Port where
+ | isa (k : ISA.Port R 0) | flag
+ deriving DecidableEq, Fintype
+
+/-- Extend a word-machine stack bank with the supplied list of cursor flags. -/
+def frame (s : Stacks (ISA.Port R 0)) (flags : List Bool) : Stacks Port
+ | .isa k => s k
+ | .flag => flags
+
+variable {w : ℕ}
+
+/-- Initial cursor stacks containing the persistent word, the specified register file, empty
+machine scratch, and the supplied flag stack. -/
+def bank (persistent : Word w) (rs : Regs R w) (flags : List Bool) :=
+ frame (ISA.bank Fin.elim0 persistent rs []) flags
+
+/-- The loop bit associated with a cursor state, true while coefficient queries continue and
+false when the rank has been returned. -/
+def continuing : State → Bool
+ | .running _ _ => true
+ | .done _ => false
+
+/-- Input register zero is overwritten by the next test. Register three
+retains the fixed column bound, and registers four through seven stay zero. -/
+def Stores (rs : Regs R w) (Z u z : ℕ) : Prop :=
+ ∀ i : Fin 8, i ≠ 0 → (rs (arg i)).val = input Z u z false i
+
+private def setFlag (zero : Bool) : RegCode R := .lit (arg 0) zero.toNat
+
+private def loadFlag : FiniteRoutine Port :=
+ .ofRoutine (Routine.popCase .flag (Routine.halt false)
+ (((setFlag false).compile).onPorts .isa).body (((setFlag true).compile).onPorts .isa).body)
+
+private def roll : RegCode R := .seq (.copy (arg 1) (resultReg 1)) (.copy (arg 2) (resultReg 2))
+
+private def emitFlag : FiniteRoutine Port := .ofRoutine
+ (Routine.popCase (.isa (.work 0)) (Routine.halt false) (Routine.push .flag false) (Routine.push .flag true))
+
+/-- One fixed step, independent of register width, rank bounds, or the
+coefficient oracle. The two indices are ready for the next iteration. -/
+def next : FiniteRoutine Port :=
+ (((loadFlag.followedBy ((control.physical control.scratch).onPorts .isa)).followedBy
+ (roll.compile.onPorts .isa)).followedBy
+ ((ISA.compareRegs .eq (resultReg 0) (arg 4)).onPorts .isa)).followedBy emitFlag
+
+/-- Step bound for one cursor update, including the zero-test input, control instructions,
+index copies, and the next loop bit. -/
+def clock (w : ℕ) :=
+ (3 + (control.emitFields control.scratch (List.finRange 6)).length)*(100*(w+1)^2) + 20*w+13
+
+theorem wordFactor_eq : control.wordFactor = 68 := by decide
+
+theorem register_count : R = 78 := by decide
+
+theorem clock_eq (w : ℕ) : clock w = 7300*(w+1)^2+20*w+13 := by
+ have hs : (control.emitFields control.scratch (List.finRange 6)).length = 70 := by decide
+ rw [clock, hs]
+ ring
+
+private theorem run_isa (r : Machine R) {t : ℕ} {s out : Stacks (ISA.Port R 0)} (flags : List Bool)
+ (h : r.Runs t s out) : (r.onPorts .isa).Runs t (frame s flags) (frame out flags) := by
+ apply r.runs_onPorts_framed (ports := Port.isa) (s := frame s flags) (u := frame out flags) (fun _ _ he => Port.isa.inj he) h
+ (fun _ => rfl) (fun _ => rfl)
+ intro p hp
+ cases p with
+ | isa k => exact (hp k rfl).elim
+ | flag => rfl
+
+private theorem load_runs (zero : Bool) (persistent : Word w) (rs : Regs R w) (tail : List Bool) :
+ ∃ t ≤ 100*(w+1)^2+1, loadFlag.Runs t (bank persistent rs (zero :: tail))
+ (bank persistent ((setFlag zero).exec rs) tail) := by
+ obtain ⟨n,hn,hr⟩ := (setFlag zero).compile_runs Fin.elim0 persistent rs
+ have hf := run_isa _ tail hr
+ have hu : Function.update (bank persistent rs (zero::tail)) Port.flag tail = bank persistent rs tail := by
+ funext k; cases k <;> rfl
+ refine ⟨n+1, Nat.add_le_add_right (by simpa only [setFlag, RegCode.length, Nat.one_mul] using hn) 1, ?_⟩
+ cases zero
+ · apply Routine.runs_popCase_false Port.flag _ _ _ (s := bank persistent rs (false :: tail)) rfl
+ rw [hu]; exact hf
+ · apply Routine.runs_popCase_true Port.flag _ _ _ (s := bank persistent rs (true :: tail)) rfl
+ rw [hu]; exact hf
+
+private theorem emit_runs (persistent : Word w) (rs : Regs R w) (b : Bool) (tail : List Bool) :
+ emitFlag.Runs 2 (frame (Function.update (ISA.bank Fin.elim0 persistent rs []) (.work 0) [b]) tail)
+ (bank persistent rs (b::tail)) := by
+ let s := frame (Function.update (ISA.bank Fin.elim0 persistent rs []) (.work 0) [b]) tail
+ have hu : Function.update s (.isa (.work 0)) [] = bank persistent rs tail := by
+ funext k
+ cases k with
+ | flag => rfl
+ | isa p =>
+ by_cases h : p = .work 0 <;> simp [s, bank, frame, h]; rfl
+ have hf : Function.update (bank persistent rs tail) .flag (b :: bank persistent rs tail .flag) =
+ bank persistent rs (b::tail) := by funext k; cases k <;> rfl
+ have push := Routine.runs_push .flag b (bank persistent rs tail)
+ rw [hf] at push
+ cases b
+ · apply Routine.runs_popCase_false (Port.isa (.work 0)) _ _ _ (s := s) (tail := []) rfl
+ rw [hu]; exact push
+ · apply Routine.runs_popCase_true (Port.isa (.work 0)) _ _ _ (s := s) (tail := []) rfl
+ rw [hu]; exact push
+
+private theorem arg_injective : Function.Injective arg := fun _ _ h => Fin.ext (congrArg (fun j : Fin R => j.val) h)
+
+private theorem result_ne_arg (i : Fin 6) (j : Fin 8) : resultReg i ≠ arg j := by
+ intro h
+ have hv := congrArg Fin.val h
+ change 8+i.val = j.val at hv
+ omega
+
+private theorem roll_result (rs : Regs R w) (i : Fin 6) : roll.exec rs (resultReg i) = rs (resultReg i) := by
+ simp [roll, RegCode.exec, Function.update_of_ne (result_ne_arg i 1), Function.update_of_ne (result_ne_arg i 2)]
+
+/-- The next flag and register bank exactly implement the abstract transition.
+In the halting case the first index is the answer and the second is zero. -/
+theorem next_runs {p : ℕ} (Z u z : ℕ) (zero : Bool) (persistent : Word w) (rs : Regs R w)
+ (tail : List Bool) (hw : (p+1)*control.wordFactor ≤ w)
+ (he : ∀ i, input Z u z zero i < 2^p) (hr : Stores rs Z u z) :
+ let v := advance Z u z zero
+ ∃ t ≤ clock w, ∃ out : Regs R w,
+ next.Runs t (bank persistent rs (zero::tail)) (bank persistent out (continuing v :: tail)) ∧
+ Stores out Z (v.words 1) (v.words 2) := by
+ let loaded := (setFlag zero).exec rs
+ let v := advance Z u z zero
+ have hpow : p ≤ w := by
+ have hn : 1 ≤ control.wordFactor := by decide
+ exact (Nat.le_succ p).trans ((Nat.le_mul_of_pos_right _ hn).trans hw)
+ have hload (i : Fin 8) : (loaded (arg i)).val = input Z u z zero i := by
+ by_cases hi : i = 0
+ · subst i
+ change (Fin.ofNat (2^w) zero.toNat).val = zero.toNat
+ exact Nat.mod_eq_of_lt ((he 0).trans_le (Nat.pow_le_pow_right (by decide) hpow))
+ · rw [show loaded (arg i) = rs (arg i) from Function.update_of_ne (arg_injective.ne hi) .., hr i hi]
+ fin_cases i <;> first | rfl | contradiction
+ obtain ⟨a,ha,h₁⟩ := load_runs zero persistent rs tail
+ obtain ⟨b,hb,mid,hm,keep,hout⟩ := control.physical_runs _ p le_rfl _ loaded hw he hload Fin.elim0 persistent
+ have h₂ := run_isa _ tail hm
+ have hmid (i : Fin 6) : (mid (resultReg i)).val = v.words i := (hout i).trans (congrFun (control_eq ..) i)
+ obtain ⟨c,hc,hroll⟩ := roll.compile_runs Fin.elim0 persistent mid
+ let out := roll.exec mid
+ have h₃ := run_isa _ tail hroll
+ have houtarg (i : Fin 8) : (out (arg i)).val = if i = 2 then v.words 2 else
+ if i = 1 then v.words 1 else input Z u z zero i := by
+ by_cases hi₂ : i = 2
+ · subst i
+ simp [out, roll, RegCode.exec, Function.update_of_ne (result_ne_arg 2 1), hmid]
+ · by_cases hi₁ : i = 1
+ · subst i
+ simp [out, roll, RegCode.exec, arg_injective.eq_iff, hi₂, hmid]
+ · simp [out, roll, RegCode.exec, arg_injective.eq_iff, hi₁, hi₂, keep, hload]
+ have hs : Stores out Z (v.words 1) (v.words 2) := by
+ intro i hi
+ rw [houtarg]
+ fin_cases i <;> first | rfl | contradiction
+ let bit := Comparison.Op.eq.eval (out (resultReg 0)) (out (arg 4))
+ have hbit : bit = continuing v := by
+ have hz : (out (arg 4)).val = 0 := hs 4 (by decide)
+ have htag : (out (resultReg 0)).val = v.words 0 := (congrArg Fin.val (roll_result mid 0)).trans (hmid 0)
+ simp only [bit, Comparison.Op.eval, Fin.ext_iff, hz, htag]
+ cases v <;> rfl
+ have h₄ := run_isa _ tail (ISA.compareRegs_run Comparison.Op.eq (resultReg 0) (arg 4)
+ Fin.elim0 persistent out [])
+ have h₅ := emit_runs persistent out bit tail
+ have hfull := (((h₁.followedBy h₂).followedBy h₃).followedBy h₄).followedBy h₅
+ rw [hbit] at hfull
+ refine ⟨_, ?_, out, hfull, hs⟩
+ change c ≤ 2*(100*(w+1)^2) at hc
+ unfold clock
+ rw [Nat.add_mul]
+ omega
+
+/-- Place a legal cursor in registers at the start of a scan. Only the two
+indices and the column bound need nonzero words. -/
+def initial (Z u z : Word w) : Regs R w :=
+ Function.update (Function.update (Function.update (fun _ => 0) (arg 1) u) (arg 2) z) (arg 3) Z
+
+theorem initial_stores (Z u z : Word w) : Stores (initial Z u z) Z.val u.val z.val := by
+ intro i hi
+ fin_cases i <;> first | contradiction | simp [initial, arg_injective.eq_iff, input]
+
+theorem bank_length (persistent : Word w) (rs : Regs R w) (flags : List Bool) (k : Port) :
+ (bank persistent rs flags k).length ≤ max w flags.length := by
+ cases k with
+ | flag => exact Nat.le_max_right ..
+ | isa p =>
+ apply le_trans _ (Nat.le_max_left w flags.length)
+ cases p with
+ | reg i | pub i => exact (length_wordBits _).le
+ | persistent => exact (length_wordBits _).le
+ | work i => exact Nat.zero_le _
+ | logPort k => cases k <;> exact Nat.zero_le _
+
+/-- Every intermediate physical stack respects the same quadratic working
+space allowance, even when an arbitrary flag tail is carried through. -/
+theorem next_space {p : ℕ} (Z u z : ℕ) (zero : Bool) (persistent : Word w) (rs : Regs R w)
+ (tail : List Bool) (hw : (p+1)*control.wordFactor ≤ w) (he : ∀ i, input Z u z zero i < 2^p)
+ (hr : Stores rs Z u z) {n : ℕ} {q : Option next.State} {s : Stacks Port}
+ (run : StackRuns next.body.standalone n (some next.body.entry) (bank persistent rs (zero::tail)) q s)
+ (k : Port) : (s k).length ≤ max w (tail.length+1) + clock w := by
+ obtain ⟨t,ht,_,hdone,_⟩ := next_runs Z u z zero persistent rs tail hw he hr
+ have hn := EvaluatorRadixDivision.ticks_le_at_return hdone (by rfl) run
+ exact (EvaluatorRadixDivision.run_length run k).trans
+ (Nat.add_le_add (bank_length persistent rs (zero::tail) k) (hn.trans ht))
+
+end RankQuery.Stack.Cursor.Registers
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorSchur.lean b/lean/OAI/Computability/VPVNP/RankCursorSchur.lean
new file mode 100644
index 0000000000..6257108dbe
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorSchur.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.RankCursorSchurFields
+import OAI.Computability.VPVNP.RankQueryStackEngineRun
+import OAI.Computability.VPVNP.RankQueryStackScan
+import OAI.Computability.VPVNP.ParseOracleResources
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-!
+# Calling the Schur coefficient machine from the rank cursor
+
+One request stages the six root fields and invokes the shared Schur engine.
+The resulting scalar occupies the engine result port in its native
+polynomial-basis representation. The cursor registers, dimension words and
+scratch retain their ready values for the following zero test.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch UniversalCountStack
+
+variable {K : Type} [DecidableEq K]
+
+/-- The instruction table stages a root from cursor registers and calls the
+same engine at every matrix dimension and every bidegree. -/
+def rootQuery (a : Engine.Actions K) : FiniteRoutine (ScanPort K) :=
+ loadRoot.followedBy ((Engine.machine a).onPorts ScanPort.engine)
+
+/-- Step bound for loading one Schur root and evaluating its coefficient, using the arity and
+recursion-depth bounds of the Schur expansion. -/
+def rootQueryClock (n U Z B w v e : ℕ) :=
+ loadClock w + ((5 + 6*SchurKey.arityBound n U Z)^(Nat.clog 2 U + 4 + Nat.clog 2 n + 1)*
+ Engine.stepBudget B w v e + 1)
+
+/-- Stack-height bound for staging the root fields and executing the Schur recursion for a
+single coefficient. -/
+def rootQuerySpace (n U A B w v e : ℕ) :=
+ max (max w A + loadClock w) (Engine.runSpace A (Nat.clog 2 U + 4 + Nat.clog 2 n) B w v e)
+
+/-- Bounding all three numerical query dimensions by `s` bits gives a
+single exponential number of engine transitions. -/
+theorem rootQueryClock_le (n U Z B w v e s : ℕ) (hn : n ≤ 2^s) (hu : U ≤ 2^s) (hz : Z ≤ 2^s) :
+ rootQueryClock n U Z B w v e ≤
+ loadClock w + (2^((2*s+8)*(2*s+5))*Engine.stepBudget B w v e + 1) := by
+ exact Nat.add_le_add_left (Nat.add_le_add_right
+ (Nat.mul_le_mul_right _ (SchurKey.clock_le_exp n U Z s hn hu hz)) _) _
+
+/-- Only logarithms of the matrix size and outer degree enter the height of
+the suspended Schur frames. -/
+theorem rootQuerySpace_le (n U A B w v e s : ℕ) (hn : n ≤ 2^s) (hu : U ≤ 2^s) :
+ rootQuerySpace n U A B w v e ≤
+ max (max w A + loadClock w) (Engine.runSpace A (2*s+4) B w v e) := by
+ have h₁ := Nat.clog_le_of_le_pow hn
+ have h₂ := Nat.clog_le_of_le_pow hu
+ have hd : Nat.clog 2 U + 4 + Nat.clog 2 n ≤ 2*s+4 := by omega
+ exact max_le_max le_rfl (Nat.add_le_add_right
+ (max_le_max le_rfl (max_le_max le_rfl (Nat.mul_le_mul_right _ hd))) _)
+
+variable {n U Z p e w v A B : ℕ} {c : SliceArithmetic.Vector p e}
+variable {a : Engine.Actions K} {entry : Entry n (Scalar c)}
+variable {ready : Stacks K → Prop} {pending : SchurKey n U Z → Stacks K → Prop}
+
+omit [DecidableEq K] in
+private theorem outer_length (persistent : Word w) (rs : Regs Registers.R w) (work : Stacks (Engine.Port K))
+ (k : ScanPort K) (outside : ∀ j, ScanPort.engine j ≠ k) :
+ (scanBank n persistent rs [] work [] k).length ≤ w := by
+ cases k with
+ | engine j => exact (outside j rfl).elim
+ | cursor j => simpa only [scanBank, List.length_nil, Nat.max_zero] using Registers.bank_length persistent rs [] j
+ | rows | depth => exact (length_digits ..).le
+ | scratch => exact Nat.zero_le _
+
+omit [DecidableEq K] in
+private theorem idle_length (persistent : Word w) (rs : Regs Registers.R w) (aux : Stacks K)
+ (ha : ∀ k, (aux k).length ≤ A) (k : ScanPort K) :
+ (scanBank n persistent rs [] (idle aux) [] k).length ≤ max w A := by
+ by_cases he : ∃ j, ScanPort.engine j = k
+ · obtain ⟨j,rfl⟩ := he
+ cases j with
+ | aux i => exact (ha i).trans (Nat.le_max_right ..)
+ | result | condition => exact Nat.zero_le _
+ | frame i => cases i <;> exact Nat.zero_le _
+ · exact (outer_length persistent rs (idle aux) k (not_exists.mp he)).trans (Nat.le_max_left ..)
+
+/-- Install any certified run of the same engine. The combined bound depends
+on the engine's space certificate separately from its number of transitions. -/
+theorem routeRoot_bounded {cap ticks : ℕ} (persistent : Word w) (rs : Regs Registers.R w)
+ (u : Limit U) (z : Limit Z) (hregs : Registers.Stores rs Z u.val z.val)
+ (aux out : Stacks K) (ha : ∀ k, (aux k).length ≤ A) (coeff : Scalar c)
+ (engine : (Engine.machine a).BoundedRun cap ticks
+ (Engine.atControl w v (.enter (SchurKey.root (n := n) u z)) ([] : List (Engine.F n U Z c)) aux)
+ (Engine.atControl w v (.returned coeff) ([] : List (Engine.F n U Z c)) out)) :
+ (rootQuery a).BoundedRun (max (max w A + loadClock w) cap) (loadClock w + ticks)
+ (scanBank n persistent rs [] (idle aux))
+ (scanBank n persistent rs [] (yielded out (Engine.scalar v coeff))) := by
+ let space := max (max w A + loadClock w) cap
+ let begin := Engine.atControl w v (.enter (SchurKey.root (n := n) u z)) ([] : List (Engine.F n U Z c)) aux
+ let finish := Engine.atControl w v (.returned coeff) ([] : List (Engine.F n U Z c)) out
+ let start := scanBank n persistent rs [] begin
+ have hload := loadRoot_runs (c := c) (v := v) persistent rs u z hregs aux (n := n)
+ have load : loadRoot.BoundedRun space (loadClock w) (scanBank n persistent rs [] (idle aux)) start :=
+ spaceRun_of_steps hload (fun k =>
+ (Nat.add_le_add_right (idle_length persistent rs aux ha k) _).trans (le_max_left ..))
+ have bounded : (Engine.machine a).BoundedRun space ticks begin finish :=
+ engine.mono_cap (le_max_right ..)
+ have outside (k : ScanPort K) (hk : ∀ j, ScanPort.engine j ≠ k) : (start k).length ≤ space :=
+ (outer_length persistent rs begin k hk).trans <|
+ (le_max_left w A).trans ((Nat.le_add_right ..).trans (le_max_left ..))
+ have call := bounded.onPorts (ports := ScanPort.engine) (fun _ _ => ScanPort.engine.inj) start outside
+ have hout : installStacks ScanPort.engine start finish =
+ scanBank n persistent rs [] (yielded out (Engine.scalar v coeff)) := by
+ apply installStacks_frame (fun _ _ => ScanPort.engine.inj) (fun k => ?_)
+ · intro k hk; cases k with | engine j => exact (hk j rfl).elim | _ => rfl
+ · cases k with
+ | frame j => cases j <;> rfl
+ | aux | condition | result => rfl
+ rw [installStacks_eq (fun _ _ => ScanPort.engine.inj) start begin (fun _ => rfl), hout] at call
+ exact load.followedBy call
+
+variable [Fact p.Prime] [NeZero e]
+
+/-- The returned scalar is the requested formal coefficient of the reverse
+characteristic polynomial. Time and stack bounds include the initial word
+copies and the engine call. The external Schur actions enter through their
+individual physical execution contracts. -/
+theorem rootQuery_bounded
+ (spec : Engine.Contracts a (SchurKey.program (U := U) (Z := Z) entry)
+ w v B (SchurKey.arityBound n U Z) ready pending)
+ (hcap : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (M : Matrix (Fin n) (Fin n) (Polynomial (Scalar c)))
+ (he : ∀ i j k, entry i j k = (M i j).coeff k)
+ (persistent : Word w) (rs : Regs Registers.R w) (u : Limit U) (z : Limit Z)
+ (hregs : Registers.Stores rs Z u.val z.val) (aux : Stacks K) (haux : ready aux) :
+ ∃ t ≤ rootQueryClock n U Z B w v e, ∃ out, ready out ∧
+ (rootQuery a).BoundedRun (rootQuerySpace n U A B w v e) t (scanBank n persistent rs [] (idle aux))
+ (scanBank n persistent rs [] (yielded out (Engine.scalar v ((M.charpolyRev.coeff u.val).coeff z.val)))) := by
+ obtain ⟨ticks, ht, out, ho, engine⟩ := Engine.eval_root spec hcap M he u z aux haux
+ exact ⟨_, Nat.add_le_add_left ht _, out, ho,
+ routeRoot_bounded persistent rs u z hregs aux out (hcap aux haux) _ engine⟩
+
+/-- Normal-return interface for callers that need the clock and scalar. -/
+theorem rootQuery_runs
+ (spec : Engine.Contracts a (SchurKey.program (U := U) (Z := Z) entry)
+ w v B (SchurKey.arityBound n U Z) ready pending)
+ (hcap : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (M : Matrix (Fin n) (Fin n) (Polynomial (Scalar c)))
+ (he : ∀ i j k, entry i j k = (M i j).coeff k)
+ (persistent : Word w) (rs : Regs Registers.R w) (u : Limit U) (z : Limit Z)
+ (hregs : Registers.Stores rs Z u.val z.val) (aux : Stacks K) (haux : ready aux) :
+ ∃ t ≤ rootQueryClock n U Z B w v e, ∃ out, ready out ∧
+ (rootQuery a).Runs t (scanBank n persistent rs [] (idle aux))
+ (scanBank n persistent rs [] (yielded out (Engine.scalar v ((M.charpolyRev.coeff u.val).coeff z.val)))) := by
+ obtain ⟨t,ht,out,ho,run⟩ := rootQuery_bounded spec hcap M he persistent rs u z hregs aux haux
+ exact ⟨t,ht,out,ho,run.runs⟩
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorSchurFields.lean b/lean/OAI/Computability/VPVNP/RankCursorSchurFields.lean
new file mode 100644
index 0000000000..331eefb691
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorSchurFields.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.RankCursorPorts
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-!
+# Loading the six Schur root fields from the rank cursor
+
+The product root consists of its zero tag, balanced-product depth, zero
+block start, matrix row count and the two cursor indices. The loader copies
+these six words from the cursor bank into the live query frame, preserving
+all input registers. The matrix dimensions and both degrees are stack data.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch UniversalCountStack
+
+variable {K : Type}
+
+private def reg (i : Fin 8) : ScanPort K := .cursor (.isa (.reg (Registers.arg i)))
+
+private def source : Fin 6 → ScanPort K :=
+ ![reg 4, .depth, reg 4, .rows, reg 1, reg 2]
+
+private def dest (i : Fin 6) : ScanPort K := .engine (.frame (.inl (Fin.castAdd 3 i).succ))
+
+private theorem dest_inj : Function.Injective (@dest K) := by
+ intro i j h
+ have he := Sum.inl.inj (Engine.Port.frame.inj (ScanPort.engine.inj h))
+ exact Fin.ext (Nat.succ.inj (congrArg Fin.val he))
+
+private theorem src_ne_dest (i j : Fin 6) : source i ≠ dest (K := K) j := by
+ fin_cases i <;> intro h <;> cases h
+
+private theorem src_ne_tmp (i : Fin 6) : source i ≠ (ScanPort.scratch : ScanPort K) := by
+ fin_cases i <;> intro h <;> cases h
+
+private def copies : List (Fin 6) → FiniteRoutine (ScanPort K)
+ | [] => .ret
+ | i :: rest => (SuccessorFields.prependCopy (source i) (dest i) .scratch).followedBy (copies rest)
+
+/-- Copy the product tag, depth, block start, row count, and two scan indices into the six
+fields of the Schur root request. -/
+def loadRoot : FiniteRoutine (ScanPort K) := copies (List.finRange 6)
+
+/-- Step bound for the six copies of w-bit words that initialize a Schur root request. -/
+def loadClock (w : ℕ) := 6*(5*w+2)+1
+
+private noncomputable def staged (s : Stacks (ScanPort K)) (todo : List (Fin 6)) :=
+ installStacks dest s (fun i => if i ∈ todo then [] else s (source i))
+
+variable [DecidableEq K]
+
+private theorem copies_runs (s : Stacks (ScanPort K)) (todo : List (Fin 6)) (hn : todo.Nodup)
+ (w : ℕ) (hw : ∀ i, (s (source i)).length = w) (ht : s .scratch = []) :
+ (copies todo).Runs (todo.length*(5*w+2)+1) (staged s todo) (staged s []) := by
+ induction todo with
+ | nil => simpa only [copies, FiniteRoutine.ret, FiniteRoutine.ofRoutine, FiniteRoutine.Runs, List.length_nil, Nat.zero_mul, Nat.zero_add] using Routine.runs_ret (staged s [])
+ | cons i rest ih =>
+ have hin := (List.nodup_cons.mp hn).1
+ have hsource : staged s (i :: rest) (source i) = s (source i) :=
+ installStacks_outside _ _ (fun j => (src_ne_dest i j).symm)
+ have htmp : staged s (i :: rest) .scratch = [] :=
+ (installStacks_outside s _ (fun j (h : dest j = .scratch) => by cases h)).trans ht
+ have hdest : staged s (i :: rest) (dest i) = [] := by
+ simp [staged, installStacks_at dest_inj]
+ have hwrite : Function.update (staged s (i :: rest)) (dest i) (s (source i)) = staged s rest := by
+ rw [staged, installStacks_update dest_inj]
+ apply congrArg (installStacks dest s)
+ funext j
+ by_cases h : j = i
+ · subst j; simp [hin]
+ · simp [h]
+ have h := SuccessorFields.prependCopy_runs (source i) (dest i) .scratch (src_ne_dest i i)
+ (src_ne_tmp i) (by intro he; cases he) (staged s (i :: rest)) htmp
+ rw [hsource, hw, hdest, List.append_nil, hwrite] at h
+ have hrun := h.followedBy (ih (List.nodup_cons.mp hn).2)
+ rw [show (i::rest).length*(5*w+2)+1 = (5*w+2) + (rest.length*(5*w+2)+1) by
+ simp only [List.length_cons, Nat.succ_mul]; omega]
+ exact hrun
+
+private theorem wordBits_digits {w : ℕ} (r : Word w) : wordBits r = digits w r.val :=
+ congrArg wordBits (Fin.ext (Nat.mod_eq_of_lt r.isLt).symm)
+
+omit [DecidableEq K] in
+private theorem source_word {n U Z w : ℕ} (persistent : Word w) (rs : Regs Registers.R w)
+ (u : Limit U) (z : Limit Z) (hregs : Registers.Stores rs Z u.val z.val) (aux : Stacks K)
+ (i : Fin 6) :
+ scanBank n persistent rs [] (idle aux) [] (source i) =
+ digits w ((SchurKey.root (n := n) u z).words i) := by
+ have h0 : (rs (Registers.arg 4)).val = 0 := hregs 4 (by decide)
+ have hu : (rs (Registers.arg 1)).val = u.val := hregs 1 (by decide)
+ have hz : (rs (Registers.arg 2)).val = z.val := hregs 2 (by decide)
+ fin_cases i <;> first
+ | rfl
+ | exact (wordBits_digits _).trans (congrArg (digits w) h0)
+ | exact (wordBits_digits _).trans (congrArg (digits w) hu)
+ | exact (wordBits_digits _).trans (congrArg (digits w) hz)
+
+/-- Normal return puts the engine directly at its typed root-entry bank, with
+the input registers, descriptor bank and empty scratch preserved. -/
+theorem loadRoot_runs {n U Z w v p e : ℕ} {c : SliceArithmetic.Vector p e}
+ (persistent : Word w) (rs : Regs Registers.R w) (u : Limit U) (z : Limit Z)
+ (hregs : Registers.Stores rs Z u.val z.val) (aux : Stacks K) :
+ loadRoot.Runs (loadClock w) (scanBank n persistent rs [] (idle aux))
+ (scanBank n persistent rs [] (Engine.atControl w v
+ (.enter (SchurKey.root (n := n) u z)) ([] : List (Engine.F n U Z c)) aux)) := by
+ let s := scanBank n persistent rs [] (idle aux)
+ have src := source_word persistent rs u z hregs aux (n := n)
+ have hw (i : Fin 6) : (s (source i)).length = w := by simp only [s, src, length_digits]
+ have h := copies_runs s (List.finRange 6) (List.nodup_finRange 6) w hw rfl
+ have start : staged s (List.finRange 6) = s := by
+ apply installStacks_eq dest_inj
+ intro i; simp [s, dest, scanBank, idle, Engine.store]
+ have finish : staged s [] = scanBank n persistent rs [] (Engine.atControl w v
+ (.enter (SchurKey.root (n := n) u z)) ([] : List (Engine.F n U Z c)) aux) := by
+ apply installStacks_frame dest_inj
+ · intro i
+ change (Engine.fields w [] (SchurKey.root (n := n) u z) [] [] [] (Fin.castAdd 3 i).succ) =
+ (if i ∈ ([] : List (Fin 6)) then [] else s (source i))
+ simp only [Engine.fields, Fin.cons_succ, Fin.append_left, List.not_mem_nil, ↓reduceIte]
+ exact (src i).symm
+ · intro k hout
+ cases k with
+ | cursor | rows | depth | scratch => rfl
+ | engine k => cases k with
+ | result | condition | aux => rfl
+ | frame f => cases f with
+ | inr j => rfl
+ | inl j =>
+ fin_cases j <;> first
+ | rfl
+ | exact (hout 0 rfl).elim
+ | exact (hout 1 rfl).elim
+ | exact (hout 2 rfl).elim
+ | exact (hout 3 rfl).elim
+ | exact (hout 4 rfl).elim
+ | exact (hout 5 rfl).elim
+ rw [start, finish, List.length_finRange] at h
+ exact h
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorSchurSpace.lean b/lean/OAI/Computability/VPVNP/RankCursorSchurSpace.lean
new file mode 100644
index 0000000000..82f435d2c1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorSchurSpace.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.RankCursorSchur
+import OAI.Computability.VPVNP.RankQueryStackEngineSpace
+
+/-! # Rank-cursor queries with separate time and space for scalar entries
+
+A streamed matrix-entry computation can use exponential time and polynomial
+space. The caller retains the descriptor's own stack cap, while its time
+bound enters the running time of the Schur recursion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch
+
+/-- Step bound for one Schur coefficient query, charging the entry descriptor’s time allowance
+at each recursive engine step. -/
+def readClock (n U Z Bd B w v e : ℕ) :=
+ loadClock w + (SchurKey.clock n U Z * Engine.boundedStepTime Bd B w v e + 1)
+
+/-- Stack-height bound for one Schur coefficient query using the entry descriptor’s separate
+peak-space allowance S. -/
+def readSpace (n U S A B w v e : ℕ) :=
+ max (max w A + loadClock w) (Engine.boundedSpace S A (Nat.clog 2 U+4+Nat.clog 2 n) B w v e)
+
+theorem readClock_le (n U Z Bd B w v e s : ℕ) (hn : n ≤ 2^s) (hu : U ≤ 2^s) (hz : Z ≤ 2^s) :
+ readClock n U Z Bd B w v e ≤
+ loadClock w + (2^((2*s+8)*(2*s+5)) * Engine.boundedStepTime Bd B w v e + 1) :=
+ Nat.add_le_add_left (Nat.add_le_add_right (Nat.mul_le_mul_right _ (SchurKey.clock_le_exp n U Z s hn hu hz)) _) _
+
+theorem readSpace_le (n U S A B w v e s : ℕ) (hn : n ≤ 2^s) (hu : U ≤ 2^s) :
+ readSpace n U S A B w v e ≤
+ max (max w A + loadClock w) (Engine.boundedSpace S A (2*s+4) B w v e) := by
+ have h₁ := Nat.clog_le_of_le_pow hn
+ have h₂ := Nat.clog_le_of_le_pow hu
+ have hd : Nat.clog 2 U + 4 + Nat.clog 2 n ≤ 2*s+4 := by omega
+ exact max_le_max le_rfl (max_le_max le_rfl (Nat.add_le_add_right
+ (max_le_max le_rfl (max_le_max le_rfl (Nat.mul_le_mul_right _ hd))) _))
+
+variable {K : Type} [DecidableEq K] {n U Z p e w v A B Bd S : ℕ} {c : SliceArithmetic.Vector p e}
+variable [Fact p.Prime] [NeZero e] {a : Engine.Actions K} {entry : Entry n (Scalar c)}
+variable {ready : Stacks K → Prop} {pending : SchurKey n U Z → Stacks K → Prop}
+
+/-- Use the descriptor time only in the total clock. Its certified stack cap,
+together with the live register and return stack caps, suffices throughout. -/
+theorem rootQuery_separate
+ (spec : Engine.Contracts a (SchurKey.program (U := U) (Z := Z) entry) w v B
+ (SchurKey.arityBound n U Z) ready pending Bd)
+ (desc : Engine.DescribeBounded a (SchurKey.program (U := U) (Z := Z) entry) w v Bd S
+ (Nat.clog 2 U+4+Nat.clog 2 n) ready)
+ (ha : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (M : Matrix (Fin n) (Fin n) (Polynomial (Scalar c))) (he : ∀ i j k, entry i j k = (M i j).coeff k)
+ (persistent : Word w) (rs : Regs Registers.R w) (u : Limit U) (z : Limit Z)
+ (hregs : Registers.Stores rs Z u.val z.val) (aux : Stacks K) (haux : ready aux) :
+ ∃ t ≤ readClock n U Z Bd B w v e, ∃ out, ready out ∧
+ (rootQuery a).BoundedRun (readSpace n U S A B w v e) t (scanBank n persistent rs [] (idle aux))
+ (scanBank n persistent rs [] (yielded out (Engine.scalar v ((M.charpolyRev.coeff u.val).coeff z.val)))) := by
+ obtain ⟨ticks, ht, out, ho, engine⟩ := Engine.eval_root_bounded spec desc ha M he u z aux haux
+ exact ⟨_, Nat.add_le_add_left ht _, out, ho,
+ routeRoot_bounded persistent rs u z hregs aux out (ha aux haux) _ engine⟩
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankCursorSpaceLoop.lean b/lean/OAI/Computability/VPVNP/RankCursorSpaceLoop.lean
new file mode 100644
index 0000000000..b19407d801
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankCursorSpaceLoop.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.RankCursorLoop
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-!
+# Bounded stack space across the descending rank scan
+
+The loop reuses the coefficient-and-cursor workspace at each bidegree. Its
+peak stack length is the same cap certified for one iteration and the
+ready banks, independently of the total number of requests.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape UniversalCountStack
+
+variable {K : Type} [DecidableEq K]
+
+private def dispatch (body : FiniteRoutine K) : Option Bool → Option (Unit ⊕ (Unit ⊕ body.State))
+ | none => none
+ | some false => some (.inr (.inl ()))
+ | some true => some (.inr (.inr body.body.entry))
+
+private theorem pop_flag (flag : K) (body : FiniteRoutine K) (s : Stacks K) (b : Bool)
+ (hs : s flag = [b]) :
+ StackStep (scan flag body).body.standalone (some (scan flag body).body.entry) s
+ (dispatch body (some b)) (Function.update s flag []) := by
+ have h : StackStep (scan flag body).body.standalone (some (scan flag body).body.entry) s
+ (dispatch body (s flag).head?) (Function.update s flag (s flag).tail) :=
+ StackStep.pop rfl
+ simpa only [hs, List.head?_cons, List.tail_cons] using h
+
+/-- A simultaneous time and per-stack space certificate for the entire
+scan. The returned register state encodes the maximum nonzero outer degree. -/
+theorem scan_boundedRun (flag : K) (body : FiniteRoutine K) (q : ℕ → ℕ → Bool) (Z B cap : ℕ)
+ (ready : State → Stacks K → Prop)
+ (hflag : ∀ state s, ready state s → s flag = [state.continues])
+ (hsafe : ∀ state s, ready state s → ∀ k, (s k).length ≤ cap)
+ (hstep : ∀ u z s, ready (.running u z) s → ∃ k ≤ B, ∃ s',
+ body.BoundedRun cap k (Function.update s flag []) s' ∧ ready (step q Z (.running u z)) s')
+ (state : State) (s : Stacks K) (hs : ready state s) :
+ ∃ k ≤ remaining Z state * (B+1) + 2, ∃ out,
+ ready (.done (answer q Z state)) out ∧ (scan flag body).BoundedRun cap k s (Function.update out flag []) := by
+ induction state using (measure (remaining Z)).wf.induction generalizing s with
+ | h state ih =>
+ have hcap := hsafe state s hs
+ have pop := pop_flag flag body s state.continues (hflag state s hs)
+ cases state with
+ | done r =>
+ have hclear (k : K) : (Function.update s flag [] k).length ≤ cap := by
+ by_cases hk : k = flag <;> simp [hk, hcap]
+ refine ⟨2, by simp [remaining], s, hs, SpaceRun.cons hcap pop ?_⟩
+ exact .cons hclear (.goto rfl) (.nil _ _ hclear)
+ | running u z =>
+ have dec := remaining_decreases q Z u z
+ obtain ⟨k, hk, s', hb, hready⟩ := hstep u z s hs
+ obtain ⟨m, hm, out, hout, rest⟩ := ih _ dec s' hready
+ have linked := hb.linkRoutine (scan flag body).body (Sum.inr ∘ Sum.inr)
+ (some (scan flag body).body.entry) (fun _ => rfl)
+ refine ⟨(k+m)+1, ?_, out, ?_, SpaceRun.cons hcap pop (linked.trans rest)⟩
+ · have h := Nat.mul_le_mul_right (B+1) dec
+ rw [Nat.succ_mul] at h
+ omega
+ · rwa [answer_step] at hout
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankMinors.lean b/lean/OAI/Computability/VPVNP/RankMinors.lean
new file mode 100644
index 0000000000..e290c998a0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankMinors.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.ShiftedPairing
+
+/-!
+# Support of maximal minors
+
+Appendix D.2 of *VP and VNP differ over every field* uses the fact that the
+nonzero minors of order equal to the rank have independently chosen row and
+column bases. All minors of larger order vanish.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+open Set
+open Set.powersetCard
+open VPVNP.Crossing
+
+variable {K : Type*} [Field K] {n m q : ℕ}
+
+private theorem det_submatrix_ne_zero_iff (M : Matrix (Fin n) (Fin m) K)
+ (hq : M.rank = q) (rows : Fin q → Fin n) (cols : Fin q → Fin m) :
+ (M.submatrix rows cols).det ≠ 0 ↔
+ LinearIndependent K (M.row ∘ rows) ∧ LinearIndependent K (M.col ∘ cols) := by
+ let restrict := LinearMap.funLeft K K cols
+ constructor
+ · intro h
+ exact ⟨LinearIndependent.of_comp restrict (Matrix.linearIndependent_rows_of_det_ne_zero h),
+ LinearIndependent.of_comp (LinearMap.funLeft K K rows)
+ (Matrix.linearIndependent_cols_of_det_ne_zero h)⟩
+ · rintro ⟨hrows, hcols⟩
+ -- The selected rows span the whole row space before restriction to the columns.
+ have hspan : Submodule.span K (range (M.row ∘ rows)) = Submodule.span K (range M.row) := by
+ apply Submodule.eq_of_le_of_finrank_eq
+ · exact Submodule.span_mono (range_comp_subset_range ..)
+ · rw [← M.rank_eq_finrank_span_row, hq]
+ simpa [Set.finrank] using (linearIndependent_iff_card_eq_finrank_span.mp hrows).symm
+ -- Restricting both equal spaces to the selected columns preserves equality.
+ have hrank : (M.submatrix rows cols).rank = (M.submatrix id cols).rank := by
+ rw [Matrix.rank_eq_finrank_span_row, Matrix.rank_eq_finrank_span_row]
+ have hs := congrArg (Submodule.map restrict) hspan
+ rw [Submodule.map_span, Submodule.map_span, ← range_comp, ← range_comp] at hs
+ exact congrArg (fun S : Submodule K (Fin q → K) => Module.finrank K S) hs
+ have hfull : (M.submatrix rows cols).rank = Fintype.card (Fin q) := by
+ rw [hrank, Matrix.rank_eq_finrank_span_cols]
+ exact (linearIndependent_iff_card_eq_finrank_span.mp hcols).symm
+ have h : LinearIndependent K (M.submatrix rows cols).row := by
+ apply linearIndependent_iff_card_eq_finrank_span.mpr
+ exact hfull.symm.trans (Matrix.rank_eq_finrank_span_row _)
+ exact ((Matrix.isUnit_iff_isUnit_det _).mp (Matrix.linearIndependent_rows_iff_isUnit.mp h)).ne_zero
+
+/-- At the rank of the matrix, the nonzero minors are precisely the pairs of
+independent row and column selections. -/
+theorem compound_ne_zero_iff (M : Matrix (Fin n) (Fin m) K) (hq : M.rank = q)
+ (I : powersetCard (Fin n) q) (J : powersetCard (Fin m) q) :
+ compound q M I J ≠ 0 ↔
+ LinearIndependent K (fun i : I.val => M.row i.val) ∧
+ LinearIndependent K (fun j : J.val => M.col j.val) := by
+ rw [compound, det_submatrix_ne_zero_iff M hq]
+ apply and_congr
+ · exact linearIndependent_equiv (R := K) (f := fun i : I.val => M.row i.val)
+ (orderIsoOfFin I).toEquiv
+ · exact linearIndependent_equiv (R := K) (f := fun j : J.val => M.col j.val)
+ (orderIsoOfFin J).toEquiv
+
+/-- Every minor of order strictly greater than the matrix rank vanishes. -/
+theorem compound_eq_zero_of_rank_lt (M : Matrix (Fin n) (Fin m) K) (hq : M.rank < q)
+ (I : powersetCard (Fin n) q) (J : powersetCard (Fin m) q) : compound q M I J = 0 := by
+ by_contra h
+ let rows := ofFinEmbEquiv.symm I
+ let cols := ofFinEmbEquiv.symm J
+ have hrank : (M.submatrix rows cols).rank = Fintype.card (Fin q) :=
+ (Matrix.linearIndependent_rows_of_det_ne_zero
+ (show (M.submatrix rows cols).det ≠ 0 from h)).rank_matrix
+ have hle := M.rank_submatrix_le rows cols
+ rw [hrank, Fintype.card_fin] at hle
+ exact hq.not_ge hle
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankPolynomial.lean b/lean/OAI/Computability/VPVNP/RankPolynomial.lean
new file mode 100644
index 0000000000..c2541d9a37
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankPolynomial.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.ShiftedPairing
+import Mathlib.LinearAlgebra.Matrix.Charpoly.Coeff
+
+/-!
+# The determinant used for rank queries
+
+Appendix D.2 of *VP and VNP differ over every field* forms a weighted Gram matrix
+over a polynomial ring. The coefficient of degree `q` in its reverse characteristic
+polynomial is a signed sum of squares of minors of the original rectangular matrix.
+Each square is tagged by the sum of its one-based row and column indices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+open Polynomial Set VPVNP.Crossing
+open scoped Matrix
+
+variable {K : Type*} [CommRing K] {n m q : ℕ}
+
+/-- Sum of the one-based indices selected for a minor. -/
+def indexWeight (I : powersetCard (Fin n) q) : ℕ :=
+ ∑ i ∈ I.val, (i.val + 1)
+
+theorem indexWeight_eq_sum (I : powersetCard (Fin n) q) :
+ indexWeight I = ∑ i : Fin q, ((powersetCard.ofFinEmbEquiv.symm I i).val + 1) := by
+ rw [indexWeight, ← Finset.sum_coe_sort]
+ exact ((powersetCard.orderIsoOfFin I).toEquiv.sum_comp fun i => i.val.val + 1).symm
+
+/-- The diagonal tagging the one-based index of each row or column. -/
+noncomputable def weightDiagonal (K : Type*) [CommRing K] (n : ℕ) :
+ Matrix (Fin n) (Fin n) (Polynomial K) :=
+ Matrix.diagonal fun i => X ^ (i.val + 1)
+
+/-- The matrix `D₁(z) M D₂(z) Mᵀ`, with constant entries of `M` embedded by `C`. -/
+noncomputable def weightedGram (M : Matrix (Fin n) (Fin m) K) :
+ Matrix (Fin n) (Fin n) (Polynomial K) :=
+ weightDiagonal K n * M.map C * weightDiagonal K m * (M.map C)ᵀ
+
+/-- The determinant `det(1 - u G(z))` as a polynomial in `u` with coefficients in `K[z]`. -/
+noncomputable def rankPolynomial (M : Matrix (Fin n) (Fin m) K) :
+ Polynomial (Polynomial K) :=
+ (weightedGram M).charpolyRev
+
+private theorem scaled_minor (M : Matrix (Fin n) (Fin m) K)
+ (I : powersetCard (Fin n) q) (J : powersetCard (Fin m) q) :
+ compound q (weightDiagonal K n * M.map C * weightDiagonal K m) I J =
+ X ^ (indexWeight I + indexWeight J) * C (compound q M I J) := by
+ let r := powersetCard.ofFinEmbEquiv.symm I
+ let c := powersetCard.ofFinEmbEquiv.symm J
+ let A := M.submatrix r c
+ have restrictWeights :
+ (weightDiagonal K n * M.map C * weightDiagonal K m).submatrix r c =
+ Matrix.diagonal (fun i : Fin q => X ^ ((r i).val + 1)) *
+ C.mapMatrix A * Matrix.diagonal (fun j : Fin q => X ^ ((c j).val + 1)) := by
+ ext i j
+ simp [weightDiagonal, A]
+ change ((weightDiagonal K n * M.map C * weightDiagonal K m).submatrix r c).det =
+ X ^ (indexWeight I + indexWeight J) * C A.det
+ rw [restrictWeights, Matrix.det_mul, Matrix.det_mul, Matrix.det_diagonal,
+ Matrix.det_diagonal, ← C.map_det, Finset.prod_pow_eq_pow_sum, Finset.prod_pow_eq_pow_sum,
+ indexWeight_eq_sum I, indexWeight_eq_sum J, pow_add]
+ ac_rfl
+
+/-- Cauchy–Binet expands each principal minor of the weighted Gram matrix. -/
+theorem weightedGram_minor (M : Matrix (Fin n) (Fin m) K) (I : powersetCard (Fin n) q) :
+ compound q (weightedGram M) I I =
+ ∑ J : powersetCard (Fin m) q,
+ X ^ (indexWeight I + indexWeight J) * C (compound q M I J) ^ 2 := by
+ rw [weightedGram, compound_mul, Matrix.mul_apply, compound_transpose]
+ refine Finset.sum_congr rfl fun J _ => ?_
+ rw [scaled_minor, Matrix.transpose_apply, pow_two, mul_assoc]
+ have hmap : compound q (M.map C) I J = C (compound q M I J) :=
+ (C.map_det (M.submatrix (powersetCard.ofFinEmbEquiv.symm I)
+ (powersetCard.ofFinEmbEquiv.symm J))).symm
+ rw [hmap]
+
+/-- Each reverse characteristic coefficient is the signed trace of the corresponding
+compound matrix, also when the requested minor size exceeds the dimension. -/
+theorem charpolyRev_coeff_eq_sum_compound {n : ℕ} {R : Type*} [CommRing R]
+ (A : Matrix (Fin n) (Fin n) R) (q : ℕ) :
+ A.charpolyRev.coeff q =
+ (-1) ^ q * ∑ I : Set.powersetCard (Fin n) q, compound q A I I := by
+ classical
+ have hrev : A.charpolyRev = (1 + (X : R[X]) • (-A).map C).det := by
+ simp only [Matrix.charpolyRev, sub_eq_add_neg]
+ congr 2
+ rw [Matrix.map_neg C (map_neg C) A, smul_neg]
+ rw [hrev, Matrix.coeff_det_one_add_X_smul_eq_sum_minors]
+ simp only [Matrix.submatrix_neg, Pi.neg_apply, Matrix.det_neg, Fintype.card_coe, Finset.mul_sum]
+ rw [Finset.sum_subtype _ (fun _ => Finset.mem_powersetCard_univ) _]
+ apply Finset.sum_congr rfl
+ intro I _
+ rw [I.property]
+ congr 1
+ exact (Matrix.det_submatrix_equiv_self (Set.powersetCard.orderIsoOfFin I).toEquiv
+ (A.submatrix Subtype.val Subtype.val)).symm
+
+/-- The coefficient identity of Appendix D.2 over the coefficient ring, in every
+characteristic. For `q` larger than a matrix dimension the sum of minors is empty. -/
+theorem rankPolynomial_coeff (M : Matrix (Fin n) (Fin m) K) (q : ℕ) :
+ (rankPolynomial M).coeff q = (-1) ^ q * ∑ I : powersetCard (Fin n) q,
+ ∑ J : powersetCard (Fin m) q,
+ X ^ (indexWeight I + indexWeight J) * C (compound q M I J) ^ 2 := by
+ rw [rankPolynomial, charpolyRev_coeff_eq_sum_compound]
+ simp_rw [weightedGram_minor]
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankPrefixRead.lean b/lean/OAI/Computability/VPVNP/RankPrefixRead.lean
new file mode 100644
index 0000000000..f3d5667d04
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankPrefixRead.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.MacaulayReadRouter
+import OAI.Computability.VPVNP.CoordinateQueries
+
+/-!
+# Macaulay readers for prefix rank queries
+
+The greedy row scan reads a row prefix at its original addresses. The
+column scan uses the same reader with row and column ports interchanged.
+Renaming these ports preserves the exact instruction trace, including its
+time and live stack-height bounds.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead
+
+open RAMTape
+
+variable {K : Type} {p e n m w v B S : ℕ} {c : SliceArithmetic.Vector p e}
+
+private def swapAddress : Port K → Port K
+ | .row => .col
+ | .col => .row
+ | .result => .result
+ | .aux k => .aux k
+
+private theorem swapAddress_involutive : Function.Involutive (swapAddress (K := K)) := by
+ intro k; cases k <;> rfl
+
+/-- The coefficient routine of the transposed matrix, with its usual caller
+convention. Only the physical addresses of its row and column ports change. -/
+def transpose (read : FiniteRoutine (Port K)) : FiniteRoutine (Port K) :=
+ read.onPorts swapAddress
+
+/-- Retain the first `r` rows of a matrix of encoded scalars. -/
+abbrev prefixMatrix {R : Type*} (A : Matrix (Fin n) (Fin m) R) (r : ℕ) (hr : r ≤ n) :=
+ RankQuery.prefixRows A r hr
+
+/-- Applying any scalar interpretation before or after restricting to the
+prefix yields exactly the matrix in the greedy rank formula. -/
+theorem map_prefixMatrix {R F : Type*} (A : Matrix (Fin n) (Fin m) R) (r : ℕ) (hr : r ≤ n)
+ (f : R → F) :
+ (prefixMatrix A r hr).map f = RankQuery.prefixRows (A.map f) r hr := rfl
+
+/-- On the column scan the interpreted matrix is transposed before taking
+the row prefix. -/
+theorem map_prefixMatrix_transpose {R F : Type*} (A : Matrix (Fin n) (Fin m) R) (r : ℕ) (hr : r ≤ m)
+ (f : R → F) :
+ (prefixMatrix A.transpose r hr).map f = RankQuery.prefixRows (A.map f).transpose r hr := rfl
+
+variable [DecidableEq K] {read : FiniteRoutine (Port K)} {M : Matrix (Fin n) (Fin m) (Scalar c)}
+ {ready : Stacks K → Prop}
+
+/-- Every original entry query gives one transpose query with exactly the
+same cost, final auxiliary bank, and peak storage allowance. -/
+theorem CorrectSpace.transpose (h : CorrectSpace read M w v B S ready) :
+ CorrectSpace (MacaulayRead.transpose read) M.transpose w v B S ready := by
+ intro i j aux hs
+ obtain ⟨t, ht, out, ho, run⟩ := h j i aux hs
+ refine ⟨t, ht, out, ho, ?_⟩
+ apply FiniteRoutine.BoundedRun.framed swapAddress_involutive.injective run
+ · intro k
+ have hh := run.initial_cap (swapAddress k)
+ cases k <;> exact hh
+ · intro k; cases k <;> rfl
+ · intro k; cases k <;> rfl
+ · intro k hk
+ exact (hk (swapAddress k) (swapAddress_involutive k)).elim
+
+/-- The ordinal of a row in a prefix is already its address in the original
+matrix. No instructions or additional stack cells are required. -/
+theorem CorrectSpace.prefixMatrix (h : CorrectSpace read M w v B S ready) (r : ℕ) (hr : r ≤ n) :
+ CorrectSpace read (prefixMatrix M r hr) w v B S ready :=
+ fun i j aux ok => h (Fin.castLE hr i) j aux ok
+
+/-- The complete calling convention used for prefix ranks of the transpose. -/
+theorem CorrectSpace.transpose_prefix (h : CorrectSpace read M w v B S ready) (r : ℕ) (hr : r ≤ m) :
+ CorrectSpace (MacaulayRead.transpose read) (MacaulayRead.prefixMatrix M.transpose r hr) w v B S ready :=
+ h.transpose.prefixMatrix r hr
+
+/-- The concrete three-way reader also accepts each transpose prefix with
+the bounds established for the routed equation, affine, and power arms. -/
+theorem reader_transpose_prefix
+ {arms : MacaulayRowDispatch.Kind → FiniteRoutine (Bus K)}
+ {leafReady : Stacks (Work K) → Prop}
+ (h : CorrectSpace (reader arms) M w v B S leafReady) (r : ℕ) (hr : r ≤ m) :
+ CorrectSpace (transpose (reader arms)) (MacaulayRead.prefixMatrix M.transpose r hr) w v B S leafReady :=
+ h.transpose_prefix r hr
+
+end RankQuery.Stack.MacaulayRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankPrefixTemplate.lean b/lean/OAI/Computability/VPVNP/RankPrefixTemplate.lean
new file mode 100644
index 0000000000..021cb43fac
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankPrefixTemplate.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.RankCursorPorts
+import OAI.Computability.VPVNP.RankQueryStackGramInitialization
+
+/-! # Supplying a variable row prefix to the determinant interpreter
+
+The outer rank cursor and the Schur interpreter read the same dimension
+from three places. All other startup stacks come from one reusable
+matrix, field and reader template.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch UniversalCountStack
+
+variable {K : Type} {p e : ℕ}
+
+/-- Ports for a row-prefix rank scan whose Schur engine obtains Gram entries from the
+underlying matrix reader. -/
+abbrev PrefixPort (K : Type) := ScanPort (GramEngine.Aux K)
+
+/-- Select the three ports that receive the variable row-prefix length, namely the row-count
+stack, cursor input one, and Gram-engine register seven. -/
+def prefixDynamic : PrefixPort K → Bool
+ | .rows => true
+ | .cursor (.isa (.reg i)) => decide (i = Registers.arg 1)
+ | .engine (.aux (.inl (.inl (.reg i)))) => decide (i.val = 7)
+ | _ => false
+
+/-- Initial stacks for the rank of an n-row prefix with m columns, with the loop flag set, the
+Gram engine idle, and the product-depth stack empty. -/
+def prefixRawBank [DecidableEq K] (w v n m : ℕ) (c : SliceArithmetic.Vector p e)
+ (base : Stacks K) : Stacks (PrefixPort K) :=
+ Function.update
+ (scanBank n (0 : Word w) (Registers.initial (Fin.ofNat _ m) (Fin.ofNat _ n) 0)
+ [true] (idle (GramEngine.initial w v n m c base))) .depth []
+
+/-- Substitution of the physical prefix-length word into the template gives
+the complete initial bank, including the empty balanced-depth stack. -/
+theorem prefixRawBank_eq [DecidableEq K] (w v n m : ℕ) (c : SliceArithmetic.Vector p e)
+ (base : Stacks K) (h : PrefixPort K) : prefixRawBank w v n m c base h =
+ if prefixDynamic h then digits w n else prefixRawBank w v 0 m c base h := by
+ cases h with
+ | rows | depth | scratch => rfl
+ | cursor q =>
+ cases q with
+ | flag => rfl
+ | isa a =>
+ cases a with
+ | pub i => exact i.elim0
+ | persistent | work | logPort => rfl
+ | reg i =>
+ have h₃ : Registers.arg 1 ≠ Registers.arg 3 := by decide
+ have h₂ : Registers.arg 1 ≠ Registers.arg 2 := by decide
+ by_cases hi : i = Registers.arg 1
+ · subst i
+ change wordBits (Registers.initial (Fin.ofNat _ m) (Fin.ofNat _ n) 0 (Registers.arg 1)) = _
+ simp [Registers.initial, prefixDynamic, h₃, h₂, digits]
+ · change wordBits (Registers.initial (Fin.ofNat _ m) (Fin.ofNat _ n) 0 i) =
+ if decide (i = Registers.arg 1) then digits w n else
+ wordBits (Registers.initial (Fin.ofNat _ m) (0 : Word w) 0 i)
+ simp [Registers.initial, hi, Function.update]
+ | engine q =>
+ cases q with
+ | frame j => cases j <;> rfl
+ | condition | result => rfl
+ | aux a =>
+ rcases a with (a | z) | extra
+ · cases a with
+ | pub i => exact i.elim0
+ | persistent | work | logPort => rfl
+ | reg i =>
+ change wordBits (if i.val = 7 then (Fin.ofNat _ n : Word w) else 0) =
+ if decide (i.val = 7) then digits w n else
+ wordBits (if i.val = 7 then (Fin.ofNat _ 0 : Word w) else 0)
+ by_cases hi : i.val = 7 <;> simp [hi, digits]
+ · rfl
+ · cases extra <;> rfl
+
+theorem prefixRawBank_length [DecidableEq K] {w v n m A : ℕ} (c : SliceArithmetic.Vector p e)
+ {ready : Stacks K → Prop} (base : Stacks K) (hr : ready base)
+ (ha : ∀ s, ready s → ∀ i, (s i).length ≤ A) (hn : n < 2^w) (hm : m < 2^w)
+ (i : PrefixPort K) : (prefixRawBank w v n m c base i).length ≤ w+v+e+e*v+A+1 := by
+ have h := GramEngine.ready_length (GramEngine.initial_ready (c := c) (v := v) base hr hn hm) ha
+ cases i with
+ | cursor q =>
+ exact (Registers.bank_length (0 : Word w) _ [true] q).trans (by simp; omega)
+ | engine q =>
+ cases q with
+ | aux a => exact (h a).trans (Nat.le_succ _)
+ | result | condition => exact Nat.zero_le _
+ | frame j => cases j <;> exact Nat.zero_le _
+ | rows => exact (length_digits w n).le.trans (by omega)
+ | depth | scratch => exact Nat.zero_le _
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankPrefixWorkspace.lean b/lean/OAI/Computability/VPVNP/RankPrefixWorkspace.lean
new file mode 100644
index 0000000000..3ffcb57f13
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankPrefixWorkspace.lean
@@ -0,0 +1,280 @@
+import OAI.Computability.VPVNP.RankCoordinateRegisters
+import OAI.Computability.VPVNP.SliceArithmeticCallCopies
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+import OAI.Computability.VPVNP.SpaceRunMonotone
+
+/-!
+# Reusing the rank workspace across prefix queries
+
+Each call copies its fixed template into private work stacks. Designated
+ports receive the live prefix-length word from register four. On return the
+selected result word replaces register three, and every work port is cleared
+before the next query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.PrefixWorkspace
+
+open RAMTape BurstRAM Dispatch UniversalCountStack SliceArithmetic
+
+/-- Auxiliary ports of a prefix-rank call, with separate template and working stacks for each
+callee port and one scratch stack for copies. -/
+inductive Aux (H : Type) where
+ | template (h : H) | work (h : H) | scratch
+ deriving DecidableEq, Fintype
+
+/-- The five prefix-search word registers together with the private workspace used for calls to
+the rank machine. -/
+abbrev Port (H : Type) := PrefixWords.Port (Aux H)
+
+variable {H : Type}
+
+/-- Initialize the template and working stacks from two banks, leaving the copy scratch empty. -/
+def auxBank (template work : Stacks H) : Stacks (Aux H)
+ | .template h => template h
+ | .work h => work h
+ | .scratch => []
+
+/-- The complete stack bank for a prefix-rank call, with the supplied template, working stacks,
+and five word registers. -/
+def bank {w : ℕ} (template work : Stacks H) (rs : Regs 5 w) :=
+ PrefixWords.bank (auxBank template work) rs
+
+/-- The caller stack holding the working copy of a particular port of the rank machine. -/
+def workPort (h : H) : Port H := .inr (.work h)
+
+private def scratch : Port H := .inr .scratch
+
+private def reg (i : Fin 5) : Port H := .inl (.reg i)
+
+private def source (dynamic : H → Bool) (h : H) : Port H :=
+ if dynamic h then reg 4 else .inr (.template h)
+
+/-- Contents of a working stack before a rank call. Dynamic ports receive the prefix word in
+register four, and the others receive their template stacks. -/
+def prepared {w : ℕ} (dynamic : H → Bool) (template : Stacks H) (rs : Regs 5 w) (h : H) :=
+ if dynamic h then wordBits (rs 4) else template h
+
+variable [Fintype H]
+
+private noncomputable def plan (dynamic : H → Bool) : List (Port H × Port H) :=
+ Finset.univ.toList.map (fun h => (source dynamic h, workPort h))
+
+private noncomputable def workPorts : List (Port H) := Finset.univ.toList.map workPort
+
+/-- Populate every working port from the prefix word or its template stack according to the
+dynamic-port predicate. -/
+noncomputable def copyIn (dynamic : H → Bool) : FiniteRoutine (Port H) := CallCopies.copyPlan scratch (plan dynamic)
+
+omit [Fintype H] in
+private theorem workPort_injective : Function.Injective (workPort (H := H)) :=
+ fun _ _ he => Aux.work.inj (Sum.inr.inj he)
+
+omit [Fintype H] in
+private theorem source_ne_work (dynamic : H → Bool) (i j : H) : source dynamic i ≠ workPort j := by
+ unfold source; split <;> intro h <;> cases h
+
+private theorem plan_dest (dynamic : H → Bool) : (plan dynamic).map Prod.snd = workPorts := by
+ simp only [plan, workPorts, List.map_map, Function.comp_def]
+
+private theorem plan_src (dynamic : H → Bool) : (plan dynamic).map Prod.fst = Finset.univ.toList.map (source dynamic) := by
+ simp only [plan, List.map_map, Function.comp_def]
+
+private theorem valid (dynamic : H → Bool) : CallCopies.Valid scratch (plan dynamic) := by
+ unfold CallCopies.Valid
+ rw [plan_dest, plan_src]
+ refine ⟨(Finset.nodup_toList _).map workPort_injective, ?_, ?_, ?_⟩
+ · intro p hp hd
+ obtain ⟨h, _, rfl⟩ := List.mem_map.mp hp
+ obtain ⟨j, _, hj⟩ := List.mem_map.mp hd
+ exact source_ne_work dynamic h j hj.symm
+ · intro hp
+ obtain ⟨h, _, he⟩ := List.mem_map.mp hp
+ unfold source at he
+ split at he <;> cases he
+ · intro hp
+ obtain ⟨h, _, he⟩ := List.mem_map.mp hp
+ cases he
+
+/-- Step bound for copying one input stack of length at most M into each of the rank workspace
+ports. -/
+def copyClock (H : Type) [Fintype H] (M : ℕ) := Fintype.card H * (5*M+2)+1
+
+/-- Step bound for clearing register three, copying the w-bit rank into it, and erasing all
+working stacks. -/
+def returnClock (H : Type) [Fintype H] (w M : ℕ) := (w+1)+(5*w+2)+(Fintype.card H*(M+1)+1)
+
+variable [DecidableEq H] {w : ℕ}
+
+omit [Fintype H] [DecidableEq H] in
+theorem bank_bound (template work : Stacks H) (rs : Regs 5 w) (M : ℕ) (hw : w ≤ M)
+ (ht : ∀ h, (template h).length ≤ M) (hs : ∀ h, (work h).length ≤ M) (p : Port H) :
+ (bank template work rs p).length ≤ M := by
+ cases p with
+ | inl k => exact (RegisterTable.bank_length_le Fin.elim0 0 rs k).trans hw
+ | inr k => cases k with
+ | template h => exact ht h
+ | work h => exact hs h
+ | scratch => exact Nat.zero_le _
+
+private theorem plan_output (dynamic : H → Bool) (template : Stacks H) (rs : Regs 5 w) :
+ CallCopies.copied (plan dynamic) (bank template (fun _ => []) rs) =
+ bank template (prepared dynamic template rs) rs := by
+ let s := bank template (fun _ => []) rs
+ have unchanged (k : Port H) (hk : ∀ h, workPort h ≠ k) : CallCopies.copied (plan dynamic) s k = s k := by
+ apply CallCopies.copied_outside
+ rw [plan_dest]
+ intro h
+ obtain ⟨a, _, ha⟩ := List.mem_map.mp h
+ exact hk a ha
+ funext k
+ cases k with
+ | inl k => exact unchanged _ (by intro h he; cases he)
+ | inr k => cases k with
+ | template k | scratch => exact unchanged _ (by intro h he; cases he)
+ | work h =>
+ have hp : (source dynamic h, workPort h) ∈ plan dynamic := List.mem_map.mpr ⟨h, by simp, rfl⟩
+ have hh := CallCopies.copied_at (plan dynamic) s (valid dynamic).1 hp
+ change CallCopies.copied (plan dynamic) s (workPort h) = prepared dynamic template rs h
+ rw [hh]
+ unfold source prepared
+ split <;> rfl
+
+/-- Copy the live prefix length and template into all callee ports without
+consuming either source. Every caller register survives the preparation. -/
+theorem copyIn_bounded (dynamic : H → Bool) (template : Stacks H) (rs : Regs 5 w) (M : ℕ)
+ (hw : w ≤ M) (ht : ∀ h, (template h).length ≤ M) :
+ ∃ t ≤ copyClock H M, (copyIn dynamic).BoundedRun (M+copyClock H M) t
+ (bank template (fun _ => []) rs) (bank template (prepared dynamic template rs) rs) := by
+ let s := bank template (fun _ => []) rs
+ have hb := bank_bound template (fun _ => []) rs M hw ht (fun _ => Nat.zero_le M)
+ obtain ⟨t, hclock, hr⟩ := CallCopies.copyPlan_runs scratch (plan dynamic) s M (valid dynamic) rfl
+ (by intro p hp; obtain ⟨a, _, rfl⟩ := List.mem_map.mp hp; rfl) (fun p _ => hb p.1)
+ have hk : t ≤ copyClock H M := by simpa [plan, copyClock] using hclock
+ refine ⟨t, hk, ?_⟩
+ change (copyIn dynamic).Runs t s (CallCopies.copied (plan dynamic) s) at hr
+ rw [show CallCopies.copied (plan dynamic) s = _ from plan_output dynamic template rs] at hr
+ exact spaceRun_of_steps hr (fun k => Nat.add_le_add (hb k) hk)
+
+/-- Any bounded callee run changes only its private work stacks. -/
+def callRank (r : FiniteRoutine H) : FiniteRoutine (Port H) := r.onPorts workPort
+
+omit [Fintype H] in
+theorem callRank_bounded (r : FiniteRoutine H) {M t : ℕ} {s out : Stacks H} (template : Stacks H)
+ (rs : Regs 5 w) (hw : w ≤ M) (ht : ∀ h, (template h).length ≤ M)
+ (hr : r.BoundedRun M t s out) :
+ (callRank r).BoundedRun M t (bank template s rs) (bank template out rs) := by
+ let base := bank template s rs
+ have outside (p : Port H) (hp : ∀ h, workPort h ≠ p) : (base p).length ≤ M := by
+ cases p with
+ | inl k => exact (RegisterTable.bank_length_le Fin.elim0 0 rs k).trans hw
+ | inr k => cases k with
+ | template h => exact ht h
+ | work h => exact (hp h rfl).elim
+ | scratch => exact Nat.zero_le _
+ have run := FiniteRoutine.BoundedRun.onPorts (a := r) workPort_injective base hr outside
+ have he : installStacks workPort base out = bank template out rs := by
+ apply installStacks_frame (small := out) (target := bank template out rs) workPort_injective (fun _ => rfl)
+ intro p hp
+ cases p with
+ | inr k => cases k with
+ | work h => exact (hp h rfl).elim
+ | _ => rfl
+ | inl k => rfl
+ rwa [installStacks_eq workPort_injective base s (fun _ => rfl), he] at run
+
+/-- Replace register three by the word from the callee’s result port and clear the working
+stacks for the next prefix query. -/
+noncomputable def returnRank (result : H) : FiniteRoutine (Port H) :=
+ ((CallClear.clear (reg 3)).followedBy (SuccessorFields.prependCopy (workPort result) (reg 3) scratch)).followedBy
+ (CallClear.cleanup workPorts)
+
+omit [Fintype H] in
+private theorem update_reg (template work : Stacks H) (rs : Regs 5 w) (rank : Word w) :
+ Function.update (bank template work rs) (reg 3) (wordBits rank) =
+ bank template work (Function.update rs 3 rank) := by
+ funext k
+ cases k with
+ | inr k => rfl
+ | inl k =>
+ have he := congrFun (ISA.bank_updateReg Fin.elim0 (0 : Word w) rs [] 3 rank) k
+ cases k with
+ | reg i => by_cases hi : i = 3 <;> simp [bank, PrefixWords.bank, reg, ISA.bank, hi]
+ | _ => exact he
+
+private theorem cleared (template work : Stacks H) (rs : Regs 5 w) :
+ CallClear.erased workPorts (bank template work rs) = bank template (fun _ => []) rs := by
+ funext k
+ cases k with
+ | inl k => simp [CallClear.erased, workPorts, workPort]; rfl
+ | inr k => cases k with
+ | work h => simp [CallClear.erased, workPorts, workPort, bank, PrefixWords.bank, auxBank]
+ | template h | scratch => simp [CallClear.erased, workPorts, workPort, bank, PrefixWords.bank, auxBank]
+
+/-- Return a complete rank word, reclaim every private port, and restore all
+prefix-machine registers other than the result register. -/
+theorem returnRank_bounded (result : H) (template work : Stacks H) (rs : Regs 5 w) (rank : Word w)
+ (M : ℕ) (hw : w ≤ M) (ht : ∀ h, (template h).length ≤ M) (hs : ∀ h, (work h).length ≤ M)
+ (hr : work result = wordBits rank) :
+ ∃ t ≤ returnClock H w M, (returnRank result).BoundedRun (M+returnClock H w M) t
+ (bank template work rs) (bank template (fun _ => []) (Function.update rs 3 rank)) := by
+ let s := bank template work rs
+ let mid := Function.update s (reg 3) []
+ let finalRegs := Function.update rs 3 rank
+ let finish := bank template work finalRegs
+ have hc := CallClear.clear_runs (reg 3) s
+ have hl : (s (reg 3)).length = w := length_wordBits _
+ rw [hl] at hc
+ have cp := SuccessorFields.prependCopy_runs (workPort result) (reg 3) scratch
+ (by intro h; cases h) (by intro h; cases h) (by intro h; cases h) mid rfl
+ have hv : mid (workPort result) = wordBits rank := hr
+ have hfinish : Function.update mid (reg 3) (mid (workPort result) ++ mid (reg 3)) = finish := by
+ rw [hv, show mid (reg 3) = [] from Function.update_self .., List.append_nil]
+ exact (Function.update_idem ..).trans (update_reg ..)
+ rw [hfinish, hv, length_wordBits] at cp
+ obtain ⟨k, hk, clean⟩ := CallClear.cleanup_runs workPorts finish M (by
+ intro a ha
+ obtain ⟨h, _, rfl⟩ := List.mem_map.mp ha
+ exact hs h)
+ have hclear : CallClear.erased workPorts finish = bank template (fun _ => []) finalRegs := cleared ..
+ rw [hclear] at clean
+ have hrun := ((FiniteRoutine.Runs.followedBy (a := CallClear.clear (reg 3))
+ (b := SuccessorFields.prependCopy (workPort result) (reg 3) scratch) hc cp).followedBy clean)
+ have hk' : k ≤ Fintype.card H*(M+1)+1 := by simpa [workPorts] using hk
+ have htime : (w+1)+(5*w+2)+k ≤ returnClock H w M := Nat.add_le_add_left hk' _
+ exact ⟨_, htime, spaceRun_of_steps hrun (fun k => Nat.add_le_add (bank_bound template work rs M hw ht hs k) htime)⟩
+
+/-- Prepare, invoke, and reclaim one rank workspace while retaining the
+immutable template for any later prefix. -/
+noncomputable def rankCall (dynamic : H → Bool) (r : FiniteRoutine H) (result : H) :=
+ ((copyIn dynamic).followedBy (callRank r)).followedBy (returnRank result)
+
+/-- Stack-height allowance for staging and returning a prefix-rank call when the incoming bank
+has stack heights at most M. -/
+def callSpace (H : Type) [Fintype H] (w M : ℕ) :=
+ M + max (copyClock H M) (returnClock H w M)
+
+theorem rankCall_bounded (dynamic : H → Bool) (r : FiniteRoutine H) (result : H)
+ (template out : Stacks H) (rs : Regs 5 w) (rank : Word w) (M t : ℕ) (hw : w ≤ M)
+ (ht : ∀ h, (template h).length ≤ M) (run : r.BoundedRun M t (prepared dynamic template rs) out)
+ (hr : out result = wordBits rank) :
+ ∃ k ≤ copyClock H M+t+returnClock H w M,
+ (rankCall dynamic r result).BoundedRun (callSpace H w M) k
+ (bank template (fun _ => []) rs) (bank template (fun _ => []) (Function.update rs 3 rank)) := by
+ obtain ⟨a, ha, h₁⟩ := copyIn_bounded dynamic template rs M hw ht
+ have h₂ := callRank_bounded r template rs hw ht run
+ obtain ⟨b, hb, h₃⟩ := returnRank_bounded result template out rs rank M hw ht run.final_cap hr
+ refine ⟨a+t+b, Nat.add_le_add (Nat.add_le_add_right ha _) hb, ?_⟩
+ apply FiniteRoutine.BoundedRun.followedBy (a := (copyIn dynamic).followedBy (callRank r))
+ · exact FiniteRoutine.BoundedRun.followedBy (a := copyIn dynamic) (b := callRank r)
+ (h₁.mono_cap (Nat.add_le_add_left (le_max_left ..) _)) (h₂.mono_cap (Nat.le_add_right ..))
+ · exact h₃.mono_cap (Nat.add_le_add_left (le_max_right ..) _)
+
+end RankQuery.Stack.Coordinate.PrefixWorkspace
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQuery.lean b/lean/OAI/Computability/VPVNP/RankQuery.lean
new file mode 100644
index 0000000000..ec9b285e2a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQuery.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.GreedyBasis
+import OAI.Computability.VPVNP.RankMinors
+import OAI.Computability.VPVNP.RankPolynomial
+
+/-!
+# Recovering rank from a weighted determinant
+
+Appendix D.2 uses the degree in `u` of `det(1 - u D₁(z) M D₂(z) Mᵀ)` to
+query the rank of a rectangular matrix. At the rank, every nonzero minor
+comes from a row basis and a column basis. The first basis of each kind has
+strictly smaller total index weight than any other. Its squared minor
+therefore supplies an isolated nonzero coefficient in `z`, in every
+characteristic.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+open Set VPVNP.Crossing
+open Polynomial
+
+/-- A unique nonzero summand at a specified weight prevents cancellation,
+including over fields of characteristic two. -/
+private theorem weight_sum_nonzero
+ {F Row Col : Type*} [Field F] [Fintype Row] [Fintype Col]
+ (rowWt : Row → ℕ) (colWt : Col → ℕ) (a : Row → Col → F) (r : Row) (c : Col)
+ (hval : a r c ≠ 0)
+ (huniq : ∀ i j, a i j ≠ 0 → rowWt i + colWt j = rowWt r + colWt c → i = r ∧ j = c) :
+ (∑ i, ∑ j, X ^ (rowWt i + colWt j) * C (a i j) ^ 2 : F[X]) ≠ 0 := by
+ classical
+ intro hz
+ have hc := congrArg (fun P : F[X] => P.coeff (rowWt r + colWt c)) hz
+ simp only [finsetSum_coeff, coeff_zero, ← map_pow, mul_comm (X ^ _) (C _),
+ coeff_C_mul_X_pow] at hc
+ have hentry (i : Row) (j : Col) (h : i ≠ r ∨ j ≠ c) :
+ (if rowWt r + colWt c = rowWt i + colWt j then a i j ^ 2 else 0) = 0 := by
+ split_ifs with he
+ · by_contra hne
+ have hn : a i j ≠ 0 := fun ha => hne (by simp [ha])
+ have hij := huniq i j hn he.symm
+ exact h.elim (fun hi => hi hij.1) (fun hj => hj hij.2)
+ · rfl
+ have hi (i : Row) (hi : i ≠ r) :
+ (∑ j, if rowWt r + colWt c = rowWt i + colWt j then a i j ^ 2 else 0) = 0 :=
+ Finset.sum_eq_zero (fun j _ => hentry i j (.inl hi))
+ rw [Fintype.sum_eq_single r hi, Fintype.sum_eq_single c (fun j hj => hentry r j (.inr hj)),
+ ite_eq_left rfl] at hc
+ exact pow_ne_zero _ hval hc
+
+/-- At maximum rank the term indexed by the first row and column bases has a
+unique weight among all nonzero terms in the minor expansion. -/
+theorem isolated_maximal_minor {K : Type*} [Field K] {n m : ℕ} (M : Matrix (Fin n) (Fin m) K) :
+ ∃ (R : powersetCard (Fin n) M.rank) (C : powersetCard (Fin m) M.rank),
+ compound M.rank M R C ≠ 0 ∧
+ ∀ I J, compound M.rank M I J ≠ 0 →
+ indexWeight I + indexWeight J = indexWeight R + indexWeight C → I = R ∧ J = C := by
+ obtain ⟨R, hr, _, hrow⟩ := exists_isolatedBasis K M.row M.rank_eq_finrank_span_row
+ obtain ⟨C, hc, _, hcol⟩ := exists_isolatedBasis K M.col M.rank_eq_finrank_span_cols
+ refine ⟨R, C, (compound_ne_zero_iff M rfl R C).mpr ⟨hr, hc⟩, ?_⟩
+ intro I J hminor hw
+ obtain ⟨hi, hj⟩ := (compound_ne_zero_iff M rfl I J).mp hminor
+ have hR (hne : R ≠ I) : indexWeight R < indexWeight I := hrow I hi hne
+ have hC (hne : C ≠ J) : indexWeight C < indexWeight J := hcol J hj hne
+ by_cases heq : R = I
+ · subst I
+ refine ⟨rfl, ?_⟩
+ by_contra hn
+ exact (hC (Ne.symm hn)).ne (Nat.add_left_cancel hw).symm
+ · have hlt := hR heq
+ by_cases heq' : C = J
+ · subst J
+ omega
+ · have hlt' := hC heq'
+ omega
+
+/-- The determinant rank test of Appendix D.2, including characteristic two
+and matrices with zero rows, zero columns, or rank zero. -/
+theorem rankPolynomial_natDegree {K : Type*} [Field K] {n m : ℕ} (M : Matrix (Fin n) (Fin m) K) :
+ (rankPolynomial M).natDegree = M.rank := by
+ apply natDegree_eq_of_le_of_coeff_ne_zero
+ · apply natDegree_le_iff_coeff_eq_zero.mpr
+ intro q hq
+ rw [rankPolynomial_coeff]
+ simp [compound_eq_zero_of_rank_lt M hq]
+ · obtain ⟨R, C, hval, huniq⟩ := isolated_maximal_minor M
+ rw [rankPolynomial_coeff]
+ exact mul_ne_zero (pow_ne_zero _ (neg_ne_zero.mpr one_ne_zero))
+ (weight_sum_nonzero indexWeight indexWeight (compound M.rank M) R C hval huniq)
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryBoundedExecution.lean b/lean/OAI/Computability/VPVNP/RankQueryBoundedExecution.lean
new file mode 100644
index 0000000000..3770cc31a3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryBoundedExecution.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.RankQueryExecution
+import OAI.Computability.VPVNP.RankQueryExecutionSpace
+import OAI.Computability.VPVNP.RankCursorSchurSpace
+
+/-! # Separate time and space in the complete rectangular rank query
+
+All determinant root requests share a single storage allowance. In particular
+an expensive scalar descriptor read is charged to the running time of the
+Schur traversal while retaining its independent peak-storage certificate.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch
+
+variable {K : Type} [DecidableEq K] {n m w v e b p B Bd S A : ℕ}
+ [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+/-- Step bound for scanning Schur coefficients of an n-by-m matrix, including each coefficient
+read, zero test, and cursor update. -/
+def boundedRankTime (n m Bd B w v e : ℕ) :=
+ let Z := (n+m)*n
+ ((n+1)*(Z+1))*(readClock n n Z Bd B w v e+checkClock w v e+1)+2
+
+/-- Stack-height bound for the full rectangular rank scan, combining the peak space of a single
+coefficient read with the cursor workspace. -/
+def boundedRankSpace (n S A B w v e : ℕ) :=
+ outerRankSpace (readSpace n n S A B w v e) A w v e
+
+/-- The rank is returned by the literal finite stack control. Every bit
+stack respects the displayed cap throughout the entire rectangular scan. -/
+theorem fullRank_boundedRun [Fact (Irreducible (SliceArithmetic.modulus c))]
+ (a : Engine.Actions K) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ (ready : Stacks K → Prop) (pending : SchurKey n n ((n+m)*n) → Stacks K → Prop)
+ (spec : Engine.Contracts a (SchurKey.program (U := n) (Z := (n+m)*n) (weightedGramEntryCoeff M))
+ w v B (SchurKey.arityBound n n ((n+m)*n)) ready pending Bd)
+ (desc : Engine.DescribeBounded a (SchurKey.program (U := n) (Z := (n+m)*n) (weightedGramEntryCoeff M))
+ w v Bd S (Nat.clog 2 n+4+Nat.clog 2 n) ready)
+ (hcap : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (hwidth : (b+1)*control.wordFactor ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (hsize : max 1 (max n ((n+m)*n)) < 2^b)
+ (persist : Word w) (rs : Regs Registers.R w) (aux : Stacks K) (haux : ready aux)
+ (hr : Registers.Stores rs ((n+m)*n) n ((n+m)*n)) :
+ ∃ k ≤ boundedRankTime n m Bd B w v e, ∃ out a', ready a' ∧
+ Registers.Stores out ((n+m)*n) (M.map (Scalar.interpretation c)).rank 0 ∧
+ (fullRank a).BoundedRun (boundedRankSpace n S A B w v e) k
+ (scanBank n persist rs [true] (idle aux)) (scanBank n persist out [] (idle a')) := by
+ let Z := (n+m)*n
+ apply rankMachine_boundedRun (rootQuery a) M ready hcap _ hwidth hv hsize persist rs aux haux hr
+ intro u z hu hz p₀ rs₀ aux₀ hrs hready
+ let i : Limit n := ⟨u, Nat.lt_succ_of_le hu⟩
+ let j : Limit Z := ⟨z, Nat.lt_succ_of_le hz⟩
+ have h := rootQuery_separate spec desc hcap (weightedGram M) (weightedGramEntryCoeff_eq M)
+ p₀ rs₀ i j hrs aux₀ hready
+ rw [SchurKey.compute_correct (weightedGram M) _ (weightedGramEntryCoeff_eq M) u z]
+ exact h
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryConcreteResources.lean b/lean/OAI/Computability/VPVNP/RankQueryConcreteResources.lean
new file mode 100644
index 0000000000..e0199113e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryConcreteResources.lean
@@ -0,0 +1,199 @@
+import OAI.Computability.VPVNP.RankCoordinateCost
+import OAI.Computability.VPVNP.RankQueryPlainBounds
+import OAI.Computability.VPVNP.RankQueryGramExecution
+
+/-!
+# Uniform bounds on the concrete determinant and rank programs
+
+The parameters below vary with the paper's input length. A matrix dimension
+and an entry-query clock can be singly exponential in this length. Widths,
+field-extension degree, and entry-query peak space are polynomial. The
+proofs apply to the clock and storage formulas of the actual finite routines.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.ConcreteResources
+
+open Cost Dispatch
+
+/-- Polynomial boundedness of a resource quantity as a function of the input length. -/
+abbrev PB := PolynomiallyBounded
+/-- Polynomial boundedness of the ceiling binary logarithm of a resource quantity as a function
+of the input length. -/
+abbrev LB := LogBound
+
+variable {f g : ℕ → ℕ}
+
+theorem poly_max (hf : PB f) (hg : PB g) : PB (fun i => max (f i) (g i)) :=
+ (hf.add hg).of_le fun _ => by omega
+
+theorem log_max (hf : LB f) (hg : LB g) : LB (fun i => max (f i) (g i)) :=
+ (PolynomiallyBounded.clog_add hf hg).of_le fun i => Nat.clog_mono_right _ (show max (f i) (g i) ≤ f i + g i by omega)
+
+/-- A constant resource quantity has a polynomially bounded ceiling binary logarithm. -/
+theorem log_const (k : ℕ) : LB (fun _ => k) := (PolynomiallyBounded.const k).clog
+
+open PolynomiallyBounded
+
+variable {w v e d r A S B : ℕ → ℕ}
+
+theorem allowance_poly (hw : PB w) (hv : PB v) (he : PB e) :
+ PB (fun i => DescribeAdapter.allowance (max (w i) (max (v i) (e i)))) := by
+ exact (const _).mul (((poly_max hw (poly_max hv he)).add (const 1)).pow 4)
+
+theorem localBudget_poly (hw : PB w) (he : PB e) (hv : PB v) :
+ PB (fun i => Engine.Assembly.localBudget (w i) (e i) (v i)) := by
+ have op (a : Operation) : PB (fun i => a.clock (w i)) := by
+ exact (const _).mul ((const 100).mul ((hw.add (const 1)).pow 2))
+ have hmac : PB (fun i => Engine.MultiplyAdd.callCap (e i) (v i)) := by
+ apply PolynomiallyBounded.of_le (g := fun i => 3000*(e i+1)^2*(v i+1)^2+2*(e i*v i+1))
+ · exact (((const 3000).mul ((he.add (const 1)).pow 2)).mul ((hv.add (const 1)).pow 2)).add ((const 2).mul ((he.mul hv).add (const 1)))
+ · intro i
+ exact Nat.add_le_add_right (SliceArithmetic.MultiplyAccumulate.callCap_le ..) _
+ have hleft := op .left
+ have hright := op .right
+ exact ((hleft.add hright).add hmac).add ((const 100).mul ((hw.add (he.mul hv)).add (const 1)))
+
+theorem gram_descriptor_log (hw : PB w) (hv : PB v) (he : PB e) (hB : LB B) :
+ LB (fun i => DescribeAdapter.clock (w i) (v i) (e i) (B i)) := by
+ have hlocal := allowance_poly hw hv he
+ refine PolynomiallyBounded.of_le
+ (g := fun i => Nat.clog 2 (2*B i + DescribeAdapter.allowance (max (w i) (max (v i) (e i))))) ?_ ?_
+ · exact clog_add (clog_mul (log_const 2) hB) hlocal.clog
+ · intro i
+ exact Nat.clog_mono_right _ (DescribeAdapter.clock_space_le (w i) (v i) (e i) _ (B i) 0 0
+ (le_max_left ..) ((le_max_left ..).trans (le_max_right ..)) ((le_max_right ..).trans (le_max_right ..))).1
+
+theorem gram_descriptor_poly (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) (hS : PB S) :
+ PB (fun i => DescribeAdapter.space (w i) (v i) (e i) (A i) (S i)) := by
+ have hlocal := allowance_poly hw hv he
+ apply PolynomiallyBounded.of_le
+ (g := fun i => max (A i) (S i) + DescribeAdapter.allowance (max (w i) (max (v i) (e i))))
+ · exact (poly_max hA hS).add hlocal
+ · intro i
+ exact (DescribeAdapter.clock_space_le (w i) (v i) (e i) _ 0 (A i) (S i)
+ (le_max_left ..) ((le_max_left ..).trans (le_max_right ..)) ((le_max_right ..).trans (le_max_right ..))).2
+
+theorem plain_descriptor_log (hw : PB w) (hv : PB v) (he : PB e) (hB : LB B) :
+ LB (fun i => PlainEngine.descriptorClock (w i) (v i) (e i) (B i)) := by
+ have hlocal := allowance_poly hw hv he
+ refine PolynomiallyBounded.of_le
+ (g := fun i => Nat.clog 2 (B i + DescribeAdapter.allowance (max (w i) (max (v i) (e i))))) ?_ ?_
+ · exact clog_add hB hlocal.clog
+ · intro i
+ exact Nat.clog_mono_right _ (PlainEngine.descriptorClock_le _ _ _ _ _
+ (le_max_left ..) ((le_max_left ..).trans (le_max_right ..)) ((le_max_right ..).trans (le_max_right ..)))
+
+theorem plain_descriptor_poly (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) (hS : PB S) :
+ PB (fun i => DescribeAdapter.peakWith (w i) (v i) (e i) (A i) (fun a => PlainScalar.space (w i) (v i) (e i) a (S i))) := by
+ have hlocal := allowance_poly hw hv he
+ apply PolynomiallyBounded.of_le (g := fun i => max (A i) (S i) + DescribeAdapter.allowance (max (w i) (max (v i) (e i))))
+ · exact (poly_max hA hS).add hlocal
+ · intro i
+ exact PlainEngine.descriptorSpace_le _ _ _ _ _ _
+ (le_max_left ..) ((le_max_left ..).trans (le_max_right ..)) ((le_max_right ..).trans (le_max_right ..))
+
+theorem step_poly {T : ℕ → ℕ} (hw : PB w) (hv : PB v) (he : PB e) (hT : PB T) :
+ PB (fun i => Engine.stepBudget (T i) (w i) (v i) (e i)) := by
+ have live := poly_max (const 1) (poly_max hw (he.mul hv))
+ exact (const 4).mul ((hT.add ((const 10).mul (((const 3).mul live).add (const 2)))).add (const 5))
+
+theorem step_log {T : ℕ → ℕ} (hw : PB w) (hv : PB v) (he : PB e) (hT : LB T) :
+ LB (fun i => Engine.boundedStepTime (T i) (Engine.Assembly.localBudget (w i) (e i) (v i)) (w i) (v i) (e i)) :=
+ log_max (clog_add hT (log_const 1)) (step_poly hw hv he (localBudget_poly hw he hv)).clog
+
+theorem entryCap_poly (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) (hd : PB d) :
+ PB (fun i => GramEngine.entryCap (w i) (v i) (e i) (A i) (d i)) := by
+ have live := poly_max (const 1) (poly_max hw (he.mul hv))
+ have history := hd.mul (((const 2).mul live).add (const 1))
+ exact poly_max ((((hw.add hv).add he).add (he.mul hv)).add hA) (poly_max live history)
+
+theorem schurSpace_poly (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) (hS : PB S) (hd : PB d) :
+ PB (fun i => Engine.boundedSpace (S i) (A i) (d i) (Engine.Assembly.localBudget (w i) (e i) (v i))
+ (w i) (v i) (e i)) := by
+ have live := poly_max (const 1) (poly_max hw (he.mul hv))
+ have history := hd.mul (((const 2).mul live).add (const 1))
+ exact poly_max (hS.add (const 1))
+ ((poly_max hA (poly_max live history)).add (step_poly hw hv he (localBudget_poly hw he hv)))
+
+/-- The full ordinary determinant clock and peak, uniformly for an
+arbitrary family of singly exponential square minors. -/
+theorem plain_feasible (hr : LB r) (hw : PB w) (hv : PB v) (he : PB e)
+ (hA : PB A) (hS : PB S) (hB : LB B) :
+ Feasible (fun i => ⟨PlainEngine.queryTime (r i) (w i) (v i) (e i) (B i),
+ PlainEngine.querySpace (r i) (w i) (v i) (e i) (A i) (S i)⟩) := by
+ let depth := fun i => Nat.clog 2 (r i)+4+Nat.clog 2 (r i)
+ have hdepth : PB depth := (hr.add (.const 4)).add hr
+ have hrec : LB (fun i => SchurKey.clock (r i) (r i) 0) := by
+ refine PolynomiallyBounded.of_le (g := fun i =>
+ (2*Nat.clog 2 (r i)+8)*(2*Nat.clog 2 (r i)+5)) ?_ ?_
+ · exact (((const 2).mul hr).add (const 8)).mul (((const 2).mul hr).add (const 5))
+ · intro i
+ have h := Nat.le_pow_clog (by decide : 1 < 2) (r i)
+ exact Nat.clog_le_of_le_pow (SchurKey.clock_le_exp _ _ 0 _ h h (Nat.zero_le _))
+ have hstep := step_log hw hv he (plain_descriptor_log hw hv he hB)
+ let initial := fun i => GramEngine.entryCap (w i) (v i) (e i) (A i) (depth i)
+ have hi : PB initial := entryCap_poly hw hv he hA hdepth
+ have hpeak := plain_descriptor_poly hw hv he hi hS
+ constructor
+ · change LB (fun i => SchurKey.clock (r i) (r i) 0 * Engine.boundedStepTime
+ (PlainEngine.descriptorClock (w i) (v i) (e i) (B i))
+ (Engine.Assembly.localBudget (w i) (e i) (v i)) (w i) (v i) (e i) + 1)
+ exact clog_add (clog_mul hrec hstep) (log_const 1)
+ · exact schurSpace_poly hw hv he ((((hw.add hv).add he).add (he.mul hv)).add hA) (poly_max hi hpeak) hdepth
+
+/-- The concrete rectangular rank scanner, including root initialization,
+scalar zero tests, and every cursor update. The shared bit bound `d` may
+vary polynomially with the external length. -/
+theorem rank_feasible (hd : PB d) (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) (hS : PB S) (hB : LB B) :
+ Feasible (fun i => ⟨Cursor.gramTime (d i) (w i) (v i) (e i) (B i),
+ Cursor.gramSpace (d i) (w i) (v i) (e i) (A i) (S i)⟩) := by
+ have hstep := step_log hw hv he (gram_descriptor_log hw hv he hB)
+ have startup : PB (fun i => Cursor.startupClock (w i)) := by
+ have sq := (hw.add (const 1)).pow 2
+ exact ((((const 5).mul hw).add (const 2)).add ((const 12).mul sq)).add ((const 5).mul ((const 100).mul sq))
+ have load : PB (fun i => Cursor.loadClock (w i)) :=
+ ((const 6).mul (((const 5).mul hw).add (const 2))).add (const 1)
+ have check : PB (fun i => Cursor.checkClock (w i) (v i) (e i)) := by
+ simp only [Cursor.checkClock,Cursor.Registers.clock_eq]
+ exact (((const 5).mul (he.mul hv)).add (const 4)).add (((((const 7300).mul ((hw.add (const 1)).pow 2)).add ((const 20).mul hw)).add (const 13)))
+ have depth : PB (fun i => 2*d i+4) := ((PolynomiallyBounded.const 2).mul hd).add (.const 4)
+ have initial := entryCap_poly hw hv he hA depth
+ have hds := poly_max initial (gram_descriptor_poly hw hv he initial hS)
+ have aux := (((hw.add hv).add he).add (he.mul hv)).add hA
+ have schur := schurSpace_poly hw hv he aux hds depth
+ constructor
+ · change LB (fun i => Cursor.startupClock (w i) + ((2^(d i)+1)*(2^(d i)+1)*
+ (Cursor.loadClock (w i) + (2^((2*d i+8)*(2*d i+5))*Engine.boundedStepTime
+ (DescribeAdapter.clock (w i) (v i) (e i) (B i)) (Engine.Assembly.localBudget (w i) (e i) (v i))
+ (w i) (v i) (e i) + 1) + Cursor.checkClock (w i) (v i) (e i) + 1)+2))
+ have dim := clog_add (clog_pow (log_const 2) hd) (log_const 1)
+ have count := clog_pow (log_const 2) ((((const 2).mul hd).add (const 8)).mul (((const 2).mul hd).add (const 5)))
+ have query := clog_add load.clog (clog_add (clog_mul count hstep) (log_const 1))
+ exact clog_add startup.clog (clog_add (clog_mul (clog_mul dim dim) (clog_add (clog_add query check.clog) (log_const 1))) (log_const 2))
+ · exact poly_max ((poly_max (poly_max hw (const 1)) aux).add startup)
+ (poly_max (poly_max ((poly_max hw aux).add load) schur) ((((aux.add hw).add (he.mul hv)).add (const 1)).add check))
+
+/-- An eventual power of the input length bounds both the bit exponent of
+the clock and the number of bits on any stack. -/
+theorem eventual_power {f : ℕ → Budget} (hf : Feasible f) :
+ ∃ c N : ℕ, ∀ n ≥ N, (f n).time ≤ 2^(n^c) ∧ (f n).space ≤ n^c := by
+ obtain ⟨T,t,Nt,ht⟩ := hf.time
+ obtain ⟨S,s,Ns,hs⟩ := hf.space
+ refine ⟨max t s+1,max (max Nt Ns) (max 1 (max T S)),fun n hn => ?_⟩
+ have hn1 : 1 ≤ n := by omega
+ have ts := Nat.pow_le_pow_right hn1 (Nat.le_max_left t s)
+ have ss := Nat.pow_le_pow_right hn1 (Nat.le_max_right t s)
+ have ht' := (ht n (by omega)).trans (Nat.mul_le_mul (by omega : T ≤ n) ts)
+ have hs' := (hs n (by omega)).trans (Nat.mul_le_mul (by omega : S ≤ n) ss)
+ rw [pow_succ']
+ exact ⟨(Nat.le_pow_clog (by decide) _).trans (Nat.pow_le_pow_right (by decide) ht'), hs'⟩
+
+end RankQuery.Stack.Coordinate.ConcreteResources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryDescribeAdapter.lean b/lean/OAI/Computability/VPVNP/RankQueryDescribeAdapter.lean
new file mode 100644
index 0000000000..6a0b7397b9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryDescribeAdapter.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.RankQueryGramAlias
+import OAI.Computability.VPVNP.RankQueryDescribeWords
+
+/-! # Executable Schur description on a Macaulay relation matrix
+
+The engine's describe action reads the current six-field query, evaluates its
+fixed decision tree, selects an arm by the actual output tag, and returns
+either a packed scalar or the loop counter and a fresh accumulator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.DescribeAdapter
+
+open Engine RAMTape Dispatch
+
+variable {K : Type} [DecidableEq K]
+
+/-- Interpret a description tag by setting up a recursive sum, returning field zero or one, or
+reading a Gram entry with the indicated sign. -/
+def entryArm (call : Bool → FiniteRoutine (GramScalar.Port K)) (tag : ℕ) : FiniteRoutine (Engine.Port (Aux K)) :=
+ if tag = 4 then Describe.arity wires
+ else if tag = 0 then Describe.terminal wires false else if tag = 1 then Describe.terminal wires true
+ else (valueRoutine call (decide (tag = 3))).followedBy Describe.finish
+
+/-- Stage the current Schur query, run the description decision tree, and dispatch on its
+three-bit tag using the supplied signed-entry routine. -/
+def describeWith (call : Bool → FiniteRoutine (GramScalar.Port K)) : FiniteRoutine (Engine.Port (Aux K)) :=
+ (EngineAlias.stageDescribe leftBank).followedBy (TagRouter.select (.aux (.inl (outputSlot 0))) 3 (entryArm call))
+
+/-- Describe one Schur query using the physical Gram-entry routine backed by the Macaulay
+matrix reader. -/
+def describe (read : FiniteRoutine (MacaulayRead.Port K)) := describeWith (GramScalar.machine read)
+
+/-- Step bound for one description dispatch when a signed Gram-entry call costs at most T
+steps. -/
+def timeWith (w v e T : ℕ) := Operation.describe.clock w + 6 + (T + (10*(w+1)+2) + 7*(e*v)+3 + (5*w+3))
+
+/-- Step bound for the physical description dispatch when each underlying Macaulay entry read
+costs at most B steps. -/
+def clock (w v e B : ℕ) := timeWith w v e (GramScalar.clock w v e B)
+
+variable {w v d p e n m U Z B : ℕ} [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+omit [DecidableEq K] in
+private theorem left_ready {s u : Stacks (Aux K)} (h : EngineAlias.Ready leftBank w n s)
+ (same : ∀ x, u (.inl x) = s (.inl x)) : EngineAlias.Ready leftBank w n u := by
+ obtain ⟨rs,pers,h₀,hn,hs⟩ := h
+ exact ⟨rs,pers,h₀,hn,fun i => (same i).trans (hs i)⟩
+
+omit [DecidableEq K] [Fact p.Prime] [NeZero e] in
+private theorem right_ready {ready : Stacks K → Prop} {s u : Stacks (Aux K)} (h : RightReady w v m c ready s)
+ (same : ∀ x, u (.inr x) = s (.inr x)) : RightReady w v m c ready u := by
+ obtain ⟨rs,pers,bank,h₀,hn,hs⟩ := h
+ exact ⟨rs,pers,bank,h₀,hn,fun i => (same i).trans (hs i)⟩
+
+/-- Physical execution contract for the engine's describe action. Its only
+matrix-dependent subprogram computes an individual Macaulay entry. -/
+theorem describe_entries {T : ℕ} (call : Bool → FiniteRoutine (GramScalar.Port K)) (entry : Entry n (Scalar c))
+ {ready : Stacks K → Prop} (hc : CallRuns call entry w v m d T ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hp : (d+1)*widthFactor ≤ w) (hd : d ≤ w)
+ (hsize : n+U+Z+m+8 < 2^d)
+ (q : SchurKey n U Z) (fs : List (F n U Z c)) (aux : Stacks (Aux K)) (hs : Ready w v n m c ready aux) :
+ ∃ t ≤ timeWith w v e T, ∃ out, Ready w v n m c ready out ∧
+ (describeWith call).Runs t (atControl w v (.enter q) fs aux)
+ (match (SchurKey.program entry).describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false]) := by
+ let vs := Dispatch.describe.eval (inputs q 0)
+ let saved := history w v fs
+ let data := fields w [] q [] [] []
+ have bounded (i : Fin 8) : inputs q 0 i < 2^d := by
+ have hq (j : Fin 6) : q.words j < 2^d := (q.words_le j).trans_lt (by omega)
+ fin_cases i <;> first | exact hq _ | (simp [inputs] <;> omega)
+ obtain ⟨t₀,ht₀,mid,hm₀,hstage,words,houtside⟩ :=
+ EngineAlias.stageDescribe_runs leftBank q saved [] [] aux hs.1 bounded hd hp
+ have hm₁ := right_ready hs.2 (fun x => houtside (.inr x) (fun _ hh => by contradiction))
+ have hm : Ready w v n m c ready mid := ⟨hm₀,hm₁⟩
+ have valid : ValidDescription n Z vs := describe_valid q 0
+ have htag : vs 0 < 2^3 := by have := valid.1; omega
+ have hdesc : (SchurKey.program entry).describe q = decode entry vs :=
+ (describe_eq _ q 0).symm
+ rw [hdesc]
+ have execute {t : ℕ} {out : Stacks (Engine.Port (Aux K))}
+ (h : (entryArm call (vs 0)).Runs t (atControl w v (.enter q) fs mid) out) :
+ (describeWith call).Runs (t₀+(2*3+t)) (atControl w v (.enter q) fs aux) out := by
+ exact hstage.followedBy (TagRouter.digits_runs _ (entryArm call) hw₃ htag _ _ (words 0) h)
+ have casesTag : vs 0 = 4 ∨ vs 0 = 0 ∨ vs 0 = 1 ∨ vs 0 = 2 ∨ vs 0 = 3 := by have := valid.1; omega
+ rcases casesTag with h4 | h0 | h1 | hread
+ · have ha := Describe.arity_runs hw wires q fs mid (clean hm₁) (vs 1) (words 1)
+ refine ⟨t₀+(2*3+((5*w+2)+(7*(e*v)+3)+1)),by unfold timeWith; omega,mid,hm,?_⟩
+ simp only [decode,h4,ite_true]
+ apply execute
+ simpa [entryArm,h4] using ha
+ · obtain ⟨t,ht,ha⟩ := Describe.terminal_runs (w := w) hw wires q fs mid (clean hm₁) false
+ refine ⟨t₀+(2*3+t),by unfold timeWith; omega,mid,hm,?_⟩
+ simp only [decode,h0,ite_false,ite_true,OfNat.zero_ne_ofNat,Nat.zero_ne_one]
+ apply execute
+ simpa [entryArm,h0,Describe.constant] using ha
+ · obtain ⟨t,ht,ha⟩ := Describe.terminal_runs (w := w) hw wires q fs mid (clean hm₁) true
+ refine ⟨t₀+(2*3+t),by unfold timeWith; omega,mid,hm,?_⟩
+ simp [decode,h1]
+ apply execute
+ simpa [entryArm,h1,Describe.constant] using ha
+ · obtain ⟨hi,hj,hz⟩ := valid.2 hread
+ let i : Fin n := ⟨vs 1,hi⟩
+ let j : Fin n := ⟨vs 2,hj⟩
+ let neg := decide (vs 0 = 3)
+ have he (a : Fin 8) : gramInput i j (vs 3) m a < 2^d := by fin_cases a <;> simp [gramInput,i,j] <;> omega
+ have hword (a : Fin 3) : mid (.inl (outputSlot ⟨a.val+1,by omega⟩)) =
+ UniversalCountStack.digits w (gramInput i j (vs 3) m ⟨a.val,by omega⟩) := by
+ fin_cases a <;> exact words _
+ obtain ⟨t₁,ht₁,out,hout₁,hleft,hr⟩ := value_runs call entry hc hd i j (vs 3) neg data saved mid hm₁ he hword
+ let r := if neg then -entry i j (vs 3) else entry i j (vs 3)
+ obtain ⟨t₂,ht₂,hf⟩ := Describe.finish_runs (w := w) (v := v) q fs r out
+ have run : (entryArm call (vs 0)).Runs (t₁+t₂) (atControl w v (.enter q) fs mid)
+ (atControl w v (.returned r) fs out [true]) := by
+ have h₀ : vs 0 ≠ 0 := by omega
+ have h₁ : vs 0 ≠ 1 := by omega
+ have h₄ : vs 0 ≠ 4 := by omega
+ simp only [entryArm,h₄,h₀,h₁,ite_false]
+ exact hr.followedBy hf
+ have eq : decode entry vs = .inl r := by
+ rcases hread with h|h <;> simp [decode,r,neg,h,hi,hj,i,j]
+ rw [eq]
+ exact ⟨t₀+(2*3+(t₁+t₂)),by unfold timeWith; omega,out,⟨left_ready hm₀ hleft,hout₁⟩,execute run⟩
+
+theorem describe_runs (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.Correct read M w v B ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hp : (d+1)*widthFactor ≤ w) (hd : d ≤ w)
+ (hsize : n+U+Z+m+8 < 2^d)
+ (q : SchurKey n U Z) (fs : List (F n U Z c)) (aux : Stacks (Aux K)) (hs : Ready w v n m c ready aux) :
+ ∃ t ≤ clock w v e B, ∃ out, Ready w v n m c ready out ∧
+ (describe read).Runs t (atControl w v (.enter q) fs aux)
+ (match (SchurKey.program (weightedGramEntryCoeff M)).describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false]) :=
+ describe_entries (GramScalar.machine read) (weightedGramEntryCoeff M)
+ (GramScalar.machine_runs read M hc hw (by omega) hp) hw hw₃ hp hd hsize q fs aux hs
+
+end RankQuery.Stack.DescribeAdapter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryDescribeArms.lean b/lean/OAI/Computability/VPVNP/RankQueryDescribeArms.lean
new file mode 100644
index 0000000000..968db8717d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryDescribeArms.lean
@@ -0,0 +1,191 @@
+import OAI.Computability.VPVNP.RankQueryStackEngineSpec
+import OAI.Computability.VPVNP.SliceArithmeticConstant
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-! # Terminal and arity arms of the physical Schur dispatch -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Describe
+
+open Engine RAMTape
+open TapeWord (ScanPort)
+open SliceArithmeticRound (packed)
+
+/-- Auxiliary stacks used by the description arms, comprising six descriptor words, the
+extension modulus coefficients, and two scratch stacks for writing field literals. -/
+inductive Wire where
+ | desc (i : Fin 6) | coeff | scratch | extra
+ deriving DecidableEq, Fintype
+
+variable {K : Type} {p e n U Z w v : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- Embed one of the ten live Schur frame slots into the stack ports of the interpreter. -/
+def livePort (i : Fin 10) : Engine.Port K := .frame (.inl i)
+
+/-- Push the descriptor branch bit onto the engine's condition stack. A true bit signals a
+returned scalar and a false bit starts a child scan. -/
+def signal (b : Bool) : FiniteRoutine (Engine.Port K) := .ofRoutine (Routine.push .condition b)
+
+/-- Connect the constant writer's input and work stacks to the coefficient, extra and scratch
+wires, and send its packed scalar to `out`. -/
+def literalPorts (bank : Wire ↪ K) (out : Engine.Port K) : ScanPort → Engine.Port K
+ | .left => .aux (bank .coeff)
+ | .right => .aux (bank .extra)
+ | .tmp => .aux (bank .scratch)
+ | .out => out
+
+/-- Write the packed scalar one for `true` or zero for `false` to the selected engine port,
+using the field advice on the coefficient wire. -/
+def literal (bank : Wire ↪ K) (out : Engine.Port K) (b : Bool) : FiniteRoutine (Engine.Port K) :=
+ (SliceArithmeticConstant.machine b).onPorts (literalPorts bank out)
+
+/-- The ten stacks holding the current Schur frame, in field order, which the terminal arm
+clears on return. -/
+def livePorts : List (Engine.Port K) := (List.finRange 10).map livePort
+
+/-- Clear the ten live frame fields and push the true return signal once the scalar result is
+in place. -/
+def finish : FiniteRoutine (Engine.Port K) :=
+ (SliceArithmetic.CallClear.cleanup livePorts).followedBy (signal true)
+
+/-- Return the constant selected by `b` from a Schur leaf by writing its packed scalar,
+clearing the live frame and signaling completion. -/
+def terminal (bank : Wire ↪ K) (b : Bool) : FiniteRoutine (Engine.Port K) :=
+ (literal bank .result b).followedBy finish
+
+/-- Start a child scan by copying descriptor word one into the remaining-child count, setting
+the scalar accumulator to zero and pushing the false signal. -/
+def arity (bank : Wire ↪ K) : FiniteRoutine (Engine.Port K) :=
+ ((SuccessorFields.prependCopy (.aux (bank (.desc 1))) (livePort 7) (.aux (bank .scratch))).followedBy
+ (literal bank (livePort 8) false)).followedBy (signal false)
+
+/-- The coefficient wire holds the packed vector `c` at limb width `v`, and the scratch and
+extra wires are empty for a constant write. -/
+def Clean (bank : Wire ↪ K) (v : ℕ) (c : SliceArithmetic.Vector p e) (aux : Stacks K) : Prop :=
+ aux (bank .coeff) = packed v (List.ofFn c) ∧ aux (bank .scratch) = [] ∧ aux (bank .extra) = []
+
+variable [DecidableEq K] [Fact p.Prime] [NeZero e]
+
+omit [DecidableEq K] in
+private theorem literal_injective (bank : Wire ↪ K) (out : Engine.Port K) (ho : ∀ i, .aux (bank i) ≠ out) :
+ Function.Injective (literalPorts bank out) := by
+ intro x y h
+ cases x <;> cases y <;> simp_all [literalPorts]
+
+/-- The scalar selected by a constant descriptor in `Scalar c`, equal to one for `true` and
+zero for `false`. -/
+def constant (c : SliceArithmetic.Vector p e) (b : Bool) : Scalar c := if b then 1 else 0
+
+omit [NeZero e] in
+private theorem scalar_constant (b : Bool) : scalar v (constant c b) =
+ packed v (List.ofFn (SliceArithmeticConstant.literal b p e)) := by
+ cases b with
+ | false => change packed v (List.ofFn (Scalar.pack c (SliceArithmetic.zero p e)).digits) = _
+ rw [Scalar.digits_pack]; rfl
+ | true => change packed v (List.ofFn (Scalar.pack c (SliceArithmetic.one p e)).digits) = _
+ rw [Scalar.digits_pack]; rfl
+
+theorem literal_runs (hw : SliceArithmetic.Word.workingWidth p ≤ v) (bank : Wire ↪ K)
+ (out : Engine.Port K) (ho : ∀ i, .aux (bank i) ≠ out) (b : Bool) (s : Stacks (Engine.Port K))
+ (hcoeff : s (.aux (bank .coeff)) = packed v (List.ofFn c))
+ (hscratch : s (.aux (bank .scratch)) = []) (hextra : s (.aux (bank .extra)) = []) (hout : s out = []) :
+ (literal bank out b).Runs (7*(e*v)+3) s (Function.update s out (scalar v (constant c b))) := by
+ have h := SliceArithmeticConstant.machine_runs (NeZero.pos e) hw b c []
+ apply (SliceArithmeticConstant.machine b).runs_onPorts_framed (literal_injective bank out ho) (by simpa using h)
+ · intro z; cases z <;> assumption
+ · intro z; cases z <;> simp [literalPorts, ho, hcoeff, hscratch, hextra, scalar_constant, TapeWord.scanStacks]
+ · intro z hz; exact Function.update_of_ne (Ne.symm (hz .out)) ..
+
+private theorem enter_width (q : SchurKey n U Z) (j : Fin 10) :
+ ((fields w [] q [] [] []) j).length ≤ w := by
+ refine Fin.cases (Nat.zero_le _) (fun j => ?_) j
+ refine Fin.addCases (motive := fun i => (Fin.append (fun x : Fin 6 => UniversalCountStack.digits w (q.words x))
+ ![[],[],[]] i).length ≤ w) (fun x : Fin 6 => ?_) (fun x : Fin 3 => ?_) j
+ · rw [Fin.append_left,UniversalCountStack.length_digits]
+ · rw [Fin.append_right]; fin_cases x <;> exact Nat.zero_le _
+
+private theorem clear_eq (data saved : Data) (res : List Bool) (aux : Stacks K) :
+ SliceArithmetic.CallClear.erased livePorts (store data saved [] res aux) =
+ store (fun _ => []) saved [] res aux := by
+ funext k
+ cases k with
+ | frame k =>
+ cases k with
+ | inl j => simp [SliceArithmetic.CallClear.erased,livePorts,livePort,store]
+ | inr j => simp [SliceArithmetic.CallClear.erased,livePorts,livePort,store]
+ | _ => simp [SliceArithmetic.CallClear.erased,livePorts,livePort,store]
+
+omit [Fact p.Prime] [NeZero e] in
+theorem finish_runs (q : SchurKey n U Z) (fs : List (F n U Z c)) (r : Scalar c) (aux : Stacks K) :
+ ∃ t ≤ 10*(w+1)+2, finish.Runs t
+ (store (fields w [] q [] [] []) (history w v fs) [] (scalar v r) aux)
+ (atControl w v (.returned r) fs aux [true]) := by
+ let init := store (fields w [] q [] [] []) (history w v fs) [] (scalar v r) aux
+ obtain ⟨t,ht,hclear⟩ := SliceArithmetic.CallClear.cleanup_runs livePorts init w (by
+ intro i hi
+ obtain ⟨j,_,rfl⟩ := List.mem_map.mp hi
+ exact enter_width ..)
+ rw [show init = _ from rfl, clear_eq] at hclear
+ let mid := store (fun _ => []) (history w v fs) [] (scalar v r) aux
+ have hpush := Routine.runs_push (Engine.Port.condition (K := K)) true mid
+ have finalEq : Function.update mid .condition (true :: mid .condition) =
+ atControl w v (.returned r) fs aux [true] := by funext k; cases k with | frame z => cases z <;> rfl | _ => rfl
+ rw [finalEq] at hpush
+ exact ⟨_, by simpa [livePorts] using Nat.add_le_add_right ht 1, hclear.followedBy hpush⟩
+
+theorem terminal_runs (hw : SliceArithmetic.Word.workingWidth p ≤ v) (bank : Wire ↪ K)
+ (q : SchurKey n U Z) (fs : List (F n U Z c)) (aux : Stacks K) (hc : Clean bank v c aux) (b : Bool) :
+ ∃ t ≤ 7*(e*v)+3 + (10*(w+1)+2), (terminal bank b).Runs t
+ (atControl w v (.enter q) fs aux) (atControl w v (.returned (constant c b)) fs aux [true]) := by
+ let init := atControl w v (.enter q) fs aux
+ have hl := literal_runs hw bank .result (fun i h => by contradiction) b init hc.1 hc.2.1 hc.2.2 rfl
+ have he : Function.update init .result (scalar v (constant c b)) =
+ store (fields w [] q [] [] []) (history w v fs) [] (scalar v (constant c b)) aux := by
+ funext k; cases k with | frame z => cases z <;> rfl | _ => rfl
+ rw [he] at hl
+ obtain ⟨t,ht,hf⟩ := finish_runs q fs (constant c b) aux
+ exact ⟨_, Nat.add_le_add_left ht _, hl.followedBy hf⟩
+
+theorem arity_runs (hw : SliceArithmetic.Word.workingWidth p ≤ v) (bank : Wire ↪ K)
+ (q : SchurKey n U Z) (fs : List (F n U Z c)) (aux : Stacks K) (hc : Clean bank v c aux)
+ (k : ℕ) (hk : aux (bank (.desc 1)) = UniversalCountStack.digits w k) :
+ (arity bank).Runs ((5*w+2)+(7*(e*v)+3)+1)
+ (atControl w v (.enter q) fs aux) (atControl w v (.scan q k 0) fs aux [false]) := by
+ let init := atControl w v (.enter q) fs aux
+ let mid := store (fields w [] q (UniversalCountStack.digits w k) [] []) (history w v fs) [] [] aux
+ let loaded := atControl w v (.scan q k 0) fs aux
+ have hcopy := SuccessorFields.prependCopy_runs (.aux (bank (.desc 1)) : Engine.Port K)
+ (livePort 7) (.aux (bank .scratch)) (by intro h; contradiction)
+ (fun h => by have := bank.injective (Engine.Port.aux.inj h); contradiction)
+ (by intro h; contradiction) init hc.2.1
+ have hlen : (init (.aux (bank (.desc 1)))).length = w := by change (aux _).length = _; simp [hk]
+ have midEq : Function.update init (livePort 7) (init (.aux (bank (.desc 1))) ++ init (livePort 7)) = mid := by
+ funext z; cases z with
+ | frame z => rcases z with z | z
+ · fin_cases z <;> first | rfl | (change aux (bank (.desc 1)) ++ [] = UniversalCountStack.digits w k; simp [hk])
+ · rfl
+ | _ => rfl
+ rw [midEq,hlen] at hcopy
+ have hlit := literal_runs hw bank (livePort 8) (fun i h => by contradiction) false mid hc.1 hc.2.1 hc.2.2 rfl
+ have loadEq : Function.update mid (livePort 8) (scalar v (constant c false)) = loaded := by
+ funext z; cases z with
+ | frame z => rcases z with z | z
+ · fin_cases z <;> rfl
+ · rfl
+ | _ => rfl
+ rw [loadEq] at hlit
+ have hpush := Routine.runs_push (Engine.Port.condition (K := K)) false loaded
+ have finalEq : Function.update loaded .condition (false :: loaded .condition) =
+ atControl w v (.scan q k 0) fs aux [false] := by funext z; cases z with | frame j => cases j <;> rfl | _ => rfl
+ rw [finalEq] at hpush
+ exact (hcopy.followedBy hlit).followedBy hpush
+
+end RankQuery.Stack.Describe
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryDescribeBounds.lean b/lean/OAI/Computability/VPVNP/RankQueryDescribeBounds.lean
new file mode 100644
index 0000000000..6afe437493
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryDescribeBounds.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.RankQueryDescribeSpace
+
+/-! # A common polynomial allowance for the descriptor's own work
+
+The Macaulay callback contributes its clock twice and its peak stack height
+once. All remaining time and storage have a fixed quartic majorant in the
+register width, field limb width, and extension degree.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.DescribeAdapter
+
+open Dispatch
+
+/-- One hundred times the number of instructions emitted for the six output fields of `op`.
+Multiplication by `(w+1)^2` gives its word-operation clock. -/
+def codeCost (op : Operation) := (op.tree.emitFields capacity (List.finRange 6)).length * 100
+
+private theorem opClock (op : Operation) (w : ℕ) : op.clock w = codeCost op * (w+1)^2 := by
+ unfold Operation.clock codeCost
+ rw [Nat.mul_assoc]
+
+/-- Quartic bound on the descriptor's own time and stack growth when register width, limb width
+and extension degree are all at most `x`. -/
+def allowance (x : ℕ) := (codeCost .describe + codeCost .gram + 4000)*(x+1)^4
+
+theorem clock_eq (w v e B : ℕ) : clock w v e B = 2*B+clock w v e 0 := by
+ unfold clock timeWith GramScalar.clock; omega
+
+theorem space_le_clock (w v e A S : ℕ) : space w v e A S ≤ max A S + clock w v e 0 := by
+ unfold space peakWith clock timeWith GramScalar.space GramScalar.clock
+ dsimp only
+ have h : max (A+Operation.describe.clock w+Operation.gram.clock w) S ≤
+ max A S + Operation.describe.clock w + Operation.gram.clock w := max_le (by omega) (by omega)
+ omega
+
+private theorem addCap_le (e v x : ℕ) (he : e ≤ x) (hv : v ≤ x) :
+ SliceArithmetic.AddCall.callCap e v ≤ 500*(x+1)^4 := by
+ calc
+ _ ≤ SliceArithmetic.AddCall.callCap x x := by unfold SliceArithmetic.AddCall.callCap; gcongr
+ _ ≤ _ := by unfold SliceArithmetic.AddCall.callCap; ring_nf; omega
+
+theorem overhead_le (w v e x : ℕ) (hw : w ≤ x) (hv : v ≤ x) (he : e ≤ x) :
+ clock w v e 0 ≤ allowance x := by
+ have hm : SliceArithmetic.MultiplyCall.callCap e v ≤ 2000*(x+1)^4 := calc
+ _ ≤ 2000*(e+1)^2*(v+1)^2 := SliceArithmetic.MultiplyCall.callCap_le e v
+ _ ≤ 2000*(x+1)^2*(x+1)^2 := by gcongr
+ _ = _ := by ring
+ have ha := addCap_le e v x he hv
+ have hc₁ : Operation.describe.clock w ≤ codeCost .describe*(x+1)^2 := by rw [opClock]; gcongr
+ have hc₂ : Operation.gram.clock w ≤ codeCost .gram*(x+1)^2 := by rw [opClock]; gcongr
+ have hv' := Nat.mul_le_mul he hv
+ unfold clock timeWith GramScalar.clock allowance
+ generalize h₁ : codeCost .describe = a at *
+ generalize h₂ : codeCost .gram = b at *
+ ring_nf at hv' hc₁ hc₂ hm ha ⊢
+ omega
+
+/-- Read the local clock and space bounds directly from the compact inputs. -/
+theorem clock_space_le (w v e x B A S : ℕ) (hw : w ≤ x) (hv : v ≤ x) (he : e ≤ x) :
+ clock w v e B ≤ 2*B + allowance x ∧ space w v e A S ≤ max A S + allowance x := by
+ have h := overhead_le w v e x hw hv he
+ exact ⟨(clock_eq ..).le.trans (Nat.add_le_add_left h _),
+ (space_le_clock ..).trans (Nat.add_le_add_left h _)⟩
+
+end RankQuery.Stack.DescribeAdapter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryDescribeSpace.lean b/lean/OAI/Computability/VPVNP/RankQueryDescribeSpace.lean
new file mode 100644
index 0000000000..f087b253b4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryDescribeSpace.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.RankQueryDescribeAdapter
+import OAI.Computability.VPVNP.RankQueryGramScalarSpace
+import OAI.Computability.VPVNP.RankQueryRoutineSpace
+
+/-! # Independent time and space bounds for the Schur description action -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.DescribeAdapter
+
+open RAMTape BurstRAM Dispatch Engine UniversalCountStack
+
+variable {K : Type} [DecidableEq K] {p e n m w v d U Z A S B T : ℕ} [Fact p.Prime] [NeZero e]
+ {c : SliceArithmetic.Vector p e}
+
+/-- A local call's per-port peak as a function of the initial height. -/
+def CallSpace (call : Bool → FiniteRoutine (GramScalar.Port K)) (entry : Entry n (Scalar c))
+ (w v m d T : ℕ) (peak : ℕ → ℕ) (ready : Stacks K → Prop) : Prop :=
+ ∀ {A : ℕ} (i j : Fin n) (z : ℕ) (neg : Bool) (persist : Word w) (rs : GramScalar.Registers w),
+ (∀ a, gramInput i j z m a < 2^d) → (∀ a, (rs (Code.inReg capacity a)).val = gramInput i j z m a) →
+ ∀ s : Stacks K, ready s →
+ (∀ a, (GramScalar.bank (GramScalar.wordBank persist rs) (GramRead.arithmeticBank v c [] []) s a).length ≤ A) →
+ ∃ t ≤ T, ∃ rs' out, ready out ∧ (∀ a, rs' (Code.inReg capacity a) = rs (Code.inReg capacity a)) ∧
+ (call neg).BoundedRun (peak A) t
+ (GramScalar.bank (GramScalar.wordBank persist rs) (GramRead.arithmeticBank v c [] []) s)
+ (GramScalar.bank (GramScalar.wordBank persist rs')
+ (GramRead.arithmeticBank v c [] (scalar v (if neg then -entry i j z else entry i j z))) out)
+
+omit [NeZero e] in
+theorem value_bounded (call : Bool → FiniteRoutine (GramScalar.Port K)) (entry : Entry n (Scalar c))
+ {ready : Stacks K → Prop} {peak : ℕ → ℕ} (hc : CallRuns call entry w v m d T ready)
+ (hspace : CallSpace call entry w v m d T peak ready) (hpeak : A ≤ peak A)
+ (hd : d ≤ w) (i j : Fin n) (z : ℕ) (neg : Bool) (live saved : Data) (aux : Stacks (Aux K))
+ (haux : RightReady w v m c ready aux) (he : ∀ a, gramInput i j z m a < 2^d)
+ (hdesc : ∀ a : Fin 3, aux (.inl (outputSlot ⟨a.val+1,by omega⟩)) =
+ UniversalCountStack.digits w (gramInput i j z m ⟨a.val,by omega⟩))
+ (start : ∀ k, (store live saved [] [] aux k).length ≤ A) :
+ ∃ t ≤ T, ∃ out, RightReady w v m c ready out ∧ (∀ x, out (.inl x) = aux (.inl x)) ∧
+ (valueRoutine call neg).BoundedRun (peak A) t (store live saved [] [] aux)
+ (store live saved [] (scalar v (if neg then -entry i j z else entry i j z)) out) := by
+ obtain ⟨t,ht,out,hready,hsame,hrun⟩ := value_runs call entry hc hd i j z neg live saved aux haux he hdesc
+ obtain ⟨base,persist,localBank,hparams,hlocal,hs⟩ := haux
+ obtain ⟨hreg,hin⟩ := prepare i j z live saved aux base persist localBank hparams hs hd he hdesc
+ obtain ⟨_,_,_,_,_,_,hb⟩ := hspace i j z neg persist _ he hreg localBank hlocal (fun k => hin k ▸ start (gramPorts k))
+ exact ⟨t,ht,out,hready,hsame,hb.lift_trace gramPorts_injective hrun (fun k => (start k).trans hpeak) hin⟩
+
+/-- Bound on each stack during description from initial height `A`. The local coefficient call
+uses `peak` after the descriptor program, with additional room for clearing, copying and
+writing a literal. -/
+def peakWith (w v e A : ℕ) (peak : ℕ → ℕ) := peak (A+Operation.describe.clock w) + (10*(w+1)+2) + 7*(e*v)+3 + (5*w+3)
+
+/-- Peak stack height for a Schur description with signed Gram entries, using `A` for initial
+height and `S` for each matrix-entry read. -/
+def space (w v e A S : ℕ) := peakWith w v e A (fun a => GramScalar.space w v e a S)
+
+/-- A Schur action shares the input bank's height bound across long matrix
+reads. The three-bit dispatch and the one-bit Gram tag restore their inputs. -/
+theorem describe_entries_bounded (call : Bool → FiniteRoutine (GramScalar.Port K)) (entry : Entry n (Scalar c))
+ {ready : Stacks K → Prop} {peak : ℕ → ℕ} (hc : CallRuns call entry w v m d T ready)
+ (hspace : CallSpace call entry w v m d T peak ready) (hpeak : ∀ a, a ≤ peak a)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hp : (d+1)*widthFactor ≤ w) (hd : d ≤ w)
+ (hsize : n+U+Z+m+8 < 2^d)
+ (q : SchurKey n U Z) (fs : List (F n U Z c)) (aux : Stacks (Aux K)) (hs : Ready w v n m c ready aux)
+ (start : ∀ k, (atControl w v (.enter q) fs aux [] k).length ≤ A) :
+ ∃ t ≤ timeWith w v e T, ∃ out, Ready w v n m c ready out ∧
+ (describeWith call).BoundedRun (peakWith w v e A peak) t (atControl w v (.enter q) fs aux)
+ (match (SchurKey.program entry).describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false]) := by
+ obtain ⟨t,ht,out,hout,whole⟩ := describe_entries call entry hc hw hw₃ hp hd hsize q fs aux hs
+ refine ⟨t,ht,out,hout,?_⟩
+ let vs := Dispatch.describe.eval (inputs q 0)
+ let saved := history w v fs
+ let data := fields w [] q [] [] []
+ let A₀ := A+Operation.describe.clock w
+ let P := peakWith w v e A peak
+ have h₀ : A₀ ≤ peak A₀ := hpeak _
+ have h₁ : peak A₀ ≤ P := by dsimp [P,peakWith,A₀]; omega
+ have bounded (i : Fin 8) : inputs q 0 i < 2^d := by
+ have hq (j : Fin 6) : q.words j < 2^d := (q.words_le j).trans_lt (by omega)
+ fin_cases i <;> first | exact hq _ | (simp [inputs] <;> omega)
+ obtain ⟨t₀,ht₀,mid,_,hstage,words,houtside⟩ :=
+ EngineAlias.stageDescribe_runs leftBank q saved [] [] aux hs.1 bounded hd hp
+ have stage := spaceRun_of_steps hstage (fun k => Nat.add_le_add (start k) ht₀)
+ have hm : RightReady w v m c ready mid := by
+ obtain ⟨rs,persist,localBank,hparams,hlocal,hbank⟩ := hs.2
+ exact ⟨rs,persist,localBank,hparams,hlocal,fun i => (houtside (.inr i) (fun _ h => by contradiction)).trans (hbank i)⟩
+ have hmid (k : Engine.Port (Aux K)) : (atControl w v (.enter q) fs mid [] k).length ≤ peak (A+Operation.describe.clock w) := (stage.final_cap k).trans h₀
+ have valid : ValidDescription n Z vs := describe_valid q 0
+ have htag : vs 0 < 2^3 := by have := valid.1; omega
+ have finish {u : ℕ} {endBank : Stacks (Engine.Port (Aux K))}
+ (arm : (entryArm call (vs 0)).BoundedRun P u (atControl w v (.enter q) fs mid) endBank) :
+ (describeWith call).BoundedRun P t (atControl w v (.enter q) fs aux)
+ (match (SchurKey.program entry).describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false]) := by
+ have routed := TagRouter.digits_bounded (.aux (.inl (outputSlot 0))) (entryArm call) hw₃ htag _ _ (words 0) arm
+ have total := (FiniteRoutine.BoundedRun.enlarge (r := EngineAlias.stageDescribe leftBank) stage (h₀.trans h₁)).followedBy routed
+ obtain ⟨eq₁,eq₂⟩ := FiniteRoutine.return_unique total.runs whole
+ rw [eq₁,eq₂] at total; exact total
+ have casesTag : vs 0 = 4 ∨ vs 0 = 0 ∨ vs 0 = 1 ∨ vs 0 = 2 ∨ vs 0 = 3 := by have := valid.1; omega
+ rcases casesTag with h4 | h0 | h1 | hread
+ · have ha := Describe.arity_runs hw wires q fs mid (clean hm) (vs 1) (words 1)
+ apply finish
+ simp only [entryArm,h4,ite_true]
+ apply spaceRun_of_steps ha
+ intro k; have := hmid k; unfold P peakWith; omega
+ · obtain ⟨u,hu,ha⟩ := Describe.terminal_runs (w := w) hw wires q fs mid (clean hm) false
+ apply finish
+ simp [entryArm,h0]
+ apply spaceRun_of_steps ha
+ intro k; have := hmid k; unfold P peakWith; omega
+ · obtain ⟨u,hu,ha⟩ := Describe.terminal_runs (w := w) hw wires q fs mid (clean hm) true
+ apply finish
+ simp [entryArm,h1]
+ apply spaceRun_of_steps ha
+ intro k; have := hmid k; unfold P peakWith; omega
+ · obtain ⟨hi,hj,hz⟩ := valid.2 hread
+ let i : Fin n := ⟨vs 1,hi⟩
+ let j : Fin n := ⟨vs 2,hj⟩
+ let neg := decide (vs 0 = 3)
+ have he (a : Fin 8) : gramInput i j (vs 3) m a < 2^d := by fin_cases a <;> simp [gramInput,i,j] <;> omega
+ have hword (a : Fin 3) : mid (.inl (outputSlot ⟨a.val+1,by omega⟩)) =
+ UniversalCountStack.digits w (gramInput i j (vs 3) m ⟨a.val,by omega⟩) := by fin_cases a <;> exact words _
+ obtain ⟨_,_,last,_,_,hr⟩ := value_bounded call entry hc hspace h₀ hd i j (vs 3) neg data saved mid hm he hword stage.final_cap
+ let r := if neg then -entry i j (vs 3) else entry i j (vs 3)
+ obtain ⟨u,hu,hf⟩ := Describe.finish_runs (w := w) (v := v) q fs r last
+ have hf' := spaceRun_of_steps hf (fun k => Nat.add_le_add (hr.final_cap k) hu)
+ apply finish
+ simp only [entryArm,ite_eq_right (show vs 0 ≠ 4 by omega),ite_eq_right (show vs 0 ≠ 0 by omega),
+ ite_eq_right (show vs 0 ≠ 1 by omega)]
+ exact (hr.enlarge h₁).followedBy (FiniteRoutine.BoundedRun.enlarge (r := Describe.finish) hf' (by dsimp [P,peakWith,A₀]; omega))
+
+theorem describe_bounded (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hp : (d+1)*widthFactor ≤ w) (hd : d ≤ w)
+ (hsize : n+U+Z+m+8 < 2^d)
+ (q : SchurKey n U Z) (fs : List (F n U Z c)) (aux : Stacks (Aux K)) (hs : Ready w v n m c ready aux)
+ (start : ∀ k, (atControl w v (.enter q) fs aux [] k).length ≤ A) :
+ ∃ t ≤ clock w v e B, ∃ out, Ready w v n m c ready out ∧
+ (describe read).BoundedRun (space w v e A S) t (atControl w v (.enter q) fs aux)
+ (match (SchurKey.program (weightedGramEntryCoeff M)).describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false]) := by
+ apply describe_entries_bounded (GramScalar.machine read) (weightedGramEntryCoeff M)
+ (GramScalar.machine_runs read M hc.correct hw (by omega) hp)
+ (fun {a} => GramScalar.machine_bounded (A := a) read M hc hw (by omega) hp) _ hw hw₃ hp hd hsize q fs aux hs start
+ intro a; unfold GramScalar.space; have := le_max_left (a+Operation.gram.clock w) S; omega
+
+end RankQuery.Stack.DescribeAdapter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryDescribeWords.lean b/lean/OAI/Computability/VPVNP/RankQueryDescribeWords.lean
new file mode 100644
index 0000000000..f5ffac6535
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryDescribeWords.lean
@@ -0,0 +1,35 @@
+import OAI.Computability.VPVNP.RankQueryStackPhysical
+
+/-! # Valid tags and row addresses of each Schur descriptor -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Dispatch
+
+/-- A read carries two valid matrix indices. The largest tag is the arity tag. -/
+def ValidDescription (n Z : ℕ) (v : Fin 6 → ℕ) : Prop :=
+ v 0 < 5 ∧ (v 0 = 2 ∨ v 0 = 3 → v 1 < n ∧ v 2 < n ∧ v 3 ≤ Z)
+
+theorem describe_valid {n U Z : ℕ} (q : SchurKey n U Z) (k : ℕ) :
+ ValidDescription n Z (describe.eval (inputs q k)) := by
+ unfold ValidDescription
+ cases q with
+ | product d b u z =>
+ by_cases hd : d.val = 0 <;> by_cases hb : b.count = 0 <;>
+ by_cases hu : u.val = 0 <;> by_cases hz : z.val = 0 <;> simplify_dispatch
+ | factor a u z =>
+ by_cases hu : u.val = 0 <;> by_cases hu' : u.val = 1 <;> by_cases hz : z.val = 0 <;> simplify_dispatch
+ omega
+ | outer | inner | one => simplify_dispatch
+ | scalar neg i j z => cases neg <;> simplify_dispatch <;> omega
+ | power a q =>
+ by_cases h0 : q.exponent.val = 0 <;> by_cases h1 : q.exponent.val = 1 <;>
+ by_cases hij : q.row.val = q.col.val <;> by_cases hz : q.degree.val = 0 <;> simplify_dispatch <;> omega
+
+end RankQuery.Stack.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryExecution.lean b/lean/OAI/Computability/VPVNP/RankQueryExecution.lean
new file mode 100644
index 0000000000..50cb80a34c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryExecution.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.RankCursorMachine
+import OAI.Computability.VPVNP.RankCursorSchur
+
+/-! # Full rectangular rank query on the determinant stack
+
+A single finite control traverses the rectangle of bidegrees. At each
+request it stages the six fields of the weighted Gram determinant, executes
+the Schur engine, tests the returned scalar, and advances or terminates.
+The result register contains the rank of the original rectangular matrix
+over the advised field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch
+
+variable {K : Type} [DecidableEq K] {n m w v A B b p e : ℕ}
+ [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+/-- Run the rectangular rank scan with the Schur engine's root query at each bidegree and leave
+the resulting rank in the cursor registers. -/
+def fullRank (a : Engine.Actions K) : FiniteRoutine (ScanPort K) := rankMachine (rootQuery a)
+
+/-- Step bound for scanning an `n` by `m` matrix. It allows a Schur root query and cursor check
+at each of the `(n+1)*((n+m)*n+1)` bidegrees. -/
+def rankTime (n m B w v e : ℕ) :=
+ let Z := (n+m)*n
+ ((n+1)*(Z+1))*(rootQueryClock n n Z B w v e+checkClock w v e+1)+2
+
+/-- The rectangular query's only engine hypotheses specify the concrete
+dispatch, entry, and arithmetic routines. No rank-oracle hypothesis enters
+the scan or the decision to stop. -/
+theorem fullRank_runs [Fact (Irreducible (SliceArithmetic.modulus c))]
+ (a : Engine.Actions K) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ (ready : Stacks K → Prop) (pending : SchurKey n n ((n+m)*n) → Stacks K → Prop)
+ (spec : Engine.Contracts a (SchurKey.program (U := n) (Z := (n+m)*n) (weightedGramEntryCoeff M))
+ w v B (SchurKey.arityBound n n ((n+m)*n)) ready pending)
+ (hcap : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (hwidth : (b+1)*control.wordFactor ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (hsize : max 1 (max n ((n+m)*n)) < 2^b)
+ (persist : Word w) (rs : Regs Registers.R w) (aux : Stacks K) (haux : ready aux)
+ (hr : Registers.Stores rs ((n+m)*n) n ((n+m)*n)) :
+ ∃ k ≤ rankTime n m B w v e, ∃ out a', ready a' ∧
+ Registers.Stores out ((n+m)*n) (M.map (Scalar.interpretation c)).rank 0 ∧
+ (fullRank a).Runs k (scanBank n persist rs [true] (idle aux)) (scanBank n persist out [] (idle a')) := by
+ let Z := (n+m)*n
+ apply rankMachine_runs (rootQuery a) M ready (rootQueryClock n n Z B w v e) _ hwidth hv hsize
+ persist rs aux haux hr
+ intro u z hu hz p₀ rs₀ aux₀ hrs hready
+ let i : Limit n := ⟨u, Nat.lt_succ_of_le hu⟩
+ let j : Limit Z := ⟨z, Nat.lt_succ_of_le hz⟩
+ have h := rootQuery_runs spec hcap (weightedGram M) (weightedGramEntryCoeff_eq M)
+ p₀ rs₀ i j hrs aux₀ hready
+ rw [SchurKey.compute_correct (weightedGram M) _ (weightedGramEntryCoeff_eq M) u z]
+ exact h
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryExecutionSpace.lean b/lean/OAI/Computability/VPVNP/RankQueryExecutionSpace.lean
new file mode 100644
index 0000000000..2ffd6f40f5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryExecutionSpace.lean
@@ -0,0 +1,119 @@
+import OAI.Computability.VPVNP.RankCursorMachine
+import OAI.Computability.VPVNP.RankCursorSpaceLoop
+
+/-! # Peak storage through a full rank scan
+
+The Schur engine releases its traversal stack at every coefficient. The
+outer scan reuses one scalar and a fixed register bank. Its space cap
+depends on the cap of a single root query and on the short cursor-update
+clock, independently of the number or total time of the root queries.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch UniversalCountStack
+
+variable {K : Type} [DecidableEq K] {n m w v e p b A B C : ℕ}
+ [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+/-- A root may take `B` instructions while its intermediate stacks fit `C` bits each. -/
+def RootBoundedRead (query : FiniteRoutine (ScanPort K)) (Z w v n B C : ℕ)
+ (value : ℕ → ℕ → Scalar c) (ready : Stacks K → Prop) : Prop :=
+ ∀ (u z : ℕ), u ≤ n → z ≤ Z → ∀ (persist : Word w) (rs : Regs Registers.R w) aux,
+ Registers.Stores rs Z u z → ready aux → ∃ k ≤ B, ∃ aux', ready aux' ∧
+ query.BoundedRun C k (scanBank n persist rs [] (idle aux))
+ (scanBank n persist rs [] (yielded aux' (Engine.scalar v (value u z))))
+
+/-- Per-stack cap for the entire rank loop, taking the maximum of the root-query peak `C` and
+the space for the returned scalar and cursor check above auxiliary height `A`. -/
+def outerRankSpace (C A w v e : ℕ) := max C (A+w+e*v+1+checkClock w v e)
+
+omit [DecidableEq K] in
+private theorem readBank_length (n : ℕ) (persist : Word w) (rs : Regs Registers.R w) (aux : Stacks K)
+ (haux : ∀ k, (aux k).length ≤ A) (bits flags : List Bool) (k : ScanPort K) :
+ (scanBank n persist rs flags (yielded aux bits) [] k).length ≤ A+w+bits.length+flags.length := by
+ cases k with
+ | cursor j =>
+ have h := Registers.bank_length persist rs flags j
+ change (Registers.bank persist rs flags j).length ≤ _
+ omega
+ | engine j =>
+ cases j with
+ | frame f => cases f <;> exact Nat.zero_le _
+ | aux i => exact (haux i).trans (by omega : A ≤ A+w+bits.length+flags.length)
+ | result => change bits.length ≤ _; omega
+ | condition => exact Nat.zero_le _
+ | rows | depth => simp only [scanBank, length_digits]; omega
+ | scratch => exact Nat.zero_le _
+
+/-- Every intermediate stack through all coefficient requests fits the same
+cap. In particular no part of the exponentially long rank loop is stored
+as a list of instructions or scalar outputs. -/
+theorem rankMachine_boundedRun [Fact (Irreducible (SliceArithmetic.modulus c))]
+ (query : FiniteRoutine (ScanPort K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ (ready : Stacks K → Prop) (hcap : ∀ a, ready a → ∀ k, (a k).length ≤ A)
+ (hq : RootBoundedRead query ((n+m)*n) w v n B C (SchurKey.compute (weightedGramEntryCoeff M)) ready)
+ (hwidth : (b+1)*control.wordFactor ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (hsize : max 1 (max n ((n+m)*n)) < 2^b)
+ (persist : Word w) (initialRegs : Regs Registers.R w) (aux : Stacks K) (haux : ready aux)
+ (hregs : Registers.Stores initialRegs ((n+m)*n) n ((n+m)*n)) :
+ let Z := (n+m)*n
+ ∃ k ≤ ((n+1)*(Z+1))*(B+checkClock w v e+1)+2, ∃ rs' aux',
+ ready aux' ∧ Registers.Stores rs' Z (M.map (Scalar.interpretation c)).rank 0 ∧
+ (rankMachine query).BoundedRun (outerRankSpace C A w v e) k
+ (scanBank n persist initialRegs [true] (idle aux)) (scanBank n persist rs' [] (idle aux')) := by
+ let Z := (n+m)*n
+ let cap := outerRankSpace C A w v e
+ let val := SchurKey.compute (weightedGramEntryCoeff M)
+ let q (u z : ℕ) := decide (val u z = 0)
+ let good (st : State) (s : Stacks (ScanPort K)) : Prop :=
+ st.words 1 ≤ n ∧ st.words 2 ≤ Z ∧ ∃ rs a, ready a ∧ Registers.Stores rs Z (st.words 1) (st.words 2) ∧
+ s = scanBank n persist rs [st.continues] (idle a)
+ have flag (st : State) (s : Stacks (ScanPort K)) (hs : good st s) : s (.cursor .flag) = [st.continues] := by
+ obtain ⟨_,_,_,_,_,_,rfl⟩ := hs; rfl
+ have fits (st : State) (s : Stacks (ScanPort K)) (hs : good st s) (k : ScanPort K) : (s k).length ≤ cap := by
+ obtain ⟨_,_,rs,a,ha,_,rfl⟩ := hs
+ have h := readBank_length n persist rs a (hcap a ha) [] [st.continues] k
+ simp only [List.length_nil, List.length_singleton, Nat.add_zero] at h
+ apply h.trans
+ dsimp only [cap, outerRankSpace]
+ exact (by omega : A+w+1 ≤ A+w+e*v+1+checkClock w v e).trans (le_max_right ..)
+ have one (u z : ℕ) (s : Stacks (ScanPort K)) (hs : good (.running u z) s) :
+ ∃ k ≤ B+checkClock w v e, ∃ out, (query.followedBy check).BoundedRun cap k (Function.update s (.cursor .flag) []) out ∧
+ good (step q Z (.running u z)) out := by
+ obtain ⟨hu,hz,rs,a,ha,hreg,rfl⟩ := hs
+ change u ≤ n at hu
+ change z ≤ Z at hz
+ obtain ⟨k, hk, a', ha', hread⟩ := hq u z hu hz persist rs a hreg ha
+ have fit (i : Fin 8) : input Z u z (q u z) i < 2^b := by
+ have hqv : (q u z).toNat ≤ 1 := by cases q u z <;> decide
+ change max 1 (max n Z) < 2^b at hsize
+ fin_cases i <;> simp [input] <;> omega
+ obtain ⟨d, hd, rs', hcheck, hstore⟩ := check_runs hv n Z u z persist rs a' (val u z) hwidth fit hreg
+ have hc := spaceRun_of_steps (cap := cap) hcheck (fun k => by
+ have h := readBank_length n persist rs a' (hcap a' ha') (Engine.scalar v (val u z)) [] k
+ rw [Engine.scalar_length, List.length_nil, Nat.add_zero] at h
+ apply (Nat.add_le_add h hd).trans
+ exact (by omega : A+w+e*v+checkClock w v e ≤ A+w+e*v+1+checkClock w v e).trans (le_max_right ..))
+ rw [clear_flag]
+ exact ⟨k+d, Nat.add_le_add hk hd, _, FiniteRoutine.BoundedRun.followedBy (a := query) (b := check) (hread.mono_cap (le_max_left ..)) hc,
+ (advance_bounds Z n u z hu hz (q u z)).1, (advance_bounds Z n u z hu hz (q u z)).2,
+ rs', a', ha', hstore, rfl⟩
+ have init : good (.running n Z) (scanBank n persist initialRegs [true] (idle aux)) :=
+ ⟨le_rfl,le_rfl,initialRegs,aux,haux,hregs,rfl⟩
+ obtain ⟨k,hk,out,hout,hrun⟩ := scan_boundedRun (.cursor .flag) (query.followedBy check) q Z
+ (B+checkClock w v e) cap good flag fits one _ _ init
+ rw [show answer q Z (.running n Z) = (M.map (Scalar.interpretation c)).rank from initial_schur_answer M] at hout
+ obtain ⟨_,_,outRegs,a,ha,hst,rfl⟩ := hout
+ exact ⟨k, by simpa only [remaining, Nat.succ_mul, Nat.add_assoc] using hk,
+ outRegs,a,ha,hst, by simpa only [rankMachine, clear_flag] using hrun⟩
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryGramAlias.lean b/lean/OAI/Computability/VPVNP/RankQueryGramAlias.lean
new file mode 100644
index 0000000000..2d4d2d6f93
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryGramAlias.lean
@@ -0,0 +1,298 @@
+import OAI.Computability.VPVNP.RankQueryGramScalar
+import OAI.Computability.VPVNP.RankQueryStackStages
+import OAI.Computability.VPVNP.RankQueryDescribeArms
+
+/-! # Installing Gram reads at the Schur engine's actual ports
+
+Three input registers read the Schur output descriptor directly. The Gram
+multiplier's accumulator is the engine's return-value port. Both banks keep
+their input widths, advice and private-register invariants across calls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.DescribeAdapter
+
+open BurstRAM RAMTape Dispatch Engine
+
+/-- Auxiliary ports of the descriptor adapter, combining the Schur dispatch word bank with the
+signed Gram coefficient and entry-reader ports. -/
+abbrev Aux (K : Type) := EngineAlias.Small ⊕ GramScalar.Port K
+
+variable {K : Type}
+
+/-- Embed the Schur dispatch word bank in the left summand of the adapter's auxiliary ports. -/
+def leftBank : EngineAlias.Small ↪ Aux K := ⟨Sum.inl,Sum.inl_injective⟩
+
+/-- The Schur dispatch register that holds output word `i` of the six-word descriptor. -/
+def outputSlot (i : Fin 6) : EngineAlias.Small := .reg (Code.outReg capacity i)
+
+/-- Place the six descriptor wires in dispatch output registers and take the coefficient,
+scratch and extra wires from the Gram bank. -/
+def wires : Describe.Wire ↪ Aux K where
+ toFun
+ | .desc i => .inl (outputSlot i)
+ | .coeff => .inr (.mul (.inr .coeff))
+ | .scratch => .inr .tmp
+ | .extra => .inr .extra
+ inj' := by
+ intro a b h; cases a <;> cases b <;> simp_all [outputSlot,Code.outReg,Fin.ext_iff]
+
+/-- Identify the aliased Gram inputs by mapping word registers zero through two to descriptor
+outputs one through three. Other ports yield `none`. -/
+def slot : GramScalar.Port K → Option (Fin 6)
+ | .words (.reg i) => if hi : i.val < 3 then some ⟨i.val+1,by omega⟩ else none
+ | _ => none
+
+/-- Connect the first three Gram input registers to the Schur descriptor, the product
+accumulator to the engine result, and the remaining ports to Gram auxiliary storage. -/
+def gramPorts (x : GramScalar.Port K) : Engine.Port (Aux K) :=
+ match slot x with
+ | some j => .aux (.inl (outputSlot j))
+ | none => match x with
+ | .mul (.inr .acc) => .result
+ | z => .aux (.inr z)
+
+private theorem slot_some {z : GramScalar.Port K} {j : Fin 6} (h : slot z = some j) :
+ ∃ i : EngineAlias.Reg, z = .words (.reg i) ∧ i.val < 3 ∧ j.val = i.val+1 := by
+ cases z with
+ | words z =>
+ cases z with
+ | reg i => simp only [slot] at h; split_ifs at h with hs; cases h; exact ⟨i,rfl,hs,rfl⟩
+ | _ => contradiction
+ | _ => contradiction
+
+private theorem plain {x : GramScalar.Port K} (hx : slot x = none) (ha : x ≠ .mul (.inr .acc)) :
+ gramPorts x = .aux (.inr x) := by
+ unfold gramPorts; rw [hx]
+ cases x with
+ | mul x => rcases x with x|x
+ · rfl
+ · cases x <;> first | rfl | exact (ha rfl).elim
+ | _ => rfl
+
+private theorem aliased {x : GramScalar.Port K} {j : Fin 6} (h : slot x = some j) :
+ gramPorts x = .aux (.inl (outputSlot j)) := by unfold gramPorts; rw [h]
+
+theorem gramPorts_injective : Function.Injective (gramPorts (K := K)) := by
+ intro a b he
+ cases ha : slot a <;> cases hb : slot b
+ · by_cases h₁ : a = .mul (.inr .acc) <;> by_cases h₂ : b = .mul (.inr .acc)
+ · exact h₁.trans h₂.symm
+ · subst a; rw [plain hb h₂] at he; contradiction
+ · subst b; rw [plain ha h₁] at he; contradiction
+ · rw [plain ha h₁,plain hb h₂] at he; exact Sum.inr.inj (Engine.Port.aux.inj he)
+ · rw [aliased hb] at he
+ by_cases hh : a = .mul (.inr .acc)
+ · subst a; contradiction
+ · rw [plain ha hh] at he; simp at he
+ · rw [aliased ha] at he
+ by_cases hh : b = .mul (.inr .acc)
+ · subst b; contradiction
+ · rw [plain hb hh] at he; simp at he
+ · rename_i x y
+ obtain ⟨i,rfl,_,hi⟩ := slot_some ha
+ obtain ⟨j,rfl,_,hj⟩ := slot_some hb
+ rw [aliased ha,aliased hb] at he
+ have eq := congrArg Fin.val (ISA.Port.reg.inj (Sum.inl.inj (Engine.Port.aux.inj he)))
+ simp only [Code.outReg] at eq
+ exact congrArg (fun r => GramScalar.Port.words (.reg r)) (Fin.ext (by omega))
+
+variable {w v p e n m : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- Gram input register three holds the column count `m`, and input registers four through
+seven hold zero. -/
+def FixedParams (rs : GramScalar.Registers w) (m : ℕ) : Prop :=
+ ∀ a : Fin 8, 3 ≤ a.val → (rs (Code.inReg capacity a)).val = gramInput 0 0 0 m a
+
+/-- The Gram bank has the fixed inputs for `m`, a clean multiplier with packed field advice and
+empty operands, and an entry-reader bank satisfying `ready`. -/
+def RightReady (w v m : ℕ) (c : SliceArithmetic.Vector p e) (ready : Stacks K → Prop)
+ (aux : Stacks (Aux K)) : Prop :=
+ ∃ (rs : GramScalar.Registers w) (persist : Word w) (localBank : Stacks K),
+ FixedParams rs m ∧ ready localBank ∧ ∀ z, aux (.inr z) =
+ GramScalar.bank (GramScalar.wordBank persist rs) (GramRead.arithmeticBank v c [] []) localBank z
+
+/-- The Schur dispatch bank is prepared for row count `n` and the Gram bank for column count
+`m`, field advice `c` and a ready entry reader. -/
+def Ready (w v n m : ℕ) (c : SliceArithmetic.Vector p e) (ready : Stacks K → Prop)
+ (aux : Stacks (Aux K)) : Prop := EngineAlias.Ready leftBank w n aux ∧ RightReady w v m c ready aux
+
+theorem clean {ready : Stacks K → Prop} {aux : Stacks (Aux K)} (h : RightReady w v m c ready aux) :
+ Describe.Clean wires v c aux := by
+ obtain ⟨rs,persist,localBank,_,_,hp⟩ := h
+ exact ⟨hp _,hp _,hp _⟩
+
+variable [DecidableEq K] [Fact p.Prime] [NeZero e]
+
+/-- Install the coefficient callback selected by `neg` on the engine's Gram ports so it reads
+the descriptor and writes to the result stack. -/
+def valueRoutine (call : Bool → FiniteRoutine (GramScalar.Port K)) (neg : Bool) : FiniteRoutine (Engine.Port (Aux K)) :=
+ (call neg).onPorts gramPorts
+
+/-- Use the supplied matrix-entry reader to evaluate a weighted Gram coefficient directly into
+the engine result, negating it when `neg` is true. -/
+def gram (read : FiniteRoutine (MacaulayRead.Port K)) (neg : Bool) : FiniteRoutine (Engine.Port (Aux K)) :=
+ valueRoutine (GramScalar.machine read) neg
+
+private theorem digits_val (x : Word w) : UniversalCountStack.digits w x.val = wordBits x := by
+ unfold UniversalCountStack.digits
+ rw [show Fin.ofNat (2^w) x.val = x by apply Fin.ext; exact Nat.mod_eq_of_lt x.isLt]
+
+/-- Reuse the three Schur output words as the row, column and degree of a
+Gram input. The inactive Gram copies of these words stay in the caller. -/
+def prepareRegs (base : GramScalar.Registers w) (env : Fin 8 → ℕ) : GramScalar.Registers w :=
+ fun a => if h : a.val < 3 then Fin.ofNat _ (env ⟨a.val,by omega⟩) else base a
+
+omit [DecidableEq K] [Fact p.Prime] [NeZero e] in
+theorem prepare {d : ℕ} (i j : Fin n) (z : ℕ) (live saved : Data) (aux : Stacks (Aux K))
+ (base : GramScalar.Registers w) (persist : Word w) (localBank : Stacks K) (hparams : FixedParams base m)
+ (hs : ∀ a, aux (.inr a) = GramScalar.bank (GramScalar.wordBank persist base) (GramRead.arithmeticBank v c [] []) localBank a)
+ (hd : d ≤ w) (he : ∀ a, gramInput i j z m a < 2^d)
+ (hdesc : ∀ a : Fin 3, aux (.inl (outputSlot ⟨a.val+1,by omega⟩)) =
+ UniversalCountStack.digits w (gramInput i j z m ⟨a.val,by omega⟩)) :
+ let rs := prepareRegs base (gramInput i j z m)
+ (∀ a, (rs (Code.inReg capacity a)).val = gramInput i j z m a) ∧
+ ∀ a, store live saved [] [] aux (gramPorts a) =
+ GramScalar.bank (GramScalar.wordBank persist rs) (GramRead.arithmeticBank v c [] []) localBank a := by
+ let env := gramInput i j z m
+ let rs := prepareRegs base env
+ have hreg (a : Fin 8) : (rs (Code.inReg capacity a)).val = env a := by
+ by_cases ha : a.val < 3
+ · change Fin.val (if h : a.val < 3 then Fin.ofNat (2^w) (env ⟨a.val,by omega⟩) else base (Code.inReg capacity a)) = _
+ rw [dite_eq_left ha]; exact Nat.mod_eq_of_lt ((he a).trans_le (Nat.pow_le_pow_right (by decide) hd))
+ · have hp' := hparams a (by omega)
+ change Fin.val (if h : a.val < 3 then Fin.ofNat (2^w) (env ⟨a.val,by omega⟩) else base (Code.inReg capacity a)) = _
+ rw [dite_eq_right ha,hp']; fin_cases a <;> first | rfl | contradiction
+ refine ⟨hreg,?_⟩
+ intro a
+ cases hh : slot a with
+ | some b =>
+ obtain ⟨r,rfl,hlt,hval⟩ := slot_some hh
+ let ai : Fin 3 := ⟨r.val,hlt⟩
+ let ix : Fin 8 := ⟨r.val,by omega⟩
+ rw [aliased hh]
+ change aux (.inl (outputSlot b)) = wordBits (rs r)
+ rw [show b = ⟨ai.val+1,by omega⟩ from Fin.ext hval,hdesc ai, ← digits_val]
+ exact congrArg (UniversalCountStack.digits w) (hreg ix).symm
+ | none =>
+ by_cases ha : a = .mul (.inr .acc)
+ · subst a; rfl
+ · rw [plain hh ha]; change aux (.inr a) = _; rw [hs]
+ cases a with
+ | words a =>
+ cases a with
+ | reg a =>
+ have hn : ¬ a.val < 3 := by intro ha; simp [slot,ha] at hh
+ change wordBits (base a) = wordBits (rs a); simp [rs,prepareRegs,hn]
+ | _ => rfl
+ | _ => rfl
+
+/-- A signed scalar-entry call uses two row indices and a coefficient degree.
+Its fixed program and mathematical entry map may come from the weighted
+Gram matrix or a constant-polynomial Cramer matrix. -/
+def CallRuns (call : Bool → FiniteRoutine (GramScalar.Port K)) (entry : Entry n (Scalar c))
+ (w v m d T : ℕ) (ready : Stacks K → Prop) : Prop :=
+ ∀ (i j : Fin n) (z : ℕ) (neg : Bool) (persist : Word w) (rs : GramScalar.Registers w),
+ (∀ a, gramInput i j z m a < 2^d) → (∀ a, (rs (Code.inReg capacity a)).val = gramInput i j z m a) →
+ ∀ s : Stacks K, ready s → ∃ t ≤ T, ∃ rs' out, ready out ∧
+ (∀ a, rs' (Code.inReg capacity a) = rs (Code.inReg capacity a)) ∧ (call neg).Runs t
+ (GramScalar.bank (GramScalar.wordBank persist rs) (GramRead.arithmeticBank v c [] []) s)
+ (GramScalar.bank (GramScalar.wordBank persist rs')
+ (GramRead.arithmeticBank v c [] (scalar v (if neg then -entry i j z else entry i j z))) out)
+
+omit [NeZero e] in
+theorem value_runs {d T : ℕ} (call : Bool → FiniteRoutine (GramScalar.Port K)) (entry : Entry n (Scalar c))
+ {ready : Stacks K → Prop} (hc : CallRuns call entry w v m d T ready)
+ (hd : d ≤ w)
+ (i j : Fin n) (z : ℕ) (neg : Bool) (live saved : Data) (aux : Stacks (Aux K)) (haux : RightReady w v m c ready aux)
+ (he : ∀ a, gramInput i j z m a < 2^d)
+ (hdesc : ∀ a : Fin 3, aux (.inl (outputSlot ⟨a.val+1,by omega⟩)) =
+ UniversalCountStack.digits w (gramInput i j z m ⟨a.val,by omega⟩)) :
+ ∃ t ≤ T, ∃ out, RightReady w v m c ready out ∧
+ (∀ x, out (.inl x) = aux (.inl x)) ∧ (valueRoutine call neg).Runs t
+ (store live saved [] [] aux) (store live saved []
+ (scalar v (if neg then -entry i j z else entry i j z)) out) := by
+ obtain ⟨base,persist,localBank,hparams,hlocal,hs⟩ := haux
+ let env := gramInput i j z m
+ let rs := prepareRegs base env
+ obtain ⟨hreg,hin⟩ := prepare i j z live saved aux base persist localBank hparams hs hd he hdesc
+ obtain ⟨t,ht,regs,localOut,hlout,hkeep,hcall⟩ :=
+ hc i j z neg persist rs he hreg localBank hlocal
+ let cleaned : GramScalar.Registers w := fun a => if a.val < 3 then base a else regs a
+ let final := Sum.elim (fun x => aux (.inl x)) (GramScalar.bank (GramScalar.wordBank persist cleaned)
+ (GramRead.arithmeticBank v c [] []) localOut)
+ let result := scalar v (if neg then -entry i j z else entry i j z)
+ have hcparams : FixedParams cleaned m := by
+ intro a ha
+ change Fin.val (if a.val < 3 then base (Code.inReg capacity a) else regs (Code.inReg capacity a)) = _
+ rw [ite_eq_right (by omega),hkeep]
+ change Fin.val (if h : a.val < 3 then Fin.ofNat (2^w) (env ⟨a.val,by omega⟩) else base (Code.inReg capacity a)) = _
+ rw [dite_eq_right (by omega), hparams a ha]
+ refine ⟨t,ht,final,⟨cleaned,persist,localOut,hcparams,hlout,fun _ => rfl⟩,fun _ => rfl,?_⟩
+ apply (call neg).runs_onPorts_framed gramPorts_injective hcall
+ · exact hin
+ · intro a
+ cases hh : slot a with
+ | some b =>
+ obtain ⟨r,rfl,hlt,hval⟩ := slot_some hh
+ let ai : Fin 3 := ⟨r.val,hlt⟩
+ let ix : Fin 8 := ⟨r.val,by omega⟩
+ rw [aliased hh]
+ change aux (.inl (outputSlot b)) = wordBits (regs r)
+ rw [show b = ⟨ai.val+1,by omega⟩ from Fin.ext hval,hdesc ai, ← digits_val]
+ exact congrArg (UniversalCountStack.digits w) ((congrArg Fin.val (hkeep ix)).trans (hreg ix)).symm
+ | none =>
+ by_cases ha : a = .mul (.inr .acc)
+ · subst a; rfl
+ · rw [plain hh ha]
+ cases a with
+ | words a =>
+ cases a with
+ | reg a =>
+ have hn : ¬ a.val < 3 := by intro ha; simp [slot,ha] at hh
+ change wordBits (cleaned a) = wordBits (regs a); simp [cleaned,hn]
+ | _ => rfl
+ | mul a => rcases a with a|a
+ · rfl
+ · cases a <;> first | rfl | exact (ha rfl).elim
+ | _ => rfl
+ · intro a ha
+ cases a with
+ | frame j => cases j <;> rfl
+ | condition => rfl
+ | result => exact (ha (.mul (.inr .acc)) rfl).elim
+ | aux a =>
+ rcases a with a|a
+ · rfl
+ · cases hh : slot a with
+ | some b =>
+ obtain ⟨r,rfl,hlt,_⟩ := slot_some hh
+ rw [show store live saved [] [] aux (.aux (.inr (.words (.reg r)))) = _ from hs _]
+ change wordBits (cleaned r) = wordBits (base r); simp [cleaned,hlt]
+ | none =>
+ by_cases hh' : a = .mul (.inr .acc)
+ · subst a; exact (hs (.mul (.inr .acc))).symm
+ · exact (ha a (plain hh hh')).elim
+
+theorem gram_runs {d B : ℕ} (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.Correct read M w v B ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₁ : 1 ≤ w) (hp : (d+1)*widthFactor ≤ w) (hd : d ≤ w)
+ (i j : Fin n) (z : ℕ) (neg : Bool) (live saved : Data) (aux : Stacks (Aux K)) (haux : RightReady w v m c ready aux)
+ (he : ∀ a, gramInput i j z m a < 2^d)
+ (hdesc : ∀ a : Fin 3, aux (.inl (outputSlot ⟨a.val+1,by omega⟩)) =
+ UniversalCountStack.digits w (gramInput i j z m ⟨a.val,by omega⟩)) :
+ ∃ t ≤ GramScalar.clock w v e B, ∃ out, RightReady w v m c ready out ∧
+ (∀ x, out (.inl x) = aux (.inl x)) ∧ (gram read neg).Runs t
+ (store live saved [] [] aux) (store live saved []
+ (scalar v (if neg then -weightedGramEntryCoeff M i j z else weightedGramEntryCoeff M i j z)) out) :=
+ value_runs (GramScalar.machine read) (weightedGramEntryCoeff M)
+ (GramScalar.machine_runs read M hc hw hw₁ hp) hd i j z neg live saved aux haux he hdesc
+
+end RankQuery.Stack.DescribeAdapter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryGramExecution.lean b/lean/OAI/Computability/VPVNP/RankQueryGramExecution.lean
new file mode 100644
index 0000000000..9012eedcc2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryGramExecution.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.RankQueryBoundedExecution
+import OAI.Computability.VPVNP.RankCursorDimensions
+import OAI.Computability.VPVNP.RankQueryStackGramRoot
+
+/-!
+# Rectangular rank on a streamed relation matrix
+
+From the binary row and column dimensions the machine constructs both scan
+bounds. It invokes the concrete Schur, weighted Gram, and field arithmetic
+controls. The remaining matrix-specific operation is a bounded read of one
+scalar entry. A single time budget and a separate stack-height budget cover
+every row prefix satisfying the same numerical size bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open RAMTape BurstRAM Dispatch
+
+/-- Sufficient binary width for the decision trees of both the Schur
+interpreter and the outer degree scan. -/
+def gramWidth (d : ℕ) := (2*d+7)*(max widthFactor control.wordFactor + 1)+3
+
+private theorem width_conditions {d w : ℕ} (h : gramWidth d ≤ w) :
+ 3 ≤ w ∧ d ≤ w ∧ 2*d+6 ≤ w ∧ (d+1)*widthFactor ≤ w ∧
+ (2*d+6+1)*widthFactor ≤ w ∧ (d+1)*control.wordFactor ≤ w := by
+ let b := max widthFactor control.wordFactor + 1
+ have h₁ : 2*d+7 ≤ (2*d+7)*b := Nat.le_mul_of_pos_right _ (Nat.succ_pos _)
+ have h₂ : (2*d+7)*widthFactor ≤ (2*d+7)*b :=
+ Nat.mul_le_mul_left _ ((le_max_left ..).trans (Nat.le_succ _))
+ have h₃ : (d+1)*control.wordFactor ≤ (2*d+7)*b :=
+ Nat.mul_le_mul (by omega) ((le_max_right ..).trans (Nat.le_succ _))
+ have h₄ : (d+1)*widthFactor ≤ (2*d+7)*widthFactor := Nat.mul_le_mul_right _ (by omega)
+ change (2*d+7)*b+3 ≤ w at h
+ rw [show 2*d+6+1 = 2*d+7 by omega]
+ omega
+
+/-- A root clock that depends on the common bit bound for the entire matrix
+and therefore applies to each smaller prefix. -/
+private def queryAllowance (d w v e B : ℕ) :=
+ loadClock w + (2^((2*d+8)*(2*d+5)) *
+ Engine.boundedStepTime (DescribeAdapter.clock w v e B) (Engine.Assembly.localBudget w e v) w v e + 1)
+
+/-- Uniform step bound for the streamed Gram rank routine with a common `d`-bit size bound. It
+charges initialization and up to `(2^d + 1)^2` coefficient queries and cursor checks using
+the entry-read time bound `B`. -/
+def gramTime (d w v e B : ℕ) :=
+ startupClock w + ((2^d+1)*(2^d+1)*(queryAllowance d w v e B + checkClock w v e + 1)+2)
+
+/-- Every prefix may reuse the same storage. The cap of the individual
+entry reader enters this expression independently of its clock. -/
+def gramSpace (d w v e A S : ℕ) :=
+ let a := w+v+e+e*v+A
+ let b := Engine.Assembly.localBudget w e v
+ let ds := GramEngine.descriptorSpace w v e A S (2*d+4)
+ max (startupSpace a w 1)
+ (outerRankSpace (max (max w a + loadClock w) (Engine.boundedSpace ds a (2*d+4) b w v e)) a w v e)
+
+variable {K : Type} [DecidableEq K]
+
+/-- An entry-point shared by all matrix shapes and every width. -/
+def gramRank (read : FiniteRoutine (MacaulayRead.Port K)) : FiniteRoutine (ScanPort (GramEngine.Aux K)) :=
+ initializeDimensions.followedBy (fullRank (GramEngine.actions read))
+
+variable {p e : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- The input includes the two matrix dimensions, the field advice and the
+entry reader's own state. The Schur-depth stack starts empty. -/
+def rawGram (w v n m : ℕ) (c : SliceArithmetic.Vector p e) (reader : Stacks K) :
+ Stacks (ScanPort (GramEngine.Aux K)) :=
+ Function.update (scanBank n (0 : Word w) (dimensionRegs w n m) [true]
+ (idle (GramEngine.initial w v n m c reader))) .depth []
+
+variable [Fact p.Prime] [NeZero e] [Fact (Irreducible (SliceArithmetic.modulus c))]
+
+/-- The rank of a streamed rectangular matrix is in cursor register one on
+return. Both displayed resource bounds are uniform over all row counts up
+to `N`; the instruction table depends only on the supplied entry routine. -/
+theorem gramRank_bounded {n N m d w v B A S : ℕ} (M : Matrix (Fin n) (Fin m) (Scalar c))
+ (read : FiniteRoutine (MacaulayRead.Port K)) {ready : Stacks K → Prop}
+ (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (ha : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (hn : n ≤ N) (hsize : N+N+(N+m)*N+m+8 < 2^d) (hw : gramWidth d ≤ w)
+ (hv : SliceArithmetic.Word.workingWidth p ≤ v) (reader : Stacks K) (hr : ready reader) :
+ ∃ t ≤ gramTime d w v e B, ∃ out aux, GramEngine.Ready w v n m c ready aux ∧
+ Registers.Stores out ((n+m)*n) (M.map (Scalar.interpretation c)).rank 0 ∧
+ (gramRank read).BoundedRun (gramSpace d w v e A S) t (rawGram w v n m c reader)
+ (scanBank n (0 : Word w) out [] (idle aux)) := by
+ let Z := (n+m)*n
+ let a := w+v+e+e*v+A
+ let b := Engine.Assembly.localBudget w e v
+ let desc := DescribeAdapter.clock w v e B
+ let ds := GramEngine.descriptorSpace w v e A S (2*d+4)
+ let initial := GramEngine.initial w v n m c reader
+ have hZ : Z ≤ (N+m)*N := Nat.mul_le_mul (Nat.add_le_add_right hn _) hn
+ have hlocal : n+n+Z+m+8 < 2^d := by omega
+ have hn' : n ≤ 2^d := by omega
+ have hz' : Z ≤ 2^d := by omega
+ obtain ⟨hw₃,hd,hs,hw₁,hw₂,hwc⟩ := width_conditions hw
+ have hdw : 2^d ≤ 2^w := Nat.pow_le_pow_right (by decide) hd
+ have hready : GramEngine.Ready w v n m c ready initial :=
+ GramEngine.initial_ready reader hr (by omega) (by omega)
+ have haux : ∀ x, GramEngine.Ready w v n m c ready x → ∀ i, (x i).length ≤ a :=
+ fun _ h => GramEngine.ready_length h ha
+ have hwork (k : Engine.Port (GramEngine.Aux K)) : (idle initial k).length ≤ a := by
+ cases k with
+ | aux i => exact haux initial hready i
+ | result | condition => exact Nat.zero_le _
+ | frame f => cases f <;> exact Nat.zero_le _
+ obtain ⟨t₁,h₁,start⟩ := initialize_bounded n m (by omega : n < 2^w) (0 : Word w)
+ [true] (idle initial) hwork
+ have spec := GramEngine.contracts (U := n) (Z := Z) read M hc.correct hv hw₃ hw₁ hd hlocal d hn' hn' hz' hs hw₂
+ have hdesc := GramEngine.describeBounded (U := n) (Z := Z) (depth := 2*d+4) read M hc ha hv hw₃ hw₁ hd hlocal
+ have hdepth : Nat.clog 2 n+4+Nat.clog 2 n ≤ 2*d+4 := by
+ have h := Nat.clog_le_of_le_pow hn'
+ omega
+ have hscan : max 1 (max n Z) < 2^d := by omega
+ have hregs := startRegs_stores n m (by omega : n+m < 2^w) (by omega : (n+m)*n < 2^w)
+ obtain ⟨t₂,h₂,out,aux,ho,rank,run⟩ := fullRank_boundedRun (GramEngine.actions read) M
+ (GramEngine.Ready w v n m c ready) (GramEngine.Pending w v m c ready) spec
+ (fun q fs s h hr => hdesc q fs s (h.trans hdepth) hr) haux hwc hv hscan
+ (0 : Word w) (startRegs w n m) initial hready hregs
+ have hroot := readClock_le n n Z desc b w v e d hn' hn' hz'
+ have hrect := Nat.mul_le_mul (Nat.add_le_add_right hn' 1) (Nat.add_le_add_right hz' 1)
+ have htime : boundedRankTime n m desc b w v e ≤
+ (2^d+1)*(2^d+1)*(queryAllowance d w v e B + checkClock w v e + 1)+2 :=
+ Nat.add_le_add_right (Nat.mul_le_mul hrect (Nat.add_le_add_right (Nat.add_le_add_right hroot _) _)) _
+ have hspace := readSpace_le n n ds a b w v e d hn' hn'
+ have htotal : boundedRankSpace n ds a b w v e ≤ gramSpace d w v e A S :=
+ (max_le_max hspace le_rfl).trans (le_max_right ..)
+ exact ⟨_, Nat.add_le_add h₁ (h₂.trans htime), out, aux, ho, rank,
+ (start.enlarge (le_max_left ..)).followedBy (run.enlarge htotal)⟩
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryGramRead.lean b/lean/OAI/Computability/VPVNP/RankQueryGramRead.lean
new file mode 100644
index 0000000000..83e90a398f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryGramRead.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.RankQueryStackEngineSpec
+import OAI.Computability.VPVNP.SliceArithmeticMultiplyCall
+
+/-! # Reading a weighted Gram coefficient on the determinant machine
+
+A nonzero Gram descriptor specifies two rows and a shared column. The first
+entry read writes directly to the multiplier's query stack and the second to
+its accumulator. Both reads see the same persistent Macaulay description.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.MacaulayRead
+
+open RAMTape Engine
+
+/-- Stack addresses for reading one matrix entry, comprising its row and column words, the
+packed scalar result and the reader's auxiliary storage. -/
+inductive Port (K : Type) where
+ | row | col | result | aux (k : K)
+ deriving DecidableEq, Fintype
+
+/-- Encode row `i` and column `j` as `w`-bit words alongside the supplied result stack and
+auxiliary state of the entry reader. -/
+def bank {K : Type} (w i j : ℕ) (result : List Bool) (aux : Stacks K) : Stacks (Port K)
+ | .row => UniversalCountStack.digits w i
+ | .col => UniversalCountStack.digits w j
+ | .result => result
+ | .aux k => aux k
+
+/-- Calling convention for a single coefficient of the advised relation matrix. -/
+def Correct {K : Type} [DecidableEq K] {p e n m : ℕ} {c : SliceArithmetic.Vector p e}
+ (read : FiniteRoutine (Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c)) (w v B : ℕ)
+ (ready : Stacks K → Prop) : Prop :=
+ ∀ (i : Fin n) (j : Fin m) (aux : Stacks K), ready aux →
+ ∃ t ≤ B, ∃ out, ready out ∧ read.Runs t (bank w i j [] aux) (bank w i j (scalar v (M i j)) out)
+
+end RankQuery.Stack.MacaulayRead
+
+namespace RankQuery.Stack.GramRead
+
+open RAMTape Engine
+
+/-- Ports for reading two entries in a common column, with separate row words, one column word,
+a field multiplier and shared reader storage. -/
+inductive Port (K : Type) where
+ | first | second | column | arithmetic (k : SliceArithmetic.MultiplyCall.Port) | aux (k : K)
+ deriving DecidableEq, Fintype
+
+variable {K : Type}
+
+/-- Route an entry read through the chosen row and common column. The first result goes to the
+multiplier's query stack and the second to its accumulator. -/
+def readPorts (second : Bool) : MacaulayRead.Port K → Port K
+ | .row => if second then .second else .first
+ | .col => .column
+ | .result => .arithmetic (.inr (if second then .acc else .query))
+ | .aux k => .aux k
+
+theorem readPorts_injective (second : Bool) : Function.Injective (readPorts (K := K) second) := by
+ intro x y h
+ cases second <;> cases x <;> cases y <;> simp_all [readPorts]
+
+/-- Read `M i k` and `M j k` from the shared column `k`, then multiply the two packed entries
+in the field accumulator. -/
+def machine (read : FiniteRoutine (MacaulayRead.Port K)) : FiniteRoutine (Port K) :=
+ ((read.onPorts (readPorts false)).followedBy (read.onPorts (readPorts true))).followedBy
+ (SliceArithmetic.MultiplyCall.machine.onPorts Port.arithmetic)
+
+/-- Pack row indices `i` and `j` and their shared column `k` into `w`-bit words alongside the
+multiplier stacks and the reader's auxiliary bank. -/
+def bank (w i j k : ℕ) (s : Stacks SliceArithmetic.MultiplyCall.Port) (aux : Stacks K) : Stacks (Port K)
+ | .first => UniversalCountStack.digits w i
+ | .second => UniversalCountStack.digits w j
+ | .column => UniversalCountStack.digits w k
+ | .arithmetic z => s z
+ | .aux z => aux z
+
+open SliceArithmetic.MultiplyCall (clean external callCap)
+open SliceArithmeticRound (packed)
+
+variable [DecidableEq K] {p e n m w v B : ℕ} [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+/-- Prepare the multiplier with packed modulus coefficients `c` at limb width `v`, the supplied
+query and accumulator stacks, and clean internal work stacks. -/
+def arithmeticBank (v : ℕ) (c : SliceArithmetic.Vector p e) (query acc : List Bool) :=
+ clean (external p e v (packed v (List.ofFn c)) query acc)
+
+/-- Two physical reads followed by the fixed polynomial-basis multiplier. -/
+theorem machine_runs (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.Correct read M w v B ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v)
+ (i j : Fin n) (k : Fin m) (s : Stacks K) (hs : ready s) :
+ ∃ t ≤ 2*B + callCap e v, ∃ out, ready out ∧ (machine read).Runs t
+ (bank w i j k (arithmeticBank v c [] []) s)
+ (bank w i j k (arithmeticBank v c [] (scalar v (M i k * M j k))) out) := by
+ let a := M i k
+ let b := M j k
+ let ab := scalar v a
+ let bb := scalar v b
+ obtain ⟨t₁,h₁,s₁,hs₁,r₁⟩ := hc i k s hs
+ obtain ⟨t₂,h₂,s₂,hs₂,r₂⟩ := hc j k s₁ hs₁
+ have l : (read.onPorts (readPorts false)).Runs t₁
+ (bank w i j k (arithmeticBank v c [] []) s)
+ (bank w i j k (arithmeticBank v c ab []) s₁) := by
+ apply read.runs_onPorts_framed (readPorts_injective false) r₁
+ · intro z; cases z <;> rfl
+ · intro z; cases z <;> rfl
+ · intro z hz
+ cases z with
+ | aux x => exact (hz (.aux x) rfl).elim
+ | arithmetic x =>
+ rcases x with x | x
+ · rfl
+ · cases x <;> first | rfl | exact (hz .result rfl).elim
+ | _ => rfl
+ have r : (read.onPorts (readPorts true)).Runs t₂
+ (bank w i j k (arithmeticBank v c ab []) s₁)
+ (bank w i j k (arithmeticBank v c ab bb) s₂) := by
+ apply read.runs_onPorts_framed (readPorts_injective true) r₂
+ · intro z; cases z <;> rfl
+ · intro z; cases z <;> rfl
+ · intro z hz
+ cases z with
+ | aux x => exact (hz (.aux x) rfl).elim
+ | arithmetic x =>
+ rcases x with x | x
+ · rfl
+ · cases x <;> first | rfl | exact (hz .result rfl).elim
+ | _ => rfl
+ obtain ⟨t₃,h₃,r₃⟩ := SliceArithmetic.MultiplyCall.machine_runs (NeZero.pos e) hw c a.digits b.digits
+ have mrun : (SliceArithmetic.MultiplyCall.machine.onPorts (Port.arithmetic (K := K))).Runs t₃
+ (bank w i j k (arithmeticBank v c ab bb) s₂)
+ (bank w i j k (arithmeticBank v c [] (scalar v (a*b))) s₂) := by
+ apply SliceArithmetic.MultiplyCall.machine.runs_onPorts_framed (fun _ _ h => Port.arithmetic.inj h) r₃
+ · intro z; rfl
+ · intro z; rw [Scalar.product_eq]; simp only [scalar, Scalar.digits_pack]; rfl
+ · intro z hz; cases z <;> first | rfl | exact (hz _ rfl).elim
+ exact ⟨_, by omega, s₂, hs₂, (l.followedBy r).followedBy mrun⟩
+
+end RankQuery.Stack.GramRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryGramReadSpace.lean b/lean/OAI/Computability/VPVNP/RankQueryGramReadSpace.lean
new file mode 100644
index 0000000000..79273d2fb9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryGramReadSpace.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.RankQueryGramRead
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-! # Live storage for two nested Macaulay reads
+
+A long coefficient query may take exponential time. Its independently
+certified stack-height bound is reused for the second query. Only the
+short multiplication is charged by its running time.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.FiniteRoutine
+
+open UniversalCountStack
+
+variable {K L : Type} [DecidableEq K] [DecidableEq L]
+
+/-- Enlarging a cap keeps the same complete instruction trace. -/
+theorem BoundedRun.enlarge {r : FiniteRoutine K} {A B t : ℕ} {s out : Stacks K}
+ (h : r.BoundedRun A t s out) (hab : A ≤ B) : r.BoundedRun B t s out := by
+ have grow {Q : Type} {code : StackCode K Q} {u z : Q} {n : ℕ} {s e : Stacks K}
+ (run : SpaceRun code A n u s z e) : SpaceRun code B n u s z e := by
+ induction run with
+ | nil _ _ hs => exact .nil _ _ (fun x => (hs x).trans hab)
+ | cons hs step _ ih => exact .cons (fun x => (hs x).trans hab) step ih
+ exact grow h
+
+theorem BoundedRun.framed {r : FiniteRoutine K} {ports : K → L} (hp : Function.Injective ports)
+ {cap t : ℕ} {s u : Stacks L} {small out : Stacks K} (run : r.BoundedRun cap t small out)
+ (start : ∀ j, (s j).length ≤ cap)
+ (hin : ∀ i, s (ports i) = small i) (hu : ∀ i, u (ports i) = out i)
+ (hout : ∀ j, (∀ i, ports i ≠ j) → u j = s j) : (r.onPorts ports).BoundedRun cap t s u := by
+ have hr := run.onPorts hp s (fun j _ => start j)
+ rwa [installStacks_frame hp hin (fun _ _ => rfl),installStacks_frame hp hu hout] at hr
+
+end RAMTape.FiniteRoutine
+
+namespace RankQuery.Stack.MacaulayRead
+
+open RAMTape Engine
+
+/-- Every valid entry read returns the packed scalar `M i j` within `B` steps and `S` bits per
+stack, preserving the indices and restoring a ready auxiliary state. -/
+def CorrectSpace {K : Type} [DecidableEq K] {p e n m : ℕ} {c : SliceArithmetic.Vector p e}
+ (read : FiniteRoutine (Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c)) (w v B S : ℕ)
+ (ready : Stacks K → Prop) : Prop :=
+ ∀ (i : Fin n) (j : Fin m) (aux : Stacks K), ready aux →
+ ∃ t ≤ B, ∃ out, ready out ∧ read.BoundedRun S t (bank w i j [] aux) (bank w i j (scalar v (M i j)) out)
+
+theorem CorrectSpace.correct {K : Type} [DecidableEq K] {p e n m w v B S : ℕ} {c : SliceArithmetic.Vector p e}
+ {read : FiniteRoutine (Port K)} {M : Matrix (Fin n) (Fin m) (Scalar c)} {ready : Stacks K → Prop}
+ (h : CorrectSpace read M w v B S ready) : Correct read M w v B ready := by
+ intro i j aux hs
+ obtain ⟨t,ht,out,hr,run⟩ := h i j aux hs
+ exact ⟨t,ht,out,hr,run.runs⟩
+
+end RankQuery.Stack.MacaulayRead
+
+namespace RankQuery.Stack.GramRead
+
+open RAMTape Engine
+open SliceArithmetic.MultiplyCall (callCap)
+open UniversalCountStack
+
+variable {K : Type} [DecidableEq K] {p e n m w v B S A : ℕ} [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+omit [Fact p.Prime] [NeZero e] in
+private theorem read_bounded (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (i j : Fin n) (k : Fin m) (s : Stacks K) (hs : ready s)
+ (second : Bool) (left : List Bool) (hcap : S ≤ A)
+ (start : ∀ a, (bank w i j k (arithmeticBank v c (if second then left else []) []) s a).length ≤ A) :
+ let x := scalar v (M (if second then j else i) k)
+ ∃ t ≤ B, ∃ out, ready out ∧ (read.onPorts (readPorts second)).BoundedRun A t
+ (bank w i j k (arithmeticBank v c (if second then left else []) []) s)
+ (bank w i j k (arithmeticBank v c (if second then left else x) (if second then x else [])) out) := by
+ obtain ⟨t,ht,out,hout,hread⟩ := hc (if second then j else i) k s hs
+ refine ⟨t,ht,out,hout,?_⟩
+ apply FiniteRoutine.BoundedRun.framed (readPorts_injective second) (hread.enlarge hcap) start
+ · intro z; cases second <;> cases z <;> rfl
+ · intro z; cases second <;> cases z <;> rfl
+ · intro z hz
+ cases z with
+ | aux z => exact (hz (.aux z) rfl).elim
+ | arithmetic z =>
+ rcases z with z|z
+ · rfl
+ · cases second <;> cases z <;> first | rfl | exact (hz .result rfl).elim
+ | _ => rfl
+
+theorem machine_bounded (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v)
+ (i j : Fin n) (k : Fin m) (s : Stacks K) (hs : ready s)
+ (start : ∀ x, (bank w i j k (arithmeticBank v c [] []) s x).length ≤ A) :
+ ∃ t ≤ 2*B+callCap e v, ∃ out, ready out ∧ (machine read).BoundedRun (max A S+callCap e v) t
+ (bank w i j k (arithmeticBank v c [] []) s)
+ (bank w i j k (arithmeticBank v c [] (scalar v (M i k * M j k))) out) := by
+ obtain ⟨t₁,h₁,s₁,hs₁,r₁⟩ := read_bounded read M hc i j k s hs false [] (le_max_right A S)
+ (fun x => (start x).trans (le_max_left A S))
+ obtain ⟨t₂,h₂,s₂,hs₂,r₂⟩ := read_bounded read M hc i j k s₁ hs₁ true (scalar v (M i k))
+ (le_max_right A S) r₁.final_cap
+ obtain ⟨t₃,h₃,hr⟩ := SliceArithmetic.MultiplyCall.machine_runs (NeZero.pos e) hw c (M i k).digits (M j k).digits
+ have run : (SliceArithmetic.MultiplyCall.machine.onPorts (Port.arithmetic (K := K))).Runs t₃
+ (bank w i j k (arithmeticBank v c (scalar v (M i k)) (scalar v (M j k))) s₂)
+ (bank w i j k (arithmeticBank v c [] (scalar v (M i k * M j k))) s₂) := by
+ apply SliceArithmetic.MultiplyCall.machine.runs_onPorts_framed (fun _ _ h => Port.arithmetic.inj h) hr
+ · intro z; rfl
+ · intro z; rw [Scalar.product_eq]; simp only [scalar, Scalar.digits_pack]; rfl
+ · intro z hz; cases z <;> first | rfl | exact (hz _ rfl).elim
+ have bound : _ := spaceRun_of_steps run (fun x => Nat.add_le_add (r₂.final_cap x) h₃)
+ exact ⟨_,by omega,s₂,hs₂,((r₁.followedBy r₂).enlarge (Nat.le_add_right ..)).followedBy bound⟩
+
+end RankQuery.Stack.GramRead
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryGramScalar.lean b/lean/OAI/Computability/VPVNP/RankQueryGramScalar.lean
new file mode 100644
index 0000000000..fd83647584
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryGramScalar.lean
@@ -0,0 +1,211 @@
+import OAI.Computability.VPVNP.RankQueryGramRead
+import OAI.Computability.VPVNP.RankQueryStackPhysical
+import OAI.Computability.VPVNP.RankQueryTagRouter
+import OAI.Computability.VPVNP.SliceArithmeticConstant
+import OAI.Computability.VPVNP.SliceArithmeticNeg
+
+/-! # The signed Gram-entry call of the physical Schur interpreter
+
+The binary program first computes the Gram column from the degree. It tests
+the emitted tag, writes zero or invokes the two Macaulay reads, and applies
+packed-field negation when the enclosing Schur factor supplies a minus sign.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.GramScalar
+
+open RAMTape BurstRAM Dispatch Engine
+open SliceArithmetic (Vector)
+open SliceArithmeticRound (packed)
+
+/-- Word-machine ports for Gram dispatch, with `14 + Dispatch.capacity` registers and zero
+public input words. -/
+abbrev Small := ISA.Port (14+Dispatch.capacity) 0
+/-- The width-`w` register file for Gram dispatch, holding the eight inputs, six descriptor
+outputs and compiler scratch registers. -/
+abbrev Registers (w : ℕ) := Regs (14+Dispatch.capacity) w
+
+/-- Stack addresses for Gram descriptor words, multiplication, negation, literal-writing
+scratch and the supplied matrix-entry reader. -/
+inductive Port (K : Type) where
+ | words (i : Small) | mul (i : SliceArithmetic.MultiplyCall.Port)
+ | neg (i : SliceArithmeticStreamRow.Port Unit) | tmp | extra | aux (k : K)
+ deriving DecidableEq, Fintype
+
+variable {K : Type}
+
+/-- Word-stack address of the `i`th Gram descriptor output register. -/
+def outWord (i : Fin 6) : Port K := .words (.reg (Code.outReg capacity i))
+
+/-- Wire the two row inputs and common column of a Gram read to output words one, two and
+three, and route its multiplier and reader ports to their banks. -/
+def reads : GramRead.Port K → Port K
+ | .first => outWord 1 | .second => outWord 2 | .column => outWord 3
+ | .arithmetic x => .mul x | .aux k => .aux k
+
+theorem reads_injective : Function.Injective (reads (K := K)) := by
+ intro a b h; cases a <;> cases b <;> simp_all [reads,outWord,Code.outReg,Fin.ext_iff]
+
+/-- Wire field negation to its own row-arithmetic workspace and the multiplier's shared
+external field stacks, including the accumulator. -/
+def negPorts : SliceArithmetic.AddCall.Port → Port K
+ | .inl x => .neg x | .inr x => .mul (.inr x)
+
+theorem negPorts_injective : Function.Injective (negPorts (K := K)) := by
+ rintro (x|x) (y|y) h <;> simp_all [negPorts]
+
+/-- Wire the literal writer to the packed coefficient advice and product accumulator, using
+`extra` and `tmp` for its work stacks. -/
+def literalPorts : TapeWord.ScanPort → Port K
+ | .left => .mul (.inr .coeff) | .out => .mul (.inr .acc) | .right => .extra | .tmp => .tmp
+
+theorem literalPorts_injective : Function.Injective (literalPorts (K := K)) := by
+ intro a b h; cases a <;> cases b <;> simp_all [literalPorts]
+
+/-- For descriptor tag one, read and multiply the two entries in the designated column. For
+every other tag, write the packed zero scalar. -/
+def branch (read : FiniteRoutine (MacaulayRead.Port K)) (tag : ℕ) : FiniteRoutine (Port K) :=
+ if tag = 1 then (GramRead.machine read).onPorts reads
+ else (SliceArithmeticConstant.machine false).onPorts literalPorts
+
+/-- Negate the field accumulator when the Schur descriptor requests a minus sign and return it
+as supplied otherwise. -/
+def sign (neg : Bool) : FiniteRoutine (Port K) :=
+ if neg then SliceArithmetic.NegCall.machine.onPorts negPorts else .ret
+
+/-- Decode the column for a weighted Gram coefficient, compute its two-entry product or zero
+according to the tag, and apply the requested sign. -/
+def machine (read : FiniteRoutine (MacaulayRead.Port K)) (neg : Bool) : FiniteRoutine (Port K) :=
+ ((Operation.gram.machine.onPorts Port.words).followedBy
+ (TagRouter.select (outWord 0) 1 (branch read))).followedBy (sign neg)
+
+/-- Assemble the signed coefficient call's word, multiplication and reader banks with empty
+negation and literal-writing work stacks. -/
+def bank (words : Stacks Small) (arith : Stacks SliceArithmetic.MultiplyCall.Port) (aux : Stacks K) :
+ Stacks (Port K)
+ | .words z => words z | .mul z => arith z | .aux z => aux z | _ => []
+
+/-- Initialize the Gram dispatch word stacks from the persistent word and registers, with an
+empty write log and zero public inputs. -/
+abbrev wordBank {w : ℕ} (persist : Word w) (rs : Registers w) : Stacks Small := ISA.bank Fin.elim0 persist rs []
+
+variable [DecidableEq K] {p e n m w v B d : ℕ} [Fact p.Prime] [NeZero e] {c : Vector p e}
+
+theorem raw_word (x : Word w) : wordBits x = UniversalCountStack.digits w x.val := by
+ unfold UniversalCountStack.digits
+ rw [show (Fin.ofNat (2^w) x.val) = x by apply Fin.ext; exact Nat.mod_eq_of_lt x.isLt]
+
+theorem zero_runs (hw : SliceArithmetic.Word.workingWidth p ≤ v) (words : Stacks Small) (aux : Stacks K) :
+ ((SliceArithmeticConstant.machine false).onPorts literalPorts).Runs (7*(e*v)+3)
+ (bank words (GramRead.arithmeticBank v c [] []) aux)
+ (bank words (GramRead.arithmeticBank v c [] (scalar v (0 : Scalar c))) aux) := by
+ have h := SliceArithmeticConstant.machine_runs (NeZero.pos e) hw false c []
+ apply (SliceArithmeticConstant.machine false).runs_onPorts_framed literalPorts_injective (by simpa using h)
+ · intro k; cases k <;> rfl
+ · intro k; cases k <;> first | rfl | (change packed v (List.ofFn (Scalar.pack c (SliceArithmetic.zero p e)).digits) = _; rw [Scalar.digits_pack]; rfl)
+ · intro z hz; cases z with
+ | mul x => rcases x with x|x
+ · rfl
+ · cases x <;> first | rfl | exact (hz .out rfl).elim
+ | _ => rfl
+
+omit [NeZero e] in
+private theorem negative_digits (x : Scalar c) : (-x).digits = fun i => -x.digits i := by
+ change (Scalar.pack c (SliceArithmetic.scale (-1) x.digits)).digits = _
+ rw [Scalar.digits_pack]
+ funext i; simp [SliceArithmetic.scale]
+
+omit [NeZero e] in
+theorem sign_runs (hw : SliceArithmetic.Word.workingWidth p ≤ v) (neg : Bool) (a : Scalar c)
+ (words : Stacks Small) (aux : Stacks K) :
+ ∃ t ≤ 5*(e*v)+2+SliceArithmetic.AddCall.callCap e v+1,
+ (sign neg).Runs t (bank words (GramRead.arithmeticBank v c [] (scalar v a)) aux)
+ (bank words (GramRead.arithmeticBank v c [] (scalar v (if neg then -a else a))) aux) := by
+ cases neg with
+ | false => exact ⟨1, by omega, Routine.runs_ret _⟩
+ | true =>
+ obtain ⟨t,ht,h⟩ := SliceArithmetic.NegCall.machine_runs hw a.digits (packed v (List.ofFn c))
+ refine ⟨t,by omega,?_⟩
+ apply SliceArithmetic.NegCall.machine.runs_onPorts_framed negPorts_injective h
+ · rintro (k|k) <;> rfl
+ · rintro (k|k)
+ · rfl
+ · cases k <;> first | rfl | (change scalar v (-a) = _; simp only [scalar,negative_digits]; rfl)
+ · intro k hk
+ cases k with
+ | mul z => rcases z with z|z
+ · rfl
+ · exact (hk (.inr z) rfl).elim
+ | _ => rfl
+
+/-- Time bound for Gram index dispatch, two entry reads of at most `B` steps each, the product
+or zero branch and the optional field negation. -/
+def clock (w v e B : ℕ) := Operation.gram.clock w + 2 +
+ (2*B + SliceArithmetic.MultiplyCall.callCap e v + 7*(e*v)+3) +
+ (5*(e*v)+2+SliceArithmetic.AddCall.callCap e v+1)
+
+theorem machine_runs (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.Correct read M w v B ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₁ : 1 ≤ w) (hp : (d+1)*widthFactor ≤ w)
+ (i j : Fin n) (z : ℕ) (neg : Bool) (persist : Word w) (rs : Registers w)
+ (he : ∀ a, gramInput i j z m a < 2^d) (hr : ∀ a, (rs (Code.inReg capacity a)).val = gramInput i j z m a)
+ (aux : Stacks K) (hs : ready aux) :
+ ∃ t ≤ clock w v e B, ∃ rs' aux', ready aux' ∧
+ (∀ a, rs' (Code.inReg capacity a) = rs (Code.inReg capacity a)) ∧ (machine read neg).Runs t
+ (bank (wordBank persist rs) (GramRead.arithmeticBank v c [] []) aux)
+ (bank (wordBank persist rs') (GramRead.arithmeticBank v c []
+ (scalar v (if neg then -weightedGramEntryCoeff M i j z else weightedGramEntryCoeff M i j z))) aux') := by
+ obtain ⟨t₀,ht₀,regs,h₀,hkeep,hout⟩ := Operation.gram.run _ rs hp he hr Fin.elim0 persist
+ let rb := wordBank persist regs
+ have load : (Operation.gram.machine.onPorts (Port.words (K := K))).Runs t₀
+ (bank (wordBank persist rs) (GramRead.arithmeticBank v c [] []) aux)
+ (bank rb (GramRead.arithmeticBank v c [] []) aux) := by
+ apply Operation.gram.machine.runs_onPorts_framed (fun _ _ h => Port.words.inj h) h₀
+ · intro k; rfl
+ · intro k; rfl
+ · intro k hk; cases k <;> first | rfl | exact (hk _ rfl).elim
+ have words (a : Fin 6) : rb (.reg (Code.outReg capacity a)) =
+ UniversalCountStack.digits w (Operation.gram.tree.eval (gramInput i j z m) a) := by
+ change wordBits (regs _) = _
+ rw [raw_word, hout]
+ simp only [gram_words] at words
+ by_cases hvalid : i.val+2 ≤ z ∧ z-i.val-2 < m
+ · simp only [hvalid] at words
+ let k : Fin m := ⟨z-i.val-2,hvalid.2⟩
+ let x := M i k * M j k
+ obtain ⟨t₁,ht₁,s₁,hs₁,h₁⟩ := GramRead.machine_runs read M hc hw i j k aux hs
+ have run : (branch read 1).Runs t₁
+ (bank rb (GramRead.arithmeticBank v c [] []) aux)
+ (bank rb (GramRead.arithmeticBank v c [] (scalar v x)) s₁) := by
+ change ((GramRead.machine read).onPorts reads).Runs _ _ _
+ apply (GramRead.machine read).runs_onPorts_framed reads_injective h₁
+ · intro a; cases a <;> first | rfl | exact words _
+ · intro a; cases a <;> first | rfl | exact words _
+ · intro a ha; cases a with
+ | mul x => exact (ha (.arithmetic x) rfl).elim
+ | aux x => exact (ha (.aux x) rfl).elim
+ | _ => rfl
+ have selected := TagRouter.digits_runs (outWord 0) (branch read) hw₁ (by decide : 1 < 2^1) _ _ (words 0) run
+ obtain ⟨t₂,ht₂,h₂⟩ := sign_runs hw neg x rb s₁
+ refine ⟨t₀+(2*1+t₁)+t₂,by unfold clock; omega,regs,s₁,hs₁,hkeep,?_⟩
+ have hx : weightedGramEntryCoeff M i j z = x := by simp [weightedGramEntryCoeff,hvalid.1,hvalid.2,k,x]
+ rw [hx]
+ exact (load.followedBy selected).followedBy h₂
+ · simp only [hvalid,ite_false] at words
+ have hzero := zero_runs (c := c) hw rb aux
+ have selected := TagRouter.digits_runs (outWord 0) (branch read) hw₁ (by decide : 0 < 2^1) _ _ (words 0) hzero
+ obtain ⟨t₂,ht₂,h₂⟩ := sign_runs hw neg (0 : Scalar c) rb aux
+ refine ⟨t₀+(2*1+(7*(e*v)+3))+t₂,by unfold clock; omega,regs,aux,hs,hkeep,?_⟩
+ have hx : weightedGramEntryCoeff M i j z = 0 := by
+ simp [weightedGramEntryCoeff,hvalid]
+ rw [hx]
+ exact (load.followedBy selected).followedBy h₂
+
+end RankQuery.Stack.GramScalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryGramScalarSpace.lean b/lean/OAI/Computability/VPVNP/RankQueryGramScalarSpace.lean
new file mode 100644
index 0000000000..3ebced723c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryGramScalarSpace.lean
@@ -0,0 +1,110 @@
+import OAI.Computability.VPVNP.RankQueryGramScalar
+import OAI.Computability.VPVNP.RankQueryTagSpace
+
+/-!
+# Storage of a signed weighted Gram coefficient call
+
+The two input-matrix reads may take singly exponential time. Their stack
+space bound is reused for each read. The fixed binary index program and
+finite-field operations add polynomial storage independently of the time
+spent inside either input query.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.GramScalar
+
+open RAMTape BurstRAM Dispatch Engine UniversalCountStack
+
+/-- Peak stack height for a signed Gram coefficient, reusing the same read cap `S` for both
+entries and allowing for index dispatch from height `A` and local field arithmetic. -/
+def space (w v e A S : ℕ) :=
+ max (A + Operation.gram.clock w) S + SliceArithmetic.MultiplyCall.callCap e v + 7*(e*v)+3 +
+ (5*(e*v)+2+SliceArithmetic.AddCall.callCap e v+1)
+
+variable {K : Type} [DecidableEq K] {p e n m w v B S A d : ℕ} [Fact p.Prime] [NeZero e]
+ {c : SliceArithmetic.Vector p e}
+
+theorem machine_bounded (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₁ : 1 ≤ w) (hp : (d+1)*widthFactor ≤ w)
+ (i j : Fin n) (z : ℕ) (neg : Bool) (persist : Word w) (rs : Registers w)
+ (he : ∀ a, gramInput i j z m a < 2^d) (hr : ∀ a, (rs (Code.inReg capacity a)).val = gramInput i j z m a)
+ (aux : Stacks K) (hs : ready aux)
+ (start : ∀ a, (bank (wordBank persist rs) (GramRead.arithmeticBank v c [] []) aux a).length ≤ A) :
+ ∃ t ≤ clock w v e B, ∃ rs' aux', ready aux' ∧
+ (∀ a, rs' (Code.inReg capacity a) = rs (Code.inReg capacity a)) ∧
+ (machine read neg).BoundedRun (space w v e A S) t
+ (bank (wordBank persist rs) (GramRead.arithmeticBank v c [] []) aux)
+ (bank (wordBank persist rs') (GramRead.arithmeticBank v c []
+ (scalar v (if neg then -weightedGramEntryCoeff M i j z else weightedGramEntryCoeff M i j z))) aux') := by
+ let A₀ := A + Operation.gram.clock w
+ let A₁ := max A₀ S + SliceArithmetic.MultiplyCall.callCap e v
+ let A₂ := A₁ + 7*(e*v)+3
+ have h01 : A₀ ≤ A₁ := (le_max_left ..).trans (Nat.le_add_right ..)
+ have h12 : A₁ ≤ A₂ := by dsimp [A₂]; omega
+ have h2 : A₂ ≤ space w v e A S := Nat.le_add_right ..
+ obtain ⟨t₀,ht₀,regs,h₀,hkeep,hout⟩ := Operation.gram.run _ rs hp he hr Fin.elim0 persist
+ let rb := wordBank persist regs
+ have load : (Operation.gram.machine.onPorts (Port.words (K := K))).Runs t₀
+ (bank (wordBank persist rs) (GramRead.arithmeticBank v c [] []) aux)
+ (bank rb (GramRead.arithmeticBank v c [] []) aux) := by
+ apply Operation.gram.machine.runs_onPorts_framed (fun _ _ h => Port.words.inj h) h₀
+ · intro k; rfl
+ · intro k; rfl
+ · intro k hk; cases k <;> first | rfl | exact (hk _ rfl).elim
+ have hload := spaceRun_of_steps (cap := A₀) load (fun k => Nat.add_le_add (start k) ht₀)
+ have words (a : Fin 6) : rb (.reg (Code.outReg capacity a)) =
+ UniversalCountStack.digits w (Operation.gram.tree.eval (gramInput i j z m) a) := by
+ change wordBits (regs _) = _
+ rw [raw_word,hout]
+ simp only [gram_words] at words
+ by_cases hvalid : i.val+2 ≤ z ∧ z-i.val-2 < m
+ · simp only [hvalid] at words
+ let k : Fin m := ⟨z-i.val-2,hvalid.2⟩
+ let x := M i k * M j k
+ have readIn (a : GramRead.Port K) :
+ bank rb (GramRead.arithmeticBank v c [] []) aux (reads a) =
+ GramRead.bank w i j k (GramRead.arithmeticBank v c [] []) aux a := by
+ cases a <;> first | rfl | exact words _
+ obtain ⟨t₁,ht₁,s₁,hs₁,h₁⟩ := GramRead.machine_bounded (A := A₀) read M hc hw i j k aux hs
+ (fun a => by rw [← readIn]; exact hload.final_cap (reads a))
+ have arm : (branch read 1).BoundedRun A₁ t₁
+ (bank rb (GramRead.arithmeticBank v c [] []) aux)
+ (bank rb (GramRead.arithmeticBank v c [] (scalar v x)) s₁) := by
+ change ((GramRead.machine read).onPorts reads).BoundedRun _ _ _ _
+ apply FiniteRoutine.BoundedRun.framed reads_injective h₁ (fun a => (hload.final_cap a).trans h01) readIn
+ · intro a; cases a <;> first | rfl | exact words _
+ · intro a ha; cases a with
+ | mul a => exact (ha (.arithmetic a) rfl).elim
+ | aux a => exact (ha (.aux a) rfl).elim
+ | _ => rfl
+ have hselected := TagRouter.digits_bounded (outWord 0) (branch read) hw₁ (by decide : 1 < 2^1) _ _ (words 0) arm
+ obtain ⟨t₂,ht₂,h₂⟩ := sign_runs hw neg x rb s₁
+ have hsign := spaceRun_of_steps (cap := space w v e A S) h₂
+ (fun a => Nat.add_le_add ((arm.final_cap a).trans h12) ht₂)
+ refine ⟨t₀+(2*1+t₁)+t₂,by unfold clock; omega,regs,s₁,hs₁,hkeep,?_⟩
+ have hx : weightedGramEntryCoeff M i j z = x := by simp [weightedGramEntryCoeff,hvalid.1,hvalid.2,k,x]
+ rw [hx]
+ exact (((FiniteRoutine.BoundedRun.enlarge hload h01).followedBy hselected).enlarge (h12.trans h2)).followedBy hsign
+ · simp only [hvalid,ite_false] at words
+ have zero := zero_runs (c := c) hw rb aux
+ have arm : (branch read 0).BoundedRun A₂ (7*(e*v)+3)
+ (bank rb (GramRead.arithmeticBank v c [] []) aux)
+ (bank rb (GramRead.arithmeticBank v c [] (scalar v (0 : Scalar c))) aux) :=
+ spaceRun_of_steps zero (fun a => by have h := (hload.final_cap a).trans h01; dsimp [A₂]; omega)
+ have hselected := TagRouter.digits_bounded (outWord 0) (branch read) hw₁ (by decide : 0 < 2^1) _ _ (words 0) arm
+ obtain ⟨t₂,ht₂,h₂⟩ := sign_runs hw neg (0 : Scalar c) rb aux
+ have hsign := spaceRun_of_steps (cap := space w v e A S) h₂ (fun a => Nat.add_le_add (arm.final_cap a) ht₂)
+ refine ⟨t₀+(2*1+(7*(e*v)+3))+t₂,by unfold clock; omega,regs,aux,hs,hkeep,?_⟩
+ have hx : weightedGramEntryCoeff M i j z = 0 := by simp [weightedGramEntryCoeff,hvalid]
+ rw [hx]
+ exact (((FiniteRoutine.BoundedRun.enlarge hload (h01.trans h12)).followedBy hselected).enlarge h2).followedBy hsign
+
+end RankQuery.Stack.GramScalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryNestedResources.lean b/lean/OAI/Computability/VPVNP/RankQueryNestedResources.lean
new file mode 100644
index 0000000000..070f349083
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryNestedResources.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.RankQueryConcreteResources
+import OAI.Computability.VPVNP.RankCoordinateSelectedMinor
+import OAI.Computability.VPVNP.RankCoordinatePairReader
+import OAI.Computability.VPVNP.RankCoordinateDynamic
+import OAI.Computability.VPVNP.RankCoordinateLabelWord
+import OAI.Computability.VPVNP.RankCoordinateRootInit
+import OAI.Computability.VPVNP.RankCoordinateReaderSpace
+
+/-!
+# Bounds for the installed coordinate readers of Appendix D.2
+
+Each index selector may scan exponentially many prefixes. Each prefix runs
+the full rectangular rank machine, and a determinant repeatedly calls both
+selectors. These routines have fixed port types. The height of the suspended
+caller is charged at each level, independently of the number of loop iterations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.ConcreteResources
+
+open PolynomiallyBounded Cost
+
+variable {d w v e A S B E rows cols r : ℕ → ℕ}
+
+theorem ordinal_overhead_poly (hw : PB w) : PB (fun i => OrdinalABI.overhead (w i)) := by
+ have copy := ((const 5).mul hw).add (const 2)
+ exact (((hw.add (const 1)).add copy).add copy).add ((const _).mul ((const 100).mul ((hw.add (const 1)).pow 2)))
+
+theorem dynamic_overhead_poly (hw : PB w) : PB (fun i => Dynamic.overhead (w i)) := by
+ have sq := (const 100).mul ((hw.add (const 1)).pow 2)
+ exact (((const _).mul sq).add (hw.add (const 1))).add ((const _).mul sq)
+
+theorem label_feasible {label : ℕ → ℕ} (hl : PB label) (hw : PB w) :
+ Feasible (fun i => ⟨LabelWord.clock (label i) (w i), max (label i) (w i) + LabelWord.clock (label i) (w i)⟩) := by
+ have clock := ((((const 5).mul hl).add (const 2)).add (const 1)).add
+ (((hl.add (const 1)).mul (((const 4).mul hw).add (const 3))).add (const 1))
+ exact ⟨clock.clog,(poly_max hl hw).add clock⟩
+
+theorem selector_feasible (K : Type) [Fintype K] (hr : LB rows)
+ (hd : PB d) (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) (hS : PB S) (hB : LB B) :
+ Feasible (fun i => ⟨Select.scanTime K (rows i) (d i) (w i) (v i) (e i) (B i) (A i) (S i) + OrdinalABI.overhead (w i),
+ Select.scanSpace K (d i) (w i) (v i) (e i) (A i) (S i) + OrdinalABI.overhead (w i)⟩) := by
+ let rank := rank_feasible hd hw hv he hA hS hB
+ have cap : PB (fun i => Select.workCap (d i) (w i) (v i) (e i) (A i) (S i)) :=
+ poly_max (((((hw.add hv).add he).add (he.mul hv)).add hA).add (const 1)) rank.space
+ let card := Fintype.card (Cursor.PrefixPort K)
+ have copy := ((const card).mul (((const 5).mul cap).add (const 2))).add (const 1)
+ have ret := ((hw.add (const 1)).add (((const 5).mul hw).add (const 2))).add
+ (((const card).mul (cap.add (const 1))).add (const 1))
+ have rankCall := clog_add (clog_add copy.clog rank.time) ret.clog
+ have arith := (const 2).mul ((const 100).mul ((hw.add (const 1)).pow 2))
+ have cmp := ((const 20).mul hw).add (const 10)
+ have perPrefix := clog_add (clog_add (clog_add (clog_add arith.clog rankCall) cmp.clog) (log_const 1)) arith.clog
+ have space := poly_max (hw.add arith) (cap.add (poly_max copy ret))
+ have extra := ordinal_overhead_poly hw
+ exact ⟨clog_add (clog_mul hr perPrefix) extra.clog,space.add extra⟩
+
+/-- The query-dependent replacement ordinal and source monomial are obtained
+by a register routine around the same row selector. -/
+theorem dynamic_feasible {selector : ℕ → Budget} (hs : Feasible selector) (hw : PB w) :
+ Feasible (fun i => ⟨(selector i).time + Dynamic.overhead (w i), (selector i).space + Dynamic.overhead (w i)⟩) :=
+ ⟨clog_add hs.time (dynamic_overhead_poly hw).clog, hs.space.add (dynamic_overhead_poly hw)⟩
+
+theorem selected_feasible (K : Type) [Fintype K] (hr : LB rows) (hc : LB cols)
+ (hd : PB d) (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) (hS : PB S) (hB : LB B) (hE : LB E) :
+ Feasible (fun i => ⟨SelectedMinor.time K (rows i) (cols i) (d i) (w i) (v i) (e i) (B i) (A i) (S i) (E i),
+ SelectedMinor.space K (d i) (w i) (v i) (e i) (A i) (S i)⟩) := by
+ have row := selector_feasible K hr hd hw hv he hA hS hB
+ have col := selector_feasible K hc hd hw hv he hA hS hB
+ have clear := (const 2).mul (hw.add (const 1))
+ exact ⟨clog_add (clog_add (clog_add row.time col.time) hE) clear.clog, poly_max row.space (poly_max hS hA)⟩
+
+/-- A common budget for both determinants' matrix entry readers. The
+comparison and choice of target occur at each entry of the numerator. -/
+def minorBudget (K : Type) [Fintype K] (rows cols d w v e B A S E : ℕ) : Budget :=
+ ⟨20*w+10+(max (SelectedMinor.time K rows cols d w v e B A S B) (SelectedMinor.time K rows cols d w v e B A S E)+1),
+ max (SelectedMinor.space K d w v e A S) (w+(20*w+10))⟩
+
+theorem minor_den_covers (K : Type) [Fintype K] (rows cols d w v e B A S E : ℕ) :
+ SelectedMinor.time K rows cols d w v e B A S B ≤ (minorBudget K rows cols d w v e B A S E).time ∧
+ SelectedMinor.space K d w v e A S ≤ (minorBudget K rows cols d w v e B A S E).space := by
+ dsimp only [minorBudget]
+ omega
+
+theorem minor_feasible (K : Type) [Fintype K] (hr : LB rows) (hc : LB cols)
+ (hd : PB d) (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) (hS : PB S) (hB : LB B) (hE : LB E) :
+ Feasible (fun i => minorBudget K (rows i) (cols i) (d i) (w i) (v i) (e i) (B i) (A i) (S i) (E i)) := by
+ have den := selected_feasible K hr hc hd hw hv he hA hS hB hB
+ have target := selected_feasible K hr hc hd hw hv he hA hS hB hE
+ have cmp := ((const 20).mul hw).add (const 10)
+ exact ⟨clog_add cmp.clog (clog_add (log_max den.time target.time) (log_const 1)),poly_max den.space (hw.add cmp)⟩
+
+theorem templateCap_poly (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) :
+ PB (fun i => RootInit.templateCap (w i) (v i) (e i) (A i)) := by
+ have live := (((hw.add hv).add he).add (he.mul hv)).add hA
+ exact poly_max (poly_max live (poly_max (const 1) (poly_max hw (he.mul hv)))) ((he.add (const 1)).mul (hv.add (const 1)))
+
+theorem loadClock_poly (H : Type) [Fintype H] {M : ℕ → ℕ} (hM : PB M) : PB (fun i => RootInit.loadClock H (M i)) :=
+ ((const (Fintype.card H)).mul (((const 5).mul hM).add (const 2))).add (const 1)
+
+theorem divideClock_poly (he : PB e) (hv : PB v) : PB (fun i => Cramer.divideClock (e i) (v i)) :=
+ (((const 7100).mul ((he.add (const 1)).pow 3)).mul ((hv.add (const 1)).pow 3)).of_le fun _ => Cramer.divideClock_le ..
+
+/-- Reserve space for the preparation, both determinant evaluations, and
+packed finite-field inversion and multiplication. -/
+def pairPeak (r w v e A S preparation : ℕ) :=
+ max preparation (max (PlainEngine.querySpace r w v e A S) ((e+1)*(v+1)+Cramer.divideClock e v))
+
+theorem pairPeak_covers (r w v e A S preparation : ℕ) :
+ preparation ≤ pairPeak r w v e A S preparation ∧
+ PlainEngine.querySpace r w v e A S ≤ pairPeak r w v e A S preparation ∧
+ (e+1)*(v+1)+Cramer.divideClock e v ≤ pairPeak r w v e A S preparation :=
+ ⟨le_max_left ..,(le_max_left ..).trans (le_max_right ..),(le_max_right ..).trans (le_max_right ..)⟩
+
+/-- The clock and peak from the two-determinant machine, including the
+determinant-independent field division and all return-workspace clearing. -/
+def pairBudget (H : Type) [Fintype H] (r w v e A : ℕ) (minor prep : Budget) : Budget :=
+ let peak := pairPeak r w v e A minor.space prep.space
+ ⟨NativeReader.pairTime H prep.time r w v e minor.time peak, peak + NativeReader.returnClock H peak⟩
+
+theorem pair_feasible (H : Type) [Fintype H] {minor prep : ℕ → Budget}
+ (hr : LB r) (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A)
+ (hm : Feasible minor) (hp : Feasible prep) :
+ Feasible (fun i => pairBudget H (r i) (w i) (v i) (e i) (A i) (minor i) (prep i)) := by
+ have det := plain_feasible hr hw hv he hA hm.space hm.time
+ have divide := divideClock_poly he hv
+ have peak := poly_max hp.space (poly_max det.space (((he.add (const 1)).mul (hv.add (const 1))).add divide))
+ have ret := (((const 5).mul peak).add (const 2)).add (((const (Fintype.card H)).mul (peak.add (const 1))).add (const 1))
+ exact ⟨clog_add (clog_add (clog_add hp.time (clog_mul (log_const 2) det.time)) divide.clog) ret.clog,peak.add ret⟩
+
+/-- Mount the physical reader on the evaluator. The caller's untouched index
+and field registers coexist with the scalar query's own workspace. -/
+theorem mounted_feasible {native : ℕ → Budget} (hn : Feasible native) (hw : PB w) (hv : PB v) (he : PB e) :
+ Feasible (fun i => ⟨(native i).time, max (native i).space (Reader.callerPeak (w i) (e i) (v i))⟩) :=
+ ⟨hn.time, poly_max hn.space (poly_max hw (poly_max hv (poly_max he (he.mul hv))))⟩
+
+/-- One exponent and one threshold work for every dense entry at an input
+length. Only the base coefficient accesses, the shape, and the staging of
+the current query occur in the hypotheses. -/
+theorem mounted_pair_time_space (H K : Type) [Fintype H] [Fintype K] {prep : ℕ → Budget} {V : ℕ → ℕ}
+ (hr : LB rows) (hc : LB cols) (horder : LB r)
+ (hd : PB d) (hw : PB w) (hv : PB v) (he : PB e) (hA : PB A) (hS : PB S)
+ (hB : LB B) (hE : LB E) (hV : PB V) (hp : Feasible prep) :
+ let minors := fun i => minorBudget K (rows i) (cols i) (d i) (w i) (v i) (e i) (B i) (A i) (S i) (E i)
+ let pair := fun i => pairBudget H (r i) (w i) (v i) (e i) (V i) (minors i) (prep i)
+ ∃ c N : ℕ, ∀ i ≥ N, (pair i).time ≤ 2^(i^c) ∧
+ max (pair i).space (Reader.callerPeak (w i) (e i) (v i)) ≤ i^c := by
+ let hm := minor_feasible K hr hc hd hw hv he hA hS hB hE
+ exact eventual_power (mounted_feasible (pair_feasible H horder hw hv he hV hm hp) hw hv he)
+
+end RankQuery.Stack.Coordinate.ConcreteResources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryPlainBounds.lean b/lean/OAI/Computability/VPVNP/RankQueryPlainBounds.lean
new file mode 100644
index 0000000000..ae5af1d4f6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryPlainBounds.lean
@@ -0,0 +1,49 @@
+import OAI.Computability.VPVNP.RankQueryPlainRoot
+import OAI.Computability.VPVNP.RankQueryDescribeBounds
+
+/-!
+# Local resource bounds of the ordinary determinant entry routine
+
+Each Cramer entry call contributes its time once and its peak height once.
+The additional polynomial work fits the allowance used for the weighted
+determinant.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.PlainEngine
+
+open Dispatch
+
+private theorem testClock_le (w : ℕ) : PlainScalar.testClock w ≤ Operation.gram.clock w := by
+ have h : (Operation.gram.tree.emitFields capacity (List.finRange 6)).length = 163 := by decide
+ rw [PlainScalar.testClock, Operation.clock, h]
+ nlinarith [Nat.zero_le ((w+1)^2)]
+
+theorem descriptorClock_le (w v e B x : ℕ) (hw : w ≤ x) (hv : v ≤ x) (he : e ≤ x) :
+ descriptorClock w v e B ≤ B + DescribeAdapter.allowance x := by
+ have h := DescribeAdapter.overhead_le w v e x hw hv he
+ have ht := testClock_le w
+ unfold descriptorClock DescribeAdapter.timeWith PlainScalar.clock
+ unfold DescribeAdapter.clock DescribeAdapter.timeWith GramScalar.clock at h
+ omega
+
+theorem descriptorSpace_le (w v e A S x : ℕ) (hw : w ≤ x) (hv : v ≤ x) (he : e ≤ x) :
+ DescribeAdapter.peakWith w v e A (fun a => PlainScalar.space w v e a S) ≤
+ max A S + DescribeAdapter.allowance x := by
+ have h := DescribeAdapter.overhead_le w v e x hw hv he
+ have ht := testClock_le w
+ have hmax : max (A+Operation.describe.clock w+PlainScalar.testClock w) S ≤
+ max A S + Operation.describe.clock w + PlainScalar.testClock w := max_le (by omega) (by omega)
+ unfold DescribeAdapter.peakWith PlainScalar.space
+ dsimp only
+ unfold DescribeAdapter.clock DescribeAdapter.timeWith GramScalar.clock at h
+ omega
+
+end RankQuery.Stack.PlainEngine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryPlainContracts.lean b/lean/OAI/Computability/VPVNP/RankQueryPlainContracts.lean
new file mode 100644
index 0000000000..2f788d085d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryPlainContracts.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.RankQueryPlainScalar
+import OAI.Computability.VPVNP.RankQueryDescribeSpace
+import OAI.Computability.VPVNP.RegisterTable
+
+/-! # Signed scalar contracts for the Cramer minor reader -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.PlainScalar
+
+open RAMTape BurstRAM Dispatch
+
+variable {K : Type} [DecidableEq K] {w v p e n d B S A : ℕ}
+ [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+/-- The constant-polynomial entry call can be installed in the same Schur
+dispatcher as a weighted Gram entry. -/
+theorem callSpace (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin n) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₁ : 1 ≤ w) :
+ DescribeAdapter.CallSpace (machine read) (entry M) w v n d (clock w v e B)
+ (fun a => space w v e a S) ready :=
+ fun i j z neg persist rs _ hr aux hs start => machine_bounded read M hc hw hw₁ i j z neg persist rs hr aux hs start
+
+theorem callRuns (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin n) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (haux : ∀ s, ready s → ∀ i, (s i).length ≤ A)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₁ : 1 ≤ w) :
+ DescribeAdapter.CallRuns (machine read) (entry M) w v n d (clock w v e B) ready := by
+ intro i j z neg persist rs he hr aux hs
+ have hstart (k : GramScalar.Port K) : (GramScalar.bank (GramScalar.wordBank persist rs)
+ (GramRead.arithmeticBank v c [] []) aux k).length ≤ w+v+e+e*v+A := by
+ cases k with
+ | words i => exact (RegisterTable.bank_length_le Fin.elim0 persist rs i).trans (by omega)
+ | aux i => exact (haux _ hs i).trans (by omega)
+ | mul i =>
+ rcases i with i | i
+ · exact Nat.zero_le _
+ · cases i <;> simp [GramScalar.bank,GramRead.arithmeticBank,SliceArithmetic.MultiplyCall.clean,
+ SliceArithmetic.MultiplyCall.external] <;> omega
+ | _ => exact Nat.zero_le _
+ obtain ⟨t,ht,out,aux',hs',hout,hrun⟩ := callSpace (d := d) read M hc hw hw₁ i j z neg persist rs he hr aux hs hstart
+ exact ⟨t,ht,out,aux',hs',hout,hrun.runs⟩
+
+end RankQuery.Stack.PlainScalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryPlainRoot.lean b/lean/OAI/Computability/VPVNP/RankQueryPlainRoot.lean
new file mode 100644
index 0000000000..766c648de2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryPlainRoot.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.RankQueryPlainContracts
+import OAI.Computability.VPVNP.RankQueryStackGramSpace
+
+/-!
+# Full fixed Schur computation for Cramer minors
+
+At a top-degree query of an ordinary square minor, each coefficient callback
+reads one scalar at degree zero. The same finite register bank, power-basis
+arithmetic, and bounded continuation stack implement every level.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.PlainEngine
+
+open Dispatch RAMTape Engine
+
+variable {K : Type} [DecidableEq K] {n w v d p e B A S : ℕ}
+ [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+/-- Schur stack machine for an ordinary square minor. Its entry callback reads a matrix scalar
+at degree zero and supplies zero at higher degrees. -/
+def machine (read : FiniteRoutine (MacaulayRead.Port K)) :=
+ Engine.machine (GramEngine.actionsWith (PlainScalar.machine read))
+
+/-- Time bound for describing one Schur node of an ordinary minor, allowing a plain scalar
+callback whose matrix-entry reader has clock `B`. -/
+def descriptorClock (w v e B : ℕ) := DescribeAdapter.timeWith w v e (PlainScalar.clock w v e B)
+
+/-- Time bound for the bidegree `(n,0)` root query of an ordinary square minor, combining the
+Schur traversal bound with the time per engine step. -/
+def queryTime (n w v e B : ℕ) :=
+ let depth := Nat.clog 2 n+4+Nat.clog 2 n
+ (5+6*SchurKey.arityBound n n 0)^(depth+1) * boundedStepTime (descriptorClock w v e B) (Assembly.localBudget w e v) w v e + 1
+
+/-- Per-stack height bound for the bidegree `(n,0)` query, accounting for the Schur
+continuation depth, initial auxiliary height `A` and peak `S` of a matrix-entry read. -/
+def querySpace (n w v e A S : ℕ) :=
+ let depth := Nat.clog 2 n+4+Nat.clog 2 n
+ let initial := GramEngine.entryCap w v e A depth
+ let descriptor := max initial (DescribeAdapter.peakWith w v e initial (fun a => PlainScalar.space w v e a S))
+ boundedSpace descriptor (w+v+e+e*v+A) depth (Assembly.localBudget w e v) w v e
+
+/-- A true run of the fixed binary-stack machine, returning the top coefficient
+of the minor pencil. The independent height bound of the input-entry reader
+enters space, and its running time enters only the clock. -/
+theorem top_query (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin n) (Scalar c))
+ {readerReady : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S readerReady)
+ (ha : ∀ s, readerReady s → ∀ i, (s i).length ≤ A)
+ (hv : SliceArithmetic.Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hw : (d+1)*widthFactor ≤ w)
+ (hd : d ≤ w) (hsize : n+n+0+n+8 < 2^d)
+ (s : ℕ) (hn : n ≤ 2^s) (hs : 2*s+6 ≤ w) (hws : (2*s+6+1)*widthFactor ≤ w)
+ (aux : Stacks (GramEngine.Aux K)) (haux : GramEngine.Ready w v n n c readerReady aux) :
+ ∃ t ≤ queryTime n w v e B, ∃ out, GramEngine.Ready w v n n c readerReady out ∧
+ (machine read).BoundedRun (querySpace n w v e A S) t
+ (atControl (c := c) w v (.enter (SchurKey.root (n := n) (Fin.last n) (Fin.last 0))) [] aux)
+ (atControl w v (.returned (SchurKey.compute (PlainScalar.entry M) n 0)) ([] : List (F n n 0 c)) out) := by
+ let call := PlainScalar.machine read
+ let ent := PlainScalar.entry M
+ let depth := Nat.clog 2 n+4+Nat.clog 2 n
+ let initial := GramEngine.entryCap w v e A depth
+ let localSpace := fun a => PlainScalar.space w v e a S
+ have cr := PlainScalar.callRuns (d := d) read M hc ha hv (by omega)
+ have cs : DescribeAdapter.CallSpace call ent w v n d (PlainScalar.clock w v e B) localSpace readerReady :=
+ PlainScalar.callSpace read M hc hv (by omega)
+ have expand (a : ℕ) : a ≤ localSpace a := by dsimp [localSpace,PlainScalar.space]; omega
+ have desc : DescribeBounded (GramEngine.actionsWith call)
+ (SchurKey.program (U := n) (Z := 0) ent) w v (descriptorClock w v e B)
+ (max initial (DescribeAdapter.peakWith w v e initial localSpace)) depth
+ (GramEngine.Ready w v n n c readerReady) :=
+ GramEngine.lift_boundedWith ha (DescribeAdapter.describe_entries_bounded call ent cr cs expand hv hw₃ hw hd hsize)
+ let C := M.map Polynomial.C
+ have he : ∀ i j z, ent i j z = (C i j).coeff z := by
+ intro i j z; simp [C, ent, PlainScalar.entry,Polynomial.coeff_C]
+ rw [SchurKey.compute_correct C _ he]
+ exact eval_root_bounded (GramEngine.contractsWith call ent cr hv hw₃ hw hd hsize s hn hn (Nat.zero_le _) hs hws)
+ desc (fun _ hr => GramEngine.ready_length hr ha) C he (Fin.last n) (Fin.last 0) aux haux
+
+end RankQuery.Stack.PlainEngine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryPlainScalar.lean b/lean/OAI/Computability/VPVNP/RankQueryPlainScalar.lean
new file mode 100644
index 0000000000..bfb257a3a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryPlainScalar.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.RankQueryGramScalarSpace
+
+/-!
+# Scalar-entry routine for an ordinary determinant
+
+The Cramer minors of Appendix D.2 have constant entries in the polynomial
+variable. At degree zero this routine reads the chosen entry once. At positive
+degree it emits a zero scalar. Both arms restore the binary index bank and
+apply the sign requested by the Schur factor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.PlainScalar
+
+open RAMTape BurstRAM Dispatch Engine UniversalCountStack
+open GramScalar (Small Registers bank wordBank outWord literalPorts raw_word)
+open SliceArithmetic (Vector)
+
+variable {K : Type}
+
+/-- Route the Macaulay row and column inputs to the query registers and the entry result to the
+scalar accumulator. -/
+def readPorts : MacaulayRead.Port K → GramScalar.Port K
+ | .row => .words (.reg (Code.inReg capacity 0))
+ | .col => .words (.reg (Code.inReg capacity 1))
+ | .result => .mul (.inr .acc)
+ | .aux k => .aux k
+
+theorem readPorts_injective : Function.Injective (readPorts (K := K)) := by
+ intro a b h
+ cases a <;> cases b <;> simp_all [readPorts,Code.inReg,Fin.ext_iff]
+
+/-- Register six contains the zero word. The branch writes the degree-zero
+indicator into output word zero, using the same bank as the Gram accessor. -/
+def degreeTest : RegCode (14+capacity) :=
+ .test (Code.inReg capacity 2) (Code.inReg capacity 6)
+ (.lit (Code.outReg capacity 0) 1) (.lit (Code.outReg capacity 0) 0)
+
+/-- Select the matrix-entry reader on tag one and the zero-scalar writer on every other tag. -/
+def arm (read : FiniteRoutine (MacaulayRead.Port K)) (tag : ℕ) : FiniteRoutine (GramScalar.Port K) :=
+ if tag = 1 then read.onPorts readPorts else (SliceArithmeticConstant.machine false).onPorts literalPorts
+
+/-- Test the requested coefficient degree, read the entry or emit zero, then apply the
+requested sign. -/
+def machine (read : FiniteRoutine (MacaulayRead.Port K)) (negative : Bool) : FiniteRoutine (GramScalar.Port K) :=
+ ((degreeTest.compile.onPorts GramScalar.Port.words).followedBy (TagRouter.select (outWord 0) 1 (arm read))).followedBy
+ (GramScalar.sign negative)
+
+/-- Regard a constant matrix as a polynomial matrix by putting each entry in degree zero. -/
+def entry {F : Type*} [Zero F] {n : ℕ} (M : Matrix (Fin n) (Fin n) F) : Entry n F :=
+ fun i j z => if z = 0 then M i j else 0
+
+/-- Step bound for testing the coefficient degree on binary words of width `w`. -/
+def testClock (w : ℕ) := 200*(w+1)^2
+/-- Step budget for the degree test, scalar read or zero output, and sign adjustment. -/
+def clock (w v e B : ℕ) := testClock w + 2 + (B + 7*(e*v)+3) +
+ (5*(e*v)+2+SliceArithmetic.AddCall.callCap e v+1)
+/-- Stack-space budget for the degree test and scalar reader followed by sign adjustment. -/
+def space (w v e A S : ℕ) := max (A+testClock w) S + 7*(e*v)+3 +
+ (5*(e*v)+2+SliceArithmetic.AddCall.callCap e v+1)
+
+variable [DecidableEq K] {w v p e n d B S A : ℕ} [Fact p.Prime] [NeZero e] {c : Vector p e}
+
+theorem machine_bounded (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin n) (Scalar c))
+ {ready : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S ready)
+ (hw : SliceArithmetic.Word.workingWidth p ≤ v) (hw₁ : 1 ≤ w)
+ (i j : Fin n) (z : ℕ) (negative : Bool) (persist : Word w) (rs : Registers w)
+ (hr : ∀ a, (rs (Code.inReg capacity a)).val = gramInput i j z n a)
+ (aux : Stacks K) (hs : ready aux)
+ (start : ∀ a, (bank (wordBank persist rs) (GramRead.arithmeticBank v c [] []) aux a).length ≤ A) :
+ ∃ t ≤ clock w v e B, ∃ rs' aux', ready aux' ∧
+ (∀ a, rs' (Code.inReg capacity a) = rs (Code.inReg capacity a)) ∧
+ (machine read negative).BoundedRun (space w v e A S) t
+ (bank (wordBank persist rs) (GramRead.arithmeticBank v c [] []) aux)
+ (bank (wordBank persist rs') (GramRead.arithmeticBank v c []
+ (scalar v (if negative then -entry M i j z else entry M i j z))) aux') := by
+ let regs := degreeTest.exec rs
+ let rb := wordBank persist regs
+ let idx := Code.outReg capacity 0
+ let A₀ := A + testClock w
+ let A₁ := max A₀ S + 7*(e*v)+3
+ have h01 : A₀ ≤ A₁ := by dsimp [A₁]; omega
+ have h12 : A₁ ≤ space w v e A S := Nat.le_add_right ..
+ have hcmp : rs (Code.inReg capacity 2) = rs (Code.inReg capacity 6) ↔ z = 0 := by
+ rw [Fin.ext_iff, hr, hr]; rfl
+ have hregs : regs = Function.update rs idx (Fin.ofNat _ (if z = 0 then 1 else 0)) := by
+ by_cases hz : z = 0
+ · simp [regs,idx,degreeTest,RegCode.exec,hcmp.mpr hz,hz]
+ · have hne : rs (Code.inReg capacity 2) ≠ rs (Code.inReg capacity 6) := fun hh => hz (hcmp.mp hh)
+ simp [regs,idx,degreeTest,RegCode.exec,hne,hz]
+ have keep (a : Fin 8) : regs (Code.inReg capacity a) = rs (Code.inReg capacity a) := by
+ rw [hregs, Function.update_of_ne]
+ intro he
+ have h := congrArg Fin.val he
+ change a.val = 8 at h
+ omega
+ have flag : rb (.reg idx) = UniversalCountStack.digits w (if z = 0 then 1 else 0) := by
+ change wordBits (regs idx) = _
+ rw [hregs,Function.update_self]; rfl
+ obtain ⟨t₀,ht₀,h₀⟩ := degreeTest.compile_runs Fin.elim0 persist rs
+ change t₀ ≤ 2*(100*(w+1)^2) at ht₀
+ have htest : t₀ ≤ testClock w := by simpa [testClock,← Nat.mul_assoc] using ht₀
+ have load : (degreeTest.compile.onPorts (GramScalar.Port.words (K := K))).Runs t₀
+ (bank (wordBank persist rs) (GramRead.arithmeticBank v c [] []) aux)
+ (bank rb (GramRead.arithmeticBank v c [] []) aux) := by
+ apply degreeTest.compile.runs_onPorts_framed (fun _ _ h => GramScalar.Port.words.inj h) h₀
+ · intro k; rfl
+ · intro k; rfl
+ · intro k hk; cases k <;> first | rfl | exact (hk _ rfl).elim
+ have hload := spaceRun_of_steps (cap := A₀) load (fun k => Nat.add_le_add (start k) htest)
+ by_cases hz : z = 0
+ · rw [ite_eq_left hz] at flag
+ obtain ⟨t₁,ht₁,out,ho,hcall⟩ := hc i j aux hs
+ have first : rb (.reg (Code.inReg capacity 0)) = UniversalCountStack.digits w i.val := by
+ change wordBits (regs _) = _
+ rw [keep,raw_word,hr]; rfl
+ have second : rb (.reg (Code.inReg capacity 1)) = UniversalCountStack.digits w j.val := by
+ change wordBits (regs _) = _
+ rw [keep,raw_word,hr]; rfl
+ have hcS : S ≤ A₁ := by dsimp [A₁]; omega
+ have branch : (arm read 1).BoundedRun A₁ t₁ (bank rb (GramRead.arithmeticBank v c [] []) aux)
+ (bank rb (GramRead.arithmeticBank v c [] (scalar v (M i j))) out) := by
+ change (read.onPorts readPorts).BoundedRun _ _ _ _
+ apply FiniteRoutine.BoundedRun.framed readPorts_injective (hcall.enlarge hcS) (fun a => (hload.final_cap a).trans h01)
+ · intro a; cases a <;> first | exact first | exact second | rfl
+ · intro a; cases a <;> first | exact first | exact second | rfl
+ · intro a ha
+ cases a with
+ | mul a => rcases a with a|a
+ · rfl
+ · cases a <;> first | rfl | exact (ha .result rfl).elim
+ | aux a => exact (ha (.aux a) rfl).elim
+ | _ => rfl
+ have select := TagRouter.digits_bounded (outWord 0) (arm read) hw₁ (by decide : 1 < 2^1) _ _ flag branch
+ obtain ⟨t₂,ht₂,hsign⟩ := GramScalar.sign_runs hw negative (M i j) rb out
+ have hfinal := spaceRun_of_steps (cap := space w v e A S) hsign (fun a => Nat.add_le_add (branch.final_cap a) ht₂)
+ refine ⟨t₀+(2*1+t₁)+t₂,by unfold clock; omega,regs,out,ho,keep,?_⟩
+ rw [entry,ite_eq_left hz]
+ exact (((FiniteRoutine.BoundedRun.enlarge hload h01).followedBy select).enlarge h12).followedBy hfinal
+ · rw [ite_eq_right hz] at flag
+ have hzero := GramScalar.zero_runs (c := c) hw rb aux
+ have branch : (arm read 0).BoundedRun A₁ (7*(e*v)+3) (bank rb (GramRead.arithmeticBank v c [] []) aux)
+ (bank rb (GramRead.arithmeticBank v c [] (scalar v (0 : Scalar c))) aux) :=
+ spaceRun_of_steps hzero (fun a => by have h := hload.final_cap a; dsimp [A₁]; omega)
+ have select := TagRouter.digits_bounded (outWord 0) (arm read) hw₁ (by decide : 0 < 2^1) _ _ flag branch
+ obtain ⟨t₂,ht₂,hsign⟩ := GramScalar.sign_runs hw negative (0 : Scalar c) rb aux
+ have hfinal := spaceRun_of_steps (cap := space w v e A S) hsign (fun a => Nat.add_le_add (branch.final_cap a) ht₂)
+ refine ⟨t₀+(2*1+(7*(e*v)+3))+t₂,by unfold clock; omega,regs,aux,hs,keep,?_⟩
+ rw [entry,ite_eq_right hz]
+ exact (((FiniteRoutine.BoundedRun.enlarge hload h01).followedBy select).enlarge h12).followedBy hfinal
+
+end RankQuery.Stack.PlainScalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryPrepareResources.lean b/lean/OAI/Computability/VPVNP/RankQueryPrepareResources.lean
new file mode 100644
index 0000000000..4a402cbafc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryPrepareResources.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.RankQueryUniformResources
+import OAI.Computability.VPVNP.RankCoordinatePrepareCost
+import OAI.Computability.VPVNP.RankCoordinateSelectedAdvice
+
+/-! # Uniform time and peak of the prepared evaluator coordinate machine -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.ConcreteResources
+
+open PolynomiallyBounded Cost
+
+theorem argumentClock_poly {w : ℕ → ℕ} (hw : PB w) : PB (fun n => ArgumentStage.clock (w n)) :=
+ (((const 4).mul (hw.add (const 1))).add (const 1)).add
+ (((const 4).mul (((const 5).mul hw).add (const 2))).add (const 1))
+
+/-- The label-mode estimate with the largest permitted label also covers
+the Frobenius branch and shorter unary labels. -/
+theorem prepare_mode_covers (P : Type) [Fintype P] (b : Bool) (M A B S w : ℕ) {label labels : ℕ}
+ (h : label ≤ labels) :
+ Prepare.time P b M B label w ≤ Prepare.time P false M B labels w ∧
+ Prepare.peak P M A S label w ≤ Prepare.peak P M A S labels w := by
+ have hclock : LabelWord.clock label w ≤ LabelWord.clock labels w := by unfold LabelWord.clock; gcongr
+ have htime : Prepare.labelTime b label w ≤ LabelWord.clock labels w := by
+ cases b with
+ | false => exact hclock
+ | true => change 1 ≤ LabelWord.clock labels w; unfold LabelWord.clock; omega
+ constructor
+ · unfold Prepare.time
+ change _ ≤ _ + LabelWord.clock labels w + ArgumentStage.clock w
+ gcongr
+ · unfold Prepare.peak Prepare.baseCap
+ gcongr
+
+theorem prepare_feasible (P : Type) [Fintype P] {M A label w : ℕ → ℕ} {row : ℕ → Budget}
+ (hM : PB M) (hA : PB A) (hl : PB label) (hw : PB w) (hr : Feasible row) :
+ Feasible (fun n => ⟨Prepare.time P false (M n) (row n).time (label n) (w n),
+ Prepare.peak P (M n) (A n) (row n).space (label n) (w n)⟩) := by
+ have load := loadClock_poly P hM
+ have dyn := dynamic_feasible hr hw
+ have tag := label_feasible hl hw
+ have args := argumentClock_poly hw
+ exact ⟨clog_add (clog_add (clog_add load.clog dyn.time) tag.time) args.clog,
+ (poly_max (hA.add load) (poly_max dyn.space tag.space)).add args⟩
+
+/-- Common bounds on the loaded root, selector, and unary-register templates
+and on the public request while they are loaded. -/
+abbrev inputCap := FullAdvice.portBound
+
+/-- Budget for the selector scan including the time and space of the ordinal calling
+convention. -/
+def selectorBudget (K : Type) [Fintype K] (rows d w v e B A S : ℕ) : Budget :=
+ ⟨Select.scanTime K rows d w v e B A S + OrdinalABI.overhead w,
+ Select.scanSpace K d w v e A S + OrdinalABI.overhead w⟩
+
+/-- Run the live preparation with the actual greedy selector as a callback. -/
+def prepareBudget (P K : Type) [Fintype P] [Fintype K] (rows d w v e B A S labels : ℕ) : Budget :=
+ let row := selectorBudget K rows d w v e B A S
+ let M := SelectedAdvice.portBound K d w v e A S
+ ⟨Prepare.time P false M row.time labels w, Prepare.peak P M (max M labels) row.space labels w⟩
+
+/-- The physical setup theorem takes the actual label, operation mode and
+starting advice. A single budget uses the largest label at this length. -/
+theorem prepareBudget_covers (P K : Type) [Fintype P] [Fintype K]
+ (rows d w v e B A S : ℕ) (mode : Bool) {label labels : ℕ} (hl : label ≤ labels) :
+ let row := selectorBudget K rows d w v e B A S
+ let M := SelectedAdvice.portBound K d w v e A S
+ let budget := prepareBudget P K rows d w v e B A S labels
+ Prepare.time P mode M row.time label w ≤ budget.time ∧
+ Prepare.peak P M (max label M) row.space label w ≤ budget.space := by
+ intro row M budget
+ have ha : max label M ≤ max M labels := max_le (hl.trans (le_max_right ..)) (le_max_left ..)
+ have room : Prepare.peak P M (max label M) row.space label w ≤
+ Prepare.peak P M (max M labels) row.space label w := by
+ unfold Prepare.peak Prepare.baseCap
+ gcongr
+ have bounds := prepare_mode_covers P mode M (max M labels) row.time row.space w hl
+ exact ⟨bounds.1,room.trans bounds.2⟩
+
+theorem prepareBudget_feasible (P K : Type) [Fintype P] [Fintype K] {rows d w v e B A S labels : ℕ → ℕ}
+ (hr : LB rows) (hd : PB d) (hw : PB w) (hv : PB v) (he : PB e)
+ (hB : LB B) (hA : PB A) (hS : PB S) (hlabels : PB labels) :
+ Feasible (fun n => prepareBudget P K (rows n) (d n) (w n) (v n) (e n) (B n) (A n) (S n) (labels n)) := by
+ have row := selector_feasible K hr hd hw hv he hA hS hB
+ have ready := poly_max row.space (poly_max hS hA)
+ have cap := poly_max (templateCap_poly hw hv he ready) (poly_max hw row.space)
+ exact prepare_feasible P cap (poly_max cap hlabels) hlabels hw row
+
+/-- The budget of the native reader as a function of its five varying
+numerical parameters. It includes the preparation at this matrix shape. -/
+def preparedBudget (P H K : Type) [Fintype P] [Fintype H] [Fintype K]
+ (rows cols r d w v e B A S E labels : ℕ) :=
+ mountedBudget H K rows cols r d w v e B A S E (prepareBudget P K rows d w v e B A S labels)
+
+/-- The public advice supplied to the literal evaluator already fits the
+same mounted reader's workspace estimate. -/
+theorem preparedBudget_advice (P H K : Type) [Fintype P] [Fintype H] [Fintype K]
+ (rows cols r d w v e B A S E labels : ℕ) :
+ SelectedAdvice.portBound K d w v e A S ≤
+ (preparedBudget P H K rows cols r d w v e B A S E labels).space := by
+ let M := SelectedAdvice.portBound K d w v e A S
+ let row := selectorBudget K rows d w v e B A S
+ let stage := prepareBudget P K rows d w v e B A S labels
+ let minor := minorBudget K rows cols d w v e B A S E
+ let V := SelectedMinor.space K d w v e A S
+ let cap := pairPeak r w v e V minor.space stage.space
+ have load : M ≤ max M labels + RootInit.loadClock P M := (le_max_left ..).trans (Nat.le_add_right ..)
+ have start : M ≤ stage.space := (load.trans (le_max_left ..)).trans (Nat.le_add_right ..)
+ have pair : M ≤ cap := start.trans (le_max_left ..)
+ exact (pair.trans (Nat.le_add_right cap (NativeReader.returnClock H cap))).trans (le_max_left ..)
+
+/-- Maximum preparation budget over the two matrix dimensions, minor order, extension degree
+and limb width admitted by the bounds. -/
+def preparedMaximum (P H K : Type) [Fintype P] [Fintype H] [Fintype K]
+ (limit d w degree limb B A S E labels : ℕ) :=
+ maximum (fun x : Shapes limit degree limb => preparedBudget P H K (x.1 0) (x.1 1) (x.1 2)
+ d w x.2.2 x.2.1 B A S E labels)
+
+theorem preparedMaximum_covers (P H K : Type) [Fintype P] [Fintype H] [Fintype K]
+ {rows cols r e v limit degree limb : ℕ} (hr : rows ≤ limit) (hc : cols ≤ limit) (ho : r ≤ limit)
+ (he : e ≤ degree) (hv : v ≤ limb) (d w B A S E labels : ℕ) :
+ let cost := preparedBudget P H K rows cols r d w v e B A S E labels
+ let cap := preparedMaximum P H K limit d w degree limb B A S E labels
+ cost.time ≤ cap.time ∧ cost.space ≤ cap.space := by
+ let shape : Shapes limit degree limb :=
+ ⟨![⟨rows,Nat.lt_succ_of_le hr⟩,⟨cols,Nat.lt_succ_of_le hc⟩,⟨r,Nat.lt_succ_of_le ho⟩],
+ ⟨e,Nat.lt_succ_of_le he⟩,⟨v,Nat.lt_succ_of_le hv⟩⟩
+ exact le_maximum (fun x : Shapes limit degree limb => preparedBudget P H K (x.1 0) (x.1 1) (x.1 2)
+ d w x.2.2 x.2.1 B A S E labels) shape
+
+theorem preparedMaximum_feasible (P H K : Type) [Fintype P] [Fintype H] [Fintype K]
+ {limit d w degree limb B A S E labels : ℕ → ℕ}
+ (hl : LB limit) (hd : PB d) (hw : PB w) (he : PB degree) (hv : PB limb)
+ (hB : LB B) (hA : PB A) (hS : PB S) (hE : LB E) (hlabels : PB labels) :
+ Feasible (fun n => preparedMaximum P H K (limit n) (d n) (w n) (degree n) (limb n)
+ (B n) (A n) (S n) (E n) (labels n)) := by
+ apply maximum_feasible
+ intro shape
+ have dim (j : Fin 3) : LB (fun n => (shape n).1 j) :=
+ hl.of_le fun n => Nat.clog_mono_right _ (Nat.lt_succ_iff.mp ((shape n).1 j).isLt)
+ have limb := hv.of_le (f := fun n => ((shape n).2.2 : ℕ)) fun n => Nat.lt_succ_iff.mp (shape n).2.2.isLt
+ have deg := he.of_le (f := fun n => ((shape n).2.1 : ℕ)) fun n => Nat.lt_succ_iff.mp (shape n).2.1.isLt
+ exact mounted_feasible_of_shape H K (dim 0) (dim 1) (dim 2) hd hw limb deg hB hA hS hE
+ (prepareBudget_feasible P K (dim 0) hd hw limb deg hB hA hS hlabels)
+
+end RankQuery.Stack.Coordinate.ConcreteResources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryReaderFits.lean b/lean/OAI/Computability/VPVNP/RankQueryReaderFits.lean
new file mode 100644
index 0000000000..61a916fbb1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryReaderFits.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.RankQueryUniformResources
+import OAI.Computability.VPVNP.MacaulayTargetBudgets
+import OAI.Computability.VPVNP.RankCoordinateSliceTargets
+
+/-! # Numerical premises of the canonical slice-coordinate reader -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.ConcreteResources
+
+open Dispatch RadicalCertificate.MonomialIndex
+open SliceMinors NativeReader
+
+variable {F : Type} [Field F] [DecidableEq F] {t eqs : ℕ}
+
+/-- Fits both rectangular orientations, both ordinary determinant roots and
+every operation-specific target, with a common clock and a separate space
+cap. The index width is also the width of the incoming evaluator ordinals. -/
+structure CanonicalFits (Q : QueryData t eqs F) (d w v e live space time : ℕ) : Prop where
+ rowShape : height Q+height Q+(height Q+width Q)*height Q+width Q+8 < 2^d
+ columnShape : width Q+width Q+(width Q+height Q)*width Q+height Q+8 < 2^d
+ orderShape : order Q+order Q+0+order Q+8 < 2^d
+ orderBound : order Q ≤ 2^d
+ rowFit : height Q < 2^w
+ columnFit : width Q < 2^w
+ orderFit : order Q < 2^w
+ dimensionFit : Q.dimension < 2^w
+ labelFit : t+1 < 2^w
+ gramFit : Cursor.gramWidth d ≤ w
+ widthThree : 3 ≤ w
+ depthFit : d ≤ w
+ rootFit : 2*d+6 ≤ w
+ descriptorFit : (d+1)*widthFactor ≤ w
+ childFit : (2*d+6+1)*widthFactor ≤ w
+ wordLive : w ≤ live
+ arityLive : t ≤ live
+ scalarLive : max live (e*v) ≤ live
+ liveSpace : live ≤ space
+ target (op : QueryData.Operation t) (i : Fin Q.dimension) :
+ PairCall.requiredWidth (targetArgs Q op i) ≤ w ∧
+ TargetRead.clock w live e v (targetArgs Q op i) ≤ time ∧ TargetRead.space w live e v ≤ space
+
+theorem canonicalFits {P : ReaderPlan} {Q : QueryData P.arity (P.equations+P.pins) F} (h : P.Covers Q)
+ {w e v degree limb : ℕ} (hw : planWidth P ≤ w) (he : e ≤ degree) (hv : v ≤ limb) (sp ex : ℕ) :
+ CanonicalFits Q (planDepth P) w v e (P.live degree limb w sp) (P.armSpace degree limb w sp)
+ (P.readTime degree limb w sp ex) := by
+ obtain ⟨_,_,_,hrow,hcol,horder,hr⟩ := plan_query_shapes h
+ have hgram := (planWidth_covers P).1.trans hw
+ have hwidth := (planWidth_covers P).2.trans hw
+ obtain ⟨h₃,hd,hroot,hdesc,hchild,_⟩ := gramWidth_fits hgram
+ have addr := Nat.pow_le_pow_right (by decide : 0 < 2) hd
+ change height Q + height Q + (height Q + width Q)*height Q + width Q + 8 < 2^(planDepth P) at hrow
+ change width Q + width Q + (width Q + height Q)*width Q + height Q + 8 < 2^(planDepth P) at hcol
+ change order Q+order Q+0+order Q+8 < 2^(planDepth P) at horder
+ have hheight : height Q < 2^w := (show height Q < 2^(planDepth P) by omega).trans_le addr
+ have hwidthQ : width Q < 2^w := (show width Q < 2^(planDepth P) by omega).trans_le addr
+ have horderQ : order Q < 2^w := (show order Q < 2^(planDepth P) by omega).trans_le addr
+ have hdim : Q.dimension ≤ order Q := Nat.sub_le ..
+ have pairFits := ExponentISA.indexFits (t := P.arity) (L := P.source) (D := P.column)
+ (scale := P.scale) (mark := P.arity) (request := 0) (k₁ := 0) (k₂ := 0) (Nat.zero_le _) (Nat.zero_le _)
+ have har : P.arity < 2^P.pairWidth := pairFits.1.arity_lt
+ have pw : P.pairWidth+1 ≤ w := by unfold ReaderPlan.wordWidth at hwidth; omega
+ have harity : P.arity+1 < 2^w := by
+ apply Nat.lt_of_lt_of_le _ (Nat.pow_le_pow_right (by decide : 0 < 2) pw)
+ rw [pow_succ]
+ have := Nat.two_pow_pos P.pairWidth
+ omega
+ have hscale := Nat.mul_le_mul he hv
+ have live : w ≤ P.live degree limb w sp ∧ P.arity ≤ P.live degree limb w sp ∧
+ max (P.live degree limb w sp) (e*v) ≤ P.live degree limb w sp := by
+ unfold ReaderPlan.live
+ omega
+ have room : P.live degree limb w sp ≤ P.armSpace degree limb w sp := by
+ dsimp only [ReaderPlan.armSpace,MacaulayRead.Arms.transient]
+ omega
+ refine ⟨hrow,hcol,horder,hr,hheight,hwidthQ,horderQ,hdim.trans_lt horderQ,harity,hgram,h₃,hd,hroot,
+ hdesc,hchild,live.1,live.2.1,live.2.2,room,?_⟩
+ intro op i
+ obtain ⟨ht,_,_,_,hc,hs⟩ := ReaderPlan.target_bounds h op (targetArgs Q op i) rfl rfl rfl rfl rfl he hv hwidth sp ex
+ exact ⟨ht,hc,hs⟩
+
+end RankQuery.Stack.Coordinate.ConcreteResources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryResourceBounds.lean b/lean/OAI/Computability/VPVNP/RankQueryResourceBounds.lean
new file mode 100644
index 0000000000..ee67d96b84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryResourceBounds.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.RankQueryTimeBounds
+import OAI.Computability.VPVNP.RankQueryExecutionSpace
+import OAI.Computability.VPVNP.RankCursorSchurSpace
+
+/-!
+# Rank resources with a separately bounded scalar-entry routine
+
+The expensive descriptor's time bound is allowed in the query clock. Its
+space bound enters the maximum with the cubic bound on the short local
+actions, binary registers, and suspended Schur frames.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+/-- A uniform exponential clock still suffices when the descriptor has a
+larger time budget than the remaining Schur actions. -/
+theorem rankReadTime_le_exp (n m Bd B w v e s : ℕ)
+ (hn : n ≤ 2^s) (hm : m ≤ 2^s) (hd : Bd ≤ 2^s) (hB : B ≤ 2^s)
+ (hw : w ≤ 2^s) (hv : v ≤ 2^s) (he : e ≤ 2^s) :
+ let Z := (n+m)*n
+ ((n+1)*(Z+1))*(readClock n n Z Bd B w v e+checkClock w v e+1)+2 ≤
+ 2^((4*s+10)*(4*s+7)+5*s+20) := by
+ let Z := (n+m)*n
+ have hlocal : Engine.boundedStepTime Bd B w v e ≤ Engine.stepBudget (max Bd B) w v e := by
+ unfold Engine.boundedStepTime Engine.stepBudget
+ omega
+ have hread : readClock n n Z Bd B w v e ≤ rootQueryClock n n Z (max Bd B) w v e :=
+ Nat.add_le_add_left (Nat.add_le_add_right (Nat.mul_le_mul_left (SchurKey.clock n n Z) hlocal) _) _
+ apply le_trans _ (rankTime_le_exp n m (max Bd B) w v e s hn hm (max_le hd hB) hw hv he)
+ exact Nat.add_le_add_right (Nat.mul_le_mul_left _ (Nat.add_le_add_right (Nat.add_le_add_right hread _) _)) _
+
+/-- If the matrix row count fits in `s` bits, space outside the descriptor is
+bounded by a cubic polynomial in the local widths, auxiliary space, and
+short-action budget. The descriptor's own space bound remains separate. -/
+theorem rankReadSpace_le (n s S A B w v e : ℕ) (hn : n ≤ 2^s) :
+ outerRankSpace (readSpace n n S A B w v e) A w v e ≤
+ max (S+1) (32768*(s+A+B+w+v+e+1)^3) := by
+ let M := s+A+B+w+v+e+1
+ have hp : 1 ≤ M := by dsimp [M]; omega
+ have hs : s ≤ M := by dsimp [M]; omega
+ have ha : A ≤ M := by dsimp [M]; omega
+ have hb : B ≤ M := by dsimp [M]; omega
+ have hw : w ≤ M := by dsimp [M]; omega
+ have hv : v ≤ M := by dsimp [M]; omega
+ have he : e ≤ M := by dsimp [M]; omega
+ have hm₂ : M ≤ M^2 := by simpa [pow_two] using Nat.mul_le_mul_left M hp
+ have hm₃ : M^2 ≤ M^3 := Nat.pow_le_pow_right hp (by decide)
+ have hev : e*v ≤ M^2 := by simpa only [pow_two] using Nat.mul_le_mul he hv
+ have hmax : max 1 (max w (e*v)) ≤ M^2 := by omega
+ have hdepth := Nat.clog_le_of_le_pow hn
+ have hhistory : (Nat.clog 2 n+4+Nat.clog 2 n)*(2*max 1 (max w (e*v))+1) ≤ 18*M^3 := calc
+ _ ≤ (6*M)*(3*M^2) := Nat.mul_le_mul (by omega) (by omega)
+ _ = _ := by ring
+ have hlocal : Engine.stepBudget B w v e ≤ 224*M^2 := by unfold Engine.stepBudget; omega
+ have hschur : Engine.runSpace A (Nat.clog 2 n+4+Nat.clog 2 n) B w v e ≤ 242*M^3 := by
+ unfold Engine.runSpace
+ omega
+ have hload : loadClock w ≤ 43*M := by unfold loadClock; omega
+ have hsq : (w+1)^2 ≤ 4*M^2 := calc
+ _ ≤ (2*M)^2 := Nat.pow_le_pow_left (by omega) 2
+ _ = _ := by ring
+ have hcheck : checkClock w v e ≤ 29242*M^2 := by unfold checkClock; rw [Registers.clock_eq]; omega
+ change _ ≤ max (S+1) (32768*M^3)
+ have hprep : max w A + loadClock w ≤ 32768*M^3 := by
+ have hx := max_le hw ha
+ omega
+ have hcap : Engine.boundedSpace S A (Nat.clog 2 n+4+Nat.clog 2 n) B w v e ≤
+ max (S+1) (32768*M^3) :=
+ max_le_max le_rfl (hschur.trans (Nat.mul_le_mul_right _ (by decide)))
+ have htail : A+w+e*v+1+checkClock w v e ≤ 32768*M^3 := by omega
+ exact max_le (max_le (hprep.trans (le_max_right ..)) hcap) (htail.trans (le_max_right ..))
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryRoutineSpace.lean b/lean/OAI/Computability/VPVNP/RankQueryRoutineSpace.lean
new file mode 100644
index 0000000000..9f7e2100c6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryRoutineSpace.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.RankQueryGramReadSpace
+import OAI.Computability.VPVNP.EvaluatorRadixSpace
+
+/-! # Lifting a bounded local trace at a known call boundary -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.FiniteRoutine
+
+open UniversalCountStack
+
+variable {K L : Type} [DecidableEq K] [DecidableEq L]
+
+private theorem same_endpoint {Q : Type} {code : StackCode K Q} {n : ℕ}
+ {q u v : Q} {s out out' : Stacks K} (a : StackRuns code n q s u out) (b : StackRuns code n q s v out') :
+ u = v ∧ out = out' := by
+ induction a with
+ | nil => cases b; exact ⟨rfl,rfl⟩
+ | cons h _ ih =>
+ cases b with
+ | cons h' tail =>
+ have unique {q₀ q₁ q₂ : Q} {s₀ s₁ s₂ : Stacks K}
+ (hh : StackStep code q₀ s₀ q₁ s₁) (hh' : StackStep code q₀ s₀ q₂ s₂) : q₁ = q₂ ∧ s₁ = s₂ := by
+ cases hh <;> cases hh' <;> simp_all
+ obtain ⟨rfl,rfl⟩ := unique h h'
+ exact ih tail
+
+/-- Returning deterministic calls have a unique length and final bank. -/
+theorem return_unique {r : FiniteRoutine K} {t n : ℕ} {s a b : Stacks K}
+ (h : r.Runs t s a) (g : r.Runs n s b) : t = n ∧ a = b := by
+ have he := Nat.le_antisymm (EvaluatorRadixDivision.ticks_le_at_return g rfl h)
+ (EvaluatorRadixDivision.ticks_le_at_return h rfl g)
+ subst n
+ exact ⟨rfl,(same_endpoint h g).2⟩
+
+/-- Lift a space certificate onto an already verified caller trace. Equality
+of normal returns identifies its actual final scratch state and elapsed time. -/
+theorem BoundedRun.lift_trace {r : FiniteRoutine K} {ports : K → L} (hp : Function.Injective ports)
+ {cap n t : ℕ} {s u : Stacks L} {small out : Stacks K} (run : r.BoundedRun cap n small out)
+ (outer : (r.onPorts ports).Runs t s u)
+ (start : ∀ j, (s j).length ≤ cap) (hin : ∀ i, s (ports i) = small i) :
+ (r.onPorts ports).BoundedRun cap t s u := by
+ have h := run.onPorts hp s (fun j _ => start j)
+ rw [installStacks_frame hp hin (fun _ _ => rfl)] at h
+ obtain ⟨rfl,he⟩ := return_unique h.runs outer
+ rwa [← he]
+
+end RAMTape.FiniteRoutine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryShapeResources.lean b/lean/OAI/Computability/VPVNP/RankQueryShapeResources.lean
new file mode 100644
index 0000000000..914666f549
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryShapeResources.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.RankQueryConcreteResources
+
+/-! # Choosing one bit width for both matrix orientations and all Schur roots -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.ConcreteResources
+
+open PolynomiallyBounded Dispatch RadicalCertificate.MonomialIndex
+
+/-- The largest rectangular prefix in either orientation bounds the
+determinant-coefficient scan. The extra unit gives the strict comparison
+required when the power of two is attained exactly. -/
+def shapeBits (rows cols : ℕ) :=
+ let N := max rows cols
+ Nat.clog 2 (N+N+(N+N)*N+N+9)
+
+theorem shapeBits_poly {rows cols : ℕ → ℕ} (hr : LB rows) (hc : LB cols) :
+ PB (fun n => shapeBits (rows n) (cols n)) := by
+ have m := log_max hr hc
+ have twice := clog_add m m
+ exact clog_add (clog_add (clog_add twice (clog_mul twice m)) m) (log_const 9)
+
+/-- A prefix may be read either as a row prefix or as a column prefix
+of the transposed matrix. The same depth bound applies in both cases. -/
+theorem shapeBits_rect {rows cols a b : ℕ} (ha : a ≤ max rows cols) (hb : b ≤ max rows cols) :
+ a+a+(a+b)*a+b+8 < 2^(shapeBits rows cols) := by
+ let N := max rows cols
+ have hh : (a+b)*a ≤ (N+N)*N := Nat.mul_le_mul (Nat.add_le_add ha hb) ha
+ exact (show a+a+(a+b)*a+b+8 < N+N+(N+N)*N+N+9 by change a ≤ N at ha; change b ≤ N at hb; omega).trans_le
+ (Nat.le_pow_clog (by decide) _)
+
+/-- The constant-polynomial determinant specialization uses degree zero
+and the same bound for the minor order and the recursion parameter. -/
+theorem shapeBits_minor {rows cols r : ℕ} (hr : r ≤ max rows cols) :
+ r+r+0+r+8 < 2^(shapeBits rows cols) ∧ r ≤ 2^(shapeBits rows cols) := by
+ have h := shapeBits_rect hr hr
+ omega
+
+theorem gramWidth_poly {d : ℕ → ℕ} (hd : PB d) : PB (fun i => Cursor.gramWidth (d i)) :=
+ ((((const 2).mul hd).add (const 7)).mul (const _)).add (const 3)
+
+/-- These are the three word-fit assumptions shared by the ordinary Schur
+root and the weighted Gram descriptor, together with the outer cursor's
+width condition. An address kernel can require a larger width. -/
+theorem gramWidth_fits {d w : ℕ} (h : Cursor.gramWidth d ≤ w) :
+ 3 ≤ w ∧ d ≤ w ∧ 2*d+6 ≤ w ∧ (d+1)*widthFactor ≤ w ∧
+ (2*d+6+1)*widthFactor ≤ w ∧ (d+1)*Cursor.control.wordFactor ≤ w := by
+ let factor := max widthFactor Cursor.control.wordFactor + 1
+ have hh : 2*d+7 ≤ (2*d+7)*factor := Nat.le_mul_of_pos_right _ (Nat.succ_pos _)
+ have hf : widthFactor ≤ factor := (le_max_left ..).trans (Nat.le_succ _)
+ have hc : Cursor.control.wordFactor ≤ factor := (le_max_right ..).trans (Nat.le_succ _)
+ have full := Nat.mul_le_mul_left (2*d+7) hf
+ have descr := Nat.mul_le_mul (show d+1 ≤ 2*d+7 by omega) hf
+ have cursor := Nat.mul_le_mul (show d+1 ≤ 2*d+7 by omega) hc
+ change (2*d+7)*factor+3 ≤ w at h
+ rw [show 2*d+6+1 = 2*d+7 by omega]
+ omega
+
+/-- A single address width accommodates the graded-key enumeration as well
+as the two orientations of the Schur rank scanner. -/
+def sliceAddress {t eqs : ℕ} {F : Type*} (s : QueryData t eqs F) :=
+ let rows := eqs*size t s.multiplierDegree+size t s.pointBound
+ let cols := size t s.columnDegree
+ max (Cursor.gramWidth (shapeBits rows cols))
+ (max (scanWidth t s.multiplierDegree) (max (scanWidth t s.columnDegree) (scanWidth t s.pointBound)))
+
+theorem sliceAddress_poly {t eqs : ℕ → ℕ} {K : ℕ → Type*} (s : (n : ℕ) → QueryData (t n) (eqs n) (K n))
+ (ht : PB t) (hE : LB eqs) (hQ : LB (fun n => (s n).fieldOrder))
+ (hD : LB (fun n => (s n).degreeBound)) (hN : LB (fun n => (s n).pointBound))
+ (hq : ∀ n, 2 ≤ (s n).fieldOrder) : PB (fun n => sliceAddress (s n)) := by
+ obtain ⟨rows,cols,multiplier,columns,points⟩ := bounded_query_dimensions s ht hE hQ hD hN hq
+ exact poly_max (gramWidth_poly (shapeBits_poly rows cols)) (poly_max multiplier (poly_max columns points))
+
+theorem sliceAddress_covers {t eqs : ℕ} {F : Type*} (s : QueryData t eqs F) :
+ let rows := eqs*size t s.multiplierDegree+size t s.pointBound
+ let cols := size t s.columnDegree
+ Cursor.gramWidth (shapeBits rows cols) ≤ sliceAddress s ∧
+ scanWidth t s.multiplierDegree ≤ sliceAddress s ∧ scanWidth t s.columnDegree ≤ sliceAddress s ∧
+ scanWidth t s.pointBound ≤ sliceAddress s := by
+ dsimp only [sliceAddress]
+ omega
+
+end RankQuery.Stack.Coordinate.ConcreteResources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStack.lean b/lean/OAI/Computability/VPVNP/RankQueryStack.lean
new file mode 100644
index 0000000000..24d4a26af7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStack.lean
@@ -0,0 +1,193 @@
+import OAI.Computability.VPVNP.DeterminantQueryBounds
+
+/-!
+# Continuation stack for scalar coefficient queries
+
+A nonterminal query adds a sequence of products. The machine scans the sequence
+in reverse index order and evaluates the two children of each product in turn.
+Only one return frame is live per active level. The execution bound counts
+push, pop and scalar-update transitions, and bounds the depth at every
+intermediate configuration.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+/-- A terminal query supplies a scalar. A composite query supplies the number
+of products in its sum and computes the two subqueries from the product index. -/
+structure Program (Q R : Type*) where
+ /-- Return the value of a leaf query or the number of product terms to evaluate for a branch. -/
+ describe : Q → Sum R ℕ
+ /-- Select the left factor query of the indexed product term. -/
+ left : Q → ℕ → Q
+ /-- Select the right factor query of the indexed product term. -/
+ right : Q → ℕ → Q
+
+variable {Q R : Type*} [Semiring R]
+
+/-- Saved parent query, remaining scan count and partial sum, with the left factor value
+retained while the right factor runs. -/
+inductive Frame (Q R : Type*) where
+ | left (q : Q) (remaining : ℕ) (accumulator : R)
+ | right (q : Q) (remaining : ℕ) (accumulator leftValue : R)
+
+/-- Current evaluator action, entering a query, scanning its sum, or returning a computed
+value. -/
+inductive Control (Q R : Type*) where
+ | enter (q : Q)
+ | scan (q : Q) (remaining : ℕ) (accumulator : R)
+ | returned (value : R)
+
+/-- Evaluator configuration consisting of the current control and the stack of suspended parent
+frames. -/
+abbrev Config (Q R : Type*) := Control Q R × List (Frame Q R)
+
+namespace Program
+
+variable (p : Program Q R)
+
+/-- One call, return, or loop transition. At a terminal result the state is fixed. -/
+def step : Config Q R → Config Q R
+ | (.enter q, s) =>
+ match p.describe q with
+ | .inl r => (.returned r, s)
+ | .inr t => (.scan q t 0, s)
+ | (.scan _ 0 a, s) => (.returned a, s)
+ | (.scan q (k + 1) a, s) => (.enter (p.left q k), .left q k a :: s)
+ | (.returned v, .left q k a :: s) => (.enter (p.right q k), .right q k a v :: s)
+ | (.returned v, .right q k a l :: s) => (.scan q k (a + l * v), s)
+ | (.returned v, []) => (.returned v, [])
+
+/-- A run of exactly `t` transitions, with at most `cap` saved frames
+throughout. The endpoint also satisfies the cap. -/
+inductive Runs (cap : ℕ) : ℕ → Config Q R → Config Q R → Prop
+ | done (c : Config Q R) (hc : c.2.length ≤ cap) : Runs cap 0 c c
+ | next {c d : Config Q R} {t : ℕ} (hc : c.2.length ≤ cap)
+ (h : Runs cap t (p.step c) d) : Runs cap (t + 1) c d
+
+theorem Runs.one {cap : ℕ} {c : Config Q R} (hc : c.2.length ≤ cap)
+ (hn : (p.step c).2.length ≤ cap) : p.Runs cap 1 c (p.step c) :=
+ .next hc (.done _ hn)
+
+theorem Runs.join {cap m n : ℕ} {a b c : Config Q R}
+ (hab : p.Runs cap m a b) (hbc : p.Runs cap n b c) : p.Runs cap (m + n) a c := by
+ induction hab with
+ | done => simpa using hbc
+ | next hc _ ih => simpa only [Nat.succ_add] using Runs.next hc (ih hbc)
+
+theorem Runs.iterate {cap t : ℕ} {a b : Config Q R} (h : p.Runs cap t a b) :
+ p.step^[t] a = b := by
+ induction h with
+ | done => rfl
+ | next _ _ ih => exact ih
+
+/-- Scalar recurrence to be realized by the machine. -/
+def Realizes (v : Q → R) : Prop := ∀ q, v q = match p.describe q with
+ | .inl r => r
+ | .inr t => ∑ k ∈ Finset.range t, v (p.left q k) * v (p.right q k)
+
+/-- Both children of every actual call decrease the same depth bound. -/
+def Descends (depth : Q → ℕ) : Prop :=
+ ∀ q t, p.describe q = .inr t → ∀ k < t,
+ depth (p.left q k) < depth q ∧ depth (p.right q k) < depth q
+
+/-- Every branch described by the program has at most `b` product terms. -/
+def ArityLE (b : ℕ) : Prop := ∀ q t, p.describe q = .inr t → t ≤ b
+
+private theorem runScan (v : Q → R) (q : Q) (t childCost cap : ℕ)
+ (s : List (Frame Q R)) (hs : s.length ≤ cap)
+ (hl : ∀ k < t, ∀ a, ∃ n ≤ childCost, p.Runs cap n
+ (.enter (p.left q k), .left q k a :: s)
+ (.returned (v (p.left q k)), .left q k a :: s))
+ (hr : ∀ k < t, ∀ a l, ∃ n ≤ childCost, p.Runs cap n
+ (.enter (p.right q k), .right q k a l :: s)
+ (.returned (v (p.right q k)), .right q k a l :: s))
+ (hpush : 0 < t → s.length + 1 ≤ cap) (acc : R) :
+ ∃ n ≤ 1 + t * (3 + 2 * childCost), p.Runs cap n (.scan q t acc, s)
+ (.returned (acc + ∑ k ∈ Finset.range t, v (p.left q k) * v (p.right q k)), s) := by
+ induction t generalizing acc with
+ | zero =>
+ exact ⟨1, by simp, by simpa [step] using Runs.one p (c := (.scan q 0 acc, s)) hs hs⟩
+ | succ k ih =>
+ let l := v (p.left q k)
+ let r := v (p.right q k)
+ have hcap := hpush (Nat.zero_lt_succ k)
+ obtain ⟨x, hx, hrunL⟩ := hl k (Nat.lt_succ_self _) acc
+ obtain ⟨y, hy, hrunR⟩ := hr k (Nat.lt_succ_self _) acc l
+ obtain ⟨z, hz, hrunS⟩ := ih (fun j hj => hl j (Nat.lt_succ_of_lt hj))
+ (fun j hj => hr j (Nat.lt_succ_of_lt hj)) (fun _ => hcap) (acc + l * r)
+ have push := Runs.one p (c := (.scan q (k + 1) acc, s)) hs hcap
+ have switch := Runs.one p (c := (.returned l, .left q k acc :: s)) hcap hcap
+ have pop := Runs.one p (c := (.returned r, .right q k acc l :: s)) hcap hs
+ refine ⟨1 + x + 1 + y + 1 + z, ?_, ?_⟩
+ · exact show 1 + x + 1 + y + 1 + z ≤ _ by rw [Nat.succ_mul]; omega
+ · have joined := ((((push.join p hrunL).join p switch).join p hrunR).join p pop).join p hrunS
+ rw [Finset.sum_range_succ, add_comm _ (v (p.left q k) * v (p.right q k)), ← add_assoc]
+ exact joined
+
+/-- A clock and a simultaneous space bound for every invocation in any
+continuation. The clock charges all control transitions. -/
+theorem run_bounded (v : Q → R) (depth : Q → ℕ) (b : ℕ)
+ (hv : p.Realizes v) (hd : p.Descends depth) (hb : p.ArityLE b)
+ (d : ℕ) (q : Q) (hq : depth q ≤ d) (s : List (Frame Q R)) :
+ ∃ t ≤ (5 + 6 * b) ^ (d + 1), p.Runs (s.length + d) t (.enter q, s) (.returned (v q), s) := by
+ induction d generalizing q s with
+ | zero =>
+ have hcap : s.length ≤ s.length + 0 := by omega
+ cases hdes : p.describe q with
+ | inl r =>
+ have he : v q = r := by simpa [hdes] using hv q
+ exact ⟨1, by simp; omega, by simpa [step, hdes, he] using Runs.one p (c := (.enter q, s)) hcap (by simp [step, hdes])⟩
+ | inr t =>
+ have ht : t = 0 := by
+ by_contra hn
+ have := (hd q t hdes 0 (Nat.pos_of_ne_zero hn)).1
+ omega
+ subst t
+ have he : v q = 0 := by simpa [hdes] using hv q
+ have start := Runs.one p (c := (.enter q, s)) hcap (by simp [step, hdes])
+ have finish := Runs.one p (c := (.scan q 0 0, s)) hcap hcap
+ refine ⟨2, by simp; omega, ?_⟩
+ simpa [step, hdes, he] using (start.join p (by simpa [step, hdes] using finish) : p.Runs _ (1+1) _ (.returned 0, s))
+ | succ d ih =>
+ have hcap : s.length ≤ s.length + (d + 1) := by omega
+ cases hdes : p.describe q with
+ | inl r =>
+ have he : v q = r := by simpa [hdes] using hv q
+ exact ⟨1, Nat.one_le_pow _ _ (by omega), by simpa [step, hdes, he] using Runs.one p (c := (.enter q, s)) hcap (by simp [step, hdes])⟩
+ | inr t =>
+ let w := (5 + 6 * b) ^ (d + 1)
+ have hdepth : ∀ k < t, depth (p.left q k) ≤ d ∧ depth (p.right q k) ≤ d := by
+ intro k hk
+ have := hd q t hdes k hk
+ omega
+ have hs' (f : Frame Q R) : (f :: s).length + d = s.length + (d + 1) := by simp; omega
+ obtain ⟨n, hn, rest⟩ := runScan p v q t w (s.length + (d+1)) s hcap
+ (fun k hk a => by simpa only [hs'] using ih _ (hdepth k hk).1 (.left q k a :: s))
+ (fun k hk a l => by simpa only [hs'] using ih _ (hdepth k hk).2 (.right q k a l :: s))
+ (fun _ => by omega) 0
+ have htb := hb q t hdes
+ have hw : 1 ≤ w := Nat.one_le_pow _ _ (by omega)
+ have hbw := Nat.mul_le_mul_left b hw
+ have ht' := Nat.mul_le_mul_right (3 + 2 * w) htb
+ have clock : 1 + n ≤ (5 + 6 * b) ^ (d + 1 + 1) := by
+ rw [pow_succ]
+ change 1 + n ≤ w * (5 + 6 * b)
+ simp only [Nat.mul_add, Nat.mul_one] at hn ht' hbw
+ nlinarith
+ refine ⟨1 + n, clock, ?_⟩
+ have he : v q = ∑ k ∈ Finset.range t, v (p.left q k) * v (p.right q k) := by
+ simpa [hdes] using hv q
+ have start := Runs.one p (c := (.enter q, s)) hcap (by simp [step, hdes])
+ exact start.join p (by simpa [step, hdes, he] using rest)
+
+end Program
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackAccumulate.lean b/lean/OAI/Computability/VPVNP/RankQueryStackAccumulate.lean
new file mode 100644
index 0000000000..fb9e37f5c9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackAccumulate.lean
@@ -0,0 +1,47 @@
+import OAI.Computability.VPVNP.RankQueryStackNativeFrames
+import OAI.Computability.VPVNP.SliceArithmeticMultiplyAccumulate
+import OAI.Computability.VPVNP.StructuredStackCount
+
+/-! # Extension-field multiply-and-add on native Schur scalars -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Scalar
+
+open SliceArithmetic
+open SliceArithmeticRound (packed)
+open MultiplyAccumulate
+
+variable {p e v : ℕ} [Fact p.Prime] [NeZero e]
+
+/-- The public stacks of the Schur multiply-and-add callback. -/
+def accumulateFrame (c : Vector p e) (v : ℕ) (left returned acc : Scalar c) : RAMTape.Stacks Port :=
+ clean (external p e v (packed v (List.ofFn c)) (Engine.scalar v left) (Engine.scalar v returned)
+ (Engine.scalar v acc))
+
+theorem accumulate_runs (hw : Word.workingWidth p ≤ v) (c : Vector p e) (left returned acc : Scalar c) :
+ ∃ t ≤ callCap e v, machine.Runs t (accumulateFrame c v left returned acc)
+ (accumulateFrame c v left returned (acc + left * returned)) := by
+ have hd : (acc + left * returned).digits = add acc.digits (mul c left.digits returned.digits) := by
+ rw [product_eq]
+ change (pack c (add acc.digits (pack c (mul c left.digits returned.digits)).digits)).digits = _
+ simp
+ simpa only [accumulateFrame, Engine.scalar, hd] using machine_runs (NeZero.pos e) hw c
+ left.digits returned.digits acc.digits
+
+/-- The deterministic arithmetic call transfers control once, deducting its
+actual running time from the remaining budget. -/
+theorem accumulate_count (hw : Word.workingWidth p ≤ v) (c : Vector p e) (left returned acc : Scalar c) :
+ ∃ t ≤ callCap e v, ∀ (continuation : ℕ → RAMTape.Stacks Port → ℕ) (fuel : ℕ),
+ machine.body.count continuation (fuel + t) (accumulateFrame c v left returned acc) =
+ continuation fuel (accumulateFrame c v left returned (acc + left * returned)) := by
+ obtain ⟨t, ht, run⟩ := accumulate_runs hw c left returned acc
+ exact ⟨t, ht, run.count_eq⟩
+
+end RankQuery.Stack.Scalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackActivate.lean b/lean/OAI/Computability/VPVNP/RankQueryStackActivate.lean
new file mode 100644
index 0000000000..b3632c50bd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackActivate.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.RankQueryStackEngineSpec
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-! # Installing the six computed child words as the next live Schur query -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine.Activate
+
+open RAMTape
+
+variable {K : Type} [DecidableEq K]
+
+/-- Live-frame slot for one of the six encoded query words, numbered one through six. -/
+def querySlot (i : Fin 6) : Fin 10 := (Fin.castAdd 3 i).succ
+
+private theorem querySlot_injective : Function.Injective querySlot := by
+ intro a b h
+ exact Fin.ext (Nat.succ.inj (congrArg Fin.val h))
+
+private def copies (src : Fin 6 → K) (tmp : K) : List (Fin 6) → FiniteRoutine (Engine.Port K)
+ | [] => .ret
+ | i :: is => (copies src tmp is).followedBy
+ (SuccessorFields.prependCopy (.aux (src i)) (.frame (.inl (querySlot i))) (.aux tmp))
+
+/-- Copy the six pending query words into the live frame using a temporary stack. -/
+def machine (src : Fin 6 → K) (tmp : K) := copies src tmp (List.finRange 6)
+
+variable {n U Z : ℕ}
+
+private def partialFields (w : ℕ) (q : Key n U Z) (ks : List (Fin 6)) : Data :=
+ Fin.cons [] (Fin.append (fun i => if i ∈ ks then UniversalCountStack.digits w (q.words i) else []) ![[],[],[]])
+
+private theorem addField (w : ℕ) (q : Key n U Z) (ks : List (Fin 6)) (i : Fin 6) :
+ Function.update (partialFields w q ks) (querySlot i) (UniversalCountStack.digits w (q.words i)) =
+ partialFields w q (i :: ks) := by
+ funext j
+ refine Fin.cases ?_ (fun j => ?_) j
+ · rw [Function.update_of_ne (show 0 ≠ querySlot i from Fin.succ_ne_zero _ |>.symm)]
+ rfl
+ · refine Fin.addCases (motive := fun j => Function.update (partialFields w q ks) (querySlot i)
+ (UniversalCountStack.digits w (q.words i)) j.succ = partialFields w q (i :: ks) j.succ)
+ (fun x : Fin 6 => ?_) (fun x : Fin 3 => ?_) j
+ · change Function.update _ (querySlot i) _ (querySlot x) = _
+ by_cases h : x = i
+ · subst x; rw [Function.update_self]; simp [partialFields]
+ · rw [Function.update_of_ne (querySlot_injective.ne h)]
+ simp [partialFields, querySlot, h]
+ · have hne : (Fin.natAdd 6 x).succ ≠ querySlot i := by
+ intro h; have := congrArg Fin.val h; simp [querySlot] at this; omega
+ simp [partialFields, Function.update_of_ne hne]
+
+private theorem setLive (l h : Data) (sig ret : List Bool) (aux : Stacks K) (i : Fin 10) (xs : List Bool) :
+ Function.update (store l h sig ret aux) (.frame (.inl i)) xs = store (Function.update l i xs) h sig ret aux := by
+ funext k; cases k with
+ | frame j => cases j with
+ | inl j => by_cases he : i = j <;> simp [he, store, Function.update]
+ | inr => rfl
+ | _ => rfl
+
+private theorem copies_runs (src : Fin 6 → K) (tmp : K) (hne : ∀ i, src i ≠ tmp)
+ (w : ℕ) (q : Key n U Z) (h : Data) (aux : Stacks K) (ht : aux tmp = [])
+ (hs : ∀ i, aux (src i) = UniversalCountStack.digits w (q.words i))
+ (ks : List (Fin 6)) (hn : ks.Nodup) :
+ (copies src tmp ks).Runs (ks.length*(5*w+2)+1) (store (fun _ => []) h [] [] aux)
+ (store (partialFields w q ks) h [] [] aux) := by
+ induction ks with
+ | nil =>
+ have h0 : partialFields w q [] = fun _ => [] := by
+ funext j; fin_cases j <;> rfl
+ rw [h0]; simp only [List.length_nil, Nat.zero_mul, Nat.zero_add]; exact StackRuns.cons (.goto rfl) (.nil ..)
+ | cons i ks ih =>
+ let s := store (partialFields w q ks) h [] [] aux
+ have hd : s (.frame (.inl (querySlot i))) = [] := by simp [s, store, partialFields, querySlot, hn.notMem]
+ have step := SuccessorFields.prependCopy_runs (Engine.Port.aux (src i)) (.frame (.inl (querySlot i))) (.aux tmp)
+ (by simp) (fun e => hne i (Engine.Port.aux.inj e)) (by simp) s ht
+ change (SuccessorFields.prependCopy _ _ _).Runs (5*(aux (src i)).length+2) _ _ at step
+ rw [show s (.aux (src i)) = UniversalCountStack.digits w (q.words i) from hs i, hs, hd,
+ List.append_nil, UniversalCountStack.length_digits, setLive, addField] at step
+ have both := FiniteRoutine.Runs.followedBy (ih hn.of_cons) step
+ rw [show (i :: ks).length*(5*w+2)+1 = ks.length*(5*w+2)+1+(5*w+2) by simp only [List.length_cons]; ring]
+ exact both
+
+/-- Enter the pending child, preserving the full auxiliary register bank and
+all ten encoded histories. -/
+theorem machine_runs (src : Fin 6 → K) (tmp : K) (hne : ∀ i, src i ≠ tmp)
+ {p e : ℕ} {c : SliceArithmetic.Vector p e} (w v : ℕ) (q : Key n U Z) (fs : List (F n U Z c)) (aux : Stacks K)
+ (ht : aux tmp = []) (hs : ∀ i, aux (src i) = UniversalCountStack.digits w (q.words i)) :
+ (machine src tmp).Runs (6*(5*w+2)+1) (store (fun _ => []) (history w v fs) [] [] aux)
+ (atControl w v (.enter q) fs aux) := by
+ have he : partialFields w q (List.finRange 6) = fields w [] q [] [] [] := by
+ simp [partialFields, fields]
+ simpa only [machine, List.length_finRange, atControl, live, output, he] using
+ copies_runs src tmp hne w q (history w v fs) aux ht hs (List.finRange 6) (List.nodup_finRange 6)
+
+end RankQuery.Stack.Engine.Activate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackAlias.lean b/lean/OAI/Computability/VPVNP/RankQueryStackAlias.lean
new file mode 100644
index 0000000000..68baf98b11
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackAlias.lean
@@ -0,0 +1,215 @@
+import OAI.Computability.VPVNP.RankQueryStackEngineSpec
+import OAI.Computability.VPVNP.RankQueryStackPhysical
+
+/-!
+# Register aliases between the determinant engine and its arithmetic bank
+
+Schur instructions read the six live query fields directly. Child instructions
+also read the saved loop index. Output registers and temporary word stacks
+belong to the auxiliary bank. The routine preserves the entire live frame and
+history, as well as every auxiliary port outside the register bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.EngineAlias
+
+open Dispatch Engine BurstRAM RAMTape
+
+/-- Register count for the aliased dispatcher, including eight input words, six outputs and the
+scratch bank. -/
+abbrev R := 14+Dispatch.capacity
+/-- Register-machine ports for the dispatcher with no public-word inputs. -/
+abbrev Small := ISA.Port R 0
+/-- Indices of the dispatcher's physical registers. -/
+abbrev Reg := Fin R
+
+/-- Identify the six query inputs and, when enabled, the count input with their corresponding
+live-frame slots. -/
+def liveSlot (countLive : Bool) : Small → Option (Fin 10)
+ | .reg i => if h : i.val < 6 ∨ countLive = true ∧ i.val = 6 then
+ some ⟨i.val+1, by omega⟩ else none
+ | _ => none
+
+private theorem liveSlot_info {flag : Bool} {port : Small} {j : Fin 10} (he : liveSlot flag port = some j) :
+ ∃ i : Reg, port = .reg i ∧ j.val = i.val+1 ∧ (i.val < 6 ∨ flag = true ∧ i.val = 6) := by
+ cases port with
+ | reg i =>
+ simp only [liveSlot] at he
+ split_ifs at he with h
+ cases he
+ exact ⟨i,rfl,rfl,h⟩
+ | pub | persistent | work | logPort => contradiction
+
+variable {K : Type}
+
+/-- Route aliased inputs to the live frame and the remaining dispatcher ports through the
+supplied auxiliary bank. -/
+def ports (bank : Small ↪ K) (countLive : Bool) (port : Small) : Engine.Port K :=
+ match liveSlot countLive port with
+ | some j => .frame (.inl j)
+ | none => .aux (bank port)
+
+theorem ports_injective (bank : Small ↪ K) (countLive : Bool) : Function.Injective (ports bank countLive) := by
+ intro a b h
+ unfold ports at h
+ cases ha : liveSlot countLive a <;> cases hb : liveSlot countLive b <;> rw [ha,hb] at h
+ · exact bank.injective (Engine.Port.aux.inj h)
+ · contradiction
+ · contradiction
+ · obtain ⟨i,rfl,hi,_⟩ := liveSlot_info ha
+ obtain ⟨j,rfl,hj,_⟩ := liveSlot_info hb
+ have eq := Sum.inl.inj (Engine.Port.frame.inj h)
+ have eq' := congrArg Fin.val eq
+ congr 1
+ apply Fin.ext
+ omega
+
+/-- Empty public-word bank of the aliased dispatcher. -/
+abbrev pub {w : ℕ} : Fin 0 → Word w := Fin.elim0
+
+/-- Width-sized auxiliary register words, including a zero dummy counter and
+the row dimension. The scratch registers may contain arbitrary words. -/
+def Ready (bank : Small ↪ K) (w n : ℕ) (aux : Stacks K) : Prop :=
+ ∃ (base : Regs R w) (persist : Word w),
+ (base (Code.inReg capacity 6)).val = 0 ∧ (base (Code.inReg capacity 7)).val = n ∧
+ ∀ i, aux (bank i) = ISA.bank pub persist base [] i
+
+/-- Install one compiled dispatch operation with its query registers aliased to the live frame. -/
+def routine (bank : Small ↪ K) (countLive : Bool) (a : Operation) : FiniteRoutine (Engine.Port K) :=
+ a.machine.onPorts (ports bank countLive)
+
+/-- The fields actually read from the caller's frame. -/
+def LiveInput (w : ℕ) (countLive : Bool) (data : Engine.Data) (env : Fin 8 → ℕ) : Prop :=
+ ∀ i j, liveSlot countLive (.reg i) = some j → ∀ ix : Fin 8, ix.val = i.val →
+ data j = UniversalCountStack.digits w (env ix)
+
+private def replaceInputs {w : ℕ} (rs : Regs R w) (env : Fin 8 → ℕ) (i : Reg) : Word w :=
+ if hi : i.val < 8 then Fin.ofNat _ (env ⟨i.val,hi⟩) else rs i
+
+private def keepInputs {w : ℕ} (base out : Regs R w) (i : Reg) : Word w :=
+ if i.val < 8 then base i else out i
+
+private theorem replace_at {w : ℕ} (rs : Regs R w) (env : Fin 8 → ℕ) (i : Fin 8) :
+ replaceInputs rs env (Code.inReg capacity i) = Fin.ofNat _ (env i) := by
+ simp only [replaceInputs, Code.inReg]
+ exact dite_eq_left i.isLt
+
+private theorem keep_at {w : ℕ} (base out : Regs R w) (i : Fin 8) :
+ keepInputs base out (Code.inReg capacity i) = base (Code.inReg capacity i) := by
+ simp only [keepInputs, Code.inReg]
+ exact ite_eq_left i.isLt
+
+/-- Execute the dispatcher directly on the engine's frame. Replacing the
+auxiliary scratch state never changes the live query, history, or result. -/
+theorem run [DecidableEq K] {w p n : ℕ} (bank : Small ↪ K) (flag : Bool) (a : Operation)
+ (env : Fin 8 → ℕ) (live saved : Engine.Data) (signal result : List Bool) (aux : Stacks K)
+ (hready : Ready bank w n aux) (hlive : LiveInput w flag live env)
+ (h6 : flag = false → env 6 = 0) (h7 : env 7 = n)
+ (he : ∀ i, env i < 2^p) (hp : p ≤ w) (hw : (p+1)*widthFactor ≤ w) :
+ ∃ t ≤ a.clock w, ∃ out, Ready bank w n out ∧
+ (routine bank flag a).Runs t (store live saved signal result aux) (store live saved signal result out) ∧
+ (∀ i, out (bank (.reg (Code.outReg capacity i))) = UniversalCountStack.digits w (a.tree.eval env i)) ∧
+ ∀ j, (∀ i, bank i ≠ j) → out j = aux j := by
+ obtain ⟨base,persist,hzero,hrows,hbase⟩ := hready
+ let rs := replaceInputs base env
+ have hr (i : Fin 8) : (rs (Code.inReg capacity i)).val = env i := by
+ rw [show rs (Code.inReg capacity i) = _ from replace_at base env i]
+ exact Nat.mod_eq_of_lt ((he i).trans_le (Nat.pow_le_pow_right (by decide) hp))
+ have hsame (i : Reg) (hn : liveSlot flag (.reg i) = none) : rs i = base i := by
+ by_cases hi : i.val < 8
+ · let ix : Fin 8 := ⟨i.val,hi⟩
+ have hei : i = Code.inReg capacity ix := Fin.ext rfl
+ have hn' : ¬(i.val < 6 ∨ flag = true ∧ i.val = 6) := by
+ intro hv
+ simp [liveSlot, hv] at hn
+ have hcases : ix = 6 ∨ ix = 7 := by
+ by_cases hh : i.val = 6
+ · exact .inl (Fin.ext hh)
+ · exact .inr (Fin.ext (by dsimp [ix]; omega))
+ rcases hcases with hh | hh
+ · have hi6 : i.val = 6 := congrArg Fin.val hh
+ have hf : flag = false := by
+ cases flag with
+ | false => rfl
+ | true => exact (hn' (.inr ⟨rfl,hi6⟩)).elim
+ rw [hei,hh]
+ exact Fin.ext ((hr 6).trans ((h6 hf).trans hzero.symm))
+ · rw [hei,hh]
+ exact Fin.ext ((hr 7).trans (h7.trans hrows.symm))
+ · exact dite_eq_right hi
+ obtain ⟨t,ht,out,hrun,hkeep,hval⟩ := a.run env rs hw he hr pub persist
+ let cleaned := keepInputs base out
+ let final := installStacks bank aux (ISA.bank pub persist cleaned [])
+ have hfinal (i : Small) : final (bank i) = ISA.bank pub persist cleaned [] i := installStacks_at bank.injective ..
+ have hin (i : Small) : store live saved signal result aux (ports bank flag i) = ISA.bank pub persist rs [] i := by
+ cases h : liveSlot flag i with
+ | none =>
+ simp only [ports,h,store,hbase]
+ cases i with
+ | reg j => exact congrArg wordBits (hsame j h).symm
+ | pub | persistent | work | logPort => rfl
+ | some j =>
+ obtain ⟨i,rfl,hj,hsmall⟩ := liveSlot_info h
+ let ix : Fin 8 := ⟨i.val,by omega⟩
+ rw [ports,h]
+ change live j = wordBits (rs i)
+ rw [hlive i j h ix rfl, show i = Code.inReg capacity ix from Fin.ext rfl]
+ exact congrArg wordBits (replace_at base env ix).symm
+ have hout (i : Small) : store live saved signal result final (ports bank flag i) = ISA.bank pub persist out [] i := by
+ cases h : liveSlot flag i with
+ | none =>
+ simp only [ports,h,store,hfinal]
+ cases i with
+ | reg j =>
+ apply congrArg wordBits
+ by_cases hi : j.val < 8
+ · let ix : Fin 8 := ⟨j.val,hi⟩
+ have hj : j = Code.inReg capacity ix := Fin.ext rfl
+ rw [show cleaned j = base j from ite_eq_left hi, ← hsame j h, hj, hkeep ix]
+ · exact ite_eq_right hi
+ | pub | persistent | work | logPort => rfl
+ | some j =>
+ obtain ⟨i,rfl,hj,hsmall⟩ := liveSlot_info h
+ let ix : Fin 8 := ⟨i.val,by omega⟩
+ have eq : i = Code.inReg capacity ix := Fin.ext rfl
+ have hv := hin (.reg i)
+ simp only [ports,h,store,ISA.bank] at hv ⊢
+ rw [eq, hkeep ix, ← eq, ← hv]
+ refine ⟨t,ht,final,⟨cleaned,persist,?_,?_,hfinal⟩,?_,?_,?_,⟩
+ · rw [show cleaned (Code.inReg capacity 6) = _ from keep_at base out 6, hzero]
+ · rw [show cleaned (Code.inReg capacity 7) = _ from keep_at base out 7, hrows]
+ · apply FiniteRoutine.runs_onPorts_framed _ (ports_injective bank flag) hrun hin hout
+ intro l hl
+ cases l with
+ | frame f => cases f <;> rfl
+ | condition | result => rfl
+ | aux k =>
+ change final k = aux k
+ by_cases h : ∃ i, bank i = k
+ · obtain ⟨i,rfl⟩ := h
+ cases ha : liveSlot flag i with
+ | none => exact (hl i (by simp [ports, ha])).elim
+ | some j =>
+ obtain ⟨i,rfl,hj,hsmall⟩ := liveSlot_info ha
+ rw [hfinal,hbase]
+ apply congrArg wordBits
+ exact ite_eq_left (by omega)
+ · exact installStacks_outside _ _ (not_exists.mp h)
+ · intro i
+ rw [hfinal]
+ change wordBits (cleaned (Code.outReg capacity i)) = wordBits _
+ apply congrArg wordBits
+ have ho : ¬(Code.outReg capacity i).val < 8 := by simp [Code.outReg]
+ rw [show cleaned (Code.outReg capacity i) = _ from ite_eq_right ho]
+ apply Fin.ext
+ rw [Fin.val_ofNat, ← hval, Nat.mod_eq_of_lt (out _).isLt]
+ · exact fun _ hj => installStacks_outside _ _ hj
+
+end RankQuery.Stack.EngineAlias
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackBorrow.lean b/lean/OAI/Computability/VPVNP/RankQueryStackBorrow.lean
new file mode 100644
index 0000000000..90f8b6376a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackBorrow.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.EvaluatorDigitCallbacks
+import OAI.Computability.VPVNP.RankQueryStackEngineSpec
+
+/-!
+# The product-loop counter test in the Schur controller
+
+A zero counter is consumed and yields a true completion flag. A positive
+counter loses one, keeps its width, and yields a false completion flag.
+The control scans the low zero bits only and reuses one empty scratch stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine.Borrow
+
+open RAMTape UniversalCountStack TapeWord
+
+/-- Counter, borrow scratch stack and completion flag used by the binary decrement routine. -/
+inductive Port where | counter | scratch | flag deriving DecidableEq
+instance : Fintype Port := derive_fintype% _
+
+/-- Control phases for scanning low bits, resolving a borrow and reporting whether the counter
+was exhausted. -/
+inductive Phase where
+ | scan | save | lower | restore | raise | discard | signal (finished : Bool)
+ deriving DecidableEq, Fintype
+
+/-- Decrement a positive little-endian counter by borrowing through its low zero bits, or
+signal completion when the counter is zero. -/
+def body : Routine Port Phase where
+ entry := .scan
+ code
+ | .scan => .pop .counter fun b => some (b.elim .discard fun d => if d then .lower else .save)
+ | .save => .push .scratch true (some .scan)
+ | .lower => .push .counter false (some .restore)
+ | .restore => .pop .scratch fun b => some (if b.isSome then .raise else .signal false)
+ | .raise => .push .counter true (some .restore)
+ | .discard => .pop .scratch fun b => some (if b.isSome then .discard else .signal true)
+ | .signal b => .push .flag b none
+
+/-- Assign the counter bits, scratch contents and flag bits to their three respective ports. -/
+def bank (counter scratch flag : List Bool) : Stacks Port
+ | .counter => counter | .scratch => scratch | .flag => flag
+
+private theorem update_bank (x t f y : List Bool) (k : Port) :
+ Function.update (bank x t f) k y = match k with
+ | .counter => bank y t f | .scratch => bank x y f | .flag => bank x t y := by
+ funext j; cases k <;> cases j <;> rfl
+
+local macro "borrow_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [bank, update_bank, List.head?_cons, List.head?_nil, List.tail_cons, List.tail_nil,
+ Option.elim_none, Option.elim_some, Option.isSome_none, Option.isSome_some,
+ Bool.false_eq_true, ite_false, ite_true])
+
+private theorem move_true (l : ℕ) (xs : List Bool) :
+ List.replicate l true ++ true :: xs = true :: (List.replicate l true ++ xs) := by
+ induction l with
+ | zero => rfl
+ | succ l ih => simp only [List.replicate_succ, List.cons_append, ih]
+
+private theorem scan (l : ℕ) (tail t : List Bool) :
+ StackRuns body.standalone (2*l) (some .scan) (bank (List.replicate l false ++ tail) t [])
+ (some .scan) (bank tail (List.replicate l true ++ t) []) := by
+ induction l generalizing t with
+ | zero => exact .nil ..
+ | succ l ih =>
+ simp only [Nat.mul_succ, List.replicate_succ, List.cons_append]
+ borrow_step
+ borrow_step
+ simpa only [move_true] using ih (true :: t)
+
+private theorem restore (l : ℕ) (x : List Bool) :
+ StackRuns body.standalone (2*l+2) (some .restore) (bank x (List.replicate l true) [])
+ none (bank (List.replicate l true ++ x) [] [false]) := by
+ induction l generalizing x with
+ | zero => borrow_step; borrow_step; exact .nil ..
+ | succ l ih =>
+ simp only [Nat.mul_succ, List.replicate_succ, List.cons_append]
+ borrow_step
+ borrow_step
+ simpa only [move_true] using ih (true :: x)
+
+private theorem discard (l : ℕ) : StackRuns body.standalone (l+2) (some .discard)
+ (bank [] (List.replicate l true) []) none (bank [] [] [true]) := by
+ induction l with
+ | zero => borrow_step; borrow_step; exact .nil ..
+ | succ l ih =>
+ simp only [List.replicate_succ]
+ borrow_step
+ exact ih
+
+theorem zero_runs (w : ℕ) : body.Runs (3*w+3) (bank (digits w 0) [] []) (bank [] [] [true]) := by
+ rw [digits_zero]
+ have first := scan w [] []
+ simp only [List.append_nil] at first
+ have rest : StackRuns body.standalone ((w+2)+1) (some .scan) (bank [] (List.replicate w true) [])
+ none (bank [] [] [true]) := by borrow_step; exact discard w
+ convert first.trans rest using 1 <;> first | rfl | omega
+
+theorem succ_runs (w k : ℕ) (h : k+1 < 2^w) :
+ ∃ t ≤ 4*w+4, body.Runs t (bank (digits w (k+1)) [] []) (bank (digits w k) [] [false]) := by
+ have hv : value (digits w (k+1)) = k+1 := by simp [Nat.mod_eq_of_lt h]
+ obtain ⟨l,tail,eq⟩ := EvaluatorDigitCallbacks.split_positive (digits w (k+1)) (by omega)
+ have hl : l+tail.length+1 = w := by
+ have hlen := congrArg List.length eq
+ simp at hlen; omega
+ have smaller : List.replicate l true ++ false :: tail = digits w k := by
+ apply eq_of_length_value (by simp; omega)
+ have := EvaluatorDigitRepeat.value_decrement l tail
+ rw [← eq, hv] at this
+ simp [Nat.mod_eq_of_lt (by omega : k < 2^w)]
+ omega
+ have first := scan l (true :: tail) []
+ simp only [List.append_nil] at first
+ have middle : StackRuns body.standalone 2 (some .scan) (bank (true :: tail) (List.replicate l true) [])
+ (some .restore) (bank (false :: tail) (List.replicate l true) []) := by
+ borrow_step; borrow_step; exact .nil ..
+ have final := (first.trans middle).trans (restore l (false :: tail))
+ rw [← eq, smaller] at final
+ exact ⟨_, by omega, final⟩
+
+end RankQuery.Stack.Engine.Borrow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackBounds.lean b/lean/OAI/Computability/VPVNP/RankQueryStackBounds.lean
new file mode 100644
index 0000000000..58522caf69
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackBounds.lean
@@ -0,0 +1,186 @@
+import OAI.Computability.VPVNP.RankQueryStackSchur
+import OAI.Computability.VPVNP.DeterminantQueries
+
+/-!
+# Time and live stack depth for determinant coefficient queries
+
+The product and the matrix-power phases contribute their two binary logarithms
+to the stack cap. Three intervening query tags connect a Schur factor to its
+power query. The loop bounds include matrix indices and both coefficient
+degrees.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+variable {Q R : Type*}
+
+namespace Node
+
+/-- Every child of a branch has depth strictly below the given limit. Leaves satisfy the bound
+unconditionally. -/
+def Below (d : Q → ℕ) (limit : ℕ) : Node Q R → Prop
+ | .leaf _ => True
+ | .branch _ f => ∀ i, d (f i).1 < limit ∧ d (f i).2 < limit
+
+/-- Number of product terms in a branch, with width zero for a leaf. -/
+def width : Node Q R → ℕ
+ | .leaf _ => 0
+ | .branch t _ => t
+
+theorem below_box {d : Q → ℕ} {limit n m : ℕ} {f : Fin n → Fin m → Q × Q}
+ (h : ∀ i j, d (f i j).1 < limit ∧ d (f i j).2 < limit) :
+ (box (R := R) n m f).Below d limit := fun k => h (finProdFinEquiv.symm k).1 (finProdFinEquiv.symm k).2
+
+theorem descends_iff (nodes : Q → Node Q R) (d : Q → ℕ) :
+ (program nodes).Descends d ↔ ∀ q, (nodes q).Below d (d q) := by
+ constructor
+ · intro H q
+ cases h : nodes q with
+ | leaf => trivial
+ | branch t f =>
+ intro i
+ have he : (program nodes).describe q = .inr t := by simp [program, h, describe]
+ simpa only [program, h, children, dite_eq_left i.isLt] using H q t he i.val i.isLt
+ · intro H q t he i hi
+ specialize H q
+ change (nodes q).describe = .inr t at he
+ cases h : nodes q with
+ | leaf r => simp [h, describe] at he
+ | branch s f =>
+ have hs : s = t := by simpa [h, describe] using he
+ subst t
+ rw [h] at H
+ simpa only [program, h, children, dite_eq_left hi] using H ⟨i,hi⟩
+
+theorem arity_iff (nodes : Q → Node Q R) (b : ℕ) :
+ (program nodes).ArityLE b ↔ ∀ q, (nodes q).width ≤ b := by
+ constructor
+ · intro H q
+ cases h : nodes q with
+ | leaf => exact Nat.zero_le _
+ | branch t f => exact H q t (by simp [program, h, describe])
+ · intro H q t he
+ specialize H q
+ cases h : nodes q with
+ | leaf r => simp [program, h, describe] at he
+ | branch s f =>
+ have ht : s = t := by simpa [program, h, describe] using he
+ simpa [h, width, ht] using H
+
+end Node
+
+namespace SchurKey
+
+variable {n U Z : ℕ} {F : Type*} [CommRing F]
+
+/-- Depth measure on Schur query keys used to bound the stack of recursive calls. -/
+def depth : K n U Z → ℕ
+ | .product d _ _ _ => Nat.clog 2 U + 4 + d.val
+ | .factor .. => Nat.clog 2 U + 3
+ | .outer .. => Nat.clog 2 U + 2
+ | .inner .. => Nat.clog 2 U + 1
+ | .power _ q => q.depth
+ | .scalar .. | .one => 0
+
+/-- Uniform bound on the number of child pairs in any Schur query with parameters `n`, `U` and
+`Z`. -/
+def arityBound (n U Z : ℕ) := 1 + n * n + n * (Z+1) + (U+1)*(Z+1) + (Z+1)
+
+private theorem below (entry : Entry n F) (q : K n U Z) :
+ (q.node entry).Below depth q.depth := by
+ cases q with
+ | product d b u z =>
+ simp only [node]
+ split_ifs with hd hc
+ · intro _
+ simp [depth, hd]
+ · trivial
+ · apply Node.below_box
+ intro s t
+ simp only [depth, predBy]
+ omega
+ | factor a u z =>
+ simp only [node]
+ split_ifs
+ · trivial
+ · trivial
+ · apply Node.below_box
+ intro i j
+ simp [depth]
+ | outer a h i j z =>
+ intro d
+ simp [depth]
+ | inner a h i j z =>
+ intro d
+ have hlt := Nat.clog_mono_right 2 (Nat.lt_succ_iff.mp h.isLt)
+ simp only [depth, PowerKey.depth]
+ omega
+ | power a q =>
+ have hp := (Node.descends_iff _ _).mp (PowerKey.descends (H := U) (Z := Z) (tailEntry entry a)) q
+ change (q.node (tailEntry entry a)).Below PowerKey.depth q.depth at hp
+ change ((q.node (tailEntry entry a)).map (.power a)).Below depth q.depth
+ cases hn : q.node (tailEntry entry a) <;> rw [hn] at hp <;> exact hp
+ | scalar | one => trivial
+
+theorem descends (entry : Entry n F) : (program (U := U) (Z := Z) entry).Descends depth :=
+ (Node.descends_iff _ _).mpr (below entry)
+
+private theorem width_le (entry : Entry n F) (q : K n U Z) :
+ (q.node entry).width ≤ arityBound n U Z := by
+ unfold arityBound
+ cases q with
+ | product d b u z =>
+ have hb : (u.val + 1) * (z.val + 1) ≤ (U+1)*(Z+1) := Nat.mul_le_mul u.isLt z.isLt
+ simp only [node]
+ split_ifs <;> simp only [Node.width, Node.box] <;> omega
+ | factor a u z =>
+ have hb := Nat.mul_le_mul (show n-a.val-1 ≤ n by omega) (show n-a.val-1 ≤ n by omega)
+ simp only [node]
+ split_ifs <;> simp only [Node.width, Node.box] <;> omega
+ | outer a h i j z => change z.val + 1 ≤ _; have := z.isLt; omega
+ | inner a h i j z => change z.val + 1 ≤ _; have := z.isLt; omega
+ | power a q =>
+ have hp := (Node.arity_iff _ _).mp (PowerKey.arity (H := U) (Z := Z) (tailEntry entry a)) q
+ change (q.node (tailEntry entry a)).width ≤ (n-a.val-1)*(Z+1) at hp
+ have hb := Nat.mul_le_mul_right (Z+1) (show n-a.val-1 ≤ n by omega)
+ change ((q.node (tailEntry entry a)).map (SchurKey.power a)).width ≤ _
+ cases hn : q.node (tailEntry entry a) <;> rw [hn] at hp <;> simp only [Node.map, Node.width] at hp ⊢ <;> omega
+ | scalar | one => exact Nat.zero_le _
+
+theorem arity (entry : Entry n F) : (program (U := U) (Z := Z) entry).ArityLE (arityBound n U Z) :=
+ (Node.arity_iff _ _).mpr (width_le entry)
+
+/-- The complete Schur stack machine computes the specified coefficient,
+with a bound on the length of every intermediate continuation. -/
+theorem run (M : Matrix (Fin n) (Fin n) (Polynomial F)) (entry : Entry n F)
+ (he : ∀ i j z, entry i j z = (M i j).coeff z) (u : Limit U) (z : Limit Z) :
+ let d := Nat.clog 2 U + 4 + Nat.clog 2 n
+ ∃ t ≤ (5 + 6 * arityBound n U Z) ^ (d+1), (program entry).Runs d t (.enter (root u z), [])
+ (.returned ((M.charpolyRev.coeff u.val).coeff z.val), []) := by
+ have h := Program.run_bounded (program entry) (value entry) depth _ (realizes entry)
+ (descends entry) (arity entry) (depth (root u z)) (root u z) le_rfl []
+ have hd : depth (root (n := n) u z) = Nat.clog 2 U + 4 + Nat.clog 2 n := rfl
+ simpa only [List.length_nil, Nat.zero_add, value_root, determinantQuery_eq M entry he, hd] using h
+
+/-- A rank scan queries the same machine with scalar reads in the input
+matrix. The weighted Gram coefficient requires at most two such reads. -/
+theorem rankCoefficientRun {F : Type*} [Field F] {m : ℕ} (M : Matrix (Fin n) (Fin m) F)
+ (u : Limit n) (z : Limit ((n+m)*n)) :
+ let entry := weightedGramEntryCoeff M
+ let d := Nat.clog 2 n + 4 + Nat.clog 2 n
+ ∃ t ≤ (5 + 6 * arityBound n n ((n+m)*n)) ^ (d+1),
+ (program entry).Runs d t (.enter (root u z), [])
+ (.returned (((rankPolynomial M).coeff u.val).coeff z.val), []) :=
+ run (weightedGram M) _ (weightedGramEntryCoeff_eq M) u z
+
+end SchurKey
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackCodec.lean b/lean/OAI/Computability/VPVNP/RankQueryStackCodec.lean
new file mode 100644
index 0000000000..304ba0aaee
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackCodec.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.RankQueryStackWords
+import OAI.Computability.VPVNP.RankQueryStackField
+import OAI.Computability.VPVNP.UniversalCountStackBounds
+
+/-!
+# Encoding a Schur continuation as ten registers
+
+The direction distinguishes waiting for the left or right operand. Six registers
+hold the parent query, followed by the remaining summand index and two packed
+extension-field scalars. The unused left operand in a waiting-left frame is
+zero. All numeric registers are little-endian words of a common width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+open UniversalCountStack
+
+namespace SchurKey
+
+variable {n U Z : ℕ}
+
+private def bounded (m a : ℕ) : Option (Fin m) := if h : a < m then some ⟨a, h⟩ else none
+
+private theorem bounded_val {m : ℕ} (a : Fin m) : bounded m a.val = some a := by simp [bounded]
+
+/-- Decode the tag, checking all index, block and degree bounds. -/
+def readWords (a : Fin 6 → ℕ) : Option (K n U Z) := do
+ match a 0 with
+ | 0 =>
+ let d ← bounded (Nat.clog 2 n + 1) (a 1)
+ let u ← bounded (U+1) (a 4)
+ let z ← bounded (Z+1) (a 5)
+ if h : a 2 + a 3 ≤ n then return .product d ⟨a 2,a 3,h⟩ u z else none
+ | 1 => return .factor (← bounded n (a 1)) (← bounded (U+1) (a 4)) (← bounded (Z+1) (a 5))
+ | 2 | 3 | 4 =>
+ let v ← bounded n (a 1)
+ let i ← bounded (n-v.val-1) (a 2)
+ let j ← bounded (n-v.val-1) (a 3)
+ let h ← bounded (U+1) (a 4)
+ let z ← bounded (Z+1) (a 5)
+ return if a 0 = 2 then .outer v h i j z else if a 0 = 3 then .inner v h i j z
+ else .power v ⟨h,i,j,z⟩
+ | 5 => return .scalar (decide (a 3 = 1)) (← bounded n (a 1)) (← bounded n (a 2)) (← bounded (Z+1) (a 5))
+ | 6 => return .one
+ | _ => none
+
+theorem readWords_words (q : K n U Z) : readWords q.words = some q := by
+ cases q with
+ | product d b u z => cases b; simp [readWords, words, bounded_val, *]
+ | factor | outer | inner | one => simp [readWords, words, bounded_val]
+ | power a q => cases q; simp [readWords, words, bounded_val]
+ | scalar b i j z => cases b <;> simp [readWords, words, bounded_val]
+
+theorem words_injective : Function.Injective (words (n := n) (U := U) (Z := Z)) := by
+ intro a b h
+ simpa only [readWords_words, Option.some.injEq] using congrArg (readWords (n := n) (U := U) (Z := Z)) h
+
+/-- One uniform bound on all six query registers, including the empty matrix. -/
+theorem words_le (q : K n U Z) (idx : Fin 6) : q.words idx ≤ n + U + Z + 6 := by
+ have hd : Nat.clog 2 n ≤ n := Nat.clog_le_of_le_pow (Nat.lt_pow_self (by decide : 1 < 2)).le
+ cases q with
+ | product d b u z =>
+ have := d.isLt; have := b.fits; have := u.isLt; have := z.isLt
+ fin_cases idx <;> simp [words] <;> omega
+ | factor a u z =>
+ have := a.isLt; have := u.isLt; have := z.isLt
+ fin_cases idx <;> simp [words] <;> omega
+ | outer a h i j z | inner a h i j z =>
+ have := a.isLt; have := h.isLt; have := i.isLt; have := j.isLt; have := z.isLt
+ fin_cases idx <;> simp [words] <;> omega
+ | power a q =>
+ have := a.isLt; have := q.exponent.isLt; have := q.row.isLt; have := q.col.isLt; have := q.degree.isLt
+ fin_cases idx <;> simp [words] <;> omega
+ | scalar b x y z =>
+ have := x.isLt; have := y.isLt; have := z.isLt
+ cases b <;> fin_cases idx <;> simp [words] <;> omega
+ | one => fin_cases idx <;> simp [words]
+
+end SchurKey
+
+namespace Frame
+
+variable {n U Z p e : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- Evaluator frame specialized to a Schur query key and an encoded extension-field scalar. -/
+abbrev SchurFrame (n U Z : ℕ) (c : SliceArithmetic.Vector p e) :=
+ Frame (SchurKey n U Z) (Scalar c)
+
+/-- Fields in order: direction, query, remaining summands, accumulator, saved left operand. -/
+def words : SchurFrame n U Z c → Fin 10 → ℕ
+ | .left q k a => Fin.cons 0 (Fin.append q.words ![k, a.code.val, 0])
+ | .right q k a v => Fin.cons 1 (Fin.append q.words ![k, a.code.val, v.code.val])
+
+/-- Remaining product-scan index saved in either kind of Schur frame. -/
+def remaining : SchurFrame n U Z c → ℕ
+ | .left _ k _ | .right _ k _ _ => k
+
+/-- Width conditions for the exact scalar and control words, with a separate
+bound for the summand index supplied by the arity estimate. -/
+theorem words_fit (f : SchurFrame n U Z c) (width : ℕ)
+ (hq : n + U + Z + 6 < 2^width) (hk : f.remaining < 2^width) (hs : p^e ≤ 2^width) :
+ ∀ i, f.words i < 2^width := by
+ intro i
+ cases f with
+ | left q k a =>
+ refine Fin.cases (by change 0 < 2^width; exact pow_pos (by decide) _) (fun j => ?_) i
+ refine Fin.addCases (motive := fun i => Fin.append q.words ![k, a.code.val, 0] i < 2^width) (fun x : Fin 6 => ?_) (fun x : Fin 3 => ?_) j
+ · simpa [words] using (SchurKey.words_le q x).trans_lt hq
+ · have ha := a.code.isLt
+ change k < 2^width at hk
+ rw [Fin.append_right]
+ fin_cases x <;> simp <;> omega
+ | right q k a b =>
+ refine Fin.cases (by change 1 < 2^width; omega) (fun j => ?_) i
+ refine Fin.addCases (motive := fun i => Fin.append q.words ![k, a.code.val, b.code.val] i < 2^width) (fun x : Fin 6 => ?_) (fun x : Fin 3 => ?_) j
+ · simpa [words] using (SchurKey.words_le q x).trans_lt hq
+ · have ha := a.code.isLt; have hb := b.code.isLt
+ change k < 2^width at hk
+ rw [Fin.append_right]
+ fin_cases x <;> simp <;> omega
+
+/-- All registers use the same width; the tag occupies a register too. -/
+def bits (width : ℕ) (f : SchurFrame n U Z c) (i : Fin 10) : List Bool :=
+ digits width (f.words i)
+
+theorem bits_value (width : ℕ) (f : SchurFrame n U Z c) (i : Fin 10) (h : f.words i < 2^width) :
+ TapeWord.value (f.bits width i) = f.words i := by rw [bits, value_digits, Nat.mod_eq_of_lt h]
+
+theorem words_injective : Function.Injective (words (n := n) (U := U) (Z := Z) (c := c)) := by
+ intro a b h
+ have tag := congrFun h 0
+ have key : ∀ i : Fin 6, a.words (Fin.castAdd 3 i).succ = b.words (Fin.castAdd 3 i).succ := fun i => congrFun h _
+ have tail : ∀ j : Fin 3, a.words (Fin.natAdd 6 j).succ = b.words (Fin.natAdd 6 j).succ := fun j => congrFun h _
+ cases a <;> cases b <;> simp only [words, Fin.cons_zero, Fin.cons_succ, Fin.append_left, Fin.append_right] at tag key tail
+ all_goals first | contradiction | skip
+ all_goals
+ have eqK := SchurKey.words_injective (funext key)
+ have h0 := tail 0
+ have h1 := tail 1
+ have h2 := tail 2
+ simp at h0 h1 h2
+ cases eqK; cases h0
+ have eqScalar (x y : Scalar c) (h : x.code.val = y.code.val) : x = y := by
+ cases x; cases y; congr 1; exact Fin.ext h
+ congr 1 <;> first | exact eqScalar _ _ h1 | exact eqScalar _ _ h2
+
+theorem bits_injective_on (width : ℕ) {a b : SchurFrame n U Z c}
+ (ha : ∀ i, a.words i < 2^width) (hb : ∀ i, b.words i < 2^width) (h : a.bits width = b.bits width) : a = b := by
+ apply words_injective
+ funext i
+ rw [← bits_value width a i (ha i), ← bits_value width b i (hb i), h]
+
+end Frame
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackCodegen.lean b/lean/OAI/Computability/VPVNP/RankQueryStackCodegen.lean
new file mode 100644
index 0000000000..9c4bb2dc2e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackCodegen.lean
@@ -0,0 +1,205 @@
+import OAI.Computability.VPVNP.RankQueryStackExpressions
+
+/-!
+# Fixed bit-stack compilation of Schur descriptor and child requests
+
+A decision tree computes each of six result words from the immutable eight
+inputs. Each test compiles its two expressions to separate scratch intervals.
+The same scratch bank is reused for the selected subtree and the remaining
+output words.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Dispatch
+
+open BurstRAM PrivateRAM RAMTape
+
+namespace Code
+
+variable {r w : ℕ}
+
+/-- Scratch-register allowance for computing one output field, counting its leaf expressions
+and both sides of every test. -/
+def need (field : Fin 6) : Code → ℕ
+ | .emit f => (f field).nodes
+ | .test x y yes no => x.nodes+y.nodes+yes.need field+no.need field
+
+/-- Sum of expression weights used to bound the word width for one field of the dispatch tree. -/
+def bits (field : Fin 6) : Code → ℕ
+ | .emit f => (f field).weight
+ | .test x y yes no => x.weight+y.weight+yes.bits field+no.bits field
+
+/-- Compile the tests and leaves that compute a single output field into register instructions. -/
+def fieldCode (arg : Fin 8 → Fin r) (out : Fin r) (slot : ℕ → Fin r) (field : Fin 6) : Code → RegCode r
+ | .emit f => .seq ((f field).compile arg slot 0) (.copy out (slot 0))
+ | .test x y yes no =>
+ .seq (x.compile arg slot 0) <| .seq (y.compile arg slot x.nodes) <|
+ .test (slot 0) (slot x.nodes) (yes.fieldCode arg out slot field) (no.fieldCode arg out slot field)
+
+theorem fieldCode_preserves (c : Code) (arg : Fin 8 → Fin r) (out : Fin r) (slot : ℕ → Fin r)
+ (field : Fin 6) (rs : Regs r w) (j : Fin r) (hout : j ≠ out)
+ (hs : ∀ i < c.need field, slot i ≠ j) : (c.fieldCode arg out slot field).exec rs j = rs j := by
+ induction c generalizing rs with
+ | emit f =>
+ simp only [fieldCode, RegCode.exec, Function.update_of_ne hout]
+ apply Expr.preserves
+ intro i _ hi
+ exact hs i (by simpa [need] using hi)
+ | test x y yes no ihy ihn =>
+ simp only [fieldCode, RegCode.exec]
+ have hsx : ∀ i, 0 ≤ i → i < 0+x.nodes → slot i ≠ j := fun i _ h => hs _ (by simp only [need]; omega)
+ have hsy : ∀ i, x.nodes ≤ i → i < x.nodes+y.nodes → slot i ≠ j := fun i _ h => hs _ (by simp only [need]; omega)
+ have hy : ∀ i < yes.need field, slot i ≠ j := fun i h => hs i (by simp only [need]; omega)
+ have hn : ∀ i < no.need field, slot i ≠ j := fun i h => hs i (by simp only [need]; omega)
+ split_ifs <;> first | rw [ihy _ hy] | rw [ihn _ hn]
+ all_goals rw [y.preserves _ _ _ _ _ hsy, x.preserves _ _ _ _ _ hsx]
+
+theorem fieldCode_correct (c : Code) (arg : Fin 8 → Fin r) (out : Fin r) (slot : ℕ → Fin r)
+ (field : Fin 6) (p cap : ℕ) (env : Fin 8 → ℕ) (rs : Regs r w)
+ (he : ∀ i, env i < 2^p) (hr : ∀ i, (rs (arg i)).val = env i)
+ (hn : c.need field ≤ cap) (hb : (p+1)*c.bits field ≤ w)
+ (hinj : ∀ i < cap, ∀ j < cap, slot i = slot j → i = j)
+ (hsep : ∀ i < cap, ∀ j, slot i ≠ arg j) :
+ ((c.fieldCode arg out slot field).exec rs out).val = c.eval env field := by
+ induction c generalizing rs with
+ | emit f =>
+ simp only [fieldCode, RegCode.exec, Function.update_self, Code.eval]
+ exact (f field).compile_correct env arg slot cap 0 rs
+ ((f field).fits_mono ((f field).fits_weight p env he) hb) hr (by simpa [need] using hn) hinj hsep
+ | test x y yes no ihy ihn =>
+ let xs := (x.compile arg slot 0).exec rs
+ let ys := (y.compile arg slot x.nodes).exec xs
+ have hsize : x.nodes+y.nodes+yes.need field+no.need field ≤ cap := hn
+ have hwidth : (p+1)*x.weight+(p+1)*y.weight+(p+1)*yes.bits field+(p+1)*no.bits field ≤ w := by
+ simpa only [bits, Nat.mul_add] using hb
+ have hx := x.compile_correct env arg slot cap 0 rs
+ (x.fits_mono (x.fits_weight p env he) (by omega)) hr (by omega) hinj hsep
+ have hxs (j : Fin 8) : (xs (arg j)).val = env j := by
+ change ((x.compile arg slot 0).exec rs (arg j)).val = _
+ rw [x.preserves _ _ _ _ _ (fun i _ hi => hsep i (by omega) j), hr]
+ have hy := y.compile_correct env arg slot cap x.nodes xs
+ (y.fits_mono (y.fits_weight p env he) (by omega)) hxs (by omega) hinj hsep
+ have hys (j : Fin 8) : (ys (arg j)).val = env j := by
+ change ((y.compile arg slot x.nodes).exec xs (arg j)).val = _
+ rw [y.preserves _ _ _ _ _ (fun i _ hi => hsep i (by omega) j), hxs]
+ have hkeep : ys (slot 0) = xs (slot 0) := by
+ apply y.preserves
+ intro i hi hc heq
+ have := x.nodes_pos
+ have := hinj i (by omega) 0 (by omega) heq
+ omega
+ have htest : ys (slot 0) = ys (slot x.nodes) ↔ x.eval env = y.eval env := by
+ rw [Fin.ext_iff, hkeep, show (xs (slot 0)).val = _ from hx, show (ys (slot x.nodes)).val = _ from hy]
+ change ((if ys (slot 0) = ys (slot x.nodes) then (yes.fieldCode arg out slot field).exec ys
+ else (no.fieldCode arg out slot field).exec ys) out).val = _
+ rw [Code.eval]
+ by_cases hh : x.eval env = y.eval env
+ · simp only [ite_eq_left hh, ite_eq_left (htest.mpr hh)]
+ exact ihy ys hys (by omega) (by omega)
+ · simp only [ite_eq_right hh, ite_eq_right (fun h => hh (htest.mp h))]
+ exact ihn ys hys (by omega) (by omega)
+
+/-- Total scratch allowance obtained by summing the register requirements of all six output
+fields. -/
+def scratch (c : Code) := ∑ i : Fin 6, c.need i
+/-- Sum of the six output fields' width factors for the compiled dispatcher. -/
+def wordFactor (c : Code) := ∑ i : Fin 6, c.bits i
+
+/-- Inputs occupy slots zero through seven, and the result words occupy slots
+eight through thirteen. The scratch interval starts at fourteen. -/
+def inReg (cap : ℕ) (i : Fin 8) : Fin (14+cap) := ⟨i.val, by omega⟩
+/-- Physical output register for field `i`, following the eight input registers. -/
+def outReg (cap : ℕ) (i : Fin 6) : Fin (14+cap) := ⟨8+i.val, by omega⟩
+/-- Scratch register at offset `i` from the end of the fourteen input and output registers,
+indexed modulo the bank size. -/
+def workReg (cap : ℕ) (i : ℕ) : Fin (14+cap) := Fin.ofNat _ (14+i)
+
+private theorem workReg_val {cap i : ℕ} (h : i < cap) : (workReg cap i).val = 14+i :=
+ Nat.mod_eq_of_lt (by omega)
+
+private theorem input_separate {cap i : ℕ} (h : i < cap) (j : Fin 8) : workReg cap i ≠ inReg cap j := by
+ intro he
+ have := congrArg Fin.val he
+ simp only [workReg_val h, inReg] at this
+ omega
+
+private theorem output_separate {cap i : ℕ} (h : i < cap) (j : Fin 6) : workReg cap i ≠ outReg cap j := by
+ intro he
+ have := congrArg Fin.val he
+ simp only [workReg_val h, outReg] at this
+ omega
+
+private theorem in_ne_out (cap : ℕ) (i : Fin 8) (j : Fin 6) : inReg cap i ≠ outReg cap j := by
+ intro he
+ have := congrArg Fin.val he
+ simp only [inReg,outReg] at this
+ omega
+
+private theorem out_inj (cap : ℕ) : Function.Injective (outReg cap) := by
+ intro i j he
+ apply Fin.ext
+ exact Nat.add_left_cancel (congrArg Fin.val he)
+
+/-- Reuse one scratch bank while evaluating a finite sequence of output fields. -/
+def emitFields (c : Code) (cap : ℕ) : List (Fin 6) → RegCode (14+cap)
+ | [] => .ret
+ | i::is => .seq (c.fieldCode (inReg cap) (outReg cap i) (workReg cap) i) (emitFields c cap is)
+
+private theorem emitFields_correct (c : Code) (cap p : ℕ) (is : List (Fin 6)) (rs : Regs (14+cap) w)
+ (env : Fin 8 → ℕ) (hcap : c.scratch ≤ cap) (hw : (p+1)*c.wordFactor ≤ w)
+ (he : ∀ i, env i < 2^p) (hr : ∀ i, (rs (inReg cap i)).val = env i) :
+ let fin := (c.emitFields cap is).exec rs
+ (∀ i, fin (inReg cap i) = rs (inReg cap i)) ∧
+ ∀ i, (fin (outReg cap i)).val = if i ∈ is then c.eval env i else (rs (outReg cap i)).val := by
+ induction is generalizing rs with
+ | nil => simp [emitFields, RegCode.exec]
+ | cons j js ih =>
+ let body := c.fieldCode (inReg cap) (outReg cap j) (workReg cap) j
+ let middle := body.exec rs
+ have hneed : c.need j ≤ cap := (Finset.single_le_sum (f := c.need) (fun _ _ => Nat.zero_le _) (Finset.mem_univ j)).trans hcap
+ have hbits := Finset.single_le_sum (f := c.bits) (fun _ _ => Nat.zero_le _) (Finset.mem_univ j)
+ have hinput (i : Fin 8) : middle (inReg cap i) = rs (inReg cap i) :=
+ c.fieldCode_preserves _ _ _ _ _ _ (in_ne_out cap i j) (fun _ hi => input_separate (hi.trans_le hneed) i)
+ have hval : (middle (outReg cap j)).val = c.eval env j :=
+ c.fieldCode_correct _ _ _ _ p cap _ _ he hr hneed ((Nat.mul_le_mul_left _ hbits).trans hw)
+ (fun i hi j hj h => Nat.add_left_cancel (by simpa only [workReg_val hi,workReg_val hj] using congrArg Fin.val h))
+ (fun _ hi j => input_separate hi j)
+ obtain ⟨hinputs, houtputs⟩ := ih middle (fun i => (congrArg Fin.val (hinput i)).trans (hr i))
+ refine ⟨fun i => (hinputs i).trans (hinput i), fun i => ?_⟩
+ change (((c.emitFields cap js).exec middle) (outReg cap i)).val = _
+ rw [houtputs]
+ by_cases heq : i = j
+ · subst i
+ simp [hval]
+ · have hkeep : middle (outReg cap i) = rs (outReg cap i) :=
+ c.fieldCode_preserves _ _ _ _ _ _ ((out_inj cap).ne heq) (fun _ hi => output_separate (hi.trans_le hneed) i)
+ simp [heq, hkeep]
+
+/-- Compile the dispatch tree to a physical machine that emits all six output fields. -/
+def physical (c : Code) (cap : ℕ) : Machine (14+cap) := (c.emitFields cap (List.finRange 6)).compile
+
+/-- The fixed compiled bit-stack program returns all six output words, while
+preserving its eight input words. Its finite control and scratch count depend
+only on the syntax of the decision tree. -/
+theorem physical_runs (c : Code) (cap p : ℕ) (hcap : c.scratch ≤ cap)
+ (env : Fin 8 → ℕ) (rs : Regs (14+cap) w) (hw : (p+1)*c.wordFactor ≤ w)
+ (he : ∀ i, env i < 2^p) (hr : ∀ i, (rs (inReg cap i)).val = env i)
+ (pub : Fin 0 → Word w) (persistent : Word w) :
+ ∃ t ≤ (c.emitFields cap (List.finRange 6)).length * (100*(w+1)^2), ∃ out,
+ (c.physical cap).Runs t (ISA.bank pub persistent rs []) (ISA.bank pub persistent out []) ∧
+ (∀ i, out (inReg cap i) = rs (inReg cap i)) ∧ ∀ i, (out (outReg cap i)).val = c.eval env i := by
+ obtain ⟨t,ht,hrun⟩ := (c.emitFields cap (List.finRange 6)).compile_runs pub persistent rs
+ obtain ⟨hinputs,houtputs⟩ := c.emitFields_correct cap p (List.finRange 6) rs env hcap hw he hr
+ refine ⟨t,ht,_,hrun,hinputs,fun i => ?_⟩
+ simpa using houtputs i
+
+end Code
+
+end RankQuery.Stack.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackCursor.lean b/lean/OAI/Computability/VPVNP/RankQueryStackCursor.lean
new file mode 100644
index 0000000000..325ad4e21b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackCursor.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.RankQueryStackCodegen
+import OAI.Computability.VPVNP.DeterminantQueries
+
+/-!
+# Descending bidegree scan for rank
+
+The scan asks for one coefficient at a time and returns the first outer degree
+with a nonzero coefficient. One transition updates the two indices, or halts
+with the exact rank. Its fixed bit-stack code receives the zero-test flag
+from the scalar routine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+open Dispatch BurstRAM RAMTape
+
+/-- State of the descending coefficient search, recording a current rank and degree or the
+finished rank. -/
+inductive State where
+ | running (u z : ℕ)
+ | done (rank : ℕ)
+ deriving DecidableEq
+
+/-- Return the current rank for a nonzero coefficient. On zero, move to the previous degree or
+restart at degree `Z` for the previous rank. -/
+def advance (Z u z : ℕ) (zero : Bool) : State :=
+ if zero then
+ if z = 0 then if u = 0 then .done 0 else .running (u-1) Z
+ else .running u (z-1)
+ else .done u
+
+/-- Perform one coefficient test on a running cursor and keep a finished cursor at its recorded
+rank. -/
+def step (q : ℕ → ℕ → Bool) (Z : ℕ) : State → State
+ | .running u z => advance Z u z (q u z)
+ | .done r => .done r
+
+/-- Six-output dispatch tree implementing one transition of the descending rank cursor. -/
+def control : Code :=
+ let zero : Expr := .reg 0
+ let u : Expr := .reg 1
+ let z : Expr := .reg 2
+ let Z : Expr := .reg 3
+ .test zero 0 (.emit ![1,u,0,0,0,0]) <|
+ .test z 0 (.test u 0 (.emit ![1,0,0,0,0,0]) (.emit ![0,u-1,Z,0,0,0])) (.emit ![0,u,z-1,0,0,0])
+
+/-- Encode the zero-test result, current rank, current degree and degree limit in the cursor's
+eight input words. -/
+def input (Z u z : ℕ) (zero : Bool) : Fin 8 → ℕ := ![zero.toNat,u,z,Z,0,0,0,0]
+
+/-- Encode a running cursor or final rank as six output words with the status tag first. -/
+def State.words : State → Fin 6 → ℕ
+ | .running u z => ![0,u,z,0,0,0]
+ | .done r => ![1,r,0,0,0,0]
+
+theorem control_eq (Z u z : ℕ) (zero : Bool) :
+ control.eval (input Z u z zero) = (advance Z u z zero).words := by
+ cases zero <;> by_cases hz : z = 0 <;> by_cases hu : u = 0 <;>
+ funext i <;> fin_cases i <;>
+ simp [control, Code.eval, Expr.eval, eval_sub, input, advance, State.words, hz, hu]
+
+/-- Maximum of the first `n` values of a natural-valued stream, starting from zero. -/
+def peak (f : ℕ → ℕ) (n : ℕ) : ℕ := streamMaximum n fun i => f i.val
+
+theorem peak_succ (f : ℕ → ℕ) (n : ℕ) : peak f (n+1) = max (peak f n) (f n) := by
+ simp only [peak, streamMaximum, Fin.foldl_succ_last, Fin.val_castSucc, Fin.val_last]
+
+/-- Contribution of rank `u` from the first `count` degree tests, equal to `u` if any
+coefficient is nonzero. -/
+def row (q : ℕ → ℕ → Bool) (u : ℕ) (count : ℕ) := peak (fun z => if q u z then 0 else u) count
+
+/-- Largest candidate rank strictly below `u` for which the zero test fails at some degree from
+zero through `Z`, defaulting to zero. -/
+def below (q : ℕ → ℕ → Bool) (Z u : ℕ) := peak (fun i => row q i (Z+1)) u
+
+/-- Rank represented by the cursor, taking the maximum over the remaining search region or
+returning the finished value. -/
+def answer (q : ℕ → ℕ → Bool) (Z : ℕ) : State → ℕ
+ | .running u z => max (below q Z u) (row q u (z+1))
+ | .done r => r
+
+private theorem row_le (q : ℕ → ℕ → Bool) (u count : ℕ) : row q u count ≤ u :=
+ (streamMaximum_le_iff count u (fun i => if q u i.val then 0 else u)).mpr fun i => by split_ifs <;> omega
+
+private theorem below_le (q : ℕ → ℕ → Bool) (Z u : ℕ) : below q Z u ≤ u :=
+ (streamMaximum_le_iff ..).mpr fun i => (row_le q i (Z+1)).trans i.isLt.le
+
+theorem answer_step (q : ℕ → ℕ → Bool) (Z : ℕ) (s : State) :
+ answer q Z (step q Z s) = answer q Z s := by
+ cases s with
+ | done => rfl
+ | running u z =>
+ cases h : q u z with
+ | false =>
+ simp only [step, h, advance, Bool.false_eq_true, ite_false, answer, row, peak_succ]
+ change u = max (below q Z u) (max (row q u z) u)
+ rw [max_eq_right (row_le q u z), max_eq_right (below_le q Z u)]
+ | true =>
+ cases z with
+ | succ z =>
+ simp only [step, h, advance, ite_true, Nat.succ_ne_zero, ite_false, Nat.add_one_sub_one, answer, row, peak_succ, max_zero]
+ | zero =>
+ cases u with
+ | zero => simp [step, h, advance, answer, below, row, peak, streamMaximum]; rfl
+ | succ u =>
+ simp only [step, h, advance, ite_true, Nat.succ_ne_zero, ite_false, Nat.add_one_sub_one, answer,
+ below, row, peak_succ]
+ simp [peak, streamMaximum]
+
+/-- Exact number of remaining requests if all remaining coefficients vanish. -/
+def remaining (Z : ℕ) : State → ℕ
+ | .running u z => u*(Z+1)+z+1
+ | .done _ => 0
+
+theorem remaining_decreases (q : ℕ → ℕ → Bool) (Z u z : ℕ) :
+ remaining Z (step q Z (.running u z)) < remaining Z (.running u z) := by
+ cases h : q u z <;> cases z <;> cases u <;> simp [step, advance, h, remaining, Nat.succ_mul]
+
+/-- Deterministic recursion asks for at most the entire rectangle of scalar
+queries. Its halting value is the maximum nonzero outer degree. -/
+theorem run (q : ℕ → ℕ → Bool) (Z : ℕ) (s : State) :
+ ∃ t ≤ remaining Z s, (step q Z)^[t] s = .done (answer q Z s) := by
+ induction s using (measure (remaining Z)).wf.induction with
+ | h s ih =>
+ cases s with
+ | done r => exact ⟨0, le_rfl,rfl⟩
+ | running u z =>
+ have ht := remaining_decreases q Z u z
+ obtain ⟨t,hclock,hrun⟩ := ih _ ht
+ refine ⟨t+1, by omega, ?_⟩
+ change (step q Z)^[t] (step q Z (.running u z)) = .done (answer q Z (.running u z))
+ rw [hrun, answer_step]
+
+theorem initial_answer {F : Type*} [Field F] [DecidableEq F] {n m : ℕ}
+ (M : Matrix (Fin n) (Fin m) F) (get : ℕ → ℕ → F)
+ (hg : ∀ u z, get u z = ((rankPolynomial M).coeff u).coeff z) :
+ let Z := (n+m)*n
+ answer (fun u z => decide (get u z = 0)) Z (.running n Z) = M.rank := by
+ let Z := (n+m)*n
+ let q := fun u z => decide (get u z = 0)
+ have hs := scanRank_correct M get hg
+ change max (below q Z n) (row q n (Z+1)) = _
+ rw [below, ← peak_succ (fun u => row q u (Z+1)) n]
+ simpa [scanRank, peak, row, q, Z] using hs
+
+/-- All index updates and the stopping decision on one scalar zero-test flag
+run on a fixed binary-stack routine. -/
+theorem physical {w p : ℕ} (Z u z : ℕ) (zero : Bool)
+ (rs : Regs (14+control.scratch) w) (hw : (p+1)*control.wordFactor ≤ w)
+ (he : ∀ i, input Z u z zero i < 2^p)
+ (hr : ∀ i, (rs (Code.inReg control.scratch i)).val = input Z u z zero i)
+ (pub : Fin 0 → Word w) (persistent : Word w) :
+ ∃ t ≤ (control.emitFields control.scratch (List.finRange 6)).length * (100*(w+1)^2), ∃ out,
+ (control.physical control.scratch).Runs t (ISA.bank pub persistent rs []) (ISA.bank pub persistent out []) ∧
+ (fun i => (out (Code.outReg control.scratch i)).val) = (advance Z u z zero).words := by
+ obtain ⟨t,ht,out,hrun,_,hvalue⟩ := control.physical_runs _ _ le_rfl _ _ hw he hr pub persistent
+ exact ⟨t,ht,out,hrun,(funext hvalue).trans (control_eq ..)⟩
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackDispatch.lean b/lean/OAI/Computability/VPVNP/RankQueryStackDispatch.lean
new file mode 100644
index 0000000000..2f4aca5367
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackDispatch.lean
@@ -0,0 +1,213 @@
+import OAI.Computability.VPVNP.RankQueryStackWords
+
+/-!
+# Fixed arithmetic code for Schur node dispatch
+
+The same decision trees serve every matrix size and every bidegree. Input
+registers zero through five hold the query, register six is the product-loop
+counter, and register seven is the matrix height. The child routine selects a
+side and returns the six registers of that child. The description routine
+returns a scalar, a scalar-entry request, or the arity of the product sum.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Dispatch
+
+/-- Natural-number arithmetic operations available in Schur dispatch expressions. -/
+inductive Arith where
+ | add | sub | mul | div | mod
+ deriving DecidableEq
+
+/-- Interpret a dispatch arithmetic operation using natural addition, subtraction,
+multiplication, division or remainder. -/
+def Arith.eval : Arith → ℕ → ℕ → ℕ
+ | .add => Nat.add
+ | .sub => Nat.sub
+ | .mul => Nat.mul
+ | .div => Nat.div
+ | .mod => Nat.mod
+
+/-- Arithmetic expression over literals and the eight immutable dispatch inputs. -/
+inductive Expr where
+ | reg (i : Fin 8)
+ | lit (v : ℕ)
+ | op (a : Arith) (lhs rhs : Expr)
+
+instance (n : ℕ) : OfNat Expr n := ⟨.lit n⟩
+instance : Add Expr := ⟨.op .add⟩
+instance : Sub Expr := ⟨.op .sub⟩
+instance : Mul Expr := ⟨.op .mul⟩
+instance : Div Expr := ⟨.op .div⟩
+instance : Mod Expr := ⟨.op .mod⟩
+
+/-- Evaluate a dispatch expression in the supplied bank of eight natural numbers. -/
+def Expr.eval (inputs : Fin 8 → ℕ) : Expr → ℕ
+ | .reg i => inputs i
+ | .lit v => v
+ | .op a l r => a.eval (l.eval inputs) (r.eval inputs)
+
+/-- Decision tree that tests expression equality and emits six expressions at the selected
+leaf. -/
+inductive Code where
+ | emit (fields : Fin 6 → Expr)
+ | test (x y : Expr) (yes no : Code)
+
+/-- Follow equality tests on the input words and evaluate the six fields of the reached leaf. -/
+def Code.eval (inputs : Fin 8 → ℕ) : Code → Fin 6 → ℕ
+ | .emit fields => fun i => (fields i).eval inputs
+ | .test x y yes no => if x.eval inputs = y.eval inputs then yes.eval inputs else no.eval inputs
+
+private abbrev tag : Expr := .reg 0
+private abbrev a : Expr := .reg 1
+private abbrev i : Expr := .reg 2
+private abbrev j : Expr := .reg 3
+private abbrev h : Expr := .reg 4
+private abbrev z : Expr := .reg 5
+private abbrev k : Expr := .reg 6
+private abbrev rows : Expr := .reg 7
+
+/-- Absolute row of an index in the trailing matrix. -/
+private abbrev absolute (x : Expr) := x + 1 + a
+private abbrev tailCount := rows - a - 1
+private abbrev mid := k / (z+1)
+private abbrev deg := k % (z+1)
+
+private def oneChild : Code := .emit ![6,0,0,0,0,0]
+
+private def productChild (right : Bool) : Code :=
+ .test a 0
+ (if right then oneChild else .emit ![1,i,0,0,h,z])
+ (if right then .emit ![0,a-1,i+j/2,j-j/2,h-mid,z-deg]
+ else .emit ![0,a-1,i,j/2,mid,deg])
+
+private def factorChild (right : Bool) : Code :=
+ if right then oneChild else .emit ![2,a,k/tailCount,k%tailCount,h-2,z]
+
+private def outerChild (right : Bool) : Code :=
+ if right then .emit ![5,absolute j,a,1,0,z-k] else .emit ![3,a,i,j,h,k]
+
+private def innerChild (right : Bool) : Code :=
+ if right then .emit ![4,a,i,j,h,z-k] else .emit ![5,a,absolute i,0,0,k]
+
+private def powerChild (right : Bool) : Code :=
+ if right then .emit ![4,a,mid,j,h-h/2,z-deg] else .emit ![4,a,i,mid,h/2,deg]
+
+/-- Dispatch on the Schur key tag to construct the selected left or right child query. -/
+def child (right : Bool) : Code :=
+ .test tag 0 (productChild right) <| .test tag 1 (factorChild right) <|
+ .test tag 2 (outerChild right) <| .test tag 3 (innerChild right) (powerChild right)
+
+private def zeroResult : Code := .emit ![0,0,0,0,0,0]
+private def oneResult : Code := .emit ![1,0,0,0,0,0]
+private def unitResult : Code := .test h 0 (.test z 0 oneResult zeroResult) zeroResult
+
+private def read (neg : Bool) (row col degree : Expr) : Code :=
+ .emit ![if neg then 3 else 2,row,col,degree,0,0]
+
+private def branch (count : Expr) : Code := .emit ![4,count,0,0,0,0]
+
+private def productDescription : Code :=
+ .test a 0 (.test j 0 unitResult (branch 1)) (branch ((h+1)*(z+1)))
+
+private def factorDescription : Code :=
+ .test h 0 (.test z 0 oneResult zeroResult) <| .test h 1 (read true a a z) (branch (tailCount*tailCount))
+
+private def powerDescription : Code :=
+ .test h 0 (.test i j (.test z 0 oneResult zeroResult) zeroResult) <|
+ .test h 1 (read false (absolute i) (absolute j) z) (branch (tailCount*(z+1)))
+
+/-- Dispatch on the Schur key tag to describe its product scan or its scalar result. -/
+def describe : Code :=
+ .test tag 0 productDescription <| .test tag 1 factorDescription <|
+ .test tag 2 (branch (z+1)) <| .test tag 3 (branch (z+1)) <|
+ .test tag 4 powerDescription <| .test tag 5 (.test j 0 (read false a i z) (read true a i z)) oneResult
+
+variable {n U Z : ℕ}
+
+/-- Assemble the six encoded query words, child index and matrix dimension into the dispatch
+input bank. -/
+def inputs (q : SchurKey n U Z) (k : ℕ) : Fin 8 → ℕ :=
+ ![q.words 0,q.words 1,q.words 2,q.words 3,q.words 4,q.words 5,k,n]
+
+/-- Interpret an emitted descriptor using only a query for a scalar entry. -/
+def decode {R : Type*} [CommRing R] (entry : Entry n R) (v : Fin 6 → ℕ) : Sum R ℕ :=
+ if v 0 = 4 then .inr (v 1) else if v 0 = 1 then .inl 1 else if v 0 = 0 then .inl 0 else
+ if hi : v 1 < n then if hj : v 2 < n then
+ let x := entry ⟨v 1,hi⟩ ⟨v 2,hj⟩ (v 3)
+ if v 0 = 2 then .inl x else if v 0 = 3 then .inl (-x) else .inl 0
+ else .inl 0 else .inl 0
+
+theorem eval_add (s : Fin 8 → ℕ) (x y : Expr) : (x+y).eval s = x.eval s + y.eval s := rfl
+theorem eval_sub (s : Fin 8 → ℕ) (x y : Expr) : (x-y).eval s = x.eval s - y.eval s := rfl
+theorem eval_mul (s : Fin 8 → ℕ) (x y : Expr) : (x*y).eval s = x.eval s * y.eval s := rfl
+theorem eval_div (s : Fin 8 → ℕ) (x y : Expr) : (x/y).eval s = x.eval s / y.eval s := rfl
+theorem eval_mod (s : Fin 8 → ℕ) (x y : Expr) : (x%y).eval s = x.eval s % y.eval s := rfl
+theorem eval_lit (s : Fin 8 → ℕ) (n : ℕ) : (OfNat.ofNat n : Expr).eval s = n := rfl
+
+private theorem subscript {q : Fin n} (i : TailIndex q) : i.val + 1 + q.val < n := by
+ have := q.isLt
+ have := i.isLt
+ omega
+
+/-- Evaluate the rank-query dispatcher and its selected child description
+using the branch and cursor equations in the local context. -/
+macro (name := simplifyDispatch) "simplify_dispatch" : tactic => `(tactic|
+ simp [Code.eval, inputs, SchurKey.words, eval_add, eval_sub, eval_mul, eval_div, eval_mod,
+ eval_lit, Expr.eval, Arith.eval, tag, a, i, j, h, z, k, rows, absolute, mid, deg, tailCount,
+ describe, productDescription, factorDescription, powerDescription, unitResult,
+ branch, read, oneResult, zeroResult, decode, SchurKey.node, Node.box, Node.describe,
+ SchurKey.unitCoeff, PowerKey.node, Node.map, tailEntry, tailIndex, suffixIndex, subscript,
+ child, productChild, factorChild, outerChild, innerChild, powerChild, oneChild,
+ SchurKey.program, Node.program, Node.children, PowerKey.split, predBy,
+ lowDegree, highDegree, Block.lower, Block.upper, Fin.ext_iff, Nat.pos_iff_ne_zero, *])
+
+theorem describe_eq {R : Type*} [CommRing R] (entry : Entry n R) (q : SchurKey n U Z) (cursor : ℕ) :
+ decode entry (describe.eval (inputs q cursor)) = (q.node entry).describe := by
+ cases q with
+ | product d b u z =>
+ by_cases hd : d.val = 0 <;> by_cases hb : b.count = 0 <;>
+ by_cases hu : u.val = 0 <;> by_cases hz : z.val = 0 <;>
+ simplify_dispatch
+ | factor a u z =>
+ by_cases hu : u.val = 0 <;> by_cases hu' : u.val = 1 <;> by_cases hz : z.val = 0 <;> simplify_dispatch
+ | outer | inner | one => simplify_dispatch
+ | scalar neg i j z => cases neg <;> simplify_dispatch
+ | power a q =>
+ by_cases h0 : q.exponent.val = 0 <;> by_cases h1 : q.exponent.val = 1 <;>
+ by_cases hij : q.row.val = q.col.val <;> by_cases hz : q.degree.val = 0 <;> simplify_dispatch
+
+/-- At a valid product-loop index the fixed code supplies precisely the
+query saved by the typed stack interpreter. -/
+theorem child_eq {R : Type*} [CommRing R] (entry : Entry n R) (q : SchurKey n U Z)
+ {t : ℕ} {f : Fin t → SchurKey n U Z × SchurKey n U Z}
+ (hn : q.node entry = .branch t f) (idx : Fin t) (right : Bool) :
+ (child right).eval (inputs q idx.val) = (if right then (f idx).2 else (f idx).1).words := by
+ cases q with
+ | product d b u z =>
+ simp only [SchurKey.node] at hn
+ split_ifs at hn with hd hc
+ all_goals cases hn; cases right <;> funext field <;> fin_cases field <;> simplify_dispatch <;> rfl
+ | factor a u z =>
+ simp only [SchurKey.node] at hn
+ split_ifs at hn
+ cases hn
+ cases right <;> funext field <;> fin_cases field <;> simplify_dispatch
+ | outer | inner =>
+ cases hn
+ cases right <;> funext field <;> fin_cases field <;> simplify_dispatch
+ | power a q =>
+ simp only [SchurKey.node, PowerKey.node] at hn
+ split_ifs at hn <;> simp only [Node.map, Node.box] at hn
+ all_goals cases hn
+ cases right <;> funext field <;> fin_cases field <;> simplify_dispatch
+ all_goals rfl
+ | scalar | one => contradiction
+
+end RankQuery.Stack.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackEngine.lean b/lean/OAI/Computability/VPVNP/RankQueryStackEngine.lean
new file mode 100644
index 0000000000..5ae485fefc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackEngine.lean
@@ -0,0 +1,154 @@
+import OAI.Computability.VPVNP.RankQueryStackFrames
+
+/-!
+# Return control for the physical determinant stack
+
+The finite control dispatches a query, scans its summands and returns each
+operand to the suspended parent. The result of a terminal descriptor and a
+finished sum both enter the same return instruction. An empty direction history
+signals that the root coefficient is ready. A nonempty history is restored
+before the frame reader consumes the saved fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine
+
+open RAMTape
+
+/-- Live and historical frame registers, the result, one condition bit and the
+scratch or persistent ports of the installed scalar and dispatch routines. -/
+inductive Port (K : Type) where
+ | frame (p : FrameStore.Port) | result | condition | aux (k : K)
+ deriving DecidableEq, Fintype
+
+/-- Each of the external calls returns normally and supplies its data on the
+named ports. Describe emits a true condition for a scalar, scan for a completed
+sum. Left and right children are placed in pending registers before the active
+frame is pushed. -/
+structure Actions (K : Type) where
+ /-- Inspect the active query and initialize its scan or signal a scalar result. -/
+ describe : FiniteRoutine (Port K)
+ /-- Advance the sum scan, signaling completion or preparing the next left child. -/
+ scan : FiniteRoutine (Port K)
+ /-- Move a pending child query into the live frame after saving its parent. -/
+ activate : FiniteRoutine (Port K)
+ /-- Prepare the right child after the left factor's value returns. -/
+ right : FiniteRoutine (Port K)
+ /-- Add the product of the returned factors to the parent accumulator. -/
+ multiplyAdd : FiniteRoutine (Port K)
+
+/-- Subroutine calls of the stack evaluator, including frame saves and restores. -/
+inductive Call where
+ | describe | scan | save | restore | activate | right | multiplyAdd
+ deriving DecidableEq
+
+instance : Fintype Call := derive_fintype% _
+
+variable {K : Type}
+
+/-- Select the installed evaluator action or built-in frame routine for a call tag. -/
+def Actions.callee (a : Actions K) : Call → FiniteRoutine (Port K)
+ | .describe => a.describe
+ | .scan => a.scan
+ | .save => FrameStore.push.onPorts Port.frame
+ | .restore => FrameStore.pop.onPorts Port.frame
+ | .activate => a.activate
+ | .right => a.right
+ | .multiplyAdd => a.multiplyAdd
+
+/-- Controller states for inspecting subroutine results, restoring the frame direction and
+rejecting invalid signals. -/
+inductive Admin where
+ | described | scanned | returned | restoreTag (b : Bool) | direction | reject
+ deriving DecidableEq, Fintype
+
+/-- Physical engine state, either a controller state or a program counter inside an identified
+subroutine. -/
+abbrev State (a : Actions K) := Admin ⊕ ((i : Call) × (a.callee i).State)
+
+/-- Enter the specified subroutine at its initial program counter. -/
+def invoke (a : Actions K) (i : Call) : State a := .inr ⟨i, (a.callee i).body.entry⟩
+
+private def after (a : Actions K) : Call → State a
+ | .describe => .inl .described
+ | .scan => .inl .scanned
+ | .save => invoke a .activate
+ | .restore => .inl .direction
+ | .activate => invoke a .describe
+ | .right => invoke a .save
+ | .multiplyAdd => invoke a .scan
+
+/-- Execute the installed evaluator actions and frame routines under the call-and-return
+controller. -/
+def routine (a : Actions K) : Routine (Port K) (State a) where
+ entry := invoke a .describe
+ code
+ | .inr ⟨i, q⟩ => (a.callee i).body.install (fun j => .inr ⟨i,j⟩) (some (after a i)) q
+ | .inl .described => .pop .condition (fun b => some (b.elim (.inl .reject) fun terminal =>
+ if terminal then .inl .returned else invoke a .scan))
+ | .inl .scanned => .pop .condition (fun b => some (b.elim (.inl .reject) fun finished =>
+ if finished then .inl .returned else invoke a .save))
+ | .inl .returned => .pop (.frame (.inr 0)) fun b => b.map (fun d => .inl (.restoreTag d))
+ | .inl (.restoreTag b) => .push (.frame (.inr 0)) b (some (invoke a .restore))
+ | .inl .direction => .pop (.frame (.inl 0)) (fun b => some (b.elim (.inl .reject) fun right =>
+ if right then invoke a .multiplyAdd else invoke a .right))
+ | .inl .reject => .halt false
+
+/-- The outer program is finite as soon as its component programs are finite. -/
+def machine (a : Actions K) : FiniteRoutine (Port K) := .ofRoutine (routine a)
+
+variable [DecidableEq K]
+
+theorem call_runs (a : Actions K) (i : Call) {t : ℕ} {s out : Stacks (Port K)}
+ (h : (a.callee i).Runs t s out) :
+ StackRuns (routine a).standalone t (some (invoke a i)) s (some (after a i)) out :=
+ h.link (routine a) (fun j => .inr ⟨i,j⟩) _ (fun _ => rfl)
+
+theorem described_step (a : Actions K) (s : Stacks (Port K)) (b : Bool) (hs : s .condition = [b]) :
+ StackRuns (routine a).standalone 1 (some (.inl .described)) s
+ (some (if b then .inl .returned else invoke a .scan)) (Function.update s .condition []) := by
+ refine .cons (.pop rfl) ?_
+ simp only [hs, List.head?_cons, List.tail_cons, Option.elim_some]
+ exact .nil ..
+
+theorem scanned_step (a : Actions K) (s : Stacks (Port K)) (b : Bool) (hs : s .condition = [b]) :
+ StackRuns (routine a).standalone 1 (some (.inl .scanned)) s
+ (some (if b then .inl .returned else invoke a .save)) (Function.update s .condition []) := by
+ refine .cons (.pop rfl) ?_
+ simp only [hs, List.head?_cons, List.tail_cons, Option.elim_some]
+ exact .nil ..
+
+/-- Test the direction history without changing the bit at its top. -/
+theorem return_to_frame (a : Actions K) (s : Stacks (Port K)) (b : Bool) (tail : List Bool)
+ (hs : s (.frame (.inr 0)) = b :: tail) :
+ StackRuns (routine a).standalone 2 (some (.inl .returned)) s (some (invoke a .restore)) s := by
+ refine .cons (.pop rfl) ?_
+ simp only [hs, List.head?_cons, List.tail_cons, Option.map_some]
+ refine .cons (.push rfl) ?_
+ simp only [Function.update_self, Function.update_idem, ← hs, Function.update_eq_self]
+ exact .nil ..
+
+/-- The empty continuation stack returns the computed root scalar to the caller. -/
+theorem return_to_caller (a : Actions K) (s : Stacks (Port K)) (hs : s (.frame (.inr 0)) = []) :
+ StackRuns (routine a).standalone 1 (some (.inl .returned)) s none s := by
+ refine .cons (.pop rfl) ?_
+ simp only [hs, List.head?_nil, List.tail_nil, Option.map_none]
+ rw [← hs, Function.update_eq_self]
+ exact .nil ..
+
+theorem direction_step (a : Actions K) (s : Stacks (Port K)) (b : Bool) (hs : s (.frame (.inl 0)) = [b]) :
+ StackRuns (routine a).standalone 1 (some (.inl .direction)) s
+ (some (if b then invoke a .multiplyAdd else invoke a .right))
+ (Function.update s (.frame (.inl 0)) []) := by
+ refine .cons (.pop rfl) ?_
+ simp only [hs, List.head?_cons, List.tail_cons, Option.elim_some]
+ exact .nil ..
+
+end RankQuery.Stack.Engine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackEngineAssembly.lean b/lean/OAI/Computability/VPVNP/RankQueryStackEngineAssembly.lean
new file mode 100644
index 0000000000..ebba4eea76
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackEngineAssembly.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.RankQueryStackScanSetup
+import OAI.Computability.VPVNP.RankQueryStackStages
+import OAI.Computability.VPVNP.RankQueryStackMultiplyAdd
+
+/-!
+# Linking the Schur determinant callbacks
+
+A single shared binary register bank computes child queries. Its output words
+are copied into the emptied live registers only after the parent's frame has
+been saved. The accumulator callback uses the native extension-field arithmetic.
+The remaining installation point reads and interprets the matrix descriptor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine.Assembly
+
+open RAMTape UniversalCountStack Dispatch
+
+variable {K : Type} [DecidableEq K]
+
+/-- Auxiliary stack holding one pending child-query word in the dispatcher's output register
+bank. -/
+def source (bank : EngineAlias.Small ↪ K) (i : Fin 6) := bank (.reg (Code.outReg capacity i))
+
+/-- Link the descriptor, child dispatcher, activation and field multiply-add routines into the
+evaluator's actions. -/
+def actions (bank : EngineAlias.Small ↪ K) (tmp : K) (mac : MultiplyAdd.Aux → K)
+ (descriptor : FiniteRoutine (Engine.Port K)) : Actions K where
+ describe := descriptor
+ scan := ScanCall.scan tmp (EngineAlias.stageChild bank false)
+ activate := Activate.machine (source bank) tmp
+ right := ScanCall.right tmp (EngineAlias.stageChild bank true)
+ multiplyAdd := MultiplyAdd.machine mac
+
+variable {n U Z p e w v : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- The descriptor's additional state occupies ports outside the shared
+Schur register bank. The field-arithmetic advice and scratch also persist. -/
+def Ready (bank : EngineAlias.Small ↪ K) (tmp : K) (mac : MultiplyAdd.Aux → K)
+ (extra : Stacks K → Prop) (n w v : ℕ) (c : SliceArithmetic.Vector p e) (s : Stacks K) : Prop :=
+ EngineAlias.Ready bank w n s ∧ s tmp = [] ∧ MultiplyAdd.Ready mac v c s ∧ extra s
+
+/-- The auxiliary bank is ready and its six pending output registers encode the specified Schur
+key. -/
+def Pending (bank : EngineAlias.Small ↪ K) (tmp : K) (mac : MultiplyAdd.Aux → K)
+ (extra : Stacks K → Prop) (w v : ℕ) (c : SliceArithmetic.Vector p e)
+ (q : Key n U Z) (s : Stacks K) : Prop :=
+ Ready bank tmp mac extra n w v c s ∧ ∀ i, s (source bank i) = digits w (q.words i)
+
+/-- Step allowance for local child dispatch, scalar multiply-add and movement of the encoded
+words. -/
+def localBudget (w e v : ℕ) : ℕ :=
+ (Operation.left.clock w + Operation.right.clock w) + MultiplyAdd.callCap e v +
+ 100*(w+e*v+1)
+
+variable [Fact p.Prime] [NeZero e]
+
+/-- Every call except the descriptor is instantiated here with an executable
+finite bit-stack routine. The descriptor may have a separate, larger clock. -/
+theorem contracts {s Bd : ℕ} (bank : EngineAlias.Small ↪ K) (tmp : K) (mac : MultiplyAdd.Aux → K)
+ (hm : Function.Injective mac) (htmp : ∀ i, bank i ≠ tmp) (hmac : ∀ i j, bank i ≠ mac j)
+ (extra : Stacks K → Prop) (hex : ∀ a b, extra a → (∀ j, (∀ i, bank i ≠ j) → b j = a j) → extra b)
+ (desc : FiniteRoutine (Engine.Port K)) (entry : Entry n (Scalar c))
+ (hn : n ≤ 2^s) (hu : U ≤ 2^s) (hz : Z ≤ 2^s) (hp : 2*s+6 ≤ w)
+ (hw : (2*s+6+1)*widthFactor ≤ w) (hv : SliceArithmetic.Word.workingWidth p ≤ v)
+ (hd : ∀ (q : Key n U Z) (fs : List (F n U Z c)) aux,
+ Ready bank tmp mac extra n w v c aux → ∃ t ≤ Bd, ∃ out, Ready bank tmp mac extra n w v c out ∧
+ desc.Runs t (atControl w v (.enter q) fs aux)
+ (match (SchurKey.program entry).describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false])) :
+ Contracts (actions bank tmp mac desc) (SchurKey.program (U := U) (Z := Z) entry) w v (localBudget w e v)
+ (SchurKey.arityBound n U Z) (Ready bank tmp mac extra n w v c) (Pending bank tmp mac extra w v c) Bd := by
+ have preserve (q : Key n U Z) (aux out : Stacks K) (ha : Ready bank tmp mac extra n w v c aux)
+ (pending : EngineAlias.Pending bank w q out)
+ (outside : ∀ j, (∀ i, bank i ≠ j) → out j = aux j) : Pending bank tmp mac extra w v c q out :=
+ ⟨⟨pending.1, (outside _ htmp).trans ha.2.1,
+ fun i => (outside _ (fun j => hmac j i)).trans (ha.2.2.1 i), hex aux out ha.2.2.2 outside⟩,
+ pending.2⟩
+ constructor
+ · exact hd
+ · intro q acc fs aux ready
+ obtain ⟨t, ht, run⟩ := ScanCall.zero_runs (w := w) (v := v) tmp (EngineAlias.stageChild bank false) q acc fs aux ready.2.1
+ exact ⟨t, by dsimp [localBudget]; omega, aux, ready, run⟩
+ · intro q k acc fs aux hk valid ready
+ have hb := EngineAlias.inputs_bounded s hn hu hz q (k+1) hk
+ have h6 : k+1 < 2^(2*s+6) := hb 6
+ have hkfit := h6.trans_le (Nat.pow_le_pow_right (by decide : 1 ≤ 2) hp)
+ obtain ⟨tc, ht, out, pend, child, outside⟩ := EngineAlias.stageChild_runs bank false entry q k valid
+ [] (scalar v acc) [] (history w v fs) [] [] aux ready.1
+ (EngineAlias.inputs_bounded s hn hu hz q k (by omega)) hp hw
+ have ho := preserve ((SchurKey.program entry).left q k) aux out ready pend outside
+ obtain ⟨t, ht', run⟩ := ScanCall.succ_runs tmp _ q k acc fs aux out ready.2.1 hkfit child
+ change tc ≤ Operation.left.clock w at ht
+ exact ⟨t, by dsimp [localBudget]; omega, out, ho, run⟩
+ · intro q fs aux pend
+ have run := Activate.machine_runs (source bank) tmp (fun i => htmp _) w v q fs aux pend.1.2.1 pend.2
+ exact ⟨_, by dsimp [localBudget]; omega, aux, pend.1, run⟩
+ · intro q k acc l fs aux hk valid ready
+ obtain ⟨tc, ht, out, pend, child, outside⟩ := EngineAlias.stageChild_runs bank true entry q k valid
+ [] (scalar v acc) [] (history w v fs) [] (scalar v l) aux ready.1
+ (EngineAlias.inputs_bounded s hn hu hz q k hk.le) hp hw
+ have ho := preserve ((SchurKey.program entry).right q k) aux out ready pend outside
+ have run := ScanCall.right_runs tmp _ q k acc l fs aux out ho.1.2.1 child
+ change tc ≤ Operation.right.clock w at ht
+ exact ⟨_, by dsimp [localBudget]; omega, out, ho, run⟩
+ · intro q k acc l r fs aux _ ready
+ obtain ⟨t,ht,run⟩ := MultiplyAdd.machine_runs mac hm hv w q k acc l r fs aux ready.2.2.1
+ exact ⟨t, by dsimp [localBudget]; omega, aux, ready, run⟩
+
+end RankQuery.Stack.Engine.Assembly
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackEngineRun.lean b/lean/OAI/Computability/VPVNP/RankQueryStackEngineRun.lean
new file mode 100644
index 0000000000..b00c4fed1e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackEngineRun.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.RankQueryStackEngineStep
+import OAI.Computability.VPVNP.RankQueryStackBounds
+
+/-! # Execution and space of the physical Schur continuation control -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine
+
+open RAMTape UniversalCountStack
+
+variable {n U Z p e : ℕ} {c : SliceArithmetic.Vector p e} {K : Type}
+
+private theorem live_length (w v : ℕ) (ctl : Ctl n U Z c) (i : Fin 10) :
+ (live w v ctl i).length ≤ max 1 (max w (e*v)) := by
+ cases ctl with
+ | returned r => simp [live]
+ | enter q =>
+ refine Fin.cases (by simp [live, fields]) (fun j => ?_) i
+ refine Fin.addCases (motive := fun i => (Fin.append (fun x => digits w (q.words x)) ![[],[],[]] i).length ≤ _)
+ (fun x : Fin 6 => ?_) (fun x : Fin 3 => ?_) j
+ · simp
+ · rw [Fin.append_right]; fin_cases x <;> simp
+ | scan q k a =>
+ refine Fin.cases (by simp [live, fields]) (fun j => ?_) i
+ refine Fin.addCases (motive := fun i => (Fin.append (fun x => digits w (q.words x))
+ ![digits w k,scalar v a,[]] i).length ≤ _) (fun x : Fin 6 => ?_) (fun x : Fin 3 => ?_) j
+ · simp
+ · rw [Fin.append_right]; fin_cases x <;> simp
+
+/-- The call-stack cap counts the nested tagged field strings in each history.
+One bounded transition accounts for the private working space between calls. -/
+def runSpace (A d B w v e : ℕ) :=
+ max A (max (max 1 (max w (e*v))) (d*(2*max 1 (max w (e*v))+1))) + stepBudget B w v e
+
+theorem state_length {A d w v : ℕ} (cfg : Cfg n U Z c) (hd : cfg.2.length ≤ d)
+ (aux : Stacks K) (ha : ∀ k, (aux k).length ≤ A) (k : Port K) :
+ (atControl w v cfg.1 cfg.2 aux [] k).length ≤ max A (max (max 1 (max w (e*v))) (d*(2*max 1 (max w (e*v))+1))) := by
+ cases k with
+ | frame j =>
+ cases j with
+ | inl i => exact (live_length w v cfg.1 i).trans ((le_max_left ..).trans (le_max_right ..))
+ | inr i =>
+ exact ((history_length_le w v cfg.2 i).trans (Nat.mul_le_mul_right _ hd)).trans
+ ((le_max_right ..).trans (le_max_right ..))
+ | aux k => exact (ha k).trans (le_max_left ..)
+ | condition => exact Nat.zero_le _
+ | result => cases cfg.1 <;> simp [atControl, store, output]
+
+variable [DecidableEq K] [Fact p.Prime] [NeZero e]
+variable {a : Actions K} {prog : Program (Key n U Z) (Scalar c)} {w v B lim A d : ℕ}
+variable {ready : Stacks K → Prop} {pending : Key n U Z → Stacks K → Prop}
+
+/-- Transfer a capped abstract execution to the finite bit-stack program. -/
+theorem eval_run (spec : Contracts a prog w v B lim ready pending) (arity : prog.ArityLE lim)
+ (ha : ∀ s, ready s → ∀ k, (s k).length ≤ A) {steps : ℕ} {start finish : Cfg n U Z c}
+ (run : prog.Runs d steps start finish) (range : InRange lim start) (cursor : CursorRange prog start)
+ (aux : Stacks K) (haux : ready aux) :
+ ∃ t ≤ steps*stepBudget B w v e, ∃ out, ready out ∧
+ SpaceRun (routine a).standalone (runSpace A d B w v e) t
+ (some (label a start.1)) (atControl w v start.1 start.2 aux)
+ (some (label a finish.1)) (atControl w v finish.1 finish.2 out) := by
+ induction run generalizing aux with
+ | done cfg depth =>
+ refine ⟨0, by simp, aux, haux, .nil _ _ fun k => ?_⟩
+ exact (state_length cfg depth aux (ha aux haux) k).trans (Nat.le_add_right ..)
+ | next depth _ ih =>
+ obtain ⟨t, ht, mid, hm, step⟩ := step_runs spec _ range cursor aux haux
+ obtain ⟨u, hu, out, ho, rest⟩ := ih (inRange_step _ _ arity _ range) (cursorRange_step _ _ cursor) mid hm
+ have bounded := spaceRun_of_steps step (fun k => Nat.add_le_add (state_length _ depth aux (ha aux haux) k) ht)
+ refine ⟨_, ?_, out, ho, bounded.trans rest⟩
+ exact (Nat.add_le_add ht hu).trans_eq ((Nat.add_comm ..).trans (Nat.succ_mul ..).symm)
+
+/-- Run the supplied matrix coefficient query from its root to a native scalar
+on the output port. The entire physical return stack has been emptied. -/
+theorem eval_root {entry : Entry n (Scalar c)}
+ (spec : Contracts a (SchurKey.program (U := U) (Z := Z) entry) w v B (SchurKey.arityBound n U Z) ready pending)
+ (ha : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (M : Matrix (Fin n) (Fin n) (Polynomial (Scalar c))) (he : ∀ i j z, entry i j z = (M i j).coeff z)
+ (u : Limit U) (z : Limit Z) (aux : Stacks K) (haux : ready aux) :
+ let depth := Nat.clog 2 U + 4 + Nat.clog 2 n
+ ∃ t ≤ (5 + 6*SchurKey.arityBound n U Z)^(depth+1)*stepBudget B w v e + 1, ∃ out, ready out ∧
+ SpaceRun (routine a).standalone (runSpace A depth B w v e) t (some (routine a).entry)
+ (atControl (c := c) w v (.enter (SchurKey.root (n := n) u z)) [] aux) none
+ (atControl w v (.returned ((M.charpolyRev.coeff u.val).coeff z.val)) ([] : List (F n U Z c)) out) := by
+ let depth := Nat.clog 2 U + 4 + Nat.clog 2 n
+ let value := (M.charpolyRev.coeff u.val).coeff z.val
+ let finish : Cfg n U Z c := (.returned value, [])
+ obtain ⟨m, hm, hrun⟩ := SchurKey.run M entry he u z
+ have startRange : InRange (SchurKey.arityBound n U Z) (c := c) (.enter (SchurKey.root (n := n) u z), []) := by
+ simp [InRange]
+ have startCursor : CursorRange (SchurKey.program entry) (.enter (SchurKey.root (n := n) u z), []) := by
+ simp [CursorRange]
+ obtain ⟨t,ht,out,ho,hr⟩ := eval_run spec (SchurKey.arity entry) ha hrun startRange startCursor aux haux
+ have stop := return_to_caller a (atControl w v finish.1 finish.2 out) rfl
+ have last : SpaceRun (routine a).standalone (runSpace A depth B w v e) 1
+ (some (.inl .returned)) (atControl w v finish.1 finish.2 out) none (atControl w v finish.1 finish.2 out) :=
+ spaceRun_of_steps stop fun k => Nat.add_le_add
+ (state_length (d := depth) finish (Nat.zero_le _) out (ha _ ho) k) (by dsimp [stepBudget]; omega)
+ exact ⟨_, Nat.add_le_add_right (ht.trans (Nat.mul_le_mul_right _ hm)) _, out, ho, hr.trans last⟩
+
+end RankQuery.Stack.Engine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackEngineSpace.lean b/lean/OAI/Computability/VPVNP/RankQueryStackEngineSpace.lean
new file mode 100644
index 0000000000..5c96dad356
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackEngineSpace.lean
@@ -0,0 +1,153 @@
+import OAI.Computability.VPVNP.RankQueryStackEngineRun
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-! # Polynomial stack space with expensive scalar-entry calls
+
+The descriptor can invoke another complete matrix or coefficient computation.
+Its time may be exponential while its space stays polynomial. The execution
+below links its bounded run directly. The other Schur actions have polynomial
+instruction budgets and reuse the same workspace between transitions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine
+
+open RAMTape UniversalCountStack
+
+variable {n U Z p e : ℕ} {c : SliceArithmetic.Vector p e} {K : Type} [DecidableEq K]
+variable [Fact p.Prime] [NeZero e]
+variable {a : Actions K} {prog : Program (Key n U Z) (Scalar c)} {w v B Bd lim A d S : ℕ}
+variable {ready : Stacks K → Prop} {pending : Key n U Z → Stacks K → Prop}
+
+/-- Scalar reads in the descriptor have independent time and space bounds.
+The caller's suspended frames are present throughout the subcall. -/
+def DescribeBounded (a : Actions K) (prog : Program (Key n U Z) (Scalar c)) (w v Bd S depth : ℕ)
+ (ready : Stacks K → Prop) : Prop := ∀ (q : Key n U Z) (fs : List (F n U Z c)) (aux : Stacks K),
+ fs.length ≤ depth → ready aux → ∃ t ≤ Bd, ∃ out, ready out ∧
+ a.describe.BoundedRun S t (atControl w v (.enter q) fs aux)
+ (match prog.describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false])
+
+/-- The descriptor subcall and the short local transitions share the same tapes. -/
+def boundedSpace (S A depth B w v e : ℕ) := max (S+1) (runSpace A depth B w v e)
+
+/-- Maximum one-step time allowance covering descriptor evaluation and the other engine
+transitions. -/
+def boundedStepTime (Bd B w v e : ℕ) := max (Bd+1) (stepBudget B w v e)
+
+omit [Fact p.Prime] [NeZero e] in
+private theorem clearSignal (w v : ℕ) (q : Ctl n U Z c) (fs : List (F n U Z c))
+ (out : Stacks K) (b : Bool) :
+ Function.update (atControl w v q fs out [b]) .condition [] = atControl w v q fs out := by
+ funext k
+ cases k with
+ | frame j => cases j <;> rfl
+ | _ => rfl
+
+private theorem step_bounded (spec : Contracts a prog w v B lim ready pending Bd)
+ (desc : DescribeBounded a prog w v Bd S d ready) (ha : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (cfg : Cfg n U Z c) (depth : cfg.2.length ≤ d) (range : InRange lim cfg) (cursor : CursorRange prog cfg)
+ (aux : Stacks K) (haux : ready aux) :
+ ∃ t ≤ boundedStepTime Bd B w v e, ∃ out, ready out ∧
+ SpaceRun (routine a).standalone (boundedSpace S A d B w v e) t
+ (some (label a cfg.1)) (atControl w v cfg.1 cfg.2 aux)
+ (some (label a (prog.step cfg).1)) (atControl w v (prog.step cfg).1 (prog.step cfg).2 out) := by
+ have short (h : (match cfg.1 with | .enter _ => Bd+1 | _ => stepBudget B w v e) = stepBudget B w v e) :
+ ∃ t ≤ boundedStepTime Bd B w v e, ∃ out, ready out ∧
+ SpaceRun (routine a).standalone (boundedSpace S A d B w v e) t
+ (some (label a cfg.1)) (atControl w v cfg.1 cfg.2 aux)
+ (some (label a (prog.step cfg).1)) (atControl w v (prog.step cfg).1 (prog.step cfg).2 out) := by
+ obtain ⟨t, ht, out, ho, run⟩ := step_runs_separate spec cfg range cursor aux haux
+ have hshort : t ≤ stepBudget B w v e := by
+ cases cEq : cfg.1 <;> simp only [cEq] at ht h <;> omega
+ have bounded := spaceRun_of_steps (cap := runSpace A d B w v e) run (fun k ↦
+ Nat.add_le_add (state_length cfg depth aux (ha aux haux) k) hshort)
+ exact ⟨t, hshort.trans (le_max_right ..), out, ho, bounded.mono_cap (le_max_right ..)⟩
+ obtain ⟨ctl, fs⟩ := cfg
+ cases ctl with
+ | scan | returned => exact short rfl
+ | enter q =>
+ obtain ⟨t, ht, out, ho, entered⟩ := desc q fs aux depth haux
+ have hroom : S+1 ≤ boundedSpace S A d B w v e := le_max_left ..
+ cases h : prog.describe q with
+ | inl r =>
+ rw [h] at entered
+ have linked := entered.linkRoutine (routine a) (fun j ↦ Sum.inr ⟨Call.describe, j⟩)
+ (some (.inl .described)) (fun _ ↦ rfl)
+ have bit := described_step a (atControl w v (.returned r) fs out [true]) true rfl
+ have pop := spaceRun_of_steps (cap := S+1) bit (fun k ↦ Nat.add_le_add_right (entered.final_cap k) 1)
+ rw [clearSignal] at pop
+ have run := (linked.mono_cap ((Nat.le_succ S).trans hroom)).trans (pop.mono_cap hroom)
+ refine ⟨t+1, (Nat.add_le_add_right ht 1).trans (le_max_left ..), out, ho, ?_⟩
+ simpa [Program.step, h, label, invoke, Actions.callee] using run
+ | inr k =>
+ rw [h] at entered
+ have linked := entered.linkRoutine (routine a) (fun j ↦ Sum.inr ⟨Call.describe, j⟩)
+ (some (.inl .described)) (fun _ ↦ rfl)
+ have bit := described_step a (atControl w v (.scan q k 0) fs out [false]) false rfl
+ have pop := spaceRun_of_steps (cap := S+1) bit (fun j ↦ Nat.add_le_add_right (entered.final_cap j) 1)
+ rw [clearSignal] at pop
+ have run := (linked.mono_cap ((Nat.le_succ S).trans hroom)).trans (pop.mono_cap hroom)
+ refine ⟨t+1, (Nat.add_le_add_right ht 1).trans (le_max_left ..), out, ho, ?_⟩
+ simpa [Program.step, h, label, invoke, Actions.callee] using run
+
+/-- Simulate the full Schur recursion with an exponential-time, polynomial-space
+descriptor while preserving both bounds across each linked action. -/
+theorem eval_run_bounded (spec : Contracts a prog w v B lim ready pending Bd)
+ (desc : DescribeBounded a prog w v Bd S d ready) (arity : prog.ArityLE lim)
+ (ha : ∀ s, ready s → ∀ k, (s k).length ≤ A) {steps : ℕ} {start finish : Cfg n U Z c}
+ (run : prog.Runs d steps start finish) (range : InRange lim start) (cursor : CursorRange prog start)
+ (aux : Stacks K) (haux : ready aux) :
+ ∃ t ≤ steps*boundedStepTime Bd B w v e, ∃ out, ready out ∧
+ SpaceRun (routine a).standalone (boundedSpace S A d B w v e) t
+ (some (label a start.1)) (atControl w v start.1 start.2 aux)
+ (some (label a finish.1)) (atControl w v finish.1 finish.2 out) := by
+ induction run generalizing aux with
+ | done cfg depth =>
+ refine ⟨0, by simp, aux, haux, .nil _ _ fun k ↦ ?_⟩
+ exact (state_length cfg depth aux (ha aux haux) k).trans ((Nat.le_add_right ..).trans (le_max_right ..))
+ | next depth _ ih =>
+ obtain ⟨t, ht, mid, hm, step⟩ := step_bounded spec desc ha _ depth range cursor aux haux
+ obtain ⟨u, hu, out, ho, rest⟩ := ih (inRange_step _ _ arity _ range) (cursorRange_step _ _ cursor) mid hm
+ refine ⟨_, ?_, out, ho, step.trans rest⟩
+ exact (Nat.add_le_add ht hu).trans_eq ((Nat.add_comm ..).trans (Nat.succ_mul ..).symm)
+
+/-- The physical root call returns the requested coefficient with a cap independent
+of the time spent inside scalar-entry queries. -/
+theorem eval_root_bounded {entry : Entry n (Scalar c)}
+ (spec : Contracts a (SchurKey.program (U := U) (Z := Z) entry) w v B (SchurKey.arityBound n U Z) ready pending Bd)
+ (desc : DescribeBounded a (SchurKey.program (U := U) (Z := Z) entry) w v Bd S
+ (Nat.clog 2 U+4+Nat.clog 2 n) ready)
+ (ha : ∀ s, ready s → ∀ k, (s k).length ≤ A)
+ (M : Matrix (Fin n) (Fin n) (Polynomial (Scalar c))) (he : ∀ i j z, entry i j z = (M i j).coeff z)
+ (u : Limit U) (z : Limit Z) (aux : Stacks K) (haux : ready aux) :
+ let depth := Nat.clog 2 U + 4 + Nat.clog 2 n
+ ∃ t ≤ (5 + 6*SchurKey.arityBound n U Z)^(depth+1)*boundedStepTime Bd B w v e + 1, ∃ out, ready out ∧
+ SpaceRun (routine a).standalone (boundedSpace S A depth B w v e) t (some (routine a).entry)
+ (atControl (c := c) w v (.enter (SchurKey.root (n := n) u z)) [] aux) none
+ (atControl w v (.returned ((M.charpolyRev.coeff u.val).coeff z.val)) ([] : List (F n U Z c)) out) := by
+ let depth := Nat.clog 2 U+4+Nat.clog 2 n
+ let finish : Cfg n U Z c := (.returned ((M.charpolyRev.coeff u.val).coeff z.val), [])
+ obtain ⟨m, hm, run⟩ := SchurKey.run M entry he u z
+ have startRange : InRange (SchurKey.arityBound n U Z) (c := c) (.enter (SchurKey.root (n := n) u z), []) := by
+ simp [InRange]
+ have startCursor : CursorRange (SchurKey.program entry) (.enter (SchurKey.root (n := n) u z), []) := by
+ simp [CursorRange]
+ obtain ⟨t,ht,out,ho,hr⟩ := eval_run_bounded spec desc (SchurKey.arity entry) ha run startRange startCursor aux haux
+ have stop := return_to_caller a (atControl w v finish.1 finish.2 out) rfl
+ have last : SpaceRun (routine a).standalone (runSpace A depth B w v e) 1
+ (some (.inl .returned)) (atControl w v finish.1 finish.2 out) none (atControl w v finish.1 finish.2 out) :=
+ spaceRun_of_steps stop fun k ↦ Nat.add_le_add
+ (state_length (d := depth) finish (Nat.zero_le _) out (ha _ ho) k) (by dsimp [stepBudget]; omega)
+ exact ⟨_, Nat.add_le_add_right (ht.trans (Nat.mul_le_mul_right _ hm)) _, out, ho,
+ hr.trans (last.mono_cap (le_max_right ..))⟩
+
+end RankQuery.Stack.Engine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackEngineSpec.lean b/lean/OAI/Computability/VPVNP/RankQueryStackEngineSpec.lean
new file mode 100644
index 0000000000..dfde61cc79
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackEngineSpec.lean
@@ -0,0 +1,165 @@
+import OAI.Computability.VPVNP.RankQueryStackNativeFrames
+
+/-! # Bank conventions at deterministic Schur subroutine boundaries -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine
+
+open RAMTape Evaluator.InputBank
+
+variable {n U Z p e : ℕ} {c : SliceArithmetic.Vector p e} {K : Type}
+
+/-- Abstract control of the evaluator specialized to Schur keys and encoded scalars. -/
+abbrev Ctl (n U Z : ℕ) (c : SliceArithmetic.Vector p e) := Control (Key n U Z) (Scalar c)
+/-- Abstract configuration of the Schur evaluator, including its stack of pending frames. -/
+abbrev Cfg (n U Z : ℕ) (c : SliceArithmetic.Vector p e) := Config (Key n U Z) (Scalar c)
+
+/-- Live register contents for an abstract control, encoding the query, scan count and
+accumulator when needed. -/
+def live (w v : ℕ) : Ctl n U Z c → Data
+ | .enter q => fields w [] q [] [] []
+ | .scan q k a => fields w [] q (UniversalCountStack.digits w k) (scalar v a) []
+ | .returned _ => fun _ => []
+
+/-- Encoded scalar on the result port of a returning control, and an empty result port during
+evaluation. -/
+def output (v : ℕ) : Ctl n U Z c → List Bool
+ | .returned a => scalar v a
+ | _ => []
+
+/-- Assemble live registers, saved frames, condition bits, result and auxiliary stacks at a
+control boundary. -/
+def atControl (w v : ℕ) (ctl : Ctl n U Z c) (fs : List (F n U Z c)) (aux : Stacks K)
+ (signal : List Bool := []) : Stacks (Port K) :=
+ store (live w v ctl) (history w v fs) signal (output v ctl) aux
+
+/-- Physical engine entry state corresponding to an abstract enter, scan or return control. -/
+def label (a : Actions K) : Ctl n U Z c → State a
+ | .enter _ => invoke a .describe
+ | .scan .. => invoke a .scan
+ | .returned _ => .inl .returned
+
+/-- Restored live-frame data after the engine has consumed the saved direction tag in field
+zero. -/
+def popped (w v : ℕ) (f : F n U Z c) : Data := Function.update (nativeFrame w v f) 0 []
+
+variable [DecidableEq K] [Fact p.Prime] [NeZero e]
+
+/-- Physical run contracts of the five arithmetic and routing subprograms.
+The engine implements the two frame operations itself. A pending state carries
+the computed child query in the dispatch output registers. -/
+structure Contracts (a : Actions K) (prog : Program (Key n U Z) (Scalar c)) (w v B lim : ℕ)
+ (ready : Stacks K → Prop) (pending : Key n U Z → Stacks K → Prop) (describeBudget : ℕ := B) : Prop where
+ describe (q : Key n U Z) (fs : List (F n U Z c)) (aux : Stacks K) : ready aux →
+ ∃ t ≤ describeBudget, ∃ out, ready out ∧ a.describe.Runs t (atControl w v (.enter q) fs aux)
+ (match prog.describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false])
+ scanZero (q : Key n U Z) (acc : Scalar c) (fs : List (F n U Z c)) (aux : Stacks K) : ready aux →
+ ∃ t ≤ B, ∃ out, ready out ∧ a.scan.Runs t (atControl w v (.scan q 0 acc) fs aux)
+ (atControl w v (.returned acc) fs out [true])
+ scanSucc (q : Key n U Z) (k : ℕ) (acc : Scalar c) (fs : List (F n U Z c)) (aux : Stacks K) :
+ k+1 ≤ lim → (∃ t, prog.describe q = .inr t ∧ k < t) → ready aux →
+ ∃ t ≤ B, ∃ out, pending (prog.left q k) out ∧ a.scan.Runs t (atControl w v (.scan q (k+1) acc) fs aux)
+ (store (nativeFrame w v (.left q k acc)) (history w v fs) [false] [] out)
+ activate (q : Key n U Z) (fs : List (F n U Z c)) (aux : Stacks K) : pending q aux →
+ ∃ t ≤ B, ∃ out, ready out ∧ a.activate.Runs t (store (fun _ => []) (history w v fs) [] [] aux)
+ (atControl w v (.enter q) fs out)
+ right (q : Key n U Z) (k : ℕ) (acc l : Scalar c) (fs : List (F n U Z c)) (aux : Stacks K) :
+ k < lim → (∃ t, prog.describe q = .inr t ∧ k < t) → ready aux →
+ ∃ t ≤ B, ∃ out, pending (prog.right q k) out ∧ a.right.Runs t
+ (store (popped w v (.left q k acc)) (history w v fs) [] (scalar v l) aux)
+ (store (nativeFrame w v (.right q k acc l)) (history w v fs) [] [] out)
+ multiplyAdd (q : Key n U Z) (k : ℕ) (acc l r : Scalar c) (fs : List (F n U Z c)) (aux : Stacks K) :
+ k < lim → ready aux →
+ ∃ t ≤ B, ∃ out, ready out ∧ a.multiplyAdd.Runs t
+ (store (popped w v (.right q k acc l)) (history w v fs) [] (scalar v r) aux)
+ (atControl w v (.scan q k (acc+l*r)) fs out)
+
+/-- The active scan count is at most `lim` and each suspended frame's remaining index is
+strictly below `lim`. -/
+def InRange (lim : ℕ) (cfg : Cfg n U Z c) : Prop :=
+ (match cfg.1 with | .scan _ k _ => k ≤ lim | _ => True) ∧ ∀ f ∈ cfg.2, f.remaining < lim
+
+omit [DecidableEq K] in
+theorem inRange_step (prog : Program (Key n U Z) (Scalar c)) (lim : ℕ) (hp : prog.ArityLE lim)
+ (cfg : Cfg n U Z c) (h : InRange lim cfg) : InRange lim (prog.step cfg) := by
+ obtain ⟨ctl, fs⟩ := cfg
+ cases ctl with
+ | enter q =>
+ cases he : prog.describe q with
+ | inl r => exact ⟨by simp [Program.step, he], by simpa [Program.step, he] using h.2⟩
+ | inr k => exact ⟨by simpa [Program.step, he] using hp q k he, by simpa [Program.step, he] using h.2⟩
+ | scan q k a =>
+ cases k with
+ | zero => exact ⟨trivial, h.2⟩
+ | succ k =>
+ refine ⟨trivial, ?_⟩
+ intro f hf
+ rcases List.mem_cons.mp hf with eq | hm
+ · subst f; exact h.1
+ · exact h.2 _ hm
+ | returned r =>
+ cases fs with
+ | nil => exact h
+ | cons f fs =>
+ have hk := h.2 f List.mem_cons_self
+ cases f with
+ | left q k a =>
+ refine ⟨trivial, ?_⟩
+ intro j hj
+ rcases List.mem_cons.mp hj with eq | hm
+ · subst j; exact hk
+ · exact h.2 _ (List.mem_cons_of_mem _ hm)
+ | right q k a l =>
+ exact ⟨Nat.le_of_lt hk, fun j hj => h.2 _ (List.mem_cons_of_mem _ hj)⟩
+
+/-- A suspended frame retains a legal child index of its own parent. This
+ensures the physical child dispatcher only sees indices in its node's arity. -/
+def CursorRange (prog : Program (Key n U Z) (Scalar c)) (cfg : Cfg n U Z c) : Prop :=
+ (match cfg.1 with | .scan q k _ => ∃ t, prog.describe q = .inr t ∧ k ≤ t | _ => True) ∧
+ ∀ f ∈ cfg.2, match f with
+ | .left q k _ | .right q k _ _ => ∃ t, prog.describe q = .inr t ∧ k < t
+
+omit [DecidableEq K] [Fact p.Prime] [NeZero e] in
+theorem cursorRange_step (prog : Program (Key n U Z) (Scalar c)) [Semiring (Scalar c)]
+ (cfg : Cfg n U Z c) (h : CursorRange prog cfg) : CursorRange prog (prog.step cfg) := by
+ obtain ⟨ctl, fs⟩ := cfg
+ cases ctl with
+ | enter q =>
+ cases he : prog.describe q with
+ | inl r => exact ⟨by simp [Program.step, he], by simpa [Program.step, he] using h.2⟩
+ | inr k =>
+ have hg : prog.step (.enter q,fs) = (.scan q k 0,fs) := by simp [Program.step, he]
+ rw [hg]; exact ⟨⟨k,he,le_rfl⟩,h.2⟩
+ | scan q k a =>
+ cases k with
+ | zero => exact ⟨trivial, h.2⟩
+ | succ k =>
+ refine ⟨trivial, fun f hf => ?_⟩
+ rcases List.mem_cons.mp hf with eq | hm
+ · subst f; exact h.1
+ · exact h.2 _ hm
+ | returned r =>
+ cases fs with
+ | nil => exact h
+ | cons f fs =>
+ have hk := h.2 f List.mem_cons_self
+ cases f with
+ | left q k a =>
+ refine ⟨trivial, fun j hj => ?_⟩
+ rcases List.mem_cons.mp hj with eq | hm
+ · subst j; exact hk
+ · exact h.2 _ (List.mem_cons_of_mem _ hm)
+ | right q k a l =>
+ obtain ⟨t,ht,hle⟩ := hk
+ exact ⟨⟨t,ht,Nat.le_of_lt hle⟩, fun j hj => h.2 _ (List.mem_cons_of_mem _ hj)⟩
+
+end RankQuery.Stack.Engine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackEngineStep.lean b/lean/OAI/Computability/VPVNP/RankQueryStackEngineStep.lean
new file mode 100644
index 0000000000..da50153527
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackEngineStep.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.RankQueryStackEngineSpec
+
+/-! # One abstract determinant transition in the linked bit-stack control -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine
+
+open RAMTape Evaluator.InputBank
+
+variable {n U Z p e : ℕ} {c : SliceArithmetic.Vector p e} {K : Type}
+variable [DecidableEq K] [Fact p.Prime] [NeZero e]
+
+private theorem setSignal (l h : Data) (f g r : List Bool) (s : Stacks K) :
+ Function.update (store l h f r s) .condition g = store l h g r s := by
+ funext k; cases k with
+ | frame i => cases i <;> rfl
+ | _ => rfl
+
+private theorem setDirection (l h : Data) (f r : List Bool) (s : Stacks K) :
+ Function.update (store l h f r s) (.frame (.inl 0)) [] = store (Function.update l 0 []) h f r s := by
+ funext k
+ cases k with
+ | frame j => cases j with
+ | inl i => by_cases hh : i = 0 <;> simp [store, Function.update, hh]
+ | inr i => rfl
+ | _ => rfl
+
+omit [Fact p.Prime] [NeZero e] in
+private theorem frameTag (w v : ℕ) (f : F n U Z c) (fs : List (F n U Z c)) :
+ ∃ b tail, history w v (f :: fs) 0 = b :: tail := by
+ cases f <;> exact ⟨true, _, rfl⟩
+
+/-- Time bound for simulating an abstract evaluator transition with the installed actions and
+ten encoded frame fields. -/
+def stepBudget (B w v e : ℕ) : ℕ := 4*(B+10*(3*max 1 (max w (e*v))+2)+5)
+
+variable {a : Actions K} {prog : Program (Key n U Z) (Scalar c)} {w v B lim Bd : ℕ}
+variable {ready : Stacks K → Prop} {pending : Key n U Z → Stacks K → Prop}
+
+omit [NeZero e] in
+private theorem saveActivate (spec : Contracts a prog w v B lim ready pending Bd)
+ (q : Key n U Z) (f : F n U Z c) (fs : List (F n U Z c)) (aux : Stacks K) (hp : pending q aux) :
+ ∃ t ≤ 10*(3*max 1 (max w (e*v))+2)+1+B, ∃ out, ready out ∧
+ StackRuns (routine a).standalone t (some (invoke a .save))
+ (store (nativeFrame w v f) (history w v fs) [] [] aux) (some (invoke a .describe))
+ (atControl w v (.enter q) (f :: fs) out) := by
+ obtain ⟨ts, hs, save⟩ := save_runs a w v f fs [] aux
+ obtain ⟨ta, ha, out, ho, active⟩ := spec.activate q (f :: fs) aux hp
+ exact ⟨_, Nat.add_le_add hs ha, out, ho, (call_runs a .save save).trans (call_runs a .activate active)⟩
+
+omit [Fact p.Prime] [NeZero e] in
+private theorem restoreDirection (w v : ℕ) (f : F n U Z c) (fs : List (F n U Z c)) (r : Scalar c)
+ (aux : Stacks K) :
+ ∃ t ≤ 10*(3*max 1 (max w (e*v))+1)+4, StackRuns (routine a).standalone t (some (.inl .returned))
+ (atControl w v (.returned r) (f :: fs) aux)
+ (some (invoke a (match f with | .left .. => .right | .right .. => .multiplyAdd)))
+ (store (popped w v f) (history w v fs) [] (scalar v r) aux) := by
+ obtain ⟨b, tail, hh⟩ := frameTag w v f fs
+ have start := return_to_frame a (atControl w v (.returned r) (f :: fs) aux) b tail hh
+ obtain ⟨t, ht, hr⟩ := restore_runs a w v f fs (scalar v r) aux
+ let s := store (nativeFrame w v f) (history w v fs) [] (scalar v r) aux
+ cases f with
+ | left q k a' =>
+ have h := direction_step a s false rfl
+ rw [show Function.update s (.frame (.inl 0)) [] = _ from setDirection ..] at h
+ exact ⟨_, by omega, (start.trans (call_runs a .restore hr)).trans h⟩
+ | right q k a' l =>
+ have h := direction_step a s true rfl
+ rw [show Function.update s (.frame (.inl 0)) [] = _ from setDirection ..] at h
+ exact ⟨_, by omega, (start.trans (call_runs a .restore hr)).trans h⟩
+
+/-- A transition of the typed Schur continuation machine uses a fixed number
+of subroutine calls, including both frame operations when switching operands. -/
+theorem step_runs_separate (spec : Contracts a prog w v B lim ready pending Bd) (cfg : Cfg n U Z c)
+ (range : InRange lim cfg) (cursor : CursorRange prog cfg) (aux : Stacks K) (ha : ready aux) :
+ ∃ t ≤ (match cfg.1 with | .enter _ => Bd+1 | _ => stepBudget B w v e), ∃ out, ready out ∧ StackRuns (routine a).standalone t
+ (some (label a cfg.1)) (atControl w v cfg.1 cfg.2 aux) (some (label a (prog.step cfg).1))
+ (atControl w v (prog.step cfg).1 (prog.step cfg).2 out) := by
+ obtain ⟨ctl, fs⟩ := cfg
+ cases ctl with
+ | enter q =>
+ obtain ⟨t, ht, out, ho, desc⟩ := spec.describe q fs aux ha
+ cases h : prog.describe q with
+ | inl r =>
+ rw [h] at desc
+ have hs := described_step a (atControl w v (.returned r) fs out [true]) true rfl
+ unfold atControl at hs
+ rw [setSignal] at hs
+ have hr := (call_runs a .describe desc).trans hs
+ refine ⟨t+1, Nat.add_le_add_right ht _, out, ho, ?_⟩
+ simpa [Program.step, h, label, atControl] using hr
+ | inr k =>
+ rw [h] at desc
+ have hs := described_step a (atControl w v (.scan q k 0) fs out [false]) false rfl
+ unfold atControl at hs
+ rw [setSignal] at hs
+ have hr := (call_runs a .describe desc).trans hs
+ refine ⟨t+1, Nat.add_le_add_right ht _, out, ho, ?_⟩
+ simpa [Program.step, h, label, atControl] using hr
+ | scan q k acc =>
+ cases k with
+ | zero =>
+ obtain ⟨t, ht, out, ho, scan⟩ := spec.scanZero q acc fs aux ha
+ have hs := scanned_step a (atControl w v (.returned acc) fs out [true]) true rfl
+ unfold atControl at hs
+ rw [setSignal] at hs
+ exact ⟨_, by change _ ≤ stepBudget B w v e; unfold stepBudget; omega, out, ho, (call_runs a .scan scan).trans hs⟩
+ | succ k =>
+ obtain ⟨t, ht, next, hn, scan⟩ := spec.scanSucc q k acc fs aux range.1 cursor.1 ha
+ let frame := Frame.left q k acc
+ have hs := scanned_step a (store (nativeFrame w v frame) (history w v fs) [false] [] next) false rfl
+ rw [setSignal] at hs
+ obtain ⟨u, hu, out, ho, rest⟩ := saveActivate spec (prog.left q k) frame fs next hn
+ exact ⟨_, by change _ ≤ stepBudget B w v e; unfold stepBudget; omega, out, ho, ((call_runs a .scan scan).trans hs).trans rest⟩
+ | returned r =>
+ cases fs with
+ | nil => exact ⟨0, Nat.zero_le _, aux, ha, .nil ..⟩
+ | cons f fs =>
+ have hk := range.2 f List.mem_cons_self
+ obtain ⟨s, hs, head⟩ := restoreDirection (a := a) w v f fs r aux
+ cases f with
+ | left q k acc =>
+ obtain ⟨t, ht, next, hn, right⟩ := spec.right q k acc r fs aux hk (cursor.2 _ List.mem_cons_self) ha
+ obtain ⟨u, hu, out, ho, tail⟩ := saveActivate spec (prog.right q k) (.right q k acc r) fs next hn
+ exact ⟨_, by change _ ≤ stepBudget B w v e; unfold stepBudget; omega, out, ho, (head.trans (call_runs a .right right)).trans tail⟩
+ | right q k acc l =>
+ obtain ⟨t, ht, out, ho, mac⟩ := spec.multiplyAdd q k acc l r fs aux hk ha
+ exact ⟨_, by change _ ≤ stepBudget B w v e; unfold stepBudget; omega, out, ho, head.trans (call_runs a .multiplyAdd mac)⟩
+
+theorem step_runs (spec : Contracts a prog w v B lim ready pending) (cfg : Cfg n U Z c)
+ (range : InRange lim cfg) (cursor : CursorRange prog cfg) (aux : Stacks K) (ha : ready aux) :
+ ∃ t ≤ stepBudget B w v e, ∃ out, ready out ∧ StackRuns (routine a).standalone t
+ (some (label a cfg.1)) (atControl w v cfg.1 cfg.2 aux) (some (label a (prog.step cfg).1))
+ (atControl w v (prog.step cfg).1 (prog.step cfg).2 out) := by
+ obtain ⟨t,ht,out,ho,run⟩ := step_runs_separate spec cfg range cursor aux ha
+ refine ⟨t, ?_, out, ho, run⟩
+ cases h : cfg.1 <;> rw [h] at ht <;> first | exact ht | change t ≤ B+1 at ht; unfold stepBudget; omega
+
+end RankQuery.Stack.Engine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackExpressions.lean b/lean/OAI/Computability/VPVNP/RankQueryStackExpressions.lean
new file mode 100644
index 0000000000..ce67a81756
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackExpressions.lean
@@ -0,0 +1,161 @@
+import OAI.Computability.VPVNP.RankQueryStackRegister
+
+/-!
+# Compiling the arithmetic expressions of a Schur query
+
+Each syntax node receives one fixed scratch register. Disjoint intervals
+serve the two subexpressions. The proofs track the result register and show
+that registers outside the assigned interval retain their values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Dispatch
+
+open BurstRAM PrivateRAM
+
+namespace Expr
+
+variable {r w : ℕ}
+
+/-- Number of nodes in an expression tree, used to allocate disjoint scratch slots for its
+subexpressions. -/
+def nodes : Expr → ℕ
+ | .reg _ | .lit _ => 1
+ | .op _ l r => 1 + l.nodes + r.nodes
+
+theorem nodes_pos (e : Expr) : 0 < e.nodes := by cases e <;> simp [nodes]
+
+/-- All intermediate natural-number results fit the register width. -/
+def Fits (w : ℕ) (env : Fin 8 → ℕ) (e : Expr) : Prop :=
+ e.eval env < 2^w ∧ match e with
+ | .reg _ | .lit _ => True
+ | .op _ l r => l.Fits w env ∧ r.Fits w env
+
+/-- Compile an expression into register code that writes its value to the scratch slot at
+`start`. -/
+def compile (arg : Fin 8 → Fin r) (slot : ℕ → Fin r) (start : ℕ) : Expr → RegCode r
+ | .reg i => .copy (slot start) (arg i)
+ | .lit n => .lit (slot start) n
+ | .op a l r => .seq (l.compile arg slot (start+1)) <|
+ .seq (r.compile arg slot (start+1+l.nodes)) <|
+ .op (slot start) a (slot (start+1)) (slot (start+1+l.nodes))
+
+/-- The compilation never writes outside the finite register interval
+assigned to this expression. -/
+theorem preserves (e : Expr) (arg : Fin 8 → Fin r) (slot : ℕ → Fin r) (start : ℕ)
+ (rs : Regs r w) (j : Fin r)
+ (h : ∀ i, start ≤ i → i < start+e.nodes → slot i ≠ j) :
+ (e.compile arg slot start).exec rs j = rs j := by
+ induction e generalizing start rs with
+ | reg i =>
+ simp [compile, RegCode.exec, Function.update_of_ne (h start le_rfl (by simp [nodes])).symm]
+ | lit n =>
+ simp [compile, RegCode.exec, Function.update_of_ne (h start le_rfl (by simp [nodes])).symm]
+ | op a l r ihl ihr =>
+ have hroot := h start le_rfl (by simp [nodes])
+ simp only [compile, RegCode.exec, Function.update_of_ne hroot.symm]
+ rw [ihr, ihl] <;> intro i hi hfin <;> apply h i <;> (try simp only [nodes]) <;> omega
+
+/-- Interpreting a compiled expression reads the eight input words and
+writes exactly its natural value to the first scratch register. -/
+theorem compile_correct (e : Expr) (env : Fin 8 → ℕ) (arg : Fin 8 → Fin r)
+ (slot : ℕ → Fin r) (cap start : ℕ) (rs : Regs r w) (hfit : e.Fits w env)
+ (hr : ∀ i, (rs (arg i)).val = env i) (hcap : start + e.nodes ≤ cap)
+ (hinj : ∀ i < cap, ∀ j < cap, slot i = slot j → i = j)
+ (hsep : ∀ i < cap, ∀ j, slot i ≠ arg j) :
+ ((e.compile arg slot start).exec rs (slot start)).val = e.eval env := by
+ induction e generalizing start rs with
+ | reg i => simpa [compile, RegCode.exec, eval] using hr i
+ | lit n =>
+ simp only [compile, RegCode.exec, Function.update_self, eval]
+ change (Fin.ofNat (2^w) n).val = n
+ exact Nat.mod_eq_of_lt hfit.1
+ | op a l r ihl ihr =>
+ let left := start+1
+ let right := start+1+l.nodes
+ let rsL := (l.compile arg slot left).exec rs
+ let rsR := (r.compile arg slot right).exec rsL
+ simp only [compile, RegCode.exec, Function.update_self]
+ change ((a.word (rsR (slot left)) (rsR (slot right))).val) = _
+ have hc : start + (1+l.nodes+r.nodes) ≤ cap := hcap
+ have hcL : left+l.nodes ≤ cap := by dsimp [left]; omega
+ have hcR : right+r.nodes ≤ cap := by dsimp [right]; omega
+ have hsafe : l.Fits w env ∧ r.Fits w env := hfit.2
+ have hL := ihl left rs hsafe.1 hr hcL
+ have hinput (i : Fin 8) : (rsL (arg i)).val = env i := by
+ change ((l.compile arg slot left).exec rs (arg i)).val = _
+ rw [preserves l arg slot left rs (arg i) (fun j _ hj => hsep j (by omega) i)]
+ exact hr i
+ have hR := ihr right rsL hsafe.2 hinput hcR
+ have hkeep : rsR (slot left) = rsL (slot left) := by
+ apply preserves
+ intro j hj hk he
+ have heq := hinj j (by omega) left (by have := l.nodes_pos; omega) he
+ dsimp [left, right] at hj heq
+ have := l.nodes_pos
+ omega
+ have vL : (rsR (slot left)).val = l.eval env := hkeep ▸ hL
+ have vR : (rsR (slot right)).val = r.eval env := hR
+ rw [a.word_val _ _ (by simpa only [vL, vR, eval] using hfit.1), vL, vR]
+ rfl
+
+/-- A syntax-dependent coefficient in the linear word-width bound. -/
+def weight : Expr → ℕ
+ | .reg _ => 1
+ | .lit n => n+1
+ | .op _ l r => l.weight+r.weight+1
+
+theorem fits_mono {env : Fin 8 → ℕ} (e : Expr) {u v : ℕ} (h : e.Fits u env) (hu : u ≤ v) :
+ e.Fits v env := by
+ induction e with
+ | reg | lit => exact ⟨h.1.trans_le (Nat.pow_le_pow_right (by decide) hu), trivial⟩
+ | op a l r ihl ihr => exact ⟨h.1.trans_le (Nat.pow_le_pow_right (by decide) hu), ihl h.2.1, ihr h.2.2⟩
+
+/-- A width linear in the input bit bound suffices for any fixed expression. -/
+theorem fits_weight (e : Expr) (p : ℕ) (env : Fin 8 → ℕ) (he : ∀ i, env i < 2^p) :
+ e.Fits ((p+1)*e.weight) env := by
+ induction e with
+ | reg i =>
+ exact ⟨(he i).trans_le (Nat.pow_le_pow_right (by decide) (by simp [weight])), trivial⟩
+ | lit n =>
+ have hn : n < 2^n := Nat.lt_two_pow_self
+ exact ⟨hn.trans_le (Nat.pow_le_pow_right (by decide) (by simp [weight, Nat.add_mul]; omega)), trivial⟩
+ | op a l r ihl ihr =>
+ let L := (p+1)*l.weight
+ let R := (p+1)*r.weight
+ let W := (p+1)*(op a l r).weight
+ have hw : W = L + R + (p+1) := by simp [W,L,R,weight,Nat.mul_add]
+ have hl : l.eval env < 2^L := by cases l <;> exact ihl.1
+ have hr : r.eval env < 2^R := by cases r <;> exact ihr.1
+ have hL : 1 ≤ 2^L := Nat.one_le_pow _ _ (by decide)
+ have hR : 1 ≤ 2^R := Nat.one_le_pow _ _ (by decide)
+ have hbig : 2^L*2^R*2 ≤ 2^W := by
+ rw [hw, pow_add, pow_add]
+ apply Nat.mul_le_mul_left
+ exact (Nat.pow_le_pow_right (n := 2) (by decide) (show 1 ≤ p+1 by omega))
+ have hlr := Nat.mul_le_mul_left (2^L) hR
+ have hrl := Nat.mul_le_mul_right (2^R) hL
+ refine ⟨?_, fits_mono l ihl (by change L ≤ W; omega), fits_mono r ihr (by change R ≤ W; omega)⟩
+ change a.eval (l.eval env) (r.eval env) < 2^W
+ have hlW : 2^L ≤ 2^W := Nat.pow_le_pow_right (by decide) (by omega)
+ cases a with
+ | add => change l.eval env + r.eval env < 2^W; simp only [Nat.mul_one, Nat.one_mul] at hlr hrl; omega
+ | sub => exact (Nat.sub_le ..).trans_lt (hl.trans_le hlW)
+ | mul =>
+ have hm := Nat.mul_le_mul hl.le hr.le
+ have hp := Nat.mul_pos (Nat.zero_lt_of_lt hl) (Nat.zero_lt_of_lt hr)
+ change l.eval env * r.eval env < 2^W
+ omega
+ | div => exact (Nat.div_le_self ..).trans_lt (hl.trans_le hlW)
+ | mod => exact (Nat.mod_le ..).trans_lt (hl.trans_le hlW)
+
+end Expr
+
+end RankQuery.Stack.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackField.lean b/lean/OAI/Computability/VPVNP/RankQueryStackField.lean
new file mode 100644
index 0000000000..3ccffe6e9d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackField.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.RankQueryStackScan
+import OAI.Computability.VPVNP.SliceArithmeticPower
+import OAI.Computability.VPVNP.SliceArithmeticWork
+
+/-!
+# Native coefficients for the determinant stack
+
+Each scalar in a continuation is one canonical base-`p` word with `e` digits.
+The product unpacks both words, uses Horner multiplication modulo the advised
+monic polynomial, and packs the reduced answer. The interpretation in the
+advised quotient is an injective ring homomorphism.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+open SliceArithmetic
+
+/-- Numeric scalar representation with a fixed advised modulus. -/
+structure Scalar {p e : ℕ} (c : Vector p e) where
+ /-- Packed index of the scalar's `e` base-`p` coordinates. -/
+ code : Fin (p^e)
+ deriving DecidableEq
+
+namespace Scalar
+
+variable {p e : ℕ} {c : Vector p e}
+
+/-- Pack a vector of prime-field coordinates into its finite scalar code. -/
+def pack (c : Vector p e) (v : Vector p e) : Scalar c := ⟨finFunctionFinEquiv v⟩
+
+/-- Decode the scalar's packed index into its vector of prime-field coordinates. -/
+def digits (s : Scalar c) : Vector p e := finFunctionFinEquiv.symm s.code
+
+@[simp] theorem digits_pack (v : Vector p e) : (pack c v).digits = v := finFunctionFinEquiv.symm_apply_apply v
+
+@[simp] theorem pack_digits (s : Scalar c) : pack c s.digits = s := by
+ cases s; simp [pack, digits]
+
+/-- Evaluate the decoded coordinate polynomial at the adjoined root of the modulus. -/
+noncomputable def interpret (s : Scalar c) : AdjoinRoot (modulus c) :=
+ SliceArithmetic.value (modulus c) s.digits
+
+variable [Fact p.Prime] [NeZero e]
+
+omit [NeZero e] in
+theorem interpret_injective (c : Vector p e) : Function.Injective (interpret (c := c)) := by
+ intro a b hab
+ have hd := value_injective (modulus_monic c) (modulus_natDegree c) hab
+ simpa only [pack_digits] using congrArg (pack c) hd
+
+instance : Zero (Scalar c) := ⟨pack c (SliceArithmetic.zero p e)⟩
+instance : One (Scalar c) := ⟨pack c (SliceArithmetic.one p e)⟩
+instance : Add (Scalar c) := ⟨fun a b => pack c (SliceArithmetic.add a.digits b.digits)⟩
+/-- Materialize each round of the extension-field product before the next round. -/
+def product (a b : Scalar c) : Scalar c :=
+ let result := Stream.product (List.ofFn c) (List.ofFn a.digits) (List.ofFn b.digits)
+ pack c fun i => result.coefficients[i.val]?.getD 0
+
+instance : Mul (Scalar c) := ⟨product⟩
+
+omit [NeZero e] in
+theorem product_eq (a b : Scalar c) : a*b = pack c (SliceArithmetic.mul c a.digits b.digits) := by
+ change product a b = _
+ unfold product
+ rw [Stream.product_correct]
+ apply congrArg (pack c)
+ funext i
+ simp [i.isLt]
+instance : Neg (Scalar c) := ⟨fun a => pack c (scale (-1) a.digits)⟩
+instance : Sub (Scalar c) := ⟨fun a b => a + -b⟩
+instance : SMul ℕ (Scalar c) := ⟨fun n a => pack c (scale ((ZMod.finEquiv p).symm n) a.digits)⟩
+instance : SMul ℤ (Scalar c) := ⟨fun n a => pack c (scale ((ZMod.finEquiv p).symm n) a.digits)⟩
+instance : Pow (Scalar c) ℕ := ⟨fun a n => pack c (SliceArithmetic.pow c a.digits n)⟩
+instance : NatCast (Scalar c) := ⟨fun n => n • (1 : Scalar c)⟩
+instance : IntCast (Scalar c) := ⟨fun n => n • (1 : Scalar c)⟩
+
+omit [NeZero e] in
+private theorem map_zero : interpret (0 : Scalar c) = 0 := by
+ change value (modulus c) (pack c (SliceArithmetic.zero p e)).digits = _
+ simp
+
+private theorem map_one : interpret (1 : Scalar c) = 1 := by
+ change value (modulus c) (pack c (SliceArithmetic.one p e)).digits = _
+ simp
+
+omit [NeZero e] in
+private theorem map_add (a b : Scalar c) : interpret (a+b) = interpret a + interpret b := by
+ change value (modulus c) (pack c (SliceArithmetic.add a.digits b.digits)).digits = _
+ rw [digits_pack, value_add]; rfl
+
+omit [NeZero e] in
+private theorem map_mul (a b : Scalar c) : interpret (a*b) = interpret a * interpret b := by
+ rw [product_eq]
+ change value (modulus c) (pack c (SliceArithmetic.mul c a.digits b.digits)).digits = _
+ rw [digits_pack, value_mul]; rfl
+
+omit [NeZero e] in
+private theorem map_neg (a : Scalar c) : interpret (-a) = -interpret a := by
+ change value (modulus c) (pack c (scale (-1) a.digits)).digits = _
+ simp [cast_val_eq_finEquiv, interpret]
+
+omit [NeZero e] in
+private theorem map_nsmul (n : ℕ) (a : Scalar c) : interpret (n • a) = n • interpret a := by
+ change value (modulus c) (pack c (scale ((ZMod.finEquiv p).symm n) a.digits)).digits = _
+ simp [cast_val_eq_finEquiv, interpret, nsmul_eq_mul]
+
+omit [NeZero e] in
+private theorem map_zsmul (n : ℤ) (a : Scalar c) : interpret (n • a) = n • interpret a := by
+ change value (modulus c) (pack c (scale ((ZMod.finEquiv p).symm n) a.digits)).digits = _
+ simp [cast_val_eq_finEquiv, interpret, zsmul_eq_mul]
+
+private theorem map_pow (a : Scalar c) (n : ℕ) : interpret (a^n) = (interpret a)^n := by
+ change value (modulus c) (pack c (SliceArithmetic.pow c a.digits n)).digits = _
+ rw [digits_pack, value_pow]; rfl
+
+instance : CommRing (Scalar c) := fast_instance%
+ (interpret_injective c).commRing _ map_zero map_one map_add map_mul map_neg
+ (fun x y => by change interpret (x + -y) = _; rw [map_add, map_neg, sub_eq_add_neg])
+ map_nsmul map_zsmul map_pow
+ (fun n => by change interpret (n • (1 : Scalar c)) = _; rw [map_nsmul, map_one, nsmul_eq_mul, mul_one])
+ (fun n => by change interpret (n • (1 : Scalar c)) = _; rw [map_zsmul, map_one, zsmul_eq_mul, mul_one])
+
+/-- Ring homomorphism interpreting encoded scalars in the algebra obtained by adjoining a root
+of the modulus. -/
+noncomputable def interpretation (c : Vector p e) : Scalar c →+* AdjoinRoot (modulus c) where
+ toFun := interpret
+ map_zero' := map_zero
+ map_one' := map_one
+ map_add' := map_add
+ map_mul' := map_mul
+
+omit [Fact p.Prime] [NeZero e] in
+/-- Every scalar occupies at most `e * clog 2 p` bits. -/
+theorem code_lt (a : Scalar c) : a.code.val < 2 ^ (e * Nat.clog 2 p) := calc
+ _ < p^e := a.code.isLt
+ _ ≤ (2^Nat.clog 2 p)^e := Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) _
+ _ = _ := by rw [← pow_mul, Nat.mul_comm]
+
+end Scalar
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackFrameField.lean b/lean/OAI/Computability/VPVNP/RankQueryStackFrameField.lean
new file mode 100644
index 0000000000..85868b6b59
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackFrameField.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.EvaluatorInputBank
+
+/-!
+# Saving and restoring one variable-length Schur frame field
+
+Saving empties the live register and prepends the tagged field to its history
+stack. Popping uses the evaluator's existing self-delimiting field reader.
+Both routines use a fixed control independent of the register width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.FrameStore
+
+open RAMTape Evaluator.InputBank
+
+/-- Control phases for moving a field's bits into its delimited history encoding. -/
+inductive WritePhase where
+ | start | scan | payload (b : Bool) | tag
+ deriving DecidableEq, Fintype
+
+private abbrev pair (value history : List Bool) : Stacks (Option Unit) :=
+ frame history (fun _ => value)
+
+private def writer : Routine (Option Unit) WritePhase where
+ entry := .start
+ code
+ | .start => .push none false (some .scan)
+ | .scan => .pop (some ()) fun b => b.map .payload
+ | .payload b => .push none b (some .tag)
+ | .tag => .push none true (some .scan)
+
+private theorem update_value (s h x : List Bool) :
+ Function.update (pair s h) (some ()) x = pair x h := by
+ funext k; cases k with
+ | none => rfl
+ | some v => cases v; rfl
+
+private theorem update_history (s h x : List Bool) :
+ Function.update (pair s h) none x = pair s x := by
+ funext k; cases k with
+ | none => rfl
+ | some v => cases v; rfl
+
+private theorem append_bit (pre : List Bool) (b : Bool) :
+ fieldBits (pre ++ [b]) = true :: b :: fieldBits pre := by
+ simp only [fieldBits, List.reverse_append, List.reverse_singleton, List.singleton_append]
+ rfl
+
+private theorem scan_runs (rest pre h : List Bool) :
+ StackRuns writer.standalone (3*rest.length + 1) (some .scan)
+ (pair rest (fieldBits pre ++ h)) none (pair [] (fieldBits (pre ++ rest) ++ h)) := by
+ induction rest generalizing pre with
+ | nil =>
+ refine .cons (.pop rfl) ?_
+ simp only [List.append_nil, pair, frame, List.head?_nil, List.tail_nil, Option.map_none, update_value]
+ exact .nil ..
+ | cons b rest ih =>
+ rw [show 3*(b::rest).length+1 = ((3*rest.length+1)+1)+1+1 by simp; omega]
+ refine .cons (.pop rfl) ?_
+ simp only [pair, frame, List.head?_cons, List.tail_cons, Option.map_some, update_value]
+ refine .cons (.push rfl) ?_
+ simp only [pair, frame, update_history]
+ refine .cons (.push rfl) ?_
+ simpa only [append_bit, List.cons_append, List.append_assoc, List.nil_append, update_history,
+ pair, frame] using ih (pre ++ [b])
+
+private theorem writer_runs (value history : List Bool) :
+ writer.Runs (3*value.length+2) (pair value history) (pair [] (fieldBits value ++ history)) := by
+ refine .cons (.push rfl) ?_
+ rw [update_history]
+ exact scan_runs value [] history
+
+private theorem reader_runs (value history old : List Bool) :
+ (readField ()).Runs (3*value.length+1) (pair old (fieldBits value ++ history))
+ (pair (value ++ old) history) := by
+ have he : Function.update (fun _ : Unit => old) () (value ++ old) = fun _ => value ++ old := by
+ funext i; cases i; rfl
+ simpa only [pair, he] using readField_runs () value history (fun _ : Unit => old)
+
+/-- The ten live-field ports together with the ten corresponding history ports. -/
+abbrev Port := Fin 10 ⊕ Fin 10
+
+private def fieldPorts (i : Fin 10) : Option Unit → Port
+ | none => .inr i
+ | some () => .inl i
+
+private theorem fieldPorts_injective (i : Fin 10) : Function.Injective (fieldPorts i) := by
+ intro a b h
+ cases a <;> cases b <;> simp_all [fieldPorts]
+
+/-- Move the live field at index `i` into its history stack using the frame-field encoding. -/
+def pushField (i : Fin 10) : FiniteRoutine Port := (FiniteRoutine.ofRoutine writer).onPorts (fieldPorts i)
+
+/-- Restore the most recently saved field at index `i` from its history stack. -/
+def popField (i : Fin 10) : FiniteRoutine Port :=
+ (FiniteRoutine.ofRoutine (readField ())).onPorts (fieldPorts i)
+
+/-- Combine the live and history banks into the stack state of the frame store. -/
+def registers (live history : Fin 10 → List Bool) : Stacks Port := Sum.elim live history
+
+/-- Move one live field to its history, preserving every other field. -/
+theorem pushField_runs (i : Fin 10) (live hist : Fin 10 → List Bool) :
+ (pushField i).Runs (3*(live i).length+2) (registers live hist)
+ (registers (Function.update live i []) (Function.update hist i (fieldBits (live i) ++ hist i))) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (fieldPorts_injective i) (writer_runs ..)
+ · intro k; cases k <;> rfl
+ · intro k; cases k <;> simp [registers, fieldPorts, pair, frame]
+ · intro j hj
+ cases j with
+ | inl j => exact Function.update_of_ne (show j ≠ i from fun he => hj (some ()) (congrArg Sum.inl he.symm)) ..
+ | inr j => exact Function.update_of_ne (show j ≠ i from fun he => hj none (congrArg Sum.inr he.symm)) ..
+
+/-- Restore the top self-delimiting field and retain the rest of its history. -/
+theorem popField_runs (i : Fin 10) (live hist : Fin 10 → List Bool) (value tail : List Bool)
+ (h : hist i = fieldBits value ++ tail) :
+ (popField i).Runs (3*value.length+1) (registers live hist)
+ (registers (Function.update live i (value ++ live i)) (Function.update hist i tail)) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (fieldPorts_injective i) (reader_runs value tail (live i))
+ · intro k; cases k with
+ | none => exact h
+ | some => rfl
+ · intro k; cases k <;> simp [registers, fieldPorts, pair, frame]
+ · intro j hj
+ cases j with
+ | inl j => exact Function.update_of_ne (show j ≠ i from fun he => hj (some ()) (congrArg Sum.inl he.symm)) ..
+ | inr j => exact Function.update_of_ne (show j ≠ i from fun he => hj none (congrArg Sum.inr he.symm)) ..
+
+end RankQuery.Stack.FrameStore
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackFrames.lean b/lean/OAI/Computability/VPVNP/RankQueryStackFrames.lean
new file mode 100644
index 0000000000..a20403d6a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackFrames.lean
@@ -0,0 +1,179 @@
+import OAI.Computability.VPVNP.RankQueryStackFrameField
+import OAI.Computability.VPVNP.RankQueryStackCodec
+
+/-!
+# Fixed bit-stack controls for Schur continuations
+
+Ten independently tagged histories form one synchronized continuation stack.
+The histories keep earlier frames intact through calls and returns. The routines
+below require only the current ten live registers, and execute the same control
+for every stack depth and register width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.FrameStore
+
+open RAMTape Evaluator.InputBank
+
+private def batch (op : Fin 10 → FiniteRoutine Port) : List (Fin 10) → FiniteRoutine Port
+ | [] => .ret
+ | i :: is => (batch op is).followedBy (op i)
+
+/-- Save all ten live fields into their respective history stacks. -/
+def push : FiniteRoutine Port := batch pushField (List.finRange 10)
+/-- Restore all ten fields of the most recently saved frame. -/
+def pop : FiniteRoutine Port := batch popField (List.finRange 10)
+
+variable {n U Z p e : ℕ} {c : SliceArithmetic.Vector p e}
+
+private abbrev Data := Fin 10 → List Bool
+
+/-- The newest saved field is first at every history port. -/
+def histories (width : ℕ) (fs : List (Frame.SchurFrame n U Z c)) : Data :=
+ fun i => fs.flatMap (fun f => fieldBits (f.bits width i))
+
+private theorem histories_cons (width : ℕ) (f : Frame.SchurFrame n U Z c) (fs : List (Frame.SchurFrame n U Z c)) :
+ histories width (f :: fs) = fun i => fieldBits (f.bits width i) ++ histories width fs i := by
+ funext i; simp [histories]
+
+private def selected (ks : List (Fin 10)) (yes no : Data) : Data := fun i =>
+ if i ∈ ks then yes i else no i
+
+private theorem update_selected (ks : List (Fin 10)) (yes no : Data) (j : Fin 10) :
+ Function.update (selected ks yes no) j (yes j) = selected (j :: ks) yes no := by
+ funext i
+ by_cases h : i = j <;> simp [selected, h]
+
+private theorem selected_nil (yes no : Data) : selected [] yes no = no := by funext i; simp [selected]
+
+private theorem selected_all (yes no : Data) : selected (List.finRange 10) yes no = yes := by
+ funext i; simp [selected]
+
+private theorem push_partial (ks : List (Fin 10)) (live hist : Data) (hks : ks.Nodup) :
+ (batch pushField ks).Runs ((ks.map (fun i => 3*(live i).length+2)).sum+1) (registers live hist)
+ (registers (selected ks (fun _ => []) live)
+ (selected ks (fun i => fieldBits (live i) ++ hist i) hist)) := by
+ induction ks with
+ | nil =>
+ rw [selected_nil, selected_nil]
+ simp only [List.map_nil, List.sum_nil, Nat.zero_add]
+ exact StackRuns.cons (.goto rfl) (.nil ..)
+ | cons i ks ih =>
+ let l := selected ks (fun _ => []) live
+ let h := selected ks (fun i => fieldBits (live i) ++ hist i) hist
+ have hl : l i = live i := by simp [l, selected, hks.notMem]
+ have hh : h i = hist i := by simp [h, selected, hks.notMem]
+ have step := pushField_runs i l h
+ rw [hl, hh] at step
+ have sl : Function.update l i [] = selected (i :: ks) (fun _ => []) live := update_selected ..
+ have sh : Function.update h i (fieldBits (live i) ++ hist i) =
+ selected (i :: ks) (fun j => fieldBits (live j) ++ hist j) hist := update_selected ..
+ rw [sl, sh] at step
+ have both := FiniteRoutine.Runs.followedBy (ih hks.of_cons) step
+ simp only [batch, List.map_cons, List.sum_cons]
+ convert both using 1
+ omega
+
+private theorem pop_partial (ks : List (Fin 10)) (live hist : Data) (hks : ks.Nodup) :
+ (batch popField ks).Runs ((ks.map (fun i => 3*(live i).length+1)).sum+1)
+ (registers (fun _ => []) (fun i => fieldBits (live i) ++ hist i))
+ (registers (selected ks live (fun _ => []))
+ (selected ks hist (fun i => fieldBits (live i) ++ hist i))) := by
+ induction ks with
+ | nil =>
+ rw [selected_nil, selected_nil]
+ simp only [List.map_nil, List.sum_nil, Nat.zero_add]
+ exact StackRuns.cons (.goto rfl) (.nil ..)
+ | cons i ks ih =>
+ let l := selected ks live (fun _ => [])
+ let h := selected ks hist (fun j => fieldBits (live j) ++ hist j)
+ have hl : l i = [] := by simp [l, selected, hks.notMem]
+ have hh : h i = fieldBits (live i) ++ hist i := by simp [h, selected, hks.notMem]
+ have step := popField_runs i l h _ _ hh
+ rw [hl, List.append_nil] at step
+ have sl : Function.update l i (live i) = selected (i :: ks) live (fun _ => []) := update_selected ..
+ have sh : Function.update h i (hist i) =
+ selected (i :: ks) hist (fun j => fieldBits (live j) ++ hist j) := update_selected ..
+ rw [sl, sh] at step
+ have both := FiniteRoutine.Runs.followedBy (ih hks.of_cons) step
+ simp only [batch, List.map_cons, List.sum_cons]
+ convert both using 1
+ omega
+
+/-- Save ten fields of arbitrary bit lengths; their lengths may differ by field. -/
+theorem push_data_runs (live hist : Fin 10 → List Bool) :
+ push.Runs (((List.finRange 10).map (fun i => 3*(live i).length+2)).sum+1) (registers live hist)
+ (registers (fun _ => []) (fun i => fieldBits (live i) ++ hist i)) := by
+ simpa only [push, selected_all] using push_partial (List.finRange 10) live hist (List.nodup_finRange 10)
+
+/-- Restore ten fields of arbitrary bit lengths and leave their history tails intact. -/
+theorem pop_data_runs (live hist : Fin 10 → List Bool) :
+ pop.Runs (((List.finRange 10).map (fun i => 3*(live i).length+1)).sum+1)
+ (registers (fun _ => []) (fun i => fieldBits (live i) ++ hist i)) (registers live hist) := by
+ simpa only [pop, selected_all] using pop_partial (List.finRange 10) live hist (List.nodup_finRange 10)
+
+/-- Move one entire live continuation into the histories. -/
+theorem push_runs (width : ℕ) (f : Frame.SchurFrame n U Z c) (fs : List (Frame.SchurFrame n U Z c)) :
+ push.Runs (10*(3*width+2)+1) (registers (f.bits width) (histories width fs))
+ (registers (fun _ => []) (histories width (f :: fs))) := by
+ rw [histories_cons]
+ have hw (i : Fin 10) : (f.bits width i).length = width := UniversalCountStack.length_digits ..
+ have ht : (((List.finRange 10).map (fun i => 3*(f.bits width i).length+2)).sum+1) = 10*(3*width+2)+1 := by
+ simp [hw]; omega
+ rw [← ht]
+ exact push_data_runs ..
+
+/-- Recover the saved direction, parent query, remaining summand and both scalars. -/
+theorem pop_runs (width : ℕ) (f : Frame.SchurFrame n U Z c) (fs : List (Frame.SchurFrame n U Z c)) :
+ pop.Runs (10*(3*width+1)+1) (registers (fun _ => []) (histories width (f :: fs)))
+ (registers (f.bits width) (histories width fs)) := by
+ rw [histories_cons]
+ have hw (i : Fin 10) : (f.bits width i).length = width := UniversalCountStack.length_digits ..
+ have ht : (((List.finRange 10).map (fun i => 3*(f.bits width i).length+1)).sum+1) = 10*(3*width+1)+1 := by
+ simp [hw]; omega
+ rw [← ht]
+ exact pop_data_runs ..
+
+/-- The abstract call-stack depth directly bounds the bit height of each history port. -/
+theorem history_length (width : ℕ) (fs : List (Frame.SchurFrame n U Z c)) (i : Fin 10) :
+ (histories width fs i).length = fs.length * (2*width+1) := by
+ induction fs with
+ | nil => simp [histories]
+ | cons f fs ih =>
+ change (fieldBits (f.bits width i) ++ histories width fs i).length = _
+ rw [List.length_append, length_fieldBits, Frame.bits, UniversalCountStack.length_digits, ih,
+ List.length_cons]
+ ring
+
+/-- Bit-space bound throughout a push, including instructions inside the field scans. -/
+theorem push_space (width : ℕ) (f : Frame.SchurFrame n U Z c) (fs : List (Frame.SchurFrame n U Z c)) :
+ UniversalCountStack.SpaceRun push.body.standalone (max width (fs.length*(2*width+1)) + (10*(3*width+2)+1))
+ (10*(3*width+2)+1) (some push.body.entry) (registers (f.bits width) (histories width fs))
+ none (registers (fun _ => []) (histories width (f :: fs))) := by
+ apply UniversalCountStack.spaceRun_of_steps (push_runs width f fs)
+ intro port
+ apply Nat.add_le_add_right
+ cases port with
+ | inl i => change (UniversalCountStack.digits width (f.words i)).length ≤ _; simp
+ | inr i => change (histories width fs i).length ≤ _; simp [history_length]
+
+/-- Bit-space bound throughout a pop, independent of the number of earlier calls. -/
+theorem pop_space (width : ℕ) (f : Frame.SchurFrame n U Z c) (fs : List (Frame.SchurFrame n U Z c)) :
+ UniversalCountStack.SpaceRun pop.body.standalone ((fs.length+1)*(2*width+1) + (10*(3*width+1)+1))
+ (10*(3*width+1)+1) (some pop.body.entry) (registers (fun _ => []) (histories width (f :: fs)))
+ none (registers (f.bits width) (histories width fs)) := by
+ apply UniversalCountStack.spaceRun_of_steps (pop_runs width f fs)
+ intro port
+ apply Nat.add_le_add_right
+ cases port with
+ | inl i => exact Nat.zero_le _
+ | inr i => exact (history_length width (f :: fs) i).le
+
+end RankQuery.Stack.FrameStore
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackGramEngine.lean b/lean/OAI/Computability/VPVNP/RankQueryStackGramEngine.lean
new file mode 100644
index 0000000000..6492971fb4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackGramEngine.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.RankQueryStackGramPorts
+import OAI.Computability.VPVNP.RankQueryDescribeAdapter
+
+/-!
+# The fixed Schur determinant machine for weighted Gram coefficients
+
+A concrete scalar reader for the input matrix is the only matrix-dependent
+subroutine. The Schur interpreter, the Gram index calculation, the two field
+products and the continuation stack all have fixed finite controls.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.GramEngine
+
+open Engine RAMTape Dispatch
+
+variable {K : Type}
+
+variable [DecidableEq K]
+
+/-- Build the Gram evaluator actions using the supplied signed scalar-read callbacks. -/
+def actionsWith (call : Bool → FiniteRoutine (GramScalar.Port K)) : Actions (Aux K) :=
+ Assembly.actions bank scratch macPort ((DescribeAdapter.describeWith call).onPorts route)
+
+/-- Instantiate the Gram evaluator actions with the scalar routine built from a Macaulay entry
+reader. -/
+def actions (read : FiniteRoutine (MacaulayRead.Port K)) : Actions (Aux K) :=
+ actionsWith (GramScalar.machine read)
+
+/-- Assemble the stack machine that evaluates Gram queries using the supplied Macaulay entry
+reader. -/
+def machine (read : FiniteRoutine (MacaulayRead.Port K)) := Engine.machine (actions read)
+
+variable {w v d p e n m U Z B : ℕ} {c : SliceArithmetic.Vector p e}
+
+omit [DecidableEq K] in
+private theorem extra_stable {readerReady : Stacks K → Prop} {s t : Stacks (Aux K)}
+ (h : extra w v m c readerReady s) (same : ∀ j, (∀ i, bank i ≠ j) → t j = s j) :
+ extra w v m c readerReady t := by
+ obtain ⟨rs, persist, ls, hf, hr, hb⟩ := h
+ exact ⟨rs, persist, ls, hf, hr, fun z => (same (.inl (.inr z)) (fun _ eq => by cases eq)).trans (hb z)⟩
+
+private theorem lift_control (inner : FiniteRoutine (Engine.Port (DescribeAdapter.Aux K)))
+ (ctl next : Ctl n U Z c) (fs : List (F n U Z c)) (out : Stacks (DescribeAdapter.Aux K))
+ (base : Stacks (Aux K)) (signal : List Bool) {t : ℕ}
+ (run : inner.Runs t (atControl w v ctl fs (base ∘ Sum.inl)) (atControl w v next fs out signal)) :
+ (inner.onPorts route).Runs t (atControl w v ctl fs base)
+ (atControl w v next fs (Sum.elim out (base ∘ Sum.inr)) signal) := by
+ apply FiniteRoutine.runs_onPorts_framed _ route_injective run
+ · intro j; cases j with | frame k => cases k <;> rfl | _ => rfl
+ · intro j; cases j with | frame k => cases k <;> rfl | _ => rfl
+ · intro j hj; cases j with
+ | frame i => exact (hj (.frame i) rfl).elim
+ | result => exact (hj .result rfl).elim
+ | condition => exact (hj .condition rfl).elim
+ | aux i => cases i with
+ | inl j => exact (hj (.aux j) rfl).elim
+ | inr j => rfl
+
+variable [Fact p.Prime] [NeZero e]
+
+/-- Install all five engine callbacks on one finite bank. The matrix-entry
+reader can be reused for different query degrees and both child directions. -/
+theorem contractsWith {T : ℕ} (call : Bool → FiniteRoutine (GramScalar.Port K)) (entry : Entry n (Scalar c))
+ {readerReady : Stacks K → Prop} (hc : DescribeAdapter.CallRuns call entry w v m d T readerReady)
+ (hv : SliceArithmetic.Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hw : (d+1)*widthFactor ≤ w)
+ (hd : d ≤ w) (hsize : n+U+Z+m+8 < 2^d)
+ (s : ℕ) (hn : n ≤ 2^s) (hu : U ≤ 2^s) (hz : Z ≤ 2^s)
+ (hs : 2*s+6 ≤ w) (hws : (2*s+6+1)*widthFactor ≤ w) :
+ Contracts (actionsWith call) (SchurKey.program (U := U) (Z := Z) entry) w v
+ (Assembly.localBudget w e v) (SchurKey.arityBound n U Z) (Ready w v n m c readerReady)
+ (Pending w v m c readerReady) (DescribeAdapter.timeWith w v e T) := by
+ apply Assembly.contracts (s := s) bank scratch macPort (fun _ _ h => Option.some.inj (Sum.inr.inj h))
+ (fun _ h => by cases h) (fun _ _ h => by cases h) _ (fun _ _ => extra_stable)
+ _ _ hn hu hz hs hws hv
+ intro q fs aux ha
+ have small : DescribeAdapter.Ready w v n m c readerReady (aux ∘ Sum.inl) := ⟨ha.1,ha.2.2.2⟩
+ obtain ⟨t,ht,out,ho,desc⟩ := DescribeAdapter.describe_entries call entry hc hv hw₃ hw hd hsize q fs _ small
+ let big := Sum.elim out (aux ∘ Sum.inr)
+ have hb : Ready w v n m c readerReady big := ⟨ho.1,ha.2.1,ha.2.2.1,ho.2⟩
+ refine ⟨t, ht, big, hb, ?_⟩
+ cases h : (SchurKey.program entry).describe q <;>
+ rw [h] at desc <;> exact lift_control _ _ _ _ _ _ _ desc
+
+theorem contracts (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {readerReady : Stacks K → Prop} (hc : MacaulayRead.Correct read M w v B readerReady)
+ (hv : SliceArithmetic.Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hw : (d+1)*widthFactor ≤ w)
+ (hd : d ≤ w) (hsize : n+U+Z+m+8 < 2^d)
+ (s : ℕ) (hn : n ≤ 2^s) (hu : U ≤ 2^s) (hz : Z ≤ 2^s)
+ (hs : 2*s+6 ≤ w) (hws : (2*s+6+1)*widthFactor ≤ w) :
+ Contracts (actions read) (SchurKey.program (U := U) (Z := Z) (weightedGramEntryCoeff M)) w v
+ (Assembly.localBudget w e v) (SchurKey.arityBound n U Z) (Ready w v n m c readerReady)
+ (Pending w v m c readerReady) (DescribeAdapter.clock w v e B) :=
+ contractsWith (GramScalar.machine read) (weightedGramEntryCoeff M)
+ (GramScalar.machine_runs read M hc hv (by omega) hw) hv hw₃ hw hd hsize s hn hu hz hs hws
+
+end RankQuery.Stack.GramEngine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackGramInitialization.lean b/lean/OAI/Computability/VPVNP/RankQueryStackGramInitialization.lean
new file mode 100644
index 0000000000..12760da4a9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackGramInitialization.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.RankQueryStackGramPorts
+
+/-! # Input bank and bounds for the physical weighted Gram interpreter -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.GramEngine
+
+open Engine RAMTape BurstRAM Dispatch
+
+variable {K : Type} {w v n m p e : ℕ} {c : SliceArithmetic.Vector p e}
+
+private def registers (w : ℕ) (slot : Fin 8) (value : ℕ) : EngineAlias.Reg → Word w :=
+ fun i => if i.val = slot.val then Fin.ofNat _ value else 0
+
+/-- Put the two matrix dimensions, the field arithmetic advice, and the
+underlying entry reader's initial work bank on their literal ports. -/
+def initial (w v n m : ℕ) (c : SliceArithmetic.Vector p e) (reader : Stacks K) : Stacks (Aux K)
+ | .inl (.inl i) => ISA.bank Fin.elim0 (0 : Word w) (registers w 7 n) [] i
+ | .inl (.inr z) => GramScalar.bank (GramScalar.wordBank 0 (registers w 3 m))
+ (GramRead.arithmeticBank v c [] []) reader z
+ | .inr none => []
+ | .inr (some i) => MultiplyAdd.expected v c i
+
+theorem initial_ready {readerReady : Stacks K → Prop} (reader : Stacks K) (hr : readerReady reader)
+ (hn : n < 2^w) (hm : m < 2^w) : Ready w v n m c readerReady (initial w v n m c reader) := by
+ refine ⟨⟨registers w 7 n, 0, ?_, ?_, fun _ => rfl⟩, rfl, fun _ => rfl,
+ ⟨registers w 3 m, 0, reader, ?_, hr, fun _ => rfl⟩⟩
+ · simp [registers, Code.inReg]
+ · simp [registers, Code.inReg, Nat.mod_eq_of_lt hn]
+ · intro i hi
+ fin_cases i <;> first | omega | simp [registers, Code.inReg, gramInput, Nat.mod_eq_of_lt hm]
+
+private theorem isa_length (rs : Dispatch.Regs EngineAlias.R w) (persistent : Word w) (i : EngineAlias.Small) :
+ (ISA.bank Fin.elim0 persistent rs [] i).length ≤ w := by
+ cases i with
+ | reg i => simp [ISA.bank]
+ | pub i => exact Fin.elim0 i
+ | persistent => simp [ISA.bank]
+ | work i => exact Nat.zero_le _
+ | logPort i => cases i <;> exact Nat.zero_le _
+
+/-- Size of every auxiliary stack at an instruction boundary, independent of
+the time spent by the matrix entry reader. -/
+theorem ready_length {readerReady : Stacks K → Prop} {s : Stacks (Aux K)} {A : ℕ}
+ (hs : Ready w v n m c readerReady s) (ha : ∀ r, readerReady r → ∀ k, (r k).length ≤ A) :
+ ∀ i, (s i).length ≤ w+v+e+e*v+A := by
+ obtain ⟨⟨lr, lp, _, _, lh⟩, scratchEmpty, mac, ⟨gr, gp, base, _, hbase, gh⟩⟩ := hs
+ rintro ((i|z)|i)
+ · change (s (bank i)).length ≤ _
+ rw [lh]
+ exact (isa_length lr lp i).trans (by omega)
+ · change ((s ∘ Sum.inl) (.inr z)).length ≤ _
+ rw [gh]
+ cases z with
+ | words i => exact (isa_length gr gp i).trans (by omega)
+ | aux i => exact (ha base hbase i).trans (by omega)
+ | mul i =>
+ rcases i with i | i
+ · exact Nat.zero_le _
+ · cases i <;> simp [GramScalar.bank, GramRead.arithmeticBank, SliceArithmetic.MultiplyCall.clean,
+ SliceArithmetic.MultiplyCall.external] <;> omega
+ | _ => exact Nat.zero_le _
+ · cases i with
+ | none => change (s scratch).length ≤ _; rw [scratchEmpty]; exact Nat.zero_le _
+ | some i =>
+ change (s (macPort i)).length ≤ _
+ rw [mac i]
+ rcases i with i | i
+ · exact Nat.zero_le _
+ · cases i <;> simp [MultiplyAdd.expected] <;> omega
+
+end RankQuery.Stack.GramEngine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackGramPorts.lean b/lean/OAI/Computability/VPVNP/RankQueryStackGramPorts.lean
new file mode 100644
index 0000000000..7a4fe18513
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackGramPorts.lean
@@ -0,0 +1,55 @@
+import OAI.Computability.VPVNP.RankQueryStackEngineAssembly
+import OAI.Computability.VPVNP.RankQueryGramAlias
+
+/-! # The shared determinant and scalar-reader ports for the weighted Gram matrix -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.GramEngine
+
+open Engine RAMTape Dispatch
+
+/-- Auxiliary ports shared by the Schur descriptor, the matrix-entry reader, and the
+multiply-and-add routine. -/
+abbrev Aux (K : Type) := DescribeAdapter.Aux K ⊕ Option MultiplyAdd.Aux
+
+variable {K : Type}
+
+/-- Embed the Schur dispatch registers into the descriptor side of the Gram engine's auxiliary
+bank. -/
+def bank : EngineAlias.Small ↪ Aux K := ⟨fun i => .inl (.inl i), fun _ _ h => Sum.inl.inj (Sum.inl.inj h)⟩
+/-- The temporary stack reserved for the Gram engine's scan and child-call routines. -/
+def scratch : Aux K := .inr none
+/-- Embed a multiply-and-add port into the Gram engine's auxiliary bank. -/
+def macPort (i : MultiplyAdd.Aux) : Aux K := .inr (some i)
+
+/-- Route descriptor calls through the Gram engine, sharing the live frame, result, and
+condition ports. -/
+def route : Engine.Port (DescribeAdapter.Aux K) → Engine.Port (Aux K)
+ | .frame j => .frame j | .result => .result | .condition => .condition | .aux j => .aux (.inl j)
+
+theorem route_injective : Function.Injective (route (K := K)) := by
+ intro a b h; cases a <;> cases b <;> simp_all [route]
+
+/-- The descriptor's scalar workspace and matrix reader are ready for a query with column count
+`m`. -/
+def extra {p e : ℕ} (w v m : ℕ) (c : SliceArithmetic.Vector p e) (readerReady : Stacks K → Prop)
+ (s : Stacks (Aux K)) : Prop := DescribeAdapter.RightReady w v m c readerReady (s ∘ Sum.inl)
+
+/-- Entry condition for the Gram engine, combining the dispatch register bank, scratch stack,
+scalar arithmetic advice, and reader state. -/
+abbrev Ready {p e : ℕ} (w v n m : ℕ) (c : SliceArithmetic.Vector p e) (readerReady : Stacks K → Prop) :=
+ Assembly.Ready (bank (K := K)) scratch macPort (extra w v m c readerReady) n w v c
+
+/-- State of the Gram engine after staging a child query and before activating its six output
+words. -/
+abbrev Pending {p e n U Z : ℕ} (w v m : ℕ) (c : SliceArithmetic.Vector p e) (readerReady : Stacks K → Prop) :=
+ Assembly.Pending (n := n) (U := U) (Z := Z) (bank (K := K)) scratch macPort (extra w v m c readerReady) w v c
+
+end RankQuery.Stack.GramEngine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackGramRoot.lean b/lean/OAI/Computability/VPVNP/RankQueryStackGramRoot.lean
new file mode 100644
index 0000000000..62fbef1ab0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackGramRoot.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.RankQueryStackGramSpace
+import OAI.Computability.VPVNP.RankQueryDescribeSpace
+
+/-!
+# End-to-end determinant coefficient query on a streamed relation matrix
+
+The independent height bound of the matrix-entry reader is reused through
+every recursive call. The entry reader's running time only enters the clock.
+The answer is the bivariate coefficient of the reverse characteristic
+polynomial of the weighted Gram matrix over the native extension-field ring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.GramEngine
+
+open Engine RAMTape Dispatch
+
+variable {K : Type} [DecidableEq K] {w v d p e n m U Z B A S depth : ℕ}
+variable [Fact p.Prime] [NeZero e] {c : SliceArithmetic.Vector p e}
+
+/-- Stack-height bound while decoding a Schur query, including its suspended frames and the
+Gram entry reader. -/
+def descriptorSpace (w v e A S depth : ℕ) :=
+ max (entryCap w v e A depth) (DescribeAdapter.space w v e (entryCap w v e A depth) S)
+
+theorem describeBounded (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {readerReady : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S readerReady)
+ (ha : ∀ s, readerReady s → ∀ i, (s i).length ≤ A)
+ (hv : SliceArithmetic.Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hw : (d+1)*widthFactor ≤ w)
+ (hd : d ≤ w) (hsize : n+U+Z+m+8 < 2^d) :
+ DescribeBounded (actions read) (SchurKey.program (U := U) (Z := Z) (weightedGramEntryCoeff M)) w v
+ (DescribeAdapter.clock w v e B) (descriptorSpace w v e A S depth) depth (Ready w v n m c readerReady) :=
+ lift_bounded ha (DescribeAdapter.describe_bounded read M hc hv hw₃ hw hd hsize)
+
+/-- Bit-stack step bound for a Schur coefficient query, using the recursion depth, branching
+bound, and entry-reader clock `B`. -/
+def queryTime (n U Z w v e B : ℕ) :=
+ (5+6*SchurKey.arityBound n U Z)^(Nat.clog 2 U+4+Nat.clog 2 n+1) *
+ boundedStepTime (DescribeAdapter.clock w v e B) (Assembly.localBudget w e v) w v e + 1
+
+/-- Maximum stack height during a Gram coefficient query, including its recursive frames and
+the entry reader's workspace. -/
+def querySpace (n U w v e A S : ℕ) :=
+ let depth := Nat.clog 2 U+4+Nat.clog 2 n
+ boundedSpace (descriptorSpace w v e A S depth) (w+v+e+e*v+A) depth (Assembly.localBudget w e v) w v e
+
+/-- The physical root subroutine performs its own Schur recursion and scalar
+arithmetic. Its caller supplies a bounded entry routine for the original
+matrix. The query's two coefficient indices may vary between calls. -/
+theorem root_query (read : FiniteRoutine (MacaulayRead.Port K)) (M : Matrix (Fin n) (Fin m) (Scalar c))
+ {readerReady : Stacks K → Prop} (hc : MacaulayRead.CorrectSpace read M w v B S readerReady)
+ (ha : ∀ s, readerReady s → ∀ i, (s i).length ≤ A)
+ (hv : SliceArithmetic.Word.workingWidth p ≤ v) (hw₃ : 3 ≤ w) (hw : (d+1)*widthFactor ≤ w)
+ (hd : d ≤ w) (hsize : n+U+Z+m+8 < 2^d)
+ (s : ℕ) (hn : n ≤ 2^s) (hu : U ≤ 2^s) (hz : Z ≤ 2^s) (hs : 2*s+6 ≤ w) (hws : (2*s+6+1)*widthFactor ≤ w)
+ (u : Limit U) (z : Limit Z) (aux : Stacks (Aux K)) (haux : Ready w v n m c readerReady aux) :
+ ∃ t ≤ queryTime n U Z w v e B, ∃ out, Ready w v n m c readerReady out ∧
+ (machine read).BoundedRun (querySpace n U w v e A S) t
+ (atControl (c := c) w v (.enter (SchurKey.root (n := n) u z)) [] aux)
+ (atControl w v (.returned (((weightedGram M).charpolyRev.coeff u.val).coeff z.val)) ([] : List (F n U Z c)) out) :=
+ eval_root_bounded (contracts read M hc.correct hv hw₃ hw hd hsize s hn hu hz hs hws)
+ (describeBounded read M hc ha hv hw₃ hw hd hsize) (fun _ hr => ready_length hr ha)
+ (weightedGram M) (weightedGramEntryCoeff_eq M) u z aux haux
+
+end RankQuery.Stack.GramEngine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackGramSpace.lean b/lean/OAI/Computability/VPVNP/RankQueryStackGramSpace.lean
new file mode 100644
index 0000000000..e30c9256be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackGramSpace.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.RankQueryStackGramEngine
+import OAI.Computability.VPVNP.RankQueryStackGramInitialization
+import OAI.Computability.VPVNP.RankQueryStackEngineSpace
+import OAI.Computability.VPVNP.RankQueryGramReadSpace
+
+/-! # Space for a matrix-entry callback on the complete Schur register bank -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.GramEngine
+
+open Engine RAMTape Dispatch
+
+variable {K : Type} [DecidableEq K] {n m U Z p e w v B A S depth : ℕ} {c : SliceArithmetic.Vector p e}
+
+/-- Live frame data, saved frames and the underlying reader all fit at entry. -/
+def entryCap (w v e A depth : ℕ) := max (w+v+e+e*v+A) (max (max 1 (max w (e*v))) (depth*(2*max 1 (max w (e*v))+1)))
+
+omit [DecidableEq K] in
+private theorem start_cap {readerReady : Stacks K → Prop} (ha : ∀ s, readerReady s → ∀ i, (s i).length ≤ A)
+ (q : Key n U Z) (fs : List (F n U Z c)) (hfs : fs.length ≤ depth) (aux : Stacks (Aux K))
+ (haux : Ready w v n m c readerReady aux) (i : Engine.Port (Aux K)) :
+ (atControl w v (.enter q) fs aux [] i).length ≤ entryCap w v e A depth :=
+ state_length (d := depth) (.enter q,fs) hfs aux (ready_length haux ha) i
+
+omit [DecidableEq K] in
+theorem inner_start_cap {readerReady : Stacks K → Prop} (ha : ∀ s, readerReady s → ∀ i, (s i).length ≤ A)
+ (q : Key n U Z) (fs : List (F n U Z c)) (hfs : fs.length ≤ depth) (aux : Stacks (Aux K))
+ (haux : Ready w v n m c readerReady aux) (i : Engine.Port (DescribeAdapter.Aux K)) :
+ (atControl w v (.enter q) fs (aux ∘ Sum.inl) [] i).length ≤ entryCap w v e A depth := by
+ have h := start_cap ha q fs hfs aux haux (route i)
+ cases i with | frame k => cases k <;> exact h | _ => exact h
+
+/-- A bounded descriptor call executes on the whole bank while the arithmetic
+advice and the unrelated scratch slot remain available to later summands. -/
+theorem lift_boundedWith {readerReady : Stacks K → Prop} {call : Bool → FiniteRoutine (GramScalar.Port K)}
+ {entry : Entry n (Scalar c)} [Fact p.Prime] [NeZero e]
+ (ha : ∀ s, readerReady s → ∀ i, (s i).length ≤ A)
+ (inner : ∀ (q : Key n U Z) (fs : List (F n U Z c)) (aux : Stacks (DescribeAdapter.Aux K)),
+ DescribeAdapter.Ready w v n m c readerReady aux →
+ (∀ j, (atControl w v (.enter q) fs aux [] j).length ≤ entryCap w v e A depth) →
+ ∃ t ≤ B, ∃ out, DescribeAdapter.Ready w v n m c readerReady out ∧
+ (DescribeAdapter.describeWith call).BoundedRun S t (atControl w v (.enter q) fs aux)
+ (match (SchurKey.program entry).describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false])) :
+ DescribeBounded (actionsWith call) (SchurKey.program (U := U) (Z := Z) entry) w v B
+ (max (entryCap w v e A depth) S) depth (Ready w v n m c readerReady) := by
+ intro q fs aux hfs haux
+ have small : DescribeAdapter.Ready w v n m c readerReady (aux ∘ Sum.inl) := ⟨haux.1,haux.2.2.2⟩
+ obtain ⟨t,ht,out,ho,run⟩ := inner q fs _ small (inner_start_cap ha q fs hfs aux haux)
+ let big := Sum.elim out (aux ∘ Sum.inr)
+ have hb : Ready w v n m c readerReady big := ⟨ho.1,haux.2.1,haux.2.2.1,ho.2⟩
+ refine ⟨t, ht, big, hb, ?_⟩
+ have place (ctl : Ctl n U Z c) (sig : List Bool)
+ (h : (DescribeAdapter.describeWith call).BoundedRun S t (atControl w v (.enter q) fs (aux ∘ Sum.inl))
+ (atControl w v ctl fs out sig)) :
+ ((actionsWith call).describe).BoundedRun (max (entryCap w v e A depth) S) t
+ (atControl w v (.enter q) fs aux) (atControl w v ctl fs big sig) := by
+ apply FiniteRoutine.BoundedRun.framed route_injective (h.enlarge (le_max_right ..))
+ (fun j => (start_cap ha q fs hfs aux haux j).trans (le_max_left ..))
+ · intro i; cases i with | frame k => cases k <;> rfl | _ => rfl
+ · intro i; cases i with | frame k => cases k <;> rfl | _ => rfl
+ · intro j hj; cases j with
+ | frame i => exact (hj (.frame i) rfl).elim
+ | result => exact (hj .result rfl).elim
+ | condition => exact (hj .condition rfl).elim
+ | aux i => cases i with
+ | inl j => exact (hj (.aux j) rfl).elim
+ | inr j => rfl
+ cases h : (SchurKey.program entry).describe q <;> rw [h] at run <;> exact place _ _ run
+
+theorem lift_bounded {readerReady : Stacks K → Prop} {read : FiniteRoutine (MacaulayRead.Port K)}
+ {M : Matrix (Fin n) (Fin m) (Scalar c)} [Fact p.Prime] [NeZero e]
+ (ha : ∀ s, readerReady s → ∀ i, (s i).length ≤ A)
+ (inner : ∀ (q : Key n U Z) (fs : List (F n U Z c)) (aux : Stacks (DescribeAdapter.Aux K)),
+ DescribeAdapter.Ready w v n m c readerReady aux →
+ (∀ j, (atControl w v (.enter q) fs aux [] j).length ≤ entryCap w v e A depth) →
+ ∃ t ≤ B, ∃ out, DescribeAdapter.Ready w v n m c readerReady out ∧
+ (DescribeAdapter.describe read).BoundedRun S t (atControl w v (.enter q) fs aux)
+ (match (SchurKey.program (weightedGramEntryCoeff M)).describe q with
+ | .inl r => atControl w v (.returned r) fs out [true]
+ | .inr k => atControl w v (.scan q k 0) fs out [false])) :
+ DescribeBounded (actions read) (SchurKey.program (U := U) (Z := Z) (weightedGramEntryCoeff M)) w v B
+ (max (entryCap w v e A depth) S) depth (Ready w v n m c readerReady) :=
+ lift_boundedWith ha inner
+
+end RankQuery.Stack.GramEngine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackInterpretation.lean b/lean/OAI/Computability/VPVNP/RankQueryStackInterpretation.lean
new file mode 100644
index 0000000000..165d181a09
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackInterpretation.lean
@@ -0,0 +1,84 @@
+import OAI.Computability.VPVNP.RankQueryStackField
+
+/-!
+# Rank over the advised field from native scalar words
+
+Interpretation commutes with the weighted Gram coefficients and the
+reverse characteristic polynomial. This identifies the numerical rank
+returned by the packed-word machine with matrix rank in the advised
+finite extension.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+open Polynomial
+
+namespace SchurKey
+
+variable {A B : Type*} [CommRing A] [CommRing B] {n m : ℕ}
+
+private theorem map_reverseCharpoly (f : A →+* B) (M : Matrix (Fin n) (Fin n) A) :
+ Polynomial.map f M.charpolyRev = (M.map f).charpolyRev := by
+ change (mapRingHom f) (1 - X • M.map C).det = _
+ rw [RingHom.map_det, Matrix.charpolyRev]
+ apply congrArg Matrix.det
+ rw [map_sub, map_one]
+ congr 1
+ ext i j : 1
+ change Polynomial.map f (X * C (M i j)) = X * C (f (M i j))
+ simp
+
+private theorem map_weightedGram (f : A →+* B) (M : Matrix (Fin n) (Fin m) A) :
+ (weightedGram M).map (mapRingHom f) = weightedGram (M.map f) := by
+ ext i j z
+ change (Polynomial.map f ((weightedGram M) i j)).coeff z = _
+ rw [coeff_map, ← weightedGramEntryCoeff_eq, ← weightedGramEntryCoeff_eq]
+ unfold weightedGramEntryCoeff
+ split_ifs <;> simp
+
+/-- Correctness of a rank scan in an executable ring embedded in a field. -/
+theorem computeRank_interpreted {F : Type*} [Field F] [DecidableEq A] [DecidableEq F]
+ (f : A →+* F) (hf : Function.Injective f) (M : Matrix (Fin n) (Fin m) A) :
+ computeRank M = (M.map f).rank := by
+ let val := compute (weightedGramEntryCoeff M)
+ have eqzero (u z : ℕ) : f (val u z) = 0 ↔ val u z = 0 := by rw [← f.map_zero, hf.eq_iff]
+ have hs : computeRank M = scanRank n m (fun u z => f (val u z)) := by
+ unfold computeRank scanRank
+ simp only [eqzero, val]
+ rw [hs]
+ apply scanRank_correct
+ intro u z
+ change f (compute _ u z) = _
+ rw [compute_correct (weightedGram M) _ (weightedGramEntryCoeff_eq M)]
+ rw [← coeff_map f]
+ change ((mapRingHom f) ((weightedGram M).charpolyRev.coeff u)).coeff z = _
+ rw [← coeff_map (mapRingHom f), map_reverseCharpoly, map_weightedGram]
+ rfl
+
+end SchurKey
+
+namespace Scalar
+
+open SliceArithmetic
+
+variable {p e n m : ℕ} [Fact p.Prime] [NeZero e] (c : Vector p e)
+
+/-- Compute in binary coefficient words and interpret the output rank in the
+advised irreducible extension. Only the input matrix entries are read. -/
+theorem rank_correct [Fact (Irreducible (modulus c))] (M : Matrix (Fin n) (Fin m) (Scalar c)) :
+ SchurKey.computeRank M = (M.map (interpretation c)).rank := by
+ classical
+ apply SchurKey.computeRank_interpreted
+ exact interpret_injective c
+
+end Scalar
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackMultiplyAdd.lean b/lean/OAI/Computability/VPVNP/RankQueryStackMultiplyAdd.lean
new file mode 100644
index 0000000000..389e6ff885
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackMultiplyAdd.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.RankQueryStackAccumulate
+import OAI.Computability.VPVNP.RankQueryStackEngineSpec
+
+/-!
+# The Schur stack machine's multiply-and-add callback
+
+After the right child returns, the live frame contains its parent's
+accumulator and the saved left factor. The callback mounts the coefficient
+arithmetic on these fields and the returned value. It then clears the two
+consumed factors and resumes the parent's scan with its updated accumulator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine.MultiplyAdd
+
+open RAMTape SliceArithmetic
+
+set_option backward.isDefEq.respectTransparency false in
+/-- Persistent arithmetic inputs for a Schur product, consisting of the prime, a zero word, the
+extension degree, and the reduction coefficients. -/
+inductive Advice where
+ | prime | zeroWord | degree | coeff
+ deriving DecidableEq, Fintype
+
+/-- Private stacks and persistent arithmetic inputs for the multiply-and-add callback. -/
+abbrev Aux := MultiplyAccumulate.Private ⊕ Advice
+
+variable {K : Type} {n U Z p e w v : ℕ}
+
+/-- Connect the arithmetic routine to its auxiliary stacks and to the Schur frame's left
+operand, returned right operand, and accumulator. -/
+def port (f : Aux → K) : MultiplyAccumulate.Port → Engine.Port K
+ | .inl i => .aux (f (.inl i))
+ | .inr .prime => .aux (f (.inr .prime))
+ | .inr .zeroWord => .aux (f (.inr .zeroWord))
+ | .inr .degree => .aux (f (.inr .degree))
+ | .inr .coeff => .aux (f (.inr .coeff))
+ | .inr .left => .frame (.inl 9)
+ | .inr .returned => .result
+ | .inr .acc => .frame (.inl 8)
+
+theorem port_injective {f : Aux → K} (hf : Function.Injective f) : Function.Injective (port f) := by
+ rintro (i|i) (j|j) h
+ · exact congrArg Sum.inl (Sum.inl.inj (hf (Engine.Port.aux.inj h)))
+ · cases j <;> simp_all [port, hf.eq_iff]
+ · cases i <;> simp_all [port, hf.eq_iff]
+ · cases i <;> cases j <;> simp_all [port, hf.eq_iff]
+
+/-- Initial arithmetic stack contents, with empty private stacks and the field parameters
+encoded at limb width `v`. -/
+def expected (v : ℕ) (c : Vector p e) : Stacks Aux
+ | .inl _ => []
+ | .inr .prime => BurstRAM.wordBits (Fin.ofNat (2 ^ v) p)
+ | .inr .zeroWord => BurstRAM.wordBits (0 : BurstRAM.Word v)
+ | .inr .degree => List.replicate e true
+ | .inr .coeff => SliceArithmeticRound.packed v (List.ofFn c)
+
+/-- The other auxiliary ports are available for the query description and
+the controller's remaining subroutines. -/
+def Ready (f : Aux → K) (v : ℕ) (c : Vector p e) (aux : Stacks K) := ∀ i, aux (f i) = expected v c i
+
+/-- Add the product of the saved left factor and the returned right factor to the parent
+accumulator, then clear both factors. -/
+def machine (f : Aux → K) : FiniteRoutine (Engine.Port K) :=
+ ((MultiplyAccumulate.machine.onPorts (port f)).followedBy (CallClear.clear (.frame (.inl 9)))).followedBy
+ (CallClear.clear .result)
+
+/-- Step bound for the multiply-and-add callback, including the cost of clearing two scalars of
+`e*v` bits. -/
+def callCap (e v : ℕ) := MultiplyAccumulate.callCap e v + 2 * (e * v + 1)
+
+variable [DecidableEq K] [Fact p.Prime] [NeZero e] {c : Vector p e}
+
+/-- The precise multiply-and-add execution required by the engine's contracts.
+The stored stack history and the entire auxiliary bank are preserved. -/
+theorem machine_runs (f : Aux → K) (hf : Function.Injective f) (hw : Word.workingWidth p ≤ v)
+ (w : ℕ) (q : Key n U Z) (k : ℕ) (acc left returned : Scalar c)
+ (fs : List (F n U Z c)) (aux : Stacks K) (hready : Ready f v c aux) :
+ ∃ t ≤ callCap e v, (machine f).Runs t
+ (store (popped w v (.right q k acc left)) (history w v fs) [] (scalar v returned) aux)
+ (atControl w v (.scan q k (acc + left * returned)) fs aux) := by
+ let result := acc + left * returned
+ let pre := store (popped w v (.right q k acc left)) (history w v fs) [] (scalar v returned) aux
+ let mid := Function.update pre (.frame (.inl 8)) (scalar v result)
+ let consumed := Function.update mid (.frame (.inl 9)) []
+ obtain ⟨t, ht, mac⟩ := Scalar.accumulate_runs hw c left returned acc
+ have hmac : (MultiplyAccumulate.machine.onPorts (port f)).Runs t pre mid := by
+ apply MultiplyAccumulate.machine.runs_onPorts_framed (port_injective hf) mac
+ · rintro (i|i)
+ · cases i <;> exact hready _
+ · cases i with
+ | prime => exact hready (.inr .prime)
+ | zeroWord => exact hready (.inr .zeroWord)
+ | degree => exact hready (.inr .degree)
+ | coeff => exact hready (.inr .coeff)
+ | left | acc | returned => rfl
+ · rintro (i|i)
+ · cases i <;> exact (Function.update_of_ne (by simp [port]) ..).trans (hready _)
+ · cases i with
+ | prime => exact (Function.update_of_ne (by simp [port]) ..).trans (hready (.inr .prime))
+ | zeroWord => exact (Function.update_of_ne (by simp [port]) ..).trans (hready (.inr .zeroWord))
+ | degree => exact (Function.update_of_ne (by simp [port]) ..).trans (hready (.inr .degree))
+ | coeff => exact (Function.update_of_ne (by simp [port]) ..).trans (hready (.inr .coeff))
+ | left | returned => rfl
+ | acc => exact Function.update_self ..
+ · intro i hi
+ exact Function.update_of_ne (Ne.symm (hi (.inr .acc))) ..
+ have leftLen : (mid (.frame (.inl 9))).length = e*v := scalar_length v left
+ have retLen : (consumed .result).length = e*v := scalar_length v returned
+ have eraseLeft := CallClear.clear_runs (.frame (.inl 9)) mid
+ have eraseRet := CallClear.clear_runs .result consumed
+ rw [leftLen] at eraseLeft
+ rw [retLen] at eraseRet
+ have hfinal : Function.update consumed .result [] = atControl w v (.scan q k result) fs aux := by
+ funext j
+ cases j with
+ | frame j => cases j with
+ | inl i => fin_cases i <;> rfl
+ | inr i => rfl
+ | aux | result | condition => rfl
+ rw [hfinal] at eraseRet
+ exact ⟨_, by unfold callCap; omega, (hmac.followedBy eraseLeft).followedBy eraseRet⟩
+
+end RankQuery.Stack.Engine.MultiplyAdd
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackNativeFrames.lean b/lean/OAI/Computability/VPVNP/RankQueryStackNativeFrames.lean
new file mode 100644
index 0000000000..e703655ada
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackNativeFrames.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.RankQueryStackEngine
+import OAI.Computability.VPVNP.SliceArithmeticRound
+
+/-! # Physical Schur frame fields with native extension-field scalars
+
+The query and loop registers use ordinary binary words. Accumulators and left
+operands keep the low-degree-first stream of base-field limbs consumed by
+the extension-field arithmetic. The direction takes one bit and the unused
+left operand occupies an empty field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine
+
+open RAMTape Evaluator.InputBank
+
+variable {n U Z p e : ℕ} {c : SliceArithmetic.Vector p e} {K : Type}
+
+/-- The ten bit-string fields of a live Schur frame or its corresponding ten history stacks. -/
+abbrev Data := Fin 10 → List Bool
+/-- A Schur query for an order-`n` matrix with coefficient degrees bounded by `U` and `Z`. -/
+abbrev Key (n U Z : ℕ) := SchurKey n U Z
+/-- A suspended Schur continuation whose accumulator and operands belong to the scalar ring
+specified by `c`. -/
+abbrev F (n U Z : ℕ) (c : SliceArithmetic.Vector p e) := Frame.SchurFrame n U Z c
+
+/-- Encode a scalar as its low-degree-first list of base-field coefficients, each in a `v`-bit
+limb. -/
+def scalar (v : ℕ) (a : Scalar c) : List Bool := SliceArithmeticRound.packed v (List.ofFn a.digits)
+
+@[simp] theorem scalar_length (v : ℕ) (a : Scalar c) : (scalar v a).length = e*v := by
+ simp [scalar]
+
+/-- Assemble the ten live fields from the direction tag, six query words, remaining count,
+accumulator, and saved left factor. -/
+def fields (w : ℕ) (tag : List Bool) (q : Key n U Z) (count acc left : List Bool) : Data :=
+ Fin.cons tag (Fin.append (fun i => UniversalCountStack.digits w (q.words i)) ![count,acc,left])
+
+/-- Encode a suspended continuation, saving the left scalar in a frame waiting for its right
+child. -/
+def nativeFrame (w v : ℕ) : F n U Z c → Data
+ | .left q k a => fields w [false] q (UniversalCountStack.digits w k) (scalar v a) []
+ | .right q k a l => fields w [true] q (UniversalCountStack.digits w k) (scalar v a) (scalar v l)
+
+theorem frame_length (w v : ℕ) (f : F n U Z c) (i : Fin 10) :
+ (nativeFrame w v f i).length ≤ max 1 (max w (e*v)) := by
+ cases f with
+ | left q k a =>
+ refine Fin.cases (by simp [nativeFrame, fields]) (fun j => ?_) i
+ refine Fin.addCases (motive := fun i => (Fin.append (fun x => UniversalCountStack.digits w (q.words x))
+ ![UniversalCountStack.digits w k,scalar v a,[]] i).length ≤ _) (fun x : Fin 6 => ?_) (fun x : Fin 3 => ?_) j
+ · simp
+ · rw [Fin.append_right]; fin_cases x <;> simp
+ | right q k a l =>
+ refine Fin.cases (by simp [nativeFrame, fields]) (fun j => ?_) i
+ refine Fin.addCases (motive := fun i => (Fin.append (fun x => UniversalCountStack.digits w (q.words x))
+ ![UniversalCountStack.digits w k,scalar v a,scalar v l] i).length ≤ _) (fun x : Fin 6 => ?_) (fun x : Fin 3 => ?_) j
+ · simp
+ · rw [Fin.append_right]; fin_cases x <;> simp
+
+/-- Encode a list of suspended frames into parallel history stacks, with the top frame's
+delimited fields first. -/
+def history (w v : ℕ) (fs : List (F n U Z c)) : Data :=
+ fun i => fs.flatMap (fun f => fieldBits (nativeFrame w v f i))
+
+theorem history_cons (w v : ℕ) (f : F n U Z c) (fs : List (F n U Z c)) :
+ history w v (f :: fs) = fun i => fieldBits (nativeFrame w v f i) ++ history w v fs i := by
+ funext i; simp [history]
+
+theorem history_length_le (w v : ℕ) (fs : List (F n U Z c)) (i : Fin 10) :
+ (history w v fs i).length ≤ fs.length * (2*max 1 (max w (e*v))+1) := by
+ induction fs with
+ | nil => simp [history]
+ | cons f fs ih =>
+ rw [history_cons, List.length_append, length_fieldBits, List.length_cons, Nat.add_mul, one_mul]
+ have := frame_length w v f i
+ omega
+
+/-- The complete physical bank. The auxiliary port values depend on the
+installed arithmetic routines and the persistent matrix description. -/
+def store (live saved : Data) (signal result : List Bool) (aux : Stacks K) : Stacks (Port K)
+ | .frame (.inl i) => live i
+ | .frame (.inr i) => saved i
+ | .condition => signal
+ | .result => result
+ | .aux i => aux i
+
+private theorem cost_le (s : Data) (c b : ℕ) (h : ∀ i, (s i).length ≤ b) :
+ (((List.finRange 10).map (fun i => 3*(s i).length+c)).sum+1) ≤ 10*(3*b+c)+1 := by
+ have hl (xs : List (Fin 10)) : (xs.map (fun i => 3*(s i).length+c)).sum ≤ xs.length*(3*b+c) := by
+ induction xs with
+ | nil => simp
+ | cons i xs ih =>
+ rw [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, one_mul]
+ have := h i
+ omega
+ simpa only [List.length_finRange] using Nat.add_le_add_right (hl (List.finRange 10)) 1
+
+variable [DecidableEq K]
+
+theorem save_runs (a : Actions K) (w v : ℕ) (f : F n U Z c) (fs : List (F n U Z c))
+ (ret : List Bool) (aux : Stacks K) :
+ ∃ t ≤ 10*(3*max 1 (max w (e*v))+2)+1,
+ (a.callee .save).Runs t (store (nativeFrame w v f) (history w v fs) [] ret aux)
+ (store (fun _ => []) (history w v (f :: fs)) [] ret aux) := by
+ refine ⟨_, cost_le _ _ _ (frame_length w v f), ?_⟩
+ apply FiniteRoutine.runs_onPorts_framed _ (ports := Port.frame) (fun _ _ h => Port.frame.inj h)
+ (FrameStore.push_data_runs (nativeFrame w v f) (history w v fs))
+ · intro k; cases k <;> rfl
+ · intro k; cases k with
+ | inl => rfl
+ | inr i => exact congrFun (history_cons ..) i
+ · intro l hl; cases l <;> first | rfl | exact (hl _ rfl).elim
+
+theorem restore_runs (a : Actions K) (w v : ℕ) (f : F n U Z c) (fs : List (F n U Z c))
+ (ret : List Bool) (aux : Stacks K) :
+ ∃ t ≤ 10*(3*max 1 (max w (e*v))+1)+1,
+ (a.callee .restore).Runs t (store (fun _ => []) (history w v (f :: fs)) [] ret aux)
+ (store (nativeFrame w v f) (history w v fs) [] ret aux) := by
+ refine ⟨_, cost_le _ _ _ (frame_length w v f), ?_⟩
+ apply FiniteRoutine.runs_onPorts_framed _ (ports := Port.frame) (fun _ _ h => Port.frame.inj h)
+ (FrameStore.pop_data_runs (nativeFrame w v f) (history w v fs))
+ · intro k; cases k with
+ | inl => rfl
+ | inr i => exact congrFun (history_cons ..) i
+ · intro k; cases k <;> rfl
+ · intro l hl; cases l <;> first | rfl | exact (hl _ rfl).elim
+
+end RankQuery.Stack.Engine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackPhysical.lean b/lean/OAI/Computability/VPVNP/RankQueryStackPhysical.lean
new file mode 100644
index 0000000000..8d9322cd2f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackPhysical.lean
@@ -0,0 +1,146 @@
+import OAI.Computability.VPVNP.RankQueryStackCodegen
+import OAI.Computability.VPVNP.RankQueryStackBounds
+
+/-!
+# Fixed bit-stack programs for matrix queries
+
+Three shared-bank routines describe the current Schur query and generate its
+left and right subqueries. A fourth computes the column index of a tagged
+Gram coefficient. Every routine has a fixed table independent of the matrix
+dimensions, extension field and degree ranges.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Dispatch
+
+open BurstRAM RAMTape
+
+private def gram : Code :=
+ let row : Expr := .reg 0
+ let col : Expr := .reg 1
+ let degree : Expr := .reg 2
+ let width : Expr := .reg 3
+ let k := degree - row - 2
+ let empty := Code.emit ![0,0,0,0,0,0]
+ .test ((row+2)-degree) 0
+ (.test ((k+1)-width) 0 (.emit ![1,row,col,k,0,0]) empty) empty
+
+/-- Inputs to the Gram coefficient dispatch, consisting of row indices `i` and `j`, degree `z`,
+column count `m`, and four zero words. -/
+def gramInput (i j z m : ℕ) : Fin 8 → ℕ := ![i,j,z,m,0,0,0,0]
+
+/-- A valid Gram request contains two row indices and the common column to
+read. The remaining descriptor gives the zero coefficient. -/
+def decodeGram {n m : ℕ} {F : Type*} [CommRing F] (M : Matrix (Fin n) (Fin m) F)
+ (words : Fin 6 → ℕ) : F :=
+ if words 0 = 1 then
+ if hr : words 1 < n then if hc : words 2 < n then if hk : words 3 < m then
+ M ⟨words 1,hr⟩ ⟨words 3,hk⟩ * M ⟨words 2,hc⟩ ⟨words 3,hk⟩ else 0 else 0 else 0
+ else 0
+
+theorem gram_eq {n m : ℕ} {F : Type*} [CommRing F] (M : Matrix (Fin n) (Fin m) F)
+ (i j : Fin n) (z : ℕ) :
+ decodeGram M (gram.eval (gramInput i j z m)) = weightedGramEntryCoeff M i j z := by
+ by_cases h₁ : i.val+2 ≤ z <;> by_cases h₂ : z-i.val-2 < m
+ all_goals have hs₂ : (z-i.val-2+1) ≤ m ↔ z-i.val-2 < m := by omega
+ all_goals simp [gram, gramInput, decodeGram, Code.eval, Expr.eval, Arith.eval, eval_sub,
+ weightedGramEntryCoeff, hs₂, h₁,h₂, Nat.sub_eq_zero_iff_le]
+
+/-- The four dispatch operations describe a Schur query, stage either child, or decode a
+weighted Gram coefficient. -/
+inductive Operation where
+ | describe | left | right | gram
+ deriving DecidableEq
+
+/-- Register decision tree implementing the chosen dispatch operation. -/
+def Operation.tree : Operation → Code
+ | .describe => VPVNP.RankQuery.Stack.Dispatch.describe
+ | .left => child false
+ | .right => child true
+ | .gram => VPVNP.RankQuery.Stack.Dispatch.gram
+
+theorem gram_words (i j z m : ℕ) :
+ Operation.gram.tree.eval (gramInput i j z m) = if i+2 ≤ z ∧ z-i-2 < m
+ then ![1,i,j,z-i-2,0,0] else ![0,0,0,0,0,0] := by
+ have hs : z-i-2+1 ≤ m ↔ z-i-2 < m := by omega
+ by_cases hi : i+2 ≤ z <;> by_cases hk : z-i-2 < m <;>
+ funext a <;> fin_cases a <;>
+ simp [Operation.tree, gram, Code.eval, Expr.eval, Arith.eval, eval_sub, gramInput,
+ Nat.sub_eq_zero_iff_le, hs, hi, hk]
+
+/-- Shared scratch-register capacity sufficient for each of the four dispatch trees. -/
+def capacity := describe.scratch + (child false).scratch + (child true).scratch + gram.scratch
+/-- Uniform factor bounding the word width needed by any of the four dispatch trees. -/
+def widthFactor := describe.wordFactor + (child false).wordFactor + (child true).wordFactor + gram.wordFactor
+
+private theorem Operation.scratch_le (a : Operation) : a.tree.scratch ≤ capacity := by
+ cases a <;> simp only [capacity, Operation.tree] <;> omega
+
+private theorem Operation.factor_le (a : Operation) : a.tree.wordFactor ≤ widthFactor := by
+ cases a <;> simp only [widthFactor, Operation.tree] <;> omega
+
+/-- Compile the operation's decision tree into a bit-stack routine on the shared register bank. -/
+def Operation.machine (a : Operation) := a.tree.physical capacity
+
+/-- Step bound for executing the operation and writing its six output fields at word width `w`. -/
+def Operation.clock (a : Operation) (w : ℕ) :=
+ (a.tree.emitFields capacity (List.finRange 6)).length * (100*(w+1)^2)
+
+/-- Execute the complete fixed bit-stack instruction table, including binary
+arithmetic, branching and all six register writes. -/
+theorem Operation.run {w p : ℕ} (a : Operation) (env : Fin 8 → ℕ)
+ (rs : Regs (14+capacity) w) (hw : (p+1)*widthFactor ≤ w)
+ (he : ∀ i, env i < 2^p) (hr : ∀ i, (rs (Code.inReg capacity i)).val = env i)
+ (pub : Fin 0 → Word w) (persistent : Word w) :
+ ∃ t ≤ a.clock w, ∃ out,
+ a.machine.Runs t (ISA.bank pub persistent rs []) (ISA.bank pub persistent out []) ∧
+ (∀ i, out (Code.inReg capacity i) = rs (Code.inReg capacity i)) ∧
+ ∀ i, (out (Code.outReg capacity i)).val = a.tree.eval env i :=
+ a.tree.physical_runs _ _ a.scratch_le env rs
+ ((Nat.mul_le_mul_left _ a.factor_le).trans hw) he hr _ _
+
+theorem describe_run {n U Z w p : ℕ} {R : Type*} [CommRing R] (q : SchurKey n U Z)
+ (entry : Entry n R) (k : ℕ) (rs : Regs (14+capacity) w) (hw : (p+1)*widthFactor ≤ w)
+ (he : ∀ i, inputs q k i < 2^p) (hr : ∀ i, (rs (Code.inReg capacity i)).val = inputs q k i)
+ (pub : Fin 0 → Word w) (persistent : Word w) :
+ ∃ t ≤ Operation.describe.clock w, ∃ out, Operation.describe.machine.Runs t
+ (ISA.bank pub persistent rs []) (ISA.bank pub persistent out []) ∧
+ decode entry (fun i => (out (Code.outReg capacity i)).val) = (q.node entry).describe := by
+ obtain ⟨t,ht,out,hrun,_,hout⟩ := Operation.describe.run _ rs hw he hr pub persistent
+ exact ⟨t,ht,out,hrun,(congrArg (decode entry) (funext hout)).trans (describe_eq entry q k)⟩
+
+theorem child_run {n U Z w p : ℕ} {R : Type*} [CommRing R] (q : SchurKey n U Z)
+ (entry : Entry n R) {t : ℕ} {f : Fin t → SchurKey n U Z × SchurKey n U Z}
+ (hn : q.node entry = .branch t f) (k : Fin t) (right : Bool)
+ (rs : Regs (14+capacity) w) (hw : (p+1)*widthFactor ≤ w)
+ (he : ∀ i, inputs q k.val i < 2^p) (hr : ∀ i, (rs (Code.inReg capacity i)).val = inputs q k.val i)
+ (pub : Fin 0 → Word w) (persistent : Word w) :
+ let a := if right then Operation.right else Operation.left
+ ∃ s ≤ a.clock w, ∃ out, a.machine.Runs s (ISA.bank pub persistent rs []) (ISA.bank pub persistent out []) ∧
+ (fun i => (out (Code.outReg capacity i)).val) = (if right then (f k).2 else (f k).1).words := by
+ let a := if right then Operation.right else Operation.left
+ obtain ⟨s,hs,out,hrun,_,hout⟩ := a.run _ rs hw he hr pub persistent
+ have ha : a.tree = child right := by cases right <;> rfl
+ rw [ha] at hout
+ exact ⟨s,hs,out,hrun,(funext hout).trans (child_eq entry q hn k right)⟩
+
+theorem gram_run {n m w p : ℕ} {R : Type*} [CommRing R] (M : Matrix (Fin n) (Fin m) R)
+ (i j : Fin n) (z : ℕ) (rs : Regs (14+capacity) w) (hw : (p+1)*widthFactor ≤ w)
+ (he : ∀ k, gramInput i j z m k < 2^p)
+ (hr : ∀ k, (rs (Code.inReg capacity k)).val = gramInput i j z m k)
+ (pub : Fin 0 → Word w) (persistent : Word w) :
+ ∃ s ≤ Operation.gram.clock w, ∃ out, Operation.gram.machine.Runs s
+ (ISA.bank pub persistent rs []) (ISA.bank pub persistent out []) ∧
+ decodeGram M (fun k => (out (Code.outReg capacity k)).val) = ((weightedGram M) i j).coeff z := by
+ obtain ⟨t,ht,out,hrun,_,hout⟩ := Operation.gram.run _ rs hw he hr pub persistent
+ exact ⟨t,ht,out,hrun,(congrArg (decodeGram M) (funext hout)).trans
+ ((gram_eq M i j z).trans (weightedGramEntryCoeff_eq M i j z))⟩
+
+end RankQuery.Stack.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackPower.lean b/lean/OAI/Computability/VPVNP/RankQueryStackPower.lean
new file mode 100644
index 0000000000..aeaca74c2d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackPower.lean
@@ -0,0 +1,180 @@
+import OAI.Computability.VPVNP.RankQueryStack
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Executing power-entry queries on a scalar stack
+
+Each product in a nontrivial power has one intermediate matrix index and
+one degree split. The machine obtains both from its single loop counter by
+division and remainder. Exponents and degrees in a saved query are bounded
+by their initial limits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+variable {Q R : Type*} [Semiring R]
+
+/-- The two recursive requests at each valid product index of a composite node. -/
+inductive Node (Q R : Type*) where
+ | leaf (r : R)
+ | branch (count : ℕ) (children : Fin count → Q × Q)
+
+/-- The matrix-index and degree loops share a single mixed-radix counter. -/
+def Node.box (n m : ℕ) (children : Fin n → Fin m → Q × Q) : Node Q R :=
+ .branch (n*m) fun k =>
+ let ij := finProdFinEquiv.symm k
+ children ij.1 ij.2
+
+namespace Node
+
+/-- Evaluate a leaf as its scalar and a branch as the sum of the products of its paired child
+values. -/
+def value (v : Q → R) : Node Q R → R
+ | .leaf r => r
+ | .branch _ f => ∑ i, v (f i).1 * v (f i).2
+
+theorem value_box (v : Q → R) (n m : ℕ) (f : Fin n → Fin m → Q × Q) :
+ (box n m f).value v = ∑ i, ∑ j, v (f i j).1 * v (f i j).2 := by
+ simp only [box, value]
+ rw [← finProdFinEquiv.sum_comp, Fintype.sum_prod_type]
+ simp only [Equiv.symm_apply_apply]
+
+/-- Describe a node by returning its scalar if it is a leaf or its number of product terms if
+it branches. -/
+def describe : Node Q R → Sum R ℕ
+ | .leaf r => .inl r
+ | .branch t _ => .inr t
+
+/-- Retrieve the two children of a product term, returning the fallback pair for a leaf or an
+out-of-range index. -/
+def children (fallback : Q) : Node Q R → ℕ → Q × Q
+ | .branch t f, k => if h : k < t then f ⟨k,h⟩ else (fallback,fallback)
+ | .leaf _, _ => (fallback,fallback)
+
+/-- Turn a family of query nodes into a stack program with descriptor, left-child, and
+right-child operations. -/
+def program (nodes : Q → Node Q R) : Program Q R where
+ describe q := (nodes q).describe
+ left q k := ((nodes q).children q k).1
+ right q k := ((nodes q).children q k).2
+
+theorem realizes {nodes : Q → Node Q R} {v : Q → R}
+ (h : ∀ q, v q = (nodes q).value v) : (program nodes).Realizes v := by
+ intro q
+ rw [h q]
+ simp only [program]
+ cases nodes q with
+ | leaf => rfl
+ | branch t f =>
+ simp only [describe, value]
+ rw [← Fin.sum_univ_eq_sum_range]
+ apply Finset.sum_congr rfl
+ intro k _
+ simp only [children, k.isLt, dite_eq_left]
+
+end Node
+
+/-- The bounded integer registers of one power request. -/
+structure PowerKey (n H Z : ℕ) where
+ /-- Exponent of the matrix power, bounded by `H`. -/
+ exponent : Fin (H + 1)
+ /-- Row index of the matrix-power entry whose coefficient is requested. -/
+ row : Fin n
+ /-- Column index of the matrix-power entry whose coefficient is requested. -/
+ col : Fin n
+ /-- Degree of the requested polynomial coefficient, bounded by `Z`. -/
+ degree : Fin (Z + 1)
+ deriving DecidableEq, Fintype
+
+variable {n H Z : ℕ}
+
+namespace PowerKey
+
+/-- Number of balanced exponent splits needed for this power query, bounded by the ceiling of
+its base-two logarithm. -/
+def depth (q : PowerKey n H Z) := Nat.clog 2 q.exponent.val
+
+/-- Requested coefficient of the specified row and column of the matrix power. -/
+def value (entry : Fin n → Fin n → ℕ → R) (q : PowerKey n H Z) : R :=
+ powerEntryCoeff entry q.exponent q.row q.col q.degree
+
+/-- Each child holds the lower or upper half of the exponent. -/
+def split (q : PowerKey n H Z) (j : Fin n) (d : Fin (q.degree.val + 1)) :
+ PowerKey n H Z × PowerKey n H Z :=
+ let h := q.exponent.val
+ (⟨⟨h / 2, by have := q.exponent.isLt; dsimp [h]; omega⟩, q.row, j,
+ ⟨d.val, by have := d.isLt; have := q.degree.isLt; omega⟩⟩,
+ ⟨⟨h - h / 2, by have := q.exponent.isLt; dsimp [h]; omega⟩, j, q.col,
+ ⟨q.degree.val - d.val, by have := q.degree.isLt; omega⟩⟩)
+
+/-- Describe a power query using the identity matrix at exponent zero, an entry read at
+exponent one, and paired subqueries at larger exponents. -/
+def node (entry : Fin n → Fin n → ℕ → R) (q : PowerKey n H Z) : Node (PowerKey n H Z) R :=
+ if q.exponent.val = 0 then .leaf (if q.row = q.col ∧ q.degree.val = 0 then 1 else 0)
+ else if q.exponent.val = 1 then .leaf (entry q.row q.col q.degree)
+ else Node.box n (q.degree.val + 1) q.split
+
+theorem value_node (entry : Fin n → Fin n → ℕ → R) (q : PowerKey n H Z) :
+ q.value entry = (q.node entry).value (value entry) := by
+ rw [value, powerEntryCoeff, node]
+ split_ifs <;> try rfl
+ rw [Node.value_box]
+ apply Finset.sum_congr rfl
+ intro j _
+ rw [Finset.Nat.sum_antidiagonal_eq_sum_range_succ_mk, ← Fin.sum_univ_eq_sum_range]
+ rfl
+
+/-- Stack program for extracting coefficients of bounded matrix powers by balanced exponent
+splitting. -/
+def program (entry : Fin n → Fin n → ℕ → R) : Program (PowerKey n H Z) R :=
+ Node.program (node entry)
+
+theorem realizes (entry : Fin n → Fin n → ℕ → R) :
+ (program (H := H) (Z := Z) entry).Realizes (value entry) :=
+ Node.realizes (value_node entry)
+
+theorem descends (entry : Fin n → Fin n → ℕ → R) :
+ (program (H := H) (Z := Z) entry).Descends depth := by
+ intro q t ht k hk
+ change (q.node entry).describe = Sum.inr t at ht
+ by_cases h0 : q.exponent.val = 0
+ · simp [node, h0, Node.describe] at ht
+ by_cases h1 : q.exponent.val = 1
+ · simp [node, h1, Node.describe] at ht
+ have ht' : n * (q.degree.val + 1) = t := by simpa [node, h0, h1, Node.box, Node.describe] using ht
+ subst t
+ have hh : 1 < q.exponent.val := by omega
+ simp only [program, Node.program, node, ite_eq_right h0, ite_eq_right h1, Node.box, Node.children, dite_eq_left hk, split, depth]
+ exact powerQuery_halves hh
+
+theorem arity (entry : Fin n → Fin n → ℕ → R) :
+ (program (H := H) (Z := Z) entry).ArityLE (n * (Z + 1)) := by
+ intro q t ht
+ change (q.node entry).describe = Sum.inr t at ht
+ unfold node at ht
+ split_ifs at ht <;> simp [Node.describe, Node.box] at ht
+ rw [← ht]
+ exact Nat.mul_le_mul_left _ q.degree.isLt
+
+/-- Every intermediate continuation has at most `⌈log₂ h⌉` frames. The run
+returns the actual scalar coefficient of the polynomial matrix power. -/
+theorem run (M : Matrix (Fin n) (Fin n) (Polynomial R)) (entry : Fin n → Fin n → ℕ → R)
+ (he : ∀ i j z, entry i j z = (M i j).coeff z) (q : PowerKey n H Z) :
+ ∃ t ≤ (5 + 6 * (n * (Z + 1))) ^ (q.depth + 1),
+ (program entry).Runs q.depth t (.enter q, [])
+ (.returned (((M ^ q.exponent.val) q.row q.col).coeff q.degree.val), []) := by
+ have h := Program.run_bounded (program entry) (value entry) depth _ (realizes entry)
+ (descends entry) (arity entry) q.depth q le_rfl []
+ simpa only [List.length_nil, Nat.zero_add, value, powerEntryCoeff_correct M entry he] using h
+
+end PowerKey
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackRegister.lean b/lean/OAI/Computability/VPVNP/RankQueryStackRegister.lean
new file mode 100644
index 0000000000..da3dff0434
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackRegister.lean
@@ -0,0 +1,182 @@
+import OAI.Computability.VPVNP.RAMTapeISAPrepare
+import OAI.Computability.VPVNP.RankQueryStackDispatch
+
+/-!
+# Fixed bit-stack routines for register decision trees
+
+Arithmetic instructions stage their two word operands before writeback. The
+natural subtraction instruction tests for underflow and returns zero in that
+case. Decisions compare two registers on the tape and execute one statically
+specified branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Dispatch
+
+open BurstRAM PrivateRAM RAMTape TapeWord
+
+variable {w r : ℕ}
+
+/-- Contents of `r` registers holding words of width `w`. -/
+abbrev Regs (r w : ℕ) := Fin r → Word w
+/-- A bit-stack routine on `r` register ports with no public input words. -/
+abbrev Machine (r : ℕ) := FiniteRoutine (ISA.Port r 0)
+
+/-- Translate a natural-arithmetic instruction to the corresponding binary word opcode. -/
+def Arith.opcode : Arith → BinaryOp
+ | .add => .add
+ | .sub => .sub
+ | .mul => .mul
+ | .div => .div
+ | .mod => .mod
+
+/-- Width-bounded register semantics for natural operations. -/
+def Arith.word (a : Arith) (x y : Word w) : Word w :=
+ if a = .sub ∧ x < y then 0 else a.opcode.eval x y
+
+theorem Arith.word_val (a : Arith) (x y : Word w) (h : a.eval x.val y.val < 2^w) :
+ (a.word x y).val = a.eval x.val y.val := by
+ cases a with
+ | sub =>
+ by_cases hs : x < y
+ · have hv : x.val < y.val := hs
+ simp [word, hs, Arith.eval, Nat.sub_eq_zero_of_le hv.le]
+ · have hv : y ≤ x := le_of_not_gt hs
+ simp [word, hs, opcode, BinaryOp.eval, Fin.sub_val_of_le hv, Arith.eval]
+ | add | mul | div | mod =>
+ simp [word, opcode, BinaryOp.eval, Fin.val_add, Fin.val_mul, Arith.eval]
+ exact Nat.mod_eq_of_lt h
+
+/-- Register programs built from literals, copies, arithmetic, sequencing, and equality tests. -/
+inductive RegCode (r : ℕ) where
+ | ret
+ | lit (dst : Fin r) (n : ℕ)
+ | copy (dst src : Fin r)
+ | op (dst : Fin r) (a : Arith) (x y : Fin r)
+ | seq (first second : RegCode r)
+ | test (x y : Fin r) (yes no : RegCode r)
+
+namespace RegCode
+
+/-- Execute a register program on width-`w` words, saturating subtraction at zero. -/
+def exec : RegCode r → Regs r w → Regs r w
+ | .ret, rs => rs
+ | .lit dst n, rs => Function.update rs dst (Fin.ofNat _ n)
+ | .copy dst src, rs => Function.update rs dst (rs src)
+ | .op dst a x y, rs => Function.update rs dst (a.word (rs x) (rs y))
+ | .seq l r, rs => r.exec (l.exec rs)
+ | .test x y yes no, rs => if rs x = rs y then yes.exec rs else no.exec rs
+
+/-- Weighted instruction count used to bound execution time, charging two units for arithmetic
+and the longer arm of a test. -/
+def length : RegCode r → ℕ
+ | .ret | .lit .. | .copy .. => 1
+ | .op .. => 2
+ | .seq l r => l.length + r.length
+ | .test _ _ yes no => 1 + max yes.length no.length
+
+private def ifTest (op : Comparison.Op) (x y : Fin r) (yes no : Machine r) : Machine r :=
+ (ISA.compareRegs op x y).followedBy (FiniteRoutine.ofRoutine
+ (Routine.popCase (.work 0) Routine.ret no.body yes.body))
+
+/-- Compile a register program into a bit-stack routine, testing for underflow before a
+subtraction. -/
+def compile : RegCode r → Machine r
+ | .ret => FiniteRoutine.ret
+ | .lit dst n => ISA.loadLiteral n dst
+ | .copy dst src => ISA.prepare (Instr.copy (w := 1) (p := 1) dst src 0)
+ | .op dst .sub x y => ifTest .lt x y (ISA.loadLiteral 0 dst) (ISA.binary .sub dst x y)
+ | .op dst a x y => ISA.binary a.opcode dst x y
+ | .seq l r => l.compile.followedBy r.compile
+ | .test x y yes no => ifTest .eq x y yes.compile no.compile
+
+private theorem ifTest_runs (op : Comparison.Op) (x y : Fin r) (yes no : Machine r)
+ (pub : Fin 0 → Word w) (persistent : Word w) (rs out : Regs r w) (t : ℕ)
+ (hb : (if op.eval (rs x) (rs y) then yes else no).Runs t
+ (ISA.bank pub persistent rs []) (ISA.bank pub persistent out [])) :
+ (ifTest op x y yes no).Runs (20*w+10 + (t+1))
+ (ISA.bank pub persistent rs []) (ISA.bank pub persistent out []) := by
+ let s := ISA.bank pub persistent rs []
+ let b := op.eval (rs x) (rs y)
+ have hb' : (if b then yes else no).Runs t s (ISA.bank pub persistent out []) := hb
+ have hc := ISA.compareRegs_run op x y pub persistent rs []
+ have hu : Function.update (Function.update s (.work 0) [b]) (.work 0) [] = s := by
+ rw [Function.update_idem]; exact Function.update_eq_self ..
+ apply FiniteRoutine.Runs.followedBy hc
+ change (Routine.popCase (.work 0) Routine.ret no.body yes.body).Runs (t+1)
+ (Function.update s (.work 0) [b]) (ISA.bank pub persistent out [])
+ cases h : b with
+ | false =>
+ apply Routine.runs_popCase_false (tail := []) (hs := Function.update_self ..)
+ rw [← h, hu]
+ simpa [h] using hb'
+ | true =>
+ apply Routine.runs_popCase_true (tail := []) (hs := Function.update_self ..)
+ rw [← h, hu]
+ simpa [h] using hb'
+
+/-- The compiled program is finite and independent of the operand width.
+It returns the specified register bank within a quadratic per-instruction
+bit-stack clock. -/
+theorem compile_runs (c : RegCode r) (pub : Fin 0 → Word w) (persistent : Word w) (rs : Regs r w) :
+ ∃ t ≤ c.length * (100*(w+1)^2), c.compile.Runs t (ISA.bank pub persistent rs [])
+ (ISA.bank pub persistent (c.exec rs) []) := by
+ have hc : 20*w+11 ≤ 100*(w+1)^2 := by nlinarith [Nat.zero_le (w^2)]
+ induction c generalizing rs with
+ | ret => exact ⟨1, by change 1 ≤ 1 * _; omega, Routine.runs_ret _⟩
+ | lit dst n => exact ⟨8*w+3, by change _ ≤ 1 * _; omega, ISA.loadLiteral_run ..⟩
+ | copy dst src =>
+ let ins : Instr 1 1 r 0 := .copy dst src 0
+ let cfg : LogConfig w 1 r := ⟨0,persistent,rs,[]⟩
+ obtain ⟨t,ht,hr⟩ := ISA.prepare_runs ins pub cfg
+ exact ⟨t, by simpa [length, ISA.prepareBound, cfg] using ht, hr⟩
+ | op dst a x y =>
+ cases a with
+ | add | mul | div | mod =>
+ obtain ⟨t,ht,hr⟩ := ISA.binary_runs _ dst x y pub persistent rs []
+ exact ⟨t, by change _ ≤ 2 * _; omega, hr⟩
+ | sub =>
+ cases h : Comparison.Op.lt.eval (rs x) (rs y) with
+ | false =>
+ have hn : ¬rs x < rs y := by simpa [Comparison.Op.eval] using h
+ obtain ⟨t,ht,hr⟩ := ISA.binary_runs BinaryOp.sub dst x y pub persistent rs []
+ have hrun := ifTest_runs .lt x y (ISA.loadLiteral 0 dst) (ISA.binary .sub dst x y) pub persistent rs _ t
+ (by simpa [h] using hr)
+ exact ⟨20*w+10+(t+1), by change _ ≤ 2 * _; omega, by simpa [exec, compile, Arith.word, hn, Arith.opcode] using hrun⟩
+ | true =>
+ have hy : rs x < rs y := by simpa [Comparison.Op.eval] using h
+ have hr := ISA.loadLiteral_run 0 dst pub persistent rs []
+ have hrun := ifTest_runs .lt x y (ISA.loadLiteral 0 dst) (ISA.binary .sub dst x y) pub persistent rs _ _
+ (by simpa [h] using hr)
+ exact ⟨20*w+10+(8*w+3+1), by change _ ≤ 2 * _; omega, by simpa [exec, compile, Arith.word, hy] using hrun⟩
+ | seq l r ihl ihr =>
+ obtain ⟨a,ha,hl⟩ := ihl rs
+ obtain ⟨b,hb,hr⟩ := ihr (l.exec rs)
+ exact ⟨a+b, by simpa [length, Nat.add_mul] using Nat.add_le_add ha hb, hl.followedBy hr⟩
+ | test x y yes no ihy ihn =>
+ by_cases he : rs x = rs y
+ · have hf : Comparison.Op.eq.eval (rs x) (rs y) = true := by simp [Comparison.Op.eval, he]
+ obtain ⟨t,ht,hr⟩ := ihy rs
+ have hrun := ifTest_runs .eq x y yes.compile no.compile pub persistent rs _ _ (by simpa [hf] using hr)
+ refine ⟨_, ?_, by simpa [compile, exec, he] using hrun⟩
+ have hm := Nat.mul_le_mul_right (100*(w+1)^2) (Nat.le_max_left yes.length no.length)
+ simp only [length, Nat.add_mul, Nat.one_mul]
+ omega
+ · have hf : Comparison.Op.eq.eval (rs x) (rs y) = false := by simp [Comparison.Op.eval, he]
+ obtain ⟨t,ht,hr⟩ := ihn rs
+ have hrun := ifTest_runs .eq x y yes.compile no.compile pub persistent rs _ _ (by simpa [hf] using hr)
+ refine ⟨_, ?_, by simpa [compile, exec, he] using hrun⟩
+ have hm := Nat.mul_le_mul_right (100*(w+1)^2) (Nat.le_max_right yes.length no.length)
+ simp only [length, Nat.add_mul, Nat.one_mul]
+ omega
+
+end RegCode
+
+end RankQuery.Stack.Dispatch
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackScan.lean b/lean/OAI/Computability/VPVNP/RankQueryStackScan.lean
new file mode 100644
index 0000000000..7e31378efa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackScan.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.RankQueryStackBounds
+
+/-!
+# Clocked stack computation of rectangular matrix rank
+
+The evaluator halts when it reaches a returned scalar at empty stack. The rank
+scan uses this evaluator for every bidegree, with no access to polynomial
+matrices or their determinants.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+namespace Program
+
+variable {Q R : Type*} [Semiring R] (p : Program Q R)
+
+/-- Tail-recursive execution with a timeout. An empty-stack return is a
+successful result, including exactly at the clock boundary. -/
+def drive : ℕ → Config Q R → Option R
+ | _, (.returned r, []) => some r
+ | 0, _ => none
+ | t+1, c => drive t (p.step c)
+
+theorem drive_next (t : ℕ) (c : Config Q R) : p.drive (t+1) c = p.drive t (p.step c) := by
+ rcases c with ⟨control, s⟩
+ cases control with
+ | enter | scan => rfl
+ | returned r => cases s <;> cases t <;> rfl
+
+theorem Runs.drive {cap t : ℕ} {a b : Config Q R} (h : p.Runs cap t a b) (rem : ℕ) :
+ p.drive (t+rem) a = p.drive rem b := by
+ induction h with
+ | done => simp
+ | next _ _ ih => rw [Nat.succ_add, drive_next, ih]
+
+end Program
+
+namespace SchurKey
+
+variable {n : ℕ} {R : Type*} [CommRing R]
+
+/-- Bound on abstract stack transitions for a Schur query with matrix order `n` and degree
+limits `U` and `Z`. -/
+def clock (n U Z : ℕ) :=
+ (5 + 6 * arityBound n U Z) ^ (Nat.clog 2 U + 4 + Nat.clog 2 n + 1)
+
+/-- Run the determinant coefficient query at bidegree `(u,z)` with its proved transition bound,
+defaulting to zero on timeout. -/
+def compute (entry : Entry n R) (u z : ℕ) : R :=
+ ((program entry).drive (clock n u z) (.enter (root (Fin.last u) (Fin.last z)), [])).getD 0
+
+theorem compute_correct (M : Matrix (Fin n) (Fin n) (Polynomial R)) (entry : Entry n R)
+ (he : ∀ i j z, entry i j z = (M i j).coeff z) (u z : ℕ) :
+ compute entry u z = (M.charpolyRev.coeff u).coeff z := by
+ obtain ⟨t,ht,hrun⟩ := run M entry he (Fin.last u) (Fin.last z)
+ change t ≤ clock n u z at ht
+ have hr := hrun.drive (program entry) (clock n u z - t)
+ rw [Nat.add_sub_of_le ht] at hr
+ unfold compute
+ rw [hr]
+ cases clock n u z - t <;> rfl
+
+/-- Rectangular matrix rank from the stack program and scalar input accesses. -/
+def computeRank {F : Type*} [CommRing F] [DecidableEq F] {m : ℕ}
+ (M : Matrix (Fin n) (Fin m) F) : ℕ :=
+ scanRank n m (compute (weightedGramEntryCoeff M))
+
+theorem computeRank_eq {F : Type*} [Field F] [DecidableEq F] {m : ℕ}
+ (M : Matrix (Fin n) (Fin m) F) : computeRank M = M.rank :=
+ scanRank_correct M _ (compute_correct (weightedGram M) _ (weightedGramEntryCoeff_eq M))
+
+theorem arityBound_le_exp (n U Z s : ℕ) (hn : n ≤ 2^s) (hu : U ≤ 2^s) (hz : Z ≤ 2^s) :
+ arityBound n U Z ≤ 2 ^ (2*s + 4) := by
+ let A := 2^s
+ have hA : 1 ≤ A := Nat.one_le_pow _ _ (by decide)
+ change n ≤ A at hn
+ change U ≤ A at hu
+ change Z ≤ A at hz
+ have hZ : Z + 1 ≤ 2*A := by omega
+ have hU : U + 1 ≤ 2*A := by omega
+ have hn2 := Nat.mul_le_mul hn hn
+ have hnZ := Nat.mul_le_mul hn hZ
+ have huZ := Nat.mul_le_mul hU hZ
+ have ha2 := Nat.mul_le_mul_left A hA
+ have hr : 2 ^ (2*s + 4) = 16*(A*A) := by dsimp [A]; rw [two_mul, pow_add, pow_add]; ring
+ rw [hr, arityBound]
+ nlinarith
+
+/-- The clock bound is singly exponential in the common bit bound. -/
+theorem clock_le_exp (n u z s : ℕ) (hn : n ≤ 2^s) (hu : u ≤ 2^s) (hz : z ≤ 2^s) :
+ clock n u z ≤ 2 ^ ((2*s+8)*(2*s+5)) := by
+ have ha := arityBound_le_exp n u z s hn hu hz
+ have hA := Nat.one_le_pow (2*s+4) 2 (by decide)
+ have hb : 5+6*arityBound n u z ≤ 2^(2*s+8) := by
+ rw [show 2*s+8 = (2*s+4)+4 by omega, pow_add]
+ norm_num
+ omega
+ have hd : Nat.clog 2 u+4+Nat.clog 2 n+1 ≤ 2*s+5 := by
+ have := Nat.clog_le_of_le_pow hn
+ have := Nat.clog_le_of_le_pow hu
+ omega
+ calc
+ clock n u z ≤ (2^(2*s+8)) ^ (Nat.clog 2 u+4+Nat.clog 2 n+1) := Nat.pow_le_pow_left hb _
+ _ ≤ (2^(2*s+8)) ^ (2*s+5) := Nat.pow_le_pow_right (by positivity) hd
+ _ = _ := (pow_mul ..).symm
+
+/-- Total scalar-stack clock over the rectangular scan, including queries
+for zero rows or zero columns. -/
+theorem rankClock_le_exp (n m p : ℕ) (hn : n ≤ 2^p) (hm : m ≤ 2^p) :
+ let s := 2*p+1
+ ∑ u : Fin (n+1), ∑ z : Fin ((n+m)*n+1), clock n u z ≤
+ 2^(p+1 + (s+1) + (2*s+8)*(2*s+5)) := by
+ let s := 2*p+1
+ let c := (2*s+8)*(2*s+5)
+ have hN : n ≤ 2^s := hn.trans (Nat.pow_le_pow_right (by decide) (by dsimp [s]; omega))
+ have hZ : (n+m)*n ≤ 2^s := calc
+ _ ≤ (2^p+2^p)*2^p := Nat.mul_le_mul (Nat.add_le_add hn hm) hn
+ _ = _ := by dsimp [s]; rw [two_mul p, pow_add, pow_add]; ring
+ have hsucc (a k : ℕ) (h : a ≤ 2^k) : a+1 ≤ 2^(k+1) := by
+ rw [pow_succ]
+ have := Nat.one_le_pow k 2 (by decide)
+ omega
+ change _ ≤ 2^(p+1 + (s+1) + c)
+ calc
+ _ ≤ ∑ _u : Fin (n+1), ∑ _z : Fin ((n+m)*n+1), 2^c :=
+ Finset.sum_le_sum fun u _ => Finset.sum_le_sum fun z _ =>
+ clock_le_exp n u z s hN ((Nat.lt_succ_iff.mp u.isLt).trans hN) ((Nat.lt_succ_iff.mp z.isLt).trans hZ)
+ _ = (n+1)*(((n+m)*n+1)*2^c) := by simp
+ _ ≤ (2^(p+1)) * ((2^(s+1)) * 2^c) :=
+ Nat.mul_le_mul (hsucc n p hn) (Nat.mul_le_mul_right _ (hsucc _ s hZ))
+ _ = _ := by simp only [pow_add, mul_assoc]
+
+end SchurKey
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackScanSetup.lean b/lean/OAI/Computability/VPVNP/RankQueryStackScanSetup.lean
new file mode 100644
index 0000000000..1069edaa2e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackScanSetup.lean
@@ -0,0 +1,218 @@
+import OAI.Computability.VPVNP.RankQueryStackBorrow
+import OAI.Computability.VPVNP.RankQueryStackActivate
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+
+/-! # Preparing a child call or a completed Schur sum -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Engine.ScanCall
+
+open RAMTape UniversalCountStack SliceArithmetic.CallClear
+
+variable {K : Type} [DecidableEq K]
+
+/-- Wire the decrement routine to the live remaining-count field, a scratch stack, and the
+engine's condition port. -/
+def borrowPorts (tmp : K) : Borrow.Port → Engine.Port K
+ | .counter => .frame (.inl 7)
+ | .scratch => .aux tmp
+ | .flag => .condition
+
+omit [DecidableEq K] in
+private theorem borrowPorts_inj (tmp : K) : Function.Injective (borrowPorts tmp) := by
+ intro i j h; cases i <;> cases j <;> simp_all [borrowPorts]
+
+/-- Decrement the remaining count and signal whether the scan has exhausted its product terms. -/
+def test (tmp : K) : FiniteRoutine (Engine.Port K) :=
+ (FiniteRoutine.ofRoutine Borrow.body).onPorts (borrowPorts tmp)
+
+private def livePorts : List (Engine.Port K) := (List.finRange 10).map (fun i => .frame (.inl i))
+
+/-- Return the completed accumulator, clear the live frame fields, and signal completion of the
+scan. -/
+def finish (tmp : K) : FiniteRoutine (Engine.Port K) :=
+ ((SuccessorFields.prependCopy (.frame (.inl 8)) .result (.aux tmp)).followedBy (cleanup livePorts)).followedBy
+ (.ofRoutine (Routine.push .condition true))
+
+private def field (k : Engine.Port K) (b : Bool) : FiniteRoutine (Engine.Port K) := .ofRoutine (Routine.push k b)
+
+/-- Compute the left child's words, set the saved direction and select descent. -/
+def descend (left : FiniteRoutine (Engine.Port K)) : FiniteRoutine (Engine.Port K) :=
+ (left.followedBy (field (.frame (.inl 0)) false)).followedBy (field .condition false)
+
+/-- Inspect the remaining count, then stage the next left child or return the completed Schur
+sum. -/
+def scan (tmp : K) (left : FiniteRoutine (Engine.Port K)) : FiniteRoutine (Engine.Port K) :=
+ (test tmp).followedBy (.ofRoutine (Routine.popCase .condition (Routine.halt false) (descend left).body (finish tmp).body))
+
+/-- Prepare the second child of a summand. Its suspended frame receives the
+just-returned left operand before the result port is cleared. -/
+def right (tmp : K) (child : FiniteRoutine (Engine.Port K)) : FiniteRoutine (Engine.Port K) :=
+ ((child.followedBy (SuccessorFields.prependCopy .result (.frame (.inl 9)) (.aux tmp))).followedBy
+ (clear .result)).followedBy (field (.frame (.inl 0)) true)
+
+variable {n U Z p e w v : ℕ} {c : SliceArithmetic.Vector p e}
+
+private def scanLive (q : Key n U Z) (counter : List Bool) (a : Scalar c) :=
+ fields w [] q counter (scalar v a) []
+
+private theorem test_general (tmp : K) (q : Key n U Z) (a : Scalar c) (fs : List (F n U Z c)) (aux : Stacks K)
+ (ht : aux tmp = []) (x y : List Bool) (done : Bool) (t : ℕ)
+ (h : Borrow.body.Runs t (Borrow.bank x [] []) (Borrow.bank y [] [done])) :
+ (test tmp).Runs t (store (scanLive (w := w) (v := v) q x a) (history w v fs) [] [] aux)
+ (store (scanLive (w := w) (v := v) q y a) (history w v fs) [done] [] aux) := by
+ apply FiniteRoutine.runs_onPorts_framed _ (borrowPorts_inj tmp) h
+ · intro j; cases j <;> first | rfl | exact ht
+ · intro j; cases j <;> first | rfl | exact ht
+ · intro j hj
+ cases j with
+ | frame k =>
+ cases k with
+ | inl i =>
+ fin_cases i <;> first | rfl | exact (hj .counter rfl).elim
+ | inr => rfl
+ | condition => exact (hj .flag rfl).elim
+ | result | aux => rfl
+
+private theorem update_sig (l h : Data) (s r : List Bool) (aux : Stacks K) (b : List Bool) :
+ Function.update (store l h s r aux) .condition b = store l h b r aux := by
+ funext j; cases j with
+ | frame k => cases k <;> rfl
+ | _ => rfl
+
+private theorem update_out (l h : Data) (s r : List Bool) (aux : Stacks K) (b : List Bool) :
+ Function.update (store l h s r aux) .result b = store l h s b aux := by
+ funext j; cases j with
+ | frame k => cases k <;> rfl
+ | _ => rfl
+
+private theorem cleanup_live (l h : Data) (sig ret : List Bool) (aux : Stacks K) :
+ erased livePorts (store l h sig ret aux) = store (fun _ => []) h sig ret aux := by
+ funext j; cases j with
+ | frame k => cases k <;> simp [erased, livePorts, store]
+ | _ => simp [erased, livePorts, store]
+
+private theorem finish_runs (tmp : K) (q : Key n U Z) (a : Scalar c) (fs : List (F n U Z c)) (aux : Stacks K)
+ (ht : aux tmp = []) :
+ ∃ t ≤ 5*(e*v)+10*(max 1 (max w (e*v))+1)+4,
+ (finish tmp).Runs t (store (scanLive (w := w) (v := v) q [] a) (history w v fs) [] [] aux)
+ (atControl w v (.returned a) fs aux [true]) := by
+ let l := scanLive (w := w) (v := v) q [] a
+ let h := history w v fs
+ let s := store l h [] [] aux
+ have copy := SuccessorFields.prependCopy_runs (Engine.Port.frame (.inl 8)) .result (.aux tmp)
+ (by simp) (by simp) (by simp) s ht
+ change (SuccessorFields.prependCopy _ _ _).Runs (5*(scalar v a).length+2) s
+ (Function.update s .result (scalar v a ++ [])) at copy
+ rw [List.append_nil, update_out, scalar_length] at copy
+ obtain ⟨t, hb, erase⟩ := cleanup_runs livePorts (store l h [] (scalar v a) aux) (max 1 (max w (e*v))) (by
+ intro j hj
+ obtain ⟨i, _, rfl⟩ := List.mem_map.mp hj
+ change (fields w [] q [] (scalar v a) [] i).length ≤ _
+ refine Fin.cases (by simp [fields]) (fun j => ?_) i
+ refine Fin.addCases (motive := fun j => (Fin.append (fun x => digits w (q.words x))
+ ![[],scalar v a,[]] j).length ≤ _) (fun x : Fin 6 => ?_) (fun x : Fin 3 => ?_) j
+ · simp
+ · rw [Fin.append_right]; fin_cases x <;> simp)
+ rw [cleanup_live] at erase
+ have sig := Routine.runs_push (Engine.Port.condition : Engine.Port K) true
+ (store (fun _ => []) h [] (scalar v a) aux)
+ change (field .condition true).Runs 1 _ (Function.update _ .condition [true]) at sig
+ rw [update_sig] at sig
+ simp only [livePorts, List.length_map, List.length_finRange] at hb
+ exact ⟨_, by omega, (copy.followedBy erase).followedBy sig⟩
+
+theorem zero_runs (tmp : K) (left : FiniteRoutine (Engine.Port K)) (q : Key n U Z) (a : Scalar c)
+ (fs : List (F n U Z c)) (aux : Stacks K) (ht : aux tmp = []) :
+ ∃ t ≤ 3*w+5*(e*v)+10*(max 1 (max w (e*v))+1)+8,
+ (scan tmp left).Runs t (atControl w v (.scan q 0 a) fs aux) (atControl w v (.returned a) fs aux [true]) := by
+ have testRun := test_general (w := w) (v := v) tmp q a fs aux ht _ _ _ _ (Borrow.zero_runs w)
+ obtain ⟨t, hticks, finishRun⟩ := finish_runs (w := w) (v := v) tmp q a fs aux ht
+ let mid := store (scanLive (w := w) (v := v) q [] a) (history w v fs) [true] [] aux
+ have branch := Routine.runs_popCase_true .condition (Routine.halt false) (descend left).body (finish tmp).body
+ (s := mid) (tail := []) rfl (show (finish tmp).body.Runs t (Function.update mid .condition []) _ by
+ rw [update_sig]; exact finishRun)
+ exact ⟨_, by omega, FiniteRoutine.Runs.followedBy testRun (b := .ofRoutine _) branch⟩
+
+private theorem setTag (q : Key n U Z) (tag k acc l xs : List Bool) (saved : Data)
+ (sig r : List Bool) (aux : Stacks K) :
+ Function.update (store (fields w tag q k acc l) saved sig r aux) (.frame (.inl 0)) xs =
+ store (fields w xs q k acc l) saved sig r aux := by
+ funext j
+ cases j with
+ | frame p => cases p with | inl i => fin_cases i <;> rfl | inr => rfl
+ | _ => rfl
+
+private theorem setLeft (q : Key n U Z) (tag k acc l xs : List Bool) (saved : Data)
+ (sig r : List Bool) (aux : Stacks K) :
+ Function.update (store (fields w tag q k acc l) saved sig r aux) (.frame (.inl 9)) xs =
+ store (fields w tag q k acc xs) saved sig r aux := by
+ funext j
+ cases j with
+ | frame p => cases p with | inl i => fin_cases i <;> rfl | inr => rfl
+ | _ => rfl
+
+/-- A positive loop counter prepares the left continuation and the pending child. -/
+theorem succ_runs (tmp : K) (left : FiniteRoutine (Engine.Port K)) (q : Key n U Z) (k : ℕ) (a : Scalar c)
+ (fs : List (F n U Z c)) (aux out : Stacks K) (ht : aux tmp = []) (hfit : k+1 < 2^w) {tc : ℕ}
+ (child : left.Runs tc (store (fields w [] q (digits w k) (scalar v a) []) (history w v fs) [] [] aux)
+ (store (fields w [] q (digits w k) (scalar v a) []) (history w v fs) [] [] out)) :
+ ∃ t ≤ tc+4*w+7, (scan tmp left).Runs t (atControl w v (.scan q (k+1) a) fs aux)
+ (store (nativeFrame w v (.left q k a)) (history w v fs) [false] [] out) := by
+ obtain ⟨s,hs,dec⟩ := Borrow.succ_runs w k hfit
+ have testRun := test_general (w := w) (v := v) tmp q a fs aux ht _ _ _ _ dec
+ let l := fields w [] q (digits w k) (scalar v a) []
+ let h := history w v fs
+ have dir := Routine.runs_push (Engine.Port.frame (.inl 0) : Engine.Port K) false (store l h [] [] out)
+ change (field (.frame (.inl 0)) false).Runs 1 _ (Function.update _ (.frame (.inl 0)) [false]) at dir
+ rw [setTag] at dir
+ have sig := Routine.runs_push (Engine.Port.condition : Engine.Port K) false
+ (store (nativeFrame w v (.left q k a)) h [] [] out)
+ change (field .condition false).Runs 1 _ (Function.update _ .condition [false]) at sig
+ rw [update_sig] at sig
+ have entry := (child.followedBy dir).followedBy sig
+ let mid := store l h [false] [] aux
+ have branch := Routine.runs_popCase_false .condition (Routine.halt false) (descend left).body (finish tmp).body
+ (s := mid) (tail := []) rfl (show (descend left).body.Runs (tc+1+1) (Function.update mid .condition []) _ by
+ rw [update_sig]; exact entry)
+ exact ⟨_, by omega, FiniteRoutine.Runs.followedBy testRun (b := .ofRoutine _) branch⟩
+
+/-- The left value changes ports while its parent's query and count are restored
+for the right-child dispatcher. -/
+theorem right_runs (tmp : K) (child : FiniteRoutine (Engine.Port K)) (q : Key n U Z) (k : ℕ) (acc l : Scalar c)
+ (fs : List (F n U Z c)) (aux out : Stacks K) (ht : out tmp = []) {tc : ℕ}
+ (dispatch : child.Runs tc (store (fields w [] q (digits w k) (scalar v acc) []) (history w v fs) [] (scalar v l) aux)
+ (store (fields w [] q (digits w k) (scalar v acc) []) (history w v fs) [] (scalar v l) out)) :
+ (right tmp child).Runs (tc+6*(e*v)+4)
+ (store (popped w v (.left q k acc)) (history w v fs) [] (scalar v l) aux)
+ (store (nativeFrame w v (.right q k acc l)) (history w v fs) [] [] out) := by
+ have hp : popped w v (.left q k acc) = fields w [] q (digits w k) (scalar v acc) [] := by
+ funext i; fin_cases i <;> rfl
+ rw [hp]
+ let h := history w v fs
+ let start := store (fields w [] q (digits w k) (scalar v acc) []) h [] (scalar v l) out
+ have copy := SuccessorFields.prependCopy_runs Engine.Port.result (.frame (.inl 9)) (.aux tmp)
+ (by simp) (by simp) (by simp) start ht
+ change (SuccessorFields.prependCopy _ _ _).Runs (5*(scalar v l).length+2) start
+ (Function.update start (.frame (.inl 9)) (scalar v l ++ [])) at copy
+ rw [List.append_nil, setLeft, scalar_length] at copy
+ let mid := store (fields w [] q (digits w k) (scalar v acc) (scalar v l)) h [] (scalar v l) out
+ have clearResult := clear_runs .result mid
+ change (clear .result).Runs ((scalar v l).length+1) mid (Function.update mid .result []) at clearResult
+ rw [update_out, scalar_length] at clearResult
+ have tag := Routine.runs_push (Engine.Port.frame (.inl 0) : Engine.Port K) true
+ (store (fields w [] q (digits w k) (scalar v acc) (scalar v l)) h [] [] out)
+ change (field (.frame (.inl 0)) true).Runs 1 _ (Function.update _ (.frame (.inl 0)) [true]) at tag
+ rw [setTag] at tag
+ have both := ((dispatch.followedBy copy).followedBy clearResult).followedBy tag
+ rw [show tc+6*(e*v)+4 = tc+(5*(e*v)+2)+(e*v+1)+1 by omega]
+ exact both
+
+end RankQuery.Stack.Engine.ScanCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackSchur.lean b/lean/OAI/Computability/VPVNP/RankQueryStackSchur.lean
new file mode 100644
index 0000000000..0cf9c0cfb5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackSchur.lean
@@ -0,0 +1,212 @@
+import OAI.Computability.VPVNP.RankQueryStackPower
+
+/-!
+# Stack execution of the Schur determinant product
+
+The query tags implement the balanced product of Schur factors, the two degree
+convolutions inside one factor, and the power of its trailing principal
+submatrix. The only matrix reads are individual scalar coefficients.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+variable {n U Z : ℕ} {R : Type*} [CommRing R]
+
+namespace Node
+
+/-- Relabel both child queries of every product term while preserving scalar leaves. -/
+def map {A B : Type*} (f : A → B) : Node A R → Node B R
+ | .leaf r => .leaf r
+ | .branch t g => .branch t (fun i => ((f (g i).1), f (g i).2))
+
+theorem value_map {A B : Type*} (f : A → B) (node : Node A R) (v : B → R) :
+ (node.map f).value v = node.value (v ∘ f) := by cases node <;> rfl
+
+end Node
+
+/-- A contiguous interval of Schur factors, stored by its start and its length. -/
+structure Block (n : ℕ) where
+ /-- First factor index in the contiguous block used by the balanced Schur product. -/
+ start : ℕ
+ /-- Number of consecutive Schur factors in the block. -/
+ count : ℕ
+ fits : start + count ≤ n
+
+namespace Block
+
+/-- Initial half of a block, containing the first `count / 2` factors. -/
+def lower (b : Block n) : Block n :=
+ ⟨b.start, b.count / 2, by have := b.fits; omega⟩
+
+/-- Remaining half of a block, starting immediately after its initial half. -/
+def upper (b : Block n) : Block n :=
+ ⟨b.start + b.count / 2, b.count - b.count / 2, by have := b.fits; omega⟩
+
+end Block
+
+/-- Natural numbers from zero through the inclusive bound `b`. -/
+abbrev Limit (b : ℕ) := Fin (b + 1)
+/-- Local indices of the principal submatrix strictly after pivot `a`. -/
+abbrev TailIndex (a : Fin n) := Fin (n - a.val - 1)
+
+/-- Embed the first part of a coefficient-degree split into the original degree range. -/
+def lowDegree {b : ℕ} (q : Limit b) (d : Fin (q.val + 1)) : Limit b :=
+ ⟨d.val, by have := d.isLt; have := q.isLt; omega⟩
+
+/-- Complementary degree `q - d` of a coefficient convolution. -/
+def highDegree {b : ℕ} (q : Limit b) (d : Fin (q.val + 1)) : Limit b :=
+ ⟨q.val - d.val, by have := q.isLt; omega⟩
+
+/-- Subtract `k` from a bounded natural degree, saturating at zero. -/
+def predBy {b : ℕ} (q : Limit b) (k : ℕ) : Limit b :=
+ ⟨q.val - k, by have := q.isLt; omega⟩
+
+/-- Translate a local tail index to its index in the original matrix after pivot `a`. -/
+def tailIndex (a : Fin n) (i : TailIndex a) : Fin n := suffixIndex a i.succ
+
+/-- Scalar coefficient reader indexed by matrix row, matrix column, and polynomial degree. -/
+abbrev Entry (n : ℕ) (R : Type*) := Fin n → Fin n → ℕ → R
+
+/-- Restrict the coefficient reader to the trailing principal submatrix after pivot `a`. -/
+def tailEntry (entry : Entry n R) (a : Fin n) : Entry (n-a.val-1) R :=
+ fun i j => entry (tailIndex a i) (tailIndex a j)
+
+/-- The query tags and their numeric fields. `inner` handles the convolution of
+the leading row with a matrix power, and `outer` multiplies by the trailing
+column with the negative sign of the Schur factor. -/
+inductive SchurKey (n U Z : ℕ) where
+ | product (d : Limit (Nat.clog 2 n)) (b : Block n) (u : Limit U) (z : Limit Z)
+ | factor (a : Fin n) (u : Limit U) (z : Limit Z)
+ | outer (a : Fin n) (h : Limit U) (i j : TailIndex a) (z : Limit Z)
+ | inner (a : Fin n) (h : Limit U) (i j : TailIndex a) (z : Limit Z)
+ | power (a : Fin n) (q : PowerKey (n-a.val-1) U Z)
+ | scalar (negative : Bool) (i j : Fin n) (z : Limit Z)
+ | one
+
+namespace SchurKey
+
+/-- Schur query keys with fixed matrix order and two bounded coefficient degrees. -/
+abbrev K (n U Z : ℕ) := SchurKey n U Z
+
+/-- Bivariate coefficient of the constant polynomial one, supported at bidegree `(0,0)`. -/
+def unitCoeff (u z : ℕ) : R := if u = 0 ∧ z = 0 then 1 else 0
+
+/-- Coefficient at `(u,z)` of the Schur factor for pivot `a`, using the unit factor after the
+last pivot. -/
+def factorCoeff (entry : Entry n R) (a u z : ℕ) : R :=
+ if ha : a < n then
+ let i : Fin n := ⟨a, ha⟩
+ streamedHeadFactorQuery (fun b c => entry (suffixIndex i b) (suffixIndex i c)) u z
+ else unitCoeff u z
+
+/-- Degree-`z` convolution of a pivot-row entry and an entry of the `h`th power of the trailing
+submatrix. -/
+def innerCoeff (entry : Entry n R) (a : Fin n) (h : ℕ) (i j : TailIndex a) (z : ℕ) : R :=
+ streamAntiSum z fun e₁ e₂ => entry a (tailIndex a i) e₁ *
+ powerEntryCoeff (tailEntry entry a) h i j e₂
+
+/-- Degree-`z` convolution of the inner Schur product and the negated entry returning from the
+tail to the pivot column. -/
+def outerCoeff (entry : Entry n R) (a : Fin n) (h : ℕ) (i j : TailIndex a) (z : ℕ) : R :=
+ streamAntiSum z fun d₁ d₂ => innerCoeff entry a h i j d₁ * (-entry (tailIndex a j) a d₂)
+
+/-- Scalar specified by a Schur query, from a product of factors down to an individual matrix
+coefficient. -/
+def value (entry : Entry n R) : K n U Z → R
+ | .product d b u z => balancedBivariateProduct (factorCoeff entry) d b.start b.count u z
+ | .factor a u z => factorCoeff entry a u z
+ | .outer a h i j z => outerCoeff entry a h i j z
+ | .inner a h i j z => innerCoeff entry a h i j z
+ | .power a q => q.value (tailEntry entry a)
+ | .scalar negative i j z => if negative then -entry i j z else entry i j z
+ | .one => 1
+
+/-- Expand a Schur query into a scalar leaf or the indexed products that make up its next
+coefficient convolution. -/
+def node (entry : Entry n R) : K n U Z → Node (K n U Z) R
+ | .product d b u z =>
+ if d.val = 0 then
+ if hc : 0 < b.count then
+ let a : Fin n := ⟨b.start, by have := b.fits; omega⟩
+ .branch 1 fun _ => (.factor a u z, .one)
+ else .leaf (unitCoeff u z)
+ else Node.box (u.val+1) (z.val+1) fun s t =>
+ (.product (predBy d 1) b.lower (lowDegree u s) (lowDegree z t),
+ .product (predBy d 1) b.upper (highDegree u s) (highDegree z t))
+ | .factor a u z =>
+ if u.val = 0 then .leaf (unitCoeff 0 z)
+ else if u.val = 1 then .leaf (-entry a a z)
+ else Node.box (n-a.val-1) (n-a.val-1) fun i j => (.outer a (predBy u 2) i j z, .one)
+ | .outer a h i j z =>
+ .branch (z.val+1) fun d => (.inner a h i j (lowDegree z d), .scalar true (tailIndex a j) a (highDegree z d))
+ | .inner a h i j z =>
+ .branch (z.val+1) fun e =>
+ (.scalar false a (tailIndex a i) (lowDegree z e), .power a ⟨h,i,j,highDegree z e⟩)
+ | .power a q => (q.node (tailEntry entry a)).map (.power a)
+ | .scalar negative i j z => .leaf (if negative then -entry i j z else entry i j z)
+ | .one => .leaf 1
+
+private theorem factor_succ (entry : Entry n R) (a : Fin n) (h z : ℕ) :
+ factorCoeff entry a (h+2) z = ∑ i, ∑ j, outerCoeff entry a h i j z := by
+ have hz : suffixIndex a 0 = a := by apply Fin.ext; simp [suffixIndex]
+ simp only [factorCoeff, a.isLt, dite_eq_left, streamedHeadFactorQuery, streamSum_eq,
+ streamAntiSum, outerCoeff, innerCoeff, streamedPowerEntryCoeff_eq, tailIndex,
+ hz, mul_neg, Finset.sum_neg_distrib]
+ rfl
+
+theorem value_node (entry : Entry n R) (q : K n U Z) :
+ q.value entry = (q.node entry).value (value entry) := by
+ cases q with
+ | product d b u z =>
+ rcases d with ⟨d, hd⟩
+ cases d with
+ | zero =>
+ by_cases hc : 0 < b.count
+ · have hn : b.count ≠ 0 := by omega
+ simp [value, node, balancedBivariateProduct, balancedProduct, hc, hn, Node.value]
+ · have hn : b.count = 0 := by omega
+ simp [value, node, balancedBivariateProduct, balancedProduct, hn, Node.value, unitCoeff]
+ | succ d =>
+ simp only [value, node, Nat.succ_ne_zero, ite_false, Node.value_box,
+ balancedBivariateProduct, balancedProduct, streamAntiSum, streamSum_eq]
+ rfl
+ | factor a u z =>
+ have hzero : suffixIndex a 0 = a := by apply Fin.ext; simp [suffixIndex]
+ rcases u with ⟨u, hu⟩
+ rcases u with _ | _ | h
+ · simp [value, node, factorCoeff, Node.value, streamedHeadFactorQuery, unitCoeff]
+ · simp [value, node, factorCoeff, Node.value, streamedHeadFactorQuery, hzero]
+ · simpa [value, node, Node.value_box, predBy] using factor_succ entry a h z
+ | outer a h i j z => simp only [value, node, Node.value, outerCoeff, streamAntiSum, streamSum_eq]; rfl
+ | inner a h i j z => simp only [value, node, Node.value, innerCoeff, streamAntiSum, streamSum_eq]; rfl
+ | power a q =>
+ rw [node, Node.value_map]
+ exact q.value_node _
+ | scalar | one => rfl
+
+/-- Stack program evaluating Schur queries by expanding their product nodes and reading scalar
+leaves. -/
+def program (entry : Entry n R) : Program (K n U Z) R := Node.program (node entry)
+
+theorem realizes (entry : Entry n R) : (program (U := U) (Z := Z) entry).Realizes (value entry) :=
+ Node.realizes (value_node entry)
+
+/-- Initial query for coefficient `(u,z)` of the determinant pencil, taking the Schur product
+over all `n` factors. -/
+def root (u : Limit U) (z : Limit Z) : K n U Z :=
+ .product (Fin.last _) ⟨0, n, by omega⟩ u z
+
+theorem value_root (entry : Entry n R) (u : Limit U) (z : Limit Z) :
+ (root (n := n) u z).value entry = determinantQuery entry u z := rfl
+
+end SchurKey
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackSignedCount.lean b/lean/OAI/Computability/VPVNP/RankQueryStackSignedCount.lean
new file mode 100644
index 0000000000..985426479b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackSignedCount.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.RankQueryStackSignedScalar
+import OAI.Computability.VPVNP.RankQueryStackNativeFrames
+import OAI.Computability.VPVNP.SliceArithmeticSignedCount
+import OAI.Computability.VPVNP.UniversalCountStackBounds
+
+/-!
+# Feeding an integer equation coefficient to the native rank-query stack
+
+The two counted Boolean circuits return the positive and negative parts of
+the coefficient. Their little-endian counter words supply a fixed stack
+routine that returns the actual integer cast in the advised scalar ring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Scalar
+
+open SliceArithmetic RAMTape SliceArithmeticSignedCount
+
+theorem signedCount_runs {p e w : ℕ} [Fact p.Prime] [NeZero e]
+ (hw : Word.workingWidth p ≤ w) (c : Vector p e) (z : ℤ) (positive negative suffix : List Bool)
+ (hsigned : (TapeWord.value positive : ℤ) - (TapeWord.value negative : ℤ) = z) :
+ ∃ t ≤ callCap positive.length negative.length e w, machine.Runs t
+ (clean (external p e w positive negative suffix))
+ (clean (external p e w positive negative (Engine.scalar w (z : Scalar c) ++ suffix))) := by
+ let a : Fin p := difference p positive negative
+ have hcast : pack c (scale a (one p e)) = (z : Scalar c) := by
+ simpa only [a, difference, hsigned] using pack_signed_counts c (TapeWord.value positive) (TapeWord.value negative)
+ have hbits : Engine.scalar w (z : Scalar c) =
+ BurstRAM.wordBits (Word.limb w a) ++ List.replicate ((e-1)*w) false := by
+ rw [← hcast, Engine.scalar, digits_pack]
+ exact packed_scale_one (NeZero.pos e) w a
+ rw [hbits]
+ exact machine_runs (NeZero.pos e) hw positive negative suffix
+
+/-- Every intermediate stack fits within the input lengths plus the
+polynomial time bound of this coefficient conversion. -/
+theorem signedCount_spaceRun {p e w : ℕ} [Fact p.Prime] [NeZero e]
+ (hw : Word.workingWidth p ≤ w) (c : Vector p e) (z : ℤ) (positive negative suffix : List Bool)
+ (hsigned : (TapeWord.value positive : ℤ) - (TapeWord.value negative : ℤ) = z) :
+ let cap := callCap positive.length negative.length e w
+ let space := positive.length + negative.length + suffix.length + e + w + cap
+ ∃ t ≤ cap, UniversalCountStack.SpaceRun machine.body.standalone space t (some machine.body.entry)
+ (clean (external p e w positive negative suffix)) none
+ (clean (external p e w positive negative (Engine.scalar w (z : Scalar c) ++ suffix))) := by
+ intro cap space
+ obtain ⟨t, ht, run⟩ := signedCount_runs hw c z positive negative suffix hsigned
+ refine ⟨t, ht, UniversalCountStack.spaceRun_of_steps run ?_⟩
+ rintro (i|i)
+ · cases i with
+ | divide j => cases j <;> simp [clean, frame, space, cap] <;> omega
+ | _ => simp [clean, frame, space, cap]; omega
+ · cases i <;> simp [clean, frame, external, space, cap] <;> omega
+
+end RankQuery.Stack.Scalar
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackSignedScalar.lean b/lean/OAI/Computability/VPVNP/RankQueryStackSignedScalar.lean
new file mode 100644
index 0000000000..204ac3459a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackSignedScalar.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.RankQueryStackField
+import OAI.Computability.VPVNP.SliceArithmeticConstantEmit
+import OAI.Computability.VPVNP.SliceArithmeticRound
+
+/-!
+# Power-basis representation of a signed coefficient
+
+A matrix coefficient supplied as the difference of two nonnegative counts
+reduces to one prime-field limb. Storing that limb followed by zero padding
+writes exactly the scalar used by the determinant stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack
+
+open SliceArithmetic SliceArithmeticRound BurstRAM RAMTape
+
+private theorem packed_zeros {p : ℕ} [NeZero p] (w n : ℕ) :
+ packed w (List.replicate n (0 : Fin p)) = List.replicate (n * w) false := by
+ induction n with
+ | zero => simp [packed]
+ | succ n ih =>
+ rw [List.replicate_succ, packed, List.flatMap_cons]
+ change wordBits (Word.limb w (0 : Fin p)) ++ packed w (List.replicate n (0 : Fin p)) = _
+ rw [ih, Nat.succ_mul, Nat.add_comm, List.replicate_add, UnaryWord.zeros_wordBits w]
+ simp [Word.limb]
+
+/-- The packed constant vector has exactly the bit prefix returned by the
+fixed constant emitter. -/
+theorem packed_scale_one {p e : ℕ} [NeZero p] (he : 0 < e) (w : ℕ) (a : Fin p) :
+ packed w (List.ofFn (scale a (one p e))) =
+ wordBits (Word.limb w a) ++ List.replicate ((e - 1) * w) false := by
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (Nat.ne_of_gt he)
+ rw [List.ofFn_succ]
+ have htail : (fun i : Fin n => scale a (one p (n + 1)) i.succ) = fun _ => 0 := by
+ funext i
+ simp [scale, one]
+ rw [htail, List.ofFn_const, packed, List.flatMap_cons]
+ change wordBits (Word.limb w (scale a (one p (n+1)) 0)) ++
+ packed w (List.replicate n (0 : Fin p)) = _
+ simp [packed_zeros, scale, one]
+
+namespace Scalar
+
+/-- Reducing the two counts modulo the advised prime, subtracting them and
+packing the result in the low limb realizes integer casting into the scalar ring. -/
+theorem pack_signed_counts {p e : ℕ} [Fact p.Prime] [NeZero e]
+ (c : Vector p e) (positive negative : ℕ) :
+ pack c (scale (Fin.ofNat p positive - Fin.ofNat p negative) (one p e)) =
+ (((positive : ℤ) - (negative : ℤ) : ℤ) : Scalar c) := by
+ apply interpret_injective c
+ change value (modulus c) (pack c (scale _ (one p e))).digits =
+ interpretation c (((positive : ℤ) - (negative : ℤ) : ℤ) : Scalar c)
+ rw [digits_pack, value_scale, value_one, mul_one, map_intCast]
+ have h (n : ℕ) : ZMod.finEquiv p (Fin.ofNat p n) = (n : ZMod p) := by
+ rw [← cast_val_eq_finEquiv, Fin.val_ofNat, ZMod.natCast_mod]
+ simp only [cast_val_eq_finEquiv, map_sub, h, map_natCast, Int.cast_sub, Int.cast_natCast]
+
+end Scalar
+
+end RankQuery.Stack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackStages.lean b/lean/OAI/Computability/VPVNP/RankQueryStackStages.lean
new file mode 100644
index 0000000000..5f408e4c63
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackStages.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.RankQueryStackAlias
+import OAI.Computability.VPVNP.RankQueryStackCodec
+
+/-!
+# Installed Schur descriptor and child routines
+
+The two child routines put a complete typed query in six auxiliary output
+registers. They read the loop index from the live continuation frame. The
+descriptor routine leaves a zero dummy index in the auxiliary bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.EngineAlias
+
+open BurstRAM RAMTape Dispatch Engine
+
+variable {n U Z w p : ℕ} {K : Type}
+
+theorem field_query (tag count acc left : List Bool) (q : SchurKey n U Z) (j : Fin 6) :
+ fields w tag q count acc left ⟨j.val+1,by omega⟩ = UniversalCountStack.digits w (q.words j) := by
+ fin_cases j <;> rfl
+
+theorem inputs_query (q : SchurKey n U Z) (k : ℕ) (j : Fin 6) :
+ inputs q k ⟨j.val,by omega⟩ = q.words j := by fin_cases j <;> rfl
+
+theorem live_fields (q : SchurKey n U Z) (k : ℕ) (tag count acc left : List Bool) (flag : Bool)
+ (hcount : flag = true → count = UniversalCountStack.digits w k) :
+ LiveInput w flag (fields w tag q count acc left) (inputs q k) := by
+ intro i j hi ix he
+ have hx : i.val < 6 ∨ flag = true ∧ i.val = 6 := by
+ by_contra hh
+ simp [liveSlot, hh] at hi
+ have hj : j.val = i.val+1 := by
+ simp only [liveSlot, dite_eq_left hx] at hi
+ exact (congrArg (fun a : Option (Fin 10) => (a.map Fin.val).getD 0) hi).symm
+ rcases hx with hl | ⟨hf,hi⟩
+ · let s : Fin 6 := ⟨i.val,hl⟩
+ have ej : j = ⟨s.val+1,by have := s.isLt; omega⟩ := Fin.ext hj
+ have eix : ix = ⟨s.val,by have := s.isLt; omega⟩ := Fin.ext he
+ rw [ej,field_query tag count acc left q s,eix,inputs_query]
+ · have ej : j = 7 := Fin.ext (by omega)
+ have eix : ix = 6 := Fin.ext (by omega)
+ rw [ej,eix]
+ exact hcount hf
+
+/-- The dispatch bank is ready and its six output registers encode the child query `q`. -/
+def Pending (bank : Small ↪ K) (w : ℕ) (q : SchurKey n U Z) (aux : Stacks K) : Prop :=
+ Ready bank w n aux ∧ ∀ i, aux (bank (.reg (Code.outReg capacity i))) = UniversalCountStack.digits w (q.words i)
+
+/-- Compute the selected left or right child query using the loop index in the live frame. -/
+def stageChild (bank : Small ↪ K) (right : Bool) : FiniteRoutine (Engine.Port K) :=
+ routine bank true (if right then .right else .left)
+
+theorem stageChild_runs [DecidableEq K] {F : Type*} [CommRing F] (bank : Small ↪ K) (right : Bool)
+ (entry : Entry n F) (q : SchurKey n U Z) (k : ℕ)
+ (hvalid : ∃ t, (SchurKey.program entry).describe q = .inr t ∧ k < t)
+ (tag acc left : List Bool) (saved : Data) (signal result : List Bool) (aux : Stacks K)
+ (hready : Ready bank w n aux) (he : ∀ i, inputs q k i < 2^p)
+ (hp : p ≤ w) (hw : (p+1)*widthFactor ≤ w) :
+ let live := fields w tag q (UniversalCountStack.digits w k) acc left
+ let prog := SchurKey.program entry
+ let a := if right then Operation.right else Operation.left
+ ∃ s ≤ a.clock w, ∃ out, Pending bank w (if right then prog.right q k else prog.left q k) out ∧
+ (stageChild bank right).Runs s (store live saved signal result aux) (store live saved signal result out) ∧
+ ∀ j, (∀ i, bank i ≠ j) → out j = aux j := by
+ let a := if right then Operation.right else Operation.left
+ have ha : a.tree = child right := by cases right <;> rfl
+ obtain ⟨s,hs,out,hr,hrun,hout,hother⟩ := run bank true a (inputs q k) _ saved signal result aux hready
+ (live_fields q k tag _ acc left true (fun _ => rfl)) (by intro h; contradiction) rfl he hp hw
+ refine ⟨s,hs,out,⟨hr,?_⟩,hrun,hother⟩
+ obtain ⟨t,ht,hk⟩ := hvalid
+ change (q.node entry).describe = .inr t at ht
+ cases h : q.node entry with
+ | leaf => simp [h,Node.describe] at ht
+ | branch T f =>
+ have hT : T = t := by simpa [h,Node.describe] using ht
+ subst t
+ have eq := child_eq entry q h (⟨k,hk⟩ : Fin T) right
+ rw [ha] at hout
+ intro i
+ rw [hout,eq]
+ cases right <;> simp only [Bool.false_eq_true, ite_false, ite_true, SchurKey.program, Node.program,
+ h, Node.children, dite_eq_left hk]
+
+/-- Compute the current query's descriptor with a zero dummy loop index. -/
+def stageDescribe (bank : Small ↪ K) : FiniteRoutine (Engine.Port K) := routine bank false .describe
+
+theorem stageDescribe_runs [DecidableEq K] (bank : Small ↪ K) (q : SchurKey n U Z)
+ (saved : Data) (signal result : List Bool) (aux : Stacks K) (hready : Ready bank w n aux)
+ (he : ∀ i, inputs q 0 i < 2^p) (hp : p ≤ w) (hw : (p+1)*widthFactor ≤ w) :
+ let live := fields w [] q [] [] []
+ ∃ s ≤ Operation.describe.clock w, ∃ out, Ready bank w n out ∧
+ (stageDescribe bank).Runs s (store live saved signal result aux) (store live saved signal result out) ∧
+ (∀ i, out (bank (.reg (Code.outReg capacity i))) =
+ UniversalCountStack.digits w (Dispatch.describe.eval (inputs q 0) i)) ∧
+ ∀ j, (∀ i, bank i ≠ j) → out j = aux j :=
+ run bank false .describe _ _ saved signal result aux hready
+ (live_fields q 0 [] [] [] [] false (by intro h; contradiction)) (fun _ => rfl) rfl he hp hw
+
+/-- A single linear bit bound covers every query register and every loop
+counter used by either child program. -/
+theorem inputs_bounded (s : ℕ) (hn : n ≤ 2^s) (hu : U ≤ 2^s) (hz : Z ≤ 2^s)
+ (q : SchurKey n U Z) (k : ℕ) (hk : k ≤ SchurKey.arityBound n U Z) :
+ ∀ i, inputs q k i < 2^(2*s+6) := by
+ have hc := SchurKey.arityBound_le_exp n U Z s hn hu hz
+ have hA : 1 ≤ 2^s := Nat.one_le_pow _ _ (by decide)
+ have hs : 2^s ≤ 2^(2*s+4) := Nat.pow_le_pow_right (by decide) (by omega)
+ have hbig : 2^(2*s+6) = 2^(2*s+4)*4 := by
+ rw [show 2*s+6 = (2*s+4)+2 by omega, pow_add]; rfl
+ have hfield (j : Fin 6) : q.words j < 2^(2*s+6) := by
+ have hq := q.words_le j
+ rw [hbig]
+ have hbase : 2^s*16 ≤ 2^(2*s+4) := by
+ rw [pow_add]
+ exact Nat.mul_le_mul_right _ (Nat.pow_le_pow_right (by decide) (by omega))
+ omega
+ intro i
+ fin_cases i <;> first | exact hfield _ | change k < _; rw [hbig]; omega | change n < _; rw [hbig]; omega
+
+end RankQuery.Stack.EngineAlias
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryStackWords.lean b/lean/OAI/Computability/VPVNP/RankQueryStackWords.lean
new file mode 100644
index 0000000000..a3c307122f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryStackWords.lean
@@ -0,0 +1,34 @@
+import OAI.Computability.VPVNP.RankQueryStackSchur
+import Mathlib.Data.Fin.VecNotation
+
+/-!
+# Numeric query registers for the Schur coefficient machine
+
+The first register selects a query tag. The other five hold indices and degrees.
+Power and factor convolution queries share the same row, column, exponent and
+degree positions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.SchurKey
+
+variable {n U Z : ℕ}
+
+/-- Six numeric fields of the current scalar query, including its tag. -/
+def words : K n U Z → Fin 6 → ℕ
+ | .product d b u z => ![0, d.val, b.start, b.count, u.val, z.val]
+ | .factor a u z => ![1, a.val, 0, 0, u.val, z.val]
+ | .outer a h i j z => ![2, a.val, i.val, j.val, h.val, z.val]
+ | .inner a h i j z => ![3, a.val, i.val, j.val, h.val, z.val]
+ | .power a q => ![4, a.val, q.row.val, q.col.val, q.exponent.val, q.degree.val]
+ | .scalar neg i j z => ![5, i.val, j.val, neg.toNat, 0, z.val]
+ | .one => ![6, 0, 0, 0, 0, 0]
+
+end RankQuery.Stack.SchurKey
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryTagRouter.lean b/lean/OAI/Computability/VPVNP/RankQueryTagRouter.lean
new file mode 100644
index 0000000000..ab16bb7b7d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryTagRouter.lean
@@ -0,0 +1,75 @@
+import OAI.Computability.VPVNP.RankQueryStackEngineSpec
+import OAI.Computability.VPVNP.RAMTapeUnaryWordValue
+
+/-! # Fixed finite control for the low bits of a descriptor tag
+
+The code pops a fixed number of little-endian bits, restores them in the
+opposite order, and enters the selected subroutine with its original bank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.TagRouter
+
+open RAMTape BurstRAM TapeWord
+
+variable {K : Type}
+
+/-- Read `n` low-order bits from a tag, restore them to the stack, and invoke the continuation
+indexed by their little-endian value. -/
+def select (k : K) : ℕ → (ℕ → FiniteRoutine K) → FiniteRoutine K
+ | 0, next => next 0
+ | n+1, next =>
+ let branch (b : Bool) := select k n (fun i =>
+ (FiniteRoutine.ofRoutine (Routine.push k b)).followedBy (next (b.toNat + 2*i)))
+ .ofRoutine (Routine.popCase k (Routine.halt false) (branch false).body (branch true).body)
+
+variable [DecidableEq K]
+
+theorem select_runs (k : K) (next : ℕ → FiniteRoutine K) (bits tail : List Bool)
+ (s out : Stacks K) (hs : s k = bits ++ tail) {t : ℕ}
+ (hr : (next (value bits)).Runs t s out) :
+ (select k bits.length next).Runs (2*bits.length+t) s out := by
+ induction bits generalizing next s t with
+ | nil => simpa only [List.length_nil, select, Nat.mul_zero, Nat.zero_add, value] using hr
+ | cons b bs ih =>
+ let cut := Function.update s k (bs ++ tail)
+ let arm (i : ℕ) := (FiniteRoutine.ofRoutine (Routine.push k b)).followedBy (next (b.toNat+2*i))
+ have hrestore : Function.update cut k (b :: cut k) = s := by
+ simp only [cut, Function.update_self, Function.update_idem]
+ change s k = b :: (bs ++ tail) at hs
+ rw [← hs, Function.update_eq_self]
+ have push := Routine.runs_push k b cut
+ rw [hrestore] at push
+ have armrun : (arm (value bs)).Runs (1+t) cut out := push.followedBy hr
+ have recur := ih arm cut (Function.update_self ..) armrun
+ rw [List.length_cons, show 2*(bs.length+1)+t = 2*bs.length+(1+t)+1 by omega]
+ cases b with
+ | false => exact Routine.runs_popCase_false _ _ _ _ hs recur
+ | true => exact Routine.runs_popCase_true _ _ _ _ hs recur
+
+/-- A tag known to fit in the tested bits is selected exactly. -/
+theorem digits_runs (k : K) (next : ℕ → FiniteRoutine K) {w d tag t : ℕ}
+ (hd : d ≤ w) (ht : tag < 2^d) (s out : Stacks K) (hs : s k = UniversalCountStack.digits w tag)
+ (hr : (next tag).Runs t s out) : (select k d next).Runs (2*d+t) s out := by
+ let bits := UniversalCountStack.digits d tag
+ let tail := List.replicate (w-d) false
+ have hb : value bits = tag := by rw [UniversalCountStack.value_digits, Nat.mod_eq_of_lt ht]
+ have htw : tag < 2^w := ht.trans_le (Nat.pow_le_pow_right (by decide) hd)
+ have htail : value tail = 0 := by
+ rw [show tail = wordBits (0 : Word (w-d)) from UnaryWord.zeros_wordBits _, value_wordBits]; rfl
+ have he : UniversalCountStack.digits w tag = bits ++ tail := by
+ apply eq_of_length_value
+ · simp only [bits,tail,UniversalCountStack.length_digits,List.length_append,List.length_replicate]; omega
+ · rw [UniversalCountStack.value_digits, Nat.mod_eq_of_lt htw, value_append, hb, htail, mul_zero, add_zero]
+ rw [he] at hs
+ have h := select_runs k next bits tail s out hs (hb ▸ hr)
+ simpa only [bits,UniversalCountStack.length_digits] using h
+
+end RankQuery.Stack.TagRouter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryTagSpace.lean b/lean/OAI/Computability/VPVNP/RankQueryTagSpace.lean
new file mode 100644
index 0000000000..d89b1d264a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryTagSpace.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.RankQueryTagRouter
+import OAI.Computability.VPVNP.RankQueryGramReadSpace
+
+/-! # Tag dispatch reuses the selected branch's live storage -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.TagRouter
+
+open RAMTape BurstRAM TapeWord UniversalCountStack
+
+variable {K : Type} [DecidableEq K]
+
+private theorem pop_bounded (k : K) (low high : FiniteRoutine K) (b : Bool) (tail : List Bool)
+ {cap t : ℕ} {s out : Stacks K} (start : ∀ a, (s a).length ≤ cap) (hs : s k = b :: tail)
+ (run : (if b then high else low).BoundedRun cap t (Function.update s k tail) out) :
+ (FiniteRoutine.ofRoutine (Routine.popCase k (Routine.halt false) low.body high.body)).BoundedRun cap (t+1) s out := by
+ let r := Routine.popCase k (Routine.halt false) low.body high.body
+ cases b with
+ | false =>
+ change low.BoundedRun cap t (Function.update s k tail) out at run
+ have h := run.linkRoutine r (Sum.inr ∘ Sum.inr ∘ Sum.inl) none (fun _ => rfl)
+ apply SpaceRun.cons start _ h
+ change StackStep r.standalone (some r.entry) s (some (.inr (.inr (.inl low.body.entry)))) (Function.update s k tail)
+ simpa only [hs,List.head?_cons,List.tail_cons] using
+ (StackStep.pop (code := r.standalone) (s := s) (q := some r.entry) (show r.standalone (some r.entry) = .pop k _ from rfl))
+ | true =>
+ change high.BoundedRun cap t (Function.update s k tail) out at run
+ have h := run.linkRoutine r (Sum.inr ∘ Sum.inr ∘ Sum.inr) none (fun _ => rfl)
+ apply SpaceRun.cons start _ h
+ change StackStep r.standalone (some r.entry) s (some (.inr (.inr (.inr high.body.entry)))) (Function.update s k tail)
+ simpa only [hs,List.head?_cons,List.tail_cons] using
+ (StackStep.pop (code := r.standalone) (s := s) (q := some r.entry) (show r.standalone (some r.entry) = .pop k _ from rfl))
+
+theorem select_bounded (k : K) (next : ℕ → FiniteRoutine K) (bits tail : List Bool)
+ {cap t : ℕ} (s out : Stacks K) (hs : s k = bits ++ tail) (hr : (next (value bits)).BoundedRun cap t s out) :
+ (select k bits.length next).BoundedRun cap (2*bits.length+t) s out := by
+ induction bits generalizing next s t with
+ | nil => simpa only [List.length_nil,select,Nat.mul_zero,Nat.zero_add,value] using hr
+ | cons b bs ih =>
+ let cut := Function.update s k (bs ++ tail)
+ let arm (i : ℕ) := (FiniteRoutine.ofRoutine (Routine.push k b)).followedBy (next (b.toNat+2*i))
+ change s k = b :: (bs ++ tail) at hs
+ have restore : Function.update cut k (b :: cut k) = s := by
+ simp only [cut,Function.update_self,Function.update_idem]; rw [← hs,Function.update_eq_self]
+ have start := hr.initial_cap
+ have hcut (i : K) : (cut i).length ≤ cap := by
+ by_cases hi : i = k
+ · subst i; have hk := start k; rw [hs,List.length_cons] at hk
+ rw [show cut k = _ from Function.update_self ..]; omega
+ · simpa [cut,hi] using start i
+ have push : (FiniteRoutine.ofRoutine (Routine.push k b)).BoundedRun cap 1 cut s := by
+ rw [← restore]
+ exact .cons hcut (.push rfl) (.nil _ _ (restore ▸ start))
+ have armrun : (arm (value bs)).BoundedRun cap (1+t) cut out := push.followedBy hr
+ have recur := ih arm cut (Function.update_self ..) armrun
+ rw [List.length_cons,show 2*(bs.length+1)+t = 2*bs.length+(1+t)+1 by omega]
+ cases b with
+ | false => exact pop_bounded _ _ _ false _ start hs recur
+ | true => exact pop_bounded _ _ _ true _ start hs recur
+
+theorem digits_bounded (k : K) (next : ℕ → FiniteRoutine K) {w d tag cap t : ℕ}
+ (hd : d ≤ w) (ht : tag < 2^d) (s out : Stacks K) (hs : s k = UniversalCountStack.digits w tag)
+ (hr : (next tag).BoundedRun cap t s out) : (select k d next).BoundedRun cap (2*d+t) s out := by
+ let bits := UniversalCountStack.digits d tag
+ let tail := List.replicate (w-d) false
+ have hb : value bits = tag := by rw [UniversalCountStack.value_digits, Nat.mod_eq_of_lt ht]
+ have htw : tag < 2^w := ht.trans_le (Nat.pow_le_pow_right (by decide) hd)
+ have htail : value tail = 0 := by
+ rw [show tail = wordBits (0 : Word (w-d)) from UnaryWord.zeros_wordBits _, value_wordBits]; rfl
+ have he : UniversalCountStack.digits w tag = bits ++ tail := by
+ apply eq_of_length_value
+ · simp only [bits,tail,UniversalCountStack.length_digits,List.length_append,List.length_replicate]; omega
+ · rw [UniversalCountStack.value_digits,Nat.mod_eq_of_lt htw,value_append,hb,htail,mul_zero,add_zero]
+ rw [he] at hs
+ have h := select_bounded k next bits tail s out hs (hb ▸ hr)
+ simpa only [bits,UniversalCountStack.length_digits] using h
+
+end RankQuery.Stack.TagRouter
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryTimeBounds.lean b/lean/OAI/Computability/VPVNP/RankQueryTimeBounds.lean
new file mode 100644
index 0000000000..15486c4656
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryTimeBounds.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.RankQueryExecution
+
+/-!
+# A uniform singly exponential clock for the physical rank scan
+
+The bidegree rectangle has at most six times the cube of the common input
+bound. Within each cell the logarithmic Schur recursion gives a singly
+exponential number of steps. Loading the root, checking the resulting scalar,
+and moving the cursor add polynomial overhead in the word widths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Cursor
+
+/-- One bound on the six physical size parameters suffices for the complete
+rank query over a rectangular matrix, including every index update. -/
+theorem rankTime_le_exp (n m B w v e s : ℕ) (hn : n ≤ 2^s) (hm : m ≤ 2^s) (hB : B ≤ 2^s)
+ (hw : w ≤ 2^s) (hv : v ≤ 2^s) (he : e ≤ 2^s) :
+ rankTime n m B w v e ≤ 2^((4*s+10)*(4*s+7) + 5*s + 20) := by
+ let A := 2^s
+ let Z := (n+m)*n
+ let H := 2^((4*s+10)*(4*s+7))
+ have hA : 1 ≤ A := Nat.two_pow_pos _
+ have hH : 1 ≤ H := Nat.two_pow_pos _
+ have hA₂ : A ≤ A^2 := by simpa [pow_two] using Nat.mul_le_mul_left A hA
+ change n ≤ A at hn
+ change m ≤ A at hm
+ change B ≤ A at hB
+ change w ≤ A at hw
+ change v ≤ A at hv
+ change e ≤ A at he
+ have hz : Z ≤ 2*A^2 := calc
+ (n+m)*n ≤ (2*A)*A := Nat.mul_le_mul (by omega) hn
+ _ = _ := by ring
+ have hsize : 2^(2*s+1) = 2*A^2 := by dsimp [A]; rw [Nat.mul_comm 2 s, pow_succ, pow_mul]; ring
+ have hrec := rootQueryClock_le n n Z B w v e (2*s+1) (by rw [hsize]; omega)
+ (by rw [hsize]; omega) (by rwa [hsize])
+ rw [show 2*(2*s+1)+8 = 4*s+10 by omega, show 2*(2*s+1)+5 = 4*s+7 by omega] at hrec
+ change rootQueryClock n n Z B w v e ≤ loadClock w + (H*Engine.stepBudget B w v e+1) at hrec
+ have hev : e*v ≤ A^2 := by simpa only [pow_two] using Nat.mul_le_mul he hv
+ have hmax : max 1 (max w (e*v)) ≤ A^2 := by omega
+ have hstep : Engine.stepBudget B w v e ≤ 224*A^2 := by unfold Engine.stepBudget; omega
+ have hload : loadClock w ≤ 43*A^2 := by unfold loadClock; omega
+ have hsq : (w+1)^2 ≤ 4*A^2 := calc
+ _ ≤ (2*A)^2 := Nat.pow_le_pow_left (by omega) 2
+ _ = _ := by ring
+ have hcheck : checkClock w v e ≤ 29242*A^2 := by
+ unfold checkClock
+ rw [Registers.clock_eq]
+ omega
+ have hsmall : A^2 ≤ H*A^2 := by simpa using Nat.mul_le_mul_right (A^2) hH
+ have hbig := Nat.mul_le_mul_left H hstep
+ rw [show H*(224*A^2) = 224*(H*A^2) by ring] at hbig
+ have hcell : rootQueryClock n n Z B w v e + checkClock w v e + 1 ≤ 65536*(H*A^2) := by omega
+ have hrect : (n+1)*(Z+1) ≤ 6*A^3 := calc
+ _ ≤ (2*A)*(3*A^2) := Nat.mul_le_mul (by omega) (by omega)
+ _ = _ := by ring
+ have hproduct := Nat.mul_le_mul hrect hcell
+ rw [show 6*A^3*(65536*(H*A^2)) = 393216*(H*A^5) by ring] at hproduct
+ have hpos : 0 < H*A^5 := Nat.mul_pos hH (Nat.pow_pos hA)
+ change (n+1)*(Z+1)*(rootQueryClock n n Z B w v e+checkClock w v e+1)+2 ≤ _
+ rw [show 2^((4*s+10)*(4*s+7)+5*s+20) = 1048576*(H*A^5) by
+ dsimp only [A,H]; rw [Nat.mul_comm 5 s, pow_add, pow_add, pow_mul]; ring]
+ omega
+
+end RankQuery.Stack.Cursor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RankQueryUniformResources.lean b/lean/OAI/Computability/VPVNP/RankQueryUniformResources.lean
new file mode 100644
index 0000000000..f59cbf663c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RankQueryUniformResources.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.RankQueryShapeResources
+import OAI.Computability.VPVNP.RankQueryNestedResources
+import OAI.Computability.VPVNP.MacaulayReaderWidth
+
+/-!
+# Uniform coordinate costs before the field and slice are chosen
+
+Rows, columns, rank, extension degree and limb width can depend on the prime
+and affine slice. At each input length these five natural numbers lie in a
+finite box fixed by the reader plan. Maximizing the clock and stack height
+separately preserves their respective bounds. This also handles the ordinary
+determinant's clock without a monotonicity assumption about its recursion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery.Stack.Coordinate.ConcreteResources
+
+open PolynomiallyBounded Cost RadicalCertificate.MonomialIndex
+
+/-- Separate maxima of the clock and peak for all possible parameters at
+one length. Only the estimates use the maxima. The machine runs the query
+at the supplied parameters. -/
+def maximum {I : Type*} [Fintype I] (cost : I → Budget) : Budget :=
+ ⟨Finset.univ.sup (fun a => (cost a).time), Finset.univ.sup (fun a => (cost a).space)⟩
+
+theorem le_maximum {I : Type*} [Fintype I] (cost : I → Budget) (a : I) :
+ (cost a).time ≤ (maximum cost).time ∧ (cost a).space ≤ (maximum cost).space :=
+ ⟨Finset.le_sup (f := fun x => (cost x).time) (Finset.mem_univ a),
+ Finset.le_sup (f := fun x => (cost x).space) (Finset.mem_univ a)⟩
+
+theorem maximum_feasible {I : ℕ → Type*} [∀ n, Fintype (I n)] [∀ n, Nonempty (I n)]
+ (cost : (n : ℕ) → I n → Budget) (h : ∀ a : (n : ℕ) → I n, Feasible (fun n => cost n (a n))) :
+ Feasible (fun n => maximum (cost n)) := by
+ classical
+ have pick (f : (n : ℕ) → I n → ℕ) : ∃ a : (n : ℕ) → I n, ∀ n, Finset.univ.sup (f n) = f n (a n) := by
+ have chooseAt (n : ℕ) := Finset.exists_mem_eq_sup Finset.univ Finset.univ_nonempty (f n)
+ choose a _ eq using chooseAt
+ exact ⟨a,eq⟩
+ obtain ⟨time,ht⟩ := pick fun n a => (cost n a).time
+ obtain ⟨space,hs⟩ := pick fun n a => (cost n a).space
+ exact ⟨(h time).time.of_le (fun n => (congrArg (Nat.clog 2) (ht n)).le),
+ (h space).space.of_le (fun n => (hs n).le)⟩
+
+/-- The natural parameters still undetermined after fixing the input
+length. The first three coordinates are the two dimensions and minor order. -/
+abbrev Shapes (limit degree limb : ℕ) :=
+ (Fin 3 → Fin (limit+1)) × Fin (degree+1) × Fin (limb+1)
+
+/-- Time and stack-height budget for a mounted Cramer coordinate query, including minor
+selection, preparation, and the caller's peak stack height. -/
+def mountedBudget (H K : Type) [Fintype H] [Fintype K] (rows cols r d w v e B A S E : ℕ)
+ (prep : Budget) : Budget :=
+ let minor := minorBudget K rows cols d w v e B A S E
+ let V := SelectedMinor.space K d w v e A S
+ let pair := pairBudget H r w v e V minor prep
+ ⟨pair.time, max pair.space (Reader.callerPeak w e v)⟩
+
+/-- The cap includes every ready denominator and numerator bank, as in
+`SelectedMinor.den_ready_length` and `SelectedMinor.num_ready_length`. -/
+theorem mounted_feasible_of_shape (H K : Type) [Fintype H] [Fintype K]
+ {rows cols r d w v e B A S E : ℕ → ℕ} {prep : ℕ → Budget}
+ (hr : LB rows) (hc : LB cols) (ho : LB r) (hd : PB d) (hw : PB w) (hv : PB v) (he : PB e)
+ (hB : LB B) (hA : PB A) (hS : PB S) (hE : LB E) (hp : Feasible prep) :
+ Feasible (fun n => mountedBudget H K (rows n) (cols n) (r n) (d n) (w n) (v n) (e n)
+ (B n) (A n) (S n) (E n) (prep n)) := by
+ have hm := minor_feasible K hr hc hd hw hv he hA hS hB hE
+ have hs := (selected_feasible K hr hc hd hw hv he hA hS hB hE).space
+ exact mounted_feasible (pair_feasible H ho hw hv he hs hm hp) hw hv he
+
+/-- Separate worst-case time and space budgets over the bounded matrix dimensions, minor order,
+extension degree, and limb width. -/
+def uniformBudget (H K : Type) [Fintype H] [Fintype K] (limit d w degree limb B A S E : ℕ) (prep : Budget) :=
+ maximum (fun x : Shapes limit degree limb => mountedBudget H K (x.1 0) (x.1 1) (x.1 2)
+ d w x.2.2 x.2.1 B A S E prep)
+
+theorem uniformBudget_covers (H K : Type) [Fintype H] [Fintype K]
+ {rows cols r e v limit degree limb : ℕ} (hr : rows ≤ limit) (hc : cols ≤ limit) (ho : r ≤ limit)
+ (he : e ≤ degree) (hv : v ≤ limb) (d w B A S E : ℕ) (prep : Budget) :
+ let cost := mountedBudget H K rows cols r d w v e B A S E prep
+ let cap := uniformBudget H K limit d w degree limb B A S E prep
+ cost.time ≤ cap.time ∧ cost.space ≤ cap.space := by
+ let shape : Shapes limit degree limb :=
+ ⟨![⟨rows,Nat.lt_succ_of_le hr⟩,⟨cols,Nat.lt_succ_of_le hc⟩,⟨r,Nat.lt_succ_of_le ho⟩],
+ ⟨e,Nat.lt_succ_of_le he⟩,⟨v,Nat.lt_succ_of_le hv⟩⟩
+ exact le_maximum (fun x : Shapes limit degree limb => mountedBudget H K (x.1 0) (x.1 1) (x.1 2)
+ d w x.2.2 x.2.1 B A S E prep) shape
+
+theorem uniform_feasible (H K : Type) [Fintype H] [Fintype K]
+ {limit d w degree limb B A S E : ℕ → ℕ} {prep : ℕ → Budget}
+ (hl : LB limit) (hd : PB d) (hw : PB w) (he : PB degree) (hv : PB limb)
+ (hB : LB B) (hA : PB A) (hS : PB S) (hE : LB E) (hp : Feasible prep) :
+ Feasible (fun n => uniformBudget H K (limit n) (d n) (w n) (degree n) (limb n)
+ (B n) (A n) (S n) (E n) (prep n)) := by
+ apply maximum_feasible
+ intro shape
+ have dim (j : Fin 3) : LB (fun n => (shape n).1 j) :=
+ hl.of_le fun n => Nat.clog_mono_right _ (Nat.lt_succ_iff.mp ((shape n).1 j).isLt)
+ exact mounted_feasible_of_shape H K (dim 0) (dim 1) (dim 2) hd hw
+ (hv.of_le fun n => Nat.lt_succ_iff.mp (shape n).2.2.isLt)
+ (he.of_le fun n => Nat.lt_succ_iff.mp (shape n).2.1.isLt) hB hA hS hE hp
+
+/-- The full rectangular and graded address kernel both fit one
+prime-independent word width. -/
+def planDepth (P : ReaderPlan) := shapeBits P.addressLimit P.addressLimit
+
+/-- Word width sufficient for both the Gram rank cursor and the plan's matrix-entry reader. -/
+def planWidth (P : ReaderPlan) := max (Cursor.gramWidth (planDepth P)) P.wordWidth
+
+theorem planSizes {P : ℕ → ReaderPlan} (hw : PB (fun n => (P n).wordWidth)) :
+ LB (fun n => (P n).addressLimit) ∧ PB (fun n => planDepth (P n)) ∧ PB (fun n => planWidth (P n)) := by
+ have lim : LB (fun n => (P n).addressLimit) := hw.of_le fun n => ((P n).dispatchWidth).2.1
+ have depth := shapeBits_poly lim lim
+ exact ⟨lim,depth,poly_max (gramWidth_poly depth) hw⟩
+
+theorem planWidth_covers (P : ReaderPlan) :
+ Cursor.gramWidth (planDepth P) ≤ planWidth P ∧ P.wordWidth ≤ planWidth P :=
+ ⟨le_max_left ..,le_max_right ..⟩
+
+theorem plan_dimensions {P : ReaderPlan} {K : Type*} {s : QueryData P.arity (P.equations+P.pins) K}
+ (h : P.Covers s) :
+ (P.equations+P.pins)*size P.arity s.multiplierDegree + size P.arity s.pointBound ≤ P.addressLimit ∧
+ size P.arity s.columnDegree ≤ P.addressLimit := by
+ have dense {D L : ℕ} (hle : D ≤ L) : size P.arity D ≤ rawSize P.arity L := by
+ rw [size_eq_card]
+ exact (RadicalCertificate.card_boundedMonomial_le ..).trans ((Nat.le_mul_of_pos_left _ (Nat.succ_pos _)).trans (ReaderPlan.raw_mono _ hle))
+ have row := Nat.add_le_add (Nat.mul_le_mul_left (P.equations+P.pins) (dense h.degrees.2.1)) (dense h.points_le)
+ have col := dense h.degrees.2.2
+ unfold ReaderPlan.addressLimit
+ omega
+
+/-- The matrix-order and both degree-scan inequalities required by the
+two orientations and by the ordinary determinant, at the common plan width. -/
+theorem plan_query_shapes {P : ReaderPlan} {F : Type} [Field F] [DecidableEq F]
+ {s : QueryData P.arity (P.equations+P.pins) F} (h : P.Covers s) :
+ let n := (P.equations+P.pins)*size P.arity s.multiplierDegree+size P.arity s.pointBound
+ let m := size P.arity s.columnDegree
+ let r := rankQuery (appendRows s.equations s.monomials)
+ let d := planDepth P
+ n ≤ P.addressLimit ∧ m ≤ P.addressLimit ∧ r ≤ P.addressLimit ∧
+ n+n+(n+m)*n+m+8 < 2^d ∧ m+m+(m+n)*m+n+8 < 2^d ∧ r+r+0+r+8 < 2^d ∧ r ≤ 2^d := by
+ intro n m r d
+ obtain ⟨hr,hc⟩ := plan_dimensions h
+ have rle : r ≤ n := by
+ dsimp only [r]
+ rw [rankQuery_eq]
+ simpa only [Fintype.card_fin] using (appendRows s.equations s.monomials).rank_le_card_height
+ have inBox {z : ℕ} (hz : z ≤ P.addressLimit) : z ≤ max P.addressLimit P.addressLimit := hz.trans (le_max_left ..)
+ have horder := rle.trans hr
+ exact ⟨hr,hc,horder,shapeBits_rect (inBox hr) (inBox hc),shapeBits_rect (inBox hc) (inBox hr),
+ shapeBits_minor (inBox horder)⟩
+
+end RankQuery.Stack.Coordinate.ConcreteResources
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RealizedTransport.lean b/lean/OAI/Computability/VPVNP/RealizedTransport.lean
new file mode 100644
index 0000000000..07b3ec8e16
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RealizedTransport.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.WireGeodesic
+import Mathlib.Data.Fin.VecNotation
+
+/-!
+# Transport in spaces whose finite configurations are realized
+
+Corollary 2.5 applies the spectral wire transport inequality to the four
+endpoints and the two fractional points in one joint realization. Its
+common positive scale cancels in both the fractional distances and the
+transport bound.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open WireTensor
+
+variable {k : Type*} [Field k]
+
+/-- The six-point wire inequality implies the same inequality in any space
+whose finite configurations are spectral up to scale. -/
+theorem fractionTransport_of_realizable {X : Type*} [PseudoMetricSpace X]
+ (hwire : ∀ (J : Type) [Fintype J] [Nontrivial J] (F : SpectralPoint k J),
+ @FractionTransport J F.wirePseudoMetric)
+ (hX : RealizableConfigurations k X) : FractionTransport X := by
+ intro a b c d x y t ht₀ ht₁ hx hy
+ let p : Fin 6 → X := ![a,b,c,d,x,y]
+ obtain ⟨w⟩ := hX 6 p
+ let D (i j : Fin 6) := w.spectrum.wireDistance (w.label i) (w.label j)
+ have eqD (i j : Fin 6) : dist (p i) (p j) = w.scale * D i j := w.distances _ _
+ have fract {i j z : Fin 6} (h : AtFraction (p i) (p j) t (p z)) :
+ @AtFraction _ w.spectrum.wirePseudoMetric (w.label i) (w.label j) t (w.label z) := by
+ obtain ⟨hl, hr⟩ := h
+ rw [eqD, eqD] at hl hr
+ constructor
+ · exact mul_left_cancel₀ w.scale_pos.ne' (hl.trans (mul_left_comm _ _ _))
+ · exact mul_left_cancel₀ w.scale_pos.ne' (hr.trans (mul_left_comm _ _ _))
+ have bound := hwire w.Parties w.spectrum ht₀ ht₁
+ (fract (i := 0) (j := 1) (z := 4) hx) (fract (i := 2) (j := 3) (z := 5) hy)
+ change D 4 5 ≤ (1-t) * D 0 2 + t * D 1 3 at bound
+ change dist (p 4) (p 5) ≤ (1-t) * dist (p 0) (p 2) + t * dist (p 1) (p 3)
+ rw [eqD, eqD, eqD]
+ calc
+ _ ≤ w.scale * ((1-t) * D 0 2 + t * D 1 3) := mul_le_mul_of_nonneg_left bound w.scale_pos.le
+ _ = _ := by ring
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RefreshHistory.lean b/lean/OAI/Computability/VPVNP/RefreshHistory.lean
new file mode 100644
index 0000000000..86d8182b27
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RefreshHistory.lean
@@ -0,0 +1,136 @@
+import OAI.Computability.VPVNP.StatePassHistory
+import OAI.Computability.VPVNP.DegreeRefreshPass
+
+/-!
+# Local records of a degree refresh
+
+Each physical port keeps exactly one old vertex. Its kernel checks the two
+diagonal segment equalities and evaluates one expander-motif entry. The demand
+arguments read the old half-wires and the two lists of external segments. The
+supply arguments use the two directions of the inner expander slots. The
+remaining slot fields, including the external and padding wires, are recorded
+by the common pass constructor.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.Refresh
+
+open NetworkKernel SpectralGeometry DegreeRefresh MotifConversion
+open scoped Classical
+
+variable {a g a₀ dH : ℕ} {k : Type*} [Field k] {K K' : ℝ}
+variable (X : State a (a + g)) (P : RegularArcGraph (Fin (2 ^ a)) dH) (hdH : 0 < dH)
+ (hconn : (arcSupportGraph P.multiplicity).Connected)
+ (F : RefreshBlock k (expanderSupply P hdH hconn) (2 ^ a₀) K K')
+ (hD : 1 < 2 ^ a) (hd : dH + 1 ≤ 2 ^ a₀)
+variable {R : Type*} [CommRing R] (κ : (parameterData F).Entry → R) (hκ : (parameterData F).IsSolution κ)
+
+/-- Identify old sites with physical ports in the dyadic refresh. -/
+private def placedPort : X.network.Site ≃ (X.Base × Fin (2 ^ a)) × BitWord g :=
+ ((Equiv.refl X.Base).prodCongr (splitBitWord a g).toEquiv).trans (refreshPositions (bitWordFinEquiv a))
+
+/-- The actual outgoing and incoming segment widths at the indicated port. -/
+private def segmentWidth (s : X.Base × BitWord g) (j : Fin (2 ^ a)) (dir : Bool) (l : Fin (2 ^ a)) : ℕ :=
+ let arc := ((s, j), l)
+ groupedWidths (bitWordFinEquiv a) (splitWidths X)
+ (if dir then (oldPortMatching (splitSlots X) (bitWordFinEquiv a)).symm arc else arc)
+
+/-- Local views used by the refresh map. `Fin 3` distinguishes the motif map
+from the two diagonal equality checks, whose scalar degree is zero. -/
+noncomputable def refreshLocalRecords :
+ (dyadicRefreshPass X P hdH hconn F hD hd κ hκ).Records := fun choice v =>
+ let s := (v.1.1, v.2)
+ { Map := Fin 3
+ mapFintype := inferInstance
+ degree j := if j = 0 then repetitions F (blockDemandWidths (splitSlots X)
+ (bitWordFinEquiv a) (splitWidths X) s) else 0
+ Field := (Bool × Fin (2 ^ a)) ⊕ ((Bool × Fin (2 ^ a)) ⊕ (Bool × Fin dH))
+ fieldFintype := inferInstance
+ width := Sum.elim (fun j => segmentWidth X s v.1.2 j.1 j.2) (Sum.elim
+ (fun j => X.halfWidth ((placedPort X).symm v) j.1 j.2)
+ (fun j => (dyadicRefreshNext X P hdH hconn F hD hd choice).halfWidth v j.1
+ (refreshSlots hd (.inr (.inl j.2))))) }
+
+/-- A degree-dependent upper bound on the counts of the local descriptors,
+including the complete demand and supply argument views. -/
+def refreshExtraCount (a dH : ℕ) : ℕ := 4 + 4 * 2 ^ a + 2 * dH
+
+set_option backward.isDefEq.respectTransparency false in
+theorem refreshLocalRecords_count (choice : DyadicRefreshChoice X P hdH hconn F)
+ (v : (X.Base × Fin (2 ^ a)) × BitWord g) :
+ (refreshLocalRecords X P hdH hconn F hD hd κ hκ choice v).count = refreshExtraCount a dH := by
+ simp [refreshLocalRecords, SiteRecords.count, refreshExtraCount, Fintype.card_sum, Fintype.card_prod]
+ ring
+
+/-- An integral constant large enough for both refreshed widths and expander entry degrees. -/
+noncomputable def refreshLengthConstant := max 1 (max (Fintype.card (Tie (2 ^ a)))
+ ⌈max ((2 ^ a : ℕ) : ℝ) (Real.sqrt ((((2 ^ a : ℕ) : ℝ) / (2 ^ a₀ : ℕ)) *
+ (K' * Fintype.card (Tie (2 ^ a)) + max 0 F.energyConstant)))⌉₊)
+
+private theorem refreshNext_width_bound (hK' : 0 ≤ K') (choice : DyadicRefreshChoice X P hdH hconn F)
+ (e : ((X.Base × Fin (2 ^ a)) × Fin (2 ^ a₀)) × BitWord g) :
+ (dyadicRefreshNext X P hdH hconn F hD hd choice).width e ≤
+ refreshLengthConstant P hdH hconn F * (X.maxWireWidth + 1) := by
+ have hh := dyadicRefreshNext_width X P hdH hconn F hD hd hK' choice X.width_le_maxWireWidth e
+ let U := max ((2 ^ a : ℕ) : ℝ) (Real.sqrt ((((2 ^ a : ℕ) : ℝ) / (2 ^ a₀ : ℕ)) *
+ (K' * Fintype.card (Tie (2 ^ a)) + max 0 F.energyConstant)))
+ have hu : U ≤ (refreshLengthConstant P hdH hconn F : ℝ) :=
+ (Nat.le_ceil U).trans (Nat.cast_le.mpr ((le_max_right ..).trans (le_max_right ..)))
+ exact_mod_cast hh.trans (mul_le_mul_of_nonneg_right hu (by positivity))
+
+/-- The placement is a bijection even when it is viewed in the term's own output coordinates. -/
+private theorem refreshPreimage_card (choice : DyadicRefreshChoice X P hdH hconn F)
+ (v : (X.Base × Fin (2 ^ a)) × BitWord g) :
+ Fintype.card (((dyadicRefreshPass X P hdH hconn F hD hd κ hκ).step.term choice).Preimage v) = 1 := by
+ let e := placedPort X
+ let equiv : (((dyadicRefreshPass X P hdH hconn F hD hd κ hκ).step.term choice).Preimage v) ≃ Unit :=
+ { toFun := fun _ => ()
+ invFun := fun _ => ⟨e.symm v, (e.apply_symm_apply v).symm⟩
+ left_inv := fun u => Subtype.ext (by
+ have h : v = e u.val := u.prop
+ exact e.symm_apply_eq.mpr h)
+ right_inv := fun _ => rfl }
+ simpa using Fintype.card_congr equiv
+
+/-- The chosen layout and every local field and monomial-degree descriptor
+satisfy the one-step bound with constants independent of the lanes and old widths. -/
+theorem refreshPass_records_bounded (hK' : 0 ≤ K') :
+ let pass := dyadicRefreshPass X P hdH hconn F hD hd κ hκ
+ let extra := refreshLocalRecords X P hdH hconn F hD hd κ hκ
+ pass.Bounded (pass.slotRecords extra)
+ (max (refreshExtraCount a dH + 1 * (2 * 2 ^ a) + 2 * 2 ^ a₀ + 1)
+ (refreshLengthConstant P hdH hconn F + 1)) := by
+ let E := refreshLengthConstant P hdH hconn F
+ have hE : 1 ≤ E := le_max_left _ _
+ have hW : X.maxWireWidth ≤ E * (X.maxWireWidth + 1) := by nlinarith [Nat.zero_le X.maxWireWidth]
+ apply StatePass.slotRecords_bounded _ _ 1 (refreshExtraCount a dH) E hE
+ · exact fun i v => (refreshPreimage_card X P hdH hconn F hD hd κ hκ i v).le
+ · exact fun i v => (refreshLocalRecords_count X P hdH hconn F hD hd κ hκ i v).le
+ · intro i v
+ apply max_le
+ · apply Finset.sup_le
+ rintro (j | (j | j)) _
+ · exact (X.width_le_maxWireWidth _).trans hW
+ · exact (X.halfWidth_le_max _ _ _).trans hW
+ · exact refreshNext_width_bound X P hdH hconn F hD hd hK' i _
+ · apply Finset.sup_le
+ intro j _
+ change Fin 3 at j
+ change (if j = 0 then repetitions F _ else 0) ≤ _
+ split_ifs
+ · have ht : Fintype.card (Tie (2 ^ a)) ≤ E := (le_max_left ..).trans (le_max_right ..)
+ refine (term_repetitions_le F _ (W := X.maxWireWidth) ?_).trans (Nat.mul_le_mul ht (by omega))
+ intro tie
+ unfold blockDemandWidths internalWidth
+ split_ifs <;> exact X.width_le_maxWireWidth _
+ · exact Nat.zero_le _
+ · exact refreshNext_width_bound X P hdH hconn F hD hd hK'
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RefreshMonomialWitness.lean b/lean/OAI/Computability/VPVNP/RefreshMonomialWitness.lean
new file mode 100644
index 0000000000..1129e1397c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RefreshMonomialWitness.lean
@@ -0,0 +1,54 @@
+import OAI.Computability.VPVNP.DegreeRefreshEntries
+import OAI.Computability.VPVNP.DegreeRefreshPass
+import OAI.Computability.VPVNP.NetworkMonomialIso
+
+/-!
+# Scalar witnesses on the dyadic refresh pass
+
+Splitting the old lane into port and remaining lane coordinates reindexes the
+arguments of the two diagonal ties and the motif matrix entry at each port.
+The accepting entry contributes its list of template labels to the pass.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.Refresh
+
+open NetworkKernel SpectralGeometry DegreeRefresh MotifConversion
+
+variable {a g a₀ dH : ℕ} {k : Type*} [Field k] {K K' : ℝ}
+variable (X : State a (a + g)) (P : RegularArcGraph (Fin (2 ^ a)) dH) (hdH : 0 < dH)
+ (hconn : (arcSupportGraph P.multiplicity).Connected)
+ (F : RefreshBlock k (expanderSupply P hdH hconn) (2 ^ a₀) K K')
+ (hD : 1 < 2 ^ a) (hd : dH + 1 ≤ 2 ^ a₀)
+variable {R : Type*} [CommRing R] (κ : (parameterData F).Entry → R)
+ (hκ : (parameterData F).IsSolution κ)
+
+/-- Each refresh site checks its two diagonal ties and reads the selected
+motif entry on its actual half-wire arguments. -/
+noncomputable def dyadicRefreshKernelWitness :
+ ∀ c v x z, MonomialWitness κ
+ (((dyadicRefreshPass X P hdH hconn F hD hd κ hκ).step.term c).kernel v x z) := by
+ let step := expanderRefreshStep (splitSlots X) (bitWordFinEquiv a) (splitWidths X)
+ P hdH hconn F κ hκ hD hd
+ exact step.reindexInputWitness (relaneIso X.slots (splitBitWord a g) X.width)
+ (fun c ↦ expanderKernelWitness (splitSlots X) (bitWordFinEquiv a) (splitWidths X)
+ P hdH hconn F hD hd c κ hκ)
+
+/-- The exponents contributed at a physical port are bounded by the number
+of internal ties times the largest old wire width. -/
+theorem dyadicRefreshKernelWitness_degree_le (c : DyadicRefreshChoice X P hdH hconn F) (v x z)
+ (b : (dyadicRefreshKernelWitness X P hdH hconn F hD hd κ hκ c v x z).Choice)
+ {W : ℕ} (hw : ∀ e, X.width e ≤ W) :
+ (∑ l, (dyadicRefreshKernelWitness X P hdH hconn F hD hd κ hκ c v x z).exponents b l) ≤
+ Fintype.card (Tie (2 ^ a)) * W :=
+ expanderKernelWitness_exponents (splitSlots X) (bitWordFinEquiv a) (splitWidths X)
+ P hdH hconn F hD hd c κ hκ v _ _ b (fun _ ↦ hw _)
+
+end Compression.Refresh
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RefreshProcedure.lean b/lean/OAI/Computability/VPVNP/RefreshProcedure.lean
new file mode 100644
index 0000000000..497c6e1bed
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RefreshProcedure.lean
@@ -0,0 +1,56 @@
+import OAI.Computability.VPVNP.CompressionProcedure
+import OAI.Computability.VPVNP.CompressionTemplates
+
+/-!
+# Running the fixed refresh template
+
+The refresh at the end of a block consumes the port-index coordinates and
+restores the degree from the last exponent in the chosen schedule. Its
+energy error uses only the fixed refresh template.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.BlockSchedule.Templates
+
+open MotifConversion Refresh DegreeRefresh
+
+variable {k : Type*} [Field k] {S : BlockSchedule k}
+variable (B : S.Templates) {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+
+/-- The refresh coefficient in (7.3) uses only the initial degree, graph
+degree and common Poincaré bound. -/
+noncomputable def refreshProcedure :
+ Procedure R S.portExponent (S.degreeExponent 0) S.portExponent 1
+ (refreshMultiplier S.baseDegree (2 ^ S.expanderExponent) S.poincare) := by
+ let hdH := Nat.two_pow_pos S.expanderExponent
+ let conn := (S.port_bound.connected_and_pos S.port_order).1
+ let hd := S.degree_bounds.2
+ let hk := (B.solution_iff f).mp hf |>.2
+ let g (n : ℕ) (X : State S.portExponent (S.portExponent + n)) :=
+ dyadicRefreshPass X S.graph hdH conn B.refresh S.port_order hd (f ∘ Sum.inr) hk
+ have hgain : 0 ≤ refreshMultiplier S.baseDegree (2 ^ S.expanderExponent) S.poincare := by
+ change 0 ≤ (S.baseDegree : ℝ) + 2 * (S.portComparison + 1)
+ positivity [S.portComparison_pos]
+ refine Procedure.ofPass (κ := 1) one_pos hgain (le_max_left 0 B.refresh.energyConstant)
+ g ?_ ?_
+ · intro n X i
+ rw [one_mul]
+ exact (dyadicRefreshNext_positions X S.graph hdH conn B.refresh S.port_order hd i).symm
+ · intro n X i
+ have h := dyadicRefreshNext_energy X S.graph hdH conn B.refresh S.port_order hd
+ (show 0 ≤ S.portComparison + 1 by linarith [S.portComparison_pos]) i
+ exact h.trans (add_le_add_right (mul_le_mul_of_nonneg_right (le_max_right 0 _)
+ (sq_nonneg (X.positions : ℝ))) _)
+
+/-- The additive bound precedes the assignment of the parameter values. -/
+@[simp] theorem refreshProcedure_error :
+ (B.refreshProcedure f hf).error = max 0 B.refresh.energyConstant := rfl
+
+end Compression.BlockSchedule.Templates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RefreshProcedureRecords.lean b/lean/OAI/Computability/VPVNP/RefreshProcedureRecords.lean
new file mode 100644
index 0000000000..13954418e4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RefreshProcedureRecords.lean
@@ -0,0 +1,52 @@
+import OAI.Computability.VPVNP.RefreshHistory
+import OAI.Computability.VPVNP.RefreshProcedure
+import OAI.Computability.VPVNP.CompressionProcedureHistory
+
+/-!
+# Uniform record bounds for the scheduled expander refresh
+
+The actual refresh in a compression block has one substep. Its local resource
+constant depends only on the chosen degrees, expander and fixed motif template.
+It can therefore be fixed before specializing the parameter values.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.BlockSchedule.Templates
+
+open MotifConversion Refresh DegreeRefresh
+
+variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates)
+
+/-- Uniform count and growth constant for the refresh in this schedule. -/
+noncomputable def refreshRecordConstant : ℕ :=
+ max (refreshExtraCount S.portExponent (2 ^ S.expanderExponent) +
+ 1 * (2 * 2 ^ S.portExponent) + 2 * 2 ^ S.degreeExponent 0 + 1)
+ (refreshLengthConstant S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1
+ B.refresh + 1)
+
+variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+
+/-- All branches of the scheduled refresh retain the actual port records and satisfy
+one bound, independent of the specialization ring, lane count and input widths. -/
+noncomputable def refreshProcedureRecords :
+ (B.refreshProcedure f hf).RecordBounds B.refreshRecordConstant 1 := by
+ let hdH := Nat.two_pow_pos S.expanderExponent
+ let conn := (S.port_bound.connected_and_pos S.port_order).1
+ let hd := S.degree_bounds.2
+ let hk := ((B.solution_iff f).mp hf).2
+ unfold refreshProcedure
+ refine Procedure.RecordBounds.ofPass _ _ _ _ _ _ (fun _ X =>
+ let pass := dyadicRefreshPass X S.graph hdH conn B.refresh S.port_order hd (f ∘ Sum.inr) hk
+ pass.slotRecords (refreshLocalRecords X S.graph hdH conn B.refresh S.port_order hd (f ∘ Sum.inr) hk)) ?_
+ intro g X
+ exact refreshPass_records_bounded X S.graph hdH conn B.refresh S.port_order hd (f ∘ Sum.inr) hk
+ (by linarith [S.portComparison_pos])
+
+end Compression.BlockSchedule.Templates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RefreshProcedureWitness.lean b/lean/OAI/Computability/VPVNP/RefreshProcedureWitness.lean
new file mode 100644
index 0000000000..1e9781ed52
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RefreshProcedureWitness.lean
@@ -0,0 +1,38 @@
+import OAI.Computability.VPVNP.RefreshMonomialWitness
+import OAI.Computability.VPVNP.RefreshProcedure
+import OAI.Computability.VPVNP.CompressionMonomialHistory
+
+/-!
+# Refresh witnesses in the common template alphabet
+
+Every scheduled refresh uses the second group of parameters in the fixed
+equations. Its kernel witnesses record the label multiplicities at each port
+for every choice of branch and half-wire arguments.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.BlockSchedule.Templates
+
+open NetworkKernel Refresh
+
+variable {k : Type*} [Field k] {S : BlockSchedule k}
+variable (B : S.Templates) {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+
+/-- Finite syntactic witnesses for each execution of the scheduled refresh,
+in the same alphabet as the shrinking passes. -/
+noncomputable def refreshProcedureWitnesses : (B.refreshProcedure f hf).MapWitnesses f := by
+ unfold refreshProcedure
+ apply Procedure.MapWitnesses.ofPass
+ intro g X c v x z
+ exact MonomialWitness.right f (dyadicRefreshKernelWitness X S.graph (Nat.two_pow_pos _)
+ (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2
+ (f ∘ Sum.inr) ((B.solution_iff f).mp hf).2 c v x z)
+
+end Compression.BlockSchedule.Templates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RegisterTable.lean b/lean/OAI/Computability/VPVNP/RegisterTable.lean
new file mode 100644
index 0000000000..183bfc4649
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RegisterTable.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.RAMTapeISADispatch
+import OAI.Computability.VPVNP.UniversalCountStackBounds
+
+/-!
+# Fixed register instruction tables on binary stacks
+
+A deterministic register program for a coordinate query can run for
+exponentially many instructions. Its program counter is finite control.
+Ordinary instruction callbacks resume directly at the next program counter,
+so the machine needs no stack of fuel credits. Each instruction restores a
+bank of width-bounded registers before the next instruction starts.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.RegisterTable
+
+open BurstRAM PrivateRAM UniversalCountStack
+
+variable {w v p r k : ℕ}
+
+/-- The next program counter and register contents for a register-only opcode. -/
+def step (i : Instr v p r k) (pub : Fin k → Word w) (persistent : Word w) (reg : Fin r → Word w) :
+ Option (Fin p × (Fin r → Word w)) :=
+ match i with
+ | .constant dst x j => some (j, Function.update reg dst (Fin.ofNat _ x.val))
+ | .publicWord dst a j => some (j, Function.update reg dst (pub a))
+ | .stateWord dst j => some (j, Function.update reg dst persistent)
+ | .copy dst src j => some (j, Function.update reg dst (reg src))
+ | .binary op dst x y j => some (j, Function.update reg dst (op.eval (reg x) (reg y)))
+ | .jumpEq x y a b => some (if reg x = reg y then a else b, reg)
+ | .jumpLt x y a b => some (if reg x < reg y then a else b, reg)
+ | _ => none
+
+/-- Runs between instruction-entry boundaries, including the boundary at which a caller takes over. -/
+inductive Runs (T : Template p r k) (pub : Fin k → Word w) (persistent : Word w) :
+ ℕ → Fin p → (Fin r → Word w) → Fin p → (Fin r → Word w) → Prop
+ | nil (j R) : Runs T pub persistent 0 j R j R
+ | cons {j R j' R' n out A} (hs : step (T.code j) pub persistent R = some (j', R')) :
+ Runs T pub persistent n j' R' out A → Runs T pub persistent (n+1) j R out A
+
+theorem Runs.one {T : Template p r k} {pub : Fin k → Word w} {persistent : Word w}
+ {j R j' R'} (hs : step (T.code j) pub persistent R = some (j',R')) :
+ Runs T pub persistent 1 j R j' R' := .cons hs (.nil ..)
+
+theorem Runs.trans {T : Template p r k} {pub : Fin k → Word w} {persistent : Word w}
+ {a b j R j' R' l A} (h : Runs T pub persistent a j R j' R') (g : Runs T pub persistent b j' R' l A) :
+ Runs T pub persistent (a+b) j R l A := by
+ induction h with
+ | nil => simpa using g
+ | cons hs _ ih => simpa only [Nat.succ_add] using Runs.cons hs (ih g)
+
+/-- Fixed physical binary control. Nonlocal callbacks are exit labels for callers. -/
+def code (T : Template p r k) : StackCode (ISA.Port r k) (ISA.State T) :=
+ fun q => match ISA.resume? T q with
+ | some (.next j) => .goto (ISA.entry T j)
+ | _ => ISA.code T q
+
+/-- Initial bit stacks for the register table, encoding the public words, persistent word, and
+registers with an empty address log. -/
+def bank (pub : Fin k → Word w) (persistent : Word w) (reg : Fin r → Word w) : Stacks (ISA.Port r k) :=
+ ISA.bank pub persistent reg []
+
+theorem bank_length_le (pub : Fin k → Word w) (persistent : Word w) (reg : Fin r → Word w)
+ (a : ISA.Port r k) : (bank pub persistent reg a).length ≤ w := by
+ cases a with
+ | reg | pub | persistent => simp [bank, ISA.bank]
+ | work => simp [bank, ISA.bank]
+ | logPort a => cases a <;> simp [bank, ISA.bank, ISA.logStacks, AddressLog.keys, AddressLog.values]
+
+private theorem dispatch_of_step (i : Instr v p r k) (pub : Fin k → Word w)
+ (pc : Fin p) (persistent : Word w) (reg : Fin r → Word w) {j reg'}
+ (hs : step i pub persistent reg = some (j,reg')) :
+ let c : LogConfig w p r := ⟨pc, persistent, reg, []⟩
+ ISA.exitFor i ((ISA.jumpTest i c).getD false) = .next j ∧
+ ISA.configBank pub (ISA.post i pub c) = bank pub persistent reg' := by
+ cases i <;> simp only [step, Option.some.injEq, Prod.mk.injEq, reduceCtorEq] at hs
+ all_goals first | contradiction | obtain ⟨rfl, rfl⟩ := hs
+ all_goals simp [ISA.exitFor, ISA.jumpTest, ISA.post, ISA.configBank, bank, TapeWord.Comparison.Op.eval]
+
+/-- One register instruction is simulated by the physical machine within a
+quadratic word-length bound. -/
+theorem one_run {T : Template p r k} {pub : Fin k → Word w} {persistent : Word w}
+ {j R j' R'} (hs : step (T.code j) pub persistent R = some (j',R')) :
+ ∃ t ≤ ISA.prepareBound w 0 + 3,
+ StackRuns (code T) t (ISA.entry T j) (bank pub persistent R) (ISA.entry T j') (bank pub persistent R') := by
+ let c : LogConfig w p r := ⟨j,persistent,R,[]⟩
+ obtain ⟨t,ht,hr⟩ := ISA.dispatch_step T pub c
+ obtain ⟨hcb,hbank⟩ := dispatch_of_step (T.code j) pub j persistent R hs
+ have hl := hr.lift id Function.injective_id id (bank pub persistent R) (target := code T)
+ (by intro q hq; simp only [id_eq, code, ISA.resume_none_of_continuing T q hq]; cases ISA.code T q <;> rfl)
+ have install (s : Stacks (ISA.Port r k)) : installStacks id (bank pub persistent R) s = s := by
+ funext a; exact installStacks_at Function.injective_id ..
+ simp only [id_eq, install] at hl
+ change StackRuns (code T) t (ISA.entry T j) (bank pub persistent R)
+ (ISA.callback T (ISA.exitFor (T.code j) ((ISA.jumpTest (T.code j) c).getD false)))
+ (ISA.configBank pub (ISA.post (T.code j) pub c)) at hl
+ rw [hcb, hbank] at hl
+ have hg := StackStep.goto (s := bank pub persistent R') (q := ISA.callback T (.next j'))
+ (show code T _ = .goto (ISA.entry T j') from by simp [code])
+ refine ⟨t+1, ?_, hl.trans (.cons hg (.nil ..))⟩
+ change t ≤ ISA.prepareBound w 0 + 2 at ht
+ omega
+
+/-- End-to-end simulation between arbitrary instruction-entry labels. Each
+stack has polynomial height independently of the number of loop iterations. -/
+theorem run {T : Template p r k} {pub : Fin k → Word w} {persistent : Word w}
+ {n j R j' R'} (h : Runs T pub persistent n j R j' R') :
+ ∃ t ≤ n * (ISA.prepareBound w 0 + 3),
+ SpaceRun (code T) (w + (ISA.prepareBound w 0 + 3)) t
+ (ISA.entry T j) (bank pub persistent R) (ISA.entry T j') (bank pub persistent R') := by
+ induction h with
+ | nil j R => exact ⟨0, by simp, .nil _ _ fun a => (bank_length_le _ _ _ a).trans (Nat.le_add_right ..)⟩
+ | @cons j R j' R' n l A hs _ ih =>
+ obtain ⟨t, ht, hr⟩ := one_run hs
+ obtain ⟨u, hu, htail⟩ := ih
+ have hbounded := spaceRun_of_steps hr fun a => Nat.add_le_add (bank_length_le _ _ _ a) ht
+ refine ⟨t+u, ?_, hbounded.trans htail⟩
+ rw [Nat.succ_mul]
+ omega
+
+end RAMTape.RegisterTable
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RegisterTableRoutine.lean b/lean/OAI/Computability/VPVNP/RegisterTableRoutine.lean
new file mode 100644
index 0000000000..6f47420920
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RegisterTableRoutine.lean
@@ -0,0 +1,82 @@
+import OAI.Computability.VPVNP.RegisterTable
+import OAI.Computability.VPVNP.RoutineSpace
+
+/-! # Calling a register table as a returning bit-stack routine
+
+An `accept` opcode returns normally to the caller after completing the final
+instruction dispatch. The return changes no register or stack, and the bound
+on transient stack height also holds after linking.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.RegisterTable
+
+open BurstRAM PrivateRAM UniversalCountStack
+
+variable {w p r k : ℕ}
+
+private def normal (T : Template p r k) (q : ISA.State T) : Bool :=
+ match ISA.resume? T q with
+ | some .accept => true
+ | _ => false
+
+/-- Run a register table from its entry label as a bit-stack subroutine that returns on its
+accept callback. -/
+def routine (T : Template p r k) : FiniteRoutine (ISA.Port r k) :=
+ FiniteRoutine.ofStackCode (code T) id (ISA.entry T T.entry) (normal T)
+
+private theorem normal_halts (T : Template p r k) (q : ISA.State T) (h : normal T q = true) :
+ (code T q).returns = true := by
+ rcases q with pc | sub | pc | cb <;> try contradiction
+ cases cb <;> first | rfl | contradiction
+
+private theorem accept_run (T : Template p r k) (pc : Fin p) (hpc : T.code pc = .accept)
+ (pub : Fin k → Word w) (persistent : Word w) (reg : Fin r → Word w) :
+ ∃ t ≤ ISA.prepareBound w 0+2,
+ StackRuns (code T) t (ISA.entry T pc) (bank pub persistent reg)
+ (ISA.callback T .accept) (bank pub persistent reg) := by
+ let c : LogConfig w p r := ⟨pc,persistent,reg,[]⟩
+ obtain ⟨t,ht,hr⟩ := ISA.dispatch_step T pub c
+ have hl := hr.lift id Function.injective_id id (bank pub persistent reg) (target := code T)
+ (by intro q hq; simp only [id_eq, code, ISA.resume_none_of_continuing T q hq]; cases ISA.code T q <;> rfl)
+ have install (s : Stacks (ISA.Port r k)) : installStacks id (bank pub persistent reg) s = s := by
+ funext a; exact installStacks_at Function.injective_id ..
+ simp only [id_eq, install] at hl
+ exact ⟨t, ht, by simpa [c, hpc, ISA.exitFor, ISA.post, ISA.configBank, bank] using hl⟩
+
+/-- Add the final dispatch to a bounded run which reached an `accept` instruction. -/
+theorem return_run {T : Template p r k} {n : ℕ} {pc : Fin p} (hpc : T.code pc = .accept)
+ {pub : Fin k → Word w} {persistent : Word w} {R R' : Fin r → Word w}
+ (hr : SpaceRun (code T) (w+(ISA.prepareBound w 0+3)) n (ISA.entry T T.entry)
+ (bank pub persistent R) (ISA.entry T pc) (bank pub persistent R')) :
+ ∃ t ≤ n+(ISA.prepareBound w 0+2), (routine T).BoundedRun (w+(ISA.prepareBound w 0+3)) t
+ (bank pub persistent R) (bank pub persistent R') := by
+ obtain ⟨m,hm,ht⟩ := accept_run T pc hpc pub persistent R'
+ have bound := spaceRun_of_steps ht fun a => Nat.add_le_add (bank_length_le _ _ _ a)
+ (hm.trans (Nat.le_succ _))
+ let labels (q : ISA.State T) : Option (ISA.State T) := if normal T q then none else some q
+ have hc (q : ISA.State T) (hq : (code T q).returns = false) :
+ (routine T).body.standalone (labels q) = (code T q).rename id labels := by
+ have hn : normal T q = false := by
+ cases hh : normal T q with
+ | false => rfl
+ | true => exact Bool.noConfusion ((normal_halts T q hh).symm.trans hq)
+ simp [labels, routine, FiniteRoutine.ofStackCode, FiniteRoutine.ofRoutine, Routine.standalone, Routine.close, hn]
+ let s := bank pub persistent R
+ have hl := (hr.trans bound).lift id Function.injective_id labels s
+ (fun a outside => (outside a rfl).elim) hc
+ have install (u : Stacks (ISA.Port r k)) : installStacks id s u = u := by
+ funext a; exact installStacks_at Function.injective_id ..
+ refine ⟨n+m, Nat.add_le_add_left hm _, ?_⟩
+ change @SpaceRun (ISA.Port r k) (Option (ISA.State T)) _ (routine T).body.standalone _ (n+m) (some (ISA.entry T T.entry)) _ none _
+ simpa only [install, labels, normal, ISA.resume_callback, ISA.resume_entry, Bool.false_eq_true,
+ ite_false, ite_true] using hl
+
+end RAMTape.RegisterTable
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RegularArcGraph.lean b/lean/OAI/Computability/VPVNP/RegularArcGraph.lean
new file mode 100644
index 0000000000..ed1dd58987
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RegularArcGraph.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.PortMatching
+import Mathlib.Basic.Real.Basic
+import Mathlib.Algebra.BigOperators.Ring.Finset
+
+/-!
+# Loop-free regular multigraphs represented by paired arcs
+
+Theorem 5.1 counts the oriented arcs of a multigraph, with equal
+multiplicities in both directions. Each vertex has one arc per port.
+Reversal pairs the arcs at opposite ends of each undirected edge.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+/-- A loop-free undirected multigraph with exactly `b` outgoing arcs at each vertex. -/
+structure RegularArcGraph (V : Type*) (b : ℕ) where
+ /-- Involutive permutation pairing each outgoing port with the oppositely oriented port of
+ the same undirected edge. -/
+ reverse : Equiv.Perm (V × Fin b)
+ involutive : Function.Involutive reverse
+ ends_ne : ∀ p, (reverse p).1 ≠ p.1
+
+namespace RegularArcGraph
+
+variable {V : Type*} {b : ℕ} (G : RegularArcGraph V b)
+
+/-- Number of arcs going from `u` to `v`. -/
+def multiplicity [DecidableEq V] (u v : V) : ℕ :=
+ (Finset.univ.filter (fun k : Fin b ↦ (G.reverse (u, k)).1 = v)).card
+
+/-- Positive multiplicity is equivalent to the existence of a port leading to the vertex. -/
+theorem multiplicity_pos_iff [DecidableEq V] (u v : V) :
+ 0 < G.multiplicity u v ↔ ∃ k : Fin b, (G.reverse (u, k)).1 = v := by
+ simp [multiplicity, Finset.card_pos, Finset.Nonempty]
+
+/-- Loop-freeness gives zero diagonal in the multiplicity matrix. -/
+@[simp] theorem multiplicity_self [DecidableEq V] (u : V) : G.multiplicity u u = 0 := by
+ apply Nat.eq_zero_of_not_pos
+ rw [G.multiplicity_pos_iff]
+ exact fun ⟨k, hk⟩ ↦ G.ends_ne (u, k) hk
+
+/-- Reversal gives a bijection between the arcs of the two orientations. -/
+theorem multiplicity_symmetric [DecidableEq V] (u v : V) :
+ G.multiplicity u v = G.multiplicity v u := by
+ have back (x y : V) (k : Fin b) (h : (G.reverse (x, k)).1 = y) :
+ G.reverse (y, (G.reverse (x, k)).2) = (x, k) := by
+ subst y
+ exact G.involutive (x, k)
+ apply Finset.card_nbij' (fun k ↦ (G.reverse (u, k)).2) (fun l ↦ (G.reverse (v, l)).2)
+ · intro k hk
+ exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, congrArg Prod.fst
+ (back u v k (Finset.mem_filter.mp hk).2)⟩
+ · intro k hk
+ exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, congrArg Prod.fst
+ (back v u k (Finset.mem_filter.mp hk).2)⟩
+ · intro k hk
+ exact congrArg Prod.snd (back u v k (Finset.mem_filter.mp hk).2)
+ · intro k hk
+ exact congrArg Prod.snd (back v u k (Finset.mem_filter.mp hk).2)
+
+/-- Counting the outgoing ports gives the degree at every vertex. -/
+theorem degree [Fintype V] [DecidableEq V] (u : V) : ∑ v, G.multiplicity u v = b := by
+ simpa [multiplicity] using Finset.sum_card_fiberwise_eq_card_filter
+ (Finset.univ : Finset (Fin b)) Finset.univ (fun k ↦ (G.reverse (u, k)).1)
+
+/-- Reversal exchanges the two different arcs of each edge. -/
+theorem reverse_ne (p : V × Fin b) : G.reverse p ≠ p :=
+ fun he ↦ G.ends_ne p (congrArg Prod.fst he)
+
+/-- Group the sum of any arc cost by its ordered pair of endpoints. -/
+theorem sum_cost [Fintype V] [DecidableEq V] (c : V → V → ℝ) :
+ (∑ p : V × Fin b, c p.1 (G.reverse p).1) = ∑ u, ∑ v, (G.multiplicity u v : ℝ) * c u v := by
+ rw [Fintype.sum_prod_type]
+ apply Finset.sum_congr rfl
+ intro u _
+ have term (v : V) : (G.multiplicity u v : ℝ) * c u v =
+ ∑ k : Fin b, if (G.reverse (u, k)).1 = v then c u v else 0 := by
+ rw [Finset.sum_ite, Finset.sum_const_zero, add_zero, Finset.sum_const,
+ nsmul_eq_mul, multiplicity]
+ simp_rw [term]
+ rw [Finset.sum_comm]
+ simp
+
+end RegularArcGraph
+
+/-- Realize a symmetric zero-diagonal matrix with constant row sum by a regular graph. -/
+theorem exists_regularArcGraph {V : Type*} [Fintype V] [DecidableEq V] {b : ℕ}
+ (M : V → V → ℕ) (hsym : ∀ u v, M u v = M v u) (hrow : ∀ u, ∑ v, M u v = b)
+ (hdiag : ∀ u, M u u = 0) :
+ ∃ G : RegularArcGraph V b, ∀ u v, G.multiplicity u v = M u v := by
+ obtain ⟨σ, hσ, hcount, _⟩ := exists_portMatching M hsym hrow
+ refine ⟨⟨σ, hσ, ?_⟩, hcount⟩
+ rintro ⟨u, k⟩ hk
+ have hempty : (Finset.univ.filter (fun l : Fin b ↦ (σ (u, l)).1 = u)) = ∅ := by
+ apply Finset.card_eq_zero.mp
+ exact (hcount u u).trans (hdiag u)
+ have hmem : k ∈ Finset.univ.filter (fun l : Fin b ↦ (σ (u, l)).1 = u) :=
+ Finset.mem_filter.mpr ⟨Finset.mem_univ _, hk⟩
+ simp only [hempty, Finset.notMem_empty] at hmem
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RegularizedMotifs.lean b/lean/OAI/Computability/VPVNP/RegularizedMotifs.lean
new file mode 100644
index 0000000000..3445658aa0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RegularizedMotifs.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.SlotOtherEnd
+import OAI.Computability.VPVNP.SlotRegularization
+import OAI.Computability.VPVNP.SlotSeparation
+import OAI.Computability.VPVNP.SlotTranslation
+import OAI.Computability.VPVNP.SurvivingSlots
+
+/-!
+# The regularized graph of a shrinking step
+
+The graph constructed at the end of Section 7.2 of *VP and VNP differ
+over every field* is a lift over the pairs consisting of an old base and a
+tag. A motif in its lane-zero section supplies one base identifier for each
+surviving type and subdivision. The role-to-role displacement restores the
+actual lanes at its ends. The uniform role counts give the common deficit
+that the cyclic dummy arcs fill.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+open SurvivingSlots
+
+variable {V H Tag L : Type*} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- Each role incidence at an absolute site corresponds to exactly one
+lane-zero motif at its packed base. Reindexing by the role's lane handles
+both ends of the edge and either layout. -/
+def baseRoleFiberEquiv (role : P.Motif → Site V Tag L)
+ (hr : ∀ m g, role (P.translateMotif m g) = translateSite (role m) g)
+ (b : V × Tag) (g : L) :
+ {z : P.BaseMotif // packedBase (role z.1) = b} ≃ {m : P.Motif // role m = (b.1, b.2, g)} := by
+ let e := P.roleLaneEquiv role hr
+ have atLane (z : P.BaseMotif) (h : L) :
+ role (e.symm (z, h)) = ((role z.1).1, (role z.1).2.1, h) :=
+ (P.roleLane_endpoints role role hr hr z h).1
+ exact {
+ toFun := fun z ↦ ⟨e.symm (z.1, g), (atLane z.1 g).trans
+ (congrArg (fun b : V × Tag ↦ (b.1, b.2, g)) z.2)⟩
+ invFun := fun m ↦ ⟨(e m.1).1, by
+ have h := atLane (e m.1).1 (e m.1).2
+ rw [Prod.mk.eta, e.symm_apply_apply] at h
+ exact (congrArg packedBase h).symm.trans (congrArg packedBase m.2)⟩
+ left_inv := fun z ↦ Subtype.ext (congrArg Prod.fst (e.apply_symm_apply (z.1, g)))
+ right_inv := fun m ↦ Subtype.ext (e.injective (by
+ rw [e.apply_symm_apply]
+ refine Prod.ext ?_ ?_
+ · rfl
+ change g = (role m.1).2.2
+ rw [m.2])) }
+
+/-- The packed base of a role of a lane-zero motif. -/
+def roleBase (layout : Bool) (r : PackedRole) (z : P.BaseMotif) : V × Tag :=
+ packedBase (P.survivingRole layout r z.1)
+
+theorem survivingRole_translate (layout : Bool) (r : PackedRole) (m : P.Motif) (g : L) :
+ P.survivingRole layout r (P.translateMotif m g) =
+ translateSite (P.survivingRole layout r m) g := by
+ cases r with
+ | a => exact P.roleA_translate m g
+ | b => exact P.roleB_translate m g
+ | d => exact P.roleD_translate layout m g
+
+/-- Fixed displacement of a role edge on a lane-zero ID. -/
+def roleDisplacement {T : Type*} (layout : Bool) (src dst : T → PackedRole) {subdiv : T → ℕ}
+ (i : Id P.BaseMotif subdiv) : L :=
+ (P.survivingRole layout (dst i.1) i.2.1.1).2.2 - (P.survivingRole layout (src i.1) i.2.1.1).2.2
+
+/-- Reindex every actual subdivided role edge by its lane-zero ID and its
+absolute source-role lane. The inverse recovers the same motif and
+subdivision, including when several supply types use the same two roles. -/
+def survivingLaneEquiv (layout : Bool) (subdiv : Fin 4 → ℕ) :
+ Id P.Motif subdiv ≃ Id P.BaseMotif subdiv × L := by
+ let e (t : Fin 4) := P.roleLaneEquiv (P.survivingRole layout (sourceRole layout t))
+ (P.survivingRole_translate layout (sourceRole layout t))
+ exact {
+ toFun := fun ⟨t, m, i⟩ ↦ (⟨t, (e t m).1, i⟩, (e t m).2)
+ invFun := fun ⟨⟨t, z, i⟩, g⟩ ↦ ⟨t, (e t).symm (z, g), i⟩
+ left_inv := by rintro ⟨t, m, i⟩; simp
+ right_inv := by rintro ⟨⟨t, z, i⟩, g⟩; simp }
+
+/-- The reconstructed actual ID has precisely the source and target sites
+of the corresponding lifted arc. -/
+theorem survivingLane_endpoints (layout : Bool) (subdiv : Fin 4 → ℕ)
+ (z : Id P.BaseMotif subdiv) (g : L) :
+ let i := (P.survivingLaneEquiv layout subdiv).symm (z, g)
+ let src := endpoint (P.roleBase layout) (sourceRole layout) z
+ let dst := endpoint (P.roleBase layout) (targetRole layout) z
+ endpoint (P.survivingRole layout) (sourceRole layout) i = (src.1, src.2, g) ∧
+ endpoint (P.survivingRole layout) (targetRole layout) i =
+ (dst.1, dst.2, g +
+ P.roleDisplacement layout (sourceRole layout) (targetRole layout) z) := by
+ rcases z with ⟨t, m, i⟩
+ exact P.roleLane_endpoints _ _ (P.survivingRole_translate layout (sourceRole layout t))
+ (P.survivingRole_translate layout (targetRole layout t)) m g
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+/-- Each packed base has the same `dQ` role count among lane-zero motifs. -/
+theorem card_roleBase (hc : 2 ≤ c) (layout : Bool) (r : PackedRole) (b : V × Tag) :
+ Fintype.card {z : P.BaseMotif // P.roleBase layout r z = b} = d * (3 * (2 ^ c * d) / 4) := by
+ unfold roleBase
+ rw [Fintype.card_congr (P.baseRoleFiberEquiv (P.survivingRole layout r)
+ (P.survivingRole_translate layout r) b 0)]
+ cases r with
+ | a => exact P.card_roleA hc _
+ | b => exact P.card_roleB hc _
+ | d => exact P.card_roleD hc layout _
+
+/-- The uniform in- and outdegree before cyclic padding. -/
+def survivingDegree (d c : ℕ) (subdiv : Fin 4 → ℕ) : ℕ :=
+ d * (3 * (2 ^ c * d) / 4) * ∑ t, subdiv t
+
+variable [Module (ZMod 2) Tag]
+
+/-- A lift of the padded, subdivided surviving graph over the packed bases.
+Every genuine ID is numbered in the given order of lane-zero IDs, and the
+dummy slots go to the next tag without changing the remaining lane. -/
+def regularizedSlotIndexing (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (layout : Bool) (subdiv : Fin 4 → ℕ) [LinearOrder (Id P.BaseMotif subdiv)]
+ {d' J : ℕ} (hd : survivingDegree d c subdiv ≤ d') (tagIndex : Tag ≃ Fin J) (hJ : 1 < J) :
+ SlotIndexing (V × Tag) (PaddedId (V × Tag) (Id P.BaseMotif subdiv)
+ (d' - survivingDegree d c subdiv)) L d'
+ (paddedSource (endpoint (P.roleBase layout) (sourceRole layout)))
+ (paddedTarget (endpoint (P.roleBase layout) (targetRole layout)) (cycleTags tagIndex))
+ (paddedShift (P.roleDisplacement layout (sourceRole layout) (targetRole layout))) := by
+ refine paddedSlotIndexing _ _ _ ?_ ?_ ?_ hd _ (cycleTags_ne tagIndex hJ)
+ · intro i
+ exact (P.survivingSlot_bases_ne hφ layout
+ (subdiv := subdiv) ⟨i.1, i.2.1.1, i.2.2⟩).symm
+ · exact card_endpoint _ _ subdiv (P.card_roleBase hc layout)
+ · exact card_endpoint _ _ subdiv (P.card_roleBase hc layout)
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/RoutineSpace.lean b/lean/OAI/Computability/VPVNP/RoutineSpace.lean
new file mode 100644
index 0000000000..8c5e754f18
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/RoutineSpace.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+import OAI.Computability.VPVNP.SpaceRunMonotone
+
+/-! # Preserving stack space across nested calls
+
+Installation, returning calls and sequential composition reuse the same bit-stack
+space bound. They can therefore compose exponentially long subroutines without
+adding their running times to the caller's space use.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalCountStack
+
+open RAMTape
+
+variable {K L Q R : Type*} [DecidableEq K] [DecidableEq L]
+
+theorem SpaceRun.initial_cap {code : StackCode K Q} {cap n q s t u} (run : SpaceRun code cap n q s t u) :
+ ∀ k, (s k).length ≤ cap := by cases run <;> assumption
+
+theorem SpaceRun.final_cap {code : StackCode K Q} {cap n q s t u} (run : SpaceRun code cap n q s t u) :
+ ∀ k, (u k).length ≤ cap := by induction run <;> assumption
+
+/-- Lift control and ports without changing the number of steps or the cap, provided
+all caller stacks outside the installed bank already lie below the cap. -/
+theorem SpaceRun.lift {src : StackCode K Q} {target : StackCode L R} {cap n q s t u}
+ (run : SpaceRun src cap n q s t u) (ports : K → L) (hp : Function.Injective ports)
+ (labels : Q → R) (base : Stacks L) (hbase : ∀ l, (∀ k, ports k ≠ l) → (base l).length ≤ cap)
+ (hc : ∀ v, (src v).returns = false → target (labels v) = (src v).rename ports labels) :
+ SpaceRun target cap n (labels q) (installStacks ports base s) (labels t) (installStacks ports base u) := by
+ have installed (v : Stacks K) (h : ∀ k, (v k).length ≤ cap) (l : L) :
+ (installStacks ports base v l).length ≤ cap := by
+ by_cases hm : ∃ k, ports k = l
+ · obtain ⟨k, rfl⟩ := hm
+ simpa only [installStacks_at hp] using h k
+ · rw [installStacks_outside _ _ (not_exists.mp hm)]
+ exact hbase l (not_exists.mp hm)
+ induction run with
+ | nil _ _ hs => exact .nil _ _ (installed _ hs)
+ | cons hs step _ ih => exact .cons (installed _ hs) (step.lift ports hp labels base hc) ih
+
+theorem SpaceRun.linkRoutine {inner : Routine K Q} {cap n : ℕ} {s out : Stacks K}
+ (run : SpaceRun inner.standalone cap n (some inner.entry) s none out)
+ (outer : Routine K R) (label : Q → R) (resume : Option R)
+ (h : ∀ q, outer.code (label q) = inner.install label resume q) :
+ SpaceRun outer.standalone cap n (some (label inner.entry)) s resume out := by
+ let labels (q : Option Q) := q.elim resume (some ∘ label)
+ have hc (q : Option Q) (hq : (inner.standalone q).returns = false) :
+ outer.standalone (labels q) = (inner.standalone q).rename id labels := by
+ cases q with
+ | none => contradiction
+ | some q => exact h q
+ have hi (st : Stacks K) : installStacks id s st = st := by
+ funext k
+ exact installStacks_at Function.injective_id s st k
+ simpa only [labels, Option.elim_none, Option.elim_some, Function.comp_apply, hi] using
+ run.lift id Function.injective_id labels s (fun l outside ↦ (outside l rfl).elim) hc
+
+end UniversalCountStack
+
+namespace RAMTape.FiniteRoutine
+
+open UniversalCountStack
+
+variable {K L : Type} [DecidableEq K] [DecidableEq L]
+
+/-- Execution of a standalone routine from entry to return in exactly `n` steps with every
+stack height bounded by `cap`. -/
+abbrev BoundedRun (r : FiniteRoutine K) (cap n : ℕ) (s out : Stacks K) :=
+ SpaceRun r.body.standalone cap n (some r.body.entry) s none out
+
+theorem BoundedRun.followedBy {a b : FiniteRoutine K} {cap m n : ℕ} {s t u : Stacks K}
+ (ha : a.BoundedRun cap m s t) (hb : b.BoundedRun cap n t u) :
+ (a.followedBy b).BoundedRun cap (m+n) s u :=
+ (ha.linkRoutine (a.body.followedBy b.body) Sum.inl (some (.inr b.body.entry)) (fun _ ↦ rfl)).trans
+ (hb.linkRoutine (a.body.followedBy b.body) Sum.inr none (fun _ ↦ rfl))
+
+theorem BoundedRun.onPorts {a : FiniteRoutine K} {ports : K → L} (hp : Function.Injective ports)
+ (base : Stacks L) {cap n : ℕ} {s out : Stacks K} (h : a.BoundedRun cap n s out)
+ (hbase : ∀ l, (∀ k, ports k ≠ l) → (base l).length ≤ cap) :
+ (a.onPorts ports).BoundedRun cap n (installStacks ports base s) (installStacks ports base out) := by
+ exact h.lift ports hp id base hbase (fun q _ ↦ by cases q <;> rfl)
+
+end RAMTape.FiniteRoutine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ScalarDescent.lean b/lean/OAI/Computability/VPVNP/ScalarDescent.lean
new file mode 100644
index 0000000000..3a831d2b80
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ScalarDescent.lean
@@ -0,0 +1,55 @@
+import Mathlib.RingTheory.Nullstellensatz
+
+/-!
+# Descent of exact polynomial computations
+
+Section 1 of *VP and VNP differ over every field* passes from a circuit over an
+arbitrary field to the same circuit topology over the algebraic closure of the prime
+field. Each scalar input of the topology can first be replaced by a parameter. The
+coefficients of the resulting formal output are polynomials in these parameters.
+Hilbert's Nullstellensatz descends the simultaneous coefficient equations to any
+algebraically closed extension of the base field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+variable {k F K σ υ : Type*} [Field k] [Field F] [Field K]
+ [Algebra k F] [Algebra k K] [IsAlgClosed K] [Finite σ]
+
+/-- A polynomial system in finitely many unknowns that has a solution in an extension
+field of `k` has a solution in every algebraically closed extension of `k`. -/
+theorem polynomialSystem_descent (S : Set (MvPolynomial σ k)) (a : σ → F)
+ (ha : ∀ p ∈ S, aeval a p = 0) :
+ ∃ b : σ → K, ∀ p ∈ S, aeval b p = 0 := by
+ have hproper : Ideal.span S ≠ ⊤ := by
+ have hle : Ideal.span S ≤ vanishingIdeal k {a} :=
+ Ideal.span_le.mpr fun p hp ↦ (mem_vanishingIdeal_singleton_iff a p).mpr (ha p hp)
+ exact fun h ↦ (inferInstance : (vanishingIdeal k {a}).IsPrime).ne_top <|
+ top_unique (h ▸ hle)
+ obtain ⟨M, hM, hSM⟩ := Ideal.exists_le_maximal (Ideal.span S) hproper
+ obtain ⟨b, rfl⟩ := eq_vanishingIdeal_singleton_of_isMaximal K hM
+ exact ⟨b, fun p hp ↦ (mem_vanishingIdeal_singleton_iff b p).mp
+ (hSM (Ideal.subset_span hp))⟩
+
+/-- An exact specialization of a formal output polynomial over a parameter ring descends
+simultaneously in all its coefficients. This applies to a circuit with any degree of
+intermediate cancellation, using its scalar inputs as the parameters. -/
+theorem formalOutput_descent (P : MvPolynomial υ (MvPolynomial σ k)) (f : MvPolynomial υ k)
+ (a : σ → F) (ha : map (aeval a).toRingHom P = map (algebraMap k F) f) :
+ ∃ b : σ → K, map (aeval b).toRingHom P = map (algebraMap k K) f := by
+ let eqn (m : υ →₀ ℕ) : MvPolynomial σ k := P.coeff m - C (f.coeff m)
+ obtain ⟨b, hb⟩ := polynomialSystem_descent (K := K) (Set.range eqn) a (by
+ rintro _ ⟨m, rfl⟩
+ have h := congrArg (fun p : MvPolynomial υ F ↦ p.coeff m) ha
+ simpa [eqn, sub_eq_zero, coeff_map] using h)
+ refine ⟨b, MvPolynomial.ext _ _ fun m ↦ ?_⟩
+ have h := hb (eqn m) (Set.mem_range_self m)
+ simpa [eqn, sub_eq_zero, coeff_map] using h
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SchurCoefficientQueries.lean b/lean/OAI/Computability/VPVNP/SchurCoefficientQueries.lean
new file mode 100644
index 0000000000..f80692b0aa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SchurCoefficientQueries.lean
@@ -0,0 +1,185 @@
+import OAI.Computability.VPVNP.FormalSchur
+import OAI.Computability.VPVNP.MatrixPowerQueries
+
+/-!
+# Bivariate coefficient queries for the Schur product
+
+Appendix D.2 of *VP and VNP differ over every field* uses the Schur product to
+compute any specified coefficient of `det (1 - uM(z))`. Each query uses an
+oracle for individual scalar coefficients of the matrix entries. Its two
+recursive computations split the list of factors and the exponents of matrix
+powers in half.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RankQuery
+
+variable {R : Type*} [CommRing R] {n : ℕ}
+
+/-- Query one bidegree of the first factor using only coefficients of matrix entries. -/
+def headFactorQuery (entry : Fin (n + 1) → Fin (n + 1) → ℕ → R) (u z : ℕ) : R :=
+ match u with
+ | 0 => if z = 0 then 1 else 0
+ | 1 => -entry 0 0 z
+ | h + 2 => -(∑ i : Fin n, ∑ j : Fin n, ∑ d ∈ Finset.antidiagonal z,
+ (∑ e ∈ Finset.antidiagonal d.1, entry 0 i.succ e.1 *
+ powerEntryCoeff (fun a b : Fin n => entry a.succ b.succ) h i j e.2) * entry j.succ 0 d.2)
+
+theorem headFactorQuery_correct (M : Matrix (Fin (n + 1)) (Fin (n + 1)) (Polynomial R))
+ (entry : Fin (n + 1) → Fin (n + 1) → ℕ → R) (he : ∀ i j z, entry i j z = (M i j).coeff z)
+ (u z : ℕ) : headFactorQuery entry u z = (PowerSeries.coeff u (headFactor M)).coeff z := by
+ rw [coeff_headFactor]
+ cases u with
+ | zero => simp [headFactorQuery, Polynomial.coeff_one]
+ | succ u =>
+ cases u with
+ | zero => simp [headFactorQuery, he]
+ | succ h =>
+ simp only [headFactorQuery, Polynomial.coeff_neg, Polynomial.finsetSum_coeff,
+ Polynomial.coeff_mul, powerEntryCoeff_correct (M.submatrix Fin.succ Fin.succ)
+ (fun a b : Fin n => entry a.succ b.succ) (fun a b z => he a.succ b.succ z), he]
+
+/-- Compute a coefficient of the Schur factor with sequential scans of
+both matrix indices and both degree splits. Each queried power of the
+trailing matrix is also evaluated by streaming scans. -/
+def streamedHeadFactorQuery (entry : Fin (n + 1) → Fin (n + 1) → ℕ → R) (u z : ℕ) : R :=
+ match u with
+ | 0 => if z = 0 then 1 else 0
+ | 1 => -entry 0 0 z
+ | h + 2 => -(streamSum n fun i => streamSum n fun j =>
+ streamAntiSum z fun d₁ d₂ =>
+ (streamAntiSum d₁ fun e₁ e₂ => entry 0 i.succ e₁ *
+ streamedPowerEntryCoeff (fun a b : Fin n => entry a.succ b.succ) h i j e₂) *
+ entry j.succ 0 d₂)
+
+theorem streamedHeadFactorQuery_eq (entry : Fin (n + 1) → Fin (n + 1) → ℕ → R) (u z : ℕ) :
+ streamedHeadFactorQuery entry u z = headFactorQuery entry u z := by
+ rcases u with _ | _ | h
+ · rfl
+ · rfl
+ · simp only [streamedHeadFactorQuery, headFactorQuery, streamSum_eq, streamAntiSum_eq,
+ streamedPowerEntryCoeff_eq]
+
+section BalancedProduct
+
+variable {ι R : Type*}
+
+/-- Query a consecutive block of factors. Each internal node splits the block
+into two halves. Each root-to-leaf path makes exactly `depth` such splits. -/
+def balancedProduct (unit : ι → R) (combine : (ι → R) → (ι → R) → ι → R)
+ (read : ℕ → ι → R) : ℕ → ℕ → ℕ → ι → R
+ | 0, first, count, q => if count = 0 then unit q else read first q
+ | depth + 1, first, count, q =>
+ let half := count / 2
+ combine (fun r => balancedProduct unit combine read depth first half r)
+ (fun r => balancedProduct unit combine read depth (first + half) (count - half) r) q
+
+private theorem balancedProduct_eq {A : Type*} [CommMonoid A] (coef : A → ι → R)
+ (unit : ι → R) (combine : (ι → R) → (ι → R) → ι → R)
+ (hunit : unit = coef 1) (hmul : ∀ a b, combine (coef a) (coef b) = coef (a * b))
+ (factor : ℕ → A) (depth first count : ℕ) (hcount : count ≤ 2 ^ depth) :
+ balancedProduct unit combine (fun i => coef (factor i)) depth first count =
+ coef (∏ j ∈ Finset.range count, factor (first + j)) := by
+ induction depth generalizing first count with
+ | zero =>
+ funext q
+ have h : count = 0 ∨ count = 1 := by simp only [pow_zero] at hcount; omega
+ rcases h with rfl | rfl <;> simp [balancedProduct, hunit]
+ | succ depth ih =>
+ funext q
+ rw [pow_succ] at hcount
+ let half := count / 2
+ have hleft : half ≤ 2 ^ depth := by dsimp [half]; omega
+ have hright : count - half ≤ 2 ^ depth := by dsimp [half]; omega
+ rw [balancedProduct, ih first half hleft, ih (first + half) (count - half) hright, hmul]
+ apply congrArg (fun a => coef a q)
+ have hsplit := Finset.prod_range_add (fun j => factor (first + j)) half (count - half)
+ rw [Nat.add_sub_of_le (show half ≤ count by dsimp [half]; omega)] at hsplit
+ simpa only [Nat.add_assoc] using hsplit.symm
+
+variable [CommSemiring R]
+
+/-- Coefficient query for the factors of the Appendix D.2 determinant in
+`R[z][[u]]`. Both degree splits stream over a single counter. The parameter
+`depth = Nat.clog 2 count` suffices for any number of consecutive factors. -/
+def balancedBivariateProduct (read : ℕ → ℕ → ℕ → R) (depth first count u z : ℕ) : R :=
+ balancedProduct (fun p : ℕ × ℕ => if p.1 = 0 ∧ p.2 = 0 then 1 else 0)
+ (fun left right p => streamAntiSum p.1 fun a₁ a₂ => streamAntiSum p.2 fun b₁ b₂ =>
+ left (a₁, b₁) * right (a₂, b₂))
+ (fun i p => read i p.1 p.2) depth first count (u, z)
+
+theorem balancedBivariateProduct_eq (factor : ℕ → PowerSeries (Polynomial R))
+ (depth first count u z : ℕ) (hcount : count ≤ 2 ^ depth) :
+ balancedBivariateProduct (fun i a b => (PowerSeries.coeff a (factor i)).coeff b)
+ depth first count u z =
+ (PowerSeries.coeff u (∏ j ∈ Finset.range count, factor (first + j))).coeff z := by
+ unfold balancedBivariateProduct
+ apply congrFun (balancedProduct_eq (fun s (p : ℕ × ℕ) => (PowerSeries.coeff p.1 s).coeff p.2)
+ _ _ ?_ ?_ factor depth first count hcount) (u, z)
+ · funext p
+ by_cases hu : p.1 = 0 <;> simp [PowerSeries.coeff_one, Polynomial.coeff_one, hu]
+ · intro a b
+ funext p
+ simp only [streamAntiSum_eq, PowerSeries.coeff_mul, Polynomial.finsetSum_coeff,
+ Polynomial.coeff_mul]
+
+end BalancedProduct
+
+/-- Query a Schur factor by its absolute index, giving the identity series
+at indices outside the matrix. -/
+private def determinantLeaf (entry : Fin n → Fin n → ℕ → R) (a u z : ℕ) : R :=
+ if h : a < n then
+ let i : Fin n := ⟨a, h⟩
+ streamedHeadFactorQuery (fun b c => entry (suffixIndex i b) (suffixIndex i c)) u z
+ else if u = 0 ∧ z = 0 then 1 else 0
+
+private theorem determinantLeaf_correct (M : Matrix (Fin n) (Fin n) (Polynomial R))
+ (entry : Fin n → Fin n → ℕ → R) (he : ∀ i j z, entry i j z = (M i j).coeff z) (a u z : ℕ) :
+ determinantLeaf entry a u z = (PowerSeries.coeff u (if h : a < n then
+ let i : Fin n := ⟨a, h⟩
+ headFactor (M.submatrix (suffixIndex i) (suffixIndex i)) else 1)).coeff z := by
+ by_cases h : a < n
+ · simp only [determinantLeaf, h, dite_eq_left, streamedHeadFactorQuery_eq]
+ apply headFactorQuery_correct
+ intro b c z
+ exact he _ _ z
+ · by_cases hu : u = 0 <;> by_cases hz : z = 0 <;>
+ simp [determinantLeaf, h, hu, hz, PowerSeries.coeff_one, Polynomial.coeff_one]
+
+private theorem padded_prod_eq {A : Type*} [CommMonoid A] {n count : ℕ} (h : n ≤ count)
+ (f : Fin n → A) : (∏ i ∈ Finset.range count, if hi : i < n then f ⟨i, hi⟩ else 1) = ∏ i, f i := by
+ let F (i : ℕ) := if hi : i < n then f ⟨i, hi⟩ else 1
+ change (∏ i ∈ Finset.range count, F i) = _
+ calc
+ _ = ∏ i ∈ Finset.range n, F i := Finset.prod_subset (Finset.range_mono h)
+ (fun i _ hi => dite_eq_right (fun hi' => hi (Finset.mem_range.mpr hi')) ) |>.symm
+ _ = ∏ i : Fin n, F i.val := (Fin.prod_univ_eq_prod_range F n).symm
+ _ = _ := Finset.prod_congr rfl fun i _ => dite_eq_left i.isLt
+
+/-- Compute a scalar bidegree of `det (1-uM(z))` without constructing its polynomial. -/
+def determinantQuery (entry : Fin n → Fin n → ℕ → R) (u z : ℕ) : R :=
+ balancedBivariateProduct (determinantLeaf entry) (Nat.clog 2 n) 0 n u z
+
+theorem determinantQuery_eq (M : Matrix (Fin n) (Fin n) (Polynomial R))
+ (entry : Fin n → Fin n → ℕ → R) (he : ∀ i j z, entry i j z = (M i j).coeff z) (u z : ℕ) :
+ determinantQuery entry u z = (M.charpolyRev.coeff u).coeff z := by
+ let F (a : ℕ) : PowerSeries (Polynomial R) := if h : a < n then
+ let i : Fin n := ⟨a, h⟩
+ headFactor (M.submatrix (suffixIndex i) (suffixIndex i)) else 1
+ have hleaf : determinantLeaf entry = fun a u z => (PowerSeries.coeff u (F a)).coeff z :=
+ funext fun a => funext fun u => funext fun z => determinantLeaf_correct M entry he a u z
+ rw [determinantQuery, hleaf, balancedBivariateProduct_eq F _ _ _ _ _ (Nat.le_pow_clog (by decide) n)]
+ have hprod : (∏ j ∈ Finset.range n, F (0 + j)) = (M.charpolyRev : PowerSeries (Polynomial R)) := by
+ simp only [Nat.zero_add, charpolyRev_eq_schurProduct]
+ exact padded_prod_eq (n := n) le_rfl
+ (fun i => headFactor (M.submatrix (suffixIndex i) (suffixIndex i)))
+ rw [hprod, Polynomial.coeff_coe]
+
+end RankQuery
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SectorSpeeds.lean b/lean/OAI/Computability/VPVNP/SectorSpeeds.lean
new file mode 100644
index 0000000000..2b3f227314
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SectorSpeeds.lean
@@ -0,0 +1,111 @@
+import OAI.Computability.VPVNP.WireGeodesic
+import Mathlib.Analysis.Convex.Topology
+import Mathlib.Tactic.FieldSimp
+import Mathlib.Tactic.Module
+
+/-!
+# Directional speeds on an affine sector
+
+In Section 4.1 of *VP and VNP differ over every field*, the sector map takes
+affine segments to constant-speed geodesics. The distance per unit step in
+a direction is independent of the step length. Fraction transport toward a
+point beyond a second interior base point shows that the speed is independent
+of the base point as well.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open Set
+open scoped Topology
+
+variable {D : Set (ℝ × ℝ)} {X : Type*} [PseudoMetricSpace X] {H : (ℝ × ℝ) → X}
+
+/-- A sufficiently short positive step from an interior point stays in the domain. -/
+theorem exists_positive_step_mem {p : ℝ × ℝ} (hp : p ∈ interior D) (v : ℝ × ℝ) :
+ ∃ t : ℝ, 0 < t ∧ p + t • v ∈ D := by
+ have hc : Continuous (fun t : ℝ ↦ p + t • v) := by fun_prop
+ have hN : (fun t : ℝ ↦ p + t • v) ⁻¹' D ∈ 𝓝 0 := by
+ apply hc.continuousAt.preimage_mem_nhds
+ simpa using mem_interior_iff_mem_nhds.mp hp
+ obtain ⟨r, hr, hrD⟩ := exists_Ico_subset_of_mem_nhds hN (exists_gt 0)
+ exact ⟨r / 2, by linarith, hrD ⟨by linarith, by linarith⟩⟩
+
+variable (hD : Convex ℝ D) (ht : FractionTransport X)
+ (hH : ∀ {x y}, x ∈ D → y ∈ D → ∀ {t : ℝ}, 0 ≤ t → t ≤ 1 →
+ AtFraction (H x) (H y) t (H ((1 - t) • x + t • y)))
+
+private def RadialSpeedAt (D : Set (ℝ × ℝ)) (H : (ℝ × ℝ) → X) (p v : ℝ × ℝ) (a : ℝ) : Prop :=
+ ∀ (t : ℝ), 0 < t → p + t • v ∈ D → dist (H p) (H (p + t • v)) = t * a
+
+include hH in
+private theorem radial_distance_mul {p v : ℝ × ℝ} (hp : p ∈ D) {s t : ℝ}
+ (hs : 0 < s) (hst : s ≤ t) (hy : p + t • v ∈ D) :
+ t * dist (H p) (H (p + s • v)) = s * dist (H p) (H (p + t • v)) := by
+ have htpos : 0 < t := hs.trans_le hst
+ have hr := (hH hp hy (div_nonneg hs.le htpos.le) ((div_le_one htpos).mpr hst)).1
+ have heq : (1 - s / t) • p + (s / t) • (p + t • v) = p + s • v := by
+ match_scalars <;> field_simp
+ all_goals ring
+ rw [heq] at hr
+ rw [hr]
+ field_simp
+
+include hH in
+private theorem exists_local_speed {p : ℝ × ℝ} (hp : p ∈ interior D) (v : ℝ × ℝ) :
+ ∃ a, RadialSpeedAt D H p v a := by
+ obtain ⟨r, hr, hrD⟩ := exists_positive_step_mem hp v
+ refine ⟨dist (H p) (H (p + r • v)) / r, fun t ht' htv ↦ ?_⟩
+ rw [← mul_div_assoc, eq_div_iff hr.ne']
+ rcases le_total t r with h | h
+ · simpa only [mul_comm (dist _ _) r] using radial_distance_mul hH (interior_subset hp) ht' h hrD
+ · simpa only [mul_comm (dist _ _) r] using
+ (radial_distance_mul hH (interior_subset hp) hr h htv).symm
+
+include hD ht hH in
+private theorem radial_speed_le {p q v : ℝ × ℝ} (hp : p ∈ interior D) (hq : q ∈ interior D)
+ {a b : ℝ} (ha : RadialSpeedAt D H p v a) (hb : RadialSpeedAt D H q v b) : b ≤ a := by
+ obtain ⟨r, hr, hrv⟩ := exists_positive_step_mem hp v
+ obtain ⟨e, he, hze⟩ := exists_positive_step_mem hq (q - p)
+ let z := q + e • (q - p)
+ let k : ℝ := (1 + e)⁻¹
+ have hden : 0 < 1 + e := by linarith
+ have hk : 0 < k := inv_pos.mpr hden
+ have hk' : k < 1 := inv_lt_one_of_one_lt₀ (by linarith)
+ have hqeq : (1 - k) • p + k • z = q := by
+ dsimp [z, k]
+ match_scalars <;> field_simp
+ all_goals ring
+ have hveq : (1 - k) • (p + r • v) + k • z = q + ((1 - k) * r) • v := by
+ rw [← hqeq]
+ module
+ have hmem : q + ((1 - k) * r) • v ∈ D := hveq ▸
+ hD hrv hze (sub_nonneg.mpr hk'.le) hk.le (by ring)
+ have h := ht hk.le hk'.le (hH (interior_subset hp) hze hk.le hk'.le)
+ (hH hrv hze hk.le hk'.le)
+ rw [hqeq, hveq, dist_self, mul_zero, add_zero, ha r hr hrv,
+ hb ((1 - k) * r) (mul_pos (sub_pos.mpr hk') hr) hmem, ← mul_assoc] at h
+ exact (mul_le_mul_iff_right₀ (mul_pos (sub_pos.mpr hk') hr)).mp h
+
+include hD ht hH in
+/-- A single directional speed applies to all positive steps from all interior
+base points, including steps that end on the boundary of the domain. -/
+theorem exists_sector_speed {p : ℝ × ℝ} (hp : p ∈ interior D) :
+ ∃ speed : (ℝ × ℝ) → ℝ, ∀ x ∈ interior D, ∀ (v : ℝ × ℝ) (t : ℝ),
+ 0 < t → x + t • v ∈ D → dist (H x) (H (x + t • v)) = t * speed v := by
+ choose speed hs using fun v ↦ exists_local_speed hH hp v
+ refine ⟨speed, fun x hx v t ht' htv ↦ ?_⟩
+ obtain ⟨b, hb⟩ := exists_local_speed hH hx v
+ have heq : b = speed v := le_antisymm (radial_speed_le hD ht hH hp hx (hs v) hb)
+ (radial_speed_le hD ht hH hx hp hb (hs v))
+ rw [← heq]
+ exact hb t ht' htv
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Separation.lean b/lean/OAI/Computability/VPVNP/Separation.lean
new file mode 100644
index 0000000000..351ad0b436
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Separation.lean
@@ -0,0 +1,40 @@
+import OAI.Computability.VPVNP.FamilyResult
+import OAI.Computability.VPVNP.FixedPaperPairCompiler
+
+/-! # Separation over every field
+
+The explicit family of (1.1) is treated in `explicit_complete_family`.
+Here the fixed compressed-pair compiler closes the diagonal argument. The
+length threshold is chosen for each exponent and characteristic before
+the coefficient field is chosen.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u
+
+/-- The uniform exact arithmetic circuit lower bound of Theorem 1.1. -/
+theorem separation_lower_bound :
+ ∀ C : ℕ, 1 ≤ C → ∀ q : ℕ, ∃ N, ∀ n ≥ N, ∀ (F : Type u) [Field F] [CharP F q],
+ n ^ C < circuitSize (MvPolynomial.map (Int.castRingHom F) (P n)) := by
+ apply FixedProgramDiagonal.uniform_of_pair_compilers
+ intro C _ q K _ _ _ _ S B _
+ exact FixedProgramDiagonal.Program.paperPairCompiler B C
+
+/-- The family on the paired variables separates the two nonuniform classes over each field. -/
+theorem vp_ne_vnp (F : Type u) [Field F] :
+ (IsVP : Family F (fun n => Fin n × Bool) → Prop) ≠ IsVNP :=
+ vp_ne_vnp_of_uniform_P separation_lower_bound F
+
+/-- Corollary 1.2 for directed Hamiltonian cycles and for the permanent outside characteristic two. -/
+theorem corollary12 (q C : ℕ) :
+ ∃ N, ∀ m ≥ N, ∀ (F : Type u) [Field F] [CharP F q],
+ m ^ C < circuitSize (hamiltonianCyclePolynomial F m) ∧
+ (q ≠ 2 → m ^ C < circuitSize (permanentPolynomial F m)) :=
+ corollary12_of_uniform_P separation_lower_bound q C
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SeparationConsequences.lean b/lean/OAI/Computability/VPVNP/SeparationConsequences.lean
new file mode 100644
index 0000000000..e4ab27202b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SeparationConsequences.lean
@@ -0,0 +1,90 @@
+import OAI.Computability.VPVNP.CharacteristicThreshold
+import OAI.Computability.VPVNP.VerifierFamily
+
+/-!
+# Quantifiers and consequences of the circuit lower bound
+
+Theorem 1.1 uses one threshold for all fields of a fixed characteristic. In
+§15.1 the projection and padding argument takes place over an algebraically
+closed representative of the characteristic, so the threshold for each matrix
+family can also be chosen before the field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial
+
+universe u
+
+/-- The circuit bound in Theorem 1.1 for the paper's explicit integer family. -/
+def UniformPBound : Prop :=
+ ∀ C : ℕ, 1 ≤ C → ∀ q : ℕ, ∃ N, ∀ n ≥ N, ∀ (F : Type u) [Field F] [CharP F q],
+ n ^ C < circuitSize (map (Int.castRingHom F) (P n))
+
+/-- It suffices to rule out arbitrarily large exceptional lengths in one
+countable algebraic closure per characteristic. -/
+theorem uniform_P_bound_of_countable_contradiction
+ (h : ∀ q : ℕ, q.Prime ∨ q = 0 →
+ ∃ (K : Type) (_ : Field K) (_ : IsAlgClosed K) (_ : Countable K) (_ : CharP K q),
+ ∀ C : ℕ, 1 ≤ C → ¬ ∀ N, ∃ n ≥ N,
+ circuitSize (map (Int.castRingHom K) (P n)) ≤ n ^ C) : UniformPBound.{u} := by
+ intro C hC q
+ by_cases hq : q.Prime ∨ q = 0
+ · obtain ⟨K, iK, closed, _, ch, hn⟩ := h q hq
+ specialize hn C hC
+ push Not at hn
+ obtain ⟨N, hN⟩ := hn
+ exact ⟨N, circuitSize_intCast_uniform_bound (K := K) P q C N hN⟩
+ · exact ⟨0, fun _ _ F _ _ => False.elim (hq (CharP.char_is_prime_or_zero F q))⟩
+
+/-- Form of the reduction for a diagonal contradiction that works in every
+countable algebraically closed field. -/
+theorem uniform_P_bound_of_diagonal_contradiction
+ (h : ∀ (C : ℕ), 1 ≤ C → ∀ (q : ℕ) (K : Type) [Field K] [IsAlgClosed K]
+ [Countable K] [CharP K q],
+ (∀ N, ∃ n ≥ N, circuitSize (map (Int.castRingHom K) (P n)) ≤ n ^ C) → False) :
+ UniformPBound.{u} := by
+ intro C hC q
+ by_contra bad
+ obtain ⟨K, iK, closed, count, ch, hsmall⟩ := unbounded_small_of_failure_of_uniform_bound P q C bad
+ exact h C hC q K hsmall
+
+/-- Specialize the common threshold to the characteristic of a single field. -/
+theorem eventual_P_bound_of_uniform_P (h : UniformPBound.{u}) (F : Type u) [Field F] :
+ EventuallySuperpolynomial fun n => circuitSize (map (Int.castRingHom F) (P n)) := by
+ intro C hC
+ obtain ⟨N, hN⟩ := h C hC (ringChar F)
+ exact ⟨N, fun n hn => hN n hn F⟩
+
+/-- The explicit complete family witnesses the distinction between the two
+class predicates, already on families in the prescribed paired variables. -/
+theorem vp_ne_vnp_of_uniform_P (h : UniformPBound.{u}) (F : Type u) [Field F] :
+ (IsVP : Family F (fun n => Fin n × Bool) → Prop) ≠ IsVNP := by
+ intro he
+ apply not_isVP_of_eventual_size (eventual_P_bound_of_uniform_P h F)
+ rw [he]
+ exact P_isVNP F
+
+/-- Corollary 1.2. The common threshold covers both matrix families in
+characteristic different from two and covers directed Hamiltonian cycles in
+characteristic two. The exponent zero is allowed as well. -/
+theorem corollary12_of_uniform_P (h : UniformPBound.{0}) (q C : ℕ) :
+ ∃ N, ∀ m ≥ N, ∀ (F : Type u) [Field F] [CharP F q],
+ m ^ C < circuitSize (hamiltonianCyclePolynomial F m) ∧
+ (q ≠ 2 → m ^ C < circuitSize (permanentPolynomial F m)) := by
+ by_cases hq : q.Prime ∨ q = 0
+ · obtain ⟨K, iK, closed, _, ch⟩ := exists_countable_algClosed_of_characteristic hq
+ have hp := eventual_P_bound_of_uniform_P h K
+ obtain ⟨N, hN⟩ := hamiltonian_uniform_of_P q hp C
+ by_cases htwo : q = 2
+ · exact ⟨N, fun m hm F _ _ => ⟨hN m hm F, fun hne => (hne htwo).elim⟩⟩
+ · obtain ⟨M, hM⟩ := permanent_uniform_of_P q htwo hp C
+ exact ⟨max N M, fun m hm F _ _ =>
+ ⟨hN m ((le_max_left ..).trans hm) F, fun _ => hM m ((le_max_right ..).trans hm) F⟩⟩
+ · exact ⟨0, fun _ _ F _ _ => False.elim (hq (CharP.char_is_prime_or_zero F q))⟩
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SharpPowerLengths.lean b/lean/OAI/Computability/VPVNP/SharpPowerLengths.lean
new file mode 100644
index 0000000000..8d440aeffc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SharpPowerLengths.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.TensorPowerLengths
+import Mathlib.Data.Nat.Find
+
+/-! # Selecting a tensor power with polynomial overhead in its length
+
+For a projection requiring `A (h+1)^D B^h` input bits, choose the largest power
+which fits at an available small-circuit length. The next power's requirement is
+an upper bound on that length. Its polynomial factor stays separate from `B^h`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+/-- At a length admitting the requested starting index, select a maximal fitting
+index and compare with its successor. -/
+private theorem exists_last_fitting_index (length : ℕ → ℕ) (growth : ∀ h, h < length h)
+ {H n : ℕ} (fits : length H ≤ n) :
+ ∃ h ≥ H, length h ≤ n ∧ n < length (h + 1) := by
+ let h := Nat.findGreatest (fun t => length t ≤ n) n
+ have hH : H ≤ n := (growth H).le.trans fits
+ have hin : length h ≤ n := Nat.findGreatest_spec (P := fun t => length t ≤ n) hH fits
+ have hnext : h + 1 ≤ n := (growth h).trans_le hin
+ exact ⟨h, Nat.le_findGreatest hH fits, hin,
+ lt_of_not_ge (Nat.findGreatest_is_greatest (P := fun t => length t ≤ n) (Nat.lt_succ_self h) hnext)⟩
+
+/-- Unboundedly many small circuits for `P` give arbitrarily high powers with the
+same exponential rate in their circuit-size bound. -/
+theorem arbitrarily_large_powers_of_sharp_projections {F : Type*} [CommRing F]
+ {V : ℕ → Type*} (forms : (h : ℕ) → MvPolynomial (V h) F)
+ {A B C D : ℕ} (hA : 0 < A) (hB : 1 < B)
+ (projections : ∀ h n, A * (h + 1)^D * B^h ≤ n →
+ ∃ φ : Projection F (Fin n × Bool) (V h),
+ φ.hom (MvPolynomial.map (Int.castRingHom F) (P n)) = forms h)
+ (small : ∀ N, ∃ n ≥ N, circuitSize (MvPolynomial.map (Int.castRingHom F) (P n)) ≤ n^C) :
+ ∀ H, ∃ h ≥ H, circuitSize (forms h) ≤ (A * B)^C * (h + 2)^(D*C) * (B^h)^C := by
+ let length (h : ℕ) := A * (h + 1)^D * B^h
+ have growth (h : ℕ) : h < length h := by
+ apply (Nat.lt_pow_self hB : h < B^h).trans_le
+ exact Nat.le_mul_of_pos_left _ (Nat.mul_pos hA (Nat.pow_pos (Nat.succ_pos _)))
+ intro H
+ obtain ⟨n, hn, hs⟩ := small (length H)
+ obtain ⟨h, hH, hlow, hhigh⟩ := exists_last_fitting_index length growth hn
+ obtain ⟨φ, hφ⟩ := projections h n hlow
+ refine ⟨h, hH, ?_⟩
+ calc
+ circuitSize (forms h) ≤ circuitSize (MvPolynomial.map (Int.castRingHom F) (P n)) :=
+ hφ ▸ circuitSize_projection_le φ _
+ _ ≤ n^C := hs
+ _ ≤ (length (h + 1))^C := Nat.pow_le_pow_left hhigh.le C
+ _ = _ := by
+ change (A * (h + 2)^D * B^(h + 1))^C = _
+ rw [pow_succ B h]
+ simp only [mul_pow, pow_mul]
+ ring
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SharpPowerObstruction.lean b/lean/OAI/Computability/VPVNP/SharpPowerObstruction.lean
new file mode 100644
index 0000000000..1af5d155dd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SharpPowerObstruction.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.BalancedPowerObstruction
+import OAI.Computability.VPVNP.SharpPowerLengths
+import OAI.Computability.VPVNP.PolynomialPowerGap
+
+/-!
+# Balanced layout comparison with polynomial overhead in the power
+
+An encoding of length `A * (h+1)^D * q^h` gives the central wire exponent `C`
+when the source circuit budget is `n^C`. The polynomial in `h` can be retained
+as a common factor in the finite sum, since each bridge distance is at most one.
+The strict layout gap absorbs this factor at all sufficiently large powers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial WireTensor Filter
+
+private theorem bridge_overhead_le (ℓ K m : ℕ) (hm : 1 ≤ m) {d : ℝ}
+ (h₀ : 0 ≤ d) (h₁ : d ≤ 1) :
+ ((ℓ * (ℓ + K * m + 1) : ℕ) : ℝ)^d ≤
+ (m : ℝ) * ((ℓ * (ℓ + K + 1) : ℕ) : ℝ)^d := by
+ have hnat : ℓ * (ℓ + K*m + 1) ≤ (ℓ*(ℓ+K+1))*m := by
+ rw [mul_assoc, add_mul, add_mul, one_mul]
+ exact Nat.mul_le_mul_left ℓ (Nat.add_le_add
+ (Nat.add_le_add_right (Nat.le_mul_of_pos_right _ (by omega)) _) hm)
+ calc
+ _ ≤ ((((ℓ*(ℓ+K+1))*m : ℕ) : ℝ))^d := Real.rpow_le_rpow (Nat.cast_nonneg _)
+ (by exact_mod_cast hnat) h₀
+ _ = ((ℓ * (ℓ + K + 1) : ℕ) : ℝ)^d * (m : ℝ)^d := by
+ rw [Nat.cast_mul, Real.mul_rpow (Nat.cast_nonneg _) (Nat.cast_nonneg _)]
+ _ ≤ _ := by
+ rw [mul_comm (m : ℝ)]
+ apply mul_le_mul_of_nonneg_left (Real.rpow_le_self_of_one_le (by exact_mod_cast hm) h₁)
+ positivity
+
+variable {k : Type*} [Field k] {I J : Type} {P : Type*}
+ [Fintype I] [DecidableEq I] [Fintype J] [Fintype P]
+
+/-- The source budget exponent enters the layout cost unchanged when the
+projection length is linear in the terminal dimension up to polynomial factors in
+the power `h`. -/
+theorem not_small_universal_of_sharp_projections (F : SpectralPoint k P)
+ (place : I → P) (centers : Finset I → Bool → P) (A : (I → J) → k)
+ (forms : (h : ℕ) → MvPolynomial (I × (Fin h → J)) k) (M D C : ℕ)
+ (hM : 0 < M) (hC : 0 < C) (hI : 3 ≤ Fintype.card I) (hJ : 1 < Fintype.card J)
+ (coeffs : ∀ h a, (forms h).coeff (partyExponent Finset.univ a) =
+ ∏ t : Fin h, A (fun i ↦ a i t))
+ (project : ∀ h n, M * (h+1)^D * Fintype.card J^h ≤ n →
+ ∃ φ : Projection k (Fin n × Bool) (I × (Fin h → J)),
+ φ.hom (map (Int.castRingHom k) (VPVNP.P n)) = forms h)
+ (hA : 0 < (F.value (placedTensor place (fun _ ↦ J) A) : ℝ))
+ (hgap : ∀ S : Finset I, Fintype.card I ≤ 3*S.card → 3*S.card ≤ 2*Fintype.card I →
+ (Fintype.card J : ℝ) ^
+ ((C : ℝ) * F.wireDistance (centers S false) (centers S true) +
+ ∑ i, F.wireDistance (place i) (centers S (cutSide S i))) <
+ (F.value (placedTensor place (fun _ ↦ J) A) : ℝ)) :
+ ¬ ∀ N, ∃ n ≥ N, circuitSize (map (Int.castRingHom k) (VPVNP.P n)) ≤ n^C := by
+ classical
+ intro small
+ let cuts := Finset.univ.filter
+ (fun S : Finset I ↦ Fintype.card I ≤ 3*S.card ∧ 3*S.card ≤ 2*Fintype.card I)
+ let bridge (S : Finset I) := F.wireDistance (centers S false) (centers S true)
+ let outer (S : Finset I) := ∑ i, F.wireDistance (place i) (centers S (cutSide S i))
+ let base (S : Finset I) := (Fintype.card J : ℝ) ^ ((C : ℝ) * bridge S + outer S)
+ let K := (M*Fintype.card J)^C
+ let ℓ := Fintype.card I
+ let weight (S : Finset I) := ((ℓ*(ℓ+K+1) : ℕ) : ℝ) ^ bridge S
+ let v := (F.value (placedTensor place (fun _ ↦ J) A) : ℝ)
+ have hw (S : Finset I) (_ : S ∈ cuts) : 0 ≤ weight S :=
+ Real.rpow_nonneg (Nat.cast_nonneg _) _
+ have hb (S : Finset I) (hS : S ∈ cuts) : 0 ≤ base S ∧ base S < v := by
+ obtain ⟨lo, hi⟩ := (Finset.mem_filter.mp hS).2
+ exact ⟨Real.rpow_nonneg (Nat.cast_nonneg _) _, hgap S lo hi⟩
+ obtain ⟨N, hN⟩ := eventually_atTop.mp
+ (eventually_polynomial_weighted_pow_lt_target cuts weight base v (D*C) hA hw hb)
+ obtain ⟨h, hn, hs⟩ := arbitrarily_large_powers_of_sharp_projections forms hM hJ project small N
+ obtain ⟨c, hc⟩ := circuitSize_spec (forms h)
+ have bound := spectral_power_bound F place centers A hC hI (by omega) hs c
+ (fun a ↦ by rw [hc]; exact coeffs h a)
+ apply (not_lt_of_ge (bound.trans ?_)) (hN h hn)
+ rw [Finset.mul_sum]
+ apply Finset.sum_le_sum
+ intro S _
+ let m := (h+2)^(D*C)
+ have hm : 1 ≤ m := by exact Nat.pow_pos (by omega)
+ have hbridge := bridge_overhead_le ℓ K m hm
+ (F.wireDistance_nonneg (centers S false) (centers S true))
+ (F.wireDistance_le_one (centers S false) (centers S true))
+ have castm : (m : ℝ) = ((h : ℝ)+2)^(D*C) := by simp [m]
+ rw [castm] at hbridge
+ simpa only [mul_assoc] using mul_le_mul_of_nonneg_right hbridge
+ (pow_nonneg (Real.rpow_nonneg (Nat.cast_nonneg (Fintype.card J))
+ ((C : ℝ)*bridge S + outer S)) h)
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SharpTensorLayout.lean b/lean/OAI/Computability/VPVNP/SharpTensorLayout.lean
new file mode 100644
index 0000000000..0e0d66670d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SharpTensorLayout.lean
@@ -0,0 +1,48 @@
+import OAI.Computability.VPVNP.SharpPowerObstruction
+import OAI.Computability.VPVNP.TensorPowerLayout
+
+/-!
+# Cube-witness comparison at the original circuit exponent
+
+For a tensor form admitting an encoding linear in its local dimension up to a
+polynomial in the tensor power, the central wire in (4.5) costs the original
+circuit exponent `C` times the centroid distance.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial WireTensor TensorPowerCNF
+
+variable {k : Type*} [Field k] {I : Type} [Fintype I] [DecidableEq I]
+ {P : Type*} [Fintype P] [Nonempty P]
+
+/-- A literal projection with length `M * (h + 1)^D * (2^b)^h` supplies the exact
+layout comparison from the paper, without multiplying the exponent `C`. -/
+theorem not_small_universal_of_sharp_tensor_layout (F : SpectralPoint k P)
+ (place : I → P) (centers : Finset I → Bool → P) {b C : ℕ} (hb : 0 < b) (hC : 0 < C)
+ (hI : 3 ≤ Fintype.card I) (A : (I → Fin (2^b)) → k) (hnz : A ≠ 0)
+ {scale threshold : ℝ} (hs : 0 < scale)
+ (hlower : threshold <
+ Real.logb 2 (F.value (placedTensor place (fun _ ↦ Fin (2^b)) A)) / (scale * b))
+ (hcost : ∀ S : Finset I, Fintype.card I ≤ 3*S.card → 3*S.card ≤ 2*Fintype.card I →
+ (C : ℝ) * F.wireDistance (centers S false) (centers S true) +
+ ∑ i, F.wireDistance (place i) (centers S (cutSide S i)) ≤ scale * threshold)
+ (hproject : ∀ T : (I → Digit b) → k, ∃ M D : ℕ, 0 < M ∧ ∀ h n,
+ M * (h+1)^D * (2^b)^h ≤ n →
+ ∃ φ : Projection k (Fin n × Bool) (I × Word b h),
+ φ.hom (map (Int.castRingHom k) (VPVNP.P n)) = form T h) :
+ ¬ ∀ N, ∃ n ≥ N, circuitSize (map (Int.castRingHom k) (VPVNP.P n)) ≤ n^C := by
+ classical
+ obtain ⟨A', hv, hgap⟩ := exists_digit_layout_witness F place centers hb A hnz hs hlower hcost
+ obtain ⟨M, D, hM, hproj⟩ := hproject A'
+ have hcard : Fintype.card (Digit b) = 2 ^ b := by simp [Digit]
+ exact not_small_universal_of_sharp_projections F place centers A' (form A') M D C
+ hM hC hI (hcard ▸ one_lt_pow₀ (by decide : 1 < (2 : ℕ)) hb.ne')
+ (fun _ a ↦ coeff_form A' a) (fun h n hn ↦ hproj h n (by simpa only [hcard] using hn))
+ hv hgap
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShiftedBlockCuts.lean b/lean/OAI/Computability/VPVNP/ShiftedBlockCuts.lean
new file mode 100644
index 0000000000..b270af8f4a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShiftedBlockCuts.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.ShiftedModeIdentity
+import OAI.Computability.VPVNP.ShiftedFactorization
+
+/-!
+# From shifted Fock modes to the two crossing factorizations
+
+The tensor in a fixed source block is its integral vacuum pairing times the
+Kronecker delta on the exterior-state indices. Its two summands factor through
+energy cutoffs differing by twice the coefficient shift in doubled-energy units.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open scoped BigOperators
+
+variable {S I J : Type*} [Fintype S]
+
+/-- An integral four-index tensor written as the sum of two cut factorizations,
+with the source block's binomial index included in each coordinate set. -/
+def ShiftedBlockCuts (energy : S → ℤ) (H E s : ℤ) (d : ℕ)
+ (C : I → J → ℤ) [DecidableEq S] : Prop :=
+ ∃ (p : Fin (d + 1) × Cutoff energy (E + H + 2 * s) → I → Cutoff energy E → ℤ)
+ (q : Fin (d + 1) × Cutoff energy (E + H + 2 * s) → J → Cutoff energy E → ℤ)
+ (r : Fin (d + 1) × Cutoff energy (E + H - 2 * s) → I → Cutoff energy E → ℤ)
+ (t : Fin (d + 1) × Cutoff energy (E + H - 2 * s) → J → Cutoff energy E → ℤ),
+ ∀ i j (out input : Cutoff energy E),
+ C i j * (if out = input then 1 else 0) =
+ (∑ v, p v i out * q v j input) + ∑ v, r v i input * t v j out
+
+omit [Fintype S] in
+/-- A matrix entry in its energy-difference diagonal has exactly the specified
+change of energy, including for negative shifts. -/
+private theorem homogeneous_energyMode (energy : S → ℤ) (A : Matrix S S ℤ) (h : ℤ) :
+ ModeHomogeneous energy h (fun b => energyMode energy A (2 * b + h)) := by
+ intro b out input hn
+ by_cases he : energy out - energy input = 2 * b + h
+ · omega
+ · exact (hn (by simp [energyMode, he])).elim
+
+/-- Apply the two finite cut bounds to an energy-mode residue identity. -/
+theorem shiftedBlockCuts_of_modes [DecidableEq S] (energy : S → ℤ)
+ (h h' H E s : ℤ) (m d : ℕ) (hdeg : 2 * (d : ℤ) + 2 = h + h')
+ (hh : h ≤ H) (hh' : h' ≤ H) (X : I → Matrix S S ℤ)
+ (Y : J → Matrix S S ℤ) (C : I → J → ℤ)
+ (hres : ∀ i j (out input : Cutoff energy E),
+ (∑ a : Fin (d + 1), multiplier d a.val *
+ (let q := 2 * s + h' - 2 * (a : ℕ)
+ (energyMode energy (X i) (-q) * energyMode energy (Y j) q) out.val input.val -
+ (-1 : ℤ) ^ (m * m) *
+ (energyMode energy (Y j) q * energyMode energy (X i) (-q)) out.val input.val)) =
+ C i j * (if out = input then 1 else 0)) :
+ ShiftedBlockCuts energy H E s d C := by
+ obtain ⟨p, q, r, t, hf⟩ := shiftedBlockFactorization energy h h' H E s m d
+ (by omega) hh hh' (fun i b => energyMode energy (X i) (2 * b + h))
+ (fun j b => energyMode energy (Y j) (2 * b + h'))
+ (fun i => homogeneous_energyMode _ _ _) (fun j => homogeneous_energyMode _ _ _)
+ refine ⟨p, q, r, t, ?_⟩
+ intro i j out input
+ rw [← hf i j out input, ← hres i j out input]
+ apply Finset.sum_congr rfl
+ intro a _
+ dsimp only
+ have hfirst : 2 * firstExponent d s a + h = -(2 * s + h' - 2 * (a : ℕ)) := by
+ unfold firstExponent
+ omega
+ have hsecond : 2 * secondExponent s a + h' = 2 * s + h' - 2 * (a : ℕ) := by
+ unfold secondExponent
+ omega
+ rw [hfirst, hsecond]
+
+open Lemmata.FockCircuits.FiniteIdentity
+
+/-- The integral block tensor from the finite exterior-algebra operators in Appendix B.
+All terminal states in the energy cutoff are included. -/
+theorem fock_block_cuts (L K H E h h' m d : ℕ) (s : ℤ)
+ (A : I → Index L) (B : J → Index L)
+ (hA : ∀ i, Lemmata.FockCircuits.doubledEnergy (A i).val = h)
+ (hB : ∀ j, Lemmata.FockCircuits.doubledEnergy (B j).val = h')
+ (hcA : ∀ i, (A i).val.card = m) (hcB : ∀ j, (B j).val.card = m)
+ (hd : 2 * d + 2 = h + h') (hh : h ≤ H) (hh' : h' ≤ H)
+ (hcut : E + K + H + 4 ≤ 2 * L) (hs : |2 * (-s - 1)| ≤ K) :
+ ShiftedBlockCuts (fun x : Index L => (Lemmata.FockCircuits.doubledEnergy x.val : ℤ))
+ H E s d (fun i j => matrix ℤ L (Pi.single (A i) 1) ⟨∅, by simp⟩ (B j)) := by
+ let energy : Index L → ℤ := fun x => Lemmata.FockCircuits.doubledEnergy x.val
+ apply shiftedBlockCuts_of_modes energy h h' H E s m d (by omega) (by omega) (by omega)
+ (fun i => matrix ℤ L (Pi.single (A i) 1)) (fun j => matrix ℤ L (Pi.single (B j) 1))
+ intro i j out input
+ have hin : Lemmata.FockCircuits.doubledEnergy input.val.val ≤ E := by
+ have he : (Lemmata.FockCircuits.doubledEnergy input.val.val : ℤ) ≤ E := input.property
+ exact_mod_cast he
+ have hres := shifted_operator_identity ℤ L K (A i) (B j) out.val input.val d s
+ (by simpa only [sourceEnergy_sort, hA, hB] using hd)
+ (by simp only [sourceEnergy_sort, hA, hB]; omega)
+ (by rwa [show -2 * s - 2 = 2 * (-s - 1) by ring])
+ have hdiag (U : Index L) (b : ℤ) : diagonal ℤ L b (Pi.single U 1) =
+ energyMode energy (matrix ℤ L (Pi.single U 1)) b := rfl
+ rw [mul_comm (matrix _ _ _ _ _)]
+ simpa only [Finset.length_sort, hcA, hcB, hB, multiplier, hdiag, Subtype.val_inj] using hres
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShiftedBlocks.lean b/lean/OAI/Computability/VPVNP/ShiftedBlocks.lean
new file mode 100644
index 0000000000..7c9a3bae29
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShiftedBlocks.lean
@@ -0,0 +1,203 @@
+import OAI.Computability.VPVNP.VacuumPairing
+import OAI.Computability.VPVNP.ShiftedBlockCuts
+
+/-!
+# Assembly of the shifted crossing blocks
+
+Appendix B indexes a block by the particle number and the two doubled source
+energies. We extend both factors of each cut by zero at incompatible source
+indices, concatenate their intermediate coordinates, and remove the integral
+pairing by its inverse. Each cut retains its own set of intermediate states.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open scoped BigOperators
+
+/-- The nonempty source states of doubled energy at most `H`. -/
+abbrev CrossingState (n H : ℕ) := Σ m : Fin n, EnergySector n (m.val + 1) H
+
+/-- The first coordinate is the particle number minus one. The other coordinates
+are the doubled energies of the two operator indices. -/
+abbrev CrossingBlock (n H : ℕ) := Fin n × Fin (H + 1) × Fin (H + 1)
+
+/-- The doubled energy of a crossing source state, viewed as a grade between zero and the
+cutoff. -/
+def sourceGrade {n H : ℕ} (i : CrossingState n H) : Fin (H + 1) :=
+ ⟨doubledSectorEnergy i.2.val, Nat.lt_succ_of_le i.2.property⟩
+
+/-- The exponent of the multiplier `(z - w)^L` for this block. For an inhabited block it is the
+sum of the two source energies minus one. -/
+def blockPoleDegree {n H : ℕ} (t : CrossingBlock n H) : ℕ :=
+ (t.2.1.val + t.2.2.val) / 2 - 1
+
+/-- A source state belongs to the row block when its particle number and doubled energy agree
+with the first source index of the block. -/
+def isBlockRow {n H : ℕ} (t : CrossingBlock n H) (i : CrossingState n H) : Prop :=
+ (t.1, t.2.1) = (i.1, sourceGrade i)
+
+/-- A source state belongs to the column block when its particle number and doubled energy
+agree with the second source index of the block. -/
+def isBlockColumn {n H : ℕ} (t : CrossingBlock n H) (i : CrossingState n H) : Prop :=
+ (t.1, t.2.2) = (i.1, sourceGrade i)
+
+/-- The source states with the particle number and row energy specified by the crossing block. -/
+abbrev BlockRows {n H : ℕ} (t : CrossingBlock n H) := {i // isBlockRow t i}
+/-- The source states with the particle number and column energy specified by the crossing
+block. -/
+abbrev BlockColumns {n H : ℕ} (t : CrossingBlock n H) := {j // isBlockColumn t j}
+
+/-- Each intermediate coordinate retains its block and its binomial index. -/
+abbrev BlockCoordinates (n H : ℕ) (M : Type*) :=
+ Σ t : CrossingBlock n H, Fin (blockPoleDegree t + 1) × M
+
+theorem blockCoordinates_card_le (n H : ℕ) (M : Type*) [Fintype M] :
+ Fintype.card (BlockCoordinates n H M) ≤ n * (H + 1)^3 * Fintype.card M := by
+ rw [Fintype.card_sigma]
+ calc
+ _ ≤ ∑ _ : CrossingBlock n H, (H + 1) * Fintype.card M := by
+ apply Finset.sum_le_sum
+ intro t _
+ rw [Fintype.card_prod, Fintype.card_fin]
+ apply Nat.mul_le_mul_right
+ have := t.2.1.isLt
+ have := t.2.2.isLt
+ unfold blockPoleDegree
+ omega
+ _ = _ := by simp [CrossingBlock]; ring
+
+/-- The local decomposition on the block tagged by `t`. It uses the two opposite
+orders of the input and output state, with the binomial index ranging to its
+actual pole degree. -/
+def BlockDecomposition {n H : ℕ} (t : CrossingBlock n H)
+ (Y K L : Type*) [Fintype K] [Fintype L] [DecidableEq Y] : Prop :=
+ ∃ (a : Fin (blockPoleDegree t + 1) × K → BlockRows t → Y → ℤ)
+ (b : Fin (blockPoleDegree t + 1) × K → BlockColumns t → Y → ℤ)
+ (c : Fin (blockPoleDegree t + 1) × L → BlockRows t → Y → ℤ)
+ (d : Fin (blockPoleDegree t + 1) × L → BlockColumns t → Y → ℤ),
+ ∀ i j α β, ∑ k, a k i α * b k j β + ∑ l, c l i β * d l j α =
+ crossingPairing n H i.val j.val * (if α = β then 1 else 0)
+
+private noncomputable def extendByZero {X Y : Type*} {p : X → Prop}
+ (f : {x // p x} → Y → ℤ) (x : X) (y : Y) : ℤ := by
+ classical
+ exact if h : p x then f ⟨x, h⟩ y else 0
+
+/-- Concatenate the local factorizations and apply the inverse of the signed
+integral pairing. The first summand factors on `(i, α) | (j, β)` and the second
+on `(i, β) | (j, α)`. -/
+theorem assembleCrossingBlocks (n H : ℕ) (Y K L : Type*)
+ [Fintype K] [Fintype L] [DecidableEq Y]
+ (blocks : ∀ t : CrossingBlock n H, BlockDecomposition t Y K L) :
+ ∃ (a b : BlockCoordinates n H K → CrossingState n H → Y → ℤ)
+ (c d : BlockCoordinates n H L → CrossingState n H → Y → ℤ),
+ ∀ i j α β, ∑ k, a k i α * b k j β + ∑ l, c l i β * d l j α =
+ (if i = j then 1 else 0) * (if α = β then 1 else 0) := by
+ classical
+ unfold BlockDecomposition at blocks
+ choose a b c d hblock using blocks
+ let a' (v : BlockCoordinates n H K) := extendByZero (a v.1 v.2)
+ let b' (v : BlockCoordinates n H K) := extendByZero (b v.1 v.2)
+ let c' (v : BlockCoordinates n H L) := extendByZero (c v.1 v.2)
+ let d' (v : BlockCoordinates n H L) := extendByZero (d v.1 v.2)
+ suffices h : ∀ i j α β, ∑ k, a' k i α * b' k j β + ∑ l, c' l i β * d' l j α =
+ crossingPairing n H i j * (if α = β then 1 else 0) by
+ obtain ⟨a'', c'', h'⟩ :=
+ normalizeCrossing a' b' c' d' _ (crossingPairing_isUnit n H) h
+ exact ⟨a'', b', c'', d', h'⟩
+ intro i j α β
+ rw [Fintype.sum_sigma, Fintype.sum_sigma, ← Finset.sum_add_distrib]
+ let t₀ : CrossingBlock n H := (i.1, sourceGrade i, sourceGrade j)
+ have off (t : CrossingBlock n H) (h : t ≠ t₀ ∨ i.1 ≠ j.1) :
+ ¬(isBlockRow t i ∧ isBlockColumn t j) := by
+ rintro ⟨hr, hc⟩
+ obtain ⟨hm, he⟩ := Prod.mk.inj hr
+ obtain ⟨hm', he'⟩ := Prod.mk.inj hc
+ have ht : t = t₀ := Prod.ext hm (Prod.ext he he')
+ exact h.elim (· ht) (· (hm.symm.trans hm'))
+ have zero (t : CrossingBlock n H) (ht : ¬(isBlockRow t i ∧ isBlockColumn t j)) :
+ ∑ k, a' ⟨t, k⟩ i α * b' ⟨t, k⟩ j β +
+ ∑ l, c' ⟨t, l⟩ i β * d' ⟨t, l⟩ j α = 0 := by
+ by_cases hr : isBlockRow t i
+ · have hc : ¬isBlockColumn t j := fun hc => ht ⟨hr, hc⟩
+ simp [b', d', extendByZero, hc]
+ · simp [a', c', extendByZero, hr]
+ by_cases hij : i.1 = j.1
+ · rw [Finset.sum_eq_single t₀]
+ · have hr : isBlockRow t₀ i := rfl
+ have hc : isBlockColumn t₀ j := Prod.ext hij rfl
+ simpa only [a', b', c', d', extendByZero, dite_eq_left hr, dite_eq_left hc] using
+ hblock t₀ ⟨i, hr⟩ ⟨j, hc⟩ α β
+ · intro t _ ht
+ exact zero t (off t (.inl ht))
+ · simp
+ · rw [Finset.sum_eq_zero (fun t _ => zero t (off t (.inr hij)))]
+ rcases i with ⟨mi, i⟩
+ rcases j with ⟨mj, j⟩
+ rw [crossingPairing, Matrix.blockDiagonal'_apply_ne _ _ _ hij, zero_mul]
+
+
+open Lemmata.FockCircuits.FiniteIdentity
+
+/-- Finite-mode states of doubled energy at most `B`. -/
+abbrev CrossingCutoff (N : ℕ) (B : ℤ) :=
+ Cutoff (fun i : Index N => (Lemmata.FockCircuits.doubledEnergy i.val : ℤ)) B
+
+private theorem degree_of_inhabited_block {n H : ℕ} {t : CrossingBlock n H}
+ (i : BlockRows t) (j : BlockColumns t) :
+ 2 * blockPoleDegree t + 2 = t.2.1.val + t.2.2.val := by
+ have hi := Prod.mk.inj i.property
+ have hj := Prod.mk.inj j.property
+ have he : t.2.1.val = doubledSectorEnergy i.val.2.val := congrArg Fin.val hi.2
+ have he' : t.2.2.val = doubledSectorEnergy j.val.2.val := congrArg Fin.val hj.2
+ have hm := congrArg Fin.val (hi.1.symm.trans hj.1)
+ rw [blockPoleDegree, he, he', doubledSectorEnergy_eq, doubledSectorEnergy_eq]
+ omega
+
+/-- Integral crossing at a fixed energy cutoff and shift. The finite-mode
+window contains the coefficient of both products, and the sizes of the two
+intermediate spaces retain the signs of the shift. -/
+theorem finiteShiftedCrossing (N B H E : ℕ) (s : ℤ)
+ (hHN : H ≤ N) (hcut : E + B + H + 4 ≤ 2 * N)
+ (hs : |2 * (-s - 1)| ≤ (B : ℤ)) :
+ ∃ (a b : BlockCoordinates H H (CrossingCutoff N ((E : ℤ) + H + 2*s)) →
+ CrossingState H H → CrossingCutoff N E → ℤ)
+ (c d : BlockCoordinates H H (CrossingCutoff N ((E : ℤ) + H - 2*s)) →
+ CrossingState H H → CrossingCutoff N E → ℤ),
+ ∀ i j α β, ∑ k, a k i α * b k j β + ∑ l, c l i β * d l j α =
+ (if i = j then 1 else 0) * (if α = β then 1 else 0) := by
+ apply assembleCrossingBlocks
+ intro t
+ classical
+ by_cases ht : Nonempty (BlockRows t × BlockColumns t)
+ · obtain ⟨⟨i₀, j₀⟩⟩ := ht
+ let A (i : BlockRows t) := sectorIndex hHN i.val.2.val
+ let C (j : BlockColumns t) := sectorIndex hHN j.val.2.val
+ have hA (i : BlockRows t) : Lemmata.FockCircuits.doubledEnergy (A i).val = t.2.1.val := by
+ simp only [A, sectorIndex_energy]
+ exact congrArg Fin.val (Prod.mk.inj i.property).2.symm
+ have hC (j : BlockColumns t) : Lemmata.FockCircuits.doubledEnergy (C j).val = t.2.2.val := by
+ simp only [C, sectorIndex_energy]
+ exact congrArg Fin.val (Prod.mk.inj j.property).2.symm
+ have hcA (i : BlockRows t) : (A i).val.card = t.1.val + 1 := by
+ simp only [A, sectorIndex_card, (Prod.mk.inj i.property).1]
+ have hcC (j : BlockColumns t) : (C j).val.card = t.1.val + 1 := by
+ simp only [C, sectorIndex_card, (Prod.mk.inj j.property).1]
+ obtain ⟨p, q, r, u, hf⟩ := fock_block_cuts N B H E t.2.1.val t.2.2.val
+ (t.1.val + 1) (blockPoleDegree t) s A C hA hC hcA hcC
+ (degree_of_inhabited_block i₀ j₀) (Nat.le_of_lt_succ t.2.1.isLt)
+ (Nat.le_of_lt_succ t.2.2.isLt) hcut hs
+ refine ⟨p, q, r, u, ?_⟩
+ intro i j α β
+ simpa only [A, C, vacuum_matrix_crossingPairing] using (hf i j α β).symm
+ · exact ⟨0, 0, 0, 0, fun i j => (ht ⟨(i, j)⟩).elim⟩
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShiftedCrossing.lean b/lean/OAI/Computability/VPVNP/ShiftedCrossing.lean
new file mode 100644
index 0000000000..656f8554df
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShiftedCrossing.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.ShiftedBlocks
+import OAI.Computability.VPVNP.CrossingCard
+import Mathlib.Data.Fintype.EquivFin
+
+/-!
+# Integral factorizations for the two-wire crossing tensor
+
+The wire labels are numbered from zero, and each of the two summands has its
+own number of factor coordinates. The four integer arrays can be reduced into
+any field without changing either cut.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open Filter
+open scoped BigOperators Topology
+
+/-- Two integral matrix factorizations, one on each of the two cuts of the
+product of the two identity wires. -/
+structure IntegralCrossing (x y plus minus : ℕ) where
+ /-- The integer factor indexed by the first operator index `i` and output state `α` on the
+ forward cut. -/
+ leftPlus : Fin plus → Fin x → Fin y → ℤ
+ /-- The integer factor indexed by the second operator index `j` and input state `β` on the
+ forward cut. -/
+ rightPlus : Fin plus → Fin x → Fin y → ℤ
+ /-- The integer factor indexed by the first operator index `i` and input state `β` on the
+ reversed cut. -/
+ leftMinus : Fin minus → Fin x → Fin y → ℤ
+ /-- The integer factor indexed by the second operator index `j` and output state `α` on the
+ reversed cut. -/
+ rightMinus : Fin minus → Fin x → Fin y → ℤ
+ identity : ∀ i j α β,
+ ∑ k, leftPlus k i α * rightPlus k j β + ∑ k, leftMinus k i β * rightMinus k j α =
+ (if i = j then 1 else 0) * (if α = β then 1 else 0)
+
+private noncomputable def padded {K X Y : Type*} [Fintype K] (r : ℕ)
+ (f : K → X → Y → ℤ) (k : Fin r) (x : X) (y : Y) : ℤ :=
+ if h : k.val < Fintype.card K then f ((Fintype.equivFin K).symm ⟨k.val, h⟩) x y else 0
+
+private theorem padded_contraction {K X Y : Type*} [Fintype K] {r : ℕ}
+ (hr : Fintype.card K ≤ r) (f g : K → X → Y → ℤ) (i j : X) (α β : Y) :
+ ∑ k, padded r f k i α * padded r g k j β = ∑ k, f k i α * g k j β := by
+ obtain ⟨d, rfl⟩ := Nat.exists_eq_add_of_le hr
+ rw [Fin.sum_trunc (hf := fun k => by simp [padded, Fin.natAdd])]
+ simpa [padded] using (Fintype.equivFin K).symm.sum_comp (fun k => f k i α * g k j β)
+
+/-- Convert the state and factor indices of an integral crossing to numbered
+wires, padding each cut independently to its prescribed bound. -/
+theorem integralCrossing_of_factors {X Y K L : Type*}
+ [Fintype X] [Fintype Y] [Fintype K] [Fintype L] [DecidableEq X] [DecidableEq Y]
+ {x y plus minus : ℕ} (hx : Fintype.card X = x) (hy : Fintype.card Y = y)
+ (hk : Fintype.card K ≤ plus) (hl : Fintype.card L ≤ minus)
+ (a b : K → X → Y → ℤ) (c d : L → X → Y → ℤ)
+ (h : ∀ i j α β, ∑ k, a k i α * b k j β + ∑ k, c k i β * d k j α =
+ (if i = j then 1 else 0) * (if α = β then 1 else 0)) :
+ Nonempty (IntegralCrossing x y plus minus) := by
+ let ex := (Fintype.equivFinOfCardEq hx).symm
+ let ey := (Fintype.equivFinOfCardEq hy).symm
+ refine ⟨⟨fun k i α => padded _ a k (ex i) (ey α),
+ fun k j β => padded _ b k (ex j) (ey β), fun k i β => padded _ c k (ex i) (ey β),
+ fun k j α => padded _ d k (ex j) (ey α), ?_⟩⟩
+ intro i j α β
+ rw [padded_contraction hk, padded_contraction hl, h]
+ simp
+
+/-- The same four integer factors give a decomposition of the two identity
+wires over every field with the indicated flattening rank bounds. The first
+tensor is flattened on `(i,α)|(j,β)` and the second on `(i,β)|(j,α)`. -/
+theorem IntegralCrossing.flatteningRanks {x y plus minus : ℕ}
+ (f : IntegralCrossing x y plus minus) (R : Type*) [Field R] :
+ ∃ P M : Matrix (Fin x × Fin y) (Fin x × Fin y) R,
+ P.rank ≤ plus ∧ M.rank ≤ minus ∧ ∀ i j α β,
+ P (i,α) (j,β) + M (i,β) (j,α) =
+ (if i = j then 1 else 0) * (if α = β then 1 else 0) := by
+ let P : Matrix (Fin x × Fin y) (Fin x × Fin y) R :=
+ fun a b => (↑(∑ k, f.leftPlus k a.1 a.2 * f.rightPlus k b.1 b.2) : R)
+ let M : Matrix (Fin x × Fin y) (Fin x × Fin y) R :=
+ fun a b => (↑(∑ k, f.leftMinus k a.1 a.2 * f.rightMinus k b.1 b.2) : R)
+ refine ⟨P, M, ?_, ?_, ?_⟩
+ · simpa only [Fintype.card_fin] using
+ factorization_rank (R := R) (fun k (p : Fin x × Fin y) => f.leftPlus k p.1 p.2)
+ (fun k (p : Fin x × Fin y) => f.rightPlus k p.1 p.2)
+ · simpa only [Fintype.card_fin] using
+ factorization_rank (R := R) (fun k (p : Fin x × Fin y) => f.leftMinus k p.1 p.2)
+ (fun k (p : Fin x × Fin y) => f.rightMinus k p.1 p.2)
+ · intro i j α β
+ dsimp only [P, M]
+ rw [← Int.cast_add, f.identity]
+ simp only [Int.cast_mul, apply_ite Int.cast, Int.cast_one, Int.cast_zero]
+
+
+/-- Finite, integer form of the shifted crossing in doubled energy units.
+The first wire omits the empty state, and the intermediate cutoffs differ by
+twice the Laurent coefficient shift. -/
+theorem integral_shifted_crossing (H E : ℕ) (s : ℤ) :
+ Nonempty (IntegralCrossing (cutoffCount H - 1) (cutoffCount E)
+ ((H+1)^4 * cutoffCount ((E : ℤ) + H + 2*s).toNat)
+ ((H+1)^4 * cutoffCount ((E : ℤ) + H - 2*s).toNat)) := by
+ let B := (2*(-s-1)).natAbs
+ let N := E + B + H + 4
+ have hs : |2*(-s-1)| ≤ (B : ℤ) := by simp [B]
+ obtain ⟨a, b, c, d, hid⟩ := finiteShiftedCrossing N B H E s (by dsimp [N]; omega)
+ (by dsimp [N]; omega) hs
+ have bound (v : ℤ) : Fintype.card (BlockCoordinates H H (CrossingCutoff N v)) ≤
+ (H+1)^4 * cutoffCount v.toNat := by
+ apply (blockCoordinates_card_le H H (CrossingCutoff N v)).trans
+ apply Nat.mul_le_mul _ (modeCutoff_card_le N v)
+ calc
+ H * (H+1)^3 ≤ (H+1) * (H+1)^3 := Nat.mul_le_mul_right _ (by omega)
+ _ = (H+1)^4 := by ring
+ exact integralCrossing_of_factors (crossingState_card H) (modeCutoff_card_eq N E (by dsimp [N]; omega))
+ (bound _) (bound _) a b c d hid
+
+/-- Theorem 3.1 of *VP and VNP differ over every field*. For two prescribed
+wire rates and one signed shift, the same integer tensors work over every field.
+The limits of the two factor bounds are distinct when the shift is nonzero.
+The ordinary flattening ranks follow from `IntegralCrossing.flatteningRanks`. -/
+theorem shiftedCrossing (t u δ : ℝ) (ht : 0 < t) (hu : 0 < u)
+ (hlo : -(t^2+u^2) < δ) (hhi : δ < t^2+u^2) :
+ ∃ x y plus minus : ℕ → ℕ,
+ Tendsto (fun n : ℕ => Real.logb 2 (x n) / n) atTop (𝓝 t) ∧
+ Tendsto (fun n : ℕ => Real.logb 2 (y n) / n) atTop (𝓝 u) ∧
+ Tendsto (fun n : ℕ => Real.logb 2 (plus n) / n) atTop (𝓝 (Real.sqrt (t^2+u^2+δ))) ∧
+ Tendsto (fun n : ℕ => Real.logb 2 (minus n) / n) atTop (𝓝 (Real.sqrt (t^2+u^2-δ))) ∧
+ ∀ n, Nonempty (IntegralCrossing (x n) (y n) (plus n) (minus n)) := by
+ obtain ⟨hx, hy, hr⟩ := shiftedCrossing_rates t u δ ht hu hlo hhi
+ refine ⟨_, _, crossingFactorBound t u δ true, crossingFactorBound t u δ false,
+ hx, hy, hr true, hr false, ?_⟩
+ intro n
+ simpa only [crossingFactorBound, Bool.false_eq_true, ↓reduceIte, add_comm
+ (crossingEnergy t n : ℤ) (crossingEnergy u n : ℤ)] using
+ integral_shifted_crossing (crossingEnergy t n) (crossingEnergy u n) (crossingShift δ n)
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShiftedFactorization.lean b/lean/OAI/Computability/VPVNP/ShiftedFactorization.lean
new file mode 100644
index 0000000000..5ee45eabc0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShiftedFactorization.lean
@@ -0,0 +1,335 @@
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Data.Matrix.Mul
+import Mathlib.Data.Nat.Choose.Sum
+import Mathlib.LinearAlgebra.Matrix.Rank
+
+/-!
+# The two energy cutoffs in the shifted crossing
+
+Appendix B of *VP and VNP differ over every field* extracts `[z^(-s-1) w^s]`
+from a product of two normally ordered fermionic fields times `(z-w)^L`.
+On the exterior basis of occupation states in the first `N` modes, the two orders
+of the product give different finite matrix factorizations over the integers.
+All energy variables are doubled to keep track of the half-integral mode energies.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open scoped BigOperators
+
+variable {N : ℕ}
+
+/-- An exterior basis state specified by the occupied modes among the first `N` modes. -/
+abbrev Occupation (N : ℕ) := Finset (Fin N)
+
+/-- Twice the energy of an occupation state, obtained by summing `2 * r + 1` over its occupied
+modes. -/
+def doubledEnergy (input : Occupation N) : ℤ := ∑ r ∈ input, (2 * (r.val : ℤ) + 1)
+
+/-- One creation or annihilation term in a divided derivative of a fermionic field on the first
+`N` modes. -/
+structure FieldTerm (N : ℕ) where
+ /-- The mode whose occupation is changed by this field term. -/
+ mode : Fin N
+ /-- Selects creation when true and annihilation when false. -/
+ create : Bool
+ /-- The order of the divided derivative applied to this field term. -/
+ derivative : ℕ
+
+namespace FieldTerm
+
+/-- Laurent exponent after the divided derivative. -/
+def exponent (f : FieldTerm N) : ℤ :=
+ (if f.create then (f.mode.val : ℤ) else -f.mode.val - 1) - f.derivative
+
+/-- The doubled source weight `2 * derivative + 1` contributed by this field term. -/
+def weight (f : FieldTerm N) : ℤ := 2 * (f.derivative : ℤ) + 1
+
+/-- The integer coefficient of the divided derivative on the chosen mode, including the sign
+from differentiating an annihilation term. -/
+def derivativeCoefficient (f : FieldTerm N) : ℤ :=
+ if f.create then f.mode.val.choose f.derivative else
+ (-1) ^ f.derivative * ((f.mode.val + f.derivative).choose f.derivative : ℤ)
+
+/-- The signed exterior creation or deletion, with the divided derivative coefficient. -/
+def matrix (f : FieldTerm N) : Matrix (Occupation N) (Occupation N) ℤ := fun out input =>
+ let scalar := f.derivativeCoefficient *
+ (-1 : ℤ)^((input.filter (· < f.mode)).card)
+ if f.create then
+ if f.mode ∉ input ∧ out = insert f.mode input then scalar else 0
+ else
+ if f.mode ∈ input ∧ out = input.erase f.mode then scalar else 0
+
+end FieldTerm
+
+private def Shifted (A : Matrix (Occupation N) (Occupation N) ℤ) (t : ℤ) : Prop :=
+ ∀ out input, A out input ≠ 0 → doubledEnergy out = doubledEnergy input + t
+
+private theorem shifted_term (f : FieldTerm N) : Shifted f.matrix (2*f.exponent+f.weight) := by
+ intro out input hn
+ cases hc : f.create with
+ | false =>
+ have h : f.mode ∈ input ∧ out = input.erase f.mode := by
+ by_contra h
+ exact hn (by simp [FieldTerm.matrix, hc, h])
+ obtain ⟨hm, rfl⟩ := h
+ have he := Finset.sum_erase_add input (fun r : Fin N => 2 * (r.val : ℤ) + 1) hm
+ simp [doubledEnergy, FieldTerm.exponent, FieldTerm.weight, hc]
+ omega
+ | true =>
+ have h : f.mode ∉ input ∧ out = insert f.mode input := by
+ by_contra h
+ exact hn (by simp [FieldTerm.matrix, hc, h])
+ obtain ⟨hm, rfl⟩ := h
+ simp [doubledEnergy, FieldTerm.exponent, FieldTerm.weight, hc, Finset.sum_insert hm]
+ omega
+
+private theorem shifted_mul {A B : Matrix (Occupation N) (Occupation N) ℤ} {r s : ℤ}
+ (ha : Shifted A r) (hb : Shifted B s) : Shifted (A * B) (r+s) := by
+ intro out input hn
+ by_contra he
+ apply hn
+ rw [Matrix.mul_apply]
+ apply Finset.sum_eq_zero
+ intro k _
+ by_cases hak : A out k = 0
+ · simp [hak]
+ by_cases hbk : B k input = 0
+ · simp [hbk]
+ exact False.elim <| he (by have := ha _ _ hak; have := hb _ _ hbk; omega)
+
+private theorem shifted_word (l : List (FieldTerm N)) :
+ Shifted (l.map FieldTerm.matrix).prod ((l.map (fun f => 2*f.exponent+f.weight)).sum) := by
+ induction l with
+ | nil =>
+ intro out input hn
+ by_cases h : out = input
+ · simp [h]
+ · exact False.elim (hn (by simp [h]))
+ | cons f l ih => simpa using shifted_mul (shifted_term f) ih
+
+/-- Move creations left and deletions right, preserving the order within each group. -/
+def normalOrder (l : List (FieldTerm N)) : List (FieldTerm N) :=
+ l.filter FieldTerm.create ++ l.filter (fun f => !f.create)
+
+private theorem normalOrder_sum (l : List (FieldTerm N)) (a : FieldTerm N → ℤ) :
+ ((normalOrder l).map a).sum = (l.map a).sum := by
+ simp only [normalOrder, List.map_append, List.sum_append]
+ induction l with
+ | nil => simp
+ | cons f l ih =>
+ cases h : f.create <;> simp [h, add_assoc, add_left_comm, ih]
+
+private theorem sum_delta (l : List (FieldTerm N)) :
+ (l.map (fun f => 2*f.exponent+f.weight)).sum =
+ 2 * (l.map FieldTerm.exponent).sum + (l.map FieldTerm.weight).sum := by
+ induction l with
+ | nil => simp
+ | cons f l ih => simp [ih]; omega
+
+/-- The permutation and derivative weights affect the values of entries, while
+every supported entry changes energy by the exponent plus the source weight. -/
+theorem normal_word_homogeneous (l : List (FieldTerm N)) (scalar : ℤ)
+ (out input : Occupation N)
+ (hn : scalar * ((normalOrder l).map FieldTerm.matrix).prod out input ≠ 0) :
+ doubledEnergy out = doubledEnergy input +
+ 2 * (l.map FieldTerm.exponent).sum + (l.map FieldTerm.weight).sum := by
+ have hm : ((normalOrder l).map FieldTerm.matrix).prod out input ≠ 0 := by
+ intro hz
+ simp [hz] at hn
+ have hs := shifted_word (normalOrder l) out input hm
+ rw [normalOrder_sum, sum_delta] at hs
+ omega
+
+/-- A coefficient of a sum of normally ordered words with the same source
+weight is homogeneous on the exterior basis. -/
+theorem normal_coefficient_homogeneous {A : Type*} [Fintype A]
+ (words : A → List (FieldTerm N)) (scalar : A → ℤ) (b h : ℤ)
+ (hw : ∀ k, ((words k).map FieldTerm.weight).sum = h)
+ (out input : Occupation N)
+ (hn : (∑ k : A, if ((words k).map FieldTerm.exponent).sum = b then
+ scalar k * ((normalOrder (words k)).map FieldTerm.matrix).prod out input else 0) ≠ 0) :
+ doubledEnergy out = doubledEnergy input + 2*b + h := by
+ by_contra he
+ apply hn
+ apply Finset.sum_eq_zero
+ intro k _
+ split
+ next hb =>
+ by_contra hk
+ exact he (by simpa [hb, hw] using normal_word_homogeneous (words k) (scalar k) out input hk)
+ next => rfl
+
+/-- Exponent of the normal-ordering sign: each deletion crosses the creations to
+its right. -/
+def normalInversions : List (FieldTerm N) → ℕ
+ | [] => 0
+ | f :: l => (if f.create then 0 else (l.filter FieldTerm.create).length) + normalInversions l
+
+private def fieldWord {m : ℕ} (D : Fin m → ℕ) (k : Fin m → Bool × Fin N) :
+ List (FieldTerm N) :=
+ List.ofFn fun a => ⟨(k a).2, (k a).1, D a⟩
+
+/-- Coefficient of the normally ordered product of the divided derivatives of
+orders `D 0, …, D (m-1)`, truncating the modes to `Fin N`. -/
+def normalBlock {m : ℕ} (D : Fin m → ℕ) (b : ℤ) :
+ Matrix (Occupation N) (Occupation N) ℤ := fun out input =>
+ ∑ k : Fin m → Bool × Fin N, let l := fieldWord D k
+ if (l.map FieldTerm.exponent).sum = b then
+ (-1 : ℤ)^(normalInversions l) * ((normalOrder l).map FieldTerm.matrix).prod out input
+ else 0
+
+/-- The coefficient `[z^b] Y_D` changes doubled energy by precisely
+`2b + ∑ᵢ(2Dᵢ+1)` whenever its matrix entry is nonzero. -/
+theorem normalBlock_homogeneous {m : ℕ} (D : Fin m → ℕ) (b : ℤ)
+ (out input : Occupation N) (hn : normalBlock D b out input ≠ 0) :
+ doubledEnergy out = doubledEnergy input + 2*b + ∑ j, (2*(D j : ℤ)+1) := by
+ apply normal_coefficient_homogeneous (fieldWord D) (fun k => (-1 : ℤ)^normalInversions (fieldWord D k))
+ b (∑ j, (2*(D j : ℤ)+1)) _ out input hn
+ intro k
+ simp [fieldWord, List.map_ofFn, List.sum_ofFn, FieldTerm.weight, Function.comp_def]
+
+variable {S I J : Type*} [Fintype S] (energy : S → ℤ)
+
+/-- A coefficient of exponent `b` for a block of doubled energy `h` changes doubled
+energy by `2*b+h`. -/
+def ModeHomogeneous (h : ℤ) (Y : ℤ → Matrix S S ℤ) : Prop :=
+ ∀ b out input, Y b out input ≠ 0 → energy out = energy input + 2 * b + h
+
+/-- The states whose specified energy is at most `E`. -/
+abbrev Cutoff (E : ℤ) := {p : S // energy p ≤ E}
+
+/-- The coefficient of `z^(L-a) w^a` in `(z-w)^L`. -/
+def multiplier (L a : ℕ) : ℤ := (-1) ^ a * L.choose a
+
+/-- The power `-s - 1 - L + a` required from the first field after choosing `z^(L-a) * w^a` in
+the multiplier. -/
+def firstExponent (L : ℕ) (s : ℤ) (a : Fin (L+1)) : ℤ := -s - 1 - L + a.val
+
+/-- The power `s - a` required from the second field after choosing the term of degree `a` in
+`w` in the multiplier. -/
+def secondExponent (s : ℤ) {L : ℕ} (a : Fin (L+1)) : ℤ := s - a.val
+
+/-- Expanding the polynomial multiplier into individual signed binomial weights. -/
+theorem multiplier_expansion (z w : ℤ) (L : ℕ) :
+ (z - w)^L = ∑ a : Fin (L+1), multiplier L a.val * z^(L-a.val) * w^a.val := by
+ rw [sub_eq_add_neg, add_comm, add_pow, Finset.sum_range]
+ apply Finset.sum_congr rfl
+ intro a _
+ simp only [multiplier, neg_eq_neg_one_mul w, mul_pow]
+ ring
+
+/-- Number of coordinates in either finite factorization. -/
+theorem coordinateCount (L : ℕ) (B : ℤ) :
+ Fintype.card (Fin (L+1) × Cutoff energy B) = (L+1) * Fintype.card (Cutoff energy B) := by
+ simp
+
+private theorem sum_restrict {B : ℤ} (f : S → ℤ)
+ (hf : ∀ x, B < energy x → f x = 0) :
+ ∑ x : S, f x = ∑ x : Cutoff energy B, f x.val := by
+ classical
+ rw [← Finset.sum_subtype (Finset.univ.filter fun x : S => energy x ≤ B)
+ (by simp) f]
+ symm
+ apply Finset.sum_subset (Finset.filter_subset _ _)
+ intro x _ hx
+ apply hf
+ simpa using hx
+
+/-- Two factorizations of the signed coefficient, with an integral factor on each side
+of the two respective cuts. The finite coordinate types include the binomial index
+and the intermediate occupation state. -/
+def HasShiftedFactorizations (H E s : ℤ) (m L : ℕ)
+ (X : I → ℤ → Matrix S S ℤ) (Y : J → ℤ → Matrix S S ℤ) : Prop :=
+ ∃ (p : Fin (L+1) × Cutoff energy (E+H+2*s) → I → Cutoff energy E → ℤ)
+ (q : Fin (L+1) × Cutoff energy (E+H+2*s) → J → Cutoff energy E → ℤ)
+ (r : Fin (L+1) × Cutoff energy (E+H-2*s) → I → Cutoff energy E → ℤ)
+ (t : Fin (L+1) × Cutoff energy (E+H-2*s) → J → Cutoff energy E → ℤ),
+ ∀ (i : I) (j : J) (out input : Cutoff energy E),
+ (∑ a : Fin (L+1), multiplier L a.val *
+ ((X i (firstExponent L s a) * Y j (secondExponent s a)) out.val input.val -
+ (-1 : ℤ)^(m*m) *
+ (Y j (secondExponent s a) * X i (firstExponent L s a)) out.val input.val)) =
+ (∑ v, p v i out * q v j input) + ∑ v, r v i input * t v j out
+
+/-- For `[z^(-s-1) w^s]`, the first product has the intermediate bound
+`E+H+2*s` in doubled energy, and the reversed product has `E+H-2*s`.
+The two product-coordinate types display both exact integer factorizations. -/
+theorem shiftedBlockFactorization (h h' H E s : ℤ) (m L : ℕ)
+ (hL : 2 * (L : ℤ) = h + h' - 2) (hh : h ≤ H) (hh' : h' ≤ H)
+ (X : I → ℤ → Matrix S S ℤ) (Y : J → ℤ → Matrix S S ℤ)
+ (hX : ∀ i, ModeHomogeneous energy h (X i))
+ (hY : ∀ j, ModeHomogeneous energy h' (Y j)) :
+ HasShiftedFactorizations energy H E s m L X Y := by
+ classical
+ refine ⟨fun v i out => multiplier L v.1.val * X i (firstExponent L s v.1) out.val v.2.val,
+ fun v j input => Y j (secondExponent s v.1) v.2.val input.val,
+ fun v i input => -(multiplier L v.1.val * (-1 : ℤ)^(m*m)) *
+ X i (firstExponent L s v.1) v.2.val input.val,
+ fun v j out => Y j (secondExponent s v.1) out.val v.2.val, ?_⟩
+ intro i j out input
+ rw [Fintype.sum_prod_type, Fintype.sum_prod_type, ← Finset.sum_add_distrib]
+ apply Finset.sum_congr rfl
+ intro a _
+ have hf {x : S} (hx : E+H+2*s < energy x) :
+ Y j (secondExponent s a) x input.val = 0 := by
+ by_contra hn
+ have := hY j _ _ _ hn
+ have := input.property
+ simp only [secondExponent] at *
+ omega
+ have hr {x : S} (hx : E+H-2*s < energy x) :
+ X i (firstExponent L s a) x input.val = 0 := by
+ by_contra hn
+ have := hX i _ _ _ hn
+ have := input.property
+ have := a.isLt
+ simp only [firstExponent] at *
+ omega
+ rw [Matrix.mul_apply, Matrix.mul_apply, mul_sub,
+ ← mul_assoc, Finset.mul_sum, Finset.mul_sum]
+ rw [sum_restrict energy _ (fun x hx => by rw [hf hx]; ring),
+ sum_restrict energy _ (fun x hx => by rw [hr hx]; ring),
+ sub_eq_add_neg, ← Finset.sum_neg_distrib]
+ congr 1 <;> apply Finset.sum_congr rfl <;> intros <;> ring
+
+/-- Apply the two distinct finite cut factorizations directly to the signed coefficient
+of the concrete normally ordered field products. The two lists of derivative orders
+have the same length and their doubled source energies are constant in this block. -/
+theorem normalBlock_factorization (N m L : ℕ) (h h' H E s : ℤ)
+ (D : I → Fin m → ℕ) (D' : J → Fin m → ℕ)
+ (hD : ∀ i, (∑ a, (2*(D i a : ℤ)+1)) = h)
+ (hD' : ∀ j, (∑ a, (2*(D' j a : ℤ)+1)) = h')
+ (hL : 2 * (L : ℤ) = h + h' - 2) (hh : h ≤ H) (hh' : h' ≤ H) :
+ HasShiftedFactorizations (doubledEnergy (N := N)) H E s m L
+ (fun i => normalBlock (D i)) (fun j => normalBlock (D' j)) := by
+ apply shiftedBlockFactorization _ h h' _ _ _ _ _ hL hh hh'
+ · intro i b out input hn
+ simpa only [hD i] using normalBlock_homogeneous (D i) b out input hn
+ · intro j b out input hn
+ simpa only [hD' j] using normalBlock_homogeneous (D' j) b out input hn
+
+/-- Integer rank factorizations give the same bound after passage to any field. -/
+theorem factorization_rank {R X Y K : Type*} [Field R] [Fintype K] [Fintype Y]
+ (p : K → X → ℤ) (q : K → Y → ℤ) :
+ Matrix.rank (fun (x : X) (y : Y) => (↑(∑ k : K, p k x * q k y) : R)) ≤
+ Fintype.card K := by
+ let A : Matrix X K R := fun x k => p k x
+ let B : Matrix K Y R := fun k y => q k y
+ have eqm : (fun (x : X) (y : Y) => (↑(∑ k : K, p k x * q k y) : R) : Matrix X Y R) =
+ A * B := by
+ ext x y
+ change (↑(∑ k : K, p k x * q k y) : R) = ∑ k : K, A x k * B k y
+ simp [A, B]
+ rw [eqm]
+ exact (Matrix.rank_mul_le_left A B).trans A.rank_le_card_width
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShiftedModeIdentity.lean b/lean/OAI/Computability/VPVNP/ShiftedModeIdentity.lean
new file mode 100644
index 0000000000..b172633df9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShiftedModeIdentity.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.ShiftedReadout
+import OAI.Computability.VPVNP.ShiftedResidue
+
+/-!
+# Matrix identity for shifted fermionic crossing
+
+Each summand in the coefficient extracted in Appendix B is the product of
+two finite matrices supported on opposite energy shifts. We recover these
+matrices from the shifted residue, with one summand for each term of
+`(z - w)^d`. The result is valid also between states of unequal energy.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open Lemmata.FockCircuits Lemmata.FockCircuits.FiniteIdentity
+open scoped BigOperators
+open LaurentPolynomial
+
+variable (R : Type*) [CommRing R]
+
+/-- Opposite-order fermionic modes recover the vacuum pairing times the
+identity matrix, at any shift inside the enlarged cutoff. -/
+theorem shifted_operator_identity (L K : ℕ) (A B I J : Index L) (d : ℕ) (s : ℤ)
+ (hd : 2 * d + 2 = sourceEnergy A.val.sort + sourceEnergy B.val.sort)
+ (hcut : doubledEnergy J.val + K + max (sourceEnergy A.val.sort) (sourceEnergy B.val.sort) + 4 ≤ 2 * L)
+ (hs : |-2 * s - 2| ≤ K) :
+ (∑ a : Fin (d + 1), (-1 : R) ^ (a : ℕ) * d.choose a *
+ (let q := 2 * s + (doubledEnergy B.val : ℤ) - 2 * (a : ℕ)
+ (diagonal R L (-q) (Pi.single A 1) * diagonal R L q (Pi.single B 1)) I J -
+ (-1 : R) ^ (A.val.sort.length * B.val.sort.length) *
+ (diagonal R L q (Pi.single B 1) * diagonal R L (-q) (Pi.single A 1)) I J)) =
+ (if I = J then (1 : R) else 0) * matrix R L (Pi.single A 1) ⟨∅, by simp⟩ B := by
+ let energy : Index L → ℤ := fun i => doubledEnergy i.val
+ let aMat := matrix R L (Pi.single A 1)
+ let bMat := matrix R L (Pi.single B 1)
+ have hA : energyField energy (doubledEnergy A.val) aMat = scaledMatrix R L A := by
+ apply Matrix.ext
+ intro i j
+ exact (scaledMatrix_eq_monomial R L A i j).symm
+ have hB : bMat.map C = constantMatrix R L B := rfl
+ by_cases hij : doubledEnergy I.val = doubledEnergy J.val
+ · have hgrade : energy I = energy J := congrArg Nat.cast hij
+ have hdegree : 2 * (d : ℤ) + 2 = (doubledEnergy A.val : ℤ) + doubledEnergy B.val := by
+ simp only [sourceEnergy_sort] at hd
+ omega
+ have readout := shifted_supercommutator_readout energy aMat bMat
+ (doubledEnergy A.val) (doubledEnergy B.val) s
+ ((-1 : R) ^ (A.val.sort.length * B.val.sort.length)) d hdegree I J hgrade
+ rw [hA, hB] at readout
+ have hidx : 2 * (-s - 1) = -2 * s - 2 := by ring
+ have hres := shifted_weighted_matrix_residue_all R L K A B I J d hd hij
+ (by omega) (-s - 1) (hidx ▸ hs)
+ rw [hidx] at hres
+ apply readout.symm.trans
+ simpa only [Units.smul_def, zsmul_eq_mul, Units.val_pow_eq_pow_val,
+ Units.val_neg, Units.val_one, Int.cast_pow, Int.cast_neg, Int.cast_one] using hres
+ · have hne : I ≠ J := fun e => hij (congrArg (fun x : Index L => doubledEnergy x.val) e)
+ have hgrade : energy I ≠ energy J := by dsimp [energy]; omega
+ simp only [hne, ↓reduceIte, zero_mul]
+ apply Finset.sum_eq_zero
+ intro a _
+ let q : ℤ := 2 * s + (doubledEnergy B.val : ℤ) - 2 * (a : ℕ)
+ have hforward := opposite_modes_off_energy energy aMat bMat (-q) I J hgrade
+ have hreverse := opposite_modes_off_energy energy bMat aMat q I J hgrade
+ rw [neg_neg] at hforward
+ change _ * ((energyMode energy aMat (-q) * energyMode energy bMat q) I J -
+ _ * (energyMode energy bMat q * energyMode energy aMat (-q)) I J) = _
+ rw [hforward, hreverse, mul_zero, sub_zero, mul_zero]
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShiftedPairing.lean b/lean/OAI/Computability/VPVNP/ShiftedPairing.lean
new file mode 100644
index 0000000000..62a595a1e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShiftedPairing.lean
@@ -0,0 +1,482 @@
+import Mathlib.Algebra.Group.Pi.Units
+import Mathlib.Data.Finset.Fin
+import Mathlib.Data.Matrix.Mul
+import Mathlib.Data.Nat.Choose.Basic
+import Mathlib.Data.Nat.Choose.Vandermonde
+import Mathlib.LinearAlgebra.ExteriorPower.Basis
+import Mathlib.LinearAlgebra.Matrix.Block
+import Mathlib.LinearAlgebra.Matrix.NonsingularInverse
+import Mathlib.LinearAlgebra.Matrix.Rank
+import Mathlib.LinearAlgebra.Matrix.Reindex
+import Mathlib.LinearAlgebra.Matrix.ToLin
+import Mathlib.Order.Hom.PowersetCard
+import Mathlib.Order.Interval.Finset.Fin
+
+/-!
+# The integral pairing for shifted crossing
+
+Appendix B of *VP and VNP differ over every field* gives the coefficient of the
+full fermionic contraction as a signed binomial determinant. In each sector of
+fixed particle number, Cauchy–Binet expresses this determinant as a Gram matrix
+of Pascal minors. A nonzero minor can only lower the energy of the intermediate
+index. This proves that the pairing on the entire energy cutoff is unimodular.
+
+Its integral inverse acts on the first operator index in both crossing terms.
+The two factorization index sets can have different sizes, and each gives a
+flattening rank bound after specialization to an arbitrary field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+section
+
+open Set
+
+variable {R I J K : Type*} [CommRing R] [LinearOrder I] [LinearOrder J] [LinearOrder K]
+
+/-- Matrix of the size-`m` minors, with each index set in increasing order. -/
+noncomputable def compound (m : ℕ) (A : Matrix I J R) :
+ Matrix (powersetCard I m) (powersetCard J m) R :=
+ fun s t ↦ (A.submatrix (powersetCard.ofFinEmbEquiv.symm s)
+ (powersetCard.ofFinEmbEquiv.symm t)).det
+
+/-- Transposition exchanges the two index sets of every minor. -/
+theorem compound_transpose (m : ℕ) (A : Matrix I J R) :
+ compound m A.transpose = (compound m A).transpose := by
+ ext s t
+ exact Matrix.det_transpose _
+
+variable [Fintype I] [Fintype J] [Fintype K]
+
+private theorem compound_eq_toMatrix (m : ℕ) (A : Matrix I J R) :
+ compound m A = LinearMap.toMatrix ((Pi.basisFun R J).exteriorPower m)
+ ((Pi.basisFun R I).exteriorPower m) (exteriorPower.map m A.mulVecLin) := by
+ ext s t
+ rw [LinearMap.toMatrix_apply, exteriorPower.basis_repr_apply, exteriorPower.basis_apply,
+ exteriorPower.map_apply_ιMulti_family, exteriorPower.ιMulti_family,
+ exteriorPower.ιMultiDual_apply_ιMulti]
+ rw [← Matrix.det_transpose]
+ apply congrArg Matrix.det
+ ext i j
+ simp [Module.Basis.coord_apply, Pi.basisFun_apply]
+
+/-- Cauchy–Binet over an arbitrary commutative ring. -/
+theorem compound_mul (m : ℕ) (A : Matrix I J R) (B : Matrix J K R) :
+ compound m (A * B) = compound m A * compound m B := by
+ rw [compound_eq_toMatrix, compound_eq_toMatrix, compound_eq_toMatrix, Matrix.mulVecLin_mul,
+ exteriorPower.map_comp, LinearMap.toMatrix_comp _ ((Pi.basisFun R J).exteriorPower m)]
+
+end
+
+/-- If an integer Pascal minor is nonzero, each selected column index is at
+most the corresponding selected row index. -/
+theorem pascalMinor_support {m n : ℕ} (r c : Fin m → Fin n)
+ (hr : StrictMono r) (hc : StrictMono c)
+ (hdet : Matrix.det (Matrix.of fun i j => ((r i).val.choose (c j).val : ℤ)) ≠ 0) :
+ ∀ k, c k ≤ r k := by
+ classical
+ intro k
+ by_contra! hbad
+ apply hdet
+ rw [Matrix.det_apply]
+ apply Finset.sum_eq_zero
+ intro σ _
+ simp only [Matrix.of_apply]
+ suffices ∃ i, σ i ≤ k ∧ k ≤ i by
+ obtain ⟨i, hrow, hcol⟩ := this
+ have hlt : r (σ i) < c i :=
+ (hr.monotone hrow).trans_lt (hbad.trans_le (hc.monotone hcol))
+ have hzero : ((r (σ i)).val.choose (c i).val : ℤ) = 0 := by
+ simp [Nat.choose_eq_zero_of_lt hlt]
+ rw [Finset.prod_eq_zero (Finset.mem_univ i) hzero, smul_zero]
+ by_contra! hall
+ have maps : Set.MapsTo σ.symm (Finset.Iic k : Finset (Fin m)) (Finset.Iio k) := by
+ intro j hj
+ apply Finset.mem_Iio.mpr
+ apply hall (σ.symm j)
+ simpa using (Finset.mem_Iic.mp hj)
+ have hcard := Finset.card_le_card_of_injOn σ.symm maps σ.symm.injective.injOn
+ simp at hcard
+
+/-- Every principal minor of the integer Pascal matrix has determinant one. -/
+theorem pascalMinor_diagonal {m n : ℕ} (r : Fin m → Fin n) (hr : StrictMono r) :
+ Matrix.det (Matrix.of fun i j => ((r i).val.choose (r j).val : ℤ)) = 1 := by
+ rw [Matrix.det_of_isLowerTriangular]
+ · simp
+ · intro i j hij
+ have hij' : (r i).val < (r j).val := hr (show i < j from hij)
+ simp [Nat.choose_eq_zero_of_lt hij']
+
+open scoped BigOperators Matrix
+open Set.powersetCard
+
+/-- The matrix of binomial coefficients before taking exterior powers. -/
+def pascalMatrix (n : ℕ) : Matrix (Fin n) (Fin n) ℤ :=
+ fun i j => (i.val.choose j.val : ℤ)
+
+/-- The Gram matrix of Pascal's triangle gives the contraction kernel. -/
+theorem pascalGram (n : ℕ) (i j : Fin n) :
+ (pascalMatrix n * (pascalMatrix n)ᵀ) i j = ((i.val + j.val).choose i.val : ℤ) := by
+ change ∑ k : Fin n, (i.val.choose k.val : ℤ) * (j.val.choose k.val : ℤ) = _
+ norm_cast
+ rw [Fin.sum_univ_eq_sum_range (fun k => i.val.choose k * j.val.choose k), add_comm i.val j.val,
+ Nat.add_choose_eq, Finset.Nat.sum_antidiagonal_eq_sum_range_succ_mk]
+ calc
+ _ = ∑ k ∈ Finset.range (i.val + 1), i.val.choose k * j.val.choose k := by
+ refine (Finset.sum_subset (Finset.range_mono i.isLt) ?_).symm
+ intro k _ hk
+ rw [Nat.choose_eq_zero_of_lt (by simpa [Finset.mem_range] using hk), zero_mul]
+ _ = _ := Finset.sum_congr rfl fun k hk => by
+ rw [Nat.choose_symm (Finset.mem_range_succ_iff.mp hk), mul_comm]
+
+/-- A sector of Fock states with fixed occupation number and bounded doubled energy. -/
+def doubledSectorEnergy {n m : ℕ} (I : Set.powersetCard (Fin n) m) : ℕ :=
+ ∑ k : Fin m, (2 * (ofFinEmbEquiv.symm I k).val + 1)
+
+/-- Doubling removes all half-integral mode energies in a fixed occupation sector. -/
+theorem doubledSectorEnergy_eq {n m : ℕ} (I : Set.powersetCard (Fin n) m) :
+ doubledSectorEnergy I = 2 * ∑ k : Fin m, (ofFinEmbEquiv.symm I k).val + m := by
+ simp [doubledSectorEnergy, Finset.sum_add_distrib, Finset.mul_sum]
+
+/-- For a pair of equally large, nonempty blocks the pole degree `L = h + h' - 1`
+is an integer. The numerator in its doubled-energy formula is exactly even. -/
+theorem sectorPoleDegree_eq {n m : ℕ} (I J : Set.powersetCard (Fin n) (m + 1)) :
+ 2 * ((doubledSectorEnergy I + doubledSectorEnergy J) / 2 - 1) + 2 =
+ doubledSectorEnergy I + doubledSectorEnergy J := by
+ rw [doubledSectorEnergy_eq, doubledSectorEnergy_eq]
+ omega
+
+/-- The states with exactly `m` occupied modes among the first `n` and doubled energy at most
+`bound`. -/
+abbrev EnergySector (n m bound : ℕ) :=
+ {I : Set.powersetCard (Fin n) m // doubledSectorEnergy I ≤ bound}
+
+private theorem sectorEnergy_le {n m : ℕ} {I J : Set.powersetCard (Fin n) m}
+ (h : ∀ k, ofFinEmbEquiv.symm J k ≤ ofFinEmbEquiv.symm I k) :
+ doubledSectorEnergy J ≤ doubledSectorEnergy I :=
+ Finset.sum_le_sum fun k _ => by
+ have hh : (ofFinEmbEquiv.symm J k).val ≤ (ofFinEmbEquiv.symm I k).val := h k
+ omega
+
+private theorem sectorEnergy_lt {n m : ℕ} {I J : Set.powersetCard (Fin n) m}
+ (hne : J ≠ I) (h : ∀ k, ofFinEmbEquiv.symm J k ≤ ofFinEmbEquiv.symm I k) :
+ doubledSectorEnergy J < doubledSectorEnergy I := by
+ obtain ⟨k, hk⟩ : ∃ k, ofFinEmbEquiv.symm J k < ofFinEmbEquiv.symm I k := by
+ by_contra! hall
+ apply hne
+ apply ofFinEmbEquiv.symm.injective
+ ext k
+ exact le_antisymm (h k) (hall k)
+ apply Finset.sum_lt_sum
+ · intro k _
+ have hh : (ofFinEmbEquiv.symm J k).val ≤ (ofFinEmbEquiv.symm I k).val := h k
+ omega
+ · refine ⟨k, Finset.mem_univ _, ?_⟩
+ change (ofFinEmbEquiv.symm J k).val < (ofFinEmbEquiv.symm I k).val at hk
+ omega
+
+/-- Pascal minors on the energy downset of a fixed occupation number. -/
+noncomputable def sectorPascal (n m bound : ℕ) :
+ Matrix (EnergySector n m bound) (EnergySector n m bound) ℤ :=
+ (compound m (pascalMatrix n)).submatrix Subtype.val Subtype.val
+
+private theorem pascalSupport {n m : ℕ} {I J : Set.powersetCard (Fin n) m}
+ (h : compound m (pascalMatrix n) I J ≠ 0) :
+ ∀ k, ofFinEmbEquiv.symm J k ≤ ofFinEmbEquiv.symm I k :=
+ pascalMinor_support _ _ (ofFinEmbEquiv.symm I).strictMono (ofFinEmbEquiv.symm J).strictMono h
+
+/-- No intermediate index outside the energy cutoff contributes to Cauchy–Binet. -/
+theorem sectorPascal_gram (n m bound : ℕ) :
+ (compound m (pascalMatrix n * (pascalMatrix n)ᵀ)).submatrix
+ (fun I : EnergySector n m bound => I.val) Subtype.val =
+ sectorPascal n m bound * (sectorPascal n m bound)ᵀ := by
+ classical
+ rw [compound_mul, compound_transpose]
+ ext I J
+ simp only [sectorPascal, Matrix.submatrix_apply, Matrix.mul_apply, Matrix.transpose_apply]
+ let good := fun K : Set.powersetCard (Fin n) m => doubledSectorEnergy K ≤ bound
+ rw [← Fintype.sum_subtype_add_sum_subtype good]
+ suffices ∑ K : {K // ¬good K},
+ compound m (pascalMatrix n) I.val K.val * compound m (pascalMatrix n) J.val K.val = 0 by
+ rw [this, add_zero]
+ apply Finset.sum_eq_zero
+ intro K _
+ have hzero : compound m (pascalMatrix n) I.val K.val = 0 := by
+ by_contra hn
+ exact K.property ((sectorEnergy_le (pascalSupport hn)).trans I.property)
+ rw [hzero, zero_mul]
+
+/-- The restricted matrix of Pascal minors has determinant one, including ties in energy. -/
+theorem sectorPascal_det (n m bound : ℕ) : (sectorPascal n m bound).det = 1 := by
+ classical
+ let grade : EnergySector n m bound → ℕᵒᵈ := fun I => doubledSectorEnergy I.val
+ have htri : (sectorPascal n m bound).BlockTriangular grade := by
+ intro I J hlt
+ by_contra hn
+ exact (not_lt_of_ge (sectorEnergy_le (pascalSupport hn))) hlt
+ have hblocks (k : ℕᵒᵈ) : (sectorPascal n m bound).toSquareBlock grade k = 1 := by
+ ext I J
+ rw [Matrix.one_apply]
+ split_ifs with hIJ
+ · subst J
+ exact pascalMinor_diagonal _ (ofFinEmbEquiv.symm I.val.val).strictMono
+ · by_contra hn
+ have hne : J.val.val ≠ I.val.val :=
+ fun heq => hIJ (Subtype.ext (Subtype.ext heq.symm))
+ have hlt := sectorEnergy_lt hne (pascalSupport hn)
+ have heq : doubledSectorEnergy I.val.val = doubledSectorEnergy J.val.val :=
+ I.property.trans J.property.symm
+ omega
+ simp [htri.det, hblocks]
+
+/-- The sign of a full matching in the order of the fermionic fields of Appendix B. -/
+def crossingRowSign {n m : ℕ} (I : Set.powersetCard (Fin n) m) : ℤ :=
+ (-1) ^ (m.choose 2 + ∑ k : Fin m, (ofFinEmbEquiv.symm I k).val)
+
+/-- The signed determinant of the full-contraction coefficients in equation (B.1),
+restricted to an energy sector. -/
+noncomputable def sectorPairing (n m bound : ℕ) :
+ Matrix (EnergySector n m bound) (EnergySector n m bound) ℤ :=
+ fun I J => crossingRowSign I.val *
+ (compound m (fun i j : Fin n => ((i.val + j.val).choose i.val : ℤ))) I.val J.val
+
+/-- Equation (B.1)'s integral pairing in each fixed-cardinality sector is unimodular. -/
+theorem sectorPairing_isUnit (n m bound : ℕ) : IsUnit (sectorPairing n m bound) := by
+ classical
+ have hgram : (fun i j : Fin n => ((i.val + j.val).choose i.val : ℤ)) =
+ pascalMatrix n * (pascalMatrix n)ᵀ := by
+ ext i j
+ exact (pascalGram n i j).symm
+ have hfactor : sectorPairing n m bound =
+ Matrix.diagonal (fun I : EnergySector n m bound => crossingRowSign I.val) *
+ (sectorPascal n m bound * (sectorPascal n m bound)ᵀ) := by
+ rw [← sectorPascal_gram]
+ ext I J
+ rw [Matrix.diagonal_mul]
+ simp only [sectorPairing, hgram, Matrix.submatrix_apply]
+ apply (Matrix.isUnit_iff_isUnit_det _).mpr
+ rw [hfactor, Matrix.det_mul, Matrix.det_mul, Matrix.det_transpose, sectorPascal_det,
+ Matrix.det_diagonal, one_mul, mul_one]
+ exact IsUnit.prod_univ_iff.mpr fun I => isUnit_one.neg.pow _
+
+/-- The pairing on all nonempty states uses the positive particle-number sectors as blocks. -/
+noncomputable def crossingPairing (n bound : ℕ) :
+ Matrix (Σ m : Fin n, EnergySector n (m.val + 1) bound)
+ (Σ m : Fin n, EnergySector n (m.val + 1) bound) ℤ :=
+ Matrix.blockDiagonal' fun m => sectorPairing n (m.val + 1) bound
+
+/-- The simultaneous pairing on every nonempty state under the energy cutoff has
+an integral inverse. -/
+theorem crossingPairing_isUnit (n bound : ℕ) : IsUnit (crossingPairing n bound) :=
+ (Pi.isUnit_iff.mpr fun m : Fin n => sectorPairing_isUnit n (m.val + 1) bound).map
+ (Matrix.blockDiagonal'RingHom (fun m : Fin n => EnergySector n (m.val + 1) bound) ℤ)
+
+/-- Enumerating the modes in increasing order preserves the total doubled energy. -/
+theorem doubledSectorEnergy_eq_sum {n m : ℕ} (I : Set.powersetCard (Fin n) m) :
+ doubledSectorEnergy I = ∑ i ∈ I.val, (2 * i.val + 1) := by
+ have hc : I.val.card = m := I.prop
+ calc
+ doubledSectorEnergy I =
+ ∑ i ∈ Finset.univ.map (I.val.orderEmbOfFin hc).toEmbedding, (2 * i.val + 1) := by
+ rw [Finset.sum_map]
+ rfl
+ _ = _ := by rw [Finset.map_orderEmbOfFin_univ I.val hc]
+
+/-- A nonvacuum fermionic state in the energy ball of doubled radius `B`. -/
+abbrev BoundedState (B : ℕ) :=
+ {S : Finset ℕ // S.Nonempty ∧ ∑ i ∈ S, (2 * i + 1) ≤ B}
+
+private def sectorState {B : ℕ} (s : Σ m : Fin B, EnergySector B (m.val + 1) B) :
+ BoundedState B := by
+ rcases s with ⟨m, I, hI⟩
+ refine ⟨I.val.map Fin.valEmbedding, Finset.card_pos.mp ?_, ?_⟩
+ · rw [Finset.card_map, I.prop]
+ omega
+ · rw [Finset.sum_map]
+ exact (doubledSectorEnergy_eq_sum I ▸ hI)
+
+private theorem sectorState_injective (B : ℕ) : Function.Injective (@sectorState B) := by
+ rintro ⟨m, I, hI⟩ ⟨k, J, hJ⟩ h
+ have hval : I.val = J.val := Finset.map_injective Fin.valEmbedding (congrArg Subtype.val h)
+ have hmk : m = k := Fin.ext (by simpa [I.prop, J.prop] using congrArg Finset.card hval)
+ subst k
+ have hIJ : I = J := Subtype.ext hval
+ subst J
+ rfl
+
+private theorem sectorState_surjective (B : ℕ) : Function.Surjective (@sectorState B) := by
+ rintro ⟨S, hS, hEnergy⟩
+ have hmode (i : ℕ) (hi : i ∈ S) : i < B := by
+ have hle := Finset.single_le_sum (f := fun j => 2 * j + 1) (fun _ _ => Nat.zero_le _) hi
+ omega
+ have hpos : 0 < S.card := Finset.card_pos.mpr hS
+ have hcard : S.card ≤ B := by
+ simpa using (Finset.card_le_univ (S.attachFin hmode))
+ let m : Fin B := ⟨S.card - 1, by omega⟩
+ let I : Set.powersetCard (Fin B) (m.val + 1) := ⟨S.attachFin hmode, by
+ change (S.attachFin hmode).card = S.card - 1 + 1
+ rw [Finset.card_attachFin]
+ omega⟩
+ have hI : doubledSectorEnergy I ≤ B := by
+ rw [doubledSectorEnergy_eq_sum]
+ change ∑ i ∈ S.attachFin hmode, (2 * i.val + 1) ≤ B
+ have h := Finset.sum_map (S.attachFin hmode) Fin.valEmbedding (fun i : ℕ => 2 * i + 1)
+ rw [Finset.map_valEmbedding_attachFin] at h
+ exact h ▸ hEnergy
+ exact ⟨⟨m, I, hI⟩, Subtype.ext (Finset.map_valEmbedding_attachFin hmode)⟩
+
+/-- Decompose the energy-bounded nonvacuum states into blocks by occupation number. -/
+noncomputable def boundedStateEquivSectors (B : ℕ) :
+ BoundedState B ≃ (Σ m : Fin B, EnergySector B (m.val + 1) B) :=
+ (Equiv.ofBijective sectorState ⟨sectorState_injective B, sectorState_surjective B⟩).symm
+
+@[simp]
+theorem boundedStateEquivSectors_symm_val {B : ℕ}
+ (s : Σ m : Fin B, EnergySector B (m.val + 1) B) :
+ ((boundedStateEquivSectors B).symm s).val = s.2.val.val.map Fin.valEmbedding := by
+ cases s with | mk m I => cases I; rfl
+
+theorem boundedStateEquivSectors_modes {B : ℕ} (S : BoundedState B) :
+ ((boundedStateEquivSectors B S).2.val.val.map Fin.valEmbedding) = S.val := by
+ rw [← boundedStateEquivSectors_symm_val, Equiv.symm_apply_apply]
+
+theorem boundedStateEquivSectors_card {B : ℕ} (S : BoundedState B) :
+ (boundedStateEquivSectors B S).1.val + 1 = S.val.card := by
+ rw [← boundedStateEquivSectors_modes S, Finset.card_map]
+ exact (boundedStateEquivSectors B S).2.val.prop.symm
+
+noncomputable instance (B : ℕ) : Fintype (BoundedState B) :=
+ Fintype.ofEquiv _ (boundedStateEquivSectors B).symm
+
+/-- The full integral pairing on the nonempty finite subsets of natural modes of
+doubled energy at most `B`. -/
+noncomputable def boundedStatePairing (B : ℕ) : Matrix (BoundedState B) (BoundedState B) ℤ :=
+ Matrix.reindexRingEquiv ℤ (boundedStateEquivSectors B).symm (crossingPairing B B)
+
+/-- An integral inverse exists for every energy cutoff in the infinite-mode indexing. -/
+theorem boundedStatePairing_isUnit (B : ℕ) : IsUnit (boundedStatePairing B) :=
+ (crossingPairing_isUnit B B).map (Matrix.reindexRingEquiv ℤ (boundedStateEquivSectors B).symm)
+
+private theorem sectorNaturalModes {B m : ℕ} (I : EnergySector B m B) {S : Finset ℕ}
+ (hS : I.val.val.map Fin.valEmbedding = S) (hc : S.card = m) :
+ (fun k : Fin m => (ofFinEmbEquiv.symm I.val k).val) = S.orderEmbOfFin hc := by
+ refine Finset.orderEmbOfFin_unique hc (fun k => ?_) ?_
+ · rw [← hS]
+ apply Finset.mem_map.mpr
+ refine ⟨ofFinEmbEquiv.symm I.val k, ?_, rfl⟩
+ exact (mem_range_ofFinEmbEquiv_symm_iff_mem _ _).mp ⟨k, rfl⟩
+ · exact fun a b hab => (ofFinEmbEquiv.symm I.val).strictMono hab
+
+/-- On states with different occupation numbers the full-contraction pairing vanishes. -/
+theorem boundedStatePairing_eq_zero_of_card_ne {B : ℕ} (S T : BoundedState B)
+ (h : S.val.card ≠ T.val.card) : boundedStatePairing B S T = 0 := by
+ have hne : (boundedStateEquivSectors B S).1 ≠ (boundedStateEquivSectors B T).1 := by
+ intro heq
+ exact h (by rw [← boundedStateEquivSectors_card S, ← boundedStateEquivSectors_card T, heq])
+ change crossingPairing B B (boundedStateEquivSectors B S) (boundedStateEquivSectors B T) = 0
+ exact Matrix.blockDiagonal'_apply_ne _ _ _ hne
+
+/-- In the natural-mode indexing, the integral pairing is the signed determinant
+of the binomial contraction kernel, in increasing order on both lists. -/
+theorem boundedStatePairing_eq_det {B m : ℕ} (S T : BoundedState B)
+ (hS : S.val.card = m) (hT : T.val.card = m) :
+ boundedStatePairing B S T =
+ (-1 : ℤ) ^ (m.choose 2 + ∑ i : Fin m, S.val.orderEmbOfFin hS i) *
+ Matrix.det (Matrix.of fun i j : Fin m =>
+ ((S.val.orderEmbOfFin hS i + T.val.orderEmbOfFin hT j).choose
+ (S.val.orderEmbOfFin hS i) : ℤ)) := by
+ have hSM := boundedStateEquivSectors_modes S
+ have hTM := boundedStateEquivSectors_modes T
+ have hSC := (boundedStateEquivSectors_card S).trans hS
+ have hTC := (boundedStateEquivSectors_card T).trans hT
+ change crossingPairing B B (boundedStateEquivSectors B S) (boundedStateEquivSectors B T) = _
+ generalize (boundedStateEquivSectors B S) = u at *
+ generalize (boundedStateEquivSectors B T) = v at *
+ obtain ⟨a, I⟩ := u
+ obtain ⟨b, J⟩ := v
+ have hab : a = b := Fin.ext (by simpa using hSC.trans hTC.symm)
+ subst b
+ change a.val + 1 = m at hSC
+ cases hSC
+ have hr := sectorNaturalModes I hSM hS
+ have hc := sectorNaturalModes J hTM hT
+ rw [crossingPairing, Matrix.blockDiagonal'_apply_eq]
+ change (-1 : ℤ) ^ ((a.val + 1).choose 2 + ∑ i : Fin (a.val + 1),
+ (ofFinEmbEquiv.symm I.val i).val) *
+ Matrix.det (Matrix.of fun i j : Fin (a.val + 1) =>
+ (((ofFinEmbEquiv.symm I.val i).val + (ofFinEmbEquiv.symm J.val j).val).choose
+ (ofFinEmbEquiv.symm I.val i).val : ℤ)) = _
+ simp_rw [← hr, ← hc]
+
+private theorem mixFactors {I K : Type*} [Fintype I] [Fintype K]
+ (w : I → ℤ) (f : K → I → ℤ) (g : K → ℤ) :
+ ∑ k, (∑ i, w i * f k i) * g k = ∑ i, w i * ∑ k, f k i * g k := by
+ simp_rw [Finset.sum_mul, Finset.mul_sum, mul_assoc]
+ exact Finset.sum_comm
+
+/-- Apply the inverse of the integral pairing on the first index in both crossing
+families. This preserves the original two index sets of factors. -/
+theorem normalizeCrossing {X Y K L : Type*}
+ [Fintype X] [DecidableEq X] [DecidableEq Y] [Fintype K] [Fintype L]
+ (a b : K → X → Y → ℤ) (c d : L → X → Y → ℤ)
+ (G : Matrix X X ℤ) (hG : IsUnit G)
+ (h : ∀ i j α β, ∑ k, a k i α * b k j β + ∑ l, c l i β * d l j α
+ = G i j * (if α = β then 1 else 0)) :
+ ∃ (a' : K → X → Y → ℤ) (c' : L → X → Y → ℤ),
+ ∀ i j α β, ∑ k, a' k i α * b k j β + ∑ l, c' l i β * d l j α
+ = (if i = j then 1 else 0) * (if α = β then 1 else 0) := by
+ obtain ⟨u, rfl⟩ := hG
+ let H : Matrix X X ℤ := ↑u⁻¹
+ refine ⟨fun k i α => ∑ t, H i t * a k t α, fun l i β => ∑ t, H i t * c l t β, ?_⟩
+ intro i j α β
+ rw [mixFactors (H i) (fun k t => a k t α) (fun k => b k j β),
+ mixFactors (H i) (fun l t => c l t β) (fun l => d l j α)]
+ simp_rw [← Finset.sum_add_distrib, ← mul_add, h, ← mul_assoc, ← Finset.sum_mul]
+ have hHG : H * (u : Matrix X X ℤ) = 1 := Units.inv_mul u
+ exact congrArg (fun v : ℤ => v * (if α = β then 1 else 0))
+ (by simpa only [Matrix.mul_apply, Matrix.one_apply] using congrFun (congrFun hHG i) j)
+
+/-- Integral coefficients of a tensor flattened on one crossing cut. -/
+def crossingMatrix {X Y K : Type*} [Fintype K] (a b : K → X → Y → ℤ) :
+ Matrix (X × Y) (X × Y) ℤ :=
+ Matrix.of fun i j => ∑ k, a k i.1 i.2 * b k j.1 j.2
+
+/-- Reducing the chosen integral flattening to any field preserves its bound
+by the number of intermediate coordinates, including in characteristic two. -/
+theorem crossingMatrix_rank_cast {X Y K : Type*} [Fintype X] [Fintype Y] [Fintype K]
+ (a b : K → X → Y → ℤ) (F : Type*) [Field F] :
+ ((crossingMatrix a b).map (Int.castRingHom F)).rank ≤ Fintype.card K := by
+ let A : Matrix (X × Y) K F := Matrix.of fun i k => (a k i.1 i.2 : F)
+ let B : Matrix K (X × Y) F := Matrix.of fun k j => (b k j.1 j.2 : F)
+ have h : (crossingMatrix a b).map (Int.castRingHom F) = A * B := by
+ ext i j
+ simp [crossingMatrix, A, B, Matrix.mul_apply]
+ exact h ▸ (Matrix.rank_mul_le_left A B).trans A.rank_le_card_width
+
+/-- Both flattenings and their two different bounds specialize simultaneously.
+The swapped second coordinates display the opposite cut of the second summand. -/
+theorem crossingRanks_overField {X Y K L : Type*} [Fintype X] [Fintype Y]
+ [Fintype K] [Fintype L] [DecidableEq X] [DecidableEq Y]
+ (a b : K → X → Y → ℤ) (c d : L → X → Y → ℤ)
+ (h : ∀ i j α β, ∑ k, a k i α * b k j β + ∑ l, c l i β * d l j α
+ = (if i = j then 1 else 0) * (if α = β then 1 else 0)) (F : Type*) [Field F] :
+ let P := (crossingMatrix a b).map (Int.castRingHom F)
+ let Q := (crossingMatrix c d).map (Int.castRingHom F)
+ (∀ i j α β, P (i, α) (j, β) + Q (i, β) (j, α) =
+ (if i = j then 1 else 0) * (if α = β then 1 else 0)) ∧
+ P.rank ≤ Fintype.card K ∧ Q.rank ≤ Fintype.card L := by
+ refine ⟨?_, crossingMatrix_rank_cast a b F, crossingMatrix_rank_cast c d F⟩
+ intro i j α β
+ simpa only [crossingMatrix, Matrix.map_apply, Matrix.of_apply, map_add, map_mul,
+ apply_ite (Int.castRingHom F), map_one, map_zero] using
+ congrArg (Int.castRingHom F) (h i j α β)
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShiftedReadout.lean b/lean/OAI/Computability/VPVNP/ShiftedReadout.lean
new file mode 100644
index 0000000000..106e088800
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShiftedReadout.lean
@@ -0,0 +1,172 @@
+import Mathlib.Algebra.Polynomial.Laurent
+import Mathlib.Data.Matrix.Mul
+import Mathlib.Tactic.Ring
+
+/-! Coefficient extraction for opposite-order products of energy-graded matrices.
+The grades can be doubled fermionic energies, which are integers for all states. -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open scoped BigOperators
+open LaurentPolynomial
+
+variable {R ι : Type*} [CommRing R]
+
+/-- Retain the entries of an operator that change the energy by exactly `q`. -/
+def energyMode (energy : ι → ℤ) (A : Matrix ι ι R) (q : ℤ) : Matrix ι ι R :=
+ fun i j => if energy i - energy j = q then A i j else 0
+
+/-- Record the energy change of an operator entry as a Laurent monomial. -/
+noncomputable def energyField (energy : ι → ℤ) (h : ℤ) (A : Matrix ι ι R) :
+ Matrix ι ι (LaurentPolynomial R) :=
+ fun i j => C (A i j) * T (energy i - energy j - h)
+
+private lemma monomial_coeff_product (c a b : R) (u v t : ℤ) :
+ (C c * T u * ((C a * T v) * C b)).coeff t =
+ if u + v = t then c * (a * b) else 0 := by
+ have h : C c * T u * ((C a * T v) * C b) = C (c * (a * b)) * T (u + v) := by
+ rw [map_mul, map_mul, T_add]
+ ring
+ rw [h, ← single_eq_C_mul_T, AddMonoidAlgebra.coeff_single, Finsupp.single_apply]
+
+private lemma binomial_laurent (d : ℕ) :
+ (T (R := R) 2 - 1) ^ d =
+ ∑ a : Fin (d + 1), C ((-1 : R) ^ (a : ℕ) * d.choose a) *
+ T ((d - (a : ℕ) : ℕ) * (2 : ℤ)) := by
+ classical
+ rw [show T (R := R) 2 - 1 = -1 + T 2 by ring, add_pow]
+ rw [Finset.sum_range]
+ apply Finset.sum_congr rfl
+ intro a _
+ simp only [map_mul, map_pow, map_neg, map_one, map_natCast, T_pow]
+ ring
+
+variable [Fintype ι]
+
+/-- Read an arbitrary coefficient of the forward product, including its binomial multiplier. -/
+theorem forward_coeff_any_energy (energy : ι → ℤ) (h t : ℤ) (A B : Matrix ι ι R)
+ (d : ℕ) (i j : ι) :
+ ((T (R := R) 2 - 1) ^ d * (energyField energy h A * B.map C) i j).coeff t =
+ ∑ a : Fin (d + 1), (-1 : R) ^ (a : ℕ) * d.choose a *
+ (let q := t + h - (d - (a : ℕ) : ℕ) * (2 : ℤ)
+ (energyMode energy A q * energyMode energy B (energy i - energy j - q)) i j) := by
+ classical
+ rw [binomial_laurent, Finset.sum_mul, AddMonoidAlgebra.coeff_sum, Finsupp.finsetSum_apply]
+ apply Finset.sum_congr rfl
+ intro a _
+ simp only [Matrix.mul_apply, Finset.mul_sum, AddMonoidAlgebra.coeff_sum,
+ Finsupp.finsetSum_apply, Matrix.map_apply, energyField]
+ apply Finset.sum_congr rfl
+ intro k _
+ rw [monomial_coeff_product]
+ dsimp only [energyMode]
+ split_ifs <;> first | (exfalso; omega) | ring
+
+/-- Coefficient between states of the same energy. -/
+theorem forward_coeff (energy : ι → ℤ) (h t : ℤ) (A B : Matrix ι ι R)
+ (d : ℕ) (i j : ι) (hij : energy i = energy j) :
+ ((T (R := R) 2 - 1) ^ d * (energyField energy h A * B.map C) i j).coeff t =
+ ∑ a : Fin (d + 1), (-1 : R) ^ (a : ℕ) * d.choose a *
+ (let q := t + h - (d - (a : ℕ) : ℕ) * (2 : ℤ)
+ (energyMode energy A q * energyMode energy B (-q)) i j) := by
+ simpa only [hij, sub_self, zero_sub] using forward_coeff_any_energy energy h t A B d i j
+
+/-- Read the same Laurent coefficient with the two operators in reverse order. -/
+theorem reverse_coeff_any_energy (energy : ι → ℤ) (h t : ℤ) (A B : Matrix ι ι R)
+ (d : ℕ) (i j : ι) :
+ ((T (R := R) 2 - 1) ^ d * (B.map C * energyField energy h A) i j).coeff t =
+ ∑ a : Fin (d + 1), (-1 : R) ^ (a : ℕ) * d.choose a *
+ (let q := t + h - (d - (a : ℕ) : ℕ) * (2 : ℤ)
+ (energyMode energy B (energy i - energy j - q) * energyMode energy A q) i j) := by
+ classical
+ rw [binomial_laurent, Finset.sum_mul, AddMonoidAlgebra.coeff_sum, Finsupp.finsetSum_apply]
+ apply Finset.sum_congr rfl
+ intro a _
+ simp only [Matrix.mul_apply, Finset.mul_sum, AddMonoidAlgebra.coeff_sum,
+ Finsupp.finsetSum_apply, Matrix.map_apply, energyField]
+ apply Finset.sum_congr rfl
+ intro k _
+ rw [mul_comm (C (B i k)) (C (A k j) * T _), monomial_coeff_product]
+ dsimp only [energyMode]
+ split_ifs <;> first | (exfalso; omega) | ring
+
+/-- Coefficient between states of the same energy. -/
+theorem reverse_coeff (energy : ι → ℤ) (h t : ℤ) (A B : Matrix ι ι R)
+ (d : ℕ) (i j : ι) (hij : energy i = energy j) :
+ ((T (R := R) 2 - 1) ^ d * (B.map C * energyField energy h A) i j).coeff t =
+ ∑ a : Fin (d + 1), (-1 : R) ^ (a : ℕ) * d.choose a *
+ (let q := t + h - (d - (a : ℕ) : ℕ) * (2 : ℤ)
+ (energyMode energy B (-q) * energyMode energy A q) i j) := by
+ simpa only [hij, sub_self, zero_sub] using reverse_coeff_any_energy energy h t A B d i j
+
+
+/-- The product of two modes vanishes outside its total energy shift. -/
+theorem modes_off_energy (energy : ι → ℤ) (A B : Matrix ι ι R)
+ (r s : ℤ) (i j : ι) (hij : energy i - energy j ≠ r+s) :
+ (energyMode energy A r * energyMode energy B s) i j = 0 := by
+ rw [Matrix.mul_apply]
+ apply Finset.sum_eq_zero
+ intro k _
+ dsimp only [energyMode]
+ split_ifs <;> first | (exfalso; omega) | simp
+
+/-- Opposite energy changes give zero on matrix entries of different energies. -/
+theorem opposite_modes_off_energy (energy : ι → ℤ) (A B : Matrix ι ι R)
+ (q : ℤ) (i j : ι) (hij : energy i ≠ energy j) :
+ (energyMode energy A q * energyMode energy B (-q)) i j = 0 :=
+ modes_off_energy energy A B q (-q) i j (by omega)
+
+/-- Bivariate coefficient readout between states whose energy difference agrees
+with the total degree of the selected monomial. The two exponents of the fields
+are `p-d+a` and `q-a` before multiplication by the binomial. -/
+theorem bivariate_supercommutator_readout (energy : ι → ℤ) (A B : Matrix ι ι R)
+ (hA hB p q : ℤ) (ε : R) (d : ℕ) (hd : 2 * (d : ℤ) + 2 = hA + hB)
+ (i j : ι) (hij : energy i - energy j = 2*(p+q+1)) :
+ ((T (R := R) 2 - 1) ^ d * (energyField energy hA A * B.map C) i j).coeff (2*p) -
+ ε * ((T (R := R) 2 - 1) ^ d * (B.map C * energyField energy hA A) i j).coeff (2*p) =
+ ∑ a : Fin (d+1), (-1 : R)^(a : ℕ) * d.choose a *
+ (let r := 2*(p-d+(a:ℕ))+hA
+ let s := 2*(q-(a:ℕ))+hB
+ (energyMode energy A r * energyMode energy B s) i j -
+ ε * (energyMode energy B s * energyMode energy A r) i j) := by
+ rw [forward_coeff_any_energy, reverse_coeff_any_energy, Finset.mul_sum, ← Finset.sum_sub_distrib]
+ apply Finset.sum_congr rfl
+ intro a _
+ have ha := a.isLt
+ have hr : 2*p+hA - (d-(a:ℕ):ℕ)*(2:ℤ) = 2*(p-d+(a:ℕ))+hA := by omega
+ have hs : energy i - energy j - (2*(p-d+(a:ℕ))+hA) = 2*(q-(a:ℕ))+hB := by omega
+ dsimp only
+ rw [hr, hs]
+ ring
+
+/-- With doubled energies and the paper's coefficient index `s`, the first order
+raises the intermediate energy by `2 * s+hB-2*a` and the second order lowers it
+by the same amount. Here `ε` is the sign in the supercommutator. -/
+theorem shifted_supercommutator_readout (energy : ι → ℤ) (A B : Matrix ι ι R)
+ (hA hB s : ℤ) (ε : R) (d : ℕ) (hd : 2 * (d : ℤ) + 2 = hA + hB)
+ (i j : ι) (hij : energy i = energy j) :
+ ((T (R := R) 2 - 1) ^ d * (energyField energy hA A * B.map C) i j).coeff (-2 * s - 2) -
+ ε * ((T (R := R) 2 - 1) ^ d * (B.map C * energyField energy hA A) i j).coeff (-2 * s - 2) =
+ ∑ a : Fin (d + 1), (-1 : R) ^ (a : ℕ) * d.choose a *
+ (let q := 2 * s + hB - 2 * (a : ℕ)
+ (energyMode energy A (-q) * energyMode energy B q) i j -
+ ε * (energyMode energy B q * energyMode energy A (-q)) i j) := by
+ rw [forward_coeff energy hA _ A B d i j hij, reverse_coeff energy hA _ A B d i j hij,
+ Finset.mul_sum, ← Finset.sum_sub_distrib]
+ apply Finset.sum_congr rfl
+ intro a _
+ have ha := a.isLt
+ have hq : -2 * s - 2 + hA - (d - (a : ℕ) : ℕ) * (2 : ℤ) =
+ -(2 * s + hB - 2 * (a : ℕ)) := by omega
+ simp only [hq, neg_neg]
+ ring
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShiftedResidue.lean b/lean/OAI/Computability/VPVNP/ShiftedResidue.lean
new file mode 100644
index 0000000000..4fdc2d2cee
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShiftedResidue.lean
@@ -0,0 +1,473 @@
+import Lemmata.FockCircuits.SignedKernel
+
+/-!
+# Shifted fermionic residues
+
+Appendix B, equation (B.1), of *VP and VNP differ over every field* extracts a
+different coefficient for every shift. Khoruzhii's `weighted_matrix_residue`
+computes the constant coefficient. Here the extra factor `T² - 1` clears every
+matched pole. On a finite window of Laurent exponents the two resulting
+Wick expansions agree, so the even coefficients of the original commutator
+all equal its constant coefficient. Widening the mode cutoff permits any
+integer shift. We use Khoruzhii's integer-valued doubled energies throughout.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open LaurentPolynomial
+
+/-- Multiplication by the Laurent binomial gives the difference of consecutive
+coefficients of the same parity. -/
+theorem coeff_T_two_sub_one_mul {R : Type*} [Ring R]
+ (f : LaurentPolynomial R) (j : ℤ) :
+ ((T 2 - 1) * f).coeff j = f.coeff (j - 2) - f.coeff j := by
+ rw [sub_mul, one_mul, AddMonoidAlgebra.coeff_sub, Finsupp.sub_apply, T,
+ AddMonoidAlgebra.coeff_single_mul_apply, one_mul, neg_add_eq_sub]
+
+/-- If the Laurent binomial clears the coefficients in a symmetric window, all
+even coefficients of the original polynomial in that window equal its constant term. -/
+theorem even_coeff_eq_zero_coeff {R : Type*} [Ring R]
+ (f : LaurentPolynomial R) (B : ℤ)
+ (h : ∀ j : ℤ, |j| ≤ B → ((T 2 - 1) * f).coeff j = 0)
+ (k : ℤ) (hk : |2 * k| ≤ B) :
+ f.coeff (2 * k) = f.coeff 0 := by
+ have step (j : ℤ) (hj : -B ≤ j ∧ j ≤ B) : f.coeff (j - 2) = f.coeff j := by
+ exact sub_eq_zero.mp ((coeff_T_two_sub_one_mul f j).symm.trans (h j (abs_le.mpr hj)))
+ rw [abs_le] at hk
+ induction k using Int.induction_on with
+ | zero => simp
+ | succ n ih =>
+ rw [← step _ hk]
+ have he : 2 * ((n : ℤ) + 1) - 2 = 2 * (n : ℤ) := by omega
+ rw [he]
+ exact ih (by omega)
+ | pred n ih =>
+ have hs := step (2 * -(n : ℤ)) (by omega)
+ have he : 2 * (-(n : ℤ) - 1) = 2 * -(n : ℤ) - 2 := by omega
+ rw [he, hs]
+ exact ih (by omega)
+
+end Crossing
+
+set_option autoImplicit false
+
+open scoped BigOperators
+namespace Crossing
+
+open Lemmata.FockCircuits Lemmata.FockCircuits.FiniteIdentity
+variable (R : Type*) [CommRing R]
+
+private theorem coeff_mul_shift (p : LaurentPolynomial R) (k : ℤ) :
+ (p * LaurentPolynomial.T (-k)).coeff 0 = p.coeff k := by
+ change (p * AddMonoidAlgebra.single (-k) (1 : R)).coeff 0 = p.coeff k
+ simp only [AddMonoidAlgebra.coeff_mul_single_apply, neg_neg, zero_add, mul_one]
+
+private theorem coeff_weighted_scalar (c : R) (s p v : LaurentPolynomial R) (k : ℤ) :
+ (s * (LaurentPolynomial.C c * p) * v).coeff k = c * (s * p * v).coeff k := by
+ have he : s * (LaurentPolynomial.C c * p) * v = LaurentPolynomial.C c * (s * p * v) := by ring
+ rw [he, ← LaurentPolynomial.single_eq_C, AddMonoidAlgebra.coeff_single_mul_apply]
+ simp
+
+private theorem shifted_replacements (L e K W w d : ℕ) (k : ℤ) (P : List (ℕ × ℕ))
+ (hpole : poleSum P ≤ d) (hdegree : 2 * d + 2 = W + w)
+ (hleft : pairedLeftWeight P ≤ w) (hright : pairedRightWeight P ≤ W)
+ (hw : w ≤ W) (hcut : e + K + W ≤ 2 * L) (hk : -(K : ℤ) ≤ k ∧ k ≤ K)
+ (v : LaurentPolynomial R)
+ (hu : UpperBound R v ((e : ℤ) - (w - pairedLeftWeight P : ℕ)))
+ (hl : LowerBound R v (-(e : ℤ) - (w - pairedLeftWeight P : ℕ))) :
+ ((((LaurentPolynomial.T 2 : LaurentPolynomial R) - 1) ^ d *
+ (P.map fun p => forwardTail R 0 L p.1 p.2).prod * v).coeff k =
+ (((LaurentPolynomial.T 2 : LaurentPolynomial R) - 1) ^ (d - poleSum P) *
+ (P.map (pairConstant R)).prod * v).coeff k) ∧
+ ((((LaurentPolynomial.T 2 : LaurentPolynomial R) - 1) ^ d *
+ (P.map fun p => reverseTail R 0 L p.1 p.2).prod * v).coeff k =
+ (((LaurentPolynomial.T 2 : LaurentPolynomial R) - 1) ^ (d - poleSum P) *
+ (P.map fun p => -pairConstant R p).prod * v).coeff k) := by
+ have htu : UpperBound R (LaurentPolynomial.T (-k)) (-k) := by
+ simpa using upperBound_monomial R 1 (-k) (-k) le_rfl
+ have htl : LowerBound R (LaurentPolynomial.T (-k)) (-k) := by
+ simpa using lowerBound_monomial R 1 (-k) (-k) le_rfl
+ have hu' := upperBound_mono R (upperBound_mul R hu htu)
+ (show (e : ℤ) - (w - pairedLeftWeight P : ℕ) + -k ≤
+ (↑(e + K) : ℤ) - (w - pairedLeftWeight P : ℕ) by omega)
+ have hl' := lowerBound_mono R (lowerBound_mul R hl htl)
+ (show -(↑(e + K) : ℤ) - (w - pairedLeftWeight P : ℕ) ≤
+ -(e : ℤ) - (w - pairedLeftWeight P : ℕ) + -k by omega)
+ obtain ⟨hf, hr⟩ := cutoff_partial_replacements R L (e + K) W w d P hpole
+ hdegree hleft hright hw hcut (v * LaurentPolynomial.T (-k)) hu' hl'
+ rw [← mul_assoc _ v _, coeff_mul_shift, ← mul_assoc _ v _, coeff_mul_shift] at hf hr
+ exact ⟨hf, hr⟩
+
+private theorem forward_actualTerm_local (L K : ℕ) {A B : List ℕ} {t : Matching.Term SourceIndex}
+ (ht : t ∈ Matching.terms (A.map Sum.inl) (B.map Sum.inr)) (d : ℕ)
+ (hdegree : 2 * d + 2 = sourceEnergy A + sourceEnergy B)
+ (hw : sourceEnergy A ≤ sourceEnergy B) (I J : Finset ℕ)
+ (hIJ : doubledEnergy I = doubledEnergy J)
+ (hcut : doubledEnergy I + K + sourceEnergy B + 2 ≤ 2 * L)
+ (k : ℤ) (hk : -(K : ℤ) ≤ k ∧ k ≤ K) :
+ (actualTerm R L (d + 1) t I J).coeff k = (commonTerm R L (d + 1) t I J).coeff k := by
+ have hp : poleSum (orientedPairs t) ≤ d + 1 := by
+ by_cases hempty : t.remaining = []
+ · exact (forward_full_pole ht hempty d hdegree).le
+ · exact Nat.le_succ_of_le (forward_partial_pole ht hempty d hdegree)
+ have hleft := forward_left_conservation ht
+ have hright := forward_right_conservation ht
+ have hv := forward_partial_coefficient_bounds R L ht I J hIJ
+ rw [actualTerm, forward_matching_coefficient R L ht, coeff_weighted_scalar,
+ commonTerm, ite_eq_left hp, forward_common_coefficient R ht, coeff_weighted_scalar]
+ exact congrArg (fun a : R => (t.sign : R) * a)
+ (shifted_replacements R L (doubledEnergy I) K (sourceEnergy B + 2)
+ (sourceEnergy A) (d + 1) k (orientedPairs t) hp (by omega) (by omega)
+ (by omega) (by omega) (by omega) hk _ hv.1 hv.2).1
+
+private theorem reverse_actualTerm_local (L K : ℕ) {A B : List ℕ} {t : Matching.Term SourceIndex}
+ (ht : t ∈ Matching.terms (B.map Sum.inr) (A.map Sum.inl)) (d : ℕ)
+ (hdegree : 2 * d + 2 = sourceEnergy A + sourceEnergy B)
+ (hw : sourceEnergy A ≤ sourceEnergy B) (I J : Finset ℕ)
+ (hIJ : doubledEnergy I = doubledEnergy J)
+ (hcut : doubledEnergy I + K + sourceEnergy B + 2 ≤ 2 * L)
+ (k : ℤ) (hk : -(K : ℤ) ≤ k ∧ k ≤ K) :
+ (actualTerm R L (d + 1) t I J).coeff k = (commonTerm R L (d + 1) t I J).coeff k := by
+ have hp : poleSum (orientedPairs t) ≤ d + 1 := by
+ by_cases hempty : t.remaining = []
+ · exact (reverse_full_pole ht hempty d hdegree).le
+ · exact Nat.le_succ_of_le (reverse_partial_pole ht hempty d hdegree)
+ have hleft := reverse_left_conservation ht
+ have hright := reverse_right_conservation ht
+ have hv := reverse_partial_coefficient_bounds R L ht I J hIJ
+ rw [actualTerm, reverse_matching_coefficient R L ht, coeff_weighted_scalar,
+ commonTerm, ite_eq_left hp, reverse_common_coefficient R ht, coeff_weighted_scalar]
+ exact congrArg (fun a : R => (t.sign : R) * a)
+ (shifted_replacements R L (doubledEnergy I) K (sourceEnergy B + 2)
+ (sourceEnergy A) (d + 1) k (orientedPairs t) hp (by omega) (by omega)
+ (by omega) (by omega) (by omega) hk _ hv.1 hv.2).2
+
+/-- Extracting a Laurent coefficient commutes with the sum over Wick matchings. -/
+private theorem wickCoeff_list_sum (P : List (LaurentPolynomial R)) (k : ℤ) :
+ P.sum.coeff k = (P.map fun p => p.coeff k).sum := by
+ induction P with
+ | nil => simp
+ | cons p P ih =>
+ simp only [List.sum_cons, AddMonoidAlgebra.coeff_add, Finsupp.add_apply, ih, List.map_cons]
+
+private theorem productPolynomial_coeff_of_terms (L d : ℕ) (A B : List SourceIndex)
+ (I J : Finset ℕ) (k : ℤ)
+ (h : ∀ t ∈ Matching.terms A B,
+ (actualTerm R L d t I J).coeff k = (commonTerm R L d t I J).coeff k) :
+ (productPolynomial R L d A B I J).coeff k =
+ (((Matching.terms A B).map fun t => commonTerm R L d t I J).sum).coeff k := by
+ rw [productPolynomial_eq_sum, wickCoeff_list_sum, wickCoeff_list_sum]
+ simp only [List.map_map, Function.comp_def]
+ exact congrArg List.sum (List.map_congr_left h)
+
+/-- When the multiplier cancels every pole at a specified coefficient, the signed
+commutator vanishes at that coefficient. The two products use opposite normal orders. -/
+theorem weighted_matrix_locality_of_terms (L d : ℕ) (A B I J : Index L) (k : ℤ)
+ (hforward : ∀ t ∈ Matching.terms (A.val.sort.map Sum.inl) (B.val.sort.map Sum.inr),
+ (actualTerm R L d t I.val J.val).coeff k = (commonTerm R L d t I.val J.val).coeff k)
+ (hreverse : ∀ t ∈ Matching.terms (B.val.sort.map Sum.inr) (A.val.sort.map Sum.inl),
+ (actualTerm R L d t I.val J.val).coeff k = (commonTerm R L d t I.val J.val).coeff k) :
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d *
+ (scaledMatrix R L A * constantMatrix R L B) I J).coeff k -
+ ((-1 : ℤˣ) ^ (A.val.sort.length * B.val.sort.length)) •
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d *
+ (constantMatrix R L B * scaledMatrix R L A) I J).coeff k = 0 := by
+ let u : ℤˣ := (-1) ^ (A.val.sort.length * B.val.sort.length)
+ have h : (productPolynomial R L d (A.val.sort.map Sum.inl) (B.val.sort.map Sum.inr)
+ I.val J.val).coeff k = u • (productPolynomial R L d (B.val.sort.map Sum.inr)
+ (A.val.sort.map Sum.inl) I.val J.val).coeff k := by
+ rw [productPolynomial_coeff_of_terms R _ _ _ _ _ _ _ hforward,
+ productPolynomial_coeff_of_terms R _ _ _ _ _ _ _ hreverse]
+ simpa only [u, Units.smul_def, AddMonoidAlgebra.coeff_smul_apply] using
+ congrArg (fun p : LaurentPolynomial R => p.coeff k)
+ (common_sum_exchange R L d A.val.sort B.val.sort I.val J.val)
+ rw [forward_productPolynomial_matrix, reverse_productPolynomial_matrix] at h
+ have hC : (dualSign J.val : LaurentPolynomial R) = LaurentPolynomial.C (dualSign J.val : R) :=
+ by simp
+ rw [hC] at h
+ simp only [← LaurentPolynomial.single_eq_C, AddMonoidAlgebra.coeff_single_mul_apply,
+ neg_zero, zero_add] at h
+ let e : R := (dualSign J.val : R)
+ have hs : e * e = 1 := by
+ simpa only [e, Int.cast_mul, Int.cast_one] using
+ congrArg (fun z : ℤ => (z : R)) (dualSign_mul_self J.val)
+ let a := ((LaurentPolynomial.T (R := R) 2 - 1) ^ d *
+ (scaledMatrix R L A * constantMatrix R L B) I J).coeff k
+ let b := ((LaurentPolynomial.T (R := R) 2 - 1) ^ d *
+ (constantMatrix R L B * scaledMatrix R L A) I J).coeff k
+ change e * a = u • (e * b) at h
+ change a - u • b = 0
+ apply sub_eq_zero.mpr
+ calc
+ a = e * (e * a) := by rw [← mul_assoc, hs, one_mul]
+ _ = e * (u • (e * b)) := by rw [h]
+ _ = u • b := by
+ simp only [Units.smul_def, zsmul_eq_mul]
+ calc
+ _ = (u : ℤ) * ((e * e) * b) := by ring
+ _ = _ := by rw [hs, one_mul]
+
+/-- The residue of the two ordered fermion fields at every even Laurent exponent in
+the cutoff window. Exponent `2 * j` corresponds to the bivariate coefficient with
+paper shift `s = -j-1`. -/
+theorem shifted_weighted_matrix_residue (L K : ℕ) (A B I J : Index L) (d : ℕ)
+ (hdegree : 2 * d + 2 = sourceEnergy A.val.sort + sourceEnergy B.val.sort)
+ (hw : sourceEnergy A.val.sort ≤ sourceEnergy B.val.sort)
+ (hIJ : doubledEnergy I.val = doubledEnergy J.val)
+ (hcut : doubledEnergy I.val + K + sourceEnergy B.val.sort + 2 ≤ 2 * L)
+ (j : ℤ) (hj : |2 * j| ≤ K) :
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d *
+ (scaledMatrix R L A * constantMatrix R L B) I J).coeff (2 * j) -
+ ((-1 : ℤˣ) ^ (A.val.sort.length * B.val.sort.length)) •
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d *
+ (constantMatrix R L B * scaledMatrix R L A) I J).coeff (2 * j) =
+ (if I = J then (1 : R) else 0) * matrix R L (Pi.single A 1) ⟨∅, by simp⟩ B := by
+ let x := (scaledMatrix R L A * constantMatrix R L B) I J
+ let y := (constantMatrix R L B * scaledMatrix R L A) I J
+ let u : ℤˣ := (-1 : ℤˣ) ^ (A.val.sort.length * B.val.sort.length)
+ let t := LaurentPolynomial.T (R := R) 2 - 1
+ let f (a : ℕ) := t ^ a * x - LaurentPolynomial.C ((u : ℤ) : R) * (t ^ a * y)
+ have hcoeff (a : ℕ) (k : ℤ) :
+ (f a).coeff k = (t ^ a * x).coeff k - u • (t ^ a * y).coeff k := by
+ simp only [f, AddMonoidAlgebra.coeff_sub, Finsupp.sub_apply, ← LaurentPolynomial.single_eq_C,
+ AddMonoidAlgebra.coeff_single_mul_apply, neg_zero, zero_add, Units.smul_def, zsmul_eq_mul]
+ have hmul : t * f d = f (d + 1) := by
+ dsimp only [f]
+ rw [pow_succ]
+ ring
+ have hlocal (k : ℤ) (hk : |k| ≤ K) : (t * f d).coeff k = 0 := by
+ rw [hmul, hcoeff]
+ apply weighted_matrix_locality_of_terms R L (d + 1) A B I J k
+ · intro m hm
+ exact forward_actualTerm_local R L K hm d hdegree hw I.val J.val hIJ hcut k (abs_le.mp hk)
+ · intro m hm
+ exact reverse_actualTerm_local R L K hm d hdegree hw I.val J.val hIJ hcut k (abs_le.mp hk)
+ have he := VPVNP.Crossing.even_coeff_eq_zero_coeff (f d) (K : ℤ) hlocal j hj
+ rw [hcoeff, hcoeff] at he
+ exact he.trans (weighted_matrix_residue R L A B I J d hdegree hw hIJ (by omega))
+
+end Crossing
+
+open Lemmata.FockCircuits
+open Lemmata.FockCircuits.FiniteIdentity
+namespace Crossing
+
+private def mapTerm {α β : Type*} (f : α → β) (t : Matching.Term α) : Matching.Term β :=
+ ⟨t.sign, t.pairs.map (Prod.map f f), t.remaining.map f⟩
+
+private lemma map_terms {α β : Type*} (f : α → β) (A B : List α) :
+ (Matching.terms A B).map (mapTerm f) = Matching.terms (A.map f) (B.map f) := by
+ induction A generalizing B with
+ | nil => simp [Matching.terms, mapTerm]
+ | cons a A ih =>
+ simp only [List.map_cons, Matching.terms, List.map_append, List.map_map,
+ List.map_flatten, List.map_ofFn]
+ congr 1
+ · rw [← ih]
+ simp only [List.map_map]
+ rfl
+ · apply congrArg List.flatten
+ rw [List.ofFn_congr (List.length_map (f := f) (as := B)).symm]
+ apply congrArg List.ofFn
+ funext j
+ simp only [Function.comp_def, Fin.val_cast, List.map_map, List.eraseIdx_map,
+ ← ih, Fin.getElem_fin, List.getElem_map, List.length_map]
+ rfl
+
+private theorem reverseFullSum_eq_swapped (R : Type*) [CommRing R] (A B : List ℕ) :
+ reverseFullSum R A B =
+ fullMatchingSum R
+ (Matching.crossGamma R fun m n => (Fock.contractionCoefficient m n : R))
+ (Matching.terms (B.map Sum.inl) (A.map Sum.inr)) := by
+ let flip : SourceIndex → SourceIndex := Sum.elim Sum.inr Sum.inl
+ have h := map_terms flip (B.map Sum.inr) (A.map Sum.inl)
+ have hB : (B.map Sum.inr).map flip = B.map Sum.inl := by simp [flip, List.map_map]
+ have hA : (A.map Sum.inl).map flip = A.map Sum.inr := by simp [flip, List.map_map]
+ rw [hB, hA] at h
+ rw [reverseFullSum, ← h, fullMatchingSum, List.map_map]
+ apply congrArg List.sum
+ apply List.map_congr_left
+ intro t ht
+ simp only [Function.comp_def, mapTerm, List.map_eq_nil_iff]
+ split_ifs
+ · unfold Matching.coefficient
+ congr 1
+ unfold orientedPairs
+ simp only [List.map_map]
+ apply congrArg List.prod
+ apply List.map_congr_left
+ intro p hp
+ obtain ⟨hl, hr⟩ := Matching.pair_mem_sources ht hp
+ obtain ⟨n, _, hn⟩ := List.mem_map.mp hl
+ obtain ⟨m, _, hm⟩ := List.mem_map.mp hr
+ have he : p = (Sum.inr n, Sum.inl m) := Prod.ext hn.symm hm.symm
+ rw [he]
+ rfl
+ · rfl
+
+/-- Transposing the two operator-source labels gives the sign from reflecting
+the variable difference and exchanging the two fermionic blocks. -/
+theorem matrix_vacuum_exchange (R : Type*) [CommRing R] (L : ℕ) (A B : Index L) (d : ℕ)
+ (hd : 2 * d + 2 = sourceEnergy A.val.sort + sourceEnergy B.val.sort) :
+ matrix R L (Pi.single A 1) ⟨∅, by simp⟩ B =
+ ((-1 : ℤˣ) ^ (A.val.sort.length * B.val.sort.length)) •
+ ((-1 : R) ^ (d + 1) * matrix R L (Pi.single B 1) ⟨∅, by simp⟩ A) := by
+ rw [matrix_single_vacuum_eq_fullMatchingSum, matrix_single_vacuum_eq_fullMatchingSum,
+ fullMatchingSum_exchange R _ _ d hd, reverse_fullMatchingSum R _ _ d hd,
+ reverseFullSum_eq_swapped]
+
+end Crossing
+
+namespace Crossing
+
+open Lemmata.FockCircuits Lemmata.FockCircuits.FiniteIdentity
+
+variable (R : Type*) [CommRing R]
+
+section
+open LaurentPolynomial
+
+/-- Inverting the Laurent variable reflects the pole-clearing multiplier. -/
+private theorem invert_multiplier (d : ℕ) :
+ invert ((T (R := R) 2 - 1) ^ d) = (-1) ^ d * T (-(2 * (d : ℤ))) * (T 2 - 1) ^ d := by
+ have ht : T (R := R) (-2) * T 2 = 1 := by rw [← T_add]; norm_num
+ have h : T (R := R) (-2) - 1 = -1 * T (-2) * (T 2 - 1) := by
+ rw [neg_one_mul, neg_mul, mul_sub, mul_one, ht]
+ ring
+ simp only [map_pow, map_sub, invert_T, map_one]
+ rw [h, mul_pow, mul_pow, T_pow]
+ congr 2
+ ring_nf
+
+private theorem shift_coeff (f : LaurentPolynomial R) (n j : ℤ) :
+ (T n * f).coeff j = f.coeff (j - n) := by
+ rw [T, AddMonoidAlgebra.coeff_single_mul_apply]
+ simp [sub_eq_add_neg, add_comm]
+
+/-- For equal external energy, the Laurent powers of the two fields in a matrix-product
+entry add to minus the sum of the two source energies. Swapping the source whose Laurent
+variable is recorded reflects the index about `-1`. -/
+private theorem reflected_term (w W x y : ℤ) (d : ℕ) (s : ℤ) (v : R)
+ (hd : 2 * (d : ℤ) + 2 = w + W) (hxy : x + y = -(w + W)) :
+ ((T (R := R) 2 - 1) ^ d * (C v * T x)).coeff (2*s) =
+ (-1) ^ d * ((T (R := R) 2 - 1) ^ d * (C v * T y)).coeff (-2*s-2) := by
+ have h := invert_multiplier (R := R) d
+ have ht : T (R := R) (-(2*(d:ℤ))) * T (-y) = T 2 * T x := by
+ rw [← T_add, ← T_add]
+ congr 1
+ omega
+ have he : invert ((T (R := R) 2 - 1) ^ d * (C v * T y)) =
+ C ((-1 : R) ^ d) * (T 2 * ((T 2 - 1) ^ d * (C v * T x))) := by
+ simp only [map_mul, h, invert_C, invert_T]
+ rw [map_pow, map_neg, map_one]
+ calc
+ _ = (-1) ^ d * ((T (R := R) 2 - 1) ^ d * C v) *
+ (T (-(2*(d:ℤ))) * T (-y)) := by ring
+ _ = _ := by rw [ht]; ring
+ have hec := congrArg (fun f : LaurentPolynomial R => f.coeff (2*s+2)) he
+ simp only [invert_apply, ← LaurentPolynomial.single_eq_C, AddMonoidAlgebra.coeff_single_mul_apply,
+ neg_zero, zero_add, shift_coeff] at hec
+ rw [show -(2 * s + 2) = -2*s - 2 by ring, add_sub_cancel_right] at hec
+ simp only [LaurentPolynomial.single_eq_C] at hec
+ have hs : (-1 : R) ^ d * (-1) ^ d = 1 := by rw [← mul_pow]; simp
+ rw [hec, ← mul_assoc ((-1 : R) ^ d), hs, one_mul]
+
+
+end
+private theorem reflect_mode_mul_constant (c c' : R) (e : ℤ) :
+ (LaurentPolynomial.C c * LaurentPolynomial.T (R := R) e) * LaurentPolynomial.C c' =
+ LaurentPolynomial.C (c*c') * LaurentPolynomial.T e := by
+ rw [map_mul]
+ ring
+
+private theorem reflect_constant_mul_mode (c c' : R) (e : ℤ) :
+ LaurentPolynomial.C c * (LaurentPolynomial.C c' * LaurentPolynomial.T (R := R) e) =
+ LaurentPolynomial.C (c*c') * LaurentPolynomial.T e := by
+ rw [map_mul, mul_assoc]
+
+
+
+/-- Switching the field that carries the Laurent variable reflects the selected
+coefficient and interchanges the two ordered products. -/
+private theorem forward_matrix_reflect (L d : ℕ) (A B I J : Index L) (j : ℤ)
+ (hd : 2 * d + 2 = doubledEnergy A.val + doubledEnergy B.val)
+ (hIJ : doubledEnergy I.val = doubledEnergy J.val) :
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (scaledMatrix R L A * constantMatrix R L B) I J).coeff (2 * j) =
+ (-1) ^ d * ((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (constantMatrix R L A * scaledMatrix R L B) I J).coeff (-2 * j - 2) := by
+ classical
+ simp only [Matrix.mul_apply, Finset.mul_sum, AddMonoidAlgebra.coeff_sum, Finsupp.finsetSum_apply,
+ scaledMatrix_eq_monomial, constantMatrix, reflect_mode_mul_constant, reflect_constant_mul_mode]
+ apply Finset.sum_congr rfl
+ intro K _
+ exact reflected_term R (doubledEnergy A.val) (doubledEnergy B.val) _ _ d j _ (by omega) (by omega)
+
+private theorem reverse_matrix_reflect (L d : ℕ) (A B I J : Index L) (j : ℤ)
+ (hd : 2 * d + 2 = doubledEnergy A.val + doubledEnergy B.val)
+ (hIJ : doubledEnergy I.val = doubledEnergy J.val) :
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (constantMatrix R L B * scaledMatrix R L A) I J).coeff (2 * j) =
+ (-1) ^ d * ((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (scaledMatrix R L B * constantMatrix R L A) I J).coeff (-2 * j - 2) := by
+ classical
+ simp only [Matrix.mul_apply, Finset.mul_sum, AddMonoidAlgebra.coeff_sum, Finsupp.finsetSum_apply,
+ scaledMatrix_eq_monomial, constantMatrix, reflect_mode_mul_constant, reflect_constant_mul_mode]
+ apply Finset.sum_congr rfl
+ intro K _
+ exact reflected_term R (doubledEnergy A.val) (doubledEnergy B.val) _ _ d j _ (by omega) (by omega)
+
+/-- The Laurent coefficient of the signed commutator at `2j` in orientation `(A,B)`
+is the coefficient at `2(-j - 1)` in the opposite orientation, up to the explicit sign. -/
+theorem commutator_reflect (L d : ℕ) (A B I J : Index L) (j : ℤ)
+ (hd : 2 * d + 2 = sourceEnergy A.val.sort + sourceEnergy B.val.sort)
+ (hIJ : doubledEnergy I.val = doubledEnergy J.val) :
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (scaledMatrix R L A * constantMatrix R L B) I J).coeff (2 * j) -
+ ((-1 : ℤˣ) ^ (A.val.sort.length * B.val.sort.length)) •
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (constantMatrix R L B * scaledMatrix R L A) I J).coeff (2 * j) =
+ -(((-1 : ℤˣ) ^ (A.val.sort.length * B.val.sort.length)) • ((-1 : R) ^ d)) *
+ (((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (scaledMatrix R L B * constantMatrix R L A) I J).coeff (2 * (-j - 1)) -
+ ((-1 : ℤˣ) ^ (B.val.sort.length * A.val.sort.length)) •
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (constantMatrix R L A * scaledMatrix R L B) I J).coeff (2 * (-j - 1))) := by
+ rw [sourceEnergy_sort, sourceEnergy_sort] at hd
+ rw [forward_matrix_reflect R L d A B I J j hd hIJ, reverse_matrix_reflect R L d A B I J j hd hIJ,
+ show 2 * (-j - 1) = -2 * j - 2 by ring, Nat.mul_comm (B.val.sort (· ≤ ·)).length (A.val.sort (· ≤ ·)).length]
+ simp only [Units.smul_def, zsmul_eq_mul, Units.val_pow_eq_pow_val, Units.val_neg, Units.val_one,
+ Int.cast_pow, Int.cast_neg, Int.cast_one]
+ generalize ((LaurentPolynomial.T (R := R) 2 - 1) ^ d *
+ (scaledMatrix R L B * constantMatrix R L A) I J).coeff (-2 * j - 2) = a
+ generalize ((LaurentPolynomial.T (R := R) 2 - 1) ^ d *
+ (constantMatrix R L A * scaledMatrix R L B) I J).coeff (-2 * j - 2) = b
+ generalize (A.val.sort (· ≤ ·)).length * (B.val.sort (· ≤ ·)).length = n
+ have hs : (-1 : R)^n * (-1)^n = 1 := by rw [← mul_pow]; simp
+ linear_combination (-1 : R) ^ d * b * (Eq.symm hs)
+
+
+/-- The shifted coefficient identity in both orientations of the input blocks. A single
+cutoff suffices for exponent `2 * j` and its reflected exponent `2 * (-j - 1)`. -/
+theorem shifted_weighted_matrix_residue_all (L K : ℕ) (A B I J : Index L) (d : ℕ)
+ (hd : 2 * d + 2 = sourceEnergy A.val.sort + sourceEnergy B.val.sort)
+ (hIJ : doubledEnergy I.val = doubledEnergy J.val)
+ (hcut : doubledEnergy I.val + K + max (sourceEnergy A.val.sort) (sourceEnergy B.val.sort) + 4 ≤ 2 * L)
+ (j : ℤ) (hj : |2 * j| ≤ K) :
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (scaledMatrix R L A * constantMatrix R L B) I J).coeff (2 * j) -
+ ((-1 : ℤˣ) ^ (A.val.sort.length * B.val.sort.length)) •
+ ((LaurentPolynomial.T (R := R) 2 - 1) ^ d * (constantMatrix R L B * scaledMatrix R L A) I J).coeff (2 * j) =
+ (if I = J then (1 : R) else 0) * matrix R L (Pi.single A 1) ⟨∅, by simp⟩ B := by
+ by_cases h : sourceEnergy A.val.sort ≤ sourceEnergy B.val.sort
+ · exact shifted_weighted_matrix_residue R L K A B I J d hd h hIJ (by omega) j hj
+ rw [commutator_reflect R L d A B I J j hd hIJ]
+ have hba : 2 * d + 2 = sourceEnergy B.val.sort + sourceEnergy A.val.sort := by omega
+ have hj' : |2 * (-j - 1)| ≤ (K+2 : ℕ) := by
+ have := abs_le.mp hj
+ exact abs_le.mpr (by omega)
+ rw [shifted_weighted_matrix_residue R L (K + 2) B A I J d hba (by omega) hIJ (by omega) (-j - 1) hj',
+ VPVNP.Crossing.matrix_vacuum_exchange R L A B d hd]
+ simp only [Units.smul_def, zsmul_eq_mul, pow_succ (-1 : R) d]
+ ring
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkConversion.lean b/lean/OAI/Computability/VPVNP/ShrinkConversion.lean
new file mode 100644
index 0000000000..236ad26b21
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkConversion.lean
@@ -0,0 +1,106 @@
+import OAI.Computability.VPVNP.ShrinkMotif
+import OAI.Computability.VPVNP.SlotDemandKernel
+import OAI.Computability.VPVNP.RAMSerialization
+
+/-!
+# Six-party identities on the packed demand words
+
+Section 7.2 applies one fixed instance of Theorem 6.1 to every AB/CD pair.
+The independently supplied old half-wire words give the four terminal inputs
+of the identity. Its outer index determines the supply widths, while one
+shared value per supply edge is summed over inside the selected term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+open WireTensor MotifGrid MotifBlocks MotifConversion MotifSelector MotifDemandPadding ShrinkMotif
+
+variable {V H Tag L : Type} {d c : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (P : PackingData V H Tag L d c)
+variable (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering) (order : P.ThickNumbering)
+variable (w : Arc V H Tag L d c → ℕ)
+
+/-- The widths of the AB and CD wires in the local identity. -/
+abbrev shrinkDemandWidths (m : P.Motif) := demandWidths (P.abWidth number w m) (w m.val)
+
+/-- Read the AB and CD words independently at both old endpoints. -/
+def shrinkDemandArg (m : P.Motif) (x : ∀ u, (P.oldWireNetwork w).Half u) (j : Fin 6) :
+ HalfBits demandSource demandTarget (P.shrinkDemandWidths number w m) j :=
+ (fun e _ ↦ match e with
+ | false => (RAMSerialization.wordBits _).symm
+ (P.abWord hc hd number order w (P.outgoingWord w x) m)
+ | true => (RAMSerialization.wordBits _).symm (P.cWord w x m),
+ fun e _ ↦ match e with
+ | false => (RAMSerialization.wordBits _).symm
+ (P.abWord hc hd number order w (P.incomingWord w x) m)
+ | true => (RAMSerialization.wordBits _).symm (P.dWord w x m))
+
+variable {k : Type*} [Field k] {H' : ℝ}
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) H')
+variable {R : Type*} [CommRing R] (κ : (parameterData B).Entry → R)
+
+/-- The admissible outer indices in the local conversion of one demand. -/
+noncomputable abbrev ShrinkChoice (m : P.Motif) :=
+ ↥(outerIndices B (P.shrinkDemandWidths number w m))
+
+/-- Supply width of an admitted local term. -/
+noncomputable abbrev shrinkSupplyWidths (m : P.Motif) (i : P.ShrinkChoice number w B m) :=
+ supplyWidths B (P.shrinkDemandWidths number w m) i.val
+
+/-- A matrix entry at each party, over the ring carrying a solution of the
+block's fixed equations. -/
+noncomputable def shrinkMap (m : P.Motif) (i : P.ShrinkChoice number w B m) (j : Fin 6) :
+ HalfBits demandSource demandTarget (P.shrinkDemandWidths number w m) j →
+ HalfBits supply.src supply.dst (P.shrinkSupplyWidths number w B m i) j → R :=
+ fun x y ↦ evalEntry κ (entry B demandMass_pos (P.shrinkDemandWidths number w m) i.val j x y)
+
+/-- Exact six-party expansion on the old independent half-wire inputs, in
+every ring satisfying the same parameter equations. -/
+theorem shrinkDemand_identity (hκ : (parameterData B).IsSolution κ) (m : P.Motif)
+ (x : ∀ u, (P.oldWireNetwork w).Half u) :
+ P.demandCoeff hc hd number order w m x =
+ ∑ i : P.ShrinkChoice number w B m,
+ ∑ z : (e : Bool × Fin 4) → Word (P.shrinkSupplyWidths number w B m i e),
+ ∏ j, P.shrinkMap number w B κ m i j (P.shrinkDemandArg hc hd number order w m x j)
+ (edgeAssignment supply.src supply.dst z j) := by
+ classical
+ let X := P.shrinkDemandArg hc hd number order w m x
+ have hw : (wireNetwork (k := R) demandSource demandTarget
+ (fun e ↦ Word (P.shrinkDemandWidths number w m e))).coeff X =
+ P.demandCoeff hc hd number order w m x := by
+ have hab : (X (demandSource false)).1 false rfl = (X (demandTarget false)).2 false rfl ↔
+ P.abWord hc hd number order w (P.outgoingWord w x) m =
+ P.abWord hc hd number order w (P.incomingWord w x) m :=
+ (RAMSerialization.wordBits _).symm.injective.eq_iff
+ have hcd : (X (demandSource true)).1 true rfl = (X (demandTarget true)).2 true rfl ↔
+ P.cWord w x m = P.dWord w x m := (RAMSerialization.wordBits _).symm.injective.eq_iff
+ simp only [wireNetwork, Fintype.prod_bool, hab, hcd, demandCoeff]
+ by_cases h : P.cWord w x m = P.dWord w x m <;> simp [h]
+ rw [← hw]
+ have h := congrFun (identity B κ hκ demandMass_pos supplyMass_pos
+ (P.shrinkDemandWidths number w m)) X
+ erw [Finset.sum_apply] at h
+ refine h.trans ?_
+ rw [← Finset.sum_coe_sort]
+ apply Finset.sum_congr rfl
+ intro i _
+ refine (applyLocal_wireNetwork (k := R) supply.src supply.dst
+ (fun e ↦ Word (P.shrinkSupplyWidths number w B m i e))
+ (P.shrinkMap number w B κ m i) X).trans ?_
+ apply Finset.sum_congr ?_ (fun _ _ ↦ rfl)
+ ext z
+ simp
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkEnergy.lean b/lean/OAI/Computability/VPVNP/ShrinkEnergy.lean
new file mode 100644
index 0000000000..ad1368ed2b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkEnergy.lean
@@ -0,0 +1,207 @@
+import OAI.Computability.VPVNP.SlotDemandEnergy
+import OAI.Computability.VPVNP.SurvivingSlots
+import Mathlib.Tactic.FieldSimp
+import Mathlib.Tactic.Linarith
+import Mathlib.Tactic.Ring
+
+/-!
+# Energy of the surviving wires in a shrinking step
+
+Section 7.2 of *VP and VNP differ over every field* applies the six-party
+identity separately at each motif, then chooses one layout for the entire
+list of terms. The chosen layout retains at most half the total supply
+energy. Subdivision into the graph's integral slots incurs the multiplicative
+mass loss and a rounding error of at most one quarter per slot.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.ShrinkEnergy
+
+open SurvivingSlots
+
+variable {M T : Type*} [Fintype M] [Fintype T]
+
+/-- Energy in one of the two surviving supply groups, at actual mass `p*q`. -/
+noncomputable def groupEnergy (p : ℝ) (q : T → ℝ) (w : M → Bool → T → ℕ) (layout : Bool) : ℝ :=
+ ∑ m, ∑ e, (w m layout e : ℝ) ^ 2 / (p * q e)
+
+/-- One deterministic choice of layout for the whole list. Equal costs retain
+BC, BN, CN and DM (`false` in `SurvivingSlots`). -/
+noncomputable def chosenLayout (p : ℝ) (q : T → ℝ) (w : M → Bool → T → ℕ) : Bool :=
+ if groupEnergy p q w false ≤ groupEnergy p q w true then false else true
+
+/-- Actual widths on the subdivided genuine arc IDs. -/
+def slotWidth (m : T → ℕ) (w : M → Bool → T → ℕ) (layout : Bool) (i : Id M m) : ℕ :=
+ splitWidth (w i.2.1 layout i.1) (m i.1) i.2.2
+
+theorem chosen_half (p : ℝ) (q : T → ℝ) (w : M → Bool → T → ℕ) :
+ 2 * groupEnergy p q w (chosenLayout p q w) ≤
+ groupEnergy p q w false + groupEnergy p q w true := by
+ unfold chosenLayout
+ split_ifs <;> linarith
+
+/-- Scaling the relative masses of Lemma 6.2 by `p` also scales the
+additive energy allowance per motif by `1/p`. -/
+theorem group_sum_le (w : M → Bool → T → ℕ) (ab cd : M → ℕ) (q : T → ℝ)
+ {p H C : ℝ} (hp : 0 < p) (hterm : ∀ m,
+ (∑ l : Bool, ∑ e, (w m l e : ℝ) ^ 2 / q e) ≤ H * (3 * (ab m : ℝ) ^ 2 + (cd m : ℝ) ^ 2) + C) :
+ groupEnergy p q w false + groupEnergy p q w true ≤
+ H * (∑ m, ((ab m : ℝ) ^ 2 / (p / 3) + (cd m : ℝ) ^ 2 / p)) + Fintype.card M * C / p := by
+ have hs (m : M) : (∑ e, (w m false e : ℝ) ^ 2 / (p * q e)) +
+ (∑ e, (w m true e : ℝ) ^ 2 / (p * q e)) ≤
+ H * ((ab m : ℝ) ^ 2 / (p / 3) + (cd m : ℝ) ^ 2 / p) + C / p := by
+ have hh := div_le_div_of_nonneg_right (hterm m) hp.le
+ rw [Fintype.sum_bool, add_div, Finset.sum_div, Finset.sum_div] at hh
+ convert hh using 1
+ · simp only [div_div, mul_comm p, add_comm]
+ · rw [div_div_eq_mul_div]; ring
+ unfold groupEnergy
+ rw [← Finset.sum_add_distrib]
+ refine (Finset.sum_le_sum (fun m _ ↦ hs m)).trans_eq ?_
+ rw [Finset.sum_add_distrib, ← Finset.mul_sum, Finset.sum_const, Finset.card_univ,
+ nsmul_eq_mul, mul_div_assoc]
+
+/-- Summed rounding cost after choosing a layout, including every parallel slot. -/
+theorem parallel_energy_le (w : M → Bool → T → ℕ) (q : T → ℝ) (m : T → ℕ) (layout : Bool)
+ {p p' α : ℝ} (hp : 0 < p) (hp' : 0 < p') (hα : 0 < α) (hq : ∀ e, 0 < q e)
+ (hm : ∀ e, 0 < m e) (hmass : ∀ e, α * p * q e ≤ (m e : ℝ) * p') :
+ (∑ i : Id M m, (slotWidth m w layout i : ℝ) ^ 2 / p') ≤
+ groupEnergy p q w layout / α + Fintype.card M * (∑ e, (m e : ℝ)) / (4 * p') := by
+ have one (v : M) (e : T) : (∑ i : Fin (m e), (splitWidth (w v layout e) (m e) i : ℝ) ^ 2 / p') ≤
+ (w v layout e : ℝ) ^ 2 / (p * q e) / α + (m e : ℝ) / (4 * p') := by
+ apply (splitWidth_energy_le _ _ (hm e) p' hp').trans
+ apply add_le_add_left
+ rw [div_div, mul_comm (p * q e), ← mul_assoc]
+ exact div_le_div_of_nonneg_left (sq_nonneg _) (mul_pos (mul_pos hα hp) (hq e)) (hmass e)
+ unfold groupEnergy slotWidth
+ rw [Fintype.sum_sigma]
+ simp_rw [Fintype.sum_prod_type]
+ rw [Finset.sum_comm]
+ refine (Finset.sum_le_sum (fun v _ ↦ Finset.sum_le_sum (fun e _ ↦ one v e))).trans_eq ?_
+ simp_rw [Finset.sum_add_distrib, ← Finset.sum_div]
+ simp [mul_div_assoc]
+
+/-- Substitute each six-party identity, choose the smaller layout, and
+regularize the surviving widths. The displayed errors account separately
+for splitting the thick bundle, selecting a motif term, and rounding slots. -/
+theorem shrinking_step_le (w : M → Bool → T → ℕ) (ab cd : M → ℕ) (q : T → ℝ) (m : T → ℕ)
+ {p p' α H C L B : ℝ} (hp : 0 < p) (hp' : 0 < p') (hα : 0 < α) (hH : 0 ≤ H)
+ (hq : ∀ e, 0 < q e) (hm : ∀ e, 0 < m e) (hmass : ∀ e, α * p * q e ≤ (m e : ℝ) * p')
+ (hdemand : (∑ i, ((ab i : ℝ) ^ 2 / (p / 3) + (cd i : ℝ) ^ 2 / p)) ≤ L + B)
+ (hterm : ∀ v, (∑ l : Bool, ∑ e, (w v l e : ℝ) ^ 2 / q e) ≤
+ H * (3 * (ab v : ℝ) ^ 2 + (cd v : ℝ) ^ 2) + C) :
+ (∑ i : Id M m, (slotWidth m w (chosenLayout p q w) i : ℝ) ^ 2 / p') ≤
+ (H / (2 * α)) * L + (H * B + Fintype.card M * C / p) / (2 * α) +
+ Fintype.card M * (∑ e, (m e : ℝ)) / (4 * p') := by
+ apply (parallel_energy_le w q m _ hp hp' hα hq hm hmass).trans
+ apply add_le_add_left
+ have h := (chosen_half p q w).trans (group_sum_le w ab cd q hp hterm)
+ have h' := h.trans (add_le_add_left (mul_le_mul_of_nonneg_left hdemand hH) _)
+ have h₂ : (0 : ℝ) < 2 * α := by positivity
+ rw [show H / (2 * α) * L + (H * B + Fintype.card M * C / p) / (2 * α) =
+ (H * (L + B) + Fintype.card M * C / p) / (2 * α) by ring]
+ apply (le_div_iff₀ h₂).mpr
+ simpa [mul_assoc, mul_comm, mul_left_comm, div_eq_mul_inv, hα.ne'] using h'
+
+/-- A common quadratic error coefficient for all position counts, widths and
+term lists at the fixed old and new degrees. `Q` is the number of AB pieces. -/
+noncomputable def roundingConstant (d d' Q : ℕ) (H C α : ℝ) (m : T → ℕ) : ℝ :=
+ ((H * (Q : ℝ) * (3 / 4) + max C 0) * (d : ℝ) ^ 2) / (2 * α) +
+ ((d : ℝ) * d' * ∑ e, (m e : ℝ)) / 4
+
+private theorem errors_quadratic (d d' Q : ℕ) (H C α : ℝ) (m : T → ℕ)
+ (n sites bundles motifs : ℕ) (hsites : sites ≤ n) (hbundles : bundles ≤ n * d)
+ (hmotifs : motifs ≤ n * d) (hH : 0 ≤ H) (hα : 0 < α) :
+ let p := (1 : ℝ) / ((n : ℝ) * d)
+ let p' := (1 : ℝ) / ((sites : ℝ) * d')
+ (H * (bundles * (Q : ℝ) / (4 * (p / 3))) + motifs * C / p) / (2 * α) +
+ motifs * (∑ e, (m e : ℝ)) / (4 * p') ≤ roundingConstant d d' Q H C α m * n ^ 2 := by
+ intro p p'
+ have hB : (bundles : ℝ) ≤ (n : ℝ) * d := by exact_mod_cast hbundles
+ have hM : (motifs : ℝ) ≤ (n : ℝ) * d := by exact_mod_cast hmotifs
+ have hS : (sites : ℝ) ≤ n := by exact_mod_cast hsites
+ have hm0 : 0 ≤ ∑ e, (m e : ℝ) := Finset.sum_nonneg fun _ _ ↦ Nat.cast_nonneg _
+ have hb : (bundles : ℝ) * Q / (4 * (p / 3)) ≤ ((n : ℝ) * d) * Q * ((n : ℝ) * d) * (3 / 4) := by
+ calc
+ _ = (bundles : ℝ) * Q * ((n : ℝ) * d) * (3 / 4) := by
+ simp only [p, div_eq_mul_inv, mul_inv_rev, inv_inv, one_mul]
+ ring
+ _ ≤ _ := by gcongr
+ have hc : (motifs : ℝ) * C / p ≤ ((n : ℝ) * d) * max C 0 * ((n : ℝ) * d) := by
+ rw [show (motifs : ℝ) * C / p = (motifs : ℝ) * C * ((n : ℝ) * d) by
+ dsimp only [p]; rw [div_div_eq_mul_div, div_one]]
+ apply mul_le_mul_of_nonneg_right _ (by positivity)
+ exact (mul_le_mul_of_nonneg_left (le_max_left C 0) (Nat.cast_nonneg _)).trans
+ (mul_le_mul_of_nonneg_right hM (le_max_right C 0))
+ have hslots : (motifs : ℝ) * (∑ e, (m e : ℝ)) / (4 * p') ≤
+ (((n : ℝ) * d) * (∑ e, (m e : ℝ)) * ((n : ℝ) * d')) / 4 := by
+ rw [show (4 : ℝ) * p' = 4 / ((sites : ℝ) * d') by dsimp [p']; ring, div_div_eq_mul_div]
+ gcongr
+ refine (add_le_add (div_le_div_of_nonneg_right (add_le_add (mul_le_mul_of_nonneg_left hb hH) hc)
+ (by positivity)) hslots).trans_eq ?_
+ unfold roundingConstant
+ ring
+
+/-- Uniform mass of a single arc on a degree-`d` graph on `V`. -/
+noncomputable def equalArcMass (V : Type*) [Fintype V] (d : ℕ) : ℝ :=
+ 1 / ((Fintype.card V : ℝ) * d)
+
+end Compression.ShrinkEnergy
+
+namespace Compression.PackingData
+
+open ShrinkEnergy SurvivingSlots
+
+variable {V H Tag L : Type*} {d c : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] [Nonempty V]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+/-- Equation (7.2) for an actual packed graph. Each motif uses one selected
+supply term. The chosen layout is shared by every motif. The error coefficient
+depends only on the degrees, number of color bits, relative masses, subdivision
+and fixed conversion constants. -/
+theorem packed_energy_le (P : PackingData V H Tag L d c) (hc : 2 ≤ c) (hd : 0 < d)
+ {d' : ℕ} (hd' : 0 < d')
+ (number : P.BundleNumbering) (old : Arc V H Tag L d c → ℕ) (w : P.Motif → Bool → Fin 4 → ℕ)
+ (q : Fin 4 → ℝ) (m : Fin 4 → ℕ) {α factor C : ℝ} (hα : 0 < α) (hf : 0 ≤ factor)
+ (hq : ∀ e, 0 < q e) (hm : ∀ e, 0 < m e)
+ (hmass : ∀ e, α * equalArcMass (Position V H Tag L c) d * q e ≤
+ (m e : ℝ) * equalArcMass (Site V Tag L) d')
+ (hterm : ∀ v, (∑ l : Bool, ∑ e, (w v l e : ℝ) ^ 2 / q e) ≤
+ factor * (3 * (P.abWidth number old v : ℝ) ^ 2 + (old v.1 : ℝ) ^ 2) + C) :
+ let p := equalArcMass (Position V H Tag L c) d
+ let p' := equalArcMass (Site V Tag L) d'
+ (∑ i : Id P.Motif m, (slotWidth m w (chosenLayout p q w) i : ℝ) ^ 2 / p') ≤
+ factor / (2 * α) * (∑ a, (old a : ℝ) ^ 2 / p) +
+ roundingConstant d d' (pieceCount d c) factor C α m *
+ (Fintype.card (Position V H Tag L c) : ℝ) ^ 2 := by
+ intro p p'
+ have hp : 0 < p := one_div_pos.mpr
+ (mul_pos (Nat.cast_pos.mpr Fintype.card_pos) (Nat.cast_pos.mpr hd))
+ have hp' : 0 < p' := one_div_pos.mpr
+ (mul_pos (Nat.cast_pos.mpr Fintype.card_pos) (Nat.cast_pos.mpr hd'))
+ have he := shrinking_step_le w (P.abWidth number old) (fun v ↦ old v.1) q m hp hp' hα hf
+ hq hm hmass (P.demand_energy_le hc hd number old hp) hterm
+ rw [add_assoc] at he
+ apply he.trans (add_le_add_right _ _)
+ apply errors_quadratic
+ · exact Fintype.card_le_of_injective (fun x : Site V Tag L ↦ (⟨x, 0, 0⟩ : Position V H Tag L c))
+ fun _ _ h ↦ congrArg Prod.fst h
+ · rw [Fintype.card_prod, Fintype.card_fin]
+ exact Nat.mul_le_mul_right _ (Fintype.card_le_of_injective
+ (fun x : Site V Tag L ↦ (⟨x, 0, 0⟩ : Position V H Tag L c)) fun _ _ h ↦ congrArg Prod.fst h)
+ · refine (Fintype.card_le_of_injective Subtype.val (Subtype.val_injective (p := _))).trans_eq ?_
+ simp only [Arc, Position, Fintype.card_prod, Fintype.card_fin]
+ ring
+ · exact hf
+ · exact hα
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkFieldBounds.lean b/lean/OAI/Computability/VPVNP/ShrinkFieldBounds.lean
new file mode 100644
index 0000000000..ca9db0f0db
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkFieldBounds.lean
@@ -0,0 +1,196 @@
+import OAI.Computability.VPVNP.ShrinkConversion
+import OAI.Computability.VPVNP.ShrinkPayload
+import OAI.Computability.VPVNP.ShrinkRoles
+
+/-!
+# Widths and local map descriptions in the shrinking step
+
+With a fixed six-party conversion block, every supply width (including its
+selectors), outer coordinate, and matrix-entry degree is linear in the
+maximum old width plus one. At each packed site each of the six parties has
+exactly `dQ` resident maps and each of the four absorbed types has `dQ`
+resident fields. The resulting local bounds depend only on the block and
+degree, allowing different widths and different selections on every lane.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+open WireTensor MotifGrid MotifBlocks MotifConversion MotifSelector MotifDemandPadding
+open SurvivingSlots
+
+namespace ShrinkMotif
+
+variable {k : Type*} [Field k] {H' : ℝ}
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) H')
+
+/-- If the conversion index bound is `A`, the supply payload and its selector
+list together have width at most `A * (1 + selectorBits) * (W + 1)`. -/
+noncomputable def fieldFactor : ℕ :=
+ (linear_index_bound B supplyMass_pos).choose * (1 + B.selectorBits)
+
+theorem linear_field_bounds (W : ℕ) (u : Bool → ℕ) (hu : ∀ e, u e ≤ W) :
+ repetitions B u ≤ fieldFactor B * (W + 1) ∧ ∀ v ∈ outerIndices B u, ∀ e,
+ v e ≤ fieldFactor B * (W + 1) ∧ supplyWidths B u v e ≤ fieldFactor B * (W + 1) := by
+ let A := (linear_index_bound B supplyMass_pos).choose
+ obtain ⟨hr,hv⟩ := (linear_index_bound B supplyMass_pos).choose_spec W u hu
+ have hA : A * (W + 1) ≤ fieldFactor B * (W + 1) := by
+ unfold fieldFactor
+ apply Nat.mul_le_mul_right
+ exact Nat.le_mul_of_pos_right _ (by omega)
+ refine ⟨hr.trans hA, fun v hm e ↦ ⟨(hv v hm e).trans hA, ?_⟩⟩
+ calc
+ supplyWidths B u v e ≤ A * (W + 1) + (A * (W + 1)) * B.selectorBits :=
+ Nat.add_le_add (hv v hm e) (Nat.mul_le_mul_right _ hr)
+ _ = fieldFactor B * (W + 1) := by change _ = (A * (1 + B.selectorBits)) * _; ring
+
+end ShrinkMotif
+
+namespace PackingData
+
+open ShrinkMotif
+
+variable {V H Tag L : Type} {d c : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (P : PackingData V H Tag L d c) (hc : 2 ≤ c) (hd : 0 < d)
+variable (number : P.BundleNumbering) (w : Arc V H Tag L d c → ℕ) {W : ℕ}
+variable (hw : ∀ a, w a ≤ W)
+
+include hc hd hw
+
+/-- Dividing the thick bundle among its assigned demands keeps even the
+AB demand within the maximum old width. The CD demand uses its old wire. -/
+theorem shrinkDemandWidths_le (m : P.Motif) (e : Bool) :
+ P.shrinkDemandWidths number w m e ≤ W := by
+ cases e
+ · exact P.abWidth_le hc hd number w hw m
+ · exact hw m.val
+
+variable {k : Type*} [Field k] {H' : ℝ}
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) H')
+
+/-- For each admitted term, bound the number of base entries in a map, its
+outer coordinates and all eight supply fields with one block constant. -/
+theorem shrinkTerm_bounds (m : P.Motif) (i : P.ShrinkChoice number w B m) :
+ repetitions B (P.shrinkDemandWidths number w m) ≤ fieldFactor B * (W + 1) ∧
+ ∀ e, i.val e ≤ fieldFactor B * (W + 1) ∧
+ P.shrinkSupplyWidths number w B m i e ≤ fieldFactor B * (W + 1) := by
+ have h := linear_field_bounds B W _ (P.shrinkDemandWidths_le hc hd number w hw m)
+ exact ⟨h.1, h.2 _ i.property⟩
+
+/-- The scalar-independent polynomial specified by each local matrix entry
+is zero or a monomial with at most the stated total exponent. -/
+theorem shrinkEntry_degree_le (m : P.Motif) (i : P.ShrinkChoice number w B m) (j : Fin 6)
+ (x : HalfBits demandSource demandTarget (P.shrinkDemandWidths number w m) j)
+ (y : HalfBits supply.src supply.dst (P.shrinkSupplyWidths number w B m i) j) :
+ let poly := P.shrinkMap number w B (MvPolynomial.X (R := ℤ)) m i j x y
+ (poly = 0 ∨ ∃ f, poly = MvPolynomial.monomial f 1) ∧
+ poly.totalDegree ≤ fieldFactor B * (W + 1) := by
+ obtain ⟨h, hdeg⟩ := entry_monomial B demandMass_pos _ i.val j x y
+ exact ⟨h,hdeg.trans (P.shrinkTerm_bounds hc hd number w hw B m i).1⟩
+
+omit hc hd hw
+
+private theorem splitWidth_le_width (b q : ℕ) (i : Fin q) :
+ splitWidth b q i ≤ b := by
+ have h := Finset.single_le_sum (f := splitWidth b q) (fun _ _ ↦ Nat.zero_le _)
+ (Finset.mem_univ i)
+ simpa only [sum_splitWidth b q (Nat.zero_lt_of_lt i.isLt)] using h
+
+include hc hd hw
+
+/-- The bound holds on the actual slots, including the dummy arcs, for any
+list of admitted motif terms and either layout. -/
+theorem shrinkSlotWidth_le (sel : ∀ m, P.ShrinkChoice number w B m)
+ (l : Bool) (subdiv : Fin 4 → ℕ) {pad d' : ℕ}
+ (outgoing : PaddedId (V × Tag) (Id P.BaseMotif subdiv) pad ≃ (V × Tag) × Fin d')
+ (a : ((V × Tag) × Fin d') × L) :
+ P.shrinkSlotWidth l subdiv (fun m t ↦ P.shrinkSupplyWidths number w B m (sel m) (l,t))
+ outgoing a ≤ fieldFactor B * (W + 1) := by
+ unfold shrinkSlotWidth
+ cases (P.shrinkArcEquiv l subdiv outgoing).symm ((a.1.1,a.2),a.1.2) with
+ | inl i =>
+ exact (splitWidth_le_width ..).trans
+ ((P.shrinkTerm_bounds hc hd number w hw B i.2.1 (sel i.2.1)).2 (l,i.1)).2
+ | inr _ => exact Nat.zero_le _
+
+omit hd hw
+
+private theorem card_placed_roles {T : Type} [Fintype T] (l : Bool) (pick : T → PackedRole)
+ (s : (V × Tag) × L) :
+ Fintype.card {x : P.Motif × T // packedSiteEquiv (P.survivingRole l (pick x.2) x.1) = s} =
+ Fintype.card T * (d * pieceCount d c) := by
+ classical
+ let e : {x : P.Motif × T // packedSiteEquiv (P.survivingRole l (pick x.2) x.1) = s} ≃
+ Σ t : T, {m : P.Motif // P.survivingRole l (pick t) m = packedSiteEquiv.symm s} := {
+ toFun x := ⟨x.1.2,x.1.1, packedSiteEquiv.injective (x.2.trans
+ (packedSiteEquiv.apply_symm_apply s).symm)⟩
+ invFun z := ⟨(z.2.1,z.1), by rw [z.2.2, Equiv.apply_symm_apply]⟩
+ left_inv _ := rfl
+ right_inv _ := rfl }
+ have count (r : PackedRole) : Fintype.card {m : P.Motif //
+ P.survivingRole l r m = packedSiteEquiv.symm s} = d * pieceCount d c := by
+ cases r with
+ | a => exact P.card_roleA hc _
+ | b => exact P.card_roleB hc _
+ | d => exact P.card_roleD hc l _
+ rw [Fintype.card_congr e, Fintype.card_sigma]
+ simp [count]
+
+/-- The resident map records include a separate occurrence of each party,
+even when several parties of one motif are assigned to the same site. -/
+theorem card_shrinkPartySite (l : Bool) (s : (V × Tag) × L) :
+ Fintype.card {x : P.Motif × Fin 6 // P.shrinkPartySite l x.1 x.2 = s} =
+ 6 * (d * pieceCount d c) := by
+ exact (Fintype.card_congr (Equiv.refl _)).trans
+ ((P.card_placed_roles hc l (partyRole l) s).trans (by rw [Fintype.card_fin]))
+
+/-- Every absorbed wire is recorded at its common owner exactly once. -/
+theorem card_shrinkInternalOwner (l : Bool) (s : (V × Tag) × L) :
+ Fintype.card {e : P.Motif × Fin 4 // P.shrinkInternalOwner l e = s} =
+ 4 * (d * pieceCount d c) := by
+ exact (Fintype.card_congr (Equiv.refl _)).trans
+ ((P.card_placed_roles hc l (internalRole l) s).trans (by rw [Fintype.card_fin]))
+
+include hd hw
+
+/-- Total length of the parameter lists of all resident maps before their
+product is evaluated. Failed entry checks require no additional entries. -/
+theorem shrinkSite_repetitions_le (l : Bool) (s : (V × Tag) × L) :
+ (∑ z : {x : P.Motif × Fin 6 // P.shrinkPartySite l x.1 x.2 = s},
+ repetitions B (P.shrinkDemandWidths number w z.1.1)) ≤
+ (6 * (d * pieceCount d c) * fieldFactor B) * (W + 1) := by
+ classical
+ have h := Finset.sum_le_sum (s := Finset.univ)
+ (fun z : {x : P.Motif × Fin 6 // P.shrinkPartySite l x.1 x.2 = s} ↦ fun _ ↦
+ (linear_field_bounds B W _ (P.shrinkDemandWidths_le hc hd number w hw z.1.1)).1)
+ simpa only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, Nat.cast_id,
+ P.card_shrinkPartySite hc, Nat.mul_assoc] using h
+
+/-- Total width of all the fields summed inside one packed site. -/
+theorem shrinkSite_internalWidth_le (sel : ∀ m, P.ShrinkChoice number w B m)
+ (l : Bool) (s : (V × Tag) × L) :
+ (∑ z : {e : P.Motif × Fin 4 // P.shrinkInternalOwner l e = s},
+ P.shrinkSupplyWidths number w B z.1.1 (sel z.1.1) (!l,z.1.2)) ≤
+ (4 * (d * pieceCount d c) * fieldFactor B) * (W + 1) := by
+ classical
+ have h := Finset.sum_le_sum (s := Finset.univ)
+ (fun z : {e : P.Motif × Fin 4 // P.shrinkInternalOwner l e = s} ↦ fun _ ↦
+ ((P.shrinkTerm_bounds hc hd number w hw B z.1.1 (sel z.1.1)).2 (!l,z.1.2)).2)
+ simpa only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, Nat.cast_id,
+ P.card_shrinkInternalOwner hc, Nat.mul_assoc] using h
+
+end PackingData
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkHistory.lean b/lean/OAI/Computability/VPVNP/ShrinkHistory.lean
new file mode 100644
index 0000000000..2566000453
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkHistory.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.ShrinkFieldBounds
+import OAI.Computability.VPVNP.CompressionHistory
+import OAI.Computability.VPVNP.PackingPreimages
+
+/-!
+# Resident map and field occurrences for shrinking histories
+
+At a new site of §7.2 the four absorbed types contribute shared local
+fields. The six-party maps resident there have their own incident demand
+and supply words. Each map's degree is bounded by its number of base
+copies. These records accompany the old and new actual slots of the
+substep in the recursive histories of Theorem 7.1.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+open NetworkKernel WireTensor MotifGrid MotifBlocks MotifConversion ShrinkMotif
+open SurvivingSlots
+
+variable {V H Tag L : Type} {d c : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (P : PackingData V H Tag L d c) (number : P.BundleNumbering) (w : Arc V H Tag L d c → ℕ)
+variable {k : Type*} [Field k] {H' : ℝ}
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) H')
+variable (sel : ∀ m, P.ShrinkChoice number w B m) (l : Bool) (s : (V × Tag) × L)
+
+/-- Distinct occurrences of the six local matrix entries assigned to a site. -/
+abbrev ResidentMap := {z : P.Motif × Fin 6 // P.shrinkPartySite l z.1 z.2 = s}
+
+/-- A matrix argument at party `j` reads the half-word of each incident
+demand and supply edge. -/
+def readsArgument (j : Fin 6) : Bool ⊕ Bool × Fin 4 → Prop
+ | .inl e => demandSource e = j ∨ demandTarget e = j
+ | .inr e => supply.src e = j ∨ supply.dst e = j
+
+instance (j : Fin 6) (e : Bool ⊕ Bool × Fin 4) : Decidable (readsArgument j e) := by
+ cases e <;> unfold readsArgument <;> infer_instance
+
+/-- Map argument occurrences retain both their resident map and edge label. -/
+abbrev ResidentArgument := {z : P.ResidentMap l s × (Bool ⊕ Bool × Fin 4) //
+ readsArgument z.1.1.2 z.2}
+
+/-- The locally summed fields and local matrix arguments at each new site.
+The bounds assigned to each map are the lengths of the conversion entry
+descriptions, before parameter specialization. -/
+noncomputable def shrinkSiteRecords : SiteRecords where
+ Field := {e : P.Motif × Fin 4 // P.shrinkInternalOwner l e = s} ⊕ P.ResidentArgument l s
+ fieldFintype := inferInstance
+ width
+ | .inl e => P.shrinkSupplyWidths number w B e.1.1 (sel e.1.1) (!l,e.1.2)
+ | .inr z => match z.1.2 with
+ | .inl e => P.shrinkDemandWidths number w z.1.1.1.1 e
+ | .inr e => P.shrinkSupplyWidths number w B z.1.1.1.1 (sel z.1.1.1.1) e
+ Map := P.ResidentMap l s
+ mapFintype := inferInstance
+ degree z := repetitions B (P.shrinkDemandWidths number w z.1.1)
+
+/-- A site has `6dQ` local maps, `4dQ` absorbed fields, and at most ten
+argument fields per resident map. -/
+theorem shrinkSiteRecords_count_le (hc : 2 ≤ c) :
+ (P.shrinkSiteRecords number w B sel l s).count ≤
+ 1 + 6 * (d * pieceCount d c) + 4 * (d * pieceCount d c) + 6 * (d * pieceCount d c) * 10 := by
+ let M := P.ResidentMap l s
+ have hM : Fintype.card M = 6 * (d * pieceCount d c) := P.card_shrinkPartySite hc l s
+ have hA : Fintype.card (P.ResidentArgument l s) ≤ Fintype.card (M × (Bool ⊕ Bool × Fin 4)) :=
+ Fintype.card_subtype_le _
+ simp only [Fintype.card_prod, Fintype.card_sum, Fintype.card_fin, Fintype.card_bool, hM] at hA
+ change 1 + Fintype.card M +
+ Fintype.card ({e : P.Motif × Fin 4 // P.shrinkInternalOwner l e = s} ⊕
+ P.ResidentArgument l s) ≤ _
+ rw [hM, Fintype.card_sum, P.card_shrinkInternalOwner hc]
+ omega
+
+set_option maxHeartbeats 400000 in
+-- The two maxima unfold the dependent field and map types of the selected record.
+/-- Every local wire word and every individual map degree obey the same
+linear envelope, independent of the particular selections and site. -/
+theorem shrinkSiteRecords_largest_le (hc : 2 ≤ c) (hd : 0 < d) {W : ℕ} (hw : ∀ a, w a ≤ W) :
+ (P.shrinkSiteRecords number w B sel l s).largest ≤ max 1 (fieldFactor B) * (W + 1) := by
+ let K := max 1 (fieldFactor B) * (W + 1)
+ have hf : fieldFactor B * (W + 1) ≤ K := Nat.mul_le_mul_right _ (le_max_right ..)
+ have hW : W ≤ K := (Nat.le_succ W).trans
+ (by simpa only [Nat.one_mul] using
+ Nat.mul_le_mul_right (W + 1) (le_max_left 1 (fieldFactor B)))
+ change max (Finset.univ.sup (P.shrinkSiteRecords number w B sel l s).width)
+ (Finset.univ.sup (fun z : P.ResidentMap l s ↦
+ repetitions B (P.shrinkDemandWidths number w z.1.1))) ≤ K
+ apply max_le <;> apply Finset.sup_le <;> intro z _
+ · rcases z with e | z
+ · exact ((P.shrinkTerm_bounds hc hd number w hw B e.1.1 (sel e.1.1)).2 (!l,e.1.2)).2.trans hf
+ · rcases z with ⟨⟨m,e | e⟩,he⟩
+ · exact (P.shrinkDemandWidths_le hc hd number w hw m.1.1 e).trans hW
+ · exact ((P.shrinkTerm_bounds hc hd number w hw B m.1.1 (sel m.1.1)).2 e).2.trans hf
+ · exact (P.shrinkTerm_bounds hc hd number w hw B z.1.1 (sel z.1.1)).1.trans hf
+
+omit [AddCommGroup H] [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+ [DecidableEq V] [DecidableEq Tag] [DecidableEq L] in
+/-- Reassembling the old lane fields and promoting the tag into the new
+base both preserve the exact immediate-preimage count. -/
+theorem card_reindexed_shrinkPlace [Finite V] [Finite H] [Finite Tag] [Finite L]
+ {U : Type}
+ (inputSites : Position V H Tag L c ≃ U) (hc : 0 < c) :
+ Nat.card {u : U // s = P.shrinkPlace l (inputSites.symm u)} = 2 ^ c * d := by
+ classical
+ let := Fintype.ofFinite V
+ let := Fintype.ofFinite H
+ let := Fintype.ofFinite Tag
+ let := Fintype.ofFinite L
+ let e := inputSites.symm.subtypeEquiv
+ (p := fun u ↦ s = P.shrinkPlace l (inputSites.symm u))
+ (q := fun x ↦ P.placement l x = packedSiteEquiv.symm s)
+ (fun u ↦ by rw [Equiv.eq_symm_apply]; exact eq_comm)
+ rw [Nat.card_congr e, Nat.card_eq_fintype_card]
+ exact P.card_placement hc l _
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkLayout.lean b/lean/OAI/Computability/VPVNP/ShrinkLayout.lean
new file mode 100644
index 0000000000..3d6a2210e2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkLayout.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.ShrinkLocalMaps
+import OAI.Computability.VPVNP.ShrinkSupplyLocal
+
+/-!
+# Regrouping all six-party matrices at the sites of the shrinking step
+
+For one choice of outer term at every motif, the layout uses one new
+numbered wire per surviving subdivision. Each absorbed wire is internal
+to a single site. The product of the six-party matrices agrees with the
+product of the entries at the new sites for every original assignment.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.ShrinkMotif
+
+variable {M V k : Type*} [Fintype M] [DecidableEq V] [CommMonoid k]
+
+/-- Computing a site entry requires precisely its list of resident map occurrences. -/
+theorem partyProduct_eq_resident (site : M → Fin 6 → V) (v : V)
+ (factor : ∀ m j, v = site m j → k) :
+ partyProduct site v factor =
+ ∏ z : {p : M × Fin 6 // site p.1 p.2 = v}, factor z.1.1 z.1.2 z.2.symm := by
+ let f (z : M × Fin 6) : k := if h : v = site z.1 z.2 then factor z.1 z.2 h else 1
+ change (∏ m, ∏ j, f (m,j)) = _
+ rw [← Fintype.prod_prod_type f,
+ ← Fintype.prod_subtype_mul_prod_subtype (fun z ↦ site z.1 z.2 = v) f]
+ have hother (z : {p : M × Fin 6 // ¬ site p.1 p.2 = v}) : f z.1 = 1 :=
+ by simp [f,Ne.symm z.2]
+ simp only [hother, Finset.prod_const_one, mul_one]
+ apply Finset.prod_congr rfl
+ intro z _
+ simp [f, z.2.symm]
+
+end Compression.ShrinkMotif
+
+namespace Compression.PackingData
+
+open NetworkKernel WireTensor MotifDemandPadding ShrinkMotif
+
+variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering) (order : P.ThickNumbering)
+variable (w : Arc V H Tag L d c → ℕ) (l : Bool) (subdiv : Fin 4 → ℕ)
+variable (width : P.Motif → Bool × Fin 4 → ℕ) {d' pad : ℕ} {next : Equiv.Perm (V × Tag)}
+variable (I : P.ShrinkIndex l subdiv next d' pad) (hpos : ∀ t, 0 < subdiv t)
+variable {R : Type*} [CommSemiring R]
+variable (matrix : ∀ m j,
+ HalfBits demandSource demandTarget (P.shrinkDemandWidths number w m) j →
+ HalfBits supply.src supply.dst (width m) j → R)
+
+/-- Layout of the selected six-party terms, including each absorbed word's
+owner and the arguments available to every map at its site. -/
+noncomputable def shrinkLayout : Layout R (P.oldWireNetwork w) where
+ output := P.shrinkOutput l subdiv (fun m t ↦ width m (l,t)) I
+ place := P.shrinkPlace l
+ Internal := P.Motif × Fin 4
+ internalFintype := inferInstance
+ Label := ShrinkMotif.internalLabel width l
+ labelFintype _ := inferInstance
+ owner := P.shrinkInternalOwner l
+ entry v a h z := partyProduct (P.shrinkPartySite l) v fun m j hv ↦
+ matrix m j (P.shrinkLocalDemandArg hc hd number order w l m j (hv ▸ a))
+ (P.shrinkLocalSupplyArg l subdiv width I hpos m j (hv ▸ h) (hv ▸ z))
+
+/-- Regrouping the selected motif factors, the final hypothesis of
+`Step.ofMotifProduct` for the actual padded output graph. -/
+theorem shrinkLayout_group (x : (m : P.Motif) → (e : Bool × Fin 4) → Fin (2 ^ width m e))
+ (a : ∀ u, (P.oldWireNetwork w).Half u) :
+ let T := P.shrinkLayout hc hd number order w l subdiv width I hpos matrix
+ let z := P.shrinkAssignmentsEquiv l subdiv width I hpos x
+ (∏ m, ∏ j, matrix m j (P.shrinkDemandArg hc hd number order w m a j)
+ (edgeAssignment supply.src supply.dst (x m) j)) =
+ ∏ v, T.entry v (fun u _ ↦ a u) (fun e _ ↦ z.2 e)
+ (edgeAssignment T.output.src T.output.dst z.1 v) := by
+ let : DecidableEq (P.shrinkOutput l subdiv (fun m t ↦ width m (l,t)) I).Site :=
+ inferInstanceAs (DecidableEq ((V × Tag) × L))
+ dsimp only [shrinkLayout]
+ erw [prod_partyProduct]
+ apply Finset.prod_congr rfl
+ intro m _
+ apply Finset.prod_congr rfl
+ intro j _
+ congr 1
+ · exact (P.shrinkLocalDemandArg_eval hc hd number order w l m j a).symm
+ · exact (P.shrinkLocalSupplyArg_eval l subdiv width I hpos m j x).symm
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkLocalMaps.lean b/lean/OAI/Computability/VPVNP/ShrinkLocalMaps.lean
new file mode 100644
index 0000000000..cea14e2a0a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkLocalMaps.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.ShrinkRoles
+import OAI.Computability.VPVNP.ShrinkConversion
+import OAI.Computability.VPVNP.SlotDemandLocal
+
+/-!
+# Demand rows of the six maps at their packed sites
+
+A and B read their respective slices of the old bundle from whole vertex
+factors placed at their sites. C and D read the two ends of their old wire,
+including the reversal when its source is thick. The resulting matrix row
+indices agree with the global demand indices used in the conversion identity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+open ShrinkMotif NetworkKernel MotifDemandPadding RAMSerialization
+
+variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+variable (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering) (order : P.ThickNumbering)
+variable (w : Arc V H Tag L d c → ℕ) (l : Bool)
+
+/-- Use the coordinates of the old packed site to access its placed old factors. -/
+def shrinkPlacedHalf (s : Site V Tag L) {v : (V × Tag) × L} (hv : v = packedSiteEquiv s)
+ (x : Placed (P.shrinkPlace l) (P.oldWireNetwork w).Half v) :
+ P.PlacedHalf w l s :=
+ fun u h ↦ x u (hv.trans (congrArg packedSiteEquiv h))
+
+/-- Each party reads only the demand coordinates located at its own site. -/
+def shrinkLocalDemandArg (m : P.Motif) (j : Fin 6)
+ (x : Placed (P.shrinkPlace l) (P.oldWireNetwork w).Half (P.shrinkPartySite l m j)) :
+ HalfBits demandSource demandTarget (P.shrinkDemandWidths number w m) j := by
+ constructor
+ · intro e he
+ subst j
+ cases e with
+ | false => exact (wordBits _).symm (P.localAWord hc hd number order w l m
+ (P.shrinkPlacedHalf w l _ rfl x))
+ | true => exact (wordBits _).symm (P.localCWord w l m
+ (P.shrinkPlacedHalf w l _ (P.shrinkPartySite_C l m) x))
+ · intro e he
+ subst j
+ cases e with
+ | false => exact (wordBits _).symm (P.localBWord hc hd number order w l m
+ (P.shrinkPlacedHalf w l _ rfl x))
+ | true => exact (wordBits _).symm (P.localDWord w l m
+ (P.shrinkPlacedHalf w l _ rfl x))
+
+/-- On the restrictions of a global assignment, the local rows read precisely
+the four demand words of the unplaced six-party identity. -/
+theorem shrinkLocalDemandArg_eval (m : P.Motif) (j : Fin 6)
+ (x : (u : (P.oldWireNetwork w).Site) → (P.oldWireNetwork w).Half u) :
+ P.shrinkLocalDemandArg hc hd number order w l m j (fun u _ ↦ x u) =
+ P.shrinkDemandArg hc hd number order w m x j := by
+ apply Prod.ext
+ · funext e he
+ subst j
+ cases e with
+ | false => rfl
+ | true => exact congrArg (wordBits _).symm (P.localCWord_eval w l m x)
+ · funext e he
+ subst j
+ cases e with
+ | false => rfl
+ | true => exact congrArg (wordBits _).symm (P.localDWord_eval w l m x)
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkMonomialWitness.lean b/lean/OAI/Computability/VPVNP/ShrinkMonomialWitness.lean
new file mode 100644
index 0000000000..2a8ff061f1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkMonomialWitness.lean
@@ -0,0 +1,129 @@
+import OAI.Computability.VPVNP.ShrinkStep
+import OAI.Computability.VPVNP.ShrinkFieldBounds
+import OAI.Computability.VPVNP.MotifEntryWitness
+
+/-!
+# Monomial witnesses of the shrinking kernels
+
+For fixed old half-wires and new half-wires, a vertex first chooses each
+absorbed word owned by it. It then performs the syntactic entry check of
+every six-party map resident at that vertex. The successful choices retain
+their parameter multiplicities in any coefficient ring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.ShrinkMotif
+
+open NetworkKernel
+
+variable {M V Label : Type} [Fintype M] [DecidableEq V] [Fintype Label]
+variable {R : Type*} [CommRing R] {κ : Label → R}
+
+/-- At one packed site only the resident motif-party occurrences contribute
+choices or labels to the product. -/
+noncomputable def partyProductWitness (site : M → Fin 6 → V) (v : V)
+ {factor : ∀ m j, v = site m j → R}
+ (W : ∀ m j h, MonomialWitness κ (factor m j h)) :
+ MonomialWitness κ (partyProduct site v factor) :=
+ (MonomialWitness.prod (fun r : {p : M × Fin 6 // site p.1 p.2 = v} ↦
+ W r.1.1 r.1.2 r.2.symm)).changeValue (partyProduct_eq_resident site v factor).symm
+
+/-- The degree of one successful product is the sum of the individual
+degrees at its resident map occurrences. -/
+theorem partyProductWitness_totalExponent (site : M → Fin 6 → V) (v : V)
+ {factor : ∀ m j, v = site m j → R}
+ (W : ∀ m j h, MonomialWitness κ (factor m j h)) (c : (partyProductWitness site v W).Choice) :
+ ∑ l, (partyProductWitness site v W).exponents c l =
+ ∑ r : {p : M × Fin 6 // site p.1 p.2 = v}, ∑ l,
+ (W r.1.1 r.1.2 r.2.symm).exponents (c r) l :=
+ Finset.sum_comm
+
+end Compression.ShrinkMotif
+
+namespace Compression.PackingData
+
+open NetworkKernel WireTensor MotifGrid MotifBlocks MotifConversion MotifDemandPadding ShrinkMotif
+
+variable {V H Tag L : Type} {d c d' pad : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (P : PackingData V H Tag L d c)
+variable (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering) (order : P.ThickNumbering)
+variable (w : Arc V H Tag L d c → ℕ) (l : Bool) (subdiv : Fin 4 → ℕ)
+variable (width : P.Motif → Bool × Fin 4 → ℕ) {next : Equiv.Perm (V × Tag)}
+variable {R : Type*} [CommRing R]
+
+/-- Product of the individual map witnesses in one concrete shrinking
+layout. All row and column arguments come from the site's own old fields,
+absorbed words and outgoing-network half-wires. -/
+noncomputable def shrinkLayoutEntryWitness
+ (I : P.ShrinkIndex l subdiv next d' pad) (hpos : ∀ t, 0 < subdiv t)
+ (matrix : ∀ m j, HalfBits demandSource demandTarget (P.shrinkDemandWidths number w m) j →
+ HalfBits supply.src supply.dst (width m) j → R)
+ {Label : Type} [Fintype Label] {κ : Label → R}
+ (W : ∀ m j x y, MonomialWitness κ (matrix m j x y)) :
+ let T := P.shrinkLayout hc hd number order w l subdiv width I hpos matrix
+ ∀ v a h z, MonomialWitness κ (T.entry v a h z) :=
+ fun v a h z ↦ partyProductWitness (P.shrinkPartySite l) v fun m j hv ↦
+ W m j (P.shrinkLocalDemandArg hc hd number order w l m j (hv ▸ a))
+ (P.shrinkLocalSupplyArg l subdiv width I hpos m j (hv ▸ h) (hv ▸ z))
+
+variable {k : Type*} [Field k] {H' δ : ℝ}
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) H')
+variable (κ : (parameterData B).Entry → R) (hκ : (parameterData B).IsSolution κ)
+variable (ready : Ready d c d' δ)
+variable (I : ∀ l : Bool, P.ShrinkIndex l (subdivisions d c d') next d' pad)
+
+/-- Witness for the actual kernel selected in (7.2). The outer witness
+selects the absorbed words, and the inner witnesses count one parameter
+per accepted copy of each resident matrix. -/
+noncomputable def shrinkKernelWitness :
+ ∀ s v a z, MonomialWitness κ
+ (((P.shrinkStep B κ hκ hc hd number order w ready I).term s).kernel v a z) :=
+ fun s ↦
+ let l := P.shrinkTermLayout B number w s
+ let width := fun m ↦ P.shrinkSupplyWidths number w B m (s m)
+ let matrix := fun m ↦ P.shrinkMap number w B κ m (s m)
+ let T := P.shrinkLayout hc hd number order w l (subdivisions d c d')
+ width (I l) ready.count_pos matrix
+ T.kernelWitness (P.shrinkLayoutEntryWitness hc hd number order w l (subdivisions d c d')
+ width (I l) ready.count_pos matrix fun m j x y ↦
+ entryWitness κ (entry B demandMass_pos (P.shrinkDemandWidths number w m) (s m).val j x y))
+
+/-- In a successful shrinking-kernel witness the degree is exactly the
+total number of base repetitions read by its resident map occurrences.
+The choice of absorbed words does not itself contribute a parameter. -/
+theorem shrinkKernelWitness_totalExponent (s : ∀ m, P.ShrinkChoice number w B m)
+ (v : (V × Tag) × L) (a z)
+ (x : (P.shrinkKernelWitness hc hd number order w B κ hκ ready I s v a z).Choice) :
+ (∑ label, (P.shrinkKernelWitness hc hd number order w B κ hκ ready I s v a z).exponents
+ x label) = ∑ t : {q : P.Motif × Fin 6 // P.shrinkPartySite
+ (P.shrinkTermLayout B number w s) q.1 q.2 = v},
+ repetitions B (P.shrinkDemandWidths number w t.1.1) := by
+ let J := {q : P.Motif × Fin 6 // P.shrinkPartySite (P.shrinkTermLayout B number w s) q.1 q.2 = v}
+ change (∑ label, ∑ t : J, _) = _
+ rw [Finset.sum_comm]
+ apply Finset.sum_congr rfl
+ intro t _
+ exact entryWitness_totalExponent κ _ _
+
+/-- The complete kernel degree at a site obeys a linear envelope in the
+largest incoming width, uniformly over selected layouts and witnesses. -/
+theorem shrinkKernelWitness_degree_le (s : ∀ m, P.ShrinkChoice number w B m)
+ (v : (V × Tag) × L) (a z)
+ (x : (P.shrinkKernelWitness hc hd number order w B κ hκ ready I s v a z).Choice)
+ {W : ℕ} (hw : ∀ e, w e ≤ W) :
+ (∑ label, (P.shrinkKernelWitness hc hd number order w B κ hκ ready I s v a z).exponents
+ x label) ≤ (6 * (d * pieceCount d c) * fieldFactor B) * (W + 1) := by
+ rw [P.shrinkKernelWitness_totalExponent]
+ exact P.shrinkSite_repetitions_le hc hd number w hw B _ _
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkMotif.lean b/lean/OAI/Computability/VPVNP/ShrinkMotif.lean
new file mode 100644
index 0000000000..6d94dc93a9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkMotif.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.MotifConversion
+import OAI.Computability.VPVNP.ShrinkMotifGraph
+import OAI.Computability.VPVNP.WireCATZero
+
+/-!
+# Converting the six-party demands over every field
+
+The spectral CAT(0) inequality for this motif gives exact base identities
+and the term energy estimate used to shrink a packed graph in Section 7.2.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.ShrinkMotif
+
+open WireTensor MotifGrid MotifBlocks MotifConversion
+
+variable {k : Type*} [Field k]
+
+/-- Lemma 6.2 as the exact hypothesis (6.1) of the wire conversion. -/
+theorem spectral_comparison (F : SpectralPoint k (Fin 6)) :
+ distanceEnergy (realWidths demandMass)
+ (fun i ↦ F.wireDistance (demandSource i) (demandTarget i)) ≤
+ (31 / 16 : ℝ) * distanceEnergy (realWidths supplyMass)
+ (fun e ↦ F.wireDistance (supply.src e) (supply.dst e)) := by
+ have h := F.sixParty_wire_energy 0 1 2 3 4 5
+ norm_num [distanceEnergy, realWidths, Fintype.sum_bool, Fintype.sum_prod_type, Fin.sum_univ_succ,
+ supplyMass, demandMass, relativeMass, demandSource, demandTarget, supply,
+ supplySource, supplyTarget]
+ linarith only [h]
+
+/-- A fixed block for all six-party demands, with its error chosen independently of the widths. -/
+theorem exists_block {H' : ℝ} (hH' : 31 / 16 < H') :
+ Nonempty (FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) H') :=
+ exists_fixed_block _ _ _ _ _ (fun i ↦ Rat.cast_pos.mpr (demandMass_pos i))
+ (fun i ↦ Rat.cast_pos.mpr (supplyMass_pos i)) (by norm_num) hH' spectral_comparison
+
+/-- Width profile of a single motif. -/
+def demandWidths (ab cd : ℕ) : Bool → ℕ | false => ab | true => cd
+
+variable {H' : ℝ} (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) H')
+
+/-- Per-term energy budget in the indexing used by the packed graph. -/
+theorem term_energy_le (ab cd : ℕ) {v : Bool × Fin 4 → ℕ}
+ (hv : v ∈ outerIndices B (demandWidths ab cd)) :
+ (∑ l : Bool, ∑ e, (supplyWidths B (demandWidths ab cd) v (l,e) : ℝ) ^ 2 /
+ (relativeMass e : ℝ)) ≤
+ H' * (3 * (ab : ℝ) ^ 2 + (cd : ℝ) ^ 2) + B.energyConstant := by
+ have h := energy_le B demandMass_pos supplyMass_pos _ v hv
+ rw [norm_sq (realWidths supplyMass) _ (fun e ↦ Rat.cast_pos.mpr (supplyMass_pos e)),
+ norm_sq (realWidths demandMass) _ (fun i ↦ Rat.cast_pos.mpr (demandMass_pos i)),
+ Fintype.sum_prod_type, Fintype.sum_bool] at h
+ simpa [demandWidths, demandMass, realWidths, supplyMass, div_div_eq_mul_div, add_comm, mul_comm]
+ using h
+
+end Compression.ShrinkMotif
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkMotifGraph.lean b/lean/OAI/Computability/VPVNP/ShrinkMotifGraph.lean
new file mode 100644
index 0000000000..d05bb79382
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkMotifGraph.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.MotifSelector
+import Mathlib.Algebra.BigOperators.Fin
+import Mathlib.Data.Fin.VecNotation
+import Mathlib.Analysis.Real.Sqrt
+import Mathlib.Tactic.FinCases
+
+/-!
+# The six-party motif for the shrinking step
+
+The parties are A, B, C, D, M, N in that order. Each supply edge carries
+a layout bit recording the layout in which it survives, and a type from
+zero to three. These are the same labels as in `SurvivingSlots`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.ShrinkMotif
+
+/-- The two demands in the order AB, CD. -/
+def demandSource : Bool → Fin 6 | false => 0 | true => 2
+
+/-- Target party of each demand edge, B for the AB demand and D for the CD demand. -/
+def demandTarget : Bool → Fin 6 | false => 1 | true => 3
+
+/-- The source party for each of BC, BN, CN, DM and AC, AM, CM, DN. -/
+def supplySource : Bool × Fin 4 → Fin 6
+ | (l, 0) | (l, 1) => if l then 0 else 1
+ | (_, 2) => 2
+ | (_, 3) => 3
+
+/-- The target party in the same two supply groups. -/
+def supplyTarget : Bool × Fin 4 → Fin 6
+ | (_, 0) => 2
+ | (l, 1) | (l, 2) => if l then 4 else 5
+ | (l, 3) => if l then 5 else 4
+
+private def adjacent (x y : Fin 6) : Prop := ∃ e,
+ (supplySource e = x ∧ supplyTarget e = y) ∨ (supplySource e = y ∧ supplyTarget e = x)
+
+private theorem path_to_center (x : Fin 6) : Relation.ReflTransGen adjacent x 2 := by
+ fin_cases x
+ · exact .single ⟨(true,0), Or.inl ⟨rfl,rfl⟩⟩
+ · exact .single ⟨(false,0), Or.inl ⟨rfl,rfl⟩⟩
+ · exact .refl
+ · exact Relation.ReflTransGen.tail (Relation.ReflTransGen.single
+ (r := adjacent) (b := 4) ⟨(false,3), Or.inl ⟨rfl,rfl⟩⟩) ⟨(true,2), Or.inr ⟨rfl,rfl⟩⟩
+ · exact .single ⟨(true,2), Or.inr ⟨rfl,rfl⟩⟩
+ · exact .single ⟨(false,2), Or.inr ⟨rfl,rfl⟩⟩
+
+/-- Connected supply graph with one incident edge at every party for reading selectors. -/
+def supply : MotifSelector.Supply (Fin 6) (Bool × Fin 4) where
+ src := supplySource
+ dst := supplyTarget
+ anchor := ![(true,0), (false,0), (true,0), (false,3), (true,2), (false,2)]
+ anchor_incident j := by fin_cases j <;> decide
+ connected x y := by
+ have hsym (i j : Fin 6) (h : adjacent j i) : adjacent i j := by
+ obtain ⟨e, he⟩ := h
+ exact ⟨e, he.symm⟩
+ exact (path_to_center x).trans ((path_to_center y).swap.mono hsym 2 y)
+
+/-- Relative masses of AB and CD. -/
+def demandMass : Bool → ℚ | false => 1 / 3 | true => 1
+
+/-- Relative masses in each group of Lemma 6.2. -/
+def relativeMass : Fin 4 → ℚ := ![8 / 31, 4 / 31, 40 / 93, 16 / 31]
+
+/-- Relative supply-edge mass indexed by edge type, using the same four masses in each layout. -/
+def supplyMass (e : Bool × Fin 4) : ℚ := relativeMass e.2
+
+theorem demandMass_pos (i : Bool) : 0 < demandMass i := by
+ cases i <;> norm_num [demandMass]
+
+theorem relativeMass_pos (e : Fin 4) : 0 < relativeMass e := by
+ fin_cases e <;> norm_num [relativeMass]
+
+theorem supplyMass_pos (e : Bool × Fin 4) : 0 < supplyMass e := relativeMass_pos e.2
+
+theorem sum_relativeMass : ∑ e, (relativeMass e : ℝ) = 4 / 3 := by
+ norm_num [Fin.sum_univ_succ, relativeMass]
+
+end Compression.ShrinkMotif
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkPayload.lean b/lean/OAI/Computability/VPVNP/ShrinkPayload.lean
new file mode 100644
index 0000000000..fb5249bb8f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkPayload.lean
@@ -0,0 +1,184 @@
+import OAI.Computability.VPVNP.RegularizedMotifs
+import OAI.Computability.VPVNP.WidthRounding
+import Mathlib.Algebra.BigOperators.Fin
+
+/-!
+# Shared payloads of the shrinking step
+
+Each surviving motif wire in §7.2 is divided into contiguous strings. Its
+subdivision labels are numbered at the base by lane-zero motif IDs and then
+lifted at the absolute lane of the source role. A padding slot has a unique
+empty string. Thus summing shared output-slot assignments is equivalent to
+summing one shared word on each original surviving motif wire.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.ShrinkPayload
+
+open SurvivingSlots
+
+/-- In subdivision order, the bit coordinates of the slices exhaust exactly
+the input wire. This includes zero-length slices. -/
+def sliceBits (b q : ℕ) (hq : 0 < q) :
+ (Σ i : Fin q, Fin (splitWidth b q i)) ≃ Fin b :=
+ finSigmaFinEquiv.trans (finCongr (sum_splitWidth b q hq))
+
+/-- Extract all slices of the shared wire word. The inverse concatenates
+them in subdivision order. -/
+def sliceWords (b q : ℕ) (hq : 0 < q) :
+ (Fin b → Bool) ≃ ((i : Fin q) → Fin (splitWidth b q i) → Bool) :=
+ ((sliceBits b q hq).symm.arrowCongr (Equiv.refl Bool)).trans (Equiv.piCurry
+ (fun (i : Fin q) (_ : Fin (splitWidth b q i)) ↦ Bool))
+
+/-- The start of a slice is the sum of the preceding slice widths. -/
+theorem sliceBits_offset (b q : ℕ) (hq : 0 < q) (i : Fin q) (j : Fin (splitWidth b q i)) :
+ (sliceBits b q hq ⟨i,j⟩ : ℕ) = (∑ k : Fin i, splitWidth b q (Fin.castLE i.isLt.le k)) + j :=
+ finSigmaFinEquiv_apply _
+
+variable {M T D : Type*} (subdiv : T → ℕ) (width : M → T → ℕ)
+
+/-- Classify output widths before outgoing slot numbering. -/
+def classWidth : Id M subdiv ⊕ D → ℕ :=
+ Sum.elim (fun i ↦ splitWidth (width i.2.1 i.1) (subdiv i.1) i.2.2) (fun _ ↦ 0)
+
+/-- Split all genuine wires and insert the empty word on each padding ID. -/
+def classPayloads (hpos : ∀ t, 0 < subdiv t) :
+ ((m : M) → (t : T) → Fin (width m t) → Bool) ≃
+ ((i : Id M subdiv ⊕ D) → Fin (classWidth subdiv width i) → Bool) where
+ toFun x
+ | .inl ⟨t,m,k⟩ => sliceWords (width m t) (subdiv t) (hpos t) (x m t) k
+ | .inr _ => Fin.elim0
+ invFun z m t := (sliceWords (width m t) (subdiv t) (hpos t)).symm (fun k ↦ z (.inl ⟨t,m,k⟩))
+ left_inv x := by funext m t; exact (sliceWords ..).symm_apply_apply (x m t)
+ right_inv z := by
+ funext i
+ rcases i with ⟨t,m,k⟩ | dummy
+ · exact congrFun ((sliceWords (width m t) (subdiv t) (hpos t)).apply_symm_apply
+ (fun j ↦ z (.inl ⟨t,m,j⟩))) k
+ · funext j
+ exact Fin.elim0 j
+
+end Compression.ShrinkPayload
+
+namespace Compression.PackingData
+
+open SurvivingSlots ShrinkPayload
+
+variable {V H Tag L : Type*} {c d d' pad : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (layout : Bool) (subdiv : Fin 4 → ℕ)
+variable (width : P.Motif → Fin 4 → ℕ)
+variable (outgoing : PaddedId (V × Tag) (Id P.BaseMotif subdiv) pad ≃ (V × Tag) × Fin d')
+
+/-- An actual outgoing arc label is its source site (base and lane) and
+slot number. The genuine label retains its motif, type and subdivision,
+and the lane of its source role fixes the copy of the numbered base arc. -/
+def shrinkArcEquiv :
+ (Id P.Motif subdiv ⊕ ((V × Tag) × Fin pad) × L) ≃ ((V × Tag) × L) × Fin d' :=
+ let atSource : (((V × Tag) × Fin d') × L) ≃ ((V × Tag) × L) × Fin d' := {
+ toFun a := ((a.1.1,a.2),a.1.2)
+ invFun a := ((a.1.1,a.2),a.1.2)
+ left_inv _ := rfl
+ right_inv _ := rfl }
+ ((P.survivingLaneEquiv layout subdiv).sumCongr (Equiv.refl _)).trans
+ ((Equiv.sumProdDistrib _ _ _).symm.trans ((outgoing.prodCongr (Equiv.refl L)).trans atSource))
+
+/-- Read a genuine numbered outgoing arc in source-lane coordinates. -/
+theorem shrinkArcEquiv_genuine (i : Id P.Motif subdiv) :
+ P.shrinkArcEquiv layout subdiv outgoing (.inl i) =
+ let z := P.survivingLaneEquiv layout subdiv i
+ let p := outgoing (.inl z.1)
+ ((p.1,z.2),p.2) := rfl
+
+/-- Each dummy ID is repeated at every remaining lane. -/
+theorem shrinkArcEquiv_padding (z : (V × Tag) × Fin pad) (g : L) :
+ P.shrinkArcEquiv layout subdiv outgoing (.inr (z,g)) =
+ (((outgoing (.inr z)).1,g),(outgoing (.inr z)).2) := rfl
+
+/-- Both ends of the numbered genuine wire coincide with its placed motif
+roles, including the destination's translated lane and the incoming slot. -/
+theorem shrinkArc_endpoints {next : Equiv.Perm (V × Tag)}
+ (I : SlotIndexing (V × Tag) (PaddedId (V × Tag) (Id P.BaseMotif subdiv) pad) L d'
+ (paddedSource (endpoint (P.roleBase layout) (sourceRole layout)))
+ (paddedTarget (endpoint (P.roleBase layout) (targetRole layout)) next)
+ (paddedShift (P.roleDisplacement layout (sourceRole layout) (targetRole layout))))
+ (i : Id P.Motif subdiv) :
+ let a := P.shrinkArcEquiv layout subdiv I.outgoing (.inl i)
+ let src := endpoint (P.survivingRole layout) (sourceRole layout) i
+ let dst := endpoint (P.survivingRole layout) (targetRole layout) i
+ a.1 = (packedBase src,src.2.2) ∧
+ (I.graph.actualGraph.target a).1 = (packedBase dst,dst.2.2) := by
+ obtain ⟨⟨z,g⟩, rfl⟩ := (P.survivingLaneEquiv layout subdiv).symm.surjective i
+ obtain ⟨hs,ht⟩ := P.survivingLane_endpoints layout subdiv z g
+ simp only [shrinkArcEquiv_genuine, Equiv.apply_symm_apply, hs, ht, LiftedSlots.actualGraph_target,
+ Prod.mk.eta, I.match_eq, I.dst_eq, I.displacement_eq]
+ rw [I.src_eq]
+ exact ⟨rfl,rfl⟩
+
+/-- The actual lifted widths, indexed by outgoing base port and source lane,
+as in `LiftedSlots.actualTarget`. -/
+def shrinkSlotWidth (p : ((V × Tag) × Fin d') × L) : ℕ :=
+ classWidth subdiv width ((P.shrinkArcEquiv layout subdiv outgoing).symm ((p.1.1,p.2),p.1.2))
+
+/-- At a genuine arc the width is the designated subdivision of the
+actual motif wire, including its lane-dependent width. -/
+theorem shrinkSlotWidth_genuine (i : Id P.Motif subdiv) :
+ let a := P.shrinkArcEquiv layout subdiv outgoing (.inl i)
+ P.shrinkSlotWidth layout subdiv width outgoing ((a.1.1,a.2),a.1.2) =
+ splitWidth (width i.2.1 i.1) (subdiv i.1) i.2.2 := by
+ simp [shrinkSlotWidth, classWidth]
+
+/-- All padding arcs have zero width. -/
+theorem shrinkSlotWidth_padding (z : (V × Tag) × Fin pad) (g : L) :
+ P.shrinkSlotWidth layout subdiv width outgoing (outgoing (.inr z),g) = 0 := by
+ change classWidth subdiv width ((P.shrinkArcEquiv layout subdiv outgoing).symm
+ (P.shrinkArcEquiv layout subdiv outgoing (.inr (z,g)))) = 0
+ simp [classWidth]
+
+/-- One shared word per original surviving motif wire is equivalent to one
+shared word per numbered arc of the padded output graph. Specializing
+`outgoing` to `dyadicSurvivingSlots.outgoing` gives the graph of Lemma C.1. -/
+def shrinkPayloadsEquiv (hpos : ∀ t, 0 < subdiv t) :
+ ((m : P.Motif) → (t : Fin 4) → Fin (width m t) → Bool) ≃
+ ((a : ((V × Tag) × L) × Fin d') →
+ Fin (P.shrinkSlotWidth layout subdiv width outgoing ((a.1.1,a.2),a.1.2)) → Bool) :=
+ (classPayloads subdiv width hpos).trans (Equiv.piCongrLeft'
+ (fun i ↦ Fin (classWidth subdiv width i) → Bool) (P.shrinkArcEquiv layout subdiv outgoing))
+
+/-- Looking up a genuine arc in the encoded assignment returns precisely
+its slice of the original motif word. -/
+theorem shrinkPayloadsEquiv_genuine (hpos : ∀ t, 0 < subdiv t)
+ (x : (m : P.Motif) → (t : Fin 4) → Fin (width m t) → Bool) (i : Id P.Motif subdiv) :
+ let a := P.shrinkArcEquiv layout subdiv outgoing (.inl i)
+ cast (congrArg (fun n ↦ Fin n → Bool)
+ (P.shrinkSlotWidth_genuine layout subdiv width outgoing i))
+ (P.shrinkPayloadsEquiv layout subdiv width outgoing hpos x a) =
+ sliceWords (width i.2.1 i.1) (subdiv i.1) (hpos i.1) (x i.2.1 i.1) i.2.2 := by
+ let e := P.shrinkArcEquiv layout subdiv outgoing
+ let z := classPayloads (D := ((V × Tag) × Fin pad) × L) subdiv width hpos x
+ change cast _ (z (e.symm (e (.inl i)))) = z (.inl i)
+ exact cast_eq_iff_heq.mpr (by rw [e.symm_apply_apply])
+
+/-- Numbering and zero-width padding preserve any additive charge on the
+widths with zero charge on a dummy. Taking the charge to be squared width
+divided by slot mass identifies the actual graph energy in (7.2). -/
+theorem sum_shrinkSlotWidth [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+ {A : Type*} [AddCommMonoid A] (charge : ℕ → A) (hzero : charge 0 = 0) :
+ (∑ a : ((V × Tag) × L) × Fin d',
+ charge (P.shrinkSlotWidth layout subdiv width outgoing ((a.1.1,a.2),a.1.2))) =
+ ∑ i : Id P.Motif subdiv, charge (splitWidth (width i.2.1 i.1) (subdiv i.1) i.2.2) := by
+ classical
+ let e := P.shrinkArcEquiv layout subdiv outgoing
+ let f (i : Id P.Motif subdiv ⊕ ((V × Tag) × Fin pad) × L) := charge (classWidth subdiv width i)
+ change (∑ a, f (e.symm a)) = _
+ rw [e.symm.sum_comp f, Fintype.sum_sum_type]
+ simp [f, classWidth, hzero]
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkProcedure.lean b/lean/OAI/Computability/VPVNP/ShrinkProcedure.lean
new file mode 100644
index 0000000000..ab96c46c1c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkProcedure.lean
@@ -0,0 +1,85 @@
+import OAI.Computability.VPVNP.CompressionProcedure
+import OAI.Computability.VPVNP.CompressionTemplates
+import OAI.Computability.VPVNP.ShrinkStatePass
+
+/-!
+# Running a shrinking template at one scheduled degree
+
+The template and scheduled degrees are fixed before the coefficient ring,
+its parameter assignment, the network and the number of remaining lanes.
+The exact shrinking pass has the position divisor and energy multiplier
+required to compose one block of Theorem 7.1.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+theorem packingLaneBits_add (a g : ℕ) : packingLaneBits a 0 + g = packingLaneBits a g := by
+ simp [packingLaneBits, Nat.add_assoc]
+
+namespace BlockSchedule.Templates
+
+open MotifConversion PackingData ShrinkEnergy ShrinkMotif
+
+variable {k : Type*} [Field k] {S : BlockSchedule k}
+variable (B : S.Templates) {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+variable (i : Fin S.steps)
+
+/-- The additive coefficient for this degree transition, before choosing
+any solution of the fixed scalar equations. -/
+noncomputable def shrinkRoundingError : ℝ :=
+ let d := 2 ^ S.degreeExponent i.castSucc
+ let d' := 2 ^ S.degreeExponent i.succ
+ let c := 2 * d + 1
+ max 0 (roundingConstant d d' (pieceCount d c) shrinkComparison B.shrink.energyConstant
+ (1 - shrinkLoss) (subdivisions d c d'))
+
+/-- The actual pass at any input lane length equal to the scheduled one. -/
+noncomputable def shrinkPassAt {g n : ℕ} (h : n = packingLaneBits (S.degreeExponent i.castSucc) g)
+ (X : State (S.degreeExponent i.castSucc) n) : StatePass R X (S.degreeExponent i.succ) g := by
+ subst n
+ exact X.shrinkStatePass B.shrink (f ∘ Sum.inl) ((B.solution_iff f).mp hf).1 (S.shrink i)
+
+theorem shrinkPassAt_positions {g n : ℕ} (h : n = packingLaneBits (S.degreeExponent i.castSucc) g)
+ (X : State (S.degreeExponent i.castSucc) n) (z : (B.shrinkPassAt f hf i h X).step.Choice) :
+ X.positions = packingFactor (S.degreeExponent i.castSucc) *
+ ((B.shrinkPassAt f hf i h X).next z).positions := by
+ subst n
+ exact X.shrinkStatePass_positions B.shrink (S.shrink i) (f ∘ Sum.inl)
+ ((B.solution_iff f).mp hf).1 z
+
+theorem shrinkPassAt_energy {g n : ℕ} (h : n = packingLaneBits (S.degreeExponent i.castSucc) g)
+ (X : State (S.degreeExponent i.castSucc) n) (z : (B.shrinkPassAt f hf i h X).step.Choice) :
+ ((B.shrinkPassAt f hf i h X).next z).energy ≤
+ shrinkMultiplier * X.energy + B.shrinkRoundingError i * (X.positions : ℝ) ^ 2 := by
+ subst n
+ have hz := X.shrinkStatePass_energy B.shrink (S.shrink i) (f ∘ Sum.inl)
+ ((B.solution_iff f).mp hf).1 shrink_constants.2.2.1 (by norm_num [shrinkComparison]) z
+ exact hz.trans (add_le_add_right (mul_le_mul_of_nonneg_right (le_max_right 0 _)
+ (sq_nonneg (X.positions : ℝ))) _)
+
+/-- An elementary scheduled shrinking procedure with the exact six-party
+expansion in every term and the bounds of (7.2). -/
+noncomputable def shrinkProcedure :
+ Procedure R (S.degreeExponent i.castSucc) (S.degreeExponent i.succ)
+ (packingLaneBits (S.degreeExponent i.castSucc) 0)
+ (packingFactor (S.degreeExponent i.castSucc))
+ shrinkMultiplier :=
+ Procedure.ofPass (by unfold packingFactor; positivity) shrink_constants.2.2.2.2.2.1.le
+ (le_max_left 0 _) (fun g X ↦ B.shrinkPassAt f hf i (packingLaneBits_add _ g) X)
+ (fun g X ↦ B.shrinkPassAt_positions f hf i (packingLaneBits_add _ g) X)
+ (fun g X ↦ B.shrinkPassAt_energy f hf i (packingLaneBits_add _ g) X)
+
+/-- The same additive error works over every ring and for every solution. -/
+@[simp] theorem shrinkProcedure_error : (B.shrinkProcedure f hf i).error =
+ B.shrinkRoundingError i := rfl
+
+end BlockSchedule.Templates
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkProcedureHistory.lean b/lean/OAI/Computability/VPVNP/ShrinkProcedureHistory.lean
new file mode 100644
index 0000000000..78da834dcb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkProcedureHistory.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.ShrinkProcedure
+import OAI.Computability.VPVNP.ShrinkStateHistory
+import OAI.Computability.VPVNP.CompressionProcedureHistory
+
+/-!
+# Local record bounds for a scheduled shrinking procedure
+
+A scheduled shrinking step has the same fixed six-party template at every
+remaining lane count. Transporting the lane length to the format of the
+dyadic state pass preserves its chosen records and their bounds. Thus the
+one-step history factor can be fixed before selecting the coefficient ring
+or any solution of the template equations.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.BlockSchedule.Templates
+
+variable {k : Type*} [Field k] {S : BlockSchedule k}
+variable (B : S.Templates) {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+variable (i : Fin S.steps)
+
+/-- At the scheduled lane length, use all actual slot and resident motif
+records of the selected dyadic state pass. -/
+private noncomputable def recordsAt {g n : ℕ}
+ (h : n = packingLaneBits (S.degreeExponent i.castSucc) g)
+ (X : State (S.degreeExponent i.castSucc) n) : (B.shrinkPassAt f hf i h X).Records := by
+ subst n
+ let hshrink := ((B.solution_iff f).mp hf).1
+ exact (X.shrinkStatePass B.shrink (f ∘ Sum.inl) hshrink (S.shrink i)).slotRecords
+ (X.shrinkExtraRecords B.shrink (f ∘ Sum.inl) hshrink (S.shrink i))
+
+private theorem boundedAt {g n : ℕ} (h : n = packingLaneBits (S.degreeExponent i.castSucc) g)
+ (X : State (S.degreeExponent i.castSucc) n) :
+ (B.shrinkPassAt f hf i h X).Bounded (B.recordsAt f hf i h X)
+ (State.shrinkHistoryFactor B.shrink (S.degreeExponent i.castSucc)
+ (S.degreeExponent i.succ)) := by
+ subst n
+ exact X.shrinkStatePass_bounded B.shrink (f ∘ Sum.inl) ((B.solution_iff f).mp hf).1 (S.shrink i)
+
+/-- Every branch of the scheduled shrinking procedure has one substep and
+satisfies the fixed history factor for its two degree exponents. -/
+noncomputable def shrinkProcedureRecords :
+ (B.shrinkProcedure f hf i).RecordBounds
+ (State.shrinkHistoryFactor B.shrink (S.degreeExponent i.castSucc)
+ (S.degreeExponent i.succ)) 1 :=
+ Procedure.RecordBounds.ofPass _ _ _ _ _ _
+ (fun g X ↦ B.recordsAt f hf i (packingLaneBits_add _ g) X)
+ (fun g X ↦ B.boundedAt f hf i (packingLaneBits_add _ g) X)
+
+end Compression.BlockSchedule.Templates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkProcedureWitness.lean b/lean/OAI/Computability/VPVNP/ShrinkProcedureWitness.lean
new file mode 100644
index 0000000000..e491954785
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkProcedureWitness.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.ShrinkStateWitness
+import OAI.Computability.VPVNP.ShrinkProcedure
+import OAI.Computability.VPVNP.CompressionMonomialHistory
+
+/-!
+# The scheduled shrinking procedure in the common parameter alphabet
+
+Shrinking maps use the first group of labels of the two fixed templates.
+The scheduled procedure retains every local hidden-field choice and every
+map witness for any input network and any number of remaining lanes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.BlockSchedule.Templates
+
+open NetworkKernel
+
+variable {k : Type*} [Field k] {S : BlockSchedule k}
+variable (B : S.Templates) {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f)
+variable (i : Fin S.steps)
+
+/-- The shrinking map at the scheduled degree contributes its parameter
+multiplicities in the shrinking summand of the common alphabet. -/
+noncomputable def shrinkPassWitnesses {g n : ℕ}
+ (h : n = packingLaneBits (S.degreeExponent i.castSucc) g)
+ (X : State (S.degreeExponent i.castSucc) n) : (B.shrinkPassAt f hf i h X).MapWitnesses f := by
+ subst n
+ intro sel v x z
+ exact MonomialWitness.left f (X.shrinkStateKernelWitness B.shrink (f ∘ Sum.inl)
+ ((B.solution_iff f).mp hf).1 (S.shrink i) sel v x z)
+
+set_option maxHeartbeats 1200000 in
+-- Elaborating the dependent input lane equality unfolds the concrete shrinking pass.
+/-- All executions of a scheduled shrinking procedure have the concrete
+finite parameter witnesses of their selected kernels. -/
+noncomputable def shrinkProcedureWitnesses : (B.shrinkProcedure f hf i).MapWitnesses f := by
+ exact Procedure.MapWitnesses.ofPass (by unfold packingFactor; positivity)
+ shrink_constants.2.2.2.2.2.1.le (le_max_left 0 _)
+ (fun g X ↦ B.shrinkPassAt f hf i (packingLaneBits_add _ g) X)
+ (fun g X ↦ B.shrinkPassAt_positions f hf i (packingLaneBits_add _ g) X)
+ (fun g X ↦ B.shrinkPassAt_energy f hf i (packingLaneBits_add _ g) X)
+ (fun g X ↦ B.shrinkPassWitnesses f hf i (packingLaneBits_add _ g) X)
+
+end Compression.BlockSchedule.Templates
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkRoles.lean b/lean/OAI/Computability/VPVNP/ShrinkRoles.lean
new file mode 100644
index 0000000000..4d490637aa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkRoles.lean
@@ -0,0 +1,103 @@
+import OAI.Computability.VPVNP.ShrinkMotifGraph
+import OAI.Computability.VPVNP.SurvivingSlots
+
+/-!
+# Placing the six parties in the two shrinking layouts
+
+In the first layout C and M move to A, and N moves to D. In the second
+layout C and N move to B, and M moves to D. Each absorbed edge has one
+owner, while the endpoints of the other four edges agree with the roles of
+the surviving slots.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+open SurvivingSlots
+
+namespace ShrinkMotif
+
+/-- Site role of A, B, C, D, M and N in each layout. -/
+def partyRole (layout : Bool) : Fin 6 → PackedRole
+ | 0 => .a
+ | 1 => .b
+ | 2 => if layout then .b else .a
+ | 3 => .d
+ | 4 => if layout then .d else .a
+ | 5 => if layout then .b else .d
+
+/-- Owner of the edge of this type from the absorbed group. -/
+def internalRole (layout : Bool) (t : Fin 4) : PackedRole :=
+ partyRole layout (supply.src (!layout,t))
+
+theorem role_src_survives (l : Bool) (t : Fin 4) :
+ partyRole l (supply.src (l,t)) = sourceRole l t :=
+ (by decide : ∀ l t, partyRole l (supply.src (l,t)) = sourceRole l t) l t
+
+theorem role_dst_survives (l : Bool) (t : Fin 4) :
+ partyRole l (supply.dst (l,t)) = targetRole l t :=
+ (by decide : ∀ l t, partyRole l (supply.dst (l,t)) = targetRole l t) l t
+
+theorem role_src_absorbed (l : Bool) (t : Fin 4) :
+ partyRole l (supply.src (!l,t)) = internalRole l t := rfl
+
+theorem role_dst_absorbed (l : Bool) (t : Fin 4) :
+ partyRole l (supply.dst (!l,t)) = internalRole l t :=
+ (by decide : ∀ l t, partyRole l (supply.dst (!l,t)) = internalRole l t) l t
+
+variable {M V k : Type*} [Fintype M] [Fintype V] [DecidableEq V] [CommMonoid k]
+
+/-- All six-party factors resident at a site, with its equality proof available
+when reading the factor's local arguments. -/
+def partyProduct (site : M → Fin 6 → V) (v : V)
+ (factor : ∀ m j, v = site m j → k) : k :=
+ ∏ m, ∏ j, if h : v = site m j then factor m j h else 1
+
+/-- Placing the factors at their resident sites preserves the full product. -/
+theorem prod_partyProduct (site : M → Fin 6 → V) (factor : ∀ v m j, v = site m j → k) :
+ (∏ v, partyProduct site v (factor v)) = ∏ m, ∏ j, factor (site m j) m j rfl := by
+ unfold partyProduct
+ rw [Finset.prod_comm]
+ apply Finset.prod_congr rfl
+ intro m _
+ rw [Finset.prod_comm]
+ apply Finset.prod_congr rfl
+ intro j _
+ exact Fintype.prod_dite_eq' _ _
+
+end ShrinkMotif
+
+/-- Site coordinates used in the new lifted graph, with the tag in its base. -/
+def packedSiteEquiv {V Tag L : Type*} : Site V Tag L ≃ (V × Tag) × L :=
+ (Equiv.prodAssoc V Tag L).symm
+
+namespace PackingData
+
+variable {V H Tag L : Type*} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- Placement of each whole old position on the new lifted graph. -/
+def shrinkPlace (l : Bool) (u : Position V H Tag L c) : (V × Tag) × L :=
+ packedSiteEquiv (P.placement l u)
+
+/-- The six map matrices are assigned to three packed positions. -/
+def shrinkPartySite (l : Bool) (m : P.Motif) (j : Fin 6) : (V × Tag) × L :=
+ packedSiteEquiv (P.survivingRole l (ShrinkMotif.partyRole l j) m)
+
+/-- Each absorbed supply edge is summed at the common site of its endpoints. -/
+def shrinkInternalOwner (l : Bool) (e : P.Motif × Fin 4) : (V × Tag) × L :=
+ packedSiteEquiv (P.survivingRole l (ShrinkMotif.internalRole l e.2) e.1)
+
+theorem shrinkPartySite_C (l : Bool) (m : P.Motif) :
+ P.shrinkPartySite l m 2 = P.shrinkPlace l (P.C m) := by
+ cases l <;> simp [shrinkPartySite, shrinkPlace, ShrinkMotif.partyRole, survivingRole, roleMap]
+
+end PackingData
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkStateHistory.lean b/lean/OAI/Computability/VPVNP/ShrinkStateHistory.lean
new file mode 100644
index 0000000000..543a8611de
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkStateHistory.lean
@@ -0,0 +1,81 @@
+import OAI.Computability.VPVNP.ShrinkHistory
+import OAI.Computability.VPVNP.ShrinkStatePass
+import OAI.Computability.VPVNP.StatePassHistory
+
+/-!
+# History bounds for the actual dyadic shrinking pass
+
+For each admissible selection the records contain its resident maps,
+absorbed fields and map arguments together with all old and new half-wire
+fields. The bound for this substep depends only on the two degree exponents
+and the fixed conversion block. It applies uniformly at every packed site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.State
+
+open NetworkKernel MotifBlocks MotifGrid MotifConversion PackingData ShrinkMotif ShrinkEnergy
+
+variable {a b g : ℕ} {δ factor : ℝ} (X : State a (packingLaneBits a g))
+variable {k : Type*} [Field k]
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable {R : Type*} [CommRing R] (κ : (parameterData B).Entry → R)
+variable (hκ : (parameterData B).IsSolution κ)
+variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ)
+
+open Classical in
+/-- Records of the selected six-party kernels before adding the actual
+old and new incident half-words. -/
+noncomputable def shrinkExtraRecords : (X.shrinkStatePass B κ hκ ready).Records :=
+ fun s v ↦ X.packingData.shrinkSiteRecords X.shrinkNumber X.packingWidth B s
+ (X.packingData.shrinkTermLayout B X.shrinkNumber X.packingWidth s) v
+
+/-- The fixed per-substep history growth factor. `K` counts old positions
+and `r = dQ` counts occurrences of each packed role. -/
+noncomputable def shrinkHistoryFactor (a b : ℕ) : ℕ :=
+ let d := 2 ^ a
+ let c := 2 * d + 1
+ let K := 2 ^ c * d
+ let r := d * pieceCount d c
+ let D := 1 + 6 * r + 4 * r + (6 * r) * 10
+ max (D + K * (2 * d) + 2 * 2 ^ b + K) (max 1 (fieldFactor B) + 1)
+
+/-- The exact state pass has the bounded local histories used in Theorem 7.1. -/
+theorem shrinkStatePass_bounded :
+ (X.shrinkStatePass B κ hκ ready).Bounded
+ ((X.shrinkStatePass B κ hκ ready).slotRecords (X.shrinkExtraRecords B κ hκ ready))
+ (shrinkHistoryFactor B a b) := by
+ classical
+ let P := X.packingData
+ let d := 2 ^ a
+ let c := 2 * d + 1
+ let r := d * pieceCount d c
+ have hc := two_le_packingColors a
+ have hd := Nat.two_pow_pos a
+ have hw (x) : X.packingWidth x ≤ X.maxWireWidth := X.width_le_maxWireWidth _
+ apply StatePass.slotRecords_bounded _ _ (2 ^ c * d)
+ (1 + 6 * r + 4 * r + (6 * r) * 10) (max 1 (fieldFactor B)) (le_max_left ..)
+ · intro i v
+ have h := P.card_reindexed_shrinkPlace (P.shrinkTermLayout B X.shrinkNumber X.packingWidth i)
+ v (packingInputSites X.Base a g) (by omega)
+ rw [← Nat.card_eq_fintype_card]
+ exact h.le
+ · intro i v
+ exact P.shrinkSiteRecords_count_le X.shrinkNumber X.packingWidth B i _ v hc
+ · intro i v
+ exact P.shrinkSiteRecords_largest_le X.shrinkNumber X.packingWidth B i _ v hc hd hw
+ · intro i e
+ let l := P.shrinkTermLayout B X.shrinkNumber X.packingWidth i
+ exact (P.shrinkSlotWidth_le hc hd X.shrinkNumber X.packingWidth hw B i l
+ (subdivisions d c (2 ^ b)) (X.shrinkStateIndex ready l).outgoing e).trans
+ (Nat.mul_le_mul_right _ (le_max_right ..))
+
+end Compression.State
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkStateInput.lean b/lean/OAI/Computability/VPVNP/ShrinkStateInput.lean
new file mode 100644
index 0000000000..ed2f75076d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkStateInput.lean
@@ -0,0 +1,111 @@
+import OAI.Computability.VPVNP.CompressionState
+import OAI.Computability.VPVNP.NetworkHalfIso
+import OAI.Computability.VPVNP.SlotDemandKernel
+import OAI.Computability.VPVNP.ShrinkEnergy
+
+/-!
+# Reindexing the actual input of a shrinking pass
+
+The state network numbers an outgoing edge by a full site and a slot.
+Appendix C writes the same edge in color, slot-label, tag and remaining-lane
+coordinates. The following relabelling identifies both incident sites and
+the entire payload of each directed edge, including parallel edges.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+open NetworkKernel
+
+/-- Reassemble all lane fields of a packed input position. -/
+def packingInputSites (V : Type) (a g : ℕ) :
+ Position V (BitWord a) (BitWord (packingTagBits (2 ^ a))) (BitWord g) (2 * 2 ^ a + 1) ≃
+ V × BitWord (packingLaneBits a g) where
+ toFun p := (p.1.1, (packingFields a g).symm (p.2.1, p.2.2, p.1.2))
+ invFun p :=
+ let f := packingFields a g p.2
+ ((p.1, f.2.2), f.1, f.2.1)
+ left_inv := by rintro ⟨⟨v,j,l⟩,w,h⟩; simp
+ right_inv := by rintro ⟨v,l⟩; simp
+
+/-- Reassemble the outgoing edge in the original state network's site-first
+numbering. The local slot index is retained at both ends. -/
+def packingInputEdges (V : Type) (a g : ℕ) :
+ Arc V (BitWord a) (BitWord (packingTagBits (2 ^ a))) (BitWord g) (2 ^ a) (2 * 2 ^ a + 1) ≃
+ (V × BitWord (packingLaneBits a g)) × Fin (2 ^ a) where
+ toFun e := (packingInputSites V a g (sourcePosition e), e.1.2)
+ invFun e := packingArcEquiv V a g ((e.1.1, e.2), e.1.2)
+ left_inv := by rintro ⟨⟨⟨v,j,l⟩,i⟩,w,h⟩; simp [packingInputSites, sourcePosition, packingArcEquiv]
+ right_inv := by rintro ⟨⟨v,l⟩,i⟩; simp [packingInputSites, sourcePosition, packingArcEquiv]
+
+namespace State
+
+variable {a g : ℕ} (X : State a (packingLaneBits a g))
+
+/-- Color and tag the base vertices in their stored numerical order. -/
+abbrev packingData := orderedDyadicPacking X.slots X.baseIndex
+
+/-- Old widths in the field order of the shrinking construction. -/
+abbrev packingWidth :=
+ X.width ∘ (packingArcEquiv X.Base a g).symm
+
+/-- An isomorphism of the old wire tensor in the proof with the tensor of the
+input state. On each word alphabet it is the identity. -/
+noncomputable def packingInputIso :
+ (X.packingData.oldWireNetwork X.packingWidth).Iso X.network where
+ site := packingInputSites X.Base a g
+ edge := packingInputEdges X.Base a g
+ src _ := rfl
+ dst e := by
+ change Arc X.Base (BitWord a) (BitWord (packingTagBits (2 ^ a))) (BitWord g)
+ (2 ^ a) (2 * 2 ^ a + 1) at e
+ let A := packingArcEquiv X.Base a g
+ have h := congrArg A.symm (orderedDyadicPacking_actual X.slots X.baseIndex (A.symm e))
+ change A.symm (X.packingData.actual (A (A.symm e))) =
+ A.symm (A (X.slots.actualTarget (A.symm e))) at h
+ rw [A.apply_symm_apply, A.symm_apply_apply] at h
+ change ((A.symm (X.packingData.actual e)).1.1,
+ (A.symm (X.packingData.actual e)).2) = _
+ rw [h]
+ rfl
+ payload _ := Equiv.refl _
+
+/-- The independent incoming and outgoing half-words at each state site
+correspond to the packed half-words at its preimage. -/
+noncomputable def packingHalfEquiv
+ (p : (X.packingData.oldWireNetwork X.packingWidth).Site) :=
+ X.packingInputIso.pullHalfEquiv p
+
+/-- Transport an entire packed identity, including its local kernels, to the
+actual input coordinates. Every output keeps its original numbering. -/
+noncomputable def reindexPackingStep {R : Type*} [CommSemiring R]
+ (s : Step R (X.packingData.oldWireNetwork X.packingWidth)) :
+ Step R X.network :=
+ s.reindexInput X.packingInputIso
+
+/-- Packing the input coordinates preserves the count of processor sites. -/
+theorem positions_packing :
+ X.positions = Fintype.card (Position X.Base (BitWord a) (BitWord (packingTagBits (2 ^ a)))
+ (BitWord g) (2 * 2 ^ a + 1)) :=
+ (Fintype.card_congr (packingInputSites X.Base a g)).symm
+
+/-- The old sum in the shrinking estimate is exactly the input state's energy. -/
+theorem energy_packingWidth :
+ X.energy = ∑ e, (X.packingWidth e : ℝ) ^ 2 /
+ ShrinkEnergy.equalArcMass (Position X.Base (BitWord a) (BitWord (packingTagBits (2 ^ a)))
+ (BitWord g) (2 * 2 ^ a + 1)) (2 ^ a) := by
+ unfold energy ShrinkEnergy.equalArcMass
+ rw [X.positions_packing]
+ apply Fintype.sum_equiv (packingArcEquiv X.Base a g)
+ intro e
+ simp [packingWidth]
+
+end State
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkStateOutput.lean b/lean/OAI/Computability/VPVNP/ShrinkStateOutput.lean
new file mode 100644
index 0000000000..8aa8aa7b1c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkStateOutput.lean
@@ -0,0 +1,78 @@
+import OAI.Computability.VPVNP.ShrinkStateInput
+import OAI.Computability.VPVNP.ShrinkSupplyReadout
+
+/-!
+# The output state of a selected shrinking layout
+
+The surviving output is already a directed regular lift over the old base
+and the tag field. Its subdivisions supply the widths of the new numbered
+arcs, including the zero widths on cyclic padding arcs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.State
+
+open PackingData SurvivingSlots ShrinkEnergy
+
+variable {a b g pad : ℕ} (X : State a (packingLaneBits a g))
+variable (layout : Bool) (subdiv : Fin 4 → ℕ)
+variable (width : X.packingData.Motif → Fin 4 → ℕ)
+variable {next : Equiv.Perm (X.Base × BitWord (packingTagBits (2 ^ a)))}
+variable (I : X.packingData.ShrinkIndex layout subdiv next (2 ^ b) pad)
+
+/-- The tag becomes part of the base, and only the unconsumed binary lane
+field participates in the next lift. -/
+noncomputable def shrinkOutputState : State b g where
+ Base := X.Base × BitWord (packingTagBits (2 ^ a))
+ baseFintype := inferInstance
+ baseNonempty := inferInstance
+ baseIndex := productIndex X.baseIndex (bitWordFinEquiv (packingTagBits (2 ^ a)))
+ slots := I.graph
+ width := X.packingData.shrinkSlotWidth layout subdiv width I.outgoing
+
+/-- The output used by the local matrices is exactly the next state's network. -/
+theorem shrinkOutputState_network :
+ (X.shrinkOutputState layout subdiv width I).network =
+ X.packingData.shrinkOutput layout subdiv width I := rfl
+
+/-- Every list of motif choices packs the input sites by the same factor K. -/
+theorem shrinkOutputState_positions :
+ X.positions = (2 ^ (2 * 2 ^ a + 1) * 2 ^ a) *
+ (X.shrinkOutputState layout subdiv width I).positions := by
+ refine (packing_position_count X.Base a g).trans ?_
+ congr 1
+ exact Fintype.card_congr (Equiv.prodAssoc _ _ _).symm
+
+/-- The energy on genuine motif slots equals the full state energy, since
+the zero-width padding has zero charge. -/
+theorem shrinkOutputState_energy :
+ (X.shrinkOutputState layout subdiv width I).energy =
+ ∑ i : Id X.packingData.Motif subdiv,
+ (splitWidth (width i.2.1 i.1) (subdiv i.1) i.2.2 : ℝ) ^ 2 /
+ equalArcMass (Site X.Base (BitWord (packingTagBits (2 ^ a))) (BitWord g)) (2 ^ b) := by
+ let Y := X.shrinkOutputState layout subdiv width I
+ have hpos : Y.positions =
+ Fintype.card (Site X.Base (BitWord (packingTagBits (2 ^ a))) (BitWord g)) :=
+ Fintype.card_congr (Equiv.prodAssoc _ _ _)
+ let p := equalArcMass (Site X.Base (BitWord (packingTagBits (2 ^ a))) (BitWord g)) (2 ^ b)
+ let charge (n : ℕ) := (n : ℝ) ^ 2 / p
+ let e : ((Y.Base × Fin (2 ^ b)) × BitWord g) ≃ (Y.Base × BitWord g) × Fin (2 ^ b) :=
+ { toFun := fun p ↦ ((p.1.1, p.2), p.1.2)
+ invFun := fun p ↦ ((p.1.1, p.2), p.1.2)
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ change (∑ e, (Y.width e : ℝ) ^ 2 / (1 / ((Y.positions : ℝ) * (2 ^ b : ℕ)))) = _
+ rw [hpos]
+ change (∑ e, charge (Y.width e)) = _
+ rw [← e.symm.sum_comp (fun e ↦ charge (Y.width e))]
+ exact X.packingData.sum_shrinkSlotWidth layout subdiv width I.outgoing
+ charge (by simp [charge])
+
+end Compression.State
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkStatePass.lean b/lean/OAI/Computability/VPVNP/ShrinkStatePass.lean
new file mode 100644
index 0000000000..fe08589482
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkStatePass.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.ShrinkStep
+import OAI.Computability.VPVNP.ShrinkingSlots
+import OAI.Computability.VPVNP.SlotBundleNumbering
+import OAI.Computability.VPVNP.ShrinkStateOutput
+
+/-!
+# A shrinking pass on a compressor state
+
+Both numberings of each thick bundle are fixed before the local identities
+are applied. The term choices then determine the layout and the widths of
+the indexed output slots. The resulting state has the output degree and
+unconsumed lane length required by the block schedule.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.State
+
+open NetworkKernel MotifBlocks MotifGrid MotifConversion PackingData
+open ShrinkMotif ShrinkEnergy SurvivingSlots
+
+variable {a b g : ℕ} {δ factor : ℝ} (X : State a (packingLaneBits a g))
+
+/-- Classical equality test on base sites used in the dyadic shrinking pass. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- The dyadic coloring has enough coordinates for two distinct endpoint colors. -/
+theorem two_le_packingColors (a : ℕ) : 2 ≤ 2 * 2 ^ a + 1 := by
+ have := Nat.two_pow_pos a
+ omega
+
+/-- Use the same finite base enumeration as the dyadic coloring and offset scans. -/
+abbrev shrinkBaseOrder := X.baseIndex
+
+/-- Number surviving slots by the mixed-radix keys of the lane-zero IDs. -/
+noncomputable def shrinkStateIndex (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ)
+ (layout : Bool) :=
+ let m := subdivisions (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b)
+ orderedDyadicSurvivingSlots X.slots X.baseIndex layout m ready.degree_budget
+
+/-- Order the CD pieces by their lane-relative old arc identifiers. -/
+noncomputable abbrev shrinkNumber :=
+ X.packingData.sortedBundleNumbering X.shrinkBaseOrder
+ (bitWordFinEquiv (packingTagBits (2 ^ a))) (two_le_packingColors a)
+
+/-- Concatenate old thick wires in the common binary coordinate order. -/
+noncomputable abbrev shrinkOrder :=
+ X.packingData.sortedThickNumbering (two_le_packingColors a)
+
+variable {k : Type*} [Field k]
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ)
+
+/-- A choice of one admitted local term on each CD occurrence. -/
+noncomputable abbrev ShrinkSelection :=
+ ∀ m, X.packingData.ShrinkChoice X.shrinkNumber X.packingWidth B m
+
+/-- The next state determined by one entire list of motif selections. -/
+noncomputable def shrinkNext (s : X.ShrinkSelection B) : State b g :=
+ let p := equalArcMass (Position X.Base (BitWord a) (BitWord (packingTagBits (2 ^ a)))
+ (BitWord g) (2 * 2 ^ a + 1)) (2 ^ a)
+ let w := X.packingData.termWidths B X.shrinkNumber X.packingWidth s
+ let l := chosenLayout p (fun e ↦ (relativeMass e : ℝ)) w
+ X.shrinkOutputState l (subdivisions (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b))
+ (fun m t ↦ w m l t) (X.shrinkStateIndex ready l)
+
+theorem shrinkNext_positions (s : X.ShrinkSelection B) :
+ X.positions = (2 ^ (2 * 2 ^ a + 1) * 2 ^ a) * (X.shrinkNext B ready s).positions :=
+ X.shrinkOutputState_positions _ _ _ _
+
+/-- Equation (7.2) in the coordinates retained between compressor substeps. -/
+theorem shrinkNext_energy (hδ : δ < 1) (hf : 0 ≤ factor) (s : X.ShrinkSelection B) :
+ (X.shrinkNext B ready s).energy ≤
+ factor / (2 * (1 - δ)) * X.energy +
+ roundingConstant (2 ^ a) (2 ^ b) (pieceCount (2 ^ a) (2 * 2 ^ a + 1))
+ factor B.energyConstant (1 - δ) (subdivisions (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b)) *
+ (X.positions : ℝ) ^ 2 := by
+ unfold shrinkNext
+ rw [shrinkOutputState_energy, X.energy_packingWidth, X.positions_packing]
+ exact X.packingData.packed_energy_from_terms B X.shrinkNumber X.packingWidth s
+ (two_le_packingColors _) (Nat.two_pow_pos _) ready hδ hf
+
+variable {R : Type*} [CommRing R] (κ : (parameterData B).Entry → R)
+variable (hκ : (parameterData B).IsSolution κ)
+
+/-- The exact shrinking identity on a compressor state. Every term carries
+its own subsequent state with the prescribed output degree and remaining lane. -/
+noncomputable def shrinkStatePass (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) :
+ StatePass R X b g where
+ step := X.reindexPackingStep (X.packingData.shrinkStep B κ hκ (two_le_packingColors a)
+ (Nat.two_pow_pos a) X.shrinkNumber
+ X.shrinkOrder X.packingWidth ready (X.shrinkStateIndex ready))
+ next := X.shrinkNext B ready
+ output_eq _ := rfl
+
+theorem shrinkStatePass_positions (s : X.ShrinkSelection B) :
+ X.positions = (2 ^ (2 * 2 ^ a + 1) * 2 ^ a) *
+ ((X.shrinkStatePass B κ hκ ready).next s).positions := X.shrinkNext_positions B ready s
+
+theorem shrinkStatePass_energy (hδ : δ < 1) (hf : 0 ≤ factor) (s : X.ShrinkSelection B) :
+ ((X.shrinkStatePass B κ hκ ready).next s).energy ≤
+ factor / (2 * (1 - δ)) * X.energy +
+ roundingConstant (2 ^ a) (2 ^ b) (pieceCount (2 ^ a) (2 * 2 ^ a + 1))
+ factor B.energyConstant (1 - δ) (subdivisions (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b)) *
+ (X.positions : ℝ) ^ 2 := X.shrinkNext_energy B ready hδ hf s
+
+end Compression.State
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkStateWitness.lean b/lean/OAI/Computability/VPVNP/ShrinkStateWitness.lean
new file mode 100644
index 0000000000..c8877709c3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkStateWitness.lean
@@ -0,0 +1,64 @@
+import OAI.Computability.VPVNP.ShrinkMonomialWitness
+import OAI.Computability.VPVNP.ShrinkStatePass
+import OAI.Computability.VPVNP.NetworkMonomialIso
+
+/-!
+# Parameter witnesses of the shrinking pass on a compressor state
+
+The change of coordinates that packs the old site and its lane for the
+shrinking step pulls the old half-wire arguments back to their packed
+forms. Every surviving local witness has the same formal exponent vector.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.State
+
+open NetworkKernel MotifBlocks MotifGrid MotifConversion PackingData ShrinkMotif
+
+variable {a b g : ℕ} {δ factor : ℝ} (X : State a (packingLaneBits a g))
+variable {k : Type*} [Field k]
+variable (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor)
+variable {R : Type*} [CommRing R] (κ : (parameterData B).Entry → R)
+variable (hκ : (parameterData B).IsSolution κ)
+variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ)
+
+/-- Classical equality test on base sites used to construct monomial witnesses for the
+shrinking kernels. -/
+noncomputable local instance : DecidableEq X.Base := Classical.decEq _
+
+/-- Every entry of every selected kernel in the dyadic shrinking state
+pass is a finite sum of parameter monomials. The witnesses enumerate the
+absorbed words and the accepted resident matrix checks. -/
+noncomputable def shrinkStateKernelWitness :
+ ∀ s v x z, MonomialWitness κ (((X.shrinkStatePass B κ hκ ready).step.term s).kernel v x z) := by
+ let P := X.packingData
+ let hc := two_le_packingColors a
+ let hd := Nat.two_pow_pos a
+ let order := X.shrinkOrder
+ let step := P.shrinkStep B κ hκ hc hd X.shrinkNumber order X.packingWidth ready
+ (X.shrinkStateIndex ready)
+ exact step.reindexInputWitness X.packingInputIso
+ (P.shrinkKernelWitness hc hd X.shrinkNumber order X.packingWidth B κ hκ ready
+ (X.shrinkStateIndex ready))
+
+/-- The parameter degree bound survives the coordinate change on the
+old half-wire inputs of the state pass. -/
+theorem shrinkStateKernelWitness_degree_le (s : X.ShrinkSelection B) (v x z)
+ (w : (X.shrinkStateKernelWitness B κ hκ ready s v x z).Choice) {W : ℕ}
+ (hW : ∀ e, X.width e ≤ W) :
+ (∑ label, (X.shrinkStateKernelWitness B κ hκ ready s v x z).exponents w label) ≤
+ (6 * (2 ^ a * pieceCount (2 ^ a) (2 * 2 ^ a + 1)) * fieldFactor B) * (W + 1) := by
+ let P := X.packingData
+ let hc := two_le_packingColors a
+ exact P.shrinkKernelWitness_degree_le hc (Nat.two_pow_pos a) X.shrinkNumber X.shrinkOrder
+ X.packingWidth B κ hκ ready (X.shrinkStateIndex ready) s v _ _ w (fun e ↦ hW _)
+
+end Compression.State
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkStep.lean b/lean/OAI/Computability/VPVNP/ShrinkStep.lean
new file mode 100644
index 0000000000..f4fd7c4382
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkStep.lean
@@ -0,0 +1,74 @@
+import OAI.Computability.VPVNP.PackedShrinkStep
+import OAI.Computability.VPVNP.ShrinkLayout
+
+/-!
+# Exact contraction of the shrinking step
+
+For any list of admissible six-party terms, one common layout minimizes
+surviving energy. This determines the placement of every old factor and the
+regular lift carrying the surviving payloads. Equation (7.1) sums the placed
+kernels on these lifts, with one shared value on each new wire.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+open NetworkKernel WireTensor MotifGrid MotifBlocks MotifConversion MotifSelector
+open ShrinkMotif ShrinkEnergy
+
+variable {V H Tag L : Type} {d c d' pad : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (P : PackingData V H Tag L d c)
+variable {k : Type*} [Field k] {H' δ : ℝ} (B : FixedBlock k demandSource demandTarget supply
+ (realWidths demandMass) (realWidths supplyMass) (31 / 16) H')
+variable {R : Type*} [CommRing R] (κ : (parameterData B).Entry → R)
+variable (hκ : (parameterData B).IsSolution κ) (hc : 2 ≤ c) (hd : 0 < d)
+variable (number : P.BundleNumbering) (order : P.ThickNumbering) (w : Arc V H Tag L d c → ℕ)
+variable (ready : Ready d c d' δ) {next : Equiv.Perm (V × Tag)}
+variable (I : ∀ l : Bool, P.ShrinkIndex l (subdivisions d c d') next d' pad)
+
+/-- Select one layout for all motifs using their aggregate supply energies. -/
+noncomputable def shrinkTermLayout (s : ∀ m, P.ShrinkChoice number w B m) : Bool :=
+ chosenLayout (equalArcMass (Position V H Tag L c) d) (fun t ↦ (relativeMass t : ℝ))
+ (P.termWidths B number w s)
+
+/-- The complete shrinking kernel, with the actual six-party identities,
+padded output arcs, and local contractions of absorbed wire values. -/
+noncomputable def shrinkStep : Step R (P.oldWireNetwork w) := by
+ let C := P.ShrinkChoice number w B
+ let W (m : P.Motif) (i : C m) := P.shrinkSupplyWidths number w B m i
+ let X (m : P.Motif) (i : C m) := (e : Bool × Fin 4) → Word (W m i e)
+ let l (s : ∀ m, C m) := P.shrinkTermLayout B number w s
+ let T (s : ∀ m, C m) := P.shrinkLayout hc hd number order w (l s) (subdivisions d c d')
+ (fun m ↦ W m (s m)) (I (l s)) ready.count_pos (fun m ↦ P.shrinkMap number w B κ m (s m))
+ refine Step.ofMotifProduct C X (P.demandCoeff hc hd number order w)
+ (fun m i z a ↦ ∏ j, P.shrinkMap number w B κ m i j
+ (P.shrinkDemandArg hc hd number order w m a j) (edgeAssignment supply.src supply.dst z j))
+ (P.oldWireNetwork_coeff hc hd number order w)
+ (P.shrinkDemand_identity hc hd number order w B κ hκ)
+ T (fun s ↦ P.shrinkAssignmentsEquiv (l s) (subdivisions d c d')
+ (fun m ↦ W m (s m)) (I (l s)) ready.count_pos) ?_
+ exact fun s x a ↦ P.shrinkLayout_group hc hd number order w (l s) (subdivisions d c d')
+ (fun m ↦ W m (s m)) (I (l s)) ready.count_pos (fun m ↦ P.shrinkMap number w B κ m (s m)) x a
+
+/-- The lift and widths passed to the next substep. -/
+theorem shrinkStep_output (s : ∀ m, P.ShrinkChoice number w B m) :
+ let l := P.shrinkTermLayout B number w s
+ ((P.shrinkStep B κ hκ hc hd number order w ready I).term s).output =
+ P.shrinkOutput l (subdivisions d c d') (fun m t ↦ P.termWidths B number w s m l t)
+ (I l) := rfl
+
+/-- A selected term moves each complete old position once. -/
+theorem shrinkStep_place (s : ∀ m, P.ShrinkChoice number w B m) :
+ ((P.shrinkStep B κ hκ hc hd number order w ready I).term s).place =
+ P.shrinkPlace (P.shrinkTermLayout B number w s) := rfl
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkSupplyLocal.lean b/lean/OAI/Computability/VPVNP/ShrinkSupplyLocal.lean
new file mode 100644
index 0000000000..345737e800
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkSupplyLocal.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.ShrinkRoles
+import OAI.Computability.VPVNP.ShrinkSupplyReadout
+import OAI.Computability.VPVNP.RAMSerialization
+
+/-!
+# Reading a six-party supply map at its packed site
+
+The four surviving wires are read from the contiguous slices incident at the
+site. Each absorbed wire is read from the single internal index at its owner.
+This reconstructs both endpoint columns of every map in the shrinking layout,
+including when the half-wire indices on the output graph are independent.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.ShrinkMotif
+
+/-- Indices of the four absorbed wires of each motif. -/
+abbrev internalLabel {M : Type} (width : M → Bool × Fin 4 → ℕ) (layout : Bool)
+ (e : M × Fin 4) := Fin (2 ^ width e.1 (!layout,e.2))
+
+/-- Read one of two dependent fields, according to its layout bit. -/
+private def layoutCases (F : Bool → Type*) :
+ (l : Bool) → F l → F (!l) → (b : Bool) → F b
+ | false, x, _, false => x
+ | false, _, y, true => y
+ | true, _, y, false => y
+ | true, x, _, true => x
+
+private theorem layoutCases_active (F : Bool → Type*) (l : Bool) (x : F l) (y : F (!l)) :
+ layoutCases F l x y l = x := by cases l <;> rfl
+
+private theorem layoutCases_absorbed (F : Bool → Type*) (l : Bool) (x : F l) (y : F (!l)) :
+ layoutCases F l x y (!l) = y := by cases l <;> rfl
+
+/-- Split all eight motif labels into the surviving words and the four
+internally summed indices. -/
+private def splitSupply {M : Type} (width : M → Bool × Fin 4 → ℕ) (layout : Bool) :
+ ((m : M) → (e : Bool × Fin 4) → Fin (2 ^ width m e)) ≃
+ ((m : M) → (t : Fin 4) → Fin (width m (layout,t)) → Bool) ×
+ ((e : M × Fin 4) → internalLabel width layout e) where
+ toFun x := (fun m t ↦ RAMSerialization.wordBits _ (x m (layout,t)),
+ fun e ↦ x e.1 (!layout,e.2))
+ invFun z m e := layoutCases (fun l ↦ (t : Fin 4) → Fin (2 ^ width m (l,t))) layout
+ (fun t ↦ (RAMSerialization.wordBits _).symm (z.1 m t)) (fun t ↦ z.2 (m,t)) e.1 e.2
+ left_inv x := by
+ funext m ⟨l,t⟩
+ by_cases h : l = layout
+ · subst l
+ simp only [layoutCases_active, Equiv.symm_apply_apply]
+ · rw [Bool.eq_not_of_ne h]
+ simp only [layoutCases_absorbed]
+ right_inv z := by
+ apply Prod.ext
+ · funext m t
+ simp only [layoutCases_active, Equiv.apply_symm_apply]
+ · funext e
+ simp only [layoutCases_absorbed]
+
+end Compression.ShrinkMotif
+
+namespace Compression.PackingData
+
+open ShrinkMotif SurvivingSlots NetworkKernel WireTensor
+
+variable {V H Tag L : Type} {c d d' pad : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (layout : Bool) (subdiv : Fin 4 → ℕ)
+variable (width : P.Motif → Bool × Fin 4 → ℕ) {next : Equiv.Perm (V × Tag)}
+variable (I : P.ShrinkIndex layout subdiv next d' pad) (hpos : ∀ t, 0 < subdiv t)
+variable [Fintype V] [Fintype Tag] [Fintype L]
+
+local notation "N" => P.shrinkOutput layout subdiv (fun m t ↦ width m (layout,t)) I
+
+/-- Reindex a sum over all shared supply labels by one shared assignment
+to the output graph and one shared index per absorbed edge. -/
+noncomputable def shrinkAssignmentsEquiv :
+ ((m : P.Motif) → (e : Bool × Fin 4) → Fin (2 ^ width m e)) ≃
+ ((a : (N).Edge) → (N).Payload a) × ((e : P.Motif × Fin 4) → internalLabel width layout e) :=
+ (splitSupply width layout).trans ((P.shrinkPayloadsEquiv layout subdiv
+ (fun m t ↦ width m (layout,t)) I.outgoing hpos).prodCongr (Equiv.refl _))
+
+theorem shrinkAssignmentsEquiv_apply (x : (m : P.Motif) → (e : Bool × Fin 4) → Fin (2 ^ width m e)) :
+ P.shrinkAssignmentsEquiv layout subdiv width I hpos x =
+ (P.shrinkPayloadsEquiv layout subdiv (fun m t ↦ width m (layout,t)) I.outgoing hpos
+ (fun m t ↦ RAMSerialization.wordBits _ (x m (layout,t))), fun e : P.Motif × Fin 4 ↦ x e.1 (!layout,e.2)) :=
+ rfl
+
+variable (m : P.Motif) (j : Fin 6)
+
+private def readSupplyEnd (endParty : Bool × Fin 4 → Fin 6) (role : Fin 4 → PackedRole)
+ (active : ∀ t, partyRole layout (endParty (layout,t)) = role t)
+ (absorbed : ∀ t, partyRole layout (endParty (!layout,t)) = internalRole layout t)
+ (readWord : (t : Fin 4) → (N).Half (packedSiteEquiv (P.survivingRole layout (role t) m)) →
+ Fin (width m (layout,t)) → Bool)
+ (h : Placed (P.shrinkInternalOwner layout) (internalLabel width layout) (P.shrinkPartySite layout m j))
+ (z : (N).Half (P.shrinkPartySite layout m j)) (e : Bool × Fin 4) :
+ j = endParty e → Fin (2 ^ width m e) :=
+ layoutCases (fun l ↦ (t : Fin 4) → j = endParty (l,t) → Fin (2 ^ width m (l,t))) layout
+ (fun t hj ↦
+ let hs := congrArg (fun r ↦ packedSiteEquiv (P.survivingRole layout r m))
+ ((congrArg (partyRole layout) hj).trans (active t))
+ (RAMSerialization.wordBits _).symm (readWord t
+ ⟨fun a ha ↦ z.1 a (hs.trans ha), fun a ha ↦ z.2 a (hs.trans ha)⟩))
+ (fun t hj ↦ h (m,t) (congrArg (fun r ↦ packedSiteEquiv (P.survivingRole layout r m))
+ ((congrArg (partyRole layout) hj).trans (absorbed t)))) e.1 e.2
+
+/-- All columns of the supply basis at a party, using only half-wires
+and absorbed indices available at that party's packed site. -/
+noncomputable def shrinkLocalSupplyArg
+ (h : Placed (P.shrinkInternalOwner layout) (internalLabel width layout) (P.shrinkPartySite layout m j))
+ (z : (N).Half (P.shrinkPartySite layout m j)) :
+ ((e : Bool × Fin 4) → j = supply.src e → Fin (2 ^ width m e)) ×
+ ((e : Bool × Fin 4) → j = supply.dst e → Fin (2 ^ width m e)) :=
+ ⟨P.readSupplyEnd layout subdiv width I m j supply.src (sourceRole layout)
+ (role_src_survives layout) (role_src_absorbed layout)
+ (P.localSurvivingSource layout subdiv _ I hpos m) h z,
+ P.readSupplyEnd layout subdiv width I m j supply.dst (targetRole layout)
+ (role_dst_survives layout) (role_dst_absorbed layout)
+ (P.localSurvivingTarget layout subdiv _ I hpos m) h z⟩
+
+private theorem readSupplyEnd_eval (endParty : Bool × Fin 4 → Fin 6) (role : Fin 4 → PackedRole)
+ (active : ∀ t, partyRole layout (endParty (layout,t)) = role t)
+ (absorbed : ∀ t, partyRole layout (endParty (!layout,t)) = internalRole layout t)
+ (readWord : (t : Fin 4) → (N).Half (packedSiteEquiv (P.survivingRole layout (role t) m)) →
+ Fin (width m (layout,t)) → Bool)
+ (x : (m : P.Motif) → (e : Bool × Fin 4) → Fin (2 ^ width m e)) (z : (a : (N).Edge) → (N).Payload a)
+ (heval : ∀ t, readWord t (edgeAssignment (N).src (N).dst z _) =
+ RAMSerialization.wordBits _ (x m (layout,t))) :
+ P.readSupplyEnd layout subdiv width I m j endParty role active absorbed readWord
+ (fun e _ ↦ x e.1 (!layout,e.2)) (edgeAssignment (N).src (N).dst z _) = fun e _ ↦ x m e := by
+ funext ⟨l,t⟩ hj
+ by_cases hl : l = layout
+ · subst l
+ simp only [readSupplyEnd, layoutCases_active]
+ change (RAMSerialization.wordBits _).symm (readWord t (edgeAssignment (N).src (N).dst z _)) = _
+ rw [heval, Equiv.symm_apply_apply]
+ · have hl' := Bool.eq_not_of_ne hl
+ subst l
+ simp only [readSupplyEnd, layoutCases_absorbed]
+
+/-- A shared assignment gives exactly the original motif column at every
+party after slicing the surviving words and placing the absorbed indices. -/
+theorem shrinkLocalSupplyArg_eval (x : (m : P.Motif) → (e : Bool × Fin 4) → Fin (2 ^ width m e)) :
+ P.shrinkLocalSupplyArg layout subdiv width I hpos m j (fun e _ ↦ x e.1 (!layout,e.2))
+ (edgeAssignment (N).src (N).dst (P.shrinkPayloadsEquiv layout subdiv _ I.outgoing hpos
+ (fun m t ↦ RAMSerialization.wordBits _ (x m (layout,t)))) _) =
+ edgeAssignment supply.src supply.dst (x m) j := by
+ apply Prod.ext
+ · exact P.readSupplyEnd_eval layout subdiv width I m j supply.src _
+ (role_src_survives layout) (role_src_absorbed layout) _ x _
+ (fun t ↦ P.localSurvivingSource_eval layout subdiv _ I hpos m t _)
+ · exact P.readSupplyEnd_eval layout subdiv width I m j supply.dst _
+ (role_dst_survives layout) (role_dst_absorbed layout) _ x _
+ (fun t ↦ P.localSurvivingTarget_eval layout subdiv _ I hpos m t _)
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkSupplyReadout.lean b/lean/OAI/Computability/VPVNP/ShrinkSupplyReadout.lean
new file mode 100644
index 0000000000..aed39d7861
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkSupplyReadout.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.DegreeRefreshActualStep
+import OAI.Computability.VPVNP.ShrinkPayload
+
+/-!
+# Reading a surviving motif word at its two packed sites
+
+The subdivisions of a surviving wire occupy numbered outgoing arcs at its
+source and numbered incoming arcs at its target. Each of the two packed
+sites can reconstruct the original word from its own half-wire fields.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+open SurvivingSlots ShrinkPayload NetworkKernel WireTensor
+
+variable {V H Tag L : Type} {c d : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c) (layout : Bool) (subdiv : Fin 4 → ℕ)
+
+/-- Numbering for the surviving subdivisions and cyclic padding slots. -/
+abbrev ShrinkIndex (next : Equiv.Perm (V × Tag)) (d' pad : ℕ) :=
+ SlotIndexing (V × Tag) (PaddedId (V × Tag) (Id P.BaseMotif subdiv) pad) L d'
+ (paddedSource (endpoint (P.roleBase layout) (sourceRole layout)))
+ (paddedTarget (endpoint (P.roleBase layout) (targetRole layout)) next)
+ (paddedShift (P.roleDisplacement layout (sourceRole layout) (targetRole layout)))
+
+variable [Fintype V] [Fintype Tag] [Fintype L] {d' pad : ℕ} {next : Equiv.Perm (V × Tag)}
+variable (width : P.Motif → Fin 4 → ℕ) (I : P.ShrinkIndex layout subdiv next d' pad)
+
+/-- The output word network on the numbered lifted arcs of a shrinking step. -/
+noncomputable abbrev shrinkOutput : Network :=
+ Refresh.actualWireGraph I.graph (P.shrinkSlotWidth layout subdiv width I.outgoing)
+
+variable (hpos : ∀ t, 0 < subdiv t) (m : P.Motif) (t : Fin 4)
+
+/-- Concatenate the genuine outgoing slices at the packed source role. -/
+def localSurvivingSource
+ (z : (P.shrinkOutput layout subdiv width I).Half
+ (let s := P.survivingRole layout (sourceRole layout t) m; (packedBase s, s.2.2))) :
+ Fin (width m t) → Bool :=
+ (sliceWords (width m t) (subdiv t) (hpos t)).symm fun k ↦
+ let i : Id P.Motif subdiv := ⟨t, m, k⟩
+ let a := P.shrinkArcEquiv layout subdiv I.outgoing (.inl i)
+ cast (congrArg (fun n ↦ Fin n → Bool)
+ (P.shrinkSlotWidth_genuine layout subdiv width I.outgoing i))
+ (z.1 a (P.shrinkArc_endpoints layout subdiv I i).1.symm)
+
+/-- Concatenate the same genuine slices at the packed target role, reading
+the incoming half of each arc with its actual lane translation. -/
+def localSurvivingTarget
+ (z : (P.shrinkOutput layout subdiv width I).Half
+ (let s := P.survivingRole layout (targetRole layout t) m; (packedBase s, s.2.2))) :
+ Fin (width m t) → Bool :=
+ (sliceWords (width m t) (subdiv t) (hpos t)).symm fun k ↦
+ let i : Id P.Motif subdiv := ⟨t, m, k⟩
+ let a := P.shrinkArcEquiv layout subdiv I.outgoing (.inl i)
+ cast (congrArg (fun n ↦ Fin n → Bool)
+ (P.shrinkSlotWidth_genuine layout subdiv width I.outgoing i))
+ (z.2 a (P.shrinkArc_endpoints layout subdiv I i).2.symm)
+
+variable (x : (m : P.Motif) → (t : Fin 4) → Fin (width m t) → Bool)
+
+/-- The local outgoing readout recovers the original motif word. -/
+theorem localSurvivingSource_eval :
+ let N := P.shrinkOutput layout subdiv width I
+ P.localSurvivingSource layout subdiv width I hpos m t
+ (edgeAssignment N.src N.dst (P.shrinkPayloadsEquiv layout subdiv width I.outgoing hpos x) _) =
+ x m t := by
+ apply (sliceWords (width m t) (subdiv t) (hpos t)).injective
+ simp only [localSurvivingSource, Equiv.apply_symm_apply]
+ funext k
+ exact P.shrinkPayloadsEquiv_genuine layout subdiv width I.outgoing hpos x ⟨t, m, k⟩
+
+/-- The local incoming readout recovers the same original motif word. -/
+theorem localSurvivingTarget_eval :
+ let N := P.shrinkOutput layout subdiv width I
+ P.localSurvivingTarget layout subdiv width I hpos m t
+ (edgeAssignment N.src N.dst (P.shrinkPayloadsEquiv layout subdiv width I.outgoing hpos x) _) =
+ x m t := by
+ apply (sliceWords (width m t) (subdiv t) (hpos t)).injective
+ simp only [localSurvivingTarget, Equiv.apply_symm_apply]
+ funext k
+ exact P.shrinkPayloadsEquiv_genuine layout subdiv width I.outgoing hpos x ⟨t, m, k⟩
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/ShrinkingSlots.lean b/lean/OAI/Computability/VPVNP/ShrinkingSlots.lean
new file mode 100644
index 0000000000..f3ab19e478
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/ShrinkingSlots.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.PackingLanes
+import OAI.Computability.VPVNP.PackingPreimages
+import OAI.Computability.VPVNP.RegularizedMotifs
+import OAI.Computability.VPVNP.SlotIdentifierOrder
+import Mathlib.Algebra.Module.Pi
+
+/-!
+# The shrinking step's slot construction
+
+Lemma C.1 of *VP and VNP differ over every field* for a directed input
+slot graph with arbitrary binary displacements. `dyadic_slot_packing`
+counts the thick wires, CD demands and placed role incidences on the actual
+input. `dyadicSurvivingSlots` constructs the indexed, regularized output
+lift. The lane-zero labels preserve parallel edges and subdivisions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+open SurvivingSlots PackingData
+
+variable {V : Type*} [Fintype V] [DecidableEq V] {a g : ℕ}
+variable (G : LiftedSlots V (2 ^ a) (BitWord (packingLaneBits a g)))
+
+/-- The multiplicities and distinct-endpoint assertions of Lemma C.1, for
+the construction obtained directly from the given input graph. -/
+theorem dyadic_slot_packing :
+ let P := dyadicPacking G
+ let d := 2 ^ a
+ let K := 2 ^ (2 * d + 1) * d
+ let Q := 3 * K / 4
+ Fintype.card (V × BitWord (packingLaneBits a g)) =
+ K * Fintype.card (Site V (BitWord (packingTagBits d)) (BitWord g)) ∧
+ (∀ b, Fintype.card {e // e.1 = b ∧ P.thick (sourcePosition e) ∧
+ P.thick (sourcePosition (P.actual e))} = K / 4) ∧
+ (∀ b, Fintype.card {m : P.Motif // P.bundle m = b} = Q) ∧
+ (∀ layout s, Fintype.card {x // P.placement layout x = s} = K) ∧
+ (∀ layout m, packedBase (P.roleA m) ≠ packedBase (P.roleB m) ∧
+ packedBase (P.roleA m) ≠ packedBase (P.roleD layout m) ∧
+ packedBase (P.roleB m) ≠ packedBase (P.roleD layout m)) ∧
+ ∀ layout role s, Fintype.card {m : P.Motif // P.survivingRole layout role m = s} = d * Q := by
+ let P := dyadicPacking G
+ have hd : 0 < 2 ^ a := Nat.two_pow_pos _
+ have hc : 2 ≤ 2 * 2 ^ a + 1 := by omega
+ refine ⟨packing_position_count V a g, P.card_thick_bundle hc, P.card_motifs_bundle hc,
+ P.card_placement (by omega), P.distinct_roleBases (dyadicPacking_validTags G),
+ fun layout role s ↦ ?_⟩
+ cases role with
+ | a => exact P.card_roleA hc s
+ | b => exact P.card_roleB hc s
+ | d => exact P.card_roleD hc layout s
+
+private def dyadicSlotIndexing (P : DyadicPackingData V a g)
+ (hφ : P.slots.ValidTagOffsets P.tagShift P.offset) (layout : Bool) (subdiv : Fin 4 → ℕ)
+ [LinearOrder (Id P.BaseMotif subdiv)] {d' : ℕ}
+ (hd' : survivingDegree (2 ^ a) (2 * 2 ^ a + 1) subdiv ≤ d') :=
+ let j := packingTagBits (2 ^ a)
+ have hd : 0 < 2 ^ a := Nat.two_pow_pos _
+ have hc : 2 ≤ 2 * 2 ^ a + 1 := by omega
+ have hj : 0 < j := Nat.succ_pos _
+ P.regularizedSlotIndexing hc hφ layout subdiv hd' (bitWordFinEquiv j)
+ (Nat.one_lt_two_pow hj.ne')
+
+/-- Number the actual surviving arcs by their lane-zero motif IDs, padding
+with dummy arcs to any admissible output degree `d'`. The resulting graph
+has packed bases `(old vertex, tag)` and the original remaining lane. -/
+noncomputable def dyadicSurvivingSlots (layout : Bool) (subdiv : Fin 4 → ℕ)
+ [LinearOrder (Id (dyadicPacking G).BaseMotif subdiv)] {d' : ℕ}
+ (hd' : survivingDegree (2 ^ a) (2 * 2 ^ a + 1) subdiv ≤ d') :=
+ dyadicSlotIndexing (dyadicPacking G) (dyadicPacking_validTags G) layout subdiv hd'
+
+/-- The supplied vertex numbering determines both the greedy scans and the
+integer keys for sorting the local incoming and outgoing incidence lists. -/
+def orderedDyadicSurvivingSlots {N : ℕ} (vertices : V ≃ Fin N) (layout : Bool)
+ (subdiv : Fin 4 → ℕ) {d' : ℕ} (hd' : survivingDegree (2 ^ a) (2 * 2 ^ a + 1) subdiv ≤ d') :=
+ let P := orderedDyadicPacking G vertices
+ letI := P.slotIdentifierOrder vertices (bitWordFinEquiv (packingTagBits (2 ^ a))) subdiv
+ dyadicSlotIndexing P (orderedDyadicPacking_validTags G vertices) layout subdiv hd'
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmetic.lean b/lean/OAI/Computability/VPVNP/SliceArithmetic.lean
new file mode 100644
index 0000000000..4706be0fc9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmetic.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.SliceField
+
+/-!
+# Binary coefficient vectors for the evaluator's slice field
+
+The prime modulus, extension degree and low coefficients of the defining monic
+polynomial come from the advice. An extension-field element is represented by
+its coefficients in increasing degree order. Each coefficient occupies
+`clog 2 p` bits in the evaluator's little-endian word format.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic
+
+open Polynomial
+
+/-- Canonical residues of the `e` low coefficients, in increasing degree order. -/
+abbrev Vector (p e : ℕ) := Fin e → Fin p
+
+/-- Encode the coefficient vector with exactly `e * clog 2 p` bits. -/
+def encode {p e : ℕ} (v : Vector p e) : Fin (e * Nat.clog 2 p) → Bool :=
+ RAMSerialization.arrayBits e (Nat.clog 2 p) fun i =>
+ ⟨(v i).val, (v i).isLt.trans_le (Nat.le_pow_clog (by decide) p)⟩
+
+/-- Decode all bit strings by reducing each word modulo the supplied prime. -/
+def ofBits {p e : ℕ} [NeZero p] (bits : Fin (e * Nat.clog 2 p) → Bool) : Vector p e :=
+ let words := (RAMSerialization.arrayBits e (Nat.clog 2 p)).symm bits
+ fun i => ⟨(words i).val % p, Nat.mod_lt _ (NeZero.pos p)⟩
+
+@[simp] theorem ofBits_encode {p e : ℕ} [NeZero p] (v : Vector p e) :
+ ofBits (encode v) = v := by
+ funext i
+ apply Fin.ext
+ simp [ofBits, encode, Nat.mod_eq_of_lt (v i).isLt]
+
+/-- Read the advised polynomial from its low coefficients. -/
+noncomputable def modulus {p e : ℕ} (c : Vector p e) : (ZMod p)[X] :=
+ X ^ e + ∑ i, C ((c i).val : ZMod p) * X ^ i.val
+
+theorem modulus_monic {p e : ℕ} (c : Vector p e) :
+ (modulus c).Monic :=
+ monic_X_pow_add (degree_sum_fin_lt _)
+
+theorem modulus_natDegree {p e : ℕ} [Nontrivial (ZMod p)] (c : Vector p e) :
+ (modulus c).natDegree = e := by
+ rw [modulus, natDegree_add_eq_left_of_degree_lt, natDegree_X_pow]
+ simpa using degree_sum_fin_lt (fun i : Fin e => ((c i).val : ZMod p))
+
+theorem modulus_ofBits {p e : ℕ} [NeZero p] (bits : Fin (e * Nat.clog 2 p) → Bool) :
+ modulus (ofBits bits) = SliceField.polynomialOfBits p e bits := by
+ simp only [modulus, SliceField.polynomialOfBits, ofBits, ZMod.natCast_mod]
+
+/-- Interpret a coefficient vector in the advised quotient ring. -/
+noncomputable def value {p e : ℕ} (f : (ZMod p)[X]) (v : Vector p e) : AdjoinRoot f :=
+ ∑ i, algebraMap (ZMod p) (AdjoinRoot f) ((v i).val : ZMod p) * AdjoinRoot.root f ^ i.val
+
+/-- The zero element in the power basis, with zero in each of the `e` coefficient positions. -/
+def zero (p e : ℕ) [NeZero p] : Vector p e := fun _ => 0
+
+/-- Power-basis vector of the constant polynomial one, with its unit coefficient in degree
+zero. -/
+def one (p e : ℕ) [NeZero p] : Vector p e := fun i => if i.val = 0 then 1 else 0
+
+/-- Add the two power-basis vectors coefficientwise modulo `p`. -/
+def add {p e : ℕ} (a b : Vector p e) : Vector p e := fun i => a i + b i
+
+/-- Multiply every coefficient of a power-basis vector by the prime-field scalar `a`. -/
+def scale {p e : ℕ} (a : Fin p) (v : Vector p e) : Vector p e := fun i => a * v i
+
+/-- The residue of a canonical limb is the image under the finite-ring equivalence. -/
+theorem cast_val_eq_finEquiv {p : ℕ} [NeZero p] (a : Fin p) :
+ (a.val : ZMod p) = ZMod.finEquiv p a := by
+ cases p with
+ | zero => exact (NeZero.ne 0 rfl).elim
+ | succ p => exact ZMod.natCast_zmod_val (n := p + 1) a
+
+@[simp] theorem value_zero {p e : ℕ} [NeZero p] (f : (ZMod p)[X]) :
+ value f (zero p e) = 0 := by simp [value, zero]
+
+@[simp] theorem value_one {p e : ℕ} [NeZero p] [NeZero e] (f : (ZMod p)[X]) :
+ value f (one p e) = 1 := by
+ rw [value, Finset.sum_eq_single (0 : Fin e)]
+ · simp [one]
+ · intro i _ hi
+ have : i.val ≠ 0 := by simpa using hi
+ simp [one, this]
+ · simp
+
+@[simp] theorem value_add {p e : ℕ} [NeZero p] (f : (ZMod p)[X]) (a b : Vector p e) :
+ value f (add a b) = value f a + value f b := by
+ simp only [value, add, cast_val_eq_finEquiv, map_add, add_mul, Finset.sum_add_distrib]
+
+@[simp] theorem value_scale {p e : ℕ} [NeZero p] (f : (ZMod p)[X]) (a : Fin p) (v : Vector p e) :
+ value f (scale a v) = algebraMap (ZMod p) _ (a.val : ZMod p) * value f v := by
+ simp only [value, scale, cast_val_eq_finEquiv, map_mul, Finset.mul_sum, mul_assoc]
+
+/-- Decoding a vector and taking its `i`th power-basis coordinate recovers the
+stored limb exactly. -/
+theorem repr_value {p e : ℕ} {f : (ZMod p)[X]} (hm : f.Monic)
+ (he : f.natDegree = e) (v : Vector p e) (i : Fin e) :
+ (AdjoinRoot.powerBasis' hm).basis.repr (value f v) (i.cast he.symm) = (v i).val := by
+ subst e
+ let b := AdjoinRoot.powerBasisAux' hm
+ have h (j : Fin f.natDegree) : b j = AdjoinRoot.root f ^ j.val :=
+ (AdjoinRoot.powerBasis' hm).basis_eq_pow j
+ have heq : value f v = ∑ j, ((v j).val : ZMod p) • b j := by simp [value, h, Algebra.smul_def]
+ change b.repr (value f v) i = _
+ rw [heq, map_sum]
+ simp [Finsupp.finsetSum_apply, map_smul, Finsupp.single_apply]
+
+theorem value_injective {p e : ℕ} [NeZero p] {f : (ZMod p)[X]} (hm : f.Monic)
+ (he : f.natDegree = e) : Function.Injective (value (e := e) f) := by
+ intro u v huv
+ funext i
+ apply (ZMod.finEquiv p).injective
+ rw [← cast_val_eq_finEquiv, ← cast_val_eq_finEquiv, ← repr_value hm he u i, huv, repr_value hm he v i]
+
+end SliceArithmetic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticAccumulatePorts.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticAccumulatePorts.lean
new file mode 100644
index 0000000000..1bc438d270
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticAccumulatePorts.lean
@@ -0,0 +1,157 @@
+import OAI.Computability.VPVNP.SliceArithmeticCallPorts
+import OAI.Computability.VPVNP.SliceArithmeticAdd
+
+/-!
+# Operand and advice ports of the evaluator's multiply-and-add call
+
+The two saved factors are copied onto private streams for the multiplication.
+The resulting product then serves as the consumable operand of vector addition.
+The original factors and the field advice remain available to the caller.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.MultiplyAccumulate
+
+open BurstRAM RAMTape
+
+/-- Caller ports for the two factors, the running accumulator, and the field parameters used to
+add their product. -/
+inductive External where
+ | prime | zeroWord | degree | coeff | left | returned | acc
+ deriving DecidableEq
+
+instance : Fintype External :=
+ ⟨{.prime, .zeroWord, .degree, .coeff, .left, .returned, .acc}, by intro i; cases i <;> simp⟩
+
+/-- Private work ports for multiplication, addition, the two operand copies, and the temporary
+stack used to copy them. -/
+inductive Private where
+ | multiply (i : HornerControl.Ports)
+ | addition (i : SliceArithmeticStreamRow.Port Unit)
+ | multiplicand | product | scratch
+ deriving DecidableEq, Fintype
+
+/-- The full stack interface for adding a product to an extension-field accumulator. -/
+abbrev Port := Private ⊕ External
+
+/-- Populate the caller's field-advice ports, the two packed factors, and the packed
+accumulator. -/
+def external (p e w : ℕ) (coeff left returned acc : List Bool) : Stacks External
+ | .prime => wordBits (Fin.ofNat (2 ^ w) p)
+ | .zeroWord => wordBits (0 : BurstRAM.Word w)
+ | .degree => List.replicate e true
+ | .coeff => coeff
+ | .left => left
+ | .returned => returned
+ | .acc => acc
+
+/-- At a call boundary all private stacks are empty. The intermediate frames
+below name the two private streams that hold the copied operands and product. -/
+def workspace (io : Stacks External) (multiplicand product : List Bool) : Stacks Port
+ | .inl .multiplicand => multiplicand
+ | .inl .product => product
+ | .inl _ => []
+ | .inr i => io i
+
+/-- Entry and return state with the caller's stacks installed and all multiplication workspace
+empty. -/
+def clean (io : Stacks External) := workspace io [] []
+
+/-- Connect the field multiplier to the private copies of the factors and the caller's field
+advice. -/
+def multiplyPorts : MultiplyCall.Port → Port
+ | .inl i => .inl (.multiply i)
+ | .inr .prime => .inr .prime
+ | .inr .zeroWord => .inr .zeroWord
+ | .inr .degree => .inr .degree
+ | .inr .coeff => .inr .coeff
+ | .inr .query => .inl .multiplicand
+ | .inr .acc => .inl .product
+
+/-- Connect the coefficientwise adder to the private product stream and the caller's
+accumulator. -/
+def addPorts : SliceArithmeticStreamRow.Port Unit ⊕ MultiplyCall.External → Port
+ | .inl i => .inl (.addition i)
+ | .inr .prime => .inr .prime
+ | .inr .zeroWord => .inr .zeroWord
+ | .inr .degree => .inr .degree
+ | .inr .coeff => .inr .coeff
+ | .inr .query => .inl .product
+ | .inr .acc => .inr .acc
+
+theorem multiplyPorts_injective : Function.Injective multiplyPorts := by
+ rintro (i|i) (j|j) h <;> try cases i <;> try cases j <;> simp_all [multiplyPorts]
+
+theorem addPorts_injective : Function.Injective addPorts := by
+ rintro (i|i) (j|j) h <;> try cases i <;> try cases j <;> simp_all [addPorts]
+
+/-- Copy the saved left and returned right factors onto the two private multiplication stacks. -/
+def stage : FiniteRoutine Port :=
+ (SuccessorFields.prependCopy (.inr .left) (.inl .multiplicand) (.inl .scratch)).followedBy
+ (SuccessorFields.prependCopy (.inr .returned) (.inl .product) (.inl .scratch))
+
+theorem stage_runs (io : Stacks External) :
+ stage.Runs (5 * (io .left).length + 2 + (5 * (io .returned).length + 2))
+ (clean io) (workspace io (io .left) (io .returned)) := by
+ let s := clean io
+ let mid := workspace io (io .left) []
+ have h₁ := SuccessorFields.prependCopy_runs (.inr External.left) (.inl Private.multiplicand) (.inl .scratch)
+ (by decide) (by decide) (by decide) s rfl
+ have h₂ := SuccessorFields.prependCopy_runs (.inr External.returned) (.inl Private.product) (.inl .scratch)
+ (by decide) (by decide) (by decide) mid rfl
+ rw [show Function.update s (.inl .multiplicand) (s (.inr .left) ++ s (.inl .multiplicand)) = mid by
+ funext i; rcases i with i|i; cases i <;> simp [s, mid, clean, workspace]; rfl] at h₁
+ rw [show Function.update mid (.inl .product) (mid (.inr .returned) ++ mid (.inl .product)) =
+ workspace io (io .left) (io .returned) by
+ funext i; rcases i with i|i; cases i <;> simp [mid, workspace]; rfl] at h₂
+ exact h₁.followedBy h₂
+
+theorem multiplyRun {routine : FiniteRoutine MultiplyCall.Port} {t p e w : ℕ}
+ (coeff left returned acc result : List Bool)
+ (run : routine.Runs t (MultiplyCall.clean (MultiplyCall.external p e w coeff left returned))
+ (MultiplyCall.clean (MultiplyCall.external p e w coeff [] result))) :
+ (routine.onPorts multiplyPorts).Runs t (workspace (external p e w coeff left returned acc) left returned)
+ (workspace (external p e w coeff left returned acc) [] result) := by
+ apply routine.runs_onPorts_framed multiplyPorts_injective run
+ · rintro (i|i)
+ · rfl
+ · cases i <;> rfl
+ · rintro (i|i)
+ · rfl
+ · cases i <;> rfl
+ rintro (i|i) hi
+ · cases i with
+ | multiplicand => exact (hi (.inr .query) rfl).elim
+ | product => exact (hi (.inr .acc) rfl).elim
+ | _ => rfl
+ · rfl
+
+theorem addRun {routine : FiniteRoutine (SliceArithmeticStreamRow.Port Unit ⊕ MultiplyCall.External)}
+ {t p e w : ℕ} (coeff left returned acc product result : List Bool)
+ (run : routine.Runs t (Sum.elim (fun _ => []) (MultiplyCall.external p e w coeff product acc))
+ (Sum.elim (fun _ => []) (MultiplyCall.external p e w coeff [] result))) :
+ (routine.onPorts addPorts).Runs t (workspace (external p e w coeff left returned acc) [] product)
+ (clean (external p e w coeff left returned result)) := by
+ apply routine.runs_onPorts_framed addPorts_injective run
+ · rintro (i|i)
+ · rfl
+ · cases i <;> rfl
+ · rintro (i|i)
+ · rfl
+ · cases i <;> rfl
+ rintro (i|i) hi
+ · cases i with
+ | product => exact (hi (.inr .query) rfl).elim
+ | _ => rfl
+ · cases i with
+ | acc => exact (hi (.inr .acc) rfl).elim
+ | _ => rfl
+
+end SliceArithmetic.MultiplyAccumulate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticAdd.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticAdd.lean
new file mode 100644
index 0000000000..78cd746a6c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticAdd.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.SliceArithmeticRound
+
+/-!
+# Vector addition on serialized coefficient streams
+
+A marker-controlled loop consumes the two vectors in increasing degree
+order. Each iteration loads two limbs, adds modulo the supplied modulus,
+and emits the sum. One final reversal puts the coefficient vector into the
+first input port, with the original order of limbs and bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticAdd
+
+open BurstRAM RAMTape SliceArithmetic SliceArithmeticStreamRow
+open SliceArithmeticRound (packed)
+
+variable {p w : ℕ} {X : Type} [DecidableEq X]
+
+private def body (op : Word.Op) : FiniteRoutine (Port X) :=
+ (((loadLimb .coeff 3).followedBy (loadLimb .factor 5)).followedBy
+ ((Word.routine op 6 3 5 0).onPorts Sum.inl)).followedBy emit
+
+/-- Apply the chosen residue operation once per degree marker, then reverse the emitted limbs
+onto the coefficient stack. -/
+def vectorOp (op : Word.Op) (marker : X) : FiniteRoutine (Port X) :=
+ (FiniteRoutine.repeatMarked (.inr (.outer marker)) (body op)).followedBy
+ (EvaluatorRadixDivision.reverseOnto (.inr .out) (.inr .coeff))
+
+/-- The two input ports retain their suffixes. The caller supplies a scratch
+port, an output port and a marker port for the duration of the call. -/
+def streams (marker : X) (base : Stacks (StreamPort X))
+ (coeff factor out : List Bool) (rows : ℕ) : Stacks (StreamPort X)
+ | .coeff => coeff ++ base .coeff
+ | .factor => factor ++ base .factor
+ | .out => out
+ | .scratch => []
+ | .outer i => if i = marker then List.replicate rows true else base (.outer i)
+ | i => base i
+
+variable [NeZero p]
+
+private def regs (op : Word.Op) (reg : Fin 8 → BurstRAM.Word w) (a b : Fin p) :=
+ Function.update (Function.update (Function.update reg 3 (Word.limb w a)) 5 (Word.limb w b)) 6
+ (Word.limb w (op.eval a b))
+
+/-- Registers outside the two operand slots and the result slot are preserved. -/
+def Preserves (reg next : Fin 8 → BurstRAM.Word w) :=
+ ∀ i, i ≠ 3 → i ≠ 5 → i ≠ 6 → next i = reg i
+
+private theorem body_runs (op : Word.Op) (hw : Word.workingWidth p ≤ w) (reg : Fin 8 → BurstRAM.Word w)
+ (hp : (reg 0).val = p) (u : Stacks (StreamPort X)) (a b : Fin p) (as bs : List Bool)
+ (ha : u .coeff = wordBits (Word.limb w a) ++ as) (hb : u .factor = wordBits (Word.limb w b) ++ bs)
+ (ht : u .scratch = []) :
+ let u' := Function.update (Function.update (Function.update u .coeff as) .factor bs) .out
+ ((wordBits (Word.limb w (op.eval a b))).reverse ++ u .out)
+ ∃ t ≤ 200 * (w + 1) ^ 2 + 17 * w + 7, (body op).Runs t (state reg u) (state (regs op reg a b) u') := by
+ intro u'
+ let r₁ := Function.update reg 3 (Word.limb w a)
+ let s₁ := Function.update u .coeff as
+ let r₂ := Function.update r₁ 5 (Word.limb w b)
+ let s₂ := Function.update s₁ .factor bs
+ have h₁ := loadLimb_runs (by simp) 3 reg u (Word.limb w a) as ha ht
+ have h₂ := loadLimb_runs (s := .factor) (by simp) 5 r₁ s₁ (Word.limb w b) bs
+ (by simpa [s₁] using hb) (by simpa [s₁] using ht)
+ obtain ⟨t, ht', h₃⟩ := Word.routine_runs hw op 6 3 5 0 (by decide) Fin.elim0 0 r₂ [] a b
+ (by simp [r₂, r₁, Word.limb_val hw]) (by simp [r₂, Word.limb_val hw]) (by simpa [r₂, r₁] using hp)
+ have h₄ := emit_runs (regs op reg a b) s₂ (by simpa [s₂, s₁] using ht)
+ have he : Function.update s₂ .out ((wordBits (regs op reg a b 6)).reverse ++ s₂ .out) = u' := by
+ simp [regs, u', s₂, s₁]
+ rw [he] at h₄
+ exact ⟨_, by omega, ((h₁.followedBy h₂).followedBy (bankRun _ s₂ h₃)).followedBy h₄⟩
+
+private def frame (marker : X) (base : Stacks (StreamPort X)) (reg : Fin 8 → BurstRAM.Word w)
+ (xs : List (Fin p × Fin p)) (out : List Bool) : Stacks (Port X) :=
+ state reg (streams marker base (packed w (xs.map Prod.fst)) (packed w (xs.map Prod.snd)) out xs.length)
+
+private theorem scan_runs (op : Word.Op) (hw : Word.workingWidth p ≤ w) (marker : X) (base : Stacks (StreamPort X))
+ (reg : Fin 8 → BurstRAM.Word w) (hp : (reg 0).val = p) (xs : List (Fin p × Fin p)) (out : List Bool) :
+ ∃ (t : ℕ) (next : Fin 8 → BurstRAM.Word w), t ≤ xs.length * (200 * (w + 1) ^ 2 + 17 * w + 8) + 1 ∧
+ Preserves reg next ∧ (FiniteRoutine.repeatMarked (.inr (.outer marker)) (body op)).Runs t
+ (frame marker base reg xs out)
+ (frame marker base next ([] : List (Fin p × Fin p)) ((packed w (xs.map (fun x => op.eval x.1 x.2))).reverse ++ out)) := by
+ induction xs generalizing reg out with
+ | nil =>
+ refine ⟨1, reg, by simp, fun _ _ _ _ => rfl, ?_⟩
+ simp only [List.map_nil, packed, List.flatMap_nil, List.reverse_nil, List.nil_append]
+ apply Routine.Runs.popLoop_empty (.inr (.outer marker)) (fun _ => true) (Routine.halt false) (body op).body
+ simp [frame, state, streams]
+ | cons x xs ih =>
+ obtain ⟨a, b⟩ := x
+ let current := streams marker base (packed w (((a, b) :: xs).map Prod.fst))
+ (packed w (((a, b) :: xs).map Prod.snd)) out (xs.length + 1)
+ let u := Function.update current (.outer marker) (List.replicate xs.length true)
+ let remaining := streams marker base (packed w (xs.map Prod.fst)) (packed w (xs.map Prod.snd))
+ ((wordBits (Word.limb w (op.eval a b))).reverse ++ out) xs.length
+ obtain ⟨t, ht, step⟩ := body_runs op hw reg hp u a b (remaining .coeff) (remaining .factor)
+ (by simp [u, current, remaining, packed, streams]) (by simp [u, current, remaining, packed, streams])
+ (by simp [u, current, streams])
+ have hs : Function.update (Function.update (Function.update u .coeff (remaining .coeff)) .factor
+ (remaining .factor)) .out ((wordBits (Word.limb w (op.eval a b))).reverse ++ u .out) = remaining := by
+ funext i
+ cases i with
+ | outer j => by_cases h : j = marker <;> simp [u, current, remaining, streams, h]
+ | old | coeff | factor | out | scratch => simp [u, current, remaining, streams]
+ rw [hs] at step
+ have same : Preserves reg (regs op reg a b) := fun i h₃ h₅ h₆ => by simp [regs, h₃, h₅, h₆]
+ have hreg := congrArg Fin.val (same 0 (by decide) (by decide) (by decide))
+ obtain ⟨n, next, hn, hnext, tail⟩ := ih (regs op reg a b) (hreg.trans hp) ((wordBits (Word.limb w (op.eval a b))).reverse ++ out)
+ refine ⟨1 + t + n, next, ?_, fun i h₃ h₅ h₆ => (hnext i h₃ h₅ h₆).trans (same i h₃ h₅ h₆), ?_⟩
+ · rw [List.length_cons, Nat.succ_mul xs.length]
+ omega
+ · apply Routine.Runs.popLoop_true_continue (.inr (.outer marker)) (fun _ => true) (Routine.halt false) (body op).body
+ (mid := state (regs op reg a b) remaining) (n := t) (m := n) (tail := List.replicate xs.length true)
+ · simp [frame, state, streams, List.replicate_succ]
+ · rfl
+ · simpa only [frame, List.length_cons, current, updateStream, u, remaining] using step
+ · change (Routine.popLoop (.inr (.outer marker)) (fun _ => true) (Routine.halt false) (body op).body).Runs n
+ (state (regs op reg a b) remaining) _ at tail
+ simpa only [List.map_cons, packed, List.flatMap_cons, List.reverse_append, List.append_assoc] using tail
+
+/-- Run one chosen prime-field operation on every pair of corresponding limbs. -/
+theorem vectorOp_runs (op : Word.Op) {e : ℕ} (hw : Word.workingWidth p ≤ w) (marker : X)
+ (base : Stacks (StreamPort X)) (reg : Fin 8 → BurstRAM.Word w) (hp : (reg 0).val = p)
+ (a b : Vector p e) :
+ ∃ (t : ℕ) (next : Fin 8 → BurstRAM.Word w),
+ t ≤ e * (200 * (w + 1) ^ 2 + 17 * w + 8) + 2 * (e * w) + 2 ∧ Preserves reg next ∧
+ (vectorOp op marker).Runs t
+ (state reg (streams marker base (packed w (List.ofFn a)) (packed w (List.ofFn b)) [] e))
+ (state next (streams marker base (packed w (List.ofFn (fun i => op.eval (a i) (b i)))) [] [] 0)) := by
+ let xs := List.ofFn fun i => (a i, b i)
+ let result := packed w (List.ofFn (fun i => op.eval (a i) (b i)))
+ obtain ⟨t, next, ht, hp', run⟩ := scan_runs op hw marker base reg hp xs []
+ have hsums : xs.map (fun x => op.eval x.1 x.2) = List.ofFn (fun i => op.eval (a i) (b i)) := by
+ rw [List.map_ofFn]; rfl
+ simp only [frame, hsums, List.map_nil, packed, List.flatMap_nil, List.length_nil, List.append_nil,
+ xs, List.map_ofFn, Function.comp_def, List.length_ofFn] at run
+ let s := state next (streams marker base [] [] result.reverse 0)
+ let u := state next (streams marker base result [] [] 0)
+ have reverseRun := EvaluatorRadixDivision.reverseOnto_runs (src := .inr (.out : StreamPort X))
+ (dst := Sum.inr (.coeff : StreamPort X)) (by simp) s u rfl (by simp [s, u, state, streams]) (by
+ rintro (j | j) hs hd
+ · rfl
+ · cases j <;> simp_all [s, u, state, streams])
+ have hlen : (s (.inr .out)).length = e * w := by
+ simp [s, state, streams, result]
+ rw [hlen] at reverseRun
+ have hbound : t ≤ e * (200 * (w + 1) ^ 2 + 17 * w + 8) + 1 := by simpa [xs] using ht
+ refine ⟨t + (2 * (e * w) + 1), next, by omega, hp', ?_⟩
+ unfold vectorOp
+ apply FiniteRoutine.Runs.followedBy (s := _) (t := s) run
+ exact reverseRun
+
+/-- Addition of two packed coefficient vectors. -/
+def vectorAdd (marker : X) : FiniteRoutine (Port X) := vectorOp .add marker
+
+/-- The coefficient vector returned by the fixed control is the exact vector
+sum in the advised quotient. Both input suffixes survive the operation. -/
+theorem vectorAdd_runs {e : ℕ} (hw : Word.workingWidth p ≤ w) (marker : X)
+ (base : Stacks (StreamPort X)) (reg : Fin 8 → BurstRAM.Word w) (hp : (reg 0).val = p)
+ (a b : Vector p e) :
+ ∃ (t : ℕ) (next : Fin 8 → BurstRAM.Word w),
+ t ≤ e * (200 * (w + 1) ^ 2 + 17 * w + 8) + 2 * (e * w) + 2 ∧ Preserves reg next ∧
+ (vectorAdd marker).Runs t
+ (state reg (streams marker base (packed w (List.ofFn a)) (packed w (List.ofFn b)) [] e))
+ (state next (streams marker base (packed w (List.ofFn (add a b))) [] [] 0)) :=
+ vectorOp_runs .add hw marker base reg hp a b
+
+end SliceArithmeticAdd
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticAddCall.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticAddCall.lean
new file mode 100644
index 0000000000..35ae7e6d74
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticAddCall.lean
@@ -0,0 +1,200 @@
+import OAI.Computability.VPVNP.SliceArithmeticAdd
+import OAI.Computability.VPVNP.SliceArithmeticCallPorts
+import OAI.Computability.VPVNP.SliceArithmeticCallCopies
+
+/-!
+# Vector addition with a clean calling convention
+
+The two operand streams belong to the caller. A copy of the degree markers
+controls the scan, and copies of the modulus and zero word initialize its
+registers. The scan consumes the query and writes its result directly onto
+the accumulator. The registers are reclaimed before the call returns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.AddCall
+
+open RAMTape BurstRAM
+open SliceArithmeticStreamRow (state StreamPort)
+open SliceArithmeticRound (packed)
+open MultiplyCall (External external)
+
+/-- Ports for a reusable scalar addition call, pairing its coefficient-scan workspace with the
+caller's field and operand stacks. -/
+abbrev Port := SliceArithmeticStreamRow.Port Unit ⊕ External
+
+/-- The caller's external stacks, with every private port empty. -/
+def clean (io : Stacks External) : Stacks Port := Sum.elim (fun _ => []) io
+
+private def reg (i : Fin 8) : Port := .inl (.inl (.reg i))
+private def persistent : Port := .inl (.inl .persistent)
+private def marker : Port := .inl (.inr (.outer ()))
+private def scratch : Port := .inl (.inr .scratch)
+
+private def regSource (i : Fin 8) : External := if i = 0 then .prime else .zeroWord
+
+private def copies : List (Port × Port) :=
+ (.inr .degree, marker) :: (.inr .zeroWord, persistent) ::
+ List.ofFn (fun i : Fin 8 => (Sum.inr (regSource i), reg i))
+
+private def occupied : List Port := persistent :: List.ofFn reg
+
+private def scanPort : SliceArithmeticStreamRow.Port Unit → Port
+ | .inr .coeff => .inr .acc
+ | .inr .factor => .inr .query
+ | i => .inl i
+
+private theorem scanPort_injective : Function.Injective scanPort := by
+ rintro (i | i) (j | j)
+ · exact fun h => Sum.inl.inj h
+ · cases j <;> simp [scanPort]
+ · cases i <;> simp [scanPort]
+ · cases i <;> cases j <;> simp [scanPort]
+
+/-- The coefficient scan has one fixed table for each prime-field operation. -/
+def operation (op : Word.Op) : FiniteRoutine Port :=
+ ((CallCopies.copyPlan scratch copies).followedBy
+ ((SliceArithmeticAdd.vectorOp op ()).onPorts scanPort)).followedBy (CallClear.cleanup occupied)
+
+/-- Initialization, the vector scan, and register cleanup, in bit-stack steps. -/
+def callCap (e w : ℕ) : ℕ :=
+ (10 * (5 * (e + w) + 2) + 1) +
+ (e * (200 * (w + 1) ^ 2 + 17 * w + 8) + 2 * (e * w) + 2) + (9 * (w + 1) + 1)
+
+private def privateStreams (rows : ℕ) : Stacks (StreamPort Unit)
+ | .outer () => List.replicate rows true
+ | _ => []
+
+private def frame {w : ℕ} (r : Fin 8 → BurstRAM.Word w) (rows : ℕ) (io : Stacks External) :
+ Stacks Port := Sum.elim (state r (privateStreams rows)) io
+
+private def registers (p w : ℕ) (i : Fin 8) : BurstRAM.Word w :=
+ if i = 0 then Fin.ofNat _ p else 0
+
+private theorem valid : CallCopies.Valid scratch copies := by
+ refine ⟨by decide, ?_, ?_, ?_⟩
+ · intro k hk
+ simp only [copies, List.map_cons, List.map_ofFn, List.mem_cons, List.mem_ofFn,
+ Function.comp_apply] at hk ⊢
+ rcases hk with rfl | rfl | ⟨i, rfl⟩ <;> simp [reg, persistent, marker]
+ · simp [copies, scratch]
+ · simp [copies, scratch, marker, persistent, reg]
+
+private theorem prepare_runs {p e w : ℕ} (c b a : List Bool) :
+ ∃ t ≤ 10 * (5 * (e + w) + 2) + 1, (CallCopies.copyPlan scratch copies).Runs t
+ (clean (external p e w c b a)) (frame (registers p w) e (external p e w c b a)) := by
+ let s := clean (external p e w c b a)
+ obtain ⟨t, ht, run⟩ := CallCopies.copyPlan_runs scratch copies s (e+w) valid rfl (by
+ intro pair h
+ simp only [copies, List.mem_cons, List.mem_ofFn] at h
+ rcases h with rfl | rfl | ⟨i, rfl⟩ <;> rfl) (by
+ intro pair h
+ simp only [copies, List.mem_cons, List.mem_ofFn] at h
+ rcases h with rfl | rfl | ⟨i, rfl⟩
+ · simp [s, clean, external]
+ · simp [s, clean, external]
+ · by_cases hi : i = 0 <;> simp [s, clean, regSource, external, hi])
+ have hreg (i : Fin 8) : CallCopies.copied copies s (reg i) = s (.inr (regSource i)) :=
+ CallCopies.copied_at copies s valid.1 (p := (.inr (regSource i), reg i))
+ (by simp only [copies, List.mem_cons, List.mem_ofFn]; exact Or.inr (Or.inr ⟨i, rfl⟩))
+ have hm : CallCopies.copied copies s marker = s (.inr .degree) :=
+ CallCopies.copied_at copies s valid.1 (List.mem_cons_self ..)
+ have hper : CallCopies.copied copies s persistent = s (.inr .zeroWord) :=
+ CallCopies.copied_at copies s valid.1 (List.mem_cons_of_mem _ (List.mem_cons_self ..))
+ have he : CallCopies.copied copies s = frame (registers p w) e (external p e w c b a) := by
+ funext j
+ rcases j with (k | k) | k
+ · cases k with
+ | reg i => by_cases hi : i = 0 <;> simpa [s, clean, frame, state, reg, registers, ISA.bank, regSource, hi,
+ external] using hreg i
+ | pub i => exact i.elim0
+ | persistent => exact hper
+ | work i => rw [CallCopies.copied_outside] <;> simp [s, clean, frame, state, ISA.bank, copies, reg,
+ marker, persistent]
+ | logPort i => rw [CallCopies.copied_outside] <;> cases i <;> simp [s, clean, frame, state, ISA.bank,
+ ISA.logStacks, AddressLog.keys, AddressLog.values, copies, reg, marker, persistent]
+ · cases k with
+ | outer x => cases x; exact hm
+ | _ => rw [CallCopies.copied_outside] <;> simp [s, clean, frame, state, privateStreams, copies,
+ reg, marker, persistent]
+ · rw [CallCopies.copied_outside] <;> simp [s, clean, frame, copies, reg, marker, persistent]
+ rw [he] at run
+ exact ⟨t, by simpa [copies] using ht, run⟩
+
+private theorem reclaim {w : ℕ} (r : Fin 8 → BurstRAM.Word w) (io : Stacks External) :
+ ∃ t ≤ 9 * (w + 1) + 1, (CallClear.cleanup occupied).Runs t (frame r 0 io) (clean io) := by
+ obtain ⟨t, ht, run⟩ := CallClear.cleanup_runs occupied (frame r 0 io) w (by
+ intro i hi
+ simp only [occupied, List.mem_cons, List.mem_ofFn] at hi
+ rcases hi with rfl | ⟨j, rfl⟩ <;> simp [frame, state, reg, persistent, ISA.bank])
+ have he : CallClear.erased occupied (frame r 0 io) = clean io := by
+ funext j
+ rcases j with (k | k) | k
+ · cases k with
+ | reg i =>
+ have hi : reg i ∈ occupied := List.mem_cons_of_mem _ (List.mem_ofFn.mpr ⟨i, rfl⟩)
+ exact ite_eq_left hi
+ | pub i => exact i.elim0
+ | persistent => exact ite_eq_left (List.mem_cons_self ..)
+ | work i => simp [CallClear.erased, occupied, reg, persistent, frame, clean, state, ISA.bank]
+ | logPort i => cases i <;> simp [CallClear.erased, occupied, reg, persistent, frame, clean, state,
+ ISA.bank, ISA.logStacks, AddressLog.keys, AddressLog.values]
+ · cases k <;> simp [CallClear.erased, occupied, reg, persistent, frame, clean, state, privateStreams]
+ · simp [CallClear.erased, occupied, reg, persistent, frame, clean]
+ rw [he] at run
+ exact ⟨t, by simpa [occupied] using ht, run⟩
+
+/-- Consume the query and replace the accumulator by the coefficientwise result. -/
+theorem operation_runs (op : Word.Op) {p e w : ℕ} [NeZero p] (hw : Word.workingWidth p ≤ w) (a b : Vector p e)
+ (coeff : List Bool) :
+ ∃ t ≤ callCap e w, (operation op).Runs t
+ (clean (external p e w coeff (packed w (List.ofFn b)) (packed w (List.ofFn a))))
+ (clean (external p e w coeff [] (packed w (List.ofFn (fun i => op.eval (a i) (b i)))))) := by
+ let input := external p e w coeff (packed w (List.ofFn b)) (packed w (List.ofFn a))
+ let output := external p e w coeff [] (packed w (List.ofFn (fun i => op.eval (a i) (b i))))
+ obtain ⟨t, ht, init⟩ := prepare_runs (p := p) (e := e) (w := w) coeff (packed w (List.ofFn b))
+ (packed w (List.ofFn a))
+ obtain ⟨n, next, hn, _, scan⟩ := SliceArithmeticAdd.vectorOp_runs op hw () (fun _ => []) (registers p w)
+ (by simpa [registers] using Nat.mod_eq_of_lt (Word.modulus_lt hw)) a b
+ have run : ((SliceArithmeticAdd.vectorOp op ()).onPorts scanPort).Runs n
+ (frame (registers p w) e input) (frame next 0 output) := by
+ apply FiniteRoutine.runs_onPorts_framed _ scanPort_injective scan
+ · rintro (i | i)
+ · rfl
+ · cases i <;> simp [scanPort, frame, state, SliceArithmeticAdd.streams, privateStreams, input, external]
+ · rintro (i | i)
+ · rfl
+ · cases i <;> simp [scanPort, frame, state, SliceArithmeticAdd.streams, privateStreams, output, external]
+ · rintro ((i | i) | i) h
+ · exact (h (.inl i) rfl).elim
+ · cases i with
+ | old | coeff | factor | out | scratch => rfl
+ | outer x => exact (h (.inr (.outer x)) rfl).elim
+ · cases i with
+ | query => exact (h (.inr .factor) rfl).elim
+ | acc => exact (h (.inr .coeff) rfl).elim
+ | _ => rfl
+ obtain ⟨k, hk, done⟩ := reclaim next output
+ exact ⟨_, Nat.add_le_add (Nat.add_le_add ht hn) hk, (init.followedBy run).followedBy done⟩
+
+/-- Add two packed coefficient vectors with the shared field-arithmetic port convention. -/
+def machine : FiniteRoutine Port := operation .add
+
+/-- Add the query to the accumulator, consuming the query and reclaiming every
+private stack. The modulus, zero word, degree markers and coefficient advice
+are available to subsequent calls. -/
+theorem machine_runs {p e w : ℕ} [NeZero p] (hw : Word.workingWidth p ≤ w) (a b : Vector p e)
+ (coeff : List Bool) :
+ ∃ t ≤ callCap e w, machine.Runs t
+ (clean (external p e w coeff (packed w (List.ofFn b)) (packed w (List.ofFn a))))
+ (clean (external p e w coeff [] (packed w (List.ofFn (add a b))))) :=
+ operation_runs .add hw a b coeff
+
+end SliceArithmetic.AddCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticAdvice.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticAdvice.lean
new file mode 100644
index 0000000000..2f83c5764b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticAdvice.lean
@@ -0,0 +1,79 @@
+import OAI.Computability.VPVNP.SliceArithmetic
+import OAI.Computability.VPVNP.SliceEvaluator
+
+/-!
+# Recovering the evaluator's functional from its advised polynomial
+
+Choose the minimal polynomial of the same power-basis generator used by the
+evaluator. The quotient isomorphism sends the formal root to this generator,
+so reading the first coefficient of an encoded field element computes the
+prime-field coordinate used by the branch counter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic
+
+open Polynomial
+
+/-- The low limb is the output of the final prime-field coordinate query. -/
+def primeCoordinate {p e : ℕ} [NeZero e] (v : Vector p e) : Fin p := v 0
+
+private theorem coord_map_value {p e : ℕ} [NeZero e]
+ {K : Type*} [Field K] [Algebra (ZMod p) K] (pb : PowerBasis (ZMod p) K)
+ (he : pb.dim = e) (f : (ZMod p)[X]) (φ : AdjoinRoot f ≃ₐ[ZMod p] K)
+ (hφ : φ (AdjoinRoot.root f) = pb.gen) (v : Vector p e) :
+ pb.basis.coord ⟨0, pb.dim_pos⟩ (φ (value f v)) = ((primeCoordinate v).val : ZMod p) := by
+ subst e
+ have h : φ (value f v) = ∑ j, ((v j).val : ZMod p) • pb.basis j := by
+ simp only [value, map_sum, map_mul, AlgEquiv.commutes, map_pow, hφ, pb.basis_eq_pow,
+ Algebra.smul_def]
+ rw [h, map_sum]
+ simp only [map_smul, Module.Basis.coord_apply, Module.Basis.repr_self, Finsupp.single_apply,
+ smul_eq_mul, mul_ite, mul_one, mul_zero]
+ rw [Finset.sum_eq_single (0 : Fin pb.dim)]
+ · simp [primeCoordinate]
+ · intro i _ hi
+ simp [hi]
+ · simp
+
+/-- Select one binary description and one field isomorphism that realize
+the evaluator's specified coordinate on all coefficient vectors at once. -/
+theorem exists_compatible_advice (p N : ℕ) [Fact p.Prime] [Fintype (SliceField.FieldOf p N)] :
+ let e := SliceField.extensionDegree p N
+ let K := SliceField.FieldOf p N
+ ∃ c : Vector p e, ∃ φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K,
+ modulus c = SliceField.polynomialOfBits p e (encode c) ∧ Irreducible (modulus c) ∧
+ ∀ v : Vector p e, SliceEvaluator.primeCoordinate p K (φ (value (modulus c) v)) =
+ ((v ⟨0, Nat.succ_pos _⟩).val : ZMod p) := by
+ let e := SliceField.extensionDegree p N
+ let K := SliceField.FieldOf p N
+ let pb := Field.powerBasisOfFiniteOfSeparable (ZMod p) K
+ let f := minpoly (ZMod p) pb.gen
+ have he : pb.dim = e := pb.finrank.symm.trans (GaloisField.finrank p (Nat.succ_ne_zero _))
+ have hf : f.natDegree = e := pb.natDegree_minpoly.trans he
+ let c : Vector p e := fun i => (ZMod.finEquiv p).symm (f.coeff i.val)
+ have hc : modulus c = f := by
+ simp only [modulus, c, cast_val_eq_finEquiv, RingEquiv.apply_symm_apply]
+ have hm : f.Monic := minpoly.monic pb.isIntegral_gen
+ conv_rhs => rw [hm.as_sum, hf]
+ congr 1
+ exact Fin.sum_univ_eq_sum_range (fun i => C (f.coeff i) * X ^ i) e
+ let φ := AdjoinRoot.equiv' (modulus c) pb
+ (by change aeval (AdjoinRoot.root (modulus c)) f = 0; rw [← hc, AdjoinRoot.aeval_eq, AdjoinRoot.mk_self])
+ (by rw [hc]; exact minpoly.aeval _ _)
+ have hφ : φ (AdjoinRoot.root (modulus c)) = pb.gen := by
+ simp only [φ, AdjoinRoot.equiv'_apply]
+ apply AdjoinRoot.liftAlgHom_root
+ have : NeZero e := ⟨Nat.succ_ne_zero _⟩
+ refine ⟨c, φ, ?_, hc ▸ minpoly.irreducible pb.isIntegral_gen, fun v => ?_⟩
+ · simpa only [ofBits_encode] using modulus_ofBits (encode c)
+ · exact coord_map_value pb he _ φ hφ v
+
+end SliceArithmetic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticCallClear.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticCallClear.lean
new file mode 100644
index 0000000000..8de9afa6cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticCallClear.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.RAMTapeISAPorts
+
+/-! # Reclaiming the finite workspace of a slice-field multiplication call -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.CallClear
+
+open RAMTape
+
+variable {K : Type} [DecidableEq K]
+
+/-- Discard the bits on one port and return on the first empty pop. -/
+def clear (k : K) : FiniteRoutine K := FiniteRoutine.ofRoutine {
+ entry := ()
+ code := fun _ => .pop k fun b => b.map fun _ => () }
+
+theorem clear_runs (k : K) (s : Stacks K) :
+ (clear k).Runs ((s k).length + 1) s (Function.update s k []) := by
+ generalize h : s k = bits
+ induction bits generalizing s with
+ | nil =>
+ have step := StackStep.pop (s := s) (code := (clear k).body.standalone)
+ (q := some ()) (show (clear k).body.standalone (some ()) = .pop k (fun b => b.map fun _ => ()) from rfl)
+ rw [h] at step
+ exact .cons step (.nil ..)
+ | cons b bs ih =>
+ have step := StackStep.pop (s := s) (code := (clear k).body.standalone)
+ (q := some ()) (show (clear k).body.standalone (some ()) = .pop k (fun x => x.map fun _ => ()) from rfl)
+ rw [h] at step
+ have run := ih (Function.update s k bs) (Function.update_self ..)
+ rw [Function.update_idem] at run
+ exact .cons step run
+
+/-- A fixed table of ports to erase before a normal return. -/
+def cleanup : List K → FiniteRoutine K
+ | [] => .ret
+ | i :: is => (clear i).followedBy (cleanup is)
+
+/-- Stack bank obtained by emptying the specified ports and retaining all other contents. -/
+def erased (ks : List K) (s : Stacks K) : Stacks K :=
+ fun k => if k ∈ ks then [] else s k
+
+theorem cleanup_runs (ks : List K) (s : Stacks K) (bound : ℕ)
+ (h : ∀ i ∈ ks, (s i).length ≤ bound) :
+ ∃ t ≤ ks.length * (bound + 1) + 1, (cleanup ks).Runs t s (erased ks s) := by
+ induction ks generalizing s with
+ | nil =>
+ have he : erased [] s = s := by funext k; simp [erased]
+ exact ⟨1, by simp, he.symm ▸ Routine.runs_ret s⟩
+ | cons k ks ih =>
+ obtain ⟨n, hn, tail⟩ := ih (Function.update s k []) (by
+ intro j hj
+ by_cases he : j = k
+ · simp [he]
+ · simpa [Function.update_of_ne he] using h j (List.mem_cons_of_mem k hj))
+ have he : erased ks (Function.update s k []) = erased (k :: ks) s := by
+ funext j
+ by_cases h₁ : j = k <;> by_cases h₂ : j ∈ ks <;> simp [erased, h₁, h₂]
+ rw [he] at tail
+ have hk := h k (List.mem_cons_self ..)
+ refine ⟨_, ?_, (clear_runs k s).followedBy tail⟩
+ rw [List.length_cons, Nat.succ_mul]
+ omega
+
+end SliceArithmetic.CallClear
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticCallCopies.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticCallCopies.lean
new file mode 100644
index 0000000000..20c4ffe9e5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticCallCopies.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-!
+# Copying the input stacks of an arithmetic call
+
+The fixed list of source and destination ports determines the control table.
+Sources may repeat, so an advised word can initialize several ports in one call.
+One empty scratch stack serves the entire sequence.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.CallCopies
+
+open RAMTape RAMTape.SuccessorFields
+
+variable {K : Type}
+
+/-- Each pair specifies a source and its destination. -/
+def copyPlan (scratch : K) : List (K × K) → FiniteRoutine K
+ | [] => .ret
+ | p :: ps => (prependCopy p.1 p.2 scratch).followedBy (copyPlan scratch ps)
+
+/-- Destinations are distinct, sources are read-only, and scratch is separate. -/
+abbrev Valid (scratch : K) (pairs : List (K × K)) : Prop :=
+ (pairs.map Prod.snd).Nodup ∧
+ (∀ k ∈ pairs.map Prod.fst, k ∉ pairs.map Prod.snd) ∧
+ scratch ∉ pairs.map Prod.fst ∧ scratch ∉ pairs.map Prod.snd
+
+variable [DecidableEq K]
+
+private def fill (pairs : List (K × K)) (source base : Stacks K) : Stacks K :=
+ pairs.foldl (fun bank p => Function.update bank p.2 (source p.1)) base
+
+/-- The destinations contain the corresponding original source values. -/
+def copied (pairs : List (K × K)) (s : Stacks K) : Stacks K :=
+ pairs.foldl (fun bank p => Function.update bank p.2 (s p.1)) s
+
+private theorem fill_outside (pairs : List (K × K)) (source base : Stacks K) (k : K)
+ (hk : k ∉ pairs.map Prod.snd) : fill pairs source base k = base k := by
+ induction pairs generalizing base with
+ | nil => rfl
+ | cons p ps ih =>
+ simp only [List.map_cons, List.mem_cons, not_or] at hk
+ exact (ih (Function.update base p.2 (source p.1)) hk.2).trans (Function.update_of_ne hk.1 ..)
+
+theorem copied_outside (pairs : List (K × K)) (s : Stacks K) (k : K)
+ (hk : k ∉ pairs.map Prod.snd) : copied pairs s k = s k :=
+ fill_outside pairs s s k hk
+
+private theorem fill_at (pairs : List (K × K)) (source base : Stacks K)
+ (hn : (pairs.map Prod.snd).Nodup) {p : K × K} (hp : p ∈ pairs) :
+ fill pairs source base p.2 = source p.1 := by
+ induction pairs generalizing base with
+ | nil => simp at hp
+ | cons q ps ih =>
+ obtain ⟨hq, hn'⟩ := List.nodup_cons.mp hn
+ rcases List.mem_cons.mp hp with rfl | hp
+ · exact (fill_outside ps source _ p.2 hq).trans (Function.update_self ..)
+ · exact ih _ hn' hp
+
+theorem copied_at (pairs : List (K × K)) (s : Stacks K) (hn : (pairs.map Prod.snd).Nodup)
+ {p : K × K} (hp : p ∈ pairs) : copied pairs s p.2 = s p.1 :=
+ fill_at pairs s s hn hp
+
+private theorem run_from (scratch : K) (pairs : List (K × K)) (source base : Stacks K) (M : ℕ)
+ (valid : Valid scratch pairs) (ht : base scratch = [])
+ (reads : ∀ p ∈ pairs, base p.1 = source p.1) (empty : ∀ p ∈ pairs, base p.2 = [])
+ (bound : ∀ p ∈ pairs, (source p.1).length ≤ M) :
+ ∃ t ≤ pairs.length * (5*M+2) + 1, (copyPlan scratch pairs).Runs t base (fill pairs source base) := by
+ induction pairs generalizing base with
+ | nil => exact ⟨1, by simp, Routine.runs_ret base⟩
+ | cons p ps ih =>
+ obtain ⟨hn, hd, hs, ht'⟩ := valid
+ obtain ⟨hfresh, hn'⟩ := List.nodup_cons.mp hn
+ simp only [List.map_cons, List.mem_cons, not_or] at hs ht'
+ have head := hd p.1 (List.mem_cons_self ..)
+ simp only [List.map_cons, List.mem_cons, not_or] at head
+ have member (q : K × K) (hq : q ∈ ps) := List.mem_cons_of_mem p hq
+ have hvalid : Valid scratch ps := ⟨hn', fun k hk hk' =>
+ hd k (List.mem_cons_of_mem _ hk) (List.mem_cons_of_mem _ hk'), hs.2, ht'.2⟩
+ let mid := Function.update base p.2 (source p.1)
+ have hread := reads p (List.mem_cons_self ..)
+ have hempty := empty p (List.mem_cons_self ..)
+ have first : (prependCopy p.1 p.2 scratch).Runs (5 * (source p.1).length + 2) base mid := by
+ simpa only [hread, hempty, List.append_nil] using
+ prependCopy_runs p.1 p.2 scratch head.1 (Ne.symm hs.1) (Ne.symm ht'.1) base ht
+ obtain ⟨t, hb, tail⟩ := ih mid hvalid (by simpa [mid, ht'.1] using ht) (by
+ intro q hq
+ have hne : q.1 ≠ p.2 := fun e => hd q.1 (List.mem_map.mpr ⟨q, member q hq, rfl⟩)
+ (List.mem_cons.mpr (.inl e))
+ simpa [mid, hne] using reads q (member q hq)) (by
+ intro q hq
+ have hne : q.2 ≠ p.2 := fun e => hfresh (List.mem_map.mpr ⟨q, hq, e⟩)
+ simpa [mid, hne] using empty q (member q hq)) (fun q hq => bound q (member q hq))
+ refine ⟨_, ?_, first.followedBy tail⟩
+ have hhead := bound p (List.mem_cons_self ..)
+ calc
+ 5 * (source p.1).length + 2 + t ≤ (5*M+2) + (ps.length * (5*M+2)+1) :=
+ Nat.add_le_add (by omega) hb
+ _ = (p :: ps).length * (5*M+2) + 1 := by rw [List.length_cons, Nat.add_mul]; ring
+
+/-- Each destination starts empty and receives one source copy. Each source
+bit costs five instructions, each copy tests for the end twice, and the
+final return costs one instruction. -/
+theorem copyPlan_runs (scratch : K) (pairs : List (K × K)) (s : Stacks K) (M : ℕ)
+ (valid : Valid scratch pairs) (ht : s scratch = [])
+ (empty : ∀ p ∈ pairs, s p.2 = []) (bound : ∀ p ∈ pairs, (s p.1).length ≤ M) :
+ ∃ t ≤ pairs.length * (5*M+2) + 1, (copyPlan scratch pairs).Runs t s (copied pairs s) :=
+ run_from scratch pairs s s M valid ht (fun _ _ => rfl) empty bound
+
+end SliceArithmetic.CallCopies
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticCallOrder.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticCallOrder.lean
new file mode 100644
index 0000000000..124a77c3ef
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticCallOrder.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.SliceArithmeticCallPorts
+import OAI.Computability.VPVNP.SliceArithmeticMultiplyReverse
+
+/-! # Installing the digit-order conversion in a reusable multiplication call -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.MultiplyCall
+
+open RAMTape BurstRAM HornerControl
+open SliceArithmeticRound (packed)
+open SliceArithmeticStreamRow (state)
+
+private def orderPort : SliceArithmeticMultiplyReverse.Port → Port
+ | .query => .inr .query
+ | .digits => localStream (.outer .digits)
+ | .old => localStream .old
+ | .marker => localStream (.outer .rows)
+ | .staging => reg 4
+ | .zero => persistent
+ | .scratch => localStream .scratch
+
+private theorem orderPort_injective : Function.Injective orderPort := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [orderPort, reg, localStream, persistent]
+
+/-- Consume the query in increasing degree order to prepare high-degree-first Horner digits and
+a zero accumulator. -/
+def orderInput : FiniteRoutine Port := SliceArithmeticMultiplyReverse.prepare.onPorts orderPort
+
+theorem orderInput_runs {p e w : ℕ} [NeZero p] (cb bb : List Bool) (a : Vector p e) :
+ let ab := packed w (List.ofFn a)
+ let digits := packed w (List.ofFn a).reverse
+ let zeros := packed w (List.ofFn (zero p e))
+ let r := initialRegisters p w
+ orderInput.Runs (e * (15*w+7) + 1 + (10*w+4))
+ (workspace (state r (streams [] [] [] [] (extra cb bb e [] e e))) (external p e w cb ab bb))
+ (workspace (state r (streams zeros [] [] [] (extra cb bb e digits e 0))) (external p e w cb [] bb)) := by
+ intro ab digits zeros r
+ let words := (List.ofFn a).map (Word.limb w)
+ have hin : SliceArithmeticMultiplyReverse.pack words = ab := by
+ simp only [SliceArithmeticMultiplyReverse.pack, words, ab, packed, List.flatMap_map]
+ have hout : SliceArithmeticMultiplyReverse.pack words.reverse = digits := by
+ rw [show words.reverse = (List.ofFn a).reverse.map (Word.limb w) from List.map_reverse.symm]
+ simp only [SliceArithmeticMultiplyReverse.pack, digits, packed, List.flatMap_map]
+ have hz : SliceArithmeticMultiplyReverse.pack (List.replicate e (0 : BurstRAM.Word w)) = zeros := by
+ have hv : List.ofFn (zero p e) = List.replicate e (0 : Fin p) := List.ofFn_const e 0
+ simp [zeros, hv, packed, SliceArithmeticMultiplyReverse.pack, Word.limb, List.flatMap_replicate]
+ have run := SliceArithmeticMultiplyReverse.prepare_runs words [] [] [] (0 : BurstRAM.Word w)
+ rw [show words.length = e by simp [words], hin, hout, hz] at run
+ simp only [List.append_nil] at run
+ apply SliceArithmeticMultiplyReverse.prepare.runs_onPorts_framed orderPort_injective run
+ · intro i
+ cases i <;> rfl
+ · intro i
+ cases i <;> rfl
+ · rintro ((k | k) | k) h
+ · rfl
+ · cases k with
+ | old => exact (h .old rfl).elim
+ | outer x =>
+ cases x with
+ | digits => exact (h .digits rfl).elim
+ | rows => exact (h .marker rfl).elim
+ | _ => rfl
+ | _ => rfl
+ · cases k with
+ | query => exact (h .query rfl).elim
+ | _ => rfl
+
+end SliceArithmetic.MultiplyCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticCallPorts.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticCallPorts.lean
new file mode 100644
index 0000000000..8ec629ecb7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticCallPorts.lean
@@ -0,0 +1,148 @@
+import OAI.Computability.VPVNP.SliceArithmeticHornerMachine
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+
+/-!
+# Ports of the reusable slice-field multiplication call
+
+The external interface uses the same low-degree-first polynomial basis for
+both operands. Each limb occupies a full arithmetic register. The internal
+Horner machine has disjoint ports so its workspace can be reclaimed on return.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.MultiplyCall
+
+open RAMTape BurstRAM HornerControl
+open SliceArithmeticStreamRow (state StreamPort)
+
+/-- Caller ports for the prime, zero-word template, degree markers, reduction polynomial, query
+scalar, and accumulator. -/
+inductive External where
+ | prime | zeroWord | degree | coeff | query | acc
+ deriving DecidableEq
+
+instance : Fintype External :=
+ ⟨{.prime, .zeroWord, .degree, .coeff, .query, .acc}, by intro x; cases x <;> simp⟩
+
+/-- The stack interface for field multiplication, combining private Horner workspace with the
+six caller ports. -/
+abbrev Port := HornerControl.Ports ⊕ External
+
+/-- Select arithmetic register `i` inside the multiplication call's Horner workspace. -/
+def reg (i : Fin 8) : Port := .inl (.inl (.reg i))
+
+/-- The multiplication workspace's persistent register-width template port. -/
+def persistent : Port := .inl (.inl .persistent)
+
+/-- Embed a Horner coefficient-stream port into the multiplication call's private workspace. -/
+def localStream (s : StreamPort Extra) : Port := .inl (.inr s)
+
+/-- The caller's packed field parameters and operands, including one unary marker per extension
+degree. -/
+def external (p e w : ℕ) (coeff query acc : List Bool) : Stacks External
+ | .prime => wordBits (Fin.ofNat (2^w) p)
+ | .zeroWord => wordBits (0 : BurstRAM.Word w)
+ | .degree => List.replicate e true
+ | .coeff => coeff
+ | .query => query
+ | .acc => acc
+
+/-- Clean entry and return boundaries. -/
+def clean (io : Stacks External) : Stacks Port := Sum.elim (fun _ => []) io
+
+/-- Combine a Horner register and stream bank with the external stacks of the multiplication
+call. -/
+def workspace (internal : Stacks HornerControl.Ports) (io : Stacks External) : Stacks Port :=
+ Sum.elim internal io
+
+/-- Copy the persistent inputs, the three loop counts and the zero-register templates. -/
+def copies : List (Port × Port) :=
+ [(.inr .prime, reg 0), (.inr .zeroWord, reg 1), (.inr .zeroWord, reg 2), (.inr .zeroWord, reg 3),
+ (.inr .zeroWord, reg 4), (.inr .zeroWord, reg 5), (.inr .zeroWord, reg 6), (.inr .zeroWord, reg 7),
+ (.inr .zeroWord, persistent), (.inr .coeff, localStream (.outer .savedCoeff)),
+ (.inr .acc, localStream (.outer .savedFactor)), (.inr .degree, localStream (.outer .savedCount)),
+ (.inr .degree, localStream (.outer .rounds)), (.inr .degree, localStream (.outer .rows))]
+
+/-- Exactly the occupied internal ports after multiplication. -/
+def occupied : List Port :=
+ (List.ofFn reg) ++ [persistent, localStream .old, localStream (.outer .savedCoeff),
+ localStream (.outer .savedFactor), localStream (.outer .savedCount)]
+
+/-- Replace the caller's accumulator with the finished Horner product and clear the occupied
+private stacks. -/
+def reclaim : FiniteRoutine Port :=
+ ((CallClear.clear (.inr .acc)).followedBy
+ (SuccessorFields.prependCopy (localStream .old) (.inr .acc) (localStream .scratch))).followedBy
+ (CallClear.cleanup occupied)
+
+private theorem occupied_length : occupied.length = 13 := by simp [occupied]
+
+/-- Copy the output to the caller, erase the old accumulator and reclaim
+all local registers and streams. -/
+theorem reclaim_runs {p e w : ℕ} (registers : Fin 8 → BurstRAM.Word w)
+ (coeff factor result : List Bool) (hc : coeff.length = e*w) (hb : factor.length = e*w)
+ (hr : result.length = e*w) :
+ let caller := extra coeff factor e [] 0 0
+ let internal := state registers (streams result [] [] [] caller)
+ ∃ t ≤ (e*w+1) + (5*(e*w)+2) + (13*((e+1)*(w+1)+1)+1), reclaim.Runs t
+ (workspace internal (external p e w coeff [] factor))
+ (clean (external p e w coeff [] result)) := by
+ intro caller internal
+ let src := workspace internal (external p e w coeff [] factor)
+ let blank := workspace internal (external p e w coeff [] [])
+ let target := workspace internal (external p e w coeff [] result)
+ have hclear := CallClear.clear_runs (.inr External.acc : Port) src
+ have hblank : Function.update src (.inr .acc) [] = blank := by
+ funext i
+ rcases i with i | i
+ · rfl
+ · cases i <;> rfl
+ rw [hblank, show (src (.inr .acc)).length = e*w from hb] at hclear
+ have hcopy := SuccessorFields.prependCopy_runs (localStream .old) (.inr External.acc)
+ (localStream .scratch) (by decide) (by decide) (by decide) blank rfl
+ have htarget : Function.update blank (.inr .acc) (blank (localStream .old) ++ blank (.inr .acc)) =
+ target := by
+ funext i
+ rcases i with i | i
+ · rfl
+ · cases i <;> simp [blank, target, workspace, external, localStream, internal, streams, state]
+ rw [htarget, show (blank (localStream .old)).length = e*w from hr] at hcopy
+ have hlen (i : Port) (hi : i ∈ occupied) : (target i).length ≤ (e+1)*(w+1) := by
+ simp only [occupied, List.mem_append, List.mem_ofFn, List.mem_cons, List.not_mem_nil, or_false] at hi
+ rcases hi with ⟨j, rfl⟩ | rfl | rfl | rfl | rfl | rfl <;>
+ simp [target, workspace, internal, state, reg, persistent, localStream, ISA.bank, streams,
+ caller, extra, hc, hb, hr] <;> nlinarith
+ obtain ⟨n, hn, hclean⟩ := CallClear.cleanup_runs occupied target ((e+1)*(w+1)) hlen
+ have finalEq : CallClear.erased occupied target = clean (external p e w coeff [] result) := by
+ funext i
+ rcases i with (k | k) | k
+ · cases k with
+ | reg i =>
+ have hi : reg i ∈ occupied := List.mem_append_left _ (List.mem_ofFn.mpr ⟨i, rfl⟩)
+ unfold CallClear.erased
+ dsimp only [reg] at hi
+ rw [ite_eq_left hi]
+ rfl
+ | pub i => exact i.elim0
+ | work i => simp [CallClear.erased, occupied, reg, persistent, localStream, target, workspace, internal, state, ISA.bank, clean]
+ | persistent => simp [CallClear.erased, occupied, persistent, clean]
+ | logPort i =>
+ cases i <;> simp [CallClear.erased, occupied, reg, persistent, localStream, target, workspace, internal, state,
+ ISA.bank, ISA.logStacks, clean, AddressLog.keys, AddressLog.values]
+ · cases k with
+ | outer x => cases x <;> simp [CallClear.erased, occupied, reg, persistent, localStream, target, workspace,
+ internal, state, streams, caller, extra, clean]
+ | _ => simp [CallClear.erased, occupied, reg, persistent, localStream, target, workspace, internal, state, streams, clean]
+ · simp [CallClear.erased, occupied, reg, persistent, localStream, target, workspace, clean]
+ rw [finalEq] at hclean
+ rw [occupied_length] at hn
+ exact ⟨_, by omega, (hclear.followedBy hcopy).followedBy hclean⟩
+
+end SliceArithmetic.MultiplyCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticConstant.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticConstant.lean
new file mode 100644
index 0000000000..a4d0ebf579
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticConstant.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.SliceArithmeticEncoding
+import OAI.Computability.VPVNP.RAMTapeWordOperands
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-!
+# Returning the field constants zero and one on bit stacks
+
+The advised defining polynomial occupies exactly as many limbs as a scalar.
+Its packed representation supplies the width template for a literal scan.
+The scan restores the template and writes the selected constant in the
+extension field's packed power-basis format.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticConstant
+
+open SliceArithmetic SliceArithmeticRound RAMTape BurstRAM TapeWord
+
+private def normal {A : Type} : Operand.State A → Bool
+ | .done _ => true
+ | _ => false
+
+/-- Scan a packed width template to write the extension-field literal zero or one according to
+`b`. -/
+def machine (b : Bool) : FiniteRoutine ScanPort :=
+ .ofStackCode (Operand.code (Operand.literalBit b.toNat)) id (.clear (Fin.last b.toNat)) normal
+
+private theorem scan_runs (b : Bool) (template old : List Bool) :
+ (machine b).Runs (old.length + 7 * template.length + 3) (scanStacks template [] [] old)
+ (scanStacks template [] [] (wordBits (Fin.ofNat (2^template.length) b.toNat))) := by
+ let W := template.length
+ let x : BurstRAM.Word W := ⟨value template, value_lt template⟩
+ have hx : wordBits x = template := eq_of_length_value (length_wordBits x) (value_wordBits x)
+ obtain ⟨q, hr⟩ := Operand.literal_run b.toNat x old
+ rw [hx] at hr
+ apply FiniteRoutine.runs_ofStackCode_framed Function.injective_id rfl (exit := .done q) rfl ?_ hr
+ (fun _ => rfl) (fun _ => rfl) (fun i hi => (hi i rfl).elim)
+ intro i hi
+ cases i <;> simp_all [normal, Operand.code]
+
+variable {p e w : ℕ} [Fact p.Prime]
+
+/-- Chosen coefficient vector of the returned field literal. -/
+def literal (b : Bool) (p e : ℕ) [NeZero p] : Vector p e := if b then one p e else zero p e
+
+private theorem packed_zero_value (w : ℕ) (e : ℕ) :
+ TapeWord.value (packed w (List.ofFn (zero p e))) = 0 := by
+ induction e with
+ | zero => rfl
+ | succ e ih =>
+ rw [List.ofFn_succ, packed, List.flatMap_cons, value_append]
+ change TapeWord.value (wordBits (Word.limb w (0 : Fin p))) +
+ 2 ^ _ * TapeWord.value (packed w (List.ofFn (zero p e))) = 0
+ simp [ih, value_wordBits, Word.limb]
+
+private theorem packed_literal_value (he : 0 < e) (hw : Word.workingWidth p ≤ w) (b : Bool) :
+ TapeWord.value (packed w (List.ofFn (literal b p e))) = b.toNat := by
+ cases b with
+ | false => exact packed_zero_value _ _
+ | true =>
+ cases e with
+ | zero => omega
+ | succ e =>
+ change TapeWord.value (packed w (List.ofFn (one p (e+1)))) = 1
+ rw [List.ofFn_succ]
+ have ht : (fun i : Fin e => one p (e + 1) i.succ) = zero p e := by funext i; simp [one, zero]
+ rw [ht, packed, List.flatMap_cons, value_append]
+ change TapeWord.value (wordBits (Word.limb w (1 : Fin p))) +
+ 2 ^ _ * TapeWord.value (packed w (List.ofFn (zero p e))) = 1
+ rw [packed_zero_value, mul_zero, add_zero, value_wordBits, Word.limb_val hw]
+ exact Nat.mod_eq_of_lt (Fact.out : p.Prime).one_lt
+
+/-- Initialize or overwrite a scalar result on `.out`. The advised
+polynomial on `.left` is preserved and both temporary stacks return empty. -/
+theorem machine_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w) (b : Bool)
+ (c : Vector p e) (old : List Bool) :
+ (machine b).Runs (old.length + 7 * (e*w) + 3)
+ (scanStacks (packed w (List.ofFn c)) [] [] old)
+ (scanStacks (packed w (List.ofFn c)) [] [] (packed w (List.ofFn (literal b p e)))) := by
+ have h := scan_runs b (packed w (List.ofFn c)) old
+ rw [packed_length, List.length_ofFn] at h
+ have hW : 0 < e * w := Nat.mul_pos he (by unfold Word.workingWidth at hw; omega)
+ have hfit : b.toNat < 2^(e*w) := (Bool.toNat_le b).trans_lt (one_lt_pow₀ (by decide) (by omega))
+ have eq : wordBits (Fin.ofNat (2^(e*w)) b.toNat) = packed w (List.ofFn (literal b p e)) := by
+ apply eq_of_length_value (by simp)
+ rw [value_wordBits, Fin.val_ofNat, Nat.mod_eq_of_lt hfit, packed_literal_value he hw]
+ rw [← eq]
+ exact h
+
+end SliceArithmeticConstant
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticConstantEmit.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticConstantEmit.lean
new file mode 100644
index 0000000000..70a8113f99
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticConstantEmit.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.SliceArithmeticStreamWord
+import OAI.Computability.VPVNP.SliceArithmeticLoop
+import OAI.Computability.VPVNP.RAMTapeUnaryWordValue
+
+/-!
+# Emitting a prime-field coefficient in the extension-field representation
+
+A scalar from the prime field occupies the low limb of its power-basis
+representation. The unary extension degree supplies one marker per limb.
+The machine copies these markers, discards the one for the low limb, then
+prepends one zero word per remaining marker before emitting the low limb.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.ConstantEmit
+
+open RAMTape BurstRAM
+
+set_option backward.isDefEq.respectTransparency false in
+/-- Ports for the extension degree, zero-word template, prime-field limb, output, and temporary
+marker and copy stacks. -/
+inductive Port where
+ | degree | zeroWord | limb | out | scratch | marker
+ deriving DecidableEq, Fintype
+
+/-- Initial or intermediate state of the constant emitter, including the current marker count
+and output suffix. -/
+def frame (e w : ℕ) (x : BurstRAM.Word w) (out : List Bool) (markers : ℕ) : Stacks Port
+ | .degree => List.replicate e true
+ | .zeroWord => wordBits (0 : BurstRAM.Word w)
+ | .limb => wordBits x
+ | .out => out
+ | .scratch => []
+ | .marker => List.replicate markers true
+
+private def zeros : FiniteRoutine Port :=
+ FiniteRoutine.repeatMarked .marker (StreamWord.store .out .zeroWord .scratch)
+
+private def pad : FiniteRoutine Port :=
+ .ofRoutine (Routine.popCase .marker (Routine.halt false) (Routine.halt false) zeros.body)
+
+/-- Fixed instruction table for prepending a scalar with one significant limb. -/
+def machine : FiniteRoutine Port :=
+ ((SuccessorFields.prependCopy .degree .marker .scratch).followedBy pad).followedBy
+ (StreamWord.store .out .limb .scratch)
+
+/-- Time for copying the degree, dropping the first marker, scanning the
+remaining markers and storing the low limb. -/
+def cost (e w : ℕ) := 5 * e + 2 + ((e - 1) * (5 * w + 3) + 2) + (5 * w + 2)
+
+private theorem update_markers (e w : ℕ) (x : BurstRAM.Word w) (s : List Bool) (m n : ℕ) :
+ Function.update (frame e w x s m) .marker (List.replicate n true) = frame e w x s n := by
+ funext i
+ cases i <;> rfl
+
+private theorem update_output (e w : ℕ) (x : BurstRAM.Word w) (s t : List Bool) (m : ℕ) :
+ Function.update (frame e w x s m) .out t = frame e w x t m := by
+ funext i
+ cases i <;> rfl
+
+private theorem zeros_runs (e w : ℕ) (x : BurstRAM.Word w) (m : ℕ) (s : List Bool) :
+ zeros.Runs (m * (5 * w + 3) + 1)
+ (frame e w x s m) (frame e w x (List.replicate (m * w) false ++ s) 0) := by
+ induction m generalizing s with
+ | zero =>
+ simp only [Nat.zero_mul, Nat.zero_add, List.replicate_zero, List.nil_append]
+ exact Routine.Runs.popLoop_empty Port.marker (fun _ => true) (Routine.halt false)
+ (StreamWord.store Port.out .zeroWord .scratch).body (s := frame e w x s 0) rfl
+ | succ m ih =>
+ let z := wordBits (0 : BurstRAM.Word w)
+ have copy := StreamWord.store_runs (stream := Port.out) (reg := .zeroWord) (scratch := .scratch)
+ (by decide) (by decide) (by decide) (frame e w x s m) (0 : BurstRAM.Word w) rfl rfl
+ rw [update_output] at copy
+ have htail := ih (z ++ s)
+ have hbits : List.replicate (m * w) false ++ (z ++ s) =
+ List.replicate ((m + 1) * w) false ++ s := by
+ rw [Nat.succ_mul, List.replicate_add, List.append_assoc, UnaryWord.zeros_wordBits w]
+ rw [hbits] at htail
+ rw [show (m + 1) * (5 * w + 3) + 1 = 1 + (5 * w + 2) + (m * (5 * w + 3) + 1) by
+ rw [Nat.succ_mul]; omega]
+ apply Routine.Runs.popLoop_true_continue Port.marker (fun _ => true) (Routine.halt false)
+ (StreamWord.store Port.out .zeroWord .scratch).body
+ (tail := List.replicate m true) (List.replicate_succ ..) rfl ?_ htail
+ rw [update_markers]
+ exact copy
+
+/-- The scalar is written before an arbitrary output suffix, least-significant
+limb first. The three input ports are preserved and both temporary ports
+return empty. -/
+theorem machine_runs {e w : ℕ} (he : 0 < e) (x : BurstRAM.Word w) (suffix : List Bool) :
+ machine.Runs (cost e w) (frame e w x suffix 0)
+ (frame e w x (wordBits x ++ List.replicate ((e - 1) * w) false ++ suffix) 0) := by
+ obtain ⟨m, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (Nat.ne_of_gt he)
+ let e := m + 1
+ have first := SuccessorFields.prependCopy_runs Port.degree .marker .scratch
+ (by decide) (by decide) (by decide) (frame e w x suffix 0) rfl
+ change (SuccessorFields.prependCopy ..).Runs (5 * (List.replicate e true).length + 2) _
+ (Function.update _ Port.marker (List.replicate e true ++ [])) at first
+ rw [List.length_replicate, List.append_nil, update_markers] at first
+ let padded := List.replicate (m * w) false ++ suffix
+ have middle : pad.Runs (m * (5 * w + 3) + 1 + 1)
+ (frame e w x suffix e) (frame e w x padded 0) := by
+ apply Routine.runs_popCase_true Port.marker (Routine.halt false) (Routine.halt false) zeros.body
+ (tail := List.replicate m true) (List.replicate_succ ..)
+ rw [update_markers]
+ exact zeros_runs e w x m suffix
+ have last := StreamWord.store_runs (stream := Port.out) (reg := .limb) (scratch := .scratch)
+ (by decide) (by decide) (by decide) (frame e w x padded 0) x rfl rfl
+ rw [update_output] at last
+ rw [List.append_assoc]
+ exact (first.followedBy middle).followedBy last
+
+end SliceArithmetic.ConstantEmit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticCountPorts.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticCountPorts.lean
new file mode 100644
index 0000000000..ab45d9e42d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticCountPorts.lean
@@ -0,0 +1,176 @@
+import OAI.Computability.VPVNP.SliceArithmeticMagnitude
+import OAI.Computability.VPVNP.SliceArithmeticSubtract
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-! # Register and stream interface for signed witness counts -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticSignedCount
+
+open BurstRAM RAMTape TapeWord
+
+/-- Caller ports for the two signed witness counts, the modulus and field width advice, and the
+output coefficient. -/
+inductive External where
+ | positive | negative | prime | zeroWord | degree | result
+ deriving DecidableEq
+instance : Fintype External :=
+ ⟨{.positive, .negative, .prime, .zeroWord, .degree, .result}, by intro i; cases i <;> simp⟩
+
+/-- Work ports for reducing both witness counts, subtracting their residues, and emitting the
+packed field coefficient. -/
+inductive Private where
+ | divide (i : DivisionStack.Port) | arithmetic (i : ISA.Port 3 0)
+ | residue (negative : Bool) | scratch | marker
+ deriving DecidableEq, Fintype
+
+/-- Stack interface for converting a signed witness count into a power-basis field element. -/
+abbrev Port := Private ⊕ External
+
+/-- Encode the two input counts, field parameters, and result suffix on the external
+signed-count ports. -/
+def external (p e w : ℕ) (positive negative result : List Bool) : Stacks External
+ | .positive => positive
+ | .negative => negative
+ | .prime => wordBits (Fin.ofNat (2^w) p)
+ | .zeroWord => wordBits (0 : BurstRAM.Word w)
+ | .degree => List.replicate e true
+ | .result => result
+
+/-- Install the current division input and the two saved residues alongside the caller's
+stacks. -/
+def frame (io : Stacks External) (input : List Bool) (residues : Bool → List Bool) : Stacks Port
+ | .inr i => io i
+ | .inl (.divide .input) => input
+ | .inl (.residue sign) => residues sign
+ | .inl _ => []
+
+/-- Signed-count workspace with empty division input and empty residue stacks for both signs. -/
+def clean (io : Stacks External) := frame io [] (fun _ => [])
+
+/-- Select the negative count when `sign` is true and the positive count otherwise. -/
+def source (sign : Bool) : External := if sign then .negative else .positive
+
+/-- Route division through the advised prime and store its remainder on the port for the chosen
+sign. -/
+def divisionPorts (sign : Bool) : DivisionStack.Port → Port
+ | .divisor => .inr .prime
+ | .remainder => .inl (.residue sign)
+ | i => .inl (.divide i)
+
+private theorem division_injective (sign : Bool) : Function.Injective (divisionPorts sign) := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [divisionPorts]
+
+/-- A preserved count supplies the input of the division. Its quotient is
+discarded, and the remainder remains on the selected arithmetic register. -/
+def reduceCount (sign : Bool) : FiniteRoutine Port :=
+ (SuccessorFields.prependCopy (.inr (source sign)) (.inl (.divide .input)) (.inl .scratch)).followedBy
+ (SliceArithmeticMagnitude.machine.onPorts (divisionPorts sign))
+
+/-- Step bound for copying an `n`-bit witness count and reducing it modulo a `w`-bit prime
+word. -/
+def reduceCost (n w : ℕ) := 5*n + 2 + SliceArithmeticMagnitude.cost n w
+
+theorem reduceCount_runs {p w : ℕ} [NeZero p] (hw : SliceArithmetic.Word.workingWidth p ≤ w)
+ (sign : Bool) (io : Stacks External) (r : Bool → List Bool) (empty : r sign = [])
+ (hprime : io .prime = wordBits (Fin.ofNat (2^w) p)) :
+ let x := io (source sign)
+ let a : Fin p := Fin.ofNat p (value x)
+ (reduceCount sign).Runs (reduceCost x.length w) (frame io [] r)
+ (frame io [] (Function.update r sign (wordBits (SliceArithmetic.Word.limb w a)))) := by
+ intro x a
+ let d : BurstRAM.Word w := Fin.ofNat _ p
+ let s := frame io [] r
+ let m := frame io x r
+ let u := frame io [] (Function.update r sign (wordBits (SliceArithmetic.Word.limb w a)))
+ have hp : d.val = p := Nat.mod_eq_of_lt (SliceArithmetic.Word.modulus_lt hw)
+ have copy := SuccessorFields.prependCopy_runs (.inr (source sign)) (.inl (.divide .input))
+ (.inl Private.scratch) (by simp) (by simp) (by decide) s rfl
+ have copied : Function.update s (.inl (.divide .input)) (s (.inr (source sign)) ++ s (.inl (.divide .input))) = m := by
+ funext i
+ rcases i with i|i
+ · cases i with
+ | divide j => cases j <;> simp [s, m, frame, x]
+ | _ => rfl
+ · rfl
+ rw [copied] at copy
+ have raw := SliceArithmeticMagnitude.machine_runs x d (hp.symm ▸ NeZero.pos p)
+ have div : (SliceArithmeticMagnitude.machine.onPorts (divisionPorts sign)).Runs
+ (SliceArithmeticMagnitude.cost x.length w) m u := by
+ apply FiniteRoutine.runs_onPorts_framed _ (division_injective sign) raw
+ · intro i
+ cases i with
+ | divisor => exact hprime
+ | remainder => exact empty
+ | _ => rfl
+ · intro i
+ cases i with
+ | divisor => exact hprime
+ | remainder =>
+ change Function.update r sign _ sign = _
+ rw [Function.update_self, hp]
+ rfl
+ | _ => rfl
+ · rintro (i|i) hi
+ · cases i with
+ | divide j => cases j <;> first | rfl | exact (hi .input rfl).elim
+ | residue b =>
+ have h : b ≠ sign := fun eq => hi .remainder (by rw [eq]; rfl)
+ exact Function.update_of_ne h ..
+ | _ => rfl
+ · rfl
+ exact copy.followedBy div
+
+/-- Map the subtraction registers to the prime and the two saved residues, using the caller's
+zero word as width template. -/
+def arithmeticPorts : ISA.Port 3 0 → Port
+ | .reg i => Fin.cases (.inr .prime) (Fin.cases (.inl (.residue false)) (fun _ => .inl (.residue true))) i
+ | .persistent => .inr .zeroWord
+ | i => .inl (.arithmetic i)
+
+private theorem arithmetic_injective : Function.Injective arithmeticPorts := by
+ change ∀ i j : ISA.Port 3 0, arithmeticPorts i = arithmeticPorts j → i = j
+ decide
+
+theorem subtract_runs {p w : ℕ} [NeZero p] (hw : SliceArithmetic.Word.workingWidth p ≤ w)
+ (io : Stacks External) (a b : Fin p)
+ (hp : io .prime = wordBits (Fin.ofNat (2^w) p)) (hz : io .zeroWord = wordBits (0 : BurstRAM.Word w)) :
+ let bits (x : Fin p) := wordBits (SliceArithmetic.Word.limb w x)
+ ∃ t ≤ 400 * (w+1)^2, (SliceArithmeticSubtract.machine.onPorts arithmeticPorts).Runs t
+ (frame io [] (fun sign => if sign then bits b else bits a))
+ (frame io [] (fun sign => if sign then bits (-b) else bits (a-b))) := by
+ intro bits
+ let d : BurstRAM.Word w := Fin.ofNat _ p
+ obtain ⟨t, ht, sub⟩ := SliceArithmeticSubtract.machine_runs hw d (Nat.mod_eq_of_lt (SliceArithmetic.Word.modulus_lt hw)) a b
+ refine ⟨t, ht, ?_⟩
+ apply FiniteRoutine.runs_onPorts_framed _ arithmetic_injective sub
+ · intro i
+ cases i with
+ | reg i => fin_cases i <;> first | rfl | exact hp
+ | persistent => exact hz
+ | pub i => exact i.elim0
+ | work => rfl
+ | logPort j => cases j <;> rfl
+ · intro i
+ cases i with
+ | reg i => fin_cases i <;> first | rfl | exact hp
+ | persistent => exact hz
+ | pub i => exact i.elim0
+ | work => rfl
+ | logPort j => cases j <;> rfl
+ rintro (i|i) hi
+ · cases i with
+ | residue sign => cases sign <;> first | exact (hi (.reg 1) rfl).elim | exact (hi (.reg 2) rfl).elim
+ | divide j => cases j <;> rfl
+ | _ => rfl
+ · rfl
+
+end SliceArithmeticSignedCount
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticEncoding.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticEncoding.lean
new file mode 100644
index 0000000000..88846d1d6e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticEncoding.lean
@@ -0,0 +1,127 @@
+import OAI.Computability.VPVNP.SliceArithmeticAdvice
+import OAI.Computability.VPVNP.SliceArithmeticRound
+import OAI.Computability.VPVNP.RAMTapeWordSlice
+
+/-!
+# Power-basis encodings at the evaluator interface
+
+Field values at the scalar-query boundary have canonical coefficient vectors.
+The packed input to the arithmetic routines consists of those same residues
+padded to the working register width. The first packed word computes the
+prime-field coordinate used by the accepting-branch routine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic
+
+open Polynomial SliceArithmeticRound BurstRAM
+
+variable {p e w : ℕ} [Fact p.Prime]
+
+/-- The quotient representation and canonical low-degree-first coefficient
+vectors form a bijection. -/
+noncomputable def valueEquiv (c : Vector p e) : Vector p e ≃ AdjoinRoot (modulus c) where
+ toFun := value (modulus c)
+ invFun z i := (ZMod.finEquiv p).symm
+ ((AdjoinRoot.powerBasisAux' (modulus_monic c)).repr z (i.cast (modulus_natDegree c).symm))
+ left_inv v := by
+ funext i
+ have h := congrArg (ZMod.finEquiv p).symm (repr_value (modulus_monic c) (modulus_natDegree c) v i)
+ rw [cast_val_eq_finEquiv, RingEquiv.symm_apply_apply] at h
+ exact h
+ right_inv z := by
+ let b := AdjoinRoot.powerBasisAux' (modulus_monic c)
+ let v (i : Fin e) := (ZMod.finEquiv p).symm (b.repr z (i.cast (modulus_natDegree c).symm))
+ apply b.repr.injective
+ ext j
+ obtain ⟨i, rfl⟩ := (finCongr (modulus_natDegree c).symm).surjective j
+ exact (repr_value (modulus_monic c) (modulus_natDegree c) v i).trans
+ ((cast_val_eq_finEquiv (v i)).trans ((ZMod.finEquiv p).apply_symm_apply _))
+
+/-- Encode a scalar computed by the matrix-entry oracle into the chosen
+polynomial basis of its actual ground field. -/
+noncomputable def scalarEncoding {K : Type*} [Field K] [Algebra (ZMod p) K]
+ {c : Vector p e} (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (x : K) : Vector p e :=
+ (valueEquiv c).symm (φ.symm x)
+
+@[simp] theorem map_scalarEncoding {K : Type*} [Field K] [Algebra (ZMod p) K]
+ {c : Vector p e} (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (x : K) :
+ φ (value (modulus c) (scalarEncoding φ x)) = x := by
+ change φ (valueEquiv c ((valueEquiv c).symm (φ.symm x))) = x
+ simp
+
+/-- Arithmetic on the query result and accumulator produces the canonical
+coefficient encoding of the product in the actual ground field. -/
+theorem mul_scalarEncoding {K : Type*} [Field K] [Algebra (ZMod p) K] {c : Vector p e}
+ (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (x y : K) :
+ mul c (scalarEncoding φ x) (scalarEncoding φ y) = scalarEncoding φ (x * y) := by
+ apply (φ.injective.comp (value_injective (modulus_monic c) (modulus_natDegree c)))
+ simp only [Function.comp_apply, value_mul, map_mul, map_scalarEncoding]
+
+/-- Widening a canonical limb for modular arithmetic appends high zero bits. -/
+theorem limb_padded (hw : Word.workingWidth p ≤ w) (a : Fin p) :
+ wordBits (Word.limb w a) =
+ wordBits (Word.limb (Nat.clog 2 p) a) ++ List.replicate (w - Nat.clog 2 p) false := by
+ apply TapeWord.eq_of_length_value
+ · simp only [length_wordBits, List.length_append, List.length_replicate]
+ unfold Word.workingWidth at hw
+ omega
+ · rw [TapeWord.value_append, TapeWord.value_zeros, mul_zero, add_zero, TapeWord.value_wordBits,
+ TapeWord.value_wordBits, Word.limb_val hw]
+ exact (Nat.mod_eq_of_lt (a.isLt.trans_le (Nat.le_pow_clog (by decide) _))).symm
+
+omit [Fact p.Prime] in
+/-- The compact binary advice for a coefficient vector is exactly its packed
+stream at the minimum coefficient width. -/
+theorem packed_advice (v : Vector p e) :
+ packed (Nat.clog 2 p) (List.ofFn v) = List.ofFn (encode v) := by
+ let W := Nat.clog 2 p
+ let limbs (i : Fin e) : BurstRAM.Word W := Word.limb W (v i)
+ have h : RAMSerialization.arrayBits e W limbs = encode v := by
+ apply congrArg (RAMSerialization.arrayBits e W)
+ funext i
+ exact Fin.ext (Nat.mod_eq_of_lt ((v i).isLt.trans_le (Nat.le_pow_clog (by decide) _)))
+ rw [← h]
+ have ha := List.ofFn_mul (RAMSerialization.arrayBits e W limbs)
+ have hb : List.ofFn (RAMSerialization.arrayBits e W limbs) =
+ (List.ofFn fun i : Fin e => List.ofFn fun j : Fin W =>
+ RAMSerialization.arrayBits e W limbs (finProdFinEquiv (i, j))).flatten := by
+ simpa only [finProdFinEquiv, Equiv.coe_fn_mk, Nat.mul_comm W, Nat.add_comm] using ha
+ rw [hb]
+ simp only [RAMSerialization.arrayBits_at, packed, List.flatMap_def, List.map_ofFn, Function.comp_def,
+ wordBits, limbs, W]
+
+omit [Fact p.Prime] in
+/-- The first complete word of a nonempty packed product is the low limb.
+The terminal callback may carry arbitrary additional bits after the product. -/
+theorem packed_low_limb {d : ℕ} (v : Vector p (d + 1)) (tail : List Bool) :
+ packed w (List.ofFn v) ++ tail =
+ wordBits (Word.limb w (v 0)) ++ (packed w (List.ofFn fun i : Fin d => v i.succ) ++ tail) := by
+ rw [List.ofFn_succ]
+ simp [packed]
+
+/-- On the selected advice, reading the first word of the accumulator gives
+the representative in `[0,p)` of its evaluator output. -/
+theorem packed_primeCoordinate {d : ℕ} {K : Type*} [Field K] [Fintype K] [Algebra (ZMod p) K]
+ {c : Vector p (d + 1)} (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K)
+ (hc : ∀ v, SliceEvaluator.primeCoordinate p K (φ (value (modulus c) v)) =
+ ((v (0 : Fin (d + 1))).val : ZMod p))
+ (hw : Word.workingWidth p ≤ w) (x : K) :
+ ∃ low : BurstRAM.Word w, ∃ tail : List Bool,
+ packed w (List.ofFn (scalarEncoding φ x)) = wordBits low ++ tail ∧
+ low.val = (SliceEvaluator.primeCoordinate p K x).val := by
+ let v := scalarEncoding φ x
+ refine ⟨Word.limb w (v 0), packed w (List.ofFn fun i : Fin d => v i.succ), ?_, ?_⟩
+ · simpa only [List.append_nil] using packed_low_limb (w := w) v []
+ · have h := hc v
+ rw [map_scalarEncoding] at h
+ rw [Word.limb_val hw, h, ZMod.val_natCast_of_lt (v 0).isLt]
+
+end SliceArithmetic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticHornerMachine.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticHornerMachine.lean
new file mode 100644
index 0000000000..48d8897b5d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticHornerMachine.lean
@@ -0,0 +1,186 @@
+import OAI.Computability.VPVNP.SliceArithmeticHornerPrepare
+import OAI.Computability.VPVNP.SliceArithmeticRound
+
+/-!
+# Uniform bit-stack multiplication in the advised polynomial basis
+
+One finite instruction table reads a stack of Horner digits, runs a complete
+coefficient scan for each digit and installs the resulting accumulator. Its
+control is independent of the prime, extension degree and register width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.HornerControl
+
+open RAMTape BurstRAM SliceArithmeticStreamRow
+open SliceArithmeticRound (packed registers packed_length)
+
+variable {p e w : ℕ} [NeZero p]
+
+private abbrev RowAcc := SliceArithmeticRound.Acc
+
+/-- A digit body stages its input, runs the coefficient scan and restores the accumulator. -/
+def digitRoutine : FiniteRoutine Ports :=
+ (prepare.followedBy (SliceArithmeticRound.scan Extra.rows)).followedBy restore
+
+/-- Consume one round marker per Horner digit and execute a complete coefficient scan for each
+digit. -/
+def machine : FiniteRoutine Ports := FiniteRoutine.repeatMarked (.inr (.outer .rounds)) digitRoutine
+
+/-- Cost of the preparation, inner scan and output reversal. -/
+def digitCap (e w : ℕ) : ℕ :=
+ 5 * (e*w + e*w + e) + 13*w + 11 + 200*(w+1)^2 +
+ (e*(800*(w+1)^2 + 22*w + 10) + 1) + (2*(e*w) + 1)
+
+private structure Logical (p e : ℕ) where
+ vector : Vector p e
+ lastDigit : Fin p
+ reduction : Fin p
+ row : RowAcc p
+
+private def top (v : Vector p e) := (List.ofFn v).getLastD 0
+
+private def rowState (s : Logical p e) : RowAcc p := {s.row with result := top s.vector, output := []}
+
+private def regState (w : ℕ) (s : Logical p e) :=
+ registers w s.lastDigit s.reduction (rowState s)
+
+private def resetRow (s : Logical p e) : RowAcc p := {rowState s with previous := 0}
+
+private def items (c b v : Vector p e) :=
+ List.ofFn (fun i => SliceArithmeticRound.Item.mk (v i) (c i) (b i))
+
+private def advance (c b : Vector p e) (s : Logical p e) (digit : Fin p) : Logical p e :=
+ let red := -top s.vector
+ let result := (items c b s.vector).foldl (SliceArithmeticRound.next digit red) (resetRow s)
+ ⟨add (companion c s.vector) (scale digit b), digit, red, result⟩
+
+private def frame (w : ℕ) (c b : Vector p e) (digits : List (Fin p)) (s : Logical p e) : Stacks Ports :=
+ state (regState w s) (streams (packed w (List.ofFn s.vector)) [] [] []
+ (extra (packed w (List.ofFn c)) (packed w (List.ofFn b)) e (packed w digits) digits.length 0))
+
+private theorem digit_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c b : Vector p e) (s : Logical p e) (digit : Fin p) (xs : List (Fin p)) :
+ ∃ t ≤ digitCap e w, digitRoutine.Runs t
+ (Function.update (frame w c b (digit :: xs) s) (.inr (.outer .rounds)) (List.replicate xs.length true))
+ (frame w c b xs (advance c b s digit)) := by
+ let cb := packed w (List.ofFn c)
+ let bb := packed w (List.ofFn b)
+ let vb := packed w (List.ofFn s.vector)
+ let tail := packed w xs
+ let r := regState w s
+ let caller := extra cb bb e tail xs.length 0
+ let base := streams [] [] [] [] caller
+ let a := resetRow s
+ let red := -top s.vector
+ let rows := items c b s.vector
+ let nextRow := rows.foldl (SliceArithmeticRound.next digit red) a
+ let v' := add (companion c s.vector) (scale digit b)
+ let out := packed w (List.ofFn v')
+ obtain ⟨k, hk, prep⟩ := prepare_runs hw r digit (top s.vector) (Nat.mod_eq_of_lt (Word.modulus_lt hw))
+ (Word.limb_val hw _) cb bb vb tail e xs.length
+ have entryEq : Function.update (frame w c b (digit :: xs) s) (.inr (.outer .rounds))
+ (List.replicate xs.length true) =
+ state r (streams vb [] [] [] (extra cb bb e (wordBits (Word.limb w digit) ++ tail) xs.length 0)) := by
+ rw [frame, updateStream]
+ congr 1
+ funext i
+ cases i with
+ | outer x => cases x <;> simp [streams, extra, packed, cb, bb, tail]
+ | _ => rfl
+ have rprep : prepared r digit (top s.vector) = registers w digit red a := by
+ funext i
+ fin_cases i <;> simp [prepared, r, regState, registers, a, resetRow, rowState, red, Word.limb]
+ obtain ⟨m, hm, scanRun⟩ := SliceArithmeticRound.scan_runs hw Extra.rows base digit red rows a
+ have hinput : SliceArithmeticRound.streams w Extra.rows base rows a =
+ streams vb cb bb [] (extra cb bb e tail xs.length e) := by
+ funext i
+ cases i with
+ | outer x => cases x <;> simp [SliceArithmeticRound.streams, streams, base, caller, extra, rows, items]
+ | _ => simp [SliceArithmeticRound.streams, rows, items, List.map_ofFn, Function.comp_def,
+ streams, base, vb, cb, bb, a, resetRow, rowState, packed]
+ have hout : nextRow.output = (List.ofFn v').reverse := by
+ simpa [nextRow, rows, items, red, top, v', a, resetRow, rowState] using
+ SliceArithmeticRound.fold_vector_output c b s.vector digit a rfl
+ have houtput : SliceArithmeticRound.streams w Extra.rows base [] nextRow =
+ streams [] [] [] out.reverse caller := by
+ funext i
+ cases i with
+ | outer x => cases x <;> simp [SliceArithmeticRound.streams, streams, base, caller, extra]
+ | out => simp [SliceArithmeticRound.streams, streams, hout, out, base]
+ | _ => rfl
+ have hrows : rows ≠ [] := by
+ intro h
+ have := congrArg List.length h
+ simp [rows, items] at this
+ omega
+ have hhead := SliceArithmeticRound.fold_result_of_nonempty digit red rows a hrows
+ change nextRow.output.head? = some nextRow.result at hhead
+ rw [hout, List.head?_reverse] at hhead
+ have htop : top v' = nextRow.result := by rw [top, List.getLastD_eq_getLast?, hhead]; rfl
+ have houtReg : regState w (advance c b s digit) = registers w digit red nextRow := by
+ change registers w digit red {nextRow with result := top v', output := []} = _
+ rw [htop]
+ rfl
+ change (SliceArithmeticRound.scan Extra.rows).Runs m
+ (state (registers w digit red a) (SliceArithmeticRound.streams w Extra.rows base rows a))
+ (state (registers w digit red nextRow) (SliceArithmeticRound.streams w Extra.rows base [] nextRow)) at scanRun
+ rw [hinput, houtput, ← rprep, ← houtReg] at scanRun
+ have restored := restore_runs (registers w digit red nextRow) out caller
+ rw [← houtReg] at restored
+ have full := (prep.followedBy scanRun).followedBy restored
+ rw [entryEq]
+ refine ⟨_, ?_, full⟩
+ simp only [cb, bb, out, packed_length, List.length_ofFn] at hk ⊢
+ simp only [rows, items, List.length_ofFn] at hm
+ unfold digitCap
+ omega
+
+/-- The register bank at entry holds the prime modulus and zero coefficients. -/
+def initialRegisters (p w : ℕ) [NeZero p] : Fin 8 → BurstRAM.Word w :=
+ registers w (0 : Fin p) 0 ⟨0, 0, 0, 0, 0, []⟩
+
+/-- A single fixed finite control multiplies arbitrary coefficient vectors
+of positive degree. It consumes all digits and stores the quotient-ring
+product as low-degree-first, little-endian words in the accumulator port. -/
+theorem machine_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w) (c a b : Vector p e) :
+ ∃ t ≤ e * (digitCap e w + 1) + 1, ∃ reg : Fin 8 → BurstRAM.Word w,
+ machine.Runs t
+ (state (initialRegisters p w) (streams (packed w (List.ofFn (zero p e))) [] [] []
+ (extra (packed w (List.ofFn c)) (packed w (List.ofFn b)) e (packed w (List.ofFn a).reverse) e 0)))
+ (state reg (streams (packed w (List.ofFn (mul c a b))) [] [] []
+ (extra (packed w (List.ofFn c)) (packed w (List.ofFn b)) e [] 0 0))) := by
+ let initial : Logical p e := ⟨zero p e, 0, 0, ⟨0,0,0,0,0,[]⟩⟩
+ let digits := (List.ofFn a).reverse
+ obtain ⟨t, ht, hrun⟩ := FiniteRoutine.repeatMarked_runs (.inr (.outer .rounds)) digitRoutine (frame w c b)
+ (advance c b) (digitCap e w) (fun _ _ => rfl) (fun digit xs s => digit_runs he hw c b s digit xs)
+ digits initial
+ have hfold (xs : List (Fin p)) (s : Logical p e) :
+ (xs.foldl (advance c b) s).vector =
+ xs.foldl (fun v digit => add (companion c v) (scale digit b)) s.vector := by
+ induction xs generalizing s with
+ | nil => rfl
+ | cons x xs ih => exact ih (advance c b s x)
+ have hout : (digits.foldl (advance c b) initial).vector = mul c a b := by
+ rw [hfold]
+ dsimp only [digits]
+ rw [List.foldl_reverse]
+ rfl
+ have hz : top (zero p e) = 0 := by
+ cases e with
+ | zero => simp [top]
+ | succ k => rw [top, List.ofFn_succ']; simp [zero]
+ have hr₀ : regState w initial = initialRegisters p w := by
+ simp only [regState, initial, rowState, hz]
+ rfl
+ simp only [frame, hr₀, hout, digits, List.length_reverse, List.length_ofFn] at hrun ht
+ exact ⟨t, ht, _, hrun⟩
+
+end SliceArithmetic.HornerControl
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticHornerPrepare.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticHornerPrepare.lean
new file mode 100644
index 0000000000..c44f43b114
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticHornerPrepare.lean
@@ -0,0 +1,155 @@
+import OAI.Computability.VPVNP.SliceArithmeticStreamBank
+import OAI.Computability.VPVNP.SliceArithmeticStreamStage
+import OAI.Computability.VPVNP.SliceArithmeticStreamWord
+
+/-!
+# Preparing the bit stacks for a Horner digit
+
+Each digit reuses the stored modulus and multiplier. The machine restores the
+row count, loads the next high-degree-first digit, clears the predecessor and
+negates the accumulator's top coefficient left in register six by the last
+round. A single whole-stack reversal installs the output for the next round.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.HornerControl
+
+open RAMTape BurstRAM SliceArithmeticStreamRow
+
+/-- Ports holding the saved modulus coefficients, multiplier and row count, together with the
+live row, digit, and round streams. -/
+inductive Extra where
+ | savedCoeff | savedFactor | savedCount | rows | digits | rounds
+ deriving DecidableEq
+
+instance : Fintype Extra :=
+ ⟨{.savedCoeff, .savedFactor, .savedCount, .rows, .digits, .rounds}, by intro x; cases x <;> simp⟩
+
+/-- Register and stream ports of the complete Horner multiplication controller. -/
+abbrev Ports := Port Extra
+
+/-- State of the saved polynomial and multiplier streams, unary row counts, pending digit bits,
+and remaining rounds. -/
+def extra (c b : List Bool) (e : ℕ) (digits : List Bool) (left rows : ℕ) : Stacks Extra
+ | .savedCoeff => c
+ | .savedFactor => b
+ | .savedCount => List.replicate e true
+ | .rows => List.replicate rows true
+ | .digits => digits
+ | .rounds => List.replicate left true
+
+/-- Install the old accumulator, reduction coefficients, multiplier coefficients, and output
+bits alongside the caller's streams. -/
+def streams (old coeff factor out : List Bool) (caller : Stacks Extra) : Stacks (StreamPort Extra)
+ | .old => old
+ | .coeff => coeff
+ | .factor => factor
+ | .out => out
+ | .scratch => []
+ | .outer x => caller x
+
+private def supplyPort : StreamStage.Port → Ports
+ | .coefficient => .inr (.outer .savedCoeff)
+ | .factor => .inr (.outer .savedFactor)
+ | .count => .inr (.outer .savedCount)
+ | .coefficientInput => .inr .coeff
+ | .factorInput => .inr .factor
+ | .countInput => .inr (.outer .rows)
+ | .scratch => .inr .scratch
+
+private theorem supplyPort_injective : Function.Injective supplyPort := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [supplyPort]
+
+private def supply : FiniteRoutine Ports := StreamStage.stage.onPorts supplyPort
+
+private theorem supply_runs {w : ℕ} (reg : Fin 8 → BurstRAM.Word w)
+ (c b old digits : List Bool) (e left : ℕ) :
+ supply.Runs (5 * (c.length + b.length + e) + 6)
+ (state reg (streams old [] [] [] (extra c b e digits left 0)))
+ (state reg (streams old c b [] (extra c b e digits left e))) := by
+ have run := StreamStage.stage_runs c b (List.replicate e true)
+ rw [List.length_replicate] at run
+ apply StreamStage.stage.runs_onPorts_framed supplyPort_injective run
+ · intro k; cases k <;> rfl
+ · intro k; cases k <;> rfl
+ · rintro (k | k) h
+ · rfl
+ · cases k with
+ | old | out | scratch => rfl
+ | coeff => exact (h .coefficientInput rfl).elim
+ | factor => exact (h .factorInput rfl).elim
+ | outer x =>
+ cases x with
+ | savedCoeff | savedFactor | savedCount | digits | rounds => rfl
+ | rows => exact (h .countInput rfl).elim
+
+/-- Stage the row inputs, load the next Horner digit, clear the predecessor, and negate the top
+accumulator limb for reduction. -/
+def prepare : FiniteRoutine Ports :=
+ ((supply.followedBy (StreamWord.load (.inr (.outer .digits)) (.inl (.reg 4)) (.inr .scratch))).followedBy
+ ((ISA.loadLiteral 0 1).onPorts Sum.inl)).followedBy
+ ((Word.routine .neg 2 6 6 0).onPorts Sum.inl)
+
+/-- The register changes at the start of a Horner round. -/
+def prepared {p w : ℕ} (reg : Fin 8 → BurstRAM.Word w) (digit top : Fin p) :
+ Fin 8 → BurstRAM.Word w :=
+ Function.update (Function.update (Function.update reg 4 (Word.limb w digit)) 1 0) 2 (Word.limb w (-top))
+
+theorem prepare_runs {p w : ℕ} [NeZero p] (hw : Word.workingWidth p ≤ w)
+ (reg : Fin 8 → BurstRAM.Word w) (digit top : Fin p)
+ (hp : (reg 0).val = p) (ht : (reg 6).val = top.val)
+ (c b old tail : List Bool) (e left : ℕ) :
+ ∃ t ≤ 5 * (c.length + b.length + e) + 13 * w + 11 + 200 * (w + 1)^2,
+ prepare.Runs t
+ (state reg (streams old [] [] []
+ (extra c b e (wordBits (Word.limb w digit) ++ tail) left 0)))
+ (state (prepared reg digit top) (streams old c b [] (extra c b e tail left e))) := by
+ let x := Word.limb w digit
+ let input := streams old c b [] (extra c b e (wordBits x ++ tail) left e)
+ let target := streams old c b [] (extra c b e tail left e)
+ let r₁ := Function.update reg 4 x
+ let r₂ := Function.update r₁ 1 (0 : BurstRAM.Word w)
+ have hs := supply_runs reg c b old (wordBits x ++ tail) e left
+ have hload := StreamWord.load_runs (stream := (.inr (.outer .digits) : Ports))
+ (reg := .inl (.reg 4)) (scratch := .inr .scratch) (by decide) (by decide) (by decide)
+ (state reg input) x tail (length_wordBits _) rfl rfl
+ have tailEq : Function.update input (.outer .digits) tail = target := by
+ funext i
+ cases i with
+ | outer y => cases y <;> simp [input, target, streams, extra, Function.update]
+ | _ => rfl
+ rw [updateStream, tailEq, updateReg] at hload
+ have hclear := bankRun (ISA.loadLiteral 0 1) target (ISA.loadLiteral_run 0 1 Fin.elim0 0 r₁ [])
+ obtain ⟨t, hticks, hneg⟩ := Word.routine_runs hw .neg 2 6 6 0 (by decide) Fin.elim0 0 r₂ []
+ top top (by simpa [r₂, r₁] using ht) (by simpa [r₂, r₁] using ht) (by simpa [r₂, r₁] using hp)
+ have hlast := bankRun (Word.routine .neg 2 6 6 0) target hneg
+ exact ⟨_, by omega, ((hs.followedBy hload).followedBy hclear).followedBy hlast⟩
+
+/-- Replace the consumed accumulator by the coefficient scan's bit-reversed output. -/
+def restore : FiniteRoutine Ports :=
+ EvaluatorRadixDivision.reverseOnto (.inr .out) (.inr .old)
+
+theorem restore_runs {w : ℕ} (reg : Fin 8 → BurstRAM.Word w) (bits : List Bool)
+ (caller : Stacks Extra) :
+ restore.Runs (2 * bits.length + 1)
+ (state reg (streams [] [] [] bits.reverse caller))
+ (state reg (streams bits [] [] [] caller)) := by
+ rw [← List.length_reverse (as := bits)]
+ apply EvaluatorRadixDivision.reverseOnto_runs (src := (.inr .out : Ports)) (dst := .inr .old)
+ (by decide) (state reg (streams [] [] [] bits.reverse caller))
+ (state reg (streams bits [] [] [] caller)) rfl
+ · change bits = bits.reverse.reverse ++ []
+ simp
+ · rintro (k | k) h₁ h₂
+ · rfl
+ · cases k <;> first | rfl | contradiction
+
+end SliceArithmetic.HornerControl
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticInverseCall.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticInverseCall.lean
new file mode 100644
index 0000000000..4697e6d59a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticInverseCall.lean
@@ -0,0 +1,98 @@
+import OAI.Computability.VPVNP.SliceArithmeticPowerMachine
+import OAI.Computability.VPVNP.SliceArithmeticInverseInit
+
+/-!
+# A fixed bit-stack routine for inversion in the advised field
+
+The saved exponent is the binary expansion of `p^e-2`, independent of the
+coordinate query. Zero starts with a zero accumulator, while a nonzero input
+starts with one. The same powering loop then handles every field size,
+including the empty exponent when the field has two elements.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.InverseCall
+
+open RAMTape
+open SliceArithmeticRound (packed)
+
+/-- Initialize the base and accumulator from the packed input, then run binary powering with
+the saved inverse exponent. -/
+def machine : FiniteRoutine Port := initializeInput.followedBy powerMachine
+
+/-- Bound on inversion steps for degree `e`, limb width `w`, and `z` stored exponent bits,
+including initialization. -/
+def wordCap (e w z : ℕ) : ℕ := (5*z+11*(e*w)+9) + (z*(bitCap e w+1)+1)
+
+/-- The canonical Fermat exponent fits in the total working width of the limbs. -/
+def callCap (e w : ℕ) := wordCap e w (e*w)
+
+theorem machine_word_runs {p e w : ℕ} [Fact p.Prime] (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c x : Vector p e) (bits : List Bool) (hv : TapeWord.value bits.reverse = p^e-2) :
+ let cb := packed w (List.ofFn c)
+ let xb := packed w (List.ofFn x)
+ ∃ t ≤ wordCap e w bits.length, machine.Runs t
+ (frame p e w cb xb bits [] [] [])
+ (frame p e w cb xb bits [] (packed w (List.ofFn (inverse c x))) []) := by
+ intro cb xb
+ obtain ⟨a, ha, init⟩ := initialize_runs he hw c x bits
+ by_cases hz : x = zero p e
+ · subst x
+ obtain ⟨b, hb, power⟩ := power_zero_runs he hw c bits bits
+ rw [ite_eq_left rfl] at init
+ simp only [inverse]
+ exact ⟨_, by unfold wordCap; omega, init.followedBy power⟩
+ · obtain ⟨b, hb, power⟩ := power_word_runs he hw c x bits bits
+ rw [hv] at power
+ rw [ite_eq_right hz] at init
+ simp only [inverse, ite_eq_right hz]
+ exact ⟨_, by unfold wordCap; omega, init.followedBy power⟩
+
+private theorem bits_value (n : ℕ) : TapeWord.value n.bits = n := by
+ induction n using Nat.binaryRec' with
+ | zero => rfl
+ | bit b n h ih =>
+ rw [Nat.bits_append_bit n b h, TapeWord.value, ih]
+ cases b <;> simp [Nat.bit]
+ omega
+
+/-- The input base and exponent advice are retained and the inversion result
+is available in the multiplier's accumulator. -/
+theorem machine_runs {p e w : ℕ} [Fact p.Prime] (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c x : Vector p e) :
+ let cb := packed w (List.ofFn c)
+ let xb := packed w (List.ofFn x)
+ let bits := (p^e-2).bits.reverse
+ ∃ t ≤ callCap e w, machine.Runs t
+ (frame p e w cb xb bits [] [] [])
+ (frame p e w cb xb bits [] (packed w (List.ofFn (inverse c x))) []) := by
+ intro cb xb bits
+ have hv : TapeWord.value bits.reverse = p^e-2 := by simp [bits, bits_value]
+ obtain ⟨n, hn, run⟩ := machine_word_runs he hw c x bits hv
+ refine ⟨n, hn.trans ?_, run⟩
+ have hlen : bits.length ≤ e*w := by
+ rw [show bits.length = (p^e-2).size by simp [bits, Nat.size_eq_bits_len]]
+ apply Nat.size_le.mpr
+ calc
+ p ^ e - 2 < p ^ e := by have := Nat.pow_pos (Fact.out : p.Prime).pos (n := e); omega
+ _ ≤ (2 ^ w) ^ e := Nat.pow_le_pow_left (Word.modulus_lt hw).le _
+ _ = 2 ^ (e*w) := by rw [← pow_mul, Nat.mul_comm]
+ unfold callCap wordCap
+ exact Nat.add_le_add (by omega) (Nat.add_le_add_right (Nat.mul_le_mul_right _ hlen) _)
+
+/-- A polynomial clock uniform in both input dimensions. -/
+theorem callCap_le (e w : ℕ) : callCap e w ≤ 5000*(e+1)^3*(w+1)^3 := by
+ have h := MultiplyCall.callCap_le e w
+ unfold callCap wordCap bitCap
+ calc
+ _ ≤ (5*(e*w)+11*(e*w)+9) + ((e*w)*(2*(5*(e*w)+2+2000*(e+1)^2*(w+1)^2)+1)+1) := by gcongr
+ _ ≤ _ := by ring_nf; omega
+
+end SliceArithmetic.InverseCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticInverseInit.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticInverseInit.lean
new file mode 100644
index 0000000000..1dd571d2e1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticInverseInit.lean
@@ -0,0 +1,138 @@
+import OAI.Computability.VPVNP.SliceArithmeticPowerPorts
+import OAI.Computability.VPVNP.SliceArithmeticConstant
+import OAI.Computability.VPVNP.SliceArithmeticZero
+
+/-!
+# Initializing inversion on packed field-element stacks
+
+The controller copies the exponent advice to a consumable stack, scans the
+input for zero and installs the appropriate packed constant in the multiplier's
+accumulator. Starting at zero for zero input handles the field of order two,
+whose Fermat exponent is zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.InverseCall
+
+open RAMTape TapeWord
+open SliceArithmeticRound (packed)
+
+private def zeroPorts : SliceArithmeticZero.Port → Port
+ | .input => .inr .base
+ | .flag => .inr .flag
+ | .scratch => .inr .scratch
+
+private def literalPorts : ScanPort → Port
+ | .left => .inl (.inr .coeff)
+ | .right => .inr .temp
+ | .tmp => .inr .scratch
+ | .out => .inl (.inr .acc)
+
+private def copyExponent : FiniteRoutine Port :=
+ SuccessorFields.prependCopy (.inr .exponent) (.inr .bits) (.inr .scratch)
+
+private def testZero : FiniteRoutine Port := SliceArithmeticZero.machine.onPorts zeroPorts
+
+private def putLiteral (b : Bool) : FiniteRoutine Port :=
+ (SliceArithmeticConstant.machine b).onPorts literalPorts
+
+private def chooseLiteral : FiniteRoutine Port :=
+ .ofRoutine (Routine.popCase (.inr .flag) (Routine.halt false) (putLiteral true).body (putLiteral false).body)
+
+/-- Fixed stack instructions for installing the exponent scan and initial accumulator. -/
+def initializeInput : FiniteRoutine Port := (copyExponent.followedBy testZero).followedBy chooseLiteral
+
+private theorem copyExponent_runs (p e w : ℕ) (cb base exponent : List Bool) :
+ copyExponent.Runs (5 * exponent.length + 2) (frame p e w cb base exponent [] [] [])
+ (frame p e w cb base exponent exponent [] []) := by
+ let s := frame p e w cb base exponent [] [] []
+ have hr := SuccessorFields.prependCopy_runs (.inr Extra.exponent : Port) (.inr Extra.bits)
+ (.inr Extra.scratch) (by decide) (by decide) (by decide) s rfl
+ have hu : Function.update s (.inr .bits) (s (.inr .exponent) ++ s (.inr .bits)) =
+ frame p e w cb base exponent exponent [] [] := by
+ funext i
+ rcases i with i|i
+ · rfl
+ · cases i <;> simp [s, frame, Function.update]
+ exact hu ▸ hr
+
+variable {p e w : ℕ} [Fact p.Prime]
+
+private theorem testZero_runs (hw : Word.workingWidth p ≤ w) (c a : Vector p e) (exp : List Bool) :
+ let cb := packed w (List.ofFn c)
+ let ab := packed w (List.ofFn a)
+ testZero.Runs (4 * (e*w) + 3) (frame p e w cb ab exp exp [] [])
+ (frame p e w cb ab exp exp [] [decide (a = zero p e)]) := by
+ intro cb ab
+ apply SliceArithmeticZero.machine.runs_onPorts_framed (ports := zeroPorts)
+ (by intro i j h; cases i <;> cases j <;> simp_all [zeroPorts]) (SliceArithmeticZero.vector_runs hw a [])
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> rfl
+ · rintro (i|i) hi
+ · rfl
+ · cases i <;> first | rfl | exact (hi .flag rfl).elim
+
+private theorem putLiteral_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w) (c : Vector p e)
+ (base exp : List Bool) (b : Bool) :
+ let cb := packed w (List.ofFn c)
+ (putLiteral b).Runs (7 * (e*w) + 3) (frame p e w cb base exp exp [] [])
+ (frame p e w cb base exp exp (packed w (List.ofFn (SliceArithmeticConstant.literal b p e))) []) := by
+ intro cb
+ have run := SliceArithmeticConstant.machine_runs he hw b c []
+ simp only [List.length_nil, Nat.zero_add] at run
+ apply (SliceArithmeticConstant.machine b).runs_onPorts_framed (ports := literalPorts)
+ (by intro i j h; cases i <;> cases j <;> simp_all [literalPorts])
+ run
+ · intro i; cases i <;> rfl
+ · intro i; cases i <;> rfl
+ · rintro ((i|i)|i) hi
+ · rfl
+ · cases i <;> first | rfl | exact (hi .out rfl).elim
+ · rfl
+
+private theorem chooseLiteral_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c a : Vector p e) (exp : List Bool) :
+ let cb := packed w (List.ofFn c)
+ let ab := packed w (List.ofFn a)
+ chooseLiteral.Runs (7*(e*w)+3+1) (frame p e w cb ab exp exp [] [decide (a = zero p e)])
+ (frame p e w cb ab exp exp (packed w (List.ofFn (if a = zero p e then zero p e else one p e))) []) := by
+ intro cb ab
+ have hup (flag : Bool) : Function.update (frame p e w cb ab exp exp [] [flag]) (.inr .flag) [] =
+ frame p e w cb ab exp exp [] [] := by
+ funext i
+ rcases i with i|i
+ · rfl
+ · cases i <;> rfl
+ by_cases h : a = zero p e
+ · rw [ite_eq_left h, decide_eq_true h]
+ apply Routine.runs_popCase_true (.inr Extra.flag : Port) (Routine.halt false) (putLiteral true).body
+ (putLiteral false).body (s := frame p e w cb ab exp exp [] [true]) (tail := []) rfl
+ rw [hup]
+ exact putLiteral_runs he hw c ab exp false
+ · rw [ite_eq_right h, decide_eq_false h]
+ apply Routine.runs_popCase_false (.inr Extra.flag : Port) (Routine.halt false) (putLiteral true).body
+ (putLiteral false).body (s := frame p e w cb ab exp exp [] [false]) (tail := []) rfl
+ rw [hup]
+ exact putLiteral_runs he hw c ab exp true
+
+/-- The saved exponent and base are preserved, the working bits are installed,
+and the flag and temporary stacks are empty upon return. -/
+theorem initialize_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c a : Vector p e) (exponent : List Bool) :
+ let cb := packed w (List.ofFn c)
+ let ab := packed w (List.ofFn a)
+ ∃ t ≤ 5 * exponent.length + 11 * (e*w) + 9, initializeInput.Runs t
+ (frame p e w cb ab exponent [] [] [])
+ (frame p e w cb ab exponent exponent (packed w (List.ofFn (if a = zero p e then zero p e else one p e))) []) := by
+ intro cb ab
+ exact ⟨_, by omega, ((copyExponent_runs p e w cb ab exponent).followedBy
+ (testZero_runs hw c a exponent)).followedBy (chooseLiteral_runs he hw c a exponent)⟩
+
+end SliceArithmetic.InverseCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticLoop.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticLoop.lean
new file mode 100644
index 0000000000..f547550342
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticLoop.lean
@@ -0,0 +1,53 @@
+import OAI.Computability.VPVNP.RAMTapeISAPorts
+import OAI.Computability.VPVNP.StructuredStackLoop
+
+/-!
+# A finite-control counted scan of a coefficient stream
+
+The register bank holds a stack of one-bit markers. Each marker causes one
+normal execution of the same body. The body can update the accumulator and
+advance all coefficient streams. The empty marker stack returns to the caller.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.FiniteRoutine
+
+variable {K : Type}
+
+/-- Execute the body on each true marker, stopping normally on an empty stack. -/
+def repeatMarked (marker : K) (body : FiniteRoutine K) : FiniteRoutine K :=
+ ofRoutine (Routine.popLoop marker (fun _ => true) (Routine.halt false) body.body)
+
+/-- A fold over a represented stream uses at most one bounded body run and
+one marker pop per item, plus the final test for the empty marker stack. -/
+theorem repeatMarked_runs [DecidableEq K] {α β : Type*} (marker : K)
+ (body : FiniteRoutine K) (frame : List α → β → Stacks K)
+ (step : β → α → β) (cap : ℕ)
+ (hmarks : ∀ xs b, frame xs b marker = List.replicate xs.length true)
+ (hstep : ∀ a xs b, ∃ t ≤ cap, body.Runs t
+ (Function.update (frame (a :: xs) b) marker (List.replicate xs.length true))
+ (frame xs (step b a)))
+ (xs : List α) (b : β) :
+ ∃ t ≤ xs.length * (cap + 1) + 1, (repeatMarked marker body).Runs t
+ (frame xs b) (frame [] (xs.foldl step b)) := by
+ induction xs generalizing b with
+ | nil =>
+ refine ⟨1, by simp, ?_⟩
+ exact Routine.Runs.popLoop_empty marker (fun _ => true) (Routine.halt false) body.body (s := frame [] b) (hmarks [] b)
+ | cons a xs ih =>
+ obtain ⟨u, hu, hbody⟩ := hstep a xs b
+ obtain ⟨v, hv, htail⟩ := ih (step b a)
+ refine ⟨1 + u + v, ?_, ?_⟩
+ · simp only [List.length_cons, Nat.succ_mul]
+ omega
+ · exact Routine.Runs.popLoop_true_continue marker (fun _ => true) (Routine.halt false) body.body
+ (by rw [hmarks, List.length_cons, List.replicate_succ]) rfl hbody htail
+
+end RAMTape.FiniteRoutine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticMagnitude.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticMagnitude.lean
new file mode 100644
index 0000000000..4dd86f32fd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticMagnitude.lean
@@ -0,0 +1,69 @@
+import OAI.Computability.VPVNP.EvaluatorRadixDivision
+import OAI.Computability.VPVNP.SliceArithmeticCallClear
+
+/-!
+# Reducing an arbitrary-width count to one residue limb
+
+A positive working-width divisor and a little-endian count may have different
+lengths. The bit division routine computes the remainder at the divisor width.
+Its unused quotient is erased before the residue returns.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticMagnitude
+
+open BurstRAM RAMTape TapeWord DivisionStack
+
+private def divide : FiniteRoutine Port := .ofStackCode code id .reverseInput (· == .done)
+
+/-- Divide a little-endian count by the advised modulus and discard the quotient, leaving the
+remainder. -/
+def machine : FiniteRoutine Port := divide.followedBy (SliceArithmetic.CallClear.clear .quotient)
+
+/-- Division stack state holding the count, divisor, and remainder stream with the other work
+stacks empty. -/
+def frame (input divisor residue : List Bool) : Stacks Port :=
+ (⟨input, [], divisor, residue, [], [], [], []⟩ : Data).stacks
+
+/-- Number of steps to reduce an `n`-bit count modulo a positive `w`-bit divisor and erase the
+quotient. -/
+def cost (n w : ℕ) := 2 * n + 5 * w + 3 + (n * (10 * w + 4) + 1) + (n + 1)
+
+theorem machine_runs {w : ℕ} (x : List Bool) (d : Word w) (hd : 0 < d.val) :
+ machine.Runs (cost x.length w) (frame x (wordBits d) [])
+ (frame [] (wordBits d) (wordBits (Fin.ofNat (2^w) (value x % d.val)))) := by
+ let ds := wordBits d
+ let out := divideWords x ds
+ let mid := (⟨[], [], ds, out.2, out.1, [], [], []⟩ : Data).stacks
+ have hd' : 0 < value ds := by simpa only [ds, value_wordBits] using hd
+ obtain ⟨hq, hr, _, hv⟩ := EvaluatorRadixDivision.divide_spec x ds hd'
+ have hbits : out.2 = wordBits (Fin.ofNat (2^w) (value x % d.val)) := by
+ apply eq_of_length_value
+ · simpa only [ds, length_wordBits] using hr
+ · simpa only [ds, value_wordBits, Fin.val_ofNat, Nat.mod_eq_of_lt ((Nat.mod_lt _ hd).trans d.isLt)] using hv
+ have hdiv : divide.Runs (ticks x ds) (frame x ds []) mid := by
+ apply FiniteRoutine.runs_ofStackCode_framed (ports := id) Function.injective_id
+ (normal := (· == State.done)) (entry := State.reverseInput) (exit := State.done) rfl rfl
+ (fun q h => by
+ have : q = State.done := by simpa using h
+ subst q
+ rfl)
+ (divideRun x ds) (fun _ => rfl) (fun _ => rfl) (fun i hi => (hi i rfl).elim)
+ have hclear := SliceArithmetic.CallClear.clear_runs .quotient mid
+ have hfinal : Function.update mid .quotient [] = frame [] ds out.2 := by
+ funext i
+ cases i <;> rfl
+ rw [hfinal, hbits, show (mid .quotient).length = x.length from hq] at hclear
+ have hclock : cost x.length w = ticks x ds + (x.length + 1) := by
+ simp only [cost, ticks, (anyBit_iff ds).mpr hd', ↓reduceIte, ds, length_wordBits]
+ rw [hclock]
+ exact hdiv.followedBy hclear
+
+end SliceArithmeticMagnitude
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticMul.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticMul.lean
new file mode 100644
index 0000000000..938372f9bb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticMul.lean
@@ -0,0 +1,99 @@
+import OAI.Computability.VPVNP.SliceArithmetic
+
+/-!
+# Multiplication in the advised polynomial basis
+
+A companion operation multiplies by the adjoined root in the quotient by the
+advised monic polynomial. Horner's rule multiplies two coefficient vectors
+using exactly one round for each coefficient of the first input.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic
+
+open Polynomial
+
+variable {p e : ℕ} [NeZero p]
+
+/-- The companion operation shifts the coordinates up one degree and uses the
+advised monic relation to reduce the top coordinate. -/
+def companion {p : ℕ} [NeZero p] : {e : ℕ} → Vector p e → Vector p e → Vector p e
+ | 0, _, v => v
+ | d + 1, c, v =>
+ add (Fin.cons 0 (fun i : Fin d => v i.castSucc)) (scale (-v (Fin.last d)) c)
+
+omit [NeZero p] in
+theorem root_pow_modulus (c : Vector p e) :
+ AdjoinRoot.root (modulus c) ^ e = -value (modulus c) c := by
+ apply eq_neg_of_add_eq_zero_left
+ have h := AdjoinRoot.mk_self (f := modulus c)
+ change AdjoinRoot.mk (modulus c) (X ^ e + ∑ i, C ((c i).val : ZMod p) * X ^ i.val) = 0 at h
+ simpa [value, AdjoinRoot.algebraMap_eq] using h
+
+theorem value_companion (c v : Vector p e) :
+ value (modulus c) (companion c v) = AdjoinRoot.root (modulus c) * value (modulus c) v := by
+ cases e with
+ | zero => simp [value]
+ | succ d =>
+ let f := modulus c
+ let r := AdjoinRoot.root f
+ let A := algebraMap (ZMod p) (AdjoinRoot f)
+ have hshift :
+ value f (Fin.cons 0 (fun i : Fin d => v i.castSucc)) =
+ r * ∑ i : Fin d, A ((v i.castSucc).val : ZMod p) * r ^ i.val := by
+ rw [value, Fin.sum_univ_succ, Finset.mul_sum]
+ simp [Fin.cons, A, r, pow_succ, mul_assoc, mul_comm]
+ have hsplit : value f v =
+ (∑ i : Fin d, A ((v i.castSucc).val : ZMod p) * r ^ i.val) +
+ A ((v (Fin.last d)).val : ZMod p) * r ^ d :=
+ Fin.sum_univ_castSucc _
+ change value f (add _ _) = r * value f v
+ rw [value_add, value_scale, hshift, hsplit, cast_val_eq_finEquiv (-v _), map_neg,
+ ← cast_val_eq_finEquiv, map_neg, mul_add]
+ have hpow : r ^ (d + 1) = -value f c := root_pow_modulus c
+ rw [← neg_eq_iff_eq_neg.mpr hpow]
+ ring
+
+/-- Horner's rule traverses the coefficients from highest to lowest, using
+one companion operation, one scalar multiplication and one addition per round. -/
+def horner (c b : Vector p e) (coefficients : List (Fin p)) : Vector p e :=
+ coefficients.foldr (fun a acc => add (companion c acc) (scale a b)) (zero p e)
+
+/-- Multiplication modulo the advised monic polynomial. -/
+def mul (c a b : Vector p e) : Vector p e := horner c b (List.ofFn a)
+
+omit [NeZero p] in
+theorem horner_rounds (a : Vector p e) : (List.ofFn a).length = e := List.length_ofFn
+
+theorem value_horner (c b : Vector p e) {k : ℕ} (a : Vector p k) :
+ value (modulus c) (horner c b (List.ofFn a)) =
+ value (modulus c) a * value (modulus c) b := by
+ induction k with
+ | zero =>
+ rw [List.ofFn_zero, horner, List.foldr_nil, value_zero]
+ simp [value]
+ | succ k ih =>
+ rw [List.ofFn_succ]
+ change value _ (add (companion c (horner c b _)) (scale _ b)) = _
+ rw [value_add, value_companion, value_scale, ih]
+ have htail : value (modulus c) a =
+ algebraMap (ZMod p) _ ((a 0).val : ZMod p) +
+ AdjoinRoot.root (modulus c) * value (modulus c) (fun i : Fin k => a i.succ) := by
+ unfold value
+ rw [Fin.sum_univ_succ, Finset.mul_sum]
+ simp [pow_succ, mul_assoc, mul_comm]
+ rw [htail]
+ ring
+
+theorem value_mul (c a b : Vector p e) :
+ value (modulus c) (mul c a b) = value (modulus c) a * value (modulus c) b :=
+ value_horner c b a
+
+end SliceArithmetic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyAccumulate.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyAccumulate.lean
new file mode 100644
index 0000000000..7524efbdd2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyAccumulate.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.SliceArithmeticAccumulatePorts
+import OAI.Computability.VPVNP.SliceArithmeticMultiplyCall
+import OAI.Computability.VPVNP.SliceArithmeticAddCall
+
+/-!
+# A clean multiply-and-add call on extension-field coefficients
+
+This subroutine adds the product of the two saved factors to the accumulator.
+The caller supplies all three in the low-degree-first polynomial basis.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.MultiplyAccumulate
+
+open RAMTape
+open SliceArithmeticRound (packed)
+
+/-- One finite control copies the factors, multiplies and adds. -/
+def machine : FiniteRoutine Port :=
+ (stage.followedBy (MultiplyCall.machine.onPorts multiplyPorts)).followedBy (AddCall.machine.onPorts addPorts)
+
+/-- Step bound for copying two packed factors, multiplying them, and adding the product to the
+accumulator. -/
+def callCap (e w : ℕ) := (10 * (e * w) + 4) + MultiplyCall.callCap e w + AddCall.callCap e w
+
+/-- Both operands and the field advice are preserved, and the private
+workspace is empty again when the updated accumulator returns. -/
+theorem machine_runs {p e w : ℕ} [NeZero p] (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c left returned acc : Vector p e) :
+ let bits := fun v : Vector p e => packed w (List.ofFn v)
+ ∃ t ≤ callCap e w, machine.Runs t
+ (clean (external p e w (bits c) (bits left) (bits returned) (bits acc)))
+ (clean (external p e w (bits c) (bits left) (bits returned) (bits (add acc (mul c left returned))))) := by
+ intro bits
+ let io := external p e w (bits c) (bits left) (bits returned) (bits acc)
+ have copied := stage_runs io
+ have hleft : (io .left).length = e*w := by simp [io, external, bits]
+ have hreturned : (io .returned).length = e*w := by simp [io, external, bits]
+ rw [hleft, hreturned] at copied
+ obtain ⟨t₁, h₁, hr₁⟩ := MultiplyCall.machine_runs he hw c left returned
+ have product := multiplyRun (bits c) (bits left) (bits returned) (bits acc) (bits (mul c left returned)) hr₁
+ obtain ⟨t₂, h₂, hr₂⟩ := AddCall.machine_runs hw acc (mul c left returned) (bits c)
+ have sum := addRun (bits c) (bits left) (bits returned) (bits acc) (bits (mul c left returned))
+ (bits (add acc (mul c left returned))) hr₂
+ exact ⟨_, by unfold callCap; omega, (copied.followedBy product).followedBy sum⟩
+
+/-- A polynomial bound in the extension degree and working limb width. -/
+theorem callCap_le (e w : ℕ) : callCap e w ≤ 3000 * (e + 1) ^ 2 * (w + 1) ^ 2 := by
+ unfold callCap MultiplyCall.callCap HornerControl.digitCap AddCall.callCap
+ ring_nf
+ omega
+
+end SliceArithmetic.MultiplyAccumulate
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyCall.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyCall.lean
new file mode 100644
index 0000000000..236a5674be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyCall.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.SliceArithmeticMultiplyInit
+import OAI.Computability.VPVNP.SliceArithmeticCallOrder
+import OAI.Computability.VPVNP.EvaluatorRadixSpace
+
+/-!
+# A reusable multiplication call on packed extension-field elements
+
+The caller supplies two low-degree-first limb streams, a prime modulus, its
+advised polynomial, the unary degree and a zero word giving the register width.
+The subroutine consumes the query operand, overwrites the accumulator with the
+product and clears its entire local workspace.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.MultiplyCall
+
+open RAMTape BurstRAM HornerControl
+open SliceArithmeticRound (packed packed_length)
+open SliceArithmeticStreamRow (state)
+
+/-- Execute packed field multiplication by setting up the workspace, reversing the query's limb
+order, running Horner rounds, and returning the product. -/
+def machine : FiniteRoutine Port :=
+ ((«initialize».followedBy orderInput).followedBy (HornerControl.machine.onPorts Sum.inl)).followedBy reclaim
+
+/-- Total bit-stack time, including port setup, digit ordering and final cleanup. -/
+def callCap (e w : ℕ) : ℕ :=
+ (14*(5*((e+1)*(w+1))+2)+1) + (e*(15*w+7)+1+(10*w+4)) +
+ (e*(digitCap e w+1)+1) + ((e*w+1)+(5*(e*w)+2)+(13*((e+1)*(w+1)+1)+1))
+
+theorem machine_runs {p e w : ℕ} [NeZero p] (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c a b : Vector p e) :
+ ∃ t ≤ callCap e w, machine.Runs t
+ (clean (external p e w (packed w (List.ofFn c)) (packed w (List.ofFn a)) (packed w (List.ofFn b))))
+ (clean (external p e w (packed w (List.ofFn c)) [] (packed w (List.ofFn (mul c a b))))) := by
+ let cb := packed w (List.ofFn c)
+ let ab := packed w (List.ofFn a)
+ let bb := packed w (List.ofFn b)
+ let yb := packed w (List.ofFn (mul c a b))
+ have hc : cb.length = e*w := by simp [cb]
+ have hb : bb.length = e*w := by simp [bb]
+ have hy : yb.length = e*w := by simp [yb]
+ obtain ⟨n₁, h₁, start⟩ := initialize_runs (p := p) cb ab bb hc hb
+ have ordered := orderInput_runs (w := w) cb bb a
+ obtain ⟨n₂, h₂, registers, main⟩ := HornerControl.machine_runs he hw c a b
+ let io := external p e w cb [] bb
+ let s₀ := state (initialRegisters p w) (streams (packed w (List.ofFn (zero p e))) [] [] []
+ (extra cb bb e (packed w (List.ofFn a).reverse) e 0))
+ let s₁ := state registers (streams yb [] [] [] (extra cb bb e [] 0 0))
+ have installed : (HornerControl.machine.onPorts Sum.inl).Runs n₂ (workspace s₀ io) (workspace s₁ io) := by
+ apply HornerControl.machine.runs_onPorts_framed Sum.inl_injective main (fun _ => rfl) (fun _ => rfl)
+ rintro (i | i) hi
+ · exact (hi i rfl).elim
+ · rfl
+ obtain ⟨n₃, h₃, finish⟩ := reclaim_runs (p := p) registers cb bb yb hc hb hy
+ exact ⟨_, by unfold callCap; omega, ((start.followedBy ordered).followedBy installed).followedBy finish⟩
+
+/-- A simple quadratic bound in both the number of limbs and their working width. -/
+theorem callCap_le (e w : ℕ) : callCap e w ≤ 2000 * (e+1)^2 * (w+1)^2 := by
+ unfold callCap digitCap
+ ring_nf
+ omega
+
+/-- A prefix of the actual instruction execution uses only polynomial storage
+on each of the finitely many ports of the multiplier. -/
+theorem prefix_stack_length {p e w : ℕ} [NeZero p] (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c a b : Vector p e) {n : ℕ} {q : Option machine.State} {s : Stacks Port}
+ (run : StackRuns machine.body.standalone n (some machine.body.entry)
+ (clean (external p e w (packed w (List.ofFn c)) (packed w (List.ofFn a)) (packed w (List.ofFn b)))) q s)
+ (k : Port) : (s k).length ≤ (e+1)*(w+1) + 2000*(e+1)^2*(w+1)^2 := by
+ obtain ⟨t, ht, hdone⟩ := machine_runs he hw c a b
+ have hn := EvaluatorRadixDivision.ticks_le_at_return hdone (by rfl) run
+ apply (EvaluatorRadixDivision.run_length run k).trans
+ apply Nat.add_le_add _ (hn.trans (ht.trans (callCap_le e w)))
+ rcases k with i | i
+ · exact Nat.zero_le _
+ · cases i <;> simp [clean, external] <;> nlinarith
+
+end SliceArithmetic.MultiplyCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyInit.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyInit.lean
new file mode 100644
index 0000000000..8d6158bb06
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyInit.lean
@@ -0,0 +1,66 @@
+import OAI.Computability.VPVNP.SliceArithmeticCallPorts
+import OAI.Computability.VPVNP.SliceArithmeticCallCopies
+
+/-!
+# Initializing the workspace of a slice-field multiplication
+
+The multiplication call starts from empty local stacks. It copies the prime
+modulus, zero-word template, polynomial coefficients, multiplier, and degree
+markers to their local ports. The query stays on its external stack until the
+subsequent digit-order conversion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.MultiplyCall
+
+open RAMTape BurstRAM HornerControl
+open SliceArithmeticStreamRow (state)
+
+/-- Copy the caller's field parameters, multiplier, and degree markers into the initially empty
+Horner workspace. -/
+def «initialize» : FiniteRoutine Port := CallCopies.copyPlan (localStream .scratch) copies
+
+private theorem validCopies : CallCopies.Valid (localStream .scratch) copies := by
+ refine ⟨by decide, ?_, ?_, ?_⟩ <;> simp [copies, localStream, reg, persistent]
+
+/-- The entry routine installs the register bank and the coefficient streams.
+Each of the fourteen copies has at most `(e+1)*(w+1)` bits. -/
+theorem initialize_runs {p e w : ℕ} [NeZero p] (cb ab bb : List Bool)
+ (hc : cb.length = e*w) (hb : bb.length = e*w) :
+ ∃ t ≤ 14*(5*((e+1)*(w+1))+2)+1, «initialize».Runs t
+ (clean (external p e w cb ab bb))
+ (workspace (state (initialRegisters p w) (streams [] [] [] [] (extra cb bb e [] e e)))
+ (external p e w cb ab bb)) := by
+ let s := clean (external p e w cb ab bb)
+ have empty : ∀ q ∈ copies, s q.2 = [] := by
+ simp [copies, s, clean, localStream, reg, persistent]
+ have bound : ∀ q ∈ copies, (s q.1).length ≤ (e+1)*(w+1) := by
+ simp [copies, s, clean, external, hc, hb]
+ exact ⟨by nlinarith, by nlinarith, by nlinarith⟩
+ obtain ⟨t, ht, run⟩ := CallCopies.copyPlan_runs (localStream .scratch) copies s
+ ((e+1)*(w+1)) validCopies rfl empty bound
+ refine ⟨t, ht, ?_⟩
+ suffices h : CallCopies.copied copies s =
+ workspace (state (initialRegisters p w) (streams [] [] [] [] (extra cb bb e [] e e)))
+ (external p e w cb ab bb) by rwa [h] at run
+ funext i
+ rcases i with (i | i) | i
+ · cases i with
+ | reg i => fin_cases i <;> rfl
+ | pub i => exact i.elim0
+ | work i => rfl
+ | persistent => rfl
+ | logPort i => cases i <;> rfl
+ · cases i with
+ | outer x => cases x <;> rfl
+ | _ => rfl
+ · rfl
+
+end SliceArithmetic.MultiplyCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyReverse.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyReverse.lean
new file mode 100644
index 0000000000..1dabaa1df6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticMultiplyReverse.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.SliceArithmeticStreamWord
+import OAI.Computability.VPVNP.SliceArithmeticLoop
+
+/-!
+# Preparing the digit and accumulator streams for Horner multiplication
+
+A marker for each coefficient controls one load of the next input word,
+followed by an order-preserving store onto the digit stack and a store of
+one zero word onto the accumulator. Thus the highest-degree coefficient is
+the first Horner digit, while each limb retains its little-endian encoding.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticMultiplyReverse
+
+open BurstRAM RAMTape SliceArithmetic.StreamWord
+
+set_option backward.isDefEq.respectTransparency false in
+/-- Operand, digit, accumulator, marker, and word-copy ports for preparing the Horner input
+order. -/
+inductive Port where
+ | query | digits | old | marker | staging | zero | scratch
+ deriving DecidableEq, Fintype
+
+private def copyOne : FiniteRoutine Port :=
+ ((load .query .staging .scratch).followedBy (store .digits .staging .scratch)).followedBy
+ (store .old .zero .scratch)
+
+/-- The final store and load use the unconsumed query suffix to reset the
+staging register. Both operations leave this suffix in its original place. -/
+def prepare : FiniteRoutine Port :=
+ ((FiniteRoutine.repeatMarked .marker copyOne).followedBy (store .query .zero .scratch)).followedBy
+ (load .query .staging .scratch)
+
+/-- Concatenate the little-endian bit encodings of a list of equal-width words in list order. -/
+def pack {w : ℕ} (words : List (Word w)) : List Bool := words.flatMap wordBits
+
+/-- State of the digit-order conversion with the remaining query, prepared digits, zero
+accumulator, marker count, and staging word. -/
+def frame {w : ℕ} (query digits old : List Bool) (markers : ℕ) (staging : Word w) : Stacks Port
+ | .query => query
+ | .digits => digits
+ | .old => old
+ | .marker => List.replicate markers true
+ | .staging => wordBits staging
+ | .zero => wordBits (0 : Word w)
+ | .scratch => []
+
+private theorem copyOne_runs {w : ℕ} (x staging : Word w) (tail digits old : List Bool) (markers : ℕ) :
+ copyOne.Runs (15*w + 6) (frame (wordBits x ++ tail) digits old markers staging)
+ (frame tail (wordBits x ++ digits) (wordBits (0 : Word w) ++ old) markers x) := by
+ let s := frame (wordBits x ++ tail) digits old markers staging
+ let s₁ := frame tail digits old markers x
+ let s₂ := frame tail (wordBits x ++ digits) old markers x
+ let s₃ := frame tail (wordBits x ++ digits) (wordBits (0 : Word w) ++ old) markers x
+ have h₁ := load_runs (stream := Port.query) (reg := .staging) (scratch := .scratch)
+ (by decide) (by decide) (by decide) s x tail (length_wordBits staging) rfl rfl
+ have h₂ := store_runs (stream := Port.digits) (reg := .staging) (scratch := .scratch)
+ (by decide) (by decide) (by decide) s₁ x rfl rfl
+ have h₃ := store_runs (stream := Port.old) (reg := .zero) (scratch := .scratch)
+ (by decide) (by decide) (by decide) s₂ (0 : Word w) rfl rfl
+ rw [show Function.update (Function.update s .query tail) .staging (wordBits x) = s₁ by
+ funext i; cases i <;> simp [s, s₁, frame]] at h₁
+ rw [show Function.update s₁ .digits (wordBits x ++ s₁ .digits) = s₂ by
+ funext i; cases i <;> simp [s₁, s₂, frame]] at h₂
+ rw [show Function.update s₂ .old (wordBits (0 : Word w) ++ s₂ .old) = s₃ by
+ funext i; cases i <;> simp [s₂, s₃, frame]] at h₃
+ rw [show 15*w + 6 = (5*w + 2 + (5*w + 2)) + (5*w + 2) by omega]
+ exact (h₁.followedBy h₂).followedBy h₃
+
+private theorem copyLoop_runs {w : ℕ} (words : List (Word w)) (tail digits old : List Bool) (staging : Word w) :
+ (FiniteRoutine.repeatMarked .marker copyOne).Runs (words.length * (15*w + 7) + 1)
+ (frame (pack words ++ tail) digits old words.length staging)
+ (frame tail (pack words.reverse ++ digits) (pack (List.replicate words.length (0 : Word w)) ++ old)
+ 0 (words.getLastD staging)) := by
+ induction words generalizing digits old staging with
+ | nil =>
+ simp only [List.length_nil, Nat.zero_mul, Nat.zero_add, List.reverse_nil, List.getLastD_nil,
+ pack, List.flatMap_nil, List.nil_append, List.replicate_zero]
+ exact Routine.Runs.popLoop_empty .marker (fun _ => true) (Routine.halt false) copyOne.body
+ (s := frame tail digits old 0 staging) rfl
+ | cons x words ih =>
+ let query := pack words ++ tail
+ let s := frame (wordBits x ++ query) digits old (words.length + 1) staging
+ have hs : Function.update s .marker (List.replicate words.length true) =
+ frame (wordBits x ++ query) digits old words.length staging := by
+ funext i; cases i <;> simp [s, frame]
+ have step := copyOne_runs x staging query digits old words.length
+ rw [← hs] at step
+ have tailRun := ih (wordBits x ++ digits) (wordBits (0 : Word w) ++ old) x
+ change (Routine.popLoop Port.marker (fun _ => true) (Routine.halt false) copyOne.body).Runs _ _ _ at tailRun
+ have run := Routine.Runs.popLoop_true_continue Port.marker (fun _ => true) (Routine.halt false) copyOne.body
+ (s := s) (by simp [s, frame, List.replicate_succ]) rfl step tailRun
+ rw [List.length_cons, Nat.succ_mul words.length]
+ change (FiniteRoutine.repeatMarked .marker copyOne).Runs _ _ _ at run
+ rw [show words.length * (15*w+7) + (15*w+7) + 1 = 1 + (15*w+6) + (words.length*(15*w+7)+1) by omega]
+ rw [List.getLastD_cons]
+ simpa [s, query, pack, List.replicate_succ', List.flatMap_append] using run
+
+/-- Exact bit-stack execution for the query preparation. The three streams can
+have arbitrary suffixes, and the staging register returns to the zero word. -/
+theorem prepare_runs {w : ℕ} (words : List (Word w)) (tail digits old : List Bool) (staging : Word w) :
+ prepare.Runs (words.length * (15*w + 7) + 1 + (10*w + 4))
+ (frame (pack words ++ tail) digits old words.length staging)
+ (frame tail (pack words.reverse ++ digits) (pack (List.replicate words.length (0 : Word w)) ++ old) 0 (0 : Word w)) := by
+ let ds := pack words.reverse ++ digits
+ let zs := pack (List.replicate words.length (0 : Word w)) ++ old
+ let s := frame tail ds zs 0 (words.getLastD staging)
+ let middle := frame (wordBits (0 : Word w) ++ tail) ds zs 0 (words.getLastD staging)
+ have scan := copyLoop_runs words tail digits old staging
+ have save := store_runs (stream := Port.query) (reg := .zero) (scratch := .scratch)
+ (by decide) (by decide) (by decide) s (0 : Word w) rfl rfl
+ have reset := load_runs (stream := Port.query) (reg := .staging) (scratch := .scratch)
+ (by decide) (by decide) (by decide) middle (0 : Word w) tail (length_wordBits _) rfl rfl
+ rw [show Function.update s .query (wordBits (0 : Word w) ++ s .query) = middle by
+ funext i; cases i <;> simp [s, middle, frame]] at save
+ rw [show Function.update (Function.update middle .query tail) .staging (wordBits (0 : Word w)) =
+ frame tail ds zs 0 (0 : Word w) by funext i; cases i <;> simp [middle, frame]] at reset
+ rw [show words.length * (15*w + 7) + 1 + (10*w + 4) =
+ (words.length * (15*w + 7) + 1 + (5*w + 2)) + (5*w + 2) by omega]
+ exact (scan.followedBy save).followedBy reset
+
+end SliceArithmeticMultiplyReverse
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticNeg.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticNeg.lean
new file mode 100644
index 0000000000..6f7c21d3cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticNeg.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.SliceArithmeticAddCall
+
+/-!
+# Destructive negation of a packed field scalar
+
+The caller holds the input scalar in the accumulator and an empty query stack.
+A copy of the scalar supplies the second input stream of the coefficientwise
+scan. Each row computes the modular negation of the first input. The scan
+consumes the copy and returns the negated scalar on the accumulator stack.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.NegCall
+
+open RAMTape BurstRAM
+open SliceArithmeticRound (packed)
+open MultiplyCall (External external)
+open AddCall (clean)
+
+private def scratch : AddCall.Port := .inl (.inr .scratch)
+
+/-- Negate the packed accumulator coefficientwise using a private copy on the query port. -/
+def machine : FiniteRoutine AddCall.Port :=
+ (SuccessorFields.prependCopy (.inr .acc) (.inr .query) scratch).followedBy (AddCall.operation .neg)
+
+theorem machine_runs {p e w : ℕ} [NeZero p] (hw : Word.workingWidth p ≤ w)
+ (a : Vector p e) (coeff : List Bool) :
+ ∃ t ≤ 5 * (e * w) + 2 + AddCall.callCap e w, machine.Runs t
+ (clean (external p e w coeff [] (packed w (List.ofFn a))))
+ (clean (external p e w coeff [] (packed w (List.ofFn fun i => -a i)))) := by
+ let x := packed w (List.ofFn a)
+ let entry := clean (external p e w coeff [] x)
+ let staged := clean (external p e w coeff x x)
+ have copy := SuccessorFields.prependCopy_runs (Sum.inr External.acc : AddCall.Port)
+ (.inr .query) scratch (by decide) (by decide) (by decide) entry rfl
+ have hstage : Function.update entry (.inr .query) (entry (.inr .acc) ++ entry (.inr .query)) = staged := by
+ funext i
+ cases i with
+ | inl i => rfl
+ | inr i => cases i <;> simp [entry, staged, AddCall.clean, external]
+ have hlen : (entry (.inr .acc)).length = e * w := by simp [entry, x, AddCall.clean, external]
+ rw [hstage, hlen] at copy
+ obtain ⟨u, hu, run⟩ := AddCall.operation_runs .neg hw a a coeff
+ exact ⟨_, Nat.add_le_add_left hu _, copy.followedBy run⟩
+
+/-- The destructive operation realizes the additive inverse in the quotient ring. -/
+theorem value_neg {p e : ℕ} [NeZero p] (f : Polynomial (ZMod p)) (v : Vector p e) :
+ value f (fun i => -v i) = -value f v := by
+ simp only [value, cast_val_eq_finEquiv, map_neg, neg_mul, Finset.sum_neg_distrib]
+
+end SliceArithmetic.NegCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticPower.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticPower.lean
new file mode 100644
index 0000000000..734cd69934
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticPower.lean
@@ -0,0 +1,135 @@
+import OAI.Computability.VPVNP.SliceArithmeticMul
+import Mathlib.Data.Nat.Size
+
+/-!
+# Powers and inverses in the evaluator's finite slice field
+
+Each instruction in the binary powering routine is one multiplication of
+coefficient vectors. The inverse routine handles zero separately, including
+the case of a field of order two where the Fermat exponent is zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic
+
+/-- An instruction takes the running product and either squares it or
+multiplies it by the original base. -/
+inductive PowerStep where
+ | square
+ | multiplyBase
+ deriving DecidableEq
+
+/-- Read the binary exponent from its most significant bit. -/
+def powerSteps (n : ℕ) : List PowerStep :=
+ n.bits.reverse.flatMap fun bit =>
+ if bit then [.square, .multiplyBase] else [.square]
+
+private theorem powerSteps_bit (n : ℕ) (b : Bool) (h : n = 0 → b = true) :
+ powerSteps (Nat.bit b n) =
+ powerSteps n ++ (if b then [.square, .multiplyBase] else [.square]) := by
+ simp [powerSteps, Nat.bits_append_bit n b h]
+
+/-- The exact number of vector multiplications is the bit length plus the
+number of one bits. -/
+theorem powerSteps_length (n : ℕ) :
+ (powerSteps n).length = n.size + n.bits.count true := by
+ induction n using Nat.binaryRec' with
+ | zero => simp [powerSteps]
+ | bit b n h ih =>
+ rw [powerSteps_bit n b h, List.length_append, ih, Nat.bits_append_bit n b h,
+ Nat.size_bit (Nat.bit_ne_zero_iff.mpr h)]
+ cases b <;> simp <;> omega
+
+theorem powerSteps_length_le (n : ℕ) : (powerSteps n).length ≤ 2 * n.size := by
+ rw [powerSteps_length]
+ have h := List.count_le_length (a := true) (l := n.bits)
+ rw [Nat.size_eq_bits_len] at h
+ omega
+
+variable {p e : ℕ} [NeZero p]
+
+/-- Execute one binary powering instruction by squaring the accumulator or multiplying it by
+the saved base modulo the defining polynomial. -/
+def PowerStep.run (c base acc : Vector p e) : PowerStep → Vector p e
+ | .square => mul c acc acc
+ | .multiplyBase => mul c acc base
+
+/-- Execute the binary powering program with initial value one. -/
+def pow (c base : Vector p e) (n : ℕ) : Vector p e :=
+ (powerSteps n).foldl (PowerStep.run c base) (one p e)
+
+theorem value_pow [NeZero e] (c base : Vector p e) (n : ℕ) :
+ value (modulus c) (pow c base n) = value (modulus c) base ^ n := by
+ induction n using Nat.binaryRec' with
+ | zero => simp [pow, powerSteps]
+ | bit b n h ih =>
+ unfold pow at ih ⊢
+ rw [powerSteps_bit n b h, List.foldl_append]
+ cases b <;> simp [PowerStep.run, value_mul, ih, Nat.bit, pow_add, pow_mul, sq, mul_comm 2 n]
+
+/-- Zero gets the zero vector. A nonzero input uses the Fermat exponent. -/
+def inverse (c a : Vector p e) : Vector p e :=
+ if a = zero p e then zero p e else pow c a (p ^ e - 2)
+
+/-- The instructions executed for the input-dependent inverse routine. -/
+def inverseSteps (a : Vector p e) : List PowerStep :=
+ if a = zero p e then [] else powerSteps (p ^ e - 2)
+
+theorem inverse_eq_fold (c a : Vector p e) :
+ inverse c a = (inverseSteps a).foldl (PowerStep.run c a)
+ (if a = zero p e then zero p e else one p e) := by
+ by_cases h : a = zero p e <;> simp [inverse, inverseSteps, pow, h]
+
+theorem inverseSteps_length_le (a : Vector p e) :
+ (inverseSteps a).length ≤ 2 * (e * Nat.clog 2 p) := by
+ unfold inverseSteps
+ split
+ · simp
+ · apply (powerSteps_length_le _).trans
+ apply Nat.mul_le_mul_left
+ apply Nat.size_le.mpr
+ calc
+ p ^ e - 2 < p ^ e := by have := Nat.pow_pos (NeZero.pos p) (n := e); omega
+ _ ≤ (2 ^ Nat.clog 2 p) ^ e := Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) _
+ _ = 2 ^ (e * Nat.clog 2 p) := by rw [← pow_mul, Nat.mul_comm]
+
+section Field
+
+variable {q : ℕ} [Fact q.Prime]
+
+/-- A monic presentation of degree `e` over the prime field has `q ^ e` elements. -/
+theorem adjoinRoot_card (c : Vector q e) : Nat.card (AdjoinRoot (modulus c)) = q ^ e := by
+ let b := (AdjoinRoot.powerBasis' (modulus_monic c)).basis
+ let := Fintype.ofEquiv _ b.equivFun.toEquiv.symm
+ rw [Nat.card_eq_fintype_card, Module.card_fintype b, ZMod.card]
+ change q ^ Fintype.card (Fin (modulus c).natDegree) = _
+ rw [Fintype.card_fin, modulus_natDegree]
+
+theorem value_inverse [NeZero e] (c a : Vector q e) [Fact (Irreducible (modulus c))] :
+ value (modulus c) (inverse c a) = (value (modulus c) a)⁻¹ := by
+ unfold inverse
+ split
+ next h => simp [h]
+ next h =>
+ have ha : value (modulus c) a ≠ 0 := by
+ intro hz
+ exact h (value_injective (modulus_monic c) (modulus_natDegree c) (hz.trans (value_zero _).symm))
+ rw [value_pow]
+ apply eq_inv_of_mul_eq_one_left
+ let b := (AdjoinRoot.powerBasis' (modulus_monic c)).basis
+ let := Fintype.ofEquiv _ b.equivFun.toEquiv.symm
+ have hq : 1 < q ^ e := one_lt_pow₀ (Fact.out : q.Prime).one_lt (NeZero.ne e)
+ have hcard : Fintype.card (AdjoinRoot (modulus c)) = q ^ e :=
+ Nat.card_eq_fintype_card.symm.trans (adjoinRoot_card c)
+ rw [← pow_succ, show q ^ e - 2 + 1 = q ^ e - 1 by omega, ← hcard]
+ exact FiniteField.pow_card_sub_one_eq_one _ ha
+
+end Field
+end SliceArithmetic
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticPowerMachine.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticPowerMachine.lean
new file mode 100644
index 0000000000..a605ac6be3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticPowerMachine.lean
@@ -0,0 +1,192 @@
+import OAI.Computability.VPVNP.SliceArithmeticPowerPorts
+import OAI.Computability.VPVNP.StructuredStackLoop
+
+/-!
+# Binary powering on a bit stack
+
+For every exponent bit the machine squares its current packed accumulator.
+A set bit triggers a second multiplication by the preserved packed base.
+Both uses of the multiplier enter and return with its entire workspace clean.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.InverseCall
+
+open RAMTape BurstRAM
+open SliceArithmeticRound (packed)
+
+private def queryPort : Port := .inl (.inr .query)
+private def accPort : Port := .inl (.inr .acc)
+
+/-- Copy the selected source to the consumed operand and run the reusable multiplier. -/
+private def multiplyFrom (src : Port) : FiniteRoutine Port :=
+ (SuccessorFields.prependCopy src queryPort (.inr .scratch)).followedBy
+ (MultiplyCall.machine.onPorts Sum.inl)
+
+private def bitBody (b : Bool) : FiniteRoutine Port :=
+ if b then (multiplyFrom accPort).followedBy (multiplyFrom (.inr .base)) else multiplyFrom accPort
+
+/-- Consume the exponent in high-bit-first order, squaring at every bit and multiplying by the
+base for each set bit. -/
+def powerMachine : FiniteRoutine Port := FiniteRoutine.ofRoutine <|
+ Routine.popLoop (.inr .bits) (fun _ => true) (bitBody false).body (bitBody true).body
+
+/-- Step bound for processing one exponent bit, allowing both a square and a multiplication by
+the base. -/
+def bitCap (e w : ℕ) : ℕ := 2 * (5*(e*w)+2+MultiplyCall.callCap e w)
+
+variable {p e w : ℕ} [Fact p.Prime]
+
+private def phase (c x v : Vector p e) (b : Bool) : Vector p e :=
+ if b then mul c (mul c v v) x else mul c v v
+
+private theorem commutative_mul (c x y : Vector p e) : mul c x y = mul c y x := by
+ apply value_injective (modulus_monic c) (modulus_natDegree c)
+ rw [value_mul, value_mul, mul_comm]
+
+private theorem multiplyFrom_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (fromBase : Bool) (c x v : Vector p e) (advice bits : List Bool) :
+ let src := if fromBase then .inr Extra.base else accPort
+ let a := if fromBase then x else v
+ let cb := packed w (List.ofFn c)
+ let xb := packed w (List.ofFn x)
+ ∃ t ≤ 5*(e*w)+2+MultiplyCall.callCap e w, (multiplyFrom src).Runs t
+ (frame p e w cb xb advice bits (packed w (List.ofFn v)) [])
+ (frame p e w cb xb advice bits (packed w (List.ofFn (mul c a v))) []) := by
+ intro src a cb xb
+ let vb := packed w (List.ofFn v)
+ let ab := packed w (List.ofFn a)
+ let yb := packed w (List.ofFn (mul c a v))
+ let input := frame p e w cb xb advice bits vb []
+ let output := frame p e w cb xb advice bits yb []
+ let middle := Function.update input queryPort ab
+ have hsrc : src ≠ queryPort ∧ src ≠ (.inr .scratch : Port) := by cases fromBase <;> decide
+ have copy := SuccessorFields.prependCopy_runs src queryPort (.inr .scratch) hsrc.1 hsrc.2
+ (by decide) input rfl
+ have ha : input src = ab := by cases fromBase <;> rfl
+ rw [ha, show input queryPort = [] from rfl, List.append_nil, show ab.length = e*w by simp [ab]] at copy
+ obtain ⟨m, hm, hmul⟩ := MultiplyCall.machine_runs he hw c a v
+ have installed : (MultiplyCall.machine.onPorts Sum.inl).Runs m middle output := by
+ apply MultiplyCall.machine.runs_onPorts_framed Sum.inl_injective hmul
+ · rintro (k | k)
+ · rfl
+ · cases k <;> rfl
+ · intro k; rfl
+ · rintro (k | k) h
+ · exact (h k rfl).elim
+ · rfl
+ exact ⟨_, by omega, copy.followedBy installed⟩
+
+private theorem bitBody_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c x v : Vector p e) (b : Bool) (advice bits : List Bool) :
+ let cb := packed w (List.ofFn c)
+ let xb := packed w (List.ofFn x)
+ ∃ t ≤ bitCap e w, (bitBody b).Runs t
+ (frame p e w cb xb advice bits (packed w (List.ofFn v)) [])
+ (frame p e w cb xb advice bits (packed w (List.ofFn (phase c x v b))) []) := by
+ intro cb xb
+ obtain ⟨t, ht, square⟩ := multiplyFrom_runs he hw false c x v advice bits
+ cases b with
+ | false => exact ⟨t, by unfold bitCap; omega, square⟩
+ | true =>
+ obtain ⟨u, hu, byBase⟩ := multiplyFrom_runs he hw true c x (mul c v v) advice bits
+ simp only [↓reduceIte] at byBase
+ rw [commutative_mul c x (mul c v v)] at byBase
+ exact ⟨_, by unfold bitCap; omega, square.followedBy byBase⟩
+
+/-- The finite powering control consumes every bit of its input stack. -/
+theorem powerMachine_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c x v : Vector p e) (advice bits : List Bool) :
+ let cb := packed w (List.ofFn c)
+ let xb := packed w (List.ofFn x)
+ ∃ t ≤ bits.length * (bitCap e w + 1) + 1, powerMachine.Runs t
+ (frame p e w cb xb advice bits (packed w (List.ofFn v)) [])
+ (frame p e w cb xb advice [] (packed w (List.ofFn (bits.foldl (phase c x) v))) []) := by
+ intro cb xb
+ induction bits generalizing v with
+ | nil =>
+ exact ⟨1, by simp, Routine.Runs.popLoop_empty (.inr Extra.bits : Port) (fun _ => true)
+ (bitBody false).body (bitBody true).body (s := frame p e w cb xb advice [] (packed w (List.ofFn v)) []) rfl⟩
+ | cons b bs ih =>
+ obtain ⟨t, ht, head⟩ := bitBody_runs he hw c x v b advice bs
+ obtain ⟨u, hu, tail⟩ := ih (phase c x v b)
+ let bank := fun bits (a : Vector p e) => frame p e w cb xb advice bits (packed w (List.ofFn a)) []
+ have hupdate : Function.update (bank (b::bs) v) (.inr .bits) bs = bank bs v := by
+ funext k
+ rcases k with i | i
+ · rfl
+ · cases i <;> rfl
+ change (Routine.popLoop (.inr Extra.bits : Port) (fun _ => true) (bitBody false).body
+ (bitBody true).body).Runs u (bank bs (phase c x v b)) (bank [] _) at tail
+ have run := Routine.Runs.popLoop_continue (.inr Extra.bits : Port) (fun _ => true)
+ (bitBody false).body (bitBody true).body (s := bank (b::bs) v) (mid := bank bs (phase c x v b))
+ (b := b) (tail := bs) rfl rfl (by rw [hupdate]; cases b <;> exact head) tail
+ exact ⟨_, by rw [List.length_cons, Nat.succ_mul]; omega, run⟩
+
+private theorem fold_phase_eq (c x : Vector p e) (bits : List Bool) (v : Vector p e) :
+ bits.foldl (phase c x) v =
+ (bits.flatMap fun b => if b then [PowerStep.square, .multiplyBase] else [.square]).foldl
+ (PowerStep.run c x) v := by
+ induction bits generalizing v with
+ | nil => rfl
+ | cons b bits ih =>
+ rw [List.flatMap_cons, List.foldl_append, List.foldl_cons, ih]
+ cases b <;> rfl
+
+/-- The canonical binary expansion computes the vector power. -/
+theorem power_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c x : Vector p e) (advice : List Bool) (n : ℕ) :
+ let cb := packed w (List.ofFn c)
+ let xb := packed w (List.ofFn x)
+ ∃ t ≤ n.size * (bitCap e w + 1) + 1, powerMachine.Runs t
+ (frame p e w cb xb advice n.bits.reverse (packed w (List.ofFn (one p e))) [])
+ (frame p e w cb xb advice [] (packed w (List.ofFn (pow c x n))) []) := by
+ simpa only [fold_phase_eq, pow, powerSteps, List.length_reverse, Nat.size_eq_bits_len] using
+ powerMachine_runs he hw c x (one p e) advice n.bits.reverse
+
+/-- A most-significant-bit-first exponent may retain its leading zero bits. -/
+theorem power_word_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c x : Vector p e) (advice bits : List Bool) :
+ let cb := packed w (List.ofFn c)
+ let xb := packed w (List.ofFn x)
+ ∃ t ≤ bits.length * (bitCap e w + 1) + 1, powerMachine.Runs t
+ (frame p e w cb xb advice bits (packed w (List.ofFn (one p e))) [])
+ (frame p e w cb xb advice [] (packed w (List.ofFn (pow c x (TapeWord.value bits.reverse)))) []) := by
+ let : NeZero e := ⟨Nat.ne_of_gt he⟩
+ have hval : value (modulus c) (bits.foldl (phase c x) (one p e)) =
+ value (modulus c) x ^ TapeWord.value bits.reverse := by
+ induction bits using List.reverseRecOn with
+ | nil => simp [TapeWord.value]
+ | append_singleton bs b ih =>
+ cases b <;> simp [phase, value_mul, ih, TapeWord.value, two_mul, pow_add]
+ ring
+ have hfold : bits.foldl (phase c x) (one p e) = pow c x (TapeWord.value bits.reverse) := by
+ apply value_injective (modulus_monic c) (modulus_natDegree c)
+ rw [hval, value_pow]
+ simpa only [hfold] using powerMachine_runs he hw c x (one p e) advice bits
+
+/-- A zero base and a zero initial accumulator stay zero, including the empty exponent. -/
+theorem power_zero_runs (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (c : Vector p e) (advice bits : List Bool) :
+ let cb := packed w (List.ofFn c)
+ let zb := packed w (List.ofFn (zero p e))
+ ∃ t ≤ bits.length * (bitCap e w + 1) + 1, powerMachine.Runs t
+ (frame p e w cb zb advice bits zb []) (frame p e w cb zb advice [] zb []) := by
+ have hmul : mul c (zero p e) (zero p e) = zero p e := by
+ apply value_injective (modulus_monic c) (modulus_natDegree c)
+ simp [value_mul]
+ have hfold : bits.foldl (phase c (zero p e)) (zero p e) = zero p e := by
+ induction bits with
+ | nil => rfl
+ | cons b bs ih =>
+ cases b <;> simpa only [List.foldl_cons, phase, Bool.false_eq_true, ↓reduceIte, hmul] using ih
+ simpa only [hfold] using powerMachine_runs he hw c (zero p e) (zero p e) advice bits
+
+end SliceArithmetic.InverseCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticPowerPorts.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticPowerPorts.lean
new file mode 100644
index 0000000000..21512b9406
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticPowerPorts.lean
@@ -0,0 +1,38 @@
+import OAI.Computability.VPVNP.SliceArithmeticMultiplyCall
+import OAI.Computability.VPVNP.SliceArithmeticPower
+
+/-! # Ports of the binary powering and inversion control -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.InverseCall
+
+open RAMTape
+
+set_option backward.isDefEq.respectTransparency false in
+/-- Extra inversion ports for the saved base and exponent, the live bit stream, the zero-test
+flag, and temporary stacks. -/
+inductive Extra where
+ | base | exponent | bits | flag | scratch | temp
+ deriving DecidableEq, Fintype
+
+/-- The multiplier's full port bank extended with the ports for binary powering and inversion. -/
+abbrev Port := MultiplyCall.Port ⊕ Extra
+
+/-- Caller-visible scalar advice and operands, together with the exponent
+scan's remaining bits and the temporary zero-test flag. -/
+def frame (p e w : ℕ) (cb base exponent bits acc flag : List Bool) : Stacks Port :=
+ Sum.elim (MultiplyCall.clean (MultiplyCall.external p e w cb [] acc)) fun
+ | .base => base
+ | .exponent => exponent
+ | .bits => bits
+ | .flag => flag
+ | .scratch | .temp => []
+
+end SliceArithmetic.InverseCall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticRound.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticRound.lean
new file mode 100644
index 0000000000..f0c89a903d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticRound.lean
@@ -0,0 +1,216 @@
+import OAI.Computability.VPVNP.SliceArithmeticLoop
+import OAI.Computability.VPVNP.SliceArithmeticWork
+import OAI.Computability.VPVNP.SliceArithmeticStreamRow
+
+/-!
+# The uniform coefficient loop of one Horner round
+
+The loop consumes the three low-degree-first streams of limbs. The result is
+pushed in reverse bit order so that one ordinary stack reversal prepares the
+next accumulator.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticRound
+
+open VPVNP.SliceArithmetic VPVNP.RAMTape
+
+variable {p w : ℕ} [NeZero p]
+
+/-- The three prime-field limbs consumed at one coefficient position of a Horner round. -/
+structure Item (p : ℕ) where
+ /-- Old accumulator limb saved as the shifted predecessor at the next coefficient position. -/
+ old : Fin p
+ /-- Coefficient of the defining monic polynomial below its leading term, used in reduction at
+ this position. -/
+ coeff : Fin p
+ /-- Coefficient of the multiplier at the current degree. -/
+ factor : Fin p
+
+/-- The previous accumulator limb and the registers last written by a row.
+The output list stores the new limbs from high to low. -/
+structure Acc (p : ℕ) where
+ /-- Preceding old accumulator coefficient, supplying the shift term for the next row. -/
+ previous : Fin p
+ /-- Most recently loaded defining-polynomial coefficient in the row registers. -/
+ coeff : Fin p
+ /-- Most recently loaded multiplier coefficient in the row registers. -/
+ factor : Fin p
+ /-- Prime-field coefficient computed by the most recent Horner row. -/
+ result : Fin p
+ /-- Temporary residue holding the Horner digit times the current multiplier coefficient. -/
+ scratch : Fin p
+ /-- Coefficients emitted by the processed rows, stored in reverse degree order. -/
+ output : List (Fin p)
+
+/-- Compute the shifted predecessor plus the reduction and digit products, prepend the result,
+and save the old limb for the next row. -/
+def next (digit reduction : Fin p) (s : Acc p) (x : Item p) : Acc p :=
+ let scratch := digit * x.factor
+ let result := s.previous + reduction * x.coeff + scratch
+ ⟨x.old, x.coeff, x.factor, result, scratch, result :: s.output⟩
+
+omit [NeZero p] in
+private theorem fold_output (digit reduction : Fin p) (xs : List (Item p)) (s : Acc p) :
+ (xs.foldl (next digit reduction) s).output =
+ (Stream.run digit reduction xs.length
+ ⟨xs.map Item.coeff, xs.map Item.factor, xs.map Item.old, s.output, s.previous, 0⟩).output := by
+ suffices ∀ (k : ℕ), (xs.foldl (next digit reduction) s).output =
+ (Stream.run digit reduction xs.length
+ ⟨xs.map Item.coeff, xs.map Item.factor, xs.map Item.old, s.output, s.previous, k⟩).output from this 0
+ intro k
+ induction xs generalizing s k with
+ | nil => rfl
+ | cons x xs ih => exact ih (next digit reduction s x) (k + 4)
+
+/-- The vector of streamed row results is the companion step of Horner's rule. -/
+theorem fold_vector_output {e : ℕ} (c b v : Vector p e) (digit : Fin p)
+ (s : Acc p) (hp : s.previous = 0) :
+ let items := List.ofFn (fun i => Item.mk (v i) (c i) (b i))
+ (items.foldl (next digit (-(List.ofFn v).getLastD 0)) s).output =
+ (List.ofFn (add (companion c v) (scale digit b))).reverse ++ s.output := by
+ intro xs
+ rw [fold_output]
+ simp only [xs, List.length_ofFn, List.map_ofFn, Function.comp_def, hp]
+ obtain ⟨h, _⟩ := Stream.scan_output digit (-(List.ofFn v).getLastD 0) 0 c b v s.output 0
+ rw [h]
+ congr 3
+ funext i
+ cases e with
+ | zero => exact i.elim0
+ | succ k =>
+ have hlast : (List.ofFn v).getLastD 0 = v (Fin.last k) := by rw [List.ofFn_succ']; simp
+ rw [hlast]
+ rfl
+
+omit [NeZero p] in
+theorem fold_result_of_nonempty (digit reduction : Fin p) (xs : List (Item p)) (s : Acc p)
+ (hx : xs ≠ []) :
+ let z := xs.foldl (next digit reduction) s
+ z.output.head? = some z.result := by
+ induction xs generalizing s with
+ | nil => exact False.elim (hx rfl)
+ | cons a xs ih =>
+ cases xs with
+ | nil => rfl
+ | cons b bs => exact ih (next digit reduction s a) (List.cons_ne_nil _ _)
+
+omit [NeZero p] in
+/-- Pack low-endian words consecutively, retaining the full working width. -/
+def packed (w : ℕ) (xs : List (Fin p)) : List Bool :=
+ xs.flatMap fun a => BurstRAM.wordBits (Word.limb w a)
+
+omit [NeZero p] in
+@[simp] theorem packed_length (w : ℕ) (xs : List (Fin p)) : (packed w xs).length = xs.length * w := by
+ induction xs with
+ | nil => simp [packed]
+ | cons a xs ih =>
+ rw [packed, List.flatMap_cons, List.length_append, BurstRAM.length_wordBits]
+ change w + (packed w xs).length = _
+ rw [ih, List.length_cons, Nat.succ_mul, Nat.add_comm]
+
+open SliceArithmeticStreamRow
+
+/-- Register order of the Horner-row kernel. -/
+def registers (w : ℕ) (digit reduction : Fin p) (s : Acc p) : Fin 8 → BurstRAM.Word w :=
+ ![Fin.ofNat _ p, Word.limb w s.previous, Word.limb w reduction, Word.limb w s.coeff,
+ Word.limb w digit, Word.limb w s.factor, Word.limb w s.result, Word.limb w s.scratch]
+
+variable {X : Type} [DecidableEq X]
+
+/-- The remaining stream inputs, the accumulated output, and the row markers.
+Other caller ports and suffixes of the input streams are preserved. -/
+def streams (w : ℕ) (marker : X) (base : Stacks (StreamPort X)) (xs : List (Item p))
+ (s : Acc p) : Stacks (StreamPort X)
+ | .old => packed w (xs.map Item.old) ++ base .old
+ | .coeff => packed w (xs.map Item.coeff) ++ base .coeff
+ | .factor => packed w (xs.map Item.factor) ++ base .factor
+ | .out => (packed w s.output.reverse).reverse ++ base .out
+ | .scratch => []
+ | .outer j => if j = marker then List.replicate xs.length true else base (.outer j)
+
+/-- One finite control for all moduli, word widths and extension degrees. -/
+def scan (marker : X) : FiniteRoutine (Port X) :=
+ FiniteRoutine.repeatMarked (.inr (.outer marker)) body
+
+/-- A complete scan on the represented coefficient stream, including
+arithmetic, register loads, output stores and loop tests. -/
+theorem scan_runs (hw : Word.workingWidth p ≤ w) (marker : X)
+ (base : Stacks (StreamPort X)) (digit reduction : Fin p) (xs : List (Item p)) (s : Acc p) :
+ let frame := fun ys a => state (registers w digit reduction a) (streams w marker base ys a)
+ ∃ ticks ≤ xs.length * (800 * (w + 1) ^ 2 + 22 * w + 10) + 1,
+ (scan marker).Runs ticks (frame xs s) (frame [] (xs.foldl (next digit reduction) s)) := by
+ intro frame
+ apply FiniteRoutine.repeatMarked_runs (.inr (.outer marker)) body frame (next digit reduction)
+ (800 * (w + 1) ^ 2 + 22 * w + 9) ?_ ?_ xs s
+ · intro ys acc
+ simp [frame, state, streams]
+ intro x ys a
+ let r := registers w digit reduction a
+ let u := Function.update (streams w marker base (x :: ys) a) (.outer marker)
+ (List.replicate ys.length true)
+ let tails := streams w marker base ys a
+ have readOld : u .old = BurstRAM.wordBits (Word.limb w x.old) ++ tails .old := by
+ simp [u, tails, streams, packed]
+ have readCoeff : u .coeff = BurstRAM.wordBits (Word.limb w x.coeff) ++ tails .coeff := by
+ simp [u, tails, streams, packed]
+ have readFactor : u .factor = BurstRAM.wordBits (Word.limb w x.factor) ++ tails .factor := by
+ simp [u, tails, streams, packed]
+ obtain ⟨k, hk, hr⟩ := body_runs hw r u a.previous reduction x.coeff digit x.factor x.old
+ (tails .old) (tails .coeff) (tails .factor)
+ (Nat.mod_eq_of_lt (Word.modulus_lt hw)) (Word.limb_val hw a.previous)
+ (Word.limb_val hw reduction) (Word.limb_val hw digit)
+ readOld readCoeff readFactor (by simp [u, streams])
+ have hreg : nextRegisters r a.previous reduction x.coeff digit x.factor x.old =
+ registers w digit reduction (next digit reduction a x) := by
+ funext i
+ fin_cases i <;> simp [nextRegisters, SliceArithmeticRow.rowRegisters, next, r, registers, Function.update]
+ have hstreams : nextStreams u (tails .old) (tails .coeff) (tails .factor)
+ (BurstRAM.wordBits (Word.limb w (a.previous + reduction * x.coeff + digit * x.factor))) =
+ streams w marker base ys (next digit reduction a x) := by
+ funext i
+ cases i with
+ | outer j => by_cases hj : j = marker <;> simp [nextStreams, streams, u, hj]
+ | old | coeff | factor | scratch | out =>
+ simp [nextStreams, tails, streams, next, u, packed, List.flatMap_append]
+ rw [hreg, hstreams] at hr
+ exact ⟨k, hk, by simpa only [frame, updateStream] using hr⟩
+
+/-- The checked bit-stack execution for one digit reads each of the three input
+vectors and writes the complete next accumulator in globally reversed bit order.
+Register 6 contains the last output limb for the following reduction. -/
+theorem horner_scan_runs {e : ℕ} (he : 0 < e) (hw : Word.workingWidth p ≤ w) (marker : X)
+ (base : Stacks (StreamPort X)) (c b v : Vector p e) (digit : Fin p)
+ (s : Acc p) (hprev : s.previous = 0) (hout : s.output = []) :
+ let reduction := -(List.ofFn v).getLastD 0
+ let xs := List.ofFn (fun i => Item.mk (v i) (c i) (b i))
+ let y := add (companion c v) (scale digit b)
+ ∃ a : Acc p, a.output = (List.ofFn y).reverse ∧ a.result = (List.ofFn y).getLastD 0 ∧
+ ∃ ticks ≤ e * (800 * (w + 1) ^ 2 + 22 * w + 10) + 1,
+ (scan marker).Runs ticks
+ (state (registers w digit reduction s) (streams w marker base xs s))
+ (state (registers w digit reduction a) (streams w marker base [] a)) := by
+ intro reduction xs y
+ let a := xs.foldl (next digit reduction) s
+ have hx : xs ≠ [] := by
+ intro hz
+ have h := congrArg List.length hz
+ simp [xs] at h
+ omega
+ have houtput : a.output = (List.ofFn y).reverse := by
+ simpa only [hout, List.append_nil] using fold_vector_output c b v digit s hprev
+ have hresult := fold_result_of_nonempty digit reduction xs s hx
+ change a.output.head? = some a.result at hresult
+ rw [houtput, List.head?_reverse] at hresult
+ refine ⟨a, houtput, ?_, ?_⟩
+ · simp [hresult]
+ · simpa only [xs, List.length_ofFn] using scan_runs hw marker base digit reduction xs s
+
+end SliceArithmeticRound
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticRow.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticRow.lean
new file mode 100644
index 0000000000..6c24d7ae37
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticRow.lean
@@ -0,0 +1,68 @@
+import OAI.Computability.VPVNP.SliceArithmeticWord
+
+/-!
+# One coefficient of a Horner round on bit stacks
+
+The evaluator computes the shifted predecessor plus two scalar products.
+It uses registers 0 through 5 for the modulus, predecessor, negated top
+coefficient, modulus coefficient, Horner digit and multiplier coefficient,
+respectively. Register 6 receives the result and register 7 holds the second
+product. The same control works at every coefficient and every word width.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticRow
+
+open BurstRAM PrivateRAM RAMTape ISA
+open SliceArithmetic.Word
+
+/-- Execute the four modular operations for one Horner coefficient, leaving its result in
+register six. -/
+def row {k : ℕ} : FiniteRoutine (Port 8 k) :=
+ (((routine .mul 6 2 3 0).followedBy (routine .add 6 1 6 0)).followedBy
+ (routine .mul 7 4 5 0)).followedBy (routine .add 6 6 7 0)
+
+/-- The two destination registers at the end of a row calculation. -/
+def rowRegisters {p w : ℕ} (reg : Fin 8 → BurstRAM.Word w)
+ (prev reduction c digit b : Fin p) : Fin 8 → BurstRAM.Word w :=
+ Function.update (Function.update reg 7 (limb w (digit * b))) 6
+ (limb w (prev + reduction * c + digit * b))
+
+theorem row_runs {p k w : ℕ} [NeZero p] (hw : workingWidth p ≤ w)
+ (pub : Fin k → BurstRAM.Word w) (persistent : BurstRAM.Word w)
+ (reg : Fin 8 → BurstRAM.Word w) (log : WriteLog w) (prev reduction c digit b : Fin p)
+ (hp : (reg 0).val = p) (hprev : (reg 1).val = prev.val)
+ (hred : (reg 2).val = reduction.val) (hc : (reg 3).val = c.val)
+ (hd : (reg 4).val = digit.val) (hb : (reg 5).val = b.val) :
+ ∃ t ≤ 800 * (w + 1) ^ 2, row.Runs t (bank pub persistent reg log)
+ (bank pub persistent (rowRegisters reg prev reduction c digit b) log) := by
+ let r₁ := Function.update reg 6 (limb w (reduction * c))
+ let r₂ := Function.update r₁ 6 (limb w (prev + reduction * c))
+ let r₃ := Function.update r₂ 7 (limb w (digit * b))
+ obtain ⟨t₁, ht₁, run₁⟩ := routine_runs hw .mul 6 2 3 0 (by decide) pub persistent reg log
+ reduction c hred hc hp
+ obtain ⟨t₂, ht₂, run₂⟩ := routine_runs hw .add 6 1 6 0 (by decide) pub persistent r₁ log
+ prev (reduction * c) (by simpa [r₁] using hprev) (by simp [r₁, limb_val hw])
+ (by simpa [r₁] using hp)
+ obtain ⟨t₃, ht₃, run₃⟩ := routine_runs hw .mul 7 4 5 0 (by decide) pub persistent r₂ log
+ digit b (by simpa [r₂, r₁] using hd) (by simpa [r₂, r₁] using hb) (by simpa [r₂, r₁] using hp)
+ obtain ⟨t₄, ht₄, run₄⟩ := routine_runs hw .add 6 6 7 0 (by decide) pub persistent r₃ log
+ (prev + reduction * c) (digit * b)
+ (by simp [r₃, r₂, limb_val hw]) (by simp [r₃, limb_val hw]) (by simpa [r₃, r₂, r₁] using hp)
+ have heq : Function.update r₃ 6 (limb w (prev + reduction * c + digit * b)) =
+ rowRegisters reg prev reduction c digit b := by
+ funext i
+ by_cases h6 : i = 6 <;> by_cases h7 : i = 7 <;>
+ simp [r₃, r₂, r₁, rowRegisters, h6, h7]
+ simp only [Op.eval] at run₄
+ rw [heq] at run₄
+ exact ⟨_, by omega, ((run₁.followedBy run₂).followedBy run₃).followedBy run₄⟩
+
+end SliceArithmeticRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticSignedCount.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticSignedCount.lean
new file mode 100644
index 0000000000..1eeba468e5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticSignedCount.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.SliceArithmeticCountPorts
+import OAI.Computability.VPVNP.SliceArithmeticConstantEmit
+
+/-!
+# Converting signed witness counts into an extension-field coefficient
+
+Each arbitrary-width little-endian count is reduced independently modulo the
+advised prime. Their difference occupies the constant coordinate of the power
+basis, with a zero word for every higher coordinate. The input counts, field
+advice and the caller's output suffix survive the conversion.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticSignedCount
+
+open BurstRAM RAMTape TapeWord SliceArithmetic
+
+/-- Route constant emission through the residue holding the signed difference, the caller's
+degree and zero word, and the result port. -/
+def emitPorts : ConstantEmit.Port → Port
+ | .degree => .inr .degree
+ | .zeroWord => .inr .zeroWord
+ | .limb => .inl (.residue false)
+ | .out => .inr .result
+ | .scratch => .inl .scratch
+ | .marker => .inl .marker
+
+private theorem emit_injective : Function.Injective emitPorts := by
+ intro i j h
+ cases i <;> cases j <;> simp_all [emitPorts]
+
+/-- Reduce both counts modulo the prime, subtract the residues, emit their difference in the
+constant coordinate, and clear the residues. -/
+def machine : FiniteRoutine Port :=
+ (((((reduceCount false).followedBy (reduceCount true)).followedBy
+ (SliceArithmeticSubtract.machine.onPorts arithmeticPorts)).followedBy
+ (ConstantEmit.machine.onPorts emitPorts)).followedBy (CallClear.clear (.inl (.residue false)))).followedBy
+ (CallClear.clear (.inl (.residue true)))
+
+/-- Step bound for signed-count conversion with input bit lengths `n` and `m`, extension degree
+`e`, and limb width `w`. -/
+def callCap (n m e w : ℕ) :=
+ reduceCost n w + reduceCost m w + 400 * (w + 1)^2 + ConstantEmit.cost e w + 2 * (w + 1)
+
+/-- The coefficient emitted from the two binary counters. -/
+def difference (p : ℕ) [NeZero p] (positive negative : List Bool) : Fin p :=
+ Fin.ofNat p (value positive) - Fin.ofNat p (value negative)
+
+private theorem emit_runs {p e w : ℕ} (he : 0 < e) (positive negative suffix : List Bool)
+ (low : BurstRAM.Word w) (other : List Bool) :
+ let residues := fun sign : Bool => if sign then other else wordBits low
+ (ConstantEmit.machine.onPorts emitPorts).Runs (ConstantEmit.cost e w)
+ (frame (external p e w positive negative suffix) [] residues)
+ (frame (external p e w positive negative (wordBits low ++ List.replicate ((e-1)*w) false ++ suffix))
+ [] residues) := by
+ intro residues
+ apply FiniteRoutine.runs_onPorts_framed _ emit_injective (ConstantEmit.machine_runs he low suffix)
+ · intro i
+ cases i <;> rfl
+ · intro i
+ cases i <;> rfl
+ rintro (i|i) hi
+ · cases i with
+ | divide i => cases i <;> rfl
+ | _ => rfl
+ · cases i <;> first | rfl | exact (hi .out rfl).elim
+
+theorem machine_runs {p e w : ℕ} [NeZero p] (he : 0 < e) (hw : Word.workingWidth p ≤ w)
+ (positive negative suffix : List Bool) :
+ let low := Word.limb w (difference p positive negative)
+ ∃ t ≤ callCap positive.length negative.length e w, machine.Runs t
+ (clean (external p e w positive negative suffix))
+ (clean (external p e w positive negative (wordBits low ++ List.replicate ((e-1)*w) false ++ suffix))) := by
+ intro low
+ let a := Fin.ofNat p (value positive)
+ let b := Fin.ofNat p (value negative)
+ let bits := fun z : Fin p => wordBits (Word.limb w z)
+ let io := external p e w positive negative suffix
+ let blank := fun _ : Bool => ([] : List Bool)
+ let first := Function.update blank false (bits a)
+ have pos := reduceCount_runs hw false io blank rfl rfl
+ have neg := reduceCount_runs hw true io first rfl rfl
+ have hboth : Function.update first true (bits b) = fun s : Bool => if s then bits b else bits a := by
+ funext s; cases s <;> rfl
+ change (reduceCount true).Runs (reduceCost negative.length w) _ (frame io [] (Function.update first true (bits b))) at neg
+ rw [hboth] at neg
+ obtain ⟨n, hn, subtract⟩ := subtract_runs hw io a b rfl rfl
+ have emit := emit_runs (p := p) he positive negative suffix low (bits (-b))
+ let next := external p e w positive negative (wordBits low ++ List.replicate ((e-1)*w) false ++ suffix)
+ let after := frame next [] (fun s : Bool => if s then bits (-b) else wordBits low)
+ let afterLow := frame next [] (fun s : Bool => if s then bits (-b) else [])
+ have hclear₁ := CallClear.clear_runs (.inl (.residue false)) after
+ have hclear₂ := CallClear.clear_runs (.inl (.residue true)) afterLow
+ have heq₁ : Function.update after (.inl (.residue false)) [] = afterLow := by
+ funext j
+ rcases j with i|i
+ · cases i with
+ | divide i => cases i <;> rfl
+ | residue s => cases s <;> rfl
+ | _ => rfl
+ · rfl
+ have heq₂ : Function.update afterLow (.inl (.residue true)) [] = clean next := by
+ funext j
+ rcases j with i|i
+ · cases i with
+ | divide i => cases i <;> rfl
+ | residue s => cases s <;> rfl
+ | _ => rfl
+ · rfl
+ rw [heq₁, show (after (.inl (.residue false))).length = w from length_wordBits _] at hclear₁
+ rw [heq₂, show (afterLow (.inl (.residue true))).length = w from length_wordBits _] at hclear₂
+ refine ⟨_, ?_, ((((pos.followedBy neg).followedBy subtract).followedBy emit).followedBy hclear₁).followedBy hclear₂⟩
+ change reduceCost positive.length w + reduceCost negative.length w + n + ConstantEmit.cost e w +
+ (w+1) + (w+1) ≤ _
+ unfold callCap
+ omega
+
+/-- A single quadratic bound in all bit lengths and the number of coordinates. -/
+theorem callCap_le (n m e w : ℕ) : callCap n m e w ≤ 600 * (n + m + e + w + 1)^2 := by
+ unfold callCap reduceCost SliceArithmeticMagnitude.cost ConstantEmit.cost
+ have h := Nat.mul_le_mul_right (5*w + 3) (Nat.sub_le e 1)
+ ring_nf at h ⊢
+ omega
+
+end SliceArithmeticSignedCount
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticStreamBank.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticStreamBank.lean
new file mode 100644
index 0000000000..64f7f465bf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticStreamBank.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.SliceArithmeticRow
+import OAI.Computability.VPVNP.RAMTapeRoutinePorts
+
+/-! # Arithmetic registers and stream ports for the finite Horner control -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticStreamRow
+
+open BurstRAM RAMTape
+
+/-- The caller supplies its own disjoint ports for the loop markers and saved inputs. -/
+inductive StreamPort (X : Type) where
+ | old | coeff | factor | out | scratch | outer (x : X)
+ deriving DecidableEq, Fintype
+
+/-- Eight-register arithmetic bank and coefficient-stream ports used by a Horner row, including
+the caller's ports of type `X`. -/
+abbrev Port (X : Type) := Sum (ISA.Port 8 0) (StreamPort X)
+
+/-- The finite arithmetic register bank and the caller's stream stacks. -/
+def state {X : Type} {w : ℕ} (reg : Fin 8 → Word w) (streams : Stacks (StreamPort X)) :
+ Stacks (Port X) := Sum.elim (ISA.bank Fin.elim0 0 reg []) streams
+
+variable {X : Type} [DecidableEq X] {w : ℕ}
+
+theorem updateStream (reg : Fin 8 → Word w) (streams : Stacks (StreamPort X))
+ (s : StreamPort X) (bits : List Bool) :
+ Function.update (state reg streams) (.inr s) bits = state reg (Function.update streams s bits) := by
+ funext i
+ cases i with
+ | inl i => simp [state]
+ | inr i => by_cases h : i = s <;> simp [state, h]
+
+theorem updateReg (reg : Fin 8 → Word w) (streams : Stacks (StreamPort X))
+ (i : Fin 8) (x : Word w) :
+ Function.update (state reg streams) (.inl (.reg i)) (wordBits x) =
+ state (Function.update reg i x) streams := by
+ funext j
+ cases j with
+ | inr j => simp [state]
+ | inl j =>
+ have h := congrFun (ISA.bank_updateReg (k := 0) Fin.elim0 0 reg [] i x) j
+ by_cases he : j = .reg i <;> simp_all [state]
+
+theorem bankRun (routine : FiniteRoutine (ISA.Port 8 0)) (streams : Stacks (StreamPort X))
+ {reg next : Fin 8 → Word w} {t : ℕ}
+ (hr : routine.Runs t (ISA.bank Fin.elim0 0 reg []) (ISA.bank Fin.elim0 0 next [])) :
+ (routine.onPorts Sum.inl).Runs t (state reg streams) (state next streams) := by
+ apply routine.runs_onPorts_framed Sum.inl_injective hr (fun _ => rfl) (fun _ => rfl)
+ rintro (j | j) hj
+ · exact (hj j rfl).elim
+ · rfl
+
+end SliceArithmeticStreamRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticStreamRow.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticStreamRow.lean
new file mode 100644
index 0000000000..6c7769a4b7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticStreamRow.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.SliceArithmeticStreamBank
+import OAI.Computability.VPVNP.SliceArithmeticStreamWord
+
+/-!
+# One streamed Horner row on bit stacks
+
+The fixed control reads the next modulus and multiplier coefficients, runs the
+four residue operations, emits the resulting limb, and saves the old
+accumulator coefficient for the next row. The output is built in reverse bit
+order so a single stack reversal restores all limbs to their input order.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticStreamRow
+
+open BurstRAM RAMTape SliceArithmetic.Word SliceArithmetic.StreamWord SliceArithmeticRow
+
+variable {X : Type} {w p : ℕ}
+
+/-- Consume the next limb from stream `s` and load it into arithmetic register `i`. -/
+def loadLimb (s : StreamPort X) (i : Fin 8) : FiniteRoutine (Port X) :=
+ load (.inr s) (.inl (.reg i)) (.inr .scratch)
+
+/-- Store the result from register six on the output stack in reversed bit order for the final
+reversal. -/
+def emit : FiniteRoutine (Port X) :=
+ storeReverse (.inr .out) (.inl (.reg 6)) (.inr .scratch) (.inl (.work 0))
+
+/-- Read a modulus limb and a multiplier limb, compute and emit the row result, then load the
+next shifted predecessor. -/
+def body : FiniteRoutine (Port X) :=
+ ((((loadLimb .coeff 3).followedBy (loadLimb .factor 5)).followedBy
+ (row.onPorts Sum.inl)).followedBy emit).followedBy (loadLimb .old 1)
+
+/-- Register contents after a Horner row, including its result, second product, and the old
+accumulator limb needed by the next row. -/
+def nextRegisters (reg : Fin 8 → BurstRAM.Word w)
+ (prev reduction c digit b old : Fin p) : Fin 8 → BurstRAM.Word w :=
+ let loaded := Function.update (Function.update reg 3 (limb w c)) 5 (limb w b)
+ Function.update (rowRegisters loaded prev reduction c digit b) 1 (limb w old)
+
+/-- Stream contents after one Horner row, with consumed inputs replaced by their tails and the
+emitted result on the output. -/
+def nextStreams (streams : Stacks (StreamPort X))
+ (oldTail coeffTail factorTail resultBits : List Bool) : Stacks (StreamPort X)
+ | .old => oldTail
+ | .coeff => coeffTail
+ | .factor => factorTail
+ | .out => resultBits.reverse ++ streams .out
+ | s => streams s
+
+variable [DecidableEq X]
+
+theorem loadLimb_runs {s : StreamPort X} (hs : s ≠ .scratch) (i : Fin 8)
+ (reg : Fin 8 → BurstRAM.Word w) (streams : Stacks (StreamPort X))
+ (x : BurstRAM.Word w) (tail : List Bool) (hread : streams s = wordBits x ++ tail)
+ (ht : streams .scratch = []) :
+ (loadLimb s i).Runs (5 * w + 2) (state reg streams)
+ (state (Function.update reg i x) (Function.update streams s tail)) := by
+ have run := load_runs (stream := Sum.inr s) (reg := Sum.inl (ISA.Port.reg i : ISA.Port 8 0))
+ (scratch := .inr .scratch) (by simp) (by simpa using hs) (by simp)
+ (state reg streams) x tail (length_wordBits (reg i)) hread ht
+ rwa [updateStream, updateReg] at run
+
+theorem emit_runs (reg : Fin 8 → BurstRAM.Word w) (streams : Stacks (StreamPort X))
+ (ht : streams .scratch = []) :
+ emit.Runs (7 * w + 3) (state reg streams)
+ (state reg (Function.update streams .out ((wordBits (reg 6)).reverse ++ streams .out))) := by
+ have run := storeReverse_runs (stream := Sum.inr (.out : StreamPort X)) (reg := .inl (.reg 6))
+ (scratch := .inr .scratch) (tmp := .inl (.work 0)) (by simp) (by simp) (by simp)
+ (by simp) (by simp) (by simp) (state reg streams) (reg 6) rfl ht rfl
+ rwa [updateStream] at run
+
+theorem body_runs [NeZero p] (hw : workingWidth p ≤ w)
+ (reg : Fin 8 → BurstRAM.Word w) (streams : Stacks (StreamPort X))
+ (prev reduction c digit b old : Fin p) (oldTail coeffTail factorTail : List Bool)
+ (hp : (reg 0).val = p) (hprev : (reg 1).val = prev.val)
+ (hred : (reg 2).val = reduction.val) (hd : (reg 4).val = digit.val)
+ (hold : streams .old = wordBits (limb w old) ++ oldTail)
+ (hc : streams .coeff = wordBits (limb w c) ++ coeffTail)
+ (hb : streams .factor = wordBits (limb w b) ++ factorTail) (ht : streams .scratch = []) :
+ ∃ t ≤ 800 * (w + 1) ^ 2 + 22 * w + 9, body.Runs t (state reg streams)
+ (state (nextRegisters reg prev reduction c digit b old)
+ (nextStreams streams oldTail coeffTail factorTail (wordBits (limb w (prev + reduction * c + digit * b))))) := by
+ let r₁ := Function.update reg 3 (limb w c)
+ let s₁ := Function.update streams .coeff coeffTail
+ let r₂ := Function.update r₁ 5 (limb w b)
+ let s₂ := Function.update s₁ .factor factorTail
+ let r₃ := rowRegisters r₂ prev reduction c digit b
+ let s₃ := Function.update s₂ .out ((wordBits (r₃ 6)).reverse ++ s₂ .out)
+ have run₁ := loadLimb_runs (by simp) 3 reg streams (limb w c) coeffTail hc ht
+ have run₂ := loadLimb_runs (s := .factor) (by simp) 5 r₁ s₁ (limb w b) factorTail
+ (by simpa [s₁] using hb) (by simpa [s₁] using ht)
+ obtain ⟨n, hn, run₃⟩ := row_runs hw Fin.elim0 0 r₂ [] prev reduction c digit b
+ (by simpa [r₂, r₁] using hp) (by simpa [r₂, r₁] using hprev)
+ (by simpa [r₂, r₁] using hred) (by simp [r₂, r₁, limb_val hw])
+ (by simpa [r₂, r₁] using hd) (by simp [r₂, limb_val hw])
+ have arithmetic := bankRun row s₂ run₃
+ have run₄ := emit_runs r₃ s₂ (by simpa [s₂, s₁] using ht)
+ have run₅ := loadLimb_runs (s := .old) (by simp) 1 r₃ s₃ (limb w old) oldTail
+ (by simpa [s₃, s₂, s₁] using hold) (by simpa [s₃, s₂, s₁] using ht)
+ have hstreams : Function.update s₃ .old oldTail =
+ nextStreams streams oldTail coeffTail factorTail (wordBits (limb w (prev + reduction * c + digit * b))) := by
+ funext s
+ cases s <;> simp [s₃, s₂, s₁, r₃, rowRegisters, nextStreams]
+ rw [hstreams] at run₅
+ exact ⟨_, by omega, (((run₁.followedBy run₂).followedBy arithmetic).followedBy run₄).followedBy run₅⟩
+
+end SliceArithmeticStreamRow
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticStreamStage.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticStreamStage.lean
new file mode 100644
index 0000000000..589c137d3d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticStreamStage.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-!
+# Staging the persistent streams of a Horner round
+
+A fixed control copies the advised modulus, the multiplier and the row count
+into the three consumable input stacks of the coefficient scan. All three
+source stacks remain available for the next Horner digit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.StreamStage
+
+open RAMTape RAMTape.SuccessorFields
+
+/-- Ports for saved and consumable copies of the reduction coefficients, multiplier, and row
+count, plus copy scratch space. -/
+inductive Port where
+ | coefficient | factor | count
+ | coefficientInput | factorInput | countInput | scratch
+ deriving DecidableEq
+
+/-- Three order-preserving copies into empty stacks. -/
+def stage : FiniteRoutine Port :=
+ ((prependCopy .coefficient .coefficientInput .scratch).followedBy
+ (prependCopy .factor .factorInput .scratch)).followedBy
+ (prependCopy .count .countInput .scratch)
+
+/-- State of the three saved streams and their three consumable input stacks for one Horner
+round. -/
+def frame (c b n ci bi ni : List Bool) : Stacks Port
+ | .coefficient => c
+ | .factor => b
+ | .count => n
+ | .coefficientInput => ci
+ | .factorInput => bi
+ | .countInput => ni
+ | .scratch => []
+
+theorem stage_runs (c b n : List Bool) :
+ stage.Runs (5 * (c.length + b.length + n.length) + 6)
+ (frame c b n [] [] []) (frame c b n c b n) := by
+ let s := frame c b n [] [] []
+ have hc := prependCopy_runs .coefficient .coefficientInput .scratch
+ (by decide) (by decide) (by decide) s rfl
+ have hb := prependCopy_runs .factor .factorInput .scratch
+ (by decide) (by decide) (by decide) (frame c b n c [] []) rfl
+ have hn := prependCopy_runs .count .countInput .scratch
+ (by decide) (by decide) (by decide) (frame c b n c b []) rfl
+ have h₁ : Function.update s .coefficientInput (s .coefficient ++ s .coefficientInput) =
+ frame c b n c [] [] := by funext i; cases i <;> simp [s, frame, Function.update]
+ have h₂ : Function.update (frame c b n c [] []) .factorInput (b ++ []) =
+ frame c b n c b [] := by funext i; cases i <;> simp [frame, Function.update]
+ have h₃ : Function.update (frame c b n c b []) .countInput (n ++ []) =
+ frame c b n c b n := by funext i; cases i <;> simp [frame, Function.update]
+ rw [h₁] at hc
+ change (prependCopy ..).Runs (5 * b.length + 2) _ (Function.update _ _ (b ++ [])) at hb
+ change (prependCopy ..).Runs (5 * n.length + 2) _ (Function.update _ _ (n ++ [])) at hn
+ rw [h₂] at hb
+ rw [h₃] at hn
+ rw [show 5 * (c.length + b.length + n.length) + 6 =
+ (5 * c.length + 2 + (5 * b.length + 2)) + (5 * n.length + 2) by omega]
+ exact (hc.followedBy hb).followedBy hn
+
+end SliceArithmetic.StreamStage
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticStreamWord.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticStreamWord.lean
new file mode 100644
index 0000000000..0354bf04cc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticStreamWord.lean
@@ -0,0 +1,149 @@
+import OAI.Computability.VPVNP.EvaluatorRadixDivision
+import OAI.Computability.VPVNP.RAMTapeSuccessorRecord
+
+/-!
+# Word transfers for the streamed extension-field evaluator
+
+Each architectural register has the common word width. During a load, popping
+the old register provides one iteration per input bit. A single scratch stack
+then restores the loaded word to least-significant-bit-first order. A store
+uses the same scratch space to prepend the register to a packed output stream.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.StreamWord
+
+open RAMTape BurstRAM
+
+variable {K : Type}
+
+private def saveBit (stream scratch : K) :=
+ Routine.popCase stream (Routine.halt false) (Routine.push scratch false) (Routine.push scratch true)
+
+private def savePrefix (stream reg scratch : K) :=
+ Routine.popLoop reg (fun _ => true) (saveBit stream scratch) (saveBit stream scratch)
+
+/-- Replace the register by one word from the front of the stream. -/
+def load (stream reg scratch : K) : FiniteRoutine K :=
+ (FiniteRoutine.ofRoutine (savePrefix stream reg scratch)).followedBy
+ (EvaluatorRadixDivision.reverseOnto scratch reg)
+
+/-- Prepend the register to the stream and restore the register. -/
+def store (stream reg scratch : K) : FiniteRoutine K :=
+ SuccessorFields.prependCopy reg stream scratch
+
+/-- Emit the register in the reverse bit order used by a backward output scan. -/
+def storeReverse (stream reg scratch tmp : K) : FiniteRoutine K :=
+ (store scratch reg tmp).followedBy (EvaluatorRadixDivision.reverseOnto scratch stream)
+
+variable [DecidableEq K] {stream reg scratch : K}
+
+private theorem savePrefix_runs (hsr : stream ≠ reg) (hst : stream ≠ scratch) (hrt : reg ≠ scratch)
+ (bits tail : List Bool) (s u : Stacks K)
+ (hreg : (s reg).length = bits.length) (hstream : s stream = bits ++ tail)
+ (uread : u stream = tail) (ureg : u reg = []) (utmp : u scratch = bits.reverse ++ s scratch)
+ (hframe : ∀ k, k ≠ stream → k ≠ reg → k ≠ scratch → u k = s k) :
+ (savePrefix stream reg scratch).Runs (3 * bits.length + 1) s u := by
+ induction bits generalizing s with
+ | nil =>
+ have hr : s reg = [] := List.length_eq_zero_iff.mp hreg
+ have hu : u = s := by
+ funext k
+ by_cases hi : k = stream
+ · subst k; exact uread.trans hstream.symm
+ by_cases hj : k = reg
+ · subst k; exact ureg.trans hr.symm
+ by_cases hk : k = scratch
+ · subst k; exact utmp
+ exact hframe k hi hj hk
+ rw [hu]
+ exact Routine.Runs.popLoop_empty reg _ _ _ hr
+ | cons b bits ih =>
+ cases h : s reg with
+ | nil => simp [h] at hreg
+ | cons d old =>
+ let a := Function.update s reg old
+ let v := Function.update a stream (bits ++ tail)
+ let next := Function.update v scratch (b :: s scratch)
+ have ha : a stream = b :: (bits ++ tail) := by simp [a, hsr, hstream]
+ have hv : v scratch = s scratch := by simp [v, a, hst.symm, hrt.symm]
+ have hpush : (Routine.push scratch b).Runs 1 v next := by
+ simpa only [hv] using Routine.runs_push scratch b v
+ have hbit : (saveBit stream scratch).Runs 2 a next := by
+ cases b with
+ | false => exact Routine.runs_popCase_false _ _ _ _ ha hpush
+ | true => exact Routine.runs_popCase_true _ _ _ _ ha hpush
+ have hr : (savePrefix stream reg scratch).Runs (3 * bits.length + 1) next u := by
+ apply ih next
+ · have hlen : old.length = bits.length := by simpa [h] using hreg
+ simpa [next, v, a, hrt, hsr.symm] using hlen
+ · simp [next, v, hst]
+ · simpa [next, List.reverse_cons, List.append_assoc] using utmp
+ · intro k hi hj hk
+ simpa [next, v, a, hi, hj, hk] using hframe k hi hj hk
+ have run := Routine.Runs.popLoop_continue reg (fun _ => true) (saveBit stream scratch)
+ (saveBit stream scratch) h rfl (by cases d <;> exact hbit) hr
+ rw [show 3 * (b :: bits).length + 1 = 1 + 2 + (3 * bits.length + 1) by
+ simp only [List.length_cons]; omega]
+ exact run
+
+/-- The width comes from the old register. Other stacks retain their contents,
+the input tail is untouched, and the scratch stack returns empty. -/
+theorem load_runs (hsr : stream ≠ reg) (hst : stream ≠ scratch) (hrt : reg ≠ scratch)
+ (s : Stacks K) {w : ℕ} (x : BurstRAM.Word w) (tail : List Bool)
+ (hreg : (s reg).length = w) (hstream : s stream = wordBits x ++ tail) (ht : s scratch = []) :
+ (load stream reg scratch).Runs (5 * w + 2) s
+ (Function.update (Function.update s stream tail) reg (wordBits x)) := by
+ let base := Function.update s stream tail
+ let mid := Function.update (Function.update base reg []) scratch (wordBits x).reverse
+ let out := Function.update base reg (wordBits x)
+ have first := savePrefix_runs hsr hst hrt (wordBits x) tail s mid (by simpa using hreg) hstream
+ (by simp [mid, base, hst, hsr]) (by simp [mid, hrt]) (by simp [mid, ht])
+ (fun k hi hj hk => by simp [mid, base, hi, hj, hk])
+ have second := EvaluatorRadixDivision.reverseOnto_runs hrt.symm mid out
+ (by simp [out, base, hst.symm, hrt.symm, ht]) (by simp [out, mid, hrt])
+ (fun k hk hj => by simp [out, mid, hk, hj])
+ have run := FiniteRoutine.Runs.followedBy (a := FiniteRoutine.ofRoutine (savePrefix stream reg scratch))
+ first second
+ change (load stream reg scratch).Runs
+ (3 * (wordBits x).length + 1 + (2 * (mid scratch).length + 1)) s out at run
+ simp only [mid, Function.update_self, List.length_reverse, length_wordBits] at run
+ rw [show 3*w + 1 + (2*w + 1) = 5*w + 2 by omega] at run
+ exact run
+
+/-- Copy a register onto the output stream in its native bit order. -/
+theorem store_runs (hsr : stream ≠ reg) (hst : stream ≠ scratch) (hrt : reg ≠ scratch)
+ (s : Stacks K) {w : ℕ} (x : BurstRAM.Word w) (hreg : s reg = wordBits x) (ht : s scratch = []) :
+ (store stream reg scratch).Runs (5 * w + 2) s
+ (Function.update s stream (wordBits x ++ s stream)) := by
+ simpa only [store, hreg, length_wordBits] using
+ SuccessorFields.prependCopy_runs reg stream scratch hsr.symm hrt hst s ht
+
+/-- A reversed store stages a copy of the register, then transfers its bits to
+the stream. Both temporary stacks return empty. -/
+theorem storeReverse_runs {tmp : K} (_hsr : stream ≠ reg) (hss : stream ≠ scratch)
+ (_hst : stream ≠ tmp) (hrs : reg ≠ scratch) (hrt : reg ≠ tmp) (hstmp : scratch ≠ tmp)
+ (s : Stacks K) {w : ℕ} (x : BurstRAM.Word w) (hreg : s reg = wordBits x)
+ (hs : s scratch = []) (ht : s tmp = []) :
+ (storeReverse stream reg scratch tmp).Runs (7*w + 3) s
+ (Function.update s stream ((wordBits x).reverse ++ s stream)) := by
+ let mid := Function.update s scratch (wordBits x)
+ let out := Function.update s stream ((wordBits x).reverse ++ s stream)
+ have first : (store scratch reg tmp).Runs (5*w + 2) s mid := by
+ simpa only [hs, List.append_nil] using store_runs hrs.symm hstmp hrt s x hreg ht
+ have second := EvaluatorRadixDivision.reverseOnto_runs hss.symm mid out
+ (by simp [out, hss.symm, hs]) (by simp [out, mid, hss])
+ (fun k hi hj => by simp [out, mid, hi, hj])
+ have run := first.followedBy second
+ simp only [mid, Function.update_self, length_wordBits] at run
+ rw [show 5*w + 2 + (2*w + 1) = 7*w + 3 by omega] at run
+ exact run
+
+end SliceArithmetic.StreamWord
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticSubtract.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticSubtract.lean
new file mode 100644
index 0000000000..d0845c96d8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticSubtract.lean
@@ -0,0 +1,48 @@
+import OAI.Computability.VPVNP.SliceArithmeticWord
+import Mathlib.Tactic.FinCases
+import Mathlib.Data.ZMod.Defs
+
+/-! # Subtracting canonical prime residues in the evaluator's register bank -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticSubtract
+
+open RAMTape ISA BurstRAM SliceArithmetic.Word
+
+/-- Negate the negative-count residue modulo the prime and add it to the positive-count residue
+in register one. -/
+def machine : FiniteRoutine (Port 3 0) :=
+ (routine .neg 2 2 2 0).followedBy (routine .add 1 1 2 0)
+
+/-- The modulus, positive-count residue, and negative-count residue in subtraction-register
+order. -/
+def registers {w : ℕ} (prime positive negative : Word w) : Fin 3 → Word w := ![prime, positive, negative]
+
+theorem machine_runs {p w : ℕ} [NeZero p] (hw : workingWidth p ≤ w) (prime : Word w)
+ (hp : prime.val = p) (a b : Fin p) :
+ ∃ t ≤ 400 * (w + 1)^2, machine.Runs t
+ (bank Fin.elim0 0 (registers prime (limb w a) (limb w b)) [])
+ (bank Fin.elim0 0 (registers prime (limb w (a - b)) (limb w (-b))) []) := by
+ let input := registers prime (limb w a) (limb w b)
+ let middle := Function.update input 2 (limb w (-b))
+ obtain ⟨m, hm, hneg⟩ := routine_runs hw .neg 2 2 2 0 (by decide) Fin.elim0 0 input [] b b
+ (limb_val hw b) (limb_val hw b) hp
+ obtain ⟨n, hn, hadd⟩ := routine_runs hw .add 1 1 2 0 (by decide) Fin.elim0 0 middle [] a (-b)
+ (by simpa [middle, input, registers] using limb_val hw a) (by simp [middle, limb_val hw])
+ (by simpa [middle, input, registers] using hp)
+ have hfinal : Function.update middle 1 (limb w (a + -b)) = registers prime (limb w (a-b)) (limb w (-b)) := by
+ funext i
+ fin_cases i <;> simp [middle, input, registers]
+ exact congrArg (limb w) (sub_eq_add_neg a b).symm
+ simp only [Op.eval] at hadd
+ rw [hfinal] at hadd
+ exact ⟨_, by omega, hneg.followedBy hadd⟩
+
+end SliceArithmeticSubtract
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticWord.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticWord.lean
new file mode 100644
index 0000000000..23fa88132d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticWord.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.RAMTapeWordISAStage
+import Mathlib.Data.Nat.Log
+
+/-!
+# Prime-field coefficient arithmetic on bit stacks
+
+The advice supplies the modulus and the canonical coefficients in registers.
+A fixed pair of word instructions computes each operation. The first instruction
+forms an ordinary integer sum, product or difference at a width large enough
+to retain it. The second reduces this word modulo the advised modulus.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.Word
+
+open BurstRAM PrivateRAM RAMTape ISA
+
+/-- Word width sufficient for a sum or product of two canonical residues and
+the modulus itself. The routine also accepts any wider register bank. -/
+def workingWidth (p : ℕ) := 2 * Nat.clog 2 p + 1
+
+theorem workingWidth_capacity {p w : ℕ} (h : workingWidth p ≤ w) :
+ 2 * p ^ 2 ≤ 2 ^ w := by
+ have hp := Nat.le_pow_clog (by decide : 1 < 2) p
+ calc
+ 2 * p ^ 2 ≤ 2 * (2 ^ Nat.clog 2 p) ^ 2 :=
+ Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hp _)
+ _ = 2 ^ workingWidth p := by
+ rw [workingWidth, mul_comm 2 (Nat.clog _ _), ← pow_mul, pow_succ' 2 (Nat.clog 2 p * 2)]
+ _ ≤ 2 ^ w := Nat.pow_le_pow_right (by decide) h
+
+/-- Embed a canonical residue in a register. -/
+def limb {p : ℕ} (w : ℕ) (a : Fin p) : BurstRAM.Word w := Fin.ofNat _ a.val
+
+theorem modulus_lt {p w : ℕ} [NeZero p] (h : workingWidth p ≤ w) : p < 2 ^ w := by
+ have hp := NeZero.pos p
+ have hc := workingWidth_capacity h
+ nlinarith
+
+@[simp] theorem limb_val {p w : ℕ} [NeZero p] (h : workingWidth p ≤ w) (a : Fin p) :
+ (limb w a).val = a.val := Nat.mod_eq_of_lt (a.isLt.trans (modulus_lt h))
+
+/-- The residue operations supported by the fixed word routine for field arithmetic. -/
+inductive Op where
+ | add | mul | neg
+ deriving DecidableEq
+
+/-- Evaluate the chosen operation modulo `p`, using only the first operand for negation. -/
+def Op.eval {p : ℕ} : Op → Fin p → Fin p → Fin p
+ | .add, x, y => x + y
+ | .mul, x, y => x * y
+ | .neg, x, _ => -x
+
+private def Op.first : Op → BinaryOp
+ | .add => .add
+ | .mul => .mul
+ | .neg => .sub
+
+private def Op.inputs {α : Type*} (op : Op) (x y modulus : α) : α × α :=
+ match op with
+ | .add | .mul => (x, y)
+ | .neg => (modulus, x)
+
+/-- Both the opcode table and the port assignment are independent of the
+prime and of the word width. The destination is reused as the intermediate. -/
+def routine {r k : ℕ} (op : Op) (dst lhs rhs modulusReg : Fin r) : FiniteRoutine (Port r k) :=
+ let args := op.inputs lhs rhs modulusReg
+ (binary op.first dst args.1 args.2).followedBy (binary .mod dst dst modulusReg)
+
+private theorem reduced {p w : ℕ} [NeZero p] (hw : workingWidth p ≤ w)
+ (op : Op) (x y : Fin p) (a b m : BurstRAM.Word w)
+ (ha : a.val = x.val) (hb : b.val = y.val) (hm : m.val = p) :
+ let args := op.inputs a b m
+ BinaryOp.mod.eval (op.first.eval args.1 args.2) m = limb w (op.eval x y) := by
+ have hcap := workingWidth_capacity hw
+ have hp := NeZero.pos p
+ have hpx := x.isLt
+ have hpy := y.isLt
+ have hsq : p ≤ p ^ 2 := by nlinarith
+ have hadd : x.val + y.val < 2 ^ w := by omega
+ have hmul : x.val * y.val < 2 ^ w :=
+ (Nat.mul_lt_mul_of_lt_of_le hpx hpy.le hp).trans_le (by nlinarith)
+ have hsub : a ≤ m := by change a.val ≤ m.val; omega
+ cases op with
+ | add =>
+ simp [Op.inputs, Op.first, Op.eval, BinaryOp.eval, limb, ha, hb, hm, Fin.val_add, Nat.mod_eq_of_lt hadd]
+ | mul =>
+ simp [Op.inputs, Op.first, Op.eval, BinaryOp.eval, limb, ha, hb, hm, Fin.val_mul, Nat.mod_eq_of_lt hmul]
+ | neg =>
+ simp [Op.inputs, Op.first, Op.eval, BinaryOp.eval, limb, Fin.sub_val_of_le hsub, ha, hm, Fin.neg_def]
+
+/-- A clean architectural bank returns with only the destination register
+updated. Input registers can alias the destination, since the first
+instruction stages its operands before writeback. -/
+theorem routine_runs {p r k w : ℕ} [NeZero p] (hw : workingWidth p ≤ w)
+ (op : Op) (dst lhs rhs modulusReg : Fin r) (hd : modulusReg ≠ dst)
+ (pub : Fin k → BurstRAM.Word w) (persistent : BurstRAM.Word w)
+ (reg : Fin r → BurstRAM.Word w) (log : WriteLog w) (x y : Fin p)
+ (hx : (reg lhs).val = x.val) (hy : (reg rhs).val = y.val) (hm : (reg modulusReg).val = p) :
+ ∃ t ≤ 200 * (w + 1) ^ 2, (routine op dst lhs rhs modulusReg).Runs t
+ (bank pub persistent reg log)
+ (bank pub persistent (Function.update reg dst (limb w (op.eval x y))) log) := by
+ let args := op.inputs lhs rhs modulusReg
+ let raw := op.first.eval (reg args.1) (reg args.2)
+ let middle := Function.update reg dst raw
+ obtain ⟨t₁, h₁, run₁⟩ := binary_runs op.first dst args.1 args.2 pub persistent reg log
+ obtain ⟨t₂, h₂, run₂⟩ := binary_runs .mod dst dst modulusReg pub persistent middle log
+ have hresult : BinaryOp.mod.eval (middle dst) (middle modulusReg) = limb w (op.eval x y) := by
+ simp only [middle, Function.update_self, Function.update_of_ne hd]
+ have h := reduced hw op x y (reg lhs) (reg rhs) (reg modulusReg) hx hy hm
+ cases op <;> exact h
+ rw [hresult, show Function.update middle dst (limb w (op.eval x y)) =
+ Function.update reg dst (limb w (op.eval x y)) from Function.update_idem ..] at run₂
+ exact ⟨t₁ + t₂, by omega, run₁.followedBy run₂⟩
+
+end SliceArithmetic.Word
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticWork.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticWork.lean
new file mode 100644
index 0000000000..2b34f1fdeb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticWork.lean
@@ -0,0 +1,179 @@
+import OAI.Computability.VPVNP.SliceArithmeticMul
+
+/-!
+# Coefficient streams for multiplication in the advised field
+
+One Horner round scans the accumulator, modulus and multiplier in increasing
+degree order. The preceding accumulator limb supplies the shift. Its last limb
+supplies the reduction coefficient for the whole round. The scan records the
+number of prime-residue additions, multiplications and negations performed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmetic.Stream
+
+open VPVNP.SliceArithmetic
+
+variable {p e : ℕ} [NeZero p]
+
+/-- Live streams in a Horner round. The output grows in reverse order. -/
+structure ScanState (p : ℕ) where
+ /-- Remaining low-degree-first coefficients of the monic modulus below its leading term. -/
+ modulus : List (Fin p)
+ /-- Remaining low-degree-first coefficients of the multiplier. -/
+ multiplier : List (Fin p)
+ /-- Remaining coefficients of the accumulator from the preceding Horner round. -/
+ accumulator : List (Fin p)
+ /-- Newly computed coefficients stored in reverse degree order during the scan. -/
+ output : List (Fin p)
+ /-- Old accumulator limb carried forward for the polynomial shift. -/
+ previous : Fin p
+ /-- Number of prime-residue operations charged so far in the coefficient scan. -/
+ work : ℕ
+
+/-- One row consumes one limb of each input. The two products and two sums
+are operations in the prime residue ring. -/
+def step (digit reduction : Fin p) (s : ScanState p) : ScanState p :=
+ match s.modulus, s.multiplier, s.accumulator with
+ | c :: cs, b :: bs, v :: vs =>
+ ⟨cs, bs, vs, (s.previous + reduction * c + digit * b) :: s.output, v, s.work + 4⟩
+ | _, _, _ => s
+
+/-- A tail-recursive scan with one transition per coefficient. -/
+def run (digit reduction : Fin p) : ℕ → ScanState p → ScanState p
+ | 0, s => s
+ | n + 1, s => run digit reduction n (step digit reduction s)
+
+/-- Count the live limbs of the scan, including the digit and reduction coefficient. -/
+def ScanState.limbs (s : ScanState p) : ℕ :=
+ s.modulus.length + s.multiplier.length + s.accumulator.length + s.output.length + 3
+
+omit [NeZero p] in
+theorem step_limbs_le (digit reduction : Fin p) (s : ScanState p) :
+ (step digit reduction s).limbs ≤ s.limbs := by
+ rcases s with ⟨c, b, v, out, prev, work⟩
+ cases c <;> cases b <;> cases v <;> simp [step, ScanState.limbs]
+ omega
+
+omit [NeZero p] in
+theorem run_limbs_le (digit reduction : Fin p) (k : ℕ) (s : ScanState p) :
+ (run digit reduction k s).limbs ≤ s.limbs := by
+ induction k generalizing s with
+ | zero => exact le_rfl
+ | succ k ih => exact (ih _).trans (step_limbs_le ..)
+
+/-- Coordinates of a shift, seeded with an arbitrary preceding limb. -/
+def shift {p : ℕ} (previous : Fin p) : {k : ℕ} → Vector p k → Vector p k
+ | 0, v => v
+ | _ + 1, v => Fin.cons previous fun j => v j.castSucc
+
+omit [NeZero p] in
+private theorem shift_tail {k : ℕ} (previous : Fin p) (v : Vector p (k + 1)) (i : Fin k) :
+ shift previous v i.succ = shift (v 0) (fun j : Fin k => v j.succ) i := by
+ cases k with
+ | zero => exact i.elim0
+ | succ k =>
+ induction i using Fin.cases with
+ | zero => simp [shift]
+ | succ i => simp [shift]
+
+omit [NeZero p] in
+theorem scan_output {k : ℕ} (digit reduction previous : Fin p)
+ (c b v : Vector p k) (out : List (Fin p)) (work : ℕ) :
+ let s := run digit reduction k ⟨List.ofFn c, List.ofFn b, List.ofFn v, out, previous, work⟩
+ s.output = (List.ofFn fun i => shift previous v i + reduction * c i + digit * b i).reverse ++ out ∧
+ s.work = work + 4 * k := by
+ induction k generalizing previous out work with
+ | zero => simp [run]
+ | succ k ih =>
+ rw [List.ofFn_succ (f := c), List.ofFn_succ (f := b), List.ofFn_succ (f := v)]
+ dsimp only [run, step]
+ rw [List.ofFn_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ rw [show shift previous v 0 = previous from rfl]
+ simp only [shift_tail]
+ obtain ⟨hrow, hcost⟩ := ih (v 0) (fun i => c i.succ) (fun i => b i.succ)
+ (fun i => v i.succ) ((previous + reduction * c 0 + digit * b 0) :: out) (work + 4)
+ exact ⟨hrow, by omega⟩
+
+/-- The counters measure prime-residue operations. Each round starts by
+negating the last limb and then executes the row scan. -/
+structure ProductState (p : ℕ) where
+ /-- Current product accumulator, stored as coefficients in increasing degree order between
+ Horner rounds. -/
+ coefficients : List (Fin p)
+ /-- Cumulative prime-residue operation count across completed Horner rounds. -/
+ work : ℕ
+
+/-- Process one Horner digit using the negated top accumulator coefficient for reduction, then
+reverse the new coefficient list. -/
+def round (c b : List (Fin p)) (s : ProductState p) (digit : Fin p) : ProductState p :=
+ let scanned := run digit (-s.coefficients.getLastD 0) c.length
+ ⟨c, b, s.coefficients, [], 0, s.work + 1⟩
+ ⟨scanned.output.reverse, scanned.work⟩
+
+theorem round_correct (c b v : Vector p e) (digit : Fin p) (work : ℕ) :
+ round (List.ofFn c) (List.ofFn b) ⟨List.ofFn v, work⟩ digit =
+ ⟨List.ofFn (add (companion c v) (scale digit b)), work + (4 * e + 1)⟩ := by
+ unfold round
+ rw [List.length_ofFn]
+ obtain ⟨hout, hwork⟩ := scan_output digit (-(List.ofFn v).getLastD 0) 0 c b v [] (work + 1)
+ dsimp only
+ rw [hout, hwork, List.append_nil, List.reverse_reverse]
+ congr 1
+ · congr 1
+ funext i
+ cases e with
+ | zero => exact i.elim0
+ | succ k =>
+ have hlast : (List.ofFn v).getLastD 0 = v (Fin.last k) := by
+ rw [List.ofFn_succ']
+ simp
+ rw [hlast]
+ rfl
+ · omega
+
+/-- The machine reads Horner digits from the highest degree down. -/
+def product (c a b : List (Fin p)) : ProductState p :=
+ a.reverse.foldl (round c b) ⟨List.replicate c.length 0, 0⟩
+
+private theorem fold_digits (c b : Vector p e) (digits : List (Fin p)) :
+ digits.reverse.foldl (round (List.ofFn c) (List.ofFn b)) ⟨List.ofFn (zero p e), 0⟩ =
+ ⟨List.ofFn (horner c b digits), digits.length * (4 * e + 1)⟩ := by
+ induction digits with
+ | nil => simp [horner]
+ | cons digit digits ih =>
+ rw [List.reverse_cons, List.foldl_append, ih]
+ simp only [List.foldl_cons, List.foldl_nil, round_correct, List.length_cons, Nat.succ_mul]
+ rfl
+
+/-- The complete stream multiplier returns the Horner product, performing
+exactly `e * (4 * e + 1)` prime-residue operations. -/
+theorem product_correct (c a b : Vector p e) :
+ product (List.ofFn c) (List.ofFn a) (List.ofFn b) =
+ ⟨List.ofFn (mul c a b), e * (4 * e + 1)⟩ := by
+ unfold product
+ have hz : List.ofFn (zero p e) = List.replicate e (0 : Fin p) := List.ofFn_const e 0
+ rw [List.length_ofFn, ← hz, mul]
+ simpa only [List.length_ofFn] using fold_digits c b (List.ofFn a)
+
+/-- Count the three persistent input lists conservatively in addition to all
+live scan limbs. The bound holds after any number of steps of any round. -/
+theorem scan_bits_le (c b v : Vector p e) (remaining : List (Fin p)) (h : remaining.length ≤ e)
+ (digit reduction : Fin p) (k work : ℕ) :
+ ((List.ofFn c).length + (List.ofFn b).length + remaining.length +
+ (run digit reduction k ⟨List.ofFn c, List.ofFn b, List.ofFn v, [], 0, work⟩).limbs) *
+ Nat.clog 2 p ≤ (6 * e + 3) * Nat.clog 2 p := by
+ apply Nat.mul_le_mul_right
+ have hscan := run_limbs_le digit reduction k
+ (⟨List.ofFn c, List.ofFn b, List.ofFn v, [], 0, work⟩ : ScanState p)
+ simp only [ScanState.limbs, List.length_ofFn, List.length_nil] at hscan ⊢
+ omega
+
+end SliceArithmetic.Stream
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceArithmeticZero.lean b/lean/OAI/Computability/VPVNP/SliceArithmeticZero.lean
new file mode 100644
index 0000000000..2e8ab4a72e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceArithmeticZero.lean
@@ -0,0 +1,133 @@
+import OAI.Computability.VPVNP.SliceArithmeticRound
+import OAI.Computability.VPVNP.RAMTapeWordDivision
+
+/-!
+# Testing a packed field element for zero
+
+A two-state bit scan records whether every bit is zero. It saves the input in
+reverse order on a scratch stack, then restores it before returning the single
+output bit. The running time depends only on the length of the packed input.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceArithmeticZero
+
+open RAMTape SliceArithmetic SliceArithmeticRound
+
+set_option backward.isDefEq.respectTransparency false in
+/-- Input, decision flag, and scratch ports of the packed scalar zero test. -/
+inductive Port where
+ | input | flag | scratch
+ deriving DecidableEq, Fintype
+
+/-- Finite control that tracks whether all bits seen so far are zero while reading, saving, and
+marking the result. -/
+inductive State where
+ | read (z : Bool) | save (z b : Bool) | mark (z : Bool)
+ deriving DecidableEq, Fintype
+
+private def scanBody : Routine Port State where
+ entry := .read true
+ code
+ | .read z => .pop .input fun
+ | none => some (.mark z)
+ | some b => some (.save (z && !b) b)
+ | .save z b => .push .scratch b (some (.read z))
+ | .mark z => .push .flag z none
+
+/-- After the scan, move the input back from scratch in its original order. -/
+def machine : FiniteRoutine Port :=
+ (FiniteRoutine.ofRoutine scanBody).followedBy (EvaluatorRadixDivision.reverseOnto .scratch .input)
+
+/-- The packed input, flag suffix, and saved bits at a stage of the zero-test scan. -/
+def frame (bits flag scratch : List Bool) : Stacks Port
+ | .input => bits
+ | .flag => flag
+ | .scratch => scratch
+
+private theorem updateInput (a b c v : List Bool) :
+ Function.update (frame a b c) .input v = frame v b c := by funext i; cases i <;> rfl
+
+private theorem updateFlag (a b c v : List Bool) :
+ Function.update (frame a b c) .flag v = frame a v c := by funext i; cases i <;> rfl
+
+private theorem updateScratch (a b c v : List Bool) :
+ Function.update (frame a b c) .scratch v = frame a b v := by funext i; cases i <;> rfl
+
+private theorem scan_run (bits flag scratch : List Bool) (z : Bool) :
+ StackRuns scanBody.standalone (2 * bits.length + 2) (some (.read z)) (frame bits flag scratch)
+ none (frame [] ((z && !(bits.any id)) :: flag) (bits.reverse ++ scratch)) := by
+ induction bits generalizing scratch z with
+ | nil =>
+ refine StackRuns.cons (.pop rfl) ?_
+ rw [updateInput]
+ refine StackRuns.cons (.push rfl) ?_
+ simp only [List.any_nil, Bool.not_false, Bool.and_true, List.reverse_nil, List.nil_append]
+ rw [updateFlag]
+ exact .nil ..
+ | cons b bits ih =>
+ rw [List.length_cons, Nat.mul_succ]
+ refine StackRuns.cons (.pop rfl) ?_
+ rw [updateInput]
+ refine StackRuns.cons (.push rfl) ?_
+ rw [updateScratch]
+ cases b with
+ | false => simpa [frame] using ih (false :: scratch) z
+ | true => simpa [frame] using ih (true :: scratch) false
+
+/-- One output bit, with the input restored and scratch empty. -/
+theorem machine_runs (bits flag : List Bool) :
+ machine.Runs (4 * bits.length + 3) (frame bits flag []) (frame bits ((!(bits.any id)) :: flag) []) := by
+ have hscan : scanBody.Runs (2 * bits.length + 2) (frame bits flag [])
+ (frame [] ((!(bits.any id)) :: flag) bits.reverse) := by
+ change StackRuns scanBody.standalone _ (some (State.read true)) _ none _
+ simpa using scan_run bits flag [] true
+ have hrestore := EvaluatorRadixDivision.reverseOnto_runs (src := Port.scratch) (dst := .input)
+ (by decide) (frame [] ((!(bits.any id)) :: flag) bits.reverse) (frame bits ((!(bits.any id)) :: flag) [])
+ rfl (by simp [frame]) (by intro i hi hj; cases i <;> simp_all [frame])
+ simpa only [machine, frame, List.length_reverse, show 2 * bits.length + 2 + (2 * bits.length + 1) =
+ 4 * bits.length + 3 by omega] using FiniteRoutine.Runs.followedBy (a := .ofRoutine scanBody) hscan hrestore
+
+private theorem any_packed_iff {p w : ℕ} [NeZero p] (hw : Word.workingWidth p ≤ w)
+ (xs : List (Fin p)) : (packed w xs).any id = true ↔ ∃ x ∈ xs, x ≠ 0 := by
+ induction xs with
+ | nil => simp [packed]
+ | cons a xs ih =>
+ change ((BurstRAM.wordBits (Word.limb w a)) ++ packed w xs).any id = true ↔ _
+ rw [List.any_append, Bool.or_eq_true, ih, TapeWord.anyBit_iff, TapeWord.value_wordBits, Word.limb_val hw]
+ have ha : 0 < a.val ↔ a ≠ 0 := by
+ rw [Nat.pos_iff_ne_zero]
+ exact not_congr ⟨fun h => Fin.ext h, fun h => h ▸ rfl⟩
+ rw [ha]
+ simp only [List.mem_cons, exists_eq_or_imp]
+
+/-- On a canonical scalar the flag is true precisely when its coefficient
+vector is zero. An arbitrary existing flag suffix is retained. -/
+theorem vector_runs {p e w : ℕ} [NeZero p] (hw : Word.workingWidth p ≤ w)
+ (v : Vector p e) (flag : List Bool) :
+ machine.Runs (4 * (e*w) + 3) (frame (packed w (List.ofFn v)) flag [])
+ (frame (packed w (List.ofFn v)) (decide (v = zero p e) :: flag) []) := by
+ have hbit : (!((packed w (List.ofFn v)).any id)) = decide (v = zero p e) := by
+ by_cases hz : v = zero p e
+ · have ha : (packed w (List.ofFn v)).any id ≠ true := by
+ intro h
+ obtain ⟨x, hx, hn⟩ := (any_packed_iff hw _).mp h
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hx
+ exact hn (hz ▸ rfl)
+ rw [Bool.eq_false_iff.mpr ha, decide_eq_true hz]
+ rfl
+ · have ha : (packed w (List.ofFn v)).any id = true := by
+ rw [any_packed_iff hw]
+ obtain ⟨i, hi⟩ := Function.ne_iff.mp hz
+ exact ⟨v i, List.mem_ofFn.mpr ⟨i, rfl⟩, hi⟩
+ simp [hz, ha]
+ simpa only [packed_length, List.length_ofFn, hbit] using machine_runs (packed w (List.ofFn v)) flag
+
+end SliceArithmeticZero
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceEvaluator.lean b/lean/OAI/Computability/VPVNP/SliceEvaluator.lean
new file mode 100644
index 0000000000..019527a3df
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceEvaluator.lean
@@ -0,0 +1,159 @@
+import OAI.Computability.VPVNP.Evaluator
+import OAI.Computability.VPVNP.FiniteSlice
+import OAI.Computability.VPVNP.MonomialBasis
+import Mathlib.FieldTheory.PrimitiveElement
+
+/-!
+# The path-counting evaluator on a finite geometric slice
+
+For a nonempty finite zero set, the quotient by its vanishing ideal supplies the labels in
+equation (8.2). A scan of the monomials through the point-count bound selects a basis
+starting with the unit. The coordinate at this unit, followed by the constant coordinate in
+a power basis of the slice field, gives the normalized functional. The number of accepting
+matrix-index paths for each exponent vector reduces to the value of that functional.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceEvaluator
+
+open FiniteSlice MonomialBasis Evaluator MvPolynomial
+
+/-- Enumerate all exponent tuples of total degree at most `N`, with the zero tuple
+first. Distinct tuples can give the same monomial value in the algebra. -/
+theorem exists_monomial_listing {L A : Type*} [Fintype L] [CommRing A] (X : L → A) (N : ℕ) :
+ ∃ m, ∃ listing : Fin (m + 1) → A, m + 1 ≤ (N + 1) ^ Fintype.card L ∧
+ Set.range listing = monomials X N ∧ listing 0 = 1 := by
+ classical
+ let B := {e : L → Fin (N + 1) // (∑ i, (e i).val) ≤ N}
+ let z : B := ⟨fun _ => 0, by simp⟩
+ let m := Fintype.card B - 1
+ have hcard : Fintype.card B = m + 1 := by
+ have := Fintype.card_pos_iff.mpr (show Nonempty B from ⟨z⟩)
+ dsimp [m]
+ omega
+ let u : Fin (m + 1) ≃ B := (Fintype.equivFinOfCardEq hcard).symm
+ let b := (Equiv.swap (0 : Fin (m + 1)) (u.symm z)).trans u
+ let val (e : B) := ∏ i, X i ^ (e.val i).val
+ refine ⟨m, val ∘ b, ?_, ?_, ?_⟩
+ · rw [← hcard]
+ simpa only [Fintype.card_fun, Fintype.card_fin] using
+ Fintype.card_le_of_injective (Subtype.val : B → (L → Fin (N + 1))) Subtype.val_injective
+ · ext a
+ constructor
+ · rintro ⟨j, rfl⟩
+ exact ⟨fun i => ((b j).val i).val, (b j).property, rfl⟩
+ · rintro ⟨e, hd, rfl⟩
+ have hle (i : L) : e i ≤ N :=
+ (Finset.single_le_sum (fun j _ => Nat.zero_le (e j)) (Finset.mem_univ i)).trans hd
+ let a : B := ⟨fun i => ⟨e i, Nat.lt_succ_of_le (hle i)⟩, hd⟩
+ exact ⟨b.symm a, by simp [a, val]⟩
+ · simp [b, z, val]
+
+variable {p : ℕ} [Fact p.Prime] {K E : Type*} [Field K] [Fintype K] [Field E]
+ [Algebra K E] [Algebra (ZMod p) K] {t : ℕ}
+
+/-- Constant coordinate of the prime-field power basis of the finite slice field. -/
+noncomputable def primeCoordinate (p : ℕ) [Fact p.Prime] (K : Type*) [Field K]
+ [Fintype K] [Algebra (ZMod p) K] : K →ₗ[ZMod p] ZMod p :=
+ let pb := Field.powerBasisOfFiniteOfSeparable (ZMod p) K
+ pb.basis.coord ⟨0, pb.dim_pos⟩
+
+theorem primeCoordinate_one : primeCoordinate p K 1 = 1 := by
+ let pb := Field.powerBasisOfFiniteOfSeparable (ZMod p) K
+ let u : Fin pb.dim := ⟨0, pb.dim_pos⟩
+ have h : pb.basis u = 1 := by simp [pb.basis_eq_pow, u]
+ change pb.basis.coord u 1 = 1
+ rw [← h, Module.Basis.coord_apply, Module.Basis.repr_self, Finsupp.single_eq_same]
+
+/-- The ordered monomial list, the retained independent entries, and the index of the unit. -/
+structure Presentation (K : Type*) [Field K] {E : Type*} [Field E] [Algebra K E]
+ (I : Ideal (MvPolynomial (Fin t) K)) (N : ℕ) where
+ /-- Last valid index in the finite list of monomials used to choose a basis of the coordinate
+ algebra. -/
+ lastIndex : ℕ
+ /-- Enumerate the coordinate monomials through degree `N`, with the constant monomial in
+ position zero. -/
+ listing : Fin (lastIndex + 1) → CoordinateAlgebra K (zeroLocus E I)
+ listing_range : Set.range listing = monomials (coordinateLabel (zeroLocus E I)) N
+ first_eq_one : listing 0 = 1
+ /-- Basis of the coordinate algebra formed by retaining each listed monomial that increases
+ the span of its predecessors. -/
+ basis : Module.Basis (RankQuery.greedyIndices K listing) K (CoordinateAlgebra K (zeroLocus E I))
+ basis_apply : ∀ i, basis i = listing i.val
+ /-- Greedy basis index of the constant monomial one, used to extract its coordinate in the
+ normalized functional. -/
+ unitIndex : RankQuery.greedyIndices K listing
+ unitIndex_val : unitIndex.val = 0
+
+/-- The selected basis of any listing of all bounded monomials beginning with one. -/
+theorem evaluator_for_listing (I : Ideal (MvPolynomial (Fin t) K))
+ [Fintype (zeroLocus E I)] [Nonempty (zeroLocus E I)] {N m : ℕ}
+ (hN : Fintype.card (zeroLocus E I) ≤ N)
+ (listing : Fin (m + 1) → CoordinateAlgebra K (zeroLocus E I))
+ (hlisting : Set.range listing = monomials (coordinateLabel (zeroLocus E I)) N)
+ (hfirst : listing 0 = 1) :
+ ∃ d : Presentation K I N (E := E), d.lastIndex = m ∧ HEq d.listing listing := by
+ let V := zeroLocus E I
+ let A := CoordinateAlgebra K V
+ obtain ⟨hfin, hdim⟩ := coordinateAlgebra_finite_finrank (E := E) I
+ let : Module.Finite K A := hfin
+ let : Nontrivial A := coordinateAlgebra_nontrivial V
+ obtain ⟨b, hb, u, hu, _⟩ := prefix_basis (coordinateLabel V) N
+ (adjoin_coordinateLabel V) (hdim.trans hN) listing hlisting hfirst
+ exact ⟨⟨m, listing, hlisting, hfirst, b, hb, u, hu⟩, rfl, HEq.rfl⟩
+
+variable {I : Ideal (MvPolynomial (Fin t) K)} {N : ℕ}
+
+/-- Coordinate on the unit of the slice algebra followed by the constant coefficient in the
+prime-field power basis of the slice field. -/
+noncomputable def Presentation.functional (d : Presentation K I N (E := E)) :
+ CoordinateAlgebra K (zeroLocus E I) →ₗ[ZMod p] ZMod p :=
+ primeFunctional d.basis d.unitIndex (primeCoordinate p K)
+
+/-- Integer number of the evaluator's successful matrix-index paths. -/
+noncomputable def Presentation.branchCount (p : ℕ) [Fact p.Prime] [Algebra (ZMod p) K]
+ (d : Presentation K I N (E := E)) (width : ℕ) (e : Fin t → ℕ) : ℕ :=
+ Fintype.card (AcceptingBranches.{0, _, 0} (primeCoordinate p K)
+ (transitionMatrices d.basis (digitProgram K (coordinateLabel (zeroLocus E I)) width e))
+ d.unitIndex d.unitIndex)
+
+theorem Presentation.functional_one (d : Presentation K I N (E := E)) :
+ d.functional (p := p) 1 = 1 := by
+ apply primeFunctional_one _ _ _ _ primeCoordinate_one
+ rw [d.basis_apply, d.unitIndex_val, d.first_eq_one]
+
+theorem Presentation.branchCount_mod (d : Presentation K I N (E := E))
+ (width : ℕ) (e : Fin t → ℕ) (he : ∀ i, e i < 2 ^ width) :
+ (d.branchCount p width e : ZMod p) =
+ d.functional (∏ i, coordinateLabel (zeroLocus E I) i ^ e i) := by
+ apply finiteAlgebra_pathCount _ _ _ _ _ _ _ he
+ rw [d.basis_apply, d.unitIndex_val, d.first_eq_one]
+
+/-- Given a finite nonempty slice, one basis and one normalized linear functional count
+every exponent vector, at every input width, and the chosen labels solve all the equations.
+The monomial listing has at most `(N + 1) ^ t` entries. -/
+theorem exists_sliceEvaluator (p : ℕ) [Fact p.Prime] [Algebra (ZMod p) K]
+ (I : Ideal (MvPolynomial (Fin t) K)) [Fintype (zeroLocus E I)] [Nonempty (zeroLocus E I)]
+ {N : ℕ} (hN : Fintype.card (zeroLocus E I) ≤ N) :
+ ∃ d : Presentation K I N (E := E), d.lastIndex + 1 ≤ (N + 1) ^ t ∧
+ d.functional (p := p) 1 = 1 ∧
+ (∀ f ∈ I, MvPolynomial.aeval (coordinateLabel (K := K) (zeroLocus E I)) f = 0) ∧
+ ∀ width (e : Fin t → ℕ), (∀ i, e i < 2 ^ width) →
+ (d.branchCount p width e : ZMod p) =
+ d.functional (∏ i, coordinateLabel (zeroLocus E I) i ^ e i) := by
+ obtain ⟨m, list, hbound, hrange, hfirst⟩ := exists_monomial_listing
+ (coordinateLabel (K := K) (zeroLocus E I)) N
+ obtain ⟨d, hd, _⟩ := evaluator_for_listing I hN list hrange hfirst
+ refine ⟨d, by simpa [hd] using hbound, d.functional_one, ?_, d.branchCount_mod⟩
+ intro f hf
+ rw [aeval_coordinateLabel]
+ exact equation_eq_zero I f hf
+
+end SliceEvaluator
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceField.lean b/lean/OAI/Computability/VPVNP/SliceField.lean
new file mode 100644
index 0000000000..e5a9648802
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceField.lean
@@ -0,0 +1,108 @@
+import OAI.Computability.VPVNP.RAMSerialization
+import Mathlib.FieldTheory.Finite.GaloisField
+import Mathlib.FieldTheory.IsAlgClosed.Basic
+import Mathlib.FieldTheory.PrimitiveElement
+
+/-!
+# A finite slice field and its defining polynomial
+
+Section 8.2 uses the smallest positive extension degree of the prime field
+whose cardinality `Q` exceeds twice the point-count bound `N`. A monic
+irreducible polynomial gives a presentation of that extension, using at most
+`2 log₂ Q` bits for all coefficients below its leading term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceField
+
+open Polynomial
+
+/-- Smallest positive degree giving a prime-power cardinality above `2 * N`. -/
+def extensionDegree (p N : ℕ) := Nat.log p (2 * N) + 1
+
+/-- The selected extension of the prime field. -/
+abbrev FieldOf (p N : ℕ) [Fact p.Prime] := GaloisField p (extensionDegree p N)
+
+theorem field_card (p N : ℕ) [Fact p.Prime] :
+ Nat.card (FieldOf p N) = p ^ extensionDegree p N :=
+ GaloisField.card p _ (Nat.succ_ne_zero _)
+
+theorem field_card_gt (p N : ℕ) [Fact p.Prime] : 2 * N < Nat.card (FieldOf p N) := by
+ rw [field_card]
+ exact Nat.lt_pow_succ_log_self (Fact.out : p.Prime).one_lt _
+
+theorem extensionDegree_minimal (p : ℕ) [Fact p.Prime] {N e : ℕ} (hN : 0 < N)
+ (h : 2 * N < p ^ e) : extensionDegree p N ≤ e :=
+ (Nat.log_lt_iff_lt_pow (Fact.out : p.Prime).one_lt (by positivity : 2 * N ≠ 0)).mpr h
+
+theorem field_card_le (p : ℕ) [Fact p.Prime] {N : ℕ} (hN : 0 < N) :
+ Nat.card (FieldOf p N) ≤ 2 * N * p := by
+ rw [field_card, extensionDegree, pow_succ]
+ exact Nat.mul_le_mul_right _ (Nat.pow_log_le_self _ (by positivity))
+
+/-- Embed the advised field in the ambient algebraic closure for the hyperplane cuts. -/
+noncomputable def embed (p N : ℕ) [Fact p.Prime] (E : Type*) [Field E] [Algebra (ZMod p) E]
+ [IsAlgClosed E] : FieldOf p N →ₐ[ZMod p] E :=
+ IsAlgClosed.lift
+
+/-- Read the low coefficients of a monic polynomial from fixed-width binary words. -/
+noncomputable def polynomialOfBits (p e : ℕ) (bits : Fin (e * Nat.clog 2 p) → Bool) : (ZMod p)[X] :=
+ let words := (RAMSerialization.arrayBits e (Nat.clog 2 p)).symm bits
+ X ^ e + ∑ i : Fin e, C ((words i).val : ZMod p) * X ^ i.val
+
+/-- The field description encodes the minimal polynomial of a power-basis generator
+and hence defines the selected field up to prime-field algebra isomorphism. -/
+theorem exists_polynomial_advice (p N : ℕ) [Fact p.Prime] :
+ let e := extensionDegree p N
+ ∃ bits : Fin (e * Nat.clog 2 p) → Bool,
+ let f := polynomialOfBits p e bits
+ f.Monic ∧ Irreducible f ∧ f.natDegree = e ∧ Nonempty (AdjoinRoot f ≃ₐ[ZMod p] FieldOf p N) := by
+ let e := extensionDegree p N
+ let pb := Field.powerBasisOfFiniteOfSeparable (ZMod p) (FieldOf p N)
+ let f := minpoly (ZMod p) pb.gen
+ have hdeg : f.natDegree = e := pb.natDegree_minpoly.trans <|
+ pb.finrank.symm.trans (GaloisField.finrank p (Nat.succ_ne_zero _))
+ have hmonic : f.Monic := minpoly.monic pb.isIntegral_gen
+ let words (i : Fin e) : BurstRAM.Word (Nat.clog 2 p) :=
+ ⟨(f.coeff i.val).val, (ZMod.val_lt _).trans_le (Nat.le_pow_clog (by decide) _)⟩
+ let bits := RAMSerialization.arrayBits _ _ words
+ have hbits : polynomialOfBits p e bits = f := by
+ rw [polynomialOfBits]
+ simp only [bits, Equiv.symm_apply_apply, words, ZMod.natCast_zmod_val]
+ conv_rhs => rw [hmonic.as_sum, hdeg]
+ congr 1
+ exact Fin.sum_univ_eq_sum_range (fun i ↦ C (f.coeff i) * X ^ i) _
+ refine ⟨bits, ?_⟩
+ change (polynomialOfBits p e bits).Monic ∧ _
+ rw [hbits]
+ exact ⟨hmonic, minpoly.irreducible pb.isIntegral_gen, hdeg,
+ ⟨AdjoinRoot.equiv' f pb (by rw [AdjoinRoot.aeval_eq, AdjoinRoot.mk_self]) (minpoly.aeval _ _)⟩⟩
+
+/-- The complete binary advice for the monic polynomial has length at most twice
+the base-two logarithm of the cardinality of the selected field. -/
+theorem advice_length_le (p N : ℕ) [Fact p.Prime] :
+ extensionDegree p N * Nat.clog 2 p ≤ 2 * Nat.log 2 (Nat.card (FieldOf p N)) := by
+ let e := extensionDegree p N
+ have hp := (Fact.out : p.Prime).two_le
+ have hlog : 1 ≤ Nat.log 2 p := Nat.le_log_of_pow_le (by decide) (by simpa using hp)
+ have hclog : Nat.clog 2 p ≤ Nat.log 2 p + 1 :=
+ Nat.clog_le_of_le_pow (Nat.lt_pow_succ_log_self (by decide : 1 < 2) p).le
+ have hexp : Nat.log 2 p * e ≤ Nat.log 2 (p ^ e) := by
+ apply Nat.le_log_of_pow_le (by decide)
+ rw [pow_mul]
+ exact Nat.pow_le_pow_left (Nat.pow_log_le_self _ (by omega)) _
+ rw [field_card]
+ change e * Nat.clog 2 p ≤ 2 * Nat.log 2 (p ^ e)
+ calc
+ _ ≤ e * (2 * Nat.log 2 p) := Nat.mul_le_mul_left _ (by omega)
+ _ = 2 * (Nat.log 2 p * e) := by ring
+ _ ≤ _ := Nat.mul_le_mul_left _ hexp
+
+end SliceField
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceGeometry.lean b/lean/OAI/Computability/VPVNP/SliceGeometry.lean
new file mode 100644
index 0000000000..b756f99daf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceGeometry.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.SliceGeometryPencil
+import OAI.Computability.VPVNP.SliceGeometryProjection
+import Mathlib.RingTheory.Nullstellensatz
+
+/-!
+# A nonempty finite geometric slice with short affine cuts
+
+Section 8.2 needs a finite geometric slice whose cardinality and base-field
+cardinality have polynomial bit length. The construction here uses the same
+effective weak Nullstellensatz bound `H` needed for characteristic descent.
+A one-parameter Macaulay matrix detects each coordinate image. Outside the
+exceptional roots of two minors its rank comparison is constant. Coordinate
+pins consequently suffice to produce a finite slice.
+
+The resulting point bound is `(2 * (H + d + 1)^t)^t`. Section 8.2's
+projective Bézout argument gives the sharper bound `d^(t+1)`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceGeometry
+
+open MvPolynomial RadicalCertificate
+
+variable {K E : Type*} [Field K] [Fintype K] [Field E] [Algebra K E]
+variable {ι : Type*} [Fintype ι] {t : ℕ}
+
+/-- A monotone upper bound on the exceptional scalar count, independent of
+the pins already chosen. -/
+def projectionBound (t H d : ℕ) := 2 * (H + d + 1) ^ t
+
+/-- The resulting point-count bound has at most `(tL+1)t+1` binary digits if
+`H+d+1 ≤ 2^L`. -/
+theorem projectionBound_pow_le {H d L : ℕ} (hL : H + d + 1 ≤ 2 ^ L) :
+ projectionBound t H d ^ t ≤ 2 ^ ((L * t + 1) * t) := by
+ rw [pow_mul]
+ apply Nat.pow_le_pow_left
+ dsimp [projectionBound]
+ rw [pow_succ, pow_mul, Nat.mul_comm _ 2]
+ exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hL t)
+
+/-- The ideal of the original system and the selected affine coordinate equations. -/
+noncomputable def pinnedIdeal (F : ι → MvPolynomial (Fin t) K) (s : Finset (Fin t))
+ (a : Fin t → K) : Ideal (MvPolynomial (Fin t) K) :=
+ Ideal.span (Set.range (pinnedEquations F s a))
+
+omit [Fintype K] [Fintype ι] in
+theorem zeroLocus_pinnedIdeal (F : ι → MvPolynomial (Fin t) K) (s : Finset (Fin t))
+ (a : Fin t → K) : zeroLocus E (pinnedIdeal F s a) =
+ pinnedPoints {y : Fin t → E | ∀ j, aeval y (F j) = 0} s a := by
+ ext x
+ rw [pinnedIdeal, zeroLocus_span, mem_pinnedPoints_iff]
+ simp only [Set.mem_ofPred_eq, Set.forall_mem_range, geometricPinnedEquations, eval_map, aeval_def]
+
+/-- A coordinate pinning with at most `t` base-field coefficients gives a
+nonempty finite geometric zero set of explicitly bounded cardinality. -/
+theorem exists_finite_coordinate_slice (F : ι → MvPolynomial (Fin t) K) {H d : ℕ}
+ (hF : ∀ i, (F i).totalDegree ≤ d) (hd : 1 ≤ d)
+ (hK : projectionBound t H d < Fintype.card K)
+ (hsol : ∃ x : Fin t → E, ∀ i, aeval x (F i) = 0)
+ (bound : WeakCertificateBound E (Option (ι ⊕ Fin t)) t d H) :
+ ∃ (s : Finset (Fin t)) (a : Fin t → K),
+ let V := zeroLocus E (pinnedIdeal F s a)
+ V.Nonempty ∧ V.Finite ∧ V.ncard ≤ projectionBound t H d ^ t := by
+ let B := projectionBound t H d
+ let W := {y : Fin t → E | ∀ j, aeval y (F j) = 0}
+ have hbound : 2 * Fintype.card (BoundedMonomial t (H + d)) ≤ B :=
+ Nat.mul_le_mul_left _ (card_boundedMonomial_le t (H + d))
+ have hproj (s : Finset (Fin t)) (a : Fin t → K) (i : Fin t) :
+ boundedOrCobounded (coordinateImage (pinnedPoints W s a) i) B := by
+ let G := geometricPinnedEquations (E := E) F s a
+ let M := coordinatePencil G i H (H + d)
+ let N := augmentedCoordinatePencil G i H (H + d)
+ have he : coordinateImage (pinnedPoints W s a) i =
+ {c | (M.map (Polynomial.eval c)).rank < (N.map (Polynomial.eval c)).rank} :=
+ Set.ext (fun c => mem_pinnedCoordinateImage_iff_rank_lt F s a i c hF hd bound)
+ rw [he]
+ have h := boundedOrCobounded_rank_lt M N (coordinatePencil_degree_le G i H (H + d))
+ (augmentedCoordinatePencil_degree_le G i H (H + d))
+ exact h.imp (fun ⟨hf, hc⟩ => ⟨hf, hc.trans hbound⟩) (fun ⟨hf, hc⟩ => ⟨hf, hc.trans hbound⟩)
+ obtain ⟨s, a, hn, hf, hc⟩ := exists_finite_pinned_slice W hsol B
+ (by dsimp [B, projectionBound]; positivity) hK hproj
+ exact ⟨s, a, by simpa only [zeroLocus_pinnedIdeal] using And.intro hn (And.intro hf hc)⟩
+
+end SliceGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceGeometryPencil.lean b/lean/OAI/Computability/VPVNP/SliceGeometryPencil.lean
new file mode 100644
index 0000000000..4159d32d71
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceGeometryPencil.lean
@@ -0,0 +1,112 @@
+import OAI.Computability.VPVNP.GreedyBasis
+import OAI.Computability.VPVNP.RankMinors
+import OAI.Computability.VPVNP.SliceGeometryPinning
+import Mathlib.Algebra.Polynomial.Roots
+
+/-!
+# Exceptional parameters for matrices of affine polynomials
+
+A maximal-rank specialization supplies a nonzero minor. Its determinant
+remains nonzero off at most one exceptional scalar per column, because the
+matrix entries have degree at most one. Comparing two such ranks therefore
+gives a bounded or cobounded parameter set.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceGeometry
+
+open VPVNP.Crossing VPVNP.RankQuery
+open scoped Polynomial
+
+variable {E : Type*} [Field E]
+
+private theorem natDegree_det_le_card {q : ℕ} (M : Matrix (Fin q) (Fin q) E[X])
+ (hd : ∀ i j, (M i j).natDegree ≤ 1) : M.det.natDegree ≤ q := by
+ rw [Matrix.det_apply]
+ apply Polynomial.natDegree_sum_le_of_forall_le
+ intro σ _
+ apply (Polynomial.natDegree_smul_le _ _).trans
+ calc
+ _ ≤ ∑ i, (M (σ i) i).natDegree := Polynomial.natDegree_prod_le _ _
+ _ ≤ ∑ _ : Fin q, 1 := Finset.sum_le_sum (fun i _ => hd (σ i) i)
+ _ = _ := by simp
+
+/-- The rank is constant away from at most `#J` parameters. This also covers
+empty matrices and finite fields. -/
+theorem exists_generic_rank {I J : Type*} [Fintype I] [Fintype J]
+ (M : Matrix I J E[X]) (hd : ∀ i j, (M i j).natDegree ≤ 1) :
+ ∃ (r : ℕ) (S : Finset E), S.card ≤ Fintype.card J ∧
+ ∀ c ∉ S, (M.map (Polynomial.eval c)).rank = r := by
+ classical
+ let ρ (c : E) := (M.map (Polynomial.eval c)).rank
+ have hb : BddAbove (Set.range ρ) :=
+ ⟨Fintype.card J, fun _ ⟨c, h⟩ => h ▸ (M.map (Polynomial.eval c)).rank_le_card_width⟩
+ obtain ⟨c₀, hc⟩ := Nat.sSup_mem (Set.range_nonempty ρ) hb
+ have hmax (c : E) : ρ c ≤ ρ c₀ := hc ▸ le_csSup hb (Set.mem_range_self c)
+ let e := (Fintype.equivFin I).symm
+ let f := (Fintype.equivFin J).symm
+ let A := (M.map (Polynomial.eval c₀)).submatrix e f
+ have hr : A.rank = ρ c₀ := Matrix.rank_submatrix _ _ _
+ obtain ⟨U, hu, _⟩ := exists_isolatedBasis E A.row (hr.symm.trans A.rank_eq_finrank_span_row)
+ obtain ⟨V, hv, _⟩ := exists_isolatedBasis E A.col (hr.symm.trans A.rank_eq_finrank_span_cols)
+ have hn := (compound_ne_zero_iff A hr U V).mpr ⟨hu, hv⟩
+ let rows := e ∘ Set.powersetCard.ofFinEmbEquiv.symm U
+ let cols := f ∘ Set.powersetCard.ofFinEmbEquiv.symm V
+ let N := M.submatrix rows cols
+ let D := N.det
+ have he (c : E) : D.eval c = ((M.map (Polynomial.eval c)).submatrix rows cols).det :=
+ (Polynomial.evalRingHom c).map_det N
+ have hD : D ≠ 0 := by
+ intro h0
+ apply hn
+ change ((M.map (Polynomial.eval c₀)).submatrix rows cols).det = 0
+ rw [← he, h0, Polynomial.eval_zero]
+ refine ⟨ρ c₀, D.roots.toFinset, (Multiset.toFinset_card_le _).trans ((Polynomial.card_roots' D).trans
+ ((natDegree_det_le_card N (fun i j => hd (rows i) (cols j))).trans
+ (M.map (Polynomial.eval c₀)).rank_le_card_width)), fun c h => ?_⟩
+ apply le_antisymm (hmax c)
+ have hdet : ((M.map (Polynomial.eval c)).submatrix rows cols).det ≠ 0 := by
+ rw [← he]
+ exact fun hz => h (Multiset.mem_toFinset.mpr ((Polynomial.mem_roots hD).mpr hz))
+ have hle := (M.map (Polynomial.eval c)).rank_submatrix_le rows cols
+ rwa [Matrix.rank_of_det_ne_zero hdet, Fintype.card_fin] at hle
+
+/-- The strict rank comparison of two affine polynomial matrices with the same
+column type holds at finitely many parameters or at all but finitely many. -/
+theorem boundedOrCobounded_rank_lt {I L J : Type*} [Fintype I] [Fintype L] [Fintype J]
+ (M : Matrix I J E[X]) (N : Matrix L J E[X])
+ (hm : ∀ i j, (M i j).natDegree ≤ 1) (hn : ∀ i j, (N i j).natDegree ≤ 1) :
+ boundedOrCobounded {c : E | (M.map (Polynomial.eval c)).rank < (N.map (Polynomial.eval c)).rank}
+ (2 * Fintype.card J) := by
+ classical
+ obtain ⟨r, S, hs, hr⟩ := exists_generic_rank M hm
+ obtain ⟨q, T, ht, hq⟩ := exists_generic_rank N hn
+ let U := S ∪ T
+ have hU : (U : Set E).ncard ≤ 2 * Fintype.card J := by
+ rw [Set.ncard_coe_finset, two_mul]
+ exact (Finset.card_union_le _ _).trans (Nat.add_le_add hs ht)
+ have hcmp (c : E) (hc : c ∉ U) :
+ (M.map (Polynomial.eval c)).rank < (N.map (Polynomial.eval c)).rank ↔ r < q := by
+ rw [hr c (fun h => hc (Finset.mem_union_left _ h)), hq c (fun h => hc (Finset.mem_union_right _ h))]
+ by_cases hlt : r < q
+ · right
+ have hsub : {c : E | (M.map (Polynomial.eval c)).rank < (N.map (Polynomial.eval c)).rank}ᶜ ⊆ U := by
+ intro c hc
+ by_contra h
+ exact hc ((hcmp c h).mpr hlt)
+ exact ⟨U.finite_toSet.subset hsub, (Set.ncard_le_ncard hsub).trans hU⟩
+ · left
+ have hsub : {c : E | (M.map (Polynomial.eval c)).rank < (N.map (Polynomial.eval c)).rank} ⊆ U := by
+ intro c hc
+ by_contra h
+ exact hlt ((hcmp c h).mp hc)
+ exact ⟨U.finite_toSet.subset hsub, (Set.ncard_le_ncard hsub).trans hU⟩
+
+end SliceGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceGeometryPinning.lean b/lean/OAI/Computability/VPVNP/SliceGeometryPinning.lean
new file mode 100644
index 0000000000..b7ec97eeea
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceGeometryPinning.lean
@@ -0,0 +1,136 @@
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+import Mathlib.Data.Fintype.BigOperators
+import Mathlib.Data.Set.Card
+import Mathlib.Algebra.Field.Basic
+import Mathlib.Algebra.Algebra.Basic
+import Mathlib.RingTheory.SimpleRing.Basic
+
+/-!
+# Finite slices from coordinate projections
+
+For a coordinate image that is cofinite in the algebraic closure, pin that
+coordinate to a base-field value in the image. Finite coordinate images only
+shrink during later cuts. If each exceptional set has at most `B` elements and
+`B < #K`, at most one pin per variable produces a nonempty slice with at most
+`B^t` geometric points.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceGeometry
+
+open Set
+
+variable {K E : Type*} [Field K] [Field E] [Algebra K E] {t : ℕ}
+
+/-- Geometric points satisfying the original equations and a set of base-field
+coordinate pins. -/
+def pinnedPoints (V : Set (Fin t → E)) (s : Finset (Fin t)) (a : Fin t → K) : Set (Fin t → E) :=
+ {x | x ∈ V ∧ ∀ i ∈ s, x i = algebraMap K E (a i)}
+
+/-- The possible values of coordinate `i` on a geometric set. -/
+def coordinateImage (V : Set (Fin t → E)) (i : Fin t) : Set E := (fun x => x i) '' V
+
+/-- A coordinate image has at most `B` points, or its complement has at most
+`B` points. The finite-set hypotheses distinguish these alternatives even when
+`Set.ncard` would vanish on an infinite set. -/
+def boundedOrCobounded (S : Set E) (B : ℕ) : Prop :=
+ (S.Finite ∧ S.ncard ≤ B) ∨ (Sᶜ.Finite ∧ Sᶜ.ncard ≤ B)
+
+private theorem exists_base_point [Fintype K] {S : Set E} {B : ℕ}
+ (h : Sᶜ.Finite) (hc : Sᶜ.ncard ≤ B) (hB : B < Fintype.card K) :
+ ∃ c : K, algebraMap K E c ∈ S := by
+ by_contra! hall
+ let f (c : K) : ↥(Sᶜ) := ⟨algebraMap K E c, hall c⟩
+ let : Finite ↥(Sᶜ) := finite_coe_iff.mpr h
+ have hle := Nat.card_le_card_of_injective f (fun _ _ he => (algebraMap K E).injective
+ (congrArg Subtype.val he))
+ change Nat.card K ≤ Sᶜ.ncard at hle
+ exact hB.not_ge ((Nat.card_eq_fintype_card (α := K)) ▸ hle.trans hc)
+
+private theorem insert_pin (V : Set (Fin t → E)) (s : Finset (Fin t)) (a : Fin t → K)
+ (i : Fin t) (hi : i ∉ s) (c : K) :
+ pinnedPoints V (insert i s) (Function.update a i c) =
+ pinnedPoints V s a ∩ {x | x i = algebraMap K E c} := by
+ ext x
+ constructor
+ · rintro ⟨hv, hx⟩
+ refine ⟨⟨hv, fun j hj => ?_⟩, ?_⟩
+ · have hji : j ≠ i := fun e => hi (e ▸ hj)
+ simpa only [Function.update_of_ne hji] using hx j (Finset.mem_insert_of_mem hj)
+ · change x i = algebraMap K E c
+ simpa only [Function.update_self] using hx i (Finset.mem_insert_self ..)
+ · rintro ⟨⟨hv, hx⟩, hc⟩
+ refine ⟨hv, fun j hj => ?_⟩
+ rcases Finset.mem_insert.mp hj with rfl | hs
+ · change x j = algebraMap K E c at hc
+ simpa only [Function.update_self] using hc
+ · have hji : j ≠ i := fun e => hi (e ▸ hs)
+ rw [Function.update_of_ne hji]
+ exact hx j hs
+
+omit [Field E] in
+private theorem bounded_set_of_coordinate_images {W : Set (Fin t → E)} {B : ℕ}
+ (h : ∀ i, (coordinateImage W i).Finite ∧ (coordinateImage W i).ncard ≤ B) :
+ W.Finite ∧ W.ncard ≤ B ^ t := by
+ classical
+ let target (i : Fin t) := coordinateImage W i
+ let (i : Fin t) : Finite (target i) := finite_coe_iff.mpr (h i).1
+ let f (x : W) (i : Fin t) : target i := ⟨x.val i, ⟨x.val, x.prop, rfl⟩⟩
+ have hf : Function.Injective f := fun u v he => Subtype.ext (funext fun i =>
+ congrArg Subtype.val (congrFun he i))
+ refine ⟨finite_coe_iff.mp (Finite.of_injective f hf), ?_⟩
+ calc
+ W.ncard ≤ Nat.card ((i : Fin t) → target i) := Nat.card_le_card_of_injective f hf
+ _ = ∏ i, (coordinateImage W i).ncard := Nat.card_pi
+ _ ≤ ∏ _ : Fin t, B := Finset.prod_le_prod (fun i _ => (h i).2)
+ _ = B ^ t := by simp
+
+/-- At most `t` distinct coordinate equations suffice when every projection of
+a partially pinned system has a bounded exceptional set. -/
+theorem exists_finite_pinned_slice [Fintype K] (V : Set (Fin t → E)) (hv : V.Nonempty)
+ (B : ℕ) (hpos : 0 < B) (hB : B < Fintype.card K)
+ (hproj : ∀ (s : Finset (Fin t)) (a : Fin t → K) (i : Fin t),
+ boundedOrCobounded (coordinateImage (pinnedPoints V s a) i) B) :
+ ∃ (s : Finset (Fin t)) (a : Fin t → K),
+ let W := pinnedPoints V s a
+ W.Nonempty ∧ W.Finite ∧ W.ncard ≤ B ^ t := by
+ classical
+ have build (T : Finset (Fin t)) : ∃ (s : Finset (Fin t)) (a : Fin t → K), s ⊆ T ∧
+ let W := pinnedPoints V s a
+ W.Nonempty ∧ ∀ i ∈ T, (coordinateImage W i).Finite ∧ (coordinateImage W i).ncard ≤ B := by
+ induction T using Finset.induction_on with
+ | empty =>
+ exact ⟨∅, 0, le_rfl, by simpa [pinnedPoints] using hv, by simp⟩
+ | @insert i T hi ih =>
+ obtain ⟨s, a, hs, hw, hbound⟩ := ih
+ let W := pinnedPoints V s a
+ rcases hproj s a i with hfin | ⟨hco, hsize⟩
+ · refine ⟨s, a, hs.trans (Finset.subset_insert ..), hw, fun j hj => ?_⟩
+ rcases Finset.mem_insert.mp hj with rfl | hT
+ · exact hfin
+ · exact hbound j hT
+ · obtain ⟨c, x, hx, he⟩ := exists_base_point hco hsize hB
+ let W' := pinnedPoints V (insert i s) (Function.update a i c)
+ have hW : W' = W ∩ {y | y i = algebraMap K E c} :=
+ insert_pin V s a i (fun hm => hi (hs hm)) c
+ refine ⟨insert i s, Function.update a i c, Finset.insert_subset_insert _ hs,
+ ⟨x, (show x ∈ W' from hW.symm ▸ ⟨hx, he⟩)⟩, fun j hj => ?_⟩
+ rcases Finset.mem_insert.mp hj with rfl | hT
+ · have hsub : coordinateImage W' j ⊆ {algebraMap K E c} := by
+ rintro _ ⟨y, hy, rfl⟩
+ exact (hW ▸ hy).2
+ exact ⟨(finite_singleton _).subset hsub, (ncard_le_ncard hsub).trans (by simpa using (Nat.succ_le_of_lt hpos))⟩
+ · have hsub : coordinateImage W' j ⊆ coordinateImage W j :=
+ image_mono (hW.symm ▸ inter_subset_left)
+ exact ⟨(hbound j hT).1.subset hsub, (ncard_le_ncard hsub (hbound j hT).1).trans (hbound j hT).2⟩
+ obtain ⟨s, a, _, hn, hb⟩ := build Finset.univ
+ exact ⟨s, a, hn, bounded_set_of_coordinate_images (fun i => hb i (Finset.mem_univ _))⟩
+
+end SliceGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SliceGeometryProjection.lean b/lean/OAI/Computability/VPVNP/SliceGeometryProjection.lean
new file mode 100644
index 0000000000..c9d4eb72d3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SliceGeometryProjection.lean
@@ -0,0 +1,226 @@
+import OAI.Computability.VPVNP.MacaulayReduction
+import OAI.Computability.VPVNP.SliceGeometryPinning
+
+/-!
+# Coordinate projections through a Macaulay matrix pencil
+
+Adjoin the equation `X_i - c = 0` to a finite polynomial system, first with
+an indeterminate in place of `c`. The resulting Macaulay matrix has entries
+of degree at most one in the parameter. Under the uniform weak Nullstellensatz
+bound, the coordinate image of the common zero set consists precisely of the
+parameters where adjoining the coefficient row of one increases rank.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SliceGeometry
+
+open MvPolynomial RadicalCertificate
+open scoped Polynomial
+
+variable {ι : Type*} {t : ℕ}
+
+/-- Adjoin the equation fixing the selected coordinate to the parameter. -/
+noncomputable def coordinateEquations {R : Type*} [CommRing R]
+ (F : ι → MvPolynomial (Fin t) R) (i : Fin t) (c : R) :
+ Option ι → MvPolynomial (Fin t) R :=
+ Option.elim' (X i - C c) F
+
+variable {E : Type*} [Field E]
+
+/-- The Macaulay matrix over the univariate parameter ring. -/
+noncomputable def coordinatePencil (F : ι → MvPolynomial (Fin t) E) (i : Fin t) (H D : ℕ) :
+ Matrix (Option ι × BoundedMonomial t H) (BoundedMonomial t D) E[X] :=
+ macaulayMatrix (coordinateEquations (fun j => map Polynomial.C (F j)) i Polynomial.X) H D
+
+/-- Augment the matrix pencil by the constant coefficient row of one. -/
+noncomputable def augmentedCoordinatePencil (F : ι → MvPolynomial (Fin t) E) (i : Fin t)
+ (H D : ℕ) :
+ Matrix (Option (Option ι × BoundedMonomial t H)) (BoundedMonomial t D) E[X] :=
+ Option.elim' (fun j => Polynomial.C (coefficientRow D (1 : MvPolynomial (Fin t) E) j))
+ (coordinatePencil F i H D)
+
+/-- Specialization at `c` gives exactly the bounded coefficient matrix of the
+original equations and the fiber equation `X_i - c`. -/
+theorem coordinatePencil_eval (F : ι → MvPolynomial (Fin t) E) (i : Fin t)
+ (H D : ℕ) (c : E) :
+ (coordinatePencil F i H D).map (Polynomial.eval c) =
+ macaulayMatrix (coordinateEquations F i c) H D := by
+ let φ := Polynomial.evalRingHom c
+ change (macaulayMatrix _ H D).map φ = _
+ rw [← CertificateReduction.macaulayMatrix_map]
+ congr 1
+ funext j
+ cases j with
+ | none => simp [coordinateEquations, φ]
+ | some j =>
+ change map φ (map Polynomial.C (F j)) = F j
+ rw [map_map, show φ.comp Polynomial.C = RingHom.id E from by ext; simp [φ], map_id]
+
+/-- The indeterminate enters the coordinate fiber equation linearly. -/
+theorem coordinatePencil_degree_le (F : ι → MvPolynomial (Fin t) E) (i : Fin t) (H D : ℕ)
+ (r : Option ι × BoundedMonomial t H) (j : BoundedMonomial t D) :
+ (coordinatePencil F i H D r j).natDegree ≤ 1 := by
+ classical
+ rw [coordinatePencil, macaulayMatrix_apply]
+ split_ifs with h
+ · rcases r with ⟨(_ | a), b⟩
+ · change ((X i - C (Polynomial.X : E[X])).coeff _).natDegree ≤ 1
+ rw [coeff_sub, coeff_X, coeff_C]
+ apply (Polynomial.natDegree_sub_le ..).trans (max_le _ _)
+ · split_ifs <;> simp
+ · split_ifs <;> simp
+ · change ((map Polynomial.C (F a)).coeff _).natDegree ≤ 1
+ rw [coeff_map]
+ simp
+ · simp
+
+theorem augmentedCoordinatePencil_degree_le (F : ι → MvPolynomial (Fin t) E) (i : Fin t)
+ (H D : ℕ) (r : Option (Option ι × BoundedMonomial t H)) (j : BoundedMonomial t D) :
+ (augmentedCoordinatePencil F i H D r j).natDegree ≤ 1 := by
+ cases r with
+ | none =>
+ change (Polynomial.C _).natDegree ≤ 1
+ simp
+ | some r => exact coordinatePencil_degree_le F i H D r j
+
+private theorem coordinateEquations_degree_le (F : ι → MvPolynomial (Fin t) E)
+ {d : ℕ} (hF : ∀ a, (F a).totalDegree ≤ d) (hd : 1 ≤ d) (i : Fin t) (c : E)
+ (a : Option ι) : (coordinateEquations F i c a).totalDegree ≤ d := by
+ cases a with
+ | some a => exact hF a
+ | none =>
+ apply (mem_restrictTotalDegree ..).mp
+ apply Submodule.sub_mem
+ · exact (mem_restrictTotalDegree ..).mpr (by simpa using hd)
+ · exact (mem_restrictTotalDegree ..).mpr (by simp)
+
+/-- The coordinate image is detected by failure of the bounded certificate
+row test. The forward direction holds for any multiplier bound. -/
+theorem coordinateImage_iff_row_notMem [Fintype ι] (F : ι → MvPolynomial (Fin t) E)
+ (i : Fin t) (c : E) {H d : ℕ} (hF : ∀ a, (F a).totalDegree ≤ d) (hd : 1 ≤ d)
+ (bound : WeakCertificateBound E (Option ι) t d H) :
+ (∃ x : Fin t → E, (∀ a, eval x (F a) = 0) ∧ x i = c) ↔
+ coefficientRow (H + d) (1 : MvPolynomial (Fin t) E) ∉ Submodule.span E
+ (Set.range ((coordinatePencil F i H (H + d)).map (Polynomial.eval c)).row) := by
+ rw [coordinatePencil_eval]
+ let G := coordinateEquations F i c
+ have hdeg := coordinateEquations_degree_le F hF hd i c
+ constructor
+ · rintro ⟨x, hx, hxi⟩ hmem
+ have hz (a : Option ι) : aeval x (G a) = 0 := by
+ cases a with
+ | some a => simpa [G, coordinateEquations] using hx a
+ | none => simp [G, coordinateEquations, hxi]
+ have h := aeval_eq_zero_of_row_mem G hdeg 1 (by simp) hmem x hz
+ simp at h
+ · intro hmem
+ obtain ⟨x, hx⟩ := CertificateReduction.commonZero_of_one_notMem G H d hdeg hmem bound
+ exact ⟨x, fun a => by simpa [G, coordinateEquations] using hx (some a),
+ by simpa [G, coordinateEquations, sub_eq_zero] using hx none⟩
+
+/-- Appending the coefficient row of one turns the fiber test into a strict
+inequality between the ranks of the two specialized matrix pencils. -/
+theorem coordinateImage_iff_rank_lt [Fintype ι] (F : ι → MvPolynomial (Fin t) E)
+ (i : Fin t) (c : E) {H d : ℕ} (hF : ∀ a, (F a).totalDegree ≤ d) (hd : 1 ≤ d)
+ (bound : WeakCertificateBound E (Option ι) t d H) :
+ (∃ x : Fin t → E, (∀ a, eval x (F a) = 0) ∧ x i = c) ↔
+ ((coordinatePencil F i H (H + d)).map (Polynomial.eval c)).rank <
+ ((augmentedCoordinatePencil F i H (H + d)).map (Polynomial.eval c)).rank := by
+ let M := (coordinatePencil F i H (H + d)).map (Polynomial.eval c)
+ let N := (augmentedCoordinatePencil F i H (H + d)).map (Polynomial.eval c)
+ let v := coefficientRow (H + d) (1 : MvPolynomial (Fin t) E)
+ have hrows : Set.range N.row = insert v (Set.range M.row) := by
+ have hn : N.row none = v := by
+ ext j
+ exact Polynomial.eval_C
+ ext w
+ constructor
+ · rintro ⟨(_ | r), rfl⟩
+ · exact Or.inl hn
+ · exact Or.inr ⟨r, rfl⟩
+ · rintro (rfl | ⟨r, rfl⟩)
+ · exact ⟨none, hn⟩
+ · exact ⟨some r, rfl⟩
+ rw [coordinateImage_iff_row_notMem F i c hF hd bound]
+ change v ∉ Submodule.span E (Set.range M.row) ↔ M.rank < N.rank
+ rw [M.rank_eq_finrank_span_row, N.rank_eq_finrank_span_row, hrows]
+ constructor
+ · intro hv
+ apply Submodule.finrank_lt_finrank_of_lt
+ refine lt_of_le_of_ne (Submodule.span_mono (Set.subset_insert _ _)) (fun he => hv ?_)
+ rw [he]
+ exact Submodule.subset_span (Set.mem_insert _ _)
+ · intro hlt hv
+ rw [Submodule.span_insert_eq_span hv] at hlt
+ exact hlt.false
+
+variable {K : Type*} [Field K] [Algebra K E]
+
+/-- Present the partially pinned set using the original equations and one
+potential linear equation per variable. An unused pin contributes zero. -/
+noncomputable def pinnedEquations (F : ι → MvPolynomial (Fin t) K) (s : Finset (Fin t))
+ (a : Fin t → K) : ι ⊕ Fin t → MvPolynomial (Fin t) K :=
+ Sum.elim F fun j => if j ∈ s then X j - C (a j) else 0
+
+/-- Extend the system of partial pins to the geometric field. -/
+noncomputable def geometricPinnedEquations (F : ι → MvPolynomial (Fin t) K)
+ (s : Finset (Fin t)) (a : Fin t → K) : ι ⊕ Fin t → MvPolynomial (Fin t) E :=
+ fun j => map (algebraMap K E) (pinnedEquations F s a j)
+
+theorem geometricPinnedEquations_degree_le (F : ι → MvPolynomial (Fin t) K)
+ (s : Finset (Fin t)) (a : Fin t → K) {d : ℕ}
+ (hF : ∀ j, (F j).totalDegree ≤ d) (hd : 1 ≤ d) (j : ι ⊕ Fin t) :
+ (geometricPinnedEquations (E := E) F s a j).totalDegree ≤ d := by
+ refine (Finset.sup_mono (support_map_subset (algebraMap K E) (pinnedEquations F s a j))).trans ?_
+ change (pinnedEquations F s a j).totalDegree ≤ d
+ cases j with
+ | inl j => exact hF j
+ | inr j =>
+ by_cases hj : j ∈ s
+ · simpa only [pinnedEquations, Sum.elim_inr, ite_eq_left hj, coordinateEquations, Option.elim'_none] using
+ coordinateEquations_degree_le F hF hd j (a j) none
+ · simp [pinnedEquations, hj]
+
+/-- The fixed-size pinned equation list cuts out precisely the partially pinned
+geometric point set. -/
+theorem mem_pinnedPoints_iff (F : ι → MvPolynomial (Fin t) K)
+ (s : Finset (Fin t)) (a : Fin t → K) (x : Fin t → E) :
+ x ∈ pinnedPoints {y : Fin t → E | ∀ j, aeval y (F j) = 0} s a ↔
+ ∀ j, eval x (geometricPinnedEquations F s a j) = 0 := by
+ have he (j : ι ⊕ Fin t) :
+ eval x (geometricPinnedEquations F s a j) = aeval x (pinnedEquations F s a j) := by
+ rw [geometricPinnedEquations, eval_map, aeval_def]
+ simp_rw [he]
+ constructor
+ · rintro ⟨hF, hs⟩ (j | j)
+ · exact hF j
+ · by_cases hj : j ∈ s
+ · simp [pinnedEquations, hj, hs j hj]
+ · simp [pinnedEquations, hj]
+ · intro h
+ refine ⟨fun j => h (.inl j), fun j hj => ?_⟩
+ simpa [pinnedEquations, hj, sub_eq_zero] using h (.inr j)
+
+/-- Rank criterion for each coordinate of each partial pin, with the same
+certificate bound and index types at every stage of the slicing procedure. -/
+theorem mem_pinnedCoordinateImage_iff_rank_lt [Fintype ι] (F : ι → MvPolynomial (Fin t) K)
+ (s : Finset (Fin t)) (a : Fin t → K) (i : Fin t) (c : E) {H d : ℕ}
+ (hF : ∀ j, (F j).totalDegree ≤ d) (hd : 1 ≤ d)
+ (bound : WeakCertificateBound E (Option (ι ⊕ Fin t)) t d H) :
+ let G := geometricPinnedEquations (E := E) F s a
+ c ∈ coordinateImage (pinnedPoints {y : Fin t → E | ∀ j, aeval y (F j) = 0} s a) i ↔
+ ((coordinatePencil G i H (H + d)).map (Polynomial.eval c)).rank <
+ ((augmentedCoordinatePencil G i H (H + d)).map (Polynomial.eval c)).rank := by
+ dsimp only
+ rw [← coordinateImage_iff_rank_lt _ i c (geometricPinnedEquations_degree_le F s a hF hd) hd bound]
+ change (∃ x, x ∈ pinnedPoints _ s a ∧ x i = c) ↔ _
+ simp_rw [mem_pinnedPoints_iff]
+
+end SliceGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotBitCounts.lean b/lean/OAI/Computability/VPVNP/SlotBitCounts.lean
new file mode 100644
index 0000000000..6ac033f6ed
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotBitCounts.lean
@@ -0,0 +1,74 @@
+import Mathlib.Data.ZMod.Basic
+import Mathlib.Data.Fintype.BigOperators
+import Mathlib.Logic.Equiv.Prod
+
+/-!
+# Independence of the color bits in Appendix C
+
+A position in Lemma C.1 of *VP and VNP differ over every field* has one bit
+per base color and a separate outgoing-slot coordinate. Fixing the endpoint
+types of a translated arc fixes precisely two distinct color bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SlotPacking
+
+variable {I : Type*} [Fintype I] [DecidableEq I]
+
+/-- Restricting a function away from its prescribed coordinates forgets exactly
+the values that are forced. -/
+private def freeBits (s : Finset I) (v : I → ZMod 2) :
+ {u : I → ZMod 2 // ∀ i ∈ s, u i = v i} ≃ (↥sᶜ → ZMod 2) where
+ toFun u i := u.1 i
+ invFun f := ⟨fun i ↦ if hi : i ∈ s then v i else f ⟨i, Finset.mem_compl.mpr hi⟩,
+ fun i hi ↦ by simp [hi]⟩
+ left_inv u := by
+ apply Subtype.ext
+ funext i
+ by_cases hi : i ∈ s
+ · simp [hi, u.property i hi]
+ · simp [hi]
+ right_inv f := by
+ funext i
+ simp [Finset.mem_compl.mp i.property]
+
+/-- Exact number of bit vectors with prescribed values on any subset of colors. -/
+theorem card_prescribedBits (s : Finset I) (v : I → ZMod 2) :
+ Fintype.card {u : I → ZMod 2 // ∀ i ∈ s, u i = v i} = 2 ^ (Fintype.card I - s.card) := by
+ rw [Fintype.card_congr (freeBits s v), Fintype.card_fun, Fintype.card_coe, Finset.card_compl,
+ ZMod.card]
+
+/-- One endpoint test cuts the color vectors in half. -/
+theorem card_oneBit (i : I) (a : ZMod 2) :
+ Fintype.card {u : I → ZMod 2 // u i = a} = 2 ^ (Fintype.card I - 1) := by
+ simpa using card_prescribedBits ({i} : Finset I) (fun _ ↦ a)
+
+/-- Prescribing the two endpoint types fixes two independent color bits. -/
+theorem card_twoBits {i j : I} (hne : i ≠ j) (a b : ZMod 2) :
+ Fintype.card {u : I → ZMod 2 // u i = a ∧ u j = b} = 2 ^ (Fintype.card I - 2) := by
+ simpa [hne, Ne.symm hne] using
+ card_prescribedBits ({i, j} : Finset I) (fun k ↦ if k = i then a else b)
+
+/-- An arc translation may displace either endpoint test. -/
+theorem card_translatedBits {i j : I} (hne : i ≠ j) (δ₁ δ₂ a b : ZMod 2) :
+ Fintype.card {u : I → ZMod 2 // u i + δ₁ = a ∧ u j + δ₂ = b} =
+ 2 ^ (Fintype.card I - 2) := by
+ simpa only [eq_sub_iff_add_eq] using card_twoBits hne (a - δ₁) (b - δ₂)
+
+/-- Free choice of the independent outgoing slot multiplies the endpoint count
+by the degree. -/
+theorem card_translatedBits_slots {i j : I} (hne : i ≠ j) (δ₁ δ₂ a b : ZMod 2) (d : ℕ) :
+ Fintype.card {p : (I → ZMod 2) × Fin d // p.1 i + δ₁ = a ∧ p.1 j + δ₂ = b} =
+ 2 ^ (Fintype.card I - 2) * d := by
+ rw [Fintype.card_congr (Equiv.prodSubtypeFstEquivSubtypeProd (β := Fin d)
+ (p := fun u : I → ZMod 2 ↦ u i + δ₁ = a ∧ u j + δ₂ = b)), Fintype.card_prod]
+ simp [card_translatedBits hne]
+
+end SlotPacking
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotBundleCount.lean b/lean/OAI/Computability/VPVNP/SlotBundleCount.lean
new file mode 100644
index 0000000000..1b288fa356
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotBundleCount.lean
@@ -0,0 +1,179 @@
+import OAI.Computability.VPVNP.SlotIncidence
+import OAI.Computability.VPVNP.SlotBitCounts
+import Mathlib.Tactic.Ring
+
+/-!
+# Exact number of demands per packed bundle
+
+For a fixed bundle, Appendix C counts outgoing thin-endpoint demands in the
+original outgoing numbering and incoming demands from thick endpoints in the
+original incoming numbering. The tag offset and lane slot are fixed in both
+enumerations, leaving only the old arc slot and its color bits.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+variable {V H Tag L : Type*} {d c : ℕ}
+variable [AddCommGroup Tag]
+variable (P : PackingData V H Tag L d c)
+
+/-- Actual arc at an endpoint with prescribed bundle assignment. The old
+incident slot is independent of the assignment's outgoing-slot coordinate. -/
+def arcAtBundle (b : Site V Tag L × Fin d) (i : Fin d) (w : BitWord c) :
+ Arc V H Tag L d c := ((P.offsetSite.symm b.1, i), w, P.slotLabel.symm b.2)
+
+@[simp] theorem assigned_atBundle (b : Site V Tag L × Fin d) (i : Fin d) (w : BitWord c) :
+ P.assignedBundle (sourcePosition (P.arcAtBundle b i w)) = b := by
+ simp [arcAtBundle, sourcePosition, assignedBundle]
+
+private theorem arcAtBundle_recover {a : Arc V H Tag L d c} {b : Site V Tag L × Fin d}
+ (h : P.assignedBundle (sourcePosition a) = b) : P.arcAtBundle b a.1.2 a.2.1 = a := by
+ subst b
+ simp [arcAtBundle, assignedBundle, sourcePosition]
+
+/-- A fixed assignment has one fiber for each incident slot, with the bit word
+as its only free parameter. -/
+def assignedArcEquiv (b : Site V Tag L × Fin d) (p : Arc V H Tag L d c → Prop) :
+ {a : Arc V H Tag L d c // p a ∧ P.assignedBundle (sourcePosition a) = b} ≃
+ Σ i : Fin d, {w : BitWord c // p (P.arcAtBundle b i w)} where
+ toFun a := ⟨a.1.1.2, a.1.2.1, by rw [P.arcAtBundle_recover a.2.2]; exact a.2.1⟩
+ invFun a := ⟨P.arcAtBundle b a.1 a.2.1, a.2.2, P.assigned_atBundle ..⟩
+ left_inv a := Subtype.ext (P.arcAtBundle_recover a.2.2)
+ right_inv _ := rfl
+
+private theorem bit_ne_one (a : ZMod 2) : a ≠ 1 ↔ a = 0 := by
+ exact (by decide : ∀ z : ZMod 2, z ≠ 1 ↔ z = 0) a
+
+private theorem c_arithmetic {c : ℕ} (hc : 2 ≤ c) (d : ℕ) :
+ d * 2 ^ (c - 1) + d * 2 ^ (c - 2) = 3 * (2 ^ c * d) / 4 ∧
+ 2 ^ (c - 2) * d = 2 ^ c * d / 4 := by
+ obtain ⟨n, rfl⟩ := Nat.exists_eq_add_of_le hc
+ simp only [Nat.add_sub_cancel_left]
+ have h : 2 + n - 1 = n + 1 := by omega
+ rw [h, pow_succ, pow_add]
+ have h₁ : d * (2 ^ n * 2) + d * 2 ^ n = 3 * (2 ^ n * d) := by ring
+ have h₂ : 2 ^ 2 * 2 ^ n * d = 4 * (2 ^ n * d) := by ring
+ rw [h₁, h₂]
+ omega
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+private theorem card_outgoingC (b : Site V Tag L × Fin d) :
+ Fintype.card {a : Arc V H Tag L d c // ¬ P.thick (sourcePosition a) ∧
+ P.assignedBundle (sourcePosition a) = b} = d * 2 ^ (c - 1) := by
+ classical
+ rw [Fintype.card_congr (P.assignedArcEquiv b (fun a ↦ ¬ P.thick (sourcePosition a))),
+ Fintype.card_sigma]
+ have hc (i : Fin d) : Fintype.card {w : BitWord c //
+ ¬ P.thick (sourcePosition (P.arcAtBundle b i w))} = 2 ^ (c - 1) := by
+ change Fintype.card {w : BitWord c // w (P.color b.1.1) ≠ 1} = _
+ simpa only [bit_ne_one, Fintype.card_fin] using SlotPacking.card_oneBit (P.color b.1.1) 0
+ simp [hc]
+
+variable [AddCommGroup H] [AddCommGroup L]
+
+private theorem card_incomingC (b : Site V Tag L × Fin d) :
+ Fintype.card {a : Arc V H Tag L d c // P.thick (sourcePosition (P.actual.symm a)) ∧
+ ¬ P.thick (sourcePosition a) ∧ P.assignedBundle (sourcePosition a) = b} =
+ d * 2 ^ (c - 2) := by
+ classical
+ let p := fun a : Arc V H Tag L d c ↦ P.thick (sourcePosition (P.actual.symm a)) ∧
+ ¬ P.thick (sourcePosition a)
+ have e := Equiv.subtypeEquivRight (p := fun a : Arc V H Tag L d c ↦
+ P.thick (sourcePosition (P.actual.symm a)) ∧ ¬ P.thick (sourcePosition a) ∧
+ P.assignedBundle (sourcePosition a) = b)
+ (q := fun a ↦ p a ∧ P.assignedBundle (sourcePosition a) = b) (fun _ ↦ and_assoc.symm)
+ rw [Fintype.card_congr (e.trans (P.assignedArcEquiv b p)), Fintype.card_sigma]
+ have hc (i : Fin d) : Fintype.card {w : BitWord c // p (P.arcAtBundle b i w)} = 2 ^ (c - 2) := by
+ let old := P.slots.target.symm (b.1.1, i)
+ have hne : P.color old.1 ≠ P.color b.1.1 := by simpa [old] using P.proper old
+ change Fintype.card {w : BitWord c //
+ w (P.color old.1) - P.bitShift old (P.color old.1) = 1 ∧ w (P.color b.1.1) ≠ 1} = _
+ simpa only [sub_eq_add_neg, add_zero, bit_ne_one, Fintype.card_fin] using
+ SlotPacking.card_translatedBits hne (- P.bitShift old (P.color old.1)) 0 1 0
+ simp [hc]
+
+/-- Every packed bundle receives exactly Q old wires as CD demands. -/
+theorem card_motifs_bundle (hc : 2 ≤ c) (b : Site V Tag L × Fin d) :
+ Fintype.card {m : P.Motif // P.bundle m = b} = 3 * (2 ^ c * d) / 4 := by
+ unfold bundle
+ rw [Fintype.card_congr (P.cdIncidenceEquiv (fun x _ ↦ P.assignedBundle x = b)),
+ Fintype.card_sum, P.card_outgoingC, P.card_incomingC]
+ exact (c_arithmetic hc d).1
+
+/-- Original base-color bit at a numbered endpoint. -/
+def arcBit (a : Arc V H Tag L d c) : ZMod 2 := a.2.1 (P.color a.1.1.1)
+
+/-- For any two endpoint types, a fixed base arc and source site carry K/4
+wires of those types, including the bundle's thick–thick wires. -/
+theorem card_bundle_types (hc : 2 ≤ c) (b : Site V Tag L × Fin d) (s t : ZMod 2) :
+ Fintype.card {a : Arc V H Tag L d c // a.1 = b ∧ P.arcBit a = s ∧ P.arcBit (P.actual a) = t} =
+ 2 ^ c * d / 4 := by
+ let p := fun u : BitWord c ↦ u (P.color b.1.1) = s ∧
+ u (P.color (P.slots.target (b.1.1,b.2)).1) +
+ P.bitShift (b.1.1,b.2) (P.color (P.slots.target (b.1.1,b.2)).1) = t
+ let e : {a : Arc V H Tag L d c // a.1 = b ∧ P.arcBit a = s ∧ P.arcBit (P.actual a) = t} ≃
+ {u : BitWord c // p u} × H := {
+ toFun := fun a ↦ (⟨a.1.2.1, by
+ rcases a with ⟨⟨b',u,h⟩, hbase, hs, ht⟩
+ change b' = b at hbase
+ subst b'
+ exact ⟨hs,ht⟩⟩, a.1.2.2)
+ invFun := fun a ↦ ⟨(b, a.1.1, a.2), rfl, a.1.2.1, a.1.2.2⟩
+ left_inv := fun a ↦ Subtype.ext (Prod.ext a.2.1.symm rfl)
+ right_inv := fun _ ↦ rfl }
+ have hp : Fintype.card {u : BitWord c // p u} = 2 ^ (c - 2) := by
+ simpa only [p, add_zero, Fintype.card_fin] using SlotPacking.card_translatedBits
+ (P.proper (b.1.1,b.2)) 0 (P.bitShift (b.1.1,b.2) (P.color (P.slots.target (b.1.1,b.2)).1)) s t
+ have hh : Fintype.card H = d := (Fintype.card_congr P.slotLabel).trans (Fintype.card_fin d)
+ rw [Fintype.card_congr e, Fintype.card_prod, hp, hh]
+ exact (c_arithmetic hc d).2
+
+/-- Size of the thick–thick bundle whose payload is concatenated in §7.2. -/
+theorem card_thick_bundle (hc : 2 ≤ c) (b : Site V Tag L × Fin d) :
+ Fintype.card {a : Arc V H Tag L d c // a.1 = b ∧ P.thick (sourcePosition a) ∧
+ P.thick (sourcePosition (P.actual a))} = 2 ^ c * d / 4 :=
+ P.card_bundle_types hc b 1 1
+
+/-- Count motifs at an endpoint by splitting that endpoint into its ports.
+The permutation is the identity for A and the site arc matching for B. -/
+private def rolePortEquiv (e : Equiv.Perm (Site V Tag L × Fin d)) (s : Site V Tag L) :
+ {m : P.Motif // (e (P.bundle m)).1 = s} ≃
+ Σ i : Fin d, {m : P.Motif // P.bundle m = e.symm (s, i)} where
+ toFun m := ⟨(e (P.bundle m.1)).2, m.1, e.injective (by
+ rw [e.apply_symm_apply]
+ exact Prod.ext m.2 rfl)⟩
+ invFun a := ⟨a.2.1, by rw [a.2.2, e.apply_symm_apply]⟩
+ left_inv _ := rfl
+ right_inv a := by
+ rcases a with ⟨i,m,hm⟩
+ apply Sigma.ext
+ · simp [hm]
+ · exact (Subtype.heq_iff_coe_eq (by simp [hm])).mpr rfl
+
+private theorem rolePort_count (hc : 2 ≤ c) (e : Equiv.Perm (Site V Tag L × Fin d))
+ (s : Site V Tag L) :
+ Fintype.card {m : P.Motif // (e (P.bundle m)).1 = s} = d * (3 * (2 ^ c * d) / 4) := by
+ rw [Fintype.card_congr (P.rolePortEquiv e s), Fintype.card_sigma]
+ simp [P.card_motifs_bundle hc]
+
+/-- Exactly dQ incidences of A occur at each packed site. -/
+theorem card_roleA (hc : 2 ≤ c) (s : Site V Tag L) :
+ Fintype.card {m : P.Motif // P.roleA m = s} = d * (3 * (2 ^ c * d) / 4) :=
+ P.rolePort_count hc (Equiv.refl _) s
+
+/-- Exactly dQ incidences of B occur at each packed site, including parallel arcs. -/
+theorem card_roleB (hc : 2 ≤ c) (s : Site V Tag L) :
+ Fintype.card {m : P.Motif // P.roleB m = s} = d * (3 * (2 ^ c * d) / 4) :=
+ P.rolePort_count hc P.siteGraph.target s
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotBundleNumbering.lean b/lean/OAI/Computability/VPVNP/SlotBundleNumbering.lean
new file mode 100644
index 0000000000..f85cfba63b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotBundleNumbering.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.SlotDemandKernel
+import OAI.Computability.VPVNP.SlotIdentifierOrder
+import Mathlib.Data.Finset.Sort
+
+/-!
+# Lane-independent combinatorial orders of the packed wires
+
+For each base arc and source tag, order the old thick wires and the assigned
+motifs at source-site lane zero. The order at every other lane is the transport
+of that order. Thus the combinatorial identifiers used for Appendix E's scans
+agree under translations even when the actual field widths vary by lane.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+variable {V Tag L : Type*} {d : ℕ} [AddCommGroup L]
+
+private abbrev Port (V Tag L : Type*) (d : ℕ) := Site V Tag L × Fin d
+
+/-- Preserve the bundle's base arc and tag while translating its remaining lane. -/
+def translateBundle (b : Site V Tag L × Fin d) (g : L) : Site V Tag L × Fin d :=
+ (translateSite b.1 g,b.2)
+
+private def zeroBundle (b : Port V Tag L d) : Port V Tag L d := ((b.1.1,b.1.2.1,0),b.2)
+
+private structure BundleAction (A : Type*) (port : A → Port V Tag L d) where
+ move : A → L → A
+ zero : ∀ a, move a 0 = a
+ add : ∀ a g h, move (move a g) h = move a (g + h)
+ port_move : ∀ a g, port (move a g) = translateBundle (port a) g
+
+namespace BundleAction
+
+variable {A : Type*} {port : A → Port V Tag L d} (S : BundleAction A port)
+
+private def zeroFiber (b : Port V Tag L d) :
+ {a : A // port a = b} ≃ {a : A // port a = zeroBundle b} where
+ toFun a := ⟨S.move a.1 (-b.1.2.2), by rw [S.port_move,a.2]; simp [translateBundle,translateSite,
+ zeroBundle]⟩
+ invFun a := ⟨S.move a.1 b.1.2.2, by rw [S.port_move,a.2]; simp [translateBundle,translateSite,
+ zeroBundle]⟩
+ left_inv a := Subtype.ext (by simp [S.add,S.zero])
+ right_inv a := Subtype.ext (by simp [S.add,S.zero])
+
+private def numbering {n : ℕ} (initial : ∀ b, {a : A // port a = b} ≃ Fin n) (b : Port V Tag L d) :
+ {a : A // port a = b} ≃ Fin n :=
+ (S.zeroFiber b).trans (initial (zeroBundle b))
+
+private theorem numbering_move {n : ℕ} (initial : ∀ b, {a : A // port a = b} ≃ Fin n)
+ (b : Port V Tag L d) (a : {a : A // port a = b}) (g : L) :
+ S.numbering initial (translateBundle b g) ⟨S.move a.1 g, (S.port_move a.1 g).trans
+ (congrArg (fun v ↦ translateBundle v g) a.2)⟩ = S.numbering initial b a := by
+ apply congrArg (initial (zeroBundle b))
+ apply Subtype.ext
+ change S.move (S.move a.1 g) (-(b.1.2.2 + g)) = S.move a.1 (-b.1.2.2)
+ simp [S.add]
+
+end BundleAction
+
+namespace PackingData
+
+variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+private def motifBundleAction : BundleAction P.Motif P.bundle where
+ move := P.translateMotif
+ zero := P.translateMotif_zero
+ add := P.translateMotif_add
+ port_move := P.bundle_translate
+
+/-- The old thick–thick wires also form complete translation orbits. -/
+def translateThickWire (a : P.ThickWire) (g : L) : P.ThickWire :=
+ ⟨translateArc a.1 g, by simpa only [actual_translate,sourcePosition_translate,thick_translate]
+ using a.2⟩
+
+private def thickBundleAction : BundleAction P.ThickWire (fun a ↦ a.1.1) where
+ move := P.translateThickWire
+ zero a := Subtype.ext (translateArc_zero a.1)
+ add a g h := Subtype.ext (translateArc_add a.1 g h)
+ port_move _ _ := rfl
+
+/-- Transport the chosen order of CD demands at lane zero to every bundle. -/
+def laneBundleNumbering (initial : P.BundleNumbering) : P.BundleNumbering :=
+ P.motifBundleAction.numbering initial
+
+/-- Transport the common endpoint order of the old thick wires from lane zero. -/
+def laneThickNumbering (initial : P.ThickNumbering) : P.ThickNumbering :=
+ P.thickBundleAction.numbering initial
+
+/-- The translated motif occupies the same piece number in the translated bundle. -/
+theorem laneBundleNumbering_translate (initial : P.BundleNumbering) (b : Site V Tag L × Fin d)
+ (m : P.MotifFiber b) (g : L) :
+ P.laneBundleNumbering initial (translateBundle b g)
+ ⟨P.translateMotif m.1 g, by rw [P.bundle_translate, m.2]; rfl⟩ =
+ P.laneBundleNumbering initial b m :=
+ P.motifBundleAction.numbering_move initial b m g
+
+/-- Each original wire keeps its rank in the translated concatenation order. -/
+theorem laneThickNumbering_translate (initial : P.ThickNumbering) (b : Site V Tag L × Fin d)
+ (a : P.ThickFiber b) (g : L) :
+ P.laneThickNumbering initial (translateBundle b g)
+ ⟨P.translateThickWire a.1 g, congrArg (fun v ↦ translateBundle v g) a.2⟩ =
+ P.laneThickNumbering initial b a :=
+ P.thickBundleAction.numbering_move initial b a g
+
+/-- At fixed source site and arc, the old thick wire is specified by its
+color word and slot-coordinate label. -/
+def thickFiberIndex (b : Site V Tag L × Fin d) (x : P.ThickFiber b) : Fin (2 ^ c * d) :=
+ finProdFinEquiv (bitWordFinEquiv c x.1.1.2.1, P.slotLabel x.1.1.2.2)
+
+theorem thickFiberIndex_injective (b : Site V Tag L × Fin d) :
+ Function.Injective (P.thickFiberIndex b) := by
+ intro x y h
+ have he := finProdFinEquiv.injective h
+ exact Subtype.ext (Subtype.ext (Prod.ext (x.2.trans y.2.symm)
+ (Prod.ext ((bitWordFinEquiv c).injective (congrArg Prod.fst he))
+ (P.slotLabel.injective (congrArg Prod.snd he)))))
+
+/-- The relative motif key distinguishes every old CD wire in a fixed bundle.
+The role-A lane recovers the missing absolute coordinate from that bundle. -/
+theorem motifFiberIndex_injective {N J : ℕ} (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J)
+ (b : Site V Tag L × Fin d) :
+ Function.Injective (fun x : P.MotifFiber b ↦
+ P.baseMotifIndex vertices tags (P.baseMotif x.1)) := by
+ intro x y h
+ apply Subtype.ext
+ apply (P.roleLaneEquiv P.roleA P.roleA_translate).injective
+ exact Prod.ext (P.baseMotifIndex_injective vertices tags h)
+ (congrArg (fun t : Site V Tag L × Fin d ↦ t.1.2.2) (x.2.trans y.2.symm))
+
+private def keyNumbering {A : Type*} [Fintype A] {n q : ℕ} (key : A → Fin n)
+ (hinj : Function.Injective key) (hcard : Fintype.card A = q) : A ≃ Fin q :=
+ letI := LinearOrder.lift' key hinj
+ (Fintype.orderIsoFinOfCardEq A hcard).symm.toEquiv
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+/-- Order the CD demands of each bundle by their relative integer keys. The
+order at an arbitrary lane is the transport of the same lane-zero list. -/
+def sortedBundleNumbering {N J : ℕ} (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J)
+ (hc : 2 ≤ c) : P.BundleNumbering :=
+ P.laneBundleNumbering fun b ↦ keyNumbering
+ (fun x : P.MotifFiber b ↦ P.baseMotifIndex vertices tags (P.baseMotif x.1))
+ (P.motifFiberIndex_injective vertices tags b) (P.card_motifs_bundle hc b)
+
+/-- Use the same integer-sorted list of old wires at both bundle ends and in
+every translated lane. -/
+def sortedThickNumbering (hc : 2 ≤ c) : P.ThickNumbering :=
+ P.laneThickNumbering fun b ↦ keyNumbering (P.thickFiberIndex b)
+ (P.thickFiberIndex_injective b) (P.card_thick_fiber hc b)
+
+end PackingData
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotDemandEnergy.lean b/lean/OAI/Computability/VPVNP/SlotDemandEnergy.lean
new file mode 100644
index 0000000000..53da0481db
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotDemandEnergy.lean
@@ -0,0 +1,156 @@
+import OAI.Computability.VPVNP.SlotBundleCount
+import OAI.Computability.VPVNP.WidthRounding
+import Mathlib.Algebra.Order.BigOperators.Ring.Finset
+
+/-!
+# Energy of the packed demand wires
+
+The first inequality of §7.2 charges every actual wire exactly once. In a
+thick–thick bundle the old payloads are concatenated and divided as evenly
+as possible among its assigned motifs. Each remaining wire retains its old
+width in the CD demand of its motif.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+variable {V H Tag L : Type*} {d c : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- The number Q of pieces in each concatenated payload. -/
+abbrev pieceCount (d c : ℕ) := 3 * (2 ^ c * d) / 4
+
+/-- Number the motifs assigned to each bundle in the common order used at A and B. -/
+abbrev BundleNumbering :=
+ ∀ b : Site V Tag L × Fin d, {m : P.Motif // P.bundle m = b} ≃ Fin (pieceCount d c)
+
+/-- The original wires concatenated at A and B. -/
+abbrev ThickWire := {a : Arc V H Tag L d c //
+ P.thick (sourcePosition a) ∧ P.thick (sourcePosition (P.actual a))}
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+/-- Lemma C.1 supplies an ordering with exactly Q pieces in each bundle. -/
+noncomputable def bundleNumbering (hc : 2 ≤ c) : P.BundleNumbering :=
+ fun b ↦ Fintype.equivFinOfCardEq (P.card_motifs_bundle hc b)
+
+/-- Total number of bits in the concatenation, before rounding. -/
+def bundleWidth (w : Arc V H Tag L d c → ℕ) (b : Site V Tag L × Fin d) : ℕ :=
+ ∑ a : {a : P.ThickWire // a.1.1 = b}, w a.1.1
+
+/-- Width of the AB wire paired with the unchanged CD wire of a motif. -/
+def abWidth (number : P.BundleNumbering) (w : Arc V H Tag L d c → ℕ) (m : P.Motif) : ℕ :=
+ splitWidth (P.bundleWidth w (P.bundle m)) (pieceCount d c) (number (P.bundle m) ⟨m,rfl⟩)
+
+private theorem abWidth_at (number : P.BundleNumbering) (w : Arc V H Tag L d c → ℕ)
+ (b : Site V Tag L × Fin d) (m : {m : P.Motif // P.bundle m = b}) :
+ P.abWidth number w m.1 = splitWidth (P.bundleWidth w b) (pieceCount d c) (number b m) := by
+ rcases m with ⟨m, hm⟩
+ subst b
+ rfl
+
+/-- Number of thick–thick wires over each original bundle. -/
+theorem card_thick_fiber (hc : 2 ≤ c) (b : Site V Tag L × Fin d) :
+ Fintype.card {a : P.ThickWire // a.1.1 = b} = 2 ^ c * d / 4 := by
+ let e : {a : P.ThickWire // a.1.1 = b} ≃ {a : Arc V H Tag L d c //
+ a.1 = b ∧ P.thick (sourcePosition a) ∧ P.thick (sourcePosition (P.actual a))} :=
+ { toFun := fun a ↦ ⟨a.1.1, a.2, a.1.2⟩
+ invFun := fun a ↦ ⟨⟨a.1,a.2.2⟩,a.2.1⟩ }
+ exact (Fintype.card_congr e).trans (P.card_thick_bundle hc b)
+
+private theorem pieces_arithmetic (hc : 2 ≤ c) (hd : 0 < d) :
+ pieceCount d c = 3 * (2 ^ c * d / 4) ∧ 0 < pieceCount d c := by
+ obtain ⟨n,rfl⟩ := Nat.exists_eq_add_of_le hc
+ have h : 2 ^ (2 + n) * d = 4 * (2 ^ n * d) := by rw [pow_add]; ring
+ have hp : 0 < 2 ^ n * d := Nat.mul_pos (pow_pos (by decide) _) hd
+ simp only [pieceCount, h]
+ omega
+
+/-- Concatenation uses at most the number of bundled wires times the maximum old width. -/
+theorem bundleWidth_le (hc : 2 ≤ c) (w : Arc V H Tag L d c → ℕ) {W : ℕ}
+ (hw : ∀ a, w a ≤ W) (b : Site V Tag L × Fin d) :
+ P.bundleWidth w b ≤ (2 ^ c * d / 4) * W := by
+ have h := Finset.sum_le_sum (s := Finset.univ)
+ (fun a : {a : P.ThickWire // a.1.1 = b} ↦ fun _ ↦ hw a.1.1)
+ simpa [bundleWidth, P.card_thick_fiber hc] using h
+
+/-- The individual AB pieces are no wider than the largest old wire. -/
+theorem abWidth_le (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering)
+ (w : Arc V H Tag L d c → ℕ) {W : ℕ} (hw : ∀ a, w a ≤ W) (m : P.Motif) :
+ P.abWidth number w m ≤ W := by
+ let b := P.bundleWidth w (P.bundle m)
+ let q := pieceCount d c
+ have hq : 0 < q := (pieces_arithmetic hc hd).2
+ have hk : 2 ^ c * d / 4 ≤ q := by dsimp [q]; rw [(pieces_arithmetic hc hd).1]; omega
+ have hb : b ≤ W * q := (P.bundleWidth_le hc w hw _).trans
+ ((Nat.mul_le_mul_right W hk).trans_eq (Nat.mul_comm q W))
+ change splitWidth b q _ ≤ W
+ unfold splitWidth
+ split_ifs with h
+ · apply (Nat.div_lt_iff_lt_mul hq).mpr
+ refine lt_of_le_of_ne hb ?_
+ rintro he
+ simp [he] at h
+ · exact Nat.div_le_of_le_mul (by simpa [Nat.mul_comm] using hb)
+
+/-- Concatenation followed by the Q-way division preserves the payload width. -/
+theorem sum_abWidth (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering)
+ (w : Arc V H Tag L d c → ℕ) (b : Site V Tag L × Fin d) :
+ ∑ m : {m : P.Motif // P.bundle m = b}, P.abWidth number w m.1 = P.bundleWidth w b := by
+ simp_rw [P.abWidth_at number w b]
+ rw [(number b).sum_comp]
+ exact sum_splitWidth _ _ (pieces_arithmetic hc hd).2
+
+/-- The bundle's perfect fractional division inherits the total old mass.
+Integral division incurs at most Q/(4(p/3)) additional energy. -/
+theorem bundle_energy_le (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering)
+ (w : Arc V H Tag L d c → ℕ) {p : ℝ} (hp : 0 < p) (b : Site V Tag L × Fin d) :
+ ∑ m : {m : P.Motif // P.bundle m = b}, (P.abWidth number w m.1 : ℝ) ^ 2 / (p / 3) ≤
+ ∑ a : {a : P.ThickWire // a.1.1 = b}, (w a.1.1 : ℝ) ^ 2 / p +
+ pieceCount d c / (4 * (p / 3)) := by
+ have hs := Finset.sq_sum_div_le_sum_sq_div Finset.univ
+ (fun a : {a : P.ThickWire // a.1.1 = b} ↦ (w a.1.1 : ℝ))
+ (g := fun _ ↦ p) (fun _ _ ↦ hp)
+ have hm : (pieceCount d c : ℝ) * (p / 3) = (↑(2 ^ c * d / 4 : ℕ) : ℝ) * p := by
+ rw [(pieces_arithmetic hc hd).1, Nat.cast_mul, Nat.cast_ofNat]
+ ring
+ simp only [Finset.sum_const, Finset.card_univ, P.card_thick_fiber hc, nsmul_eq_mul] at hs
+ simp_rw [P.abWidth_at number w b]
+ rw [(number b).sum_comp (fun i ↦ (splitWidth (P.bundleWidth w b) (pieceCount d c) i : ℝ) ^ 2 /
+ (p / 3))]
+ calc
+ _ ≤ (P.bundleWidth w b : ℝ) ^ 2 / (pieceCount d c * (p / 3)) +
+ pieceCount d c / (4 * (p / 3)) :=
+ splitWidth_energy_le _ _ (pieces_arithmetic hc hd).2 _ (by positivity)
+ _ ≤ _ := by rw [hm]; exact add_le_add_left (by simpa [bundleWidth] using hs) _
+
+/-- Total demand energy at the actual masses p/3 and p, before any supply
+substitution. The last term is the per-bundle integral rounding cost. -/
+theorem demand_energy_le (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering)
+ (w : Arc V H Tag L d c → ℕ) {p : ℝ} (hp : 0 < p) :
+ (∑ m : P.Motif, ((P.abWidth number w m : ℝ) ^ 2 / (p / 3) + (w m.1 : ℝ) ^ 2 / p)) ≤
+ (∑ a : Arc V H Tag L d c, (w a : ℝ) ^ 2 / p) +
+ Fintype.card (Site V Tag L × Fin d) * (pieceCount d c : ℝ) / (4 * (p / 3)) := by
+ let E := fun a : Arc V H Tag L d c ↦ (w a : ℝ) ^ 2 / p
+ have h := Finset.sum_le_sum (s := Finset.univ) (fun b _ ↦ P.bundle_energy_le hc hd number w hp b)
+ rw [Fintype.sum_fiberwise P.bundle (fun m ↦ (P.abWidth number w m : ℝ) ^ 2 / (p / 3)),
+ Finset.sum_add_distrib, Fintype.sum_fiberwise (fun a : P.ThickWire ↦ a.1.1)
+ (fun a ↦ (w a.1 : ℝ) ^ 2 / p)] at h
+ have hall : (∑ a : P.ThickWire, E a.1) + (∑ m : P.Motif, E m.1) = ∑ a, E a :=
+ Fintype.sum_subtype_add_sum_subtype _ E
+ rw [Finset.sum_add_distrib]
+ change _ + (∑ m : P.Motif, E m.1) ≤ (∑ a, E a) + _
+ rw [← hall, add_right_comm]
+ apply add_le_add_left
+ simpa [Finset.sum_const, mul_div_assoc] using h
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotDemandKernel.lean b/lean/OAI/Computability/VPVNP/SlotDemandKernel.lean
new file mode 100644
index 0000000000..f24e9dfac8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotDemandKernel.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.SlotDemandEnergy
+import OAI.Computability.VPVNP.NetworkKernel
+import Mathlib.Algebra.BigOperators.Fin
+
+/-!
+# Repartitioning wire payloads into the AB and CD demands
+
+A thick–thick bundle is one ordered string at A and B. Each demand reads its
+contiguous slice at both ends in the same order. This module identifies the
+individual old bits with the repartitioned bits and proves the product of
+the motif demand coefficients is exactly the original wire-network coefficient.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+/-- Enumerate all bit positions by concatenating fields in the given order. -/
+def orderedBits {A : Type*} [Fintype A] {n : ℕ} (order : A ≃ Fin n) (w : A → ℕ) :
+ (Σ a, Fin (w a)) ≃ Fin (∑ a, w a) :=
+ (Equiv.sigmaCongr order (fun a ↦ finCongr (show w a = w (order.symm (order a)) by simp))).trans
+ (finSigmaFinEquiv.trans (finCongr (order.symm.sum_comp w)))
+
+variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+/-- Old thick–thick wires whose underlying site and port identify bundle `b`. -/
+abbrev ThickFiber (b : Site V Tag L × Fin d) := {a : P.ThickWire // a.1.1 = b}
+/-- Shrinking motifs whose CD demand is assigned to bundle `b`. -/
+abbrev MotifFiber (b : Site V Tag L × Fin d) := {m : P.Motif // P.bundle m = b}
+
+/-- The numbering of old wires used at both packed ends. -/
+abbrev ThickNumbering := ∀ b : Site V Tag L × Fin d, P.ThickFiber b ≃ Fin (2 ^ c * d / 4)
+
+/-- Choose a bijection from the thick–thick wires in each bundle to the first `2 ^ c * d / 4`
+indices when `2 ≤ c`. -/
+noncomputable def thickNumbering (hc : 2 ≤ c) : P.ThickNumbering := fun b ↦
+ Fintype.equivFinOfCardEq (P.card_thick_fiber hc b)
+
+variable (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering) (order : P.ThickNumbering)
+variable (w : Arc V H Tag L d c → ℕ)
+
+/-- Pass from an AB slice and its local bit to an old wire and its local bit
+through the common offset in the concatenated payload. -/
+def demandBitEquiv (b : Site V Tag L × Fin d) :
+ (Σ m : P.MotifFiber b, Fin (P.abWidth number w m.1)) ≃
+ (Σ a : P.ThickFiber b, Fin (w a.1.1)) :=
+ (orderedBits (number b) (fun m ↦ P.abWidth number w m.1)).trans
+ ((finCongr (P.sum_abWidth hc hd number w b)).trans
+ (orderedBits (order b) (fun a ↦ w a.1.1)).symm)
+
+/-- Read the AB slice of a single motif at one packed endpoint. -/
+def abWord (x : (a : Arc V H Tag L d c) → Fin (w a) → Bool) (m : P.Motif) :
+ Fin (P.abWidth number w m) → Bool := fun i ↦
+ let z := P.demandBitEquiv hc hd number order w (P.bundle m) ⟨⟨m,rfl⟩,i⟩
+ x z.1.1.1 z.2
+
+private theorem abWord_at (x : (a : Arc V H Tag L d c) → Fin (w a) → Bool)
+ (b : Site V Tag L × Fin d) (z : Σ m : P.MotifFiber b, Fin (P.abWidth number w m.1)) :
+ P.abWord hc hd number order w x z.1.1 z.2 =
+ let a := P.demandBitEquiv hc hd number order w b z
+ x a.1.1.1 a.2 := by
+ rcases z with ⟨⟨m,hm⟩,i⟩
+ subst b
+ rfl
+
+/-- All AB tests together impose precisely equality on every old thick–thick wire. -/
+theorem abWords_eq_iff (x y : (a : Arc V H Tag L d c) → Fin (w a) → Bool) :
+ (∀ m, P.abWord hc hd number order w x m = P.abWord hc hd number order w y m) ↔
+ ∀ a : P.ThickWire, x a.1 = y a.1 := by
+ constructor
+ · intro h a
+ funext i
+ let e := P.demandBitEquiv hc hd number order w a.1.1
+ let z := e.symm ⟨⟨a,rfl⟩,i⟩
+ have eqn := congrFun (h z.1.1) z.2
+ rw [P.abWord_at hc hd number order w x _ z, P.abWord_at hc hd number order w y _ z] at eqn
+ change x (e z).1.1.1 (e z).2 = y (e z).1.1.1 (e z).2 at eqn
+ rw [show e z = ⟨⟨a,rfl⟩,i⟩ from e.apply_symm_apply _] at eqn
+ exact eqn
+ · intro h m
+ funext i
+ let a := P.demandBitEquiv hc hd number order w (P.bundle m) ⟨⟨m,rfl⟩,i⟩
+ exact congrFun (h a.1.1) a.2
+
+/-- Actual input network of the shrinking step. -/
+def oldWireNetwork : NetworkKernel.Network where
+ Site := Position V H Tag L c
+ siteFintype := inferInstance
+ Edge := Arc V H Tag L d c
+ edgeFintype := inferInstance
+ src := sourcePosition
+ dst a := sourcePosition (P.actual a)
+ Payload a := Fin (w a) → Bool
+ payloadFintype _ := inferInstance
+
+/-- Old source word of a directed wire. -/
+def outgoingWord (x : ∀ s, (P.oldWireNetwork w).Half s) (a : Arc V H Tag L d c) :
+ Fin (w a) → Bool :=
+ (x (sourcePosition a)).1 a rfl
+
+/-- Old destination word of the same wire, using its original outgoing label. -/
+def incomingWord (x : ∀ s, (P.oldWireNetwork w).Half s) (a : Arc V H Tag L d c) :
+ Fin (w a) → Bool :=
+ (x (sourcePosition (P.actual a))).2 a rfl
+
+/-- CD word at its designated thin endpoint. -/
+def cWord (x : ∀ s, (P.oldWireNetwork w).Half s) (m : P.Motif) : Fin (w m.1) → Bool :=
+ if P.thick (sourcePosition m.1) then P.incomingWord w x m.1 else P.outgoingWord w x m.1
+
+/-- CD word at its other old endpoint. -/
+def dWord (x : ∀ s, (P.oldWireNetwork w).Half s) (m : P.Motif) : Fin (w m.1) → Bool :=
+ if P.thick (sourcePosition m.1) then P.outgoingWord w x m.1 else P.incomingWord w x m.1
+
+omit [DecidableEq V] [DecidableEq Tag] [DecidableEq L] in
+private theorem cdWords_eq_iff (x : ∀ s, (P.oldWireNetwork w).Half s) (m : P.Motif) :
+ P.cWord w x m = P.dWord w x m ↔ P.outgoingWord w x m.1 = P.incomingWord w x m.1 := by
+ by_cases h : P.thick (sourcePosition m.1) <;> simp [cWord,dWord,h,eq_comm]
+
+variable {k : Type*} [CommSemiring k]
+
+/-- Coefficient of the two demand wires read from an arbitrary assignment of
+independent old half-wires. -/
+noncomputable def demandCoeff (m : P.Motif) (x : ∀ s, (P.oldWireNetwork w).Half s) : k :=
+ if P.abWord hc hd number order w (P.outgoingWord w x) m =
+ P.abWord hc hd number order w (P.incomingWord w x) m ∧
+ P.cWord w x m = P.dWord w x m then 1 else 0
+
+/-- Exact demand factorization for the shrinking step of equation (7.1). -/
+theorem oldWireNetwork_coeff (x : ∀ s, (P.oldWireNetwork w).Half s) :
+ (P.oldWireNetwork w).coeff (k := k) x = ∏ m, P.demandCoeff hc hd number order w m x := by
+ classical
+ have hcoeff : (P.oldWireNetwork w).coeff (k := k) x =
+ if ∀ a, P.outgoingWord w x a = P.incomingWord w x a then (1 : k) else 0 := by
+ let q := fun a : Arc V H Tag L d c ↦ P.outgoingWord w x a = P.incomingWord w x a
+ apply (@Fintype.prod_boole _ k _ _ q (fun _ ↦ Classical.propDecidable _)).trans
+ by_cases h : ∀ i, q i <;> simp only [q] at h ⊢ <;> simp [h]
+ rw [hcoeff]
+ simp only [demandCoeff, Fintype.prod_boole, forall_and,
+ P.abWords_eq_iff hc hd number order w, P.cdWords_eq_iff w]
+ congr 1
+ apply propext
+ constructor
+ · exact fun h ↦ ⟨fun a ↦ h a.1, fun m ↦ h m.1⟩
+ · intro ⟨h₁,h₂⟩ a
+ by_cases h : P.thick (sourcePosition a) ∧ P.thick (sourcePosition (P.actual a))
+ · exact h₁ ⟨a,h⟩
+ · exact h₂ ⟨a,h⟩
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotDemandLocal.lean b/lean/OAI/Computability/VPVNP/SlotDemandLocal.lean
new file mode 100644
index 0000000000..211f46e4be
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotDemandLocal.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.SlotDemandKernel
+
+/-!
+# Reading the four demand words locally
+
+The bit slices of an AB demand can contain pieces from several old wires.
+Every outgoing old factor in those pieces lands at the single packed A site,
+and every incoming factor lands at B. The unsplit CD words are read at the
+new site of their respective old endpoint. This supplies the demand arguments
+of the local map rows in equation (7.1).
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- All thick source positions of a bundle are packed together at A. -/
+theorem place_thick_source (layout : Bool) (a : P.ThickWire) :
+ P.placement layout (sourcePosition a.1) = a.1.1.1 := by
+ rw [placement, ite_eq_left a.2.1]
+ rfl
+
+/-- All thick destination positions of the same bundle are packed at B. -/
+theorem place_thick_target (layout : Bool) (a : P.ThickWire) :
+ P.placement layout (sourcePosition (P.actual a.1)) = (P.siteGraph.target a.1.1).1 := by
+ rw [placement, ite_eq_left a.2.2]
+ rfl
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+variable (hc : 2 ≤ c) (hd : 0 < d) (number : P.BundleNumbering) (order : P.ThickNumbering)
+variable (w : Arc V H Tag L d c → ℕ) (layout : Bool)
+
+/-- Half-wire fields of all whole old vertices placed at a single new site. -/
+abbrev PlacedHalf (s : Site V Tag L) :=
+ NetworkKernel.Placed (P.placement layout) (P.oldWireNetwork w).Half s
+
+/-- Extract the source half of the AB slice from the local inputs at A. -/
+def localAWord (m : P.Motif) (x : P.PlacedHalf w layout (P.roleA m)) :
+ Fin (P.abWidth number w m) → Bool := fun i ↦
+ let z := P.demandBitEquiv hc hd number order w (P.bundle m) ⟨⟨m,rfl⟩,i⟩
+ let h : P.roleA m = P.placement layout (sourcePosition z.1.1.1) :=
+ (congrArg Prod.fst z.1.2.symm).trans (P.place_thick_source layout z.1.1).symm
+ (x (sourcePosition z.1.1.1) h).1 z.1.1.1 rfl z.2
+
+/-- Extract the destination half of the same slice from the inputs at B. -/
+def localBWord (m : P.Motif) (x : P.PlacedHalf w layout (P.roleB m)) :
+ Fin (P.abWidth number w m) → Bool := fun i ↦
+ let z := P.demandBitEquiv hc hd number order w (P.bundle m) ⟨⟨m,rfl⟩,i⟩
+ let h : P.roleB m = P.placement layout (sourcePosition (P.actual z.1.1.1)) :=
+ (congrArg (fun b ↦ (P.siteGraph.target b).1) z.1.2.symm).trans
+ (P.place_thick_target layout z.1.1).symm
+ (x (sourcePosition (P.actual z.1.1.1)) h).2 z.1.1.1 rfl z.2
+
+/-- Extract the CD half-wire at C, whichever original slot supplied it. -/
+def localCWord (m : P.Motif) (x : P.PlacedHalf w layout (P.placement layout (P.C m))) :
+ Fin (w m.1) → Bool :=
+ if h : P.thick (sourcePosition m.1) then
+ (x (sourcePosition (P.actual m.1)) (by simp [C,h])).2 m.1 rfl
+ else (x (sourcePosition m.1) (by simp [C,h])).1 m.1 rfl
+
+/-- Read the opposite CD half-wire at D's new position. -/
+def localDWord (m : P.Motif) (x : P.PlacedHalf w layout (P.roleD layout m)) :
+ Fin (w m.1) → Bool :=
+ if h : P.thick (sourcePosition m.1) then
+ (x (sourcePosition m.1) (by simp [roleD,D,h])).1 m.1 rfl
+ else (x (sourcePosition (P.actual m.1)) (by simp [roleD,D,h])).2 m.1 rfl
+
+@[simp] theorem localAWord_eval (m : P.Motif) (x : ∀ s, (P.oldWireNetwork w).Half s) :
+ P.localAWord hc hd number order w layout m (fun u _ ↦ x u) =
+ P.abWord hc hd number order w (P.outgoingWord w x) m := rfl
+
+@[simp] theorem localBWord_eval (m : P.Motif) (x : ∀ s, (P.oldWireNetwork w).Half s) :
+ P.localBWord hc hd number order w layout m (fun u _ ↦ x u) =
+ P.abWord hc hd number order w (P.incomingWord w x) m := rfl
+
+omit [DecidableEq V] [DecidableEq Tag] [DecidableEq L] in
+@[simp] theorem localCWord_eval (m : P.Motif) (x : ∀ s, (P.oldWireNetwork w).Half s) :
+ P.localCWord w layout m (fun u _ ↦ x u) = P.cWord w x m := by
+ by_cases h : P.thick (sourcePosition m.1) <;> simp [localCWord,cWord,h] <;> rfl
+
+omit [DecidableEq V] [DecidableEq Tag] [DecidableEq L] in
+@[simp] theorem localDWord_eval (m : P.Motif) (x : ∀ s, (P.oldWireNetwork w).Half s) :
+ P.localDWord w layout m (fun u _ ↦ x u) = P.dWord w x m := by
+ by_cases h : P.thick (sourcePosition m.1) <;> simp [localDWord,dWord,h] <;> rfl
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotDemandSlices.lean b/lean/OAI/Computability/VPVNP/SlotDemandSlices.lean
new file mode 100644
index 0000000000..6a10590393
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotDemandSlices.lean
@@ -0,0 +1,91 @@
+import OAI.Computability.VPVNP.SlotDemandKernel
+
+/-!
+# Copy descriptors for the packed demand words
+
+Appendix E constructs the fields of a kernel before choosing wire bits. For
+an AB demand, intersecting the old and new intervals in the concatenated
+bundle gives three integers: a source offset, a destination offset and a
+length. The results below identify these descriptors with the exact bit
+bijection used in the coefficient identity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+/-- Starting position of a field in an ordered concatenation. -/
+def fieldStart {A : Type*} {n : ℕ} (order : A ≃ Fin n) (w : A → ℕ) (a : A) : ℕ :=
+ ∑ i : Fin (order a), w (order.symm (Fin.castLE (order a).isLt.le i))
+
+/-- Ordered concatenation preserves the position within each field. -/
+theorem orderedBits_offset {A : Type*} [Fintype A] {n : ℕ} (order : A ≃ Fin n)
+ (w : A → ℕ) (a : A) (i : Fin (w a)) :
+ (orderedBits order w ⟨a,i⟩ : ℕ) = fieldStart order w a + i := by
+ simp [orderedBits,fieldStart,Equiv.sigmaCongr]
+
+/-- The contiguous piece copied from one old field into one demand field. -/
+structure CopySlice where
+ /-- Starting bit offset within the source field for this copy. -/
+ sourceOffset : ℕ
+ /-- Starting bit offset within the target field for the same copied interval. -/
+ targetOffset : ℕ
+ /-- Number of consecutive bits copied from the source offset to the target offset. -/
+ length : ℕ
+
+/-- The shared interval starts at the larger start and ends at the smaller
+end. Truncated subtraction gives length zero for disjoint or empty fields. -/
+def copySlice (s ns t nt : ℕ) : CopySlice where
+ sourceOffset := max s t - s
+ targetOffset := max s t - t
+ length := min (s + ns) (t + nt) - max s t
+
+private theorem copySlice_spec (s ns t nt : ℕ) (i : Fin ns) (j : Fin nt) :
+ s + i = t + j ↔ ∃ k < (copySlice s ns t nt).length,
+ (i : ℕ) = (copySlice s ns t nt).sourceOffset + k ∧
+ (j : ℕ) = (copySlice s ns t nt).targetOffset + k := by
+ have hi := i.isLt
+ have hj := j.isLt
+ simp only [copySlice]
+ constructor
+ · intro he
+ exact ⟨s + i - max s t, by omega, by omega, by omega⟩
+ · rintro ⟨k,_,h₁,h₂⟩
+ omega
+
+variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable (number : P.BundleNumbering) (order : P.ThickNumbering) (w : Arc V H Tag L d c → ℕ)
+variable (b : Site V Tag L × Fin d)
+
+/-- Descriptor generated by one old field and one new piece of a bundle.
+It depends only on the two lists of widths and their combinatorial orders. -/
+def demandSlice (a : P.ThickFiber b) (m : P.MotifFiber b) : CopySlice :=
+ copySlice (fieldStart (order b) (fun x ↦ w x.1.1) a) (w a.1.1)
+ (fieldStart (number b) (fun y ↦ P.abWidth number w y.1) m) (P.abWidth number w m.1)
+
+/-- The bit bijection sends a new bit to an old bit precisely when the single
+copy descriptor for that pair of fields contains both local positions. -/
+theorem demandBitEquiv_eq_iff_slice (hc : 2 ≤ c) (hd : 0 < d) (a : P.ThickFiber b)
+ (m : P.MotifFiber b) (i : Fin (w a.1.1)) (j : Fin (P.abWidth number w m.1)) :
+ P.demandBitEquiv hc hd number order w b ⟨m,j⟩ = ⟨a,i⟩ ↔
+ let slice := P.demandSlice number order w b a m
+ ∃ k < slice.length, (i : ℕ) = slice.sourceOffset + k ∧
+ (j : ℕ) = slice.targetOffset + k := by
+ let source := orderedBits (order b) (fun x ↦ w x.1.1)
+ let dest := orderedBits (number b) (fun y ↦ P.abWidth number w y.1)
+ have h : source (P.demandBitEquiv hc hd number order w b ⟨m,j⟩) =
+ finCongr (P.sum_abWidth hc hd number w b) (dest ⟨m,j⟩) := source.apply_symm_apply _
+ rw [← source.injective.eq_iff, ← Fin.val_inj, h, finCongr_apply_coe]
+ simp only [source, dest, orderedBits_offset, demandSlice]
+ exact eq_comm.trans (copySlice_spec _ _ _ _ i j)
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotGraph.lean b/lean/OAI/Computability/VPVNP/SlotGraph.lean
new file mode 100644
index 0000000000..83249abceb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotGraph.lean
@@ -0,0 +1,84 @@
+import Mathlib.Algebra.Group.Equiv.Basic
+import Mathlib.Data.Fintype.Card
+
+/-!
+# Indexed directed regular wire graphs
+
+In Section 7 of *VP and VNP differ over every field* each vertex has `d`
+outgoing and `d` incoming slots. A permutation sends each outgoing slot to
+the unique incoming slot of its arc. The two numberings are independent.
+An arc translates its source lane by its own displacement.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+/-- A directed multigraph with separate incoming and outgoing slot numberings. -/
+structure SlotGraph (V : Type*) (d : ℕ) where
+ /-- The permutation matching each outgoing base slot to the incoming base slot at the other
+ end of its directed arc. -/
+ target : Equiv.Perm (V × Fin d)
+ ends_ne : ∀ p, (target p).1 ≠ p.1
+
+/-- A base slot graph equipped with its lane displacements. -/
+structure LiftedSlots (V : Type*) (d : ℕ) (L : Type*) where
+ /-- The directed slot graph whose arcs are lifted over the lane group. -/
+ base : SlotGraph V d
+ /-- The lane increment assigned to each outgoing base slot, added to the source lane to
+ obtain the target lane. -/
+ displacement : V × Fin d → L
+
+namespace LiftedSlots
+
+variable {V L : Type*} {d : ℕ} [AddCommGroup L] (G : LiftedSlots V d L)
+
+/-- Match each actual outgoing slot to its actual incoming slot. The inverse
+recovers the source base arc and subtracts its displacement. -/
+def actualTarget : Equiv.Perm ((V × Fin d) × L) where
+ toFun p := (G.base.target p.1, p.2 + G.displacement p.1)
+ invFun q := (G.base.target.symm q.1, q.2 - G.displacement (G.base.target.symm q.1))
+ left_inv := by rintro ⟨p, g⟩; simp
+ right_inv := by rintro ⟨q, g⟩; simp
+
+@[simp] theorem actualTarget_apply (p : V × Fin d) (g : L) :
+ G.actualTarget (p, g) = (G.base.target p, g + G.displacement p) := rfl
+
+@[simp] theorem actualTarget_symm_apply (q : V × Fin d) (g : L) :
+ G.actualTarget.symm (q, g) =
+ (G.base.target.symm q, g - G.displacement (G.base.target.symm q)) := rfl
+
+/-- Slot endpoints move together when all lanes translate by a common offset. -/
+theorem actualTarget_translate (p : V × Fin d) (g a : L) :
+ G.actualTarget (p, g + a) = ((G.actualTarget (p,g)).1, (G.actualTarget (p,g)).2 + a) := by
+ simp [add_right_comm]
+
+/-- Forget the lane structure, retaining the full directed regular graph. -/
+def actualGraph : SlotGraph (V × L) d where
+ target :=
+ let e := Equiv.prodAssoc V L (Fin d) |>.trans
+ ((Equiv.refl V).prodCongr (Equiv.prodComm L (Fin d))) |>.trans
+ (Equiv.prodAssoc V (Fin d) L).symm
+ e.trans (G.actualTarget.trans e.symm)
+ ends_ne := by
+ rintro ⟨⟨x, g⟩, i⟩ h
+ exact G.base.ends_ne (x,i) (congrArg (fun z : V × L => z.1) h)
+
+@[simp] theorem actualGraph_target (x : V) (g : L) (i : Fin d) :
+ G.actualGraph.target ((x,g),i) =
+ (((G.base.target (x,i)).1, g + G.displacement (x,i)), (G.base.target (x,i)).2) := rfl
+
+@[simp] theorem actualGraph_target_symm (y : V) (g : L) (i : Fin d) :
+ G.actualGraph.target.symm ((y,g),i) =
+ (((G.base.target.symm (y,i)).1, g - G.displacement (G.base.target.symm (y,i))),
+ (G.base.target.symm (y,i)).2) := rfl
+
+end LiftedSlots
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotGreedyScan.lean b/lean/OAI/Computability/VPVNP/SlotGreedyScan.lean
new file mode 100644
index 0000000000..f3c13eb511
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotGreedyScan.lean
@@ -0,0 +1,284 @@
+import OAI.Computability.VPVNP.SlotGraph
+import Mathlib.Data.Finset.Max
+import Mathlib.Data.Fintype.Option
+import Mathlib.Data.Fintype.Prod
+import Mathlib.Data.Fintype.Sum
+import Mathlib.Logic.Function.Basic
+
+/-!
+# The indexed greedy scans for Appendix C
+
+An indexed base admits deterministic choices of all colors and offsets.
+Each scan visits the base in increasing index order. It stores one label
+per vertex and selects the first index outside the bounded list of
+forbidden values at that vertex. The two scans provide the first local
+record construction in Appendix E of *VP and VNP differ over every field*.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+variable {V : Type*} {d : ℕ}
+
+/-- The list of increments in Appendix C's `Lₓ`: zero and the tag
+displacements of all the outgoing slots. Repeated values are harmless. -/
+def tagIncrement {Tag : Type*} [Zero Tag] (τ : V × Fin d → Tag) (x : V) :
+ Option (Fin d) → Tag
+ | none => 0
+ | some i => τ (x, i)
+
+namespace SlotGraph
+
+variable (G : SlotGraph V d) {N : ℕ}
+
+/-- The tag exclusions imposed at both incidences of each arc in Appendix C. -/
+def ValidTagOffsets {Tag : Type*} [AddCommGroup Tag] (τ : V × Fin d → Tag) (φ : V → Tag) : Prop :=
+ ∀ e, (∀ a, φ e.1 ≠ τ e + tagIncrement τ e.1 a) ∧
+ (∀ b, φ (G.target e).1 ≠ τ e + tagIncrement τ (G.target e).1 b) ∧
+ ∀ a b, φ e.1 + φ (G.target e).1 ≠
+ τ e + tagIncrement τ e.1 a + tagIncrement τ (G.target e).1 b
+
+/-- Take the least candidate index absent from the forbidden list. -/
+private def firstMissing {I : Type*} [Fintype I] {J : ℕ}
+ (f : I → Fin J) (hcard : Fintype.card I < J) : {j : Fin J // ∀ i, j ≠ f i} := by
+ let choices := Finset.univ \ Finset.univ.image f
+ have hn : choices.Nonempty := by
+ by_contra! h
+ have hs : Function.Surjective f := by
+ intro j
+ have hj : j ∉ choices := by simp [h]
+ simpa [choices] using hj
+ exact hcard.not_ge (by simpa using Fintype.card_le_of_surjective f hs)
+ refine ⟨choices.min' hn, ?_⟩
+ have h := (Finset.mem_sdiff.mp (choices.min'_mem hn)).2
+ intro i hi
+ exact h (Finset.mem_image.mpr ⟨i, Finset.mem_univ _, hi.symm⟩)
+
+private theorem firstMissing_earlier {I : Type*} [Fintype I] {J : ℕ}
+ (f : I → Fin J) (hcard : Fintype.card I < J) (k : Fin J)
+ (hk : k < (firstMissing f hcard).1) : ∃ i, f i = k := by
+ by_contra! h
+ have hm : k ∈ Finset.univ \ Finset.univ.image f := by simp [h]
+ exact hk.not_ge (Finset.min'_le _ _ hm)
+
+private def lookup {A : Type*} (order : V ≃ Fin N) (labels : Vector A N) (x : V) : A :=
+ labels[(order x).val]
+
+private def visit {A : Type*} (order : V ≃ Fin N) (select : V → (V → A) → A)
+ (labels : Vector A N) (i : Fin N) : Vector A N :=
+ labels.set i (select (order.symm i) (lookup order labels))
+
+private def scan {A : Type*} (order : V ≃ Fin N) (init : A) (select : V → (V → A) → A) : V → A :=
+ lookup order ((List.finRange N).foldl (visit order select) (Vector.replicate N init))
+
+private def goodOn {A : Type*} (allowed : V → A → Prop)
+ (compatible : V × Fin d → A → A → Prop) (s : V → Prop) (f : V → A) : Prop :=
+ (∀ x, s x → allowed x (f x)) ∧
+ ∀ e, s e.1 → s (G.target e).1 → compatible e (f e.1) (f (G.target e).1)
+
+private theorem update_good {A : Type*} [DecidableEq V] {allowed : V → A → Prop}
+ {compatible : V × Fin d → A → A → Prop} {s : V → Prop} {f : V → A}
+ (hf : G.goodOn allowed compatible s f) {x : V} {a : A} (hu : allowed x a)
+ (hout : ∀ i, compatible (x, i) a (f (G.target (x, i)).1))
+ (hin : ∀ i, compatible (G.target.symm (x, i)) (f (G.target.symm (x, i)).1) a) :
+ G.goodOn allowed compatible (fun y ↦ y = x ∨ s y) (Function.update f x a) := by
+ constructor
+ · intro y hy
+ by_cases h : y = x
+ · subst y
+ simpa using hu
+ · rw [Function.update_of_ne h]
+ exact hf.1 y (hy.resolve_left h)
+ · rintro ⟨y, i⟩ hy hz
+ by_cases h : y = x
+ · subst y
+ rw [Function.update_self, Function.update_of_ne (G.ends_ne (x, i))]
+ exact hout i
+ · rw [Function.update_of_ne h]
+ by_cases hz' : (G.target (y, i)).1 = x
+ · rw [hz', Function.update_self]
+ have eqn : G.target (y, i) = (x, (G.target (y, i)).2) := Prod.ext hz' rfl
+ simpa only [← eqn, Equiv.symm_apply_apply] using hin (G.target (y, i)).2
+ · rw [Function.update_of_ne hz']
+ exact hf.2 (y, i) (hy.resolve_left h) (hz.resolve_left hz')
+
+/-- One visit updates just the selected vertex of the partial label table. -/
+def orderedUpdate {A : Type*} [DecidableEq V] (order : V ≃ Fin N)
+ (select : V → (V → A) → A) (f : V → A) (i : Fin N) : V → A :=
+ Function.update f (order.symm i) (select (order.symm i) f)
+
+private theorem lookup_visit {A : Type*} [DecidableEq V] (order : V ≃ Fin N)
+ (select : V → (V → A) → A) (labels : Vector A N) (i : Fin N) :
+ lookup order (visit order select labels i) = orderedUpdate order select (lookup order labels) i := by
+ funext y
+ by_cases hy : y = order.symm i
+ · subst y
+ simp [lookup, visit, orderedUpdate]
+ · have hi : i.val ≠ (order y).val := fun h ↦ hy (order.eq_symm_apply.mpr (Fin.ext h.symm))
+ simp [visit, lookup, hi, orderedUpdate, Function.update_of_ne hy]
+
+private theorem scan_eq_fold {A : Type*} [DecidableEq V] (order : V ≃ Fin N)
+ (init : A) (select : V → (V → A) → A) :
+ scan order init select = (List.finRange N).foldl (orderedUpdate order select) (fun _ ↦ init) := by
+ have fold (ids : List (Fin N)) (labels : Vector A N) :
+ lookup order (ids.foldl (visit order select) labels) =
+ ids.foldl (orderedUpdate order select) (lookup order labels) := by
+ induction ids generalizing labels with
+ | nil => rfl
+ | cons i ids ih => simp only [List.foldl_cons, ih, lookup_visit]
+ rw [scan, fold]
+ congr 1
+ funext x
+ simp [lookup]
+
+private theorem scan_valid {A : Type*} (order : V ≃ Fin N) (init : A) (select : V → (V → A) → A)
+ (allowed : V → A → Prop) (compatible : V × Fin d → A → A → Prop)
+ (step : ∀ x f, allowed x (select x f) ∧
+ (∀ i, compatible (x, i) (select x f) (f (G.target (x, i)).1)) ∧
+ (∀ i, compatible (G.target.symm (x, i)) (f (G.target.symm (x, i)).1) (select x f))) :
+ (∀ x, allowed x (scan order init select x)) ∧
+ ∀ e, compatible e (scan order init select e.1) (scan order init select (G.target e).1) := by
+ classical
+ have walk (ids : List (Fin N)) (s : V → Prop) (labels : Vector A N)
+ (hs : G.goodOn allowed compatible s (lookup order labels)) :
+ G.goodOn allowed compatible (fun x ↦ order x ∈ ids ∨ s x)
+ (lookup order (ids.foldl (visit order select) labels)) := by
+ induction ids generalizing s labels with
+ | nil => simpa only [List.foldl_nil, List.not_mem_nil, false_or] using hs
+ | cons i ids ih =>
+ obtain ⟨hu, hout, hin⟩ := step (order.symm i) (lookup order labels)
+ have h := G.update_good hs hu hout hin
+ change G.goodOn _ _ _ (orderedUpdate order select (lookup order labels) i) at h
+ rw [← lookup_visit order select] at h
+ have ht := ih _ _ h
+ simpa only [List.foldl_cons, List.mem_cons, order.eq_symm_apply,
+ or_assoc, or_left_comm] using ht
+ have h := walk (List.finRange N) (fun _ ↦ False) (Vector.replicate N init)
+ (by simp [goodOn])
+ exact ⟨fun x ↦ h.1 x (Or.inl (List.mem_finRange _)),
+ fun e ↦ h.2 e (Or.inl (List.mem_finRange _)) (Or.inl (List.mem_finRange _))⟩
+
+/-- The colors currently stored at the outgoing and incoming neighbors of a vertex, indexed by
+direction and slot number. -/
+def colorForbidden (x : V) (f : V → Fin (2 * d + 1)) : Bool × Fin d → Fin (2 * d + 1)
+ | (true, i) => f (G.target (x, i)).1
+ | (false, i) => f (G.target.symm (x, i)).1
+
+/-- Least permissible color at a vertex of a partially filled table. -/
+def chooseColor (x : V) (f : V → Fin (2 * d + 1)) : Fin (2 * d + 1) :=
+ (firstMissing (G.colorForbidden x f) (by simp)).1
+
+theorem chooseColor_spec (x : V) (f : V → Fin (2 * d + 1)) :
+ (∀ t, G.chooseColor x f ≠ G.colorForbidden x f t) ∧
+ (∀ k < G.chooseColor x f, ∃ t, G.colorForbidden x f t = k) :=
+ ⟨(firstMissing (G.colorForbidden x f) (by simp)).2,
+ firstMissing_earlier (G.colorForbidden x f) (by simp)⟩
+
+/-- Select a proper coloring by visiting the indexed base once, reading
+only colors at the two lists of neighboring endpoints. -/
+def orderedColor (order : V ≃ Fin N) : V → Fin (2 * d + 1) :=
+ scan order 0 G.chooseColor
+
+theorem orderedColor_fold [DecidableEq V] (order : V ≃ Fin N) :
+ G.orderedColor order = (List.finRange N).foldl (orderedUpdate order G.chooseColor) (fun _ ↦ 0) :=
+ scan_eq_fold order 0 G.chooseColor
+
+theorem orderedColor_proper (order : V ≃ Fin N) (e : V × Fin d) :
+ G.orderedColor order e.1 ≠ G.orderedColor order (G.target e).1 := by
+ let select (x : V) (f : V → Fin (2 * d + 1)) := (firstMissing (G.colorForbidden x f) (by simp)).1
+ have h := G.scan_valid order 0 select (fun _ _ ↦ True) (fun _ a b ↦ a ≠ b) (fun x f ↦
+ ⟨trivial, fun i ↦ (firstMissing (G.colorForbidden x f) (by simp)).2 (true, i),
+ fun i ↦ ((firstMissing (G.colorForbidden x f) (by simp)).2 (false, i)).symm⟩)
+ exact h.2 e
+
+variable {Tag : Type*} [AddCommGroup Tag] {J : ℕ}
+
+/-- Indices for the forbidden-tag tests, recording an incident arc and either one local
+increment or a pair of endpoint increments. -/
+abbrev TagTests (d : ℕ) :=
+ (Bool × Fin d) × (Option (Fin d) ⊕ (Option (Fin d) × Option (Fin d)))
+
+/-- Compute the excluded tag for one incident-arc test from its displacement and the specified
+increments, using the neighboring tag assignment in the two-endpoint case. -/
+def tagForbidden (τ : V × Fin d → Tag) (x : V) (f : V → Tag) : TagTests d → Tag
+ | ((true, i), .inl a) => τ (x, i) + tagIncrement τ x a
+ | ((false, i), .inl a) => τ (G.target.symm (x, i)) + tagIncrement τ x a
+ | ((true, i), .inr (a, b)) =>
+ let y := (G.target (x, i)).1
+ τ (x, i) + tagIncrement τ x a + tagIncrement τ y b - f y
+ | ((false, i), .inr (a, b)) =>
+ let e := G.target.symm (x, i)
+ τ e + tagIncrement τ e.1 a + tagIncrement τ x b - f e.1
+
+/-- Choose the least indexed tag outside the forbidden list for the current vertex and partial
+tag assignment. -/
+def chooseTag (index : Tag ≃ Fin J) (τ : V × Fin d → Tag)
+ (hcard : 2 * d * ((d + 1) + (d + 1) ^ 2) < J) (x : V) (f : V → Tag) : Tag :=
+ index.symm (firstMissing (index ∘ G.tagForbidden τ x f)
+ (by simpa [TagTests, pow_two] using hcard)).1
+
+theorem chooseTag_spec (index : Tag ≃ Fin J) (τ : V × Fin d → Tag)
+ (hcard : 2 * d * ((d + 1) + (d + 1) ^ 2) < J) (x : V) (f : V → Tag) :
+ (∀ t, index (G.chooseTag index τ hcard x f) ≠ index (G.tagForbidden τ x f t)) ∧
+ (∀ k < index (G.chooseTag index τ hcard x f), ∃ t, index (G.tagForbidden τ x f t) = k) := by
+ unfold chooseTag
+ rw [Equiv.apply_symm_apply]
+ exact ⟨(firstMissing (index ∘ G.tagForbidden τ x f)
+ (by simpa [TagTests, pow_two] using hcard)).2,
+ firstMissing_earlier (index ∘ G.tagForbidden τ x f) _⟩
+
+/-- Select tag offsets in one indexed base scan. Every step examines a
+list of at most `2d((d+1)+(d+1)²)` forbidden indices, counting duplicates. -/
+def orderedTagOffsets (order : V ≃ Fin N) (index : Tag ≃ Fin J) (τ : V × Fin d → Tag)
+ (hcard : 2 * d * ((d + 1) + (d + 1) ^ 2) < J) : V → Tag :=
+ scan order 0 (G.chooseTag index τ hcard)
+
+theorem orderedTagOffsets_fold [DecidableEq V] (order : V ≃ Fin N) (index : Tag ≃ Fin J)
+ (τ : V × Fin d → Tag) (hcard : 2 * d * ((d + 1) + (d + 1) ^ 2) < J) :
+ G.orderedTagOffsets order index τ hcard =
+ (List.finRange N).foldl (orderedUpdate order (G.chooseTag index τ hcard)) (fun _ ↦ 0) :=
+ scan_eq_fold order 0 (G.chooseTag index τ hcard)
+
+theorem orderedTagOffsets_valid (order : V ≃ Fin N) (index : Tag ≃ Fin J) (τ : V × Fin d → Tag)
+ (hcard : 2 * d * ((d + 1) + (d + 1) ^ 2) < J) :
+ G.ValidTagOffsets τ (G.orderedTagOffsets order index τ hcard) := by
+ let allowed (x : V) (t : Tag) := ∀ i a,
+ t ≠ τ (x, i) + tagIncrement τ x a ∧ t ≠ τ (G.target.symm (x, i)) + tagIncrement τ x a
+ let compatible (e : V × Fin d) (t u : Tag) := ∀ a b,
+ t + u ≠ τ e + tagIncrement τ e.1 a + tagIncrement τ (G.target e).1 b
+ have step (x : V) (f : V → Tag) :
+ allowed x (G.chooseTag index τ hcard x f) ∧
+ (∀ i, compatible (x, i) (G.chooseTag index τ hcard x f) (f (G.target (x, i)).1)) ∧
+ (∀ i, compatible (G.target.symm (x, i)) (f (G.target.symm (x, i)).1)
+ (G.chooseTag index τ hcard x f)) := by
+ let t := G.chooseTag index τ hcard x f
+ have ht (i : TagTests d) : t ≠ G.tagForbidden τ x f i := by
+ intro hi
+ exact (firstMissing (index ∘ G.tagForbidden τ x f)
+ (by simpa [TagTests, pow_two] using hcard)).2 i
+ (by simpa only [t, chooseTag, Equiv.apply_symm_apply, Function.comp_apply] using
+ congrArg index hi)
+ refine ⟨fun i a ↦ ⟨ht ((true, i), .inl a), ht ((false, i), .inl a)⟩, ?_, ?_⟩
+ · intro i a b h
+ exact ht ((true, i), .inr (a, b)) (eq_sub_iff_add_eq.mpr h)
+ · intro i a b h
+ apply ht ((false, i), .inr (a, b))
+ apply eq_sub_iff_add_eq.mpr
+ simpa only [Equiv.apply_symm_apply, add_comm t] using h
+ obtain ⟨hu, he⟩ := G.scan_valid order 0 (G.chooseTag index τ hcard) allowed compatible step
+ intro e
+ refine ⟨fun a ↦ (hu e.1 e.2 a).1, ?_, he e⟩
+ intro b
+ simpa only [orderedTagOffsets, Prod.mk.eta, Equiv.symm_apply_apply] using
+ (hu (G.target e).1 (G.target e).2 b).2
+
+end SlotGraph
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotIdentifierOrder.lean b/lean/OAI/Computability/VPVNP/SlotIdentifierOrder.lean
new file mode 100644
index 0000000000..48c89317c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotIdentifierOrder.lean
@@ -0,0 +1,76 @@
+import OAI.Computability.VPVNP.BitSlotIndex
+import OAI.Computability.VPVNP.SlotTranslation
+import OAI.Computability.VPVNP.SurvivingSlots
+
+/-!
+# Integer keys for the unweighted shrinking slots
+
+Appendix C numbers surviving slots using their motif ID, surviving type
+and subdivision. A lane-zero motif is recovered from the base and tag of
+the original CD wire, its old outgoing slot, its color bits and its slot
+coordinate. Packing these fields into integers gives an explicit order
+with no dependence on widths, maps, or the unconsumed lane length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+open SurvivingSlots
+
+variable {V H Tag L : Type*} {d c N J : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- Mixed-radix index of the source coordinates of the original CD wire,
+suppressing its remaining lane, which is zero in a base representative. -/
+def baseMotifIndex (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (m : P.BaseMotif) :
+ Fin (N * (J * (d * (2 ^ c * d)))) :=
+ let a := m.1.1
+ finProdFinEquiv (vertices a.1.1.1, finProdFinEquiv (tags a.1.1.2.1,
+ finProdFinEquiv (a.1.2, finProdFinEquiv (bitWordFinEquiv c a.2.1, P.slotLabel a.2.2))))
+
+theorem baseMotifIndex_injective (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) :
+ Function.Injective (P.baseMotifIndex vertices tags) := by
+ rintro ⟨⟨⟨⟨⟨x, j, g⟩, i⟩, u, h⟩, hm⟩, hg⟩ ⟨⟨⟨⟨⟨x', j', g'⟩, i'⟩, u', h'⟩, hm'⟩, hg'⟩ eqn
+ change g = 0 at hg
+ change g' = 0 at hg'
+ subst g
+ subst g'
+ simp only [baseMotifIndex, EmbeddingLike.apply_eq_iff_eq, Prod.mk.injEq] at eqn
+ obtain ⟨rfl, rfl, rfl, rfl, rfl⟩ := eqn
+ rfl
+
+/-- Mixed-radix integer key for a role edge. Subdivision indices use the
+sum of all four subdivision counts as their common radix. -/
+def slotIdentifier (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (subdiv : Fin 4 → ℕ)
+ (i : Id P.BaseMotif subdiv) :
+ Fin (4 * ((N * (J * (d * (2 ^ c * d)))) * ∑ t, subdiv t)) :=
+ let bound : subdiv i.1 ≤ ∑ t, subdiv t :=
+ Finset.single_le_sum (fun t _ ↦ Nat.zero_le (subdiv t)) (Finset.mem_univ _)
+ finProdFinEquiv (i.1, finProdFinEquiv
+ (P.baseMotifIndex vertices tags i.2.1, Fin.castLE bound i.2.2))
+
+theorem slotIdentifier_injective (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (subdiv : Fin 4 → ℕ) :
+ Function.Injective (P.slotIdentifier vertices tags subdiv) := by
+ rintro ⟨t, m, i⟩ ⟨t', m', i'⟩ h
+ simp only [slotIdentifier, EmbeddingLike.apply_eq_iff_eq, Prod.mk.injEq] at h
+ obtain ⟨rfl, hm, hi⟩ := h
+ obtain rfl := P.baseMotifIndex_injective vertices tags hm
+ have hidx : i = i' := Fin.ext (congrArg (fun j : Fin (∑ t, subdiv t) ↦ j.val) hi)
+ subst i'
+ rfl
+
+/-- Sorting the lane-zero IDs is ordinary integer sorting of their keys. -/
+@[instance_reducible]
+def slotIdentifierOrder (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (subdiv : Fin 4 → ℕ) :
+ LinearOrder (Id P.BaseMotif subdiv) :=
+ LinearOrder.lift' _ (P.slotIdentifier_injective vertices tags subdiv)
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotIncidence.lean b/lean/OAI/Computability/VPVNP/SlotIncidence.lean
new file mode 100644
index 0000000000..bd2aa0594d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotIncidence.lean
@@ -0,0 +1,51 @@
+import OAI.Computability.VPVNP.SlotPacking
+
+/-!
+# Directed incidences at the thin endpoint
+
+Appendix C assigns each non-thick–thick wire to the bundle of its thin
+endpoint C. The original direction breaks ties on thin–thin wires. Incoming
+wires can be enumerated at their target through the inverse slot permutation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+variable {V H Tag L : Type*} {d c : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- Partition the actual CD wires by their old direction relative to C.
+The predicate may inspect either old position. This allows the same
+enumeration to count demands by bundle or by the new position of D. -/
+def cdIncidenceEquiv (p : Position V H Tag L c → Position V H Tag L c → Prop) :
+ {m : P.Motif // p (P.C m) (P.D m)} ≃
+ {a : Arc V H Tag L d c // ¬ P.thick (sourcePosition a) ∧
+ p (sourcePosition a) (sourcePosition (P.actual a))} ⊕
+ {a : Arc V H Tag L d c // P.thick (sourcePosition (P.actual.symm a)) ∧
+ ¬ P.thick (sourcePosition a) ∧ p (sourcePosition a) (sourcePosition (P.actual.symm a))} where
+ toFun m :=
+ if hs : P.thick (sourcePosition m.1.1) then
+ Sum.inr ⟨P.actual m.1.1, by
+ simp only [Equiv.symm_apply_apply]
+ exact ⟨hs, fun ht ↦ m.1.2 ⟨hs, ht⟩, by simpa [C, D, hs] using m.2⟩⟩
+ else Sum.inl ⟨m.1.1, hs, by simpa [C, D, hs] using m.2⟩
+ invFun
+ | .inl a => ⟨⟨a.1, fun h ↦ a.2.1 h.1⟩, by simpa [C, D, a.2.1] using a.2.2⟩
+ | .inr a => ⟨⟨P.actual.symm a.1, fun h ↦ a.2.2.1 (by simpa using h.2)⟩, by
+ simpa [C, D, a.2.1] using a.2.2.2⟩
+ left_inv m := by
+ by_cases hs : P.thick (sourcePosition m.1.1) <;> simp [hs]
+ right_inv a := by
+ rcases a with a | a
+ · simp [a.2.1]
+ · simp [a.2.1]
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotOtherEnd.lean b/lean/OAI/Computability/VPVNP/SlotOtherEnd.lean
new file mode 100644
index 0000000000..6b51015427
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotOtherEnd.lean
@@ -0,0 +1,167 @@
+import OAI.Computability.VPVNP.SlotBundleCount
+
+/-!
+# Placements of the D endpoint
+
+At any site in either layout, D can arise at the thick end of a mixed wire
+in either direction, or at the destination of an old thin–thin wire. Each
+of these three cases contributes `d*K/4` incidences. In the last case the
+bundle used to place D is its own bundle, which can differ from C's.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.PackingData
+
+variable {V H Tag L : Type*} {d c : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- Send a thin endpoint's assigned bundle to its chosen side, retaining
+that side's local slot number. -/
+def layoutPorts (layout : Bool) : Equiv.Perm (Site V Tag L × Fin d) :=
+ if layout then P.siteGraph.target else Equiv.refl _
+
+private abbrev srcThick (a : Arc V H Tag L d c) := P.thick (sourcePosition a)
+
+omit [AddCommGroup H] in
+private theorem place_thin (l : Bool) (a : Arc V H Tag L d c) (h : ¬ P.srcThick a) :
+ P.placement l (sourcePosition a) =
+ (P.layoutPorts l (P.assignedBundle (sourcePosition a))).1 := by
+ cases l <;> simp [placement, layoutPorts, srcThick] at h ⊢ <;> simp [h]
+
+private theorem place_source (l : Bool) (m : P.Motif) (h : P.srcThick m.val) :
+ P.roleD l m = m.val.1.1 := by
+ unfold roleD D
+ rw [ite_eq_left h]
+ unfold placement
+ rw [ite_eq_left h]
+ rfl
+
+private theorem place_target (l : Bool) (m : P.Motif) (hs : ¬ P.srcThick m.val)
+ (ht : P.srcThick (P.actual m.val)) : P.roleD l m = (P.actual m.val).1.1 := by
+ unfold roleD D
+ rw [ite_eq_right hs]
+ unfold placement
+ rw [ite_eq_left ht]
+ rfl
+
+private def dCases (l : Bool) (s : Site V Tag L) :
+ {m : P.Motif // P.roleD l m = s} ≃
+ {a : Arc V H Tag L d c // (P.srcThick a ∧ ¬ P.srcThick (P.actual a)) ∧ a.1.1 = s} ⊕
+ {a : Arc V H Tag L d c // (¬ P.srcThick a ∧ P.srcThick (P.actual a)) ∧
+ (P.actual a).1.1 = s} ⊕
+ {a : Arc V H Tag L d c // (¬ P.srcThick a ∧ ¬ P.srcThick (P.actual a)) ∧
+ (P.layoutPorts l (P.assignedBundle (sourcePosition (P.actual a)))).1 = s} where
+ toFun m :=
+ if hs : P.srcThick m.1.1 then .inl ⟨m.1.1, ⟨hs, fun ht ↦ m.1.2 ⟨hs,ht⟩⟩,
+ (P.place_source l m.1 hs).symm.trans m.2⟩
+ else if ht : P.srcThick (P.actual m.1.1) then .inr (.inl ⟨m.1.1, ⟨hs, ht⟩,
+ (P.place_target l m.1 hs ht).symm.trans m.2⟩)
+ else .inr (.inr ⟨m.1.1, ⟨hs, ht⟩, by
+ simpa [roleD, D, hs, P.place_thin l _ ht] using m.2⟩)
+ invFun
+ | .inl a =>
+ let m : P.Motif := ⟨a.1, fun h ↦ a.2.1.2 h.2⟩
+ ⟨m, (P.place_source l m a.2.1.1).trans a.2.2⟩
+ | .inr (.inl a) =>
+ let m : P.Motif := ⟨a.1, fun h ↦ a.2.1.1 h.1⟩
+ ⟨m, (P.place_target l m a.2.1.1 a.2.1.2).trans a.2.2⟩
+ | .inr (.inr a) => ⟨⟨a.1, fun h ↦ a.2.1.1 h.1⟩, by
+ simpa [roleD, D, a.2.1.1, P.place_thin l _ a.2.1.2] using a.2.2⟩
+ left_inv m := by
+ by_cases hs : P.srcThick m.1.1 <;> by_cases ht : P.srcThick (P.actual m.1.1) <;> simp [hs, ht]
+ right_inv a := by
+ rcases a with a | (a | a) <;> simp [a.2.1.1, a.2.1.2]
+
+private def bySlot {A S : Type*} (port : A → S × Fin d) (p : A → Prop) (s : S) :
+ {a : A // p a ∧ (port a).1 = s} ≃ Σ i : Fin d, {a : A // p a ∧ port a = (s,i)} where
+ toFun a := ⟨(port a.1).2, a.1, a.2.1, Prod.ext a.2.2 rfl⟩
+ invFun z := ⟨z.2.1, z.2.2.1, congrArg Prod.fst z.2.2.2⟩
+ left_inv _ := rfl
+ right_inv z := by
+ obtain ⟨i, a, ha, he⟩ := z
+ have hi : (port a).2 = i := congrArg Prod.snd he
+ subst i
+ rfl
+
+private theorem count_bySlot {A S : Type*} [Fintype A] (port : A → S × Fin d) (p : A → Prop)
+ [DecidablePred p] [DecidableEq S]
+ (s : S) (k : ℕ) (h : ∀ b, Fintype.card {a : A // p a ∧ port a = b} = k) :
+ Fintype.card {a : A // p a ∧ (port a).1 = s} = d * k := by
+ rw [Fintype.card_congr (bySlot port p s), Fintype.card_sigma]
+ simp [h]
+
+private theorem bit_ne_one (v : ZMod 2) : v ≠ 1 ↔ v = 0 :=
+ (by decide : ∀ v : ZMod 2, v ≠ 1 ↔ v = 0) v
+
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+variable [Fintype V] [Fintype Tag] [Fintype H] [Fintype L]
+
+private theorem count_mixedOut (hc : 2 ≤ c) (b : Site V Tag L × Fin d) :
+ Fintype.card {a : Arc V H Tag L d c // (P.srcThick a ∧ ¬ P.srcThick (P.actual a)) ∧
+ a.1 = b} = 2 ^ c * d / 4 := by
+ have e := Equiv.subtypeEquivRight (p := fun a : Arc V H Tag L d c ↦
+ (P.srcThick a ∧ ¬ P.srcThick (P.actual a)) ∧ a.1 = b)
+ (q := fun a ↦ a.1 = b ∧ P.arcBit a = 1 ∧ P.arcBit (P.actual a) = 0)
+ (fun a ↦ by change (_ ∧ P.arcBit (P.actual a) ≠ 1) ∧ _ ↔ _; rw [bit_ne_one]; tauto)
+ exact (Fintype.card_congr e).trans (P.card_bundle_types hc b 1 0)
+
+private theorem count_mixedIn (hc : 2 ≤ c) (b : Site V Tag L × Fin d) :
+ Fintype.card {a : Arc V H Tag L d c // (¬ P.srcThick a ∧ P.srcThick (P.actual a)) ∧
+ (P.actual a).1 = b} = 2 ^ c * d / 4 := by
+ have e := Equiv.subtypeEquivRight (p := fun a : Arc V H Tag L d c ↦
+ (¬ P.srcThick a ∧ P.srcThick (P.actual a)) ∧ (P.actual a).1 = b)
+ (q := fun a ↦ a.1 = P.siteGraph.target.symm b ∧ P.arcBit a = 0 ∧ P.arcBit (P.actual a) = 1)
+ (fun a ↦ by
+ change (P.arcBit a ≠ 1 ∧ _) ∧ P.siteGraph.target a.1 = b ↔ _
+ rw [bit_ne_one, ← Equiv.eq_symm_apply]
+ tauto)
+ exact (Fintype.card_congr e).trans (P.card_bundle_types hc _ 0 1)
+
+private theorem count_thinIn (l : Bool) (b : Site V Tag L × Fin d) :
+ Fintype.card {a : Arc V H Tag L d c // (¬ P.srcThick a ∧ ¬ P.srcThick (P.actual a)) ∧
+ P.layoutPorts l (P.assignedBundle (sourcePosition (P.actual a))) = b} =
+ d * 2 ^ (c - 2) := by
+ let b' := (P.layoutPorts l).symm b
+ let p := fun a : Arc V H Tag L d c ↦ ¬ P.srcThick (P.actual.symm a) ∧ ¬ P.srcThick a
+ have e := P.actual.subtypeEquiv (p := fun a ↦ (¬ P.srcThick a ∧ ¬ P.srcThick (P.actual a)) ∧
+ P.layoutPorts l (P.assignedBundle (sourcePosition (P.actual a))) = b)
+ (q := fun a ↦ p a ∧ P.assignedBundle (sourcePosition a) = b') (fun a ↦ by
+ simp only [p, b', Equiv.symm_apply_apply, ← Equiv.eq_symm_apply])
+ rw [Fintype.card_congr (e.trans (P.assignedArcEquiv b' p)), Fintype.card_sigma]
+ have count (i : Fin d) : Fintype.card {w : BitWord c // p (P.arcAtBundle b' i w)} =
+ 2 ^ (c - 2) := by
+ let old := P.slots.target.symm (b'.1.1, i)
+ have hne : P.color old.1 ≠ P.color b'.1.1 := by simpa [old] using P.proper old
+ change Fintype.card {w : BitWord c //
+ w (P.color old.1) - P.bitShift old (P.color old.1) ≠ 1 ∧ w (P.color b'.1.1) ≠ 1} = _
+ simpa only [sub_eq_add_neg, add_zero, bit_ne_one, Fintype.card_fin] using
+ SlotPacking.card_translatedBits hne (-P.bitShift old (P.color old.1)) 0 0 0
+ simp [count]
+
+/-- Both layouts give exactly `dQ` occurrences of D at every new position. -/
+theorem card_roleD (hc : 2 ≤ c) (l : Bool) (s : Site V Tag L) :
+ Fintype.card {m : P.Motif // P.roleD l m = s} = d * (3 * (2 ^ c * d) / 4) := by
+ rw [Fintype.card_congr (P.dCases l s), Fintype.card_sum, Fintype.card_sum]
+ rw [count_bySlot (fun a : Arc V H Tag L d c ↦ a.1)
+ (fun a ↦ P.srcThick a ∧ ¬ P.srcThick (P.actual a)) s _ (P.count_mixedOut hc),
+ count_bySlot (fun a : Arc V H Tag L d c ↦ (P.actual a).1)
+ (fun a ↦ ¬ P.srcThick a ∧ P.srcThick (P.actual a)) s _ (P.count_mixedIn hc),
+ count_bySlot (fun a ↦ P.layoutPorts l (P.assignedBundle (sourcePosition (P.actual a))))
+ (fun a ↦ ¬ P.srcThick a ∧ ¬ P.srcThick (P.actual a)) s _ (P.count_thinIn l)]
+ obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le hc
+ rw [pow_add, Nat.add_sub_cancel_left]
+ have h : (2:ℕ) ^ 2 * 2 ^ k * d = 4 * (d * 2 ^ k) := by ring
+ rw [h]
+ have ht : 3 * (4 * (d * 2 ^ k)) / 4 = 3 * (d * 2 ^ k) := by omega
+ rw [ht, Nat.mul_div_cancel_left _ (by decide : 0 < 4)]
+ ring
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotPacking.lean b/lean/OAI/Computability/VPVNP/SlotPacking.lean
new file mode 100644
index 0000000000..03294a0eba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotPacking.lean
@@ -0,0 +1,150 @@
+import OAI.Computability.VPVNP.SlotGraph
+import Mathlib.Data.ZMod.Basic
+
+/-!
+# Positions, bundles and placements for the shrinking step
+
+Appendix C of *VP and VNP differ over every field* splits a lane into color
+bits, an outgoing-slot label, a tag and an unconsumed lane. A wire whose
+endpoints are both thick goes into the bundle indexed by its base arc, source
+tag and remaining lane. Every other wire supplies exactly one CD demand. Its
+C endpoint is thin, with ties settled by the original direction of the arc.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+/-- A word of the given length with entries in the additive group of integers modulo two. -/
+abbrev BitWord (c : ℕ) := Fin c → ZMod 2
+/-- A packed site specified by a base vertex, a tag, and the unconsumed lane coordinate. -/
+abbrev Site (V Tag L : Type*) := V × (Tag × L)
+/-- An old position specified by its packed site, color-bit word, and lane coordinate used to
+label a slot. -/
+abbrev Position (V H Tag L : Type*) (c : ℕ) := Site V Tag L × (BitWord c × H)
+/-- An old arc address consisting of a site, an incident slot number, and the color and
+slot-label coordinates of its lane. -/
+abbrev Arc (V H Tag L : Type*) (d c : ℕ) := (Site V Tag L × Fin d) × (BitWord c × H)
+
+/-- Input to Appendix C after selecting the proper coloring and tag offsets.
+The bijection `slotLabel` lets the lane use a binary vector group even when
+the graph's outgoing slots are labeled by `Fin d`. -/
+structure PackingData (V H Tag L : Type*) (d c : ℕ) where
+ /-- The directed regular base graph matching outgoing and incoming slots for the shrinking
+ step. -/
+ slots : SlotGraph V d
+ /-- The proper coloring of the base vertices used to select the bit that determines whether a
+ position is thick. -/
+ color : V → Fin c
+ proper : ∀ p, color p.1 ≠ color (slots.target p).1
+ /-- Bijection from the slot-label coordinate of a lane to the index of one of the outgoing
+ slots. -/
+ slotLabel : H ≃ Fin d
+ /-- Tag increment at each base vertex used when assigning a thin position to its outgoing
+ bundle. -/
+ offset : V → Tag
+ /-- Change in the color-bit word along each base arc, added to the source word when lifting
+ the arc. -/
+ bitShift : V × Fin d → BitWord c
+ /-- Additive displacement of the slot-label coordinate along each base arc. -/
+ slotShift : V × Fin d → H
+ /-- Displacement of the tag and unconsumed lane coordinates along a base arc of the lifted
+ site graph. -/
+ siteShift : V × Fin d → Tag × L
+
+variable {V H Tag L : Type*} {d c : ℕ}
+
+/-- Forget the slot of an outgoing (or, dually, incoming) endpoint. -/
+def sourcePosition (a : Arc V H Tag L d c) : Position V H Tag L c := (a.1.1, a.2)
+
+namespace PackingData
+
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- Once the color bits and slot label are suppressed, bundles themselves
+form a regular lift with only tag and remaining-lane coordinates. -/
+def siteGraph : SlotGraph (Site V Tag L) d := (LiftedSlots.mk P.slots P.siteShift).actualGraph
+
+/-- Each old arc's permutation of the complete coordinate tuple. -/
+def actual : Equiv.Perm (Arc V H Tag L d c) :=
+ (LiftedSlots.mk P.siteGraph (fun p ↦
+ (P.bitShift (p.1.1,p.2), P.slotShift (p.1.1,p.2)))).actualTarget
+
+@[simp] theorem actual_apply (p : Site V Tag L × Fin d) (w : BitWord c) (h : H) :
+ P.actual (p,w,h) = (P.siteGraph.target p,w + P.bitShift (p.1.1,p.2),
+ h + P.slotShift (p.1.1,p.2)) := rfl
+
+@[simp] theorem actual_symm_apply (p : Site V Tag L × Fin d) (w : BitWord c) (h : H) :
+ P.actual.symm (p,w,h) = (P.siteGraph.target.symm p,
+ w - P.bitShift (P.slots.target.symm (p.1.1,p.2)),
+ h - P.slotShift (P.slots.target.symm (p.1.1,p.2))) := rfl
+
+/-- Test the bit belonging to the position's base color. -/
+def thick (x : Position V H Tag L c) : Prop := x.2.1 (P.color x.1.1) = 1
+
+instance (x : Position V H Tag L c) : Decidable (P.thick x) := by unfold thick; infer_instance
+
+/-- The bundle assignment offsets the tag while preserving the unconsumed lane. -/
+def offsetSite : Equiv.Perm (Site V Tag L) where
+ toFun x := (x.1, x.2.1 + P.offset x.1, x.2.2)
+ invFun x := (x.1, x.2.1 - P.offset x.1, x.2.2)
+ left_inv := by rintro ⟨x,t,g⟩; simp
+ right_inv := by rintro ⟨x,t,g⟩; simp
+
+/-- Each thin position is assigned to its own outgoing slot at the offset tag. -/
+def assignedBundle (x : Position V H Tag L c) : Site V Tag L × Fin d :=
+ (P.offsetSite x.1, P.slotLabel x.2.2)
+
+/-- The demand motifs are indexed by all actual wires outside thick–thick bundles. -/
+abbrev Motif := {a : Arc V H Tag L d c //
+ ¬ (P.thick (sourcePosition a) ∧ P.thick (sourcePosition (P.actual a)))}
+
+/-- On a thin–thin wire `C` is the outgoing endpoint. -/
+def C (m : P.Motif) : Position V H Tag L c :=
+ if P.thick (sourcePosition m.val) then sourcePosition (P.actual m.val) else sourcePosition m.val
+
+/-- The old endpoint opposite `C`. -/
+def D (m : P.Motif) : Position V H Tag L c :=
+ if P.thick (sourcePosition m.val) then sourcePosition m.val else sourcePosition (P.actual m.val)
+
+/-- In both possible directions the designated C endpoint is thin. -/
+theorem not_thick_C (m : P.Motif) : ¬ P.thick (P.C m) := by
+ unfold C
+ split_ifs with h
+ · exact fun ht ↦ m.property ⟨h,ht⟩
+ · exact h
+
+/-- The single bundle which receives this CD demand. -/
+def bundle (m : P.Motif) : Site V Tag L × Fin d := P.assignedBundle (P.C m)
+
+/-- The source site of the bundle assigned to a demand motif, serving as its A site. -/
+def roleA (m : P.Motif) : Site V Tag L := (P.bundle m).1
+
+/-- The target site of the bundle assigned to a demand motif, serving as its B site. -/
+def roleB (m : P.Motif) : Site V Tag L := (P.siteGraph.target (P.bundle m)).1
+
+/-- `false` puts every thin position at the source of its assigned bundle,
+`true` puts it at the destination. Every thick position stays at its packed site. -/
+def placement (layout : Bool) (x : Position V H Tag L c) : Site V Tag L :=
+ if P.thick x then x.1 else if layout then (P.siteGraph.target (P.assignedBundle x)).1
+ else (P.assignedBundle x).1
+
+/-- A `D` map moves with the whole old factor at that position. -/
+def roleD (layout : Bool) (m : P.Motif) : Site V Tag L := P.placement layout (P.D m)
+
+@[simp] theorem placement_C_source (m : P.Motif) : P.placement false (P.C m) = P.roleA m := by
+ simp [placement, P.not_thick_C, roleA, bundle]
+
+@[simp] theorem placement_C_target (m : P.Motif) : P.placement true (P.C m) = P.roleB m := by
+ simp [placement, P.not_thick_C, roleB, bundle]
+
+end PackingData
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotRegularization.lean b/lean/OAI/Computability/VPVNP/SlotRegularization.lean
new file mode 100644
index 0000000000..514a13e062
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotRegularization.lean
@@ -0,0 +1,181 @@
+import OAI.Computability.VPVNP.SlotGraph
+import Mathlib.Data.Finset.Sort
+import Mathlib.Logic.Equiv.Fin.Rotate
+
+/-!
+# Regularizing labeled wire slots
+
+In Section 7.2 and Appendix C of *VP and VNP differ over every field*,
+surviving role edges carry an identifier for their motif, role pair and
+subdivision number. Once their two base-endpoint fibers have a common size,
+the fibers can be numbered separately. Parallel dummy edges fill any
+deficit. All numbering is at the base, so it transports along the remaining
+lane without depending on widths.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+variable {B E L : Type*} {k d : ℕ}
+
+/-- Both endpoint numberings of a set of identified arcs, with their lane
+displacements. The incoming slot of an ID is the target of its outgoing slot. -/
+structure SlotIndexing (B E L : Type*) (d : ℕ) (src dst : E → B) (shift : E → L) where
+ /-- The lifted slot graph implementing the given source, target, and lane displacement for
+ every arc identifier. -/
+ graph : LiftedSlots B d L
+ /-- The bijection assigning each arc identifier its source base vertex and local outgoing
+ slot number. -/
+ outgoing : E ≃ B × Fin d
+ /-- The bijection assigning each arc identifier its target base vertex and local incoming
+ slot number. -/
+ incoming : E ≃ B × Fin d
+ src_eq : ∀ e, (outgoing e).1 = src e
+ dst_eq : ∀ e, (incoming e).1 = dst e
+ match_eq : ∀ e, graph.base.target (outgoing e) = incoming e
+ displacement_eq : ∀ e, graph.displacement (outgoing e) = shift e
+
+/-- At any absolute source lane the ID gives both slot addresses and the
+destination lane, with the same endpoint numberings at every translate. -/
+theorem SlotIndexing.actualTarget [AddCommGroup L] {src dst : E → B} {shift : E → L}
+ (I : SlotIndexing B E L d src dst shift) (e : E) (g : L) :
+ I.graph.actualTarget (I.outgoing e, g) = (I.incoming e, g + shift e) := by
+ simp [I.match_eq, I.displacement_eq]
+
+/-- Number each endpoint fiber by its ID order. -/
+private def numberFiber [Fintype E] [LinearOrder E] [DecidableEq B]
+ (endpoint : E → B) (h : ∀ b, Fintype.card {e // endpoint e = b} = k) : E ≃ B × Fin k :=
+ (Equiv.sigmaFiberEquiv endpoint).symm.trans (Equiv.sigmaEquivProdOfEquiv
+ fun b ↦ (Fintype.orderIsoFinOfCardEq {e // endpoint e = b} (h b)).symm.toEquiv)
+
+/-- Padding attaches one new ID per missing outgoing slot at each base. -/
+abbrev PaddedId (B E : Type*) (deficit : ℕ) := E ⊕ B × Fin deficit
+
+/-- All padded arcs leave the vertex in their ID. -/
+def paddedSource (src : E → B) : PaddedId B E k → B := Sum.elim src Prod.fst
+
+/-- The added slots advance the base through a common permutation. -/
+def paddedTarget (dst : E → B) (next : Equiv.Perm B) : PaddedId B E k → B :=
+ Sum.elim dst fun p ↦ next p.1
+
+/-- Dummy arcs preserve the remaining lane. -/
+def paddedShift [Zero L] (shift : E → L) : PaddedId B E k → L := Sum.elim shift (fun _ ↦ 0)
+
+/-- For arbitrary widths, including lane-dependent ones, assign zero to
+each dummy arc. -/
+def paddedWidth (width : E → L → ℕ) : PaddedId B E k → L → ℕ := Sum.elim width (fun _ _ ↦ 0)
+
+/-- A common deficit in the two endpoint counts can be padded to degree
+`d`. Real slots keep their ID order inside each fiber and dummy slots follow
+them. The next-base permutation may be the cyclic shift on the tag. -/
+def paddedSlotIndexing [Fintype E] [LinearOrder E] [DecidableEq B] [Zero L]
+ (src dst : E → B) (shift : E → L) (hends : ∀ e, dst e ≠ src e)
+ (hsrc : ∀ b, Fintype.card {e // src e = b} = k)
+ (hdst : ∀ b, Fintype.card {e // dst e = b} = k)
+ (hkd : k ≤ d) (next : Equiv.Perm B) (hnext : ∀ b, next b ≠ b) :
+ SlotIndexing B (PaddedId B E (d - k)) L d (paddedSource src) (paddedTarget dst next)
+ (paddedShift shift) := by
+ let combine : (B × Fin k ⊕ B × Fin (d - k)) ≃ B × Fin d :=
+ (Equiv.prodSumDistrib B (Fin k) (Fin (d - k))).symm.trans
+ ((Equiv.refl B).prodCongr (finSumFinEquiv.trans (finCongr (Nat.add_sub_of_le hkd))))
+ let out := (Equiv.sumCongr (numberFiber src hsrc) (Equiv.refl (B × Fin (d - k)))).trans combine
+ let inc := (Equiv.sumCongr (numberFiber dst hdst)
+ (next.prodCongr (Equiv.refl (Fin (d - k))))).trans combine
+ have source (e : PaddedId B E (d - k)) : (out e).1 = paddedSource src e := by
+ cases e <;> rfl
+ have target (e : PaddedId B E (d - k)) : (inc e).1 = paddedTarget dst next e := by
+ cases e <;> rfl
+ let G : SlotGraph B d := {
+ target := out.symm.trans inc
+ ends_ne := by
+ intro p
+ obtain ⟨e, rfl⟩ := out.surjective p
+ change (inc (out.symm (out e))).1 ≠ (out e).1
+ rw [out.symm_apply_apply, source, target]
+ cases e with
+ | inl e => exact hends e
+ | inr p => exact hnext p.1 }
+ exact {
+ graph := ⟨G, fun p ↦ paddedShift shift (out.symm p)⟩
+ outgoing := out
+ incoming := inc
+ src_eq := source
+ dst_eq := target
+ match_eq e := congrArg inc (out.symm_apply_apply e)
+ displacement_eq e := congrArg (paddedShift shift) (out.symm_apply_apply e) }
+
+private theorem numberFiber_rank [Fintype E] [LinearOrder E] [DecidableEq B]
+ (endpoint : E → B) (h : ∀ b, Fintype.card {e // endpoint e = b} = k)
+ (e : E) (ids : Finset E) (hids : ∀ a, a ∈ ids ↔ endpoint a = endpoint e) :
+ ((numberFiber endpoint h e).2 : ℕ) = (ids.filter (· < e)).card := by
+ let F := {a // endpoint a = endpoint e}
+ let label := (Fintype.orderIsoFinOfCardEq F (h (endpoint e))).symm
+ let a₀ : F := ⟨e, rfl⟩
+ let smaller := label.toEquiv.subtypeEquiv (p := fun a : F ↦ a < a₀)
+ (q := fun i : Fin k ↦ (i : ℕ) < (label a₀).val) (fun a ↦ by
+ change a < a₀ ↔ label a < label a₀
+ simp)
+ let members : {a : F // a < a₀} ≃ (ids.filter (· < e)) := {
+ toFun := fun a ↦ ⟨a.1.1, Finset.mem_filter.mpr ⟨(hids _).mpr a.1.2, a.2⟩⟩
+ invFun := fun a ↦ ⟨⟨a.1, (hids _).mp (Finset.mem_filter.mp a.2).1⟩,
+ (Finset.mem_filter.mp a.2).2⟩
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ change (label a₀).val = _
+ rw [← Fintype.card_fin_lt_of_le (label a₀).isLt.le, ← Fintype.card_congr smaller,
+ Fintype.card_congr members, Fintype.card_coe]
+
+/-- The two slot numbers of a real ID can be recovered from the two local
+incidence lists alone. Each is the number of smaller IDs in its list. -/
+theorem paddedSlot_numbers [Fintype E] [LinearOrder E] [DecidableEq B] [Zero L]
+ (src dst : E → B) (shift : E → L) (hends : ∀ e, dst e ≠ src e)
+ (hsrc : ∀ b, Fintype.card {e // src e = b} = k)
+ (hdst : ∀ b, Fintype.card {e // dst e = b} = k)
+ (hkd : k ≤ d) (next : Equiv.Perm B) (hnext : ∀ b, next b ≠ b)
+ (e : E) (outIds inIds : Finset E) (hout : ∀ a, a ∈ outIds ↔ src a = src e)
+ (hin : ∀ a, a ∈ inIds ↔ dst a = dst e) :
+ let I := paddedSlotIndexing src dst shift hends hsrc hdst hkd next hnext
+ ((I.outgoing (.inl e)).2 : ℕ) = (outIds.filter (· < e)).card ∧
+ ((I.incoming (.inl e)).2 : ℕ) = (inIds.filter (· < e)).card :=
+ ⟨numberFiber_rank src hsrc e outIds hout, numberFiber_rank dst hdst e inIds hin⟩
+
+/-- Dummy slots follow the genuine incidence list in both numberings. -/
+theorem paddedSlot_dummy_numbers [Fintype E] [LinearOrder E] [DecidableEq B] [Zero L]
+ (src dst : E → B) (shift : E → L) (hends : ∀ e, dst e ≠ src e)
+ (hsrc : ∀ b, Fintype.card {e // src e = b} = k)
+ (hdst : ∀ b, Fintype.card {e // dst e = b} = k)
+ (hkd : k ≤ d) (next : Equiv.Perm B) (hnext : ∀ b, next b ≠ b) (b : B) (i : Fin (d - k)) :
+ let I := paddedSlotIndexing src dst shift hends hsrc hdst hkd next hnext
+ ((I.outgoing (.inr (b, i))).2 : ℕ) = k + i ∧ ((I.incoming (.inr (b, i))).2 : ℕ) = k + i :=
+ ⟨rfl, rfl⟩
+
+/-- Cyclic dummy slots change only the tag of the new base. -/
+def cycleTags {V Tag : Type*} {J : ℕ} (index : Tag ≃ Fin J) : Equiv.Perm (V × Tag) :=
+ (Equiv.refl V).prodCongr (index.trans ((finRotate J).trans index.symm))
+
+theorem cycleTags_ne {V Tag : Type*} {J : ℕ} (index : Tag ≃ Fin J) (hJ : 1 < J)
+ (b : V × Tag) : cycleTags index b ≠ b := by
+ intro h
+ have hrot := congrArg (fun p : V × Tag ↦ index p.2) h
+ change index (index.symm (finRotate J (index b.2))) = index b.2 at hrot
+ rw [index.apply_symm_apply] at hrot
+ cases J with
+ | zero => omega
+ | succ n =>
+ have he := congrArg Fin.val hrot
+ rw [coe_finRotate] at he
+ split at he
+ · rename_i hlast
+ rw [hlast] at he
+ simp at he
+ omega
+ · omega
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotSeparation.lean b/lean/OAI/Computability/VPVNP/SlotSeparation.lean
new file mode 100644
index 0000000000..c9831b6a78
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotSeparation.lean
@@ -0,0 +1,121 @@
+import OAI.Computability.VPVNP.SlotPacking
+import OAI.Computability.VPVNP.SlotTags
+
+/-!
+# Separation of the three bases in each shrinking motif
+
+Appendix C of *VP and VNP differ over every field* assigns one base and
+tag to each packed position. Both layouts keep the three roles of a motif
+at distinct such pairs. The binary tag group makes an arc displacement
+the same in both directions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+variable {V H Tag L : Type*} {d c : ℕ}
+
+/-- The base after packing consists of the old base and the packed tag. -/
+def packedBase (s : Site V Tag L) : V × Tag := (s.1, s.2.1)
+
+namespace PackingData
+
+variable [AddCommGroup H] [AddCommGroup Tag] [Module (ZMod 2) Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- The tag component of the old arc displacement. -/
+def tagShift (e : V × Fin d) : Tag := (P.siteShift e).1
+
+private theorem motifTagConditions (m : P.Motif)
+ (hφ : P.slots.ValidTagOffsets P.tagShift P.offset) :
+ ∃ t, (P.D m).1.2.1 = (P.C m).1.2.1 + t ∧
+ (∀ a, P.offset (P.C m).1.1 ≠ t + tagIncrement P.tagShift (P.C m).1.1 a) ∧
+ ∀ a b, P.offset (P.C m).1.1 + P.offset (P.D m).1.1 ≠ t +
+ tagIncrement P.tagShift (P.C m).1.1 a + tagIncrement P.tagShift (P.D m).1.1 b := by
+ let e := (m.val.1.1.1, m.val.1.2)
+ obtain ⟨hout, hin, hpair⟩ := hφ e
+ refine ⟨P.tagShift e, ?_⟩
+ by_cases hs : P.thick (sourcePosition m.val)
+ · simp only [D, C, ite_eq_left hs]
+ refine ⟨?_, hin, ?_⟩
+ · change m.val.1.1.2.1 = m.val.1.1.2.1 + P.tagShift e + P.tagShift e
+ rw [add_assoc, ZModModule.add_self, add_zero]
+ · intro a b
+ change P.offset (P.slots.target e).1 + P.offset e.1 ≠ P.tagShift e +
+ tagIncrement P.tagShift (P.slots.target e).1 a + tagIncrement P.tagShift e.1 b
+ simpa only [add_comm, add_left_comm, add_assoc] using hpair b a
+ · simp only [D, C, ite_eq_right hs]
+ exact ⟨rfl, hout, hpair⟩
+
+/-- Excluding the unary and binary shifts keeps either bundle tag distinct
+from the placed tag of the other endpoint, for each choice of layout. -/
+private theorem tag_ne_placed (m : P.Motif) (layout : Bool)
+ (hφ : P.slots.ValidTagOffsets P.tagShift P.offset) (a : Option (Fin d)) :
+ (P.C m).1.2.1 + (P.offset (P.C m).1.1 + tagIncrement P.tagShift (P.C m).1.1 a) ≠
+ (P.roleD layout m).2.1 := by
+ obtain ⟨t, htag, hsingle, hpair⟩ := P.motifTagConditions m hφ
+ by_cases hd : P.thick (P.D m)
+ · rw [roleD, placement, ite_eq_left hd, htag]
+ intro he
+ exact hsingle a ((eq_sub_iff_add_eq.mpr (add_left_cancel he)).trans (ZModModule.sub_eq_add ..))
+ · have placed : ∃ b, (P.roleD layout m).2.1 = (P.D m).1.2.1 +
+ (P.offset (P.D m).1.1 + tagIncrement P.tagShift (P.D m).1.1 b) := by
+ cases layout with
+ | false =>
+ refine ⟨none, ?_⟩
+ rw [roleD, placement, ite_eq_right hd]
+ change _ = _ + (_ + 0)
+ rw [add_zero]
+ rfl
+ | true =>
+ refine ⟨some (P.slotLabel (P.D m).2.2), ?_⟩
+ rw [roleD, placement, ite_eq_right hd]
+ exact add_assoc ..
+ obtain ⟨b, hb⟩ := placed
+ rw [hb, htag, add_assoc (P.C m).1.2.1 t]
+ intro he
+ have h := add_left_cancel he
+ let u := P.offset (P.C m).1.1
+ let v := P.offset (P.D m).1.1
+ let s := tagIncrement P.tagShift (P.C m).1.1 a
+ let r := tagIncrement P.tagShift (P.D m).1.1 b
+ change u + s = t + (v + r) at h
+ apply hpair a b
+ change u + v = t + s + r
+ calc
+ u + v = (u + v) + (s + s) := by rw [ZModModule.add_self, add_zero]
+ _ = (u + s) + (v + s) := by ac_rfl
+ _ = (t + (v + r)) + (v + s) := by rw [h]
+ _ = (t + s + r) + (v + v) := by ac_rfl
+ _ = t + s + r := by rw [ZModModule.add_self, add_zero]
+
+/-- The packed bases of the three roles are pairwise distinct in every
+motif, simultaneously for the source and target layouts. -/
+theorem distinct_roleBases (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (layout : Bool) (m : P.Motif) :
+ packedBase (P.roleA m) ≠ packedBase (P.roleB m) ∧
+ packedBase (P.roleA m) ≠ packedBase (P.roleD layout m) ∧
+ packedBase (P.roleB m) ≠ packedBase (P.roleD layout m) := by
+ refine ⟨?_, ?_, ?_⟩
+ · intro h
+ exact P.slots.ends_ne ((P.C m).1.1, P.slotLabel (P.C m).2.2) (congrArg Prod.fst h).symm
+ · intro h
+ apply P.tag_ne_placed m layout hφ none
+ change _ + (_ + 0) = _
+ rw [add_zero]
+ exact congrArg Prod.snd h
+ · intro h
+ apply P.tag_ne_placed m layout hφ (some (P.slotLabel (P.C m).2.2))
+ rw [← add_assoc]
+ exact congrArg Prod.snd h
+
+end PackingData
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotSubdivision.lean b/lean/OAI/Computability/VPVNP/SlotSubdivision.lean
new file mode 100644
index 0000000000..2f7b3a2562
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotSubdivision.lean
@@ -0,0 +1,103 @@
+import Mathlib.Algebra.Order.Floor.Semifield
+import Mathlib.Algebra.Order.BigOperators.Ring.Finset
+import Mathlib.Algebra.BigOperators.Field
+import Mathlib.Algebra.Order.Archimedean.Real.Basic
+import Mathlib.Tactic.FieldSimp
+import Mathlib.Tactic.Linarith
+import Mathlib.Tactic.LinearCombination
+import Mathlib.Tactic.Ring
+
+/-!
+# The subdivision counts in degree regularization
+
+In §7.2 of *VP and VNP differ over every field*, an old wire has mass
+`p` and a new slot has mass `p * K * d / d'`. Thus the floor count depends
+only on the degrees, the packing ratio and the supply type's relative mass.
+The same degree threshold works for every position count and every term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.SlotSubdivision
+
+/-- Number of regularized slots for one surviving supply edge. -/
+noncomputable def count (K d d' : ℕ) (q : ℝ) : ℕ := ⌊(d' : ℝ) * q / (K * d)⌋₊
+
+/-- For the paper's rational supply masses, ordinary natural division computes
+the subdivisions used in the local circuit descriptions. -/
+theorem count_fraction (K d d' a b : ℕ) :
+ count K d d' ((a : ℝ) / b) = d' * a / (b * K * d) := by
+ rw [count, ← Nat.floor_div_eq_div (K := ℝ)]
+ congr 1
+ simp only [Nat.cast_mul, div_eq_mul_inv, mul_inv_rev]
+ ring
+
+variable {T : Type*}
+
+/-- For every sufficiently large output degree, the floored counts are positive
+and represent at least `1-δ` of each type's old mass. In particular the same
+threshold works when output degrees are restricted to powers of two. -/
+theorem eventually_represented [Finite T] (q : T → ℝ) (hq : ∀ t, 0 < q t) {K d : ℕ}
+ (hK : 0 < K) (hd : 0 < d) {δ : ℝ} (hδ : 0 < δ) (hδ' : δ < 1) :
+ ∃ N : ℕ, ∀ d' ≥ N, 0 < d' ∧ ∀ (p p' : ℝ), 0 < p → p' = p * (K * d) / d' →
+ ∀ t, 0 < count K d d' (q t) ∧
+ (1 - δ) * p * q t ≤ (count K d d' (q t) : ℝ) * p' := by
+ let := Fintype.ofFinite T
+ let S : ℝ := K * d
+ have hS : 0 < S := mul_pos (Nat.cast_pos.mpr hK) (Nat.cast_pos.mpr hd)
+ let bound (t : T) := S / (δ * q t)
+ have hbound (t : T) : 0 ≤ bound t := (div_pos hS (mul_pos hδ (hq t))).le
+ obtain ⟨N, hN⟩ := exists_nat_gt (∑ t, bound t)
+ refine ⟨N, fun d' hd' ↦ ?_⟩
+ have hdn : (∑ t, bound t) < (d' : ℝ) := hN.trans_le (Nat.cast_le.mpr hd')
+ have hpos : 0 < (d' : ℝ) := (Finset.sum_nonneg (fun t _ ↦ hbound t)).trans_lt hdn
+ refine ⟨Nat.cast_pos.mp hpos, ?_⟩
+ rintro p _ hp rfl t
+ have ht : bound t < (d' : ℝ) :=
+ (Finset.single_le_sum (fun s _ ↦ hbound s) (Finset.mem_univ t)).trans_lt hdn
+ have hscaled : S < (d' : ℝ) * (δ * q t) := (div_lt_iff₀ (mul_pos hδ (hq t))).mp ht
+ let x := (d' : ℝ) * q t / S
+ have hx : 0 < x := div_pos (mul_pos hpos (hq t)) hS
+ have hxδ : 1 < δ * x := by
+ dsimp only [x]
+ rw [← mul_div_assoc]
+ apply (lt_div_iff₀ hS).mpr
+ simpa only [one_mul, mul_assoc, mul_left_comm] using hscaled
+ have hlower : (1 - δ) * x ≤ (count K d d' (q t) : ℝ) := by
+ change (1 - δ) * x ≤ (⌊x⌋₊ : ℝ)
+ linarith only [Nat.lt_floor_add_one x, hxδ]
+ refine ⟨Nat.cast_pos.mp ((mul_pos (sub_pos.mpr hδ') hx).trans_le hlower), ?_⟩
+ calc
+ (1 - δ) * p * q t = ((1 - δ) * x) * (p * S / d') := by
+ dsimp only [x]
+ field_simp
+ _ ≤ _ := mul_le_mul_of_nonneg_right hlower (div_pos (mul_pos hp hS) hpos).le
+
+/-- The sum of the floored subdivisions fits inside the available output degree.
+Each of the four types has `d * Q` incidences at each site, and the relative
+masses of one surviving group sum to `4/3`. -/
+theorem degree_budget [Fintype T] (q : T → ℝ) (hq : ∀ t, 0 ≤ q t) (htotal : ∑ t, q t = 4 / 3)
+ {K Q d d' : ℕ} (hK : 0 < K) (hd : 0 < d) (hQ : 4 * Q = 3 * K) :
+ d * Q * ∑ t, count K d d' (q t) ≤ d' := by
+ let S : ℝ := K * d
+ have hS : 0 < S := mul_pos (Nat.cast_pos.mpr hK) (Nat.cast_pos.mpr hd)
+ have hsum : ∑ t, (count K d d' (q t) : ℝ) ≤ (d' : ℝ) * (4 / 3) / S := calc
+ _ ≤ ∑ t, (d' : ℝ) * q t / S :=
+ Finset.sum_le_sum fun t _ ↦ Nat.floor_le
+ (div_nonneg (mul_nonneg (Nat.cast_nonneg _) (hq t)) hS.le)
+ _ = _ := by rw [← Finset.sum_div, ← Finset.mul_sum, htotal]
+ have hQ' : 4 * (Q : ℝ) = 3 * (K : ℝ) := by exact_mod_cast hQ
+ have h := mul_le_mul_of_nonneg_left hsum (mul_nonneg (Nat.cast_nonneg d) (Nat.cast_nonneg Q))
+ have hright : (d : ℝ) * Q * ((d' : ℝ) * (4 / 3) / S) = d' := by
+ dsimp only [S]
+ field_simp
+ linear_combination (d' : ℝ) * hQ'
+ exact_mod_cast h.trans_eq hright
+
+end Compression.SlotSubdivision
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotTags.lean b/lean/OAI/Computability/VPVNP/SlotTags.lean
new file mode 100644
index 0000000000..c2022f3600
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotTags.lean
@@ -0,0 +1,40 @@
+import OAI.Computability.VPVNP.SlotGreedyScan
+import Mathlib.Data.Fintype.EquivFin
+
+/-!
+# Greedy coloring and tag offsets for a finite base
+
+In Appendix C of *VP and VNP differ over every field*, the color and
+offset scans apply to any finite base. Choosing enumerations of the
+base and tags gives the two existence statements used for wire packing.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.SlotGraph
+
+variable {V : Type*} [Finite V] {d : ℕ} (G : SlotGraph V d)
+
+/-- The two ends of every base arc have distinct colors using `2d + 1`
+colors. The bound counts both incoming and outgoing slots. -/
+theorem exists_baseColor :
+ ∃ color : V → Fin (2 * d + 1), ∀ e, color e.1 ≠ color (G.target e).1 := by
+ let := Fintype.ofFinite V
+ exact ⟨G.orderedColor (Fintype.equivFin V), G.orderedColor_proper _⟩
+
+/-- The unary and binary conditions on the offsets at all incidences can
+be satisfied simultaneously with the indicated tag cardinality. -/
+theorem exists_tagOffsets {Tag : Type*} [AddCommGroup Tag] [Fintype Tag] (τ : V × Fin d → Tag)
+ (hcard : 2 * d * ((d + 1) + (d + 1) ^ 2) < Fintype.card Tag) :
+ ∃ φ : V → Tag, G.ValidTagOffsets τ φ := by
+ let := Fintype.ofFinite V
+ exact ⟨G.orderedTagOffsets (Fintype.equivFin V) (Fintype.equivFin Tag) τ hcard,
+ G.orderedTagOffsets_valid _ _ τ hcard⟩
+
+end Compression.SlotGraph
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SlotTranslation.lean b/lean/OAI/Computability/VPVNP/SlotTranslation.lean
new file mode 100644
index 0000000000..a1989d03af
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SlotTranslation.lean
@@ -0,0 +1,171 @@
+import OAI.Computability.VPVNP.SlotPacking
+
+/-!
+# Translation on the unconsumed lane
+
+In the last part of Appendix C, a common layout commutes with translation
+in the remaining lane. Each orbit of actual motifs is represented uniquely
+by the motif whose original wire starts at lane zero. A surviving role edge
+over that representative lifts with one fixed lane displacement.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+variable {V H Tag L : Type*} {d c : ℕ} [AddCommGroup L]
+
+/-- Move a packed site in its remaining lane, retaining the old base and tag. -/
+def translateSite (s : Site V Tag L) (g : L) : Site V Tag L := (s.1,s.2.1,s.2.2 + g)
+
+/-- Move the packed-site component, retaining the slot label and color bits. -/
+def translatePosition (p : Position V H Tag L c) (g : L) : Position V H Tag L c :=
+ (translateSite p.1 g,p.2)
+
+/-- The action on original arc labels is given in outgoing numbering. -/
+def translateArc (a : Arc V H Tag L d c) (g : L) : Arc V H Tag L d c :=
+ ((translateSite a.1.1 g,a.1.2),a.2)
+
+@[simp] theorem translateSite_zero (s : Site V Tag L) : translateSite s 0 = s := by
+ simp [translateSite]
+
+@[simp] theorem translateSite_add (s : Site V Tag L) (g h : L) :
+ translateSite (translateSite s g) h = translateSite s (g + h) := by
+ simp [translateSite, add_assoc]
+
+@[simp] theorem translateArc_zero (a : Arc V H Tag L d c) : translateArc a 0 = a := by
+ simp [translateArc]
+
+@[simp] theorem translateArc_add (a : Arc V H Tag L d c) (g h : L) :
+ translateArc (translateArc a g) h = translateArc a (g + h) := by simp [translateArc]
+
+@[simp] theorem sourcePosition_translate (a : Arc V H Tag L d c) (g : L) :
+ sourcePosition (translateArc a g) = translatePosition (sourcePosition a) g := rfl
+
+namespace PackingData
+
+variable (P : PackingData V H Tag L d c)
+
+@[simp] theorem thick_translate (p : Position V H Tag L c) (g : L) :
+ P.thick (translatePosition p g) ↔ P.thick p := Iff.rfl
+
+variable [AddCommGroup Tag]
+
+@[simp] theorem siteGraph_translate (s : Site V Tag L) (i : Fin d) (g : L) :
+ P.siteGraph.target (translateSite s g,i) =
+ (translateSite (P.siteGraph.target (s,i)).1 g,(P.siteGraph.target (s,i)).2) := by
+ rcases s with ⟨v,t,l⟩
+ simp [siteGraph, translateSite, add_right_comm]
+ rfl
+
+@[simp] theorem assignedBundle_translate (x : Position V H Tag L c) (g : L) :
+ P.assignedBundle (translatePosition x g) =
+ (translateSite (P.assignedBundle x).1 g,(P.assignedBundle x).2) := rfl
+
+variable [AddCommGroup H]
+
+@[simp] theorem actual_translate (a : Arc V H Tag L d c) (g : L) :
+ P.actual (translateArc a g) = translateArc (P.actual a) g := by
+ rcases a with ⟨⟨s,i⟩,u,h⟩
+ simp only [translateArc, actual_apply, siteGraph_translate]
+ rfl
+
+/-- Translation on actual arcs restricts to the wires indexing the motifs. -/
+def translateMotif (m : P.Motif) (g : L) : P.Motif :=
+ ⟨translateArc m.1 g, by simpa only [actual_translate, sourcePosition_translate,
+ thick_translate] using m.2⟩
+
+@[simp] theorem translateMotif_zero (m : P.Motif) : P.translateMotif m 0 = m :=
+ Subtype.ext (translateArc_zero _)
+
+@[simp] theorem translateMotif_add (m : P.Motif) (g h : L) :
+ P.translateMotif (P.translateMotif m g) h = P.translateMotif m (g + h) :=
+ Subtype.ext (translateArc_add ..)
+
+@[simp] theorem C_translate (m : P.Motif) (g : L) :
+ P.C (P.translateMotif m g) = translatePosition (P.C m) g := by
+ by_cases h : P.thick (sourcePosition m.1) <;> simp [C, translateMotif, h]
+
+@[simp] theorem D_translate (m : P.Motif) (g : L) :
+ P.D (P.translateMotif m g) = translatePosition (P.D m) g := by
+ by_cases h : P.thick (sourcePosition m.1) <;> simp [D, translateMotif, h]
+
+@[simp] theorem bundle_translate (m : P.Motif) (g : L) :
+ P.bundle (P.translateMotif m g) = (translateSite (P.bundle m).1 g,(P.bundle m).2) := by
+ simp [bundle]
+
+@[simp] theorem roleA_translate (m : P.Motif) (g : L) :
+ P.roleA (P.translateMotif m g) = translateSite (P.roleA m) g := by simp [roleA]
+
+@[simp] theorem roleB_translate (m : P.Motif) (g : L) :
+ P.roleB (P.translateMotif m g) = translateSite (P.roleB m) g := by simp [roleB]
+
+omit [AddCommGroup H] in
+@[simp] theorem placement_translate (layout : Bool) (x : Position V H Tag L c) (g : L) :
+ P.placement layout (translatePosition x g) = translateSite (P.placement layout x) g := by
+ by_cases h : P.thick x <;> cases layout <;> simp [placement, h] <;> rfl
+
+@[simp] theorem roleD_translate (layout : Bool) (m : P.Motif) (g : L) :
+ P.roleD layout (P.translateMotif m g) = translateSite (P.roleD layout m) g := by simp [roleD]
+
+/-- Unconsumed lane of the old wire in its original outgoing numbering. -/
+def sourceLane (m : P.Motif) : L := (sourcePosition m.1).1.2.2
+
+@[simp] theorem sourceLane_translate (m : P.Motif) (g : L) :
+ P.sourceLane (P.translateMotif m g) = P.sourceLane m + g := rfl
+
+/-- Finite orbit labels for motifs, indexed by representatives at source lane zero. -/
+abbrev BaseMotif := {m : P.Motif // P.sourceLane m = 0}
+
+/-- The representative obtained by translating the source back to zero. -/
+def baseMotif (m : P.Motif) : P.BaseMotif :=
+ ⟨P.translateMotif m (-P.sourceLane m), by simp⟩
+
+@[simp] theorem baseMotif_translate (m : P.Motif) (g : L) :
+ P.baseMotif (P.translateMotif m g) = P.baseMotif m := by
+ apply Subtype.ext
+ simp [baseMotif]
+
+@[simp] theorem baseMotif_coe (m : P.BaseMotif) : P.baseMotif m.1 = m := by
+ apply Subtype.ext
+ simp [baseMotif,m.2]
+
+/-- A motif is specified by its lane-zero label and the remaining lane. -/
+def motifLaneEquiv : P.Motif ≃ P.BaseMotif × L where
+ toFun m := (P.baseMotif m,P.sourceLane m)
+ invFun a := P.translateMotif a.1.1 a.2
+ left_inv m := by simp [baseMotif]
+ right_inv a := by rcases a with ⟨m,g⟩; simp [m.2]
+
+@[simp] theorem motifLaneEquiv_symm_apply (m : P.BaseMotif) (g : L) :
+ P.motifLaneEquiv.symm (m,g) = P.translateMotif m.1 g := rfl
+
+/-- Reindex an orbit by the lane of any chosen source role of a surviving edge. -/
+def roleLaneEquiv (s : P.Motif → Site V Tag L)
+ (hs : ∀ m g, s (P.translateMotif m g) = translateSite (s m) g) :
+ P.Motif ≃ P.BaseMotif × L where
+ toFun m := (P.baseMotif m,(s m).2.2)
+ invFun a := P.translateMotif a.1.1 (a.2 - (s a.1.1).2.2)
+ left_inv m := by simp [baseMotif, hs, translateSite]
+ right_inv a := by rcases a with ⟨m,g⟩; simp [hs,translateSite]
+
+/-- The lift of a surviving edge, enumerated by its source-role lane, has
+displacement equal to the difference of the two lane-zero role coordinates. -/
+theorem roleLane_endpoints (s t : P.Motif → Site V Tag L)
+ (hs : ∀ m g, s (P.translateMotif m g) = translateSite (s m) g)
+ (ht : ∀ m g, t (P.translateMotif m g) = translateSite (t m) g)
+ (z : P.BaseMotif) (g : L) :
+ let m := (P.roleLaneEquiv s hs).symm (z,g)
+ s m = ((s z.1).1,(s z.1).2.1,g) ∧
+ t m = ((t z.1).1,(t z.1).2.1,g + ((t z.1).2.2 - (s z.1).2.2)) := by
+ simp [roleLaneEquiv, hs, ht, translateSite, sub_eq_add_neg, add_left_comm]
+
+end PackingData
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SmallPrime.lean b/lean/OAI/Computability/VPVNP/SmallPrime.lean
new file mode 100644
index 0000000000..18dae35485
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SmallPrime.lean
@@ -0,0 +1,53 @@
+import Mathlib.NumberTheory.Chebyshev
+
+/-!
+# A small characteristic preserving a nonzero integer minor
+
+Section 8.2 of *VP and VNP differ over every field* needs a prime avoiding a
+nonzero integer determinant. If the determinant has absolute value at most
+`2 ^ B`, the prime may be taken at most `2 * (B + 2) ^ 2`. The elementary
+estimate for the least common multiple of the first `n` integers gives this
+polynomial bound directly.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+/-- A positive integer of at most `B + 1` binary digits has a nondividing
+prime bounded quadratically in `B`. -/
+theorem exists_small_prime_not_dvd {D B : ℕ} (hD : D ≠ 0) (hB : D ≤ 2 ^ B) :
+ ∃ p : ℕ, p.Prime ∧ p ≤ 2 * (B + 2) ^ 2 ∧ ¬ p ∣ D := by
+ let n := 2 * (B + 2) ^ 2
+ let k := 2 * (B + 2)
+ have hn : n ≠ 0 := by dsimp [n]; positivity
+ have hsize : n + 1 ≤ 2 ^ k := Nat.two_mul_sq_add_one_le_two_pow_two_mul _
+ by_contra! hall
+ have hlcm : Nat.lcmUpto n ∣ D ^ k := by
+ apply (Nat.factorization_prime_le_iff_dvd (Nat.lcmUpto_ne_zero n) (pow_ne_zero _ hD)).mp
+ intro p hp
+ rw [Nat.factorization_lcmUpto n hp, Nat.factorization_pow, Finsupp.smul_apply, smul_eq_mul]
+ by_cases hpn : p ≤ n
+ · have he : p.log n ≤ k := (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp <|
+ (Nat.pow_le_pow_left hp.two_le _).trans ((Nat.pow_log_le_self p hn).trans (by omega))
+ have hpos := hp.factorization_pos_of_dvd hD (hall p hp hpn)
+ exact he.trans (Nat.le_mul_of_pos_right _ hpos)
+ · simp [Nat.log_of_lt (by omega : n < p)]
+ have hbound : 2 ^ n ≤ 2 ^ (k + B * k) := calc
+ 2 ^ n ≤ (n + 1) * Nat.lcmUpto n := Chebyshev.two_pow_le_mul_lcmUpto n
+ _ ≤ 2 ^ k * (2 ^ B) ^ k := Nat.mul_le_mul hsize
+ ((Nat.le_of_dvd (Nat.pow_pos (Nat.pos_of_ne_zero hD)) hlcm).trans (Nat.pow_le_pow_left hB _))
+ _ = _ := by rw [pow_add, pow_mul (2 : ℕ) B k]
+ have := (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp hbound
+ dsimp [n, k] at this
+ nlinarith
+
+/-- The integer minor stays nonzero modulo a prime with the same bound. -/
+theorem exists_small_prime_not_dvd_int {D : ℤ} {B : ℕ} (hD : D ≠ 0) (hB : D.natAbs ≤ 2 ^ B) :
+ ∃ p : ℕ, p.Prime ∧ p ≤ 2 * (B + 2) ^ 2 ∧ ¬ (p : ℤ) ∣ D := by
+ obtain ⟨p, hp, hbound, hn⟩ := exists_small_prime_not_dvd (Int.natAbs_ne_zero.mpr hD) hB
+ exact ⟨p, hp, hbound, fun h ↦ hn (by simpa using (Int.natAbs_dvd_natAbs.mpr h))⟩
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpaceRunMonotone.lean b/lean/OAI/Computability/VPVNP/SpaceRunMonotone.lean
new file mode 100644
index 0000000000..68f71fbf84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpaceRunMonotone.lean
@@ -0,0 +1,23 @@
+import OAI.Computability.VPVNP.UniversalCountStackBounds
+
+/-! # Enlarging a bound on the height of each machine stack -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalCountStack
+
+/-- Enlarge a uniform height bound on every configuration of the same machine run. -/
+theorem SpaceRun.mono_cap {K Q : Type*} [DecidableEq K] {code : RAMTape.StackCode K Q}
+ {a b t q s q' s'} (h : SpaceRun code a t q s q' s') (hab : a ≤ b) :
+ SpaceRun code b t q s q' s' := by
+ induction h with
+ | nil q s hs => exact .nil q s fun k ↦ (hs k).trans hab
+ | cons hs step _ ih => exact .cons (fun k ↦ (hs k).trans hab) step ih
+
+end UniversalCountStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpanningStar.lean b/lean/OAI/Computability/VPVNP/SpanningStar.lean
new file mode 100644
index 0000000000..f54445bd37
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpanningStar.lean
@@ -0,0 +1,109 @@
+import OAI.Computability.VPVNP.WireSpectrum
+import Mathlib.Analysis.SpecialFunctions.Log.Base
+import Mathlib.Data.Finset.CastCard
+
+/-! # Diameter of a spectral configuration on all parties
+
+A star joining a central party to every party restricts to the all-parties
+diagonal. The loop at the central party has spectral wire distance zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v w
+
+namespace WireTensor
+
+open scoped NNReal
+
+variable {k : Type u} {J : Type v} [Fintype J]
+
+/-- At each party keep the basis vectors whose incident wire labels are all
+the output coordinate. Along a spanning star these restrictions impose the
+all-parties diagonal. -/
+theorem starNetwork_restricts_diagonal [CommSemiring k] {E : Type*} [Fintype E]
+ (center : J) (leaf : E → J) (hcover : Function.Surjective leaf)
+ (I : Type w) [Fintype I] :
+ Restricts (wireNetwork (k := k) (fun _ ↦ center) leaf (fun _ ↦ I)) (diagonal I) := by
+ classical
+ let W := wireNetwork (k := k) (fun _ : E ↦ center) leaf (fun _ ↦ I)
+ let select (j : J) (i : I) : W.Basis j := ⟨fun _ _ ↦ i, fun _ _ ↦ i⟩
+ refine ⟨_, (applyLocal_pullback select W.coeff).trans ?_⟩
+ funext x
+ simp only [W, select, wireNetwork, diagonal]
+ rw [Fintype.prod_boole]
+ congr 1
+ apply propext
+ constructor
+ · intro h
+ exact ⟨x center, fun j ↦ by obtain ⟨e, rfl⟩ := hcover j; exact (h e).symm⟩
+ · rintro ⟨i, hi⟩ e
+ exact (hi center).trans (hi (leaf e)).symm
+
+namespace SpectralPoint
+
+variable [Field k] (F : SpectralPoint k J)
+
+/-- The total wire distance along the spanning star is at least one. -/
+theorem one_le_sum_wireDistance (center : J) : 1 ≤ ∑ j, F.wireDistance center j := by
+ have : Nonempty J := ⟨center⟩
+ let leaf := (Fintype.equivFin J).symm
+ have h := F.monotone (starNetwork_restricts_diagonal (k := k) center leaf leaf.surjective (Fin 2))
+ rw [F.value_diagonal_fin, F.value_wireNetwork] at h
+ have hprod : (2 : ℝ) ≤ ∏ i, F.wireDimension center (leaf i) 2 := by
+ change (2 : ℝ) ≤ ∏ i, (F.value (wire center (leaf i) (Fin 2)) : ℝ)
+ exact_mod_cast h
+ have hpos (j : J) : 0 < F.wireDimension center j 2 :=
+ zero_lt_one.trans_le (F.one_le_wireDimension center j (by decide))
+ have hlog := Real.log_le_log (by norm_num : 0 < (2 : ℝ)) hprod
+ rw [Real.log_prod fun i _ ↦ (hpos (leaf i)).ne',
+ leaf.sum_comp (fun j ↦ Real.log (F.wireDimension center j 2))] at hlog
+ simp only [wireDistance, ← Finset.sum_div]
+ exact (one_le_div (Real.log_pos (by norm_num : (1 : ℝ) < 2))).mpr hlog
+
+include F in
+/-- A nonempty party set admitting a spectral point has at least two parties.
+For a singleton, the star sum would vanish. -/
+theorem nontrivial_parties [Nonempty J] : Nontrivial J := by
+ by_contra! h
+ have : Subsingleton J := h
+ let center : J := Classical.ofNonempty
+ have hzero (j : J) : F.wireDistance center j = 0 := by
+ rw [Subsingleton.elim center j, F.wireDistance_self]
+ simpa only [hzero, Finset.sum_const_zero, not_le.mpr zero_lt_one] using
+ F.one_le_sum_wireDistance center
+
+/-- The sharp normalization bound for the diameter of any configuration whose
+labels cover all parties. -/
+theorem inv_card_sub_one_le_wire_diameter {ι : Type*} [Fintype ι] [Nonempty ι]
+ (label : ι → J) (hlabel : Function.Surjective label) (hcard : 1 < Fintype.card J) :
+ 1 / ((Fintype.card J : ℝ) - 1) ≤ Finset.univ.sup' Finset.univ_nonempty
+ (fun i : ι × ι ↦ F.wireDistance (label i.1) (label i.2)) := by
+ classical
+ let c : ι := Classical.ofNonempty
+ let center := label c
+ let diam := Finset.univ.sup' Finset.univ_nonempty
+ (fun i : ι × ι ↦ F.wireDistance (label i.1) (label i.2))
+ have hdist (j : J) : F.wireDistance center j ≤ diam := by
+ obtain ⟨i, rfl⟩ := hlabel j
+ exact Finset.le_sup' (fun i : ι × ι ↦ F.wireDistance (label i.1) (label i.2))
+ (Finset.mem_univ (c, i))
+ have hpos : (0 : ℝ) < Fintype.card J - 1 := sub_pos.mpr (by exact_mod_cast hcard)
+ apply (div_le_iff₀ hpos).mpr
+ calc
+ 1 ≤ ∑ j, F.wireDistance center j := F.one_le_sum_wireDistance center
+ _ = ∑ j ∈ Finset.univ.erase center, F.wireDistance center j := by
+ rw [← Finset.sum_erase_add _ _ (Finset.mem_univ center), F.wireDistance_self, add_zero]
+ _ ≤ ∑ _j ∈ Finset.univ.erase center, diam := Finset.sum_le_sum fun j _ ↦ hdist j
+ _ = diam * ((Fintype.card J : ℝ) - 1) := by
+ rw [Finset.sum_const, nsmul_eq_mul, Finset.cast_card_erase_of_mem (Finset.mem_univ center),
+ Finset.card_univ, mul_comm]
+
+end SpectralPoint
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SparseGrassmann.lean b/lean/OAI/Computability/VPVNP/SparseGrassmann.lean
new file mode 100644
index 0000000000..a9eacdcfc8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SparseGrassmann.lean
@@ -0,0 +1,282 @@
+import OAI.Computability.VPVNP.GraphRounding
+import Mathlib.Data.Fintype.BigOperators
+
+/-!
+# Sparse walks from the Grassmann inequality
+
+In Section 5.2 of *VP and VNP differ over every field*, conditioning on the
+restriction of a random linear map to a common hyperplane leaves two independent
+vertices in corresponding fibers. Two bijections from `I × E` onto the vertex
+set describe the two fiber partitions, with `I` indexing the restrictions and
+`E` indexing the possible extensions. We compare the energy of this conditional
+coupling with a copy of the previous walk in every fiber and a symmetric
+permutation walk joining corresponding extensions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {Ω I E J X : Type*} [Fintype Ω] [Fintype I] [Fintype E] [Fintype J]
+
+/-- Place one copy of the preceding walk in each source fiber. -/
+noncomputable def fiberWalk (l : I × E ≃ Ω) (P : Matrix E E ℝ) : Matrix Ω Ω ℝ := by
+ classical
+ exact fun u v ↦ if (l.symm u).1 = (l.symm v).1 then P (l.symm u).2 (l.symm v).2 else 0
+
+/-- Match a vertex to its partner in the target fiber, symmetrizing the direction. -/
+noncomputable def matchingWalk (π : Ω ≃ Ω) : Matrix Ω Ω ℝ := by
+ classical
+ exact fun u v ↦ ((if π u = v then 1 else 0) + (if π v = u then 1 else 0)) / 2
+
+/-- The conditional adjacent-pair energy times the number of vertices. -/
+noncomputable def adjacentEnergy [PseudoMetricSpace X] (l r : I × E ≃ Ω) (x : Ω → X) : ℝ :=
+ (∑ i, ∑ a, ∑ b, dist (x (l (i,a))) (x (r (i,b))) ^ 2) / Fintype.card E
+
+private theorem sum_chart {M : Type*} [AddCommMonoid M] (l : I × E ≃ Ω) (f : Ω → M) :
+ ∑ u, f u = ∑ i, ∑ a, f (l (i,a)) := by
+ rw [← l.sum_comp f, Fintype.sum_prod_type]
+
+private theorem sum_divisor {T : Type*} [Fintype T] (f : T → ℝ) (d : ℝ) :
+ ∑ a, f a / d = (∑ a, f a) / d := by
+ simp only [div_eq_mul_inv, Finset.sum_mul]
+
+theorem fiberWalk_row (l : I × E ≃ Ω) (P : Matrix E E ℝ) (hr : ∀ a, ∑ b, P a b = 1)
+ (u : Ω) : ∑ v, fiberWalk l P u v = 1 := by
+ classical
+ rw [sum_chart l]
+ simp [fiberWalk, hr]
+
+theorem matchingWalk_row (π : Ω ≃ Ω) (u : Ω) : ∑ v, matchingWalk π u v = 1 := by
+ classical
+ simp only [matchingWalk, sum_divisor, Finset.sum_add_distrib,
+ show ∀ v, (π v = u) = (v = π.symm u) from fun _ ↦ propext π.eq_symm_apply.symm]
+ simp
+
+omit [Fintype Ω] [Fintype I] [Fintype E] in
+theorem fiberWalk_symm (l : I × E ≃ Ω) (P : Matrix E E ℝ) (hs : ∀ a b, P a b = P b a)
+ (u v : Ω) : fiberWalk l P u v = fiberWalk l P v u := by
+ classical
+ unfold fiberWalk
+ by_cases h : (l.symm u).1 = (l.symm v).1 <;> simp [h, eq_comm, hs]
+
+omit [Fintype Ω] in
+theorem matchingWalk_symm (π : Ω ≃ Ω) (u v : Ω) : matchingWalk π u v = matchingWalk π v u := by
+ unfold matchingWalk
+ rw [add_comm]
+
+omit [Fintype Ω] [Fintype I] [Fintype E] in
+theorem fiberWalk_nonneg (l : I × E ≃ Ω) (P : Matrix E E ℝ) (hn : ∀ a b, 0 ≤ P a b)
+ (u v : Ω) : 0 ≤ fiberWalk l P u v := by
+ classical
+ unfold fiberWalk
+ split_ifs <;> simp [hn]
+
+omit [Fintype Ω] in
+theorem matchingWalk_nonneg (π : Ω ≃ Ω) (u v : Ω) : 0 ≤ matchingWalk π u v := by
+ unfold matchingWalk
+ split_ifs <;> norm_num
+
+variable [PseudoMetricSpace X]
+
+theorem walkEnergy_fiberWalk (l : I × E ≃ Ω) (P : Matrix E E ℝ) (x : Ω → X) :
+ walkEnergy (fiberWalk l P) x = ∑ i, walkEnergy P (fun a ↦ x (l (i,a))) := by
+ classical
+ unfold walkEnergy
+ rw [sum_chart l]
+ apply Finset.sum_congr rfl
+ intro i _
+ apply Finset.sum_congr rfl
+ intro a _
+ rw [sum_chart l]
+ simp [fiberWalk, ite_mul]
+
+theorem walkEnergy_matchingWalk (π : Ω ≃ Ω) (x : Ω → X) :
+ walkEnergy (matchingWalk π) x = ∑ u, dist (x u) (x (π u)) ^ 2 := by
+ classical
+ unfold walkEnergy matchingWalk
+ have hi (u : Ω) : ∑ v, (((if π u = v then 1 else 0) + (if π v = u then 1 else 0)) / 2) *
+ dist (x v) (x u) ^ 2 =
+ (dist (x (π u)) (x u) ^ 2 + dist (x (π.symm u)) (x u) ^ 2) / 2 := by
+ simp only [div_mul_eq_mul_div, add_mul, ite_mul, one_mul, zero_mul,
+ show ∀ v, (π v = u) = (v = π.symm u) from fun _ ↦ propext π.eq_symm_apply.symm,
+ sum_divisor, Finset.sum_add_distrib, Finset.sum_ite_eq, Finset.sum_ite_eq',
+ Finset.mem_univ, ↓reduceIte]
+ simp only [hi, sum_divisor, Finset.sum_add_distrib]
+ have h := π.sum_comp (fun u ↦ dist (x (π.symm u)) (x u) ^ 2)
+ simp only [Equiv.symm_apply_apply] at h
+ rw [← h]
+ simp_rw [dist_comm (x (π _)) (x _)]
+ ring
+
+private theorem dist_sq_le_split (u v w : X) {ε : ℝ} (hε : 0 < ε) :
+ dist u w ^ 2 ≤ (1 + ε) * dist u v ^ 2 + (1 + 1 / ε) * dist v w ^ 2 := by
+ have h := pow_le_pow_left₀ dist_nonneg (dist_triangle u v w) 2
+ have hcross := sq_nonneg (ε * dist u v - dist v w)
+ apply (le_of_mul_le_mul_left (a := ε) _ hε)
+ field_simp
+ nlinarith [mul_le_mul_of_nonneg_left h hε.le]
+
+/-- Compare independent conditional endpoints through the source partner of the
+target endpoint. The factor `γ` is paid only on the part of the energy within
+a fiber. This gives the multiplicative coefficient used in the sparse recursion. -/
+theorem adjacentEnergy_le [Nonempty E] (l r : I × E ≃ Ω) (P : Matrix E E ℝ) {ε γ : ℝ}
+ (hε : 0 < ε) (hP : HasPoincareBound X P γ) (x : Ω → X) :
+ adjacentEnergy l r x ≤ ((1 + ε) * γ) * walkEnergy (fiberWalk l P) x +
+ (1 + 1 / ε) * walkEnergy (matchingWalk (l.symm.trans r)) x := by
+ let L (i : I) (a : E) := x (l (i,a))
+ let R (i : I) (a : E) := x (r (i,a))
+ have hc : 0 < (Fintype.card E : ℝ) := by exact_mod_cast Fintype.card_pos
+ have hlocal (i : I) :
+ (∑ a, ∑ b, dist (L i a) (R i b) ^ 2) / Fintype.card E ≤
+ (1 + ε) * (γ * walkEnergy P (L i)) + (1 + 1 / ε) * ∑ b, dist (L i b) (R i b) ^ 2 := by
+ have h := Finset.sum_le_sum (s := Finset.univ) fun a _ ↦
+ Finset.sum_le_sum (s := Finset.univ) fun b _ ↦ dist_sq_le_split (L i a) (L i b) (R i b) hε
+ simp only [Finset.sum_add_distrib, ← Finset.mul_sum, Finset.sum_const,
+ Finset.card_univ, nsmul_eq_mul] at h
+ have hp := (div_le_iff₀ hc).mp (hP (L i))
+ apply (div_le_iff₀ hc).mpr
+ nlinarith only [h, mul_le_mul_of_nonneg_left hp (by linarith only [hε] : 0 ≤ 1 + ε)]
+ have h := Finset.sum_le_sum (s := Finset.univ) fun i _ ↦ hlocal i
+ simp only [sum_divisor, Finset.sum_add_distrib, ← Finset.mul_sum, ← mul_assoc] at h
+ rw [walkEnergy_fiberWalk, walkEnergy_matchingWalk, sum_chart l (fun u ↦
+ dist (x u) (x ((l.symm.trans r) u)) ^ 2)]
+ simpa only [adjacentEnergy, L, R, Equiv.trans_apply, Equiv.symm_apply_apply] using h
+
+/-- Average the fiber walk and the matching walk over the ordered adjacencies,
+using their respective weights from the squared triangle inequality. -/
+noncomputable def sparseWalk (l r : J → I × E ≃ Ω) (P : Matrix E E ℝ) (a b : ℝ) :
+ Matrix Ω Ω ℝ := fun u v ↦
+ (∑ j, (a * fiberWalk (l j) P u v + b * matchingWalk ((l j).symm.trans (r j)) u v)) /
+ ((Fintype.card J : ℝ) * (a + b))
+
+theorem sparseWalk_row [Nonempty J] (l r : J → I × E ≃ Ω) (P : Matrix E E ℝ)
+ (hr : ∀ e, ∑ f, P e f = 1) {a b : ℝ} (hab : a + b ≠ 0) (u : Ω) :
+ ∑ v, sparseWalk l r P a b u v = 1 := by
+ unfold sparseWalk
+ rw [sum_divisor, Finset.sum_comm]
+ simp only [Finset.sum_add_distrib, ← Finset.mul_sum, fiberWalk_row _ _ hr, matchingWalk_row,
+ mul_one, Finset.sum_const, Finset.card_univ, nsmul_eq_mul]
+ have hc : 0 < (Fintype.card J : ℝ) := Nat.cast_pos.mpr Fintype.card_pos
+ rw [← mul_add, div_self (mul_ne_zero hc.ne' hab)]
+
+omit [Fintype Ω] [Fintype I] [Fintype E] in
+theorem sparseWalk_symm (l r : J → I × E ≃ Ω) (P : Matrix E E ℝ)
+ (hs : ∀ a b, P a b = P b a) (a b : ℝ) (u v : Ω) :
+ sparseWalk l r P a b u v = sparseWalk l r P a b v u := by
+ unfold sparseWalk
+ congr 1
+ exact Finset.sum_congr rfl fun j _ ↦ by
+ rw [fiberWalk_symm _ _ hs u v, matchingWalk_symm _ u v]
+
+omit [Fintype Ω] [Fintype I] [Fintype E] in
+theorem sparseWalk_nonneg (l r : J → I × E ≃ Ω) (P : Matrix E E ℝ)
+ (hn : ∀ e f, 0 ≤ P e f) {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (u v : Ω) :
+ 0 ≤ sparseWalk l r P a b u v :=
+ div_nonneg (Finset.sum_nonneg fun _ _ ↦
+ add_nonneg (mul_nonneg ha (fiberWalk_nonneg _ _ hn u v))
+ (mul_nonneg hb (matchingWalk_nonneg _ u v))) (mul_nonneg (Nat.cast_nonneg _) (add_nonneg ha hb))
+
+omit [Fintype I] [Fintype E] in
+theorem walkEnergy_sparseWalk (l r : J → I × E ≃ Ω) (P : Matrix E E ℝ) (a b : ℝ) (x : Ω → X) :
+ walkEnergy (sparseWalk l r P a b) x =
+ (∑ j, (a * walkEnergy (fiberWalk (l j) P) x +
+ b * walkEnergy (matchingWalk ((l j).symm.trans (r j))) x)) /
+ ((Fintype.card J : ℝ) * (a + b)) := by
+ unfold walkEnergy sparseWalk
+ simp only [div_mul_eq_mul_div, sum_divisor, Finset.sum_mul, add_mul, mul_assoc]
+ congr 1
+ calc
+ _ = ∑ u, ∑ j, ∑ v, (a * (fiberWalk (l j) P u v * dist (x v) (x u) ^ 2) +
+ b * (matchingWalk ((l j).symm.trans (r j)) u v * dist (x v) (x u) ^ 2)) :=
+ Finset.sum_congr rfl fun _ _ ↦ Finset.sum_comm
+ _ = _ := by
+ rw [Finset.sum_comm]
+ simp only [Finset.sum_add_distrib, ← Finset.mul_sum]
+
+/-- The sparse recursion of Section 5.2. The sampling inequality is stated in
+the same normalization as `HasPoincareBound`. Its coefficient `c` is `m - η`
+when applied to the adjacent pairs of the binary Grassmannian. -/
+theorem sparseWalk_hasPoincareBound [Nonempty E] [Nonempty J] (l r : J → I × E ≃ Ω)
+ (P : Matrix E E ℝ) {ε γ c : ℝ} (hε : 0 < ε) (hγ : 0 ≤ γ) (hc : 0 ≤ c)
+ (hP : HasPoincareBound X P γ)
+ (hsamp : ∀ x : Ω → X, (∑ u, ∑ v, dist (x u) (x v) ^ 2) / Fintype.card Ω ≤
+ c * ((∑ j, adjacentEnergy (l j) (r j) x) / Fintype.card J)) :
+ HasPoincareBound X (sparseWalk l r P ((1 + ε) * γ) (1 + 1 / ε))
+ (c * ((1 + ε) * γ + (1 + 1 / ε))) := by
+ intro x
+ let a := (1 + ε) * γ
+ let b := 1 + 1 / ε
+ have hab : 0 < a + b := by dsimp [a,b]; positivity
+ have hj : 0 < (Fintype.card J : ℝ) := by exact_mod_cast Fintype.card_pos
+ have h := Finset.sum_le_sum (s := Finset.univ) fun j _ ↦ adjacentEnergy_le (l j) (r j) P hε hP x
+ refine (hsamp x).trans ?_
+ rw [walkEnergy_sparseWalk]
+ change c * (_ / (Fintype.card J : ℝ)) ≤ (c * (a + b)) * (_ / ((Fintype.card J : ℝ) * (a + b)))
+ rw [show ∀ s : ℝ, (c * (a + b)) * (s / ((Fintype.card J : ℝ) * (a + b))) =
+ c * (s / (Fintype.card J : ℝ)) from fun s ↦ by field_simp]
+ exact mul_le_mul_of_nonneg_left (div_le_div_of_nonneg_right h hj.le) hc
+
+@[simp] theorem mem_rowSupport {T : Type*} [Fintype T] (P : Matrix T T ℝ) (u v : T) :
+ v ∈ rowSupport P u ↔ P u v ≠ 0 := by classical simp [rowSupport]
+
+omit [Fintype I] in
+theorem fiberWalk_support (l : I × E ≃ Ω) (P : Matrix E E ℝ) (u : Ω) :
+ (rowSupport (fiberWalk l P) u).card ≤ (rowSupport P (l.symm u).2).card := by
+ classical
+ let S := (rowSupport P (l.symm u).2).image fun e ↦ l ((l.symm u).1, e)
+ refine (Finset.card_le_card (t := S) ?_).trans Finset.card_image_le
+ intro v hv
+ have h := (mem_rowSupport _ _ _).mp hv
+ unfold fiberWalk at h
+ split_ifs at h with h'
+ · refine Finset.mem_image.mpr ⟨(l.symm v).2, (mem_rowSupport _ _ _).mpr h, ?_⟩
+ rw [h']
+ simp
+ · exact False.elim (h rfl)
+
+theorem matchingWalk_support (π : Ω ≃ Ω) (u : Ω) : (rowSupport (matchingWalk π) u).card ≤ 2 := by
+ classical
+ have hs : rowSupport (matchingWalk π) u ⊆ {π u, π.symm u} := by
+ intro v hv
+ have h := (mem_rowSupport _ _ _).mp hv
+ by_contra hc
+ have hv₁ : π u ≠ v := fun he ↦ hc (by simp [← he])
+ have hv₂ : π v ≠ u := fun he ↦ hc (by simp [π.eq_symm_apply.mpr he])
+ simp [matchingWalk, hv₁, hv₂] at h
+ exact (Finset.card_le_card hs).trans (Finset.card_le_two)
+
+omit [Fintype I] in
+/-- A row of the new walk uses at most one old row and two matching edges per
+ordered Grassmann adjacency. This count is independent of the fiber count. -/
+theorem sparseWalk_support (l r : J → I × E ≃ Ω) (P : Matrix E E ℝ) (a b : ℝ)
+ {k : ℕ} (hk : ∀ e, (rowSupport P e).card ≤ k) (u : Ω) :
+ (rowSupport (sparseWalk l r P a b) u).card ≤ Fintype.card J * (k + 2) := by
+ classical
+ let S (j : J) := rowSupport (fiberWalk (l j) P) u ∪ rowSupport (matchingWalk ((l j).symm.trans (r j))) u
+ have hS : rowSupport (sparseWalk l r P a b) u ⊆ Finset.univ.biUnion S := by
+ intro v hv
+ by_contra h
+ have hzero (j : J) :
+ fiberWalk (l j) P u v = 0 ∧ matchingWalk ((l j).symm.trans (r j)) u v = 0 := by
+ by_contra! hn
+ apply h
+ simpa [S] using (show ∃ j, v ∈ S j from ⟨j, by
+ simp only [S, Finset.mem_union, mem_rowSupport]; tauto⟩)
+ apply (mem_rowSupport _ _ _).mp hv
+ simp [sparseWalk, fun j ↦ (hzero j).1, fun j ↦ (hzero j).2]
+ calc
+ _ ≤ _ := Finset.card_le_card hS
+ _ ≤ ∑ j, (S j).card := Finset.card_biUnion_le
+ _ ≤ ∑ _j : J, (k + 2) := Finset.sum_le_sum fun j _ ↦
+ (Finset.card_union_le _ _).trans (Nat.add_le_add ((fiberWalk_support _ _ _).trans (hk _))
+ (matchingWalk_support _ _))
+ _ = _ := by simp
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SparseGrassmannFamily.lean b/lean/OAI/Computability/VPVNP/SparseGrassmannFamily.lean
new file mode 100644
index 0000000000..8b8d9ac435
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SparseGrassmannFamily.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.GrassmannSampling
+import OAI.Computability.VPVNP.SparseParameters
+import OAI.Computability.VPVNP.SparseWalkIteration
+
+/-!
+# The rounded sparse Grassmann family
+
+Section 5.2 of *VP and VNP differ over every field* constructs a common graph
+for an entire class of targets from their strict Grassmann inequality. Its
+order is `D ^ (m ^ j)`, its power-of-two degree is at most `4 Cj D`, and its
+Poincaré coefficient grows as `O(α ^ j)` for `α < m`. The degree constant may
+depend on `j`, while the coefficient prefactor is independent of both `D` and `j`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open SpectralGeometry
+
+variable {n : ℕ}
+
+/-- The same linear map is sampled for every plane. On complementary pairs its
+two readings are independent, and on adjacent pairs their extensions are
+conditionally independent given the restriction to the intersection. -/
+theorem exists_readPlane_laws (E : Type*) [AddCommGroup E] [Module (ZMod 2) E] [Fintype E] :
+ ∃ l r : Pair (n+1) 1 → ((Fin n → E) × E) ≃ (Fin (n+1) → E),
+ PairSamplingLaws (fun f U ↦ readPlane E U f) l r := by
+ choose l r hr using exists_adjacent_charts (n := n) E
+ exact ⟨l, r, ⟨fun p g ↦ average_read_complement E p.property g, hr⟩⟩
+
+variable {T : Type*} (X : T → Type*) [∀ t, PseudoMetricSpace (X t)]
+
+private theorem sparseStep [Nonempty (Pair (n+1) (n+1))] [Nonempty (Pair (n+1) 1)]
+ {ε c : ℝ} (hε : 0 < ε) (hc : 0 ≤ c)
+ (hgrass : ∀ t (f : Plane (n+1) → X t), mean (fun a b ↦ dist (f a) (f b) ^ 2) (n+1) ≤
+ c * mean (fun a b ↦ dist (f a) (f b) ^ 2) 1)
+ (w k : ℕ) (P : Matrix (WordSpace w) (WordSpace w) ℝ) (γ : ℝ) (hγ : 0 ≤ γ)
+ (hP : SparseWalkBound X P k γ) :
+ ∃ Q : Matrix (Fin (n+1) → WordSpace w) (Fin (n+1) → WordSpace w) ℝ,
+ SparseWalkBound X Q (Fintype.card (Pair (n+1) 1) * (k + 2))
+ ((c * (1 + ε)) * γ + c * (1 + 1 / ε)) := by
+ obtain ⟨l,r,h⟩ := exists_readPlane_laws (n := n) (WordSpace w)
+ let a := (1 + ε) * γ
+ let b := 1 + 1 / ε
+ have ha : 0 ≤ a := by dsimp [a]; positivity
+ have hb : 0 < b := by dsimp [b]; positivity
+ refine ⟨sparseWalk l r P a b, ⟨sparseWalk_nonneg _ _ _ hP.nonneg ha hb.le,
+ sparseWalk_row _ _ _ hP.row (add_pos_of_nonneg_of_pos ha hb).ne',
+ sparseWalk_symm _ _ _ hP.symm _ _, sparseWalk_support _ _ _ _ _ hP.support, ?_⟩⟩
+ intro t
+ have ht := h.sparseBound P hε hγ hc (hP.bound t) (hgrass t)
+ simpa only [mul_add, ← mul_assoc, a, b] using ht
+
+/-- Sparse regular multigraphs of order `D^(m^j)` for every starting order
+`D=2^d≥2`. The choices of the matrices and of their power-of-two degrees are
+simultaneous for all the targets satisfying the strict Grassmann inequality. -/
+theorem exists_sparse_rounded_family {m : ℕ} (hm : 1 < m) {c₀ : ℝ} (hc₀ : c₀ < m)
+ (hgrass : ∀ t (f : Plane m → X t), mean (fun a b ↦ dist (f a) (f b) ^ 2) m ≤
+ c₀ * mean (fun a b ↦ dist (f a) (f b) ^ 2) 1) :
+ ∃ α C' : ℝ, 1 < α ∧ α < m ∧ 0 ≤ C' ∧ ∀ j : ℕ, ∃ Cj : ℕ, 0 < Cj ∧ ∀ d : ℕ, 0 < d →
+ ∃ e : ℕ, 2 ^ e ≤ 4 * Cj * 2 ^ d ∧
+ ∃ M : Matrix (Fin ((2 ^ d) ^ (m ^ j))) (Fin ((2 ^ d) ^ (m ^ j))) ℕ,
+ (∀ i j, M i j = M j i) ∧ (∀ i, ∑ j, M i j = 2 ^ e) ∧
+ ∀ t, HasPoincareBound (X t) (normalizeArcs M (2 ^ e)) (2 * C' * α ^ j) := by
+ obtain ⟨n,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (show m ≠ 0 by omega)
+ let := nonempty_pair (Nat.le_refl (n+1))
+ let := nonempty_pair (show 1 ≤ n+1 by omega)
+ obtain ⟨c,ε,hc₀c,hc,hε,ha,ham⟩ := exists_sparse_parameters (by exact_mod_cast hm) hc₀
+ let α := c * (1 + ε)
+ let κ := c * (1 + 1 / ε)
+ let C' := 1 + κ / (α - 1)
+ have hκ : 0 ≤ κ := by dsimp [κ]; positivity
+ have hα : 1 < α := ha
+ have hC : 0 ≤ C' := by dsimp only [C']; positivity
+ have hbig (t : T) (f : Plane (n+1) → X t) : mean (fun a b ↦ dist (f a) (f b) ^ 2) (n+1) ≤
+ c * mean (fun a b ↦ dist (f a) (f b) ^ 2) 1 := by
+ refine (hgrass t f).trans (mul_le_mul_of_nonneg_right hc₀c ?_)
+ exact div_nonneg (Finset.sum_nonneg fun _ _ ↦ sq_nonneg _) (Nat.cast_nonneg _)
+ let L := Fintype.card (Pair (n+1) 1)
+ have hL : 0 < L := Fintype.card_pos
+ refine ⟨α, C', hα, ham, hC, fun j ↦ ⟨(2 * L) ^ j, by positivity, fun d hd ↦ ?_⟩⟩
+ obtain ⟨P,hP⟩ := iterate_sparse_walk hd hL ha hκ (sparseStep X hε hc hbig) j
+ obtain ⟨e,_,he,M,hM,hrow,hhalf⟩ := exists_regular_rounding P (by positivity) hP.nonneg
+ hP.row hP.symm hP.support
+ refine ⟨e, by simpa only [Nat.mul_assoc] using he, M, hM, hrow, fun t ↦ ?_⟩
+ rw [mul_assoc]
+ exact hasPoincareBound_of_half_le hhalf (mul_nonneg hC (pow_nonneg (zero_le_one.trans hα.le) _)) (hP.bound t)
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SparseParameters.lean b/lean/OAI/Computability/VPVNP/SparseParameters.lean
new file mode 100644
index 0000000000..df061370db
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SparseParameters.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.GrassmannSeeds
+import Mathlib.Tactic.Linarith
+
+/-!
+# Parameters of the sparse Grassmann recursion
+
+The strict Grassmann coefficient leaves room to enlarge it and pay the
+triangle-inequality factor at each recursive step, while still growing
+strictly more slowly than the plane dimension.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+/-- The index type of the uniform type-`r` pair law is inhabited. -/
+theorem nonempty_pair {m r : ℕ} (hr : r ≤ m) : Nonempty (Pair m r) := by
+ obtain ⟨a, b, hab⟩ := exists_pair hr
+ exact ⟨⟨(a, b), hab⟩⟩
+
+/-- Choice of the enlarged Grassmann coefficient and the triangle parameter
+in Section 5.2. Their product lies strictly between one and the dimension. -/
+theorem exists_sparse_parameters {m c₀ : ℝ} (hm : 1 < m) (hc₀ : c₀ < m) :
+ ∃ c ε : ℝ, c₀ ≤ c ∧ 0 ≤ c ∧ 0 < ε ∧ 1 < c * (1 + ε) ∧ c * (1 + ε) < m := by
+ let c := max 1 c₀
+ have hc : 1 ≤ c := le_max_left _ _
+ have hc' : c < m := max_lt hm hc₀
+ have hp : 0 < c := lt_of_lt_of_le zero_lt_one hc
+ let ε := (m - c) / (2 * c)
+ have hε : 0 < ε := div_pos (sub_pos.mpr hc') (mul_pos (by norm_num) hp)
+ have hprod : c * (1 + ε) = (m + c) / 2 := by
+ dsimp [ε]
+ field_simp
+ ring
+ refine ⟨c, ε, le_max_right _ _, hp.le, hε, ?_, ?_⟩ <;> rw [hprod] <;> linarith
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SparseWalkIteration.lean b/lean/OAI/Computability/VPVNP/SparseWalkIteration.lean
new file mode 100644
index 0000000000..f3dcbfb3ba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SparseWalkIteration.lean
@@ -0,0 +1,143 @@
+import OAI.Computability.VPVNP.GrassmannWalkTransfer
+
+/-!
+# Iterating and rounding the sparse walk
+
+The size `D` of the starting walk is a power of two. At each step the vertex
+set consists of `m`-tuples of the preceding vertices. The row support grows by
+at most a factor twice the number of Grassmann adjacencies, while the Poincaré
+coefficient satisfies an affine recurrence with multiplier strictly below `m`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+universe u v
+
+variable {T : Type u} (X : T → Type v) [∀ t, PseudoMetricSpace (X t)]
+variable {E Ω : Type*} [Fintype E] [Fintype Ω]
+
+/-- Uniform bounds for one symmetric stochastic matrix on every target in the class. -/
+structure SparseWalkBound (P : Matrix E E ℝ) (k : ℕ) (γ : ℝ) : Prop where
+ nonneg : ∀ i j, 0 ≤ P i j
+ row : ∀ i, ∑ j, P i j = 1
+ symm : ∀ i j, P i j = P j i
+ support : ∀ i, (rowSupport P i).card ≤ k
+ bound : ∀ t, HasPoincareBound (X t) P γ
+
+variable {X}
+
+theorem SparseWalkBound.reindex {P : Matrix E E ℝ} {k : ℕ} {γ : ℝ}
+ (h : SparseWalkBound X P k γ) (e : E ≃ Ω) :
+ SparseWalkBound X (fun i j ↦ P (e.symm i) (e.symm j)) k γ := by
+ classical
+ let Q : Matrix Ω Ω ℝ := fun i j ↦ P (e.symm i) (e.symm j)
+ change SparseWalkBound X Q k γ
+ refine ⟨fun i j ↦ h.nonneg _ _, fun i ↦ ?_, fun i j ↦ h.symm _ _, fun i ↦ ?_, fun t x ↦ ?_⟩
+ · exact (e.symm.sum_comp _).trans (h.row _)
+ · have hs : rowSupport Q i ⊆ (rowSupport P (e.symm i)).image e := by
+ intro j hj
+ exact Finset.mem_image.mpr ⟨e.symm j, (mem_rowSupport _ _ _).mpr ((mem_rowSupport Q i j).mp hj),
+ e.apply_symm_apply j⟩
+ exact (Finset.card_le_card hs).trans (Finset.card_image_le.trans (h.support _))
+ · have changeSum (f : Ω → Ω → ℝ) : (∑ i, ∑ j, f i j) = ∑ i, ∑ j, f (e i) (e j) := by
+ rw [← e.sum_comp (fun i ↦ ∑ j, f i j)]
+ exact Finset.sum_congr rfl fun i _ ↦ (e.sum_comp _).symm
+ rw [changeSum, ← Fintype.card_congr e, walkEnergy, changeSum]
+ simpa only [Q, Equiv.symm_apply_apply, walkEnergy, Function.comp_apply] using h.bound t (x ∘ e)
+
+/-- The starting graph is the uniform matrix on the full set. -/
+theorem uniform_sparseWalkBound (X : T → Type v) [∀ t, PseudoMetricSpace (X t)]
+ (E : Type*) [Fintype E] [Nonempty E] :
+ SparseWalkBound X (fun (_ _ : E) ↦ 1 / (Fintype.card E : ℝ)) (Fintype.card E) 1 := by
+ have he : 0 < (Fintype.card E : ℝ) := Nat.cast_pos.mpr Fintype.card_pos
+ refine ⟨fun _ _ ↦ by positivity, fun _ ↦ ?_, fun _ _ ↦ rfl,
+ fun _ ↦ Finset.card_le_univ _, fun t x ↦ ?_⟩
+ · simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul]
+ field_simp
+ · unfold walkEnergy
+ rw [one_mul]
+ simp only [← Finset.mul_sum, div_eq_inv_mul, mul_one]
+ rw [Finset.sum_comm (f := fun i j ↦ dist (x j) (x i) ^ 2)]
+
+/-- Binary words of length `k`, used as the vertex vector space at each stage. -/
+abbrev WordSpace (k : ℕ) := Fin k → ZMod 2
+
+theorem card_wordSpace (k : ℕ) : Fintype.card (WordSpace k) = 2 ^ k := by
+ simp [WordSpace, ZMod.card]
+
+/-- The affine Poincaré recurrence in Section 5.2. -/
+def sparseCoefficient (α κ : ℝ) : ℕ → ℝ
+ | 0 => 1
+ | j + 1 => α * sparseCoefficient α κ j + κ
+
+theorem sparseCoefficient_nonneg {α κ : ℝ} (ha : 0 ≤ α) (hk : 0 ≤ κ) (j : ℕ) :
+ 0 ≤ sparseCoefficient α κ j := by
+ induction j with
+ | zero => exact zero_le_one
+ | succ j ih => exact add_nonneg (mul_nonneg ha ih) hk
+
+/-- Solving the recurrence gives a prefactor independent of the starting size
+and the iteration index. -/
+theorem sparseCoefficient_le {α κ : ℝ} (ha : 1 < α) (hk : 0 ≤ κ) (j : ℕ) :
+ sparseCoefficient α κ j ≤ (1 + κ / (α - 1)) * α ^ j := by
+ have hdiv := div_nonneg hk (sub_nonneg.mpr ha.le)
+ have hshift : α * (κ / (α - 1)) = κ / (α - 1) + κ := by field_simp [(sub_pos.mpr ha).ne']; ring
+ have heq : sparseCoefficient α κ j + κ / (α - 1) = (1 + κ / (α - 1)) * α ^ j := by
+ induction j with
+ | zero => simp [sparseCoefficient]
+ | succ j ih =>
+ rw [sparseCoefficient, pow_succ', ← mul_assoc, mul_comm (1 + _), mul_assoc, ← ih, mul_add, hshift]
+ ring
+ linarith
+
+/-- Iterate the one-step construction on binary word spaces. The output is
+reindexed by `Fin` so its size is available directly to the port construction. -/
+theorem iterate_sparse_walk {m L d : ℕ} (hd : 0 < d) (hL : 0 < L) {α κ : ℝ}
+ (ha : 1 < α) (hk : 0 ≤ κ)
+ (step : ∀ (w k : ℕ) (P : Matrix (WordSpace w) (WordSpace w) ℝ) (γ : ℝ), 0 ≤ γ →
+ SparseWalkBound X P k γ → ∃ Q : Matrix (Fin m → WordSpace w) (Fin m → WordSpace w) ℝ,
+ SparseWalkBound X Q (L * (k + 2)) (α * γ + κ)) (j : ℕ) :
+ ∃ P : Matrix (Fin ((2 ^ d) ^ (m ^ j))) (Fin ((2 ^ d) ^ (m ^ j))) ℝ,
+ SparseWalkBound X P ((2 * L) ^ j * 2 ^ d) ((1 + κ / (α - 1)) * α ^ j) := by
+ have hd₂ : 2 ≤ 2 ^ d := Nat.le_pow (by omega)
+ have grow (i : ℕ) : 2 ≤ (2 * L) ^ i * 2 ^ d := hd₂.trans
+ (Nat.le_mul_of_pos_left _ (pow_pos (by omega) i))
+ have build (i : ℕ) : ∃ P : Matrix (WordSpace (d * m ^ i)) (WordSpace (d * m ^ i)) ℝ,
+ SparseWalkBound X P ((2 * L) ^ i * 2 ^ d) (sparseCoefficient α κ i) := by
+ induction i with
+ | zero =>
+ rw [pow_zero, Nat.mul_one, pow_zero, Nat.one_mul]
+ simpa only [sparseCoefficient, card_wordSpace] using
+ (show ∃ P : Matrix (WordSpace d) (WordSpace d) ℝ, SparseWalkBound X P (Fintype.card (WordSpace d)) 1
+ from ⟨_, uniform_sparseWalkBound X (WordSpace d)⟩)
+ | succ i ih =>
+ obtain ⟨P, hP⟩ := ih
+ obtain ⟨Q, hQ⟩ := step _ _ P _ (sparseCoefficient_nonneg (zero_le_one.trans ha.le) hk i) hP
+ have hcard : Fintype.card (Fin m → WordSpace (d * m ^ i)) =
+ Fintype.card (WordSpace (d * m ^ (i + 1))) := by
+ simp only [Fintype.card_fun, Fintype.card_fin, ← pow_mul, pow_succ, Nat.mul_assoc]
+ have hR := hQ.reindex (Fintype.equivOfCardEq hcard)
+ refine ⟨_, {hR with support := fun u ↦ (hR.support u).trans ?_}⟩
+ rw [pow_succ' (2 * L)]
+ have hsum : (2 * L) ^ i * 2 ^ d + 2 ≤ 2 * ((2 * L) ^ i * 2 ^ d) := by
+ linarith only [grow i]
+ calc
+ _ ≤ L * (2 * ((2 * L) ^ i * 2 ^ d)) := Nat.mul_le_mul_left _ hsum
+ _ = _ := by ring
+ obtain ⟨P, hP⟩ := build j
+ have hcard : Fintype.card (WordSpace (d * m ^ j)) = (2 ^ d) ^ (m ^ j) := by
+ rw [card_wordSpace, pow_mul]
+ have hR := hP.reindex (Fintype.equivFinOfCardEq hcard)
+ refine ⟨_, {hR with bound := fun t x ↦ (hR.bound t x).trans ?_}⟩
+ apply mul_le_mul_of_nonneg_right (sparseCoefficient_le ha hk j)
+ exact Finset.sum_nonneg fun u _ ↦ Finset.sum_nonneg fun v _ ↦ mul_nonneg (hR.nonneg u v) (sq_nonneg _)
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralCatalyst.lean b/lean/OAI/Computability/VPVNP/SpectralCatalyst.lean
new file mode 100644
index 0000000000..9d3795b8af
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralCatalyst.lean
@@ -0,0 +1,94 @@
+import OAI.Computability.VPVNP.SpectralLocalizationCone
+
+/-!
+# Removing additive slack in strict spectral comparison
+
+Appendix A.1 obtains a comparison with a common summand after clearing
+denominators. Trading multiple copies absorbs that summand and leaves a
+single multiplicative catalyst. Its size bounds the number of copies needed
+for all tensor powers simultaneously.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+variable {S : Type*} [CommSemiring S] [Preorder S] (H : OrderBounds S)
+include H
+
+private theorem copy_trade {u v w : S} (h : u + w ≤ v + w) (q : ℕ) :
+ (q : S) * u + w ≤ (q : S) * v + w := by
+ induction q with
+ | zero => simp
+ | succ q ih =>
+ calc
+ _ = (q : S) * u + (u + w) := by push_cast; ring
+ _ ≤ (q : S) * u + (v + w) := H.add_mono le_rfl h
+ _ = v + ((q : S) * u + w) := by ring
+ _ ≤ v + ((q : S) * v + w) := H.add_mono le_rfl ih
+ _ = _ := by push_cast; ring
+
+private theorem one_le_product {u v : S} (hu : 1 ≤ u) (hv : 1 ≤ v) : 1 ≤ u * v :=
+ hu.trans (by simpa using H.mul_mono u hv)
+
+private theorem one_le_succ (n : ℕ) : (1 : S) ≤ (n : S) + 1 := by
+ simpa using H.add_mono (H.zero_le (n : S)) (le_rfl (a := (1 : S)))
+
+/-- A common summand in the comparison between `(b+1)cX` and `bcY` can
+be traded away by taking `q` copies, with `q c Y` large enough to cover it. -/
+theorem remove_additive_slack {x y c w : S} (hc : c ≠ 0) (hy : y ≠ 0) (b : ℕ)
+ (h : c * (((b : S) + 1) * x) + w ≤ c * ((b : S) * y) + w) :
+ ∃ D : S, 1 ≤ D ∧ D * x ≤ D * y := by
+ obtain ⟨r, hr⟩ := H.bounded w
+ let q := r + 1
+ have hq : (1 : S) ≤ q := by simpa [q] using one_le_succ H r
+ have hcy := one_le_product H (H.one_le hc) (H.one_le hy)
+ have hw : w ≤ (q : S) * (c * y) := calc
+ w ≤ (r : S) := hr
+ _ ≤ (q : S) := by simpa [q] using H.add_mono (le_rfl (a := (r : S))) (H.zero_le 1)
+ _ ≤ _ := by simpa using H.mul_mono (q : S) hcy
+ let D := (q : S) * ((b : S) + 1) * c
+ refine ⟨D, one_le_product H (one_le_product H hq (one_le_succ H b)) (H.one_le hc), ?_⟩
+ calc
+ D * x = (q : S) * (c * (((b : S) + 1) * x)) := by dsimp [D]; ring
+ _ ≤ (q : S) * (c * (((b : S) + 1) * x)) + w := by
+ simpa using H.add_mono (le_rfl (a := (q : S) * (c * (((b : S) + 1) * x)))) (H.zero_le w)
+ _ ≤ (q : S) * (c * ((b : S) * y)) + w := copy_trade H h q
+ _ ≤ (q : S) * (c * ((b : S) * y)) + (q : S) * (c * y) := H.add_mono le_rfl hw
+ _ = D * y := by dsimp [D]; ring
+
+/-- The same catalyst can be reused once per factor of a tensor power. -/
+theorem catalyst_powers {x y D : S} (h : D * x ≤ D * y) (m : ℕ) :
+ D * x ^ m ≤ D * y ^ m := by
+ induction m with
+ | zero => simp
+ | succ m ih =>
+ calc
+ D * x ^ (m + 1) = x ^ m * (D * x) := by rw [pow_succ]; ring
+ _ ≤ x ^ m * (D * y) := H.mul_mono _ h
+ _ = y * (D * x ^ m) := by ring
+ _ ≤ y * (D * y ^ m) := H.mul_mono _ ih
+ _ = D * y ^ (m + 1) := by rw [pow_succ]; ring
+
+/-- The catalyst is bounded by a natural number independent of the power. -/
+theorem catalyst_uniform_bound {x y D : S} (hD : 1 ≤ D) (h : D * x ≤ D * y) :
+ ∃ K : ℕ, 1 ≤ K ∧ ∀ m : ℕ, x ^ m ≤ (K : S) * y ^ m := by
+ obtain ⟨r, hr⟩ := H.bounded D
+ refine ⟨r + 1, by omega, ?_⟩
+ intro m
+ calc
+ x ^ m ≤ D * x ^ m := by simpa [mul_comm] using H.mul_mono (x ^ m) hD
+ _ ≤ D * y ^ m := catalyst_powers H h m
+ _ ≤ (r : S) * y ^ m := by simpa [mul_comm] using H.mul_mono (y ^ m) hr
+ _ ≤ _ := by
+ have hsucc : (r : S) ≤ (r : S) + 1 := by
+ simpa using H.add_mono (le_rfl (a := (r : S))) (H.zero_le 1)
+ simpa [mul_comm] using H.mul_mono (y ^ m) hsucc
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralCompactGap.lean b/lean/OAI/Computability/VPVNP/SpectralCompactGap.lean
new file mode 100644
index 0000000000..86b124ac93
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralCompactGap.lean
@@ -0,0 +1,132 @@
+import OAI.Computability.VPVNP.SpectralLocalizationCone
+import Mathlib.Topology.Instances.Real.Lemmas
+import Mathlib.Topology.Order.Compact
+
+/-!
+# Compactness margins for spectral comparison and exact extension
+
+Appendix A.1 turns a pointwise strict comparison into a single integer
+margin. In the proof of Theorem 2.4, failure to match every prescribed
+generator yields a finite set of generators and a single multiplicative
+margin, in one of the two ratio directions.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+open Set
+
+/-- Monotone semiring homomorphisms, viewed in the ambient space of
+real-valued functions on the restriction semiring. -/
+def spectrumValues (S : Type*) [CommSemiring S] [Preorder S] : Set (S → ℝ) :=
+ {g | ∃ F : S →+* ℝ, Monotone F ∧ ⇑F = g}
+
+theorem spectrumValues_isClosed (S : Type*) [CommSemiring S] [Preorder S] :
+ IsClosed (spectrumValues S) := by
+ have heq : spectrumValues S = {g : S → ℝ | g 0 = 0 ∧ g 1 = 1 ∧
+ (∀ x y, g (x+y) = g x + g y) ∧ (∀ x y, g (x*y) = g x * g y) ∧
+ (∀ x y, x ≤ y → g x ≤ g y)} := by
+ ext g
+ constructor
+ · rintro ⟨F, hF, rfl⟩
+ exact ⟨F.map_zero, F.map_one, F.map_add, F.map_mul, fun _ _ h => hF h⟩
+ · rintro ⟨h₀, h₁, hAdd, hMul, hOrder⟩
+ let F : S →+* ℝ :=
+ { toFun := g
+ map_zero' := h₀
+ map_one' := h₁
+ map_add' := hAdd
+ map_mul' := hMul }
+ exact ⟨F, fun _ _ h => hOrder _ _ h, rfl⟩
+ rw [heq]
+ simp only [ofPred_and, ofPred_forall]
+ exact (isClosed_eq (continuous_apply 0) continuous_const).inter <|
+ (isClosed_eq (continuous_apply 1) continuous_const).inter <|
+ (isClosed_iInter fun x => isClosed_iInter fun y => isClosed_eq
+ (continuous_apply (x+y)) ((continuous_apply x).add (continuous_apply y))).inter <|
+ (isClosed_iInter fun x => isClosed_iInter fun y => isClosed_eq
+ (continuous_apply (x*y)) ((continuous_apply x).mul (continuous_apply y))).inter <|
+ isClosed_iInter fun x => isClosed_iInter fun y => isClosed_iInter fun (_ : x ≤ y) =>
+ isClosed_le (continuous_apply x) (continuous_apply y)
+
+/-- Tychonoff compactness for the spectral points of Section 2. Each tensor
+coordinate lies between zero and an integer rank bound. -/
+theorem spectrumValues_isCompact {S : Type*} [CommSemiring S] [Preorder S]
+ (H : OrderBounds S) : IsCompact (spectrumValues S) := by
+ choose bound hb using H.bounded
+ refine (isCompact_univ_pi fun x : S => isCompact_Icc (a := (0 : ℝ)) (b := bound x)).of_isClosed_subset
+ (spectrumValues_isClosed S) ?_
+ rintro _ ⟨F, hF, rfl⟩ x _
+ exact ⟨by simpa using hF (H.zero_le x), by simpa using hF (hb x)⟩
+
+/-- A uniform integer margin for strict comparison over a compact spectrum,
+with the topology of pointwise convergence. -/
+theorem compact_strict_comparison_margin {S : Type*} {K : Set (S → ℝ)}
+ (hK : IsCompact K) {X Y : S} (h : ∀ F ∈ K, F X < F Y) :
+ ∃ b : ℕ, ∀ F ∈ K, ((b : ℝ) + 1) * F X < (b : ℝ) * F Y := by
+ rcases K.eq_empty_or_nonempty with rfl | hne
+ · exact ⟨1, by simp⟩
+ let r (F : S → ℝ) := F X / (F Y - F X)
+ have hc : ContinuousOn r K := (continuous_apply X).continuousOn.div
+ ((continuous_apply Y).sub (continuous_apply X)).continuousOn
+ (fun F hF => (sub_pos.mpr (h F hF)).ne')
+ obtain ⟨G, _, hG⟩ := hK.exists_isMaxOn hne hc
+ obtain ⟨b, hb⟩ := exists_nat_gt (r G)
+ refine ⟨b, fun F hF => ?_⟩
+ have hlt : r F < b := (hG hF).trans_lt hb
+ have hb' := (div_lt_iff₀ (sub_pos.mpr (h F hF))).mp hlt
+ linarith
+
+/-- A finite set of generators detects every failure to match the target
+values with a uniform relative gap. It can include any specified generators. -/
+theorem compact_finite_generator_gap {ι Ω : Type*} [TopologicalSpace Ω] {K : Set Ω}
+ (hK : IsCompact K) (value : ι → Ω → ℝ) (target : ι → ℝ)
+ (hc : ∀ i, Continuous (value i)) (ht : ∀ i, 0 < target i)
+ (hv : ∀ x ∈ K, ∀ i, 0 < value i x)
+ (hmismatch : ∀ x ∈ K, ∃ i, value i x ≠ target i)
+ (required : Finset ι) :
+ ∃ G : Finset ι, required ⊆ G ∧ ∃ δ : ℝ, 0 < δ ∧
+ ∀ x ∈ K, ∃ i ∈ G, 1 + δ ≤ value i x / target i ∨ 1 + δ ≤ target i / value i x := by
+ classical
+ let I := ι × {δ : ℝ // 0 < δ}
+ let U (p : I) := {x | (1 + p.2.val) * target p.1 < value p.1 x} ∪
+ {x | (1 + p.2.val) * value p.1 x < target p.1}
+ have hopen (p : I) : IsOpen (U p) :=
+ (isOpen_lt continuous_const (hc p.1)).union
+ (isOpen_lt (continuous_const.mul (hc p.1)) continuous_const)
+ have hcover : K ⊆ ⋃ p, U p := by
+ intro x hx
+ obtain ⟨i, hi⟩ := hmismatch x hx
+ rcases lt_or_gt_of_ne hi with h | h
+ · have hr : 1 < target i / value i x := (one_lt_div (hv x hx i)).mpr h
+ obtain ⟨c, hc₁, hc₂⟩ := exists_between hr
+ refine mem_iUnion.mpr ⟨(i, ⟨c - 1, sub_pos.mpr hc₁⟩), Or.inr ?_⟩
+ change (1 + (c - 1)) * value i x < target i
+ simpa using (lt_div_iff₀ (hv x hx i)).mp hc₂
+ · have hr : 1 < value i x / target i := (one_lt_div (ht i)).mpr h
+ obtain ⟨c, hc₁, hc₂⟩ := exists_between hr
+ refine mem_iUnion.mpr ⟨(i, ⟨c - 1, sub_pos.mpr hc₁⟩), Or.inl ?_⟩
+ change (1 + (c - 1)) * target i < value i x
+ simpa using (lt_div_iff₀ (ht i)).mp hc₂
+ obtain ⟨s, hs⟩ := hK.elim_finite_subcover U hopen hcover
+ rcases s.eq_empty_or_nonempty with rfl | hne
+ · have : K = ∅ := by simpa using hs
+ exact ⟨required, Finset.Subset.refl _, 1, by norm_num, by simp [this]⟩
+ let δ := s.inf' hne fun p => p.2.val
+ have hδ : 0 < δ := (Finset.lt_inf'_iff hne).mpr fun p _ => p.2.property
+ refine ⟨required ∪ s.image Prod.fst, Finset.subset_union_left, δ, hδ, fun x hx => ?_⟩
+ obtain ⟨p, hp, hxU⟩ := mem_iUnion₂.mp (hs hx)
+ have hδp : δ ≤ p.2.val := Finset.inf'_le _ hp
+ refine ⟨p.1, Finset.mem_union_right _ (Finset.mem_image_of_mem _ hp), ?_⟩
+ rcases hxU with h | h
+ · exact Or.inl ((add_le_add_right hδp 1).trans ((lt_div_iff₀ (ht p.1)).mpr h).le)
+ · exact Or.inr ((add_le_add_right hδp 1).trans ((lt_div_iff₀ (hv x hx p.1)).mpr h).le)
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralCubeObstruction.lean b/lean/OAI/Computability/VPVNP/SpectralCubeObstruction.lean
new file mode 100644
index 0000000000..c49fe923e5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralCubeObstruction.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.WireCATZero
+import OAI.Computability.VPVNP.BalancedLayoutThreshold
+import OAI.Computability.VPVNP.ExactTensorPowerLayout
+import OAI.Computability.VPVNP.TerminalStarWitness
+import OAI.Computability.VPVNP.CubeExclusion
+import OAI.Computability.VPVNP.SpectralRealizable
+
+/-!
+# Excluding a Euclidean cube from spectral wire distances
+
+A hypothetical cube realization supplies one tensor whose spectral value is
+strictly above the cost of every balanced two-center layout. Tensor powers of
+this witness are projections from the paired-variable universal family at all
+sufficiently large input lengths. This excludes the cube under the small-circuit
+hypothesis, at the paper's threshold of `18 * C²`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open WireTensor
+open scoped symmDiff
+
+private theorem cube_wire_distances {k : Type*} [Field k] {ℓ : ℕ}
+ (w : WireRealization k (Grassmann.cubeDistances ℓ)) (A B : Finset (Fin ℓ)) :
+ w.spectrum.wireDistance (w.label A) (w.label B)^2 = (w.scale⁻¹)^2 * (A ∆ B).card := by
+ have h := w.distances A B
+ have h' : w.spectrum.wireDistance (w.label A) (w.label B) =
+ w.scale⁻¹ * Real.sqrt ((A ∆ B).card : ℝ) := by
+ rw [show Real.sqrt ((A ∆ B).card : ℝ) = w.scale * w.spectrum.wireDistance (w.label A) (w.label B) from h,
+ inv_mul_cancel_left₀ w.scale_pos.ne']
+ rw [h', mul_pow, Real.sq_sqrt (Nat.cast_nonneg _)]
+
+
+/-- Infinitely many circuits of size at most `n^C` exclude the corners of the
+Euclidean cube from every spectral wire metric over the field. The literal incidence-table encoding of the
+tensor power preserves the asymptotic central wire exponent `C`. -/
+theorem cube_obstruction (k : Type*) [Field k] {C ℓ : ℕ} (hC : 1 ≤ C)
+ (hdim : 18 * C^2 ≤ ℓ)
+ (hsmall : ∀ N, ∃ n ≥ N, circuitSize (MvPolynomial.map (Int.castRingHom k) (P n)) ≤ n^C) :
+ ¬ RealizableUpToScale k (Grassmann.cubeDistances ℓ) := by
+ intro hw
+ obtain ⟨w⟩ := hw
+ let σ := w.scale⁻¹
+ have hσ : 0 < σ := inv_pos.mpr w.scale_pos
+ have hcreal : (1 : ℝ) ≤ (C : ℕ) := by exact_mod_cast hC
+ have hℓreal : (18 : ℝ)*((C : ℕ) : ℝ)^2 ≤ ℓ := by exact_mod_cast hdim
+ have hℓ : 3 ≤ ℓ := by
+ have hh : 1 ≤ C^2 := Nat.one_le_pow _ _ hC
+ omega
+ obtain ⟨S, centers, ε, hε, hgap⟩ := w.spectrum.exists_cubeCentroid_layout_threshold
+ w.label hσ (cube_wire_distances w) hcreal hℓreal (by
+ intro S
+ let : Nontrivial S.Parties := S.old.injective.nontrivial
+ exact S.point.catZero_embedding)
+ let corner := S.old ∘ w.label
+ have hcorner (A B : Finset (Fin ℓ)) :
+ S.point.wireDistance (corner A) (corner B)^2 = σ^2 * (A ∆ B).card := by
+ rw [show S.point.wireDistance (corner A) (corner B) = _ from S.distances _ _]
+ exact cube_wire_distances w A B
+ let : Nontrivial S.Parties := S.old.injective.nontrivial
+ obtain ⟨b, hb, A, hnz, hval⟩ := S.point.exists_cubeStar_witness corner hσ hε hcorner
+ have hn := not_small_universal_of_exact_tensorPower_layout S.point (fun i => corner {i}) centers hb
+ (by omega : 0 < C) (by simpa only [Fintype.card_fin] using hℓ) A hnz hσ hval (by
+ intro s hlo hhi
+ simp only [Fintype.card_fin] at hlo hhi
+ exact (hgap s hlo hhi).le)
+ exact hn hsmall
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralCurvature.lean b/lean/OAI/Computability/VPVNP/SpectralCurvature.lean
new file mode 100644
index 0000000000..92e4931d55
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralCurvature.lean
@@ -0,0 +1,163 @@
+import OAI.Computability.VPVNP.SpectralSectorDistance
+import OAI.Computability.VPVNP.SpectralOppositeRays
+import OAI.Computability.VPVNP.TangentRatio
+import OAI.Computability.VPVNP.SpectralMidpointToCAT
+import OAI.Computability.VPVNP.RealizedTransport
+
+/-!
+# The squared midpoint inequality for wire metric spaces
+
+Section 4.1 rescales the three segments from a midpoint to the three
+marked vertices. In each tangent sector the distance from the first ray at
+time `t` to the second ray at time one obeys a Euclidean quadratic law.
+The triangle inequality between the opposite rays at arbitrary `t` forces
+the comparison at the original midpoint. Saturation forces each original
+sector to have its Euclidean distances at every parameter.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open Set
+
+variable (k : Type*) [Field k] {X : Type*} [MetricSpace X] {o x y z : X}
+
+private theorem tangentRay_vertex_sq (hf : HasFractions X) (hT : FractionTransport X)
+ (hTT : FractionTransport (Tangent o)) (hr : RealizableConfigurations k X)
+ (a : RadialSegment o x) (c : RadialSegment o z) (t : ℝ) (ht : 0 ≤ t) :
+ dist (tangentRay a t) (tangentRay c 1) ^ 2 =
+ t ^ 2 * dist o x ^ 2 + dist o z ^ 2 +
+ t * (radialSlope a c ^ 2 - dist o x ^ 2 - dist o z ^ 2) := by
+ let f := tangent_hasFractions hf o
+ let A := tangentRay a
+ let C := tangentRay c
+ have hc (r : ℝ) (hr : r ∈ Ici 0) : dist (A r) (C r) = radialSlope a c * r :=
+ tangentRay_cross hT a c hr
+ have haxis₁ := sectorPoint_axis_left f A C hc ht (show t ∈ Ici 0 from ht)
+ have haxis₂ := sectorPoint_axis_right f A C hc (r := 1) zero_le_one (by norm_num : (1 : ℝ) ∈ Ici 0)
+ let p : ℝ × ℝ := (t, 0)
+ let q : ℝ × ℝ := (0, 1)
+ have hp : p ∈ sectorDomain (Ici 0) := ⟨ht, le_rfl, by simpa [p] using ht⟩
+ have hq : q ∈ sectorDomain (Ici 0) := ⟨le_rfl, zero_le_one, by norm_num [q]⟩
+ have hsq := sectorPoint_dist_sq k f hTT (tangent_realizableConfigurations hr o)
+ (convex_Ici _) (by norm_num : (0 : ℝ) ∈ Ici 0) (by norm_num : (1 : ℝ) ∈ Ici 0)
+ (fun _ hr _ hs ↦ tangentRay_speed a hr hs) (fun _ hr _ hs ↦ tangentRay_speed c hr hs)
+ hc hp hq
+ have heq : dist (A t) (C 1) = dist (sectorPoint f A C p) (sectorPoint f A C q) := calc
+ dist (A t) (C 1) = dist (C 1) (A t) := dist_comm _ _
+ _ = dist (C 1) (sectorPoint f A C p) := PseudoMetricSpace.dist_eq_of_dist_zero _ haxis₁
+ _ = dist (sectorPoint f A C p) (C 1) := dist_comm _ _
+ _ = _ := (PseudoMetricSpace.dist_eq_of_dist_zero _ haxis₂).symm
+ change dist (A t) (C 1) ^ 2 = _
+ rw [heq, hsq]
+ dsimp only [p,q]
+ ring
+
+private theorem opposite_slopes (hf : HasFractions X) (hT : FractionTransport X)
+ (hTT : FractionTransport (Tangent o)) (hr : RealizableConfigurations k X)
+ (ho : AtFraction x y (1 / 2) o) (a : RadialSegment o x) (b : RadialSegment o y)
+ (c : RadialSegment o z) :
+ 2 * (dist o x ^ 2 + dist o z ^ 2) ≤ radialSlope a c ^ 2 + radialSlope b c ^ 2 := by
+ have hx := ho.1
+ rw [dist_comm x o] at hx
+ have hy : dist o y = dist o x := by linarith only [hx, ho.2]
+ apply opposite_ray_quadratic_bound dist_nonneg
+ (fun t ↦ dist (tangentRay a t) (tangentRay c 1)) (fun t ↦ dist (tangentRay b t) (tangentRay c 1))
+ · intro t ht
+ rw [← tangentRay_opposite hT ho a b ht, dist_comm (tangentRay b t) (tangentRay c 1)]
+ exact dist_triangle _ _ _
+ · exact tangentRay_vertex_sq k hf hT hTT hr a c
+ · intro t ht
+ simpa only [hy] using tangentRay_vertex_sq k hf hT hTT hr b c t ht
+
+/-- Lemma 4.1's inequality when the segment transport inequalities (2.2)
+are given in the space and its rescaling at the marked midpoint. -/
+theorem squared_midpoint_of_transport (hf : HasFractions X) (hT : FractionTransport X)
+ (hTT : FractionTransport (Tangent o)) (hr : RealizableConfigurations k X)
+ (ho : AtFraction x y (1 / 2) o) (z : X) :
+ 2 * dist z o ^ 2 + (1 / 2 : ℝ) * dist x y ^ 2 ≤ dist z x ^ 2 + dist z y ^ 2 := by
+ obtain ⟨a⟩ := exists_radialSegment hf hT o x
+ obtain ⟨b⟩ := exists_radialSegment hf hT o y
+ obtain ⟨c⟩ := exists_radialSegment hf hT o z
+ have h := opposite_slopes k hf hT hTT hr ho a b c
+ have h₁ := (sq_le_sq₀ (radialSlope_nonneg a c) dist_nonneg).mpr (radialSlope_le_dist a c)
+ have h₂ := (sq_le_sq₀ (radialSlope_nonneg b c) dist_nonneg).mpr (radialSlope_le_dist b c)
+ have hx := ho.1
+ rw [dist_comm x o] at hx
+ rw [dist_comm z x, dist_comm z y, dist_comm z o]
+ rw [hx] at h
+ linarith only [h, h₁, h₂]
+
+/-- Euclidean (possibly degenerate) distances throughout the filled sector
+of two segments. The mixed coefficient is determined by the three boundary
+lengths, as in the Euclidean cosine rule. -/
+def IsEuclideanSector (hf : HasFractions X) (a : RadialSegment o x) (c : RadialSegment o z) : Prop :=
+ ∀ p ∈ sectorDomain (Icc (0 : ℝ) 1), ∀ q ∈ sectorDomain (Icc (0 : ℝ) 1),
+ dist (sectorPoint hf a.path c.path p) (sectorPoint hf a.path c.path q) ^ 2 =
+ (p.1 - q.1) ^ 2 * dist o x ^ 2 + (p.2 - q.2) ^ 2 * dist o z ^ 2 +
+ (p.1 - q.1) * (p.2 - q.2) * (dist o x ^ 2 + dist o z ^ 2 - dist x z ^ 2)
+
+private theorem euclideanSector_of_endpointSlope (hf : HasFractions X) (hT : FractionTransport X)
+ (hr : RealizableConfigurations k X) (a : RadialSegment o x) (c : RadialSegment o z)
+ (h : radialSlope a c = dist x z) : IsEuclideanSector hf a c := by
+ have hc := (radialSlope_eq_endpoint hT a c).mp h
+ rw [h] at hc
+ intro p hp q hq
+ exact sectorPoint_dist_sq k hf hT hr (convex_Icc _ _) (by simp) (by simp)
+ a.speed c.speed hc hp hq
+
+/-- At equality in Lemma 4.1, both sectors based at the midpoint, joining
+the third vertex to each endpoint, are Euclidean throughout. -/
+theorem euclideanSectors_of_midpoint_eq (hf : HasFractions X) (hT : FractionTransport X)
+ (hTT : FractionTransport (Tangent o)) (hr : RealizableConfigurations k X)
+ (ho : AtFraction x y (1 / 2) o) (a : RadialSegment o x) (b : RadialSegment o y)
+ (c : RadialSegment o z) (heq : 2 * dist z o ^ 2 + (1 / 2 : ℝ) * dist x y ^ 2 =
+ dist z x ^ 2 + dist z y ^ 2) : IsEuclideanSector hf a c ∧ IsEuclideanSector hf b c := by
+ have h := opposite_slopes k hf hT hTT hr ho a b c
+ have h₁ := (sq_le_sq₀ (radialSlope_nonneg a c) dist_nonneg).mpr (radialSlope_le_dist a c)
+ have h₂ := (sq_le_sq₀ (radialSlope_nonneg b c) dist_nonneg).mpr (radialSlope_le_dist b c)
+ have hx := ho.1
+ rw [dist_comm x o] at hx
+ rw [dist_comm z x, dist_comm z y, dist_comm z o] at heq
+ rw [hx] at h
+ constructor
+ · apply euclideanSector_of_endpointSlope k hf hT hr
+ apply (sq_eq_sq₀ (radialSlope_nonneg a c) dist_nonneg).mp
+ linarith only [h, h₁, h₂, heq]
+ · apply euclideanSector_of_endpointSlope k hf hT hr
+ apply (sq_eq_sq₀ (radialSlope_nonneg b c) dist_nonneg).mp
+ linarith only [h, h₁, h₂, heq]
+
+/-- Equation (4.2) from spectral configurations, using the six-point wire
+transport law of Lemma 2.2. No completeness assumption on the target is needed. -/
+theorem hasCATZeroSegments_of_wire_transport
+ (hwire : ∀ (J : Type) [Fintype J] [Nontrivial J] (F : WireTensor.SpectralPoint k J),
+ @FractionTransport J F.wirePseudoMetric)
+ (hf : HasFractions X) (hr : RealizableConfigurations k X) :
+ SpectralGeometry.HasCATZeroSegments X := by
+ have hT : FractionTransport X := fractionTransport_of_realizable hwire hr
+ apply hasCATZeroSegments_of_midpoint hf hT
+ intro x y z o ho
+ exact squared_midpoint_of_transport k hf hT
+ (fractionTransport_of_realizable hwire (tangent_realizableConfigurations hr o)) hr ho z
+
+/-- The equality assertion of Lemma 4.1 under the same six-point wire
+transport law. The formula applies to every marked point in both sectors. -/
+theorem euclideanSectors_of_wire_transport
+ (hwire : ∀ (J : Type) [Fintype J] [Nontrivial J] (F : WireTensor.SpectralPoint k J),
+ @FractionTransport J F.wirePseudoMetric)
+ (hf : HasFractions X) (hr : RealizableConfigurations k X)
+ (ho : AtFraction x y (1 / 2) o) (a : RadialSegment o x) (b : RadialSegment o y)
+ (c : RadialSegment o z) (heq : 2 * dist z o ^ 2 + (1 / 2 : ℝ) * dist x y ^ 2 =
+ dist z x ^ 2 + dist z y ^ 2) : IsEuclideanSector hf a c ∧ IsEuclideanSector hf b c :=
+ euclideanSectors_of_midpoint_eq k hf (fractionTransport_of_realizable hwire hr)
+ (fractionTransport_of_realizable hwire (tangent_realizableConfigurations hr o)) hr ho a b c heq
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralGeometry.lean b/lean/OAI/Computability/VPVNP/SpectralGeometry.lean
new file mode 100644
index 0000000000..8234c0cdff
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralGeometry.lean
@@ -0,0 +1,422 @@
+import OAI.Computability.VPVNP.Barycenter
+import Mathlib.Analysis.InnerProductSpace.PiL2
+import Mathlib.Analysis.Real.Sqrt
+import Mathlib.Algebra.Order.Group.MinMax
+import Mathlib.Topology.MetricSpace.Pseudo.Defs
+import Mathlib.Tactic.Positivity
+import Mathlib.Tactic.NormNum
+import Mathlib.Tactic.FieldSimp
+import Mathlib.Tactic.Linarith
+import Mathlib.Tactic.Ring
+
+/-!
+# Spectral wire geometry and compression estimates
+
+In Theorem 4.2 of *VP and VNP differ over every field*, the unit cube's basis
+vertices have total distance `√(j * (j - 1))` to their centroid, for a group
+of size `j`. Equation (4.5) uses two such groups and charges the wire between
+their centroids in proportion to its length `√(1/s + 1/t)`. Lemma 6.2 uses
+the squared-distance CAT(0) inequality to reduce the weighted energy of the
+six-party wire motif. Appendix A.3 obtains its endpoint-coupling bound by
+splitting a two-row cost table and shrinking the range of its column gaps.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+/-- Total length of the star from the centroid to a group of basis vertices. -/
+noncomputable def starLength (j : ℝ) : ℝ := Real.sqrt (j * (j - 1))
+
+private theorem starLength_sq {j : ℝ} (hj : 1 ≤ j) :
+ starLength j ^ 2 = j * (j - 1) :=
+ Real.sq_sqrt (mul_nonneg (by linarith) (by linarith))
+
+private theorem starLength_lt {j : ℝ} (hj : 1 ≤ j) :
+ starLength j < j - 1 / 2 := by
+ by_contra! h
+ have hs := starLength_sq hj
+ have := mul_self_le_mul_self (by linarith : 0 ≤ j - 1 / 2) h
+ nlinarith
+
+/-- Splitting the star at two centroids saves strictly more than half a unit
+on the terminal wires, before paying for the wire between the centroids. -/
+theorem starLength_split {s t : ℝ} (hs : 1 ≤ s) (ht : 1 ≤ t) :
+ starLength s + starLength t + 1 / 2 < starLength (s + t) := by
+ have h : starLength s + t < starLength (s + t) := by
+ apply Real.lt_sqrt_of_sq_lt
+ nlinarith only [starLength_sq hs,
+ mul_pos (by linarith : 0 < t) (sub_pos.mpr (starLength_lt hs))]
+ linarith [starLength_lt ht]
+
+/-- The strict gap between the star bound (4.4) and the leading term of (4.5).
+The balance conditions say that each side contains at least one third of the
+terminals. The inequality remains strict at the threshold `s + t = 18 * C²`. -/
+theorem balancedCut_strictGap {s t C : ℝ} (hs : 1 ≤ s) (ht : 1 ≤ t)
+ (hbal₁ : s ≤ 2 * t) (hbal₂ : t ≤ 2 * s) (hdim : 18 * C ^ 2 ≤ s + t) :
+ starLength s + starLength t + C * Real.sqrt (1 / s + 1 / t) < starLength (s + t) := by
+ have hs' : 0 < s := by linarith
+ have ht' : 0 < t := by linarith
+ have hbudget : 4 * (C ^ 2 * (s + t)) ≤ s * t := by
+ nlinarith only [mul_nonneg (sub_nonneg.mpr hbal₁) (sub_nonneg.mpr hbal₂),
+ mul_nonneg (sub_nonneg.mpr hdim) (add_pos hs' ht').le]
+ have hsqrt : (C * Real.sqrt (1 / s + 1 / t)) ^ 2 * (s * t) = C ^ 2 * (s + t) := by
+ rw [mul_pow, Real.sq_sqrt (add_nonneg (by positivity) (by positivity))]
+ field_simp
+ ring
+ have hsq : (C * Real.sqrt (1 / s + 1 / t)) ^ 2 ≤ (1 / 2 : ℝ) ^ 2 := by
+ apply (mul_le_mul_iff_left₀ (mul_pos hs' ht')).mp
+ rw [hsqrt]
+ linarith
+ have hlen : C * Real.sqrt (1 / s + 1 / t) ≤ 1 / 2 := by
+ by_contra! h
+ have := mul_self_lt_mul_self (by norm_num : (0 : ℝ) ≤ 1 / 2) h
+ nlinarith
+ linarith [starLength_split hs ht]
+
+noncomputable section
+
+variable {ι : Type*} [Fintype ι] [DecidableEq ι]
+
+/-- The centroid of the standard basis vertices indexed by a subset. -/
+def subsetCentroid (S : Finset ι) : EuclideanSpace ℝ ι :=
+ WithLp.toLp 2 (fun i ↦ if i ∈ S then (S.card : ℝ)⁻¹ else 0)
+
+private lemma subsetCentroid_inner_self (S : Finset ι) :
+ inner ℝ (subsetCentroid S) (subsetCentroid S) = (S.card : ℝ)⁻¹ := by
+ simp only [PiLp.inner_apply, RCLike.inner_apply, subsetCentroid]
+ change (∑ i, (if i ∈ S then (S.card : ℝ)⁻¹ else 0) *
+ star (if i ∈ S then (S.card : ℝ)⁻¹ else 0)) = (S.card : ℝ)⁻¹
+ simp only [star_trivial, apply_ite₂ (· * ·), zero_mul, Finset.sum_ite_mem, Finset.univ_inter,
+ Finset.sum_const, nsmul_eq_mul]
+ by_cases hs : S.card = 0
+ · simp [hs]
+ · have h : (S.card : ℝ) ≠ 0 := by exact_mod_cast hs
+ field_simp
+
+/-- Distance from a standard basis vertex in a subset to that subset's centroid. -/
+theorem basis_dist_subsetCentroid_sq {S : Finset ι} {i : ι} (hi : i ∈ S) :
+ (dist (EuclideanSpace.single i (1 : ℝ)) (subsetCentroid S)) ^ 2 =
+ 1 - (S.card : ℝ)⁻¹ := by
+ rw [dist_eq_norm, ← real_inner_self_eq_norm_sq, inner_sub_left, inner_sub_right,
+ inner_sub_right, subsetCentroid_inner_self, EuclideanSpace.inner_single_left,
+ EuclideanSpace.inner_single_left, EuclideanSpace.inner_single_right]
+ simp [subsetCentroid, hi]
+
+/-- Total terminal-to-centroid length of one side of the balanced layout. -/
+theorem subsetCentroid_star_length (S : Finset ι) :
+ ∑ i ∈ S, dist (EuclideanSpace.single i (1 : ℝ)) (subsetCentroid S) =
+ √((S.card : ℝ) * ((S.card : ℝ) - 1)) := by
+ rcases S.eq_empty_or_nonempty with rfl | hS
+ · simp
+ obtain ⟨j, hj⟩ := hS
+ let r := dist (EuclideanSpace.single j (1 : ℝ)) (subsetCentroid S)
+ have hr : 0 ≤ r := dist_nonneg
+ have hsq : r ^ 2 = 1 - (S.card : ℝ)⁻¹ := basis_dist_subsetCentroid_sq hj
+ have heq (i) (hi : i ∈ S) :
+ dist (EuclideanSpace.single i (1 : ℝ)) (subsetCentroid S) = r := by
+ apply (sq_eq_sq₀ dist_nonneg hr).mp
+ rw [basis_dist_subsetCentroid_sq hi, hsq]
+ rw [Finset.sum_congr rfl heq, Finset.sum_const, nsmul_eq_mul]
+ have hc : (1 : ℝ) ≤ S.card := by exact_mod_cast S.card_pos.mpr ⟨j, hj⟩
+ have hc' : (S.card : ℝ) ≠ 0 := by linarith
+ symm
+ rw [Real.sqrt_eq_iff_eq_sq (mul_nonneg (by positivity) (sub_nonneg.mpr hc))
+ (mul_nonneg (by positivity) hr), mul_pow, hsq]
+ field_simp
+
+/-- Disjoint sides of a cut have orthogonal centroids. -/
+theorem disjoint_subsetCentroids_inner {S T : Finset ι} (h : Disjoint S T) :
+ inner ℝ (subsetCentroid S) (subsetCentroid T) = 0 := by
+ rw [PiLp.inner_apply]
+ apply Finset.sum_eq_zero
+ intro i _
+ have disj : i ∈ S → i ∉ T := fun hS hT ↦ Finset.disjoint_left.mp h hS hT
+ by_cases hs : i ∈ S <;> simp [subsetCentroid, hs, disj, RCLike.inner_apply]
+
+/-- The length of the wire joining the two side centroids in the balanced layout of (4.5). -/
+theorem disjoint_subsetCentroids_dist {S T : Finset ι} (h : Disjoint S T) :
+ dist (subsetCentroid S) (subsetCentroid T) =
+ √((S.card : ℝ)⁻¹ + (T.card : ℝ)⁻¹) := by
+ symm
+ apply (Real.sqrt_eq_iff_eq_sq (by positivity) dist_nonneg).mpr
+ rw [ dist_eq_norm, ← real_inner_self_eq_norm_sq, inner_sub_left, inner_sub_right,
+ inner_sub_right, subsetCentroid_inner_self, subsetCentroid_inner_self,
+ disjoint_subsetCentroids_inner h, disjoint_subsetCentroids_inner h.symm]
+ ring
+
+
+/-- Centroid of the standard basis vertices of the full cube. -/
+def basisCentroid (n : ℕ) : EuclideanSpace ℝ (Fin n) :=
+ subsetCentroid (Finset.univ : Finset (Fin n))
+
+theorem basisCentroid_dist_sq {n : ℕ} (i : Fin n) :
+ (dist (EuclideanSpace.single i (1 : ℝ)) (basisCentroid n)) ^ 2 = 1 - (n : ℝ)⁻¹ := by
+ simpa [basisCentroid] using basis_dist_subsetCentroid_sq (Finset.mem_univ i)
+
+theorem basisCentroid_star_length (n : ℕ) :
+ ∑ i : Fin n, dist (EuclideanSpace.single i (1 : ℝ)) (basisCentroid n) =
+ √((n : ℝ) * ((n : ℝ) - 1)) := by
+ simpa [basisCentroid] using subsetCentroid_star_length (Finset.univ : Finset (Fin n))
+
+private theorem equidistant_centroid_minimizes {ι E : Type*} [Fintype ι]
+ [NormedAddCommGroup E] [InnerProductSpace ℝ E] {x : ι → E} {c : E} {r : ℝ}
+ (hr : 0 ≤ r) (hzero : ∑ i, (x i - c) = 0)
+ (hrad : ∀ i, ‖x i - c‖ = r) (q : E) :
+ ∑ i, dist (x i) c ≤ ∑ i, dist (x i) q := by
+ simp only [dist_eq_norm, hrad]
+ rcases hr.eq_or_lt with rfl | hr
+ · simp only [Finset.sum_const_zero]
+ exact Finset.sum_nonneg fun i _ ↦ norm_nonneg (x i - q)
+ apply le_of_mul_le_mul_left _ hr
+ simp only [Finset.mul_sum]
+ calc
+ ∑ _ : ι, r * r = ∑ i, inner ℝ (x i - c) (x i - c) := by
+ simp only [real_inner_self_eq_norm_sq, hrad, sq]
+ _ = ∑ i, inner ℝ (x i - c) (x i - q) := by
+ have h : ∀ i, x i - q = (x i - c) + (c - q) := fun i ↦ by abel
+ simp_rw [h, inner_add_right]
+ rw [Finset.sum_add_distrib, ← sum_inner, hzero, inner_zero_left, add_zero]
+ _ ≤ ∑ i, r * ‖x i - q‖ := Finset.sum_le_sum fun i _ ↦ by
+ simpa only [hrad] using real_inner_le_norm (x i - c) (x i - q)
+
+private theorem basisCentroid_sum_sub (n : ℕ) :
+ ∑ i : Fin n, (EuclideanSpace.single i (1 : ℝ) - basisCentroid n) = 0 := by
+ ext j
+ have hn : (n : ℝ) ≠ 0 := by exact_mod_cast (Nat.ne_of_gt j.pos)
+ change (WithLp.ofLp (∑ i : Fin n, (EuclideanSpace.single i (1 : ℝ) - basisCentroid n))) j = 0
+ rw [WithLp.ofLp_sum, Finset.sum_apply]
+ simp only [WithLp.ofLp_sub, Pi.sub_apply, EuclideanSpace.single, PiLp.ofLp_single, Pi.single_apply,
+ basisCentroid, subsetCentroid, Finset.sum_sub_distrib]
+ simp [hn]
+
+/-- Among all centers, the centroid minimizes the total distance to the basis vertices. -/
+theorem basisCentroid_minimizes {n : ℕ} (q : EuclideanSpace ℝ (Fin n)) :
+ ∑ i : Fin n, dist (EuclideanSpace.single i (1 : ℝ)) (basisCentroid n) ≤
+ ∑ i : Fin n, dist (EuclideanSpace.single i (1 : ℝ)) q := by
+ refine equidistant_centroid_minimizes (r := √(1 - (n : ℝ)⁻¹))
+ (Real.sqrt_nonneg _) (basisCentroid_sum_sub n) ?_ q
+ intro i
+ rw [← basisCentroid_dist_sq i, Real.sqrt_sq (dist_nonneg), dist_eq_norm]
+
+
+/-- A balanced two-centroid layout has strictly less total weighted wire length
+than the single-center layout, for every choice of the single center. The
+terminal wires have unit cost and the wire between centroids has weight `C`. -/
+theorem balancedLayout_strict {n : ℕ} {C : ℝ} (hC : 1 ≤ C) (hdim : 18 * C ^ 2 ≤ n)
+ (S : Finset (Fin n)) (hlo : n ≤ 3 * S.card) (hhi : 3 * S.card ≤ 2 * n)
+ (q : EuclideanSpace ℝ (Fin n)) :
+ (∑ i ∈ S, dist (EuclideanSpace.single i (1 : ℝ)) (subsetCentroid S)) +
+ (∑ i ∈ Sᶜ, dist (EuclideanSpace.single i (1 : ℝ)) (subsetCentroid Sᶜ)) +
+ C * dist (subsetCentroid S) (subsetCentroid Sᶜ) <
+ ∑ i : Fin n, dist (EuclideanSpace.single i (1 : ℝ)) q := by
+ have hnR : (1 : ℝ) ≤ n := by nlinarith only [sq_nonneg (C - 1), hC, hdim]
+ have hn : 1 ≤ n := by exact_mod_cast hnR
+ have hsum : S.card + Sᶜ.card = n := by simp
+ have hs : 1 ≤ S.card := by omega
+ have ht : 1 ≤ Sᶜ.card := by omega
+ have hbal₁ : S.card ≤ 2 * Sᶜ.card := by omega
+ have hbal₂ : Sᶜ.card ≤ 2 * S.card := by omega
+ have hsumR : (S.card : ℝ) + (Sᶜ.card : ℝ) = n := by exact_mod_cast hsum
+ have hgap := balancedCut_strictGap (C := C) (s := (S.card : ℝ)) (t := (Sᶜ.card : ℝ))
+ (by exact_mod_cast hs) (by exact_mod_cast ht) (by exact_mod_cast hbal₁)
+ (by exact_mod_cast hbal₂) (hsumR ▸ hdim)
+ apply lt_of_lt_of_le _ (basisCentroid_minimizes q)
+ rw [subsetCentroid_star_length, subsetCentroid_star_length,
+ disjoint_subsetCentroids_dist disjoint_compl_right, basisCentroid_star_length]
+ simpa only [hsumR, starLength, one_div] using hgap
+
+end
+
+/-- Lemma 6.2. The two demand edges are `ab` and `cd`. Each group of four
+supply edges receives masses `8/31, 4/31, 40/93, 16/31`, totaling `4/3`. -/
+theorem sixParty_energy {X : Type*} [PseudoMetricSpace X] (h : HasCATZeroSegments X)
+ (a b c d m n : X) :
+ (1 / 3 : ℝ) * dist a b ^ 2 + dist c d ^ 2 ≤
+ (31 / 16 : ℝ) * ((8 / 31 : ℝ) * (dist a c ^ 2 + dist b c ^ 2) +
+ (4 / 31 : ℝ) * (dist a m ^ 2 + dist b n ^ 2) +
+ (40 / 93 : ℝ) * (dist c m ^ 2 + dist c n ^ 2) +
+ (16 / 31 : ℝ) * (dist d m ^ 2 + dist d n ^ 2)) := by
+ obtain ⟨u, hu⟩ := h c m (1 / 3) (by norm_num) (by norm_num)
+ obtain ⟨v, hv⟩ := h c n (1 / 3) (by norm_num) (by norm_num)
+ obtain ⟨o, ho⟩ := h m n (1 / 2) (by norm_num) (by norm_num)
+ -- The two one-third points satisfy the common-origin convexity estimate.
+ have hcu := hu c
+ rw [dist_self] at hcu
+ have hnu := hu n
+ rw [dist_comm n c, dist_comm n m, dist_comm n u] at hnu
+ have huv := hv u
+ rw [dist_comm u c] at huv
+ have huv_le : dist u v ≤ (1 / 3 : ℝ) * dist m n := by
+ apply (sq_le_sq₀ dist_nonneg (by positivity)).1
+ linarith only [hcu, hnu, huv]
+ have hab : dist a b ≤ dist a u + dist b v + dist m n / 3 := by
+ have hpath := dist_triangle4 a u v b
+ rw [dist_comm v b] at hpath
+ linarith
+ have hab_sq := (sq_le_sq₀ dist_nonneg (by positivity)).2 hab
+ have hab_energy : (1 / 3 : ℝ) * dist a b ^ 2 ≤
+ (3 / 4 : ℝ) * (dist a u ^ 2 + dist b v ^ 2) + dist m n ^ 2 := by
+ nlinarith only [hab_sq, sq_nonneg (dist a u - dist b v),
+ sq_nonneg (dist a u - 4 * dist m n), sq_nonneg (dist b v - 4 * dist m n),
+ sq_nonneg (dist a u), sq_nonneg (dist b v), sq_nonneg (dist m n)]
+ have hcd_sq := (sq_le_sq₀ dist_nonneg (by positivity)).2 (dist_triangle_right c d o)
+ have hcd_energy : dist c d ^ 2 ≤ 2 * (dist c o ^ 2 + dist d o ^ 2) := by
+ nlinarith only [hcd_sq, sq_nonneg (dist c o - dist d o)]
+ linarith only [hab_energy, hcd_energy, hu a, hv b, ho c, ho d]
+
+/-- A table on the endpoint choices of two intervals. `false` denotes the first endpoint. -/
+abbrev EndpointTable := Bool → Bool → ℝ
+
+/-- The difference between the two rows in column `j`. -/
+def columnGap (M : EndpointTable) (j : Bool) : ℝ := M false j - M true j
+
+/-- With two columns the midpoint between the maximum and minimum gap is their average. -/
+noncomputable def gapMidpoint (M : EndpointTable) : ℝ := (columnGap M false + columnGap M true) / 2
+
+/-- The `true` branch is the positive split and lowers entries of row zero. The negative
+split lowers entries of row one. -/
+noncomputable def splitTable (M : EndpointTable) : Bool → EndpointTable
+ | true, false, j => min (M false j) (M true j + gapMidpoint M)
+ | true, true, j => M true j
+ | false, false, j => M false j
+ | false, true, j => min (M true j) (M false j - gapMidpoint M)
+
+theorem splitTable_le (M : EndpointTable) (branch i j : Bool) :
+ splitTable M branch i j ≤ M i j := by
+ cases branch <;> cases i <;> simp [splitTable]
+
+theorem columnGap_split (M : EndpointTable) (branch j : Bool) :
+ columnGap (splitTable M branch) j = if branch then min (columnGap M j) (gapMidpoint M)
+ else max (columnGap M j) (gapMidpoint M) := by
+ cases branch
+ · simp only [columnGap, splitTable, Bool.false_eq_true, ↓reduceIte, ← max_sub_sub_left,
+ sub_sub_cancel]
+ · simp only [columnGap, splitTable, ↓reduceIte, ← min_sub_sub_right, add_sub_cancel_left]
+
+theorem splitTable_gapDifference (M : EndpointTable) (branch : Bool) :
+ columnGap (splitTable M branch) false - columnGap (splitTable M branch) true =
+ (columnGap M false - columnGap M true) / 2 := by
+ have hmid : ∀ a b : ℝ, a ≤ b → a ≤ (a + b) / 2 ∧ (a + b) / 2 ≤ b := by
+ intro a b hab
+ constructor <;> linarith
+ rcases le_total (columnGap M false) (columnGap M true) with hab | hba
+ · obtain ⟨ha, hb⟩ := hmid _ _ hab
+ cases branch <;> simp [columnGap_split, gapMidpoint, ha, hb] <;> ring
+ · have ha : (columnGap M false + columnGap M true) / 2 ≤ columnGap M false := by linarith
+ have hb : columnGap M true ≤ (columnGap M false + columnGap M true) / 2 := by linarith
+ cases branch <;> simp [columnGap_split, gapMidpoint, ha, hb] <;> ring
+
+/-- Follow the specified sequence of positive and negative splits from the root table. -/
+noncomputable def leafTable (M : EndpointTable) : List Bool → EndpointTable
+ | [] => M
+ | branch :: rest => leafTable (splitTable M branch) rest
+
+theorem leafTable_le (M : EndpointTable) (path : List Bool) (i j : Bool) :
+ leafTable M path i j ≤ M i j := by
+ induction path generalizing M with
+ | nil => rfl
+ | cons branch rest ih => exact (ih (splitTable M branch)).trans (splitTable_le M branch i j)
+
+/-- At a leaf the difference of the two column gaps is exactly the initial difference
+multiplied by one half per split. -/
+theorem leafTable_gapDifference (M : EndpointTable) (path : List Bool) :
+ columnGap (leafTable M path) false - columnGap (leafTable M path) true =
+ (columnGap M false - columnGap M true) * (1 / 2) ^ path.length := by
+ induction path generalizing M with
+ | nil => simp [leafTable]
+ | cons branch rest ih =>
+ rw [leafTable, ih, splitTable_gapDifference, List.length_cons, pow_succ]
+ ring
+
+/-- The gap in each column stays in the initial interval at every stage. -/
+theorem leafTable_columnGap_mem (M : EndpointTable) (path : List Bool) {t : ℝ}
+ (h : ∀ j, |columnGap M j| ≤ t) (j : Bool) : |columnGap (leafTable M path) j| ≤ t := by
+ induction path generalizing M with
+ | nil => exact h j
+ | cons branch rest ih =>
+ apply ih
+ intro k
+ have h₀ := abs_le.mp (h false)
+ have h₁ := abs_le.mp (h true)
+ have hmid : -t ≤ gapMidpoint M ∧ gapMidpoint M ≤ t := by
+ unfold gapMidpoint
+ constructor <;> linarith
+ have hk := abs_le.mp (h k)
+ rw [columnGap_split, abs_le]
+ cases branch <;> simp [hk.1, hk.2, hmid.1, hmid.2]
+
+/-- A joint distribution with endpoint marginals `(1-u,u)` and `(1-v,v)`. -/
+structure EndpointCoupling (u v : ℝ) where
+ /-- Joint mass at each pair of endpoints, with row and column sums prescribed by the two
+ interpolation parameters. -/
+ mass : EndpointTable
+ nonneg : ∀ i j, 0 ≤ mass i j
+ row₀ : mass false false + mass false true = 1 - u
+ row₁ : mass true false + mass true true = u
+ col₀ : mass false false + mass true false = 1 - v
+ col₁ : mass false true + mass true true = v
+
+/-- Independent choices of the two endpoints. -/
+noncomputable def independentCoupling {u v : ℝ} (hu : 0 ≤ u ∧ u ≤ 1) (hv : 0 ≤ v ∧ v ≤ 1) :
+ EndpointCoupling u v where
+ mass i j := (if i then u else 1 - u) * (if j then v else 1 - v)
+ nonneg i j := by
+ cases i <;> cases j <;> simp <;> exact mul_nonneg (by linarith) (by linarith)
+ row₀ := by simp; ring
+ row₁ := by simp; ring
+ col₀ := by simp; ring
+ col₁ := by simp; ring
+
+/-- Expected value of the four entries under the coupling. -/
+noncomputable def EndpointCoupling.cost {u v : ℝ} (π : EndpointCoupling u v) (M : EndpointTable) : ℝ :=
+ π.mass false false * M false false + π.mass false true * M false true +
+ π.mass true false * M true false + π.mass true true * M true true
+
+private theorem coupling_mass₀_le_one {u v : ℝ} (π : EndpointCoupling u v) :
+ π.mass false false ≤ 1 := by
+ linarith only [π.row₀, π.row₁, π.nonneg false true, π.nonneg true false, π.nonneg true true]
+
+/-- Equal marginals force the signed difference of joint masses to be a multiple of the
+alternating table. Only the difference of the two column gaps contributes to its cost. -/
+theorem coupling_cost_sub {u v : ℝ} (ρ π : EndpointCoupling u v) (M : EndpointTable) :
+ ρ.cost M - π.cost M = (ρ.mass false false - π.mass false false) *
+ (columnGap M false - columnGap M true) := by
+ let e := ρ.mass false false - π.mass false false
+ have h₀₁ : ρ.mass false true = π.mass false true - e := by dsimp [e]; linarith only [ρ.row₀, π.row₀]
+ have h₁₀ : ρ.mass true false = π.mass true false - e := by dsimp [e]; linarith only [ρ.col₀, π.col₀]
+ have h₁₁ : ρ.mass true true = π.mass true true + e := by linarith only [ρ.row₁, π.row₁, h₁₀]
+ simp only [EndpointCoupling.cost, columnGap, h₀₁, h₁₀, h₁₁, e]
+ ring
+
+/-- The scalar coupling estimate at depth `path.length` in Appendix A.3. In particular
+`ρ` can be the independent coupling, while `π` may be any coupling of the endpoints. -/
+theorem coupling_leaf_bound {u v t : ℝ} (ρ π : EndpointCoupling u v)
+ (M : EndpointTable) (h : ∀ j, |columnGap M j| ≤ t) (path : List Bool) :
+ ρ.cost (leafTable M path) ≤ π.cost M + 2 * t * (1 / 2) ^ path.length := by
+ have hmass : |ρ.mass false false - π.mass false false| ≤ 1 := by
+ apply abs_le.mpr
+ constructor <;> linarith only [coupling_mass₀_le_one π, coupling_mass₀_le_one ρ,
+ π.nonneg false false, ρ.nonneg false false]
+ have hgap : |columnGap M false - columnGap M true| ≤ 2 * t := by
+ exact (abs_sub _ _).trans (by linarith only [h false, h true])
+ have hpow : 0 ≤ (1 / 2 : ℝ) ^ path.length := by positivity
+ have hleaf : π.cost (leafTable M path) ≤ π.cost M := by
+ have hw (i j : Bool) := mul_le_mul_of_nonneg_left (leafTable_le M path i j) (π.nonneg i j)
+ unfold EndpointCoupling.cost
+ linarith only [hw false false, hw false true, hw true false, hw true true]
+ have habs : |ρ.cost (leafTable M path) - π.cost (leafTable M path)| ≤
+ 2 * t * (1 / 2) ^ path.length := by
+ rw [coupling_cost_sub, leafTable_gapDifference, abs_mul, abs_mul, abs_of_nonneg hpow]
+ calc _ ≤ 1 * (2 * t * (1 / 2) ^ path.length) :=
+ mul_le_mul hmass (mul_le_mul_of_nonneg_right hgap hpow) (by positivity) (by norm_num)
+ _ = _ := one_mul _
+ linarith only [hleaf, (le_abs_self _).trans habs]
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralInterpolation.lean b/lean/OAI/Computability/VPVNP/SpectralInterpolation.lean
new file mode 100644
index 0000000000..32d3e203f3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralInterpolation.lean
@@ -0,0 +1,164 @@
+import OAI.Computability.VPVNP.SplitWireExtension
+import OAI.Computability.VPVNP.PlacedTensorComposition
+import OAI.Computability.VPVNP.CubeStar
+
+/-!
+# Adjoining finitely many interpolated parties to a spectral point
+
+A finite interpolation tree describes a point in every CAT(0) realization
+of a configuration. Each internal node can be adjoined by the fractional
+extension of Theorem 2.4(1). Subsequent extensions preserve all old tensor
+values and hence the already realized wire distances. This places the
+centroids used for the balanced cuts in Section 4.3 simultaneously.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u
+namespace WireTensor
+open VPVNP.SpectralGeometry
+
+variable {k : Type u} [Field k] {J : Type} [Fintype J]
+
+/-- An enlarged finite spectral configuration with its old parties marked.
+All placed old tensors keep their values. -/
+structure ExtendedSpectrum (F : SpectralPoint k J) where
+ /-- Finite party set of the enlarged spectral configuration. -/
+ Parties : Type
+ finiteParties : Fintype Parties
+ /-- Spectral point on the enlarged party set whose values extend those of the original point. -/
+ point : @SpectralPoint k Parties _ finiteParties
+ /-- Embedding that marks the original parties inside the enlarged configuration. -/
+ old : J ↪ Parties
+ values : ∀ T : Tensor.{u,0,0} k J, point.value (placeTensor old T) = F.value T
+ distances : ∀ a b, point.wireDistance (old a) (old b) = F.wireDistance a b
+
+attribute [instance] ExtendedSpectrum.finiteParties
+
+namespace ExtendedSpectrum
+
+variable {F : SpectralPoint k J}
+
+/-- Regard a spectral point as an extension of itself using the identity embedding on parties. -/
+noncomputable def refl (F : SpectralPoint k J) : ExtendedSpectrum F where
+ Parties := J
+ finiteParties := inferInstance
+ point := F
+ old := Function.Embedding.refl _
+ values T := (F.value_eq_of_mutual (placeTensor_id_mutual T)).symm
+ distances _ _ := rfl
+
+/-- Compose two successive extensions of a spectral point by composing the embeddings of their
+marked parties. -/
+noncomputable def trans (S : ExtendedSpectrum F) (U : ExtendedSpectrum S.point) :
+ ExtendedSpectrum F where
+ Parties := U.Parties
+ finiteParties := U.finiteParties
+ point := U.point
+ old := S.old.trans U.old
+ values T := ((U.point.value_eq_of_mutual (placeTensor_comp_mutual S.old U.old T)).symm.trans
+ (U.values _)).trans (S.values _)
+ distances a b := (U.distances _ _).trans (S.distances a b)
+
+private noncomputable def addParty (H : SpectralPoint k (Option J))
+ (extendsOld : ∀ T, H.value (embedOld T) = F.value T) : ExtendedSpectrum F where
+ Parties := Option J
+ finiteParties := inferInstance
+ point := H
+ old := Function.Embedding.some
+ values T := (H.value_eq_of_mutual (placeTensor_some_mutual T)).symm.trans (extendsOld _)
+ distances := F.wireDistance_extension H extendsOld
+
+/-- The marked party realizes the prescribed tree in every CAT(0) metric
+embedding of this finite configuration. -/
+def RealizesTree {V : Type*} (S : ExtendedSpectrum F) (labels : V → J)
+ (t : InterpolationTree V) (c : S.Parties) : Prop :=
+ ∀ (X : Type) [MetricSpace X] (hc : HasCATZeroSegments X) (e : S.Parties → X),
+ (∀ a b, dist (e a) (e b) = S.point.wireDistance a b) →
+ e c = t.eval hc (e ∘ S.old ∘ labels)
+
+/-- Once a tree is realized, it remains realized in each further extension. -/
+theorem RealizesTree.trans {V : Type*} {S : ExtendedSpectrum F} {labels : V → J}
+ {t : InterpolationTree V} {c : S.Parties} (h : S.RealizesTree labels t c)
+ (U : ExtendedSpectrum S.point) : (S.trans U).RealizesTree labels t (U.old c) := by
+ intro X _ hc e he
+ exact h X hc (e ∘ U.old) (fun a b ↦ (he _ _).trans (U.distances a b))
+
+end ExtendedSpectrum
+
+namespace SpectralPoint
+
+variable {V : Type*}
+
+/-- A single finite interpolation prescription can be realized while preserving
+every old tensor value. -/
+theorem exists_tree_extension (F : SpectralPoint k J) (labels : V → J)
+ (t : InterpolationTree V) :
+ ∃ (S : ExtendedSpectrum F) (c : S.Parties), S.RealizesTree labels t c := by
+ induction t generalizing J with
+ | vertex v =>
+ exact ⟨.refl F, labels v, fun _ _ _ _ _ ↦ rfl⟩
+ | segment l r frac ihl ihr =>
+ obtain ⟨S, a, ha⟩ := ihl F labels
+ obtain ⟨U, b, hb⟩ := ihr S.point (S.old ∘ labels)
+ obtain ⟨H, hH, hfrac⟩ := U.point.exists_fraction_extension (U.old a) b frac.property.1 frac.property.2
+ let Z := ExtendedSpectrum.addParty H hH
+ refine ⟨(S.trans U).trans Z, none, ?_⟩
+ intro X _ hc e he
+ have heH (i j : Option U.Parties) : dist (e i) (e j) = H.wireDistance i j := he i j
+ have he' (i j : U.Parties) : dist (e (some i)) (e (some j)) = U.point.wireDistance i j :=
+ (he _ _).trans (U.point.wireDistance_extension H hH i j)
+ have hleft := (ha.trans U) X hc (e ∘ some) he'
+ have hright := hb X hc (e ∘ some) he'
+ let g (v : V) := e (some (U.old (S.old (labels v))))
+ change e none = catPoint hc (l.eval hc g) (r.eval hc g) frac
+ change e (some (U.old a)) = l.eval hc g at hleft
+ change e (some b) = r.eval hc g at hright
+ rw [← hleft, ← hright]
+ apply catPoint_unique
+ · rw [dist_comm, heH, heH]
+ exact hfrac.1
+ · rw [heH, heH]
+ exact hfrac.2
+
+/-- Realize all trees in a finite indexed family in one enlarged spectrum. -/
+theorem exists_treeFamily_extension (F : SpectralPoint k J) (labels : V → J)
+ {I : Type} [Fintype I] (trees : I → InterpolationTree V) :
+ ∃ (S : ExtendedSpectrum F) (c : I → S.Parties), ∀ i, S.RealizesTree labels (trees i) (c i) := by
+ have byFin : ∀ n : ℕ, ∀ {K : Type} [Fintype K] (G : SpectralPoint k K) (v : V → K)
+ (ts : Fin n → InterpolationTree V), ∃ (S : ExtendedSpectrum G) (c : Fin n → S.Parties),
+ ∀ i, S.RealizesTree v (ts i) (c i) := by
+ intro n
+ induction n with
+ | zero =>
+ intro K _ G _ _
+ exact ⟨.refl G, Fin.elim0, fun i ↦ Fin.elim0 i⟩
+ | succ n ih =>
+ intro K _ G v ts
+ obtain ⟨S, a, ha⟩ := G.exists_tree_extension v (ts 0)
+ obtain ⟨U, c, hc⟩ := ih S.point (S.old ∘ v) (fun i ↦ ts i.succ)
+ exact ⟨S.trans U, Fin.cases (U.old a) c, Fin.cases (ha.trans U) hc⟩
+ let e := Fintype.equivFin I
+ obtain ⟨S, c, hc⟩ := byFin (Fintype.card I) F labels (trees ∘ e.symm)
+ exact ⟨S, c ∘ e, fun i ↦ by simpa only [Function.comp_apply, Equiv.symm_apply_apply] using hc (e i)⟩
+
+/-- The centroids of all subsets of the marked basis corners are parties of
+a single extension. Every isometric CAT(0) embedding locates those parties
+at the prescribed points of the filled cube. -/
+theorem exists_cubeCentroid_extension (F : SpectralPoint k J) {n : ℕ} (corner : Finset (Fin n) → J) :
+ ∃ (S : ExtendedSpectrum F) (c : Finset (Fin n) → S.Parties),
+ ∀ (X : Type) [MetricSpace X] (hc : HasCATZeroSegments X) (e : S.Parties → X),
+ (∀ a b, dist (e a) (e b) = S.point.wireDistance a b) → ∀ s,
+ e (c s) = filledSubsetCentroid hc (e ∘ S.old ∘ corner) s := by
+ obtain ⟨S, c, hs⟩ := F.exists_treeFamily_extension corner
+ (fun s ↦ cubeInterpolation (cubeCentroidCoordinates s))
+ exact ⟨S, c, fun X _ hc e he s ↦ (hs s X hc e he).trans (cubeInterpolation_eval _ _ _)⟩
+
+end SpectralPoint
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralLocalization.lean b/lean/OAI/Computability/VPVNP/SpectralLocalization.lean
new file mode 100644
index 0000000000..f0e1aaca84
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralLocalization.lean
@@ -0,0 +1,158 @@
+import OAI.Computability.VPVNP.SpectralLocalizationCone
+import OAI.Computability.VPVNP.SpectralLocalizationRing
+
+/-!
+# Clearing spectral comparison in the tensor semiring
+
+The denominators in Appendix A.1 are images of nonzero tensors, even if their
+images in the group completion are zero divisors. Equality after localization
+first supplies a multiplicative factor and then a common additive term. Both
+are elements of the original semiring.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+noncomputable section
+
+/-- The multiplicative system in the ring of formal differences. For a tensor
+semiring without zero divisors it is exactly the image of the nonzero tensors. -/
+def denominators (S : Type*) [CommSemiring S] : Submonoid (G S) :=
+ (nonZeroDivisors S).map toG.toMonoidHom
+
+/-- Ring of formal differences localized at the images of the non-zero-divisors of the
+semiring. -/
+abbrev A (S : Type*) [CommSemiring S] := Localization (denominators S)
+
+variable {S : Type*} [CommSemiring S]
+
+/-- The canonical map to the ring in which every nonzero tensor is invertible. -/
+def toA : S →+* A S := (algebraMap (G S) (A S)).comp toG
+
+instance [Countable S] : Countable (A S) :=
+ (IsLocalization.mk'_surjective (denominators S) (S := A S)).countable
+
+variable [NoZeroDivisors S]
+
+theorem toA_isUnit {s : S} (hs : s ≠ 0) : IsUnit (toA s) :=
+ IsLocalization.map_units (M := denominators S) (A S)
+ ⟨toG s, Submonoid.mem_map_of_mem toG.toMonoidHom (mem_nonZeroDivisors_of_ne_zero hs)⟩
+
+instance [CharZero S] : Algebra ℚ (A S) :=
+ ratAlgebraOfUnits _ fun n hn => by
+ simpa only [map_natCast] using toA_isUnit (S := S) (Nat.cast_ne_zero.mpr hn)
+
+/-- The inverse of the image of a nonzero tensor, chosen as the fraction with
+numerator one. -/
+def fractionInverse (s : S) (hs : s ≠ 0) : A S :=
+ IsLocalization.mk' (A S) (1 : G S)
+ (⟨toG s, Submonoid.mem_map_of_mem toG.toMonoidHom (mem_nonZeroDivisors_of_ne_zero hs)⟩ :
+ denominators S)
+
+theorem fraction_inverse_spec (s : S) (hs : s ≠ 0) :
+ fractionInverse s hs * toA s = 1 := by
+ unfold fractionInverse toA
+ rw [RingHom.comp_apply]
+ simpa only [map_one] using IsLocalization.mk'_spec (A S) (1 : G S)
+ (⟨toG s, Submonoid.mem_map_of_mem toG.toMonoidHom (mem_nonZeroDivisors_of_ne_zero hs)⟩ :
+ denominators S)
+
+omit [NoZeroDivisors S] in
+theorem one_add_ne_zero_of_rank (rank : S →+* ℕ) (s : S) : 1 + s ≠ 0 := by
+ intro he
+ have h := congrArg rank he
+ simp only [map_add, map_one, map_zero] at h
+ omega
+
+variable [Nontrivial S]
+
+/-- A localized element has one denominator and a difference of two original
+semiring elements as numerator. -/
+theorem exists_fraction (x : A S) :
+ ∃ a b s : S, s ≠ 0 ∧ x * toA s = toA a - toA b := by
+ obtain ⟨⟨g, ⟨m, hm⟩⟩, h⟩ := IsLocalization.surj (denominators S) x
+ obtain ⟨s, hs, rfl⟩ : ∃ s : S, s ∈ nonZeroDivisors S ∧ toG s = m := hm
+ obtain ⟨a,b,rfl⟩ := exists_sub g
+ exact ⟨a,b,s, mem_nonZeroDivisors_iff_ne_zero.mp hs, by simpa only [toA, RingHom.comp_apply,
+ map_sub] using h⟩
+
+/-- Clearing an equality of images in the localized completion produces both
+a common nonzero factor and a common summand in the original semiring. -/
+theorem toA_eq_iff (a b : S) : toA a = toA b ↔
+ ∃ c : S, c ≠ 0 ∧ ∃ w : S, c*a + w = c*b + w := by
+ change algebraMap (G S) (A S) (toG a) = algebraMap (G S) (A S) (toG b) ↔ _
+ rw [IsLocalization.eq_iff_exists (denominators S)]
+ constructor
+ · rintro ⟨⟨m, hm⟩, h⟩
+ obtain ⟨c,hc,rfl⟩ : ∃ c : S, c ∈ nonZeroDivisors S ∧ toG c = m := hm
+ refine ⟨c, mem_nonZeroDivisors_iff_ne_zero.mp hc, (toG_eq_iff _ _).mp ?_⟩
+ simpa only [map_mul] using h
+ · rintro ⟨c,hc,w,hw⟩
+ refine ⟨⟨toG c, Submonoid.mem_map_of_mem toG.toMonoidHom (mem_nonZeroDivisors_of_ne_zero hc)⟩, ?_⟩
+ simpa only [map_mul] using (toG_eq_iff _ _).mpr ⟨w,hw⟩
+
+variable [Preorder S]
+
+/-- Membership of a difference in the order cone clears to a single
+restriction with a multiplicative catalyst and a common additive term. -/
+theorem clear_comparison (H : OrderBounds S) {x y : S}
+ (h : FractionPositive toA (toA y - toA x)) :
+ ∃ c : S, c ≠ 0 ∧ ∃ w : S, c*x+w ≤ c*y+w := by
+ obtain ⟨a,b,s,hab,hs,h⟩ := h
+ have he : toA (s*y + b) = toA (s*x + a) := by
+ simp only [map_mul, map_add]
+ linear_combination h
+ obtain ⟨c,hc,w,hw⟩ := (toA_eq_iff _ _).mp he
+ refine ⟨c*s, mul_ne_zero hc hs, c*b+w, ?_⟩
+ calc
+ _ = c*(s*x+b)+w := by ring
+ _ ≤ c*(s*x+a)+w := H.add_mono (H.mul_mono c (H.add_mono (le_refl _) hab)) (le_refl _)
+ _ = c*(s*y+b)+w := hw.symm
+ _ = _ := by ring
+
+variable [CharZero S]
+
+theorem orderCone_bound (H : OrderBounds S) (x : A S) :
+ ∃ n : ℕ, n • (1 : A S) + x ∈ orderCone toA H :=
+ fractionPositive_bound toA H x (exists_fraction x)
+
+theorem one_mem_orderCone (H : OrderBounds S) : (1 : A S) ∈ orderCone toA H :=
+ fractionPositive_one toA H
+
+/-- A monotone flattening rank excludes minus the unit from the order cone. -/
+theorem neg_one_notMem_orderCone (H : OrderBounds S) (rank : S →+* ℕ)
+ (hmono : Monotone rank) : (-1 : A S) ∉ orderCone toA H := by
+ intro h
+ have hp : FractionPositive toA (toA (0:S) - toA (1:S)) := by
+ simpa only [map_zero, map_one, zero_sub, mem_orderCone] using h
+ obtain ⟨c,hc,w,hw⟩ := clear_comparison H hp
+ have hr := hmono hw
+ have hrc := hmono (H.one_le hc)
+ simp only [mul_zero, zero_add, mul_one, map_add, map_one] at hr hrc
+ omega
+
+/-- All tensor fractions, including the two multipliers in the extreme-state
+argument, preserve the order cone. -/
+theorem orderCone_mul_of_fraction (H : OrderBounds S) {x y : A S}
+ (hx : x ∈ orderCone toA H) (t u : S) (hu : u ≠ 0) (hy : y * toA u = toA t) :
+ y*x ∈ orderCone toA H :=
+ fractionPositive_mul H hx t u hu hy
+
+theorem orderCone_mul_tensor (H : OrderBounds S) (s : S) {x : A S}
+ (hx : x ∈ orderCone toA H) : toA s * x ∈ orderCone toA H :=
+ orderCone_mul_of_fraction H hx s 1 one_ne_zero (by simp)
+
+theorem orderCone_mul_inv (H : OrderBounds S) (s : S) (hs : s ≠ 0) {x : A S}
+ (hx : x ∈ orderCone toA H) : fractionInverse s hs * x ∈ orderCone toA H :=
+ orderCone_mul_of_fraction H hx 1 s hs (by simpa using fraction_inverse_spec s hs)
+
+end
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralLocalizationCone.lean b/lean/OAI/Computability/VPVNP/SpectralLocalizationCone.lean
new file mode 100644
index 0000000000..663f265d0b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralLocalizationCone.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.SpectralLocalizationRational
+import Mathlib.Geometry.Convex.Cone.Pointed
+import Mathlib.Tactic
+
+/-!
+# The rational cone used for strict spectral comparison
+
+Appendix A.1 writes a positive element as a sum of differences over nonzero
+tensor denominators. Addition can be done over a common tensor denominator,
+so a single ordered difference suffices. The witnesses are kept in the
+original semiring so they can later be used to recover a restriction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+/-- The order properties of restriction that enter the localization argument. -/
+structure OrderBounds (S : Type*) [CommSemiring S] [Preorder S] : Prop where
+ zero_le (a : S) : 0 ≤ a
+ one_le {s : S} (hs : s ≠ 0) : 1 ≤ s
+ bounded (a : S) : ∃ n : ℕ, a ≤ (n : S)
+ add_mono {a b c d : S} : a ≤ b → c ≤ d → a + c ≤ b + d
+ mul_mono (t : S) {a b : S} : a ≤ b → t * a ≤ t * b
+
+variable {S A : Type*} [CommSemiring S] [Preorder S] [CommRing A]
+
+/-- An ordered difference with a common nonzero denominator. -/
+def FractionPositive (f : S →+* A) (x : A) : Prop :=
+ ∃ a b s : S, b ≤ a ∧ s ≠ 0 ∧ x * f s = f a - f b
+
+/-- Addition collects the two denominators and retains the numerator comparison. -/
+theorem fractionPositive_add [NoZeroDivisors S] {f : S →+* A} (H : OrderBounds S) {x y : A}
+ (hx : FractionPositive f x) (hy : FractionPositive f y) :
+ FractionPositive f (x + y) := by
+ obtain ⟨a,b,s,hab,hs,hx⟩ := hx
+ obtain ⟨c,d,t,hcd,ht,hy⟩ := hy
+ refine ⟨t*a+s*c, t*b+s*d, s*t, H.add_mono (H.mul_mono t hab) (H.mul_mono s hcd),
+ mul_ne_zero hs ht, ?_⟩
+ simp only [map_mul, map_add]
+ linear_combination f t * hx + f s * hy
+
+/-- Multiplication by a tensor fraction preserves the cone. -/
+theorem fractionPositive_mul [NoZeroDivisors S] {f : S →+* A} (H : OrderBounds S) {x y : A}
+ (hx : FractionPositive f x) (t u : S) (hu : u ≠ 0) (hy : y * f u = f t) :
+ FractionPositive f (y * x) := by
+ obtain ⟨a,b,s,hab,hs,hx⟩ := hx
+ refine ⟨t*a, t*b, s*u, H.mul_mono t hab, mul_ne_zero hs hu, ?_⟩
+ simp only [map_mul]
+ calc
+ _ = (y * f u) * (x * f s) := by ring
+ _ = _ := by rw [hy, hx, mul_sub]
+
+theorem fractionPositive_difference [Nontrivial S] {f : S →+* A} {a b : S} (hab : b ≤ a) :
+ FractionPositive f (f a - f b) :=
+ ⟨a, b, 1, hab, one_ne_zero, by simp⟩
+
+theorem fractionPositive_one [Nontrivial S] (f : S →+* A) (H : OrderBounds S) :
+ FractionPositive f 1 := by
+ simpa using fractionPositive_difference (f := f) (H.zero_le 1)
+
+theorem fractionPositive_bound (f : S →+* A) (H : OrderBounds S) (x : A)
+ (hx : ∃ a b s : S, s ≠ 0 ∧ x * f s = f a - f b) :
+ ∃ n : ℕ, FractionPositive f (n • (1 : A) + x) := by
+ obtain ⟨a,b,s,hs,hx⟩ := hx
+ obtain ⟨n,hn⟩ := H.bounded b
+ have hn' : (n : S) ≤ (n : S)*s := by simpa using H.mul_mono (n : S) (H.one_le hs)
+ refine ⟨n, (n : S)*s+a, b, s, ?_, hs, ?_⟩
+ · exact (hn.trans hn').trans (by simpa using H.add_mono (le_refl ((n:S)*s)) (H.zero_le a))
+ · simp only [nsmul_eq_mul, mul_one, map_add, map_mul, map_natCast, add_mul, hx]
+ ring
+
+variable [Nontrivial S] [NoZeroDivisors S] [CharZero S] [Algebra ℚ A]
+
+/-- The order cone in the rational algebra. Positive rational multiples use
+the positive denominator of the scalar and its nonnegative integer numerator. -/
+def orderCone (f : S →+* A) (H : OrderBounds S) : PointedCone ℚ A where
+ carrier := FractionPositive f
+ zero_mem' := by
+ change FractionPositive f 0
+ simpa using fractionPositive_difference (f := f) (le_refl (0 : S))
+ add_mem' := fractionPositive_add H
+ smul_mem' q x hx := by
+ obtain ⟨a,b,s,hab,hs,hx⟩ := hx
+ let k := q.val.num.toNat
+ have hden : (q.val.den : S) ≠ 0 := Nat.cast_ne_zero.mpr q.val.den_nz
+ have hrat := den_mul_algebraMap_eq_num_toNat A q.val q.property
+ refine ⟨(k:S)*a, (k:S)*b, (q.val.den:S)*s, H.mul_mono _ hab, mul_ne_zero hden hs, ?_⟩
+ change (q.val • x) * _ = _
+ simp only [Algebra.smul_def, map_mul, map_natCast]
+ calc
+ _ = ((q.val.den : A) * algebraMap ℚ A q.val) * (x * f s) := by ring
+ _ = _ := by rw [hrat, hx, mul_sub]
+
+@[simp] theorem mem_orderCone (f : S →+* A) (H : OrderBounds S) (x : A) :
+ x ∈ orderCone f H ↔ FractionPositive f x := Iff.rfl
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralLocalizationRational.lean b/lean/OAI/Computability/VPVNP/SpectralLocalizationRational.lean
new file mode 100644
index 0000000000..0c748dbf9c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralLocalizationRational.lean
@@ -0,0 +1,45 @@
+import Mathlib.RingTheory.Localization.FractionRing
+
+/-!
+# Rational scalars in the localization of a spectral semiring
+
+In characteristic zero the images of the positive natural numbers become
+units when we invert the nonzero elements of the semiring. This supplies the
+rational scalar action used in the algebraic separation argument. Clearing
+denominators then writes each nonnegative rational as a ratio of naturals.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+/-- A commutative ring in which positive natural numbers are units is a
+rational algebra by the universal property of the localization of `ℤ`. -/
+@[instance_reducible]
+noncomputable def ratAlgebraOfUnits (A : Type*) [CommRing A]
+ (hunit : ∀ n : ℕ, n ≠ 0 → IsUnit (n : A)) : Algebra ℚ A := by
+ refine (IsLocalization.lift (S := ℚ) (M := Submonoid.pos ℤ)
+ (g := Int.castRingHom A) ?_).toAlgebra
+ intro x
+ have hx : 0 < x.val := x.property
+ have hnat := hunit x.val.toNat (by omega)
+ change IsUnit (x.val : A)
+ rwa [← Int.cast_natCast, Int.toNat_of_nonneg hx.le] at hnat
+
+/-- Clearing the positive denominator of a nonnegative rational in any
+rational algebra gives its natural numerator. -/
+theorem den_mul_algebraMap_eq_num_toNat (A : Type*) [CommRing A] [Algebra ℚ A]
+ (q : ℚ) (hq : 0 ≤ q) :
+ (q.den : A) * algebraMap ℚ A q = (q.num.toNat : A) := by
+ have h := congrArg (algebraMap ℚ A) (Rat.den_mul_eq_num q)
+ simp only [map_mul, map_natCast, map_intCast] at h
+ rw [← Int.cast_natCast q.num.toNat, Int.toNat_of_nonneg (Rat.num_nonneg.mpr hq)]
+ exact h
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralLocalizationRing.lean b/lean/OAI/Computability/VPVNP/SpectralLocalizationRing.lean
new file mode 100644
index 0000000000..f6bc5c34bc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralLocalizationRing.lean
@@ -0,0 +1,107 @@
+import Mathlib.Algebra.Ring.Basic
+import Mathlib.Basic.Countable.Basic
+import Mathlib.GroupTheory.MonoidLocalization.GrothendieckGroup
+import Mathlib.Tactic.Abel
+
+/-!
+# Additive group completion for the spectral localization
+
+We pass from a commutative semiring to a ring by forming formal differences.
+Multiplication extends by additivity in each variable, even when addition in
+the original semiring is noncancellative.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+noncomputable section
+
+/-- The additive Grothendieck group of a semiring, equipped below with the induced ring structure. -/
+def G (S : Type*) [CommSemiring S] := Algebra.GrothendieckAddGroup S
+deriving AddCommGroup
+
+variable {S : Type*} [CommSemiring S]
+
+private abbrev incl : S →+ G S := Algebra.GrothendieckAddGroup.of
+
+private theorem exists_sub_incl (z : G S) : ∃ a b : S, z = incl a - incl b := by
+ obtain ⟨⟨a, b⟩, h⟩ := (AddLocalization.addMonoidOf (⊤ : AddSubmonoid S)).surj z
+ exact ⟨a, b, eq_sub_iff_add_eq.mpr h⟩
+
+private def lift {A : Type*} [AddCommGroup A] (f : S →+ A) : G S →+ A :=
+ Algebra.GrothendieckAddGroup.lift f
+
+private theorem lift_incl {A : Type*} [AddCommGroup A] (f : S →+ A) (x : S) :
+ lift f (incl x) = f x :=
+ DFunLike.congr_fun (Algebra.GrothendieckAddGroup.lift.symm_apply_apply f) x
+
+private def product : G S →+ G S →+ G S :=
+ lift (lift ((AddMonoidHom.mul : S →+ S →+ S).compr₂ incl)).flip
+
+private theorem product_incl (a b : S) : product (incl a) (incl b) = incl (a * b) := by
+ unfold product
+ rw [lift_incl]
+ change lift ((AddMonoidHom.mul : S →+ S →+ S).compr₂ incl) (incl b) a = _
+ rw [lift_incl]
+ exact congrArg incl (mul_comm b a)
+
+instance : CommRing (G S) where
+ __ := (inferInstance : AddCommGroup (G S))
+ mul := fun a b => product a b
+ one := incl 1
+ zero_mul a := DFunLike.congr_fun (map_zero product) a
+ mul_zero a := map_zero (product a)
+ left_distrib a b c := map_add (product a) b c
+ right_distrib a b c := DFunLike.congr_fun (map_add product a b) c
+ one_mul x := by
+ change product (incl (1 : S)) x = x
+ obtain ⟨a, b, rfl⟩ := exists_sub_incl x
+ simp only [map_sub, product_incl, one_mul]
+ mul_one x := by
+ change product x (incl (1 : S)) = x
+ obtain ⟨a, b, rfl⟩ := exists_sub_incl x
+ simp only [map_sub, AddMonoidHom.sub_apply, product_incl, mul_one]
+ mul_comm x y := by
+ change product x y = product y x
+ obtain ⟨a, b, rfl⟩ := exists_sub_incl x
+ obtain ⟨c, d, rfl⟩ := exists_sub_incl y
+ simp only [map_sub, AddMonoidHom.sub_apply, product_incl, mul_comm a, mul_comm b]
+ abel
+ mul_assoc x y z := by
+ change product (product x y) z = product x (product y z)
+ obtain ⟨a, b, rfl⟩ := exists_sub_incl x
+ obtain ⟨c, d, rfl⟩ := exists_sub_incl y
+ obtain ⟨e, f, rfl⟩ := exists_sub_incl z
+ simp only [map_sub, AddMonoidHom.sub_apply, product_incl, mul_assoc]
+
+/-- The canonical semiring homomorphism to the ring of differences. -/
+def toG : S →+* G S where
+ __ := incl
+ map_one' := rfl
+ map_mul' a b := (product_incl a b).symm
+
+/-- Two generators agree exactly when adding a common semiring element makes them equal. -/
+theorem toG_eq_iff (a b : S) : toG a = toG b ↔ ∃ w : S, a + w = b + w := by
+ change AddLocalization.addMonoidOf ⊤ a = AddLocalization.addMonoidOf ⊤ b ↔ _
+ rw [AddSubmonoid.LocalizationMap.eq_iff_exists]
+ simp [add_comm a, add_comm b]
+
+/-- Every element of the completion is a difference of two generators. -/
+theorem exists_sub (z : G S) : ∃ a b : S, z = toG a - toG b := exists_sub_incl z
+
+instance [Countable S] : Countable (G S) := by
+ apply Function.Surjective.countable (f := fun p : S × S => toG p.1 - toG p.2)
+ intro z
+ obtain ⟨a, b, h⟩ := exists_sub z
+ exact ⟨(a, b), h.symm⟩
+
+end
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralMatching.lean b/lean/OAI/Computability/VPVNP/SpectralMatching.lean
new file mode 100644
index 0000000000..424cc6c324
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralMatching.lean
@@ -0,0 +1,142 @@
+import OAI.Computability.VPVNP.ExtensionAmplification
+import OAI.Computability.VPVNP.SpectralStrictComparison
+import OAI.Computability.VPVNP.SpectralPolynomialBound
+import OAI.Computability.VPVNP.StarGrowth
+import Mathlib.Algebra.MvPolynomial.Eval
+
+/-!
+# Matching the prescribed generator values in an exact extension
+
+Section 2.3 uses a compactness argument to test a finite list of generators.
+If every spectral point misses a target, one polynomial supply dominates the
+balanced monomial at every spectral point. Its contraction bound contradicts
+the exponential growth of contractions of that monomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+open Filter Topology
+
+variable {S ι : Type*} [CommSemiring S] [Preorder S]
+
+/-- A comparison between all powers bounds their contracted growth. The supply
+is evaluated as a polynomial in the chosen generators, so its monomial bounds
+apply even to covectors acting jointly on all factors. -/
+theorem contraction_budget_of_power_comparison
+ (G : ι → S) (target : ι → ℝ) (Φ : S → ℝ)
+ (hmono : Monotone Φ) (hnonneg : ∀ x, 0 ≤ Φ x)
+ (hcopies : ∀ (n : ℕ) x, Φ ((n : S) * x) = (n : ℝ) * Φ x)
+ (hpoly : ∀ P : MvPolynomial ι ℕ,
+ Φ (P.eval₂ (Nat.castRingHom S) G) ≤ P.eval₂ (Nat.castRingHom ℝ) target)
+ (M : S) (f : ℝ) (L K : ℕ) (hK : 0 < K) (P : MvPolynomial ι ℕ)
+ (hlim : Tendsto (fun m : ℕ => (Φ (M ^ m)) ^ (m : ℝ)⁻¹) atTop (𝓝 f))
+ (hcompare : ∀ m : ℕ, ((L : S) * M) ^ m ≤ (K : S) * (P.eval₂ (Nat.castRingHom S) G) ^ m) :
+ (L : ℝ) * f ≤ P.eval₂ (Nat.castRingHom ℝ) target := by
+ have hbudget : 0 ≤ P.eval₂ (Nat.castRingHom ℝ) target :=
+ (hnonneg _).trans (hpoly P)
+ apply limit_le_of_half_power_bound (Nat.cast_nonneg L) hbudget
+ (Nat.cast_pos.mpr hK) (Filter.Eventually.of_forall fun m => hnonneg (M ^ m)) hlim
+ apply Filter.Frequently.of_forall
+ intro m
+ have hp : Φ (P.eval₂ (Nat.castRingHom S) G ^ m) ≤ P.eval₂ (Nat.castRingHom ℝ) target ^ m := by
+ simpa only [MvPolynomial.eval₂_pow] using hpoly (P ^ m)
+ have h := hmono (hcompare m)
+ rw [mul_pow, ← Nat.cast_pow, hcopies, hcopies, Nat.cast_pow] at h
+ calc
+ (L : ℝ) ^ m * (Φ (M ^ m) / 2) ≤ (L : ℝ) ^ m * Φ (M ^ m) :=
+ mul_le_mul_of_nonneg_left (by linarith [hnonneg (M ^ m)]) (by positivity)
+ _ ≤ _ := h.trans (mul_le_mul_of_nonneg_left hp (Nat.cast_nonneg K))
+
+private noncomputable def variantSupply {ι : Type*} (s : Finset ι) [DecidableEq s] (e : ℕ) (c : s × Bool → ℕ) :
+ MvPolynomial ι ℕ :=
+ ∑ j, (c j : MvPolynomial ι ℕ) * ∏ i : s, MvPolynomial.X (i : ι) ^ amplificationExponent e j i
+
+private theorem eval_variantSupply {ι R : Type*} [CommSemiring R] (g : ι → R)
+ (s : Finset ι) [DecidableEq s] (e : ℕ) (c : s × Bool → ℕ) :
+ (variantSupply s e c).eval₂ (Nat.castRingHom R) g =
+ ∑ j, (c j : R) * ∏ i : s, g i ^ amplificationExponent e j i := by
+ simp [variantSupply]
+
+variable [NoZeroDivisors S] [Nontrivial S] [CharZero S]
+
+/-- Finite-generator matching in the proof of Theorem 2.4. A contraction
+functional bounds all monomials by their target products. If the bound is
+asymptotically attained on each balanced reference monomial, some spectral
+point realizes every generator target simultaneously. -/
+theorem exists_matching_spectral_point
+ (H : OrderBounds S) (rank : S →+* ℕ) (hrank : Monotone rank)
+ (G : ι → S) (hG : ∀ i, G i ≠ 0) (target : ι → ℝ) (ht : ∀ i, 0 < target i)
+ (required : Finset ι) (hreq : required.Nonempty) (Φ : S → ℝ)
+ (hmono : Monotone Φ) (hnonneg : ∀ x, 0 ≤ Φ x)
+ (hadd : ∀ a b, Φ (a + b) ≤ Φ a + Φ b)
+ (hcopies : ∀ (n : ℕ) x, Φ ((n : S) * x) = (n : ℝ) * Φ x)
+ (hmonomial : ∀ d : ι →₀ ℕ, Φ (d.prod fun i n => G i ^ n) ≤ d.prod fun i n => target i ^ n)
+ (hbalanced : ∀ s : Finset ι, required ⊆ s → ∀ e : ℕ, 0 < e →
+ Tendsto (fun m : ℕ => Φ ((∏ i : s, G i ^ e) ^ m) ^ (m : ℝ)⁻¹)
+ atTop (𝓝 (∏ i : s, target i ^ e))) :
+ ∃ F : S →+* ℝ, Monotone F ∧ ∀ i, F (G i) = target i := by
+ classical
+ by_contra hnone
+ have miss : ∀ f ∈ spectrumValues S, ∃ i, f (G i) ≠ target i := by
+ rintro _ ⟨F, hF, rfl⟩
+ by_contra! h
+ exact hnone ⟨F, hF, h⟩
+ have hpos (F : S →+* ℝ) (hF : Monotone F) (i : ι) : 0 < F (G i) := by
+ have h := hF (H.one_le (hG i))
+ rw [map_one] at h
+ exact zero_lt_one.trans_le h
+ obtain ⟨s, hs, δ, hδ, hgap⟩ := compact_finite_generator_gap (spectrumValues_isCompact H)
+ (fun i f => f (G i)) target (fun i => continuous_apply (G i)) ht
+ (fun _ ⟨F, hF, eq⟩ i => eq ▸ hpos F hF i) miss required
+ let : Nonempty s := (hreq.mono hs).coe_sort
+ let Ω := { F : S →+* ℝ // Monotone F }
+ let v (F : Ω) (i : s) : ℝ := F.val (G i)
+ have hgap' (F : Ω) : ∃ i : s, 1 + δ ≤ v F i / target i ∨ 1 + δ ≤ target i / v F i := by
+ obtain ⟨i, hi, h⟩ := hgap F.val ⟨F.val, F.property, rfl⟩
+ exact ⟨⟨i, hi⟩, h⟩
+ obtain ⟨e, L, c, he, hL, _, hdom, hbudget⟩ :=
+ finiteProfileAmplification (H := Ω) (fun i : s => target i) v (fun i => ht i) (fun (F : Ω) i => hpos F.val F.property i)
+ δ hδ hgap'
+ let M : S := ∏ i : s, G i ^ e
+ let P := variantSupply s e c
+ let Y := P.eval₂ (Nat.castRingHom S) G
+ have hyStrict (F : S →+* ℝ) (hF : Monotone F) : F ((L : S) * M) < F Y := by
+ obtain ⟨j, hj⟩ := hdom (⟨F, hF⟩ : Ω)
+ have hterm (l : s × Bool) :
+ 0 ≤ (c l : ℝ) * ∏ i : s, F (G i) ^ amplificationExponent e l i :=
+ mul_nonneg (Nat.cast_nonneg _) (Finset.prod_nonneg fun i _ => pow_nonneg (hpos F hF i).le _)
+ have hle := Finset.single_le_sum (fun l _ => hterm l) (Finset.mem_univ j)
+ simpa only [M, Y, P, eval_variantSupply, map_sum, map_prod, map_mul, map_natCast, map_pow, v]
+ using hj.trans_le hle
+ have hY : Y ≠ 0 := by
+ intro hz
+ let R := (Nat.castRingHom ℝ).comp rank
+ have hm : Monotone R := by
+ intro a b hab
+ change (rank a : ℝ) ≤ (rank b : ℝ)
+ exact_mod_cast hrank hab
+ have hy := hyStrict R hm
+ rw [hz, map_zero] at hy
+ have hzero := hm (H.zero_le ((L : S) * M))
+ rw [map_zero] at hzero
+ exact hy.not_ge hzero
+ obtain ⟨K, hK, hrestrict⟩ := strict_spectral_comparison H rank hrank hY hyStrict
+ have hpoly (p : MvPolynomial ι ℕ) : Φ (p.eval₂ (Nat.castRingHom S) G) ≤ p.eval₂ (Nat.castRingHom ℝ) target :=
+ polynomial_target_bound Φ G target hadd (fun n a => (hcopies n a).le) hmonomial p
+ have h := contraction_budget_of_power_comparison G target Φ hmono hnonneg hcopies hpoly
+ M (∏ i : s, target i ^ e) L K hK P (hbalanced s hs e he) hrestrict
+ rw [show P = variantSupply s e c by rfl, eval_variantSupply] at h
+ have hM : 0 < (∏ i : s, target i ^ e) :=
+ Finset.prod_pos fun i _ => pow_pos (ht i) _
+ have hLp : 0 < (L : ℝ) := Nat.cast_pos.mpr hL
+ linarith [mul_pos hLp hM]
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralMidpointToCAT.lean b/lean/OAI/Computability/VPVNP/SpectralMidpointToCAT.lean
new file mode 100644
index 0000000000..96b5b23a4f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralMidpointToCAT.lean
@@ -0,0 +1,83 @@
+import OAI.Computability.VPVNP.Barycenter
+import OAI.Computability.VPVNP.FractionalGeodesic
+import OAI.Computability.VPVNP.WireGeodesic
+import Mathlib.Topology.Order.Compact
+
+/-!
+# From midpoint comparison to CAT(0) comparison
+
+Section 4.1 passes from (4.1) to the full geodesic inequality (4.2). Along a
+constant-speed segment, subtracting the comparison quadratic from the squared
+distance gives a continuous midpoint-convex function that vanishes at both
+ends. At a maximum, express its parameter as the midpoint of an interval with
+one end at a boundary point. The maximum is then at most half itself.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open scoped unitInterval
+open VPVNP.SpectralGeometry
+
+/-- A continuous midpoint-convex function vanishing at both ends of the unit interval is
+nonpositive on the whole interval. -/
+private theorem nonpos_of_midpoint_convex {f : I → ℝ} (hf : Continuous f)
+ (h₀ : f 0 = 0) (h₁ : f 1 = 0)
+ (hm : ∀ s m t : I, (m : ℝ) = ((s : ℝ) + t)/2 → 2 * f m ≤ f s + f t) :
+ ∀ t, f t ≤ 0 := by
+ obtain ⟨m, _, hmMax⟩ := isCompact_univ.exists_isMaxOn Set.univ_nonempty hf.continuousOn
+ have hmax := isMaxOn_univ_iff.mp hmMax
+ have hnonpos : f m ≤ 0 := by
+ by_cases h : (m : ℝ) ≤ 1/2
+ · let r : I := ⟨2 * (m : ℝ), mul_nonneg (by norm_num) m.property.1, by linarith⟩
+ have hr := hm 0 m r (by change (m : ℝ) = (0 + 2*(m:ℝ))/2; ring)
+ linarith only [hr, h₀, hmax r]
+ · let l : I := ⟨2*(m:ℝ)-1, by linarith, by linarith [m.property.2]⟩
+ have hl := hm l m 1 (by change (m : ℝ) = (2*(m:ℝ)-1+1)/2; ring)
+ linarith only [hl, h₁, hmax l]
+ exact fun t ↦ (hmax t).trans hnonpos
+
+variable {X : Type*} [MetricSpace X]
+
+/-- The squared midpoint comparison (4.1) implies the full CAT(0) inequality (4.2). -/
+theorem hasCATZeroSegments_of_midpoint (hf : HasFractions X) (hT : FractionTransport X)
+ (hm : ∀ x y z m : X, AtFraction x y (1/2) m →
+ 2 * dist z m ^ 2 + (1/2 : ℝ) * dist x y ^ 2 ≤ dist z x ^ 2 + dist z y ^ 2) :
+ HasCATZeroSegments X := by
+ intro a b t ht ht'
+ have hfrac (x y : X) (s : I) : ∃! w, AtFraction x y (s : ℝ) w := by
+ obtain ⟨w, hw⟩ := hf x y s s.property.1 s.property.2
+ exact ⟨w, hw, fun u hu ↦ atFraction_unique hT s.property.1 s.property.2 hu hw⟩
+ obtain ⟨g, hg₀, hg₁, hg⟩ := exists_constantSpeedSegment hfrac a b
+ let u : I := ⟨t, ht, ht'⟩
+ refine ⟨g u, fun z ↦ ?_⟩
+ let f (s : I) := dist z (g s)^2 - ((1-(s:ℝ)) * dist z a^2 + s * dist z b^2 -
+ s * (1-s) * dist a b^2)
+ have hcg := continuous_of_constantSpeed a b hg
+ have hcf : Continuous f := by dsimp [f]; fun_prop
+ have h₀ : f 0 = 0 := by simp [f, hg₀]
+ have h₁ : f 1 = 0 := by simp [f, hg₁]
+ apply sub_nonpos.mp (nonpos_of_midpoint_convex hcf h₀ h₁ ?_ u)
+ intro s m v hmid
+ have hgm : AtFraction (g s) (g v) (1/2) (g m) := by
+ constructor
+ · rw [hg, hg, hmid, show (s:ℝ) - ((s:ℝ)+v)/2 = (1/2)*((s:ℝ)-v) by ring,
+ abs_mul, abs_of_nonneg (by norm_num : (0:ℝ) ≤ 1/2)]
+ ring
+ · rw [hg, hg, hmid, show ((s:ℝ)+v)/2 - v = (1/2)*((s:ℝ)-v) by ring,
+ abs_mul, abs_of_nonneg (by norm_num : (0:ℝ) ≤ 1/2)]
+ ring
+ have h := hm _ _ z _ hgm
+ rw [hg, mul_pow, sq_abs] at h
+ dsimp only [f]
+ rw [hmid]
+ linarith only [h]
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralMidpointTower.lean b/lean/OAI/Computability/VPVNP/SpectralMidpointTower.lean
new file mode 100644
index 0000000000..797ad8e21b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralMidpointTower.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.SplitWireExtension
+import OAI.Computability.VPVNP.WireGeodesic
+import OAI.Computability.VPVNP.MidpointUnion
+import Mathlib.Data.Nat.Pairing
+import Mathlib.Logic.Equiv.List
+
+/-!
+# The countable union of finite spectral midpoint extensions
+
+For Corollary 2.5, retain the original parties and index the new parties by
+their creation times. A pair is scheduled at arbitrarily late stages, so a
+stage at which both parties already exist adds their midpoint. Old distances
+are preserved at every subsequent stage. Every finite list therefore has
+its full distance matrix in one finite spectrum.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+universe u
+
+private def TowerStage (J : Type) : ℕ → Type
+ | 0 => J
+ | n + 1 => Option (TowerStage J n)
+
+@[instance_reducible] private def stageFintype {J : Type} [Fintype J] : (n : ℕ) → Fintype (TowerStage J n)
+ | 0 => inferInstanceAs (Fintype J)
+ | n + 1 => @instFintypeOption _ (stageFintype n)
+
+private theorem stageNontrivial {J : Type} [Nontrivial J] : (n : ℕ) → Nontrivial (TowerStage J n)
+ | 0 => inferInstanceAs (Nontrivial J)
+ | n + 1 => by
+ let : Nontrivial (TowerStage J n) := stageNontrivial n
+ exact inferInstanceAs (Nontrivial (Option (TowerStage J n)))
+
+attribute [local instance] stageFintype stageNontrivial
+
+variable {J : Type}
+
+/-- A party named by its creation time first exists at the next stage. -/
+private def birth : J ⊕ ℕ → ℕ
+ | .inl _ => 0
+ | .inr m => m + 1
+
+open scoped Classical in
+private noncomputable def representative [Inhabited J] : (n : ℕ) → J ⊕ ℕ → TowerStage J n
+ | 0, x => x.elim (fun j : J ↦ j) (fun _ ↦ (default : J))
+ | n + 1, x => if x = Sum.inr n then none else some (representative n x)
+
+private theorem representative_old [Inhabited J] {x : J ⊕ ℕ} {n : ℕ} (hx : birth x ≤ n) :
+ representative (n + 1) x = some (representative n x) := by
+ have hne : x ≠ Sum.inr n := by rintro rfl; simp [birth] at hx
+ simp [representative, hne]
+ rfl
+
+private theorem representative_new [Inhabited J] (n : ℕ) :
+ representative (J := J) (n + 1) (.inr n) = none := by
+ simp [representative]
+ rfl
+
+/-- The left unpairing coordinate encodes the pair and the right coordinate
+can be chosen arbitrarily large. -/
+private def scheduled [Encodable J] [Inhabited J] (n : ℕ) : (J ⊕ ℕ) × (J ⊕ ℕ) :=
+ (Encodable.decode (α := (J ⊕ ℕ) × (J ⊕ ℕ)) n.unpair.1).getD (.inl default, .inl default)
+
+private theorem scheduled_late [Encodable J] [Inhabited J] (x y : J ⊕ ℕ) :
+ ∃ n, birth x ≤ n ∧ birth y ≤ n ∧ scheduled n = (x, y) := by
+ let m := max (birth x) (birth y)
+ let n := Nat.pair (Encodable.encode (x,y)) m
+ exact ⟨n, (le_max_left _ _).trans (Nat.right_le_pair _ m),
+ (le_max_right _ _).trans (Nat.right_le_pair _ m), by simp [scheduled, n]⟩
+
+variable {k : Type u} [Field k] [Fintype J] [Inhabited J] [Encodable J]
+
+private noncomputable def extendAt {A : Type} [Fintype A] (G : SpectralPoint k A) (a b : A) :
+ SpectralPoint k (Option A) :=
+ (G.exists_split_extension a b (div_nonneg (G.wireDistance_nonneg _ _) (by norm_num))
+ (div_nonneg (G.wireDistance_nonneg _ _) (by norm_num)) (add_halves _)).choose
+
+private theorem extendAt_spec {A : Type} [Fintype A] (G : SpectralPoint k A) (a b : A) :
+ (∀ T, (extendAt G a b).value (embedOld T) = G.value T) ∧
+ (extendAt G a b).wireDistance (some a) none = G.wireDistance a b / 2 ∧
+ (extendAt G a b).wireDistance none (some b) = G.wireDistance a b / 2 :=
+ (G.exists_split_extension a b (div_nonneg (G.wireDistance_nonneg _ _) (by norm_num))
+ (div_nonneg (G.wireDistance_nonneg _ _) (by norm_num)) (add_halves _)).choose_spec
+
+private noncomputable def stagePoint (F : SpectralPoint k J) :
+ (n : ℕ) → SpectralPoint k (TowerStage J n)
+ | 0 => F
+ | n + 1 => extendAt (stagePoint F n) (representative n (scheduled n).1) (representative n (scheduled n).2)
+
+private noncomputable def stageDist (F : SpectralPoint k J) (n : ℕ) (x y : J ⊕ ℕ) : ℝ :=
+ (stagePoint F n).wireDistance (representative n x) (representative n y)
+
+private theorem stageDist_stable (F : SpectralPoint k J) (n : ℕ) (x y : J ⊕ ℕ)
+ (hx : birth x ≤ n) (hy : birth y ≤ n) : stageDist F (n+1) x y = stageDist F n x y := by
+ simp only [stageDist, representative_old hx, representative_old hy]
+ exact (stagePoint F n).wireDistance_extension _ (extendAt_spec _ _ _).1 _ _
+
+private theorem stage_midpoint (F : SpectralPoint k J) (x y : J ⊕ ℕ) :
+ ∃ n, birth x ≤ n ∧ birth y ≤ n ∧
+ stageDist F (n+1) x (.inr n) = stageDist F n x y / 2 ∧
+ stageDist F (n+1) (.inr n) y = stageDist F n x y / 2 := by
+ obtain ⟨n, hx, hy, hpair⟩ := scheduled_late x y
+ refine ⟨n, hx, hy, ?_⟩
+ simp only [stageDist, representative_old hx, representative_old hy, representative_new, stagePoint, hpair]
+ exact (extendAt_spec _ _ _).2
+
+end WireTensor
+
+
+namespace WireTensor.SpectralPoint
+
+universe u
+
+attribute [local instance] stageFintype stageNontrivial
+
+open VPVNP.SpectralGeometry VPVNP.WireGeometry
+
+variable {k : Type u} [Field k] {J : Type} [Fintype J] [Nontrivial J]
+
+/-- The finite spectral pseudometric extends to a countable pseudometric
+space with a midpoint for each pair. Each finite configuration of the new
+space occurs, with scale one, in a finite spectral point. -/
+theorem exists_midpoint_tower (F : SpectralPoint k J) :
+ ∃ M : PseudoMetricSpace (J ⊕ ℕ),
+ (∀ a b : J, @dist (J ⊕ ℕ) M.toDist (.inl a) (.inl b) = F.wireDistance a b) ∧
+ @RealizableConfigurations k _ _ M ∧ ∀ a b, ∃ z, @AtFraction _ M a b (1 / 2) z := by
+ classical
+ let : Encodable J := Fintype.toEncodable J
+ let : Inhabited J := Classical.inhabited_of_nonempty inferInstance
+ let M := unionPseudoMetric birth (stageDist F) (stageDist_stable F)
+ (fun n _ ↦ (stagePoint F n).wireDistance_self _)
+ (fun n _ _ ↦ (stagePoint F n).wireDistance_comm _ _)
+ (fun n _ _ _ ↦ (stagePoint F n).wireDistance_triangle _ _ _)
+ refine ⟨M, fun _ _ ↦ rfl, ?_, ?_⟩
+ · intro m f
+ obtain ⟨n, _, hn⟩ := unionDist_finite_stage (stageDist_stable F) f
+ exact ⟨{ Parties := TowerStage J n, spectrum := stagePoint F n, scale := 1,
+ scale_pos := zero_lt_one, label := fun i ↦ representative n (f i),
+ distances := fun i j ↦ (hn i j).trans (one_mul _).symm }⟩
+ · intro x y
+ obtain ⟨n, hx, hy, hl, hr⟩ := stage_midpoint F x y
+ refine ⟨.inr n, ?_⟩
+ have hn : birth (J := J) (.inr n) ≤ n + 1 := le_rfl
+ change unionDist birth (stageDist F) x (.inr n) = (1 / 2) * unionDist birth (stageDist F) x y ∧
+ unionDist birth (stageDist F) (.inr n) y = (1 - 1 / 2) * unionDist birth (stageDist F) x y
+ rw [unionDist_eq_stage (stageDist_stable F) hx hy,
+ unionDist_eq_stage (stageDist_stable F) (Nat.le_succ_of_le hx) hn,
+ unionDist_eq_stage (stageDist_stable F) hn (Nat.le_succ_of_le hy), hl, hr]
+ constructor <;> ring
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralOppositeRays.lean b/lean/OAI/Computability/VPVNP/SpectralOppositeRays.lean
new file mode 100644
index 0000000000..58921e5e66
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralOppositeRays.lean
@@ -0,0 +1,89 @@
+import OAI.Computability.VPVNP.SpectralTangentRay
+
+/-! # Opposite rays in the spectral tangent space
+
+At a midpoint the rays toward the two original endpoints separate at twice
+the speed of either ray. Applying the triangle inequality to points arbitrarily
+far along those rays gives the quadratic comparison of Lemma 4.1.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open Set
+
+variable {X : Type*} [MetricSpace X] {x y o : X}
+
+/-- Equal-parameter points on the two halves of a segment have exactly the
+sum of their distances from the midpoint. -/
+theorem opposite_segment_distance (ho : AtFraction x y (1 / 2) o)
+ (a : RadialSegment o x) (b : RadialSegment o y) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) :
+ dist (a.path t) (b.path t) = 2 * t * dist o x := by
+ have hx := ho.1
+ rw [dist_comm x o] at hx
+ have hxy : dist x y = 2 * dist o x := by linarith only [hx]
+ have hy : dist o y = dist o x := by linarith only [ho.2, hx]
+ have hxa := a.speed 1 (by simp) t ht
+ have hby := b.speed t ht 1 (by simp)
+ have hao := a.speed t ht 0 (by simp)
+ have hob := b.speed 0 (by simp) t ht
+ rw [a.finish, abs_of_nonneg (sub_nonneg.mpr ht.2)] at hxa
+ rw [b.finish, hy, abs_of_nonpos (sub_nonpos.mpr ht.2)] at hby
+ rw [a.start, sub_zero, abs_of_nonneg ht.1] at hao
+ rw [b.start, hy, zero_sub, abs_neg, abs_of_nonneg ht.1] at hob
+ have hu := dist_triangle (a.path t) o (b.path t)
+ have hl := (dist_triangle x (a.path t) y).trans
+ (add_le_add (le_rfl (a := dist x (a.path t))) (dist_triangle (a.path t) (b.path t) y))
+ rw [hxa, hby, hxy] at hl
+ rw [hao, hob] at hu
+ linarith only [hl, hu]
+
+/-- Opposite directions at a midpoint attain the full separation speed. -/
+theorem radialSlope_opposite (ho : AtFraction x y (1 / 2) o)
+ (a : RadialSegment o x) (b : RadialSegment o y) : radialSlope a b = 2 * dist o x := by
+ have hratio (t : ℝ) (ht : t ∈ Ioc (0 : ℝ) 1) :
+ dist (a.path t) (b.path t) / t = 2 * dist o x := by
+ rw [opposite_segment_distance ho a b ⟨ht.1.le, ht.2⟩]
+ field_simp [ht.1.ne']
+ apply le_antisymm
+ · exact (radialSlope_le_ratio a b (t := 1) ⟨zero_lt_one, le_rfl⟩).trans_eq
+ (hratio 1 ⟨zero_lt_one, le_rfl⟩)
+ · apply le_csInf (image_nonempty.mpr (nonempty_Ioc.mpr zero_lt_one))
+ rintro _ ⟨t, ht, rfl⟩
+ exact (hratio t ht).ge
+
+/-- Opposite rays in the tangent space have linear separation at every
+nonnegative parameter, including parameters beyond the original endpoints. -/
+theorem tangentRay_opposite (hT : FractionTransport X) (ho : AtFraction x y (1 / 2) o)
+ (a : RadialSegment o x) (b : RadialSegment o y) {t : ℝ} (ht : 0 ≤ t) :
+ dist (tangentRay a t) (tangentRay b t) = 2 * t * dist o x := by
+ rw [tangentRay_cross hT a b ht, radialSlope_opposite ho a b]
+ ring
+
+/-- If the two distances to the opposite rays obey the Euclidean quadratic
+formula, the triangle inequality at arbitrarily large parameters bounds the
+sum of the two squared distances at unit parameter. -/
+theorem opposite_ray_quadratic_bound {A B α β : ℝ} (hA : 0 ≤ A) (a b : ℝ → ℝ)
+ (htri : ∀ t, 0 ≤ t → 2 * t * A ≤ a t + b t)
+ (ha : ∀ t, 0 ≤ t → a t ^ 2 = t ^ 2 * A ^ 2 + B ^ 2 + t * (α ^ 2 - A ^ 2 - B ^ 2))
+ (hb : ∀ t, 0 ≤ t → b t ^ 2 = t ^ 2 * A ^ 2 + B ^ 2 + t * (β ^ 2 - A ^ 2 - B ^ 2)) :
+ 2 * (A ^ 2 + B ^ 2) ≤ α ^ 2 + β ^ 2 := by
+ by_contra! h
+ let gap := 2 * (A ^ 2 + B ^ 2) - (α ^ 2 + β ^ 2)
+ have hgap : 0 < gap := sub_pos.mpr h
+ let t := (2 * B ^ 2 + 1) / gap
+ have ht : 0 ≤ t := div_nonneg (by positivity) hgap.le
+ have hmul : t * gap = 2 * B ^ 2 + 1 := div_mul_cancel₀ _ hgap.ne'
+ have hsq := (sq_le_sq₀ (mul_nonneg (mul_nonneg (by norm_num) ht) hA)
+ ((mul_nonneg (mul_nonneg (by norm_num) ht) hA).trans (htri t ht))).mpr (htri t ht)
+ dsimp only [gap] at hmul
+ nlinarith only [hsq, sq_nonneg (a t - b t), ha t ht, hb t ht, hmul]
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralPolynomialBound.lean b/lean/OAI/Computability/VPVNP/SpectralPolynomialBound.lean
new file mode 100644
index 0000000000..d0b6420dc7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralPolynomialBound.lean
@@ -0,0 +1,43 @@
+import Mathlib.Algebra.MvPolynomial.Eval
+import Mathlib.Basic.Real.Basic
+
+/-!
+# Contraction bounds for polynomials in tensor generators
+
+In Theorem 2.4 of *VP and VNP differ over every field*, a contraction of
+each monomial in the generators satisfies its own target bound. Expanding
+the direct sums and tensor powers on the right of the comparison gives a
+polynomial with natural coefficients. Subadditivity and the bound for
+copies extend the monomial estimates to this whole polynomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+/-- A subadditive function with a bound on copies respects the target
+bound for every natural-coefficient polynomial in the generators, provided
+it respects the bound on each coefficient-one monomial. -/
+theorem polynomial_target_bound {ι S : Type*} [CommSemiring S]
+ (Φ : S → ℝ) (G : ι → S) (target : ι → ℝ)
+ (hadd : ∀ x y, Φ (x + y) ≤ Φ x + Φ y)
+ (hcopies : ∀ (n : ℕ) (x : S), Φ ((n : S) * x) ≤ (n : ℝ) * Φ x)
+ (hmonomial : ∀ d : ι →₀ ℕ,
+ Φ (d.prod fun i k => G i ^ k) ≤ d.prod fun i k => target i ^ k)
+ (p : MvPolynomial ι ℕ) :
+ Φ (MvPolynomial.aeval G p) ≤ MvPolynomial.aeval target p := by
+ induction p using MvPolynomial.induction_on' with
+ | monomial d n =>
+ simp only [MvPolynomial.aeval_monomial]
+ exact (hcopies n _).trans (mul_le_mul_of_nonneg_left (hmonomial d) n.cast_nonneg)
+ | add p q hp hq =>
+ simp only [map_add]
+ exact (hadd _ _).trans (add_le_add hp hq)
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralRealizable.lean b/lean/OAI/Computability/VPVNP/SpectralRealizable.lean
new file mode 100644
index 0000000000..2750222145
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralRealizable.lean
@@ -0,0 +1,63 @@
+import OAI.Computability.VPVNP.WireSpectrum
+
+/-!
+# Finite configurations of spectral wire distances
+
+A configuration of labelled points is realized up to scale when the distances
+between labels are a single positive multiple of their distances in a spectral
+wire pseudometric. Several labels may designate the same tensor party.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+/-- The data realizing a matrix of distances by finitely many tensor parties.
+The ambient party set has at least two members, as in Section 2. -/
+structure WireRealization (k : Type*) [Field k] {ι : Type*} (d : ι → ι → ℝ) where
+ /-- Finite ambient party set, with at least two members, carrying the wire metric of the
+ realization. -/
+ Parties : Type
+ [finiteParties : Fintype Parties]
+ [nontrivialParties : Nontrivial Parties]
+ /-- Spectral point that assigns the wire distance between ambient tensor parties. -/
+ spectrum : SpectralPoint k Parties
+ /-- Party representing each label of the given configuration. Labels may share a party. -/
+ label : ι → Parties
+ /-- Positive factor multiplying the spectral wire distances to recover the given labelled
+ distances. -/
+ scale : ℝ
+ scale_pos : 0 < scale
+ distances : ∀ i j, d i j = scale * spectrum.wireDistance (label i) (label j)
+
+attribute [instance] WireRealization.finiteParties WireRealization.nontrivialParties
+
+/-- Realizability up to a common positive scale, in the sense of Section 2.2. -/
+def RealizableUpToScale (k : Type*) [Field k] {ι : Type*} (d : ι → ι → ℝ) : Prop :=
+ Nonempty (WireRealization k d)
+
+/-- Restrict or repeat any of the labels in a realized configuration. -/
+theorem RealizableUpToScale.relabel {k ι μ : Type*} [Field k] {d : ι → ι → ℝ}
+ (h : RealizableUpToScale k d) (f : μ → ι) :
+ RealizableUpToScale k (fun i j => d (f i) (f j)) := by
+ obtain ⟨w⟩ := h
+ exact ⟨{ Parties := w.Parties, spectrum := w.spectrum, label := w.label ∘ f,
+ scale := w.scale, scale_pos := w.scale_pos, distances := fun i j => w.distances _ _ }⟩
+
+/-- The choice of units for the distance matrix does not affect realizability. -/
+theorem RealizableUpToScale.smul {k ι : Type*} [Field k] {d : ι → ι → ℝ}
+ (h : RealizableUpToScale k d) {c : ℝ} (hc : 0 < c) :
+ RealizableUpToScale k (fun i j => c * d i j) := by
+ obtain ⟨w⟩ := h
+ refine ⟨{ Parties := w.Parties, spectrum := w.spectrum, label := w.label,
+ scale := c * w.scale, scale_pos := mul_pos hc w.scale_pos, distances := ?_ }⟩
+ intro i j
+ rw [w.distances, mul_assoc]
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralRelabel.lean b/lean/OAI/Computability/VPVNP/SpectralRelabel.lean
new file mode 100644
index 0000000000..8746eaba7b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralRelabel.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.WireSpectrum
+
+/-!
+# Relabeling the parties of a spectral point
+
+In Lemma 2.3 of *VP and VNP differ over every field*, the parties used by a
+fixed pattern of labels are identified across different realizations. A
+bijection of party sets transports all local restrictions and both tensor
+operations, so it gives a spectral point with the corresponding wire distances.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v v' w
+
+namespace WireTensor
+
+variable {k : Type u} {J : Type v} {R : Type v'}
+
+/-- Use a bijection to rename every party of a tensor. The finite local bases
+are the same bases, indexed by the new party names. -/
+def relabelTensor (e : J ≃ R) (T : Tensor.{u,v',w} k R) : Tensor.{u,v,w} k J where
+ Basis j := T.Basis (e j)
+ finiteBasis j := T.finiteBasis (e j)
+ coeff x := T.coeff (Equiv.piCongrLeft T.Basis e x)
+
+private theorem relabelTensor_coeff (e : J ≃ R) (T : Tensor.{u,v',w} k R)
+ (x : (r : R) → T.Basis r) :
+ (relabelTensor e T).coeff (fun j ↦ x (e j)) = T.coeff x :=
+ congrArg T.coeff ((Equiv.piCongrLeft T.Basis e).apply_symm_apply x)
+
+section
+variable [CommSemiring k] [Fintype J] [Fintype R]
+
+/-- Local contractions agree after reindexing the sum of basis assignments and
+the product of local matrix entries. -/
+private theorem applyLocal_relabel (e : J ≃ R) {B C : R → Type*} [∀ r, Fintype (B r)]
+ (L : ∀ r, C r → B r → k) (f : Array k B) (c : (r : R) → C r) :
+ applyLocal (B := fun j ↦ B (e j)) (C := fun j ↦ C (e j))
+ (fun j ↦ L (e j)) (fun b ↦ f (Equiv.piCongrLeft B e b)) (fun j ↦ c (e j)) =
+ applyLocal L f c := by
+ classical
+ unfold applyLocal
+ symm
+ apply Fintype.sum_equiv (Equiv.piCongrLeft B e).symm
+ intro b
+ simp only [Equiv.apply_symm_apply, Equiv.piCongrLeft_symm_apply]
+ exact congrArg (· * f b) (e.prod_comp (fun r ↦ L r (c r) (b r))).symm
+
+theorem Restricts.relabelTensor {T U : Tensor.{u,v',w} k R} (h : Restricts T U) (e : J ≃ R) :
+ Restricts (relabelTensor e T) (relabelTensor e U) := by
+ obtain ⟨L, hL⟩ := h
+ refine ⟨fun j ↦ L (e j), ?_⟩
+ funext x
+ obtain ⟨c, rfl⟩ := (Equiv.piCongrLeft U.Basis e).symm.surjective x
+ exact (applyLocal_relabel e L T.coeff c).trans ((congrFun hL c).trans (relabelTensor_coeff e U c).symm)
+
+private theorem relabelTensor_directSum (e : J ≃ R) (T U : Tensor.{u,v',w} k R) :
+ Restricts (relabelTensor e (directSum T U)) (directSum (relabelTensor e T) (relabelTensor e U)) ∧
+ Restricts (directSum (relabelTensor e T) (relabelTensor e U)) (relabelTensor e (directSum T U)) := by
+ classical
+ apply restricts_of_reindex (T := relabelTensor e (directSum T U))
+ (U := directSum (relabelTensor e T) (relabelTensor e U)) (fun _ ↦ Equiv.refl _)
+ intro x
+ obtain ⟨c, rfl⟩ := (Equiv.piCongrLeft (fun r ↦ T.Basis r ⊕ U.Basis r) e).symm.surjective x
+ have h₁ := applyLocal_relabel e (fun r (c : T.Basis r ⊕ U.Basis r) b ↦
+ if c = Sum.inl b then 1 else 0) T.coeff c
+ have h₂ := applyLocal_relabel e (fun r (c : T.Basis r ⊕ U.Basis r) b ↦
+ if c = Sum.inr b then 1 else 0) U.coeff c
+ exact (congrArg₂ (· + ·) h₁ h₂).trans (relabelTensor_coeff e (directSum T U) c).symm
+
+omit [Fintype R] in
+private theorem relabelTensor_tensorProduct (e : J ≃ R) (T U : Tensor.{u,v',w} k R) :
+ Restricts (relabelTensor e (tensorProduct T U)) (tensorProduct (relabelTensor e T) (relabelTensor e U)) ∧
+ Restricts (tensorProduct (relabelTensor e T) (relabelTensor e U)) (relabelTensor e (tensorProduct T U)) := by
+ apply restricts_of_reindex (T := relabelTensor e (tensorProduct T U))
+ (U := tensorProduct (relabelTensor e T) (relabelTensor e U)) (fun _ ↦ Equiv.refl _)
+ intro x
+ obtain ⟨c, rfl⟩ := (Equiv.piCongrLeft (fun r ↦ T.Basis r × U.Basis r) e).symm.surjective x
+ exact (congrArg₂ (· * ·) (relabelTensor_coeff e T (fun r ↦ (c r).1))
+ (relabelTensor_coeff e U (fun r ↦ (c r).2))).trans (relabelTensor_coeff e (tensorProduct T U) c).symm
+
+omit [Fintype R] in
+private theorem relabelTensor_wire (e : J ≃ R) (a b : J) (I : Type w) [Fintype I] :
+ Restricts (relabelTensor e (wire (k := k) (e a) (e b) I)) (wire a b I) ∧
+ Restricts (wire (k := k) a b I) (relabelTensor e (wire (e a) (e b) I)) := by
+ let q (j a : J) : (j = a → I) ≃ (e j = e a → I) :=
+ { toFun := fun f h ↦ f (e.injective h)
+ invFun := fun f h ↦ f (congrArg e h)
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ apply restricts_of_reindex (fun j ↦ (q j a).prodCongr (q j b))
+ intro x
+ let B (r : R) := (r = e a → I) × (r = e b → I)
+ let y (j : J) : B (e j) := (q j a (x j).1, q j b (x j).2)
+ classical
+ change (if (x a).1 rfl = (x b).2 rfl then (1 : k) else 0) =
+ if (Equiv.piCongrLeft B e y (e a)).1 rfl = (Equiv.piCongrLeft B e y (e b)).2 rfl then 1 else 0
+ rw [Equiv.piCongrLeft_apply_apply, Equiv.piCongrLeft_apply_apply]
+ rfl
+end
+
+namespace SpectralPoint
+variable [Field k] [Fintype J] [Fintype R]
+
+/-- Pull a spectral point back along a bijection of its party labels. -/
+noncomputable def relabel (F : SpectralPoint k J) (e : R ≃ J) : SpectralPoint k R where
+ value T := F.value (relabelTensor e.symm T)
+ monotone h := F.monotone (h.relabelTensor e.symm)
+ value_unit := F.value_unit
+ value_zero T h := F.value_zero _ (funext fun x ↦ congrFun h (Equiv.piCongrLeft T.Basis e.symm x))
+ value_directSum T U := (F.value_eq_of_mutual (relabelTensor_directSum e.symm T U)).trans
+ (F.value_directSum _ _)
+ value_tensorProduct T U := (F.value_eq_of_mutual (relabelTensor_tensorProduct e.symm T U)).trans
+ (F.value_tensorProduct _ _)
+
+/-- Wire distances follow the party labels under a bijection. -/
+theorem wireDistance_relabel (F : SpectralPoint k J) (e : R ≃ J) (a b : R) :
+ (F.relabel e).wireDistance a b = F.wireDistance (e a) (e b) := by
+ have h := relabelTensor_wire (k := k) e.symm (e a) (e b) (Fin 2)
+ simp only [Equiv.symm_apply_apply] at h
+ exact congrArg (fun v : NNReal ↦ Real.log v / Real.log 2) (F.value_eq_of_mutual h)
+
+end SpectralPoint
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralSectorDistance.lean b/lean/OAI/Computability/VPVNP/SpectralSectorDistance.lean
new file mode 100644
index 0000000000..062d7771f6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralSectorDistance.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.SpectralSectorMap
+import OAI.Computability.VPVNP.SpectralSectorSeminorm
+import OAI.Computability.VPVNP.SpectralSectorQuadratic
+
+/-!
+# Euclidean coordinates on a spectral sector
+
+The pullback seminorm from Section 4.1 has a quadratic square on the coordinate
+plane. Its three coefficients are determined by the two unit axis lengths and
+the length of the chord between their endpoints. The calculation includes
+boundary points and degenerate sectors.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open Set
+
+private theorem sectorDomain_interior {S : Set ℝ} (hS : Convex ℝ S) (h0 : 0 ∈ S) (h1 : 1 ∈ S) :
+ ((1/4, 1/4) : ℝ × ℝ) ∈ interior (sectorDomain S) := by
+ let U : Set (ℝ × ℝ) := {p | 0 < p.1 ∧ 0 < p.2 ∧ p.1 + p.2 < 1}
+ have hopen : IsOpen U :=
+ (isOpen_lt continuous_const continuous_fst).inter
+ ((isOpen_lt continuous_const continuous_snd).inter
+ (isOpen_lt (continuous_fst.add continuous_snd) continuous_const))
+ have hsub : U ⊆ sectorDomain S := by
+ intro p hp
+ have hr₀ : 0 ≤ p.1 + p.2 := add_nonneg hp.1.le hp.2.1.le
+ have hr₁ : p.1 + p.2 ≤ 1 := hp.2.2.le
+ refine ⟨hp.1.le, hp.2.1.le, ?_⟩
+ simpa only [smul_eq_mul, mul_zero, mul_one, zero_add] using
+ hS h0 h1 (sub_nonneg.mpr hr₁) hr₀ (show 1-(p.1+p.2)+(p.1+p.2)=1 by ring)
+ apply interior_maximal hsub hopen
+ change 0 < (1/4 : ℝ) ∧ 0 < (1/4 : ℝ) ∧ (1/4 : ℝ) + 1/4 < 1
+ norm_num
+
+private theorem dist_congr_zero {X : Type*} [PseudoMetricSpace X] {x y x' y' : X}
+ (hx : dist x x' = 0) (hy : dist y y' = 0) : dist x y = dist x' y' := by
+ rw [dist_comm x y, PseudoMetricSpace.dist_eq_of_dist_zero y hx, dist_comm y x',
+ PseudoMetricSpace.dist_eq_of_dist_zero x' hy]
+
+/-- The sector of two rays or segments with a linear equal-parameter distance
+has exactly the Euclidean squared distances determined by its three side lengths. -/
+theorem sectorPoint_dist_sq {X : Type*} [PseudoMetricSpace X]
+ (k : Type*) [Field k] (hf : HasFractions X) (hT : FractionTransport X)
+ (hX : RealizableConfigurations k X)
+ {a b : ℝ → X} {A B c : ℝ} {S : Set ℝ}
+ (hS : Convex ℝ S) (h0 : 0 ∈ S) (h1 : 1 ∈ S)
+ (ha : ∀ r ∈ S, ∀ s ∈ S, dist (a r) (a s) = A * |r-s|)
+ (hb : ∀ r ∈ S, ∀ s ∈ S, dist (b r) (b s) = B * |r-s|)
+ (hc : ∀ r ∈ S, dist (a r) (b r) = c * r)
+ {p q : ℝ × ℝ} (hp : p ∈ sectorDomain S) (hq : q ∈ sectorDomain S) :
+ dist (sectorPoint hf a b p) (sectorPoint hf a b q)^2 =
+ (p.1-q.1)^2*A^2 + (p.2-q.2)^2*B^2 + (p.1-q.1)*(p.2-q.2)*(A^2+B^2-c^2) := by
+ let H := sectorPoint hf a b
+ let D := sectorDomain S
+ have hbase := sectorDomain_interior hS h0 h1
+ obtain ⟨P, hP⟩ := exists_sector_seminorm (H := H) (sectorDomain_convex hS) hT
+ (fun {x y} hx hy {t} ht ht' => sectorPoint_atFraction hf hT hS ha hb hc hx hy ht ht') hbase
+ have hr (f : Fin 8 → ℝ × ℝ) (hf' : ∀ i, f i ∈ interior D) :
+ WireTensor.RealizableUpToScale k (fun i j => P (f i - f j)) := by
+ have hdist (i j : Fin 8) : dist (H (f i)) (H (f j)) = P (f i - f j) :=
+ (dist_comm _ _).trans (hP _ (interior_subset (hf' j)) _ (interior_subset (hf' i)))
+ simpa only [hdist] using hX 8 (fun i => H (f i))
+ obtain ⟨L, W, C, hquad⟩ :=
+ SpectralGeometry.sectorSeminorm_quadratic P isOpen_interior ⟨_, hbase⟩ hr
+ have hdist (s t : ℝ × ℝ) (hs : s ∈ D) (ht : t ∈ D) :
+ dist (H s) (H t)^2 = (s.1-t.1)^2*L + (s.2-t.2)^2*W + (s.1-t.1)*(s.2-t.2)*C := by
+ rw [dist_comm, hP t ht s hs, hquad]
+ rfl
+ have ho : (0, 0) ∈ D := ⟨le_rfl, le_rfl, by simpa using h0⟩
+ have he : (1, 0) ∈ D := ⟨zero_le_one, le_rfl, by simpa using h1⟩
+ have hg : (0, 1) ∈ D := ⟨le_rfl, zero_le_one, by simpa using h1⟩
+ obtain ⟨ho₁, ho₂⟩ := sectorPoint_boundary_distances hf a b hc ho
+ obtain ⟨he₁, _⟩ := sectorPoint_boundary_distances hf a b hc he
+ obtain ⟨_, hg₂⟩ := sectorPoint_boundary_distances hf a b hc hg
+ have o₁ : dist (H (0,0)) (a 0) = 0 := by simpa [H, dist_comm] using ho₁
+ have o₂ : dist (H (0,0)) (b 0) = 0 := by simpa [H] using ho₂
+ have e₁ : dist (H (1,0)) (a 1) = 0 := by simpa [H, dist_comm] using he₁
+ have g₂ : dist (H (0,1)) (b 1) = 0 := by simpa [H] using hg₂
+ have hL := hdist _ _ ho he
+ rw [dist_congr_zero o₁ e₁, ha 0 h0 1 h1] at hL
+ norm_num at hL
+ have hW := hdist _ _ ho hg
+ rw [dist_congr_zero o₂ g₂, hb 0 h0 1 h1] at hW
+ norm_num at hW
+ have hC := hdist _ _ he hg
+ rw [dist_congr_zero e₁ g₂, hc 1 h1] at hC
+ norm_num at hC
+ have heq : C = A^2+B^2-c^2 := by linarith only [hC, hL, hW]
+ rw [← hL, ← hW, heq] at hdist
+ exact hdist p q hp hq
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralSectorMap.lean b/lean/OAI/Computability/VPVNP/SpectralSectorMap.lean
new file mode 100644
index 0000000000..169af9f45c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralSectorMap.lean
@@ -0,0 +1,251 @@
+import OAI.Computability.VPVNP.WireGeodesic
+import Mathlib.Analysis.Convex.Basic
+import Mathlib.Tactic.FunProp
+import Mathlib.Tactic.Linarith
+import Mathlib.Tactic.Ring
+
+/-!
+# Interpolation on a sector of the spectral wire geometry
+
+Section 4.1 constructs a sector from two constant-speed segments or rays
+whose distance at parameter `r` equals `c * r`. Equation (2.2) forces
+affine interpolation of sector coordinates to trace a constant-speed segment.
+Taking the radial parameter set to be `Icc 0 R` gives a triangle, and taking
+it to be `Ici 0` gives the entire quadrant.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+variable {X : Type*} [PseudoMetricSpace X]
+
+/-- Coordinates in the nonnegative quadrant with radius in `S`. -/
+def sectorDomain (S : Set ℝ) : Set (ℝ × ℝ) :=
+ {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 ∈ S}
+
+/-- Convexity of the radial interval gives convexity of the sector. -/
+theorem sectorDomain_convex {S : Set ℝ} (hS : Convex ℝ S) : Convex ℝ (sectorDomain S) := by
+ intro p hp q hq u v hu hv huv
+ refine ⟨add_nonneg (mul_nonneg hu hp.1) (mul_nonneg hv hq.1),
+ add_nonneg (mul_nonneg hu hp.2.1) (mul_nonneg hv hq.2.1), ?_⟩
+ change u*p.1+v*q.1 + (u*p.2+v*q.2) ∈ S
+ rw [show u*p.1+v*q.1 + (u*p.2+v*q.2) = u*(p.1+p.2)+v*(q.1+q.2) by ring]
+ exact hS hp.2.2 hq.2.2 hu hv huv
+
+theorem sectorRatio_mem (p : ℝ × ℝ) (hp₁ : 0 ≤ p.1) (hp₂ : 0 ≤ p.2) :
+ 0 ≤ p.2 / (p.1 + p.2) ∧ p.2 / (p.1 + p.2) ≤ 1 :=
+ ⟨div_nonneg hp₂ (add_nonneg hp₁ hp₂), div_le_one_of_le₀ (by linarith) (add_nonneg hp₁ hp₂)⟩
+
+theorem sectorRatio_mul (p : ℝ × ℝ) (hp₁ : 0 ≤ p.1) (hp₂ : 0 ≤ p.2) :
+ p.2 / (p.1 + p.2) * (p.1 + p.2) = p.2 := by
+ by_cases h : p.1 + p.2 = 0
+ · have : p.2 = 0 := by linarith
+ simp [this]
+ · exact div_mul_cancel₀ _ h
+
+/-- The point at fraction `v / (u + v)` on the chord joining the two rays at radius `u + v`.
+The total function is used only on its sector domain. -/
+noncomputable def sectorPoint (hf : HasFractions X) (a b : ℝ → X) (p : ℝ × ℝ) : X :=
+ if hp : 0 ≤ p.1 ∧ 0 ≤ p.2 then
+ (hf (a (p.1 + p.2)) (b (p.1 + p.2)) (p.2 / (p.1 + p.2))
+ (sectorRatio_mem p hp.1 hp.2).1 (sectorRatio_mem p hp.1 hp.2).2).choose
+ else a 0
+
+theorem sectorPoint_radial_fraction (hf : HasFractions X) (a b : ℝ → X) (p : ℝ × ℝ)
+ (hp₁ : 0 ≤ p.1) (hp₂ : 0 ≤ p.2) :
+ AtFraction (a (p.1 + p.2)) (b (p.1 + p.2)) (p.2 / (p.1 + p.2)) (sectorPoint hf a b p) := by
+ rw [sectorPoint, dite_eq_left ⟨hp₁, hp₂⟩]
+ exact Exists.choose_spec _
+
+/-- Distances from the two ends of the chord at the given radius. -/
+theorem sectorPoint_boundary_distances (hf : HasFractions X) (a b : ℝ → X)
+ {S : Set ℝ} {c : ℝ} (hc : ∀ r ∈ S, dist (a r) (b r) = c * r)
+ {p : ℝ × ℝ} (hp : p ∈ sectorDomain S) :
+ dist (a (p.1 + p.2)) (sectorPoint hf a b p) = c * p.2 ∧
+ dist (sectorPoint hf a b p) (b (p.1 + p.2)) = c * p.1 := by
+ obtain ⟨h₁, h₂⟩ := sectorPoint_radial_fraction hf a b p hp.1 hp.2.1
+ rw [hc _ hp.2.2] at h₁ h₂
+ have he := sectorRatio_mul p hp.1 hp.2.1
+ constructor <;> linarith only [h₁, h₂, congrArg (c * ·) he]
+
+/-- The horizontal coordinate axis agrees, up to distance zero, with the first ray. -/
+theorem sectorPoint_axis_left (hf : HasFractions X) (a b : ℝ → X)
+ {S : Set ℝ} {c : ℝ} (hc : ∀ r ∈ S, dist (a r) (b r) = c * r)
+ {r : ℝ} (hr : 0 ≤ r) (hS : r ∈ S) : dist (a r) (sectorPoint hf a b (r, 0)) = 0 := by
+ have hp : (r, 0) ∈ sectorDomain S := ⟨hr, le_rfl, by simpa using hS⟩
+ simpa using (sectorPoint_boundary_distances hf a b hc hp).1
+
+/-- The vertical coordinate axis agrees, up to distance zero, with the second ray. -/
+theorem sectorPoint_axis_right (hf : HasFractions X) (a b : ℝ → X)
+ {S : Set ℝ} {c : ℝ} (hc : ∀ r ∈ S, dist (a r) (b r) = c * r)
+ {r : ℝ} (hr : 0 ≤ r) (hS : r ∈ S) : dist (sectorPoint hf a b (0, r)) (b r) = 0 := by
+ have hp : (0, r) ∈ sectorDomain S := ⟨le_rfl, hr, by simpa using hS⟩
+ simpa using (sectorPoint_boundary_distances hf a b hc hp).2
+
+/-- A constant-speed boundary ray carries affine combinations of parameters to fractions. -/
+private theorem ray_fraction {S : Set ℝ} {a : ℝ → X} {A : ℝ}
+ (ha : ∀ r ∈ S, ∀ s ∈ S, dist (a r) (a s) = A * |r - s|)
+ {r s t : ℝ} (hr : r ∈ S) (hs : s ∈ S) (hm : (1 - t) * r + t * s ∈ S)
+ (ht : 0 ≤ t) (ht' : t ≤ 1) :
+ AtFraction (a r) (a s) t (a ((1-t)*r+t*s)) := by
+ constructor
+ · rw [ha _ hr _ hm, ha _ hr _ hs, show r - ((1-t)*r+t*s) = t*(r-s) by ring,
+ abs_mul, abs_of_nonneg ht]
+ ring
+ · rw [ha _ hm _ hs, ha _ hr _ hs, show (1-t)*r+t*s - s = (1-t)*(r-s) by ring,
+ abs_mul, abs_of_nonneg (sub_nonneg.mpr ht')]
+ ring
+
+/-- Interpolating the coordinates of any two points in the sector interpolates their
+images at the same fraction. This applies to both boundary and interior points. -/
+theorem sectorPoint_atFraction (hf : HasFractions X) (hT : FractionTransport X)
+ {a b : ℝ → X} {A B c : ℝ} {S : Set ℝ} (hS : Convex ℝ S)
+ (ha : ∀ r ∈ S, ∀ s ∈ S, dist (a r) (a s) = A * |r - s|)
+ (hb : ∀ r ∈ S, ∀ s ∈ S, dist (b r) (b s) = B * |r - s|)
+ (hc : ∀ r ∈ S, dist (a r) (b r) = c * r)
+ {p q : ℝ × ℝ} (hp : p ∈ sectorDomain S) (hq : q ∈ sectorDomain S)
+ {t : ℝ} (ht : 0 ≤ t) (ht' : t ≤ 1) :
+ AtFraction (sectorPoint hf a b p) (sectorPoint hf a b q) t
+ (sectorPoint hf a b ((1-t) • p + t • q)) := by
+ let v := (1-t) • p + t • q
+ have v₁ : v.1 = (1-t)*p.1+t*q.1 := rfl
+ have v₂ : v.2 = (1-t)*p.2+t*q.2 := rfl
+ have vr : v.1+v.2 = (1-t)*(p.1+p.2)+t*(q.1+q.2) := by rw [v₁, v₂]; ring
+ have h₀ : 0 ≤ 1-t := sub_nonneg.mpr ht'
+ have hm := hS hp.2.2 hq.2.2 h₀ ht (show 1-t+t = 1 by ring)
+ have hv : v ∈ sectorDomain S :=
+ ⟨add_nonneg (mul_nonneg h₀ hp.1) (mul_nonneg ht hq.1),
+ add_nonneg (mul_nonneg h₀ hp.2.1) (mul_nonneg ht hq.2.1), vr ▸ hm⟩
+ have hva := ray_fraction ha hp.2.2 hq.2.2 hm ht ht'
+ have hvb := ray_fraction hb hp.2.2 hq.2.2 hm ht ht'
+ rw [← vr] at hva hvb
+ obtain ⟨w, hw⟩ := hf (sectorPoint hf a b p) (sectorPoint hf a b q) t ht ht'
+ have hu := hT ht ht' hva hw
+ have hz := hT ht ht' hw hvb
+ obtain ⟨hap, hbp⟩ := sectorPoint_boundary_distances hf a b hc hp
+ obtain ⟨haq, hbq⟩ := sectorPoint_boundary_distances hf a b hc hq
+ rw [hap, haq] at hu
+ rw [hbp, hbq] at hz
+ have htri := dist_triangle (a (v.1 + v.2)) w (b (v.1 + v.2))
+ rw [hc _ hv.2.2] at htri
+ have hwf : AtFraction (a (v.1+v.2)) (b (v.1+v.2)) (v.2/(v.1+v.2)) w := by
+ have hu' : dist (a (v.1+v.2)) w ≤ c*v.2 := hu.trans_eq (by rw [v₂]; ring)
+ have hz' : dist w (b (v.1+v.2)) ≤ c*v.1 := hz.trans_eq (by rw [v₁]; ring)
+ have hmul := congrArg (c * ·) (sectorRatio_mul v hv.1 hv.2.1)
+ constructor <;> rw [hc _ hv.2.2] <;> linarith only [hu', hz', htri, hmul]
+ have hrat := sectorRatio_mem v hv.1 hv.2.1
+ have hwH := hwf.dist_eq_zero_of_transport hT hrat.1 hrat.2
+ (sectorPoint_radial_fraction hf a b v hv.1 hv.2.1)
+ constructor
+ · exact (PseudoMetricSpace.dist_eq_of_dist_zero _ hwH).symm.trans hw.1
+ · rw [dist_comm]
+ exact (PseudoMetricSpace.dist_eq_of_dist_zero _ hwH).symm.trans ((dist_comm _ _).trans hw.2)
+
+/-- Exact distance between two fractions of the same chord, before passing to the metric
+quotient. -/
+private theorem chord_distance_of_le (hf : HasFractions X) (hT : FractionTransport X)
+ {a b x y : X} {s t : ℝ} (hs : 0 ≤ s) (hst : s ≤ t) (ht : t ≤ 1)
+ (hx : AtFraction a b s x) (hy : AtFraction a b t y) :
+ dist x y = (t - s) * dist a b := by
+ let k := s / t
+ have hk : 0 ≤ k := div_nonneg hs (hs.trans hst)
+ have hk' : k ≤ 1 := div_le_one_of_le₀ hst (hs.trans hst)
+ have hkt : k * t = s := by
+ by_cases h : t = 0
+ · have : s = 0 := by linarith
+ simp [k, h, this]
+ · exact div_mul_cancel₀ _ h
+ obtain ⟨w, hw⟩ := hf a y k hk hk'
+ have haw : dist a w = s * dist a b := by rw [hw.1, hy.1, ← mul_assoc, hkt]
+ have hwy : dist w y = (t-s) * dist a b := by
+ rw [hw.2, hy.1]
+ linarith only [congrArg (· * dist a b) hkt]
+ have hwb : AtFraction a b s w := by
+ refine ⟨haw, ?_⟩
+ linarith only [haw, hwy, hy.2, dist_triangle a w b, dist_triangle w y b]
+ have hzero := hx.dist_eq_zero_of_transport hT hs (hst.trans ht) hwb
+ rw [dist_comm x y, PseudoMetricSpace.dist_eq_of_dist_zero y hzero, dist_comm y w, hwy]
+
+theorem AtFraction.chord_distance (hf : HasFractions X) (hT : FractionTransport X)
+ {a b x y : X} {s t : ℝ} (hs : 0 ≤ s) (hs' : s ≤ 1) (ht : 0 ≤ t) (ht' : t ≤ 1)
+ (hx : AtFraction a b s x) (hy : AtFraction a b t y) :
+ dist x y = |s-t| * dist a b := by
+ rcases le_total s t with h | h
+ · rw [abs_of_nonpos (sub_nonpos.mpr h), neg_sub]
+ exact chord_distance_of_le hf hT hs h ht' hx hy
+ · rw [dist_comm x y, abs_of_nonneg (sub_nonneg.mpr h)]
+ exact chord_distance_of_le hf hT ht h hs' hy hx
+
+/-- A uniform continuity estimate comparing two slices. In particular it has no denominator
+at the vertex of the sector. -/
+theorem sectorPoint_distance_le (hf : HasFractions X) (hT : FractionTransport X)
+ {a b : ℝ → X} {A B c : ℝ} {S : Set ℝ}
+ (ha : ∀ r ∈ S, ∀ s ∈ S, dist (a r) (a s) = A * |r - s|)
+ (hb : ∀ r ∈ S, ∀ s ∈ S, dist (b r) (b s) = B * |r - s|)
+ (hc : ∀ r ∈ S, dist (a r) (b r) = c * r)
+ {p q : ℝ × ℝ} (hp : p ∈ sectorDomain S) (hq : q ∈ sectorDomain S) :
+ dist (sectorPoint hf a b p) (sectorPoint hf a b q) ≤
+ (max A B + |c|) * |(p.1+p.2) - (q.1+q.2)| + |c| * |p.2-q.2| := by
+ let r := p.1+p.2
+ let R := q.1+q.2
+ let s := p.2/r
+ let t := q.2/R
+ have hs := sectorRatio_mem p hp.1 hp.2.1
+ have ht := sectorRatio_mem q hq.1 hq.2.1
+ have hsr : s*r = p.2 := sectorRatio_mul p hp.1 hp.2.1
+ have htR : t*R = q.2 := sectorRatio_mul q hq.1 hq.2.1
+ have hR : 0 ≤ R := add_nonneg hq.1 hq.2.1
+ obtain ⟨w, hw⟩ := hf (a R) (b R) s hs.1 hs.2
+ have hrad := hT hs.1 hs.2 (sectorPoint_radial_fraction hf a b p hp.1 hp.2.1) hw
+ rw [ha _ hp.2.2 _ hq.2.2, hb _ hp.2.2 _ hq.2.2] at hrad
+ have hrad' : dist (sectorPoint hf a b p) w ≤ max A B * |r-R| := by
+ apply hrad.trans
+ change (1-s) * (A * |r-R|) + s * (B * |r-R|) ≤ _
+ rw [← mul_assoc, ← mul_assoc, ← add_mul]
+ apply mul_le_mul_of_nonneg_right _ (abs_nonneg _)
+ linarith only [mul_le_mul_of_nonneg_left (le_max_left A B) (sub_nonneg.mpr hs.2),
+ mul_le_mul_of_nonneg_left (le_max_right A B) hs.1]
+ have hchord := hw.chord_distance hf hT hs.1 hs.2 ht.1 ht.2
+ (sectorPoint_radial_fraction hf a b q hq.1 hq.2.1)
+ rw [hc _ hq.2.2] at hchord
+ change dist w (sectorPoint hf a b q) = |s-t| * (c*R) at hchord
+ have hrat : |s-t| * R ≤ |r-R| + |p.2-q.2| := by
+ calc
+ |s-t| * R = |s*R-t*R| := by rw [← sub_mul, abs_mul, abs_of_nonneg hR]
+ _ ≤ |s*R-s*r| + |s*r-t*R| := abs_sub_le _ _ _
+ _ = s*|r-R| + |p.2-q.2| := by
+ rw [← mul_sub, abs_mul, abs_of_nonneg hs.1, abs_sub_comm R r, hsr, htR]
+ _ ≤ _ := by linarith only [mul_le_mul_of_nonneg_right hs.2 (abs_nonneg (r-R))]
+ have hchord' : dist w (sectorPoint hf a b q) ≤ |c| * (|r-R|+|p.2-q.2|) := by
+ calc
+ _ = c * (|s-t| * R) := by rw [hchord]; ring
+ _ ≤ |c| * (|s-t| * R) := mul_le_mul_of_nonneg_right (le_abs_self c)
+ (mul_nonneg (abs_nonneg _) hR)
+ _ ≤ _ := mul_le_mul_of_nonneg_left hrat (abs_nonneg _)
+ change _ ≤ (max A B + |c|)*|r-R| + |c| *|p.2-q.2|
+ linarith only [dist_triangle (sectorPoint hf a b p) w (sectorPoint hf a b q), hrad', hchord']
+
+/-- The sector map is continuous on the closed triangle or quadrant, including its vertex. -/
+theorem sectorPoint_continuousOn (hf : HasFractions X) (hT : FractionTransport X)
+ {a b : ℝ → X} {A B c : ℝ} {S : Set ℝ}
+ (ha : ∀ r ∈ S, ∀ s ∈ S, dist (a r) (a s) = A * |r - s|)
+ (hb : ∀ r ∈ S, ∀ s ∈ S, dist (b r) (b s) = B * |r - s|)
+ (hc : ∀ r ∈ S, dist (a r) (b r) = c * r) :
+ ContinuousOn (sectorPoint hf a b) (sectorDomain S) := by
+ intro q hq
+ apply tendsto_iff_dist_tendsto_zero.mpr
+ let g (p : ℝ × ℝ) := (max A B + |c|) * |(p.1+p.2) - (q.1+q.2)| + |c| * |p.2-q.2|
+ apply squeeze_zero' (Filter.Eventually.of_forall fun _ ↦ dist_nonneg) (g := g)
+ · exact Filter.Eventually.mono self_mem_nhdsWithin fun _ hp ↦
+ sectorPoint_distance_le hf hT ha hb hc hp hq
+ · have hg : Continuous g := by unfold g; fun_prop
+ simpa [g] using (hg.continuousWithinAt (s := sectorDomain S) (x := q)).tendsto
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralSectorQuadratic.lean b/lean/OAI/Computability/VPVNP/SpectralSectorQuadratic.lean
new file mode 100644
index 0000000000..167fffea3f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralSectorQuadratic.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.NormRigidity
+import Mathlib.Topology.Algebra.SeparationQuotient.Basic
+
+/-!
+# Euclidean distances of possibly degenerate spectral sectors
+
+Section 4.1 obtains a seminorm on the coordinate plane of a sector. Realizing
+the distances on any nonempty open set forces its square to be a positive
+semidefinite quadratic form, including when some directions have zero length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+universe u
+
+/-- The separation quotient of a finite-dimensional seminormed space inherits an
+inner product if its eight-point distances are realizable by spectral wires. -/
+theorem exists_normPreserving_map_of_realizable
+ {E : Type u} [AddCommGroup E] [Module ℝ E] [FiniteDimensional ℝ E]
+ (k : Type*) [Field k] (p : Seminorm ℝ E)
+ (h : ∀ a : Fin 8 → E,
+ WireTensor.RealizableUpToScale k (fun i j => p (a i - a j))) :
+ ∃ (Q : Type u) (_ : NormedAddCommGroup Q) (_ : InnerProductSpace ℝ Q) (f : E →ₗ[ℝ] Q),
+ ∀ x, ‖f x‖ = p x := by
+ let : SeminormedAddCommGroup E := p.toAddGroupSeminorm.toSeminormedAddCommGroup
+ let : NormedSpace ℝ E := { norm_smul_le := fun a x => (map_smul_eq_mul p a x).le }
+ let Q := SeparationQuotient E
+ let f : E →ₗ[ℝ] Q := (SeparationQuotient.mkCLM ℝ E).toLinearMap
+ have hsur : Function.Surjective f := SeparationQuotient.surjective_mk
+ let : FiniteDimensional ℝ Q := FiniteDimensional.of_surjective f hsur
+ have hf (x : E) : ‖f x‖ = p x := rfl
+ obtain ⟨innerQ⟩ := NormRigidity.innerProduct_of_local_costs (E := Q) isOpen_univ Set.univ_nonempty (by
+ intro a _
+ choose x hx using fun i => hsur (a i)
+ obtain ⟨w⟩ := h x
+ refine ⟨w.scale⁻¹, inv_pos.mpr w.scale_pos, ?_⟩
+ have hd (i j : Fin 8) : w.scale⁻¹ * dist (a i) (a j) =
+ w.spectrum.wireDistance (w.label i) (w.label j) := by
+ rw [dist_eq_norm, ← hx i, ← hx j, ← map_sub, hf, w.distances,
+ inv_mul_cancel_left₀ w.scale_pos.ne']
+ simp only [hd]
+ intro X Y P M hX hY hP hM factor
+ exact NormRigidity.eightPointCost_of_spectrum w.spectrum w.label hX hY hP hM factor)
+ exact ⟨Q, inferInstance, innerQ, f, hf⟩
+
+/-- The squared seminorm of a difference along two fixed directions has a
+single mixed coefficient valid for every real parameter, including when one
+or both directions lie in the kernel. -/
+theorem seminorm_sq_smul_sub (k : Type*) [Field k] {V : Type*} [AddCommGroup V]
+ [Module ℝ V] [FiniteDimensional ℝ V] (p : Seminorm ℝ V)
+ (h : ∀ n (x : Fin n → V),
+ WireTensor.RealizableUpToScale k (fun i j ↦ p (x i - x j))) (u v : V) :
+ ∃ c : ℝ, ∀ T : ℝ, p (T • u - v) ^ 2 = T ^ 2 * p u ^ 2 + p v ^ 2 - 2 * T * c := by
+ obtain ⟨Q, qnorm, qinner, q, hn⟩ := exists_normPreserving_map_of_realizable k p (h 8)
+ refine ⟨inner ℝ (q u) (q v), fun T ↦ ?_⟩
+ rw [← hn, map_sub, map_smul, norm_sub_sq_real, real_inner_smul_left, norm_smul,
+ Real.norm_eq_abs, mul_pow, sq_abs, hn, hn]
+ ring
+
+end WireGeometry
+
+namespace SpectralGeometry
+
+open scoped InnerProductSpace
+open WireTensor
+
+private theorem realizePlaneGlobally {k : Type*} [Field k] (p : Seminorm ℝ (ℝ × ℝ))
+ {U : Set (ℝ × ℝ)} (hU : IsOpen U) (hne : U.Nonempty)
+ (h : ∀ f : Fin 8 → ℝ × ℝ, (∀ i, f i ∈ U) →
+ RealizableUpToScale k (fun i j => p (f i - f j))) (f : Fin 8 → ℝ × ℝ) :
+ RealizableUpToScale k (fun i j => p (f i - f j)) := by
+ obtain ⟨c, r, hr, hmem⟩ := NormRigidity.exists_homothety_mem f hU hne
+ have hr' := (h (fun i => c + r • f i) hmem).smul (inv_pos.mpr hr)
+ simpa only [add_sub_add_left_eq_sub, ← smul_sub, map_smul_eq_mul,
+ Real.norm_of_nonneg hr.le, inv_mul_cancel_left₀ hr.ne'] using hr'
+
+private theorem quadratic_of_normPreserving_map (p : Seminorm ℝ (ℝ × ℝ))
+ {Q : Type*} [NormedAddCommGroup Q] [InnerProductSpace ℝ Q]
+ (f : (ℝ × ℝ) →ₗ[ℝ] Q) (h : ∀ x, ‖f x‖ = p x) :
+ ∃ L W B : ℝ, ∀ x : ℝ × ℝ, p x ^ 2 = x.1 ^ 2 * L + x.2 ^ 2 * W + x.1 * x.2 * B := by
+ let e₁ : ℝ × ℝ := (1, 0)
+ let e₂ : ℝ × ℝ := (0, 1)
+ refine ⟨‖f e₁‖ ^ 2, ‖f e₂‖ ^ 2, 2 * ⟪f e₁, f e₂⟫_ℝ, ?_⟩
+ intro x
+ have hcoord : x = x.1 • e₁ + x.2 • e₂ := by ext <;> simp [e₁, e₂]
+ rw [← h, ← real_inner_self_eq_norm_sq, hcoord, map_add, map_smul, map_smul]
+ simp only [inner_add_left, inner_add_right, real_inner_smul_left, real_inner_smul_right,
+ real_inner_self_eq_norm_sq, real_inner_comm (f e₂) (f e₁), e₁, e₂, Prod.fst_add,
+ Prod.snd_add, Prod.smul_fst, Prod.smul_snd, smul_eq_mul, mul_one, mul_zero,
+ add_zero, zero_add]
+ simp only [norm_smul, mul_pow, Real.norm_eq_abs, sq_abs]
+ ring
+
+/-- The square of the pullback seminorm on the coordinate plane of a spectral
+sector is a quadratic form. The topology in the open-set hypothesis is the
+usual topology of the coordinate plane. -/
+theorem sectorSeminorm_quadratic {k : Type*} [Field k] (p : Seminorm ℝ (ℝ × ℝ))
+ {U : Set (ℝ × ℝ)} (hU : IsOpen U) (hne : U.Nonempty)
+ (h : ∀ f : Fin 8 → ℝ × ℝ, (∀ i, f i ∈ U) →
+ RealizableUpToScale k (fun i j => p (f i - f j))) :
+ ∃ L W B : ℝ, ∀ x : ℝ × ℝ, p x ^ 2 = x.1 ^ 2 * L + x.2 ^ 2 * W + x.1 * x.2 * B := by
+ obtain ⟨Q, qnorm, qinner, f, hf⟩ := WireGeometry.exists_normPreserving_map_of_realizable
+ k p (realizePlaneGlobally p hU hne h)
+ exact quadratic_of_normPreserving_map p f hf
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralSectorSeminorm.lean b/lean/OAI/Computability/VPVNP/SpectralSectorSeminorm.lean
new file mode 100644
index 0000000000..15f6dd94dd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralSectorSeminorm.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.SectorSpeeds
+import Mathlib.Analysis.Convex.Topology
+import Mathlib.Analysis.Normed.Module.Seminorm.Basic
+import Mathlib.Tactic.Module
+import Mathlib.Tactic.FunProp
+import Mathlib.Tactic.Linarith
+
+/-!
+# The pullback seminorm of a spectral sector
+
+In Section 4.1 the speeds of parallel affine segments agree at every
+interior base point. The triangle inequality on a small translated triangle
+gives subadditivity of the common speed. Reversing and rescaling small
+segments gives absolute homogeneity. Moving endpoints towards an interior
+point and taking a one-sided limit extends the distance formula to the
+entire convex sector, including its boundary.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open Filter Topology
+
+variable {X : Type*} [PseudoMetricSpace X] {D : Set (ℝ × ℝ)} {H : (ℝ × ℝ) → X}
+
+private theorem eventually_interior_step {p : ℝ × ℝ} (hp : p ∈ interior D) (v : ℝ × ℝ) :
+ ∀ᶠ t in 𝓝[>] (0 : ℝ), p + t • v ∈ interior D := by
+ have hc : Continuous (fun t : ℝ ↦ p + t • v) := by fun_prop
+ have hlim : Tendsto (fun t : ℝ ↦ p + t • v) (𝓝[>] 0) (𝓝 p) := by
+ simpa using (hc.continuousWithinAt (s := Set.Ioi 0) (x := 0)).tendsto
+ exact hlim (isOpen_interior.mem_nhds hp)
+
+private theorem seminorm_of_sector_speed {p : ℝ × ℝ} (hp : p ∈ interior D)
+ (speed : (ℝ × ℝ) → ℝ)
+ (hs : ∀ x ∈ interior D, ∀ (v : ℝ × ℝ) (t : ℝ), 0 < t → x + t • v ∈ D →
+ dist (H x) (H (x + t • v)) = t * speed v) :
+ ∃ P : Seminorm ℝ (ℝ × ℝ), (P : (ℝ × ℝ) → ℝ) = speed := by
+ have hpos : ∀ᶠ t in 𝓝[>] (0 : ℝ), 0 < t := self_mem_nhdsWithin
+ have hadd (v w : ℝ × ℝ) : speed (v + w) ≤ speed v + speed w := by
+ obtain ⟨t, ht, hv, hvw⟩ := (hpos.and ((eventually_interior_step hp v).and
+ (eventually_interior_step hp (v + w)))).exists
+ have hpath : p + t • v + t • w = p + t • (v + w) := by module
+ have hw := hs (p + t • v) hv w t ht (hpath ▸ interior_subset hvw)
+ rw [hpath] at hw
+ have htri := dist_triangle (H p) (H (p + t • v)) (H (p + t • (v + w)))
+ rw [hs p hp v t ht (interior_subset hv), hw,
+ hs p hp (v + w) t ht (interior_subset hvw), ← mul_add] at htri
+ exact (mul_le_mul_iff_right₀ ht).mp htri
+ have hzero : speed 0 = 0 := by
+ have hz := hs p hp 0 1 zero_lt_one (by simpa using interior_subset hp)
+ simpa using hz.symm
+ have hsmul (r : ℝ) (v : ℝ × ℝ) : speed (r • v) = ‖r‖ * speed v := by
+ obtain ⟨t, ht, hv⟩ := (hpos.and (eventually_interior_step hp (r • v))).exists
+ have hbase := hs p hp (r • v) t ht (interior_subset hv)
+ rcases lt_trichotomy r 0 with hr | rfl | hr
+ · have hend : p + t • (r • v) + (-(t * r)) • v = p := by module
+ have he := hs (p + t • (r • v)) hv v (-(t * r)) (neg_pos.mpr (mul_neg_of_pos_of_neg ht hr))
+ (by rw [hend]; exact interior_subset hp)
+ rw [hend, dist_comm, hbase] at he
+ rw [Real.norm_eq_abs, abs_of_neg hr]
+ apply mul_left_cancel₀ ht.ne'
+ linarith only [he]
+ · simp [hzero]
+ · have he := hs p hp v (t * r) (mul_pos ht hr) (by simpa [mul_smul] using interior_subset hv)
+ rw [mul_smul, hbase, mul_assoc] at he
+ rw [Real.norm_eq_abs, abs_of_pos hr]
+ exact mul_left_cancel₀ ht.ne' he
+ exact ⟨Seminorm.of speed hadd hsmul, rfl⟩
+
+private theorem sector_distance_boundary (hD : Convex ℝ D)
+ (hH : ∀ {x y}, x ∈ D → y ∈ D → ∀ {t : ℝ}, 0 ≤ t → t ≤ 1 →
+ AtFraction (H x) (H y) t (H ((1 - t) • x + t • y)))
+ {p : ℝ × ℝ} (hp : p ∈ interior D) (P : Seminorm ℝ (ℝ × ℝ))
+ (hi : ∀ x ∈ interior D, ∀ y ∈ D, dist (H x) (H y) = P (y - x))
+ {x y : ℝ × ℝ} (hx : x ∈ D) (hy : y ∈ D) :
+ dist (H x) (H y) = P (y - x) := by
+ let f (t : ℝ) := dist (dist (H x) (H y)) ((1 - t) * P (y - x))
+ let g (t : ℝ) := t * (dist (H x) (H p) + dist (H y) (H p))
+ have he : ∀ᶠ t in 𝓝[>] (0 : ℝ), f t ≤ g t := by
+ filter_upwards [self_mem_nhdsWithin, nhdsWithin_le_nhds (gt_mem_nhds zero_lt_one)]
+ with t ht ht'
+ have htpos : 0 < t := ht
+ have hs : 0 ≤ 1 - t := sub_nonneg.mpr ht'.le
+ let u := (1 - t) • x + t • p
+ let v := (1 - t) • y + t • p
+ have hu : u ∈ interior D := hD.combo_self_interior_mem_interior hx hp hs htpos (by ring)
+ have hv : v ∈ interior D := hD.combo_self_interior_mem_interior hy hp hs htpos (by ring)
+ have hd := hi u hu v (interior_subset hv)
+ have hsub : v - u = (1 - t) • (y - x) := by dsimp [v, u]; module
+ rw [hsub, map_smul_eq_mul, Real.norm_eq_abs, abs_of_nonneg hs] at hd
+ have hxu : dist (H x) (H u) = t * dist (H x) (H p) :=
+ (hH hx (interior_subset hp) htpos.le ht'.le).1
+ have hyv : dist (H y) (H v) = t * dist (H y) (H p) :=
+ (hH hy (interior_subset hp) htpos.le ht'.le).1
+ simpa only [f, g, hd, hxu, hyv, mul_add] using dist_dist_dist_le (H x) (H y) (H u) (H v)
+ have hcf : Continuous f := by dsimp [f]; fun_prop
+ have hcg : Continuous g := by dsimp [g]; fun_prop
+ have h0 := le_of_tendsto_of_tendsto hcf.continuousWithinAt.tendsto hcg.continuousWithinAt.tendsto he
+ exact dist_le_zero.mp (by simpa [f, g] using h0)
+
+/-- The pullback distances of an affine geodesic parametrization on a convex
+sector with nonempty interior are given by a single seminorm on the plane.
+The conclusion includes pairs of boundary points. -/
+theorem exists_sector_seminorm (hD : Convex ℝ D) (htr : FractionTransport X)
+ (hH : ∀ {x y}, x ∈ D → y ∈ D → ∀ {t : ℝ}, 0 ≤ t → t ≤ 1 →
+ AtFraction (H x) (H y) t (H ((1 - t) • x + t • y)))
+ {p : ℝ × ℝ} (hp : p ∈ interior D) :
+ ∃ P : Seminorm ℝ (ℝ × ℝ), ∀ x ∈ D, ∀ y ∈ D, dist (H x) (H y) = P (y - x) := by
+ obtain ⟨speed, hs⟩ := exists_sector_speed hD htr hH hp
+ obtain ⟨P, hP⟩ := seminorm_of_sector_speed hp speed hs
+ have hi (x : ℝ × ℝ) (hx : x ∈ interior D) (y : ℝ × ℝ) (hy : y ∈ D) :
+ dist (H x) (H y) = P (y - x) := by
+ have hv := hs x hx (y - x) 1 zero_lt_one (by simpa using hy)
+ simpa [← hP] using hv
+ exact ⟨P, fun _ hx _ hy ↦ sector_distance_boundary hD hH hp P hi hx hy⟩
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralSeparation.lean b/lean/OAI/Computability/VPVNP/SpectralSeparation.lean
new file mode 100644
index 0000000000..9fdfef2bcf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralSeparation.lean
@@ -0,0 +1,211 @@
+import Mathlib.Algebra.Algebra.Rat
+import Mathlib.Algebra.Order.Module.Rat
+import Mathlib.Analysis.Convex.Cone.Extension
+
+/-!
+# Separation by a rational-linear state
+
+Appendix A.1 of *VP and VNP differ over every field* works with a rational cone
+in the localized tensor algebra. For a vector `z` outside the cone, adjoining
+`-z` preserves exclusion of the negative order unit. A positive extension from
+the rational order-unit line to the whole space then has value at most zero at `z`.
+
+The scalar coefficients of the linear maps are rational. Their values lie in
+`ℝ`, where the supremum needed to choose a value in a new direction exists.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+open Set Submodule
+
+variable {E : Type*} [AddCommGroup E] [Module ℚ E]
+
+/-- Extend a positive rational-linear functional in one new direction. -/
+theorem rational_extension_step (s : PointedCone ℚ E) (f : E →ₗ.[ℚ] ℝ)
+ (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x)
+ (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) (hdom : f.domain ≠ ⊤) :
+ ∃ g, f < g ∧ ∀ x : g.domain, (x : E) ∈ s → 0 ≤ g x := by
+ obtain ⟨y, _, hy⟩ := SetLike.exists_of_lt (lt_top_iff_ne_top.mpr hdom)
+ let lows : Set ℝ := {u | ∃ a : f.domain, (a : E) + y ∈ s ∧ u = -f a}
+ have compat (a b : f.domain) (ha : (a : E) + y ∈ s) (hb : (b : E) - y ∈ s) :
+ -f a ≤ f b := by
+ have hab : ((a + b : f.domain) : E) ∈ s := by
+ have h := s.add_mem ha hb
+ rw [sub_eq_add_neg, add_add_add_comm, add_neg_cancel, add_zero] at h
+ exact h
+ exact neg_le_iff_add_nonneg.mpr (by simpa only [f.map_add, add_comm] using nonneg _ hab)
+ have upper (b : f.domain) (hb : (b : E) - y ∈ s) : f b ∈ upperBounds lows := by
+ rintro _ ⟨a, ha, rfl⟩
+ exact compat a b ha hb
+ obtain ⟨b, hb⟩ := dense (-y)
+ have bound : BddAbove lows := ⟨f b, upper b (by simpa only [sub_eq_add_neg] using hb)⟩
+ obtain ⟨a, ha⟩ := dense y
+ have inhabited : lows.Nonempty := ⟨-f a, a, ha, rfl⟩
+ let c := sSup lows
+ have lower_value (x : f.domain) (hx : (x : E) + y ∈ s) : 0 ≤ f x + c :=
+ neg_le_iff_add_nonneg'.mp (le_csSup bound ⟨x, hx, rfl⟩)
+ have upper_value (x : f.domain) (hx : (x : E) - y ∈ s) : 0 ≤ f x - c :=
+ sub_nonneg.mpr (csSup_le inhabited (upper x hx))
+ refine ⟨f.supSpanSingleton y c hy, lt_of_le_of_ne (f.left_le_sup _ _) ?_, ?_⟩
+ · intro heq
+ apply hy
+ rw [heq, LinearPMap.domain_supSpanSingleton]
+ exact mem_sup_right (mem_span_singleton_self _)
+ · rintro ⟨z, hz⟩ hcone
+ obtain ⟨x, hx, z', hz', rfl⟩ := mem_sup.mp hz
+ obtain ⟨r, rfl⟩ := mem_span_singleton.mp hz'
+ change x + r • y ∈ s at hcone
+ rw [LinearPMap.supSpanSingleton_apply_mk _ _ _ _ _ hx, RingHom.id_apply]
+ let u : f.domain := ⟨x, hx⟩
+ rcases lt_trichotomy r 0 with hr | rfl | hr
+ · let t := -r
+ have ht : 0 < t := neg_pos.mpr hr
+ have ht' : t * t⁻¹ = 1 := mul_inv_cancel₀ ht.ne'
+ have hnorm : ((t⁻¹ • u : f.domain) : E) - y ∈ s := by
+ apply (s.smul_mem_iff ht).mp
+ simpa only [Submodule.coe_smul, smul_sub, smul_smul, ht', one_smul, t, neg_smul,
+ sub_neg_eq_add] using hcone
+ have hval := smul_nonneg ht.le (upper_value (t⁻¹ • u) hnorm)
+ simpa only [smul_sub, f.map_smul, RingHom.id_apply, smul_smul, ht', one_smul, t, neg_smul,
+ sub_neg_eq_add] using hval
+ · simpa only [zero_smul, add_zero] using
+ (nonneg u (by simpa only [zero_smul, add_zero] using hcone))
+ · have hr' : r * r⁻¹ = 1 := mul_inv_cancel₀ hr.ne'
+ have hnorm : ((r⁻¹ • u : f.domain) : E) + y ∈ s := by
+ apply (s.smul_mem_iff hr).mp
+ simpa only [Submodule.coe_smul, smul_add, smul_smul, hr', one_smul] using hcone
+ have hval := smul_nonneg hr.le (lower_value (r⁻¹ • u) hnorm)
+ simpa only [smul_add, f.map_smul, RingHom.id_apply, smul_smul, hr', one_smul] using hval
+
+/-- An increasing chain of positive partial functionals is positive on the union
+of its domains. -/
+private theorem chain_positive (P : PointedCone ℚ E) (c : Set (E →ₗ.[ℚ] ℝ))
+ (hne : c.Nonempty) (hc : DirectedOn (· ≤ ·) c)
+ (hpos : ∀ p ∈ c, ∀ x : p.domain, (x : E) ∈ P → 0 ≤ p x) :
+ ∀ x : (LinearPMap.sSup c hc).domain, (x : E) ∈ P → 0 ≤ LinearPMap.sSup c hc x := by
+ rintro ⟨x, hx⟩ hPx
+ obtain ⟨p, hpc, hpx⟩ := (LinearPMap.mem_domain_sSup_iff hne hc).mp hx
+ rw [LinearPMap.sSup_apply hc hpc ⟨x, hpx⟩]
+ exact hpos p hpc ⟨x, hpx⟩ hPx
+
+/-- A real-valued positive functional on a rational subspace extends whenever
+the subspace contains a translate of every vector into the cone. -/
+theorem rational_riesz_extension (P : PointedCone ℚ E) (p : E →ₗ.[ℚ] ℝ)
+ (hp : ∀ x : p.domain, (x : E) ∈ P → 0 ≤ p x)
+ (hdense : ∀ y : E, ∃ x : p.domain, (x : E) + y ∈ P) :
+ ∃ f : E →ₗ[ℚ] ℝ, (∀ x : p.domain, f x = p x) ∧ ∀ x ∈ P, 0 ≤ f x := by
+ let positive := {q : E →ₗ.[ℚ] ℝ | ∀ x : q.domain, (x : E) ∈ P → 0 ≤ q x}
+ have hub : ∀ c ⊆ positive, IsChain (· ≤ ·) c → ∀ q ∈ c,
+ ∃ b ∈ positive, ∀ r ∈ c, r ≤ b := by
+ intro c hsub hchain q hqc
+ refine ⟨LinearPMap.sSup c hchain.directedOn, ?_, fun _ hr => LinearPMap.le_sSup _ hr⟩
+ exact chain_positive P c ⟨q, hqc⟩ hchain.directedOn fun _ hr => hsub hr
+ obtain ⟨q, hpq, hq, hmax⟩ := zorn_le_nonempty₀ positive hub p hp
+ have htop : q.domain = ⊤ := by
+ by_contra hproper
+ have hcofinal (y : E) : ∃ x : q.domain, (x : E) + y ∈ P := by
+ obtain ⟨x, hx⟩ := hdense y
+ exact ⟨⟨x, hpq.1 x.property⟩, hx⟩
+ obtain ⟨r, hqr, hr⟩ := rational_extension_step P q hq hcofinal hproper
+ exact hqr.not_ge (hmax hr hqr.le)
+ let inc : E →ₗ[ℚ] q.domain := LinearMap.id.codRestrict q.domain (fun x => htop ▸ trivial)
+ refine ⟨q.toFun.comp inc, ?_, ?_⟩
+ · intro x
+ exact (hpq.2 (y := inc (x : E)) rfl).symm
+ · intro x hx
+ exact hq (inc x) hx
+
+/-- The cone obtained by adjoining the ray generated by `-z` to `P`. -/
+def augmentCone (P : PointedCone ℚ E) (z : E) : PointedCone ℚ E :=
+ P ⊔ PointedCone.hull ℚ {-z}
+
+theorem le_augmentCone (P : PointedCone ℚ E) (z : E) : P ≤ augmentCone P z :=
+ le_sup_left
+
+theorem neg_mem_augmentCone (P : PointedCone ℚ E) (z : E) : -z ∈ augmentCone P z :=
+ (show PointedCone.hull ℚ {-z} ≤ augmentCone P z from le_sup_right)
+ (PointedCone.subset_hull (Set.mem_singleton (-z)))
+
+theorem mem_augmentCone_iff {P : PointedCone ℚ E} {z x : E} :
+ x ∈ augmentCone P z ↔ ∃ p ∈ P, ∃ r : ℚ, 0 ≤ r ∧ p - r • z = x := by
+ rw [augmentCone, Submodule.mem_sup]
+ constructor
+ · rintro ⟨p, hp, y, hy, h⟩
+ obtain ⟨r, hr, rfl⟩ := PointedCone.mem_hull_singleton.mp hy
+ exact ⟨p, hp, r, hr, by simpa [sub_eq_add_neg] using h⟩
+ · rintro ⟨p, hp, r, hr, rfl⟩
+ exact ⟨p, hp, r • (-z), PointedCone.mem_hull_singleton.mpr ⟨r, hr, rfl⟩,
+ by simp [sub_eq_add_neg]⟩
+
+/-- If `z` lies outside the cone, adjoining `-z` still excludes the negative order unit. -/
+theorem neg_notMem_augmentCone {P : PointedCone ℚ E} {e z : E}
+ (he : e ∈ P) (hne : -e ∉ P) (hz : z ∉ P) : -e ∉ augmentCone P z := by
+ intro h
+ obtain ⟨p, hp, r, hr, hrepr⟩ := mem_augmentCone_iff.mp h
+ rcases eq_or_lt_of_le hr with hzero | hpos
+ · subst r
+ simp only [zero_smul, sub_zero] at hrepr
+ exact hne (hrepr ▸ hp)
+ · have hrz : r • z = p + e := by
+ rw [sub_eq_iff_eq_add] at hrepr
+ rw [hrepr]
+ simp [add_comm]
+ apply hz
+ apply (PointedCone.smul_mem_iff P hpos).mp
+ exact hrz ▸ P.add_mem hp he
+
+/-- The functional on the order-unit line sends a rational multiple of the unit
+to its coefficient. Cone positivity and the order-unit property make this line
+a suitable initial domain for positive extension. -/
+theorem exists_orderUnitLine (P : PointedCone ℚ E) (e : E)
+ (hne : -e ∉ P) (horder : ∀ y : E, ∃ n : ℕ, n • e + y ∈ P) :
+ ∃ f : E →ₗ.[ℚ] ℝ, ∃ he : e ∈ f.domain,
+ f ⟨e, he⟩ = 1 ∧
+ (∀ x : f.domain, (x : E) ∈ P → 0 ≤ f x) ∧
+ ∀ y : E, ∃ x : f.domain, (x : E) + y ∈ P := by
+ have h0 : e ≠ 0 := by
+ rintro rfl
+ exact hne (by simpa only [neg_zero] using P.zero_mem)
+ let f : E →ₗ.[ℚ] ℝ := LinearPMap.mkSpanSingleton e 1 h0
+ have he : e ∈ f.domain := Submodule.mem_span_singleton_self e
+ refine ⟨f, he, LinearPMap.mkSpanSingleton_apply ℚ ℚ h0 1, ?_, ?_⟩
+ · rintro ⟨x, hx⟩ hP
+ obtain ⟨r, rfl⟩ := Submodule.mem_span_singleton.mp hx
+ have hr : 0 ≤ r := by
+ by_contra! hneg
+ apply hne
+ have hsc : 0 ≤ -r⁻¹ := neg_nonneg.mpr (inv_nonpos.mpr hneg.le)
+ have hs := P.smul_mem hsc hP
+ simpa [smul_smul, neg_mul, inv_mul_cancel₀ hneg.ne] using hs
+ change 0 ≤ LinearPMap.mkSpanSingleton' e (1 : ℝ) _ ⟨r • e, hx⟩
+ rw [LinearPMap.mkSpanSingleton'_apply, RingHom.id_apply, Rat.smul_def, mul_one]
+ exact_mod_cast hr
+ · intro y
+ obtain ⟨n, hn⟩ := horder y
+ exact ⟨⟨n • e, f.domain.nsmul_mem he n⟩, hn⟩
+
+/-- A vector outside the rational order-unit cone admits a normalized
+nonnegative functional whose value on the vector is at most zero. -/
+theorem separate_order_unit (P : PointedCone ℚ E) (e z : E) (he : e ∈ P)
+ (hneg : -e ∉ P) (horder : ∀ x : E, ∃ n : ℕ, n • e + x ∈ P) (hz : z ∉ P) :
+ ∃ f : E →ₗ[ℚ] ℝ, f e = 1 ∧ (∀ x ∈ P, 0 ≤ f x) ∧ f z ≤ 0 := by
+ let Q := augmentCone P z
+ have hQneg : -e ∉ Q := neg_notMem_augmentCone he hneg hz
+ have hQorder (x : E) : ∃ n : ℕ, n • e + x ∈ Q := by
+ obtain ⟨n, hn⟩ := horder x
+ exact ⟨n, le_augmentCone P z hn⟩
+ obtain ⟨p, hep, hpone, hppos, hpdense⟩ := exists_orderUnitLine Q e hQneg hQorder
+ obtain ⟨f, hfp, hfpos⟩ := rational_riesz_extension Q p hppos hpdense
+ have hfe : f e = 1 := (hfp ⟨e, hep⟩).trans hpone
+ refine ⟨f, hfe, fun x hx => hfpos x (le_augmentCone P z hx), ?_⟩
+ simpa only [map_neg, neg_nonneg] using hfpos (-z) (neg_mem_augmentCone P z)
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralStateHom.lean b/lean/OAI/Computability/VPVNP/SpectralStateHom.lean
new file mode 100644
index 0000000000..36e7606913
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralStateHom.lean
@@ -0,0 +1,125 @@
+import OAI.Computability.VPVNP.SpectralLocalization
+import OAI.Computability.VPVNP.SpectralSeparation
+import OAI.Computability.VPVNP.SpectralStates
+
+/-!
+# Multiplicativity of extreme states on tensor fractions
+
+In Appendix A.1 the reciprocal of `1 + s` splits the normalized unit into
+two positive summands. Extremality makes each summand act multiplicatively.
+Restricting the resulting state to the original semiring gives a spectral point.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+variable {A : Type*} [CommRing A] [Algebra ℚ A]
+
+/-- A unit whose multiplication preserves an order-unit cone has strictly
+positive value at every normalized positive state. -/
+theorem state_pos_of_unit_multiplier {P : PointedCone ℚ A} {f : A → ℝ}
+ (hf : f ∈ states P) (orderUnit : ∀ x : A, ∃ n : ℕ, n • (1 : A) + x ∈ P)
+ {v : A} (hv : IsUnit v) (hstable : ∀ x ∈ P, v * x ∈ P) : 0 < f v := by
+ obtain ⟨w, hw⟩ := hv.exists_right_inv
+ obtain ⟨n, hn⟩ := orderUnit (-w)
+ have hp := hstable _ hn
+ simp only [mul_add, mul_smul_comm, mul_one, mul_neg, hw] at hp
+ let L := stateLinearMap hf
+ have h1 : L 1 = 1 := hf.1
+ have hval : 0 ≤ L (n • v + -(1 : A)) := hf.2.2.2 _ hp
+ simp only [map_add, map_neg, map_nsmul, h1] at hval
+ rw [nsmul_eq_mul] at hval
+ change 0 < L v
+ by_contra! h
+ have := mul_nonpos_of_nonneg_of_nonpos (Nat.cast_nonneg (α := ℝ) n) h
+ linarith
+
+/-- A tensor unit acts multiplicatively on every extreme state when it and
+the reciprocal of its sum with the unit preserve the cone. -/
+theorem extreme_state_mul_of_unit_denominator {P : PointedCone ℚ A} {f : A → ℝ}
+ (he : f ∈ (states P).extremePoints ℝ)
+ (orderUnit : ∀ x : A, ∃ n : ℕ, n • (1 : A) + x ∈ P)
+ {s v : A} (hs : IsUnit s) (hden : v * (1 + s) = 1)
+ (ss : ∀ x ∈ P, s * x ∈ P) (sv : ∀ x ∈ P, v * x ∈ P) (x : A) :
+ f (s * x) = f s * f x := by
+ have hv : IsUnit v := .of_mul_eq_one _ hden
+ have su (y : A) (hy : y ∈ P) : (v * s) * y ∈ P := by
+ rw [mul_assoc]
+ exact sv _ (ss _ hy)
+ apply extreme_state_mul_generator he (u := v * s) (v := v) _ rfl
+ (state_pos_of_unit_multiplier he.1 orderUnit (hv.mul hs) su)
+ (state_pos_of_unit_multiplier he.1 orderUnit hv sv) su sv x
+ simpa only [mul_add, mul_one, add_comm v] using hden
+
+section Tensor
+
+variable {S : Type*} [CommSemiring S] [NoZeroDivisors S] [Nontrivial S] [Preorder S] [CharZero S]
+variable {H : OrderBounds S} {f : Spectral.A S → ℝ}
+
+/-- Extreme states multiply by every tensor in the localization. -/
+theorem extreme_state_mul_tensor
+ (he : f ∈ (states (orderCone toA H)).extremePoints ℝ) (rank : S →+* ℕ)
+ (s : S) (x : Spectral.A S) : f (toA s * x) = f (toA s) * f x := by
+ by_cases hs : s = 0
+ · subst s
+ have hzero : f 0 = 0 := map_zero (stateLinearMap he.1)
+ simp only [map_zero, zero_mul, hzero]
+ · let hn := one_add_ne_zero_of_rank rank s
+ let v := fractionInverse (1 + s) hn
+ have hden : v * (1 + toA s) = 1 := by
+ simpa only [v, map_add, map_one] using fraction_inverse_spec (1 + s) hn
+ exact extreme_state_mul_of_unit_denominator he (orderCone_bound H) (toA_isUnit hs) hden
+ (fun _ => orderCone_mul_tensor H s) (fun _ => orderCone_mul_inv H _ hn) x
+
+/-- Restriction of an extreme state to the original tensor semiring. -/
+noncomputable def extremeStateHom (he : f ∈ (states (orderCone toA H)).extremePoints ℝ)
+ (rank : S →+* ℕ) : S →+* ℝ where
+ toFun s := f (toA s)
+ map_zero' := by rw [map_zero]; exact map_zero (stateLinearMap he.1)
+ map_one' := by rw [map_one]; exact he.1.1
+ map_add' a b := by rw [map_add]; exact he.1.2.1 _ _
+ map_mul' a b := by rw [map_mul]; exact extreme_state_mul_tensor he rank _ _
+
+@[simp] theorem extremeStateHom_apply (he : f ∈ (states (orderCone toA H)).extremePoints ℝ)
+ (rank : S →+* ℕ) (s : S) : extremeStateHom he rank s = f (toA s) := rfl
+
+theorem monotone_extremeStateHom (he : f ∈ (states (orderCone toA H)).extremePoints ℝ)
+ (rank : S →+* ℕ) : Monotone (extremeStateHom he rank) := by
+ intro a b hab
+ let L := stateLinearMap he.1
+ have hp : toA b - toA a ∈ orderCone toA H := fractionPositive_difference hab
+ have h : 0 ≤ L (toA b - toA a) := he.1.2.2.2 _ hp
+ exact sub_nonneg.mp (by rwa [map_sub] at h)
+
+/-- Strict comparison at every spectral point places the corresponding
+difference inside the order cone of the localization. -/
+theorem fractionPositive_of_spectrum_lt (H : OrderBounds S)
+ (rank : S →+* ℕ) (hmono : Monotone rank) (x y : S)
+ (hlt : ∀ F : S →+* ℝ, Monotone F → F x < F y) :
+ FractionPositive toA (toA y - toA x) := by
+ let P := orderCone toA H
+ let z := toA y - toA x
+ change z ∈ P
+ by_contra hz
+ obtain ⟨L, hL1, hLp, hLz⟩ := separate_order_unit P 1 z (one_mem_orderCone H)
+ (neg_one_notMem_orderCone H rank hmono) (orderCone_bound H) hz
+ have hL : (⇑L : Spectral.A S → ℝ) ∈ states P :=
+ ⟨hL1, L.map_add, L.map_smul, hLp⟩
+ obtain ⟨f, he, hfle⟩ := exists_extreme_state_le P (orderCone_bound H) z hL
+ have hneg : f z ≤ 0 := hfle.trans hLz
+ have hpos := hlt (extremeStateHom he rank) (monotone_extremeStateHom he rank)
+ let g := stateLinearMap he.1
+ have hpos' : 0 < g (toA y) - g (toA x) := sub_pos.mpr hpos
+ rw [← map_sub] at hpos'
+ exact hpos'.not_ge hneg
+
+end Tensor
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralStates.lean b/lean/OAI/Computability/VPVNP/SpectralStates.lean
new file mode 100644
index 0000000000..9592588b5e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralStates.lean
@@ -0,0 +1,128 @@
+import Mathlib.Analysis.Convex.KreinMilman
+import Mathlib.Geometry.Convex.Cone.Pointed
+
+/-! # Extreme positive states in spectral comparison
+
+In Appendix A.1 the localization has an order unit. Its rational-linear
+positive functionals normalized at the unit form a compact subset of the
+space of real-valued functions, with the topology of pointwise convergence.
+An extreme such functional is multiplicative on the tensor generators.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+open Set
+
+variable {A : Type*} [CommRing A] [Algebra ℚ A]
+
+/-- Real-valued rational-linear functionals normalized to one at the unit and nonnegative on
+the specified cone. -/
+def states (P : PointedCone ℚ A) : Set (A → ℝ) :=
+ {f | f 1 = 1 ∧ (∀ x y, f (x + y) = f x + f y) ∧
+ (∀ (r : ℚ) x, f (r • x) = r • f x) ∧ ∀ x ∈ P, 0 ≤ f x}
+
+/-- The rational-linear map underlying a normalized positive state on the cone. -/
+def stateLinearMap {P : PointedCone ℚ A} {f : A → ℝ} (hf : f ∈ states P) : A →ₗ[ℚ] ℝ where
+ toFun := f
+ map_add' := hf.2.1
+ map_smul' := hf.2.2.1
+
+theorem states_isClosed (P : PointedCone ℚ A) : IsClosed (states P) := by
+ unfold states
+ simp only [ofPred_and, ofPred_forall]
+ refine (isClosed_eq (continuous_apply 1) continuous_const).inter ?_
+ refine (isClosed_iInter fun x => isClosed_iInter fun y => isClosed_eq
+ (continuous_apply (x + y)) (by fun_prop)).inter ?_
+ refine (isClosed_iInter fun (r : ℚ) => isClosed_iInter fun (x : A) =>
+ isClosed_eq (continuous_apply (r • x)) (by fun_prop)).inter ?_
+ exact isClosed_iInter fun (x : A) => isClosed_iInter fun (_ : x ∈ P) =>
+ isClosed_le continuous_const (continuous_apply x)
+
+theorem states_isCompact (P : PointedCone ℚ A)
+ (orderUnit : ∀ x : A, ∃ n : ℕ, n • (1 : A) + x ∈ P) : IsCompact (states P) := by
+ choose bound hb using orderUnit
+ refine (isCompact_univ_pi fun (x : A) =>
+ isCompact_Icc (a := -(bound x : ℝ)) (b := (bound (-x) : ℝ))).of_isClosed_subset
+ (states_isClosed P) ?_
+ intro f hf x _
+ let L := stateLinearMap hf
+ have h1 : L 1 = 1 := hf.1
+ have hpos (a : A) : 0 ≤ L (bound a • (1 : A) + a) := hf.2.2.2 _ (hb a)
+ have hlo := hpos x
+ have hhi := hpos (-x)
+ simp only [map_add, map_neg] at hlo hhi
+ rw [map_nsmul L, h1, nsmul_eq_mul, mul_one] at hlo hhi
+ change -(bound x : ℝ) ≤ L x ∧ L x ≤ bound (-x)
+ constructor <;> linarith
+
+/-- A minimizing face contains a state extreme in the original set. -/
+theorem exists_extreme_state_le (P : PointedCone ℚ A)
+ (orderUnit : ∀ x : A, ∃ n : ℕ, n • (1 : A) + x ∈ P)
+ (z : A) {f₀ : A → ℝ} (hf₀ : f₀ ∈ states P) :
+ ∃ f ∈ (states P).extremePoints ℝ, f z ≤ f₀ z := by
+ let s := states P
+ let face := {f ∈ s | ∀ g ∈ s, -g z ≤ -f z}
+ have exposed : IsExposed ℝ s face := fun _ => ⟨-ContinuousLinearMap.proj z, rfl⟩
+ have comp := states_isCompact P orderUnit
+ obtain ⟨g, hg, hmax⟩ := comp.exists_isMaxOn ⟨f₀, hf₀⟩ (continuous_apply z).neg.continuousOn
+ obtain ⟨f, h⟩ := (exposed.isCompact comp).extremePoints_nonempty ⟨g, hg, hmax⟩
+ exact ⟨f, exposed.isExtreme.extremePoints_subset_extremePoints h,
+ neg_le_neg_iff.mp (h.1.2 _ hf₀)⟩
+
+private theorem reweighted_state {P : PointedCone ℚ A} {f : A → ℝ} (hf : f ∈ states P)
+ (u : A) (hu : 0 < f u) (hstable : ∀ x ∈ P, u * x ∈ P) :
+ (fun x => f (u * x) / f u) ∈ states P := by
+ refine ⟨by simp [hu.ne'], fun x y => ?_, fun r x => ?_, fun x hx => ?_⟩
+ · dsimp only
+ rw [mul_add, hf.2.1, add_div]
+ · dsimp only
+ rw [mul_smul_comm, hf.2.2.1]
+ simp [Rat.smul_def, mul_div_assoc]
+ · exact div_nonneg (hf.2.2.2 _ (hstable x hx)) hu.le
+
+/-- Splitting the unit into two positive multipliers makes both reweighted
+states coincide with an extreme state. This is the multiplicativity step of A.1. -/
+theorem extreme_state_mul_of_split {P : PointedCone ℚ A} {f : A → ℝ}
+ (he : f ∈ (states P).extremePoints ℝ) {u v : A} (huv : u + v = 1)
+ (hu : 0 < f u) (hv : 0 < f v)
+ (su : ∀ x ∈ P, u * x ∈ P) (sv : ∀ x ∈ P, v * x ∈ P) :
+ (∀ x, f (u*x) = f u * f x) ∧ ∀ x, f (v*x) = f v * f x := by
+ let g := fun x => f (u*x) / f u
+ let h := fun x => f (v*x) / f v
+ have hf := he.1
+ have hg : g ∈ states P := reweighted_state hf u hu su
+ have hh : h ∈ states P := reweighted_state hf v hv sv
+ have hseg : f ∈ openSegment ℝ g h := by
+ refine ⟨f u, f v, hu, hv, by rw [← hf.2.1, huv, hf.1], ?_⟩
+ funext x
+ change f u * (f (u*x) / f u) + f v * (f (v*x) / f v) = f x
+ rw [mul_div_cancel₀ _ hu.ne', mul_div_cancel₀ _ hv.ne', ← hf.2.1, ← add_mul, huv, one_mul]
+ have fg := (mem_extremePoints_iff_left.mp he).2 _ hg _ hh hseg
+ have fh := (mem_extremePoints_iff_left.mp he).2 _ hh _ hg ((openSegment_symm ℝ g h) ▸ hseg)
+ constructor
+ · intro x
+ have hx : f (u*x) / f u = f x := congrFun fg x
+ exact (div_eq_iff hu.ne').mp hx |>.trans (mul_comm _ _)
+ · intro x
+ have hx : f (v*x) / f v = f x := congrFun fh x
+ exact (div_eq_iff hv.ne').mp hx |>.trans (mul_comm _ _)
+
+/-- If `v*s=u`, the split proves multiplicativity on the original element `s`. -/
+theorem extreme_state_mul_generator {P : PointedCone ℚ A} {f : A → ℝ}
+ (he : f ∈ (states P).extremePoints ℝ) {s u v : A} (huv : u+v=1) (hs : v*s=u)
+ (hu : 0 < f u) (hv : 0 < f v)
+ (su : ∀ x ∈ P, u*x ∈ P) (sv : ∀ x ∈ P, v*x ∈ P) (x : A) :
+ f (s*x) = f s * f x := by
+ obtain ⟨hmulu, hmulv⟩ := extreme_state_mul_of_split he huv hu hv su sv
+ apply mul_left_cancel₀ hv.ne'
+ rw [← hmulv, ← mul_assoc v s x, hs, hmulu, ← mul_assoc, ← hmulv, hs]
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralStrictComparison.lean b/lean/OAI/Computability/VPVNP/SpectralStrictComparison.lean
new file mode 100644
index 0000000000..fa36786485
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralStrictComparison.lean
@@ -0,0 +1,47 @@
+import OAI.Computability.VPVNP.SpectralCompactGap
+import OAI.Computability.VPVNP.SpectralStateHom
+import OAI.Computability.VPVNP.SpectralCatalyst
+
+/-!
+# Uniform comparison of powers from spectral separation
+
+A strict inequality at every point of the compact spectrum gives an integer
+margin. Detecting this stronger inequality in the rational order cone, clearing
+denominators, and removing additive slack gives a restriction with a single
+number of copies for all powers.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+variable {S : Type*} [CommSemiring S] [Preorder S] [NoZeroDivisors S] [Nontrivial S]
+
+/-- Lemma 2.1 in the ordered-semiring setting of Appendix A.1. A monotone
+natural-valued rank is a witness that the negative unit is outside the
+localized order cone. Strict comparison at every spectral point gives the
+same finite copy bound for all powers. -/
+theorem strict_spectral_comparison [CharZero S] (H : OrderBounds S)
+ (rank : S →+* ℕ) (hmono : Monotone rank)
+ {x y : S} (hy : y ≠ 0)
+ (h : ∀ F : S →+* ℝ, Monotone F → F x < F y) :
+ ∃ K : ℕ, 1 ≤ K ∧ ∀ m : ℕ, x ^ m ≤ (K : S) * y ^ m := by
+ have hs : ∀ F ∈ spectrumValues S, F x < F y := by
+ rintro _ ⟨F, hF, rfl⟩
+ exact h F hF
+ obtain ⟨b, hb⟩ := compact_strict_comparison_margin (spectrumValues_isCompact H) hs
+ have hm : ∀ F : S →+* ℝ, Monotone F →
+ F (((b : S) + 1) * x) < F ((b : S) * y) := by
+ intro F hF
+ simpa only [map_add, map_mul, map_one, map_natCast] using hb F ⟨F, hF, rfl⟩
+ obtain ⟨c, hc, w, hw⟩ := clear_comparison H (fractionPositive_of_spectrum_lt H rank hmono _ _ hm)
+ obtain ⟨D, hD, htrade⟩ := remove_additive_slack H hc hy b hw
+ exact catalyst_uniform_bound H hD htrade
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralTangent.lean b/lean/OAI/Computability/VPVNP/SpectralTangent.lean
new file mode 100644
index 0000000000..91206f5c10
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralTangent.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.WireGeodesic
+import OAI.Computability.VPVNP.ConfigurationCompletion
+import Mathlib.Topology.Instances.Real.Lemmas
+import Mathlib.Topology.Compactness.Compact
+
+/-!
+# Rescaling at a basepoint of a wire metric space
+
+Lemma 4.1 passes to a simultaneous limit of rescaled configurations. An
+ultrafilter tending to infinity takes that limit for all bounded marked
+sequences at once. Its pseudometric retains every finite configuration when
+the cone of spectral configurations is closed. Fractional points can be
+chosen term by term.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open Filter Set Topology
+
+variable {X : Type*} [PseudoMetricSpace X]
+
+/-- The rescaling factors at the successive terms of a marked sequence. -/
+def tangentScale (n : ℕ) : ℝ := n + 1
+
+theorem tangentScale_pos (n : ℕ) : 0 < tangentScale n := by unfold tangentScale; positivity
+
+/-- The filter used for simultaneous convergence of all marked distances. -/
+noncomputable def tangentFilter : Ultrafilter ℕ := Ultrafilter.of atTop
+
+theorem tangentFilter_le_atTop : (tangentFilter : Filter ℕ) ≤ atTop := Ultrafilter.of_le _
+
+/-- Sequences at uniformly bounded rescaled distance from the basepoint. -/
+structure Tangent (o : X) where
+ /-- Sequence of marked points whose rescaled distances to the basepoint have a common upper
+ bound. -/
+ point : ℕ → X
+ bounded : ∃ C : ℝ, ∀ n, tangentScale n * dist o (point n) ≤ C
+
+variable {o : X}
+
+private theorem bounded_pair (a b : Tangent o) :
+ ∃ C : ℝ, ∀ n, tangentScale n * dist (a.point n) (b.point n) ≤ C := by
+ obtain ⟨A, hA⟩ := a.bounded
+ obtain ⟨B, hB⟩ := b.bounded
+ refine ⟨A+B, fun n ↦ ?_⟩
+ have ht := mul_le_mul_of_nonneg_left (dist_triangle (a.point n) o (b.point n))
+ (tangentScale_pos n).le
+ rw [dist_comm (a.point n) o, mul_add] at ht
+ exact ht.trans (add_le_add (hA n) (hB n))
+
+private noncomputable def tangentDist (a b : Tangent o) : ℝ :=
+ limUnder tangentFilter (fun n ↦ tangentScale n * dist (a.point n) (b.point n))
+
+private theorem tangentDist_tendsto (a b : Tangent o) :
+ Tendsto (fun n ↦ tangentScale n * dist (a.point n) (b.point n)) tangentFilter
+ (𝓝 (tangentDist a b)) := by
+ obtain ⟨C, hC⟩ := bounded_pair a b
+ let d (n : ℕ) := tangentScale n * dist (a.point n) (b.point n)
+ have hI : Icc (0 : ℝ) C ∈ tangentFilter.map d := by
+ change ∀ᶠ n : ℕ in (tangentFilter : Filter ℕ), d n ∈ Icc 0 C
+ exact Eventually.of_forall fun n ↦ ⟨mul_nonneg (tangentScale_pos n).le dist_nonneg, hC n⟩
+ obtain ⟨v, _, hv⟩ := isCompact_Icc.ultrafilter_le_nhds' (tangentFilter.map d) hI
+ exact tendsto_nhds_limUnder ⟨v, hv⟩
+
+noncomputable instance (o : X) : PseudoMetricSpace (Tangent o) where
+ dist := tangentDist
+ dist_self a := (tendsto_nhds_unique (tangentDist_tendsto a a) (by simp))
+ dist_comm a b := by simp only [tangentDist, dist_comm (a.point _) (b.point _)]
+ dist_triangle a b c := le_of_tendsto_of_tendsto (tangentDist_tendsto a c)
+ ((tangentDist_tendsto a b).add (tangentDist_tendsto b c)) <| Eventually.of_forall fun n ↦ by
+ simpa only [Pi.add_apply, ← mul_add] using
+ mul_le_mul_of_nonneg_left (dist_triangle (a.point n) (b.point n) (c.point n))
+ (tangentScale_pos n).le
+
+/-- Rescaled distances converge to the distance in the tangent pseudometric. -/
+theorem tangent_dist_tendsto (a b : Tangent o) :
+ Tendsto (fun n ↦ tangentScale n * dist (a.point n) (b.point n)) tangentFilter (𝓝 (dist a b)) :=
+ tangentDist_tendsto a b
+
+theorem tangent_dist_eq_of_tendsto {a b : Tangent o} {v : ℝ}
+ (h : Tendsto (fun n ↦ tangentScale n * dist (a.point n) (b.point n)) atTop (𝓝 v)) :
+ dist a b = v :=
+ tendsto_nhds_unique (tangent_dist_tendsto a b) (h.mono_left tangentFilter_le_atTop)
+
+/-- A geodesic fraction can be taken independently at each term. -/
+theorem tangent_hasFractions (hf : HasFractions X) (o : X) : HasFractions (Tangent o) := by
+ intro a b t ht ht'
+ choose p hp using fun n ↦ hf (a.point n) (b.point n) t ht ht'
+ obtain ⟨A, hA⟩ := a.bounded
+ obtain ⟨C, hC⟩ := bounded_pair a b
+ have hbounded (n : ℕ) : tangentScale n * dist o (p n) ≤ A + t*C := by
+ have htri := mul_le_mul_of_nonneg_left (dist_triangle o (a.point n) (p n)) (tangentScale_pos n).le
+ rw [mul_add, (hp n).1, mul_left_comm] at htri
+ exact htri.trans (add_le_add (hA n) (mul_le_mul_of_nonneg_left (hC n) ht))
+ let q : Tangent o := ⟨p, A+t*C, hbounded⟩
+ refine ⟨q, ?_, ?_⟩
+ · apply tendsto_nhds_unique (tangent_dist_tendsto a q)
+ exact ((tangent_dist_tendsto a b).const_mul t).congr fun n ↦ by simp [q, (hp n).1, mul_left_comm]
+ · apply tendsto_nhds_unique (tangent_dist_tendsto q b)
+ exact ((tangent_dist_tendsto a b).const_mul (1-t)).congr fun n ↦ by simp [q, (hp n).2, mul_left_comm]
+
+/-- Finite configurations pass to the tangent space by closedness of each
+realizable cone. The common positive scale absorbs the rescaling factor. -/
+theorem tangent_realizableConfigurations {k : Type*} [Field k]
+ (h : RealizableConfigurations k X) (o : X) : RealizableConfigurations k (Tangent o) := by
+ intro n p
+ apply (WireTensor.RealizableUpToScale.isClosed (k := k) (ι := Fin n)).mem_of_tendsto (f := fun i a b ↦
+ tangentScale i * dist ((p a).point i) ((p b).point i)) (b := (tangentFilter : Filter ℕ))
+ · exact tendsto_pi_nhds.mpr fun a ↦ tendsto_pi_nhds.mpr fun b ↦ tangent_dist_tendsto _ _
+ · exact Eventually.of_forall fun i ↦ (h n (fun a ↦ (p a).point i)).smul (tangentScale_pos i)
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectralTangentRay.lean b/lean/OAI/Computability/VPVNP/SpectralTangentRay.lean
new file mode 100644
index 0000000000..fd7d22e821
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectralTangentRay.lean
@@ -0,0 +1,160 @@
+import OAI.Computability.VPVNP.SpectralTangent
+import OAI.Computability.VPVNP.FractionalGeodesic
+import Mathlib.Tactic.FieldSimp
+
+/-!
+# Rays in the rescaled tangent space
+
+The rescaling of three geodesic segments in Lemma 4.1 produces rays. For
+each pair with common origin their equal-parameter distance is exactly
+linear, with slope the infimum of the original positive-parameter ratios.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open Filter Set Topology
+
+variable {X : Type*} [MetricSpace X]
+
+/-- A constant-speed geodesic on the unit interval, represented by a total
+function on the real line for the coordinate sector constructions. -/
+structure RadialSegment (o x : X) where
+ /-- Parametrized path that runs at constant speed from the basepoint at zero to its endpoint
+ at one. -/
+ path : ℝ → X
+ start : path 0 = o
+ finish : path 1 = x
+ speed : ∀ r ∈ Icc (0 : ℝ) 1, ∀ s ∈ Icc (0 : ℝ) 1,
+ dist (path r) (path s) = dist o x * |r-s|
+
+theorem exists_radialSegment (hf : HasFractions X) (hT : FractionTransport X) (o x : X) :
+ Nonempty (RadialSegment o x) := by
+ obtain ⟨g, hg0, hg1, hg⟩ := SpectralGeometry.exists_constantSpeedSegment
+ (fun a b t ↦ by
+ obtain ⟨z, hz⟩ := hf a b t t.property.1 t.property.2
+ exact ⟨z, hz, fun w hw ↦ atFraction_unique hT t.property.1 t.property.2 hw hz⟩) o x
+ let p (t : ℝ) := if h : t ∈ Icc (0 : ℝ) 1 then g ⟨t,h⟩ else o
+ refine ⟨⟨p, ?_, ?_, ?_⟩⟩
+ · simpa [p] using hg0
+ · simpa [p] using hg1
+ · intro r hr s hs
+ simpa only [p, dite_eq_left hr, dite_eq_left hs, mul_comm] using hg ⟨r,hr⟩ ⟨s,hs⟩
+
+variable {o x y : X}
+
+private theorem RadialSegment.origin_dist (a : RadialSegment o x) (r : ℝ) (hr : r ∈ Icc (0:ℝ) 1) :
+ dist o (a.path r) = r * dist o x := by
+ simpa only [zero_sub, abs_neg, abs_of_nonneg hr.1, a.start, mul_comm] using a.speed 0 (by simp) r hr
+
+private theorem RadialSegment.fraction (a : RadialSegment o x) {s t : ℝ} (hs : 0 ≤ s)
+ (hst : s ≤ t) (ht : 0 < t) (ht' : t ≤ 1) : AtFraction o (a.path t) (s/t) (a.path s) := by
+ have hs' : s ∈ Icc (0:ℝ) 1 := ⟨hs, hst.trans ht'⟩
+ have htI : t ∈ Icc (0:ℝ) 1 := ⟨ht.le, ht'⟩
+ constructor
+ · rw [a.origin_dist _ hs', a.origin_dist _ htI]
+ field_simp
+ · rw [a.speed s hs' t htI, a.origin_dist _ htI, abs_of_nonpos (sub_nonpos.mpr hst)]
+ field_simp
+ ring
+
+theorem radial_ratio_mono (hT : FractionTransport X) (a : RadialSegment o x) (b : RadialSegment o y) :
+ MonotoneOn (fun t ↦ dist (a.path t) (b.path t) / t) (Ioc 0 1) := by
+ intro s hs t ht hst
+ have h := hT (div_nonneg hs.1.le ht.1.le) ((div_le_one ht.1).mpr hst)
+ (a.fraction hs.1.le hst ht.1 ht.2) (b.fraction hs.1.le hst ht.1 ht.2)
+ rw [dist_self, mul_zero, zero_add] at h
+ apply (div_le_iff₀ hs.1).mpr
+ convert h using 1
+ ring
+
+/-- The speed of separation in the tangent cone. -/
+noncomputable def radialSlope (a : RadialSegment o x) (b : RadialSegment o y) : ℝ :=
+ sInf ((fun t ↦ dist (a.path t) (b.path t)/t) '' Ioc 0 1)
+
+theorem radialSlope_le_ratio (a : RadialSegment o x) (b : RadialSegment o y) {t : ℝ} (ht : t ∈ Ioc 0 1) :
+ radialSlope a b ≤ dist (a.path t) (b.path t)/t := by
+ apply csInf_le _ (mem_image_of_mem _ ht)
+ exact ⟨0, fun _ ⟨s, hs, h⟩ ↦ h ▸ div_nonneg dist_nonneg hs.1.le⟩
+
+theorem radialSlope_le_dist (a : RadialSegment o x) (b : RadialSegment o y) :
+ radialSlope a b ≤ dist x y := by
+ simpa only [a.finish, b.finish, div_one] using
+ radialSlope_le_ratio a b (t := 1) ⟨zero_lt_one, le_rfl⟩
+
+private noncomputable def rayValue (a : RadialSegment o x) (r : ℝ) (n : ℕ) : X :=
+ if r / tangentScale n ∈ Icc 0 1 then a.path (r / tangentScale n) else o
+
+/-- Rescaling a segment produces a ray defined at every nonnegative time. -/
+noncomputable def tangentRay (a : RadialSegment o x) (r : ℝ) : Tangent o := by
+ refine ⟨rayValue a r, max 0 r * dist o x, fun n ↦ ?_⟩
+ unfold rayValue
+ split_ifs with ht
+ · rw [a.origin_dist _ ht, ← mul_assoc, mul_div_cancel₀ r (tangentScale_pos n).ne']
+ exact mul_le_mul_of_nonneg_right (le_max_right _ _) dist_nonneg
+ · simp only [dist_self, mul_zero]
+ exact mul_nonneg (le_max_left _ _) dist_nonneg
+
+private theorem parameter_eventually (r : ℝ) (hr : 0 ≤ r) :
+ ∀ᶠ n : ℕ in atTop, r / tangentScale n ∈ Icc 0 1 := by
+ filter_upwards [tendsto_natCast_atTop_atTop.eventually_ge_atTop r] with n hn
+ exact ⟨div_nonneg hr (tangentScale_pos n).le, (div_le_one (tangentScale_pos n)).mpr
+ (by unfold tangentScale; linarith)⟩
+
+/-- The ray inherits the speed of its original segment. -/
+theorem tangentRay_speed (a : RadialSegment o x) {r s : ℝ} (hr : 0 ≤ r) (hs : 0 ≤ s) :
+ dist (tangentRay a r) (tangentRay a s) = dist o x * |r-s| := by
+ apply tangent_dist_eq_of_tendsto
+ apply tendsto_const_nhds.congr'
+ filter_upwards [parameter_eventually r hr, parameter_eventually s hs] with n hnr hns
+ change _ = tangentScale n * dist (rayValue a r n) (rayValue a s n)
+ rw [rayValue, rayValue, ite_eq_left hnr, ite_eq_left hns, a.speed _ hnr _ hns,
+ ← sub_div, abs_div, abs_of_pos (tangentScale_pos n)]
+ field_simp [(tangentScale_pos n).ne']
+
+/-- The distance between two rays at time `r` is exactly `r` times their
+common infinitesimal separation. -/
+theorem tangentRay_cross (hT : FractionTransport X) (a : RadialSegment o x) (b : RadialSegment o y)
+ {r : ℝ} (hr : 0 ≤ r) : dist (tangentRay a r) (tangentRay b r) = radialSlope a b * r := by
+ rcases eq_or_lt_of_le hr with rfl | hr
+ · apply tangent_dist_eq_of_tendsto
+ simp [tangentRay, rayValue, a.start, b.start]
+ let d := dist (tangentRay a r) (tangentRay b r)
+ have hd := tangent_dist_tendsto (tangentRay a r) (tangentRay b r)
+ let q := fun t ↦ dist (a.path t) (b.path t)/t
+ have heq : ∀ᶠ n : ℕ in (tangentFilter : Filter ℕ),
+ tangentScale n * dist ((tangentRay a r).point n) ((tangentRay b r).point n) =
+ r * q (r / tangentScale n) := by
+ filter_upwards [tangentFilter_le_atTop (parameter_eventually r hr.le)] with n ht
+ simp only [tangentRay, rayValue, ite_eq_left ht, q]
+ field_simp [hr.ne']
+ have hlim : Tendsto (fun n ↦ r * q (r / tangentScale n)) tangentFilter (𝓝 d) := hd.congr' heq
+ apply le_antisymm
+ · rw [← div_le_iff₀ hr]
+ apply le_csInf (image_nonempty.mpr (nonempty_Ioc.mpr zero_lt_one))
+ rintro _ ⟨t, ht, rfl⟩
+ apply (div_le_iff₀ hr).mpr
+ apply le_of_tendsto hlim
+ have htend : ∀ᶠ n : ℕ in atTop, r / tangentScale n ≤ t := by
+ filter_upwards [tendsto_natCast_atTop_atTop.eventually_ge_atTop (r / t)] with n hn
+ apply (div_le_iff₀ (tangentScale_pos n)).mpr
+ have := (div_le_iff₀ ht.1).mp hn
+ unfold tangentScale
+ nlinarith only [this, ht.1.le]
+ filter_upwards [tangentFilter_le_atTop htend, tangentFilter_le_atTop (parameter_eventually r hr.le)]
+ with n hn hi
+ exact (mul_le_mul_of_nonneg_left (radial_ratio_mono hT a b ⟨div_pos hr (tangentScale_pos n), hi.2⟩ ht hn)
+ hr.le).trans_eq (mul_comm _ _)
+ · rw [mul_comm]
+ apply ge_of_tendsto hlim
+ filter_upwards [tangentFilter_le_atTop (parameter_eventually r hr.le)] with n hn
+ exact mul_le_mul_of_nonneg_left (radialSlope_le_ratio a b ⟨div_pos hr (tangentScale_pos n), hn.2⟩) hr.le
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SpectrumCompactness.lean b/lean/OAI/Computability/VPVNP/SpectrumCompactness.lean
new file mode 100644
index 0000000000..42d7e66078
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SpectrumCompactness.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.WireSpectrum
+
+/-!
+# Compactness of the tensor spectrum
+
+Section 2 of *VP and VNP differ over every field* uses the topology of
+pointwise convergence on spectral points. Their defining equations and
+restriction inequalities cut out a closed subset of a product of compact
+intervals. The upper endpoints are the coordinate rank bounds.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+
+open scoped NNReal
+open Set
+
+namespace WireTensor.SpectralPoint
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J]
+
+/-- The defining conditions of spectral points are closed under pointwise limits. -/
+theorem isClosed_range_value : IsClosed (range (value (k := k) (J := J))) := by
+ let A := Tensor.{u,v,0} k J
+ have hrange : range (value (k := k) (J := J)) =
+ {f : A → ℝ≥0 | (∀ Y X, Restricts Y X → f X ≤ f Y) ∧ f unit = 1 ∧
+ (∀ T, T.coeff = 0 → f T = 0) ∧
+ (∀ T U, f (directSum T U) = f T + f U) ∧
+ (∀ T U, f (tensorProduct T U) = f T * f U)} := by
+ ext f
+ constructor
+ · rintro ⟨F, rfl⟩
+ exact ⟨fun _ _ h ↦ F.monotone h, F.value_unit, F.value_zero,
+ F.value_directSum, F.value_tensorProduct⟩
+ · rintro ⟨hm, hu, hz, hs, hp⟩
+ exact ⟨⟨f, fun {Y X} ↦ hm Y X, hu, hz, hs, hp⟩, rfl⟩
+ rw [hrange]
+ simp only [ofPred_and, ofPred_forall]
+ refine (isClosed_iInter fun Y ↦ isClosed_iInter fun X ↦ isClosed_iInter fun _ ↦
+ isClosed_le (continuous_apply X) (continuous_apply Y)).inter ?_
+ refine (isClosed_eq (continuous_apply unit) continuous_const).inter ?_
+ refine (isClosed_iInter fun T ↦ isClosed_iInter fun _ ↦
+ isClosed_eq (continuous_apply T) continuous_const).inter ?_
+ exact (isClosed_iInter fun T ↦ isClosed_iInter fun U ↦ isClosed_eq
+ (continuous_apply (directSum T U)) ((continuous_apply T).add (continuous_apply U))).inter
+ (isClosed_iInter fun T ↦ isClosed_iInter fun U ↦ isClosed_eq
+ (continuous_apply (tensorProduct T U)) ((continuous_apply T).mul (continuous_apply U)))
+
+/-- The spectrum of tensors on a finite nonempty party set is compact for the
+topology of pointwise convergence. -/
+theorem isCompact_range_value [Nonempty J] : IsCompact (range (value (k := k) (J := J))) := by
+ let bound (T : Tensor.{u,v,0} k J) : ℝ≥0 := ↑(∏ j, Fintype.card (T.Basis j) : ℕ)
+ have hc := isCompact_pi_infinite (fun T ↦ isCompact_Icc (a := (0 : ℝ≥0)) (b := bound T))
+ apply hc.of_isClosed_subset isClosed_range_value
+ rintro _ ⟨F, rfl⟩ T
+ exact ⟨zero_le, F.value_le_basis_product T⟩
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SplitWireExtension.lean b/lean/OAI/Computability/VPVNP/SplitWireExtension.lean
new file mode 100644
index 0000000000..4aa40053fc
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SplitWireExtension.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.SplitWires
+import OAI.Computability.VPVNP.TensorExtensionMatching
+import OAI.Computability.VPVNP.TensorFlatteningPoint
+import OAI.Computability.VPVNP.WireGeodesic
+import Mathlib.Analysis.SpecialFunctions.Log.Base
+
+/-!
+# Prescribing both distances to a new party
+
+For the two new generators of Theorem 2.4(1), the contraction supremum of
+any monomial is at most its prescribed value. Equal exponents on the two
+new generators give equality at every power.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+
+namespace WireTensor.SpectralPoint
+
+open RestrictionClass Filter
+open scoped Topology
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nonempty J]
+variable (F : SpectralPoint k J)
+
+private noncomputable def splitWireClass (a b : J) (i : Bool) : RestrictionClass k (Option J) :=
+ ofTensor (wire none (some (if i then b else a)) (Fin 2))
+
+private noncomputable def splitWireTarget (l₁ l₂ : ℝ) (i : Bool) : ℝ :=
+ (2 : ℝ) ^ (if i then l₂ else l₁)
+
+private theorem splitWireTarget_mul (l₁ l₂ : ℝ) (u v : ℕ) :
+ splitWireTarget l₁ l₂ false ^ u * splitWireTarget l₁ l₂ true ^ v =
+ (2 : ℝ) ^ ((u : ℝ) * l₁ + (v : ℝ) * l₂) := by
+ simp only [splitWireTarget, Bool.false_eq_true, ↓reduceIte]
+ rw [← Real.rpow_mul_natCast (by norm_num), ← Real.rpow_mul_natCast (by norm_num),
+ ← Real.rpow_add (by norm_num)]
+ congr 1
+ ring
+
+private theorem splitClass_upper (a b : J) {l₁ l₂ : ℝ} (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂)
+ (hs : l₁ + l₂ = F.wireDistance a b) (x : RestrictionClass k J) (u v : ℕ) :
+ F.contractionClassValue (embedOldClass x * (splitWireClass a b false ^ u *
+ splitWireClass a b true ^ v)) ≤
+ ofSpectralPoint F x * (splitWireTarget l₁ l₂ false ^ u * splitWireTarget l₁ l₂ true ^ v) := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ simp only [splitWireClass, Bool.false_eq_true, ↓reduceIte, ← ofTensor_binarySplit,
+ embedOldClass_ofTensor, ← ofTensor_tensorProduct, F.contractionClassValue_ofTensor,
+ ofSpectralPoint_ofTensor, splitWireTarget_mul]
+ exact F.contractionValue_binarySplit_monomial_le T a b u v h₁ h₂ hs
+
+private theorem splitClass_balanced (a b : J) {l₁ l₂ : ℝ} (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂)
+ (hs : l₁ + l₂ = F.wireDistance a b) (x : RestrictionClass k J) (e : ℕ) :
+ F.contractionClassValue (embedOldClass x * (splitWireClass a b false ^ e *
+ splitWireClass a b true ^ e)) =
+ ofSpectralPoint F x * (splitWireTarget l₁ l₂ false ^ e * splitWireTarget l₁ l₂ true ^ e) := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ simp only [splitWireClass, Bool.false_eq_true, ↓reduceIte, ← ofTensor_binarySplit,
+ embedOldClass_ofTensor, ← ofTensor_tensorProduct, F.contractionClassValue_ofTensor,
+ ofSpectralPoint_ofTensor, splitWireTarget_mul]
+ exact F.contractionValue_binarySplit_monomial_eq T a b e h₁ h₂ hs
+
+private theorem splitClass_power (a b : J) {l₁ l₂ : ℝ} (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂)
+ (hs : l₁ + l₂ = F.wireDistance a b) (x : RestrictionClass k J) (e m : ℕ) :
+ F.contractionClassValue ((embedOldClass x * (splitWireClass a b false ^ e *
+ splitWireClass a b true ^ e)) ^ m) =
+ (ofSpectralPoint F x * (splitWireTarget l₁ l₂ false ^ e * splitWireTarget l₁ l₂ true ^ e)) ^ m := by
+ simpa only [mul_pow, ← pow_mul, map_pow] using
+ F.splitClass_balanced a b h₁ h₂ hs (x ^ m) (e * m)
+
+private theorem splitWireClass_ne_zero (a b : J) (i : Bool) :
+ splitWireClass (k := k) a b i ≠ 0 := by
+ let W := wire (k := k) none (some (if i then b else a)) (Fin 2)
+ change ofTensor W ≠ 0
+ intro hz
+ have he := congrFun ((ofTensor_eq_zero_iff _).mp hz) (fun _ ↦ (fun _ ↦ 0, fun _ ↦ 0))
+ have h : W.coeff (fun _ ↦ (fun _ ↦ 0, fun _ ↦ 0)) ≠ 0 := by simp [W, wire]
+ exact h he
+
+private theorem splitClass_upper_prod (a b : J) {l₁ l₂ : ℝ} (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂)
+ (hs : l₁ + l₂ = F.wireDistance a b) (x : RestrictionClass k J) (n : Bool → ℕ) :
+ F.contractionClassValue (embedOldClass x * ∏ i, splitWireClass a b i ^ n i) ≤
+ ofSpectralPoint F x * ∏ i, splitWireTarget l₁ l₂ i ^ n i := by
+ simp only [Fintype.prod_bool]
+ rw [mul_comm (splitWireClass a b true ^ _), mul_comm (splitWireTarget l₁ l₂ true ^ _)]
+ exact F.splitClass_upper a b h₁ h₂ hs x (n false) (n true)
+
+private theorem splitClass_limit (a b : J) {l₁ l₂ : ℝ} (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂)
+ (hs : l₁ + l₂ = F.wireDistance a b) (x : RestrictionClass k J) (e : ℕ) :
+ Tendsto (fun m : ℕ ↦
+ F.contractionClassValue ((embedOldClass x * ∏ i, splitWireClass a b i ^ e) ^ m) ^ (m : ℝ)⁻¹)
+ atTop (𝓝 (ofSpectralPoint F x * ∏ i, splitWireTarget l₁ l₂ i ^ e)) := by
+ simp only [Fintype.prod_bool]
+ rw [mul_comm (splitWireClass a b true ^ _), mul_comm (splitWireTarget l₁ l₂ true ^ _)]
+ apply tendsto_const_nhds.congr'
+ filter_upwards [eventually_gt_atTop (0 : ℕ)] with m hm
+ rw [F.splitClass_power a b h₁ h₂ hs x e m]
+ symm
+ apply Real.pow_rpow_inv_natCast _ hm.ne'
+ have hx : 0 ≤ ofSpectralPoint F x := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ exact NNReal.coe_nonneg _
+ exact mul_nonneg hx (mul_nonneg (pow_nonneg (Real.rpow_nonneg (by norm_num) _) _)
+ (pow_nonneg (Real.rpow_nonneg (by norm_num) _) _))
+
+/-- A spectral value prescribed as a power of two fixes the corresponding wire distance. -/
+private theorem wireDistance_eq_of_target {J' : Type*} [Fintype J'] (H : SpectralPoint k J')
+ (i j : J') (l : ℝ) (h : (H.value (wire i j (Fin 2)) : ℝ) = (2 : ℝ) ^ l) :
+ H.wireDistance i j = l := by
+ change Real.log (H.value (wire i j (Fin 2))) / Real.log 2 = l
+ rw [h, Real.log_rpow (by norm_num), mul_div_cancel_right₀ _ (Real.log_pos (by norm_num)).ne']
+
+omit [Nonempty J] in
+/-- Theorem 2.4(1). An added party can realize prescribed nonnegative portions of
+the old wire distance while preserving the value of every old tensor. -/
+theorem exists_split_extension (a b : J) {l₁ l₂ : ℝ} (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂)
+ (hs : l₁ + l₂ = F.wireDistance a b) :
+ ∃ H : SpectralPoint k (Option J), (∀ T, H.value (embedOld T) = F.value T) ∧
+ H.wireDistance (some a) none = l₁ ∧ H.wireDistance none (some b) = l₂ := by
+ let : Nonempty J := ⟨a⟩
+ obtain ⟨H, hold, hmatch⟩ := F.exists_extension_matching_of_rank
+ (flatteningRankHom (k := k) (none : Option J)) (flatteningRankHom_monotone _)
+ (splitWireClass a b) (splitWireTarget l₁ l₂) (splitWireClass_ne_zero a b)
+ (fun _ ↦ Real.rpow_pos_of_pos (by norm_num) _) (F.splitClass_upper_prod a b h₁ h₂ hs)
+ (fun x e _ ↦ F.splitClass_limit a b h₁ h₂ hs x e)
+ refine ⟨H, hold, ?_, wireDistance_eq_of_target H _ _ _ (hmatch true)⟩
+ rw [H.wireDistance_comm]
+ exact wireDistance_eq_of_target H _ _ _ (hmatch false)
+
+omit [Nonempty J] in
+/-- The fractional-point form of exact extension, used when adjoining points
+for the geodesic completion in Corollary 2.5. -/
+theorem exists_fraction_extension (a b : J) {t : ℝ} (ht : 0 ≤ t) (ht' : t ≤ 1) :
+ ∃ H : SpectralPoint k (Option J), (∀ T, H.value (embedOld T) = F.value T) ∧
+ @WireGeometry.AtFraction (Option J) H.wirePseudoMetric (some a) (some b) t none := by
+ have hd := F.wireDistance_nonneg a b
+ obtain ⟨H, hold, hleft, hright⟩ := F.exists_split_extension a b
+ (mul_nonneg ht hd) (mul_nonneg (sub_nonneg.mpr ht') hd) (by ring)
+ refine ⟨H, hold, ?_⟩
+ change H.wireDistance (some a) none = t * H.wireDistance (some a) (some b) ∧
+ H.wireDistance none (some b) = (1 - t) * H.wireDistance (some a) (some b)
+ rw [F.wireDistance_extension H hold]
+ exact ⟨hleft, hright⟩
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SplitWires.lean b/lean/OAI/Computability/VPVNP/SplitWires.lean
new file mode 100644
index 0000000000..65757765fd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SplitWires.lean
@@ -0,0 +1,290 @@
+import OAI.Computability.VPVNP.ContractionValue
+import OAI.Computability.VPVNP.StarEmbedding
+import OAI.Computability.VPVNP.MatrixWire
+import OAI.Computability.VPVNP.WireSpectrum
+import Mathlib.LinearAlgebra.Matrix.Rank
+
+/-!
+# Contraction of a split pair of wires
+
+In the first case of Theorem 2.4 of *VP and VNP differ over every field*,
+the added party is the common endpoint of two bundles of binary wires.
+Contracting with one covector gives a rectangular matrix on the old parties.
+The identity covector on equal-size bundles recovers the old equality wire.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v w
+
+namespace WireTensor
+
+variable {k : Type u} {J : Type v} [CommSemiring k]
+
+/-- Two wire bundles with a common new endpoint and outside endpoints `a` and `b`. -/
+noncomputable def splitWires (a b : J) (I K : Type w) [Fintype I] [Fintype K] :
+ Tensor k (Option J) :=
+ tensorProduct (wire none (some a) I) (wire none (some b) K)
+
+/-- The center keeps one independent index for each bundle. -/
+def splitCenterEquiv (a b : J) (I K : Type w) [Fintype I] [Fintype K] :
+ I × K ≃ (splitWires (k := k) a b I K).Basis none where
+ toFun z := ((fun _ ↦ z.1, fun h ↦ nomatch h), (fun _ ↦ z.2, fun h ↦ nomatch h))
+ invFun z := (z.1.1 rfl, z.2.1 rfl)
+ left_inv _ := rfl
+ right_inv z := by
+ apply Prod.ext <;> apply Prod.ext <;> funext h
+ all_goals first | rfl | cases h
+
+/-- The old legs keep just the corresponding outside endpoint indices. -/
+def splitLeafEquiv (a b : J) (I K : Type w) [Fintype I] [Fintype K] (j : J) :
+ (j = a → I) × (j = b → K) ≃ (splitWires (k := k) a b I K).Basis (some j) where
+ toFun z := (((fun h : some j = none ↦ nomatch h), fun h ↦ z.1 (Option.some.inj h)),
+ ((fun h : some j = none ↦ nomatch h), fun h ↦ z.2 (Option.some.inj h)))
+ invFun z := (fun h ↦ z.1.2 (congrArg some h), fun h ↦ z.2.2 (congrArg some h))
+ left_inv _ := rfl
+ right_inv z := by
+ apply Prod.ext <;> apply Prod.ext <;> funext h
+ all_goals first | rfl | cases h
+
+/-- In endpoint bases a covector is a rectangular matrix of independent entries. -/
+def splitMatrix (a b : J) (I K : Type w) [Fintype I] [Fintype K]
+ (ξ : (splitWires (k := k) a b I K).Basis none → k) : Matrix I K k :=
+ fun i j ↦ ξ (splitCenterEquiv a b I K (i, j))
+
+/-- Exact readout of the matrix supplied by the center covector. -/
+theorem contractCenter_splitWires_coeff (a b : J) (I K : Type w) [Fintype I] [Fintype K]
+ (ξ : (splitWires (k := k) a b I K).Basis none → k)
+ (x : (j : J) → (splitWires (k := k) a b I K).Basis (some j)) :
+ (contractCenter (splitWires a b I K) ξ).coeff x =
+ splitMatrix a b I K ξ ((x a).1.2 rfl) ((x b).2.2 rfl) := by
+ classical
+ let f (c : (splitWires (k := k) a b I K).Basis none) :=
+ ξ c * (splitWires (k := k) a b I K).coeff (withCenter c x)
+ change (∑ c, f c) = _
+ rw [← (splitCenterEquiv (k := k) a b I K).sum_comp f, Fintype.sum_prod_type]
+ change (∑ i : I, ∑ j : K, ξ (splitCenterEquiv a b I K (i, j)) *
+ ((if i = (x a).1.2 rfl then 1 else 0) * if j = (x b).2.2 rfl then 1 else 0)) = _
+ simp [mul_ite, splitMatrix]
+
+/-- A tensor power of an equality wire is one wire whose index is the tuple
+of the individual edge indices. -/
+theorem wire_power_mutual [Fintype J] (a b : J) (I : Type w) [Fintype I] (n : ℕ) :
+ Restricts (wire (k := k) a b (Fin n → I)) (tensorPowerFin n (wire a b I)) ∧
+ Restricts (tensorPowerFin n (wire (k := k) a b I)) (wire a b (Fin n → I)) := by
+ classical
+ let e (j : J) : (Fin n → (j = a → I) × (j = b → I)) ≃
+ (j = a → Fin n → I) × (j = b → Fin n → I) :=
+ { toFun := fun z ↦ (fun h i ↦ (z i).1 h, fun h i ↦ (z i).2 h)
+ invFun := fun z i ↦ (fun h ↦ z.1 h i, fun h ↦ z.2 h i)
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ apply restricts_of_reindex e
+ intro x
+ simp only [tensorPowerFin, wire, Fintype.prod_boole, funext_iff]
+ split_ifs <;> first | rfl | contradiction
+
+/-- The split monomial before regrouping the parallel binary factors. -/
+noncomputable def binarySplit (a b : J) (u v : ℕ) : Tensor.{u,v,0} k (Option J) :=
+ tensorProduct (tensorPowerFin u (wire none (some a) (Fin 2)))
+ (tensorPowerFin v (wire none (some b) (Fin 2)))
+
+/-- Regrouping powers of two binary wires into the two dyadic bundles. -/
+theorem binary_splitWires_mutual [Fintype J] (a b : J) (u v : ℕ) :
+ let M := binarySplit (k := k) a b u v
+ let S := splitWires (k := k) a b (Fin (2 ^ u)) (Fin (2 ^ v))
+ Restricts S M ∧ Restricts M S := by
+ classical
+ have bundle (j : J) (n : ℕ) :
+ let W := wire (k := k) none (some j) (Fin (2 ^ n))
+ let P := tensorPowerFin n (wire (k := k) none (some j) (Fin 2))
+ Restricts W P ∧ Restricts P W := by
+ let e : (Fin n → Fin 2) ≃ Fin (2 ^ n) := Fintype.equivOfCardEq (by simp)
+ have h := wire_power_mutual (k := k) none (some j) (Fin 2) n
+ exact ⟨(wire_restricts_of_embedding _ _ e.toEmbedding).trans h.1,
+ h.2.trans (wire_restricts_of_embedding _ _ e.symm.toEmbedding)⟩
+ exact ⟨(bundle a u).1.tensorProduct (bundle b v).1, (bundle a u).2.tensorProduct (bundle b v).2⟩
+
+/-- Contraction gives exactly the matrix tensor after local basis changes at the leaves. -/
+theorem splitWires_matrix_mutual [Fintype J] (a b : J) (I K : Type w) [Fintype I] [Fintype K]
+ (ξ : (splitWires (k := k) a b I K).Basis none → k) :
+ let T := contractCenter (splitWires a b I K) ξ
+ let M := matrixTensor a b (splitMatrix a b I K ξ)
+ Restricts T M ∧ Restricts M T := by
+ apply restricts_of_reindex (splitLeafEquiv a b I K)
+ intro x
+ exact (contractCenter_splitWires_coeff a b I K ξ (fun j ↦ splitLeafEquiv a b I K j (x j))).symm
+
+/-- Conversely every matrix on the two outside endpoints occurs as a center contraction. -/
+theorem exists_splitWires_matrix [Fintype J] (a b : J) {I K : Type w} [Fintype I] [Fintype K]
+ (M : Matrix I K k) :
+ ∃ ξ, Restricts (contractCenter (splitWires a b I K) ξ) (matrixTensor a b M) ∧
+ Restricts (matrixTensor a b M) (contractCenter (splitWires a b I K) ξ) := by
+ let e := splitCenterEquiv (k := k) a b I K
+ let ξ := fun c ↦ M (e.symm c).1 (e.symm c).2
+ have hM : splitMatrix a b I K ξ = M := by
+ ext i j
+ change M (e.symm (e (i, j))).1 (e.symm (e (i, j))).2 = M i j
+ rw [e.symm_apply_apply]
+ exact ⟨ξ, by simpa only [hM] using splitWires_matrix_mutual a b I K ξ⟩
+
+/-- Embedding an old wire preserves both endpoint bases and adds a trivial
+factor at the center. This identifies old and enlarged wire values. -/
+theorem embedOld_wire_mutual [Fintype J] (a b : J) (I : Type) [Fintype I] :
+ Restricts (embedOld (wire (k := k) a b I)) (wire (some a) (some b) I) ∧
+ Restricts (wire (k := k) (some a) (some b) I) (embedOld (wire a b I)) := by
+ let e (j : Option J) :
+ (wire (k := k) (some a) (some b) I).Basis j ≃ (embedOld (wire (k := k) a b I)).Basis j :=
+ match j with
+ | none =>
+ { toFun := fun _ ↦ PUnit.unit
+ invFun := fun _ ↦ ((fun h ↦ nomatch h), fun h ↦ nomatch h)
+ left_inv := fun z ↦ by apply Prod.ext <;> funext h <;> cases h
+ right_inv := fun _ ↦ rfl }
+ | some j =>
+ { toFun := fun z ↦ (fun h ↦ z.1 (congrArg some h), fun h ↦ z.2 (congrArg some h))
+ invFun := fun z ↦ (fun h ↦ z.1 (Option.some.inj h), fun h ↦ z.2 (Option.some.inj h))
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ apply restricts_of_reindex e
+ intro x
+ rfl
+
+section Field
+
+variable {k : Type u} [Field k]
+
+/-- Rank bound for the contraction matrix of the two dyadic bundles. -/
+theorem rank_splitMatrix_le (a b : J) (u v : ℕ)
+ (ξ : (splitWires (k := k) a b (Fin (2 ^ u)) (Fin (2 ^ v))).Basis none → k) :
+ (splitMatrix a b (Fin (2 ^ u)) (Fin (2 ^ v)) ξ).rank ≤ 2 ^ min u v := by
+ rcases le_total u v with h | h
+ · rw [min_eq_left h]
+ exact Matrix.rank_le_height _
+ · rw [min_eq_right h]
+ exact Matrix.rank_le_width _
+
+namespace SpectralPoint
+
+variable [Fintype J]
+variable (F : SpectralPoint k J)
+
+/-- An extension on all old tensors restricts to the original wire pseudometric
+at every pair of old parties. -/
+theorem wireDistance_extension (H : SpectralPoint k (Option J))
+ (extendsOld : ∀ T, H.value (embedOld T) = F.value T) (a b : J) :
+ H.wireDistance (some a) (some b) = F.wireDistance a b := by
+ apply congrArg (fun z : NNReal ↦ Real.log (z : ℝ) / Real.log 2)
+ exact (H.value_eq_of_mutual (embedOld_wire_mutual a b (Fin 2))).symm.trans (extendsOld _)
+
+private theorem dyadic_wire_value (a b : J) (n : ℕ) :
+ (F.value (wire a b (Fin (2 ^ n))) : ℝ) = (2 : ℝ) ^ ((n : ℝ) * F.wireDistance a b) := by
+ rw [F.value_wire_eq_rpow a b (by positivity), Real.rpow_natCast_mul (by norm_num)]
+ norm_cast
+
+/-- The contracted value is bounded by the wire with the smaller dimension. -/
+theorem value_splitWires_le_min (a b : J) (u v : ℕ)
+ (ξ : (splitWires (k := k) a b (Fin (2 ^ u)) (Fin (2 ^ v))).Basis none → k) :
+ (F.value (contractCenter (splitWires a b (Fin (2 ^ u)) (Fin (2 ^ v))) ξ) : ℝ) ≤
+ (2 : ℝ) ^ ((min u v : ℕ) * F.wireDistance a b) := by
+ let M := splitMatrix a b (Fin (2 ^ u)) (Fin (2 ^ v)) ξ
+ have hm := (splitWires_matrix_mutual a b (Fin (2 ^ u)) (Fin (2 ^ v)) ξ).2
+ rcases le_total u v with h | h
+ · rw [min_eq_left h, ← F.dyadic_wire_value]
+ exact_mod_cast F.monotone ((wire_restricts_matrixTensor_left a b M).trans hm)
+ · rw [min_eq_right h, ← F.dyadic_wire_value]
+ exact_mod_cast F.monotone ((wire_restricts_matrixTensor_right a b M).trans hm)
+
+/-- Every joint center covector obeys the split target for arbitrary prescribed
+nonnegative lengths whose sum equals the old wire distance. -/
+theorem value_splitWires_le (a b : J) (u v : ℕ) {l₁ l₂ : ℝ}
+ (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂) (hs : l₁ + l₂ = F.wireDistance a b)
+ (ξ : (splitWires (k := k) a b (Fin (2 ^ u)) (Fin (2 ^ v))).Basis none → k) :
+ (F.value (contractCenter (splitWires a b (Fin (2 ^ u)) (Fin (2 ^ v))) ξ) : ℝ) ≤
+ (2 : ℝ) ^ ((u : ℝ) * l₁ + (v : ℝ) * l₂) := by
+ apply (F.value_splitWires_le_min a b u v ξ).trans
+ apply Real.rpow_le_rpow_of_exponent_le (by norm_num)
+ rw [← hs, mul_add]
+ exact add_le_add (mul_le_mul_of_nonneg_right (by exact_mod_cast min_le_left u v) h₁)
+ (mul_le_mul_of_nonneg_right (by exact_mod_cast min_le_right u v) h₂)
+
+/-- With equal bundle widths the identity covector attains the split target. -/
+theorem exists_splitWires_value_eq (a b : J) (n : ℕ) {l₁ l₂ : ℝ}
+ (hs : l₁ + l₂ = F.wireDistance a b) :
+ ∃ ξ, (F.value (contractCenter (splitWires a b (Fin (2 ^ n)) (Fin (2 ^ n))) ξ) : ℝ) =
+ (2 : ℝ) ^ ((n : ℝ) * l₁ + (n : ℝ) * l₂) := by
+ obtain ⟨ξ, h⟩ := exists_splitWires_matrix a b (1 : Matrix (Fin (2 ^ n)) (Fin (2 ^ n)) k)
+ rw [matrixTensor_one] at h
+ rw [← mul_add, hs, ← F.dyadic_wire_value]
+ exact ⟨ξ, congrArg (fun z : NNReal ↦ (z : ℝ)) (F.value_eq_of_mutual h)⟩
+
+/-- The same bound for a monomial in the original binary wire generators times any
+embedded old tensor. The covector can couple all binary indices. -/
+theorem value_binarySplit_monomial_le (T : Tensor.{u,v,0} k J) (a b : J) (u v : ℕ) {l₁ l₂ : ℝ}
+ (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂) (hs : l₁ + l₂ = F.wireDistance a b)
+ (ξ : (tensorProduct (embedOld T) (binarySplit a b u v)).Basis none → k) :
+ (F.value (contractCenter (tensorProduct (embedOld T) (binarySplit a b u v)) ξ) : ℝ) ≤
+ (F.value T : ℝ) * (2 : ℝ) ^ ((u : ℝ) * l₁ + (v : ℝ) * l₂) := by
+ rw [contractCenter_old_product, F.value_tensorProduct, NNReal.coe_mul]
+ apply mul_le_mul_of_nonneg_left _ (F.value T).coe_nonneg
+ obtain ⟨η, hη⟩ := contractCenter_restricts (binary_splitWires_mutual (k := k) a b u v).1
+ (fun y ↦ ξ (PUnit.unit, y))
+ exact (NNReal.coe_le_coe.mpr (F.monotone hη)).trans (F.value_splitWires_le a b u v h₁ h₂ hs η)
+
+/-- Equal multiplicities attain the monomial target, with the embedded old factor
+passing through the contraction. -/
+theorem exists_binarySplit_monomial_eq (T : Tensor.{u,v,0} k J) (a b : J) (n : ℕ) {l₁ l₂ : ℝ}
+ (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂) (hs : l₁ + l₂ = F.wireDistance a b) :
+ ∃ ξ, (F.value (contractCenter (tensorProduct (embedOld T) (binarySplit a b n n)) ξ) : ℝ) =
+ (F.value T : ℝ) * (2 : ℝ) ^ ((n : ℝ) * l₁ + (n : ℝ) * l₂) := by
+ obtain ⟨η, hη⟩ := F.exists_splitWires_value_eq a b n hs
+ obtain ⟨ξ, hξ⟩ := contractCenter_restricts (binary_splitWires_mutual (k := k) a b n n).2 η
+ refine ⟨fun y ↦ ξ y.2, le_antisymm (F.value_binarySplit_monomial_le T a b n n h₁ h₂ hs _) ?_⟩
+ rw [contractCenter_old_product, F.value_tensorProduct, NNReal.coe_mul, ← hη]
+ exact mul_le_mul_of_nonneg_left (NNReal.coe_le_coe.mpr (F.monotone hξ)) (F.value T).coe_nonneg
+
+/-- The upper bound holds for the supremum of all joint contractions. -/
+theorem contractionValue_binarySplit_monomial_le [Nonempty J]
+ (T : Tensor.{u,v,0} k J) (a b : J) (u v : ℕ) {l₁ l₂ : ℝ}
+ (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂) (hs : l₁ + l₂ = F.wireDistance a b) :
+ (F.contractionValue (tensorProduct (embedOld T) (binarySplit a b u v)) : ℝ) ≤
+ (F.value T : ℝ) * (2 : ℝ) ^ ((u : ℝ) * l₁ + (v : ℝ) * l₂) := by
+ apply (F.isLUB_contractionValue _).2
+ rintro _ ⟨ξ, rfl⟩
+ exact F.value_binarySplit_monomial_le T a b u v h₁ h₂ hs ξ
+
+/-- The supremum for equal multiplicities is the target itself. -/
+theorem contractionValue_binarySplit_monomial_eq [Nonempty J]
+ (T : Tensor.{u,v,0} k J) (a b : J) (n : ℕ) {l₁ l₂ : ℝ}
+ (h₁ : 0 ≤ l₁) (h₂ : 0 ≤ l₂) (hs : l₁ + l₂ = F.wireDistance a b) :
+ (F.contractionValue (tensorProduct (embedOld T) (binarySplit a b n n)) : ℝ) =
+ (F.value T : ℝ) * (2 : ℝ) ^ ((n : ℝ) * l₁ + (n : ℝ) * l₂) := by
+ apply le_antisymm (F.contractionValue_binarySplit_monomial_le T a b n n h₁ h₂ hs)
+ obtain ⟨ξ, hξ⟩ := F.exists_binarySplit_monomial_eq T a b n h₁ h₂ hs
+ rw [← hξ]
+ exact NNReal.coe_le_coe.mpr (F.value_le_contractionValue _ ξ)
+
+end SpectralPoint
+
+namespace RestrictionClass
+
+variable [Fintype J]
+
+/-- On restriction classes the two bundles are the corresponding monomial
+in the two added generators. -/
+@[simp] theorem ofTensor_binarySplit (a b : J) (u v : ℕ) :
+ ofTensor (binarySplit (k := k) a b u v) =
+ (ofTensor (wire none (some a) (Fin 2))) ^ u * (ofTensor (wire none (some b) (Fin 2))) ^ v := by
+ simp only [binarySplit, ofTensor_tensorProduct, ofTensor_tensorPowerFin]
+
+end RestrictionClass
+
+end Field
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StarContraction.lean b/lean/OAI/Computability/VPVNP/StarContraction.lean
new file mode 100644
index 0000000000..e1a3c4903c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StarContraction.lean
@@ -0,0 +1,271 @@
+import OAI.Computability.VPVNP.StarTensor
+
+/-!
+# Transport of a center covector
+
+For the extension in Theorem 2.4, a covector on the output of a restriction
+pulls back through the matrix at the new party. The matrices at the old
+parties act after this contraction. Direct sums split the pulled-back
+covector into its two coordinate blocks. An embedded old tensor has a
+singleton center basis, so it factors through an arbitrary contraction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v w w'
+
+namespace WireTensor
+
+variable {k : Type u} {J : Type v} [CommSemiring k]
+
+section Local
+
+variable [Fintype J]
+
+/-- The center covector pulled back through a local restriction matrix. -/
+def pullCovector {A B : Type*} [Fintype B] (L : B → A → k) (ξ : B → k) (a : A) : k :=
+ ∑ b, ξ b * L b a
+
+open scoped Classical in
+/-- Split the center index out of a sum over all local basis tuples. -/
+private theorem sum_withCenter {A : Option J → Type*} [∀ j, Fintype (A j)]
+ (f : ((j : Option J) → A j) → k) :
+ ∑ a, f a = ∑ t, ∑ b : (j : J) → A (some j), f (withCenter t b) := by
+ classical
+ rw [← Fintype.sum_prod_type']
+ refine ((Equiv.piOptionEquivProd (β := A)).symm.sum_comp f).symm.trans ?_
+ apply Finset.sum_congr rfl
+ intro z _
+ apply congrArg f
+ funext j
+ cases j <;> rfl
+
+/-- The matrix at the center acts on its covector, and all other matrices act
+on the resulting old-party array. -/
+theorem contractCenter_applyLocal {A : Option J → Type w} {B : Option J → Type w'}
+ [a : ∀ j, Fintype (A j)] [b : ∀ j, Fintype (B j)]
+ (L : ∀ j, B j → A j → k) (T : Array k A) (ξ : B none → k) :
+ (contractCenter (.mk B b (applyLocal L T)) ξ).coeff =
+ applyLocal (fun j ↦ L (some j))
+ (contractCenter (.mk A a T) (pullCovector (L none) ξ)).coeff := by
+ classical
+ funext x
+ change (j : J) → B (some j) at x
+ simp only [contractCenter, applyLocal, pullCovector]
+ have split (c : B none) := sum_withCenter (A := A)
+ (fun z ↦ (∏ j, L j (withCenter c x j) (z j)) * T z)
+ calc
+ _ = ∑ c, ξ c * ∑ t, ∑ y : (j : J) → A (some j),
+ (∏ j, L j (withCenter c x j) (withCenter t y j)) * T (withCenter t y) := by
+ apply Finset.sum_congr rfl
+ intro c _
+ apply congrArg (ξ c * ·)
+ convert! split c using 2
+ ext z
+ simp
+ _ = _ := ?_
+ simp_rw [Fintype.prod_option]
+ simp only [withCenter, Finset.mul_sum, Finset.sum_mul]
+ rw [Finset.sum_comm, Finset.sum_comm (s := Finset.univ) (t := Finset.univ) (f := fun y t ↦
+ ∑ c, (∏ j, L (some j) (x j) (y j)) * (ξ c * L none c t * T (withCenter t y)))]
+ apply Finset.sum_congr rfl
+ intro t _
+ rw [Finset.sum_comm]
+ apply Finset.sum_congr rfl
+ intro y _
+ apply Finset.sum_congr rfl
+ intro c _
+ ac_rfl
+
+/-- Every contraction of the demand tensor is obtained by restricting a
+contraction of the supply tensor. The pulled-back covector can be entangled
+across all factors at the center. -/
+theorem contractCenter_restricts {Y : Tensor.{u,v,w} k (Option J)}
+ {X : Tensor.{u,v,w'} k (Option J)} (h : Restricts Y X) (ξ : X.Basis none → k) :
+ ∃ η, Restricts (contractCenter Y η) (contractCenter X ξ) := by
+ obtain ⟨L, hL⟩ := h
+ refine ⟨pullCovector (L none) ξ, fun j ↦ L (some j), ?_⟩
+ have hcoeff := (contractCenter_applyLocal L Y.coeff ξ).symm
+ rw [hL] at hcoeff
+ exact hcoeff
+
+/-- Each coordinate block of the center covector contracts its own summand.
+The old-party bases still form a direct sum. -/
+theorem contractCenter_directSum (T : Tensor.{u,v,w} k (Option J))
+ (U : Tensor.{u,v,w'} k (Option J)) (ξ : (directSum T U).Basis none → k) :
+ contractCenter (directSum T U) ξ =
+ directSum (contractCenter T (fun x ↦ ξ (.inl x))) (contractCenter U (fun y ↦ ξ (.inr y))) := by
+ classical
+ let B (j : Option J) := T.Basis j ⊕ U.Basis j
+ let l (j : Option J) (c : B j) (x : T.Basis j) : k := if c = Sum.inl x then 1 else 0
+ let r (j : Option J) (c : B j) (x : U.Basis j) : k := if c = Sum.inr x then 1 else 0
+ have hl : pullCovector (l none) ξ = fun x ↦ ξ (.inl x) := by
+ funext x
+ unfold pullCovector
+ rw [Finset.sum_eq_single (Sum.inl x)]
+ · simp [l]
+ · intro z _ hz
+ simp [l, hz]
+ · simp
+ have hr : pullCovector (r none) ξ = fun y ↦ ξ (.inr y) := by
+ funext y
+ unfold pullCovector
+ rw [Finset.sum_eq_single (Sum.inr y)]
+ · simp [r]
+ · intro z _ hz
+ simp [r, hz]
+ · simp
+ have hlt := contractCenter_applyLocal l T.coeff ξ
+ have hrt := contractCenter_applyLocal r U.coeff ξ
+ rw [hl] at hlt
+ rw [hr] at hrt
+ unfold contractCenter directSum
+ congr 1
+ funext x
+ change (j : J) → B (some j) at x
+ change (∑ c, ξ c * ((applyLocal l T.coeff) (withCenter c x) +
+ (applyLocal r U.coeff) (withCenter c x))) = _
+ simp only [mul_add, Finset.sum_add_distrib, Pi.add_apply]
+ exact congrArg₂ (· + ·) (congrFun hlt x) (congrFun hrt x)
+
+/-- The old-party maps after restricting an extended direct sum act on the
+contracted branches separately, with ordinary addition of their output arrays. -/
+theorem contractCenter_restricted_directSum (T : Tensor.{u,v,w} k (Option J))
+ (U : Tensor.{u,v,w'} k (Option J)) {X : Tensor k (Option J)}
+ (h : Restricts (directSum T U) X) (ξ : X.Basis none → k) :
+ ∃ (η : T.Basis none → k) (θ : U.Basis none → k)
+ (L : ∀ j : J, X.Basis (some j) → T.Basis (some j) → k)
+ (M : ∀ j : J, X.Basis (some j) → U.Basis (some j) → k),
+ (contractCenter X ξ).coeff =
+ applyLocal L (contractCenter T η).coeff + applyLocal M (contractCenter U θ).coeff := by
+ obtain ⟨γ, hγ⟩ := contractCenter_restricts h ξ
+ rw [contractCenter_directSum] at hγ
+ obtain ⟨K, hK⟩ := hγ
+ refine ⟨_, _, _, _, hK.symm.trans (applyLocal_directSum _ _ K)⟩
+
+/-- An extended tensor can supply any center contraction with the trivial leg
+restored. This lets an extending spectral point bound the old spectral value
+of every contraction. -/
+theorem restricts_embedOld_contractCenter (T : Tensor.{u,v,w} k (Option J))
+ (ξ : T.Basis none → k) : Restricts T (embedOld (contractCenter T ξ)) := by
+ classical
+ let L (j : Option J) : (embedOld (contractCenter T ξ)).Basis j → T.Basis j → k :=
+ match j with
+ | none => fun _ t ↦ ξ t
+ | some i => fun c t ↦ if c = t then 1 else 0
+ refine ⟨L, ?_⟩
+ funext x
+ unfold applyLocal
+ calc
+ _ = ∑ t, ∑ y : (j : J) → T.Basis (some j),
+ (∏ j, L j (x j) (withCenter t y j)) * T.coeff (withCenter t y) := by
+ convert! sum_withCenter (A := T.Basis) (fun z ↦ (∏ j, L j (x j) (z j)) * T.coeff z) using 2
+ ext z
+ simp
+ _ = _ := by
+ let y₀ : (j : J) → T.Basis (some j) := fun j ↦ x (some j)
+ simp only [Fintype.prod_option, L, withCenter, embedOld, contractCenter]
+ apply Finset.sum_congr rfl
+ intro t _
+ change (∑ y, (ξ t * ∏ j, if y₀ j = y j then 1 else 0) * T.coeff (withCenter t y)) =
+ ξ t * T.coeff (withCenter t y₀)
+ simp [Fintype.prod_boole, ← funext_iff, mul_ite, ite_mul]
+
+/-- Adding a trivial party preserves local restriction. -/
+theorem embedOld_restricts {T : Tensor.{u,v,w} k J} {U : Tensor.{u,v,w'} k J}
+ (h : Restricts T U) : Restricts (embedOld T) (embedOld U) := by
+ classical
+ obtain ⟨L, hL⟩ := h
+ let M (j : Option J) : (embedOld U).Basis j → (embedOld T).Basis j → k :=
+ match j with
+ | none => fun _ _ ↦ 1
+ | some i => L i
+ refine ⟨M, ?_⟩
+ funext x
+ unfold applyLocal
+ calc
+ _ = ∑ t, ∑ y : (j : J) → (embedOld T).Basis (some j),
+ (∏ j, M j (x j) (withCenter t y j)) * (embedOld T).coeff (withCenter t y) := by
+ convert! sum_withCenter (A := (embedOld T).Basis)
+ (fun z ↦ (∏ j, M j (x j) (z j)) * (embedOld T).coeff z) using 2
+ ext z
+ simp
+ _ = _ := by
+ change (∑ t : PUnit, ∑ y : (j : J) → T.Basis j,
+ (∏ j, M j (x j) (withCenter t y j)) * (embedOld T).coeff (withCenter t y)) = _
+ simpa only [Fintype.sum_unique, Fintype.prod_option, M, withCenter, embedOld, one_mul, applyLocal] using
+ congrFun hL (fun j ↦ x (some j))
+
+/-- Parallel products of embedded old tensors differ from the embedded
+product only by the canonical bijection of their singleton center bases. -/
+theorem embedOld_product_mutual (T : Tensor.{u,v,w} k J) (U : Tensor.{u,v,w'} k J) :
+ Restricts (embedOld (tensorProduct T U)) (tensorProduct (embedOld T) (embedOld U)) ∧
+ Restricts (tensorProduct (embedOld T) (embedOld U)) (embedOld (tensorProduct T U)) := by
+ let e (j : Option J) : (tensorProduct (embedOld T) (embedOld U)).Basis j ≃
+ (embedOld (tensorProduct T U)).Basis j :=
+ match j with
+ | none => (⟨fun _ ↦ .unit, fun _ ↦ (.unit, .unit), fun p ↦ by cases p; rfl,
+ fun _ ↦ rfl⟩ : (PUnit × PUnit) ≃ PUnit)
+ | some _ => Equiv.refl _
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+end Local
+
+/-- Evaluating the embedded singleton leg at one returns the old tensor. -/
+theorem contractCenter_embedOld_one (T : Tensor.{u,v,w} k J) :
+ contractCenter (embedOld T) (fun _ ↦ 1) = T := by
+ cases T with
+ | mk A a T =>
+ unfold contractCenter embedOld
+ congr 1
+ funext x
+ change (∑ _ : PUnit.{w+1}, 1 * T x) = T x
+ rw [Fintype.sum_unique, one_mul]
+
+/-- A scalar multiple of an old tensor is a local restriction: one old
+party absorbs the scalar into its identity matrix. -/
+theorem restricts_contractCenter_embedOld [Fintype J] [Nonempty J]
+ (T : Tensor.{u,v,w} k J) (ξ : (embedOld T).Basis none → k) :
+ Restricts T (contractCenter (embedOld T) ξ) := by
+ classical
+ let p : J := Classical.choice inferInstance
+ let L (j : J) (c b : T.Basis j) : k :=
+ if c = b then (if j = p then ξ PUnit.unit else 1) else 0
+ refine ⟨L, ?_⟩
+ funext x
+ change (j : J) → T.Basis j at x
+ change (∑ b, (∏ j, L j (x j) (b j)) * T.coeff b) =
+ ∑ t : PUnit.{w+1}, ξ t * T.coeff x
+ rw [Finset.sum_eq_single x, Fintype.sum_unique]
+ · simp [L, Finset.prod_ite_eq']
+ · intro b _ hb
+ obtain ⟨j, hj⟩ : ∃ j, x j ≠ b j := Classical.not_forall.mp (fun he ↦ hb (funext he).symm)
+ rw [Finset.prod_eq_zero (Finset.mem_univ j) (by simp [L, hj]), zero_mul]
+ · simp
+
+/-- A general covector on the center leg of an old tensor times an extended
+tensor leaves the old tensor intact. -/
+theorem contractCenter_old_product (T : Tensor.{u,v,w} k J)
+ (U : Tensor.{u,v,w'} k (Option J)) (ξ : (tensorProduct (embedOld T) U).Basis none → k) :
+ contractCenter (tensorProduct (embedOld T) U) ξ =
+ tensorProduct T (contractCenter U (fun y ↦ ξ (PUnit.unit, y))) := by
+ classical
+ unfold contractCenter tensorProduct embedOld
+ congr 1
+ funext x
+ rw [Fintype.sum_prod_type]
+ simp only [Fintype.sum_unique, Finset.mul_sum, withCenter, mul_left_comm]
+ apply Finset.sum_congr rfl
+ intro y _
+ congr 2
+ apply congrArg U.coeff
+ funext j
+ cases j <;> rfl
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StarEmbedding.lean b/lean/OAI/Computability/VPVNP/StarEmbedding.lean
new file mode 100644
index 0000000000..9d1f9f497f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StarEmbedding.lean
@@ -0,0 +1,93 @@
+import OAI.Computability.VPVNP.StarContraction
+import OAI.Computability.VPVNP.TensorRestrictionSemiring
+
+/-!
+# Embedded old tensor classes
+
+Adjoining the trivial center leg preserves parallel products and reflects
+local restrictions. The old factors in a monomial of Theorem 2.4 can thus
+be multiplied in the old party set, then embedded as one tensor class.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+
+namespace WireTensor.RestrictionClass
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nonempty J]
+
+/-- Embedding an old tensor induces a multiplicative map on restriction
+classes which also preserves zero. -/
+noncomputable def embedOldClass : RestrictionClass k J →*₀ RestrictionClass k (Option J) where
+ toFun := Quotient.map embedOld fun _ _ h ↦ ⟨embedOld_restricts h.1, embedOld_restricts h.2⟩
+ map_zero' := by
+ change ofTensor (embedOld (diagonal (Fin 0))) = 0
+ apply (ofTensor_eq_zero_iff _).2
+ funext x
+ simp [embedOld, diagonal]
+ map_one' := by
+ change ofTensor (embedOld unit) = ofTensor unit
+ apply (ofTensor_eq_iff _ _).2
+ let e (j : Option J) : (unit (k := k) (J := Option J)).Basis j ≃ (embedOld (unit.{u,v,0} (k := k) (J := J))).Basis j :=
+ match j with
+ | none => Equiv.refl _
+ | some _ => Equiv.refl _
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+ map_mul' a b := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective a
+ obtain ⟨U, rfl⟩ := ofTensor_surjective b
+ exact (ofTensor_eq_iff _ _).2 (embedOld_product_mutual T U)
+
+@[simp] theorem embedOldClass_ofTensor (T : Tensor.{u,v,0} k J) :
+ embedOldClass (ofTensor T) = ofTensor (embedOld T) := rfl
+
+/-- Embedding a trivial center leg preserves and reflects restriction. To
+reflect a restriction, contract the demand with the unit covector and pull
+it back to the singleton center basis of the supply. -/
+@[simp] theorem embedOldClass_le_iff (x y : RestrictionClass k J) :
+ embedOldClass x ≤ embedOldClass y ↔ x ≤ y := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ obtain ⟨U, rfl⟩ := ofTensor_surjective y
+ change Restricts (embedOld U) (embedOld T) ↔ Restricts U T
+ refine ⟨?_, embedOld_restricts⟩
+ intro h
+ obtain ⟨ξ, hξ⟩ := contractCenter_restricts h (fun _ ↦ 1)
+ rw [contractCenter_embedOld_one] at hξ
+ exact (restricts_contractCenter_embedOld U ξ).trans hξ
+
+/-- Adjoining a trivial leg is faithful on tensor restriction classes. -/
+theorem embedOldClass_injective : Function.Injective (embedOldClass (k := k) (J := J)) := by
+ intro x y h
+ exact le_antisymm ((embedOldClass_le_iff _ _).1 h.le) ((embedOldClass_le_iff _ _).1 h.ge)
+
+/-- The concrete product indexed by `Fin n` represents the `n`-th power
+in the semiring of restriction classes. -/
+@[simp] theorem ofTensor_tensorPowerFin (n : ℕ) (T : Tensor.{u,v,0} k J) :
+ ofTensor (tensorPowerFin n T) = ofTensor T ^ n := by
+ induction n with
+ | zero =>
+ rw [pow_zero]
+ change ofTensor (tensorPowerFin 0 T) = ofTensor unit
+ apply (ofTensor_eq_iff _ _).2
+ apply restricts_of_reindex (fun j ↦ Equiv.ofUnique PUnit (Fin 0 → T.Basis j))
+ intro x
+ simp [tensorPowerFin, unit]
+ | succ n ih =>
+ rw [pow_succ', ← ih, ← ofTensor_tensorProduct]
+ apply (ofTensor_eq_iff _ _).2
+ apply restricts_of_reindex (fun j ↦ Fin.consEquiv (fun _ : Fin (n + 1) ↦ T.Basis j))
+ intro x
+ change (j : J) → T.Basis j × (Fin n → T.Basis j) at x
+ change T.coeff (fun j ↦ (x j).1) * (∏ i, T.coeff (fun j ↦ (x j).2 i)) = _
+ change _ = ∏ i, T.coeff (fun j ↦ Fin.cons (α := fun _ : Fin (n + 1) ↦ T.Basis j) (x j).1 (x j).2 i)
+ rw [Fin.prod_univ_succ]
+ simp
+
+end WireTensor.RestrictionClass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StarExtension.lean b/lean/OAI/Computability/VPVNP/StarExtension.lean
new file mode 100644
index 0000000000..3057f664ba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StarExtension.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.StarProfile
+import OAI.Computability.VPVNP.TensorExtensionMatching
+import OAI.Computability.VPVNP.TensorFlatteningPoint
+
+/-!
+# Exact extension for a prescribed width profile
+
+Theorem 2.4(2) requires the extension to match every old tensor value and
+the target of one dyadic star. Products of the old generators reduce to
+one old tensor, while all star occurrences combine into one power. This
+identifies the finite-generator estimates with the concrete contraction
+bounds on arrays.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u
+namespace WireTensor.SpectralPoint
+
+open RestrictionClass
+variable {k : Type u} {J : Type} [Field k] [Fintype J] [Nonempty J]
+
+/-- The class of the star whose width at leaf `j` is `w j`. -/
+noncomputable def dyadicStarClass (w : J → ℕ) : RestrictionClass k (Option J) :=
+ ofTensor (starTensor (fun j ↦ Fin (2 ^ w j)))
+
+omit [Nonempty J] in
+theorem dyadicStarClass_ne_zero (w : J → ℕ) : dyadicStarClass (k := k) w ≠ 0 := by
+ rw [dyadicStarClass, ne_eq, ofTensor_eq_zero_iff]
+ intro hz
+ let a (j : J) : Fin (2 ^ w j) := ⟨0, Nat.pow_pos (by decide)⟩
+ have h := congrFun hz (withCenter (B := starBasis (fun j ↦ Fin (2 ^ w j))) a a)
+ have h₁ : (starTensor (k := k) (fun j ↦ Fin (2 ^ w j))).coeff (withCenter a a) = 1 := by
+ dsimp only [starTensor, withCenter]
+ exact ite_eq_left rfl
+ exact one_ne_zero (h₁.symm.trans h)
+
+variable (F : SpectralPoint k J)
+
+/-- A monomial with a combined old factor and a star power obeys its target bound. -/
+theorem contractionClassValue_old_star_le (w : J → ℕ) (x : RestrictionClass k J) (n : ℕ) :
+ F.contractionClassValue (embedOldClass x * dyadicStarClass w ^ n) ≤
+ ofSpectralPoint F x * ((2 : ℝ) ^ F.starRate w) ^ n := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ rw [F.contractionClassValue_old_product, ofSpectralPoint_ofTensor,
+ dyadicStarClass, ← ofTensor_tensorPowerFin, F.contractionClassValue_ofTensor]
+ apply mul_le_mul_of_nonneg_left _ (by positivity)
+ refine (F.contractionValue_starPower_le w n).trans_eq ?_
+ rw [mul_comm, Real.rpow_mul_natCast (by norm_num)]
+
+/-- The root limit of a power of one folded monomial equals its target. -/
+theorem contractionClassValue_old_star_root (w : J → ℕ) (x : RestrictionClass k J) (n : ℕ) :
+ Filter.Tendsto (fun m : ℕ ↦
+ (F.contractionClassValue ((embedOldClass x * dyadicStarClass w ^ n) ^ m)) ^ (m : ℝ)⁻¹)
+ Filter.atTop (nhds (ofSpectralPoint F x * ((2 : ℝ) ^ F.starRate w) ^ n)) := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ have h := F.starPower_contractionRoot T w n
+ simpa only [← F.contractionClassValue_ofTensor, ofTensor_tensorProduct, ← embedOldClass_ofTensor,
+ ofTensor_tensorPowerFin, map_pow, pow_mul, mul_pow, dyadicStarClass, ofSpectralPoint_ofTensor,
+ mul_comm (n : ℝ), Real.rpow_mul_natCast (by norm_num : 0 ≤ (2 : ℝ))] using h
+
+/-- Theorem 2.4(2), attainment. A single new spectral point preserves every
+old tensor value and realizes the profile rate as its weighted star length. -/
+theorem exists_starRate_extension (w : J → ℕ) :
+ ∃ H : SpectralPoint k (Option J), (∀ T, H.value (embedOld T) = F.value T) ∧
+ ∑ j, (w j : ℝ) * H.wireDistance none (some j) = F.starRate w := by
+ classical
+ let extra (_ : Unit) := dyadicStarClass (k := k) w
+ let cost (_ : Unit) := (2 : ℝ) ^ F.starRate w
+ have upper (x : RestrictionClass k J) (n : Unit → ℕ) :
+ F.contractionClassValue (embedOldClass x * ∏ i, extra i ^ n i) ≤
+ ofSpectralPoint F x * ∏ i, cost i ^ n i := by
+ simpa only [Fintype.prod_unique] using F.contractionClassValue_old_star_le w x (n ())
+ have balanced (x : RestrictionClass k J) (e : ℕ) (_ : 0 < e) :
+ Filter.Tendsto (fun m : ℕ ↦ F.contractionClassValue ((embedOldClass x * ∏ i, extra i ^ e) ^ m)
+ ^ (m : ℝ)⁻¹) Filter.atTop (nhds (ofSpectralPoint F x * ∏ i, cost i ^ e)) := by
+ simpa only [Fintype.prod_unique] using F.contractionClassValue_old_star_root w x e
+ obtain ⟨H, hExtends, hStar⟩ := F.exists_extension_matching_of_rank
+ (flatteningRankHom (none : Option J)) (flatteningRankHom_monotone none) extra cost
+ (fun _ ↦ dyadicStarClass_ne_zero w) (fun _ ↦ Real.rpow_pos_of_pos (by norm_num) _)
+ upper balanced
+ refine ⟨H, hExtends, (Real.strictMono_rpow_of_base_gt_one (by norm_num : 1 < (2 : ℝ))).injective ?_⟩
+ rw [← value_dyadicStar H w]
+ exact hStar ()
+
+/-- Equation (2.1). The minimum over all spectral points extending `F` is
+attained, for each individual choice of the width profile. -/
+theorem starRate_isLeast (w : J → ℕ) :
+ IsLeast {c : ℝ | ∃ H : SpectralPoint k (Option J),
+ (∀ T, H.value (embedOld T) = F.value T) ∧
+ ∑ j, (w j : ℝ) * H.wireDistance none (some j) = c} (F.starRate w) := by
+ refine ⟨F.exists_starRate_extension w, ?_⟩
+ rintro _ ⟨H, hH, rfl⟩
+ exact F.starRate_le_extension H hH w
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StarGrowth.lean b/lean/OAI/Computability/VPVNP/StarGrowth.lean
new file mode 100644
index 0000000000..c1b56de3e3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StarGrowth.lean
@@ -0,0 +1,122 @@
+import Mathlib.Algebra.Order.Floor.Semifield
+import Mathlib.Analysis.SpecialFunctions.Log.Base
+import Mathlib.Analysis.SpecialFunctions.Pow.Continuity
+import Mathlib.Analysis.SpecificLimits.Basic
+import Mathlib.Topology.Order.IsLUB
+import Mathlib.Tactic.Linarith
+
+/-!
+# Growth of contractions of a powered star
+
+Section 2.3 of *VP and VNP differ over every field* computes the exponential
+rate of the supremum of the values of contractions at a new party. A tensor
+with local widths indexed by `h` fits into `u*m` copies of the width profile
+exactly `u*m/h` times, using natural-number division.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Spectral
+
+open Filter Topology
+
+/-- The fraction of the power occupied by copies of a fixed witness has the
+limit used in the star construction. -/
+private theorem packedCopyRatio_tendsto (u h : ℕ) :
+ Tendsto (fun m : ℕ ↦ ((u * m / h : ℕ) : ℝ) / m) atTop (𝓝 ((u : ℝ) / h)) := by
+ have lim := (tendsto_nat_floor_mul_div_atTop
+ (show 0 ≤ (u : ℝ) / h by positivity)).comp tendsto_natCast_atTop_atTop
+ apply lim.congr
+ intro m
+ change (⌊(u : ℝ) / h * m⌋₊ : ℝ) / m = _
+ rw [div_mul_eq_mul_div, ← Nat.cast_mul, Nat.floor_div_eq_div]
+
+/-- Taking roots in the value of a single packed witness. -/
+private theorem packedStarRoot_tendsto {a b : ℝ} (ha : 0 ≤ a) (hb : 0 < b) (u h : ℕ) :
+ Tendsto (fun m : ℕ ↦ (a ^ m * b ^ (u*m/h)) ^ (m⁻¹ : ℝ)) atTop
+ (𝓝 (a * b ^ ((u : ℝ) / h))) := by
+ have lim := ((Real.continuousAt_const_rpow hb.ne').tendsto.comp
+ (packedCopyRatio_tendsto u h)).const_mul a
+ apply lim.congr'
+ filter_upwards [eventually_gt_atTop (0 : ℕ)] with m hm
+ change a * b ^ (((u * m / h : ℕ) : ℝ) / m) = _
+ rw [Real.mul_rpow (pow_nonneg ha m) (pow_nonneg hb.le _),
+ Real.pow_rpow_inv_natCast ha hm.ne', ← Real.rpow_natCast b (u*m/h),
+ ← Real.rpow_mul hb.le, div_eq_mul_inv]
+
+/-- In the star case of Theorem 2.4, `I` indexes the pairs of a positive
+width parameter and a nonzero old tensor of that width. `g` is the supremum
+of their normalized log values, `a` is the old factor's value, and `C m` is
+the supremum of the contracted values of the monomial's `m`-th power.
+The packing and contraction inequalities imply the claimed root limit, even
+for zero star multiplicity. -/
+theorem starContractionRoot_tendsto {I : Type*} [Nonempty I] (height : I → ℕ)
+ (value : I → ℝ) (u : ℕ) {a g : ℝ} (C : ℕ → ℝ)
+ (ha : 0 ≤ a) (hv : ∀ i, 0 < value i)
+ (hg : IsLUB (Set.range (fun i ↦ Real.logb 2 (value i) / height i)) g)
+ (pack : ∀ i m, 0 < m → a ^ m * value i ^ (u * m / height i) ≤ C m)
+ (bound : ∀ m, 0 < m → C m ≤ (a * (2 : ℝ) ^ ((u : ℝ) * g)) ^ m) :
+ Tendsto (fun m : ℕ ↦ C m ^ (m⁻¹ : ℝ)) atTop (𝓝 (a * (2 : ℝ) ^ ((u : ℝ) * g))) := by
+ obtain ⟨r, _, _, hr, hmem⟩ := hg.exists_seq_monotone_tendsto (Set.range_nonempty _)
+ have htarget : Tendsto (fun n : ℕ ↦ a * (2 : ℝ) ^ ((u : ℝ) * r n)) atTop
+ (𝓝 (a * (2 : ℝ) ^ ((u : ℝ) * g))) :=
+ ((Real.continuousAt_const_rpow (by norm_num : (2 : ℝ) ≠ 0)).tendsto.comp
+ (hr.const_mul (u : ℝ))).const_mul a
+ apply tendsto_order.2
+ constructor
+ · intro x hx
+ obtain ⟨n, hn⟩ := (htarget.eventually (lt_mem_nhds hx)).exists
+ obtain ⟨i, hi⟩ := hmem n
+ change x < a * (2 : ℝ) ^ ((u : ℝ) * r n) at hn
+ rw [← hi, show (u : ℝ) * (Real.logb 2 (value i) / height i) =
+ Real.logb 2 (value i) * ((u : ℝ) / height i) by ring,
+ Real.rpow_mul (by norm_num), Real.rpow_logb (by norm_num) (by norm_num) (hv i)] at hn
+ filter_upwards [(packedStarRoot_tendsto ha (hv i) u (height i)).eventually (lt_mem_nhds hn),
+ eventually_gt_atTop (0 : ℕ)] with m hx hm
+ exact hx.trans_le (Real.rpow_le_rpow (mul_nonneg (pow_nonneg ha _) (pow_nonneg (hv i).le _))
+ (pack i m hm) (by positivity))
+ · intro x hx
+ filter_upwards [eventually_gt_atTop (0 : ℕ)] with m hm
+ have i := Classical.choice ‹Nonempty I›
+ have hc : 0 ≤ C m := (mul_nonneg (pow_nonneg ha _) (pow_nonneg (hv i).le _)).trans
+ (pack i m hm)
+ have h := Real.rpow_le_rpow hc (bound m hm) (show 0 ≤ (m⁻¹ : ℝ) by positivity)
+ rw [Real.pow_rpow_inv_natCast (mul_nonneg ha (by positivity)) hm.ne'] at h
+ exact h.trans_lt hx
+
+/-- A positive contraction supremum admits a contraction strictly above half its value. -/
+theorem exists_gt_half_of_isLUB {S : Set ℝ} {c : ℝ} (h : IsLUB S c) (hc : 0 < c) :
+ ∃ d ∈ S, c / 2 < d ∧ d ≤ c :=
+ h.exists_between (by linarith)
+
+/-- Any fixed multiplicative loss disappears after taking the `m`-th root. It is
+sufficient for the power estimate to hold on an unbounded set of integers. -/
+theorem limit_le_of_half_power_bound {C : ℕ → ℝ} {L B K f : ℝ}
+ (hL : 0 ≤ L) (hB : 0 ≤ B) (hK : 0 < K)
+ (hC : ∀ᶠ m in atTop, 0 ≤ C m)
+ (hlim : Tendsto (fun m : ℕ ↦ C m ^ (m : ℝ)⁻¹) atTop (𝓝 f))
+ (hbound : ∃ᶠ m in atTop, L ^ m * (C m / 2) ≤ K * B ^ m) : L * f ≤ B := by
+ have hrec : Tendsto (fun m : ℕ ↦ (m : ℝ)⁻¹) atTop (𝓝 0) :=
+ tendsto_inv_atTop_zero.comp tendsto_natCast_atTop_atTop
+ have h2K : 0 < 2 * K := by positivity
+ have hscale : Tendsto (fun m : ℕ ↦ (2 * K) ^ (m : ℝ)⁻¹) atTop (𝓝 1) := by
+ simpa only [Real.rpow_zero] using tendsto_const_nhds.rpow hrec (Or.inl h2K.ne')
+ have hright : Tendsto (fun m : ℕ ↦ (2 * K) ^ (m : ℝ)⁻¹ * B) atTop (𝓝 B) := by
+ simpa only [one_mul] using hscale.mul_const B
+ apply le_of_tendsto_of_tendsto_of_frequently (hlim.const_mul L) hright
+ apply (hbound.and_eventually (hC.and (eventually_gt_atTop (0 : ℕ)))).mono
+ rintro m ⟨hm, hCm, hpos⟩
+ have hprod : L ^ m * C m ≤ (2 * K) * B ^ m := by linarith
+ have hroot := Real.rpow_le_rpow (mul_nonneg (pow_nonneg hL m) hCm) hprod
+ (inv_nonneg.mpr (Nat.cast_nonneg m : 0 ≤ (m : ℝ)))
+ simpa only [Real.mul_rpow (pow_nonneg hL m) hCm,
+ Real.mul_rpow h2K.le (pow_nonneg hB m), Real.pow_rpow_inv_natCast hL hpos.ne',
+ Real.pow_rpow_inv_natCast hB hpos.ne'] using hroot
+
+end Spectral
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StarPacking.lean b/lean/OAI/Computability/VPVNP/StarPacking.lean
new file mode 100644
index 0000000000..1cafcba59e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StarPacking.lean
@@ -0,0 +1,92 @@
+import OAI.Computability.VPVNP.StarTensor
+
+/-!
+# Packing tensors into a dyadic star
+
+In the star case of Theorem 2.4, a tensor of local dimensions `2^(h*w j)`
+fits into the contraction of a star of local dimensions `2^(r*w j)` after
+taking `r / h` copies. Coordinate inclusion pads the entries by zero, and
+coordinate selection recovers the original tensor power.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v w
+
+namespace WireTensor
+
+variable {k : Type u} [CommSemiring k]
+
+private theorem exists_padded_array {J : Type v} [Fintype J]
+ (T : Tensor.{u,v,w} k J) (I : J → Type v) [b : ∀ j, Fintype (I j)]
+ (e : ∀ j, T.Basis j ↪ I j) :
+ ∃ A : Array k I, Restricts T (.mk I b A) ∧ Restricts (.mk I b A) T := by
+ classical
+ let L (j : J) (b : I j) (a : T.Basis j) : k := if b = e j a then 1 else 0
+ refine ⟨applyLocal L T.coeff, ⟨L, rfl⟩, ?_⟩
+ refine ⟨_, (applyLocal_pullback (fun j ↦ e j) (applyLocal L T.coeff)).trans ?_⟩
+ funext a
+ simp [applyLocal, L, Fintype.prod_boole, ← funext_iff, ite_mul]
+
+/-- Pad a tensor by zero along local basis embeddings and realize the padded
+array by a single covector at the center. Both local restrictions are exact. -/
+theorem exists_star_contraction_of_embeddings {J : Type v} [Fintype J]
+ (T : Tensor.{u,v,w} k J) (I : J → Type v) [∀ j, Fintype (I j)]
+ (e : ∀ j, T.Basis j ↪ I j) :
+ ∃ ξ, Restricts T (contractCenter (starTensor I) ξ) ∧
+ Restricts (contractCenter (starTensor I) ξ) T := by
+ obtain ⟨A, hA⟩ := exists_padded_array T I e
+ exact ⟨A, by simpa only [contractCenter_starTensor] using hA⟩
+
+private theorem packed_card_le {J : Type} (T : Tensor.{u,0,0} k J)
+ (w : J → ℕ) (h r : ℕ) (dims : ∀ j, Fintype.card (T.Basis j) = 2 ^ (h * w j))
+ (j : J) : Fintype.card ((tensorPowerFin (r / h) T).Basis j) ≤ 2 ^ (r * w j) := by
+ change Fintype.card (Fin (r / h) → T.Basis j) ≤ _
+ simp only [Fintype.card_fun, Fintype.card_fin, dims, ← pow_mul]
+ apply Nat.pow_le_pow_right (by decide)
+ simpa only [mul_assoc, mul_comm, mul_left_comm] using
+ Nat.mul_le_mul_right (w j) (Nat.div_mul_le_self r h)
+
+/-- At each party, the floor number of copies has enough local coordinates
+in the dyadic star. This includes zero star multiplicity and zero widths. -/
+theorem exists_dyadic_star_packing {J : Type} [Fintype J] (T : Tensor.{u,0,0} k J)
+ (w : J → ℕ) (h r : ℕ) (dims : ∀ j, Fintype.card (T.Basis j) = 2 ^ (h * w j)) :
+ ∃ ξ, Restricts (tensorPowerFin (r / h) T)
+ (contractCenter (starTensor (fun j ↦ Fin (2 ^ (r * w j)))) ξ) ∧
+ Restricts (contractCenter (starTensor (fun j ↦ Fin (2 ^ (r * w j)))) ξ)
+ (tensorPowerFin (r / h) T) := by
+ classical
+ apply exists_star_contraction_of_embeddings
+ intro j
+ apply Classical.choice
+ apply Function.Embedding.nonempty_of_card_le
+ simpa only [Fintype.card_fin] using packed_card_le T w h r dims j
+
+/-- Contract the power of the width-profile star itself to a zero padding
+of the packed tensor power, using a joint covector on all center indices. -/
+theorem exists_starPowerFin_packing {J : Type} [Fintype J] (T : Tensor.{u,0,0} k J)
+ (w : J → ℕ) (h r : ℕ) (dims : ∀ j, Fintype.card (T.Basis j) = 2 ^ (h * w j)) :
+ ∃ ξ, Restricts (tensorPowerFin (r / h) T)
+ (contractCenter (tensorPowerFin r (starTensor (fun j ↦ Fin (2 ^ w j)))) ξ) ∧
+ Restricts (contractCenter (tensorPowerFin r (starTensor (fun j ↦ Fin (2 ^ w j)))) ξ)
+ (tensorPowerFin (r / h) T) := by
+ classical
+ let I (j : J) := Fin r → Fin (2 ^ w j)
+ have e (j : J) : (tensorPowerFin (r / h) T).Basis j ↪ I j := by
+ apply Classical.choice
+ apply Function.Embedding.nonempty_of_card_le
+ simpa only [I, Fintype.card_fun, Fintype.card_fin, ← pow_mul, mul_comm (w j) r] using
+ packed_card_le T w h r dims j
+ obtain ⟨A, hA⟩ := exists_padded_array (tensorPowerFin (r / h) T) I e
+ obtain ⟨ξ, hξ⟩ := contractCenter_starPowerFin (fun j ↦ Fin (2 ^ w j)) r A
+ refine ⟨ξ, ?_⟩
+ cases hξ
+ exact hA
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StarProfile.lean b/lean/OAI/Computability/VPVNP/StarProfile.lean
new file mode 100644
index 0000000000..755b90ba92
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StarProfile.lean
@@ -0,0 +1,217 @@
+import OAI.Computability.VPVNP.ContractionValue
+import OAI.Computability.VPVNP.StarPacking
+import OAI.Computability.VPVNP.StarGrowth
+import Mathlib.Analysis.SpecialFunctions.Log.Base
+
+/-!
+# The width profile of a spectral point
+
+Theorem 2.4 takes the supremum of the normalized spectral values of nonzero
+tensors with local dimensions `2 ^ (h * w j)`. The coordinate rank bound
+makes this supremum finite. It controls arbitrary covectors on a powered star,
+including entangled covectors and the power zero.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u
+
+namespace WireTensor
+
+variable {J : Type} {k : Type u}
+
+/-- A positive height and a nonzero tensor of the dimensions of the width profile. -/
+structure StarWitness (k : Type u) [Zero k] (w : J → ℕ) where
+ /-- Positive integer scaling the logarithmic local dimensions in a witness for the width
+ profile. -/
+ height : ℕ
+ positive : 0 < height
+ /-- Nonzero tensor coefficient array with local dimension `2 ^ (height * w j)` at party `j`. -/
+ coeff : Array k (fun j ↦ Fin (2 ^ (height * w j)))
+ nonzero : coeff ≠ 0
+
+namespace StarWitness
+
+variable [Field k] {w : J → ℕ}
+
+/-- Package the coefficients and the prescribed bases into an old-party tensor. -/
+def tensor (W : StarWitness k w) : Tensor k J :=
+ .mk _ (fun _ ↦ inferInstance) W.coeff
+
+instance : Nonempty (StarWitness k w) := by
+ refine ⟨⟨1, by decide, fun _ ↦ 1, ?_⟩⟩
+ intro h
+ exact one_ne_zero (congrFun h (fun j ↦ ⟨0, Nat.pow_pos (by decide)⟩))
+
+end StarWitness
+
+namespace SpectralPoint
+
+variable [Field k] [Fintype J] [Nonempty J] (F : SpectralPoint k J)
+
+/-- The supremum in equation (2.1), for a fixed integer width at every old party. -/
+noncomputable def starRate (w : J → ℕ) : ℝ :=
+ sSup (Set.range (fun W : StarWitness k w ↦ Real.logb 2 (F.value W.tensor) / W.height))
+
+theorem starWitness_pos {w : J → ℕ} (W : StarWitness k w) : 0 < (F.value W.tensor : ℝ) := by
+ exact_mod_cast zero_lt_one.trans_le (F.one_le_value W.tensor W.nonzero)
+
+/-- Coordinate rank bounds each normalized logarithm by the sum of local widths. -/
+theorem starWitness_log_le {w : J → ℕ} (W : StarWitness k w) :
+ Real.logb 2 (F.value W.tensor) / W.height ≤ (∑ j, w j : ℕ) := by
+ have hcard (j : J) : Fintype.card (W.tensor.Basis j) = 2 ^ (W.height * w j) :=
+ (Fintype.card_congr (show W.tensor.Basis j ≃ Fin (2 ^ (W.height * w j)) from
+ Equiv.refl _)).trans (Fintype.card_fin _)
+ have hdim : (∏ j, Fintype.card (W.tensor.Basis j)) = 2 ^ (W.height * ∑ j, w j) := by
+ simp only [hcard, Finset.prod_pow_eq_pow_sum, Finset.mul_sum]
+ have hval := F.value_le_basis_product W.tensor
+ rw [hdim] at hval
+ have hval' : (F.value W.tensor : ℝ) ≤ (2 : ℝ) ^ (W.height * ∑ j, w j) := by exact_mod_cast hval
+ have hlog := Real.logb_le_logb_of_le (b := 2) (by norm_num) (F.starWitness_pos W) hval'
+ rw [Real.logb_pow, Real.logb_self_eq_one (by norm_num), mul_one] at hlog
+ apply (div_le_iff₀ (show 0 < (W.height : ℝ) by exact_mod_cast W.positive)).mpr
+ simpa only [Nat.cast_mul, mul_comm] using hlog
+
+/-- The defining supremum is the least upper bound of a nonempty, bounded set. -/
+theorem starRate_isLUB (w : J → ℕ) :
+ IsLUB (Set.range (fun W : StarWitness k w ↦ Real.logb 2 (F.value W.tensor) / W.height))
+ (F.starRate w) := by
+ refine isLUB_csSup (Set.range_nonempty _) ?_
+ refine ⟨((∑ j, w j : ℕ) : ℝ), ?_⟩
+ rintro _ ⟨W, rfl⟩
+ exact F.starWitness_log_le W
+
+theorem starRate_le_sum (w : J → ℕ) : F.starRate w ≤ (∑ j, w j : ℕ) :=
+ (F.starRate_isLUB w).2 (fun _ ⟨W, hW⟩ ↦ hW ▸ F.starWitness_log_le W)
+
+theorem starRate_nonneg (w : J → ℕ) : 0 ≤ F.starRate w := by
+ let W := Classical.choice (inferInstance : Nonempty (StarWitness k w))
+ have h1 : 1 ≤ (F.value W.tensor : ℝ) := by exact_mod_cast F.one_le_value W.tensor W.nonzero
+ exact (div_nonneg (Real.logb_nonneg (by norm_num : 1 < (2 : ℝ)) h1) (Nat.cast_nonneg _)).trans
+ ((F.starRate_isLUB w).1 (Set.mem_range_self W))
+
+/-- Apply the profile to arbitrary finite local bases of the prescribed cardinalities. -/
+theorem value_le_starRate {w : J → ℕ} (n : ℕ) (T : Tensor k J)
+ (hdim : ∀ j, Fintype.card (T.Basis j) = 2 ^ (n * w j)) :
+ (F.value T : ℝ) ≤ (2 : ℝ) ^ ((n : ℝ) * F.starRate w) := by
+ classical
+ by_cases hn : n = 0
+ · subst n
+ have hval := F.value_le_basis_product T
+ simpa [hdim] using (NNReal.coe_le_coe.mpr hval)
+ by_cases hz : T.coeff = 0
+ · rw [F.value_zero _ hz]
+ exact Real.rpow_nonneg (by norm_num) _
+ let e (j : J) := Fintype.equivFinOfCardEq (hdim j)
+ let W : StarWitness k w :=
+ { height := n, positive := Nat.pos_of_ne_zero hn,
+ coeff := fun x ↦ T.coeff (fun j ↦ (e j).symm (x j))
+ nonzero := by
+ intro h
+ apply hz
+ funext x
+ simpa only [Equiv.symm_apply_apply, Pi.zero_apply] using congrFun h (fun j ↦ e j (x j)) }
+ have heq : F.value T = F.value W.tensor :=
+ F.value_eq_of_mutual (restricts_of_reindex (fun j ↦ (e j).symm) (fun _ ↦ rfl))
+ rw [heq]
+ apply (Real.logb_le_iff_le_rpow (by norm_num : 1 < (2 : ℝ)) (F.starWitness_pos W)).mp
+ have h := (F.starRate_isLUB w).1 (Set.mem_range_self W)
+ change Real.logb 2 (F.value W.tensor) / (n : ℝ) ≤ F.starRate w at h
+ rw [mul_comm]
+ exact (div_le_iff₀ (Nat.cast_pos.mpr (Nat.pos_of_ne_zero hn))).mp h
+
+/-- An arbitrary contraction of a star power has the advertised spectral upper bound. -/
+theorem starPower_contraction_le (w : J → ℕ) (n : ℕ)
+ (ξ : (tensorPowerFin n (starTensor (k := k) (fun j ↦ Fin (2 ^ w j)))).Basis none → k) :
+ (F.value (contractCenter (tensorPowerFin n (starTensor (fun j ↦ Fin (2 ^ w j)))) ξ) : ℝ) ≤
+ (2 : ℝ) ^ ((n : ℝ) * F.starRate w) := by
+ apply F.value_le_starRate
+ intro j
+ change Fintype.card (Fin n → Fin (2 ^ w j)) = _
+ rw [Fintype.card_fun, Fintype.card_fin, Fintype.card_fin, ← pow_mul, Nat.mul_comm]
+
+omit [Nonempty J] in
+/-- Finite powers have the usual spectral value, also at exponent zero. -/
+theorem value_tensorPowerFin (n : ℕ) (T : Tensor k J) :
+ F.value (tensorPowerFin n T) = F.value T ^ n := by
+ have h := F.value_tensorFamilyProduct (fun _ : Fin n ↦ T)
+ calc
+ F.value (tensorPowerFin n T) = F.value (tensorFamilyProduct (fun _ : Fin n ↦ T)) :=
+ F.value_eq_of_mutual (restricts_of_reindex (fun _ ↦ Equiv.refl _) (fun _ ↦ rfl))
+ _ = _ := by simpa using h
+
+omit [Nonempty J] in
+/-- The packed copies and their simple padding have exactly the value of the unpadded power. -/
+theorem starPower_exists_packed (w : J → ℕ) (W : StarWitness k w) (n : ℕ) :
+ ∃ ξ, (F.value W.tensor : ℝ) ^ (n / W.height) =
+ F.value (contractCenter (tensorPowerFin n (starTensor (fun j ↦ Fin (2 ^ w j)))) ξ) := by
+ obtain ⟨ξ, hξ⟩ := exists_starPowerFin_packing W.tensor w W.height n
+ (fun j ↦ Fintype.card_fin _)
+ refine ⟨ξ, ?_⟩
+ exact_mod_cast (F.value_tensorPowerFin _ _).symm.trans (F.value_eq_of_mutual hξ)
+
+/-- Real upper bound on the supremum over all center covectors. -/
+theorem contractionValue_starPower_le (w : J → ℕ) (n : ℕ) :
+ (F.contractionValue (tensorPowerFin n (starTensor (fun j ↦ Fin (2 ^ w j)))) : ℝ) ≤
+ (2 : ℝ) ^ ((n : ℝ) * F.starRate w) := by
+ apply (F.isLUB_contractionValue _).2
+ rintro _ ⟨ξ, rfl⟩
+ exact F.starPower_contraction_le w n ξ
+
+/-- The contraction values of the powered old factor and star in the proof
+of Theorem 2.4 have the prescribed exponential rate. -/
+theorem starPower_contractionRoot (T : Tensor k J) (w : J → ℕ) (u : ℕ) :
+ Filter.Tendsto (fun m : ℕ ↦
+ (F.contractionValue (tensorProduct (embedOld (tensorPowerFin m T))
+ (tensorPowerFin (u * m) (starTensor (fun j ↦ Fin (2 ^ w j))))) : ℝ) ^ (m : ℝ)⁻¹)
+ Filter.atTop (nhds ((F.value T : ℝ) * (2 : ℝ) ^ ((u : ℝ) * F.starRate w))) := by
+ apply VPVNP.Spectral.starContractionRoot_tendsto (StarWitness.height (w := w) (k := k))
+ (fun W ↦ (F.value W.tensor : ℝ)) u _ (by positivity) (fun W ↦ F.starWitness_pos W)
+ (F.starRate_isLUB w)
+ · intro W m _
+ obtain ⟨ξ, hξ⟩ := F.starPower_exists_packed w W (u * m)
+ rw [F.contractionValue_old_product, F.value_tensorPowerFin, NNReal.coe_mul, NNReal.coe_pow, hξ]
+ exact mul_le_mul_of_nonneg_left (NNReal.coe_le_coe.mpr (F.value_le_contractionValue _ ξ))
+ (by positivity)
+ · intro m _
+ rw [F.contractionValue_old_product, F.value_tensorPowerFin, NNReal.coe_mul, NNReal.coe_pow, mul_pow]
+ apply mul_le_mul_of_nonneg_left _ (by positivity)
+ refine (F.contractionValue_starPower_le w (u * m)).trans_eq ?_
+ rw [← Real.rpow_mul_natCast (by norm_num), Nat.cast_mul]
+ ring_nf
+
+omit [Nonempty J] in
+/-- The spectral value of the dyadic star is the exponential of its weighted wire sum. -/
+theorem value_dyadicStar (H : SpectralPoint k (Option J)) (w : J → ℕ) :
+ (H.value (starTensor (fun j ↦ Fin (2 ^ w j))) : ℝ) =
+ (2 : ℝ) ^ (∑ j, (w j : ℝ) * H.wireDistance none (some j)) := by
+ rw [← H.value_eq_of_mutual (starTensor_wireNetwork (fun j ↦ Fin (2 ^ w j)))]
+ exact H.value_binary_wireNetwork _ _ w
+
+/-- Every extension of the given spectral point has weighted star length at
+least the old width-profile rate. -/
+theorem starRate_le_extension (H : SpectralPoint k (Option J))
+ (extendsOld : ∀ T, H.value (embedOld T) = F.value T) (w : J → ℕ) :
+ F.starRate w ≤ ∑ j, (w j : ℝ) * H.wireDistance none (some j) := by
+ apply (F.starRate_isLUB w).2
+ rintro _ ⟨W, rfl⟩
+ let w' (j : J) := W.height * w j
+ have hrest := restricts_embedOld_contractCenter (starTensor (fun j ↦ Fin (2 ^ w' j))) W.coeff
+ rw [contractCenter_starTensor] at hrest
+ have hval : (F.value W.tensor : ℝ) ≤ (H.value (starTensor (fun j ↦ Fin (2 ^ w' j))) : ℝ) := by
+ rw [← extendsOld]
+ exact_mod_cast H.monotone hrest
+ rw [value_dyadicStar H w'] at hval
+ have hlog := (Real.logb_le_iff_le_rpow (by norm_num : 1 < (2 : ℝ)) (F.starWitness_pos W)).mpr hval
+ apply (div_le_iff₀ (show 0 < (W.height : ℝ) by exact_mod_cast W.positive)).mpr
+ rw [mul_comm, Finset.mul_sum]
+ simpa only [w', Nat.cast_mul, mul_assoc] using hlog
+
+end SpectralPoint
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StarTensor.lean b/lean/OAI/Computability/VPVNP/StarTensor.lean
new file mode 100644
index 0000000000..0817c819c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StarTensor.lean
@@ -0,0 +1,208 @@
+import OAI.Computability.VPVNP.WireTensor
+
+/-!
+# Adding a center to a tensor
+
+In the star construction of Theorem 2.4, the added party holds one end of
+every wire. Its product basis is indexed by the full tuple of leaf indices.
+A covector at the center can therefore specify the entries of an arbitrary
+old-party tensor independently.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v w
+
+namespace WireTensor
+
+variable {k : Type u} {J : Type v}
+
+/-- Extend an old tuple of indices by an index for the additional party. -/
+def withCenter {B : Option J → Type w} (c : B none) (x : (j : J) → B (some j)) :
+ (t : Option J) → B t
+ | none => c
+ | some j => x j
+
+/-- Embed an old tensor by using a one-dimensional factor at the center. -/
+def embedOld (T : Tensor.{u,v,w} k J) : Tensor.{u,v,w} k (Option J) where
+ Basis
+ | none => PUnit
+ | some j => T.Basis j
+ finiteBasis
+ | none => inferInstance
+ | some j => T.finiteBasis j
+ coeff x := T.coeff (fun j ↦ x (some j))
+
+/-- Evaluate a covector on the center leg while keeping all the old legs. -/
+def contractCenter [CommSemiring k] (T : Tensor.{u,v,w} k (Option J))
+ (ξ : T.Basis none → k) : Tensor.{u,v,w} k J where
+ Basis j := T.Basis (some j)
+ finiteBasis j := T.finiteBasis (some j)
+ coeff x := ∑ c, ξ c * T.coeff (withCenter c x)
+
+/-- The basis of a star of wires. The center stores a tuple and leaf `j`
+stores only its component at `j`. -/
+def starBasis (I : J → Type v) : Option J → Type v
+ | none => (j : J) → I j
+ | some j => I j
+
+/-- Equality wires from the center to every old party, in their product basis. -/
+noncomputable def starTensor [Fintype J] [Zero k] [One k]
+ (I : J → Type v) [∀ j, Fintype (I j)] : Tensor k (Option J) where
+ Basis := starBasis I
+ finiteBasis
+ | none => by classical exact Pi.instFintype
+ | some j => inferInstanceAs (Fintype (I j))
+ coeff x := by
+ classical exact if x none = fun j ↦ x (some j) then 1 else 0
+
+/-- A single unrestricted covector on the center of the star realizes any
+coefficient array in the indicated local dimensions. -/
+theorem contractCenter_starTensor [Fintype J] [CommSemiring k]
+ (I : J → Type v) [b : ∀ j, Fintype (I j)] (T : Array k I) :
+ contractCenter (starTensor I) T = Tensor.mk I b T := by
+ classical
+ unfold contractCenter
+ dsimp only [starTensor, starBasis, withCenter]
+ congr 1
+ funext x
+ rw [Finset.sum_eq_single x]
+ · simp
+ · intro c _ hc
+ simp [hc]
+ · intro h
+ exact (h (Finset.mem_univ _)).elim
+
+/-- A tensor power with its copies indexed by `Fin n` and their local legs
+grouped at each party. -/
+def tensorPowerFin [CommMonoid k] (n : ℕ) (T : Tensor.{u,v,w} k J) :
+ Tensor.{u,v,w} k J where
+ Basis j := Fin n → T.Basis j
+ finiteBasis j := inferInstanceAs (Fintype (Fin n → T.Basis j))
+ coeff x := ∏ a, T.coeff (fun j ↦ x j a)
+
+
+private def starNetworkBasisEquiv (I : J → Type v) (t : Option J) :
+ starBasis I t ≃ (((j : J) → t = none → I j) × ((j : J) → t = some j → I j)) :=
+ match t with
+ | none =>
+ { toFun := fun c ↦ ⟨fun j _ ↦ c j, fun _ h ↦ nomatch h⟩
+ invFun := fun x j ↦ x.1 j rfl
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ by
+ apply Prod.ext
+ · rfl
+ · funext j h; exact nomatch h }
+ | some i =>
+ { toFun := fun c ↦ ⟨(fun _ h ↦ nomatch h), fun j h ↦ cast (congrArg I (Option.some.inj h)) c⟩
+ invFun := fun x ↦ x.2 i rfl
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ by
+ apply Prod.ext
+ · funext j h; exact nomatch h
+ · funext j h
+ obtain rfl := Option.some.inj h
+ rfl }
+
+/-- The tuple-indexed star is the wire network joining the center to each
+leaf, up to invertible local changes of basis. -/
+theorem starTensor_wireNetwork [Fintype J] [CommSemiring k]
+ (I : J → Type v) [∀ j, Fintype (I j)] :
+ Restricts (wireNetwork (k := k) (fun _ ↦ none) some I) (starTensor I) ∧
+ Restricts (starTensor I) (wireNetwork (k := k) (fun _ ↦ none) some I) := by
+ classical
+ apply restricts_of_reindex (starNetworkBasisEquiv I)
+ intro x
+ simp only [starTensor, wireNetwork, Fintype.prod_boole]
+ congr 1
+ apply propext
+ change (x none = fun j ↦ x (some j)) ↔ ∀ j : J, x none j = x (some j)
+ exact funext_iff
+
+private def starProductBasisEquiv (I K : J → Type v) (t : Option J) :
+ starBasis (fun j ↦ I j × K j) t ≃ (starBasis I t × starBasis K t) :=
+ match t with
+ | none => Equiv.arrowProdEquivProdArrow J I K
+ | some _ => Equiv.refl _
+
+private theorem indicator_eq_product [MulZeroOneClass k] {P Q R : Prop}
+ [Decidable P] [Decidable Q] [Decidable R] (h : P ↔ Q ∧ R) :
+ (if P then (1 : k) else 0) = (if Q then 1 else 0) * (if R then 1 else 0) := by
+ split_ifs <;> simp_all
+
+/-- Multiplying two stars independently combines their two sets of wire
+indices at each leaf and at the center. -/
+theorem starTensor_tensorProduct [Fintype J] [CommSemiring k]
+ (I K : J → Type v) [∀ j, Fintype (I j)] [∀ j, Fintype (K j)] :
+ Restricts (tensorProduct (starTensor (k := k) I) (starTensor K))
+ (starTensor (fun j ↦ I j × K j)) ∧
+ Restricts (starTensor (k := k) (fun j ↦ I j × K j))
+ (tensorProduct (starTensor I) (starTensor K)) := by
+ classical
+ apply restricts_of_reindex (starProductBasisEquiv I K)
+ intro x
+ let f : (j : J) → I j × K j := x none
+ let g : (j : J) → I j × K j := fun j ↦ x (some j)
+ let e := Equiv.arrowProdEquivProdArrow J I K
+ have he : f = g ↔ (e f).1 = (e g).1 ∧ (e f).2 = (e g).2 :=
+ e.injective.eq_iff.symm.trans Prod.ext_iff
+ apply indicator_eq_product
+ exact he
+
+private def starPowerBasisEquiv (I : J → Type v) (n : ℕ) (t : Option J) :
+ starBasis (fun j ↦ Fin n → I j) t ≃ (Fin n → starBasis I t) :=
+ match t with
+ | none => ⟨fun x a j ↦ x j a, fun x j a ↦ x a j, fun _ ↦ rfl, fun _ ↦ rfl⟩
+ | some _ => Equiv.refl _
+
+/-- The power of a star has one enlarged wire of dimension `|I j| ^ n` at
+each leaf. This identifies its joint center, including the zeroth power. -/
+theorem starTensor_powerFin [Fintype J] [CommSemiring k]
+ (I : J → Type v) [∀ j, Fintype (I j)] (n : ℕ) :
+ Restricts (tensorPowerFin n (starTensor (k := k) I))
+ (starTensor (fun j ↦ Fin n → I j)) ∧
+ Restricts (starTensor (k := k) (fun j ↦ Fin n → I j))
+ (tensorPowerFin n (starTensor I)) := by
+ classical
+ apply restricts_of_reindex (starPowerBasisEquiv I n)
+ intro x
+ simp only [starTensor, tensorPowerFin, Fintype.prod_boole]
+ congr 1
+ apply propext
+ change (x none = fun j ↦ x (some j)) ↔
+ ∀ a : Fin n, (fun j ↦ x none j a) = fun j ↦ x (some j) a
+ constructor
+ · intro h a
+ exact funext fun j ↦ congrFun (congrFun h j) a
+ · intro h
+ exact funext fun j ↦ funext fun a ↦ congrFun (h a) j
+
+/-- Arbitrary leaf coefficients on a power of the star are realized by one
+covector on its entire center leg. Its coordinates transpose the copy and
+party indices. -/
+theorem contractCenter_starPowerFin [Fintype J] [CommSemiring k]
+ (I : J → Type v) [∀ j, Fintype (I j)] (n : ℕ) (T : Array k (fun j ↦ Fin n → I j)) :
+ ∃ ξ : (tensorPowerFin n (starTensor (k := k) I)).Basis none → k,
+ (contractCenter (tensorPowerFin n (starTensor I)) ξ).coeff = T := by
+ classical
+ refine ⟨fun c ↦ T (fun j a ↦ c a j), ?_⟩
+ funext x
+ change (j : J) → Fin n → I j at x
+ simp only [contractCenter, tensorPowerFin, starTensor, withCenter, starBasis]
+ let c : Fin n → (j : J) → I j := fun a j ↦ x j a
+ rw [Finset.sum_eq_single c]
+ · simp [c]
+ · intro b _ hb
+ have h : ¬ ∀ a : Fin n, b a = fun j ↦ x j a := fun H ↦ hb (funext H)
+ obtain ⟨a, ha⟩ := Classical.not_forall.mp h
+ exact mul_eq_zero_of_right _ (Finset.prod_eq_zero (Finset.mem_univ a) (by simp only [ha, ↓reduceIte]))
+ · intro h
+ exact (h (Finset.mem_univ _)).elim
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StateCount.lean b/lean/OAI/Computability/VPVNP/StateCount.lean
new file mode 100644
index 0000000000..6ac83f0543
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StateCount.lean
@@ -0,0 +1,337 @@
+import OAI.Computability.VPVNP.ShiftedFactorization
+import Lemmata.FockCircuits.PartitionAnalysis
+import Mathlib.Analysis.SpecialFunctions.Log.Base
+import Mathlib.Data.Finset.Fin
+
+/-!
+# State counts for the shifted crossing
+
+Appendix B of *VP and VNP differ over every field* bounds the sizes of two
+integral factorizations using different energy cutoffs. Energies here are
+doubled, so a signed integer shift changes the cutoff by twice that integer.
+
+We use the fermionic partition asymptotic from Khoruzhii's development, count
+the finite-mode states, and evaluate the two dimension sequences and both
+factorization bounds for the same shift.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+open Filter
+open scoped Topology BigOperators
+open Lemmata.FockCircuits (partitionSlice partitionDimension mem_partitionSlice fermionIntegral
+ fermionIntegral_pos partitionDimension_zero partition_cumulative_log_tendsto cumulativeWeight)
+
+/-- Number of fermionic states of doubled energy at most `H`. Each occupied
+mode `i` contributes `2*i+1`. -/
+def cutoffCount (H : ℕ) : ℕ :=
+ ∑ k ∈ Finset.range (H+1), partitionDimension k
+
+/-- Base-two growth constant for a cutoff measured in doubled energy. -/
+noncomputable def stateExponent : ℝ :=
+ 2 * Real.sqrt (fermionIntegral / 2) / Real.log 2
+
+theorem stateExponent_pos : 0 < stateExponent :=
+ div_pos (mul_pos (by norm_num) (Real.sqrt_pos.mpr (half_pos fermionIntegral_pos)))
+ (Real.log_pos (by norm_num))
+
+theorem cutoffCount_pos (H : ℕ) : 0 < cutoffCount H := by
+ have h := Finset.single_le_sum (s := Finset.range (H+1)) (f := partitionDimension)
+ (fun _ _ => Nat.zero_le _) (a := 0) (Finset.mem_range.mpr (Nat.zero_lt_succ H))
+ exact (Nat.zero_lt_one.trans_le (by simpa only [partitionDimension_zero, cutoffCount] using h))
+
+/-- The partition-function asymptotic in the logarithmic base and energy units
+of the two shifted flattening bounds. -/
+theorem cutoffCount_limit :
+ Tendsto (fun k : ℕ => Real.logb 2 (cutoffCount k) / Real.sqrt k)
+ atTop (𝓝 stateExponent) := by
+ have h := partition_cumulative_log_tendsto.div_const (Real.log 2)
+ apply h.congr fun k => ?_
+ simp only [cumulativeWeight, Real.logb, cutoffCount, Nat.cast_sum]
+ ring
+
+private def partitionCutoff (k : ℕ) : Finset (Finset ℕ) :=
+ (Finset.range (k+1)).biUnion partitionSlice
+
+private theorem mem_partitionCutoff {k : ℕ} {s : Finset ℕ} :
+ s ∈ partitionCutoff k ↔ Lemmata.FockCircuits.doubledEnergy s ≤ k := by
+ simp only [partitionCutoff, Finset.mem_biUnion, Finset.mem_range, mem_partitionSlice]
+ constructor
+ · rintro ⟨e, he, rfl⟩
+ omega
+ · intro hs
+ exact ⟨_, by omega, rfl⟩
+
+private theorem card_partitionCutoff (k : ℕ) :
+ (partitionCutoff k).card = cutoffCount k := by
+ apply Finset.card_biUnion
+ intro a _ b _ hab
+ apply Finset.disjoint_left.mpr
+ intro s hsa hsb
+ exact hab ((mem_partitionSlice.mp hsa).symm.trans (mem_partitionSlice.mp hsb))
+
+theorem doubledEnergy_map_val {N : ℕ} (s : Occupation N) :
+ (Lemmata.FockCircuits.doubledEnergy (s.map Fin.valEmbedding) : ℤ) = doubledEnergy s := by
+ simp [Lemmata.FockCircuits.doubledEnergy, doubledEnergy, Fin.valEmbedding]
+
+private def forgetModeBound (N k : ℕ) :
+ {s : Occupation N // doubledEnergy s ≤ (k : ℤ)} ↪ partitionCutoff k where
+ toFun s := ⟨s.val.map Fin.valEmbedding, mem_partitionCutoff.mpr (by
+ exact_mod_cast ((doubledEnergy_map_val s.val).le.trans s.property))⟩
+ inj' := fun _ _ h => Subtype.ext <| Finset.map_injective Fin.valEmbedding (congrArg Subtype.val h)
+
+/-- The dimension bound for finite occupation states of doubled energy at most `k`. -/
+theorem occupationCount_le (N k : ℕ) :
+ Fintype.card {s : Occupation N // doubledEnergy s ≤ (k : ℤ)} ≤
+ cutoffCount k := by
+ rw [← card_partitionCutoff, ← Fintype.card_coe]
+ exact Fintype.card_le_of_injective _ (forgetModeBound N k).injective
+
+/-- Once modes below `k` are included, the entire partition cutoff occurs. -/
+theorem occupationCount_eq (N k : ℕ) (hk : k ≤ N) :
+ Fintype.card {s : Occupation N // doubledEnergy s ≤ (k : ℤ)} =
+ cutoffCount k := by
+ rw [← card_partitionCutoff, ← Fintype.card_coe]
+ apply Fintype.card_of_bijective (f := forgetModeBound N k)
+ refine ⟨(forgetModeBound N k).injective, ?_⟩
+ intro s
+ have hs := mem_partitionCutoff.mp s.property
+ have hb (i : ℕ) (hi : i ∈ s.val) : i < N := by
+ have hi' := Finset.single_le_sum (f := fun j : ℕ => 2*j+1) (fun j _ => Nat.zero_le _) hi
+ change 2*i+1 ≤ Lemmata.FockCircuits.doubledEnergy s.val at hi'
+ omega
+ refine ⟨⟨s.val.attachFin hb, ?_⟩, ?_⟩
+ · rw [← doubledEnergy_map_val, Finset.map_valEmbedding_attachFin]
+ exact_mod_cast hs
+ · exact Subtype.ext (Finset.map_valEmbedding_attachFin hb)
+
+/-- A negative doubled-energy cutoff contains no states, including the vacuum. -/
+theorem occupationCount_of_neg (N : ℕ) {B : ℤ} (hB : B < 0) :
+ Fintype.card {s : Occupation N // doubledEnergy s ≤ B} = 0 := by
+ apply Fintype.card_eq_zero_iff.mpr
+ refine ⟨fun s => ?_⟩
+ have h := s.property
+ rw [← doubledEnergy_map_val] at h
+ omega
+
+/-- A signed integer cut at quadratic scale. In particular the displacement may be negative. -/
+noncomputable def roundedQuadratic (a : ℝ) (n : ℕ) : ℤ :=
+ ⌊(n : ℝ) ^ 2 * a⌋
+
+theorem tendsto_roundedQuadratic (a : ℝ) :
+ Tendsto (fun n : ℕ ↦ (roundedQuadratic a n : ℝ) / (n : ℝ) ^ 2) atTop (𝓝 a) := by
+ have hinv : Tendsto (fun n : ℕ ↦ 1 / (n : ℝ) ^ 2) atTop (𝓝 0) :=
+ tendsto_const_nhds.div_atTop ((tendsto_pow_atTop (by decide : 2 ≠ 0)).comp
+ tendsto_natCast_atTop_atTop)
+ have hlower : Tendsto (fun n : ℕ ↦ a - 1 / (n : ℝ) ^ 2) atTop (𝓝 a) := by
+ simpa using tendsto_const_nhds.sub hinv
+ refine tendsto_of_tendsto_of_tendsto_of_le_of_le' hlower tendsto_const_nhds ?_ ?_
+ · filter_upwards [eventually_gt_atTop (0 : ℕ)] with n hn
+ have hn' : 0 < (n : ℝ) ^ 2 := by positivity
+ change a - 1 / (n : ℝ) ^ 2 ≤ (⌊(n : ℝ) ^ 2 * a⌋ : ℝ) / (n : ℝ) ^ 2
+ rw [le_div_iff₀ hn', sub_mul, div_mul_cancel₀ _ hn'.ne']
+ linarith only [Int.lt_floor_add_one ((n : ℝ) ^ 2 * a)]
+ · filter_upwards [eventually_gt_atTop (0 : ℕ)] with n hn
+ have hn' : 0 < (n : ℝ) ^ 2 := by positivity
+ exact (div_le_iff₀ hn').2 (mul_comm a ((n : ℝ) ^ 2) ▸ Int.floor_le _)
+
+/-- A nonnegative integer energy, obtained from the signed cut by truncation at zero. -/
+noncomputable def quadraticEnergy (a : ℝ) (n : ℕ) : ℕ :=
+ (roundedQuadratic a n).toNat
+
+private theorem tendsto_quadraticScale_toNat {g : ℕ → ℤ} {a : ℝ} (ha : 0 < a)
+ (hg : Tendsto (fun n : ℕ ↦ (g n : ℝ) / (n : ℝ) ^ 2) atTop (𝓝 a)) :
+ Tendsto (fun n : ℕ ↦ ((g n).toNat : ℝ) / (n : ℝ) ^ 2) atTop (𝓝 a) := by
+ apply hg.congr'
+ filter_upwards [hg.eventually_const_lt ha] with n hn
+ have hnonneg : (0 : ℝ) ≤ g n := by
+ by_contra! hneg
+ exact hn.not_ge (div_nonpos_of_nonpos_of_nonneg hneg.le (sq_nonneg _))
+ have hcast := Int.toNat_of_nonneg (show 0 ≤ g n by exact_mod_cast hnonneg)
+ have heq : ((g n).toNat : ℝ) = g n := by exact_mod_cast hcast
+ exact congrArg (fun x : ℝ ↦ x / (n : ℝ) ^ 2) heq.symm
+
+theorem tendsto_quadraticEnergy {a : ℝ} (ha : 0 < a) :
+ Tendsto (fun n : ℕ ↦ (quadraticEnergy a n : ℝ) / (n : ℝ) ^ 2) atTop (𝓝 a) :=
+ tendsto_quadraticScale_toNat ha (tendsto_roundedQuadratic a)
+
+/-- Both shifted energies use the same integer displacement. -/
+noncomputable def shiftedEnergy (v w δ : ℝ) (positive : Bool) (n : ℕ) : ℕ :=
+ let base : ℤ := quadraticEnergy v n + (quadraticEnergy w n : ℤ)
+ let displacement := 2 * roundedQuadratic δ n
+ (if positive then base + displacement else base - displacement).toNat
+
+theorem tendsto_shiftedEnergy {v w δ : ℝ} (hv : 0 < v) (hw : 0 < w) (positive : Bool)
+ (h : 0 < (if positive then v + w + 2 * δ else v + w - 2 * δ)) :
+ Tendsto (fun n : ℕ ↦ (shiftedEnergy v w δ positive n : ℝ) / (n : ℝ) ^ 2)
+ atTop (𝓝 (if positive then v + w + 2 * δ else v + w - 2 * δ)) := by
+ have hbase := (tendsto_quadraticEnergy hv).add (tendsto_quadraticEnergy hw)
+ have hdisp := (tendsto_roundedQuadratic δ).const_mul 2
+ unfold shiftedEnergy
+ apply tendsto_quadraticScale_toNat h
+ cases positive
+ · simpa only [Bool.false_eq_true, ↓reduceIte, Int.cast_sub, Int.cast_add, Int.cast_natCast,
+ Int.cast_mul, Int.cast_ofNat, sub_div, add_div, mul_div_assoc] using hbase.sub hdisp
+ · simpa only [↓reduceIte, Int.cast_add, Int.cast_natCast, Int.cast_mul, Int.cast_ofNat,
+ add_div, mul_div_assoc] using hbase.add hdisp
+
+/-- The logarithmic state-count asymptotic along an integral cutoff growing as
+`v * n²`. The growth constant is expressed in base two. -/
+theorem count_quadratic_limit (D H : ℕ → ℕ) {c v : ℝ} (hv : 0 < v)
+ (hD : Tendsto (fun k : ℕ => Real.logb 2 (D k) / Real.sqrt k) atTop (𝓝 c))
+ (hH : Tendsto (fun n : ℕ => (H n : ℝ) / (n : ℝ)^2) atTop (𝓝 v)) :
+ Tendsto (fun n : ℕ => Real.logb 2 (D (H n)) / n) atTop (𝓝 (c * Real.sqrt v)) := by
+ have hn : Tendsto (fun n : ℕ => (n : ℝ)) atTop atTop := tendsto_natCast_atTop_atTop
+ have hn2 : Tendsto (fun n : ℕ => (n : ℝ)^2) atTop atTop :=
+ (tendsto_pow_atTop (by decide : 2 ≠ 0)).comp hn
+ have hHreal := hH.pos_mul_atTop hv hn2
+ have hHtop : Tendsto H atTop atTop := by
+ apply (tendsto_natCast_atTop_iff (R := ℝ)).mp
+ apply hHreal.congr'
+ filter_upwards [eventually_ne_atTop (0 : ℕ)] with n hn
+ have hn' : (n : ℝ) ≠ 0 := by exact_mod_cast hn
+ simp [hn']
+ have hs : Tendsto (fun n : ℕ => Real.sqrt (H n) / n) atTop (𝓝 (Real.sqrt v)) := by
+ refine hH.sqrt.congr fun n => ?_
+ rw [Real.sqrt_div (Nat.cast_nonneg _), Real.sqrt_sq (Nat.cast_nonneg _)]
+ refine ((hD.comp hHtop).mul hs).congr' ?_
+ filter_upwards [hHtop.eventually_gt_atTop 0] with n hn
+ have hp : Real.sqrt (H n) ≠ 0 := (Real.sqrt_pos.mpr (by exact_mod_cast hn)).ne'
+ change Real.logb 2 (D (H n)) / Real.sqrt (H n) * (Real.sqrt (H n) / n) =
+ Real.logb 2 (D (H n)) / n
+ field_simp [hp]
+
+/-- A fixed power of the quadratic energy cutoff has subexponential size. -/
+theorem logb_polynomial_overhead (h : ℕ → ℕ) (v : ℝ) (d : ℕ)
+ (hh : Tendsto (fun n : ℕ ↦ (h n : ℝ) / (n : ℝ)^2) atTop (𝓝 v)) :
+ Tendsto (fun n : ℕ ↦ Real.logb 2 (((h n + 1)^d : ℕ) : ℝ) / n) atTop (𝓝 0) := by
+ have hlog : Tendsto (fun n : ℕ ↦ Real.logb 2 (n : ℝ) / n) atTop (𝓝 0) := by
+ simpa [Function.comp_def] using
+ (Real.tendsto_pow_logb_div_mul_add_atTop (b := 2) 1 0 1 one_ne_zero).comp
+ (tendsto_natCast_atTop_atTop (R := ℝ))
+ have upper : Tendsto (fun n : ℕ ↦ ((d : ℝ) * 3) * (Real.logb 2 n / n)) atTop (𝓝 0) := by
+ simpa using hlog.const_mul ((d : ℝ) * 3)
+ apply squeeze_zero' _ _ upper
+ · filter_upwards with n
+ apply div_nonneg _ (Nat.cast_nonneg n)
+ apply Real.logb_nonneg (by norm_num)
+ exact_mod_cast Nat.one_le_pow _ _ (by omega)
+ · filter_upwards [hh.eventually (gt_mem_nhds (show v < v + 1 by linarith)),
+ (tendsto_natCast_atTop_atTop (R := ℝ)).eventually_ge_atTop (v+2),
+ eventually_ge_atTop (1 : ℕ)] with n hn hv hn1
+ have hn' : (1 : ℝ) ≤ n := by exact_mod_cast hn1
+ have hnpos : 0 < (n : ℝ) := by linarith
+ have hh' : (h n : ℝ) < (v + 1) * (n : ℝ)^2 :=
+ (div_lt_iff₀ (sq_pos_of_pos hnpos)).mp hn
+ have bound : (h n : ℝ) + 1 ≤ (n : ℝ)^3 := by
+ nlinarith [mul_nonneg (sub_nonneg.mpr hv) (sq_nonneg (n : ℝ)),
+ sq_nonneg ((n : ℝ)-1)]
+ simp only [Nat.cast_pow, Nat.cast_add, Nat.cast_one, Real.logb_pow]
+ calc
+ _ ≤ (d : ℝ) * Real.logb 2 ((n : ℝ)^3) / n :=
+ div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left
+ (Real.logb_le_logb_of_le (by norm_num) (by positivity) bound) (by positivity))
+ (by positivity)
+ _ = _ := by rw [Real.logb_pow]; push_cast; ring
+
+/-- Removing the empty state preserves any positive exponential growth rate. -/
+theorem logb_pred_rate (D : ℕ → ℕ) (t : ℝ) (ht : 0 < t)
+ (hD : Tendsto (fun n : ℕ ↦ Real.logb 2 (D n : ℝ) / n) atTop (𝓝 t)) :
+ Tendsto (fun n : ℕ ↦ Real.logb 2 ((D n - 1 : ℕ) : ℝ) / n) atTop (𝓝 t) := by
+ have hlarge : ∀ᶠ n in atTop, 2 ≤ D n := by
+ filter_upwards [hD.eventually (lt_mem_nhds ht)] with n hn
+ by_contra! h
+ have heq : D n = 0 ∨ D n = 1 := by omega
+ rcases heq with h0 | h1 <;> simp_all
+ have hlower : Tendsto (fun n : ℕ ↦ Real.logb 2 (D n : ℝ) / n - 1 / n) atTop (𝓝 t) := by
+ simpa using hD.sub (tendsto_const_div_atTop_nhds_zero_nat (1 : ℝ))
+ apply tendsto_of_tendsto_of_tendsto_of_le_of_le' hlower hD
+ · filter_upwards [hlarge] with n hn
+ have h1 : 0 < ((D n - 1 : ℕ) : ℝ) := by exact_mod_cast (show 0 < D n - 1 by omega)
+ have h2 : (D n : ℝ) ≤ ((D n - 1 : ℕ) : ℝ) * 2 := by
+ exact_mod_cast (show D n ≤ (D n - 1) * 2 by omega)
+ have H := Real.logb_le_logb_of_le (b := 2) (by norm_num)
+ (by exact_mod_cast (show 0 < D n by omega)) h2
+ rw [Real.logb_mul h1.ne' (by norm_num), Real.logb_self_eq_one (by norm_num)] at H
+ rw [← sub_div]
+ exact div_le_div_of_nonneg_right (by linarith) (by positivity)
+ · filter_upwards [hlarge] with n hn
+ apply div_le_div_of_nonneg_right _ (by positivity)
+ exact Real.logb_le_logb_of_le (by norm_num)
+ (by exact_mod_cast (show 0 < D n - 1 by omega)) (by exact_mod_cast Nat.sub_le (D n) 1)
+
+/-- Doubled-energy cutoff of a wire with prescribed base-two logarithmic rate. -/
+noncomputable def crossingEnergy (t : ℝ) (n : ℕ) : ℕ :=
+ quadraticEnergy ((t / stateExponent)^2) n
+
+/-- The integer shift shared by the two crossing factorizations. -/
+noncomputable def crossingShift (δ : ℝ) (n : ℕ) : ℤ :=
+ roundedQuadratic (δ / (2 * stateExponent^2)) n
+
+/-- The number of available factor coordinates on one of the two cuts, including
+the polynomial cost of summing over cardinalities, energies, and monomials. -/
+noncomputable def crossingFactorBound (t u δ : ℝ) (positive : Bool) (n : ℕ) : ℕ :=
+ let H := crossingEnergy t n
+ let E := crossingEnergy u n
+ let s := crossingShift δ n
+ let B : ℤ := if positive then H + (E : ℤ) + 2*s else H + (E : ℤ) - 2*s
+ (H+1)^4 * cutoffCount B.toNat
+
+theorem crossingEnergy_count_limit (t : ℝ) (ht : 0 < t) :
+ Tendsto (fun n : ℕ => Real.logb 2 (cutoffCount (crossingEnergy t n)) / n)
+ atTop (𝓝 t) := by
+ have hp := div_pos ht stateExponent_pos
+ have h := count_quadratic_limit cutoffCount (crossingEnergy t) (sq_pos_of_pos hp)
+ cutoffCount_limit (tendsto_quadraticEnergy (sq_pos_of_pos hp))
+ rwa [Real.sqrt_sq hp.le, mul_div_cancel₀ _ stateExponent_pos.ne'] at h
+
+/-- The exponential rates in Theorem 3.1, using one integral displacement for both
+bounds. The first dimension omits the empty state and the second includes it. -/
+theorem shiftedCrossing_rates (t u δ : ℝ) (ht : 0 < t) (hu : 0 < u)
+ (hlo : -(t^2+u^2) < δ) (hhi : δ < t^2+u^2) :
+ Tendsto (fun n : ℕ => Real.logb 2 ((cutoffCount (crossingEnergy t n) - 1 : ℕ) : ℝ) / n)
+ atTop (𝓝 t) ∧
+ Tendsto (fun n : ℕ => Real.logb 2 (cutoffCount (crossingEnergy u n)) / n)
+ atTop (𝓝 u) ∧
+ ∀ positive : Bool,
+ Tendsto (fun n : ℕ => Real.logb 2 (crossingFactorBound t u δ positive n) / n) atTop
+ (𝓝 (Real.sqrt (if positive then t^2+u^2+δ else t^2+u^2-δ))) := by
+ refine ⟨logb_pred_rate _ t ht (crossingEnergy_count_limit t ht),
+ crossingEnergy_count_limit u hu, ?_⟩
+ intro positive
+ let v := (t / stateExponent)^2
+ let w := (u / stateExponent)^2
+ let d := δ / (2 * stateExponent^2)
+ let T := if positive then t^2+u^2+δ else t^2+u^2-δ
+ have hc := stateExponent_pos
+ have hv : 0 < v := sq_pos_of_pos (div_pos ht hc)
+ have hw : 0 < w := sq_pos_of_pos (div_pos hu hc)
+ have hT : 0 < T := by cases positive <;> dsimp [T] <;> linarith
+ have hscale : (if positive then v + w + 2*d else v + w - 2*d) = T / stateExponent^2 := by
+ cases positive <;> dsimp [v, w, d, T] <;> field_simp
+ have hpos : 0 < (if positive then v + w + 2*d else v + w - 2*d) :=
+ hscale ▸ div_pos hT (sq_pos_of_pos hc)
+ have hcount := count_quadratic_limit cutoffCount (shiftedEnergy v w d positive)
+ hpos cutoffCount_limit (tendsto_shiftedEnergy hv hw positive hpos)
+ rw [hscale, Real.sqrt_div hT.le, Real.sqrt_sq hc.le, mul_div_cancel₀ _ hc.ne'] at hcount
+ have hpoly := logb_polynomial_overhead (crossingEnergy t) v 4 (tendsto_quadraticEnergy hv)
+ have htotal := hpoly.add hcount
+ rw [zero_add] at htotal
+ apply htotal.congr fun n => ?_
+ change Real.logb 2 (((crossingEnergy t n + 1)^4 : ℕ) : ℝ) / n +
+ Real.logb 2 (cutoffCount (shiftedEnergy v w d positive n)) / n =
+ Real.logb 2 ((((crossingEnergy t n + 1)^4 : ℕ) *
+ cutoffCount (shiftedEnergy v w d positive n) : ℕ) : ℝ) / n
+ have hn : 0 < (cutoffCount (shiftedEnergy v w d positive n) : ℝ) := by
+ exact_mod_cast cutoffCount_pos _
+ rw [Nat.cast_mul, Real.logb_mul (by positivity) hn.ne', add_div]
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StatePassHistory.lean b/lean/OAI/Computability/VPVNP/StatePassHistory.lean
new file mode 100644
index 0000000000..1b0aeba1b6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StatePassHistory.lean
@@ -0,0 +1,101 @@
+import OAI.Computability.VPVNP.CompressionHistory
+
+/-!
+# Field records for the actual slots of a compression pass
+
+At each output site, keep the local motif records, both half-fields of every
+placed old vertex in every slot, and the new site's incoming and outgoing fields.
+Outgoing fields in these records cover the entire output width profile.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+open NetworkKernel
+open scoped Classical
+
+variable {a b g n : ℕ}
+
+/-- An outgoing slot reads its own arc and an incoming slot recovers its
+source by the inverse of the actual slot permutation. -/
+def State.halfWidth (X : State a g) (v : X.network.Site) (direction : Bool) (j : Fin (2 ^ a)) : ℕ :=
+ let e := ((v.1, j), v.2)
+ X.width (if direction then X.slots.actualTarget.symm e else e)
+
+theorem State.halfWidth_le_max (X : State a g) (v : X.network.Site) (dir : Bool) (j : Fin (2 ^ a)) :
+ X.halfWidth v dir j ≤ X.maxWireWidth := X.width_le_maxWireWidth _
+
+variable {R : Type*} [CommSemiring R] {X : State a g}
+
+namespace StatePass
+
+/-- Identify the term's output site with its site in the new lifted state. -/
+def outputSite (p : StatePass R X b n) (i : p.step.Choice) :
+ (p.step.term i).output.Site ≃ (p.next i).network.Site :=
+ Equiv.cast (congrArg Network.Site (p.output_eq i))
+
+/-- Include all old and new slot fields alongside the motif's local entries. -/
+noncomputable def slotRecords (p : StatePass R X b n) (extra : p.Records) : p.Records := fun i v =>
+ { Field := (extra i v).Field ⊕ (((p.step.term i).Preimage v × (Bool × Fin (2 ^ a))) ⊕
+ (Bool × Fin (2 ^ b)))
+ fieldFintype := inferInstance
+ width := Sum.elim (extra i v).width (Sum.elim
+ (fun x => X.halfWidth x.1.val x.2.1 x.2.2)
+ (fun x => (p.next i).halfWidth (p.outputSite i v) x.1 x.2))
+ Map := (extra i v).Map
+ mapFintype := inferInstance
+ degree := (extra i v).degree }
+
+set_option backward.isDefEq.respectTransparency false in
+theorem slotRecords_count (p : StatePass R X b n) (extra : p.Records) (i : p.step.Choice)
+ (v : (p.step.term i).output.Site) :
+ (p.slotRecords extra i v).count = (extra i v).count +
+ Fintype.card ((p.step.term i).Preimage v) * (2 * 2 ^ a) + 2 * 2 ^ b := by
+ simp [SiteRecords.count, slotRecords, Fintype.card_sum, Fintype.card_prod, Nat.add_assoc]
+
+/-- One constant bounds the substep even when the old graph, widths, placements,
+and selected terms vary. The extra records describe the local motif computations. -/
+theorem slotRecords_bounded (p : StatePass R X b n) (extra : p.Records) (A D E : ℕ) (hE : 1 ≤ E)
+ (hpre : ∀ i v, Fintype.card ((p.step.term i).Preimage v) ≤ A)
+ (hcount : ∀ i v, (extra i v).count ≤ D)
+ (hextra : ∀ i v, (extra i v).largest ≤ E * (X.maxWireWidth + 1))
+ (hnext : ∀ i e, (p.next i).width e ≤ E * (X.maxWireWidth + 1)) :
+ p.Bounded (p.slotRecords extra) (max (D + A * (2 * 2 ^ a) + 2 * 2 ^ b + A) (E + 1)) := by
+ intro i
+ refine ⟨fun v => ?_, ?_, ?_⟩
+ · rw [slotRecords_count]
+ apply le_trans _ (le_max_left _ _)
+ gcongr <;> first | exact hpre i v | exact hcount i v
+ · have hb : TermChain.largest (p.slotRecords extra i) ≤ E * (X.maxWireWidth + 1) := by
+ apply Finset.sup_le
+ intro v _
+ apply max_le
+ · apply Finset.sup_le
+ rintro (e | (e | e)) _
+ · exact ((extra i v).width_le_largest e).trans (hextra i v)
+ · exact (X.halfWidth_le_max _ _ _).trans (by nlinarith [Nat.zero_le X.maxWireWidth])
+ · exact hnext i _
+ · apply Finset.sup_le
+ intro j _
+ exact ((extra i v).degree_le_largest j).trans (hextra i v)
+ calc
+ _ ≤ E * (X.maxWireWidth + 1) + 1 := Nat.succ_le_succ hb
+ _ ≤ (E + 1) * (X.maxWireWidth + 1) := by rw [Nat.add_mul, Nat.one_mul]; omega
+ _ ≤ _ := Nat.mul_le_mul_right _ (le_max_right _ _)
+ · apply Finset.sup_le
+ rintro ⟨⟨x,j⟩, lane⟩ _
+ let v := (p.outputSite i).symm (x, lane)
+ have h := (p.slotRecords extra i v).width_le_largest (.inr (.inr (false,j)))
+ change (p.next i).halfWidth (p.outputSite i v) false j ≤ _ at h
+ rw [show p.outputSite i v = (x,lane) from (p.outputSite i).apply_symm_apply _] at h
+ exact h.trans (Finset.le_sup (f := fun u => (p.slotRecords extra i u).largest) (Finset.mem_univ v))
+
+end StatePass
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StructuredStackCall.lean b/lean/OAI/Computability/VPVNP/StructuredStackCall.lean
new file mode 100644
index 0000000000..5b0e8f2a73
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StructuredStackCall.lean
@@ -0,0 +1,43 @@
+import OAI.Computability.VPVNP.StructuredStacks
+
+/-! # Using an existing finite stack program as a returning routine
+
+The distinguished halt of a legacy program becomes a normal return to the caller.
+A deterministic execution ending at that halt has exactly the same length after
+installation, provided it starts outside the return state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Routine
+
+variable {K Q : Type*} [DecidableEq Q]
+
+/-- Redirect transitions entering the normal completion state to the caller. -/
+def ofCode (code : StackCode K Q) (entry done : Q) : Routine K Q where
+ entry := entry
+ code q := if q = done then .goto none else
+ (code q).rename id (fun q' => if q' = done then none else some q')
+
+theorem runs_ofCode [DecidableEq K] {code : StackCode K Q} {entry done : Q}
+ {t : ℕ} {s out : Stacks K} (hentry : entry ≠ done) (hdone : (code done).returns = true)
+ (run : StackRuns code t entry s done out) : (ofCode code entry done).Runs t s out := by
+ let labels (q : Q) : Option Q := if q = done then none else some q
+ let target := (ofCode code entry done).standalone
+ have hc (q : Q) (hq : (code q).returns = false) : target (labels q) = (code q).rename id labels := by
+ have hne : q ≠ done := fun h => by subst q; exact Bool.noConfusion (hdone.symm.trans hq)
+ simp [target, standalone, close, ofCode, labels, hne]
+ have hi (st : Stacks K) : installStacks id s st = st := by
+ funext k
+ exact installStacks_at Function.injective_id s st k
+ change StackRuns target t (some entry) s none out
+ simpa only [labels, ite_eq_right hentry, ite_eq_left rfl, hi] using
+ run.lift id Function.injective_id labels s hc
+
+end RAMTape.Routine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StructuredStackClock.lean b/lean/OAI/Computability/VPVNP/StructuredStackClock.lean
new file mode 100644
index 0000000000..c1539b9680
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StructuredStackClock.lean
@@ -0,0 +1,55 @@
+import OAI.Computability.VPVNP.StructuredStacks
+
+/-! # Stop bounds through deterministic prefixes of the transcript validator
+
+A deterministic parser consumes a known number of steps before entering the
+nondeterministic part of the validator. At that point every accepting or rejecting
+branch has its own path length. A common bound on all leaves permits any larger
+clock to be used without changing the path count.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+variable {K Q : Type*} [DecidableEq K] {code : StackCode K Q}
+
+/-- The normal stop budget of a deterministic prefix is added to the budget at its exit. -/
+theorem StackRuns.stopsWithin_iff {n q s u v} (h : StackRuns code n q s u v) (fuel : ℕ) :
+ StopsWithin code (fuel+n) q s ↔ StopsWithin code fuel u v := by
+ induction h with
+ | nil => rfl
+ | cons hs _ ih => cases hs <;> simp_all [StopsWithin]
+
+theorem StopsWithin.mono {n m : ℕ} (hnm : n ≤ m) {q : Q} {s : Stacks K}
+ (h : StopsWithin code n q s) : StopsWithin code m q s := by
+ induction n generalizing m q s with
+ | zero => exact h.elim
+ | succ n ih =>
+ obtain ⟨m, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : m ≠ 0)
+ cases he : code q <;> simp only [StopsWithin, he] at h ⊢
+ · exact ih (by omega) h
+ · exact ih (by omega) h
+ · exact ih (by omega) h
+ · exact ⟨ih (by omega) h.1, ih (by omega) h.2⟩
+
+/-- Once every leaf has halted, enlarging the budget preserves the entire multiplicity. -/
+theorem StopsWithin.stackPaths_eq {n m : ℕ} (hnm : n ≤ m) {q : Q} {s : Stacks K}
+ (h : StopsWithin code n q s) : stackPaths code m q s = stackPaths code n q s := by
+ induction n generalizing m q s with
+ | zero => exact h.elim
+ | succ n ih =>
+ obtain ⟨m, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : m ≠ 0)
+ cases he : code q <;> simp only [StopsWithin, he] at h <;> simp only [stackPaths, he]
+ · exact ih (by omega) h
+ · exact ih (by omega) h
+ · exact ih (by omega) h
+ · exact congrArg₂ (· + ·) (ih (by omega) h.1) (ih (by omega) h.2)
+
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StructuredStackCount.lean b/lean/OAI/Computability/VPVNP/StructuredStackCount.lean
new file mode 100644
index 0000000000..c3d3b6d0ca
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StructuredStackCount.lean
@@ -0,0 +1,46 @@
+import OAI.Computability.VPVNP.StructuredStacks
+
+/-! # Continuation counts after deterministic stack runs -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Routine
+
+variable {K Q : Type*} [DecidableEq K]
+
+private theorem countFrom_runs (r : Routine K Q) {q q' : Option Q} {s out : Stacks K} {n : ℕ}
+ (h : StackRuns r.standalone n q s q' out) (c : ℕ → Stacks K → ℕ) (fuel : ℕ) :
+ r.countFrom c (fuel+n) q s = r.countFrom c fuel q' out := by
+ induction h with
+ | nil => rfl
+ | @cons q₀ _ _ _ _ _ _ hs _ ih =>
+ cases q₀ with
+ | none => cases hs <;> simp [standalone, close] at *
+ | some q =>
+ cases hs with
+ | push h =>
+ simp only [standalone, close] at h
+ simp only [countFrom, h]
+ exact ih
+ | pop h =>
+ simp only [standalone, close] at h
+ simp only [countFrom, h]
+ exact ih
+ | goto h =>
+ simp only [standalone, close] at h
+ simp only [countFrom, h]
+ exact ih
+
+/-- A deterministic run to a normal return invokes the continuation once,
+with exactly the run length deducted from the available budget. -/
+theorem Runs.count_eq {r : Routine K Q} {n : ℕ} {s out : Stacks K} (h : r.Runs n s out)
+ (c : ℕ → Stacks K → ℕ) (fuel : ℕ) : r.count c (fuel + n) s = c fuel out :=
+ (countFrom_runs r h c fuel).trans (countFrom_none ..)
+
+end RAMTape.Routine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StructuredStackLink.lean b/lean/OAI/Computability/VPVNP/StructuredStackLink.lean
new file mode 100644
index 0000000000..7e7efb8219
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StructuredStackLink.lean
@@ -0,0 +1,38 @@
+import OAI.Computability.VPVNP.StructuredStacks
+
+/-! # Executing a structured routine inside its caller
+
+Installed instructions keep the same stack labels. The last ordinary
+instruction returns directly to the caller's continuation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Routine
+
+variable {K Q R : Type*} [DecidableEq K]
+
+/-- A deterministic run transfers to its caller without changing its cost. -/
+theorem Runs.link {inner : Routine K Q} {t : ℕ} {s out : Stacks K}
+ (run : inner.Runs t s out) (outer : Routine K R) (label : Q → R) (resume : Option R)
+ (h : ∀ q, outer.code (label q) = inner.install label resume q) :
+ StackRuns outer.standalone t (some (label inner.entry)) s resume out := by
+ let labels (q : Option Q) := q.elim resume (some ∘ label)
+ have hc (q : Option Q) (hq : (inner.standalone q).returns = false) :
+ outer.standalone (labels q) = (inner.standalone q).rename id labels := by
+ cases q with
+ | none => contradiction
+ | some q => exact h q
+ have hi (st : Stacks K) : installStacks id s st = st := by
+ funext k
+ exact installStacks_at Function.injective_id s st k
+ simpa only [labels, Option.elim_none, Option.elim_some, Function.comp_apply, hi] using
+ run.lift id Function.injective_id labels s hc
+
+end RAMTape.Routine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StructuredStackLoop.lean b/lean/OAI/Computability/VPVNP/StructuredStackLoop.lean
new file mode 100644
index 0000000000..c6bf2b5497
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StructuredStackLoop.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.StructuredStackLink
+
+/-!
+# Exact instruction costs of a structured stack loop
+
+An empty pop returns immediately. A nonempty pop spends one instruction before
+entering its body, whose normal return either finishes the loop or resumes at
+the next pop. The bodies may use any of the stacks, including the stack scanned.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Routine.Runs
+
+variable {K Q R : Type*} [DecidableEq K]
+variable (k : K) (repeatOn : Bool → Bool) (low : Routine K Q) (high : Routine K R)
+variable {s mid out : Stacks K} {tail : List Bool} {n m : ℕ}
+
+private def nextState (bit : Option Bool) : Option (Unit ⊕ (Q ⊕ R)) :=
+ match bit with
+ | none => none
+ | some false => some (.inr (.inl low.entry))
+ | some true => some (.inr (.inr high.entry))
+
+private theorem enter :
+ StackStep (popLoop k repeatOn low high).standalone
+ (some (popLoop k repeatOn low high).entry) s (nextState low high (s k).head?)
+ (Function.update s k (s k).tail) :=
+ StackStep.pop rfl
+
+/-- The terminating empty pop preserves the stacks. -/
+theorem popLoop_empty (hstack : s k = []) :
+ (popLoop k repeatOn low high).Runs 1 s s := by
+ have hs := enter k repeatOn low high (s := s)
+ rw [hstack] at hs
+ have hup : Function.update s k ([] : List Bool) = s := by
+ rw [← hstack]
+ exact Function.update_eq_self k s
+ change StackStep _ _ s none (Function.update s k []) at hs
+ rw [hup] at hs
+ exact .cons hs (.nil ..)
+
+private theorem popLoop_body {b : Bool} (hstack : s k = b :: tail)
+ (hbody : if b then high.Runs n (Function.update s k tail) mid
+ else low.Runs n (Function.update s k tail) mid) :
+ StackRuns (popLoop k repeatOn low high).standalone (n + 1)
+ (some (popLoop k repeatOn low high).entry) s
+ (if repeatOn b then some (popLoop k repeatOn low high).entry else none) mid := by
+ have hs := enter k repeatOn low high (s := s)
+ rw [hstack] at hs
+ cases b with
+ | false =>
+ have hb : low.Runs n (Function.update s k tail) mid := hbody
+ exact .cons hs (hb.link _ (Sum.inr ∘ Sum.inl) _ (fun _ => rfl))
+ | true =>
+ have hb : high.Runs n (Function.update s k tail) mid := hbody
+ exact .cons hs (hb.link _ (Sum.inr ∘ Sum.inr) _ (fun _ => rfl))
+
+/-- A continuing iteration costs one pop plus the body and the remaining loop. -/
+theorem popLoop_continue {b : Bool} (hstack : s k = b :: tail) (hrep : repeatOn b = true)
+ (hbody : if b then high.Runs n (Function.update s k tail) mid
+ else low.Runs n (Function.update s k tail) mid)
+ (hrest : (popLoop k repeatOn low high).Runs m mid out) :
+ (popLoop k repeatOn low high).Runs (1 + n + m) s out := by
+ have h := popLoop_body k repeatOn low high hstack hbody
+ rw [ite_eq_left hrep] at h
+ simpa only [Nat.add_comm n 1] using h.trans hrest
+
+/-- The final nonempty iteration costs one pop plus the body. -/
+theorem popLoop_stop {b : Bool} (hstack : s k = b :: tail) (hrep : repeatOn b = false)
+ (hbody : if b then high.Runs n (Function.update s k tail) out
+ else low.Runs n (Function.update s k tail) out) :
+ (popLoop k repeatOn low high).Runs (1 + n) s out := by
+ simpa only [hrep, Bool.false_eq_true, ite_false, Nat.add_comm n 1] using
+ popLoop_body k repeatOn low high hstack hbody
+
+theorem popLoop_false_continue (hstack : s k = false :: tail) (hrep : repeatOn false = true)
+ (hbody : low.Runs n (Function.update s k tail) mid)
+ (hrest : (popLoop k repeatOn low high).Runs m mid out) :
+ (popLoop k repeatOn low high).Runs (1 + n + m) s out :=
+ popLoop_continue k repeatOn low high hstack hrep hbody hrest
+
+theorem popLoop_true_continue (hstack : s k = true :: tail) (hrep : repeatOn true = true)
+ (hbody : high.Runs n (Function.update s k tail) mid)
+ (hrest : (popLoop k repeatOn low high).Runs m mid out) :
+ (popLoop k repeatOn low high).Runs (1 + n + m) s out :=
+ popLoop_continue k repeatOn low high hstack hrep hbody hrest
+
+theorem popLoop_false_stop (hstack : s k = false :: tail) (hrep : repeatOn false = false)
+ (hbody : low.Runs n (Function.update s k tail) out) :
+ (popLoop k repeatOn low high).Runs (1 + n) s out :=
+ popLoop_stop k repeatOn low high hstack hrep hbody
+
+theorem popLoop_true_stop (hstack : s k = true :: tail) (hrep : repeatOn true = false)
+ (hbody : high.Runs n (Function.update s k tail) out) :
+ (popLoop k repeatOn low high).Runs (1 + n) s out :=
+ popLoop_stop k repeatOn low high hstack hrep hbody
+
+end RAMTape.Routine.Runs
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StructuredStackRuns.lean b/lean/OAI/Computability/VPVNP/StructuredStackRuns.lean
new file mode 100644
index 0000000000..e3e0bf264f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StructuredStackRuns.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.StructuredStackLink
+
+/-!
+# Exact deterministic runs of stack routines
+
+Sequencing adds the costs of its components. A dispatch on the top symbol
+consumes one instruction in addition to the run of the selected branch.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Routine
+
+variable {K Q R M : Type*} [DecidableEq K]
+
+theorem Runs.followedBy {a : Routine K Q} {b : Routine K R} {n m : ℕ} {s u out : Stacks K}
+ (ha : a.Runs n s u) (hb : b.Runs m u out) : (a.followedBy b).Runs (n + m) s out :=
+ (ha.link (a.followedBy b) Sum.inl (some (.inr b.entry)) (fun _ => rfl)).trans
+ (hb.link (a.followedBy b) Sum.inr none (fun _ => rfl))
+
+theorem runs_ret (s : Stacks K) : (ret : Routine K Unit).Runs 1 s s :=
+ .cons (.goto rfl) (.nil ..)
+
+theorem runs_push (k : K) (b : Bool) (s : Stacks K) :
+ (push k b).Runs 1 s (Function.update s k (b :: s k)) :=
+ .cons (.push rfl) (.nil ..)
+
+variable (k : K) (missing : Routine K M) (low : Routine K Q) (high : Routine K R)
+ {s out : Stacks K} {t : ℕ}
+
+theorem runs_popCase_empty (hs : s k = []) (hm : missing.Runs t s out) :
+ (popCase k missing low high).Runs (t + 1) s out := by
+ let r := popCase k missing low high
+ have h := hm.link r (Sum.inr ∘ Sum.inl) none (fun _ => rfl)
+ have hup : Function.update s k [] = s := by rw [← hs, Function.update_eq_self]
+ have he : StackStep r.standalone (some r.entry) s (some (.inr (.inl missing.entry))) s := by
+ simpa only [hs, List.head?_nil, List.tail_nil, hup] using
+ (StackStep.pop (code := r.standalone) (s := s) (q := some r.entry)
+ (show r.standalone (some r.entry) = .pop k _ from rfl))
+ exact .cons he h
+
+theorem runs_popCase_false {tail : List Bool} (hs : s k = false :: tail)
+ (hl : low.Runs t (Function.update s k tail) out) :
+ (popCase k missing low high).Runs (t + 1) s out := by
+ let r := popCase k missing low high
+ have h := hl.link r (Sum.inr ∘ Sum.inr ∘ Sum.inl) none (fun _ => rfl)
+ have he : StackStep r.standalone (some r.entry) s (some (.inr (.inr (.inl low.entry))))
+ (Function.update s k tail) := by
+ simpa only [hs, List.head?_cons, List.tail_cons] using
+ (StackStep.pop (code := r.standalone) (s := s) (q := some r.entry)
+ (show r.standalone (some r.entry) = .pop k _ from rfl))
+ exact .cons he h
+
+theorem runs_popCase_true {tail : List Bool} (hs : s k = true :: tail)
+ (hh : high.Runs t (Function.update s k tail) out) :
+ (popCase k missing low high).Runs (t + 1) s out := by
+ let r := popCase k missing low high
+ have h := hh.link r (Sum.inr ∘ Sum.inr ∘ Sum.inr) none (fun _ => rfl)
+ have he : StackStep r.standalone (some r.entry) s (some (.inr (.inr (.inr high.entry))))
+ (Function.update s k tail) := by
+ simpa only [hs, List.head?_cons, List.tail_cons] using
+ (StackStep.pop (code := r.standalone) (s := s) (q := some r.entry)
+ (show r.standalone (some r.entry) = .pop k _ from rfl))
+ exact .cons he h
+
+end RAMTape.Routine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StructuredStackSafe.lean b/lean/OAI/Computability/VPVNP/StructuredStackSafe.lean
new file mode 100644
index 0000000000..de52a02f69
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StructuredStackSafe.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.StructuredStackTotal
+import OAI.Computability.VPVNP.RAMTapeSpace
+
+/-! # A space invariant on every branch of a returning stack routine
+
+The caller checks its own invariant at a normal return. At each active
+instruction the callee checks the current bank and both successors of a
+binary choice. This gives a simultaneous clock and peak-space contract.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Routine
+
+variable {K Q R : Type*} [DecidableEq K]
+
+/-- Every branch from the given local control checks the stack invariant at each active
+instruction and reaches a halt or a return within the fuel budget. At a return the
+continuation receives the remaining fuel and stack bank. -/
+def SafeFrom (r : Routine K Q) (safe : Stacks K → Prop) (cont : ℕ → Stacks K → Prop) :
+ ℕ → Option Q → Stacks K → Prop
+ | t, none, s => cont t s
+ | 0, some _, _ => False
+ | t+1, some q, s => safe s ∧
+ match r.code q with
+ | .push k b next => r.SafeFrom safe cont t next (Function.update s k (b :: s k))
+ | .pop k next => r.SafeFrom safe cont t (next (s k).head?) (Function.update s k (s k).tail)
+ | .goto next => r.SafeFrom safe cont t next s
+ | .choose a b => r.SafeFrom safe cont t a s ∧ r.SafeFrom safe cont t b s
+ | .halt _ => True
+
+/-- The all-branches stack invariant and fuel bound for a routine started at its entry label. -/
+abbrev Safe (r : Routine K Q) (safe : Stacks K → Prop) (cont : ℕ → Stacks K → Prop)
+ (t : ℕ) (s : Stacks K) := r.SafeFrom safe cont t (some r.entry) s
+
+@[simp] theorem safeFrom_none (r : Routine K Q) (safe : Stacks K → Prop)
+ (c : ℕ → Stacks K → Prop) (t : ℕ) (s : Stacks K) : r.SafeFrom safe c t none s ↔ c t s := by
+ cases t <;> rfl
+
+theorem safeFrom_install (outer : Routine K R) (inner : Routine K Q)
+ (label : Q → R) (resume : Option R) (h : ∀ q, outer.code (label q) = inner.install label resume q)
+ (safe : Stacks K → Prop) (c : ℕ → Stacks K → Prop) (t : ℕ) (q : Option Q) (s : Stacks K) :
+ outer.SafeFrom safe c t (q.elim resume (some ∘ label)) s ↔
+ inner.SafeFrom safe (fun n st => outer.SafeFrom safe c n resume st) t q s := by
+ induction t generalizing q s with
+ | zero => cases q <;> rfl
+ | succ t ih =>
+ cases q with
+ | none => rfl
+ | some q =>
+ simp only [Option.elim_some, Function.comp_apply, SafeFrom, h, install]
+ cases inner.code q <;> simp only [StackOp.rename, id_eq, Function.comp_apply, ih]
+
+theorem safe_followedBy (a : Routine K Q) (b : Routine K R) (safe : Stacks K → Prop)
+ (c : ℕ → Stacks K → Prop) (t : ℕ) (s : Stacks K) :
+ (a.followedBy b).Safe safe c t s ↔ a.Safe safe (b.Safe safe c) t s := by
+ have second (n : ℕ) (st : Stacks K) :
+ (a.followedBy b).SafeFrom safe c n (some (.inr b.entry)) st ↔ b.Safe safe c n st := by
+ simpa only [Option.elim_some, Function.comp_apply, safeFrom_none] using
+ safeFrom_install (a.followedBy b) b Sum.inr none (fun _ => rfl) safe c n (some b.entry) st
+ change (a.followedBy b).SafeFrom safe c t (some (.inl a.entry)) s ↔
+ a.SafeFrom safe (fun n st => b.Safe safe c n st) t (some a.entry) s
+ simpa only [Option.elim_some, Function.comp_apply, second] using
+ safeFrom_install (a.followedBy b) a Sum.inl (some (.inr b.entry)) (fun _ => rfl)
+ safe c t (some a.entry) s
+
+theorem SafeFrom.allStops {r : Routine K Q} {safe c d t q s}
+ (h : r.SafeFrom safe c t q s) (hd : ∀ n u, c n u → d n u) : r.AllStopsFrom d t q s := by
+ induction t generalizing q s with
+ | zero => cases q <;> simp_all [SafeFrom, AllStopsFrom]
+ | succ t ih =>
+ cases q with
+ | none => exact hd _ _ ((safeFrom_none ..).mp h)
+ | some q =>
+ simp only [SafeFrom] at h
+ simp only [AllStopsFrom]
+ cases he : r.code q <;> rw [he] at h <;> simp only at h ⊢
+ all_goals first | exact ih h.2 | exact ⟨ih h.2.1, ih h.2.2⟩
+
+theorem SafeFrom.stopsWithin {r : Routine K Q} {safe c t q s} (outcome : Bool)
+ (h : r.SafeFrom safe c t q s) (hc : ∀ n u, c n u → 0 < n) :
+ StopsWithin (r.close outcome) t q s :=
+ (stopsWithin_close_iff ..).mpr (h.allStops hc)
+
+/-- Every reachable bank satisfies the invariant, including a normal return
+when the caller's continuation enforces it there. -/
+theorem SafeFrom.reach {r : Routine K Q} {safe c t q s} (outcome : Bool)
+ (h : r.SafeFrom safe c t q s) (hc : ∀ n u, c n u → safe u) {v u}
+ (path : StackCompiler.Reach (r.close outcome) q s v u) : safe u := by
+ have certificate : ∃ n, r.SafeFrom safe c n v u := by
+ induction path with
+ | initial => exact ⟨t, h⟩
+ | @step a x b y _ hs ih =>
+ obtain ⟨n, hn⟩ := ih
+ cases a with
+ | none => cases hs <;> contradiction
+ | some a =>
+ cases n with
+ | zero => exact False.elim hn
+ | succ n =>
+ refine ⟨n, ?_⟩
+ cases hs with
+ | push he | pop he | goto he =>
+ change r.code a = _ at he
+ rw [SafeFrom, he] at hn
+ exact hn.2
+ | @low a x l b _ he ih | @high a x l b _ he ih =>
+ obtain ⟨n, hn⟩ := ih
+ cases a with
+ | none => contradiction
+ | some a =>
+ cases n with
+ | zero => exact False.elim hn
+ | succ n =>
+ change r.code a = _ at he
+ rw [SafeFrom, he] at hn
+ first | exact ⟨n, hn.2.1⟩ | exact ⟨n, hn.2.2⟩
+ obtain ⟨n, hn⟩ := certificate
+ cases v with
+ | none => exact hc n u ((safeFrom_none ..).mp hn)
+ | some v => cases n with
+ | zero => exact False.elim hn
+ | succ n => exact hn.1
+
+end RAMTape.Routine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StructuredStackTotal.lean b/lean/OAI/Computability/VPVNP/StructuredStackTotal.lean
new file mode 100644
index 0000000000..00ec0165e0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StructuredStackTotal.lean
@@ -0,0 +1,105 @@
+import OAI.Computability.VPVNP.StructuredStackClock
+
+/-!
+# Bounding all branches of a structured stack program
+
+The continuation receives the remaining fuel on each normal return. A direct
+halt always finishes, including a rejecting halt. A binary choice satisfies
+the bound exactly when both alternatives satisfy it.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Routine
+
+variable {K Q R : Type*} [DecidableEq K]
+
+/-- Every branch from the given local control halts or returns within the available fuel, with
+each normal return satisfying the continuation at its remaining fuel and final stack bank. -/
+def AllStopsFrom (r : Routine K Q) (cont : ℕ → Stacks K → Prop) :
+ ℕ → Option Q → Stacks K → Prop
+ | t, none, s => cont t s
+ | 0, some _, _ => False
+ | t+1, some q, s =>
+ match r.code q with
+ | .push k b next => r.AllStopsFrom cont t next (Function.update s k (b :: s k))
+ | .pop k next => r.AllStopsFrom cont t (next (s k).head?) (Function.update s k (s k).tail)
+ | .goto next => r.AllStopsFrom cont t next s
+ | .choose a b => r.AllStopsFrom cont t a s ∧ r.AllStopsFrom cont t b s
+ | .halt _ => True
+
+/-- The all-branches termination condition for a routine started at its entry label, with the
+continuation checked on each normal return. -/
+abbrev AllStops (r : Routine K Q) (cont : ℕ → Stacks K → Prop) (n : ℕ) (s : Stacks K) :=
+ r.AllStopsFrom cont n (some r.entry) s
+
+@[simp] theorem allStopsFrom_none (r : Routine K Q) (c : ℕ → Stacks K → Prop)
+ (t : ℕ) (s : Stacks K) : r.AllStopsFrom c t none s ↔ c t s := by cases t <;> rfl
+
+theorem stopsWithin_close_iff (r : Routine K Q) (outcome : Bool) (t : ℕ) (q : Option Q)
+ (s : Stacks K) :
+ StopsWithin (r.close outcome) t q s ↔ r.AllStopsFrom (fun n _ => 0 < n) t q s := by
+ induction t generalizing q s with
+ | zero => cases q <;> simp [StopsWithin, AllStopsFrom]
+ | succ t ih =>
+ cases q with
+ | none => simp [StopsWithin, AllStopsFrom, close]
+ | some q =>
+ simp only [StopsWithin, close, AllStopsFrom]
+ cases r.code q <;> simp only [ih]
+
+theorem allStopsFrom_install (outer : Routine K R) (inner : Routine K Q)
+ (label : Q → R) (resume : Option R) (h : ∀ q, outer.code (label q) = inner.install label resume q)
+ (c : ℕ → Stacks K → Prop) (t : ℕ) (q : Option Q) (s : Stacks K) :
+ outer.AllStopsFrom c t (q.elim resume (some ∘ label)) s ↔
+ inner.AllStopsFrom (fun n st => outer.AllStopsFrom c n resume st) t q s := by
+ induction t generalizing q s with
+ | zero => cases q <;> rfl
+ | succ t ih =>
+ cases q with
+ | none => rfl
+ | some q =>
+ simp only [Option.elim_some, Function.comp_apply, AllStopsFrom, h, install]
+ cases inner.code q <;> simp only [StackOp.rename, id_eq, Function.comp_apply, ih]
+
+theorem allStops_followedBy (a : Routine K Q) (b : Routine K R) (c : ℕ → Stacks K → Prop)
+ (t : ℕ) (s : Stacks K) :
+ (a.followedBy b).AllStops c t s ↔ a.AllStops (b.AllStops c) t s := by
+ have second (n : ℕ) (st : Stacks K) :
+ (a.followedBy b).AllStopsFrom c n (some (.inr b.entry)) st ↔ b.AllStops c n st := by
+ simpa only [Option.elim_some, Function.comp_apply, allStopsFrom_none] using
+ allStopsFrom_install (a.followedBy b) b Sum.inr none (fun _ => rfl) c n (some b.entry) st
+ change (a.followedBy b).AllStopsFrom c t (some (.inl a.entry)) s ↔
+ a.AllStopsFrom (fun n st => b.AllStops c n st) t (some a.entry) s
+ simpa only [Option.elim_some, Function.comp_apply, second] using
+ allStopsFrom_install (a.followedBy b) a Sum.inl (some (.inr b.entry)) (fun _ => rfl)
+ c t (some a.entry) s
+
+/-- A deterministic successful run spends exactly its stated cost and hands every
+remaining clock tick to the continuation. -/
+theorem Runs.allStops_iff {r : Routine K Q} {n : ℕ} {s out : Stacks K} (h : r.Runs n s out)
+ (cont : ℕ → Stacks K → Prop) (fuel : ℕ) :
+ r.AllStops cont (fuel+n) s ↔ cont fuel out := by
+ have aux {a : ℕ} {q q' : Option Q} {u v : Stacks K}
+ (run : StackRuns r.standalone a q u q' v) :
+ r.AllStopsFrom cont (fuel+a) q u ↔ r.AllStopsFrom cont fuel q' v := by
+ induction run with
+ | nil => rfl
+ | @cons q u _ _ _ _ a hs _ ih =>
+ cases q with
+ | none => cases hs <;> contradiction
+ | some q =>
+ cases hs with
+ | push he | pop he | goto he =>
+ change r.code q = _ at he
+ rw [show fuel + (a+1) = (fuel+a)+1 by omega, AllStopsFrom, he]
+ exact ih
+ simpa only [allStopsFrom_none] using aux h
+
+end RAMTape.Routine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/StructuredStacks.lean b/lean/OAI/Computability/VPVNP/StructuredStacks.lean
new file mode 100644
index 0000000000..8a364ec5e4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/StructuredStacks.lean
@@ -0,0 +1,245 @@
+import OAI.Computability.VPVNP.RAMTapeStackLift
+
+/-!
+# Structured finite-control programs for bit stacks
+
+The local validator in §10 performs nested scans, branches and calls. Each routine
+has one normal return and may also halt with acceptance or rejection. Linking a
+return to the next instruction introduces no extra machine step. All constructions
+on finite controls use only finite sums and individual new labels.
+
+The continuation semantics counts accepting paths with a fixed remaining step budget.
+It permits exact accounting through a call even when the callee makes binary choices.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape
+
+/-- A control label is local to this routine. `none` in an instruction's continuation
+returns to the caller, while a halt ends the entire execution. -/
+structure Routine (K Q : Type*) where
+ /-- The local control label at which an invocation of the routine begins. -/
+ entry : Q
+ /-- The stack instruction at each local control label, using an absent successor to return to
+ the caller. -/
+ code : Q → StackOp K (Option Q)
+
+namespace Routine
+
+variable {K Q R M : Type*}
+
+/-- Closed executable with an arbitrary halt outcome at the normal-return boundary. -/
+def close (r : Routine K Q) (outcome : Bool) : StackCode K (Option Q)
+ | none => .halt outcome
+ | some q => r.code q
+
+/-- Closes a routine as a stack program by installing a rejecting halt at its normal-return
+boundary. -/
+abbrev standalone (r : Routine K Q) := r.close false
+
+/-- A deterministic execution from the routine entry to normal return in exactly the indicated
+number of instructions, with the specified initial and final stack banks. -/
+abbrev Runs [DecidableEq K] (r : Routine K Q) (t : ℕ) (s out : Stacks K) :=
+ StackRuns r.standalone t (some r.entry) s none out
+
+/-- Install a routine's control into its caller, redirecting normal returns. -/
+def install (r : Routine K Q) (label : Q → R) (resume : Option R) (q : Q) :
+ StackOp K (Option R) :=
+ (r.code q).rename id (Option.elim · resume (some ∘ label))
+
+/-- Returns normally in one instruction, preserving the stack bank. -/
+def ret : Routine K Unit := ⟨(), fun _ => .goto none⟩
+
+/-- Pushes one bit onto the specified stack and returns normally. -/
+def push (k : K) (b : Bool) : Routine K Unit := ⟨(), fun _ => .push k b none⟩
+
+/-- Halts the whole execution with the specified acceptance bit. -/
+def halt (accept : Bool) : Routine K Unit := ⟨(), fun _ => .halt accept⟩
+
+/-- Run both routines, returning normally only when the second does. -/
+def followedBy (a : Routine K Q) (b : Routine K R) : Routine K (Q ⊕ R) :=
+ ⟨.inl a.entry, Sum.elim (a.install Sum.inl (some (.inr b.entry))) (b.install Sum.inr none)⟩
+
+/-- Two branch slots count separately, even for routines with identical effects. -/
+def choose (a : Routine K Q) (b : Routine K R) : Routine K (Unit ⊕ (Q ⊕ R)) where
+ entry := .inl ()
+ code
+ | .inl _ => .choose (some (.inr (.inl a.entry))) (some (.inr (.inr b.entry)))
+ | .inr (.inl q) => a.install (Sum.inr ∘ Sum.inl) none q
+ | .inr (.inr q) => b.install (Sum.inr ∘ Sum.inr) none q
+
+/-- Pop one bit, dispatching separately on an empty stack, zero, and one. -/
+def popCase (k : K) (missing : Routine K M) (low : Routine K Q) (high : Routine K R) :
+ Routine K (Unit ⊕ (M ⊕ (Q ⊕ R))) where
+ entry := .inl ()
+ code
+ | .inl _ => .pop k fun
+ | none => some (.inr (.inl missing.entry))
+ | some false => some (.inr (.inr (.inl low.entry)))
+ | some true => some (.inr (.inr (.inr high.entry)))
+ | .inr (.inl q) => missing.install (Sum.inr ∘ Sum.inl) none q
+ | .inr (.inr (.inl q)) => low.install (Sum.inr ∘ Sum.inr ∘ Sum.inl) none q
+ | .inr (.inr (.inr q)) => high.install (Sum.inr ∘ Sum.inr ∘ Sum.inr) none q
+
+/-- An empty stack ends the loop. On a present bit, first run the selected body.
+When it returns, `repeatOn` decides whether to continue or to finish the scan. -/
+def popLoop (k : K) (repeatOn : Bool → Bool) (low : Routine K Q) (high : Routine K R) :
+ Routine K (Unit ⊕ (Q ⊕ R)) where
+ entry := .inl ()
+ code
+ | .inl _ => .pop k fun
+ | none => none
+ | some false => some (.inr (.inl low.entry))
+ | some true => some (.inr (.inr high.entry))
+ | .inr (.inl q) => low.install (Sum.inr ∘ Sum.inl) (if repeatOn false then some (.inl ()) else none) q
+ | .inr (.inr q) => high.install (Sum.inr ∘ Sum.inr) (if repeatOn true then some (.inl ()) else none) q
+
+variable [DecidableEq K]
+
+/-- At a normal return the continuation receives the exact remaining fuel and stacks. -/
+def countFrom (r : Routine K Q) (continuation : ℕ → Stacks K → ℕ) :
+ ℕ → Option Q → Stacks K → ℕ
+ | t, none, s => continuation t s
+ | 0, some _, _ => 0
+ | t + 1, some q, s =>
+ match r.code q with
+ | .push k b next => r.countFrom continuation t next (Function.update s k (b :: s k))
+ | .pop k next => r.countFrom continuation t (next (s k).head?) (Function.update s k (s k).tail)
+ | .goto next => r.countFrom continuation t next s
+ | .choose a b => r.countFrom continuation t a s + r.countFrom continuation t b s
+ | .halt accept => accept.toNat
+
+/-- Counts accepting branches from the routine entry within the fuel budget, using the
+continuation’s count at each normal return. -/
+abbrev count (r : Routine K Q) (continuation : ℕ → Stacks K → ℕ) (t : ℕ) (s : Stacks K) :=
+ r.countFrom continuation t (some r.entry) s
+
+/-- A fixed closed machine realizes the continuation semantics for either return outcome. -/
+theorem stackPaths_close (r : Routine K Q) (b : Bool) (t : ℕ) (q : Option Q) (s : Stacks K) :
+ stackPaths (r.close b) t q s = r.countFrom (fun n _ => if n = 0 then 0 else b.toNat) t q s := by
+ induction t generalizing q s with
+ | zero => cases q <;> rfl
+ | succ t ih =>
+ cases q with
+ | none => rfl
+ | some q =>
+ simp only [stackPaths, close, countFrom]
+ cases r.code q <;> simp only [ih]
+
+/-- An installed control counts precisely the same paths as its original routine,
+then resumes with the residual budget. -/
+theorem countFrom_install (outer : Routine K R) (inner : Routine K Q)
+ (label : Q → R) (resume : Option R)
+ (h : ∀ q, outer.code (label q) = inner.install label resume q)
+ (continuation : ℕ → Stacks K → ℕ) (t : ℕ) (q : Option Q) (s : Stacks K) :
+ outer.countFrom continuation t (q.elim resume (some ∘ label)) s =
+ inner.countFrom (fun n st => outer.countFrom continuation n resume st) t q s := by
+ induction t generalizing q s with
+ | zero => cases q <;> rfl
+ | succ t ih =>
+ cases q with
+ | none => rfl
+ | some q =>
+ simp only [Option.elim_some, Function.comp_apply, countFrom, h, install]
+ cases inner.code q <;> simp only [StackOp.rename, Function.comp_apply, id_eq, ih]
+
+@[simp] theorem countFrom_none (r : Routine K Q) (c : ℕ → Stacks K → ℕ) (t : ℕ) (s : Stacks K) :
+ r.countFrom c t none s = c t s := by cases t <;> rfl
+
+/-- Sequencing spends no instruction on transferring control from one routine to the next. -/
+theorem count_followedBy (a : Routine K Q) (b : Routine K R)
+ (c : ℕ → Stacks K → ℕ) (t : ℕ) (s : Stacks K) :
+ (a.followedBy b).count c t s = a.count (b.count c) t s := by
+ have second (n : ℕ) (st : Stacks K) :
+ (a.followedBy b).countFrom c n (some (.inr b.entry)) st = b.count c n st := by
+ simpa only [Option.elim_some, Function.comp_apply, countFrom_none] using
+ countFrom_install (a.followedBy b) b Sum.inr none (fun _ => rfl) c n (some b.entry) st
+ change (a.followedBy b).countFrom c t (some (.inl a.entry)) s =
+ a.countFrom (fun n st => b.count c n st) t (some a.entry) s
+ simpa only [Option.elim_some, Function.comp_apply, second] using
+ countFrom_install (a.followedBy b) a Sum.inl (some (.inr b.entry)) (fun _ => rfl)
+ c t (some a.entry) s
+
+private theorem installed_normal (outer : Routine K R) (inner : Routine K Q)
+ (label : Q → R) (h : ∀ q, outer.code (label q) = inner.install label none q)
+ (c : ℕ → Stacks K → ℕ) (n : ℕ) (s : Stacks K) :
+ outer.countFrom c n (some (label inner.entry)) s = inner.count c n s := by
+ simpa only [Option.elim_some, Function.comp_apply, countFrom_none] using
+ countFrom_install outer inner label none h c n (some inner.entry) s
+
+/-- A binary nondeterministic instruction contributes both of its branch counts. -/
+theorem count_choose (a : Routine K Q) (b : Routine K R)
+ (c : ℕ → Stacks K → ℕ) (t : ℕ) (s : Stacks K) :
+ (choose a b).count c (t + 1) s = a.count c t s + b.count c t s := by
+ change (choose a b).countFrom c t (some (.inr (.inl a.entry))) s +
+ (choose a b).countFrom c t (some (.inr (.inr b.entry))) s = _
+ exact congrArg₂ (· + ·)
+ (installed_normal (choose a b) a (Sum.inr ∘ Sum.inl) (fun _ => rfl) c t s)
+ (installed_normal (choose a b) b (Sum.inr ∘ Sum.inr) (fun _ => rfl) c t s)
+
+/-- A case instruction consumes exactly one machine step and removes the head when present. -/
+theorem count_popCase (k : K) (missing : Routine K M) (low : Routine K Q) (high : Routine K R)
+ (c : ℕ → Stacks K → ℕ) (t : ℕ) (s : Stacks K) :
+ (popCase k missing low high).count c (t + 1) s =
+ let st := Function.update s k (s k).tail
+ match (s k).head? with
+ | none => missing.count c t st
+ | some false => low.count c t st
+ | some true => high.count c t st := by
+ let outer := popCase k missing low high
+ unfold count
+ rw [countFrom]
+ cases hb : (s k).head? with
+ | none =>
+ simpa only [outer, popCase, hb, Function.comp_apply, count] using installed_normal outer missing (Sum.inr ∘ Sum.inl)
+ (fun _ => rfl) c t (Function.update s k (s k).tail)
+ | some b =>
+ cases b
+ · simpa only [outer, popCase, hb, Function.comp_apply, count] using installed_normal outer low (Sum.inr ∘ Sum.inr ∘ Sum.inl)
+ (fun _ => rfl) c t (Function.update s k (s k).tail)
+ · simpa only [outer, popCase, hb, Function.comp_apply, count] using installed_normal outer high (Sum.inr ∘ Sum.inr ∘ Sum.inr)
+ (fun _ => rfl) c t (Function.update s k (s k).tail)
+
+/-- One test of the loop selects the body and links its normal return either to the next test
+or to the caller. The body may make any number of binary choices before returning. -/
+theorem count_popLoop (k : K) (repeatOn : Bool → Bool) (low : Routine K Q) (high : Routine K R)
+ (c : ℕ → Stacks K → ℕ) (t : ℕ) (s : Stacks K) :
+ (popLoop k repeatOn low high).count c (t + 1) s =
+ let st := Function.update s k (s k).tail
+ let resume (b : Bool) := if repeatOn b then (popLoop k repeatOn low high).count c else c
+ match (s k).head? with
+ | none => c t st
+ | some false => low.count (resume false) t st
+ | some true => high.count (resume true) t st := by
+ let outer := popLoop k repeatOn low high
+ have branch (b : Bool) :
+ (fun n st => outer.countFrom c n (if repeatOn b then some (.inl ()) else none) st) =
+ (if repeatOn b then outer.count c else c) := by
+ cases repeatOn b <;> simp only [Bool.false_eq_true, ite_false, ite_true, countFrom_none]
+ rfl
+ unfold count
+ rw [countFrom]
+ cases hb : (s k).head? with
+ | none => simp only [popLoop, hb, countFrom_none]
+ | some b =>
+ cases b
+ · have h := countFrom_install outer low (Sum.inr ∘ Sum.inl)
+ (if repeatOn false then some (.inl ()) else none) (fun _ => rfl)
+ c t (some low.entry) (Function.update s k (s k).tail)
+ rw [branch] at h
+ simpa only [outer, popLoop, hb, Option.elim_some, Function.comp_apply, count] using h
+ · have h := countFrom_install outer high (Sum.inr ∘ Sum.inr)
+ (if repeatOn true then some (.inl ()) else none) (fun _ => rfl)
+ c t (some high.entry) (Function.update s k (s k).tail)
+ rw [branch] at h
+ simpa only [outer, popLoop, hb, Option.elim_some, Function.comp_apply, count] using h
+
+end Routine
+end RAMTape
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SubpartyEmbedding.lean b/lean/OAI/Computability/VPVNP/SubpartyEmbedding.lean
new file mode 100644
index 0000000000..5328233e3d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SubpartyEmbedding.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.WireSpectrum
+
+/-!
+# Trivial legs outside a subset of parties
+
+Section 2.2 of *VP and VNP differ over every field* restricts a spectral
+point to a smaller party set, with a one-dimensional leg at every remaining
+party. The embedding preserves products and restrictions. The embedded
+direct sum is a restriction of the full-party direct sum.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v w
+
+namespace WireTensor
+
+variable {k : Type u} {I : Type v} {O : Type w}
+
+/-- Extend a tensor to the disjoint union of its parties with a new set, giving each new party
+a one-dimensional leg. -/
+def trivialExtension (O : Type w) (T : Tensor.{u, v, 0} k I) :
+ Tensor.{u, max v w, 0} k (I ⊕ O) where
+ Basis
+ | .inl i => T.Basis i
+ | .inr _ => PUnit
+ finiteBasis
+ | .inl _ => inferInstance
+ | .inr _ => inferInstance
+ coeff x := T.coeff (fun i ↦ x (.inl i))
+
+private def extendTuple (T : Tensor.{u, v, 0} k I) (x : ∀ i, T.Basis i) :
+ (j : I ⊕ O) → (trivialExtension O T).Basis j
+ | .inl i => x i
+ | .inr _ => .unit
+
+private def tupleEquiv (T : Tensor.{u, v, 0} k I) :
+ ((j : I ⊕ O) → (trivialExtension O T).Basis j) ≃ ((i : I) → T.Basis i) where
+ toFun x i := x (.inl i)
+ invFun := extendTuple T
+ left_inv x := by
+ funext j
+ cases j with
+ | inl i => rfl
+ | inr o => exact Subsingleton.elim (α := PUnit) _ _
+ right_inv _ := rfl
+
+variable [Fintype I] [Fintype O] [Field k]
+
+/-- Local maps supported on the old parties act on the original tensor. -/
+private theorem applyLocal_trivialExtension (T : Tensor.{u, v, 0} k I) {C : I ⊕ O → Type}
+ (L : ∀ j, C j → (trivialExtension O T).Basis j → k)
+ (hout : ∀ (o : O) c b, L (.inr o) c b = 1) (c : ∀ j, C j) :
+ applyLocal L (trivialExtension O T).coeff c =
+ applyLocal (fun i ↦ L (.inl i)) T.coeff (fun i ↦ c (.inl i)) := by
+ classical
+ let : DecidableEq (I ⊕ O) := Classical.decEq _
+ unfold applyLocal
+ apply Fintype.sum_equiv (tupleEquiv T)
+ intro x
+ rw [Fintype.prod_sum_type]
+ simp [hout, tupleEquiv, trivialExtension]
+ rfl
+
+/-- Local restrictions extend to the larger set of parties. -/
+theorem trivialExtension_restricts {T U : Tensor.{u, v, 0} k I} (h : Restricts T U) :
+ Restricts (trivialExtension O T) (trivialExtension O U) := by
+ obtain ⟨L, hL⟩ := h
+ let K : ∀ j, (trivialExtension O U).Basis j → (trivialExtension O T).Basis j → k :=
+ fun j ↦ match j with
+ | .inl i => L i
+ | .inr _ => fun _ _ ↦ 1
+ refine ⟨K, ?_⟩
+ funext c
+ exact (applyLocal_trivialExtension T K (fun _ _ _ ↦ rfl) c).trans (congrFun hL _)
+
+/-- Extension commutes with the tensor product after identifying singleton factors. -/
+theorem trivialExtension_product (T U : Tensor.{u, v, 0} k I) :
+ Restricts (trivialExtension O (tensorProduct T U))
+ (tensorProduct (trivialExtension O T) (trivialExtension O U)) ∧
+ Restricts (tensorProduct (trivialExtension O T) (trivialExtension O U))
+ (trivialExtension O (tensorProduct T U)) := by
+ apply restricts_of_reindex (fun j ↦ match j with
+ | .inl _ => Equiv.refl _
+ | .inr _ => Equiv.prodPUnit PUnit)
+ intro c
+ rfl
+
+theorem trivialExtension_unit :
+ Restricts (trivialExtension O (unit (k := k) (J := I))) (unit.{u, max v w, 0}) ∧
+ Restricts (unit.{u, max v w, 0}) (trivialExtension O (unit (k := k) (J := I))) := by
+ apply restricts_of_reindex (fun j ↦ match j with
+ | .inl _ => Equiv.refl _
+ | .inr _ => Equiv.refl _)
+ intro c
+ rfl
+
+/-- Merging the two singleton blocks at each outside party produces the
+embedded direct sum on the old parties. -/
+theorem trivialExtension_directSum (T U : Tensor.{u, v, 0} k I) :
+ Restricts (directSum (trivialExtension O T) (trivialExtension O U))
+ (trivialExtension O (directSum T U)) := by
+ classical
+ let L : ∀ j, (trivialExtension O (directSum T U)).Basis j →
+ ((trivialExtension O T).Basis j ⊕ (trivialExtension O U).Basis j) → k :=
+ fun j ↦ match j with
+ | .inl _ => fun c b ↦ if c = b then 1 else 0
+ | .inr _ => fun _ _ ↦ 1
+ refine ⟨L, ?_⟩
+ refine (applyLocal_directSum (trivialExtension O T) (trivialExtension O U) L).trans ?_
+ funext c
+ rw [Pi.add_apply, applyLocal_trivialExtension T _ (fun _ _ _ ↦ rfl),
+ applyLocal_trivialExtension U _ (fun _ _ _ ↦ rfl)]
+ simp only [L, trivialExtension, directSum, Pi.add_apply]
+ congr 1 <;> congr 2 <;> funext i c b <;> split_ifs with hb <;> simp [hb]
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SubpartyNormalization.lean b/lean/OAI/Computability/VPVNP/SubpartyNormalization.lean
new file mode 100644
index 0000000000..a557b799f3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SubpartyNormalization.lean
@@ -0,0 +1,162 @@
+import OAI.Computability.VPVNP.SubpartyEmbedding
+import OAI.Computability.VPVNP.Normalization
+import OAI.Computability.VPVNP.TensorRestrictionSemiring
+
+/-!
+# Normalizing a spectral point on fewer parties
+
+Lemma 2.3 of *VP and VNP differ over every field* embeds tensors on the used
+parties by trivial legs outside them. Raising the old values to the reciprocal
+of the embedded diagonal exponent makes their direct sums additive and thus
+defines a spectral point on the smaller set.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v w
+
+open scoped NNReal
+
+namespace WireTensor.SpectralPoint
+
+open RestrictionClass
+
+variable {k : Type u} {I : Type v} {O : Type w} [Field k] [Fintype I] [Nonempty I]
+ [Fintype O] (F : SpectralPoint k (I ⊕ O))
+
+/-- The old value on trivial extensions descends to the restriction classes
+on the smaller party set. -/
+noncomputable def embeddedValue : RestrictionClass k I →*₀ ℝ where
+ toFun := Quotient.lift (fun T ↦ (F.value (trivialExtension O T) : ℝ))
+ (fun _ _ h ↦ congrArg (fun x : ℝ≥0 ↦ (x : ℝ)) <| F.value_eq_of_mutual
+ ⟨trivialExtension_restricts h.1, trivialExtension_restricts h.2⟩)
+ map_one' := by
+ change (F.value (trivialExtension O unit) : ℝ) = 1
+ rw [F.value_eq_of_mutual trivialExtension_unit, F.value_unit, NNReal.coe_one]
+ map_zero' := by
+ change (F.value (trivialExtension O (diagonal (Fin 0))) : ℝ) = 0
+ rw [F.value_zero, NNReal.coe_zero]
+ funext c
+ simp [trivialExtension, diagonal]
+ map_mul' a b := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective a
+ obtain ⟨U, rfl⟩ := ofTensor_surjective b
+ change (F.value (trivialExtension O (tensorProduct T U)) : ℝ) =
+ (F.value (trivialExtension O T) : ℝ) * (F.value (trivialExtension O U) : ℝ)
+ rw [F.value_eq_of_mutual (trivialExtension_product T U), F.value_tensorProduct, NNReal.coe_mul]
+
+@[simp] theorem embeddedValue_ofTensor (T : Tensor.{u, v, 0} k I) :
+ F.embeddedValue (ofTensor T) = F.value (trivialExtension O T) := rfl
+
+private theorem embeddedValue_nonneg (x : RestrictionClass k I) : 0 ≤ F.embeddedValue x := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ exact (F.value _).coe_nonneg
+
+private theorem embeddedValue_summand (x y : RestrictionClass k I) :
+ F.embeddedValue x ≤ F.embeddedValue (x + y) := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ obtain ⟨U, rfl⟩ := ofTensor_surjective y
+ exact F.monotone (trivialExtension_restricts (directSum_restricts_left T U))
+
+private theorem embeddedValue_add_le (x y : RestrictionClass k I) :
+ F.embeddedValue (x + y) ≤ F.embeddedValue x + F.embeddedValue y := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective x
+ obtain ⟨U, rfl⟩ := ofTensor_surjective y
+ exact_mod_cast (F.monotone (trivialExtension_directSum T U)).trans_eq (F.value_directSum _ _)
+
+/-- Base-two logarithm of the value of the embedded two-dimensional diagonal. -/
+noncomputable def subpartyExponent : ℝ := Real.log (F.embeddedValue 2) / Real.log 2
+
+/-- The power law for local diagonal tensors on the used parties. -/
+theorem embeddedValue_natCast {q : ℕ} (hq : 0 < q) :
+ F.embeddedValue q = (q : ℝ) ^ F.subpartyExponent := by
+ let g := F.embeddedValue.toMonoidHom.comp (Nat.castRingHom (RestrictionClass k I)).toMonoidHom
+ have hg : Monotone g := by
+ intro a b hab
+ obtain ⟨c, rfl⟩ := Nat.exists_eq_add_of_le hab
+ change F.embeddedValue a ≤ F.embeddedValue (↑(a+c))
+ simpa only [Nat.cast_add] using F.embeddedValue_summand a c
+ exact monotone_dimension_power_law g hg hq
+
+/-- The smaller-party spectral point, with the local diagonal normalized to
+dimension. Its evaluations include every tensor supported on the used parties. -/
+noncomputable def subpartyNormalization (hpos : 0 < F.subpartyExponent) : SpectralPoint k I where
+ value T := F.value (trivialExtension O T) ^ F.subpartyExponent⁻¹
+ monotone h :=
+ NNReal.rpow_le_rpow (F.monotone (trivialExtension_restricts h)) (inv_nonneg.mpr hpos.le)
+ value_unit := by rw [F.value_eq_of_mutual trivialExtension_unit, F.value_unit, NNReal.one_rpow]
+ value_zero T hT := by
+ rw [F.value_zero, NNReal.zero_rpow (inv_pos.mpr hpos).ne']
+ funext c
+ exact congrFun hT _
+ value_tensorProduct T U := by
+ rw [F.value_eq_of_mutual (trivialExtension_product T U), F.value_tensorProduct, NNReal.mul_rpow]
+ value_directSum T U := by
+ apply NNReal.eq
+ simp only [NNReal.coe_rpow, NNReal.coe_add]
+ apply Spectral.normalized_multiplicative_value_add F.embeddedValue F.embeddedValue_nonneg
+ F.embeddedValue_summand F.embeddedValue_add_le hpos _ (ofTensor T) (ofTensor U)
+ intro n
+ rcases Nat.eq_zero_or_pos n with rfl | hn
+ · simp [Real.zero_rpow hpos.ne']
+ · exact F.embeddedValue_natCast hn
+
+@[simp] theorem subpartyNormalization_value (hpos : 0 < F.subpartyExponent)
+ (T : Tensor.{u, v, 0} k I) :
+ (F.subpartyNormalization hpos).value T =
+ F.value (trivialExtension O T) ^ F.subpartyExponent⁻¹ := rfl
+
+omit [Nonempty I] in
+/-- Keeping an old wire and adding trivial legs agrees with the same wire
+between the included endpoints. -/
+private theorem trivialExtension_wire (a b : I) (D : Type) [Fintype D] :
+ Restricts (trivialExtension O (wire (k := k) a b D)) (wire (.inl a) (.inl b) D) ∧
+ Restricts (wire (.inl a) (.inl b) D) (trivialExtension O (wire (k := k) a b D)) := by
+ let e (j : I ⊕ O) :
+ (wire (k := k) (Sum.inl a) (Sum.inl b) D).Basis j ≃
+ (trivialExtension O (wire (k := k) a b D)).Basis j :=
+ match j with
+ | .inl i =>
+ { toFun := fun x ↦ ⟨fun h ↦ x.1 (congrArg Sum.inl h), fun h ↦ x.2 (congrArg Sum.inl h)⟩
+ invFun := fun x ↦ ⟨fun h ↦ x.1 (Sum.inl.inj h), fun h ↦ x.2 (Sum.inl.inj h)⟩
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ | .inr o =>
+ { toFun := fun _ ↦ .unit
+ invFun := fun _ ↦ ⟨(fun h ↦ nomatch h), (fun h ↦ nomatch h)⟩
+ left_inv := fun x ↦ Prod.ext (funext fun h ↦ nomatch h) (funext fun h ↦ nomatch h)
+ right_inv := fun _ ↦ rfl }
+ apply restricts_of_reindex e
+ intro c
+ rfl
+
+/-- Each wire on the used parties is a restriction of their local diagonal. -/
+theorem wireDistance_le_subpartyExponent (a b : I) :
+ F.wireDistance (.inl a) (.inl b) ≤ F.subpartyExponent := by
+ have hval : F.wireDimension (.inl a) (.inl b) 2 ≤ F.embeddedValue 2 := by
+ change (F.value (wire (.inl a) (.inl b) (Fin 2)) : ℝ) ≤
+ F.value (trivialExtension O (diagonal (Fin 2)))
+ rw [← F.value_eq_of_mutual (trivialExtension_wire a b (Fin 2))]
+ exact F.monotone (trivialExtension_restricts (diagonal_restricts_wire a b (Fin 2)))
+ apply div_le_div_of_nonneg_right _ (Real.log_pos (by norm_num : 1 < (2 : ℝ))).le
+ exact Real.log_le_log (zero_lt_one.trans_le (F.one_le_wireDimension _ _ (by decide))) hval
+
+/-- All wire distances are scaled by the same positive reciprocal diagonal
+exponent upon passing to the smaller spectrum. -/
+theorem subpartyNormalization_wireDistance (hpos : 0 < F.subpartyExponent) (a b : I) :
+ (F.subpartyNormalization hpos).wireDistance a b =
+ F.wireDistance (.inl a) (.inl b) / F.subpartyExponent := by
+ change Real.log ((F.subpartyNormalization hpos).value (wire a b (Fin 2))) / Real.log 2 =
+ (Real.log (F.value (wire (.inl a) (.inl b) (Fin 2))) / Real.log 2) / F.subpartyExponent
+ rw [subpartyNormalization_value, F.value_eq_of_mutual (trivialExtension_wire a b (Fin 2)),
+ NNReal.coe_rpow, Real.log_rpow]
+ · ring
+ · exact zero_lt_one.trans_le (F.one_le_wireDimension _ _ (by decide : 0 < 2))
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SubspaceOrbits.lean b/lean/OAI/Computability/VPVNP/SubspaceOrbits.lean
new file mode 100644
index 0000000000..8883201b1c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SubspaceOrbits.lean
@@ -0,0 +1,133 @@
+import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas
+
+/-! # Ordered pairs of subspaces
+
+The dimensions of the two subspaces and their sum determine the orbit of an ordered pair
+under the general linear group. This identifies the orbits used for Grassmannian walks.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Grassmann
+
+open Module IsModularLattice
+
+variable {K V : Type*} [Field K] [AddCommGroup V] [Module K V]
+
+/-- Addition in a direct sum of two disjoint subspaces. -/
+private noncomputable def sumEquiv {A B S : Submodule K V} (h : Disjoint A B)
+ (hs : A ⊔ B = S) : (A × B) ≃ₗ[K] S :=
+ let f := A.subtype.coprod B.subtype
+ have hf : Function.Injective f := by
+ rw [← LinearMap.ker_eq_bot, LinearMap.ker_coprod_of_disjoint_range, Submodule.ker_subtype,
+ Submodule.ker_subtype, Submodule.prod_bot]
+ simpa using h
+ (LinearEquiv.ofInjective f hf).trans
+ (LinearEquiv.ofEq _ _ ((Submodule.sup_eq_range _ _).symm.trans hs))
+
+private theorem sumEquiv_coe {A B S : Submodule K V} (h : Disjoint A B) (hs : A ⊔ B = S)
+ (x : A × B) : (sumEquiv h hs x : V) = x.1 + x.2 := rfl
+
+/-- Glue two changes of coordinates on disjoint summands. -/
+private theorem glue {A B S A' B' S' : Submodule K V}
+ (hd : Disjoint A B) (hs : A ⊔ B = S) (hd' : Disjoint A' B') (hs' : A' ⊔ B' = S')
+ (f : A ≃ₗ[K] A') (g : B ≃ₗ[K] B') :
+ ∃ e : S ≃ₗ[K] S',
+ (∀ (x : A) (y : S), (y : V) = x → (e y : V) = f x) ∧
+ (∀ (x : B) (y : S), (y : V) = x → (e y : V) = g x) := by
+ let t := sumEquiv hd hs
+ let t' := sumEquiv hd' hs'
+ let e := t.symm ≪≫ₗ f.prodCongr g ≪≫ₗ t'
+ have he (x : A × B) : (e (t x) : V) = (f x.1 : V) + (g x.2 : V) := by
+ simp only [e, LinearEquiv.trans_apply, LinearEquiv.symm_apply_apply]
+ rfl
+ refine ⟨e, ?_, ?_⟩
+ · intro x y hy
+ have : y = t (x, 0) := Subtype.ext (by simpa [t, sumEquiv_coe] using hy)
+ rw [this, he]
+ simp
+ · intro x y hy
+ have : y = t (0, x) := Subtype.ext (by simpa [t, sumEquiv_coe] using hy)
+ rw [this, he]
+ simp
+
+private theorem complement_finrank {A B S : Submodule K V} [FiniteDimensional K V]
+ (h : Disjoint A B) (hs : A ⊔ B = S) : finrank K S = finrank K A + finrank K B := by
+ have hab := A.finrank_sup_add_finrank_inf_eq B
+ rw [hs, h.eq_bot, finrank_bot, Nat.add_zero] at hab
+ exact hab
+
+private theorem disjoint_from_first {A B C : Submodule K V}
+ (h : Disjoint (A ⊓ B) C) (hc : (A ⊓ B) ⊔ C = B) : Disjoint A C := by
+ have hCB : C ≤ B := hc ▸ le_sup_right
+ rw [disjoint_iff] at h ⊢
+ calc
+ A ⊓ C = (A ⊓ B) ⊓ C := by rw [inf_assoc, inf_eq_right.mpr hCB]
+ _ = ⊥ := h
+
+private theorem map_eq_of_agrees {A A' : Submodule K V} (e : V ≃ₗ[K] V)
+ (f : A ≃ₗ[K] A') (h : ∀ x : A, e (x : V) = (f x : V)) : A.map e.toLinearMap = A' := by
+ ext y
+ constructor
+ · rintro ⟨x, hx, rfl⟩
+ exact h ⟨x, hx⟩ ▸ (f ⟨x, hx⟩).property
+ · intro hy
+ obtain ⟨x, hx⟩ := f.surjective ⟨y, hy⟩
+ exact ⟨x, x.property, (h x).trans (congrArg Subtype.val hx)⟩
+
+/-- Two ordered pairs of subspaces are conjugate if the corresponding first subspaces,
+second subspaces, and sums have equal dimensions. -/
+theorem exists_pair_linearEquiv [FiniteDimensional K V] (A B A' B' : Submodule K V)
+ (hA : finrank K A = finrank K A') (hB : finrank K B = finrank K B')
+ (hS : finrank K (A ⊔ B : Submodule K V) = finrank K (A' ⊔ B' : Submodule K V)) :
+ ∃ e : V ≃ₗ[K] V, A.map e.toLinearMap = A' ∧ B.map e.toLinearMap = B' := by
+ let I := A ⊓ B
+ let I' := A' ⊓ B'
+ have hI : finrank K I = finrank K I' := by
+ have h := A.finrank_sup_add_finrank_inf_eq B
+ have h' := A'.finrank_sup_add_finrank_inf_eq B'
+ dsimp [I, I']
+ omega
+ obtain ⟨D, hd, hs⟩ := exists_disjoint_and_sup_eq (show I ≤ A from inf_le_left)
+ obtain ⟨D', hd', hs'⟩ := exists_disjoint_and_sup_eq (show I' ≤ A' from inf_le_left)
+ obtain ⟨C, hc, ht⟩ := exists_disjoint_and_sup_eq (show I ≤ B from inf_le_right)
+ obtain ⟨C', hc', ht'⟩ := exists_disjoint_and_sup_eq (show I' ≤ B' from inf_le_right)
+ have hD : finrank K D = finrank K D' := by
+ have := complement_finrank hd hs
+ have := complement_finrank hd' hs'
+ omega
+ have hC : finrank K C = finrank K C' := by
+ have := complement_finrank hc ht
+ have := complement_finrank hc' ht'
+ omega
+ let fi := LinearEquiv.ofFinrankEq I I' hI
+ let fc := LinearEquiv.ofFinrankEq C C' hC
+ obtain ⟨fa, ha, _⟩ := glue hd hs hd' hs' fi (LinearEquiv.ofFinrankEq D D' hD)
+ have hAC : A ⊔ C = A ⊔ B := by
+ calc A ⊔ C = (A ⊔ I) ⊔ C := by rw [sup_eq_left.mpr (show I ≤ A from inf_le_left)]
+ _ = A ⊔ B := by rw [sup_assoc, ht]
+ have hAC' : A' ⊔ C' = A' ⊔ B' := by
+ calc A' ⊔ C' = (A' ⊔ I') ⊔ C' := by rw [sup_eq_left.mpr (show I' ≤ A' from inf_le_left)]
+ _ = A' ⊔ B' := by rw [sup_assoc, ht']
+ obtain ⟨fs, hsa, hsc⟩ := glue (disjoint_from_first hc ht) hAC (disjoint_from_first hc' ht')
+ hAC' fa fc
+ obtain ⟨e, he⟩ := Submodule.exists_linearEquiv_restrict_eq fs
+ have hea (x : A) : e (x : V) = (fa x : V) := by
+ let y : (A ⊔ B : Submodule K V) := ⟨x, (show A ≤ A ⊔ B from le_sup_left) x.property⟩
+ exact (he y).symm.trans (hsa x y rfl)
+ have hec (x : C) : e (x : V) = (fc x : V) := by
+ let y : (A ⊔ B : Submodule K V) := ⟨x, (show C ≤ A ⊔ B from hAC ▸ le_sup_right) x.property⟩
+ exact (he y).symm.trans (hsc x y rfl)
+ have hei (x : I) : e (x : V) = (fi x : V) := by
+ let y : A := ⟨x, x.property.1⟩
+ exact (hea y).trans (ha x y rfl)
+ refine ⟨e, map_eq_of_agrees e fa hea, ?_⟩
+ rw [← ht, Submodule.map_sup, map_eq_of_agrees e fi hei, map_eq_of_agrees e fc hec, ht']
+
+end Grassmann
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/SurvivingSlots.lean b/lean/OAI/Computability/VPVNP/SurvivingSlots.lean
new file mode 100644
index 0000000000..db8d6e5fa0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/SurvivingSlots.lean
@@ -0,0 +1,148 @@
+import OAI.Computability.VPVNP.SlotOtherEnd
+import OAI.Computability.VPVNP.SlotSeparation
+import Mathlib.Algebra.BigOperators.Ring.Finset
+
+/-!
+# Incidences of the surviving slots in a shrinking step
+
+Section 7.2 of *VP and VNP differ over every field* splits each surviving
+supply edge of type `t` into the same number of slots at every motif.
+Each of the packed roles A, B, D occurs equally often at every site.
+Counting by type gives the same incoming and outgoing degree at every site.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression.SurvivingSlots
+
+/-- The three packed positions of one motif, with D denoting the placed D*. -/
+inductive PackedRole where
+ | a | b | d
+ deriving DecidableEq
+
+/-- Apply one of the three role maps of the chosen layout to a motif. -/
+def roleMap {M V : Type*} (A B D : M → V) : PackedRole → M → V
+ | .a => A
+ | .b => B
+ | .d => D
+
+/-- Orient the surviving wires in the order of their party names. Layout
+`false` retains BC, BN, CN, DM and layout `true` retains AC, AM, CM, DN. -/
+def sourceRole (layout : Bool) : Fin 4 → PackedRole
+ | 0 | 1 => if layout then .a else .b
+ | 2 => if layout then .b else .a
+ | 3 => .d
+
+/-- Destination roles after identifying ACM and DN in the first layout,
+or BCN and DM in the second layout. -/
+def targetRole (layout : Bool) : Fin 4 → PackedRole
+ | 0 | 3 => if layout then .b else .a
+ | 1 | 2 => .d
+
+theorem sourceRole_ne_targetRole (layout : Bool) (e : Fin 4) :
+ sourceRole layout e ≠ targetRole layout e :=
+ (by decide : ∀ l : Bool, ∀ t : Fin 4, sourceRole l t ≠ targetRole l t) layout e
+
+/-- The type, original CD arc (motif), and index of a parallel slot. -/
+abbrev Id (M : Type*) {T : Type*} (subdiv : T → ℕ) := Σ t, M × Fin (subdiv t)
+
+variable {R M V T : Type*}
+
+/-- The source or target of a surviving slot, determined by the role at
+that end of its supply type. -/
+def endpoint (role : R → M → V) (pick : T → R) {subdiv : T → ℕ} (i : Id M subdiv) : V :=
+ role (pick i.1) i.2.1
+
+/-- Counting the incidences at a vertex can be done separately for each type,
+then independently for the motif and the subdivision index. -/
+def endpointFiberEquiv (role : R → M → V) (pick : T → R) (subdiv : T → ℕ) (v : V) :
+ {i : Id M subdiv // endpoint role pick i = v} ≃
+ Σ t, {m : M // role (pick t) m = v} × Fin (subdiv t) where
+ toFun i := ⟨i.1.1, ⟨i.1.2.1, i.2⟩, i.1.2.2⟩
+ invFun i := ⟨⟨i.1, i.2.1.1, i.2.2⟩, i.2.1.2⟩
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+/-- The uniform degree formula applies to either orientation. Here `r` is
+the common number of occurrences of each role at any site. -/
+theorem card_endpoint [Fintype M] [Fintype T] [DecidableEq V]
+ (role : R → M → V) (pick : T → R) (subdiv : T → ℕ) {r : ℕ}
+ (hrole : ∀ k v, Fintype.card {m : M // role k m = v} = r) (v : V) :
+ Fintype.card {i : Id M subdiv // endpoint role pick i = v} = r * ∑ t, subdiv t := by
+ rw [Fintype.card_congr (endpointFiberEquiv role pick subdiv v)]
+ simp [Fintype.card_prod, hrole, Finset.mul_sum]
+
+/-- Distinct roles give distinct endpoints, including after projection to the
+base when the three projected roles are pairwise distinct. -/
+theorem endpoint_ne (role : R → M → V) (src dst : T → R)
+ (hrole : ∀ m, Function.Injective (fun k ↦ role k m))
+ (hdiff : ∀ t, src t ≠ dst t) {subdiv : T → ℕ} (i : Id M subdiv) :
+ endpoint role src i ≠ endpoint role dst i :=
+ fun h ↦ hdiff i.1 (hrole i.2.1 h)
+
+/-- The three pairwise inequalities of Appendix C imply role injectivity. -/
+theorem injective_roleMap (A B D : M → V) (m : M)
+ (h : A m ≠ B m ∧ A m ≠ D m ∧ B m ≠ D m) :
+ Function.Injective (fun k ↦ roleMap A B D k m) := by
+ intro k l he
+ cases k <;> cases l <;> simp_all [roleMap, ne_comm]
+
+end Compression.SurvivingSlots
+
+namespace Compression.PackingData
+
+open SurvivingSlots
+
+variable {V H Tag L : Type*} {d c : ℕ}
+variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L]
+variable (P : PackingData V H Tag L d c)
+
+/-- The three role maps of the actual packed layout. -/
+def survivingRole (layout : Bool) : PackedRole → P.Motif → Site V Tag L :=
+ roleMap P.roleA P.roleB (P.roleD layout)
+
+/-- Each surviving slot has distinct packed bases for its source and target,
+including parallel slots of the same supply type. -/
+theorem survivingSlot_bases_ne [Module (ZMod 2) Tag]
+ (hφ : P.slots.ValidTagOffsets P.tagShift P.offset)
+ (layout : Bool) {subdiv : Fin 4 → ℕ} (i : Id P.Motif subdiv) :
+ packedBase (endpoint (P.survivingRole layout) (sourceRole layout) i) ≠
+ packedBase (endpoint (P.survivingRole layout) (targetRole layout) i) := by
+ apply endpoint_ne (fun k m ↦ packedBase (P.survivingRole layout k m)) _ _ _
+ (sourceRole_ne_targetRole layout)
+ intro m
+ have hm := injective_roleMap (packedBase ∘ P.roleA) (packedBase ∘ P.roleB)
+ (packedBase ∘ P.roleD layout) m (P.distinct_roleBases hφ layout m)
+ have hmap (k : PackedRole) :
+ packedBase (P.survivingRole layout k m) = roleMap (packedBase ∘ P.roleA)
+ (packedBase ∘ P.roleB) (packedBase ∘ P.roleD layout) k m := by
+ cases k <;> rfl
+ simpa only [hmap] using hm
+
+variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L]
+variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L]
+
+/-- Before filling the deficit, every packed position has exactly
+`d * Q * ∑ t, subdiv t` outgoing and incoming arcs in either layout. -/
+theorem survivingSlot_degree (hc : 2 ≤ c) (layout : Bool) (subdiv : Fin 4 → ℕ) (s : Site V Tag L) :
+ Fintype.card {i : Id P.Motif subdiv //
+ endpoint (P.survivingRole layout) (sourceRole layout) i = s} =
+ d * (3 * (2 ^ c * d) / 4) * ∑ t, subdiv t ∧
+ Fintype.card {i : Id P.Motif subdiv //
+ endpoint (P.survivingRole layout) (targetRole layout) i = s} =
+ d * (3 * (2 ^ c * d) / 4) * ∑ t, subdiv t := by
+ have hrole (k : PackedRole) (v : Site V Tag L) :
+ Fintype.card {m : P.Motif // P.survivingRole layout k m = v} = d * (3 * (2 ^ c * d) / 4) := by
+ cases k with
+ | a => exact P.card_roleA hc v
+ | b => exact P.card_roleB hc v
+ | d => exact P.card_roleD hc layout v
+ exact ⟨card_endpoint _ _ _ hrole s, card_endpoint _ _ _ hrole s⟩
+
+end Compression.PackingData
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TableCompiler.lean b/lean/OAI/Computability/VPVNP/TableCompiler.lean
new file mode 100644
index 0000000000..4a43d83480
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TableCompiler.lean
@@ -0,0 +1,147 @@
+import OAI.Computability.VPVNP.UniversalMachine
+import Mathlib.Data.Fintype.EquivFin
+
+/-!
+# Deterministic finite controls as literal transition tables
+
+A control reads the head of the first tape and either halts or moves that head.
+The compiled two-tape table preserves both tapes' symbols and the second head's
+position. The ordering of the running states puts the given start state first.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TableCompiler
+
+open UniversalMachine
+
+/-- A deterministic read-only control action that halts with an acceptance bit or enters
+another state with a specified motion of the first tape head. -/
+inductive Step (Q : Type*) where
+ | halt (accept : Bool)
+ | move (next : Q) (dir : Fin 3)
+
+variable {Q : Type*} [Fintype Q]
+
+private theorem card_pos (start : Q) : 0 < Fintype.card Q :=
+ Fintype.card_pos_iff.mpr ⟨start⟩
+
+private noncomputable def numbering (start : Q) : Q ≃ Fin (Fintype.card Q) :=
+ (Fintype.equivFin Q).trans (Equiv.swap (Fintype.equivFin Q start) ⟨0, card_pos start⟩)
+
+private theorem numbering_start (start : Q) : (numbering start start).val = 0 := by
+ simp [numbering]
+
+private noncomputable def stateNumber (start q : Q) : Fin (Fintype.card Q + 2) :=
+ ⟨(numbering start q).val + 2, Nat.add_lt_add_right (numbering start q).isLt 2⟩
+
+private noncomputable def instruction (start : Q) (s : Step Q) (first second : Symbol) :
+ Instruction (Fintype.card Q) :=
+ match s with
+ | .halt accept => ⟨⟨if accept then 1 else 0, by split <;> omega⟩, first, 0, second, 0⟩
+ | .move next dir => ⟨stateNumber start next, first, dir, second, 0⟩
+
+private def rowState (i : Fin (Fintype.card Q * 9)) : Fin (Fintype.card Q) :=
+ ⟨i.val / 9, by omega⟩
+
+private def rowFirst {m : ℕ} (i : Fin (m * 9)) : Symbol := ⟨i.val % 9 / 3, by omega⟩
+private def rowSecond {m : ℕ} (i : Fin (m * 9)) : Symbol := ⟨i.val % 3, by omega⟩
+
+private noncomputable def row (start : Q) (f : Q → Symbol → Step Q)
+ (i : Fin (Fintype.card Q * 9)) : Branches (Fintype.card Q) :=
+ .one (instruction start (f ((numbering start).symm (rowState i)) (rowFirst i))
+ (rowFirst i) (rowSecond i))
+
+/-- The nine rows per running state, in the order used by the literal machine. -/
+noncomputable abbrev compile (start : Q) (f : Q → Symbol → Step Q) : Program :=
+ ⟨Fintype.card Q, List.ofFn (row start f), List.length_ofFn⟩
+
+/-- Running configuration corresponding to a finite control state. -/
+noncomputable def running (start q : Q) (tape work : Turing.Tape Symbol) : Config (Fintype.card Q) :=
+ ⟨stateNumber start q, tape, work⟩
+
+/-- Motion of the read-only head, with the literal codes stay, left, right. -/
+def moveTape (tape : Turing.Tape Symbol) (dir : Fin 3) : Turing.Tape Symbol :=
+ match dir.val with
+ | 0 => tape
+ | 1 => tape.move .left
+ | _ => tape.move .right
+
+theorem initial_eq_running (start : Q) (f : Q → Symbol → Step Q) (input : Word) :
+ initial (compile start f) input =
+ running start start (Turing.Tape.mk₁ (input.map fun b => if b then 2 else 1))
+ (Turing.Tape.mk₁ []) := by
+ unfold initial running
+ congr 1
+ apply Fin.ext
+ simp [compile, (card_pos start).ne', stateNumber, numbering_start]
+
+private theorem lookup (start : Q) (f : Q → Symbol → Step Q) (q : Q)
+ (tape work : Turing.Tape Symbol) :
+ branches (compile start f) (running start q tape work) =
+ .one (instruction start (f q tape.head) tape.head work.head) := by
+ let j := (numbering start q).val * 9 + tape.head.val * 3 + work.head.val
+ have hj : j < Fintype.card Q * 9 := by
+ have := (numbering start q).isLt
+ have := tape.head.isLt
+ have := work.head.isLt
+ dsimp [j]
+ omega
+ let i : Fin (Fintype.card Q * 9) := ⟨j, hj⟩
+ have hs : rowState i = numbering start q := by
+ apply Fin.ext
+ change j / 9 = _
+ have := tape.head.isLt
+ have := work.head.isLt
+ dsimp [j]
+ omega
+ have hfirst : rowFirst i = tape.head := by
+ apply Fin.ext
+ change j % 9 / 3 = _
+ have := tape.head.isLt
+ have := work.head.isLt
+ dsimp [j]
+ omega
+ have hsecond : rowSecond i = work.head := by
+ apply Fin.ext
+ change j % 3 = _
+ have := work.head.isLt
+ dsimp [j]
+ omega
+ have hrow : row start f i = .one (instruction start (f q tape.head) tape.head work.head) := by
+ simp [row, hs, hfirst, hsecond]
+ unfold branches compile running stateNumber
+ simp only [Nat.add_sub_cancel]
+ change (List.ofFn (row start f))[j]?.getD .stop = _
+ rw [List.getElem?_eq_getElem (by simpa using hj)]
+ simpa only [Option.getD_some, List.getElem_ofFn] using hrow
+
+theorem paths_running_succ (start : Q) (f : Q → Symbol → Step Q) (q : Q)
+ (tape work : Turing.Tape Symbol) (fuel : ℕ) :
+ paths (compile start f) (fuel + 1) (running start q tape work) =
+ match f q tape.head with
+ | .halt b => if b then 1 else 0
+ | .move next dir => paths (compile start f) fuel (running start next (moveTape tape dir) work) := by
+ have h1 : (running start q tape work).state.val ≠ 1 := by
+ change (numbering start q).val + 2 ≠ 1
+ omega
+ have h0 : (running start q tape work).state.val ≠ 0 := by
+ change (numbering start q).val + 2 ≠ 0
+ omega
+ rw [paths]
+ simp only [ite_eq_right h1, ite_eq_right h0, lookup]
+ cases f q tape.head with
+ | halt b =>
+ cases b
+ · exact paths_reject _ _ rfl _
+ · exact paths_accept _ _ rfl _
+ | move next dir =>
+ congr 1
+
+end TableCompiler
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TallyConstantRoutines.lean b/lean/OAI/Computability/VPVNP/TallyConstantRoutines.lean
new file mode 100644
index 0000000000..4f147b7f99
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TallyConstantRoutines.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.TallyStacks
+
+/-! # Fixed literal and clear instructions for unary parameters -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Tally
+
+variable {K : Type*} [DecidableEq K]
+
+/-- The finite control itself specifies the literal number of marks to append. -/
+def addConstant (k : K) (a : ℕ) : Routine K (Fin (a+1)) where
+ entry := Fin.last a
+ code i := if h : i.val = 0 then .goto none else
+ .push k true (some ⟨i.val - 1, by have := i.isLt; omega⟩)
+
+theorem addConstant_runs (k : K) (a : ℕ) (s : State K) :
+ (addConstant k a).Runs (a+1) (encode s) (encode (Function.update s k (s k+a))) := by
+ have aux (j : ℕ) (hj : j ≤ a) (u : State K) :
+ StackRuns (addConstant k a).standalone (j+1) (some ⟨j, by omega⟩) (encode u)
+ none (encode (Function.update u k (u k+j))) := by
+ induction j generalizing u with
+ | zero =>
+ simp only [Nat.add_zero, Function.update_eq_self]
+ exact .cons (.goto rfl) (.nil ..)
+ | succ j ih =>
+ let v := Function.update u k (u k+1)
+ have later := ih (by omega) v
+ have hstate : Function.update v k (v k+j) = Function.update u k (u k+(j+1)) := by
+ simp only [v, Function.update_self, Function.update_idem]
+ congr 1
+ omega
+ rw [hstate] at later
+ have step : StackStep (addConstant k a).standalone (some ⟨j+1, by omega⟩)
+ (encode u) (some ⟨j, by omega⟩) (encode v) := by
+ rw [show encode v = Function.update (encode u) k (true :: encode u k) from by
+ rw [← encode_update, List.replicate_succ]; rfl]
+ exact .push (by simp [Routine.standalone, Routine.close, addConstant])
+ exact .cons step later
+ exact aux a le_rfl s
+
+/-- Pop all marks, returning on the first empty pop. -/
+abbrev clear (k : K) := Routine.popLoop k (fun _ => true) (Routine.ret : Routine K Unit) Routine.ret
+
+theorem clear_runs (k : K) (s : State K) :
+ (clear k).Runs (2*s k+1) (encode s) (encode (Function.update s k 0)) := by
+ have h := drainRuns k Routine.ret (fun j => Function.update s k j) (fun _ => 1) (s k)
+ (fun _ _ => by simp) (fun i _ => by
+ simp only [Function.update_idem]
+ exact Routine.runs_ret _)
+ simpa [clear, Function.update_eq_self, Nat.mul_comm, Nat.add_comm] using h
+
+end RAMTape.Tally
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TallyConstants.lean b/lean/OAI/Computability/VPVNP/TallyConstants.lean
new file mode 100644
index 0000000000..0a4fbca3b5
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TallyConstants.lean
@@ -0,0 +1,38 @@
+import OAI.Computability.VPVNP.TallyPrograms
+import OAI.Computability.VPVNP.TallyConstantRoutines
+
+/-! # Constant writes and clearing for packaged tally programs -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Tally.Program
+
+variable {K : Type} [DecidableEq K]
+
+/-- Adds the fixed constant to one unary register in one push per mark followed by a return. -/
+@[simps eval work ready]
+def addConst (k : K) (a : ℕ) : Program K where
+ Q := Fin (a+1)
+ code := addConstant k a
+ eval s := Function.update s k (s k+a)
+ work _ := a+1
+ ready _ := True
+ spec s _ := addConstant_runs k a s
+
+/-- Empties one unary register in twice its initial value plus one stack instructions. -/
+@[simps eval work ready]
+def clear (k : K) : Program K where
+ Q := _
+ code := Tally.clear k
+ eval s := Function.update s k 0
+ work s := 2*s k+1
+ ready _ := True
+ spec s _ := clear_runs k s
+
+end RAMTape.Tally.Program
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TallyPrograms.lean b/lean/OAI/Computability/VPVNP/TallyPrograms.lean
new file mode 100644
index 0000000000..7602b839bb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TallyPrograms.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.RAMTapeInputParametersMultiply
+import OAI.Computability.VPVNP.RAMTapeInputParametersTriangle
+import Mathlib.Data.Fintype.Sum
+
+/-!
+# Composing the fixed tally programs for the input widths
+
+A program packages its finite control, tally update, exact instruction count and scratch
+precondition. Sequential composition checks the second precondition on the first output and
+counts both runs. The transition code consists of the previously verified stack routines.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Tally
+
+/-- A finite-control routine on unary registers together with its register update, exact
+instruction count, and a proof that it realizes both on ready inputs. -/
+structure Program (K : Type) [DecidableEq K] where
+ /-- The finite type of local control labels of the tally routine. -/
+ Q : Type
+ [finite : Fintype Q]
+ /-- The executable stack routine implementing the tally register update. -/
+ code : Routine K Q
+ /-- The final natural-number register state specified for each initial tally state. -/
+ eval : State K → State K
+ /-- The exact number of stack instructions used by the tally routine on a ready input. -/
+ work : State K → ℕ
+ /-- The precondition on the initial tally registers under which the specified update and
+ instruction count hold. -/
+ ready : State K → Prop
+ spec : ∀ s, ready s → code.Runs (work s) (encode s) (encode (eval s))
+
+attribute [instance] Program.finite
+
+namespace Program
+
+variable {K : Type} [DecidableEq K]
+
+/-- Link the two finite controls at the normal-return boundary. -/
+@[simps eval work ready]
+def seq (a b : Program K) : Program K where
+ Q := a.Q ⊕ b.Q
+ code := a.code.followedBy b.code
+ eval s := b.eval (a.eval s)
+ work s := a.work s + b.work (a.eval s)
+ ready s := a.ready s ∧ b.ready (a.eval s)
+ spec s h := (a.spec s h.1).followedBy (b.spec _ h.2)
+
+/-- Add a preserved source to the destination. -/
+@[simps eval work ready]
+def copy (src dst tmp : K) (hsd : src ≠ dst) (hst : src ≠ tmp) (hdt : dst ≠ tmp) : Program K where
+ Q := _
+ code := copyAdd src dst tmp
+ eval s := Function.update s dst (s dst + s src)
+ work s := 5 * s src + 2
+ ready s := s tmp = 0
+ spec s := copyAdd_runs src dst tmp hsd hst hdt s
+
+/-- Add the product of the two preserved sources to the destination. -/
+@[simps eval work ready]
+def mul (lhs rhs dst outer tmp : K) (hd : [lhs, rhs, dst, outer, tmp].Nodup) : Program K where
+ Q := _
+ code := mulAdd lhs rhs dst outer tmp
+ eval s := Function.update s dst (s dst + s lhs * s rhs)
+ work s := s lhs * (5 * s rhs + 6) + 2
+ ready s := s outer = 0 ∧ s tmp = 0
+ spec s h := mulAdd_runs lhs rhs dst outer tmp hd s h.1 h.2
+
+/-- Add the triangular number `1 + … + s src` to the destination. -/
+@[simps eval work ready]
+def triangle (src dst outer tmp : K) (hsc : src ≠ outer) (hst : src ≠ tmp)
+ (hdc : dst ≠ outer) (hdt : dst ≠ tmp) (hct : outer ≠ tmp) : Program K where
+ Q := _
+ code := triangleAdd src dst outer tmp
+ eval s := Function.update s dst (s dst + (s src + 1).choose 2)
+ work s := 3 + 9 * s src + 5 * (s src).choose 2
+ ready s := s outer = 0 ∧ s tmp = 0
+ spec s h := triangleAdd_runs src dst outer tmp hsc hst hdc hdt hct s h.1 h.2
+
+end Program
+end RAMTape.Tally
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TallyStacks.lean b/lean/OAI/Computability/VPVNP/TallyStacks.lean
new file mode 100644
index 0000000000..ec6b838fb7
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TallyStacks.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.StructuredStackRuns
+import OAI.Computability.VPVNP.StructuredStackLoop
+import Mathlib.Algebra.BigOperators.Group.Finset.Basic
+
+/-! # Unary registers in a fixed bit-stack program
+
+The validator's input offsets are natural numbers. A stack of true marks stores
+such a number without placing it in the control. The routines below transfer
+or add registers with an exact stack-instruction cost.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace RAMTape.Tally
+
+/-- A natural-number value for each tally register. -/
+abbrev State (K : Type*) := K → ℕ
+
+variable {K Q : Type*} [DecidableEq K]
+
+/-- Represents each unary register by a stack containing one true bit per unit of its value. -/
+def encode (s : State K) : Stacks K := fun k => List.replicate (s k) true
+
+theorem encode_update (s : State K) (k : K) (v : ℕ) :
+ Function.update (encode s) k (List.replicate v true) = encode (Function.update s k v) := by
+ funext j
+ by_cases hj : j = k <;> simp [encode, hj]
+
+theorem increment (s : State K) (k : K) :
+ (Routine.push k true).Runs 1 (encode s) (encode (Function.update s k (s k + 1))) := by
+ rw [← encode_update, List.replicate_succ]
+ exact Routine.runs_push k true _
+
+/-- Loop from a unary count `n` to zero. A body runs once per mark, with its
+actual cost and state allowed to vary between iterations. -/
+theorem drainRuns (src : K) (body : Routine K Q) (states : ℕ → State K) (cost : ℕ → ℕ)
+ (n : ℕ) (hs : ∀ i ≤ n, states i src = i)
+ (hb : ∀ i < n, body.Runs (cost i) (encode (Function.update (states (i + 1)) src i))
+ (encode (states i))) :
+ (Routine.popLoop src (fun _ => true) body body).Runs
+ (1 + ∑ i ∈ Finset.range n, (1 + cost i)) (encode (states n)) (encode (states 0)) := by
+ induction n with
+ | zero =>
+ simp only [Finset.range_zero, Finset.sum_empty, Nat.add_zero]
+ exact Routine.Runs.popLoop_empty src (fun _ => true) body body (by simp [encode, hs])
+ | succ n ih =>
+ have rest := ih (fun i hi => hs i (by omega)) (fun i hi => hb i (by omega))
+ have head : encode (states (n+1)) src = true :: List.replicate n true := by
+ simp [encode, hs (n+1) le_rfl, List.replicate_succ]
+ have one := hb n (Nat.lt_succ_self n)
+ rw [← encode_update] at one
+ simpa only [Finset.sum_range_succ, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using
+ Routine.Runs.popLoop_true_continue src (fun _ => true) body body head rfl one rest
+
+/-- Transfers marks from a source stack to a distinct destination until the source is empty,
+adding its tally to the destination. -/
+abbrev move (src dst : K) :=
+ Routine.popLoop src (fun _ => true) (Routine.push dst true) (Routine.push dst true)
+
+theorem move_runs (src dst : K) (hne : src ≠ dst) (s : State K) :
+ (move src dst).Runs (2 * s src + 1) (encode s)
+ (encode (Function.update (Function.update s src 0) dst (s dst + s src))) := by
+ let f (j : ℕ) := Function.update (Function.update s src j) dst (s dst + (s src - j))
+ have h := drainRuns src (Routine.push dst true) f (fun _ => 1) (s src)
+ (fun i _ => by simp [f, Function.update_of_ne hne]) (by
+ intro i hi
+ have hi' : s src - (i+1) + 1 = s src-i := by omega
+ have hstate : Function.update (Function.update (f (i+1)) src i) dst
+ (Function.update (f (i+1)) src i dst + 1) = f i := by
+ ext a
+ by_cases he : a = dst
+ · subst a
+ simp [f, Function.update_of_ne hne.symm, ← hi', Nat.add_assoc]
+ · by_cases ha : a = src <;> simp [f, ha, he, hne]
+ rw [← hstate]
+ exact increment _ _)
+ have hf : f (s src) = s := by simp [f, Function.update_eq_self]
+ simpa [move, hf, f, Nat.mul_comm, Nat.add_comm] using h
+
+private abbrev scatter (src a b : K) :=
+ let body := (Routine.push a true).followedBy (Routine.push b true)
+ Routine.popLoop src (fun _ => true) body body
+
+private theorem scatter_runs (src a b : K) (hsa : src ≠ a) (hsb : src ≠ b) (hab : a ≠ b)
+ (s : State K) : (scatter src a b).Runs (3*s src+1) (encode s)
+ (encode (Function.update (Function.update (Function.update s src 0) a (s a+s src)) b (s b+s src))) := by
+ let f (j : ℕ) := Function.update (Function.update (Function.update s src j)
+ a (s a + (s src - j))) b (s b + (s src - j))
+ let body := (Routine.push a true).followedBy (Routine.push b true)
+ have h := drainRuns src body f (fun _ => 2) (s src)
+ (fun i _ => by simp [f, hsa, hsb]) (by
+ intro i hi
+ let pre := Function.update (f (i+1)) src i
+ let mid := Function.update pre a (pre a + 1)
+ have step := (increment pre a).followedBy (increment mid b)
+ have hstate : Function.update mid b (mid b + 1) = f i := by
+ have hi' : s src - (i+1) + 1 = s src - i := by omega
+ ext z
+ by_cases hz : z = b
+ · subst z
+ simp [f, mid, pre, hab.symm, hsb.symm, ← hi', Nat.add_assoc]
+ · by_cases ha : z = a
+ · subst z
+ simp [f, mid, pre, hz, hsa.symm, ← hi', Nat.add_assoc]
+ · by_cases hs : z = src <;> simp [f, mid, pre, hz, ha, hs, hsa, hsb]
+ rw [← hstate]
+ exact step)
+ have hf : f (s src) = s := by simp [f, Function.update_eq_self]
+ simpa [scatter, body, hf, f, Nat.mul_comm, Nat.add_comm] using h
+
+/-- Preserve the source while adding its contents to the destination. -/
+abbrev copyAdd (src dst tmp : K) := (move src tmp).followedBy (scatter tmp src dst)
+
+theorem copyAdd_runs (src dst tmp : K) (hsd : src ≠ dst) (hst : src ≠ tmp) (hdt : dst ≠ tmp)
+ (s : State K) (ht : s tmp = 0) : (copyAdd src dst tmp).Runs (5*s src+2)
+ (encode s) (encode (Function.update s dst (s dst+s src))) := by
+ let m := Function.update (Function.update s src 0) tmp (s tmp + s src)
+ have first := move_runs src tmp hst s
+ have second := scatter_runs tmp src dst hst.symm hdt.symm hsd m
+ have hfinal : Function.update (Function.update (Function.update m tmp 0) src (m src+m tmp)) dst
+ (m dst+m tmp) = Function.update s dst (s dst+s src) := by
+ ext a
+ by_cases ha : a = dst
+ · subst a
+ simp [m, ht, hdt, hsd.symm]
+ · by_cases h₁ : a = src
+ · subst a
+ simp [m, ht, ha, hst]
+ · by_cases h₂ : a = tmp <;> simp [m, ht, ha, h₁, h₂, hst.symm, hdt.symm]
+ rw [hfinal] at second
+ have hcost : 2*s src+1 + (3*m tmp+1) = 5*s src+2 := by simp [m, ht]; omega
+ rw [← hcost]
+ exact first.followedBy second
+
+end RAMTape.Tally
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TangentRatio.lean b/lean/OAI/Computability/VPVNP/TangentRatio.lean
new file mode 100644
index 0000000000..6651b67e85
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TangentRatio.lean
@@ -0,0 +1,61 @@
+import OAI.Computability.VPVNP.SpectralTangentRay
+import Mathlib.Topology.Order.Monotone
+
+/-! # The radial slope and its equality case
+
+The proof of Lemma 4.1 of *VP and VNP differ over every field* compares
+the endpoint distance with the right limit of the equal-parameter ratios.
+Equality forces the original segments to have the same equal-parameter
+distances as their tangent rays.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open Set Filter
+open scoped Topology
+
+variable {X : Type*} [MetricSpace X] {o x y : X}
+
+theorem radialSlope_nonneg (a : RadialSegment o x) (b : RadialSegment o y) : 0 ≤ radialSlope a b := by
+ refine le_csInf ((nonempty_Ioc.mpr (zero_lt_one : (0 : ℝ) < 1)).image _) ?_
+ rintro _ ⟨t, ht, rfl⟩
+ exact div_nonneg dist_nonneg ht.1.le
+
+/-- The radial ratios converge from the right at zero to their infimum. -/
+theorem radialRatio_tendsto (hT : FractionTransport X)
+ (a : RadialSegment o x) (b : RadialSegment o y) :
+ Tendsto (fun t ↦ dist (a.path t) (b.path t) / t) (𝓝[>] (0 : ℝ)) (𝓝 (radialSlope a b)) := by
+ refine tendsto_order.mpr ⟨fun l hl => ?_, fun u hu => ?_⟩
+ · filter_upwards [Ioo_mem_nhdsGT (zero_lt_one : (0 : ℝ) < 1)] with t ht
+ exact hl.trans_le (radialSlope_le_ratio a b ⟨ht.1, ht.2.le⟩)
+ · obtain ⟨_, ⟨t, ht, rfl⟩, htu⟩ := exists_lt_of_csInf_lt
+ ((nonempty_Ioc.mpr (zero_lt_one : (0 : ℝ) < 1)).image _) hu
+ filter_upwards [Ioo_mem_nhdsGT ht.1] with s hs
+ exact (radial_ratio_mono hT a b ⟨hs.1, hs.2.le.trans ht.2⟩ ht hs.2.le).trans_lt htu
+
+/-- The distance between endpoints attains the radial slope exactly when the
+equal-parameter distance between the two original segments grows linearly. -/
+theorem radialSlope_eq_endpoint (hT : FractionTransport X)
+ (a : RadialSegment o x) (b : RadialSegment o y) :
+ radialSlope a b = dist x y ↔
+ ∀ t ∈ Icc (0 : ℝ) 1, dist (a.path t) (b.path t) = radialSlope a b * t := by
+ constructor
+ · intro heq t ht
+ rcases eq_or_lt_of_le ht.1 with rfl | hpos
+ · simp [a.start, b.start]
+ · apply (div_eq_iff hpos.ne').mp
+ apply le_antisymm _ (radialSlope_le_ratio a b ⟨hpos, ht.2⟩)
+ have h := radial_ratio_mono hT a b ⟨hpos, ht.2⟩ (show (1 : ℝ) ∈ Ioc 0 1 from ⟨zero_lt_one, le_rfl⟩) ht.2
+ simpa [heq, a.finish, b.finish] using h
+ · intro heq
+ simpa [a.finish, b.finish] using (heq 1 ⟨zero_le_one, le_rfl⟩).symm
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorDistributivity.lean b/lean/OAI/Computability/VPVNP/TensorDistributivity.lean
new file mode 100644
index 0000000000..f24e4803db
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorDistributivity.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.WireTensor
+import Mathlib.Logic.Equiv.Sum
+
+/-!
+# Direct sums and products up to local restriction
+
+Relabeling local bases lets us permute and regroup direct summands, and distribute
+a tensor product over a direct sum. Pure coordinate blocks carry the entries of
+their summands and mixed blocks vanish.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+
+namespace WireTensor
+
+variable {k : Type u} {J : Type v}
+
+/-- An assignment to disjoint local bases lies in one block at every party, or uses both. -/
+theorem sum_assignment_cases {A : J → Type*} {B : J → Type*} (x : ∀ j, A j ⊕ B j) :
+ (∃ a : ∀ j, A j, x = fun j ↦ Sum.inl (a j)) ∨
+ (∃ b : ∀ j, B j, x = fun j ↦ Sum.inr (b j)) ∨
+ (∃ (i j : J) (a : A i) (b : B j), x i = Sum.inl a ∧ x j = Sum.inr b) := by
+ classical
+ by_cases hl : ∀ j, ∃ a, x j = Sum.inl a
+ · choose a ha using hl
+ exact Or.inl ⟨a, funext ha⟩
+ by_cases hr : ∀ j, ∃ b, x j = Sum.inr b
+ · choose b hb using hr
+ exact Or.inr (Or.inl ⟨b, funext hb⟩)
+ push Not at hl hr
+ obtain ⟨i, hi⟩ := hr
+ obtain ⟨j, hj⟩ := hl
+ cases hai : x i with
+ | inr b => exact (hi b hai).elim
+ | inl a =>
+ cases hbj : x j with
+ | inl b => exact (hj b hbj).elim
+ | inr b => exact Or.inr (Or.inr ⟨i, j, a, b, hai, hbj⟩)
+
+/-- Regrouping the three coordinate blocks at every party preserves the tensor. -/
+theorem directSum_assoc_mutual [Fintype J] [CommSemiring k] (T U V : Tensor k J) :
+ Restricts (directSum (directSum T U) V) (directSum T (directSum U V)) ∧
+ Restricts (directSum T (directSum U V)) (directSum (directSum T U) V) := by
+ classical
+ let e (j : J) := Equiv.sumAssoc (T.Basis j) (U.Basis j) (V.Basis j)
+ let M (j : J) (c b : T.Basis j ⊕ (U.Basis j ⊕ V.Basis j)) : k := if c = b then 1 else 0
+ let L (j : J) (c : T.Basis j ⊕ (U.Basis j ⊕ V.Basis j))
+ (b : (T.Basis j ⊕ U.Basis j) ⊕ V.Basis j) := M j c (e j b)
+ have h :
+ applyLocal L (directSum (directSum T U) V).coeff =
+ applyLocal M (directSum T (directSum U V)).coeff := by
+ erw [applyLocal_directSum (directSum T U) V L, applyLocal_directSum T (directSum U V) M,
+ applyLocal_directSum T U, applyLocal_directSum U V, add_assoc]
+ rfl
+ have hL : L = fun j c b ↦ if (e j).symm c = b then 1 else 0 := by
+ funext j c b
+ simp [L, M, Equiv.symm_apply_eq]
+ dsimp only [M] at h
+ erw [hL, applyLocal_pullback (fun j c ↦ (e j).symm c), applyLocal_id] at h
+ apply restricts_of_reindex (fun j ↦ (e j).symm)
+ exact fun c ↦ (congrFun h c).symm
+
+variable [CommSemiring k] [Fintype J] [Nonempty J]
+
+/-- Swapping the left and right local blocks interchanges the summands. -/
+theorem directSum_comm_mutual (T U : Tensor.{u,v,0} k J) :
+ Restricts (directSum T U) (directSum U T) ∧ Restricts (directSum U T) (directSum T U) := by
+ apply restricts_of_reindex (fun j ↦ Equiv.sumComm (U.Basis j) (T.Basis j))
+ intro x
+ rcases sum_assignment_cases x with ⟨a, rfl⟩ | ⟨b, rfl⟩ | ⟨i, j, a, b, hi, hj⟩
+ · exact (directSum_coeff_inl U T a).trans (directSum_coeff_inr T U a).symm
+ · exact (directSum_coeff_inr U T b).trans (directSum_coeff_inl T U b).symm
+ · rw [directSum_coeff_mixed U T x hi hj]
+ symm
+ apply directSum_coeff_mixed T U _ (a := j) (b := i) (i := b) (l := a)
+ · rw [hj]
+ rfl
+ · rw [hi]
+ rfl
+
+/-- Local distribution of product coordinates over a disjoint union gives
+mutual restrictions for the distributive law. -/
+theorem tensorProduct_directSum_mutual (T U V : Tensor.{u,v,0} k J) :
+ Restricts (tensorProduct T (directSum U V))
+ (directSum (tensorProduct T U) (tensorProduct T V)) ∧
+ Restricts (directSum (tensorProduct T U) (tensorProduct T V))
+ (tensorProduct T (directSum U V)) := by
+ let e (j : J) := (Equiv.prodSumDistrib (T.Basis j) (U.Basis j) (V.Basis j)).symm
+ apply restricts_of_reindex e
+ intro x
+ rcases sum_assignment_cases x with ⟨a, rfl⟩ | ⟨b, rfl⟩ | ⟨i, j, a, b, hi, hj⟩
+ · rw [directSum_coeff_inl]
+ change _ = T.coeff (fun j ↦ (a j).1) * (directSum U V).coeff (fun j ↦ Sum.inl (a j).2)
+ rw [directSum_coeff_inl]
+ rfl
+ · rw [directSum_coeff_inr]
+ change _ = T.coeff (fun j ↦ (b j).1) * (directSum U V).coeff (fun j ↦ Sum.inr (b j).2)
+ rw [directSum_coeff_inr]
+ rfl
+ · rw [directSum_coeff_mixed _ _ x hi hj]
+ change 0 = T.coeff _ * (directSum U V).coeff (fun l ↦ (e l (x l)).2)
+ have hl : (e i (x i)).2 = Sum.inl a.2 := by rw [hi]; rfl
+ have hr : (e j (x j)).2 = Sum.inr b.2 := by rw [hj]; rfl
+ rw [directSum_coeff_mixed U V _ hl hr, mul_zero]
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorExtensionMatching.lean b/lean/OAI/Computability/VPVNP/TensorExtensionMatching.lean
new file mode 100644
index 0000000000..d87cbd3ab4
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorExtensionMatching.lean
@@ -0,0 +1,95 @@
+import OAI.Computability.VPVNP.ContractionClass
+import OAI.Computability.VPVNP.GeneratorProducts
+import OAI.Computability.VPVNP.SpectralMatching
+
+/-!
+# Prescribing added tensor values while extending the entire old spectrum
+
+For the two cases of Theorem 2.4, the finite set of required generators
+consists of the added star or the two added wires. The generator family
+also contains every nonzero old restriction class. Multiplication folds
+the old factors into one class before the contraction estimates are used.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+open Filter Topology
+namespace WireTensor.SpectralPoint
+
+open RestrictionClass
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nonempty J]
+variable (F : SpectralPoint k J)
+
+/-- The contraction estimates for a finite family of added tensors imply
+that one spectral point matches their prescribed values and extends the
+original point on all old tensors. -/
+theorem exists_extension_matching_of_rank {E : Type*} [Fintype E] [Nonempty E]
+ (rank : RestrictionClass k (Option J) →+* ℕ) (hrank : Monotone rank)
+ (extra : E → RestrictionClass k (Option J)) (cost : E → ℝ)
+ (hExtra : ∀ i, extra i ≠ 0) (hcost : ∀ i, 0 < cost i)
+ (upper : ∀ (x : RestrictionClass k J) (n : E → ℕ),
+ F.contractionClassValue (embedOldClass x * ∏ i, extra i ^ n i) ≤
+ ofSpectralPoint F x * ∏ i, cost i ^ n i)
+ (balanced : ∀ (x : RestrictionClass k J) (e : ℕ), 0 < e →
+ Tendsto (fun m : ℕ ↦ F.contractionClassValue ((embedOldClass x * ∏ i, extra i ^ e) ^ m)
+ ^ (m : ℝ)⁻¹) atTop (𝓝 (ofSpectralPoint F x * ∏ i, cost i ^ e))) :
+ ∃ H : SpectralPoint k (Option J), (∀ T, H.value (embedOld T) = F.value T) ∧
+ ∀ i, ofSpectralPoint H (extra i) = cost i := by
+ classical
+ let : CharZero (RestrictionClass k (Option J)) := rank.charZero
+ let Old := {x : RestrictionClass k J // x ≠ 0}
+ let old : Old → RestrictionClass k J := Subtype.val
+ let emb := (embedOldClass (k := k) (J := J)).toMonoidHom
+ let eval := (ofSpectralPoint F).toMonoidHom
+ let G : Old ⊕ E → RestrictionClass k (Option J) := Sum.elim (emb ∘ old) extra
+ let target : Old ⊕ E → ℝ := Sum.elim (eval ∘ old) cost
+ let required : Finset (Old ⊕ E) := Finset.univ.image Sum.inr
+ have hG : ∀ i, G i ≠ 0 := by
+ rintro (i | i)
+ · change embedOldClass i.val ≠ 0
+ exact fun h ↦ i.property (embedOldClass_injective (h.trans (map_zero _).symm))
+ · exact hExtra i
+ have ht : ∀ i, 0 < target i := by
+ rintro (i | i)
+ · have h := ofSpectralPoint_monotone F (orderBounds.one_le i.property)
+ rw [map_one] at h
+ exact zero_lt_one.trans_le h
+ · exact hcost i
+ have hmonomial (d : (Old ⊕ E) →₀ ℕ) :
+ F.contractionClassValue (d.prod fun i n ↦ G i ^ n) ≤ d.prod fun i n ↦ target i ^ n := by
+ dsimp only [G, target]
+ rw [Spectral.fold_generatorMonomial emb old extra, Spectral.fold_generatorMonomial eval old cost]
+ exact upper (∏ j ∈ d.support.toLeft, old j ^ d (.inl j)) (fun i ↦ d (.inr i))
+ have hbalanced (s : Finset (Old ⊕ E)) (hs : required ⊆ s) (e : ℕ) (he : 0 < e) :
+ Tendsto (fun m : ℕ ↦ F.contractionClassValue ((∏ i : s, G i ^ e) ^ m) ^ (m : ℝ)⁻¹)
+ atTop (𝓝 (∏ i : s, target i ^ e)) := by
+ have hall (i : E) : Sum.inr i ∈ s := hs (Finset.mem_image_of_mem _ (Finset.mem_univ i))
+ have hGfold := (Finset.prod_coe_sort s (fun i ↦ G i ^ e)).trans
+ (Spectral.fold_generatorBalanced emb old extra s e hall)
+ have htargetfold := (Finset.prod_coe_sort s (fun i ↦ target i ^ e)).trans
+ (Spectral.fold_generatorBalanced eval old cost s e hall)
+ rw [hGfold, htargetfold]
+ exact balanced _ e he
+ obtain ⟨H, hH, hmatch⟩ := Spectral.exists_matching_spectral_point orderBounds rank hrank G hG
+ target ht required (Finset.univ_nonempty.image _) F.contractionClassValue
+ F.contractionClassValue_monotone F.contractionClassValue_nonneg (fun x y ↦ (map_add _ x y).le)
+ F.contractionClassValue_copies hmonomial hbalanced
+ refine ⟨toSpectralPoint H hH, ?_, fun i ↦ ?_⟩
+ · intro T
+ apply NNReal.coe_injective
+ change H (embedOldClass (ofTensor T)) = ofSpectralPoint F (ofTensor T)
+ by_cases hz : ofTensor T = 0
+ · rw [hz, map_zero, map_zero, map_zero]
+ · exact hmatch (.inl ⟨ofTensor T, hz⟩)
+ · obtain ⟨T, hT⟩ := ofTensor_surjective (extra i)
+ rw [← hT, ofSpectralPoint_ofTensor, coe_toSpectralPoint_value, hT]
+ exact hmatch (.inr i)
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorFlattening.lean b/lean/OAI/Computability/VPVNP/TensorFlattening.lean
new file mode 100644
index 0000000000..97dabf76a3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorFlattening.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.WireTensor
+import Mathlib.LinearAlgebra.Matrix.Rank
+import Mathlib.LinearAlgebra.Matrix.Kronecker
+
+/-!
+# Flattening across one tensor party
+
+The row of the matrix is the basis index at the distinguished party and
+the column consists of the basis indices at all other parties.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+variable {k J : Type*}
+
+/-- Column indices for the flattening at party `a`. -/
+abbrev OtherBasis (a : J) (B : J → Type*) := (j : {j : J // j ≠ a}) → B j
+
+/-- Combine one row index and one column index into a full tensor index. -/
+def joinBasis [DecidableEq J] (a : J) {B : J → Type*} (x : B a) (y : OtherBasis a B) :
+ (j : J) → B j := (Equiv.piSplitAt a B).symm (x, y)
+
+@[simp] theorem joinBasis_self [DecidableEq J] (a : J) {B : J → Type*}
+ (x : B a) (y : OtherBasis a B) : joinBasis a x y a = x := by
+ simp [joinBasis, Equiv.piSplitAt_symm_apply]
+
+@[simp] theorem joinBasis_other [DecidableEq J] (a : J) {B : J → Type*}
+ (x : B a) (y : OtherBasis a B) (j : {j : J // j ≠ a}) : joinBasis a x y j = y j := by
+ simp [joinBasis, Equiv.piSplitAt_symm_apply, j.property]
+
+/-- The matrix of a tensor across one party and its complement. -/
+def flattening [DecidableEq J] (a : J) (T : Tensor k J) :
+ Matrix (T.Basis a) (OtherBasis a T.Basis) k :=
+ .of fun x y => T.coeff (joinBasis a x y)
+
+section Rank
+
+variable [DecidableEq J] [Fintype J] [Field k]
+
+private theorem prod_separate (a : J) (f : J → k) :
+ ∏ j, f j = f a * ∏ j : {j : J // j ≠ a}, f j := by
+ rw [Fintype.prod_eq_mul_prod_compl a, Finset.prod_subtype _ (by simp : ∀ j, j ∈ ({a}ᶜ : Finset J) ↔ j ≠ a)]
+
+/-- Applying local maps multiplies the flattening on the left and the right.
+The right-hand matrix combines the local maps on the complementary parties. -/
+theorem flattening_rank_mono (a : J) {T U : Tensor k J} (h : Restricts T U) :
+ (flattening a U).rank ≤ (flattening a T).rank := by
+ obtain ⟨L, hL⟩ := h
+ let A : Matrix (U.Basis a) (T.Basis a) k := .of (L a)
+ let B : Matrix (OtherBasis a T.Basis) (OtherBasis a U.Basis) k :=
+ .of fun y z => ∏ j : {j : J // j ≠ a}, L j (z j) (y j)
+ have heq : flattening a U = A * (flattening a T * B) := by
+ ext x z
+ change U.coeff (joinBasis a x z) = _
+ rw [← hL]
+ let f (b : (j : J) → T.Basis j) :=
+ (∏ j, L j (joinBasis a x z j) (b j)) * T.coeff b
+ unfold applyLocal
+ convert_to! ∑ b, f b = _ using 2
+ · ext
+ simp
+ rw [← (Equiv.piSplitAt a T.Basis).symm.sum_comp f, Fintype.sum_prod_type]
+ simp only [Matrix.mul_apply, Finset.mul_sum]
+ apply Finset.sum_congr rfl
+ intro i _
+ apply Finset.sum_congr rfl
+ intro y _
+ change (∏ j, L j (joinBasis a x z j) (joinBasis a i y j)) *
+ T.coeff (joinBasis a i y) =
+ L a x i * (T.coeff (joinBasis a i y) * ∏ j : {j : J // j ≠ a}, L j (z j) (y j))
+ rw [prod_separate a]
+ simp [mul_left_comm, mul_comm]
+ rw [heq]
+ exact (Matrix.rank_mul_le_right _ _).trans (Matrix.rank_mul_le_left _ _)
+
+/-- Parallel tensor factors flatten to the Kronecker product after regrouping
+the two column index tuples. -/
+theorem flattening_product_rank (a : J) (T U : Tensor k J) :
+ (flattening a (tensorProduct T U)).rank =
+ (Matrix.kronecker (flattening a T) (flattening a U)).rank := by
+ let e := Equiv.arrowProdEquivProdArrow {j : J // j ≠ a}
+ (fun j => T.Basis j) (fun j => U.Basis j)
+ have heq : flattening a (tensorProduct T U) =
+ (Matrix.kronecker (flattening a T) (flattening a U)).submatrix (Equiv.refl _) e := by
+ ext x y
+ change T.coeff (fun j => (joinBasis a x y j).1) * U.coeff (fun j => (joinBasis a x y j).2) =
+ T.coeff (joinBasis a x.1 (fun j => (y j).1)) * U.coeff (joinBasis a x.2 (fun j => (y j).2))
+ congr 2 <;> funext j <;> by_cases hj : j = a
+ all_goals first | subst j; simp | simp [joinBasis, Equiv.piSplitAt_symm_apply, hj]
+ rw [heq]
+ exact Matrix.rank_submatrix _ _ _
+
+/-- A zero coefficient array has zero flattening rank. -/
+theorem flattening_zero_rank (a : J) (T : Tensor k J) (h : T.coeff = 0) :
+ (flattening a T).rank = 0 := by
+ have hz : flattening a T = 0 := by
+ ext
+ simp [flattening, h]
+ rw [hz, Matrix.rank_zero]
+
+/-- Flattening the simple unit gives a one-by-one matrix of rank one. -/
+theorem flattening_unit_rank (a : J) : (flattening a (unit (k := k) (J := J))).rank = 1 := by
+ let e := Equiv.equivPUnit (OtherBasis a (fun _ => PUnit))
+ let M := (1 : Matrix PUnit PUnit k)
+ have heq : flattening a (unit (k := k) (J := J)) = M.submatrix (Equiv.refl _) e := by
+ ext x y
+ change PUnit at x
+ change 1 = M x (e y)
+ simp [M]
+ rw [heq]
+ exact (Matrix.rank_submatrix M (Equiv.refl _) e).trans (by simp [M])
+
+end Rank
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorFlatteningPoint.lean b/lean/OAI/Computability/VPVNP/TensorFlatteningPoint.lean
new file mode 100644
index 0000000000..2fdca8a178
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorFlatteningPoint.lean
@@ -0,0 +1,65 @@
+import OAI.Computability.VPVNP.FlatteningKronecker
+import OAI.Computability.VPVNP.TensorFlatteningSum
+import OAI.Computability.VPVNP.TensorRestrictionSpectrum
+
+/-!
+# Flattening rank as a tensor spectral point
+
+For a party set with at least two elements, separating any one party
+from the rest gives an additive, multiplicative, restriction-monotone rank.
+Appendix A.1 uses this natural-valued homomorphism on restriction classes
+to exclude the negative order unit from the comparison cone.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open scoped Classical
+
+namespace WireTensor
+
+universe u v
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nontrivial J]
+
+/-- The matrix rank across a single-party cut, on mutual restriction classes. -/
+noncomputable def flatteningRankHom (a : J) : RestrictionClass k J →+* ℕ where
+ toFun := Quotient.lift (fun T => (flattening a T).rank)
+ (fun _ _ h => le_antisymm (flattening_rank_mono a h.2) (flattening_rank_mono a h.1))
+ map_zero' := by
+ change (flattening a (diagonal (k := k) (Fin 0))).rank = 0
+ apply flattening_zero_rank
+ funext x
+ exact (x a).elim0
+ map_one' := flattening_unit_rank a
+ map_add' x y := by
+ obtain ⟨T, rfl⟩ := RestrictionClass.ofTensor_surjective x
+ obtain ⟨U, rfl⟩ := RestrictionClass.ofTensor_surjective y
+ exact flattening_directSum_rank a T U
+ map_mul' x y := by
+ obtain ⟨T, rfl⟩ := RestrictionClass.ofTensor_surjective x
+ obtain ⟨U, rfl⟩ := RestrictionClass.ofTensor_surjective y
+ exact (flattening_product_rank a T U).trans (rank_kronecker _ _)
+
+@[simp] theorem flatteningRankHom_ofTensor (a : J) (T : Tensor.{u,v,0} k J) :
+ flatteningRankHom a (RestrictionClass.ofTensor T) = (flattening a T).rank := rfl
+
+theorem flatteningRankHom_monotone (a : J) : Monotone (flatteningRankHom (k := k) a) := by
+ intro x y h
+ obtain ⟨T, rfl⟩ := RestrictionClass.ofTensor_surjective x
+ obtain ⟨U, rfl⟩ := RestrictionClass.ofTensor_surjective y
+ exact flattening_rank_mono a ((RestrictionClass.ofTensor_le_iff T U).1 h)
+
+/-- The spectral point measuring the rank across the chosen cut. -/
+noncomputable def flatteningPoint (a : J) : SpectralPoint k J :=
+ RestrictionClass.toSpectralPoint ((Nat.castRingHom ℝ).comp (flatteningRankHom a))
+ (fun _ _ h => Nat.cast_le.mpr (flatteningRankHom_monotone a h))
+
+@[simp] theorem coe_flatteningPoint_value (a : J) (T : Tensor.{u,v,0} k J) :
+ ((flatteningPoint a).value T : ℝ) = (flattening a T).rank := rfl
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorFlatteningSum.lean b/lean/OAI/Computability/VPVNP/TensorFlatteningSum.lean
new file mode 100644
index 0000000000..ed17c987c2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorFlatteningSum.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.TensorFlattening
+import OAI.Computability.VPVNP.TensorDistributivity
+import OAI.Computability.VPVNP.FlatteningBlockRank
+
+/-!
+# Direct sums in one-party flattenings
+
+Across a nontrivial cut, the pure columns form the block diagonal matrix of
+the two summands. A column using both summands on the complementary parties
+vanishes, so the full flattening and the block matrix have the same column span.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+variable {k J : Type*} [Field k] [Fintype J] [DecidableEq J] [Nontrivial J]
+
+omit [Fintype J] [Nontrivial J] in
+private theorem joinBasis_map {B C : J → Type*} (f : ∀ j, B j → C j)
+ (a : J) (x : B a) (y : OtherBasis a B) :
+ joinBasis a (f a x) (fun j ↦ f j (y j)) = fun j ↦ f j (joinBasis a x y j) := by
+ funext j
+ by_cases hj : j = a
+ · subst j
+ simp
+ · exact (joinBasis_other a _ _ ⟨j, hj⟩).trans
+ (congrArg (f j) (joinBasis_other a x y ⟨j, hj⟩)).symm
+
+private theorem flattening_directSum_pureColumn (a : J) (T U : Tensor k J)
+ (y : OtherBasis a T.Basis ⊕ OtherBasis a U.Basis) :
+ (flattening a (directSum T U)).col
+ (y.elim (fun l j ↦ Sum.inl (l j)) (fun r j ↦ Sum.inr (r j))) =
+ (Matrix.fromBlocks (flattening a T) 0 0 (flattening a U)).col y := by
+ obtain ⟨b, hb⟩ := exists_ne a
+ funext x
+ rcases x with l | r <;> rcases y with l' | r'
+ · change (directSum T U).coeff (joinBasis a (.inl l) (fun j ↦ .inl (l' j))) = _
+ exact (congrArg (directSum T U).coeff (joinBasis_map (C := (directSum T U).Basis)
+ (fun _ ↦ Sum.inl) a l l')).trans (directSum_coeff_inl T U _)
+ · apply directSum_coeff_mixed T U _ (a := a) (b := b) (i := l) (l := r' ⟨b, hb⟩)
+ · exact joinBasis_self a _ _
+ · exact joinBasis_other a _ _ ⟨b, hb⟩
+ · apply directSum_coeff_mixed T U _ (a := b) (b := a) (i := l' ⟨b, hb⟩) (l := r)
+ · exact joinBasis_other a _ _ ⟨b, hb⟩
+ · exact joinBasis_self a _ _
+ · change (directSum T U).coeff (joinBasis a (.inr r) (fun j ↦ .inr (r' j))) = _
+ exact (congrArg (directSum T U).coeff (joinBasis_map (C := (directSum T U).Basis)
+ (fun _ ↦ Sum.inr) a r r')).trans (directSum_coeff_inr T U _)
+
+/-- Mixed columns are zero, so deleting them from the direct-sum flattening
+preserves its rank. -/
+theorem flattening_directSum_rank_block (a : J) (T U : Tensor k J) :
+ (flattening a (directSum T U)).rank =
+ (Matrix.fromBlocks (flattening a T) 0 0 (flattening a U)).rank := by
+ classical
+ rw [Matrix.rank_eq_finrank_span_cols, Matrix.rank_eq_finrank_span_cols]
+ apply congrArg (fun p : Submodule k ((T.Basis a ⊕ U.Basis a) → k) ↦ Module.finrank k p)
+ apply le_antisymm <;> apply Submodule.span_le.mpr <;> rintro _ ⟨y, rfl⟩
+ · rcases sum_assignment_cases (A := fun j : {j : J // j ≠ a} ↦ T.Basis j)
+ (B := fun j ↦ U.Basis j) y with ⟨l, rfl⟩ | ⟨r, rfl⟩ | ⟨i, j, l, r, hi, hj⟩
+ · exact Submodule.subset_span (R := k) (M := (T.Basis a ⊕ U.Basis a) → k)
+ ⟨.inl l, (flattening_directSum_pureColumn a T U (.inl l)).symm⟩
+ · exact Submodule.subset_span (R := k) (M := (T.Basis a ⊕ U.Basis a) → k)
+ ⟨.inr r, (flattening_directSum_pureColumn a T U (.inr r)).symm⟩
+ · have hz : (flattening a (directSum T U)).col y = 0 := by
+ funext x
+ apply directSum_coeff_mixed T U _ (a := i.1) (b := j.1) (i := l) (l := r)
+ · exact (joinBasis_other a x y i).trans hi
+ · exact (joinBasis_other a x y j).trans hj
+ rw [hz]
+ exact Submodule.zero_mem _
+ · exact Submodule.subset_span (R := k) (M := (directSum T U).Basis a → k)
+ ⟨_, flattening_directSum_pureColumn a T U y⟩
+
+/-- Flattening rank is additive under direct sum when there are at least two parties. -/
+theorem flattening_directSum_rank (a : J) (T U : Tensor k J) :
+ (flattening a (directSum T U)).rank = (flattening a T).rank + (flattening a U).rank :=
+ (flattening_directSum_rank_block a T U).trans (rank_fromBlocks_zero _ _)
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorPowerCNF.lean b/lean/OAI/Computability/VPVNP/TensorPowerCNF.lean
new file mode 100644
index 0000000000..b4f84bde92
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorPowerCNF.lean
@@ -0,0 +1,168 @@
+import OAI.Computability.VPVNP.MatchClauses
+import OAI.Computability.VPVNP.HardnessWeights
+
+/-! # Weighted literal encoding of a tensor power
+
+The input gives one sequence of binary digits per party. Word flags select
+one variable at each party and digit-tuple flags select one coefficient per
+copy of the tensor. The CNF has exactly one satisfying extension of each input.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TensorPowerCNF
+
+open HardnessCNF MvPolynomial
+open scoped Classical
+
+/-- A block of `b` bits selecting a local basis index in one tensor factor. -/
+abbrev Digit (b : ℕ) := Fin b → Bool
+/-- The `h` successive local index blocks selected by one party in the tensor power. -/
+abbrev Word (b h : ℕ) := Fin h → Digit b
+
+/-- The multilinear form of the tensor power, grouping copies at each party. -/
+noncomputable def form {J R : Type*} [Fintype J] [CommSemiring R] {b : ℕ}
+ (T : (J → Digit b) → R) (h : ℕ) : MvPolynomial (J × Word b h) R :=
+ ∑ x : J → Word b h, (∏ j, X (j, x j)) * ∏ t, C (T (fun j => x j t))
+
+private abbrev Coordinates (J : Type*) (b h : ℕ) :=
+ (J × (Fin h × Fin b)) ⊕ (J × Word b h) ⊕ (Fin h × (J → Digit b))
+
+/-- Number of bits including the two families of flags. -/
+noncomputable def width (J : Type*) [Fintype J] (b h : ℕ) :=
+ Fintype.card (Coordinates J b h)
+
+theorem width_eq (J : Type*) [Fintype J] (b h : ℕ) :
+ width J b h = Fintype.card J * (h * b) + Fintype.card J * (2 ^ b) ^ h +
+ h * (2 ^ b) ^ Fintype.card J := by
+ simp [width, Coordinates, Word, Digit, add_assoc]
+
+variable {J : Type*} [Fintype J] {b h : ℕ}
+
+private noncomputable abbrev index : Coordinates J b h ≃ Fin (width J b h) :=
+ Fintype.equivFin _
+
+private noncomputable def bit (j : J) (t : Fin h) (a : Fin b) : Fin (width J b h) :=
+ index (.inl (j, t, a))
+
+private noncomputable def wordFlag (j : J) (w : Word b h) : Fin (width J b h) :=
+ index (.inr (.inl (j, w)))
+
+private noncomputable def tupleFlag (t : Fin h) (u : J → Digit b) : Fin (width J b h) :=
+ index (.inr (.inr (t, u)))
+
+private noncomputable def wordClauses (p : J × Word b h) : CNF (width J b h) :=
+ matchClauses (wordFlag p.1 p.2) (fun z : Fin h × Fin b => bit p.1 z.1 z.2)
+ (fun z => p.2 z.1 z.2)
+
+private noncomputable def tupleClauses (p : Fin h × (J → Digit b)) : CNF (width J b h) :=
+ matchClauses (tupleFlag p.1 p.2) (fun z : J × Fin b => bit z.1 p.1 z.2)
+ (fun z => p.2 z.1 z.2)
+
+/-- All word and tuple match tests. -/
+noncomputable def formula (J : Type*) [Fintype J] (b h : ℕ) : CNF (width J b h) :=
+ meetCNF wordClauses ++ meetCNF tupleClauses
+
+theorem literalCount_formula (J : Type*) [Fintype J] (b h : ℕ) :
+ literalCount (formula J b h) = Fintype.card J * (2 ^ b) ^ h * (3 * (h * b) + 1) +
+ h * (2 ^ b) ^ Fintype.card J * (3 * (Fintype.card J * b) + 1) := by
+ have hcount {k : ℕ} (a c : CNF k) :
+ literalCount (a ++ c) = literalCount a + literalCount c := by simp [literalCount]
+ rw [formula, hcount, literalCount_meetCNF_const wordClauses (3 * (h*b) + 1),
+ literalCount_meetCNF_const tupleClauses (3 * (Fintype.card J * b) + 1)]
+ · simp [Word, Digit]
+ · intro i
+ simp [tupleClauses, literalCount_matchClauses]
+ · intro i
+ simp [wordClauses, literalCount_matchClauses]
+
+private noncomputable def bits (v : Fin (width J b h) → Bool) : J → Word b h :=
+ fun j t a => v (bit j t a)
+
+private theorem satisfies_iff (v : Fin (width J b h) → Bool) :
+ Satisfies (formula J b h) v ↔
+ (∀ j w, v (wordFlag j w) = true ↔ bits v j = w) ∧
+ (∀ t u, v (tupleFlag t u) = true ↔ (fun j => bits v j t) = u) := by
+ have happ {k : ℕ} (a c : CNF k) (x : Fin k → Bool) :
+ Satisfies (a ++ c) x ↔ Satisfies a x ∧ Satisfies c x := by
+ simp [Satisfies]
+ aesop
+ simp only [formula, happ, satisfies_meetCNF, wordClauses, tupleClauses, satisfies_matchClauses,
+ Prod.forall, funext_iff, bits]
+
+private noncomputable def extendAt (x : J → Word b h) : Coordinates J b h → Bool
+ | .inl (j, t, a) => x j t a
+ | .inr (.inl (j, w)) => decide (x j = w)
+ | .inr (.inr (t, u)) => decide ((fun j => x j t) = u)
+
+private noncomputable def extend (x : J → Word b h) : Fin (width J b h) → Bool :=
+ extendAt x ∘ index.symm
+
+@[simp] private theorem extend_index (x : J → Word b h) (i : Coordinates J b h) :
+ extend x (index i) = extendAt x i := by simp [extend]
+
+@[simp] private theorem bits_extend (x : J → Word b h) : bits (extend x) = x := by
+ funext j t a
+ simp [bits, bit, extendAt]
+
+private theorem satisfies_extend (x : J → Word b h) : Satisfies (formula J b h) (extend x) := by
+ simp [satisfies_iff, wordFlag, tupleFlag, extendAt]
+
+private noncomputable def satisfyingEquiv :
+ (J → Word b h) ≃ {v // Satisfies (formula J b h) v} where
+ toFun x := ⟨extend x, satisfies_extend x⟩
+ invFun v := bits v.val
+ left_inv := bits_extend
+ right_inv v := by
+ apply Subtype.ext
+ funext i
+ obtain ⟨c, rfl⟩ := index.surjective i
+ change extend (bits v.val) (index c) = v.val (index c)
+ rw [extend_index]
+ obtain ⟨hw, ht⟩ := (satisfies_iff v.val).mp v.property
+ rcases c with ⟨j,t,a⟩ | (⟨j,w⟩ | ⟨t,u⟩)
+ · rfl
+ · change decide (bits v.val j = w) = v.val (wordFlag j w)
+ apply Bool.eq_iff_iff.mpr
+ simpa only [decide_eq_true_eq] using (hw j w).symm
+ · change decide ((fun j => bits v.val j t) = u) = v.val (tupleFlag t u)
+ apply Bool.eq_iff_iff.mpr
+ simpa only [decide_eq_true_eq] using (ht t u).symm
+
+variable {R : Type*} [CommSemiring R]
+
+private def weightAt (T : (J → Digit b) → R) : Coordinates J b h → (J × Word b h) ⊕ R
+ | .inl _ => .inr 1
+ | .inr (.inl p) => .inl p
+ | .inr (.inr (_, u)) => .inr (T u)
+
+/-- Each bit weight is either a scalar or one variable. -/
+noncomputable def weights (T : (J → Digit b) → R) (h : ℕ) :
+ Fin (width J b h) → (J × Word b h) ⊕ R := weightAt T ∘ index.symm
+
+private theorem extension_weight (T : (J → Digit b) → R) (x : J → Word b h) :
+ (∏ i, if extend x i then (weights T h i).elim X C else 1) =
+ (∏ j, X (j, x j)) * ∏ t, C (T (fun j => x j t)) := by
+ rw [← index.prod_comp (fun i => if extend x i then (weights T h i).elim X C else 1)]
+ simp only [extend_index, weights, Function.comp_apply, Equiv.symm_apply_apply,
+ Fintype.prod_sum_type, Fintype.prod_prod_type, extendAt, weightAt, Sum.elim_inr,
+ Sum.elim_inl, map_one, ite_self, Finset.prod_const_one, one_mul, decide_eq_true_eq]
+ simp
+
+/-- The weighted satisfying-assignment polynomial is exactly the tensor power form. -/
+theorem weightedCNF_formula (T : (J → Digit b) → R) (h : ℕ) :
+ weightedCNF (formula J b h) (fun i => (weights T h i).elim X C) = form T h := by
+ have hs {k : ℕ} (f : CNF k) (w : Fin k → MvPolynomial (J × Word b h) R) :
+ weightedCNF f w = ∑ v : {x // Satisfies f x}, ∏ i, if v.val i then w i else 1 := by
+ rw [weightedCNF, ← Finset.sum_filter]
+ exact Finset.sum_subtype _ (fun x => by simp) _
+ rw [hs, ← satisfyingEquiv.sum_comp, form]
+ exact Finset.sum_congr rfl (fun x _ => extension_weight T x)
+
+end TensorPowerCNF
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorPowerCNFBounds.lean b/lean/OAI/Computability/VPVNP/TensorPowerCNFBounds.lean
new file mode 100644
index 0000000000..e277277946
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorPowerCNFBounds.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.TensorPowerCNF
+import OAI.Computability.VPVNP.PaddedQuery
+import Mathlib.Tactic.Ring
+
+/-! # Input lengths for the tensor-power CNF
+
+For fixed bit width and number of parties, the control-state count and payload
+length grow at most exponentially in the number of tensor factors. The exponent
+of the local dimension in the compiled input length is absolute.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TensorPowerCNF
+
+/-- Uniform coefficient for the CNF width, literal count and query state count. -/
+def sizeCoefficient (b d : ℕ) : ℕ := 4 * d + (2 ^ b) ^ d * (3 * (d * b) + 1) + 2
+
+/-- Coefficient of the bound for the compiled table together with the payload. -/
+def lengthCoefficient (b d : ℕ) : ℕ := 4001 * sizeCoefficient b d ^ 6
+
+theorem lengthCoefficient_pos (b d : ℕ) : 0 < lengthCoefficient b d := by
+ unfold lengthCoefficient sizeCoefficient
+ positivity
+
+private theorem width_bound {d b h u : ℕ} (hh : h ≤ u) (hbits : h * b ≤ u)
+ (hpos : 0 < u) :
+ d * (h * b) + d * u + h * (2 ^ b) ^ d + 1 ≤ sizeCoefficient b d * u ^ 2 := by
+ have hco : 2 * d + (2 ^ b) ^ d + 1 ≤ sizeCoefficient b d := by
+ unfold sizeCoefficient
+ have := Nat.le_mul_of_pos_right ((2 ^ b) ^ d) (by omega : 0 < 3 * (d * b) + 1)
+ omega
+ calc
+ _ ≤ d * u + d * u + u * (2 ^ b) ^ d + u :=
+ Nat.add_le_add (Nat.add_le_add (Nat.add_le_add_right (Nat.mul_le_mul_left _ hbits) _)
+ (Nat.mul_le_mul_right _ hh)) hpos
+ _ = (2 * d + (2 ^ b) ^ d + 1) * u := by ring
+ _ ≤ _ := Nat.mul_le_mul hco (by simpa using Nat.pow_le_pow_right hpos (by decide : 1 ≤ 2))
+
+private theorem literal_bound {d b h u : ℕ} (hh : h ≤ u) (hbits : h * b ≤ u)
+ (hpos : 0 < u) :
+ d * u * (3 * (h * b) + 1) + h * (2 ^ b) ^ d * (3 * (d * b) + 1) + 2 ≤
+ sizeCoefficient b d * u ^ 2 := by
+ have hup : u ≤ u ^ 2 := by simpa using Nat.pow_le_pow_right hpos (by decide : 1 ≤ 2)
+ have hfirst : 3 * (h * b) + 1 ≤ 4 * u := by omega
+ calc
+ _ ≤ d * u * (4 * u) + u ^ 2 * (2 ^ b) ^ d * (3 * (d * b) + 1) + 2 * (u ^ 2) := by
+ apply Nat.add_le_add
+ · exact Nat.add_le_add (Nat.mul_le_mul_left _ hfirst)
+ (Nat.mul_le_mul_right _ (Nat.mul_le_mul_right _ (hh.trans hup)))
+ · exact Nat.le_mul_of_pos_right _ (Nat.pow_pos hpos)
+ _ = _ := by
+ unfold sizeCoefficient
+ ring
+
+private theorem growth {b : ℕ} (hb : 0 < b) (h : ℕ) :
+ h ≤ (2 ^ b) ^ h ∧ h * b ≤ (2 ^ b) ^ h := by
+ have hbits : h * b ≤ (2 ^ b) ^ h := by
+ rw [← pow_mul, Nat.mul_comm b h]
+ exact (h * b).lt_two_pow_self.le
+ exact ⟨(Nat.le_mul_of_pos_right _ hb).trans hbits, hbits⟩
+
+private theorem compiledLength_bound {b d h k : ℕ} (φ : HardnessCNF.CNF k)
+ (hwidth : k + 1 ≤ sizeCoefficient b d * ((2 ^ b) ^ h) ^ 2)
+ (hlits : HardnessCNF.literalCount φ + 2 ≤ sizeCoefficient b d * ((2 ^ b) ^ h) ^ 2) :
+ (UniversalMachine.programPrefix
+ (QueryMachine.machine (HardnessCNF.query φ) (HardnessCNF.literalCount φ))).length + k ≤
+ lengthCoefficient b d * ((2 ^ b) ^ 12) ^ h := by
+ let q := QueryMachine.machine (HardnessCNF.query φ) (HardnessCNF.literalCount φ)
+ have hstates : q.extra =
+ (HardnessCNF.literalCount φ + 1) * Fintype.card (HardnessCNF.State φ) * (k + 1) := by
+ simp [q, QueryMachine.machine, TableCompiler.compile, QueryMachine.Control, Nat.mul_assoc]
+ have hprefix := UniversalMachine.programPrefix_length_le q
+ rw [hstates] at hprefix
+ have hcard := HardnessCNF.card_state φ
+ have ht : HardnessCNF.literalCount φ + 1 ≤ sizeCoefficient b d * ((2 ^ b) ^ h) ^ 2 := by omega
+ have hq : Fintype.card (HardnessCNF.State φ) ≤ sizeCoefficient b d * ((2 ^ b) ^ h) ^ 2 := by omega
+ refine (queryInputLength_le hprefix ht hq hwidth).trans_eq ?_
+ simp only [lengthCoefficient, mul_pow, ← pow_mul, Nat.mul_assoc]
+ rw [Nat.mul_comm h 12]
+
+/-- Bound for the payload width including one unit of control overhead. -/
+theorem width_add_one_le (J : Type*) [Fintype J] (b h : ℕ) (hb : 0 < b) :
+ width J b h + 1 ≤ sizeCoefficient b (Fintype.card J) * ((2 ^ b) ^ h) ^ 2 := by
+ rw [width_eq]
+ obtain ⟨hh, hbits⟩ := growth hb h
+ exact width_bound hh hbits (by positivity)
+
+/-- The CNF compiler needs one read state per literal and two halting states. -/
+theorem literalCount_add_two_le (J : Type*) [Fintype J] (b h : ℕ) (hb : 0 < b) :
+ HardnessCNF.literalCount (formula J b h) + 2 ≤
+ sizeCoefficient b (Fintype.card J) * ((2 ^ b) ^ h) ^ 2 := by
+ rw [literalCount_formula]
+ obtain ⟨hh, hbits⟩ := growth hb h
+ exact literal_bound hh hbits (by positivity)
+
+/-- The entire table and payload fit at this length, uniformly in the tensor entries. -/
+theorem compiledLength_le (J : Type*) [Fintype J] (b h : ℕ) (hb : 0 < b) :
+ (UniversalMachine.programPrefix (QueryMachine.machine (HardnessCNF.query (formula J b h))
+ (HardnessCNF.literalCount (formula J b h)))).length + width J b h ≤
+ lengthCoefficient b (Fintype.card J) * ((2 ^ b) ^ 12) ^ h :=
+ compiledLength_bound (formula J b h) (width_add_one_le J b h hb)
+ (literalCount_add_two_le J b h hb)
+
+/-- At every sufficiently large source length, the universal polynomial projects
+onto the regrouped tensor power. The projection uses the entries of the given
+tensor as scalar constants. -/
+theorem projection {J R : Type*} [Fintype J] [CommRing R] {b : ℕ}
+ (T : (J → Digit b) → R) (hb : 0 < b) (h n : ℕ)
+ (hn : lengthCoefficient b (Fintype.card J) * ((2 ^ b) ^ 12) ^ h ≤ n) :
+ ∃ φ : Projection R (Fin n × Bool) (J × Word b h),
+ φ.hom (MvPolynomial.map (Int.castRingHom R) (P n)) = form T h := by
+ rw [← weightedCNF_formula, HardnessCNF.weightedCNF_eq_query]
+ exact weightedQuery_projection_at_length _ _ (weights T h) n
+ ((compiledLength_le J b h hb).trans hn)
+
+end TensorPowerCNF
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorPowerIncidence.lean b/lean/OAI/Computability/VPVNP/TensorPowerIncidence.lean
new file mode 100644
index 0000000000..0d1bf99208
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorPowerIncidence.lean
@@ -0,0 +1,152 @@
+import OAI.Computability.VPVNP.TensorPowerCNF
+
+/-! # An exact-one incidence matrix for tensor powers
+
+One block of columns selects a word at each party. Another block selects a
+tuple of digits at each position. Each consistency row counts a true bit on the
+word side and a false bit on the tuple side, so exact-one means the bits agree.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TensorPowerCNF
+
+open MvPolynomial
+open scoped Classical
+
+/-- Columns carrying the word and tuple selection flags. -/
+abbrev Col (J : Type*) (b h : ℕ) := (J × Word b h) ⊕ (Fin h × (J → Digit b))
+
+/-- A row for each one-hot field and each bit agreement. -/
+abbrev Row (J : Type*) (b h : ℕ) := (J ⊕ Fin h) ⊕ (J × (Fin h × Fin b))
+
+theorem card_col (J : Type*) [Fintype J] (b h : ℕ) :
+ Fintype.card (Col J b h) = Fintype.card J * (2 ^ b) ^ h + h * (2 ^ b) ^ Fintype.card J := by
+ simp [Col, Word, Digit]
+
+theorem card_row (J : Type*) [Fintype J] (b h : ℕ) :
+ Fintype.card (Row J b h) = Fintype.card J + h + Fintype.card J * (h * b) := by
+ simp [Row]
+
+variable {J : Type*} {b h : ℕ}
+
+/-- The entries for word and tuple columns use opposite polarities on a bit row. -/
+noncomputable def incidence : Row J b h → Col J b h → Bool
+ | .inl (.inl j), .inl (j', _) => decide (j = j')
+ | .inl (.inr t), .inr (t', _) => decide (t = t')
+ | .inl _, _ => false
+ | .inr (j, t, a), .inl (j', w) => decide (j = j') && w t a
+ | .inr (j, t, a), .inr (t', u) => decide (t = t') && !(u j a)
+
+/-- A selected word contributes a variable, and a selected tuple contributes a tensor entry. -/
+def columnWeight {R : Type*} (T : (J → Digit b) → R) (h : ℕ) :
+ Col J b h → (J × Word b h) ⊕ R
+ | .inl jw => .inl jw
+ | .inr (_, u) => .inr (T u)
+
+private noncomputable def flags (p : J → Word b h) (q : Fin h → J → Digit b) :
+ Col J b h → Bool
+ | .inl (j, w) => decide (p j = w)
+ | .inr (t, u) => decide (q t = u)
+
+private def Exact (x : Col J b h → Bool) : Prop :=
+ ∀ r : Row J b h, ∃! i, x i = true ∧ incidence r i = true
+
+private theorem wordRow_iff (x : Col J b h → Bool) (j : J) :
+ (∃! i, x i = true ∧ incidence (.inl (.inl j)) i = true) ↔
+ ∃! w, x (.inl (j, w)) = true := by
+ simp [ExistsUnique, Sum.exists, Sum.forall, Prod.exists, Prod.forall, incidence]
+ grind
+
+private theorem tupleRow_iff (x : Col J b h → Bool) (t : Fin h) :
+ (∃! i, x i = true ∧ incidence (.inl (.inr t)) i = true) ↔
+ ∃! u, x (.inr (t, u)) = true := by
+ simp [ExistsUnique, Sum.exists, Sum.forall, Prod.exists, Prod.forall, incidence]
+ grind
+
+private theorem bitRow_iff (p : J → Word b h) (q : Fin h → J → Digit b)
+ (j : J) (t : Fin h) (a : Fin b) :
+ (∃! i, flags p q i = true ∧ incidence (.inr (j, t, a)) i = true) ↔ p j t a = q t j a := by
+ have hx (i : Col J b h) :
+ (flags p q i = true ∧ incidence (.inr (j, t, a)) i = true) ↔
+ (i = .inl (j, p j) ∧ p j t a = true) ∨ (i = .inr (t, q t) ∧ q t j a = false) := by
+ rcases i with ⟨j', w⟩ | ⟨t', u⟩
+ · simp [incidence, flags]
+ aesop
+ · simp [incidence, flags]
+ aesop
+ simp_rw [hx]
+ cases hp : p j t a <;> cases hq : q t j a <;>
+ simp [ExistsUnique]
+
+private noncomputable def selection (p : J → Word b h) : Col J b h → Bool :=
+ flags p (fun t j => p j t)
+
+private theorem exact_selection (p : J → Word b h) : Exact (selection p) := by
+ rintro ((j | t) | ⟨j, t, a⟩)
+ · rw [wordRow_iff]
+ simp [selection, flags, ExistsUnique]
+ · rw [tupleRow_iff]
+ simp [selection, flags, ExistsUnique]
+ · exact (bitRow_iff p _ j t a).mpr rfl
+
+private theorem exists_selection (x : Col J b h → Bool) (hx : Exact x) :
+ ∃ p : J → Word b h, selection p = x := by
+ choose p hp hp' using fun j => (wordRow_iff x j).mp (hx (.inl (.inl j)))
+ choose q hq hq' using fun t => (tupleRow_iff x t).mp (hx (.inl (.inr t)))
+ have he : flags p q = x := by
+ funext i
+ apply Bool.eq_iff_iff.mpr
+ rcases i with ⟨j, w⟩ | ⟨t, u⟩
+ · simp only [flags, decide_eq_true_eq]
+ exact ⟨fun e => e ▸ hp j, fun hw => (hp' j w hw).symm⟩
+ · simp only [flags, decide_eq_true_eq]
+ exact ⟨fun e => e ▸ hq t, fun hu => (hq' t u hu).symm⟩
+ have hbits : (fun t j => p j t) = q := by
+ funext t j a
+ apply (bitRow_iff p q j t a).mp
+ rw [he]
+ exact hx (.inr (j, t, a))
+ exact ⟨p, by simpa only [selection, hbits] using he⟩
+
+private noncomputable def exactSelectionEquiv :
+ (J → Word b h) ≃ {x : Col J b h → Bool // Exact x} :=
+ Equiv.ofBijective (fun p => ⟨selection p, exact_selection p⟩) (by
+ constructor
+ · intro p p' he
+ have he' := congrArg Subtype.val he
+ funext j
+ have hc := congrFun he' (.inl (j, p' j))
+ simpa [selection, flags] using hc
+ · intro x
+ obtain ⟨p, hp⟩ := exists_selection x.val x.property
+ exact ⟨p, Subtype.ext hp⟩)
+
+variable [Fintype J] {R : Type*} [CommSemiring R]
+
+private theorem selectedWeight (T : (J → Digit b) → R) (p : J → Word b h) :
+ (∏ i, if selection p i then (columnWeight T h i).elim X C else 1) =
+ (∏ j, X (j, p j)) * ∏ t, C (T (fun j => p j t)) := by
+ simp [Fintype.prod_sum_type, Fintype.prod_prod_type, selection, flags, columnWeight]
+
+/-- Summing the weights of all exact-one solutions gives the regrouped tensor power form. -/
+theorem weightedIncidence_eq_form (T : (J → Digit b) → R) (h : ℕ) :
+ (∑ x : Col J b h → Bool,
+ if ∀ r : Row J b h, ∃! i, x i = true ∧ incidence r i = true then
+ ∏ i, if x i then (columnWeight T h i).elim X C else 1 else 0) = form T h := by
+ let w (x : Col J b h → Bool) := ∏ i, if x i then (columnWeight T h i).elim X C else 1
+ have hs : (∑ x : Col J b h → Bool,
+ if ∀ r : Row J b h, ∃! i, x i = true ∧ incidence r i = true then w x else 0) =
+ ∑ x : {v // Exact v}, w x.val := by
+ rw [← Finset.sum_filter]
+ exact Finset.sum_subtype _ (fun x => by simp [Exact]) _
+ rw [hs, ← exactSelectionEquiv.sum_comp, form]
+ exact Finset.sum_congr rfl (fun p _ => selectedWeight T p)
+
+end TensorPowerCNF
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorPowerLayout.lean b/lean/OAI/Computability/VPVNP/TensorPowerLayout.lean
new file mode 100644
index 0000000000..26b2515644
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorPowerLayout.lean
@@ -0,0 +1,114 @@
+import OAI.Computability.VPVNP.ProjectedPowerObstruction
+import OAI.Computability.VPVNP.TensorPowerCNFBounds
+import Mathlib.Analysis.SpecialFunctions.Log.Base
+
+/-!
+# The tensor-power layout bound for the universal family
+
+The finite-state tensor-power verifier uses source length at most a constant times
+`((2^b)^12)^h`. Thus the comparison with an `n^C` circuit uses the exponent `12*C`.
+The constant may depend on the number of parties and the fixed digit width, while the
+exponent twelve is independent of both. The terminal tensor below uses cardinality
+indices `Fin (2^b)`, as in the star-witness construction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+open MvPolynomial WireTensor TensorPowerCNF
+
+variable {k : Type*} [Field k] {I : Type} [Fintype I] [DecidableEq I]
+ {P : Type*} [Fintype P] [Nonempty P]
+
+/-- A layout whose scaled length lies below the normalized logarithm of the witness
+has strictly smaller spectral growth. -/
+theorem power_lt_of_scaled_logb {scale threshold cost v : ℝ} {b : ℕ} (hs : 0 < scale)
+ (hb : 0 < b) (hv : 0 < v) (hcost : cost ≤ scale * threshold)
+ (hval : threshold < Real.logb 2 v / (scale * b)) :
+ (((2 ^ b : ℕ) : ℝ) ^ cost) < v := by
+ rw [Nat.cast_pow, Nat.cast_ofNat, ← Real.rpow_natCast_mul (by norm_num : 0 ≤ (2 : ℝ))]
+ apply (Real.lt_logb_iff_rpow_lt (by norm_num : 1 < (2 : ℝ)) hv).mp
+ calc
+ (b : ℝ) * cost ≤ b * (scale * threshold) := mul_le_mul_of_nonneg_left hcost (Nat.cast_nonneg _)
+ _ = threshold * (scale * b) := by ring
+ _ < _ := (lt_div_iff₀ (mul_pos hs (Nat.cast_pos.mpr hb))).mp hval
+
+omit [DecidableEq I] [Nonempty P] in
+/-- A local reindexing of all terminal legs leaves their placed tensor's value unchanged. -/
+theorem value_reindex_terminal_array {J L : Type} [Fintype J] [Fintype L] (F : SpectralPoint k P)
+ (place : I → P) (e : J ≃ L) (A : (I → L) → k) :
+ F.value (placedTensor place (fun _ ↦ J) (fun x ↦ A (e ∘ x))) =
+ F.value (placedTensor place (fun _ ↦ L) A) := by
+ let eqv (j : P) : ((r : I) → j = place r → J) ≃ ((r : I) → j = place r → L) :=
+ Equiv.piCongrRight fun _ ↦ Equiv.piCongrRight fun _ ↦ e
+ exact (F.value_eq_of_mutual (restricts_of_reindex eqv (fun _ ↦ rfl))).symm
+
+omit [DecidableEq I] in
+/-- The `h`-fold tensor form from the machine construction records the ordered
+product of the selected tensor entries. -/
+theorem TensorPowerCNF.coeff_form {b h : ℕ} (A : (I → Digit b) → k) (a : I → Word b h) :
+ (form A h).coeff (partyExponent Finset.univ a) = ∏ t : Fin h, A (fun i ↦ a i t) := by
+ classical
+ simpa only [form, map_prod] using coeff_partyForm (fun x : I → Word b h ↦ ∏ t : Fin h, A (fun i ↦ x i t)) a
+
+/-- Reindex the star witness by binary digits and convert its normalized log
+lower bound into a strict spectral growth comparison for every balanced cut. -/
+theorem exists_digit_layout_witness (F : SpectralPoint k P)
+ (place : I → P) (centers : Finset I → Bool → P) {b C : ℕ} (hb : 0 < b)
+ (A : (I → Fin (2^b)) → k) (hnz : A ≠ 0) {scale threshold : ℝ} (hs : 0 < scale)
+ (hlower : threshold <
+ Real.logb 2 (F.value (placedTensor place (fun _ ↦ Fin (2^b)) A)) / (scale * b))
+ (hcost : ∀ S : Finset I, Fintype.card I ≤ 3*S.card → 3*S.card ≤ 2*Fintype.card I →
+ (C : ℝ) * F.wireDistance (centers S false) (centers S true) +
+ ∑ i, F.wireDistance (place i) (centers S (cutSide S i)) ≤ scale * threshold) :
+ ∃ A' : (I → Digit b) → k, 0 < (F.value (placedTensor place (fun _ ↦ Digit b) A') : ℝ) ∧
+ ∀ S : Finset I, Fintype.card I ≤ 3*S.card → 3*S.card ≤ 2*Fintype.card I →
+ (Fintype.card (Digit b) : ℝ) ^ ((C : ℝ) * F.wireDistance (centers S false) (centers S true) +
+ ∑ i, F.wireDistance (place i) (centers S (cutSide S i))) <
+ (F.value (placedTensor place (fun _ ↦ Digit b) A') : ℝ) := by
+ classical
+ let e : Digit b ≃ Fin (2 ^ b) := Fintype.equivFinOfCardEq (by simp [Digit])
+ let A' : (I → Digit b) → k := fun a ↦ A (e ∘ a)
+ let v := (F.value (placedTensor place (fun _ ↦ Fin (2^b)) A) : ℝ)
+ have heq : F.value (placedTensor place (fun _ ↦ Digit b) A') =
+ F.value (placedTensor place (fun _ ↦ Fin (2^b)) A) :=
+ value_reindex_terminal_array F place e A
+ have hv : 0 < v := by
+ have hnz' : (placedTensor place (fun _ ↦ Fin (2^b)) A).coeff ≠ 0 := by
+ intro hz
+ exact hnz (funext fun a ↦ congrFun hz (fun _ r _ ↦ a r))
+ exact_mod_cast zero_lt_one.trans_le (F.one_le_value _ hnz')
+ have hcard : Fintype.card (Digit b) = 2 ^ b := by simp [Digit]
+ refine ⟨A', heq.symm ▸ hv, fun S hlo hhi ↦ ?_⟩
+ rw [heq, hcard]
+ exact power_lt_of_scaled_logb hs hb hv (hcost S hlo hhi) hlower
+
+/-- A star witness strictly above every balanced layout precludes infinitely many
+small-circuit lengths. The exponent of the layout's central wire includes the length
+overhead of the concrete literal projection. -/
+theorem not_small_universal_of_tensorPower_layout (F : SpectralPoint k P)
+ (place : I → P) (centers : Finset I → Bool → P) {b C : ℕ} (hb : 0 < b) (hC : 0 < C)
+ (hI : 3 ≤ Fintype.card I) (A : (I → Fin (2^b)) → k) (hnz : A ≠ 0)
+ {scale threshold : ℝ} (hs : 0 < scale)
+ (hlower : threshold <
+ Real.logb 2 (F.value (placedTensor place (fun _ ↦ Fin (2^b)) A)) / (scale * b))
+ (hcost : ∀ S : Finset I, Fintype.card I ≤ 3*S.card → 3*S.card ≤ 2*Fintype.card I →
+ ((12*C : ℕ) : ℝ) * F.wireDistance (centers S false) (centers S true) +
+ ∑ i, F.wireDistance (place i) (centers S (cutSide S i)) ≤ scale * threshold) :
+ ¬ ∀ N, ∃ n ≥ N, circuitSize (map (Int.castRingHom k) (VPVNP.P n)) ≤ n^C := by
+ classical
+ obtain ⟨A', hv, hgap⟩ := exists_digit_layout_witness F place centers hb A hnz hs hlower hcost
+ have hcard : Fintype.card (Digit b) = 2 ^ b := by simp [Digit]
+ apply not_small_universal_of_power_projections F place centers A' (form A')
+ (lengthCoefficient b (Fintype.card I)) 12 C (lengthCoefficient_pos _ _) (by decide) hC hI
+ (hcard ▸ one_lt_pow₀ (by decide : 1 < (2 : ℕ)) hb.ne')
+ · exact fun h a ↦ TensorPowerCNF.coeff_form A' a
+ · intro h n hn
+ exact projection A' hb h n (by simpa only [hcard] using hn)
+ · exact hv
+ · exact hgap
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorPowerLengths.lean b/lean/OAI/Computability/VPVNP/TensorPowerLengths.lean
new file mode 100644
index 0000000000..29da352b7f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorPowerLengths.lean
@@ -0,0 +1,45 @@
+import OAI.Computability.VPVNP.PaddedQuery
+import Mathlib.Data.Nat.Log
+
+/-! # Selecting powers at lengths with a small circuit
+
+A polynomial-size literal encoding of each tensor power suffices for cube
+exclusion if its polynomial exponent is absolute. Use the largest power whose
+encoding fits at the given length. The cutoff is selected after the circuit
+length, which can belong to an arbitrary unbounded set.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+theorem arbitrarily_large_powers_of_small_circuits {F : Type*} [CommRing F]
+ {V : ℕ → Type*} (forms : (h : ℕ) → MvPolynomial (V h) F)
+ {A B C : ℕ} (hA : 0 < A) (hB : 1 < B)
+ (projections : ∀ h n, A * B^h ≤ n → ∃ φ : Projection F (Fin n × Bool) (V h),
+ φ.hom (MvPolynomial.map (Int.castRingHom F) (P n)) = forms h)
+ (small : ∀ N, ∃ n ≥ N, circuitSize (MvPolynomial.map (Int.castRingHom F) (P n)) ≤ n^C) :
+ ∀ H, ∃ h ≥ H, circuitSize (forms h) ≤ (A * B)^C * (B^h)^C := by
+ intro H
+ obtain ⟨n, hn, hs⟩ := small (A * B^H)
+ let h := Nat.log B (n/A)
+ have hquot : B^H ≤ n/A := (Nat.le_div_iff_mul_le hA).mpr (by simpa [mul_comm] using hn)
+ have hpos : n/A ≠ 0 := Nat.ne_of_gt ((Nat.pow_pos (by omega : 0 < B)).trans_le hquot)
+ have hlow : A * B^h ≤ n := by
+ rw [mul_comm]
+ exact (Nat.le_div_iff_mul_le hA).mp (Nat.pow_log_le_self B hpos)
+ have hhigh : n ≤ A * B * B^h := by
+ have bound := (Nat.div_lt_iff_lt_mul hA).mp (Nat.lt_pow_succ_log_self hB (n/A))
+ simpa [h, pow_succ, Nat.mul_comm, Nat.mul_left_comm, Nat.mul_assoc] using bound.le
+ obtain ⟨φ, hφ⟩ := projections h n hlow
+ refine ⟨h, Nat.le_log_of_pow_le hB hquot, ?_⟩
+ calc
+ circuitSize (forms h) ≤ circuitSize (MvPolynomial.map (Int.castRingHom F) (P n)) :=
+ hφ ▸ circuitSize_projection_le φ _
+ _ ≤ n^C := hs
+ _ ≤ (A * B * B^h)^C := Nat.pow_le_pow_left hhigh C
+ _ = _ := mul_pow _ _ _
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorPowerSharpProjection.lean b/lean/OAI/Computability/VPVNP/TensorPowerSharpProjection.lean
new file mode 100644
index 0000000000..0052886ae2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorPowerSharpProjection.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.TensorPowerIncidence
+import OAI.Computability.VPVNP.IncidenceReindex
+import OAI.Computability.VPVNP.IncidenceProjection
+import Mathlib.Tactic.Ring
+
+/-! # Tensor powers as projections with a near-linear input length
+
+The exact-one table has one row per party, position and digit comparison.
+Its row count is linear in the power index. The columns are the one-hot
+flags, whose count grows at the rate of the local dimension to that power.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace TensorPowerCNF
+open scoped Classical
+
+private def rowCoefficient (b d : ℕ) := d + d * b + 2
+
+/-- Uniform constant in the source-length estimate for the exact-one table. -/
+def sharpCoefficient (b d : ℕ) :=
+ 1000000 * rowCoefficient b d ^ 4 + (d + (2 ^ b) ^ d) * rowCoefficient b d + 1
+
+private theorem table_size_le (J : Type*) [Fintype J] (b h : ℕ) :
+ 1000000 * (Fintype.card (Row J b h) + 1) ^ 4 +
+ Fintype.card (Col J b h) * (Fintype.card (Row J b h) + 2) + 1 ≤
+ sharpCoefficient b (Fintype.card J) * (h + 1) ^ 4 * (2 ^ b) ^ h := by
+ let d := Fintype.card J
+ let u := (2 ^ b) ^ h
+ let M := rowCoefficient b d
+ let K := d + (2 ^ b) ^ d
+ have hu : 0 < u := by
+ dsimp [u]
+ positivity
+ have hm : Fintype.card (Row J b h) + 2 ≤ M * (h + 1) := by
+ rw [card_row]
+ dsimp [M, rowCoefficient, d]
+ nlinarith only [Nat.zero_le (Fintype.card J * h), Nat.zero_le (Fintype.card J * b)]
+ have hk : Fintype.card (Col J b h) ≤ K * (h + 1) * u := by
+ rw [card_col]
+ change d * u + h * (2 ^ b) ^ d ≤ _
+ calc
+ _ ≤ d * ((h + 1) * u) + (2 ^ b) ^ d * ((h + 1) * u) := by
+ apply Nat.add_le_add
+ · apply Nat.mul_le_mul_left
+ exact Nat.le_mul_of_pos_left _ (by omega)
+ · rw [Nat.mul_comm h]
+ exact Nat.mul_le_mul_left _ ((Nat.le_succ h).trans (Nat.le_mul_of_pos_right _ hu))
+ _ = _ := by
+ dsimp [K]
+ ring
+ have hp : (h + 1) ^ 2 ≤ (h + 1) ^ 4 :=
+ Nat.pow_le_pow_right (by omega) (by decide)
+ have hprefix : 1000000 * (Fintype.card (Row J b h) + 1) ^ 4 ≤
+ (1000000 * M ^ 4) * (h + 1) ^ 4 * u := by
+ refine (Nat.mul_le_mul_left 1000000 (Nat.pow_le_pow_left (le_trans ?_ hm) 4)).trans ?_
+ · omega
+ · rw [mul_pow, ← mul_assoc]
+ exact Nat.le_mul_of_pos_right _ hu
+ have hpayload : Fintype.card (Col J b h) * (Fintype.card (Row J b h) + 2) ≤
+ (K * M) * (h + 1) ^ 4 * u := by
+ calc
+ _ ≤ (K * (h + 1) * u) * (M * (h + 1)) := Nat.mul_le_mul hk hm
+ _ = (K * M) * (h + 1) ^ 2 * u := by ring
+ _ ≤ _ := Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ hp)
+ have hunit : 1 ≤ (h + 1) ^ 4 * u := Nat.mul_pos (Nat.pow_pos (by omega)) hu
+ refine (Nat.add_le_add (Nat.add_le_add hprefix hpayload) hunit).trans_eq ?_
+ dsimp [sharpCoefficient, M, K, d, u]
+ ring
+
+variable {J R : Type*} [Fintype J] [CommRing R] {b : ℕ}
+
+/-- At every length above this explicit bound, the universal polynomial projects
+to the tensor power. The bound depends only on the bit width and party count. -/
+theorem projection_at_sharp_length (T : (J → Digit b) → R) (h n : ℕ)
+ (hn : sharpCoefficient b (Fintype.card J) * (h + 1) ^ 4 * (2 ^ b) ^ h ≤ n) :
+ ∃ φ : Projection R (Fin n × Bool) (J × Word b h),
+ φ.hom (MvPolynomial.map (Int.castRingHom R) (P n)) = form T h := by
+ let rows := (Fintype.equivFin (Row J b h)).symm
+ let cols := (Fintype.equivFin (Col J b h)).symm
+ obtain ⟨φ, hφ⟩ := IncidenceMachine.weighted_projection
+ (fun r i => incidence (rows r) (cols i)) (columnWeight T h ∘ cols) n
+ ((table_size_le J b h).trans hn)
+ refine ⟨φ, hφ.trans ?_⟩
+ apply (IncidenceMachine.weighted_exactOne_reindex rows cols incidence (columnWeight T h)).trans
+ convert weightedIncidence_eq_form T h using 1
+ congr
+ exact Subsingleton.elim _ _
+
+/-- The exponential growth rate of the projection length is at most the local
+dimension, with polynomial overhead in the power index. -/
+theorem sharp_projection (T : (J → Digit b) → R) :
+ ∃ A > 0, ∀ h n, A * (h + 1) ^ 4 * (2 ^ b) ^ h ≤ n →
+ ∃ φ : Projection R (Fin n × Bool) (J × Word b h),
+ φ.hom (MvPolynomial.map (Int.castRingHom R) (P n)) = form T h :=
+ ⟨sharpCoefficient b (Fintype.card J), Nat.zero_lt_succ _, projection_at_sharp_length T⟩
+
+end TensorPowerCNF
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorRestriction.lean b/lean/OAI/Computability/VPVNP/TensorRestriction.lean
new file mode 100644
index 0000000000..15c4289365
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorRestriction.lean
@@ -0,0 +1,87 @@
+import OAI.Computability.VPVNP.WireTensor
+
+/-!
+# Tensor classes modulo mutual restriction
+
+Each class retains its concrete restriction comparisons. The smaller class
+is the demand and the larger class is the supply. Direct sums and products
+descend to the quotient because independent local maps act on both factors.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+universe u v
+
+variable (k : Type u) (J : Type v) [Field k] [Fintype J]
+
+/-- Identifying exactly those tensors that restrict to each other. -/
+def restrictionSetoid : Setoid (Tensor.{u,v,0} k J) where
+ r T U := Restricts T U ∧ Restricts U T
+ iseqv := ⟨fun T => ⟨.refl T, .refl T⟩, fun h => h.symm,
+ fun h g => ⟨h.1.trans g.1, g.2.trans h.2⟩⟩
+
+/-- The restriction classes used to form the semiring of Section 2. -/
+def RestrictionClass := Quotient (restrictionSetoid k J)
+
+namespace RestrictionClass
+
+variable {k J}
+
+/-- Map a concrete tensor to its equivalence class under mutual restriction by local linear
+maps. -/
+def ofTensor (T : Tensor.{u,v,0} k J) : RestrictionClass k J :=
+ Quotient.mk (restrictionSetoid k J) T
+
+theorem ofTensor_eq_iff (T U : Tensor.{u,v,0} k J) :
+ ofTensor T = ofTensor U ↔ Restricts T U ∧ Restricts U T :=
+ Quotient.eq
+
+theorem ofTensor_surjective : Function.Surjective (ofTensor (k := k) (J := J)) :=
+ Quotient.exists_rep
+
+instance : LE (RestrictionClass k J) where
+ le x y := Quotient.liftOn₂ x y (fun T U => Restricts U T) <| by
+ intro a b c d hab hcd
+ exact propext ⟨fun h => hcd.2.trans (h.trans hab.1), fun h => hcd.1.trans (h.trans hab.2)⟩
+
+theorem ofTensor_le_iff (T U : Tensor.{u,v,0} k J) :
+ ofTensor T ≤ ofTensor U ↔ Restricts U T := Iff.rfl
+
+instance : PartialOrder (RestrictionClass k J) where
+ le_refl x := Quotient.inductionOn x Restricts.refl
+ le_trans x y z := Quotient.inductionOn₃ x y z fun _ _ _ h g => Restricts.trans g h
+ le_antisymm x y := Quotient.inductionOn₂ x y fun _ _ h g => Quotient.sound ⟨g, h⟩
+
+noncomputable instance : Add (RestrictionClass k J) where
+ add := Quotient.map₂ directSum fun _ _ h _ _ g =>
+ ⟨directSum_restricts h.1 g.1, directSum_restricts h.2 g.2⟩
+
+instance : Mul (RestrictionClass k J) where
+ mul := Quotient.map₂ tensorProduct fun _ _ h _ _ g =>
+ ⟨h.1.tensorProduct g.1, h.2.tensorProduct g.2⟩
+
+noncomputable instance : Zero (RestrictionClass k J) := ⟨ofTensor (diagonal (Fin 0))⟩
+
+instance : One (RestrictionClass k J) := ⟨ofTensor unit⟩
+
+@[simp] theorem ofTensor_directSum (T U : Tensor.{u,v,0} k J) :
+ ofTensor (directSum T U) = ofTensor T + ofTensor U := rfl
+
+@[simp] theorem ofTensor_tensorProduct (T U : Tensor.{u,v,0} k J) :
+ ofTensor (tensorProduct T U) = ofTensor T * ofTensor U := rfl
+
+@[simp] theorem ofTensor_diagonal_zero : ofTensor (diagonal (Fin 0)) = (0 : RestrictionClass k J) :=
+ rfl
+
+@[simp] theorem ofTensor_unit : ofTensor unit = (1 : RestrictionClass k J) := rfl
+
+end RestrictionClass
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorRestrictionSemiring.lean b/lean/OAI/Computability/VPVNP/TensorRestrictionSemiring.lean
new file mode 100644
index 0000000000..e5f93ac81a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorRestrictionSemiring.lean
@@ -0,0 +1,118 @@
+import OAI.Computability.VPVNP.TensorRestriction
+import OAI.Computability.VPVNP.TensorDistributivity
+import OAI.Computability.VPVNP.TensorUnitLaws
+import OAI.Computability.VPVNP.WireSpectrum
+import OAI.Computability.VPVNP.SpectralLocalizationCone
+
+/-!
+# The restriction semiring on a finite party set
+
+The direct sum and parallel tensor product of arrays make their mutual
+restriction classes into a commutative semiring. The natural number `n`
+is represented by the all-party diagonal with `n` entries. A nonzero array
+restricts to the unit, and the product of its local dimensions gives a
+natural number that restricts to the array. These are the order bounds
+used in Appendix A.1 of *VP and VNP differ over every field*.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor.RestrictionClass
+
+universe u v
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nonempty J]
+
+private theorem add_swap (a b : RestrictionClass k J) : a + b = b + a :=
+ Quotient.inductionOn₂ a b fun T U => Quotient.sound (directSum_comm_mutual T U)
+
+omit [Nonempty J] in
+private theorem mul_swap (a b : RestrictionClass k J) : a * b = b * a :=
+ Quotient.inductionOn₂ a b fun T U => Quotient.sound (tensorProduct_comm_mutual T U)
+
+private theorem mul_distrib (a b c : RestrictionClass k J) :
+ a * (b + c) = a*b + a*c :=
+ Quotient.inductionOn₃ a b c fun T U V => Quotient.sound (tensorProduct_directSum_mutual T U V)
+
+private theorem diagonal_succ (n : ℕ) :
+ (ofTensor (diagonal (Fin (n+1))) : RestrictionClass k J) = ofTensor (diagonal (Fin n)) + 1 := by
+ calc
+ _ = ofTensor (diagonal (Fin n ⊕ Fin 1)) :=
+ (ofTensor_eq_iff _ _).2 (diagonal_reindex_mutual finSumFinEquiv.symm)
+ _ = ofTensor (directSum (diagonal (Fin n)) (diagonal (Fin 1))) :=
+ (ofTensor_eq_iff _ _).2 (diagonal_sum_mutual _ _)
+ _ = _ := congrArg (ofTensor (diagonal (Fin n)) + ·) ((ofTensor_eq_iff _ _).2 diagonal_unit_mutual)
+
+noncomputable instance : CommSemiring (RestrictionClass k J) where
+ nsmul := nsmulRec
+ natCast n := ofTensor (diagonal (Fin n))
+ natCast_zero := rfl
+ natCast_succ := diagonal_succ
+ add_assoc a b c := Quotient.inductionOn₃ a b c fun T U V => Quotient.sound (directSum_assoc_mutual T U V)
+ add_comm := add_swap
+ add_zero a := Quotient.inductionOn a fun T => Quotient.sound (directSum_zero_mutual T)
+ zero_add a := (add_swap 0 a).trans (Quotient.inductionOn a fun T => Quotient.sound (directSum_zero_mutual T))
+ mul_assoc a b c := Quotient.inductionOn₃ a b c fun T U V => Quotient.sound (tensorProduct_assoc_mutual T U V)
+ mul_comm := mul_swap
+ mul_one a := Quotient.inductionOn a fun T => Quotient.sound (tensorProduct_unit_mutual T)
+ one_mul a := (mul_swap 1 a).trans (Quotient.inductionOn a fun T => Quotient.sound (tensorProduct_unit_mutual T))
+ mul_zero a := Quotient.inductionOn a fun T => Quotient.sound (tensorProduct_zero_mutual T)
+ zero_mul a := (mul_swap 0 a).trans (Quotient.inductionOn a fun T => Quotient.sound (tensorProduct_zero_mutual T))
+ left_distrib := mul_distrib
+ right_distrib a b c := by rw [mul_swap (a+b), mul_distrib, mul_swap c a, mul_swap c b]
+
+@[simp] theorem ofTensor_diagonal_fin (n : ℕ) :
+ ofTensor (diagonal (Fin n)) = (n : RestrictionClass k J) := rfl
+
+@[simp] theorem ofTensor_eq_zero_iff (T : Tensor.{u,v,0} k J) :
+ ofTensor T = 0 ↔ T.coeff = 0 := by
+ change ofTensor T = ofTensor (diagonal (Fin 0)) ↔ _
+ rw [ofTensor_eq_iff, zero_restricts_iff, and_iff_right (restricts_zero T)]
+
+instance : Nontrivial (RestrictionClass k J) := by
+ refine ⟨⟨1, 0, ?_⟩⟩
+ intro h
+ have hz := (ofTensor_eq_zero_iff (k := k) (J := J) unit).1 h
+ exact one_ne_zero (α := k) (congrFun hz (fun _ => PUnit.unit))
+
+/-- Nonzero coefficient witnesses in the two factors combine into one in their product. -/
+instance : NoZeroDivisors (RestrictionClass k J) where
+ eq_zero_or_eq_zero_of_mul_eq_zero {a b} := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective a
+ obtain ⟨U, rfl⟩ := ofTensor_surjective b
+ rw [← ofTensor_tensorProduct, ofTensor_eq_zero_iff, ofTensor_eq_zero_iff, ofTensor_eq_zero_iff]
+ contrapose!
+ rintro ⟨hT, hU⟩
+ obtain ⟨x, hx⟩ := Function.ne_iff.mp hT
+ obtain ⟨y, hy⟩ := Function.ne_iff.mp hU
+ exact Function.ne_iff.mpr ⟨fun j => (x j, y j), mul_ne_zero hx hy⟩
+
+/-- Rank bounds and monotonicity under independent restrictions supply all
+the order hypotheses of strict spectral comparison. -/
+theorem orderBounds : Spectral.OrderBounds (RestrictionClass k J) where
+ zero_le a := Quotient.inductionOn a restricts_zero
+ one_le {a} := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective a
+ exact fun h => restricts_unit_of_ne_zero T (fun hT => h ((ofTensor_eq_zero_iff T).2 hT))
+ bounded a := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective a
+ exact ⟨_, diagonal_restricts_of_card T⟩
+ add_mono {a b c d} := by
+ obtain ⟨A, rfl⟩ := ofTensor_surjective a
+ obtain ⟨B, rfl⟩ := ofTensor_surjective b
+ obtain ⟨C, rfl⟩ := ofTensor_surjective c
+ obtain ⟨D, rfl⟩ := ofTensor_surjective d
+ exact fun h g => directSum_restricts h g
+ mul_mono t {a b} := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective t
+ obtain ⟨A, rfl⟩ := ofTensor_surjective a
+ obtain ⟨B, rfl⟩ := ofTensor_surjective b
+ exact fun h => (Restricts.refl T).tensorProduct h
+
+end WireTensor.RestrictionClass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorRestrictionSpectrum.lean b/lean/OAI/Computability/VPVNP/TensorRestrictionSpectrum.lean
new file mode 100644
index 0000000000..94e151b171
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorRestrictionSpectrum.lean
@@ -0,0 +1,88 @@
+import OAI.Computability.VPVNP.TensorRestrictionSemiring
+import OAI.Computability.VPVNP.WireSpectrum
+
+/-!
+# Spectral points on the semiring of tensor restriction classes
+
+A spectral point is constant on each class of mutually restricting tensors.
+Its real values define a monotone semiring homomorphism on the quotient.
+Conversely, monotonicity bounds the values of such a homomorphism below by
+zero, so its evaluations on tensor representatives form a spectral point.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+open scoped NNReal
+
+namespace WireTensor.RestrictionClass
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nonempty J]
+
+/-- Real-valued evaluation of a spectral point on restriction classes. -/
+noncomputable def ofSpectralPoint (F : SpectralPoint k J) : RestrictionClass k J →+* ℝ where
+ toFun := Quotient.lift (fun T ↦ (F.value T : ℝ))
+ (fun _ _ h ↦ congrArg (fun r : ℝ≥0 ↦ (r : ℝ)) (F.value_eq_of_mutual h))
+ map_zero' := by
+ change (F.value (diagonal (Fin 0)) : ℝ) = 0
+ simp [F.value_diagonal_fin]
+ map_one' := by
+ change (F.value unit : ℝ) = 1
+ simp [F.value_unit]
+ map_add' a b := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective a
+ obtain ⟨U, rfl⟩ := ofTensor_surjective b
+ change (F.value (directSum T U) : ℝ) = (F.value T : ℝ) + F.value U
+ rw [F.value_directSum, NNReal.coe_add]
+ map_mul' a b := by
+ obtain ⟨T, rfl⟩ := ofTensor_surjective a
+ obtain ⟨U, rfl⟩ := ofTensor_surjective b
+ change (F.value (tensorProduct T U) : ℝ) = (F.value T : ℝ) * F.value U
+ rw [F.value_tensorProduct, NNReal.coe_mul]
+
+@[simp] theorem ofSpectralPoint_ofTensor (F : SpectralPoint k J) (T : Tensor.{u,v,0} k J) :
+ ofSpectralPoint F (ofTensor T) = (F.value T : ℝ) := rfl
+
+theorem ofSpectralPoint_monotone (F : SpectralPoint k J) : Monotone (ofSpectralPoint F) := by
+ intro a b hab
+ obtain ⟨T, rfl⟩ := ofTensor_surjective a
+ obtain ⟨U, rfl⟩ := ofTensor_surjective b
+ exact F.monotone ((ofTensor_le_iff T U).1 hab)
+
+/-- Evaluate a monotone real-valued semiring homomorphism on tensor representatives. -/
+noncomputable def toSpectralPoint (f : RestrictionClass k J →+* ℝ) (hf : Monotone f) :
+ SpectralPoint k J where
+ value T := ⟨f (ofTensor T), by simpa using hf (orderBounds.zero_le (ofTensor T))⟩
+ monotone h := hf ((ofTensor_le_iff _ _).2 h)
+ value_unit := NNReal.eq f.map_one
+ value_zero T hT := NNReal.eq (show f (ofTensor T) = 0 by rw [(ofTensor_eq_zero_iff T).2 hT, map_zero])
+ value_directSum T U := NNReal.eq (f.map_add (ofTensor T) (ofTensor U))
+ value_tensorProduct T U := NNReal.eq (f.map_mul (ofTensor T) (ofTensor U))
+
+@[simp] theorem coe_toSpectralPoint_value (f : RestrictionClass k J →+* ℝ) (hf : Monotone f)
+ (T : Tensor.{u,v,0} k J) : ((toSpectralPoint f hf).value T : ℝ) = f (ofTensor T) := rfl
+
+/-- The two descriptions of the tensor spectrum agree point by point. -/
+noncomputable def spectralPointEquiv :
+ SpectralPoint k J ≃ {f : RestrictionClass k J →+* ℝ // Monotone f} where
+ toFun F := ⟨ofSpectralPoint F, ofSpectralPoint_monotone F⟩
+ invFun f := toSpectralPoint f.val f.property
+ left_inv _ := rfl
+ right_inv f := by
+ apply Subtype.ext
+ apply RingHom.ext
+ intro a
+ obtain ⟨T, rfl⟩ := ofTensor_surjective a
+ rfl
+
+/-- One spectral point distinguishes every pair of distinct natural-number classes. -/
+theorem charZeroOfSpectralPoint (F : SpectralPoint k J) : CharZero (RestrictionClass k J) :=
+ (ofSpectralPoint F).charZero
+
+end WireTensor.RestrictionClass
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorSpectralComparison.lean b/lean/OAI/Computability/VPVNP/TensorSpectralComparison.lean
new file mode 100644
index 0000000000..9580899fcd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorSpectralComparison.lean
@@ -0,0 +1,48 @@
+import OAI.Computability.VPVNP.StarEmbedding
+import OAI.Computability.VPVNP.TensorFlatteningPoint
+import OAI.Computability.VPVNP.TensorRestrictionSpectrum
+import OAI.Computability.VPVNP.SpectralStrictComparison
+
+/-!
+# Strict spectral comparison for tensor restrictions
+
+Lemma 2.1 turns strict comparison at all spectral points into local linear
+maps on every tensor power. The same number of copies of the supply tensor
+works for every power. A flattening at a single party supplies the required
+natural-valued rank on mutual-restriction classes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+open RestrictionClass
+
+universe u v
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] [Nontrivial J]
+
+/-- One integer copy bound gives genuine local linear restrictions for all
+powers, whenever all spectral points strictly prefer the supply tensor. -/
+theorem tensor_strict_spectral_comparison
+ {X Y : Tensor.{u,v,0} k J} (hY : Y.coeff ≠ 0)
+ (h : ∀ F : SpectralPoint k J, F.value X < F.value Y) :
+ ∃ K : ℕ, 1 ≤ K ∧ ∀ m : ℕ,
+ Restricts (tensorProduct (diagonal (Fin K)) (tensorPowerFin m Y)) (tensorPowerFin m X) := by
+ let a := Classical.choice (inferInstance : Nonempty J)
+ let rank := flatteningRankHom (k := k) a
+ let : CharZero (RestrictionClass k J) := rank.charZero
+ have h' (F : RestrictionClass k J →+* ℝ) (hF : Monotone F) : F (ofTensor X) < F (ofTensor Y) :=
+ h (toSpectralPoint F hF)
+ obtain ⟨K, hK, hpow⟩ := Spectral.strict_spectral_comparison orderBounds rank (flatteningRankHom_monotone a)
+ (fun hy => hY ((ofTensor_eq_zero_iff Y).mp hy)) h'
+ refine ⟨K, hK, fun m => (ofTensor_le_iff _ _).mp ?_⟩
+ simpa only [ofTensor_tensorProduct, ofTensor_diagonal_fin, ofTensor_tensorPowerFin] using hpow m
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TensorUnitLaws.lean b/lean/OAI/Computability/VPVNP/TensorUnitLaws.lean
new file mode 100644
index 0000000000..66c2f0bcf1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TensorUnitLaws.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.WireTensor
+
+/-!
+# Tensor identities under mutual local restriction
+
+Regrouping or permuting tensor factors only relabels their local bases.
+The diagonal with empty bases represents zero under local restriction.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+
+namespace WireTensor
+
+variable {k : Type u} {J : Type v} [CommSemiring k] [Fintype J]
+
+/-- The simple tensor is the multiplicative unit up to local restriction. -/
+theorem tensorProduct_unit_mutual (T : Tensor.{u,v,0} k J) :
+ Restricts (tensorProduct T (unit.{u,v,0})) T ∧
+ Restricts T (tensorProduct T (unit.{u,v,0})) := by
+ apply restricts_of_reindex (fun j ↦ (Equiv.prodPUnit (T.Basis j)).symm)
+ intro x
+ exact (mul_one (T.coeff x)).symm
+
+/-- Reassociating three tensor factors preserves the local restriction class. -/
+theorem tensorProduct_assoc_mutual (T U V : Tensor.{u,v,0} k J) :
+ Restricts (tensorProduct (tensorProduct T U) V) (tensorProduct T (tensorProduct U V)) ∧
+ Restricts (tensorProduct T (tensorProduct U V)) (tensorProduct (tensorProduct T U) V) := by
+ apply restricts_of_reindex (fun j ↦ (Equiv.prodAssoc (T.Basis j) (U.Basis j) (V.Basis j)).symm)
+ intro x
+ exact (mul_assoc _ _ _).symm
+
+/-- Swapping the two factors preserves the local restriction class. -/
+theorem tensorProduct_comm_mutual (T U : Tensor.{u,v,0} k J) :
+ Restricts (tensorProduct T U) (tensorProduct U T) ∧
+ Restricts (tensorProduct U T) (tensorProduct T U) := by
+ apply restricts_of_reindex (fun j ↦ Equiv.prodComm (U.Basis j) (T.Basis j))
+ intro x
+ exact mul_comm _ _
+
+variable [Nonempty J]
+
+/-- The empty diagonal is the additive unit up to local restriction. -/
+theorem directSum_zero_mutual (T : Tensor.{u,v,0} k J) :
+ Restricts (directSum T (diagonal (Fin 0))) T ∧
+ Restricts T (directSum T (diagonal (Fin 0))) := by
+ apply restricts_of_reindex (fun j ↦ (Equiv.sumEmpty (T.Basis j) (Fin 0)).symm)
+ intro x
+ exact (directSum_coeff_inl T (diagonal (Fin 0)) x).symm
+
+/-- Every tensor restricts to the empty diagonal. -/
+theorem restricts_zero (T : Tensor.{u,v,0} k J) : Restricts T (diagonal (Fin 0)) := by
+ refine ⟨fun _ _ _ ↦ 0, ?_⟩
+ funext c
+ exact Fin.elim0 (c (Classical.choice ‹Nonempty J›))
+
+/-- The empty diagonal restricts exactly to tensors with zero coefficient array. -/
+theorem zero_restricts_iff (T : Tensor.{u,v,0} k J) :
+ Restricts (diagonal (Fin 0)) T ↔ T.coeff = 0 := by
+ constructor
+ · rintro ⟨L, hL⟩
+ rw [← hL]
+ funext x
+ simp [applyLocal, diagonal]
+ · intro hT
+ refine ⟨fun _ _ _ ↦ 0, ?_⟩
+ rw [hT]
+ funext x
+ simp [applyLocal, diagonal]
+
+/-- The tensor product with the empty diagonal has zero coefficient array. -/
+theorem tensorProduct_zero_mutual (T : Tensor.{u,v,0} k J) :
+ Restricts (tensorProduct T (diagonal (Fin 0))) (diagonal (Fin 0)) ∧
+ Restricts (diagonal (Fin 0)) (tensorProduct T (diagonal (Fin 0))) := by
+ refine ⟨restricts_zero _, (zero_restricts_iff _).2 ?_⟩
+ funext x
+ exact Fin.elim0 (x (Classical.choice ‹Nonempty J›)).2
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TerminalStarWitness.lean b/lean/OAI/Computability/VPVNP/TerminalStarWitness.lean
new file mode 100644
index 0000000000..66aee769a1
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TerminalStarWitness.lean
@@ -0,0 +1,134 @@
+import OAI.Computability.VPVNP.StarExtension
+import OAI.Computability.VPVNP.PlacedTensor
+import OAI.Computability.VPVNP.CubeStar
+import OAI.Computability.VPVNP.SplitWires
+import OAI.Computability.VPVNP.WireCATZero
+
+/-!
+# Extracting a tensor witness on equally wide terminals
+
+In (4.4), the height and the old tensor are chosen before the circuit
+lengths. The star width is the number of terminal legs at each party.
+Reindexing the profile witness gives one coefficient table on the
+terminals, with dimension `2 ^ b` at each of them and no other legs.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+variable {k : Type*} [Field k] {J R : Type} [Fintype J] [Fintype R]
+
+open scoped Classical in
+/-- The number of terminal legs grouped at the given party. -/
+noncomputable def terminalMultiplicity (p : R → J) (j : J) : ℕ :=
+ Fintype.card {r : R // p r = j}
+
+private def terminalFiberEquiv (p : R → J) (j : J) (D : Type) :
+ ((r : R) → j = p r → D) ≃ ({r : R // p r = j} → D) where
+ toFun z r := z r.val r.property.symm
+ invFun z r hr := z ⟨r, hr.symm⟩
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+theorem sum_terminalMultiplicity (p : R → J) (f : J → ℝ) :
+ ∑ j, (terminalMultiplicity p j : ℝ) * f j = ∑ r, f (p r) := by
+ classical
+ rw [← Fintype.sum_fiberwise p (fun r ↦ f (p r))]
+ apply Finset.sum_congr rfl
+ intro j _
+ have h (i : {r : R // p r = j}) : f (p i.val) = f j := congrArg f i.property
+ simp only [h, Finset.sum_const, Finset.card_univ, nsmul_eq_mul, terminalMultiplicity]
+
+namespace SpectralPoint
+
+variable (F : SpectralPoint k J)
+
+/-- Reindex the coordinates of a width-profile witness as one equal-sized
+leg per terminal. At a party with no terminal there is one coordinate. -/
+theorem starWitness_eq_placed (p : R → J) (W : StarWitness k (terminalMultiplicity p)) :
+ ∃ A : (R → Fin (2 ^ W.height)) → k, A ≠ 0 ∧
+ F.value (placedTensor p (fun _ ↦ Fin (2 ^ W.height)) A) = F.value W.tensor := by
+ classical
+ let D := Fin (2 ^ W.height)
+ let e (j : J) : ((r : R) → j = p r → D) ≃ Fin (2 ^ (W.height * terminalMultiplicity p j)) :=
+ (terminalFiberEquiv p j D).trans (Fintype.equivFinOfCardEq (by
+ rw [Fintype.card_fun, Fintype.card_fin, ← pow_mul]
+ rfl))
+ let regroup := placedAssignmentEquiv p (fun _ ↦ D)
+ let A (x : R → D) : k := W.coeff (fun j ↦ e j (regroup x j))
+ have hcoeff (x : (j : J) → (r : R) → j = p r → D) :
+ A (regroup.symm x) = W.coeff (fun j ↦ e j (x j)) := by
+ simp only [A, Equiv.apply_symm_apply]
+ refine ⟨A, ?_, (F.value_eq_of_mutual (restricts_of_reindex e hcoeff)).symm⟩
+ intro hz
+ apply W.nonzero
+ funext x
+ let y := fun j ↦ (e j).symm (x j)
+ have h := hcoeff y
+ rw [hz] at h
+ change (0 : k) = W.coeff (fun j ↦ e j ((e j).symm (x j))) at h
+ change W.coeff x = (0 : k)
+ simpa only [Equiv.apply_symm_apply] using h.symm
+
+/-- A strict lower bound valid for every extending center selects a concrete
+height and terminal coefficient table over the original field. -/
+theorem exists_terminalStar_witness [Nonempty J] (p : R → J) (threshold : ℝ)
+ (hlower : ∀ H : SpectralPoint k (Option J), (∀ T, H.value (embedOld T) = F.value T) →
+ threshold < ∑ r, H.wireDistance none (some (p r))) :
+ ∃ (b : ℕ) (_ : 0 < b) (A : (R → Fin (2 ^ b)) → k), A ≠ 0 ∧
+ threshold < Real.logb 2 (F.value (placedTensor p (fun _ ↦ Fin (2 ^ b)) A)) / b := by
+ obtain ⟨H, hExt, hEq⟩ := F.exists_starRate_extension (terminalMultiplicity p)
+ have hRate := hlower H hExt
+ rw [← sum_terminalMultiplicity p (fun j ↦ H.wireDistance none (some j)), hEq] at hRate
+ obtain ⟨v, ⟨W, rfl⟩, hlt, _⟩ := (F.starRate_isLUB _).exists_between hRate
+ obtain ⟨A, hA, heq⟩ := F.starWitness_eq_placed p W
+ exact ⟨W.height, W.positive, A, hA, heq ▸ hlt⟩
+
+open scoped symmDiff
+
+/-- Equation (4.4) from CAT(0) embeddings of the extending spectral points.
+The selected tensor has one explicit equal-sized basis at each marked
+singleton corner. The height and the table are independent of later powers. -/
+theorem exists_cubeStar_witness_of_embeddings [Nonempty J] {n : ℕ} (corner : Finset (Fin n) → J)
+ {σ ε : ℝ} (hσ : 0 < σ) (hε : 0 < ε)
+ (hcorner : ∀ A B, F.wireDistance (corner A) (corner B) ^ 2 = σ ^ 2 * (A ∆ B).card)
+ (embedding : ∀ H : SpectralPoint k (Option J), (∀ T, H.value (embedOld T) = F.value T) →
+ ∃ (X : Type) (_ : MetricSpace X) (_ : SpectralGeometry.HasCATZeroSegments X)
+ (e : Option J → X), ∀ a b, dist (e a) (e b) = H.wireDistance a b) :
+ ∃ (b : ℕ) (_ : 0 < b) (A : (Fin n → Fin (2 ^ b)) → k), A ≠ 0 ∧
+ SpectralGeometry.starLength n - ε <
+ Real.logb 2 (F.value (placedTensor (fun i ↦ corner {i}) (fun _ ↦ Fin (2 ^ b)) A)) /
+ (σ * b) := by
+ have hlower (H : SpectralPoint k (Option J)) (hH : ∀ T, H.value (embedOld T) = F.value T) :
+ σ * (SpectralGeometry.starLength n - ε) < ∑ i : Fin n, H.wireDistance none (some (corner {i})) := by
+ obtain ⟨X, hX, hcat, e, he⟩ := embedding H hH
+ let f (A : Finset (Fin n)) := e (some (corner A))
+ have hf (A B : Finset (Fin n)) : dist (f A) (f B) ^ 2 = σ ^ 2 * (A ∆ B).card := by
+ rw [show dist (f A) (f B) = _ from he _ _, F.wireDistance_extension H hH, hcorner]
+ have h := SpectralGeometry.cube_star_lower hcat f hσ.le hf (e none)
+ simp only [f, he] at h
+ exact (mul_lt_mul_of_pos_left (sub_lt_self _ hε) hσ).trans_le h
+ obtain ⟨b, hb, A, hA, hlt⟩ := F.exists_terminalStar_witness (fun i ↦ corner {i}) _ hlower
+ refine ⟨b, hb, A, hA, (lt_div_iff₀ (mul_pos hσ (Nat.cast_pos.mpr hb))).mpr ?_⟩
+ simpa only [mul_left_comm, mul_comm, mul_assoc] using (lt_div_iff₀ (Nat.cast_pos.mpr hb)).mp hlt
+
+/-- Equation (4.4) for a cube realized by a spectral wire metric. The
+CAT(0) completion of the attaining extension supplies the star bound. -/
+theorem exists_cubeStar_witness [Nonempty J] {n : ℕ} (corner : Finset (Fin n) → J)
+ {σ ε : ℝ} (hσ : 0 < σ) (hε : 0 < ε)
+ (hcorner : ∀ A B, F.wireDistance (corner A) (corner B) ^ 2 = σ ^ 2 * (A ∆ B).card) :
+ ∃ (b : ℕ) (_ : 0 < b) (A : (Fin n → Fin (2 ^ b)) → k), A ≠ 0 ∧
+ SpectralGeometry.starLength n - ε <
+ Real.logb 2 (F.value (placedTensor (fun i ↦ corner {i}) (fun _ ↦ Fin (2 ^ b)) A)) /
+ (σ * b) :=
+ F.exists_cubeStar_witness_of_embeddings corner hσ hε hcorner (fun H _ ↦ H.catZero_embedding)
+
+end SpectralPoint
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TwoMarkedSplit.lean b/lean/OAI/Computability/VPVNP/TwoMarkedSplit.lean
new file mode 100644
index 0000000000..9ebf70d05f
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TwoMarkedSplit.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.TwoMarkedTransport
+import OAI.Computability.VPVNP.ExteriorLevels
+
+/-!
+# Tensor nodes in the endpoint-coupling split
+
+Appendix A.3 splits the first marked index while retaining the second.
+The exterior column and row become background indices at the fixed endpoints,
+so that a child is again a two-marked table with both marks free to move.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+open scoped Classical
+open ExteriorLevels Lemmata.FockCircuits
+
+universe u v
+
+/-- A coefficient table with two movable indices and a finite background
+basis at each party. The background may grow at successive splits. -/
+structure TwoMarkedNode (k : Type u) (J : Type v) (I K : Type) where
+ /-- Finite background basis at each party, separate from the two movable indices of the node. -/
+ Basis : J → Type
+ finiteBasis : ∀ j, Fintype (Basis j)
+ /-- Tensor coefficients indexed by a background basis assignment and the two independently
+ marked indices. -/
+ coeff : ((j : J) → Basis j) → I → K → k
+
+attribute [instance] TwoMarkedNode.finiteBasis
+
+namespace TwoMarkedNode
+
+variable {k : Type u} {J : Type v} {I K : Type} [Fintype I] [Fintype K]
+
+/-- Place the two indices without moving any background index. -/
+noncomputable def place (W : TwoMarkedNode k J I K) (a b : J) : Tensor k J :=
+ twoMarked W.Basis I K W.coeff a b
+
+/-- The root table is the identity on a pair of marked indices. -/
+noncomputable def wire [Zero k] [One k] (q : ℕ) : TwoMarkedNode k J (Fin q) (Fin q) where
+ Basis _ := Unit
+ finiteBasis _ := inferInstance
+ coeff _ i j := @ite k (i = j) (Classical.propDecidable _) 1 0
+
+/-- Contract the old first index against the last argument of the operator.
+Its column lives at `a₀`, its row at `a₁`, and the new first index can be
+placed anywhere. -/
+noncomputable def child [CommSemiring k] (W : TwoMarkedNode k J I K) (a₀ a₁ : J)
+ {H : Type} [Fintype H] (operator : H → H → I → I → k) : TwoMarkedNode k J I K where
+ Basis j := W.Basis j × (j = a₀ → H) × (j = a₁ → H)
+ finiteBasis _ := inferInstance
+ coeff x i l := ∑ j, W.coeff (fun p => (x p).1) j l *
+ operator ((x a₁).2.2 rfl) ((x a₀).2.1 rfl) i j
+
+/-- `true` chooses contraction after creation. The intermediate level is
+one higher on that branch and one lower on the `false` branch. -/
+noncomputable def exteriorOperator [CommRing k] {q : ℕ} (b : ℕ) (branch : Bool)
+ (β α : Level q b) (i j : Fin q) : k :=
+ if branch then
+ ∑ γ : Level q (b+1), entry k (Fock.contract k j) β γ * entry k (Fock.create k i) γ α
+ else
+ ∑ γ : Level q (b-1), entry k (Fock.create k i) β γ * entry k (Fock.contract k j) γ α
+
+/-- One exterior split in the binary tree of Appendix A.3. -/
+noncomputable def exteriorChild [CommRing k] {q : ℕ} (W : TwoMarkedNode k J (Fin q) K)
+ (a₀ a₁ : J) (b : ℕ) (branch : Bool) : TwoMarkedNode k J (Fin q) K :=
+ W.child a₀ a₁ (exteriorOperator b branch)
+
+variable [Fintype J] [Field k]
+
+theorem value_wire (F : SpectralPoint k J) (q : ℕ) (a b : J) :
+ F.value ((wire q).place a b) = F.value (WireTensor.wire a b (Fin q)) :=
+ F.value_eq_of_mutual (twoMarked_wire_mutual (k := k) (Fin q) a b)
+
+/-- At each placement the sum of the two child arrays represents the parent
+times the identity wire on the exterior level. -/
+theorem value_exterior_split {q : ℕ} (F : SpectralPoint k J) (W : TwoMarkedNode k J (Fin q) K)
+ (a₀ a₁ x y : J) (b : ℕ) :
+ F.value (W.place x y) * F.value (WireTensor.wire a₀ a₁ (Level q b)) ≤
+ F.value ((W.exteriorChild a₀ a₁ b true).place x y) +
+ F.value ((W.exteriorChild a₀ a₁ b false).place x y) := by
+ let P := (W.exteriorChild a₀ a₁ b true).place x y
+ let M := (W.exteriorChild a₀ a₁ b false).place x y
+ let Z := Tensor.mk P.Basis P.finiteBasis (fun z => P.coeff z + M.coeff z)
+ let U := tensorProduct (W.place x y) (WireTensor.wire a₀ a₁ (Level q b))
+ let e (j : J) : Z.Basis j ≃ U.Basis j :=
+ { toFun z := ((z.1.1, z.2), z.1.2)
+ invFun z := ((z.1.1, z.2), z.1.2)
+ left_inv _ := rfl
+ right_inv _ := rfl }
+ have h : Restricts U Z ∧ Restricts Z U := by
+ apply restricts_of_reindex e
+ intro z
+ let α := (z a₀).1.2.1 rfl
+ let β := (z a₁).1.2.2 rfl
+ let i := (z x).2.1 rfl
+ let t (j : Fin q) := W.coeff (fun p => (z p).1.1) j ((z y).2.2 rfl)
+ change (∑ j, t j * exteriorOperator b true β α i j) +
+ (∑ j, t j * exteriorOperator b false β α i j) =
+ t i * (@ite k (α = β) (Classical.propDecidable _) 1 0)
+ simp only [exteriorOperator, ↓reduceIte, Bool.false_eq_true]
+ rw [matrix_car_apply]
+ by_cases h : α = β <;> simp [h, eq_comm]
+ rw [← F.value_tensorProduct, F.value_eq_of_mutual h]
+ exact F.value_add_le (B := P.Basis) P.coeff M.coeff
+
+end TwoMarkedNode
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TwoMarkedSplitBounds.lean b/lean/OAI/Computability/VPVNP/TwoMarkedSplitBounds.lean
new file mode 100644
index 0000000000..61d54445a8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TwoMarkedSplitBounds.lean
@@ -0,0 +1,120 @@
+import OAI.Computability.VPVNP.MarkedEndpointOperation
+import OAI.Computability.VPVNP.MarkedSplitBound
+
+/-!
+# Endpoint estimates for the children of an exterior split
+
+The second marked index is held in the background when applying the local
+operations of Appendix A.2 to a child from Appendix A.3.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor.TwoMarkedNode
+
+open scoped Classical
+open ExteriorLevels Lemmata.FockCircuits
+
+universe u v
+variable {k : Type u} {J : Type v} [Field k] [Fintype J]
+variable {I K H : Type} [Fintype I] [Fintype K] [Fintype H]
+
+/-- Regroup the second marked index with the background so that the child
+has precisely the three movable roles used in the one-mark exterior split. -/
+theorem child_splitMarkedTerm_mutual (W : TwoMarkedNode k J I K) (s p x y : J)
+ (op : H → H → I → I → k) :
+ let P := (W.child s p op).place x y
+ let V := splitMarkedTerm (fun j => W.Basis j × (j = y → K)) I H x s p
+ (holdSecond W.Basis I K W.coeff y) (fun i j β α => op β α i j)
+ Restricts P V ∧ Restricts V P := by
+ let P := (W.child s p op).place x y
+ let V := splitMarkedTerm (fun j => W.Basis j × (j = y → K)) I H x s p
+ (holdSecond W.Basis I K W.coeff y) (fun i j β α => op β α i j)
+ let e (j : J) : V.Basis j ≃ P.Basis j :=
+ { toFun z := ((z.1.1, z.2 (some false), z.2 (some true)), z.2 none, z.1.2)
+ invFun z := ((z.1.1, z.2.2), fun r => match r with
+ | none => z.2.1
+ | some false => z.1.2.1
+ | some true => z.1.2.2)
+ right_inv _ := rfl
+ left_inv z := by
+ refine Prod.ext ?_ ?_
+ · rfl
+ funext r
+ rcases r with _ | (_ | _) <;> rfl }
+ exact restricts_of_reindex e (fun _ => rfl)
+
+/-- The ordinary endpoint bound uses the exterior level itself as the
+identity wire for either child. -/
+theorem value_exteriorChild_same_le {q : ℕ} (W : TwoMarkedNode k J (Fin q) K)
+ (F : SpectralPoint k J) (A B : Bool → J) (b : ℕ) (hbq : b < q) (s i j : Bool) :
+ (F.value ((W.exteriorChild (A false) (A true) b s).place (A i) (B j)) : ℝ) ≤
+ (q.choose b : ℝ) ^ F.wireDistance (A false) (A true) *
+ (F.value (W.place (A i) (B j)) : ℝ) := by
+ have hi : A i = A false ∨ A i = A true := by cases i <;> simp
+ have hH : 0 < Fintype.card (Level q b) := by
+ rw [card_level]
+ exact Nat.choose_pos hbq.le
+ simpa only [exteriorChild, card_level, mul_comm] using
+ W.value_child_same_le (exteriorOperator b s) F (A false) (A true) (A i) (B j) hi hH
+
+private theorem level_nonempty {q b : ℕ} (h : b ≤ q) : Nonempty (Level q b) :=
+ Fintype.card_pos_iff.mp (by simpa only [card_level] using Nat.choose_pos h)
+
+/-- At the column endpoint the positive branch is supplied from the row
+endpoint through the level one degree higher. -/
+theorem value_exteriorChild_plus_le {q : ℕ} (W : TwoMarkedNode k J (Fin q) K)
+ (F : SpectralPoint k J) (A B : Bool → J) (b : ℕ) (hbq : b < q) (j : Bool) :
+ (F.value ((W.exteriorChild (A false) (A true) b true).place (A false) (B j)) : ℝ) ≤
+ (q.choose (b+1) : ℝ) ^ F.wireDistance (A false) (A true) *
+ (F.value (W.place (A true) (B j)) : ℝ) := by
+ have : Nonempty (Fin q) := ⟨⟨0, by omega⟩⟩
+ have : Nonempty (Level q b) := level_nonempty hbq.le
+ have : Nonempty (Level q (b+1)) := level_nonempty hbq
+ let op := exteriorOperator (k := k) (q := q) b true
+ have hc := F.value_eq_of_mutual (W.child_splitMarkedTerm_mutual (A false) (A true)
+ (A false) (B j) op)
+ have hp := F.value_eq_of_mutual (twoMarked_first_mutual W.Basis (Fin q) K W.coeff (A true) (B j))
+ change (F.value ((W.child (A false) (A true) op).place (A false) (B j)) : ℝ) ≤
+ _ * (F.value (twoMarked W.Basis (Fin q) K W.coeff (A true) (B j)) : ℝ)
+ rw [hc, hp]
+ have h := F.value_splitMarkedTerm_le_plus (fun p => W.Basis p × (p = B j → K))
+ (Fin q) (Level q b) (Level q (b+1)) (A false) (A false) (A true) (A true)
+ (holdSecond W.Basis (Fin q) K W.coeff (B j)) (fun i l β α => op β α i l)
+ (fun i α z => entry k (Fock.create k i) z α)
+ (fun l β z => entry k (Fock.contract k l) β z)
+ (fun _ _ _ _ => by simp [op, exteriorOperator, mul_comm])
+ simpa only [card_level, F.wireDistance_self, Real.rpow_zero, one_mul, mul_comm] using h
+
+/-- At the row endpoint the negative branch is supplied from the column
+endpoint through the level one degree lower. -/
+theorem value_exteriorChild_minus_le {q : ℕ} (W : TwoMarkedNode k J (Fin q) K)
+ (F : SpectralPoint k J) (A B : Bool → J) (b : ℕ) (hbq : b < q) (j : Bool) :
+ (F.value ((W.exteriorChild (A false) (A true) b false).place (A true) (B j)) : ℝ) ≤
+ (q.choose (b-1) : ℝ) ^ F.wireDistance (A false) (A true) *
+ (F.value (W.place (A false) (B j)) : ℝ) := by
+ have : Nonempty (Fin q) := ⟨⟨0, by omega⟩⟩
+ have : Nonempty (Level q b) := level_nonempty hbq.le
+ have : Nonempty (Level q (b-1)) := level_nonempty (by omega)
+ let op := exteriorOperator (k := k) (q := q) b false
+ have hc := F.value_eq_of_mutual (W.child_splitMarkedTerm_mutual (A false) (A true)
+ (A true) (B j) op)
+ have hp := F.value_eq_of_mutual (twoMarked_first_mutual W.Basis (Fin q) K W.coeff (A false) (B j))
+ change (F.value ((W.child (A false) (A true) op).place (A true) (B j)) : ℝ) ≤
+ _ * (F.value (twoMarked W.Basis (Fin q) K W.coeff (A false) (B j)) : ℝ)
+ rw [hc, hp]
+ have h := F.value_splitMarkedTerm_le_minus (fun p => W.Basis p × (p = B j → K))
+ (Fin q) (Level q b) (Level q (b-1)) (A true) (A false) (A true) (A false)
+ (holdSecond W.Basis (Fin q) K W.coeff (B j)) (fun i l β α => op β α i l)
+ (fun l α z => entry k (Fock.contract k l) z α)
+ (fun i β z => entry k (Fock.create k i) β z)
+ (fun _ _ _ _ => by simp [op, exteriorOperator, mul_comm])
+ simpa only [card_level, F.wireDistance_self, Real.rpow_zero, one_mul, mul_comm] using h
+
+end WireTensor.TwoMarkedNode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/TwoMarkedTransport.lean b/lean/OAI/Computability/VPVNP/TwoMarkedTransport.lean
new file mode 100644
index 0000000000..f82ff215d0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/TwoMarkedTransport.lean
@@ -0,0 +1,124 @@
+import OAI.Computability.VPVNP.MarkedRelocation
+import OAI.Computability.VPVNP.SpectralGeometry
+
+/-!
+# Transporting two marked tensor indices
+
+The two marked factors in Appendix A.3 may be placed at coincident parties.
+To relocate one of them, keep the other as part of the background basis.
+The two regroupings preserve every coefficient.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor
+
+open scoped Classical
+
+universe u v
+variable {k : Type u} {J : Type v} (B : J → Type) [∀ j, Fintype (B j)]
+ (I K : Type) [Fintype I] [Fintype K]
+ (T : ((j : J) → B j) → I → K → k)
+
+/-- An array with a marked row at `a` and a marked column at `b`. -/
+noncomputable def twoMarked (a b : J) : Tensor k J where
+ Basis j := B j × (j = a → I) × (j = b → K)
+ finiteBasis _ := inferInstance
+ coeff x := T (fun j ↦ (x j).1) ((x a).2.1 rfl) ((x b).2.2 rfl)
+
+/-- View the second marked leg as part of the background. -/
+def holdSecond (b : J) (x : (j : J) → B j × (j = b → K)) (i : I) : k :=
+ T (fun j ↦ (x j).1) i ((x b).2 rfl)
+
+/-- View the first marked leg as part of the background. -/
+def holdFirst (a : J) (x : (j : J) → B j × (j = a → I)) (j : K) : k :=
+ T (fun t ↦ (x t).1) ((x a).2 rfl) j
+
+theorem twoMarked_coeff_eq_zero_iff [Zero k] (a b : J) :
+ (twoMarked B I K T a b).coeff = 0 ↔ T = 0 := by
+ constructor
+ · intro h
+ funext x i j
+ exact congrFun h (fun t ↦ (x t, fun _ ↦ i, fun _ ↦ j))
+ · intro h
+ subst T
+ rfl
+
+variable [Fintype J] [Field k]
+
+theorem twoMarked_first_mutual (a b : J) :
+ let P := twoMarked B I K T a b
+ let U := marked (fun j ↦ B j × (j = b → K)) I a (holdSecond B I K T b)
+ Restricts P U ∧ Restricts U P := by
+ let e (j : J) : (B j × (j = b → K)) × (j = a → I) ≃ B j × (j = a → I) × (j = b → K) :=
+ { toFun x := (x.1.1, x.2, x.1.2)
+ invFun x := ((x.1, x.2.2), x.2.1)
+ left_inv _ := rfl
+ right_inv _ := rfl }
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+theorem twoMarked_second_mutual (a b : J) :
+ let P := twoMarked B I K T a b
+ let U := marked (fun j ↦ B j × (j = a → I)) K b (holdFirst B I K T a)
+ Restricts P U ∧ Restricts U P := by
+ exact restricts_of_reindex
+ (fun j ↦ Equiv.prodAssoc (B j) (j = a → I) (j = b → K)) (fun _ ↦ rfl)
+
+/-- With trivial background and the identity coefficient table, the two
+marked legs give the equality wire at their chosen parties. -/
+theorem twoMarked_wire_mutual (a b : J) :
+ let W := twoMarked (fun _ : J ↦ Unit) I I (fun _ i j ↦ if i = j then (1 : k) else 0) a b
+ Restricts W (wire a b I) ∧ Restricts (wire a b I) W := by
+ let e (j : J) : (j = a → I) × (j = b → I) ≃ Unit × (j = a → I) × (j = b → I) :=
+ { toFun x := ((), x)
+ invFun x := x.2
+ left_inv _ := rfl
+ right_inv _ := rfl }
+ exact restricts_of_reindex e (fun _ ↦ rfl)
+
+/-- Combining first-index and second-index relocation bounds gives the four
+independent endpoint weights of (A.4). -/
+theorem twoMarked_independent_bound (F : SpectralPoint k J)
+ (a b : Bool → J) (c d : J) {u v : ℝ} (hu : 0 ≤ u ∧ u ≤ 1) (hv : 0 ≤ v ∧ v ≤ 1)
+ (first : (F.value (twoMarked B I K T c d) : ℝ) ≤
+ (F.value (twoMarked B I K T (a false) d) : ℝ) ^ (1-u) *
+ (F.value (twoMarked B I K T (a true) d) : ℝ) ^ u)
+ (second : ∀ i, (F.value (twoMarked B I K T (a i) d) : ℝ) ≤
+ (F.value (twoMarked B I K T (a i) (b false)) : ℝ) ^ (1-v) *
+ (F.value (twoMarked B I K T (a i) (b true)) : ℝ) ^ v) :
+ (F.value (twoMarked B I K T c d) : ℝ) ≤ ∏ i : Bool, ∏ j : Bool,
+ (F.value (twoMarked B I K T (a i) (b j)) : ℝ) ^
+ ((SpectralGeometry.independentCoupling hu hv).mass i j) := by
+ have h₀ := Real.rpow_le_rpow (by positivity) (second false) (sub_nonneg.mpr hu.2)
+ have h₁ := Real.rpow_le_rpow (by positivity) (second true) hu.1
+ have h := first.trans (mul_le_mul h₀ h₁ (by positivity) (by positivity))
+ rw [Real.mul_rpow (by positivity) (by positivity), Real.mul_rpow (by positivity) (by positivity),
+ ← Real.rpow_mul (by positivity), ← Real.rpow_mul (by positivity),
+ ← Real.rpow_mul (by positivity), ← Real.rpow_mul (by positivity)] at h
+ simp only [Fintype.prod_bool, SpectralGeometry.independentCoupling, Bool.false_eq_true,
+ ↓reduceIte]
+ simpa only [mul_comm, mul_assoc, mul_left_comm] using h
+
+/-- Equation (A.4). Relocation of each mark bounds the value at the two
+fractional points by the independent product of all four endpoint values. -/
+theorem SpectralPoint.value_twoMarked_atFraction_le (F : SpectralPoint k J)
+ (a b : Bool → J) (c d : J) {u v : ℝ} (hu : 0 ≤ u ∧ u ≤ 1) (hv : 0 ≤ v ∧ v ≤ 1)
+ (hc : @WireGeometry.AtFraction _ F.wirePseudoMetric (a false) (a true) u c)
+ (hd : @WireGeometry.AtFraction _ F.wirePseudoMetric (b false) (b true) v d) :
+ (F.value (twoMarked B I K T c d) : ℝ) ≤ ∏ i : Bool, ∏ j : Bool,
+ (F.value (twoMarked B I K T (a i) (b j)) : ℝ) ^
+ ((SpectralGeometry.independentCoupling hu hv).mass i j) := by
+ apply twoMarked_independent_bound B I K T F a b c d hu hv
+ · simp only [F.value_eq_of_mutual (twoMarked_first_mutual B I K T _ d)]
+ exact F.value_marked_atFraction_le _ I _ _ _ _ hu.1 hu.2 hc
+ · intro i
+ simp only [F.value_eq_of_mutual (twoMarked_second_mutual B I K T (a i) _)]
+ exact F.value_marked_atFraction_le _ K _ _ _ _ hv.1 hv.2 hd
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/UniformLinearSampling.lean b/lean/OAI/Computability/VPVNP/UniformLinearSampling.lean
new file mode 100644
index 0000000000..61b2906fd8
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/UniformLinearSampling.lean
@@ -0,0 +1,69 @@
+import Mathlib.Algebra.BigOperators.Group.Finset.Sigma
+import Mathlib.Algebra.BigOperators.Ring.Finset
+import Mathlib.Algebra.Group.Equiv.Basic
+import Mathlib.Basic.Real.Basic
+import Mathlib.LinearAlgebra.Basis.VectorSpace
+
+/-!
+# Uniform sampling through a surjective additive map
+
+In Section 5.2, evaluation of a random linear map on a frame is a surjective
+additive homomorphism. Translation invariance of finite group averages shows
+that its image is uniformly distributed, including for simultaneous evaluation
+on a frame spanning the two adjacent planes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+/-- A surjective additive homomorphism carries the uniform distribution of the
+finite domain to the uniform distribution of the codomain. -/
+theorem uniformAverage_comp_surjective {A B : Type*} [AddGroup A] [AddGroup B]
+ [Fintype A] [Fintype B] (f : A →+ B) (hf : Function.Surjective f) (g : B → ℝ) :
+ (∑ a : A, g (f a)) / Fintype.card A = (∑ b : B, g b) / Fintype.card B := by
+ have ha (b : B) : (∑ a : A, g (f a + b)) = ∑ a : A, g (f a) := by
+ obtain ⟨t, rfl⟩ := hf b
+ simp_rw [← map_add]
+ exact Equiv.sum_comp (Equiv.addRight t) (fun a : A ↦ g (f a))
+ have hb (a : A) : (∑ b : B, g (f a + b)) = ∑ b : B, g b :=
+ Equiv.sum_comp (Equiv.addLeft (f a)) g
+ apply (div_eq_div_iff (Nat.cast_ne_zero.mpr Fintype.card_ne_zero)
+ (Nat.cast_ne_zero.mpr Fintype.card_ne_zero)).2
+ calc
+ _ = ∑ b : B, ∑ a : A, g (f a + b) := by simp_rw [ha]; simp [mul_comm]
+ _ = ∑ a : A, ∑ b : B, g (f a + b) := Finset.sum_comm
+ _ = _ := by simp_rw [hb]; simp [mul_comm]
+
+variable {K V E ι : Type*} [Field K] [AddCommGroup V] [Module K V]
+ [AddCommGroup E] [Module K E]
+
+/-- Independent columns can be assigned arbitrary values by a linear map. -/
+theorem frame_eval_surjective (w : ι → V) (hw : LinearIndependent K w) :
+ Function.Surjective (fun (f : V →ₗ[K] E) (j : ι) ↦ f (w j)) := by
+ obtain ⟨r, hr⟩ := (Finsupp.linearCombination K w).exists_leftInverse_of_injective
+ (linearIndependent_iff_ker.mp hw)
+ intro z
+ refine ⟨(Finsupp.linearCombination K z).comp r, ?_⟩
+ funext j
+ have h := LinearMap.congr_fun hr (Finsupp.single j 1)
+ simp only [LinearMap.comp_apply, Finsupp.linearCombination_single, one_smul,
+ LinearMap.id_coe, id_eq] at h
+ simp only [LinearMap.comp_apply, h, Finsupp.linearCombination_single, one_smul]
+
+/-- The joint images of any independent frame under a uniform linear map
+have the uniform distribution on all tuples of target values. -/
+theorem uniformAverage_frame_eval [Fintype ι] [DecidableEq ι] [Fintype E] [Fintype (V →ₗ[K] E)]
+ (w : ι → V) (hw : LinearIndependent K w) (g : (ι → E) → ℝ) :
+ (∑ f : V →ₗ[K] E, g (fun j ↦ f (w j))) / Fintype.card (V →ₗ[K] E) =
+ (∑ z : ι → E, g z) / Fintype.card (ι → E) := by
+ let f := LinearMap.pi (fun j ↦ LinearMap.applyₗ (R := K) (M₂ := E) (w j))
+ exact uniformAverage_comp_surjective f.toAddMonoidHom (frame_eval_surjective w hw) g
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/UniversalCountAdvice.lean b/lean/OAI/Computability/VPVNP/UniversalCountAdvice.lean
new file mode 100644
index 0000000000..7889150d57
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/UniversalCountAdvice.lean
@@ -0,0 +1,57 @@
+import OAI.Computability.VPVNP.AdviceCircuitCompiler
+import OAI.Computability.VPVNP.UniversalCountStackBounds
+import OAI.Computability.VPVNP.VerifierMachine
+
+/-!
+# The circuit advice for the integer coefficient of the paired family
+
+The same advice program verifies every input and candidate path of a given
+length. It simulates the decoded machine on the full input, including its own
+prefix, using the canonical zero-padded choices. The deterministic enumeration
+thus computes the integer coefficient before reduction into any field.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalCountStack
+
+open RAMTape TapeWord VerifierMachine
+
+/-- The gate instructions for checking a canonical path of the universal machine on an input of
+length n, shared by every input and candidate path of that length. -/
+noncomputable def verifierProgram (n : ℕ) := AdviceCircuit.compile (verifierCircuit n)
+
+theorem verifierProgram_run {n : ℕ} (x : Fin n → Bool) (bits : Fin (n^clockExponent) → Bool) :
+ ∃ tail, AdviceCircuit.run (verifierProgram n) (AdviceCircuit.inputs x bits) =
+ some (verifiesInput x bits :: tail) := by
+ simpa only [verifierProgram, verifierCircuit_eval] using
+ AdviceCircuit.compile_run (verifierCircuit n) x bits
+
+theorem verifierProgram_advice_polynomial :
+ PolynomiallyBounded (fun n => (AdviceCircuit.encode (verifierProgram n)).length) := by
+ have hs := verifierSize_polynomiallyBounded
+ have hsum := (((hs.add .id).add (PolynomiallyBounded.id.pow clockExponent)).add (.const 2))
+ exact ((hs.add (.const 2)).mul (((PolynomiallyBounded.const 2).mul hsum).add (.const 3))).of_le
+ (fun n => AdviceCircuit.compile_size (verifierCircuit n))
+
+/-- The raw integer count fits even when every path branches and accepts. -/
+theorem acceptingCount_le {n : ℕ} (x : Fin n → Bool) : acceptingCount x ≤ 2^(n^clockExponent) := by
+ rw [acceptingCount_eq_card_witnesses]
+ simpa using Finset.card_le_card (Finset.filter_subset _ (Finset.univ : Finset (Fin (n^clockExponent) → Bool)))
+
+/-- Reading the final stack as a natural number retains the entire path count. -/
+theorem count_digits_value {n : ℕ} (x : Fin n → Bool) :
+ value (digits (n^clockExponent + 1) (acceptingCount x)) = acceptingCount x := by
+ rw [value_digits, Nat.mod_eq_of_lt]
+ have := acceptingCount_le x
+ rw [pow_succ]
+ have : 0 < 2^(n^clockExponent) := pow_pos (by decide) _
+ omega
+
+end UniversalCountStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/UniversalCountQuery.lean b/lean/OAI/Computability/VPVNP/UniversalCountQuery.lean
new file mode 100644
index 0000000000..dc7b2e3788
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/UniversalCountQuery.lean
@@ -0,0 +1,115 @@
+import OAI.Computability.VPVNP.UniversalCountAdvice
+import OAI.Computability.VPVNP.AdviceCountAdapter
+
+/-!
+# Executable coefficient queries for the universal path-count family
+
+The coefficient query uses one fixed finite bit-stack control for all lengths.
+Its only circuit-specific input is the unary-addressed gate stream. The final
+binary count includes all and only accepting canonical choices. Both its width
+and the maximum height of every intermediate stack are polynomial in the
+length for the concrete coefficient verifier.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalCountStack
+
+open RAMTape VerifierMachine
+open AdviceCountAdapter (AuxPort verify)
+
+/-- A fixed stack routine that enumerates all witnesses of the advised Boolean circuit and
+returns their accepting count in binary. -/
+abbrev countCircuit := enumerate verify.body
+
+variable {u w g : ℕ}
+
+/-- Instruction budget per candidate witness, including the ripple counters. -/
+def perChoice (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) g) : ℕ :=
+ 32 * ((AdviceCircuit.encode (AdviceCircuit.compile c)).length + (AdviceCircuit.compile c).length +
+ u + w + 1) + 8*w + 9
+
+/-- Space per stack, measured at every instruction of the full count. -/
+def stackLimit (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) g) : ℕ :=
+ max (max u (AdviceCircuit.encode (AdviceCircuit.compile c)).length) (w+1) + perChoice c
+
+/-- Install the advice and query, leaving the verifier's work ports empty. -/
+def scalarInputs (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) g) (x : Fin u → Bool) : Stacks AuxPort :=
+ AdviceCountAdapter.inputs (List.ofFn x) (AdviceCircuit.encode (AdviceCircuit.compile c))
+
+/-- One uniform machine counts satisfying witnesses of any topologically ordered
+Boolean circuit supplied on its advice port. Its control and number of stacks
+are independent of all circuit parameters. -/
+theorem countCircuit_runs (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) g) (x : Fin u → Bool) :
+ ∃ t ≤ 2^w * perChoice c, SpaceRun countCircuit.standalone (stackLimit c) t
+ (some countCircuit.entry) (bank (scalarInputs c x) (digits w 0) (digits (w+1) 0) [] []) none
+ (bank (scalarInputs c x) (digits w 0) (digits (w+1) (∑ bits, (c.eval (Sum.elim x bits)).toNat)) [] []) := by
+ let p := AdviceCircuit.compile c
+ let a := AdviceCircuit.encode p
+ let B := 32 * (a.length + p.length + u + w + 1)
+ apply enumerate_runs (B := B) (A := max u a.length)
+ · intro k
+ cases k with
+ | query => change (List.ofFn x).length ≤ max u a.length; simp
+ | advice => exact le_max_right ..
+ | vmStream | vmValues | vmScratch | vmResult | copyTmp => exact Nat.zero_le _
+ · intro bits count _
+ obtain ⟨tail, h⟩ := AdviceCircuit.compile_run c x bits
+ obtain ⟨t, ht, hr⟩ := AdviceCountAdapter.verify_runs p (List.ofFn x) (List.ofFn bits) count h
+ exact ⟨t, by simpa only [B, a, List.length_ofFn] using ht, hr⟩
+
+private theorem sum_verifier_eval {n : ℕ} (x : Fin n → Bool) :
+ (∑ bits, ((verifierCircuit n).eval (Sum.elim x bits)).toNat) = acceptingCount x := by
+ have h := acceptingCount_eq_sum_witnesses (R := ℕ) x
+ simp only [Nat.cast_id] at h
+ rw [h]
+ refine Finset.sum_congr rfl fun bits _ => ?_
+ rw [verifierCircuit_eval]
+ cases verifiesInput x bits <;> rfl
+
+/-- The §8.1 constant-term oracle for the polynomial family (1.1), including
+malformed input prefixes and early accepting halts. No interpreter assumptions
+are required. The exact integer output is read by `count_digits_value`. -/
+theorem coefficient_query_runs {n : ℕ} (x : Fin n → Bool) :
+ ∃ t ≤ 2^(n^clockExponent) * perChoice (verifierCircuit n),
+ SpaceRun countCircuit.standalone (stackLimit (verifierCircuit n)) t (some countCircuit.entry)
+ (bank (scalarInputs (verifierCircuit n) x) (digits (n^clockExponent) 0)
+ (digits (n^clockExponent+1) 0) [] []) none
+ (bank (scalarInputs (verifierCircuit n) x) (digits (n^clockExponent) 0)
+ (digits (n^clockExponent+1) (acceptingCount x)) [] []) := by
+ simpa only [sum_verifier_eval] using countCircuit_runs (verifierCircuit n) x
+
+private theorem perChoice_polynomial :
+ PolynomiallyBounded (fun n => perChoice (verifierCircuit n)) := by
+ have hsize := verifierProgram_advice_polynomial
+ have ht := PolynomiallyBounded.id.pow clockExponent
+ have hp := verifierSize_polynomiallyBounded.add (.const 2)
+ simp only [perChoice, AdviceCircuit.compile_length]
+ exact (((PolynomiallyBounded.const 32).mul
+ ((((hsize.add hp).add .id).add ht).add (.const 1))).add ((PolynomiallyBounded.const 8).mul ht)).add (.const 9)
+
+/-- The entire physical bit-stack bank uses polynomial space, since the
+program has a fixed finite number of ports. -/
+theorem coefficient_query_space :
+ PolynomiallyBounded (fun n => stackLimit (verifierCircuit n)) := by
+ have ht := PolynomiallyBounded.id.pow clockExponent
+ have hsize := verifierProgram_advice_polynomial
+ refine ((((PolynomiallyBounded.id.add hsize).add (ht.add (.const 1))).add perChoice_polynomial)).of_le ?_
+ intro n
+ dsimp only [stackLimit, verifierProgram]
+ omega
+
+/-- A single polynomial exponent bounds the entire running time over all query words. -/
+theorem coefficient_query_time : ∃ e : ℕ → ℕ, PolynomiallyBounded e ∧ ∀ n,
+ 2^(n^clockExponent) * perChoice (verifierCircuit n) ≤ 2^(e n) := by
+ refine ⟨_, (PolynomiallyBounded.id.pow clockExponent).add perChoice_polynomial, fun n => ?_⟩
+ rw [pow_add]
+ exact Nat.mul_le_mul_left _ (Nat.lt_pow_self (by decide : 1 < 2)).le
+
+end UniversalCountStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/UniversalCountStack.lean b/lean/OAI/Computability/VPVNP/UniversalCountStack.lean
new file mode 100644
index 0000000000..f452b09ff0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/UniversalCountStack.lean
@@ -0,0 +1,175 @@
+import OAI.Computability.VPVNP.RAMTapeUnaryWordValue
+import OAI.Computability.VPVNP.StructuredStackLink
+import Mathlib.Tactic.DeriveFintype
+
+/-!
+# Deterministic enumeration of fixed-length Boolean witnesses
+
+Section 8.1 queries an integer coefficient by counting all canonical witnesses.
+Two little-endian counters hold the current witness and the number accepted.
+The control invokes a verifier, adds its one-bit result to the count, and
+increments the witness. Overflow of the witness counter ends the enumeration,
+including the case of a zero-bit witness.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalCountStack
+
+open RAMTape TapeWord RAMTape.UnaryWord
+
+/-- The witness and total counters, temporary digit stack, verifier result flag, and auxiliary
+ports used by the witness enumerator. -/
+inductive Port (K : Type*) where
+ | choice | total | scratch | flag | aux (k : K)
+ deriving DecidableEq, Fintype
+
+/-- Selects the binary counter holding the current witness or the number of witnesses accepted
+so far. -/
+inductive Register where
+ | choice | total
+ deriving DecidableEq
+
+instance : Fintype Register := derive_fintype% _
+
+/-- The stack port storing the selected witness or total counter. -/
+def Register.port {K : Type*} : Register → Port K
+ | .choice => .choice
+ | .total => .total
+
+/-- The local states for invoking the verifier, collecting its result, and propagating a carry
+through either counter before restoring its digit order. -/
+inductive Control (Q : Type*) where
+ | verify (q : Q) | collect
+ | scan (r : Register) (carry : Bool)
+ | emit (r : Register) (digit carry : Bool)
+ | restore (r : Register) (overflow : Bool)
+ | put (r : Register) (overflow digit : Bool)
+ deriving DecidableEq, Fintype
+
+variable {K Q : Type*}
+
+private def resume (entry : Q) : Register → Bool → Option (Control Q)
+ | .total, _ => some (.scan .choice true)
+ | .choice, false => some (.verify entry)
+ | .choice, true => none
+
+/-- The finite control and ports are independent of the width of either counter. -/
+def enumerate (v : Routine (Port K) Q) : Routine (Port K) (Control Q) where
+ entry := .verify v.entry
+ code
+ | .verify q => v.install Control.verify (some .collect) q
+ | .collect => .pop .flag (fun b => some (.scan .total (b.getD false)))
+ | .scan r c => .pop r.port (fun b => some (b.elim (.restore r c) (fun d => .emit r (d ^^ c) (d && c))))
+ | .emit r d c => .push .scratch d (some (.scan r c))
+ | .restore r c => .pop .scratch (fun b => b.elim (resume v.entry r c) (fun d => some (.put r c d)))
+ | .put r c d => .push r.port d (some (.restore r c))
+
+/-- Call boundary for the verifier. Its private work and its persistent input
+are all located at `aux` ports. A normal return places one Boolean in `flag`. -/
+def bank (aux : Stacks K) (choice total scratch flag : List Bool) : Stacks (Port K)
+ | .choice => choice
+ | .total => total
+ | .scratch => scratch
+ | .flag => flag
+ | .aux k => aux k
+
+private def scanBank (r : Register) (aux : Stacks K) (active other scratch : List Bool) :=
+ match r with
+ | .choice => bank aux active other scratch []
+ | .total => bank aux other active scratch []
+
+private theorem scanBank_active (r : Register) (aux : Stacks K) (a o s : List Bool) :
+ scanBank r aux a o s r.port = a := by cases r <;> rfl
+
+private theorem scanBank_scratch (r : Register) (aux : Stacks K) (a o s : List Bool) :
+ scanBank r aux a o s .scratch = s := by cases r <;> rfl
+
+variable [DecidableEq K]
+
+private theorem active_update (r : Register) (aux : Stacks K) (a o s b : List Bool) :
+ Function.update (scanBank r aux a o s) r.port b = scanBank r aux b o s := by
+ funext i
+ cases r <;> cases i <;> simp [Register.port, scanBank, bank]
+
+private theorem scratch_update (r : Register) (aux : Stacks K) (a o s b : List Bool) :
+ Function.update (scanBank r aux a o s) .scratch b = scanBank r aux a o b := by
+ funext i
+ cases r <;> cases i <;> simp [scanBank, bank]
+
+local macro "counter_step" : tactic => `(tactic|
+ (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_)
+ <;> simp only [scanBank_active, scanBank_scratch, active_update, scratch_update,
+ List.head?_cons, List.tail_cons, List.head?_nil, List.tail_nil, Option.elim_some, Option.elim_none])
+
+variable (v : Routine (Port K) Q) (aux : Stacks K)
+
+private theorem scan_run (r : Register) (carry : Bool) (active other scratch : List Bool) :
+ StackRuns (enumerate v).standalone (2 * active.length + 1) (some (.scan r carry))
+ (scanBank r aux active other scratch) (some (.restore r (incScan carry active).2))
+ (scanBank r aux [] other ((incScan carry active).1.reverse ++ scratch)) := by
+ induction active generalizing carry scratch with
+ | nil => counter_step; exact .nil ..
+ | cons b bs ih =>
+ simp only [List.length_cons, Nat.mul_succ, incScan, List.reverse_cons, List.append_assoc,
+ List.singleton_append]
+ counter_step
+ counter_step
+ exact ih (b && carry) ((b ^^ carry) :: scratch)
+
+private theorem restore_run (r : Register) (carry : Bool) (active other scratch : List Bool) :
+ StackRuns (enumerate v).standalone (2 * scratch.length + 1) (some (.restore r carry))
+ (scanBank r aux active other scratch) (resume v.entry r carry)
+ (scanBank r aux (scratch.reverse ++ active) other []) := by
+ induction scratch generalizing active with
+ | nil => counter_step; exact .nil ..
+ | cons b bs ih =>
+ simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, List.singleton_append]
+ counter_step
+ counter_step
+ exact ih (b :: active)
+
+private theorem increment_run (r : Register) (carry : Bool) (active other : List Bool) :
+ StackRuns (enumerate v).standalone (4 * active.length + 2) (some (.scan r carry))
+ (scanBank r aux active other []) (resume v.entry r (incScan carry active).2)
+ (scanBank r aux (incScan carry active).1 other []) := by
+ have h := (scan_run v aux r carry active other []).trans
+ (restore_run v aux r (incScan carry active).2 [] other ((incScan carry active).1.reverse ++ []))
+ simp only [List.append_nil, List.length_reverse, List.reverse_reverse, incScan_length] at h
+ convert h using 1
+ omega
+
+/-- The next call starts with the incremented counters. On the last witness
+the normal return has exactly the same layout, with the witness reset to zero. -/
+theorem iteration_run {v : Routine (Port K) Q} {aux : Stacks K} {work : ℕ}
+ {choice total : List Bool} {ok : Bool}
+ (hv : v.Runs work (bank aux choice total [] []) (bank aux choice total [] [ok])) :
+ StackRuns (enumerate v).standalone (work + 4 * total.length + 4 * choice.length + 5)
+ (some (enumerate v).entry) (bank aux choice total [] [])
+ (if (incScan true choice).2 then none else some (enumerate v).entry)
+ (bank aux (incScan true choice).1 (incScan ok total).1 [] []) := by
+ have verified := hv.link (enumerate v) Control.verify (some .collect) (fun _ => rfl)
+ have hf : Function.update (bank aux choice total [] [ok]) .flag [] = bank aux choice total [] [] := by
+ funext i
+ cases i <;> simp [bank]
+ have pop : StackRuns (enumerate v).standalone 1 (some .collect) (bank aux choice total [] [ok])
+ (some (.scan .total ok)) (bank aux choice total [] []) := by
+ refine .cons (.pop rfl) ?_
+ simp only [bank, List.head?_cons, List.tail_cons, hf, Option.getD_some]
+ exact .nil ..
+ have add := increment_run v aux .total ok total choice
+ have next := increment_run v aux .choice true choice (incScan ok total).1
+ have h := ((verified.trans pop).trans add).trans next
+ have he : resume v.entry .choice (incScan true choice).2 =
+ (if (incScan true choice).2 then none else some (enumerate v).entry) := by
+ cases (incScan true choice).2 <;> rfl
+ rw [he] at h
+ convert h using 1 <;> first | rfl | omega
+
+end UniversalCountStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/UniversalCountStackBounds.lean b/lean/OAI/Computability/VPVNP/UniversalCountStackBounds.lean
new file mode 100644
index 0000000000..8842cab10c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/UniversalCountStackBounds.lean
@@ -0,0 +1,182 @@
+import OAI.Computability.VPVNP.UniversalCountStack
+
+/-!
+# Time and space for the witness enumerator
+
+For a verifier using at most `B` steps per witness, the counter makes exactly
+one call per binary word. The bound on the height of every stack is independent
+of the number of calls. This follows by restarting the space estimate at each
+call boundary, where the counters have their original widths and the auxiliary
+stacks have their original contents.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalCountStack
+
+open RAMTape TapeWord RAMTape.UnaryWord BurstRAM
+
+variable {K Q : Type*} [DecidableEq K]
+
+/-- Every stack in every intermediate configuration has length at most `cap`. -/
+inductive SpaceRun (code : StackCode K Q) (cap : ℕ) : ℕ → Q → Stacks K → Q → Stacks K → Prop
+ | nil (q : Q) (s : Stacks K) (hs : ∀ k, (s k).length ≤ cap) : SpaceRun code cap 0 q s q s
+ | cons {q s q' s' n t u} (hs : ∀ k, (s k).length ≤ cap) :
+ StackStep code q s q' s' → SpaceRun code cap n q' s' t u →
+ SpaceRun code cap (n + 1) q s t u
+
+theorem SpaceRun.runs {code : StackCode K Q} {cap n q s t u} (h : SpaceRun code cap n q s t u) :
+ StackRuns code n q s t u := by
+ induction h with
+ | nil => exact .nil ..
+ | cons _ step _ ih => exact .cons step ih
+
+theorem SpaceRun.trans {code : StackCode K Q} {cap a b q s q' s' t u}
+ (h : SpaceRun code cap a q s q' s') (g : SpaceRun code cap b q' s' t u) :
+ SpaceRun code cap (a + b) q s t u := by
+ induction h with
+ | nil => simpa using g
+ | cons hs step _ ih => simpa only [Nat.succ_add] using SpaceRun.cons hs step (ih g)
+
+private theorem step_length {code : StackCode K Q} {q s q' s'}
+ (h : StackStep code q s q' s') (k : K) : (s' k).length ≤ (s k).length + 1 := by
+ cases h with
+ | push =>
+ rename_i j b _
+ by_cases e : k = j <;> simp [e]
+ | pop =>
+ rename_i j f _
+ by_cases e : k = j <;> simp [e]
+ omega
+ | goto => omega
+
+theorem spaceRun_of_steps {code : StackCode K Q} {cap n q s t u}
+ (h : StackRuns code n q s t u) (hs : ∀ k, (s k).length + n ≤ cap) : SpaceRun code cap n q s t u := by
+ induction h with
+ | nil => exact .nil _ _ (by simpa using hs)
+ | cons step _ ih =>
+ refine .cons (fun k => by have := hs k; omega) step (ih fun k => ?_)
+ have := step_length step k
+ have := hs k
+ omega
+
+/-- The low `w` bits in the same order as the finite Boolean witness. -/
+def digits (w i : ℕ) : List Bool := wordBits (Fin.ofNat (2 ^ w) i)
+
+@[simp] theorem length_digits (w i : ℕ) : (digits w i).length = w := length_wordBits _
+
+@[simp] theorem value_digits (w i : ℕ) : value (digits w i) = i % (2 ^ w) := by
+ rw [digits, value_wordBits, Fin.val_ofNat]
+
+theorem digits_zero (w : ℕ) : digits w 0 = List.replicate w false :=
+ eq_of_length_value (by simp) (by simp)
+
+private theorem inc_digits (w i : ℕ) (b : Bool) (hi : i < 2^w) :
+ (incScan b (digits w i)).1 = digits w (i + b.toNat) ∧
+ ((incScan b (digits w i)).2 = true ↔ 2^w ≤ i + b.toNat) := by
+ have h := incScan_value b (digits w i)
+ rw [length_digits, value_digits, Nat.mod_eq_of_lt hi] at h
+ have hlen := incScan_length b (digits w i)
+ rw [length_digits] at hlen
+ have hlt := value_lt (incScan b (digits w i)).1
+ rw [hlen] at hlt
+ constructor
+ · apply eq_of_length_value (by simp [hlen])
+ rw [value_digits, ← h, Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hlt]
+ · cases hc : (incScan b (digits w i)).2 <;> simp [hc] at h ⊢ <;> omega
+
+/-- Applies the witness predicate to the low w bits of the given index in little-endian order. -/
+def testAt {w : ℕ} (f : (Fin w → Bool) → Bool) (i : ℕ) : Bool :=
+ f (RAMSerialization.wordBits w (Fin.ofNat (2 ^ w) i))
+
+private def tally {w : ℕ} (f : (Fin w → Bool) → Bool) (i : ℕ) : ℕ :=
+ ∑ j ∈ Finset.range i, (testAt f j).toNat
+
+private theorem tally_succ {w : ℕ} (f : (Fin w → Bool) → Bool) (i : ℕ) :
+ tally f (i+1) = tally f i + (testAt f i).toNat := Finset.sum_range_succ ..
+
+private theorem tally_le {w : ℕ} (f : (Fin w → Bool) → Bool) (i : ℕ) : tally f i ≤ i := by
+ induction i with
+ | zero => simp [tally]
+ | succ i ih => rw [tally_succ]; cases testAt f i <;> simp <;> omega
+
+private theorem tally_all {w : ℕ} (f : (Fin w → Bool) → Bool) :
+ tally f (2^w) = ∑ bits, (f bits).toNat := by
+ rw [tally, Finset.sum_range]
+ have cast (i : Fin (2^w)) : Fin.ofNat (2^w) i.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt)
+ simp only [testAt, cast]
+ exact (RAMSerialization.wordBits w).sum_comp (fun bits => (f bits).toNat)
+
+variable {v : Routine (Port K) Q} {aux : Stacks K} {B A w : ℕ} {f : (Fin w → Bool) → Bool}
+
+/-- A full run returns the numeric count in a `w + 1` bit register. The
+control remains fixed across word lengths and verifier inputs. Each individual
+stack stays within the stated space bound throughout the run. -/
+theorem enumerate_runs (haux : ∀ k, (aux k).length ≤ A)
+ (hv : ∀ (bits : Fin w → Bool) (count : List Bool), count.length = w + 1 →
+ ∃ t ≤ B, v.Runs t (bank aux (List.ofFn bits) count [] [])
+ (bank aux (List.ofFn bits) count [] [f bits])) :
+ ∃ t ≤ 2 ^ w * (B + 8 * w + 9),
+ SpaceRun (enumerate v).standalone (max A (w+1) + (B + 8*w + 9)) t
+ (some (enumerate v).entry) (bank aux (digits w 0) (digits (w+1) 0) [] []) none
+ (bank aux (digits w 0) (digits (w+1) (∑ bits, (f bits).toNat)) [] []) := by
+ let bound := B + 8*w + 9
+ let cap := max A (w+1) + bound
+ let state (j : ℕ) := bank aux (digits w j) (digits (w+1) (tally f j)) [] []
+ let pc (j : ℕ) := if j = 2^w then none else some (enumerate v).entry
+ have hs (j : ℕ) (k : Port K) : (state j k).length ≤ max A (w+1) := by
+ cases k with
+ | aux k => exact (haux k).trans (le_max_left ..)
+ | choice => simp [state, bank]
+ | total => simp [state, bank]
+ | scratch | flag => simp [state, bank]
+ have loop (rem j : ℕ) (hr : j + rem = 2^w) :
+ ∃ t ≤ rem * bound, SpaceRun (enumerate v).standalone cap t (pc j) (state j)
+ none (state (2^w)) := by
+ induction rem generalizing j with
+ | zero =>
+ simp only [Nat.add_zero] at hr
+ subst j
+ refine ⟨0, by simp, ?_⟩
+ rw [show pc (2^w) = none by simp [pc]]
+ exact .nil _ _ (fun k => (hs _ k).trans (Nat.le_add_right ..))
+ | succ rem ih =>
+ have hj : j < 2^w := by omega
+ let bits := RAMSerialization.wordBits w (Fin.ofNat (2^w) j)
+ obtain ⟨t, ht, verified⟩ := hv bits (digits (w+1) (tally f j)) (length_digits ..)
+ have hfit : tally f j < 2^(w+1) := by
+ have := tally_le f j
+ rw [pow_succ]
+ omega
+ have hc := inc_digits w j true hj
+ have ha := inc_digits (w+1) (tally f j) (testAt f j) hfit
+ simp only [Bool.toNat_true] at hc
+ have run := iteration_run verified
+ have hb : List.ofFn bits = digits w j := rfl
+ have he : f bits = testAt f j := rfl
+ rw [hb, he, length_digits, length_digits, hc.1, ha.1, ← tally_succ] at run
+ have hov : (incScan true (digits w j)).2 = true ↔ j+1 = 2^w := by
+ rw [hc.2]
+ omega
+ simp only [hov] at run
+ have step : StackRuns (enumerate v).standalone (t+4*(w+1)+4*w+5) (pc j) (state j)
+ (pc (j+1)) (state (j+1)) := by simpa only [pc, ite_eq_right hj.ne, state] using run
+ have hd : t+4*(w+1)+4*w+5 ≤ bound := by dsimp [bound]; omega
+ have bounded := spaceRun_of_steps (cap := cap) step (fun k => Nat.add_le_add (hs j k) hd)
+ obtain ⟨u, hu, rest⟩ := ih (j+1) (by omega)
+ refine ⟨_, ?_, bounded.trans rest⟩
+ exact (Nat.add_le_add hd hu).trans_eq ((Nat.add_comm ..).trans (Nat.succ_mul ..).symm)
+ have h := loop (2^w) 0 (Nat.zero_add _)
+ have hp : 0 < 2^w := pow_pos (by decide) _
+ have hz : digits w (2^w) = digits w 0 := eq_of_length_value (by simp) (by simp)
+ have t0 : tally f 0 = 0 := by simp [tally]
+ simpa only [pc, ite_eq_right hp.ne, state, tally_all, hz, t0,
+ bound, cap] using h
+
+end UniversalCountStack
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/UniversalMachine.lean b/lean/OAI/Computability/VPVNP/UniversalMachine.lean
new file mode 100644
index 0000000000..fc3d91e945
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/UniversalMachine.lean
@@ -0,0 +1,279 @@
+import Mathlib.Computability.TuringMachine.Tape
+import Mathlib.Data.List.OfFn
+
+/-!
+# The coefficient machine of “VP and VNP differ over every field”, §1.1
+
+We fix two two-way tapes over the alphabet blank, zero, one (codes 0, 1, 2). States 0 and 1
+halt with rejection and acceptance. The running states start at 2. Every transition writes
+one symbol on each tape, moves each head by at most one cell and enters its target state.
+
+The prefix is the table's bit length in unary (`1^k 0`) followed by exactly `k` bits. Inside
+that table each natural-number field is also unary. The empty table has no running states and
+starts in the accepting state. Otherwise the first field is the number of running states minus
+one. The remaining fields give all nine rows for each running state, ordered by state, first
+head and second head. Each row is a branch count (0, 1 or 2) followed by that many records.
+A record lists target, first symbol, first move, second symbol, second move. Moves 0, 1 and 2
+mean stay, left and right. All fields are literal. Both tapes start with the head at cell 0,
+and the first tape carries the complete input, including the program prefix.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+/-- The tape alphabet encodes blank, binary zero and binary one as 0, 1 and 2. -/
+abbrev Symbol := Fin 3
+/-- A finite binary input, including its literal program prefix. -/
+abbrev Word := List Bool
+
+/-- `target = 0` rejects, `target = 1` accepts, and `target = 2 + i` enters running state `i`. -/
+structure Instruction (extra : ℕ) where
+ /-- The state entered after the writes and head movements. -/
+ target : Fin (extra + 2)
+ /-- Symbol written under the first head. -/
+ firstSymbol : Symbol
+ /-- First-head movement, in the order stay, left, right. -/
+ firstMove : Fin 3
+ /-- Symbol written under the second head. -/
+ secondSymbol : Symbol
+ /-- Second-head movement, in the order stay, left, right. -/
+ secondMove : Fin 3
+
+/-- Each branch occupies its own slot, even if two transitions are identical. -/
+inductive Branches (extra : ℕ)
+ | stop
+ | one (a : Instruction extra)
+ | two (a b : Instruction extra)
+
+/-- A finite nondeterministic table with a row for each running state and symbol pair. -/
+structure Program where
+ /-- Number of states besides the two halting states. -/
+ extra : ℕ
+ /-- Transition lists ordered by state, first-head symbol, then second-head symbol. -/
+ rows : List (Branches extra)
+ rows_length : rows.length = extra * 9
+
+/-- The state and both head-centered tapes at one instant of a computation. -/
+structure Config (extra : ℕ) where
+ /-- The current running or halting state. -/
+ state : Fin (extra + 2)
+ /-- The tape that initially holds the input word. -/
+ firstTape : Turing.Tape Symbol
+ /-- The initially blank work tape. -/
+ secondTape : Turing.Tape Symbol
+
+/-- The empty table is the machine that starts already halted in acceptance. -/
+def emptyProgram : Program := ⟨0, [], rfl⟩
+
+/-- Start at the first running state with the complete input on the first tape.
+The empty table starts in the accepting state. -/
+def initial (p : Program) (input : Word) : Config p.extra where
+ state := if h : p.extra = 0 then ⟨1, by omega⟩ else ⟨2, by omega⟩
+ firstTape := Turing.Tape.mk₁ (input.map fun b => if b then 2 else 1)
+ secondTape := Turing.Tape.mk₁ []
+
+/-- Look up the transition slots for the current running state and the two scanned symbols. -/
+def branches (p : Program) (c : Config p.extra) : Branches p.extra :=
+ p.rows[(c.state.val - 2) * 9 + c.firstTape.head.val * 3 + c.secondTape.head.val]?.getD .stop
+
+/-- Write at the head and then carry out its specified movement. -/
+def updateTape (t : Turing.Tape Symbol) (write : Symbol) (move : Fin 3) :=
+ let t' := t.write write
+ match move.val with
+ | 0 => t'
+ | 1 => t'.move .left
+ | _ => t'.move .right
+
+/-- Apply one chosen transition to both tapes and enter its target state. -/
+def advance {extra : ℕ} (c : Config extra) (a : Instruction extra) : Config extra where
+ state := a.target
+ firstTape := updateTape c.firstTape a.firstSymbol a.firstMove
+ secondTape := updateTape c.secondTape a.secondSymbol a.secondMove
+
+/-- Accepting leaves within `fuel` transitions of the encoded machine, including time zero. -/
+def paths (p : Program) : ℕ → Config p.extra → ℕ
+ | 0, c => if c.state.val = 1 then 1 else 0
+ | fuel + 1, c =>
+ if c.state.val = 1 then 1 else if c.state.val = 0 then 0 else
+ match branches p c with
+ | .stop => 0
+ | .one a => paths p fuel (advance c a)
+ | .two a b => paths p fuel (advance c a) + paths p fuel (advance c b)
+
+theorem paths_accept (p : Program) (c : Config p.extra) (hc : c.state.val = 1) (fuel : ℕ) :
+ paths p fuel c = 1 := by cases fuel <;> simp [paths, hc]
+
+theorem paths_reject (p : Program) (c : Config p.extra) (hc : c.state.val = 0) (fuel : ℕ) :
+ paths p fuel c = 0 := by cases fuel <;> simp [paths, hc]
+
+/-- The unary field for a number, including the terminating zero. -/
+def unary (k : ℕ) : Word := List.replicate k true ++ [false]
+
+private def readUnary : Word → Option (ℕ × Word)
+ | [] => none
+ | false :: xs => some (0, xs)
+ | true :: xs => (fun (k, rest) => (k + 1, rest)) <$> readUnary xs
+
+private theorem readUnary_append (k : ℕ) (xs : Word) :
+ readUnary (unary k ++ xs) = some (k, xs) := by
+ induction k with
+ | zero => rfl
+ | succ k ih =>
+ change (fun (j, rest) => (j + 1, rest)) <$> readUnary (unary k ++ xs) = _
+ rw [ih]
+ rfl
+
+/-- Read all unary fields in the table. A last field with no terminator fails. -/
+private def readFields : Word → Option (List ℕ)
+ | [] => some []
+ | false :: xs => (0 :: ·) <$> readFields xs
+ | true :: xs => do
+ let k :: rest ← readFields xs | none
+ return (k + 1) :: rest
+
+private def checkFin (m k : ℕ) : Option (Fin m) :=
+ if h : k < m then some ⟨k, h⟩ else none
+
+private def readInstruction (extra : ℕ) : List ℕ → Option (Instruction extra × List ℕ)
+ | q :: x :: u :: y :: v :: rest => do
+ let target ← checkFin (extra + 2) q
+ let firstSymbol ← checkFin 3 x
+ let firstMove ← checkFin 3 u
+ let secondSymbol ← checkFin 3 y
+ let secondMove ← checkFin 3 v
+ return (⟨target, firstSymbol, firstMove, secondSymbol, secondMove⟩, rest)
+ | _ => none
+
+private def readBranch (extra : ℕ) : List ℕ → Option (Branches extra × List ℕ)
+ | 0 :: xs => some (.stop, xs)
+ | 1 :: xs => do
+ let (a, rest) ← readInstruction extra xs
+ return (.one a, rest)
+ | 2 :: xs => do
+ let (a, rest) ← readInstruction extra xs
+ let (b, tail) ← readInstruction extra rest
+ return (.two a b, tail)
+ | _ => none
+
+private def readRows (extra : ℕ) : ℕ → List ℕ → Option (List (Branches extra) × List ℕ)
+ | 0, xs => some ([], xs)
+ | count + 1, xs => do
+ let (b, rest) ← readBranch extra xs
+ let (bs, tail) ← readRows extra count rest
+ return (b :: bs, tail)
+
+private def decodeTable (table : Word) : Option Program := do
+ match ← readFields table with
+ | [] => return emptyProgram
+ | k :: xs =>
+ let extra := k + 1
+ let (rows, []) ← readRows extra (extra * 9) xs | none
+ if h : rows.length = extra * 9 then return ⟨extra, rows, h⟩ else none
+
+/-- Decode just the program prefix. The payload is unrestricted. -/
+def decode (input : Word) : Option Program := do
+ let (len, rest) ← readUnary input
+ if len ≤ rest.length then decodeTable (rest.take len) else none
+
+/-- The five integer fields that encode a single instruction. -/
+def instructionFields {extra : ℕ} (a : Instruction extra) : List ℕ :=
+ [a.target, a.firstSymbol, a.firstMove, a.secondSymbol, a.secondMove]
+
+/-- Encode the number of branches followed by their instructions in slot order. -/
+def branchFields {extra : ℕ} : Branches extra → List ℕ
+ | .stop => [0]
+ | .one a => 1 :: instructionFields a
+ | .two a b => 2 :: (instructionFields a ++ instructionFields b)
+
+/-- Serialize the table with no implicit rows or unbounded instructions. -/
+def tableBits (p : Program) : Word :=
+ if p.extra = 0 then [] else ((p.extra - 1) :: p.rows.flatMap branchFields).flatMap unary
+
+/-- A literal prefix, independent of the subsequent payload. -/
+def programPrefix (p : Program) : Word := unary (tableBits p).length ++ tableBits p
+
+private theorem readFields_unary (k : ℕ) (xs : Word) :
+ readFields (unary k ++ xs) = (k :: ·) <$> readFields xs := by
+ induction k with
+ | zero => rfl
+ | succ k ih =>
+ change (do
+ let j :: rest ← readFields (unary k ++ xs) | none
+ return (j + 1) :: rest) = _
+ rw [ih]
+ cases readFields xs <;> rfl
+
+private theorem readFields_encode (xs : List ℕ) : readFields (xs.flatMap unary) = some xs := by
+ induction xs with
+ | nil => rfl
+ | cons x xs ih => simp [List.flatMap_cons, readFields_unary, ih]
+
+private theorem readInstruction_encode {extra : ℕ} (a : Instruction extra) (xs : List ℕ) :
+ readInstruction extra (instructionFields a ++ xs) = some (a, xs) := by
+ cases a
+ simp [instructionFields, readInstruction, checkFin]
+
+private theorem readBranch_encode {extra : ℕ} (b : Branches extra) (xs : List ℕ) :
+ readBranch extra (branchFields b ++ xs) = some (b, xs) := by
+ cases b <;> simp [branchFields, readBranch, List.append_assoc, readInstruction_encode]
+
+private theorem readRows_encode {extra : ℕ} (bs : List (Branches extra)) (xs : List ℕ) :
+ readRows extra bs.length (bs.flatMap branchFields ++ xs) = some (bs, xs) := by
+ induction bs with
+ | nil => rfl
+ | cons b bs ih => simp [List.flatMap_cons, List.append_assoc, readRows, readBranch_encode, ih]
+
+private theorem decodeTable_encode (p : Program) : decodeTable (tableBits p) = some p := by
+ rcases p with ⟨extra, rows, hrows⟩
+ cases extra with
+ | zero =>
+ have : rows = [] := List.length_eq_zero_iff.mp (by simpa using hrows)
+ subst rows
+ rfl
+ | succ k =>
+ have h := readRows_encode rows []
+ simp only [List.append_nil, hrows] at h
+ simp [tableBits, decodeTable, readFields_unary, readFields_encode, h, hrows]
+
+/-- Decoding the self-delimiting prefix recovers the exact machine, on every payload. -/
+theorem decode_programPrefix (p : Program) (payload : Word) :
+ decode (programPrefix p ++ payload) = some p := by
+ simp [decode, programPrefix, List.append_assoc, readUnary_append, decodeTable_encode]
+
+theorem decode_false_cons (payload : Word) : decode (false :: payload) = some emptyProgram := by
+ simp [decode, readUnary, decodeTable, readFields]
+
+end UniversalMachine
+
+section
+
+open UniversalMachine
+
+/-- The exponent `K_*` from §1.1. -/
+def clockExponent : ℕ := 10 ^ 9
+
+/-- The integer coefficient `U_n(x)` of equation (1.1), prior to casting to a field. -/
+def acceptingCount {n : ℕ} (x : Fin n → Bool) : ℕ :=
+ let input := List.ofFn x
+ match decode input with
+ | none => 0
+ | some p => paths p (n ^ clockExponent) (initial p input)
+
+theorem acceptingCount_of_malformed {n : ℕ} (x : Fin n → Bool) (h : decode (List.ofFn x) = none) :
+ acceptingCount x = 0 := by simp [acceptingCount, h]
+
+theorem acceptingCount_allFalse {n : ℕ} (hn : 0 < n) :
+ acceptingCount (fun _ : Fin n => false) = 1 := by
+ obtain ⟨k, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hn.ne'
+ simp only [acceptingCount, List.ofFn_succ, decode_false_cons]
+ apply paths_accept
+ rfl
+
+end
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VacuumPairing.lean b/lean/OAI/Computability/VPVNP/VacuumPairing.lean
new file mode 100644
index 0000000000..7d5e5f2c5a
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VacuumPairing.lean
@@ -0,0 +1,198 @@
+import Lemmata.FockCircuits.Duality
+import OAI.Computability.VPVNP.ShiftedPairing
+
+/-!
+# Vacuum pairing in the shifted crossing
+
+The empty-output matrix entry of the finite fermion field is the signed
+Pascal minor in Appendix B. Coordinates of exterior products give the
+determinant, and the energy-sector enumeration gives the same pairing as the
+unimodularity calculation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Crossing
+
+variable {R M I : Type*} [CommRing R] [AddCommGroup M] [Module R M] [LinearOrder I]
+ {n : ℕ}
+
+/-- The coordinate of a wedge on an ordered set of modes is a determinant. -/
+private theorem wedge_coefficient_det (b : Module.Basis I R M)
+ (B : Set.powersetCard I n) (v : Fin n → M) :
+ b.ExteriorAlgebra.repr (ExteriorAlgebra.ιMulti R n v) B.val =
+ (Matrix.of fun i j ↦ b.repr (v i) (B.val.orderEmbOfFin B.prop j)).det := by
+ classical
+ have h : (b.ExteriorAlgebra.coord B.val).comp (⋀[R]^n M).subtype =
+ (b.exteriorPower n).coord B := by
+ apply (b.exteriorPower n).ext
+ intro C
+ rw [LinearMap.comp_apply, Submodule.subtype_apply, ← ExteriorAlgebra.basis_eq_coe_basis]
+ simp only [Module.Basis.coord_apply, Module.Basis.repr_self, Finsupp.single_apply,
+ Subtype.ext_iff]
+ change ((b.ExteriorAlgebra.coord B.val).comp (⋀[R]^n M).subtype)
+ (exteriorPower.ιMulti R n v) = _
+ rw [h, exteriorPower.basis_coord, exteriorPower.ιMultiDual_apply_ιMulti]
+ rfl
+
+/-- A homogeneous wedge has no coordinate in another occupation degree. -/
+private theorem wedge_coefficient_eq_zero_of_card_ne (b : Module.Basis I R M)
+ (B : Finset I) (v : Fin n → M) (hB : B.card ≠ n) :
+ b.ExteriorAlgebra.repr (ExteriorAlgebra.ιMulti R n v) B = 0 := by
+ classical
+ have h : (b.ExteriorAlgebra.coord B).comp (⋀[R]^n M).subtype = 0 := by
+ apply (b.exteriorPower n).ext
+ intro C
+ rw [LinearMap.comp_apply, Submodule.subtype_apply, ← ExteriorAlgebra.basis_eq_coe_basis,
+ Module.Basis.coord_apply, Module.Basis.repr_self, LinearMap.zero_apply]
+ exact Finsupp.single_eq_of_ne (fun h ↦ hB (h ▸ C.prop))
+ exact LinearMap.congr_fun h (exteriorPower.ιMulti R n v)
+
+open Lemmata.FockCircuits Lemmata.FockCircuits.FiniteIdentity
+open Set.powersetCard
+open scoped BigOperators
+
+/-- At the empty output only deletion modes contribute, in increasing source order. -/
+private theorem rightProjection_kernel_single_one (R : Type*) [CommRing R] (L : ℕ) (A : Index L) :
+ rightProjection R (kernel R L (Pi.single A 1)) =
+ ExteriorAlgebra.ιMulti R A.val.card (fun i => finiteVector R L
+ (fun k => (negativeCoefficient (A.val.orderEmbOfFin rfl i) k : R))) := by
+ classical
+ rw [kernel, realize_single, one_smul, map_mul, rightProjection_kernel, mul_one]
+ change ExteriorAlgebra.map (rightParticle R)
+ (ExteriorAlgebra.map (substitution R L)
+ ((Finsupp.basisSingleOne : Module.Basis ℕ R (OneParticle R)).ExteriorAlgebra A.val)) = _
+ rw [ExteriorAlgebra.basis_apply_ofCard (n := A.val.card) _ rfl]
+ unfold ExteriorAlgebra.ιMulti_family
+ rw [ExteriorAlgebra.map_apply_ιMulti, ExteriorAlgebra.map_apply_ιMulti]
+ congr 1
+ funext i
+ simp [Function.comp_def, Set.powersetCard.ofFinEmbEquiv_symm_apply]
+
+/-- The vacuum matrix entry on an equal-cardinality sector is the signed
+minor of the divided-derivative contraction matrix in Appendix B. -/
+theorem vacuum_matrix_det (R : Type*) [CommRing R] {L : ℕ} (A B : Index L)
+ (h : B.val.card = A.val.card) :
+ matrix R L (Pi.single A 1) ⟨∅, by simp⟩ B =
+ (dualSign B.val : R) *
+ (Matrix.of fun i j : Fin A.val.card =>
+ (negativeCoefficient (A.val.orderEmbOfFin rfl i) (B.val.orderEmbOfFin h j) : R)).det := by
+ classical
+ change (dualSign B.val : R) * (colourBasis R).repr _ (colourIndex ∅ B.val) = _
+ rw [← rightProjection_coefficient, rightProjection_kernel_single_one]
+ have coeff := wedge_coefficient_det (Finsupp.basisSingleOne : Module.Basis ℕ R (OneParticle R))
+ (Set.powersetCard.ofCard h)
+ (fun i => finiteVector R L (fun k => (negativeCoefficient (A.val.orderEmbOfFin rfl i) k : R)))
+ rw [show (Fock.basis R).repr _ B.val = _ from coeff]
+ congr 2
+ ext i j
+ change finiteVector R L _ (B.val.orderEmbOfFin h j) = _
+ exact finiteVector_apply R L _ ⟨_, Finset.mem_range.mp ((Finset.mem_powerset.mp B.property)
+ (B.val.orderEmbOfFin_mem h j))⟩
+
+/-- Unequal occupation sectors have zero vacuum pairing. -/
+theorem vacuum_matrix_eq_zero_of_card_ne (R : Type*) [CommRing R] {L : ℕ} (A B : Index L)
+ (h : B.val.card ≠ A.val.card) :
+ matrix R L (Pi.single A 1) ⟨∅, by simp⟩ B = 0 := by
+ classical
+ change (dualSign B.val : R) * (colourBasis R).repr _ (colourIndex ∅ B.val) = 0
+ rw [← rightProjection_coefficient, rightProjection_kernel_single_one]
+ exact mul_eq_zero_of_right _ (wedge_coefficient_eq_zero_of_card_ne _ B.val _ h)
+
+
+/-- The negative mode gives a sign depending on each row alone. -/
+theorem det_negativeCoefficient {m : ℕ} (a b : Fin m → ℕ) :
+ (Matrix.of fun i j => Lemmata.FockCircuits.negativeCoefficient (a i) (b j)).det =
+ (-1 : ℤ) ^ (∑ i, a i) *
+ (Matrix.of fun i j => ((a i + b j).choose (a i) : ℤ)).det := by
+ simpa only [Lemmata.FockCircuits.negativeCoefficient, Nat.add_comm, Matrix.of_apply,
+ Finset.prod_pow_eq_pow_sum] using
+ Matrix.det_mul_column (fun i => (-1 : ℤ) ^ a i)
+ (Matrix.of fun i j => ((a i + b j).choose (a i) : ℤ))
+
+/-- With the order reversal from the vacuum contraction, the signed matrix is
+exactly the integral pairing in each energy sector of Appendix B. -/
+theorem signed_det_negativeCoefficient_eq_sectorPairing {n m bound : ℕ}
+ (I J : EnergySector n m bound) :
+ (-1 : ℤ) ^ m.choose 2 *
+ (Matrix.of fun i j => Lemmata.FockCircuits.negativeCoefficient
+ (Set.powersetCard.ofFinEmbEquiv.symm I.val i).val
+ (Set.powersetCard.ofFinEmbEquiv.symm J.val j).val).det =
+ sectorPairing n m bound I J := by
+ rw [det_negativeCoefficient, ← mul_assoc, ← pow_add]
+ rfl
+
+
+/-- The same occupied modes in the larger mode cutoff used for the Wick identity. -/
+def sectorIndex {n m L : ℕ} (hn : n ≤ L) (I : Set.powersetCard (Fin n) m) : Index L :=
+ ⟨I.val.map Fin.valEmbedding, Finset.mem_powerset.mpr (by
+ intro k hk
+ obtain ⟨j, _, rfl⟩ := Finset.mem_map.mp hk
+ exact Finset.mem_range.mpr (j.isLt.trans_le hn))⟩
+
+@[simp] theorem sectorIndex_card {n m L : ℕ} (hn : n ≤ L)
+ (I : Set.powersetCard (Fin n) m) : (sectorIndex hn I).val.card = m := by
+ change (I.val.map Fin.valEmbedding).card = m
+ rw [Finset.card_map, I.prop]
+
+/-- Embedding into a larger cutoff preserves the increasing enumeration of the modes. -/
+theorem sectorIndex_order {n m L : ℕ} (hn : n ≤ L) (I : Set.powersetCard (Fin n) m) :
+ (fun i => ((ofFinEmbEquiv.symm I i).val)) =
+ (sectorIndex hn I).val.orderEmbOfFin (sectorIndex_card hn I) := by
+ apply Finset.orderEmbOfFin_unique
+ · intro i
+ exact Finset.mem_map.mpr ⟨_, I.val.orderEmbOfFin_mem I.prop i, rfl⟩
+ · exact (Fin.valOrderEmb n).strictMono.comp (ofFinEmbEquiv.symm I).strictMono
+
+@[simp] theorem sectorIndex_energy {n m L : ℕ} (hn : n ≤ L)
+ (I : Set.powersetCard (Fin n) m) : Lemmata.FockCircuits.doubledEnergy (sectorIndex hn I).val =
+ doubledSectorEnergy I := by
+ unfold Lemmata.FockCircuits.doubledEnergy doubledSectorEnergy
+ rw [← Finset.map_orderEmbOfFin_univ (sectorIndex hn I).val (sectorIndex_card hn I),
+ Finset.sum_map]
+ simp only [RelEmbedding.coe_toEmbedding, ← sectorIndex_order]
+
+private theorem vacuum_matrix_det_of_card {m L : ℕ} (I J : Index L)
+ (hI : I.val.card = m) (hJ : J.val.card = m) :
+ matrix ℤ L (Pi.single I 1) ⟨∅, by simp⟩ J = (-1 : ℤ) ^ m.choose 2 *
+ (Matrix.of fun i j => negativeCoefficient (I.val.orderEmbOfFin hI i)
+ (J.val.orderEmbOfFin hJ j)).det := by
+ subst m
+ rw [vacuum_matrix_det ℤ I J hJ, dualSign, hJ, Nat.choose_two_right]
+ rfl
+
+/-- The vacuum coefficient in the finite operator identity is the paper's
+integral pairing, with identical orderings of the rows and columns. -/
+theorem vacuum_matrix_sectorPairing {n m bound L : ℕ} (hn : n ≤ L)
+ (I J : EnergySector n m bound) :
+ matrix ℤ L (Pi.single (sectorIndex hn I.val) 1) ⟨∅, by simp⟩ (sectorIndex hn J.val) =
+ sectorPairing n m bound I J := by
+ rw [vacuum_matrix_det_of_card _ _ (sectorIndex_card hn I.val) (sectorIndex_card hn J.val),
+ ← sectorIndex_order, ← sectorIndex_order]
+ exact signed_det_negativeCoefficient_eq_sectorPairing I J
+
+/-- The simultaneous matrix of vacuum entries on all nonempty states of bounded
+energy is the integral block matrix from Appendix B. -/
+theorem vacuum_matrix_crossingPairing {n bound L : ℕ} (hn : n ≤ L)
+ (I J : Σ m : Fin n, EnergySector n (m.val + 1) bound) :
+ matrix ℤ L (Pi.single (sectorIndex hn I.2.val) 1) ⟨∅, by simp⟩ (sectorIndex hn J.2.val) =
+ crossingPairing n bound I J := by
+ obtain ⟨i, I⟩ := I
+ obtain ⟨j, J⟩ := J
+ by_cases h : i = j
+ · subst j
+ rw [crossingPairing, Matrix.blockDiagonal'_apply_eq]
+ exact vacuum_matrix_sectorPairing hn I J
+ · rw [crossingPairing, Matrix.blockDiagonal'_apply_ne
+ (fun k : Fin n => sectorPairing n (k.val + 1) bound) I J h]
+ apply vacuum_matrix_eq_zero_of_card_ne
+ simp only [sectorIndex_card]
+ exact fun hij => h (Fin.ext (by omega))
+
+end Crossing
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Valiant/Project.lean b/lean/OAI/Computability/VPVNP/Valiant/Project.lean
new file mode 100644
index 0000000000..805b0c23cb
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Valiant/Project.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.PermanentCompleteness
+import OAI.Computability.VPVNP.PolynomialBounds
+import OAI.Computability.VPVNP.Valiant.ProjectCircuitEquiv
+
+/-! # Valiant's theorem in the project's exact arithmetic circuit model -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Valiant.Project
+
+variable {F : Type*} [Field F] {σ : ℕ → Type} [∀ n, Fintype (σ n)]
+
+/-- A polynomial bound on realizable table sizes is equivalent to a bound on the
+project's minimum gate counts. -/
+theorem isVP_iff (p : Family F σ) : IsVP p ↔ VPVNP.IsVP p := by
+ constructor
+ · rintro ⟨hfamily, s, hs, h⟩
+ refine ⟨hfamily, VPVNP.PolynomiallyBounded.of_le hs fun n => ?_⟩
+ obtain ⟨c, hc⟩ := computes_iff.mp (h n)
+ exact hc ▸ VPVNP.circuitSize_le_of_circuit c
+ · rintro ⟨hfamily, hsize⟩
+ exact ⟨hfamily, fun n => VPVNP.circuitSize (p n), hsize,
+ fun n => computes_iff.mpr (VPVNP.circuitSize_spec (p n))⟩
+
+/-- Identical Boolean witness substitutions and the same size bounds give identical VNP classes. -/
+theorem isVNP_iff (p : Family F σ) : IsVNP p ↔ VPVNP.IsVNP p := by
+ constructor
+ · rintro ⟨hf, W, inst, g, hW, hg, h⟩
+ exact ⟨hf, W, inst, g, hW, (isVP_iff g).mp hg, h⟩
+ · rintro ⟨hf, W, inst, g, hW, hg, h⟩
+ exact ⟨hf, W, inst, g, hW, (isVP_iff g).mpr hg, h⟩
+
+omit [∀ n, Fintype (σ n)] in
+/-- The source index, substitutions, and formal polynomial equalities in a projection
+are definitionally the same as in the project. -/
+theorem pProjects_iff {τ : ℕ → Type} (target : Family F τ) (source : Family F σ) :
+ PProjects target source ↔ VPVNP.PProjects target source := Iff.rfl
+
+/-- The standalone completeness predicate agrees with the original on every family. -/
+theorem complete_iff (p : Family F σ) : VNPComplete p ↔ VPVNP.VNPComplete p := by
+ constructor
+ · rintro ⟨hp, hh⟩
+ refine ⟨(isVNP_iff p).mp hp, fun τ _ g hg => ?_⟩
+ exact (pProjects_iff g p).mp (hh τ g ((isVNP_iff g).mpr hg))
+ · rintro ⟨hp, hh⟩
+ refine ⟨(isVNP_iff p).mpr hp, fun τ _ g hg => ?_⟩
+ exact (pProjects_iff g p).mpr (hh τ g ((isVNP_iff g).mp hg))
+
+/-- Over every field of characteristic different from two, the permanent is VNP-complete. -/
+theorem permanent_complete (F : Type*) [Field F] (hchar : ringChar F ≠ 2) :
+ VNPComplete (permanent F) :=
+ (complete_iff _).mpr (VPVNP.permanent_vnpComplete F (ringChar F) hchar)
+
+end Valiant.Project
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Valiant/ProjectCircuitEquiv.lean b/lean/OAI/Computability/VPVNP/Valiant/ProjectCircuitEquiv.lean
new file mode 100644
index 0000000000..8224887e12
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Valiant/ProjectCircuitEquiv.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.Valiant.ProjectModel
+import OAI.Computability.VPVNP.CircuitSize
+
+/-! # Exact circuit correspondence for the project permanent-completeness statement -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Valiant.Project
+
+open MvPolynomial (C X)
+
+variable {F σ : Type*} [Field F] {s k : ℕ}
+
+private abbrev available (v : Fin s → MvPolynomial σ F) (k : ℕ) (x : MvPolynomial σ F) : Prop :=
+ (∃ j : σ, X j = x) ∨ (∃ a : F, C a = x) ∨ ∃ j : Fin s, j.val < k ∧ v j = x
+
+private abbrev prefixValues (v : Fin s → MvPolynomial σ F) (hk : k ≤ s) (i : Fin k) :=
+ v (i.castLE hk)
+
+private abbrev gateValue (allowed : MvPolynomial σ F → Prop) (x : MvPolynomial σ F) : Prop :=
+ ∃ a b, allowed a ∧ allowed b ∧ (x = a + b ∨ x = a - b ∨ x = a * b)
+
+private theorem available_iff_ref (v : Fin s → MvPolynomial σ F) (hk : k ≤ s)
+ (x : MvPolynomial σ F) :
+ available v k x ↔ ∃ r : Ref F σ k, r.read C X (prefixValues v hk) = x := by
+ constructor
+ · rintro (⟨j, rfl⟩ | ⟨c, rfl⟩ | ⟨j, hj, rfl⟩)
+ · exact ⟨.var j, rfl⟩
+ · exact ⟨.const c, rfl⟩
+ · exact ⟨.gate ⟨j, hj⟩, rfl⟩
+ · rintro ⟨r, rfl⟩
+ cases r with
+ | var j => exact Or.inl ⟨j, rfl⟩
+ | const c => exact Or.inr (Or.inl ⟨c, rfl⟩)
+ | gate j => exact Or.inr (Or.inr ⟨j.castLE hk, j.isLt, rfl⟩)
+
+private theorem gateValue_iff (v : Fin s → MvPolynomial σ F) (hk : k ≤ s)
+ (x : MvPolynomial σ F) :
+ gateValue (available v k) x ↔ ∃ op : BinOp, ∃ a b : Ref F σ k,
+ op.apply (a.read C X (prefixValues v hk)) (b.read C X (prefixValues v hk)) = x := by
+ constructor
+ · rintro ⟨a, b, ha, hb, hx⟩
+ obtain ⟨ra, rfl⟩ := (available_iff_ref v hk a).mp ha
+ obtain ⟨rb, rfl⟩ := (available_iff_ref v hk b).mp hb
+ rcases hx with rfl | rfl | rfl
+ · exact ⟨.add, ra, rb, rfl⟩
+ · exact ⟨.sub, ra, rb, rfl⟩
+ · exact ⟨.mul, ra, rb, rfl⟩
+ · rintro ⟨op, a, b, rfl⟩
+ refine ⟨_, _, (available_iff_ref v hk _).mpr ⟨a, rfl⟩,
+ (available_iff_ref v hk _).mpr ⟨b, rfl⟩, ?_⟩
+ cases op with
+ | add => exact Or.inl rfl
+ | sub => exact Or.inr (Or.inl rfl)
+ | mul => exact Or.inr (Or.inr rfl)
+
+private theorem run_snoc_last (q : Program F σ s) (op : BinOp) (a b : Ref F σ s) :
+ (q.snoc op a b).run C X (Fin.last s) =
+ op.apply (a.read C X (q.run C X)) (b.read C X (q.run C X)) := by
+ simp only [Program.run, Fin.lastCases_last]
+
+private theorem run_snoc_castSucc (q : Program F σ s) (op : BinOp) (a b : Ref F σ s)
+ (i : Fin s) : (q.snoc op a b).run C X i.castSucc = q.run C X i := by
+ simp only [Program.run, Fin.lastCases_castSucc]
+
+/-- Build a program for a prefix without duplicating any of its referenced gates. -/
+private theorem realize_prefix (v : Fin s → MvPolynomial σ F)
+ (h : ∀ i : Fin s, gateValue (available v i.val) (v i)) (k : ℕ) (hk : k ≤ s) :
+ ∃ q : Program F σ k, q.run C X = prefixValues v hk := by
+ induction k with
+ | zero => exact ⟨.nil, Subsingleton.elim _ _⟩
+ | succ k ih =>
+ obtain ⟨q, hq⟩ := ih (Nat.le_of_succ_le hk)
+ let i : Fin s := ⟨k, hk⟩
+ obtain ⟨op, a, b, hop⟩ := (gateValue_iff v (Nat.le_of_succ_le hk) (v i)).mp (h i)
+ refine ⟨q.snoc op a b, ?_⟩
+ funext j
+ refine Fin.lastCases ?_ (fun j => ?_) j
+ · rw [run_snoc_last, hq]
+ exact hop
+ · rw [run_snoc_castSucc]
+ exact congrFun hq j
+
+/-- Reading a program as a table recovers legal operands at every position. -/
+private theorem program_gate (q : Program F σ s) (i : Fin s) :
+ gateValue (available (q.run C X) i.val) (q.run C X i) := by
+ induction q with
+ | nil => exact i.elim0
+ | @snoc s q op a b ih =>
+ let v := q.run C X
+ let v' := (q.snoc op a b).run C X
+ have previous (k : ℕ) (hk : k ≤ s) :
+ prefixValues v' (Nat.le_succ_of_le hk) = prefixValues v hk := by
+ funext j
+ exact run_snoc_castSucc q op a b (j.castLE hk)
+ cases i using Fin.lastCases with
+ | last =>
+ apply (gateValue_iff v' (Nat.le_succ s) _).mpr
+ refine ⟨op, a, b, ?_⟩
+ rw [previous s le_rfl]
+ exact (run_snoc_last q op a b).symm
+ | cast j =>
+ obtain ⟨op', a', b', hj⟩ := (gateValue_iff v j.isLt.le _).mp (ih j)
+ apply (gateValue_iff v' (Nat.le_succ_of_le j.isLt.le) _).mpr
+ refine ⟨op', a', b', ?_⟩
+ rw [previous j.val j.isLt.le]
+ exact hj.trans (run_snoc_castSucc q op a b j).symm
+
+/-- The self-contained table model and the project's exact circuits compute precisely
+the same formal polynomials with exactly the same number of binary gates. -/
+theorem computes_iff {s : ℕ} {p : MvPolynomial σ F} :
+ Computes s p ↔ ∃ c : VPVNP.Circuit F σ s, c.polynomial = p := by
+ constructor
+ · rintro ⟨v, hout, h⟩
+ obtain ⟨q, hq⟩ := realize_prefix v h s le_rfl
+ obtain ⟨r, hr⟩ := (available_iff_ref v le_rfl p).mp hout
+ refine ⟨⟨q, r⟩, ?_⟩
+ change r.read C X (q.run C X) = p
+ rwa [hq]
+ · rintro ⟨c, rfl⟩
+ exact ⟨c.program.run C X, (available_iff_ref _ le_rfl _).mpr ⟨c.output, rfl⟩,
+ program_gate c.program⟩
+
+end Valiant.Project
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/Valiant/ProjectModel.lean b/lean/OAI/Computability/VPVNP/Valiant/ProjectModel.lean
new file mode 100644
index 0000000000..d84b27b362
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/Valiant/ProjectModel.lean
@@ -0,0 +1,68 @@
+import Mathlib.Algebra.MvPolynomial.Degrees
+import Mathlib.Algebra.MvPolynomial.Eval
+import Mathlib.Algebra.CharP.Basic
+import Mathlib.LinearAlgebra.Matrix.Permanent
+
+/-! # Permanent completeness for exact arithmetic circuits -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Valiant.Project
+
+open scoped Classical
+
+/-- A table of `s` binary gates computes `p`. Variables and scalars are free, and the
+output and later gates may reuse any previously available value. -/
+def Computes {F σ : Type*} [Field F] (s : ℕ) (p : MvPolynomial σ F) : Prop :=
+ ∃ v : Fin s → MvPolynomial σ F,
+ let available (k : ℕ) (x : MvPolynomial σ F) :=
+ (∃ j : σ, MvPolynomial.X j = x) ∨ (∃ a : F, MvPolynomial.C a = x) ∨
+ ∃ j : Fin s, j.val < k ∧ v j = x
+ available s p ∧ ∀ i : Fin s, ∃ a b, available i.val a ∧ available i.val b ∧
+ (v i = a + b ∨ v i = a - b ∨ v i = a * b)
+
+/-- A polynomial bound uniform in all sufficiently large indices. -/
+def PolynomiallyBounded (f : ℕ → ℕ) : Prop := ∃ A d N : ℕ, ∀ n ≥ N, f n ≤ A * n ^ d
+
+/-- At each index a family has its own finite type of indeterminates. -/
+abbrev Family (F : Type*) [Field F] (σ : ℕ → Type) := (n : ℕ) → MvPolynomial (σ n) F
+
+variable {F : Type*} [Field F] {σ τ : ℕ → Type} [∀ n, Fintype (σ n)]
+
+/-- Arity and total degree grow at most polynomially with the index. -/
+def PFamily (p : Family F σ) : Prop :=
+ PolynomiallyBounded (fun n => Fintype.card (σ n)) ∧
+ PolynomiallyBounded (fun n => (p n).totalDegree)
+
+/-- VP consists of polynomial families computed by polynomial-size exact circuits. -/
+def IsVP (p : Family F σ) : Prop :=
+ PFamily p ∧ ∃ s : ℕ → ℕ, PolynomiallyBounded s ∧ ∀ n, Computes (s n) (p n)
+
+/-- A VNP family sums a VP verifier over all Boolean assignments to its witness variables. -/
+def IsVNP (p : Family F σ) : Prop :=
+ PFamily p ∧ ∃ (W : ℕ → Type) (inst : ∀ n, Fintype (W n)) (g : Family F (fun n => σ n ⊕ W n)),
+ PolynomiallyBounded (fun n => @Fintype.card _ (inst n)) ∧ IsVP g ∧ ∀ n,
+ p n = ∑ y : W n → Bool, MvPolynomial.eval₂Hom MvPolynomial.C
+ (Sum.elim MvPolynomial.X (fun i => MvPolynomial.C (if y i then 1 else 0))) (g n)
+
+/-- A p-projection substitutes target variables or scalars at polynomially bounded indices. -/
+def PProjects (target : Family F τ) (source : Family F σ) : Prop :=
+ ∃ r : ℕ → ℕ, PolynomiallyBounded r ∧ ∀ n, ∃ φ : σ (r n) → τ n ⊕ F,
+ MvPolynomial.eval₂Hom MvPolynomial.C (fun i => (φ i).elim MvPolynomial.X MvPolynomial.C)
+ (source (r n)) = target n
+
+/-- Membership in VNP and hardness for every VNP family over the same field. -/
+def VNPComplete (p : Family F σ) : Prop :=
+ IsVNP p ∧ ∀ (τ : ℕ → Type) [∀ n, Fintype (τ n)] (g : Family F τ), IsVNP g → PProjects g p
+
+/-- The permanent of the generic square matrix of formal variables. -/
+noncomputable def permanent (F : Type*) [Field F] (n : ℕ) : MvPolynomial (Fin n × Fin n) F :=
+ Matrix.permanent (Matrix.of fun i j => MvPolynomial.X (i, j))
+
+end Valiant.Project
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierCircuit.lean b/lean/OAI/Computability/VPVNP/VerifierCircuit.lean
new file mode 100644
index 0000000000..b9787d3371
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierCircuit.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.VPVNP.VerifierSummand
+import OAI.Computability.VPVNP.VerifierWeight
+
+/-!
+# Exact circuit and degree bounds for the §1.1 summand
+
+The transcript check has eight arithmetic gates per Boolean gate, plus the
+acceptance indicator. The selector product uses four operations per input bit
+and one multiplication into the running product. All the bounds refer to the
+unspecialized summand as a formal polynomial.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Verifier
+
+open MvPolynomial
+
+variable {R : Type*} [CommRing R] {n t g : ℕ}
+
+private def selectorFormula (j : Fin n) : Formula R (Variables n t g) :=
+ let x := Formula.var (Sum.inr (Sum.inl (Sum.inl j)))
+ (((Formula.const 1).sub x).mul (.var (.inl (j, false)))).add (x.mul (.var (.inl (j, true))))
+
+/-- Arithmetic formula for the unspecialized summand. -/
+noncomputable def summandFormula (c : BooleanTranscript.Circuit (Inputs n t) g) :
+ Formula R (Variables n t g) :=
+ (c.weightFormula (fun i => .inr (.inl i)) (fun i => .inr (.inr i))).mul
+ (Formula.prod selectorFormula)
+
+theorem polynomial_summandFormula (c : BooleanTranscript.Circuit (Inputs n t) g) :
+ (summandFormula (R := R) c).polynomial = summand c := by
+ unfold summandFormula summand
+ change _ * (Formula.prod _).polynomial = _
+ rw [Formula.polynomial_prod]
+ congr 1
+ exact c.eval_weightFormula _ _ MvPolynomial.C MvPolynomial.X
+
+theorem size_summandFormula_le (c : BooleanTranscript.Circuit (Inputs n t) g) :
+ (summandFormula (R := R) c).size ≤ 8 * g + 5 * n + 2 := by
+ have h := c.size_weightFormula_le (R := R)
+ (fun i => Sum.inr (Sum.inl i) : Inputs n t → Variables n t g)
+ (fun i => Sum.inr (Sum.inr i))
+ simp [summandFormula, Formula.size, selectorFormula]
+ omega
+
+theorem degree_summandFormula_le (c : BooleanTranscript.Circuit (Inputs n t) g) :
+ (summandFormula (R := R) c).degree ≤ 3 * g + 2 * n + 1 := by
+ have h := c.degree_weightFormula_le (R := R)
+ (fun i => Sum.inr (Sum.inl i) : Inputs n t → Variables n t g)
+ (fun i => Sum.inr (Sum.inr i))
+ simp [summandFormula, Formula.degree, selectorFormula]
+ omega
+
+theorem totalDegree_summand_le (c : BooleanTranscript.Circuit (Inputs n t) g) :
+ (summand (R := R) c).totalDegree ≤ 3 * g + 2 * n + 1 := by
+ rw [← polynomial_summandFormula]
+ exact (Formula.totalDegree_le _).trans (degree_summandFormula_le _)
+
+/-- The local checks and selectors admit an exact circuit over every coefficient ring. -/
+theorem exists_circuit_summand (c : BooleanTranscript.Circuit (Inputs n t) g) :
+ ∃ m ≤ 8 * g + 5 * n + 2, ∃ d : Circuit R (Variables n t g) m, d.polynomial = summand c :=
+ ⟨_, size_summandFormula_le _, (summandFormula c).compile,
+ (Formula.compile_polynomial _).trans (polynomial_summandFormula _)⟩
+
+end Verifier
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierFamily.lean b/lean/OAI/Computability/VPVNP/VerifierFamily.lean
new file mode 100644
index 0000000000..48beaa5cba
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierFamily.lean
@@ -0,0 +1,21 @@
+import OAI.Computability.VPVNP.VerifierMembership
+import OAI.Computability.VPVNP.VerifierMachine
+
+/-! # VNP membership of the integer family of Theorem 1.1 -/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+/-- Equation (1.1), interpreted as a formal polynomial family over any field, lies in
+VNP. The Boolean witnesses are the input word, the canonical path choices and the
+gate values of the compiled verifier for the encoded transition table. -/
+theorem P_isVNP (F : Type*) [Field F] :
+ IsVNP (σ := fun n => Fin n × Bool) (fun n => MvPolynomial.map (Int.castRingHom F) (P n)) :=
+ Verifier.P_isVNP_of_verifier VerifierMachine.verifierCircuit
+ VerifierMachine.verifierSize_polynomiallyBounded
+ (fun _ x w => VerifierMachine.verifierCircuit_eval x w)
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierFormula.lean b/lean/OAI/Computability/VPVNP/VerifierFormula.lean
new file mode 100644
index 0000000000..c684e61a6d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierFormula.lean
@@ -0,0 +1,130 @@
+import OAI.Computability.VPVNP.CircuitComposition
+import Mathlib.Algebra.MvPolynomial.CommRing
+import Mathlib.Data.Fintype.BigOperators
+
+/-!
+# Arithmetic formulas for Boolean witness verification
+
+Formulas give explicit circuits for products of local constraints in a VNP summand.
+Compilation uses one gate per binary node, including products of constants.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+variable {R σ A ι : Type*}
+
+/-- An arithmetic formula with scalar and variable leaves. -/
+inductive Formula (R σ : Type*) where
+ | const : R → Formula R σ
+ | var : σ → Formula R σ
+ | bin : BinOp → Formula R σ → Formula R σ → Formula R σ
+
+namespace Formula
+
+/-- Form a binary addition node with summands `a` and `b`. -/
+abbrev add (a b : Formula R σ) := bin .add a b
+/-- Form a binary subtraction node with minuend `a` and subtrahend `b`. -/
+abbrev sub (a b : Formula R σ) := bin .sub a b
+/-- Form a binary multiplication node with factors `a` and `b` in that order. -/
+abbrev mul (a b : Formula R σ) := bin .mul a b
+
+/-- Gate count excludes scalar and variable leaves. -/
+def size : Formula R σ → ℕ
+ | .const _ | .var _ => 0
+ | .bin _ a b => a.size + b.size + 1
+
+/-- Syntactic degree bounds the degree of the formal polynomial even after cancellation. -/
+def degree : Formula R σ → ℕ
+ | .const _ => 0
+ | .var _ => 1
+ | .bin .add a b | .bin .sub a b => max a.degree b.degree
+ | .bin .mul a b => a.degree + b.degree
+
+/-- Evaluate a formula in the ring `A`, interpreting each constant with `s`, each variable with
+`x`, and each binary node by its ring operation. -/
+def eval [Ring A] (s : R → A) (x : σ → A) : Formula R σ → A
+ | .const r => s r
+ | .var i => x i
+ | .bin op a b => op.apply (a.eval s x) (b.eval s x)
+
+/-- The formal multivariate polynomial represented by a formula over a commutative ring,
+interpreting constants by `MvPolynomial.C` and variables by `MvPolynomial.X`. -/
+noncomputable def polynomial [CommRing R] (f : Formula R σ) : MvPolynomial σ R :=
+ f.eval MvPolynomial.C MvPolynomial.X
+
+/-- Compile the formula to a straight-line program of exactly its binary node count. -/
+def compile : (f : Formula R σ) → Circuit R σ f.size
+ | .const r => ⟨.nil, .const r⟩
+ | .var i => ⟨.nil, .var i⟩
+ | .bin op a b => Circuit.combine op a.compile b.compile
+
+theorem compile_eval [Ring A] (f : Formula R σ) (s : R → A) (x : σ → A) :
+ f.compile.eval s x = f.eval s x := by
+ induction f with
+ | const | var => rfl
+ | bin op a b ha hb =>
+ exact (Circuit.eval_combine op a.compile b.compile s x).trans (congrArg₂ op.apply ha hb)
+
+@[simp] theorem compile_polynomial [CommRing R] (f : Formula R σ) :
+ f.compile.polynomial = f.polynomial := compile_eval _ _ _
+
+theorem totalDegree_le [CommRing R] (f : Formula R σ) : f.polynomial.totalDegree ≤ f.degree := by
+ induction f with
+ | const r => simp [polynomial, eval, degree]
+ | var i =>
+ rcases subsingleton_or_nontrivial R with h | h
+ · have he : (var i : Formula R σ).polynomial = 0 := Subsingleton.elim _ _
+ simp [he]
+ · simp [polynomial, eval, degree]
+ | bin op a b ha hb =>
+ cases op with
+ | add => exact (MvPolynomial.totalDegree_add _ _).trans (max_le_max ha hb)
+ | sub => exact (MvPolynomial.totalDegree_sub _ _).trans (max_le_max ha hb)
+ | mul => exact (MvPolynomial.totalDegree_mul _ _).trans (Nat.add_le_add ha hb)
+
+/-- Product of a finite family of formulas, starting with a scalar one. -/
+noncomputable def prod [Fintype ι] [One R] (f : ι → Formula R σ) : Formula R σ :=
+ Finset.univ.toList.foldr (fun i acc => mul (f i) acc) (.const 1)
+
+@[simp] theorem size_prod [Fintype ι] [One R] (f : ι → Formula R σ) :
+ (prod f).size = (∑ i, (f i).size) + Fintype.card ι := by
+ have aux (l : List ι) :
+ (l.foldr (fun i acc => mul (f i) acc) (.const 1)).size =
+ (l.map (fun i => (f i).size)).sum + l.length := by
+ induction l with
+ | nil => rfl
+ | cons i l ih => simp [size, ih, Nat.add_assoc]
+ simp [prod, aux, Finset.sum_map_toList, Finset.length_toList]
+
+@[simp] theorem degree_prod [Fintype ι] [One R] (f : ι → Formula R σ) :
+ (prod f).degree = ∑ i, (f i).degree := by
+ have aux (l : List ι) :
+ (l.foldr (fun i acc => mul (f i) acc) (.const 1)).degree =
+ (l.map (fun i => (f i).degree)).sum := by
+ induction l with
+ | nil => rfl
+ | cons i l ih => simp [degree, ih]
+ simp [prod, aux, Finset.sum_map_toList]
+
+theorem eval_prod [Fintype ι] [One R] [CommRing A] (f : ι → Formula R σ)
+ (s : R → A) (x : σ → A) (hs : s 1 = 1) :
+ (prod f).eval s x = ∏ i, (f i).eval s x := by
+ have aux (l : List ι) :
+ (l.foldr (fun i acc => mul (f i) acc) (.const 1)).eval s x =
+ (l.map (fun i => (f i).eval s x)).prod := by
+ induction l with
+ | nil => exact hs
+ | cons i l ih => simp [eval, BinOp.apply, ih]
+ simp [prod, aux, Finset.prod_map_toList]
+
+@[simp] theorem polynomial_prod [Fintype ι] [CommRing R] (f : ι → Formula R σ) :
+ (prod f).polynomial = ∏ i, (f i).polynomial :=
+ eval_prod f MvPolynomial.C MvPolynomial.X (map_one _)
+
+end Formula
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachine.lean b/lean/OAI/Computability/VPVNP/VerifierMachine.lean
new file mode 100644
index 0000000000..c95ef674d3
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachine.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.VPVNP.VerifierMachineDecodeNetwork
+import OAI.Computability.VPVNP.VerifierMachineInitial
+import OAI.Computability.VPVNP.VerifierMachineIteration
+import OAI.Computability.VPVNP.VerifierMachineSplice
+import OAI.Computability.VPVNP.PolynomialBounds
+
+/-!
+# Boolean circuits for the coefficient verifier
+
+The input consists of the word and one choice bit per clock tick. The first circuit
+decodes the transition table from the word. The next layer initializes the tape windows,
+and the simulation applies one transition per choice bit. This gives a polynomial-size
+Boolean verifier for the coefficients in equation (1.1).
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierMachine
+
+open UniversalMachine VerifierMachineDecode VerifierMachineIteration VerifierNetwork
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit (Expr.eval Expr.size)
+
+private abbrev Inputs (n T : ℕ) := Fin n ⊕ Fin T
+private abbrev Decoded (n T : ℕ) := Inputs n T ⊕ DecoderWire n
+
+private noncomputable def parseInputs (n T : ℕ) : Frame (Inputs n T) (Decoded n T) :=
+ ((decoder n).subst (Frame.initial Sum.inl)).withInput
+
+private def initExpr (n T : ℕ) : Slice n T T → Expr (Decoded n T)
+ | .inl i => .input (.inl i)
+ | .inr (.inl d) => .input (.inr d)
+ | .inr (.inr j) => initialRegisterExpr (fun i => .inl (.inl i)) (.inr .empty) j
+
+private noncomputable def initialFrame (n T : ℕ) : Frame (Inputs n T) (Slice n T T) :=
+ (parseInputs n T).step (initExpr n T)
+
+private theorem wordInputs_eval {n T : ℕ} (x : Fin n → Bool) (w : Fin T → Bool) :
+ (Frame.initial Sum.inl : Frame (Inputs n T) (Fin n)).eval (Sum.elim x w) = x := by
+ funext i
+ simp
+
+private theorem initialize_decoder {n T : ℕ} (x : Fin n → Bool) (w : Fin T → Bool)
+ (d : DecoderWire n) :
+ (initialFrame n T).eval (Sum.elim x w) (.inr (.inl d)) = (decoder n).eval x d := by
+ simp [initialFrame, initExpr, Expr.eval, parseInputs, wordInputs_eval]
+
+private theorem initialize_size_le (n T : ℕ) :
+ (initialFrame n T).size ≤ (decoder n).size + Fintype.card (Slice n T T) * 2 := by
+ have h := Frame.step_size_le (parseInputs n T) (initExpr n T) 2 (by
+ rintro (i | d | j)
+ · exact Nat.le_succ _
+ · exact Nat.le_succ _
+ · dsimp only [initExpr]
+ exact initialRegisterExpr_size_le _ _ j)
+ simpa [initialFrame, parseInputs] using h
+
+/-- The final Boolean circuit checks that the literal program is valid and that its
+canonical path choices end in acceptance after the universal clock. -/
+noncomputable def verifierFrame (n : ℕ) : Frame (Inputs n (n ^ clockExponent)) Unit :=
+ accept (initialFrame n (n ^ clockExponent))
+
+theorem verifierFrame_eval {n : ℕ} (x : Fin n → Bool)
+ (w : Fin (n ^ clockExponent) → Bool) :
+ (verifierFrame n).eval (Sum.elim x w) () = verifiesInput x w := by
+ let T := n ^ clockExponent
+ unfold verifierFrame
+ simp only [verifiesInput]
+ cases hd : decode (List.ofFn x) with
+ | none =>
+ apply accept_eval_invalid
+ rw [initialize_decoder, Bool.eq_false_iff]
+ simp [decoder_eval_iff, hd]
+ | some p =>
+ have hv (q : DecoderWire n) : (decoder n).eval x q = true ↔ wireHolds p q := by
+ simp [decoder_eval_iff, hd]
+ have hp : p.extra ≤ n := by simpa using decoded_extra_le_length hd
+ rw [accept_eval_valid (initialFrame n T) (Sum.elim x w) p hp (windowInitial p T x) w]
+ · exact windowRun_acceptsChoices p T T le_rfl x w
+ · rw [initialize_decoder, hv]
+ trivial
+ · intro i b k
+ rw [initialize_decoder, hv]
+ · intro j
+ rw [initialFrame, Frame.step_eval]
+ dsimp only [initExpr]
+ apply initialRegisterExpr_eval _ _ _ x p
+ · intro i
+ simp [parseInputs]
+ · simp only [parseInputs, Frame.withInput_eval_inr, Frame.subst_eval, wordInputs_eval]
+ exact Bool.eq_iff_iff.mpr (by simpa [wireHolds] using hv .empty)
+ · intro i
+ simp [initialFrame, initExpr, Expr.eval, parseInputs]
+
+/-- Size of the compiled verifier, counting binary AND and unary NOT gates. -/
+noncomputable def verifierSize (n : ℕ) := (verifierFrame n).circuitSize ()
+
+/-- The single-output Boolean circuit on the input bits and its canonical path-choice bits. -/
+noncomputable def verifierCircuit (n : ℕ) :
+ BooleanTranscript.Circuit (Fin n ⊕ Fin (n ^ clockExponent)) (verifierSize n) :=
+ (verifierFrame n).circuit ()
+
+theorem verifierCircuit_eval {n : ℕ} (x : Fin n → Bool)
+ (w : Fin (n ^ clockExponent) → Bool) :
+ (verifierCircuit n).eval (Sum.elim x w) = verifiesInput x w :=
+ (Frame.circuit_eval ..).trans (verifierFrame_eval x w)
+
+theorem verifierFrame_polynomiallyBounded : PolynomiallyBounded (fun n => (verifierFrame n).size) := by
+ let t (n : ℕ) := n ^ clockExponent
+ have ht : PolynomiallyBounded t := PolynomiallyBounded.id.pow _
+ have h₂ : PolynomiallyBounded (fun n => n + 2) := PolynomiallyBounded.id.add (.const 2)
+ have hcard : PolynomiallyBounded (fun n => Fintype.card (Slice n (t n) (t n))) := by
+ simp only [card_slice]
+ have table := (PolynomiallyBounded.const 2).add
+ (((((PolynomiallyBounded.const 9).mul .id).mul (.const 2)).mul h₂).mul (.const 81))
+ have cells := ((PolynomiallyBounded.const 2).mul ht).add (.const 1)
+ have tapes := (PolynomiallyBounded.const 2).mul (cells.mul (.const 3))
+ exact (PolynomiallyBounded.id.add ht).add (table.add (h₂.add tapes))
+ have hdecode := (PolynomiallyBounded.const 6000000000).mul (PolynomiallyBounded.succ.pow 9)
+ have hinit : PolynomiallyBounded (fun n => (initialFrame n (t n)).size) :=
+ (hdecode.add (hcard.mul (.const 2))).of_le (fun n => (initialize_size_le n (t n)).trans
+ (Nat.add_le_add_right (decoder_size_le n) _))
+ have hstep := (PolynomiallyBounded.const 1000000).mul (h₂.pow 2)
+ exact
+ ((hinit.add (ht.mul (hcard.mul hstep))).add (.const 3)).of_le
+ (fun n => accept_size_le (initialFrame n (t n)))
+
+theorem verifierSize_polynomiallyBounded : PolynomiallyBounded verifierSize :=
+ ((PolynomiallyBounded.const 4).mul verifierFrame_polynomiallyBounded).of_le
+ (fun n => (verifierFrame n).circuitSize_le ())
+
+end VerifierMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineCell.lean b/lean/OAI/Computability/VPVNP/VerifierMachineCell.lean
new file mode 100644
index 0000000000..adfd368c90
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineCell.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.BinPacking.CookLevin.ConfigIndex
+import OAI.Computability.VPVNP.VerifierMachineSimulation
+
+/-!
+# One tape cell in the Boolean coefficient verifier
+
+For a fixed candidate move, the destination reads a blank at the boundary, the written
+symbol at the old head, and the old symbol at every other source. A disjunction over the
+three moves selects this candidate, and a multiplexer preserves the tape on halted branches.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+
+variable {ι : Type*} {r : ℕ}
+
+/-- The symbol bit at a destination for a fixed candidate move. -/
+private def movedCell (old : WindowCell r → Symbol → Expr ι) (write : Symbol → Expr ι)
+ (d : Fin 3) (i : WindowCell r) (s : Symbol) : Expr ι :=
+ match shiftSource d i with
+ | none => .const (decide ((0 : Symbol) = s))
+ | some j => if j = windowCenter r then write s else old j s
+
+/-- The new one-hot bit for symbol `s` at tape cell `i`. -/
+def cellNext (old : WindowCell r → Symbol → Expr ι) (present : Expr ι)
+ (write move : Fin 3 → Expr ι) (i : WindowCell r) (s : Symbol) : Expr ι :=
+ Expr.mux present
+ (Expr.disjoin (List.ofFn fun d => Expr.and (move d) (movedCell old write d i s)))
+ (old i s)
+
+theorem cellNext_eval_none (old : WindowCell r → Symbol → Expr ι) (present : Expr ι)
+ (write move : Fin 3 → Expr ι) (i : WindowCell r) (s : Symbol) (x : ι → Bool)
+ (hp : present.eval x = false) :
+ (cellNext old present write move i s).eval x = (old i s).eval x := by
+ simp [cellNext, hp]
+
+private theorem movedCell_eval (old : WindowCell r → Symbol → Expr ι)
+ (write : Symbol → Expr ι) (d : Fin 3) (i : WindowCell r) (s : Symbol)
+ (x : ι → Bool) (tape : WindowTape r) (w : Symbol)
+ (ho : ∀ j a, (old j a).eval x = decide (tape j = a))
+ (hw : ∀ a, (write a).eval x = decide (w = a)) :
+ (movedCell old write d i s).eval x = decide (windowUpdate tape w d i = s) := by
+ cases h : shiftSource d i with
+ | none => simp [movedCell, windowUpdate, h, Expr.eval]
+ | some j =>
+ by_cases hc : j = windowCenter r <;> simp [movedCell, windowUpdate, h, hc, ho, hw]
+
+theorem cellNext_eval_some (old : WindowCell r → Symbol → Expr ι) (present : Expr ι)
+ (write move : Fin 3 → Expr ι) (i : WindowCell r) (s : Symbol) (x : ι → Bool)
+ (tape : WindowTape r) (w d : Fin 3)
+ (hp : present.eval x = true)
+ (ho : ∀ j a, (old j a).eval x = decide (tape j = a))
+ (hw : ∀ a, (write a).eval x = decide (w = a))
+ (hm : ∀ k, (move k).eval x = decide (d = k)) :
+ (cellNext old present write move i s).eval x = decide (windowUpdate tape w d i = s) := by
+ simp only [cellNext, Expr.eval_mux, hp, ite_true]
+ apply Bool.eq_iff_iff.mpr
+ simp only [Expr.eval_disjoin_true, List.mem_ofFn, exists_exists_eq_and, Expr.eval,
+ Bool.and_eq_true, hm, decide_eq_true_eq, movedCell_eval old write _ i s x tape w ho hw]
+ simp
+
+theorem cellNext_size_le (old : WindowCell r → Symbol → Expr ι) (present : Expr ι)
+ (write move : Fin 3 → Expr ι) (i : WindowCell r) (s : Symbol) (C : ℕ)
+ (ho : ∀ j a, (old j a).size ≤ C) (hp : present.size ≤ C)
+ (hw : ∀ a, (write a).size ≤ C) (hm : ∀ k, (move k).size ≤ C) :
+ (cellNext old present write move i s).size ≤ 12 * (C + 1) := by
+ have hpos := present.size_pos
+ have hcell (d : Fin 3) : (movedCell old write d i s).size ≤ C := by
+ unfold movedCell
+ split
+ · simp only [Expr.size]
+ omega
+ · split <;> first | exact hw s | exact ho _ s
+ have hall := Expr.size_disjoin_le
+ (List.ofFn fun d => Expr.and (move d) (movedCell old write d i s)) (2 * C + 1) (by
+ intro e he
+ obtain ⟨d, rfl⟩ := List.mem_ofFn.mp he
+ simp only [Expr.size]
+ have := hcell d
+ have := hm d
+ omega)
+ simp only [List.length_ofFn] at hall
+ simp only [cellNext, Expr.mux, Expr.size]
+ have := ho i s
+ omega
+
+end UniversalMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineCook.lean b/lean/OAI/Computability/VPVNP/VerifierMachineCook.lean
new file mode 100644
index 0000000000..d6efe8b96e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineCook.lean
@@ -0,0 +1,191 @@
+import OAI.Computability.BinPacking.CookLevin.ConfigIndex
+import OAI.Computability.VPVNP.BooleanTranscript
+
+/-!
+# Boolean circuits for the gate-transcript verifier
+
+The Cook–Levin compiler uses numbered wires and the AND/OR/NOT basis.
+Translate its output to the AND/NOT basis of the VNP transcript construction,
+with a bound of four gates per original gate and arbitrary input pinning.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace CookCircuit
+
+open BinPackingGames.Foundations.Complexity
+
+variable {σ : Type*}
+
+/-- The translated program and the current translation of each source wire. -/
+private structure Builder (σ : Type*) where
+ size : ℕ
+ program : BooleanTranscript.Program σ size
+ wire : ℕ → Ref Bool σ size
+
+private def Builder.read (b : Builder σ) (x : σ → Bool) (i : ℕ) : Bool :=
+ (b.wire i).read id x (b.program.run x)
+
+private theorem read_ref (b : Builder σ) (x : σ → Bool) (i : ℕ) :
+ (b.wire i).read id x (b.program.run x) = b.read x i := rfl
+
+private def weaken {n : ℕ} : Ref Bool σ n → Ref Bool σ (n + 1)
+ | .const v => .const v
+ | .var i => .var i
+ | .gate i => .gate i.castSucc
+
+private theorem read_weaken {n : ℕ} (r : Ref Bool σ n) (x : σ → Bool)
+ (v : Fin n → Bool) (w : Bool) :
+ (weaken r).read id x (Fin.snoc v w) = r.read id x v := by
+ cases r <;> simp [weaken, Ref.read]
+
+/-- Write one translated gate at the specified source-wire address. -/
+private def emit (b : Builder σ) (i : ℕ) (g : BooleanTranscript.Gate σ b.size) :
+ Builder σ where
+ size := b.size + 1
+ program := b.program.snoc g
+ wire := Function.update (fun j => weaken (b.wire j)) i (.gate (Fin.last b.size))
+
+private theorem emit_read_self (b : Builder σ) (i : ℕ) (g : BooleanTranscript.Gate σ b.size)
+ (x : σ → Bool) : (emit b i g).read x i = g.eval x (b.program.run x) := by
+ simp [emit, Builder.read, Ref.read, BooleanTranscript.Program.run]
+
+private theorem emit_read_other (b : Builder σ) (i j : ℕ) (h : j ≠ i)
+ (g : BooleanTranscript.Gate σ b.size) (x : σ → Bool) :
+ (emit b i g).read x j = b.read x j := by
+ simp [emit, Builder.read, Function.update_of_ne h, BooleanTranscript.Program.run, read_weaken]
+
+/-- Temporary wires of the De Morgan expansion lie above every live source wire. -/
+private def next (b : Builder σ) (i : ℕ) : CookLevin.Gate → Builder σ
+ | .const v => { b with wire := Function.update b.wire i (.const v) }
+ | .not a => emit b i (.not (b.wire a))
+ | .and a c => emit b i (.and (b.wire a) (b.wire c))
+ | .or a c =>
+ let p := emit b (i + 1) (.not (b.wire a))
+ let q := emit p (i + 2) (.not (p.wire c))
+ let r := emit q (i + 3) (.and (q.wire (i + 1)) (q.wire (i + 2)))
+ emit r i (.not (r.wire (i + 3)))
+
+private theorem next_read_other (b : Builder σ) (g : CookLevin.Gate) (x : σ → Bool)
+ {i j : ℕ} (hj : j < i) : (next b i g).read x j = b.read x j := by
+ have h0 : j ≠ i := Nat.ne_of_lt hj
+ have h1 : j ≠ i + 1 := by omega
+ have h2 : j ≠ i + 2 := by omega
+ have h3 : j ≠ i + 3 := by omega
+ cases g with
+ | const v => simp [next, Builder.read, Function.update_of_ne h0]
+ | not a | and a c | or a c =>
+ simp only [next, emit_read_other _ _ _ h0, emit_read_other _ _ _ h1,
+ emit_read_other _ _ _ h2, emit_read_other _ _ _ h3]
+
+private theorem next_read_self (b : Builder σ) (g : CookLevin.Gate) (x : σ → Bool)
+ (i : ℕ) (hg : g.Bounded i) : (next b i g).read x i = g.eval (b.read x) := by
+ cases g with
+ | const v => simp [next, Builder.read, Ref.read, CookLevin.Gate.eval]
+ | not a | and a c =>
+ rw [next, emit_read_self]
+ rfl
+ | or a c =>
+ have hc : c < i := hg.2
+ have h1 : c ≠ i + 1 := by omega
+ have h2 : i + 1 ≠ i + 2 := by omega
+ simp only [next, emit_read_self, BooleanTranscript.Gate.eval, CookLevin.Gate.eval,
+ read_ref, emit_read_other _ _ _ h2, emit_read_other _ _ _ h1]
+ cases b.read x a <;> cases b.read x c <;> rfl
+
+private theorem next_size_le (b : Builder σ) (i : ℕ) (g : CookLevin.Gate) :
+ (next b i g).size ≤ b.size + 4 := by
+ cases g <;> simp only [next, emit] <;> omega
+
+private def compile (start : ℕ) (b : Builder σ) : List CookLevin.Gate → Builder σ
+ | [] => b
+ | g :: gs => compile (start + 1) (next b start g) gs
+
+private theorem compile_size_le (gs : List CookLevin.Gate) (start : ℕ) (b : Builder σ) :
+ (compile start b gs).size ≤ b.size + 4 * gs.length := by
+ induction gs generalizing start b with
+ | nil => simp [compile]
+ | cons g gs ih =>
+ have h := ih (start + 1) (next b start g)
+ have h' := next_size_le b start g
+ simp only [compile, List.length_cons]
+ omega
+
+private theorem compile_correct (gs : List CookLevin.Gate) (start : ℕ) (b : Builder σ)
+ (h : CookLevin.Ordered start gs) (x : σ → Bool) (A : ℕ → Bool)
+ (ha : ∀ j < start, b.read x j = A j) :
+ ∀ j < start + gs.length, (compile start b gs).read x j = CookLevin.run start gs A j := by
+ induction gs generalizing start b A with
+ | nil => simpa [compile, CookLevin.run] using ha
+ | cons g gs ih =>
+ obtain ⟨hg, hgs⟩ := (CookLevin.ordered_cons _ _ _).mp h
+ apply fun j hj => ih (start + 1) (next b start g) hgs
+ (Function.update A start (g.eval A)) ?_ j (by simp only [List.length_cons] at hj; omega)
+ intro j hj
+ by_cases he : j = start
+ · subst j
+ rw [Function.update_self, next_read_self _ _ _ _ hg]
+ exact CookLevin.Gate.eval_congr _ hg _ _ ha
+ · rw [Function.update_of_ne he, next_read_other _ _ _ (by omega)]
+ exact ha _ (by omega)
+
+/-- Each primary source input can be either an input variable or a Boolean constant. -/
+private def initial {n : ℕ} (pins : Fin n → σ ⊕ Bool) : Builder σ where
+ size := 0
+ program := .nil
+ wire j := if hj : j < n then (pins ⟨j, hj⟩).elim .var .const else .const false
+
+/-- Size of the compiled AND/NOT verifier circuit. -/
+def transcriptSize (C : CookLevin.Circuit) : ℕ :=
+ (compile C.inputs (initial (fun i : Fin C.inputs => Sum.inl i)) C.gates).size
+
+private theorem compile_size_eq {τ : Type*} (gs : List CookLevin.Gate) (start : ℕ)
+ (b : Builder σ) (c : Builder τ) (h : b.size = c.size) :
+ (compile start b gs).size = (compile start c gs).size := by
+ induction gs generalizing start b c with
+ | nil => exact h
+ | cons g gs ih =>
+ apply ih
+ cases g <;> simp only [next, emit, h]
+
+/-- Compile an ordered Boolean circuit while substituting inputs or constants. -/
+def toTranscriptWith (C : CookLevin.Circuit) (pins : Fin C.inputs → σ ⊕ Bool) :
+ BooleanTranscript.Circuit σ (transcriptSize C) :=
+ let b := compile C.inputs (initial pins) C.gates
+ let he : b.size = transcriptSize C := compile_size_eq C.gates _ _ _ rfl
+ he ▸ (⟨b.program, b.wire C.output⟩ : BooleanTranscript.Circuit σ b.size)
+
+private theorem eval_cast {n m : ℕ} (h : n = m) (c : BooleanTranscript.Circuit σ n)
+ (x : σ → Bool) : ((h ▸ c : BooleanTranscript.Circuit σ m).eval x) = c.eval x := by
+ cases h
+ rfl
+
+/-- Input pinning and gate translation agree with ordinary Boolean evaluation on every input. -/
+theorem toTranscriptWith_eval (C : CookLevin.Circuit) (pins : Fin C.inputs → σ ⊕ Bool)
+ (x : σ → Bool) :
+ (toTranscriptWith C pins).eval x = C.eval (fun i => (pins i).elim x id) := by
+ have hc := compile_correct C.gates C.inputs (initial pins) C.ordered x
+ (CookLevin.inputEnv (fun i => (pins i).elim x id)) (by
+ intro j hj
+ cases hh : pins ⟨j, hj⟩ <;> simp [initial, Builder.read, CookLevin.inputEnv, hj, hh, Ref.read])
+ C.output C.output.isLt
+ exact (eval_cast _ _ x).trans hc
+
+/-- Translate with all primary inputs free. -/
+def toTranscript (C : CookLevin.Circuit) : BooleanTranscript.Circuit (Fin C.inputs) (transcriptSize C) :=
+ toTranscriptWith C Sum.inl
+
+theorem toTranscript_eval (C : CookLevin.Circuit) (x : Fin C.inputs → Bool) :
+ (toTranscript C).eval x = C.eval x := toTranscriptWith_eval C Sum.inl x
+
+theorem toTranscript_size_le (C : CookLevin.Circuit) : transcriptSize C ≤ 4 * C.gates.length := by
+ simpa [transcriptSize, initial] using
+ compile_size_le C.gates C.inputs (initial (fun i : Fin C.inputs => Sum.inl i))
+
+end CookCircuit
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineDecodeCanonical.lean b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeCanonical.lean
new file mode 100644
index 0000000000..f5fa190344
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeCanonical.lean
@@ -0,0 +1,204 @@
+import OAI.Computability.VPVNP.UniversalMachine
+
+/-!
+# Recognizing the program prefix
+
+A successful decode consumes exactly the canonical prefix of the returned machine. The length of
+that prefix bounds the state space to be represented by a verifier on a fixed input length.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+open private readUnary readFields decodeTable readRows
+ readInstruction readBranch checkFin from OAI.Computability.VPVNP.UniversalMachine
+
+private theorem readUnary_canonical {input rest : Word} {k : ℕ}
+ (h : readUnary input = some (k, rest)) : input = unary k ++ rest := by
+ induction input generalizing k rest with
+ | nil => simp [readUnary] at h
+ | cons b xs ih =>
+ cases b with
+ | false =>
+ simp [readUnary] at h
+ obtain ⟨rfl, rfl⟩ := h
+ rfl
+ | true =>
+ obtain ⟨⟨j, ys⟩, hj, heq⟩ := Option.map_eq_some_iff.mp h
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj heq
+ rw [ih hj]
+ rfl
+
+private theorem readFields_canonical {input : Word} {fields : List ℕ}
+ (h : readFields input = some fields) : input = fields.flatMap unary := by
+ induction input generalizing fields with
+ | nil =>
+ simp [readFields] at h
+ subst fields
+ rfl
+ | cons b xs ih =>
+ cases b with
+ | false =>
+ obtain ⟨ys, hy, rfl⟩ := Option.map_eq_some_iff.mp h
+ rw [ih hy]
+ rfl
+ | true =>
+ simp only [readFields] at h
+ obtain ⟨ks, hk, heq⟩ := Option.bind_eq_some_iff.mp h
+ cases ks with
+ | nil => contradiction
+ | cons j ys =>
+ change some ((j + 1) :: ys) = some fields at heq
+ obtain rfl := Option.some.inj heq
+ rw [ih hk]
+ rfl
+
+private theorem checkFin_canonical {m k : ℕ} {a : Fin m} (h : checkFin m k = some a) :
+ k = a.val := by
+ unfold checkFin at h
+ split at h
+ · obtain rfl := Option.some.inj h
+ rfl
+ · contradiction
+
+private theorem readInstruction_canonical {extra : ℕ} {xs tail : List ℕ} {a : Instruction extra}
+ (h : readInstruction extra xs = some (a, tail)) : xs = instructionFields a ++ tail := by
+ unfold readInstruction at h
+ split at h
+ · obtain ⟨target, hq, h⟩ := Option.bind_eq_some_iff.mp h
+ obtain ⟨first, hx, h⟩ := Option.bind_eq_some_iff.mp h
+ obtain ⟨move₁, hu, h⟩ := Option.bind_eq_some_iff.mp h
+ obtain ⟨second, hy, h⟩ := Option.bind_eq_some_iff.mp h
+ obtain ⟨move₂, hv, eq⟩ := Option.bind_eq_some_iff.mp h
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj eq)
+ simp [instructionFields, checkFin_canonical hq, checkFin_canonical hx,
+ checkFin_canonical hu, checkFin_canonical hy, checkFin_canonical hv]
+ · contradiction
+
+private theorem readBranch_canonical {extra : ℕ} {xs tail : List ℕ} {b : Branches extra}
+ (h : readBranch extra xs = some (b, tail)) : xs = branchFields b ++ tail := by
+ unfold readBranch at h
+ split at h
+ · obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj h)
+ rfl
+ · obtain ⟨⟨a, rest⟩, ha, heq⟩ := Option.bind_eq_some_iff.mp h
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj heq)
+ rw [readInstruction_canonical ha]
+ rfl
+ · obtain ⟨⟨a, rest⟩, ha, hs⟩ := Option.bind_eq_some_iff.mp h
+ obtain ⟨⟨c, last⟩, hc, heq⟩ := Option.bind_eq_some_iff.mp hs
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj heq)
+ rw [readInstruction_canonical ha, readInstruction_canonical hc]
+ simp [branchFields, List.append_assoc]
+ · contradiction
+
+private theorem readRows_canonical {extra count : ℕ} {xs tail : List ℕ} {bs : List (Branches extra)}
+ (h : readRows extra count xs = some (bs, tail)) : xs = bs.flatMap branchFields ++ tail := by
+ induction count generalizing xs bs with
+ | zero =>
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj h)
+ rfl
+ | succ count ih =>
+ obtain ⟨⟨b, rest⟩, hb, hs⟩ := Option.bind_eq_some_iff.mp h
+ obtain ⟨⟨rows, last⟩, hr, heq⟩ := Option.bind_eq_some_iff.mp hs
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj (Option.some.inj heq)
+ rw [readBranch_canonical hb, ih hr]
+ simp [List.flatMap_cons, List.append_assoc]
+
+
+private theorem decodeTable_canonical {bits : Word} {p : Program}
+ (h : decodeTable bits = some p) : bits = tableBits p := by
+ obtain ⟨fields, hfields, heq⟩ := Option.bind_eq_some_iff.mp h
+ rw [readFields_canonical hfields]
+ cases fields with
+ | nil =>
+ change some emptyProgram = some p at heq
+ obtain rfl := Option.some.inj heq
+ rfl
+ | cons k xs =>
+ obtain ⟨⟨rows, tail⟩, hrows, hp⟩ := Option.bind_eq_some_iff.mp heq
+ cases tail with
+ | cons _ _ => contradiction
+ | nil =>
+ change (if h : rows.length = (k + 1) * 9 then some ⟨k + 1, rows, h⟩ else none) =
+ some p at hp
+ split at hp
+ · obtain rfl := Option.some.inj hp
+ simpa [tableBits] using congrArg (fun ns => (k :: ns).flatMap unary)
+ (readRows_canonical hrows)
+ · contradiction
+
+/-- An input successfully decodes to a given program exactly when it begins with that program's
+self-delimiting code. -/
+theorem decode_eq_some_iff {input : Word} {p : Program} :
+ decode input = some p ↔ ∃ payload, input = programPrefix p ++ payload := by
+ constructor
+ · intro h
+ obtain ⟨⟨len, rest⟩, hlen, hp⟩ := Option.bind_eq_some_iff.mp h
+ change (if len ≤ rest.length then decodeTable (rest.take len) else none) = some p at hp
+ split at hp
+ next hle =>
+ have ht := decodeTable_canonical hp
+ have hl : (tableBits p).length = len := by simp [← ht, hle]
+ refine ⟨rest.drop len, ?_⟩
+ rw [readUnary_canonical hlen, programPrefix, hl, List.append_assoc, ← ht,
+ List.take_append_drop]
+ next => contradiction
+ · rintro ⟨payload, rfl⟩
+ exact decode_programPrefix p payload
+
+private theorem row_fields_length {extra : ℕ} (rows : List (Branches extra)) :
+ rows.length ≤ (rows.flatMap branchFields).length := by
+ induction rows with
+ | nil => rfl
+ | cons b bs ih =>
+ simp only [List.flatMap_cons, List.length_append, List.length_cons]
+ have hb : 1 ≤ (branchFields b).length := by cases b <;> simp [branchFields]
+ omega
+
+private theorem unary_fields_length (fields : List ℕ) :
+ fields.length ≤ (fields.flatMap unary).length := by
+ induction fields with
+ | nil => rfl
+ | cons k fields ih =>
+ simp only [List.flatMap_cons, List.length_cons, List.length_append, unary,
+ List.length_replicate]
+ change _ ≤ k + 1 + _
+ omega
+
+/-- A nonempty table spends one unary bit per running state in its header and at least nine bits
+per running state on its rows. The empty table satisfies the same bound. -/
+theorem tableBits_length_ge (p : Program) : 10 * p.extra ≤ (tableBits p).length := by
+ by_cases h : p.extra = 0
+ · simp [h]
+ · have h₁ := row_fields_length p.rows
+ have h₂ := unary_fields_length (p.rows.flatMap branchFields)
+ rw [p.rows_length] at h₁
+ simp only [tableBits, ite_eq_right h, List.flatMap_cons, List.length_append, unary,
+ List.length_replicate]
+ change _ ≤ p.extra - 1 + 1 + _
+ omega
+
+/-- A decoded program occupies a unary-framed prefix of length at least twenty bits per running
+state, plus the terminator. -/
+theorem decoded_state_bound {p : Program} {input : Word} (h : decode input = some p) :
+ 20 * p.extra + 1 ≤ input.length := by
+ obtain ⟨payload, rfl⟩ := decode_eq_some_iff.mp h
+ have htable := tableBits_length_ge p
+ simp only [List.length_append, programPrefix, unary, List.length_replicate]
+ change _ ≤ (tableBits p).length + 1 + (tableBits p).length + payload.length
+ omega
+
+theorem decoded_extra_le_length {p : Program} {input : Word} (h : decode input = some p) :
+ p.extra ≤ input.length := by
+ have := decoded_state_bound h
+ omega
+
+end UniversalMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineDecodeFinish.lean b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeFinish.lean
new file mode 100644
index 0000000000..fcc9ca477d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeFinish.lean
@@ -0,0 +1,73 @@
+import OAI.Computability.VPVNP.VerifierMachineDecodeLanguage
+import OAI.Computability.VPVNP.VerifierMachineDecodeCanonical
+
+/-!
+# Correctness of the completed row scan
+
+The final endpoint has to agree with both the number of bits actually scanned and the outer
+unary length. Together these checks identify exactly the canonical prefix of a valid machine.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierMachineDecode
+
+open UniversalMachine
+
+private theorem header_rows (len : ℕ) (p : Program) :
+ header len p.extra ++ p.rows.flatMap rowBits = unary len ++ tableBits p := by
+ by_cases h : p.extra = 0
+ · have hrows : p.rows = [] := List.length_eq_zero_iff.mp (by simp [p.rows_length, h])
+ simp [header, h, hrows, tableBits]
+ · simp [header, h, tableBits_rows p h, List.append_assoc]
+
+private theorem length_programPrefix (p : Program) :
+ (programPrefix p).length = 2 * (tableBits p).length + 1 := by
+ simp [programPrefix, unary]
+ omega
+
+/-- Finishing at the end of the announced table length is equivalent to successful decoding
+of a program satisfying the requested wire. -/
+theorem finished_iff {n : ℕ} (x : Fin n → Bool) (q : DecoderWire n) :
+ (∃ len extra : Fin (n + 1), queryAllowed q extra ∧ ∃ pos : Fin (n + 1),
+ pos.val = 2 * len.val + 1 ∧ Reach (List.ofFn x) q len extra (9 * n) pos) ↔
+ ∃ p, decode (List.ofFn x) = some p ∧ wireHolds p q := by
+ constructor
+ · rintro ⟨len, extra, hq, pos, hend, rows, hcount, hkeep, hpos, hmatch⟩
+ have he : extra.val ≤ n := Nat.lt_succ_iff.mp extra.isLt
+ have hr : rows.length = extra.val * 9 := by
+ rw [hcount, min_eq_right (Nat.mul_le_mul_left 9 he), Nat.mul_comm]
+ let p : Program := ⟨extra.val, rows, hr⟩
+ have hword : header len extra ++ rows.flatMap rowBits = unary len ++ tableBits p :=
+ header_rows len p
+ rw [hword, List.length_append] at hpos
+ have hul : (unary len).length = len.val + 1 := by simp [unary]
+ have hlen : len.val = (tableBits p).length := by omega
+ rw [hword, hlen] at hmatch
+ obtain ⟨_, payload, hp⟩ := (matchAt_iff_drop _ _ _).mp hmatch
+ exact ⟨p, decode_eq_some_iff.mpr ⟨payload, by simpa [programPrefix] using hp⟩,
+ (query_iff q p).mpr ⟨hq, hkeep⟩⟩
+ · rintro ⟨p, hd, hq⟩
+ obtain ⟨payload, hinput⟩ := decode_eq_some_iff.mp hd
+ have hprefix : (programPrefix p).length ≤ n := by
+ have h := congrArg List.length hinput
+ simp only [List.length_ofFn, List.length_append] at h
+ omega
+ have hbits : (tableBits p).length ≤ n := by rw [length_programPrefix] at hprefix; omega
+ have he : p.extra ≤ n := by simpa using decoded_extra_le_length hd
+ obtain ⟨hallowed, hkeep⟩ := (query_iff q p).mp hq
+ refine ⟨⟨_, Nat.lt_succ_of_le hbits⟩, ⟨_, Nat.lt_succ_of_le he⟩, hallowed,
+ ⟨_, Nat.lt_succ_of_le hprefix⟩, length_programPrefix p, p.rows, ?_, hkeep, ?_, ?_⟩
+ · rw [p.rows_length, min_eq_right (Nat.mul_le_mul_left 9 he), Nat.mul_comm]
+ · rw [header_rows]
+ rfl
+ · rw [header_rows]
+ exact ⟨[], payload, hinput, rfl⟩
+
+end VerifierMachineDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineDecodeLanguage.lean b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeLanguage.lean
new file mode 100644
index 0000000000..232132694b
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeLanguage.lean
@@ -0,0 +1,97 @@
+import OAI.Computability.VPVNP.VerifierMachineDecodeRows
+import OAI.Computability.VPVNP.VerifierMachineDecodeWire
+
+/-!
+# A dynamic program for reading the table
+
+Fix the declared table length and the number of running states. After reading each row,
+the parser marks the offsets at which the first rows could have ended. A requested slot
+constrains just the indexed row. After the prescribed number of rows the marks stay fixed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierMachineDecode
+
+open UniversalMachine
+
+/-- Bits preceding the rows of a nonempty table, or the length field for an empty one. -/
+def header (len extra : ℕ) : Word :=
+ unary len ++ if extra = 0 then [] else unary (extra - 1)
+
+theorem header_length (len extra : ℕ) : (header len extra).length = len + 1 + extra := by
+ cases extra <;> simp [header, unary, Nat.add_assoc]
+ omega
+
+private theorem rowsKeep_snoc {n extra : ℕ} (q : DecoderWire n)
+ (rows : List (Branches extra)) (b : Branches extra) :
+ RowsKeep q (rows ++ [b]) ↔ RowsKeep q rows ∧ keepRow q rows.length b = true := by
+ constructor
+ · intro h
+ refine ⟨?_, h rows.length b (by simp)⟩
+ intro i b' hi
+ exact h i b' (by rw [List.getElem?_append_left (List.getElem?_eq_some_iff.mp hi).1, hi])
+ · rintro ⟨h, hlast⟩ i b' hi
+ by_cases hlt : i < rows.length
+ · exact h i b' (by rwa [List.getElem?_append_left hlt] at hi)
+ · have hib := (List.getElem?_eq_some_iff.mp hi).1
+ simp only [List.length_append, List.length_singleton] at hib
+ have heq : i = rows.length := by omega
+ subst i
+ simp only [List.getElem?_concat_length, Option.some.injEq] at hi
+ exact hi ▸ hlast
+
+/-- Position reached by the first `min t (9*extra)` rows, when their bits agree with the input. -/
+def Reach {n : ℕ} (input : Word) (q : DecoderWire n) (len extra t pos : ℕ) : Prop :=
+ ∃ rows : List (Branches extra), rows.length = min t (9 * extra) ∧ RowsKeep q rows ∧
+ pos = (header len extra ++ rows.flatMap rowBits).length ∧
+ MatchAt input 0 (header len extra ++ rows.flatMap rowBits)
+
+theorem Reach_zero {n : ℕ} {input : Word} (q : DecoderWire n) (len extra pos : ℕ) :
+ Reach input q len extra 0 pos ↔
+ pos = (header len extra).length ∧ MatchAt input 0 (header len extra) := by
+ simp [Reach, RowsKeep]
+
+theorem Reach_succ_of_le {n : ℕ} {input : Word} (q : DecoderWire n) (len extra t pos : ℕ)
+ (h : 9 * extra ≤ t) :
+ Reach input q len extra (t+1) pos ↔ Reach input q len extra t pos := by
+ simp only [Reach, min_eq_right h, min_eq_right (Nat.le_succ_of_le h)]
+
+theorem Reach_succ_of_lt {n : ℕ} {input : Word} (q : DecoderWire n) (len extra t pos : ℕ)
+ (h : t < 9 * extra) :
+ Reach input q len extra (t+1) pos ↔
+ ∃ (b : Branches extra) (i : Fin (input.length+1)),
+ keepRow q t b = true ∧ Reach input q len extra t i.val ∧
+ i.val + (rowBits b).length = pos ∧ MatchAt input i.val (rowBits b) := by
+ simp only [Reach, min_eq_left (Nat.succ_le_of_lt h), min_eq_left h.le]
+ constructor
+ · rintro ⟨allRows, hlen, hkeep, hpos, hword⟩
+ obtain rfl | ⟨rows, b, rfl⟩ := List.eq_nil_or_concat' allRows
+ · simp at hlen
+ simp only [List.length_append, List.length_singleton] at hlen
+ have hlen : rows.length = t := by omega
+ obtain ⟨hrows, hb⟩ := (rowsKeep_snoc q rows b).mp hkeep
+ let prefixWord := header len extra ++ rows.flatMap rowBits
+ have he : header len extra ++ (rows ++ [b]).flatMap rowBits = prefixWord ++ rowBits b := by
+ simp [prefixWord, List.flatMap_append, List.append_assoc]
+ rw [he] at hpos hword
+ obtain ⟨hp, hm⟩ := (matchAt_append_iff input 0 prefixWord (rowBits b)).mp hword
+ have hbound := hp.end_le
+ exact ⟨b, ⟨prefixWord.length, by omega⟩, hlen ▸ hb, ⟨rows, hlen, hrows, rfl, hp⟩,
+ by simpa using hpos.symm, by simpa using hm⟩
+ · rintro ⟨b, i, hb, ⟨rows, hlen, hrows, hi, hp⟩, hpos, hm⟩
+ let prefixWord := header len extra ++ rows.flatMap rowBits
+ have he : header len extra ++ (rows ++ [b]).flatMap rowBits = prefixWord ++ rowBits b := by
+ simp [prefixWord, List.flatMap_append, List.append_assoc]
+ refine ⟨rows ++ [b], by simp [hlen], (rowsKeep_snoc q rows b).mpr ⟨hrows, hlen ▸ hb⟩, ?_, ?_⟩
+ · rw [he, List.length_append, ← hpos, hi]
+ · apply (he ▸ (matchAt_append_iff input 0 prefixWord (rowBits b))).mpr
+ exact ⟨hp, by simpa [hi, prefixWord] using hm⟩
+
+end VerifierMachineDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineDecodeMatch.lean b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeMatch.lean
new file mode 100644
index 0000000000..51665a8575
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeMatch.lean
@@ -0,0 +1,100 @@
+import OAI.Computability.BinPacking.CookLevin.ConfigIndex
+import OAI.Computability.VPVNP.UniversalMachine
+
+/-!
+# Literal substring tests for the universal machine
+
+The table interpreter tests an encoded field or row at a specified position
+in its input. Every bit is checked by an input literal. An empty word can match
+at the end of the input, and any test that extends past the input fails.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierMachineDecode
+
+open UniversalMachine
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+
+private def literal {n : ℕ} (i : Fin n) (b : Bool) : Expr (Fin n) :=
+ if b then .input i else .not (.input i)
+
+private theorem eval_literal {n : ℕ} (x : Fin n → Bool) (i : Fin n) (b : Bool) :
+ (literal i b).eval x = true ↔ x i = b := by
+ cases b <;> simp [literal, Expr.eval]
+
+/-- Conjunction of the literals of `word`, starting at zero-based position `j`. -/
+def matchAt (n j : ℕ) : Word → Expr (Fin n)
+ | [] => .const (decide (j ≤ n))
+ | b :: word =>
+ if hj : j < n then .and (literal ⟨j, hj⟩ b) (matchAt n (j + 1) word)
+ else .const false
+
+theorem eval_matchAt_drop {n : ℕ} (x : Fin n → Bool) (j : ℕ) (word : Word) :
+ (matchAt n j word).eval x = true ↔ j ≤ n ∧ ∃ t, (List.ofFn x).drop j = word ++ t := by
+ induction word generalizing j with
+ | nil => simp [matchAt, Expr.eval]
+ | cons b word ih =>
+ by_cases hj : j < n
+ · have hj' : j < (List.ofFn x).length := by simpa using hj
+ rw [List.drop_eq_getElem_cons hj']
+ simp [matchAt, Expr.eval, hj, eval_literal, ih, hj.le, Nat.succ_le_of_lt hj]
+ · have hd : (List.ofFn x).drop j = [] :=
+ List.drop_eq_nil_of_le (by simpa using Nat.le_of_not_gt hj)
+ simp [matchAt, hj, Expr.eval, hd]
+
+/-- The input contains `word` after a prefix of length `j`. -/
+def MatchAt (input : Word) (j : ℕ) (word : Word) : Prop :=
+ ∃ s t, input = s ++ word ++ t ∧ s.length = j
+
+theorem matchAt_iff_drop (input : Word) (j : ℕ) (word : Word) :
+ MatchAt input j word ↔ j ≤ input.length ∧ ∃ t, input.drop j = word ++ t := by
+ constructor
+ · rintro ⟨s, t, rfl, rfl⟩
+ exact ⟨by simp, t, by simp [List.append_assoc]⟩
+ · rintro ⟨hj, t, ht⟩
+ exact ⟨input.take j, t, by rw [List.append_assoc, ← ht, List.take_append_drop],
+ by simp [hj]⟩
+
+theorem MatchAt.end_le {input word : Word} {j : ℕ} (h : MatchAt input j word) :
+ j + word.length ≤ input.length := by
+ obtain ⟨s, t, rfl, rfl⟩ := h
+ simp
+
+/-- Matching two adjacent words is equivalent to matching their concatenation. -/
+theorem matchAt_append_iff (input : Word) (j : ℕ) (a b : Word) :
+ MatchAt input j (a ++ b) ↔ MatchAt input j a ∧ MatchAt input (j + a.length) b := by
+ constructor
+ · rintro ⟨s, t, rfl, rfl⟩
+ exact ⟨⟨s, b ++ t, by simp [List.append_assoc], rfl⟩,
+ ⟨s ++ a, t, by simp [List.append_assoc], by simp⟩⟩
+ · rintro ⟨⟨s, rest, rfl, rfl⟩, hb⟩
+ obtain ⟨_, t, ht⟩ := (matchAt_iff_drop _ _ _).mp hb
+ have hrest : rest = b ++ t := by
+ rw [← List.length_append, List.drop_left] at ht
+ exact ht
+ exact ⟨s, t, by simp [hrest, List.append_assoc], rfl⟩
+
+/-- Acceptance is exactly occurrence of the specified word after a prefix of length `j`. -/
+theorem eval_matchAt {n : ℕ} (x : Fin n → Bool) (j : ℕ) (word : Word) :
+ (matchAt n j word).eval x = true ↔ MatchAt (List.ofFn x) j word := by
+ rw [eval_matchAt_drop, matchAt_iff_drop, List.length_ofFn]
+
+/-- Each bit contributes at most an input node, a negation, and a conjunction. -/
+theorem size_matchAt (n j : ℕ) (word : Word) :
+ (matchAt n j word).size ≤ 3 * word.length + 1 := by
+ induction word generalizing j with
+ | nil => simp [matchAt, Expr.size]
+ | cons b word ih =>
+ specialize ih (j + 1)
+ by_cases hj : j < n
+ · cases b <;> simp [matchAt, hj, literal, Expr.size] <;> omega
+ · simp [matchAt, hj, Expr.size]
+
+end VerifierMachineDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineDecodeNetwork.lean b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeNetwork.lean
new file mode 100644
index 0000000000..333894c3dd
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeNetwork.lean
@@ -0,0 +1,199 @@
+import OAI.Computability.VPVNP.VerifierMachineDecodeFinish
+import OAI.Computability.VPVNP.VerifierMachineNetwork
+
+/-!
+# Boolean circuit for decoding a literal transition table
+
+The circuit simultaneously tests candidate lengths and state counts. For each output
+query it stores a bit at each possible endpoint of the prefix parsed so far. One
+layer consumes a complete transition row. Once a candidate has consumed all its
+rows, later layers copy its bits. The final disjunction checks the endpoint against
+the outer length header.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierMachineDecode
+
+open UniversalMachine
+open VerifierNetwork (Frame)
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+
+private abbrev Offset (n : ℕ) := Fin (n + 1)
+
+private abbrev DecodeState (n : ℕ) :=
+ Fin n ⊕ (DecoderWire n × Offset n × Offset n × Offset n)
+
+private def beginExpr (n : ℕ) : DecodeState n → Expr (Fin n)
+ | .inl i => .input i
+ | .inr (_, len, extra, pos) =>
+ if pos.val = (header len extra).length then matchAt n 0 (header len extra) else .const false
+
+private noncomputable def nextExpr (n t : ℕ) : DecodeState n → Expr (DecodeState n)
+ | .inl i => .input (.inl i)
+ | .inr (q, len, extra, pos) =>
+ if t < 9 * extra.val then
+ (rowStep n extra pos (keepRow q t)).rename
+ (Sum.elim Sum.inl (fun i => .inr (q, len, extra, i)))
+ else .input (.inr (q, len, extra, pos))
+
+private noncomputable def parse (n t : ℕ) : Frame (Fin n) (DecodeState n) :=
+ ((Frame.initial id).step (beginExpr n)).steps (nextExpr n) t
+
+private theorem parse_eval {n : ℕ} (x : Fin n → Bool) (t : ℕ) :
+ (∀ i, (parse n t).eval x (.inl i) = x i) ∧
+ (∀ (q : DecoderWire n) (len extra pos : Offset n),
+ (parse n t).eval x (.inr (q, len, extra, pos)) = true ↔
+ Reach (List.ofFn x) q len extra t pos) := by
+ induction t with
+ | zero =>
+ have hx : (Frame.initial id : Frame (Fin n) (Fin n)).eval x = x := by
+ funext i
+ simp
+ constructor
+ · intro i
+ simp [parse, beginExpr, Expr.eval, hx]
+ · intro q len extra pos
+ rw [Reach_zero]
+ by_cases hp : pos.val = (header len extra).length <;>
+ simp [parse, beginExpr, hp, hx, Expr.eval, eval_matchAt]
+ | succ t ih =>
+ have hstep : parse n (t + 1) = (parse n t).step (nextExpr n t) := rfl
+ constructor
+ · intro i
+ simpa [hstep, nextExpr, Expr.eval] using ih.1 i
+ · intro q len extra pos
+ rw [hstep, Frame.step_eval]
+ by_cases ht : t < 9 * extra.val
+ · have he : (fun i : Fin n ⊕ Offset n =>
+ (parse n t).eval x (Sum.elim Sum.inl (fun j => .inr (q, len, extra, j)) i)) =
+ Sum.elim x (fun j => (parse n t).eval x (.inr (q, len, extra, j))) := by
+ funext i
+ cases i with
+ | inl i => exact ih.1 i
+ | inr i => rfl
+ simp only [nextExpr, ite_eq_left ht, Expr.eval_rename, he, rowStep_eval, ih.2]
+ rw [Reach_succ_of_lt q len extra t pos ht]
+ constructor <;> rintro ⟨b, i, hb, hi, hp, hm⟩ <;>
+ exact ⟨b, ⟨i.val, by simpa using i.isLt⟩, hb, hi, hp, hm⟩
+ · simpa only [nextExpr, ite_eq_right ht, Expr.eval,
+ Reach_succ_of_le q len extra t pos (Nat.le_of_not_gt ht)] using ih.2 q len extra pos
+
+private def endpointExpr {n : ℕ} (q : DecoderWire n) :
+ Offset n × Offset n × Offset n → Expr (DecodeState n)
+ | (len, extra, pos) =>
+ if queryAllowed q extra ∧ pos.val = 2 * len.val + 1 then .input (.inr (q, len, extra, pos))
+ else .const false
+
+private noncomputable def finishExpr {n : ℕ} (q : DecoderWire n) : Expr (DecodeState n) :=
+ Expr.disjoin (Finset.univ.toList.map (endpointExpr q))
+
+private theorem finishExpr_eval {n : ℕ} (q : DecoderWire n) (s : DecodeState n → Bool) :
+ (finishExpr q).eval s = true ↔
+ ∃ len extra : Offset n, queryAllowed q extra ∧
+ ∃ pos : Offset n, pos.val = 2 * len.val + 1 ∧ s (.inr (q, len, extra, pos)) = true := by
+ simp only [finishExpr, Expr.eval_disjoin_true, List.mem_map, Finset.mem_toList,
+ Finset.mem_univ, true_and, exists_exists_eq_and]
+ constructor
+ · rintro ⟨⟨len, extra, pos⟩, h⟩
+ simp only [endpointExpr] at h
+ split at h
+ · rename_i hp
+ exact ⟨len, extra, hp.1, pos, hp.2, h⟩
+ · contradiction
+ · rintro ⟨len, extra, hq, pos, hp, h⟩
+ exact ⟨⟨len, extra, pos⟩, by simpa [endpointExpr, hq, hp, Expr.eval] using h⟩
+
+/-- Decode every output bit of the literal table from the same input fragment. -/
+noncomputable def decoder (n : ℕ) : Frame (Fin n) (DecoderWire n) :=
+ (parse n (9 * n)).step finishExpr
+
+/-- Every accepted bit describes the unique program parsed from the input. -/
+theorem decoder_eval_iff {n : ℕ} (x : Fin n → Bool) (q : DecoderWire n) :
+ (decoder n).eval x q = true ↔ ∃ p, decode (List.ofFn x) = some p ∧ wireHolds p q := by
+ simp only [decoder, Frame.step_eval, finishExpr_eval, (parse_eval x (9 * n)).2]
+ exact finished_iff x q
+
+private theorem beginExpr_size_le (n : ℕ) (i : DecodeState n) :
+ (beginExpr n i).size ≤ 8 * (n + 1) := by
+ rcases i with i | ⟨q, len, extra, pos⟩
+ · simp only [beginExpr, Expr.size]
+ omega
+ · simp only [beginExpr]
+ split
+ · have h := size_matchAt n 0 (header len extra)
+ rw [header_length] at h
+ have := len.isLt
+ have := extra.isLt
+ omega
+ · simp only [Expr.size]
+ omega
+
+private theorem nextExpr_size_le (n t : ℕ) (i : DecodeState n) :
+ (nextExpr n t i).size ≤ 200000 * (n + 1) ^ 3 := by
+ rcases i with i | ⟨q, len, extra, pos⟩
+ · simp only [nextExpr, Expr.size]
+ exact Nat.succ_le_of_lt (by positivity)
+ · simp only [nextExpr]
+ split
+ · rw [Expr.size_rename]
+ exact rowStep_size_le n extra pos (keepRow q t) (Nat.le_of_lt_succ extra.isLt)
+ · simp only [Expr.size]
+ exact Nat.succ_le_of_lt (by positivity)
+
+private theorem finishExpr_size_le {n : ℕ} (q : DecoderWire n) :
+ (finishExpr q).size ≤ 2 * (n + 1) ^ 3 + 1 := by
+ apply (Expr.size_disjoin_le _ 1 ?_).trans
+ · simp [Offset, pow_succ, Nat.mul_assoc, Nat.mul_comm]
+ · intro e he
+ obtain ⟨⟨len, extra, pos⟩, _, rfl⟩ := List.mem_map.mp he
+ simp only [endpointExpr]
+ split <;> simp [Expr.size]
+
+private theorem query_count_le (n : ℕ) :
+ Fintype.card (DecoderWire n) ≤ 2000 * (n + 1) ^ 2 := by
+ rw [decoderWire_card]
+ nlinarith [Nat.zero_le (n ^ 2)]
+
+private theorem parse_width_le (n : ℕ) :
+ Fintype.card (DecodeState n) ≤ 2001 * (n + 1) ^ 5 := by
+ simp only [DecodeState, Offset, Fintype.card_sum, Fintype.card_prod, Fintype.card_fin]
+ have hn : n ≤ (n + 1) ^ 5 := by
+ calc n ≤ n + 1 := by omega
+ _ ≤ (n + 1) ^ 5 := Nat.le_self_pow (by decide) _
+ calc
+ _ ≤ (n + 1) ^ 5 + 2000 * (n + 1) ^ 2 * ((n + 1) * ((n + 1) * (n + 1))) := by
+ gcongr
+ exact query_count_le n
+ _ = _ := by ring
+
+/-- The number of gates is polynomial even though the table is part of the input. -/
+theorem decoder_size_le (n : ℕ) : (decoder n).size ≤ 6000000000 * (n + 1) ^ 9 := by
+ let first := (Frame.initial id).step (beginExpr n)
+ have hfirst := Frame.step_size_le (Frame.initial id) (beginExpr n) _ (beginExpr_size_le n)
+ have hparse := Frame.steps_size_le first (nextExpr n) (9 * n) _
+ (fun t _ => nextExpr_size_le n t)
+ have hfinish := Frame.step_size_le (parse n (9 * n)) finishExpr _ finishExpr_size_le
+ change (decoder n).size ≤ (first.steps (nextExpr n) (9 * n)).size + _ at hfinish
+ rw [Frame.initial_size, Nat.zero_add] at hfirst
+ change first.size ≤ _ at hfirst
+ have hw := parse_width_le n
+ have hq := query_count_le n
+ calc
+ _ ≤ Fintype.card (DecodeState n) * (8 * (n + 1)) +
+ 9 * n * (Fintype.card (DecodeState n) * (200000 * (n + 1) ^ 3)) +
+ Fintype.card (DecoderWire n) * (2 * (n + 1) ^ 3 + 1) := by omega
+ _ ≤ 2001 * (n + 1) ^ 5 * (8 * (n + 1)) +
+ 9 * (n + 1) * (2001 * (n + 1) ^ 5 * (200000 * (n + 1) ^ 3)) +
+ 2000 * (n + 1) ^ 2 * (2 * (n + 1) ^ 3 + 1) := by
+ gcongr
+ omega
+ _ ≤ _ := by ring_nf; omega
+
+end VerifierMachineDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineDecodeRows.lean b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeRows.lean
new file mode 100644
index 0000000000..8acc362328
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeRows.lean
@@ -0,0 +1,102 @@
+import OAI.Computability.VPVNP.VerifierMachineDecodeMatch
+import OAI.Computability.VPVNP.VerifierMachineRowCount
+import Mathlib.Tactic.Ring
+
+/-!
+# One row of the table interpreter
+
+For each possible row ending at a specified input position, the expression
+tests its literal encoding and the preceding position's reachability wire.
+The row predicate can restrict the transition record for a particular lookup.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierMachineDecode
+
+open UniversalMachine
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+
+/-- Concatenated unary fields of one machine row, including the branch count. -/
+def rowBits {extra : ℕ} (b : Branches extra) : Word := (branchFields b).flatMap unary
+
+theorem tableBits_rows (p : Program) (h : p.extra ≠ 0) :
+ tableBits p = unary (p.extra - 1) ++ p.rows.flatMap rowBits := by
+ simp only [tableBits, ite_eq_right h, List.flatMap_cons, List.flatMap_assoc]
+ rfl
+
+private def rowStart {n : ℕ} (j : Fin (n + 1)) (len : ℕ) : Fin (n + 1) :=
+ ⟨j.val - len, lt_of_le_of_lt (Nat.sub_le ..) j.isLt⟩
+
+private def rowOption {n extra : ℕ} (j : Fin (n + 1)) (keep : Branches extra → Bool)
+ (b : Branches extra) : Expr (Fin n ⊕ Fin (n + 1)) :=
+ if keep b = true ∧ (rowBits b).length ≤ j.val then
+ let i := rowStart j (rowBits b).length
+ .and (.input (.inr i)) ((matchAt n i.val (rowBits b)).rename Sum.inl)
+ else .const false
+
+private theorem rowOption_eval {n extra : ℕ} (j : Fin (n + 1)) (keep : Branches extra → Bool)
+ (b : Branches extra) (x : Fin n → Bool) (prev : Fin (n + 1) → Bool) :
+ (rowOption j keep b).eval (Sum.elim x prev) = true ↔
+ ∃ i : Fin (n + 1), keep b = true ∧ prev i = true ∧
+ i.val + (rowBits b).length = j.val ∧ MatchAt (List.ofFn x) i.val (rowBits b) := by
+ by_cases h : keep b = true ∧ (rowBits b).length ≤ j.val
+ · simp only [rowOption, ite_eq_left h, Expr.eval, Sum.elim_inr, Expr.eval_rename, Sum.elim_inl,
+ Bool.and_eq_true, eval_matchAt]
+ constructor
+ · rintro ⟨hp, hm⟩
+ exact ⟨rowStart j _, h.1, hp, Nat.sub_add_cancel h.2, hm⟩
+ · rintro ⟨i, _, hp, hi, hm⟩
+ have e : i = rowStart j (rowBits b).length := Fin.ext (by change i.val = j.val - _; omega)
+ subst i
+ exact ⟨hp, hm⟩
+ · simp only [rowOption, ite_eq_right h, Expr.eval, Bool.false_eq_true, false_iff]
+ rintro ⟨i, hk, _, hi, _⟩
+ exact h ⟨hk, by omega⟩
+
+/-- Reachability of a row endpoint, using the previous layer's start-position wires. -/
+noncomputable def rowStep (n extra : ℕ) (j : Fin (n + 1)) (keep : Branches extra → Bool) :
+ Expr (Fin n ⊕ Fin (n + 1)) :=
+ Expr.disjoin (Finset.univ.toList.map (rowOption j keep))
+
+theorem rowStep_eval (n extra : ℕ) (j : Fin (n + 1)) (keep : Branches extra → Bool)
+ (x : Fin n → Bool) (prev : Fin (n + 1) → Bool) :
+ (rowStep n extra j keep).eval (Sum.elim x prev) = true ↔
+ ∃ (b : Branches extra) (i : Fin (n + 1)), keep b = true ∧ prev i = true ∧
+ i.val + (rowBits b).length = j.val ∧ MatchAt (List.ofFn x) i.val (rowBits b) := by
+ simp [rowStep, Expr.eval_disjoin_true, rowOption_eval]
+
+private theorem size_rowOption {n extra : ℕ} (j : Fin (n + 1)) (keep : Branches extra → Bool)
+ (b : Branches extra) : (rowOption j keep b).size ≤ 3 * n + 3 := by
+ unfold rowOption
+ split
+ · rename_i h
+ simp only [Expr.size, Expr.size_rename]
+ have := size_matchAt n (rowStart j (rowBits b).length).val (rowBits b)
+ have := j.isLt
+ omega
+ · simp [Expr.size]
+
+/-- The number of possible rows is quadratic in the number of states. Each literal
+test costs at most linearly many gates in the input length. -/
+theorem rowStep_size_le (n extra : ℕ) (j : Fin (n + 1)) (keep : Branches extra → Bool)
+ (h : extra ≤ n) : (rowStep n extra j keep).size ≤ 200000 * (n + 1) ^ 3 := by
+ unfold rowStep
+ have hb : ∀ e ∈ Finset.univ.toList.map (rowOption j keep), e.size ≤ 3 * n + 3 := by
+ intro e he
+ obtain ⟨b, _, rfl⟩ := List.mem_map.mp he
+ exact size_rowOption j keep b
+ have hs := Expr.size_disjoin_le _ _ hb
+ simp only [List.length_map, Finset.length_toList, Finset.card_univ, card_branches] at hs
+ calc
+ _ ≤ _ := hs
+ _ ≤ (1 + ((n + 2) * 81) + ((n + 2) * 81)^2) * (3 * n + 3 + 1) + 1 := by gcongr
+ _ ≤ _ := by ring_nf; omega
+
+end VerifierMachineDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineDecodeWire.lean b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeWire.lean
new file mode 100644
index 0000000000..1fd0b70382
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineDecodeWire.lean
@@ -0,0 +1,123 @@
+import OAI.Computability.VPVNP.UniversalMachine
+import Mathlib.Tactic.DeriveFintype
+import Mathlib.Data.Fintype.Prod
+import Mathlib.Data.Fintype.Sum
+import Mathlib.Data.Fintype.Sigma
+import Mathlib.Tactic.Ring
+
+/-!
+# The output wires of the coefficient machine's table decoder
+
+A wire can test validity, recognize the empty program, or request a specific instruction at a
+specific row and branch. A request records both tape updates and the target state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierMachineDecode
+
+open UniversalMachine
+
+/-- The target state and the two symbol-and-motion pairs tested by an instruction query at
+input length `n`. -/
+abbrev InstructionKey (n : ℕ) := Fin (n + 2) × Fin 3 × Fin 3 × Fin 3 × Fin 3
+
+/-- A decoder output testing validity, the empty program, or the instruction in a specific
+transition slot. -/
+inductive DecoderWire (n : ℕ)
+ | valid
+ | empty
+ | slot (row : Fin (9 * n)) (branch : Bool) (key : InstructionKey n)
+ deriving DecidableEq, Fintype
+
+theorem decoderWire_card (n : ℕ) :
+ Fintype.card (DecoderWire n) = 2 + 9 * n * 2 * (n + 2) * 81 := by
+ let e : DecoderWire n ≃ Unit ⊕ Unit ⊕ (Fin (9 * n) × Bool × InstructionKey n) :=
+ { toFun := fun | .valid => .inl () | .empty => .inr (.inl ())
+ | .slot i c k => .inr (.inr (i, c, k))
+ invFun := fun | .inl _ => .valid | .inr (.inl _) => .empty
+ | .inr (.inr (i, c, k)) => .slot i c k
+ left_inv := by intro q; cases q <;> rfl
+ right_inv := by rintro (_ | (_ | ⟨i,c,k⟩)) <;> rfl }
+ rw [Fintype.card_congr e]
+ simp [InstructionKey]
+ ring
+
+/-- Read one branch slot of a row. A one-branch row uses the false slot. -/
+def rowInstruction {extra : ℕ} : Branches extra → Bool → Option (Instruction extra)
+ | .stop, _ => none
+ | .one a, false => some a
+ | .one _, true => none
+ | .two a _, false => some a
+ | .two _ b, true => some b
+
+/-- The queried target, writes, and movements all agree with the literal instruction, comparing
+target indices by value. -/
+def KeyMatches {n extra : ℕ} (k : InstructionKey n) (a : Instruction extra) : Prop :=
+ a.target.val = k.1.val ∧ a.firstSymbol = k.2.1 ∧ a.firstMove = k.2.2.1 ∧
+ a.secondSymbol = k.2.2.2.1 ∧ a.secondMove = k.2.2.2.2
+
+instance {n extra : ℕ} (k : InstructionKey n) (a : Instruction extra) :
+ Decidable (KeyMatches k a) := inferInstanceAs (Decidable (_ ∧ _ ∧ _ ∧ _ ∧ _))
+
+/-- The predicate on a decoded program expressed by a particular decoder output wire. -/
+def wireHolds {n : ℕ} (p : Program) : DecoderWire n → Prop
+ | .valid => True
+ | .empty => p.extra = 0
+ | .slot i c k =>
+ ∃ row a, p.rows[i.val]? = some row ∧ rowInstruction row c = some a ∧ KeyMatches k a
+
+/-- The global check on the running state count for the requested output. -/
+def queryAllowed {n : ℕ} : DecoderWire n → ℕ → Prop
+ | .valid, _ => True
+ | .empty, extra => extra = 0
+ | .slot i _ _, extra => i.val < 9 * extra
+
+instance {n : ℕ} (q : DecoderWire n) (extra : ℕ) : Decidable (queryAllowed q extra) := by
+ cases q <;> unfold queryAllowed <;> infer_instance
+
+/-- Local constraint at the indexed row. -/
+def keepRow {n extra : ℕ} : DecoderWire n → ℕ → Branches extra → Bool
+ | .valid, _, _ | .empty, _, _ => true
+ | .slot i c k, j, b => if j = i.val then
+ (rowInstruction b c).any fun a => decide (KeyMatches k a)
+ else true
+
+/-- Every indexed row passes the requested decoder test, including the queried branch when its
+row is reached. -/
+def RowsKeep {n extra : ℕ} (q : DecoderWire n) (rows : List (Branches extra)) : Prop :=
+ ∀ (i : ℕ) (b : Branches extra), rows[i]? = some b → keepRow q i b = true
+
+theorem query_iff {n : ℕ} (q : DecoderWire n) (p : Program) :
+ wireHolds p q ↔ queryAllowed q p.extra ∧ RowsKeep q p.rows := by
+ cases q with
+ | valid | empty => simp [wireHolds, queryAllowed, RowsKeep, keepRow]
+ | slot i c k =>
+ constructor
+ · rintro ⟨b, a, hrow, ha, hk⟩
+ have hi : i.val < p.rows.length := (List.getElem?_eq_some_iff.mp hrow).1
+ refine ⟨by simpa [queryAllowed, p.rows_length, Nat.mul_comm] using hi, ?_⟩
+ intro j b' hb'
+ by_cases hj : j = i.val
+ · subst j
+ rw [hrow] at hb'
+ cases hb'
+ simp [keepRow, ha, hk]
+ · simp [keepRow, hj]
+ · rintro ⟨hi, h⟩
+ have hlen : i.val < p.rows.length := by simpa [queryAllowed, p.rows_length, Nat.mul_comm] using hi
+ let b := p.rows[i.val]
+ have hb : p.rows[i.val]? = some b := List.getElem?_eq_getElem hlen
+ have ha := h i.val b hb
+ cases hx : rowInstruction b c with
+ | none => simp [keepRow, hx] at ha
+ | some a =>
+ exact ⟨b, a, hb, hx, by simpa [keepRow, hx] using ha⟩
+
+end VerifierMachineDecode
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineInitial.lean b/lean/OAI/Computability/VPVNP/VerifierMachineInitial.lean
new file mode 100644
index 0000000000..59a56e263d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineInitial.lean
@@ -0,0 +1,72 @@
+import OAI.Computability.BinPacking.CookLevin.ConfigIndex
+import OAI.Computability.VPVNP.VerifierMachineSimulation
+
+/-!
+# Loading the coefficient machine's Boolean registers
+
+An initial state bit reads the decoder's empty-program flag or its complement.
+At a first-tape input position the symbol-two register reads the input bit, and
+the symbol-one register reads its complement.
+All other cells initially contain the blank symbol.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+
+variable {ι : Type*} {n r : ℕ}
+
+/-- Initialize each one-hot register using at most a single input and a negation. -/
+def initialRegisterExpr (input : Fin n → ι) (empty : ι) : WindowRegister n r → Expr ι
+ | .inl q =>
+ if 1 = q.val then .input empty else if 2 = q.val then .not (.input empty) else .const false
+ | .inr (true, _, s) => .const (decide ((0 : Symbol) = s))
+ | .inr (false, i, s) =>
+ if h : r ≤ i.val ∧ i.val - r < n then
+ let j : Fin n := ⟨i.val - r, h.2⟩
+ if (2 : Symbol) = s then .input (input j) else if (1 : Symbol) = s then .not (.input (input j)) else .const false
+ else .const (decide ((0 : Symbol) = s))
+
+theorem initialRegisterExpr_eval (input : Fin n → ι) (empty : ι) (v : ι → Bool) (x : Fin n → Bool)
+ (p : Program) (hx : ∀ i, v (input i) = x i) (he : v empty = decide (p.extra = 0))
+ (j : WindowRegister n r) :
+ (initialRegisterExpr input empty j).eval v = registerEncoding (windowInitial p r x) j := by
+ cases j with
+ | inl q =>
+ have hs : (windowInitial p r x).state.val = if p.extra = 0 then 1 else 2 := by
+ unfold windowInitial
+ split <;> rfl
+ simp only [registerEncoding, hs]
+ by_cases h : p.extra = 0 <;> by_cases h₁ : 1 = q.val <;> by_cases h₂ : 2 = q.val <;>
+ simp [initialRegisterExpr, h, h₁, h₂, Expr.eval, he]
+ omega
+ | inr reg =>
+ rcases reg with ⟨b,i,s⟩
+ cases b with
+ | true => rfl
+ | false =>
+ by_cases h : r ≤ i.val ∧ i.val - r < n
+ · cases hb : x ⟨i.val - r, h.2⟩ <;> by_cases h₁ : (1 : Symbol) = s <;> by_cases h₂ : (2 : Symbol) = s <;>
+ simp [initialRegisterExpr, registerEncoding, windowInitial, h, h₁, h₂, Expr.eval, hx,
+ hb]
+ exact (by decide : (1 : Symbol) ≠ 2) (h₁.trans h₂.symm)
+ · simp [initialRegisterExpr, registerEncoding, windowInitial, h, Expr.eval]
+
+theorem initialRegisterExpr_size_le (input : Fin n → ι) (empty : ι) (j : WindowRegister n r) :
+ (initialRegisterExpr input empty j).size ≤ 2 := by
+ rcases j with q | ⟨b,i,s⟩
+ · simp only [initialRegisterExpr]
+ split_ifs <;> simp [Expr.size]
+ · cases b <;> simp only [initialRegisterExpr]
+ · split_ifs <;> simp [Expr.size]
+ · simp [Expr.size]
+
+end UniversalMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineIteration.lean b/lean/OAI/Computability/VPVNP/VerifierMachineIteration.lean
new file mode 100644
index 0000000000..0e6f7dd2f0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineIteration.lean
@@ -0,0 +1,141 @@
+import OAI.Computability.VPVNP.VerifierMachineRegisters
+import OAI.Computability.VPVNP.VerifierMachineNetwork
+
+/-!
+# Iterating the universal verifier on its bounded tape window
+
+One circuit layer consumes the next choice bit and computes the next configuration.
+The decoded table and the input and choice bits remain accessible by wire references
+at every layer. After exactly `T` layers the circuit tests validity and the accepting state.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierMachineIteration
+
+open UniversalMachine VerifierMachineDecode
+open VerifierNetwork (Frame)
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+
+/-- Inputs and choices, decoded table flags, and configuration registers for a radius-`r` window. -/
+abbrev Slice (n T r : ℕ) := (Fin n ⊕ Fin T) ⊕ (DecoderWire n ⊕ WindowRegister n r)
+
+theorem card_slice (n T r : ℕ) : Fintype.card (Slice n T r) =
+ n + T + (2 + 9 * n * 2 * (n + 2) * 81 + (n + 2 + 2 * ((2 * r + 1) * 3))) := by
+ simp [Slice, decoderWire_card, WindowRegister, WindowCell, UniversalMachine.Symbol]
+
+variable {n T r : ℕ} {σ : Type*} [Fintype σ]
+
+private def choiceAt (t : ℕ) : Expr (Slice n T r) :=
+ if h : t < T then .input (.inl (.inr ⟨t, h⟩)) else .const false
+
+private def slotWire (i : Fin (9 * n)) (b : Bool) (k : InstructionKey n) : Expr (Slice n T r) :=
+ .input (.inr (.inl (.slot i b k)))
+
+private def regWire (j : WindowRegister n r) : Expr (Slice n T r) := .input (.inr (.inr j))
+
+private noncomputable def layer (t : ℕ) : Slice n T r → Expr (Slice n T r)
+ | .inl i => .input (.inl i)
+ | .inr (.inl d) => .input (.inr (.inl d))
+ | .inr (.inr j) => registerStepExpr slotWire regWire (choiceAt t) j
+
+/-- Append exactly one Boolean circuit layer per choice bit, in order. -/
+noncomputable def simulate (f : Frame σ (Slice n T r)) : Frame σ (Slice n T r) := f.steps layer T
+
+private theorem steps_eval_input (f : Frame σ (Slice n T r)) (input : σ → Bool)
+ (i : Fin n ⊕ Fin T) (t : ℕ) : (f.steps layer t).eval input (.inl i) = f.eval input (.inl i) := by
+ induction t with
+ | zero => rfl
+ | succ t ih => simpa [Frame.steps_succ, layer, Expr.eval] using ih
+
+private theorem steps_eval_decoder (f : Frame σ (Slice n T r)) (input : σ → Bool)
+ (d : DecoderWire n) (t : ℕ) :
+ (f.steps layer t).eval input (.inr (.inl d)) = f.eval input (.inr (.inl d)) := by
+ induction t with
+ | zero => rfl
+ | succ t ih => simpa [Frame.steps_succ, layer, Expr.eval] using ih
+
+/-- All bounded configuration bits after `T` layers encode the run on the supplied choices. -/
+theorem simulate_eval_register (f : Frame σ (Slice n T r)) (input : σ → Bool)
+ (p : UniversalMachine.Program) (hp : p.extra ≤ n) (c : WindowConfig p.extra r) (w : Fin T → Bool)
+ (hslots : ∀ i b k, f.eval input (.inr (.inl (.slot i b k))) = true ↔
+ wireHolds p (.slot i b k))
+ (hreg : ∀ j, f.eval input (.inr (.inr j)) = registerEncoding c j)
+ (hw : ∀ i, f.eval input (.inl (.inr i)) = w i) (j : WindowRegister n r) :
+ (simulate f).eval input (.inr (.inr j)) = registerEncoding (windowRun p c (List.ofFn w)) j := by
+ have run (t : ℕ) (ht : t ≤ T) (a : WindowRegister n r) :
+ (f.steps layer t).eval input (.inr (.inr a)) =
+ registerEncoding (windowRun p c ((List.ofFn w).take t)) a := by
+ induction t generalizing a with
+ | zero => simpa [windowRun] using hreg a
+ | succ t ih =>
+ have hlt : t < T := ht
+ have hlen : t < (List.ofFn w).length := by simpa using hlt
+ rw [Frame.steps_succ, Frame.step_eval, List.take_succ_eq_append_getElem hlen]
+ simp only [layer, windowRun, List.foldl_append, List.foldl_cons, List.foldl_nil, List.getElem_ofFn]
+ refine registerStepExpr_eval _ _ _ _ p hp _ _ ?_ ?_ ?_ a
+ · intro i b k
+ simpa only [slotWire, Expr.eval, steps_eval_decoder] using hslots i b k
+ · intro i
+ exact ih (by omega) i
+ · simpa [choiceAt, hlt, Expr.eval, steps_eval_input] using hw ⟨t, hlt⟩
+ have hfull : (List.ofFn w).take T = List.ofFn w := List.take_of_length_le (by simp)
+ simpa only [simulate, hfull] using run T le_rfl j
+
+private def acceptanceBit : Fin (n + 2) := ⟨1, by omega⟩
+
+private def outputExpr (_ : Unit) : Expr (Slice n T r) :=
+ .and (.input (.inr (.inl .valid))) (.input (.inr (.inr (.inl acceptanceBit))))
+
+/-- Circuit output after executing the entire witness and checking that its table was valid. -/
+noncomputable def accept (f : Frame σ (Slice n T r)) : Frame σ Unit := (simulate f).step outputExpr
+
+theorem accept_eval_invalid (f : Frame σ (Slice n T r)) (input : σ → Bool)
+ (hv : f.eval input (.inr (.inl .valid)) = false) : (accept f).eval input () = false := by
+ simp [accept, outputExpr, Expr.eval, simulate, steps_eval_decoder, hv]
+
+theorem accept_eval_valid (f : Frame σ (Slice n T r)) (input : σ → Bool)
+ (p : UniversalMachine.Program) (hp : p.extra ≤ n) (c : WindowConfig p.extra r) (w : Fin T → Bool)
+ (hv : f.eval input (.inr (.inl .valid)) = true)
+ (hslots : ∀ i b k, f.eval input (.inr (.inl (.slot i b k))) = true ↔
+ wireHolds p (.slot i b k))
+ (hreg : ∀ j, f.eval input (.inr (.inr j)) = registerEncoding c j)
+ (hw : ∀ i, f.eval input (.inl (.inr i)) = w i) :
+ (accept f).eval input () = decide ((windowRun p c (List.ofFn w)).state.val = 1) := by
+ have hv' : (simulate f).eval input (.inr (.inl .valid)) = true :=
+ (steps_eval_decoder f input .valid T).trans hv
+ simp only [accept, Frame.step_eval, outputExpr, Expr.eval, hv', Bool.true_and]
+ exact simulate_eval_register f input p hp c w hslots hreg hw (.inl acceptanceBit)
+
+private theorem layer_size_le (t : ℕ) (a : Slice n T r) :
+ (layer t a).size ≤ 1000000 * (n + 2) ^ 2 := by
+ rcases a with i | d | j
+ · change 1 ≤ 1000000 * (n + 2) ^ 2
+ exact Nat.succ_le_of_lt (by positivity)
+ · change 1 ≤ 1000000 * (n + 2) ^ 2
+ exact Nat.succ_le_of_lt (by positivity)
+ · have hc : (choiceAt (n := n) (T := T) (r := r) t).size ≤ 1 := by
+ unfold choiceAt
+ split <;> rfl
+ have h := registerStepExpr_size_le slotWire regWire (choiceAt (T := T) t) 1
+ (fun _ _ _ => le_rfl) (fun _ => le_rfl) hc j
+ calc
+ (layer t (.inr (.inr j))).size ≤ _ := h
+ _ = _ := by ring
+
+/-- The simulation has a fixed width, and the output test uses three more circuit nodes. -/
+theorem accept_size_le (f : Frame σ (Slice n T r)) :
+ (accept f).size ≤ f.size + T * (Fintype.card (Slice n T r) * (1000000 * (n + 2) ^ 2)) + 3 := by
+ have hs := Frame.steps_size_le f layer T (1000000 * (n + 2) ^ 2)
+ (fun t _ a => layer_size_le t a)
+ have ho := Frame.step_size_le (simulate f) outputExpr 3 (fun _ => le_rfl)
+ simp only [Fintype.card_unit, Nat.one_mul] at ho
+ exact ho.trans (Nat.add_le_add_right hs 3)
+
+end VerifierMachineIteration
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineNetwork.lean b/lean/OAI/Computability/VPVNP/VerifierMachineNetwork.lean
new file mode 100644
index 0000000000..881ad43331
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineNetwork.lean
@@ -0,0 +1,137 @@
+import OAI.Computability.BinPacking.CookLevin.OutputOrder
+import OAI.Computability.VPVNP.VerifierMachineCook
+
+/-!
+# Compiling finite arrays of local Boolean formulas
+
+The coefficient verifier in §1.1 parses a table and then simulates one chosen transition
+per clock tick. This interface indexes the existing Cook–Levin circuit compiler by named
+finite types, so that table fields, tape cells, and input bits can be used directly as wire
+indices. A layer preserves sharing between all previous gates.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierNetwork
+
+open BinPackingGames.Foundations.Complexity.CookLevin
+
+/-- Boolean expressions over the live wires of a verifier circuit. -/
+abbrev Expr := StatementCircuit.Expr
+
+/-- An array of live wire references in a circuit whose free inputs are indexed by `σ`. -/
+structure Frame (σ τ : Type*) [Fintype σ] [Fintype τ] where
+ /-- The gate fragment and its live wire references, with the input and output index types
+ enumerated by finite ordinals. -/
+ core : CircuitBatch.Frame (Fintype.card σ) (Fintype.card τ)
+
+namespace Frame
+
+variable {σ τ ρ : Type*} [Fintype σ] [Fintype τ] [Fintype ρ]
+
+/-- Read the value of a chosen live wire under an assignment to the free inputs. -/
+noncomputable def eval (f : Frame σ τ) (x : σ → Bool) (i : τ) : Bool :=
+ f.core.eval (x ∘ (Fintype.equivFin σ).symm) (Fintype.equivFin τ i)
+
+/-- Number of gates already emitted into the frame's circuit fragment. -/
+def size (f : Frame σ τ) : ℕ := f.core.fragment.gates.length
+
+/-- The gate-free frame that selects its live wires directly from the inputs. -/
+noncomputable def initial (wire : τ → σ) : Frame σ τ :=
+ ⟨CircuitBatch.Frame.initial (Fintype.equivFin σ ∘ wire ∘ (Fintype.equivFin τ).symm)⟩
+
+@[simp] theorem initial_eval (wire : τ → σ) (x : σ → Bool) (i : τ) :
+ (initial wire).eval x i = x (wire i) := by simp [initial, eval]
+
+@[simp] theorem initial_size (wire : τ → σ) : (initial wire).size = 0 := rfl
+
+/-- Append a batch of Boolean expressions over the current live wires and expose their outputs
+as the next frame. -/
+noncomputable def step (f : Frame σ τ) (es : ρ → Expr τ) : Frame σ ρ :=
+ ⟨f.core.step (fun i => (es ((Fintype.equivFin ρ).symm i)).rename (Fintype.equivFin τ))⟩
+
+@[simp] theorem step_eval (f : Frame σ τ) (es : ρ → Expr τ) (x : σ → Bool) (i : ρ) :
+ (f.step es).eval x i = (es i).eval (f.eval x) := by
+ simp [step, eval, CircuitBatch.Frame.step_eval]
+ rfl
+
+theorem step_size_le (f : Frame σ τ) (es : ρ → Expr τ) (D : ℕ)
+ (h : ∀ i, (es i).size ≤ D) :
+ (f.step es).size ≤ f.size + Fintype.card ρ * D := by
+ apply f.core.step_gate_count_le
+ intro i
+ simpa using h ((Fintype.equivFin ρ).symm i)
+
+/-- Perform a sequence of indexed expression batches, retaining all previously emitted gates. -/
+noncomputable def steps (f : Frame σ τ) (es : ℕ → τ → Expr τ) : ℕ → Frame σ τ
+ | 0 => f
+ | t + 1 => (steps f es t).step (es t)
+
+@[simp] theorem steps_zero (f : Frame σ τ) (es : ℕ → τ → Expr τ) : f.steps es 0 = f := rfl
+
+theorem steps_succ (f : Frame σ τ) (es : ℕ → τ → Expr τ) (t : ℕ) :
+ f.steps es (t + 1) = (f.steps es t).step (es t) := rfl
+
+theorem steps_size_le (f : Frame σ τ) (es : ℕ → τ → Expr τ) (T D : ℕ)
+ (h : ∀ t < T, ∀ i, (es t i).size ≤ D) :
+ (f.steps es T).size ≤ f.size + T * (Fintype.card τ * D) := by
+ induction T with
+ | zero => simp
+ | succ T ih =>
+ rw [steps_succ, Nat.succ_mul]
+ have hp := ih fun t ht => h t (by omega)
+ have hs := step_size_le (f.steps es T) (es T) D (h T (by omega))
+ omega
+
+/-- Select live outputs without emitting any gates. -/
+noncomputable def select (f : Frame σ τ) (wire : ρ → τ) : Frame σ ρ :=
+ ⟨⟨f.core.fragment, f.core.wires ∘ Fintype.equivFin τ ∘ wire ∘ (Fintype.equivFin ρ).symm⟩⟩
+
+@[simp] theorem select_size (f : Frame σ τ) (wire : ρ → τ) : (f.select wire).size = f.size := rfl
+
+@[simp] theorem select_eval (f : Frame σ τ) (wire : ρ → τ) (x : σ → Bool) (i : ρ) :
+ (f.select wire).eval x i = f.eval x (wire i) := by
+ simp [select, eval, CircuitBatch.Frame.eval]
+
+/-- Retain free inputs alongside a block's outputs for later layers. -/
+noncomputable def withInput (f : Frame σ τ) : Frame σ (σ ⊕ τ) :=
+ ⟨⟨f.core.fragment, fun j => ((Fintype.equivFin (σ ⊕ τ)).symm j).elim
+ (fun i => Fin.castLE (Nat.le_add_right _ _) (Fintype.equivFin σ i))
+ (fun i => f.core.wires (Fintype.equivFin τ i))⟩⟩
+
+@[simp] theorem withInput_size (f : Frame σ τ) : f.withInput.size = f.size := rfl
+
+@[simp] theorem withInput_eval_inl (f : Frame σ τ) (x : σ → Bool) (i : σ) :
+ f.withInput.eval x (.inl i) = x i := by
+ simp [withInput, eval, CircuitBatch.Frame.eval, CircuitBatch.Fragment.evalWires_input]
+
+@[simp] theorem withInput_eval_inr (f : Frame σ τ) (x : σ → Bool) (i : τ) :
+ f.withInput.eval x (.inr i) = f.eval x i := by
+ simp [withInput, eval, CircuitBatch.Frame.eval]
+
+/-- Designate a live wire as the output of the AND/NOT transcript circuit. -/
+noncomputable def circuitSize (f : Frame σ τ) (out : τ) : ℕ :=
+ CookCircuit.transcriptSize (f.core.toCircuit (Fintype.equivFin τ out))
+
+/-- Compile one selected output of the gate fragment as a single-output Boolean transcript
+circuit. -/
+noncomputable def circuit (f : Frame σ τ) (out : τ) :
+ BooleanTranscript.Circuit σ (f.circuitSize out) :=
+ CookCircuit.toTranscriptWith (f.core.toCircuit (Fintype.equivFin τ out))
+ (Sum.inl ∘ (Fintype.equivFin σ).symm)
+
+@[simp] theorem circuit_eval (f : Frame σ τ) (out : τ) (x : σ → Bool) :
+ (f.circuit out).eval x = f.eval x out :=
+ CookCircuit.toTranscriptWith_eval _ _ _
+
+theorem circuitSize_le (f : Frame σ τ) (out : τ) : f.circuitSize out ≤ 4 * f.size :=
+ CookCircuit.toTranscript_size_le _
+
+end Frame
+end VerifierNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineRegisters.lean b/lean/OAI/Computability/VPVNP/VerifierMachineRegisters.lean
new file mode 100644
index 0000000000..5a23204687
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineRegisters.lean
@@ -0,0 +1,128 @@
+import OAI.Computability.VPVNP.VerifierMachineSelector
+import OAI.Computability.VPVNP.VerifierMachineCell
+
+/-!
+# Boolean register transitions for the coefficient machine
+
+Each register tests one state or one symbol in a cell of one of the two tapes.
+The decoder supplies one bit per transition record. A Boolean choice selects the
+branch of the current row, including its write and motion fields. A missing
+branch rejects, except for canonical zero padding after an accepting halt.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+open VPVNP.VerifierMachineDecode
+
+variable {ι : Type*} {n r : ℕ}
+
+private def fallbackState (accept choice : Expr ι) (q : Fin (n + 2)) : Expr ι :=
+ Expr.mux (.and accept (.not choice)) (.const (decide (1 = q.val))) (.const (decide (0 = q.val)))
+
+private theorem fallbackState_eval (input : ι → Bool) {e : ℕ} (c : WindowConfig e r) (bit : Bool)
+ (accept choice : Expr ι) (ha : accept.eval input = decide (c.state.val = 1))
+ (hb : choice.eval input = bit) (q : Fin (n + 2)) :
+ (fallbackState accept choice q).eval input =
+ decide ((if c.state.val = 1 ∧ bit = false then (1 : Fin (e + 2)) else 0).val = q.val) := by
+ by_cases h : c.state.val = 1 <;> cases bit <;>
+ simp [fallbackState, Expr.eval_mux, Expr.eval, ha, hb, h]
+
+private def keyWrite (tape : Bool) (k : InstructionKey n) : Symbol :=
+ if tape then k.2.2.2.1 else k.2.1
+
+private def keyMove (tape : Bool) (k : InstructionKey n) : Fin 3 :=
+ if tape then k.2.2.2.2 else k.2.2.1
+
+/-- Formula for one output register, using shared input wires for the decoded table
+and the previous configuration. -/
+noncomputable def registerStepExpr
+ (slots : Fin (9 * n) → Bool → InstructionKey n → Expr ι)
+ (reg : WindowRegister n r → Expr ι) (choice : Expr ι) :
+ WindowRegister n r → Expr ι
+ | .inl q =>
+ let sel := selectedExpr slots reg choice
+ Expr.mux (sel fun _ => true) (sel fun k => decide (k.1 = q))
+ (fallbackState (reg (.inl ⟨1, by omega⟩)) choice q)
+ | .inr (t, i, s) =>
+ let sel := selectedExpr slots reg choice
+ cellNext (fun j a => reg (.inr (t, j, a))) (sel fun _ => true)
+ (fun a => sel fun k => decide (keyWrite t k = a))
+ (fun d => sel fun k => decide (keyMove t k = d)) i s
+
+/-- Evaluating the next Boolean register gives the corresponding bit of the machine step. -/
+theorem registerStepExpr_eval (slots : Fin (9 * n) → Bool → InstructionKey n → Expr ι)
+ (reg : WindowRegister n r → Expr ι) (choice : Expr ι) (input : ι → Bool)
+ (p : Program) (h : p.extra ≤ n) (c : WindowConfig p.extra r) (bit : Bool)
+ (hs : ∀ i b k, (slots i b k).eval input = true ↔ wireHolds p (.slot i b k))
+ (hr : ∀ i, (reg i).eval input = registerEncoding c i)
+ (hb : choice.eval input = bit) (j : WindowRegister n r) :
+ (registerStepExpr slots reg choice j).eval input = registerEncoding (windowStep p c bit) j := by
+ have sel (f : InstructionKey n → Bool) :=
+ eval_selectedExpr slots reg choice f input p h c bit hs hr hb
+ rcases j with q | ⟨t, i, s⟩
+ · cases ha : windowInstruction p c bit with
+ | none =>
+ simp only [registerStepExpr, Expr.eval_mux, sel, ha, Option.any_none, Bool.false_eq_true,
+ ite_false, windowStep, registerEncoding]
+ exact fallbackState_eval input c bit _ _ (hr _) hb q
+ | some a =>
+ simp only [registerStepExpr, Expr.eval_mux, sel, ha, Option.any_some, ite_true, windowStep,
+ windowAdvance, registerEncoding]
+ simp [Fin.ext_iff, instructionKey]
+ · cases ha : windowInstruction p c bit with
+ | none =>
+ rw [registerStepExpr, cellNext_eval_none _ _ _ _ _ _ _ (by simp [sel, ha]), hr]
+ cases t <;> simp [windowStep, ha, registerEncoding]
+ | some a =>
+ cases t <;>
+ simp only [registerStepExpr, windowStep, ha, windowAdvance, registerEncoding] <;>
+ apply cellNext_eval_some <;> first
+ | exact fun j b => hr _
+ | intro k; rw [sel, ha]; rfl
+ | simp only [sel, ha, Option.any_some]
+
+/-- One step has quadratic formula size per register in the bound on the number of
+states. Its cost is independent of the tape radius, since each destination uses at most
+three neighboring cells. -/
+theorem registerStepExpr_size_le (slots : Fin (9 * n) → Bool → InstructionKey n → Expr ι)
+ (reg : WindowRegister n r → Expr ι) (choice : Expr ι) (C : ℕ)
+ (hs : ∀ i b k, (slots i b k).size ≤ C) (hr : ∀ j, (reg j).size ≤ C)
+ (hb : choice.size ≤ C) (j : WindowRegister n r) :
+ (registerStepExpr slots reg choice j).size ≤ 500000 * (n + 2) ^ 2 * (C + 1) := by
+ let B := 20000 * (n + 2) ^ 2 * (C + 1)
+ have sel (f : InstructionKey n → Bool) : (selectedExpr slots reg choice f).size ≤ B :=
+ size_selectedExpr slots reg choice f C hs hr hb
+ have hbase : C + 1 ≤ (n + 2) ^ 2 * (C + 1) := by
+ have hn : 0 < (n + 2) ^ 2 := by positivity
+ simpa using Nat.mul_le_mul_right (C + 1) hn
+ have hlarge : C ≤ B := by
+ dsimp [B]
+ rw [Nat.mul_assoc]
+ omega
+ rcases j with q | ⟨t, i, s⟩
+ · have h₁ := sel fun _ => true
+ have h₂ := sel fun k => decide (k.1 = q)
+ have h₃ := hr (.inl ⟨1, by omega⟩)
+ simp only [registerStepExpr, Expr.mux, fallbackState, Expr.size]
+ dsimp [B] at h₁ h₂
+ rw [Nat.mul_assoc] at h₁ h₂ ⊢
+ omega
+ · have hc := cellNext_size_le (fun j a => reg (.inr (t, j, a))) _ _ _ i s B
+ (fun j a => (hr _).trans hlarge) (sel fun _ => true)
+ (fun a => sel fun k => decide (keyWrite t k = a))
+ (fun d => sel fun k => decide (keyMove t k = d))
+ apply hc.trans
+ dsimp [B]
+ rw [Nat.mul_assoc, Nat.mul_assoc 500000]
+ omega
+
+end UniversalMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineRowCount.lean b/lean/OAI/Computability/VPVNP/VerifierMachineRowCount.lean
new file mode 100644
index 0000000000..b793a9370d
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineRowCount.lean
@@ -0,0 +1,59 @@
+import OAI.Computability.VPVNP.UniversalMachine
+import Mathlib.Data.Fintype.Prod
+import Mathlib.Data.Fintype.Sum
+
+/-!
+# Counting literal machine rows
+
+Each instruction chooses a target state and four ternary fields. A transition
+row contains zero, one, or two ordered instructions, and a repeated instruction
+in a two-branch row is allowed.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+private def instructionEquiv (extra : ℕ) :
+ Instruction extra ≃ Fin (extra + 2) × Fin 3 × Fin 3 × Fin 3 × Fin 3 where
+ toFun a := (a.target, a.firstSymbol, a.firstMove, a.secondSymbol, a.secondMove)
+ invFun := fun (q, x, u, y, v) => ⟨q, x, u, y, v⟩
+ left_inv _ := rfl
+ right_inv _ := rfl
+
+instance (extra : ℕ) : Fintype (Instruction extra) :=
+ Fintype.ofEquiv _ (instructionEquiv extra).symm
+
+@[simp] theorem card_instruction (extra : ℕ) :
+ Fintype.card (Instruction extra) = (extra + 2) * 81 := by
+ rw [Fintype.card_congr (instructionEquiv extra)]
+ simp
+
+private def branchesEquiv (extra : ℕ) :
+ Branches extra ≃ Unit ⊕ Instruction extra ⊕ Instruction extra × Instruction extra where
+ toFun
+ | .stop => .inl ()
+ | .one a => .inr (.inl a)
+ | .two a b => .inr (.inr (a, b))
+ invFun
+ | .inl () => .stop
+ | .inr (.inl a) => .one a
+ | .inr (.inr (a, b)) => .two a b
+ left_inv b := by cases b <;> rfl
+ right_inv b := by rcases b with ⟨⟩ | a | ⟨a, c⟩ <;> rfl
+
+instance (extra : ℕ) : Fintype (Branches extra) :=
+ Fintype.ofEquiv _ (branchesEquiv extra).symm
+
+@[simp] theorem card_branches (extra : ℕ) :
+ Fintype.card (Branches extra) = 1 + (extra + 2) * 81 + ((extra + 2) * 81) ^ 2 := by
+ rw [Fintype.card_congr (branchesEquiv extra)]
+ simp [pow_two, Nat.add_assoc]
+
+end UniversalMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineSelector.lean b/lean/OAI/Computability/VPVNP/VerifierMachineSelector.lean
new file mode 100644
index 0000000000..3fa3be93d2
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineSelector.lean
@@ -0,0 +1,145 @@
+import OAI.Computability.BinPacking.CookLevin.ConfigIndex
+import OAI.Computability.VPVNP.VerifierMachineSimulation
+import OAI.Computability.VPVNP.VerifierMachineDecodeWire
+
+/-!
+# Selecting one transition from the decoded program
+
+The current state and the two symbols under the heads determine a row. The next witness
+bit selects its branch. The disjunction tests every possible instruction in that slot
+against a Boolean predicate on its fields. It returns false for a halted state, a missing
+branch, or an instruction failing the predicate.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+open BinPackingGames.Foundations.Complexity.CookLevin.StatementCircuit
+open VPVNP.VerifierMachineDecode
+
+/-- Represent an instruction in the fixed range allocated for an input of length `n`. -/
+def instructionKey {e n : ℕ} (h : e ≤ n) (a : Instruction e) : InstructionKey n :=
+ (a.target.castLE (by omega), a.firstSymbol, a.firstMove, a.secondSymbol, a.secondMove)
+
+theorem keyMatches_iff {e n : ℕ} (h : e ≤ n) (a : Instruction e) (k : InstructionKey n) :
+ KeyMatches k a ↔ instructionKey h a = k := by
+ rcases k with ⟨q, x, u, y, v⟩
+ simp [KeyMatches, instructionKey, Prod.mk.injEq, Fin.ext_iff]
+
+private abbrev SelectIndex (n : ℕ) := Fin n × Symbol × Symbol × InstructionKey n
+
+private def SelectIndex.state {n : ℕ} (z : SelectIndex n) : Fin (n + 2) :=
+ ⟨z.1.val + 2, by have := z.1.isLt; omega⟩
+
+private def SelectIndex.row {n : ℕ} (z : SelectIndex n) : Fin (9 * n) :=
+ ⟨z.1.val * 9 + z.2.1.val * 3 + z.2.2.1.val, by
+ have := z.1.isLt
+ have := z.2.1.isLt
+ have := z.2.2.1.isLt
+ omega⟩
+
+variable {ι : Type*} {n r : ℕ}
+variable (slots : Fin (9 * n) → Bool → InstructionKey n → Expr ι)
+variable (reg : WindowRegister n r → Expr ι) (choice : Expr ι) (f : InstructionKey n → Bool)
+
+private def selectTerm (z : SelectIndex n) : Expr ι :=
+ .and (reg (.inl z.state))
+ (.and (reg (.inr (false, windowCenter r, z.2.1)))
+ (.and (reg (.inr (true, windowCenter r, z.2.2.1)))
+ (.and (.const (f z.2.2.2))
+ (Expr.mux choice (slots z.row true z.2.2.2) (slots z.row false z.2.2.2)))))
+
+/-- Test whether the instruction selected by the current state, scanned symbols, and branch bit
+satisfies the supplied predicate. -/
+noncomputable def selectedExpr : Expr ι :=
+ Expr.disjoin (Finset.univ.toList.map (selectTerm slots reg choice f))
+
+private def currentRow {e : ℕ} (c : WindowConfig e r) : ℕ :=
+ (c.state.val - 2) * 9 + (c.firstTape (windowCenter r)).val * 3 +
+ (c.secondTape (windowCenter r)).val
+
+private theorem rowInstruction_eq_chosen {e : ℕ} (row : Branches e) (bit : Bool) :
+ rowInstruction row bit = chosenInstruction row bit := by
+ cases row <;> cases bit <;> rfl
+
+private theorem windowInstruction_some (p : Program) (c : WindowConfig p.extra r)
+ (bit : Bool) (a : Instruction p.extra) :
+ windowInstruction p c bit = some a ↔ 2 ≤ c.state.val ∧
+ ∃ row, p.rows[currentRow c]? = some row ∧ rowInstruction row bit = some a := by
+ by_cases h : 2 ≤ c.state.val
+ · simp only [windowInstruction, h, ite_true, true_and, ← rowInstruction_eq_chosen]
+ change rowInstruction (p.rows[currentRow c]?.getD .stop) bit = some a ↔ _
+ cases hr : p.rows[currentRow c]? with
+ | none => simp [rowInstruction]
+ | some b => simp
+ · simp [windowInstruction, h]
+
+private theorem eval_selectTerm (z : SelectIndex n) (input : ι → Bool) (p : Program)
+ (c : WindowConfig p.extra r) (bit : Bool)
+ (hslot : ∀ i b k, (slots i b k).eval input = true ↔ wireHolds p (.slot i b k))
+ (hreg : ∀ i, (reg i).eval input = registerEncoding c i) (hchoice : choice.eval input = bit) :
+ (selectTerm slots reg choice f z).eval input = true ↔
+ c.state.val = z.1.val + 2 ∧ c.firstTape (windowCenter r) = z.2.1 ∧
+ c.secondTape (windowCenter r) = z.2.2.1 ∧ f z.2.2.2 = true ∧
+ wireHolds p (.slot z.row bit z.2.2.2) := by
+ cases bit <;>
+ simp [selectTerm, Expr.eval, Expr.eval_mux, hreg, hchoice, hslot, registerEncoding,
+ SelectIndex.state]
+
+theorem eval_selectedExpr (input : ι → Bool) (p : Program) (h : p.extra ≤ n)
+ (c : WindowConfig p.extra r) (bit : Bool)
+ (hslot : ∀ i b k, (slots i b k).eval input = true ↔ wireHolds p (.slot i b k))
+ (hreg : ∀ i, (reg i).eval input = registerEncoding c i) (hchoice : choice.eval input = bit) :
+ (selectedExpr slots reg choice f).eval input =
+ (windowInstruction p c bit).any (fun a => f (instructionKey h a)) := by
+ apply Bool.eq_iff_iff.mpr
+ rw [selectedExpr, Expr.eval_disjoin_true, Option.any_eq_true]
+ constructor
+ · rintro ⟨t, ht, ht'⟩
+ obtain ⟨z, _, rfl⟩ := List.mem_map.mp ht
+ obtain ⟨hq, hx, hy, hf, row, a, hrow, ha, hk⟩ :=
+ (eval_selectTerm slots reg choice f z input p c bit hslot hreg hchoice).mp ht'
+ have hr : currentRow c = z.row.val := by simp [currentRow, SelectIndex.row, hq, hx, hy]
+ exact ⟨a, (windowInstruction_some p c bit a).mpr
+ ⟨by omega, row, hr ▸ hrow, ha⟩, (keyMatches_iff h a _).mp hk ▸ hf⟩
+ · rintro ⟨a, ha, hf⟩
+ obtain ⟨hrun, row, hrow, hbranch⟩ := (windowInstruction_some p c bit a).mp ha
+ let q : Fin n := ⟨c.state.val - 2, by have := c.state.isLt; omega⟩
+ let z : SelectIndex n :=
+ (q, c.firstTape (windowCenter r), c.secondTape (windowCenter r), instructionKey h a)
+ refine ⟨selectTerm slots reg choice f z, List.mem_map.mpr ⟨z, by simp, rfl⟩,
+ (eval_selectTerm slots reg choice f z input p c bit hslot hreg hchoice).mpr ?_⟩
+ exact ⟨by change c.state.val = c.state.val - 2 + 2; omega, rfl, rfl, hf,
+ row, a, hrow, hbranch, (keyMatches_iff h a _).mpr rfl⟩
+
+/-- Each possible source and instruction contributes one constant-depth selector term. -/
+theorem size_selectedExpr
+ (slots : Fin (9 * n) → Bool → InstructionKey n → Expr ι)
+ (reg : WindowRegister n r → Expr ι) (choice : Expr ι) (f : InstructionKey n → Bool)
+ (C : ℕ) (hslot : ∀ i b k, (slots i b k).size ≤ C) (hreg : ∀ i, (reg i).size ≤ C)
+ (hchoice : choice.size ≤ C) : (selectedExpr slots reg choice f).size ≤
+ 20000 * (n + 2) ^ 2 * (C + 1) := by
+ unfold selectedExpr
+ have hb : ∀ e ∈ Finset.univ.toList.map (selectTerm slots reg choice f), e.size ≤ 7 * C + 9 := by
+ intro e he
+ obtain ⟨z, _, rfl⟩ := List.mem_map.mp he
+ simp only [selectTerm, Expr.mux, Expr.size]
+ have hq := hreg (.inl z.state)
+ have h₁ := hreg (.inr (false, windowCenter r, z.2.1))
+ have h₂ := hreg (.inr (true, windowCenter r, z.2.2.1))
+ have ht := hslot z.row true z.2.2.2
+ have hf := hslot z.row false z.2.2.2
+ omega
+ have hs := Expr.size_disjoin_le _ _ hb
+ simp only [List.length_map, Finset.length_toList, Finset.card_univ, SelectIndex,
+ InstructionKey, Symbol, Fintype.card_prod, Fintype.card_fin] at hs
+ exact hs.trans (by ring_nf; omega)
+
+end UniversalMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineSimulation.lean b/lean/OAI/Computability/VPVNP/VerifierMachineSimulation.lean
new file mode 100644
index 0000000000..9aa5b70191
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineSimulation.lean
@@ -0,0 +1,259 @@
+import OAI.Computability.VPVNP.ChoiceWitness
+
+/-!
+# Finite tape windows for the coefficient verifier
+
+For a run of at most `r` steps, keep `2*r+1` cells of each tape centered at its
+current head. A move shifts this array by one, reading a blank at the outside
+edge. The cells with distance at most the remaining running time continue to
+agree with the unbounded two-way tapes.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace UniversalMachine
+
+/-- A cell of the finite tape window of radius `r`, numbered from the left edge. -/
+abbrev WindowCell (r : ℕ) := Fin (2 * r + 1)
+/-- The symbol stored at each cell of a finite head-centered tape window. -/
+abbrev WindowTape (r : ℕ) := WindowCell r → Symbol
+
+/-- The cell scanned by the head in a radius-`r` window. -/
+def windowCenter (r : ℕ) : WindowCell r := ⟨r, by omega⟩
+
+/-- The old cell which moves into a given position after a head motion. -/
+def shiftSource {r : ℕ} (move : Fin 3) (i : WindowCell r) : Option (WindowCell r) :=
+ match move.val with
+ | 0 => some i
+ | 1 => if i.val = 0 then none else some ⟨i.val - 1, by have := i.isLt; omega⟩
+ | _ => if h : i.val + 1 < 2 * r + 1 then some ⟨i.val + 1, h⟩ else none
+
+/-- Write the head cell, then move the head and shift the whole window. -/
+def windowUpdate {r : ℕ} (old : WindowTape r) (write move : Fin 3) (i : WindowCell r) : Symbol :=
+ match shiftSource move i with
+ | none => 0
+ | some j => if j = windowCenter r then write else old j
+
+/-- A machine configuration restricted to the two tape windows used by the bounded verifier. -/
+structure WindowConfig (extra r : ℕ) where
+ /-- Current running or halting state in the window simulation. -/
+ state : Fin (extra + 2)
+ /-- The head-centered window of the input tape. -/
+ firstTape : WindowTape r
+ /-- The head-centered window of the work tape. -/
+ secondTape : WindowTape r
+
+/-- State bits, followed by the symbol bits of the two finite tape windows. -/
+abbrev WindowRegister (n r : ℕ) := Fin (n + 2) ⊕ (Bool × WindowCell r × Symbol)
+
+/-- Boolean tests for the current state at each candidate state index and for each candidate
+symbol at every represented cell of either tape. -/
+def registerEncoding {n e r : ℕ} (c : WindowConfig e r) : WindowRegister n r → Bool
+ | .inl q => decide (c.state.val = q.val)
+ | .inr (false, i, s) => decide (c.firstTape i = s)
+ | .inr (true, i, s) => decide (c.secondTape i = s)
+
+/-- Look up the literal transition row using the current state and the symbols at both window
+centers. -/
+def windowBranches {r : ℕ} (p : Program) (c : WindowConfig p.extra r) : Branches p.extra :=
+ p.rows[(c.state.val - 2) * 9 + (c.firstTape (windowCenter r)).val * 3 +
+ (c.secondTape (windowCenter r)).val]?.getD .stop
+
+/-- Select a branch using the path bit. A deterministic row accepts only the false choice bit. -/
+def chosenInstruction {extra : ℕ} (row : Branches extra) (bit : Bool) :
+ Option (Instruction extra) :=
+ match row with
+ | .stop => none
+ | .one a => if bit then none else some a
+ | .two a b => some (if bit then b else a)
+
+/-- Select the next instruction of a running configuration from the literal table and path bit. -/
+def windowInstruction {r : ℕ} (p : Program) (c : WindowConfig p.extra r) (bit : Bool) :
+ Option (Instruction p.extra) :=
+ if 2 ≤ c.state.val then chosenInstruction (windowBranches p c) bit else none
+
+/-- Apply one instruction, updating the state and recentering both finite tape windows after
+their head moves. -/
+def windowAdvance {extra r : ℕ} (c : WindowConfig extra r) (a : Instruction extra) :
+ WindowConfig extra r where
+ state := a.target
+ firstTape := windowUpdate c.firstTape a.firstSymbol a.firstMove
+ secondTape := windowUpdate c.secondTape a.secondSymbol a.secondMove
+
+/-- One deterministic step, including rejection of invalid choices and nonzero padding. -/
+def windowStep {r : ℕ} (p : Program) (c : WindowConfig p.extra r) (bit : Bool) :
+ WindowConfig p.extra r :=
+ match windowInstruction p c bit with
+ | some a => windowAdvance c a
+ | none => { c with state := if c.state.val = 1 ∧ bit = false then 1 else 0 }
+
+/-- Signed displacement of a window cell from the head. -/
+def windowOffset {r : ℕ} (i : WindowCell r) : ℤ := (i.val : ℤ) - r
+
+/-- Agreement on all cells reachable in the remaining `t` transitions. -/
+def TapeAgrees {r : ℕ} (t : ℕ) (w : WindowTape r) (c : Turing.Tape Symbol) : Prop :=
+ ∀ i, -(t : ℤ) ≤ windowOffset i → windowOffset i ≤ t → w i = c.nth (windowOffset i)
+
+/-- The finite and unbounded configurations have the same state, and their two tapes agree at
+every represented offset between minus t and t, inclusive. -/
+structure WindowAgrees {extra r : ℕ} (t : ℕ) (w : WindowConfig extra r) (c : Config extra) :
+ Prop where
+ state : w.state = c.state
+ first : TapeAgrees t w.firstTape c.firstTape
+ second : TapeAgrees t w.secondTape c.secondTape
+
+private theorem TapeAgrees.head {r t : ℕ} {w : WindowTape r} {c : Turing.Tape Symbol}
+ (h : TapeAgrees t w c) : w (windowCenter r) = c.head := by
+ simpa [windowOffset, windowCenter] using h (windowCenter r) (by simp [windowOffset, windowCenter])
+ (by simp [windowOffset, windowCenter])
+
+private theorem TapeAgrees.mono {r t : ℕ} {w : WindowTape r} {c : Turing.Tape Symbol}
+ (h : TapeAgrees (t + 1) w c) : TapeAgrees t w c :=
+ fun i hlo hhi => h i (by omega) (by omega)
+
+private theorem shiftSource_inside {r t : ℕ} (hr : t + 1 ≤ r) (m : Fin 3) (i : WindowCell r)
+ (hlo : -(t : ℤ) ≤ windowOffset i) (hhi : windowOffset i ≤ t) :
+ ∃ j, shiftSource m i = some j ∧
+ windowOffset j = windowOffset i + (if m.val = 0 then 0 else if m.val = 1 then -1 else 1) := by
+ unfold windowOffset at *
+ have hi := i.isLt
+ rcases m with ⟨m, hm⟩
+ match m with
+ | 0 => exact ⟨i, rfl, by simp⟩
+ | 1 =>
+ have hpos : i.val ≠ 0 := by omega
+ exact ⟨⟨i.val - 1, by omega⟩, by simp [shiftSource, hpos], by simp; omega⟩
+ | m + 2 =>
+ have hlt : i.val + 1 < 2 * r + 1 := by omega
+ exact ⟨⟨i.val + 1, hlt⟩, by simp [shiftSource, hlt], by simp; omega⟩
+
+private theorem windowBranches_eq {r t : ℕ} (p : Program) {w : WindowConfig p.extra r}
+ {c : Config p.extra} (h : WindowAgrees t w c) : windowBranches p w = branches p c := by
+ simp [windowBranches, branches, h.state, h.first.head, h.second.head]
+
+
+private theorem updateTape_nth (c : Turing.Tape Symbol) (b m : Fin 3) (i : ℤ) :
+ (updateTape c b m).nth i =
+ (c.write b).nth (i + (if m.val = 0 then 0 else if m.val = 1 then -1 else 1)) := by
+ rcases m with ⟨m, hm⟩
+ match m with
+ | 0 => simp [updateTape]
+ | 1 => simp [updateTape, sub_eq_add_neg]
+ | m + 2 => simp [updateTape]
+
+private theorem TapeAgrees.update {r t : ℕ} {w : WindowTape r} {c : Turing.Tape Symbol}
+ (h : TapeAgrees (t + 1) w c) (hr : t + 1 ≤ r) (b m : Fin 3) :
+ TapeAgrees t (windowUpdate w b m) (updateTape c b m) := by
+ intro i hlo hhi
+ obtain ⟨j, hj, hoff⟩ := shiftSource_inside hr m i hlo hhi
+ have hlo' : -(↑(t + 1 : ℕ) : ℤ) ≤ windowOffset j := by
+ rw [hoff]
+ split_ifs <;> omega
+ have hhi' : windowOffset j ≤ (t + 1 : ℕ) := by
+ rw [hoff]
+ split_ifs <;> omega
+ have hc : j = windowCenter r ↔ windowOffset j = 0 := by
+ rw [Fin.ext_iff]
+ simp only [windowCenter, windowOffset]
+ omega
+ rw [updateTape_nth, ← hoff, Turing.Tape.write_nth]
+ simp only [windowUpdate, hj, hc, h j hlo' hhi']
+
+private theorem WindowAgrees.advance {r t extra : ℕ}
+ {w : WindowConfig extra r} {c : Config extra}
+ (h : WindowAgrees (t + 1) w c) (hr : t + 1 ≤ r) (a : Instruction extra) :
+ WindowAgrees t (windowAdvance w a) (advance c a) :=
+ ⟨rfl, h.first.update hr _ _, h.second.update hr _ _⟩
+
+/-- One tick preserves agreement on the portion of the tape reachable by future ticks. -/
+theorem windowStep_agrees {r t : ℕ} (p : Program) {w : WindowConfig p.extra r}
+ {c : Config p.extra} (h : WindowAgrees (t + 1) w c) (hr : t + 1 ≤ r) (bit : Bool) :
+ WindowAgrees t (windowStep p w bit) (choiceStep p c bit) := by
+ have hw := windowBranches_eq p h
+ by_cases ha : c.state.val = 1
+ · cases bit <;> simp [windowStep, windowInstruction, choiceStep, h.state, ha] <;>
+ exact ⟨by apply Fin.ext; simp [reject, ha], h.first.mono, h.second.mono⟩
+ by_cases hz : c.state.val = 0
+ · simp [windowStep, windowInstruction, choiceStep, h.state, hz]
+ exact ⟨by apply Fin.ext; simp [hz], h.first.mono, h.second.mono⟩
+ have hrun : 2 ≤ c.state.val := by omega
+ simp only [windowStep, windowInstruction, choiceStep, h.state, hw, hrun, ha, hz, ite_true,
+ ite_false, false_and]
+ cases hb : branches p c with
+ | stop => exact ⟨rfl, h.first.mono, h.second.mono⟩
+ | one a =>
+ cases bit
+ · exact h.advance hr a
+ · exact ⟨rfl, h.first.mono, h.second.mono⟩
+ | two a b => exact h.advance hr _
+
+/-- Run the machine on a finite window, consuming one bit per step. -/
+def windowRun {r : ℕ} (p : Program) (c : WindowConfig p.extra r) (bits : List Bool) :
+ WindowConfig p.extra r :=
+ bits.foldl (windowStep p) c
+
+theorem windowRun_agrees {r : ℕ} (p : Program) (bits : List Bool) (hr : bits.length ≤ r)
+ (w : WindowConfig p.extra r) (c : Config p.extra) (h : WindowAgrees bits.length w c) :
+ WindowAgrees 0 (windowRun p w bits) (bits.foldl (choiceStep p) c) := by
+ induction bits generalizing w c with
+ | nil => exact h
+ | cons b bs ih =>
+ exact ih (by simp at hr; omega) _ _ (windowStep_agrees p h hr b)
+
+/-- Load input bits on and to the right of the first tape head. -/
+def windowInitial {n : ℕ} (p : Program) (r : ℕ) (x : Fin n → Bool) :
+ WindowConfig p.extra r where
+ state := if h : p.extra = 0 then ⟨1, by omega⟩ else ⟨2, by omega⟩
+ firstTape := fun i =>
+ if h : r ≤ i.val ∧ i.val - r < n then if x ⟨i.val - r, h.2⟩ then 2 else 1 else 0
+ secondTape := fun _ => 0
+
+private theorem tape_nth_mk₁ (xs : List Symbol) (i : ℤ) :
+ (Turing.Tape.mk₁ xs).nth i = if 0 ≤ i then xs[i.toNat]?.getD 0 else 0 := by
+ cases i with
+ | ofNat k =>
+ change (Turing.Tape.mk' (Turing.ListBlank.mk []) (Turing.ListBlank.mk xs)).nth (k : ℤ) = _
+ simp [Turing.ListBlank.nth_mk]
+ rw [← List.getD_default_eq_getI, List.getD_eq_getElem?_getD]
+ rfl
+ | negSucc k =>
+ change (Turing.ListBlank.mk ([] : List Symbol)).nth k = _
+ simp [Turing.ListBlank.nth_mk]
+
+theorem windowInitial_agrees {n : ℕ} (p : Program) (r t : ℕ) (x : Fin n → Bool) :
+ WindowAgrees t (windowInitial p r x) (initial p (List.ofFn x)) := by
+ refine ⟨rfl, ?_, ?_⟩
+ · intro i _ _
+ change (if h : r ≤ i.val ∧ i.val - r < n then if x ⟨i.val - r, h.2⟩ then 2 else 1 else 0)
+ = (Turing.Tape.mk₁ ((List.ofFn x).map fun b => if b then (2 : Symbol) else 1)).nth (windowOffset i)
+ rw [tape_nth_mk₁]
+ have hto : (windowOffset i).toNat = i.val - r := by unfold windowOffset; omega
+ have hnonneg : 0 ≤ windowOffset i ↔ r ≤ i.val := by unfold windowOffset; omega
+ simp only [hto, hnonneg]
+ by_cases hlo : r ≤ i.val
+ · by_cases hhi : i.val - r < n
+ · simp [hlo, hhi]
+ · simp [hlo, hhi]
+ · simp [hlo]
+ · intro i _ _
+ change 0 = (Turing.Tape.mk₁ []).nth (windowOffset i)
+ simp [tape_nth_mk₁]
+
+/-- The bounded register machine computes the canonical witness predicate for the actual
+two-way-tape program, including both halting states and all branch counts. -/
+theorem windowRun_acceptsChoices {n : ℕ} (p : Program) (t r : ℕ) (ht : t ≤ r)
+ (x : Fin n → Bool) (w : Fin t → Bool) :
+ decide ((windowRun p (windowInitial p r x) (List.ofFn w)).state.val = 1) =
+ acceptsChoices p t (initial p (List.ofFn x)) w := by
+ rw [acceptsChoices_eq_foldl]
+ have h := windowRun_agrees p (List.ofFn w) (by simpa using ht) _ _
+ (windowInitial_agrees p r (List.ofFn w).length x)
+ rw [h.state]
+
+end UniversalMachine
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMachineSplice.lean b/lean/OAI/Computability/VPVNP/VerifierMachineSplice.lean
new file mode 100644
index 0000000000..290cb99caf
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMachineSplice.lean
@@ -0,0 +1,104 @@
+import OAI.Computability.VPVNP.VerifierMachineNetwork
+
+/-!
+# Substitution of compiled Boolean networks
+
+Feeding all outputs of one circuit block into another takes the disjoint union of their
+gate lists. Wires of the second block either select an output of the first block or
+reference a gate in the appended list. This allows a verifier to use a compiled subroutine
+more than once while sharing intermediate wires within each invocation.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace VerifierNetwork
+
+open BinPackingGames.Foundations.Complexity.CookLevin
+
+private def renameGate (wire : ℕ → ℕ) : Gate → Gate
+ | .const b => .const b
+ | .not i => .not (wire i)
+ | .and i j => .and (wire i) (wire j)
+ | .or i j => .or (wire i) (wire j)
+
+private theorem renameGate_eval (wire : ℕ → ℕ) (g : Gate) (A : ℕ → Bool) :
+ (renameGate wire g).eval A = g.eval (A ∘ wire) := by
+ cases g <;> rfl
+
+private theorem renameGate_bounded (wire : ℕ → ℕ) (g : Gate) {a b : ℕ}
+ (h : g.Bounded a) (hw : ∀ j < a, wire j < b) : (renameGate wire g).Bounded b := by
+ cases g with
+ | const => trivial
+ | not i => exact hw i h
+ | and i j => exact ⟨hw i h.1, hw j h.2⟩
+ | or i j => exact ⟨hw i h.1, hw j h.2⟩
+
+private def relocate {p n : ℕ} (g : CircuitBatch.Frame p n) (j : ℕ) : ℕ :=
+ if h : j < n then g.wires ⟨j, h⟩ else p + g.fragment.gates.length + (j - n)
+
+private theorem relocate_lt {p n : ℕ} (g : CircuitBatch.Frame p n) {i j : ℕ}
+ (hj : j < n + i) : relocate g j < p + g.fragment.gates.length + i := by
+ unfold relocate
+ split
+ · next h => exact lt_of_lt_of_le (g.wires ⟨j, h⟩).isLt (Nat.le_add_right _ _)
+ · omega
+
+private theorem relocate_ordered {p n : ℕ} (g : CircuitBatch.Frame p n)
+ (f : CircuitBatch.Fragment n) :
+ Ordered (p + g.fragment.gates.length) (f.gates.map (renameGate (relocate g))) := by
+ intro i hi
+ have hi' : i < f.gates.length := by simpa using hi
+ rw [List.getElem_map]
+ exact renameGate_bounded _ _ (f.ordered i hi') (fun _ hj => relocate_lt g hj)
+
+private def spliceCore {p n m : ℕ} (f : CircuitBatch.Frame n m)
+ (g : CircuitBatch.Frame p n) : CircuitBatch.Frame p m where
+ fragment := g.fragment.append (f.fragment.gates.map (renameGate (relocate g)))
+ (relocate_ordered g f.fragment)
+ wires := fun i => ⟨relocate g (f.wires i), by
+ simpa [CircuitBatch.Fragment.append, Nat.add_assoc] using relocate_lt g (f.wires i).isLt⟩
+
+private theorem spliceCore_eval {p n m : ℕ} (f : CircuitBatch.Frame n m)
+ (g : CircuitBatch.Frame p n) (x : Fin p → Bool) (i : Fin m) :
+ (spliceCore f g).eval x i = f.eval (g.eval x) i := by
+ let A := (spliceCore f g).fragment.evalWires x
+ let gs := f.fragment.gates.map (renameGate (relocate g))
+ have hc : Consistent (p + g.fragment.gates.length) gs A :=
+ ((consistent_append p g.fragment.gates gs A).mp
+ ((spliceCore f g).fragment.evalWires_consistent x)).2
+ have hf : Consistent n f.fragment.gates (A ∘ relocate g) := by
+ intro k hk
+ have h := hc k (by simpa [gs] using hk)
+ simp only [gs, List.getElem_map, renameGate_eval] at h
+ simpa [Function.comp_apply, relocate] using h
+ have hx : ∀ j < n, inputEnv (g.eval x) j = (A ∘ relocate g) j := by
+ intro j hj
+ simp only [inputEnv, dite_eq_left hj, Function.comp_apply, relocate]
+ exact (g.fragment.evalWires_append_old gs (relocate_ordered g f.fragment) x
+ (g.wires ⟨j, hj⟩) (g.wires ⟨j, hj⟩).isLt).symm
+ exact (run_unique n f.fragment.gates _ _ f.fragment.ordered hf hx _ (f.wires i).isLt).symm
+
+namespace Frame
+
+variable {σ τ ρ : Type*} [Fintype σ] [Fintype τ] [Fintype ρ]
+
+/-- Substitute a compiled network for the free inputs of another. -/
+def subst (f : Frame σ τ) (g : Frame ρ σ) : Frame ρ τ :=
+ ⟨spliceCore f.core g.core⟩
+
+@[simp] theorem subst_size (f : Frame σ τ) (g : Frame ρ σ) :
+ (f.subst g).size = g.size + f.size := by
+ simp [subst, size, spliceCore, CircuitBatch.Fragment.append]
+
+@[simp] theorem subst_eval (f : Frame σ τ) (g : Frame ρ σ) (x : ρ → Bool) (i : τ) :
+ (f.subst g).eval x i = f.eval (g.eval x) i := by
+ simp [subst, eval, spliceCore_eval, Function.comp_def]
+
+end Frame
+end VerifierNetwork
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierMembership.lean b/lean/OAI/Computability/VPVNP/VerifierMembership.lean
new file mode 100644
index 0000000000..50a9c8b47e
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierMembership.lean
@@ -0,0 +1,96 @@
+import OAI.Computability.VPVNP.PolynomialBounds
+import OAI.Computability.VPVNP.VerifierCircuit
+
+/-!
+# VNP membership from Boolean verification
+
+For a family of Boolean verifiers with polynomially many choice bits and gates, the
+paired coefficient-counting polynomials lie in VNP. The size and degree estimates
+come from the explicitly compiled arithmetic summand. For the machine-defined
+family, the remaining input to this construction is a polynomial-size Boolean
+circuit family implementing the canonical path verifier.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Verifier
+
+variable {F : Type*} [Field F]
+
+private theorem bounded_of_verifier_bound {t g f : ℕ → ℕ}
+ (ht : PolynomiallyBounded t) (hg : PolynomiallyBounded g)
+ (hf : ∀ n, f n ≤ 8 * (n + t n + g n + 1)) : PolynomiallyBounded f := by
+ exact ((PolynomiallyBounded.const 8).mul
+ (((PolynomiallyBounded.id.add ht).add hg).add (PolynomiallyBounded.const 1))).of_le hf
+
+/-- A bounded Boolean verifier gives a VNP representation of its paired counting
+polynomial, with a formal summand on the visible variables and all witness bits. -/
+theorem isVNP_of_counting_verifier {t g : ℕ → ℕ}
+ (ht : PolynomiallyBounded t) (hg : PolynomiallyBounded g)
+ (c : (n : ℕ) → BooleanTranscript.Circuit (Inputs n (t n)) (g n)) :
+ IsVNP (F := F) (σ := fun n => Fin n × Bool)
+ (fun n => pairedPolynomial (fun x => ∑ y : Fin (t n) → Bool,
+ BooleanTranscript.bit ((c n).eval (Sum.elim x y)))) := by
+ let W (n : ℕ) := Witness n (t n) (g n)
+ let p : Family F (fun n => Fin n × Bool) := fun n => pairedPolynomial (fun x =>
+ ∑ y : Fin (t n) → Bool, BooleanTranscript.bit ((c n).eval (Sum.elim x y)))
+ let s : Family F (fun n => (Fin n × Bool) ⊕ W n) := fun n => summand (c n)
+ change IsVNP p
+ constructor
+ · constructor
+ · apply bounded_of_verifier_bound ht hg
+ intro n
+ simp
+ omega
+ · apply bounded_of_verifier_bound ht hg
+ intro n
+ exact (pairedPolynomial_isHomogeneous _).totalDegree_le.trans (by omega)
+ · refine ⟨W, fun n => inferInstanceAs (Fintype (Witness n (t n) (g n))), s, ?_, ?_, ?_⟩
+ · apply bounded_of_verifier_bound ht hg
+ intro n
+ simp [W, Witness, Inputs]
+ omega
+ · constructor
+ · constructor
+ · apply bounded_of_verifier_bound ht hg
+ intro n
+ simp [W, Witness, Inputs]
+ omega
+ · apply bounded_of_verifier_bound ht hg
+ intro n
+ exact (totalDegree_summand_le _).trans (by omega)
+ · apply bounded_of_verifier_bound ht hg
+ intro n
+ obtain ⟨m, hm, d, hd⟩ := exists_circuit_summand (R := F) (c n)
+ apply (circuitSize_le_iff.mpr ⟨m, hm, d, hd⟩).trans
+ omega
+ · intro n
+ convert (sum_summand (R := F) (c n)).symm using 2
+ · ext w
+ simp
+ · rfl
+
+/-- Applying the generic verifier construction to the machine family (1.1). -/
+theorem P_isVNP_of_verifier {g : ℕ → ℕ}
+ (c : (n : ℕ) → BooleanTranscript.Circuit (Inputs n (n ^ clockExponent)) (g n))
+ (hg : PolynomiallyBounded g)
+ (hc : ∀ n x y, (c n).eval (Sum.elim x y) = verifiesInput x y) :
+ IsVNP (F := F) (σ := fun n => Fin n × Bool)
+ (fun n => MvPolynomial.map (Int.castRingHom F) (P n)) := by
+ have ht : PolynomiallyBounded (fun n => n ^ clockExponent) :=
+ ⟨1, clockExponent, 0, fun n _ => by simp⟩
+ have h := isVNP_of_counting_verifier (F := F) ht hg c
+ convert h using 1
+ funext n
+ rw [map_P]
+ congr 1
+ funext x
+ simpa only [hc, BooleanTranscript.bit] using acceptingCount_eq_sum_witnesses (R := F) x
+
+end Verifier
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierSummand.lean b/lean/OAI/Computability/VPVNP/VerifierSummand.lean
new file mode 100644
index 0000000000..d74a353689
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierSummand.lean
@@ -0,0 +1,116 @@
+import OAI.Computability.VPVNP.BooleanTranscript
+import OAI.Computability.VPVNP.ChoiceWitness
+import OAI.Computability.VPVNP.PairedFamily
+
+/-!
+# The Boolean witness sum for the paired counting polynomial
+
+The summand of §1.1 of *VP and VNP differ over every field* has visible variables
+`(j,b)` and three sets of Boolean summation variables. They encode the input word,
+the path choices, and the gate values of the deterministic verifier. Specialization
+of the Boolean variables leaves a formal polynomial in the visible variables.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Verifier
+
+open MvPolynomial
+open BooleanTranscript (bit)
+
+variable {n t g : ℕ} {R : Type*} [CommRing R]
+
+/-- The verifier reads the word and the path choices. -/
+abbrev Inputs (n t : ℕ) := Fin n ⊕ Fin t
+
+/-- The summation also ranges over the claimed transcript of the verifier. -/
+abbrev Witness (n t g : ℕ) := Inputs n t ⊕ Fin g
+
+/-- Polynomial variables in the verifier summand, consisting of the paired input variables and
+the Boolean witness coordinates. -/
+abbrev Variables (n t g : ℕ) := (Fin n × Bool) ⊕ Witness n t g
+
+/-- Multilinear selector for one pair of indeterminates. -/
+def selector (x z₀ z₁ : R) : R := (1 - x) * z₀ + x * z₁
+
+theorem selector_bit (b : Bool) (z₀ z₁ : R) :
+ selector (bit b) z₀ z₁ = if b then z₁ else z₀ := by
+ cases b <;> simp [selector, bit]
+
+/-- Evaluate only the witness variables on the Boolean cube. -/
+noncomputable def specialize {σ β : Type*} (w : β → Bool) :
+ MvPolynomial (σ ⊕ β) R →+* MvPolynomial σ R :=
+ eval₂Hom C (Sum.elim X (fun i => C (bit (w i))))
+
+@[simp] theorem specialize_X_visible {σ β : Type*} (w : β → Bool) (z : σ) :
+ specialize (R := R) w (X (Sum.inl z)) = X z := by simp [specialize]
+
+@[simp] theorem specialize_X_witness {σ β : Type*} (w : β → Bool) (i : β) :
+ specialize (R := R) (σ := σ) w (X (Sum.inr i)) = C (bit (w i)) := by simp [specialize]
+
+/-- The verifier weight times the selectors, before any witness is fixed. -/
+noncomputable def summand (c : BooleanTranscript.Circuit (Inputs n t) g) :
+ MvPolynomial (Variables n t g) R :=
+ c.weight (fun i => X (.inr (.inl i))) (fun i => X (.inr (.inr i))) *
+ ∏ j : Fin n, selector (X (.inr (.inl (.inl j))))
+ (X (.inl (j, false))) (X (.inl (j, true)))
+
+private theorem C_bit (b : Bool) : C (σ := Fin n × Bool) (bit b : R) = bit b := by
+ cases b <;> simp [bit]
+
+/-- On fixing the witness, each selector becomes the single variable named by the input bit. -/
+theorem specialize_summand (c : BooleanTranscript.Circuit (Inputs n t) g)
+ (u : Inputs n t → Bool) (a : Fin g → Bool) :
+ specialize (R := R) (Sum.elim u a) (summand c) =
+ c.weight (bit ∘ u) (bit ∘ a) * ∏ j : Fin n, X (j, u (.inl j)) := by
+ classical
+ rw [summand, map_mul, c.weight_hom, map_prod]
+ congr 1
+ · congr 1 <;> funext i <;> simp [C_bit]
+ · apply Finset.prod_congr rfl
+ intro j _
+ simp only [selector, map_add, map_mul, map_sub, map_one, specialize_X_witness,
+ specialize_X_visible, Sum.elim_inl, C_bit]
+ cases u (.inl j) <;> simp [bit]
+
+private theorem sum_split {α β A : Type*} [Fintype α] [Fintype β] [DecidableEq α] [DecidableEq β] [AddCommMonoid A]
+ (f : (α ⊕ β → Bool) → A) :
+ ∑ w, f w = ∑ x : α → Bool, ∑ y : β → Bool, f (Sum.elim x y) := by
+ rw [← (Equiv.sumArrowEquivProdArrow α β Bool).symm.sum_comp f, Fintype.sum_prod_type]
+ rfl
+
+/-- Eliminate the auxiliary transcript bits to obtain the coefficient-counting polynomial. -/
+theorem sum_summand (c : BooleanTranscript.Circuit (Inputs n t) g) :
+ ∑ w : Witness n t g → Bool, specialize (R := R) w (summand c) =
+ pairedPolynomial (fun x => ∑ y : Fin t → Bool, bit (c.eval (Sum.elim x y))) := by
+ classical
+ rw [sum_split, sum_split, pairedPolynomial]
+ apply Finset.sum_congr rfl
+ intro x _
+ simp only [specialize_summand, Sum.elim_inl, ← Finset.sum_mul, c.sum_weight_bits]
+ rw [map_sum]
+ congr 1
+ apply Finset.sum_congr rfl
+ intro y _
+ exact (C_bit _).symm
+
+/-- The §1.1 summand computes the actual integer family after base change whenever its
+Boolean circuit implements the canonical path verifier. This separates the exact counting
+identity from the problem of constructing a polynomial-size circuit for that verifier. -/
+theorem sum_summand_eq_map_P
+ (c : BooleanTranscript.Circuit (Inputs n (n ^ clockExponent)) g)
+ (hc : ∀ x y, c.eval (Sum.elim x y) = verifiesInput x y) :
+ ∑ w : Witness n (n ^ clockExponent) g → Bool, specialize (R := R) w (summand c) =
+ MvPolynomial.map (Int.castRingHom R) (P n) := by
+ rw [sum_summand, map_P]
+ congr 1
+ funext x
+ simpa only [hc, bit] using (acceptingCount_eq_sum_witnesses (R := R) x).symm
+
+end Verifier
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/VerifierWeight.lean b/lean/OAI/Computability/VPVNP/VerifierWeight.lean
new file mode 100644
index 0000000000..3418e4e898
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/VerifierWeight.lean
@@ -0,0 +1,131 @@
+import OAI.Computability.VPVNP.BooleanTranscript
+import OAI.Computability.VPVNP.VerifierFormula
+
+/-!
+# Arithmetic formulas for a Boolean verifier's transcript
+
+A reference reads either a Boolean constant, an input variable or a proposed gate
+value. With all transcript values provided as variables, checking one AND or NOT
+gate takes eight binary arithmetic operations and has syntactic degree at most
+three. The final acceptance test multiplies this product by the output bit.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace BooleanTranscript
+
+variable {σ τ R A : Type*} [CommRing R] {n : ℕ}
+
+private def refFormula (r : Ref Bool σ n) (input : σ → τ) (wires : Fin n → τ) : Formula R τ :=
+ r.read (fun b => .const (bit b)) (fun i => .var (input i)) (fun i => .var (wires i))
+
+private theorem eval_refFormula [CommRing A] (r : Ref Bool σ n) (input : σ → τ)
+ (wires : Fin n → τ) (s : R →+* A) (x : τ → A) :
+ (refFormula r input wires).eval s x = r.read bit (x ∘ input) (x ∘ wires) := by
+ cases r with
+ | const b => cases b <;> simp [refFormula, Ref.read, bit, Formula.eval]
+ | var | gate => rfl
+
+private theorem size_refFormula (r : Ref Bool σ n) (input : σ → τ) (wires : Fin n → τ) :
+ (refFormula (R := R) r input wires).size = 0 := by
+ cases r <;> rfl
+
+private theorem degree_refFormula (r : Ref Bool σ n) (input : σ → τ) (wires : Fin n → τ) :
+ (refFormula (R := R) r input wires).degree ≤ 1 := by
+ cases r <;> simp [refFormula, Ref.read, Formula.degree]
+
+private def Gate.arithFormula (g : Gate σ n) (input : σ → τ) (wires : Fin n → τ) : Formula R τ :=
+ match g with
+ | .and a b => (refFormula a input wires).mul (refFormula b input wires)
+ | .not a => (.const (1 : R) : Formula R τ).sub (refFormula a input wires)
+
+private theorem Gate.eval_arithFormula [CommRing A] (g : Gate σ n) (input : σ → τ)
+ (wires : Fin n → τ) (s : R →+* A) (x : τ → A) :
+ (g.arithFormula input wires).eval s x = g.arith (x ∘ input) (x ∘ wires) := by
+ cases g <;> simp [arithFormula, arith, Formula.mul, Formula.sub, Formula.eval,
+ BinOp.apply, eval_refFormula]
+
+private theorem Gate.size_arithFormula (g : Gate σ n) (input : σ → τ) (wires : Fin n → τ) :
+ (g.arithFormula (R := R) input wires).size = 1 := by
+ cases g <;> simp [arithFormula, Formula.mul, Formula.sub, Formula.size, size_refFormula]
+
+private theorem Gate.degree_arithFormula (g : Gate σ n) (input : σ → τ) (wires : Fin n → τ) :
+ (g.arithFormula (R := R) input wires).degree ≤ 2 := by
+ cases g with
+ | and a b => exact Nat.add_le_add (degree_refFormula a input wires) (degree_refFormula b input wires)
+ | not a => exact max_le (Nat.zero_le _) ((degree_refFormula a input wires).trans (by decide))
+
+private def testFormula (a b : Formula R τ) : Formula R τ :=
+ (a.mul b).add (((Formula.const 1).sub a).mul ((Formula.const 1).sub b))
+
+private theorem eval_testFormula [CommRing A] (a b : Formula R τ) (s : R →+* A) (x : τ → A) :
+ (testFormula a b).eval s x = equalBit (a.eval s x) (b.eval s x) := by
+ simp [testFormula, Formula.add, Formula.sub, Formula.mul, Formula.eval, BinOp.apply, equalBit]
+
+private theorem size_testFormula (a b : Formula R τ) :
+ (testFormula a b).size = 2 * a.size + 2 * b.size + 5 := by
+ simp only [testFormula, Formula.add, Formula.sub, Formula.mul, Formula.size]
+ omega
+
+private theorem degree_testFormula (a b : Formula R τ) :
+ (testFormula a b).degree = a.degree + b.degree := by
+ simp [testFormula, Formula.add, Formula.sub, Formula.mul, Formula.degree]
+
+/-- Product of local consistency tests for the proposed gate values. -/
+def Program.checkFormula (input : σ → τ) : {n : ℕ} → Program σ n → (Fin n → τ) → Formula R τ
+ | _, .nil, _ => .const 1
+ | k + 1, .snoc p g, wires => (p.checkFormula input (Fin.init wires)).mul
+ (testFormula (g.arithFormula input (Fin.init wires)) (.var (wires (Fin.last k))))
+
+private theorem Program.eval_checkFormula [CommRing A] (p : Program σ n) (input : σ → τ)
+ (wires : Fin n → τ) (s : R →+* A) (x : τ → A) :
+ (p.checkFormula input wires).eval s x = p.check (x ∘ input) (x ∘ wires) := by
+ induction p with
+ | nil => simp [checkFormula, check, Formula.eval]
+ | snoc p g ih =>
+ simp [checkFormula, check, Formula.mul, Formula.eval, BinOp.apply, eval_testFormula,
+ Gate.eval_arithFormula, ih, Fin.comp_init]
+
+private theorem Program.size_checkFormula (p : Program σ n) (input : σ → τ) (wires : Fin n → τ) :
+ (p.checkFormula (R := R) input wires).size = 8 * n := by
+ induction p with
+ | nil => rfl
+ | snoc p g ih =>
+ simp only [checkFormula, Formula.mul, Formula.size, size_testFormula, Gate.size_arithFormula, ih]
+ omega
+
+private theorem Program.degree_checkFormula_le (p : Program σ n) (input : σ → τ)
+ (wires : Fin n → τ) : (p.checkFormula (R := R) input wires).degree ≤ 3 * n := by
+ induction p with
+ | nil => rfl
+ | @snoc k p g ih =>
+ simp only [checkFormula, Formula.mul, Formula.degree, degree_testFormula]
+ have := g.degree_arithFormula (R := R) input (Fin.init wires)
+ have := ih (Fin.init wires)
+ omega
+
+/-- Formula for the product of all gate tests and the designated output. -/
+def Circuit.weightFormula (c : Circuit σ n) (input : σ → τ) (wires : Fin n → τ) : Formula R τ :=
+ (c.program.checkFormula input wires).mul (refFormula c.output input wires)
+
+theorem Circuit.eval_weightFormula [CommRing A] (c : Circuit σ n) (input : σ → τ)
+ (wires : Fin n → τ) (s : R →+* A) (x : τ → A) :
+ (c.weightFormula input wires).eval s x = c.weight (x ∘ input) (x ∘ wires) := by
+ simp [weightFormula, weight, Formula.mul, Formula.eval, BinOp.apply,
+ Program.eval_checkFormula, eval_refFormula]
+
+theorem Circuit.size_weightFormula_le (c : Circuit σ n) (input : σ → τ) (wires : Fin n → τ) :
+ (c.weightFormula (R := R) input wires).size ≤ 8 * n + 1 := by
+ simp [weightFormula, Formula.mul, Formula.size, Program.size_checkFormula, size_refFormula]
+
+theorem Circuit.degree_weightFormula_le (c : Circuit σ n) (input : σ → τ) (wires : Fin n → τ) :
+ (c.weightFormula (R := R) input wires).degree ≤ 3 * n + 1 :=
+ Nat.add_le_add (c.program.degree_checkFormula_le input wires) (degree_refFormula c.output input wires)
+
+end BooleanTranscript
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WalkDenominators.lean b/lean/OAI/Computability/VPVNP/WalkDenominators.lean
new file mode 100644
index 0000000000..3cc96cbe1c
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WalkDenominators.lean
@@ -0,0 +1,97 @@
+import Mathlib.Algebra.Order.Archimedean.Real.Basic
+import Mathlib.Algebra.Divisibility.Basic
+import Mathlib.Algebra.Order.GroupWithZero.Basic
+import Mathlib.Tactic.Linarith
+
+/-!
+# Choosing the port count for the averaged lazy walk
+
+In Section 5.3 of *VP and VNP differ over every field*, the mean of the first
+`t` positive powers of a lazy walk on a `b`-regular graph has common
+denominator `t * (2 * b) ^ t`. The port set has size `Q = D ^ (4 * t)`.
+Here `t`, `D` and `b` are powers of two. A sufficiently large choice of `D`
+makes the port count divisible by this denominator for *every* rounded
+degree satisfying the support bound `2 * b ≤ 16 * C * D`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+/-- Sufficient size conditions for the divisibility in the first paragraph
+of the port construction. -/
+theorem walk_denominator_dvd_port_count {k d e C : ℕ}
+ (ht : 2 ^ k ≤ 2 ^ d) (hC : 16 * C ≤ 2 ^ d)
+ (hdegree : 2 * 2 ^ e ≤ 16 * C * 2 ^ d) :
+ 2 ^ k * (2 * 2 ^ e) ^ (2 ^ k) ∣ (2 ^ d) ^ (4 * 2 ^ k) := by
+ have hkd : k ≤ d := (pow_le_pow_iff_right₀ (by decide : 1 < (2 : ℕ))).mp ht
+ have hpower : 2 ^ (1 + e) ≤ (2 : ℕ) ^ (d + d) := by
+ rw [pow_add, pow_one, pow_add]
+ exact hdegree.trans (Nat.mul_le_mul_right _ hC)
+ have he : 1 + e ≤ d + d := (pow_le_pow_iff_right₀ (by decide : 1 < (2 : ℕ))).mp hpower
+ have htpos := Nat.two_pow_pos k
+ have hkt : k ≤ d * 2 ^ k := hkd.trans (Nat.le_mul_of_pos_right _ htpos)
+ have hexp : k + (1 + e) * 2 ^ k ≤ d * (4 * 2 ^ k) := by
+ nlinarith only [hkt, Nat.mul_le_mul_right (2 ^ k) he]
+ have hb : 2 * 2 ^ e = (2 : ℕ) ^ (1 + e) := by rw [pow_add, pow_one]
+ rw [hb, ← pow_mul, ← pow_add, ← pow_mul]
+ exact pow_dvd_pow _ hexp
+
+/-- The sparse recursion may request arbitrarily large starting order `D`.
+Choose it before the rounded degree `b` is known. -/
+theorem exists_walk_port_order (k C minimum : ℕ) :
+ ∃ d : ℕ, minimum ≤ 2 ^ d ∧ 2 ≤ 2 ^ d ∧
+ ∀ e : ℕ, 2 * 2 ^ e ≤ 16 * C * 2 ^ d →
+ 2 ^ k * (2 * 2 ^ e) ^ (2 ^ k) ∣ (2 ^ d) ^ (4 * 2 ^ k) := by
+ let d := max k (max (16 * C) (max minimum 1))
+ have hkd : k ≤ d := le_max_left _ _
+ have hCd : 16 * C ≤ d := (le_max_left _ _).trans (le_max_right _ _)
+ have hm : minimum ≤ d := ((le_max_left _ _).trans (le_max_right _ _)).trans (le_max_right _ _)
+ have h1 : 1 ≤ d := ((le_max_right _ _).trans (le_max_right _ _)).trans (le_max_right _ _)
+ have hd : d < 2 ^ d := Nat.lt_two_pow_self
+ refine ⟨d, hm.trans hd.le, by omega, fun _ he ↦ ?_⟩
+ exact walk_denominator_dvd_port_count (Nat.pow_le_pow_right (by decide) hkd) (hCd.trans hd.le) he
+
+/-- When the sparse Poincaré bound grows like `α ^ j` with `α < m = 2^r`,
+choose `j` so that the even smoothing length `t = m^j / 4` dominates the
+rounded port bound `β = max 1 (2*C' * α^j)` by the factor `1776` used in
+the cloud iteration. -/
+theorem exists_walk_smoothing_scale (r : ℕ) (hr : 0 < r) {α : ℝ} (hα : 1 ≤ α)
+ (hsmall : α < 2 ^ r) (C' : ℝ) :
+ ∃ j k : ℕ, 0 < k ∧ ((2 : ℕ) ^ r) ^ j = 4 * 2 ^ k ∧
+ 1776 * max 1 (2 * C' * α ^ j) ≤ (2 : ℝ) ^ k := by
+ let B := max 1 (2 * C')
+ have hB : 1 ≤ B := le_max_left _ _
+ have hBpos : 0 < B := zero_lt_one.trans_le hB
+ have hm : 0 < (2 : ℝ) ^ r := by positivity
+ have hratio : α / 2 ^ r < 1 := (div_lt_one hm).mpr hsmall
+ obtain ⟨i, hi⟩ := exists_pow_lt_of_lt_one (by positivity : 0 < 1 / (7104 * B)) hratio
+ let j := i + 3
+ let k := r * j - 2
+ have hrj : 3 ≤ r * j := by
+ have := Nat.le_mul_of_pos_left j hr
+ dsimp [j] at *
+ omega
+ have hk : k + 2 = r * j := Nat.sub_add_cancel (by omega)
+ have hcard : ((2 : ℕ) ^ r) ^ j = 4 * 2 ^ k := by
+ rw [← pow_mul, ← hk, pow_add]; omega
+ have hsmallj : (α / 2 ^ r) ^ j ≤ 1 / (7104 * B) := by
+ refine le_trans ?_ hi.le
+ exact pow_le_pow_of_le_one (div_nonneg (by linarith) hm.le) hratio.le (by dsimp [j]; omega)
+ rw [div_pow] at hsmallj
+ have hscale := (div_le_div_iff₀ (pow_pos hm _) (by positivity)).mp hsmallj
+ have hreal : ((2 : ℝ) ^ r) ^ j = 4 * 2 ^ k := by exact_mod_cast hcard
+ have hpower : 1 ≤ α ^ j := one_le_pow₀ hα
+ have hbeta : max 1 (2 * C' * α ^ j) ≤ B * α ^ j := max_le
+ (one_le_mul_of_one_le_of_one_le hB hpower)
+ (mul_le_mul_of_nonneg_right (le_max_right _ _) (by linarith only [hpower]))
+ refine ⟨j, k, by dsimp [k]; omega, hcard, ?_⟩
+ linarith only [hreal, hscale, hbeta]
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WalkEnergy.lean b/lean/OAI/Computability/VPVNP/WalkEnergy.lean
new file mode 100644
index 0000000000..78ad020ad9
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WalkEnergy.lean
@@ -0,0 +1,277 @@
+import OAI.Computability.VPVNP.Barycenter
+import Mathlib.Data.Matrix.Basic
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+import Mathlib.Tactic.FieldSimp
+
+/-!
+# Barycentric smoothing of a finite walk
+
+Section 5.3 of *VP and VNP differ over every field* bounds the squared-distance
+Poincaré constant of the Cesàro average of powers of a lazy walk. All energies
+here multiply the paper's averages by the number of vertices. This common
+factor cancels in the Poincaré inequality.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+variable {ι X : Type*} [Fintype ι] [DecidableEq ι] [PseudoMetricSpace X]
+
+/-- Sum of squared lengths over the directed edges with the given weights. -/
+noncomputable def walkEnergy (A : Matrix ι ι ℝ) (x : ι → X) : ℝ :=
+ ∑ i, ∑ j, A i j * dist (x j) (x i) ^ 2
+
+/-- Row `i`'s mean squared distance from the previous configuration to its new center. -/
+noncomputable def rowVariance (A : Matrix ι ι ℝ) (x : ℕ → ι → X) (h : ℕ) (i : ι) : ℝ :=
+ ∑ j, A i j * dist (x h j) (x (h + 1) i) ^ 2
+
+private noncomputable def accumulatedVariance (A : Matrix ι ι ℝ) (x : ℕ → ι → X) : ℕ → ι → ℝ
+ | 0, _ => 0
+ | h + 1, i => rowVariance A x h i + ∑ j, A i j * accumulatedVariance A x h j
+
+private theorem variance_row_le (A : Matrix ι ι ℝ) (hn : ∀ i j, 0 ≤ A i j)
+ (x : ℕ → ι → X)
+ (hvar : ∀ h i z, rowVariance A x h i + dist (x (h + 1) i) z ^ 2 ≤
+ ∑ j, A i j * dist (x h j) z ^ 2)
+ (h : ℕ) (i : ι) (z : X) :
+ accumulatedVariance A x h i + dist (x h i) z ^ 2 ≤
+ ∑ j, (A ^ h) i j * dist (x 0 j) z ^ 2 := by
+ induction h generalizing i with
+ | zero => simp [accumulatedVariance, Matrix.one_apply, ite_mul]
+ | succ h ih =>
+ have hprev := Finset.sum_le_sum (s := Finset.univ) fun j _ ↦
+ mul_le_mul_of_nonneg_left (ih j) (hn i j)
+ simp_rw [mul_add, Finset.sum_add_distrib] at hprev
+ have hrew : (∑ j, A i j * ∑ k, (A ^ h) j k * dist (x 0 k) z ^ 2) =
+ ∑ k, (A ^ (h + 1)) i k * dist (x 0 k) z ^ 2 := by
+ rw [pow_succ']
+ simp_rw [Finset.mul_sum, Matrix.mul_apply, Finset.sum_mul, mul_assoc]
+ exact Finset.sum_comm
+ rw [hrew] at hprev
+ unfold accumulatedVariance
+ linarith only [hvar h i z, hprev]
+
+omit [DecidableEq ι] in
+private theorem sum_accumulatedVariance (A : Matrix ι ι ℝ) (hcol : ∀ j, ∑ i, A i j = 1)
+ (x : ℕ → ι → X) (h : ℕ) :
+ ∑ i, accumulatedVariance A x h i = ∑ g ∈ Finset.range h, ∑ i, rowVariance A x g i := by
+ induction h with
+ | zero => simp [accumulatedVariance]
+ | succ h ih =>
+ simp only [accumulatedVariance, Finset.sum_add_distrib, Finset.sum_range_succ]
+ rw [Finset.sum_comm (f := fun i j ↦ A i j * accumulatedVariance A x h j)]
+ simp_rw [← Finset.sum_mul, hcol, one_mul]
+ rw [ih, add_comm]
+
+/-- Repeated conditioning using the variance inequality in each row. The edge
+energy of an `h`-step stationary walk pays for the displacement of its barycentric
+iterate and for all the intermediate row variances (Section 5.3, page 18). -/
+theorem walkEnergy_ge_variances (A : Matrix ι ι ℝ) (hn : ∀ i j, 0 ≤ A i j)
+ (hcol : ∀ j, ∑ i, A i j = 1) (x : ℕ → ι → X)
+ (hvar : ∀ h i z, rowVariance A x h i + dist (x (h + 1) i) z ^ 2 ≤
+ ∑ j, A i j * dist (x h j) z ^ 2) (h : ℕ) :
+ (∑ i, dist (x h i) (x 0 i) ^ 2) + (∑ g ∈ Finset.range h, ∑ i, rowVariance A x g i) ≤
+ walkEnergy (A ^ h) (x 0) := by
+ have hb := Finset.sum_le_sum (s := Finset.univ) fun i _ ↦
+ variance_row_le A hn x hvar h i (x 0 i)
+ rwa [Finset.sum_add_distrib, sum_accumulatedVariance A hcol, add_comm] at hb
+
+/-- Comparison through each row's center for the lazy stochastic matrix in §5.3. -/
+theorem walkEnergy_le_four_localEnergy (P : Matrix ι ι ℝ)
+ (hP : ∀ i j, 0 ≤ P i j) (hrow : ∀ i, ∑ j, P i j = 1) (y b : ι → X) :
+ (∑ i, ∑ j, P i j * dist (y i) (y j) ^ 2) ≤
+ 4 * ∑ i, ∑ j, (((if i = j then 1 else 0) + P i j) / 2) *
+ dist (b i) (y j) ^ 2 := by
+ rw [Finset.mul_sum]
+ apply Finset.sum_le_sum
+ intro i _
+ have triangle (j : ι) :
+ dist (y i) (y j) ^ 2 ≤ 2 * (dist (b i) (y i) ^ 2 + dist (b i) (y j) ^ 2) := by
+ have h := dist_triangle (y i) (b i) (y j)
+ rw [dist_comm (y i) (b i)] at h
+ have hs := pow_le_pow_left₀ dist_nonneg h 2
+ nlinarith [sq_nonneg (dist (b i) (y i) - dist (b i) (y j))]
+ calc
+ _ ≤ ∑ j, P i j * (2 * (dist (b i) (y i) ^ 2 + dist (b i) (y j) ^ 2)) :=
+ Finset.sum_le_sum fun j _ => mul_le_mul_of_nonneg_left (triangle j) (hP i j)
+ _ = 2 * (dist (b i) (y i) ^ 2 + ∑ j, P i j * dist (b i) (y j) ^ 2) := by
+ simp_rw [show ∀ j, P i j * (2 * (dist (b i) (y i) ^ 2 + dist (b i) (y j) ^ 2)) =
+ 2 * (P i j * dist (b i) (y i) ^ 2 + P i j * dist (b i) (y j) ^ 2) by
+ intro j; ring]
+ rw [← Finset.mul_sum, Finset.sum_add_distrib, ← Finset.sum_mul, hrow, one_mul]
+ _ = _ := by
+ rw [Finset.mul_sum]
+ simp_rw [show ∀ j, 4 * (((if i = j then 1 else 0) + P i j) / 2 *
+ dist (b i) (y j) ^ 2) = 2 * ((if i = j then dist (b i) (y j) ^ 2 else 0) +
+ P i j * dist (b i) (y j) ^ 2) by intro j; split_ifs <;> ring]
+ rw [← Finset.mul_sum, Finset.sum_add_distrib]
+ simp
+
+omit [DecidableEq ι] in
+/-- Comparison of pairwise squared distances through an intermediate configuration in §5.3. -/
+theorem pairVariance_le_displacement_variance (x y : ι → X) :
+ (∑ i, ∑ j, dist (x i) (x j) ^ 2) ≤
+ 3 * (2 * (Fintype.card ι : ℝ) * (∑ i, dist (x i) (y i) ^ 2) +
+ ∑ i, ∑ j, dist (y i) (y j) ^ 2) := by
+ have pointwise (i j : ι) :
+ dist (x i) (x j) ^ 2 ≤ 3 * (dist (x i) (y i) ^ 2 + dist (x j) (y j) ^ 2 +
+ dist (y i) (y j) ^ 2) := by
+ have h₁ := dist_triangle (x i) (y i) (x j)
+ have h₂ := dist_triangle (y i) (y j) (x j)
+ rw [dist_comm (y j) (x j)] at h₂
+ have h := pow_le_pow_left₀ dist_nonneg (h₁.trans (add_le_add_right h₂ _)) 2
+ nlinarith [sq_nonneg (dist (x i) (y i) - dist (x j) (y j)),
+ sq_nonneg (dist (x i) (y i) - dist (y i) (y j)),
+ sq_nonneg (dist (x j) (y j) - dist (y i) (y j))]
+ calc
+ _ ≤ ∑ i, ∑ j, 3 * (dist (x i) (y i) ^ 2 + dist (x j) (y j) ^ 2 +
+ dist (y i) (y j) ^ 2) :=
+ Finset.sum_le_sum fun i _ => Finset.sum_le_sum fun j _ => pointwise i j
+ _ = _ := by
+ simp only [← Finset.mul_sum, Finset.sum_add_distrib, Finset.sum_const,
+ Finset.card_univ, nsmul_eq_mul]
+ ring
+
+/-- Index selection in the CAT(0) walk averaging argument of Section 5.3.
+The first half of the walk lengths pays for all the displacements. Each walk
+in the second half pays for every energy in the first half. -/
+theorem exists_walk_energy_le_average {n : ℕ} (hn : 0 < n) (D E W : ℕ → ℝ)
+ (hD : ∀ g, 0 ≤ D g) (hE : ∀ g, 0 ≤ E g) (hzero : D 0 = 0)
+ (hwalk : ∀ h, D (h + 1) + ∑ k ∈ Finset.range (h + 1), E k ≤ W (h + 1)) :
+ ∃ g < n, D g + (n : ℝ) * E g ≤
+ (∑ h ∈ Finset.range (2 * n), W (h + 1)) / n := by
+ have hshift := Finset.sum_range_succ' D n
+ rw [Finset.sum_range_succ, hzero, add_zero] at hshift
+ have hnext : ∑ g ∈ Finset.range n, D (g + 1) ≤ ∑ g ∈ Finset.range n, W (g + 1) := by
+ apply Finset.sum_le_sum
+ intro g _
+ linarith only [hwalk g, Finset.sum_nonneg (s := Finset.range (g + 1)) (fun k _ ↦ hE k)]
+ have hfirst : ∑ g ∈ Finset.range n, D g ≤ ∑ g ∈ Finset.range n, W (g + 1) := by
+ linarith only [hshift, hnext, hD n]
+ have henergy (g : ℕ) : ∑ k ∈ Finset.range n, E k ≤ W (n + g + 1) := by
+ have hsub : ∑ k ∈ Finset.range n, E k ≤ ∑ k ∈ Finset.range (n + g + 1), E k :=
+ Finset.sum_le_sum_of_subset_of_nonneg (Finset.range_subset_range.mpr (by omega))
+ (fun k _ _ ↦ hE k)
+ linarith only [hsub, hwalk (n + g), hD (n + g + 1)]
+ have hsecond : (n : ℝ) * (∑ k ∈ Finset.range n, E k) ≤
+ ∑ g ∈ Finset.range n, W (n + g + 1) := by
+ simpa only [Finset.sum_const, Finset.card_range, nsmul_eq_mul] using
+ (Finset.sum_le_sum (s := Finset.range n) (fun g _ ↦ henergy g))
+ let total := ∑ h ∈ Finset.range (2 * n), W (h + 1)
+ have hsum : ∑ g ∈ Finset.range n, (D g + (n : ℝ) * E g) ≤ total := by
+ dsimp only [total]
+ rw [Finset.sum_add_distrib, ← Finset.mul_sum, two_mul,
+ Finset.sum_range_add (fun h ↦ W (h + 1)) n n]
+ exact add_le_add hfirst hsecond
+ have hn' : (0 : ℝ) < n := Nat.cast_pos.mpr hn
+ have hmean : ∑ _g ∈ Finset.range n, total / n = total := by
+ rw [Finset.sum_const, Finset.card_range, nsmul_eq_mul, mul_comm, div_mul_cancel₀ _ hn'.ne']
+ obtain ⟨g, hg, h⟩ := Finset.exists_le_of_sum_le (Finset.nonempty_range_iff.mpr hn.ne')
+ (hsum.trans_eq hmean.symm)
+ exact ⟨g, Finset.mem_range.mp hg, h⟩
+
+/-- The scalar estimate converting the selected walk bound to the amplified
+Poincaré coefficient `max 12 (48 * γ / t)` in Section 5.3. -/
+theorem walk_poincare_coefficient {D E S t γ : ℝ} (ht : 0 < t) (hD : 0 ≤ D) (hE : 0 ≤ E)
+ (hmean : D + (t / 2) * E ≤ 2 * S) :
+ 3 * (2 * D + 4 * γ * E) ≤ max 12 (48 * γ / t) * S := by
+ let M := max 12 (48 * γ / t)
+ have hleft : 12 ≤ M := le_max_left _ _
+ have hright : 48 * γ ≤ M * t := (div_le_iff₀ ht).mp (le_max_right _ _)
+ calc
+ 3 * (2 * D + 4 * γ * E) = 6 * D + (12 * γ) * E := by ring
+ _ ≤ (M / 2) * D + (M * t / 4) * E :=
+ add_le_add (mul_le_mul_of_nonneg_right (by linarith only [hleft]) hD)
+ (mul_le_mul_of_nonneg_right (by linarith only [hright]) hE)
+ _ = (M / 2) * (D + (t / 2) * E) := by ring
+ _ ≤ (M / 2) * (2 * S) := mul_le_mul_of_nonneg_left hmean (by linarith only [hleft])
+ _ = M * S := by ring
+
+/-- Poincaré inequality in the normalization obtained by multiplying the paper's
+variance and edge energy by the order of the graph. -/
+def HasPoincareBound (X : Type*) [PseudoMetricSpace X] (A : Matrix ι ι ℝ) (γ : ℝ) : Prop :=
+ ∀ x : ι → X, (∑ i, ∑ j, dist (x i) (x j) ^ 2) / Fintype.card ι ≤ γ * walkEnergy A x
+
+/-- Add a one-half probability of staying at the current vertex. -/
+noncomputable def lazyWalk (P : Matrix ι ι ℝ) : Matrix ι ι ℝ :=
+ fun i j ↦ ((if i = j then 1 else 0) + P i j) / 2
+
+/-- Uniform mixture of lengths from one to `t`, inclusive. -/
+noncomputable def cesaroWalk (A : Matrix ι ι ℝ) (t : ℕ) : Matrix ι ι ℝ :=
+ fun i j ↦ (∑ h ∈ Finset.range t, (A ^ (h + 1)) i j) / t
+
+private theorem walkEnergy_cesaro (A : Matrix ι ι ℝ) (t : ℕ) (x : ι → X) :
+ walkEnergy (cesaroWalk A t) x = (∑ h ∈ Finset.range t, walkEnergy (A ^ (h + 1)) x) / t := by
+ unfold walkEnergy cesaroWalk
+ simp_rw [div_mul_eq_mul_div, Finset.sum_mul, div_eq_mul_inv, ← Finset.sum_mul]
+ congr 1
+ simp_rw [Finset.sum_mul]
+ calc
+ _ = ∑ i, ∑ h ∈ Finset.range t, ∑ j, (A ^ (h + 1)) i j * dist (x j) (x i) ^ 2 :=
+ Finset.sum_congr rfl fun i _ ↦ Finset.sum_comm
+ _ = _ := Finset.sum_comm
+
+/-- The averaging estimate in Section 5.3. The Cesàro average of the first `2n`
+lazy powers has a Poincaré bound independent of `γ` once the number of powers
+is proportional to `γ`. Symmetry of the original matrix may be replaced by
+stationarity of the uniform measure, expressed by its column sums. -/
+theorem cesaroWalk_hasPoincareBound [Nonempty ι] [CompleteSpace X] [Nonempty X]
+ (hcat : HasCATZeroSegments X) (P : Matrix ι ι ℝ) (hP : ∀ i j, 0 ≤ P i j)
+ (hrow : ∀ i, ∑ j, P i j = 1) (hcol : ∀ j, ∑ i, P i j = 1)
+ {γ : ℝ} (hγ : 0 ≤ γ) (hbound : HasPoincareBound X P γ) {n : ℕ} (hn : 0 < n) :
+ HasPoincareBound X (cesaroWalk (lazyWalk P) (2 * n)) (max 12 (48 * γ / (2 * n))) := by
+ let A := lazyWalk P
+ have ha (i j : ι) : 0 ≤ A i j := by
+ unfold A lazyWalk
+ split_ifs <;> linarith only [hP i j]
+ have harow (i : ι) : ∑ j, A i j = 1 := by
+ simp [A, lazyWalk, div_eq_mul_inv, ← Finset.sum_mul, Finset.sum_add_distrib, hrow]
+ norm_num
+ have hacol (j : ι) : ∑ i, A i j = 1 := by
+ simp [A, lazyWalk, div_eq_mul_inv, ← Finset.sum_mul, Finset.sum_add_distrib, hcol]
+ norm_num
+ choose center hc using fun (p : ι → X) (i : ι) ↦
+ exists_barycenter_variance hcat (A i) p (ha i) (harow i)
+ intro x₀
+ let x : ℕ → ι → X := fun k ↦ Nat.rec x₀ (fun _ p ↦ center p) k
+ have hvar (g : ℕ) (i : ι) (z : X) : rowVariance A x g i + dist (x (g+1) i) z ^ 2 ≤
+ ∑ j, A i j * dist (x g j) z ^ 2 := hc (x g) i z
+ let D (g : ℕ) := ∑ i, dist (x g i) (x 0 i) ^ 2
+ let E (g : ℕ) := ∑ i, rowVariance A x g i
+ let W (h : ℕ) := walkEnergy (A ^ h) (x 0)
+ have hD (g : ℕ) : 0 ≤ D g := Finset.sum_nonneg fun _ _ ↦ sq_nonneg _
+ have hE (g : ℕ) : 0 ≤ E g := Finset.sum_nonneg fun i _ ↦
+ Finset.sum_nonneg fun j _ ↦ mul_nonneg (ha i j) (sq_nonneg _)
+ have hDzero : D 0 = 0 := by simp [D]
+ obtain ⟨g, _, hmean⟩ := exists_walk_energy_le_average hn D E W hD hE hDzero
+ (fun h ↦ walkEnergy_ge_variances A ha hacol x hvar (h+1))
+ have hlocal : walkEnergy P (x g) ≤ 4 * E g := by
+ simpa only [walkEnergy, E, rowVariance, A, lazyWalk, dist_comm] using
+ walkEnergy_le_four_localEnergy P hP hrow (x g) (x (g+1))
+ have hcard : 0 < (Fintype.card ι : ℝ) := by exact_mod_cast Fintype.card_pos
+ have hnext := pairVariance_le_displacement_variance (x 0) (x g)
+ simp only [dist_comm (x 0 _) (x g _)] at hnext
+ have hratio : (∑ i, ∑ j, dist (x 0 i) (x 0 j) ^ 2) / Fintype.card ι ≤
+ 3 * (2 * D g + 4 * γ * E g) := by
+ apply (div_le_iff₀ hcard).mpr
+ have hmid := (div_le_iff₀ hcard).mp (hbound (x g))
+ have hres := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hlocal hγ) hcard.le
+ dsimp only [D]
+ linarith only [hnext, hmid, hres]
+ have hn' : (0 : ℝ) < n := Nat.cast_pos.mpr hn
+ have hpay : D g + (2 * (n : ℝ) / 2) * E g ≤ 2 * walkEnergy (cesaroWalk A (2*n)) (x 0) := by
+ rw [walkEnergy_cesaro]
+ push_cast
+ change D g + 2 * (n : ℝ) / 2 * E g ≤ 2 * ((∑ h ∈ Finset.range (2 * n), W (h + 1)) / (2 * n))
+ convert hmean using 1 <;> ring
+ exact hratio.trans (walk_poincare_coefficient (by positivity : 0 < 2 * (n : ℝ))
+ (hD g) (hE g) hpay)
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WidthRounding.lean b/lean/OAI/Computability/VPVNP/WidthRounding.lean
new file mode 100644
index 0000000000..b5621e6916
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WidthRounding.lean
@@ -0,0 +1,85 @@
+import Mathlib.Algebra.BigOperators.Field
+import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise
+import Mathlib.Basic.Real.Basic
+import Mathlib.Order.Interval.Finset.Fin
+import Mathlib.Tactic.FieldSimp
+import Mathlib.Tactic.Linarith
+import Mathlib.Tactic.Ring
+
+/-!
+# Integer wire widths in the shrinking step
+
+Section 7.2 of *VP and VNP differ over every field* divides a bundled wire
+into equal-mass slots. An integral width `b` splits into slots of widths
+`b / q` and `b / q + 1`. The excess in the sum of squares is exactly
+`r * (q - r) / q`, where `r` is the remainder, and hence is at most `q / 4`.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace Compression
+
+open scoped BigOperators
+
+/-- The first `b % q` slots receive the extra bit. -/
+def splitWidth (b q : ℕ) (i : Fin q) : ℕ :=
+ if i.val < b % q then b / q + 1 else b / q
+
+private theorem sum_splitWidth_apply {M : Type*} [AddCommMonoid M] (f : ℕ → M)
+ (b q : ℕ) (hq : 0 < q) :
+ ∑ i : Fin q, f (splitWidth b q i) =
+ (b % q) • f (b / q + 1) + (q - b % q) • f (b / q) := by
+ let r : Fin q := ⟨b % q, Nat.mod_lt _ hq⟩
+ have hlo : Finset.univ.filter (fun i : Fin q => i < r) = Finset.Iio r := by ext; simp
+ have hhi : Finset.univ.filter (fun i : Fin q => ¬ i < r) = Finset.Ici r := by ext; simp
+ change (∑ i : Fin q, f (if i < r then b / q + 1 else b / q)) = _
+ simp only [apply_ite f, Finset.sum_ite, hlo, hhi, Finset.sum_const, Fin.card_Iio, Fin.card_Ici, r]
+
+/-- Concatenating the split payloads recovers exactly the old bit count. -/
+theorem sum_splitWidth (b q : ℕ) (hq : 0 < q) : ∑ i : Fin q, splitWidth b q i = b := by
+ have hr := Nat.mod_lt b hq
+ calc
+ ∑ i : Fin q, splitWidth b q i =
+ b % q * (b / q + 1) + (q - b % q) * (b / q) := by
+ simpa using sum_splitWidth_apply id b q hq
+ _ = (b % q + (q - b % q)) * (b / q) + b % q := by ring
+ _ = b := by rw [show b % q + (q - b % q) = q by omega, Nat.div_add_mod]
+
+/-- Exact sum of squared widths, expressed as the fractional optimum plus the
+rounding error. -/
+theorem sum_splitWidth_sq (b q : ℕ) (hq : 0 < q) :
+ ∑ i : Fin q, (splitWidth b q i : ℝ) ^ 2 =
+ (b : ℝ) ^ 2 / q + (b % q : ℕ) * ((q : ℝ) - (b % q : ℕ)) / q := by
+ have hq' : (q : ℝ) ≠ 0 := by exact_mod_cast hq.ne'
+ have hb : (b : ℝ) = (q : ℝ) * (b / q : ℕ) + (b % q : ℕ) := by
+ exact_mod_cast (Nat.div_add_mod b q).symm
+ rw [sum_splitWidth_apply (fun w : ℕ => (w : ℝ) ^ 2) b q hq, hb]
+ simp only [nsmul_eq_mul, Nat.cast_sub (Nat.mod_lt _ hq).le, Nat.cast_add, Nat.cast_one]
+ field_simp
+ ring
+
+/-- The error from rounding all the widths is at most one quarter per slot. -/
+theorem sum_splitWidth_sq_le (b q : ℕ) (hq : 0 < q) :
+ ∑ i : Fin q, (splitWidth b q i : ℝ) ^ 2 ≤ (b : ℝ) ^ 2 / q + q / 4 := by
+ rw [sum_splitWidth_sq _ _ hq]
+ apply add_le_add_right
+ apply (div_le_iff₀ (by exact_mod_cast hq : (0 : ℝ) < q)).mpr
+ nlinarith [sq_nonneg ((q : ℝ) / 2 - (b % q : ℕ))]
+
+/-- With mass `p` per slot, the energy penalty for integral splitting is at
+most `q / (4*p)`. This applies to both subdivisions in Section 7.2. -/
+theorem splitWidth_energy_le (b q : ℕ) (hq : 0 < q) (p : ℝ) (hp : 0 < p) :
+ ∑ i : Fin q, (splitWidth b q i : ℝ) ^ 2 / p ≤ (b : ℝ) ^ 2 / (q * p) + q / (4 * p) := by
+ rw [← Finset.sum_div]
+ calc
+ _ ≤ ((b : ℝ) ^ 2 / q + q / 4) / p :=
+ div_le_div_of_nonneg_right (sum_splitWidth_sq_le _ _ hq) hp.le
+ _ = _ := by rw [add_div, div_div, div_div]
+
+end Compression
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WireCATZero.lean b/lean/OAI/Computability/VPVNP/WireCATZero.lean
new file mode 100644
index 0000000000..03511da978
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WireCATZero.lean
@@ -0,0 +1,77 @@
+import OAI.Computability.VPVNP.GeodesicExtension
+import OAI.Computability.VPVNP.SpectralCurvature
+import OAI.Computability.VPVNP.SpectralGeometry
+import OAI.Computability.VPVNP.WireCoupling
+
+/-!
+# CAT(0) completion and the six-party wire inequality
+
+Combining Corollary 2.5, the shifted crossing rigidity, and the squared
+midpoint comparison yields a complete CAT(0) target for each spectral point.
+The completion still has finite configurations realized by spectral points
+over the same coefficient field. Lemma 6.2 then applies to its six wire parties.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open WireTensor SpectralGeometry
+
+/-- Every geodesic space with finite configurations realized by wire metrics
+satisfies the CAT(0) squared-distance comparison (4.2). -/
+theorem hasCATZeroSegments_of_realizable (k : Type*) [Field k] {X : Type*} [MetricSpace X]
+ (hf : HasFractions X) (hr : RealizableConfigurations k X) : HasCATZeroSegments X :=
+ hasCATZeroSegments_of_wire_transport k (fun _ _ _ G ↦ G.fractionTransport) hf hr
+
+/-- At equality in Lemma 4.1, the sectors based at the midpoint and ending
+at the third vertex are Euclidean throughout. -/
+theorem euclideanSectors_of_realizable (k : Type*) [Field k] {X : Type*} [MetricSpace X]
+ (hf : HasFractions X) (hr : RealizableConfigurations k X) {o x y z : X}
+ (ho : AtFraction x y (1 / 2) o) (a : RadialSegment o x) (b : RadialSegment o y)
+ (c : RadialSegment o z) (heq : 2 * dist z o ^ 2 + (1 / 2 : ℝ) * dist x y ^ 2 =
+ dist z x ^ 2 + dist z y ^ 2) : IsEuclideanSector hf a c ∧ IsEuclideanSector hf b c :=
+ euclideanSectors_of_wire_transport k (fun _ _ _ G ↦ G.fractionTransport) hf hr ho a b c heq
+
+end WireGeometry
+
+namespace WireTensor.SpectralPoint
+
+open WireGeometry SpectralGeometry
+
+variable {k : Type*} [Field k] {J : Type} [Fintype J] [Nontrivial J] (F : SpectralPoint k J)
+
+/-- A complete CAT(0) space realizes all the distances of the given wire
+pseudometric. Its own finite distance arrays remain spectrally realizable. -/
+theorem exists_catZero_completion :
+ ∃ (X : Type) (_ : MetricSpace X) (_ : CompleteSpace X) (e : J → X),
+ (∀ a b, dist (e a) (e b) = F.wireDistance a b) ∧
+ RealizableConfigurations k X ∧ HasCATZeroSegments X := by
+ obtain ⟨X, _, _, e, he, hr, hf, _, _⟩ :=
+ exists_geodesic_completion_of_wire_transport F (fun _ _ _ G ↦ G.fractionTransport)
+ exact ⟨X, inferInstance, inferInstance, e, he, hr, hasCATZeroSegments_of_realizable k hf hr⟩
+
+/-- Distance-preserving CAT(0) realization used in the cube obstruction. -/
+theorem catZero_embedding :
+ ∃ (X : Type) (_ : MetricSpace X) (_ : HasCATZeroSegments X) (e : J → X),
+ ∀ a b, dist (e a) (e b) = F.wireDistance a b := by
+ obtain ⟨X, _, _, e, he, _, hc⟩ := F.exists_catZero_completion
+ exact ⟨X, inferInstance, hc, e, he⟩
+
+/-- Lemma 6.2 for the actual six-party wire distances of a spectral point. -/
+theorem sixParty_wire_energy (a b c d m n : J) :
+ (1 / 3 : ℝ) * F.wireDistance a b ^ 2 + F.wireDistance c d ^ 2 ≤
+ (31 / 16 : ℝ) * ((8 / 31 : ℝ) * (F.wireDistance a c ^ 2 + F.wireDistance b c ^ 2) +
+ (4 / 31 : ℝ) * (F.wireDistance a m ^ 2 + F.wireDistance b n ^ 2) +
+ (40 / 93 : ℝ) * (F.wireDistance c m ^ 2 + F.wireDistance c n ^ 2) +
+ (16 / 31 : ℝ) * (F.wireDistance d m ^ 2 + F.wireDistance d n ^ 2)) := by
+ obtain ⟨X, _, hc, e, he⟩ := F.catZero_embedding
+ simpa only [he] using sixParty_energy hc (e a) (e b) (e c) (e d) (e m) (e n)
+
+end WireTensor.SpectralPoint
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WireCompletion.lean b/lean/OAI/Computability/VPVNP/WireCompletion.lean
new file mode 100644
index 0000000000..9f6a0199fa
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WireCompletion.lean
@@ -0,0 +1,60 @@
+import OAI.Computability.VPVNP.WireGeodesic
+import Mathlib.Topology.MetricSpace.Cauchy
+import Mathlib.Topology.MetricSpace.Isometry
+import Mathlib.Topology.Sequences
+
+/-! # Midpoints in the completion of spectral wire geometry
+
+The six-point transport inequality controls the displacement of midpoints
+when their endpoints move. This makes midpoints of approximating endpoint
+pairs a Cauchy sequence, as required in Corollary 2.5.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open Filter Set
+open scoped Topology
+
+/-- Exact midpoints pass through a dense isometry into a complete space if
+midpoints in the source satisfy the fractional transport inequality. -/
+theorem midpoints_of_dense_isometry {X Y : Type*} [PseudoMetricSpace X] [PseudoMetricSpace Y]
+ [CompleteSpace Y] (f : X → Y) (hf : Isometry f) (hd : DenseRange f)
+ (hmid : ∀ a b : X, ∃ z, AtFraction a b (1 / 2) z) (hT : FractionTransport X) :
+ ∀ a b : Y, ∃ z, AtFraction a b (1 / 2) z := by
+ intro a b
+ have approx (y : Y) : ∃ x : ℕ → X, Tendsto (fun n ↦ f (x n)) atTop (𝓝 y) := by
+ obtain ⟨w, hw, hlim⟩ := mem_closure_iff_seq_limit.mp (hd y)
+ choose x hx using hw
+ exact ⟨x, hlim.congr fun n ↦ (hx n).symm⟩
+ obtain ⟨x, hx⟩ := approx a
+ obtain ⟨y, hy⟩ := approx b
+ choose mid hm using fun n ↦ hmid (x n) (y n)
+ have hc : CauchySeq (fun n ↦ f (mid n)) := by
+ apply Metric.cauchySeq_iff.mpr
+ intro ε hε
+ obtain ⟨M, hM⟩ := Metric.cauchySeq_iff.mp hx.cauchySeq ε hε
+ obtain ⟨N, hN⟩ := Metric.cauchySeq_iff.mp hy.cauchySeq ε hε
+ refine ⟨max M N, fun i hi j hj ↦ ?_⟩
+ have h₁ := hM i ((le_max_left M N).trans hi) j ((le_max_left M N).trans hj)
+ have h₂ := hN i ((le_max_right M N).trans hi) j ((le_max_right M N).trans hj)
+ have h := hT (by norm_num) (by norm_num) (hm i) (hm j)
+ simp only [hf.dist_eq] at h₁ h₂ ⊢
+ linarith only [h₁, h₂, h]
+ obtain ⟨z, hz⟩ := cauchySeq_tendsto_of_complete hc
+ refine ⟨z, ?_, ?_⟩
+ · apply tendsto_nhds_unique (hx.dist hz)
+ exact ((hx.dist hy).const_mul (1 / 2 : ℝ)).congr fun n ↦ by
+ simpa only [hf.dist_eq] using (hm n).1.symm
+ · apply tendsto_nhds_unique (hz.dist hy)
+ exact ((hx.dist hy).const_mul (1 - 1 / 2 : ℝ)).congr fun n ↦ by
+ simpa only [hf.dist_eq] using (hm n).2.symm
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WireCoupling.lean b/lean/OAI/Computability/VPVNP/WireCoupling.lean
new file mode 100644
index 0000000000..8250583c28
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WireCoupling.lean
@@ -0,0 +1,217 @@
+import OAI.Computability.VPVNP.CouplingAmplification
+import OAI.Computability.VPVNP.RealizedTransport
+import OAI.Computability.VPVNP.TwoMarkedSplitBounds
+
+/-!
+# Coupling the endpoint choices of two spectral wire intervals
+
+The recursive split in Appendix A.3 keeps the two marked legs open at every
+node. Dividing by the product of the ancestor diagonal-wire values gives a
+subadditive binary tree, whose endpoint values obey the shrinking cost tables.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireTensor.SpectralPoint
+
+open SpectralGeometry
+
+variable {k J : Type*} [Field k] [Fintype J] (F : SpectralPoint k J)
+
+/-- The four pairwise distances between the endpoint choices. -/
+noncomputable def wireEndpointTable (A B : Bool → J) : EndpointTable :=
+ fun i j => F.wireDistance (A i) (B j)
+
+theorem wireEndpointTable_gap (A B : Bool → J) (j : Bool) :
+ |columnGap (F.wireEndpointTable A B) j| ≤ F.wireDistance (A false) (A true) := by
+ apply abs_le.mpr
+ change -F.wireDistance (A false) (A true) ≤
+ F.wireDistance (A false) (B j) - F.wireDistance (A true) (B j) ∧
+ F.wireDistance (A false) (B j) - F.wireDistance (A true) (B j) ≤
+ F.wireDistance (A false) (A true)
+ have h₀ := F.wireDistance_triangle (A true) (A false) (B j)
+ rw [F.wireDistance_comm (A true) (A false)] at h₀
+ have h₁ := F.wireDistance_triangle (A false) (A true) (B j)
+ constructor <;> linarith
+
+private theorem endpoint_cost_eq_of_zero {u v : ℝ} (A B : Bool → J)
+ (ht : F.wireDistance (A false) (A true) = 0) (ρ π : EndpointCoupling u v) :
+ ρ.cost (F.wireEndpointTable A B) = π.cost (F.wireEndpointTable A B) := by
+ have hgap (j) : columnGap (F.wireEndpointTable A B) j = 0 :=
+ abs_nonpos_iff.mp (ht ▸ F.wireEndpointTable_gap A B j)
+ apply sub_eq_zero.mp
+ simp only [coupling_cost_sub, hgap, sub_self, mul_zero]
+
+/-- The two-mark tensor at a path in the exterior split tree. Each level is
+chosen from the endpoint table *before* the new branch is taken. -/
+private noncomputable def couplingNode (q : ℕ) (t : ℝ) (A : Bool → J) (M : EndpointTable)
+ (p : List Bool) : TwoMarkedNode k J (Fin q) (Fin q) :=
+ p.reverseRecOn (TwoMarkedNode.wire q) fun pre branch W =>
+ W.exteriorChild (A false) (A true) (couplingLevel q t (leafTable M pre)) branch
+
+/-- Product of the values of the exterior-level wires along the ancestry. -/
+private noncomputable def ancestry (q : ℕ) (t : ℝ) (M : EndpointTable) (p : List Bool) : ℝ :=
+ p.reverseRecOn 1 fun pre _ D => D * (q.choose (couplingLevel q t (leafTable M pre)) : ℝ) ^ t
+
+private theorem ancestry_pos {q : ℕ} (hq : 2 ≤ q) {t : ℝ} (ht : 0 < t)
+ {M : EndpointTable} (hgap : ∀ j, |columnGap M j| ≤ t) (p : List Bool) :
+ 0 < ancestry q t M p := by
+ induction p using List.reverseRecOn with
+ | nil => simp [ancestry]
+ | append_singleton p b ih =>
+ have hlev := couplingLevel_bounds hq ht (leafTable_columnGap_mem M p hgap)
+ have hn := Nat.choose_pos hlev.2.1.le
+ simpa only [ancestry, List.reverseRecOn_concat] using mul_pos ih
+ (Real.rpow_pos_of_pos (Nat.cast_pos.mpr hn) t)
+
+private theorem level_wire_value (A : Bool → J) {q b : ℕ} (hb : b ≤ q) :
+ (F.value (WireTensor.wire (A false) (A true) (ExteriorLevels.Level q b)) : ℝ) =
+ (q.choose b : ℝ) ^ F.wireDistance (A false) (A true) := by
+ rw [F.value_wire_equiv _ _ (Fintype.equivFin _), ExteriorLevels.card_level]
+ exact F.value_wire_eq_rpow _ _ (Nat.choose_pos hb)
+
+private theorem normalized_same {x y D H : ℝ} (hD : 0 < D) (hH : 0 < H)
+ (h : x ≤ H*y) : x / (D*H) ≤ y/D := by
+ apply (div_le_div_iff₀ (mul_pos hD hH) hD).2
+ simpa only [mul_assoc, mul_comm, mul_left_comm] using mul_le_mul_of_nonneg_right h hD.le
+
+private theorem normalized_cross {x y D H C t : ℝ} (hD : 0 < D) (hH : 0 < H) (hC : 0 ≤ C)
+ (h : x ≤ C ^ t * y) : x / (D * H ^ t) ≤ (C/H) ^ t * (y/D) := by
+ have ht := Real.rpow_pos_of_pos hH t
+ rw [Real.div_rpow hC hH.le, div_mul_div_comm, mul_comm (H ^ t) D]
+ exact div_le_div_of_nonneg_right h (mul_pos hD ht).le
+
+private theorem normalized_split {x y z D H : ℝ} (hD : 0 < D) (hH : 0 < H)
+ (h : x*H ≤ y+z) : x/D ≤ y/(D*H) + z/(D*H) := by
+ rw [← add_div, div_le_div_iff₀ hD (mul_pos hD hH)]
+ simpa only [mul_assoc, mul_comm, mul_left_comm] using mul_le_mul_of_nonneg_right h hD.le
+
+private theorem coupling_wire_power_bound {q : ℕ} (hq : 2 ≤ q)
+ (A B : Bool → J) (c x : J) {u v : ℝ} (ρ π : EndpointCoupling u v)
+ (ht : 0 < F.wireDistance (A false) (A true))
+ (independent : ∀ W : TwoMarkedNode k J (Fin q) (Fin q), (F.value (W.place c x) : ℝ) ≤
+ ∏ i, ∏ j, (F.value (W.place (A i) (B j)) : ℝ) ^ ρ.mass i j)
+ (a : ℕ) :
+ (q : ℝ) ^ F.wireDistance c x ≤ (2 : ℝ) ^ a *
+ (q : ℝ) ^ (π.cost (F.wireEndpointTable A B) + 2 * F.wireDistance (A false) (A true) * (1/2)^a) := by
+ let t := F.wireDistance (A false) (A true)
+ let M := F.wireEndpointTable A B
+ let W (p : List Bool) := couplingNode (k := k) q t A M p
+ let D (p : List Bool) := ancestry q t M p
+ let b (p : List Bool) := couplingLevel q t (leafTable M p)
+ let H (p : List Bool) := (q.choose (b p) : ℝ) ^ t
+ let V (p : List Bool) (i j : J) := (F.value ((W p).place i j) : ℝ) / D p
+ have hgap : ∀ j, |columnGap M j| ≤ t := F.wireEndpointTable_gap A B
+ have hD (p) : 0 < D p := ancestry_pos hq ht hgap p
+ have hb (p) : 1 ≤ b p ∧ b p < q := by
+ obtain ⟨h₁, h₂, _⟩ := couplingLevel_bounds hq ht (leafTable_columnGap_mem M p hgap)
+ exact ⟨h₁, h₂⟩
+ have hdim (p) : 0 < (q.choose (b p) : ℝ) := Nat.cast_pos.mpr (Nat.choose_pos (hb p).2.le)
+ have hH (p) : 0 < H p := Real.rpow_pos_of_pos (hdim p) t
+ have hV (p : List Bool) (s : Bool) (i j : J) : V (p ++ [s]) i j =
+ (F.value (((W p).exteriorChild (A false) (A true) (b p) s).place i j) : ℝ) / (D p * H p) := by
+ simp only [V, W, D, H, b, couplingNode, ancestry, List.reverseRecOn_concat]
+ have hroot (i j : J) : V [] i j = (q : ℝ) ^ F.wireDistance i j := by
+ simp only [V, W, D, couplingNode, ancestry, List.reverseRecOn_nil, div_one, TwoMarkedNode.value_wire]
+ exact F.value_wire_eq_rpow _ _ (by omega)
+ have hend := endpoint_tree_bounds hq ht a M hgap (fun p i j => V p (A i) (B j))
+ (fun p i j => div_nonneg (NNReal.coe_nonneg _) (hD p).le) (fun i j => (hroot (A i) (B j)).le)
+ (fun p _ s i j => by
+ rw [hV]
+ exact normalized_same (hD p) (hH p) ((W p).value_exteriorChild_same_le F A B (b p) (hb p).2 s i j))
+ (fun p _ j => by
+ rw [hV]
+ exact normalized_cross (hD p) (hdim p) (Nat.cast_nonneg _)
+ ((W p).value_exteriorChild_plus_le F A B (b p) (hb p).2 j))
+ (fun p _ j => by
+ rw [hV]
+ exact normalized_cross (hD p) (hdim p) (Nat.cast_nonneg _)
+ ((W p).value_exteriorChild_minus_le F A B (b p) (hb p).2 j))
+ rw [← hroot c x]
+ apply coupling_tree_bound ρ π M hgap (by exact_mod_cast (show 1 ≤ q by omega)) a (fun p => V p c x)
+ · intro p _
+ rw [hV, hV]
+ apply normalized_split (hD p) (hH p)
+ have h := TwoMarkedNode.value_exterior_split F (W p) (A false) (A true) c x (b p)
+ have h' := NNReal.coe_le_coe.mpr h
+ rw [NNReal.coe_mul, NNReal.coe_add, F.level_wire_value A (hb p).2.le] at h'
+ exact h'
+ · intro p hp
+ exact normalized_endpoint_product_bound ρ (by exact_mod_cast (show 0 < q by omega)) (hD p)
+ (fun _ _ => NNReal.coe_nonneg _) (independent (W p)) (hend p hp.le)
+
+/-- The two-mark independent product inequality implies the bound for every endpoint coupling. -/
+theorem wireDistance_endpointCoupling_of_product_bound (A B : Bool → J) (c x : J)
+ {u v : ℝ} (ρ π : EndpointCoupling u v)
+ (independent : ∀ q : ℕ, 2 ≤ q → ∀ W : TwoMarkedNode k J (Fin q) (Fin q),
+ (F.value (W.place c x) : ℝ) ≤
+ ∏ i, ∏ j, (F.value (W.place (A i) (B j)) : ℝ) ^ ρ.mass i j) :
+ F.wireDistance c x ≤ π.cost (F.wireEndpointTable A B) := by
+ rcases (F.wireDistance_nonneg (A false) (A true)).eq_or_lt with hzero | ht
+ · have val (i j : J) : (F.value ((TwoMarkedNode.wire 2).place i j) : ℝ) = (2 : ℝ) ^ F.wireDistance i j := by
+ rw [TwoMarkedNode.value_wire]
+ exact F.value_wire_eq_rpow _ _ (by decide : 0 < 2)
+ have h := normalized_endpoint_product_bound (N := F.wireEndpointTable A B) (D := 1)
+ ρ (by norm_num : (0 : ℝ) < 2) (by norm_num) (fun _ _ => NNReal.coe_nonneg _)
+ (independent 2 (by decide) (TwoMarkedNode.wire 2))
+ (fun i j => by simp only [div_one, val, wireEndpointTable]; rfl)
+ rw [div_one, val, F.endpoint_cost_eq_of_zero A B hzero.symm ρ π] at h
+ exact (Real.rpow_le_rpow_left_iff (by norm_num : (1 : ℝ) < 2)).1 h
+ · apply le_of_dyadic_amplification
+ intro a n hn
+ have hq : 2 ≤ (2:ℕ)^n := (le_refl 2).trans
+ (by simpa using Nat.pow_le_pow_right (by norm_num : 0 < 2) hn)
+ simpa only [Nat.cast_pow, Nat.cast_ofNat] using
+ F.coupling_wire_power_bound hq A B c x ρ π ht (independent _ hq) a
+
+/-- Equation (A.3). Every coupling of the endpoint choices bounds the
+distance between the two fractional points. -/
+theorem wireDistance_endpointCoupling (A B : Bool → J) (c x : J) {u v : ℝ}
+ (hu : 0 ≤ u ∧ u ≤ 1) (hv : 0 ≤ v ∧ v ≤ 1)
+ (hc : @WireGeometry.AtFraction J F.wirePseudoMetric (A false) (A true) u c)
+ (hx : @WireGeometry.AtFraction J F.wirePseudoMetric (B false) (B true) v x)
+ (π : EndpointCoupling u v) :
+ F.wireDistance c x ≤ π.cost (F.wireEndpointTable A B) := by
+ apply F.wireDistance_endpointCoupling_of_product_bound A B c x (independentCoupling hu hv) π
+ intro q _ W
+ exact F.value_twoMarked_atFraction_le W.Basis (Fin q) (Fin q) W.coeff A B c x hu hv hc hx
+
+/-- Pair the first endpoints and the second endpoints with equal interval parameter. -/
+private def diagonalCoupling {u : ℝ} (hu : 0 ≤ u ∧ u ≤ 1) : EndpointCoupling u u where
+ mass i j := if i = j then (if i then u else 1-u) else 0
+ nonneg i j := by cases i <;> cases j <;> simp [hu.1, hu.2]
+ row₀ := by simp
+ row₁ := by simp
+ col₀ := by simp
+ col₁ := by simp
+
+/-- Lemma 2.2. Interpolating at the same fraction on two wire intervals
+bounds the distance by the correspondingly weighted endpoint distances. -/
+theorem fractionTransport :
+ @WireGeometry.FractionTransport J F.wirePseudoMetric := by
+ intro a b c d x y t ht₀ ht₁ hx hy
+ let A (i : Bool) := if i then b else a
+ let B (i : Bool) := if i then d else c
+ have ht := And.intro ht₀ ht₁
+ have e := F.wireDistance_endpointCoupling A B x y ht ht hx hy (diagonalCoupling ht)
+ change F.wireDistance x y ≤ (1-t) * F.wireDistance a c + t * F.wireDistance b d
+ simpa only [EndpointCoupling.cost, wireEndpointTable, A, B, diagonalCoupling,
+ ↓reduceIte, Bool.false_eq_true, Bool.true_eq_false, zero_mul, add_zero] using e
+
+end WireTensor.SpectralPoint
+
+namespace WireGeometry
+
+/-- The spectral transport inequality passes to every jointly realizable
+finite configuration by cancellation of the realization's positive scale. -/
+theorem realizable_fractionTransport {k X : Type*} [Field k] [PseudoMetricSpace X]
+ (hX : RealizableConfigurations k X) : FractionTransport X :=
+ fractionTransport_of_realizable (fun _ _ _ F => F.fractionTransport) hX
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WireExpanders.lean b/lean/OAI/Computability/VPVNP/WireExpanders.lean
new file mode 100644
index 0000000000..aaec31f694
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WireExpanders.lean
@@ -0,0 +1,86 @@
+import OAI.Computability.VPVNP.Expanders
+import OAI.Computability.VPVNP.GraphConnectivity
+import OAI.Computability.VPVNP.SpectralCubeObstruction
+
+/-!
+# Common expanders for spectral wire pseudometrics
+
+In Corollary 5.2 the class of complete CAT(0) targets consists of spaces whose
+finite distance configurations are realizable by wires over the given field.
+Closedness upgrades exact cube exclusion to uniform exclusion throughout the
+class. Theorem 5.1 then provides a single graph at each selected order. Its
+Poincaré bound pulls back to every labeling by parties of every spectral point.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace SpectralGeometry
+
+open WireTensor WireGeometry Grassmann
+
+private structure WireTarget (k : Type*) [Field k] where
+ carrier : Type
+ metric : MetricSpace carrier
+ complete : CompleteSpace carrier
+ realizable : RealizableConfigurations k carrier
+ comparison : HasCATZeroSegments carrier
+
+attribute [local instance] WireTarget.metric WireTarget.complete
+
+/-- Connected loopless regular graphs of arbitrarily large power-of-two orders
+have the same power-of-two degree and Poincaré bound for all spectral wire
+pseudometrics over the field. Arc multiplicities come from port reversal. -/
+def HasWireExpanders (k : Type*) [Field k] : Prop :=
+ ∃ (e : ℕ) (γ : ℝ), 0 < γ ∧ ∀ minimum : ℕ, ∃ o : ℕ, minimum ≤ 2 ^ o ∧
+ ∃ G : RegularArcGraph (Fin (2 ^ o)) (2 ^ e), (arcSupportGraph G.multiplicity).Connected ∧
+ ∀ (J : Type) [Fintype J] (F : SpectralPoint k J),
+ letI := F.wirePseudoMetric
+ HasPoincareBound J (normalizeArcs G.multiplicity (2 ^ e)) γ
+
+/-- Exact exclusion of one cube over the field implies the common graph
+family of Corollary 5.2, with all its bounds uniform over the spectral points. -/
+theorem wire_expanders_of_cube_exclusion (k : Type*) [Field k] {ℓ : ℕ}
+ (hexclude : ¬ RealizableUpToScale k (cubeDistances ℓ)) : HasWireExpanders k := by
+ classical
+ let Y := WireTarget.carrier (k := k)
+ have hclosed : cubeDistances ℓ ∉ closure (markedDistances Y (Finset (Fin ℓ))) := by
+ apply RealizableUpToScale.notMem_closure_markedDistances Y _ hexclude
+ intro a x
+ let v := Fintype.equivFin (Finset (Fin ℓ))
+ simpa only [Equiv.symm_apply_apply] using
+ (a.realizable _ (fun i ↦ x (v.symm i))).relabel v
+ obtain ⟨e, γ, hγ, hgraphs⟩ := expanders_of_cube_exclusion Y WireTarget.comparison hclosed
+ refine ⟨e, γ, hγ, fun minimum ↦ ?_⟩
+ obtain ⟨o, ho, M, hsym, hloop, hrow, hreach, hbound⟩ := hgraphs minimum
+ obtain ⟨G, hG, hconnected⟩ := exists_connected_regularArcGraph M hsym hrow hloop hreach
+ refine ⟨o, ho, G, hconnected, fun J _ F ↦ ?_⟩
+ let : PseudoMetricSpace J := F.wirePseudoMetric
+ intro x
+ rw [hG]
+ rcases subsingleton_or_nontrivial J with hJ | hJ
+ · have hz (i j) : dist (x i) (x j) = 0 := by rw [Subsingleton.elim (x i) (x j), dist_self]
+ simp [walkEnergy, hz]
+ · obtain ⟨X, hX, hcomplete, p, hp, hr, hc⟩ := F.exists_catZero_completion
+ let a : WireTarget k := ⟨X, hX, hcomplete, hr, hc⟩
+ have h := hbound a (p ∘ x)
+ change (∑ i, ∑ j, dist (p (x i)) (p (x j)) ^ 2) / Fintype.card (Fin (2 ^ o)) ≤
+ γ * walkEnergy (normalizeArcs M (2 ^ e)) (p ∘ x) at h
+ change (∑ i, ∑ j, F.wireDistance (x i) (x j) ^ 2) / Fintype.card (Fin (2 ^ o)) ≤
+ γ * ∑ i, ∑ j, normalizeArcs M (2 ^ e) i j * F.wireDistance (x j) (x i) ^ 2
+ simpa only [walkEnergy, Function.comp_apply, hp] using h
+
+/-- Corollary 5.2. Infinitely many small exact circuits for the integer
+family over a fixed field provide one common expander family for its wire
+pseudometrics. The excluded dimension can be chosen after the circuit exponent. -/
+theorem wire_expanders_of_small_circuits (k : Type*) [Field k] {C : ℕ} (hC : 1 ≤ C)
+ (hsmall : ∀ N, ∃ n ≥ N, circuitSize (MvPolynomial.map (Int.castRingHom k) (P n)) ≤ n ^ C) :
+ HasWireExpanders k :=
+ wire_expanders_of_cube_exclusion k (cube_obstruction k hC le_rfl hsmall)
+
+end SpectralGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WireGeodesic.lean b/lean/OAI/Computability/VPVNP/WireGeodesic.lean
new file mode 100644
index 0000000000..083ec046e6
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WireGeodesic.lean
@@ -0,0 +1,58 @@
+import OAI.Computability.VPVNP.SpectralRealizable
+import Mathlib.Topology.MetricSpace.Pseudo.Lemmas
+
+/-!
+# Fractional points in the spectral wire geometry
+
+Corollary 2.5 and Section 4 of *VP and VNP differ over every field* use
+the metric characterization of a point at a specified fraction along a
+segment. The six-point transport inequality makes such a point unique in a
+metric space and controls its dependence on both endpoints.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+namespace WireGeometry
+
+open WireTensor
+
+variable {X : Type*} [PseudoMetricSpace X]
+
+/-- The two endpoint distances specifying a fractional point. -/
+def AtFraction (x y : X) (t : ℝ) (z : X) : Prop :=
+ dist x z = t * dist x y ∧ dist z y = (1-t) * dist x y
+
+/-- Every pair admits an interpolating point at each fraction. -/
+def HasFractions (X : Type*) [PseudoMetricSpace X] : Prop :=
+ ∀ (x y : X) (t : ℝ), 0 ≤ t → t ≤ 1 → ∃ z, AtFraction x y t z
+
+/-- Equation (2.2), controlling interpolation along two segments. -/
+def FractionTransport (X : Type*) [PseudoMetricSpace X] : Prop :=
+ ∀ {a b c d x y : X} {t : ℝ}, 0 ≤ t → t ≤ 1 → AtFraction a b t x → AtFraction c d t y →
+ dist x y ≤ (1-t) * dist a c + t * dist b d
+
+/-- Every finite list of points is jointly realized up to one scale in a
+spectral wire pseudometric. -/
+def RealizableConfigurations (k X : Type*) [Field k] [PseudoMetricSpace X] : Prop :=
+ ∀ n (p : Fin n → X), RealizableUpToScale k (fun i j ↦ dist (p i) (p j))
+
+theorem AtFraction.dist_eq_zero_of_transport (h : FractionTransport X)
+ {x y z w : X} {t : ℝ} (ht : 0 ≤ t) (ht' : t ≤ 1)
+ (hz : AtFraction x y t z) (hw : AtFraction x y t w) : dist z w = 0 := by
+ have bound := h ht ht' hz hw
+ simp only [dist_self, mul_zero, add_zero] at bound
+ exact le_antisymm bound dist_nonneg
+
+/-- Metric separation gives uniqueness at every fraction. -/
+theorem atFraction_unique {Y : Type*} [MetricSpace Y] (h : FractionTransport Y)
+ {x y z w : Y} {t : ℝ} (ht : 0 ≤ t) (ht' : t ≤ 1)
+ (hz : AtFraction x y t z) (hw : AtFraction x y t w) : z = w :=
+ dist_eq_zero.mp (hz.dist_eq_zero_of_transport h ht ht' hw)
+
+end WireGeometry
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WireSpectrum.lean b/lean/OAI/Computability/VPVNP/WireSpectrum.lean
new file mode 100644
index 0000000000..d9716294c0
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WireSpectrum.lean
@@ -0,0 +1,365 @@
+import OAI.Computability.VPVNP.WireTensor
+import Mathlib.Analysis.SpecialFunctions.Pow.NNReal
+import Mathlib.Logic.Equiv.Fin.Basic
+import Mathlib.Topology.MetricSpace.Pseudo.Defs
+
+/-!
+# Spectral points on finite multipartite tensors
+
+A spectral point of Section 2 of *VP and VNP differ over every field* is a
+nonnegative, normalized, additive and multiplicative function that is monotone
+under local linear restriction. This presentation uses coefficient arrays and
+derives invariance under mutual restrictions from monotonicity.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v
+open scoped NNReal
+
+namespace WireTensor
+
+/-- A spectral point on finite multipartite tensors over `k`. -/
+structure SpectralPoint (k : Type u) (J : Type v) [Field k] [Fintype J] where
+ /-- The nonnegative real value assigned to each tensor by this point of the asymptotic
+ spectrum. -/
+ value : Tensor.{u,v,0} k J → ℝ≥0
+ monotone {Y X} : Restricts Y X → value X ≤ value Y
+ value_unit : value unit = 1
+ value_zero (T) : T.coeff = 0 → value T = 0
+ value_directSum (T U) : value (directSum T U) = value T + value U
+ value_tensorProduct (T U) : value (tensorProduct T U) = value T * value U
+
+section Diagonals
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J]
+
+/-- A bijection of labels gives mutual restrictions between the diagonals. -/
+theorem diagonal_reindex_mutual {I K : Type} [Fintype I] [Fintype K] (e : I ≃ K) :
+ Restricts (diagonal (k := k) (J := J) I) (diagonal K) ∧
+ Restricts (diagonal (k := k) (J := J) K) (diagonal I) := by
+ apply restricts_of_reindex (fun _ ↦ e.symm)
+ intro x
+ change J → K at x
+ have h : (∃ i : K, ∀ j, x j = i) ↔ (∃ i : I, ∀ j, e.symm (x j) = i) := by
+ constructor
+ · rintro ⟨i, hi⟩
+ exact ⟨e.symm i, fun j ↦ congrArg e.symm (hi j)⟩
+ · rintro ⟨i, hi⟩
+ exact ⟨e i, fun j ↦ (e.apply_symm_apply (x j)).symm.trans (congrArg e (hi j))⟩
+ simp only [diagonal]
+ split_ifs <;> tauto
+
+private theorem diagonal_sum_coeff [Nonempty J] {I K : Type} [Fintype I] [Fintype K]
+ (x : J → I ⊕ K) :
+ (directSum (diagonal I) (diagonal K)).coeff x = (diagonal (k := k) (I ⊕ K)).coeff x := by
+ classical
+ by_cases h : ∃ i, ∀ j, x j = i
+ · obtain ⟨i | i, hi⟩ := h
+ · have hx : x = fun _ ↦ Sum.inl i := funext hi
+ rw [hx]
+ exact (directSum_coeff_inl (diagonal I) (diagonal K) (fun _ ↦ i)).trans (by simp [diagonal])
+ · have hx : x = fun _ ↦ Sum.inr i := funext hi
+ rw [hx]
+ exact (directSum_coeff_inr (diagonal I) (diagonal K) (fun _ ↦ i)).trans (by simp [diagonal])
+ · simp only [directSum, Pi.add_apply, applyLocal, diagonal, Fintype.prod_boole, h, ↓reduceIte]
+ calc
+ _ = (0 : k) + 0 := by
+ apply congrArg₂ (· + ·)
+ all_goals
+ apply Finset.sum_eq_zero
+ intro y _
+ split_ifs with hy ha
+ · obtain ⟨a, ha⟩ := ha
+ exact False.elim (h ⟨_, fun j ↦ by rw [hy j, ha j]⟩)
+ all_goals simp
+ _ = _ := by simp
+
+/-- The diagonal on a disjoint union and the direct sum of the diagonals have
+the same coefficients in the sum basis. -/
+theorem diagonal_sum_mutual [Nonempty J] (I K : Type) [Fintype I] [Fintype K] :
+ Restricts (diagonal (k := k) (J := J) (I ⊕ K)) (directSum (diagonal I) (diagonal K)) ∧
+ Restricts (directSum (diagonal (k := k) (J := J) I) (diagonal K)) (diagonal (I ⊕ K)) :=
+ restricts_of_reindex (fun _ ↦ Equiv.refl _) diagonal_sum_coeff
+
+/-- A one-dimensional diagonal is mutually restrictable with the unit. -/
+theorem diagonal_unit_mutual :
+ Restricts (diagonal (k := k) (J := J) (Fin 1)) unit.{u,v,0} ∧
+ Restricts (unit.{u,v,0} (k := k) (J := J)) (diagonal (Fin 1)) := by
+ apply restricts_of_reindex (fun _ ↦ Equiv.ofUnique PUnit (Fin 1))
+ intro x
+ have h : ∃ i : Fin 1, ∀ j : J, Equiv.ofUnique PUnit (Fin 1) (x j) = i :=
+ ⟨0, fun _ ↦ Subsingleton.elim _ _⟩
+ simp only [unit, diagonal]
+ split_ifs <;> tauto
+
+end Diagonals
+
+namespace SpectralPoint
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] (F : SpectralPoint k J)
+
+/-- Mutual restrictions give equal spectral values. -/
+theorem value_eq_of_mutual {T U : Tensor.{u,v,0} k J} (h : Restricts T U ∧ Restricts U T) :
+ F.value T = F.value U := le_antisymm (F.monotone h.2) (F.monotone h.1)
+
+/-- Ordinary addition of arrays in common bases is subadditive at a spectral point. -/
+theorem value_add_le {B : J → Type} [b : ∀ j, Fintype (B j)] (T U : Array k B) :
+ F.value (.mk B b (T + U)) ≤ F.value (.mk B b T) + F.value (.mk B b U) :=
+ (F.monotone (directSum_restricts_add T U)).trans_eq (F.value_directSum _ _)
+
+/-- The unit restriction bounds each nonzero tensor's spectral value from below. -/
+theorem one_le_value [Nonempty J] (T : Tensor.{u,v,0} k J) (hT : T.coeff ≠ 0) :
+ 1 ≤ F.value T := F.value_unit.symm.le.trans (F.monotone (restricts_unit_of_ne_zero T hT))
+
+
+/-- Subadditivity for finite ordinary sums in common bases. -/
+theorem value_sum_le {B : J → Type} [b : ∀ j, Fintype (B j)] {ι : Type*}
+ (s : Finset ι) (T : ι → Array k B) :
+ F.value (.mk B b (∑ i ∈ s, T i)) ≤ ∑ i ∈ s, F.value (.mk B b (T i)) := by
+ classical
+ induction s using Finset.induction_on with
+ | empty =>
+ simp only [Finset.sum_empty]
+ exact (F.value_zero _ rfl).le
+ | insert a s ha ih =>
+ rw [Finset.sum_insert ha, Finset.sum_insert ha]
+ exact (F.value_add_le _ _).trans (add_le_add_right ih _)
+
+/-- Changing the finite index set of a diagonal by a bijection preserves its value. -/
+theorem value_diagonal_congr {I K : Type} [Fintype I] [Fintype K] (e : I ≃ K) :
+ F.value (diagonal I) = F.value (diagonal K) :=
+ F.value_eq_of_mutual (diagonal_reindex_mutual e)
+
+/-- The diagonal indexed by a disjoint union is the direct sum of its two diagonals. -/
+theorem value_diagonal_sum [Nonempty J] (I K : Type) [Fintype I] [Fintype K] :
+ F.value (diagonal (I ⊕ K)) = F.value (diagonal I) + F.value (diagonal K) :=
+ (F.value_eq_of_mutual (diagonal_sum_mutual I K)).trans (F.value_directSum _ _)
+
+private theorem value_diagonal_one : F.value (diagonal (Fin 1)) = 1 :=
+ (F.value_eq_of_mutual diagonal_unit_mutual).trans F.value_unit
+
+/-- Every spectral point has value `n` on the `n`-dimensional all-parties diagonal. -/
+theorem value_diagonal_fin [Nonempty J] (n : ℕ) : F.value (diagonal (Fin n)) = n := by
+ induction n with
+ | zero =>
+ rw [Nat.cast_zero]
+ apply F.value_zero
+ funext x
+ simp [diagonal]
+ | succ n ih =>
+ calc
+ F.value (diagonal (Fin (n + 1))) = F.value (diagonal (Fin n ⊕ Fin 1)) :=
+ (F.value_diagonal_congr finSumFinEquiv).symm
+ _ = F.value (diagonal (Fin n)) + F.value (diagonal (Fin 1)) := F.value_diagonal_sum _ _
+ _ = _ := by rw [ih, F.value_diagonal_one, Nat.cast_succ]
+
+/-- The diagonal value counts its finite index set. -/
+theorem value_diagonal [Nonempty J] (I : Type) [Fintype I] :
+ F.value (diagonal I) = Fintype.card I :=
+ (F.value_diagonal_congr (Fintype.equivFin I)).trans (F.value_diagonal_fin _)
+
+/-- The coordinate rank bound controls the spectral value of every tensor. -/
+theorem value_le_basis_product [Nonempty J] (T : Tensor.{u,v,0} k J) :
+ F.value T ≤ (∏ j, Fintype.card (T.Basis j) : ℕ) :=
+ (F.monotone (diagonal_restricts_of_card T)).trans_eq (F.value_diagonal_fin _)
+
+end SpectralPoint
+
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J]
+
+/-- Product of a finite family of tensors, regrouping all factors at each party. -/
+noncomputable def tensorFamilyProduct {E : Type} [Fintype E] (T : E → Tensor.{u,v,0} k J) :
+ Tensor.{u,v,0} k J where
+ Basis j := (e : E) → (T e).Basis j
+ finiteBasis _ := by classical exact inferInstance
+ coeff x := ∏ e, (T e).coeff (fun j ↦ x j e)
+
+namespace SpectralPoint
+
+variable (F : SpectralPoint k J)
+
+private theorem value_finProduct (n : ℕ) (T : Fin n → Tensor.{u,v,0} k J) :
+ F.value (tensorFamilyProduct T) = ∏ i, F.value (T i) := by
+ classical
+ induction n with
+ | zero =>
+ have h : Restricts unit (tensorFamilyProduct T) ∧ Restricts (tensorFamilyProduct T) unit := by
+ apply restricts_of_reindex (fun j ↦ Equiv.equivPUnit ((i : Fin 0) → (T i).Basis j))
+ intro c
+ simp [tensorFamilyProduct, unit]
+ simpa using (F.value_eq_of_mutual h).symm.trans F.value_unit
+ | succ n ih =>
+ let rest := tensorFamilyProduct (fun i : Fin n ↦ T i.succ)
+ have h : Restricts (tensorProduct (T 0) rest) (tensorFamilyProduct T) ∧
+ Restricts (tensorFamilyProduct T) (tensorProduct (T 0) rest) := by
+ apply restricts_of_reindex (fun j ↦ (Fin.consEquiv (fun i ↦ (T i).Basis j)).symm)
+ intro c
+ change (∏ e, (T e).coeff (fun j ↦ c j e)) = _
+ rw [Fin.prod_univ_succ]
+ rfl
+ rw [← F.value_eq_of_mutual h, F.value_tensorProduct, Fin.prod_univ_succ]
+ exact congrArg (F.value (T 0) * ·) (ih _)
+
+/-- Finite multiplicativity, including the empty product. -/
+theorem value_tensorFamilyProduct {E : Type} [Fintype E] (T : E → Tensor.{u,v,0} k J) :
+ F.value (tensorFamilyProduct T) = ∏ e, F.value (T e) := by
+ classical
+ let e := (Fintype.equivFin E).symm
+ let Ts (i : Fin (Fintype.card E)) := T (e i)
+ have h : Restricts (tensorFamilyProduct Ts) (tensorFamilyProduct T) ∧
+ Restricts (tensorFamilyProduct T) (tensorFamilyProduct Ts) := by
+ apply restricts_of_reindex (fun j ↦ (Equiv.piCongrLeft (fun i ↦ (T i).Basis j) e).symm)
+ intro c
+ change (∏ i, (T i).coeff (fun j ↦ c j i)) = _
+ rw [← e.prod_comp (fun i ↦ (T i).coeff (fun j ↦ c j i))]
+ rfl
+ rw [← F.value_eq_of_mutual h, value_finProduct]
+ exact e.prod_comp (fun i ↦ F.value (T i))
+
+/-- The value of an equality-wire network is the product of the values of its individual
+edges, even if endpoints repeat or different wires have different index types. -/
+theorem value_wireNetwork {E : Type} [Fintype E] (a b : E → J) (I : E → Type)
+ [∀ e, Fintype (I e)] : F.value (wireNetwork a b I) =
+ ∏ e, F.value (wire (a e) (b e) (I e)) := by
+ classical
+ let T (e : E) : Tensor k J := wire (a e) (b e) (I e)
+ have h : Restricts (wireNetwork a b I) (tensorFamilyProduct T) ∧
+ Restricts (tensorFamilyProduct T) (wireNetwork a b I) := by
+ apply restricts_of_reindex (fun j ↦ Equiv.arrowProdEquivProdArrow E
+ (fun e ↦ j = a e → I e) (fun e ↦ j = b e → I e))
+ intro c
+ rfl
+ exact (F.value_eq_of_mutual h).trans (F.value_tensorFamilyProduct T)
+
+end SpectralPoint
+
+namespace SpectralPoint
+
+variable {k : Type u} {J : Type v} [Field k] [Fintype J] (F : SpectralPoint k J)
+
+/-- Equal wire index cardinalities give equal spectral values. -/
+theorem value_wire_equiv (a b : J) {I K : Type} [Fintype I] [Fintype K] (e : I ≃ K) :
+ F.value (wire a b I) = F.value (wire a b K) :=
+ F.value_eq_of_mutual ⟨wire_restricts_of_embedding _ _ e.symm.toEmbedding,
+ wire_restricts_of_embedding _ _ e.toEmbedding⟩
+
+/-- The spectral value of a wire as a multiplicative function of its dimension. -/
+noncomputable def wireDimension (a b : J) : ℕ →* ℝ where
+ toFun q := F.value (wire a b (Fin q))
+ map_one' := by
+ exact_mod_cast (F.value_eq_of_mutual (wire_one a b)).symm.trans F.value_unit
+ map_mul' m n := by
+ have h := F.value_wire_equiv a b (finProdFinEquiv (m := m) (n := n))
+ rw [F.value_eq_of_mutual (wire_tensorProduct a b (Fin m) (Fin n)),
+ F.value_tensorProduct] at h
+ exact_mod_cast h.symm
+
+theorem wireDimension_monotone (a b : J) : Monotone (F.wireDimension a b) :=
+ fun _ _ h ↦ NNReal.coe_le_coe.mpr (F.monotone (wire_restricts_of_le a b h))
+
+theorem one_le_wireDimension (a b : J) {q : ℕ} (hq : 0 < q) : 1 ≤ F.wireDimension a b q := by
+ simpa using F.wireDimension_monotone a b (show 1 ≤ q from hq)
+
+/-- Base-two logarithm of the two-dimensional wire value, as in Section 2.1. -/
+noncomputable def wireDistance (a b : J) : ℝ :=
+ Real.log (F.wireDimension a b 2) / Real.log 2
+
+theorem wireDistance_nonneg (a b : J) : 0 ≤ F.wireDistance a b :=
+ div_nonneg (Real.log_nonneg (F.one_le_wireDimension a b (by decide))) (Real.log_pos (by norm_num)).le
+
+theorem wireDistance_self (a : J) : F.wireDistance a a = 0 := by
+ have hle := (F.monotone (unit_restricts_loop a (Fin 2))).trans_eq F.value_unit
+ have heq := le_antisymm (show F.wireDimension a a 2 ≤ 1 by exact_mod_cast hle)
+ (F.one_le_wireDimension a a (by decide))
+ simp [wireDistance, heq]
+
+theorem wireDistance_comm (a b : J) : F.wireDistance a b = F.wireDistance b a := by
+ exact congrArg (fun x : ℝ≥0 ↦ Real.log x / Real.log 2)
+ (F.value_eq_of_mutual (wire_swap a b (Fin 2)))
+
+theorem wireDistance_triangle (a b c : J) :
+ F.wireDistance a c ≤ F.wireDistance a b + F.wireDistance b c := by
+ have h := F.monotone (restricts_wire_triangle a b c (Fin 2))
+ rw [F.value_tensorProduct] at h
+ have hval : F.wireDimension a c 2 ≤ F.wireDimension a b 2 * F.wireDimension b c 2 := by
+ exact_mod_cast h
+ have hp (i j : J) : 0 < F.wireDimension i j 2 := zero_lt_one.trans_le
+ (F.one_le_wireDimension i j (by decide))
+ have hlog := Real.log_le_log (hp a c) hval
+ rw [Real.log_mul (hp a b).ne' (hp b c).ne'] at hlog
+ simpa only [wireDistance, ← add_div] using
+ div_le_div_of_nonneg_right hlog (Real.log_pos (by norm_num : (1 : ℝ) < 2)).le
+
+/-- The wire pseudometric induced by a spectral point on the party set. -/
+@[instance_reducible] noncomputable def wirePseudoMetric : PseudoMetricSpace J where
+ dist := F.wireDistance
+ dist_self := F.wireDistance_self
+ dist_comm := F.wireDistance_comm
+ dist_triangle := F.wireDistance_triangle
+
+theorem wireDistance_le_one (a b : J) : F.wireDistance a b ≤ 1 := by
+ have : Nonempty J := ⟨a⟩
+ have h := (F.monotone (diagonal_restricts_wire a b (Fin 2))).trans_eq (F.value_diagonal_fin 2)
+ have hle : F.wireDimension a b 2 ≤ 2 := by exact_mod_cast h
+ have hp := zero_lt_one.trans_le (F.one_le_wireDimension a b (by decide : 0 < 2))
+ exact (div_le_one (Real.log_pos (by norm_num : (1 : ℝ) < 2))).mpr (Real.log_le_log hp hle)
+
+/-- Every positive-dimensional wire follows the same power law at this spectral point. -/
+theorem value_wire_eq_rpow (a b : J) {q : ℕ} (hq : 0 < q) :
+ (F.value (wire a b (Fin q)) : ℝ) = (q : ℝ) ^ F.wireDistance a b :=
+ monotone_dimension_power_law (F.wireDimension a b) (F.wireDimension_monotone a b) hq
+
+/-- The spectral value of a matrix factorization is bounded by the product of the
+wire values between terminals and centers and the wire between centers. -/
+theorem value_cutFactorization_le {R : Type} [Fintype R]
+ (place : R → J) (side : R → Bool) (center : Bool → J)
+ (B : R → Type) [∀ r, Fintype (B r)] (K : Type) [Fintype K]
+ (L : ((r : R) → side r = false → B r) → K → k)
+ (M : ((r : R) → side r = true → B r) → K → k) :
+ F.value (placedTensor place B (fun x ↦ ∑ z, L (fun r _ ↦ x r) z * M (fun r _ ↦ x r) z)) ≤
+ F.value (wire (center false) (center true) K) *
+ ∏ r, F.value (wire (place r) (center (side r)) (B r)) := by
+ have h := F.monotone (cutFactorization_restricts place side center B K L M)
+ rw [F.value_wireNetwork, Fintype.prod_option] at h
+ exact h
+
+
+/-- Each edge contributes its index cardinality raised to the distance between
+its endpoints. This includes parallel edges and loops. -/
+theorem value_wireNetwork_eq_prod_rpow {E : Type} [Fintype E] (a b : E → J) (I : E → Type)
+ [∀ e, Fintype (I e)] (hI : ∀ e, 0 < Fintype.card (I e)) :
+ (F.value (wireNetwork a b I) : ℝ) =
+ ∏ e, (Fintype.card (I e) : ℝ) ^ F.wireDistance (a e) (b e) := by
+ rw [F.value_wireNetwork, NNReal.coe_prod]
+ apply Finset.prod_congr rfl
+ intro e _
+ rw [F.value_wire_equiv _ _ (Fintype.equivFin (I e))]
+ exact F.value_wire_eq_rpow _ _ (hI e)
+
+/-- The value of binary wires with varying bit widths, as used in Section 6. -/
+theorem value_binary_wireNetwork {E : Type} [Fintype E] (a b : E → J) (width : E → ℕ) :
+ (F.value (wireNetwork a b (fun e ↦ Fin (2 ^ width e))) : ℝ) =
+ (2 : ℝ) ^ ∑ e, (width e : ℝ) * F.wireDistance (a e) (b e) := by
+ rw [F.value_wireNetwork_eq_prod_rpow _ _ _ (fun e ↦ by simp)]
+ rw [Real.rpow_sum_of_pos (by norm_num : (0 : ℝ) < 2)]
+ simp only [Fintype.card_fin, Nat.cast_pow, Nat.cast_ofNat, Real.rpow_natCast_mul (by norm_num : (0 : ℝ) ≤ 2)]
+
+/-- The base-two logarithm of a binary wire network's spectral value is the
+sum of edge widths weighted by wire distances. -/
+theorem log2_value_binary_wireNetwork {E : Type} [Fintype E] (a b : E → J) (width : E → ℕ) :
+ Real.log (F.value (wireNetwork a b (fun e ↦ Fin (2 ^ width e)))) / Real.log 2 =
+ ∑ e, (width e : ℝ) * F.wireDistance (a e) (b e) := by
+ rw [F.value_binary_wireNetwork, Real.log_rpow (by norm_num : (0 : ℝ) < 2),
+ mul_div_cancel_right₀ _ (Real.log_pos (by norm_num : (1 : ℝ) < 2)).ne']
+
+end SpectralPoint
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/OAI/Computability/VPVNP/WireTensor.lean b/lean/OAI/Computability/VPVNP/WireTensor.lean
new file mode 100644
index 0000000000..cfd5b07567
--- /dev/null
+++ b/lean/OAI/Computability/VPVNP/WireTensor.lean
@@ -0,0 +1,722 @@
+import Mathlib.Data.Matrix.Basic
+import Mathlib.Analysis.SpecialFunctions.Pow.Real
+import Mathlib.Data.Nat.Log
+import Mathlib.Tactic.Linarith
+import Mathlib.Algebra.Order.BigOperators.Group.Finset
+
+/-!
+# Multipartite tensors and local restrictions
+
+Finite coefficient arrays implement the restriction preorder of Section 2 of
+*VP and VNP differ over every field*. Each party has its own finite basis. A
+local restriction independently applies one matrix at each party. The ordinary
+sum of arrays in the same bases differs from the direct sum, which uses separate
+local coordinate blocks at every party.
+-/
+
+namespace OAI
+namespace Computability
+namespace VPVNP
+
+universe u v w w'
+
+namespace WireTensor
+
+/-- A scalar for every simultaneous choice of one basis index at each party. -/
+abbrev Array (k : Type u) {J : Type v} (B : J → Type w) := ((j : J) → B j) → k
+
+/-- A tensor given by its entries in a finite basis at each party. -/
+structure Tensor (k : Type u) (J : Type v) where
+ /-- The basis-index type for the tensor factor at each party. -/
+ Basis : J → Type w
+ finiteBasis : ∀ j, Fintype (Basis j)
+ /-- The coefficients of the tensor in the specified product basis. -/
+ coeff : Array k Basis
+
+attribute [instance] Tensor.finiteBasis
+
+variable {k : Type u} {J : Type v}
+
+/-- Apply a linear map at each party, contracting its old index against the
+corresponding column of the matrix. -/
+noncomputable def applyLocal [Fintype J] [CommSemiring k] {B : J → Type*} {C : J → Type*}
+ [∀ j, Fintype (B j)] (L : ∀ j, C j → B j → k) (T : Array k B) : Array k C := by
+ classical exact fun c ↦ ∑ b, (∏ j, L j (c j) (b j)) * T b
+
+/-- The tensor restriction preorder, oriented from supply to demand. -/
+def Restricts [Fintype J] [CommSemiring k] (Y : Tensor.{u,v,w} k J) (X : Tensor.{u,v,w'} k J) : Prop :=
+ ∃ L : ∀ j, X.Basis j → Y.Basis j → k, applyLocal L Y.coeff = X.coeff
+
+/-- Product with parallel factors regrouped at each party. -/
+def tensorProduct [Mul k] (T : Tensor.{u,v,w} k J) (U : Tensor.{u,v,w'} k J) : Tensor k J where
+ Basis j := T.Basis j × U.Basis j
+ finiteBasis _ := inferInstance
+ coeff p := T.coeff (fun j ↦ (p j).1) * U.coeff (fun j ↦ (p j).2)
+
+/-- The simple unit tensor with singleton bases. -/
+def unit [One k] : Tensor.{u,v,w} k J where
+ Basis _ := PUnit
+ finiteBasis _ := inferInstance
+ coeff _ := 1
+
+/-- The all-parties equality tensor. -/
+noncomputable def diagonal [Zero k] [One k] (I : Type w) [Fintype I] : Tensor k J where
+ Basis _ := I
+ finiteBasis _ := inferInstance
+ coeff x := by classical exact if ∃ i, ∀ j, x j = i then 1 else 0
+
+/-- The direct sum includes the first array in the left block and the second
+array in the right block. The coefficient vanishes on every mixed block. -/
+noncomputable def directSum [Fintype J] [CommSemiring k]
+ (T : Tensor.{u,v,w} k J) (U : Tensor.{u,v,w'} k J) : Tensor k J where
+ Basis j := T.Basis j ⊕ U.Basis j
+ finiteBasis _ := inferInstance
+ coeff := by
+ classical
+ exact applyLocal (fun _ i b ↦ if i = Sum.inl b then 1 else 0) T.coeff +
+ applyLocal (fun _ i b ↦ if i = Sum.inr b then 1 else 0) U.coeff
+
+/-- A wire has one endpoint index at `a`, one at `b`, and trivial factors at
+other parties. The proof-indexed functions keep both local factors even when
+the two endpoints coincide. -/
+noncomputable def wire [Zero k] [One k] (a b : J) (I : Type w) [Fintype I] : Tensor k J where
+ Basis j := (j = a → I) × (j = b → I)
+ finiteBasis j := by classical exact inferInstance
+ coeff x := by classical exact if (x a).1 rfl = (x b).2 rfl then 1 else 0
+
+section Restrictions
+
+variable [Fintype J] [CommSemiring k]
+
+/-- Selecting one old coordinate at each party pulls back the coefficient array. -/
+theorem applyLocal_pullback {B C : J → Type*} [∀ j, Fintype (B j)]
+ [∀ j, DecidableEq (B j)] (f : ∀ j, C j → B j) (T : Array k B) :
+ applyLocal (fun j c b ↦ if f j c = b then 1 else 0) T =
+ fun c ↦ T (fun j ↦ f j (c j)) := by
+ classical
+ funext c
+ simp [applyLocal, Fintype.prod_boole, ← funext_iff, ite_mul]
+
+theorem applyLocal_id {B : J → Type*} [∀ j, Fintype (B j)] [∀ j, DecidableEq (B j)]
+ (T : Array k B) :
+ applyLocal (fun _ c b ↦ if c = b then 1 else 0) T = T :=
+ applyLocal_pullback (fun _ ↦ id) T
+
+/-- Composing two local restrictions multiplies the matrices at each party. -/
+theorem applyLocal_comp {A B C : J → Type*} [∀ j, Fintype (A j)] [∀ j, Fintype (B j)]
+ (M : ∀ j, C j → B j → k) (L : ∀ j, B j → A j → k) (T : Array k A) :
+ applyLocal M (applyLocal L T) =
+ applyLocal (fun j c a ↦ ∑ b, M j c b * L j b a) T := by
+ classical
+ funext c
+ simp only [applyLocal, Fintype.prod_sum, Finset.prod_mul_distrib, Finset.mul_sum,
+ Finset.sum_mul, mul_assoc]
+ rw [Finset.sum_comm]
+
+theorem Restricts.refl (T : Tensor k J) : Restricts T T := by
+ classical
+ exact ⟨_, applyLocal_id T.coeff⟩
+
+theorem Restricts.trans {T U V : Tensor k J} (hTU : Restricts T U) (hUV : Restricts U V) :
+ Restricts T V := by
+ obtain ⟨L, hL⟩ := hTU
+ obtain ⟨M, hM⟩ := hUV
+ exact ⟨_, (applyLocal_comp M L T.coeff).symm.trans (by rw [hL, hM])⟩
+
+/-- Relabeling the finite bases at every party gives mutual local restrictions. -/
+theorem restricts_of_reindex {T U : Tensor k J} (e : ∀ j, U.Basis j ≃ T.Basis j)
+ (h : ∀ c, U.coeff c = T.coeff (fun j ↦ e j (c j))) :
+ Restricts T U ∧ Restricts U T := by
+ classical
+ constructor
+ · exact ⟨_, (applyLocal_pullback (fun j ↦ e j) T.coeff).trans (funext h).symm⟩
+ · refine ⟨_, (applyLocal_pullback (fun j ↦ (e j).symm) U.coeff).trans ?_⟩
+ funext b
+ simp [h]
+
+end Restrictions
+
+section Products
+
+variable [Fintype J] [CommSemiring k]
+
+/-- Independent restrictions of two tensors combine after the parallel local
+factors are regrouped, by taking their Kronecker products at each party. -/
+theorem Restricts.tensorProduct {T T' U U' : Tensor k J} (hT : Restricts T T')
+ (hU : Restricts U U') : Restricts (tensorProduct T U) (tensorProduct T' U') := by
+ classical
+ obtain ⟨L, hL⟩ := hT
+ obtain ⟨M, hM⟩ := hU
+ refine ⟨fun j p q ↦ L j p.1 q.1 * M j p.2 q.2, ?_⟩
+ funext c
+ let f (b : ∀ j, T.Basis j) := (∏ j, L j (c j).1 (b j)) * T.coeff b
+ let g (b : ∀ j, U.Basis j) := (∏ j, M j (c j).2 (b j)) * U.coeff b
+ change (∑ b : ∀ j, T.Basis j × U.Basis j,
+ (∏ j, L j (c j).1 (b j).1 * M j (c j).2 (b j).2) *
+ (T.coeff (fun j ↦ (b j).1) * U.coeff (fun j ↦ (b j).2))) =
+ T'.coeff (fun j ↦ (c j).1) * U'.coeff (fun j ↦ (c j).2)
+ rw [← hL, ← hM]
+ change _ = (∑ b, f b) * ∑ b, g b
+ calc
+ _ = ∑ p : (∀ j, T.Basis j) × (∀ j, U.Basis j), f p.1 * g p.2 := by
+ apply Fintype.sum_equiv (Equiv.arrowProdEquivProdArrow J T.Basis U.Basis)
+ intro b
+ rw [Finset.prod_mul_distrib, mul_mul_mul_comm]
+ rfl
+ _ = _ := by rw [Fintype.sum_prod_type, Finset.sum_mul_sum]
+
+end Products
+
+section DirectSum
+variable [Fintype J] [CommSemiring k]
+
+/-- Coefficients on the first block of the direct sum. -/
+theorem directSum_coeff_inl [Nonempty J] (T : Tensor.{u,v,w} k J) (U : Tensor.{u,v,w'} k J)
+ (x : (j : J) → T.Basis j) :
+ (directSum T U).coeff (fun j ↦ Sum.inl (x j)) = T.coeff x := by
+ classical
+ simp [directSum, applyLocal, Fintype.prod_boole, ← funext_iff, ite_mul]
+
+/-- Coefficients on the second block of the direct sum. -/
+theorem directSum_coeff_inr [Nonempty J] (T : Tensor.{u,v,w} k J) (U : Tensor.{u,v,w'} k J)
+ (x : (j : J) → U.Basis j) :
+ (directSum T U).coeff (fun j ↦ Sum.inr (x j)) = U.coeff x := by
+ classical
+ simp [directSum, applyLocal, Fintype.prod_boole, ← funext_iff, ite_mul]
+
+/-- An entry using the left block at one party and the right block at another is zero. -/
+theorem directSum_coeff_mixed (T : Tensor.{u,v,w} k J) (U : Tensor.{u,v,w'} k J)
+ (x : (j : J) → T.Basis j ⊕ U.Basis j) {a b : J} {i : T.Basis a} {l : U.Basis b}
+ (ha : x a = Sum.inl i) (hb : x b = Sum.inr l) :
+ (directSum T U).coeff x = 0 := by
+ classical
+ have hleft (y : (j : J) → T.Basis j) : ¬ ∀ j, x j = Sum.inl (y j) := by
+ intro h
+ simpa [hb] using h b
+ have hright (y : (j : J) → U.Basis j) : ¬ ∀ j, x j = Sum.inr (y j) := by
+ intro h
+ simpa [ha] using h a
+ simp [directSum, applyLocal, Fintype.prod_boole, hleft, hright]
+
+/-- A local map on a direct sum acts separately on the two blocks, after which
+the resulting arrays are added in the ordinary sense. -/
+theorem applyLocal_directSum {C : J → Type*} (T : Tensor.{u,v,w} k J)
+ (U : Tensor.{u,v,w'} k J) (L : ∀ j, C j → (T.Basis j ⊕ U.Basis j) → k) :
+ applyLocal L (directSum T U).coeff =
+ applyLocal (fun j c b ↦ L j c (.inl b)) T.coeff +
+ applyLocal (fun j c b ↦ L j c (.inr b)) U.coeff := by
+ classical
+ funext c
+ simp only [directSum, applyLocal, Pi.add_apply, Fintype.prod_boole, ite_mul,
+ one_mul, zero_mul, mul_add, Finset.sum_add_distrib, Finset.mul_sum, mul_ite, mul_zero]
+ congr 1 <;> rw [Finset.sum_comm] <;> apply Finset.sum_congr rfl <;> intro x hx <;>
+ simp [← funext_iff]
+
+/-- Merging corresponding coordinates of the two blocks realizes the
+ordinary sum as a restriction of the direct sum. -/
+theorem directSum_restricts_add {B : J → Type w} [b : ∀ j, Fintype (B j)] (T U : Array k B) :
+ Restricts (directSum (Tensor.mk B b T) (Tensor.mk B b U)) (Tensor.mk B b (T + U)) := by
+ classical
+ let L (j : J) (c : B j) (p : B j ⊕ B j) : k := if c = p.elim id id then 1 else 0
+ refine ⟨L, ?_⟩
+ refine (applyLocal_directSum (C := B) (Tensor.mk B b T) (Tensor.mk B b U) L).trans ?_
+ change applyLocal (fun j (c x : B j) ↦ if c = x then 1 else 0) T +
+ applyLocal (fun j (c x : B j) ↦ if c = x then 1 else 0) U = T + U
+ funext c
+ simp [applyLocal, Fintype.prod_boole, ← funext_iff, ite_mul]
+
+end DirectSum
+
+/-- Local restrictions on the two summands act independently on the corresponding
+blocks at each party. -/
+theorem directSum_restricts [Fintype J] [CommSemiring k]
+ {T : Tensor k J} {U : Tensor k J} {T' : Tensor k J} {U' : Tensor k J} (hT : Restricts T T') (hU : Restricts U U') :
+ Restricts (directSum T U) (directSum T' U') := by
+ classical
+ obtain ⟨L, hL⟩ := hT
+ obtain ⟨M, hM⟩ := hU
+ let K (j : J) (c : T'.Basis j ⊕ U'.Basis j) (b : T.Basis j ⊕ U.Basis j) : k :=
+ match c, b with
+ | .inl x, .inl y => L j x y
+ | .inr x, .inr y => M j x y
+ | _, _ => 0
+ refine ⟨K, (applyLocal_directSum (C := fun j ↦ T'.Basis j ⊕ U'.Basis j) T U K).trans ?_⟩
+ simp only [directSum, ← hL, ← hM, applyLocal_comp]
+ congr 1
+ · apply congrArg (fun m ↦ applyLocal m T.coeff)
+ funext j c b
+ cases c <;> simp [K, ite_mul]
+ · apply congrArg (fun m ↦ applyLocal m U.coeff)
+ funext j c b
+ cases c <;> simp [K, ite_mul]
+
+section Summand
+variable [Fintype J] [CommSemiring k] [Nonempty J]
+
+/-- Projection onto the first coordinate block restricts a direct sum to its first summand. -/
+theorem directSum_restricts_left (T : Tensor.{u,v,w} k J) (U : Tensor.{u,v,w'} k J) :
+ Restricts (directSum T U) T := by
+ classical
+ let L (j : J) (c : T.Basis j) : T.Basis j ⊕ U.Basis j → k :=
+ Sum.elim (fun b ↦ if c = b then 1 else 0) (fun _ ↦ 0)
+ refine ⟨L, (applyLocal_directSum (C := T.Basis) T U L).trans ?_⟩
+ change applyLocal (fun j (c x : T.Basis j) ↦ if c = x then 1 else 0) T.coeff +
+ applyLocal (fun _ _ _ ↦ 0) U.coeff = T.coeff
+ funext c
+ simp [applyLocal, Fintype.prod_boole, ← funext_iff, ite_mul]
+
+/-- Projection onto the second coordinate block restricts a direct sum to its second summand. -/
+theorem directSum_restricts_right (T : Tensor.{u,v,w} k J) (U : Tensor.{u,v,w'} k J) :
+ Restricts (directSum T U) U := by
+ classical
+ let L (j : J) (c : U.Basis j) : T.Basis j ⊕ U.Basis j → k :=
+ Sum.elim (fun _ ↦ 0) (fun b ↦ if c = b then 1 else 0)
+ refine ⟨L, (applyLocal_directSum (C := U.Basis) T U L).trans ?_⟩
+ change applyLocal (fun _ _ _ ↦ 0) T.coeff +
+ applyLocal (fun j (c x : U.Basis j) ↦ if c = x then 1 else 0) U.coeff = U.coeff
+ funext c
+ simp [applyLocal, Fintype.prod_boole, ← funext_iff, ite_mul]
+
+end Summand
+
+/-- Move the factors indexed by `R` to the prescribed parties, grouping all
+factors at the same party into one local basis. -/
+noncomputable def placedTensor {R : Type*} [Fintype R] (place : R → J) (B : R → Type w)
+ [∀ r, Fintype (B r)] (T : Array k B) : Tensor k J where
+ Basis j := (r : R) → j = place r → B r
+ finiteBasis _ := by classical exact inferInstance
+ coeff x := T (fun r ↦ x (place r) r rfl)
+
+/-- The tensor enforcing equality of the indices at both ends of every edge.
+The local basis lists its incoming and outgoing endpoint indices separately. -/
+noncomputable def wireNetwork [CommSemiring k] {E : Type*} [Fintype E]
+ (a b : E → J) (I : E → Type w) [∀ e, Fintype (I e)] : Tensor k J where
+ Basis j := ((e : E) → j = a e → I e) × ((e : E) → j = b e → I e)
+ finiteBasis _ := by classical exact inferInstance
+ coeff x := by classical exact ∏ e, if (x (a e)).1 e rfl = (x (b e)).2 e rfl then 1 else 0
+
+/-- Encode a global assignment of indices to edges as the local half-wire
+assignments at a party. This is the point on the diagonal of the wire tensor. -/
+def edgeAssignment {E : Type*} (a b : E → J) {I : E → Type w} (x : (e : E) → I e) (j : J) :
+ ((e : E) → j = a e → I e) × ((e : E) → j = b e → I e) :=
+ ⟨fun e _ ↦ x e, fun e _ ↦ x e⟩
+
+private def endpointEquiv {E : Type*} (a b : E → J) (I : E → Type w) :
+ (((e : E) → I e) × ((e : E) → I e)) ≃
+ ((j : J) → ((e : E) → j = a e → I e) × ((e : E) → j = b e → I e)) where
+ toFun xy _ := ⟨fun e _ ↦ xy.1 e, fun e _ ↦ xy.2 e⟩
+ invFun x := ⟨fun e ↦ (x (a e)).1 e rfl, fun e ↦ (x (b e)).2 e rfl⟩
+ left_inv _ := rfl
+ right_inv x := by
+ funext j
+ apply Prod.ext
+ · funext e h
+ subst j
+ rfl
+ · funext e h
+ subst j
+ rfl
+
+open scoped Classical in
+/-- Contraction of the equality network leaves exactly one sum per edge,
+including when there are parallel edges or repeated parties. -/
+theorem applyLocal_wireNetwork [Fintype J] [CommSemiring k] {E : Type*} [Fintype E]
+ (a b : E → J) (I : E → Type w) [∀ e, Fintype (I e)] {C : J → Type*}
+ (L : ∀ j, C j → (wireNetwork (k := k) a b I).Basis j → k) (c : (j : J) → C j) :
+ applyLocal L (wireNetwork a b I).coeff c =
+ ∑ x : (e : E) → I e, ∏ j, L j (c j) (edgeAssignment a b x j) := by
+ classical
+ unfold applyLocal
+ let f := fun z : (j : J) → (wireNetwork (k := k) a b I).Basis j ↦
+ (∏ j, L j (c j) (z j)) * (wireNetwork (k := k) a b I).coeff z
+ change (∑ z, f z) = _
+ calc
+ _ = ∑ xy, f (endpointEquiv a b I xy) := ((endpointEquiv a b I).sum_comp f).symm
+ _ = _ := ?_
+ dsimp only [f]
+ rw [Fintype.sum_prod_type]
+ apply Finset.sum_congr rfl
+ intro x _
+ simp [wireNetwork, endpointEquiv, Fintype.prod_boole, ← funext_iff, mul_ite, edgeAssignment]
+
+end WireTensor
+
+namespace WireTensor
+
+variable {k : Type u} {J : Type v} [Fintype J] [Nonempty J]
+
+/-- A nonzero coefficient gives a restriction to the unit tensor. Each party
+selects its coordinate, and one party divides by the selected coefficient. -/
+theorem restricts_unit_of_ne_zero [Field k] (T : Tensor.{u,v,w} k J) (hT : T.coeff ≠ 0) :
+ Restricts T (unit.{u,v,0} (k := k) (J := J)) := by
+ classical
+ obtain ⟨p, hp⟩ : ∃ p, T.coeff p ≠ 0 :=
+ Classical.not_forall.mp (fun h ↦ hT (funext h))
+ let a : J := Classical.choice inferInstance
+ let L (j : J) (_ : PUnit) (i : T.Basis j) : k :=
+ if i = p j then (if j = a then (T.coeff p)⁻¹ else 1) else 0
+ refine ⟨L, ?_⟩
+ funext c
+ change (∑ b : (j : J) → T.Basis j, (∏ j, L j (c j) (b j)) * T.coeff b) = 1
+ rw [Finset.sum_eq_single p]
+ · simpa [L, Finset.prod_ite_eq'] using inv_mul_cancel₀ hp
+ · intro b _ hbp
+ obtain ⟨j, hj⟩ : ∃ j, b j ≠ p j := Classical.not_forall.mp (fun h ↦ hbp (funext h))
+ have hprod : (∏ j, L j (c j) (b j)) = 0 :=
+ Finset.prod_eq_zero (Finset.mem_univ j) (by simp [L, hj])
+ rw [hprod, zero_mul]
+ · simp
+
+/-- The diagonal indexed by all tuples of basis coordinates restricts to
+the tensor, giving the product of the local dimensions as a rank bound.
+One party contributes the selected coefficient, and all parties check their
+component of the tuple. -/
+theorem diagonal_restricts_of_card [CommSemiring k] (T : Tensor.{u,v,w} k J) :
+ Restricts (diagonal (Fin (∏ j, Fintype.card (T.Basis j)))) T := by
+ classical
+ let I := Fin (∏ j, Fintype.card (T.Basis j))
+ let e : ((j : J) → T.Basis j) ≃ I := Fintype.equivFinOfCardEq Fintype.card_pi
+ let a : J := Classical.choice inferInstance
+ let L (j : J) (i : T.Basis j) (s : I) : k :=
+ if i = e.symm s j then (if j = a then T.coeff (e.symm s) else 1) else 0
+ refine ⟨L, ?_⟩
+ funext p
+ simp only [applyLocal, diagonal]
+ rw [Finset.sum_eq_single (fun _ ↦ e p)]
+ · simp [L, Finset.prod_ite_eq']
+ · intro x _ hx
+ split_ifs with hdiag
+ · obtain ⟨s, hs⟩ := hdiag
+ obtain ⟨j, hj⟩ : ∃ j, p j ≠ e.symm s j := by
+ apply Classical.not_forall.mp
+ intro he
+ have hep : e p = s := by rw [funext he, e.apply_symm_apply]
+ exact hx (funext (fun i ↦ (hs i).trans hep.symm))
+ have hprod : (∏ j, L j (p j) (x j)) = 0 :=
+ Finset.prod_eq_zero (Finset.mem_univ j) (by simp [L, hs j, hj])
+ rw [hprod, zero_mul]
+ · simp
+ · intro h
+ exact (h (Finset.mem_univ _)).elim
+
+end WireTensor
+
+namespace WireTensor
+
+private theorem nonpos_of_nat_mul_bounded {x C : ℝ} (h : ∀ m : ℕ, (m : ℝ) * x ≤ C) :
+ x ≤ 0 := by
+ by_contra! hx
+ obtain ⟨m, hm⟩ := exists_nat_gt (C / x)
+ exact (not_lt_of_ge (h m)) ((div_lt_iff₀ hx).mp hm)
+
+/-- In Section 2.1, the monotonicity and multiplicativity of the value on
+integer-dimensional wires force the power law. For each power of `q`, compare
+the adjacent powers of two and then apply the same comparison to their images. -/
+theorem monotone_dimension_power_law (f : ℕ →* ℝ) (hf : Monotone f) {q : ℕ} (hq : 0 < q) :
+ f q = (q : ℝ) ^ (Real.log (f 2) / Real.log 2) := by
+ have hf_one (i : ℕ) (hi : 0 < i) : 1 ≤ f i := by
+ simpa using hf (show 1 ≤ i from hi)
+ have hf_pos (i : ℕ) (hi : 0 < i) : 0 < f i := zero_lt_one.trans_le (hf_one i hi)
+ have hb : 0 < Real.log 2 := Real.log_pos (by norm_num)
+ have hd : 0 ≤ Real.log (f 2) := Real.log_nonneg (hf_one _ (by decide))
+ have hlog {i j : ℕ} (hi : 0 < i) (hij : i ≤ j) : Real.log i ≤ Real.log j :=
+ Real.log_le_log (by exact_mod_cast hi) (by exact_mod_cast hij)
+ have hbounds (m : ℕ) :
+ (m : ℝ) * (Real.log (f q) * Real.log 2 - Real.log q * Real.log (f 2)) ≤
+ Real.log (f 2) * Real.log 2 ∧
+ (m : ℝ) * (Real.log q * Real.log (f 2) - Real.log (f q) * Real.log 2) ≤
+ Real.log (f 2) * Real.log 2 := by
+ let r := Nat.log 2 (q ^ m)
+ have hlo : 2 ^ r ≤ q ^ m := Nat.pow_log_le_self 2 (pow_ne_zero _ hq.ne')
+ have hhi : q ^ m ≤ 2 ^ r.succ := (Nat.lt_pow_succ_log_self (by decide) _).le
+ have hlo_log := hlog (by positivity) hlo
+ have hhi_log := hlog (pow_pos hq _) hhi
+ have hlo_image := Real.log_le_log (hf_pos _ (by positivity)) (hf hlo)
+ have hhi_image := Real.log_le_log (hf_pos _ (pow_pos hq _)) (hf hhi)
+ simp only [Nat.cast_pow, Nat.cast_ofNat, Real.log_pow, Nat.cast_succ] at hlo_log hhi_log
+ simp only [map_pow, Real.log_pow, Nat.cast_succ] at hlo_image hhi_image
+ constructor
+ · linarith only [mul_le_mul_of_nonneg_right hhi_image hb.le,
+ mul_le_mul_of_nonneg_right hlo_log hd]
+ · linarith only [mul_le_mul_of_nonneg_right hlo_image hb.le,
+ mul_le_mul_of_nonneg_right hhi_log hd]
+ have hcross : Real.log (f q) * Real.log 2 = Real.log q * Real.log (f 2) :=
+ le_antisymm (sub_nonpos.mp (nonpos_of_nat_mul_bounded fun m ↦ (hbounds m).1))
+ (sub_nonpos.mp (nonpos_of_nat_mul_bounded fun m ↦ (hbounds m).2))
+ rw [Real.rpow_def_of_pos (by exact_mod_cast hq), ← Real.exp_log (hf_pos q hq)]
+ congr 1
+ calc
+ Real.log (f q) = (Real.log q * Real.log (f 2)) / Real.log 2 :=
+ (eq_div_iff hb.ne').mpr hcross
+ _ = _ := by ring
+
+
+section WireArithmetic
+
+variable {k : Type u} {J : Type v}
+
+section Wires
+
+variable [Fintype J] [CommSemiring k]
+
+/-- Swapping the endpoints of a wire permutes the local bases. -/
+theorem wire_swap (a b : J) (I : Type*) [Fintype I] :
+ Restricts (wire (k := k) a b I) (wire b a I) ∧
+ Restricts (wire (k := k) b a I) (wire a b I) := by
+ classical
+ apply restricts_of_reindex (fun _ ↦ Equiv.prodComm _ _)
+ intro z
+ change (if (z b).1 rfl = (z a).2 rfl then (1 : k) else 0) =
+ if (z a).2 rfl = (z b).1 rfl then 1 else 0
+ rw [@eq_comm _ ((z b).1 rfl) ((z a).2 rfl)]
+
+/-- A wire on a smaller index set is obtained by coordinate selection at its endpoints. -/
+theorem wire_restricts_of_embedding (a b : J) {I K : Type*} [Fintype I] [Fintype K]
+ (e : I ↪ K) : Restricts (wire (k := k) a b K) (wire a b I) := by
+ classical
+ let f (j : J) (z : (j = a → I) × (j = b → I)) :
+ (j = a → K) × (j = b → K) := (e ∘ z.1, e ∘ z.2)
+ refine ⟨_, (applyLocal_pullback f (wire (k := k) a b K).coeff).trans ?_⟩
+ funext z
+ simp [wire, f]
+
+theorem wire_restricts_of_le (a b : J) {m n : ℕ} (h : m ≤ n) :
+ Restricts (wire (k := k) a b (Fin n)) (wire a b (Fin m)) :=
+ wire_restricts_of_embedding a b (Fin.castLEEmb h)
+
+/-- The two coordinate components of an ordered pair give the two parallel wires. -/
+theorem wire_tensorProduct (a b : J) (I K : Type*) [Fintype I] [Fintype K] :
+ Restricts (wire (k := k) a b (I × K)) (tensorProduct (wire a b I) (wire a b K)) ∧
+ Restricts (tensorProduct (wire (k := k) a b I) (wire a b K)) (wire a b (I × K)) := by
+ classical
+ let e (j : J) :
+ ((j = a → I) × (j = b → I)) × ((j = a → K) × (j = b → K)) ≃
+ ((j = a → I × K) × (j = b → I × K)) :=
+ { toFun := fun z ↦ (fun h ↦ (z.1.1 h, z.2.1 h), fun h ↦ (z.1.2 h, z.2.2 h))
+ invFun := fun z ↦ ((fun h ↦ (z.1 h).1, fun h ↦ (z.2 h).1),
+ (fun h ↦ (z.1 h).2, fun h ↦ (z.2 h).2))
+ left_inv := fun _ ↦ rfl
+ right_inv := fun _ ↦ rfl }
+ apply restricts_of_reindex e
+ intro z
+ have he : (e a (z a)).1 rfl = (e b (z b)).2 rfl ↔
+ (z a).1.1 rfl = (z b).1.2 rfl ∧ (z a).2.1 rfl = (z b).2.2 rfl :=
+ Prod.mk.injEq _ _ _ _ |>.to_iff
+ simp only [wire, tensorProduct]
+ split_ifs <;> simp_all <;> contradiction
+
+/-- Sending each copy of the unit to the matching pair of endpoint basis
+vectors produces a wire of the same dimension. -/
+theorem diagonal_restricts_wire (a b : J) (I : Type*) [Fintype I] :
+ Restricts (diagonal (k := k) I) (wire a b I) := by
+ classical
+ let L (j : J) (z : (j = a → I) × (j = b → I)) (i : I) : k :=
+ if (∀ h, z.1 h = i) ∧ (∀ h, z.2 h = i) then 1 else 0
+ refine ⟨L, ?_⟩
+ funext z
+ simp only [applyLocal, diagonal, wire, L, Fintype.prod_boole]
+ rw [Finset.sum_eq_single (fun _ ↦ (z a).1 rfl)]
+ · have he : (∀ j, (∀ h : j = a, (z j).1 h = (z a).1 rfl) ∧
+ (∀ h : j = b, (z j).2 h = (z a).1 rfl)) ↔ (z a).1 rfl = (z b).2 rfl := by
+ constructor
+ · exact fun h ↦ ((h b).2 rfl).symm
+ · intro h j
+ exact ⟨by rintro rfl; rfl, by rintro rfl; exact h.symm⟩
+ have hc : ∃ i : I, ∀ _ : J, (z a).1 rfl = i := ⟨_, fun _ ↦ rfl⟩
+ simp only [hc, ite_true, mul_one, he]
+ · intro x _ hx
+ split_ifs with hloc hdiag
+ · obtain ⟨i, hi⟩ := hdiag
+ exact False.elim (hx (funext (fun j ↦ (hi j).trans ((hi a).symm.trans ((hloc a).1 rfl).symm))))
+ all_goals simp
+ · intro h
+ exact (h (Finset.mem_univ _)).elim
+
+end Wires
+
+section UnitWires
+
+variable [Fintype J] [CommSemiring k]
+
+/-- A one-dimensional wire is the simple unit, including when its endpoints coincide. -/
+theorem wire_one (a b : J) :
+ Restricts (unit.{u,v,0} (k := k) (J := J)) (wire a b (Fin 1)) ∧
+ Restricts (wire (k := k) a b (Fin 1)) unit.{u,v,0} := by
+ classical
+ let (j : J) : Unique ((j = a → Fin 1) × (j = b → Fin 1)) :=
+ uniqueOfSubsingleton (fun _ ↦ 0, fun _ ↦ 0)
+ apply restricts_of_reindex (fun j ↦ Equiv.equivPUnit ((j = a → Fin 1) × (j = b → Fin 1)))
+ intro z
+ simp [wire, unit, Subsingleton.elim ((z a).1 rfl) ((z b).2 rfl)]
+
+/-- A loop carries both endpoint indices at a single party, so its Kronecker
+delta can be created by a linear map from that party's one-dimensional leg. -/
+theorem unit_restricts_loop (a : J) (I : Type*) [Fintype I] :
+ Restricts (unit.{u,v,0} (k := k) (J := J)) (wire a a I) := by
+ classical
+ let L (j : J) (z : (j = a → I) × (j = a → I)) (_ : PUnit) : k :=
+ if ∀ h, z.1 h = z.2 h then 1 else 0
+ refine ⟨L, ?_⟩
+ funext z
+ have he : (∀ j, ∀ h : j = a, (z j).1 h = (z j).2 h) ↔ (z a).1 rfl = (z a).2 rfl :=
+ ⟨fun h ↦ h a rfl, fun h _ eq ↦ by subst eq; exact h⟩
+ change (∑ x : J → PUnit, (∏ j, L j (z j) (x j)) * 1) = _
+ rw [Fintype.sum_unique]
+ simp [wire, L, Fintype.prod_boole, he]
+
+end UnitWires
+
+/-- Contracting the common endpoint of two wires produces the wire between
+their outside endpoints. This works even when some of the three parties coincide. -/
+theorem restricts_wire_triangle [Fintype J] [CommSemiring k] (a b c : J)
+ (I : Type w) [Fintype I] :
+ Restricts (tensorProduct (wire (k := k) a b I) (wire b c I)) (wire a c I) := by
+ classical
+ let ok (j : J) (z : (wire (k := k) a c I).Basis j)
+ (y : (tensorProduct (wire (k := k) a b I) (wire b c I)).Basis j) : Prop :=
+ (∀ h : j = a, z.1 h = y.1.1 h) ∧ (∀ h : j = b, y.1.2 h = y.2.1 h) ∧
+ (∀ h : j = c, z.2 h = y.2.2 h)
+ refine ⟨fun j z y ↦ if ok j z y then 1 else 0, ?_⟩
+ funext z
+ let y₀ (j : J) : (tensorProduct (wire (k := k) a b I) (wire b c I)).Basis j :=
+ ((fun _ ↦ (z a).1 rfl, fun _ ↦ (z a).1 rfl),
+ (fun _ ↦ (z c).2 rfl, fun _ ↦ (z c).2 rfl))
+ have hok : (∀ j, ok j (z j) (y₀ j)) ↔ (z a).1 rfl = (z c).2 rfl := by
+ refine ⟨fun h ↦ (h b).2.1 rfl, fun h j ↦ ⟨?_, ?_, ?_⟩⟩
+ · rintro rfl
+ rfl
+ · rintro rfl
+ exact h
+ · rintro rfl
+ rfl
+ have uniqueY (y : ∀ j, (tensorProduct (wire (k := k) a b I) (wire b c I)).Basis j)
+ (h : ∀ j, ok j (z j) (y j))
+ (hl : (y a).1.1 rfl = (y b).1.2 rfl) (hr : (y b).2.1 rfl = (y c).2.2 rfl) :
+ y = y₀ := by
+ funext j
+ apply Prod.ext
+ · apply Prod.ext
+ · funext hj
+ subst j
+ exact ((h a).1 rfl).symm
+ · funext hj
+ subst j
+ exact hl.symm.trans ((h a).1 rfl).symm
+ · apply Prod.ext
+ · funext hj
+ subst j
+ exact hr.trans ((h c).2.2 rfl).symm
+ · funext hj
+ subst j
+ exact ((h c).2.2 rfl).symm
+ have product (y : ∀ j, (tensorProduct (wire (k := k) a b I) (wire b c I)).Basis j) :
+ (∏ j, if ok j (z j) (y j) then (1 : k) else 0) =
+ if ∀ j, ok j (z j) (y j) then 1 else 0 := Fintype.prod_boole (p := fun j ↦ ok j (z j) (y j))
+ rw [applyLocal, Finset.sum_eq_single y₀]
+ · rw [product, if_congr hok (rfl : (1 : k) = 1) (rfl : (0 : k) = 0)]
+ simp [tensorProduct, wire, y₀]
+ · intro y _ hy
+ rw [product]
+ simp only [tensorProduct, wire]
+ split_ifs with h hl hr <;> simp only [zero_mul, mul_zero, one_mul]
+ exact (hy (uniqueY y h hl hr)).elim
+ · simp
+
+end WireArithmetic
+
+end WireTensor
+
+
+universe z
+
+namespace WireTensor
+
+variable {k J R : Type*} [CommSemiring k] [Fintype J] [Fintype R]
+
+/-- The extra edge in `Option R` carries the factorization index. -/
+def cutBasis (B : R → Type z) (K : Type z) : Option R → Type z
+ | none => K
+ | some r => B r
+
+instance cutBasisFintype (B : R → Type z) (K : Type z) [∀ r, Fintype (B r)] [Fintype K]
+ (e : Option R) : Fintype (cutBasis B K e) := by
+ cases e with
+ | none => exact inferInstanceAs (Fintype K)
+ | some r => exact inferInstanceAs (Fintype (B r))
+
+/-- The terminals feed into the center on their own side. The remaining edge
+carries the common matrix-factorization index from the first center to the second. -/
+def cutSource (place : R → J) (center : Bool → J) : Option R → J
+ | none => center false
+ | some r => place r
+
+/-- Send each routed wire to the center on its selected side of the cut, and the auxiliary wire
+to the true-side center. -/
+def cutTarget (side : R → Bool) (center : Bool → J) : Option R → J
+ | none => center true
+ | some r => center (side r)
+
+private theorem prod_at [DecidableEq J] (a : J) (f : ∀ j, j = a → k) :
+ ∏ j, (if h : j = a then f j h else 1) = f a rfl := by
+ rw [Finset.prod_eq_single a]
+ · simp
+ · intro j _ hj
+ simp [hj]
+ · simp
+
+private def cutBasisEquiv (B : R → Type z) (K : Type z) :
+ K × ((r : R) → B r) ≃ ((e : Option R) → cutBasis B K e) where
+ toFun p | none => p.1 | some r => p.2 r
+ invFun x := (x none, fun r ↦ x (some r))
+ left_inv _ := rfl
+ right_inv x := by funext e; cases e <;> rfl
+
+open scoped Classical in
+/-- Any matrix factorization across a cut of the terminal roles can be realized
+by terminal-to-center wires plus a rank wire between the two centers. Roles and
+centers may coincide as parties. Used for both shifted cuts in Lemma 3.2. -/
+theorem cutFactorization_restricts (place : R → J) (side : R → Bool) (center : Bool → J)
+ (B : R → Type z) [∀ r, Fintype (B r)] (K : Type z) [Fintype K]
+ (F : ((r : R) → side r = false → B r) → K → k)
+ (G : ((r : R) → side r = true → B r) → K → k) :
+ Restricts (wireNetwork (cutSource place center) (cutTarget side center) (cutBasis B K))
+ (placedTensor place B (fun x ↦ ∑ z, F (fun r _ ↦ x r) z * G (fun r _ ↦ x r) z)) := by
+ classical
+ let _ : DecidableEq (Option R) := Classical.decEq _
+ let a := cutSource place center
+ let b := cutTarget side center
+ let I := cutBasis B K
+ let L (j : J) (u : (r : R) → j = place r → B r)
+ (w : (wireNetwork (k := k) a b I).Basis j) : k :=
+ (∏ r, if h : j = place r then (if u r h = w.1 (some r) h then (1 : k) else 0) else 1) *
+ (if h : j = center false then
+ F (fun r hr ↦ w.2 (some r) (h.trans (congrArg center hr).symm)) (w.1 none h) else 1) *
+ (if h : j = center true then
+ G (fun r hr ↦ w.2 (some r) (h.trans (congrArg center hr).symm)) (w.2 none h) else 1)
+ refine ⟨L, ?_⟩
+ funext u
+ refine (applyLocal_wireNetwork a b I L u).trans ?_
+ let f := fun x : (e : Option R) → I e ↦ ∏ j, L j (u j) (edgeAssignment a b x j)
+ change (∑ x, f x) = _
+ calc
+ _ = ∑ p, f (cutBasisEquiv B K p) := ((cutBasisEquiv B K).sum_comp f).symm
+ _ = _ := ?_
+ rw [Fintype.sum_prod_type]
+ apply Finset.sum_congr rfl
+ intro z _
+ let out := fun r ↦ u (place r) r rfl
+ have hp (x : (r : R) → B r) : f (cutBasisEquiv B K (z, x)) =
+ (if out = x then 1 else 0) * F (fun r _ ↦ x r) z * G (fun r _ ↦ x r) z := by
+ dsimp only [f, L, edgeAssignment, cutBasisEquiv, Equiv.coe_fn_mk]
+ rw [Finset.prod_mul_distrib, Finset.prod_mul_distrib, Finset.prod_comm]
+ simp_rw [prod_at]
+ simp [Fintype.prod_boole, out, ← funext_iff]
+ change (∑ x, f (cutBasisEquiv B K (z, x))) = _
+ simp_rw [hp]
+ simp [ite_mul, out]
+
+end WireTensor
+
+end VPVNP
+end Computability
+end OAI
diff --git a/lean/docs/379.md b/lean/docs/379.md
new file mode 100644
index 0000000000..e138903e12
--- /dev/null
+++ b/lean/docs/379.md
@@ -0,0 +1,17 @@
+# Separation of VP and VNP over every field
+
+The following describes the scope of the Lean formalization related to the following accompanying paper(s):
+
+- [VP and VNP are different](../../preprints/VP-and-VNP-are-different-November-23-2026/paper.pdf)
+
+## Scope
+
+The formalization proves that VP differs from VNP over every field in the nonuniform model of exact arithmetic circuits with binary addition, subtraction, and multiplication gates. It gives an explicit VNP-complete family whose $n$th polynomial is homogeneous of degree $n$ and multilinear in $2n$ variables. For each exponent $C\ge 1$ and each characteristic, its exact circuit size exceeds $n^C$ for all sufficiently large $n$, with a threshold uniform over fields of that characteristic.
+
+Lean also proves this superpolynomial exact circuit lower bound for the directed Hamiltonian cycle polynomial over every field and for the permanent over fields of characteristic other than two. The paper gives the stronger lower bound $\exp(\Omega((\log n)^{5/4}))$ for border circuits.
+
+## Comparator links
+
+| Result | Comparator statement |
+| --- | --- |
+| Separation of exact VP and VNP over every field | [VPVNP.lean](../ComparatorChallenges/VPVNP.lean) |
diff --git a/lean/formalization.yaml b/lean/formalization.yaml
index 372bcd714c..760c5864b8 100644
--- a/lean/formalization.yaml
+++ b/lean/formalization.yaml
@@ -884,6 +884,11 @@ sources:
id: ../preprints/Universal-cover-splitting-for-compact-Kahler-manifolds-September-23-2026/paper.pdf
type: article
+ - title: "VP and VNP are different"
+ authors: ["OpenAI"]
+ id: ../preprints/VP-and-VNP-are-different-November-23-2026/paper.pdf
+ type: article
+
- title: "Weak Hessian bounds along every geodesic in RCD spaces"
authors: ["OpenAI"]
id: ../preprints/Weak-Hessian-bounds-along-every-geodesic-in-RCD-spaces-September-24-2026/weak-hessian-geodesics.pdf
@@ -1800,6 +1805,10 @@ status:
declaration: OAI.UniversalFInfinity.universal_group_of_type_FInfinity
file: OAI/GroupTheory/UniversalGroup/Main.lean
+ - comparator_config: ComparatorChallenges/VPVNP.json
+ declaration: OAI.Computability.VPVNP.Standalone.vp_ne_vnp
+ file: OAI/Computability/VPVNP/ClassSeparation.lean
+
- comparator_config: ComparatorChallenges/VertexCover.json
declaration: OAI.VertexCover.every_fixed_factor_below_two
file: OAI/Computability/VertexCover/Main.lean
diff --git a/lean/lake-manifest.json b/lean/lake-manifest.json
index 67d01d2717..1736c44cef 100644
--- a/lean/lake-manifest.json
+++ b/lean/lake-manifest.json
@@ -71,6 +71,36 @@
"inputRev": "c39a751132c88b6e8080b74c74023fd95b3d8be0",
"inherited": false,
"configFile": "lakefile.toml"},
+ {"url": "https://github.com/ZIB-IOL/lemmata.git",
+ "type": "git",
+ "subDir": "lean",
+ "scope": "",
+ "rev": "a2dd430f283febd755a6ee6932d0b0fdabfb330c",
+ "name": "lemmata",
+ "manifestFile": "lake-manifest.json",
+ "inputRev": "a2dd430f283febd755a6ee6932d0b0fdabfb330c",
+ "inherited": false,
+ "configFile": "lakefile.toml"},
+ {"url": "https://github.com/leanprover/cslib",
+ "type": "git",
+ "subDir": null,
+ "scope": "",
+ "rev": "254e30e6d4299c51323aaeaf5f51a4763b375d4a",
+ "name": "cslib",
+ "manifestFile": "lake-manifest.json",
+ "inputRev": "254e30e6d4299c51323aaeaf5f51a4763b375d4a",
+ "inherited": false,
+ "configFile": "lakefile.toml"},
+ {"url": "https://github.com/cslib-community/complexitylib.git",
+ "type": "git",
+ "subDir": null,
+ "scope": "",
+ "rev": "242879e6913ca3b29005f7c48536896983d2ad2f",
+ "name": "complexitylib",
+ "manifestFile": "lake-manifest.json",
+ "inputRev": "242879e6913ca3b29005f7c48536896983d2ad2f",
+ "inherited": false,
+ "configFile": "lakefile.toml"},
{"url": "https://github.com/lana-agents/belyi.git",
"type": "git",
"subDir": null,
diff --git a/lean/lakefile.lean b/lean/lakefile.lean
index cd24ca2ee0..1cf49aac8a 100644
--- a/lean/lakefile.lean
+++ b/lean/lakefile.lean
@@ -69,6 +69,13 @@ require «formal-schemes» from git
require «belyi» from git
"https://github.com/lana-agents/belyi.git" @ "9ce4d3f793d3bc831f2fc7214b7dbad90ea012d8"
+require complexitylib from git
+ "https://github.com/cslib-community/complexitylib.git" @ "242879e6913ca3b29005f7c48536896983d2ad2f"
+require cslib from git
+ "https://github.com/leanprover/cslib" @ "254e30e6d4299c51323aaeaf5f51a4763b375d4a"
+require lemmata from git
+ "https://github.com/ZIB-IOL/lemmata.git" @ "a2dd430f283febd755a6ee6932d0b0fdabfb330c" / "lean"
+
-- Declare shared dependencies last: Lake resolves later requirements first.
-- These pins override the older versions in the upstream packages' manifests.
require PrimeNumberTheoremAnd from git
@@ -319,7 +326,7 @@ post_update pkg do
-- Preflight every dependency before changing any of them.
let mut plans := #[]
- for name in #[`«fixed-point-theorems», `PrimeNumberTheoremAnd, `Zeta3Irrational,
+ for name in #[`complexitylib, `lemmata, `«fixed-point-theorems», `PrimeNumberTheoremAnd, `Zeta3Irrational,
`«rellich-kondrachov», `carleson, `StrongPNT, `AbsorptionCutoff, `AINTLIB,
`ClassFieldTheory, `«schoenflies-lean», `SphereEversion, `gromov] do
let label := name.toString (escape := false)
@@ -329,7 +336,7 @@ post_update pkg do
| error s!"Missing direct dependency declaration for {label}."
let some (.git _ (some revision) _) := declaration.src?
| error s!"{label} must be pinned to a Git commit."
- let patchDirectory := dep.dir
+ let patchDirectory := if name == `lemmata then dep.dir / ".." else dep.dir
let head ← patchGit patchDirectory #["rev-parse", "HEAD"]
unless head.exitCode == 0 && head.stdout.trimAscii.toString == revision do
error s!"{label}: expected commit {revision}, got {head.stdout}\n{head.stderr}"
diff --git a/lean/patches/complexitylib-lean4341.patch b/lean/patches/complexitylib-lean4341.patch
new file mode 100644
index 0000000000..7d426ac086
--- /dev/null
+++ b/lean/patches/complexitylib-lean4341.patch
@@ -0,0 +1,30 @@
+diff --git a/Complexity/Computability/Circuit/Bird.lean b/Complexity/Computability/Circuit/Bird.lean
+index a39c61a..ea33a70 100644
+--- a/Complexity/Computability/Circuit/Bird.lean
++++ b/Complexity/Computability/Circuit/Bird.lean
+@@ -8,7 +8,7 @@ module
+ -- upstream: candidate
+
+ public import Complexity.Init
+-public import Mathlib.LinearAlgebra.Matrix.Array
++public import Mathlib.LinearAlgebra.Matrix.Defs
+ public import Mathlib.LinearAlgebra.Matrix.Determinant.Bird.Defs
+ public import Mathlib.LinearAlgebra.Matrix.Determinant.Basic
+ import Mathlib.Algebra.Order.BigOperators.Group.LocallyFinite
+diff --git a/lakefile.toml b/lakefile.toml
+index 7752f5b50..4b373406e 100644
+--- a/lakefile.toml
++++ b/lakefile.toml
+@@ -3,12 +3,6 @@ version = "0.2.0"
+ defaultTargets = ["Complexity", "ComplexityResults"]
+ testDriver = "ComplexityTests"
+ lintDriver = "batteries/runLinter"
+-# Share build outputs between local checkouts (worktrees, agent sandboxes) through Lake's
+-# content-addressed artifact cache, so a module built in one checkout is reused by every other
+-# checkout with the same inputs. Restoring hard-links cached outputs back into `.lake/build`, so
+-# tools and CI caches that read the build directory still see a complete tree.
+-enableArtifactCache = true
+-restoreAllArtifacts = true
+ # The library has no native code, so its build outputs are the same on every platform and the
+ # remote cache (see `scripts/cache/README.md`) built on Linux CI also serves macOS checkouts.
+ platformIndependent = true
diff --git a/lean/patches/lemmata-lean4341.patch b/lean/patches/lemmata-lean4341.patch
new file mode 100644
index 0000000000..9c64fcd839
--- /dev/null
+++ b/lean/patches/lemmata-lean4341.patch
@@ -0,0 +1,543 @@
+diff --git a/lean/Lemmata/FockCircuits/Duality.lean b/lean/Lemmata/FockCircuits/Duality.lean
+index 7ee82e8..92e9f35 100644
+--- a/lean/Lemmata/FockCircuits/Duality.lean
++++ b/lean/Lemmata/FockCircuits/Duality.lean
+@@ -27,8 +27,7 @@ noncomputable def rightProjection : Fock R →ₐ[R] Fock R :=
+
+ @[simp] theorem rightProjection_left (i : ℕ) :
+ rightProjection R (TwoColour.left R i) = 0 := by
+- have hm : (2 * i) % 2 ≠ 1 := by omega
+- simp [rightProjection, TwoColour.left, Fock.generator, rightParticle, hm]
++ simp [rightProjection, TwoColour.left, Fock.generator, rightParticle]
+
+ @[simp] theorem rightProjection_right (i : ℕ) :
+ rightProjection R (TwoColour.right R i) = Fock.generator R i := by
+@@ -50,7 +49,7 @@ theorem rightProjection_left_word (I : Finset ℕ) :
+ intro hI
+ subst I
+ simp at h
+- simp [h, hI, Function.comp_def]
++ simp [hI, Function.comp_def]
+
+ theorem rightProjection_right_word (I : Finset ℕ) :
+ rightProjection R (colourBasis R (colourIndex ∅ I)) = Fock.basis R I := by
+@@ -206,7 +205,7 @@ theorem dualState_energy {L : ℕ} (I : Finset ℕ) (J : Index L)
+ (hJ : doubledEnergy I < doubledEnergy J.val) : dualState R L I J = 0 := by
+ have h := congrArg (fun x : Fock R => (Fock.basis R).repr x J.val)
+ (Fock.pascalExteriorInverse_basis_energy R I)
+- rw [Fock.energyProjection_coefficient, if_neg (by omega)] at h
++ rw [Fock.energyProjection_coefficient, ite_eq_right (by omega)] at h
+ exact h.symm
+
+ theorem dualState_parity {L : ℕ} (I : Finset ℕ) (J : Index L)
+@@ -214,7 +213,7 @@ theorem dualState_parity {L : ℕ} (I : Finset ℕ) (J : Index L)
+ (hJ : doubledEnergy J.val % 2 ≠ doubledEnergy I % 2) : dualState R L I J = 0 := by
+ have h := congrArg (fun x : Fock R => (Fock.basis R).repr x J.val)
+ (Fock.pascalExteriorInverse_basis_parity R I hI)
+- rw [Fock.parityProjection_coefficient, if_neg hJ] at h
++ rw [Fock.parityProjection_coefficient, ite_eq_right hJ] at h
+ exact h.symm
+
+ theorem dualState_supported {L : ℕ} (I : Index L) (J : Index L)
+@@ -240,7 +239,7 @@ theorem dual_kernel_coefficient {L : ℕ} (I J : Index L)
+ Finset.mem_range.mp (Finset.mem_powerset.mp I.property hi))]
+ have h := congrArg (fun x : Fock R => (Fock.basis R).repr x J.val)
+ (Fock.finitePascal_homogeneous_diagonal R L I.val)
+- rw [Fock.energyProjection_coefficient, if_pos (by omega)] at h
++ rw [Fock.energyProjection_coefficient, ite_eq_left (by omega)] at h
+ simpa only [Module.Basis.repr_self_apply, Subtype.val_inj, eq_comm] using h
+
+ theorem dual_matrix_vacuum {L : ℕ} (I J : Index L)
+diff --git a/lean/Lemmata/FockCircuits/EnergyProjection.lean b/lean/Lemmata/FockCircuits/EnergyProjection.lean
+index bd241e8..b656ec0 100644
+--- a/lean/Lemmata/FockCircuits/EnergyProjection.lean
++++ b/lean/Lemmata/FockCircuits/EnergyProjection.lean
+@@ -83,7 +83,7 @@ private theorem selected_basis_coefficient (P : Finset ℕ → Prop) [DecidableP
+ intro I
+ by_cases hJ : P J <;>
+ by_cases hI : P I <;>
+- by_cases hIJ : I = J <;> simp_all [F, G, Finsupp.single_apply]
++ by_cases hIJ : I = J <;> simp_all [F, G]
+ by_cases hJ : P J <;>
+ simpa [F, G, hJ] using LinearMap.congr_fun h x
+
+diff --git a/lean/Lemmata/FockCircuits/ExteriorMatching.lean b/lean/Lemmata/FockCircuits/ExteriorMatching.lean
+index b93a827..83bfec2 100644
+--- a/lean/Lemmata/FockCircuits/ExteriorMatching.lean
++++ b/lean/Lemmata/FockCircuits/ExteriorMatching.lean
+@@ -54,7 +54,7 @@ theorem contract_word (x : α → M) (d : Module.Dual R M) (A : List α) :
+ conv_rhs => rw [Fin.sum_univ_succ]
+ simp only [Fin.getElem_fin, Fin.val_zero, pow_zero, one_mul, List.getElem_cons_zero,
+ List.eraseIdx_cons_zero, Fin.val_succ, List.getElem_cons_succ,
+- List.eraseIdx_cons_succ, word_cons, Finset.mul_sum, Finset.smul_sum,
++ List.eraseIdx_cons_succ, word_cons, Finset.mul_sum,
+ Algebra.mul_smul_comm, pow_succ, mul_neg, neg_mul, mul_one, neg_smul,
+ Finset.sum_neg_distrib]
+ module
+diff --git a/lean/Lemmata/FockCircuits/FiniteIdentity.lean b/lean/Lemmata/FockCircuits/FiniteIdentity.lean
+index d372a52..abbfdab 100644
+--- a/lean/Lemmata/FockCircuits/FiniteIdentity.lean
++++ b/lean/Lemmata/FockCircuits/FiniteIdentity.lean
+@@ -4,7 +4,7 @@ public import Lemmata.FockCircuits.Kernel
+ public import Lemmata.FockCircuits.BasisAction
+ public import Mathlib.Algebra.Polynomial.Laurent
+ public import Mathlib.Logic.Equiv.Nat
+-public import Mathlib.Order.Sum.Order
++public import Mathlib.Data.Sum.Order
+ public import Mathlib.Order.Interval.Finset.Nat
+ public import Mathlib.Algebra.Polynomial.Div
+ public import Mathlib.RingTheory.PowerSeries.Trunc
+diff --git a/lean/Lemmata/FockCircuits/Kernel.lean b/lean/Lemmata/FockCircuits/Kernel.lean
+index e20a79d..b9433d0 100644
+--- a/lean/Lemmata/FockCircuits/Kernel.lean
++++ b/lean/Lemmata/FockCircuits/Kernel.lean
+@@ -177,7 +177,7 @@ theorem normalList_create_of_orthogonal
+ smul_neg, smul_add, smul_smul, hs, one_smul, map_add]
+ match_scalars <;>
+ rcases neg_one_pow_eq_or R L.length with hsign | hsign <;>
+- simp [hsign] <;> ring
++ simp [hsign]
+
+ noncomputable def colouredList (N : ℕ) (L : List ((Fin N → R) × (Fin N → R))) :
+ List (OneParticle R × OneParticle R) :=
+diff --git a/lean/Lemmata/FockCircuits/KernelCoevaluation.lean b/lean/Lemmata/FockCircuits/KernelCoevaluation.lean
+index edbbf1a..82a4043 100644
+--- a/lean/Lemmata/FockCircuits/KernelCoevaluation.lean
++++ b/lean/Lemmata/FockCircuits/KernelCoevaluation.lean
+@@ -64,8 +64,7 @@ theorem colourBasis_left_word (I : Finset ℕ) :
+ rw [sort_image_strictMono (fun i : ℕ => toLex (Sum.inl i : ℕ ⊕ ℕ))
+ (fun _ _ h => Sum.Lex.inl h) I]
+ simp [List.map_map, Function.comp_def, Module.Basis.reindex_apply,
+- Finsupp.coe_basisSingleOne, Equiv.natSumNatEquivNat_apply,
+- TwoColour.left, Fock.generator]
++ Finsupp.coe_basisSingleOne, Equiv.natSumNatEquivNat_apply]
+ rfl
+
+ theorem colourBasis_right_word (I : Finset ℕ) :
+@@ -76,8 +75,7 @@ theorem colourBasis_right_word (I : Finset ℕ) :
+ rw [sort_image_strictMono (fun i : ℕ => toLex (Sum.inr i : ℕ ⊕ ℕ))
+ (fun _ _ h => Sum.Lex.inr h) I]
+ simp [List.map_map, Function.comp_def, Module.Basis.reindex_apply,
+- Finsupp.coe_basisSingleOne, Equiv.natSumNatEquivNat_apply,
+- TwoColour.right, Fock.generator]
++ Finsupp.coe_basisSingleOne, Equiv.natSumNatEquivNat_apply]
+ rfl
+
+ noncomputable def leftParticle : OneParticle R →ₗ[R] OneParticle R :=
+@@ -271,8 +269,8 @@ theorem matrix_vacuum (L : ℕ) :
+ have hs : (dualSign I.val : R) * (dualSign I.val : R) = 1 := by
+ have h := congrArg (fun z : ℤ => (z : R)) (dualSign_mul_self I.val)
+ simpa only [Int.cast_mul, Int.cast_one] using h
+- simp [Matrix.one_apply, hsub, hs]
++ simp [hsub, hs]
+ · have hval : I.val ≠ J.val := fun h => hIJ (Subtype.ext h)
+- simp [Matrix.one_apply, hIJ, hval]
++ simp [hIJ, hval]
+
+ end Lemmata.FockCircuits.FiniteIdentity
+diff --git a/lean/Lemmata/FockCircuits/KernelOperators.lean b/lean/Lemmata/FockCircuits/KernelOperators.lean
+index e043b4d..a16b736 100644
+--- a/lean/Lemmata/FockCircuits/KernelOperators.lean
++++ b/lean/Lemmata/FockCircuits/KernelOperators.lean
+@@ -26,7 +26,7 @@ theorem leftParticle_even (v : OneParticle R) (i : ℕ) :
+ · subst j
+ simp [Finsupp.lapply_apply]
+ · have hne : 2 * j ≠ 2 * i := by omega
+- simp [Finsupp.lapply_apply, Finsupp.single_apply, hji, hne]
++ simp [Finsupp.lapply_apply, hji, hne]
+ exact LinearMap.congr_fun h v
+
+ theorem contract_right_word (i : ℕ) (J : List ℕ) :
+@@ -68,7 +68,7 @@ noncomputable def finiteVector (L : ℕ) (a : Fin L → R) : OneParticle R :=
+
+ @[simp] theorem finiteVector_apply (L : ℕ) (a : Fin L → R) (i : Fin L) :
+ finiteVector R L a i = a i := by
+- simp [finiteVector, Finsupp.finsetSum_apply, Finsupp.smul_apply,
++ simp [finiteVector, Finsupp.finsetSum_apply,
+ Finsupp.single_apply, smul_eq_mul, Fin.val_inj]
+
+ theorem coordinateDual_finiteVector (L : ℕ) (a b : Fin L → R) :
+@@ -81,7 +81,7 @@ theorem coordinateDual_finiteVector (L : ℕ) (a b : Fin L → R) :
+
+ theorem leftParticle_finiteVector (L : ℕ) (a : Fin L → R) :
+ leftParticle R (finiteVector R L a) = TwoColour.leftVector R L a := by
+- simp [finiteVector, TwoColour.leftVector, smul_smul]
++ simp [finiteVector, TwoColour.leftVector]
+
+ theorem contractVector_finiteVector (L : ℕ) (a : Fin L → R) (x : Fock R) :
+ Fock.contractVector R (finiteVector R L a) x =
+@@ -167,7 +167,7 @@ theorem normalList_kernel_coefficient (L : ℕ)
+ rw [normalList_kernel_coevaluation]
+ simp only [map_sum, map_smul, Finsupp.finsetSum_apply, Finsupp.smul_apply,
+ smul_eq_mul, leftInclusion_right_coefficient]
+- simp [Finset.mem_powerset.mp J.property]
++ simp
+
+ theorem matrix_single_eq_normalList (L : ℕ) (A I J : Index L) (c : R) :
+ matrix R L (Pi.single A c) I J = c *
+@@ -216,18 +216,20 @@ theorem state_eq_sum_single (L : ℕ) (v : State R L) :
+ v = ∑ A : Index L, v A • Pi.single A (1 : R) := by
+ classical
+ ext A
+- simp [Pi.single_apply, eq_comm]
++ simp [Pi.single_apply]
+
+ theorem matrix_eq_sum_single (L : ℕ) (v : State R L) :
+ matrix R L v = ∑ A : Index L, v A • matrix R L (Pi.single A (1 : R)) := by
+ change matrixLinear R L v = _
+ conv_lhs => rw [state_eq_sum_single R L v]
+- simp only [map_sum, map_smul] <;> rfl
++ simp only [map_sum, map_smul]
++ rfl
+
+ theorem diagonal_eq_sum_single (L : ℕ) (r : ℤ) (v : State R L) :
+ diagonal R L r v = ∑ A : Index L, v A • diagonal R L r (Pi.single A (1 : R)) := by
+ change diagonalLinear R L r v = _
+ conv_lhs => rw [state_eq_sum_single R L v]
+- simp only [map_sum, map_smul] <;> rfl
++ simp only [map_sum, map_smul]
++ rfl
+
+ end Lemmata.FockCircuits.FiniteIdentity
+diff --git a/lean/Lemmata/FockCircuits/KernelRectangle.lean b/lean/Lemmata/FockCircuits/KernelRectangle.lean
+index df35de4..fbbb36e 100644
+--- a/lean/Lemmata/FockCircuits/KernelRectangle.lean
++++ b/lean/Lemmata/FockCircuits/KernelRectangle.lean
+@@ -37,7 +37,7 @@ def projection (b : Module.Basis E R M) (index : D → E) : M →ₗ[R] M where
+ theorem projection_basis_outside (b : Module.Basis E R M) (index : D → E)
+ {e : E} (he : ∀ d, e ≠ index d) : projection b index (b e) = 0 := by
+ classical
+- simp [projection_apply, Module.Basis.repr_self_apply, he]
++ simp [projection_apply, he]
+
+ @[simp] theorem repr_projection (b : Module.Basis E R M) (index : D → E)
+ (hinj : Function.Injective index) (v : M) (d : D) :
+diff --git a/lean/Lemmata/FockCircuits/KernelScaling.lean b/lean/Lemmata/FockCircuits/KernelScaling.lean
+index e57df90..e2c23a4 100644
+--- a/lean/Lemmata/FockCircuits/KernelScaling.lean
++++ b/lean/Lemmata/FockCircuits/KernelScaling.lean
+@@ -167,7 +167,7 @@ theorem dilation_kernel (L : ℕ) :
+ congr 1
+ simp only [TwoColour.factor, map_add, map_one, map_mul, dilation_left, dilation_right,
+ smul_mul_assoc, mul_smul_comm, smul_smul, ← LaurentPolynomial.T_add,
+- add_neg_cancel, neg_add_cancel, LaurentPolynomial.T_zero, one_smul]
++ neg_add_cancel, LaurentPolynomial.T_zero, one_smul]
+
+ noncomputable def plainSymbol (L m : ℕ) : Fock R :=
+ ExteriorAlgebra.ι R (TwoColour.leftVector R L (fun k => (positiveCoefficient m k : R))) +
+diff --git a/lean/Lemmata/FockCircuits/LaurentExterior.lean b/lean/Lemmata/FockCircuits/LaurentExterior.lean
+index f51fe5c..bb0b7fd 100644
+--- a/lean/Lemmata/FockCircuits/LaurentExterior.lean
++++ b/lean/Lemmata/FockCircuits/LaurentExterior.lean
+@@ -248,7 +248,7 @@ theorem colourBasis_left_singleton (k : ℕ) :
+ rw [ExteriorAlgebra.basis_apply_ofCard _ (Finset.card_singleton _)]
+ simp [ExteriorAlgebra.ιMulti_family, ExteriorAlgebra.ιMulti_succ_apply,
+ Set.powersetCard.ofFinEmbEquiv_symm_apply, colourParticleBasis,
+- Module.Basis.reindex_apply, Finsupp.coe_basisSingleOne,
++ Finsupp.coe_basisSingleOne,
+ Equiv.natSumNatEquivNat_apply, TwoColour.left, Fock.generator]
+
+ theorem colourBasis_right_singleton (k : ℕ) :
+@@ -257,7 +257,7 @@ theorem colourBasis_right_singleton (k : ℕ) :
+ rw [ExteriorAlgebra.basis_apply_ofCard _ (Finset.card_singleton _)]
+ simp [ExteriorAlgebra.ιMulti_family, ExteriorAlgebra.ιMulti_succ_apply,
+ Set.powersetCard.ofFinEmbEquiv_symm_apply, colourParticleBasis,
+- Module.Basis.reindex_apply, Finsupp.coe_basisSingleOne,
++ Finsupp.coe_basisSingleOne,
+ Equiv.natSumNatEquivNat_apply, TwoColour.right, Fock.generator]
+
+ theorem sourceBound_left_monomial (k : ℕ) (a : ℤ) (c : R) (e : ℤ)
+diff --git a/lean/Lemmata/FockCircuits/MatchingResidue.lean b/lean/Lemmata/FockCircuits/MatchingResidue.lean
+index 6801873..4c3dd87 100644
+--- a/lean/Lemmata/FockCircuits/MatchingResidue.lean
++++ b/lean/Lemmata/FockCircuits/MatchingResidue.lean
+@@ -1,7 +1,7 @@
+ module
+
+ public import Lemmata.FockCircuits.ExteriorMatching
+-public import Mathlib.LinearAlgebra.ExteriorAlgebra.BaseChange
++public import Mathlib.RingTheory.TensorProduct.Maps
+ public import Mathlib.LinearAlgebra.TensorProduct.Basis
+ public import Mathlib.Algebra.Polynomial.Coeff
+
+@@ -23,7 +23,7 @@ theorem poleSelector_monomial (s c : R) (d j : ℕ) :
+ if j ≤ d then s ^ (d - j) * c else 0 := by
+ classical
+ simp [poleSelector, Polynomial.lcoeff_apply, Polynomial.coeff_monomial,
+- Finset.mem_range, Nat.lt_succ_iff, smul_eq_mul]
++ Finset.mem_range, smul_eq_mul]
+
+ variable {α : Type*}
+
+@@ -46,27 +46,49 @@ theorem sourceNormalMap_word (x : α → OneParticle R × OneParticle R) (A : Li
+ ExteriorAlgebra.map_apply_ι, Finsupp.linearCombination_single, one_smul]
+ rw [he, Fock.normalSymbol_word]
+
++/-- Extend each source generator to polynomial coefficients, leaving its exterior factor
++over the original ring. -/
++noncomputable def sourceExteriorMap :
++ ExteriorAlgebra (Polynomial R) (Polynomial R ⊗[R] (α →₀ R)) →ₐ[Polynomial R]
++ Polynomial R ⊗[R] ExteriorAlgebra R (α →₀ R) := by
++ let gen := (ExteriorAlgebra.ι R (M := α →₀ R)).baseChange (Polynomial R)
++ have anti (x y : Polynomial R ⊗[R] (α →₀ R)) :
++ gen x * gen y + gen y * gen x = 0 := by
++ induction x using TensorProduct.inductionOn with
++ | tmul p a =>
++ induction y using TensorProduct.inductionOn with
++ | tmul q b =>
++ simp [gen, Algebra.TensorProduct.tmul_mul_tmul, mul_comm q p,
++ ← TensorProduct.tmul_add, ExteriorAlgebra.ι_add_mul_swap]
++ | add y z hy hz =>
++ rw [map_add, mul_add, add_mul, add_add_add_comm, hy, hz, add_zero]
++ | add x z hx hz =>
++ rw [map_add, add_mul, mul_add, add_add_add_comm, hx, hz, add_zero]
++ refine ExteriorAlgebra.lift _ ⟨gen, fun x ↦ ?_⟩
++ induction x using TensorProduct.inductionOn with
++ | tmul p a => simp [gen, Algebra.TensorProduct.tmul_mul_tmul]
++ | add x y hx hy =>
++ rw [map_add, mul_add, add_mul, add_mul, hx, hy, zero_add, add_zero, anti]
++
+ noncomputable def residueMap (s : R) (d : ℕ) (x : α → OneParticle R × OneParticle R) :
+ ExteriorAlgebra (Polynomial R) (Polynomial R ⊗[R] (α →₀ R)) →ₗ[R]
+ Module.End R (Fock R) :=
+ (TensorProduct.lid R (Module.End R (Fock R))).toLinearMap.comp
+ ((TensorProduct.map (poleSelector R s d) (sourceNormalMap R x)).comp
+ (LinearMap.restrictScalars R
+- (ExteriorAlgebra.baseChangeEquiv R (α →₀ R) (Polynomial R)).symm.toLinearMap))
++ (sourceExteriorMap R (α := α)).toLinearMap))
+
+ noncomputable def extendedSource (i : α) : Polynomial R ⊗[R] (α →₀ R) :=
+ (1 : Polynomial R) ⊗ₜ[R] Finsupp.single i 1
+
+ theorem baseChange_generator (i : α) :
+- (ExteriorAlgebra.baseChangeEquiv R (α →₀ R) (Polynomial R)).symm
++ (sourceExteriorMap R (α := α))
+ (ExteriorAlgebra.ι (Polynomial R) (extendedSource R i)) =
+ (1 : Polynomial R) ⊗ₜ[R] ExteriorAlgebra.ι R (Finsupp.single i 1) := by
+- simpa only [extendedSource] using
+- ExteriorAlgebra.baseChangeEquiv_symm_apply R (α →₀ R) (Polynomial R)
+- (1 : Polynomial R) (Finsupp.single i 1)
++ simp [sourceExteriorMap, extendedSource]
+
+ theorem baseChange_word (A : List α) :
+- (ExteriorAlgebra.baseChangeEquiv R (α →₀ R) (Polynomial R)).symm
++ (sourceExteriorMap R (α := α))
+ (word (Polynomial R) (extendedSource R) A) =
+ (1 : Polynomial R) ⊗ₜ[R] word R (fun i => Finsupp.single i 1) A := by
+ induction A with
+@@ -81,7 +103,7 @@ theorem residueMap_smul_word (s : R) (d : ℕ)
+ poleSelector R s d p • Fock.normalList R (A.map x) := by
+ unfold residueMap
+ simp only [LinearMap.comp_apply, LinearMap.restrictScalars_apply,
+- AlgEquiv.toLinearMap_apply, map_smul, baseChange_word,
++ AlgHom.toLinearMap_apply, map_smul, baseChange_word,
+ TensorProduct.smul_tmul', smul_eq_mul, mul_one, TensorProduct.map_tmul,
+ sourceNormalMap_word]
+ rfl
+diff --git a/lean/Lemmata/FockCircuits/NormalSymbol.lean b/lean/Lemmata/FockCircuits/NormalSymbol.lean
+index b063fbb..b1414f6 100644
+--- a/lean/Lemmata/FockCircuits/NormalSymbol.lean
++++ b/lean/Lemmata/FockCircuits/NormalSymbol.lean
+@@ -118,17 +118,13 @@ theorem normalPair_word (L : List (OneParticle R × OneParticle R)) :
+ rfl
+ · apply LinearMap.ext
+ intro x
+- have hs : (-1 : R) ^ L.length * (-1 : R) ^ L.length = 1 := by
+- rw [← mul_pow]
+- simp
+ change -createVector R a.1 (((-1 : R) ^ L.length) • normalList R L x) -
+ normalList R L (contractVector R a.2 x) = _
+ simp only [normalList_cons, List.length_cons, LinearMap.smul_apply,
+- map_smul, smul_add, smul_smul, pow_succ, mul_neg, mul_one, neg_smul,
+- hs, one_smul]
++ map_smul, smul_add, smul_smul, pow_succ, mul_neg, mul_one, neg_smul]
+ match_scalars <;>
+ rcases neg_one_pow_eq_or R L.length with hsign | hsign <;>
+- simp [hsign] <;> ring
++ simp [hsign]
+
+ theorem normalSymbol_word (L : List (OneParticle R × OneParticle R)) :
+ normalSymbol R (L.map (ExteriorAlgebra.ι R)).prod = normalList R L := by
+diff --git a/lean/Lemmata/FockCircuits/PascalShears.lean b/lean/Lemmata/FockCircuits/PascalShears.lean
+index 6198a4d..d6b5d52 100644
+--- a/lean/Lemmata/FockCircuits/PascalShears.lean
++++ b/lean/Lemmata/FockCircuits/PascalShears.lean
+@@ -62,7 +62,7 @@ theorem raisingStage_single (L m : ℕ) :
+ (if m < L then (L.choose m : R) else 0) • Finsupp.single L 1 := by
+ rw [raisingStage_apply]
+ congr 2
+- simp [Finsupp.single_apply, eq_comm]
++ simp [Finsupp.single_apply]
+
+ noncomputable def finitePascal (L : ℕ) : OneParticle R →ₗ[R] OneParticle R :=
+ Finsupp.linearCombination R fun m =>
+@@ -80,7 +80,7 @@ theorem finitePascal_single_apply (L m k : ℕ) :
+ if m < L then (if k < L then (k.choose m : R) else 0)
+ else if m = k then 1 else 0 := by
+ rw [finitePascal_single]
+- split_ifs <;> simp_all [Finsupp.finsetSum_apply, Finsupp.smul_apply,
++ split_ifs <;> simp_all [Finsupp.finsetSum_apply,
+ Finsupp.single_apply, smul_eq_mul, eq_comm]
+
+ theorem finitePascal_succ (L : ℕ) :
+@@ -96,19 +96,22 @@ theorem finitePascal_succ (L : ℕ) :
+ finitePascal_single_apply]
+ by_cases hm : m < L
+ · by_cases hk : k < L
+- · simp [hm, hk, show m < L + 1 by omega, show L ≠ k by omega] <;> omega
++ · simp [hm, hk, show m < L + 1 by omega, show L ≠ k by omega]
++ omega
+ · by_cases hkl : k = L
+ · subst k
+- simp [hm] <;> omega
+- · simp [hm, hk, hkl, show ¬ k < L + 1 by omega, Ne.symm hkl] <;> omega
++ simp [hm]
++ omega
++ · simp [hm, hk, show ¬ k < L + 1 by omega, Ne.symm hkl]
++ omega
+ · by_cases hml : m = L
+ · subst m
+ by_cases hk : k < L
+- · simp [hk, Nat.choose_eq_zero_of_lt hk, show L ≠ k by omega]
++ · simp [Nat.choose_eq_zero_of_lt hk, show L ≠ k by omega]
+ · by_cases hkl : k = L
+ · subst k; simp
+- · simp [hk, hkl, Ne.symm hkl, show ¬ k < L + 1 by omega]
+- · simp [hm, hml, show ¬ m < L + 1 by omega]
++ · simp [Ne.symm hkl, show ¬ k < L + 1 by omega]
++ · simp [hm, show ¬ m < L + 1 by omega]
+
+ noncomputable def raisingSteps : ℕ → List (ℕ × ℕ × R)
+ | 0 => []
+diff --git a/lean/Lemmata/FockCircuits/Shear.lean b/lean/Lemmata/FockCircuits/Shear.lean
+index 968c544..177b285 100644
+--- a/lean/Lemmata/FockCircuits/Shear.lean
++++ b/lean/Lemmata/FockCircuits/Shear.lean
+@@ -19,7 +19,7 @@ theorem shearLinear_apply (a : R) (i j : ℕ) (v : OneParticle R) :
+ ext k
+ by_cases hj : j = k <;>
+ simp [shearLinear, Finsupp.lsingle_apply, Finsupp.lapply_apply,
+- Finsupp.single_apply, hj, smul_eq_mul, mul_assoc]
++ hj, smul_eq_mul]
+
+ noncomputable def shear (a : R) (i j : ℕ) : Fock R →ₐ[R] Fock R :=
+ ExteriorAlgebra.map (shearLinear R a i j)
+@@ -49,9 +49,9 @@ theorem shear_apply (a : R) (i j : ℕ) (x : Fock R) :
+ apply eq_neg_iff_add_eq_zero.mpr
+ exact ExteriorAlgebra.ι_add_mul_swap (R := R) (Finsupp.single j 1) v
+ rw [map_mul, shear_ι, ih, hd]
+- simp only [add_mul, mul_add, mul_sub, smul_add, smul_sub,
++ simp only [add_mul, mul_add, mul_sub, smul_sub,
+ smul_mul_assoc, mul_smul_comm, smul_smul, ← mul_assoc,
+- generator_sq, zero_mul, smul_zero, add_zero, hc, neg_mul, smul_neg]
++ generator_sq, smul_zero, add_zero, hc, neg_mul, smul_neg]
+ module
+
+ theorem doubledEnergy_replace {i j : ℕ} {I : Finset ℕ}
+diff --git a/lean/Lemmata/FockCircuits/SignedKernel.lean b/lean/Lemmata/FockCircuits/SignedKernel.lean
+index 6fbab9b..4974df8 100644
+--- a/lean/Lemmata/FockCircuits/SignedKernel.lean
++++ b/lean/Lemmata/FockCircuits/SignedKernel.lean
+@@ -575,7 +575,7 @@ theorem reverse_common_coefficient {A B : List ℕ} {t : Matching.Term SourceInd
+ obtain ⟨m, hm, hj⟩ := List.mem_map.mp h.2
+ have hp' : p = (Sum.inr n, Sum.inl m) := Prod.ext hi.symm hj.symm
+ rw [hp']
+- simp [Matching.crossGamma, orientPair, derivative, pairConstant]
++ simp [Matching.crossGamma, orientPair, pairConstant]
+
+ theorem constantTerm_weighted_C (c : R) (s p v : LaurentPolynomial R) :
+ (s * (LaurentPolynomial.C c * p) * v).coeff 0 = c * (s * p * v).coeff 0 := by
+@@ -606,7 +606,7 @@ theorem forward_term_constantTerm (L : ℕ) {A B : List ℕ} {t : Matching.Term
+ Finsupp.zero_apply]
+ · have hp := forward_partial_pole ht hempty d hdegree
+ rw [actualTerm, forward_matching_coefficient R L ht,
+- constantTerm_weighted_C, commonTerm, if_pos hp,
++ constantTerm_weighted_C, commonTerm, ite_eq_left hp,
+ forward_common_coefficient R ht, constantTerm_weighted_C]
+ rw [forward_term_replacement R L ht hempty d hdegree hw I J hIJ hcut]
+
+@@ -634,9 +634,9 @@ theorem reverse_term_constantTerm (L : ℕ) {A B : List ℕ} {t : Matching.Term
+ Finsupp.zero_apply, reverseScalar, hempty, ite_true, zero_add]
+ · have hp := reverse_partial_pole ht hempty d hdegree
+ rw [actualTerm, reverse_matching_coefficient R L ht,
+- constantTerm_weighted_C, commonTerm, if_pos hp,
++ constantTerm_weighted_C, commonTerm, ite_eq_left hp,
+ reverse_common_coefficient R ht, constantTerm_weighted_C,
+- reverseScalar, if_neg hempty, add_zero]
++ reverseScalar, ite_eq_right hempty, add_zero]
+ rw [reverse_term_replacement R L ht hempty d hdegree hw I J hIJ hcut]
+
+ noncomputable def colourEntry (I J : Finset ℕ) :
+@@ -825,7 +825,7 @@ theorem vacuumSource_left_list (L : ℕ) (A : Index L) :
+ theorem vacuumSource_right_vacuum (L : ℕ) (B : Index L) :
+ Fock.normalList R ((B.val.sort.map Sum.inr).map (vacuumSource R L)) 1 = Fock.basis R B.val := by
+ rw [Fock.normalList_one, Fock.basis_eq_sorted_prod]
+- simp only [List.map_map, Function.comp_def, vacuumSource, Fock.generator]
++ simp only [List.map_map, Function.comp_def, vacuumSource]
+ rfl
+
+ theorem vacuum_matching_coefficient (L : ℕ) (A B : Index L) {t : Matching.Term SourceIndex}
+@@ -885,7 +885,7 @@ theorem reverse_gamma_coefficient {A B : List ℕ} {t : Matching.Term SourceInde
+ obtain ⟨m, hm, hj⟩ := List.mem_map.mp h.2
+ have hp' : p = (Sum.inr n, Sum.inl m) := Prod.ext hi.symm hj.symm
+ rw [hp']
+- simp only [Matching.crossGamma, Function.comp_def, orientPair, derivative]
++ simp only [Matching.crossGamma, Function.comp_def, orientPair]
+
+ theorem neg_contraction_product (P : List (ℕ × ℕ)) :
+ (P.map fun p => -(Fock.contractionCoefficient p.1 p.2 : R)).prod =
+@@ -916,7 +916,7 @@ theorem reverse_fullMatchingSum (A B : List ℕ) (d : ℕ)
+ intro t ht
+ by_cases hempty : t.remaining = []
+ · have hp := reverse_full_pole ht hempty d hdegree
+- rw [if_pos hempty, if_pos hempty, reverse_gamma_coefficient R ht,
++ rw [ite_eq_left hempty, ite_eq_left hempty, reverse_gamma_coefficient R ht,
+ neg_contraction_product, hp]
+ ring
+ · simp only [hempty, ite_false, mul_zero]
+@@ -1019,7 +1019,7 @@ theorem normalLists_kernel_coefficient {L : ℕ}
+ simp only [map_sum, map_smul, normalList_leftInclusion_mul_right,
+ Finsupp.finsetSum_apply, Finsupp.smul_apply, smul_eq_mul,
+ leftInclusion_right_coefficient]
+- simp [Finset.mem_powerset.mp J.property]
++ simp
+
+ theorem normalMatrix_scaled {L : ℕ} (A I J : Index L) :
+ normalMatrix (LaurentPolynomial R) L
+diff --git a/lean/Lemmata/FockCircuits/SparseCircuit.lean b/lean/Lemmata/FockCircuits/SparseCircuit.lean
+index 8117294..cb87737 100644
+--- a/lean/Lemmata/FockCircuits/SparseCircuit.lean
++++ b/lean/Lemmata/FockCircuits/SparseCircuit.lean
+@@ -113,7 +113,7 @@ theorem scatter_realizes_linearMap [CommRing R] [Fintype D] [DecidableEq D]
+ rw [Finset.sum_comm]
+ apply Finset.sum_congr rfl
+ intro j hj
+- simp [ite_smul, eq_comm]
++ simp [ite_smul]
+
+ theorem scatter_matrix [CommSemiring R] [Fintype D] [DecidableEq D]
+ {A : Type*} [Semiring A] [Algebra R A]
+@@ -135,8 +135,8 @@ theorem scatter_matrix [CommSemiring R] [Fintype D] [DecidableEq D]
+ · simp only [ite_eq_left hji, ite_eq_right hit, map_one, map_zero,
+ mul_one, mul_zero, add_zero]
+ · by_cases hit : i = target j
+- · simp only [ite_eq_right hji, ite_eq_left hit, map_one, map_zero,
+- mul_one, mul_zero, zero_add]
++ · simp only [ite_eq_right hji, ite_eq_left hit, map_zero,
++ mul_zero, zero_add]
+ · simp only [ite_eq_right hji, ite_eq_right hit, map_zero, mul_zero, add_zero]
+ simp_rw [ht]
+ rw [Finset.sum_add_distrib, eval_scatter]
+diff --git a/lean/Lemmata/FockCircuits/Wick.lean b/lean/Lemmata/FockCircuits/Wick.lean
+index f68d1ab..45087f8 100644
+--- a/lean/Lemmata/FockCircuits/Wick.lean
++++ b/lean/Lemmata/FockCircuits/Wick.lean
+@@ -113,7 +113,7 @@ theorem wickDerivative_eq_sum (v : OneParticle R)
+ congrArg (fun n : ℕ => (-1 : R) ^ n) hlen.symm
+ _ = _ := by rw [pow_succ]; simp
+ rw [hs, normalList_cons]
+- simp only [Fin.getElem_fin, Fin.val_succ, List.getElem_cons_succ,
++ simp only [Fin.getElem_fin,
+ map_smul, smul_add, smul_smul, pow_succ]
+ module
+
diff --git a/overview.pdf b/overview.pdf
index 3734b17480..95a77404a1 100644
Binary files a/overview.pdf and b/overview.pdf differ
diff --git a/overview.tex b/overview.tex
index 57f6f5aa08..dcb62b7524 100644
--- a/overview.tex
+++ b/overview.tex
@@ -9,7 +9,7 @@
\usepackage{fancyhdr,lastpage,xcolor,ragged2e,needspace}
\definecolor{muted}{gray}{0.38}
\definecolor{linkink}{HTML}{275B59}
-\usepackage[unicode,colorlinks=true,linkcolor=linkink,urlcolor=linkink,pdfauthor={OpenAI},pdftitle={OpenAI Research Catalog},pdfsubject={373 result families in 721 manuscripts}]{hyperref}
+\usepackage[unicode,colorlinks=true,linkcolor=linkink,urlcolor=linkink,pdfauthor={OpenAI},pdftitle={OpenAI Research Catalog},pdfsubject={374 result families in 722 manuscripts}]{hyperref}
\setlength{\parindent}{0pt}
\setlength{\parskip}{0pt}
\setlength{\emergencystretch}{1.2em}
@@ -20,7 +20,7 @@
\fancyhf{}
\fancyhead[L]{\footnotesize\scshape OpenAI Research Catalog}
\fancyhead[R]{\footnotesize\scshape OpenAI}
-\fancyfoot[L]{\footnotesize\color{muted}373 result families\enspace\textperiodcentered\enspace721 manuscripts}
+\fancyfoot[L]{\footnotesize\color{muted}374 result families\enspace\textperiodcentered\enspace722 manuscripts}
\fancyfoot[R]{\footnotesize\thepage\, /\,\pageref*{LastPage}}
\renewcommand{\headrulewidth}{0.3pt}
\renewcommand{\footrulewidth}{0pt}
@@ -46,7 +46,7 @@
\vspace{5pt}
{\LARGE\bfseries OpenAI Research Catalog\par}
\vspace{4pt}
-{\small 373 result families in 721 manuscripts\hfill October 26, 2026\par}
+{\small 374 result families in 722 manuscripts\hfill November 23, 2026\par}
\vspace{7pt}
{\small An overview of the \href{https://github.com/openai/math}{manuscript collection}. Results are grouped by subject; entry numbers follow the catalog order and do not indicate a ranking. PDF links follow each summary.\par}
\vspace{8pt}\hrule height 0.35pt\vspace{5pt}
@@ -362,6 +362,8 @@
\resultentry{378}{Disproof of the Exponential Time Hypothesis}{For every fixed $k\ge2$, a deterministic algorithm counts the satisfying assignments of a $k$-CNF with $n$ variables and $m$ clauses in time $(n+m)^{O_k(1)}2^{n/(\log n)^{1/2+o(1)}}$. This yields superlinear circuit lower bounds for a language in $\mathsf{E}^{\mathsf{NP}}$ on infinitely many input lengths.}{\href{https://github.com/openai/math/blob/main/preprints/The-Exponential-Time-Hypothesis-is-False-October-25-2026/paper.pdf}{The Exponential Time Hypothesis is False}}
+\resultentry{379}{Separation of VP and VNP over every field}{An explicit VNP family requires border arithmetic circuits of size at least $\exp(\Omega((\log n)^{5/4}))$ over every field. The same bound holds for the directed Hamiltonian cycle polynomial over every field and for the permanent outside characteristic two.}{\href{https://github.com/openai/math/blob/main/preprints/VP-and-VNP-are-different-November-23-2026/paper.pdf}{VP and VNP are different}}
+
\cataloguesection{Dynamical systems and ergodic theory}{12}
\resultentry{143}{Uniform limit-cycle bounds in Hilbert's sixteenth problem}{Resolves the uniform boundedness assertion in Hilbert's sixteenth problem: the number of isolated periodic orbits of a real planar polynomial vector field is bounded by a finite constant depending only on its degree. For classical quintic Li\'enard systems, the exact maximum is two limit cycles.}{\href{https://github.com/openai/math/blob/main/preprints/uniform-bounds-for-planar-polynomial-limit-cycles-September-24-2026/uniform-bounds-for-planar-polynomial-limit-cycles-September-24-2026.pdf}{Uniform limit-cycle bounds}\enspace\textperiodcentered\enspace\href{https://github.com/openai/math/blob/main/preprints/two-limit-cycles-for-quintic-lienard-systems-September-24-2026/two-limit-cycles-for-quintic-lienard-systems-September-24-2026.pdf}{Quintic Liénard limit cycles}}
diff --git a/preprints/VP-and-VNP-are-different-November-23-2026/README.md b/preprints/VP-and-VNP-are-different-November-23-2026/README.md
new file mode 100644
index 0000000000..d1803d08a4
--- /dev/null
+++ b/preprints/VP-and-VNP-are-different-November-23-2026/README.md
@@ -0,0 +1,33 @@
+# [VP and VNP are different](paper.pdf)
+
+OpenAI · November 23, 2026 edition
+
+Theorem 1.1 gives a border arithmetic circuit size lower bound of
+$\exp(\Omega((\log n)^{5/4}))$ for an explicit VNP family over every field.
+Corollary 1.2 transfers the bound to the directed Hamiltonian cycle polynomial
+over every field and to the permanent outside characteristic two.
+The [Lean proof of the exact VP–VNP separation](../../lean/OAI/Computability/VPVNP/ClassSeparation.lean)
+is also available in this repository.
+
+## Manuscript files
+
+The [LaTeX source](build/Paper.tex) contains the full proof, with
+[TikZ figures](build/figures/) and an editable [bibliography](build/references.tex).
+To regenerate the [PDF](paper.pdf) with Tectonic, run these commands from this directory.
+
+```sh
+cd build
+tectonic Paper.tex
+cp Paper.pdf ../paper.pdf
+```
+
+## Citation
+
+```bibtex
+@misc{OAI:VP-and-VNP-are-different-November-23-2026,
+ author = {{OpenAI}},
+ title = {{VP and VNP are different}},
+ year = {2026},
+ note = {November 23 edition}
+}
+```
diff --git a/preprints/VP-and-VNP-are-different-November-23-2026/build/Paper.tex b/preprints/VP-and-VNP-are-different-November-23-2026/build/Paper.tex
new file mode 100644
index 0000000000..7e83dc86fb
--- /dev/null
+++ b/preprints/VP-and-VNP-are-different-November-23-2026/build/Paper.tex
@@ -0,0 +1,1317 @@
+\documentclass[11pt,letterpaper]{article}
+\usepackage[T1]{fontenc}
+\usepackage{lmodern}
+\usepackage[margin=1.15in]{geometry}
+\usepackage{amsmath,amssymb,amsthm}
+\usepackage{tikz}
+\usepackage[hidelinks]{hyperref}
+\hypersetup{pdftitle={VP and VNP are different},pdfauthor={OpenAI}}
+
+\newtheorem{theorem}{Theorem}[section]
+\newtheorem{corollary}[theorem]{Corollary}
+\newtheorem{lemma}[theorem]{Lemma}
+\newtheorem{proposition}[theorem]{Proposition}
+\theoremstyle{definition}
+\newtheorem{definition}[theorem]{Definition}
+\numberwithin{equation}{section}
+\DeclareMathOperator{\poly}{poly}
+\DeclareMathOperator{\Res}{Res}
+\DeclareMathOperator{\Tr}{Tr}
+\setlength{\emergencystretch}{2em}
+\setcounter{tocdepth}{1}
+
+\title{VP and VNP are different}
+\author{OpenAI}
+\date{}
+
+\begin{document}
+\maketitle
+\begin{abstract}
+We prove that VP differs from VNP over every field. The lower bound holds for
+border circuits and is superpolynomial, of the form $\exp(\Omega((\log n)^{5/4}))$. In particular
+it applies to the permanent outside characteristic two. The proof trades two kinds of
+hardness against one another: the rigidity of tensor networks priced in Euclidean space,
+and the ability to diagonalize even against degenerating nonuniform circuits by replaying
+their computations inside a wire budget.
+\end{abstract}
+
+\tableofcontents
+\clearpage
+
+\section{Introduction}\label{sec:introduction}
+
+A polynomial can have an enormous number of terms and still be easy to compute. But
+suppose that the only compression we know is the following one: the terms (with repetitions
+allowed) can be described locally, or checked quickly given an index. Does this suffice?
+
+Valiant's completeness theory \cite{Valiant,ValiantProjections} gave us a formal version of this question and
+some of the most arresting concrete versions as well. $\mathrm{VP}$ over a field consists of families of
+multivariate polynomials of polynomial degree in polynomially many variables, computable
+by polynomial size arithmetic circuits; $\mathrm{VNP}$ allows, on top, summing over all settings of
+polynomially many auxiliary inputs to zero and one. Here and throughout, size and degree
+bounds for classes are polynomial in the family index, circuits are nonuniform, computing
+with free field constants and binary additions, subtractions and multiplications, and the
+computation is of formal polynomials. No assumptions are made about degrees along the
+way. For background and formulations see e.g. \cite{BCS,Burgisser,BC2024,ShpilkaYehudayoff,BLMW}.
+
+We give a negative answer. In fact we prove the geometric strengthening (cf. \cite{ApproxFactors}): $\mathrm{VNP}$
+is not contained even in border $\mathrm{VP}$. By this we mean that we may take coefficient-wise
+limits of circuits, in the sense of Zariski closure over the algebraic closure. To give the result
+a quantitative form, take the family
+\[
+ f_n(Z) = \sum_{x\in\{0,1\}^n} c_x Z_{1,x_1}\cdots Z_{n,x_n}.
+\]
+Here $c_x$ counts accepting paths of an ordinary universal machine, running the program
+encoded by a self-delimiting prefix of $x$, with $x$ itself as input. For definiteness permit
+up to $n^{1000}$ bit steps per path (binary choices; reject malformed or over-clock paths);
+any convenient efficient Turing machine conventions will do, with polynomial simulation
+overheads comfortably inside that clock for the fixed programs used below.
+
+\begin{theorem}[separation]\label{thm:separation}
+Over every field, border circuits for $f_n$ require $\exp(\Omega((\log n)^{5/4}))$
+gates. This is so even measuring approximation in degree $n$ only.
+\end{theorem}
+
+In particular, this concerns an integral family with particularly simple summands. The
+$\mathrm{VNP}$ upper bound is standard: use auxiliary Boolean variables for $x$, branch choices (forcing
+unused ones to zero), and an accepting Cook--Levin tableau \cite{Cook71,Levin} with unique auxiliaries.
+The product of local indicator polynomials and $((1-x_i)Z_{i,0}+x_i Z_{i,1})_{1\le i\le n}$ (multiply these
+factors also) is in $\mathrm{VP}$.
+
+By the classical projection completeness theorems \cite{Valiant,ValiantProjections,Burgisser,BC2024}, we have:
+
+\begin{corollary}\label{thm:projections}
+The same lower bound in terms of matrix order holds for the directed
+Hamiltonian cycle polynomial, and (except in characteristic two) the permanent. It holds
+also for determinantal complexity (minimum order of a determinant of affine linear forms),
+including border determinantal complexity. In particular for all sufficiently large $m$ and
+\[
+ m\le N\le \exp(c(\log m)^{5/4})
+\]
+with sufficiently small $c>0$, the degree-$N$ padded $m\times m$ permanent in characteristic zero is
+excluded from the determinant orbit closure.
+\end{corollary}
+
+\begin{proof}
+When only the degree in question is approximated, first homogenize to obtain exactly
+that degree, at polynomial cost in the size and degree. Polynomial projections preserve
+border upper bounds by continuity. Bounds at polynomially sampled dimensions give bounds
+of this form at all large dimensions by standard padding (to force extra HC vertices subdivide
+a vertex through a mandatory chain). Determinant has polynomial size over every field \cite{MahajanVinay}.
+For orbit closure (affine cone, allowing extra ambient variables if needed), use that the orbit
+consists of determinants of linear matrices and that padding by a power of a new variable
+can be undone by specialization. Even padding by an existing variable works: split into
+components by degree in that variable, discard too-low degrees and undo the shift, a linear
+operation costing polynomial overhead.
+\end{proof}
+
+\paragraph{Where this sits.}
+We mean separation at the polynomial scale; there are harder quasipolynomial questions (notice the
+formulation already in \cite{Valiant}; see also \cite{MulmuleySohoni2008}), closely connected to
+formula complexity by depth reduction \cite{Hyafil,VSBR}. Nor is this a separation for decision problems
+in the Boolean model. But even the polynomial determinantal projection question by itself
+has long been a benchmark open problem (e.g. \cite{AviICM}), and in orbit-closure form central to
+geometric complexity theory \cite{MulmuleySohoni,MulmuleySohoni2008,BLMW,BIPnooccurrence}. We give
+no explicit module of equations or
+representation-theoretic obstruction; occurrence obstructions are known not to work for
+standard GCT with large polynomial padding \cite{BIPnooccurrence}. Previous advances on determinantal
+lower bounds include quadratic bounds \cite{MignonRessayre,CaiChenLi,LandsbergManivelRessayre} and,
+in recent preprints, cubic border
+bounds \cite{CubOAI,Sheshadri287} (see also the polar methods of \cite{SheshadriBorder2026} and
+\cite{KumarVolk2026}). For unrestricted circuits think
+of the $n\log d$ scale: gradient and degree give such lower bounds even on simple degree-$d$
+polynomials in $n$ variables \cite{BaurStrassen,StrassenBezout}; see also the recent treatment and
+permanent results in
+\cite{TenAdvances}.
+
+There is a magnificent history of large bounds after changing the problem slightly.
+Monotonicity can force exponential bounds \cite{Val80,JerrumSnir}; symmetry too can come at a steep price
+\cite{DawarWilsenach}. The multilinear world has superpolynomial bounds on formulas even for determinant
+\cite{RazMultilinear}. Ranks of partial derivative matrices and relatives \cite{Nisan,NW97pd,CKW}
+are ubiquitous; but
+circuits give us low ranks across \emph{varying} cuts, which is quite different from a single matrix (cf.
+the discrepancy and partition issues in \cite{Raz06,RSY08,AKV20,BFLY26,CKSS24}). There is the depth-four program
+\cite{AgrawalVinay,Koiran2012,Tavenas2013} with formidable progress via shifted partials and beyond,
+attaining even the
+square-root scale in the exponent for homogeneous depth four, but with constants critical for
+unrestricted circuit implications \cite{Kayal2012,GKKS14,KSS13regular,KLSS14,KumarSaraf2014}; see
+\cite{DEP5OAI} for recent progress at depth five.
+And there are now even superpolynomial bounds at arbitrary \emph{constant} depth
+\cite{LSTconst,BDS24,Forbes2024}. For
+more perspectives, including the power and possible limitations of proofs by low-complexity
+equations, see \cite{ShpilkaYehudayoff,KSsurvey,Gro15,GKSS17,FSV18}. Here the approach will be
+different, although varying cuts
+play an essential role.
+
+\paragraph{Strategy.}
+Call a binary index in a tensor contraction a wire. Imagine placing the tensors in
+Euclidean space, and charging length for each wire. We isolate a \emph{strict shortening} hypothesis.
+Informally: is there some dimension and some fixed local tensor identity that communicates
+along bundles of orthogonal diameters more cheaply than literally laying the wires? We can
+allow alternatives (send a selector from the center to the terminals and sum).
+
+\begin{itemize}
+\item Without strict shortening, there is a direct, short proof. On a graph with independent
+bundles along the edges, any balanced cut saving enough rank would allow wire to
+be saved: reroute through a hub displaced a little in the direction of the resultant of
+the cut wires. Even cuts chosen differently in different terms would work. This leads
+quickly to Theorem~\ref{thm:separation}.
+\item With strict shortening, we can save wire in computations. The point of saving is
+to \emph{diagonalize}. Think of a coefficient of $f_n$ as a programmable processor. Against a
+description of a circuit, compute this very coefficient, plus one. Now that sounds like
+diagonalization against a linear bound at best. Instead take a contraction with very
+many programmed processors in it; in its live execution it must be able to replay this
+entire contraction with the hypothetical small circuit substituted for every processor.
+It gets some important economies. First, the same circuit services all the queries: it
+is possible to batch, charging essentially only degree per query since we compute by
+counting and may follow just one parse tree. (For other kinds of batching see e.g.
+\cite{Uhlig,Wbatch}.) And second, this computation can itself be performed as a contraction, with
+RAM transcripts guessed and checked by sorting. So we can keep shortening its wires
+so as to fit the processors' communication budget.
+\item There are real difficulties with this program. Wire saving in big networks must be
+made to \emph{iterate} (compare gap amplification in undirected network coding \cite{BGS}, though
+here our alphabet may be contracted by summation and we even sum over wirings).
+We build ribbon-like switching hosts: locally Euclidean along many axes, with vast
+routing room; the cost accounting will pay even for concentration of traffic. We will
+also need a final constant-factor squeeze, adapting the grid method of the recent \cite{Anthropic3SAT}
+on counting SAT (cf. also \cite{Khoruzhii,ETHfalse}). And how can one learn, let alone distribute, a
+circuit using arbitrary constants, possibly only working in a limit? We avoid that:
+after collecting powers of all circuit parameters, insert certain universal weights. We
+realize the limit as an eigenvector law for operators whose \emph{entries} can be replayed by
+counting with very modest advice. Cartier operators in positive characteristic are key
+to this step, even if we began in characteristic zero.
+\end{itemize}
+
+Thus the proof is not just a rigidity argument and not just an algorithmic lower bound
+(for a different use of algorithms and diagonalization in lower bounds see \cite{Williams13}): if geometry
+fails to prove hardness directly, its failure powers a hierarchy theorem. We organize the
+proof around that hinge. After making shortening precise and giving the direct bound,
+we state and reduce the contrasting \emph{stretch theorem} (\S\ref{sec:stretch})---stretch because a single fixed
+saving will boost the lower bound to stretched exponential. Its reductions go to a boundary
+lemma (\S\ref{sec:slicing}) and a replay lemma; the rest of the core argument constructs the replay. One
+can also proceed directly to that construction (using the one-dimensional, exact version of
+the boundary lemma for motivation), returning to \S\ref{sec:slicing} at the end.
+
+\section{The hinge}\label{sec:hinge}
+
+A bit tensor network has arbitrary local tables. Joining ports sums over a shared bit; multiply
+all local entries and sum over assignments (external ports left as arguments). A width-$b$
+cable joins $b$ pairs of ports. Place nodes in a metric space: charge width times distance for
+each cable, including any run up to an external terminal. Thus local reblocking or other
+computation at the same point costs nothing.
+
+\begin{definition}\label{thm:shortening}
+In dimension $D\ge 2$, let $C_{D,m}$ consist of width-$m$ cables on the $D$ coordinate
+diameters of the Euclidean unit ball ($m\ge 1$). That is, the tensor at the $2D$ terminals testing
+equality across all diameters. A strict shortening is a finite sum identity for this tensor over
+a field, using $A$ networks in the ball each of cost $\le w$ where
+\[
+ w + 2D\log_2 A < 2Dm.
+\]
+\end{definition}
+
+We take log base two throughout. We can equally well begin with membership in
+the closure of such sums (fixed finite layouts, variable tables, algebraically closed field).
+Indeed the $t$-th tensor power lies in the span of $t$-th powers of actual sums since this span
+is closed. It requires only polynomially many (in $t$, by counting monomials in the fixed
+ambient dimension). Thus at width $tm$ we get an exact sum with $\poly(t)A^t$ terms of cost
+$\le tw$. Taking powers we can and will even pay for rounding up the log. Positions can be
+made rational; the saving is strict. Also existence in any characteristic is unchanged among
+algebraically closed fields there, by the Nullstellensatz.
+
+Here is how we actually use one. For $j$ juxtaposed crossings, sum over profiles $(j_1,\ldots,j_A)$
+of multiplicities, one layout for each. \emph{Within} a layout, send a word of $j$ selectors (constrained
+to have that profile) from the origin to all terminals; sum on it. Copies of each term operate
+on assigned terminal blocks in order of occurrence; inner nodes can use separate cables per
+term, with widths proportional to $j_a$, not needing to see the selectors. This realizes the
+tensor exactly, each layout saving a fixed fraction of length, and with a bounded number
+of cable descriptions (widths $O(j)$). Local operations are word parsing, reblocking, and
+applying constant tables.
+
+\subsection{If wire cannot be saved}
+
+Suppose no strict shortening works (any $D,m$) over an algebraically closed field. Take a
+bounded-degree expander on $d\asymp a\sqrt{\log n}$ vertices, so every balanced cut (sides of size at
+least $d/3$) has at least $\gamma d$ edges across it. Here $\gamma >0$ is absolute, $a>0$ a small constant to
+choose (for expanders see \cite{HLW}). Use bundles of $m=\lfloor c\log n\rfloor$ bits ($c>0$ sufficiently small) on
+each edge, and a variable for each vertex and setting of its incident bits. The polynomial $g$ is
+the partition function: multiply one variable per vertex and sum over consistent assignments.
+With the variables as slots grouped by vertex, its coefficient tensor consists simply of wires
+(for context on graph contractions see e.g. \cite{MarkovShi}).
+
+This is an ordinary projection of $f_n$: the bits $x$ include one-hot choices of vertex variables,
+checked for consistency by the deterministic program in a forced prefix (also including graph
+data, rejecting nonzero padding). Insert each variable for the corresponding ``one'' weight;
+there is room since the number of variables is at most $n^{1/2}$ with $c$ small. If $f_n$ has border
+cost $s$ as in Theorem~\ref{thm:separation}, then (first homogenizing) $g$ has full border cost $\poly(n+s)$.
+
+Consequently its coefficient tensor is in the closure of sums with one term per balanced
+cut, of rank across that cut bounded by
+\[
+ 2^{O(d)}\poly(n+s).
+\]
+Indeed apply the usual balanced-product decomposition to the set-multilinear component of
+actual circuit outputs. Keep components multilinear in distinct variable \emph{groups} (multidegrees
+zero or one) throughout with $3^{O(d)}$ overhead. In the output expansion collect uses of a first
+balanced gate (group set of balanced size), descending from the output in a parse tree through
+linear choices and through the larger child at products (fix ties); one is necessarily reached.
+Terms at each such gate factor into its polynomial times a polynomial on complementary
+groups. See e.g. \cite{ValiantProjections,VSBR,Raz13rank} for related cuts and multilinearization.
+
+Place the graph tensor as $C_{D,m}$, one diameter per edge ($D=O(d)$), taking the independent
+terminals out of their vertex groups. For a term, stream all bits in to two hubs (one
+per side). Factor there with a bridge of at most
+\[
+ h=C(d+\log(n+s))
+\]
+bits by the rank bound. With hubs at zero this just matches the direct cost. But the unit
+position vectors of the terminals served by the first hub have a sum of norm at least $\sqrt{\gamma d}$.
+Move that hub in the direction of this sum by $u=b/\sqrt{d}$. Using $\sqrt{1+x}\le 1+x/2$, change
+of cost is at most
+\[
+ -mu\sqrt{\gamma d} + Dmu^2+ hu.
+\]
+With $b>0$ fixed small and $h\le m\sqrt{\gamma d}/2$, this saves a constant times $m$. Paying at most
+$2Dd$ for selection still gives a strict saving if $a$ is small enough. Hence $h$ must be larger.
+This proves Theorem~\ref{thm:separation} in the indicated case.
+
+\section{Stretch theorem and reduction}\label{sec:stretch}
+
+Here is what we have left to prove.
+
+\begin{theorem}[stretch]\label{thm:stretch}
+If a strict shortening exists in the characteristic over consideration
+(which may be zero), then the border cost in Theorem~\ref{thm:separation} exceeds $2^{n^\sigma}$,
+some $\sigma >0$, for all
+sufficiently large $n$.
+\end{theorem}
+
+We use the integral universal parse map for circuits of size $M$, into the space of \emph{all}
+coefficients of homogeneous degree $n$ in the $2n$ variables. Here is one version. Use a
+$\poly(n,M)$ palette of gates per positive degree $\le n$. Each leaf gate is a linear combination
+of variables with new parameters; each higher gate is the sum of all ordered products of two
+gates of smaller degrees adding correctly, each product weighted by a new parameter. Use
+one designated final gate. With large enough palettes this covers the degree-$n$ component
+of every circuit of size $M$: form positive homogeneous components (degree-zero ones are
+scalars), absorbing linear combinations. Let $Y(X)$ be the map, $X=(X_1,\ldots,X_h)$ the
+parameters. Output coordinates have parameter degree $2n-1$ (one choice per node of an
+ordered parse tree, $n$ leaves). Parameter indices can use a regular format, e.g. complete
+tuples padded with unused parameters.
+
+Fix exact shortening data, reducing its constants into a finite field when needed; for
+characteristic zero one presentation over a number field works outside a fixed finite set of
+primes. We take all fixed exponents in resource constructions rational where appropriate.
+For a sufficiently small fixed $\rho >0$ (depends on shortening data), put
+\[
+ \sigma=\rho/2,\qquad M=2^{\lceil n^\sigma\rceil},\qquad r=2^{\lceil n^\rho\rceil},\qquad L=r^2.
+\]
+Write $c$ for the full coefficient vector ($0$ on slots outside the pattern).
+
+\begin{lemma}[replay]\label{thm:replay}
+Work modulo a prime $p$ with $\poly(M)$ bits, with the exact shortening,
+over a finite extension with arithmetic (including field presentations and shortening coefficients)
+of bit complexity $\poly(M)$. Take square matrices $W_\mu$ over the prime field on binary
+indices (called pins), with pin length $\poly(M)$, one matrix per parameter monomial $X^\mu$ of
+degree $\le L$. Entries indexed by monomial and two pins are available by counting modulo
+$p$ with $\poly(M)$ cost per path and $\poly(M)$ bits of advice. Mark any one pin $\ast$. Then, for
+all sufficiently large $n$, there is a row vector of polynomials $F$ over the prime field of degree
+$\le L/(2n)$ in coefficient slots, with
+\[
+ F(c) = e_\ast+ \sum_\mu \bigl([X^\mu] F(Y(X))\bigr) W_\mu,
+\]
+where $e_\ast$ is the row unit vector.
+\end{lemma}
+
+As usual these asymptotic assertions work also on unbounded sets of $n$, with fixed
+polynomial bounds and primes allowed to vary.
+
+\begin{lemma}[boundary evaluation]\label{thm:boundary}
+Suppose $c$ belongs to the degree-$n$ border image (closure
+of the parse map image) in fixed characteristic. Use that prime in positive characteristic; in
+characteristic zero we can take a prime as in Lemma~\ref{thm:replay}, avoiding any fixed finite list. There
+exist matrices as in that lemma, and a nonzero column $\Omega$ over the prime field, such that
+\[
+ \left(\sum_\mu[X^\mu](G(Y(X))) W_\mu\right)\Omega=G(c)\Omega
+\]
+for every prime-field polynomial $G$ in coefficient slots of degree $\le L/(2n)$.
+\end{lemma}
+
+If we had $c=Y(a)$ in a small prime field, we could simply take scalar weights $a^\mu$. Matrix
+weights will let us stay local even at a boundary point reached with high-degree constants
+and large poles.
+
+\begin{proof}[Proof of Theorem~\ref{thm:stretch} from the lemmas]
+If a border circuit exists along an unbounded sequence, apply Lemma~\ref{thm:boundary}, then
+Lemma~\ref{thm:replay} marking a nonzero position of $\Omega$. Multiply the
+replay equation by $\Omega$ and cancel using the boundary equations: $e_\ast \Omega=0$, a contradiction.
+\end{proof}
+
+\section{Evaluation on the boundary: slicing to a curve}\label{sec:slicing}
+
+We prove Lemma~\ref{thm:boundary}, in this and the next section. Measure polynomial and singly exponential
+($2^{\poly(M)}$) in $M$. Write $T_X(Z)=\sum_\nu Y_\nu(X)Z^\nu$ for the parse map output, reindexing $Z$ from
+$1$ to $2n$, and $d=2n-1$; remember that $Y$ has degree $d$ and its coordinate polynomials have
+coefficient $\ell^1$ norms with polynomial bit length, by counting parses.
+
+\subsection{A prime of modest size}
+
+We recall three geometric degree bounds, using the degree of the projective closure in the
+affine case (see \cite[Ch. I, \S7]{Hartshorne} and \cite[Lemma 2 and Proposition 3]{Heintz}). A linear image of an
+irreducible variety has closure of degree at most the degree of the variety. More generally,
+the closure of an image of an open subset of $\mathbb{A}^h$ under a rational map with a common
+denominator and all degrees at most $e\ge 1$ has degree at most $e^h$. Indeed a general linear
+section of complementary dimension meets the image closure in its attained locus in as many
+distinct points as its degree. The pullbacks must have at least one component per such
+point. Bézout bounds this number, including when a pullback intersection has components
+of several dimensions: in a cut of degree at most $e$ the sum of $(\deg V)e^{\dim V}$ over components
+cannot increase. In particular, successive linear sections never increase the total degree.
+
+Finally, if a point is outside an irreducible closed set of degree $D$ and dimension $b$, an
+equation of degree at most $D$ separates them. Indeed, project the projective closure to $\mathbb{P}^{b+1}$
+from a linear center disjoint from its join with the point. The image is a hypersurface (a
+positive-dimensional projective fiber would meet the center), and misses the projected point.
+Its equation pulls back to one as asserted. In codimension one use the hypersurface equation
+itself. These arguments work over any algebraically closed field. For a reducible set one can
+multiply the separating equations of its components.
+
+\begin{lemma}\label{thm:reduction}
+If $c\in\overline{Y(\mathbb{A}^h)}$ over $\overline{\mathbb{Q}}$, there is a prime $p$ of polynomial
+bit length for which
+the same inclusion holds over $\overline{\mathbb{F}}_p$. The fixed tensor identities can be specialized at the same
+prime, with coefficients of bounded extension degree.
+\end{lemma}
+
+\begin{proof}
+In every characteristic the closure has degree at most $D=d^h$. Form the integer
+matrix whose column for a monomial $y^\eta$, $|\eta|\le D$, is the coefficient vector of $Y(X)^\eta$ in
+the $X$-monomials of degree at most $dD$. Let $u=(c^\eta)_{|\eta|\le D}$. By the closure hypothesis $u$
+annihilates the rational kernel and hence is in the rational row span. The number of columns
+can be very large, but the number of rows is only $\binom{h+dD}{h}$
+, a single exponential. Every entry
+has at most singly exponential bit length by submultiplicativity of the coefficient norm.
+Choose a basis of rows and a square nonsingular minor on those rows. Cramer's rule on its
+columns gives a row expression for $u$ with common denominator dividing the determinant.
+The expression holds on all columns because $u$ is in the row span. Hadamard's inequality
+bounds the bit length of the determinant by a single exponential.
+
+The fixed constants lie in a number field and are integral after inverting a fixed integer.
+Outside its prime divisors we may reduce at any prime ideal above $p$, obtaining a residue
+field of degree at most the number-field degree. All tensor identities survive, as do any
+fixed nonvanishings after excluding finitely many more primes. The prime number theorem
+supplies a prime $p$ of polynomial bit length outside these exclusions and coprime to the
+determinant: the logarithm of the product of primes up to $x$ grows linearly in $x$. The
+reduced row expression now shows, even after scalar extension, that every relation of degree
+$\le D$ on the reduced image vanishes at the reduced $c$. The separating-equation bound proves
+the inclusion.
+\end{proof}
+
+Henceforth write $\mathcal{K}=\overline{\mathbb{F}}_p$. In fixed positive characteristic we keep the
+original prime. In
+characteristic zero the chosen $p$ may depend on $n$. In either case let $E_0$ be a finite field
+containing the constants for the fixed identities. Its degree over $\mathbb{F}_p$ is bounded independently
+of $n$.
+
+\subsection{Equations for the branch}
+
+Lehmkuhl and Lickteig for tensors, and Bürgisser for circuits, used the degree of a graph
+to bound the cost of passage to a limit \cite{LehmkuhlLickteig,ApproxFactors}. Guo, Saxena and Sinhababu obtained
+bounded-degree approximations for approximate polynomial satisfiability over arbitrary
+fields \cite[Theorem 4.2]{GSS}. Here the parameter on the curve must also be separable, and each
+defining equation must admit a short evaluator.
+
+\begin{proposition}\label{thm:branch}
+There are a finite extension $E$ of $E_0$, with $\log_2|E|$ polynomial, and $h$
+polynomials $g_i(X,t)\in E[X,t]$ of polynomial degree with the following properties. Their
+common zero set over $\mathcal{K}$ has an irreducible curve component of singly exponential degree,
+dominant over the $t$-line, on which $J=\det(\partial g_i/\partial X_j)$ is generically nonzero. The function
+field of this curve has a place above $t=0$ at which all $Y_\nu$ are regular with residue $c_\nu$. With
+polynomial advice, each $g_i$ can be evaluated in polynomial bit time over $E$ or a specified
+extension of polynomial bit length, given its field representation and the embedding of $E$.
+\end{proposition}
+
+\begin{proof}
+Close the graph of $Y$ in $\mathbb{P}^h \times \mathbb{A}^{\{\nu :|\nu|=n\}}$, using homogeneous
+parameter coordinates
+$(1:X)$. Projection to the output space is closed, so the fiber over $c$ is a nonempty projective
+set. On each of the $h+1$ standard parameter charts the graph closure has degree at most
+$(d+1)^h$. In fact, on its dense affine-parameter part it is parametrized by $(X,Y(X))$ with
+the parameter coordinates expressed as ratios having a common linear denominator. After
+multiplying each output polynomial by this denominator, all numerator degrees are at most
+$d+1$. The fiber in each chart is a linear section, so the total number and sum of degrees of
+its projective components are at most $(h+1)(d+1)^h$, by counting every component in a
+chart that meets it.
+
+We first isolate a point of the fiber, allowing it to lie at parameter infinity. Cut the
+projective fiber by hyperplanes in the parameter coordinates until it is finite. At each
+cut choose a hyperplane containing none of the positive-dimensional components. Every
+top-dimensional component meets it by projectivity, so the final cut retains a point. The
+number of forbidden linear conditions on the hyperplane coefficients is at most the degree
+bound above. Fix one retained geometric point $P$ and choose a standard chart containing it.
+Write $z=(z_1,\ldots,z_h)$ for its coordinates, $y$ for the output coordinates, $G$ for the chart of
+the graph closure, and $\ell_1(z),\ldots,\ell_b(z)$ for the hyperplanes just used in this chart. In $G$, the
+common zeros of the $y_\nu-c_\nu$ and the $\ell_j$ now form a finite nonempty set.
+
+We choose $h$ linear combinations of these equations that still have finitely many common
+zeros and can be evaluated without listing the output coordinates. Put $B=(n+1)^{2n}$ and
+$e(\nu)=\sum_{j=1}^{2n}\nu_j(n+1)^{j-1}$. For a scalar $a$ use the form
+\[
+ D_a(z,y) = \sum_\nu a^{e(\nu)}(y_\nu-c_\nu) + \sum_{j=1}^b a^{B+j}\ell_j(z).
+\]
+All exponents are distinct. On any positive-dimensional component of the current intersection
+some original equation is nonzero at some point. At that point $D_a$ is a nonzero polynomial
+in $a$ of degree at most $B+b$. Choosing $a$ outside its roots for each component cuts their
+dimensions by one. The number of components stays bounded by $\deg G$ under linear sections.
+After $h$ choices we have forms $D_1,\ldots,D_h$, now indexed by the order of selection. Their
+common zero set in $G$ is finite and contains $P$.
+
+We next make the generic fiber separable. The deformation must pass through $P$ when
+$t=0$, even if every output derivative vanishes. We can thus add a linear term multiplied by
+$t$ to each equation. Write $D=(D_1,\ldots,D_h)$ and use the equations
+\begin{equation}\label{eq:deformation}
+ D_i(z,y)+t(z_i-v_i)=0 \qquad(1\le i\le h).
+\end{equation}
+Over $\overline{\mathcal{K}(t)}$ these describe a fiber of the affine linear map
+$\psi_t(z,y)=z+t^{-1}D(z,y)$. Let $U\subset G$
+be the locus of finite parameters. It is an open subset of affine $z$-space, with $y=Y(X(z))$.
+Write $\widetilde{D}(z)=D(z,Y(X(z)))$. The determinant $\det(tI+\partial \widetilde{D}/\partial z)$
+on $U$ is monic in $t$ over
+$\mathcal{K}(G)$. In particular its zero set on $U$ over the generic $t$ has dimension less than $h$. The
+same is true of $G\setminus U$. Their image closures under $\psi_t$ therefore lie in a proper hypersurface
+of singly exponential degree. For the degree estimate, $G\setminus U$ is cut out by the vanishing
+of one chart coordinate (or is empty). On $U$ the $X$ are ratios of affine linear forms with
+a common denominator, so each $D_i(z,Y(X(z)))$ has such a denominator to power $d$ and
+numerator degree at most $d+1$. Clearing the derivatives' denominators in the determinant
+gives a polynomial of degree $O(h(d+1))$ in $z$. Intersect $G$ with this polynomial and apply
+the linear-image and separating-equation bounds above. Choose $v$ outside the resulting
+hypersurface. Every point of the generic fiber then has finite parameters and invertible
+$z$-Jacobian.
+
+The hyperplane coefficients, the scalars defining $D_1,\ldots,D_h$, and the vector $v$ can all
+be chosen in one extension $E$ of $E_0$ of singly exponential cardinality. Indeed, all excluded
+sets were zeros of nonzero polynomials of singly exponential total degree, uniformly in the
+previous choices. A grid of larger side length avoids each such polynomial, including one
+with coefficients in $\overline{\mathcal{K}(t)}$. Finite extensions of $E_0$ with this size bound
+exist since $\log_2|E_0|$ is
+polynomial.
+
+At $(P,0)$, Krull's dimension theorem gives local dimension at least one for the $h$ equations
+in \eqref{eq:deformation} in $G\times \mathbb{A}^1$. The special fiber is finite and the generic
+fiber has dimension at most
+zero by the Jacobian calculation. Thus there is a curve through the point dominant over
+the $t$-line. A point above it on the normalization gives the claimed place: every output
+coordinate $y_\nu$ is regular there and equals $c_\nu$ at the point. The parameter functions $X_j$
+themselves can have poles there.
+
+To obtain equations in the original circuit parameters, let $\delta(X)$ be the chart denominator
+and write $z_i=u_i(X)/\delta(X)$ with $u_i,\delta$ affine linear. Then
+\[
+ g_i(X,t) = \delta(X)D_i\bigl(z,Y(X)\bigr) + t\bigl(u_i(X)-v_i\delta(X)\bigr)
+\]
+is a polynomial since $D_i$ is affine linear in $z,y$. On $U$, multiplication by $\delta$ scales each Jacobian
+row by a unit at a zero, and the change between $z$ and $X$ has invertible Jacobian. The
+affine closure of the resulting curve in $X,t$ is therefore a component with $J\ne 0$ generically.
+Its degree is at most $(d+2)^h$ by Bézout, since each $g_i$ has total degree at most $d+2$. In
+particular $dt$ spans its function-field differentials over $\mathcal{K}$: the $dg_i=0$ express every $dX_j$ as a
+multiple of $dt$, and this space has dimension one since $\mathcal{K}$ is perfect.
+
+Finally, the weighted sum of output coordinates in $D_a$ is evaluated by one evaluation of
+the original homogeneous table,
+\[
+ \sum_\nu a^{e(\nu)}Y_\nu(X) = T_X\bigl(a^{(n+1)^0},\ldots,a^{(n+1)^{2n-1}}\bigr).
+\]
+The single offset $\sum_\nu a^{e(\nu)}c_\nu$ for each chosen $a$ is advice. The circuit for the homogeneous
+table is specified by its slot and degree ranges from our parse map; its weights are the input
+variables $X$. The slice coefficients, $v$, offsets and finite-field arithmetic data together use
+polynomially many advice bits. All exponents in this evaluation have polynomial bit length.
+Repeated squaring and the homogeneous table recursion therefore evaluate the numerator
+polynomial $g_i$ in polynomial bit time, including at inputs where the chart denominator is
+zero. The field $E$ contains the coefficients of the equations and offsets. The point $P$ and
+the chosen branch can be defined over larger fields because the evaluator uses only these
+equations and offsets.
+\end{proof}
+
+\section{Reading a boundary value with residues}\label{sec:residues}
+
+Let $g_1,\ldots,g_h \in E[X_1,\ldots,X_h,t]$ be the equations from Proposition~\ref{thm:branch}, and fix its branch
+over $t=0$. The parameters $X_i$ may have poles there, even though all the outputs $Y(X)$
+are regular with value $c$. A computation path sees only one monomial. Regularity at the
+chosen place can come from cancellation between distinct paths. We assign each weighted
+monomial a matrix with entries given by short counting paths. After summing the matrices,
+one fixed nonzero vector recovers the value of every regular sum whose residue belongs to
+the prime field. Throughout this section, polynomial and single-exponential bounds are in
+the parameter $M$ of Section~\ref{sec:slicing}.
+
+\begin{lemma}[Residue pins]\label{thm:pins}
+Fix a single-exponential degree bound $L$. There are a nonzero
+vector $\Omega\in\mathbb{F}_p^d$ and $d\times d$ matrices $W_{a,\mu}$ over $\mathbb{F}_p$, indexed
+by $a\in E$ and $\mu\in\mathbb{Z}_{\ge 0}^h$ with $|\mu|\le L$,
+with the following property. If $A=\sum_\mu a_\mu X^\mu \in E[X]$ has degree at most $L$, is regular at the
+branch and has value $z\in \mathbb{F}_p$, then
+\begin{equation}\label{eq:eigenvector}
+ \biggl(\sum_\mu W_{a_\mu,\mu}\biggr)\Omega=z\Omega.
+\end{equation}
+In particular this holds for $A=F(Y(X))$ of degree at most $L$, with $F$ over $\mathbb{F}_p$ and $z=F(c)$.
+The matrices depend $\mathbb{F}_p$-linearly on $a$. Their dimension $d$ is single exponential. With one
+polynomial-length advice string for all $a,\mu$ and all index pairs, any specified entry is the sum
+modulo $p$ of the outputs of polynomial-time binary-guess paths returning $0$ or $1$.
+\end{lemma}
+
+Taking $W_\mu=W_{1,\mu}$ gives Lemma~\ref{thm:boundary}.
+
+The proof uses test differentials $\eta$ on the curve. If $A$ has value $z\in \mathbb{F}_p$, then $A^q-z$
+vanishes to order at least $q$ for every $p$-power $q$. Once $q$ exceeds the pole order of $\eta$, the
+differentials $A^q \eta$ and $z\eta$ have equal residues. The Cartier identity $C_q(A^q \eta)=AC_q(\eta)$ moves
+the power from the unknown function to an operation on the given test. We choose finitely
+many tests for which the coefficients of $AC_q(\eta)$ can be read one monomial at a time. This use
+of finite-dimensional actions on differentials is related to the Cartier transitions in Bridy's
+work on automatic sequences \cite{Bridy}.
+
+\subsection{Cartier extraction in the parameter coordinates}
+
+Write $x=(x_1,\ldots,x_h)$ for the coordinate functions on the chosen geometric curve and
+$K=E(t,x)$ for the subfield they generate. The extension $K/E(t)$ is finite: each $x_i$ is
+algebraic over $\overline{\mathbb{F}}_p(t)$ and only finitely many algebraic constants occur in an equation for it.
+Restrict the branch valuation to $K$ and normalize it to have value group $\mathbb{Z}$. Its residue
+field $\kappa$ is finite, since this place lies over $t=0$ in a finite function field extension. The
+functions $Y(x)$ still have residue $c$. For a uniformizer $s\in K$, the completion is $\kappa((s))$, with
+the coefficient field obtained by lifting the roots of $T^{|\kappa|}-T$. Put
+\[
+ J = \det\left(\frac{\partial g_i}{\partial X_j}\right), \qquad \eta_0= \frac{dt}{J(x,t)}.
+\]
+The Jacobian is nonzero at the generic point. Differentiating $g_i(x,t)=0$ therefore expresses
+all $dx_j$ as multiples of $dt$. This also proves $dt\ne 0$ in the completion. Indeed, $s\in E(t,x)$, so
+$ds$ is a multiple of $dt$, while $s$ is the local uniformizer and $ds\ne 0$. This argument allows
+ramification at $t=0$.
+
+Put $Z=(X_1,\ldots,X_h,t)$. For each $q=p^u$ with $u\ge 1$, define the following operator on
+Laurent polynomials:
+\[
+ \Lambda_q\left(\sum_j v_j Z^j\right) = \sum_i v_{qi+(q-1)\mathbf{1}}^{1/q} Z^i.
+\]
+On differentials in $\kappa((s))$, use the one-variable version
+$C_q(\sum_j v_j s^j\,ds)=\sum_i v_{qi+q-1}^{1/q}s^i\,ds$.
+Thus $C_q(D^q \eta)=DC_q(\eta)$ and $\Res(C_q \eta)=(\Res\eta)^{1/q}$, where $\Res$ extracts the coefficient of
+$s^{-1}ds$.
+
+\begin{lemma}\label{thm:cartier}
+For $f\in E[X_1,\ldots,X_h,t,t^{-1}]$ one has
+\begin{equation}\label{eq:cartier}
+ C_q\bigl(f(x,t)\eta_0\bigr) = \Lambda_q\left(f\prod_{i=1}^h g_i^{q-1}\right)(x,t)\,\eta_0.
+\end{equation}
+\end{lemma}
+
+\begin{proof}
+We give the change of coordinates, which recovers the plane-curve formula of Stöhr
+and Voloch when $h=1$ \cite[Theorem 1.1]{StoehrVoloch}. In characteristic $p$, Cartier on top differentials
+commutes with the field embedding used below \cite{Cartier,Katz}. Recall the reason. In coordinates
+$z_1,\ldots,z_b$ forming a $p$-basis, every coefficient expands uniquely in $z^j$, $0\le j_i(q-1)S$. Its elements
+still have polynomial bit length. By orthogonality in the cyclic group $(E')^\times$,
+\[
+ [Z^j]V = N^{-(h+1)} \sum_{z\in((E')^\times)^{h+1}} V(z)z^{-j}.
+\]
+In the stated intervals the only exponent congruent to $j$ coordinatewise modulo $N$ is $j$ itself.
+This is why the formula also reads negative $t$ exponents correctly.
+
+A path guesses one tuple in canonical field encodings, rejecting invalid encodings and
+zero entries. It evaluates the corresponding summand, including the normalizing scalar,
+by Proposition~\ref{thm:branch} and binary powering. Supply the finite field presentations, embeddings,
+and basis data as polynomial advice. Multiply by $a$ and apply the requested prime-field
+coordinate projection of $E$, extended linearly to $E'$. Both operations take polynomial time
+and commute with summing the paths. To realize its resulting prime-field element, guess
+a binary integer in $[0,2^{\lceil \log_2 p\rceil})$ and return one precisely if the guess is smaller than its
+representative in $[0,p-1]$. Padding to a power-of-two dimension adds zero coordinates to $\Omega$
+and zero rows and columns to the matrices. This completes the construction.
+\end{proof}
+
+\section{Architecture of replay}\label{sec:replay}
+
+We turn to Lemma~\ref{thm:replay}. This section describes the two executions that will give the two
+sides of the replay identity. The subsequent sections meet the budget.
+
+\paragraph{The big network.}
+The layout defining the row $F$ will have teams of $r$ processors each (a
+processor has $n$ bit ports and is to have table $c_x$). There are $R$ teams, a very small power of
+$n$. Each processor has literal fields hardwired, and we can plug a pin string in, distributed
+over the first team. We use all processors, with unused ports forced. Every two teams have
+a predetermined bundle of \emph{exterior} links, evenly distributed among processors (ports equal
+at opposite ends). In its live execution the network runs $f_n$ programs, i.e. local counting
+programs with their codes literally in the $x$ fields. Together one team can perform long
+nondeterministic random access computations (RAM), taking the literals, pin fields and
+exterior links as initial data: we spend some \emph{interior} ports within a team on the RAM
+simulation.
+
+Formally, for the coordinate of the row with a given pin, put that pin in the board. $F$ is
+just the contraction with symbolic table (slots indexed by $x$, other coefficient slots ignored) at
+every processor. Regardless of what we will program live, there is also the primed execution:
+\emph{instead} of $c_x$ put the same coordinate of $Y(X)$ at every processor. Now the literals are just
+data specifying slots. This execution gives $F(Y(X))$. Thus for instance the primed network
+sums over interior RAM wires with no demand that they be legal RAM transcripts.
+
+\paragraph{Replay inside the live programs.}
+We will give these programs an indicator branch
+for the $e_\ast$ term and a replay branch. The latter sums over primed pins and assignments
+for the primed execution, using parses and inserting matrix weights according to \emph{total}
+parameters used. These last weights are cheap given histograms. Within a primed team,
+a batch algorithm of cost $\widetilde{O}(rn)$ guesses all its interior wires, parses values and extracts
+coefficients. (Here and in replay we hide fixed polylogs in $rn$; $\rho$ is very small.) It returns
+counts \emph{conditional} on all incident exterior bits. Putting this batch algorithm itself in RAM
+transcript form gives a network to compress---$R$ such networks attached along the primed
+exterior links.
+
+\input{figures/replay}
+
+It is important that we need to process more than the exterior links here. New RAM
+transcript wires in the replay may carry width even larger than all the ports we started
+with! So there will be two scheduling theorems.
+
+\begin{enumerate}
+\item We pack the primed RAM computations together by repeated geometric shortening
+(\S\ref{sec:packing}). This squeezes nearly all of their new wires into little cells (very cheap to
+compute \emph{privately} in the live RAM). Costs to describe a wire bundle \emph{publicly} are only
+polylogarithmic; large widths amortize the overhead. The primed exterior links are
+carried along unharmed; too few and dispersed for bulk shortening, their ends can
+wind up anywhere.
+\item We clear everything still crossing, dominated by these exterior links, by a final squeeze
+(\S\ref{sec:exterior}). Total available physical capacity between teams would look about adequate but
+the capacity between \emph{each pair} must suffice, plus we need breathing room. We assign
+packed cells to live RAMs in a way that lets us save a constant fraction even on this
+unstructured interconnection.
+\end{enumerate}
+
+\subsection{Transcript compilation}
+
+Here is the RAM convention we use and its compiler to bit networks. The idea of sorting to
+check RAM/random access is standard (see e.g. \cite{BCGTV} and references therein). Words, including
+for addresses and times, have $w=O(\log(nr))$ bits with sufficiently large constant; polylog-bit
+quantities can also just use several words. Our fixed programs use a constant number of
+registers. A tick does elementary work on constantly many words (ordinary integer/bit
+operations on bounded words, one memory probe, one binary choice, branching); the initial
+state can include size/index parameters. In live programs only, allow calls to a fixed private
+subroutine on $b\le n^{1/2}$ consecutive memory words read, with its own nondeterminism (can
+reject); cost $b+1$ ticks (call parameters, including $b$, already determined by register state
+before these ticks). It may validate declared outputs in those words; it need make no changes.
+Bound its time by $n^{50}$ multitape steps. We count accepting paths.
+
+Compile onto $t$ buckets ($t$ power of two); initial memory is the disjoint union of $O(B)$
+given bits per bucket (one bit per word, other memory zero). The machine gets $tB$ ticks for
+ordinary programs; halve for those with private calls, using in that case $B\gg n^{1/2}$. Time
+out by rejection. Then:
+
+\begin{itemize}
+\item The contraction with these inputs gives the acceptance count, each path counted
+exactly once.
+\item The compiler uses $\widetilde{O}(B)$ incident internal bits per bucket, in polylog many cable
+descriptions. Cables are between indices related by one-bit flip or predecessor/successor.
+We assume $B\le n$, $t$ polynomial in $nr$.
+\item Layout of compiler cables at any bucket is computable in polylog time. Bucket functions
+are counts of local validators.
+\end{itemize}
+
+Indeed give each bucket $B$ consecutive ticks, passing register state (and halt status propagated
+canonically, time used, etc.) to the successor. If a call will not fit, pass before it; wasted
+ticks thus cannot defeat the halved budget. Guess previous contents at all probes (including
+for the memory reads of a private call), producing records by address and time of previous
+and resulting words. Include initialization records for given bits at time zero (previous word
+zero) and canonical dummies, padding to a fixed common power of two $O(B)$ records per
+bucket. Sort deterministically by address and time (dummies last), with Batcher bitonic
+sort \cite{Batcher}. This uses $O(\log^2(tB))$ parallel layers in which partners differ in one index bit of
+the entire record array; across buckets this gives one full exchange between XOR neighbors.
+At the end, exchange also boundary records with successive buckets; check previous values
+by immediate predecessors at same address (default zero). Thus for any accepting path all
+guesses of probe values are forced. All internal shared bits have canonical values. These
+operations are local checks given incident cable bits; deterministic wiring and unused bits
+do not add multiplicity. We require simple indexing conventions (given sizes and bucket
+ordinal) for assigning initial addresses, as used below. Validators without private calls have
+ample implementations in $n^{15}$ local tape time (even scanning all local data for individual
+references and using school arithmetic); those with calls fit in $n^{80}$. Here we already take $\rho$
+small so polylogs used by fixed routines are, say, $O(n^{.01})$.
+
+\subsection{Choice of scales}
+
+Here and below there is generous polynomial slack except in the total width of exterior
+links. Packing (\S\ref{sec:packing}) gives fixed constants $K_0 \ge 2$ (number of networks combined per epoch),
+$C_\ast \ge 2$ (per-cell growth factor including incidence), independent of resource exponents. Use
+\[
+ T=\lfloor\tau\log n\rfloor,\qquad R=K_0^T,\qquad \xi=\tau/3,\qquad X_0=rn^{1-\xi}.
+\]
+Make $\tau >0$ so small that $R,C_\ast^T,2^T\le n^{10^{-7}}$. Then take $\rho >0$ small. Every fixed polylog
+overhead used in the construction and its estimates may be absorbed in $O(n^{\xi/100})$, taking
+account also of combined overheads; the fixed powers of logs in our algorithms are independent
+of $\rho$. We can supply all size parameters; no real arithmetic is intended. Use floors or ceilings
+as needed.
+
+Each processor has fields of $\lfloor n^{.2}\rfloor$ literal and that many pin bits. Pin inputs fit distributed
+over team one (pin length $\poly(M)\ll r$); pad all fields. For each other team use $\lfloor n^{1-\xi}/R\rfloor$
+exterior links per processor, physically between equal processor numbers; their total incident
+at a team is at most $X_0$. Team RAMs use the compiler with $t=r$, $B=\lfloor n^{1-\xi/2}\rfloor$, private
+calls allowed, initializing these three kinds of fields as input bits, memory order by processor.
+All fields and compiler cable ends together fit the $n$ ports per processor. Literal header
+includes validator program, parameters and processor name. There is no need for a program
+to compute its own code: these same literal bits are also inputs. Large advice, including
+entry algorithms, can likewise be distributed. All validators themselves use fixed code (with
+universal interpretation within the RAM program as needed, timed in ticks, e.g. to use the
+entry algorithms).
+
+\paragraph{Batch algorithm for primed teams.}
+Fix all primed literal, pin and exterior bits for one
+primed team. Given also a parameter exponent vector for that team (total degree $r(2n-1)$),
+count its coefficient in the primed execution of the team. There is a $\widetilde{O}(rn)$ ordinary RAM
+for this. Guess all interior links, use the resulting processor inputs $x$ (padded as in defining
+$F$) to specify the $r$ requested slots of the degree-$n$ output, and guess one ordered parse per
+slot. Validate that leaves match the specified $Z$-monomial, and aggregate parameter uses,
+checking the given histogram. Indeed palettes and parameter names have size polynomial
+in $M$ (number of possible names), and we can aggregate by random access to counters;
+initialization and final histogram check outside the parse loop are cheap. One parse costs
+$\widetilde{O}(n)$, using regularly numbered gates and parameters, stack traversal and bit array checks.
+Also the per-processor layout of live interior links can be interpreted within this time, using
+the regular compiler layouts (even the $R$ exterior fields have simple address arithmetic).
+Therefore the full primed contraction with fixed pin has its coefficients given by contracting
+such batch networks along the primed exterior links and adding exponents across teams.
+
+Compile this RAM with $B=\lfloor n^{.2}\rfloor$ and $t=\widetilde{O}(rn^{.8})$, same at all teams
+and with sufficient
+ticks. Group initial-memory inputs in lists: exterior list for each other team, ordered
+by processor number then bit number (shared at both teams), literal and pin fields, and
+exponent inputs. Chunk each list separately into blocks of at most $B$ bits so exterior-list
+cables are attached between corresponding initialization chunks (one bucket per chunk on
+each side). Addressing is regular and all descriptors per bucket including compiler incidence
+fit polylog words. Only compiler cables, \emph{not} exterior lists, are charged during bulk shortening.
+Primed validators are used as little boxes: no need to reveal their local probes or choices in
+a public description. They don't run the live validators; this keeps their private cost very
+small. All these networks are placed next.
+
+\section{A geometry for iterating the saving}\label{sec:packing}
+
+The following lemma implements bulk shortening. It does not depend on the functions in
+the boxes. We detail algorithmic bounds because our diagonal program must itself recreate
+the schedules, inside its tick budget.
+
+\input{figures/window}
+
+\paragraph{Windowed host.}
+Fix shortening of fraction $\nu >0$ in dimension $D$ as above, exact with
+integer selector budget. Put $q=2^D$. Take $q$ cycles of length $\ell$ and sites with height in
+$(\mathbb{Z}/\ell)^q$. Additionally each site has $q$ partial binary lamp strings, one on each cycle: all lamps
+specified except those in a window of radius $a$ at its current height in that cycle. Thus the
+number of sites at radius $a$ is
+\[
+ V_a= \ell^q2^{q(\ell-1-2a)}.
+\]
+All radii used will be $O(\log n)$, with $\ell$ of order $\log r$, much larger. Neighbor steps change
+height by one on one axis and agree on overlapping known lamp bits. Radius zero looks like
+a cyclic butterfly: passing a lamp frees one to switch the bit there (compare cube-connected
+cycles \cite{PVCC}). Increasing radius lets us perform local Euclidean geometry on heights and pay
+for it by a little folding in lamp space.
+
+During an epoch allow rational heights (bounded denominators), windows centered at
+floors; cables of height displacement norm at most one, with labels agreeing on joint domain.
+Cost for a charged bit is the Euclidean displacement norm using short cyclic lifts. Bits
+local at a site are free and remain local. Uncharged cables take no part; one can work with
+external terminals attached.
+
+For a placed network at radius $a$, let $W$ be total charged length, and
+\[
+ Z=\sqrt{V_a}\left(\sum_x z_x^2\right)^{1/2}
+\]
+where $z_x$ counts incidences at actual site $x$ of charged bits of positive length. A public record
+(descriptor) can name a box, a port interval, a cable end, etc., with constantly many indices.
+Also track expanded load at each site: public records with, in addition, incident widths
+(even uncharged), local slot bits and data, and multiplicities of local block factors implicit in
+bundled descriptions (including identity/reblocking operations, but fixed tables or validators
+treated as boxes, counting input widths not private evaluation time).
+
+\begin{lemma}[epoch]\label{thm:epoch}
+There are constants $K_0 \ge 2,\lambda >0,C_\ast \ge 2$ and a constant radius
+increment with the following property. Combine $K_0$ networks at the same radius with integral
+heights and only neighbor steps charged. They can be replaced by a sum at the increased
+radius (allowing this much window room), again integral with neighbor steps. In every
+summand,
+\[
+ W_{\mathrm{out}}+\lambda Z_{\mathrm{out}} \le K_0\left(\tfrac12\max_i(W_i+\lambda Z_i)+O(V_a)\right).
+\]
+Largest per-site public record count (including old boxes and new) and similarly expanded
+load, measured with one added, grow by factors at most $C_\ast$. The summands are indexed by
+successive profiles; given these as reached, public work per summand is near-linear in public
+record count plus $V_a$ (allow fixed polylogs of total sizes, including $V_a$, expanded loads and
+names in use), not linear in expanded widths.
+\end{lemma}
+
+\begin{proof}
+Assume throughout $a\le \ell/4$ with room, as in use. We give a step that combines $K$
+networks, and repeat for a fixed $b$ steps on a $K$-ary tree, $K_0=K^b$. Here $b$ is chosen first;
+in particular all bounded geometric types and grids in the steps can be fixed before $K$ is
+chosen.
+
+\paragraph{Motion.}
+Apply independently to each incoming network a signed permutation of axes and
+uniform shifts of the heights on a fixed rational grid, transporting lamps using the same
+reindexing and reflection and the integer parts of shifts. XOR the lamps by uniform strings
+(one whole pattern per motion). Take permutations also uniform with all signs; this is
+initially a randomized description, to be fixed deterministically. Increase the window radius
+by two so new known lamps indeed come from old ones. A cable retains displacement up
+to signed permutation, and agreement on lamps. Any fixed such motion is bounded-to-one
+since only boundedly many known bits can be lost and heights are carried isometrically.
+
+Bin all charged positive-length segments, oriented in advance, by exact midpoint height,
+lamp label for that midpoint at radius another two larger, and exact displacement vector.
+Either endpoint provides this label, since all requested lamps are known to both. There are
+$O(V_a)$ bins (include all signed variants), since we have only constantly many such rational
+displacement vectors and fixed grids. Indeed start with integral heights, take the shift
+grids containing all previous heights and possible midpoints, and all geometric replacements
+below also use only rational combinations, with denominator bounds fixed at each step. In
+expectation, bin counts (counting width bits) are invariant under signed permutations on
+the vector part \emph{alone}: conditional on displacement, midpoint is uniform on its grid and
+lamps are independently uniform.
+
+\paragraph{Pairing in orthogonal tuples.}
+Index axes by binary strings of length $D$. The $D$ signed
+permutations
+\[
+ A_j e_x= (-1)^{x_1+\cdots+x_{j-1}} e_{x^{(j)}}
+\]
+(where the superscript flips bit $j$) are symmetric involutions anticommuting pairwise. Thus
+$A_j v$ are pairwise orthogonal for each $v$. In each bin, divide width into $D$ equal integer
+pools (leaving remainder alone). For each seed bin $s$, use pool $j$ of bin $A_j s$ (acting just
+on displacement); these requests are disjoint. Take the minimum available width, rounded
+down to a multiple of shortening width $m$, in all these directions. We have crossings: use the
+grouped identity with profiles there, at midpoint, taking as frame the vectors $A_j v/2$ (seed
+displacement $v$), hence scaling by $\| v\| /2$. This saves fraction $\nu$ of length served (decrease
+the fraction if needed). Increase all radii to midpoint label radius plus two, so all new
+sites get labels from the midpoint, matching moved endpoints, and all segments again have
+the required form. Unserved bits stay. As throughout, different objects at the same site
+can retain their own boxes, using free local wires. Profile sums here are exact expansions
+with any other slots left open, so after profiles are specified we may expand anew in ways
+depending on the result.
+
+The per-site growth at each step is bounded (allow factors depending on $K$ here). A
+bin involves only boundedly many nearby possible sites: heights within bounded distance
+on fixed grids, and labels constrained except for boundedly many bits. Conversely only
+boundedly many bins affect a site, for the same reasons. We used also bounded fibers of
+a motion. Pool intervals meet cable descriptions in only linear complexity (order cables
+deterministically); at crossing terminals concatenate all relevant widths before applying the
+grouped gadget. Thus new descriptors are locally linear in input descriptor counts plus
+constant, with profile integers themselves just counts. Expanded load grows likewise relative
+to expanded load (gadget size and work counted here linear as positions, not necessarily as
+tape time).
+
+\paragraph{Cost and concentration.}
+For a step let $y$ be the sum of bin count vectors over incoming
+packs (networks), and $\bar y$ its expectation. With bin invariance, ideal counts would achieve
+full service apart from rounding. Thus unserved length is bounded by
+\[
+ C\left(V_a+\sqrt{V_a}\,\lVert y-\bar y\rVert_2\right),
+\]
+as loss at one seed is bounded by constant plus a constant times the sum of absolute
+deviations at its requested bins; use Cauchy--Schwarz. Here and below $C$ can depend on $b$
+and the fixed geometric construction but not $K$. For one pack, any motion gives bin-vector
+norm $\le CZ_i/\sqrt{V_a}$ (bounded fibers and nearby sites as above). Therefore deterministically
+we can obtain
+\[
+ \sqrt{V_a}\,\lVert y-\bar y\rVert_2 \le C\sqrt{K}\max_i Z_i
+\]
+by not exceeding the expected squared norm of the deviation (independence). Furthermore,
+$\sqrt{V_a}\,\lVert\bar y\rVert_2\le C\sum_i W_i$ by uniformity over positions with lamps and a
+positive minimum length.
+New incidence norm $Z'$ is at most $C\sqrt{V_a}\lVert y\rVert_2$ by bounded geometry again (counting new
+charged bits, even control, per served width). Consequently
+\[
+ \begin{aligned}
+ W'/K &\le(1-\nu)\max_i W_i+ C(K^{-1/2}\max_i Z_i+V_a), \\
+ Z'/K &\le C(\max_i W_i+K^{-1/2}\max_i Z_i).
+ \end{aligned}
+\]
+\paragraph{Fixing motions efficiently.}
+Use conditional expectations, as standard (cf. \cite{Raghavan}). Fix
+one motion at a time, enumerating the permutation, signs and heights (poly in $\ell$); then
+determine its XOR pattern bit by bit. All comparisons of conditional objectives are rational
+with polylog bit size: common denominators can use the numbers of completions/products
+of choices. Here are details to see near-linear work. For given permutation/signs and shifts,
+form the moved count vector with XOR bits yet unfixed taken zero. Its squared norm is
+independent of the remaining XOR pattern (permutation of bins). To form the conditional
+mean vector, average each bin class with displacement, center and all bits unaffected by
+remaining XOR choices fixed; this distributes its sum uniformly in that class. These are
+list operations using sorting/prefix sums over all possible bins and cable descriptors. They
+therefore give the needed means and second moments (square-norm expectations), even
+averaging over permutations and shifts when those are not specified. For different packs use
+independence for inner products. This implements the choices in the bound, with no need
+for any individual bit of a payload cable.
+
+\paragraph{Rounding.}
+After $b$ steps round heights to integers with common offset then floor, routing
+a segment by successive coordinate steps. As before increase window radius by a constant
+(say six); along the short route all specified lamps can be inherited from common knowledge
+of both endpoints. Mean length with uniform offset in the unit cube is now bounded by $\sqrt{q}$
+times previous length, by comparison with $\ell_1$. Fix minimizing offsets (enumerate fixed grids),
+with this bound. Incidence norm and site loads incur at most constant factors by bounded
+geometry. Choose $b$ so $\sqrt{q}(1-\nu)^b<1/8$. Iterate the two inequalities above (equivalently
+normalize by number of starting packs under each subtree). After rounding and dividing by
+$K^b$, length is bounded by
+\[
+ \tfrac18\max_i W_i+ O(K^{-1/2})(\max_i W_i+\max_i Z_i) + O(V_a);
+\]
+incidence norm similarly but with $O(1)$ instead of $1/8$. Thus choosing $\lambda$ small, then $K$ large,
+proves the lemma; public work and descriptors have the claimed bounds by the lists and
+bounded local operations.
+\end{proof}
+
+\paragraph{Application to batch networks.}
+Take minimal $\ell$ with $2^{q(\ell-1)}\ge t$ for the primed batch
+RAMs. At radius zero place buckets by Gray coding their binary numbers (binary-reflected:
+XOR number with its right shift), padding into the lamps at height vector zero. Thus
+successors differ in one bit, XOR neighbors in at most two. Route all charged cables by
+paths changing single bits: take the height on the appropriate cycle around to the lamp
+position, then back with that bit changed (treat other passing bits as unchanged, specifying
+the originally omitted height-zero bits by zero as needed). Insert identity operations. This
+costs polylog factors and causes at most polylog local growth within one team. Indeed at
+any intermediate site only polylog original buckets are possible (only constantly many bits
+changed or unspecified), routes have polylog length and each bucket polylog descriptors.
+
+Thus for one input pack, descriptors per site number $\widetilde{O}(1)$ and expanded load is
+$\widetilde{O}(n^{.2})$.
+Also
+\[
+ V_0=\widetilde{O}(rn^{.8}),\qquad W+\lambda Z=\widetilde{O}(rn).
+\]
+Iterate Lemma~\ref{thm:epoch} through $T$ epochs combining all $R$ packs, tracking profiles. This requires
+radius $O(T)\ll \ell$. After normalizing output per original team we have on every summand
+\[
+ O(2^{-T})\,\widetilde{O}(rn)+O(V_0)=o(X_0)
+\]
+as a bound on charged length. At this point call the sites cells. Between cells, total width of
+shared bits, including primed exterior, is at most
+\begin{equation}\label{eq:intercell}
+ RX_0/2+o(RX_0).
+\end{equation}
+The small literal and pin fields (and exponent lists) attach separately as fixed inputs once
+supplied by a ledger.
+
+Each cell has $O(n^{.001})$ descriptors and $O(n^{.25})$ expanded load. All public reconstruction,
+starting from team descriptions, and given successive profiles, costs $O(rn^{.82})$ ticks even for a
+single live RAM reproducing everything. Indeed there are at most $O(RT)$ epoch applications
+and the per-site descriptor bound holds throughout; public algorithms use polylog overheads,
+with initial record lists and routes generated by regular indices and colors, lamps and counts
+fitting polylog bits (by colors here we mean indices of fixed shortening entries, \emph{not} their
+field values). Profile sequences fit the same bound in bits; e.g. allocate profile counters in
+deterministic order as the public replacements are made, reading from a tape, rejecting
+malformed or out-of-range profiles and requiring zero padding.
+
+\section{Clearing exterior links}\label{sec:exterior}
+
+Here we adapt the striking square scheme of \cite[\S2]{Anthropic3SAT}---including its two-layout crossing
+step, the $11/12$ saving and grid and balancing ideas---to transcript replay. We need the
+integral form across characteristics (cf. Clifford and sums-of-squares literature \cite{HWY,Hrubes}, and
+the powerful integral construction \cite{Khoruzhii}), tight \emph{pairwise} capacities, uniquely checkable choices,
+and near-linear public reconstruction (cf. also the balancing in \cite{ETHfalse}).
+
+Let $d=R^{16}$ (new notation in this section), $Z_0=d^2$. Give each cell a label in $[d]^2$.
+Do this so that orienting intercell cables by a fixed rule first, each ordered pair of labels
+(including equal) gets width at most
+\[
+ RX_0/(2Z_0^2) + o(RX_0/Z_0^2).
+\]
+Indeed under independent uniform labels this holds in expectation by \eqref{eq:intercell}. Variance for
+any pair of labels is at most $O(RX_0 \cdot n^{.25})$, since only cables meeting a common cell need be
+counted for deviations, and cell loads are bounded. Thus deterministically not exceeding
+expectation of sum of squares of deviations suffices ($r$ dwarfs any polynomial in $n$).
+
+Again choose by conditional expectations. To give explicit public cost bounds: maintain
+the means and variances for pair totals separately, trying each label for the next cell. Mean
+updates use incident cable records; variance is a sum of covariances over meeting pairs of
+cables including self-pairs, so update at pairs including an incident cable and use probabilities
+given by equality and uniform probabilities at at most three vertices. Thus with $O(n^{.001})$
+incident records per cell even $O(Z_0^4 n^{.003})$ such polylog-arithmetic work per cell suffices.
+Parallel cables need not be expanded.
+
+Pad to equal multiple-of-three width on every ordered pair, pinning dummies (if there
+are no wires, allow width zero). Total padded width $P\le RX_0/2+o(RX_0)$. All but $O(P/d)$
+bits run between corners differing in both coordinates. Make packets in each rectangle
+joining its two diagonals (opposite label pairs), taking three consecutive bits on each. Do
+this separately for lexicographically forward and backward wires.
+
+A packet tensor on the four corners has the identity
+\[
+ \mathbf{1}_{x=y}\mathbf{1}_{i=j} = \sum_{z=1}^8 A(x,i,z)B(y,j,z) + \sum_{z=1}^8 C(y,i,z)D'(x,j,z)
+\]
+with integral fixed arrays, where $x,y$ are indices of size eight at one pair of opposite corners
+and $i,j$ at the other pair. Indeed on exterior algebra of four generators take $P_x$ to be the
+eight wedge and contraction operators, $Q_y$ the same with wedge and contraction exchanged.
+Use even-to-even entries $(j,i)$ of $Q_y P_x+P_x Q_y=\delta_{xy}I$, factoring through odd states.
+
+Group labels by one coordinate into $d$ symbols. For each packet there are two symbols
+involved. Between them use one shared selector bit choosing the term. For the term factored
+along this split send three rank bits. For the other term use six (trivial rank bound; one side
+gives both indices to the other). Add the two possibilities for coordinate choice: given term,
+cost with selection is four for one grouping and seven for the other. This is a real saving
+since packing two unaltered diagonals would cost six either way.
+
+Specifically add to a common ledger the histogram of selectors within each rectangle and
+orientation. Use consistent indexing of corners throughout such a class. Choose grouping
+minimizing total cost given histograms (canonical ties; direct wires between symbols for
+nonpacket bits), so total between-symbol widths are at most
+\[
+ (11/12)P+O(P/d).
+\]
+\input{figures/packet}
+
+For a histogram, costs by symbol pair are public; actual selector bits need be available only
+to the two symbols handling the rectangle. On shared strings use selector bits first and
+check histograms to know the rest of the layout, enforcing equality bits and applying factor
+tables within symbols. Even though the grouping can change with histograms, summing
+gives exactly the desired packet contraction: for each choice of all selectors the same term
+tensors are used (rank-cable contraction gives exactly the term for either grouping). Also
+the raw load per symbol in padded wires and incident packet positions is $O(P/d)$ by equal
+padding.
+
+Assign symbols to live teams, again by conditional expectations. For each unordered
+pair of distinct teams the load under independent assignment has expectation at most
+$2((11/12)P+O(P/d))/R^2$ and variance $O(P^2/d)$ (meeting pairs). Also the number of
+symbols assigned to a team has mean $d/R$, variance at most $d$. Control sum of squares of
+deviations for both by normalizing separately by $(P/R^2)^2$ (omit if $P=0$), $(d/R)^2$; resulting
+expectation summed is $o(1)$. Thus simultaneously:
+
+\begin{itemize}
+\item each distinct team pair gets at most $(11/12+o(1))X_0/R$ bits;
+\item each team's padded load to process, including symbols assigned to the same team
+communicating locally, is $O(X_0)$.
+\end{itemize}
+
+All operations on histograms and totals for ordered pairs, rectangles, symbols or team pairs
+can certainly be done in $O(d^{20})$ work times polylogs, besides manipulating lists of all the
+cable descriptions (form intervals by sorting and prefix sums, keeping track of cell endpoints).
+For assignment of symbols only the graph on $d$ symbols with weights by pair is needed, so
+naive conditional computations (covariances and means as before) more than fit.
+
+\section{Assembling the programs}\label{sec:assembly}
+
+Here we finish Lemma~\ref{thm:replay}. We include details since one needs both resource bounds and
+exact counts (in particular no multiplicity for \emph{proofs} that a layout is legal). All scheduling
+routines use fixed formats and deterministic tie breaking.
+
+\paragraph{Common ledger.}
+Given the lemma data, use live processors, literals (including advice)
+and layouts as in \S\ref{sec:replay}. Reserve prefixes on physical exterior bundles between every pair of
+teams, so that live team RAMs have initial copies of the same guessed ledger: check equality
+at each team, giving equality throughout. The ledger includes a branch bit; in the unit
+branch require all other exterior-link bits zero (including unused ledger), and team one tests
+the live pin for equality to $\ast$ (decode $\ast$ from advice there). No private guessing in team
+RAMs for that branch, hence contribution $e_\ast$ exactly.
+
+In replay branch include:
+
+\begin{itemize}
+\item copies of \emph{all} literal fields checked by their owners, primed pin index $I$ (to initialize
+primed pin fields), and proposed exponent vectors at every primed team;
+\item epoch profiles and squeeze histograms in reconstruction order;
+\item later-used color subtotals at each live team: total uses of each fixed table value in its
+own part of the contraction as expanded. These colors are drawn from a fixed finite
+list of table entries of shortening and packet gadgets, tracked by their names. Other
+operations just count (e.g. enforce selectors and routing, or contribute one per local
+accepting path).
+\end{itemize}
+
+Weights, programs for computing matrix entries, and fields and specialization data need
+not be small in $n$; they need only have $\poly(M)$ bits, and are easily carried in literals and
+accessible in reconstructed arrays (in particular give team one all data needed for final scalar
+operations). Live processors hold only their own shares of large literal data.
+
+Use fixed padded ledger room, say $\lceil rn^{.90}\rceil$ bits per physical team pair. This easily
+suffices by the reconstruction bounds and $Rrn^{.2}$ literal volume. All counters of layout sizes,
+table uses, etc., need only polylog bits as all expanded sizes are polynomial in $rn$. Check
+all formats, ranges, sizes and padding, to enforce canonical descriptions. All sizes used
+as capacities and public padding dimensions can themselves be supplied unsurprisingly in
+advice, which is fixed in defining $F$. In particular program headers give compiler parameters,
+clocks and field lengths. Corrupt ledger or nonconforming computation can always just
+reject.
+
+Each team RAM reconstructs public schedules, and checks and accesses ledger data as
+needed, in $O(rn^{.95})$ ticks by the bounds. It learns the symbol grouping, assignment, and
+shared string lengths for squeeze. Pack these shared strings canonically between distinct
+team pairs, using physical link bundles ($r\lfloor n^{1-\xi}/R\rfloor$ bits available per pair before ledger).
+They fit, by the $11/12$ bound. All unused bits are enforced zero.
+
+\paragraph{Inside a team.}
+The team's job in contraction is exactly its assigned symbols, including all
+cells therein. For squeeze it handles only its incident shared strings (guessing each same-team
+shared string once), computing also unshared packet and padded data (dummy pins use zero).
+This is straightforward bit-level contraction: guess local indices once, check all selectors and
+histograms for the involved rectangles, equality/delivery to cell slot arguments, and attach
+the designated packet table entries to the path. Work including grouping individual wire
+bits for cell calls costs $\widetilde{O}(X_0)$ plus public reconstruction: the raw expanded squeeze cost
+per team is $O(X_0)$, we can translate positions through padded intervals by binary search in
+public cable arrays, and use ordinary addressed memory, or sorting, for reordering.
+
+Call the private subroutine on every assigned cell, supplying its public descriptors,
+intercell slot bits, and data fields for its input positions (batch literal, pin and histogram
+inputs for primed RAMs), plus declared cell totals of colors (which it checks). Total of such
+primed RAM initial data fields, not counting primed exterior, over the entire construction is
+$O(Rrn^{.2}+R\poly(M))$, since folding and placing do not duplicate any initial box. Thus call
+overhead and outer RAM work of preparing arguments fits the bounds (assemble by records
+by cell name). Each call fits in $n^{1/2}$ words by per-site estimates; we do not pass the bits
+on cables \emph{inside} a cell. Privately expand and process the local contraction, guessing those
+internal bits, testing local constraints and reblocking and executing local batch-compiler
+bucket validators (one per hosted bucket), so multiplicities are the path counts. This fits
+the private time cap per call: with $O(n^{.25})$ expanded load, even generating explicit arrays of
+local slots and uses with polylog addressing overhead, using repeated scans for lookups and
+selector subsequence indices and school arithmetic for bounded integers, takes, say, $O(n^{10})$,
+besides validator work ($O(n^{15})$ per bucket). There is no arithmetic in a huge finite field here:
+only tally color names. Team RAMs total these counts (also their squeeze packet colors)
+and check their ledger subtotals.
+
+Finally, let $\lambda$ denote the product of all recorded color values. Team one computes
+this weight by powering from subtotals. Fix a prime-field linear projection $\pi$ from the
+specialization field to the prime field with $\pi(1)=1$, part of advice. With $\mu$ the sum of
+proposed team exponents and $H$ the live pin, team one inserts
+\[
+ \pi(\lambda)\,(W_\mu)_{I,H}
+\]
+as path multiplicity modulo $p$. Implement as ordinary nondeterminism by allowing as many
+choices as the representative of $\pi(\lambda)$ (guess a smaller nonnegative integer canonically) and
+running the matrix entry path procedure. All operations on the aggregated values are of
+cost $\poly(M)$, or that times $R$; standard polynomial overhead simulation suffices.
+
+Thus a live team fits in $O(rn^{.95})+\widetilde{O}(X_0)$ ticks (increasing the first exponent a little, say
+to $.96$, if needed), inside its compiler limit. Private, tick and validator limits may always
+be enforced, with rejection on malformed data. They do not exclude any contributing
+computation.
+
+\paragraph{Accounting identity.}
+Hold fixed $I$ and the team exponent proposals. By contraction,
+summing fully expanded terms with color weights gives exactly the corresponding batch
+count: squeeze, then each shortening, can be summed out in reverse order, with all these
+inputs fixed. In this expanded sum a term specifies profiles and histogram choices, internal
+indices, and paths where boxes count. Live counting realizes precisely this enumeration (up to
+the final weight multiplication just described). Indeed any such term meeting the contraction
+checks gives unique additional ledger data such as color subtotals, unique additional physical
+assignments and transcripts by their checks and deterministic layouts; conversely accepting
+paths must correspond (including the private local path choices). Projection $\pi$ commutes
+with summing these weighted terms, and batch counts were prime-field to begin with.
+
+Summing also over the proposals giving total $\mu$, one therefore gets
+\[
+ ([X^\mu]F_I(Y(X)))\,(W_\mu)_{I,H}.
+\]
+The symbolic row has degree $Rr\le L/(2n)$, so all exponents used are in range. Adding over
+$I,\mu$ and including the unit branch proves precisely Lemma~\ref{thm:replay}. This finishes the proof of
+separation.
+
+\paragraph{Low degree application.}
+To indicate the flexibility of the witness, even clique polynomials
+can show such bounds with only polylogarithmic degree. In each fixed characteristic take
+ordinary clique (monomial is product of edge variables) on $N$ vertices, clique size $\lceil \log^A N\rceil$ for
+a sufficiently large constant $A$. This is in $\mathrm{VNP}$, and has border complexity
+$\exp(\Omega((\log N)^{5/4}))$.
+To see this, recall the elementary projection: encode a sum over compatible choices at $k$
+sites (pairwise constraints, unary weights) by one part of vertices per site plus a singleton
+for attaching all unary weights by edges. Force selection of one per part by zero within
+parts; extra singleton parts pad the clique size. Use constants for compatibility. In the
+no-shortening proof apply this directly to the partition polynomial $g$ with $n$ taken a small
+fixed power of $N$ (the same balanced-cut proof bounds $g$ itself). With shortening, take $n$ a
+power of $\log N$ large enough for the stretch theorem to suffice; encode the tableau sum for
+$f_n$. For example, sites represent Boolean values and also satisfying tuples for individual local
+constraints, edges matching constraint arguments to their values; attach variable weights
+at the $x$ sites. This uses only polynomially many sites and vertices in $n$, so fits with $A$
+large. As before projection after homogenization suffices even for degree-component border
+lower bounds. This growing-parameter conclusion is to be distinguished from hardness in
+parameterized models (cf. \cite{be}).
+
+\input{references}
+\end{document}
diff --git a/preprints/VP-and-VNP-are-different-November-23-2026/build/figures/packet.tex b/preprints/VP-and-VNP-are-different-November-23-2026/build/figures/packet.tex
new file mode 100644
index 0000000000..2f6c654134
--- /dev/null
+++ b/preprints/VP-and-VNP-are-different-November-23-2026/build/figures/packet.tex
@@ -0,0 +1,23 @@
+\begin{figure}[htbp]
+\centering
+\begin{tikzpicture}[x=.7cm,y=.7cm]
+ \definecolor{vertical}{RGB}{18,102,99}
+ \definecolor{horizontal}{RGB}{37,56,100}
+ \draw[orange!75!black] (0,0) node[left,text=black] {$x$} --
+ (2,2) node[right,text=black] {$y$};
+ \draw[orange!75!black] (0,2) node[left,text=black] {$i$} --
+ (2,0) node[right,text=black] {$j$};
+ \node at (3.35,1) {$=$};
+ \foreach \x in {4.6,6.6}
+ \fill[vertical] (\x,-.14) rectangle ++(.55,2.28);
+ \draw[vertical] (5.15,1) -- (6.6,1) node[midway,above] {$3$};
+ \node at (8.1,1) {$+$};
+ \foreach \y in {-.27,1.73}
+ \fill[horizontal] (9.1,\y) rectangle ++(2.28,.55);
+ \draw[horizontal] (10.24,.28) -- (10.24,1.73) node[midway,right] {$3$};
+\end{tikzpicture}
+\caption{Two terms for a packet (numbers in bits). For either term one of the two ways of grouping
+costs three, the other at most six, before adding selectors. One grouping will be chosen globally
+using selector histograms.}
+\label{fig:packet}
+\end{figure}
diff --git a/preprints/VP-and-VNP-are-different-November-23-2026/build/figures/replay.tex b/preprints/VP-and-VNP-are-different-November-23-2026/build/figures/replay.tex
new file mode 100644
index 0000000000..aa332937cb
--- /dev/null
+++ b/preprints/VP-and-VNP-are-different-November-23-2026/build/figures/replay.tex
@@ -0,0 +1,29 @@
+\begin{figure}[htbp]
+\centering
+\begin{tikzpicture}[x=1cm,y=1cm,font=\small]
+ \definecolor{live}{RGB}{37,56,100}
+ \definecolor{primed}{RGB}{181,73,30}
+ \foreach \offset in {0,5.1} {
+ \begin{scope}[xshift=\offset cm]
+ \draw[live,fill=live!6] (0,0) rectangle (3.4,2.55);
+ \node[live,above] at (1.7,2.6) {live RAM};
+ \foreach \x in {1.02,2.38}
+ \node[draw=primed,text=primed,fill=white,rounded corners=2pt]
+ at (\x,1.65) {cell};
+ \foreach \x in {0.51,1.32,2.13,2.94}
+ \node[circle,fill=live,text=white,inner sep=2pt] at (\x,.38) {$c$};
+ \draw[primed,fill=primed!7] (.25,-2.38) rectangle (3.15,-1.40);
+ \node at (1.7,-1.89) {batch RAM on $Y$};
+ \end{scope}
+ }
+ \foreach \y in {.30,.38,1.275,1.88,1.96}
+ \draw[live] (3.4,\y) -- (5.1,\y);
+ \node[primed] at (4.25,-.77) {$\uparrow$ shorten together, then squeeze $\uparrow$};
+ \draw[primed] (3.15,-1.99) -- (5.35,-1.99)
+ node[midway,below] {primed links};
+\end{tikzpicture}
+\caption{What gets replayed (two of many teams). A batch RAM sees even the code for the live
+simulation but uses it only as slot addresses, not as code. Pieces from many primed teams can end
+up inside the same cell, and the cells migrate to live teams as determined by a public ledger.}
+\label{fig:replay}
+\end{figure}
diff --git a/preprints/VP-and-VNP-are-different-November-23-2026/build/figures/window.tex b/preprints/VP-and-VNP-are-different-November-23-2026/build/figures/window.tex
new file mode 100644
index 0000000000..0bcc803905
--- /dev/null
+++ b/preprints/VP-and-VNP-are-different-November-23-2026/build/figures/window.tex
@@ -0,0 +1,20 @@
+\begin{figure}[htbp]
+\centering
+\begin{tikzpicture}[x=.57cm,y=1cm,font=\small]
+ \definecolor{lamp}{RGB}{18,102,99}
+ \foreach \y/\first/\last/\name in {1.1/5/7/old,0/4/10/folded} {
+ \draw[lamp] (0,\y) -- (14,\y) node[right=4pt,text=black] {\name};
+ \foreach \x in {0,...,14} {
+ \ifnum\x<\first \fill[lamp] (\x,\y) circle (1.8pt);
+ \else\ifnum\x>\last \fill[lamp] (\x,\y) circle (1.8pt);
+ \else \draw[lamp,fill=white] (\x,\y) circle (1.8pt);
+ \fi\fi
+ }
+ }
+ \draw[->] (6.2,1.02) -- (7.16,.08);
+\end{tikzpicture}
+\caption{One cycle, cut open. White lamps are forgotten. When making a new site at a nearby
+height we can inherit all specified lamps by increasing the radius by a constant. Only boundedly
+many old site labels per height can compete to feed one such label.}
+\label{fig:window}
+\end{figure}
diff --git a/preprints/VP-and-VNP-are-different-November-23-2026/build/references.tex b/preprints/VP-and-VNP-are-different-November-23-2026/build/references.tex
new file mode 100644
index 0000000000..049e4564dd
--- /dev/null
+++ b/preprints/VP-and-VNP-are-different-November-23-2026/build/references.tex
@@ -0,0 +1,340 @@
+\begin{thebibliography}{99}
+\small\raggedright
+\bibitem{AgrawalVinay}
+Manindra Agrawal and V. Vinay. Arithmetic circuits: A chasm at depth four. In \emph{49th Annual
+IEEE Symposium on Foundations of Computer Science}, pages 67--75, 2008.
+
+\bibitem{AKV20}
+Noga Alon, Mrinal Kumar, and Ben Lee Volk. Unbalancing sets and an almost quadratic lower
+bound for syntactically multilinear arithmetic circuits. \emph{Combinatorica}, 40(2):149--178, 2020.
+
+\bibitem{Batcher}
+K. E. Batcher. Sorting networks and their applications. In \emph{Proceedings of the Spring Joint
+Computer Conference}, volume 32 of \emph{AFIPS Conference Proceedings}, pages 307--314, 1968.
+
+\bibitem{BaurStrassen}
+Walter Baur and Volker Strassen. The complexity of partial derivatives. \emph{Theoretical Computer
+Science}, 22(3):317--330, 1983.
+
+\bibitem{BCGTV}
+Eli Ben-Sasson, Alessandro Chiesa, Daniel Genkin, Eran Tromer, and Madars Virza. SNARKs
+for C: Verifying program executions succinctly and in zero knowledge. In \emph{CRYPTO}, pages
+90--108, 2013.
+
+\bibitem{BDS24}
+C. S. Bhargav, Sagnik Dutta, and Nitin Saxena. Improved lower bound, and proof barrier, for
+constant depth algebraic circuits. \emph{ACM Transactions on Computation Theory}, 16(4):23:1--23:22,
+2024.
+
+\bibitem{be}
+Markus Bläser and Christian Engels. Parameterized Valiant's classes. In \emph{14th International
+Symposium on Parameterized and Exact Computation}, volume 148 of \emph{Leibniz International
+Proceedings in Informatics}, pages 3:1--3:14. Schloss Dagstuhl--Leibniz-Zentrum für Informatik,
+2019.
+
+\bibitem{BGS}
+Mark Braverman, Sumegha Garg, and Ariel Schvartzman. Coding in undirected graphs is either
+very helpful or not helpful at all. In \emph{8th Innovations in Theoretical Computer Science Conference
+(ITCS 2017)}, volume 67 of \emph{Leibniz International Proceedings in Informatics}, pages 18:1--18:18,
+2017.
+
+\bibitem{Bridy}
+Andrew Bridy. Automatic sequences and curves over finite fields. \emph{Algebra \& Number Theory},
+11(3):685--712, 2017.
+
+\bibitem{Burgisser}
+Peter Bürgisser. \emph{Completeness and Reduction in Algebraic Complexity Theory}, volume 7 of
+\emph{Algorithms and Computation in Mathematics}. Springer, 2000.
+
+\bibitem{ApproxFactors}
+Peter Bürgisser. The complexity of factors of multivariate polynomials. \emph{Foundations of
+Computational Mathematics}, 4(4):369--396, 2004. Corrected version: arXiv:1812.06828v1.
+
+\bibitem{BC2024}
+Peter Bürgisser. Completeness classes in algebraic complexity theory, 2024. arXiv:2406.06217v1.
+
+\bibitem{BCS}
+Peter Bürgisser, Michael Clausen, and Mohammad Amin Shokrollahi. \emph{Algebraic Complexity
+Theory}, volume 315 of \emph{Grundlehren der mathematischen Wissenschaften}. Springer, 1997.
+
+\bibitem{BIPnooccurrence}
+Peter Bürgisser, Christian Ikenmeyer, and Greta Panova. No occurrence obstructions in geometric
+complexity theory. \emph{Journal of the American Mathematical Society}, 32(1):163--193, 2019.
+
+\bibitem{BLMW}
+Peter Bürgisser, J. M. Landsberg, Laurent Manivel, and Jerzy Weyman. An overview of
+mathematical issues arising in the geometric complexity theory approach to
+$\mathrm{VP}\ne \mathrm{VNP}$. \emph{SIAM
+Journal on Computing}, 40:1179--1209, 2011.
+
+\bibitem{CaiChenLi}
+Jin-Yi Cai, Xi Chen, and Dong Li. Quadratic lower bound for permanent vs. determinant in
+any characteristic. \emph{Computational Complexity}, 19:37--56, 2010.
+
+\bibitem{Cartier}
+Pierre Cartier. Une nouvelle opération sur les formes différentielles. \emph{Comptes rendus de
+l'Académie des sciences de Paris}, 244:426--428, 1957.
+
+\bibitem{CKSS24}
+Prerona Chatterjee, Deepanshu Kush, Shubhangi Saraf, and Amir Shpilka. Lower bounds for
+set-multilinear branching programs. In \emph{39th Computational Complexity Conference}, volume 300
+of \emph{LIPIcs}, pages 20:1--20:20, 2024.
+
+\bibitem{CKW}
+Xi Chen, Neeraj Kayal, and Avi Wigderson. Partial derivatives in arithmetic complexity and
+beyond. \emph{Foundations and Trends in Theoretical Computer Science}, 6(1--2):1--138, 2011.
+
+\bibitem{Anthropic3SAT}
+Claude (Anthropic). A $2^{o(n)}$ Time Algorithm for 3-SAT. Hexagon:2610.00577v1, 2026.
+
+\bibitem{Cook71}
+Stephen A. Cook. The complexity of theorem-proving procedures. In \emph{Proceedings of the Third
+Annual ACM Symposium on Theory of Computing}, pages 151--158. Association for Computing
+Machinery, 1971.
+
+\bibitem{DawarWilsenach}
+Anuj Dawar and Gregory Wilsenach. Symmetric arithmetic circuits. \emph{Theory of Computing},
+21(14):1--32, 2025.
+
+\bibitem{BFLY26}
+Théo Borém Fabris, Nutan Limaye, Srikanth Srinivasan, and Amir Yehudayoff. Multilinear
+algebraic branching programs and the min-partition rank method. In \emph{41st Computational
+Complexity Conference}, volume 383 of \emph{LIPIcs}, pages 22:1--22:20, 2026.
+
+\bibitem{Forbes2024}
+Michael A. Forbes. Low-depth algebraic circuit lower bounds over any field. In \emph{39th
+Computational Complexity Conference (CCC 2024)}, volume 300 of \emph{Leibniz International
+Proceedings in
+Informatics}, pages 31:1--31:16. Schloss Dagstuhl -- Leibniz-Zentrum für Informatik, 2024.
+
+\bibitem{FSV18}
+Michael A. Forbes, Amir Shpilka, and Ben Lee Volk. Succinct hitting sets and barriers to
+proving lower bounds for algebraic circuits. \emph{Theory of Computing}, 14(18):1--45, 2018.
+
+\bibitem{Gro15}
+Joshua A. Grochow. Unifying known lower bounds via geometric complexity theory. \emph{Computational
+Complexity}, 24:393--475, 2015.
+
+\bibitem{GKSS17}
+Joshua A. Grochow, Mrinal Kumar, Michael Saks, and Shubhangi Saraf. Towards an algebraic
+natural proofs barrier via polynomial identity testing. Technical Report TR17-009, Electronic
+Colloquium on Computational Complexity, 2017.
+
+\bibitem{GSS}
+Zeyu Guo, Nitin Saxena, and Amit Sinhababu. Algebraic dependencies and PSPACE algorithms
+in approximative complexity over any field. \emph{Theory of Computing}, 15(16):1--30, 2019.
+
+\bibitem{GKKS14}
+Ankit Gupta, Pritish Kamath, Neeraj Kayal, and Ramprasad Saptharishi. Approaching the
+chasm at depth four. \emph{Journal of the ACM}, 61(6):33:1--33:16, 2014.
+
+\bibitem{Hartshorne}
+Robin Hartshorne. \emph{Algebraic Geometry}, volume 52 of \emph{Graduate Texts in Mathematics}. Springer,
+1977.
+
+\bibitem{Heintz}
+Joos Heintz. Definability and fast quantifier elimination in algebraically closed fields. \emph{Theoretical
+Computer Science}, 24:239--277, 1983.
+
+\bibitem{HLW}
+Shlomo Hoory, Nathan Linial, and Avi Wigderson. Expander graphs and their applications.
+\emph{Bull. Amer. Math. Soc.}, 43:439--561, 2006.
+
+\bibitem{Hrubes}
+Pavel Hrube\v{s}. A subquadratic upper bound on Hurwitz's problem and related noncommutative
+polynomials. \emph{SIAM Journal on Computing}, 55(2):451--467, 2026.
+
+\bibitem{HWY}
+Pavel Hrube\v{s}, Avi Wigderson, and Amir Yehudayoff. Non-commutative circuits and the
+sum-of-squares problem. \emph{Journal of the American Mathematical Society}, 24:871--898, 2011.
+
+\bibitem{Hyafil}
+Laurent Hyafil. On the parallel evaluation of multivariate polynomials. \emph{SIAM Journal on
+Computing}, 8(2):120--123, 1979.
+
+\bibitem{JerrumSnir}
+Mark Jerrum and Marc Snir. Some exact complexity results for straight-line computations over
+semirings. \emph{Journal of the ACM}, 29(3):874--897, 1982.
+
+\bibitem{Katz}
+Nicholas M. Katz. Nilpotent connections and the monodromy theorem: Applications of a result
+of Turrittin. \emph{Publications Mathématiques de l'IHÉS}, 39:175--232, 1970.
+
+\bibitem{Kayal2012}
+Neeraj Kayal. An exponential lower bound for the sum of powers of bounded degree polynomials.
+Technical Report TR12-081, Electronic Colloquium on Computational Complexity, 2012.
+
+\bibitem{KLSS14}
+Neeraj Kayal, Nutan Limaye, Chandan Saha, and Srikanth Srinivasan. An exponential lower
+bound for homogeneous depth four arithmetic formulas. Technical Report TR14-005, Electronic
+Colloquium on Computational Complexity, 2014.
+
+\bibitem{KSS13regular}
+Neeraj Kayal, Chandan Saha, and Ramprasad Saptharishi. A super-polynomial lower bound for
+regular arithmetic formulas. Technical Report TR13-091, Electronic Colloquium on Computational Complexity, 2013.
+
+\bibitem{KSsurvey}
+Neeraj Kayal and Ramprasad Saptharishi. A selection of lower bounds for arithmetic circuits.
+In \emph{Perspectives in Computational Complexity}, pages 77--115. Birkhäuser, 2014.
+
+\bibitem{Khoruzhii}
+Kirill Khoruzhii. Crossing decomposition for subquadratic noncommutative circuits. Lemmata,
+November 2, revised November 4, 2026.
+
+\bibitem{Koiran2012}
+Pascal Koiran. Arithmetic circuits: The chasm at depth four gets wider. \emph{Theoretical Computer
+Science}, 448:56--65, 2012.
+
+\bibitem{KumarSaraf2014}
+Mrinal Kumar and Shubhangi Saraf. On the power of homogeneous depth 4 arithmetic circuits.
+\emph{SIAM Journal on Computing}, 46(1):336--387, 2017.
+
+\bibitem{KumarVolk2026}
+Mrinal Kumar and Ben Lee Volk. A quadratic lower bound on determinantal complexity.
+arXiv:2609.34462v1, 2026.
+
+\bibitem{LandsbergManivelRessayre}
+Joseph M. Landsberg, Laurent Manivel, and Nicolas Ressayre. Hypersurfaces with degenerate
+duals and the geometric complexity theory program. \emph{Commentarii Mathematici Helvetici},
+88(2):469--484, 2013.
+
+\bibitem{LehmkuhlLickteig}
+T. Lehmkuhl and T. Lickteig. On the order of approximation in approximative triadic decompositions
+of tensors. \emph{Theoretical Computer Science}, 66(1):1--14, 1989.
+
+\bibitem{Levin}
+Leonid A. Levin. Universal sequential search problems. \emph{Problems Inform. Transmission},
+9(3):265--266, 1973.
+
+\bibitem{LSTconst}
+Nutan Limaye, Srikanth Srinivasan, and Sébastien Tavenas. Superpolynomial lower bounds
+against low-depth algebraic circuits. \emph{Journal of the ACM}, 72(4):26:1--26:35, 2025.
+
+\bibitem{MahajanVinay}
+Meena Mahajan and V. Vinay. Determinant: combinatorics, algorithms, and complexity. \emph{Chicago
+Journal of Theoretical Computer Science}, 1997(5), 1997.
+
+\bibitem{MarkovShi}
+Igor L. Markov and Yaoyun Shi. Simulating quantum computation by contracting tensor
+networks. \emph{SIAM Journal on Computing}, 38(3):963--981, 2008.
+
+\bibitem{MignonRessayre}
+Thierry Mignon and Nicolas Ressayre. A quadratic bound for the determinant and permanent
+problem. \emph{International Mathematics Research Notices}, 2004(79):4241--4253, 2004.
+
+\bibitem{MulmuleySohoni}
+Ketan D. Mulmuley and Milind Sohoni. Geometric complexity theory I: An approach to the P
+vs. NP and related problems. \emph{SIAM Journal on Computing}, 31(2):496--526, 2001.
+
+\bibitem{MulmuleySohoni2008}
+Ketan D. Mulmuley and Milind Sohoni. Geometric complexity theory II: Towards explicit
+obstructions for embeddings among class varieties. \emph{SIAM Journal on Computing}, 38(3):1175--1206, 2008.
+
+\bibitem{Nisan}
+Noam Nisan. Lower bounds for non-commutative computation. In \emph{Proceedings of the 23rd
+Annual ACM Symposium on Theory of Computing}, pages 410--418, 1991.
+
+\bibitem{NW97pd}
+Noam Nisan and Avi Wigderson. Lower bounds on arithmetic circuits via partial derivatives.
+\emph{Computational Complexity}, 6(3):217--234, 1997.
+
+% The published bibliography skips numbers 57 and 58.
+\setcounter{enumiv}{58}
+\bibitem{CubOAI}
+OpenAI. A cubic lower bound for border determinantal complexity of the permanent. OpenAI
+Math Release preprint, September 24, 2026.
+OAI:A-cubic-lower-bound-for-border-determinantal-complexity-of-the-permanent-September-24-2026.
+
+\bibitem{DEP5OAI}
+OpenAI. Homogeneous depth-five lower bounds for iterated matrix multiplication.
+Preprint, September 25, 2026.
+OAI:Homogeneous-depth-five-lower-bounds-for-iterated-matrix-multiplication-September-25-2026.
+
+\bibitem{TenAdvances}
+OpenAI. Ten Advances in Mathematics and Theoretical Computer Science. Preprint, updated
+August 6, 2026.
+
+\bibitem{ETHfalse}
+OpenAI. The Exponential Time Hypothesis is False. OpenAI Math Release preprint, October
+25, 2026. OAI:The-Exponential-Time-Hypothesis-is-False-October-25-2026.
+
+\bibitem{PVCC}
+Franco P. Preparata and Jean Vuillemin. The cube-connected cycles: a versatile network for
+parallel computation. \emph{Commun. ACM}, 24(5):300--309, 1981.
+
+\bibitem{Raghavan}
+Prabhakar Raghavan. Probabilistic construction of deterministic algorithms: approximating
+packing integer programs. \emph{J. Comput. System Sci.}, 37(2):130--143, 1988.
+
+\bibitem{Raz06}
+Ran Raz. Separation of multilinear circuit and formula size. \emph{Theory of Computing}, 2:121--135,
+2006.
+
+\bibitem{RazMultilinear}
+Ran Raz. Multi-linear formulas for permanent and determinant are of super-polynomial size.
+\emph{Journal of the ACM}, 56(2):8:1--8:17, 2009.
+
+\bibitem{Raz13rank}
+Ran Raz. Tensor-rank and lower bounds for arithmetic formulas. \emph{Journal of the ACM}, 60(6):40:1--40:15, 2013.
+
+\bibitem{RSY08}
+Ran Raz, Amir Shpilka, and Amir Yehudayoff. A lower bound for the size of syntactically
+multilinear arithmetic circuits. \emph{SIAM Journal on Computing}, 38(4):1624--1647, 2008.
+
+\bibitem{Sheshadri287}
+Karthik Sheshadri. Extending OpenAI's cubic lower bound for the permanent to odd characteristic,
+Pfaffian representations, and polynomial entries. ECCC Report TR26-287, 2026.
+
+\bibitem{SheshadriBorder2026}
+Karthik Sheshadri. A near-quadratic lower bound on the border determinantal complexity of
+$\sum_i x_i^n$ via conormal specialization. arXiv:2606.13628v1, 2026.
+
+\bibitem{ShpilkaYehudayoff}
+Amir Shpilka and Amir Yehudayoff. Arithmetic circuits: A survey of recent results and open
+questions. \emph{Foundations and Trends in Theoretical Computer Science}, 5(3--4):207--388, 2010.
+
+\bibitem{StoehrVoloch}
+Karl-Otto Stöhr and José Felipe Voloch. A formula for the Cartier operator on plane algebraic
+curves. \emph{Journal für die reine und angewandte Mathematik}, 377:49--64, 1987.
+
+\bibitem{StrassenBezout}
+Volker Strassen. Die Berechnungskomplexität von elementarsymmetrischen Funktionen und von
+Interpolationskoeffizienten. \emph{Numerische Mathematik}, 20:238--251, 1973.
+
+\bibitem{Tavenas2013}
+Sébastien Tavenas. Improved bounds for reduction to depth 4 and depth 3. \emph{Information and
+Computation}, 240:2--11, 2015.
+
+\bibitem{Uhlig}
+Dietmar Uhlig. Networks computing Boolean functions for multiple input values. In M. S.
+Paterson, editor, \emph{Boolean Function Complexity}, volume 169 of \emph{London Math. Soc. Lecture Note
+Ser.}, pages 165--173. Cambridge University Press, 1992.
+
+\bibitem{Valiant}
+Leslie G. Valiant. Completeness classes in algebra. In \emph{Proceedings of the Eleventh Annual ACM
+Symposium on Theory of Computing}, pages 249--261. ACM, 1979.
+
+\bibitem{Val80}
+Leslie G. Valiant. Negation can be exponentially powerful. \emph{Theoretical Computer Science},
+12:303--314, 1980.
+
+\bibitem{ValiantProjections}
+Leslie G. Valiant. Reducibility by algebraic projections. \emph{L'Enseignement Mathématique}, 28:253--268, 1982.
+
+\bibitem{VSBR}
+Leslie G. Valiant, Sven Skyum, Stuart Berkowitz, and Charles Rackoff. Fast parallel computation
+of polynomials using few processors. \emph{SIAM Journal on Computing}, 12(4):641--644, 1983.
+
+\bibitem{AviICM}
+Avi Wigderson. P, NP and mathematics---a computational complexity perspective. In \emph{Proceedings
+of the ICM 2006 (Madrid)}, volume 1, pages 665--712. EMS, 2007.
+
+\bibitem{Wbatch}
+Richard Ryan Williams. Strong ETH Breaks With Merlin and Arthur: Short Non-Interactive
+Proofs of Batch Evaluation. In \emph{Computational Complexity Conference}, volume 50 of \emph{LIPIcs},
+pages 2:1--2:17, 2016.
+
+\bibitem{Williams13}
+Ryan Williams. Improving exhaustive search implies superpolynomial lower bounds. \emph{SIAM J.
+Comput.}, 42:1218--1244, 2013.
+\end{thebibliography}
diff --git a/preprints/VP-and-VNP-are-different-November-23-2026/paper.pdf b/preprints/VP-and-VNP-are-different-November-23-2026/paper.pdf
new file mode 100644
index 0000000000..2d1db08311
Binary files /dev/null and b/preprints/VP-and-VNP-are-different-November-23-2026/paper.pdf differ